{"text": "//------------------------------------------------------------------------------\n// \\file Functor_tests.cpp\n//------------------------------------------------------------------------------\n#include \"Algebra/Categories/Functor.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <cmath>\n\nusing Categories::Functors::Details::object_map;\nusing std::cos;\nusing std::sin;\nusing std::sqrt;\n\nBOOST_AUTO_TEST_SUITE(Categories)\nBOOST_AUTO_TEST_SUITE(Functors)\nBOOST_AUTO_TEST_SUITE(Functors_tests)\n\nBOOST_AUTO_TEST_SUITE(Details)\n\nBOOST_AUTO_TEST_SUITE(ObjectMap)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(MapAsTemplateParameter)\n{\n  const auto result = object_map<double, double, &sin>(M_PI_4);\n  BOOST_TEST(result == 1.0 / sqrt(2.0));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // ObjectMap\n\nBOOST_AUTO_TEST_SUITE_END() // Details\n\nBOOST_AUTO_TEST_SUITE_END() // Functors_tests\nBOOST_AUTO_TEST_SUITE_END() // Functors\nBOOST_AUTO_TEST_SUITE_END() // Categories", "meta": {"hexsha": "28af44466e0e391f3b35bc1f3d0d2474bd04365b", "size": 1080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Manifolds/Source/UnitTests/Algebra/Categories/Functor_tests.cpp", "max_stars_repo_name": "hhchi13/mathphysics", "max_stars_repo_head_hexsha": "61790697b65a987617ddd0c0404e345ae6072e98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T14:24:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:19:23.000Z", "max_issues_repo_path": "Manifolds/Source/UnitTests/Algebra/Categories/Functor_tests.cpp", "max_issues_repo_name": "hhchi13/mathphysics", "max_issues_repo_head_hexsha": "61790697b65a987617ddd0c0404e345ae6072e98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-09-29T09:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T03:12:29.000Z", "max_forks_repo_path": "Manifolds/Source/UnitTests/Algebra/Categories/Functor_tests.cpp", "max_forks_repo_name": "hhchi13/mathphysics", "max_forks_repo_head_hexsha": "61790697b65a987617ddd0c0404e345ae6072e98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2018-01-21T05:33:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T20:15:13.000Z", "avg_line_length": 30.0, "max_line_length": 80, "alphanum_fraction": 0.5592592593, "num_tokens": 192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6499872764740771}}
{"text": "/**\n * @file tests/activation_functions_test.cpp\n * @author Marcus Edel\n * @author Dhawal Arora\n *\n * Tests for the various activation functions.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>\n#include <mlpack/methods/ann/activation_functions/identity_function.hpp>\n#include <mlpack/methods/ann/activation_functions/softsign_function.hpp>\n#include <mlpack/methods/ann/activation_functions/tanh_function.hpp>\n#include <mlpack/methods/ann/activation_functions/rectifier_function.hpp>\n#include <mlpack/methods/ann/activation_functions/softplus_function.hpp>\n#include <mlpack/methods/ann/activation_functions/swish_function.hpp>\n#include <mlpack/methods/ann/activation_functions/hard_sigmoid_function.hpp>\n#include <mlpack/methods/ann/activation_functions/mish_function.hpp>\n#include <mlpack/methods/ann/activation_functions/lisht_function.hpp>\n#include <mlpack/methods/ann/activation_functions/gelu_function.hpp>\n#include <mlpack/methods/ann/activation_functions/elliot_function.hpp>\n#include <mlpack/methods/ann/activation_functions/elish_function.hpp>\n#include <mlpack/methods/ann/activation_functions/inverse_quadratic_function.hpp>\n#include <mlpack/methods/ann/activation_functions/quadratic_function.hpp>\n#include <mlpack/methods/ann/activation_functions/multi_quadratic_function.hpp>\n#include <mlpack/methods/ann/activation_functions/spline_function.hpp>\n#include <mlpack/methods/ann/activation_functions/poisson1_function.hpp>\n#include <mlpack/methods/ann/activation_functions/gaussian_function.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(ActivationFunctionsTest);\n\n// Generate dataset for activation function tests.\nconst arma::colvec activationData(\"-2 3.2 4.5 -100.2 1 -1 2 0\");\n\n/**\n * Implementation of the activation function test.\n *\n * @param input Input data used for evaluating the activation function.\n * @param target Target data used to evaluate the activation.\n *\n * @tparam ActivationFunction Activation function used for the check.\n */\ntemplate<class ActivationFunction>\nvoid CheckActivationCorrect(const arma::colvec input,\n                            const arma::colvec target)\n{\n  // Test the activation function using a single value as input.\n  for (size_t i = 0; i < target.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(ActivationFunction::Fn(input.at(i)),\n        target.at(i), 1e-3);\n  }\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  ActivationFunction::Fn(input, activations);\n  for (size_t i = 0; i < activations.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the activation function derivative test.\n *\n * @param input Input data used for evaluating the activation function.\n * @param target Target data used to evaluate the activation.\n *\n * @tparam ActivationFunction Activation function used for the check.\n */\ntemplate<class ActivationFunction>\nvoid CheckDerivativeCorrect(const arma::colvec input,\n                            const arma::colvec target)\n{\n  // Test the calculation of the derivatives using a single value as input.\n  for (size_t i = 0; i < target.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(ActivationFunction::Deriv(input.at(i)),\n        target.at(i), 1e-3);\n  }\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives;\n  ActivationFunction::Deriv(input, derivatives);\n  for (size_t i = 0; i < derivatives.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the activation function inverse test.\n *\n * @param input Input data used for evaluating the activation function.\n * @param target Target data used to evaluate the activation.\n *\n * @tparam ActivationFunction Activation function used for the check.\n */\ntemplate<class ActivationFunction>\nvoid CheckInverseCorrect(const arma::colvec input)\n{\n    // Test the calculation of the inverse using a single value as input.\n  for (size_t i = 0; i < input.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(ActivationFunction::Inv(ActivationFunction::Fn(\n        input.at(i))), input.at(i), 1e-3);\n  }\n\n  // Test the calculation of the inverse using the entire vector as input.\n  arma::colvec activations;\n  ActivationFunction::Fn(input, activations);\n  ActivationFunction::Inv(activations, activations);\n\n  for (size_t i = 0; i < input.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), input.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the HardTanH activation function test. The function is\n * implemented as a HardTanH Layer in hard_tanh.hpp\n *\n * @param input Input data used for evaluating the HardTanH activation function.\n * @param target Target data used to evaluate the HardTanH activation.\n */\nvoid CheckHardTanHActivationCorrect(const arma::colvec input,\n                                    const arma::colvec target)\n{\n  HardTanH<> htf;\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  htf.Forward(input, activations);\n  for (size_t i = 0; i < activations.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the HardTanH activation function derivative test. The\n * derivative is implemented as HardTanH Layer in hard_tanh.hpp\n *\n * @param input Input data used for evaluating the HardTanH activation\n * function.\n * @param target Target data used to evaluate the HardTanH activation.\n */\nvoid CheckHardTanHDerivativeCorrect(const arma::colvec input,\n                                    const arma::colvec target)\n{\n  HardTanH<> htf;\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives;\n\n  // This error vector will be set to 1 to get the derivatives.\n  arma::colvec error = arma::ones<arma::colvec>(input.n_elem);\n  htf.Backward(input, error, derivatives);\n\n  for (size_t i = 0; i < derivatives.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the LeakyReLU activation function test. The function is\n * implemented as LeakyReLU layer in the file leaky_relu.hpp\n *\n * @param input Input data used for evaluating the LeakyReLU activation\n * function.\n * @param target Target data used to evaluate the LeakyReLU activation.\n */\nvoid CheckLeakyReLUActivationCorrect(const arma::colvec input,\n                                     const arma::colvec target)\n{\n  LeakyReLU<> lrf;\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  lrf.Forward(input, activations);\n  for (size_t i = 0; i < activations.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the LeakyReLU activation function derivative test.\n * The derivative function is implemented as LeakyReLU layer in the file\n * leaky_relu_layer.hpp\n *\n * @param input Input data used for evaluating the LeakyReLU activation\n * function.\n * @param target Target data used to evaluate the LeakyReLU activation.\n */\nvoid CheckLeakyReLUDerivativeCorrect(const arma::colvec input,\n                                     const arma::colvec target)\n{\n  LeakyReLU<> lrf;\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives;\n\n  // This error vector will be set to 1 to get the derivatives.\n  arma::colvec error = arma::ones<arma::colvec>(input.n_elem);\n  lrf.Backward(input, error, derivatives);\n  for (size_t i = 0; i < derivatives.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the ELU activation function test. The function is\n * implemented as ELU layer in the file elu.hpp\n *\n * @param input Input data used for evaluating the ELU activation function.\n * @param target Target data used to evaluate the ELU activation.\n */\nvoid CheckELUActivationCorrect(const arma::colvec input,\n                               const arma::colvec target)\n{\n  // Initialize ELU object with alpha = 1.0.\n  ELU<> lrf(1.0);\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  lrf.Forward(input, activations);\n  for (size_t i = 0; i < activations.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the ELU activation function derivative test. The function\n * is implemented as ELU layer in the file elu.hpp\n *\n * @param input Input data used for evaluating the ELU activation function.\n * @param target Target data used to evaluate the ELU activation.\n */\nvoid CheckELUDerivativeCorrect(const arma::colvec input,\n                               const arma::colvec target)\n{\n  // Initialize ELU object with alpha = 1.0.\n  ELU<> lrf(1.0);\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives, activations;\n\n  // This error vector will be set to 1 to get the derivatives.\n  arma::colvec error = arma::ones<arma::colvec>(input.n_elem);\n  lrf.Forward(input, activations);\n  lrf.Backward(activations, error, derivatives);\n  for (size_t i = 0; i < derivatives.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the PReLU activation function test. The function\n * is implemented as PReLU layer in the file parametric_relu.hpp.\n *\n * @param input Input data used for evaluating the PReLU activation\n *   function.\n * @param target Target data used to evaluate the PReLU activation.\n */\nvoid CheckPReLUActivationCorrect(const arma::colvec input,\n                                 const arma::colvec target)\n{\n  PReLU<> prelu;\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  prelu.Forward(input, activations);\n  for (size_t i = 0; i < activations.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the PReLU activation function derivative test.\n * The function is implemented as PReLU layer in the file\n * parametric_relu.hpp\n *\n * @param input Input data used for evaluating the PReLU activation\n *   function.\n * @param target Target data used to evaluate the PReLU activation.\n */\nvoid CheckPReLUDerivativeCorrect(const arma::colvec input,\n                                 const arma::colvec target)\n{\n  PReLU<> prelu;\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives;\n\n  // This error vector will be set to 1 to get the derivatives.\n  arma::colvec error = arma::ones<arma::colvec>(input.n_elem);\n  prelu.Backward(input, error, derivatives);\n  for (size_t i = 0; i < derivatives.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the PReLU activation function gradient test.\n * The function is implemented as PReLU layer in the file\n * parametric_relu.hpp\n *\n * @param input Input data used for evaluating the PReLU activation\n *   function.\n * @param target Target data used to evaluate the PReLU gradient.\n */\nvoid CheckPReLUGradientCorrect(const arma::colvec input,\n                               const arma::colvec target)\n{\n  PReLU<> prelu;\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec gradient;\n\n  // This error vector will be set to 1 to get the gradient.\n  arma::colvec error = arma::ones<arma::colvec>(input.n_elem);\n  prelu.Gradient(input, error, gradient);\n  BOOST_REQUIRE_EQUAL(gradient.n_rows, 1);\n  BOOST_REQUIRE_EQUAL(gradient.n_cols, 1);\n  BOOST_REQUIRE_CLOSE(gradient(0), target(0), 1e-3);\n}\n\n/**\n * Implementation of the Hard Shrink activation function test. The function is\n * implemented as Hard Shrink layer in the file hardshrink.hpp\n *\n * @param input Input data used for evaluating the Hard Shrink activation function.\n * @param target Target data used to evaluate the Hard Shrink activation.\n */\nvoid CheckHardShrinkActivationCorrect(const arma::colvec input,\n                                      const arma::colvec target)\n{\n  HardShrink<> hardshrink;\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  hardshrink.Forward(input, activations);\n  for (size_t i = 0; i < activations.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the HardShrink activation function derivative test.\n * The derivative function is implemented as HardShrink layer in the file\n * hardshrink.hpp\n *\n * @param input Input data used for evaluating the HardShrink activation\n * function.\n * @param target Target data used to evaluate the HardShrink activation.\n */\nvoid CheckHardShrinkDerivativeCorrect(const arma::colvec input,\n                                      const arma::colvec target)\n{\n  HardShrink<> hardshrink;\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives;\n\n  // This error vector will be set to 1 to get the derivatives.\n  arma::colvec error = arma::ones<arma::colvec>(input.n_elem);\n  hardshrink.Backward(input, error, derivatives);\n  for (size_t i = 0; i < derivatives.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the Soft Shrink activation function test. The function is\n * implemented as Soft Shrink layer in the file softshrink.hpp.\n *\n * @param input Input data used for evaluating the Soft Shrink activation\n * function.\n * @param target Target data used to evaluate the Soft Shrink activation.\n */\nvoid CheckSoftShrinkActivationCorrect(const arma::colvec input,\n                                      const arma::colvec target)\n{\n  SoftShrink<> softshrink;\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  softshrink.Forward(input, activations);\n  for (size_t i = 0; i < activations.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the Soft Shrink activation function derivative test.\n * The derivative function is implemented as Soft Shrink layer in the file\n * softshrink.hpp\n *\n * @param input Input data used for evaluating the Soft Shrink activation\n * function.\n * @param target Target data used to evaluate the Soft Shrink activation.\n */\nvoid CheckSoftShrinkDerivativeCorrect(const arma::colvec input,\n                                      const arma::colvec target)\n{\n  SoftShrink<> softshrink;\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives;\n\n  // This error vector will be set to 1 to get the derivatives.\n  arma::colvec error = arma::ones<arma::colvec>(input.n_elem);\n  softshrink.Backward(input, error, derivatives);\n  for (size_t i = 0; i < derivatives.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Simple SELU activation test to check whether the mean and variance remain\n * invariant after passing normalized inputs through the function.\n */\nBOOST_AUTO_TEST_CASE(SELUFunctionNormalizedTest)\n{\n  arma::mat input = arma::randn<arma::mat>(1000, 1);\n\n  arma::mat output;\n\n  SELU selu;\n\n  selu.Forward(input, output);\n\n  BOOST_REQUIRE_LE(arma::as_scalar(arma::abs(arma::mean(input) -\n      arma::mean(output))), 0.1);\n\n  BOOST_REQUIRE_LE(arma::as_scalar(arma::abs(arma::var(input) -\n      arma::var(output))), 0.1);\n}\n\n/**\n * Simple SELU activation test to check whether the mean and variance\n * vary significantly after passing unnormalized inputs through the function.\n */\nBOOST_AUTO_TEST_CASE(SELUFunctionUnnormalizedTest)\n{\n  const arma::colvec input(\"5.96402758 0.9966824 0.99975321 1 \\\n                            7.76159416 -0.76159416 0.96402758 8\");\n\n  arma::mat output;\n\n  SELU selu;\n\n  selu.Forward(input, output);\n\n  BOOST_REQUIRE_GE(arma::as_scalar(arma::abs(arma::mean(input) -\n      arma::mean(output))), 0.1);\n\n  BOOST_REQUIRE_GE(arma::as_scalar(arma::abs(arma::var(input) -\n      arma::var(output))), 0.1);\n}\n\n/**\n * Simple SELU derivative test to check whether the derivatives\n * produced by the activation function are correct.\n *\n */\nBOOST_AUTO_TEST_CASE(SELUFunctionDerivativeTest)\n{\n  arma::mat input = arma::ones<arma::mat>(1000, 1);\n\n  arma::mat error = arma::ones<arma::mat>(input.n_elem, 1);\n\n  arma::mat derivatives, activations;\n\n  SELU selu;\n\n  selu.Forward(input, activations);\n  selu.Backward(activations, error, derivatives);\n\n  BOOST_REQUIRE_LE(arma::as_scalar(arma::abs(arma::mean(derivatives) -\n      selu.Lambda())), 10e-4);\n\n  input.fill(-1);\n\n  selu.Forward(input, activations);\n  selu.Backward(activations, error, derivatives);\n\n  BOOST_REQUIRE_LE(arma::as_scalar(arma::abs(arma::mean(derivatives) -\n      selu.Lambda() * selu.Alpha() - arma::mean(activations))), 10e-4);\n}\n\n/**\n * Implementation of the CELU activation function test. The function is\n * implemented as CELU layer in the file celu.hpp.\n *\n * @param input Input data used for evaluating the CELU activation function.\n * @param target Target data used to evaluate the CELU activation.\n */\nvoid CheckCELUActivationCorrect(const arma::colvec input,\n                                const arma::colvec target)\n{\n  // Initialize CELU object with alpha = 1.0.\n  CELU<> lrf(1.0);\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  lrf.Forward(input, activations);\n  for (size_t i = 0; i < activations.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Implementation of the CELU activation function derivative test. The function\n * is implemented as CELU layer in the file celu.hpp.\n *\n * @param input Input data used for evaluating the CELU activation function.\n * @param target Target data used to evaluate the CELU activation.\n */\nvoid CheckCELUDerivativeCorrect(const arma::colvec input,\n                                const arma::colvec target)\n{\n  // Initialize CELU object with alpha = 1.0.\n  CELU<> lrf(1.0);\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives, activations;\n\n  // This error vector will be set to 1 to get the derivatives.\n  arma::colvec error = arma::ones<arma::colvec>(input.n_elem);\n  lrf.Forward(input, activations);\n  lrf.Backward(activations, error, derivatives);\n  for (size_t i = 0; i < derivatives.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Basic test of the tanh function.\n */\nBOOST_AUTO_TEST_CASE(TanhFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-0.96402758 0.9966824 0.99975321 -1 \\\n                                         0.76159416 -0.76159416 0.96402758 0\");\n\n  const arma::colvec desiredDerivatives(\"0.07065082 0.00662419 0.00049352 0 \\\n                                         0.41997434 0.41997434 0.07065082 1\");\n\n  CheckActivationCorrect<TanhFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<TanhFunction>(desiredActivations, desiredDerivatives);\n  CheckInverseCorrect<TanhFunction>(desiredActivations);\n}\n\n/**\n * Basic test of the logistic function.\n */\nBOOST_AUTO_TEST_CASE(LogisticFunctionTest)\n{\n  const arma::colvec desiredActivations(\"1.19202922e-01 9.60834277e-01 \\\n                                         9.89013057e-01 3.04574e-44 \\\n                                         7.31058579e-01 2.68941421e-01 \\\n                                         8.80797078e-01 0.5\");\n\n  const arma::colvec desiredDerivatives(\"0.10499359 0.03763177 0.01086623 \\\n                                         3.04574e-44 0.19661193 0.19661193 \\\n                                         0.10499359 0.25\");\n\n  CheckActivationCorrect<LogisticFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<LogisticFunction>(desiredActivations,\n                                           desiredDerivatives);\n  CheckInverseCorrect<LogisticFunction>(activationData);\n}\n\n/**\n * Basic test of the softsign function.\n */\nBOOST_AUTO_TEST_CASE(SoftsignFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-0.66666667 0.76190476 0.81818182 \\\n                                         -0.99011858 0.5 -0.5 0.66666667 0\");\n\n  const arma::colvec desiredDerivatives(\"0.11111111 0.05668934 0.03305785 \\\n                                         9.7642e-05 0.25 0.25 0.11111111 1\");\n\n  CheckActivationCorrect<SoftsignFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<SoftsignFunction>(desiredActivations,\n                                           desiredDerivatives);\n  CheckInverseCorrect<SoftsignFunction>(desiredActivations);\n}\n\n/**\n * Basic test of the identity function.\n */\nBOOST_AUTO_TEST_CASE(IdentityFunctionTest)\n{\n  const arma::colvec desiredDerivatives = arma::ones<arma::colvec>(\n      activationData.n_elem);\n\n  CheckActivationCorrect<IdentityFunction>(activationData, activationData);\n  CheckDerivativeCorrect<IdentityFunction>(activationData, desiredDerivatives);\n}\n\n/**\n * Basic test of the rectifier function.\n */\nBOOST_AUTO_TEST_CASE(RectifierFunctionTest)\n{\n  const arma::colvec desiredActivations(\"0 3.2 4.5 0 1 0 2 0\");\n\n  const arma::colvec desiredDerivatives(\"0 1 1 0 1 0 1 0\");\n\n  CheckActivationCorrect<RectifierFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<RectifierFunction>(desiredActivations,\n                                            desiredDerivatives);\n}\n\n/**\n * Basic test of the LeakyReLU function.\n */\nBOOST_AUTO_TEST_CASE(LeakyReLUFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-0.06 3.2 4.5 -3.006 \\\n                                         1 -0.03 2 0\");\n\n  const arma::colvec desiredDerivatives(\"0.03 1 1 0.03 \\\n                                         1 0.03 1 1\");\n\n  CheckLeakyReLUActivationCorrect(activationData, desiredActivations);\n  CheckLeakyReLUDerivativeCorrect(desiredActivations, desiredDerivatives);\n}\n\n/**\n * Basic test of the HardTanH function.\n */\nBOOST_AUTO_TEST_CASE(HardTanHFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-1 1 1 -1 \\\n                                         1 -1 1 0\");\n\n  const arma::colvec desiredDerivatives(\"0 0 0 0 \\\n                                         1 1 0 1\");\n\n  CheckHardTanHActivationCorrect(activationData, desiredActivations);\n  CheckHardTanHDerivativeCorrect(activationData, desiredDerivatives);\n}\n\n/**\n * Basic test of the ELU function.\n */\nBOOST_AUTO_TEST_CASE(ELUFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-0.86466471 3.2 4.5 -1.0 \\\n                                         1 -0.63212055 2 0\");\n\n  const arma::colvec desiredDerivatives(\"0.13533529 1 1 0 \\\n                                         1 0.36787945 1 1\");\n\n  CheckELUActivationCorrect(activationData, desiredActivations);\n  CheckELUDerivativeCorrect(activationData, desiredDerivatives);\n}\n\n/**\n * Basic test of the softplus function.\n */\nBOOST_AUTO_TEST_CASE(SoftplusFunctionTest)\n{\n  const arma::colvec activationData(\"-2 3.2 4.5 -100.2 1 -1 2 0 1000 10000\");\n\n  const arma::colvec desiredActivations(\"0.12692801 3.23995333 4.51104774 \\\n                                         0 1.31326168 0.31326168 2.12692801 \\\n                                         0.69314718 1000 10000\");\n\n  const arma::colvec desiredDerivatives(\"0.53168946 0.96231041 0.98913245 \\\n                                         0.5 0.78805844 0.57768119 0.89349302\\\n                                         0.66666666 1 1\");\n\n  CheckActivationCorrect<SoftplusFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<SoftplusFunction>(desiredActivations,\n                                           desiredDerivatives);\n  CheckInverseCorrect<SoftplusFunction>(desiredActivations);\n}\n\n/**\n * Basic test of the PReLU function.\n */\nBOOST_AUTO_TEST_CASE(PReLUFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-0.06 3.2 4.5 -3.006 \\\n                                         1 -0.03 2 0\");\n\n  const arma::colvec desiredDerivatives(\"0.03 1 1 0.03 \\\n                                         1 0.03 1 1\");\n  const arma::colvec desiredGradient(\"-103.2\");\n\n  CheckPReLUActivationCorrect(activationData, desiredActivations);\n  CheckPReLUDerivativeCorrect(desiredActivations, desiredDerivatives);\n  CheckPReLUGradientCorrect(activationData, desiredGradient);\n}\n\n/**\n * Basic test of the CReLU function.\n */\nBOOST_AUTO_TEST_CASE(CReLUFunctionTest)\n{\n  const arma::colvec desiredActivations(\"0 3.2 4.5 0 \\\n                                         1 0 2 0 2 0 0 \\\n                                         100.2 0 1 0 0\");\n\n  const arma::colvec desiredDerivatives(\"0 0 0 0 \\\n                                         0 0 0 0\");\n  CReLU<> crelu;\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  crelu.Forward(activationData, activations);\n  arma::colvec derivatives;\n  // This error vector will be set to 1 to get the derivatives.\n  arma::colvec error = arma::ones<arma::colvec>(desiredActivations.n_elem);\n  crelu.Backward(desiredActivations, error, derivatives);\n  for (size_t i = 0; i < activations.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), desiredActivations.at(i), 1e-3);\n  }\n  for (size_t i = 0; i < derivatives.n_elem; ++i)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), desiredDerivatives.at(i), 1e-3);\n  }\n}\n\n/**\n * Basic test of the swish function.\n */\nBOOST_AUTO_TEST_CASE(SwishFunctionTest)\n{\n  // Hand-calculated values using Python interpreter.\n  const arma::colvec desiredActivations(\"-0.238405 3.07466 4.45055 \\\n                                         -3.05183208657e-42 0.731058 -0.26894 \\\n                                         1.76159 0\");\n\n  const arma::colvec desiredDerivatives(\"0.3819171 1.0856295 1.039218 \\\n                                         0.5 0.83540367 0.3671335 1.073787\\\n                                         0.5\");\n\n  CheckActivationCorrect<SwishFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<SwishFunction>(desiredActivations,\n                                        desiredDerivatives);\n}\n\n/**\n * Basic test of the hard sigmoid function.\n */\nBOOST_AUTO_TEST_CASE(HardSigmoidFunctionTest)\n{\n  // Hand-calculated values using Python interpreter.\n  const arma::colvec desiredActivations(\"0.1 1 1 \\\n                                         0 0.7 0.3 \\\n                                         0.9 0.5\");\n\n  const arma::colvec desiredDerivatives(\"0.2 0.0 0.0 \\\n                                         0.0 0.2 0.2 0.2\\\n                                         0.2\");\n\n  CheckActivationCorrect<HardSigmoidFunction>(activationData,\n                                              desiredActivations);\n  CheckDerivativeCorrect<HardSigmoidFunction>(desiredActivations,\n                                              desiredDerivatives);\n}\n\n/**\n * Basic test of the Mish function.\n */\nBOOST_AUTO_TEST_CASE(MishFunctionTest)\n{\n  // Calculated using tfa.activations.mish().\n  // where tfa is tensorflow_addons.\n  const arma::colvec desiredActivations(\"-0.25250152 3.1901977 \\\n                                         4.498914 -3.05183208e-42 0.86509836 \\\n                                         -0.30340138 1.943959 0\");\n\n  const arma::colvec desiredDerivatives(\"0.4382387  1.0159768849 \\\n                                         1.0019108 0.6 \\\n                                         1.0192586  0.40639898 \\\n                                         1.0725079  0.6\");\n\n  CheckActivationCorrect<MishFunction>(activationData,\n                                       desiredActivations);\n  CheckDerivativeCorrect<MishFunction>(desiredActivations,\n                                       desiredDerivatives);\n}\n\n/**\n * Basic test of the LiSHT function.\n */\nBOOST_AUTO_TEST_CASE(LiSHTFunctionTest)\n{\n  // Calculated using tfa.activations.LiSHT().\n  // where tfa is tensorflow_addons.\n  const arma::colvec desiredActivations(\"1.928055 3.189384 \\\n                                         4.4988894 100.2 0.7615942 \\\n                                         0.7615942 1.9280552 0\");\n\n  const arma::colvec desiredDerivatives(\"1.1150033 1.0181904 \\\n                                         1.001978 1.0 \\\n                                         1.0896928 1.0896928 \\\n                                         1.1150033 0.0\");\n\n  CheckActivationCorrect<LiSHTFunction>(activationData,\n                                        desiredActivations);\n  CheckDerivativeCorrect<LiSHTFunction>(desiredActivations,\n                                        desiredDerivatives);\n}\n\n/**\n * Basic test of the GELU function.\n */\nBOOST_AUTO_TEST_CASE(GELUFunctionTest)\n{\n  // Calculated using torch.nn.gelu().\n  const arma::colvec desiredActivations(\"-0.0454023 3.1981304 \\\n                                         4.5 -0.0 0.84119199 \\\n                                         -0.158808 1.954597694 0.0\");\n\n  const arma::colvec desiredDerivatives(\"0.4637992 1.0065302 \\\n                                         1.0000293 0.5 1.03513446 \\\n                                         0.37435387 1.090984 0.5\");\n\n  CheckActivationCorrect<GELUFunction>(activationData,\n                                       desiredActivations);\n  CheckDerivativeCorrect<GELUFunction>(desiredActivations,\n                                       desiredDerivatives);\n}\n\n/**\n * Basic test of the Hard Shrink function.\n */\nBOOST_AUTO_TEST_CASE(HardShrinkFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-2 3.2 4.5 -100.2 1 -1 2 0\");\n\n  const arma::colvec desiredDerivatives(\"1 1 1 1 1 1 1 0\");\n\n  CheckHardShrinkActivationCorrect(activationData,\n                                   desiredActivations);\n  CheckHardShrinkDerivativeCorrect(desiredActivations,\n                                   desiredDerivatives);\n}\n\n/**\n * Basic test of the Elliot function.\n */\nBOOST_AUTO_TEST_CASE(ElliotFunctionTest)\n{\n  // Calculated using PyTorch tensor.\n  const arma::colvec desiredActivations(\"-0.66666667 0.76190476 0.81818182 \\\n                                         -0.99011858 0.5 -0.5 \\\n                                          0.66666667 0.0 \");\n\n  const arma::colvec desiredDerivatives(\"0.36 0.32213294 0.3025 \\\n                                         0.25248879 0.44444444 \\\n                                         0.44444444 0.36 1.0 \");\n\n  CheckActivationCorrect<ElliotFunction>(activationData,\n                                         desiredActivations);\n  CheckDerivativeCorrect<ElliotFunction>(desiredActivations,\n                                         desiredDerivatives);\n}\n\n/**\n * Basic test of the EliSH function.\n */\nBOOST_AUTO_TEST_CASE(ElishFunctionTest)\n{\n  // Manually-calculated using python-numpy module.\n  const arma::colvec desiredActivations(\"-0.10307056 3.0746696 4.4505587 \\\n                                         -3.0457406e-44 0.731058578 \\\n                                         -0.1700034 1.76159415 0.0 \");\n\n  const arma::colvec desiredDerivatives(\"0.4033889 1.0856292 \\\n                                         1.03921798 0.5 0.83540389 \\\n                                         0.34725726 1.07378804 0.5\");\n\n  CheckActivationCorrect<ElishFunction>(activationData,\n                                        desiredActivations);\n  CheckDerivativeCorrect<ElishFunction>(desiredActivations,\n                                        desiredDerivatives);\n}\n\n/** \n * Basic test of the Soft Shrink function.\n */\nBOOST_AUTO_TEST_CASE(SoftShrinkFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-1.5 2.7 4 -99.7 0.5 -0.5 1.5 0\");\n\n  const arma::colvec desiredDerivatives(\"1 1 1 1 1 1 1 0\");\n\n  CheckSoftShrinkActivationCorrect(activationData,\n                                   desiredActivations);\n  CheckSoftShrinkDerivativeCorrect(desiredActivations,\n                                   desiredDerivatives);\n}\n\n/**\n * Basic test of the CELU activation function.\n */\nBOOST_AUTO_TEST_CASE(CELUFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-0.86466472 3.2 4.5 \\\n                                         -1 1 -0.63212056 2 0\");\n\n  const arma::colvec desiredDerivatives(\"0.42119275 1 1 \\\n                                         0.36787944 1 \\\n                                         0.5314636 1 1\");\n\n  CheckCELUActivationCorrect(activationData, desiredActivations);\n  CheckCELUDerivativeCorrect(desiredActivations, desiredDerivatives);\n}\n\n/**\n * Basic test of the inverse quadratic function.\n */\nBOOST_AUTO_TEST_CASE(InverseQuadraticFunctionTest)\n{\n  // Hand-calculated values.\n  const arma::colvec desiredActivations(\"0.2 0.088968 0.0470588 \\\n                                         9.95913e-05 0.5 0.5 \\\n                                         0.2 1\");\n\n  const arma::colvec desiredDerivatives(\"-0.369822 -0.175152 -0.0937021 \\\n                                         -0.000199183 -0.64 -0.64 -0.369822\\\n                                         -0.5\");\n\n  CheckActivationCorrect<InvQuadFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<InvQuadFunction>(desiredActivations,\n                                          desiredDerivatives);\n}\n\n/**\n * Basic test of the quadratic function.\n */\nBOOST_AUTO_TEST_CASE(QuadraticFunctionTest)\n{\n  // Hand-calculated values.\n  const arma::colvec desiredActivations(\"4 10.24 20.25 \\\n                                         10040 1 1 \\\n                                         4 0\");\n\n  const arma::colvec desiredDerivatives(\"8 20.48 40.50 \\\n                                         20080 2 2 \\\n                                         8 0\");\n\n  CheckActivationCorrect<QuadraticFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<QuadraticFunction>(desiredActivations,\n                                            desiredDerivatives);\n}\n\n/**\n * Basic test of the Spline function.\n */\nBOOST_AUTO_TEST_CASE(SplineFunctionTest)\n{\n  const arma::colvec activationData1(\"2 3.2 4.5 100.2 1 1 2 0\");\n\n  // Hand-calculated values.\n  const arma::colvec desiredActivations(\"4.39445 14.6953 34.5211 \\\n                                         46355.9 0.693147 0.693147 \\\n                                         4.39445 0\");\n\n  const arma::colvec desiredDerivatives(\"18.3923 94.6819 280.03866 \\\n                                         1042462.1078 1.0137702 1.0137702 \\\n                                         18.3923 0\");\n\n  CheckActivationCorrect<SplineFunction>(activationData1, desiredActivations);\n  CheckDerivativeCorrect<SplineFunction>(desiredActivations,\n                                         desiredDerivatives);\n}\n\n/**\n * Basic test of the multi quadratic function.\n */\nBOOST_AUTO_TEST_CASE(MultiquadFunctionTest)\n{\n  // Hand-calculated values.\n  const arma::colvec desiredActivations(\"2.23607 3.35261 4.60977 \\\n                                         100.205 1.41421 1.41421 \\\n                                         2.23607 1\");\n\n  const arma::colvec desiredDerivatives(\"0.912871 0.95828 0.97727 \\\n                                         0.99995 0.816496 0.816496 \\\n                                         0.912871 0.707107\");\n\n  CheckActivationCorrect<MultiQuadFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<MultiQuadFunction>(desiredActivations,\n                                            desiredDerivatives);\n}\n\n\n/**\n * Basic test of the Poisson one function.\n */\nBOOST_AUTO_TEST_CASE(Poisson1FunctionTest)\n{\n  const arma::colvec activationData1(\"-2 3.2 4.5 5 1 -1 2 0\");\n\n  // Hand-calculated values.\n  const arma::colvec desiredActivations(\"-22.1672 0.0896768 0.0388815 \\\n                                         0.0269518 0 -5.43656 \\\n                                         0.135335 -1\");\n\n  const arma::colvec desiredDerivatives(\"1.02404e+11 1.74647 1.88633 \\\n                                         1.92058 2 1707.81 \\\n                                         1.62864 8.15485\");\n\n  CheckActivationCorrect<Poisson1Function>(activationData1, desiredActivations);\n  CheckDerivativeCorrect<Poisson1Function>(desiredActivations,\n                                           desiredDerivatives);\n}\n\n/**\n * Basic test of the Gaussian activation function.\n */\nBOOST_AUTO_TEST_CASE(GaussianFunctionTest)\n{\n  const arma::colvec desiredActivations(\"0.018315639 0.000035713 \\\n                                         1.6052280551856116e-09 \\\n                                         0 0.367879441 0.367879441 \\\n                                         0.018315639 1\");\n\n  const arma::colvec desiredDerivatives(\"-0.036618991635992616 \\\n                                         -0.0000714259999 \\\n                                         -0.0000000032104561 \\\n                                         0 -0.6426287436 \\\n                                         -0.642628743680 \\\n                                         -0.03661899163 \\\n                                         -0.73575888234\");\n\n  CheckActivationCorrect<GaussianFunction>(activationData,\n                                           desiredActivations);\n  CheckDerivativeCorrect<GaussianFunction>(desiredActivations,\n                                           desiredDerivatives);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "4325fb569bd11565c24caa91d976b653f123cd42", "size": 37487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/activation_functions_test.cpp", "max_stars_repo_name": "birm/mlpack", "max_stars_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-29T17:39:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-16T23:36:01.000Z", "max_issues_repo_path": "src/mlpack/tests/activation_functions_test.cpp", "max_issues_repo_name": "birm/mlpack", "max_issues_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/activation_functions_test.cpp", "max_forks_repo_name": "birm/mlpack", "max_forks_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0345794393, "max_line_length": 83, "alphanum_fraction": 0.6435831088, "num_tokens": 9252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.649987270016695}}
{"text": "//####### Test module for the overload of cmath functions ##################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"math/cmath_overload\"\n\n#include <cmath>\n#include <vector>\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#define PXRMP_PREVENT_USE_STD_FOR_MATH\n#include \"cmath_overloads.hpp\"\n\nusing namespace picsar::multi_physics::math;\n\n// ------------- Tests --------------\n\n// ***Test cmath overloads\n\ntemplate<typename RealType>\nvoid test_case_cmath_overloads()\n{\n    const auto vals = std::vector<RealType>{1.0e-30, 1.0e-20, 1.0e-10, 1.0,\n     3.141459, 1.0e10, 1.0e20, 1.0e30};\n\n     for (const auto val : vals){\n        BOOST_CHECK_EQUAL(m_sqrt(val), std::sqrt(val));\n        BOOST_CHECK_EQUAL(m_cbrt(val), std::cbrt(val));\n        BOOST_CHECK_EQUAL(m_exp(val), std::exp(val));\n        BOOST_CHECK_EQUAL(m_exp(-val), std::exp(-val));\n        BOOST_CHECK_EQUAL(m_log(val), std::log(val));\n        BOOST_CHECK_EQUAL(m_tanh(val), std::tanh(val));\n        BOOST_CHECK_EQUAL(m_tanh(-val), std::tanh(-val));\n     }\n\n    const auto vals_floor_fabs = std::vector<RealType>{0.0, 0.001, 0.3, 0.7,\n         1.11, 1.5, 1.55, 20.9, 100.56, 1000.24};\n\n    for (const auto val : vals_floor_fabs){\n        BOOST_CHECK_EQUAL(m_floor(val), std::floor(val));\n        BOOST_CHECK_EQUAL(m_floor(-val), std::floor(-val));\n\n        BOOST_CHECK_EQUAL(m_fabs(val), std::fabs(val));\n        BOOST_CHECK_EQUAL(m_fabs(-val), std::fabs(-val));\n    }\n}\n\nBOOST_AUTO_TEST_CASE( picsar_cmath_overloads )\n{\n    test_case_cmath_overloads<double>();\n    test_case_cmath_overloads<float>();\n}\n\n// *******************************\n", "meta": {"hexsha": "3e7359eb8cc62c333a02f3bca8eac707c4b9e02c", "size": 1733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_picsar_cmath_overload.cpp", "max_stars_repo_name": "LDAmorim/picsar", "max_stars_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multi_physics/QED_tests/test_picsar_cmath_overload.cpp", "max_issues_repo_name": "LDAmorim/picsar", "max_issues_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multi_physics/QED_tests/test_picsar_cmath_overload.cpp", "max_forks_repo_name": "LDAmorim/picsar", "max_forks_repo_head_hexsha": "024db7c01daf820ae321c3473f2dd5ec73476946", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4035087719, "max_line_length": 76, "alphanum_fraction": 0.6474321985, "num_tokens": 480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.649987267950505}}
{"text": "//\n// Created by Vlad Argunov on 03/01/2022.\n//\n\n#include \"Simulation.h\"\n\n#include <Eigen/Dense>\n#include <random>\n#include <cmath>\n#include <tuple>\n\nEigen::VectorXd Simulation::generate_uniform_variable(int n) {\n        std::random_device rd;\n        std::mt19937 gen(rd());\n        Eigen::VectorXd uniform_numbers;\n        uniform_numbers.resize(n);\n        std::uniform_real_distribution<double> uniform(0.0, 1.0);\n        for (int i = 0; i < n; ++i) {\n            uniform_numbers(i) = uniform(gen);\n        }\n        return uniform_numbers;\n}\n\nEigen::VectorXd Simulation::generate_normal_variable(int n, double mu, double sigma) {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    Eigen::VectorXd normal_numbers;\n    normal_numbers.resize(n);\n    std::normal_distribution<> normal{mu,sigma};\n    for (int i = 0; i < n; ++i) {\n        normal_numbers(i) = normal(gen);\n    }\n    return normal_numbers;\n}\n\nEigen::MatrixXd Simulation::generate_gbm(int n_processes, double tn, double stock_price, double mu, double sigma, int n_steps) {\n//    Generates the matrix of Geometric brownian motions for each row and a time step for each column\n    double time_step = tn / n_steps;\n    Eigen::MatrixXd simulated_processes;\n    Eigen::Index n_rows = n_processes;\n    Eigen::Index n_cols = n_steps + 1;\n    simulated_processes.resize(n_rows, n_cols);\n    simulated_processes.leftCols(1) = Eigen::MatrixXd::Constant(n_rows, 1, stock_price);\n\n    Eigen::VectorXd normal_rv;\n    normal_rv.resize(n_processes);\n    for (int col = 0; col < n_cols - 1; ++col) {\n        normal_rv = generate_normal_variable(n_processes, 0, 1);\n        for (int row = 0; row < n_rows; ++row) {\n            simulated_processes(row, col + 1) = simulated_processes(row, col)\n                    * exp(mu - 0.5 * sigma * sigma * time_step + sigma * sqrt(time_step) * normal_rv(row) );\n        }\n\n    }\n\n    return simulated_processes;\n}\n\nstd::tuple<Eigen::MatrixXd , Eigen::MatrixXd>\nSimulation::generate_heston_process(int n_processes, double tn, double stock_price, double mu, double variance,\n                                    double kappa, double theta, double sigma, double rho, int n_steps) {\n    //    Generates the matrix of Heston processes for each row and a time step for each column\n    // Here variance is the starting value_matrix of the volatility, theta is the long-term level,\n    // kappa is the speed of convergence, and sigma is the volatility of volatility\n    double time_step = tn / n_steps;\n    Eigen::MatrixXd simulated_stock_processes, simulated_var_process;\n    Eigen::Index n_rows = n_processes;\n    Eigen::Index n_cols = n_steps + 1;\n\n    simulated_stock_processes.resize(n_rows, n_cols);\n    simulated_var_process.resize(n_rows, n_cols);\n\n    simulated_stock_processes.leftCols(1) = Eigen::MatrixXd::Constant(n_rows, 1, stock_price);\n    simulated_var_process.leftCols(1) = Eigen::MatrixXd::Constant(n_rows, 1, variance);\n\n    Eigen::VectorXd normal_rv1, normal_rv2;\n    normal_rv1.resize(n_processes);\n    normal_rv2.resize(n_processes);\n    for (int col = 0; col < n_cols - 1; ++col) {\n        normal_rv1 = generate_normal_variable(n_processes, 0, 1);\n        for (int row = 0; row < n_rows; ++row) {\n            simulated_var_process(row, col + 1) = simulated_var_process(row, col) +\n                                                  kappa * (theta - simulated_var_process(row, col)) * time_step\n                                                  + sigma * sqrt(simulated_var_process(row, col) * time_step)\n                                                  * (rho * normal_rv1(row) + sqrt(1 - rho * rho) * normal_rv2(row));\n\n\n            simulated_stock_processes(row, col + 1) = simulated_stock_processes(row, col) * (1 + mu * time_step)\n                    + simulated_stock_processes(row, col) * sqrt(simulated_var_process(row, col) * time_step) * normal_rv1(row);\n        }\n\n    }\n    return {simulated_stock_processes, simulated_var_process};\n}\n", "meta": {"hexsha": "ed8277dfdfd6d2871ce4b189f3d83cda411f7b0f", "size": 3956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Simulation.cpp", "max_stars_repo_name": "vladargunov/QuantKit", "max_stars_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Simulation.cpp", "max_issues_repo_name": "vladargunov/QuantKit", "max_issues_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Simulation.cpp", "max_forks_repo_name": "vladargunov/QuantKit", "max_forks_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6421052632, "max_line_length": 128, "alphanum_fraction": 0.6481294237, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6499654381892955}}
{"text": "#include <iostream>\n\n#include <Eigen/Dense>\n\n#include \"LSLOpt/BFGS.hpp\"\n\n\nstruct Parabola {\n    double value(const Eigen::VectorXd& x)\n    {\n      return x.dot(x);\n    }\n\n    Eigen::VectorXd gradient(const Eigen::VectorXd& x)\n    {\n      return 2 * x;\n    }\n\n    double initial_step_length(const Eigen::VectorXd& x, const Eigen::VectorXd& p)\n    {\n      double max_change = p.array().abs().maxCoeff();\n\n      return 0.2 / max_change;\n    }\n\n    double change_acceptable(const Eigen::VectorXd& x, const Eigen::VectorXd& xp) {\n      return (xp - x).array().abs().maxCoeff() - (0.2 + 1e-6);\n    }\n};\n\n\nint main()\n{\n  Parabola parabola;\n  Eigen::VectorXd x0 = Eigen::VectorXd::Constant(2, 1.0);\n  LSLOpt::OptimizationParameters<double> params\n      = LSLOpt::getOptimizationParameters<double>();\n  LSLOpt::OstreamOutput output{LSLOpt::OutputLevel::Status, std::cerr};\n\n  auto result = LSLOpt::lsl_bfgs(parabola, x0, params, output);\n\n  std::cout << \"STATUS \" << result.status << std::endl;\n  std::cout << \"F      \" << result.function_value << std::endl;\n  std::cout << \"X      \" << result.x << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "f1fd6996b2be61b08c6cac9d8e1cd05651698ec8", "size": 1116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Examples/Example.cpp", "max_stars_repo_name": "flachsenberg/LSLOpt", "max_stars_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T02:42:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T14:09:06.000Z", "max_issues_repo_path": "src/Examples/Example.cpp", "max_issues_repo_name": "flachsenberg/LSLOpt", "max_issues_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Examples/Example.cpp", "max_forks_repo_name": "flachsenberg/LSLOpt", "max_forks_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-08T12:12:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T12:12:51.000Z", "avg_line_length": 23.25, "max_line_length": 83, "alphanum_fraction": 0.6245519713, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6499512644425554}}
{"text": "#include \"NMatrixOperations.h\"\n\n#include <Eigen/Dense>\n#include <stdexcept>\n#include <assert.h>\n#include <string.h>\n#include <vector>\n#include <QDebug>\n\n#define print(something) {std::stringstream ss; ss << something; qDebug() << ss.str().c_str(); }\n\n// This was based on https://ef.gy/linear-algebra:normal-vectors-in-higher-dimensional-spaces\nEigen::VectorXd getNormalVector(Eigen::MatrixXd vectors) {\n\tassert(vectors.rows() == vectors.cols() + 1);\n\tconst unsigned int N = vectors.rows();\n\n\tEigen::MatrixXd pM = vectors.transpose();\n\tpM.conservativeResize(pM.rows() + 1, Eigen::NoChange);\n\tpM.row(N - 1) = Eigen::VectorXd::Zero(N);\n\tEigen::MatrixXd baseVectors = Eigen::MatrixXd::Identity(N, N);\n\n\tEigen::VectorXd result = Eigen::VectorXd::Zero(N);\n\n\tint signal = 1;\n\tfor (unsigned int i = 0; i < N; i++) {\n\t\tEigen::MatrixXd pS(N - 1, N - 1);\n\n\t\tfor (unsigned int j = 0; j < (N - 1); j++) {\n\t\t\tpS.block(j, 0, 1, i) = pM.block(j, 0, 1, i);\n\t\t\tpS.block(j, i, 1, N - i - 1) = pM.block(j, i + 1, 1, N - i - 1);\n\t\t}\n\t\t\n\t\tresult += signal * baseVectors.row(i) * pS.determinant();\n\t\tsignal *= -1;\n\t}\n\n\treturn result;\n}\n\nEigen::MatrixXd translateMatrixN(int N, Eigen::VectorXd point) {\n\tassert(N > 0);\n\n\tEigen::MatrixXd m = Eigen::MatrixXd::Identity(N + 1, N + 1);\n\tm.topRightCorner(N, 1) = point;\n\treturn m;\n}\n\n// This was based on https://ef.gy/linear-algebra:perspective-projections\n// However, he makes this in a different way than every other LookAt I could find\n// Therefor it has been silightly adjusted to conform to the others\nEigen::MatrixXd lookAtMatrixN(const int N, Eigen::VectorXd from, Eigen::VectorXd to, Eigen::MatrixXd ups) {\n\tassert(N > 2);\n\n\t//print(\"LookAt Double Calculation:\");\n\t//print(\"FROM:\");\n\t//print(from.transpose());\n\t//print(\"TO:\");\n\t//print(to.transpose());\n\t//print(\"UPS\");\n\t//print(ups);\n\n\tEigen::MatrixXd m(N, N);\n\n\tm.rightCols(1) = (to - from).normalized();\n\n\tint numLoops = 0;\n\tfor (int currentColumn = N - 2; currentColumn > 0; currentColumn--) {\n\t\tEigen::MatrixXd vectorsToCross(N, N - 1);\n\t\tint currentColumnOnVectorsToCross = 1;\n\n\t\t//First, cross product all ups, in order\n\t\tvectorsToCross.col(0) = ups.col(numLoops);\n\t\tfor (int i = 1; i < currentColumn; i++) {\n\t\t\tvectorsToCross.col(currentColumnOnVectorsToCross) = ups.col(numLoops + i);\n\t\t\tcurrentColumnOnVectorsToCross++;\n\t\t}\n\n\t\tnumLoops++;\n\t\tfor (int i = 0; i < numLoops; i++) {\n\t\t\tvectorsToCross.col(currentColumnOnVectorsToCross) = m.col(currentColumn + i + 1);\n\t\t\tcurrentColumnOnVectorsToCross++;\n\t\t}\n\n\t\t//print(\"vectorsToCross\\n\" << vectorsToCross << \"\\n\");\n\n\t\tauto normal = getNormalVector(vectorsToCross);\n\t\t//print(\"Normal:\\n\" << normal << \"\\n\");\n\t\t//print(\"Normal Normalized:\\n\" << normal.normalized() << \"\\n\");\n\n\t\tm.col(currentColumn) = normal.normalized();\n\n\t\t//print(\"Current Matrix:\\n\" << m << \"\\n\");\n\t}\n\n\tm.col(0) = getNormalVector(m.rightCols(N - 1)).normalized();\n\n\t//print(\"m\");\n\t//print(m);\n\n\tEigen::MatrixXd temp = Eigen::MatrixXd::Identity(N + 1, N + 1);\n\t//m.leftCols(N - 1).rowwise().reverseInPlace();\n\ttemp.topLeftCorner(N, N) = m;\n\n\treturn temp.transpose();\n}\n\nEigen::MatrixXd perspectiveMatrixN(const int N, double eye_radians_angle, double nearPlane, double farPlane, double aspectRatio) {\n\tassert(N > 2);\n\n\tif (N == 3) {\n\t\tEigen::MatrixXd m = Eigen::MatrixXd::Zero(N + 1, N + 1);\n\n\t\tdouble f_tan = 1 / tan(eye_radians_angle / 2);\n\t\tm(0, 0) = f_tan / aspectRatio;\n\t\tm(1, 1) = f_tan;\n\t\tm(2, 2) = (nearPlane + farPlane) / (nearPlane - farPlane);\n\t\tm(2, 3) = -1.f;\n\t\tm(3, 2) = 2 * (nearPlane*farPlane) / (nearPlane - farPlane);\n\n\t\treturn m.transpose();\n\t}\n\telse {\n\t\tEigen::MatrixXd m = Eigen::MatrixXd::Identity(N + 1, N + 1);\n\n\t\tdouble f_tan = 1 / tan(eye_radians_angle / 2);\n\t\tm = m*f_tan;\n\t\tm(N - 1, N - 1) = 1;\n\t\tm(N, N) = 1;\n\n\t\treturn m;\n\t}\n}\n\n// N > 3\nEigen::MatrixXd viewMatrixN(\n\tconst int N,\n\tEigen::VectorXd from,\n\tEigen::VectorXd to,\n\tEigen::MatrixXd ups,\n\tdouble eyeRadiansAngle,\n\tdouble nearPlane,\n\tdouble farPlane,\n\tdouble aspectRatio) {\n\n\tauto tr = translateMatrixN(N, -from);\n\n\tauto la = lookAtMatrixN(N, from, to, ups);\n\n\tauto pm = perspectiveMatrixN(N, eyeRadiansAngle, nearPlane, farPlane, aspectRatio);\n\n\tEigen::MatrixXd result = pm * la * tr;\n\t\n\t//Axis direction correction\n\tEigen::MatrixXd aux = Eigen::MatrixXd::Identity(N + 1, N + 1);\n\t//X correction\n\taux(0, 0) = -1;\n\t//Z correction\n\taux(2, 2) = N != 4 ? -1 : 1;\n\tresult = aux * result;\n\n\t//Z correction\n\t\n\treturn result;\n}\n\n//This assumes that point is an N+1 dimensional vector and that point(N) == 1\nEigen::VectorXd projectPointLosingDimension(Eigen::VectorXd point, Eigen::MatrixXd m) {\n\t//std::cout << \"point\\n\" << point << \"\\n\";\n\n\tEigen::VectorXd pointWith1(point.rows() + 1);\n\tpointWith1.topRightCorner(point.rows(), 1) = point;\n\tpointWith1(point.rows()) = 1;\n\n\t//std::cout << \"pointWith1\\n\" << pointWith1 << \"\\n\";\n\n\tEigen::VectorXd v = m * pointWith1;\n\t//std::cout << \"v\\n\" << v << \"\\n\";\n\tv = v / v(v.rows() - 2, 0);\n\t//std::cout << \"v\\n\" << v << \"\\n\";\n\tauto result = v.topLeftCorner(v.rows() - 1, 1);\n\t//std::cout << \"result\\n\" << result << \"\\n\";\n\n\treturn result;\n}\n\n//This assumes that each point is an N+1 dimensional column in a matrix and that point(N) == 1\nEigen::MatrixXd projectPointsLosingDimension(Eigen::MatrixXd points, Eigen::MatrixXd m, bool usePerspective) {\n\t//std::cout << \"point\\n\" << points << \"\\n\";\n\n\tEigen::MatrixXd pointWith1(points.rows() + 1, points.cols());\n\tpointWith1.topRightCorner(points.rows(), points.cols()) = points;\n\tpointWith1.row(points.rows()) = Eigen::VectorXd::Ones(points.cols());\n\n\t//std::cout << \"pointWith1\\n\" << pointWith1 << \"\\n\";\n\n\tEigen::MatrixXd v = m * pointWith1;\n\t//std::cout << \"v\\n\" << v << \"\\n\";\n\n\tif (usePerspective) {\n\t\tfor (int i = 0; i < v.cols(); i++) {\n\t\t\tif (v.col(i)(v.rows() - 2, 0) == 0 || v.col(i)(v.rows() - 2, 0) == -0) {\n\t\t\t\tv.col(i) = v.col(i) / (0.000001);\n\t\t\t} else {\n\t\t\t\tv.col(i) = v.col(i) / v.col(i)(v.rows() - 2, 0);\n\t\t\t}\n\t\t}\n\t}else{\n\t\tfor (int i = 0; i < v.cols(); i++) {\n\t\t\tif (v.col(i)(v.rows() - 1, 0) == 0 || v.col(i)(v.rows() - 1, 0) == -0) {\n\t\t\t\tv.col(i) = v.col(i) / (0.000001);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tv.col(i) = v.col(i) / v.col(i)(v.rows() - 1, 0);\n\t\t\t}\n\t\t}\n\t}\n\n\tEigen::MatrixXd result = v.topRows(v.rows() - 2);\n\n\treturn result;\n}\n\nEigen::MatrixXd rotateMatrixN(const unsigned int N, unsigned int axis1, unsigned int axis2, double radians_angle) {\n\tassert(axis1 != axis2);\n\n\tEigen::MatrixXd rot_aa = Eigen::MatrixXd::Identity(N, N);\n\n\trot_aa(axis1, axis1) = cos(radians_angle);\n\trot_aa(axis1, axis2) = sin(radians_angle);\n\trot_aa(axis2, axis1) = -sin(radians_angle);\n\trot_aa(axis2, axis2) = cos(radians_angle);\n\n\treturn rot_aa.transpose();\n}\n\nstd::string generateNDimensionalShader(int n) {\n\tstd::stringstream ss;\n\tss << \"#version 330 core\\nlayout (location = 0) in double[\" << n << \"] position;\\n\";\n\n\tfor (int i = n; i >= 3; i--) {\n\t\tss << \"uniform double m\" << i << \"[\" << ((i + 1) * (i + 1)) << \"];\\n\";\n\t}\n\n\tss << \"\\nvoid main() {\\n\";\n\n\tss << \"\tdouble[\" << (n + 1) << \"] positionWithOne;\\n\";\n\tss << \"\tfor (int i = 0; i < \" << n << \"; i++){\\n\";\n\tss << \"\t\tpositionWithOne[i] = position[i];\\n\";\n\tss << \"\t}\\n\";\n\tss << \"\tpositionWithOne[\" << n << \"] = 1;\\n\\n\";\n\n\tss << \"\tdouble[\" << (n + 1) << \"] newPos\" << n << \";\\n\";\n\n\tfor (int i = n; i >= 3; i--) {\n\t\tss << \"\tfor (int i = 0; i <= \" << i << \"; i++) {\\n\";\n\t\tss << \"\t\tdouble newVal = 0;\\n\";\n\t\tss << \"\t\tfor (int j = 0; j <= \" << i << \"; j++){\\n\";\n\t\tss << \"\t\t\tnewVal += m\" << i << \"[j * \" << i << \" + i] * positionWithOne[j];\\n\";\n\t\tss << \"\t\t}\\n\";\n\t\tss << \"\t\tnewPos\" << i << \"[i] = newVal;\\n\";\n\t\tss << \"\t}\\n\";\n\t\tss << \"\t\\n\";\n\t\tif (i != 3) {\n\t\t\tss << \"\tfor (int i = 0; i < \" << i << \"; i++) {\\n\";\n\t\t\tss << \"\t\tpositionWithOne[i] = newPos\" << i << \"[i] / newPos\" << i << \"[\" << (i - 1) << \"];\\n\";\n\t\t\tss << \"\t}\\n\";\n\t\t\tss << \"\t\\n\";\n\t\t\tss << \"\tdouble[\" << i << \"] newPos\" << i - 1 << \";\\n\";\n\t\t}\n\t}\n\n\tss << \"\tgl_Position.x = newPos3[0]/newPos3[3];\\n\";\n\tss << \"\tgl_Position.y = newPos3[1]/newPos3[3];\\n\";\n\tss << \"\tgl_Position.z = newPos3[2]/newPos3[3];\\n\";\n\tss << \"\tgl_Position.w = newPos3[3]/newPos3[3];\\n\";\n\tss << \"}\\n\";\n\n\tstd::string str = ss.str();\n\treturn str;\n}\n\nEigen::MatrixXd makeVectorsHomogeneous(Eigen::MatrixXd points) {\n\tpoints.conservativeResize(points.rows() + 1, Eigen::NoChange);\n\tpoints.row(points.rows() - 1) = Eigen::VectorXd::Ones(points.cols());\n\n\treturn points;\n}\n\nEigen::MatrixXd makeMatrixHomogeneous(Eigen::MatrixXd matrix) {\n\tmatrix.conservativeResize(matrix.rows() + 1, matrix.cols() + 1);\n\tmatrix.row(matrix.rows() - 1) = Eigen::VectorXd::Zero(matrix.cols());\n\tmatrix.col(matrix.cols() - 1) = Eigen::VectorXd::Zero(matrix.rows());\n\tmatrix(matrix.rows() - 1, matrix.cols() - 1) = 1;\n\n\treturn matrix;\n}\n\n#define print(something) {std::stringstream ss; ss << something; qDebug() << ss.str().c_str(); }\n\nEigen::MatrixXd rotateShapeToLowerDimension(Eigen::MatrixXd m) {\n\tconst int D = m.rows();\n\n\t// First we move the first vertex of the shape to the origin\n\tm = translateMatrixN(D, -m.col(0).cast<double>()).cast<double>() * makeVectorsHomogeneous(m);\n\tm.conservativeResize(m.rows() - 1, Eigen::NoChange);\n\n\t//Then, we find a new base created from the points of the polytope\n\t//And also a vector that is simply the last dimension\n\tEigen::MatrixXd newBase = Eigen::MatrixXd::Zero(D, D);\n\tint currentSizeBase = 1;;\n\t{\n\t\tEigen::VectorXd aux = Eigen::VectorXd::Zero(D);\n\t\taux(D - 1) = 1;\n\t\tnewBase.col(0) = aux;\n\n\t\tfor (int i = 0; i < m.cols() && currentSizeBase < 2; i++) {\n\t\t\tfor (int j = i + 1; j < m.cols() && currentSizeBase < 2; j++) {\n\t\t\t\tEigen::VectorXd newVectorOfBase = m.col(j) - m.col(i);\n\t\t\t\tnewVectorOfBase.normalize();\n\t\t\t\tif (newVectorOfBase(0) < 0) {\n\t\t\t\t\tnewVectorOfBase = newVectorOfBase * -1;\n\t\t\t\t}\n\n\t\t\t\tif (newVectorOfBase != newBase.col(0)) {\n\t\t\t\t\tnewBase.col(currentSizeBase) = newVectorOfBase;\n\t\t\t\t\tcurrentSizeBase++;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int i = 0; i < m.cols() && currentSizeBase < D; i++) {\n\t\tfor (int j = i + 1; j < m.cols() && currentSizeBase < D; j++) {\n\t\t\tEigen::VectorXd newVectorOfBase = m.col(j) - m.col(i);\n\t\t\tnewVectorOfBase.normalize();\n\t\t\tif (newVectorOfBase(0) < 0) {\n\t\t\t\tnewVectorOfBase = newVectorOfBase * -1;\n\t\t\t}\n\n\t\t\tEigen::VectorXd x = newBase.colPivHouseholderQr().solve(newVectorOfBase);\n\n\t\t\tEigen::VectorXd check = (newBase * x) - newVectorOfBase;\n\t\t\tdouble error = 0;\n\t\t\tfor (int k = 0; k < x.size(); k++) {\n\t\t\t\terror += check(k) * check(k);\n\t\t\t}\n\n\t\t\tif (error > 1e-5f) {\n\t\t\t\tnewBase.col(currentSizeBase) = newVectorOfBase;\n\t\t\t\tcurrentSizeBase++;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (currentSizeBase != newBase.cols()) {\n\t\tfor (int i = 0; i < newBase.rows(); i++) {\n\t\t\tif (newBase.row(i).isZero(1e-10)) {\n\t\t\t\tm.row(i) = m.row(m.rows() - 1);\n\t\t\t\treturn m.topRows(D - 1);\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//We set the coordinate we want to exclude as the last one\n\t\tfor (int i = 0; i < D - 1; i++) {\n\t\t\tEigen::VectorXd aux = newBase.col(i);\n\t\t\tnewBase.col(i) = newBase.col(i + 1);\n\t\t\tnewBase.col(i + 1) = aux;\n\t\t}\n\n\t\t//We change the base\n\t\tEigen::MatrixXd transformationMatrix = newBase.inverse();\n\t\tEigen::MatrixXd newVertices = transformationMatrix * m;\n\n\t\t//Return only the top rows, excluding the last one\n\t\treturn newVertices.topRows(D - 1);\n\t}\n\n\treturn Eigen::MatrixXd(0, 0);\n}", "meta": {"hexsha": "d33b56966ffada110939078e244924f6d6b6b344", "size": 11142, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TrueNgine/NMatrixOperations.cpp", "max_stars_repo_name": "GSBicalho/TrueNgine", "max_stars_repo_head_hexsha": "069ac9acc1558ae0b549e15eba67dfc646da9200", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-12-06T20:47:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-06T23:54:50.000Z", "max_issues_repo_path": "TrueNgine/NMatrixOperations.cpp", "max_issues_repo_name": "GSBicalho/TrueNgine", "max_issues_repo_head_hexsha": "069ac9acc1558ae0b549e15eba67dfc646da9200", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TrueNgine/NMatrixOperations.cpp", "max_forks_repo_name": "GSBicalho/TrueNgine", "max_forks_repo_head_hexsha": "069ac9acc1558ae0b549e15eba67dfc646da9200", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-24T18:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-19T03:15:35.000Z", "avg_line_length": 29.3210526316, "max_line_length": 130, "alphanum_fraction": 0.6042003231, "num_tokens": 3673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.6498795814956875}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_CONSTANT_CONSTANTS_GOLD_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_CONSTANTS_GOLD_HPP_INCLUDED\n\n#include <boost/simd/include/functor.hpp>\n#include <boost/simd/constant/register.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n   /*!\n     @brief Gold generic tag\n\n     Represents the Gold constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    BOOST_SIMD_CONSTANT_REGISTER( Gold,double,1\n                                , 0x3FCF1BBD,0x3FF9E3779B97F4A8ULL\n                                )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Gold, Site> dispatching_Gold(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::Gold, Site>();\n   }\n   template<class... Args>\n   struct impl_Gold;\n  }\n  /*!\n    Generates the golden ratio that is \\f$\\phi = \\frac{1+\\sqrt5}{2}\\f$\n\n    @par Semantic:\n\n    @code\n    T r = Gold<T>();\n    @endcode\n\n    is similar for floating types to:\n\n    @code\n    T r = (1+sqrt(5))/2;\n    @endcode\n\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Gold, Gold)\n} }\n\n#include <boost/simd/constant/common.hpp>\n\n#endif\n", "meta": {"hexsha": "daf4292b38515ba485da0a95dc3204ba5b04bc3b", "size": 1792, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/constant/constants/gold.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/constant/constants/gold.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/constant/constants/gold.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5692307692, "max_line_length": 164, "alphanum_fraction": 0.5853794643, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6497923041492863}}
{"text": "#include \"math_unit_test.hpp\"\n#include <boost/math/fft/multiprecision_complex.hpp>\n#include <boost/math/fft/bsl_backend.hpp>\n#if defined(__GNUC__)\n#include <boost/math/fft/fftw_backend.hpp>\n#include <boost/math/fft/gsl_backend.hpp>\n#endif\n#include <boost/math/fft/algorithms.hpp>\n#include <boost/math/constants/constants.hpp>\n#ifdef BOOST_MATH_USE_FLOAT128\n#include <boost/multiprecision/complex128.hpp>\n#endif\n#include <boost/multiprecision/cpp_complex.hpp>\n// TODO:\n//#include <boost/multiprecision/mpfr.hpp>\n//#include <boost/multiprecision/mpc.hpp>\n#include <boost/random.hpp>\n\n#include \"fft_test_helpers.hpp\"\n\n#include <type_traits>\n#include <vector>\n#include <limits>\n\nusing namespace boost::math::fft;\n\ntemplate<class T>\nvoid convolution_brute_force(\n  const T* first1, const T* last1, \n  const T* first2,\n  T* out)\n{\n  long N = std::distance(first1,last1);\n  for(long i=0;i<N;++i)\n  {\n    T sum{0};\n    for(int j=0;j<N;++j)\n    {\n      sum += first1[j] * first2[(i-j+N) % N];\n    }\n    out[i] = sum;\n  }\n}\n\ntemplate<class T>\nvoid dft_forward_bruteForce(\n  const T* in_beg, const T* in_end,\n  T* out)\n{\n  ::boost::math::fft::detail::complex_dft_prime_bruteForce(\n    in_beg,in_end,out,\n    1,\n    std::allocator<T>{});\n}\n\ntemplate<template<class ...Args> class backend_t, class T>\nvoid test_directly(unsigned int N, int tolerance)\n{\n  using Complex = boost::multiprecision::complex<T>;\n  const T tol = tolerance*std::numeric_limits<T>::epsilon();\n  \n  // ...\n  boost::random::mt19937 rng;\n  boost::random::uniform_real_distribution<T> U(0.0,1.0);\n  {\n    std::vector<Complex> A(N),B(N),C(N);\n    \n    for(auto& x: A)\n    {\n        x.real( U(rng) );\n        x.imag( U(rng) );\n    }\n    backend_t<Complex> plan(N);\n    plan.forward(A.begin(),A.end(),B.begin());\n    dft_forward_bruteForce(A.data(),A.data()+N,C.data());\n    \n    T diff{0.0};\n    \n    for(size_t i=0;i<N;++i)\n    {\n        using std::norm;\n        diff += norm(B[i]-C[i]);\n    }\n    using std::sqrt;\n    diff = sqrt(diff)/N;\n    CHECK_MOLLIFIED_CLOSE(T{0.0},diff,tol);\n  }\n}\n\ntemplate<class backend_t>\nvoid test_convolution(unsigned int N, int tolerance)\n{\n  using Complex = typename backend_t::value_type;\n  using T = typename Complex::value_type;\n  \n  // using Complex = boost::multiprecision::complex<T>;\n  const T tol = tolerance*std::numeric_limits<T>::epsilon();\n  \n  // ...\n  boost::random::mt19937 rng;\n  boost::random::uniform_real_distribution<T> U(0.0,1.0);\n  {\n    std::vector<Complex> A(N),B(N),C(N);\n    \n    for(auto& x: A)\n    {\n        x.real( U(rng) );\n        x.imag( U(rng) );\n    }\n    for(auto& x: B)\n    {\n        x.real( U(rng) );\n        x.imag( U(rng) );\n    }\n    convolution_brute_force(A.data(),A.data()+N,B.data(),C.data());\n    \n    std::vector<Complex> C_candidate;\n    transform<backend_t>::convolution(A.begin(),A.end(),B.begin(),std::back_inserter(C_candidate));\n    \n    T diff{0.0};\n    \n    for(size_t i=0;i<N;++i)\n    {\n        using std::norm;\n        diff += norm(C[i]-C_candidate[i]);\n    }\n    using std::sqrt;\n    diff = sqrt(diff)/N;\n    CHECK_MOLLIFIED_CLOSE(T{0.0},diff,tol);\n  }\n}\n\ntemplate<class Backend>\nvoid test_fixed_transforms(int tolerance)\n{\n  // using Complex = boost::multiprecision::complex<T>;\n  using Complex = typename Backend::value_type;\n  using real_value_type = typename Complex::value_type;\n  const real_value_type tol = tolerance*std::numeric_limits<real_value_type>::epsilon();\n  {\n    std::vector< Complex > A{1.0},B(1);\n    Backend plan(A.size());\n    plan.forward(A.data(),A.data()+A.size(),B.data());\n    CHECK_MOLLIFIED_CLOSE(real_value_type{1.0},B[0].real(),0);\n    CHECK_MOLLIFIED_CLOSE(real_value_type{0.0},B[0].imag(),0);\n  }\n  {\n    std::vector< Complex > A{1.0,1.0},B(2);\n    Backend plan(A.size());\n    plan.forward(A.data(),A.data()+A.size(),B.data());\n    CHECK_MOLLIFIED_CLOSE(real_value_type{2.0},B[0].real(),tol);\n    CHECK_MOLLIFIED_CLOSE(real_value_type{0.0},B[0].imag(),tol);\n    \n    CHECK_MOLLIFIED_CLOSE(real_value_type{0.0},B[1].real(),tol);\n    CHECK_MOLLIFIED_CLOSE(real_value_type{0.0},B[1].imag(),tol);\n  }\n  {\n    std::vector< Complex > A{1.0,1.0,1.0},B(3);\n    Backend plan(A.size());\n    plan.forward(A.data(),A.data()+A.size(),B.data());\n    CHECK_MOLLIFIED_CLOSE(real_value_type{3.0},B[0].real(),tol);\n    CHECK_MOLLIFIED_CLOSE(real_value_type{0.0},B[0].imag(),tol);\n    \n    CHECK_MOLLIFIED_CLOSE(\n        real_value_type{0.0},B[1].real(),tol);\n    CHECK_MOLLIFIED_CLOSE(\n        real_value_type{0.0},B[1].imag(),tol);\n    \n    CHECK_MOLLIFIED_CLOSE(\n        real_value_type{0.0},B[2].real(),tol);\n    CHECK_MOLLIFIED_CLOSE(\n        real_value_type{0.0},B[2].imag(),tol);\n  }\n  {\n    std::vector< Complex > A{1.0,1.0,1.0};\n    Backend plan(A.size());\n    plan.forward(A.data(),A.data()+A.size(),A.data());\n    CHECK_MOLLIFIED_CLOSE(real_value_type{3.0},A[0].real(),tol);\n    CHECK_MOLLIFIED_CLOSE(real_value_type{0.0},A[0].imag(),tol);\n    \n    CHECK_MOLLIFIED_CLOSE(\n        real_value_type{0.0},A[1].real(),tol);\n    CHECK_MOLLIFIED_CLOSE(\n        real_value_type{0.0},A[1].imag(),tol);\n    \n    CHECK_MOLLIFIED_CLOSE(\n        real_value_type{0.0},A[2].real(),tol);\n    CHECK_MOLLIFIED_CLOSE(\n        real_value_type{0.0},A[2].imag(),tol);\n  }\n}\n\n\ntemplate<class Backend>\nvoid test_inverse(int N, int tolerance)\n{\n  using Complex = typename Backend::value_type;\n  using real_value_type = typename Complex::value_type;\n  const real_value_type tol = tolerance*std::numeric_limits<real_value_type>::epsilon();\n  \n  boost::random::mt19937 rng;\n  boost::random::uniform_real_distribution<real_value_type> U(0.0,1.0);\n  {\n    std::vector<Complex> A(N),B(N),C(N);\n    \n    for(auto& x: A)\n    {\n        x.real( U(rng) );\n        x.imag( U(rng) );\n    }\n    Backend plan(N);\n    plan.forward(A.data(),A.data()+A.size(),B.data());\n    plan.backward(B.data(),B.data()+B.size(),C.data());\n    \n    const real_value_type inverse_N = real_value_type{1.0}/N;\n    for(auto &x : C)\n      x *= inverse_N;\n    \n    real_value_type diff{0.0};\n    \n    for(size_t i=0;i<A.size();++i)\n    {\n        using std::norm;\n        diff += norm(A[i]-C[i]);\n    }\n    using std::sqrt;\n    diff = sqrt(diff)*inverse_N;\n    CHECK_MOLLIFIED_CLOSE(real_value_type{0.0},diff,tol);\n  }\n}\n\n#if defined(__GNUC__)\ntemplate<class T>\nusing complex_fftw_dft = fftw_dft< boost::multiprecision::complex<T> >;\n\ntemplate<class T>\nusing complex_gsl_dft = gsl_dft< boost::multiprecision::complex<T> >;\n#endif\n\ntemplate<class T>\nusing complex_bsl_dft = bsl_dft< boost::multiprecision::complex<T> >;\n\n//template<class T>\n//using complex_rader_dft = rader_dft< boost::multiprecision::complex<T>  >;\n//\n//template<class T>\n//using complex_bruteForce_dft = bruteForce_dft< boost::multiprecision::complex<T>  >;\n//\n//template<class T>\n//using complex_bruteForce_cdft = bruteForce_cdft< boost::multiprecision::complex<T>  >;\n//\n//template<class T>\n//using complex_composite_dft = composite_dft< boost::multiprecision::complex<T>  >;\n//\n//template<class T>\n//using complex_composite_cdft = composite_cdft< boost::multiprecision::complex<T>  >;\n//\n//template<class T>\n//using complex_power2_dft = power2_dft< boost::multiprecision::complex<T>  >;\n//\n//template<class T>\n//using complex_power2_cdft = power2_cdft< boost::multiprecision::complex<T>  >;\n\nint main()\n{\n#if defined(__GNUC__)\n  test_fixed_transforms<complex_fftw_dft<float>>(1);\n  test_fixed_transforms<complex_fftw_dft<double>>(1);\n  test_fixed_transforms<complex_fftw_dft<long double>>(1);\n#endif  \n   \n#if defined(BOOST_MATH_USE_FLOAT128)\n  test_fixed_transforms<complex_fftw_dft<boost::multiprecision::float128>>(1);\n#endif\n  \n#if defined(__GNUC__)\n  test_fixed_transforms<complex_gsl_dft<double>>(1);\n#endif\n\n//  test_fixed_transforms<complex_bruteForce_dft<float> >(4);\n//  test_fixed_transforms<complex_bruteForce_dft<double> >(4);\n//  test_fixed_transforms<complex_bruteForce_dft<long double> >(4);\n  \n//  test_fixed_transforms<complex_bruteForce_cdft<float> >(4);\n//  test_fixed_transforms<complex_bruteForce_cdft<double> >(4);\n//  test_fixed_transforms<complex_bruteForce_cdft<long double> >(4);\n//  \n//  \n//  test_fixed_transforms<complex_composite_dft<float>>(4);\n//  test_fixed_transforms<complex_composite_dft<double>>(4);\n//  test_fixed_transforms<complex_composite_dft<long double>>(4);\n//  \n//  test_fixed_transforms<complex_composite_cdft<float>>(4);\n//  test_fixed_transforms<complex_composite_cdft<double>>(4);\n//  test_fixed_transforms<complex_composite_cdft<long double>>(4);\n  \n  test_fixed_transforms<complex_bsl_dft<float>>(2);\n  test_fixed_transforms<complex_bsl_dft<double>>(2);\n  test_fixed_transforms<complex_bsl_dft<long double>>(2);\n#ifdef BOOST_MATH_USE_FLOAT128\n  test_fixed_transforms<complex_bsl_dft< boost::multiprecision::float128 >>(1);\n#endif\n  test_fixed_transforms<complex_bsl_dft< boost::multiprecision::cpp_bin_float_50>>(2);\n  test_fixed_transforms<complex_bsl_dft< boost::multiprecision::cpp_bin_float_100 >>(2);\n  test_fixed_transforms<complex_bsl_dft< boost::multiprecision::cpp_bin_float_quad >>(2);\n  // TODO:\n  //test_fixed_transforms<complex_bsl_dft< boost::multiprecision::mpfr_float_100 >>(1);\n  \n  for(int i=1;i<=(1<<10); i*=2)\n  {\n#if defined(__GNUC__)\n    test_directly<fftw_dft,double>(i,i*8);\n    test_directly<gsl_dft,double>(i,i*8);\n#endif\n    test_directly<bsl_dft,double>(i,i*8);\n    \n#if defined(__GNUC__)\n    test_inverse<complex_fftw_dft<float>>(i,1);\n    test_inverse<complex_fftw_dft<double>>(i,1);\n    test_inverse<complex_fftw_dft<long double>>(i,1);\n#endif\n#if defined(BOOST_MATH_USE_FLOAT128)\n    test_inverse<complex_fftw_dft<boost::multiprecision::float128>>(i,1);\n#endif\n#if defined(__GNUC__)\n    test_inverse<complex_gsl_dft<double>>(i,1);\n#endif\n    test_inverse<complex_bsl_dft<float>>(i,1);\n    test_inverse<complex_bsl_dft<double>>(i,1);\n    test_inverse<complex_bsl_dft<long double>>(i,1);\n#if defined(BOOST_MATH_USE_FLOAT128)\n    test_inverse<complex_bsl_dft<boost::multiprecision::float128>>(i,1);\n#endif\n    test_inverse<complex_bsl_dft<boost::multiprecision::cpp_bin_float_50>>(i,1);\n    \n//    test_inverse<complex_power2_dft<float>>(i,32);\n//    test_inverse<complex_power2_dft<double>>(i,32);\n//    test_inverse<complex_power2_dft<long double>>(i,32);\n//    test_inverse<complex_power2_dft<boost::multiprecision::cpp_bin_float_50>>(i,32);\n//#ifdef BOOST_MATH_USE_FLOAT128\n//    test_inverse<complex_power2_dft<boost::multiprecision::float128>>(i,32);\n//#endif\n//    \n//    test_inverse<complex_power2_cdft<float>>(i,1);\n//    test_inverse<complex_power2_cdft<double>>(i,1);\n//    test_inverse<complex_power2_cdft<long double>>(i,1);\n//    test_inverse<complex_power2_cdft<boost::multiprecision::cpp_bin_float_50>>(i,1);\n//#ifdef BOOST_MATH_USE_FLOAT128\n//    test_inverse<complex_power2_cdft<boost::multiprecision::float128>>(i,1);\n//#endif\n  }\n  for(int i=1;i<=1000; i*=10)\n  {\n#if defined(__GNUC__)\n    test_directly<fftw_dft,double>(i,i*8);\n    test_directly<gsl_dft,double>(i,i*8);\n#endif\n    test_directly<bsl_dft,double>(i,i*8);\n    \n#if defined(__GNUC__)\n    test_inverse<complex_fftw_dft<float>>(i,1);\n    test_inverse<complex_fftw_dft<double>>(i,1);\n    test_inverse<complex_fftw_dft<long double>>(i,1);\n#endif\n#if defined(BOOST_MATH_USE_FLOAT128)\n    test_inverse<complex_fftw_dft<boost::multiprecision::float128>>(i,1);\n#endif\n#if defined(__GNUC__)\n    test_inverse<complex_gsl_dft<double>>(i,1);\n#endif\n    test_inverse<complex_bsl_dft<float>>(i,1);\n    test_inverse<complex_bsl_dft<double>>(i,1);\n    test_inverse<complex_bsl_dft<long double>>(i,1);\n#if defined(BOOST_MATH_USE_FLOAT128)\n    test_inverse<complex_bsl_dft<boost::multiprecision::float128>>(i,1);\n#endif\n    test_inverse<complex_bsl_dft<boost::multiprecision::cpp_bin_float_50>>(i,1);\n  }\n  for(auto i : std::vector<int>{2,3,5,7,11,13,17,23,29,31})\n  {\n#if defined(__GNUC__)\n    test_directly<fftw_dft,double>(i,i*8);\n    test_directly<gsl_dft,double>(i,i*8);\n#endif\n    test_directly<bsl_dft,double>(i,i*8);\n    \n#if defined(__GNUC__)\n    test_inverse<complex_fftw_dft<float>>(i,1);\n    test_inverse<complex_fftw_dft<double>>(i,1);\n    test_inverse<complex_fftw_dft<long double>>(i,1);\n#endif\n#if defined(BOOST_MATH_USE_FLOAT128)\n    test_inverse<complex_fftw_dft<boost::multiprecision::float128>>(i,1);\n#endif\n#if defined(__GNUC__)\n    test_inverse<complex_gsl_dft<double>>(i,1);\n#endif\n    test_inverse<complex_bsl_dft<float>>(i,2);\n    test_inverse<complex_bsl_dft<double>>(i,2);\n    test_inverse<complex_bsl_dft<long double>>(i,2);\n#if defined(BOOST_MATH_USE_FLOAT128)\n    test_inverse<complex_bsl_dft<boost::multiprecision::float128>>(i,2);\n#endif\n    test_inverse<complex_bsl_dft<boost::multiprecision::cpp_bin_float_50>>(i,2);\n\n    \n//    if(i>2)\n//    {\n//      test_inverse<complex_rader_dft<float> >(i,2);\n//      test_inverse<complex_rader_dft<double> >(i,2);\n//      test_inverse<complex_rader_dft<long double> >(i,2);\n//#ifdef BOOST_MATH_USE_FLOAT128\n//      test_inverse<complex_rader_dft<boost::multiprecision::float128> >(i,2);\n//#endif\n//      test_inverse<complex_rader_dft<boost::multiprecision::cpp_bin_float_50> >(i,2);\n//    }\n  }\n  \n  for(int i=1;i<=100;++i)\n  {\n#if defined(__GNUC__)\n    test_directly<fftw_dft,double>(i,i*8);\n    test_directly<gsl_dft,double>(i,i*8);\n#endif\n    test_directly<bsl_dft,double>(i,i*8);\n    \n#if defined(__GNUC__)\n    test_inverse<complex_fftw_dft<float>>(i,1);\n    test_inverse<complex_fftw_dft<double>>(i,1);\n    test_inverse<complex_fftw_dft<long double>>(i,1);\n#endif\n#if defined(BOOST_MATH_USE_FLOAT128)\n    test_inverse<complex_fftw_dft<boost::multiprecision::float128>>(i,1);\n#endif\n#if defined(__GNUC__)\n    test_inverse<complex_gsl_dft<double>>(i,1);\n#endif\n    test_inverse<complex_bsl_dft<float>>(i,2);\n    test_inverse<complex_bsl_dft<double>>(i,2);\n    test_inverse<complex_bsl_dft<long double>>(i,2);\n#if defined(BOOST_MATH_USE_FLOAT128)\n    test_inverse<complex_bsl_dft<boost::multiprecision::float128>>(i,2);\n#endif\n    test_inverse<complex_bsl_dft<boost::multiprecision::cpp_bin_float_50>>(i,2);\n    \n//    if(i<=20)\n//    {\n//      test_inverse<complex_bruteForce_dft<float> >(i,i*8);\n//      test_inverse<complex_bruteForce_dft<double> >(i,i*8);\n//      test_inverse<complex_bruteForce_dft<long double> >(i,i*8);\n//      test_inverse<complex_bruteForce_dft<boost::multiprecision::cpp_bin_float_50> >(i,i*8);\n//#ifdef BOOST_MATH_USE_FLOAT128\n//      test_inverse<complex_bruteForce_dft<boost::multiprecision::float128> >(i,i*8);\n//#endif\n//      \n//      test_inverse<complex_bruteForce_cdft<float> >(i,i*8);\n//      test_inverse<complex_bruteForce_cdft<double> >(i,i*8);\n//      test_inverse<complex_bruteForce_cdft<long double> >(i,i*8);\n//      test_inverse<complex_bruteForce_cdft<boost::multiprecision::cpp_bin_float_50> >(i,i*8);\n//#ifdef BOOST_MATH_USE_FLOAT128\n//      test_inverse<complex_bruteForce_cdft<boost::multiprecision::float128> >(i,i*8);\n//#endif\n//    }\n    \n#if defined(__GNUC__)\n    test_convolution<fftw_dft<std::complex<double>>>(i,i*8);\n    test_convolution<gsl_dft<std::complex<double>>>(i,i*8);\n#endif\n    test_convolution<bsl_dft<std::complex<double>>>(i,i*8);\n    \n//    test_inverse<complex_composite_dft<float>>(i,i*8);\n//    test_inverse<complex_composite_dft<double>>(i,i*8);\n//    test_inverse<complex_composite_dft<long double>>(i,i*8);\n//    \n//    test_inverse<complex_composite_cdft<float>>(i,2);\n//    test_inverse<complex_composite_cdft<double>>(i,2);\n//    test_inverse<complex_composite_cdft<long double>>(i,2);\n  }\n  // TODO: can we print a useful compilation error message for the following\n  // illegal case?\n  // dft<std::complex<int>> P(3);   \n  return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "0ade1cda7aeb326cae0833ad4fcfa296d512b380", "size": 15655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fft_correctedness.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/fft_correctedness.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_correctedness.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 32.3450413223, "max_line_length": 99, "alphanum_fraction": 0.6935803258, "num_tokens": 4627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6497576443116466}}
{"text": "//\n//#include <cstdlib>\n//#include <iostream>\n//#include <Eigen/Dense>\n//#include <Eigen/Eigenvalues>\n\n#include <iostream>\n#include <cstdlib>\n#include <cstring>\n#include <random>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nextern \"C\"\n{\n\tdouble randValue(double max, double min) {\n\t\t\treturn min + ((rand() / (double)RAND_MAX) * (max - min));\n\t}\n\n\t__declspec(dllexport) void cleanModel(double * model)\n\t{\n\t\tfree(model);\n\t}\n\n\t__declspec(dllexport) double * lineaire_model(int nbInput)\n\t{\n\t\tdouble * model = (double *)malloc((nbInput + 1) * sizeof(double));\n\t\tmodel[0] = 1;\n\n\t\tfor (int i = 1; i <= nbInput; ++i)\n\t\t{\n\t\t\tmodel[i] = randValue(1, -1);\n\t\t}\n\t\treturn model;\n\t}\n\n\t__declspec(dllexport) double classifyRegression(double* model, double* input, int inputSize)\n\t{\n\t\tdouble sum = model[0];\n\t\tfor (int i = 0; i < inputSize; ++i)\n\t\t{\n\t\t\tsum += model[i + 1] * input[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\t__declspec(dllexport) void regression(double* model, double* valueSend, int size, int inputSize, double* waitValue)\n\t{\n\t\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> entry(size, inputSize + 1);\n\t\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> waited(size, 1);\n\n\t\tfor (int i = 0; i < size; ++i)\n\t\t{\n\t\t\twaited(i, 0) = *waitValue;\n\t\t\t++waitValue;\n\t\t}\n\n\t\tfor (int i = 0; i < size; ++i)\n\t\t{\n\t\t\tentry(i, 0) = 1.0;\n\t\t\tfor (int j = 1; j < inputSize + 1; ++j)\n\t\t\t{\n\t\t\t\tentry(i, j) = *valueSend;\n\t\t\t\t++valueSend;\n\t\t\t}\n\t\t}\n\n\t\tEigen::MatrixXd transposedMatrix = entry.transpose();\n\t\tEigen::MatrixXd inverseMatrix = (transposedMatrix*entry).inverse();\n\t\tEigen::MatrixXd final = inverseMatrix*transposedMatrix;\n\t\tEigen::MatrixXd weight = final*waited;\n\n\t\tfor (int i = 0; i < weight.rows(); ++i)\n\t\t{\n\t\t\t*model = weight(i, 0);\n\t\t\t++model;\n\t\t}\n\t}\n}", "meta": {"hexsha": "ca668ab3a85c98e060f2fe715a30ddb9aed224e8", "size": 1796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "linear regression/LinearRegressionCpp/ConsoleApplication1/Source.cpp", "max_stars_repo_name": "DamienBidaud/machine_learning_esgi", "max_stars_repo_head_hexsha": "657aaa00957c29b4db74079b1dda96f3e70c2455", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear regression/LinearRegressionCpp/ConsoleApplication1/Source.cpp", "max_issues_repo_name": "DamienBidaud/machine_learning_esgi", "max_issues_repo_head_hexsha": "657aaa00957c29b4db74079b1dda96f3e70c2455", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear regression/LinearRegressionCpp/ConsoleApplication1/Source.cpp", "max_forks_repo_name": "DamienBidaud/machine_learning_esgi", "max_forks_repo_head_hexsha": "657aaa00957c29b4db74079b1dda96f3e70c2455", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1728395062, "max_line_length": 116, "alphanum_fraction": 0.6319599109, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.649734730799777}}
{"text": "#include<iostream>\n#include<vector>\n#include<fstream>\n#include <boost/math/special_functions/gamma.hpp>\n\nconst int X=0;\nconst int O2=1;\nconst int G=2;\nconst int Xy=3;\nconst int A=4;\nconst int B=5;\n\nvoid get_rhs(std::vector<double>& rhs,std::vector<double> solnvec,double t,int nvars)\n{\n  // ------- MODEL CONSTANTS -------\n  double y_xs = 0.009;\n  double y_as = 1.01;\n  double y_bs = 0.88;\n  double y_os = 0.0467;\n\n  double x_max = 11;\n  double qs_max = 17;\n  double o2_max = 0.214;\n\n  double K_e = 0.0214;\n  double K_s = 31;\n\n  double alpha_s = 3;\n  double beta_s = 12;\n  double alpha_e = 1;\n  double beta_e = 1e3;\n\n  double kLa = 5;\n\n  // calculate chi_i\n  // A word of explanation about the form of the gamma incomplete call. This function\n  // is usually expressed as g(a, x), where a and x are obligate positive. Therefore, we need\n  // to restrict x to be no lower than 0. Additionally, we need to make sure we don't hit a\n  // divide by zero error, so we condition use of the gamma function on the denominator being\n  // non-zero.\n  double chi_s = 1;\n  double chi_e = 1;\n\n  if (solnvec[Xy]>1e-8) {\n    double sRatio = std::max(solnvec[G]/(solnvec[Xy]), 0.0);\n    chi_s = boost::math::gamma_p(alpha_s, beta_s*sRatio);\n  }\n  \n  if (solnvec[A]>1e-8) {\n    double eRatio = std::max(solnvec[O2]/(solnvec[A]), 0.0);\n    chi_e = boost::math::gamma_p(alpha_e, beta_e*eRatio);\n  }\n  \n  double chi_p = 0.3;\n\n  // calculate q_s\n  double F_s = (solnvec[G] + solnvec[Xy])/(solnvec[G] + solnvec[Xy] + K_s);\n  double F_e = (solnvec[O2] + solnvec[A]/beta_e)/(solnvec[O2] + solnvec[A]/beta_e + K_e);\n  double q_s = qs_max*F_s*F_e;\n\n  // calculate intermediate rates\n  double rar = chi_p*y_as*q_s*solnvec[X];\n  double rbr = (1-chi_p)*y_bs*q_s*solnvec[X];\n\n  double our = -chi_e*y_os*q_s*solnvec[X];\n  double otr = kLa *(o2_max - solnvec[O2]);\n  double rae = -(1-chi_e)*y_as*q_s*solnvec[X];\n  double rbe = -rae;\n\n\n  // calculate final rates\n  rhs[X] = y_xs*q_s*solnvec[X]*(1 - solnvec[X]/x_max);\n  //rhs[O2] = our+otr;\n  rhs[02] = 0;\n  rhs[G] = -chi_s     *q_s*solnvec[X];\n  rhs[Xy] = -(1-chi_s) *q_s*solnvec[X];\n  rhs[A] = rar+rae;\n  rhs[B] = rbr+rbe;\n\n}\n\ndouble get_our(std::vector<double> solnvec,double t,int nvars)\n{\n  // ------- MODEL CONSTANTS -------\n  double y_os = 0.0467;\n\n  double x_max = 11;\n  double qs_max = 17;\n  double o2_max = 0.214;\n\n  double K_e = 0.0214;\n  double K_s = 31;\n\n  double alpha_s = 3;\n  double beta_s = 12;\n  double alpha_e = 1;\n  double beta_e = 1e3;\n\n\n  // calculate chi_i\n  double chi_s = 1;\n  double chi_e = 1;\n\n  if (solnvec[Xy]>1e-8) {\n    double sRatio = std::max(solnvec[G]/(solnvec[Xy]), 0.0);\n    chi_s = boost::math::gamma_p(alpha_s, beta_s*sRatio);\n  }\n  \n  if (solnvec[A]>1e-8) {\n    double eRatio = std::max(solnvec[O2]/(solnvec[A]), 0.0);\n    chi_e = boost::math::gamma_p(alpha_e, beta_e*eRatio);\n  }\n  \n  double chi_p = 0.3;\n\n  // calculate q_s\n  double F_s = (solnvec[G] + solnvec[Xy])/(solnvec[G] + solnvec[Xy] + K_s);\n  double F_e = (solnvec[O2] + solnvec[A]/beta_e)/(solnvec[O2] + solnvec[A]/beta_e + K_e);\n  double q_s = qs_max*F_s*F_e;\n\n  double our = -chi_e*y_os*q_s*solnvec[X];\n\n  return our;\n}\n\n\n\nvoid advance(std::vector<double>& solnvec,int nvars,double t_now,double t_adv,double dt)\n{\n    double current_time=t_now;\n    double final_time=t_now+t_adv;\n\n    std::vector<double> rhs(nvars);\n    std::vector<double> solnvec_n(nvars);\n\n    while(current_time < final_time)\n    {\n        current_time += dt;\n\n        //at current time level n\n        solnvec_n=solnvec;\n\n        //Doing RK23\n\n        //stage 1\n        get_rhs(rhs,solnvec,current_time,nvars);\n        for(int i=0;i<nvars;i++)\n        {\n            solnvec[i] = solnvec_n[i] + 0.5*rhs[i]*dt;\n        }\n        \n        //stage 2\n        get_rhs(rhs,solnvec,current_time,nvars);\n        for(int i=0;i<nvars;i++)\n        {\n            solnvec[i] = solnvec_n[i] + rhs[i]*dt;\n        }\n    }\n}\n\nint main()\n{\n    int nvars=6;\n    std::vector<double> solnvec(nvars);\n\n\n    double final_time=24.0;\n    double advance_time=0.5;\n    double current_time=0.0;\n    double dt=advance_time/50.0;\n\n    std::ofstream outfile(\"timehist.dat\");\n\n    //set initial conditions\n    solnvec[X]  = 0.5;\n    solnvec[O2] = 0.214;\n    solnvec[G]  = 500.0;\n    solnvec[Xy] = 250.0;\n    solnvec[A]  = 0.0;\n    solnvec[B]  = 0.0;\n\n    //write initial condition\n    outfile<<current_time<<\"\\t\";\n    for(int i=0;i<nvars;i++)\n    {\n        outfile<<solnvec[i]<<\"\\t\";\n    }\n    outfile<<\"\\n\";\n\n\n    while(current_time < final_time)\n    {\n        current_time += advance_time;\n\n        advance(solnvec,nvars,current_time,advance_time,dt);\n\n        outfile<<current_time<<\"\\t\";\n        for(int i=0;i<nvars;i++)\n        {\n            outfile<<solnvec[i]<<\"\\t\";\n        }\n        outfile<<\"\\n\";\n    }\n\n    outfile.close();\n    return(0);\n}\n", "meta": {"hexsha": "ae84b6a544a12dd6d8c054dab85b3b9466574afd", "size": 4811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bioreactor/wellmixed_ODE_solver/solver.cpp", "max_stars_repo_name": "NREL/VirtualEngineering", "max_stars_repo_head_hexsha": "f23f409132bc7965334db1e29d83502001ec4e09", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-02-23T21:33:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T08:06:24.000Z", "max_issues_repo_path": "bioreactor/wellmixed_ODE_solver/solver.cpp", "max_issues_repo_name": "NREL/VirtualEngineering", "max_issues_repo_head_hexsha": "f23f409132bc7965334db1e29d83502001ec4e09", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-02-28T19:10:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T22:24:34.000Z", "max_forks_repo_path": "bioreactor/wellmixed_ODE_solver/solver.cpp", "max_forks_repo_name": "NREL/VirtualEngineering", "max_forks_repo_head_hexsha": "f23f409132bc7965334db1e29d83502001ec4e09", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1298076923, "max_line_length": 93, "alphanum_fraction": 0.6025774267, "num_tokens": 1672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6496659877028997}}
{"text": "/*\n * MIT License\n *\n * Copyright (c) 2020 Robert Grupp\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include \"xregPairedPointRegi3D3D.h\"\n\n#include <Eigen/Eigenvalues>\n\n#include \"xregAssert.h\"\n#include \"xregRotUtils.h\"\n#include \"xregPointCloudUtils.h\"\n#include \"xregLandmarkMapUtils.h\"\n\nxreg::FrameTransform\nxreg::PairedPointRegi3D3D(const Pt3List& pts1, const Pt3List& pts2, const CoordScalar scale)\n{\n  const size_type num_pts = pts1.size();\n  xregASSERT(num_pts == pts2.size());\n\n  FrameTransform xform = FrameTransform::Identity();\n\n  // These calls are threaded\n  const Pt3 cent1 = ComputeCentroid(pts1);\n  const Pt3 cent2 = ComputeCentroid(pts2);\n\n  // These calls are threaded\n  const Pt3List pts1_prime = OffsetPoints(-cent1, pts1);\n  const Pt3List pts2_prime = OffsetPoints(-cent2, pts2);\n\n  CoordScalar s = scale;\n  if (s <= 0)\n  {\n    s = 0;\n\n    const CoordScalar s1 = SumOfNormsSquared(pts1_prime);  // threaded\n\n    if (std::abs(s1) > 1.0e-6)\n    {\n      const CoordScalar s2 = SumOfNormsSquared(pts2_prime);  // threaded\n\n      s = std::sqrt(s2 / s1);\n    }\n  }\n\n  CoordScalar S[9];\n\n  CoordScalar* S_dst = S;\n  for (size_type i = 0; i < 3; ++i)\n  {\n    for (size_type j = 0; j < 3; ++j, ++S_dst)\n    {\n      // This call is threaded\n      *S_dst = InnerProductAboutDimsOfPts(pts1_prime, pts2_prime, i, j);\n    }\n  }\n\n  const CoordScalar S_xx = S[0];\n  const CoordScalar S_xy = S[1];\n  const CoordScalar S_xz = S[2];\n  const CoordScalar S_yx = S[3];\n  const CoordScalar S_yy = S[4];\n  const CoordScalar S_yz = S[5];\n  const CoordScalar S_zx = S[6];\n  const CoordScalar S_zy = S[7];\n  const CoordScalar S_zz = S[8];\n\n  Mat4x4 N_matrix;\n  N_matrix(0,0) = S_xx + S_yy + S_zz;\n  N_matrix(0,1) = S_yz - S_zy;\n  N_matrix(0,2) = S_zx - S_xz;\n  N_matrix(0,3) = S_xy - S_yx;\n  N_matrix(1,0) = N_matrix(0,1);\n  N_matrix(1,1) = S_xx - S_yy - S_zz;\n  N_matrix(1,2) = S_xy + S_yx;\n  N_matrix(1,3) = S_zx + S_xz;\n  N_matrix(2,0) = N_matrix(0,2);\n  N_matrix(2,1) = N_matrix(1,2);\n  N_matrix(2,2) = -S_xx + S_yy - S_zz;\n  N_matrix(2,3) = S_yz + S_zy;\n  N_matrix(3,0) = N_matrix(0,3);\n  N_matrix(3,1) = N_matrix(1,3);\n  N_matrix(3,2) = N_matrix(2,3);\n  N_matrix(3,3) = -S_xx - S_yy + S_zz;\n\n  Eigen::EigenSolver<Mat4x4> eig_dec(N_matrix, true);\n\n  size_type max_index = 0;\n  eig_dec.eigenvalues().real().maxCoeff(&max_index);\n  xform.linear().matrix() = QuatToRotMat(eig_dec.eigenvectors().col(max_index).real());\n\n  xform.linear().matrix() *= s;\n\n  xform.matrix().block(0,3,3,1) = cent2 - (xform.linear() * cent1);\n  \n  return xform;\n}\n\nxreg::FrameTransform\nxreg::PairedPointRegi3D3D(const LandMap3& pts1, const LandMap3& pts2, const CoordScalar scale)\n{\n  const auto corr_lists = CreateCorrespondencePointLists(pts1, pts2);\n\n  return PairedPointRegi3D3D(std::get<0>(corr_lists), std::get<1>(corr_lists), scale);\n}\n\n", "meta": {"hexsha": "730951984b2ba2426388f80ab38c3b69b76534a7", "size": 3850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/regi/xregPairedPointRegi3D3D.cpp", "max_stars_repo_name": "rg2/xreg", "max_stars_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2020-09-29T18:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:25:13.000Z", "max_issues_repo_path": "lib/regi/xregPairedPointRegi3D3D.cpp", "max_issues_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_issues_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-09T01:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T15:39:44.000Z", "max_forks_repo_path": "lib/regi/xregPairedPointRegi3D3D.cpp", "max_forks_repo_name": "rg2/xreg", "max_forks_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-05-25T05:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T12:29:50.000Z", "avg_line_length": 30.5555555556, "max_line_length": 94, "alphanum_fraction": 0.6914285714, "num_tokens": 1232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6496659803672258}}
{"text": "//  (C) Copyright Nick Thompson 2021.\n//  (C) Copyright Matt Borland 2022.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <cmath>\n#include <cstdint>\n#include <array>\n#include <complex>\n#include <tuple>\n#include <iostream>\n#include <vector>\n#include <limits>\n#include <boost/math/tools/color_maps.hpp>\n\n#if !__has_include(\"lodepng.h\")\n #error \"lodepng.h is required to run this example.\"\n#endif\n#include \"lodepng.h\"\n#include <iostream>\n#include <string>\n#include <vector>\n\n\n// In lodepng, the vector is expected to be row major, with the top row\n// specified first. Note that this is a bit confusing sometimes as it's more\n// natural to let y increase moving *up*.\nunsigned write_png(const std::string &filename,\n                   const std::vector<std::uint8_t> &img, std::size_t width,\n                   std::size_t height) {\n  unsigned error = lodepng::encode(filename, img, width, height,\n                                   LodePNGColorType::LCT_RGBA, 8);\n  if (error) {\n    std::cerr << \"Error encoding png: \" << lodepng_error_text(error) << \"\\n\";\n  }\n  return error;\n}\n\n\n// Computes ab - cd.\n// See: https://pharr.org/matt/blog/2019/11/03/difference-of-floats.html\ntemplate <typename Real>\ninline Real difference_of_products(Real a, Real b, Real c, Real d)\n{\n    Real cd = c * d;\n    Real err = std::fma(-c, d, cd);\n    Real dop = std::fma(a, b, -cd);\n    return dop + err;\n}\n\ntemplate<typename Real>\nauto fifth_roots(std::complex<Real> z)\n{\n    std::complex<Real> v = std::pow(z,4);\n    std::complex<Real> dw = Real(5)*v;\n    std::complex<Real> w = v*z - Real(1);\n    return std::make_pair(w, dw);\n}\n\ntemplate<typename Real>\nauto g(std::complex<Real> z)\n{\n    std::complex<Real> z2 = z*z;\n    std::complex<Real> z3 = z*z2;\n    std::complex<Real> z4 = z2*z2;\n    std::complex<Real> w = z4*(z4 + Real(15)) - Real(16);\n    std::complex<Real> dw = Real(4)*z3*(Real(2)*z4 + Real(15));\n    return std::make_pair(w, dw);\n}\n\ntemplate<typename Real>\nstd::complex<Real> complex_newton(std::function<std::pair<std::complex<Real>,std::complex<Real>>(std::complex<Real>)> f, std::complex<Real> z)\n{\n    // f(x(1+e)) = f(x) + exf'(x)\n    bool close = false;\n    do\n    {\n        auto [y, dy] = f(z);\n        z -= y/dy;\n        close = (abs(y) <= 1.4*std::numeric_limits<Real>::epsilon()*abs(z*dy));\n    } while(!close);\n    return z;\n}\n\ntemplate<typename Real>\nclass plane_pixel_map\n{\npublic:\n    plane_pixel_map(int64_t image_width, int64_t image_height, Real xmin, Real ymin)\n    {\n        image_width_ = image_width;\n        image_height_ = image_height;\n        xmin_ = xmin;\n        ymin_ = ymin;\n    }\n\n    std::complex<Real> to_complex(int64_t i, int64_t j) const {\n        Real x = xmin_ + 2*abs(xmin_)*Real(i)/Real(image_width_ - 1);\n        Real y = ymin_ + 2*abs(ymin_)*Real(j)/Real(image_height_ - 1);\n        return std::complex<Real>(x,y);\n    }\n\n    std::pair<int64_t, int64_t> to_pixel(std::complex<Real> z) const {\n        Real x = z.real();\n        Real y = z.imag();\n        Real ii = (image_width_ - 1)*(x - xmin_)/(2*abs(xmin_));\n        Real jj = (image_height_ - 1)*(y - ymin_)/(2*abs(ymin_));\n\n        return std::make_pair(std::round(ii), std::round(jj));\n    }\n\nprivate:\n    int64_t image_width_;\n    int64_t image_height_;\n    Real xmin_;\n    Real ymin_;\n};\n\nint main(int argc, char** argv)\n{\n    using Real = double;\n    using boost::math::tools::viridis;\n    using std::sqrt;\n\n    std::function<std::array<Real, 3>(Real)> color_map = viridis<Real>;\n    std::string requested_color_map = \"viridis\";\n    if (argc == 2) {\n       requested_color_map = std::string(argv[1]);\n       if (requested_color_map == \"smooth_cool_warm\") {\n          color_map = boost::math::tools::smooth_cool_warm<Real>;\n       }\n       else if (requested_color_map == \"plasma\") {\n          color_map = boost::math::tools::plasma<Real>;\n       }\n       else if (requested_color_map == \"black_body\") {\n          color_map = boost::math::tools::black_body<Real>;\n       }\n       else if (requested_color_map == \"inferno\") {\n          color_map = boost::math::tools::inferno<Real>;\n       }\n       else if (requested_color_map == \"kindlmann\") {\n          color_map = boost::math::tools::kindlmann<Real>;\n       }\n       else if (requested_color_map == \"extended_kindlmann\") {\n          color_map = boost::math::tools::extended_kindlmann<Real>;\n       }\n       else {\n          std::cerr << \"Could not recognize color map \" << argv[1] << \".\";\n          return 1;\n       }\n    }\n    constexpr int64_t image_width = 1024;\n    constexpr int64_t image_height = 1024;\n    constexpr const Real two_pi = 6.28318530718;\n\n    std::vector<std::uint8_t> img(4*image_width*image_height, 0);\n    plane_pixel_map<Real> map(image_width, image_height, Real(-2), Real(-2));\n\n    for (int64_t j = 0; j < image_height; ++j)\n    {\n        std::cout << \"j = \" << j << \"\\n\";\n        for (int64_t i = 0; i < image_width; ++i)\n        {\n            std::complex<Real> z0 = map.to_complex(i,j);\n            auto rt = complex_newton<Real>(g<Real>, z0);\n            // The root is one of exp(2*pi*ij/5). Therefore, it can be classified by angle.\n            Real theta = std::atan2(rt.imag(), rt.real());\n            // Now theta in [-pi,pi]. Get it into [0,2pi]:\n            if (theta < 0) {\n                theta += two_pi;\n            }\n            theta /= two_pi;\n            if (std::isnan(theta)) {\n                std::cerr << \"Theta is a nan!\\n\";\n            }\n            auto c = boost::math::tools::to_8bit_rgba(color_map(theta));\n            int64_t idx = 4 * image_width * (image_height - 1 - j) + 4 * i;\n            img[idx + 0] = c[0];\n            img[idx + 1] = c[1];\n            img[idx + 2] = c[2];\n            img[idx + 3] = c[3];\n        }\n    }\n\n    std::array<std::complex<Real>, 8> roots;\n    roots[0] = -Real(1);\n    roots[1] = Real(1);\n    roots[2] = {Real(0), Real(1)};\n    roots[3] = {Real(0), -Real(1)};\n    roots[4] = {sqrt(Real(2)), sqrt(Real(2))};\n    roots[5] = {sqrt(Real(2)), -sqrt(Real(2))};\n    roots[6] = {-sqrt(Real(2)), -sqrt(Real(2))};\n    roots[7] = {-sqrt(Real(2)), sqrt(Real(2))};\n\n    for (int64_t k = 0; k < 8; ++k)\n    {\n        auto [ic, jc] = map.to_pixel(roots[k]);\n\n        int64_t r = 7;\n        for (int64_t i = ic - r; i < ic + r; ++i)\n        {\n            for (int64_t j = jc - r; j < jc + r; ++j)\n            {\n                if ((i-ic)*(i-ic) + (j-jc)*(j-jc) > r*r)\n                {\n                    continue;\n                }\n                int64_t idx = 4 * image_width * (image_height - 1 - j) + 4 * i;\n                img[idx + 0] = 0;\n                img[idx + 1] = 0;\n                img[idx + 2] = 0;\n                img[idx + 3] = 0xff;\n            }\n        }\n    }\n\n    // Requires lodepng.h\n    // See: https://github.com/lvandeve/lodepng for download and compilation instructions\n    write_png(requested_color_map + \"_newton_fractal.png\", img, image_width, image_height);\n}\n", "meta": {"hexsha": "22bb0ed78a8a68d50d64accd832e088552f8d958", "size": 7068, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/color_maps_example.cpp", "max_stars_repo_name": "grlee77/math", "max_stars_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/color_maps_example.cpp", "max_issues_repo_name": "grlee77/math", "max_issues_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/color_maps_example.cpp", "max_forks_repo_name": "grlee77/math", "max_forks_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8378378378, "max_line_length": 142, "alphanum_fraction": 0.5609790606, "num_tokens": 2086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6496659790577558}}
{"text": "//\n// Copyright (c) 2019-2020 INRIA\n//\n\n#include <pinocchio/math/rpy.hpp>\n#include <pinocchio/math/quaternion.hpp>\n#include <pinocchio/spatial/skew.hpp>\n\n#include <boost/variant.hpp> // to avoid C99 warnings\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_rpyToMatrix)\n{\n  double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n  double p = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/M_PI)) - (M_PI/2);\n  double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n  \n  Eigen::Matrix3d R = pinocchio::rpy::rpyToMatrix(r, p, y);\n  \n  Eigen::Matrix3d Raa = (Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ())\n                            * Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY())\n                            * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX())\n                            ).toRotationMatrix();\n  \n  BOOST_CHECK(R.isApprox(Raa));\n  \n  Eigen::Vector3d v;\n  v << r, p, y;\n  \n  Eigen::Matrix3d Rv = pinocchio::rpy::rpyToMatrix(v);\n  \n  BOOST_CHECK(Rv.isApprox(Raa));\n  BOOST_CHECK(Rv.isApprox(R));\n}\n\nBOOST_AUTO_TEST_CASE(test_matrixToRpy)\n{\n  #ifdef NDEBUG\n    const int n = 1e5;\n  #else\n    const int n = 1e2;\n  #endif\n  for(int k = 0; k < n ; ++k)\n  {\n    Eigen::Quaterniond quat;\n    pinocchio::quaternion::uniformRandom(quat);\n    const Eigen::Matrix3d R = quat.toRotationMatrix();\n\n    const Eigen::Vector3d v = pinocchio::rpy::matrixToRpy(R);\n    Eigen::Matrix3d Rprime = pinocchio::rpy::rpyToMatrix(v);\n\n    BOOST_CHECK(Rprime.isApprox(R));\n    BOOST_CHECK(-M_PI <= v[0] && v[0] <= M_PI);\n    BOOST_CHECK(-M_PI/2 <= v[1] && v[1] <= M_PI/2);\n    BOOST_CHECK(-M_PI <= v[2] && v[2] <= M_PI);\n  }\n\n#ifdef NDEBUG\n  const int n2 = 1e3;\n#else\n  const int n2 = 1e2;\n#endif\n\n  // Test singular case theta = pi/2\n  for(int k = 0; k < n2 ; ++k)\n  {\n    double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n    double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n    Eigen::Matrix3d Rp;\n    Rp <<  0.0, 0.0, 1.0,\n           0.0, 1.0, 0.0,\n          -1.0, 0.0, 0.0;\n    const Eigen::Matrix3d R = Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ()).toRotationMatrix()\n                            * Rp\n                            * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()).toRotationMatrix();\n\n    const Eigen::Vector3d v = pinocchio::rpy::matrixToRpy(R);\n    Eigen::Matrix3d Rprime = pinocchio::rpy::rpyToMatrix(v);\n\n    BOOST_CHECK(Rprime.isApprox(R));\n    BOOST_CHECK(-M_PI <= v[0] && v[0] <= M_PI);\n    BOOST_CHECK(-M_PI/2 <= v[1] && v[1] <= M_PI/2);\n    BOOST_CHECK(-M_PI <= v[2] && v[2] <= M_PI);\n  }\n\n  // Test singular case theta = -pi/2\n  for(int k = 0; k < n2 ; ++k)\n  {\n    double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n    double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n    Eigen::Matrix3d Rp;\n    Rp << 0.0, 0.0, -1.0,\n          0.0, 1.0,  0.0,\n          1.0, 0.0,  0.0;\n    const Eigen::Matrix3d R = Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ()).toRotationMatrix()\n                            * Rp\n                            * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()).toRotationMatrix();\n\n    const Eigen::Vector3d v = pinocchio::rpy::matrixToRpy(R);\n    Eigen::Matrix3d Rprime = pinocchio::rpy::rpyToMatrix(v);\n\n    BOOST_CHECK(Rprime.isApprox(R));\n    BOOST_CHECK(-M_PI <= v[0] && v[0] <= M_PI);\n    BOOST_CHECK(-M_PI/2 <= v[1] && v[1] <= M_PI/2);\n    BOOST_CHECK(-M_PI <= v[2] && v[2] <= M_PI);\n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(test_computeRpyJacobian)\n{\n  // Check identity at zero\n  Eigen::Vector3d rpy(Eigen::Vector3d::Zero());\n  Eigen::Matrix3d j0 = pinocchio::rpy::computeRpyJacobian(rpy);\n  BOOST_CHECK(j0.isIdentity());\n  Eigen::Matrix3d jL = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL);\n  BOOST_CHECK(jL.isIdentity());\n  Eigen::Matrix3d jW = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::WORLD);\n  BOOST_CHECK(jW.isIdentity());\n  Eigen::Matrix3d jA = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL_WORLD_ALIGNED);\n  BOOST_CHECK(jA.isIdentity());\n\n  // Check correct identities between different versions\n  double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n  double p = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/M_PI)) - (M_PI/2);\n  double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n  rpy = Eigen::Vector3d(r, p, y);\n  Eigen::Matrix3d R = pinocchio::rpy::rpyToMatrix(rpy);\n  j0 = pinocchio::rpy::computeRpyJacobian(rpy);\n  jL = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL);\n  jW = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::WORLD);\n  jA = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL_WORLD_ALIGNED);\n  BOOST_CHECK(j0 == jL);\n  BOOST_CHECK(jW == jA);\n  BOOST_CHECK(jW.isApprox(R*jL));\n\n  // Check against analytical formulas \n  Eigen::Vector3d jL0Expected = Eigen::Vector3d::UnitX();\n  Eigen::Vector3d jL1Expected = Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()).toRotationMatrix().transpose().col(1);\n  Eigen::Vector3d jL2Expected = (Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY())\n                               * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX())\n                                ).toRotationMatrix().transpose().col(2);\n  BOOST_CHECK(jL.col(0).isApprox(jL0Expected));\n  BOOST_CHECK(jL.col(1).isApprox(jL1Expected));\n  BOOST_CHECK(jL.col(2).isApprox(jL2Expected));\n\n  Eigen::Vector3d jW0Expected = (Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ())\n                               * Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY())\n                                ).toRotationMatrix().col(0);\n  Eigen::Vector3d jW1Expected = Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ()).toRotationMatrix().col(1);\n  Eigen::Vector3d jW2Expected = Eigen::Vector3d::UnitZ();\n  BOOST_CHECK(jW.col(0).isApprox(jW0Expected));\n  BOOST_CHECK(jW.col(1).isApprox(jW1Expected));\n  BOOST_CHECK(jW.col(2).isApprox(jW2Expected));\n\n  // Check against finite differences\n  Eigen::Vector3d rpydot = Eigen::Vector3d::Random();\n  double const eps = 1e-7;\n  double const tol = 1e-5;\n\n  Eigen::Matrix3d dRdr = (pinocchio::rpy::rpyToMatrix(r + eps, p, y) - R) / eps;\n  Eigen::Matrix3d dRdp = (pinocchio::rpy::rpyToMatrix(r, p + eps, y) - R) / eps;\n  Eigen::Matrix3d dRdy = (pinocchio::rpy::rpyToMatrix(r, p, y + eps) - R) / eps;\n  Eigen::Matrix3d Rdot = dRdr * rpydot[0] + dRdp * rpydot[1] + dRdy * rpydot[2];\n\n  Eigen::Vector3d omegaL = jL * rpydot;\n  BOOST_CHECK(Rdot.isApprox(R * pinocchio::skew(omegaL), tol));\n\n  Eigen::Vector3d omegaW = jW * rpydot;\n  BOOST_CHECK(Rdot.isApprox(pinocchio::skew(omegaW) * R, tol));\n}\n\n\nBOOST_AUTO_TEST_CASE(test_computeRpyJacobianInverse)\n{\n  // Check correct identities between different versions\n  double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n  double p = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/M_PI)) - (M_PI/2);\n  p *= 0.999; // ensure we are not too close to a singularity\n  double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n  Eigen::Vector3d rpy(r, p, y);\n\n  Eigen::Matrix3d j0 = pinocchio::rpy::computeRpyJacobian(rpy);\n  Eigen::Matrix3d j0inv = pinocchio::rpy::computeRpyJacobianInverse(rpy);\n  BOOST_CHECK(j0inv.isApprox(j0.inverse()));\n\n  Eigen::Matrix3d jL = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL);\n  Eigen::Matrix3d jLinv = pinocchio::rpy::computeRpyJacobianInverse(rpy, pinocchio::LOCAL);\n  BOOST_CHECK(jLinv.isApprox(jL.inverse()));\n\n  Eigen::Matrix3d jW = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::WORLD);\n  Eigen::Matrix3d jWinv = pinocchio::rpy::computeRpyJacobianInverse(rpy, pinocchio::WORLD);\n  BOOST_CHECK(jWinv.isApprox(jW.inverse()));\n\n  Eigen::Matrix3d jA = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL_WORLD_ALIGNED);\n  Eigen::Matrix3d jAinv = pinocchio::rpy::computeRpyJacobianInverse(rpy, pinocchio::LOCAL_WORLD_ALIGNED);\n  BOOST_CHECK(jAinv.isApprox(jA.inverse()));\n}\n\n\nBOOST_AUTO_TEST_CASE(test_computeRpyJacobianTimeDerivative)\n{\n  // Check zero at zero velocity\n  double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n  double p = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/M_PI)) - (M_PI/2);\n  double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;\n  Eigen::Vector3d rpy(r, p, y);\n  Eigen::Vector3d rpydot(Eigen::Vector3d::Zero());\n  Eigen::Matrix3d dj0 = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot);\n  BOOST_CHECK(dj0.isZero());\n  Eigen::Matrix3d djL = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::LOCAL);\n  BOOST_CHECK(djL.isZero());\n  Eigen::Matrix3d djW = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::WORLD);\n  BOOST_CHECK(djW.isZero());\n  Eigen::Matrix3d djA = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::LOCAL_WORLD_ALIGNED);\n  BOOST_CHECK(djA.isZero());\n\n  // Check correct identities between different versions\n  rpydot = Eigen::Vector3d::Random();\n  dj0 = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot);\n  djL = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::LOCAL);\n  djW = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::WORLD);\n  djA = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::LOCAL_WORLD_ALIGNED);\n  BOOST_CHECK(dj0 == djL);\n  BOOST_CHECK(djW == djA);\n\n  Eigen::Matrix3d R = pinocchio::rpy::rpyToMatrix(rpy);\n  Eigen::Matrix3d jL = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL);\n  Eigen::Matrix3d jW = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::WORLD);\n  Eigen::Vector3d omegaL = jL * rpydot;\n  Eigen::Vector3d omegaW = jW * rpydot;\n  BOOST_CHECK(omegaW.isApprox(R*omegaL));\n  BOOST_CHECK(djW.isApprox(pinocchio::skew(omegaW)*R*jL + R*djL));\n  BOOST_CHECK(djW.isApprox(R*pinocchio::skew(omegaL)*jL + R*djL));\n\n  // Check against finite differences\n  double const eps = 1e-7;\n  double const tol = 1e-5;\n  Eigen::Vector3d rpyEps = rpy;\n\n  rpyEps[0] += eps;\n  Eigen::Matrix3d djLdr = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::LOCAL) - jL) / eps;\n  rpyEps[0] = rpy[0];\n  rpyEps[1] += eps;\n  Eigen::Matrix3d djLdp = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::LOCAL) - jL) / eps;\n  rpyEps[1] = rpy[1];\n  rpyEps[2] += eps;\n  Eigen::Matrix3d djLdy = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::LOCAL) - jL) / eps;\n  rpyEps[2] = rpy[2];\n  Eigen::Matrix3d djLf = djLdr * rpydot[0] + djLdp * rpydot[1] + djLdy * rpydot[2];\n  BOOST_CHECK(djL.isApprox(djLf, tol));\n\n  rpyEps[0] += eps;\n  Eigen::Matrix3d djWdr = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::WORLD) - jW) / eps;\n  rpyEps[0] = rpy[0];\n  rpyEps[1] += eps;\n  Eigen::Matrix3d djWdp = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::WORLD) - jW) / eps;\n  rpyEps[1] = rpy[1];\n  rpyEps[2] += eps;\n  Eigen::Matrix3d djWdy = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::WORLD) - jW) / eps;\n  rpyEps[2] = rpy[2];\n  Eigen::Matrix3d djWf = djWdr * rpydot[0] + djWdp * rpydot[1] + djWdy * rpydot[2];\n  BOOST_CHECK(djW.isApprox(djWf, tol));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0198b285b5cdcb13def0d778f145970266db7b30", "size": 11474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/rpy.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "unittest/rpy.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "unittest/rpy.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 42.3394833948, "max_line_length": 118, "alphanum_fraction": 0.6662018477, "num_tokens": 3993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.649619249606779}}
{"text": "#include \"problemes.h\"\n#include \"chiffres.h\"\n#include \"utilitaires.h\"\n#include \"mpz_nombre.h\"\n#include \"mpq_fraction.h\"\n\n#include <boost/range/adaptor/reversed.hpp>\n\nENREGISTRER_PROBLEME(65, \"Convergents of e\") {\n    // The square root of 2 can be written as an infinite continued fraction.\n    // \n    // The infinite continued fraction can be written, \u221a2 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a\n    // similar way, \u221a23 = [4;(1,3,1,8)].\n    //\n    // It turns out that the sequence of partial values of continued fractions for square roots provide the best rational\n    // approximations. Let us consider the convergents for \u221a2.\n    // \n    // Hence the sequence of the first ten convergents for \u221a2 are:\n    // \n    // 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ...\n    // What is most surprising is that the important mathematical constant,\n    // e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...].\n    // \n    // The first ten terms in the sequence of convergents for e are:\n    // \n    // 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ...\n    // The sum of digits in the numerator of the 10th convergent is 1+4+5+7=17.\n    // \n    // Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e.\n    std::vector<mpz_nombre> fraction_continue;\n    fraction_continue.emplace_back(2);\n    for (size_t n = 2; n < 101; n += 2) {\n        fraction_continue.emplace_back(1);\n        fraction_continue.emplace_back(n);\n        fraction_continue.emplace_back(1);\n    }\n    fraction_continue.resize(99);\n    mpq_fraction f(1);\n    for (const auto &p: boost::adaptors::reverse(fraction_continue)) f = p + 1 / f;\n\n    mpz_nombre resultat = f.numerateur().somme_chiffres();\n    return resultat.to_string();\n}\n", "meta": {"hexsha": "003ab106dc8c93022bc3ddddbaf5593266c7cd60", "size": 1802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme065.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme065.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme0xx/probleme065.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9545454545, "max_line_length": 121, "alphanum_fraction": 0.6498335183, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6495865741958006}}
{"text": "/*\r\n * Copyright 2012 Karsten Ahnert\r\n * Copyright 2012 Mario Mulansky\r\n *\r\n * Distributed under the Boost Software License, Version 1.0.\r\n * (See accompanying file LICENSE_1_0.txt or\r\n * copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <utility>\r\n#include \"time.h\"\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n#include <boost/phoenix/phoenix.hpp>\r\n#include <boost/numeric/mtl/mtl.hpp>\r\n\r\n#include <boost/numeric/odeint/external/mtl4/implicit_euler_mtl4.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\nnamespace phoenix = boost::phoenix;\r\n\r\n\r\n\r\ntypedef mtl::dense_vector< double > vec_mtl4;\r\ntypedef mtl::compressed2D< double > mat_mtl4;\r\n\r\ntypedef boost::numeric::ublas::vector< double > vec_ublas;\r\ntypedef boost::numeric::ublas::matrix< double > mat_ublas;\r\n\r\n\r\n// two systems defined 1 & 2 both are mostly sparse with the number of element variable\r\nstruct system1_mtl4\r\n{\r\n\r\n    void operator()( const vec_mtl4 &x , vec_mtl4 &dxdt , double t )\r\n    {\r\n        int size = mtl::size(x);\r\n\r\n        dxdt[ 0 ] = -0.06*x[0];\r\n\r\n        for (int i =1; i< size ; ++i){\r\n\r\n            dxdt[ i ] = 4.2*x[i-1]-2.2*x[i]*x[i];\r\n        }\r\n\r\n    }\r\n};\r\n\r\nstruct jacobi1_mtl4\r\n{\r\n    void operator()( const vec_mtl4 &x , mat_mtl4 &J , const double &t )\r\n    {\r\n        int size = mtl::size(x);\r\n        mtl::matrix::inserter<mat_mtl4> ins(J);\r\n\r\n        ins[0][0]=-0.06;\r\n\r\n        for (int i =1; i< size ; ++i)\r\n        {\r\n            ins[i][i-1] = + 4.2;\r\n            ins[i][i] = -4.2*x[i];\r\n        }\r\n    }\r\n};\r\n\r\n\r\n\r\nstruct system1_ublas\r\n{\r\n\r\n    void operator()( const vec_ublas &x , vec_ublas &dxdt , double t )\r\n    {\r\n        int size = x.size();\r\n\r\n        dxdt[ 0 ] = -0.06*x[0];\r\n\r\n        for (int i =1; i< size ; ++i){\r\n\r\n            dxdt[ i ] = 4.2*x[i-1]-2.2*x[i]*x[i];\r\n        }\r\n\r\n    }\r\n};\r\n\r\nstruct jacobi1_ublas\r\n{\r\n    void operator()( const vec_ublas &x , mat_ublas &J , const double &t )\r\n    {\r\n        int size = x.size();\r\n// mtl::matrix::inserter<mat_mtl4> ins(J);\r\n\r\n        J(0,0)=-0.06;\r\n\r\n        for (int i =1; i< size ; ++i){\r\n//ins[i][0]=120.0*x[i];\r\n            J(i,i-1) = + 4.2;\r\n            J(i,i) = -4.2*x[i];\r\n\r\n        }\r\n    }\r\n};\r\n\r\nstruct system2_mtl4\r\n{\r\n\r\n    void operator()( const vec_mtl4 &x , vec_mtl4 &dxdt , double t )\r\n    {\r\n        int size = mtl::size(x);\r\n\r\n\r\n        for (int i =0; i< size/5 ; i+=5){\r\n\r\n            dxdt[ i ] = -0.5*x[i];\r\n            dxdt[i+1]= +25*x[i+1]*x[i+2]-740*x[i+3]*x[i+3]+4.2e-2*x[i];\r\n            dxdt[i+2]= +25*x[i]*x[i]-740*x[i+3]*x[i+3];\r\n            dxdt[i+3]= -25*x[i+1]*x[i+2]+740*x[i+3]*x[i+3];\r\n            dxdt[i+4] = 0.250*x[i]*x[i+1]-44.5*x[i+3];\r\n\r\n        }\r\n\r\n    }\r\n};\r\n\r\nstruct jacobi2_mtl4\r\n{\r\n    void operator()( const vec_mtl4 &x , mat_mtl4 &J , const double &t )\r\n    {\r\n        int size = mtl::size(x);\r\n        mtl::matrix::inserter<mat_mtl4> ins(J);\r\n\r\n        for (int i =0; i< size/5 ; i+=5){\r\n\r\n            ins[ i ][i] = -0.5;\r\n            ins[i+1][i+1]=25*x[i+2];\r\n            ins[i+1][i+2] = 25*x[i+1];\r\n            ins[i+1][i+3] = -740*2*x[i+3];\r\n            ins[i+1][i] =+4.2e-2;\r\n\r\n            ins[i+2][i]= 50*x[i];\r\n            ins[i+2][i+3]= -740*2*x[i+3];\r\n            ins[i+3][i+1] = -25*x[i+2];\r\n            ins[i+3][i+2] = -25*x[i+1];\r\n            ins[i+3][i+3] = +740*2*x[i+3];\r\n            ins[i+4][i] = 0.25*x[i+1];\r\n            ins[i+4][i+1] =0.25*x[i];\r\n            ins[i+4][i+3]=-44.5;\r\n\r\n\r\n\r\n        }\r\n    }\r\n};\r\n\r\n\r\n\r\nstruct system2_ublas\r\n{\r\n\r\n    void operator()( const vec_ublas &x , vec_ublas &dxdt , double t )\r\n    {\r\n        int size = x.size();\r\n        for (int i =0; i< size/5 ; i+=5){\r\n\r\n            dxdt[ i ] = -4.2e-2*x[i];\r\n            dxdt[i+1]= +25*x[i+1]*x[i+2]-740*x[i+3]*x[i+3]+4.2e-2*x[i];\r\n            dxdt[i+2]= +25*x[i]*x[i]-740*x[i+3]*x[i+3];\r\n            dxdt[i+3]= -25*x[i+1]*x[i+2]+740*x[i+3]*x[i+3];\r\n            dxdt[i+4] = 0.250*x[i]*x[i+1]-44.5*x[i+3];\r\n\r\n        }\r\n\r\n    }\r\n};\r\n\r\nstruct jacobi2_ublas\r\n{\r\n    void operator()( const vec_ublas &x , mat_ublas &J , const double &t )\r\n    {\r\n        int size = x.size();\r\n\r\n        for (int i =0; i< size/5 ; i+=5){\r\n\r\n            J(i ,i) = -4.2e-2;\r\n            J(i+1,i+1)=25*x[i+2];\r\n            J(i+1,i+2) = 25*x[i+1];\r\n            J(i+1,i+3) = -740*2*x[i+3];\r\n            J(i+1,i) =+4.2e-2;\r\n\r\n            J(i+2,i)= 50*x[i];\r\n            J(i+2,i+3)= -740*2*x[i+3];\r\n            J(i+3,i+1) = -25*x[i+2];\r\n            J(i+3,i+2) = -25*x[i+1];\r\n            J(i+3,i+3) = +740*2*x[i+3];\r\n            J(i+4,i) = 0.25*x[i+1];\r\n            J(i+4,i+1) =0.25*x[i];\r\n            J(i+4,i+3)=-44.5;\r\n\r\n\r\n\r\n        }\r\n\r\n\r\n    }\r\n};\r\n\r\n\r\n\r\n\r\nvoid testRidiculouslyMassiveArray( int size )\r\n{\r\n    typedef boost::numeric::odeint::implicit_euler_mtl4 < double > mtl4stepper;\r\n    typedef boost::numeric::odeint::implicit_euler< double > booststepper;\r\n\r\n    vec_mtl4 x(size , 0.0);\r\n    x[0]=1;\r\n\r\n\r\n    double dt = 0.02;\r\n    double endtime = 10.0;\r\n\r\n    clock_t tstart_mtl4 = clock();\r\n    size_t num_of_steps_mtl4 = integrate_const(\r\n        mtl4stepper() ,\r\n        make_pair( system1_mtl4() , jacobi1_mtl4() ) ,\r\n        x , 0.0 , endtime , dt  );\r\n    clock_t tend_mtl4 = clock() ;\r\n\r\n    clog << x[0] << endl;\r\n    clog << num_of_steps_mtl4 << \" time elapsed: \" << (double)(tend_mtl4-tstart_mtl4 )/CLOCKS_PER_SEC << endl;\r\n\r\n    vec_ublas x_ublas(size , 0.0);\r\n    x_ublas[0]=1;\r\n\r\n    clock_t tstart_boost = clock();\r\n    size_t num_of_steps_ublas = integrate_const(\r\n        booststepper() ,\r\n        make_pair( system1_ublas() , jacobi1_ublas() ) ,\r\n        x_ublas , 0.0 , endtime , dt  );\r\n    clock_t tend_boost = clock() ;\r\n    \r\n    clog << x_ublas[0] << endl;\r\n    clog << num_of_steps_ublas << \" time elapsed: \" << (double)(tend_boost-tstart_boost)/CLOCKS_PER_SEC<< endl;\r\n\r\n    clog << \"dt_ublas/dt_mtl4 = \" << (double)( tend_boost-tstart_boost )/( tend_mtl4-tstart_mtl4 ) << endl << endl;\r\n    return ;\r\n}\r\n\r\n\r\n\r\nvoid testRidiculouslyMassiveArray2( int size )\r\n{\r\n    typedef boost::numeric::odeint::implicit_euler_mtl4 < double > mtl4stepper;\r\n    typedef boost::numeric::odeint::implicit_euler< double > booststepper;\r\n\r\n\r\n    vec_mtl4 x(size , 0.0);\r\n    x[0]=100;\r\n\r\n\r\n    double dt = 0.01;\r\n    double endtime = 10.0;\r\n\r\n    clock_t tstart_mtl4 = clock();\r\n    size_t num_of_steps_mtl4 = integrate_const(\r\n        mtl4stepper() ,\r\n        make_pair( system1_mtl4() , jacobi1_mtl4() ) ,\r\n        x , 0.0 , endtime , dt );\r\n\r\n\r\n    clock_t tend_mtl4 = clock() ;\r\n    \r\n    clog << x[0] << endl;\r\n    clog << num_of_steps_mtl4 << \" time elapsed: \" << (double)(tend_mtl4-tstart_mtl4 )/CLOCKS_PER_SEC << endl;\r\n\r\n    vec_ublas x_ublas(size , 0.0);\r\n    x_ublas[0]=100;\r\n\r\n    clock_t tstart_boost = clock();\r\n    size_t num_of_steps_ublas = integrate_const(\r\n        booststepper() ,\r\n        make_pair( system1_ublas() , jacobi1_ublas() ) ,\r\n        x_ublas , 0.0 , endtime , dt  );\r\n\r\n\r\n    clock_t tend_boost = clock() ;\r\n    \r\n    clog << x_ublas[0] << endl;\r\n    clog << num_of_steps_ublas << \" time elapsed: \" << (double)(tend_boost-tstart_boost)/CLOCKS_PER_SEC<< endl;\r\n\r\n    clog << \"dt_ublas/dt_mtl4 = \" << (double)( tend_boost-tstart_boost )/( tend_mtl4-tstart_mtl4 ) << endl << endl;\r\n    return ;\r\n}\r\n\r\n\r\n\r\n \r\nint main( int argc , char **argv )\r\n{\r\n    std::vector< size_t > length;\r\n    length.push_back( 8 );\r\n    length.push_back( 16 );\r\n    length.push_back( 32 );\r\n    length.push_back( 64 );\r\n    length.push_back( 128 );\r\n    length.push_back( 256 );\r\n\r\n    for( size_t i=0 ; i<length.size() ; ++i )\r\n    {\r\n        clog << \"Testing with size \" << length[i] << endl;\r\n        testRidiculouslyMassiveArray( length[i] );\r\n    }\r\n    clog << endl << endl;\r\n\r\n    for( size_t i=0 ; i<length.size() ; ++i )\r\n    {\r\n        clog << \"Testing with size \" << length[i] << endl;\r\n        testRidiculouslyMassiveArray2( length[i] );\r\n    }\r\n}\r\n", "meta": {"hexsha": "0e4297e409ff72212033133f1b2100d2587795a8", "size": 7940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/mtl/implicit_euler_mtl.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/mtl/implicit_euler_mtl.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/mtl/implicit_euler_mtl.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 24.4307692308, "max_line_length": 116, "alphanum_fraction": 0.5055415617, "num_tokens": 2678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6495862382309783}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n#include <numeric>\n\ntypedef unsigned long long nombre;\n\nENREGISTRER_PROBLEME(42, \"Coded triangle numbers\") {\n    // The nth term of the sequence of triangle numbers is given by, tn = \u00bdn(n+1); so the first ten triangle numbers are:\n    //\n    //                                      1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...\n    //\n    // By converting each letter in a word to a number corresponding to its alphabetical position and adding these values\n    // we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle\n    // number then we shall call the word a triangle word.\n    //\n    // Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?\n    std::ifstream ifs(\"data/p042_words.txt\");\n    std::string entree;\n    ifs >> entree;\n    std::vector<std::string> names;\n    boost::split(names, entree, boost::is_any_of(\",\"));\n\n    std::set<nombre> triangle;\n    for (nombre n = 1; n < 50; ++n)\n        triangle.insert(n * (n + 1) / 2);\n\n    nombre resultat = 0;\n    for (const auto &name: names) {\n        nombre score = std::accumulate(name.begin(), name.end(), 0ULL, [](const nombre &n, char c) {\n            if (c != '\"')\n                return n + 1 + static_cast<nombre>(c - 'A');\n            return n;\n        });\n        if (triangle.find(score) != triangle.end())\n            ++resultat;\n    }\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "b0b0cf8508a8e6d03577803fffe9d15f71ffffcf", "size": 1611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme042.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme042.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme0xx/probleme042.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3571428571, "max_line_length": 164, "alphanum_fraction": 0.6045934202, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6495862358897504}}
{"text": "//\n//  gmatrix9float.cpp\n//  GCommon\n//\n//  Created by David Coen on 2011 06 01\n//  Copyright Pleasure seeking morons 2011. All rights reserved.\n//\n\n#include \"gmatrix9float.h\"\n\n#include \"gvector3float.h\"\n#include \"gmathmatrix.h\"\n#include \"gmath.h\"\n\n#include <boost/swap.hpp>\n\n#define DSC_INLINE_MATRIX_MUL\n\n/*static*/ const GMatrix9Float GMatrix9Float::sIdentity(1.0F, 0.0F, 0.0F,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  0.0F, 1.0F, 0.0F,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  0.0F, 0.0F, 1.0F);\n\n\n//constructors\nGMatrix9Float::GMatrix9Float(const GR32 in_data_0_0, const GR32 in_data_0_1, const GR32 in_data_0_2,\n\tconst GR32 in_data_1_0, const GR32 in_data_1_1, const GR32 in_data_1_2,\n\tconst GR32 in_data_2_0, const GR32 in_data_2_1, const GR32 in_data_2_2\n\t)\n{\n\tSetData(in_data_0_0, in_data_0_1, in_data_0_2,\n\t\tin_data_1_0, in_data_1_1, in_data_1_2,\n\t\tin_data_2_0, in_data_2_1, in_data_2_2\n\t\t);\n\treturn;\n}\nGMatrix9Float::GMatrix9Float(const GR32* const in_data)\n{\n\tfor (GS32 index = 0; index < 9; ++index)\n\t{\n\t\tm_data[index] = in_data[index];\n\t}\n\treturn;\n\n}\n\nGMatrix9Float::GMatrix9Float(const GMatrix9Float& in_src)\n{\n\t(*this) = in_src;\n\treturn;\n}\n\nGMatrix9Float::~GMatrix9Float()\n{\n\treturn;\n}\n\t\n//operators\nconst GMatrix9Float& GMatrix9Float::operator=(const GMatrix9Float& in_rhs)\n{\n\tfor (GS32 index = 0; index < 9; ++index)\n\t{\n\t\tm_data[index] = in_rhs.m_data[index];\n\t}\n\treturn (*this);\n}\n\n//public methods\nGMatrix9Float& GMatrix9Float::TransposeSelf()\n{\n\tstd::swap(m_0_1, m_1_0);\n\tstd::swap(m_0_2, m_2_0);\n\tstd::swap(m_1_2, m_2_1);\n\n\treturn (*this);\n}\n\nconst GMatrix9Float GMatrix9Float::ReturnInverse()const\n{\n\tGMatrix9Float result;\n\tGMathMatrix<GR32>::Inverse4(&result.m_data[0], &m_data[0]);\n\n\treturn result;\n}\n\n//public accessors\nvoid GMatrix9Float::SetData(const GR32 in_data_0_0, const GR32 in_data_0_1, const GR32 in_data_0_2,\n\tconst GR32 in_data_1_0, const GR32 in_data_1_1, const GR32 in_data_1_2,\n\tconst GR32 in_data_2_0, const GR32 in_data_2_1, const GR32 in_data_2_2\n\t)\n{\n\tm_0_0 = in_data_0_0;\n\tm_1_0 = in_data_1_0;\n\tm_2_0 = in_data_2_0;\n\n\tm_0_1 = in_data_0_1;\n\tm_1_1 = in_data_1_1;\n\tm_2_1 = in_data_2_1;\n\n\tm_0_2 = in_data_0_2;\n\tm_1_2 = in_data_1_2;\n\tm_2_2 = in_data_2_2;\n\n\treturn;\n}\n\nconst GVector3Float GMatrix9Float::GetAt()const\n{\n\tconst GVector3Float result(\n\t\tm_0_2,\n\t\tm_1_2,\n\t\tm_2_2\n\t\t);\n\treturn result;\n}\n\nconst GVector3Float GMatrix9Float::GetUp()const\n{\n\tconst GVector3Float result(\n\t\tm_0_1,\n\t\tm_1_1,\n\t\tm_2_1\n\t\t);\n\treturn result;\n}\n\n//global operators\nconst GMatrix9Float operator*(const GMatrix9Float& in_lhs, const GMatrix9Float& in_rhs)\n{\n\tGR32 value[9];\n#ifdef DSC_INLINE_MATRIX_MUL\n\tconst GR32* const lhsData = in_lhs.GetData();\n\tconst GR32* const rhsData = in_rhs.GetData();\n\tvalue[ 0] = (lhsData[ 0] * rhsData[ 0]) + (lhsData[ 1] * rhsData[ 3]) + (lhsData[ 2] * rhsData[ 6]);\n\tvalue[ 1] = (lhsData[ 0] * rhsData[ 1]) + (lhsData[ 1] * rhsData[ 4]) + (lhsData[ 2] * rhsData[ 7]);\n\tvalue[ 2] = (lhsData[ 0] * rhsData[ 2]) + (lhsData[ 1] * rhsData[ 5]) + (lhsData[ 2] * rhsData[ 8]);\n\n\tvalue[ 3] = (lhsData[ 3] * rhsData[ 0]) + (lhsData[ 4] * rhsData[ 3]) + (lhsData[ 5] * rhsData[ 6]);\n\tvalue[ 4] = (lhsData[ 3] * rhsData[ 1]) + (lhsData[ 4] * rhsData[ 4]) + (lhsData[ 5] * rhsData[ 7]);\n\tvalue[ 5] = (lhsData[ 3] * rhsData[ 2]) + (lhsData[ 4] * rhsData[ 5]) + (lhsData[ 5] * rhsData[ 8]);\n\n\tvalue[ 6] = (lhsData[ 6] * rhsData[ 0]) + (lhsData[ 7] * rhsData[ 3]) + (lhsData[ 8] * rhsData[ 6]);\n\tvalue[ 7] = (lhsData[ 6] * rhsData[ 1]) + (lhsData[ 7] * rhsData[ 4]) + (lhsData[ 8] * rhsData[ 7]);\n\tvalue[ 8] = (lhsData[ 6] * rhsData[ 2]) + (lhsData[ 7] * rhsData[ 5]) + (lhsData[ 8] * rhsData[ 8]);\n#else\n\tGMathMatrix<GR32>::MatrixMul( \n\t\tin_lhs.GetData(),\n\t\tin_rhs.GetData(), \n\t\t3, \n\t\t3, \n\t\t3, \n\t\t&value[0]\n\t\t);\n#endif\n\treturn GMatrix9Float(&value[0]);\n}\n\nconst GVector3Float operator*(const GVector3Float& in_lhs, const GMatrix9Float& in_rhs)\n{\n\tGR32 value[3];\n#ifdef DSC_INLINE_MATRIX_MUL\n\tconst GR32* const lhsData = in_lhs.GetData();\n\tconst GR32* const rhsData = in_rhs.GetData();\n\tvalue[ 0] = (lhsData[ 0] * rhsData[ 0]) + (lhsData[ 1] * rhsData[ 3]) + (lhsData[ 2] * rhsData[ 6]);\n\tvalue[ 1] = (lhsData[ 0] * rhsData[ 1]) + (lhsData[ 1] * rhsData[ 4]) + (lhsData[ 2] * rhsData[ 7]);\n\tvalue[ 2] = (lhsData[ 0] * rhsData[ 2]) + (lhsData[ 1] * rhsData[ 5]) + (lhsData[ 2] * rhsData[ 8]);\n#else\n\tGMathMatrix<GR32>::MatrixMul( \n\t\tin_lhs.GetData(),\n\t\tin_rhs.GetData(), \n\t\t3, \n\t\t1, \n\t\t3, \n\t\t&value[0]\n\t\t);\n#endif\n\treturn GVector3Float(value[0], value[1], value[2]);\n}\n\nconst GMatrix9Float& operator*=(GMatrix9Float& in_lhs, const GMatrix9Float& in_rhs)\n{\n\tin_lhs = (in_lhs * in_rhs);\n\treturn in_lhs;\n}\t\n\n/*\n  from _Mathematics for computer graphics p.171\n mapping a pair of vectors onto another pair, u,x being one pair, a,y being another of unit vectors at same angle\n u.x = a.y = cos(\\), with sin(\\) != 0\n a roation matrix sending u,x to a,y given by\n               a \n M = [u v w ][ b ]\n               c\n d = | x * u | = | y * a | = | sin(\\) |\n if 90deg = u to x, cos(\\) = 0, sin(\\) = 1\n v = ( x * u ) / d\n b = ( y * a ) / d\n w = ( x - u( cos(\\) ) ) / d\n c = ( y - a( cos(\\) ) ) / d\n*/\nconst GMatrix9Float GMatrix9FloatConstructAtUp( \n\tconst GVector3Float& in_targetAt, \n\tconst GVector3Float& in_targetUp,\n\tconst GVector3Float& in_baseAt, \n\tconst GVector3Float& in_baseUp\n\t)\n{\n\tGMatrix9Float returnMatrix;\n\n\tconst GVector3Float crossBaseUpAt = CrossProduct(in_baseUp, in_baseAt);\n\tconst GVector3Float crossTargetUpAt = CrossProduct(in_targetUp, in_targetAt);\n\n\treturn GMatrix9Float(\n\t\t(in_baseAt.m_x * in_targetAt.m_x) + (crossBaseUpAt.m_x * crossTargetUpAt.m_x) + (in_baseUp.m_x * in_targetUp.m_x),\n\t\t(in_baseAt.m_y * in_targetAt.m_x) + (crossBaseUpAt.m_y * crossTargetUpAt.m_x) + (in_baseUp.m_y * in_targetUp.m_x),\n\t\t(in_baseAt.m_z * in_targetAt.m_x) + (crossBaseUpAt.m_z * crossTargetUpAt.m_x) + (in_baseUp.m_z * in_targetUp.m_x),\n\n\t\t(in_baseAt.m_x * in_targetAt.m_y) + (crossBaseUpAt.m_x * crossTargetUpAt.m_y) + (in_baseUp.m_x * in_targetUp.m_y),\n\t\t(in_baseAt.m_y * in_targetAt.m_y) + (crossBaseUpAt.m_y * crossTargetUpAt.m_y) + (in_baseUp.m_y * in_targetUp.m_y),\n\t\t(in_baseAt.m_z * in_targetAt.m_y) + (crossBaseUpAt.m_z * crossTargetUpAt.m_y) + (in_baseUp.m_z * in_targetUp.m_y),\n\n\t\t(in_baseAt.m_x * in_targetAt.m_z) + (crossBaseUpAt.m_x * crossTargetUpAt.m_z) + (in_baseUp.m_x * in_targetUp.m_z),\n\t\t(in_baseAt.m_y * in_targetAt.m_z) + (crossBaseUpAt.m_y * crossTargetUpAt.m_z) + (in_baseUp.m_y * in_targetUp.m_z),\n\t\t(in_baseAt.m_z * in_targetAt.m_z) + (crossBaseUpAt.m_z * crossTargetUpAt.m_z) + (in_baseUp.m_z * in_targetUp.m_z)\n\t\t);\n}\n\n/*\n  http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToMatrix/index.htm\n*/\nconst GMatrix9Float GMatrix9FloatConstructAxisAngle(const GVector3Float& in_axis, const GR32 in_angleRad)\n{\n\tconst GVector3Float localAxis = Normalise(in_axis);\n\tconst GR32 axis_x = localAxis.m_x;\n\tconst GR32 axis_y = localAxis.m_y;\n\tconst GR32 axis_z = localAxis.m_z;\n\n\tconst GR32 c = GMath::Cos( in_angleRad );\n\tconst GR32 s = GMath::Sin( in_angleRad );\n\tconst GR32 t = 1.0F - c;\n\n\tconst GR32 tmp1_01 = axis_x * axis_y * t;\n\tconst GR32 tmp2_01 = axis_z * s;\n\n\tconst GR32 tmp1_02 = axis_x * axis_z * t;\n\tconst GR32 tmp2_02 = axis_y * s;\n  \n\tconst GR32 tmp1_21 = axis_y * axis_z * t;\n\tconst GR32 tmp2_21 = axis_x * s;\n\n\treturn GMatrix9Float(\n\t\tc + axis_x * axis_x * t, tmp1_01 - tmp2_01, tmp1_02 + tmp2_02,\n\t\ttmp1_01 + tmp2_01, c + axis_y * axis_y * t, tmp1_21 - tmp2_21,\n\t\ttmp1_02 - tmp2_02, tmp1_21 + tmp2_21, c + axis_z * axis_z * t\n\t\t);\n}\n", "meta": {"hexsha": "30ab6f6cd8914f24b1b694af60936e1e91f583d1", "size": 7476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gcommon/source/gmatrix9float.cpp", "max_stars_repo_name": "DavidCoenFish/ancient-code-0", "max_stars_repo_head_hexsha": "243fb47b9302a77f9b9392b6e3f90bba2ef3c228", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gcommon/source/gmatrix9float.cpp", "max_issues_repo_name": "DavidCoenFish/ancient-code-0", "max_issues_repo_head_hexsha": "243fb47b9302a77f9b9392b6e3f90bba2ef3c228", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gcommon/source/gmatrix9float.cpp", "max_forks_repo_name": "DavidCoenFish/ancient-code-0", "max_forks_repo_head_hexsha": "243fb47b9302a77f9b9392b6e3f90bba2ef3c228", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.203125, "max_line_length": 116, "alphanum_fraction": 0.6775013376, "num_tokens": 2877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6495862235078762}}
{"text": "#include <bundle/error/projection_errors.h>\n#include <gmock/gmock.h>\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/AutoDiff>\n\nclass ReprojectionError2DFixtureBase : public ::testing::Test {\n public:\n  typedef Eigen::AutoDiffScalar<Eigen::VectorXd> AScalar;\n  ReprojectionError2DFixtureBase() { observed << 0.5, 0.5; }\n\n  constexpr static int size_residual = 2;\n  constexpr static int size_point = 3;\n  constexpr static int size_rt = 6;\n\n  Vec2d observed;\n  double scale{0.1};\n  const double point[size_point] = {1.0, 2.0, 3.0};\n\n  AScalar residual_adiff[size_residual];\n  AScalar point_adiff[size_point];\n\n  double residuals[size_residual];\n  double jac_point[size_residual * size_point];\n};\n\nclass ReprojectionError2DFixture : public ReprojectionError2DFixtureBase {\n public:\n  void SetupADiff(int size, const double* camera, AScalar* camera_adiff) {\n    const int total_size = size_point + size_rt + size_rt + size;\n    for (int i = 0; i < size_point; ++i) {\n      point_adiff[i].value() = point[i];\n      point_adiff[i].derivatives() = VecXd::Unit(total_size, i);\n    }\n    for (int i = 0; i < size_rt; ++i) {\n      rt_instance_adiff[i].value() = rt_instance[i];\n      rt_instance_adiff[i].derivatives() =\n          VecXd::Unit(total_size, size_point + i);\n    }\n    for (int i = 0; i < size_rt; ++i) {\n      rt_camera_adiff[i].value() = rt_camera[i];\n      rt_camera_adiff[i].derivatives() =\n          VecXd::Unit(total_size, size_point + size_rt + i);\n    }\n    for (int i = 0; i < size; ++i) {\n      camera_adiff[i].value() = camera[i];\n      camera_adiff[i].derivatives() =\n          VecXd::Unit(total_size, size_point + size_rt + size_rt + i);\n    }\n  }\n\n  void CheckJacobians(int size, const double* jac_camera) {\n    const double eps = 1e-14;\n    for (int i = 0; i < size_residual; ++i) {\n      for (int j = 0; j < size; ++j) {\n        ASSERT_NEAR(\n            residual_adiff[i].derivatives()(size_point + size_rt + size_rt + j),\n            jac_camera[i * size + j], eps);\n      }\n    }\n    for (int i = 0; i < size_residual; ++i) {\n      for (int j = 0; j < size_point; ++j) {\n        ASSERT_NEAR(residual_adiff[i].derivatives()(j),\n                    jac_point[i * size_point + j], eps);\n      }\n    }\n    for (int i = 0; i < size_residual; ++i) {\n      for (int j = 0; j < size_rt; ++j) {\n        ASSERT_NEAR(residual_adiff[i].derivatives()(size_point + j),\n                    jac_rt_instance[i * size_rt + j], eps);\n      }\n    }\n    for (int i = 0; i < size_residual; ++i) {\n      for (int j = 0; j < size_rt; ++j) {\n        ASSERT_NEAR(residual_adiff[i].derivatives()(size_point + size_rt + j),\n                    jac_rt_camera[i * size_rt + j], eps);\n      }\n    }\n  }\n\n  template <int N>\n  void RunTest(const geometry::ProjectionType& type, const double* camera) {\n    constexpr int size = N;\n\n    // Autodiff-ed version will be used as reference/expected values\n    AScalar camera_adiff[size];\n    SetupADiff(size, &camera[0], &camera_adiff[0]);\n    bundle::ReprojectionError2D autodiff(type, observed, scale);\n    autodiff(camera_adiff, rt_instance_adiff, rt_camera_adiff, point_adiff,\n             residual_adiff);\n\n    // We test for analytic evaluation\n    double jac_camera[size_residual * size];\n    const double* params[] = {camera, rt_camera, rt_instance, point};\n    double* jacobians[] = {jac_camera, jac_rt_instance, jac_rt_camera,\n                           jac_point};\n    bundle::ReprojectionError2DAnalytic<size> analytic(type, observed, scale);\n    analytic.Evaluate(params, residuals, &jacobians[0]);\n\n    // Check\n    CheckJacobians(size, jac_camera);\n  }\n\n  const double rt_instance[size_rt] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6};\n  AScalar rt_instance_adiff[size_rt];\n  double jac_rt_instance[size_residual * size_rt];\n\n  const double rt_camera[size_rt] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6};\n  AScalar rt_camera_adiff[size_rt];\n  double jac_rt_camera[size_residual * size_rt];\n};\n\nTEST_F(ReprojectionError2DFixture, BrownAnalyticErrorEvaluatesOK) {\n  constexpr int size = 9;\n\n  // focal, ar, cx, cy, k1, k2, k3, p1, p2\n  constexpr std::array<double, size> camera{0.3,   1.0,   0.001,  -0.02, 0.1,\n                                            -0.03, 0.001, -0.005, 0.001};\n  RunTest<size>(geometry::ProjectionType::BROWN, &camera[0]);\n}\n\nTEST_F(ReprojectionError2DFixture, PerspectiveAnalyticErrorEvaluatesOK) {\n  constexpr int size = 3;\n\n  // focal, k1, k2\n  constexpr std::array<double, size> camera{0.3, 0.1, -0.03};\n  RunTest<size>(geometry::ProjectionType::PERSPECTIVE, &camera[0]);\n}\n\nTEST_F(ReprojectionError2DFixture, FisheyeAnalyticErrorEvaluatesOK) {\n  constexpr int size = 3;\n\n  // focal, k1, k2, k3\n  constexpr std::array<double, size> camera{0.3, 0.1, -0.03};\n  RunTest<size>(geometry::ProjectionType::FISHEYE, &camera[0]);\n}\n\nTEST_F(ReprojectionError2DFixture, FisheyeOpencvAnalyticErrorEvaluatesOK) {\n  constexpr int size = 8;\n\n  // focal, ar, cx, cy, k1, k2, k3, k4\n  constexpr std::array<double, size> camera{0.3, 1.0,   0.001, -0.02,\n                                            0.1, -0.03, 0.001, -0.005};\n  RunTest<size>(geometry::ProjectionType::FISHEYE_OPENCV, &camera[0]);\n}\n\nTEST_F(ReprojectionError2DFixture, Fisheye62AnalyticErrorEvaluatesOK) {\n  constexpr int size = 12;\n\n  // focal, ar, cx, cy, k1, k2, k3, k4, k5, k6, p1, p2\n  constexpr std::array<double, size> camera{0.3,  1.0,   0.001, -0.02,\n                                            0.1,  -0.03, 0.001, -0.005,\n                                            0.01, 0.006, 0.02,  0.003};\n  RunTest<size>(geometry::ProjectionType::FISHEYE62, &camera[0]);\n}\n\nTEST_F(ReprojectionError2DFixture, Fisheye624AnalyticErrorEvaluatesOK) {\n  constexpr int size = 16;\n\n  // focal, ar, cx, cy, k1, k2, k3, k4, k5, k6, p1, p2, s0, s1, s2, s3\n  constexpr std::array<double, size> camera{0.3,  1.0,   0.001, -0.02,\n                                            0.1,  -0.03, 0.001, -0.005,\n                                            0.01, 0.006, 0.02,  0.003,\n                                            0.001, -0.009, -0.01, 0.03};\n  RunTest<size>(geometry::ProjectionType::FISHEYE624, &camera[0]);\n}\n\nTEST_F(ReprojectionError2DFixture, DualAnalyticErrorEvaluatesOK) {\n  constexpr int size = 4;\n\n  // transtion, focal, k1, k2\n  constexpr std::array<double, size> camera{0.5, 0.3, 0.1, -0.03};\n  RunTest<size>(geometry::ProjectionType::DUAL, &camera[0]);\n}\n\nclass ReprojectionError3DFixture : public ::testing::Test {\n public:\n  static constexpr int size = 3;\n\n  typedef Eigen::AutoDiffScalar<Eigen::VectorXd> AScalar;\n  ReprojectionError3DFixture() { observed << 0.5, 0.5; }\n\n  void SetupADiff() {\n    const int total_size = size_point + size_rt + size_rt;\n    for (int i = 0; i < size_point; ++i) {\n      point_adiff[i].value() = point[i];\n      point_adiff[i].derivatives() = VecXd::Unit(total_size, i);\n    }\n    for (int i = 0; i < size_rt; ++i) {\n      rt_instance_adiff[i].value() = rt_instance[i];\n      rt_instance_adiff[i].derivatives() =\n          VecXd::Unit(total_size, size_point + i);\n    }\n    for (int i = 0; i < size_rt; ++i) {\n      rt_camera_adiff[i].value() = rt_camera[i];\n      rt_camera_adiff[i].derivatives() =\n          VecXd::Unit(total_size, size_point + size_rt + i);\n    }\n  }\n\n  void CheckJacobians() {\n    const double eps = 1e-14;\n    for (int i = 0; i < size; ++i) {\n      for (int j = 0; j < size_point; ++j) {\n        ASSERT_NEAR(residual_adiff[i].derivatives()(j),\n                    jac_point[i * size_point + j], eps);\n      }\n    }\n    for (int i = 0; i < size; ++i) {\n      for (int j = 0; j < size_rt; ++j) {\n        ASSERT_NEAR(residual_adiff[i].derivatives()(size_point + j),\n                    jac_instance_rt[i * size_rt + j], eps);\n      }\n    }\n    for (int i = 0; i < size; ++i) {\n      for (int j = 0; j < size_rt; ++j) {\n        ASSERT_NEAR(residual_adiff[i].derivatives()(size_point + size_rt + j),\n                    jac_camera_rt[i * size_rt + j], eps);\n      }\n    }\n  }\n\n  constexpr static int size_point = 3;\n  constexpr static int size_rt = 6;\n\n  Vec2d observed;\n  double scale{0.1};\n  const double point[size_point] = {1.0, 2.0, 3.0};\n  const double rt_instance[size_rt] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6};\n  const double rt_camera[size_rt] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6};\n\n  AScalar residual_adiff[size];\n  AScalar point_adiff[size_point];\n  AScalar rt_instance_adiff[size_rt];\n  AScalar rt_camera_adiff[size_rt];\n\n  double residuals[size];\n  double jac_instance_rt[size * size_rt];\n  double jac_camera_rt[size * size_rt];\n  double jac_point[size * size_point];\n};\n\nTEST_F(ReprojectionError3DFixture, AnalyticErrorEvaluatesOK) {\n  // Autodiff-ed version will be used as reference/expected values\n  SetupADiff();\n  AScalar dummy_adiff;\n  bundle::ReprojectionError3D autodiff(geometry::ProjectionType::SPHERICAL,\n                                       observed, scale);\n  autodiff(&dummy_adiff, rt_instance_adiff, rt_camera_adiff, point_adiff,\n           residual_adiff);\n\n  // We test for analytic evaluation\n  double dummy = 0.;\n  double dummy_jac[] = {0., 0., 0.};\n  const double* params[] = {&dummy, rt_instance, rt_camera, point};\n  double* jacobians[] = {&dummy_jac[0], jac_instance_rt, jac_camera_rt,\n                         jac_point};\n  bundle::ReprojectionError3DAnalytic analytic(\n      geometry::ProjectionType::SPHERICAL, observed, scale);\n  analytic.Evaluate(params, residuals, &jacobians[0]);\n\n  // Check\n  CheckJacobians();\n}\n", "meta": {"hexsha": "14074db9a20e94ace355364fedb570ba914537b1", "size": 9430, "ext": "cc", "lang": "C++", "max_stars_repo_path": "opensfm/src/bundle/test/reprojection_errors_test.cc", "max_stars_repo_name": "ricklentz/OpenSfM", "max_stars_repo_head_hexsha": "b44b5f2b533b6fce8055b3a5a98a59bc22ae2cf6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-27T07:05:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T01:10:14.000Z", "max_issues_repo_path": "opensfm/src/bundle/test/reprojection_errors_test.cc", "max_issues_repo_name": "ricklentz/OpenSfM", "max_issues_repo_head_hexsha": "b44b5f2b533b6fce8055b3a5a98a59bc22ae2cf6", "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": "opensfm/src/bundle/test/reprojection_errors_test.cc", "max_forks_repo_name": "ricklentz/OpenSfM", "max_forks_repo_head_hexsha": "b44b5f2b533b6fce8055b3a5a98a59bc22ae2cf6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-01T01:10:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T01:10:15.000Z", "avg_line_length": 35.4511278195, "max_line_length": 80, "alphanum_fraction": 0.6195121951, "num_tokens": 2952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225574, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6495292949072967}}
{"text": "/**\n * @file rmsprop_test.cpp\n * @author Marcus Edel\n *\n * Tests the RMSProp optimizer.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/core/optimizers/rmsprop/rmsprop.hpp>\n#include <mlpack/core/optimizers/sgd/test_function.hpp>\n\n#include <mlpack/methods/logistic_regression/logistic_regression.hpp>\n\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n#include <mlpack/methods/ann/performance_functions/mse_function.hpp>\n#include <mlpack/methods/ann/layer/binary_classification_layer.hpp>\n#include <mlpack/methods/ann/layer/bias_layer.hpp>\n#include <mlpack/methods/ann/layer/linear_layer.hpp>\n#include <mlpack/methods/ann/layer/base_layer.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::optimization;\nusing namespace mlpack::optimization::test;\n\nusing namespace mlpack::distribution;\nusing namespace mlpack::regression;\n\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(RMSpropTest);\n\n/**\n * Tests the RMSprop optimizer using a simple test function.\n */\nBOOST_AUTO_TEST_CASE(SimpleRMSpropTestFunction)\n{\n  SGDTestFunction f;\n  RMSprop<SGDTestFunction> optimizer(f, 1e-3, 0.99, 1e-8, 5000000, 1e-9, true);\n\n  arma::mat coordinates = f.GetInitialPoint();\n  optimizer.Optimize(coordinates);\n\n  BOOST_REQUIRE_SMALL(coordinates[0], 0.1);\n  BOOST_REQUIRE_SMALL(coordinates[1], 0.1);\n  BOOST_REQUIRE_SMALL(coordinates[2], 0.1);\n}\n\n/**\n * Run RMSprop on logistic regression and make sure the results are acceptable.\n */\nBOOST_AUTO_TEST_CASE(LogisticRegressionTest)\n{\n  // Generate a two-Gaussian dataset.\n  GaussianDistribution g1(arma::vec(\"1.0 1.0 1.0\"), arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g2(arma::vec(\"9.0 9.0 9.0\"), arma::eye<arma::mat>(3, 3));\n\n  arma::mat data(3, 1000);\n  arma::Row<size_t> responses(1000);\n  for (size_t i = 0; i < 500; ++i)\n  {\n    data.col(i) = g1.Random();\n    responses[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    data.col(i) = g2.Random();\n    responses[i] = 1;\n  }\n\n  // Shuffle the dataset.\n  arma::uvec indices = arma::shuffle(arma::linspace<arma::uvec>(0,\n      data.n_cols - 1, data.n_cols));\n  arma::mat shuffledData(3, 1000);\n  arma::Row<size_t> shuffledResponses(1000);\n  for (size_t i = 0; i < data.n_cols; ++i)\n  {\n    shuffledData.col(i) = data.col(indices[i]);\n    shuffledResponses[i] = responses[indices[i]];\n  }\n\n  // Create a test set.\n  arma::mat testData(3, 1000);\n  arma::Row<size_t> testResponses(1000);\n  for (size_t i = 0; i < 500; ++i)\n  {\n    testData.col(i) = g1.Random();\n    testResponses[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    testData.col(i) = g2.Random();\n    testResponses[i] = 1;\n  }\n\n  LogisticRegression<> lr(shuffledData.n_rows, 0.5);\n\n  LogisticRegressionFunction<> lrf(shuffledData, shuffledResponses, 0.5);\n  RMSprop<LogisticRegressionFunction<> > rmsprop(lrf);\n  lr.Train(rmsprop);\n\n  // Ensure that the error is close to zero.\n  const double acc = lr.ComputeAccuracy(data, responses);\n  BOOST_REQUIRE_CLOSE(acc, 100.0, 0.3); // 0.3% error tolerance.\n\n  const double testAcc = lr.ComputeAccuracy(testData, testResponses);\n  BOOST_REQUIRE_CLOSE(testAcc, 100.0, 0.6); // 0.6% error tolerance.\n}\n\n/**\n * Run RMSprop on a feedforward neural network and make sure the results are\n * acceptable.\n */\nBOOST_AUTO_TEST_CASE(FeedforwardTest)\n{\n  // Test on a non-linearly separable dataset (XOR).\n  arma::mat input, labels;\n  input << 0 << 1 << 1 << 0 << arma::endr\n        << 1 << 0 << 1 << 0 << arma::endr;\n  labels << 1 << 1 << 0 << 0;\n\n  // Instantiate the first layer.\n  LinearLayer<> inputLayer(input.n_rows, 8);\n  BiasLayer<> biasLayer(8);\n  TanHLayer<> hiddenLayer0;\n\n  // Instantiate the second layer.\n  LinearLayer<> hiddenLayer1(8, labels.n_rows);\n  TanHLayer<> outputLayer;\n\n  // Instantiate the output layer.\n  BinaryClassificationLayer classOutputLayer;\n\n  // Instantiate the feedforward network.\n  auto modules = std::tie(inputLayer, biasLayer, hiddenLayer0, hiddenLayer1,\n      outputLayer);\n  FFN<decltype(modules), decltype(classOutputLayer), RandomInitialization,\n      MeanSquaredErrorFunction> net(modules, classOutputLayer);\n\n  RMSprop<decltype(net)> opt(net, 0.03, 0.99, 1e-8, 300 * input.n_cols, -10);\n\n  net.Train(input, labels, opt);\n\n  arma::mat prediction;\n  net.Predict(input, prediction);\n\n  BOOST_REQUIRE_EQUAL(prediction(0), 1);\n  BOOST_REQUIRE_EQUAL(prediction(1), 1);\n  BOOST_REQUIRE_EQUAL(prediction(2), 0);\n  BOOST_REQUIRE_EQUAL(prediction(3), 0);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b62d77f531bb9b81262479850b122c5644dedef1", "size": 4556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/rmsprop_test.cpp", "max_stars_repo_name": "jmlevin7878/mlpack", "max_stars_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:16.000Z", "max_issues_repo_path": "src/mlpack/tests/rmsprop_test.cpp", "max_issues_repo_name": "jmlevin7878/mlpack", "max_issues_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/rmsprop_test.cpp", "max_forks_repo_name": "jmlevin7878/mlpack", "max_forks_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.835443038, "max_line_length": 80, "alphanum_fraction": 0.7050043898, "num_tokens": 1335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6494858311508144}}
{"text": "// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n#include <OpenTissue/core/spline/spline.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <boost/test/auto_unit_test.hpp>\r\n\r\n// Boost Test declaration and Checking macros\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\ntypedef OpenTissue::spline::MathTypes<double, size_t>    math_types;\r\ntypedef math_types::vector_type                                vector_type;\r\ntypedef math_types::matrix_type                                matrix_type;\r\ntypedef std::vector<double>                                    knot_container;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_spline_init_m_table);  \r\n\r\nBOOST_AUTO_TEST_CASE(test_init_m_table)\r\n{\r\n  knot_container U;\r\n\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);  //k = 3\r\n  U.push_back(1.0);\r\n  U.push_back(2.0);\r\n  U.push_back(3.0);\r\n  U.push_back(4.0);  // n = 6  => |P| = 7\r\n  U.push_back(5.0);\r\n  U.push_back(5.0);\r\n  U.push_back(5.0);  // m = 9  => |U| = 10\r\n\r\n  // Indices of basis functions belongs to the interval [0..n]\r\n\r\n  double const tolerance = 0.00001;\r\n\r\n  // u-parameter at half-way\r\n  {\r\n    double const u = 2.5;\r\n\r\n    matrix_type M;\r\n    BOOST_CHECK_NO_THROW( OpenTissue::spline::detail::initialize_m_table(4, u, 4, U, M) );\r\n\r\n    // Test content of M.\r\n    BOOST_CHECK_CLOSE(M(0,0), 1.0,     tolerance);\r\n    BOOST_CHECK_CLOSE(M(0,1), 1.0/2.0, tolerance);\r\n    BOOST_CHECK_CLOSE(M(0,2), 1.0/8.0, tolerance);\r\n    BOOST_CHECK_CLOSE(M(1,0), 1.0,     tolerance);\r\n    BOOST_CHECK_CLOSE(M(1,1), 1.0/2.0, tolerance);\r\n    BOOST_CHECK_CLOSE(M(1,2), 6.0/8.0, tolerance);\r\n    BOOST_CHECK_CLOSE(M(2,0), 2.0,     tolerance);\r\n    BOOST_CHECK_CLOSE(M(2,1), 2.0,     tolerance);\r\n    BOOST_CHECK_CLOSE(M(2,2), 1.0/8.0, tolerance);\r\n\r\n  }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "edc7ad8ad3a4c67d199f779820fcd8448e10827d", "size": 2018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/spline/init_m_table/src/unit_init_m_table.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/spline/init_m_table/src/unit_init_m_table.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/spline/init_m_table/src/unit_init_m_table.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 31.53125, "max_line_length": 91, "alphanum_fraction": 0.6432111001, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6494854109850874}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 2019 by the deal.II authors\n *\n * This file is part of the deal.II library.\n *\n * The deal.II library is free software; you can use it, redistribute\n * it, and/or modify it under the terms of the GNU Lesser General\n * Public License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * The full text of the license can be found in the file LICENSE.md at\n * the top level of the deal.II distribution.\n *\n * ---------------------------------------------------------------------\n *\n * based on deal.II step-1\n */\n\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\nusing namespace dealii;\n\n\n//! Generate a hypercube, and output it as an svg file.\nvoid first_grid(Triangulation<2> &triangulation)\n{\n  GridGenerator::hyper_cube(triangulation);\n  triangulation.refine_global(4);\n\n  std::ofstream out(\"grid-1.svg\");\n  GridOut       grid_out;\n  grid_out.write_svg(triangulation, out);\n  std::cout << \"Grid written to grid-1.svg\" << std::endl;\n}\n\n\n//! Generate a locally refined hyper_shell, and output it as an svg file.\nvoid second_grid(Triangulation<2> &triangulation)\n{\n  const Point<2> center(1, 0);\n  const double   inner_radius = 0.5, outer_radius = 1.0;\n  GridGenerator::hyper_shell(\n    triangulation, center, inner_radius, outer_radius, 10);\n\n\n  // triangulation.reset_manifold(0);\n\n  for (unsigned int step = 0; step < 5; ++step)\n    {\n      for (auto &cell : triangulation.active_cell_iterators())\n        {\n          for (const auto v : cell->vertex_indices())\n            {\n              const double distance_from_center =\n                center.distance(cell->vertex(v));\n\n              if (std::fabs(distance_from_center - inner_radius) <=\n                  1e-6 * inner_radius)\n                {\n                  cell->set_refine_flag();\n                  break;\n                }\n            }\n        }\n\n      triangulation.execute_coarsening_and_refinement();\n    }\n\n\n  std::ofstream out(\"grid-2.svg\");\n  GridOut       grid_out;\n  grid_out.write_svg(triangulation, out);\n\n  std::cout << \"Grid written to grid-2.svg\" << std::endl;\n}\n\n\n//! Create an L-shaped domain with one global refinement, and write it on\n// `third_grid.vtk`.  Refine the L-shaped mesh adaptively around the re-entrant\n// corner three times (after the global refinement you already did), but with a\n// twist: refine all cells with the distance between the center of the cell and\n// re-entrant corner is smaller than 1/3.\nvoid third_grid(Triangulation<2> &tria)\n{\n  // Insert code here\n  // last year code in comments\n  /* Triangulation<2> tr1,tr2,tr3,tr_final;\n   const Point<2> p1(0, 0);\n   const Point<2> p2(1,2);\n   const Point<2> p3(2,1);\n   const Point<2> p4(1,0);\n   const Point<2> p5(1,1);\n   const Point<2> p6(0,1);\n   GridGenerator::hyper_rectangle(tr1,p1,p5);\n   GridGenerator::hyper_rectangle(tr2,p6,p2);\n   GridGenerator::hyper_rectangle(tr3,p4,p3);\n   //they cannot be refined!\n   GridGenerator::merge_triangulations ({&tr1,&tr2,&tr3},tr_final);*/\n  GridGenerator::hyper_L(tria);\n  tria.refine_global(1);\n  const Point<2> p5(0, 0);\n  for (unsigned int step = 0; step < 3; ++step)\n    {\n      // Active cells are those that are not further refined\n      // we need to mark cells for refinement\n      for (auto &cell : tria.active_cell_iterators())\n        {\n          const double distance_from_corner = cell->center().distance({0, 0});\n          // choose whatever refinement condition\n          if (distance_from_corner < 2.0 / 3.0)\n            {\n              cell->set_refine_flag();\n            }\n        }\n      // refine global calls this function too\n      tria.execute_coarsening_and_refinement();\n    } // for steps loop\n\n  // tr_final.refine_global(2); //we want a nice picture :)\n\n  std::ofstream file_var(\"grid-3.vtk\");\n  GridOut       grid_out;\n  grid_out.write_vtk(tria, file_var);\n  std::cout << \"Grid written to grid-3.vtk\" << std::endl;\n}\n\n//! Returns a tuple with number of levels, number of cells, number of active\n// cells. Test this with all of  your meshes.\nstd::tuple<unsigned int, unsigned int, unsigned int>\nget_info(const Triangulation<2> &tria)\n{\n  // Insert code here\n  return std::make_tuple(tria.n_levels(),\n                         tria.n_cells(),\n                         tria.n_active_cells());\n}\n\nvoid\ntorus_grid()\n{\n  Triangulation<2, 3> tria;\n  GridGenerator::torus(tria, 2, 1);\n  tria.refine_global(2);\n\n  std::ofstream out(\"grid-torus.vtk\");\n  GridOut       grid_out;\n  grid_out.write_vtk(tria, out);\n  std::cout << \"Grid written to grid-torus.vtk\" << std::endl;\n}\n\n\nint\nmain()\n{\n  Triangulation<2> triangulation;\n  first_grid(triangulation);\n  triangulation.clear();\n  second_grid(triangulation);\n  triangulation.clear();\n  third_grid(triangulation);\n\n  torus_grid();\n}\n", "meta": {"hexsha": "8fdaff5ce263e915fc0beb877939e504e7dcef22", "size": 5072, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/step-1.cc", "max_stars_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-davydenk", "max_stars_repo_head_hexsha": "3353fa9cd3aca4e100e4bae1de6331265755147d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/step-1.cc", "max_issues_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-davydenk", "max_issues_repo_head_hexsha": "3353fa9cd3aca4e100e4bae1de6331265755147d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/step-1.cc", "max_forks_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-davydenk", "max_forks_repo_head_hexsha": "3353fa9cd3aca4e100e4bae1de6331265755147d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3179190751, "max_line_length": 79, "alphanum_fraction": 0.6360410095, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.6494212358121941}}
{"text": "/**\n * @file conslawwithsource_main.cc\n * @brief NPDE exam TEMPLATE CODE FILE\n * @author Oliver Rietmann\n * @date 20.07.2020\n * @copyright Developed at SAM, ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"conslawwithsource.h\"\n\nint main() {\n  // Initial data\n  auto u0 = [](double x) { return (0.0 <= x && x < 1.0) ? 1.0 : 0.0; };\n\n  // Prepare different spacial resolutions\n  const int samples = 8;\n  Eigen::VectorXi N(samples);\n  N(0) = 10;\n  for (int i = 1; i < samples; ++i) N(i) = 2 * N(i - 1);\n\n  // Compute total masses at endtime T=3\n  Eigen::VectorXd m3(samples);\n  for (int i = 0; i < samples; ++i) {\n    Eigen::VectorXd m = ConsLawWithSource::traceMass(u0, N(i));\n    m3(i) = m(m.size() - 1);\n  }\n\n  // Print N vs. total masses\n  Eigen::Matrix<double, samples, 2> table;\n  std::cout << \"          N        m(3)\" << std::endl;\n  table.col(0) = N.cast<double>();\n  table.col(1) = m3;\n  std::cout << table << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "dc97000ac48db435be74e943a4d2b4b2cc6c21e7", "size": 963, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ConsLawWithSource/templates/conslawwithsource_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ConsLawWithSource/templates/conslawwithsource_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ConsLawWithSource/templates/conslawwithsource_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 24.075, "max_line_length": 71, "alphanum_fraction": 0.5887850467, "num_tokens": 327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6494212353462486}}
{"text": "#include <dvs_mosaic/poisolve/laplace.h>\n#include <dvs_mosaic/reconstruction.h>\n\n#include <boost/multi_array.hpp>\n#include <glog/logging.h>\n\n\nnamespace poisson\n{\n\nvoid reconstructBrightnessFromGradientMap(const cv::Mat& grad_map,\n                                                cv::Mat* map_reconstructed)\n{\n  CHECK_EQ(grad_map.type(), CV_32FC2);\n  CHECK_GT(grad_map.cols, 0);\n  CHECK_GT(grad_map.rows, 0);\n  const cv::Size img_size = grad_map.size();\n\n  // Compute the right hand side of Poisson eq.\n  // F = dgx/dx + dgy/dy and put it into a boost::multi_array\n  const size_t height = img_size.height;\n  const size_t width = img_size.width;\n  boost::multi_array<double,2> M(boost::extents[height][width]);\n  boost::multi_array<double,2> F(boost::extents[height][width]);\n\n  // Compute right hand side (rhs) using one-sided finite differences\n  for(size_t i=0; i < height-1; ++i)\n  {\n    for(size_t j=0; j < width-1; ++j)\n    {\n      F[i][j] = double( grad_map.at<cv::Vec2f>(i,j+1)[0] - grad_map.at<cv::Vec2f>(i,j)[0]\n                      + grad_map.at<cv::Vec2f>(i+1,j)[1] - grad_map.at<cv::Vec2f>(i,j)[1] );\n    }\n  }\n  F[height-1][width-1] = 0.0;\n\n  // Solve for M_xx + M_yy = F using Poisson solver,\n  // with constant intensity (zero) boundary conditions\n  const double gradient_on_boundary = 0.0;\n  pde::poisolve(M, F, 1.0, 1.0, 1.0, 1.0,\n                gradient_on_boundary,\n                pde::types::boundary::Neumann,false);\n\n  // Fill in output variable\n  *map_reconstructed = cv::Mat(img_size, CV_32FC1);\n  // FILL IN ...\n\n}\n\n}\n", "meta": {"hexsha": "2731ae4740baadace44f47ab308d44eb17985ad3", "size": 1544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/reconstruction.cpp", "max_stars_repo_name": "tub-rip/dvs_mosaic_skeleton", "max_stars_repo_head_hexsha": "ee3fc860eb312bcb0167a97b6b9f241096ab4179", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-27T02:06:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-02T09:06:31.000Z", "max_issues_repo_path": "src/reconstruction.cpp", "max_issues_repo_name": "tub-rip/dvs_mosaic_skeleton", "max_issues_repo_head_hexsha": "ee3fc860eb312bcb0167a97b6b9f241096ab4179", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reconstruction.cpp", "max_forks_repo_name": "tub-rip/dvs_mosaic_skeleton", "max_forks_repo_head_hexsha": "ee3fc860eb312bcb0167a97b6b9f241096ab4179", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-25T01:56:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T01:56:10.000Z", "avg_line_length": 30.2745098039, "max_line_length": 92, "alphanum_fraction": 0.6334196891, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6492867653501584}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace boost::numeric::ublas;\n\nint main()\n{\n\t// op(Matrix)\n\tmatrix<std::complex<double> > m (3, 3);\n\tfor (unsigned i = 0; i < m.size1 (); ++ i)\n\t\tfor (unsigned j = 0; j < m.size2 (); ++ j)\n\t\t\tm (i, j) = std::complex<double> (3 * i + j, 3 * i + j);\n\n\tstd::cout << \"minus \\t\" << - m << std::endl;\n\tstd::cout << \"conj \\t\" << conj (m) << std::endl;\n\tstd::cout << \"real \\t\" << real (m) << std::endl;\n\tstd::cout << \"imag \\t\" << imag (m) << std::endl;\n\tstd::cout << \"trans \\t\" << trans (m) << std::endl;\n\tstd::cout << \"herm \\t\" << herm (m) << std::endl;\n\n\t// Matrix +/- Matrix\n\tmatrix<double> m1 (3, 3), m2 (3, 3);\n\tfor (unsigned i = 0; i < std::min (m1.size1 (), m2.size1 ()); ++ i)\n\t\tfor (unsigned j = 0; j < std::min (m1.size2 (), m2.size2 ()); ++ j)\n\t\t\tm1 (i, j) = m2 (i, j) = 3 * i + j;\n\n\tstd::cout << \"add \\t\" << m1 + m2 << std::endl;\n\tstd::cout << \"subt \\t\" << m1 - m2 << std::endl;\n\n\t// scalar * Matrix\n\tmatrix<double> mm (3, 3);\n\tfor (unsigned i = 0; i < mm.size1 (); ++ i)\n\t\tfor (unsigned j = 0; j < mm.size2 (); ++ j)\n\t\t\tmm (i, j) = 3 * i + j;\n\n\tstd::cout << \"2 * matrix \\t\" << 2.0 * mm << std::endl;\n\tstd::cout << \"matrix * 2 \\t\" << mm * 2.0 << std::endl;\n\n\t// Matrix * Vector\n\tmatrix<double> m_ (3, 3);\n\tvector<double> v (3);\n\tfor (unsigned i = 0; i < std::min (m_.size1 (), v.size ()); ++ i) {\n\t\tfor (unsigned j = 0; j < m_.size2 (); ++ j)\n\t\t\tm_ (i, j) = 3 * i + j;\n\t\tv (i) = i;\n\t}\n\n\tstd::cout << \"matrix * vector (A * b) \\t\" << prod (m_, v) << std::endl;\n\tstd::cout << \"vector * matrix (A' * b)\\t\" << prod (v, m_) << std::endl;   \n\n\t// Matrix * Matrix\n\tmatrix<double> m11 (3, 3), m22 (3, 3);\n\tfor (unsigned i = 0; i < std::min (m11.size1 (), m22.size1 ()); ++ i)\n\t\tfor (unsigned j = 0; j < std::min (m11.size2 (), m22.size2 ()); ++ j)\n\t\t\tm11 (i, j) = m22 (i, j) = 3 * i + j;\n\n\tstd::cout << \"matrix * matrix (A * B) \\t\" << prod (m11, m22) << std::endl;\n\treturn 0;\n}", "meta": {"hexsha": "fbfd54151dbb5632a24eec4b8aabacf287c5c25c", "size": 1962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "basic_operation.cpp", "max_stars_repo_name": "yoon-gu/la-table", "max_stars_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "basic_operation.cpp", "max_issues_repo_name": "yoon-gu/la-table", "max_issues_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "basic_operation.cpp", "max_forks_repo_name": "yoon-gu/la-table", "max_forks_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2542372881, "max_line_length": 75, "alphanum_fraction": 0.498470948, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6492867500919898}}
{"text": "#include <string>\n#include <vector>\n#include <Eigen/Dense>\n#include <cmath>\n#include <exception>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n\n#include \"naive_bayes.cpp\"\n#include \"eigen_space.cpp\"\n\n#define PI 3.141592653589793238462643383279502884L\n#define REGULARIZATION_FACTOR 0.5\n#define IDEAL_NUM_PRINCIPLE_COMPONENTS 16\n\n\n#define _l_ std::cout<<__LINE__<<std::endl;\n\n\nconst std::string TRAINING_FILE_NAME = \"data/zip.train\"; // 7291 items\nconst std::string TEST_FILE_NAME = \"data/zip.test\"; // 2007 items\n\n\n\nstd::vector<ClassificationObject>\nReadData(\n  const std::string& fileName,\n  const unsigned featureDim,\n  const unsigned numItems) {\n\n  std::ifstream fin;\n  fin.clear(); fin.open(fileName.c_str());\n\n  if (!fin.good()) {\n    throw std::exception();\n  }\n\n  std::vector<ClassificationObject> data; data.reserve(numItems);\n\n  for (unsigned i = 0; i < numItems; ++i) {\n    ClassificationObject classificationObject;\n    double dummy;\n    fin >> dummy;\n    classificationObject.label = (unsigned) dummy;\n\n    classificationObject.features.resize(featureDim);\n    for (unsigned j = 0; j < featureDim; ++j) {\n      fin >> classificationObject.features(j);\n    }\n    data.push_back(classificationObject);\n  }\n\n  return data;\n}\n\n\nEigen::MatrixXi\nPerformClassifications(const std::vector<unsigned>& labelSet,\n  const std::vector<ClassInfo>& classSummaries,\n  const std::vector<ClassificationObject>& testObjects) {\n\n  Eigen::MatrixXi confusionMatrix(labelSet.size(), labelSet.size());\n  confusionMatrix.setZero(labelSet.size(), labelSet.size());\n\n  unsigned i = 1;\n  unsigned onePercent = testObjects.size() / 100;\n  for (const ClassificationObject& object : testObjects) {\n    if (i % onePercent == 0) {\n      std::cout << i << \"%% processed.\" << std::endl;\n    }\n    i++;\n\n    unsigned classifiedAs = ClassifyObject(object, classSummaries);\n    confusionMatrix(object.label, classifiedAs)++;\n  }\n\n  return confusionMatrix;\n}\n\nEigen::MatrixXi\nPerformPcaClassifications(const std::vector<unsigned>& labelSet,\n  const std::vector<ReducedDimClassInfo>& classSummaries,\n  const std::vector<ClassificationObject>& testObjects) {\n\n  Eigen::MatrixXi confusionMatrix(labelSet.size(), labelSet.size());\n  confusionMatrix.setZero(labelSet.size(), labelSet.size());\n\n  unsigned i = 1;\n  unsigned onePercent = testObjects.size() / 100;\n  for (const ClassificationObject& object : testObjects) {\n    if (i % onePercent == 0) {\n      std::cout << (double)i * 100.0 / testObjects.size() << \"% processed.\" << std::endl;\n    }\n    i++;\n\n    unsigned classifiedAs = PcaClassifyObject(object, classSummaries);\n    confusionMatrix(object.label, classifiedAs)++;\n  }\n\n  return confusionMatrix;\n}\n\n\nint\nmain(const int argc, const char** argv) {\n  std::cout << \"Reading Data...\" << std::endl;\n  std::vector<ClassificationObject> trainingData = ReadData(\n    TRAINING_FILE_NAME,\n    256,\n    7291\n  );\n  std::vector<ClassificationObject> testData = ReadData(\n    TEST_FILE_NAME,\n    256,\n    2007\n  );\n\n  std::cout << \"Training Models...\" << std::endl;\n  std::vector<ClassInfo> classSummaries; classSummaries.reserve(10);\n  for (unsigned label = 0; label <= 9; ++label) {\n    classSummaries.push_back(ComputeClassInfo(trainingData, label, 256));\n  }\n\n  std::cout << \"Training Reduced Dimensionality Models...\" << std::endl;\n  std::vector<ReducedDimClassInfo> reducedClassSummaries; reducedClassSummaries.reserve(10);\n  for (unsigned label = 0; label <= 9; ++label) {\n    reducedClassSummaries.push_back(\n      ComputeClassInfoInPcaDimensionReducedSpace(\n        trainingData,\n        classSummaries[label],\n        16\n      )\n    );\n  }\n  \n  std::cout << \"Classifying Objects...\" << std::endl;\n  Eigen::MatrixXi confusionMatrix = PerformPcaClassifications(\n    {0,1,2,3,4,5,6,7,8,9},\n    reducedClassSummaries,\n    testData\n  );\n\n  std::cout << \"Results:\" << std::endl;\n  std::cout << confusionMatrix << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "9212f88d81a2da7a27e2b47aca7a3234a792d337", "size": 3923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STAT775/HW03/Exercise03.cpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "STAT775/HW03/Exercise03.cpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "STAT775/HW03/Exercise03.cpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 26.3288590604, "max_line_length": 92, "alphanum_fraction": 0.6923273005, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6492867413384056}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#ifndef FCPPT_MPL_CEIL_DIV_HPP_INCLUDED\n#define FCPPT_MPL_CEIL_DIV_HPP_INCLUDED\n\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/mpl/integral_c.hpp>\n#include <type_traits>\n#include <fcppt/config/external_end.hpp>\n\n\nnamespace fcppt\n{\nnamespace mpl\n{\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\n/**\n\\brief Calculates a division of integral contants rounded towards infinity\n\n\\ingroup fcpptmpl\n\nCalculates <code>Dividend / Divisor</code> rounded towards infinity. For\nexample, <code>5 / 3</code> would result in <code>2</code>.\n\n\\snippet mpl/various.cpp mpl_ceil_div\n\n\\tparam Type Must be an unsigned integral type\n\n\\tparam Dividend The dividend\n\n\\tparam Divisor The divisor\n*/\ntemplate<\n\ttypename Type,\n\tType Dividend,\n\tType Divisor\n>\nstruct ceil_div\n:\nboost::mpl::integral_c<\n\tType,\n\tDividend\n\t/\n\tDivisor\n\t+\n\t(\n\t\tDividend %\n\t\tDivisor\n\t\t?\n\t\t\t1u\n\t\t:\n\t\t\t0u\n\t)\n>\n{\n\tstatic_assert(\n\t\tstd::is_unsigned<\n\t\t\tType\n\t\t>::value,\n\t\t\"ceil_div only works on unsigned types\"\n\t);\n};\n\nFCPPT_PP_POP_WARNING\n\n}\n}\n\n#endif\n", "meta": {"hexsha": "d60bb9a73670cae477f8c0ca4d4fb7ff90857c66", "size": 1399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fcppt/mpl/ceil_div.hpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/fcppt/mpl/ceil_div.hpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/fcppt/mpl/ceil_div.hpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4875, "max_line_length": 74, "alphanum_fraction": 0.7433881344, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6492867408655632}}
{"text": "#include <iostream>\n\n#include <Eigen/Eigen>\n\n#include \"slick/math/so2.h\"\n#include \"slick/math/se2.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace slick;\n\nvoid test_constructors(){\n  cout << \"SE2():\\n\" << SE2() << endl;\n  SO2 so2;\n  Matrix<SlickScalar,2,1> v2=Matrix<SlickScalar,2,1>::Zero();\n  v2[0]=1;\n  cout << \"SE2(so2,v2):\\n\" << SE2(so2,v2) << endl;\n  Matrix<SlickScalar,3,1> v3 = Matrix<SlickScalar,3,1>::Zero();\n  v3[0]=1;\n  cout << \"SE2(v3):\\n\" << SE2(v3) << endl;\n}\n\nvoid test_operators(){\n  SO2 so2;\n  Matrix<SlickScalar,3,1> v3 = Matrix<SlickScalar,3,1>::Zero();\n  v3[0]=1;\n  Matrix<SlickScalar,3,1> v3Minus = -v3;\n  cout << \"SE2(v3)*SE2(-v3):\\n\" << SE2(v3)*SE2(v3Minus) << endl;\n  Matrix<SlickScalar,3,3> m3 = Matrix<SlickScalar,3,3>::Identity();\n  cout << \"SE2(v3)*m3:\\n\" << SE2(v3)*m3 << endl;\n  cout << \"m3*SE2(v3):\\n\" << endl;\n  cout << m3*SE2(v3) << endl;\n  cout << \"SE2(v3).inverse():\\n\" << SE2(v3).inverse() << endl;\n  cout << \"SE2(v3).ln():\\n\" << SE2(v3).ln() << endl;\n  cout << \"SO2()*SE2(v3):\\n\" << SO2()*SE2(v3) << endl;\n}\n\nint main(int , char ** )\n{\n  cout << \"testing constructors ...\\n\" << endl;\n  test_constructors();\n  cout << \"testing operators ...\\n\" << endl;\n  test_operators();\n  return 0;\n}\n\n", "meta": {"hexsha": "b8b1e510c34f80415ee4c90f73c94a4fb0271c04", "size": 1240, "ext": "cc", "lang": "C++", "max_stars_repo_path": "slick/test/test_math_se2.cc", "max_stars_repo_name": "williammc/Slick", "max_stars_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-13T05:26:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-13T05:26:40.000Z", "max_issues_repo_path": "slick/test/test_math_se2.cc", "max_issues_repo_name": "williammc/Slick", "max_issues_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slick/test/test_math_se2.cc", "max_forks_repo_name": "williammc/Slick", "max_forks_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_forks_repo_licenses": ["BSD-3-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.3829787234, "max_line_length": 67, "alphanum_fraction": 0.589516129, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6492813525539574}}
{"text": "\n#include \"camsim.hpp\"\n\n#include \"gtsam/inference/Symbol.h\"\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/nonlinear/Marginals.h>\n#include <gtsam/geometry/SimpleCamera.h>\n#include <boost/make_shared.hpp>\n\nusing namespace gtsam;\nusing namespace gtsam::noiseModel;\nusing symbol_shorthand::X;\n\n/**\n * Unary factor on the unknown pose, resulting from measuring the projection of\n * a known 3D point in the image\n */\nclass ResectioningFactor_xxx : public NoiseModelFactor1<Pose3>\n{\n  typedef NoiseModelFactor1<Pose3> Base;\n\n  Cal3_S2::shared_ptr K_; ///< camera's intrinsic parameters\n  Point3 P_;              ///< 3D point on the calibration rig\n  Point2 p_;              ///< 2D measurement of the 3D point\n\npublic:\n\n  /// Construct factor given known point P and its projection p\n  ResectioningFactor_xxx(const SharedNoiseModel &model, const Key &key,\n                         const Cal3_S2::shared_ptr &calib, const Point2 &p, const Point3 &P) :\n    Base(model, key), K_(calib), P_(P), p_(p)\n  {\n  }\n\n  /// evaluate the error\n  virtual Vector evaluateError(const Pose3 &pose, boost::optional<Matrix &> H =\n  boost::none) const\n  {\n    SimpleCamera camera(pose, *K_);\n    return camera.project(P_, H, boost::none, boost::none) - p_;\n  }\n};\n\n/*******************************************************************************\n * Camera: f = 1, Image: 100x100, center: 50, 50.0\n * Pose (ground truth): (Xw, -Yw, -Zw, [0,0,2.0]')\n * Known landmarks:\n *    3D Points: (10,10,0) (-10,10,0) (-10,-10,0) (10,-10,0)\n * Perfect measurements:\n *    2D Point:  (55,45)   (45,45)    (45,55)     (55,55)\n *******************************************************************************/\n\nint gtsam_resection()\n{\n  /* read camera intrinsic parameters */\n  Cal3_S2::shared_ptr calib(new Cal3_S2(1, 1, 0, 50, 50));\n\n  /* 1. create graph */\n  NonlinearFactorGraph graph;\n\n  /* 2. add factors to the graph */\n  // add measurement factors\n  SharedDiagonal measurementNoise = Diagonal::Sigmas(Vector2(5., .5));\n  graph.emplace_shared<ResectioningFactor_xxx>(measurementNoise, X(1), calib,\n                                               Point2(55, 45), Point3(10, 10, 0));\n  graph.emplace_shared<ResectioningFactor_xxx>(measurementNoise, X(1), calib,\n                                               Point2(45, 45), Point3(-10, 10, 0));\n  graph.emplace_shared<ResectioningFactor_xxx>(measurementNoise, X(1), calib,\n                                               Point2(45, 55), Point3(-10, -10, 0));\n  graph.emplace_shared<ResectioningFactor_xxx>(measurementNoise, X(1), calib,\n                                               Point2(55, 55), Point3(10, -10, 0));\n\n  /* 3. Create an initial estimate for the camera pose */\n  Values initial;\n  initial.insert(X(1),\n//                 Pose3(Rot3(1, 1, 0, 0, -1, 0, 0, 0, -1), Point3(0, 0, 2)));\n                 Pose3(Rot3(1, 0, 0, 0, -1, 0, 0, 0, -1), Point3(0, 0, 2)));\n\n  graph.print(\"full graph\");\n\n  /* 4. Optimize the graph using Levenberg-Marquardt*/\n  Values result = LevenbergMarquardtOptimizer(graph, initial).optimize();\n  result.print(\"Final result:\\n\");\n\n  auto camera_f_marker = result.at<Pose3>(X(1));\n  std::cout << camera_f_marker.rotation() << camera_f_marker.rotation().xyz() << std::endl;\n\n  std::cout.precision(2);\n  Marginals marginals(graph, result);\n  std::cout << \"x1 covariance:\\n\" << marginals.marginalCovariance(X(1)) << std::endl;\n\n  std::cout << \"initial error = \" << graph.error(initial) << std::endl;\n  std::cout << \"final error = \" << graph.error(result) << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "ea2e4142643944f2cbc252085d286bfa47153d5f", "size": 3572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gtsam_resection.cpp", "max_stars_repo_name": "ptrmu/camsim", "max_stars_repo_head_hexsha": "2d79bf2eff32a33aca81cc205cb9256937abcbed", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T16:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-12T16:51:58.000Z", "max_issues_repo_path": "src/gtsam_resection.cpp", "max_issues_repo_name": "ptrmu/camsim", "max_issues_repo_head_hexsha": "2d79bf2eff32a33aca81cc205cb9256937abcbed", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gtsam_resection.cpp", "max_forks_repo_name": "ptrmu/camsim", "max_forks_repo_head_hexsha": "2d79bf2eff32a33aca81cc205cb9256937abcbed", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.824742268, "max_line_length": 94, "alphanum_fraction": 0.6007838746, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6492813499105727}}
{"text": "// Copyright (c) 2018-2019, University of Bremen, M. Farzalipour Tabriz\r\n// Copyrights licensed under the 2-Clause BSD License.\r\n// See the accompanying LICENSE.txt file for terms.\r\n\r\n#pragma once\r\n#include <armadillo>\r\n#include \"arma_io.hpp\"\r\n#include <fftw3.h>\r\n#include \"general_io.hpp\"\r\n#include \"spline.hpp\"\r\n\r\n#define PI datum::pi\r\n\r\n\r\n//These functions extend the functionality of the included Armadillo library by providing:\r\n// (arma,iostream) << and >> operators for reading from iostreams to armadillo types and vice versa\r\n// fft/ifft functions for cube files: Wrappers for FFTW with MATLAB/Octave scaling convention\r\n//\t\t\t\tin FFT functions the forward FFT scales by 1, and the reverse scales by 1/N. \r\n// 3D ndgrid and 3D meshgrid\r\n// 3D spline interpolation\r\n// 3D shift: by number of the elements along one axis or with a relative 3D shift vector\r\n// irowvec to matrix/cube size conversion\r\n// scalar triple product\r\n\r\n\r\nusing namespace arma;\r\n\r\n// a (very inefficient) 3D spline interpolation!\r\ncube interp3(const rowvec& x, const rowvec& y, const rowvec& z, const cube& v, const rowvec& xi, const rowvec& yi, const rowvec& zi);\r\ncube interp3(const cube& v, const rowvec& xi, const rowvec& yi, const rowvec& zi);\r\n\r\n//Rectangular grid in 3D space\r\ntuple<cube, cube, cube> ndgrid(const rowvec& v1, const rowvec& v2, const rowvec& v3);\r\n\r\n//3D meshgrid\r\ntuple<cube, cube, cube> meshgrid(const rowvec& v1, const rowvec& v2, const rowvec& v3);\r\n\r\n//shifts a cube by a relative 3D vector [0 1]\r\ncube shift(cube cube_in, rowvec3 shifts);\r\n\r\n//Planar average of a cube in the defined direction\r\n//direction: 0,1,2 > x,y,z\r\nvec planar_average(const uword& direction, const cube& cube_in);\r\n\r\n\r\n//1D FFT of complex data.\r\n//no normalization for forward FFT\r\ncx_vec fft(cx_vec X);\r\n\r\n//1D FFT of real data.\r\n//no normalization for forward FFT\r\ncx_vec fft(vec X);\r\n\r\n\r\n//3D FFT of complex data.\r\n//no normalization for forward FFT\r\ncx_cube fft(cx_cube X);\r\n\r\n//3D FFT of real data.\r\n//no normalization for forward FFT\r\ncx_cube fft(cube X);\r\n\r\n//1D inverse FFT of complex data.\r\n//normalized by N = X.n_elem\r\ncx_vec ifft(cx_vec X);\r\n\r\n//3D inverse FFT of complex data.\r\n//normalized by N = X.n_elem\r\ncx_cube ifft(cx_cube X);\r\n\r\n//returns a cube size object from the values inside a vector\r\nSizeCube as_size(const urowvec3& vec);\r\n\r\n//returns a matrix size object from the values inside a vector\r\nSizeMat as_size(const urowvec2& vec);\r\n\r\n//element-wise fmod\r\nmat fmod(mat mat_in, const double& denom) noexcept;\r\n\r\n//element-wise positive fmod\r\nmat fmod_p(mat mat_in, const double& denom) noexcept;\r\n\r\n//positive fmod\r\ndouble fmod_p(double num, const double& denom) noexcept;\r\n\r\n//just a simple square! May cause overflows!!\r\ninline double square(const double& input) noexcept {\r\n\treturn input * input;\r\n}\r\n\r\n\r\n//Poisson solver in 3D with anisotropic dielectric profiles\r\n//diel is the N*3 matrix of variations in dielectric tensor elements in direction normal to the surface\r\ncx_cube poisson_solver_3D(const cx_cube& rho, mat diel, rowvec3 lengths, uword normal_direction);\r\n\r\n\r\n\r\n//generate a copy of the cube with the elements shifted by N positions along:\r\n//dim=0: each row\r\n//dim=1: each column\r\n//dim=2: each slice\r\ntemplate <typename T>\r\nCube<T> shift(const Cube<T>& A, const sword& N, const uword& dim) {\r\n\tCube<T> B(arma::size(A));\r\n\tconst auto index_init = regspace<uvec>(0, A.n_elem - 1);\r\n\timat sub_shift = conv_to<imat>::from(ind2sub(arma::size(A), index_init));\r\n\tconst uword size = arma::size(A)(dim);\r\n\tsub_shift.row(dim).for_each([&N, &size](sword& i) noexcept {\r\n\t\ti += N;\r\n\t\twhile (i < 0) i += size;\r\n\t\ti = i % size;\r\n\t});\r\n\r\n\tB(sub2ind(arma::size(A), conv_to<umat>::from(sub_shift))) = A(index_init);\r\n\r\n\treturn B;\r\n}\r\n\r\n//Undo a fftshift\r\ntemplate <typename T>\r\nRow<T> ifftshift(const Row<T> &A) {\r\n\treturn shift(A, -1 * (A.n_elem / 2));\r\n}\r\n\r\n//Undo a fftshift\r\ntemplate <typename T>\r\nCube<T> ifftshift(Cube<T> A) {\r\n\tfor (uword i = 0; i < 3; ++i) {\r\n\t\tA = shift(A, -1 * (arma::size(A)(i) / 2), i);\r\n\t}\r\n\r\n\treturn A;\r\n}\r\n\r\n//returns the size of a cube as a rowvec\r\ntemplate<typename T>\r\nurowvec3 SizeVec(const Cube<T>& c) {\r\n\tconst SizeCube size = arma::size(c);\r\n\treturn urowvec({ size(0), size(1), size(2) });\r\n}\r\n\r\n//returns the size of a matrix as a rowvec\r\ntemplate<typename T>\r\nurowvec2 SizeVec(const Mat<T>& c) {\r\n\tconst SizeMat size = arma::size(c);\r\n\treturn urowvec({ size(0), size(1) });\r\n}\r\n\r\n\r\n//sign of the val as -1/0/+1\r\ntemplate <typename T> int sgn(T val) {\r\n\treturn (T(0) < val) - (val < T(0));\r\n}\r\n\r\n", "meta": {"hexsha": "94d6f56bedb7fb53d3983ab3d26b2fd82eeeb3bc", "size": 4544, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/slabcc_math.hpp", "max_stars_repo_name": "Anower120/slabcc", "max_stars_repo_head_hexsha": "8b8d17224314ad4c37c6c57d3c613592572870f8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-02T01:11:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-02T01:11:56.000Z", "max_issues_repo_path": "src/slabcc_math.hpp", "max_issues_repo_name": "Anower120/slabcc", "max_issues_repo_head_hexsha": "8b8d17224314ad4c37c6c57d3c613592572870f8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/slabcc_math.hpp", "max_forks_repo_name": "Anower120/slabcc", "max_forks_repo_head_hexsha": "8b8d17224314ad4c37c6c57d3c613592572870f8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3161290323, "max_line_length": 134, "alphanum_fraction": 0.6899207746, "num_tokens": 1287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6492813436474222}}
{"text": "#include <doctest/doctest.h>\n\n#define EIGEN_INITIALIZE_MATRICES_BY_ZERO\n\n#include <Eigen/Core>\n#include <ode/ode.hpp>\n\nTEST_CASE(\"ODE Test\")\n{\n  using method_type    = ode::explicit_method<ode::runge_kutta_4_tableau<float>>;\n  using problem_type   = ode::initial_value_problem<float, Eigen::Vector3f>;\n\n  constexpr auto sigma = 10.0f;\n  constexpr auto rho   = 28.0f;\n  constexpr auto beta  = 8.0f / 3.0f;\n\n  const auto problem   = problem_type\n  {\n    0.0f,                                         /* t0 */\n    Eigen::Vector3f(16.0f, 16.0f, 16.0f),         /* y0 */\n    [&] (const float t, const Eigen::Vector3f& y) /* y' = f(t, y) */\n    {\n      return Eigen::Vector3f(sigma * (y[1] - y[0]), y[0] * (rho - y[2]) - y[1], y[0] * y[1] - beta * y[2]); /* Lorenz system */\n    }\n  };\n\n  auto iterator = ode::fixed_step_iterator<method_type, problem_type>(problem, 1.0f /* h */);\n  for (auto i = 0; i < 1000; ++i)\n    ++iterator;\n}", "meta": {"hexsha": "6b3fd58bf053072c3dfd689944cafbd7cf999cdb", "size": 926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ode_test.cpp", "max_stars_repo_name": "acdemiralp/ode", "max_stars_repo_head_hexsha": "e953d3abdff8ce9340f52d43c02d4b6fb65319f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-12-18T10:44:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T12:04:10.000Z", "max_issues_repo_path": "tests/ode_test.cpp", "max_issues_repo_name": "acdemiralp/ode", "max_issues_repo_head_hexsha": "e953d3abdff8ce9340f52d43c02d4b6fb65319f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-11-21T20:54:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T23:12:08.000Z", "max_forks_repo_path": "tests/ode_test.cpp", "max_forks_repo_name": "acdemiralp/ode", "max_forks_repo_head_hexsha": "e953d3abdff8ce9340f52d43c02d4b6fb65319f0", "max_forks_repo_licenses": ["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.8666666667, "max_line_length": 127, "alphanum_fraction": 0.5831533477, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357702, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6492374174577199}}
{"text": "#pragma once\n\n#include <crest/geometry/indexed_mesh.hpp>\n#include <crest/geometry/biscale_mesh.hpp>\n#include <crest/geometry/triangle.hpp>\n#include <crest/quadrature/triquad.hpp>\n#include <crest/util/eigen_extensions.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nnamespace crest\n{\n    namespace detail\n    {\n        /**\n         * Returns the coefficients of the three linear Lagrange basis functions\n         * associated with the triangle.\n         *\n         * Given basis function l_i for i = 0, 1, 2, then\n         * l_i = a_i x + b_i y + c_i\n         * where\n         *      [ a_0   a_1   a_2 ]\n         * B =  [ b_0   b_1   b_2 ]\n         *      [ c_0   c_1   c_2 ]\n         * @param triangle\n         * @return\n         */\n        template <typename Scalar>\n        Eigen::Matrix<Scalar, 3, 3> basis_coefficients_for_triangle(const Triangle<Scalar> & triangle)\n        {\n            constexpr Scalar one = static_cast<Scalar>(1.0);\n            Eigen::Matrix<Scalar, 3, 3> X;\n            X <<\n              triangle.a.x, triangle.a.y, one,\n                    triangle.b.x, triangle.b.y, one,\n                    triangle.c.x, triangle.c.y, one;\n\n            return X.partialPivLu().solve(Eigen::Matrix<Scalar, 3, 3>::Identity());\n        };\n        /**\n         * The interpolation of a fine-scale finite element space in the (possibly discontinuous) space of\n         * affine functions on a coarse finite element space can be computed by the relation\n         * Py = Bx, where y represent the weights in the affine coarse space and x represents the weights\n         * in the fine-scale finite element space. This function computes B.\n         * @param coarse\n         * @param fine\n         * @return\n         */\n        template <typename Scalar>\n        Eigen::SparseMatrix<Scalar> build_affine_interpolator_rhs(\n                const BiscaleMesh<Scalar, int> & mesh)\n        {\n            std::vector<Eigen::Triplet<Scalar>> triplets;\n\n            for (int coarse_index = 0; coarse_index < mesh.coarse_mesh().num_elements(); ++coarse_index)\n            {\n                // The basis functions p_h in the affine space can be expressed as\n                // p_h(x, y) = a x + b y + c\n                // for some coefficients a, b, c.\n                const auto coarse_triangle = mesh.coarse_mesh().triangle_for(coarse_index);\n                const Eigen::Matrix<Scalar, 3, 3> coarse_coeff = basis_coefficients_for_triangle(coarse_triangle);\n                for (const auto fine_index : mesh.descendants_for(coarse_index))\n                {\n                    const auto vertex_indices = mesh.fine_mesh().elements()[fine_index].vertex_indices;\n                    const auto fine_triangle = mesh.fine_mesh().triangle_for(fine_index);\n                    const Eigen::Matrix<Scalar, 3, 3> fine_coeff = basis_coefficients_for_triangle(fine_triangle);\n\n                    // Local coarse basis function i\n                    for (size_t i = 0; i < 3; ++i)\n                    {\n                        // Local fine basis function j\n                        for (size_t j = 0; j < 3; ++j)\n                        {\n                            const auto vertex_index = vertex_indices[j];\n                            const auto product = [&](auto x, auto y)\n                            {\n                                const auto coarse_basis_value =\n                                        coarse_coeff(0, i) * x + coarse_coeff(1, i) * y + coarse_coeff(2, i);\n                                const auto fine_basis_value =\n                                        fine_coeff(0, j) * x + fine_coeff(1, j) * y + fine_coeff(2, j);\n                                return coarse_basis_value * fine_basis_value;\n                            };\n                            const auto inner_product = triquad<2>(product,\n                                                                  fine_triangle.a,\n                                                                  fine_triangle.b,\n                                                                  fine_triangle.c);\n                            const auto row = 3 * coarse_index + i;\n                            triplets.push_back(Eigen::Triplet<Scalar>(row, vertex_index, inner_product));\n                        }\n                    }\n                }\n            }\n\n            const auto num_dof_affine_space = 3 * mesh.coarse_mesh().num_elements();\n            Eigen::SparseMatrix<Scalar> B(num_dof_affine_space, mesh.fine_mesh().num_vertices());\n            B.setFromTriplets(triplets.cbegin(), triplets.cend());\n            return B;\n        };\n\n        template <typename Scalar>\n        Eigen::SparseMatrix<Scalar> build_affine_interpolator_lhs_inverse(\n                const IndexedMesh<Scalar, int> & coarse)\n        {\n            const auto num_dof_affine_space = 3 * coarse.num_elements();\n            Eigen::SparseMatrix<Scalar> P(num_dof_affine_space, num_dof_affine_space);\n\n            // P will be block diagonal with 3x3 blocks, so we can reserve space in advance.\n            P.reserve(Eigen::VectorXi::Constant(num_dof_affine_space, 3));\n\n            Eigen::Matrix<Scalar, 3, 3> P_ref;\n            P_ref << 2.0 / 24.0, 1.0 / 24.0, 1.0 / 24.0,\n                    1.0 / 24.0, 2.0 / 24.0, 1.0 / 24.0,\n                    1.0 / 24.0, 1.0 / 24.0, 2.0 / 24.0;\n\n            for (int t = 0; t < coarse.num_elements(); ++t)\n            {\n                const auto triangle = coarse.triangle_for(t);\n                const auto determinant = static_cast<Scalar>(2.0) * crest::area(triangle);\n                assert(determinant != static_cast<Scalar>(0));\n                Eigen::Matrix<Scalar, 3, 3> P_local = determinant * P_ref.template cast<Scalar>();\n                P_local = P_local.inverse().eval();\n\n                for (int j = 0; j < 3; ++j)\n                {\n                    for (int i = 0; i < 3; ++i)\n                    {\n                        const auto row = 3 * t + i;\n                        const auto col = 3 * t + j;\n                        P.insert(row, col) = P_local(i, j);\n                    }\n                }\n            }\n\n            return P;\n        };\n\n        /**\n         * Given a coarse and fine mesh where the coarse mesh is a subset of the fine mesh (when interpreted as a forest),\n         * build a matrix that interpolates functions in the fine finite element space in the\n         * (possibly discontinuous) space of affine functions on the coarse space.\n         * @param coarse\n         * @param fine\n         * @return\n         */\n        template <typename Scalar>\n        Eigen::SparseMatrix<Scalar> affine_interpolator(\n                const BiscaleMesh<Scalar, int> & mesh)\n        {\n            const Eigen::SparseMatrix<Scalar> B = build_affine_interpolator_rhs(mesh);\n            const Eigen::SparseMatrix<Scalar> P = build_affine_interpolator_lhs_inverse(mesh.coarse_mesh());\n            return P * B;\n        };\n\n        template <typename Scalar>\n        std::vector<unsigned int> count_vertex_occurrences(const IndexedMesh<Scalar, int> & mesh)\n        {\n            auto count = std::vector<unsigned int>(mesh.num_vertices(), static_cast<Scalar>(0));\n            for (const auto & element : mesh.elements())\n            {\n                for (const auto & v : element.vertex_indices)\n                {\n                    ++count[v];\n                }\n            }\n            return count;\n        }\n\n        /**\n         * Given a triangulation T, returns a matrix of dimensions N(T) x [3 * card(T)] which maps functions in the\n         * (possibly discontinuous) affine space P_1 to functions in the standard linear finite element space\n         * on the mesh.\n         * Here, N(T) denotes the number of vertices in T, and card(T) denotes the number of elements in T.\n         * @param mesh\n         * @return\n         */\n        template <typename Scalar>\n        Eigen::SparseMatrix<Scalar> nodal_average_interpolator(const IndexedMesh<Scalar, int> & mesh)\n        {\n            const auto occurrences = count_vertex_occurrences(mesh);\n\n            // Reserve space for 1 non-zero per column, since each basis function in the affine space\n            // maps to exactly one vertex in the standard finite element space.\n            const auto num_dof_affine_space = 3 * mesh.num_elements();\n            Eigen::SparseMatrix<Scalar> J(mesh.num_vertices(), num_dof_affine_space);\n            J.reserve(Eigen::VectorXi::Constant(num_dof_affine_space, 1));\n\n            for (int t = 0; t < mesh.num_elements(); ++t)\n            {\n                const auto vertices = mesh.elements()[t].vertex_indices;\n\n                for (size_t v = 0; v < 3; ++v)\n                {\n                    const auto col = 3 * t + v;\n                    const auto vertex_index = vertices[v];\n                    const auto cardinality = occurrences[vertex_index];\n                    J.insert(vertex_index, col) = static_cast<Scalar>(1.0) / static_cast<Scalar>(cardinality);\n                }\n            }\n\n            return J;\n        };\n    }\n\n    template <typename Scalar>\n    Eigen::SparseMatrix<Scalar> quasi_interpolator(const BiscaleMesh<Scalar, int> & mesh)\n    {\n        const auto P = detail::affine_interpolator(mesh);\n        const auto J = detail::nodal_average_interpolator(mesh.coarse_mesh());\n        return J * P;\n    }\n\n}\n", "meta": {"hexsha": "420eaaf5387b640a99a5316f19f4272007b0f429", "size": 9366, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crest/basis/quasi_interpolation.hpp", "max_stars_repo_name": "Andlon/crest", "max_stars_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crest/basis/quasi_interpolation.hpp", "max_issues_repo_name": "Andlon/crest", "max_issues_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-01-24T10:45:27.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-27T16:21:37.000Z", "max_forks_repo_path": "include/crest/basis/quasi_interpolation.hpp", "max_forks_repo_name": "Andlon/crest", "max_forks_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7663551402, "max_line_length": 122, "alphanum_fraction": 0.5269058296, "num_tokens": 2041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.6492374028954583}}
{"text": "/**\n * @file kalmen.hpp\n * @author Vahid Bastani\n *\n * Implementation of Kalman filter\n */\n#ifndef SSMPACK_FILTER_KALMAN_HPP\n#define SSMPACK_FILTER_KALMAN_HPP\n\n#include \"ssmkit/distribution/gaussian.hpp\"\n#include \"ssmkit/distribution/conditional.hpp\"\n#include \"ssmkit/process/markov.hpp\"\n#include \"ssmkit/process/memoryless.hpp\"\n#include \"ssmkit/process/hierarchical.hpp\"\n#include \"ssmkit/filter/recursive_bayesian_base.hpp\"\n#include <armadillo>\n\nnamespace ssmkit {\nnamespace filter {\n\nusing process::Hierarchical;\nusing process::Markov;\nusing process::Memoryless;\nusing distribution::Conditional;\nusing distribution::Gaussian;\n\n/** Kalman filter\n */\ntemplate <class STA_MAP, class OBS_MAP>\nclass Kalman\n    : public RecursiveBayesianBase<Kalman<STA_MAP, OBS_MAP>> {\n\n public:\n  //! Type of process object\n  using TProcess =\n      Hierarchical<Markov<Gaussian, STA_MAP, Gaussian>,\n                   Memoryless<Gaussian, OBS_MAP>>;\n  //! Type of the posterior state \\f$(\\hat{\\mathbf{x}}, \\hat{\\mathbf{P}})\\f$ \n  using TCompeleteState =\n      std::tuple<arma::vec, arma::mat>;\n\n private:\n  //! The process object\n  TProcess process_;\n  //! The state transition matrix \\f$\\mathbf{F}\\f$\n  const arma::mat &dyn_mat_;\n  //! The measurement matrix \\f$\\mathbf{H}\\f$\n  const arma::mat &mes_mat_;\n  //! The covariance of dynamic noise \\f$\\mathbf{Q}\\f$\n  const arma::mat &dyn_cov_;\n  //! The covariance of measurement noise \\f$\\mathbf{R}\\f$\n  const arma::mat &mes_cov_;\n  //! The corrected state vector \\f$\\mathbf{x}_{t|t}\\f$\n  arma::vec state_vec_;\n  //! The corrected state covariance \\f$\\mathbf{P}_{t|t}\\f$\n  arma::mat state_cov_;\n  //! The predicted state vector \\f$\\mathbf{x}_{t|t-1}\\f$\n  arma::vec p_state_vec_;\n  //! The predicted state covariance \\f$\\mathbf{P}_{t|t-1}\\f$\n  arma::mat p_state_cov_;\n\n public:\n  /** Construct a Kalman filter\n   *\n   * Construct a Kalman filter with parameters taken from \\p process argument.\n   */\n  Kalman(const TProcess &process)\n      : process_(process),\n        dyn_mat_(\n            process_.template getProcess<0>().getCPDF().getParamMap().transfer),\n        mes_mat_(\n            process_.template getProcess<1>().getCPDF().getParamMap().transfer),\n        dyn_cov_(process_.template getProcess<0>()\n                     .getCPDF()\n                     .getParamMap()\n                     .covariance),\n        mes_cov_(process_.template getProcess<1>()\n                     .getCPDF()\n                     .getParamMap()\n                     .covariance) {}\n\n  \n  /** Prediction\n   *\n   * Performs the prediction step.\n   *\n   * \\f{equation}{\\hat{\\mathbf{x}}_{t|t-1} = \\mathbf{F}\\hat{\\mathbf{x}}_{t-1|t-1}+u_d(y^d_1,\n   * \\cdots, y^d_{N_d}) \\f}\n   * \\f{equation}{\\mathbf{P}_{t|t-1} = \\mathbf{F}\\mathbf{P}_{t-1|t-1}\\mathbf{F}^T+\\mathbf{Q}\\f}\n   *\n   * @param args... Control variables \\f$y^d_1, \\cdots, y^d_{N_d}\\f$ of the dynamic process, if any.\n   */\n  template <class... TArgs>\n  void predict(const TArgs &... args) {\n    // use the map function to pass controls, avoiding control definition\n    // is move used here??\n    p_state_vec_ =\n        std::get<0>(process_.template getProcess<0>().getCPDF().getParamMap()(\n            state_vec_, args...));\n    p_state_cov_ = dyn_mat_ * state_cov_ * dyn_mat_.t() + dyn_cov_;\n  }\n  \n  /** Correction\n   *\n   * Performs correction step.\n   *\n   * \\f{equation}{\\tilde{\\mathbf{z}}_t=\\mathbf{z}_t-\\mathbf{H}\\hat{\\mathbf{x}}_{t|t-1}-u_m(y^m_1, \\cdots, y^m_{N_m})\\f}\n   * \\f{equation}{\\mathbf {S}_t=\\mathbf{H}\\mathbf{P}_{t|t-1}\\mathbf{H}^T+\\mathbf{R} \\f}\n   * \\f{equation}{\\mathbf{K}_t=\\mathbf{P}_{t|t-1}\\mathbf{H}^T\\mathbf{S}_t^{-1} \\f}\n   * \\f{equation}{\\hat{\\mathbf{x}}_{t|t}=\\hat{\\mathbf{x}}_{t|t-1}+\\mathbf{K}_{t}\\tilde{\\mathbf{z}}_t \\f}\n   * \\f{equation}{\\mathbf{P}_{t|t}=(I-\\mathbf{K}_t\\mathbf{H})\\mathbf{P}_{t|t-1}\\f}\n   *\n   * @param measurement Measurement vector \\f$\\mathbf{z}_t\\f$.\n   * @param args... Control variables \\f$y^m_1, \\cdots, y^m_{N_m}\\f$ of the measurement process, if any.\n   * @return Estimated state \\f$(\\hat{\\mathbf{x}}_{t|t}, \\mathbf{P}_{t|t})\\f$\n   */\n  template <class... TArgs>\n  TCompeleteState correct(const arma::vec &measurement,\n                          const TArgs &... args) {\n    arma::vec inovation =\n        measurement -\n        std::get<0>(process_.template getProcess<1>().getCPDF().getParamMap()(\n            p_state_vec_, args...));\n\n    arma::mat inovation_cov = mes_mat_ * p_state_cov_ * mes_mat_.t() + mes_cov_;\n    arma::mat kalman_gain =\n        p_state_cov_ * mes_mat_.t() * arma::inv_sympd(inovation_cov);\n\n    state_vec_ = p_state_vec_ + kalman_gain * inovation;\n    state_cov_ = p_state_cov_ - kalman_gain * mes_mat_ * p_state_cov_;\n    return std::make_tuple(state_vec_, state_cov_);\n  }\n  /** Initialization\n   *\n   * @return Initial state \\f$(\\hat{\\mathbf{x}}_{0|0}, \\mathbf{P}_{0|0})\\f$\n   */\n  TCompeleteState initialize() {\n    state_vec_ = process_.template getProcess<0>().getInitialPDF().getMean();\n    state_cov_ =\n        process_.template getProcess<0>().getInitialPDF().getCovariance();\n    return std::make_tuple(state_vec_, state_cov_);\n  }\n};\n\ntemplate <class STA_MAP, class OBS_MAP>\nKalman<STA_MAP, OBS_MAP> makeKalman(\n    Hierarchical<Markov<Gaussian, STA_MAP, Gaussian>,\n                 Memoryless<Gaussian, OBS_MAP>> process) {\n  return Kalman<STA_MAP, OBS_MAP>(process);\n}\n\n} // namespace filter\n} // namespace ssmkit\n\n#endif // SSMPACK_FILTER_KALMAN_HPP\n", "meta": {"hexsha": "063c9966482529e6b180704131e68fa42f9ea9e5", "size": 5416, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ssmkit/filter/kalman.hpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "src/ssmkit/filter/kalman.hpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssmkit/filter/kalman.hpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 34.7179487179, "max_line_length": 119, "alphanum_fraction": 0.6419867061, "num_tokens": 1687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6492373956720136}}
{"text": "// Copyright (C) 2009  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/matrix.h>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <vector>\n#include \"../stl_checked.h\"\n#include \"../array.h\"\n#include \"../rand.h\"\n#include <dlib/string.h>\n\n#include \"tester.h\"\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.matrix_lu\");\n\n    dlib::rand rnd;\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename mat_type>\n    const matrix<typename mat_type::type> symm(const mat_type& m) { return m*trans(m); }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename type>\n    const matrix<type> randmat(long r, long c)\n    {\n        matrix<type> m(r,c);\n        for (long row = 0; row < m.nr(); ++row)\n        {\n            for (long col = 0; col < m.nc(); ++col)\n            {\n                m(row,col) = static_cast<type>(rnd.get_random_double()); \n            }\n        }\n\n        return m;\n    }\n\n    template <typename type, long NR, long NC>\n    const matrix<type,NR,NC> randmat()\n    {\n        matrix<type,NR,NC> m;\n        for (long row = 0; row < m.nr(); ++row)\n        {\n            for (long col = 0; col < m.nc(); ++col)\n            {\n                m(row,col) = static_cast<type>(rnd.get_random_double()); \n            }\n        }\n\n        return m;\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename matrix_type>\n    void test_lu ( const matrix_type& m)\n    {\n        typedef typename matrix_type::type type;\n        const type eps = 10*max(abs(m))*sqrt(std::numeric_limits<type>::epsilon());\n        dlog << LDEBUG << \"test_lu():  \" << m.nr() << \" x \" << m.nc() << \"  eps: \" << eps;\n        print_spinner();\n\n\n        lu_decomposition<matrix_type> test(m);\n\n        DLIB_TEST(test.is_square() == (m.nr() == m.nc()));\n\n        DLIB_TEST(test.nr() == m.nr());\n        DLIB_TEST(test.nc() == m.nc());\n\n        dlog << LDEBUG << \"m.nr(): \" << m.nr() << \"  m.nc(): \" << m.nc();\n\n        type temp;\n        DLIB_TEST_MSG( (temp= max(abs(test.get_l()*test.get_u() - rowm(m,test.get_pivot())))) < eps,temp);\n\n        if (test.is_square())\n        {\n            // none of the matrices we should be passing in to test_lu() should be singular.  \n            DLIB_TEST_MSG (abs(test.det()) > eps/100, \"det: \" << test.det() );\n            dlog << LDEBUG << \"big det: \" << test.det();\n\n            DLIB_TEST(test.is_singular() == false);\n\n            matrix<type> m2;\n            matrix<type,0,1> col;\n\n            m2 = identity_matrix<type>(m.nr());\n            DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2)));\n            m2 = randmat<type>(m.nr(),5);\n            DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2)));\n            m2 = randmat<type>(m.nr(),1);\n            DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2)));\n            col = randmat<type>(m.nr(),1);\n            DLIB_TEST_MSG(equal(m*test.solve(col), col,eps),max(abs(m*test.solve(m2)- m2)));\n\n            // now make us a singular matrix\n            if (m.nr() > 1)\n            {\n                matrix<type> sm(m);\n                set_colm(sm,0) = colm(sm,1);\n\n                lu_decomposition<matrix_type> test2(sm);\n                DLIB_TEST_MSG( (temp= max(abs(test2.get_l()*test2.get_u() - rowm(sm,test2.get_pivot())))) < eps,temp);\n\n                // these checks are only accurate for small matrices\n                if (test2.nr() < 100)\n                {\n                    DLIB_TEST_MSG(test2.is_singular() == true,\"det: \" << test2.det());\n                    DLIB_TEST_MSG(abs(test2.det()) < eps,\"det: \" << test2.det());\n                }\n\n            }\n        }\n\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void matrix_test_double()\n    {\n\n\n        test_lu(10*randmat<double>(2,2));\n        test_lu(10*randmat<double>(1,1));\n        test_lu(10*symm(randmat<double>(2,2)));\n        test_lu(10*randmat<double>(4,4));\n        test_lu(10*randmat<double>(9,4));\n        test_lu(10*randmat<double>(3,8));\n        test_lu(10*randmat<double>(15,15));\n        test_lu(2*symm(randmat<double>(15,15)));\n        test_lu(10*randmat<double>(100,100));\n        test_lu(10*randmat<double>(137,200));\n        test_lu(10*randmat<double>(200,101));\n\n        test_lu(10*randmat<double,2,2>());\n        test_lu(10*randmat<double,1,1>());\n        test_lu(10*randmat<double,4,3>());\n        test_lu(10*randmat<double,4,4>());\n        test_lu(10*randmat<double,9,4>());\n        test_lu(10*randmat<double,3,8>());\n        test_lu(10*randmat<double,15,15>());\n        test_lu(10*randmat<double,100,100>());\n        test_lu(10*randmat<double,137,200>());\n        test_lu(10*randmat<double,200,101>());\n\n        typedef matrix<double,0,0,default_memory_manager, column_major_layout> mat;\n        test_lu(mat(3*randmat<double>(4,4)));\n        test_lu(mat(3*randmat<double>(9,4)));\n        test_lu(mat(3*randmat<double>(3,8)));\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void matrix_test_float()\n    {\n\n    // -------------------------------\n\n        test_lu(3*randmat<float>(1,1));\n        test_lu(3*randmat<float>(2,2));\n        test_lu(3*randmat<float>(4,4));\n        test_lu(3*randmat<float>(9,4));\n        test_lu(3*randmat<float>(3,8));\n        test_lu(3*randmat<float>(137,200));\n        test_lu(3*randmat<float>(200,101));\n\n        test_lu(3*randmat<float,1,1>());\n        test_lu(3*randmat<float,2,2>());\n        test_lu(3*randmat<float,4,3>());\n        test_lu(3*randmat<float,4,4>());\n        test_lu(3*randmat<float,9,4>());\n        test_lu(3*randmat<float,3,8>());\n        test_lu(3*randmat<float,137,200>());\n        test_lu(3*randmat<float,200,101>());\n\n        typedef matrix<float,0,0,default_memory_manager, column_major_layout> mat;\n        test_lu(mat(3*randmat<float>(4,4)));\n        test_lu(mat(3*randmat<float>(9,4)));\n        test_lu(mat(3*randmat<float>(3,8)));\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class matrix_tester : public tester\n    {\n    public:\n        matrix_tester (\n        ) :\n            tester (\"test_matrix_lu\",\n                    \"Runs tests on the matrix LU component.\")\n        {\n            //rnd.set_seed(cast_to_string(time(0)));\n        }\n\n        void perform_test (\n        )\n        {\n            dlog << LINFO << \"seed string: \" << rnd.get_seed();\n\n            dlog << LINFO << \"begin testing with double\";\n            matrix_test_double();\n            dlog << LINFO << \"begin testing with float\";\n            matrix_test_float();\n        }\n    } a;\n\n}\n\n\n\n", "meta": {"hexsha": "f5425b355df028bb6007d937c62bf374bd879944", "size": 6989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/dlib/test/matrix_lu.cpp", "max_stars_repo_name": "mohitjain4395/mosip", "max_stars_repo_head_hexsha": "20ee978dc539be42c8b79cd4b604fdf681e7b672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "dlib/test/matrix_lu.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "dlib/test/matrix_lu.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 31.2008928571, "max_line_length": 118, "alphanum_fraction": 0.4873372442, "num_tokens": 1846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6492238549451902}}
{"text": "//\n// Created by Jacques Perrault on 10/2/21.\n//\n#include <catch2/catch.hpp>\n#include <iostream>\n#include <Eigen/Dense>\n#include <3dMethods/pca.h>\nusing namespace Eigen;\nusing namespace std;\n\nSCENARIO(\"pca\", \"[pca.h]\")\n{\n  MatrixXd mat(4, 3);\n  mat << 1, 1, 1, -2, -1, -1, 1.2, 1.2, 1.2, 21, 21, 21;\n  auto j = Pca(mat);\n\n  cout << \"eigenValues:\\n\" << get<0>(j) << endl;\n  cout << \"eigen vectors: \\n\" << get<1>(j) << endl;\n  // make some real test data\n}\n\nSCENARIO(\"findRigidTransform\", \"[pca.h]\")\n{\n  MatrixXd source(2, 3);\n  source << 1, 1, 1, -1, -1, -1;\n  MatrixXd target(2, 3);\n  target << -1, -1, -1, 2, 2, 2;\n  auto out = findRigidTransform(source, target);\n  cout << \"rotation: \\n\" << get<0>(out) << endl;\n  cout << \"translation: \\n\" << get<1>(out) << endl;\n}", "meta": {"hexsha": "adb06034bd571a18108e2a160d381659e4e52eb8", "size": 767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fitter/test/3dMethods.cpp", "max_stars_repo_name": "jdilla52/meshFitter", "max_stars_repo_head_hexsha": "7adfd5a00a394e459c8213701ea05f681c4ea207", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fitter/test/3dMethods.cpp", "max_issues_repo_name": "jdilla52/meshFitter", "max_issues_repo_head_hexsha": "7adfd5a00a394e459c8213701ea05f681c4ea207", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fitter/test/3dMethods.cpp", "max_forks_repo_name": "jdilla52/meshFitter", "max_forks_repo_head_hexsha": "7adfd5a00a394e459c8213701ea05f681c4ea207", "max_forks_repo_licenses": ["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.7419354839, "max_line_length": 56, "alphanum_fraction": 0.5801825293, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6491129293238532}}
{"text": "#include <Eigen/Core>\n#include <catch2/catch.hpp>\n#include <memory>\n#include <tuple>\n#include <vector>\n#include \"ear/bs2051.hpp\"\n#include \"ear/common/geom.hpp\"\n#include \"ear/common/helpers/eigen_helpers.hpp\"\n#include \"ear/object_based/extent.hpp\"\n\nusing namespace ear;\n\nTEST_CASE(\"test_basis\") {\n  double eps = 1e-6;\n\n  Eigen::Matrix3d expected;\n  // cardinal directions\n  expected = Eigen::Matrix3d::Identity();\n  REQUIRE(calcBasis(cart(0.0, 0.0, 1.0)).isApprox(expected, eps));\n  expected << 0, 1, 0,  //\n      -1, 0, 0,  //\n      0, 0, 1;\n  REQUIRE(calcBasis(cart(90.0, 0.0, 1.0)).isApprox(expected, eps));\n  expected << 0, -1, 0,  //\n      1, 0, 0,  //\n      0, 0, 1;\n  REQUIRE(calcBasis(cart(-90.0, 0.0, 1.0)).isApprox(expected, eps));\n  expected << -1, 0, 0,  //\n      0, -1, 0,  //\n      0, 0, 1;\n  REQUIRE(calcBasis(cart(180.0, 0.0, 1.0)).isApprox(expected, eps));\n  expected << 1, 0, 0,  //\n      0, 0, 1,  //\n      0, -1, 0;\n  REQUIRE(calcBasis(cart(0.0, 90.0, 1.0)).isApprox(expected, eps));\n  expected << 1, 0, 0,  //\n      0, 0, -1,  //\n      0, 1, 0;\n  REQUIRE(calcBasis(cart(0.0, -90.0, 1.0)).isApprox(expected, eps));\n\n  // slight offset from pole should behave as if pointing forwards\n  expected << 1, 0, 0,  //\n      0, 0, 1,  //\n      0, -1, 0;\n  REQUIRE(calcBasis(cart(90.0, 90.0 - 1e-6, 1.0)).isApprox(expected, eps));\n  expected << 1, 0, 0,  //\n      0, 0, -1,  //\n      0, 1, 0;\n  REQUIRE(calcBasis(cart(90.0, -90.0 + 1e-6, 1.0)).isApprox(expected, eps));\n}\n\nTEST_CASE(\"test_azimuth_elevation_on_basis\") {\n  double eps = 1e-6;\n\n  double azimuth, elevation;\n  Eigen::Matrix3d basis;\n  basis = calcBasis(cart(0.0, 10.0, 1.0));\n  std::tie(azimuth, elevation) =\n      azimuthElevationOnBasis(basis, cart(0.0, 10.0, 1.0));\n  REQUIRE(azimuth == Approx(0.0).margin(eps));\n  REQUIRE(elevation == Approx(0.0).margin(eps));\n  std::tie(azimuth, elevation) =\n      azimuthElevationOnBasis(basis, cart(0.0, 20.0, 1.0));\n  REQUIRE(azimuth == Approx(0.0).margin(eps));\n  REQUIRE(elevation == Approx(radians(10.0)).margin(eps));\n  basis = calcBasis(cart(-10.0, 0.0, 1.0));\n  std::tie(azimuth, elevation) =\n      azimuthElevationOnBasis(basis, cart(-20.0, 0.0, 1.0));\n  REQUIRE(azimuth == Approx(radians(10.0)).margin(eps));\n  REQUIRE(elevation == Approx(0.0).margin(eps));\n}\n\nTEST_CASE(\"test_cart_on_basis\") {\n  Eigen::Matrix3d basis;\n  basis = calcBasis(cart(0.0, 10.0, 1.0));\n  REQUIRE(\n      cartOnBasis(basis, 0.0, radians(10.0)).isApprox(cart(0.0, 20.0, 1.0)));\n  basis = calcBasis(cart(-10.0, 0.0, 1.0));\n  REQUIRE(\n      cartOnBasis(basis, radians(10.0), 0.0).isApprox(cart(-20.0, 0.0, 1.0)));\n}\n\nTEST_CASE(\"test_weight_func\") {\n  double fade = 10.0;\n  double height = 10.0;\n\n  double width;\n  double azimuth;\n  double expected;\n  double actual;\n  Eigen::Vector3d point;\n  for (auto entry : {std::make_pair(20.0, 0.0), std::make_pair(360.0, 0.0),\n                     std::make_pair(360.0, 180.0)}) {\n    std::tie(width, azimuth) = entry;\n    Eigen::VectorXd elevations = Eigen::VectorXd::LinSpaced(50, -90.0, 90.0);\n    for (double elevation : elevations) {\n      expected = interp(elevation,\n                        Eigen::Vector4d{-(height / 2 + fade), -height / 2,\n                                        height / 2, height / 2 + fade},\n                        Eigen::Vector4d{0, 1, 1, 0});\n\n      point = cart(azimuth, elevation, 1.0);\n      WeightingFunction weightingFunc(cart(0.0, 0.0, 1.0), width, height);\n      actual = weightingFunc(point);\n      REQUIRE(actual == Approx(expected));\n      // Swapped\n      point = cart(elevation, azimuth, 1.0);\n      WeightingFunction weightingFuncSwap(cart(0.0, 0.0, 1.0), height, width);\n      actual = weightingFuncSwap(point);\n      REQUIRE(actual == Approx(expected));\n    }\n  }\n  Eigen::VectorXd azimuths = Eigen::VectorXd::LinSpaced(50, -180, 180);\n  for (double azimuth : azimuths) {\n    double expected = interp(azimuth,\n                             Eigen::Vector4d{-(width / 2 + fade), -width / 2,\n                                             width / 2, width / 2 + fade},\n                             Eigen::Vector4d{0, 1, 1, 0});\n\n    point = cart(azimuth, 0.0, 1.0);\n    WeightingFunction weightingFunc(cart(0.0, 0.0, 1.0), width, height);\n    actual = weightingFunc(point);\n    REQUIRE(actual == Approx(expected));\n    // Swapped\n    point = cart(0.0, azimuth, 1.0);\n    WeightingFunction weightingFuncSwap(cart(0.0, 0.0, 1.0), height, width);\n    actual = weightingFuncSwap(point);\n    REQUIRE(actual == Approx(expected));\n  }\n}\n\nTEST_CASE(\"test_pv\") {\n  Layout layout = getLayout(\"9+10+3\").withoutLfe();\n  std::shared_ptr<PointSourcePanner> psp = configurePolarPanner(layout);\n  PolarExtentPanner extentPanner(psp);\n\n  REQUIRE(extentPanner.calcPvSpread(cart(0.0, 0.0, 1.0), 0.0, 0.0) ==\n          psp->handle(cart(0.0, 0.0, 1.0)).get());\n  REQUIRE(extentPanner.calcPvSpread(cart(10.0, 20.0, 1.0), 0.0, 0.0) ==\n          psp->handle(cart(10.0, 20.0, 1.0)).get());\n\n  std::vector<std::pair<Eigen::Vector3d, double>> positions{\n      std::make_pair(cart(0.0, 0.0, 1.0), 1e-10),\n      std::make_pair(cart(30.0, 10.0, 1.0), 1e-2)};\n  for (auto position : positions) {\n    Eigen::Vector3d pos = position.first;\n    double tol = position.second;\n    Eigen::VectorXd spread_pv = extentPanner.calcPvSpread(pos, 20.0, 10.0);\n    REQUIRE(spread_pv.norm() == Approx(1.0));\n    Eigen::VectorXd vv =\n        spread_pv.transpose() * toPositionsMatrix(layout.positions());\n    vv /= vv.norm();\n    REQUIRE(vv.isApprox(pos, tol));\n  }\n}\n", "meta": {"hexsha": "ce1cbca8a351efec749c27aa95c1bce96e4718f0", "size": 5497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/extent_tests.cpp", "max_stars_repo_name": "valnoel/libear", "max_stars_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/extent_tests.cpp", "max_issues_repo_name": "valnoel/libear", "max_issues_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/extent_tests.cpp", "max_forks_repo_name": "valnoel/libear", "max_forks_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2371794872, "max_line_length": 78, "alphanum_fraction": 0.5994178643, "num_tokens": 1928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6491021570543409}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main(){\n    Matrix3f haha;\n    haha << 1, 2, 3,\n            4, 5, 6,\n            7, 8, 9;\n    std::cout << haha << std::endl;\n}", "meta": {"hexsha": "bbcb63d2d3366d44377850c926540f099e736dfc", "size": 199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_eigen.cpp", "max_stars_repo_name": "SuhrudhSarathy/filters", "max_stars_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_eigen.cpp", "max_issues_repo_name": "SuhrudhSarathy/filters", "max_issues_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_eigen.cpp", "max_forks_repo_name": "SuhrudhSarathy/filters", "max_forks_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5833333333, "max_line_length": 35, "alphanum_fraction": 0.5075376884, "num_tokens": 67, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6491021444646757}}
{"text": "/*\n* This file is part of Teseo Android HAL\n*\n* Copyright (c) 2016-2017, STMicroelectronics - All Rights Reserved\n* Author(s): Baudouin Feildel <baudouin.feildel@st.com> for STMicroelectronics.\n*\n* License terms: Apache 2.0.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*/\n/**\n * @file model.cpp\n * @author Baudouin Feildel <baudouin.feildel@st.com>\n * @copyright 2016, STMicroelectronics, All rights reserved.\n */\n\n#include <teseo/geofencing/model.h>\n\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\n\nnamespace stm {\nnamespace geofencing {\nnamespace model {\n\ndouble degree_to_rad(double d)\n{\n    return d * boost::math::double_constants::degree;\n}\n\nbool transitionFlagsIsValid(TransitionFlags flags)\n{\n    constexpr TransitionFlags ALL_FLAGS_INVERTED = ~(\n        static_cast<int32_t>(Transition::Entered) &\n        static_cast<int32_t>(Transition::Exited)  &\n        static_cast<int32_t>(Transition::Uncertain));\n\n    // force all valid values in flags to zero\n    // if others bit are enabled transition flags is not valie\n    return !(flags & ALL_FLAGS_INVERTED);\n}\n\nconstexpr double WGS84_A = 6378137.0;\nconstexpr double WGS84_E = 0.0818191908426;\nconstexpr double WGS84_E2 = WGS84_E * WGS84_E;\n\nPoint::Point()\n{ }\n\nPoint::Point(const Location & loc) :\n    latitude(loc.latitude()),\n    longitude(loc.longitude())\n{ }\n\nPoint::Point(const ICoordinate & lat, const ICoordinate & lon) :\n    latitude(lat.asDecimalDegree()),\n    longitude(lon.asDecimalDegree())\n{ }\n\nstd::pair<double, double> Point::to_rad() const\n{\n    return std::make_pair(\n        degree_to_rad(latitude.value()),\n        degree_to_rad(longitude.value())\n    );\n}\n\ndouble Point::distanceFrom(const Point & p)\n{\n    const auto this_rad = to_rad();\n    const auto p_rad = p.to_rad();\n\n    const double sin_lat = sin(this_rad.first);\n\n    /* Earth local radius @ given latitude */\n    const double N = WGS84_A / sqrt(1.0 - (WGS84_E2 * sin_lat * sin_lat));\n\n    return sqrt(\n        ((N * (p_rad.first - this_rad.first)) * (N * (p_rad.first - this_rad.first))) +\n        ((N * (p_rad.second - this_rad.second) * sin_lat) * (N * (p_rad.second - this_rad.second) * sin_lat))\n    );\n}\n\n} // namespace model\n} // namespace geofencing\n} // namespace stm", "meta": {"hexsha": "c46f8177cea7418f64a0c4f669351d0a246fa2d0", "size": 2731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libteseo.geofencing/src/model.cpp", "max_stars_repo_name": "STMicroelectronics/STADG_Teseo_Android_HAL", "max_stars_repo_head_hexsha": "8822808d5a3ddebe4267fa94d62dc099c1173120", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-07-14T23:50:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T10:41:52.000Z", "max_issues_repo_path": "libteseo.geofencing/src/model.cpp", "max_issues_repo_name": "STMicroelectronics/STADG_Teseo_Android_HAL", "max_issues_repo_head_hexsha": "8822808d5a3ddebe4267fa94d62dc099c1173120", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libteseo.geofencing/src/model.cpp", "max_forks_repo_name": "STMicroelectronics/STADG_Teseo_Android_HAL", "max_forks_repo_head_hexsha": "8822808d5a3ddebe4267fa94d62dc099c1173120", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-31T13:56:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T09:09:34.000Z", "avg_line_length": 27.8673469388, "max_line_length": 109, "alphanum_fraction": 0.7008421824, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6491021442961483}}
{"text": "//\n// Created by kellerberrin on 5/08/18.\n//\n\n#include \"kel_exec_env.h\"\n#include \"kel_distribution.h\"\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/math/distributions/hypergeometric.hpp>\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/math/distributions/negative_binomial.hpp>\n\n\nnamespace bm = boost::math;\nnamespace kel = kellerberrin;\n\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// Distribution functions use boost special functions.\n//\n////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\ndouble kel::NormalDistribution::pdf(double x, double mean, double std_dev) {\n\n  static const double inv_sqrt_2pi = 0.3989422804014327;\n\n  double a = (x - mean) / std_dev;\n\n  return (inv_sqrt_2pi / std_dev) * std::exp(-0.5 * a * a);\n\n}\n\n\ndouble kel::GammaDistribution::pdf(double x) const {\n\n  return bm::pdf(bm::gamma_distribution<>(_a, _b), x);\n\n}\n\ndouble kel::GammaDistribution::cdf(double x) const {\n\n  return bm::cdf(bm::gamma_distribution<>(_a, _b), x);\n\n}\n\ndouble kel::GammaDistribution::quantile(double p) const {\n\n  return bm::quantile(bm::gamma_distribution<>(_a, _b), p);\n\n}\n\n\n\ndouble kel::BetaDistribution::logInverseBetaFunction(double a, double b) {\n\n  assert(a > 0.0);\n  assert(b > 0.0);\n\n  double log_gamma = bm::lgamma<double>(a + b) - bm::lgamma<double>(a) - bm::lgamma<double>(b);\n\n  return log_gamma;\n\n}\n\n\ndouble kel::BetaDistribution::logPartialPdf(double x, double a, double b) {\n\n  assert(x >= 0 && x <= 1);\n  assert(a >= 0);\n  assert(b >= 0);\n\n  double ret =  (b - 1) * std::log(1 - x) + (a - 1) * std::log(x);\n\n  return ret;\n\n}\n\n\ndouble kel::BetaDistribution::logPdf(double x, double a, double b) {\n\n  assert(x >= 0 && x <= 1);\n  assert(a > 0);\n  assert(b > 0);\n\n  double ret = logInverseBetaFunction(a, b) + logPartialPdf(x, a, b);\n\n  return ret;\n\n}\n\ndouble kel::BetaDistribution::pdf(double x, double a, double b) {\n\n  assert(x >= 0 && x <= 1);\n  assert(a > 0);\n  assert(b > 0);\n\n  double p = bm::tgamma<double>(a + b) / (bm::tgamma<double>(a) * bm::tgamma<double>(b));\n  double q = std::pow(1 - x, b - 1) * std::pow(x, a - 1);\n  return p * q;\n\n}\n\n\ndouble kel::BetaDistribution::mean(double a, double b) {\n\n  assert(a > 0);\n  assert(b > 0);\n\n  return a / (a + b);\n\n}\n\n\ndouble kel::BetaDistribution::var(double a, double b) {\n\n  assert(a > 0);\n  assert(b > 0);\n\n  return (a * b) / ((a + b) * (a + b) * (a + b + 1.0));\n\n}\n\n\ndouble kel::BetaDistribution::mode(double a, double b) {\n\n  assert(a > 1);\n  assert(b > 1);\n\n  return (a - 1.0) / (a + b - 2.0);\n\n}\n\ndouble kel::BetaBinomialDistribution::pdf(size_t n, size_t k, double alpha, double beta) {\n\n  assert(k <= n);\n  assert(alpha > 0);\n  assert(beta > 0);\n\n  double coeff = bm::binomial_coefficient<double>(n, k);\n\n  double a1 = static_cast<double>(k) + alpha;\n  double b1 = static_cast<double>(n-k) + beta;\n\n  double p = bm::beta<double>(a1, b1);\n  double q = bm::beta<double>(alpha, beta);\n\n  return coeff * (p / q);\n\n}\n\n\ndouble kel::BetaBinomialDistribution::partialPdf(double n, double k, double alpha, double beta) {\n\n  assert(k <= n);\n  assert(alpha > 0);\n  assert(beta > 0);\n\n  double a1 = k + alpha;\n  double b1 = n - k + beta;\n\n  double p = bm::beta<double>(a1, b1);\n  double q = bm::beta<double>(alpha, beta);\n\n  return (p / q);\n\n}\n\n\ndouble kel::BetaBinomialDistribution::logPartialPdf(double n, double k, double alpha, double beta) {\n\n  assert(k <= n);\n  assert(alpha > 0.0);\n  assert(beta > 0.0);\n\n  double r = n - k;\n  double a1 = k + alpha;\n  double b1 = r + beta;\n\n  double beta_n = bm::lgamma<double>(a1) + bm::lgamma<double>(b1) - bm::lgamma<double>(a1 + b1);\n  double beta_d = bm::lgamma<double>(alpha) + bm::lgamma<double>(beta) - bm::lgamma<double>(alpha + beta);\n  double prob = beta_n - beta_d;\n\n  return prob;\n\n}\n\n\ndouble kel::BetaBinomialDistribution::logPdf(double n, double k, double alpha, double beta) {\n\n  assert(k <= n);\n  assert(alpha > 0.0);\n  assert(beta > 0.0);\n\n  double r = n - k;\n  double a1 = k + alpha;\n  double b1 = r + beta;\n\n  double beta_coeff = bm::lgamma<double>(r + 1.0) + bm::lgamma<double>(k + 1.0) - bm::lgamma<double>(n + 2.0);\n  double inverse_log_binonimal_coeff = std::log(n + 1.0) + beta_coeff;\n  double beta_n = bm::lgamma<double>(a1) + bm::lgamma<double>(b1) - bm::lgamma<double>(a1 + b1);\n  double beta_d = bm::lgamma<double>(alpha) + bm::lgamma<double>(beta) - bm::lgamma<double>(alpha + beta);\n  double prob = beta_n - beta_d - inverse_log_binonimal_coeff;\n\n  return prob;\n\n}\n\n\n// .first is alpha, .second is beta. The raw moments are calculated from the observations and used to calculate alpha and beta.\n[[nodiscard]] std::pair<double, double> kel::BetaBinomialDistribution::methodOfMoments(const std::vector<size_t>& observations, size_t n_trials) {\n\n  // calculate the first moment\n  size_t obs_sum = std::accumulate(observations.begin(), observations.end(), static_cast<size_t>(0));\n  const double m1 = static_cast<double>(obs_sum) / static_cast<double>(observations.size());\n\n  // calculate the 2nd moment\n  auto sqr_lambda = [](size_t accumulate, size_t obs)->size_t { return accumulate + (obs * obs); };\n  size_t sqr_sum = std::accumulate(observations.begin(), observations.end(), static_cast<size_t>(0), sqr_lambda);\n  const double m2 = static_cast<double>(sqr_sum) / static_cast<double>(observations.size());\n\n  const double n = static_cast<double>(n_trials);\n\n  const double a_numer = (n * m1) - m2;\n  const double ab_denom = n * ((m2 / m1) - m1 - 1) + m1;\n  const double a = a_numer / ab_denom;\n\n  const double b_numer = (n - m1) * (n - (m2/m1));\n  const double b = b_numer / ab_denom;\n\n  return {a, b};\n\n}\n\n\n\ndouble kel::BinomialDistribution::pdf(size_t n, size_t k, double prob_success) {\n\n  assert(k <= n and k >= 0);\n  assert(prob_success >= 0 and prob_success <= 1.0);\n\n  double coeff = bm::binomial_coefficient<double>(n, k);\n\n  double p = std::pow(prob_success, static_cast<double>(k));\n\n  double q = std::pow((1.0 - prob_success), static_cast<double>(n - k));\n\n  return coeff * p * q;\n\n}\n\n\ndouble kel::BinomialDistribution::cdf(size_t n, double k, double prob_success) {\n\n  assert(k <= n and k >= 0);\n  assert(prob_success >= 0 and prob_success <= 1.0);\n\n  size_t integer_k = std::floor(k);\n  double sum_pdf = 0.0;\n\n  for (size_t index = 0; index <= integer_k; ++index) {\n\n    sum_pdf += cdf(n, index, prob_success);\n\n  }\n\n  return sum_pdf;\n\n}\n\n\nkel::HypergeometricDistribution::HypergeometricDistribution(size_t pop_successes_K, size_t sample_size_n, size_t population_N) {\n\n\n  if (pop_successes_K > population_N) {\n\n    ExecEnv::log().warn(\"HypergeometricDistribution::HypergeometricDistribution; Population Successes K:{} exceeds population size :{}\",\n                         pop_successes_K, population_N);\n    pop_successes_K = population_N;\n  }\n\n  if (sample_size_n > population_N) {\n\n    ExecEnv::log().warn(\"HypergeometricDistribution::HypergeometricDistribution; Sample size n:{} exceeds population size :{}\",\n                         sample_size_n, population_N);\n    sample_size_n = population_N;\n  }\n\n  pop_successes_K_ = pop_successes_K;\n  sample_size_n_ = sample_size_n;\n  population_N_ = population_N;\n\n}\n\ndouble kel::HypergeometricDistribution::pdf(size_t successes_k) const {\n\n  if (successes_k > upperSuccesses_k()) {\n\n    ExecEnv::log().warn(\"HypergeometricDistribution::pdf; r_successes k:{} exceeds upper limit :{}\",\n                         successes_k, upperSuccesses_k());\n    successes_k = upperSuccesses_k();\n\n  }\n\n  if (successes_k < lowerSuccesses_k()) {\n\n    ExecEnv::log().warn(\"HypergeometricDistribution::pdf; r_successes k:{} below lower limit :{}\",\n                         successes_k, lowerSuccesses_k());\n    successes_k = lowerSuccesses_k();\n\n  }\n\n  bm::hypergeometric_distribution hypergeometric(pop_successes_K_, sample_size_n_, population_N_);\n\n  return bm::pdf(hypergeometric, successes_k);\n\n}\n\ndouble kel::HypergeometricDistribution::cdf(size_t successes_k) const {\n\n  if (successes_k > upperSuccesses_k()) {\n\n    ExecEnv::log().warn(\"HypergeometricDistribution(N:{},K:{},n:{},k:{})::cdf; r_successes k exceeds upper limit :{}\",\n                        population_N_, pop_successes_K_, sample_size_n_, successes_k, upperSuccesses_k());\n    successes_k = upperSuccesses_k();\n\n  }\n\n  if (successes_k < lowerSuccesses_k()) {\n\n    ExecEnv::log().warn(\"HypergeometricDistribution(N:{},K:{},n:{},k:{})::cdf; r_successes k exceeds upper limit :{}\",\n                        population_N_, pop_successes_K_, sample_size_n_, successes_k, lowerSuccesses_k());\n    successes_k = lowerSuccesses_k();\n\n  }\n\n  bm::hypergeometric_distribution hypergeometric(pop_successes_K_, sample_size_n_, population_N_);\n\n  return bm::cdf(hypergeometric, successes_k);\n\n}\n\ndouble kel::HypergeometricDistribution::quantile(size_t successes_k) const {\n\n  if (successes_k > upperSuccesses_k()) {\n\n    ExecEnv::log().warn(\"HypergeometricDistribution::quantile; r_successes k:{} exceeds upper limit :{}\",\n                         successes_k, upperSuccesses_k());\n    successes_k = upperSuccesses_k();\n\n  }\n\n  if (successes_k < lowerSuccesses_k()) {\n\n    ExecEnv::log().warn(\"HypergeometricDistribution::quantile; r_successes k:{} below lower limit :{}\",\n                         successes_k, lowerSuccesses_k());\n    successes_k = lowerSuccesses_k();\n\n  }\n\n  bm::hypergeometric_distribution hypergeometric(pop_successes_K_, sample_size_n_, population_N_);\n\n  return bm::quantile(hypergeometric, successes_k);\n\n}\n\n\nsize_t kel::HypergeometricDistribution::lowerSuccesses_k() const {\n\n  int64_t lower_success = static_cast<int64_t>(sample_size_n_ + pop_successes_K_) - static_cast<int64_t>(population_N_);\n  return static_cast<size_t>(std::max<int64_t>(0, lower_success));\n\n}\n\n\ndouble kel::HypergeometricDistribution::upperSingleTailTest(size_t test_value_k) const {\n\n  if (test_value_k > 0) {\n\n    test_value_k = test_value_k - 1;\n\n  }\n\n  return 1.0 - cdf(test_value_k);\n\n}\n\ndouble kel::HypergeometricDistribution::lowerSingleTailTest(size_t test_value_k) const {\n\n  return cdf(test_value_k);\n\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// The Poisson distribution. Uses boost for implementation.\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\ndouble kel::Poisson::pdf(size_t count) const {\n\n  return bm::pdf(bm::poisson_distribution<>(lambda_), count);\n\n}\n\ndouble kel::Poisson::cdf(size_t count) const  {\n\n  return bm::cdf(bm::poisson_distribution<>(lambda_), count);\n\n}\n\nsize_t kel::Poisson::quantile(double quantile) const {\n\n  return bm::quantile(bm::poisson_distribution<>(lambda_), quantile);\n\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// The Negative Binomial distribution. Uses boost for implementation.\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\ndouble kel::NegativeBinomial::pdf(size_t count) const {\n\n  return bm::pdf(bm::negative_binomial_distribution<>(r_successes_, p_prob_success_), count);\n\n}\n\ndouble kel::NegativeBinomial::cdf(size_t count) const {\n\n  return bm::cdf(bm::negative_binomial_distribution<>(r_successes_, p_prob_success_), count);\n\n}\n\nsize_t kel::NegativeBinomial::quantile(double quantile) const {\n\n  return bm::quantile(bm::negative_binomial_distribution<>(r_successes_, p_prob_success_), quantile);\n\n}\n\ndouble kel::NegativeBinomial::mean() const {\n\n  return bm::mean(bm::negative_binomial_distribution<>(r_successes_, p_prob_success_));\n\n}\n", "meta": {"hexsha": "059dc7bece2bdf1b74826decabbb6f50c1fa4e2b", "size": 11832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kel_utility/kel_distribution.cpp", "max_stars_repo_name": "kellerberrin/OSM_Gene_Cpp", "max_stars_repo_head_hexsha": "4ec4d1244f3f1b16213cf05f0056d8e5f85d68c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kel_utility/kel_distribution.cpp", "max_issues_repo_name": "kellerberrin/OSM_Gene_Cpp", "max_issues_repo_head_hexsha": "4ec4d1244f3f1b16213cf05f0056d8e5f85d68c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kel_utility/kel_distribution.cpp", "max_forks_repo_name": "kellerberrin/OSM_Gene_Cpp", "max_forks_repo_head_hexsha": "4ec4d1244f3f1b16213cf05f0056d8e5f85d68c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4697986577, "max_line_length": 146, "alphanum_fraction": 0.6423258959, "num_tokens": 3128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6490699263585817}}
{"text": "\n#include <iostream>\n#include <Eigen/Geometry>\n#include <bench/BenchTimer.h>\nusing namespace Eigen;\nusing namespace std;\n\n\n\ntemplate<typename Q>\nEIGEN_DONT_INLINE Q nlerp(const Q& a, const Q& b, typename Q::Scalar t)\n{\n  return Q((a.coeffs() * (1.0-t) + b.coeffs() * t).normalized());\n}\n\ntemplate<typename Q>\nEIGEN_DONT_INLINE Q slerp_eigen(const Q& a, const Q& b, typename Q::Scalar t)\n{\n  return a.slerp(t,b);\n}\n\ntemplate<typename Q>\nEIGEN_DONT_INLINE Q slerp_legacy(const Q& a, const Q& b, typename Q::Scalar t)\n{\n  typedef typename Q::Scalar Scalar;\n  static const Scalar one = Scalar(1) - dummy_precision<Scalar>();\n  Scalar d = a.dot(b);\n  Scalar absD = internal::abs(d);\n  if (absD>=one)\n    return a;\n\n  // theta is the angle between the 2 quaternions\n  Scalar theta = std::acos(absD);\n  Scalar sinTheta = internal::sin(theta);\n\n  Scalar scale0 = internal::sin( ( Scalar(1) - t ) * theta) / sinTheta;\n  Scalar scale1 = internal::sin( ( t * theta) ) / sinTheta;\n  if (d<0)\n    scale1 = -scale1;\n\n  return Q(scale0 * a.coeffs() + scale1 * b.coeffs());\n}\n\ntemplate<typename Q>\nEIGEN_DONT_INLINE Q slerp_legacy_nlerp(const Q& a, const Q& b, typename Q::Scalar t)\n{\n  typedef typename Q::Scalar Scalar;\n  static const Scalar one = Scalar(1) - epsilon<Scalar>();\n  Scalar d = a.dot(b);\n  Scalar absD = internal::abs(d);\n\n  Scalar scale0;\n  Scalar scale1;\n\n  if (absD>=one)\n  {\n    scale0 = Scalar(1) - t;\n    scale1 = t;\n  }\n  else\n  {\n    // theta is the angle between the 2 quaternions\n    Scalar theta = std::acos(absD);\n    Scalar sinTheta = internal::sin(theta);\n\n    scale0 = internal::sin( ( Scalar(1) - t ) * theta) / sinTheta;\n    scale1 = internal::sin( ( t * theta) ) / sinTheta;\n    if (d<0)\n      scale1 = -scale1;\n  }\n\n  return Q(scale0 * a.coeffs() + scale1 * b.coeffs());\n}\n\ntemplate<typename T>\ninline T sin_over_x(T x)\n{\n  if (T(1) + x*x == T(1))\n    return T(1);\n  else\n    return std::sin(x)/x;\n}\n\ntemplate<typename Q>\nEIGEN_DONT_INLINE Q slerp_rw(const Q& a, const Q& b, typename Q::Scalar t)\n{\n  typedef typename Q::Scalar Scalar;\n\n  Scalar d = a.dot(b);\n  Scalar theta;\n  if (d<0.0)\n    theta = /*M_PI -*/ Scalar(2)*std::asin( (a.coeffs()+b.coeffs()).norm()/2 );\n  else\n    theta = Scalar(2)*std::asin( (a.coeffs()-b.coeffs()).norm()/2 );\n\n  // theta is the angle between the 2 quaternions\n//   Scalar theta = std::acos(absD);\n  Scalar sinOverTheta = sin_over_x(theta);\n\n  Scalar scale0 = (Scalar(1)-t)*sin_over_x( ( Scalar(1) - t ) * theta) / sinOverTheta;\n  Scalar scale1 = t * sin_over_x( ( t * theta) ) / sinOverTheta;\n  if (d<0)\n    scale1 = -scale1;\n\n  return Quaternion<Scalar>(scale0 * a.coeffs() + scale1 * b.coeffs());\n}\n\ntemplate<typename Q>\nEIGEN_DONT_INLINE Q slerp_gael(const Q& a, const Q& b, typename Q::Scalar t)\n{\n  typedef typename Q::Scalar Scalar;\n\n  Scalar d = a.dot(b);\n  Scalar theta;\n//   theta = Scalar(2) * atan2((a.coeffs()-b.coeffs()).norm(),(a.coeffs()+b.coeffs()).norm());\n//   if (d<0.0)\n//     theta = M_PI-theta;\n\n  if (d<0.0)\n    theta = /*M_PI -*/ Scalar(2)*std::asin( (-a.coeffs()-b.coeffs()).norm()/2 );\n  else\n    theta = Scalar(2)*std::asin( (a.coeffs()-b.coeffs()).norm()/2 );\n\n\n  Scalar scale0;\n  Scalar scale1;\n  if(theta*theta-Scalar(6)==-Scalar(6))\n  {\n    scale0 = Scalar(1) - t;\n    scale1 = t;\n  }\n  else\n  {\n    Scalar sinTheta = std::sin(theta);\n    scale0 = internal::sin( ( Scalar(1) - t ) * theta) / sinTheta;\n    scale1 = internal::sin( ( t * theta) ) / sinTheta;\n    if (d<0)\n      scale1 = -scale1;\n  }\n\n  return Quaternion<Scalar>(scale0 * a.coeffs() + scale1 * b.coeffs());\n}\n\nint main()\n{\n  typedef double RefScalar;\n  typedef float TestScalar;\n\n  typedef Quaternion<RefScalar>  Qd;\n  typedef Quaternion<TestScalar> Qf;\n\n  unsigned int g_seed = (unsigned int) time(NULL);\n  std::cout << g_seed << \"\\n\";\n//   g_seed = 1259932496;\n  srand(g_seed);\n\n  Matrix<RefScalar,Dynamic,1> maxerr(7);\n  maxerr.setZero();\n\n  Matrix<RefScalar,Dynamic,1> avgerr(7);\n  avgerr.setZero();\n\n  cout << \"double=>float=>double       nlerp        eigen        legacy(snap)         legacy(nlerp)        rightway         gael's criteria\\n\";\n\n  int rep = 100;\n  int iters = 40;\n  for (int w=0; w<rep; ++w)\n  {\n    Qf a, b;\n    a.coeffs().setRandom();\n    a.normalize();\n    b.coeffs().setRandom();\n    b.normalize();\n\n    Qf c[6];\n\n    Qd ar(a.cast<RefScalar>());\n    Qd br(b.cast<RefScalar>());\n    Qd cr;\n\n\n\n    cout.precision(8);\n    cout << std::scientific;\n    for (int i=0; i<iters; ++i)\n    {\n      RefScalar t = 0.65;\n      cr = slerp_rw(ar,br,t);\n\n      Qf refc = cr.cast<TestScalar>();\n      c[0] = nlerp(a,b,t);\n      c[1] = slerp_eigen(a,b,t);\n      c[2] = slerp_legacy(a,b,t);\n      c[3] = slerp_legacy_nlerp(a,b,t);\n      c[4] = slerp_rw(a,b,t);\n      c[5] = slerp_gael(a,b,t);\n\n      VectorXd err(7);\n      err[0] = (cr.coeffs()-refc.cast<RefScalar>().coeffs()).norm();\n//       std::cout << err[0] << \"    \";\n      for (int k=0; k<6; ++k)\n      {\n        err[k+1] = (c[k].coeffs()-refc.coeffs()).norm();\n//         std::cout << err[k+1] << \"    \";\n      }\n      maxerr = maxerr.cwise().max(err);\n      avgerr += err;\n//       std::cout << \"\\n\";\n      b = cr.cast<TestScalar>();\n      br = cr;\n    }\n//     std::cout << \"\\n\";\n  }\n  avgerr /= RefScalar(rep*iters);\n  cout << \"\\n\\nAccuracy:\\n\"\n       << \"  max: \" << maxerr.transpose() << \"\\n\";\n  cout << \"  avg: \" << avgerr.transpose() << \"\\n\";\n\n  // perf bench\n  Quaternionf a,b;\n  a.coeffs().setRandom();\n  a.normalize();\n  b.coeffs().setRandom();\n  b.normalize();\n  //b = a;\n  float s = 0.65;\n\n  #define BENCH(FUNC) {\\\n    BenchTimer t; \\\n    for(int k=0; k<2; ++k) {\\\n      t.start(); \\\n      for(int i=0; i<1000000; ++i) \\\n        FUNC(a,b,s); \\\n      t.stop(); \\\n    } \\\n    cout << \"  \" << #FUNC << \" => \\t \" << t.value() << \"s\\n\"; \\\n  }\n\n  cout << \"\\nSpeed:\\n\" << std::fixed;\n  BENCH(nlerp);\n  BENCH(slerp_eigen);\n  BENCH(slerp_legacy);\n  BENCH(slerp_legacy_nlerp);\n  BENCH(slerp_rw);\n  BENCH(slerp_gael);\n}\n", "meta": {"hexsha": "d715de75d2a229c3ce097abbbb16ef82f06516e8", "size": 5937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/quat_slerp.cpp", "max_stars_repo_name": "eundersander/bps-nav", "max_stars_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:17:14.000Z", "max_issues_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/quat_slerp.cpp", "max_issues_repo_name": "eundersander/bps-nav", "max_issues_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T21:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:46:40.000Z", "max_forks_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/quat_slerp.cpp", "max_forks_repo_name": "eundersander/bps-nav", "max_forks_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-27T17:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:00:06.000Z", "avg_line_length": 24.036437247, "max_line_length": 143, "alphanum_fraction": 0.577901297, "num_tokens": 1971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.6490432370815239}}
{"text": "#ifndef DEFINITIONS_CPP\r\n#define DEFINITIONS_CPP\r\n\r\n#include  <Eigen/Core>\r\n#include <bits/stdc++.h> \r\n#include <Eigen/SVD>\r\n#include  <iostream>\r\n#include <math.h>\r\n#include <assert.h>\r\n#include <time.h>\r\n#include <fstream>\r\n#include <random>\r\n#include <stdlib.h>\r\n#include <math.h>\r\n#include <vector>\r\n#include <iterator>\r\n#include <cstdlib>\r\n#include <unistd.h>\r\n\r\nusing  namespace  std;\r\nusing  namespace  Eigen;\r\ntypedef complex<double> cd; \r\n\r\n#define mat MatrixXd\r\n#define MIN 0.00001\r\n#define vec VectorXd\r\n\r\n\r\n// #define CROSSCHECK true\r\n#define CROSSCHECK false\r\n// #define DEBUG true\r\n#define DEBUG false\r\n\r\n\r\n#endif // DEFINITIONS_CPP\r\n", "meta": {"hexsha": "345a2014b762cf5e09da49faf0758fba26da1d29", "size": 648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "headers/definitions.cpp", "max_stars_repo_name": "mkbera/tensorsketch", "max_stars_repo_head_hexsha": "2be0a51291e32de815c21bff36571480eff0f363", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-09T01:32:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-11T04:58:11.000Z", "max_issues_repo_path": "headers/definitions.cpp", "max_issues_repo_name": "mkbera/tensorsketch", "max_issues_repo_head_hexsha": "2be0a51291e32de815c21bff36571480eff0f363", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "headers/definitions.cpp", "max_forks_repo_name": "mkbera/tensorsketch", "max_forks_repo_head_hexsha": "2be0a51291e32de815c21bff36571480eff0f363", "max_forks_repo_licenses": ["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": 29, "alphanum_fraction": 0.6944444444, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146847, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6490432314420402}}
{"text": "//\n// Created by hhy on 2022/3/11.\n//\n#include \"OsqpEigen/OsqpEigen.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\n\nint main() {\n  OsqpEigen::Solver solver;\n\n  // assert(InitMat(solver));\n  int numOfVar = 3;\n  int numOfCons = 4;\n\n  Eigen::SparseMatrix<double> hessian(numOfVar, numOfVar);\n  hessian.insert(0, 0) = 1;\n  hessian.insert(0, 1) = -1;\n  hessian.insert(0, 2) = 1;\n  hessian.insert(1, 0) = -1;\n  hessian.insert(1, 1) = 2;\n  hessian.insert(1, 2) = -2;\n  hessian.insert(2, 0) = 1;\n  hessian.insert(2, 1) = -2;\n  hessian.insert(2, 2) = 4;\n  std::cout << \"hessian:\" << hessian << std::endl;\n  /* hessian << 1, -1, 1,\n           -1, 2, -2,\n            1, -2, 4;*/\n\n  Eigen::SparseMatrix<double> linearMatrix(numOfCons, numOfVar);\n  linearMatrix.insert(0, 0) = 1;\n  linearMatrix.insert(1, 1) = 1;\n  linearMatrix.insert(2, 2) = 1;\n  linearMatrix.insert(3, 0) = 1;\n  linearMatrix.insert(3, 1) = 1;\n  linearMatrix.insert(3, 2) = 1;\n  std::cout << \" linearMatrix:\" << linearMatrix << std::endl;\n  /*linearMatrix << 1, 0, 0,\n                0, 1, 0,\n                0, 0, 1,\n                1, 1, 1;*/\n\n  Eigen::Vector3d gradient;\n  gradient << 2, -3, 1;\n  std::cout << \"gradient:\\n\" << gradient << std::endl;\n\n  Eigen::VectorXd lowerBound;\n  lowerBound.resize(4, 1);\n  lowerBound << 0, 0, 0, 0.4;\n  std::cout << \"lowerBound:\\n\" << lowerBound << std::endl;\n\n  Eigen::VectorXd upperBound;\n  upperBound.resize(4, 1);\n  upperBound << 1, 1, 1, 0.5;\n\n  solver.settings()->setVerbosity(true);\n  solver.settings()->setAlpha(1.0);\n\n  //  assert(solver.data()->setHessianMatrix(H_s)== true);\n  solver.data()->setNumberOfVariables(numOfVar);\n  solver.data()->setNumberOfConstraints(numOfCons);\n\n  assert(solver.data()->setHessianMatrix(hessian));\n  assert(solver.data()->setGradient(gradient));\n  assert(solver.data()->setLinearConstraintsMatrix(linearMatrix));\n  assert(solver.data()->setLowerBound(lowerBound));\n  assert(solver.data()->setUpperBound(upperBound));\n\n  assert(solver.initSolver());\n\n  // assert(solver.solve() == true);\n  assert(solver.solveProblem() == OsqpEigen::ErrorExitFlag::NoError);\n\n  std::cout << solver.getSolution() << std::endl;\n}", "meta": {"hexsha": "ee289d3df42a3f50ca5f13da8af23e16b8a52615", "size": 2167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "osqp_eigen/test/test_osqp2.cpp", "max_stars_repo_name": "HaiYangLib/Tools", "max_stars_repo_head_hexsha": "7cd6be3545574b8431bf404163d24202bda3e621", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "osqp_eigen/test/test_osqp2.cpp", "max_issues_repo_name": "HaiYangLib/Tools", "max_issues_repo_head_hexsha": "7cd6be3545574b8431bf404163d24202bda3e621", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "osqp_eigen/test/test_osqp2.cpp", "max_forks_repo_name": "HaiYangLib/Tools", "max_forks_repo_head_hexsha": "7cd6be3545574b8431bf404163d24202bda3e621", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1428571429, "max_line_length": 69, "alphanum_fraction": 0.6262113521, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6490230500020151}}
{"text": "/**\n * Copyright (C) Omar Thor <omarthoro@gmail.com> - All Rights Reserved\n * Unauthorized copying of this file, via any medium is strictly prohibited\n * Proprietary and confidential\n *\n * Written by Omar Thor <omarthoro@gmail.com>, 2017\n */\n#ifndef SP_ALGO_NN_LOSS_MEAN_SQUARE_ERROR_HPP\n#define SP_ALGO_NN_LOSS_MEAN_SQUARE_ERROR_HPP\n\n#include <boost/assert.hpp>\n#include \"../config.hpp\"\n#include \"../matrix.hpp\"\n#include \"../types.hpp\"\n#include \"sp/util/hints.hpp\"\n\n\nSP_ALGO_NN_NAMESPACE_BEGIN\n\n/**\n * \\brief Mean Square Error Derivative\n */\nstruct mean_square_error_derivative {\n\n    sp_hot void operator()(         const size_t& si,\n                                    const tensor_4& predicted,\n                                    const tensor_4& observed,\n                                    tensor_4& result) {\n\n        BOOST_ASSERT(predicted.dimensions() == observed.dimensions());\n\n        const size_t m = predicted.dimension(1) * predicted.dimension(2) * predicted.dimension(3);\n\n        float_t factor = float_t(2.0f) / static_cast<float_t> (m);\n\n        result.chip(si, 0) = factor * (predicted.chip(si, 0) - observed.chip(si, 0));\n    }\n};\n\n/**\n * \\brief Mean Square Error\n */\nstruct mean_square_error {\n\n    using derivative_type = mean_square_error_derivative;\n\n    auto operator()(                    const size_t& si,\n                                        const tensor_4& predicted,\n                                        const tensor_4& observed) {\n        BOOST_ASSERT(predicted.dimensions() == observed.dimensions());\n\n        tensor_0 d = (\n            (predicted.chip(si, 0) - observed.chip(si, 0))\n                *\n            (predicted.chip(si, 0) - observed.chip(si, 0))\n        ).sum();\n\n        return d(0) / static_cast<float_t> (predicted.size());\n    }\n\n    derivative_type derivative;\n};\n\n\nSP_ALGO_NN_NAMESPACE_END\n\n#endif\t/* SP_ALGO_NN_LOSS_MEAN_SQUARE_ERROR_HPP */\n\n", "meta": {"hexsha": "11629f3087f90757e21a3fe64923a2fce54717e2", "size": 1904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sp/algo/nn/loss/mean_square_error.hpp", "max_stars_repo_name": "thorigin/sp", "max_stars_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sp/algo/nn/loss/mean_square_error.hpp", "max_issues_repo_name": "thorigin/sp", "max_issues_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/sp/algo/nn/loss/mean_square_error.hpp", "max_forks_repo_name": "thorigin/sp", "max_forks_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5942028986, "max_line_length": 98, "alphanum_fraction": 0.6050420168, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6490230439631302}}
{"text": "/**\n * @file gmm_test.cpp\n * @author Ryan Curtin\n * @author Michael Fox\n *\n * Test for the Gaussian Mixture Model class.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/gmm/gmm.hpp>\n\n#include <mlpack/methods/gmm/no_constraint.hpp>\n#include <mlpack/methods/gmm/positive_definite_constraint.hpp>\n#include <mlpack/methods/gmm/diagonal_constraint.hpp>\n#include <mlpack/methods/gmm/eigenvalue_ratio_constraint.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::gmm;\n\nBOOST_AUTO_TEST_SUITE(GMMTest);\n/**\n * Test GMM::Probability() for a single observation for a few cases.\n */\nBOOST_AUTO_TEST_CASE(GMMProbabilityTest)\n{\n  // Create a GMM.\n  GMM gmm(2, 2);\n  gmm.Component(0) = distribution::GaussianDistribution(\"0 0\", \"1 0; 0 1\");\n  gmm.Component(1) = distribution::GaussianDistribution(\"3 3\", \"2 1; 1 2\");\n  gmm.Weights() = \"0.3 0.7\";\n\n  // Now test a couple observations.  These comparisons are calculated by hand.\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"0 0\"), 0.05094887202, 1e-5);\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"1 1\"), 0.03451996667, 1e-5);\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"2 2\"), 0.04696302254, 1e-5);\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"3 3\"), 0.06432759685, 1e-5);\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"-1 5.3\"), 2.503171278804e-6, 1e-5);\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"1.4 0\"), 0.024676682176, 1e-5);\n}\n\n/**\n * Test GMM::Probability() for a single observation being from a particular\n * component.\n */\nBOOST_AUTO_TEST_CASE(GMMProbabilityComponentTest)\n{\n  // Create a GMM (same as the last test).\n  GMM gmm(2, 2);\n  gmm.Component(0) = distribution::GaussianDistribution(\"0 0\", \"1 0; 0 1\");\n  gmm.Component(1) = distribution::GaussianDistribution(\"3 3\", \"2 1; 1 2\");\n  gmm.Weights() = \"0.3 0.7\";\n\n  // Now test a couple observations.  These comparisons are calculated by hand.\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"0 0\", 0), 0.0477464829276, 1e-5);\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"0 0\", 1), 0.0032023890978, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"1 1\", 0), 0.0175649494573, 1e-5);\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"1 1\", 1), 0.0169550172159, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"2 2\", 0), 8.7450733951e-4, 1e-5);\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"2 2\", 1), 0.0460885151993, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"3 3\", 0), 5.8923841039e-6, 1e-5);\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"3 3\", 1), 0.0643217044658, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"-1 5.3\", 0), 2.30212100302e-8, 1e-5);\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"-1 5.3\", 1), 2.48015006877e-6, 1e-5);\n\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"1.4 0\", 0), 0.0179197849738, 1e-5);\n  BOOST_REQUIRE_CLOSE(gmm.Probability(\"1.4 0\", 1), 0.0067568972024, 1e-5);\n}\n\n/**\n * Test training a model on only one Gaussian (randomly generated) in two\n * dimensions.  We will vary the dataset size from small to large.  The EM\n * algorithm is used for training the GMM.\n */\nBOOST_AUTO_TEST_CASE(GMMTrainEMOneGaussian)\n{\n  for (size_t iterations = 0; iterations < 4; iterations++)\n  {\n    // Determine random covariance and mean.\n    arma::vec mean;\n    mean.randu(2);\n    arma::vec covar;\n    covar.randu(2);\n\n    arma::mat data;\n    data.randn(2 /* dimension */, 150 * pow(10, (iterations / 3.0)));\n\n    // Now apply mean and covariance.\n    data.row(0) *= covar(0);\n    data.row(1) *= covar(1);\n\n    data.row(0) += mean(0);\n    data.row(1) += mean(1);\n\n    // Now, train the model.\n    GMM gmm(1, 2);\n    gmm.Train(data, 10);\n\n    arma::vec actualMean = arma::mean(data, 1);\n    arma::mat actualCovar = ccov(data, 1 /* biased estimator */);\n\n    // Check the model to see that it is correct.\n    CheckMatrices(gmm.Component(0).Mean(), actualMean);\n    CheckMatrices(gmm.Component(0).Covariance(), actualCovar);\n\n    BOOST_REQUIRE_CLOSE(gmm.Weights()[0], 1.0, 1e-5);\n  }\n}\n\n/**\n * Test a training model on multiple Gaussians in higher dimensionality than\n * two.  We will hold the dataset size constant at 10k points.  The EM algorithm\n * is used for training the GMM.\n */\nBOOST_AUTO_TEST_CASE(GMMTrainEMMultipleGaussians)\n{\n  // Higher dimensionality gives us a greater chance of having separated\n  // Gaussians.\n  size_t dims = 8;\n  size_t gaussians = 3;\n\n  // Generate dataset.\n  arma::mat data;\n  data.zeros(dims, 500);\n\n  std::vector<arma::vec> means(gaussians);\n  std::vector<arma::mat> covars(gaussians);\n  arma::vec weights(gaussians);\n  arma::Col<size_t> counts(gaussians);\n\n  // Choose weights randomly.\n  weights.zeros();\n  while (weights.min() < 0.02)\n  {\n    weights.randu(gaussians);\n    weights /= accu(weights);\n  }\n\n  for (size_t i = 0; i < gaussians; i++)\n    counts[i] = round(weights[i] * (data.n_cols - gaussians));\n  // Ensure one point minimum in each.\n  counts += 1;\n\n  // Account for rounding errors (possibly necessary).\n  counts[gaussians - 1] += (data.n_cols - arma::accu(counts));\n\n  // Build each Gaussian individually.\n  size_t point = 0;\n  for (size_t i = 0; i < gaussians; i++)\n  {\n    arma::mat gaussian;\n    gaussian.randn(dims, counts[i]);\n\n    // Randomly generate mean and covariance.\n    means[i].randu(dims);\n    means[i] -= 0.5;\n    means[i] *= 50;\n\n    // We need to make sure the covariance is positive definite.  We will take a\n    // random matrix C and then set our covariance to 4 * C * C', which will be\n    // positive semidefinite.\n    covars[i].randu(dims, dims);\n    covars[i] *= 4 * trans(covars[i]);\n\n    data.cols(point, point + counts[i] - 1) = (covars[i] * gaussian + means[i]\n        * arma::ones<arma::rowvec>(counts[i]));\n\n    // Calculate the actual means and covariances because they will probably\n    // be different (this is easier to do before we shuffle the points).\n    means[i] = arma::mean(data.cols(point, point + counts[i] - 1), 1);\n    covars[i] = ccov(data.cols(point, point + counts[i] - 1), 1 /* biased */);\n\n    point += counts[i];\n  }\n\n  // Calculate actual weights.\n  for (size_t i = 0; i < gaussians; i++)\n    weights[i] = (double) counts[i] / data.n_cols;\n\n  // Now train the model.\n  GMM gmm(gaussians, dims);\n  gmm.Train(data, 10);\n\n  arma::uvec sortRef = sort_index(weights);\n  arma::uvec sortTry = sort_index(gmm.Weights());\n\n  // Check the model to see that it is correct.\n  for (size_t i = 0; i < gaussians; i++)\n  {\n    // Check the mean.\n    CheckMatrices(gmm.Component(sortTry[i]).Mean(), means[sortRef[i]], 1e-3);\n    // Check the covariance.\n    CheckMatrices(gmm.Component(sortTry[i]).Covariance(), covars[sortRef[i]],\n                  0.05);\n    // Check the weight.\n    BOOST_REQUIRE_CLOSE(gmm.Weights()[sortTry[i]], weights[sortRef[i]],\n        0.001);\n  }\n}\n\n/**\n * Train a single-gaussian mixture, but using the overload of Train() where\n * probabilities of the observation are given.\n */\nBOOST_AUTO_TEST_CASE(GMMTrainEMSingleGaussianWithProbability)\n{\n  // Generate observations from a Gaussian distribution.\n  distribution::GaussianDistribution d(\"0.5 1.0\", \"1.0 0.3; 0.3 1.0\");\n\n  // 10000 observations, each with random probability.\n  arma::mat observations(2, 20000);\n  for (size_t i = 0; i < 20000; i++)\n    observations.col(i) = d.Random();\n  arma::vec probabilities;\n  probabilities.randu(20000); // Random probabilities.\n\n  // Now train the model.\n  GMM g(1, 2);\n  g.Train(observations, probabilities, 10);\n\n  // Check that it is trained correctly.  5% tolerance because of random error\n  // present in observations.\n  BOOST_REQUIRE_CLOSE(g.Component(0).Mean()[0], 0.5, 5.0);\n  BOOST_REQUIRE_CLOSE(g.Component(0).Mean()[1], 1.0, 5.0);\n\n  // 6% tolerance on the large numbers, 10% on the smaller numbers.\n  BOOST_REQUIRE_CLOSE(g.Component(0).Covariance()(0, 0), 1.0, 6.0);\n  BOOST_REQUIRE_CLOSE(g.Component(0).Covariance()(0, 1), 0.3, 10.0);\n  BOOST_REQUIRE_CLOSE(g.Component(0).Covariance()(1, 0), 0.3, 10.0);\n  BOOST_REQUIRE_CLOSE(g.Component(0).Covariance()(1, 1), 1.0, 6.0);\n\n  BOOST_REQUIRE_CLOSE(g.Weights()[0], 1.0, 1e-5);\n}\n\n/**\n * Train a multi-Gaussian mixture, using the overload of Train() where\n * probabilities of the observation are given.\n */\nBOOST_AUTO_TEST_CASE(GMMTrainEMMultipleGaussiansWithProbability)\n{\n  // We'll have three Gaussian distributions from this mixture, and one Gaussian\n  // not from this mixture (but we'll put some observations from it in).\n  distribution::GaussianDistribution d1(\"0.0 1.0 0.0\", \"1.0 0.0 0.5;\"\n                                                       \"0.0 0.8 0.1;\"\n                                                       \"0.5 0.1 1.0\");\n  distribution::GaussianDistribution d2(\"2.0 -1.0 5.0\", \"3.0 0.0 0.5;\"\n                                                        \"0.0 1.2 0.2;\"\n                                                        \"0.5 0.2 1.3\");\n  distribution::GaussianDistribution d3(\"0.0 5.0 -3.0\", \"2.0 0.0 0.0;\"\n                                                        \"0.0 0.3 0.0;\"\n                                                        \"0.0 0.0 1.0\");\n  distribution::GaussianDistribution d4(\"4.0 2.0 2.0\", \"1.5 0.6 0.5;\"\n                                                       \"0.6 1.1 0.1;\"\n                                                       \"0.5 0.1 1.0\");\n\n  // Now we'll generate points and probabilities.  1500 points.  Slower than I\n  // would like...\n  arma::mat points(3, 5000);\n  arma::vec probabilities(5000);\n\n  for (size_t i = 0; i < 5000; i++)\n  {\n    double randValue = math::Random();\n\n    if (randValue <= 0.20) // p(d1) = 0.20\n      points.col(i) = d1.Random();\n    else if (randValue <= 0.50) // p(d2) = 0.30\n      points.col(i) = d2.Random();\n    else if (randValue <= 0.90) // p(d3) = 0.40\n      points.col(i) = d3.Random();\n    else // p(d4) = 0.10\n      points.col(i) = d4.Random();\n\n    // Set the probability right.  If it came from this mixture, it should be\n    // 0.97 plus or minus a little bit of noise.  If not, then it should be 0.03\n    // plus or minus a little bit of noise.  The base probability (minus the\n    // noise) is parameterizable for easy modification of the test.\n    double confidence = 0.998;\n    double perturbation = math::Random(-0.002, 0.002);\n\n    if (randValue <= 0.90)\n      probabilities(i) = confidence + perturbation;\n    else\n      probabilities(i) = (1 - confidence) + perturbation;\n  }\n\n  // Now train the model.\n  GMM g(3, 3); // 3 dimensions, 3 components (the fourth component is fake).\n\n  g.Train(points, probabilities, 8);\n\n  // Now check the results.  We need to order by weights so that when we do the\n  // checking, things will be correct.\n  arma::uvec sortedIndices = sort_index(g.Weights());\n\n  // The tolerances in our checks are quite large, but it is good to remember\n  // that we introduced a fair amount of random noise into this whole process.\n  // We don't need to look for the fourth Gaussian since that is not supposed to\n  // be a part of this mixture.\n\n  // First Gaussian (d1).\n  BOOST_REQUIRE_SMALL(g.Weights()[sortedIndices[0]] - 0.2, 0.1);\n\n  for (size_t i = 0; i < 3; i++)\n    BOOST_REQUIRE_SMALL((g.Component(sortedIndices[0]).Mean()[i]\n        - d1.Mean()[i]), 0.4);\n\n  for (size_t row = 0; row < 3; row++)\n    for (size_t col = 0; col < 3; col++)\n      BOOST_REQUIRE_SMALL((g.Component(sortedIndices[0]).Covariance()(row, col)\n          - d1.Covariance()(row, col)), 0.7); // Big tolerance!  Lots of noise.\n\n  // Second Gaussian (d2).\n  BOOST_REQUIRE_SMALL(g.Weights()[sortedIndices[1]] - 0.3, 0.1);\n\n  for (size_t i = 0; i < 3; i++)\n    BOOST_REQUIRE_SMALL((g.Component(sortedIndices[1]).Mean()[i]\n        - d2.Mean()[i]), 0.4);\n\n  for (size_t row = 0; row < 3; row++)\n    for (size_t col = 0; col < 3; col++)\n      BOOST_REQUIRE_SMALL((g.Component(sortedIndices[1]).Covariance()(row, col)\n          - d2.Covariance()(row, col)), 0.7); // Big tolerance!  Lots of noise.\n\n  // Third Gaussian (d3).\n  BOOST_REQUIRE_SMALL(g.Weights()[sortedIndices[2]] - 0.4, 0.1);\n\n  for (size_t i = 0; i < 3; ++i)\n    BOOST_REQUIRE_SMALL((g.Component(sortedIndices[2]).Mean()[i]\n        - d3.Mean()[i]), 0.4);\n\n  for (size_t row = 0; row < 3; ++row)\n    for (size_t col = 0; col < 3; ++col)\n      BOOST_REQUIRE_SMALL((g.Component(sortedIndices[2]).Covariance()(row, col)\n          - d3.Covariance()(row, col)), 0.7);\n}\n\n/**\n * Make sure generating observations randomly works.  We'll do this by\n * generating a bunch of random observations and then re-training on them, and\n * hope that our model is the same.\n */\nBOOST_AUTO_TEST_CASE(GMMRandomTest)\n{\n  // Simple GMM distribution.\n  GMM gmm(2, 2);\n  gmm.Weights() = arma::vec(\"0.40 0.60\");\n\n  // N([2.25 3.10], [1.00 0.20; 0.20 0.89])\n  gmm.Component(0) = distribution::GaussianDistribution(\"2.25 3.10\",\n      \"1.00 0.60; 0.60 0.89\");\n\n\n  // N([4.10 1.01], [1.00 0.00; 0.00 1.01])\n  gmm.Component(1) = distribution::GaussianDistribution(\"4.10 1.01\",\n      \"1.00 0.70; 0.70 1.01\");\n\n  // Now generate a bunch of observations.\n  arma::mat observations(2, 4000);\n  for (size_t i = 0; i < 4000; i++)\n    observations.col(i) = gmm.Random();\n\n  // A new one which we'll train.\n  GMM gmm2(2, 2);\n  gmm2.Train(observations, 10);\n\n  // Now check the results.  We need to order by weights so that when we do the\n  // checking, things will be correct.\n  arma::uvec sortedIndices = sort_index(gmm2.Weights());\n\n  // Now check that the parameters are the same.  Tolerances are kind of big\n  // because we only used 2000 observations.\n  BOOST_REQUIRE_CLOSE(gmm.Weights()[0], gmm2.Weights()[sortedIndices[0]], 7.0);\n  BOOST_REQUIRE_CLOSE(gmm.Weights()[1], gmm2.Weights()[sortedIndices[1]], 7.0);\n\n  BOOST_REQUIRE_CLOSE(gmm.Component(0).Mean()[0],\n      gmm2.Component(sortedIndices[0]).Mean()[0], 7.5);\n  BOOST_REQUIRE_CLOSE(gmm.Component(0).Mean()[1],\n      gmm2.Component(sortedIndices[0]).Mean()[1], 7.5);\n\n  BOOST_REQUIRE_CLOSE(gmm.Component(0).Covariance()(0, 0),\n      gmm2.Component(sortedIndices[0]).Covariance()(0, 0), 13.0);\n  BOOST_REQUIRE_CLOSE(gmm.Component(0).Covariance()(0, 1),\n      gmm2.Component(sortedIndices[0]).Covariance()(0, 1), 22.0);\n  BOOST_REQUIRE_CLOSE(gmm.Component(0).Covariance()(1, 0),\n      gmm2.Component(sortedIndices[0]).Covariance()(1, 0), 22.0);\n  BOOST_REQUIRE_CLOSE(gmm.Component(0).Covariance()(1, 1),\n      gmm2.Component(sortedIndices[0]).Covariance()(1, 1), 13.0);\n\n  BOOST_REQUIRE_CLOSE(gmm.Component(1).Mean()[0],\n      gmm2.Component(sortedIndices[1]).Mean()[0], 7.5);\n  BOOST_REQUIRE_CLOSE(gmm.Component(1).Mean()[1],\n      gmm2.Component(sortedIndices[1]).Mean()[1], 7.5);\n\n  BOOST_REQUIRE_CLOSE(gmm.Component(1).Covariance()(0, 0),\n      gmm2.Component(sortedIndices[1]).Covariance()(0, 0), 13.0);\n  BOOST_REQUIRE_CLOSE(gmm.Component(1).Covariance()(0, 1),\n      gmm2.Component(sortedIndices[1]).Covariance()(0, 1), 22.0);\n  BOOST_REQUIRE_CLOSE(gmm.Component(1).Covariance()(1, 0),\n      gmm2.Component(sortedIndices[1]).Covariance()(1, 0), 22.0);\n  BOOST_REQUIRE_CLOSE(gmm.Component(1).Covariance()(1, 1),\n      gmm2.Component(sortedIndices[1]).Covariance()(1, 1), 13.0);\n}\n\n/**\n * Test classification of observations by component.\n */\nBOOST_AUTO_TEST_CASE(GMMClassifyTest)\n{\n  // First create a Gaussian with a few components.\n  GMM gmm(3, 2);\n  gmm.Component(0) = distribution::GaussianDistribution(\"0 0\", \"1 0; 0 1\");\n  gmm.Component(1) = distribution::GaussianDistribution(\"1 3\", \"3 2; 2 3\");\n  gmm.Component(2) = distribution::GaussianDistribution(\"-2 -2\",\n      \"2.2 1.4; 1.4 5.1\");\n  gmm.Weights() = \"0.6 0.25 0.15\";\n\n  arma::mat observations = arma::trans(arma::mat(\n    \" 0  0;\"\n    \" 0  1;\"\n    \" 0  2;\"\n    \" 1 -2;\"\n    \" 2 -2;\"\n    \"-2  0;\"\n    \" 5  5;\"\n    \"-2 -2;\"\n    \" 3  3;\"\n    \"25 25;\"\n    \"-1 -1;\"\n    \"-3 -3;\"\n    \"-5  1\"));\n\n  arma::Row<size_t> classes;\n\n  gmm.Classify(observations, classes);\n\n  // Test classification of points.  Classifications produced by hand.\n  BOOST_REQUIRE_EQUAL(classes[ 0], 0);\n  BOOST_REQUIRE_EQUAL(classes[ 1], 0);\n  BOOST_REQUIRE_EQUAL(classes[ 2], 1);\n  BOOST_REQUIRE_EQUAL(classes[ 3], 0);\n  BOOST_REQUIRE_EQUAL(classes[ 4], 0);\n  BOOST_REQUIRE_EQUAL(classes[ 5], 0);\n  BOOST_REQUIRE_EQUAL(classes[ 6], 1);\n  BOOST_REQUIRE_EQUAL(classes[ 7], 2);\n  BOOST_REQUIRE_EQUAL(classes[ 8], 1);\n  BOOST_REQUIRE_EQUAL(classes[ 9], 1);\n  BOOST_REQUIRE_EQUAL(classes[10], 0);\n  BOOST_REQUIRE_EQUAL(classes[11], 2);\n  BOOST_REQUIRE_EQUAL(classes[12], 2);\n}\n\nBOOST_AUTO_TEST_CASE(GMMLoadSaveTest)\n{\n  // Create a GMM, save it, and load it.\n  GMM gmm(10, 4);\n  gmm.Weights().randu();\n\n  for (size_t i = 0; i < gmm.Gaussians(); ++i)\n  {\n    gmm.Component(i).Mean().randu();\n    arma::mat covariance = arma::randu<arma::mat>(\n        gmm.Component(i).Covariance().n_rows,\n        gmm.Component(i).Covariance().n_cols);\n    covariance *= covariance.t();\n    covariance += arma::eye<arma::mat>(covariance.n_rows, covariance.n_cols);\n    gmm.Component(i).Covariance(std::move(covariance));\n  }\n\n  // Save the GMM.\n  {\n    std::ofstream ofs(\"test-gmm-save.xml\");\n    boost::archive::xml_oarchive ar(ofs);\n    ar << data::CreateNVP(gmm, \"gmm\");\n  }\n\n  // Load the GMM.\n  GMM gmm2;\n  {\n    std::ifstream ifs(\"test-gmm-save.xml\");\n    boost::archive::xml_iarchive ar(ifs);\n    ar >> data::CreateNVP(gmm2, \"gmm\");\n  }\n\n  // Remove clutter.\n  //remove(\"test-gmm-save.xml\");\n\n  BOOST_REQUIRE_EQUAL(gmm.Gaussians(), gmm2.Gaussians());\n  BOOST_REQUIRE_EQUAL(gmm.Dimensionality(), gmm2.Dimensionality());\n\n  for (size_t i = 0; i < gmm.Dimensionality(); ++i)\n    BOOST_REQUIRE_CLOSE(gmm.Weights()[i], gmm2.Weights()[i], 1e-3);\n\n  for (size_t i = 0; i < gmm.Gaussians(); ++i)\n  {\n    for (size_t j = 0; j < gmm.Dimensionality(); ++j)\n      BOOST_REQUIRE_CLOSE(gmm.Component(i).Mean()[j],\n          gmm2.Component(i).Mean()[j], 1e-3);\n\n    for (size_t j = 0; j < gmm.Dimensionality(); ++j)\n    {\n      for (size_t k = 0; k < gmm.Dimensionality(); ++k)\n      {\n        BOOST_REQUIRE_CLOSE(gmm.Component(i).Covariance()(j, k),\n            gmm2.Component(i).Covariance()(j, k), 1e-3);\n      }\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(NoConstraintTest)\n{\n  // Generate random matrices and make sure they end up the same.\n  for (size_t i = 0; i < 30; ++i)\n  {\n    const size_t rows = 5 + math::RandInt(100);\n    const size_t cols = 5 + math::RandInt(100);\n    arma::mat cov(rows, cols);\n    cov.randu();\n    arma::mat newcov(cov);\n\n    NoConstraint::ApplyConstraint(newcov);\n\n    for (size_t j = 0; j < cov.n_elem; ++j)\n      BOOST_REQUIRE_CLOSE(newcov(j), cov(j), 1e-20);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(PositiveDefiniteConstraintTest)\n{\n  // Make sure matrices are made to be positive definite, or more specifically,\n  // that they can be Cholesky decomposed.\n  for (size_t i = 0; i < 30; ++i)\n  {\n    const size_t elem = 5 + math::RandInt(50);\n    arma::mat cov(elem, elem);\n    cov.randu();\n\n    PositiveDefiniteConstraint::ApplyConstraint(cov);\n\n    arma::mat c;\n    #if (ARMA_VERSION_MAJOR < 4) || \\\n        ((ARMA_VERSION_MAJOR == 4) && (ARMA_VERSION_MINOR < 500))\n    BOOST_REQUIRE(arma::chol(c, cov));\n    #else\n    BOOST_REQUIRE(arma::chol(c, cov, \"lower\"));\n    #endif\n\n  }\n}\n\nBOOST_AUTO_TEST_CASE(DiagonalConstraintTest)\n{\n  // Make sure matrices are made to be positive definite.\n  for (size_t i = 0; i < 30; ++i)\n  {\n    const size_t elem = 5 + math::RandInt(50);\n    arma::mat cov(elem, elem);\n    cov.randu();\n\n    DiagonalConstraint::ApplyConstraint(cov);\n\n    for (size_t j = 0; j < elem; ++j)\n      for (size_t k = 0; k < elem; ++k)\n        if (j != k)\n          BOOST_REQUIRE_SMALL(cov(j, k), 1e-50);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(EigenvalueRatioConstraintTest)\n{\n  // Generate a list of eigenvalue ratios.\n  arma::vec ratios(\"1.0 0.7 0.4 0.2 0.1 0.1 0.05 0.01\");\n  EigenvalueRatioConstraint erc(ratios);\n\n  // Now make some random matrices and see if the constraint works.\n  for (size_t i = 0; i < 30; ++i)\n  {\n    arma::mat cov(8, 8);\n    cov.randu();\n\n    erc.ApplyConstraint(cov);\n\n    // Decompose the matrix and make sure things are right.\n    arma::vec eigenvalues = arma::eig_sym(cov);\n\n    for (size_t i = 0; i < eigenvalues.n_elem; ++i)\n      BOOST_REQUIRE_CLOSE(eigenvalues[i] / eigenvalues[0], ratios[i], 1e-5);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(UseExistingModelTest)\n{\n  // If we run a GMM and it converges, then if we run it again using the\n  // converged results as the starting point, then it should terminate after one\n  // iteration and give basically the same results.\n\n  // Higher dimensionality gives us a greater chance of having separated\n  // Gaussians.\n  size_t dims = 8;\n  size_t gaussians = 3;\n\n  // Generate dataset.\n  arma::mat data;\n  data.zeros(dims, 500);\n\n  std::vector<arma::vec> means(gaussians);\n  std::vector<arma::mat> covars(gaussians);\n  arma::vec weights(gaussians);\n  arma::Col<size_t> counts(gaussians);\n\n  // Choose weights randomly.\n  weights.zeros();\n  while (weights.min() < 0.02)\n  {\n    weights.randu(gaussians);\n    weights /= accu(weights);\n  }\n\n  for (size_t i = 0; i < gaussians; i++)\n    counts[i] = round(weights[i] * (data.n_cols - gaussians));\n  // Ensure one point minimum in each.\n  counts += 1;\n\n  // Account for rounding errors (possibly necessary).\n  counts[gaussians - 1] += (data.n_cols - arma::accu(counts));\n\n  // Build each Gaussian individually.\n  size_t point = 0;\n  for (size_t i = 0; i < gaussians; i++)\n  {\n    arma::mat gaussian;\n    gaussian.randn(dims, counts[i]);\n\n    // Randomly generate mean and covariance.\n    means[i].randu(dims);\n    means[i] -= 0.5;\n    means[i] *= 50;\n\n    // We need to make sure the covariance is positive definite.  We will take a\n    // random matrix C and then set our covariance to 4 * C * C', which will be\n    // positive semidefinite.\n    covars[i].randu(dims, dims);\n    covars[i] *= 4 * trans(covars[i]);\n\n    data.cols(point, point + counts[i] - 1) = (covars[i] * gaussian + means[i]\n        * arma::ones<arma::rowvec>(counts[i]));\n\n    // Calculate the actual means and covariances because they will probably\n    // be different (this is easier to do before we shuffle the points).\n    means[i] = arma::mean(data.cols(point, point + counts[i] - 1), 1);\n    covars[i] = ccov(data.cols(point, point + counts[i] - 1), 1 /* biased */);\n\n    point += counts[i];\n  }\n\n  // Calculate actual weights.\n  for (size_t i = 0; i < gaussians; i++)\n    weights[i] = (double) counts[i] / data.n_cols;\n\n  // Now train the model.\n  GMM gmm(gaussians, dims);\n  gmm.Train(data, 10);\n\n  GMM oldgmm(gmm);\n\n  // Retrain the model with the existing model as the starting point.\n  gmm.Train(data, 1, true);\n\n  // Check for similarity.\n  for (size_t i = 0; i < gmm.Gaussians(); ++i)\n  {\n    BOOST_REQUIRE_CLOSE(gmm.Weights()[i], oldgmm.Weights()[i], 1e-4);\n\n    for (size_t j = 0; j < gmm.Dimensionality(); ++j)\n    {\n      BOOST_REQUIRE_CLOSE(gmm.Component(i).Mean()[j],\n                          oldgmm.Component(i).Mean()[j], 1e-3);\n\n      for (size_t k = 0; k < gmm.Dimensionality(); ++k)\n        BOOST_REQUIRE_CLOSE(gmm.Component(i).Covariance()(j, k),\n                            oldgmm.Component(i).Covariance()(j, k), 1e-3);\n    }\n  }\n\n  // Do it again, with a larger number of trials.\n  gmm = oldgmm;\n\n  // Retrain the model with the existing model as the starting point.\n  gmm.Train(data, 10, true);\n\n  // Check for similarity.\n  for (size_t i = 0; i < gmm.Gaussians(); ++i)\n  {\n    BOOST_REQUIRE_CLOSE(gmm.Weights()[i], oldgmm.Weights()[i], 1e-4);\n\n    for (size_t j = 0; j < gmm.Dimensionality(); ++j)\n    {\n      BOOST_REQUIRE_CLOSE(gmm.Component(i).Mean()[j],\n                          oldgmm.Component(i).Mean()[j], 1e-3);\n\n      for (size_t k = 0; k < gmm.Dimensionality(); ++k)\n        BOOST_REQUIRE_CLOSE(gmm.Component(i).Covariance()(j, k),\n                            oldgmm.Component(i).Covariance()(j, k), 1e-3);\n    }\n  }\n\n  // Do it again, but using the overload of Train() that takes probabilities\n  // into account.\n  arma::vec probabilities(data.n_cols);\n  probabilities.ones(); // Fill with ones.\n\n  gmm = oldgmm;\n  gmm.Train(data, probabilities, 1, true);\n\n  // Check for similarity.\n  for (size_t i = 0; i < gmm.Gaussians(); ++i)\n  {\n    BOOST_REQUIRE_CLOSE(gmm.Weights()[i], oldgmm.Weights()[i], 1e-4);\n\n    for (size_t j = 0; j < gmm.Dimensionality(); ++j)\n    {\n      BOOST_REQUIRE_CLOSE(gmm.Component(i).Mean()[j],\n          oldgmm.Component(i).Mean()[j], 1e-3);\n\n      for (size_t k = 0; k < gmm.Dimensionality(); ++k)\n        BOOST_REQUIRE_CLOSE(gmm.Component(i).Covariance()(j, k),\n                            oldgmm.Component(i).Covariance()(j, k), 1e-3);\n    }\n  }\n\n  // One more time, with multiple trials.\n  gmm = oldgmm;\n  gmm.Train(data, probabilities, 10, true);\n\n  // Check for similarity.\n  for (size_t i = 0; i < gmm.Gaussians(); ++i)\n  {\n    BOOST_REQUIRE_CLOSE(gmm.Weights()[i], oldgmm.Weights()[i], 1e-4);\n\n    for (size_t j = 0; j < gmm.Dimensionality(); ++j)\n    {\n      BOOST_REQUIRE_CLOSE(gmm.Component(i).Mean()[j],\n          oldgmm.Component(i).Mean()[j], 1e-3);\n\n      for (size_t k = 0; k < gmm.Dimensionality(); ++k)\n        BOOST_REQUIRE_CLOSE(gmm.Component(i).Covariance()(j, k),\n                            oldgmm.Component(i).Covariance()(j, k), 1e-3);\n    }\n  }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "28a1dfcb7b87b14cb9d8e90ea76befc1727e67ae", "size": 25294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/gmm_test.cpp", "max_stars_repo_name": "NaxAlpha/mlpack-build", "max_stars_repo_head_hexsha": "1f0c1454d4b35eb97ff115669919c205cee5bd1c", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-21T11:08:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:52:14.000Z", "max_issues_repo_path": "src/mlpack/tests/gmm_test.cpp", "max_issues_repo_name": "okmegy/Mlpack", "max_issues_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/gmm_test.cpp", "max_forks_repo_name": "okmegy/Mlpack", "max_forks_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0208877285, "max_line_length": 80, "alphanum_fraction": 0.6326401518, "num_tokens": 7984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6489905095615893}}
{"text": "#ifndef QATUX_GENERAL\n#define QATUX_GENERAL\n\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <Eigen/KroneckerProduct>\n#include <bitset>\n#include <cmath>\n#include <random>\n#include <assert.h>\n\nnamespace Qatux {\n    template<typename T = float>\n    using Complex = std::complex<T>;\n\n    template<typename T = float>\n    using Vector = Eigen::Matrix<Complex<T>, Eigen::Dynamic, 1>;\n\n    template<typename T = float>\n    using Matrix = Eigen::SparseMatrix<Complex<T>>;\n\n    int pow2(int exp);\n    void printBin(int N, int BITS);\n\n    //return |0>\n    template<typename T = float>\n    Vector<T> zero(void);\n\n    //return |1>\n    template<typename T = float>\n    Vector<T> one(void);\n\n    template<typename T = float>\n    Matrix<T> identityGate(int NQUBITS);\n\n    //returns |N> for a space of size NQUBITS\n    template<typename T = float>\n    Vector<T> basis(int N, int NQUBITS);\n}\n\n#endif\n", "meta": {"hexsha": "9e61613e251216fae942ebba32659540dbaa0fcf", "size": 892, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/general.hpp", "max_stars_repo_name": "RobertZ2011/qatux", "max_stars_repo_head_hexsha": "150ec5df6f719a71e603a1aea79a3b3bfbf0667e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/general.hpp", "max_issues_repo_name": "RobertZ2011/qatux", "max_issues_repo_head_hexsha": "150ec5df6f719a71e603a1aea79a3b3bfbf0667e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/general.hpp", "max_forks_repo_name": "RobertZ2011/qatux", "max_forks_repo_head_hexsha": "150ec5df6f719a71e603a1aea79a3b3bfbf0667e", "max_forks_repo_licenses": ["BSD-3-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.2380952381, "max_line_length": 64, "alphanum_fraction": 0.66367713, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6489905050758983}}
{"text": "//\n// Created by lei on 4/22/19.\n//\n\n#include \"catch.hpp\"\n\n#include \"tgo.hpp\"\n\n#include <armadillo>\n#include <vector>\n#include <cmath>\n#include <functional>\n#include <fmt/format.h>\n\nint count = 0;\n\ndouble func(double x) {\n    count += 1;\n    return std::pow(x - 0.5, 2);\n}\n\nTEST_CASE(\"x^2\", \"[tgo]\") {\n    int nsample = 1e2;\n    int nk = 4;\n    double xmin = -1.0;\n    double xmax = 1.0;\n    double xtol = 1.0e-7;\n    TGO tgo(func, nsample, nk, xmin, xmax, xtol);\n    OptimizeResult result = tgo.optimize();\n    fmt::print(\"count: {:d}\\n\", count);\n    REQUIRE(result.x == Approx(0.5));\n}\n", "meta": {"hexsha": "97017f9b3c273f33048aa1248606d7e5fcc7ca24", "size": 588, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_tgo.cc", "max_stars_repo_name": "pan3rock/tgo1d-cxx", "max_stars_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_tgo.cc", "max_issues_repo_name": "pan3rock/tgo1d-cxx", "max_issues_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_tgo.cc", "max_forks_repo_name": "pan3rock/tgo1d-cxx", "max_forks_repo_head_hexsha": "9553b48279c918e0f19ca3a22538caf1a2eff296", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8181818182, "max_line_length": 49, "alphanum_fraction": 0.5867346939, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6489730489267699}}
{"text": "// Boost.GIL (Generic Image Library) - tests\n//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include <boost/gil/point.hpp>\n#include <cmath>\n#include <cstddef>\n\nnamespace boost\n{\nnamespace gil\n{\n/// \\defgroup Rasterization\n/// \\brief A set of functions to rasterize shapes\n///\n/// Due to images being discrete, most shapes require specialized algorithms to\n/// handle rasterization efficiently and solve problem of connectivity and being\n/// close to the original shape.\n\n/// \\defgroup LineRasterization\n/// \\ingroup Rasterization\n/// \\brief A set of rasterizers for lines\n///\n/// The main problem with line rasterization is to do it efficiently, e.g. less\n/// floating point operations. There are multiple algorithms that on paper\n/// should reach the same result, but due to quirks of IEEE-754 they don't.\n/// Please select one and stick to it if possible. At the moment only Bresenham\n/// rasterizer is implemented.\n\n/// \\ingroup LineRasterization\n/// \\brief Rasterize a line according to Bresenham algorithm\n///\n/// Do note that if either width or height is 1, slope is set to zero.\n/// reference:\n/// https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm#:~:text=Bresenham's%20line%20algorithm%20is%20a,straight%20line%20between%20two%20points.\nstruct bresenham_line_rasterizer\n{\n    constexpr std::ptrdiff_t point_count(std::ptrdiff_t width, std::ptrdiff_t height) const noexcept\n    {\n        return width > height ? width : height;\n    }\n\n    std::ptrdiff_t point_count(point_t start, point_t end) const noexcept\n    {\n        const auto abs_width = std::abs(end.x - start.x) + 1;\n        const auto abs_height = std::abs(end.y - start.y) + 1;\n        return point_count(abs_width, abs_height);\n    }\n\n    template <typename RandomAccessIterator>\n    void operator()(point_t start, point_t end, RandomAccessIterator d_first) const\n    {\n        if (start == end)\n        {\n            // put the point and immediately exit, as later on division by zero will\n            // occur\n            *d_first = start;\n            return;\n        }\n\n        auto width = std::abs(end.x - start.x) + 1;\n        auto height = std::abs(end.y - start.y) + 1;\n        bool const needs_flip = width < height;\n        if (needs_flip)\n        {\n            // transpose the coordinate system if uncomfortable angle detected\n            std::swap(width, height);\n            std::swap(start.x, start.y);\n            std::swap(end.x, end.y);\n        }\n        std::ptrdiff_t const x_increment = end.x >= start.x ? 1 : -1;\n        std::ptrdiff_t const y_increment = end.y >= start.y ? 1 : -1;\n        double const slope =\n            height == 1 ? 0 : static_cast<double>(height) / static_cast<double>(width);\n        std::ptrdiff_t y = start.y;\n        double error_term = 0;\n        for (std::ptrdiff_t x = start.x; x != end.x; x += x_increment)\n        {\n            // transpose coordinate system back to proper form if needed\n            *d_first++ = needs_flip ? point_t{y, x} : point_t{x, y};\n            error_term += slope;\n            if (error_term >= 0.5)\n            {\n                --error_term;\n                y += y_increment;\n            }\n        }\n        *d_first++ = needs_flip ? point_t{end.y, end.x} : end;\n    }\n};\n\n}} // namespace boost::gil\n", "meta": {"hexsha": "1ff91b6a35f87c8127837e2aa8c508cef6b4aff2", "size": 3483, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/rasterization/line.hpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "include/boost/gil/rasterization/line.hpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "include/boost/gil/rasterization/line.hpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 35.5408163265, "max_line_length": 152, "alphanum_fraction": 0.63680735, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6489730441866042}}
{"text": "// Copyright(c) 2019-present, Alexander Silva Barbosa & bflib contributors.\r\n// Distributed under the MIT License (http://opensource.org/licenses/MIT)\r\n\r\n/**\r\n * @author Alexander Silva Barbosa <alexander.ti.ufv@gmail.com>\r\n * @date 2019\r\n * Kalman Filter\r\n */\r\n\r\n#pragma once\r\n\r\n#include <Eigen/Dense>\r\n#include <random>\r\n#include <chrono>\r\n#include <vector>\r\n#include <thread>\r\n\r\nusing namespace Eigen;\r\n\r\ntemplate <typename dataType, int states, int inputs, int outputs>\r\nclass KF\r\n{\r\n    private:\r\n        typedef Matrix<dataType, states, 1> MatNx1;\r\n        typedef Matrix<dataType, states, states> MatNxN;\r\n        typedef Matrix<dataType, states, inputs> MatNxM;\r\n        typedef Matrix<dataType, states, outputs> MatNxP;\r\n        typedef Matrix<dataType, outputs, states> MatPxN;\r\n        typedef Matrix<dataType, outputs, outputs> MatPxP;\r\n        typedef Matrix<dataType, inputs, 1> MatMx1;\r\n        typedef Matrix<dataType, outputs, 1> MatPx1;\r\n        typedef Matrix<dataType, 3, 1> Mat3x1;\r\n\r\n    public:\r\n        typedef MatNx1 State;\r\n        typedef MatMx1 Input;\r\n        typedef MatPx1 Output;\r\n        typedef Input Control;\r\n        typedef Output Sensor;\r\n        typedef MatNxN ModelCovariance;\r\n        typedef MatPxP SensorCovariance;\r\n        typedef MatNxN StateMatrix;\r\n        typedef MatNxM InputMatrix;\r\n        typedef MatPxN OutputMatrix;\r\n        typedef Mat3x1 Uncertainty;\r\n        \r\n    private:\r\n        typedef void (*ProcessFunction)(StateMatrix &A, InputMatrix &B, OutputMatrix &C, double dt);\r\n\r\n        std::default_random_engine gen;\r\n        std::normal_distribution<double> distr{0.0, 1.0};\r\n        std::chrono::time_point<std::chrono::high_resolution_clock> start;\r\n\r\n        State x;\r\n        StateMatrix A;\r\n        ModelCovariance Q;\r\n        InputMatrix B;\r\n        OutputMatrix C;\r\n        SensorCovariance R;\r\n        \r\n        MatNx1 randX;\r\n        MatPx1 randY;\r\n\r\n        MatNxN P;\r\n        MatNxN Qsqrt;\r\n        MatPxP Rsqrt;\r\n\r\n        Output z, yError;\r\n        MatPxP S;\r\n        MatNxP K;\r\n        MatNxN I;\r\n\r\n\r\n        ProcessFunction processFn;\r\n\r\n        void init()\r\n        {\r\n            processFn = NULL;\r\n            P = Q;\r\n            I.setIdentity();\r\n\r\n            Qsqrt = Q.cwiseSqrt();\r\n            Rsqrt = R.cwiseSqrt();\r\n\r\n            start = std::chrono::high_resolution_clock::now();\r\n        }\r\n    public:\r\n        KF()\r\n        {\r\n            Q.setIdentity();\r\n            R.setIdentity();\r\n            x.setZero();\r\n            init();\r\n        }\r\n\r\n        KF(State X) : x(X)\r\n        {\r\n            Q.setIdentity();\r\n            R.setIdentity();\r\n            init();\r\n        }\r\n\r\n        KF(ModelCovariance Q, SensorCovariance R) : Q(Q), R(R)\r\n        {\r\n            x.setZero();\r\n            init();\r\n        }\r\n\r\n        KF(State X, ModelCovariance Q, SensorCovariance R) : x(X), Q(Q), R(R)\r\n        {\r\n            init();\r\n        }\r\n\r\n        virtual ~KF()\r\n        {\r\n\r\n        }\r\n\r\n        void seed()\r\n        {\r\n            gen = std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count());\r\n        }\r\n\r\n        void seed(long long s)\r\n        {\r\n            gen = std::default_random_engine(s);\r\n        }\r\n\r\n        State state()\r\n        {\r\n            State x;\r\n            x.setZero();\r\n            return x;\r\n        }\r\n\r\n        Input input()\r\n        {\r\n            Input u;\r\n            u.setZero();\r\n            return u;\r\n        }\r\n\r\n        Output output()\r\n        {\r\n            Output y;\r\n            y.setZero();\r\n            return y;\r\n        }\r\n\r\n        ModelCovariance createQ()\r\n        {\r\n            ModelCovariance Q;\r\n            Q.setZero();\r\n            return Q;\r\n        }\r\n\r\n        SensorCovariance createR()\r\n        {\r\n            SensorCovariance R;\r\n            R.setZero();\r\n            return R;\r\n        }\r\n\r\n        ModelCovariance getP()\r\n        {\r\n            return P;\r\n        }\r\n\r\n        Uncertainty getUncertainty(unsigned int x1, unsigned int x2)\r\n        {\r\n            Uncertainty C;\r\n            C.setZero();\r\n            if(x1 >= states || x2 >= states)\r\n                return C;\r\n            \r\n            Matrix<dataType, 2, 2> p;\r\n            p(0, 0) = P(x1, x1);\r\n            p(0, 1) = P(x1, x2);\r\n            p(1, 0) = P(x2, x1);\r\n            p(1, 1) = P(x2, x2);\r\n\r\n            EigenSolver< Matrix<dataType, 2, 2> > es(p);\r\n            Matrix<dataType, 2, 2> eValue = es.pseudoEigenvalueMatrix();\r\n            Matrix<dataType, 2, 2> eVector = es.pseudoEigenvectors();\r\n\r\n            C[0] = eValue(0,0);\r\n            C[1] = eValue(1,1);\r\n            C[2] = std::atan2(eVector(0, 1), eVector(0, 0));\r\n\r\n            return C;\r\n        }\r\n\r\n        void setQ(ModelCovariance Q)\r\n        {\r\n            this->Q = Q;\r\n            P = Q;\r\n            Qsqrt = Q.cwiseSqrt();\r\n        }\r\n\r\n        void setR(SensorCovariance R)\r\n        {\r\n            this->R = R;\r\n            Rsqrt = R.cwiseSqrt();\r\n        }\r\n\r\n        double time()\r\n        {\r\n            auto end = std::chrono::high_resolution_clock::now();\r\n            std::chrono::duration<double> diff = end - start;\r\n            start = std::chrono::high_resolution_clock::now();\r\n            return diff.count();\r\n        }\r\n\r\n        double delay(double s)\r\n        {\r\n            double ellapsed = time();\r\n            double remain = s - ellapsed;\r\n            if(remain < 0)\r\n                return ellapsed;\r\n            std::this_thread::sleep_for(std::chrono::nanoseconds((long long)(remain * 1e9)));\r\n            ellapsed += time();\r\n            return ellapsed;\r\n        }\r\n\r\n        void setProcess(ProcessFunction fn)\r\n        {\r\n            processFn = fn;\r\n        }\r\n\r\n        virtual void process(StateMatrix &A, InputMatrix &B, OutputMatrix &C, double dt)\r\n        {\r\n\r\n        }\r\n\r\n        void simulate(State &x, Output &y, Input &u, double dt)\r\n        {\r\n            doProcess(dt);\r\n\r\n            randn(randX);\r\n            randn(randY);\r\n\r\n            x = A * x + B * u + Qsqrt * randX;\r\n            y = C * x + Rsqrt * randY;\r\n        }\r\n\r\n        void run(State &xK, Output &y, Input &u, double dt)\r\n        {\r\n            predict(u, dt);\r\n            update(y);\r\n            xK = x;\r\n        }\r\n\r\n    private:\r\n        void predict(Input &u, double dt)\r\n        {\r\n            doProcess(dt);\r\n            x = A * x + B * u;\r\n            P = A * P * A.transpose() + Q;\r\n        }\r\n\r\n        void update(Output &y)\r\n        {\r\n            z = C * x;\r\n            yError = y - z;\r\n\r\n            S = C * P * C.transpose() + R;\r\n            K = P * C.transpose() * S.inverse();\r\n            x = x + K * yError;\r\n\r\n            P = (I - K * C) * P;\r\n        }\r\n\r\n        void doProcess(double dt)\r\n        {\r\n            if(processFn != NULL)\r\n                processFn(A, B, C, dt);\r\n            else\r\n                process(A, B, C, dt);\r\n        }\r\n\r\n        template<class T>\r\n        void randn(T &mat)\r\n        {\r\n            for (size_t i = 0; i < mat.rows(); i++)\r\n            {\r\n                for (size_t j = 0; j < mat.cols(); j++)\r\n                {\r\n                    mat(i, j) = distr(gen);\r\n                }\r\n            }\r\n        }\r\n\r\n};", "meta": {"hexsha": "7ffc21396f9f0d93ea59be82a5a3920d137a9127", "size": 7217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bflib/KF.hpp", "max_stars_repo_name": "AlexanderSilvaB/KFs", "max_stars_repo_head_hexsha": "b5eb3692ebc88d158a5210c714b7e7ac1fe3ee32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-30T07:46:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T10:35:29.000Z", "max_issues_repo_path": "bflib/KF.hpp", "max_issues_repo_name": "AlexanderSilvaB/KFs", "max_issues_repo_head_hexsha": "b5eb3692ebc88d158a5210c714b7e7ac1fe3ee32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bflib/KF.hpp", "max_forks_repo_name": "AlexanderSilvaB/KFs", "max_forks_repo_head_hexsha": "b5eb3692ebc88d158a5210c714b7e7ac1fe3ee32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T08:35:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T09:06:35.000Z", "avg_line_length": 24.6313993174, "max_line_length": 107, "alphanum_fraction": 0.4465844534, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.648971524509422}}
{"text": "/* This file (C) 2008 Maik Beckmann\n * https://lists.boost.org/MailArchives/ublas/2008/09/2984.php\n */\n\n#ifndef determinant_hpp\n#define determinant_hpp\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n\nnamespace ublas = boost::numeric::ublas;\n\n\ntemplate<class matrix_T>\ndouble determinant(ublas::matrix_expression<matrix_T> const& mat_r)\n{\n  double det = 1.0;\n\n  matrix_T mLu(mat_r());\n  ublas::permutation_matrix<std::size_t> pivots(mat_r().size1());\n\n  int is_singular = lu_factorize(mLu, pivots);\n\n  if (!is_singular)\n  {\n    for (std::size_t i=0; i < pivots.size(); ++i)\n    {\n      if (pivots(i) != i)\n        det *= -1.0;\n\n      det *= mLu(i,i);\n    }\n  }\n  else\n    det = 0.0;\n\n  return det;\n}\n\n\n#endif\n", "meta": {"hexsha": "b7576a66864f7fe07c52a0325afc36f360ea51bb", "size": 868, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost_contribs/determinant.hpp", "max_stars_repo_name": "BuildJet/siconos", "max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/boost_contribs/determinant.hpp", "max_issues_repo_name": "BuildJet/siconos", "max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/boost_contribs/determinant.hpp", "max_forks_repo_name": "BuildJet/siconos", "max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 18.4680851064, "max_line_length": 67, "alphanum_fraction": 0.6658986175, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6489715210737006}}
{"text": "\n// BLAS level 1 (vectors) \n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/atlas/cblas1.hpp>\n#ifdef F_USE_STD_VECTOR\n#include <vector>\n#include <boost/numeric/bindings/traits/std_vector.hpp> \n#endif \n#include \"utils.h\"\n\nnamespace atlas = boost::numeric::bindings::atlas;\nnamespace ublas = boost::numeric::ublas;\n\nusing std::cout;\nusing std::endl; \nusing std::size_t; \n\ntypedef double real_t;\n\n#ifndef F_USE_STD_VECTOR\ntypedef ublas::vector<real_t> vct_t;\n#else\ntypedef ublas::vector<real_t, std::vector<double> > vct_t;\n#endif \n\nint main() {\n\n  cout << endl; \n\n  vct_t v (10);\n  init_v (v, times_plus<real_t> (0.1, 0.1)); \n  print_v (v, \"v\"); \n  vct_t vy (10); \n  atlas::set (1., vy); \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // v <- 2 v\n  atlas::scal (2.0, v); \n  print_v (v, \"v <- 2 v\");\n\n  // vy <- 0.5 v + vy\n  atlas::axpy (0.5, v, vy); \n  print_v (vy, \"vy <- 0.5 v + vy\"); \n\n  // v^T vy\n  cout << \"v vy = \" << atlas::dot (v, vy) << endl;\n  cout << endl; \n\n  /////////////////\n  // ranges \n\n  // v -- new init \n  init_v (v, times_plus<real_t> (0.1, 0.1)); \n  print_v (v, \"v\"); \n  // vy -- new init \n  init_v (vy, kpp (1)); \n  print_v (vy, \"vy\"); \n\n  // v[2..6]\n  ublas::vector_range<vct_t> vr (v, ublas::range (2, 6)); \n  print_v (vr, \"v[2..6]\"); \n  // vy[4..8] \n  ublas::vector_range<vct_t> vry (vy, ublas::range (4, 8)); \n  print_v (vry, \"vy[4..8]\"); \n\n  // v[2..6] <- 0.1 v[2..6]\n  atlas::scal (0.1, vr); \n  print_v (v, \"v[2..6] <- 0.1 v[2..6]\"); \n\n  // vr^T vr \n  // ublas::vector_range<vct_t const> cvr (v, ublas::range (2, 6)); \n  cout << \"v[2..6] v[2..6] = \" << atlas::dot (vr, vr) << endl;\n\n  // vy[4..8] <- v[2..6] + vy[4..8]\n  atlas::xpy (vr, vry); \n  print_v (vy, \"vy[4..8] <- v[2..6] + vy[4..8]\"); \n  cout << endl; \n\n  /////////////////\n  // slices \n\n  // v -- new init \n  init_v (v, times_plus<real_t> (0.1, 0.1)); \n  print_v (v, \"v\"); \n  // vy -- new init \n  init_v (vy, kpp (1)); \n  print_v (vy, \"vy\"); \n\n  // v[1:2:4]\n  ublas::vector_slice<vct_t> vs (v, ublas::slice (1, 2, 4)); \n  print_v (vs, \"v[1:2:4]\"); \n  // vy[2:2:4] \n  ublas::vector_slice<vct_t> vsy (vy, ublas::slice (2, 2, 4)); \n  print_v (vsy, \"vy[2:2:4]\"); \n\n  // v[1:2:4] <- 10 v[1:2:4]\n  atlas::scal (10.0, vs); \n  print_v (v, \"v[1:2:4] <- 10 v[1:2:4]\"); \n\n  // vs^T vs\n  cout << \"v[1:2:4] v[1:2:4] = \" << atlas::dot (vs, vs) << endl;\n\n  // vy[2:2:4] <- 0.01 v[1:2:4] + vy[2:2:4] \n  atlas::axpy (0.01, vs, vsy); \n  print_v (vy, \"vy[2:2:4] <- 0.01 v[1:2:4] + vy[2:2:4]\"); \n  cout << endl; \n\n  ////////////////////////////////////////////\n  // ranges & slices \n\n  // v -- new init \n  init_v (v, times_plus<real_t> (0.1, 0.1)); \n  print_v (v, \"v\"); \n  // vy <- 1.0\n  atlas::set (1., vy);\n  print_v (vy, \"vy <- 1.0\"); \n\n  // vy[2:2:4] <- 0.01 v[2..6] + vy[2:2:4] \n  atlas::axpy (0.01, vr, vsy); \n  print_v (vy, \"vy[2:2:4] <- 0.01 v[2..6] + vy[2:2:4]\"); \n\n  // vy <- 1.0\n  atlas::set (1., vy); \n  print_v (vy, \"vy <- 1.0\"); \n\n  // vy[4..8] <- 0.01 v[1:2:4] + vy[4..8] \n  atlas::axpy (0.01, vs, vry); \n  print_v (vy, \"vy[4..8] <- 0.01 v[1:2:4] + vy[4..8]\"); \n\n  // vr^T vs == vs^T vr\n  cout << \"v[2..6] v[1:2:4] = \" << atlas::dot (vr, vs) << \" == \" \n       << atlas::dot (vs, vr) << endl;\n\n  // vr^T vsy == vsy^T vr\n  cout << \"v[2..6] vy[2:2:4] = \" << atlas::dot (vr, vsy) << \" == \" \n       << atlas::dot (vsy, vr) << endl;\n\n  cout << endl; \n\n  ///////////////////\n  // slice of range\n\n  // v -- new init \n  init_v (v, times_plus<real_t> (0.1, 0.1)); \n  print_v (v, \"v\"); \n\n  // v[1..9][1:2:3] \n  ublas::vector_range<vct_t> vr1 (v, ublas::range (1, 9)); \n  ublas::vector_slice< \n    ublas::vector_range<vct_t> \n  > vsr (vr1, ublas::slice (1, 2, 3)); \n  print_v (vr1, \"v[1..9]\"); \n  print_v (vsr, \"v[1..9][1:2:3]\"); \n\n  // v[1..9][1:2:3] <- 0.1 v[1..9][1:2:3]\n  atlas::scal (0.1, vsr); \n  print_v (v, \"0.1 v[1..9][1:2:3]\"); \n\n  // ||vsr||_2 \n  cout << \"||v[1..9][1:2:3]||_2 = \" << atlas::nrm2 (vsr) << endl; \n  cout << endl; \n\n  ///////////////////\n  // range of slice \n\n  // vy <- 1.0\n  init_v (vy, kpp (1)); \n  print_v (vy, \"vy\"); \n\n  // v[0:2:5][1:4] \n  ublas::vector_slice<vct_t> vsy1 (vy, ublas::slice (0, 2, 5));\n  ublas::vector_range<\n    ublas::vector_slice<vct_t> \n  > vrs (vsy1, ublas::range (1, 4)); \n  print_v (vsy1, \"v[0:2:5]\");\n  print_v (vrs, \"v[0:2:5][1:4]\");\n\n  // v[0:2:5][1:4] <- 0.01 v[1..9][1:2:3] + v[0:2:5][1:4]\n  atlas::axpy (0.01, vsr, vrs); \n  print_v (vy, \"0.01 v[1..9][1:2:3] + v[0:2:5][1:4]\"); \n\n  cout << endl; \n\n}\n", "meta": {"hexsha": "f6d44f45638528e623b70c3c976fc0a3d4569392", "size": 4678, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_vct.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_vct.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_vct.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 24.2383419689, "max_line_length": 68, "alphanum_fraction": 0.5027789654, "num_tokens": 2121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6489391954490265}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2009 Mark Borgerding mark a borgerding net\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include <iostream>\r\n\r\n#include <bench/BenchUtil.h>\r\n#include <complex>\r\n#include <vector>\r\n#include <Eigen/Core>\r\n\r\n#include <unsupported/Eigen/FFT>\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\n\r\ntemplate <typename T>\r\nstring nameof();\r\n\r\ntemplate <> string nameof<float>() {return \"float\";}\r\ntemplate <> string nameof<double>() {return \"double\";}\r\ntemplate <> string nameof<long double>() {return \"long double\";}\r\n\r\n#ifndef TYPE\r\n#define TYPE float\r\n#endif\r\n\r\n#ifndef NFFT\r\n#define NFFT 1024\r\n#endif\r\n#ifndef NDATA\r\n#define NDATA 1000000\r\n#endif\r\n\r\nusing namespace Eigen;\r\n\r\ntemplate <typename T>\r\nvoid bench(int nfft,bool fwd,bool unscaled=false, bool halfspec=false)\r\n{\r\n    typedef typename NumTraits<T>::Real Scalar;\r\n    typedef typename std::complex<Scalar> Complex;\r\n    int nits = NDATA/nfft;\r\n    vector<T> inbuf(nfft);\r\n    vector<Complex > outbuf(nfft);\r\n    FFT< Scalar > fft;\r\n\r\n    if (unscaled) {\r\n        fft.SetFlag(fft.Unscaled);\r\n        cout << \"unscaled \";\r\n    }\r\n    if (halfspec) {\r\n        fft.SetFlag(fft.HalfSpectrum);\r\n        cout << \"halfspec \";\r\n    }\r\n\r\n\r\n    std::fill(inbuf.begin(),inbuf.end(),0);\r\n    fft.fwd( outbuf , inbuf);\r\n\r\n    BenchTimer timer;\r\n    timer.reset();\r\n    for (int k=0;k<8;++k) {\r\n        timer.start();\r\n        if (fwd)\r\n            for(int i = 0; i < nits; i++)\r\n                fft.fwd( outbuf , inbuf);\r\n        else\r\n            for(int i = 0; i < nits; i++)\r\n                fft.inv(inbuf,outbuf);\r\n        timer.stop();\r\n    }\r\n\r\n    cout << nameof<Scalar>() << \" \";\r\n    double mflops = 5.*nfft*log2((double)nfft) / (1e6 * timer.value() / (double)nits );\r\n    if ( NumTraits<T>::IsComplex ) {\r\n        cout << \"complex\";\r\n    }else{\r\n        cout << \"real   \";\r\n        mflops /= 2;\r\n    }\r\n\r\n\r\n    if (fwd)\r\n        cout << \" fwd\";\r\n    else\r\n        cout << \" inv\";\r\n\r\n    cout << \" NFFT=\" << nfft << \"  \" << (double(1e-6*nfft*nits)/timer.value()) << \" MS/s  \" << mflops << \"MFLOPS\\n\";\r\n}\r\n\r\nint main(int argc,char ** argv)\r\n{\r\n    bench<complex<float> >(NFFT,true);\r\n    bench<complex<float> >(NFFT,false);\r\n    bench<float>(NFFT,true);\r\n    bench<float>(NFFT,false);\r\n    bench<float>(NFFT,false,true);\r\n    bench<float>(NFFT,false,true,true);\r\n\r\n    bench<complex<double> >(NFFT,true);\r\n    bench<complex<double> >(NFFT,false);\r\n    bench<double>(NFFT,true);\r\n    bench<double>(NFFT,false);\r\n    bench<complex<long double> >(NFFT,true);\r\n    bench<complex<long double> >(NFFT,false);\r\n    bench<long double>(NFFT,true);\r\n    bench<long double>(NFFT,false);\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "60e7154cf042a32d3e6b79658c204e3934b40ebe", "size": 2921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/bench/benchFFT.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/bench/benchFFT.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/bench/benchFFT.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 25.1810344828, "max_line_length": 117, "alphanum_fraction": 0.5813077713, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6489391921037119}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n#include <boost/math/special_functions/erf.hpp>\n\nTEST(AgradRev, erf) {\n  AVAR a = 1.3;\n  AVAR f = erf(a);\n  EXPECT_FLOAT_EQ(stan::math::erf(1.3), f.val());\n\n  AVEC x = createAVEC(a);\n  VEC grad_f;\n  f.grad(x, grad_f);\n  EXPECT_FLOAT_EQ(2.0 / std::sqrt(boost::math::constants::pi<double>())\n                      * std::exp(-1.3 * 1.3),\n                  grad_f[0]);\n}\nstruct erf_fun {\n  template <typename T0>\n  inline T0 operator()(const T0& arg1) const {\n    return erf(arg1);\n  }\n};\n\nTEST(AgradRev, erf_NaN) {\n  erf_fun erf_;\n  test_nan(erf_, false, true);\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a = 1.3;\n  test::check_varis_on_stack(stan::math::erf(a));\n}\n", "meta": {"hexsha": "8223500af8a9d2a9bf86a489d1489b46ec29561d", "size": 825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/rev/scal/fun/erf_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T14:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T14:57:41.000Z", "max_issues_repo_path": "test/unit/math/rev/scal/fun/erf_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T19:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T12:03:41.000Z", "max_forks_repo_path": "test/unit/math/rev/scal/fun/erf_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5714285714, "max_line_length": 71, "alphanum_fraction": 0.6351515152, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6489391817264291}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/included/unit_test.hpp>\n#include <srook/math/vector.hpp>\n#include <srook/math/matrix.hpp>\n#include <srook/type_traits/is_same.hpp>\n#include <srook/type_traits/detail/logical.hpp>\n#include <srook/type_traits/decay.hpp>\n#include <srook/tmpl/vt/map.hpp>\n#include <srook/math/constants/algorithm/abs.hpp>\n\n#include <boost/type_index.hpp>\n\nBOOST_AUTO_TEST_SUITE(srook_math_vector_test)\n\nBOOST_AUTO_TEST_CASE(vector_construct)\n{\n    srook::math::vector<int, double> vec0;\n    SROOK_ST_ASSERT(std::tuple_size<SROOK_DECLTYPE(vec0)>::value == 2);\n    SROOK_ST_ASSERT(srook::type_traits::detail::Land<\n        srook::is_same<SROOK_DEDUCED_TYPENAME std::tuple_element<0, SROOK_DECLTYPE(vec0)>::type, int>, srook::is_same<SROOK_DEDUCED_TYPENAME std::tuple_element<1, SROOK_DECLTYPE(vec0)>::type, double>\n    >::value);\n    BOOST_CHECK_EQUAL(vec0.get<0>(), 0);\n    BOOST_CHECK_EQUAL(vec0.get<1>(), 0.0);\n\n    constexpr auto vec1 = \n#if SROOK_CPLUSPLUS >= SROOK_CPLUSPLUS17_CONSTANT\n        srook::math::vector(1, 2.f, 3.0)\n#else\n        srook::math::make_vector(1, 2.f, 3.0)\n#endif\n        ;\n    SROOK_ST_ASSERT(srook::is_same<SROOK_DECLTYPE(vec1), const srook::math::vector<int, float, double>>::value);\n    SROOK_ST_ASSERT(vec1.get<0>() == 1);\n    SROOK_ST_ASSERT(vec1.get<1>() == 2.f);\n    SROOK_ST_ASSERT(vec1.get<2>() == 3.0);\n    SROOK_ST_ASSERT(srook::tmpl::vt::and_<SROOK_DEDUCED_TYPENAME srook::tmpl::vt::map<srook::is_equality_comparable, srook::tmpl::vt::packer<SROOK_DECLTYPE(vec0), SROOK_DECLTYPE(vec1)>>::type>::value);\n}\n\nBOOST_AUTO_TEST_CASE(vector_copy_construct)\n{\n    constexpr auto vec0 = srook::math::make_vector(1, 2.f, 3.0);\n    constexpr auto vec1 = vec0;\n    SROOK_ST_ASSERT(srook::is_same<SROOK_DECLTYPE(vec0), SROOK_DECLTYPE(vec1)>::value);\n    SROOK_ST_ASSERT(vec0 == vec1);\n}\n\nBOOST_AUTO_TEST_CASE(vector_assign)\n{\n    constexpr auto vec0 = srook::math::make_vector(1, 2.f);\n    srook::math::vector<int, float> vec1;\n    vec1 = vec0;\n    BOOST_CHECK_EQUAL(vec0, vec1);\n}\n\nBOOST_AUTO_TEST_CASE(vector_length_equality)\n{\n    typedef srook::numeric_limits<srook::floatmax_t> result_float;\n    auto vec0 = srook::math::make_vector(4.0, 3.0);\n    BOOST_TEST(srook::math::abs(vec0.length() - 5) < result_float::epsilon());\n    SROOK_ST_ASSERT(srook::math::abs(srook::math::make_vector(12, 5).length() - 13) < result_float::epsilon());\n    SROOK_ST_ASSERT(srook::math::abs(srook::math::make_vector(8, 15).length() - 17) < result_float::epsilon());\n    \n    BOOST_TEST(!vec0.is_unit());\n    if (vec0.normalize()) { // When vec0.length() == 0, it returns false.\n        BOOST_TEST(vec0.is_unit());\n        BOOST_TEST(srook::math::abs(vec0.get<0>() - 0.8) < srook::numeric_limits<double>::epsilon());\n        BOOST_TEST(srook::math::abs(vec0.get<1>() - 0.6) < srook::numeric_limits<double>::epsilon());\n    }\n    srook::math::make_vector(4.0, 3.0).get_normalized<double>() >>= [](const auto& normalized_vec) { // When vec0.length() == 0, it returns nullopt. Otherwise, it returns optional<vector<...>>.\n        BOOST_CHECK_EQUAL(normalized_vec, srook::math::make_vector(0.8, 0.6)); // This equivalence is handled appropriately about floating error.\n        return srook::make_optional(normalized_vec);\n    };\n}\n\nBOOST_AUTO_TEST_CASE(vector_dot_product)\n{\n    SROOK_ST_ASSERT(!srook::math::make_vector(3, 5).dot_product(5, -3));\n    SROOK_ST_ASSERT(srook::math::make_vector(1, 2).dot_product(3, 4) == 11);\n    SROOK_ST_ASSERT(srook::math::make_vector(1, 2).dot_product(-2, 3) == 4);\n}\n\nBOOST_AUTO_TEST_CASE(vector_cross_product)\n{\n    SROOK_ST_ASSERT(srook::math::make_vector(1, 2, 3).cross_product(4, 5, 6) == srook::math::make_vector(-3, 6, -3));\n}\n\nBOOST_AUTO_TEST_CASE(vector_projection)\n{\n    SROOK_ST_ASSERT(srook::math::make_vector(1.f, 2.f, 2.f).projection(4.f, 0.f, 3.f) == srook::math::make_vector(1.6f, .0f, 1.2f));\n}\n\nBOOST_AUTO_TEST_CASE(vector_perpendicular)\n{\n    SROOK_ST_ASSERT(srook::math::make_vector(1.f, 2.f, 2.f).perpendicular(4.f, 0.f, 3.f) == srook::math::make_vector(-0.6f, 2.f, .8f));\n}\n\nBOOST_AUTO_TEST_CASE(vector_compute_triangle_from_points)\n{\n    // Compute the area of the triangle for P1 = (1, 3, 0), P2 = (3, 4, 0), P3 = (2, 6, 0) \n    // in compile time.\n    using namespace srook::math;\n\n    constexpr auto p1 = make_vector(1, 3, 0), p2 = make_vector(3, 4, 0), p3 = make_vector(2, 6, 0);\n    SROOK_ST_ASSERT(\n        ((p2 - p1).cross_product(p3 - p1).length() / 2 - 2.5) < srook::numeric_limits<double>::epsilon()\n    );\n}\n\nBOOST_AUTO_TEST_CASE(vector_matrix_conversion)\n{\n    constexpr auto vec0 = srook::math::make_vector(1, 3, 0);\n    constexpr SROOK_DEDUCED_TYPENAME srook::tmpl::vt::transfer<\n        srook::math::linear_algebra::detail::matrix_impl, \n        SROOK_DEDUCED_TYPENAME srook::tmpl::vt::replicate<\n            SROOK_DECLTYPE(vec0)::size,\n            SROOK_DEDUCED_TYPENAME srook::tmpl::vt::transfer<\n                srook::math::row,\n                SROOK_DEDUCED_TYPENAME srook::tmpl::vt::foldr1<std::common_type, SROOK_DEDUCED_TYPENAME SROOK_DECLTYPE(vec0)::packed_type>::type\n            >::type\n        >::type\n    >::type mat0 = srook::math::make_matrix(vec0);\n    constexpr auto vec1 = srook::math::make_vector(mat0);\n    SROOK_ST_ASSERT(vec0 == vec1);\n    SROOK_ST_ASSERT(vec0 == mat0);\n\n    constexpr SROOK_DECLTYPE(mat0) mat1 { 2, 3, 0 };\n    SROOK_ST_ASSERT(vec0 != mat1);\n    SROOK_ST_ASSERT(srook::math::make_vector(2, 3, 0) == mat1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "8ab76d29174d81f73295c29af866c25ce3a3bfe0", "size": 5482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math/vector/test1.cpp", "max_stars_repo_name": "falgon/srookCppLibraries", "max_stars_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-01T07:54:37.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-01T07:54:37.000Z", "max_issues_repo_path": "tests/math/vector/test1.cpp", "max_issues_repo_name": "falgon/srookCppLibraries", "max_issues_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/math/vector/test1.cpp", "max_forks_repo_name": "falgon/srookCppLibraries", "max_forks_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5303030303, "max_line_length": 201, "alphanum_fraction": 0.6882524626, "num_tokens": 1822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6489347432590666}}
{"text": "#include <tiny_math_types.h>\n#include <tiny_matrix_functions.h>\n#include <tiny_covariance3x3.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(tiny_covariance3x3);\n\nBOOST_AUTO_TEST_CASE(simple_test)\n{\n  \n  typedef tiny::MathTypes<double> math_types;\n  \n  typedef  math_types::matrix3x3_type   matrix3x3_type;\n  typedef  math_types::vector3_type     vector3_type;\n  \n  \n  matrix3x3_type C;\n  vector3_type mean;\n  \n  vector3_type samples[100];\n    \n  for( size_t i=0;i<100;++i)\n    samples[i] = vector3_type::random(  );\n  \n  tiny::covariance( samples, samples+100, mean, C );\n  \n  BOOST_CHECK_CLOSE( C(1,0), C(0,1), 0.01 );\n  BOOST_CHECK_CLOSE( C(2,0), C(0,2), 0.01 );\n  BOOST_CHECK_CLOSE( C(2,1), C(1,2), 0.01 );\n  \n  BOOST_CHECK( mean(0) > 0.0 );\n  BOOST_CHECK( mean(0) < 1.0 );\n  BOOST_CHECK( mean(1) > 0.0 );\n  BOOST_CHECK( mean(1) < 1.0 );\n  BOOST_CHECK( mean(2) > 0.0 );\n  BOOST_CHECK( mean(2) < 1.0 );\n  \n  matrix3x3_type C1 = C;\n  vector3_type mean1 = mean;\n  \n  matrix3x3_type C2 = C;\n  vector3_type mean2 = mean;\n  \n  matrix3x3_type C3;\n  vector3_type mean3;\n  tiny::covariance_union( mean1, C1, mean2, C2, mean3, C3 );\n  \n  \n  BOOST_CHECK_CLOSE( C3(1,0), C3(0,1), 0.01 );\n  BOOST_CHECK_CLOSE( C3(2,0), C3(0,2), 0.01 );\n  BOOST_CHECK_CLOSE( C3(2,1), C3(1,2), 0.01 );\n  \n  BOOST_CHECK( mean3(0) > 0.0 );\n  BOOST_CHECK( mean3(0) < 1.0 );\n  BOOST_CHECK( mean3(1) > 0.0 );\n  BOOST_CHECK( mean3(1) < 1.0 );\n  BOOST_CHECK( mean3(2) > 0.0 );\n  BOOST_CHECK( mean3(2) < 1.0 );\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "4ca19d899bffd31f380ce030a4986306364bf735", "size": 1690, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_covariance3x3/tiny_covariance3x3.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_covariance3x3/tiny_covariance3x3.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_covariance3x3/tiny_covariance3x3.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8529411765, "max_line_length": 60, "alphanum_fraction": 0.6662721893, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6489347417795839}}
{"text": "#ifndef _TESTSHP_CPP__\n#define _TESTSHP_CPP__\n\n#include <iostream>\n#include <vector>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/undirected_graph.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <time.h>\n#include <stdlib.h>\n#include \"OrientedGraph.h\"\n#include \"UnorientedGraphValuedEdge.hpp\"\n#include \"GraphManager.h\"\n#include \"AdjacencyMatrixUnoriented.h\"\n\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property,\n                               boost::property<boost::edge_weight_t,int> > BoostGraph;\ntypename BoostGraph::vertex_descriptor u, v;\ntypedef typename BoostGraph ::edge_property_type Weight;\n\nint randInt()\n{\n    return rand() % 256;\n}\n\nvoid TestShortestPaths(double probability)\n{\n    const int SIZE = 10000;\n    UnorientedGraphValuedEdge<int>* g = new UnorientedGraphValuedEdge<int>(SIZE, new AdjacencyMatrixUnoriented());\n    g->RandomizeGraph(probability, &randInt);\n    clock_t start_t, end_t;\n    std::cout << \"Probability: \" << probability << std::endl;\n    double sumBFS = 0;\n    double sumDj = 0;\n    double sumBDj = 0;\n    std::vector<int> requests;\n    for(int i = 0; i < 20; ++i)\n    {\n        int u = rand() % SIZE;\n        int v = rand() % SIZE;\n        requests.push_back(u);\n        start_t = clock();\n        g->BFS(u, v);\n        end_t = clock();\n        sumBFS += (float)(end_t - start_t)/CLOCKS_PER_SEC;\n\n        start_t = clock();\n        g->Dijkstra(u, v);\n        end_t = clock();\n        sumDj += (float)(end_t - start_t)/CLOCKS_PER_SEC;\n    }\n    BoostGraph gb(g->Size());\n    for(int i = 0; i < g->Size(); ++i)\n        for(int j = i + 1; j < g->Size(); ++j)\n            if(g->CheckEdge(i, j))\n            {\n                boost::add_edge(boost::vertex(i, gb), boost::vertex(j,gb), Weight(g->GetEdgeValue(i, j)), gb);\n            }\n\n    std::vector<BoostGraph::vertex_descriptor> p(boost::num_vertices(gb));\n    std::vector<int> d(boost::num_vertices(gb));\n\n    auto bgl = boost::predecessor_map(boost::make_iterator_property_map(p.begin(),\n                            boost::get(boost::vertex_index, gb))).\n                            distance_map(boost::make_iterator_property_map(d.begin(), get(boost::vertex_index, gb)));\n    delete g;\n    for(int i = 0; i < 20; ++i)\n    {\n        BoostGraph::vertex_descriptor s = boost::vertex(u, gb);\n        start_t = clock();\n        boost::dijkstra_shortest_paths(gb, s, bgl);\n        end_t = clock();\n        sumBDj += (float)(end_t - start_t)/CLOCKS_PER_SEC;\n    }\n    std::cout << \"\\tBFS 1-K \" << sumBFS << std::endl;\n    std::cout << \"\\tDijkstra \" << sumDj << std::endl;\n    std::cout << \"\\tboost::Dijkstra \" << sumBDj << std::endl;\n}\n\nvoid TestMy1KBFS(int u, int v)\n{\n    /*GraphValuedEdge* g = new GraphValuedEdge(10000);\n    g->RandomizeUnorientedGraph(0.02);\n    g->Graph::WriteToFile(\"graph.gr\");*/\n    UnorientedGraphValuedEdge<int>* g = new UnorientedGraphValuedEdge<int>(1000, new AdjacencyMatrixUnoriented());\n    g->RandomizeGraph(0.05, &randInt);\n    std::cout << g->BFS(u, v) << std::endl;\n    delete g;\n}\nvoid TestMy1KBFS()\n{\n    unsigned int u, v;\n    std::cin >> u;\n    std::cin >> v;\n    TestMy1KBFS(u, v);\n}\nvoid TestMyDijkstra(int u, int v)\n{\n    UnorientedGraphValuedEdge<int>* g = new UnorientedGraphValuedEdge<int>(10000, new AdjacencyMatrixUnoriented());\n    g->RandomizeGraph(0.05, &randInt);\n    std::cout << g->Dijkstra(u,v) << std::endl;\n    delete g;\n}\nvoid TestMyDijkstra()\n{\n    unsigned int u, v;\n    std::cin >> u;\n    std::cin >> v;\n    TestMyDijkstra(u, v);\n}\nvoid TestBoostDijkstra(int u, int v)\n{\n    UnorientedGraphValuedEdge<int>* g = new UnorientedGraphValuedEdge<int>(10000, new AdjacencyMatrixUnoriented());\n    g->RandomizeGraph(0.05, &randInt);\n    BoostGraph gb(g->Size());\n    for(int i = 0; i < g->Size(); ++i)\n        for(int j = i + 1; j < g->Size(); ++j)\n            if(g->CheckEdge(i, j))\n            {\n                boost::add_edge(boost::vertex(i, gb), boost::vertex(j,gb), Weight(g->GetEdgeValue(i, j)), gb);\n            }\n\n    std::vector<BoostGraph::vertex_descriptor> p(boost::num_vertices(gb));\n    std::vector<int> d(boost::num_vertices(gb));\n    BoostGraph::vertex_descriptor s = boost::vertex(u, gb);\n    boost::dijkstra_shortest_paths(gb, s,\n                                                boost::predecessor_map(boost::make_iterator_property_map(p.begin(),\n                                                                                                         boost::get(boost::vertex_index, gb))).\n                                   distance_map(boost::make_iterator_property_map(d.begin(), get(boost::vertex_index, gb))));\n    std::cout << d[v] << std::endl;\n    delete g;\n}\nvoid TestBoostDijkstra()\n{\n    unsigned int u, v;\n    std::cin >> u;\n    std::cin >> v;\n    TestBoostDijkstra(u, v);\n}\n\n#endif\n", "meta": {"hexsha": "3c7339ca32b89a00b29ef78d3e8eb557ede4ff64", "size": 4871, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GraphUnitTests/include/TestShortestPath.hpp", "max_stars_repo_name": "IKholopov/StudyingStuff", "max_stars_repo_head_hexsha": "8e5d9b98431fcc439d246d499963c33c729d5474", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GraphUnitTests/include/TestShortestPath.hpp", "max_issues_repo_name": "IKholopov/StudyingStuff", "max_issues_repo_head_hexsha": "8e5d9b98431fcc439d246d499963c33c729d5474", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphUnitTests/include/TestShortestPath.hpp", "max_forks_repo_name": "IKholopov/StudyingStuff", "max_forks_repo_head_hexsha": "8e5d9b98431fcc439d246d499963c33c729d5474", "max_forks_repo_licenses": ["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.8263888889, "max_line_length": 143, "alphanum_fraction": 0.5974132622, "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6489347363981636}}
{"text": "#include <dlib/matrix.h>\n#include <iostream>\n\nint main() {\n  // definitions\n  {\n    // compile time sized matrix\n    dlib::matrix<double, 3, 1> y;\n    // dynamically sized matrix\n    dlib::matrix<double> m(3, 3);\n    // later we can change size of this matrix\n    m.set_size(6, 6);\n  }\n  // initializations\n  {\n    // comma operator\n    dlib::matrix<double> m(3, 3);\n    m = 1., 2., 3., 4., 5., 6., 7., 8., 9.;\n    std::cout << \"Matix from comma operator\\n\" << m << std::endl;\n\n    // wrap array\n    double data[] = {1, 2, 3, 4, 5, 6};\n    auto m2 = dlib::mat(data, 2, 3);  // create matrix with size 2x3\n    std::cout << \"Matix from array\\n\" << m2 << std::endl;\n\n    // Matrix elements can be accessed with () operator\n    m(1, 2) = 300;\n    std::cout << \"Matix element updated\\n\" << m << std::endl;\n\n    // Also you can initialize matrix with some predefined values\n    auto a = dlib::identity_matrix<double>(3);\n    std::cout << \"Identity matix \\n\" << a << std::endl;\n\n    auto b = dlib::ones_matrix<double>(3, 4);\n    std::cout << \"Ones matix \\n\" << b << std::endl;\n\n    auto c = dlib::randm(3, 4);  // matrix with random values with size 3x3\n    std::cout << \"Random matix \\n\" << c << std::endl;\n  }\n  // arithmetic operations\n  {\n    dlib::matrix<double> a(2, 2);\n    a = 1, 1, 1, 1;\n    dlib::matrix<double> b(2, 2);\n    b = 2, 2, 2, 2;\n\n    auto c = a + b;\n    std::cout << \"c = a + b \\n\" << c << std::endl;\n\n    auto e = a * b;  // real matrix multiplication\n    std::cout << \"e = a dot b \\n\" << e << std::endl;\n\n    a += 5;\n    std::cout << \"a += 5 \\n\" << a << std::endl;\n\n    auto d = dlib::pointwise_multiply(a, b);  // element wise multiplication\n    std::cout << \"d = a * b \\n\" << e << std::endl;\n\n    auto t = dlib::trans(a);  // transpose matrix\n    std::cout << \"transposed matrix a \\n\" << t << std::endl;\n  }\n  // partial access\n  {\n    dlib::matrix<float, 4, 4> m;\n    m = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;\n    auto sm =\n        dlib::subm(m, dlib::range(1, 2),\n                   dlib::range(1, 2));  // original matrix can't be updated\n    std::cout << \"Sub matrix \\n\" << sm << std::endl;\n\n    dlib::set_subm(m, dlib::range(1, 2), dlib::range(1, 2)) = 100;\n    std::cout << \"Updated sub matrix \\n\" << m << std::endl;\n  }\n  // there are no implicit broadcasting in dlib\n  {\n    // we can simulate broadcasting with partial access\n    dlib::matrix<float, 2, 1> v;\n    v = 10, 10;\n    dlib::matrix<float, 2, 3> m;\n    m = 1, 2, 3, 4, 5, 6;\n    for (int i = 0; i < m.nc(); ++i) {\n      dlib::set_colm(m, i) += v;\n    }\n    std::cout << \"Matrix with updated columns \\n\" << m << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "14c4880ed5160ef13f49d9eed25ffa70307c6933", "size": 2644, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter01/dlib_samples/linalg_dlib.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter01/dlib_samples/linalg_dlib.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter01/dlib_samples/linalg_dlib.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 30.0454545455, "max_line_length": 76, "alphanum_fraction": 0.5321482602, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6488199557261368}}
{"text": "/* \n * Copyright (c) 2021, Tetsuro Nagai\n */\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <cassert>\n#include <string>\n#include <boost/format.hpp>\n\nconstexpr int BUF_MAX=100000;\n\nconstexpr int DIM_DATA=2 ;\n\nusing std::string;\nusing std::vector;\nusing std::array;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\n\nint main(int argc, char** argv)\n{\n\n  if(argc != 1){\n        cerr << \"ERROR: no arguments allowed\"  <<endl;\n        cerr << \"Data should be provided via standard input\"  <<endl;\n        cerr << \"Use, for example, by cat data.txt | ./pdf_analyzer \\n\" <<endl;\n        cerr << \"First column must be coordinate, and the second must be probability.\"  <<endl;\n        cerr << \"The probability may not be normalized.\"  <<endl;\n        return -1;\n  }\n\n  vector<double> pdf;\n  vector<double> x;\n\n  string buf;\n  while (std::getline(std::cin, buf))\n  {\n    char tmp1[BUF_MAX];\n    char tmp2[BUF_MAX];\n    auto bsscanf = std::sscanf(buf.c_str(), \"%s %s\" , tmp1,tmp2);\n    if(bsscanf != DIM_DATA){\n        cerr << \"ERROR: not enough columns\\n\" << \"Exit!!\" <<endl;\n        return -1;\n    }\n\n    char *err;\n    double x_tmp=std::strtod(tmp1, &err);\n    if(*err!='\\0'){\n      cerr << \"ERROR: error to convert: \" << tmp1 << \"\\nExit!!\" <<endl;\n      return -1;\n    }\n    double pdf_tmp =std::strtod(tmp2, &err);\n    if(*err!='\\0'){\n      cerr << \"ERROR: error to convert: \" << tmp2 << \"\\nExit!!\" <<endl;\n      return -1;\n    }\n\n    if(pdf_tmp < 0){\n      cerr << \"ERROR: pdf should be non-negative\\nExit!!\" <<endl;\n      return -1;\n    }\n      \n    if(!x.empty() and x.back() > x_tmp){\n      cerr << \"ERROR: x should be in ascending (increasing) order\\nExit!!\" <<endl;\n      return -1;\n    }\n      \n    x.push_back(x_tmp);\n    pdf.push_back(pdf_tmp);\n  }\n  if(x.size() == 0){\n      cerr << \"ERROR: no data provided\\nExit!!\" <<endl;\n      return -1;\n  }\n\n\n  auto sum_pdf = std::accumulate(pdf.begin(), pdf.end(), 0.0);\n  std::transform(pdf.begin(), pdf.end(), pdf.begin(), [&sum_pdf](double x){return x / sum_pdf;});\n  auto ave_x = std::inner_product(pdf.begin(), pdf.end(), x.begin(), 0.0);\n\n  vector<double> residual_sq(pdf.size(), 0);\n  std::transform(x.begin(), x.end(), residual_sq.begin(), [&ave_x](double x){return (x-ave_x)*(x-ave_x);});\n\n  double  variance = std::inner_product(residual_sq.begin(), residual_sq.end(), pdf.begin(), 0.0) ;\n  double  stddev = sqrt(variance);\n\n  vector<double> residual_3th(pdf.size(), 0);\n  std::transform(x.begin(), x.end(), residual_3th.begin(), [&ave_x](double x){return (x-ave_x)*(x-ave_x)*(x-ave_x);});\n\n  auto skew = std::inner_product(residual_3th.begin(), residual_3th.end(), pdf.begin(), 0.0) / pow(stddev, 3) ;\n\n  vector<double> residual_4th(pdf.size(), 0);\n  std::transform(x.begin(), x.end(), residual_4th.begin(), [&ave_x](double x){return (x-ave_x)*(x-ave_x)*(x-ave_x)*(x-ave_x);});\n\n  auto kurtosis = std::inner_product(residual_4th.begin(), residual_4th.end(), pdf.begin(), 0.0) / pow(variance, 2) -3.0 ;\n\n  auto  at_max = std::max_element(pdf.begin(), pdf.end());\n  auto  mode = x[std::distance(pdf.begin(), at_max)];\n\n  //auto  median  = x[std::distance(pdf.begin(), at_max)];\n  vector<double> cdf(pdf.size(), 0);\n  std::partial_sum(pdf.begin(), pdf.end(), cdf.begin());\n\n  auto at_Q1 = find_if(cdf.begin(), cdf.end(), [](double x){return x>0.25? true : false;});\n  auto at_Q2 = find_if(cdf.begin(), cdf.end(), [](double x){return x>0.50? true : false;});\n  auto at_Q3 = find_if(cdf.begin(), cdf.end(), [](double x){return x>0.75? true : false;});\n\n  auto Q1 = x[std::distance(cdf.begin(), at_Q1)];\n  auto Q2 = x[std::distance(cdf.begin(), at_Q2)];\n  auto Q3 = x[std::distance(cdf.begin(), at_Q3)];\n\n\n  std::cout  << boost::format(\"#%12s %12s %12s %12s %12s\") % \"ave_x\"%\"stddev\" % \"variance\"  % \"skew\" % \"kurtosis\" << std::endl;\n  std::cout  << boost::format(\" %12.8g %12.8g %12.8g %12.8g %12.8g\\n\") % ave_x % stddev % variance % skew % kurtosis;\n\n  std::cout  << boost::format(\"#%12s %12s %12s\") % \"1Q\"%\"2Q(median)\" % \"3Q\"  << std::endl;\n  std::cout  << boost::format(\" %12.8g %12.8g %12.8g \\n\") % Q1  % Q2 % Q3 ;\n\n  std::cout  << boost::format(\"#%12s %12s %12s\") % \"mode \"%\"normalization\" % \"\"  << std::endl;\n  std::cout  << boost::format(\" %12.8g %12.8g\\n\") % mode  % sum_pdf ;\n\n  return EXIT_SUCCESS ;\n}\n", "meta": {"hexsha": "17acce8a2ad3d37409aad1812438e153060ca89d", "size": 4341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pdf_anlyzer.cpp", "max_stars_repo_name": "tnagai-github/pdf_analyzer", "max_stars_repo_head_hexsha": "dd31d84094166e6d23317f5861a7605afc60a250", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pdf_anlyzer.cpp", "max_issues_repo_name": "tnagai-github/pdf_analyzer", "max_issues_repo_head_hexsha": "dd31d84094166e6d23317f5861a7605afc60a250", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pdf_anlyzer.cpp", "max_forks_repo_name": "tnagai-github/pdf_analyzer", "max_forks_repo_head_hexsha": "dd31d84094166e6d23317f5861a7605afc60a250", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1374045802, "max_line_length": 128, "alphanum_fraction": 0.5966367196, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6488199345831044}}
{"text": "#include \"util.hpp\"\n#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <algorithm>\n\nvoid assert_chi_squared(const std::vector<int>& counts,\n                        const std::vector<double>& expected, double tolerance) {\n  int bins = counts.size();\n  EXPECT_EQ(bins, expected.size());\n\n  double chi = 0;\n  for (int i = 0; i < bins; ++i) {\n    double discrepancy = expected[i] - counts[i];\n    chi += discrepancy * discrepancy / expected[i];\n  }\n  boost::math::chi_squared dist(bins - 1);\n  double chi_threshold = quantile(complement(dist, tolerance));\n\n  EXPECT_TRUE(chi < chi_threshold);\n}\nvoid assert_matches_bins(const std::vector<double>& samples,\n                         const std::vector<double>& bin_boundaries,\n                         const std::vector<double>& proportions,\n                         double tolerance) {\n  ASSERT_GT(samples.size(), 0);\n  int N = samples.size();\n  std::vector<double> mysamples = samples;\n  std::sort(mysamples.begin(), mysamples.end());\n\n  ASSERT_GT(bin_boundaries.size(), 0);\n  ASSERT_TRUE(bin_boundaries.size() == proportions.size());\n  int K = bin_boundaries.size();\n  std::vector<double> expected;\n  for (int i = 0; i < K; i++) {\n    ASSERT_TRUE(proportions[i] >= 0 && proportions[i] <= 1);\n    expected.push_back(proportions[i] * N);\n  }\n\n  std::vector<int> counts(K);\n  size_t current_index = 0;\n  for (int i = 0; i < N; ++i) {\n    while (mysamples[i] >= bin_boundaries[current_index]) {\n      ++current_index;\n      EXPECT_TRUE(current_index < bin_boundaries.size());\n    }\n    ++counts[current_index];\n  }\n  assert_chi_squared(counts, expected, tolerance);\n}\nvoid assert_matches_quantiles(const std::vector<double>& samples,\n                              const std::vector<double>& quantiles,\n                              double tolerance) {\n  int K = quantiles.size();\n  std::vector<double> proportions;\n  for (int i = 0; i < K; ++i)\n    proportions.push_back(1.0 / K);\n\n  assert_matches_bins(samples, quantiles, proportions, tolerance);\n}\n", "meta": {"hexsha": "9f9e8427b1740b83df0f9e73105dcd3fef37effa", "size": 2016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/scal/prob/util.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/prim/scal/prob/util.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/prim/scal/prob/util.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6, "max_line_length": 80, "alphanum_fraction": 0.6299603175, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.648806520839624}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearloadvector.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <functional>\n\nnamespace ElementMatrixComputation {\n\nnamespace {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector4d computeLoadVector(\n    const Eigen::MatrixXd &vertices,\n    std::function<double(const Eigen::Vector2d &)> f) {\n  // Number of nodes of the element: triangles = 3, rectangles = 4\n  const int num_nodes = vertices.cols();\n  // Vector for returning element vector\n  Eigen::Vector4d elem_vec = Eigen::Vector4d::Zero();\n#if SOLUTION\n  // Area of the cell\n  double area;\n  // Midpoints of edges in the reference cell\n  Eigen::MatrixXd midpoints(2, num_nodes);\n  switch (num_nodes) {\n    case 3: {\n      // Compute cell area for triangles\n      area = 0.5 * ((vertices(0, 1) - vertices(0, 0)) *\n                        (vertices(1, 2) - vertices(1, 0)) -\n                    (vertices(1, 1) - vertices(1, 0)) *\n                        (vertices(0, 2) - vertices(0, 0)));\n      // clang-format off\n      midpoints << vertices(0, 0) + vertices(0, 1),\n\tvertices(0, 1) + vertices(0, 2),\n\tvertices(0, 2) + vertices(0, 0),\n\tvertices(1, 0) + vertices(1, 1),\n\tvertices(1, 1) + vertices(1, 2),\n\tvertices(1, 2) + vertices(1, 0);\n      // clang-format on\n      break;\n    }\n    case 4: {\n      // Compute cell area for rectangles\n      area =\n          (vertices(0, 1) - vertices(0, 0)) * (vertices(1, 3) - vertices(1, 0));\n      // clang-format off\n      midpoints << vertices(0, 0) + vertices(0, 1),\n\tvertices(0, 1) + vertices(0, 2),\n\tvertices(0, 2) + vertices(0, 3),\n\tvertices(0, 3) + vertices(0, 0),\n\tvertices(1, 0) + vertices(1, 1),\n\tvertices(1, 1) + vertices(1, 2),\n\tvertices(1, 2) + vertices(1, 3),\n\tvertices(1, 3) + vertices(1, 0);\n      // clang-format on\n      break;\n    }\n    default: {\n      LF_ASSERT_MSG(false, \"Illegal entity type!\");\n      break;\n    }\n  }                  // end switch\n  midpoints *= 0.5;  // The factor 1/2\n  // Evaluate f(x) at the quadrature points, i.e. the midpoints of the edges\n  Eigen::VectorXd fvals = Eigen::VectorXd::Zero(4);\n  for (int i = 0; i < num_nodes; ++i) {\n    fvals(i) = f(midpoints.col(i));\n  }\n  // Midpoint quadrature for all nodes of the element\n  for (int k = 0; k < num_nodes; k++) {\n    // Contribution from one end of an edge\n    elem_vec[k] += 0.5 * fvals(k);\n    // Contribution from the other end of the end\n    elem_vec[(k + 1) % num_nodes] += 0.5 * fvals(k);\n  }\n  // Rescale with quadrature weights\n  elem_vec *= (area / num_nodes);\n#else\n\n  //====================\n  // Your code goes here\n  //====================\n\n#endif\n  return elem_vec;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace\n\nEigen::Vector4d MyLinearLoadVector::Eval(const lf::mesh::Entity &cell) {\n  // Topological type of the cell\n  const lf::base::RefEl ref_el{cell.RefEl()};\n  const lf::base::size_type num_nodes{ref_el.NumNodes()};\n\n  // Obtain the vertex coordinates of the cell, which completely\n  // describe its shape.\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n\n  // Matrix storing corner coordinates in its columns\n  auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n\n  return computeLoadVector(vertices, f_);\n}\n\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "1270c6350ddebd4145826243f1ecb62aeb30d90e", "size": 3440, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/ElementMatrixComputation/mastersolution/mylinearloadvector.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/ElementMatrixComputation/mastersolution/mylinearloadvector.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/ElementMatrixComputation/mastersolution/mylinearloadvector.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 29.4017094017, "max_line_length": 80, "alphanum_fraction": 0.6171511628, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6488065102014404}}
{"text": "/// My typedefs\n#include <boost/cstdint.hpp>\n#include <boost/integer_traits.hpp>\n\ntypedef int32_t    node_t;\ntypedef int32_t    edge_t;\ntypedef int64_t    cost_t;\n\n/// From STL library\n#include <fstream>\n\n#include <vector>\nusing std::vector;\n\n#include <string>\n\nusing std::pair;\nusing std::make_pair;\n\n/// Boost Timer\n#include <boost/progress.hpp>\nusing boost::timer;\n\n/// HashMap by google or-tools\n#include \"base/logging.h\"\n#include \"base/commandlineflags.h\"\n#include \"base/hash.h\"\n#include \"base/map-util.h\"\n#include \"base/callback.h\"\n#include \"graph/shortestpaths.h\"\n\ntypedef std::pair<node_t, node_t>                        PairNode;\ntypedef operations_research::hash_map<PairNode, cost_t>  ArcMap;\ntypedef operations_research::hash_map<node_t, cost_t>    NodeMap;\n\n/// Graph class as callback as required by Google Or-Tools\nstruct GraphByCallback {\n   vector<NodeMap> C;\n   cost_t kDisconnectedDistance;\n   GraphByCallback( const vector<NodeMap>& _C, cost_t _kDisconnectedDistance ) \n      : C(_C), kDisconnectedDistance(_kDisconnectedDistance) {}\n   inline cost_t hasArc(node_t i, node_t j) {\n      NodeMap::iterator p_iter = C[i].find(j);\n      if ( p_iter != C[i].end() )\n         return p_iter->second;\n      else\n         return kDisconnectedDistance;\n   }\n};\n\n/// Read input data, build graph, and run Dijkstra\ncost_t runDijkstra( char* argv[] ) {\n   /// Read instance from the OR-lib\n   std::ifstream infile(argv[1]); \n   if (!infile) \n      exit ( EXIT_FAILURE ); \n\n   int n;     /// Number of variables\n   int m;     /// Number of constraints\n\n   // reads file of the form\n   // #nodes #edges\n   // e_1 = v_i v_j cost[e_m]\n   // ..\n   // e_m = v_i v_j cost[e_m]\n   \n   /// Read the first line\n   infile >> n >> m;\n   fprintf(stdout,\"n %d, m %d\\n\", n, m);\n   /// Build the graph\n   int avg_degree = m/n+1;\n   vector<NodeMap> A;\n   for ( int i = 0; i < n; ++i ) {\n      NodeMap node(avg_degree);\n      A.push_back(node);\n   }\n   /// Read arcs from file\n   int v, w;\n   cost_t c;\n   for ( int i = 0; i < m; i++ ) {\n      infile >> v >> w >> c;\n      A[v-1][w-1] = c;\n   }\n   \n   /// Elaborate input data for Dijkstra's algorithm \n   cost_t kMaxInf = std::numeric_limits<cost_t>::max();\n   cost_t T_dist;\n\n   timer TIMER;\n   for ( int i = 0; i < 50; ++i ) {\n      double t0 = TIMER.elapsed();\n      node_t S = i;\n      node_t T = n-1-i;\n      vector<node_t> paths;\n      GraphByCallback call(A,kMaxInf);\n      ResultCallback2<cost_t, node_t, node_t>* const arc_callback =\n         NewPermanentCallback(&call, &GraphByCallback::hasArc);\n      operations_research::DijkstraShortestPath(n, S, T, arc_callback, kMaxInf, &paths);\n      /// Compute exact distance (the path is stored in the reversed order)\n      T_dist = 0.0;\n      for ( unsigned int j = 0; j < paths.size()-1; ++j ) \n         T_dist += A[paths[j+1]][paths[j]];\n      fprintf(stdout,\"Time %.4f Cost %\"PRId64\"\\n\", TIMER.elapsed()-t0, T_dist);\n   }\n   fprintf(stdout,\"Tot %.4f\\n\", TIMER.elapsed());\n   \n   return T_dist;\n}\n\n/// Main function\nint\nmain (int argc, char **argv)\n{\n   if ( argc != 2 ) {\n      fprintf(stdout, \"usage: ./dijkstra <filename>\\n\");\n      exit ( EXIT_FAILURE );\n   }\n   /// Measure overall time\n   timer TIMER;\n   /// Invoke the different Dijkstra algorithm implementations\n   cost_t T_dist = runDijkstra(argv);\n   /// Print basic figures\n   fprintf(stdout,\"Cost %\"PRId64\" - Time %.3f\\n\", T_dist, TIMER.elapsed());\n\n   return 0;\n}\n", "meta": {"hexsha": "4fa3b459027ce6e6f9324509c1297404787c762b", "size": 3425, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Dijkstra/dijkstra_or-tools.cc", "max_stars_repo_name": "772700563/MyBlogEntries", "max_stars_repo_head_hexsha": "ea579ab0698d59bc1af0fac08a059c16f11336c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T09:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T05:16:33.000Z", "max_issues_repo_path": "Dijkstra/dijkstra_or-tools.cc", "max_issues_repo_name": "772700563/MyBlogEntries", "max_issues_repo_head_hexsha": "ea579ab0698d59bc1af0fac08a059c16f11336c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-07-08T03:27:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-21T19:35:11.000Z", "max_forks_repo_path": "Dijkstra/dijkstra_or-tools.cc", "max_forks_repo_name": "772700563/MyBlogEntries", "max_forks_repo_head_hexsha": "ea579ab0698d59bc1af0fac08a059c16f11336c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-08-03T06:33:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T12:58:26.000Z", "avg_line_length": 26.968503937, "max_line_length": 88, "alphanum_fraction": 0.6259854015, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6488064971255133}}
{"text": "#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <iostream>\n#include <random> // Requires C++ 11\n\n#include <Spectra/SymGEigsSolver.h>\n#include <Spectra/MatOp/DenseSymMatProd.h>\n#include <Spectra/MatOp/DenseCholesky.h>\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include <Spectra/MatOp/SparseCholesky.h>\n\nusing namespace Spectra;\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\ntypedef Eigen::MatrixXd Matrix;\ntypedef Eigen::VectorXd Vector;\ntypedef Eigen::SparseMatrix<double> SpMatrix;\n\n// Traits to obtain operation type from matrix type\ntemplate <typename MatType>\nstruct OpTypeTrait\n{\n    typedef DenseSymMatProd<double> OpType;\n};\n\ntemplate <>\nstruct OpTypeTrait<SpMatrix>\n{\n    typedef SparseSymMatProd<double> OpType;\n};\n\ntemplate <typename MatType>\nstruct BOpTypeTrait\n{\n    typedef DenseCholesky<double> OpType;\n};\n\ntemplate <>\nstruct BOpTypeTrait<SpMatrix>\n{\n    typedef SparseCholesky<double> OpType;\n};\n\n// Generate random sparse matrix\nSpMatrix sprand(int size, double prob = 0.5)\n{\n    SpMatrix mat(size, size);\n    std::default_random_engine gen;\n    gen.seed(0);\n    std::uniform_real_distribution<double> distr(0.0, 1.0);\n    for(int i = 0; i < size; i++)\n    {\n        for(int j = 0; j < size; j++)\n        {\n            if(distr(gen) < prob)\n                mat.insert(i, j) = distr(gen) - 0.5;\n        }\n    }\n    return mat;\n}\n\n// Generate data for testing\nvoid gen_dense_data(int n, Matrix& A, Matrix& B)\n{\n    Matrix M = Eigen::MatrixXd::Random(n, n);\n    A = M + M.transpose();\n    B = M.transpose() * M;\n    // To make sure B is positive definite\n    B.diagonal() += Eigen::VectorXd::Random(n).cwiseAbs();\n}\n\nvoid gen_sparse_data(int n, SpMatrix& A, SpMatrix& B)\n{\n    // Eigen solver only uses the lower triangle of A,\n    // so we don't need to make A symmetric here.\n    A = sprand(n, 0.1);\n    B = A.transpose() * A;\n    // To make sure B is positive definite\n    for(int i = 0; i < n; i++)\n        B.coeffRef(i, i) += 0.1;\n}\n\n\n\ntemplate <typename MatType, int SelectionRule>\nvoid run_test(const MatType& A, const MatType& B, int k, int m, bool allow_fail = false)\n{\n    typedef typename OpTypeTrait<MatType>::OpType OpType;\n    typedef typename BOpTypeTrait<MatType>::OpType BOpType;\n    OpType op(A);\n    BOpType Bop(B);\n    // Make sure B is positive definite and the decomposition is successful\n    REQUIRE( Bop.info() == SUCCESSFUL );\n\n    SymGEigsSolver<double, SelectionRule, OpType, BOpType, GEIGS_CHOLESKY> eigs(&op, &Bop, k, m);\n    eigs.init();\n    int nconv = eigs.compute(100); // maxit = 100 to reduce running time for failed cases\n    int niter = eigs.num_iterations();\n    int nops  = eigs.num_operations();\n\n    if(allow_fail)\n    {\n        if( eigs.info() != SUCCESSFUL )\n        {\n            WARN( \"FAILED on this test\" );\n            std::cout << \"nconv = \" << nconv << std::endl;\n            std::cout << \"niter = \" << niter << std::endl;\n            std::cout << \"nops  = \" << nops  << std::endl;\n            return;\n        }\n    } else {\n        INFO( \"nconv = \" << nconv );\n        INFO( \"niter = \" << niter );\n        INFO( \"nops  = \" << nops );\n        REQUIRE( eigs.info() == SUCCESSFUL );\n    }\n\n    Vector evals = eigs.eigenvalues();\n    Matrix evecs = eigs.eigenvectors();\n\n    Matrix resid = A.template selfadjointView<Eigen::Lower>() * evecs -\n                   B.template selfadjointView<Eigen::Lower>() * evecs * evals.asDiagonal();\n    const double err = resid.array().abs().maxCoeff();\n\n    INFO( \"||AU - BUD||_inf = \" << err );\n    REQUIRE( err == Approx(0.0).margin(1e-9) );\n}\n\ntemplate <typename MatType>\nvoid run_test_sets(const MatType& A, const MatType& B, int k, int m)\n{\n    SECTION( \"Largest Magnitude\" )\n    {\n        run_test<MatType, LARGEST_MAGN>(A, B, k, m);\n    }\n    SECTION( \"Largest Value\" )\n    {\n        run_test<MatType, LARGEST_ALGE>(A, B, k, m);\n    }\n    SECTION( \"Smallest Magnitude\" )\n    {\n        run_test<MatType, SMALLEST_MAGN>(A, B, k, m, true);\n    }\n    SECTION( \"Smallest Value\" )\n    {\n        run_test<MatType, SMALLEST_ALGE>(A, B, k, m);\n    }\n    SECTION( \"Both Ends\" )\n    {\n        run_test<MatType, BOTH_ENDS>(A, B, k, m);\n    }\n}\n\nTEST_CASE(\"Generalized eigensolver of symmetric real matrix [10x10]\", \"[geigs_sym]\")\n{\n    std::srand(123);\n\n    Matrix A, B;\n    gen_dense_data(10, A, B);\n    int k = 3;\n    int m = 6;\n\n    run_test_sets(A, B, k, m);\n}\n\nTEST_CASE(\"Generalized eigensolver of symmetric real matrix [100x100]\", \"[geigs_sym]\")\n{\n    std::srand(123);\n\n    Matrix A, B;\n    gen_dense_data(100, A, B);\n    int k = 10;\n    int m = 20;\n\n    run_test_sets(A, B, k, m);\n}\n\nTEST_CASE(\"Generalized eigensolver of symmetric real matrix [1000x1000]\", \"[geigs_sym]\")\n{\n    std::srand(123);\n\n    Matrix A, B;\n    gen_dense_data(1000, A, B);\n    int k = 20;\n    int m = 50;\n\n    run_test_sets(A, B, k, m);\n}\n\nTEST_CASE(\"Generalized eigensolver of sparse symmetric real matrix [10x10]\", \"[geigs_sym]\")\n{\n    std::srand(123);\n\n    // Eigen solver only uses the lower triangle\n    SpMatrix A, B;\n    gen_sparse_data(10, A, B);\n    int k = 3;\n    int m = 6;\n\n    run_test_sets(A, B, k, m);\n}\n\nTEST_CASE(\"Generalized eigensolver of sparse symmetric real matrix [100x100]\", \"[geigs_sym]\")\n{\n    std::srand(123);\n\n    // Eigen solver only uses the lower triangle\n    SpMatrix A, B;\n    gen_sparse_data(100, A, B);\n    int k = 10;\n    int m = 20;\n\n    run_test_sets(A, B, k, m);\n}\n\nTEST_CASE(\"Generalized eigensolver of sparse symmetric real matrix [1000x1000]\", \"[geigs_sym]\")\n{\n    std::srand(123);\n\n    // Eigen solver only uses the lower triangle\n    SpMatrix A, B;\n    gen_sparse_data(1000, A, B);\n    int k = 20;\n    int m = 50;\n\n    run_test_sets(A, B, k, m);\n}\n", "meta": {"hexsha": "61663492d07258a603d5ac474ad3eafc91df3611", "size": 5681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/depends/spectra/test/SymGEigsCholesky.cpp", "max_stars_repo_name": "venumb/zSpace", "max_stars_repo_head_hexsha": "a85de6d29c9099fcbd3d2c67f5f1be315eed6dc4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T16:52:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T16:52:23.000Z", "max_issues_repo_path": "cpp/depends/spectra/test/SymGEigsCholesky.cpp", "max_issues_repo_name": "venumb/zSpace", "max_issues_repo_head_hexsha": "a85de6d29c9099fcbd3d2c67f5f1be315eed6dc4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-24T09:16:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-26T18:21:36.000Z", "max_forks_repo_path": "cpp/depends/spectra/test/SymGEigsCholesky.cpp", "max_forks_repo_name": "venumb/ZSPACE", "max_forks_repo_head_hexsha": "c7d884f5423edd845a00c1b65c887d0371b360c3", "max_forks_repo_licenses": ["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.7, "max_line_length": 97, "alphanum_fraction": 0.6160887168, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6487793068233823}}
{"text": "//\n// Created by chen-tian on 7/24/17.\n//\n\n#include \"pose_estimate_3d3d.h\"\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nvoid pose_estimate_3d3d::pose_estimation_3d3d\n        (const vector<Point3f> &pts1,\n         const vector<Point3f> &pts2,\n         Mat &R, Mat &t)\n{\n    Point3f p1, p2;  //center of mass\n    int N = pts1.size();\n    for ( int i = 0; i < N; i++ )\n    {\n        p1 += pts1[i];\n        p2 += pts2[i];\n    }\n\n    p1 /= N;\n    p2 /= N;\n    vector<Point3f> q1(N), q2(N);//remove the center\n    for ( int i = 0; i < N; i++ )\n    {\n        q1[i] = pts1[i] - p1;\n        q2[i] = pts2[i] - p2;\n    }\n\n    //compute q1*q2^T\n    Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n    for ( int i = 0; i<N; i++ )\n    {\n        W += Eigen::Vector3d( q1[i].x, q1[i].y, q1[i].z )* Eigen::Vector3d( q2[i].x, q2[i].y, q2[i].z ).transpose();\n    }\n    cout<<\"W=\"<<W<<endl;\n\n    //SVD ON W\n    Eigen::JacobiSVD<Eigen::Matrix3d> svd(W, Eigen::ComputeFullU|Eigen::ComputeFullV);\n    Eigen::Matrix3d U = svd.matrixU();\n    Eigen::Matrix3d V = svd.matrixV();\n    cout<<\"U=\"<<U<<endl;\n    cout<<\"V=\"<<V<<endl;\n\n    Eigen::Matrix3d R_ = U*(V.transpose() );\n    Eigen::Vector3d t_ = Eigen::Vector3d( p1.x, p1.y, p1.z ) - R_* Eigen::Vector3d( p2.x, p2.y, p2.z );\n\n    //convert to cv::Mat\n    R = (Mat_<double>(3,3)<<\n                          R_(0,0), R_(0,1),R_(0,2),\n            R_(1,0),R_(1,1),R_(1,2),\n            R_(2,0),R_(2,1),R_(2,2) );\n    t = ( Mat_<double>(3,1)<< t_(0,0),t_(1,0),t_(2,0));\n}", "meta": {"hexsha": "8f234d1c559df513ac12f96cf1f2d33a2d3b4d5d", "size": 1628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7_VO1/pose_estimation_3d3d/src/pose_estimate_3d3d.cpp", "max_stars_repo_name": "ClovisChen/slam14", "max_stars_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch7_VO1/pose_estimation_3d3d/src/pose_estimate_3d3d.cpp", "max_issues_repo_name": "ClovisChen/slam14", "max_issues_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch7_VO1/pose_estimation_3d3d/src/pose_estimate_3d3d.cpp", "max_forks_repo_name": "ClovisChen/slam14", "max_forks_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6885245902, "max_line_length": 116, "alphanum_fraction": 0.5245700246, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.64868229714921}}
{"text": "\n#include <boost/test/unit_test.hpp>\n#include \"matrix.h\"\n\nnamespace\n{\n\ntemplate<int N> void\ntest_axis_angle_i(math::vec<3> const &src, math::vec<3> const &axis, math::scalar angle, math::vec<3> const &res)\n{\n\tmath::matrix<N,N> m;\n\tm.rotation(axis, angle);\n\n\tmath::vec<3> result = src * m;\n\n\tBOOST_REQUIRE ((result.length() - src.length()) < math::EPSILON);\n\tBOOST_REQUIRE ((res - result).length() < math::EPSILON);\n}\n\nvoid test_axis_angle(math::vec<3> const &src, math::vec<3> const &axis, math::scalar angle, math::vec<3> const &res)\n{\n\ttest_axis_angle_i<3>(src, axis, angle, res);\n\ttest_axis_angle_i<4>(src, axis, angle, res);\n\n\ttest_axis_angle_i<3>(res, axis, -angle, src);\n\ttest_axis_angle_i<4>(res, axis, -angle, src);\n}\n\ntemplate<int N> void\ntest_rotation_i(math::vec<3> const &src, math::vec<3> const &angles, math::vec<3> const &res)\n{\n\tmath::matrix<N,N> m;\n\tm.rotation(angles);\n\n\tmath::vec<3> result = src * m;\n\n\tBOOST_REQUIRE ((result.length() - src.length()) < math::EPSILON);\n\tBOOST_REQUIRE ((res - result).length() < math::EPSILON);\n}\n\nvoid test_rotation(math::vec<3> const &src, math::vec<3> const &angles, math::vec<3> const &res)\n{\n\ttest_rotation_i<3>(src, angles, res);\n\ttest_rotation_i<4>(src, angles, res);\n\n\ttest_rotation_i<3>(res, -angles, src);\n\ttest_rotation_i<4>(res, -angles, src);\n}\n\n}\n\nBOOST_AUTO_TEST_SUITE (test_matrix)\n\nBOOST_AUTO_TEST_CASE (test_ijk)\n{\n\tmath::vec<3> const i(1, 0, 0), j(0, 1, 0), k(0, 0, 1);\n\n\ttest_axis_angle(i, j, -math::PI / 2, k);\n\ttest_rotation(i, -math::PI / 2 * j, k);\n\n\ttest_axis_angle(j, k, -math::PI / 2, i);\n\ttest_rotation(j, -math::PI / 2 * k, i);\n\n\ttest_axis_angle(k, i, -math::PI / 2, j);\n\ttest_rotation(k, -math::PI / 2 * i, j);\n}\n\nBOOST_AUTO_TEST_CASE (test_pi4)\n{\n\t{\n\t\tmath::vec<3> src(1, 0, 0);\n\t\tmath::vec<3> res = math::normalize(math::vec<3>(1, -1, 0));\n\n\t\ttest_rotation(src, math::vec<3>(0, 0, -math::PI / 4), res);\n\t\ttest_axis_angle(src, math::vec<3>(0, 0, 1), -math::PI / 4, res);\n\t}\n\n\t{\n\t\tmath::vec<3> src(0, 1, 0);\n\t\tmath::vec<3> res = math::normalize(math::vec<3>(1, 1, 0));\n\n\t\ttest_rotation(src, math::vec<3>(0, 0, -math::PI / 4), res);\n\t\ttest_axis_angle(src, math::vec<3>(0, 0, 1), -math::PI / 4, res);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE (test_pi4_number_2)\n{\n\t{\n\t\tmath::vec<3> src(1, 0, 0);\n\t\tmath::vec<3> res = math::normalize(math::vec<3>(1, 1, 0));\n\n\t\ttest_rotation(src, math::vec<3>(0, 0, math::PI / 4), res);\n\t\ttest_axis_angle(src, math::vec<3>(0, 0, 1), math::PI / 4, res);\n\t}\n\n\t{\n\t\tmath::vec<3> src(0, 1, 0);\n\t\tmath::vec<3> res = math::normalize(math::vec<3>(-1, 1, 0));\n\n\t\ttest_rotation(src, math::vec<3>(0, 0, math::PI / 4), res);\n\t\ttest_axis_angle(src, math::vec<3>(0, 0, 1), math::PI / 4, res);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE (test_matrix_inverse_4x4_1)\n{\n\tmath::matrix<4,4> M, I, R, U;\n\n\tM.scaling(math::scalar(rand() + 1), math::scalar(rand() + 1), math::scalar(rand() + 1));\n\n\tM.inverse(I);\n\n\tR = M * I;\n\tU.identity();\n\n\tBOOST_REQUIRE(math::equal(R, U));\n}\n\nBOOST_AUTO_TEST_CASE (test_matrix_inverse_4x4_2)\n{\n\tmath::matrix<4,4> M, I, R, U;\n\n\tM.rotation(rand() * math::PI / RAND_MAX , rand() * math::PI / RAND_MAX, rand() * math::PI / RAND_MAX);\n\n\tM.inverse(I);\n\n\tR = M * I;\n\tU.identity();\n\n\tBOOST_REQUIRE(math::equal(R, U));\n}\n\n\nBOOST_AUTO_TEST_CASE (test_matrix_inverse_4x4_3)\n{\n\tmath::matrix<4,4> M, I, R, U;\n\n\tM.translation(rand() * 10.0f / RAND_MAX, rand() * 10.0f / RAND_MAX, rand() * 10.0f / RAND_MAX);\n\n\tM.inverse(I);\n\n\tR = M * I;\n\tU.identity();\n\n\tBOOST_REQUIRE(math::equal(R, U));\n}\n\nBOOST_AUTO_TEST_CASE (test_matrix_inverse_4x4_4)\n{\n\tmath::matrix<4,4> M, I, R, U;\n\n\tM.translation(rand() * 10.0f / RAND_MAX, rand() * 10.0f / RAND_MAX, rand() * 10.0f / RAND_MAX);\n\tM.rotate(rand() * math::PI / RAND_MAX , rand() * math::PI / RAND_MAX, rand() * math::PI / RAND_MAX);\n\n\tM.inverse(I);\n\n\tR = M * I;\n\tU.identity();\n\n\tBOOST_REQUIRE(math::equal(R, U));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f4d85161af07f8245173b637e6f964f398ab92f7", "size": 3865, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/math/test_matrix.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/math/test_matrix.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/test_matrix.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4242424242, "max_line_length": 116, "alphanum_fraction": 0.6271668823, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6486822948142084}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[correct\r\n//` Shows how to correct a polygon with respect to its orientation and closure\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\n\r\n#include <boost/assign.hpp>\r\n\r\nint main()\r\n{\r\n    using boost::assign::tuple_list_of;\r\n\r\n    typedef boost::geometry::model::polygon\r\n        <\r\n            boost::tuple<int, int>\r\n        > clockwise_closed_polygon;\r\n\r\n    clockwise_closed_polygon cwcp;\r\n\r\n    // Fill it counterclockwise (so wrongly), forgetting the closing point\r\n    boost::geometry::exterior_ring(cwcp) = tuple_list_of(0, 0)(10, 10)(0, 9);\r\n\r\n    // Add a counterclockwise closed inner ring (this is correct)\r\n    boost::geometry::interior_rings(cwcp).push_back(tuple_list_of(1, 2)(4, 6)(2, 8)(1, 2));\r\n\r\n    // Its area should be negative (because of wrong orientation)\r\n    //     and wrong (because of omitted closing point)\r\n    double area_before = boost::geometry::area(cwcp);\r\n\r\n    // Correct it!\r\n    boost::geometry::correct(cwcp);\r\n\r\n    // Check its new area\r\n    double area_after = boost::geometry::area(cwcp);\r\n\r\n    // And output it\r\n    std::cout << boost::geometry::dsv(cwcp) << std::endl;\r\n    std::cout << area_before << \" -> \" << area_after << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[correct_output\r\n/*`\r\nOutput:\r\n[pre\r\n(((0, 0), (0, 9), (10, 10), (0, 0)), ((1, 2), (4, 6), (2, 8), (1, 2)))\r\n-7 -> 38\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "0be5834059f9a3549282ce1f72463bcbc2793e28", "size": 1877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/correct.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/doc/src/examples/algorithms/correct.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/doc/src/examples/algorithms/correct.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 27.2028985507, "max_line_length": 92, "alphanum_fraction": 0.6457112413, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.6486463371593395}}
{"text": "/*  \n*   Copyright 2017-2018 Simon Raschke\n*\n*   Licensed under the Apache License, Version 2.0 (the \"License\");\n*   you may not use this file except in compliance with the License.\n*   You may obtain a copy of the License at\n*\n*       http://www.apache.org/licenses/LICENSE-2.0\n*\n*   Unless required by applicable law or agreed to in writing, software\n*   distributed under the License is distributed on an \"AS IS\" BASIS,\n*   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n*   See the License for the specific language governing permissions and\n*   limitations under the License.\n*/\n\n#pragma once\n\n#include <cmath>\n#include <cstdint>\n#include <sstream>\n#include <exception>\n#if __has_include(<Eigen/Core>)\n#include <Eigen/Core>\n#elif __has_include(<eigen3/Eigen/Core>)\n#include <eigen3/Eigen/Core>\n#endif\n    \n\n\nnamespace enhance\n{\n    // number of digits\n    template <typename T>\n    std::uint16_t numDigits(T number)\n    {\n        std::uint16_t digits = 0;\n        if (number < 0) digits = 1; // remove this line if '-' counts as a digit\n        std::uint32_t helper = static_cast<int>(number);\n        while (helper) \n        {\n            helper /= 10;\n            digits++;\n        }\n        return digits;\n    }\n    \n\n\n    // angle between two eigen vectors\n    // vectors dont have to be normalized\n    // will give signed result\n    template<typename DERIVED1, typename DERIVED2>\n    constexpr float directed_angle(const DERIVED1& v1, const DERIVED2& v2)\n    {\n        assert(std::isfinite(std::atan2(v2.normalized()(1), v2.normalized()(0)) - std::atan2(v1.normalized()(1), v1.normalized()(0))));\n        return std::atan2(v2.normalized()(1), v2.normalized()(0)) - std::atan2(v1.normalized()(1), v1.normalized()(0));\n    }\n    \n\n\n    // will give unsigned result\n    template<typename DERIVED1, typename DERIVED2>\n    constexpr float absolute_angle(const DERIVED1& v1, const DERIVED2& v2)\n    {\n        return std::abs(directed_angle(v1,v2));\n    }\n    \n\n    \n    //directed angle normalized to 0 to 360\u00b0\n    template<typename DERIVED1, typename DERIVED2>\n    constexpr float normalized_angle(const DERIVED1& v1, const DERIVED2& v2)\n    {\n        const float angle = directed_angle(v1,v2);\n        return angle < 0.f ? angle+M_PI : angle;\n    }\n        \n    \n    \n    // calculate rad from given deg\n    // expects floating pioint type\n    template<typename T, typename ENABLER = typename std::enable_if<std::is_floating_point<T>::value>::type>\n    constexpr T deg_to_rad(const T& __deg) noexcept\n    {\n        return __deg*M_PI/180;\n    }\n    \n    \n    \n    // calculate deg from given rad\n    // expects floating pioint type\n    template<typename T, typename ENABLER = typename std::enable_if<std::is_floating_point<T>::value>::type>\n    constexpr T rad_to_deg(const T& __rad) noexcept\n    {\n        return __rad/M_PI*180;\n    }\n    \n    \n    \n    // calculates the volume of a sphere given its radius\n    // may throw if radius is negative\n    template<typename T>\n    constexpr T sphere_volume(const T& __rad) \n    {\n        if(__rad < 0) throw std::logic_error(\"radius must not be negative\");\n        return M_PI*__rad*__rad*__rad*4.f/3.f;\n    }\n    \n    \n    \n    // calculates the surface of a sphere given its radius\n    // may throw if radius is negative\n    template<typename T>\n    constexpr T sphere_surface(const T& __rad) \n    {\n        if(__rad < 0) throw std::logic_error(\"radius must not be negative\");\n        return M_PI*__rad*__rad*4.f;\n    }\n    \n    \n    \n    // calculates the area of a circle given its radius\n    // may throw if radius is negative\n    template<typename T>\n    constexpr T circle_area(const T& __rad) \n    {\n        if(__rad < 0) throw std::logic_error(\"radius must not be negative\");\n        return M_PI*__rad*__rad;\n    }\n    \n    \n    \n    // calculates the radius of a circle given its area\n    // may throw if area is negative\n    template<typename T>\n    constexpr T circle_area_to_radius(const T& __area)\n    {\n        if(__area < 0) throw std::logic_error(\"area must not be negative\");\n        return std::sqrt( __area/M_PI );\n    }\n    \n    \n    \n    // calculates the volume of a cone given its base radius and heigt\n    // may throw if area is negative\n    // may throw if height is negative\n    template<typename T>\n    constexpr T cone_volume(const T& __rad, const T& __height) \n    {\n        if(__rad < 0) throw std::logic_error(\"radius must not be negative\");\n        if(__height < 0) throw std::logic_error(\"height must not be negative\");\n        return enhance::circle_area(__rad)*__height/(static_cast<T>(3));\n    }\n\n\n\n    template<std::size_t N, typename T>\n    constexpr typename std::enable_if<std::is_floating_point<T>::value,T>::type nth_root(const T& __val )\n    {\n        return std::pow(__val, 1.0/N);\n    }\n}", "meta": {"hexsha": "5e65e65e7f8849fc1882c8f85c3175b4e8f83520", "size": 4812, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "enhance/math_utility.hpp", "max_stars_repo_name": "simonraschke/vesicle", "max_stars_repo_head_hexsha": "3b9b5529c3f36bdeff84596bc59509781b103ead", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T17:24:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T17:24:52.000Z", "max_issues_repo_path": "enhance/math_utility.hpp", "max_issues_repo_name": "simonraschke/vesicle", "max_issues_repo_head_hexsha": "3b9b5529c3f36bdeff84596bc59509781b103ead", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "enhance/math_utility.hpp", "max_forks_repo_name": "simonraschke/vesicle", "max_forks_repo_head_hexsha": "3b9b5529c3f36bdeff84596bc59509781b103ead", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5214723926, "max_line_length": 135, "alphanum_fraction": 0.6417290108, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6486062881967635}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_LOGSPACE_SUB_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_LOGSPACE_SUB_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing logspace_sub capabilities\n\n     Compute the log of a sum from logs of terms\n     properly compute \\f$\\log (\\exp (\\log x) - \\exp (\\log y))\\f$\n\n    @par Semantic:\n\n    For every parameters of floating type T:\n\n    @code\n    T r = logspace_sub(x, y);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r =  log(exp(log(x)) - exp(log(y)));\n    @endcode\n\n  **/\n  const boost::dispatch::functor<tag::logspace_sub_> logspace_sub = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/logspace_sub.hpp>\n#include <boost/simd/function/simd/logspace_sub.hpp>\n\n#endif\n", "meta": {"hexsha": "2824f102bd70e4240a5217a91ff2d4d6340656a1", "size": 1220, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/logspace_sub.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/logspace_sub.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/logspace_sub.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4, "max_line_length": 100, "alphanum_fraction": 0.5860655738, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818987, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6485985283988829}}
{"text": "#pragma once\n\n#include <vpp/vpp.hh>\n#include <list>\n#include <iostream>\n#include <iterator>\n#include <random>\n\n#include <opencv2/highgui.hpp>\n#include <opencv2/videoio.hpp>\n#include <vpp/vpp.hh>\n#include <vpp/utils/opencv_bridge.hh>\n#include <Eigen/Core>\n\nusing namespace vpp;\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\n// Inhomogeneous coordinates\nclass point_3d\n{\npublic: double x,y,z;\n\n    point_3d()\n    {x=y=z=0.0;}\n\n    point_3d(double xx, double yy, double zz)\n    {x=xx;y=yy;z=zz;}\n\n    friend ostream & operator << (ostream & os, const point_3d p)\n    {\n        os<<\"[\"<<p.x<<\",\"<<p.y<<\",\"<<p.z<<\"]\";\n        return os;\n    }\n};\n\nclass Plucker{\npublic: double c[6];\n\n\n    Plucker(point_3d p1, point_3d p2)\n    {\n        c[0]=p2.x-p1.x;\n        c[1]=p2.y-p1.y;\n        c[2]=p2.z-p1.z;\n        c[3]=p1.y*p2.z-p1.z*p2.y;\n        c[4]=p2.x*p1.z-p1.x*p2.z;\n        c[5]=p1.x*p2.y-p2.x*p1.y;\n    }\n\n\n\n\n    friend ostream & operator << (ostream & os, const Plucker l)\n    {\n        os<<\"Plucker Line:[\"<< l.c[0] <<\",\" << l.c[1] <<\",\"<<l.c[2]<<\",\"<<l.c[3]<<\",\"<<l.c[4]<<\",\"<<l.c[5]<<\"]\";\n        return os;\n    }\n\n\n}; // Homogeneous coordinates\n\ndouble plucker_dot_product(Plucker l1, Plucker l2)\n{\n    double s=0;\n\n    for(int i=0;i<6;i++)\n        s+=l1.c[i]*l2.c[(3+i)%6];\n\n    return s;\n}\n\n\n// The same primitive rewritten differently\ndouble plucker_line_intersect(Plucker l1, Plucker l2)\n{\n    double s;\n\n    s=l1.c[0]*l2.c[3]+l2.c[0]*l1.c[3] +\\\n            l1.c[1]*l2.c[4]+l2.c[1]*l1.c[4]+\\\n            l1.c[2]*l2.c[5]+l2.c[2]*l1.c[5];\n\n    return s;\n}\n\n\ndouble plucker_point_on_line(Plucker l, point_3d p)\n{\n    double rx, ry, rz, rw;\n\n    rx=l.c[3]*p.x+l.c[4]*p.y+l.c[5]*p.z;\n    ry=-l.c[2]*p.y+l.c[1]*p.z+l.c[3];\n    rz=-l.c[2]*p.x+l.c[0]*p.z-l.c[4];\n    rw=-l.c[1]*p.x+l.c[0]*p.y+l.c[5];\n\n    //cout<<rx<<\" \"<<ry<< \" \"<<rz<<\" \"<<rw<<\" \"<<endl;\n    return fabs(rx)+fabs(ry)+fabs(rz)+fabs(rw);\n}\n\n", "meta": {"hexsha": "1bfbec0cd1f8f1bcfe212f36c8f117447bf64270", "size": 1927, "ext": "hh", "lang": "C++", "max_stars_repo_path": "vpp/algorithms/line_tracker_4_sfm/sfm/plucker.hh", "max_stars_repo_name": "WLChopSticks/vpp", "max_stars_repo_head_hexsha": "2e17b21c56680bcfa94292ef5117f73572bf277d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 624.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T16:40:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T03:09:43.000Z", "max_issues_repo_path": "vpp/algorithms/line_tracker_4_sfm/sfm/plucker.hh", "max_issues_repo_name": "WLChopSticks/vpp", "max_issues_repo_head_hexsha": "2e17b21c56680bcfa94292ef5117f73572bf277d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2015-01-22T20:50:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-15T10:41:34.000Z", "max_forks_repo_path": "vpp/algorithms/line_tracker_4_sfm/sfm/plucker.hh", "max_forks_repo_name": "WLChopSticks/vpp", "max_forks_repo_head_hexsha": "2e17b21c56680bcfa94292ef5117f73572bf277d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 113.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T11:58:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:15:20.000Z", "avg_line_length": 19.0792079208, "max_line_length": 112, "alphanum_fraction": 0.5381421899, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6485985196776584}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n\n#include <boost/range/adaptor/reversed.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\nnamespace {\n    nombre cycle(nombre p, nombre m) {\n        nombre n = p, i = 1;\n        while (n != 1) {\n            ++i;\n            n = (n * p) % m;\n        }\n        return i;\n    }\n}\n\nENREGISTRER_PROBLEME(188, \"The hyperexponentiation of a number\") {\n    // The hyperexponentiation or tetration of a number a by a positive integer b, denoted by a\u2191\u2191b or ba, \n    // is recursively defined by:\n    //\n    // a\u2191\u21911 = a,\n    // a\u2191\u2191(k+1) = a(a\u2191\u2191k).\n    //\n    // Thus we have e.g. 3\u2191\u21912 = 33 = 27, hence 3\u2191\u21913 = 327 = 7625597484987 and 3\u2191\u21914 is roughly \n    // 10^(3.6383346400240996*10^12).\n    //\n    // Find the last 8 digits of 1777\u2191\u21911855.\n    vecteur masques{100000000};\n    while (masques.back() > 2)\n        masques.push_back(cycle(1777, masques.back()));\n\n    nombre resultat = 1;\n    for (const auto &m : boost::adaptors::reverse(masques))\n        resultat = puissance::puissance_modulaire<nombre>(1777, resultat, m);\n\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "6f443b9a31a1735568656b83ca43f90a7cb2f577", "size": 1150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme188.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme1xx/probleme188.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme1xx/probleme188.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7441860465, "max_line_length": 106, "alphanum_fraction": 0.5973913043, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.940789754239075, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.6484916558065409}}
{"text": "#include <cstdlib>\r\n#include <cmath>\r\n#include <Eigen/Dense>\r\n#include \"nv_core.h\"\r\n#include \"nv_ml_mlp.h\"\r\n\r\n\r\n// \u591a\u5c64\u30d1\u30fc\u30bb\u30d7\u30c8\u30ed\u30f3\r\n// 2 Layer\r\n\r\nstatic float nv_mlp_sigmoid(float a) {\r\n\treturn 1.0F / (1.0F + expf(-a));\r\n}\r\n\r\n// \u30af\u30e9\u30b9\u5206\u985e\r\n\r\nint nv_mlp_predict_label(const nv_mlp_t *mlp, const Eigen::Ref<Eigen::Matrix<float, NV_FACE_HAARLIKE_DIM, 1> > x)\r\n{\r\n\tEigen::Map<Eigen::VectorXf> input_bias(mlp->input_bias->v, mlp->hidden);\r\n\tEigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > input_w(mlp->input_w->v, mlp->hidden, mlp->input);\r\n\tEigen::Map<Eigen::VectorXf> hidden_bias(mlp->hidden_bias->v, mlp->output);\r\n\tEigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > hidden_w(mlp->hidden_w->v, mlp->output, mlp->hidden);\r\n\tEigen::VectorXf y = hidden_w*(input_w*x + input_bias).unaryExpr(&nv_mlp_sigmoid) + hidden_bias;\r\n\tint l;\r\n\ty.maxCoeff(&l);\r\n\treturn (y[l] > 0.F) ? l : -1;\r\n}\r\n\r\ndouble nv_mlp_predict_d(const nv_mlp_t *mlp, const Eigen::Ref<Eigen::Matrix<float, NV_FACE_HAARLIKE_DIM, 1> > x)\r\n{\r\n\tEigen::Map<Eigen::VectorXf> input_bias(mlp->input_bias->v, mlp->hidden);\r\n\tEigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > input_w(mlp->input_w->v, mlp->hidden, mlp->input);\r\n\tfloat hidden_bias = *mlp->hidden_bias->v;\r\n\tEigen::Map<Eigen::RowVectorXf > hidden_w(mlp->hidden_w->v, mlp->hidden);\r\n\treturn 1./(1.+exp(-hidden_w.dot((input_w*x + input_bias).unaryExpr(&nv_mlp_sigmoid)) - hidden_bias));\r\n}\r\n\r\ndouble nv_mlp_bagging_predict_d(const nv_mlp_t **mlp, int nmlp, const Eigen::Ref<Eigen::Matrix<float, NV_FACE_HAARLIKE_DIM, 1> > x)\r\n{\r\n\tdouble p = 0.0F;\r\n\tdouble factor = 1.0 / nmlp;\r\n\tint i;\r\n\t\r\n\tfor (i = 0; i < nmlp; ++i) {\r\n\t\tp += factor * nv_mlp_predict_d(mlp[i], x);\r\n\t}\r\n\r\n\treturn p;\r\n}\r\n\r\n// \u975e\u7dda\u5f62\u91cd\u56de\u5e30\r\n\r\nvoid nv_mlp_regression(const nv_mlp_t *mlp, const Eigen::Ref<Eigen::Matrix<float, NV_FACE_HAARLIKE_DIM, 1> >  x, nv_matrix_t *out)\r\n{\r\n\tEigen::Map<Eigen::VectorXf> input_bias(mlp->input_bias->v, mlp->hidden);\r\n\tEigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > input_w(mlp->input_w->v, mlp->hidden, mlp->input);\r\n\tEigen::Map<Eigen::VectorXf> hidden_bias(mlp->hidden_bias->v, mlp->output);\r\n\tEigen::Map<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > hidden_w(mlp->hidden_w->v, mlp->output, mlp->hidden);\r\n\tEigen::Map<Eigen::VectorXf> y(out->v, out->n);\r\n\ty = hidden_w*(input_w*x + input_bias).unaryExpr(&nv_mlp_sigmoid) + hidden_bias;\r\n}\r\n", "meta": {"hexsha": "0476a1a20f9dc2eeba62c8de6b8582d02591a8f6", "size": 2501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nvxs/nv_ml/nv_mlp.cpp", "max_stars_repo_name": "aliakseis/animeface-2009", "max_stars_repo_head_hexsha": "ca633bf3623c2aac1823657bb5004c5ec2b46723", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nvxs/nv_ml/nv_mlp.cpp", "max_issues_repo_name": "aliakseis/animeface-2009", "max_issues_repo_head_hexsha": "ca633bf3623c2aac1823657bb5004c5ec2b46723", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nvxs/nv_ml/nv_mlp.cpp", "max_forks_repo_name": "aliakseis/animeface-2009", "max_forks_repo_head_hexsha": "ca633bf3623c2aac1823657bb5004c5ec2b46723", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3387096774, "max_line_length": 138, "alphanum_fraction": 0.6881247501, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.6893056040203134, "lm_q1q2_score": 0.6484916452245668}}
{"text": "// TestMatrixExcel.cpp\n//\n// Test output of a matrix in Excel. Here we \n// use the Excel Driver object directly.\n//\n// The output is in cell/numeric format.\n//\n// (C) Datasim Education BV 2006-2017\n//\n\n\n#include \"ExcelDriverlite.hpp\"\n#include \"Utilities.hpp\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include \"UtilitiesDJD/VectorsAndMatrices/NestedMatrix.hpp\"\n\n#include <string>\n#include <vector>\n#include <list>\n\ndouble rho = 0.5;\ndouble NormalPdf2d(double x, double y)\n{ // Bivariate normal density function\n\t\n\tdouble fac = 1.0 / (2.0 * 3.14159265359 * std::sqrt(1.0 - rho*rho));\n\tdouble t = x*x - 2.0*rho*x*y + y*y;\n\tt /= 2.0 * (1.0 - rho*rho);\n\n\treturn fac * std::exp(-t);\n}\n\ntemplate <typename Matrix>\n\tMatrix DiscreteNormalPdf2d(const std::vector<double>& x, const std::vector<double>& y)\n{\n\treturn CreateDiscreteFunction2d<Matrix>(x, y, NormalPdf2d);\n}\n\nint main()\n{\n\t\t//\tusing NumericMatrix = boost::numeric::ublas::matrix<double>;\n\t\t// C++11 syntax\n\t\t//using NumericMatrix = NestedMatrix<double>;\n\t\t// using Vector = std::vector<double>\n\t\ttypedef NestedMatrix<double> NumericMatrix;\n\t\ttypedef std::vector<double> Vector;\n\n\t\tstd::size_t N = 10; std::size_t M = 6; // rows and columns\n\t\tNumericMatrix matrix(N + 1, M + 1);\n\t\tfor (std::size_t i = 0; i < matrix.size1(); ++i)\n\t\t{\n\t\t\tfor (std::size_t j = 0; j < matrix.size2(); ++j)\n\t\t\t{\n\t\t\t\tmatrix(i, j) = static_cast<double>(i + j);\n\t\t\t}\n\t\t}\n\t\n\t\t// Start Excel\n\t\tExcelDriver& excel = ExcelDriver::Instance();\n\t\texcel.MakeVisible(true);\t\t// Default is INVISIBLE!\n\n\t\t// Call Excel print function\n\t\tstd::string sheetName(\"Test Case 101 Matrix\");\n\t\tlong row = 4; long col = 2;\n\t//\texcel.AddMatrix<NumericMatrix>(matrix, sheetName, row, col);\n\t\n\n\t\tstd::string sheetName2(\"Matrix Labels Case\");\n\n\t//\tExcelDriver& excel = ExcelDriver::Instance();\n\t//\texcel.MakeVisible(true);\t\t// Default is INVISIBLE!\n\n\t\t// Labels for rows and columns of the Excel matrix.\n\t\t// Only labelled values are printed!!\n\t\tstd::list<std::string> rowLabels; // C++11: {\"A\",\"B\",\"C\",\"D\",\"E\", \"F\",\"K\",\"L\"};\n\t\trowLabels.push_back(\"A\");\n\t\trowLabels.push_back(\"B\");\n\t\trowLabels.push_back(\"C\");\n\t\trowLabels.push_back(\"D\");\n\t\trowLabels.push_back(\"E\");\n\t\trowLabels.push_back(\"F\");\n\t\trowLabels.push_back(\"K\");\n\t\trowLabels.push_back(\"L\");\n\n\t\tstd::list<std::string> colLabels; // C++11: {\"C1\", \"C2\", \"C3\", \"C4\",\"C5\"};\n\t\tcolLabels.push_back(\"C1\");\n\t\tcolLabels.push_back(\"C2\");\n\t\tcolLabels.push_back(\"C3\");\n\t\tcolLabels.push_back(\"C4\");\n\t\tcolLabels.push_back(\"C5\");\n\n\t\tlong rowPos = 4; long colPos = 3;\n\t//\texcel.AddMatrix<NumericMatrix>(matrix, sheetName2, rowLabels, colLabels, \n\t\t//\t\t\t\t\t\t\t\t\t\trowPos, colPos);\n\t\t\n\t\t{\n\t\t\t// Using mapping continuous space to discrete space\n\t\t\tstd::size_t N = 20; std::size_t M = 10;\n\t\t\tauto x = CreateMesh(N, -4.0, 4.0);\n\t\t\tauto y = CreateMesh(M, -4.0, 4.0);\n\n\t\t\tNumericMatrix matrix = DiscreteNormalPdf2d<NumericMatrix>(x, y);\n\t\t\n\t\t//\tExcelDriver& excel = ExcelDriver::Instance();\n\t\t\tstd::string sheetName(\"Bivariate Normal pdf\");\n\t\t\tlong row = 1; long col = 1;\n\t\t\texcel.AddMatrix<NumericMatrix>(matrix, sheetName, row, col);\n\t}\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "a1a24a98157eae97a7a45708e8e9253eb79f0440", "size": 3090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level_9/myUtilities/ExcelDriver/TestMatrixExcel.cpp", "max_stars_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_stars_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Level_9/myUtilities/ExcelDriver/TestMatrixExcel.cpp", "max_issues_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_issues_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Level_9/myUtilities/ExcelDriver/TestMatrixExcel.cpp", "max_forks_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_forks_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3451327434, "max_line_length": 87, "alphanum_fraction": 0.657605178, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.6484231826054118}}
{"text": "#include <toynet/math.h>\n#include <toynet/stlio.h>\n#include <toynet/ublas/convert.h>\n#include <toynet/ublas/io.h>\n#include <toynet/ublas/test.h>\n#include <boost/test/unit_test.hpp>\n\nusing namespace toynet;\n\nvoid help_test_softmax_size_0(ublas::vector<double> (*fn)(const ublas::vector<double>&))\n{\n    const ublas::vector<double> v;\n    const ublas::vector<double> expected;\n    const ublas::vector<double> got = (*fn)(v);\n    check_close_vectors(expected, got);\n}\n\nvoid help_test_softmax_size_1(ublas::vector<double> (*fn)(const ublas::vector<double>&))\n{\n    const ublas::vector<double> v = convert({5.0});\n    const ublas::vector<double> expected = convert({1});\n    const ublas::vector<double> got = (*fn)(v);\n    check_close_vectors(expected, got);\n}\n\nvoid help_test_softmax_size_1_sum_0(ublas::vector<double> (*fn)(const ublas::vector<double>&))\n{\n    // Make sure we don't divide by 0!\n    const ublas::vector<double> v = convert({0.0});\n    const ublas::vector<double> expected = convert({1.0});\n    const ublas::vector<double> got = (*fn)(v);\n    check_close_vectors(expected, got);\n}\n\nvoid help_test_softmax_size_2(ublas::vector<double> (*fn)(const ublas::vector<double>&))\n{\n    const ublas::vector<double> v = convert({1.0, 2.0});\n    const ublas::vector<double> expected = convert({0.26894142, 0.73105858});  // numpy 1.15.4\n    const ublas::vector<double> got = (*fn)(v);\n    check_close_vectors(expected, got);\n}\n\nvoid help_test_softmax_numerical_stability(ublas::vector<double> (*fn)(const ublas::vector<double>&))\n{\n    // https://ogunlao.github.io/2020/04/26/you_dont_really_know_softmax.html#numerical-stability-of-softmax\n    const ublas::vector<double> v = convert({10, 2, 10000, 4});\n    const ublas::vector<double> expected = convert({0, 0, 1, 0});\n    const ublas::vector<double> got = (*fn)(v);\n    check_close_vectors(expected, got);\n}\n\nBOOST_AUTO_TEST_CASE(test_softmax)\n{\n    help_test_softmax_size_0(softmax);\n    help_test_softmax_size_1(softmax);\n    help_test_softmax_size_1_sum_0(softmax);\n    help_test_softmax_size_2(softmax);\n    help_test_softmax_numerical_stability(softmax);\n}\n\nBOOST_AUTO_TEST_CASE(test_naive_softmax)\n{\n    help_test_softmax_size_0(naive_softmax);\n    help_test_softmax_size_1(naive_softmax);\n    help_test_softmax_size_1_sum_0(naive_softmax);\n    help_test_softmax_size_2(naive_softmax);\n}\n\nBOOST_AUTO_TEST_CASE(test_stable_softmax)\n{\n    help_test_softmax_size_0(stable_softmax);\n    help_test_softmax_size_1(stable_softmax);\n    help_test_softmax_size_1_sum_0(stable_softmax);\n    help_test_softmax_size_2(stable_softmax);\n    help_test_softmax_numerical_stability(stable_softmax);\n}\n\nvoid help_test_magnitude_size_0(double (*fn)(const ublas::vector<double>&))\n{\n    const ublas::vector<double> v;\n    const double expected = 0.0;\n    const double got = (*fn)(v);\n    BOOST_CHECK_CLOSE(expected, got, 0.000001);\n}\n\nvoid help_test_magnitude_size_1(double (*fn)(const ublas::vector<double>&))\n{\n    const ublas::vector<double> v = convert({6});\n    const double expected = 6;\n    const double got = (*fn)(v);\n    BOOST_CHECK_CLOSE(expected, got, 0.000001);\n}\n\nvoid help_test_magnitude_size_2(double (*fn)(const ublas::vector<double>&))\n{\n    const ublas::vector<double> v = convert({4, 3});\n    const double expected = 5;\n    const double got = (*fn)(v);\n    BOOST_CHECK_CLOSE(expected, got, 0.000001);\n}\n\nBOOST_AUTO_TEST_CASE(test_magnitude)\n{\n    help_test_magnitude_size_0(magnitude);\n    help_test_magnitude_size_1(magnitude);\n    help_test_magnitude_size_2(magnitude);\n}\n\nBOOST_AUTO_TEST_CASE(test_naive_magnitude)\n{\n    help_test_magnitude_size_0(naive_magnitude);\n    help_test_magnitude_size_1(naive_magnitude);\n    help_test_magnitude_size_2(naive_magnitude);\n}\n\nBOOST_AUTO_TEST_CASE(test_ublas_magnitude)\n{\n    help_test_magnitude_size_0(ublas_magnitude);\n    help_test_magnitude_size_1(ublas_magnitude);\n    help_test_magnitude_size_2(ublas_magnitude);\n}\n\nvoid help_test_dot_product_size_0(double (*fn)(const ublas::vector<double>& v1, const ublas::vector<double>& v2))\n{\n    const ublas::vector<double> v1;\n    const ublas::vector<double> v2;\n    const double expected = 0.0;\n    const double got = (*fn)(v1, v2);\n    BOOST_CHECK_EQUAL(expected, got);\n}\n\nvoid help_test_dot_product_size_1(double (*fn)(const ublas::vector<double>& v1, const ublas::vector<double>& v2))\n{\n    const ublas::vector<double> v1 = convert({1.5});\n    const ublas::vector<double> v2 = convert({-2.0});\n    const double expected = -3.0;\n    const double got = (*fn)(v1, v2);\n    BOOST_CHECK_EQUAL(expected, got);\n}\n\nvoid help_test_dot_product_size_2(double (*fn)(const ublas::vector<double>& v1, const ublas::vector<double>& v2))\n{\n    const ublas::vector<double> v1 = convert({1.5, 10});\n    const ublas::vector<double> v2 = convert({-2.0, 0.25});\n    const double expected = -0.5;\n    const double got = (*fn)(v1, v2);\n    BOOST_CHECK_EQUAL(expected, got);\n}\n\nBOOST_AUTO_TEST_CASE(test_dot_product)\n{\n    help_test_dot_product_size_0(dot_product);\n    help_test_dot_product_size_1(dot_product);\n    help_test_dot_product_size_2(dot_product);\n}\n\nBOOST_AUTO_TEST_CASE(test_naive_dot_product)\n{\n    help_test_dot_product_size_0(naive_dot_product);\n    help_test_dot_product_size_1(naive_dot_product);\n    help_test_dot_product_size_2(naive_dot_product);\n}\n\nBOOST_AUTO_TEST_CASE(test_ublas_dot_product)\n{\n    help_test_dot_product_size_0(ublas_dot_product);\n    help_test_dot_product_size_1(ublas_dot_product);\n    help_test_dot_product_size_2(ublas_dot_product);\n}\n\nBOOST_AUTO_TEST_CASE(cosine_distance_a)\n{\n    // https://stackoverflow.com/a/1750187\n    const ublas::vector<double> v1 = convert({2, 0, 1, 1, 0, 2, 1, 1});\n    const ublas::vector<double> v2 = convert({2, 1, 1, 0, 1, 1, 1, 1});\n    const double expected = 0.822;\n    const double got12 = cosine_distance(v1, v2);\n    const double got21 = cosine_distance(v2, v1);\n    const double got11 = cosine_distance(v1, v1);\n    const double got22 = cosine_distance(v2, v2);\n    BOOST_CHECK_CLOSE(expected, got12, 0.1);\n    BOOST_CHECK_EQUAL(got12, got21);\n    BOOST_CHECK_CLOSE(1.0, got11, 1e-12);\n    BOOST_CHECK_CLOSE(1.0, got22, 1e-12);\n}\n\nBOOST_AUTO_TEST_CASE(cosine_distance_b)\n{\n    // https://stackoverflow.com/a/14038820\n    const ublas::vector<double> v1 = convert({-1, -1, 0});\n    const ublas::vector<double> v2 = convert({-1, 0, -1});\n    const double expected = 0.5;\n    const double got12 = cosine_distance(v1, v2);\n    const double got21 = cosine_distance(v2, v1);\n    const double got11 = cosine_distance(v1, v1);\n    const double got22 = cosine_distance(v2, v2);\n    BOOST_CHECK_CLOSE(expected, got12, 0.1);\n    BOOST_CHECK_EQUAL(got12, got21);\n    BOOST_CHECK_CLOSE(1.0, got11, 1e-12);\n    BOOST_CHECK_CLOSE(1.0, got22, 1e-12);\n}\n\nBOOST_AUTO_TEST_CASE(nearest_neighbors_size_0)\n{\n    const ublas::vector<double> v = convert({-1, -1, 0});\n    const std::vector<ublas::vector<double>> points{};\n    const std::vector<int> expected{};\n    const std::vector<int> got = nearest_neighbors(v, points);\n    BOOST_CHECK_EQUAL(expected, got);\n}\n\nBOOST_AUTO_TEST_CASE(nearest_neighbors_size_1_equal)\n{\n    const ublas::vector<double> v = convert({-1, -1, 0});\n    const std::vector<ublas::vector<double>> points{convert({-1, -1, 0})};\n    const std::vector<int> expected{0};\n    const std::vector<int> got = nearest_neighbors(v, points);\n    BOOST_CHECK_EQUAL(expected, got);\n}\n\nBOOST_AUTO_TEST_CASE(nearest_neighbors_size_1_not_equal)\n{\n    const ublas::vector<double> v = convert({-1, -1, 0});\n    const std::vector<ublas::vector<double>> points{convert({-1, 0, -1})};\n    const std::vector<int> expected{0};\n    const std::vector<int> got = nearest_neighbors(v, points);\n    BOOST_CHECK_EQUAL(expected, got);\n}\n\nBOOST_AUTO_TEST_CASE(nearest_neighbors_size_2)\n{\n    const ublas::vector<double> v = convert({-1, -1, 0});\n    const std::vector<ublas::vector<double>> points{\n        convert({-1, 0, -1}),\n        convert({-1, -1, 0})\n    };\n    const std::vector<int> expected{1, 0};\n    const std::vector<int> got = nearest_neighbors(v, points);\n    BOOST_CHECK_EQUAL(expected, got);\n}\n\nBOOST_AUTO_TEST_CASE(nearest_neighbors_size_4)\n{\n    const ublas::vector<double> v = convert({-1, -1, 0});\n    const std::vector<ublas::vector<double>> points{\n        convert({-2, -1, 0}),\n        convert({-1, 0, -1}),\n        convert({-1, -1, 0}),\n        convert({-3, -1, 0})\n    };\n    const std::vector<int> expected{2, 0, 3, 1};\n    const std::vector<int> got = nearest_neighbors(v, points);\n    BOOST_CHECK_EQUAL(expected, got);\n}\n", "meta": {"hexsha": "50a92a00703f68f1ae14896ea56e49a52c7e1e27", "size": 8533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toynet/math.t.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.t.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.t.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": 33.462745098, "max_line_length": 113, "alphanum_fraction": 0.70784015, "num_tokens": 2485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6484231755548415}}
{"text": "#include <chrono>\n#include <cstdlib>\n#include <iostream>\n#include <iterator>\n\n#include <boost/multiprecision/mpfr.hpp>\n\nnamespace mp = boost::multiprecision;\nusing float_huge = mp::number<mp::mpfr_float_backend<PRECISION_DIGITS>>;\nusing timer_value_type = float;\nusing std::chrono::high_resolution_clock;\n\ntemplate <typename T>\nstruct scoped_timer\n{\n    explicit scoped_timer(T& t) : t_(t), start_(high_resolution_clock::now()) { }\n    ~scoped_timer()\n    {\n        t_ = std::chrono::duration<T,\n           std::chrono::milliseconds::period>(high_resolution_clock::now() -\n                   start_).count();\n    }\n\nprivate:\n    T& t_;\n    high_resolution_clock::time_point start_;\n};\n\nfloat_huge pi_gauss_legendre()\n{\n    float_huge a = static_cast<float_huge>(1);\n    float_huge b = static_cast<float_huge>(1) /\n        mp::sqrt(static_cast<float_huge>(2));\n    float_huge t = static_cast<float_huge>(.25);\n    float_huge p = static_cast<float_huge>(1);\n\n    for (int correct_digits = 3;\n        correct_digits < std::numeric_limits<float_huge>::digits;\n        correct_digits *= 2)\n    {\n        float_huge a_n = (a + b) / static_cast<float_huge>(2);\n        b = mp::sqrt(a * b);\n        t -= p * mp::pow(a - a_n, static_cast<float_huge>(2));\n        p *= static_cast<float_huge>(2);\n        a = a_n;\n    }\n\n    float_huge pi = mp::pow(a + b, 2) / (static_cast<float_huge>(4) * t);\n\n    return pi;\n}\n\nint main()\n{\n    timer_value_type t = 0;\n    {\n        scoped_timer<timer_value_type> timer(t);\n\n        std::cout <<\n            std::setprecision(std::numeric_limits<float_huge>::max_digits10)\n            << \"pi = \" << pi_gauss_legendre() << '\\n';\n    }\n    std::cout << \"Gauss-Legendre took \" << std::fixed << std::setprecision(4)\n              << t << \"(ms)\\n\";\n\n    return 0;\n}\n/*\nPartial Output (Windows, x64, Release, VC 15):\nAbout to run Gauss-Legendre, t is 0(ms)\npi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062...\nGauss-Legendre took 6674.4258(ms)\n*/\n", "meta": {"hexsha": "bd65245d4385820f9e3f644b4b299e9502c9e898", "size": 1998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pi.cpp", "max_stars_repo_name": "parsa/pi-day", "max_stars_repo_head_hexsha": "90eeadefdfeffc520e60924e60b73ea092502949", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pi.cpp", "max_issues_repo_name": "parsa/pi-day", "max_issues_repo_head_hexsha": "90eeadefdfeffc520e60924e60b73ea092502949", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pi.cpp", "max_forks_repo_name": "parsa/pi-day", "max_forks_repo_head_hexsha": "90eeadefdfeffc520e60924e60b73ea092502949", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 83, "alphanum_fraction": 0.6326326326, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6482655410089982}}
{"text": "\n#include <boost/test/unit_test.hpp>\n\n#include \"LinearEquation.h\"\n\nBOOST_AUTO_TEST_CASE( LinearEquationTest )\n{\n    LinearEquation noSlope(0.0,0.0);\n\n    BOOST_CHECK( noSlope.yVal(0.0) == 0.0);\n}\n\n\nBOOST_AUTO_TEST_CASE( LinearEquation_Intersection )\n{\n\n\t// Example taken from: https://www.evernote.com/shard/s3/sh/da1d5daa-2e24-404a-b26c-f84d9edb1aa3/4c4e4dd48d11085f49629933e0600aa2\n    LinearEquation equation1(3.0,2.0);\n    LinearEquation equation2(2.0,-1.0);\n\n    XYCoord intercept = equation1.intercept(equation2);\n\n    BOOST_CHECK( intercept.x() == -3.0);\n    BOOST_CHECK( intercept.y() == -7.0);\n}\n\n\nBOOST_AUTO_TEST_CASE( LinearEquation_InterceptEndpoints )\n{\n\n    BOOST_TEST_MESSAGE(\"LinearEquation_InterceptEndpoints: checking intercept used in WedgeScannerEngine_SynthesizedPattern test case\");\n\n   LinearEquation upperTrendline(XYCoord(3,100),XYCoord(11,98));\n    LinearEquation lowerTrendline(XYCoord(7,92),XYCoord(15,94));\n\n    XYCoord intercept = upperTrendline.intercept(lowerTrendline);\n\n    BOOST_TEST_MESSAGE(\"LinearEquation_InterceptEndpoints: intercept: \" << intercept);\n\n    BOOST_CHECK_CLOSE( intercept.x(),21,0.001);\n    BOOST_CHECK_CLOSE( intercept.y(),95.5,0.001);\n}\n\n", "meta": {"hexsha": "6fe03aa10a5a132a74df71d573c3f92c33f3d0d7", "size": 1193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/LinearEquation.cpp", "max_stars_repo_name": "sroehling/ChartPatternRecognitionLib", "max_stars_repo_head_hexsha": "d9bd25c0fc5a8942bb98c74c42ab52db80f680c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-07-15T19:10:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T12:16:18.000Z", "max_issues_repo_path": "test/math/LinearEquation.cpp", "max_issues_repo_name": "sroehling/ChartPatternRecognitionLib", "max_issues_repo_head_hexsha": "d9bd25c0fc5a8942bb98c74c42ab52db80f680c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/LinearEquation.cpp", "max_forks_repo_name": "sroehling/ChartPatternRecognitionLib", "max_forks_repo_head_hexsha": "d9bd25c0fc5a8942bb98c74c42ab52db80f680c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-05-23T03:25:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T16:41:44.000Z", "avg_line_length": 27.1136363636, "max_line_length": 136, "alphanum_fraction": 0.7518860017, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6482655259674782}}
{"text": "/**\n * Copyright (C) Omar Thor <omarthoro@gmail.com> - All Rights Reserved\n * Unauthorized copying of this file, via any medium is strictly prohibited\n * Proprietary and confidential\n *\n * Written by Omar Thor <omarthoro@gmail.com>, 2017\n */\n\n//#include \"sp/util/timing.hpp\"\n//#include \"sp/util/rand.hpp\"\n//#include \"sp/util/typename.hpp\"\n\n#include <iostream>\n#include <iomanip>\n#define BOOST_TEST_MODULE sp_algo_nn\n#include <boost/test/unit_test.hpp>\n#include \"sp/algo/nn.hpp\"\n#include \"sp/algo/nn/gradient_check.hpp\"\n#include \"assert_matrix.hpp\"\n\nusing namespace sp::algo::nn;\nusing namespace sp::testing;\n\nBOOST_AUTO_TEST_CASE(test_pooling_layer_mean_fprop_stride) {\n\n    using input_dims = volume_dims<1, 4, 4>;\n    using k_params = pooling_kernel_params<2, 2>;\n\n    using mean_pooling_layer_type = mean_pooling_layer<input_dims, k_params>;\n\n    mean_pooling_layer_type layer;\n\n    layer.weight_initializer = fixed_weight_initializer(1);\n    layer.bias_initializer = fixed_weight_initializer(0);\n    layer.configure(1, true);\n\n    /* Layer weight and bias override */\n    tensor_4 input(1, 1, 4, 4);\n    input.setValues({{{\n        {0,  1,  2,  3},\n        {8,  7,  5,  6},\n        {4,  3,  1,  2},\n        {0, -1, -2, -3}\n    }}});\n\n    tensor_4 result(1, 1, 2, 2);\n\n    tensor_4 expected_result(1, 1, 2, 2);\n\n    expected_result.setValues({{{\n        { 4,    4  },\n        { 1.5, -0.5},\n    }}});\n\n    layer.forward_prop(input, result);\n\n    assert_tensor_equals(expected_result, result);\n\n}\n\nBOOST_AUTO_TEST_CASE(test_pooling_layer_mean_fprop_stride_with_weights_and_biases) {\n\n    using input_dims = volume_dims<1, 4, 4>;\n    using k_params = pooling_kernel_params<2, 2>;\n\n    using mean_pooling_layer_type = mean_pooling_layer<input_dims, k_params>;\n\n    mean_pooling_layer_type layer;\n\n    layer.weight_initializer = vector_weight_initializer({1.25});\n    layer.bias_initializer = vector_weight_initializer({0.5});\n    layer.configure(1, true);\n\n    /* Layer weight and bias override */\n    tensor_4 input(1, 1, 4, 4);\n    input.setValues({{{\n        {-0.948148,  0.863082,   0.0993249, 0.895461},\n        {-0.129355, -0.0305018, -0.159264, -0.358927},\n        {-0.33933,  -0.691147,  -0.590703,  0.397725},\n        {0.238542,  -0.760099,  -0.400691, -0.0296482}\n    }}});\n\n    tensor_4 result(1, 1, 2, 2);\n\n    tensor_4 expected_result(1, 1, 2, 2);\n\n    expected_result.setValues({{{\n        { 0.423461625, 0.64893590625},\n        { 0.014989375, 0.305213375}\n    }}});\n\n    layer.forward_prop(input, result);\n    assert_tensor_equals(expected_result, result);\n\n}\n\nBOOST_AUTO_TEST_CASE(test_pooling_layer_mean_bprop_stride) {\n\n    using input_dims = volume_dims<1, 4, 4>;\n    using k_params = pooling_kernel_params<2, 2>;\n\n    using avg_pooling_layer_type = mean_pooling_layer<input_dims, k_params>;\n\n    avg_pooling_layer_type layer;\n\n    layer.configure(1, true);\n\n    /* Layer weight and bias override */\n    tensor_4 prev_out(1, 1, 4, 4);\n    tensor_4 curr_out(1, 1, 2, 2); curr_out.setZero();\n    tensor_4 prev_delta(1, 1, 4, 4); prev_delta.setZero();\n    tensor_4 expected_prev_delta(1, 1, 4, 4);\n    tensor_4 curr_delta(1, 1, 2, 2);\n\n    prev_out.setValues({{{\n        {0,  1,  2,  3},\n        {8,  7,  5,  6},\n        {4,  3,  1,  2},\n        {0, -1, -2, -3}\n    }}});\n    curr_delta.setValues({{{\n        {1, 2},\n        {3, 4},\n    }}});\n    expected_prev_delta.setValues({{{\n        {1, 1, 2, 2},\n        {1, 1, 2, 2},\n        {3, 3, 4, 4},\n        {3, 3, 4, 4}\n    }}});\n    expected_prev_delta = expected_prev_delta * (1 / 4.0f);\n\n    tensor_4 result(1, 1, 2, 2);\n\n    layer.forward_prop(prev_out, result);\n\n    layer.backward_prop(prev_out, prev_delta, curr_out, curr_delta);\n\n    assert_tensor_equals(expected_prev_delta, prev_delta);\n\n}\n\nBOOST_AUTO_TEST_CASE(test_pooling_layer_max_bprop_stride) {\n\n    using input_dims = volume_dims<1, 4, 4>;\n    using k_params = pooling_kernel_params<2, 2>;\n    using max_pooling_layer_type = max_pooling_layer<input_dims, k_params>;\n\n    max_pooling_layer_type layer;\n    layer.weight_initializer = fixed_weight_initializer(1.0f);\n    layer.configure(1, true);\n\n    tensor_4 prev_out(1, 1, 4, 4);\n    tensor_4 curr_out(1, 1, 2, 2); curr_out.setZero();\n    tensor_4 prev_delta(1, 1, 4, 4); prev_delta.setZero();\n    tensor_4 expected_prev_delta(1, 1, 4, 4);\n    tensor_4 curr_delta(1, 1, 2, 2);\n\n    prev_out.setValues({{{\n        {0,  1,  2,  3},\n        {8,  7,  5,  6},\n        {4,  3,  1,  2},\n        {0, -1, -2, -3}\n    }}});\n    curr_delta.setValues({{{\n        {1, 2},\n        {3, 4},\n    }}});\n    expected_prev_delta.setValues({{{\n        {0, 0, 0, 0},\n        {1, 0, 0, 2},\n        {3, 0, 0, 4},\n        {0, 0, 0, 0}\n    }}});\n\n    layer.forward_prop(prev_out, curr_out);\n\n\n    layer.backward_prop(prev_out, prev_delta, curr_out, curr_delta);\n\n    assert_tensor_equals(expected_prev_delta, prev_delta);\n\n}\nBOOST_AUTO_TEST_CASE(test_pooling_layer_mean_gradient_check) {\n\n    /** FIX SEED FOR TESTING, REPRODUCIBLE RESULTS< NOT TO BE COMMITTED! */\n    random_generator::get().seed(2);\n    using input_dims = volume_dims<1, 4, 4>;\n    using k_params = pooling_kernel_params<2, 2>;\n\n    constexpr float_t epsilon = 1e-2f;\n    constexpr size_t batch_size = 1;\n\n    using avg_pooling_layer_type = mean_pooling_layer<input_dims, k_params>;\n    avg_pooling_layer_type layer;\n\n    layer.weight_initializer = gauss_weight_initializer(-1.0f, 1.0f);\n    layer.bias_initializer = gauss_weight_initializer(-1.0f, 1.0f);\n\n    /* setup weights and dimensions */\n    layer.configure(batch_size, true);\n\n    auto in = generate_inputs_for(layer, batch_size);\n\n    for(size_t i = 0; i < 1; ++i) {\n        auto in_selected  = gradient_random_input(layer);\n        auto out_selected = gradient_random_output(layer);\n\n        /* Perform numerical and analytics gradient */\n        /* estimate */\n        auto n = numerical_gradient (layer, in, in_selected, out_selected);\n        /* actual */\n        auto a = analytical_gradient(layer, in, in_selected, out_selected);\n\n        /* Validate result */\n        BOOST_CHECK_MESSAGE(std::abs(a-n) <= epsilon, \"Gradient check |\" << std::setprecision(15) << a << \" - \" << n << \"| < \" << epsilon);\n    }\n}\n", "meta": {"hexsha": "7ff490adb09ef193a9e22333e27eb5c34877837e", "size": 6198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_nn_pooling.cpp", "max_stars_repo_name": "thorigin/sp", "max_stars_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_nn_pooling.cpp", "max_issues_repo_name": "thorigin/sp", "max_issues_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_nn_pooling.cpp", "max_forks_repo_name": "thorigin/sp", "max_forks_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.301369863, "max_line_length": 139, "alphanum_fraction": 0.6355275895, "num_tokens": 1923, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6482655259674781}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/special.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n\n\n//==================================================================================================\n// Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of eve::double_factorial\"\n              , eve::test::simd::unsigned_integers)\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  using d_t = eve::wide<double, eve::cardinal_t<T>>;\n  TTS_EXPR_IS( eve::double_factorial(T())                       , d_t);\n  TTS_EXPR_IS( eve::double_factorial(v_t())                     , double );\n};\n\n//==================================================================================================\n// Test for corner-cases values\n//==================================================================================================\nEVE_TEST_TYPES( \"Check corner-cases behavior of eve::double_factorial on wide\"\n        , eve::test::simd::unsigned_integers\n         )\n  <typename T>(eve::as<T>)\n{\n  using eve::as;\n  using d_t = eve::wide<double, eve::cardinal_t<T>>;\n  TTS_ULP_EQUAL(eve::double_factorial(T(10))  , d_t(boost::math::double_factorial<double>(10)), 0.5);\n  TTS_ULP_EQUAL(eve::double_factorial(T( 5))  , d_t(boost::math::double_factorial<double>( 5)), 0.5);\n  TTS_ULP_EQUAL(eve::double_factorial(T(180)) , d_t(boost::math::double_factorial<double>( 180)), 1.);\n  TTS_ULP_EQUAL(eve::double_factorial(T(181)) , d_t(boost::math::double_factorial<double>( 181)), 1.5);\n\n  if constexpr(sizeof(eve::element_type_t<T>) > 1)\n  {\n    TTS_ULP_EQUAL(eve::double_factorial(T(300)), d_t(boost::math::double_factorial<double>( 300)), 1.0);\n    TTS_ULP_EQUAL(eve::double_factorial(T(301)), eve::inf(eve::as<d_t>()), 0);\n    TTS_ULP_EQUAL(eve::double_factorial(T(302)), eve::inf(eve::as<d_t>()), 0);\n  }\n};\n", "meta": {"hexsha": "78ebf636e39f9dc098a43c959977257df74a19b8", "size": 2236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/special/double_factorial.cpp", "max_stars_repo_name": "clayne/eve", "max_stars_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/special/double_factorial.cpp", "max_issues_repo_name": "clayne/eve", "max_issues_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/special/double_factorial.cpp", "max_forks_repo_name": "clayne/eve", "max_forks_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5833333333, "max_line_length": 104, "alphanum_fraction": 0.4879248658, "num_tokens": 512, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6482403195161617}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n\nTEST(AgradRev,log_rising_factorial_var_double) {\n  double a(1);\n  AVAR b(4.0);\n  AVAR f = stan::math::log_rising_factorial(b,a);\n  EXPECT_FLOAT_EQ(std::log(4.0),f.val());\n\n  AVEC x = createAVEC(a,b);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(0, g[0]);\n  EXPECT_FLOAT_EQ(boost::math::digamma(5) - boost::math::digamma(4),g[1]);\n\n  double eps = 1e-6;\n  EXPECT_FLOAT_EQ((stan::math::log_rising_factorial(4.0 + eps, 1.0)\n                  - stan::math::log_rising_factorial(4.0 - eps, 1.0))\n                  / (2 * eps), g[1]);\n}\n\nTEST(AgradRev, log_rising_factorial_exceptions) {\n  double a(1);\n  AVAR b(-3.0);\n  EXPECT_THROW(stan::math::log_rising_factorial(b,a), std::domain_error);\n  EXPECT_THROW(stan::math::log_rising_factorial(b,b), std::domain_error);\n}\n\nTEST(AgradRev, log_rising_factorial_double_var) {\n  double a(5.0);\n  AVAR b(4.0);\n  AVAR f = stan::math::log_rising_factorial(a,b);\n  EXPECT_FLOAT_EQ(std::log(5*6*7*8), f.val());\n  AVEC x = createAVEC(a,b);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(0, g[0]);\n  EXPECT_FLOAT_EQ(boost::math::digamma(9), g[1]);\n\n  double eps = 1e-6;\n  EXPECT_FLOAT_EQ((stan::math::log_rising_factorial(5.0, 4.0 + eps)\n                  - stan::math::log_rising_factorial(5.0, 4.0 - eps))\n                  / (2 * eps), g[1]);\n}\n\nTEST(AgradRev, log_rising_factorial_var_var) {\n  AVAR c(5.0);\n  AVAR b(4.0);\n  AVAR f = stan::math::log_rising_factorial(b,c);\n  EXPECT_FLOAT_EQ(std::log(4*5*6*7*8), f.val());\n  AVEC x = createAVEC(b,c);\n  VEC g;\n  f.grad(x,g);\n  EXPECT_FLOAT_EQ(boost::math::digamma(9.0) - boost::math::digamma(4.0), g[0]);\n  EXPECT_FLOAT_EQ(boost::math::digamma(9), g[1]);\n  \n  double eps = 1e-6;\n  EXPECT_FLOAT_EQ((stan::math::log_rising_factorial(4.0 + eps, 5.0)\n                  - stan::math::log_rising_factorial(4.0 - eps, 5.0))\n                  / (2 * eps), g[0]);\n  EXPECT_FLOAT_EQ((stan::math::log_rising_factorial(4.0, 5.0 + eps)\n                  - stan::math::log_rising_factorial(4.0, 5.0 - eps))\n                  / (2 * eps), g[1]);\n}\n\nstruct log_rising_factorial_fun {\n  template <typename T0, typename T1>\n  inline \n  typename stan::return_type<T0,T1>::type\n  operator()(const T0& arg1,\n             const T1& arg2) const {\n    return log_rising_factorial(arg1,arg2);\n  }\n};\n\nTEST(AgradRev, log_rising_factorial_nan) {\n  log_rising_factorial_fun log_rising_factorial_;\n  test_nan(log_rising_factorial_,3.0,5.0,false,true);\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a(1.0);\n  AVAR b(4.0);\n  test::check_varis_on_stack(stan::math::log_rising_factorial(b, a));\n  test::check_varis_on_stack(stan::math::log_rising_factorial(b, 1.0));\n  test::check_varis_on_stack(stan::math::log_rising_factorial(4.0, a));\n}\n", "meta": {"hexsha": "337cdc3b80b11dc6967e484d3ceccd02fe600ae8", "size": 2892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/log_rising_factorial_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/log_rising_factorial_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/log_rising_factorial_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7802197802, "max_line_length": 79, "alphanum_fraction": 0.6507607192, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6482403076111689}}
{"text": "/*\n(c) 2019 M. Werner - Part of the GIS++ tutorial \n- https://www.martinwerner.de/teaching/spatial-cpp\n- https://github.com/mwernerds/spatial-cpp\n\nProgram: Hello world in C\nCompile: g++ -Wall -std=c++17  -o 05-algo 05-algo.cpp\n*/\n\n#include<iostream>\n#include<vector>\n#include<list>\n#include<map>\n#include<unordered_map>\n\n#include<algorithm>\n#include<numeric>\n\n#include<chrono>\n\n#include <boost/range/adaptor/indexed.hpp>\n#include <boost/assign.hpp>\n#include <boost/assign/list_inserter.hpp> // for 'insert()'\n\n\n// you will need this header for the C++17 parallel version, but it is not yet available everywhere.\n//#include<execution>\n\nusing  boost::adaptors::indexed;\nusing namespace boost::assign;\n\n\n\ntemplate <typename T>\nstd::ostream &operator<< (std::ostream &os, const std::vector<T>  & data)\n{\n    os << \"(@\" <<  (void *) &data[0] << \"): \";\n    std::copy(data.begin(), data.end(), std::ostream_iterator<int>(os, \" \"));\n    return os;\n}\n\n\nint main(int argc, char **argv)\n{\n    // some algorithm templates in use\n\n    std::vector<int> v;\n    v += 1,2,3,4,5,6,7;\n    std::cout << v << std::endl;\n    // let us randomize v\n    std::random_shuffle(v.begin(), v.end());\n    std::cout << v << std::endl;\n    // sort\n    std::sort(v.begin(), v.end());\n    // in c++ 20, you can see a vector as a range and do\n    // std::ranges::sort(v)\n    std::cout << v << std::endl;\n    // show only even entries\n    std::random_shuffle(v.begin(), v.end());\n\n    auto uneven = std::count_if(v.begin(), v.end(), [](int a) {return (a%2 == 1);});\n    std::cout << \"Found \" << uneven << \" uneven numbers.\" << std::endl;\n\n    // Okay, but how does this help us? Let us search for a number in an ordered list in three ways\n    // and do some timing on simple, classical, and C++ style solutions.\n\n    std::vector<long> many(1024*1024);\n    std::iota(many.begin(), many.end(),0);\n//    std::cout << many << std::endl;\n\n    {\n    unsigned long sink;\n    auto start = std::chrono::high_resolution_clock::now();\n    auto it = many.begin();\n    for (sink=0; it != many.end(); ++it){  sink += *it;};\n    \n    auto end = std::chrono::high_resolution_clock::now();\n     std::chrono::duration<double> diff = end-start;\n     std::cout << \"Summed up to \" << sink << \" in \" << diff.count() << \"seconds\" << std::endl;\n    }\n\n    // faster (!) and easier to read\n    { \n    auto start = std::chrono::high_resolution_clock::now();\n    auto sink = std::accumulate(many.begin(), many.end(), 0ul); \n    auto end = std::chrono::high_resolution_clock::now();\n     std::chrono::duration<double> diff = end-start;\n     std::cout << \"Summed up to \" << sink << \" in \" << diff.count() << \"seconds\" << std::endl;\n    }\n\n    // similar: let us search for the location of the value 12345\n    \n    { \n    auto start = std::chrono::high_resolution_clock::now();\n    size_t i;\n    for(i=0; i<many.size();i++)\n    {\n\tif (many[i] == 123456)\n\t   break;\n    }\n    \n    auto end = std::chrono::high_resolution_clock::now();\n     std::chrono::duration<double> diff = end-start;\n     std::cout << \"Found it at \" << i << \" in \" << diff.count() << \"seconds\" << std::endl;\n    }\n\n    \n    // algorithm version (using sorted property, that is binary search)\n    { \n    auto start = std::chrono::high_resolution_clock::now();\n    auto it = std::lower_bound(many.begin(), many.end(),123456);\n    auto end = std::chrono::high_resolution_clock::now();\n     std::chrono::duration<double> diff = end-start;\n     std::cout << \"Found it at \" << std::distance(many.begin(),it) << \" in \" << diff.count() << \"seconds\" << std::endl;\n    }\n\n    // in c++17: MapReduce?!\n    // Map:\n    std::transform(many.begin(), many.end(), many.begin(), [](int v) -> int {return v*2;});\n\n    std::cout << \"transform: \";\n    std::copy_n(many.begin(), 10 , std::ostream_iterator<int>(std::cout, \" \"));\n    std::cout << \"...\" << std::endl;\n\n    // accumulate (e.g., sequential)\n     { \n\tauto start = std::chrono::high_resolution_clock::now();\n\tauto sink = std::accumulate(many.begin(), many.end(), 0ul); \n\tauto end = std::chrono::high_resolution_clock::now();\n\t std::chrono::duration<double> diff = end-start;\n\t std::cout << \"Summed up to \" << sink << \" in \" << diff.count() << \"seconds\" << std::endl;\n    }\n\n    // reduce (e.g. parallel, accumulate out of order, c++17, specified execution strategy)\n/* \nthis is C++17 and not yet widely available. But how cool is this: just tell it to be parallel and it does ;-)\n\n    { \n\tauto start = std::chrono::high_resolution_clock::now();\n\tauto sink = std::reduce(std::execution::par, many.begin(), many.end(), 0ul); \n\tauto end = std::chrono::high_resolution_clock::now();\n\t std::chrono::duration<double> diff = end-start;\n\t std::cout << \"Summed up to \" << sink << \" in \" << diff.count() << \"seconds\" << std::endl;\n    }\n\n\n\n// and a complete example of the simple algorithm std::sort in C++17:\n\nusing namespace std;\nvector<int> v = ...\n\n// standard sequential sort\nsort(v.begin(), v.end());\n\n// explicitly sequential sort\nsort(sequential, v.begin(), v.end());\n\n// permitting parallel execution\nsort(par, v.begin(), v.end());\n\n// permitting vectorization as well\nsort(par_vec, v.begin(), v.end());\n*/  \n    \n    return 0;\n}\n", "meta": {"hexsha": "c1a1134765f322f335fb350aa355cbbeb24f2426", "size": 5172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "01_cpp/05-algo.cpp", "max_stars_repo_name": "mwernerds/spatial-cpp", "max_stars_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "01_cpp/05-algo.cpp", "max_issues_repo_name": "mwernerds/spatial-cpp", "max_issues_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "01_cpp/05-algo.cpp", "max_forks_repo_name": "mwernerds/spatial-cpp", "max_forks_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-08T23:57:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T23:57:30.000Z", "avg_line_length": 30.7857142857, "max_line_length": 119, "alphanum_fraction": 0.6080819799, "num_tokens": 1434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.6482403045843043}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\n\n// Contributed and/or modified by Tinko Bartels,\n//   as part of Google Summer of Code 2019 program.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_STRATEGIES_CARTESIAN_SIDE_ROBUST_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_STRATEGIES_CARTESIAN_SIDE_ROBUST_HPP\n\n#include <boost/geometry/util/select_most_precise.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/extensions/triangulation/strategies/cartesian/detail/precise_math.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace side\n{\n\n/*!\n\\brief Adaptive precision predicate to check at which side of a segment a point lies:\n    left of segment (>0), right of segment (< 0), on segment (0).\n\\ingroup strategies\n\\tparam CalculationType \\tparam_calculation (numeric_limits<ct>::epsilon() and numeric_limits<ct>::digits must be supported for calculation type ct)\n\\tparam Robustness std::size_t value from 0 (fastest) to 3 (default, guarantees correct results).\n\\details This predicate determines at which side of a segment a point lies using an algorithm that is adapted from orient2d as described in \"Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates\" by Jonathan Richard Shewchuk ( https://dl.acm.org/citation.cfm?doid=237218.237337 ). More information and copies of the paper can also be found at https://www.cs.cmu.edu/~quake/robust.html . It is designed to be adaptive in the sense that it should be fast for inputs that lead to correct results with plain float operations but robust for inputs that require higher precision arithmetics.\n */\ntemplate\n<\n    typename CalculationType = void,\n    std::size_t Robustness = 3\n>\nstruct side_robust\n{\npublic:\n    //! \\brief Computes double the signed area of the CCW triangle p1, p2, p\n    template\n    <\n        typename PromotedType,\n        typename P1,\n        typename P2,\n        typename P\n    >\n    static inline PromotedType side_value(P1 const& p1, P2 const& p2,\n        P const& p)\n    {\n        typedef ::boost::geometry::detail::precise_math::vec2d<PromotedType> vec2d;\n        vec2d pa { get<0>(p1), get<1>(p1) };\n        vec2d pb { get<0>(p2), get<1>(p2) };\n        vec2d pc { get<0>(p), get<1>(p) };\n        return ::boost::geometry::detail::precise_math::orient2d\n            <PromotedType, Robustness>(pa, pb, pc);\n    }\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n    template\n    <\n        typename P1,\n        typename P2,\n        typename P\n    >\n    static inline int apply(P1 const& p1, P2 const& p2, P const& p)\n    {\n        typedef typename select_calculation_type_alt\n            <\n                CalculationType,\n                P1,\n                P2,\n                P\n            >::type coordinate_type;\n        typedef typename select_most_precise\n            <\n                coordinate_type,\n                double\n            >::type promoted_type;\n\n        promoted_type sv = side_value<promoted_type>(p1, p2, p);\n        return sv > 0 ? 1\n            : sv < 0 ? -1\n            : 0;\n    }\n#endif\n\n};\n\n}} // namespace strategy::side\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_STRATEGIES_CARTESIAN_SIDE_ROBUST_HPP\n", "meta": {"hexsha": "59228c06033355764edd3b7a4eabfddb5f0cfd61", "size": 3486, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/triangulation/strategies/cartesian/side_robust.hpp", "max_stars_repo_name": "Siddharth-coder13/geometry", "max_stars_repo_head_hexsha": "ff1f245f21215ddcbd2d350702c2da47fccc0f2d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T20:30:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T08:14:05.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/triangulation/strategies/cartesian/side_robust.hpp", "max_issues_repo_name": "Siddharth-coder13/geometry", "max_issues_repo_head_hexsha": "ff1f245f21215ddcbd2d350702c2da47fccc0f2d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/geometry/extensions/triangulation/strategies/cartesian/side_robust.hpp", "max_forks_repo_name": "Siddharth-coder13/geometry", "max_forks_repo_head_hexsha": "ff1f245f21215ddcbd2d350702c2da47fccc0f2d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:43:59.000Z", "avg_line_length": 36.3125, "max_line_length": 613, "alphanum_fraction": 0.6910499139, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6482350850240679}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n#include <OpenTissue/core/math/math_eigen_system_decomposition.h>\n#include <OpenTissue/core/math/math_polar_decomposition.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n#include <cmath>\n#include <iostream>\n\nusing namespace OpenTissue;\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_polar_decomposition);\n\n  BOOST_AUTO_TEST_CASE(eigen_method)\n  {\n    typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n    typedef math_types::vector3_type                         vector3_type;\n    typedef math_types::matrix3x3_type                       matrix3x3_type;\n    typedef math_types::real_type                            real_type;\n    typedef math_types::index_type                           index_type;\n    typedef math_types::value_traits                         value_traits;\n\n    real_type epsilon = 10e-7;\n    matrix3x3_type A,R,S,D;\n\n    for(index_type i=0;i<100000;++i)\n    {\n      OpenTissue::math::random(S);\n      S = OpenTissue::math::trans(S)*S;\n      OpenTissue::math::random(A);\n      R = OpenTissue::math::ortonormalize( A );\n      A = R*S;\n      R = OpenTissue::math::diag(1.0);\n      S = OpenTissue::math::diag(1.0);\n      bool success = OpenTissue::math::polar_decomposition::eigen(A,R,S);\n      if(success)\n      {\n        bool right_handed = det(R) > value_traits::zero();\n        BOOST_CHECK( right_handed );\n        \n        D = A - R*S;\n        real_type maximum_deviation =  max_value(  fabs(D) );\n\n        //BOOST_CHECK_CLOSE( maximum_deviation, value_traits::zero(), tol);\n        BOOST_CHECK( maximum_deviation<epsilon );\n      }\n    }\n  }\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "346e6ee21677ebc6b76b2af9addff5d3a3fbf3f2", "size": 2120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/poloar_decomposition/src/unit_poloar_decomposition.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/poloar_decomposition/src/unit_poloar_decomposition.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/poloar_decomposition/src/unit_poloar_decomposition.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 33.6507936508, "max_line_length": 78, "alphanum_fraction": 0.6768867925, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6482350778250882}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;  \n\ntemplate <typename Matrix>\nvoid test(Matrix& , const char* name)\n{\n    typedef typename mtl::Collection<Matrix>::value_type value_type;\n    typedef mtl::dense_vector<value_type>                vector_type;\n    value_type  ar[][3] = {{3., 9., 0.},\n\t\t\t   {1., 2., 7.},\n\t\t\t   {9., 6., 8.}};\n    const Matrix A(ar);\n    \n    // trans(A)[0][1]= 11.0;\n    \n    cout << name << \":\\n trans(A)[0][1]= \" << trans(A)[0][1] << \"\\n\";\n\n    MTL_THROW_IF(trans(A)[0][1] != value_type(1.), mtl::runtime_error(\"constant transposing wrong\"));\n\n    vector_type v(3), vcomp(3), w(3);\n    w= 4, 7, 8;\n    vcomp= 91,98,113;\n\n    v= trans(A) * w;\n    // cout << \"trans(A) * w = \" << v << '\\n';\n    MTL_THROW_IF(one_norm(vector_type(v - vcomp)) > 0.01, mtl::runtime_error(\"Error in trans(A) * w\"));\n}\n\n\ntemplate <typename Matrix>\nvoid mutable_test(Matrix&, const char* name)\n{\n    typedef typename mtl::Collection<Matrix>::value_type value_type;\n    value_type  ar[][3] = {{3., 9., 0.},\n\t\t\t   {1., 2., 7.},\n\t\t\t   {9., 6., 8.}};\n    Matrix A(ar);\n    \n    trans(A)[0][1]= 11.0;\n    \n    cout << name << \":\\n trans(A)[0][1]= \" << trans(A)[0][1] << \"\\n\";\n\n    MTL_THROW_IF(trans(A)[0][1] != value_type(11.), mtl::runtime_error(\"transposing wrong\"));\n}\n\n\nint main(int argc, char* argv[])\n{\n    using namespace mtl;\n    \n    unsigned size= 3; \n    if (argc > 1) size= atoi(argv[1]); \n\n    dense2D<double>                                      dr(size, size);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n    morton_dense<double, recursion::morton_z_mask>       mzd(size, size);\n    morton_dense<double, recursion::doppled_2_row_mask>  d2r(size, size);\n    compressed2D<double>                                 cr(size, size);\n    compressed2D<double, mat::parameters<col_major> > cc(size, size);\n\n    dense2D<complex<double> >                            drc(size, size);\n    compressed2D<complex<double> >                       crc(size, size);\n\n\n    test(dr, \"Dense row major\");\n    test(dc, \"Dense column major\");\n    test(mzd, \"Morton Z-order\");\n    test(d2r, \"Hybrid 2 row-major\");\n    test(cr, \"Compressed row major\");\n    test(cc, \"Compressed column major\");\n    test(drc, \"Dense row major complex\");\n    test(crc, \"Compressed row major complex\");\n\n    mutable_test(dr, \"Dense row major\");\n    mutable_test(dc, \"Dense column major\");\n    mutable_test(mzd, \"Morton Z-order\");\n    mutable_test(d2r, \"Hybrid 2 row-major\");\n    mutable_test(drc, \"Dense row major complex\");\n\n    return 0;\n}\n", "meta": {"hexsha": "27e48964236923a402412ac8404aaf788f66d5cf", "size": 3049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_trans_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/matrix_trans_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/matrix_trans_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 30.797979798, "max_line_length": 103, "alphanum_fraction": 0.5900295179, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.6481505401148704}}
{"text": "#include \"fem_solve.hpp\"\n#include \"writer.hpp\"\n#include <Eigen/Core>\n#include <sstream>\n\ndouble f_square(double x, double y) {\n\treturn 2 * M_PI * M_PI * sin(M_PI * x) * sin(M_PI * y);\n}\n\nint main(int, char **) {\n\ttry {\n\t\tVector u;\n\n\t\tEigen::MatrixXd vertices;\n\t\tEigen::MatrixXi triangles;\n\t\tEigen::MatrixXi tetrahedra;\n\n\t\tigl::readMESH(NPDE_DATA_PATH \"square_5.mesh\", vertices, tetrahedra, triangles);\n\n\t\tsolveFiniteElement(u, vertices, triangles, f_square);\n\n\t\twriteToFile(\"square_5_values.txt\", u);\n\t\twriteMatrixToFile(\"square_5_vertices.txt\", vertices);\n\t\twriteMatrixToFile(\"square_5_triangles.txt\", triangles);\n\n\t} catch (std::runtime_error &e) {\n\t\tstd::cerr << \"An error occurred. Error message: \" << std::endl;\n\t\tstd::cerr << \"    \\\"\" << e.what() << \"\\\"\" << std::endl;\n\t\treturn EXIT_FAILURE;\n\t} catch (...) {\n\t\tstd::cerr << \"An unknown error occurred.\" << std::endl;\n\t\tthrow;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "1840dcd4333bdf831aa1da908a9892755854d9af", "size": 910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series2_warmup/2d-poissonlFEM/fem2d.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_warmup/2d-poissonlFEM/fem2d.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_warmup/2d-poissonlFEM/fem2d.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": 24.5945945946, "max_line_length": 81, "alphanum_fraction": 0.6681318681, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6481283067905373}}
{"text": "#include \"KMC/integrals.hpp\"\n#include \"KMC/lookup_table.hpp\"\n#include \"KMC/lut_filler_edep.hpp\"\n#include \"KMC/macros.hpp\"\n#include \"catch.hpp\"\n#include \"test_helpers.hpp\"\n\n#include <cmath>\n#include <cstdio>\n#include <iostream>\n#include <string>\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n\nTEST_CASE(\"Lookup table test SOFT spring \", \"[lookup_soft]\") {\n    constexpr double errTol = 1e-3;\n    const double D = 0.024;\n    const double alpha = 0.1 / (2 * 0.00411);\n    const double freelength = 0.05;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n\n    LUTFillerEdep lut_filler(256, 256);\n    lut_filler.Init(alpha, freelength, D);\n    LookupTable LUT(&lut_filler);\n\n    double distPerp = 0;\n    distPerp = 0.2;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(LUT.Lookup(distPerp, sbound * D) ==\n              Approx(D * integral(distPerp / D, 0, sbound, M, ell0))\n                  .epsilon(errTol));\n    }\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(LUT.Lookup(distPerp, sbound * D) ==\n              Approx(D * integral(distPerp / D, 0, sbound, M, ell0))\n                  .epsilon(errTol));\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(LUT.Lookup(distPerp, sbound * D) ==\n              Approx(D * integral(distPerp / D, 0, sbound, M, ell0))\n                  .epsilon(errTol));\n    }\n}\n\nTEST_CASE(\"Lookup table test MEDIUM spring \", \"[lookup_med]\") {\n    constexpr double errTol = 1e-3;\n    const double D = 0.024;\n    const double alpha = 1.0 / (2 * 0.00411);\n    const double freelength = 0.05;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n\n    LUTFillerEdep lut_filler(256, 256);\n    lut_filler.Init(alpha, freelength, D);\n    LookupTable LUT(&lut_filler);\n\n    double distPerp = 0;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    distPerp = 0.2;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(LUT.Lookup(distPerp, sbound * D) ==\n              Approx(D * integral(distPerp / D, 0, sbound, M, ell0))\n                  .epsilon(errTol));\n    }\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(LUT.Lookup(distPerp, sbound * D) ==\n              Approx(D * integral(distPerp / D, 0, sbound, M, ell0))\n                  .epsilon(errTol));\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(LUT.Lookup(distPerp, sbound * D) ==\n              Approx(D * integral(distPerp / D, 0, sbound, M, ell0))\n                  .epsilon(errTol));\n    }\n}\n\nTEST_CASE(\"Lookup table test STIFF spring \", \"[lookup_stiff]\") {\n    constexpr double absTol = 1e-5;\n    const double D = 0.024;\n    const double alpha = 10.0 / (2 * 0.00411);\n    const double freelength = 0.05 + D;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n\n    LUTFillerEdep lut_filler(256, 256);\n    lut_filler.Init(alpha, freelength, D);\n    LookupTable LUT(&lut_filler);\n\n    double distPerp = 0;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    distPerp = 0.2;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        // CHECK(errorPass(LUT.Lookup(distPerp, sbound * D),\n        // D * integral(distPerp / D, 0, sbound, M, ell0)));\n        CHECK(LUT.Lookup(distPerp, sbound * D) ==\n              Approx(D * integral(distPerp / D, 0, sbound, M, ell0))\n                  .margin(absTol));\n    }\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        // CHECK(errorPass(LUT.Lookup(distPerp, sbound * D),\n        // D * integral(distPerp / D, 0, sbound, M, ell0)));\n        CHECK(LUT.Lookup(distPerp, sbound * D) ==\n              Approx(D * integral(distPerp / D, 0, sbound, M, ell0))\n                  .margin(absTol));\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < 20; sbound += 0.5) {\n        CHECK(errorPass(LUT.Lookup(distPerp, sbound * D),\n                        D * integral(distPerp / D, 0, sbound, M, ell0)));\n        CHECK(LUT.Lookup(distPerp, sbound * D) ==\n              Approx(D * integral(distPerp / D, 0, sbound, M, ell0))\n                  .margin(absTol));\n    }\n}\n\nTEST_CASE(\"Lookup table test manual medium spring REL error\", \"[lookup]\") {\n    // integrated by mathematica\n    const double D = 0.024;\n    constexpr double tol = 1e-4;\n\n    LUTFillerEdep lut_filler(256, 256);\n    lut_filler.Init(1.0 / (2 * 0.00411), 0.05 + D, D);\n    LookupTable LUT(&lut_filler);\n\n    double distPerp = 0;\n\n    distPerp = 0.2;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    CHECK(LUT.Lookup(distPerp, 0.5 * D) / D == Approx(0.0722077).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 1.0 * D) / D == Approx(0.1428390).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 1.5 * D) / D == Approx(0.2104120).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 2.0 * D) / D == Approx(0.2736230).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 3.0 * D) / D == Approx(0.3830390).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 4.0 * D) / D == Approx(0.4663750).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 5.0 * D) / D == Approx(0.5238890).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 6.0 * D) / D == Approx(0.5596700).epsilon(tol));\n\n    distPerp = 0.08;\n    // \"distPerp = 0.08 > D+ell0, single peaked\"/D,\n    CHECK(LUT.Lookup(distPerp, 0.5 * D) / D == Approx(0.497588).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 1.0 * D) / D == Approx(0.993608).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 1.5 * D) / D == Approx(1.485540).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 2.0 * D) / D == Approx(1.969290).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 3.0 * D) / D == Approx(2.887840).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 4.0 * D) / D == Approx(3.692500).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 5.0 * D) / D == Approx(4.333200).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 6.0 * D) / D == Approx(4.789860).epsilon(tol));\n\n    distPerp = 0.06;\n    // \"distPerp = 0.06 < D+ell0, double peaked\"/D,\n    CHECK(LUT.Lookup(distPerp, 0.5 * D) / D == Approx(0.488864).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 1.0 * D) / D == Approx(0.981139).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 1.5 * D) / D == Approx(1.478150).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 2.0 * D) / D == Approx(1.977880).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 3.0 * D) / D == Approx(2.960520).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 4.0 * D) / D == Approx(3.858570).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 5.0 * D) / D == Approx(4.598640).epsilon(tol));\n    CHECK(LUT.Lookup(distPerp, 6.0 * D) / D == Approx(5.140580).epsilon(tol));\n}\n\nTEST_CASE(\"REVERSE Lookup table test manual medium spring REL error\",\n          \"[REVERSE lookup]\") {\n    // integrated by mathematica\n    const double D = 0.024;\n\n    double distPerp = 0;\n    LUTFillerEdep lut_filler(256, 256);\n    lut_filler.Init(1.0 / (2 * 0.00411), 0.05 + D, D);\n    LookupTable LUT(&lut_filler);\n    // LUT.Init(&lut_filler);\n\n    // double tol = RELTOL * REVERSEFAC;\n    const double tol = 1e-4;\n\n    distPerp = 0.1;\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    CHECK(LUT.ReverseLookup(distPerp, D * 0) / D == Approx(0.0).epsilon(tol));\n    CHECK(LUT.ReverseLookup(distPerp, D * 0.0460519) / D ==\n          Approx(.05).epsilon(tol));\n    CHECK(LUT.ReverseLookup(distPerp, D * 0.3221280) / D ==\n          Approx(.35).epsilon(tol));\n    CHECK(LUT.ReverseLookup(distPerp, D * 0.4598240) / D ==\n          Approx(0.5).epsilon(tol));\n    CHECK(LUT.ReverseLookup(distPerp, D * 0.9153560) / D ==\n          Approx(1.0).epsilon(tol));\n    CHECK(LUT.ReverseLookup(distPerp, D * 1.3619600) / D ==\n          Approx(1.5).epsilon(tol));\n    CHECK(LUT.ReverseLookup(distPerp, D * 1.7944600) / D ==\n          Approx(2.0).epsilon(tol));\n    CHECK(LUT.ReverseLookup(distPerp, D * 2.2071800) / D ==\n          Approx(2.5).epsilon(tol));\n    CHECK(LUT.ReverseLookup(distPerp, D * 3.2701500) / D ==\n          Approx(4.0).epsilon(tol));\n    CHECK(LUT.ReverseLookup(distPerp, D * 3.7911500) / D ==\n          Approx(5.0).epsilon(tol));\n    CHECK(LUT.ReverseLookup(distPerp, D * 4.1524200) / D ==\n          Approx(6.0).epsilon(tol));\n    // CHECK(relError(LUT.ReverseLookup(distPerp / D, 4.37561), 7.0) < tol);\n}\n\nTEST_CASE(\"REVERSE Lookup table test soft spring \", \"[REVERSE lookup]\") {\n    const double tol = 1e-2;\n    const double D = 0.024;\n    const double alpha = 0.1 / (2 * 0.00411);\n    const double freelength = 0.05;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n\n    LUTFillerEdep lut_filler(256, 256);\n    lut_filler.Init(alpha, freelength, D);\n    LookupTable LUT(&lut_filler);\n\n    double distPerp = 0;\n    distPerp = 0.2;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 2; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(LUT.ReverseLookup(distPerp, val * D) ==\n              Approx(sbound * D).epsilon(tol));\n    }\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 2; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(LUT.ReverseLookup(distPerp, val * D) ==\n              Approx(sbound * D).epsilon(tol));\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 2; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(LUT.ReverseLookup(distPerp, val * D) ==\n              Approx(sbound * D).epsilon(tol));\n    }\n}\n\nTEST_CASE(\"REVERSE Lookup table test medium spring \", \"[REVERSE lookup]\") {\n    const double tol = 1e-2;\n    const double D = 0.024;\n    const double alpha = 1.0 / (2 * 0.00411);\n    const double freelength = 0.05;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n\n    LUTFillerEdep lut_filler(256, 256);\n    lut_filler.Init(alpha, freelength, D);\n    LookupTable LUT(&lut_filler);\n\n    double distPerp = 0;\n    distPerp = 0.2;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 3; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        // CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D));\n        CHECK(LUT.ReverseLookup(distPerp, val * D) ==\n              Approx(sbound * D).epsilon(tol));\n    }\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 2; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        // CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D));\n        CHECK(LUT.ReverseLookup(distPerp, val * D) ==\n              Approx(sbound * D).epsilon(tol));\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 2; sbound += 0.2) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        // CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D));\n        CHECK(LUT.ReverseLookup(distPerp, val * D) ==\n              Approx(sbound * D).epsilon(tol));\n    }\n}\n\nTEST_CASE(\"REVERSE Lookup table test stiff spring \", \"[REVERSE lookup]\") {\n    const double tol = 1e-2;\n\n    const double D = 0.024;\n    const double alpha = 10.0 / (2 * 0.00411);\n    const double freelength = 0.05;\n    const double M = alpha * D * D;\n    const double ell0 = freelength / D;\n\n    LUTFillerEdep lut_filler(256, 256);\n    lut_filler.Init(alpha, freelength, D);\n    LookupTable LUT(&lut_filler);\n\n    double distPerp = 0;\n    // (\"distPerp = 0.2 > D+ell0, single peaked\")\n    // WARNING: This reverse lookup fails because function is too flat\n    // distPerp = 0.2;\n    // for (double sbound = 0; sbound < LUT.getNonDsbound() / 8; sbound += 0.1)\n    // {\n    //    double val = integral(distPerp / D, 0, sbound, M, ell0);\n    //    double scalc = LUT.ReverseLookup(distPerp, val * D);\n    //    printf(\"scalc = %f\\n\", scalc);\n    //    printf(\"sbound = %f\\n\", sbound * D);\n    //    CHECK(errorPass(scalc, sbound * D, REVERSEFAC));\n    //}\n\n    // (\"distPerp = 0.1 > D+ell0, single peaked\")\n    distPerp = 0.1;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 2; sbound += 0.1) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(LUT.ReverseLookup(distPerp, val * D) ==\n              Approx(sbound * D).margin(tol));\n        // CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n        // REVERSEFAC));\n    }\n    // (\"distPerp = 0.06 < D+ell0, double peaked\")\n    distPerp = 0.06;\n    for (double sbound = 0; sbound < LUT.getNonDsbound() / 2; sbound += 0.1) {\n        double val = integral(distPerp / D, 0, sbound, M, ell0);\n        CHECK(LUT.ReverseLookup(distPerp, val * D) ==\n              Approx(sbound * D).epsilon(tol));\n        // CHECK(errorPass(LUT.ReverseLookup(distPerp, val * D), sbound * D,\n        // REVERSEFAC));\n    }\n}\n\nTEST_CASE(\"REVERSE binary Lookup with different springs\", \"[REVERSE binary]\") {\n\n    const double D = 0.024;\n    const double freelength = 0.05;\n    const double ell0 = freelength / D;\n    double alpha, M;\n\n    LUTFillerEdep lut_filler(256, 256);\n\n    double rowIndexMax = lut_filler.getDistPerpGridNum();\n    double colIndexMax = lut_filler.getDistParaGridNum();\n    double distPerpSpacing;\n\n    SECTION(\"Soft spring\") {\n        alpha = 0.1 / (2 * 0.00411);\n        M = alpha * D * D;\n\n        lut_filler.Init(alpha, freelength, D);\n        LookupTable LUT(&lut_filler);\n\n        distPerpSpacing = LUT.perp_spacing_;\n        for (int i = 0; i < rowIndexMax - 2; ++i) {\n            double C0 = LUT.table_[LUT.getTableIndex(i, colIndexMax - 1)] * D;\n            double C1 =\n                LUT.table_[LUT.getTableIndex(i + 1, colIndexMax - 1)] * D;\n            double Cavg = .5 * (C0 + C1);\n            double distPerpAvg = distPerpSpacing * (i + .5) * D;\n            double sbound = LUT.ReverseLookup(distPerpAvg, Cavg);\n            double Cintegral =\n                integral(distPerpAvg / D, 0, sbound / D, M, ell0) * D;\n            CHECK(Cintegral == Approx(Cavg).epsilon(RELTOL));\n        }\n    }\n\n    SECTION(\"Medium spring\") {\n        alpha = 1.0 / (2 * 0.00411);\n        M = alpha * D * D;\n\n        lut_filler.Init(alpha, freelength, D);\n        LookupTable LUT(&lut_filler);\n\n        distPerpSpacing = LUT.perp_spacing_;\n        for (int i = 0; i < rowIndexMax - 2; ++i) {\n            double C0 = LUT.table_[LUT.getTableIndex(i, colIndexMax - 1)] * D;\n            double C1 =\n                LUT.table_[LUT.getTableIndex(i + 1, colIndexMax - 1)] * D;\n            double Cavg = .5 * (C0 + C1);\n            double distPerpAvg = distPerpSpacing * (i + .5) * D;\n            double sbound = LUT.ReverseLookup(distPerpAvg, Cavg);\n            double Cintegral =\n                integral(distPerpAvg / D, 0, sbound / D, M, ell0) * D;\n            CHECK(Cintegral == Approx(Cavg).epsilon(RELTOL));\n        }\n    }\n\n    SECTION(\"Stiff spring\") {\n        alpha = 10. / (2 * 0.00411);\n        M = alpha * D * D;\n\n        lut_filler.Init(alpha, freelength, D);\n        LookupTable LUT(&lut_filler);\n\n        distPerpSpacing = LUT.perp_spacing_;\n        for (int i = 0; i < rowIndexMax - 2; ++i) {\n            double C0 = LUT.table_[LUT.getTableIndex(i, colIndexMax - 1)] * D;\n            double C1 =\n                LUT.table_[LUT.getTableIndex(i + 1, colIndexMax - 1)] * D;\n            double Cavg = .5 * (C0 + C1);\n            double distPerpAvg = distPerpSpacing * (i + .5) * D;\n            double sbound = LUT.ReverseLookup(distPerpAvg, Cavg);\n            double Cintegral =\n                integral(distPerpAvg / D, 0, sbound / D, M, ell0) * D;\n            CHECK(Cintegral == Approx(Cavg).margin(1e-5));\n        }\n    }\n}\n\nTEST_CASE(\"Test the calculation of binding volume.\", \"[bind volume]\") {\n    const double D = 0.024;\n    const double freelength = 0.05;\n    double alpha = 1. / (2 * 0.00411);\n    const double ell0 = freelength / D;\n    double M = alpha * D * D;\n\n    LUTFillerEdep lut_filler(256, 256);\n\n    for (double i = 0.1; i < 1.0; i += .1) {\n        lut_filler.Init(alpha * i, freelength, D);\n        double bind_vol =\n            bind_vol_integral(lut_filler.getUpperBound(), i * M, ell0);\n        REQUIRE(lut_filler.getBindingVolume() ==\n                Approx(bind_vol).epsilon(1e-8));\n    }\n}\n", "meta": {"hexsha": "8b7aae6d659b9fa367d468b418a8cfc0c3c14c04", "size": 16925, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/lookup_test.hpp", "max_stars_repo_name": "lamsoa729/KMC", "max_stars_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-04-15T22:02:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T22:06:52.000Z", "max_issues_repo_path": "tests/lookup_test.hpp", "max_issues_repo_name": "lamsoa729/KMC", "max_issues_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-27T17:05:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T15:59:17.000Z", "max_forks_repo_path": "tests/lookup_test.hpp", "max_forks_repo_name": "lamsoa729/KMC", "max_forks_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-04-18T20:17:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-18T20:17:58.000Z", "avg_line_length": 39.4522144522, "max_line_length": 79, "alphanum_fraction": 0.5779615953, "num_tokens": 5584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6481283019439742}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/boost/graph/graph_traits_Delaunay_triangulation_2.h>\n\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <fstream>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point;\n\ntypedef CGAL::Delaunay_triangulation_2<K> Triangulation;\n\n// As we only consider finite vertices and edges\n// we need the following filter\n\ntemplate <typename T>\nstruct Is_finite {\n\n  const T* t_;\n\n  Is_finite()\n    : t_(NULL)\n  {}\n\n  Is_finite(const T& t)\n    : t_(&t)\n  { }\n\n  template <typename VertexOrEdge>\n  bool operator()(const VertexOrEdge& voe) const {\n    return ! t_->is_infinite(voe);\n  }\n};\n\ntypedef Is_finite<Triangulation> Filter;\ntypedef boost::filtered_graph<Triangulation,Filter,Filter> Finite_triangulation;\ntypedef boost::graph_traits<Finite_triangulation>::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits<Finite_triangulation>::vertex_iterator vertex_iterator;\ntypedef boost::graph_traits<Finite_triangulation>::edge_descriptor edge_descriptor;\n\n// The BGL makes use of indices associated to the vertices\n// We use a std::map to store the index\ntypedef std::map<vertex_descriptor,int> VertexIndexMap;\nVertexIndexMap vertex_id_map;\n\n// A std::map is not a property map, because it is not lightweight\ntypedef boost::associative_property_map<VertexIndexMap> VertexIdPropertyMap;\nVertexIdPropertyMap vertex_index_pmap(vertex_id_map);\n\nint\nmain(int argc,char* argv[])\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/points.xy\";\n  std::ifstream input(filename);\n  Triangulation t;\n  Filter is_finite(t);\n  Finite_triangulation ft(t, is_finite, is_finite);\n\n  Point p ;\n  while(input >> p){\n    t.insert(p);\n  }\n\n  vertex_iterator vit, ve;\n  // Associate indices to the vertices\n  int index = 0;\n  // boost::tie assigns the first and second element of the std::pair\n  // returned by boost::vertices to the variables vit and ve\n  for(boost::tie(vit,ve)=boost::vertices(ft); vit!=ve; ++vit ){\n    vertex_descriptor  vd = *vit;\n    vertex_id_map[vd]= index++;\n    }\n\n\n  // We use the default edge weight which is the squared length of the edge\n  // This property map is defined in graph_traits_Triangulation_2.h\n\n  // In the function call you can see a named parameter: vertex_index_map\n   std::list<edge_descriptor> mst;\n   boost::kruskal_minimum_spanning_tree(ft,\n\t\t\t\t\tstd::back_inserter(mst),\n\t\t\t\t\tvertex_index_map(vertex_index_pmap));\n\n\n   std::cout << \"The edges of the Euclidean mimimum spanning tree:\" << std::endl;\n\n   for(std::list<edge_descriptor>::iterator it = mst.begin(); it != mst.end(); ++it){\n     edge_descriptor ed = *it;\n     vertex_descriptor svd = source(ed,t);\n     vertex_descriptor tvd = target(ed,t);\n     Triangulation::Vertex_handle sv = svd;\n     Triangulation::Vertex_handle tv = tvd;\n     std::cout << \"[ \" << sv->point() << \"  |  \" << tv->point() << \" ] \" << std::endl;\n   }\n\n   return 0;\n}\n", "meta": {"hexsha": "ca8282d31954a7551a27be808cecc2d17d2e10cc", "size": 3041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_triangulation_2/emst.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_triangulation_2/emst.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_triangulation_2/emst.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 30.7171717172, "max_line_length": 87, "alphanum_fraction": 0.7300230187, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6481283015839473}}
{"text": "/// @file simple.hpp Sampling for various simple base distributions\n\n#ifndef BIGGLES_SAMPLING_SIMPLE_HPP__\n#define BIGGLES_SAMPLING_SIMPLE_HPP__\n\n#include <numeric> // std::partial_sum\n#include <vector>\n#include <boost/tuple/tuple.hpp>\n\n#include \"../detail/random.hpp\"\n#include \"../detail/fun.hpp\"\n#include \"../observation.hpp\"\n#include \"../observation_collection.hpp\"\n\nnamespace biggles {\n\n/// @brief Utility sampling methods and functions.\nnamespace sampling\n{\n\n/// @brief Sample an integer from a uniform distribution on the interval [\\p first, \\p last).\n///\n/// @note This function will never return an integer equal to \\p last.\n///\n/// @param first\n/// @param last\nint uniform_int(int first, int last);\n\n/// @brief Sample a real uniformly from the interval [\\p first, \\p last).\n///\n/// @param first\n/// @param last\nfloat uniform_real(float first = 0.f, float last = 1.f);\n\n/// @brief Sample a floating point value from the exponential distribution with rate parameter \\p lambda.\n///\n/// @param lambda\nfloat exponential(float lambda = 1.f);\n\n/// @brief Sample a Poisson variate from a distribution with mean \\p lambda.\n///\n/// @param lambda\nint poisson(float lambda);\n\n/// @brief Sample an iterator uniformly from the range [\\p first, \\p last).\n///\n/// If \\p first = \\p last, then return \\p last.\n///\n/// @note This is currently only implemented for \\c InputIterator types. Really there should be a specialisation for\n/// a \\c RandomAccessIterator. This is a FIXME for someone enthused to learn about iterator traits.\n///\n/// @tparam InputIterator\n/// @param first\n/// @param last\ntemplate<typename InputIterator>\nInputIterator from_range(InputIterator first, InputIterator last);\n\n/// @brief Sample an iterator uniformly from the range [\\p first, \\p last).\n///\n/// If \\p first = \\p last, then return \\p last. The reference \\p log_prob is only written to when \\p first != \\p last.\n///\n/// @note This is currently only implemented for \\c InputIterator types. Really there should be a specialisation for\n/// a \\c RandomAccessIterator. This is a FIXME for someone enthused to learn about iterator traits.\n///\n/// @tparam InputIterator\n/// @param first\n/// @param last\n/// @param[out] log_prob write the log probability of having sampled the return value to this reference\ntemplate<typename InputIterator>\nInputIterator from_range(InputIterator first, InputIterator last, float& log_prob);\n\n/*\n/// @brief Sample an observation from within a light cone.\n///\n/// Given the definition of a light cone as in biggles::observations_within_light_cone(), sample an observation from it\n/// with the following procedure:\n///\n/// - sample uniformly some time stamp within the light cone\n/// - sample uniformly from the observations with that time stamp\n///\n/// The log probability of drawing the sample is returned in \\p output_log_prob and the sample itself is returned in \\p\n/// output_obs.\n///\n/// @note The sampling procedure may sometimes fail to sample an observation. In this case the output references are\n/// untouched and the function returns \\p false.\n///\n/// @sa observations_within_light_cone()\n/// @sa log_prob_of_sampling_from_light_cone()\n///\n/// @param observations\n/// @param start\n/// @param speed_of_light\n/// @param first_time_stamp\n/// @param last_time_stamp\n/// @param[out] output_obs\n/// @param[out] output_log_prob\n///\n/// @return \\c true iff a sample could be drawn\nbool observation_from_light_cone(const observation_collection& observations,\n                                 const observation& start,\n                                 float speed_of_light,\n                                 time_stamp first_time_stamp,\n                                 time_stamp last_time_stamp,\n                                 observation& output_obs,\n                                 float& output_log_prob);\n                                 */\n\n/// @brief Return the log probability of having sampled an observation from a light cone.\n///\n/// This is the distribution from which observation_from_light_cone() actually samples. If \\p o could never have\n/// been sampled, this returns \\c -FLT_MAX as a place holder for negative infinity.\n///\n/// The parameters are as those in observation_from_light_cone().\n///\n/// @sa observations_within_light_cone()\n/// @sa observation_from_light_cone()\n///\n/// @param o\n/// @param observations\n/// @param start\n/// @param speed_of_light\n/// @param first_time_stamp\n/// @param last_time_stamp\nfloat log_prob_of_sampling_from_light_cone(const observation& o,\n                                           const observation_collection& observations,\n                                           const observation& start,\n                                           float speed_of_light,\n                                           time_stamp first_time_stamp,\n                                           time_stamp last_time_stamp);\n\n/// @brief Sample an observation from an observation collection\n///\n/// Sample an observation from \\p oc using the following procedure:\n///\n/// - sample a time stamp uniformly from the range covered by \\p oc;\n/// - sample an observation uniformly from those in \\p oc with that timestamp\n///\n/// It is possible for this procedure to fail to sample an observation in which case this function returns \\c false. If\n/// the sampling succeeded, the sample is written to \\p output_obs and the log probability of having sampled it is\n/// written to \\p output_log_prob.\n///\n/// @sa log_prob_of_sampling_observation()\n///\n/// @param oc Sample an observation from this collection\n/// @param[out] output_obs\n/// @param[out] output_log_prob\n///\n/// @return \\c true iff an observation was sampled\nbool observation_from_collection(const observation_collection& oc,\n                                 observation& output_obs,\n                                 float& output_log_prob);\n\n/// @brief The distribution from which observation() samples.\n///\n/// This is the distribution from which observation() actually samples. If \\p o could never have been sampled,\n/// this returns \\c -FLT_MAX as a place holder for negative infinity.\n///\n/// The parameters are as those in observation().\n///\n/// @param observation The observation sampled\n/// @param oc The collection from which it was sampled\nfloat log_prob_of_sampling_observation(const observation& observation,\n                                       const observation_collection& oc);\n\n\n/// @brief samples from a range of \\p items with probabilities proporational to \\p weights\n///\n/// @param items_begin the iterator pointing to the begin of \\p items\n/// @param weights_begin the iterator pointing to the begin of \\p weights\n/// @param weights_end the iterator pointing to the end of \\p weights\n///\n/// @return the sampled item\ntemplate <class ITEMITER, class WEIGHTITER>\ntypename ITEMITER::value_type\nweighted_choice(ITEMITER items_begin, WEIGHTITER weights_begin, WEIGHTITER weights_end) {\n    std::vector<float> partsum(std::distance(weights_begin, weights_end));\n    std::partial_sum(weights_begin, weights_end, partsum.begin());\n    size_t i = std::distance( partsum.begin(),\n        std::lower_bound( partsum.begin(), partsum.end(), uniform_real(0.f, partsum.back()) )\n    );\n    return *(items_begin+i);\n}\n\n/// @brief samples from a range of \\p items with probabilities proporational to \\p weights\n///\n/// @param items_begin the iterator pointing to the begin of \\p items\n/// @param weights_begin the iterator pointing to the begin of \\p weights\n/// @param weights_end the iterator pointing to the end of \\p weights\n/// @param log_prob the log-probability to sample the returned item\n///\n/// @return the sampled item\ntemplate <class ITEMITER, class WEIGHTITER>\ntypename ITEMITER::value_type\nweighted_choice(ITEMITER items_begin, WEIGHTITER weights_begin, WEIGHTITER weights_end, float& log_prob) {\n    std::vector<float> partsum(std::distance(weights_begin, weights_end));\n    float total = std::accumulate(weights_begin, weights_end, 0.0);\n    std::partial_sum(weights_begin, weights_end, partsum.begin());\n    size_t i = std::distance( partsum.begin(),\n        std::lower_bound( partsum.begin(), partsum.end(), uniform_real(0.f, partsum.back()) )\n    );\n    log_prob = logf(*(weights_begin+i)/total);\n    std::advance(items_begin, i);\n    return *items_begin;\n}\n\n/// @brief samples from a range of \\p items with probabilities proporational to weights given by \\em fun\n///\n/// @param items_begin the iterator pointing to the begin of \\p items\n/// @param items_end the iterator pointing to the end of \\p items\n/// @param fun the the weight functor\n/// @param log_prob the log-probability to sample the returned item\n///\n/// @return the iterator to the sampled item\ntemplate <class ITEMITER, class FUN>\nITEMITER weighted_choice(ITEMITER items_begin, ITEMITER items_end, FUN& fun , float& log_prob) {\n    std::vector<float> partsum(std::distance(items_begin, items_end));\n    fun_partial_sum(items_begin, items_end, partsum.begin(), fun, 0.f);\n    if (partsum.back() == 0) return items_end;\n    size_t i = std::distance( partsum.begin(),\n        std::lower_bound( partsum.begin(), partsum.end(), uniform_real(0.f, partsum.back()) )\n    );\n    log_prob = std::log((i == 0 ? *partsum.begin() : partsum[i] - partsum[i-1]) / partsum.back()) ;\n    std::advance(items_begin, i);\n    return items_begin;\n}\n\ntemplate <class WEIGHTITER>\nsize_t weighted_choice_index(WEIGHTITER weights_begin, WEIGHTITER weights_end, float& log_prob) {\n    std::vector<float> partsum(std::distance(weights_begin, weights_end));\n    float total = std::accumulate(weights_begin, weights_end, 0.f);\n    std::partial_sum(weights_begin, weights_end, partsum.begin());\n    size_t i = std::distance( partsum.begin(),\n        std::lower_bound( partsum.begin(), partsum.end(), uniform_real(0.f, partsum.back()) )\n    );\n    log_prob = logf(*(weights_begin+i)/total);\n    return i;\n}\n\n\n/// @brief  sample inverse wishart\nEigen::Matrix2f sample_inverse_wishart(const Eigen::Matrix2f& Phi, size_t s);\n/// @brief  sample wishart\nEigen::Matrix2f sample_wishart(const Eigen::Matrix2f& Phi, size_t s);\n\n/// @brief A simple functor yielding a uniformly sampled real from the interval [0, 1).\nstruct uniform_real_functor\n{\n    typedef float result_type;\n    float operator () () const { return sampling::uniform_real(); }\n};\n\nfloat sample_normal();\n\n/// @brief A default uniform real generator.\n///\n/// This is a convenience functor struct which can be used to get a uniform variate on the interval [0,1]. It is the\n/// default source of randomness for metropolis_hastings::sampler<> unless otherwise specified.\n///\n/// It is implemented using an internal boost Mersenne twister random number generator and a uniform real\n/// distribution.\nstruct boost_uniform\n{\n    boost_uniform() : dist_(0.,1.), uni_real_(biggles::detail::random_generator, dist_) { }\n    boost_uniform(const boost_uniform&) : dist_(0.,1.), uni_real_(biggles::detail::random_generator, dist_) { }\n    const boost_uniform& operator = (const boost_uniform&) { return *this; }\n\n    float operator() () { return uni_real_(); }\nprotected:\n    boost::uniform_real<float> dist_;\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<float> > uni_real_;\n};\n\n/// @brief Sample a Beta variate from a distribution with shape parameters \\p alpha and \\p beta.\n///\n/// @param alpha\n/// @param beta\nfloat sample_beta(float alpha, float beta);\n\n/** \\brief Sample a truncated Beta variate from a distribution with shape parameters \\p alpha and \\p beta.\n * and limits \\p lo_limit and \\p hi_limit\n *\n * The truncated beta is defined by:\n * * p(x; alpha, beta) = B(x; alpha, beta)/B([lo_limit, hi_limit]; alpha, beta) if \\b x is in [lo_limit, hi_limit]\n * * p(x; alpha, beta) = 0 if \\b x is not in  [lo_limit, hi_limit]\n *\n */\nfloat sample_truncated_beta(float alpha, float beta, float lo_limit, float hi_limit);\n\n/// @brief Sample a Gamma variate from a distribution with shape parmater \\p k and scale parameter \\p theta.\n///\n/// @param k shape\n/// @param theta scale\nfloat sample_gamma(unsigned int k, float theta);\n\n/// @brief Sample a Gamma variate from a distribution with shape parmater \\p k and scale parameter \\p theta.\n///\n/// Ensures that the result is > 0.0f\n/// @param k shape\n/// @param theta scale\nfloat sample_gamma0(unsigned int k, float theta);\n\ntemplate<typename Real, int Dim>\nEigen::Matrix<Real, Dim, 1> sample_multivariate_gaussian(const Eigen::Matrix<Real, Dim, 1>& mean,\n                                                         const Eigen::Matrix<Real, Dim, Dim>& covariance)\n{\n    // this uses http://en.wikipedia.org/wiki/Multivariate_normal_distribution#Drawing_values_from_the_distribution\n\n    typedef Eigen::Matrix<Real, Dim, Dim> Matrix;\n    typedef Eigen::Matrix<Real, Dim, 1> Vector;\n\n    Vector sample;\n\n    for(int i=0; i<Dim; ++i)\n        sample(i) = sample_normal();\n\n    Matrix cholesky_decomposition = covariance.llt().matrixL();\n\n    return mean + cholesky_decomposition * sample;\n}\n\n\n\n}\n\n}\n\n#define WITHIN_BIGGLES_SAMPLING_SIMPLE_HPP__\n#include \"simple.tcc\"\n#undef WITHIN_BIGGLES_SAMPLING_SIMPLE_HPP__\n\n#endif // BIGGLES_SAMPLING_SIMPLE_HPP__\n", "meta": {"hexsha": "a39711c2ff371c8d44edaeb609694f9871833a69", "size": 13103, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/biggles/sampling/simple.hpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "include/biggles/sampling/simple.hpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/biggles/sampling/simple.hpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4668674699, "max_line_length": 119, "alphanum_fraction": 0.6998397314, "num_tokens": 2940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6481282967373843}}
{"text": "/* Copyright 2022 CNRS-AIST JRL and CNRS-UM LIRMM */\n#if TVM_WITH_LEXLS\n#  include <tvm/solver/LexLSHierarchicalLeastSquareSolver.h>\n#endif\n\n#include <tvm/LinearizedControlProblem.h>\n#include <tvm/Variable.h>\n#include <tvm/constraint/BasicLinearConstraint.h>\n#include <tvm/function/IdentityFunction.h>\n#include <tvm/scheme/HierarchicalLeastSquares.h>\n#include <tvm/scheme/WeightedLeastSquares.h>\n#include <tvm/task_dynamics/None.h>\n\n#include <Eigen/SVD>\n\n#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN\n#define DOCTEST_CONFIG_SUPER_FAST_ASSERTS\n#include \"doctest/EigenDoctest.h\"\n\nusing namespace tvm;\nusing namespace tvm::constraint;\nusing namespace tvm::requirements;\nusing namespace tvm::solver;\nusing namespace Eigen;\n\nMatrixXd pinv(const MatrixConstRef & M, double eps = 1e-10)\n{\n  auto svd = M.jacobiSvd(ComputeThinU | ComputeThinV);\n  svd.setThreshold(eps);\n  int r = svd.rank();\n  return svd.matrixV().leftCols(r) * svd.singularValues().head(r).cwiseInverse().asDiagonal()\n         * svd.matrixU().leftCols(r).transpose();\n}\n\n#if TVM_WITH_LEXLS\nTEST_CASE(\"LexLSHierarchicalLeastSquareSolver\")\n{\n  VariablePtr x = Space(6).createVariable(\"x\");\n  MatrixXd A0(3, 6), A1(3, 6), A2(3, 6);\n  VectorXd b0(3), b1(3), b2(3);\n  // rank(A0)=2\n  A0 = MatrixXd::Random(3, 2) * MatrixXd::Random(2, 6);\n  // rank(A1) = 3 but rank(A1 projected on the nullspace of A0) = 2\n  A1 << MatrixXd::Random(1, 3) * A0, MatrixXd::Random(2, 6);\n  A1 = MatrixXd::Random(3, 3) * A1;\n  A2.setRandom();\n  b0.setRandom();\n  b1.setRandom();\n  b2.setRandom();\n  auto c0 = std::make_shared<BasicLinearConstraint>(A0, x, b0, constraint::Type::EQUAL);\n  auto c1a = std::make_shared<BasicLinearConstraint>(A1.row(0), x, b1.head(1), constraint::Type::EQUAL);\n  auto c1b = std::make_shared<BasicLinearConstraint>(A1.row(1), x, b1.segment(1, 1), constraint::Type::EQUAL);\n  auto c1c = std::make_shared<BasicLinearConstraint>(A1.row(2), x, b1.tail(1), constraint::Type::EQUAL);\n  auto c2 = std::make_shared<BasicLinearConstraint>(A2, x, b2, constraint::Type::EQUAL);\n\n  auto r0 = std::make_shared<SolvingRequirementsWithCallbacks>(PriorityLevel(0));\n  auto r1 = std::make_shared<SolvingRequirementsWithCallbacks>(PriorityLevel(1));\n  auto r2 = std::make_shared<SolvingRequirementsWithCallbacks>(PriorityLevel(2));\n\n  LexLSHierarchicalLeastSquareSolver solver(LexLSHLSSolverOptions{});\n  VariableVector vars(x);\n  solver.startBuild(vars, {3, 3, 3}, {0, 0, 0}, false);\n  solver.addConstraint(c0, r0);\n  solver.addConstraint(c1a, r1);\n  solver.addConstraint(c1b, r1);\n  solver.addConstraint(c1c, r1);\n  solver.addConstraint(c2, r2);\n  solver.finalizeBuild();\n\n  solver.solve();\n\n  // Compute the solution by hand\n  MatrixXd P0 = MatrixXd::Identity(6, 6) - pinv(A0) * A0;\n  MatrixXd A01(6, 6);\n  A01 << A0, A1;\n  MatrixXd P1 = MatrixXd::Identity(6, 6) - pinv(A01) * A01;\n  VectorXd dx0 = pinv(A0) * b0;\n  VectorXd dx1 = pinv(A1 * P0) * (b1 - A1 * dx0);\n  VectorXd dx2 = pinv(A2 * P1) * (b2 - A2 * (dx0 + dx1));\n  VectorXd x0 = dx0 + dx1 + dx2;\n\n  FAST_CHECK_EQ(solver.result(), Approx(x0).epsilon(1e-10));\n}\n\nTEST_CASE(\"LexLSHierarchicalLeastSquareSolver min norm\")\n{\n  VariablePtr x = Space(6).createVariable(\"x\");\n  MatrixXd A0(3, 6), A1(3, 6);\n  VectorXd b0(3), b1(3);\n  // rank(A0)=2\n  A0 = MatrixXd::Random(3, 2) * MatrixXd::Random(2, 6);\n  // rank(A1) = 3 but rank(A1 projected on the nullspace of A0) = 2\n  A1 << MatrixXd::Random(1, 3) * A0, MatrixXd::Random(2, 6);\n  A1 = MatrixXd::Random(3, 3) * A1;\n  b0.setRandom();\n  b1.setRandom();\n  auto c0 = std::make_shared<BasicLinearConstraint>(A0, x, b0, constraint::Type::EQUAL);\n  auto c1 = std::make_shared<BasicLinearConstraint>(A1, x, b1, constraint::Type::EQUAL);\n\n  auto r0 = std::make_shared<SolvingRequirementsWithCallbacks>(PriorityLevel(0));\n  auto r1 = std::make_shared<SolvingRequirementsWithCallbacks>(PriorityLevel(1));\n\n  LexLSHierarchicalLeastSquareSolver solver(LexLSHLSSolverOptions{});\n  VariableVector vars(x);\n  solver.startBuild(vars, {3, 3, 6}, {0, 0, 0}, false);\n  solver.addConstraint(c0, r0);\n  solver.addConstraint(c1, r1);\n  solver.setMinimumNorm(); // Equivalent to A2 = I and b2 = 0\n  solver.finalizeBuild();\n\n  solver.solve();\n\n  // Compute the solution by hand\n  MatrixXd P0 = MatrixXd::Identity(6, 6) - pinv(A0) * A0;\n  MatrixXd A01(6, 6);\n  A01 << A0, A1;\n  MatrixXd P1 = MatrixXd::Identity(6, 6) - pinv(A01) * A01;\n  VectorXd dx0 = pinv(A0) * b0;\n  VectorXd dx1 = pinv(A1 * P0) * (b1 - A1 * dx0);\n  VectorXd dx2 = pinv(P1) * (-(dx0 + dx1));\n  VectorXd x0 = dx0 + dx1 + dx2;\n\n  FAST_CHECK_EQ(solver.result(), Approx(x0).epsilon(1e-10));\n}\n\nTEST_CASE(\"HierarchicalLeastSquares\")\n{\n  SUBCASE(\"Equality only\")\n  {\n    VariablePtr x = Space(6).createVariable(\"x\");\n    MatrixXd A0(3, 6), A1(3, 6), A2(3, 6);\n    VectorXd b0(3), b1(3), b2(3);\n    // rank(A0)=2\n    A0 = MatrixXd::Random(3, 2) * MatrixXd::Random(2, 6);\n    // rank(A1) = 3 but rank(A1 projected on the nullspace of A0) = 2\n    A1 << MatrixXd::Random(1, 3) * A0, MatrixXd::Random(2, 6);\n    A1 = MatrixXd::Random(3, 3) * A1;\n    A2.setRandom();\n    b0.setRandom();\n    b1.setRandom();\n    b2.setRandom();\n\n    LinearizedControlProblem pb;\n    pb.add(A0 * x - b0 == 0., {PriorityLevel(0)});\n    pb.add(A1 * x - b1 == 0., {PriorityLevel(1)});\n    pb.add(A2 * x - b2 == 0., {PriorityLevel(2)});\n\n    scheme::HierarchicalLeastSquares solver(LexLSHLSSolverOptions{});\n\n    solver.solve(pb);\n\n    // Compute the solution by hand\n    MatrixXd P0 = MatrixXd::Identity(6, 6) - pinv(A0) * A0;\n    MatrixXd A01(6, 6);\n    A01 << A0, A1;\n    MatrixXd P1 = MatrixXd::Identity(6, 6) - pinv(A01) * A01;\n    VectorXd dx0 = pinv(A0) * b0;\n    VectorXd dx1 = pinv(A1 * P0) * (b1 - A1 * dx0);\n    VectorXd dx2 = pinv(A2 * P1) * (b2 - A2 * (dx0 + dx1));\n    VectorXd x0 = dx0 + dx1 + dx2;\n\n    FAST_CHECK_EQ(x->value(), Approx(x0).epsilon(1e-10));\n  }\n\n  SUBCASE(\"Inequality only\")\n  {\n    VariablePtr x = Space(1).createVariable(\"x\");\n    VariablePtr y = Space(1).createVariable(\"y\");\n\n    LinearizedControlProblem pb;\n    pb.add(-1. <= x <= 1., {PriorityLevel(0)});\n    pb.add(2. <= x <= 3., {PriorityLevel(1)});\n    pb.add(-1. <= y <= 1., {PriorityLevel(2)});\n    pb.add(x + y <= 0., {PriorityLevel(4)});\n\n    scheme::HierarchicalLeastSquares solver(LexLSHLSSolverOptions().feasibleFirstLevel(true));\n\n    solver.solve(pb);\n    FAST_CHECK_EQ(x->value()[0], doctest::Approx(1).epsilon(1e-10));\n    FAST_CHECK_EQ(y->value()[0], doctest::Approx(-1).epsilon(1e-10));\n  }\n}\n#endif\n", "meta": {"hexsha": "351a3c9f761f922464b63a30620451c1de17d019", "size": 6462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/HierarchicalLeastSquareSolverTest.cpp", "max_stars_repo_name": "mcx/tvm", "max_stars_repo_head_hexsha": "fab0eb3740be7e9156ca1018f7448ec07ac2a125", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/HierarchicalLeastSquareSolverTest.cpp", "max_issues_repo_name": "mcx/tvm", "max_issues_repo_head_hexsha": "fab0eb3740be7e9156ca1018f7448ec07ac2a125", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/HierarchicalLeastSquareSolverTest.cpp", "max_forks_repo_name": "mcx/tvm", "max_forks_repo_head_hexsha": "fab0eb3740be7e9156ca1018f7448ec07ac2a125", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1195652174, "max_line_length": 110, "alphanum_fraction": 0.6669761684, "num_tokens": 2250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.6481151480277195}}
{"text": "#include <armadillo>\n\n#include <mona/utility.hpp>\n#include <mona/targets/window.hpp>\n#include <mona/surface_mesh.hpp>\n#include <mona/axes3.hpp>\n\n\nauto f(double x, double y)\n{\n    return (7 * x * y) / std::exp(x*x + y*y);\n}\n\nint main()\n{\n    arma::fvec line = mona::linspace(-2, 2, 50);\n    auto [x, y] = mona::meshgrid(line, line);\n    auto z = mona::apply(f, x, y);\n\n    auto win = mona::targets::window();\n    auto mesh = mona::surface_mesh(x, y, z);\n    auto axes = mona::axes3({x.min(), x.max()}, {y.min(), y.max()}, {z.min(), z.max()}, 5);\n    axes.set_camera_control(win.get_camera_control());\n\n    while (win.active())\n    {\n        axes.submit(mesh);\n        win.submit(axes);\n        win.draw();\n    }\n}", "meta": {"hexsha": "10696fbd18fe53a4a5ac2846647b955aa6c02ec4", "size": 712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/surface_plot/main.cpp", "max_stars_repo_name": "Eleobert/mona", "max_stars_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/surface_plot/main.cpp", "max_issues_repo_name": "Eleobert/mona", "max_issues_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/surface_plot/main.cpp", "max_forks_repo_name": "Eleobert/mona", "max_forks_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9677419355, "max_line_length": 91, "alphanum_fraction": 0.5744382022, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6481123505307912}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <Eigen/Core>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include \"pixel2cam.h\"\n#include \"match.h\"\n#include \"BA.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\nint main( int argc, char** argv ) {\n    if ( argc != 5 )\n    {\n        cout<<\"usage: pose_estimation_3d2d img1 img2 depth1 depth2\"<<endl;\n        return 1;\n    }\n    Mat img_1 = imread ( argv[1], CV_LOAD_IMAGE_COLOR );\n    Mat img_2 = imread ( argv[2], CV_LOAD_IMAGE_COLOR );\n\n    vector<KeyPoint> keypoints_1,keypoints_2;\n    vector<DMatch> matches;\n\n\n    match ooo;\n\n    ooo.find_feature_matches ( img_1, img_2, keypoints_1, keypoints_2, matches );\n    cout<<\"totally find \"<<matches.size()<<\"pairs\"<<endl;\n\n    //build 3D point\n    Mat d1 = imread(argv[3], CV_LOAD_IMAGE_UNCHANGED);\n    Mat K = (Mat_<double> (3,3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n    vector<Point3f>pts_3d;\n    vector<Point2f>pts_2d;\n    for ( DMatch m:matches )\n    {\n        ushort d = d1.ptr<unsigned short> (int(keypoints_1[m.queryIdx].pt.y) )[int(keypoints_1[m.queryIdx].pt.x) ];\n        if (d == 0) //bad depth\n            continue;\n        float dd = d/1000.0;\n        pixel2cam mpixel2cam;\n\n        Point2d p1 = mpixel2cam.trans( keypoints_1[m.queryIdx].pt, K);\n        pts_3d.push_back( Point3f(p1.x*dd, p1.y*dd, dd) );\n        pts_2d.push_back( keypoints_2[m.trainIdx].pt );\n    }\n\n    cout<<\"3d-2d pairs: \"<<pts_3d.size()<<endl;\n\n    Mat r, t;\n    //PnP: EPnP DLS\n    solvePnP( pts_3d, pts_2d, K, Mat(), r, t, false, cv::SOLVEPNP_EPNP );\n\n    Mat R;\n    Rodrigues(r, R);//\u7f57\u5fb7\u91cc\u683c\u65af\n    cout<<\"R=\"<<endl<<R<<endl;\n    cout<<\"t=\"<<endl<<t<<endl;\n\n    cout<<\"calling bundle adjustment\"<<endl;\n\n    BA QQQ ;\n    QQQ.bundleadjustment(pts_3d, pts_2d, K, R, t);\n\n}", "meta": {"hexsha": "a73085d53ce8d89e660de1e2c1d811f863835f92", "size": 1957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7_VO1/pose_estimation_3d2d/src/pose_estimation_3d2d.cpp", "max_stars_repo_name": "ClovisChen/slam14", "max_stars_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch7_VO1/pose_estimation_3d2d/src/pose_estimation_3d2d.cpp", "max_issues_repo_name": "ClovisChen/slam14", "max_issues_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch7_VO1/pose_estimation_3d2d/src/pose_estimation_3d2d.cpp", "max_forks_repo_name": "ClovisChen/slam14", "max_forks_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9571428571, "max_line_length": 115, "alphanum_fraction": 0.6295350026, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6481123484117965}}
{"text": "\n/** MIT License\n\nCopyright (c) 2018 Benjamin Bercovici and Jay McMahon\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/**\n@file   main.cpp\n@Author Benjamin Bercovici (bebe0705@colorado.edu)\n@date   July, 2017\n@brief  main.cpp Implementation of the frames example\n*/\n\n#include <RigidBodyKinematics.hpp>\n#include <armadillo>\n#include <iostream>\n\n\nint main() {\n\n\t// This example features 2 frames: an inertial frame of reference \"N\" and a body frame \"B\"\n\n\t// Orienting B with respect to N means\n\tdouble yaw = 0.1;\n\tdouble pitch = 0.1;\n\tdouble roll = 0.1;\n\n\tarma::vec angles_321 = {yaw, pitch, roll};\n\tarma::mat dcm_BN = RBK::euler321_to_dcm(angles_321);\n\n\t// The position of B's origin is also expressed in N\n\tarma::vec origin_B_in_N = {150, 20, 40};\n\n\t// Some vector, for instance representative of a position in the inertial frame\n\tarma::vec pos_N = {150, 120, 20};\n\n\t// This vector is expressed in the B frame\n\tarma::vec pos_B = dcm_BN * (pos_N - origin_B_in_N);\n\n\t\n\n\n\treturn 0;\n\n}", "meta": {"hexsha": "c8cda2c9cbf68958943e0fc78246f50580ec87e9", "size": 1963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/frames/source/main.cpp", "max_stars_repo_name": "bbercovici/RigidBodyKinematics", "max_stars_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Examples/frames/source/main.cpp", "max_issues_repo_name": "bbercovici/RigidBodyKinematics", "max_issues_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/frames/source/main.cpp", "max_forks_repo_name": "bbercovici/RigidBodyKinematics", "max_forks_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1587301587, "max_line_length": 91, "alphanum_fraction": 0.7554763118, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6481123409520503}}
{"text": "#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include \"../include/layer.h\"\n#include \"../include/activation.h\"\n#include \"../include/loss.h\"\n\nnamespace MyDL\n{\n\n    using namespace Eigen;\n    using std::cout;\n    using std::endl;\n    using std::vector;\n\n    // -------------------------------------------------\n    //          AddLayer\n    // -------------------------------------------------\n    vector<MatrixXd> AddLayer::forward(vector<MatrixXd> inputs)\n    {\n\n        vector<MatrixXd> outs;\n\n        // \u672c\u5f53\u306f\u3053\u3053\u306b\u5165\u529b\u306e\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\u3092\u5165\u308c\u308b(\u8981\u7d20\u6570\u304c2)\n\n        outs.push_back(inputs[0] + inputs[1]);\n        return outs;\n    }\n\n    vector<MatrixXd> AddLayer::backward(vector<MatrixXd> douts)\n    {\n        vector<MatrixXd> grads;\n        MatrixXd dx, dy;\n        dx = douts[0];\n        dy = douts[0];\n\n        grads.push_back(dx);\n        grads.push_back(dy);\n        return grads;\n    }\n\n    // -------------------------------------------------\n    //          MulLayer\n    // -------------------------------------------------\n    vector<MatrixXd> MulLayer::forward(vector<MatrixXd> inputs)\n    {\n        _x = inputs[0];\n        _y = inputs[1];\n\n        vector<MatrixXd> outs;\n        MatrixXd out;\n\n        out = _x.array() * _y.array();\n\n        outs.push_back(out);\n        return outs;\n    }\n\n    vector<MatrixXd> MulLayer::backward(vector<MatrixXd> douts)\n    {\n        vector<MatrixXd> grads;\n        MatrixXd dx, dy;\n\n        dx = douts[0].array() * _y.array();\n        dy = douts[0].array() * _x.array();\n\n        grads.push_back(dx);\n        grads.push_back(dy);\n        return grads;\n    }\n\n    // -------------------------------------------------\n    //          ReLU\n    // -------------------------------------------------\n    vector<MatrixXd> ReLU::forward(vector<MatrixXd> inputs)\n    {\n        MatrixXd X;\n        vector<MatrixXd> outs;\n        X = inputs[0];\n\n        _mask = X.unaryExpr([](double p) { return p > 0; }).cast<double>();\n        outs.push_back(X.array() * _mask.array()); // \u8ca0\u306e\u6570\u306b\u5bfe\u3057\u3066\u3001mask\u3057\u305f\u90e8\u5206\u306f-0\u306b\u306a\u308b\u306e\u304c\u6c17\u304c\u304b\u308a\n        return outs;\n    }\n\n    vector<MatrixXd> ReLU::backward(vector<MatrixXd> douts)\n    {\n        vector<MatrixXd> grads;\n        MatrixXd dx;\n\n        dx = douts[0].array() * _mask.array();\n\n        grads.push_back(dx);\n        return grads;\n    }\n\n    // -------------------------------------------------\n    //          Sigmoid\n    // -------------------------------------------------\n    vector<MatrixXd> Sigmoid::forward(vector<MatrixXd> inputs)\n    {\n        MatrixXd X;\n        vector<MatrixXd> outs;\n        X = inputs[0];\n\n        _y = X.unaryExpr([](double p) { return 1 / (1 + exp(-p)); });\n\n        outs.push_back(_y);\n        return outs;\n    }\n\n    vector<MatrixXd> Sigmoid::backward(vector<MatrixXd> douts)\n    {\n        vector<MatrixXd> grads;\n        MatrixXd dx;\n\n        dx = douts[0].array() * (MatrixXd::Ones(_y.rows(), _y.cols()) - _y).array();\n\n        grads.push_back(dx);\n        return grads;\n    }\n\n    // -------------------------------------------------\n    //          Affine\n    // -------------------------------------------------\n    Affine::Affine(MatrixXd& W, MatrixXd& b)\n    {\n        _W = W;\n        _b = b;\n    }\n\n    Affine::Affine(const shared_ptr<MatrixXd> W, const shared_ptr<MatrixXd> b)\n    {\n        pW = W;\n        pb = b;\n    }\n\n    Affine::Affine(const int input_size, const int output_size, const double weight_init_std)\n    {\n        auto W = std::make_shared<MatrixXd>(input_size, output_size);\n        auto b = std::make_shared<MatrixXd>(1, output_size);\n        *W = weight_init_std * MatrixXd::Random(input_size, output_size);\n        *b = MatrixXd::Zero(1, output_size);\n        pW = W;\n        pb = b;\n    }\n\n    vector<MatrixXd> Affine::forward(vector<MatrixXd> inputs)\n    {\n        MatrixXd X, Y, W;\n        VectorXd b;\n        vector<MatrixXd> outs;\n        X = inputs[0];\n        _X = X;\n        W = *pW;\n        b = pb->row(0);\n        // W = _W;\n        // b = _b.row(0); // \u975e\u63a8\u5968 \u2192 \u30b3\u30d4\u30fc\u304c\u8d70\u308b\u3060\u3051\n\n        Y = (X * W).rowwise() + b.transpose();\n\n        outs.push_back(Y);\n        return outs;\n    }\n\n    vector<MatrixXd> Affine::backward(vector<MatrixXd> douts)\n    {\n        vector<MatrixXd> grads;\n        MatrixXd dX, dout;\n        MatrixXd W;\n\n        dout = douts[0];\n        W = *pW;\n        // W = _W; // \u975e\u63a8\u5968 \u2192 \u30b3\u30d4\u30fc\u304c\u8d70\u308b\u3060\u3051\n\n        dX = dout * W.transpose();\n        dW = _X.transpose() * dout;\n        db = dout.colwise().sum();\n\n        grads.push_back(dX);\n        return grads;\n    }\n\n    // -------------------------------------------------\n    //          SoftmaxWithLoss\n    // -------------------------------------------------\n    vector<MatrixXd> SoftmaxWithLoss::forward(vector<MatrixXd> inputs)\n    {\n        vector<MatrixXd> outs;\n        MatrixXd out = MatrixXd::Zero(1,1);\n        MatrixXd X = inputs[0];\n        _Y = softmax(X);\n        _t = inputs[1];\n\n        _loss = cross_entropy_error(_Y, _t);\n\n        out << _loss;\n        outs.push_back(out);\n        return outs;\n    }\n\n    vector<MatrixXd> SoftmaxWithLoss::backward(vector<MatrixXd> dout)\n    {\n        vector<MatrixXd> grads;\n\n        // \u51fa\u529b\u306e\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\n        if (!(dout[0].rows() == 1 && dout[0].cols() == 1))\n        {\n            cout << \"dout shape is not valid @ SoftmaxWithLoss Layer!!\" << endl;\n            cout << \"Please Check Your DNN Architecture.\" << endl;\n            return grads;\n        }\n\n        double batch_size = _t.rows();\n        MatrixXd dx;\n\n        dx = (_Y - _t) / batch_size;\n\n        grads.push_back(dx);\n        return grads;\n    }\n\n    // -------------------------------------------------\n    //          BatchNormalization\n    // -------------------------------------------------\n    BatchNorm::BatchNorm(const shared_ptr<MatrixXd> gamma, const shared_ptr<MatrixXd> beta, double momentum)\n    {\n        int cols;\n\n        pgamma = gamma;\n        pbeta = beta;\n        _momentum = momentum;\n\n        cols = pgamma->cols();\n\n        // pgamma, pbeta\u304c\u6a2a\u30d9\u30af\u30c8\u30eb\u3067\u3042\u308b\u3053\u3068\u3092\u3053\u3053\u3067\u30d0\u30ea\u30c7\u30fc\u30b7\u30e7\u30f3\u3057\u3066\u304a\u304f\uff1f(rows()==1\u3092\u78ba\u8a8d\u3068\u304b\u3002)\n\n        // \u3053\u3053\u3067\u521d\u671f\u5316\u3057\u3066\u304a\u304f\u3002\u30df\u30cb\u30d0\u30c3\u30c1\u306b\u304a\u3051\u308b\u5e73\u5747\u306a\u306e\u3067\u3001\u6a2a\u30d9\u30af\u30c8\u30eb\u306b\u306a\u308b\u3002\n        _avg_mean = VectorXd::Zero(cols);\n        _avg_var  = VectorXd::Zero(cols);\n    }\n\n\n    BatchNorm::BatchNorm(const int input_size, const double momentum)\n    {\n        auto gamma = std::make_shared<MatrixXd>(1, input_size);\n        auto beta = std::make_shared<MatrixXd>(1, input_size);\n        *gamma = MatrixXd::Ones(1, input_size); // Ones\u3067\u521d\u671f\u5316\u3059\u308b\u65b9\u304c\u826f\u3044\uff1f\n        *beta = MatrixXd::Zero(1, input_size);  // Zeros\u3067\u521d\u671f\u5316\u3059\u308b\u65b9\u304c\u826f\u3044\uff1f\n\n        pgamma = gamma;\n        pbeta = beta;\n        _momentum = momentum;\n\n        _avg_mean = VectorXd::Zero(input_size);\n        _avg_var = VectorXd::Zero(input_size);\n    }\n\n\n    vector<MatrixXd> BatchNorm::forward(vector<MatrixXd> inputs)\n    {\n        MatrixXd X = inputs[0];\n        MatrixXd Xn, Xc, out;\n        VectorXd gamma, beta;\n        VectorXd mu, var, std;\n        vector<MatrixXd> outs;\n        double momentum = _momentum;\n\n        gamma = pgamma->row(0);\n        beta = pbeta->row(0);\n\n        bool train_flg = Config::getInstance().get_flag(); // Singleton\u306eConfig\u30af\u30e9\u30b9\u304b\u3089\u30e2\u30fc\u30c9\u53d6\u5f97\n\n        if (train_flg){\n            mu = X.colwise().mean(); // \u30df\u30cb\u30d0\u30c3\u30c1\u306b\u304a\u3051\u308b\u30c7\u30fc\u30bf\u306e\u5e73\u5747\u5024(\u5404\u6b21\u5143\u3054\u3068)\n            Xc = X.rowwise() - mu.transpose();   // \u5165\u529b\u30c7\u30fc\u30bf\u306e\u5404\u6b21\u5143\u304b\u3089\u5e73\u5747\u5024\u3092\u5f15\u304d\u3001\u4e2d\u5fc3\u5316\n            var = Xc.array().pow(2).colwise().mean();                  // \u30df\u30cb\u30d0\u30c3\u30c1\u306b\u304a\u3051\u308b\u6a19\u672c\u5206\u6563(\u5404\u6b21\u5143\u3054\u3068)\n            std = var.unaryExpr([](double p){return sqrt(p + 1e-7);}); // \u30df\u30cb\u30d0\u30c3\u30c1\u306b\u304a\u3051\u308b\u6a19\u6e96\u504f\u5dee(\u5404\u6b21\u5143\u3054\u3068)\n\n            Xn = Xc.array().rowwise() / std.transpose().array();\n\n            _batch_size = X.rows();\n            _Xc = Xc;\n            _Xn = Xn;\n            _std = std;\n            _avg_mean = (momentum * _avg_mean.array() + (1 - momentum) * mu.array()).matrix();\n            _avg_var  = (momentum * _avg_var.array()  + (1 - momentum) * var.array()).matrix();\n        }\n        else\n        {\n            Xc = X.rowwise() - _avg_mean.transpose(); // broadcast\u6f14\u7b97\n            std = _avg_var.unaryExpr([](double p) { return sqrt(p + 1e-7); });\n            Xn = Xc.array().rowwise() / std.transpose().array();\n        }\n\n        // gamma\u3068beta\u306fVectorXd\u306b\u5909\u63db\u3059\u308b\u305f\u3081\u3001row(0)\u3092\u4f7f\u7528\u3057\u3066\u3044\u308b\u3002\n        out = (Xn * gamma.asDiagonal()).rowwise() + beta.transpose();\n        outs.push_back(out);\n\n        return outs;\n    }\n\n\n\n    vector<MatrixXd> BatchNorm::backward(vector<MatrixXd> douts)\n    {\n        vector<MatrixXd> grads;\n        MatrixXd dout  = douts[0];\n        MatrixXd dXn, dXc;\n        MatrixXd Xn = _Xn;\n        MatrixXd Xc = _Xc;\n        VectorXd std = _std;\n        VectorXd var;\n        MatrixXd dX;\n        VectorXd gamma, beta, dmu, dstd, dvar;\n\n        gamma = pgamma->row(0); // \u30d6\u30ed\u30fc\u30c9\u30ad\u30e3\u30b9\u30c8\u6f14\u7b97\u7528\u306bVectorXd\u5316\n        beta  = pbeta->row(0);  // \u540c\u4e0a\n\n        // parameter's gradient\n        dbeta = dout.colwise().sum();\n        dgamma = (dout.array() * Xn.array()).colwise().sum();\n\n        // For inputs' gradient\n        dXn  = dout * gamma.asDiagonal();                        // \u30d6\u30ed\u30fc\u30c9\u30ad\u30e3\u30b9\u30c8\u6f14\u7b97\n        dXc  = dXn.array().rowwise() / _std.transpose().array(); // \u30d6\u30ed\u30fc\u30c9\u30ad\u30e3\u30b9\u30c8\u6f14\u7b97\n\n        // colwise()\u3092\u5fd8\u308c\u306a\u3044\u3088\u3046\u306b -> shape\u304c\u5408\u308f\u306a\u3044\n        dstd = ((-1.0 * dXn).array() * Xc.array()).colwise().sum().array().rowwise()\n                / (std.transpose().array().pow(2)); // \u30d6\u30ed\u30fc\u30c9\u30ad\u30e3\u30b9\u30c8\u6f14\u7b97\n\n\n        dvar = (0.5 * dstd).array() * std.array().inverse(); // Vector\u540c\u58eb\u306e\u8981\u7d20\u7a4d\u306farray()\u3092\u4f7f\u7528\u3002\u8981\u7d20\u5546\u306farray().inverse()\u3068\u3059\u308b\u3002\n        dXc += (((2.0 / _batch_size)*Xc).array().rowwise() * dvar.transpose().array()).matrix(); // \u5de6\u8fba\u3068\u53f3\u8fba\u3067matrix\u578b\u304barray\u578b\u304b\u3092\u5408\u308f\u305b\u308b\n        dmu  = dXc.colwise().sum();\n        dX   = dXc.rowwise() - ((1/_batch_size) * dmu.transpose());\n\n        grads.push_back(dX);\n\n        return grads;\n    }\n\n    // -------------------------------------------------\n    //          Dropout\n    // -------------------------------------------------\n    Dropout::Dropout(const double dropout_ratio)\n    {\n        _dropout_ratio = dropout_ratio;\n    }\n\n    Dropout::Dropout(const int row, const int col, const double dropout_ratio)\n    {\n        _dropout_ratio = dropout_ratio;\n        _mask = MatrixXd::Zero(row, col).cast<bool>();\n    }\n\n    vector<MatrixXd> Dropout::forward(vector<MatrixXd> inputs)\n    {\n        MatrixXd X = inputs[0];\n        MatrixXd out;\n        vector<MatrixXd> outs;\n        bool train_flg = Config::getInstance().get_flag();\n        int col, row;\n        col = X.cols(); // \u30b5\u30a4\u30ba\u306e\u53d6\u5f97\n        row = X.rows(); // \u30b5\u30a4\u30ba\u306e\u53d6\u5f97\n        _mask = MatrixXd::Zero(row, col).cast<bool>();\n\n        // Eigen MatrixXd::Random \u306f -1 ~ 1 \u306e\u7bc4\u56f2\u3067\u4e71\u6570\u751f\u6210\u3059\u308b\u306e\u3067\u3001\u3053\u308c\u30920~1\u306e\u7bc4\u56f2\u306b\u5909\u66f4\u3059\u308b\n        double HI = 1.0;\n        double LO = 0;\n        double range = HI - LO;\n\n        if (train_flg)\n        {\n            // \u4e71\u6570\u306e\u7bc4\u56f2\u8abf\u6574 \u2192 \u81ea\u4f5c\u95a2\u6570\u306b\u3057\u3001util\u3068\u3057\u3066\u4f7f\u7528\uff1f\n            MatrixXd rand = MatrixXd::Random(row, col);\n            rand = (rand + MatrixXd::Constant(row, col, 1.)*range/2.);\n            rand = (rand + MatrixXd::Constant(row, col, LO));\n            _mask = rand.array() < _dropout_ratio;\n            MatrixXd mask = _mask.cast<double>();\n            out = X.array() * mask.array();\n        } else {\n            out = X * (1.0 - _dropout_ratio);\n        }\n\n        outs.push_back(out);\n        return outs;\n    }\n\n    vector<MatrixXd> Dropout::backward(vector<MatrixXd> douts)\n    {\n        vector<MatrixXd> grads;\n        MatrixXd dout = douts[0];\n        MatrixXd grad;\n\n        grad = dout.array() * _mask.cast<double>().array();\n\n        grads.push_back(grad);\n        return grads;\n    }\n\n    // -------------------------------------------------\n    //          Convolution\n    // -------------------------------------------------\n\n    Conv2D::Conv2D(int C, int H, int W, int Fh, int Fw, int Fn, int stride, int pad, double weight_init_std)\n    :_C(C), _H(H), _W(W), _Fh(Fh), _Fw(Fw), _Fn(Fn), _stride(stride), _pad(pad)\n    {\n        pW = std::make_shared<MatrixXd>(C*Fh*Fw, Fn);\n        pb = std::make_shared<MatrixXd>(1, Fn);\n        *pW = weight_init_std * MatrixXd::Random(C*Fh*Fw, Fn);\n        *pb = MatrixXd::Zero(1, Fn);\n    }\n\n    vector<MatrixXd> Conv2D::forward(vector<MatrixXd> inputs)\n    {\n        MatrixXd X, Y, W;\n        VectorXd b;\n        vector<MatrixXd> outs;\n        X = inputs[0];\n        _N = X.rows(); // batch size\n        \n        W = *pW;\n        b = pb->row(0);\n\n        int Oh = 1 + (_H + 2 * _pad - _Fh) / _stride;\n        int Ow = 1 + (_W + 2 * _pad - _Fw) / _stride;\n\n        im2col(X, _col);\n\n        Y = (_col * W).rowwise() + b.transpose();\n        Map<MatrixXd> Y_reshaped(Y.data(), _N, _Fn*Oh*Ow);\n\n        outs.push_back(Y_reshaped);\n        return outs;\n    }\n\n    vector<MatrixXd> Conv2D::backward(vector<MatrixXd> douts)\n    {\n        vector<MatrixXd> grads;\n        // dout\u3068\u3057\u3066\u5165\u3063\u3066\u304f\u308b\u306e\u306f\u3001(N, Fn*Oh*Ow) \u3068\u3044\u3046\u5f62\u72b6\u304c\u524d\u63d0\n\n        MatrixXd dout = douts[0];\n        MatrixXd W, dcol, dX;\n        VectorXd b;\n        W = *pW;\n\n\n        int Oh = (2*_pad+_H-_Fh) / _stride + 1;\n        int Ow = (2*_pad+_W-_Fw) / _stride + 1;\n\n        Map<MatrixXd> reshaped_dout(dout.data(), _N*Oh*Ow, _Fn);\n\n        db = reshaped_dout.colwise().sum();\n        dW = _col.transpose() * reshaped_dout;\n\n        dcol = reshaped_dout * W.transpose(); // (N\u00d7Oh\u00d7Ow) \u00d7 (C\u00d7Fh\u00d7Fw)\n\n        col2im(dcol, dX);\n\n        grads.push_back(dX);\n\n        return grads;\n    }\n\n    void Conv2D::padding(MatrixXd& img, MatrixXd& pad_img)\n    {\n        pad_img = MatrixXd::Zero(_N, _C * (_H + 2 * _pad) * (_W + 2 * _pad));\n\n        int pad_H_elems = _H + 2 * _pad;\n        int pad_W_elems = _W + 2 * _pad;\n        int pad_C_elems = pad_H_elems * pad_W_elems;\n\n        for (int n = 0; n < _N; n++)\n        {\n            for (int c = 0; c < _C; c++)\n            {\n                for (int h = 0; h < _H; h++)\n                {\n                    for (int w = 0; w < _W; w++)\n                    {\n                        // 1pixel\u305a\u3064\u7f6e\u304d\u63db\u3048\n                        pad_img(n, c * pad_C_elems + (h + _pad) * pad_W_elems + (w + _pad)) = img(n, c * (_H * _W) + _W * h + w);\n                    }\n                }\n            }\n        }\n    }\n\n    void Conv2D::im2col(MatrixXd& img, MatrixXd& col)\n    {\n        MatrixXd pad_img;\n\n        padding(img, pad_img);\n\n        int Oh = (2 * _pad + _H - _Fh) / _stride + 1;\n        int Ow = (2 * _pad + _W - _Fw) / _stride + 1;\n\n        col = MatrixXd::Zero(_N * Oh * Ow, _Fh * _Fw * _C);\n\n        int h_start = 0;\n        int w_start = 0;\n\n        int pad_H = _H + 2 * _pad;\n        int pad_W = _W + 2 * _pad;\n\n        int tmp_col_row, tmp_col_width;\n        int tmp_img_start; \n\n        for (int n = 0; n < _N; n++)\n        {\n            for (int c = 0; c < _C; c++)\n            {\n                for (int h_start = 0; h_start < Oh; h_start++)\n                {\n                    for (int w_start = 0; w_start < Ow; w_start++)\n                    {\n                        for (int h_offset = 0; h_offset < _Fh; h_offset++)\n                        {\n                            tmp_col_row = n * Oh * Ow + h_start * Ow + w_start;\n                            tmp_col_width = c * _Fh * _Fw + h_offset * _Fw;\n                            tmp_img_start = c * pad_H * pad_W + (h_start * _stride + h_offset) * pad_W + w_start * _stride;\n                            col.block(tmp_col_row, tmp_col_width, 1, _Fw) = pad_img.block(n, tmp_img_start, 1, _Fw);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    void Conv2D::col2im(MatrixXd& col, MatrixXd& img)\n    {\n        int pad_H = _H + 2 * _pad;\n        int pad_W = _W + 2 * _pad;\n\n        MatrixXd pad_img = MatrixXd::Zero(_N, _C*pad_H*pad_W);\n\n        int Oh = (2 * _pad + _H - _Fh) / _stride + 1;\n        int Ow = (2 * _pad + _W - _Fw) / _stride + 1;\n\n        int tmp_img_start;\n        int tmp_col_row, tmp_col_width;\n\n        for (int n = 0; n < _N; n++)\n        {\n            for (int c = 0; c < _C; c++)\n            {\n                for (int h = 0; h < Oh; h++)\n                {\n                    for (int w = 0; w < Ow; w++)\n                    {\n                        for (int h_offset = 0; h_offset < _Fh; h_offset++)\n                        {\n                            tmp_img_start = pad_H*pad_W*c+(h*_stride+h_offset)*pad_W+w*_stride;\n                            tmp_col_row = Oh*Ow*n+Ow*h+w;\n                            tmp_col_width = c*_Fh*_Fw+h_offset*_Fw;\n                            pad_img.block(n, tmp_img_start, 1, _Fw) += col.block(tmp_col_row, tmp_col_width, 1, _Fw);\n                        }\n                    }\n                }\n            }\n        }\n\n        suppress(pad_img, img);\n\n    }\n\n    void Conv2D::suppress(MatrixXd& pad_img, MatrixXd& img)\n    {\n        img = MatrixXd::Zero(_N, _C*_H*_W);\n        int pad_H = 2*_pad + _H;\n        int pad_W = 2*_pad + _W;\n\n        for (int n = 0; n < _N; n++)\n        {\n            for (int c = 0; c < _C; c++)\n            {\n                for (int h = 0; h < _H; h++)\n                {\n                    for (int w = 0; w < _W; w++)\n                    {\n                        // 1pixel\u305a\u3064\u7f6e\u304d\u63db\u3048\n                        img(n, c*_H*_W+h*_W+w) = pad_img(n, c*pad_H*pad_W+(h+_pad)*pad_W+(_pad+w));\n                    }\n                }\n            }\n        }\n    }\n\n    // -------------------------------------------------\n    //          Pooling\n    // -------------------------------------------------\n\n    Pooling::Pooling(int c, int h, int w, int Ph, int Pw, int stride, int pad)\n    :_C(c), _H(h), _W(w), _Ph(Ph), _Pw(Pw), _stride(stride), _pad(pad)\n    {\n    }\n\n    vector<MatrixXd> Pooling::forward(vector<MatrixXd> inputs)\n    {\n        MatrixXd X, col, vec_out;\n        vector<MatrixXd> outs;\n\n        X = inputs[0];\n        _X = X;\n        _N = X.rows();\n\n        int Oh = (2*_pad + _H - _Ph) / _stride + 1;\n        int Ow = (2*_pad + _W - _Pw) / _stride + 1;\n\n        im2col(X, col); // col\u306f N*Oh*Ow \u00d7 C*Ph*Pw \u306eshape\u3092\u3082\u3064\n\n        MatrixXd reshaped_col = MatrixXd::Zero(_C*_N*Oh*Ow, _Ph*_Pw);\n        MatrixXd tmp_c_col = MatrixXd::Zero(_N*Oh*Ow, _Ph*_Pw);\n\n        // column major\u306a\u306e\u3067\u3001\u76f4\u63a5reshape\u3059\u308b\u3068\u610f\u56f3\u3057\u305f\u6319\u52d5\u306b\u306a\u3089\u306a\u3044\n        // \u5404\u30c1\u30e3\u30cd\u30eb\u3054\u3068\u306breshape\u3092\u304b\u3051\u306a\u304a\u3059\n        for (int c = 0; c < _C; c++)\n        {\n            tmp_c_col = col.block(0, c*_Ph*_Pw, _N*Oh*Ow, _Ph*_Pw);\n            reshaped_col.block(c*_Ph*_Pw, 0, _N*Oh*Ow, _Ph*_Pw) = tmp_c_col;\n        }\n\n        int num_rows = reshaped_col.rows();\n        _argmax = MatrixXi::Zero(num_rows, 1);\n        vec_out = MatrixXd::Zero(num_rows, 1);\n        MatrixXi::Index dummy_row = 0;\n        MatrixXi::Index max_col = 0;\n\n        for (int r = 0; r < num_rows; r++)\n        {\n            vec_out(r, 0) = reshaped_col.row(r).maxCoeff(&dummy_row, &max_col);\n            _argmax(r, 0) = max_col;\n        }\n    \n        Map<MatrixXd> out(vec_out.data(), _N, Oh*Ow*_C);\n\n        outs.push_back(out);\n\n        return outs;\n    }\n\n    vector<MatrixXd> Pooling::backward(vector<MatrixXd> douts)\n    {\n        MatrixXd dout; // size: N \u00d7 (C\u00d7Oh\u00d7Ow)\n        MatrixXd dX;\n        vector<MatrixXd> grads;\n\n        int Oh = (2 * _pad + _H - _Ph) / _stride + 1;\n        int Ow = (2 * _pad + _W - _Pw) / _stride + 1;\n\n        dout = douts[0];\n        Map<MatrixXd> vec_dout(dout.data(), _N*Oh*Ow*_C, 1);\n\n        MatrixXd dmax = MatrixXd::Zero(_N*_C*Oh*Ow, _Ph*_Pw);\n        int argmax_index = 0;\n\n        for (int r = 0; r < dmax.rows(); r++)\n        {\n            argmax_index = _argmax(r, 0);\n            dmax(r, argmax_index) = vec_dout(r, 0);\n        }\n\n        MatrixXd tmp_c_dmax = MatrixXd::Zero(_N*Oh*Ow, _Ph*_Pw);\n        MatrixXd dcol = MatrixXd::Zero(_N*Oh*Ow, _C*_Ph*_Pw);\n\n        for (int c = 0; c < _C; c++)\n        {\n            tmp_c_dmax = dmax.block(c*_N*Oh*Ow, 0, _N*Oh*Ow, _Ph*_Pw);\n            dcol.block(0, c*_Ph*_Pw, _N*Oh*Ow, _Ph*_Pw) = tmp_c_dmax;\n        }\n\n        col2im(dcol, dX);\n\n        grads.push_back(dX);\n\n        return grads;\n    }\n\n    void Pooling::im2col(MatrixXd& img, MatrixXd& col)\n    {\n        MatrixXd pad_img;\n\n        padding(img, pad_img);\n\n        int Oh = (2 * _pad + _H - _Ph) / _stride + 1;\n        int Ow = (2 * _pad + _W - _Pw) / _stride + 1;\n\n        col = MatrixXd::Zero(_N * Oh * Ow, _Ph * _Pw * _C);\n\n        int h_start = 0;\n        int w_start = 0;\n\n        int pad_H = _H + 2 * _pad;\n        int pad_W = _W + 2 * _pad;\n\n        int tmp_col_row, tmp_col_width;\n        int tmp_img_start;\n\n        for (int n = 0; n < _N; n++)\n        {\n            for (int c = 0; c < _C; c++)\n            {\n                for (int h_start = 0; h_start < Oh; h_start++)\n                {\n                    for (int w_start = 0; w_start < Ow; w_start++)\n                    {\n                        for (int h_offset = 0; h_offset < _Ph; h_offset++)\n                        {\n                            tmp_col_row = n * Oh * Ow + h_start * Ow + w_start;\n                            tmp_col_width = c * _Ph * _Pw + h_offset * _Pw;\n                            tmp_img_start = c * pad_H * pad_W + (h_start * _stride + h_offset) * pad_W + w_start * _stride;\n                            col.block(tmp_col_row, tmp_col_width, 1, _Pw) = pad_img.block(n, tmp_img_start, 1, _Pw);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    void Pooling::col2im(MatrixXd& col, MatrixXd& img)\n    {\n        int pad_H = _H + 2 * _pad;\n        int pad_W = _W + 2 * _pad;\n\n        MatrixXd pad_img = MatrixXd::Zero(_N, _C*pad_H*pad_W);\n\n        int Oh = (2 * _pad + _H - _Ph) / _stride + 1;\n        int Ow = (2 * _pad + _W - _Pw) / _stride + 1;\n\n        int tmp_img_start;\n        int tmp_col_row, tmp_col_width;\n\n        for (int n = 0; n < _N; n++)\n        {\n            for (int c = 0; c < _C; c++)\n            {\n                for (int h = 0; h < Oh; h++)\n                {\n                    for (int w = 0; w < Ow; w++)\n                    {\n                        for (int h_offset = 0; h_offset < _Ph; h_offset++)\n                        {\n                            tmp_img_start = pad_H*pad_W*c+(h*_stride+h_offset)*pad_W+w*_stride;\n                            tmp_col_row = Oh*Ow*n+Ow*h+w;\n                            tmp_col_width = c*_Ph*_Pw+h_offset*_Pw;\n                            pad_img.block(n, tmp_img_start, 1, _Pw) += col.block(tmp_col_row, tmp_col_width, 1, _Pw);\n                        }\n                    }\n                }\n            }\n        }\n\n        suppress(pad_img, img);\n    }\n\n    void Pooling::padding(MatrixXd &img, MatrixXd &pad_img)\n    {\n        pad_img = MatrixXd::Zero(_N, _C * (_H + 2 * _pad) * (_W + 2 * _pad));\n\n        int pad_H_elems = _H + 2 * _pad;\n        int pad_W_elems = _W + 2 * _pad;\n        int pad_C_elems = pad_H_elems * pad_W_elems;\n\n        for (int n = 0; n < _N; n++)\n        {\n            for (int c = 0; c < _C; c++)\n            {\n                for (int h = 0; h < _H; h++)\n                {\n                    for (int w = 0; w < _W; w++)\n                    {\n                        // 1pixel\u305a\u3064\u7f6e\u304d\u63db\u3048\n                        pad_img(n, c * pad_C_elems + (h + _pad) * pad_W_elems + (w + _pad)) = img(n, c * (_H * _W) + _W * h + w);\n                    }\n                }\n            }\n        }\n    }\n\n    void Pooling::suppress(MatrixXd &pad_img, MatrixXd &img)\n    {\n        img = MatrixXd::Zero(_N, _C * _H * _W);\n        int pad_H = 2 * _pad + _H;\n        int pad_W = 2 * _pad + _W;\n\n        for (int n = 0; n < _N; n++)\n        {\n            for (int c = 0; c < _C; c++)\n            {\n                for (int h = 0; h < _H; h++)\n                {\n                    for (int w = 0; w < _W; w++)\n                    {\n                        // 1pixel\u305a\u3064\u7f6e\u304d\u63db\u3048\n                        img(n, c * _H * _W + h * _W + w) = pad_img(n, c * pad_H * pad_W + (h + _pad) * pad_W + (_pad + w));\n                    }\n                }\n            }\n        }\n    }\n}", "meta": {"hexsha": "0f476f8693c588beb81b85a6e643f5cd60a704d8", "size": 23608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/layer.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "src/layer.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/layer.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4364089776, "max_line_length": 129, "alphanum_fraction": 0.4573873263, "num_tokens": 7041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6480702353079597}}
{"text": "/* copied from the article:\nhttp://amitsaha.github.io/site/notes/articles/c_scientific/article.html\n*/\n\n/*Listing-5: array_demo.cc*/\n\n/* Simple demonstration of using Array\n   in Blitz++*/\n\n#include <blitz/array.h>\n\nusing namespace blitz;\n\nint main()\n{\n\n  cout << \">>>> 1-D Array Demonstration >>>>\" << endl << endl;\n\n  Array<float,1> a(5);\n  a=1,2,3,4,5;\n  cout << \"a = \" << a <<endl << endl;\n\n  Array<float,1> b(5);\n  b=2,1,3,4,1;\n  cout << \"b = \" << b <<endl << endl;\n\n  cout << \" >> Basic Arithmetic Operations >>\" << endl << endl;\n\n  Array<float,1> c(5);\n  c = a+b;\n  cout << \"c = a+b = \" << c <<endl << endl;\n\n  c = a*b;\n  cout << \"c = a*b = \" << c <<endl << endl;\n\n  c = a/b;\n  cout << \"c = a/b = \" << c <<endl << endl;\n\n  cout << \">>>> 2-D Array Demonstration >>>>\" << endl << endl;\n\n  Array<float,2> A(3,3);\n  A = 1, 2, 3,\n    3, 5, 1,\n    1, 1, 4;\n\n  cout << \"A = \" << A << endl;\n\n  Array<float,2> B(3,3);\n  B = 1, 2, 3,\n    3, 5, 1,\n    1, 1, 4;\n\n  cout << \"B = \" << B << endl;\n\n  cout << \" >> Basic Arithmetic Operations >>\" << endl << endl;\n\n  Array<float,2> C(3,3);\n  C = A+B;\n  cout << \"C = A+B = \" << C <<endl << endl;\n\n  C = A*B;\n  cout << \"C = A*B = \" << C <<endl << endl;\n\n  C = A/B;\n  cout << \"c = A/B = \" << C <<endl << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "1206e78059e2f725b23ba079a7de6b784d7974e8", "size": 1262, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/array_blitz.cc", "max_stars_repo_name": "FedoraScientific/scientific_spin_tests", "max_stars_repo_head_hexsha": "953620749c50092e0265846f49d89b1de77e93d3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-04-06T02:09:57.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-06T02:09:57.000Z", "max_issues_repo_path": "cpp/array_blitz.cc", "max_issues_repo_name": "FedoraScientific/scientific_spin_tests", "max_issues_repo_head_hexsha": "953620749c50092e0265846f49d89b1de77e93d3", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-27T06:42:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-27T06:42:26.000Z", "max_forks_repo_path": "cpp/array_blitz.cc", "max_forks_repo_name": "FedoraScientific/scientific_spin_tests", "max_forks_repo_head_hexsha": "953620749c50092e0265846f49d89b1de77e93d3", "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": 18.2898550725, "max_line_length": 71, "alphanum_fraction": 0.4770206022, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6480384502448737}}
{"text": "/*****************************************************************************\n*\n* Copyright (C) 2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include <iomanip>\n#include <iostream>\n#include <cmath>\n#include <limits>\n#include <boost/math/quadrature/exp_sinh.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/zeta.hpp>\n\ntemplate<class T>\nclass func {\npublic:\n  typedef T real_t;\n  func(real_t s) : s_(s) {}\n  real_t operator()(real_t x) const {\n    using std::exp; using std::pow; using std::sqrt;\n    if ((exp(x) - 1) > sqrt(std::numeric_limits<real_t>::epsilon())) {\n      return pow(x, s_ - 1) / (exp(x) - 1);\n    } else {\n      return pow(x, s_ - 1) / (x + x * x / 2);\n    }\n  }\n  real_t result() const {\n    return boost::math::tgamma(s_) * boost::math::zeta(s_);\n  }\nprivate:\n  real_t s_;\n};\n\nint main() {\n  using std::abs; \n  typedef double real_t;\n  \n  boost::math::quadrature::exp_sinh<real_t> integrator;\n  real_t termination = sqrt(std::numeric_limits<real_t>::epsilon());\n  real_t error, L1;\n  size_t levels;\n\n  real_t values[5] = { 1.1, 1.5, 2, 2.5, 3 };\n  for (auto s : values) {\n    func<real_t> f(s);\n    real_t q = integrator.integrate(f, termination, &error, &L1, &levels);\n\n    std::cout << std::scientific << std::setprecision(std::numeric_limits<real_t>::digits10)\n              << \"value of s: \" << s << std::endl\n              << \"result: \" << q << std::endl\n              << \"estimated error: \" << error << std::endl\n              << \"real error: \" << abs(q - f.result()) << std::endl\n              << \"L1 * error: \" << L1 * error << std::endl\n              << \"levels: \" << levels << std::endl;\n  }\n}\n", "meta": {"hexsha": "4cda2bb30191a35ae3f13ef92d654f06f6859863", "size": 1909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exp_sinh/zeta.cpp", "max_stars_repo_name": "wistaria/boost-examples", "max_stars_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exp_sinh/zeta.cpp", "max_issues_repo_name": "wistaria/boost-examples", "max_issues_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exp_sinh/zeta.cpp", "max_forks_repo_name": "wistaria/boost-examples", "max_forks_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2950819672, "max_line_length": 92, "alphanum_fraction": 0.5489785228, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6480384445263876}}
{"text": "/*****************************************************************\n*  Inversion of a symmetric matrix by Cholesky decomposition.    *\n*  The matrix must be positive definite.                         * \n* -------------------------------------------------------------- *\n* REFERENCE:                                                     *\n*             From a Java Library Created by Vadim Kutsyy,       *\n*             \"http://www.kutsyy.com\".                           *\n* -------------------------------------------------------------- * \n* SAMPLE RUN:                                                    *\n*                                                                *\n* Inversion of a square real symetric matrix by Cholevsky method *\n* (The matrix must positive definite).                           *\n*                                                                *\n* Size = 4                                                       *\n*                                                                *\n* Determinant = 432.000000                                       *\n*                                                                *\n* Matrix A:                                                      *\n* 5.000000 -1.000000 -1.000000 -1.000000                         *\n* -1.000000 5.000000 -1.000000 -1.000000                         *\n* -1.000000 -1.000000 5.000000 -1.000000                         *\n* -1.000000 -1.000000 -1.000000 5.000000                         *\n*                                                                *\n* Matrix Inv(A):                                                 *\n* 0.250000 0.083333 0.083333 0.083333                            *\n* 0.083333 0.250000 0.083333 0.083333                            *\n* 0.083333 0.083333 0.250000 0.083333                            *\n* 0.083333 0.083333 0.083333 0.250000                            *\n*                                                                *\n*                      C++ Release By Jean-Pierre Moreau, Paris. *\n*                                (www.jpmoreau.fr)               *\n* -------------------------------------------------------------- *\n* Release 1.1 : added verification Inv(A) * A = I.               *\n*****************************************************************/\n#include <stdio.h>\n#include <math.h>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <universal/number/posit/posit.hpp>\n\n#define  SIZE 25\n\n\ntypedef double MAT[SIZE][SIZE], VEC[SIZE];\n\nvoid choldc1(int,MAT,VEC); \n\n//print a square real matrix A of size n with caption s\n//(n items per line).\nvoid MatPrint(const char *s, int n, MAT A) {\n\tint i, j; printf(\"\\n %s\\n\", s);\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\" %10.6f\", A[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n}\n\n/* -----------------------------------------------\n        Cholesky decomposition.\n\n        input    n  size of matrix\n        input    A  Symmetric positive def. matrix\n        output   a  lower deomposed matrix\n        uses        choldc1(int,MAT,VEC)\n   ----------------------------------------------- */\nvoid choldc(int n,MAT A, MAT a) {\n\tint i,j;\n\tVEC p;\n\tfor (i = 0; i < n; i++) \n\t\tfor (j = 0; j < n; j++) \n\t\t\ta[i][j] = A[i][j];\n\tcholdc1(n, a, p);\n\tfor (i = 0; i < n; i++) {\n\t\ta[i][i] = p[i];\n\t\tfor (j = i + 1; j < n; j++) {\n\t\t\ta[i][j] = 0;\n\t\t}\n\t}\n}\n \n/* -----------------------------------------------------\n         Inverse of Cholesky decomposition.\n\n         input    n  size of matrix\n         input    A  Symmetric positive def. matrix\n         output   a  inverse of lower decomposed matrix\n         uses        choldc1(int,MAT,VEC)         \n   ----------------------------------------------------- */\n    void choldcsl(int n, MAT A, MAT a) {\n\t  int i,j,k; double sum;\n\t  VEC p;\n      for (i = 0; i < n; i++) \n\t    for (j = 0; j < n; j++) \n\t      a[i][j] = A[i][j];\n      \n\t  choldc1(n, a, p);\n      for (i = 0; i < n; i++) {\n        a[i][i] = 1 / p[i];\n        for (j = i + 1; j < n; j++) {\n            sum = 0;\n            for (k = i; k < j; k++) {\n                sum -= a[j][k] * a[k][i];\n\t        }\n            a[j][i] = sum / p[j];\n\t    }\n\t  }\n\t}\n \n/* -----------------------------------------------------------------------------\n        Computation of Determinant of the matrix using Cholesky decomposition\n\n        input    n  size of matrix\n        input    a  Symmetric positive def. matrix\n        return      det(a)\n        uses        choldc(int,MAT,MAT)\n   ------------------------------------------------------------------------------ */\n    double choldet(int n, MAT a) {\n\t   MAT c; \n\t   double d=1; \n\t   int i;\n       choldc(n,a,c);\n\t   MatPrint(\"choldet calls choldc:\\n\", n, c);\n       for (i = 0; i < n; i++)  d *= c[i][i];\n       return d * d;\n\t}\n \n/* ---------------------------------------------------\n        Matrix inverse using Cholesky decomposition\n\n        input    n  size of matrix\n        input\t  A  Symmetric positive def. matrix\n        output   a  inverse of A\n        uses        choldc1(MAT, VEC)\n   --------------------------------------------------- */\nvoid cholsl(int n, MAT A, MAT a) {\n\tint i,j,k;\n\tMatPrint(\"a\", n, a);\n    choldcsl(n,A,a);\n\tMatPrint(\"first a\", n, a);\n\n    for (i = 0; i < n; i++) {\n\t\tfor (j = i + 1; j < n; j++) {\n\t\t\ta[i][j] = 0.0;\n\t\t}\n\t}\n\tMatPrint(\"2nd a\", n, a);\n    for (i = 0; i < n; i++) {\n\t\ta[i][i] *= a[i][i];\n\t\tfor (k = i + 1; k < n; k++) {\n\t\t\ta[i][i] += a[k][i] * a[k][i];\n\t\t}\n\t\tfor (j = i + 1; j < n; j++) {\n\t\t\tfor (k = j; k < n; k++) {\n\t\t\t\ta[i][j] += a[k][i] * a[k][j];\n\t\t\t}\n\t\t}\n\t}\n\tMatPrint(\"3rd a\", n, a);\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < i; j++) {\n\t\t\ta[i][j] = a[j][i];\n\t\t}\n\t}\n\tMatPrint(\"final a\", n, a);\n}\n\n/* ----------------------------------------------------\n        main method for Cholesky decomposition.\n\n        input         n  size of matrix\n        input/output  a  Symmetric positive def. matrix\n        output        p  vector of resulting diag of a\n        author:       <Vadum Kutsyy, kutsyy@hotmail.com>\n   ----------------------------------------------------- */\n        void choldc1(int n, MAT a, VEC p) {\n          int i,j,k;\n          double sum;\n\n\t  for (i = 0; i < n; i++) {\n            for (j = i; j < n; j++) {\n              sum = a[i][j];\n              for (k = i - 1; k >= 0; k--) {\n                sum -= a[i][k] * a[j][k];\n\t      }\n              if (i == j) {\n                if (sum <= 0) {\n                  printf(\" a is not positive definite!\\n\");\n\t\t}\n                p[i] = sqrt(sum);\n\t      }\n              else {\n                a[j][i] = sum / p[i];\n\t      }\n\t    }\n\t  }\n\t}\n\n\n\n//check if matrix A is positive definite (return 1)\n//or not positive definite (return 0) \nint Check_Matrix(int n, MAT A) {\n    int i,j,k,result; double sum;\n    result=1;\n\tfor (i=0; i<n; i++) {\n\t    for (j = i; j<n; j++) {\n              sum = A[i][j];\n              for (k = i - 1; k>=0; k--)\n                sum -= A[i][k] * A[j][k];\n              if (i == j)\n                if (sum <= 0.0) result=0;\n\t    }\n    }\n\treturn result;\n}\n\n/******************************************\n*    MULTIPLICATION OF TWO SQUARE REAL    *                                     \n*    MATRICES                             *\n* --------------------------------------- *                                     \n* INPUTS:    A  MATRIX N*N                *                                     \n*            B  MATRIX N*N                *                                     \n*            N  INTEGER                   *                                     \n* --------------------------------------- *                                     \n* OUTPUTS:   C  MATRIX N*N PRODUCT A*B    *                                     \n*                                         *\n******************************************/\nvoid MatMult(int n, MAT A,MAT B, MAT C) {\n  double SUM;\n  int I,J,K;\n  for (I=0; I<n; I++)                                                                  \n    for (J=0; J<n; J++) {\n      SUM = 0.0;                                                                \n      for (K=0; K<n; K++)\n       SUM += A[I][K]*B[K][J];                                               \n      C[I][J]=SUM;                                                            \n    }                                                                   \n}\n\n//copy MAT A in MAT A1\nvoid MatCopy(int n, MAT A, MAT A1) {\n  int i,j;\n  for (i=0; i<n; i++)\n    for (j=0; j<n; j++)\n      A1[i][j]=A[i][j];\n}\n\n// main program to demonstrate the use of function cholsl()\nint main(int argc, char* argv[]) \ntry {\n\tMAT A, A1; int i,j, n;\n\tprintf(\" Inversion of a square real symetric matrix by Cholesky method\\n\");\n\tprintf(\" (The matrix must positive def.).\\n\");\n\n\tn = 4;\n\tprintf(\"\\n Size = %d\\n\", n);\n\n\t// define lower half of symmetrical matrix\n\tA[0][0]= 5;\n\tA[1][0]=-1; A[1][1]= 5;\n\tA[2][0]=-1; A[2][1]=-1; A[2][2]= 5;\n\tA[3][0]=-1; A[3][1]=-1; A[3][2]=-1; A[3][3]= 5;\n\n\t// define upper half by symmetry\n\tfor (i=0; i<n; i++)\n\t\tfor (j=i+1; j<n; j++)\t\n\t\t\tA[i][j]=A[j][i];\n\tMatCopy(n, A, A1);\n\n\tmtl::mat::dense2D<double> B(4, 4); B = 0;\n\tMAT C;\n\tif (Check_Matrix(n,A)) {\n\t\t//MatPrint(\"Matrix B:\", n, B);\n\t\tstd::cout << \"B:\\n\" << B << std::endl;\n\t\tMatPrint(\"Matrix C:\", n, C);\n\n\t\tdouble det = choldet(n, A);\n\t\t//MatPrint(\"Matrix B:\", n, B);\n\t\tstd::cout << \"B:\\n\" << B << std::endl;\n\t\tprintf(\"\\n Determinant = %f\\n\", det);\n\t\tMatPrint(\"Matrix A:\", n, A);\n\t\t// MatPrint(\"Matrix B:\", n, B);\n\t\tstd::cout << \"B:\\n\" << B << std::endl;\n\t\tMatPrint(\"Matrix C:\", n, C);\n\t\tcholsl(n,A,C);\n\t\tMatPrint(\"Matrix Inv(A):\",n,C);\n\t\tstd::cout << \"B:\\n\" << B << std::endl;\n\t}\n\telse {\n\t\tprintf(\"\\n Sorry, this matrix is not positive definite !\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tMAT Bprime;\n\tMatCopy(n, C, Bprime);\n\tprintf(\"\\n Verification: \");\n\tMatMult(n,A1,Bprime,C);\n\tMatPrint(\"Verification A * Inv(A) = I:\",n,C);\n\tprintf(\"\\n\");\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const sw::universal::posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const sw::universal::quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const sw::universal::posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (std::runtime_error& err) {\n\tstd::cerr << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"Caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}\n", "meta": {"hexsha": "2ece9fa0ebde68b1d74317368fb9631f282e72bc", "size": 10556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/blas/cholesky.cpp", "max_stars_repo_name": "stillwater-sc/hpr-blas", "max_stars_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-13T10:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T20:30:58.000Z", "max_issues_repo_path": "applications/blas/cholesky.cpp", "max_issues_repo_name": "stillwater-sc/hpr-blas", "max_issues_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T11:19:32.000Z", "max_forks_repo_path": "applications/blas/cholesky.cpp", "max_forks_repo_name": "stillwater-sc/hpr-blas", "max_forks_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:35:35.000Z", "avg_line_length": 32.48, "max_line_length": 87, "alphanum_fraction": 0.3703107238, "num_tokens": 2840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6479054812479421}}
{"text": "#include <complex>\n#include \"functions/std_functions.hh\"\n#include \"functions/full_function_defs.hh\"\n#include \"pointwise_equal.hh\"\n#include \"functions/all_simplifications.hh\"\n#include <boost/test/unit_test.hpp>\n#include \"functions/operators.hh\"\n#include <limits>\n\nBOOST_AUTO_TEST_CASE(trig_tests) {\n  using namespace manifolds;\n\n  PointwiseEqual(sin_, [](auto x) { return std::sin(std::get<0>(x)); });\n  PointwiseEqual(cos_, [](auto x) { return std::cos(std::get<0>(x)); });\n  PointwiseEqual(tan_, [](auto x) { return std::tan(std::get<0>(x)); });\n\n  PointwiseEqual(sinh_, [](auto x) { return std::sinh(std::get<0>(x)); });\n  PointwiseEqual(cosh_, [](auto x) { return std::cosh(std::get<0>(x)); });\n  PointwiseEqual(tanh_, [](auto x) { return std::tanh(std::get<0>(x)); });\n\n  std::complex<double> i(0, 1);\n  BOOST_CHECK_EQUAL(std::abs(sin_(i)), sinh_(1));\n  BOOST_CHECK_EQUAL(std::abs(sinh_(i)), sin_(1));\n\n  double min = -0.9999;\n  double max = -min;\n  PointwiseEqual(asin_, [](auto x) { return std::asin(std::get<0>(x)); }, 100,\n                 0, min, max);\n  PointwiseEqual(acos_, [](auto x) { return std::acos(std::get<0>(x)); }, 100,\n                 0, min, max);\n  PointwiseEqual(atan_, [](auto x) { return std::atan(std::get<0>(x)); }, 100,\n                 0, min, max);\n\n  PointwiseEqual(asinh_, [](auto x) { return std::asinh(std::get<0>(x)); }, 100,\n                 0);\n  PointwiseEqual(acosh_, [](auto x) { return std::acosh(std::get<0>(x)); }, 100,\n                 0, 1, 25);\n  PointwiseEqual(atanh_, [](auto x) { return std::atanh(std::get<0>(x)); }, 100,\n                 0, min, max);\n\n  BOOST_CHECK_EQUAL(Simplify(acos_(cos_(x))), x);\n  BOOST_CHECK_EQUAL(Simplify(asin_(sin_(x))), x);\n  BOOST_CHECK_EQUAL(Simplify(atan_(tan_(x))), x);\n\n  BOOST_CHECK_EQUAL(Simplify(acosh_(cosh_(x))), x);\n  BOOST_CHECK_EQUAL(Simplify(asinh_(sinh_(x))), x);\n  BOOST_CHECK_EQUAL(Simplify(atanh_(tanh_(x))), x);\n  static_assert(is_all_but_last_0<0, 0, 2>::value, \"\");\n\n  BOOST_CHECK_EQUAL(Simplify(sin_(IP<0, -2>())(x)),\n                    (IP<0, -2>()((sin_ * cos_))(x)));\n  BOOST_CHECK_EQUAL(Simplify(Cos()(IP<0, -2>())(x)),\n                    (cos_ * cos_ - sin_ * sin_)(x));\n  BOOST_CHECK_EQUAL(Simplify(sin_(IP<0, 3>()(x))),\n                    ComposeRaw(IP<0, 3, 0, -4>(), sin_, x));\n  PointwiseEqual(Simplify(cos_(IP<0, 3>())(x)),\n                 (Composition<Cos, IntegralPolynomial<0, 3>, decltype(x)>()),\n                 100, 1E-9);\n\n  BOOST_CHECK_EQUAL(Simplify(sin_(IP<0, 1, 1>())(x)),\n                    sin_(x) * cos_(x * x) + cos_(x) * sin_(x * x));\n\n  BOOST_CHECK_EQUAL(Simplify(tan_(IP<0, -1>()(x))), Simplify(-tan_(x)));\n\n  BOOST_CHECK_EQUAL(Simplify(tan_(x + x)),\n                    Simplify(((tan_ + tan_) / (IP<1>() + tan_ * tan_))(x)));\n\n  BOOST_CHECK_EQUAL(Simplify((sqrt_ * sqrt_)(x)), x);\n}\n", "meta": {"hexsha": "611dae58aed91d20b07fb79dd08319556adc345f", "size": 2825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_std_functions.cpp", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/tests/test_std_functions.cpp", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/tests/test_std_functions.cpp", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["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.3571428571, "max_line_length": 80, "alphanum_fraction": 0.5872566372, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6479054755596874}}
{"text": "// Boost.GIL (Generic Image Library) - tests\n//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n#ifndef BOOST_GIL_RASTERIZATION_CIRCLE_HPP\n#define BOOST_GIL_RASTERIZATION_CIRCLE_HPP\n\n#include <boost/gil/detail/math.hpp>\n#include <boost/gil/point.hpp>\n#include <cmath>\n#include <cstddef>\n\nnamespace boost { namespace gil {\n/// \\defgroup CircleRasterization\n/// \\ingroup Rasterization\n/// \\brief Circle rasterization algorithms\n///\n/// The main problems are connectivity and equation following. Circle can be easily moved\n/// to new offset, and rotation has no effect on it (not recommended to do rotation).\n\n/// \\ingroup CircleRasterization\n/// \\brief Rasterize trigonometric circle according to radius by sine and radius by cosine\n///\n/// This rasterizer is the one used that is used in standard Hough circle transform in\n/// the books. It is also quite expensive to compute.\n/// WARNING: the product of this rasterizer does not follow circle equation, even though it\n/// produces quite round like shapes.\nstruct trigonometric_circle_rasterizer\n{\n    /// \\brief Calculates minimum angle step that is distinguishable when walking on circle\n    ///\n    /// It is important to not have disconnected circle and to not compute unnecessarily,\n    /// thus the result of this function is used when rendering.\n    double minimum_angle_step(std::ptrdiff_t radius) const noexcept\n    {\n        const auto diameter = radius * 2 - 1;\n        return std::atan2(1.0, diameter);\n    }\n\n    /// \\brief Calculate the amount of points that rasterizer will output\n    std::ptrdiff_t point_count(std::ptrdiff_t radius) const noexcept\n    {\n        return 8 * static_cast<std::ptrdiff_t>(\n                       std::round(detail::pi / 4 / minimum_angle_step(radius)) + 1);\n    }\n\n    /// \\brief perform rasterization and output into d_first\n    template <typename RandomAccessIterator>\n    void operator()(std::ptrdiff_t radius, point_t offset, RandomAccessIterator d_first) const\n    {\n        const double minimum_angle_step = std::atan2(1.0, radius);\n        auto translate_mirror_points = [&d_first, offset](point_t p) {\n            *d_first++ = point_t{offset.x + p.x, offset.y + p.y};\n            *d_first++ = point_t{offset.x + p.x, offset.y - p.y};\n            *d_first++ = point_t{offset.x - p.x, offset.y + p.y};\n            *d_first++ = point_t{offset.x - p.x, offset.y - p.y};\n            *d_first++ = point_t{offset.x + p.y, offset.y + p.x};\n            *d_first++ = point_t{offset.x + p.y, offset.y - p.x};\n            *d_first++ = point_t{offset.x - p.y, offset.y + p.x};\n            *d_first++ = point_t{offset.x - p.y, offset.y - p.x};\n        };\n        const std::ptrdiff_t iteration_count = point_count(radius) / 8;\n        double angle = 0;\n        // do note that + 1 was done inside count estimation, thus <= is not needed, only <\n        for (std::ptrdiff_t i = 0; i < iteration_count; ++i, angle += minimum_angle_step)\n        {\n            std::ptrdiff_t x = static_cast<std::ptrdiff_t>(std::round(radius * std::cos(angle)));\n            std::ptrdiff_t y = static_cast<std::ptrdiff_t>(std::round(radius * std::sin(angle)));\n            translate_mirror_points({x, y});\n        }\n    }\n};\n\n/// \\ingroup CircleRasterization\n/// \\brief Perform circle rasterization according to Midpoint algorithm\n///\n/// This algorithm givess reasonable output and is cheap to compute.\n/// reference:\n/// https://en.wikipedia.org/wiki/Midpoint_circle_algorithm\nstruct midpoint_circle_rasterizer\n{\n    /// \\brief Calculate the amount of points that rasterizer will output\n    std::ptrdiff_t point_count(std::ptrdiff_t radius) const noexcept\n    {\n        // the reason for pulling 8 out is so that when the expression radius * cos(45 degrees)\n        // is used, it would yield the same result as here\n        // + 1 at the end is because the point at radius itself is computed as well\n        return 8 * static_cast<std::ptrdiff_t>(\n                       std::round(radius * std::cos(boost::gil::detail::pi / 4)) + 1);\n    }\n\n    /// \\brief perform rasterization and output into d_first\n    template <typename RAIterator>\n    void operator()(std::ptrdiff_t radius, point_t offset, RAIterator d_first) const\n    {\n        auto translate_mirror_points = [&d_first, offset](point_t p) {\n            *d_first++ = point_t{offset.x + p.x, offset.y + p.y};\n            *d_first++ = point_t{offset.x + p.x, offset.y - p.y};\n            *d_first++ = point_t{offset.x - p.x, offset.y + p.y};\n            *d_first++ = point_t{offset.x - p.x, offset.y - p.y};\n            *d_first++ = point_t{offset.x + p.y, offset.y + p.x};\n            *d_first++ = point_t{offset.x + p.y, offset.y - p.x};\n            *d_first++ = point_t{offset.x - p.y, offset.y + p.x};\n            *d_first++ = point_t{offset.x - p.y, offset.y - p.x};\n        };\n        std::ptrdiff_t iteration_distance = point_count(radius) / 8;\n        std::ptrdiff_t y_current = radius;\n        std::ptrdiff_t r_squared = radius * radius;\n        translate_mirror_points({0, y_current});\n        for (std::ptrdiff_t x = 1; x < iteration_distance; ++x)\n        {\n            std::ptrdiff_t midpoint = x * x + y_current * y_current - y_current - r_squared;\n            if (midpoint > 0)\n            {\n                --y_current;\n            }\n            translate_mirror_points({x, y_current});\n        }\n    }\n};\n}} // namespace boost::gil\n#endif\n", "meta": {"hexsha": "31c3cf6caf5f88054ca61f615141e4749e16860c", "size": 5601, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/rasterization/circle.hpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "include/boost/gil/rasterization/circle.hpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "include/boost/gil/rasterization/circle.hpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 44.1023622047, "max_line_length": 97, "alphanum_fraction": 0.6407784324, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6478875614783616}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_DIRICHLET_LPMF_HPP\n#define STAN_MATH_PRIM_MAT_PROB_DIRICHLET_LPMF_HPP\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/mat/err/check_simplex.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <stan/math/prim/scal/fun/multiply_log.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * The log of the Dirichlet density for the given theta and\n     * a vector of prior sample sizes, alpha.\n     * Each element of alpha must be greater than 0.\n     * Each element of theta must be greater than or 0.\n     * Theta sums to 1.\n     *\n     * \\f{eqnarray*}{\n     \\theta &\\sim& \\mbox{\\sf{Dirichlet}} (\\alpha_1, \\ldots, \\alpha_k) \\\\\n     \\log (p (\\theta \\, |\\, \\alpha_1, \\ldots, \\alpha_k) ) &=& \\log \\left( \\frac{\\Gamma(\\alpha_1 + \\cdots + \\alpha_k)}{\\Gamma(\\alpha_1) \\cdots \\Gamma(\\alpha_k)}\n     \\theta_1^{\\alpha_1 - 1} \\cdots \\theta_k^{\\alpha_k - 1} \\right) \\\\\n     &=& \\log (\\Gamma(\\alpha_1 + \\cdots + \\alpha_k)) - \\log(\\Gamma(\\alpha_1)) - \\cdots - \\log(\\Gamma(\\alpha_k)) +\n     (\\alpha_1 - 1) \\log (\\theta_1) + \\cdots + (\\alpha_k - 1) \\log (\\theta_k)\n     \\f}\n     *\n     * @param theta A scalar vector.\n     * @param alpha Prior sample sizes.\n     * @return The log of the Dirichlet density.\n     * @throw std::domain_error if any element of alpha is less than\n     * or equal to 0.\n     * @throw std::domain_error if any element of theta is less than 0.\n     * @throw std::domain_error if the sum of theta is not 1.\n     * @tparam T_prob Type of scalar.\n     * @tparam T_prior_sample_size Type of prior sample sizes.\n     */\n    template <bool propto,\n              typename T_prob, typename T_prior_sample_size>\n    typename boost::math::tools::promote_args<T_prob, T_prior_sample_size>::type\n    dirichlet_lpmf(const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta,\n                  const Eigen::Matrix\n                  <T_prior_sample_size, Eigen::Dynamic, 1>& alpha) {\n      static const char* function(\"dirichlet_lpmf\");\n      using boost::math::lgamma;\n      using boost::math::tools::promote_args;\n\n      typename promote_args<T_prob, T_prior_sample_size>::type lp(0.0);\n      check_consistent_sizes(function,\n                             \"probabilities\", theta,\n                             \"prior sample sizes\", alpha);\n      check_positive(function, \"prior sample sizes\", alpha);\n      check_simplex(function, \"probabilities\", theta);\n\n      if (include_summand<propto, T_prior_sample_size>::value) {\n        lp += lgamma(alpha.sum());\n        for (int k = 0; k < alpha.rows(); ++k)\n          lp -= lgamma(alpha[k]);\n      }\n      if (include_summand<propto, T_prob, T_prior_sample_size>::value) {\n        for (int k = 0; k < theta.rows(); ++k)\n          lp += multiply_log(alpha[k] - 1, theta[k]);\n      }\n      return lp;\n    }\n\n    template <typename T_prob, typename T_prior_sample_size>\n    inline\n    typename boost::math::tools::promote_args<T_prob, T_prior_sample_size>::type\n    dirichlet_lpmf(const Eigen::Matrix<T_prob, Eigen::Dynamic, 1>& theta,\n                  const Eigen::Matrix\n                  <T_prior_sample_size, Eigen::Dynamic, 1>& alpha) {\n      return dirichlet_lpmf<false>(theta, alpha);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "abca8a0c941e05150b48fe0c5070fc21c694be4c", "size": 3483, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/dirichlet_lpmf.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/dirichlet_lpmf.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/dirichlet_lpmf.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9638554217, "max_line_length": 159, "alphanum_fraction": 0.6431237439, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.647807527845109}}
{"text": "#include \"PointCloud.hpp\"\n\n#include <Eigen/Dense>\n#include <numeric>\n\n#include \"../KDTreeFlann/KDTreeFlann.hpp\"\n\n\nnamespace pointcloudhandler \n{\n\n\t\tPointCloud& PointCloud::Clear() \n\t\t{\n\t\t\tmPoints.clear();\n\t\t\treturn *this;\n\t\t}\n\n\t\tbool PointCloud::IsEmpty() const \n\t\t{ \n\t\t\treturn !HasPoints(); \n\t\t}\n\n\t\tEigen::Vector3d PointCloud::GetMinBound() const \n\t\t{\n\t\t\treturn ComputeMinBound(mPoints);\n\t\t}\n\n\t\tEigen::Vector3d PointCloud::GetMaxBound() const \n\t\t{\n\t\t\treturn ComputeMaxBound(mPoints);\n\t\t}\n\n\t\tEigen::Vector3d PointCloud::GetCenter() const \n\t\t{ \n\t\t\treturn ComputeCenter(mPoints); \n\t\t}\n\n\t\tPointCloud& PointCloud::Transform(const Eigen::Matrix4d &transformation) \n\t\t{\n\t\t\tTransformPoints(transformation, mPoints);\n\t\t\treturn *this;\n\t\t}\n\n\t\tPointCloud& PointCloud::Translate(const Eigen::Vector3d &translation, bool relative) \n\t\t{\n\t\t\tTranslatePoints(translation, mPoints, relative);\n\t\t\treturn *this;\n\t\t}\n\n\t\tPointCloud& PointCloud::Scale(const double scale, bool center) \n\t\t{\n\t\t\tScalePoints(scale, mPoints, center);\n\t\t\treturn *this;\n\t\t}\n\n\t\tPointCloud& PointCloud::Rotate(const Eigen::Matrix3d &R, bool center) \n\t\t{\n\t\t\tRotatePoints(R, mPoints, center);\n\t\t\treturn *this;\n\t\t}\n\n\t\tPointCloud& PointCloud::operator+=(const PointCloud &cloud) \n\t\t{\n\t\t\tif (cloud.IsEmpty()) \n\t\t\t\treturn (*this);\n\t\t\tsize_t oldVertNum = mPoints.size();\n\t\t\tsize_t addVertNum = cloud.mPoints.size();\n\t\t\tsize_t newVertNum = oldVertNum + addVertNum;\n\t\t\tmPoints.resize(newVertNum);\n\t\t\tfor (size_t i = 0; i < addVertNum; i++)\n\t\t\t\tmPoints[oldVertNum + i] = cloud.mPoints[i];\n\t\t\treturn (*this);\n\t\t}\n\n\t\tPointCloud PointCloud::operator+(const PointCloud &cloud) const \n\t\t{\n\t\t\treturn (PointCloud(*this) += cloud);\n\t\t}\n\n\t\tstd::vector<double> PointCloud::ComputePointCloudDistance(const PointCloud &target) \n\t\t{\n\t\t\tstd::vector<double> distances(mPoints.size());\n\t\t\tKDTreeFlann kdtree;\n\t\t\tkdtree.SetGeometry(target);\n\t\t\tfor (int i = 0; i < (int)mPoints.size(); i++) \n\t\t\t{\n\t\t\t\tstd::vector<int> indices(1);\n\t\t\t\tstd::vector<double> dists(1);\n\t\t\t\tif (kdtree.SearchKNN(mPoints[i], 1, indices, dists) == 0) \n\t\t\t\t{\n\t\t\t\t\t/*Found a point without neighbors.\");*/\n\t\t\t\t\tdistances[i] = 0.0;\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\tdistances[i] = std::sqrt(dists[0]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn distances;\n\t\t}\n\n\t\tPointCloud& PointCloud::RemoveNoneFinitePoints(bool removeNan, bool removeInfinite) {\n\t\t\tsize_t oldPointNum = mPoints.size();\n\t\t\tsize_t k = 0;                                 // new index\n\t\t\tfor (size_t i = 0; i < oldPointNum; i++) \n\t\t\t{  // old index\n\t\t\t\tbool isNan = removeNan &&\n\t\t\t\t\t(std::isnan(mPoints[i](0)) || std::isnan(mPoints[i](1)) || std::isnan(mPoints[i](2)));\n\t\t\t\tbool is_infinite = removeInfinite && \n\t\t\t\t\t(std::isinf(mPoints[i](0)) || std::isinf(mPoints[i](1)) ||std::isinf(mPoints[i](2)));\n\t\t\t\tif (!isNan && !is_infinite) \n\t\t\t\t{\n\t\t\t\t\tmPoints[k] = mPoints[i];\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmPoints.resize(k);\n\t\t\treturn *this;\n\t\t}\n\n\t\tstd::tuple<Eigen::Vector3d, Eigen::Matrix3d>PointCloud::ComputeMeanAndCovariance() const \n\t\t{\n\t\t\tif (IsEmpty()) \n\t\t\t{\n\t\t\t\treturn std::make_tuple(Eigen::Vector3d::Zero(), Eigen::Matrix3d::Identity());\n\t\t\t}\n\t\t\tEigen::Matrix<double, 9, 1> cumulants;\n\t\t\tcumulants.setZero();\n\t\t\tfor (const auto &point : mPoints) \n\t\t\t{\n\t\t\t\tcumulants(0) += point(0);\n\t\t\t\tcumulants(1) += point(1);\n\t\t\t\tcumulants(2) += point(2);\n\t\t\t\tcumulants(3) += point(0) * point(0);\n\t\t\t\tcumulants(4) += point(0) * point(1);\n\t\t\t\tcumulants(5) += point(0) * point(2);\n\t\t\t\tcumulants(6) += point(1) * point(1);\n\t\t\t\tcumulants(7) += point(1) * point(2);\n\t\t\t\tcumulants(8) += point(2) * point(2);\n\t\t\t}\n\t\t\tcumulants /= (double)mPoints.size();\n\t\t\tEigen::Vector3d mean;\n\t\t\tEigen::Matrix3d covariance;\n\t\t\tmean(0) = cumulants(0);\n\t\t\tmean(1) = cumulants(1);\n\t\t\tmean(2) = cumulants(2);\n\t\t\tcovariance(0, 0) = cumulants(3) - cumulants(0) * cumulants(0);\n\t\t\tcovariance(1, 1) = cumulants(6) - cumulants(1) * cumulants(1);\n\t\t\tcovariance(2, 2) = cumulants(8) - cumulants(2) * cumulants(2);\n\t\t\tcovariance(0, 1) = cumulants(4) - cumulants(0) * cumulants(1);\n\t\t\tcovariance(1, 0) = covariance(0, 1);\n\t\t\tcovariance(0, 2) = cumulants(5) - cumulants(0) * cumulants(2);\n\t\t\tcovariance(2, 0) = covariance(0, 2);\n\t\t\tcovariance(1, 2) = cumulants(7) - cumulants(1) * cumulants(2);\n\t\t\tcovariance(2, 1) = covariance(1, 2);\n\t\t\treturn std::make_tuple(mean, covariance);\n\t\t}\n\n\t\tstd::vector<double> PointCloud::ComputeMahalanobisDistance() const \n\t\t{\n\t\t\tstd::vector<double> mahalanobis(mPoints.size());\n\t\t\tEigen::Vector3d mean;\n\t\t\tEigen::Matrix3d covariance;\n\t\t\tstd::tie(mean, covariance) = ComputeMeanAndCovariance();\n\t\t\tEigen::Matrix3d covInv = covariance.inverse();\n\n\t\t\tfor (int i = 0; i < (int)mPoints.size(); i++) \n\t\t\t{\n\t\t\t\tEigen::Vector3d p = mPoints[i] - mean;\n\t\t\t\tmahalanobis[i] = std::sqrt(p.transpose() * covInv * p);\n\t\t\t}\n\t\t\treturn mahalanobis;\n\t\t}\n\n\t\tstd::vector<double> PointCloud::ComputeNearestNeighborDistance() const \n\t\t{\n\t\t\tstd::vector<double> nnDis(mPoints.size());\n\t\t\tKDTreeFlann kdtree(*this);\n\t\t\tfor (int i = 0; i < (int)mPoints.size(); i++) \n\t\t\t{\n\t\t\t\tstd::vector<int> indices(2);\n\t\t\t\tstd::vector<double> dists(2);\n\t\t\t\tif (kdtree.SearchKNN(mPoints[i], 2, indices, dists) <= 1) \n\t\t\t\t{\n\t\t\t\t\t/*Found a point without neighbors.\");*/\n\t\t\t\t\tnnDis[i] = 0.0;\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\tnnDis[i] = std::sqrt(dists[1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nnDis;\n\t\t}\n\n}  // namespace pointcloudhandler", "meta": {"hexsha": "bc55a2bccb222ea6a98dafad8d50c1e82ae61b2d", "size": 5290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PointCloudHandler/PointCloud/PointCloud.cpp", "max_stars_repo_name": "serjik85kg/PointCloudHandler", "max_stars_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PointCloudHandler/PointCloud/PointCloud.cpp", "max_issues_repo_name": "serjik85kg/PointCloudHandler", "max_issues_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PointCloudHandler/PointCloud/PointCloud.cpp", "max_forks_repo_name": "serjik85kg/PointCloudHandler", "max_forks_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9897959184, "max_line_length": 91, "alphanum_fraction": 0.6247637051, "num_tokens": 1794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.647541977275338}}
{"text": "/** @file\n * @brief NPDE ZienkiewiczZhuEstimator\n * @author Erick Schulz\n * @date 25/07/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"zienkiewiczzhuestimator.h\"\n\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <iomanip>\n// Eigen includes\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n// Lehrfem++ includes\n#include <lf/assemble/assemble.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\nnamespace ZienkiewiczZhuEstimator {\n\n/* Implementing member function Eval of class VectorProjectionMatrixProvider*/\n/* SAM_LISTING_BEGIN_1 */\nEigen::MatrixXd VectorProjectionMatrixProvider::Eval(\n    const lf::mesh::Entity &entity) {\n  Eigen::MatrixXd elMat_vec;  // element matrix to be returned\n  // Throw error in case cell is not Tria nor Quad\n  LF_VERIFY_MSG(entity.RefEl() == lf::base::RefEl::kTria() ||\n                    entity.RefEl() == lf::base::RefEl::kQuad(),\n                \"Unsupported cell type \" << entity.RefEl());\n\n  if (entity.RefEl() == lf::base::RefEl::kTria()) {\n    elMat_vec = Eigen::MatrixXd::Zero(6, 6);\n    // For TRIANGULAR CELLS\n    // Compute the area of the triangle cell\n    const double area = lf::geometry::Volume(*(entity.Geometry()));\n    // Assemble the mass element matrix over the cell\n    // clang-format off\n      elMat_vec << 2.0, 0.0, 1.0, 0.0, 1.0, 0.0,\n                   0.0, 2.0, 0.0, 1.0, 0.0, 1.0,\n\t           1.0, 0.0, 2.0, 0.0, 1.0, 0.0,\n\t           0.0, 1.0, 0.0, 2.0, 0.0, 1.0,\n\t           1.0, 0.0, 1.0, 0.0, 2.0, 0.0,\n\t           0.0, 1.0, 0.0, 1.0, 0.0, 2.0;\n    // clang-format on\n    elMat_vec *= area / 12.0;\n  } else {\n    // for QUADRILATERAL CELLS\n    elMat_vec = Eigen::MatrixXd::Zero(8, 8);\n    Eigen::MatrixXd elMat_scal =\n        Eigen::MatrixXd::Zero(4, 4);  // element matrix for scalar FEM\n    // Tensor product Gauss-Legendre quadrature rule of order 4\n    const lf::quad::QuadRule qr{\n        lf::quad::make_QuadRule(lf::base::RefEl::kQuad(), 3)};\n    // Reference quadrature points\n    const Eigen::MatrixXd zeta_ref{qr.Points()};\n    // Quadrature weights\n    const Eigen::VectorXd w_ref{qr.Weights()};\n    // Number of quadrature points\n    const lf::base::size_type P = qr.NumPoints();\n\n    // Reference tensor product basis functions on quadrilateral ref entity\n    std::vector<std::function<double(coord_t)>> ref_basis_vec;\n    auto b0_ref = [](coord_t x) -> double { return (1 - x(0)) * (1 - x(1)); };\n    auto b1_ref = [](coord_t x) -> double { return x(0) * (1 - x(1)); };\n    auto b2_ref = [](coord_t x) -> double { return x(0) * x(1); };\n    auto b3_ref = [](coord_t x) -> double { return (1 - x(0)) * x(1); };\n    ref_basis_vec.push_back(b0_ref);\n    ref_basis_vec.push_back(b1_ref);\n    ref_basis_vec.push_back(b2_ref);\n    ref_basis_vec.push_back(b3_ref);\n\n    const lf::geometry::Geometry &geo{*(entity.Geometry())};\n    const Eigen::VectorXd gram_dets{geo.IntegrationElement(zeta_ref)};\n    for (int i = 0; i < 4; i++) {\n      for (int j = 0; j < 4; j++) {\n        for (int l = 0; l < P; l++) {\n          elMat_scal(i, j) += w_ref[l] * ref_basis_vec[i](zeta_ref.col(l)) *\n                              ref_basis_vec[j](zeta_ref.col(l)) * gram_dets[l];\n        }\n      }\n    }\n    // 8x8 element (mass) matrix for vectorial FEM\n    // clang-format off\n    elMat_vec << elMat_scal(0, 0), 0.0, elMat_scal(0, 1), 0.0, elMat_scal(0, 2), 0.0, elMat_scal(0, 3), 0.0,\n                 0.0, elMat_scal(0, 0), 0.0, elMat_scal(0, 1), 0.0, elMat_scal(0, 2), 0.0, elMat_scal(0, 3),\n                 elMat_scal(1, 0), 0.0, elMat_scal(1, 1), 0.0, elMat_scal(1, 2), 0.0, elMat_scal(1, 3), 0.0,\n\t         0.0, elMat_scal(1, 0), 0.0, elMat_scal(1, 1), 0.0, elMat_scal(1, 2), 0.0, elMat_scal(1, 3),\n\t         elMat_scal(2, 0), 0.0, elMat_scal(2, 1), 0.0, elMat_scal(2, 2), 0.0, elMat_scal(2, 3), 0.0,\n\t         0.0, elMat_scal(2, 0), 0.0, elMat_scal(2, 1), 0.0, elMat_scal(2, 2), 0.0, elMat_scal(2, 3),\n                 elMat_scal(3, 0), 0.0, elMat_scal(3, 1), 0.0, elMat_scal(3, 2), 0.0, elMat_scal(3, 3), 0.0,\n                 0.0, elMat_scal(3, 0), 0.0, elMat_scal(3, 1), 0.0, elMat_scal(3, 2), 0.0, elMat_scal(3, 3);\n    // clang-format on\n\n  }\n  return elMat_vec;  // return the local mass element matrix\n}  //\n/* SAM_LISTING_END_1 */\n\n/* Implementing member function Eval of class GradientProjectionVectorProvider*/\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd GradientProjectionVectorProvider::Eval(\n    const lf::mesh::Entity &entity) {\n  Eigen::VectorXd elVec(6);  // for returning the element vector\n  // Obtain local->global index mapping for current finite element space\n  const lf::assemble::DofHandler &dofh{_fe_space_p->LocGlobMap()};\n  // Obtain global indices of the vertices of the triangle entity\n  auto dof_idx_vec = dofh.GlobalDofIndices(entity);\n  LF_ASSERT_MSG(dofh.NumLocalDofs(entity) == 3,\n                \"Too many global indices were returned for a triangle entity!\");\n\n  // Obtain the gradients of the barycentric coordinate functions\n  Eigen::Matrix<double, 2, 3> elgrad_Mat = gradbarycoordinates(entity);\n  // Compute the local constant gradient of the finite element solution\n  Eigen::Vector2d grad_vec(0.0, 0.0);\n  for (int i = 0; i < 3; i++) {\n    grad_vec = grad_vec + elgrad_Mat.col(i) * _mu(dof_idx_vec[i]);\n  }\n  // Assemble local element vector\n  // Compute the area of the triangle cell\n  const double area = lf::geometry::Volume(*(entity.Geometry()));\n  // clang-format off\n    elVec << grad_vec(0),\n             grad_vec(1),\n             grad_vec(0),\n             grad_vec(1),\n             grad_vec(0),\n             grad_vec(1);\n  // clang-format on\n  elVec *= area / 3.0;\n  return elVec;\n}  // GradientProjectionVectorProvider::Eval\n/* SAM_LISTING_END_2 */\n\nEigen::Matrix<double, 2, 3> gradbarycoordinates(\n    const lf::mesh::Entity &entity) {\n  LF_VERIFY_MSG(entity.RefEl() == lf::base::RefEl::kTria(),\n                \"Unsupported cell type \" << entity.RefEl());\n\n  // Get vertices of the triangle\n  auto endpoints = lf::geometry::Corners(*(entity.Geometry()));\n\n  Eigen::Matrix<double, 3, 3> X;  // temporary matrix\n  X.block<3, 1>(0, 0) = Eigen::Vector3d::Ones();\n  X.block<3, 2>(0, 1) = endpoints.transpose();\n\n  return X.inverse().block<2, 3>(1, 0);\n}  // gradbarycoordinates\n\n/* SAM_LISTING_BEGIN_3 */\nEigen::VectorXd computeLumpedProjection(\n    const lf::assemble::DofHandler &scal_dofh, const Eigen::VectorXd &mu,\n    const lf::assemble::DofHandler &vec_dofh) {\n  // Obtain shared_ptr to mesh\n  std::shared_ptr<const lf::mesh::Mesh> mesh_p = scal_dofh.Mesh();\n  // Dimension of vector-valued finite element space\n  const lf::uscalfe::size_type N_vec_dofs(vec_dofh.NumDofs());\n  // Initialize vector FE basis expansion coefficient vector with zeros\n  Eigen::VectorXd proj_vec(N_vec_dofs);\n  proj_vec.setZero();\n  // Initialize temporary helper nodal DataSet (codim 2)\n  auto nodal_sum_of_areas =\n      lf::mesh::utils::CodimMeshDataSet<double>(mesh_p, 2, 0.0);\n\n  // Loop over the triangular cells of the mesh in the spirit of\n  // cell oriented assembly\n  for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n    LF_VERIFY_MSG(cell->RefEl() == lf::base::RefEl::kTria(),\n                  \"Unsupported cell type \" << cell->RefEl());\n    // Obtain global scalar-FE indices of the vertices\n    const auto scal_dof_idx_vec = scal_dofh.GlobalDofIndices(*cell);\n    // Obtain the gradients of the barycentric coordinate functions\n    const Eigen::Matrix<double, 2, 3> elgrad_Mat = gradbarycoordinates(*cell);\n    // Obtain area of the triangular cell\n    const double area = lf::geometry::Volume(*(cell->Geometry()));\n// Compute the gradient of the passed coefficient vector\n    const Eigen::Vector2d grad_mu =\n        elgrad_Mat.col(0) * mu(scal_dof_idx_vec[0]) +\n        elgrad_Mat.col(1) * mu(scal_dof_idx_vec[1]) +\n        elgrad_Mat.col(2) * mu(scal_dof_idx_vec[2]);\n    // Local contribution to the area of the cell patch surrounding a node\n    for (const lf::mesh::Entity *node : cell->SubEntities(2)) {\n      LF_VERIFY_MSG(node->RefEl() == lf::base::RefEl::kPoint(),\n                    \"Expected kPoint type!\" << node->RefEl());\n      auto vec_dofh_idx = vec_dofh.GlobalDofIndices(*node);\n      proj_vec[vec_dofh_idx[0]] += area * grad_mu[0];\n      proj_vec[vec_dofh_idx[1]] += area * grad_mu[1];\n      nodal_sum_of_areas(*node) = nodal_sum_of_areas(*node) + area;\n    }\n  }\n\n  // Scaling of components of vector of dofs\n  for (const lf::mesh::Entity *node : mesh_p->Entities(2)) {\n    LF_VERIFY_MSG(node->RefEl() == lf::base::RefEl::kPoint(),\n                  \"Expected kPoint type!\" << node->RefEl());\n    const double area_scal_fac = 1.0 / nodal_sum_of_areas(*node);\n    auto vec_dofh_idx = vec_dofh.GlobalDofIndices(*node);\n    proj_vec[vec_dofh_idx[0]] *= area_scal_fac;\n    proj_vec[vec_dofh_idx[1]] *= area_scal_fac;\n  }\n  return proj_vec;\n};  // computeLumpedProjection\n\n/* SAM_LISTING_END_3 */\n\n/* SAM_LISTING_BEGIN_4 */\ndouble computeL2Deviation(const lf::assemble::DofHandler &scal_dofh,\n                          const Eigen::VectorXd &eta,\n                          const lf::assemble::DofHandler &vec_dofh,\n                          const Eigen::VectorXd &gamma) {\n  double deviation_norm_value = 0.0;  // For retrurning the result\n  // Obtain shared_ptr to mesh\n  auto mesh_p = scal_dofh.Mesh();\n  // Cell-oriented computation of deviation norm (squared)\n  for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n    LF_VERIFY_MSG(cell->RefEl() == lf::base::RefEl::kTria(),\n                  \"Unsupported cell type \" << cell->RefEl());\n    // Obtain area of the triangular cell\n    const double area = lf::geometry::Volume(*(cell->Geometry()));\n\n    // Obtain global scalar-FE indices of the vertices\n    auto scal_dof_idx_vec = scal_dofh.GlobalDofIndices(*cell);\n    // Obtain the gradients of the barycentric coordinates functions\n    Eigen::Matrix<double, 2, 3> elgrad_Mat = gradbarycoordinates(*cell);\n// Compute the gradient of the passed coefficient vector eta\n    const Eigen::Vector2d grad_eta =\n        elgrad_Mat.col(0) * eta(scal_dof_idx_vec[0]) +\n        elgrad_Mat.col(1) * eta(scal_dof_idx_vec[1]) +\n        elgrad_Mat.col(2) * eta(scal_dof_idx_vec[2]);\n\n    // Obtaining the values of the passed vector at each node\n    std::vector<Eigen::Vector2d> r_vec_values;\n    for (const lf::mesh::Entity *node : cell->SubEntities(2)) {\n      LF_VERIFY_MSG(node->RefEl() == lf::base::RefEl::kPoint(),\n                    \"Expected kPoint type!\" << node->RefEl());\n      auto vec_dofh_idx = vec_dofh.GlobalDofIndices(*node);\n      Eigen::Vector2d r_vec_at_node;\n      r_vec_at_node[0] = gamma[vec_dofh_idx[0]];\n      r_vec_at_node[1] = gamma[vec_dofh_idx[1]];\n      r_vec_values.push_back(r_vec_at_node);\n    }\n\n    // Computing local contribution of the cell to the deviation norm\n    double local_norm_value =\n        (0.5 * (r_vec_values.at(0) + r_vec_values.at(1)) - grad_eta)\n            .squaredNorm() +\n        (0.5 * (r_vec_values.at(1) + r_vec_values.at(2)) - grad_eta)\n            .squaredNorm() +\n        (0.5 * (r_vec_values.at(2) + r_vec_values.at(0)) - grad_eta)\n            .squaredNorm();\n    local_norm_value *= area / 3.0;\n\n    // Adding local contribution to the value of the deviation norm\n    deviation_norm_value += local_norm_value;\n  }\n  return std::sqrt(deviation_norm_value);\n};  // computeL2Deviation\n/* SAM_LISTING_END_4 */\n\nEigen::VectorXd solveBVP(\n    const std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> &fe_space_p) {\n  Eigen::VectorXd discrete_solution;\n\n  // TOOLS AND DATA\n  // Pointer to current mesh\n  std::shared_ptr<const lf::mesh::Mesh> mesh_p = fe_space_p->Mesh();\n  // Obtain local->global index mapping for current finite element space\n  const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n  // Dimension of finite element space\n  const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n  // Obtain specification for shape functions on edges\n  std::shared_ptr<const lf::uscalfe::ScalarReferenceFiniteElement<double>>\n      rsf_edge_p = fe_space_p->ShapeFunctionLayout(lf::base::RefEl::kSegment());\n\n  // Dirichlet data\n  auto mf_g = lf::mesh::utils::MeshFunctionGlobal(\n      [](coord_t x) -> double { return 0.0; });\n  // Right-hand side source function f\n  auto mf_f = lf::mesh::utils::MeshFunctionGlobal([](coord_t x) -> double {\n    return sin(M_PI * x[0]) * sin(2 * M_PI * x[1]);\n  });\n\n  // I : ASSEMBLY\n  // Matrix in triplet format holding Galerkin matrix, zero initially.\n  lf::assemble::COOMatrix<double> A(N_dofs, N_dofs);\n  // Right hand side vector, must be initialized with 0!\n  Eigen::Matrix<double, Eigen::Dynamic, 1> phi(N_dofs);\n  phi.setZero();\n\n  // I.i : Computing volume matrix for negative Laplace operator\n  // Initialize object taking care of local mass (volume) computations.\n  lf::uscalfe::LinearFELaplaceElementMatrix elmat_builder{};\n  // Invoke assembly on cells (co-dimension = 0 as first argument)\n  // Information about the mesh and the local-to-global map is passed through\n  // a Dofhandler object, argument 'dofh'. This function call adds triplets to\n  // the internal COO-format representation of the sparse matrix A.\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elmat_builder, A);\n\n  // I.ii : Computing right-hand side vector\n  lf::uscalfe::ScalarLoadElementVectorProvider<double, decltype(mf_f)>\n      elvec_builder(fe_space_p, mf_f);\n  // Invoke assembly on cells (codim == 0)\n  AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n  // I.iii : Imposing essential boundary conditions\n  // Obtain an array of boolean flags for the edges of the mesh, 'true'\n  // indicates that the edge lies on the boundary (codim = 1)\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 1)};\n  // Inspired by the example in the documentation of\n  // InitEssentialConditionFromFunction()\n  // https://craffael.github.io/lehrfempp/namespacelf_1_1uscalfe.html#a5afbd94919f0382cf3fb200c452797ac\n  // Creating a predicate that will guarantee that the computations are carried\n  // only on the exterior boundary edges of the mesh using the boundary flags\n  auto edges_predicate_Dirichlet =\n      [&bd_flags](const lf::mesh::Entity &edge) -> bool {\n    return bd_flags(edge);\n  };\n  // Determine the fixed dofs on the boundary and their values\n  // Alternative: See lecturedemoDirichlet() in\n  // https://github.com/craffael/lehrfempp/blob/master/examples/lecturedemos/lecturedemoassemble.cc\n  auto edges_flag_values_Dirichlet{\n      lf::uscalfe::InitEssentialConditionFromFunction(\n          dofh, *rsf_edge_p, edges_predicate_Dirichlet, mf_g)};\n  // Eliminate Dirichlet dofs from the linear system\n  lf::assemble::FixFlaggedSolutionCompAlt<double>(\n      [&edges_flag_values_Dirichlet](lf::assemble::glb_idx_t gdof_idx) {\n        return edges_flag_values_Dirichlet[gdof_idx];\n      },\n      A, phi);\n\n  // Assembly completed! Convert COO matrix A into CRS format using Eigen's\n  // internal conversion routines.\n  Eigen::SparseMatrix<double> A_sparse = A.makeSparse();\n\n  // II : SOLVING  THE LINEAR SYSTEM\n  // II.i : Setting up Eigen's sparse direct elimination\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(A_sparse);\n  LF_VERIFY_MSG(solver.info() == Eigen::Success, \"LU decomposition failed\");\n  // II.ii : Solving\n  discrete_solution = solver.solve(phi);\n  LF_VERIFY_MSG(solver.info() == Eigen::Success, \"Solving LSE failed\");\n\n  return discrete_solution;\n};  // solveBVP\n\nEigen::VectorXd solveGradVP(\n    const std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> &fe_space_p,\n    const Eigen::VectorXd &mu, const lf::assemble::DofHandler &vec_dofh) {\n  Eigen::VectorXd approx_grad;\n\n  // TOOLS AND DATA\n  // Pointer to current mesh\n  std::shared_ptr<const lf::mesh::Mesh> mesh_p = fe_space_p->Mesh();\n  // Dimension of finite vector elements space\n  const lf::uscalfe::size_type N_vec_dofs(vec_dofh.NumDofs());\n  // Matrix in triplet format holding the Galerkin matrix, zero initially.\n  lf::assemble::COOMatrix<double> M_COO(N_vec_dofs, N_vec_dofs);\n  // Right-hand side vector has to be set to zero initially\n  Eigen::Matrix<double, Eigen::Dynamic, 1> phi(N_vec_dofs);\n  phi.setZero();\n\n  // Initialize classes containing the information required for the\n  // local computations of the Galerkin matrix and the load vector\n  VectorProjectionMatrixProvider elMat_builder;\n  GradientProjectionVectorProvider elVec_builder(fe_space_p, mu);\n  // Compute the Galerkin matrix and load vector\n  lf::assemble::AssembleMatrixLocally(0, vec_dofh, vec_dofh, elMat_builder,\n                                      M_COO);\n  lf::assemble::AssembleVectorLocally(0, vec_dofh, elVec_builder, phi);\n\n  // Solve the linear problem\n  Eigen::SparseMatrix<double> M = M_COO.makeSparse();\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(M);\n  LF_VERIFY_MSG(solver.info() == Eigen::Success, \"LU decomposition failed\");\n  approx_grad = solver.solve(phi);\n\n  return approx_grad;\n};  // solveGradVP\n\ndouble getMeshSize(const std::shared_ptr<const lf::mesh::Mesh> &mesh_p) {\n  double mesh_size = 0.0;\n\n  // Find maximal edge length\n  double edge_length;\n  for (const lf::mesh::Entity *edge : mesh_p->Entities(1)) {\n    // Compute the length of the edge\n    auto endpoints = lf::geometry::Corners(*(edge->Geometry()));\n    edge_length = (endpoints.col(0) - endpoints.col(1)).norm();\n    if (mesh_size < edge_length) {\n      mesh_size = edge_length;\n    }\n  }\n\n  return mesh_size;\n};  // getMeshSize\n\nvoid progress_bar::write(double fraction) {\n  // clamp fraction to valid range [0,1]\n  if (fraction < 0)\n    fraction = 0;\n  else if (fraction > 1)\n    fraction = 1;\n\n  auto width = bar_width - message.size();\n  auto offset = bar_width - static_cast<unsigned>(width * fraction);\n\n  std::string sign = \"%\";\n  os << '\\r' << message;\n  os.write(full_bar.data() + offset, width);\n  os << \" [completed: \" << std::setw(3) << static_cast<int>(100 * fraction)\n     << sign + \" of meshes]\" << std::flush;\n};\n\n}  // namespace ZienkiewiczZhuEstimator\n", "meta": {"hexsha": "a3888b467963e21a775626119032f1826a8c1303", "size": 18005, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ZienkiewiczZhuEstimator/mastersolution/zienkiewiczzhuestimator.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/ZienkiewiczZhuEstimator/mastersolution/zienkiewiczzhuestimator.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/ZienkiewiczZhuEstimator/mastersolution/zienkiewiczzhuestimator.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.869047619, "max_line_length": 108, "alphanum_fraction": 0.6690919189, "num_tokens": 5344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6475334464968779}}
{"text": "/**\n * @file quic_svd_test.cpp\n * @author Siddharth Agrawal\n *\n * Test file for QUIC-SVD class.\n */\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/quic_svd/quic_svd.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nBOOST_AUTO_TEST_SUITE(QUICSVDTest);\n\nusing namespace mlpack;\nusing namespace mlpack::svd;\n\n/**\n * The reconstruction error of the obtained SVD should be small.\n */\nBOOST_AUTO_TEST_CASE(QUICSVDReconstructionError)\n{\n  // Load the dataset.\n  arma::mat dataset;\n  data::Load(\"test_data_3_1000.csv\", dataset);\n\n  // Obtain the SVD using default parameters.\n  arma::mat u, v, sigma;\n  QUIC_SVD quicsvd(dataset, u, v, sigma);\n\n  // Reconstruct the matrix using the SVD.\n  arma::mat reconstruct;\n  reconstruct = u * sigma * v.t();\n\n  // The relative reconstruction error should be small.\n  double relativeError = arma::norm(dataset - reconstruct, \"frob\") /\n                         arma::norm(dataset, \"frob\");\n  BOOST_REQUIRE_SMALL(relativeError, 1e-5);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "f859e2116a66a74525799d52d20a6ce039a3e6f4", "size": 1036, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/quic_svd_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:20.000Z", "max_issues_repo_path": "src/mlpack/tests/quic_svd_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/quic_svd_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0930232558, "max_line_length": 68, "alphanum_fraction": 0.7123552124, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6475334358779711}}
{"text": "#ifndef MULTIVARIATE_GAUSSIAN_HPP\n#define MULTIVARIATE_GAUSSIAN_HPP\n\n#include \"gtest/gtest_prod.h\"\n#include \"multinomial.hpp\"\n#include \"types.hpp\"\n\n#include <Eigen/Dense>\n#include <boost/log/trivial.hpp>\n#include <vector>\n\nnamespace FilterModel {\n\n/**\n * Represents a Multivariate Guassian distribution, especially when approximated from a multinomial.\n */\nclass MultivariateGuassian {\n   public:\n    MultivariateGuassian(const std::vector<double> mean,\n                         const std::vector<std::vector<double>> covariance);\n\n    /**\n     * Constructs a MultivariateGuassian as an approximation of a multinomial distribution.\n     */\n    static MultivariateGuassian from_multinomial(int n, const std::vector<double>& p);\n    static MultivariateGuassian from_multinomial(const Multinomial& m);\n    /**\n     * Returns the triangular covariance matrix of the guassian as a vector of vectors.\n     */\n    std::vector<std::vector<double>> get_covariance() const;\n    /**\n     * Returns the mean vector of the guassian.\n     */\n    std::vector<double> get_mean() const;\n\n    void shift_hyperplanes(std::vector<std::vector<double>>& hyperplanes);\n    double density(std::vector<double> point) const;\n\n   private:\n    Eigen::VectorXd mean;\n    Eigen::MatrixXd covariance;\n    Eigen::MatrixXd covariance_inverse;\n};\n}  // namespace FilterModel\n\n#endif", "meta": {"hexsha": "b7a715ca27a9af8ce81b750d8e9d63f22b619d2f", "size": 1348, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/multivariate_guassian.hpp", "max_stars_repo_name": "skinnersBoxy/input-filter", "max_stars_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/multivariate_guassian.hpp", "max_issues_repo_name": "skinnersBoxy/input-filter", "max_issues_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/multivariate_guassian.hpp", "max_forks_repo_name": "skinnersBoxy/input-filter", "max_forks_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3043478261, "max_line_length": 100, "alphanum_fraction": 0.7143916914, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6475334305685175}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <map>\n#include <limits>\n#include <cmath>\n#include <iomanip>\n\n#include <fire-hpp/fire.hpp>\n\n#include <boost/lexical_cast.hpp>\n\nint fired_main(std::string file_path = fire::arg({\"--file-path\",\"-f\"})) {\n    std::ifstream file(file_path, std::fstream::binary);\n\n    if (!file.good()) {\n        std::cerr << \"Couldn't open file!\" << std::endl;\n        return 1;\n    }\n    file >> std::noskipws;\n\n    std::map<char,int> freq;\n\n    uint64_t total_bytes;\n\n    char buf;\n    while (file >> buf) {\n        freq[buf]++;\n        total_bytes++;\n    }\n    file.close();\n\n    double entropy = 0;\n    for (const auto& f : freq) {\n        double p=(double)f.second/(double)total_bytes;\n        entropy-=p*log2(p);\n    }\n\n    std::cout << \"Entropy: \" << boost::lexical_cast<std::string>(entropy) << \"\\n\" << \"Metric entropy: \" << boost::lexical_cast<std::string>(entropy/total_bytes) << std::endl;\n\n    return 0;\n}\n\nFIRE(fired_main, \"Calculate file entropy\")\n", "meta": {"hexsha": "6ddf43b8e18678ae436782e7e54a2eaf8b03c1e5", "size": 1006, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "app/entropy.cxx", "max_stars_repo_name": "northy/huffman-compactor", "max_stars_repo_head_hexsha": "bcb174b0d8e6a97f5a9f6e7f6ce7e94de2ce0bbc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/entropy.cxx", "max_issues_repo_name": "northy/huffman-compactor", "max_issues_repo_head_hexsha": "bcb174b0d8e6a97f5a9f6e7f6ce7e94de2ce0bbc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/entropy.cxx", "max_forks_repo_name": "northy/huffman-compactor", "max_forks_repo_head_hexsha": "bcb174b0d8e6a97f5a9f6e7f6ce7e94de2ce0bbc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3555555556, "max_line_length": 174, "alphanum_fraction": 0.5994035785, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6475334170234034}}
{"text": "// This file contains my implementation for pose esimtation\n#include \"marker.hpp\"\n#include <Eigen/SVD>\n#include <Eigen/Dense>\n#include <glm/gtc/matrix_transform.hpp>\n#include <opencv2/opencv.hpp>\n#include <cmath>\n#include <limits>\n#include <iostream>\n\n// refer to: https://www.dropbox.com/s/qkulg4j64lyn0qa/2018_proj_geo_for_cv_projcv_assignment.pdf?dl=0\n// update computed rotation matrix\nvoid updateRotationSVD(glm::mat4x3& M)\n{\n    Eigen::Matrix3f R;\n    R << M[0][0], M[1][0], M[2][0],\n         M[0][1], M[1][1], M[2][1],\n         M[0][2], M[1][2], M[2][2];\n    Eigen::JacobiSVD<Eigen::MatrixXf> svdSolver(R, Eigen::ComputeFullV | Eigen::ComputeFullU);\n    R = svdSolver.matrixU() * svdSolver.matrixV().transpose();\n    M[0][0] = R.col(0)[0];\n    M[0][1] = R.col(0)[1];\n    M[0][2] = R.col(0)[2];\n    M[1][0] = R.col(1)[0];\n    M[1][1] = R.col(1)[1];\n    M[1][2] = R.col(1)[2];\n    M[2][0] = R.col(2)[0];\n    M[2][1] = R.col(2)[1];\n    M[2][2] = R.col(2)[2];\n}\n\n// refer to https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.895.2324&rep=rep1&type=pdf\n// update to Tait-Bryan rotation matrix\nvoid updateRotationTaitBryan(glm::mat4x3& M)\n{\n    float theta = -std::asin(M[2][0]);\n    float thetaS = std::sin(theta);\n    float thetaC = std::cos(theta);\n    float psi = std::asin(M[1][0] / thetaC);\n    float psiS = std::sin(psi);\n    float psiC = std::cos(psi);\n    float phi = std::asin(M[2][1] / thetaC);\n    float phiS = std::sin(phi);\n    float phiC = std::cos(phi);\n\n    M[0][0] = thetaC * psiC;\n    M[1][0] = thetaC * psiS;\n    M[2][0] = -thetaS;\n\n    M[0][1] = phiS * thetaS * psiC - phiC * psiS;\n    M[1][1] = phiS * thetaS * psiS + phiC * psiC;\n    M[2][1] = phiS * thetaC;\n\n    M[0][2] = phiC * thetaS * psiC + phiS * psiS;\n    M[1][2] = phiC * thetaS * psiS - phiS * psiC;\n    M[2][2] = phiC * thetaC;\n}\n\n// refer to: https://stackoverflow.com/questions/12463487/obtain-rotation-axis-from-rotation-matrix-and-translation-vector-in-opencv\nvoid updateRotationEuclidean(glm::mat4x3& M)\n{\n    // obtain rotation angle\n    float angle = std::acos(0.5f * (M[0][0] + M[1][1] + M[2][2] - 1.0f));\n    // obtain axis\n    glm::vec3 axis = glm::vec3(M[1][2] - M[2][1], M[2][0] - M[0][2], M[0][1] - M[1][0]);\n    axis = glm::normalize(axis);\n    glm::mat4 rot = glm::rotate(glm::mat4(1.0f), glm::degrees(angle), axis);\n    M[0][0] = rot[0][0]; M[1][0] = rot[1][0]; M[2][0] = rot[2][0];\n    M[0][1] = rot[0][1]; M[1][1] = rot[1][1]; M[2][1] = rot[2][1];\n    M[0][2] = rot[0][2]; M[1][2] = rot[1][2]; M[2][2] = rot[2][2];\n}\n\n// compute reprojection error\nfloat reprojectionError(\n    const glm::mat3& cameraK, const glm::mat4x3& M,\n    const std::vector<glm::vec2>& objPoints,\n    const std::vector<glm::vec2>& imgPoints\n)\n{\n    float error = 0.0f;\n    for(size_t i = 0; i < 4; i++)\n    {\n        // auto projected = M * glm::vec4(objPoints[i], 0.0f, 1.0f);\n        auto projected = cameraK * M * glm::vec4(objPoints[i], 0.0f, 1.0f);\n        float dx = projected.x - imgPoints[i].x;\n        float dy = projected.y - imgPoints[i].y;\n        error += dx * dx + dy * dy;\n    }\n    return std::sqrt(error * 0.125f);\n}\n\n// validate solution based on Zhang's method\nbool validateSolutionZhang(\n    const Eigen::Vector3f& tstar, const Eigen::Vector3f& nstar, const Eigen::MatrixXf& H,\n    const Eigen::MatrixXf& mstarT, Eigen::Matrix3f& outR, Eigen::Vector3f& outT\n)\n{\n    // prepare rotation matrix and translation vector\n    // R = H (I + t* n^T)^-1\n    outR = H * (Eigen::Matrix3f::Identity() + tstar * nstar.transpose()).inverse();\n    if(outR.determinant() < 0.0f)\n    {\n        // flip surface\n        outR *= -1.0f;\n    }\n    outT = outR * tstar;\n    // 1 + n^T R^T t\n    float positive = 1.0f + (nstar.transpose() * outR.transpose() * outT)[0];\n    if(positive <= 0.0f)\n        return false;\n    // m*^T n*\n    Eigen::Vector4f positives = mstarT * nstar;\n    if(positives[0] <= 0.0f || positives[1] <= 0.0f ||\n       positives[2] <= 0.0f || positives[3] <= 0.0f)\n       return false;\n    return true;\n}\n\n// refer to https://hal.inria.fr/inria-00174036v3/document\n// refer to https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/homography_decomp.cpp#L217\n// decompose homography matrix\nvoid decomposeHomoMatrixZhang(\n    const glm::mat3& cameraK, const glm::mat3& cameraInvK, const glm::mat3x4& mstarTransposed,\n    const glm::mat3& G, const std::vector<glm::vec2>& objPoints,\n    const std::vector<glm::vec2>& imgPoints, glm::mat4x3& outputM)\n{\n    // normalize H\n    // glm::mat3 hHat = cameraInvK * G * cameraK;\n    glm::mat3 hHat = cameraInvK * G;\n    // retrieve homography matrix H\n    Eigen::Matrix<float, 3, 3> H;\n    H << hHat[0][0], hHat[1][0], hHat[2][0],\n         hHat[0][1], hHat[1][1], hHat[2][1],\n         hHat[0][2], hHat[1][2], hHat[2][2];\n    Eigen::EigenSolver<Eigen::MatrixXf> eigenSolver;\n    // eigenSolver.compute(H, false);\n    // float gamma = eigenSolver.eigenvalues().real()[1];\n    // H = H / gamma; // scale by lambda2\n    // H^TH = V A V^T and solve for eigenvalues and eigenvectors\n    // H = H.transpose() * H;\n    eigenSolver.compute(H, true);\n    Eigen::VectorXf lambdas = eigenSolver.eigenvalues().real();\n    Eigen::MatrixXf vs = eigenSolver.eigenvectors().real();\n    // verify the eigenvectors\n    if (vs.rows() < 3 || vs.cols() < 3) return;\n    float lambda1 = lambdas[0];\n    float lambda3 = lambdas[2];\n    // float lambda1 = lambdas[0] >= lambdas[2] ? lambdas[0] : lambdas[2];\n    // float lambda3 = lambdas[0] >= lambdas[2] ? lambdas[2] : lambdas[0];\n    float lambda1x3 = lambda1 * lambda3;\n    float lambda1m3 = lambda1 - lambda3;\n    float lambda1m3_2 = lambda1m3 * lambda1m3;\n    // prepare zeta\n    float tmp1 = 1.0f / (2.0f * lambda1x3);\n    float tmp2 = std::sqrt(std::abs(1.0f + 4.0f * lambda1x3 / lambda1m3_2));\n    float tmp1x2 = tmp1 * tmp2;\n    float zeta1 = -tmp1 + tmp1x2;\n    float zeta3 = -tmp1 - tmp1x2;\n    float zeta1_2 = zeta1 * zeta1;\n    float zeta3_2 = zeta3 * zeta3;\n    float zeta1m3 = zeta1 - zeta3;\n    float zeta1m3_inv = 1.0f / zeta1m3;\n    // compute norms of v'1,3\n    float nv1p = std::sqrt(std::abs(zeta1_2 * lambda1m3_2 + 2.0f * zeta1 * (lambda1x3 - 1.0f) + 1.0f));\n    float nv3p = std::sqrt(std::abs(zeta3_2 * lambda1m3_2 + 2.0f * zeta3 * (lambda1x3 - 1.0f) + 1.0f));\n    // compute v1' and v3'\n    Eigen::Vector3f v1p, v3p;\n    v1p << vs.col(0)[0]*nv1p, vs.col(0)[1]*nv1p, vs.col(0)[2]*nv1p;\n    v3p << vs.col(2)[0]*nv3p, vs.col(2)[1]*nv3p, vs.col(2)[2]*nv3p;\n    // 8 solutions in total:\n    Eigen::Vector3f tstar[4], nstar[4];\n    // solution 1\n    tstar[0] =  (v1p - v3p) * zeta1m3_inv;\n    tstar[1] = -(v1p - v3p) * zeta1m3_inv;\n    nstar[0] =  (zeta1 * v3p - zeta3 * v1p) * zeta1m3_inv;\n    nstar[1] = -(zeta1 * v3p - zeta3 * v1p) * zeta1m3_inv;\n    // solution 2\n    tstar[2] =  (v1p + v3p) * zeta1m3_inv;\n    tstar[3] = -(v1p + v3p) * zeta1m3_inv;\n    nstar[2] =  (zeta1 * v3p + zeta3 * v1p) * zeta1m3_inv;\n    nstar[3] = -(zeta1 * v3p + zeta3 * v1p) * zeta1m3_inv;\n    // prepare mstar transposed (for validation)\n    Eigen::Matrix<float, 4, 3> mstarT;\n    mstarT << mstarTransposed[0][0], mstarTransposed[1][0], mstarTransposed[2][0],\n              mstarTransposed[0][1], mstarTransposed[1][1], mstarTransposed[2][1],\n              mstarTransposed[0][2], mstarTransposed[1][2], mstarTransposed[2][2],\n              mstarTransposed[0][3], mstarTransposed[1][3], mstarTransposed[2][3];\n    // validate solutions, collect the first one\n    Eigen::Matrix3f R; // rotation\n    Eigen::Vector3f T; // translation\n    std::vector<glm::mat4x3> candidates;\n    for(int i = 0; i < 2; i++)\n    {\n        for(int j = 0; j < 2; j++)\n        {\n            if(validateSolutionZhang(tstar[i], nstar[j], H, mstarT, R, T))\n            {\n                candidates.push_back(glm::mat4x3(\n                    glm::vec3(R.col(0)[0], R.col(0)[1], R.col(0)[2]),\n                    glm::vec3(R.col(1)[0], R.col(1)[1], R.col(1)[2]),\n                    glm::vec3(R.col(2)[0], R.col(2)[1], R.col(2)[2]),\n                    glm::vec3(T[0], T[1], T[2])\n                ));\n            }\n            if(validateSolutionZhang(tstar[i+2], nstar[j+2], H, mstarT, R, T))\n            {\n                candidates.push_back(glm::mat4x3(\n                    glm::vec3(R.col(0)[0], R.col(0)[1], R.col(0)[2]),\n                    glm::vec3(R.col(1)[0], R.col(1)[1], R.col(1)[2]),\n                    glm::vec3(R.col(2)[0], R.col(2)[1], R.col(2)[2]),\n                    glm::vec3(T[0], T[1], T[2])\n                ));\n            }\n        }\n    }\n\n    if(candidates.size() == 0)\n    {\n        outputM = glm::mat4x3(0.0f);\n        return;\n    }\n    // compute reprojection error for each\n    float minError = std::numeric_limits<float>::max();\n    size_t selectedIdx = 0;\n    for(size_t i = 0; i < candidates.size(); i++)\n    {\n        float error = reprojectionError(cameraK, candidates[i], objPoints, imgPoints);\n        if(error < minError)\n        {\n            minError = error;\n            selectedIdx = i;\n        }\n    }\n    // std::cout << \"Reprojection Error: \" << minError << std::endl;\n    // set pose matrix\n    outputM = candidates[selectedIdx];\n}\n\n// refer to: https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384\n// undistort image points\nvoid undistortPoints(\n    const glm::mat3& cameraK, const glm::vec3& cameraDistK, const glm::vec2& cameraDistP,\n    glm::vec2& p1, glm::vec2& p2, glm::vec2& p3, glm::vec2& p4)\n{\n    glm::vec2 src[4] = {p1, p2, p3, p4};\n    glm::vec2 dst[4];\n    float fx = cameraK[0][0], fy = cameraK[1][1];\n    float invfx = 1.0f / fx, invfy = 1.0f / fy;\n    float cx = cameraK[2][0], cy = cameraK[2][1];\n    // prepare coefficient K\n    // k1,k2,p1,p2,k3\n    float k[5] = {cameraDistK.x, cameraDistK.y, cameraDistP.x, cameraDistP.y, cameraDistK.z};\n    for(int i = 0; i < 4; i++)\n    {\n        float x = src[i].x, y = src[i].y;\n        float x0, y0, u, v;\n        u = x;\n        v = y;\n        x = x0 = (x - cx) * invfx;\n        y = y0 = (y - cy) * invfy;\n        // init error\n        float error = std::numeric_limits<float>::max();\n        // iteratively reduce distortion error\n        const int MAX_ITER = 10;\n        const float EPS = 0.0005f;\n        int j = 0;\n        for(; j < MAX_ITER; j++)\n        {\n            if(error < EPS) break;\n            float r2 = x*x + y*y;\n            float icdist = 1.0f / (\n                1.0f + ((k[4] * r2 + k[1]) * r2 + k[0]) * r2\n            );\n            // if distortion is negative, reset\n            if(icdist < 0.0f)\n            {\n                x = (u - cx) * invfx;\n                y = (v - cy) * invfy;\n                break;\n            }\n            float deltaX = 2.0f * k[2] * x * y + k[3] * (r2 + 2.0f * x * x);\n            float deltaY = k[2] * (r2 + 2 * y * y) + 2.0f * k[3] * x * y;\n            x = (x0 - deltaX) * icdist;\n            y = (y0 - deltaY) * icdist;\n            // compute error\n            {\n                float r4, r6;\n                float a1, a2, a3;\n                float cdist;\n                float xd, yd;\n                r2 = x * x + y * y;\n                r4 = r2 * r2;\n                r6 = r4 * r2;\n                a1 = 2.0f * x * y;\n                a2 = r2 + 2.0f * x * x;\n                a3 = r2 + 2.0f * y * y;\n                cdist = 1.0f + k[0] * r2 + k[1] * r4 + k[4] * r6;\n                xd = x * cdist + k[2] * a1 + k[3] * a2;\n                yd = y * cdist + k[2] * a3 + k[3] * a1;\n                float xproj, yproj;\n                xproj = xd * fx + cx;\n                yproj = yd * fy + cy;\n                error = std::sqrt((xproj - u) * (xproj - u) + (yproj - v) * (yproj - v));\n            }\n        }\n        // std::cout << j << \",\" << error << std::endl;\n        dst[i].x = x * fx + cx;\n        dst[i].y = y * fy + cy;\n    }\n    // retrieve new positions\n    p1 = dst[0];\n    p2 = dst[1];\n    p3 = dst[2];\n    p4 = dst[3];\n}\n\n// refer to book: \"Augmented Reality: Principles and Practice\"\n// decompose homography matrix\nvoid decomposeHomoMatrixARBook(\n    const glm::mat3& cameraK, const glm::mat3& cameraInvK, glm::mat3 H, glm::mat4x3& outputM\n)\n{\n    H = cameraInvK * H;\n    // recover rotation matrix and translation vector\n    float d = 1.0f / std::sqrt(glm::length(H[0]) * glm::length(H[1]));\n    // set translation\n    outputM[3] = d * H[2];\n    glm::vec3 h1 = H[0];\n    glm::vec3 h2 = H[1];\n    glm::vec3 h12 = glm::normalize(h1 + h2);\n    glm::vec3 h21 = glm::normalize(glm::cross(h12, glm::cross(h1, h2)));\n    // set rotations\n    d = 1.0f / std::sqrt(2.0f);\n    outputM[0] = (h12 + h21) * d; // set R1\n    outputM[1] = (h12 - h21) * d; // set R2\n    outputM[2] = glm::cross(outputM[0], outputM[1]); // set R3\n}\n\n// refer to https://stackoverflow.com/questions/8927771/computing-camera-pose-with-homography-matrix-based-on-4-coplanar-points\n// decompose homography matrix\nvoid decomposeHomoMatrixInternet(\n    const glm::mat3& cameraK, const glm::mat3& cameraInvK, glm::mat3 H, glm::mat4x3& outputM\n)\n{\n    H = cameraInvK * H;\n    float tnorm = 2.0f / (glm::length(H[0]) + glm::length(H[1]));\n    // set translation\n    outputM[3] = tnorm * H[2];\n    // set rotations\n    outputM[0] = glm::normalize(H[0]);\n    outputM[1] = glm::normalize(H[1]);\n    outputM[2] = glm::cross(outputM[0], outputM[1]);\n}\n\n// refer to https://gist.github.com/inspirit/740979/97f54a63eb5f61f8f2eb578d60eb44839556ff3f\nvoid decomposeHomoMatrixInternet2(\n    const glm::mat3& cameraK, const glm::mat3& cameraInvK, glm::mat3 H, glm::mat4x3& outputM\n)\n{\n    H = cameraInvK * H;\n    float lambda = 1.0f / glm::length(H[0]);\n    // set translation\n    outputM[3] = lambda * H[2];\n    // set rotations\n    outputM[0] = lambda * H[0];\n    outputM[1] = lambda * H[1];\n    outputM[2] = glm::cross(outputM[0], outputM[1]);\n}\n\n\n// refer to https://courses.cs.duke.edu//spring22/compsci527/notes/n_10_reconstruction.pdf\n// decompose homography matrix\nvoid decomposeHomoMatrixDuke(\n    const glm::mat3& cameraK, const glm::mat3& cameraInvK,\n    const std::vector<glm::vec2>& objPoints, const std::vector<glm::vec2>& imgPoints,\n    glm::mat3 H, glm::mat4x3& outputM\n)\n{\n    H = cameraInvK * H;\n    // prepare E\n    Eigen::Matrix<float, 3, 3> E;\n    E << H[0][0], H[1][0], H[2][0],\n         H[0][1], H[1][1], H[2][1],\n         H[0][2], H[1][2], H[2][2];\n    // decompose E\n    Eigen::JacobiSVD<Eigen::MatrixXf> svdSolver;\n    svdSolver.compute(E, Eigen::ComputeFullV | Eigen::ComputeFullU);\n    // estimate two possible t\n    auto& U = svdSolver.matrixU();\n    auto& V = svdSolver.matrixV();\n    Eigen::Vector3f T1 =  V.col(2);\n    Eigen::Vector3f T2 = -V.col(2);\n    // prepare alpha, beta\n    Eigen::Matrix3f ab1 = U.col(0) * V.col(0).transpose();\n    Eigen::Matrix3f ab2 = U.col(1) * V.col(1).transpose();\n    Eigen::Matrix3f ab3 = U.col(2) * V.col(2).transpose();\n    // compute Q\n    Eigen::Matrix3f Q1 = ab1 + ab2 + ab3;\n    Eigen::Matrix3f Q2 = ab1 + ab2 - ab3;\n    // compute R\n    Eigen::Matrix3f R1 = Q1 * Q1.determinant();\n    Eigen::Matrix3f R2 = Q2 * Q2.determinant();\n    std::vector<glm::mat4x3> candidates;\n    candidates.push_back(glm::mat4x3(\n        glm::vec3(R1.col(0)[0], R1.col(0)[1], R1.col(0)[2]),\n        glm::vec3(R1.col(1)[0], R1.col(1)[1], R1.col(1)[2]),\n        glm::vec3(R1.col(2)[0], R1.col(2)[1], R1.col(2)[2]),\n        glm::vec3(T1[0], T1[1], T1[2])\n    ));\n    candidates.push_back(glm::mat4x3(\n        glm::vec3(R1.col(0)[0], R1.col(0)[1], R1.col(0)[2]),\n        glm::vec3(R1.col(1)[0], R1.col(1)[1], R1.col(1)[2]),\n        glm::vec3(R1.col(2)[0], R1.col(2)[1], R1.col(2)[2]),\n        glm::vec3(T2[0], T2[1], T2[2])\n    ));\n    candidates.push_back(glm::mat4x3(\n        glm::vec3(R2.col(0)[0], R2.col(0)[1], R2.col(0)[2]),\n        glm::vec3(R2.col(1)[0], R2.col(1)[1], R2.col(1)[2]),\n        glm::vec3(R2.col(2)[0], R2.col(2)[1], R2.col(2)[2]),\n        glm::vec3(T1[0], T1[1], T1[2])\n    ));\n    candidates.push_back(glm::mat4x3(\n        glm::vec3(R2.col(0)[0], R2.col(0)[1], R2.col(0)[2]),\n        glm::vec3(R2.col(1)[0], R2.col(1)[1], R2.col(1)[2]),\n        glm::vec3(R2.col(2)[0], R2.col(2)[1], R2.col(2)[2]),\n        glm::vec3(T2[0], T2[1], T2[2])\n    ));\n    float minError = std::numeric_limits<float>::max();\n    size_t selectedIdx = 0;\n    for(size_t i = 0; i < candidates.size(); i++)\n    {\n        float error = reprojectionError(cameraK, candidates[i], objPoints, imgPoints);\n        if(error < minError)\n        {\n            minError = error;\n            selectedIdx = i;\n        }\n    }\n    // set pose matrix\n    outputM = candidates[selectedIdx];\n}\n\n// refer to https://stanford.edu/class/ee267/notes/ee267_notes_tracking.pdf\n// decompose homography matrix\nvoid decomposeHomoMatrixStanford(\n    const glm::mat3& cameraK, const glm::mat3& cameraInvK, glm::mat3 H, glm::mat4x3& outputM\n)\n{\n    H = cameraInvK * H;\n    float normCol0 = glm::length(H[0]);\n    float normCol1 = glm::length(H[1]);\n    float s = 2.0f / (normCol0 + normCol1);\n    // set translation\n    outputM[3] = s * H[2];\n    // set rotations\n    outputM[0] = H[0] / normCol0;\n    outputM[1] = H[1] - outputM[0] * glm::dot(outputM[0], H[1]);\n    outputM[1] = glm::normalize(outputM[1]);\n    outputM[2] = glm::cross(outputM[0], outputM[1]);\n}\n\n// scale the estimated projection matrix\nfloat scalePoseM(glm::mat4x3& M)\n{\n    float scale = std::abs(M[3][2]);\n    M /= scale;\n    return scale;\n}\n\nvoid testPoseM(const glm::mat3& cameraK, glm::mat4x3& M, const glm::vec2& q)\n{\n    auto tmp = cameraK * M * glm::vec4(q, 0.0f, 1.0f);\n    std::cout << tmp.x << \",\" << tmp.y << \",\" << tmp.z << std::endl;\n}\n\n// estimate pose from homography (SVD method)\nvoid Marker::estimatePoseSVD(\n    const glm::mat3& cameraK, const glm::mat3& cameraInvK,\n    const glm::vec3& cameraDistK, const glm::vec2& cameraDistP\n)\n{\n    if(!_new_marker) return;\n    if(_marker_borderp1p2.x <= 0.0f)\n    {\n        _poseM = glm::mat4x3(0.0f);\n        _poseMRefined = glm::mat4x3(0.0f);\n        return;\n    }\n    // prepare p\n    glm::vec2 p1 = glm::vec2(_marker_borderp1p2.x, _marker_borderp1p2.y);\n    glm::vec2 p2 = glm::vec2(_marker_borderp1p2.z, _marker_borderp1p2.w);\n    glm::vec2 p3 = glm::vec2(_marker_borderp3p4.x, _marker_borderp3p4.y);\n    glm::vec2 p4 = glm::vec2(_marker_borderp3p4.z, _marker_borderp3p4.w);\n    // undistort points\n    undistortPoints(\n        cameraK, cameraDistK, cameraDistP,\n        p1, p2, p3, p4\n    );\n    // glm::mat3x4 mstarT = glm::transpose(\n    //     cameraInvK * glm::mat4x3(\n    //         glm::vec3(p1, 1.0f),\n    //         glm::vec3(p2, 1.0f),\n    //         glm::vec3(p3, 1.0f),\n    //         glm::vec3(p4, 1.0f)\n    //     )\n    // );\n    // prepare q\n    // const glm::vec2 q1 = glm::vec2(0.0f, 0.0f);\n    // const glm::vec2 q2 = glm::vec2(0.0f, 1.0f);\n    // const glm::vec2 q4 = glm::vec2(1.0f, 0.0f);\n    // const glm::vec2 q3 = glm::vec2(1.0f, 1.0f);\n    const glm::vec2 q1 = glm::vec2(-1.0f, -1.0f);\n    const glm::vec2 q2 = glm::vec2(-1.0f,  1.0f);\n    const glm::vec2 q3 = glm::vec2( 1.0f, -1.0f);\n    const glm::vec2 q4 = glm::vec2( 1.0f,  1.0f);\n    // set up matrix A\n    Eigen::Matrix<float, 8, 9> A;\n    A << q1.x, q1.y, 1.0f, 0.0f, 0.0f, 0.0f, -p1.x*q1.x, -p1.x*q1.y, -p1.x,\n         0.0f, 0.0f, 0.0f, q1.x, q1.y, 1.0f, -p1.y*q1.x, -p1.y*q1.y, -p1.y,\n\n         q2.x, q2.y, 1.0f, 0.0f, 0.0f, 0.0f, -p2.x*q2.x, -p2.x*q2.y, -p2.x,\n         0.0f, 0.0f, 0.0f, q2.x, q2.y, 1.0f, -p2.y*q2.x, -p2.y*q2.y, -p2.y,\n\n         q3.x, q3.y, 1.0f, 0.0f, 0.0f, 0.0f, -p3.x*q3.x, -p3.x*q3.y, -p3.x,\n         0.0f, 0.0f, 0.0f, q3.x, q3.y, 1.0f, -p3.y*q3.x, -p3.y*q3.y, -p3.y,\n\n         q4.x, q4.y, 1.0f, 0.0f, 0.0f, 0.0f, -p4.x*q4.x, -p4.x*q4.y, -p4.x,\n         0.0f, 0.0f, 0.0f, q4.x, q4.y, 1.0f, -p4.y*q4.x, -p4.y*q4.y, -p4.y;\n    // solve SVD for A\n    Eigen::JacobiSVD<Eigen::MatrixXf> svdSolver(A, Eigen::ComputeFullV);\n    auto& matrixV = svdSolver.matrixV();\n    auto& h = matrixV.col(matrixV.cols() - 1);\n    glm::mat3 H = glm::mat3(\n        glm::vec3(h[0], h[3], h[6]),\n        glm::vec3(h[1], h[4], h[7]),\n        glm::vec3(h[2], h[5], h[8])\n    );\n    std::vector<glm::vec2> objPoints = {q1, q2, q3, q4};\n    std::vector<glm::vec2> imgPoints = {p1, p2, p3, p4};\n    // decomposeHomoMatrixZhang(cameraK, cameraInvK, mstarT, H, objPoints, imgPoints, _poseM);\n    // decomposeHomoMatrixARBook(cameraK, cameraInvK, H, _poseM);\n    decomposeHomoMatrixInternet(cameraK, cameraInvK, H, _poseM);\n    // decomposeHomoMatrixInternet2(cameraK, cameraInvK, H, _poseM);\n    // decomposeHomoMatrixStanford(cameraK, cameraInvK, H, _poseM);\n    _err_scale = scalePoseM(_poseM);\n    refinePoseM(cameraInvK, objPoints, imgPoints);\n    _err_reproj = reprojectionError(cameraK, _poseMRefined, objPoints, imgPoints);\n}\n\n// reference: https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/\n// estimate pose from homography (linear equation method)\nvoid Marker::estimatePoseLinear(\n    const glm::mat3& cameraK, const glm::mat3& cameraInvK,\n    const glm::vec3& cameraDistK, const glm::vec2& cameraDistP\n)\n{\n    if(!_new_marker) return;\n    if(_marker_borderp1p2.x <= 0.0f)\n    {\n        _poseM = glm::mat4x3(0.0f);\n        _poseMRefined = glm::mat4x3(0.0f);\n        return;\n    }\n    // prepare p\n    glm::vec2 p1 = glm::vec2(_marker_borderp1p2.x, _marker_borderp1p2.y);\n    glm::vec2 p2 = glm::vec2(_marker_borderp1p2.z, _marker_borderp1p2.w);\n    glm::vec2 p3 = glm::vec2(_marker_borderp3p4.x, _marker_borderp3p4.y);\n    glm::vec2 p4 = glm::vec2(_marker_borderp3p4.z, _marker_borderp3p4.w);\n    // undistort points\n    undistortPoints(\n        cameraK, cameraDistK, cameraDistP,\n        p1, p2, p3, p4\n    );\n    // prepare q\n    static glm::vec2 q1 = glm::vec2(-1.0f, -1.0f);\n    static glm::vec2 q2 = glm::vec2(-1.0f,  1.0f);\n    static glm::vec2 q3 = glm::vec2( 1.0f, -1.0f);\n    static glm::vec2 q4 = glm::vec2( 1.0f,  1.0f);\n    // set up matrix A\n    Eigen::Matrix<float, 8, 8> A;\n    A << q1.x, q1.y, 1.0f, 0.0f, 0.0f, 0.0f, -p1.x*q1.x, -p1.x*q1.y,\n         0.0f, 0.0f, 0.0f, q1.x, q1.y, 1.0f, -p1.y*q1.x, -p1.y*q1.y,\n\n         q2.x, q2.y, 1.0f, 0.0f, 0.0f, 0.0f, -p2.x*q2.x, -p2.x*q2.y,\n         0.0f, 0.0f, 0.0f, q2.x, q2.y, 1.0f, -p2.y*q2.x, -p2.y*q2.y,\n\n         q3.x, q3.y, 1.0f, 0.0f, 0.0f, 0.0f, -p3.x*q3.x, -p3.x*q3.y,\n         0.0f, 0.0f, 0.0f, q3.x, q3.y, 1.0f, -p3.y*q3.x, -p3.y*q3.y,\n\n         q4.x, q4.y, 1.0f, 0.0f, 0.0f, 0.0f, -p4.x*q4.x, -p4.x*q4.y,\n         0.0f, 0.0f, 0.0f, q4.x, q4.y, 1.0f, -p4.y*q4.x, -p4.y*q4.y;\n\n    Eigen::Vector<float, 8> b;\n    b << p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y;\n    auto h = A.colPivHouseholderQr().solve(b);\n    glm::mat3 H = glm::mat3(\n        glm::vec3(h[0], h[3], h[6]),\n        glm::vec3(h[1], h[4], h[7]),\n        glm::vec3(h[2], h[5], 1.0f)\n    );\n\n    std::vector<glm::vec2> objPoints = {q1, q2, q3, q4};\n    std::vector<glm::vec2> imgPoints = {p1, p2, p3, p4};\n    // decomposeHomoMatrixStanford(cameraK, cameraInvK, H, _poseM);\n    // decomposeHomoMatrixARBook(cameraK, cameraInvK, H, _poseM);\n    decomposeHomoMatrixInternet(cameraK, cameraInvK, H, _poseM);\n    // decomposeHomoMatrixInternet2(cameraK, cameraInvK, H, _poseM);\n    // decomposeHomoMatrixDuke(cameraK, cameraInvK, objPoints, imgPoints, H, _poseM);\n    _err_scale = scalePoseM(_poseM);\n    refinePoseM(cameraInvK, objPoints, imgPoints);\n    _err_reproj = reprojectionError(cameraK, _poseMRefined, objPoints, imgPoints);\n}\n\n// use opencv as reference\n// estimate pose (OpenCV method)\nvoid Marker::estimatePoseOpenCV(\n    const glm::mat3& cameraK, const glm::mat3& cameraInvK,\n    const glm::vec3& cameraDistK, const glm::vec2& cameraDistP\n)\n{\n    if(!_new_marker) return;\n    if(_marker_borderp1p2.x <= 0.0f)\n    {\n        _poseM = glm::mat4x3(0.0f);\n        _poseMRefined = glm::mat4x3(0.0f);\n        return;\n    }\n    std::vector<cv::Point2d> imgPoints = {\n        cv::Point2d(_marker_borderp1p2.x, _marker_borderp1p2.y),\n        cv::Point2d(_marker_borderp1p2.z, _marker_borderp1p2.w),\n        cv::Point2d(_marker_borderp3p4.x, _marker_borderp3p4.y),\n        cv::Point2d(_marker_borderp3p4.z, _marker_borderp3p4.w),\n    };\n    std::vector<cv::Point3d> objPoints = {\n        cv::Point3d(-1.0, -1.0, 0.0),\n        cv::Point3d(-1.0,  1.0, 0.0),\n        cv::Point3d( 1.0, -1.0, 0.0),\n        cv::Point3d( 1.0,  1.0, 0.0),\n    };\n    // std::vector<cv::Point3d> objPoints = {\n    cv::Mat3d cameraMat = (\n        cv::Mat_<cv::Vec<double,3>>(3,3) << cameraK[0][0], cameraK[1][0], cameraK[2][0],\n            cameraK[0][1], cameraK[1][1], cameraK[2][1],\n            cameraK[0][2], cameraK[1][2], cameraK[2][2]\n    );\n    std::vector<double> cameraDist = {\n        cameraDistK.x, cameraDistK.y, cameraDistP.x, cameraDistP.y, cameraDistK.z\n    };\n    cv::Mat rvec, tvec;\n    if(!cv::solvePnP(objPoints, imgPoints, cameraMat, cameraDist, rvec, tvec, false, cv::SOLVEPNP_IPPE))\n    {\n        _poseM = glm::mat4x3(0.0f);\n        return;\n    }\n    cv::Mat rotMat;\n    cv::Rodrigues(rvec, rotMat);\n    rotMat.convertTo(rotMat, CV_32F);\n    tvec.convertTo(tvec, CV_32F);\n    _poseM = glm::mat4x3(\n        glm::vec3(rotMat.at<float>(0,0), rotMat.at<float>(1,0), rotMat.at<float>(2,0)),\n        glm::vec3(rotMat.at<float>(0,1), rotMat.at<float>(1,1), rotMat.at<float>(2,1)),\n        glm::vec3(rotMat.at<float>(0,2), rotMat.at<float>(1,2), rotMat.at<float>(2,2)),\n        glm::vec3(tvec.at<float>(0,0), tvec.at<float>(0,1), tvec.at<float>(0,2))\n    );\n    _err_scale = scalePoseM(_poseM);\n}", "meta": {"hexsha": "5c8238dbf5c74c29334a6ef5160d7361446d4902", "size": 25376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PC/src/markerpose.cpp", "max_stars_repo_name": "teamclouday/Marker", "max_stars_repo_head_hexsha": "3dc0e48db1a2c297d7962dd6280078e57409b2cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PC/src/markerpose.cpp", "max_issues_repo_name": "teamclouday/Marker", "max_issues_repo_head_hexsha": "3dc0e48db1a2c297d7962dd6280078e57409b2cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PC/src/markerpose.cpp", "max_forks_repo_name": "teamclouday/Marker", "max_forks_repo_head_hexsha": "3dc0e48db1a2c297d7962dd6280078e57409b2cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1021021021, "max_line_length": 132, "alphanum_fraction": 0.5614360025, "num_tokens": 9801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.6474485034386046}}
{"text": "#include <eigen3/Eigen/Dense>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n#include <iostream>\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n#include \"ros/ros.h\"\n#include \"std_msgs/Float64.h\"\n#include \"std_msgs/Float64MultiArray.h\"\n#include \"sensor_msgs/JointState.h\"\n#include \"gazebo_msgs/LinkStates.h\"\n#include \"define.h\"\n\n#include <typeinfo>\n\n#define DESIRED_VEL 40  // RW_qdot_des [rad/s]\n#define NUM_OF_MEASUREMENTS 1000\n\ntypedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> Matrix;\n\ntemplate<typename MatType>\nusing PseudoInverseType = Eigen::Matrix<typename MatType::Scalar, MatType::ColsAtCompileTime, MatType::RowsAtCompileTime>;\n\ntemplate<typename MatType>\nPseudoInverseType<MatType> pseudoInverse(const MatType &a, double epsilon = std::numeric_limits<double>::epsilon())\n{\n    using WorkingMatType = Eigen::Matrix<typename MatType::Scalar, Eigen::Dynamic, Eigen::Dynamic, 0, MatType::MaxRowsAtCompileTime, MatType::MaxColsAtCompileTime>;\n    Eigen::BDCSVD<WorkingMatType> svd(a, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    svd.setThreshold(epsilon*std::max(a.cols(), a.rows()));\n    Eigen::Index rank = svd.rank();\n    Eigen::Matrix<typename MatType::Scalar, Eigen::Dynamic, MatType::RowsAtCompileTime,\n    0, Eigen::BDCSVD<WorkingMatType>::MaxDiagSizeAtCompileTime, MatType::MaxRowsAtCompileTime>\n    tmp = svd.matrixU().leftCols(rank).adjoint();\n    tmp = svd.singularValues().head(rank).asDiagonal().inverse() * tmp;\n    return svd.matrixV().leftCols(rank) * tmp;\n}\n\nbool reachedVel = false;\n\nfloat q1;       // angle of first joint [rad]\nfloat q2;       // angle of second joint [rad]\nfloat q1dot;    // rate of first joint [rad/s]\nfloat q2dot;    // rate of second joint [rad/s]\nfloat omega0;   // base angular velocity [rad/s]\nfloat RW_vel;   // reaction wheel velocity [rad/s]\n\nvoid velocityCheckCallback(const sensor_msgs::JointState::ConstPtr& msg) {\n    \n    q1      = msg->position[0];\n    q2      = msg->position[1];\n    q1dot   = msg->velocity[0];\n    q2dot   = msg->velocity[1];\n    RW_vel  = msg->velocity[4];\n    \n    // ROS_INFO(\"RW_vel: %.5f | q1: %.5f | q2: %.5f | q1dot: %.5f | q2dot: %.5f\", RW_vel, q1, q2, q1dot, q2dot);\n\n    if (!reachedVel && RW_vel >= DESIRED_VEL)\n        reachedVel = true;\n    else if (reachedVel) {\n        // ROS_INFO(\"Measurement number: %d\");\n    }\n}\n\nvoid positionCheckCallback(const gazebo_msgs::LinkStates::ConstPtr& msg) {\n\n    omega0 = msg->twist[3].angular.z;\n    // ROS_INFO(\"angular twist z: %.5f\", omega0);\n}\n\n\nint main(int argc, char **argv) {\n\n    // calculations\n    double EulerConstant = std::exp(1.0);\n\n    double M   = M0+M1+M2;\n    double I0  = ((double)1/2)*(M0*pow(RH, (double)2));\n    double I1  = 3.46*pow(EulerConstant, (double)-4);\n    double I2  = 3.46*pow(EulerConstant, (double)-4);\n    // double R0X = 0.1954*cos(27.9*PI/180);\n    // double R0Y = 0.1954*sin(27.9*PI/180);\n\n    double frequency = (float)1/DT;\n\n    double hrw = Irw * DESIRED_VEL;\n\n    /* define the robot 8 inertial parameters */\n    double pi1 = M0*R0X*((M1+M2)*L1+M2*R1)/M;\n    double pi2 = M0*R0X*M2*L2/M;\n    double pi3 = M0*R0Y*((M1+M2)*L1+M2*R1)/M;\n    double pi4 = M0*R0Y*M2*L2/M;\n    double pi5 = I0+M0*(M1+M2)*(pow(R0X, (double)2) + pow(R0Y, (double)2))/M;\n    double pi6 = M2*L2*(M0*L1+(M0+M1)*R1)/M;\n    double pi7 = I1+(M0*(M1+M2)*pow(L1, (double)2)+2*M0*M2*L1*R1+M2*(M0+M1)*pow(R1, (double)2))/M;\n    double pi8 = I2+(M2*(M0+M1)*pow(L2, (double)2))/M;\n\n    Eigen::Matrix<double, 8, 1> robotInertialParameters;\n    robotInertialParameters(0, 0) = pi1;\n    robotInertialParameters(1, 0) = pi2;\n    robotInertialParameters(2, 0) = pi3;\n    robotInertialParameters(3, 0) = pi4;\n    robotInertialParameters(4, 0) = pi5;\n    robotInertialParameters(5, 0) = pi6;\n    robotInertialParameters(6, 0) = pi7;\n    robotInertialParameters(7, 0) = pi8;\n\n\n    q1 = q2 = q1dot = q2dot = omega0 = 0.0;\n    \n    /* Eigen Matrix */\n    Matrix Y;\n    Y.resize(NUM_OF_MEASUREMENTS, 8);\n\n    /* Define Hrw matrix as a Nx1 column vector and all components equal to hrw */\n    Eigen::Matrix<float, NUM_OF_MEASUREMENTS, 1> Hcm;\n    for (int i = 0; i < NUM_OF_MEASUREMENTS; ++i)\n        Hcm(i, 0) = hrw;\n\n    /* ros init */\n    ros::init(argc, argv, \"cepheus_controller_node\");\n    ros::NodeHandle n;\n\n    /* Create publishers */\n    ros::Publisher RW_velocity_pub = n.advertise<std_msgs::Float64>(\"/cepheus/reaction_wheel_velocity_controller/command\", 1);\n    ros::Publisher LE_position_pub = n.advertise<std_msgs::Float64>(\"/cepheus/left_elbow_position_controller/command\", 1);\n    ros::Publisher LS_position_pub = n.advertise<std_msgs::Float64>(\"/cepheus/left_shoulder_position_controller/command\", 1);\n\n    /* messages to publish */\n    std_msgs::Float64 msg_RW;\n    std_msgs::Float64 msg_LE;\n    std_msgs::Float64 msg_LS;\n    \n    /* init messages */ \n    msg_RW.data = 0.1;\n    msg_LE.data = 0.1;\n    msg_LS.data = 0.1;\n\n    int currentMeasurement = 0;\n\n    /* Create subscribers */\n    ros::Subscriber RW_velocity_sub = n.subscribe<sensor_msgs::JointState>(\"/cepheus/joint_states\", 1, velocityCheckCallback);\n    ros::Subscriber position_sub = n.subscribe<gazebo_msgs::LinkStates>(\"/gazebo/link_states\", 1, positionCheckCallback);\n\n    \n    ros::Rate loop_rate(frequency);\n\n\n    while (ros::ok()) {\n\n        RW_velocity_pub.publish(msg_RW);\n        LE_position_pub.publish(msg_LE);\n        LS_position_pub.publish(msg_LS);\n        \n        ros::spinOnce();\n\n        // arm joins sinusoidal movement\n        msg_LE.data = 3 * sin(ros::Time::now().toSec());\n        msg_LS.data = -1 * sin(ros::Time::now().toSec());\n\n\n        if (reachedVel && (currentMeasurement < NUM_OF_MEASUREMENTS)) {\n            \n            /* Keep RW desired velocity while taking measurements */\n\n            msg_RW.data = DESIRED_VEL;\n            \n            ROS_INFO(\"-----------------------------------------------------------------\");\n            ROS_INFO(\"current measurement number: %d\", currentMeasurement+1);\n            ROS_INFO(\"q1: %.3f, q2: %.3f, q1dot: %.3f, q2dot: %.3f, omega0: %.3f\", q1, q2, q1dot, q2dot, omega0);\n\n            Y(currentMeasurement, 0) = (2*omega0 + q1dot) * cos(q1);\n            Y(currentMeasurement, 1) = (2*omega0 + q1dot + q2dot) * cos(q1+q2);\n            Y(currentMeasurement, 2) = (2*omega0 + q1dot) * sin(q1);\n            Y(currentMeasurement, 3) = (2*omega0 + q1dot + q2dot) * sin(q1+q2);\n            Y(currentMeasurement, 4) = omega0;\n            Y(currentMeasurement, 5) = (2*omega0 + 2*q1dot + q2dot) * cos(q2);\n            Y(currentMeasurement, 6) = omega0 + q1dot;\n            Y(currentMeasurement, 7) = omega0 + q1dot + q2dot;\n\n            currentMeasurement++;\n        }\n        else if (currentMeasurement >= NUM_OF_MEASUREMENTS) {\n\n            /* Measurements completed */\n\n            RW_velocity_sub.shutdown();\n            position_sub.shutdown();\n            // std::cout << Y << std::endl;\n            \n            Eigen::ColPivHouseholderQR<Eigen::MatrixXf> qr_decomp(Y);\n            // Eigen::FullPivLU<Matrix> lu_decomp(Y);\n            // auto fs = Y.colPivHouseholderQr();\n            auto rank = qr_decomp.rank();\n            ROS_INFO(\"rank = %ld\", rank);\n            if (rank == 8) {\n                // std::cout << Y << std::endl;\n                auto pinv = pseudoInverse(Y);\n                // auto pinv = Y.completeOrthogonalDecomposition().pseudoInverse();\n                // std::cout << Y.rows() << \" \" << Y.cols() << \" \" << pinv.rows() << \" \" << pinv.cols() <<'\\n';\n\n                auto pi_est = pinv*Hcm;\n                std::ofstream file;\n                file.open(\"/home/pelekoudas/cepheus_simulator/ls_pi_est.txt\");\n                if (file.is_open()) {\n                    double e = 0.0;\n                    for (int i = 0; i < 8; ++i) {\n                        e = (robotInertialParameters(i, 0) - pi_est(i, 0))/robotInertialParameters(i, 0)*100;\n                        file << \"Robot Parameter \" << i << \": \" << robotInertialParameters(i, 0) << \", LS estimation: \" << pi_est(i, 0) << \", error(%): \"<< e << '\\n';     \n                    }\n                    file.close();\n                } else {\n                    std::cout << pi_est << std::endl;\n                } \n                break;\n            }\n\n            // break;\n        }\n        else {\n            msg_RW.data += 0.1;\n        }\n\n        loop_rate.sleep();\n    }\n\n\n    return 0;\n}\n", "meta": {"hexsha": "003134a67d82b60bfd4c5bcda149a02fb6389824", "size": 8384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cepheus_control/src/cepheus_controller.cpp", "max_stars_repo_name": "pelekoudasq/cepheus_launcher", "max_stars_repo_head_hexsha": "d51ab9441acac00ab95d00352a4d44a6dad61fc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-08T20:01:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T12:31:43.000Z", "max_issues_repo_path": "src/cepheus_control/src/cepheus_controller.cpp", "max_issues_repo_name": "pelekoudasq/cepheus_simulator", "max_issues_repo_head_hexsha": "d51ab9441acac00ab95d00352a4d44a6dad61fc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-08-19T16:10:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-21T12:33:17.000Z", "max_forks_repo_path": "src/cepheus_control/src/cepheus_controller.cpp", "max_forks_repo_name": "pelekoudasq/cepheus_simulator", "max_forks_repo_head_hexsha": "d51ab9441acac00ab95d00352a4d44a6dad61fc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-16T18:49:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T18:49:03.000Z", "avg_line_length": 36.2943722944, "max_line_length": 171, "alphanum_fraction": 0.5938692748, "num_tokens": 2516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6474484924046331}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_NORMAL_HPP\n#define MCL_NORMAL_HPP 1\n\n#include <Eigen/Dense>\n\nnamespace mcl\n{\n\ntemplate <typename T>\nstatic inline Eigen::Matrix<T,3,1> triangle_normal(\n\tconst Eigen::Matrix<T,3,1> &a,\n\tconst Eigen::Matrix<T,3,1> &b,\n\tconst Eigen::Matrix<T,3,1> &c,\n\tbool normalize = true)\n{\n\tEigen::Matrix<T,3,1> n = (b-a).cross(c-a);\n\tif (normalize) { n.stableNormalize(); }\n\treturn n;\n}\n\ntemplate <typename T>\nstatic inline Eigen::Matrix<T,2,1> edge_normal(\n\tconst Eigen::Matrix<T,2,1> &p0,\n\tconst Eigen::Matrix<T,2,1> &p1,\n\tbool normalize = true)\n{\n\tEigen::Matrix<T,2,1> n(p1[1]-p0[1], -(p1[0]-p0[0]));\n\tif (normalize) { n.stableNormalize(); }\n\treturn n;\n}\n\n} // ns mcl\n\n#endif\n", "meta": {"hexsha": "f90f9aaa0f2d70bbc9ec6495c4873e2012c583fc", "size": 746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/Normal.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/Normal.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/Normal.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6315789474, "max_line_length": 53, "alphanum_fraction": 0.6689008043, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.647448476836581}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/hypot.hpp>\n#include <math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdHypot, Fvar) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n  using std::isnan;\n\n  fvar<double> x(0.5, 1.0);\n  fvar<double> y(2.3, 2.0);\n\n  fvar<double> a = hypot(x, y);\n  EXPECT_FLOAT_EQ(hypot(0.5, 2.3), a.val_);\n  EXPECT_FLOAT_EQ((0.5 * 1.0 + 2.3 * 2.0) / hypot(0.5, 2.3), a.d_);\n\n  fvar<double> z(0.0, 1.0);\n  fvar<double> w(-2.3, 2.0);\n  fvar<double> b = hypot(x, z);\n\n  EXPECT_FLOAT_EQ(0.5, b.val_);\n  EXPECT_FLOAT_EQ(1.0, b.d_);\n\n  fvar<double> c = hypot(x, w);\n  isnan(c.val_);\n  isnan(c.d_);\n\n  fvar<double> d = hypot(z, x);\n  EXPECT_FLOAT_EQ(0.5, d.val_);\n  EXPECT_FLOAT_EQ(1.0, d.d_);\n}\n\nTEST(AgradFwdHypot, FvarFvarDouble) {\n  using boost::math::hypot;\n  using stan::math::fvar;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = hypot(x, y);\n\n  EXPECT_FLOAT_EQ(hypot(3.0, 6.0), a.val_.val_);\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0, 6.0), a.val_.d_);\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0, 6.0), a.d_.val_);\n  EXPECT_FLOAT_EQ(-0.059628479, a.d_.d_);\n}\n\nstruct hypot_fun {\n  template <typename T0, typename T1>\n  inline typename boost::math::tools::promote_args<T0, T1>::type operator()(\n      const T0 arg1, const T1 arg2) const {\n    return hypot(arg1, arg2);\n  }\n};\n\nTEST(AgradFwdHypot, nan_0) {\n  hypot_fun hypot_;\n  test_nan_fwd(hypot_, 3.0, 5.0, false);\n}\n", "meta": {"hexsha": "0c7e801f41585cf4507b5da65ae0ad1cfefb7c80", "size": 1545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/fwd/scal/fun/hypot_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/fwd/scal/fun/hypot_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/fwd/scal/fun/hypot_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4090909091, "max_line_length": 76, "alphanum_fraction": 0.6349514563, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.647431466712107}}
{"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#include <iostream>\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n#include <gtsam_vio/math_utils.hpp>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace gtsam_vio;\n\nTEST(MathUtilsTest, skewSymmetric) {\n  Vector3d w(1.0, 2.0, 3.0);\n  Matrix3d w_hat = skewSymmetric(w);\n  Vector3d zero_vector = w_hat * w;\n\n  FullPivLU<Matrix3d> lu_helper(w_hat);\n  EXPECT_EQ(lu_helper.rank(), 2);\n  EXPECT_DOUBLE_EQ(zero_vector.norm(), 0.0);\n  return;\n}\n\nTEST(MathUtilsTest, quaternionNormalize) {\n  Vector4d q(1.0, 1.0, 1.0, 1.0);\n  quaternionNormalize(q);\n\n  EXPECT_DOUBLE_EQ(q.norm(), 1.0);\n  return;\n}\n\nTEST(MathUtilsTest, quaternionToRotation) {\n  Vector4d q(0.0, 0.0, 0.0, 1.0);\n  Matrix3d R = quaternionToRotation(q);\n  Matrix3d zero_matrix = R - Matrix3d::Identity();\n\n  FullPivLU<Matrix3d> lu_helper(zero_matrix);\n  EXPECT_EQ(lu_helper.rank(), 0);\n  return;\n}\n\nTEST(MathUtilsTest, rotationToQuaternion) {\n  Vector4d q1(0.0, 0.0, 0.0, 1.0);\n  Matrix3d I = Matrix3d::Identity();\n  Vector4d q2 = rotationToQuaternion(I);\n  Vector4d zero_vector = q1 - q2;\n\n  EXPECT_DOUBLE_EQ(zero_vector.norm(), 0.0);\n  return;\n}\n\nTEST(MathUtilsTest, quaternionMultiplication) {\n  Vector4d q1(2.0, 2.0, 1.0, 1.0);\n  Vector4d q2(1.0, 2.0, 3.0, 1.0);\n  q1 = q1 / q1.norm();\n  q2 = q2 / q2.norm();\n  Vector4d q_prod = quaternionMultiplication(q1, q2);\n\n  Matrix3d R1 = quaternionToRotation(q1);\n  Matrix3d R2 = quaternionToRotation(q2);\n  Matrix3d R_prod = R1 * R2;\n  Matrix3d R_prod_cp = quaternionToRotation(q_prod);\n\n  Matrix3d zero_matrix = R_prod - R_prod_cp;\n\n  EXPECT_NEAR(zero_matrix.sum(), 0.0, 1e-10);\n  return;\n}\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "1d49954a85f156b03a406a082e4f78e610bccd00", "size": 1870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math_utils_test.cpp", "max_stars_repo_name": "vkopli/isam2_vio", "max_stars_repo_head_hexsha": "2fe49c74a307921b4af29a4197ef43b9757c4b8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2020-04-05T08:16:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T17:31:37.000Z", "max_issues_repo_path": "test/math_utils_test.cpp", "max_issues_repo_name": "vkopli/isam2_vio", "max_issues_repo_head_hexsha": "2fe49c74a307921b4af29a4197ef43b9757c4b8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T02:26:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-09T04:35:29.000Z", "max_forks_repo_path": "test/math_utils_test.cpp", "max_forks_repo_name": "vkopli/isam2_vio", "max_forks_repo_head_hexsha": "2fe49c74a307921b4af29a4197ef43b9757c4b8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-09-30T23:02:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T09:59:07.000Z", "avg_line_length": 23.9743589744, "max_line_length": 68, "alphanum_fraction": 0.7026737968, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6474314667121069}}
{"text": "#include \"gtest/gtest.h\"\n\n#include \"conex/exponential_map_pade.h\"\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n\n#include \"conex/debug_macros.h\"\n\nnamespace conex {\n\nusing Eigen::Map;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nGTEST_TEST(ExponentialMapPadeApproximation, CompareWithEigen) {\n  int n = 4;\n  MatrixXd A(n, n);\n  // clang-format off\n  A << 3, 1, 0, 1,\n       1, 3, 1, 0,\n       0, 1, 4, 1,\n       1, 0, 1, 5;\n  // clang-format on\n  A = A / A.trace();\n\n  MatrixXd reference = A.exp();\n  MatrixXd calculated(n, n);\n\n  Map<MatrixXd, Eigen::Aligned> map(calculated.data(), n, n);\n  ExponentialMapPadeApproximation(A, &map);\n  for (int i = 0; i < n; i++) {\n    for (int j = 0; j < n; j++) {\n      EXPECT_NEAR(reference(i, j), calculated(i, j), 1e-7);\n    }\n  }\n}\n\n}  // namespace conex\n", "meta": {"hexsha": "92ce890dd2f8bba279787b6ffc3d70da826fa3d1", "size": 820, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/exponential_map_pade_test.cc", "max_stars_repo_name": "frankpermenter/conex", "max_stars_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T20:41:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T20:41:20.000Z", "max_issues_repo_path": "conex/test/exponential_map_pade_test.cc", "max_issues_repo_name": "frankpermenter/conex", "max_issues_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/exponential_map_pade_test.cc", "max_forks_repo_name": "frankpermenter/conex", "max_forks_repo_head_hexsha": "40f8838e6e618bf68df9aae80db7272ff95b7244", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5, "max_line_length": 63, "alphanum_fraction": 0.6219512195, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6474314639048675}}
{"text": "//\n// $Id$\n//\n//\n// Original author: Darren Kessner <darren@proteowizard.org>\n//\n// Copyright 2006 Louis Warschaw Prostate Cancer Center\n//   Cedars Sinai Medical Center, Los Angeles, California  90048\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \n// you may not use this file except in compliance with the License. \n// You may obtain a copy of the License at \n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software \n// distributed under the License is distributed on an \"AS IS\" BASIS, \n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n// See the License for the specific language governing permissions and \n// limitations under the License.\n//\n\n\n#include \"MagnitudeLorentzian.hpp\"\n#include \"MagnitudeLorentzianTestData.hpp\"\n#include \"pwiz/data/misc/FrequencyData.hpp\"\n#include \"pwiz/utility/misc/unit.hpp\"\n#include <boost/filesystem/operations.hpp>\n#include \"pwiz/utility/misc/Std.hpp\"\n#include <cstring>\n\n\nusing namespace pwiz::util;\nusing namespace pwiz::frequency;\nusing namespace pwiz::data;\n\n\nostream* os_ = 0;\ndouble epsilon_ = numeric_limits<double>::epsilon();\n\n\nvoid testBasic()\n{\n    MagnitudeLorentzian m(1,0,1); // m(x) = 1/sqrt(x^2+1)\n    unit_assert_equal(m(0), 1, epsilon_);\n    unit_assert_equal(m(1), 1/sqrt(2.), epsilon_);\n    unit_assert_equal(m(2), 1/sqrt(5.), epsilon_);\n    unit_assert_equal(m(3), 1/sqrt(10.), epsilon_);\n    unit_assert_equal(m(4), 1/sqrt(17.), epsilon_);\n\n    // center == 0, alpha == 2*pi, tau == 1/(2*pi)\n    unit_assert_equal(m.center(), 0, epsilon_);\n    unit_assert_equal(m.alpha(), 2*M_PI, epsilon_);\n    unit_assert_equal(m.tau(), 1/(2*M_PI), epsilon_);\n\n    if (os_) *os_ << \"testBasic(): success!\\n\";\n}\n\n\nvoid testFit()\n{\n    MagnitudeLorentzian ref(1,0,1);\n\n    // choose sample values near 1!\n    // weighting pow(y,6) gives big roundoff errors\n\n    vector< pair<double,double> > samples;\n    for (int i=-2; i<3; i++)\n        samples.push_back(make_pair(i/10.,ref(i/10.)));\n\n    MagnitudeLorentzian m(samples);\n\n    if (os_)\n    {\n        *os_ << \"coefficients: \" << setprecision(14);\n        copy(m.coefficients().begin(), m.coefficients().end(), ostream_iterator<double>(*os_, \" \"));\n        *os_ << endl;\n\n        *os_ << \"error: \" << m(0)-1 << endl;\n\n        for (int i=0; i<5; i++)\n            *os_ << i << \", \" << m(i) << endl;\n    }\n\n    unit_assert_equal(m(0), 1, epsilon_*100);\n    unit_assert_equal(m(1), 1/sqrt(2.), epsilon_*100);\n    unit_assert_equal(m(2), 1/sqrt(5.), epsilon_*100);\n    unit_assert_equal(m(3), 1/sqrt(10.), epsilon_*100);\n    unit_assert_equal(m(4), 1/sqrt(17.), epsilon_*100);\n    if (os_) *os_ << \"testFit(): success!\\n\";\n}\n\n\nvoid testData()\n{\n    string filename = \"MagnitudeLorentizianTest.cfd.temp.txt\";\n    ofstream temp(filename.c_str());\n    temp << sampleData_;\n    temp.close();\n\n    FrequencyData fd(filename);\n    boost::filesystem::remove(filename); \n\n    FrequencyData::const_iterator max = fd.max();\n    if (os_) *os_ << \"max: (\" << max->x << \", \" << abs(max->y) << \")\\n\";\n\n    // fit MagnitudeLorentzian to 3 points on unnormalized data\n\n    vector< pair<double,double> > samples1;\n    transform(fd.max()-1, fd.max()+2, back_inserter(samples1), FrequencyData::magnitudeSample);\n\n    if (os_)\n    {\n        *os_ << \"raw data:\\n\";\n        for (unsigned int i=0; i<samples1.size(); i++)\n            *os_ << \"sample \" << i << \": (\" << samples1[i].first << \", \" << samples1[i].second << \")\\n\";\n    }\n\n    const MagnitudeLorentzian m1(samples1);\n\n    if (os_)\n    {\n        *os_ << \"m1: \";\n        copy(m1.coefficients().begin(), m1.coefficients().end(), ostream_iterator<double>(*os_, \" \"));\n        *os_ << endl;\n        *os_ << \"error: \" << scientific << m1.leastSquaresError() << endl;\n\n        for (unsigned int i=0; i<samples1.size(); i++)\n            *os_ << \"m1(\" << i << \") == \" << m1(samples1[i].first) << endl;\n    }\n\n    // now on normalized data\n\n\n    fd.normalize();\n\n    vector< pair<double,double> > samples2;\n    transform(fd.max()-1, fd.max()+2, back_inserter(samples2), FrequencyData::magnitudeSample);\n\n    if (os_)\n    {\n        *os_ << \"normalized: \\n\";\n        for (unsigned int i=0; i<samples2.size(); i++)\n            *os_ << \"sample \" << i << \": (\" << samples2[i].first << \", \" << samples2[i].second << \")\\n\";\n    }\n\n    const MagnitudeLorentzian m2(samples2);\n\n    if (os_)\n    {\n        *os_ << \"m2: \";\n        copy(m2.coefficients().begin(), m2.coefficients().end(), ostream_iterator<double>(*os_, \" \"));\n        *os_ << endl;\n        *os_ << \"error: \" << scientific << m2.leastSquaresError() << endl;\n\n        for (unsigned int i=0; i<samples2.size(); i++)\n            *os_ << \"m2(\" << i << \") == \" << m2(samples2[i].first) << \" [\" << fd.scale()*m2(samples2[i].first) << \"]\\n\";\n    }\n\n    unit_assert_equal(m2.leastSquaresError(), 0, 1e-15);\n}\n\n\nint main(int argc, char* argv[])\n{\n    TEST_PROLOG(argc, argv)\n\n    try\n    {\n        if (argc>1 && !strcmp(argv[1],\"-v\")) os_ = &cout;\n        if (os_) *os_ << \"MagnitudeLorentzianTest\\n\";\n        testBasic();\n        testFit();\n        testData();\n    }\n    catch (exception& e)\n    {\n        TEST_FAILED(e.what())\n    }\n    catch (...)\n    {\n        TEST_FAILED(\"Caught unknown exception.\")\n    }\n\n    TEST_EPILOG\n}\n\n", "meta": {"hexsha": "b4f64c0d4329ecf3e9da14d69ef6990c07647072", "size": 5311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz/analysis/frequency/MagnitudeLorentzianTest.cpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "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": "pwiz/analysis/frequency/MagnitudeLorentzianTest.cpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz/analysis/frequency/MagnitudeLorentzianTest.cpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_forks_repo_licenses": ["Apache-2.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.25, "max_line_length": 120, "alphanum_fraction": 0.5934852194, "num_tokens": 1532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6474314547489632}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace std;\nint main()\n{\n    Eigen::Quaterniond q1(0.35,0.2,0.3,0.1);\n    q1=q1.normalized();\n    Eigen::Quaterniond p(0,0.1,0.2,0.3);\n    cout<<\"p\"<<endl<<p.coeffs()<<endl;\n    Eigen::Quaterniond p1=q1*p*q1.inverse();\n    cout<<\"p after rotate:\"<<endl<<p1.coeffs()<<endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "96d5a778a0c151de39f0025529108cb1d2544d76", "size": 369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/assignment/ex3_3/ex3_3.cpp", "max_stars_repo_name": "linmeeka/slambook", "max_stars_repo_head_hexsha": "554a9fdd33fc50b2b7d375cdbf4a1a5f8b46e7b8", "max_stars_repo_licenses": ["MIT"], "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/assignment/ex3_3/ex3_3.cpp", "max_issues_repo_name": "linmeeka/slambook", "max_issues_repo_head_hexsha": "554a9fdd33fc50b2b7d375cdbf4a1a5f8b46e7b8", "max_issues_repo_licenses": ["MIT"], "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/assignment/ex3_3/ex3_3.cpp", "max_forks_repo_name": "linmeeka/slambook", "max_forks_repo_head_hexsha": "554a9fdd33fc50b2b7d375cdbf4a1a5f8b46e7b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5, "max_line_length": 53, "alphanum_fraction": 0.620596206, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6474184637991163}}
{"text": "/* Copyright (C) 2012-2019 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n\n/* Test_Permutations.cpp - Applying plaintext permutation to encrypted vector\n */\n#include <NTL/ZZ.h>\nNTL_CLIENT\n\n#include <helib/NumbTh.h>\n#include <helib/timing.h>\n#include <helib/permutations.h>\n#include <helib/EncryptedArray.h>\n#include <helib/ArgMap.h>\n\nusing namespace helib;\n\nstatic bool noPrint = true;\n\nvoid testCtxt(long m, long p, long widthBound=0, long L=0, long r=1);\n\n// OLD CODE\n//void usage(char *prog)\n//{\n//  cout << \"Usage: \"<<prog<<\" [test=? [optional parameters...]]\\n\";\n//  cout << \"  optional parameters have the form 'attr1=val1 attr2=val2 ...'\\n\";\n//  cout << \"  e.g, 'test=1 m=108 p=2 r=1\\n\";\n//  cout << \"  test is either 0 (plaintext) or 1 (ciphertext)[default=1]\\n\\n\";\n//  cout << \"test=0, permuting plaintext hypercubes (dimension upto 4):\\n\";\n//  cout << \"  ord1,ord2,ord3,ord4 size of dimensions 1..4 [default ord1=30, ord2,3,4=0]\\n\";\n//  cout << \"  good1,good2,good3,good4 native rotation flags (0/1) [default=1]\\n\";\n//  cout << \"  depth bounds the depth of permutation network [default=5]\\n\";\n//  cout << \"\\ntest=1, permuting ciphertext slots:\\n\";\n//  cout << \"  m is the cyclotomic field [default=4369]\\n\";\n//  cout << \"  p,r define the plaintext space p^r [default p=2,r=1]\\n\";\n//  cout << \"  depth bounds the depth of permutation network [default=5]\\n\";\n//  cout << \"  L is number of bits in chain [default=30*depth]\\n\\n\";\n//  cout << \"dry=1 for dry run [default=0]\\n\";\n//  exit(0);\n//}\n\nvoid testCube(Vec<GenDescriptor>& vec, long widthBound)\n{\n  GeneratorTrees trees;\n  long cost = trees.buildOptimalTrees(vec, widthBound);\n  if (!noPrint) {\n    cout << \"@TestCube: trees=\" << trees << endl;\n    cout << \" cost =\" << cost << endl;\n  }\n  Vec<long> dims;\n  trees.getCubeDims(dims);\n  CubeSignature sig(dims);\n\n  for (long cnt=0; cnt<3; cnt++) {\n    Permut pi;\n    randomPerm(pi, trees.getSize());\n\n    PermNetwork net;\n    net.buildNetwork(pi, trees);\n\n    HyperCube<long> cube1(sig), cube2(sig);\n    for (long i=0; i<cube1.getSize(); i++) cube1[i] = i;\n    HyperCube<long> cube3 = cube1;\n    applyPermToVec(cube2.getData(), cube1.getData(), pi); // direct application\n    net.applyToCube(cube3); // applying permutation netwrok\n    if (cube2==cube3) cout << \"GOOD\\n\";\n    else {\n      cout << \"BAD\\n\";\n      if (cube1.getSize()<100 && !noPrint) {\n\tcout << \"in=\"<<cube1.getData() << endl;\n\tcout << \"out1=\"<<cube2.getData()<<\", out2=\"\n\t     << cube3.getData()<<endl<<endl;\n      }\n    }\n  }\n}\n\nvoid testCtxt(long m, long p, long widthBound, long L, long r)\n{\n  if (!noPrint)\n    cout << \"@testCtxt(m=\"<<m<<\",p=\"<<p<<\",depth=\"<<widthBound<< \",r=\"<<r<<\")\";\n\n  Context context(m,p,r);\n  EncryptedArray ea(context); // Use G(X)=X for this ea object\n\n  // Some arbitrary initial plaintext array\n  vector<long> in(ea.size());\n  for (long i=0; i<ea.size(); i++) in[i] = i % p;\n\n  // Setup generator-descriptors for the PAlgebra generators\n  Vec<GenDescriptor> vec(INIT_SIZE, ea.dimension());\n  for (long i=0; i<ea.dimension(); i++)\n    vec[i] = GenDescriptor(/*order=*/ea.sizeOfDimension(i),\n\t\t\t   /*good=*/ ea.nativeDimension(i), /*genIdx=*/i);\n\n  // Some default for the width-bound, if not provided\n  if (widthBound<=0) widthBound = 1+log2((double)ea.size());\n\n  // Get the generator-tree structures and the corresponding hypercube\n  GeneratorTrees trees;\n  long cost = trees.buildOptimalTrees(vec, widthBound);\n  if (!noPrint) {\n    context.zMStar.printout();\n    cout << \": trees=\" << trees << endl;\n    cout << \" cost =\" << cost << endl;\n  }\n  //  Vec<long> dims;\n  //  trees.getCubeDims(dims);\n  //  CubeSignature sig(dims);\n\n  // 1/2 prime per level should be more or less enough, here we use 1 per layer\n  if (L<=0) L = (1+trees.numLayers())*context.BPL();\n  buildModChain(context, /*nLevels=*/L, /*nDigits=*/3);\n  if (!noPrint) cout << \"**Using \"<<L<<\" and \"\n\t\t     << context.ctxtPrimes.card() << \" Ctxt-primes\\n\";\n\n  // Generate a sk/pk pair\n  SecKey secretKey(context);\n  const PubKey& publicKey = secretKey;\n  secretKey.GenSecKey(); // A +-1/0 secret key\n  Ctxt ctxt(publicKey);\n\n  for (long cnt=0; cnt<3; cnt++) {\n    resetAllTimers();\n    // Choose a random permutation\n    Permut pi;\n    randomPerm(pi, trees.getSize());\n\n    // Build a permutation network for pi\n    PermNetwork net;\n    net.buildNetwork(pi, trees);\n\n    // make sure we have the key-switching matrices needed for this network\n    addMatrices4Network(secretKey, net);\n\n    // Apply the permutation pi to the plaintext\n    vector<long> out1(ea.size());\n    vector<long> out2(ea.size());\n    applyPermToVec(out1, in, pi); // direct application\n\n    // Encrypt plaintext array, then apply permutation network to ciphertext\n    ea.encrypt(ctxt, publicKey, in);\n    if (!noPrint)\n      cout << \"  ** applying permutation network to ciphertext... \" << flush;\n    double t = GetTime();\n    net.applyToCtxt(ctxt, ea); // applying permutation netwrok\n    t = GetTime() -t;\n    if (!noPrint)\n      cout << \"done in \" << t << \" seconds\" << endl;\n    ea.decrypt(ctxt, secretKey, out2);\n\n    if (out1==out2) cout << \"GOOD\\n\";\n    else {\n      cout << \"************ BAD\\n\";\n    }\n    // printAllTimers();\n  }\n}\n\n\n/* m = 31, p = 2, phi(m) = 30\n  ord(p)=5\n  generator 6 has order (== Z_m^*) of 6\n  T = [1 6 5 30 25 26 ]\n\n  m = 61, p = 3, phi(m) = 60\n  ord(p)=10\n  generator 13 has order (== Z_m^*) of 3\n  generator 2 has order (!= Z_m^*) of 2\n  T = [1 2 13 26 47 33 ]\n\n  m = 683, p = 2, phi(m) = 682\n  ord(p)=22\n  generator 3 has order (== Z_m^*) of 31\n\n  m = 47127, p = 2, phi(m) = 30008\n  ord(p)=22\n  generator 5 has order (== Z_m^*) of 682\n  generator 13661 has order (== Z_m^*) of 2\n*/\n\nint main(int argc, char *argv[])\n{\n  long test = 1;\n  long p = 2;\n  long r = 1;\n  long m = 4369;\n  long depth = 5;\n  long L = 0;\n\n  long ord1 = 30;\n  long ord2 = 0;\n  long ord3 = 0;\n  long ord4 = 0;\n  long good1 = 1;\n  long good2 = 1;\n  long good3 = 1;\n  long good4 = 1;\n\n  bool dry = 0;\n  noPrint = 1;\n\n  ArgMap amap;\n  amap.arg(\"test\", test);\n  amap.arg(\"p\", p);\n  amap.arg(\"r\", r);\n  amap.arg(\"m\", m);\n  amap.arg(\"depth\", depth);\n  amap.arg(\"L\", L);\n  amap.arg(\"ord1\", ord1);\n  amap.arg(\"ord2\", ord2);\n  amap.arg(\"ord3\", ord3);\n  amap.arg(\"ord4\", ord4);\n  amap.arg(\"good1\", good1);\n  amap.arg(\"good2\", good2);\n  amap.arg(\"good3\", good3);\n  amap.arg(\"good4\", good4);\n  amap.arg(\"dry\", dry);\n  amap.arg(\"noPrint\", noPrint);\n  amap.parse(argc, argv);\n\n  // get parameters from the command line\n  //if (!parseArgs(argc, argv, argmap)) usage(argv[0]);\n\n  setDryRun(dry);\n  if (test==0 || dry!=0) {\n    Vec<GenDescriptor> vec;\n    long nGens;\n    if (ord2<=1) nGens=1;\n    else if (ord3<=1) nGens=2;\n    else if (ord4<=1) nGens=3;\n    else nGens=4;\n    vec.SetLength(nGens);\n\n    switch (nGens) {\n    case 4:  vec[3] = GenDescriptor(ord4, good4, /*genIdx=*/3);\n    case 3:  vec[2] = GenDescriptor(ord3, good3, /*genIdx=*/2);\n    case 2:  vec[1] = GenDescriptor(ord2, good2, /*genIdx=*/1);\n    default: vec[0] = GenDescriptor(ord1, good1, /*genIdx=*/0);\n    }\n    if (!noPrint) {\n      cout << \"***Testing \";\n      if (isDryRun()) cout << \"(dry run) \";\n      for (long i=0; i<vec.length(); i++)\n\tcout << \"(\"<<vec[i].order<<\",\"<<vec[i].good<<\")\";\n      cout << \", depth=\"<<depth<<\"\\n\";\n    }\n    testCube(vec, depth);\n  }\n  else {\n    setTimersOn();\n    if (!noPrint)\n      cout << \"***Testing m=\"<<m<<\", p=\"<<p<<\", depth=\"<<depth<< endl;\n    testCtxt(m,p,depth,L,r);\n  }\n}\n\n\n\n#if 0\n  cout << \"***Testing m=31, p=2, width=3\\n\"; // (6 good)\n  testCtxt(/*m=*/31, /*p=*/2, /*width=*/3);\n\n  cout << \"\\n***Testing m=61, p=3, width=3\\n\"; // (3 good), (2, bad)\n  testCtxt(/*m=*/61, /*p=*/3, /*width=*/3);\n\n  cout << \"\\n***Testing m=683, p=2, width=5\\n\"; // (31, good)\n  testCtxt(/*m=*/683, /*p=*/2, /*width=*/5);\n\n  //  cout << \"\\n***Testing m=47127, p=2, width=11\\n\"; // (682,good),(2,good)\n  //  testCtxt(/*m=*/47127, /*p=*/2, /*width=*/11);\n\n  // Test 1: a single good small prime-order generator (3)\n  {\n  Vec<GenDescriptor> vec(INIT_SIZE, 1);\n  vec[0] = GenDescriptor(/*order=*/3, /*good=*/true, /*genIdx=*/0);\n  cout << \"***Testing (3,good), width=1\\n\";\n  testCube(vec, /*width=*/1);\n  }\n\n  // Test 2: a single bad larger prime-order generator (31)\n  {\n  Vec<GenDescriptor> vec(INIT_SIZE, 1);\n  vec[0] = GenDescriptor(/*order=*/31, /*good=*/false, /*genIdx=*/0);\n  cout << \"\\n***Testing (31,bad), width=5\\n\";\n  testCube(vec, /*width=*/5);\n  }\n\n  // Test 3: two generators with small prime orders (2,3), both bad\n  {\n  Vec<GenDescriptor> vec(INIT_SIZE, 2);\n  vec[0] = GenDescriptor(/*order=*/2, /*good=*/false, /*genIdx=*/0);\n  vec[1] = GenDescriptor(/*order=*/3, /*good=*/false, /*genIdx=*/1);\n  cout << \"\\n***Testing [(2,bad),(3,bad)], width=3\\n\";\n  testCube(vec, /*width=*/3);\n  }\n\n  // Test 4: two generators with small prime orders (2,3), one good\n  {\n  Vec<GenDescriptor> vec(INIT_SIZE, 2);\n  vec[0] = GenDescriptor(/*order=*/3, /*good=*/true, /*genIdx=*/0);\n  vec[1] = GenDescriptor(/*order=*/2, /*good=*/false, /*genIdx=*/1);\n  cout << \"\\n***Testing [(3,good),(2,bad)], width=3\\n\";\n  testCube(vec, /*width=*/3);\n  }\n\n  // Test 5: a single good composite-order generator (6)\n  {\n  Vec<GenDescriptor> vec(INIT_SIZE, 1);\n  vec[0] = GenDescriptor(/*order=*/6, /*good=*/true, /*genIdx=*/0);\n  cout << \"\\n***Testing (6,good), width=3\\n\";\n  testCube(vec, /*width=*/3);\n  }\n\n  // Test 6: (6,good),(2,bad)\n  {\n  Vec<GenDescriptor> vec(INIT_SIZE, 2);\n  vec[0] = GenDescriptor(/*order=*/6,/*good=*/true, /*genIdx=*/0);\n  vec[1] = GenDescriptor(/*order=*/ 2, /*good=*/false,/*genIdx=*/1);\n  cout << \"\\n**Testing [(6,good),(2,bad)], width=5\\n\";\n  testCube(vec, /*width=*/5);\n  }\n\n  // Test 7: the \"general case\", (682,good),(2,bad)\n  {\n  Vec<GenDescriptor> vec(INIT_SIZE, 2);\n  vec[0] = GenDescriptor(/*order=*/682,/*good=*/true, /*genIdx=*/0);\n  vec[1] = GenDescriptor(/*order=*/ 2, /*good=*/false,/*genIdx=*/1);\n  cout << \"\\n**Testing [(682,good),(2,bad)], width=11\\n\";\n  testCube(vec, /*width=*/11);\n  }\n#endif\n", "meta": {"hexsha": "f392a38fd1ca3ba703549eeb0eaaf9b8e2f5ceed", "size": 10528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/legacy_tests/Test_Permutations.cpp", "max_stars_repo_name": "jatanloya/HElib-PSI", "max_stars_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1360.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T23:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:25:28.000Z", "max_issues_repo_path": "misc/legacy_tests/Test_Permutations.cpp", "max_issues_repo_name": "felipeturing/HElib", "max_issues_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 226.0, "max_issues_repo_issues_event_min_datetime": "2015-01-13T08:07:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T09:26:24.000Z", "max_forks_repo_path": "misc/legacy_tests/Test_Permutations.cpp", "max_forks_repo_name": "felipeturing/HElib", "max_forks_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 402.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T04:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T00:50:34.000Z", "avg_line_length": 30.8739002933, "max_line_length": 92, "alphanum_fraction": 0.5984992401, "num_tokens": 3470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6474096109755817}}
{"text": "// Copyright (c) 2021 FRC Team 3512. All Rights Reserved.\n\n#pragma once\n\n#include <algorithm>\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n#include <drake/math/discrete_algebraic_riccati_equation.h>\n#include <frc/StateSpaceUtil.h>\n#include <frc/system/Discretization.h>\n#include <frc/system/LinearSystem.h>\n#include <units/time.h>\n#include <wpi/array.h>\n\n#include \"controllers/LQR.hpp\"\n\nnamespace frc3512 {\n\n/**\n * Contains the controller coefficients and logic for an implicit model\n * follower.\n *\n * Implicit model following lets us design a feedback controller that erases the\n * dynamics of our system and makes it behave like some other system. This can\n * be used to make a drivetrain more controllable during teleop driving by\n * making it behave like a slower or more benign drivetrain.\n *\n * For more on the underlying math, read appendix C.3 in\n * https://file.tavsys.net/control/controls-engineering-in-frc.pdf.\n */\ntemplate <int States, int Inputs>\nclass ImplicitModelFollower {\npublic:\n    /**\n     * Constructs a controller with the given coefficients and plant.\n     *\n     * @param plant    The plant being controlled.\n     * @param plantRef The plant whose dynamics should be followed.\n     * @param Qelems   The maximum desired error tolerance for each state.\n     * @param Relems   The maximum desired control effort for each input.\n     * @param dt       Discretization timestep.\n     */\n    template <int Outputs>\n    ImplicitModelFollower(\n        const frc::LinearSystem<States, Inputs, Outputs>& plant,\n        const frc::LinearSystem<States, Inputs, Outputs>& plantRef,\n        const wpi::array<double, States>& Qelems,\n        const wpi::array<double, Inputs>& Relems, units::second_t dt)\n        : ImplicitModelFollower<States, Inputs>(plant.A(), plant.B(),\n                                                plantRef.A(), plantRef.B(),\n                                                Qelems, Relems, dt) {}\n\n    /**\n     * Constructs a controller with the given coefficients and plant.\n     *\n     * @param A      Continuous system matrix of the plant being controlled.\n     * @param B      Continuous input matrix of the plant being controlled.\n     * @param Aref   Continuous system matrix whose dynamics should be followed.\n     * @param Bref   Continuous input matrix whose dynamics should be followed.\n     * @param Qelems The maximum desired error tolerance for each state.\n     * @param Relems The maximum desired control effort for each input.\n     * @param dt     Discretization timestep.\n     */\n    ImplicitModelFollower(const Eigen::Matrix<double, States, States>& A,\n                          const Eigen::Matrix<double, States, Inputs>& B,\n                          const Eigen::Matrix<double, States, States>& Aref,\n                          const Eigen::Matrix<double, States, States>& Bref,\n                          const wpi::array<double, States>& Qelems,\n                          const wpi::array<double, Inputs>& Relems,\n                          units::second_t dt) {\n        // Discretize real dynamics\n        Eigen::Matrix<double, States, States> discA;\n        Eigen::Matrix<double, States, Inputs> discB;\n        frc::DiscretizeAB<States, Inputs>(A, B, dt, &discA, &discB);\n\n        // Discretize desired dynamics\n        Eigen::Matrix<double, States, States> discAref;\n        Eigen::Matrix<double, States, Inputs> discBref;\n        frc::DiscretizeAB<States, Inputs>(Aref, Bref, dt, &discAref, &discBref);\n\n        // Find initial Q and R weights\n        Eigen::Matrix<double, States, States> Q = frc::MakeCostMatrix(Qelems);\n        Eigen::Matrix<double, Inputs, Inputs> R = frc::MakeCostMatrix(Relems);\n\n        Eigen::Matrix<double, States, States> Adiff = discA - discAref;\n\n        Eigen::Matrix<double, States, States> Qimf =\n            Adiff.transpose() * Q * Adiff;\n        Eigen::Matrix<double, Inputs, Inputs> Rimf =\n            discB.transpose() * Q * discB + R;\n        Eigen::Matrix<double, States, Inputs> Nimf =\n            Adiff.transpose() * Q * discB;\n\n        // Nudge eigenvalues of Qimf slightly more positive if Q <= 0, since\n        // this is usually caused by numerical imprecision\n        Eigen::SelfAdjointEigenSolver<decltype(Qimf)> Qeigen{Qimf};\n        if (!std::all_of(Qeigen.eigenvalues().data(),\n                         Qeigen.eigenvalues().data() + States,\n                         [](const auto& elem) { return elem >= 0.0; })) {\n            Qimf += decltype(Qimf)::Identity() * 1e-10;\n        }\n\n        m_K = LQR<States, Inputs>(discA, discB, Qimf, Rimf, Nimf);\n\n        // Find u_imf that makes real model match reference model.\n        //\n        // x_k+1 = Ax_k + Bu_imf\n        // z_k+1 = Aref z_k + Bref u_k\n        //\n        // Let x_k = z_k.\n        //\n        // x_k+1 = z_k+1\n        // Ax_k + Bu_imf = Aref x_k + Bref u_k\n        // Bu_imf = Aref x_k - Ax_k + Bref u_k\n        // Bu_imf = (Aref - A)x_k + Bref u_k\n        // u_imf = B^+ ((Aref - A)x_k + Bref u_k)\n        // u_imf = -B^+ (A - Aref)x_k + B^+ Bref u_k\n\n        // The first term makes the open-loop poles that of the reference\n        // system, and the second term makes the input behave like that of the\n        // reference system.\n        m_B = discB.householderQr().solve(discBref);\n\n        Reset();\n    }\n\n    /**\n     * Returns the controller matrix K.\n     */\n    const Eigen::Matrix<double, Inputs, States>& K() const { return m_K; }\n\n    /**\n     * Returns an element of the controller matrix K.\n     *\n     * @param i Row of K.\n     * @param j Column of K.\n     */\n    double K(int i, int j) const { return m_K(i, j); }\n\n    /**\n     * Returns the control input vector u.\n     *\n     * @return The control input.\n     */\n    const Eigen::Matrix<double, Inputs, 1>& U() const { return m_u; }\n\n    /**\n     * Returns an element of the control input vector u.\n     *\n     * @param i Row of u.\n     *\n     * @return The row of the control input vector.\n     */\n    double U(int i) const { return m_u(i, 0); }\n\n    /**\n     * Resets the controller.\n     */\n    void Reset() { m_u.setZero(); }\n\n    /**\n     * Returns the next output of the controller.\n     *\n     * @param x The current state x.\n     * @param u The current input for the original model.\n     */\n    Eigen::Matrix<double, Inputs, 1> Calculate(\n        const Eigen::Matrix<double, States, 1>& x,\n        const Eigen::Matrix<double, Inputs, 1>& u) {\n        m_u = -m_K * x + m_B * u;\n        return m_u;\n    }\n\nprivate:\n    // Computed controller output\n    Eigen::Matrix<double, Inputs, 1> m_u;\n\n    // Controller gain\n    Eigen::Matrix<double, Inputs, States> m_K;\n\n    // Input space conversion gain\n    Eigen::Matrix<double, Inputs, Inputs> m_B;\n};\n\n}  // namespace frc3512\n", "meta": {"hexsha": "f643aa85e41da25e5c4d4c7b390d32b0ffad2c5e", "size": 6773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/controllers/ImplicitModelFollower.hpp", "max_stars_repo_name": "frc3512/Robot-2020", "max_stars_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T04:13:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T00:13:39.000Z", "max_issues_repo_path": "src/main/include/controllers/ImplicitModelFollower.hpp", "max_issues_repo_name": "frc3512/Robot-2020", "max_issues_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2020-02-12T03:05:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T02:14:38.000Z", "max_forks_repo_path": "src/main/include/controllers/ImplicitModelFollower.hpp", "max_forks_repo_name": "frc3512/Robot-2020", "max_forks_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T16:24:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:10:01.000Z", "avg_line_length": 35.835978836, "max_line_length": 80, "alphanum_fraction": 0.6051971062, "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6472086914422801}}
{"text": "#include \"lib/header.h\"\n#include \"lib/random.h\"\n\n#include <armadillo/armadillo>\n\n#include \"glog/logging.h\"\n\nstruct Kalman {\n   public:\n    Kalman(size_t n_out, size_t n_states) : n_out_(n_out) {\n        x_ = arma::colvec(n_states, arma::fill::zeros);\n\n        a_ = arma::mat(n_states, n_states, arma::fill::zeros);\n        for (size_t i = 0; i < n_states; ++i) {\n            for (size_t j = i; j < n_states; ++j) {\n                a_(i, j) = 1.0 / std::pow(10.0, j - i);\n            }\n        }\n\n        // LOG(INFO) << \"A:\\n\" << a_;\n\n        i_ = arma::eye(n_states, n_states);\n\n        h_ = arma::mat(n_out, n_states, arma::fill::zeros);\n        for (size_t i = 0; i < n_out; ++i) {\n            h_(i, i) = 1.0;\n        }\n\n        q_ = 10.0 * arma::eye(n_states, n_states) + 0.1 * arma::ones(n_states, n_states);\n        r_ = 40.0 * arma::eye(n_out, n_out) + 0.1 * arma::ones(n_out, n_out);\n        p_ = arma::zeros(n_states, n_states);\n    }\n\n    void update(const DoubleVector& z) {\n        x_hat_ = a_ * x_;\n        p_ = a_ * p_ * a_.t() + q_;\n        const arma::colvec y = arma::colvec(z) - h_ * x_hat_;\n        const arma::mat s = h_ * p_ * h_.t() + r_;\n        k_ = p_ * h_.t() * s.i();\n        x_hat_ += k_ * y;\n        p_ = (i_ - k_ * h_) * p_;\n        x_ = x_hat_;\n        // LOG(INFO) << \"Z:\\n\" << z;\n        // LOG(INFO) << \"X:\\n\" << x_;\n    }\n\n    DoubleVector state() const {\n        DoubleVector result(n_out_);\n        const arma::vec s = h_ * x_;\n        for (size_t i = 0; i < n_out_; ++i) {\n            result[i] = s(i);\n        }\n        return result;\n    }\n\n   private:\n    size_t n_out_;\n    arma::colvec x_;\n    arma::colvec x_hat_;\n    arma::mat a_;\n    arma::mat h_;\n    arma::mat q_;\n    arma::mat r_;\n    arma::mat k_;\n    arma::mat p_;\n    arma::mat i_;\n};\n\nint main() {\n    Kalman k(1, 3);\n    double sum1 = 0;\n    double sum2 = 0;\n    for (size_t i = 0; i < 100000; ++i) {\n        const double value = std::sin(static_cast<double>(i) / 1000.);\n        const double noise_value = value + 0.01 * randNorm01<double>();\n        k.update({noise_value});\n        sum1 += std::abs(noise_value - value);\n        sum2 += std::abs(k.state()[0] - value);\n        std::cout << (noise_value - value) << \" \" << (k.state()[0] - value) << std::endl;\n    }\n    std::cout << sum2 / sum1 << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "eacb846c91d6682944d16483d369ccf2ab165ddd", "size": 2331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eulerKalman/Kalman.cpp", "max_stars_repo_name": "evilmucedin/project-euler", "max_stars_repo_head_hexsha": "08ed51a5ff0d05f60271d99d35b3e601bcddf85d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-23T04:31:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T09:03:09.000Z", "max_issues_repo_path": "eulerKalman/Kalman.cpp", "max_issues_repo_name": "evilmucedin/project-euler", "max_issues_repo_head_hexsha": "08ed51a5ff0d05f60271d99d35b3e601bcddf85d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eulerKalman/Kalman.cpp", "max_forks_repo_name": "evilmucedin/project-euler", "max_forks_repo_head_hexsha": "08ed51a5ff0d05f60271d99d35b3e601bcddf85d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-03-28T20:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-27T07:03:02.000Z", "avg_line_length": 27.75, "max_line_length": 89, "alphanum_fraction": 0.4916344916, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6472086896315487}}
{"text": "//===- gemm.cc ------------------------------------------------------------===//\n//\n//                       The CIM Hardware Simulator Project\n//\n// See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n#include \"gemm.hh\"\n#include \"diagnostic/msgHandling.hh\"\n#include <Eigen/Dense>\n\nnamespace cimHW {\n\ncimHWGemmOp::cimHWGemmOp(\n  const std::string &configFile,\n  const_element_type* input_A_, const_dim_type input_A_ndim_, const_dim_type* input_A_dims_,\n  const_element_type* input_B_, const_dim_type input_B_ndim_, const_dim_type* input_B_dims_,\n  const_element_type* input_C_, const_dim_type input_C_ndim_, const_dim_type* input_C_dims_,\n  element_type* output_Y_, const_dim_type output_Y_ndim_, const_dim_type* output_Y_dims_,\n  const_element_type alpha_, const_element_type beta_,\n  const_dim_type transA_, const_dim_type transB_)\n\t: cimHWOp(\"Gemm\")\n  , m_input_A(input_A_)\n  , m_input_B(input_B_)\n  , m_input_C(input_C_)\n  , m_output_Y(output_Y_)\n  , m_alpha(alpha_), m_beta(beta_)\n  , m_cimCU(configFile)\n{\n  verbose1(opName());\n\n  // input data validation check\n  if(input_A_ndim_ != 2 || input_B_ndim_ != 2)\n    error(\"Rank of inputs should be 2\");\n\n  // handle transition of matrix, finally the matrix should look like...\n  // (m_M, m_K) x (m_K, m_N)\n  if(!transA_)\n  {\n    m_M = input_A_dims_[0];\n    m_K = input_A_dims_[1];\n  }\n  else\n  {\n    m_M = input_A_dims_[1];\n    m_K = input_A_dims_[0];\n  }\n  if(!transB_)\n  {\n    m_N = input_B_dims_[1];\n    if(m_K != input_B_dims_[0])\n      error(\"The dimension of matrics to be gemm should be consistent\");\n  }\n  else\n  {\n    m_N = input_B_dims_[0];\n    if(m_K != input_B_dims_[1])\n      error(\"The dimension of matrics to be gemm should be consistent\");\n  }\n  \n  // map to proper view of matrix according to transision\n  m_matrix_A = (!transA_)?\n              Eigen::Map<const MatrixXfRowMajor>(m_input_A, m_M, m_K).eval() :\n              Eigen::Map<const MatrixXfRowMajor>(m_input_A, m_K, m_M).transpose();\n  m_matrix_B = (!transB_)?\n              Eigen::Map<const MatrixXfRowMajor>(m_input_B, m_K, m_N).eval() :\n              Eigen::Map<const MatrixXfRowMajor>(m_input_B, m_N, m_K).transpose();\n\n  // transform C's shape and size\n  m_C_shape = std::vector<dim_type>(input_C_dims_, input_C_dims_ + input_C_ndim_);\n  m_C_size = std::accumulate(m_C_shape.cbegin(), m_C_shape.cend(), 1, std::multiplies<dim_type>());\n}\n\nvoid cimHWGemmOp::simulate() \n{\n  // take matrixA as kernel and matrixB as data to use ComputeUnit\n  MatrixXfRowMajor result = MatrixXfRowMajor::Zero(m_M, m_N);\n  for(int i=0; i<m_matrix_A.rows(); i++)\n    result.row(i) = m_cimCU.compute(m_matrix_B, m_matrix_A.row(i).transpose());\n\n  // multiply alpha\n  result *= m_alpha;\n  // Broadcast the bias as needed if bias is given\n  if (m_beta != 0 && m_input_C != nullptr) {\n    MatrixXfRowMajor bias_mat(m_M, m_N);\n    if (m_C_size == 1) {\n      // C is (), (1,) or (1, 1), set the scalar\n      bias_mat.setConstant(*m_input_C);\n    } else if (m_C_shape.size() == 1 || m_C_shape[0] == 1) {\n      // C is (N,) or (1, N)\n      bias_mat.rowwise() = Eigen::Map<const RowVectorXf>(m_input_C, m_N);\n    } else if (m_C_shape[1] == 1) {\n      // C is (M, 1)\n      bias_mat.colwise() = Eigen::Map<const Eigen::VectorXf>(m_input_C, m_M);\n    } else {\n      // C is (M, N), no broadcast needed.\n      bias_mat = Eigen::Map<const MatrixXfRowMajor>(m_input_C, m_M, m_N);\n    }\n    // multiply apply beta\n    result += bias_mat * m_beta;\n  }  \n\n  // copy back to output\n  memcpy(m_output_Y, result.data(), sizeof(numType) * m_M * m_N);\n  verbose1(\"\\n\");\n}\n\n} // namespace cimHW", "meta": {"hexsha": "cfa8e49b853460646df3b65c7ca8a53142be848b", "size": 3643, "ext": "cc", "lang": "C++", "max_stars_repo_path": "skysim/onnc-cimHW/lib/gemm.cc", "max_stars_repo_name": "ONNC/ONNC-CIM", "max_stars_repo_head_hexsha": "dd15eae6b22b39dcd2bff179e14ad0eda40e4338", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-05T02:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T10:37:20.000Z", "max_issues_repo_path": "skysim/onnc-cimHW/lib/gemm.cc", "max_issues_repo_name": "ONNC/ONNC-CIM", "max_issues_repo_head_hexsha": "dd15eae6b22b39dcd2bff179e14ad0eda40e4338", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skysim/onnc-cimHW/lib/gemm.cc", "max_forks_repo_name": "ONNC/ONNC-CIM", "max_forks_repo_head_hexsha": "dd15eae6b22b39dcd2bff179e14ad0eda40e4338", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-11T10:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T10:39:01.000Z", "avg_line_length": 33.7314814815, "max_line_length": 99, "alphanum_fraction": 0.6371122701, "num_tokens": 1068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951570602081, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.6472013264743813}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Dense>\n#include <vector>\n#include <type_traits>\n\nusing namespace std;\nusing namespace Eigen;\n\nMatrixXd open(string fileToOpen)\n{\n    vector<double> MtxEntries;\n    ifstream MtxDataFile(fileToOpen);\n    string MtxRowString;\n    string MtxEntry;\n \n    int MtxRowNumber = 0;\n  \n    while (getline(MtxDataFile, MtxRowString))\n    {\n        stringstream MtxRowStringStream(MtxRowString);\n \n        while (getline(MtxRowStringStream, MtxEntry, ',')) \n        {\n            MtxEntries.push_back(stod(MtxEntry));  \n        }\n        MtxRowNumber++; \n    }\n \n    return Map<Matrix<double, Dynamic, Dynamic, RowMajor>>(matrixEntries.data(), matrixRowNumber, matrixEntries.size() / matrixRowNumber);\n }\n\nvoid save(string fileName, MatrixXd  matrix)\n{\n    const static IOFormat CSVFormat(FullPrecision, DontAlignCols, \" \", \"\\n\");\n    ofstream file(fileName);\n    if (file.is_open())\n    {\n        file << matrix.format(CSVFormat);\n        file.close();\n    }\n}\n\nvoid Print(MatrixXd a, int n, int m)\n{\n     for (int i = 0; i < n; i++) \n{       \n\t for (int j = n; j < m; j++) \n{\n            printf(\"%.3f  \", a(i, j));\n        }\n        fprintf(output_file,\"\\n\");\n    }\n   \n     return;\n}\n\n\nvoid GaussJordan(MatrixXd mtx){\n    \n   MatrixXd I_ = MatrixXd::Identity(mtx.rows(),mtx.cols());\n   \n   MatrixXd C(mtx.rows(), mtx.cols()+I_.cols());\n    \n   C << mtx, I_;\n    \n   C.row(0).swap(C.row(mtx.rows() - 1));\n    \n   for (int i = 0; i < mtx.rows(); i++) {\n\n        for (int j = 0; j < mtx.rows(); j++) \n{\n            if (j != i) {\n\n                float temp = C(j,i) / C(i,i);\n                for (int k = 0; k < 2*mtx.rows(); k++) \n{\n                    C(j,k) -= C(i,k)*temp;\n                }\n            }\n        }\n    }\n    \n    for (int i = 0; i < mtx.rows(); i++)\n{\n        float temp_ = C(i,i);\n        \n        for (int j = 0; j < 2 * mtx.rows(); j++) \n{\n            C(i,j) = C(i,j)/temp_;\n        }\n      }\n\n    Print(C, mtx.cols(), 2*mtx.cols());\n}\n\n\n\n", "meta": {"hexsha": "51f28d2bcaea95c63ed71b5081df715d2a871c5a", "size": 2023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "soluciones/nt.bermudez/tarea2/solucion.cpp", "max_stars_repo_name": "japeinado/FISI2028-202120", "max_stars_repo_head_hexsha": "6b16a779f3e34bcbf35d8b5e0ea345cf50ffdadd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T19:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:26:41.000Z", "max_issues_repo_path": "soluciones/nt.bermudez/tarea2/solucion.cpp", "max_issues_repo_name": "Camilors95/FISI2028-202120", "max_issues_repo_head_hexsha": "85fbe8408be0a733fdab639784ad9b235025340a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-09-18T01:33:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T00:11:45.000Z", "max_forks_repo_path": "soluciones/nt.bermudez/tarea2/solucion.cpp", "max_forks_repo_name": "Camilors95/FISI2028-202120", "max_forks_repo_head_hexsha": "85fbe8408be0a733fdab639784ad9b235025340a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-09-17T22:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T19:59:49.000Z", "avg_line_length": 20.23, "max_line_length": 138, "alphanum_fraction": 0.5155709343, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6471516826230528}}
{"text": "/*\n * Copyright (c) 2015, The Regents of the University of California (Regents).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *    1. Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *\n *    2. Redistributions in binary form must reproduce the above\n *       copyright notice, this list of conditions and the following\n *       disclaimer in the documentation and/or other materials provided\n *       with the distribution.\n *\n *    3. Neither the name of the copyright holder nor the names of its\n *       contributors may be used to endorse or promote products derived\n *       from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Please contact the author(s) of this library if you have any questions.\n * Authors: Erik Nelson            ( eanelson@eecs.berkeley.edu )\n *          David Fridovich-Keil   ( dfk@eecs.berkeley.edu )\n */\n\n#include \"rotation.h\"\n\n#include <cmath>\n#include <Eigen/LU>\n#include <glog/logging.h>\n\nnamespace bsfm {\n\n// Convert from Euler angles to a rotation matrix. Phi, theta, and psi define the\n// angles of the intermediate rotations about x (R_x), y (R_y), and z (R_z)\n// respectively. See https://en.wikipedia.org/wiki/Rotation_matrix.\nMatrix3d EulerAnglesToMatrix(double phi, double theta, double psi) {\n  double c1 = std::cos(phi);\n  double c2 = std::cos(theta);\n  double c3 = std::cos(psi);\n  double s1 = std::sin(phi);\n  double s2 = std::sin(theta);\n  double s3 = std::sin(psi);\n\n  Matrix3d R;\n  R(0, 0) = c2*c3;\n  R(0, 1) = c3*s1*s2 - c1*s3;\n  R(0, 2) = s1*s3 + c1*c3*s2;\n  R(1, 0) = c2*s3;\n  R(1, 1) = c1*c3 + s1*s2*s3;\n  R(1, 2) = c1*s2*s3 - c3*s1;\n  R(2, 0) = -s2;\n  R(2, 1) = c2*s1;\n  R(2, 2) = c1*c2;\n\n  return R;\n}\n\n// Same thing as above, but where phi, theta, and psi are specified as a vector.\nMatrix3d EulerAnglesToMatrix(const Vector3d& euler_angles) {\n  return EulerAnglesToMatrix(euler_angles(0), euler_angles(1), euler_angles(2));\n}\n\n// Convert from a rotation matrix to Euler angles.\n// From: http://staff.city.ac.uk/~sbbh653/publications/euler.pdf\n// Note that the solution that is returned is only unique when phi, theta, and\n// psi are all <= 0.5 * PI. If this is not the case, they will still be correct,\n// but may not be unique!\nVector3d MatrixToEulerAngles(const Matrix3d& R) {\n  // Make sure R is actually a rotation matrix.\n  if (std::abs(R.determinant() - 1) > 1e-4) {\n    LOG(WARNING) << \"R does not have a determinant of 1.\";\n    return Vector3d::Zero();\n  }\n\n  double theta = -std::asin(R(2, 0));\n\n  if (std::abs(cos(theta)) < 1e-8) {\n    LOG(WARNING) << \"Theta is approximately +/- PI/2, which yields a \"\n                    \"singularity. Cannot decompose matrix into Euler angles.\";\n    return Vector3d(theta, 0.0, 0.0);\n  }\n\n  double phi = std::atan2(R(2, 1), R(2, 2));\n  double psi = std::atan2(R(1, 0) / std::cos(theta), R(0, 0) / std::cos(theta));\n\n  return Vector3d(phi, theta, psi);\n}\n\n// Get roll angle from a rotation matrix.\n// Just like above, the solution will only be unique if roll < 0.5 * PI.\ndouble Roll(const Matrix3d& R) {\n  double theta = -std::asin(R(2, 0));\n  if (std::abs(std::cos(theta)) < 1e-8)\n    return 0.0;\n  return std::atan2(R(2, 1), R(2, 2));\n}\n\n// Get pitch angle from a rotation matrix.\n// This solution is unique.\ndouble Pitch(const Matrix3d& R) {\n  return -std::asin(R(2, 0));\n}\n\n// Get yaw angle from a rotation matrix.\n// Just like above, the solution will only be unique if yaw < 0.5 * PI.\ndouble Yaw(const Matrix3d& R) {\n  double theta = -std::asin(R(2, 0));\n  if (std::abs(std::cos(theta)) < 1e-8)\n    return 0.0;\n  return std::atan2(R(1, 0) / std::cos(theta), R(0, 0) / std::cos(theta));\n}\n\n// Unroll an angle to be \\in [0, 2*PI)\ndouble Unroll(double angle) {\n  angle = fmod(angle, 2.0 * M_PI);\n  if (angle < 0)\n    angle += 2.0 * M_PI;\n  return angle;\n}\n\n// Normalize an angle to be \\in [-PI, PI)\ndouble Normalize(double angle) {\n  angle = fmod(angle + M_PI, 2.0 * M_PI);\n  if (angle < 0)\n    angle += 2.0 * M_PI;\n  return angle - M_PI;\n}\n\n// Computes the shortest distance between two angles on S^1.\n// Found by manipulating the first answer on:\n// stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles\ndouble S1Distance(double from, double to) {\n  double d = Unroll(Unroll(to) - Unroll(from));\n  if (d > M_PI)\n    d -= 2.0*M_PI;\n  return Normalize(d);\n}\n\n// Convert from degrees to radians.\ndouble D2R(double angle) {\n  return angle * M_PI / 180.0;\n}\n\n// Convert from radians to degrees.\ndouble R2D(double angle) {\n  return angle * 180.0 / M_PI;\n}\n\n// An error metric between two rotation matrices on SO3.\ndouble SO3Error(const Matrix3d& R1, const Matrix3d& R2) {\n  const Matrix3d R_error = R1.transpose()*R2 - R2.transpose()*R1;\n\n  // 'vee' is the inverse of the hat operator, and extracts a vector from a\n  // cross-product matrix.\n  const Vector3d R_vee(R_error(2,1), R_error(0,2), R_error(1,0));\n  return (0.5 * R_vee).norm();\n}\n\n}  //\\namespace bsfm\n", "meta": {"hexsha": "c4743d1209439dcbef6f5321ec9913b146e2337f", "size": 5917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/geometry/rotation.cpp", "max_stars_repo_name": "jamesdsmith/berkeley_sfm", "max_stars_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T13:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T19:30:33.000Z", "max_issues_repo_path": "src/cpp/geometry/rotation.cpp", "max_issues_repo_name": "jamesdsmith/berkeley_sfm", "max_issues_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T17:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-22T20:59:43.000Z", "max_forks_repo_path": "src/cpp/geometry/rotation.cpp", "max_forks_repo_name": "erik-nelson/berkeley_sfm", "max_forks_repo_head_hexsha": "5bf0b45fac176ff7abfca0ff690893c1afc73c51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-01-22T06:23:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-16T03:54:33.000Z", "avg_line_length": 34.2023121387, "max_line_length": 81, "alphanum_fraction": 0.6765252662, "num_tokens": 1744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6471516719295941}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_GAMMALN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_GAMMALN_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-euler\n    Function object implementing gammaln capabilities\n\n    Natural logarithm of the absolute value of the Gamma function\n     \\f$\\displaystyle \\log |\\Gamma(x)|\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = gammaln(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = log(abs(gamma(x))));\n    @endcode\n\n    @par Notes\n\n    - The accuracy of the function is not uniformly good for negative entries\n      The algorithm used is currently an adapted vesion of the cephes one.\n      For better accuracy in the negative entry case one can use the extern\n      boost_math gammaln functor but at a loss of speed.\n\n      However, as stated in boost math:\n\n      \"While the relative errors near the positive roots of lgamma are very low,\n       the  function has an infinite number of irrational roots for negative arguments:\n       very close to these negative roots only a low absolute error can be guaranteed.\"\n\n    - The call gammaln(x, sgn) also returns the sign of gamma in the output parameter sgn.\n\n       Be aware that POSIX version of lgamma is not thread-safe: each execution of the function\n       stores the sign of the gamma function of x in the static external variable signgam.\n\n       boost.simd also provides @ref signgam which independantly computes the sign.\n\n    @par Decorators\n\n    std_ for floating entries  provides access to @c std::lgamma\n\n    @see gamma, signgam\n\n  **/\n  Value gammaln(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/gammaln.hpp>\n#include <boost/simd/function/simd/gammaln.hpp>\n\n#endif\n", "meta": {"hexsha": "3ec693824d6d019395f580f90f54fd830cb7e549", "size": 2171, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/gammaln.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/function/gammaln.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/gammaln.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 28.9466666667, "max_line_length": 100, "alphanum_fraction": 0.6508521419, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6471516592377264}}
{"text": "#include <Eigen/Dense>\n#include <complex>\n#include <iostream>\n\n#include <fft/fft2.hpp>\n\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n  typedef std::complex<double> cdouble;\n\n  typedef Eigen::Array<cdouble, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> complex_array_t;\n  typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> array_t;\n\n  complex_array_t f_tilde_hat(4, 4);\n\n  f_tilde_hat << 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1;\n  array_t f;\n\n  FFT fft;\n\n  std::cout << \"f_tilde_hat:\\n\" << f_tilde_hat << \"\\n\";\n\n  fft.ifft2(f, f_tilde_hat);\n  std::cout << \"f:\\n\" << f << \"\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "f93f7aedba65e0ba209ee6b50ecbb6d43de19511", "size": 640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main_test_ifft2.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "test/main_test_ifft2.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/main_test_ifft2.cpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 21.3333333333, "max_line_length": 97, "alphanum_fraction": 0.6453125, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6471469093710668}}
{"text": "#include <OpenTissue/core/math/math_vector3.h>\n#include <util_angle.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\ntypedef double                        T;\ntypedef OpenTissue::math::Vector3<T>  V;\ntypedef V::value_traits               VT;\n\n\nBOOST_AUTO_TEST_SUITE(util_angle);\n\nBOOST_AUTO_TEST_CASE(test1)\n{\n\n  V const v0 = V(0.0, 1.0, 0.0);\n  V const v1 = V(0.0, 0.0, 0.0);\n  V const v2 = V(1.0, 0.0, 0.0);\n\n  T const angle = util::angle(v0,v1,v2);\n\n  BOOST_CHECK_CLOSE(angle, VT::pi_half(), 0.01 );\n}\n\nBOOST_AUTO_TEST_CASE(test2)\n{\n\n  V const v0 = V(0.0, 1.0, 0.0);\n  V const v1 = V(0.0, 0.0, 0.0);\n  V const v2 = V(1.0, 1.0, 0.0);\n\n  T const angle = util::angle(v0,v1,v2);\n\n  BOOST_CHECK_CLOSE(angle, VT::pi_quarter(), 0.01 );\n}\n\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "2a3bc884d5648b2037da57d74a34c4624ab2a97c", "size": 921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GRIT/unit_tests/util_angle/util_angle.cpp", "max_stars_repo_name": "H2020-MSCA-ITN-rainbow/GRIT", "max_stars_repo_head_hexsha": "1bdfb0735515e9d462214f66b88a71aabf836d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-28T19:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T19:57:26.000Z", "max_issues_repo_path": "GRIT/unit_tests/util_angle/util_angle.cpp", "max_issues_repo_name": "H2020-MSCA-ITN-rainbow/GRIT", "max_issues_repo_head_hexsha": "1bdfb0735515e9d462214f66b88a71aabf836d76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2018-05-06T21:08:19.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-11T17:59:00.000Z", "max_forks_repo_path": "GRIT/unit_tests/util_angle/util_angle.cpp", "max_forks_repo_name": "misztal/GRIT", "max_forks_repo_head_hexsha": "6850fec967c9de7c6c501f5067d021ef5288b88e", "max_forks_repo_licenses": ["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.4186046512, "max_line_length": 52, "alphanum_fraction": 0.6590662324, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483235, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6471156581560743}}
{"text": "#include <Eigen/Core>\n#include <iostream>\nusing namespace Eigen;\nusing namespace std;\nvoid PolygonToEquations(const MatrixX2d& pts, MatrixX2d& ab, VectorXd& c) {\n  // ax + by + c <= 0\n  // assume polygon is convex\n\n  Vector2d p0 = pts.row(0);\n\n  for (int i=0; i < pts.rows(); ++i) {\n    int i1 = (i+1) % pts.rows();\n    double x0 = pts(i,0),\n        y0 = pts(i,1),\n        x1 = pts(i1,0),\n        y1 = pts(i1,1);\n    ab(i,0) = -(y1 - y0);\n    ab(i,1) = x1 - x0;\n    ab.row(i).normalize();\n    c(i) = -ab.row(i).dot(pts.row(i));\n  }\n\n}\n\nint main() {\n  MatrixX2d m(4,2), ab(4,2);\n  VectorXd c(4);\n  m << 0,0,\n      0,1,\n      1,1,\n      1,0;\n  PolygonToEquations(m, ab, c);\n  cout << \"ab: \" << ab << endl;\n  cout << \"c: \" << c.transpose() << endl;\n}\n", "meta": {"hexsha": "176d0b83e605d5d5c3ec9862f4f5338b3efe44a5", "size": 748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sandbox/polygon_expt.cpp", "max_stars_repo_name": "HARPLab/trajopt", "max_stars_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 250.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T04:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T15:52:54.000Z", "max_issues_repo_path": "src/sandbox/polygon_expt.cpp", "max_issues_repo_name": "HARPLab/trajopt", "max_issues_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-08-19T13:14:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T08:08:26.000Z", "max_forks_repo_path": "src/sandbox/polygon_expt.cpp", "max_forks_repo_name": "HARPLab/trajopt", "max_forks_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 118.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T11:44:00.000Z", "avg_line_length": 20.7777777778, "max_line_length": 75, "alphanum_fraction": 0.5093582888, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6471156546473502}}
{"text": "#include \"gaussianprocessregressor.h\"\n#include <iostream>\n#include <cmath>\n#include <ctime>\n#include <Eigen/LU>\n#include \"nloptutility.h\"\n#include \"utility.h\"\n\n//#define VERBOSE\n//#define NOISELESS\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nnamespace\n{\n\nconst bool   useLogNormalPrior     = true;\nconst double a_prior_mu            = std::log(0.500);\nconst double a_prior_sigma_squared = 0.10;\n#ifdef NOISELESS\nconst double b_fixed               = 1e-06;\n#else\nconst double b_prior_mu            = std::log(0.001);\nconst double b_prior_sigma_squared = 0.10;\n#endif\nconst double r_prior_mu            = std::log(0.500);\nconst double r_prior_sigma_squared = 0.10;\n\ndouble calc_grad_a_prior(const double a)\n{\n    return (a_prior_mu - a_prior_sigma_squared - std::log(a)) / (a_prior_sigma_squared * a);\n}\n\n#ifndef NOISELESS\ndouble calc_grad_b_prior(const double b)\n{\n    return (b_prior_mu - b_prior_sigma_squared - std::log(b)) / (b_prior_sigma_squared * b);\n}\n#endif\n\ndouble calc_grad_r_i_prior(const Eigen::VectorXd &r, const int index)\n{\n    return (r_prior_mu - r_prior_sigma_squared - std::log(r(index))) / (r_prior_sigma_squared * r(index));\n}\n\ndouble calc_a_prior(const double a)\n{\n    return std::log(Utility::log_normal(a, a_prior_mu, a_prior_sigma_squared));\n}\n\n#ifndef NOISELESS\ndouble calc_b_prior(const double b)\n{\n    return std::log(Utility::log_normal(b, b_prior_mu, b_prior_sigma_squared));\n}\n#endif\n\ndouble calc_r_i_prior(const Eigen::VectorXd &r, const int index)\n{\n    return std::log(Utility::log_normal(r(index), r_prior_mu, r_prior_sigma_squared));\n}\n\ndouble calc_grad_a(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r)\n{\n    const MatrixXd C_grad_a = Regressor::calc_C_grad_a(X, a, b, r);\n    const double term1 = + 0.5 * y.transpose() * C_inv * C_grad_a * C_inv * y;\n    const double term2 = - 0.5 * (C_inv * C_grad_a).trace();\n    return term1 + term2 + (useLogNormalPrior ? calc_grad_a_prior(a) : 0.0);\n}\n\n#ifndef NOISELESS\ndouble calc_grad_b(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r)\n{\n    const MatrixXd C_grad_b = Regressor::calc_C_grad_b(X, a, b, r);\n    const double term1 = + 0.5 * y.transpose() * C_inv * C_grad_b * C_inv * y;\n    const double term2 = - 0.5 * (C_inv * C_grad_b).trace();\n    return term1 + term2 + (useLogNormalPrior ? calc_grad_b_prior(b) : 0.0);\n}\n#endif\n\ndouble calc_grad_r_i(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r, const int index)\n{\n    const MatrixXd C_grad_r_i = Regressor::calc_C_grad_r_i(X, a, b, r, index);\n    const double term1 = + 0.5 * y.transpose() * C_inv * C_grad_r_i * C_inv * y;\n    const double term2 = - 0.5 * (C_inv * C_grad_r_i).trace();\n    return term1 + term2 + (useLogNormalPrior ? calc_grad_r_i_prior(r, index) : 0.0);\n}\n\nVectorXd calc_grad(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r)\n{\n    const unsigned D = X.rows();\n\n    VectorXd grad(D + 2);\n    grad(0) = calc_grad_a(X, C_inv, y, a, b, r);\n#ifdef NOISELESS\n    grad(1) = 0.0;\n#else\n    grad(1) = calc_grad_b(X, C_inv, y, a, b, r);\n#endif\n\n    for (unsigned i = 2; i < D + 2; ++ i)\n    {\n        const unsigned index = i - 2;\n        grad(i) = calc_grad_r_i(X, C_inv, y, a, b, r, index);\n    }\n\n    return grad;\n}\n\nstruct Data\n{\n    Data(const MatrixXd& X, const VectorXd& y) : X(X), y(y)\n    {\n    }\n\n    const MatrixXd X;\n    const VectorXd y;\n};\n\n// For counting the number of function evaluations\nunsigned count;\n\n// Log likelihood that will be maximized\ndouble objective(const std::vector<double> &x, std::vector<double>& grad, void* data)\n{\n    // For counting the number of function evaluations\n    ++ count;\n\n    const MatrixXd& X = static_cast<const Data*>(data)->X;\n    const VectorXd& y = static_cast<const Data*>(data)->y;\n\n    const unsigned N = X.cols();\n\n    const double   a = x[0];\n#ifdef NOISELESS\n    const double   b = b_fixed;\n#else\n    const double   b = x[1];\n#endif\n    const VectorXd r = [&x]() { std::vector<double> _x = x; return Eigen::Map<VectorXd>(&_x[2], _x.size() - 2); }();\n\n    const MatrixXd C     = Regressor::calc_C(X, a, b, r);\n    const MatrixXd C_inv = C.inverse();\n\n    // When the algorithm is gradient-based, compute the gradient vector\n    if (grad.size() == x.size())\n    {\n        const VectorXd g = calc_grad(X, C_inv, y, a, b, r);\n        for (unsigned i = 0; i < g.rows(); ++ i) grad[i] = g(i);\n    }\n\n    const double term1 = - 0.5 * y.transpose() * C_inv * y;\n    const double term2 = - 0.5 * std::log(C.determinant());\n    const double term3 = - 0.5 * N * std::log(2.0 * M_PI);\n\n    // Computing the regularization terms from a prior assumptions\n    const double a_prior = calc_a_prior(a);\n#ifdef NOISELESS\n    const double b_prior = 1.0;\n#else\n    const double b_prior = calc_b_prior(b);\n#endif\n    const double r_prior = [&r]()\n    {\n        double sum = 0.0;\n        for (unsigned i = 0; i < r.rows(); ++ i) sum += calc_r_i_prior(r, i);\n        return sum;\n    }();\n    const double regularization = useLogNormalPrior ? (a_prior + b_prior + r_prior) : 0.0;\n\n    return term1 + term2 + term3 + regularization;\n}\n\n}\n\nGaussianProcessRegressor::GaussianProcessRegressor(const MatrixXd& X, const VectorXd& y)\n{\n    this->X = X;\n    this->y = y;\n\n    compute_MAP();\n\n    C     = calc_C(X, a, b, r);\n    C_inv = C.inverse();\n}\n\nGaussianProcessRegressor::GaussianProcessRegressor(const Eigen::MatrixXd &X, const Eigen::VectorXd &y, double a, double b, const Eigen::VectorXd &r)\n{\n    this->X = X;\n    this->y = y;\n    this->a = a;\n    this->b = b;\n    this->r = r;\n\n    C     = calc_C(X, a, b, r);\n    C_inv = C.inverse();\n}\n\ndouble GaussianProcessRegressor::estimate_y(const VectorXd &x) const\n{\n    const VectorXd k = calc_k(x, X, a, b, r);\n    return k.transpose() * C_inv * y;\n}\n\ndouble GaussianProcessRegressor::estimate_s(const VectorXd &x) const\n{\n    const VectorXd k = calc_k(x, X, a, b, r);\n    return std::sqrt(a + b - k.transpose() * C_inv * k);\n}\n\nvoid GaussianProcessRegressor::compute_MAP()\n{\n    const unsigned D = X.rows();\n\n    Data data(X, y); // Constant during optimization\n\n#ifdef VERBOSE\n    const auto t1 = std::chrono::system_clock::now();\n    count = 0;\n#endif\n\n    const VectorXd x_ini = VectorXd::Constant(D + 2, 1e+00);\n    const VectorXd upper = VectorXd::Constant(D + 2, 5e+01);\n    const VectorXd lower = VectorXd::Constant(D + 2, 1e-08);\n\n    const VectorXd x_glo = nloptUtility::compute(x_ini, upper, lower, objective, &data, nlopt::GN_DIRECT, 300);\n\n#ifdef VERBOSE\n    const auto t2 = std::chrono::system_clock::now();\n    const unsigned g_count = count;\n    count = 0;\n#endif\n\n    const VectorXd x_loc = nloptUtility::compute(x_glo, upper, lower, objective, &data, nlopt::LD_TNEWTON, 1000);\n\n    a = x_loc(0);\n    b = x_loc(1);\n    r = x_loc.block(2, 0, D, 1);\n\n#ifdef NOISELESS\n    b = b_fixed;\n#endif\n\n#ifdef VERBOSE\n    const auto t3 = std::chrono::system_clock::now();\n    const unsigned l_count = count;\n\n    std::cout << \"global optimization: \" << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << \" ms, \" << g_count << \" evaluations, obj = \" << objective(x_star_global, x_ini, &data) << std::endl;\n    std::cout << \"local optimization: \" << std::chrono::duration_cast<std::chrono::milliseconds>(t3 - t2).count() << \" ms, \" << l_count << \" evaluations, obj = \" << objective(x_star_local, x_ini, &data) << std::endl;\n    std::cout << \"a = \" << a << \", b = \" << b << \", r = \" << r.transpose() << std::endl;\n#endif\n}\n", "meta": {"hexsha": "cf36a7a7870483b83181a8c85971c2aa51064228", "size": 7636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main/gaussianprocessregressor.cpp", "max_stars_repo_name": "takuma-ya/sequential_bayesian_optimization", "max_stars_repo_head_hexsha": "cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/gaussianprocessregressor.cpp", "max_issues_repo_name": "takuma-ya/sequential_bayesian_optimization", "max_issues_repo_head_hexsha": "cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/gaussianprocessregressor.cpp", "max_forks_repo_name": "takuma-ya/sequential_bayesian_optimization", "max_forks_repo_head_hexsha": "cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.062992126, "max_line_length": 218, "alphanum_fraction": 0.6474594028, "num_tokens": 2286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6471156469739989}}
{"text": "#include <functional>\n#include <iostream>\n#include <sstream>\n#include <stdlib.h>\n#include <string.h>\n\n#include <boost/random.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/tuple/tuple_io.hpp>\n\n#include \"biggles/detail/random.hpp\"\n#include \"biggles/sampling/metropolis_hastings.hpp\"\n\nextern \"C\" {\n#include <ccan/tap/tap.h>\n}\n\ntypedef boost::tuples::tuple<float, float> point;\n\ninline float rosenbrock(const point& p)\n{\n    float x, y;\n    boost::tuples::tie(x,y) = p;\n    return (1.f-x)*(1.f-x) + 100.f*(y-x*x)*(y-x*x);\n}\n\n// a cooked-up PDF which has a maximum where the Rosenbrock function has a minimum.\ninline float rosenbrock_log_pdf(const point& p)\n{\n    return -rosenbrock(p);\n}\n\ntypedef boost::tuples::tuple<point, float> proposal_result_t;\n\ninline proposal_result_t propose_gaussian(const point& p)\n{\n    static boost::normal_distribution<float> norm(0.f, 0.2f);\n    static boost::variate_generator<boost::mt19937&, boost::normal_distribution<float> > variate(\n        biggles::detail::random_generator, norm);\n\n    point new_p(p.get<0>() + variate(), p.get<1>() + variate());\n\n    return proposal_result_t(new_p, 0.f);\n}\n\nusing namespace biggles::sampling::metropolis_hastings;\n\nint main(int argc, char** argv)\n{\n    biggles::detail::seed_prng(0xdeadbeef);\n\n    bool verbose = (argc > 1) && (0 == strcmp(argv[1], \"-v\"));\n\n    plan_tests(4);\n\n    typedef std::pointer_to_unary_function<const point&, float> pdf_t;\n    typedef std::pointer_to_unary_function<const point&, proposal_result_t> proposal_func_t;\n\n    // MH sampler for Rosenbrock function. An example of using a function pointer directly.\n    sampler<pdf_t, proposal_func_t> s(std::ptr_fun(rosenbrock_log_pdf), std::ptr_fun(propose_gaussian));\n\n    point optimum(s.last_sample());\n    float optimum_log_density(s.current_sample_log_density());\n\n    for(int i=0; i<4096; ++i)\n    {\n        s.draw();\n\n        if(s.current_sample_log_density() > optimum_log_density)\n        {\n            optimum_log_density = s.current_sample_log_density();\n            optimum = s.last_sample();\n        }\n\n        if(verbose)\n        {\n            std::stringstream ss;\n            ss << \"sample: \" << s.last_sample();\n            diag(\"%s\", ss.str().c_str());\n        }\n    }\n\n    {\n        std::stringstream ss;\n        ss << \"optimum: \" << optimum << \", log-pdf: \" << optimum_log_density\n        << \", alpha: \" << s.acceptance_rate() << \", rosenbrock: \" << rosenbrock(optimum);\n        diag(\"%s\", ss.str().c_str());\n    }\n\n    diag(\"acceptance rate = %.2f%%\", s.acceptance_rate()*100.f);\n    //ok(fabs(s.acceptance_rate() - 0.25f) < 0.2f, \"acceptance rate within 0.2 of 0.25\");\n    ok(fabs(optimum.get<0>() - 1.f) < 0.1f, \"x-co-ordinate within 10%% of optimum\");\n    ok(fabs(optimum.get<1>() - 1.f) < 0.1f, \"y-co-ordinate within 10%% of optimum\");\n\n    // the same thing using the optimise function\n    point optimum2 = optimise(std::ptr_fun(rosenbrock_log_pdf), std::ptr_fun(propose_gaussian));\n\n    {\n        std::stringstream ss;\n        ss << \"optimum via optimise(): \" << optimum2 << \", log-pdf: \" << rosenbrock_log_pdf(optimum2)\n        << \", rosenbrock: \" << rosenbrock(optimum2);\n        diag(\"%s\", ss.str().c_str());\n    }\n\n    ok(fabs(optimum2.get<0>() - 1.f) < 0.1f, \"x-co-ordinate within 10%% of optimum\");\n    ok(fabs(optimum2.get<1>() - 1.f) < 0.1f, \"y-co-ordinate within 10%% of optimum\");\n\n    return exit_status();\n}\n", "meta": {"hexsha": "20dbd818d1945b4645aff8ab1076a54d0a6e35f3", "size": 3398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/metropolis_hastings.cpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "test/metropolis_hastings.cpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/metropolis_hastings.cpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8909090909, "max_line_length": 104, "alphanum_fraction": 0.6362566215, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6470902843445976}}
{"text": "// Copyright Nick Thompson, 2017\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_TEST_MODULE Gauss Kronrod_quadrature_test\n\n#include <complex>\n#include <boost/config.hpp>\n#include <boost/detail/workaround.hpp>\n\n#if !defined(BOOST_NO_CXX11_DECLTYPE) && !defined(BOOST_NO_CXX11_TRAILING_RESULT_TYPES) && !defined(BOOST_NO_SFINAE_EXPR)\n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <boost/math/special_functions/sinc.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/debug_adaptor.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/complex128.hpp>\n#endif\n\n#if !defined(TEST1) && !defined(TEST1A) && !defined(TEST2) && !defined(TEST3)\n#  define TEST1\n#  define TEST1A\n#  define TEST2\n#  define TEST3\n#endif\n\n#ifdef _MSC_VER\n#pragma warning(disable:4127)  // Conditional expression is constant\n#endif\n\nusing std::expm1;\nusing std::atan;\nusing std::tan;\nusing std::log;\nusing std::log1p;\nusing std::asinh;\nusing std::atanh;\nusing std::sqrt;\nusing std::isnormal;\nusing std::abs;\nusing std::sinh;\nusing std::tanh;\nusing std::cosh;\nusing std::pow;\nusing std::exp;\nusing std::sin;\nusing std::cos;\nusing std::string;\nusing boost::math::quadrature::gauss_kronrod;\nusing boost::math::constants::pi;\nusing boost::math::constants::half_pi;\nusing boost::math::constants::two_div_pi;\nusing boost::math::constants::two_pi;\nusing boost::math::constants::half;\nusing boost::math::constants::third;\nusing boost::math::constants::half;\nusing boost::math::constants::third;\nusing boost::math::constants::catalan;\nusing boost::math::constants::ln_two;\nusing boost::math::constants::root_two;\nusing boost::math::constants::root_two_pi;\nusing boost::math::constants::root_pi;\nusing boost::multiprecision::cpp_bin_float_quad;\nusing boost::multiprecision::cpp_dec_float_50;\nusing boost::multiprecision::debug_adaptor;\nusing boost::multiprecision::number;\n\n//\n// Error rates depend only on the number of points in the approximation, not the type being tested,\n// define all our expected errors here:\n//\n\nenum\n{\n   test_ca_error_id,\n   test_ca_error_id_2,\n   test_three_quad_error_id,\n   test_three_quad_error_id_2,\n   test_integration_over_real_line_error_id,\n   test_right_limit_infinite_error_id,\n   test_left_limit_infinite_error_id\n};\n\ntemplate <unsigned Points>\ndouble expected_error(unsigned)\n{\n   return 0; // placeholder, all tests will fail\n}\n\ntemplate <>\ndouble expected_error<15>(unsigned id)\n{\n   switch (id)\n   {\n   case test_ca_error_id:\n      return 1e-7;\n   case test_ca_error_id_2:\n      return 2e-5;\n   case test_three_quad_error_id:\n      return 1e-8;\n   case test_three_quad_error_id_2:\n      return 3.5e-3;\n   case test_integration_over_real_line_error_id:\n      return 6e-3;\n   case test_right_limit_infinite_error_id:\n   case test_left_limit_infinite_error_id:\n      return 1e-5;\n   }\n   return 0;  // placeholder, all tests will fail\n}\n\ntemplate <>\ndouble expected_error<17>(unsigned id)\n{\n   switch (id)\n   {\n   case test_ca_error_id:\n      return 1e-7;\n   case test_ca_error_id_2:\n      return 2e-5;\n   case test_three_quad_error_id:\n      return 1e-8;\n   case test_three_quad_error_id_2:\n      return 3.5e-3;\n   case test_integration_over_real_line_error_id:\n      return 6e-3;\n   case test_right_limit_infinite_error_id:\n   case test_left_limit_infinite_error_id:\n      return 1e-5;\n   }\n   return 0;  // placeholder, all tests will fail\n}\n\ntemplate <>\ndouble expected_error<21>(unsigned id)\n{\n   switch (id)\n   {\n   case test_ca_error_id:\n      return 1e-12;\n   case test_ca_error_id_2:\n      return 3e-6;\n   case test_three_quad_error_id:\n      return 2e-13;\n   case test_three_quad_error_id_2:\n      return 2e-3;\n   case test_integration_over_real_line_error_id:\n      return 6e-3;  // doesn't get any better with more points!\n   case test_right_limit_infinite_error_id:\n   case test_left_limit_infinite_error_id:\n      return 5e-8;\n   }\n   return 0;  // placeholder, all tests will fail\n}\n\ntemplate <>\ndouble expected_error<31>(unsigned id)\n{\n   switch (id)\n   {\n   case test_ca_error_id:\n      return 6e-20;\n   case test_ca_error_id_2:\n      return 3e-7;\n   case test_three_quad_error_id:\n      return 1e-19;\n   case test_three_quad_error_id_2:\n      return 6e-4;\n   case test_integration_over_real_line_error_id:\n      return 6e-3;  // doesn't get any better with more points!\n   case test_right_limit_infinite_error_id:\n   case test_left_limit_infinite_error_id:\n      return 5e-11;\n   }\n   return 0;  // placeholder, all tests will fail\n}\n\ntemplate <>\ndouble expected_error<41>(unsigned id)\n{\n   switch (id)\n   {\n   case test_ca_error_id:\n      return 1e-26;\n   case test_ca_error_id_2:\n      return 1e-7;\n   case test_three_quad_error_id:\n      return 3e-27;\n   case test_three_quad_error_id_2:\n      return 3e-4;\n   case test_integration_over_real_line_error_id:\n      return 5e-5;  // doesn't get any better with more points!\n   case test_right_limit_infinite_error_id:\n   case test_left_limit_infinite_error_id:\n      return 1e-15;\n   }\n   return 0;  // placeholder, all tests will fail\n}\n\ntemplate <>\ndouble expected_error<51>(unsigned id)\n{\n   switch (id)\n   {\n   case test_ca_error_id:\n      return 5e-33;\n   case test_ca_error_id_2:\n      return 1e-8;\n   case test_three_quad_error_id:\n      return 1e-32;\n   case test_three_quad_error_id_2:\n      return 3e-4;\n   case test_integration_over_real_line_error_id:\n      return 1e-14;\n   case test_right_limit_infinite_error_id:\n   case test_left_limit_infinite_error_id:\n      return 3e-19;\n   }\n   return 0;  // placeholder, all tests will fail\n}\n\ntemplate <>\ndouble expected_error<61>(unsigned id)\n{\n   switch (id)\n   {\n   case test_ca_error_id:\n      return 5e-34;\n   case test_ca_error_id_2:\n      return 5e-9;\n   case test_three_quad_error_id:\n      return 4e-34;\n   case test_three_quad_error_id_2:\n      return 1e-4;\n   case test_integration_over_real_line_error_id:\n      return 1e-16;\n   case test_right_limit_infinite_error_id:\n   case test_left_limit_infinite_error_id:\n      return 3e-23;\n   }\n   return 0;  // placeholder, all tests will fail\n}\n\n\ntemplate<class Real, unsigned Points>\nvoid test_linear()\n{\n    std::cout << \"Testing linear functions are integrated properly by gauss_kronrod on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = boost::math::tools::epsilon<Real>() * 10;\n    Real error;\n    auto f = [](const Real& x)->Real\n    {\n       return 5*x + 7;\n    };\n    Real L1;\n    Real Q = gauss_kronrod<Real, Points>::integrate(f, (Real) 0, (Real) 1, 0, 0, &error, &L1);\n    BOOST_CHECK_CLOSE_FRACTION(Q, 9.5, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, 9.5, tol);\n\n    Q = gauss_kronrod<Real, Points>::integrate(f, (Real) 1, (Real) 0, 0, 0, &error, &L1);\n    BOOST_CHECK_CLOSE_FRACTION(Q, -9.5, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, 9.5, tol);\n\n    Q = gauss_kronrod<Real, Points>::integrate(f, (Real) 0, (Real) 0, 0, 0, &error, &L1);\n    BOOST_CHECK_CLOSE(Q, Real(0), tol);\n}\n\ntemplate<class Real, unsigned Points>\nvoid test_quadratic()\n{\n    std::cout << \"Testing quadratic functions are integrated properly by Gauss Kronrod on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = boost::math::tools::epsilon<Real>() * 10;\n    Real error;\n\n    auto f = [](const Real& x)->Real { return 5*x*x + 7*x + 12; };\n    Real L1;\n    Real Q = gauss_kronrod<Real, Points>::integrate(f, 0, 1, 0, 0, &error, &L1);\n    BOOST_CHECK_CLOSE_FRACTION(Q, (Real) 17 + half<Real>()*third<Real>(), tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, (Real) 17 + half<Real>()*third<Real>(), tol);\n}\n\n// Examples taken from\n//http://crd-legacy.lbl.gov/~dhbailey/dhbpapers/quadrature.pdf\ntemplate<class Real, unsigned Points>\nvoid test_ca()\n{\n    std::cout << \"Testing integration of C(a) on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = expected_error<Points>(test_ca_error_id);\n    Real L1;\n    Real error;\n\n    auto f1 = [](const Real& x)->Real { return atan(x)/(x*(x*x + 1)) ; };\n    Real Q = gauss_kronrod<Real, Points>::integrate(f1, 0, 1, 0, 0, &error, &L1);\n    Real Q_expected = pi<Real>()*ln_two<Real>()/8 + catalan<Real>()*half<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\n\n    auto f2 = [](Real x)->Real { Real t0 = x*x + 1; Real t1 = sqrt(t0); return atan(t1)/(t0*t1); };\n    Q = gauss_kronrod<Real, Points>::integrate(f2, 0 , 1, 0, 0, &error, &L1);\n    Q_expected = pi<Real>()/4 - pi<Real>()/root_two<Real>() + 3*atan(root_two<Real>())/root_two<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\n\n    tol = expected_error<Points>(test_ca_error_id_2);\n    auto f5 = [](Real t)->Real { return t*t*log(t)/((t*t - 1)*(t*t*t*t + 1)); };\n    Q = gauss_kronrod<Real, Points>::integrate(f5, 0, 1, 0);\n    Q_expected = pi<Real>()*pi<Real>()*(2 - root_two<Real>())/32;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n}\n\ntemplate<class Real, unsigned Points>\nvoid test_three_quadrature_schemes_examples()\n{\n    std::cout << \"Testing integral in 'A Comparison of Three High Precision Quadrature Schemes' on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = expected_error<Points>(test_three_quad_error_id);\n    Real Q;\n    Real Q_expected;\n\n    // Example 1:\n    auto f1 = [](const Real& t)->Real { return t*boost::math::log1p(t); };\n    Q = gauss_kronrod<Real, Points>::integrate(f1, 0 , 1, 0);\n    Q_expected = half<Real>()*half<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n\n    // Example 2:\n    auto f2 = [](const Real& t)->Real { return t*t*atan(t); };\n    Q = gauss_kronrod<Real, Points>::integrate(f2, 0 , 1, 0);\n    Q_expected = (pi<Real>() -2 + 2*ln_two<Real>())/12;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, 2 * tol);\n\n    // Example 3:\n    auto f3 = [](const Real& t)->Real { return exp(t)*cos(t); };\n    Q = gauss_kronrod<Real, Points>::integrate(f3, 0, half_pi<Real>(), 0);\n    Q_expected = boost::math::expm1(half_pi<Real>())*half<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n    // Example 4:\n    auto f4 = [](Real x)->Real { Real t0 = sqrt(x*x + 2); return atan(t0)/(t0*(x*x+1)); };\n    Q = gauss_kronrod<Real, Points>::integrate(f4, 0 , 1, 0);\n    Q_expected = 5*pi<Real>()*pi<Real>()/96;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n    tol = expected_error<Points>(test_three_quad_error_id_2);\n    // Example 5:\n    auto f5 = [](const Real& t)->Real { return sqrt(t)*log(t); };\n    Q = gauss_kronrod<Real, Points>::integrate(f5, 0 , 1, 0);\n    Q_expected = -4/ (Real) 9;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n\n    // Example 6:\n    auto f6 = [](const Real& t)->Real { return sqrt(1 - t*t); };\n    Q = gauss_kronrod<Real, Points>::integrate(f6, 0 , 1, 0);\n    Q_expected = pi<Real>()/4;\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n}\n\n\ntemplate<class Real, unsigned Points>\nvoid test_integration_over_real_line()\n{\n    std::cout << \"Testing integrals over entire real line in 'A Comparison of Three High Precision Quadrature Schemes' on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = expected_error<Points>(test_integration_over_real_line_error_id);\n    Real Q;\n    Real Q_expected;\n    Real L1;\n    Real error;\n\n    auto f1 = [](const Real& t)->Real { return 1/(1+t*t);};\n    Q = gauss_kronrod<Real, Points>::integrate(f1, -boost::math::tools::max_value<Real>(), boost::math::tools::max_value<Real>(), 0, 0, &error, &L1);\n    Q_expected = pi<Real>();\n    BOOST_CHECK_CLOSE_FRACTION(Q, Q_expected, tol);\n    BOOST_CHECK_CLOSE_FRACTION(L1, Q_expected, tol);\n}\n\ntemplate<class Real, unsigned Points>\nvoid test_right_limit_infinite()\n{\n    std::cout << \"Testing right limit infinite for Gauss Kronrod in 'A Comparison of Three High Precision Quadrature Schemes' on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = expected_error<Points>(test_right_limit_infinite_error_id);\n    Real Q;\n    Real Q_expected;\n    Real L1;\n    Real error;\n\n    // Example 11:\n    auto f1 = [](const Real& t)->Real { return 1/(1+t*t);};\n    Q = gauss_kronrod<Real, Points>::integrate(f1, 0, boost::math::tools::max_value<Real>(), 0, 0, &error, &L1);\n    Q_expected = half_pi<Real>();\n    BOOST_CHECK_CLOSE(Q, Q_expected, 100*tol);\n\n    auto f4 = [](const Real& t)->Real { return 1/(1+t*t); };\n    Q = gauss_kronrod<Real, Points>::integrate(f4, 1, boost::math::tools::max_value<Real>(), 0, 0, &error, &L1);\n    Q_expected = pi<Real>()/4;\n    BOOST_CHECK_CLOSE(Q, Q_expected, 100*tol);\n}\n\ntemplate<class Real, unsigned Points>\nvoid test_left_limit_infinite()\n{\n    std::cout << \"Testing left limit infinite for Gauss Kronrod in 'A Comparison of Three High Precision Quadrature Schemes' on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real tol = expected_error<Points>(test_left_limit_infinite_error_id);\n    Real Q;\n    Real Q_expected;\n\n    // Example 11:\n    auto f1 = [](const Real& t)->Real { return 1/(1+t*t);};\n    Q = gauss_kronrod<Real, Points>::integrate(f1, -boost::math::tools::max_value<Real>(), Real(0), 0);\n    Q_expected = half_pi<Real>();\n    BOOST_CHECK_CLOSE(Q, Q_expected, 100*tol);\n}\n\ntemplate<class Complex>\nvoid test_complex_lambert_w()\n{\n    std::cout << \"Testing that complex-valued integrands are integrated correctly by Gaussian quadrature on type \" << boost::typeindex::type_id<Complex>().pretty_name() << \"\\n\";\n    typedef typename Complex::value_type Real;\n    Real tol = 10e-9;\n    using boost::math::constants::pi;\n    Complex z{2, 3};\n    auto lw = [&z](Real v)->Complex {\n      using std::cos;\n      using std::sin;\n      using std::exp;\n      Real sinv = sin(v);\n      Real cosv = cos(v);\n\n      Real cotv = cosv/sinv;\n      Real cscv = 1/sinv;\n      Real t = (1-v*cotv)*(1-v*cotv) + v*v;\n      Real x = v*cscv*exp(-v*cotv);\n      Complex den = z + x;\n      Complex num = t*(z/pi<Real>());\n      Complex res = num/den;\n      return res;\n    };\n\n    //N[ProductLog[2+3*I], 150]\n    boost::math::quadrature::gauss_kronrod<Real, 61> integrator;\n    Complex Q = integrator.integrate(lw, (Real) 0, pi<Real>());\n    BOOST_CHECK_CLOSE_FRACTION(Q.real(), boost::lexical_cast<Real>(\"1.09007653448579084630177782678166964987102108635357778056449870727913321296238687023915522935120701763447787503167111962008709116746523970476893277703\"), tol);\n    BOOST_CHECK_CLOSE_FRACTION(Q.imag(), boost::lexical_cast<Real>(\"0.530139720774838801426860213574121741928705631382703178297940568794784362495390544411799468140433404536019992695815009036975117285537382995180319280835\"), tol);\n}\n\nBOOST_AUTO_TEST_CASE(gauss_quadrature_test)\n{\n#ifdef TEST1\n    std::cout << \"Testing 15 point approximation:\\n\";\n    test_linear<double, 15>();\n    test_quadratic<double, 15>();\n    test_ca<double, 15>();\n    test_three_quadrature_schemes_examples<double, 15>();\n    test_integration_over_real_line<double, 15>();\n    test_right_limit_infinite<double, 15>();\n    test_left_limit_infinite<double, 15>();\n\n    //  test one case where we do not have pre-computed constants:\n    std::cout << \"Testing 17 point approximation:\\n\";\n    test_linear<double, 17>();\n    test_quadratic<double, 17>();\n    test_ca<double, 17>();\n    test_three_quadrature_schemes_examples<double, 17>();\n    test_integration_over_real_line<double, 17>();\n    test_right_limit_infinite<double, 17>();\n    test_left_limit_infinite<double, 17>();\n    test_complex_lambert_w<std::complex<double>>();\n    test_complex_lambert_w<std::complex<long double>>();\n#endif\n#ifdef TEST1A\n    std::cout << \"Testing 21 point approximation:\\n\";\n    test_linear<cpp_bin_float_quad, 21>();\n    test_quadratic<cpp_bin_float_quad, 21>();\n    test_ca<cpp_bin_float_quad, 21>();\n    test_three_quadrature_schemes_examples<cpp_bin_float_quad, 21>();\n    test_integration_over_real_line<cpp_bin_float_quad, 21>();\n    test_right_limit_infinite<cpp_bin_float_quad, 21>();\n    test_left_limit_infinite<cpp_bin_float_quad, 21>();\n\n    std::cout << \"Testing 31 point approximation:\\n\";\n    test_linear<cpp_bin_float_quad, 31>();\n    test_quadratic<cpp_bin_float_quad, 31>();\n    test_ca<cpp_bin_float_quad, 31>();\n    test_three_quadrature_schemes_examples<cpp_bin_float_quad, 31>();\n    test_integration_over_real_line<cpp_bin_float_quad, 31>();\n    test_right_limit_infinite<cpp_bin_float_quad, 31>();\n    test_left_limit_infinite<cpp_bin_float_quad, 31>();\n#endif\n#ifdef TEST2\n    std::cout << \"Testing 41 point approximation:\\n\";\n    test_linear<cpp_bin_float_quad, 41>();\n    test_quadratic<cpp_bin_float_quad, 41>();\n    test_ca<cpp_bin_float_quad, 41>();\n    test_three_quadrature_schemes_examples<cpp_bin_float_quad, 41>();\n    test_integration_over_real_line<cpp_bin_float_quad, 41>();\n    test_right_limit_infinite<cpp_bin_float_quad, 41>();\n    test_left_limit_infinite<cpp_bin_float_quad, 41>();\n\n    std::cout << \"Testing 51 point approximation:\\n\";\n    test_linear<cpp_bin_float_quad, 51>();\n    test_quadratic<cpp_bin_float_quad, 51>();\n    test_ca<cpp_bin_float_quad, 51>();\n    test_three_quadrature_schemes_examples<cpp_bin_float_quad, 51>();\n    test_integration_over_real_line<cpp_bin_float_quad, 51>();\n    test_right_limit_infinite<cpp_bin_float_quad, 51>();\n    test_left_limit_infinite<cpp_bin_float_quad, 51>();\n#endif\n#ifdef TEST3\n    // Need at least one set of tests with expression templates turned on:\n    std::cout << \"Testing 61 point approximation:\\n\";\n    test_linear<cpp_dec_float_50, 61>();\n    test_quadratic<cpp_dec_float_50, 61>();\n    test_ca<cpp_dec_float_50, 61>();\n    test_three_quadrature_schemes_examples<cpp_dec_float_50, 61>();\n    test_integration_over_real_line<cpp_dec_float_50, 61>();\n    test_right_limit_infinite<cpp_dec_float_50, 61>();\n    test_left_limit_infinite<cpp_dec_float_50, 61>();\n#ifdef BOOST_HAS_FLOAT128\n    test_complex_lambert_w<boost::multiprecision::complex128>();\n#endif\n#endif\n}\n\n#else\n\nint main() { return 0; }\n\n#endif\n", "meta": {"hexsha": "c80ffe85405d58d41da7d27567c1104b225e7266", "size": 18332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gauss_kronrod_quadrature_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/gauss_kronrod_quadrature_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/test/gauss_kronrod_quadrature_test.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": 34.2014925373, "max_line_length": 229, "alphanum_fraction": 0.6986689941, "num_tokens": 5299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6470902787100732}}
{"text": "/*\n * Copyright (c) 2013-2019 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef ODE_MAFFINE_HPP\n#define ODE_MAFFINE_HPP\n\n//\n// ODE using Affine and Mean Value Form\n//\n//  (2018/11/28) ode-maffine0 and ode-maffine are integrated by\n//   porting maffine's algorithm to ode-autodif.hpp .\n//\n//  use -DODE_AUTODIF_NEW=0 to come back the behaviour of maffine0.\n//\n\n#include <iostream>\n#include <list>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n// #include <boost/tuple/tuple.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/interval-vector.hpp>\n#include <kv/affine.hpp>\n#include <kv/ode.hpp>\n#include <kv/ode-autodif.hpp>\n#include <kv/ode-param.hpp>\n#include <kv/ode-callback.hpp>\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T, class F>\nint\node_maffine(F f, ub::vector< affine<T> >& init, const interval<T>& start, interval<T>& end, ode_param<T> p = ode_param<T>() , ub::matrix< interval<T> >* mat = NULL, ub::vector< psa< interval<T> > >* result_psa = NULL)\n{\n\tint n = init.size();\n\tint i, j;\n\n\tub::vector< interval<T> > c;\n\tub::vector< interval<T> > fc;\n\tub::vector< interval<T> > I;\n\tub::vector< autodif< interval<T> > > Iad;\n\n\tub::vector< interval<T> > result_i;\n\tub::matrix< interval<T> > result_d;\n\n\tub::vector< affine<T> > result;\n\n\n\tint maxnum_save;\n\n\tint r;\n\n\tint ret_val;\n\tinterval<T> end2 = end;\n\n\tI.resize(n);\n\tc.resize(n);\n\tfor (i=0; i<n; i++) {\n\t\tI(i) = to_interval(init(i));\n\t\tc(i) = mid(I(i));\n\t}\n\n\tIad = autodif< interval<T> >::init(I);\n\t// NOTICE: below must be autodif version of ode\n\tr = ode(f, Iad, start, end2, p, result_psa);\n\tif (r == 0) return 0;\n\tret_val = r;\n\tautodif< interval<T> >::split(Iad, result_i, result_d);\n\n\tfc = c;\n\t// Step size should be same as above ode call.\n\t// Because above ode call is with autodif and interval input and\n\t// below ode call is without autodif and point input,\n\t// below ode call is supposed to be easier to succeed than above.\n\t// If below ode call fails, force success by increasing order.\n\tode_param<T> p2 = p;\n\tp2.set_autostep(false);\n\twhile (true) {\n\t\tr = ode(f, fc, start, end2, p2);\n\t\tif (r != 0) break;\n\t\tp2.order++;\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"ode_maffine: increase order: \" << p.order << \"\\n\";\n\t\t}\n\t}\n\n\tif (p.ep_reduce == 0) {\n\t\tmaxnum_save = affine<T>::maxnum();\n\t}\n\n\tresult = fc + prod(result_d, init - c);\n\n\tif (p.ep_reduce == 0) {\n\t\tepsilon_reduce2(result, maxnum_save);\n\t} else {\n\t\tepsilon_reduce(result, p.ep_reduce, p.ep_reduce_limit);\n\t}\n\n\tinit = result;\n\tif (ret_val == 1) end = end2;\n\tif (mat != NULL) *mat = result_d;\n\n\treturn ret_val;\n}\n\ntemplate <class T, class F>\nint\nodelong_maffine(\n\tF f,\n\tub::vector< affine<T> >& init,\n\tconst interval<T>& start,\n\tinterval<T>& end,\n\tode_param<T> p = ode_param<T>(),\n\tconst ode_callback<T>& callback = ode_callback<T>(),\n\tub::matrix< interval<T> >* mat = NULL\n) {\n\n\tint s = init.size();\n\tub::vector< affine<T> > x, x1;\n\tinterval<T> t, t1;\n\tint ret_ode;\n\tub::matrix< interval<T> > M, M_tmp;\n\tub::matrix< interval<T> >* M_p;\n\tint ret_val = 0;\n\tbool ret_callback;\n\n\tub::vector< psa< interval<T> > > result_tmp;\n\n\n\tif (mat == NULL) {\n\t\tM_p = NULL;\n\t} else {\n\t\tM_p = &M_tmp;\n\t\tM = ub::identity_matrix< interval<T> >(s);\n\t}\n\n\tx = init;\n\tt = start;\n\tp.set_autostep(true);\n\n\twhile (true) {\n\t\tx1 = x;\n\t\tt1 = end;\n\n\t\tret_ode = ode_maffine(f, x1, t, t1, p, M_p, &result_tmp);\n\t\tif (ret_ode == 0) {\n\t\t\tif (ret_val == 1) {\n\t\t\t\tinit = x1;\n\t\t\t\tif (mat != NULL) *mat = M;\n\t\t\t\tend = t;\n\t\t\t}\n\t\t\treturn ret_val;\n\t\t}\n\t\tret_val = 1;\n\t\tif (mat != NULL) M = prod(M_tmp, M);\n\t\t#if 0\n\t\tif (result_psa != NULL) {\n\t\t\t(*result_psa).push_back(boost::make_tuple(t, t1, result_tmp));\n\t\t}\n\t\t#endif\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"t: \" << t1 << \"\\n\";\n\t\t\tstd::cout << to_interval(x1) << \"\\n\";\n\t\t}\n\n\t\tret_callback = callback(t, t1, to_interval(x), to_interval(x1), result_tmp);\n\n\t\tif (ret_callback == false) {\n\t\t\tinit = x1;\n\t\t\tif (mat != NULL) *mat = M;\n\t\t\tend = t1;\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (ret_ode == 2) {\n\t\t\tinit = x1;\n\t\t\tif (mat != NULL) *mat = M;\n\t\t\treturn 2;\n\t\t}\n\n\t\tt = t1;\n\t\tx = x1;\n\t}\n}\n\ntemplate <class T, class F>\nint\nodelong_maffine(\n\tF f,\n\tub::vector< interval<T> >& init,\n\tconst interval<T>& start,\n\tinterval<T>& end,\n\tode_param<T> p = ode_param<T>(),\n\tconst ode_callback<T>& callback = ode_callback<T>()\n) {\n\tint s = init.size();\n\tint i;\n\tub::vector< affine<T> > x;\n\tint maxnum_save;\n\tint r;\n\n\tmaxnum_save = affine<T>::maxnum();\n\taffine<T>::maxnum() = 0;\n\n\tx = init;\n\n\tr = odelong_maffine(f, x, start, end, p, callback);\n\n\taffine<T>::maxnum() = maxnum_save;\n\n\tif (r == 0) return 0;\n\n\tfor (i=0; i<s; i++) init(i) = to_interval(x(i));\n\n\treturn r;\n}\n\ntemplate <class T, class F>\nint\nodelong_maffine(\n\tF f,\n\tub::vector< autodif< interval<T> > >& init,\n\tconst interval<T>& start,\n\tinterval<T>& end,\n\tode_param<T> p = ode_param<T>(),\n\tconst ode_callback<T>& callback = ode_callback<T>()\n) {\n\tint s = init.size();\n\tint i, j;\n\tub::vector< interval<T> > xi;\n\tub::vector< affine<T> > x;\n\tub::matrix< interval<T> > M, M_tmp;\n\tint maxnum_save;\n\tint r;\n\n\tautodif< interval<T> >::split(init, xi, M);\n\tint s2 = M.size2();\n\n\tmaxnum_save = affine<T>::maxnum();\n\taffine<T>::maxnum() = 0;\n\n\tx = xi;\n\n\tr = odelong_maffine(f, x, start, end, p, callback, &M_tmp);\n\n\taffine<T>::maxnum() = maxnum_save;\n\n\tif (r == 0) return 0;\n\n\tM = prod(M_tmp, M);\n\n\tfor (i=0; i<s; i++) {\n\t\tinit(i).v = to_interval(x(i));\n\t\tinit(i).d.resize(s2);\n\t\tfor (j=0; j<s2; j++) {\n\t\t\tinit(i).d(j) = M(i, j);\n\t\t}\n\t}\n\t\n\treturn r;\n}\n\n} // namespace kv\n\n#endif // ODE_MAFFINE_HPP\n", "meta": {"hexsha": "fca04aecc756ecdea0775b03e249a135070a5948", "size": 5573, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/ode-maffine.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "src/interval/kv/ode-maffine.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "src/interval/kv/ode-maffine.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 20.4139194139, "max_line_length": 217, "alphanum_fraction": 0.614749686, "num_tokens": 1904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6470902684046633}}
{"text": "/**\n    @file .cpp\n\n    @author Terence Henriod\n\n    Project Name\n\n    @brief This program...\n\n    @version Original Code 1.00 (10/29/2013) - T. Henriod\n*/\n\n/*\nbool extensionIsGood( const string& file_name, const string& extension )\n{\n    return ( file_name.find( extension, file_name.length() - 5 ) !=\n             string::npos );\n}\n */\n\n/*==============================================================================\n=======     HEADER FILES     ===================================================\n==============================================================================*/\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <cstdio>\n#include <cmath>\n#include <ctime>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>  // -I /home/thenriod/Desktop/cpp_libs/Eigen_lib\n#include \"my_stopwatch.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\n\n/*==============================================================================\n=======     GLOBAL CONSTANTS     ===============================================\n==============================================================================*/\n#define DEBUG 1\n\nconst int STD_STR_LEN = 100;\n\nconst char MATCH = 'X';\nconst char NO_MATCH = '-';\n\nconst string TRAINING_RESULTS_DIRECTORY = \"/training_results/\";\n\nenum Status\n{\n    NO_ERRORS = 0,\n    ERROR\n};\n\nenum Mode\n{\n    TRAINING_MODE = 0,\n    TESTING_MODE = 1,\n    INVALID = 666\n};\n\n\n/*==============================================================================\n\n=======     USER DEFINED TYPES     =============================================\n==============================================================================*/\n\n/**\n@struct\n\nDescription\n\n@var\n*/\ntypedef struct\n{\n    char** training_image_names;\n    int num_training_images;\n    char** training_eigenweight_names;\n    int num_training_eigenweights;\n    char** testing_image_names;\n    int num_testing_images;\n    int pixels_per_image;\n    int width_in_pixels;\n    int height_in_pixels;\n} JobInfo;\n\n\ntypedef struct\n{\n    char tested_image_name[ STD_STR_LEN ];\n    int test_image_index;\n    char matched_image_name[ STD_STR_LEN ];\n    int matched_image_index;\n    double distance_between_images;\n    char is_match_by_test;\n    char is_actual_match;\n} MatchResult;\n\n/*==============================================================================\n=======     GLOBAL VARIABLES     ===============================================\n==============================================================================*/\n\n\n/*==============================================================================\n=======     FUNCTION PROTOTYPES     ============================================\n==============================================================================*/\n/**\nFunctionName\n\nA short description\n\n@param\n\n@return\n\n@pre\n-# \n\n@post\n-# \n\n@detail @bAlgorithm\n-# \n\n@exception\n\n@code\n@endcode\n*/\nint processCommandLineArguments( const int argc, char** argv,\n                                 JobInfo& info );\n\nint trainingMode( JobInfo& info );\n\nint findSampleImageSize( int& image_width, int& image_height,\n                         const char* file_name );\n\nint allocateArrays( double**& face_data_matrix, double*& mean_face, const JobInfo& info );\n\nint loadTrainingData( Matrix<double, Dynamic, Dynamic>& face_data, const JobInfo& info );\n\nint readPgmToVector( VectorXd& image_vector, const char* file_name, const JobInfo& info );\n\nint trainMeanFace( VectorXd& mean_face,  const Matrix<double, Dynamic, Dynamic>& face_data, const JobInfo& info );\n\nint writeVectorToFile( const char* file_name, const VectorXd& data_vector );\n\nint centerFaceData( Matrix<double, Dynamic, Dynamic>& centered_data, Matrix<double, Dynamic, Dynamic>& face_data, const VectorXd& mean_face, const JobInfo& info );\n\nint findFaceCovariance( Matrix<double, Dynamic, Dynamic>& face_covariance,\n                        const Matrix<double, Dynamic, Dynamic>& centered_data,\n                        const JobInfo& info );\n\nint findEigenValuesVectors( VectorXd& eigenvalues, MatrixXd& eigenvectors,\n                            const MatrixXd& A_matrix, const JobInfo& info );\n\nbool compareEigenvalIndexPairs( const pair< double, int >& one,\n                                const pair< double, int >& other );\n\ndouble getVectorMagnitude( const VectorXd the_vector );\n\nint writePgmImage( const string& file_name, const VectorXd& image_data,\n                   int image_width, int image_height, int image_shades );\n\nVectorXd scaleImageToPgm( const VectorXd& image_data, const JobInfo& info );\n\nint storeEigenData( const VectorXd& eigenvalues, const MatrixXd& eigenvectors );\n\nint promptForNumEigens( const VectorXd& eigenvalues );\n\nint storeEigenProjections( const int eigens_to_keep, const MatrixXd& centered_data, const MatrixXd& face_eigenvectors, const JobInfo& info );\n\nint writeEigenweightFile( const char* file_name, const VectorXd& eigen_weights );\n\nint testingMode( JobInfo& info );\n\nint loadTrainingOutcomes( VectorXd& mean_face, VectorXd& eigenvalues, MatrixXd& eigenvectors, MatrixXd& training_eigenweights, const JobInfo& info );\n\nint readDataVectorFromTxt( VectorXd& data_vector, const char* file_name );\n\nint readMatrixFromTxt( MatrixXd& data_matrix, const char* file_name );\n\nint loadTestingData( Matrix<double, Dynamic, Dynamic>& face_data, const JobInfo& info );\n\nint centerTestData( MatrixXd& centered_data, MatrixXd& face_data, const VectorXd& mean_face, const JobInfo& info );\n\nint projectDataInEigenspace( MatrixXd& eigenweights, const MatrixXd& data, const MatrixXd& eigenvectors );\n\nVectorXd projectImageInEigenspace( const VectorXd& centered_image, const MatrixXd& eigenvectors  );\n\ndouble promptForThreshold();\n\nint matchAllImages( vector< MatchResult >& matching_results,\n                 const MatrixXd& training_eigenweights,\n                 const MatrixXd& testing_eigenweights,\n                 const MatrixXd& eigenvalues,\n                 const double threshold,\n                 const int num_eigens_to_use,\n                 const JobInfo& info );\n\nint matchImage( MatchResult& result, const VectorXd& test_weights, const MatrixXd& training_weights );\n\nint matchImage( MatchResult& result, const VectorXd& test_weights,\n                const MatrixXd& training_weights, const VectorXd& eigenvalues,\n                const int num_eigens_to_use, const double threshold,\n                const JobInfo& info );\n\ndouble computeMahalanobisDistance( const VectorXd& test_weights,\n                                   const VectorXd& training_weights,\n                                   const VectorXd& eigenvalues,\n                                   const int num_eigens_to_use );\n\nint outputDataSummary( vector< MatchResult >& results, double threshold, int num_eigens_to_use, bool explicit_summary );\n\nchar* stripFilePath( char* file_name );\n\n/*==============================================================================\n=======     MAIN FUNCTION     ==================================================\n==============================================================================*/\n\n/**\nFunctionName\n\nA short description\n\n@param\n\n@return\n\n@pre\n-# \n\n@post\n-# \n\n@detail @bAlgorithm\n-# \n\n@exception\n\n@code\n@endcode\n*/\nint main( int argc, char** argv )\n{\n    // variables\n    int program_status = NO_ERRORS;\n    int program_mode = TRAINING_MODE;\n    JobInfo info;\n\n    // process the command line arguments\n    program_mode = processCommandLineArguments( argc, argv, info );\n\ninfo.pixels_per_image = 2880; // 48 x 60 for hi-res samples\n\n    // case: the program is running in training mode\n    if( program_mode == TRAINING_MODE )\n    {\n        // indicate that the program is running in training mode\n        cout << char( 0x0C )\n             << \"    =====================\" << endl\n             << \"    |   TRAINING MODE   |\" << endl\n             << \"    =====================\" << endl << endl;\n\n        // run program in training mode\n        trainingMode( info );\n    }\n    // case: the program is running in \"testing\" mode\n    else if( program_mode == TESTING_MODE )\n    {\n        // indicate that the program is running in training mode\n        cout << char( 0x0C )\n             << \"       ====================\" << endl\n             << \"       |   TESTING MODE   |\" << endl\n             << \"       ====================\" << endl << endl;\n\n        testingMode( info );\n    }    \n    // case: bad command line arguments were used\n    else\n    {\n        puts( \"Bad command line arguments result in program termination.\\n\" );\n    }\n\n    // return a program operation status signal\n    return program_status;\n}\n\n\n/*==============================================================================\n=======     FUNCTION IMPLEMENTATIONS     =======================================\n==============================================================================*/\nint processCommandLineArguments( const int argc, char** argv,\n                                 JobInfo& info )\n{\n    // variables\n    int program_mode = INVALID;\n\n    // case: a large enough number of command line arguments were given\n    if( argc >= 3 )\n    {\n        // collect the numerical value of the first command line argument\n        program_mode = atoi( argv[1] );\n\n        // case: the given mode is not a valid one\n        if( !( program_mode == TRAINING_MODE ||\n               program_mode == TESTING_MODE    ) )\n        {\n            // set the mode to indicate an invalid mode\n            program_mode = INVALID;\n        }\n\n        if( program_mode == TRAINING_MODE )\n        {\n            // set up the job information\n            info.num_training_images = argc - 2;\n            info.training_image_names = argv + 2;\n        }\n        else if( program_mode == TESTING_MODE )\n        {\n            // set up the job information\n            info.training_image_names = argv + 2;\n            info.num_training_images = 0;\n            while( strstr( info.training_image_names[ info.num_training_images ], \".pgm\" ) != NULL )\n            {\n                info.num_training_images++;\n            }\n\n            info.training_eigenweight_names = info.training_image_names + info.num_training_images;\n            info.num_training_eigenweights = 0;\n            while( strstr( info.training_eigenweight_names[ info.num_training_eigenweights ], \".txt\" ) != NULL )\n            {\n                info.num_training_eigenweights++;\n            }\n\n            info.testing_image_names = info.training_eigenweight_names + info.num_training_eigenweights;\n            info.num_testing_images = 0;\n            while( ( info.num_testing_images < 1196 ) &&\n                   ( strstr( info.testing_image_names[ info.num_testing_images ], \".pgm\" ) != NULL ) )\n            {\n                info.num_testing_images++;\n            }\n        }\n    }\n    // case: too few arguments were used\n    else\n    {\n        // give a stern message\n        cout << \"Something's wrong there guy... You need more arguments.\"\n             << endl << endl;\n    }\n\n    // return the mode the program will be running in\n    return program_mode;\n}\n\n\nint trainingMode( JobInfo& info )\n{\n    // variables\n    int training_success = NO_ERRORS;\n\n    VectorXd mean_face;\n    VectorXd face_eigenvalues;\n    Matrix< double, Dynamic, Dynamic > face_eigenvectors;\n    Matrix< double, Dynamic, Dynamic > face_data;\n    Matrix< double, Dynamic, Dynamic > centered_data; // A matrix\n    Matrix< double, Dynamic, Dynamic > face_covariance;\n    Matrix< double, Dynamic, Dynamic > eigen_faces;\n    pair< VectorXd, MatrixXd > eigen_values_vectors;\n\n    int eigens_to_keep = 1;\n\n    info.pixels_per_image = findSampleImageSize( info.width_in_pixels,\n                                                 info.height_in_pixels,\n                                                 info.training_image_names[0] );\n\n    puts( \"Loading data...\\n\" );\n    loadTrainingData( face_data, info );\n\n    puts( \"Training mean...\\n\" );\n    trainMeanFace( mean_face, face_data, info );\n\n    puts( \"\\\"Centering\\\" faces...\\n\" );\n    centerFaceData( centered_data, face_data, mean_face, info );\n\n/*    puts( \"Training covariance matrix...\\n\" );\n    findFaceCovariance( face_covariance, centered_data, info );\n */\n\n    // compute the Eigen values/vectors\n    puts( \"Finding Eigenvalues/Eigenvectors...\\n\" );\n    findEigenValuesVectors( face_eigenvalues, face_eigenvectors,\n                            centered_data, info );\n\n    // create data/coefficients file\n    puts( \"Storing the found eigen-data...\\n\" );\n    storeEigenData( face_eigenvalues, face_eigenvectors );\n\n    // prompt user for the amount of information to keep\n    eigens_to_keep = promptForNumEigens( face_eigenvalues );\n\n    // create the reduced dimensionality eigenfaces, store them to a file\n    puts( \"Storing the training faces projected into eigenspace...\\n\" );\n    storeEigenProjections( eigens_to_keep, centered_data, face_eigenvectors, info );\n\n\n    // return a signal as to whether or not training was successful\n    return training_success;\n}\n\n\nint findSampleImageSize( int& image_width, int& image_height,\n                         const char* file_name )\n{\n    ifstream fin;\n    string magic_number;\n    int width = 0;\n    int height = 0;\n\n    fin.clear();\n    fin.open( file_name );\n    fin >> magic_number >> image_width >> image_height;\n    fin.close();\n\n    return ( image_width * image_height );\n}\n\n\nint loadTrainingData( Matrix<double, Dynamic, Dynamic>& face_data, const JobInfo& info )\n{\n    // variables\n    int image_num = 0;\n    VectorXd temp;\n\n    face_data.resize( info.pixels_per_image, info.num_training_images );\n\n    // for every image\n    for( image_num = 0; image_num < info.num_training_images; image_num++ )\n    {\n        readPgmToVector( temp, info.training_image_names[image_num], info );\n        face_data.col( image_num ) = temp;\n    }\n\n\n#if 0\nwritePgmImage( info.training_image_names[20], face_data.col( 20 ), info.width_in_pixels,\n               info.height_in_pixels, 255 );\n#endif\n\n}\n\n\nint readPgmToVector( VectorXd& image_vector, const char* file_name, const JobInfo& info )\n{\n    int read_success = NO_ERRORS;\n    int pixel_num = 0;\n    ifstream fin;\n    string magic_number;\n    int width;\n    int height;\n    int granularity;\n    unsigned char pixel_byte;\n\n    // open the file\n    fin.clear();\n    fin.open( file_name );\n\n    // size the vector appropriately\n    image_vector.resize( info.pixels_per_image );\n\n    // eat the header\n    fin >> magic_number >> width >> height >> granularity;\n    fin.get(); // and an endline char\n\n    // read in the data to a column vector\n    for( pixel_num = 0; pixel_num < info.pixels_per_image; pixel_num++ )\n    {\n        // read in the byte, convert to float\n        pixel_byte = fin.get();\n        image_vector( pixel_num ) = (double) pixel_byte;\n    }\n\n    // close the file\n    fin.close();\n\n    return read_success;\n}\n\n\nint trainMeanFace( VectorXd& mean_face,  const Matrix<double, Dynamic, Dynamic>& face_data, const JobInfo& info )\n{\n    int mean_success = NO_ERRORS;\n    int image_num = 0, pixel_num = 0;\n\n    mean_face.resize( info.pixels_per_image );\n\n    for( pixel_num = 0; pixel_num < info.pixels_per_image; pixel_num++ )\n    {\n        for( image_num = 0, mean_face( pixel_num ) = 0;\n             image_num < info.num_training_images;\n             image_num++ )\n        {\n            mean_face( pixel_num ) += face_data( pixel_num, image_num );\n        }\n\n        mean_face( pixel_num ) /= info.num_training_images;\n    }\n\n\n#if 1\nwritePgmImage( \"mean_training_face.pgm\", mean_face, info.width_in_pixels,\n               info.height_in_pixels, 255 );\n\nwriteVectorToFile( \"mean_training_face_data.txt\", mean_face );\n#endif\n\n    return mean_success;\n}\n\n\nint writeVectorToFile( const char* file_name, const VectorXd& data_vector )\n{\n    int write_success = NO_ERRORS;\n    ofstream fout;\n    int i = 0;\n\n    fout.clear();\n    fout.open( file_name );\n    fout << data_vector.size() << endl;\n    fout<< data_vector << endl;\n\n    return write_success;\n}\n\n\nint centerFaceData( Matrix<double, Dynamic, Dynamic>& centered_data, Matrix<double, Dynamic, Dynamic>& face_data, const VectorXd& mean_face, const JobInfo& info )\n{\n    int centering_success = NO_ERRORS;\n    int image_number = 0, pixel_number = 0;\n\n    centered_data.resize( face_data.rows(), face_data.cols() );\n\n    for( image_number = 0; image_number < info.num_training_images; image_number++ )\n    {\n        for( pixel_number = 0; pixel_number < info.pixels_per_image; pixel_number++ )\n        {\n            centered_data( pixel_number, image_number ) = face_data( pixel_number, image_number ) - mean_face( pixel_number );\n        }\n    }\n\n\n#if 0\nwritePgmImage( \"test_center.pgm\", centered_data.col( 5 ), info.width_in_pixels,\n               info.height_in_pixels, 255 );\n#endif\n\n    return centering_success;\n}\n\n\nint findFaceCovariance( Matrix<double, Dynamic, Dynamic>& face_covariance,\n                        const Matrix<double, Dynamic, Dynamic>& centered_data,\n                        const JobInfo& info )\n{\n    int covariance_success = NO_ERRORS;\n    double inverse_num_training_images = 1.0 / info.num_training_images;\n\n    face_covariance.resize( info.pixels_per_image, info.pixels_per_image );\n\n    face_covariance = inverse_num_training_images *\n                      ( centered_data * centered_data.transpose().eval() );\n\n    return covariance_success;\n}\n\n\nbool compareEigenvalIndexPairs( const pair< double, int >& one,\n                                const pair< double, int >& other )\n{\n    // this makes for a high to low sort when used with std::sort\n    return ( one.first > other.first );\n}\n\n\ndouble getVectorMagnitude( const VectorXd the_vector )\n{\n    double magnitude = 0.0;\n    int i = 0;\n\n    for( i = 0; i < the_vector.size(); i++ )\n    {\n        magnitude += ( the_vector( i ) * the_vector( i ) );\n    }\n\n    return sqrt( magnitude );\n}\n\n\nint writePgmImage( const string& file_name, const VectorXd& image_data, int image_width, int image_height, int image_shades )\n{\n    int write_success = NO_ERRORS;\n    ofstream fout;\n    int pixel_num = 0;\n    int row_sizer = 0;\n    int num_pixels = image_width * image_height;\n\n    fout.clear();\n    fout.open( file_name.c_str() );\n\n\n    // write header with PGM \"magic number\" for binary type\n    fout << \"P5\" << '\\n' << image_width << ' '\n         << image_height << '\\n' << image_shades << '\\n';\n\n    // write the data\n    for( pixel_num = 0; pixel_num < num_pixels; pixel_num++ )\n    {\n        fout << (unsigned char) ((unsigned int)image_data( pixel_num ) % (image_shades + 1));\n    }\n\n#if 0\n    // write header with PGM \"magic number\" for ASCII type\n    fout << \"P2\" << ' ' << image_width << ' '\n         << image_height << ' ' << image_shades << '\\n';\n\n    // write the data\n    for( pixel_num = 0; pixel_num < num_pixels; pixel_num++ )\n    {\n        fout << (unsigned int) image_data( pixel_num ) % image_shades;\n        row_sizer++;\n        if( row_sizer < image_width )\n        {\n            fout << ' ';\n        }\n        else\n        {\n            row_sizer = 0;\n            fout << '\\n';\n        }\n    }\n#endif\n    fout.close();\n\n    return write_success;\n}\n\n\nint findEigenValuesVectors( VectorXd& eigenvalues, MatrixXd& eigenvectors, const MatrixXd& A_matrix, const JobInfo& info )\n{\n    EigenSolver<MatrixXd> eigen_solver;\n    Matrix<double, Dynamic, Dynamic> At_A_matrix;   // A^t * A matrix\n    Matrix<double, Dynamic, Dynamic> interim_eigenvectors;\n    vector< pair< double, int> > eigen_indices;\n    pair< double, int > temp;\n    int i = 0;\n    char buffer[100];\n\n    // compute the A^t * A matrix to save on computations vs A * A^t\n    At_A_matrix = A_matrix.transpose().eval() * A_matrix;\n\n    // compute the eigen-stuff of the matrix\n    eigen_solver.compute( At_A_matrix );\n\n    // identify the strictly real eigen values and vectors\n    for( i = 0; i < eigen_solver.eigenvalues().size(); i++ )\n    {\n        if( ( eigen_solver.eigenvalues().imag()( i ) == 0.0 ) )\n        {\n            temp.first = eigen_solver.eigenvalues().real()( i );\n            temp.second = i;\n            eigen_indices.push_back( temp );\n        }\n    }\n\n    // sort the eigen stuff in descending order by eigen value\n    sort( eigen_indices.begin(), eigen_indices.end(),\n          compareEigenvalIndexPairs );\n\n    // store the eigen-stuff in usable objects\n    eigenvalues.resize( eigen_indices.size() );\n    interim_eigenvectors.resize( A_matrix.cols(), eigen_indices.size() );\n    eigenvectors.resize( A_matrix.rows(), eigen_indices.size() );\n    for( i = 0; i < eigen_indices.size(); i++ )\n    {\n        eigenvalues( i ) = eigen_indices[i].first;\n        interim_eigenvectors.col( i ) = eigen_solver.eigenvectors().col( eigen_indices[i].second ).real();\n    }\n\n    // get from Av to u for actual eigenvectors\n    for( i = 0; i < eigenvectors.cols(); i++ )\n    {\n        // get the u vector\n        eigenvectors.col( i ) = (A_matrix * interim_eigenvectors.col( i ));\n\n        // make it a unit u vector\n        eigenvectors.col( i ) /= getVectorMagnitude( eigenvectors.col( i ) );\n    }\n\n    for( i = 0; i < eigenvalues.size(); i++ )\n    {\n        sprintf( buffer, \"eigenfaces/eigenface_%d.pgm\", i );\n\n        writePgmImage( buffer, scaleImageToPgm( eigenvectors.col( i ), info ), info.width_in_pixels,\n               info.height_in_pixels, 255 );\n    }\n\n    return 0;\n}\n\n\nVectorXd scaleImageToPgm( const VectorXd& image_data, const JobInfo& info )\n{\n    VectorXd scaled_vector;\n    double minimum_value = image_data( 0 );\n    double maximum_value = image_data( 0 );\n    int pixel_num = 0;\n\n    scaled_vector.resize( image_data.size() );\n    scaled_vector = image_data;\n\n    // find the minimum and maximum values for scaling\n    for( pixel_num = 0; pixel_num < image_data.size(); pixel_num++ )\n    {\n        if( image_data( pixel_num ) < minimum_value )\n        {\n            minimum_value = image_data( pixel_num );\n        }\n\n        if( image_data( pixel_num ) > maximum_value )\n        {\n            maximum_value = image_data( pixel_num );\n        }\n    }\n\n    // scale the pixel values properly\n    for( pixel_num = 0; pixel_num < image_data.size(); pixel_num++ )\n    {\n        scaled_vector( pixel_num ) = image_data( pixel_num ) - minimum_value;\n    }\n    maximum_value -= minimum_value;\n    scaled_vector *= ( 255.0 / (maximum_value ));//- minimum_value ));\n\n    return scaled_vector;\n}\n\n\nint storeEigenData( const VectorXd& eigenvalues, const MatrixXd& eigenvectors )\n{\n    int storage_success = NO_ERRORS;\n    ofstream fout;\n    int i = 0;\n    int j = 0;\n\n    fout.clear();\n    fout.open( \"EIGENVALUES.txt\" );\n    fout << eigenvalues.size() << endl;\n    for( i = 0; i < eigenvalues.size(); i++ )\n    {\n        fout << eigenvalues( i ) << endl;\n    }\n    fout.close();\n\n    fout.clear();\n    fout.open( \"EIGENVECTORS.txt\" );\n    fout << eigenvectors.rows() << ' ' << eigenvectors.cols() << endl;\n\n    fout << eigenvectors << endl;\n\n    fout.close();\n\n    return storage_success;\n}\n\n\nint promptForNumEigens( const VectorXd& eigenvalues )\n{\n    int num_eigens_to_keep = 0;\n    double eigenvalue_sum = 0;\n    double kept_eigenvalue_sum = 0;\n    char response;\n    bool keep_prompting = true;\n    int i = 0;\n\n    for( i = 0; i < eigenvalues.size(); i++ )\n    {\n        eigenvalue_sum += eigenvalues( i );\n    }\n\n    while( keep_prompting )\n    {\n        cout << \"How many eigen values (faces) should be kept? (\"\n             << eigenvalues.size() << \" available): \";\n        cin >> num_eigens_to_keep;\n // use 16 for ~80%\n\n        for( kept_eigenvalue_sum = 0, i = 0; i < num_eigens_to_keep; i++ )\n        {\n            kept_eigenvalue_sum += eigenvalues( i );\n        }\n\n        cout << ( kept_eigenvalue_sum * 100 / eigenvalue_sum )\n             << \"% of the information will be kept. Is this acceptable? (y/n): \";\n        cin >> response;\n\n        if( response == 'y' )\n        {\n            keep_prompting = false;\n        }\n    }\n\n    return num_eigens_to_keep;\n}\n\n\nint storeEigenProjections( const int eigens_to_keep, const MatrixXd& centered_data, const MatrixXd& eigenvectors, const JobInfo& info )\n{\n    int eigenprojection_success = NO_ERRORS;\n    VectorXd projected_face;\n    MatrixXd eigen_weights;\n    char buffer[100];\n    ofstream fout;\n    int i = 0;\n    int j = 0;\n\n    // initial setup and resizing\n    eigen_weights.resize( eigens_to_keep, centered_data.cols() );\n    projected_face.resize( info.pixels_per_image );\n\n    for( j = 0; j < centered_data.cols(); j++ )\n    {\n       // eigen_weights.col( j ) = projectImageInEigenspace( centered_data.col( j ), eigenvectors );\n\n        for( i = 0; i < eigens_to_keep; i++ )\n        {\n            eigen_weights( i, j ) = eigenvectors.col( i ).transpose().eval() * centered_data.col( j );\n        }\n\n    }\n\n    for( j = 0; j < centered_data.cols(); j++ )\n    {\n        projected_face *= 0;\n\n        for( i = 0; i < eigens_to_keep; i++ )\n        {\n            projected_face += eigen_weights( i, j ) * eigenvectors.col( i );\n        }\n\n        sprintf( buffer, \"training_eigenprojections/projected_face_%d_coefficients.txt\", j );\n        writeEigenweightFile( buffer, eigen_weights.col( j ) );\n\n        sprintf( buffer, \"training_eigenprojections/projected_face_%d.pgm\", j );\n        writePgmImage( buffer, scaleImageToPgm( projected_face, info ), info.width_in_pixels,\n               info.height_in_pixels, 255 );\n    }\n\n    return eigenprojection_success;\n}\n\n\nint writeEigenweightFile( const char* file_name, const VectorXd& eigen_weights )\n{\n    int write_success = NO_ERRORS;\n    ofstream fout;\n\n    fout.clear();\n    fout.open( file_name );\n\n    fout << eigen_weights.size() << endl;\n    fout << eigen_weights << endl;\n    \n    fout.close();\n\n    return write_success;\n}\n\n\nint testingMode( JobInfo& info )\n{\n    int testing_success = NO_ERRORS;\n    VectorXd mean_face;\n    VectorXd eigenvalues;\n    MatrixXd eigenvectors;\n    MatrixXd testing_faces;\n    MatrixXd centered_test_faces;\n    MatrixXd training_eigenweights;\n    MatrixXd testing_eigenweights;\n    int num_eigens_to_use = 0;\n    vector< MatchResult > matching_results;\n    double threshold = 1.0;\n    ofstream fout;\n    int i = 0;\n    int true_positive = 0, false_positive = 0, total_positive = 0, total_negative = 0;\n\n    info.pixels_per_image = findSampleImageSize( info.width_in_pixels,\n                                                 info.height_in_pixels,\n                                                 info.training_image_names[0] );\n\n    puts( \"Loading training outcomes...\\n\" );\n    loadTrainingOutcomes( mean_face, eigenvalues, eigenvectors, training_eigenweights, info );\n\n    puts( \"Projecting inputs onto eigenspace...\\n\" );\n    loadTestingData( testing_faces, info );\n    centerTestData( centered_test_faces, testing_faces, mean_face, info );\n    projectDataInEigenspace( testing_eigenweights, centered_test_faces, eigenvectors );\n\n    puts( \"Matching inputs to training images...\\n\" );\n    fout.clear()\n    fout.open( \"ROC.txt\" );\n    fout << \"True positives, total positives, false negatives, total negatives\" << endl;\n    for( threshold = 0.0001, true_positive = 0, false_positive = 0, total_positive = 0, total_negative = 0;\n           threshold < 0.004; threshold += 0.0005 )\n    {\n        num_eigens_to_use = 114; //promptForNumEigens( eigenvalues );\n        // threshold = 1.5; // promptForThreshold();\n        matchAllImages( matching_results, training_eigenweights, testing_eigenweights, eigenvalues, threshold, num_eigens_to_use, info );\n\n        puts( \"Outputting matching data...\\n\" );\n        outputDataSummary( matching_results, threshold, num_eigens_to_use, false );\n\n        for( i = 0; i < matching_results.size(); i++ );\n        \n\n\n    }\n\n    return testing_success;\n}\n\n\nint loadTrainingOutcomes( VectorXd& mean_face, VectorXd& eigenvalues, MatrixXd& eigenvectors, MatrixXd& training_eigenweights, const JobInfo& info )\n{\n    int load_success = NO_ERRORS;\n    int i = 0;\n    VectorXd temp;\n\n    readDataVectorFromTxt( mean_face, \"mean_training_face_data.txt\" );\n    readDataVectorFromTxt( eigenvalues, \"EIGENVALUES.txt\" );\n    readMatrixFromTxt( eigenvectors, \"EIGENVECTORS.txt\" );\n\ncout << eigenvalues.size() << endl;\n\n    training_eigenweights.resize( 1204, eigenvectors.cols() );\n    for( i = 0; i < info.num_training_eigenweights; i++ )\n    {\n        readDataVectorFromTxt( temp, info.training_eigenweight_names[i] );\n        training_eigenweights.col( i ) = temp;\n    }\n\n    return load_success;\n}\n\n\nint readDataVectorFromTxt( VectorXd& data_vector, const char* file_name )\n{\n    int read_success = NO_ERRORS;\n    ifstream fin;\n    int size;\n    double value;\n    int i;\n\n    fin.clear();\n    fin.open( file_name );\n\n    if( fin.good() )\n    {\n        fin >> size;\n        data_vector.resize( size );\n\n        for( i = 0; i < size; i++ )\n        {\n            fin >> value;\n            data_vector( i ) = value;\n        }\n    }\n\n    return read_success;\n}\n\n\nint readMatrixFromTxt( MatrixXd& data_matrix, const char* file_name )\n{\n    int read_success = NO_ERRORS;\n    ifstream fin;\n    int rows, cols;\n    double value;\n    int i = 0, j = 0;\n\n    fin.clear();\n    fin.open( file_name );\n\n    if( fin.good() )\n    {\n        fin >> rows >> cols;\n        data_matrix.resize( rows, cols );\n\n        for( i = 0; i < rows; i++ )\n        {\n            for( j = 0; j < cols; j++ )\n            {\n                fin >> value;\n                data_matrix( i, j ) = value;\n            }\n        }\n    }\n\n    return read_success;\n}\n\n\nint loadTestingData( Matrix<double, Dynamic, Dynamic>& face_data, const JobInfo& info )\n{\n    // variables\n    int image_num = 0;\n    VectorXd temp;\n\n    face_data.resize( info.pixels_per_image, info.num_testing_images );\n\n    // for every image\n    for( image_num = 0; image_num < info.num_testing_images; image_num++ )\n    {\n        readPgmToVector( temp, info.testing_image_names[image_num], info );\n        face_data.col( image_num ) = temp;\n    }\n\n\n#if 1\nwritePgmImage( info.training_image_names[20], face_data.col( 20 ), info.width_in_pixels,\n               info.height_in_pixels, 255 );\n#endif\n}\n\n\nint centerTestData( MatrixXd& centered_data, MatrixXd& face_data, const VectorXd& mean_face, const JobInfo& info )\n{\n    int centering_success = NO_ERRORS;\n    int image_number = 0, pixel_number = 0;\n\n    centered_data.resize( face_data.rows(), face_data.cols() );\n\n    for( image_number = 0; image_number < info.num_testing_images; image_number++ )\n    {\n        for( pixel_number = 0; pixel_number < info.pixels_per_image; pixel_number++ )\n        {\n            centered_data( pixel_number, image_number ) = face_data( pixel_number, image_number ) - mean_face( pixel_number );\n        }\n    }\n\n\n#if 0\n\nwritePgmImage( \"test_center.pgm\", centered_data.col( 5 ), info.width_in_pixels,\n               info.height_in_pixels, 255 );\n#endif\n\n    return centering_success;\n}\n\nint projectDataInEigenspace( MatrixXd& eigenweights, const MatrixXd& data, const MatrixXd& eigenvectors )\n{\n    int eigenprojection_success = NO_ERRORS;\n    int j = 0;\n\n    // initial setup and resizing\n    eigenweights.resize( eigenvectors.cols(), data.cols() );\n\n    for( j = 0; j < data.cols(); j++ )  // for each image\n    {\n        eigenweights.col( j ) = projectImageInEigenspace( data.col( j ), eigenvectors );\n\n/*\n        for( i = 0; i < eigenvectors.cols(); i++ ) // for each feature/weight\n        {\n            eigenweights( i, j ) = eigenvectors.col( i ).transpose().eval() * data.col( j );\n        }\n*/\n    }\n\n    return eigenprojection_success;\n}\n\n\nVectorXd projectImageInEigenspace( const VectorXd& centered_image, const MatrixXd& eigenvectors  )\n{\n    VectorXd weight_vector;\n    int i = 0;\n\n    weight_vector.resize( eigenvectors.cols() );\n\n    for( i = 0; i < eigenvectors.cols(); i++ ) // for every eigenvector\n    {\n        weight_vector( i ) = eigenvectors.col( i ).transpose().eval() * centered_image;\n    }\n\n    return weight_vector;\n}\n\n\ndouble promptForThreshold()\n{\n    double threshold;\n\n    cout << \"Enter the threshold value to be used: \";\n    cin >> threshold;\n\n    return threshold;   \n}\n\n\nint matchAllImages( vector< MatchResult >& matching_results,\n                 const MatrixXd& training_eigenweights,\n                 const MatrixXd& testing_eigenweights,\n                 const MatrixXd& eigenvalues,\n                 const double threshold,\n                 const int num_eigens_to_use,\n                 const JobInfo& info )\n{\n    int matching_success;\n    int i = 0;\n    int j = 0;\n    double temp_distance = 0;\n    double distance = 0;\n    MatchResult temp;\n\n    for( i = 0; i < testing_eigenweights.cols(); i++ )\n    {\n        strcpy( temp.tested_image_name, stripFilePath( info.testing_image_names[i] ) );\n\n        matchImage( temp, testing_eigenweights.col( i ), training_eigenweights, eigenvalues, num_eigens_to_use, threshold, info );\n\n        matching_results.push_back( temp );\n    }\n\n    return matching_success;\n}\n\n\nint matchImage( MatchResult& result, const VectorXd& test_weights,\n                const MatrixXd& training_weights, const VectorXd& eigenvalues,\n                const int num_eigens_to_use, const double threshold,\n                const JobInfo& info )\n{\n    int match_function_success = NO_ERRORS;\n    int i = 0;\n    double temp_distance = 2E64;\n    int CMC_counter = 0;\n\n    // check against all other sets of weights\n    for( i = 0, result.distance_between_images = 2E64; i < training_weights.cols(); i++ )\n    {\n        // find the distance between the image and a training one\n        temp_distance = computeMahalanobisDistance( test_weights, training_weights.col( i ), eigenvalues, num_eigens_to_use );\n\n        // case: the distance is better than what was thought to be the previous best\n        if( temp_distance < result.distance_between_images )\n        {\n            // update the index of the match and the new, lower distance\n            result.distance_between_images = temp_distance;\n            result.matched_image_index = i;\n        }\n\n        if( atoi(result.tested_image_name) == atoi( stripFilePath( info.training_image_names[ i ] ) )\n            && temp_distance < threshold )\n        {\n            CMC_counter++;\n        }\n\n    }\n\ncout << \"CMC\" << CMC_counter << endl;\n\n    // indicate which image the test one is closest to\n    strcpy( result.matched_image_name,\n            stripFilePath( info.training_image_names[ result.matched_image_index ] ) );\n\n    // case: the best distance could be considered a match\n    if( result.distance_between_images < threshold )\n    {\n        // indicate that there was a match, get matching image's name\n        result.is_match_by_test = MATCH;\n    }\n    // case: the distance does not indicate a match\n    else\n    {\n        result.is_match_by_test = NO_MATCH;\n    }\n\n    // determine if the images are an actual match\n    // NOTE: I expect the atoi to read just the first segment of the image name, up to the first underscore\n    if( atoi( result.tested_image_name ) == atoi( result.matched_image_name ) )\n    {\n        result.is_actual_match = MATCH;\n\ncout << result.tested_image_name << \"  \" << result.matched_image_name << \"  \" << result.is_actual_match << ' ' <<  MATCH << endl;\n\n    }\n    else\n    {\n        result.is_actual_match = NO_MATCH;\n    }\n\n    return match_function_success;\n}\n\n\ndouble computeMahalanobisDistance( const VectorXd& test_weights,\n                                   const VectorXd& training_weights,\n                                   const VectorXd& eigenvalues,\n                                   const int num_eigens_to_use )\n{\n    double mahalanobis_distance = 0;\n    double euclidean_component;\n    int i = 0;\n\n    for( i = 0; i < num_eigens_to_use; i++ )\n    {\n        euclidean_component = ( test_weights( i ) - training_weights( i ) );\n        euclidean_component *= euclidean_component;\n        mahalanobis_distance += euclidean_component / eigenvalues( i );\n    }\n\n    return mahalanobis_distance;\n}\n\n\nint outputDataSummary( vector< MatchResult >& results, double threshold, int num_eigens_to_use, bool explicit_summary )\n{\n    ofstream fout;\n    int i = 0;\n\n\n    if( explicit_summary )\n    {\n        fout.clear();\n        fout.open( \"RESULTS.txt\" );\n\n        fout << \"Test Image Name,\"\n                \"Matched Image Name,\"\n                \"Distance Between Images,\"\n                \"Is Match By Test,\"\n                \"Is Actually A Match,\"\n             << endl;    \n\n        for( i = 0; i < results.size(); i++ )\n        {\n            fout << results[i].tested_image_name << \", \"\n                 << results[i].matched_image_name << \", \"\n                 << results[i].distance_between_images << \", \"\n                 << results[i].is_match_by_test << \", \"\n                 << results[i].is_actual_match << endl;\n        }\n    }\n}\n\n\nchar* stripFilePath( char* file_name )\n{\n    char* stripped_string = file_name;\n    char* temp;\n\n    temp = strstr( stripped_string, \"/\" );\n    while( temp != NULL )\n    {\n        stripped_string = temp + 1;\n        temp = strstr( stripped_string, \"/\" );\n    }\n\n    return stripped_string;\n}\n\n\n\n", "meta": {"hexsha": "0e3ce66c9949a757448b1fcae5227d858c81dc24", "size": 37015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CS479/Project_3/driver_project_3 (2).cpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "CS479/Project_3/driver_project_3 (2).cpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "CS479/Project_3/driver_project_3 (2).cpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 28.940578577, "max_line_length": 163, "alphanum_fraction": 0.6019451574, "num_tokens": 8630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.647090267441024}}
{"text": "#include <Eigen/Dense>\n\n#include <ancse/cfl_condition.hpp>\n#include <ancse/config.hpp>\n#include <ancse/fvm_rate_of_change.hpp>\n#include <ancse/snapshot_writer.hpp>\n#include <ancse/time_loop.hpp>\n\ntemplate <class F>\nEigen::VectorXd ic(const F &f, const Grid &grid) {\n    Eigen::VectorXd u0(grid.n_cells);\n    for (int i = 0; i < grid.n_cells; ++i) {\n        u0[i] = f(cell_center(grid, i));\n    }\n\n    return u0;\n}\n\nTimeLoop make_fvm(const Grid &grid) {\n    auto config = get_global_config();\n    double t_end = config[\"t_end\"];\n    double cfl_number = config[\"cfl_number\"];\n\n    auto n_ghost = grid.n_ghost;\n    auto n_cells = grid.n_cells;\n\n    auto model = Model{};\n\n    auto simulation_time = std::make_shared<SimulationTime>(t_end);\n    auto fvm_rate_of_change\n        = make_fvm_rate_of_change(grid, model, simulation_time);\n    auto boundary_condition\n        = make_boundary_condition(n_ghost, config[\"boundary_condition\"]);\n    auto time_integrator\n        = make_runge_kutta(fvm_rate_of_change, boundary_condition, n_cells);\n    auto cfl_condition = make_cfl_condition(grid, model, cfl_number);\n    auto snapshot_writer = std::make_shared<JSONSnapshotWriter>(\n        grid, simulation_time, std::string(config[\"output\"]));\n\n    return TimeLoop(\n        simulation_time, time_integrator, cfl_condition, snapshot_writer);\n}\n\ntemplate <class F>\nvoid run_test(const F &f) {\n    auto config = get_global_config();\n\n    int n_ghost = config[\"n_ghost\"];\n    int n_cells = int(config[\"n_interior_cells\"]) + n_ghost * 2;\n\n    auto grid = Grid({0.0, 1.0}, n_cells, n_ghost);\n    auto u0 = ic(f, grid);\n\n    auto fvm = make_fvm(grid);\n    fvm(u0);\n}\n\nvoid smooth_sine_test() {\n    run_test([](double x) { return std::sin(2.0 * M_PI * x); });\n}\n\nvoid jump_test() {\n    run_test([](double x) { return (x < 0.5 ? 1.0 : 0.0); });\n}\n\nvoid backward_jump_test() {\n    run_test([](double x) { return (x < 0.5 ? -1.0 : 1.0); });\n}\n\nvoid ex2() {\n    auto config = get_global_config();\n\n    int n_ghost = config[\"n_ghost\"];\n    int n_cells = int(config[\"n_interior_cells\"]) + n_ghost * 2;\n\n    auto grid = Grid({-1.5, 3.0}, n_cells, n_ghost);\n\n    auto f = [](double x) {\n        if (x < -1.0) {\n            return 0.0;\n        } else if (x < 0.0) {\n            return 1.0;\n        } else if (x < 1.0) {\n            return 1.0 - x;\n        } else {\n            return 0.0;\n        }\n    };\n    auto u0 = ic(f, grid);\n\n    auto fvm = make_fvm(grid);\n    fvm(u0);\n}\n\nint main() {\n    auto config = get_global_config();\n\n    std::string ic_key = config[\"initial_conditions\"];\n    if (ic_key == \"sine\") {\n        smooth_sine_test();\n    } else if (ic_key == \"jump\") {\n        jump_test();\n    } else if (ic_key == \"backward-jump\") {\n        backward_jump_test();\n    } else if (ic_key == \"ex2\") {\n        ex2();\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "74fc6a42c674c07eba61705bdd8cbc282facbc79", "size": 2818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series1_solution/fvm_scalar_1d/src/fvm_scalar.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series1_solution/fvm_scalar_1d/src/fvm_scalar.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series1_solution/fvm_scalar_1d/src/fvm_scalar.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": 25.3873873874, "max_line_length": 76, "alphanum_fraction": 0.605748758, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6470902599528761}}
{"text": "// NormalGenerator.hpp\n//\n// A class hierarchy for generating random numbers, \n// vectors and matrices.\n// \n// This hierarchy uses the Template Method Pattern and it\n// delegates to a Strategy pattern for generating uniform\n// random numbers.\n//\n// The solution is object-oriented and uses run-time polymorphic\n// functions. In another chapter we use policy classes and templates.\n//\n// 2012-17 DD restrict to Boost\n//\n// (C) Datasim Education BV 2008-2012\n//\n\n#ifndef NormalGenerator_HPP\n#define NormalGenerator_HPP\n\n// boost\n#include <boost/random.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nclass NormalGenerator\n{\n\npublic:\n        \n\t// Empty at the moment\n\tvirtual double getNormal() const = 0;\n};\n\n\nclass BoostNormal : public NormalGenerator\n{\nprivate:\n\n\tboost::lagged_fibonacci607 rng;\n\tboost::normal_distribution<> nor;\n//\n\tboost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> >* myRandom;\n\n\npublic:\n\tBoostNormal();\t// NB no uniform parameters\n\n\t// Implement (variant) hook function\n\tdouble getNormal() const;\n\n\t~BoostNormal();\n};\n\n\n#endif\n", "meta": {"hexsha": "e78a970b598dc3e2a4eecd532bf20a213f23e44e", "size": 1178, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Level_9/VI.4 Monte Carlo Simulation/VI.4 Monte Carlo Simulation/RNG/NormalGenerator.hpp", "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/VI.4 Monte Carlo Simulation/VI.4 Monte Carlo Simulation/RNG/NormalGenerator.hpp", "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/VI.4 Monte Carlo Simulation/VI.4 Monte Carlo Simulation/RNG/NormalGenerator.hpp", "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": 20.3103448276, "max_line_length": 96, "alphanum_fraction": 0.746179966, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.8031737916455819, "lm_q1q2_score": 0.6470626748885364}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_EULER_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_EULER_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    GeneratesEuler constant.\n\n\n    @par Header <boost/simd/constant/euler.hpp>\n\n    @par Semantic:\n    The Euler constant can be defined as \\f$\\displaystyle \\lim_{n \\rightarrow \\infty} \\left(\\sum_1^n \\frac1n -\\log n\\right)\\f$\n\n    @code\n    T r = Euler<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n      r =  T(0.577215664901532860606512090082402431042159335939923598805767234884867726777664670936947063291746749);\n    @endcode\n\n\n**/\n  template<typename T> T Euler();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      GeneratesEuler constant.\n\n      Generate the  constant euler.\n\n      @return The Euler constant for the proper type\n    **/\n    Value Euler();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/euler.hpp>\n#include <boost/simd/constant/simd/euler.hpp>\n\n#endif\n", "meta": {"hexsha": "818a3efae8bccd684dc88d1b51ac07c554f78cef", "size": 1401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/euler.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/constant/euler.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/constant/euler.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 21.890625, "max_line_length": 126, "alphanum_fraction": 0.6002855103, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6470363038258053}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2016 Sebastian Schlenkrich\n\n*/\n\n\n\n#ifndef quantlib_templateauxilliaries_choleskyfactorisation_hpp\n#define quantlib_templateauxilliaries_choleskyfactorisation_hpp\n\n//#include <ql/types.hpp>\n//#include <boost/function.hpp>\n\n#include <stdlib.h>\n#include <math.h>\n\n\nnamespace TemplateAuxilliaries {\n\n    // This method is unsafe! Memory allocation need to be ensured by user\n    // A(i,j) (and L) is stored row-wise as A[i*n+j]\n    // L(i,j) is lower triangular matrix with L L^T = A\n    template <typename Type> \n    inline void cholesky(std::vector< Type >& A, std::vector< Type >& L, size_t n) {\n        for (size_t i = 0; i < n; ++i) {\n            for (size_t j = 0; j < (i+1); ++j) {\n                Type s = 0;\n                for (size_t k = 0; k < j; ++k) s += L[i * n + k] * L[j * n + k];\n                if (i==j) {\n                    if (A[i * n + i] < s) throw std::exception();\n                    L[i * n + j] = sqrt(A[i * n + i] - s);\n                }\n                else L[i * n + j] = (1.0 / L[j * n + j] * (A[i * n + j] - s));\n            }\n        } \n    }\n\n    template <typename Type>\n    std::vector< std::vector< Type > > cholesky(const std::vector< std::vector< Type > >& A) {\n        std::vector<Type> arrayA(A.size()*A.size());\n        std::vector<Type> arrayL(A.size()*A.size());\n        for (size_t i = 0; i < A.size(); ++i) {\n            if (A.size()!=A[i].size()) throw std::exception();\n            for (size_t j = 0; j < A[i].size(); ++j) arrayA[i*A[i].size() + j] = A[i][j];\n        }\n        cholesky(arrayA, arrayL, A.size());\n        std::vector< std::vector< Type > > L(A.size(), std::vector< Type >(A.size(), 0.0));\n        for (size_t i = 0; i < L.size(); ++i) {\n            for (size_t j = 0; j <= i; ++j) L[i][j] = arrayL[i*L[i].size() + j];\n        }\n        return L;\n    }\n\n\n    // alternative implementation of Cholesky decomposition\n    template<class T>\n    void performCholesky(std::vector< std::vector<T> >& matrix, size_t dimIn, bool flexible) {\n        size_t dim = dimIn;\n        for (size_t i = 0; i < dim; i++) {\n            for (size_t j = i; j < dim; j++) {\n                if (abs(matrix[i][j] - matrix[j][i])>QL_EPSILON)\n                    QL_FAIL(std::string(\"A symmetrix matrix is necessary to apply Cholesky Decomposition\"));\n            }\n        }\n\n        //Perform Decomposition as described in script of Trottenberg (S. 47):\n        //Because script delivers Upper right matrix, we interchange indizes in order to end up with lower left matrix.\n\n        //First step:\n        matrix[0][0] = sqrt(matrix[0][0]);\n        if (abs(matrix[0][0]) < QL_EPSILON && !flexible)\n            QL_FAIL(\"No positive definite Correlation Matrix because rank is not full.\");\n        for (size_t i = 1; i < dim; i++) {\n            matrix[i][0] = abs(matrix[0][0]) < QL_EPSILON ? 0.0 : matrix[i][0] / matrix[0][0];\n        }\n\n        //Now iterate:\n        for (size_t i = 1; i < dim; i++) {\n            for (size_t k = 0; k < i; k++) {\n                matrix[i][i] = matrix[i][i] - matrix[i][k] * matrix[i][k];\n            }\n            matrix[i][i] = sqrt(matrix[i][i]);\n            if (abs(matrix[i][i]) < QL_EPSILON && !flexible)\n                QL_FAIL(std::string(\"No positive definite Correlation Matrix because rank is not full.\"));\n            if (matrix[i][i] != matrix[i][i] && !flexible) {\n                QL_FAIL(std::string(\"No positive definite Correlation Matrix as diagonal square entry is negative.\"));\n            }\n            matrix[i][i] = (matrix[i][i] != matrix[i][i]) ? 0.0 : matrix[i][i];\n            for (size_t j = 0; j < dim; j++) {\n                if (j >= i + 1) {\n                    for (size_t k = 0; k < i; k++) {\n                        matrix[j][i] = matrix[j][i] - matrix[i][k] * matrix[j][k];\n                    }\n                    matrix[j][i] = (abs(matrix[i][i]) < QL_EPSILON || matrix[i][i] != matrix[i][i]) ? 0.0 : matrix[j][i] / matrix[i][i];\n                }\n                else if (j<i) {\n                    matrix[j][i] = 0;\n                }\n                else {\n                    //Nothing because diagonale.\n                }\n            }\n        }\n    }\n\n\n}\n\n#endif  /* ifndef quantlib_templateauxilliaries_qrfactorisation_hpp */\n", "meta": {"hexsha": "ffe90ce1a0fe4843305c5f59da3192c6d930b8af", "size": 4339, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/auxilliaries/choleskyfactorisationT.hpp", "max_stars_repo_name": "sschlenkrich/quantlib", "max_stars_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/experimental/templatemodels/auxilliaries/choleskyfactorisationT.hpp", "max_issues_repo_name": "sschlenkrich/quantlib", "max_issues_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/templatemodels/auxilliaries/choleskyfactorisationT.hpp", "max_forks_repo_name": "sschlenkrich/quantlib", "max_forks_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7410714286, "max_line_length": 136, "alphanum_fraction": 0.4906660521, "num_tokens": 1252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6470000333142462}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nint main()\n{\nusing Eigen::Quaterniond;\nusing Eigen::Vector3d;\nEigen::Quaterniond q(2, 0, 1, -3); \n\n  std::cout << \"This quaternion consists of a scalar \" << q.w() << \" and a vector \" << std::endl << q.vec() << std::endl;\n\n\n  q.normalize();\n\n  std::cout << \"To represent rotation, we need to normalize it such that its length is \" << q.norm() << std::endl;\n\n\n  Eigen::Vector3d v(1, 2, -1);\n\n  Eigen::Quaterniond p;\n\n  p.w() = 0;\n\n  p.vec() = v;\n\n  Eigen::Quaterniond rotatedP = q * p * q.inverse(); \n\n  Eigen::Vector3d rotatedV = rotatedP.vec();\n\n  std::cout << \"We can now use it to rotate a vector \" << std::endl << v << \" to \" << std::endl << rotatedV << std::endl;\n\n\n  Eigen::Matrix3d R = q.toRotationMatrix(); // convert a quaternion to a 3x3 rotation matrix\n\n  std::cout << \"Compare with the result using an rotation matrix \" << std::endl << R * v << std::endl;\n\n \n\n  Eigen::Quaterniond a = Eigen::Quaterniond::Identity();\n\n  Eigen::Quaterniond b = Eigen::Quaterniond::Identity();\n\n  Eigen::Quaterniond c; // Adding two quaternion as two 4x1 vectors is not supported by the EIgen API. That is, c = a + b is not allowed. We have to do this in a hard way\n\n  c.w() = a.w() + b.w();\n\n  c.x() = a.x() + b.x();\n\n  c.y() = a.y() + b.y();\n\n  c.z() = a.z() + b.z();\n}\n", "meta": {"hexsha": "b6f83c0bd6836b6b06f1090deaa651a3f85eb4f5", "size": 1308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "quaternionExample.cpp", "max_stars_repo_name": "nearlab/rover_visual_od", "max_stars_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quaternionExample.cpp", "max_issues_repo_name": "nearlab/rover_visual_od", "max_issues_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quaternionExample.cpp", "max_forks_repo_name": "nearlab/rover_visual_od", "max_forks_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.679245283, "max_line_length": 170, "alphanum_fraction": 0.6039755352, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6469945816618062}}
{"text": "#include <iostream>\n#include <boost/math/special_functions/bessel.hpp>\n\n#include \"gauss_lobatto.hpp\"\n\ndouble f(double x)\n{\n    return std::exp(std::sin(M_PI*x));\n}\n\nbool test_gauss_lobatto()\n{\n    quad_rule a = gauss_lobatto<double>(9);\n\n    double I = 0;\n    for (int i=0; i < a.x.size(); ++i)\n        I += f(a.x[i])*a.w[i];\n    \n    double e1 = std::abs(I - 2*boost::math::cyl_bessel_i(0,1.0));\n\n    quad_rule b = gauss_lobatto<double>(10);\n\n    I = 0;\n    for (int i=0; i < b.x.size(); ++i)\n        I += f(b.x[i]) * b.w[i];\n    \n    double e2 = std::abs(I - 2*boost::math::cyl_bessel_i(0,1.0));\n\n    bool passed = true;\n\n    if (e1 > 1e-4)\n    {\n        std::cout << \"gauss_lobatto() failed accuracy test.\\n\";\n        passed = false;\n    }\n\n    if (e2 > e1)\n    {\n        std::cout << \"gauss_lobatto() failed convergence test.\\n\";        \n        passed = false;\n    }\n\n    return passed;\n}", "meta": {"hexsha": "6d5e8041e2b17796c6b6131f65a609bcfdd07f4a", "size": 893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/gauss_lobatto.cpp", "max_stars_repo_name": "arotem3/SchrodingerSEM", "max_stars_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/gauss_lobatto.cpp", "max_issues_repo_name": "arotem3/SchrodingerSEM", "max_issues_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/gauss_lobatto.cpp", "max_forks_repo_name": "arotem3/SchrodingerSEM", "max_forks_repo_head_hexsha": "b1d5c5a959efe46cb8d473f284d150c3c7f0beb6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2954545455, "max_line_length": 74, "alphanum_fraction": 0.5375139978, "num_tokens": 297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.6469711437913619}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <ctime>\n\nusing namespace std;\nusing namespace arma;\n\nconst double pi  =3.141592653589793238462;\nint n,k;  // nrow(X),ncol(X)\nmat z,X,y,XXi,Xt;\nconst double a=1;\nconst double b=1;\nconst int B=pow(10,5);\nconst double s2 = 10;\n\ndouble ll(mat be, double sig2) {\n  mat c(1,k), out(k,1);\n\n  c = y-X*be;\n  out = (c.t()*c / sig2 + n*log(sig2))/-2;\n  \n  return as_scalar(out);\n}\n\ndouble lpb(mat be) {\n  return as_scalar(-be.t()*XXi*be/(2*s2));\n}\n\ndouble lps(double sig2) {\n  return (a-1) * log(sig2) - sig2/b;\n}\n\nmat mvrnorm(mat M, mat S) {\n  int n = M.n_rows;\n  mat e = randn(n);\n  return M + chol(S).t()*e;\n}\n\nint main(int argc, char** argv) {\n  mat mle;\n\n  //posteriors:\n  mat bb; \n  mat ss;\n\n  // candidate sigma:\n  mat csb;\n  const double css = 1;\n\n  //candidate values:\n  mat candb;\n  double cands;\n  \n  //acceptance rates:\n  int accb = 0;\n  int accs = 0;\n\n  //metropolis ratio:\n  double q;\n\n  z.load(\"../data/dat.txt\");\n  n = z.n_rows;\n  k = z.n_cols-1;\n\n  y = z.col(0);\n  X = z.cols(1,k); // columns 2 to k+1 of z\n  Xt = X.t();\n  XXi = (Xt*X).i();\n  csb = 4*XXi;\n  mle = XXi * Xt * y;\n  \n  bb.set_size(B,k);\n  ss.set_size(B,1);\n  bb.zeros();\n  ss.ones();\n\n  //current vals:\n  mat bc = bb.row(0);\n  double sc = 1.0;\n\n  cout << \"Starting Metropolis:\" <<endl;\n  clock_t t1 = clock();\n  for (int i=1; i<B; i++) {\n    // Set Initial Values:\n    bb.row(i) = bb.row(i-1);\n    ss.at(i,0) = sc;\n    bc = bb.row(i).t();\n\n    //Update Beta:\n    candb = mvrnorm(bc,csb);\n    q = ll(candb,sc)+lpb(candb) -ll(bc,sc)-lpb(bc);\n    if (q>log(randu())) {\n      bc = candb;\n      bb.row(i) = bc.t();\n      accb++;\n    }\n\n    //Update sigma2:\n    cands = randn()*sqrt(css)+sc;\n    if (cands>0){\n      q = ll(bc,cands)+lps(cands) -ll(bc,sc)-lps(sc);\n      if (q>log(randu())) {\n        sc = cands;\n        accs++;\n      }\n    }\n    \n    cout << \"\\r\" << i*100/B <<\"%\";\n  }\n  clock_t t2 = clock();\n  double elapsed = double(t2-t1) / CLOCKS_PER_SEC;\n  cout << \"Elapsed Time: \" <<elapsed<<\"s. \\n\"<<endl;\n\n  cout << \"Posterior Means Beta: \\n\" << \n          mean(bb.rows(90000,100000-1)).t()<<endl;\n  cout << \"Posterior Mean Sigma2: \\n\" <<\n          mean(ss.rows(90000,100000-1))<<endl;\n  cout << \"Beta Acceptance:   \"<< 100*accb/B <<\"%\"<<endl;\n  cout << \"Sigma2 Acceptance: \"<< 100*accs/B <<\"%\"<<endl;\n  cout <<endl;\n  //ss.save(\"s2.txt\",raw_ascii);\n\n  return 0;\n}\n", "meta": {"hexsha": "5c77cd524be92d99ff7a427a9bb1401bdf2c01f8", "size": 2388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_posts/langcompare/code/raw.cpp", "max_stars_repo_name": "luiarthur/padawan", "max_stars_repo_head_hexsha": "027f3f1ae4fea211f38ee0f37d6184700285e3cf", "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": "_posts/langcompare/code/raw.cpp", "max_issues_repo_name": "luiarthur/padawan", "max_issues_repo_head_hexsha": "027f3f1ae4fea211f38ee0f37d6184700285e3cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-05-17T22:59:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T01:19:59.000Z", "max_forks_repo_path": "_posts/langcompare/code/raw.cpp", "max_forks_repo_name": "luiarthur/padawan", "max_forks_repo_head_hexsha": "027f3f1ae4fea211f38ee0f37d6184700285e3cf", "max_forks_repo_licenses": ["Apache-2.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.104, "max_line_length": 57, "alphanum_fraction": 0.540201005, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6469695650745978}}
{"text": "// Test ../include/LinAlg/UpperHessenbergEigen.h and\n//      ../include/LinAlg/TridiagEigen.h\n#include <LinAlg/UpperHessenbergEigen.h>\n#include <LinAlg/TridiagEigen.h>\n#include <Eigen/Eigenvalues>\n#include <ctime>\n\nusing namespace Spectra;\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::MatrixXcd;\nusing Eigen::VectorXcd;\n\nTEST_CASE(\"Eigen decomposition of upper Hessenberg matrix\", \"[Eigen]\")\n{\n    std::srand(123);\n    int n = 100;\n    MatrixXd m = MatrixXd::Random(n, n);\n    m.array() -= 0.5;\n    MatrixXd H = m.triangularView<Eigen::Upper>();\n    H.diagonal(-1) = m.diagonal(-1);\n\n    UpperHessenbergEigen<double> decomp(H);\n    VectorXcd evals = decomp.eigenvalues();\n    MatrixXcd evecs = decomp.eigenvectors();\n\n    MatrixXcd err = H * evecs - evecs * evals.asDiagonal();\n\n    INFO( \"||HU - UD||_inf = \" << err.cwiseAbs().maxCoeff() );\n    REQUIRE( err.cwiseAbs().maxCoeff() == Approx(0.0) );\n\n    clock_t t1, t2;\n    t1 = clock();\n    for(int i = 0; i < 100; i++)\n    {\n        UpperHessenbergEigen<double> decomp(H);\n        VectorXcd evals = decomp.eigenvalues();\n        MatrixXcd evecs = decomp.eigenvectors();\n    }\n    t2 = clock();\n    std::cout << \"elapsed time for UpperHessenbergEigen: \"\n              << double(t2 - t1) / CLOCKS_PER_SEC << \" secs\\n\";\n\n    t1 = clock();\n    for(int i = 0; i < 100; i++)\n    {\n        Eigen::EigenSolver<MatrixXd> decomp(H);\n        VectorXcd evals = decomp.eigenvalues();\n        MatrixXcd evecs = decomp.eigenvectors();\n    }\n    t2 = clock();\n    std::cout << \"elapsed time for Eigen::EigenSolver: \"\n              << double(t2 - t1) / CLOCKS_PER_SEC << \" secs\\n\";\n}\n\nTEST_CASE(\"Eigen decomposition of symmetric tridiagonal matrix\", \"[Eigen]\")\n{\n    std::srand(123);\n    int n = 100;\n    MatrixXd m = MatrixXd::Random(n, n);\n    m.array() -= 0.5;\n    MatrixXd H = MatrixXd::Zero(n, n);\n    H.diagonal() = m.diagonal();\n    H.diagonal(-1) = m.diagonal(-1);\n    H.diagonal(1) = m.diagonal(-1);\n\n    TridiagEigen<double> decomp(H);\n    VectorXd evals = decomp.eigenvalues();\n    MatrixXd evecs = decomp.eigenvectors();\n\n    MatrixXd err = H * evecs - evecs * evals.asDiagonal();\n\n    INFO( \"||HU - UD||_inf = \" << err.cwiseAbs().maxCoeff() );\n    REQUIRE( err.cwiseAbs().maxCoeff() == Approx(0.0) );\n\n    clock_t t1, t2;\n    t1 = clock();\n    for(int i = 0; i < 100; i++)\n    {\n        TridiagEigen<double> decomp(H);\n        VectorXd evals = decomp.eigenvalues();\n        MatrixXd evecs = decomp.eigenvectors();\n    }\n    t2 = clock();\n    std::cout << \"elapsed time for TridiagEigen: \"\n              << double(t2 - t1) / CLOCKS_PER_SEC << \" secs\\n\";\n\n    t1 = clock();\n    for(int i = 0; i < 100; i++)\n    {\n        Eigen::SelfAdjointEigenSolver<MatrixXd> decomp(H);\n        VectorXd evals = decomp.eigenvalues();\n        MatrixXd evecs = decomp.eigenvectors();\n    }\n    t2 = clock();\n    std::cout << \"elapsed time for Eigen::SelfAdjointEigenSolver: \"\n              << double(t2 - t1) / CLOCKS_PER_SEC << \" secs\\n\";\n}\n", "meta": {"hexsha": "73893a17b842357ca3f0f48400ad136be10479ec", "size": 3034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/spectra/test/Eigen.cpp", "max_stars_repo_name": "maxchernet/TheiaSfM", "max_stars_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 770.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T14:32:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:54:33.000Z", "max_issues_repo_path": "libraries/spectra/test/Eigen.cpp", "max_issues_repo_name": "maxchernet/TheiaSfM", "max_issues_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 237.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T18:50:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T05:21:48.000Z", "max_forks_repo_path": "libraries/spectra/test/Eigen.cpp", "max_forks_repo_name": "maxchernet/TheiaSfM", "max_forks_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 278.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T06:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:25:21.000Z", "avg_line_length": 29.4563106796, "max_line_length": 75, "alphanum_fraction": 0.5992089651, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6469695650745978}}
{"text": "#ifndef _COCONUT_PULP_MATH_ANGLE_HPP_\n#define _COCONUT_PULP_MATH_ANGLE_HPP_\n\n#include <iosfwd>\n\n#include <boost/operators.hpp>\n\nnamespace coconut {\nnamespace pulp {\nnamespace math {\n\nconst float PI = static_cast<float>(3.14159264f);\n\nclass Angle :\n\tboost::less_than_comparable<Angle,\n\tboost::equality_comparable<Angle,\n\tboost::additive<Angle,\n\tboost::multiplicative<Angle, float>>>>\n{\npublic:\n\n\tstatic const Angle RIGHT;\n\n\tstatic const Angle HALF_FULL;\n\n\tstatic const Angle FULL;\n\n\tconstexpr float radians() const noexcept {\n\t\treturn radians_;\n\t}\n\n\tconstexpr float degrees() const noexcept {\n\t\treturn radians_ * (180.0f / PI);\n\t}\n\n\tconstexpr bool operator==(const Angle& rhs) const noexcept {\n\t\treturn radians_ == rhs.radians_;\n\t}\n\n\tconstexpr bool operator<(const Angle& rhs) const noexcept {\n\t\treturn radians_ < rhs.radians_;\n\t}\n\n\tAngle& operator+=(const Angle& rhs) noexcept {\n\t\tradians_ += rhs.radians_;\n\t\treturn *this;\n\t}\n\n\tAngle& operator-=(const Angle& rhs) noexcept {\n\t\tradians_ -= rhs.radians_;\n\t\treturn *this;\n\t}\n\n\tAngle& operator*=(float rhs) noexcept {\n\t\tradians_ *= rhs;\n\t\treturn *this;\n\t}\n\n\tAngle& operator/=(float rhs) noexcept {\n\t\tradians_ /= rhs;\n\t\treturn *this;\n\t}\n\n\tAngle operator-() const noexcept {\n\t\treturn -1.0f * (*this);\n\t}\n\n\tfriend const Angle radians(float radians) noexcept;\n\n\tfriend const Angle degrees(float degrees) noexcept;\n\nprivate:\n\n\tconstexpr explicit Angle(float radians) noexcept :\n\t\tradians_(radians)\n\t{\n\t}\n\nprivate:\n\n\tfloat radians_;\n\n};\n\nstatic_assert(sizeof(Angle) == sizeof(float), \"Angle should have no extra data\");\n\nstd::ostream& operator<<(std::ostream& os, const Angle& angle);\n\ninline const Angle radians(float radians) noexcept {\n\treturn Angle(radians);\n}\n\ninline const Angle degrees(float degrees) noexcept {\n\treturn Angle(degrees * (PI / 180.0f));\n}\n\ninline const Angle operator\"\"_rad(long double r) noexcept {\n\treturn radians(static_cast<float>(r));\n}\n\ninline const Angle operator\"\"_deg(long double d) noexcept {\n\treturn degrees(static_cast<float>(d));\n}\n\n} // namespace math\n\nusing math::PI;\nusing math::Angle;\nusing math::radians;\nusing math::degrees;\n\nnamespace math_literals {\n\nusing math::operator \"\"_deg;\nusing math::operator \"\"_rad;\n\n} // namespace math_literals\n\n} // namespace pulp\n} // namespace coconut\n\n#endif /* _COCONUT_PULP_MATH_ANGLE_HPP_ */\n", "meta": {"hexsha": "6ad7b7e450162ba6077337049b4812f3d797f0ec", "size": 2310, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Angle.hpp", "max_stars_repo_name": "mikosz/coconut", "max_stars_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T12:01:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T12:01:54.000Z", "max_issues_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Angle.hpp", "max_issues_repo_name": "mikosz/coconut", "max_issues_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Angle.hpp", "max_forks_repo_name": "mikosz/coconut", "max_forks_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7804878049, "max_line_length": 81, "alphanum_fraction": 0.7207792208, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6469695600648488}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <cmath>\n\ndouble calculate_anisotropy(const arma::mat &m) {\n\n    const double iso = arma::mean(arma::eig_sym(m));\n    double aniso = arma::accu(m % m);\n    aniso = std::sqrt(std::abs(1.5*(aniso - (3.0*iso*iso))));\n\n    return aniso;\n}\n\nint main() {\n\n    arma::mat tensor(3, 3);\n    tensor(0, 0) = 71.96979730;\n    tensor(0, 1) = -7.19617988;\n    tensor(0, 2) = 1.01470321;\n    tensor(1, 0) = -7.19617833;\n    tensor(1, 1) = 65.74361807;\n    tensor(1, 2) = -5.62003645;\n    tensor(2, 0) = 1.01469269;\n    tensor(2, 1) = -5.62002592;\n    tensor(2, 2) = 65.05385723;\n\n    // arma::cx_vec principal_components_cx;\n    // arma::cx_mat orientation_cx;\n\n    // arma::eig_gen(principal_components_cx, orientation_cx, tensor);\n    // principal_components_cx.print(\"principal components (complex)\");\n    // orientation_cx.print(\"orientation (complex)\");\n\n    arma::vec principal_components;\n    arma::mat orientation;\n\n    arma::eig_sym(principal_components, orientation, tensor);\n\n    principal_components.print(\"principal components (real)\");\n    orientation.print(\"orientation (real)\");\n\n    double isotropic = arma::mean(principal_components);\n    std::cout << \"isotropic  : \" << isotropic << std::endl;\n    double anisotropic = calculate_anisotropy(tensor);\n    std::cout << \"anisotropic: \" << anisotropic << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "63acaf2191456b38dc3fa066180f25cb4eb2dc4f", "size": 1381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/armadillo/arma_aniso.cpp", "max_stars_repo_name": "berquist/eg", "max_stars_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/armadillo/arma_aniso.cpp", "max_issues_repo_name": "berquist/eg", "max_issues_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/armadillo/arma_aniso.cpp", "max_forks_repo_name": "berquist/eg", "max_forks_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1836734694, "max_line_length": 71, "alphanum_fraction": 0.6473569877, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6469695599109831}}
{"text": "//-----------------------------------------------------------------------------\n// Copyright (c) 2015-2018 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE mitrax convolution\n#include <boost/test/unit_test.hpp>\n\n#include <mitrax/convolution.hpp>\n\n#include <iostream>\n\n\nusing boost::typeindex::type_id;\nusing boost::typeindex::type_id_runtime;\nusing namespace mitrax;\nusing namespace mitrax::literals;\n\n\nconstexpr auto image = make_matrix< int >(5_DS, {\n\t{1, 2, 3, 4, 5},\n\t{2, 3, 4, 5, 6},\n\t{3, 4, 5, 6, 7},\n\t{4, 5, 6, 7, 8},\n\t{5, 6, 7, 8, 9}\n});\n\nconstexpr auto sobel_x = make_matrix< int >(3_DS, {\n\t{1, 0, -1},\n\t{2, 0, -2},\n\t{1, 0, -1}\n});\n\n\nBOOST_AUTO_TEST_SUITE(suite_convolution)\n\n\nBOOST_AUTO_TEST_CASE(test_convolution){\n\tconstexpr auto m = convolution(image, sobel_x);\n\n\tauto eq =\n\t\tm.cols() == 3_CS &&\n\t\tm.rows() == 3_RS &&\n\t\tm(0_c, 0_r) == -8 &&\n\t\tm(1_c, 0_r) == -8 &&\n\t\tm(2_c, 0_r) == -8 &&\n\t\tm(0_c, 1_r) == -8 &&\n\t\tm(1_c, 1_r) == -8 &&\n\t\tm(2_c, 1_r) == -8 &&\n\t\tm(0_c, 2_r) == -8 &&\n\t\tm(1_c, 2_r) == -8 &&\n\t\tm(2_c, 2_r) == -8;\n\n\tBOOST_TEST(eq);\n\n\tBOOST_TEST(type_id_runtime(m) == (type_id< std_matrix< int, 3_C, 3_R > >()));\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "239ecbac084ab2e1d66f1683cc307988ba73ede4", "size": 1433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/convolution.cpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/convolution.cpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/convolution.cpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.390625, "max_line_length": 79, "alphanum_fraction": 0.5561758548, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6469695576369073}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <vector>\n\n#include \"crossprod.h\"\n\nint main() {\n  double T = 1.;\n  int N = 1;\n\n  Eigen::Vector3d y0(0.1, 0.2, 0.4);\n\n  auto f = [](Eigen::Vector3d y) -> Eigen::Vector3d {\n    return Eigen::Vector3d(y(0) * y(1), y(1) * y(2), y(2) - y(0));\n  };\n\n  auto Jf = [](Eigen::Vector3d y) -> Eigen::Matrix3d {\n    Eigen::Matrix3d J;\n    J << y(1), y(0), 0, 0, y(2), y(1), -1, 0, 1;\n    return J;\n  };\n  // test implicit midpoint\n  std::vector<Eigen::VectorXd> test_imp =\n      CrossProd::solve_imp_mid(f, Jf, T, y0, N);\n  std::cout << \"Implicit midpoint:\\n\"\n            << test_imp.back() << std::endl\n            << std::endl;\n\n  // test linear implicit midpoint\n  std::vector<Eigen::VectorXd> test_lin =\n      CrossProd::solve_lin_mid(f, Jf, T, y0, N);\n  std::cout << \"Implicit linear midpoint:\\n\"\n            << test_lin.back() << std::endl\n            << std::endl;\n\n  // CrossProd::tab_crossprod();\n\n  return 0;\n}\n", "meta": {"hexsha": "90a757468e68ad4cd3a11b2fa3c843c1f51be06e", "size": 958, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/CrossProd/templates/crossprod_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/CrossProd/templates/crossprod_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/CrossProd/templates/crossprod_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 23.95, "max_line_length": 66, "alphanum_fraction": 0.5553235908, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6469695550551001}}
{"text": "#include \"drake/math/quadratic_form.h\"\n\n#include <algorithm>\n\n#include <Eigen/Cholesky>\n#include <Eigen/Eigenvalues>\n\n#include \"drake/math/matrix_util.h\"\n\nnamespace drake {\nnamespace math {\nEigen::MatrixXd DecomposePSDmatrixIntoXtransposeTimesX(\n    const Eigen::Ref<const Eigen::MatrixXd>& Y, double zero_tol) {\n  if (Y.rows() != Y.cols()) {\n    throw std::runtime_error(\"Y is not square.\");\n  }\n  if (zero_tol < 0) {\n    throw std::runtime_error(\"zero_tol should be non-negative.\");\n  }\n  Eigen::LLT<Eigen::MatrixXd> llt_Y(Y);\n  if (llt_Y.info() == Eigen::Success) {\n    return llt_Y.matrixU();\n  } else {\n    // TODO(hongkai.dai) Switch to use robust Choleskly decomposition instead\n    // of Eigen value decomposition, when the bug in\n    // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=1479 is fixed.\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es_Y(Y);\n    if (es_Y.info() == Eigen::Success) {\n      Eigen::MatrixXd X(Y.rows(), Y.cols());\n      int X_row_count = 0;\n      for (int i = 0; i < es_Y.eigenvalues().rows(); ++i) {\n        if (es_Y.eigenvalues()(i) < -zero_tol) {\n          throw std::runtime_error(\"Y is not positive definite.\");\n        } else if (es_Y.eigenvalues()(i) > zero_tol) {\n          X.row(X_row_count++) = std::sqrt(es_Y.eigenvalues()(i)) *\n                                 es_Y.eigenvectors().col(i).transpose();\n        }\n      }\n      return X.topRows(X_row_count);\n    }\n  }\n  throw std::runtime_error(\"Y is not PSD.\");\n}\n\nstd::pair<Eigen::MatrixXd, Eigen::MatrixXd> DecomposePositiveQuadraticForm(\n    const Eigen::Ref<const Eigen::MatrixXd>& Q,\n    const Eigen::Ref<const Eigen::VectorXd>& b, double c, double tol) {\n  if (Q.rows() != Q.cols()) {\n    throw std::runtime_error(\"Q should be a square matrix.\");\n  }\n  if (b.rows() != Q.rows()) {\n    throw std::runtime_error(\"b does not have the right size.\");\n  }\n  // The quadratic form x\u1d40Qx + b\u1d40x + c can also be written as\n  // [x]\u1d40 * [Q   b/2] * [x]\n  // [1]    [b/2   c]   [1]\n  // We will call the matrix in the middle as M\n  Eigen::MatrixXd M(Q.rows() + 1, Q.rows() + 1);\n  // clang-format on\n  M << (Q + Q.transpose()) / 2, b / 2,\n       b.transpose() / 2, c;\n  // clang-format off\n\n  const Eigen::MatrixXd A = DecomposePSDmatrixIntoXtransposeTimesX(M, tol);\n  Eigen::MatrixXd R = A.leftCols(Q.cols());\n  Eigen::VectorXd d = A.col(Q.cols());\n  return std::make_pair(R, d);\n}\n\nEigen::MatrixXd BalanceQuadraticForms(\n    const Eigen::Ref<const Eigen::MatrixXd>& S,\n    const Eigen::Ref<const Eigen::MatrixXd>& P) {\n  const double tolerance = 1e-8;\n  const int n = S.rows();\n  DRAKE_THROW_UNLESS(P.rows() == n);\n  DRAKE_THROW_UNLESS(IsPositiveDefinite(S, tolerance));\n  DRAKE_THROW_UNLESS(IsSymmetric(P, tolerance));\n\n  const Eigen::MatrixXd R =\n      S.llt().matrixL().solve(Eigen::MatrixXd::Identity(n, n));\n\n  const Eigen::JacobiSVD<Eigen::MatrixXd> svd(R * P * R.transpose(),\n                                              Eigen::ComputeThinU);\n  // Check that P was full rank (hence RPR' full-rank).\n  DRAKE_THROW_UNLESS(svd.singularValues()(svd.singularValues().size()-1) >=\n                         tolerance*std::max(1., svd.singularValues()(0)));\n\n  const Eigen::VectorXd sigmaRootN4 =\n      svd.singularValues().array().pow(-0.25).matrix();\n  return R.transpose() * svd.matrixU() * sigmaRootN4.asDiagonal();\n}\n\n}  // namespace math\n}  // namespace drake\n", "meta": {"hexsha": "e1b8d7d1bb1b7a839dd107e676b7eeca58f7202a", "size": 3360, "ext": "cc", "lang": "C++", "max_stars_repo_path": "math/quadratic_form.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "math/quadratic_form.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/quadratic_form.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 35.3684210526, "max_line_length": 77, "alphanum_fraction": 0.6255952381, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6469695500453513}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/videoio/videoio.hpp>\n\nEigen::Affine2d get_svd_transform(const Eigen::Matrix<double, -1, 2> &src, const Eigen::Matrix<double, -1, 2> &tgt)\n{\n\n  assert(src.rows() == tgt.rows());\n  Eigen::Affine2d result = Eigen::Affine2d::Identity();\n  Eigen::Matrix<double, -1, 2> src_ = src;\n  Eigen::Matrix<double, -1, 2> tgt_ = tgt;\n  Eigen::Vector2d centroid_src, centroid_tgt;\n  // std::cout << \"getting mean\" << std::endl;\n\n  centroid_src = src.colwise().mean();\n  centroid_tgt = tgt.colwise().mean();\n\n  std::cout << centroid_src << std::endl\n            << centroid_tgt << std::endl;\n\n  src_.colwise() -= centroid_src;\n  tgt_.colwise() -= centroid_tgt;\n  // std::cout << \"getting svd\" << std::endl;\n  Eigen::Matrix2d mat = tgt_.transpose() * src_;\n  Eigen::JacobiSVD<Eigen::Matrix2d> svd(mat, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Eigen::Matrix2d u, v;\n  u = svd.matrixU();\n  v = svd.matrixV();\n  // std::cout << \"getting rot\" << std::endl;\n  result.linear() = u * v.transpose();\n  if (result.linear().determinant() < 0)\n  {\n    Eigen::Matrix<double, 2, 2> inv;\n    inv << 1, 0,\n           0, -1;\n    std::cout << \"special case\" << std::endl;\n    // v.transpose().rowwise() *= v;\n    v = v * inv;\n    result.linear() = u * v.transpose();\n  }\n  // std::cout << \"getting trans\" << std::endl;\n  result.translation() = centroid_tgt - result.linear() * centroid_src;\n  return result;\n}\n\n// Return l2 distance of transformed points\ndouble compare_point_sets(const Eigen::Matrix<double, -1, 2> &src, const Eigen::Matrix<double, -1, 2> &tgt, Eigen::Affine2d &result)\n{\n  int rows = src.rows();\n\n  // std::cout << \"src: \\n\" << src << std::endl;\n  // std::cout << \"tgt: \\n\" << tgt << std::endl;\n  // std::cout << \"getting tf\" << std::endl;\n\n  result = get_svd_transform(src, tgt);\n  std::cout << \"rot:\" << std::endl\n            << result.linear() << std::endl;\n  std::cout << \"trans:\" << std::endl\n            << result.translation() << std::endl;\n\n  Eigen::Matrix<double, -1, 2> transformed_src = (result * src.transpose()).transpose();\n  // transformed_src.resize(rows, 2);\n  // for(int i=0; i<rows; i++){\n  //   transformed_src.row(i) = result * src.row(i);\n  // }\n\n  std::cout << \"before \\n\"\n            << src << std::endl;\n  std::cout << \"after \\n\"\n            << transformed_src << std::endl;\n\n  Eigen::Matrix<double, -1, 2> diff = tgt - transformed_src.topLeftCorner(rows, 2);\n  Eigen::Matrix<double, -1, 1> err = diff.rowwise().norm();\n\n  cv::Mat before = cv::Mat::zeros(cv::Size(640, 480), CV_8UC3);\n  cv::Mat after = cv::Mat::zeros(cv::Size(640, 480), CV_8UC3);\n  for (int i = 0; i < src.rows(); i++)\n  {\n    cv::circle(before, cv::Point(src(i, 0), src(i, 1)), 2, cv::Scalar(0, 0, 255), 2);\n  }\n\n  for (int i = 0; i < tgt.rows(); i++)\n  {\n    cv::circle(before, cv::Point(tgt(i, 0), tgt(i, 1)), 2, cv::Scalar(255, 255, 0), 2);\n    cv::circle(after, cv::Point(tgt(i, 0), tgt(i, 1)), 2, cv::Scalar(255, 255, 0), 2);\n  }\n\n  for (int i = 0; i < transformed_src.rows(); i++)\n  {\n    cv::circle(after, cv::Point(transformed_src(i, 0), transformed_src(i, 1)), 2, cv::Scalar(0, 0, 255), 2);\n  }\n\n  cv::imshow(\"before\", before);\n  cv::imshow(\"after\", after);\n  cv::waitKey(2);\n  return err.sum();\n}", "meta": {"hexsha": "fa6048fddb481a10586532b2078620ded95a216a", "size": 3328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/point_set_compare.hpp", "max_stars_repo_name": "biomotion/esd-2020-final", "max_stars_repo_head_hexsha": "548a0e9a16372cfc04e77220b347ffcfc54efd2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/point_set_compare.hpp", "max_issues_repo_name": "biomotion/esd-2020-final", "max_issues_repo_head_hexsha": "548a0e9a16372cfc04e77220b347ffcfc54efd2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/point_set_compare.hpp", "max_forks_repo_name": "biomotion/esd-2020-final", "max_forks_repo_head_hexsha": "548a0e9a16372cfc04e77220b347ffcfc54efd2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6161616162, "max_line_length": 132, "alphanum_fraction": 0.5919471154, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6469347000574693}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <sys/stat.h>\n#include <igl/readPLY.h>\n#include <igl/writePLY.h>\n#include <igl/point_mesh_squared_distance.h>\n#include <igl/slice.h>\n#include <igl/barycentric_coordinates.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n\nigl::AABB<Eigen::MatrixXd,3> tree;\n\n/*\nfloat icp_step(Eigen::MatrixXd *Vmov, Eigen::MatrixXd Vref, Eigen::MatrixXi Fref)\n{\n  using namespace Eigen;\n  using namespace std;\n  using namespace igl;\n\n  int i;\n  float dist = 0;\n\n  // compute closest points\n  VectorXd sqrD;\n  VectorXi I;\n  MatrixXd Vout;\n\n  igl::point_mesh_squared_distance(*Vmov, Vref, Fref, sqrD, I, Vout);\n\n  // compute rotation and translation\n  MatrixXd C = Matrix3d::Constant(0);\n  VectorXd oout = Vout.colwise().sum()/Vout.rows();\n  VectorXd omov = (*Vmov).colwise().sum()/(*Vmov).rows();\n\n  for(i=0;i<(*Vmov).rows();i++)\n    C += ((*Vmov).row(i) - omov.transpose()).transpose()\n         * (Vout.row(i) - oout.transpose());\n\n  JacobiSVD<MatrixXd> svd(C, ComputeThinU|ComputeThinV);\n  Matrix3d U = svd.matrixU();\n  Matrix3d V = svd.matrixV().transpose();\n\n  MatrixXd R = U*V;\n  MatrixXd t = omov - R*oout;\n\n  // apply rotation and translation\n  (*Vmov)*=R;\n  (*Vmov).transpose().colwise() -= t.col(0);\n\n  // check convergence\n  // angle_dist = arccos((trace(P*Q')-1)/2), P, Q rotation matrices\n  // (here, Q=I)\n  // http://www.boris-belousov.net/2016/12/01/quat-dist/\n  dist = acos((R.trace()-1)/2.0);\n  dist = dist + t.norm();\n\n  return dist;\n}\n  \nint icp(Eigen::MatrixXd Vref, Eigen::MatrixXi Fref,\n        Eigen::MatrixXd *Vmov, Eigen::MatrixXi Fmov,\n        float *diff)\n{\n  using namespace Eigen;\n  using namespace std;\n  using namespace igl;\n\n  int i;\n  float dist;\n  int maxiter = 100;\n  float tol = 1e-6;\n\n  // init distance AABB tree\n  tree.init(Vref, Fref);\n\n  float dist0=-1;\n\n  for(i=0;i<maxiter;i++)\n  {\n    dist = icp_step(Vmov, Vref, Fref);\n    if(dist0<0)\n    {\n        *diff = dist;\n        printf(\"initial distance: %g\\n\", *diff);\n    }\n    else\n        *diff = fabs(dist-dist0);\n\n    if(*diff < tol)\n        break;\n\n    dist0=dist;\n  }\n  printf(\"final distance: %g (after %i iterations)\\n\", *diff, i);\n\n  return i;\n}\n*/\n\nvoid read_vertices(char *path, Eigen::MatrixXd *V, Eigen::MatrixXi *E)\n{\n  using namespace Eigen;\n  using namespace std;\n\n  FILE *f;\n  int i, nv, ne;\n  float x, y, z;\n  int a, b;\n\n  f=fopen(path,\"r\");\n  fscanf(f,\" %i %*i %i \", &nv, &ne);\n  cout<<\"verts: \"<<nv<<endl;\n  MatrixXd X(nv, 3);\n  for(i=0;i<nv;i++)\n  {\n    fscanf(f, \" %f %f %f \", &x, &y, &z);\n    X.row(i)<<x,y,z;\n  }\n  MatrixXi Y(ne, 2);\n  for(i=0;i<ne;i++)\n  {\n    fscanf(f, \" %i %i \", &a, &b);\n    Y.row(i)<<a,b;\n  }\n  (*V) = X;\n  (*E) = Y;\n}\n\nvoid save_vertices(char *path, Eigen::MatrixXd V, Eigen::MatrixXi E)\n{\n  using namespace Eigen;\n  using namespace std;\n  \n  FILE *f;\n  int i;\n  \n  f=fopen(path,\"w\");\n  fprintf(f,\"%i 0 %i\\n\", (int)V.rows(), (int)E.rows());\n  for(i=0;i<V.rows();i++)\n  {\n    fprintf(f, \"%f %f %f\\n\", V(i,0), V(i,1), V(i,2));\n  }\n  for(i=0;i<E.rows();i++)\n  {\n    fprintf(f, \"%i %i\\n\", E(i,0), E(i,1));\n  }\n  fclose(f);\n}\n\nint main(int argc, char * argv[])\n{\n  using namespace Eigen;\n  using namespace std;\n  using namespace igl;\n  \n  /*\n    Transform fold curves to sphere\n  */\n  char path_orig[] = \"/Users/roberto/Documents/annex-foldgraph/data/raw/baboon/both.ply\";\n  char path_sph[] = \"/Users/roberto/Documents/annex-foldgraph/data/derived/skeleton/baboon/both_spherical.ply\";\n  char path_verts[] = \"/Users/roberto/Documents/annex-foldgraph/data/derived/skeleton/baboon/both_skel_curves.txt\";\n  char path_out[] = \"/Users/roberto/Documents/annex-foldgraph/data/derived/skeleton/baboon/test.txt\";\n\n  struct stat info;\n  if(stat(path_orig, &info))\n      printf(\"File %s not found\\n\", path_orig);\n  if(stat(path_sph, &info))\n      printf(\"File %s not found\\n\", path_sph);\n  if(stat(path_verts, &info))\n      printf(\"File %s not found\\n\", path_verts);\n\n  MatrixXd Vorig, Vsph;\n  MatrixXi Forig, Fsph;\n  MatrixXd TMP1, TMP2;\n\n  igl::readPLY(path_orig, Vorig, Forig, TMP1, TMP2);\n  cout<<\"Original nv, nt: \"<<Vorig.rows()<<\", \"<<Forig.rows()<<endl;\n\n  igl::readPLY(path_sph, Vsph, Fsph, TMP1, TMP2);\n  cout<<\"Spherical nv, nt: \"<<Vsph.rows()<<\", \"<<Fsph.rows()<<endl;\n\n  MatrixXd V;\n  MatrixXi E;\n  Vector3d t;\n  t<<32.5,38.74,23.92;\n  read_vertices(path_verts, &V, &E);\n  V*=0.26;\n  V.transpose().colwise() -=t;\n  cout<<\"Verts: \"<<V.rows()<<endl;\n\n  // init distance AABB tree\n  tree.init(Vorig, Forig);\n\n  // compute closest points\n  VectorXd sqrD;\n  VectorXi I;\n  MatrixXd Vout;\n  igl::point_mesh_squared_distance(V, Vorig, Forig, sqrD, I, Vout);\n\n  // get barycentric coordinates\n  MatrixXd Vx, Vy, Vz, B;\n  Vector3d xyz;\n  xyz<<0,1,2;\n  MatrixXd VV(Vout.rows(),3);\n  MatrixXi FF;\n  slice(Forig, I, xyz, FF);\n  slice(Vorig, FF.col(0), xyz, Vx);\n  slice(Vorig, FF.col(1), xyz, Vy);\n  slice(Vorig, FF.col(2), xyz, Vz);\n  barycentric_coordinates(Vout, Vx, Vy, Vz, B);\n\n  // get coordinates in Vsph space\n  slice(Vsph, FF.col(0), xyz, Vx);\n  slice(Vsph, FF.col(1), xyz, Vy);\n  slice(Vsph, FF.col(2), xyz, Vz);\n  int i;\n  for(i=0;i<Vout.rows();i++)\n    VV.row(i) = Vx.row(i)*B(i, 0) + Vy.row(i)*B(i, 1) + Vz.row(i)*B(i, 2);\n    \n  // save result\n  save_vertices(path_out, VV, E);\n\n  return 0;\n}\n", "meta": {"hexsha": "e69041ddd08a2ab45c6c665a646854ba7fa8fc45", "size": 5250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scratch/work_roberto/register_graph/main.cpp", "max_stars_repo_name": "katjaq/foldgraph", "max_stars_repo_head_hexsha": "12582c3263612329c742205d3da6564728927961", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-25T02:55:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-28T11:09:14.000Z", "max_issues_repo_path": "scratch/work_roberto/register_graph/main.cpp", "max_issues_repo_name": "katjaq/foldgraph", "max_issues_repo_head_hexsha": "12582c3263612329c742205d3da6564728927961", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-17T08:57:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-17T08:57:45.000Z", "max_forks_repo_path": "scratch/work_roberto/register_graph/main.cpp", "max_forks_repo_name": "katjaq/foldgraph", "max_forks_repo_head_hexsha": "12582c3263612329c742205d3da6564728927961", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-05T10:32:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-18T08:02:55.000Z", "avg_line_length": 23.127753304, "max_line_length": 115, "alphanum_fraction": 0.6127619048, "num_tokens": 1802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7090191399336401, "lm_q1q2_score": 0.6469347000574692}}
{"text": "#include \"registration.h\"\n#include <Eigen/Cholesky>\n#include <vector>\n\nstruct SPoint2D\n{\n\tdouble x[2];\n};\n\ndouble computeAngle(const Eigen::Vector2d& e_im, const Eigen::Vector2d& e_i)\n{\n\t//compute theta\n\t//when e_im.dot(e_i) = 1.0, theta = pi;\n\tconst double r_sinT = e_im(0)*e_i(1) - e_im(1)*e_i(0);\n\tconst double r_cosT = -e_im.dot(e_i);\n\treturn atan2(r_sinT, r_cosT);\n}\n\ndouble sgn(const double& x)\n{\n\treturn (x >= 0) ? 1.0 : -1.0;\n}\n\n\ndouble computeOmegaFromAngle(const double& theta)\n{\n\tconst double sinT = sin(theta);\n\tconst double cosT = cos(theta);\n\tconst double tan_phi_over_2 = sgn(sinT) * sqrt((1.0+cosT)/(max(0.0, 1.0-cosT) + 1.0e-10));\n\treturn 2.0 * tan_phi_over_2;\n}\n\ndouble computeOmega(const Eigen::Vector2d& e_im, const Eigen::Vector2d& e_i)\n{\n\t//compute 2.0 * tan(phi / 2.0)\n\t//phi = pi - theta\n\treturn computeOmegaFromAngle(computeAngle(e_im, e_i));\t\n}\n\ndouble sampleDistanceField(const SImage<double, 1>& in_DF, const SRegion& in_Region, const Eigen::Vector2d& x)\n{\n\tassert(in_DF.width == in_DF.height);\n\tassert(in_Region.right-in_Region.left == in_Region.top-in_Region.bottom);\n\n\tEigen::Vector2d proj_x = x;\n\tproj_x(0) = std::max(in_Region.left, std::min(in_Region.right, x(0)));\n\tproj_x(1) = std::max(in_Region.bottom, std::min(in_Region.top, x(1)));\n\n\tconst double dist_scale = (in_Region.right-in_Region.left) / in_DF.width;\n\n\tdouble fi = (proj_x(0) - in_Region.left) * in_DF.width / (in_Region.right - in_Region.left);\n\tdouble fj = (proj_x(1) - in_Region.bottom) * in_DF.height / (in_Region.top - in_Region.bottom);\n\tdouble _i = floor(fi);\n\tdouble _j = floor(fj);\n\n\tint i = std::max(0, std::min(in_DF.width-1, int(_i)));\n\tint j = std::max(0, std::min(in_DF.height-1, int(_j)));\n\tint ip = std::min(in_DF.width-1, i+1);\n\tint jp = std::min(in_DF.height-1, j+1);\n\n\tdouble s = fi - _i;\n\tdouble t = fj - _j;\n\n\tdouble dist_proj = (1.0 - t) * (s * in_DF.ptr[j*in_DF.width+ip] + (1.0-s) * in_DF.ptr[j*in_DF.width+i])\n\t\t+ t * (s * in_DF.ptr[jp*in_DF.width+ip] + (1.0-s) * in_DF.ptr[jp*in_DF.width+i]);\n\n\treturn dist_proj * dist_scale + (proj_x - x).norm();\n}\n\ndouble integrateDF2OverSegment(const SParameters* in_Params, const Eigen::Vector2d& x1, const Eigen::Vector2d& x2, const double restL)\n{\n\tdouble tot = 0.0;\n\tconst double len = restL / in_Params->substep_fit;\n\n\t//printf(\"integ_DF: \");\n\tfor(int i=0; i<in_Params->substep_fit; i++)\n\t{\n\t\tconst Eigen::Vector2d& p1 = x1 + (x2-x1) * double(i)/double(in_Params->substep_fit);\n\t\tconst Eigen::Vector2d& p2 = x1 + (x2-x1) * double(i+1)/double(in_Params->substep_fit);\n\t\t\n\t\tconst double d1 = sampleDistanceField(in_Params->df, in_Params->region, p1);\n\t\tconst double d2 = sampleDistanceField(in_Params->df, in_Params->region, p2);\n\n\t\t//printf(\"[%f, %f, %f], \", d1, d2, len);\n\n\t\tconst double e1 = 0.5 * (exp(d1) + exp(-d1)) - 1.0;\n\t\tconst double e2 = 0.5 * (exp(d2) + exp(-d2)) - 1.0;\n\n\t\t//tot += 0.5 * (d1*d1+d2*d2) * len;\n\t\ttot += 0.5 * (e1*e1+e2*e2) * len;\n\t}\n\t//printf(\"\\n\");\n\n\treturn tot;\n}\n\ninline double computeSegmentElasticEnergy(const Eigen::Vector2d& p1, const Eigen::Vector2d& p2, const double& YA, const double& restLength)\n{\n\tconst Eigen::Vector2d diff = p1 - p2;\n\treturn 0.5 * YA * restLength\n\t\t* (diff.norm() / restLength - 1)\n\t\t* (diff.norm() / restLength - 1);\n}\n\ninline double computeSegmentBendingEnergy(const Eigen::Vector2d& pp, const Eigen::Vector2d& pc, const Eigen::Vector2d& pn, \n\tconst double& alpha, const double& restLengthP, const double& restLengthN, const double& theta)\n{\n\tconst Eigen::Vector2d e_im = pc - pp;\n\tconst Eigen::Vector2d e_i = pn - pc;\n\n\t/*\n\tdouble omega = 2.0 * fabs(e_im(0)*e_i(1)-e_im(1)*e_i(0)) / (e_im.norm()*e_i.norm() + e_im.dot(e_i));\n\tdouble omega_bar = 2.0 * fabs(tan(phi*0.5));\n\t//*/\n\tdouble omega = computeOmega(e_im, e_i);\n\tdouble omega_bar = computeOmegaFromAngle(theta);\n\treturn alpha * (omega - omega_bar) * (omega - omega_bar) / (restLengthP + restLengthN);\n}\n\ndouble computeEnergy_elastic(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tdouble energy = 0.0;\n\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % in_Curve->nVertices;\n\t\tenergy += computeSegmentElasticEnergy(in_Position.col(ip), in_Position.col(i), in_Params->YA, in_Curve->restLengths(i));\n\t}\n\n\treturn energy;\n}\n\ndouble computeEnergy_bending(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position)\n{\n\tint nAngles = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 2; \n\n\tdouble energy = 0.0;\n\n\tfor(int i=0; i<nAngles; i++)\n\t{\n\t\tint iim = in_Curve->closed ? \n\t\t\t(i + in_Curve->nVertices - 1) % in_Curve->nVertices : i;\n\t\tint ii = in_Curve->closed ? i : i + 1;\n\t\tint iip = in_Curve->closed ? (i + 1) % in_Curve->nVertices : i + 2;\n\n\t\tdouble restL_m = in_Curve->closed ? in_Curve->restLengths((i + in_Curve->nVertices - 1) % in_Curve->nVertices) : \n\t\t\tin_Curve->restLengths(i);\n\t\tdouble restL = in_Curve->closed ? in_Curve->restLengths(i) : \n\t\t\tin_Curve->restLengths(i+1);\n\n\t\tenergy += computeSegmentBendingEnergy(in_Position.col(iim), in_Position.col(ii), in_Position.col(iip),\n\t\t\tin_Params->alpha, restL_m, restL, in_Curve->restAngles(i));\n\t}\n\n\treturn energy;\n}\n\ndouble computeEnergy_fit(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tdouble energy = 0.0;\n\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % in_Curve->nVertices;\n\t\tdouble int_df_seg = integrateDF2OverSegment(in_Params, in_Position.col(i), in_Position.col(ip), in_Curve->restLengths(i));\n\t\tenergy += 0.5 * in_Params->fit * int_df_seg;\n\t}\n\n\treturn energy;\n}\n\ndouble computeEnergy(const SParameters* in_Params, const SCurve* in_Curve, const SVar& in_Vars)\n{\n\tconst double E_elastic = computeEnergy_elastic(in_Params, in_Curve, in_Vars.pos);\n\tconst double E_bending = computeEnergy_bending(in_Params, in_Curve, in_Vars.pos);\n\tconst double E_fit = computeEnergy_fit(in_Params, in_Curve, in_Vars.pos);\n\treturn E_elastic + E_bending + E_fit;\n}\n\nvoid compute_f_elastic(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position, Eigen::VectorXd& io_f, int offset_row)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tassert(io_f.rows() >= nSegs + offset_row);\n\tassert(in_Curve->nVertices == in_Position.cols());\n\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % in_Curve->nVertices;\n\t\tconst Eigen::Vector2d diff = in_Position.col(ip) - in_Position.col(i);\n\t\tio_f(i+offset_row) = sqrt(0.5 * in_Params->YA * in_Curve->restLengths(i)) * (diff.norm() / in_Curve->restLengths(i) - 1);\n\t}\n}\n\nvoid compute_f_bending(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position, Eigen::VectorXd& io_f, int offset_row)\n{\n\tint nAngles = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 2; \n\n\tassert(io_f.rows() >= nAngles + offset_row);\n\tassert(in_Curve->nVertices == in_Position.cols());\n\n\tfor(int i=0; i<nAngles; i++)\n\t{\n\t\tint iim = in_Curve->closed ? \n\t\t\t(i + in_Curve->nVertices - 1) % in_Curve->nVertices : i;\n\t\tint ii = in_Curve->closed ? i : i + 1;\n\t\tint iip = in_Curve->closed ? (i + 1) % in_Curve->nVertices : i + 2;\n\n\t\tdouble restL_m = in_Curve->closed ? in_Curve->restLengths((i + in_Curve->nVertices - 1) % in_Curve->nVertices) : \n\t\t\tin_Curve->restLengths(i);\n\t\tdouble restL = in_Curve->closed ? in_Curve->restLengths(i) : \n\t\t\tin_Curve->restLengths(i+1);\n\n\t\tconst Eigen::Vector2d e_im = in_Position.col(ii) - in_Position.col(iim);\n\t\tconst Eigen::Vector2d e_i = in_Position.col(iip) - in_Position.col(ii);\n\n\t\t/*\n\t\tdouble omega = 2.0 * fabs(e_im(0)*e_i(1)-e_im(1)*e_i(0)) / (e_im.norm()*e_i.norm() + e_im.dot(e_i));\n\t\tdouble omega_bar = 2.0 * fabs(tan(in_Curve->restAngles(i)*0.5));\n\t\t//*/\n\t\tdouble omega = computeOmega(e_im, e_i);\n\t\tdouble omega_bar = computeOmegaFromAngle(in_Curve->restAngles(i));\n\t\tio_f(i+offset_row) = sqrt(in_Params->alpha/(restL_m + restL)) * (omega - omega_bar);\n\t}\n}\n\nvoid compute_f_fit(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position, Eigen::VectorXd& io_f, int offset_row)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tassert(io_f.rows() >= nSegs + offset_row);\n\tassert(in_Curve->nVertices == in_Position.cols());\n\n\t//printf(\"int_seg: \");\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % in_Curve->nVertices;\n\t\tdouble int_df_seg = integrateDF2OverSegment(in_Params, in_Position.col(i), in_Position.col(ip), in_Curve->restLengths(i));\n\t\t//printf(\"%f, \", int_df_seg);\n\t\tio_f(i+offset_row) = sqrt(in_Params->fit * 0.5) * sqrt(int_df_seg);\n\t}\n\t//printf(\"\\n\");\n}\n\nvoid compute_f(const SParameters* in_Params, const SCurve* in_Curve, const SVar& in_Vars, Eigen::VectorXd& io_f)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\tint nAngles = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 2; \n\n\tint nElems = nSegs + nAngles + nSegs;\n\n\tassert(io_f.rows() == nElems);\n\tassert(in_Curve->nVertices == in_Vars.pos.cols());\n\tassert(in_Curve->nVertices == in_Vars.pos.cols());\n\n\tio_f.setZero();\n\n\tcompute_f_elastic(in_Params, in_Curve, in_Vars.pos, io_f, 0);\n\tcompute_f_bending(in_Params, in_Curve, in_Vars.pos, io_f, nSegs);\n\tcompute_f_fit(in_Params, in_Curve, in_Vars.pos, io_f, nSegs+nAngles);\n\n\t/*\n\tprintf(\"f: [\");\n\tfor(int i=0; i<nElems; i++)\n\t{\n\t\tif(i<nElems-1) printf(\"%f, \", io_f(i));\n\t\telse printf(\"%f]\\n\", io_f(i));\n\t}\n\t//*/\n}\n\nvoid computeNumericalDerivative_elastic(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position, double epsilon, Eigen::MatrixXd& io_Jacobian, int offset_row)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tassert(io_Jacobian.rows() >= nSegs + offset_row);\n\tassert(io_Jacobian.cols() == in_Curve->nVertices * 2);\n\n\tconst Eigen::Vector2d dx(epsilon, 0.0); \n\tconst Eigen::Vector2d dy(0.0, epsilon);\n\n\t//dJ/dxi, dJ/dyi\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\t//l_i is a function of x_i, x_{i+1}, y_i and y_{i+1}\n\t\tint ip = (i+1) % in_Curve->nVertices;\n\n\t\tconst Eigen::Vector2d xi = in_Position.col(i);\n\t\tconst Eigen::Vector2d xip = in_Position.col(ip);\n\n\t\tconst Eigen::Vector2d diff0 = xip - xi;\n\t\tconst double fi = sqrt(in_Params->YA * in_Curve->restLengths(i) * 0.5) * (diff0.norm() / in_Curve->restLengths(i) - 1);\n\n\t\t//dJ/dxi_i\n\t\tconst Eigen::Vector2d xi_dx = xi + dx;\n\t\tconst Eigen::Vector2d diff1 = xip - xi_dx;\n\t\tconst double fi_i_dx = sqrt(in_Params->YA * in_Curve->restLengths(i) * 0.5) * (diff1.norm() / in_Curve->restLengths(i) - 1);\n\t\tio_Jacobian(i+offset_row, i) = (fi_i_dx - fi) / epsilon;\n\n\t\t//dJ/dyi_i\n\t\tconst Eigen::Vector2d xi_dy = xi + dy;\n\t\tconst Eigen::Vector2d diff2 = xip - xi_dy;\n\t\tconst double fi_i_dy = sqrt(in_Params->YA * in_Curve->restLengths(i) * 0.5) * (diff2.norm() / in_Curve->restLengths(i) - 1);\n\t\tio_Jacobian(i+offset_row, i+in_Curve->nVertices) = (fi_i_dy - fi) / epsilon;\n\n\t\t//dJ/dxi_ip\n\t\tconst Eigen::Vector2d xip_dx = xip + dx;\n\t\tconst Eigen::Vector2d diff3 = xip_dx - xi;\n\t\tconst double fi_ip_dx = sqrt(in_Params->YA * in_Curve->restLengths(i) * 0.5) * (diff3.norm() / in_Curve->restLengths(i) - 1);\n\t\tio_Jacobian(i+offset_row, ip) = (fi_ip_dx - fi) / epsilon;\n\t\t\n\t\t//dJ/dyi_i\n\t\tconst Eigen::Vector2d xip_dy = xip + dy;\n\t\tconst Eigen::Vector2d diff4 = xip_dy - xi;\n\t\tconst double fi_ip_dy = sqrt(in_Params->YA * in_Curve->restLengths(i) * 0.5) * (diff4.norm() / in_Curve->restLengths(i) - 1);\n\t\tio_Jacobian(i+offset_row, ip+in_Curve->nVertices) = (fi_ip_dy - fi) / epsilon;\n\t}\n}\n\nvoid computeNumericalDerivative_bending(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position, double epsilon, Eigen::MatrixXd& io_Jacobian, int offset_row)\n{\n\tint nAngles = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 2; \n\n\tassert(io_Jacobian.rows() >= nAngles + offset_row);\n\tassert(io_Jacobian.cols() == in_Curve->nVertices * 2);\n\n\tconst Eigen::Vector2d dx(epsilon, 0.0); \n\tconst Eigen::Vector2d dy(0.0, epsilon);\n\n\t//dB/dxi, dB/dyi\n\tfor(int i=0; i<nAngles; i++)\n\t{\n\t\tint iim = in_Curve->closed ? \n\t\t\t(i + in_Curve->nVertices - 1) % in_Curve->nVertices : i;\n\t\tint ii = in_Curve->closed ? i : i + 1;\n\t\tint iip = in_Curve->closed ? (i + 1) % in_Curve->nVertices : i + 2;\n\n\t\tdouble restL_m = in_Curve->restLengths(iim);\n\t\tdouble restL = in_Curve->restLengths(ii);\n\n\t\tconst Eigen::Vector2d xim = in_Position.col(iim);\n\t\tconst Eigen::Vector2d xi = in_Position.col(ii);\n\t\tconst Eigen::Vector2d xip = in_Position.col(iip);\n\n\t\tconst Eigen::Vector2d xim_dx = xim + dx; const Eigen::Vector2d xim_dy = xim + dy;\n\t\tconst Eigen::Vector2d xi_dx = xi + dx; const Eigen::Vector2d xi_dy = xi + dy;\n\t\tconst Eigen::Vector2d xip_dx = xip + dx; const Eigen::Vector2d xip_dy = xip + dy;\n\n\t\tconst Eigen::Vector2d e_prev = xi - xim;\n\t\tconst Eigen::Vector2d e_next = xip - xi;\n\n\t\tconst Eigen::Vector2d e_prev_im_dx = xi - xim_dx; const Eigen::Vector2d e_prev_im_dy = xi - xim_dy;\n\t\tconst Eigen::Vector2d e_prev_i_dx = xi_dx - xim; const Eigen::Vector2d e_prev_i_dy = xi_dy - xim;\n\n\t\tconst Eigen::Vector2d e_next_i_dx = xip - xi_dx; const Eigen::Vector2d e_next_i_dy = xip - xi_dy;\n\t\tconst Eigen::Vector2d e_next_ip_dx = xip_dx - xi; const Eigen::Vector2d e_next_ip_dy = xip_dy - xi;\n\n\t\t/*\n\t\tconst double omega = 2.0 * fabs(e_prev(0)*e_next(1)-e_prev(1)*e_next(0)) / (e_prev.norm()*e_next.norm() + e_prev.dot(e_next));\n\n\t\tconst double omega_im_dx = 2.0 * fabs(e_prev_im_dx(0)*e_next(1)-e_prev_im_dx(1)*e_next(0)) / (e_prev_im_dx.norm()*e_next.norm() + e_prev_im_dx.dot(e_next));\n\t\tconst double omega_im_dy = 2.0 * fabs(e_prev_im_dy(0)*e_next(1)-e_prev_im_dy(1)*e_next(0)) / (e_prev_im_dy.norm()*e_next.norm() + e_prev_im_dy.dot(e_next));\n\t\tconst double omega_i_dx = 2.0 * fabs(e_prev_i_dx(0)*e_next_i_dx(1)-e_prev_i_dx(1)*e_next_i_dx(0)) / (e_prev_i_dx.norm()*e_next_i_dx.norm() + e_prev_i_dx.dot(e_next_i_dx));\n\t\tconst double omega_i_dy = 2.0 * fabs(e_prev_i_dy(0)*e_next_i_dy(1)-e_prev_i_dy(1)*e_next_i_dy(0)) / (e_prev_i_dy.norm()*e_next_i_dy.norm() + e_prev_i_dy.dot(e_next_i_dy));\n\t\tconst double omega_ip_dx = 2.0 * fabs(e_prev(0)*e_next_ip_dx(1)-e_prev(1)*e_next_ip_dx(0)) / (e_prev.norm()*e_next_ip_dx.norm() + e_prev.dot(e_next_ip_dx));\n\t\tconst double omega_ip_dy = 2.0 * fabs(e_prev(0)*e_next_ip_dy(1)-e_prev(1)*e_next_ip_dy(0)) / (e_prev.norm()*e_next_ip_dy.norm() + e_prev.dot(e_next_ip_dy));\n\t\t//*/\n\n\t\tconst double omega = computeOmega(e_prev, e_next);\n\n\t\tconst double omega_im_dx = computeOmega(e_prev_im_dx, e_next);\n\t\tconst double omega_im_dy = computeOmega(e_prev_im_dy, e_next);\n\t\tconst double omega_i_dx = computeOmega(e_prev_i_dx, e_next_i_dx);\n\t\tconst double omega_i_dy = computeOmega(e_prev_i_dy, e_next_i_dy);\n\t\tconst double omega_ip_dx = computeOmega(e_prev, e_next_ip_dx);\n\t\tconst double omega_ip_dy = computeOmega(e_prev, e_next_ip_dy);\t\t\n\n\t\tconst double fi = sqrt(in_Params->alpha/(restL_m + restL)) * omega; //omega_bar will be cancelled out, so omit it\n\t\tconst double fi_im_dx = sqrt(in_Params->alpha/(restL_m + restL)) * omega_im_dx;\n\t\tconst double fi_im_dy = sqrt(in_Params->alpha/(restL_m + restL)) * omega_im_dy;\n\t\tconst double fi_i_dx = sqrt(in_Params->alpha/(restL_m + restL)) * omega_i_dx;\n\t\tconst double fi_i_dy = sqrt(in_Params->alpha/(restL_m + restL)) * omega_i_dy;\n\t\tconst double fi_ip_dx = sqrt(in_Params->alpha/(restL_m + restL)) * omega_ip_dx;\n\t\tconst double fi_ip_dy = sqrt(in_Params->alpha/(restL_m + restL)) * omega_ip_dy;\n\t\t\n\t\tio_Jacobian(i+offset_row, iim) = (fi_im_dx - fi) / epsilon;\n\t\tio_Jacobian(i+offset_row, iim+in_Curve->nVertices) = (fi_im_dy - fi) / epsilon;\n\n\t\tio_Jacobian(i+offset_row, ii) = (fi_i_dx - fi) / epsilon;\n\t\tio_Jacobian(i+offset_row, ii+in_Curve->nVertices) = (fi_i_dy - fi) / epsilon;\n\n\t\tio_Jacobian(i+offset_row, iip) = (fi_ip_dx - fi) / epsilon;\n\t\tio_Jacobian(i+offset_row, iip+in_Curve->nVertices) = (fi_ip_dy - fi) / epsilon;\n\t}\n}\n\nvoid computeNumericalDerivative_fit(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position, double epsilon, Eigen::MatrixXd& io_Jacobian, int offset_row)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tassert(io_Jacobian.rows() >= nSegs + offset_row);\n\tassert(io_Jacobian.cols() == in_Curve->nVertices * 2);\n\n\tconst Eigen::Vector2d dx(epsilon, 0.0); \n\tconst Eigen::Vector2d dy(0.0, epsilon);\n\n\t//dfit/dxi, dfit/dyi\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\t//l_i is a function of x_i, x_{i+1}, y_i and y_{i+1}\n\t\tint ip = (i+1) % in_Curve->nVertices;\n\n\t\tconst Eigen::Vector2d xi = in_Position.col(i);\n\t\tconst Eigen::Vector2d xip = in_Position.col(ip);\n\t\tconst double restL = in_Curve->restLengths(i);\n\n\t\tconst double fi = sqrt(in_Params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_Params, xi, xip, restL));\n\n\t\t//dfit/dxi_i\n\t\tconst Eigen::Vector2d xi_dx = xi + dx;\n\t\tconst double fi_i_dx = sqrt(in_Params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_Params, xi_dx, xip, restL));\n\t\tio_Jacobian(i+offset_row, i) = (fi_i_dx - fi) / epsilon;\n\n\t\t//dfit/dyi_i\n\t\tconst Eigen::Vector2d xi_dy = xi + dy;\n\t\tconst double fi_i_dy = sqrt(in_Params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_Params, xi_dy, xip, restL));\n\t\tio_Jacobian(i+offset_row, i+in_Curve->nVertices) = (fi_i_dy - fi) / epsilon;\n\n\t\t//dfit/dxi_ip\n\t\tconst Eigen::Vector2d xip_dx = xip + dx;\n\t\tconst double fi_ip_dx = sqrt(in_Params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_Params, xi, xip_dx, restL));\n\t\tio_Jacobian(i+offset_row, ip) = (fi_ip_dx - fi) / epsilon;\n\t\t\n\t\t//dfit/dyi_i\n\t\tconst Eigen::Vector2d xip_dy = xip + dy;\n\t\tconst double fi_ip_dy = sqrt(in_Params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_Params, xi, xip_dy, restL));\n\t\tio_Jacobian(i+offset_row, ip+in_Curve->nVertices) = (fi_ip_dy - fi) / epsilon;\n\t}\n}\n\nvoid computeNumericalDerivative(const SParameters* in_Params, const SCurve* in_Curve, const SVar& in_Vars, double epsilon, Eigen::MatrixXd& io_Jacobian)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\tint nAngles = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 2; \n\n\t//assert(io_Jacobian.rows() == nSegs + nAngles + nSegs);\n\t//assert(io_Jacobian.cols() == in_Curve->nVertices * 2);\n\t//assert(in_Vars.pos.cols() == in_Curve->nVertices);\n\t//assert(in_Vars.conf.cols() == in_Curve->nVertices);\n\n\tio_Jacobian.setZero();\n\n\tcomputeNumericalDerivative_elastic(in_Params, in_Curve, in_Vars.pos, epsilon, io_Jacobian, 0);\n\tcomputeNumericalDerivative_bending(in_Params, in_Curve, in_Vars.pos, epsilon, io_Jacobian, nSegs);\n\tcomputeNumericalDerivative_fit(in_Params, in_Curve, in_Vars.pos, epsilon, io_Jacobian, nSegs+nAngles);\n\n\t/*\n\tprintf(\"B: [\\n\");\n\tfor(int j=0; j<io_Jacobian.rows(); j++)\n\t{\n\t\tprintf(\"[\");\n\t\tfor(int i=0; i<io_Jacobian.cols(); i++)\n\t\t{\n\t\t\tif(i<io_Jacobian.cols()-1) printf(\"%f, \", io_Jacobian(j, i));\n\t\t\telse printf(\"%f],\\n\", io_Jacobian(j, i));\n\t\t}\n\t}\n\tprintf(\"]\\n\");\n\t//*/\n}\n\nvoid updateRestLength(const Eigen::Matrix2Xd& in_Position, SCurve* io_Curve)\n{\n\tint nSegs = io_Curve->closed ? io_Curve->nVertices : io_Curve->nVertices - 1;\n\tassert(io_Curve->nVertices == in_Position.cols());\n\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % io_Curve->nVertices;\n\t\tconst Eigen::Vector2d diff = in_Position.col(ip) - in_Position.col(i);\n\t\tio_Curve->restLengths(i) = diff.norm();\n\t}\n}\n\nvoid updateCurveSubdivision(const SParameters* in_Params, SVar& io_InitialVars, SVar& io_Vars, SCurve* io_Curve, SSolverVars& io_SolverVars)\n{\n\tint nSegs = io_Curve->closed ? io_Curve->nVertices : io_Curve->nVertices - 1;\n\t//assert(io_Curve->nVertices == in_Position.cols());\n\n\tstd::vector<SPoint2D> pos;\n\tstd::vector<double> angles;\n\tstd::vector<int> vids;\n\n\tbool subdivided = false;\n\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tSPoint2D p; p.x[0] = io_Vars.pos.col(i)(0); p.x[1] = io_Vars.pos.col(i)(1);\n\t\tpos.push_back(p);\n\t\tvids.push_back(io_Curve->vertexIDs(i));\n\n\t\tif(i!=0 || io_Curve->closed) angles.push_back(io_Curve->restAngles(i));\n\n\t\tint ip = (i+1) % io_Curve->nVertices;\n\t\tconst Eigen::Vector2d diff = io_Vars.pos.col(ip) - io_Vars.pos.col(i);\n\t\tif(diff.norm() > in_Params->refLength)\n\t\t{\n\t\t\tSPoint2D p;\n\t\t\tp.x[0] = (io_Vars.pos.col(ip)(0) + io_Vars.pos.col(i)(0)) * 0.5;\n\t\t\tp.x[1] = (io_Vars.pos.col(ip)(1) + io_Vars.pos.col(i)(1)) * 0.5;\n\t\t\tpos.push_back(p);\n\t\t\t//angles.push_back((io_Curve->restAngles(i) + io_Curve->restAngles(ip)) * 0.5);\n\t\t\tangles.push_back(PI);\n\t\t\tvids.push_back(-1);\n\t\t\tsubdivided = true;\n\t\t}\n\t}\n\n\tif(!io_Curve->closed)\n\t{\n\t\tint ilast = io_Curve->nVertices-1;\n\t\tSPoint2D p; p.x[0] = io_Vars.pos.col(ilast)(0); p.x[1] = io_Vars.pos.col(ilast)(1);\n\t\tpos.push_back(p);\n\t\tvids.push_back(io_Curve->vertexIDs(ilast));\n\t}\n\n\tio_Curve->nVertices = pos.size();\n\tnSegs = io_Curve->closed ? io_Curve->nVertices : io_Curve->nVertices - 1;\n\tio_Curve->restLengths.resize(nSegs);\n\tint nAngles = io_Curve->closed ? io_Curve->nVertices : io_Curve->nVertices - 2; \n\tio_Curve->restAngles.resize(nAngles);\n\tio_Curve->vertexIDs.resize(io_Curve->nVertices);\n\n\tresize(io_Vars, io_Curve->nVertices);\n\tresize(io_InitialVars, io_Curve->nVertices);\n\n\tfor(int i=0; i<io_Curve->nVertices; i++)\n\t{\n\t\tio_Vars.pos.col(i)(0) = pos[i].x[0];\n\t\tio_Vars.pos.col(i)(1) = pos[i].x[1];\n\t\tio_Vars.conf(i) = 0.0;\n\t\tio_Curve->vertexIDs(i) = vids[i];\n\t}\n\n\tnSegs = io_Curve->closed ? io_Curve->nVertices : io_Curve->nVertices - 1;\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % io_Curve->nVertices;\n\t\tconst Eigen::Vector2d diff = io_Vars.pos.col(ip) - io_Vars.pos.col(i);\n\t\tio_Curve->restLengths(i) = diff.norm();\n\t}\n\n\tfor(int i=0; i<nAngles; i++)\n\t\tio_Curve->restAngles(i) = angles[i];\n\n\tio_InitialVars = io_Vars;\n\n\tinitSolverVars(in_Params, io_Curve, io_InitialVars, io_SolverVars, true);\n}\n\nbool secantLMMethodSingleUpdate(const SParameters* in_Params, const SCurve* in_Curve, const SVar& in_InitialVars, SSolverVars& io_SolverVars, SVar& solution)\n{\n\tif(io_SolverVars.found || io_SolverVars.k > in_Params->kmax)\n\t\treturn true;\n\n\tio_SolverVars.k++;\n\tio_SolverVars.A_muI = io_SolverVars.B.transpose() * io_SolverVars.B + io_SolverVars.mu * io_SolverVars.I;\n\tio_SolverVars.h = io_SolverVars.A_muI.ldlt().solve(-io_SolverVars.g);\n\n\tif(io_SolverVars.h.norm() <= in_Params->epsilon_2 * (io_SolverVars.x.pos.norm() + in_Params->epsilon_2))\n\t\tio_SolverVars.found = true;\n\telse\n\t{\n\t\tfor(int q=0; q<io_SolverVars.nV; q++)\n\t\t{\n\t\t\tio_SolverVars.xnew.pos(0, q) = io_SolverVars.x.pos(0, q) + io_SolverVars.h(q);\n\t\t\tio_SolverVars.xnew.pos(1, q) = io_SolverVars.x.pos(1, q) + io_SolverVars.h(q + io_SolverVars.nV);\n\t\t}\n\t}\n\t\t\t\n\tdouble Fnew = 0.5 * computeEnergy(in_Params, in_Curve, io_SolverVars.xnew);\n\tdouble F = 0.5 * computeEnergy(in_Params, in_Curve, io_SolverVars.x);\n\n\tdouble gain_denom = - io_SolverVars.h.dot(io_SolverVars.B.transpose() * io_SolverVars.f) \n\t\t- 0.5 * io_SolverVars.h.dot(io_SolverVars.B.transpose() * io_SolverVars.B * io_SolverVars.h);\n\tdouble gain = (F - Fnew) / gain_denom;\n\n\tif(gain > 0)\n\t{\n\t\tio_SolverVars.x = io_SolverVars.xnew;\n\t\tcompute_f(in_Params, in_Curve, io_SolverVars.x, io_SolverVars.f);\n\t\tcomputeNumericalDerivative(in_Params, in_Curve, io_SolverVars.x, io_SolverVars.epsilon, io_SolverVars.B);\n\t\tio_SolverVars.g = io_SolverVars.B.transpose() * io_SolverVars.f;\n\t\tio_SolverVars.found = (io_SolverVars.g.lpNorm<Eigen::Infinity>() <= in_Params->epsilon_1);\n\t\tprintf(\"k: %d, gain: %f, |g|_inf: %f\\n\", io_SolverVars.k, gain, io_SolverVars.g.lpNorm<Eigen::Infinity>());\n\t\tio_SolverVars.mu = io_SolverVars.mu * std::max(1.0/3.0, 1.0 - (2.0 * gain - 1.0) * (2.0 * gain - 1.0) * (2.0 * gain - 1.0));\n\t\tio_SolverVars.nu = 2.0;\n\t}\n\telse\n\t{\n\t\tio_SolverVars.mu = io_SolverVars.mu * io_SolverVars.nu;\n\t\tio_SolverVars.nu = io_SolverVars.nu * 2.0;\n\t}\n\n\tif(io_SolverVars.found)\n\t\tprintf(\"found in %d steps\\n\", io_SolverVars.k);\n\n\tsolution = io_SolverVars.x;\n\n\treturn io_SolverVars.found || io_SolverVars.k > in_Params->kmax;\n}\n\nvoid showFeaturePoints(const SCurve* in_Curve, const SVar& solution)\n{\n\tprintf(\"Feature points:\\n\");\n\tfor(int i=0; i<in_Curve->nVertices; i++)\n\t{\n\t\tif(in_Curve->vertexIDs(i) >= 0)\n\t\t{\n\t\t\tprintf(\"%d: %f, %f\\n\", in_Curve->vertexIDs(i), solution.pos.col(i).x(), solution.pos.col(i).y());\n\t\t}\n\t}\n}\n\nvoid secantLMMethod(const SParameters* in_Params, SCurve* in_Curve, SVar& in_InitialVars, SSolverVars& io_SolverVars, SVar& solution)\n{\n\tinitSolverVars(in_Params, in_Curve, in_InitialVars, io_SolverVars);\n\n\twhile(1)\n\t{\n\t\tif(secantLMMethodSingleUpdate(in_Params, in_Curve, in_InitialVars, io_SolverVars, solution))\n\t\t\tbreak;\n\t\tupdateCurveSubdivision(in_Params, in_InitialVars, solution, in_Curve, io_SolverVars);\n\t}\n\n\tprintf(\"found in %d steps\\n\", io_SolverVars.k);\n\tsolution = io_SolverVars.x;\n\tshowFeaturePoints(in_Curve, solution);\n}\n", "meta": {"hexsha": "a4011b2e3fcc4c5e681f2ba32315a65527c09f94", "size": 24705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/folding_planner_cmake/project/2dregistration_v2/registration.cpp", "max_stars_repo_name": "roop-pal/robotic-folding", "max_stars_repo_head_hexsha": "a0e062ac6d23cd07fe10e3f45abc4ba50e533141", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T16:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T03:15:55.000Z", "max_issues_repo_path": "catkin_ws/src/folding_planner_cmake/project/2dregistration_v2/registration.cpp", "max_issues_repo_name": "roop-pal/robotic-folding", "max_issues_repo_head_hexsha": "a0e062ac6d23cd07fe10e3f45abc4ba50e533141", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-17T04:39:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-17T04:39:38.000Z", "max_forks_repo_path": "catkin_ws/src/folding_planner_cmake/project/2dregistration_v2/registration.cpp", "max_forks_repo_name": "roop-pal/robotic-folding", "max_forks_repo_head_hexsha": "a0e062ac6d23cd07fe10e3f45abc4ba50e533141", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-03-18T14:13:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-15T15:03:51.000Z", "avg_line_length": 38.3618012422, "max_line_length": 192, "alphanum_fraction": 0.6960534305, "num_tokens": 8425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.646934688291733}}
{"text": "#include <boost/math/special_functions/binomial.hpp>\n\n#include <iostream>\n#include <ctime>\n#include <cassert>\n#include <vector>\n#include <algorithm>\n#include <math.h> \n\ndouble condRankP(unsigned int r, unsigned int c, double p, unsigned int q);\ndouble nCkF(unsigned int n, unsigned int k);\ndouble rhoF(unsigned int l, unsigned int e, unsigned int q, double p);\ndouble piF(unsigned int l, unsigned int e, unsigned int q, double p);\n", "meta": {"hexsha": "8964bdf2e9d642b43c2c20007344cd2c57bb38b9", "size": 431, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trunk/+simLib/src/C-mexed/rankProbApp.hpp", "max_stars_repo_name": "andreatassi/SparseRLNC", "max_stars_repo_head_hexsha": "7b98409409762e381c2da4633e0fb584909393e6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "trunk/+simLib/src/C-mexed/rankProbApp.hpp", "max_issues_repo_name": "andreatassi/SparseRLNC", "max_issues_repo_head_hexsha": "7b98409409762e381c2da4633e0fb584909393e6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trunk/+simLib/src/C-mexed/rankProbApp.hpp", "max_forks_repo_name": "andreatassi/SparseRLNC", "max_forks_repo_head_hexsha": "7b98409409762e381c2da4633e0fb584909393e6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7857142857, "max_line_length": 75, "alphanum_fraction": 0.7494199536, "num_tokens": 105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6469346815387549}}
{"text": "/* boost random/linear_congruential.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Permission to use, copy, modify, sell, and distribute this software\n * is hereby granted without fee provided that the above copyright notice\n * appears in all copies and that both that copyright notice and this\n * permission notice appear in supporting documentation,\n *\n * Jens Maurer makes no representations about the suitability of this\n * software for any purpose. It is provided \"as is\" without express or\n * implied warranty.\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: linear_congruential.hpp 12208 2002-01-03 22:21:34Z jmaurer $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP\n#define BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP\n\n#include <iostream>\n#include <cassert>\n#include <boost/config.hpp>\n#include <boost/random/detail/const_mod.hpp>\n\nnamespace boost {\nnamespace random {\n\n// compile-time configurable linear congruential generator\ntemplate<class IntType, IntType a, IntType c, IntType m, IntType val>\nclass linear_congruential\n{\npublic:\n  typedef IntType result_type;\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n  static const bool has_fixed_range = true;\n  static const result_type min_value = ( c == 0 ? 1 : 0 );\n  static const result_type max_value = m-1;\n#else\n  BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);\n#endif\n  BOOST_STATIC_CONSTANT(IntType, multiplier = a);\n  BOOST_STATIC_CONSTANT(IntType, increment = c);\n  BOOST_STATIC_CONSTANT(IntType, modulus = m);\n\n  result_type min() const { return c == 0 ? 1 : 0; }\n  result_type max() const { return m-1; }\n  explicit linear_congruential(IntType x0 = 1)\n    : _x(x0)\n  { \n    assert(c || x0); /* if c == 0 and x(0) == 0 then x(n) = 0 for all n */\n    // overflow check\n    // disabled because it gives spurious \"divide by zero\" gcc warnings\n    // assert(m == 0 || (a*(m-1)+c) % m == (c < a ? c-a+m : c-a)); \n  }\n  // compiler-generated copy constructor and assignment operator are fine\n  void seed(IntType x0) { assert(c || x0); _x = x0; }\n  IntType operator()()\n  {\n    _x = const_mod<IntType, m>::mult_add(a, _x, c);\n    return _x;\n  }\n  bool validation(IntType x) const { return val == x; }\n\n#ifndef  BOOST_NO_OPERATORS_IN_NAMESPACE\n  friend std::ostream& operator<<(std::ostream& os,\n                                  const linear_congruential& lcg)\n  { os << lcg._x; return os; }\n  friend std::istream& operator>>(std::istream& is, linear_congruential& lcg)\n  { is >> lcg._x; return is; }\n  friend bool operator==(const linear_congruential& x,\n                         const linear_congruential& y)\n  { return x._x == y._x; }\n#else\n  // Use a member function; Streamable concept not supported.\n  bool operator==(const linear_congruential& rhs) const\n  { return _x == rhs._x; }\n#endif\nprivate:\n  IntType _x;\n};\n\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n//  A definition is required even for integral static constants\ntemplate<class IntType, IntType a, IntType c, IntType m, IntType val>\nconst bool linear_congruential<IntType, a, c, m, val>::has_fixed_range;\ntemplate<class IntType, IntType a, IntType c, IntType m, IntType val>\nconst typename linear_congruential<IntType, a, c, m, val>::result_type linear_congruential<IntType, a, c, m, val>::min_value;\ntemplate<class IntType, IntType a, IntType c, IntType m, IntType val>\nconst typename linear_congruential<IntType, a, c, m, val>::result_type linear_congruential<IntType, a, c, m, val>::max_value;\n#endif\n\n} // namespace random\n\n// validation values from the publications\ntypedef random::linear_congruential<int32_t, 16807, 0, 2147483647, \n  1043618065> minstd_rand0;\ntypedef random::linear_congruential<int32_t, 48271, 0, 2147483647,\n  399268537> minstd_rand;\n\n\n#if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)\n// emulate the lrand48() C library function; requires support for uint64_t\nclass rand48 \n{\npublic:\n  typedef int32_t result_type;\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n  static const bool has_fixed_range = true;\n  static const int32_t min_value = 0;\n  static const int32_t max_value = integer_traits<int32_t>::const_max;\n#else\n  enum { has_fixed_range = false };\n#endif\n  int32_t min() const { return 0; }\n  int32_t max() const { return std::numeric_limits<int32_t>::max(); }\n  \n  explicit rand48(int32_t x0 = 1) : lcf(cnv(x0)) { }\n  explicit rand48(uint64_t x0) : lcf(x0) { }\n  // compiler-generated copy ctor and assignment operator are fine\n  void seed(int32_t x0) { lcf.seed(cnv(x0)); }\n  void seed(uint64_t x0) { lcf.seed(x0); }\n  int32_t operator()() { return lcf() >> 17; }\n  // by experiment from lrand48()\n  bool validation(int32_t x) const { return x == 1993516219; }\n\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n  friend std::ostream& operator<<(std::ostream& os, const rand48& r)\n  { os << r.lcf; return os; }\n  friend std::istream& operator>>(std::istream& is, rand48& r)\n  { is >> r.lcf; return is; }\n  friend bool operator==(const rand48& x, const rand48& y)\n  { return x.lcf == y.lcf; }\n#else\n  // Use a member function; Streamable concept not supported.\n  bool operator==(const rand48& rhs) const\n  { return lcf == rhs.lcf; }\n#endif\nprivate:\n  random::linear_congruential<uint64_t,\n    uint64_t(0xDEECE66DUL) | (uint64_t(0x5) << 32), // xxxxULL is not portable\n    0xB, uint64_t(1)<<48, /* unknown */ 0> lcf;\n  static uint64_t cnv(int32_t x) \n  { return (static_cast<uint64_t>(x) << 16) | 0x330e;  }\n};\n#endif /* !BOOST_NO_INT64_T && !BOOST_NO_INTEGRAL_INT64_T */\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP\n", "meta": {"hexsha": "f4e84b31ad9bdf9b1049d94a1b3c17930b45b3a7", "size": 5645, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/random/linear_congruential.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/random/linear_congruential.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_28/boost/random/linear_congruential.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["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.6558441558, "max_line_length": 125, "alphanum_fraction": 0.7140832595, "num_tokens": 1622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.798186768138228, "lm_q1q2_score": 0.6469135407557627}}
{"text": "#define BOOST_TEST_MODULE geometry test\n#include <boost/test/included/unit_test.hpp>\n\n#include <cmath>\n\n#include <pastel/geometry/vector.hpp>\n#include <pastel/geometry/vector_io.hpp>\n#include <pastel/geometry/point.hpp>\n#include <pastel/geometry/point_io.hpp>\n#include <pastel/geometry/get.hpp>\n#include <pastel/geometry/dot_product.hpp>\n#include <pastel/geometry/cross_product.hpp>\n#include <pastel/geometry/squared_norm.hpp>\n#include <pastel/geometry/norm.hpp>\n#include <pastel/geometry/meta/dimension_of.hpp>\n\n\nBOOST_AUTO_TEST_CASE(geometry_1dim_test, * boost::unit_test::tolerance(0.000001))\n{\n  using vector_type = pastel::geometry::vector<1u, double>;\n  using point_type = pastel::geometry::point<1u, double>;\n  BOOST_TEST(pastel::geometry::meta::dimension_of<vector_type>::value == 1u);\n  BOOST_TEST(pastel::geometry::meta::dimension_of<point_type>::value == 1u);\n\n  auto const vec1 = vector_type{1.0};\n  auto const vec2 = vector_type{2.0};\n  BOOST_TEST(pastel::geometry::get<0>(vec1) == 1.0);\n  BOOST_TEST(vec1 + vec1 == vec2);\n  BOOST_TEST(vec1 - vec2 == -vec1);\n  BOOST_TEST(2.0 * vec1 == vec2);\n  BOOST_TEST(vec1 * 2.0 == vec2);\n  BOOST_TEST(vec2 / 2.0 == vec1);\n  BOOST_TEST(pastel::geometry::dot_product(vec1, vec2) == 2.0);\n  BOOST_TEST(pastel::geometry::squared_norm(vec1) == 1.0);\n  using std::sqrt;\n  BOOST_TEST(pastel::geometry::norm(vec1) == sqrt(1.0));\n  BOOST_TEST(pastel::geometry::cross_product(vec1, vec2) == 0.0);\n\n  auto const pnt1 = point_type{1.0};\n  auto const pnt2 = point_type{3.0};\n  BOOST_TEST(pastel::geometry::get<0>(pnt1) == 1.0);\n  BOOST_TEST(pnt1 + vec2 == pnt2);\n  BOOST_TEST(vec2 + pnt1 == pnt2);\n  BOOST_TEST(pnt2 - vec2 == pnt1);\n  BOOST_TEST(pnt2 - pnt1 == vec2);\n\n  auto vec3 = vector_type{0.0};\n  vec3.fill(1.0);\n  BOOST_TEST((vec3 == vector_type{1.0}));\n  auto vec4 = vec2;\n  using std::swap;\n  swap(vec3, vec4);\n  BOOST_TEST(vec3 == vec2);\n\n  for (auto& component: vec3)\n    component = 1.0;\n  BOOST_TEST((vec3 == vector_type{1.0}));\n  for (auto iter = vec3.rbegin(), last = vec3.rend(); iter != last; ++iter)\n    *iter = 2.0;\n  BOOST_TEST((vec3 == vector_type{2.0}));\n  BOOST_TEST(vec1.size() == pastel::geometry::meta::dimension_of<vector_type>::value);\n  BOOST_TEST(vec1.max_size() == pastel::geometry::meta::dimension_of<vector_type>::value);\n  BOOST_TEST(!vec1.empty());\n  BOOST_TEST(vec1.at(0u) == vec1.front());\n  BOOST_TEST(vec1.at(vec1.size()-1u) == vec1.back());\n\n  auto pnt3 = point_type{0.0};\n  pnt3.fill(1.0);\n  BOOST_TEST((pnt3 == point_type{1.0}));\n  auto pnt4 = pnt2;\n  using std::swap;\n  swap(pnt3, pnt4);\n  BOOST_TEST(pnt3 == pnt2);\n\n  for (auto& component: pnt3)\n    component = 1.0;\n  BOOST_TEST((pnt3 == point_type{1.0}));\n  for (auto iter = pnt3.rbegin(), last = pnt3.rend(); iter != last; ++iter)\n    *iter = 2.0;\n  BOOST_TEST((pnt3 == point_type{2.0}));\n  BOOST_TEST(pnt1.size() == pastel::geometry::meta::dimension_of<point_type>::value);\n  BOOST_TEST(pnt1.max_size() == pastel::geometry::meta::dimension_of<point_type>::value);\n  BOOST_TEST(!pnt1.empty());\n  BOOST_TEST(pnt1.at(0u) == pnt1.front());\n  BOOST_TEST(pnt1.at(pnt1.size()-1u) == pnt1.back());\n}\n\nBOOST_AUTO_TEST_CASE(geometry_2dim_test, * boost::unit_test::tolerance(0.000001))\n{\n  using vector_type = pastel::geometry::vector<2u, double>;\n  using point_type = pastel::geometry::point<2u, double>;\n  BOOST_TEST(pastel::geometry::meta::dimension_of<vector_type>::value == 2u);\n  BOOST_TEST(pastel::geometry::meta::dimension_of<point_type>::value == 2u);\n\n  auto const vec1 = vector_type{1.0, 2.0};\n  auto const vec2 = vector_type{2.0, 4.0};\n  BOOST_TEST(pastel::geometry::get<0>(vec1) == 1.0);\n  BOOST_TEST(vec1 + vec1 == vec2);\n  BOOST_TEST(vec1 - vec2 == -vec1);\n  BOOST_TEST(2.0 * vec1 == vec2);\n  BOOST_TEST(vec1 * 2.0 == vec2);\n  BOOST_TEST(vec2 / 2.0 == vec1);\n  BOOST_TEST(pastel::geometry::dot_product(vec1, vec2) == 10.0);\n  BOOST_TEST(pastel::geometry::squared_norm(vec1) == 5.0);\n  using std::sqrt;\n  BOOST_TEST(pastel::geometry::norm(vec1) == sqrt(5.0));\n  BOOST_TEST(pastel::geometry::cross_product(vec1, vec2) == 0.0);\n\n  auto const pnt1 = point_type{1.0, 2.0};\n  auto const pnt2 = point_type{3.0, 6.0};\n  BOOST_TEST(pastel::geometry::get<0>(pnt1) == 1.0);\n  BOOST_TEST(pnt1 + vec2 == pnt2);\n  BOOST_TEST(vec2 + pnt1 == pnt2);\n  BOOST_TEST(pnt2 - vec2 == pnt1);\n  BOOST_TEST(pnt2 - pnt1 == vec2);\n\n  auto vec3 = vector_type{0.0, 0.0};\n  vec3.fill(1.0);\n  BOOST_TEST((vec3 == vector_type{1.0, 1.0}));\n  auto vec4 = vec2;\n  using std::swap;\n  swap(vec3, vec4);\n  BOOST_TEST(vec3 == vec2);\n\n  for (auto& component: vec3)\n    component = 1.0;\n  BOOST_TEST((vec3 == vector_type{1.0, 1.0}));\n  for (auto iter = vec3.rbegin(), last = vec3.rend(); iter != last; ++iter)\n    *iter = 2.0;\n  BOOST_TEST((vec3 == vector_type{2.0, 2.0}));\n  BOOST_TEST(vec1.size() == pastel::geometry::meta::dimension_of<vector_type>::value);\n  BOOST_TEST(vec1.max_size() == pastel::geometry::meta::dimension_of<vector_type>::value);\n  BOOST_TEST(!vec1.empty());\n  BOOST_TEST(vec1.at(vec1.size()-1u) == vec1.back());\n\n  auto pnt3 = point_type{0.0, 0.0};\n  pnt3.fill(1.0);\n  BOOST_TEST((pnt3 == point_type{1.0, 1.0}));\n  auto pnt4 = pnt2;\n  using std::swap;\n  swap(pnt3, pnt4);\n  BOOST_TEST(pnt3 == pnt2);\n\n  for (auto& component: pnt3)\n    component = 1.0;\n  BOOST_TEST((pnt3 == point_type{1.0, 1.0}));\n  for (auto iter = pnt3.rbegin(), last = pnt3.rend(); iter != last; ++iter)\n    *iter = 2.0;\n  BOOST_TEST((pnt3 == point_type{2.0, 2.0}));\n  BOOST_TEST(pnt1.size() == pastel::geometry::meta::dimension_of<point_type>::value);\n  BOOST_TEST(pnt1.max_size() == pastel::geometry::meta::dimension_of<point_type>::value);\n  BOOST_TEST(!pnt1.empty());\n  BOOST_TEST(pnt1.at(0u) == pnt1.front());\n  BOOST_TEST(pnt1.at(pnt1.size()-1u) == pnt1.back());\n}\n\nBOOST_AUTO_TEST_CASE(geometry_3dim_test, * boost::unit_test::tolerance(0.000001))\n{\n  using vector_type = pastel::geometry::vector<3u, double>;\n  using point_type = pastel::geometry::point<3u, double>;\n  BOOST_TEST(pastel::geometry::meta::dimension_of<vector_type>::value == 3u);\n  BOOST_TEST(pastel::geometry::meta::dimension_of<point_type>::value == 3u);\n\n  auto const vec1 = vector_type{0.0, 1.0, 2.0};\n  auto const vec2 = vector_type{0.0, 2.0, 4.0};\n  BOOST_TEST(pastel::geometry::get<1>(vec1) == 1.0);\n  BOOST_TEST(vec1 + vec1 == vec2);\n  BOOST_TEST(vec1 - vec2 == -vec1);\n  BOOST_TEST(2.0 * vec1 == vec2);\n  BOOST_TEST(vec1 * 2.0 == vec2);\n  BOOST_TEST(vec2 / 2.0 == vec1);\n  BOOST_TEST(pastel::geometry::dot_product(vec1, vec2) == 10.0);\n  BOOST_TEST(pastel::geometry::squared_norm(vec1) == 5.0);\n  using std::sqrt;\n  BOOST_TEST(pastel::geometry::norm(vec1) == sqrt(5.0));\n  auto const vec0 = vector_type{0.0, 0.0, 0.0};\n  BOOST_TEST(pastel::geometry::cross_product(vec1, vec2) == vec0);\n\n  auto const pnt1 = point_type{0.0, 1.0, 2.0};\n  auto const pnt2 = point_type{0.0, 3.0, 6.0};\n  BOOST_TEST(pastel::geometry::get<1>(pnt1) == 1.0);\n  BOOST_TEST(pnt1 + vec2 == pnt2);\n  BOOST_TEST(vec2 + pnt1 == pnt2);\n  BOOST_TEST(pnt2 - vec2 == pnt1);\n  BOOST_TEST(pnt2 - pnt1 == vec2);\n\n  auto vec3 = vector_type{0.0, 0.0, 0.0};\n  vec3.fill(1.0);\n  BOOST_TEST((vec3 == vector_type{1.0, 1.0, 1.0}));\n  auto vec4 = vec2;\n  using std::swap;\n  swap(vec3, vec4);\n  BOOST_TEST(vec3 == vec2);\n\n  for (auto& component: vec3)\n    component = 1.0;\n  BOOST_TEST((vec3 == vector_type{1.0, 1.0, 1.0}));\n  for (auto iter = vec3.rbegin(), last = vec3.rend(); iter != last; ++iter)\n    *iter = 2.0;\n  BOOST_TEST((vec3 == vector_type{2.0, 2.0, 2.0}));\n  BOOST_TEST(vec1.size() == pastel::geometry::meta::dimension_of<vector_type>::value);\n  BOOST_TEST(vec1.max_size() == pastel::geometry::meta::dimension_of<vector_type>::value);\n  BOOST_TEST(!vec1.empty());\n  BOOST_TEST(vec1.at(vec1.size()-1u) == vec1.back());\n\n  auto pnt3 = point_type{0.0, 0.0, 0.0};\n  pnt3.fill(1.0);\n  BOOST_TEST((pnt3 == point_type{1.0, 1.0, 1.0}));\n  auto pnt4 = pnt2;\n  using std::swap;\n  swap(pnt3, pnt4);\n  BOOST_TEST(pnt3 == pnt2);\n\n  for (auto& component: pnt3)\n    component = 1.0;\n  BOOST_TEST((pnt3 == point_type{1.0, 1.0, 1.0}));\n  for (auto iter = pnt3.rbegin(), last = pnt3.rend(); iter != last; ++iter)\n    *iter = 2.0;\n  BOOST_TEST((pnt3 == point_type{2.0, 2.0, 2.0}));\n  BOOST_TEST(pnt1.size() == pastel::geometry::meta::dimension_of<point_type>::value);\n  BOOST_TEST(pnt1.max_size() == pastel::geometry::meta::dimension_of<point_type>::value);\n  BOOST_TEST(!pnt1.empty());\n  BOOST_TEST(pnt1.at(0u) == pnt1.front());\n  BOOST_TEST(pnt1.at(pnt1.size()-1u) == pnt1.back());\n}\n\n", "meta": {"hexsha": "37c88dd9c25b901354b518b15b17a1eba9fb776f", "size": 8507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/geometry.cpp", "max_stars_repo_name": "naoki-yoshioka/pastel", "max_stars_repo_head_hexsha": "b443dcc6ae86ff3e94ec9c2e7085b5d6521214e8", "max_stars_repo_licenses": ["MIT"], "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/geometry.cpp", "max_issues_repo_name": "naoki-yoshioka/pastel", "max_issues_repo_head_hexsha": "b443dcc6ae86ff3e94ec9c2e7085b5d6521214e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2017-12-23T07:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-20T10:16:37.000Z", "max_forks_repo_path": "test/geometry.cpp", "max_forks_repo_name": "naoki-yoshioka/pastel", "max_forks_repo_head_hexsha": "b443dcc6ae86ff3e94ec9c2e7085b5d6521214e8", "max_forks_repo_licenses": ["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.4757709251, "max_line_length": 90, "alphanum_fraction": 0.6640413777, "num_tokens": 3023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6468633369658743}}
{"text": "#include <iostream>\n#include <rmagine/math/math.h>\n#include <rmagine/math/types.h>\n#include <rmagine/util/StopWatch.hpp>\n\n#include <Eigen/Dense>\n\nusing namespace rmagine;\n\nvoid print(Matrix3x3 M)\n{\n    for(size_t i=0; i<3; i++)\n    {\n        for(size_t j=0; j<3; j++)\n        {\n            std::cout << M(i,j) << \" \";\n        }\n        std::cout << std::endl;\n    }\n}\n\nvoid print(Matrix4x4 M)\n{\n    for(size_t i=0; i<4; i++)\n    {\n        for(size_t j=0; j<4; j++)\n        {\n            std::cout << M(i,j) << \" \";\n        }\n        std::cout << std::endl;\n    }\n}\n\nvoid print(Eigen::Matrix4f M)\n{\n    for(size_t i=0; i<4; i++)\n    {\n        for(size_t j=0; j<4; j++)\n        {\n            std::cout << M(i,j) << \" \";\n        }\n        std::cout << std::endl;\n    }\n}\n\nvoid print(Vector v)\n{\n    std::cout << v.x << \" \" << v.y << \" \" << v.z << std::endl;\n}\n\nvoid print(Quaternion q)\n{\n    std::cout << q.x << \" \" << q.y << \" \" << q.z << \" \" << q.w << std::endl;\n}\n\nvoid print(Transform T)\n{\n    print(T.R);\n    print(T.t);\n}\n\nbool rotationConversionTest()\n{\n    std::cout << std::endl;\n    std::cout << \"--------------------------------\" << std::endl;\n    std::cout << \"---- rotationConversionTest ----\" << std::endl;\n    std::cout << \"--------------------------------\" << std::endl;\n    std::cout << std::endl;\n\n    EulerAngles e0;\n    e0.roll = -0.1;\n    e0.pitch = 0.1;\n    e0.yaw = M_PI / 2.0;\n\n    EulerAngles e;\n    Quaternion q;\n    Matrix3x3 R;\n\n    Vector x1{1.0, 0.0, 0.0};\n    Vector x2{0.0, 1.0, 0.0};\n    Vector x3{0.0, 0.0, 1.0};\n\n    std::cout << \"Euler -> Quat\" << std::endl;\n    q = e0;\n    print(q * x1);\n    print(q * x2);\n    print(q * x3);\n    std::cout << std::endl;\n\n    std::cout << \"Quat -> Euler\" << std::endl;\n    e = q;\n    std::cout << e.roll << \" \" << e.pitch << \" \" << e.yaw << std::endl;\n    std::cout << std::endl;\n\n    if(    fabs(e.roll - e0.roll) > 0.0001 \n        || fabs(e.pitch - e0.pitch) > 0.0001 \n        || fabs(e.yaw - e0.yaw) > 0.0001)\n    {\n        std::cout << \"Euler -> Quat -> Euler error.\" << std::endl;\n        return false;\n    }\n\n    std::cout << \"Euler -> Matrix\" << std::endl;\n    R = e0;\n    print(R * x1);\n    print(R * x2);\n    print(R * x3);\n    std::cout << std::endl;\n\n    std::cout << \"Matrix -> Euler\" << std::endl;\n    e = R;\n    std::cout << e.roll << \" \" << e.pitch << \" \" << e.yaw << std::endl;\n    std::cout << std::endl;\n\n    std::cout << \"Quat -> Matrix\" << std::endl;\n    R = q;\n    print(R * x1);\n    print(R * x2);\n    print(R * x3);\n    std::cout << std::endl;\n\n    std::cout << \"Matrix -> Quat\" << std::endl;\n    q = R;\n    print(q * x1);\n    print(q * x2);\n    print(q * x3);\n    std::cout << std::endl;\n\n    return true;\n}\n\nEigen::Vector3f& eigenView(Vector3& v)\n{\n    return *reinterpret_cast<Eigen::Vector3f*>( &v );\n}\n\nEigen::Matrix3f& eigenView(Matrix3x3& M)\n{\n    return *reinterpret_cast<Eigen::Matrix3f*>( &M );\n}\n\nEigen::Matrix4f& eigenView(Matrix4x4& M)\n{\n    return *reinterpret_cast<Eigen::Matrix4f*>( &M );\n}\n\nbool checkMatrix3x3()\n{\n    std::cout << \"---------- checkMatrix3x3\" << std::endl;\n    EulerAngles e{-0.1, 0.1, M_PI / 2.0};\n\n    Matrix3x3 M;\n    M = e;\n    M(0,1) = 10.0;\n\n    // shallow copy. \n    Eigen::Matrix3f& Meig_shallow = eigenView(M);\n    std::cout << Meig_shallow << std::endl;\n\n    // deep copy\n    Eigen::Matrix3f Meig(&M(0,0));\n\n\n    // Eigen::Matrix3f Meig_inv = Meig.inverse();\n    Matrix3x3 M_inv = ~M;\n    Eigen::Matrix3f Meig_inv = Meig.inverse();\n\n    // std::cout << Meig_inv << std::endl;\n    // print(M_inv);\n    Matrix3x3 I = M_inv * M;\n    Eigen::Matrix3f Ieig = Meig_inv * Meig;\n\n    std::cout << \"M = \" << std::endl;\n    print(M);\n\n    std::cout << \"M_inv = \" << std::endl;\n    print(M_inv);\n\n    std::cout << \"M_inv * M = \" << std::endl;\n    print(I);\n\n    std::cout << \"Meig = \" << std::endl;\n    std::cout << Meig << std::endl;\n\n    std::cout << \"Meig_inv = \" << std::endl;\n    std::cout << Meig_inv << std::endl;\n\n    std::cout << \"Meig_inv * Meig =\" << std::endl;\n    std::cout << Meig_inv * Meig <<  std::endl;\n    \n\n    std::cout << \"Eigen::Matrix3f stats: \" << std::endl;\n    std::cout << \"- det: \" << Meig.determinant() << std::endl;\n    std::cout << \"- trace: \" << Meig.trace() << std::endl;\n    \n\n    std::cout << \"Matrix3x3 stats:\" << std::endl;\n    std::cout << \"- det: \" << M.det() << std::endl;\n    std::cout << \"- trace: \" << M.trace() << std::endl;\n\n    return true;\n}\n\nbool checkMatrix4x4()\n{\n    std::cout << \"------- checkMatrix4x4\" << std::endl;\n    EulerAngles e{-0.1, 0.1, M_PI / 2.0};\n\n    Matrix4x4 M;\n    M.setIdentity();\n    M.setRotation(e);\n\n    Eigen::Matrix4f& Meig_shallow = eigenView(M);\n    \n    \n    // M(0,1) = 10.0;\n\n    Vector trans{0.0, 0.0, 1.0};\n    M.setTranslation(trans);\n\n    std::cout << Meig_shallow << std::endl;\n\n    Matrix4x4 M_inv = M.inv();\n    Matrix4x4 I = M_inv * M;\n\n\n    std::cout << \"M = \" << std::endl;\n    print(M);\n    std::cout << \"M_inv = \" << std::endl;\n    print(M_inv);\n    std::cout << \"(invRigid)=\" << std::endl;\n    print(M.invRigid());\n    \n    std::cout << \"M_inv * M = \" << std::endl;\n    print(I);\n\n    Eigen::Matrix4f Meig(&M(0,0));\n    Eigen::Matrix4f Meig_inv = Meig.inverse();\n\n    std::cout << \"Meig = \" << std::endl;\n    std::cout << Meig << std::endl;\n\n    std::cout << \"Meig_inv = \" << std::endl;\n    std::cout << Meig_inv << std::endl;\n\n    std::cout << \"Meig_inv * Meig =\" << std::endl;\n    std::cout << Meig_inv * Meig <<  std::endl;\n\n\n    std::cout << \"Eigen::Matrix4f stats: \" << std::endl;\n    std::cout << \"- det: \" << Meig.determinant() << std::endl;\n    std::cout << \"- trace: \" << Meig.trace() << std::endl;\n    \n    std::cout << \"Matrix4x4 stats:\" << std::endl;\n    std::cout << \"- det: \" << M.det() << std::endl;\n    std::cout << \"- trace: \" << M.trace() << std::endl;\n\n    return true;\n}\n\n\nint main(int argc, char** argv)\n{\n    std::cout << \"Rmagine Test: Basic Math\" << std::endl;\n    // rotationConversionTest();\n\n\n    // checkMatrix3x3();\n    // checkMatrix4x4();\n\n    Vector ab{1.0, 2.0, 3.0};\n    Vector ac{4.0, 5.0, 6.0};\n    Vector n{7.0, 8.0, 9.0};\n\n\n    Eigen::Matrix3f R;\n    R.col(0) = Eigen::Vector3f(ab.x, ab.y, ab.z);\n    R.col(1) = Eigen::Vector3f(ac.x, ac.y, ac.z);\n    R.col(2) = Eigen::Vector3f(n.x, n.y, n.z);\n\n    std::cout << R << std::endl;\n\n    R(0,0) = ab.x;\n    R(1,0) = ab.y;\n    R(2,0) = ab.z;\n\n    R(0,1) = ac.x;\n    R(1,1) = ac.y;\n    R(2,1) = ac.z;\n\n    R(0,2) = n.x;\n    R(1,2) = n.y;\n    R(2,2) = n.z;\n\n    std::cout << R << std::endl;\n\n\n    return 0;\n}", "meta": {"hexsha": "16d5f1b93dd9517863d2f52cc1b0ce5305e0d50a", "size": 6506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rmagine_tests/basic_math/Main.cpp", "max_stars_repo_name": "uos/rmagine", "max_stars_repo_head_hexsha": "b2228d77ea685af050e43c697d3a76535a9d8940", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-30T07:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:31:03.000Z", "max_issues_repo_path": "src/rmagine_tests/basic_math/Main.cpp", "max_issues_repo_name": "uos/rmagine", "max_issues_repo_head_hexsha": "b2228d77ea685af050e43c697d3a76535a9d8940", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rmagine_tests/basic_math/Main.cpp", "max_forks_repo_name": "uos/rmagine", "max_forks_repo_head_hexsha": "b2228d77ea685af050e43c697d3a76535a9d8940", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7591973244, "max_line_length": 76, "alphanum_fraction": 0.4875499539, "num_tokens": 2275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.6468517983783467}}
{"text": "/* Boost numeric test of the rosenbrock4 stepper test file\n\n Copyright 2012 Karsten Ahnert\n Copyright 2012 Mario Mulansky\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n*/\n\n// disable checked iterator warning for msvc\n#include <boost/config.hpp>\n#ifdef BOOST_MSVC\n    #pragma warning(disable:4996)\n#endif\n\n#define BOOST_TEST_MODULE numeric_rosenbrock\n\n#include <iostream>\n#include <cmath>\n\n#include <boost/array.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/numeric/odeint/stepper/rosenbrock4.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\n\ntypedef double value_type;\ntypedef boost::numeric::ublas::vector< value_type > state_type;\ntypedef boost::numeric::ublas::matrix< value_type > matrix_type;\n\n// harmonic oscillator, analytic solution x[0] = sin( t )\nstruct sys\n{\n    void operator()( const state_type &x , state_type &dxdt , const value_type &t ) const\n    {\n        dxdt( 0 ) = x( 1 );\n        dxdt( 1 ) = -x( 0 );\n    }\n};\n\nstruct jacobi\n{\n    void operator()( const state_type &x , matrix_type &jacobi , const value_type &t , state_type &dfdt ) const\n    {\n        jacobi( 0 , 0 ) = 0;\n        jacobi( 0 , 1 ) = 1;\n        jacobi( 1 , 0 ) = -1;\n        jacobi( 1 , 1 ) = 0;\n        dfdt( 0 ) = 0.0;\n        dfdt( 1 ) = 0.0;\n    }\n};\n\n\nBOOST_AUTO_TEST_SUITE( numeric_rosenbrock4 )\n\nBOOST_AUTO_TEST_CASE( rosenbrock4_numeric_test )\n{\n    typedef rosenbrock4< value_type > stepper_type;\n    stepper_type stepper;\n\n    const int o = stepper.order()+1;\n\n    state_type x0( 2 ) , x1( 2 );\n    x0(0) = 0.0; x0(1) = 1.0;\n\n    double dt = 0.5;\n\n    stepper.do_step( std::make_pair( sys() , jacobi() ) , x0 , 0.0 , x1 , dt );\n    const double f = 2.0 * std::abs( sin(dt) - x1(0) ) / std::pow( dt , o );\n\n    std::cout << o << \" , \" << f << std::endl;\n\n    while( f*std::pow( dt , o ) > 1E-16 )\n    {\n        stepper.do_step( std::make_pair( sys() , jacobi() ) , x0 , 0.0 , x1 , dt );\n        std::cout << \"Testing dt=\" << dt << std::endl;\n        BOOST_CHECK_SMALL( std::abs( sin(dt) - x1(0) ) , f*std::pow( dt , o ) );\n        dt *= 0.5;\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0bb83650b440a23037df8de6a9cf49be6b2a7d37", "size": 2309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/test/numeric/rosenbrock.cpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/test/numeric/rosenbrock.cpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/test/numeric/rosenbrock.cpp", "max_forks_repo_name": "473867143/Prometheus", "max_forks_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 25.6555555556, "max_line_length": 111, "alphanum_fraction": 0.6288436553, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6468391811332691}}
{"text": "/*\n    MIT License\n\n    Copyright (c) 2021 Zhepei Wang (wangzhepei@live.com)\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n*/\n\n#ifndef GEO_UTILS_HPP\n#define GEO_UTILS_HPP\n\n#include \"quickhull.hpp\"\n#include \"sdlp.hpp\"\n\n#include <Eigen/Eigen>\n\n#include <cfloat>\n#include <cstdint>\n#include <set>\n#include <chrono>\n\nnamespace geo_utils\n{\n\n    // Each row of hPoly is defined by h0, h1, h2, h3 as\n    // h0*x + h1*y + h2*z + h3 <= 0\n    inline bool findInterior(const Eigen::MatrixX4d &hPoly,\n                             Eigen::Vector3d &interior)\n    {\n        const int m = hPoly.rows();\n\n        Eigen::MatrixX4d A(m, 4);\n        Eigen::VectorXd b(m);\n        Eigen::Vector4d c, x;\n        const Eigen::ArrayXd hNorm = hPoly.leftCols<3>().rowwise().norm();\n        A.leftCols<3>() = hPoly.leftCols<3>().array().colwise() / hNorm;\n        A.rightCols<1>().setConstant(1.0);\n        b = -hPoly.rightCols<1>().array() / hNorm;\n        c.setZero();\n        c(3) = -1.0;\n\n        const double minmaxsd = sdlp::linprog<4>(c, A, b, x);\n        interior = x.head<3>();\n\n        return minmaxsd < 0.0 && !std::isinf(minmaxsd);\n    }\n\n    inline bool overlap(const Eigen::MatrixX4d &hPoly0,\n                        const Eigen::MatrixX4d &hPoly1,\n                        const double eps = 1.0e-6)\n\n    {\n        const int m = hPoly0.rows();\n        const int n = hPoly1.rows();\n        Eigen::MatrixX4d A(m + n, 4);\n        Eigen::Vector4d c, x;\n        Eigen::VectorXd b(m + n);\n        A.leftCols<3>().topRows(m) = hPoly0.leftCols<3>();\n        A.leftCols<3>().bottomRows(n) = hPoly1.leftCols<3>();\n        A.rightCols<1>().setConstant(1.0);\n        b.topRows(m) = -hPoly0.rightCols<1>();\n        b.bottomRows(n) = -hPoly1.rightCols<1>();\n        c.setZero();\n        c(3) = -1.0;\n\n        const double minmaxsd = sdlp::linprog<4>(c, A, b, x);\n\n        return minmaxsd < -eps && !std::isinf(minmaxsd);\n    }\n\n    struct filterLess\n    {\n        inline bool operator()(const Eigen::Vector3d &l,\n                               const Eigen::Vector3d &r)\n        {\n            return l(0) < r(0) ||\n                   (l(0) == r(0) &&\n                    (l(1) < r(1) ||\n                     (l(1) == r(1) &&\n                      l(2) < r(2))));\n        }\n    };\n\n    inline void filterVs(const Eigen::Matrix3Xd &rV,\n                         const double &epsilon,\n                         Eigen::Matrix3Xd &fV)\n    {\n        const double mag = std::max(fabs(rV.maxCoeff()), fabs(rV.minCoeff()));\n        const double res = mag * std::max(fabs(epsilon) / mag, DBL_EPSILON);\n        std::set<Eigen::Vector3d, filterLess> filter;\n        fV = rV;\n        int offset = 0;\n        Eigen::Vector3d quanti;\n        for (int i = 0; i < rV.cols(); i++)\n        {\n            quanti = (rV.col(i) / res).array().round();\n            if (filter.find(quanti) == filter.end())\n            {\n                filter.insert(quanti);\n                fV.col(offset) = rV.col(i);\n                offset++;\n            }\n        }\n        fV = fV.leftCols(offset).eval();\n        return;\n    }\n\n    // Each row of hPoly is defined by h0, h1, h2, h3 as\n    // h0*x + h1*y + h2*z + h3 <= 0\n    // proposed epsilon is 1.0e-6\n    inline void enumerateVs(const Eigen::MatrixX4d &hPoly,\n                            const Eigen::Vector3d &inner,\n                            Eigen::Matrix3Xd &vPoly,\n                            const double epsilon = 1.0e-6)\n    {\n        const Eigen::VectorXd b = -hPoly.rightCols<1>() - hPoly.leftCols<3>() * inner;\n        const Eigen::Matrix<double, 3, -1, Eigen::ColMajor> A =\n            (hPoly.leftCols<3>().array().colwise() / b.array()).transpose();\n\n        quickhull::QuickHull<double> qh;\n        const double qhullEps = std::min(epsilon, quickhull::defaultEps<double>());\n        // CCW is false because the normal in quickhull towards interior\n        const auto cvxHull = qh.getConvexHull(A.data(), A.cols(), false, true, qhullEps);\n        const auto &idBuffer = cvxHull.getIndexBuffer();\n        const int hNum = idBuffer.size() / 3;\n        Eigen::Matrix3Xd rV(3, hNum);\n        Eigen::Vector3d normal, point, edge0, edge1;\n        for (int i = 0; i < hNum; i++)\n        {\n            point = A.col(idBuffer[3 * i + 1]);\n            edge0 = point - A.col(idBuffer[3 * i]);\n            edge1 = A.col(idBuffer[3 * i + 2]) - point;\n            normal = edge0.cross(edge1); //cross in CW gives an outter normal\n            rV.col(i) = normal / normal.dot(point);\n        }\n        filterVs(rV, epsilon, vPoly);\n        vPoly = (vPoly.array().colwise() + inner.array()).eval();\n        return;\n    }\n\n    // Each row of hPoly is defined by h0, h1, h2, h3 as\n    // h0*x + h1*y + h2*z + h3 <= 0\n    // proposed epsilon is 1.0e-6\n    inline bool enumerateVs(const Eigen::MatrixX4d &hPoly,\n                            Eigen::Matrix3Xd &vPoly,\n                            const double epsilon = 1.0e-6)\n    {\n        Eigen::Vector3d inner;\n        if (findInterior(hPoly, inner))\n        {\n            enumerateVs(hPoly, inner, vPoly, epsilon);\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n\n} // namespace geo_utils\n\n#endif\n", "meta": {"hexsha": "4d36966f8ce91ab01653da5dcd4a12c6ffcfba80", "size": 6222, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gcopter/include/gcopter/geo_utils.hpp", "max_stars_repo_name": "RENyunfan/GCOPTER", "max_stars_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T11:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:17:51.000Z", "max_issues_repo_path": "gcopter/include/gcopter/geo_utils.hpp", "max_issues_repo_name": "RENyunfan/GCOPTER", "max_issues_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gcopter/include/gcopter/geo_utils.hpp", "max_forks_repo_name": "RENyunfan/GCOPTER", "max_forks_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7597765363, "max_line_length": 89, "alphanum_fraction": 0.5515911283, "num_tokens": 1702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6468391615518303}}
{"text": "/* Copyright (c) 2021, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#include <ensemble_management.hh>\n\n#include <deal.II/base/mpi.h>\n\n#include <execution>\n#include <numeric>\n\n#define BOOST_TEST_MODULE EnsembleManagement\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\n#include \"main.cc\"\n\nBOOST_AUTO_TEST_CASE(fill_and_sync_random_vector)\n{\n  // Fairly loose tolerance because this is a statistical check\n  double tolerance = 10.0;\n\n  // Create the random vector\n  double mean = -1.2;\n  double stddev = 0.25;\n  unsigned int ensemble_size = 5000;\n  std::vector<double> vec =\n      adamantine::fill_and_sync_random_vector(ensemble_size, mean, stddev);\n\n  // Check vector size\n  BOOST_CHECK(vec.size() == ensemble_size);\n\n  // Check vector mean\n  double mean_check =\n      std::reduce(std::execution::par, vec.cbegin(), vec.cend()) /\n      ensemble_size;\n\n  BOOST_CHECK_CLOSE(mean, mean_check, tolerance);\n\n  // Check vector variance\n  boost::accumulators::accumulator_set<\n      double, boost::accumulators::features<boost::accumulators::tag::variance>>\n      acc;\n  for (unsigned int member = 0; member < ensemble_size; ++member)\n  {\n    acc(vec[member]);\n  }\n  BOOST_CHECK_CLOSE(stddev * stddev, boost::accumulators::variance(acc),\n                    tolerance);\n}\n", "meta": {"hexsha": "d0da38432ffec0e9621a83239b756c60618fd8e7", "size": 1513, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/test_ensemble_management.cc", "max_stars_repo_name": "Rombur/adamantine", "max_stars_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-09-03T02:08:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T01:26:41.000Z", "max_issues_repo_path": "tests/test_ensemble_management.cc", "max_issues_repo_name": "Rombur/adamantine", "max_issues_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74.0, "max_issues_repo_issues_event_min_datetime": "2016-08-31T18:10:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T01:51:44.000Z", "max_forks_repo_path": "tests/test_ensemble_management.cc", "max_forks_repo_name": "Rombur/adamantine", "max_forks_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-12T15:43:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-19T02:58:56.000Z", "avg_line_length": 27.5090909091, "max_line_length": 80, "alphanum_fraction": 0.7197620621, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6467556197781957}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix<double> SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet<double> Triplet;\n#include \"igl/edge_lengths.h\"\n#include \"igl/readMESH.h\"\n#include \"stiffness_matrix.hpp\"\n#include \"time_evolution_explicit.hpp\"\n#include \"time_evolution_implicit.hpp\"\n#include \"writer.hpp\"\n#include <sstream>\n\nint main(int, char **) {\n\ttry {\n\t\tEigen::MatrixXd vertices;\n\t\tEigen::MatrixXi triangles;\n\t\tEigen::MatrixXi tetrahedra;\n\n\t\tigl::readMESH(NPDE_DATA_PATH \"square_3.mesh\", vertices, tetrahedra, triangles);\n\t\twriteMatrixToFile(\"vertices.txt\", vertices);\n\t\twriteMatrixToFile(\"triangles.txt\", triangles);\n\n\t\tEigen::MatrixXd edgeLengths;\n\t\tigl::edge_lengths(vertices, triangles, edgeLengths);\n\t\tdouble dx = edgeLengths.minCoeff();\n\n\t\tdouble gamma = 1;\n\n\t\t// We want dt to scale roughly as dx to make sure\n\t\t// the error of the time discretization scales in the same\n\t\t// manner as the spatial discretization.\n\t\tint m = std::ceil(1 / dx);\n\n\t\tEigen::VectorXd u0(vertices.rows());\n\t\tu0.setOnes();\n\t\tauto uImplicit = radiativeTimeEvolutionImplicit(vertices, triangles, u0, gamma, m);\n\n\t\twriteToFile(\"energy_implicit.txt\", uImplicit.second);\n\t\twriteToFile(\"u_implicit.txt\", uImplicit.first);\n\n\t\tauto uExplicitNoCfl = radiativeTimeEvolutionExplicit(vertices, triangles, u0, gamma, m);\n\n\t\twriteToFile(\"energy_explicit_no_cfl.txt\", uExplicitNoCfl.second);\n\t\twriteToFile(\"u_explicit_no_cfl.txt\", uExplicitNoCfl.first);\n\n\t\tauto uExplicitCfl = radiativeTimeEvolutionExplicit(vertices, triangles, u0, gamma, std::ceil(std::pow(4.0 / dx, 2)));\n\n\t\twriteToFile(\"energy_explicit_cfl.txt\", uExplicitCfl.second);\n\t\twriteToFile(\"u_explicit_cfl.txt\", uExplicitCfl.first);\n\n\t} catch (std::runtime_error &e) {\n\t\tstd::cerr << \"An error occurred. Error message: \" << std::endl;\n\t\tstd::cerr << \"    \\\"\" << e.what() << \"\\\"\" << std::endl;\n\t\treturn EXIT_FAILURE;\n\t} catch (...) {\n\t\tstd::cerr << \"An unknown error occurred.\" << std::endl;\n\t\tthrow;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "e209f5b0e1c61a85a5593fc52ff2592e2cee22a0", "size": 2101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series4/2d-rad-cooling/heat.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/2d-rad-cooling/heat.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/2d-rad-cooling/heat.cpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8333333333, "max_line_length": 119, "alphanum_fraction": 0.7263207996, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6467556153718023}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n\n// This file was modified by Oracle on 2016-2020.\n// Modifications copyright (c) 2016-2020, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ARITHMETIC_CROSS_PRODUCT_HPP\n#define BOOST_GEOMETRY_ARITHMETIC_CROSS_PRODUCT_HPP\n\n\n#include <cstddef>\n#include <type_traits>\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/make.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/static_assert.hpp>\n\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <std::size_t Dimension>\nstruct cross_product\n{\n    // We define cross product only for 2d (see Wolfram) and 3d.\n    // In Math, it is also well-defined for 7-dimension.\n    // Generalisation of cross product to n-dimension is defined as\n    // wedge product but it is not direct analogue to binary cross product.\n    BOOST_GEOMETRY_STATIC_ASSERT_FALSE(\n        \"Not implemented for this Dimension.\",\n        std::integral_constant<std::size_t, Dimension>);\n};\n\ntemplate <>\nstruct cross_product<2>\n{\n    template <typename P1, typename P2, typename ResultP>\n    static void apply(P1 const& p1, P2 const& p2, ResultP& result)\n    {\n        assert_dimension<P1, 2>();\n        assert_dimension<P2, 2>();\n        assert_dimension<ResultP, 2>();\n\n        // For 2-dimensions, analog of the cross product U(x,y) and V(x,y) is\n        // Ux * Vy - Uy * Vx\n        // which is returned as 0-component (or X) of 2d vector, 1-component is undefined.\n        set<0>(result, get<0>(p1) * get<1>(p2) - get<1>(p1) * get<0>(p2));\n    }\n};\n\ntemplate <>\nstruct cross_product<3>\n{\n    template <typename P1, typename P2, typename ResultP>\n    static void apply(P1 const& p1, P2 const& p2, ResultP& result)\n    {\n        assert_dimension<P1, 3>();\n        assert_dimension<P2, 3>();\n        assert_dimension<ResultP, 3>();\n\n        set<0>(result, get<1>(p1) * get<2>(p2) - get<2>(p1) * get<1>(p2));\n        set<1>(result, get<2>(p1) * get<0>(p2) - get<0>(p1) * get<2>(p2));\n        set<2>(result, get<0>(p1) * get<1>(p2) - get<1>(p1) * get<0>(p2));\n    }\n\n    template <typename ResultP, typename P1, typename P2>\n    static constexpr ResultP apply(P1 const& p1, P2 const& p2)\n    {\n        assert_dimension<P1, 3>();\n        assert_dimension<P2, 3>();\n        assert_dimension<ResultP, 3>();\n\n        return traits::make<ResultP>::apply(\n                get<1>(p1) * get<2>(p2) - get<2>(p1) * get<1>(p2),\n                get<2>(p1) * get<0>(p2) - get<0>(p1) * get<2>(p2),\n                get<0>(p1) * get<1>(p2) - get<1>(p1) * get<0>(p2));\n    }\n};\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\n/*!\n\\brief Computes the cross product of two vectors.\n\\details All vectors should have the same dimension, 3 or 2.\n\\ingroup arithmetic\n\\param p1 first vector\n\\param p2 second vector\n\\return the cross product vector\n\n*/\n\ntemplate\n<\n    typename ResultP, typename P1, typename P2,\n    std::enable_if_t\n        <\n            dimension<ResultP>::value != 3\n         || ! traits::make<ResultP>::is_specialized,\n            int\n        > = 0\n>\ninline ResultP cross_product(P1 const& p1, P2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<ResultP>) );\n    BOOST_CONCEPT_ASSERT( (concepts::ConstPoint<P1>) );\n    BOOST_CONCEPT_ASSERT( (concepts::ConstPoint<P2>) );\n\n    ResultP result;\n    detail::cross_product<dimension<ResultP>::value>::apply(p1, p2, result);\n    return result;\n}\n\ntemplate\n<\n    typename ResultP, typename P1, typename P2,\n    std::enable_if_t\n        <\n            dimension<ResultP>::value == 3\n         && traits::make<ResultP>::is_specialized,\n            int\n        > = 0\n>\n// workaround for VS2015\n#if !defined(_MSC_VER) || (_MSC_VER >= 1910)\nconstexpr\n#endif\ninline ResultP cross_product(P1 const& p1, P2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT((concepts::Point<ResultP>));\n    BOOST_CONCEPT_ASSERT((concepts::ConstPoint<P1>));\n    BOOST_CONCEPT_ASSERT((concepts::ConstPoint<P2>));\n\n    return detail::cross_product<3>::apply<ResultP>(p1, p2);\n}\n\n/*!\n\\brief Computes the cross product of two vectors.\n\\details All vectors should have the same dimension, 3 or 2.\n\\ingroup arithmetic\n\\param p1 first vector\n\\param p2 second vector\n\\return the cross product vector\n\n\\qbk{[heading Examples]}\n\\qbk{[cross_product] [cross_product_output]}\n*/\ntemplate\n<\n    typename P,\n    std::enable_if_t\n        <\n            dimension<P>::value != 3\n         || ! traits::make<P>::is_specialized,\n            int\n        > = 0\n>\ninline P cross_product(P const& p1, P const& p2)\n{\n    BOOST_CONCEPT_ASSERT((concepts::Point<P>));\n    BOOST_CONCEPT_ASSERT((concepts::ConstPoint<P>));\n\n    P result;\n    detail::cross_product<dimension<P>::value>::apply(p1, p2, result);\n    return result;\n}\n\n\ntemplate\n<\n    typename P,\n    std::enable_if_t\n        <\n            dimension<P>::value == 3\n         && traits::make<P>::is_specialized,\n            int\n        > = 0\n>\n// workaround for VS2015\n#if !defined(_MSC_VER) || (_MSC_VER >= 1910)\nconstexpr\n#endif\ninline P cross_product(P const& p1, P const& p2)\n{\n    BOOST_CONCEPT_ASSERT((concepts::Point<P>));\n    BOOST_CONCEPT_ASSERT((concepts::ConstPoint<P>));\n\n    return detail::cross_product<3>::apply<P>(p1, p2);\n}\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ARITHMETIC_CROSS_PRODUCT_HPP\n", "meta": {"hexsha": "9172a7e5778ec18196d079f34432d73e1370fb95", "size": 5858, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/cross_product.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/cross_product.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/cross_product.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 27.7630331754, "max_line_length": 90, "alphanum_fraction": 0.6555138272, "num_tokens": 1673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6467556092457871}}
{"text": "// Statistical Computing //\r\n// Load typical packages\r\n\r\n#include<cmath>\r\n#include<iostream>\r\n#include<iomanip>\r\n\r\n// Typiccal C libraries\r\n#include<cmath>\r\n#include<cstdlib>\r\n\r\n// C++ Data Structures\r\n#include<set>\r\n#include<map>\r\n#include<vector>\r\n\r\n// Include Eigen Package for Matrices\r\n#include <Eigen/Core>\r\n\r\n// Load Matrix615 header file to read in from file\r\n#include \"Matrix615.h\"\r\n\r\nusing namespace std;\r\n// we avoid using namespace Eigen to be able to clearly see where we are calling the Eigen Package\r\n\r\n// Driver Code\r\nint main(int argc, char* argv[]) {\r\n\r\n\t// Steps corresponding to the commented code is associated with the following documents:\r\n\t\r\n\t// Tentative Read Matrix using Matrix615.h\r\n\t\r\n\tMatrix615<double> read_Design; // throw-away Matrices to read in data\r\n\tMatrix615<double> read_Y;\r\n\tMatrix615<double> read_ID;\r\n\r\n\t// Read the data in\r\n\tread_Design.readFromFile(argv[3]); // t\r\n\tread_Y.readFromFile(argv[2]);\r\n\tread_ID.readFromFile(argv[1]);\r\n\r\n\t// Step (1): Store the design matrix, response, and Id into an Eigen Matrix\r\n\tEigen::MatrixXd\tdesign_X;\r\n\tEigen::MatrixXd outcome_Y;\r\n\r\n\tread_Design.cloneToEigen(design_X);\r\n\tread_Y.cloneToEigen(outcome_Y);\r\n\r\n\t\r\n\r\n\t// cout << Weights.rows() << endl << endl;\r\n\t// cout << Weights << endl;\r\n\tEigen::MatrixXd Weights(outcome_Y.rows(), 1);\r\n\tWeights.setOnes();\r\n\r\n\tif (int (argc) == 5) {\r\n\t\tMatrix615<double> read_Weights;\r\n\t\tread_Weights.readFromFile(argv[4]);\r\n\r\n\t\tEigen::MatrixXd Weights;\r\n\t\tread_Weights.cloneToEigen(Weights);\r\n\t}\r\n\r\n\t// else {\r\n\t// \tEigen::MatrixXd Weights(outcome_Y.rows(), 1);\r\n\t// \tWeights.setOnes();\r\n\t// }\r\n\r\n\t// cout << design_X.rows() << \" \" << design_X.cols() << endl << endl;\r\n\t// cout << design_X << endl << endl << endl;\r\n\t// cout << outcome_Y.rows() << \" \" << outcome_Y.cols() << endl << endl;\r\n\t// cout << outcome_Y << endl << endl << endl;\r\n\r\n\t// Step (2): Count number of unique ID's, patients\r\n\tEigen::MatrixXd ID_Mat;\r\n\tread_ID.cloneToEigen(ID_Mat);\r\n\r\n\tstd::set<int> unique_ID; // to dynamically count n\r\n\tstd::map<int, int> id_map; // to dynamically count m\r\n\tstd::map<int, double> weight_map;\r\n\r\n\tfor (int i = 0; i < int(ID_Mat.rows()); ++i) {\r\n\t\tunique_ID.insert(  ID_Mat(i,0) );\r\n\t\tid_map[ID_Mat(i, 0)] += 1;\r\n\t\tweight_map[ID_Mat(i, 0)] = Weights(i, 0); \r\n\t}\r\n\r\n\tint n = int( unique_ID.size() );\r\n\t// int m = int( id_map[ID_Mat(1,0)] );\r\n\r\n\t// q = (p + 1) : # number of paramters to be estimated using GEE\r\n\tint q = int ( design_X.cols() );\r\n\r\n\t// Correlation Structure\r\n\r\n\t// Step : Weights\r\n\r\n\t// Step (3): Initialize betas *********** Should we incorporate the beta's that come from a fast linear regression or no?\r\n\r\n\tEigen::MatrixXd Betas_new(q , 1); // dimensions (p+1)  x 1\r\n\tBetas_new.setZero();\r\n\r\n\t// cout << \"Betas ***********************\" << endl;\r\n\t// cout << Betas_new << endl << endl;\r\n\r\n\t// Step (4): Initialize rho and phi (rho: off diagonals of correlation structure & phi: )\r\n\tdouble rho = 0.0;\r\n\t// double phi = 0.0;\r\n\r\n\t// Step (5): Set up variables for iteration convergence check\r\n\r\n\t// Should we make this dynamic? \r\n\r\n\tdouble diff_beta = 1; // updated difference in beta estimation {beta (new) - beta (old)}\r\n\t\r\n\tdouble diff_threshold = 0.00000010; // threshold for the update difference in betas\r\n\t\r\n\tint iteration_threshold = 1000; // threshold on how many iterations there will be\r\n\r\n\t// Step (6): Initialize the iteration\r\n\tint iteration_count = 0;\r\n\r\n\t// Step (7): Assign appropriate value to n*\r\n\t// double n_star = (0.5) * double(n) * double(m) * double(m - 1);\r\n\r\n\t// double n_star = (0.5) * double(n) * double(5) * double(5 - 1);\r\n\r\n\t// cout << \" n* is \" << n_star << endl;\r\n\r\n\tdouble n_star_sum = 0.0;\r\n\r\n\t// Step (8): Start the GEE Estimation\r\n\r\n\tEigen::MatrixXd Betas_updated = Betas_new;\r\n\r\n\tEigen::MatrixXd sandwhich_Mat;\r\n\r\n\t// cout << Betas_updated << endl << endl;\r\n\r\n\twhile ( (diff_beta > diff_threshold) && (iteration_count < iteration_threshold) ) {\r\n\t\t// (1)\r\n\t\tBetas_updated = Betas_new;\r\n\r\n\t\t// (2) Vector EE ((p+1) x 1)\r\n\t\tEigen::MatrixXd EE(q , 1);\r\n\t\tEE.setZero();\r\n\r\n\t\t// (3) Matrix GI ( (p+1) x (p+1) )\r\n\t\t// First derivative of EE; Model-based Variance\r\n\t\tEigen::MatrixXd GI(q , q);\r\n\t\tGI.setZero();\r\n\r\n\t\t// (4) Matrix G ( (p+1) x (p+1) )\r\n\t\t// Meat of the Sandwhich Estimator\r\n\t\tEigen::MatrixXd G(q , q);\r\n\t\tG.setZero();\t\t\r\n\r\n\t\t// (5) Initialize phi(sum) and tau(sum)\r\n\t\tdouble phi_sum = 0.0;\r\n\t\tdouble tau_sum = 0.0;\r\n\r\n\t\t// (6) Initialize start and end\r\n\t\tint start = 0;\r\n\t\tint end = -1;\r\n\r\n\t\t// inner loop in while loop Time-Complexity: O(n^2)??\r\n\r\n\t\tfor (int i = 0; i < n; ++i) {\r\n\r\n\t\t\tint m = id_map[i + 1];\r\n\t\t\tstart = end + 1;\r\n\t\t\tend = start + m - 1;\r\n\r\n\t\t\t//update n*\r\n\t\t\tn_star_sum = n_star_sum + (0.5) * double(m) * double(double(m) - 1.0);\r\n\r\n\t\t\t// assign mu_i ( m x (p+1) ) for ith person\r\n\t\t\t// Eigen.block(starting_row = , starting_col = , dim_row = , dim_col = )\r\n\t\t\tEigen::MatrixXd mu_i = design_X.block(start, 0, m, q) * Betas_updated;\r\n\r\n\t\t\t// assign r_i (m x 1)\r\n\t\t\tEigen::MatrixXd r_i = outcome_Y.block(start, 0, m, 1) - mu_i;\r\n\r\n\t\t\t// Loop to update phi-sum\r\n\t\t\tfor (int j = 0; j < int(m); ++j) phi_sum = phi_sum + (r_i(j,0) * r_i(j,0));\r\n\r\n\t\t\t// Loop to update tau-sum\r\n\t\t\tfor (int j = 0; j < int(m - 1); ++j) {\r\n\t\t\t\tfor (int k = (j + 1); k < m; ++k) tau_sum = tau_sum + r_i(j,0) * r_i(k, 0);\r\n\t\t\t}\r\n\r\n\t\t\t// create R matrix (m x m) for each observation/patient\r\n\t\t\tEigen::MatrixXd R(m, m);\r\n\t\t\tR.setConstant(rho); // off-diagonals will be rho\r\n\t\t\tfor (int d = 0; d < int(m); ++d) R(d, d) = 1; //diagonals will be 1\r\n\r\n\t\t\t// update EE ((p+1) x 1)\r\n\t\t\tEE = EE + ((design_X.block(start, 0, m, q).transpose()) * (R.inverse() * (weight_map[i+1] * r_i) )); // weight_map\r\n\r\n\t\t\t// update GI ((p+1) x (p+1)) or (q x q)\r\n\t\t\tGI = GI + ((design_X.block(start, 0, m, q).transpose()) * R.inverse() *  design_X.block(start, 0, m, q));\r\n\r\n\t\t\t// update G ((p+1) x (p+1)) or (q x q)\r\n\t\t\tG = G + ((design_X.block(start, 0, m, q).transpose()) *\r\n\t\t\t\t( ((R.inverse()) * r_i) * (r_i.transpose()*(R.inverse())) ) * design_X.block(start, 0, m, q));\r\n\t\t}\r\n\r\n\t\t// Update beta using either Newton Raphson or Gradient Boosting *** we can add an if statement\r\n\t\tBetas_new = Betas_updated + ( GI.inverse() * EE);\r\n\r\n\t\t// calculate the difference in the betas\r\n\t\tdiff_beta = (Betas_new - Betas_updated).norm();\r\n\r\n\t\t// update rho\r\n\t\trho = ( (( double(n) - double(q) ) * tau_sum) / ( (double(n_star_sum) - double(q) ) * phi_sum) );\r\n\r\n\r\n\t\tsandwhich_Mat = GI.inverse() * G * GI.inverse();\r\n\t\t// increment iteration count\r\n\t\titeration_count += 1;\r\n\t}\r\n\r\n\tcout << endl << \"Estimated Betas are: \" << endl;\r\n\tcout << Betas_new.transpose() << endl << endl << endl;\r\n\r\n\t// cout << \"The sandwhich matrix is: \" << endl << endl;\r\n\t// cout << sandwhich_Mat << endl << endl;\r\n\r\n\tcout << \"The beta Robust S.E.'s are: \" << endl << endl;\r\n\tcout << sandwhich_Mat.diagonal().array().sqrt() << endl << endl;\r\n\t\r\n\treturn 0;\r\n\r\n}", "meta": {"hexsha": "29cd6bd27c6dd60ac1407795c9794b54f6c7412c", "size": 6874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gee/geec_oneloop.cpp", "max_stars_repo_name": "hengshiyu/geeCpp", "max_stars_repo_head_hexsha": "bdcc54dd7fc0c28e4d27326c52670f2c4b2e0ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gee/geec_oneloop.cpp", "max_issues_repo_name": "hengshiyu/geeCpp", "max_issues_repo_head_hexsha": "bdcc54dd7fc0c28e4d27326c52670f2c4b2e0ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gee/geec_oneloop.cpp", "max_forks_repo_name": "hengshiyu/geeCpp", "max_forks_repo_head_hexsha": "bdcc54dd7fc0c28e4d27326c52670f2c4b2e0ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3760683761, "max_line_length": 123, "alphanum_fraction": 0.6012510911, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6467556044094885}}
{"text": "#define BOOST_TEST_MODULE \"Test Manhattan Normalization class\"\n\n#include <boost/test/unit_test.hpp>\n\n#include \"distance/Manhattan.hpp\"\n#include \"Exception.hpp\"\n\nusing namespace genex;\n\n#define TOLERANCE 1e-9\n\nstruct MockData\n{\n  data_t dat_1[5] = {1, 2, 3, 4, 5};\n  data_t dat_2[5] = {11, 2, 3, 4, 5};\n};\n\nBOOST_AUTO_TEST_CASE( man_norm, *boost::unit_test::tolerance(TOLERANCE) )\n{\n  MockData data;\n  TimeSeries ts_1(data.dat_1, 0, 0, 5);\n  TimeSeries ts_2(data.dat_2, 0, 0, 5);\n\n  Manhattan dist;\n\n  data_t total = dist.init();\n\n  for (int i = 0; i < ts_1.getLength(); i++) {\n    total = dist.reduce(total, total, ts_1[i], ts_2[i]);\n  }\n\n  BOOST_TEST( dist.norm(total, ts_1, ts_2) == 2.0 );\n\n  dist.clean(total);\n}\n", "meta": {"hexsha": "101bd3927295a5a0d7601c672759f085cacf1fca", "size": 716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distance/ManhattanNormTest.cpp", "max_stars_repo_name": "mihinsumaria/genex", "max_stars_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-28T07:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T07:49:24.000Z", "max_issues_repo_path": "test/distance/ManhattanNormTest.cpp", "max_issues_repo_name": "mihinsumaria/genex", "max_issues_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/distance/ManhattanNormTest.cpp", "max_forks_repo_name": "mihinsumaria/genex", "max_forks_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T20:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T20:25:42.000Z", "avg_line_length": 19.8888888889, "max_line_length": 73, "alphanum_fraction": 0.6634078212, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6467556044094884}}
{"text": "#pragma once\r\n\r\n\r\n#include <Eigen/Dense>\r\n\r\nclass CubicKernel\r\n{\r\npublic:\r\n\t double getRadius() { return m_radius; }\r\n\t void setRadius(double val)\r\n\t{\r\n\t\tm_radius = val;\r\n\t\tconst double pi = static_cast<double>(M_PI);\r\n\r\n\t\tconst double h3 = m_radius*m_radius*m_radius;\r\n\t\tm_k = 8.0 / (pi*h3);\r\n\t\tm_l = 48.0 / (pi*h3);\r\n\t\tm_W_zero = W(Eigen::Vector3d::Zero());\r\n\t}\r\n\r\npublic:\r\n\tdouble W(Eigen::Vector3d const& r)\r\n\t{\r\n\t\tdouble res = 0.0;\r\n\t\tconst double rl = r.norm();\r\n\t\tconst double q = rl/m_radius;\r\n\t\tif (q <= 1.0)\r\n\t\t{\r\n\t\t\tif (q <= 0.5)\r\n\t\t\t{\r\n\t\t\t\tconst double q2 = q*q;\r\n\t\t\t\tconst double q3 = q2*q;\r\n\t\t\t\tres = m_k * (6.0*q3-6.0*q2+1.0);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tauto _1mq = 1.0 - q;\r\n\t\t\t\tres = m_k * (2.0*_1mq*_1mq*_1mq);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn res;\r\n\t}\r\n\r\n\tEigen::Vector3d gradW(const Eigen::Vector3d &r)\r\n\t{\r\n\t\tusing namespace Eigen;\r\n\t\tVector3d res;\r\n\t\tconst double rl = r.norm();\r\n\t\tconst double q = rl / m_radius;\r\n\t\tif (q <= 1.0)\r\n\t\t{\r\n\t\t\tif (rl > 1.0e-6)\r\n\t\t\t{\r\n\t\t\t\tconst Vector3d gradq = r * ((double) 1.0 / (rl*m_radius));\r\n\t\t\t\tif (q <= 0.5)\r\n\t\t\t\t{\r\n\t\t\t\t\tres = m_l*q*((double) 3.0*q - (double) 2.0)*gradq;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tconst double factor = 1.0 - q;\r\n\t\t\t\t\tres = m_l*(-factor*factor)*gradq;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t\tres.setZero();\r\n\r\n\t\treturn res;\r\n\t}\r\n\r\n\tdouble W_zero()\r\n\t{\r\n\t\treturn m_W_zero;\r\n\t}\r\n\r\nprivate:\r\n\tdouble m_radius;\r\n\tdouble m_k;\r\n\tdouble m_l;\r\n\tdouble m_W_zero;\r\n};\r\n", "meta": {"hexsha": "9f22fc2c0d980d3d65f005da3de15e608ac2535e", "size": 1417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_stars_repo_name": "digitalillusions/Discregrid", "max_stars_repo_head_hexsha": "af5880ecfa62c736a25e23a607bd8bd51d833fe2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 214.0, "max_stars_repo_stars_event_min_datetime": "2017-11-10T11:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T16:24:01.000Z", "max_issues_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_issues_repo_name": "digitalillusions/Discregrid", "max_issues_repo_head_hexsha": "af5880ecfa62c736a25e23a607bd8bd51d833fe2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-02-20T07:53:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T14:03:11.000Z", "max_forks_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_forks_repo_name": "digitalillusions/Discregrid", "max_forks_repo_head_hexsha": "af5880ecfa62c736a25e23a607bd8bd51d833fe2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47.0, "max_forks_repo_forks_event_min_datetime": "2017-11-19T05:42:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T11:55:09.000Z", "avg_line_length": 17.0722891566, "max_line_length": 63, "alphanum_fraction": 0.5299929428, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.646610338774384}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\nnamespace vpp\n{\n\n  // http://www.cse.psu.edu/~rcollins/CSE486/lecture19_6pp.pdf\n  // Page 5.\n  inline vfloat2 epipole_left(const Eigen::Matrix3f& F)\n  {\n    // F e_l = 0.\n    Eigen::EigenSolver<Eigen::Matrix3d> es(F.cast<double>().transpose() * F.cast<double>());\n\n    auto values = es.eigenvalues();\n    auto vectors = es.eigenvectors();\n    vdouble2 epipole;\n    double min_ev = FLT_MAX;\n    for (int i = 0; i < values.size(); i++)\n      if (values[i].real() < min_ev)\n      {\n        min_ev = values[i].real();\n        auto vc = vectors.col(i);\n        epipole[0] = vc[0].real();\n        epipole[1] = vc[1].real();\n        epipole /= double(vc[2].real());\n      }\n\n    return epipole.cast<float>();\n  }\n\n  // http://www.cse.psu.edu/~rcollins/CSE486/lecture19_6pp.pdf\n  // Page 5.\n  inline vfloat2 epipole_right(const Eigen::Matrix3f& F)\n  {\n    // e_r F  = 0.\n    Eigen::EigenSolver<Eigen::Matrix3d> es(F.cast<double>() * F.cast<double>().transpose());\n\n\n    auto values = es.eigenvalues();\n    auto vectors = es.eigenvectors();\n    vdouble2 epipole;\n    double min_ev = FLT_MAX;\n    for (int i = 0; i < values.size(); i++)\n      if (values[i].real() < min_ev)\n      {\n        min_ev = values[i].real();\n        auto vc = vectors.col(i);\n        epipole[0] = vc[0].real();\n        epipole[1] = vc[1].real();\n        epipole /= double(vc[2].real());\n      }\n\n    return epipole.cast<float>();\n  }\n}\n", "meta": {"hexsha": "e55cd4459142e9a97c4cf8da0383c8a36d059776", "size": 1454, "ext": "hh", "lang": "C++", "max_stars_repo_path": "vpp/algorithms/epipolar_geometry.hh", "max_stars_repo_name": "jjzhang166/videopp", "max_stars_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 624.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T16:40:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T03:09:43.000Z", "max_issues_repo_path": "vpp/algorithms/epipolar_geometry.hh", "max_issues_repo_name": "jjzhang166/videopp", "max_issues_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2015-01-22T20:50:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-15T10:41:34.000Z", "max_forks_repo_path": "vpp/algorithms/epipolar_geometry.hh", "max_forks_repo_name": "jjzhang166/videopp", "max_forks_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 113.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T11:58:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:15:20.000Z", "avg_line_length": 25.9642857143, "max_line_length": 92, "alphanum_fraction": 0.5715268226, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6466103285270899}}
{"text": "/**\n * @file crossprod.cc\n * @brief NPDE homework CrossProd code\n * @author Unknown, Oliver Rietmann\n * @date 31.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"crossprod.h\"\n\n#include <Eigen/Geometry>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nnamespace CrossProd {\n\n/* SAM_LISTING_BEGIN_0 */\nvoid tab_crossprod() {\n  // TO DO (13-1.e): solve the cross-product ODE with the implicit RK method\n  // defined in solve_imp_mid. Tabulate the norms of the results at all steps.\n  double T = 10.;\n  int N = 128;\n  // set data\n  double c = 1.;\n  Eigen::Vector3d y0(1., 1., 1.);\n  Eigen::Vector3d a(1., 0., 0.);\n\n  // define rhs\n  auto f = [a, c](Eigen::Vector3d y) -> Eigen::Vector3d {\n    return a.cross(y) + c * y.cross(a.cross(y));\n  };\n  // define Jacobian of rhs\n  auto Jf = [a, c](Eigen::Vector3d y) -> Eigen::Matrix3d {\n    Eigen::Matrix3d temp;\n    temp << -c * (a(1) * y(1) + a(2) * y(2)),\n        c * (2 * a(0) * y(1) - a(1) * y(0)) - a(2),\n        a(1) + c * (2 * a(0) * y(2) - a(2) * y(0)),\n        a(2) - c * (a(0) * y(1) - 2 * a(1) * y(0)),\n        -c * (a(0) * y(0) + a(2) * y(2)),\n        c * (2 * a(1) * y(2) - a(2) * y(1)) - a(0),\n        -a(1) - c * (a(0) * y(2) - 2 * a(2) * y(0)),\n        a(0) - c * (a(1) * y(2) - 2 * a(2) * y(1)),\n        -c * (a(0) * y(0) + a(1) * y(1));\n    return temp;\n  };\n\n  std::vector<Eigen::VectorXd> res_imp = solve_imp_mid(f, Jf, T, y0, N);\n\n  std::cout << \"1. Implicit midpoint method\" << std::endl;\n  std::cout << std::setw(10) << \"t\" << std::setw(15) << \"norm(y(t))\"\n            << std::endl;\n\n  for (int i = 0; i < N + 1; ++i) {\n    std::cout << std::setw(10) << T * i / N << std::setw(15)\n              << res_imp[i].norm() << std::endl;\n  }\n  /* SAM_LISTING_END_0 */\n\n  /* SAM_LISTING_BEGIN_1 */\n  // TO DO (13-1.g): solve the cross-product ODE with the implicit RK method\n  // defined in solve_lin_mid. Tabulate the norms of the results at all steps.\n  std::vector<Eigen::VectorXd> res_lin = solve_lin_mid(f, Jf, T, y0, N);\n\n  std::cout << \"\\n2. Linear implicit midpoint method\" << std::endl;\n  std::cout << std::setw(10) << \"t\" << std::setw(15) << \"norm(y(t))\"\n            << std::endl;\n  for (int i = 0; i < N + 1; ++i) {\n    std::cout << std::setw(10) << T * i / N << std::setw(15)\n              << res_lin[i].norm() << std::endl;\n  }\n  /* SAM_LISTING_END_1 */\n}\n\n}  // namespace CrossProd\n", "meta": {"hexsha": "dc247a895e73c2ad9b41bdf29b35081f1ddd1344", "size": 2371, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/CrossProd/mastersolution/crossprod.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/CrossProd/mastersolution/crossprod.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/CrossProd/mastersolution/crossprod.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1973684211, "max_line_length": 78, "alphanum_fraction": 0.5229860818, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954683, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6465663819395951}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file libw/numeric/ublasx/operation/balance.cpp\n *\n * \\brief Test case for matrix balance operation.\n *\n * \\author Marco Guazzone, &lt;marco.guazzone@gmail&gt;\n *\n * <hr/>\n *\n * Copyright (c) 2011, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublasx/operations.hpp>\n\n\nnamespace ublas = boost::numeric::ublas;\nnamespace ublasx = boost::numeric::ublasx;\n\n\nint main()\n{\n    // MATLAB/Octave:\n    //   a = linspace(0, 2, 2)\n    //   b = linspace(1, 2, 2)\n    //   c = 2*a + 3*b\n    ublas::vector<double> a = ublasx::linspace(0.0, 2.0, 2); // a = [0 2]\n    ublas::vector<double> b = ublasx::linspace(1.0, 2.0, 2); // b = [1 2]\n    ublas::vector<double> c = 2*a + 3*b; // c = [3 10]\n    std::cout << \"a = \" << a << \"\\n\";\n    std::cout << \"b = \" << b << \"\\n\";\n    std::cout << \"c = 2*a + 3*b = \" << c << \"\\n\";\n\n    // MATLAB/Octave:\n    //   A = rot90(2*eye(2))\n    //   rank(A)\n    //   B = inv(A)\n    ublas::matrix<double> A = ublasx::rot90(2*ublas::identity_matrix<double>(2)); // A = [0 2; 2 0]\n    ublas::matrix<double> B = ublasx::inv(A); // B = [0 0.5; 0.5 0]\n    std::cout << \"A = \" << A << \"\\n\";\n    std::cout << \"rank of A = \" << ublasx::rank(A) << \"\\n\";\n    std::cout << \"inverse of A = \" << B << \"\\n\";\n\n    // MATLAB/Octave:\n    //   C = reshape(linspace(1, 9, 9), 3, 3)\n    //   D = pow2(C)\n    //   E = cat(2, C, D)\n    ublas::matrix<double> C = ublasx::reshape(ublasx::linspace(1.0, 9.0, 9), 3, 3); // C = [1 2 3; 4 5 6; 7 8 9]\n    ublas::matrix<double> D = ublasx::pow2(C); // [2 4 8; 16 32 64; 128 256 512]\n    ublas::matrix<double> E = ublasx::cat<2>(C, D); // [1 2 3 2 4 8; 4 5 6 16 32 64; 7 8 9 128 256 512]\n    std::cout << \"C = \" << C << \"\\n\";\n    std::cout << \"D = 2.^C = \" << D << \"\\n\";\n    std::cout << \"E = [C D] = \" << E << \"\\n\";\n}\n", "meta": {"hexsha": "4167ea976e233e2c3c6823d9073ad27232c52f23", "size": 2082, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/examples/get_started.cpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "libs/numeric/ublasx/examples/get_started.cpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "libs/numeric/ublasx/examples/get_started.cpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 33.0476190476, "max_line_length": 112, "alphanum_fraction": 0.5331412104, "num_tokens": 840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6465657349170346}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n#include \"graphe.h\"\n\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n#include <numeric>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\ntypedef std::pair<nombre, nombre> paire;\n\nENREGISTRER_PROBLEME(107, \"Minimal network\") {\n    // The following undirected network consists of seven vertices and twelve edges with a total weight of 243.\n    //\n    //\n    // The same network can be represented by the matrix below.\n    //\n    //      \tA\tB\tC\tD\tE\tF\tG\n    //      A\t-\t16\t12\t21\t-\t-\t-\n    //      B\t16\t-\t-\t17\t20\t-\t-\n    //      C\t12\t-\t-\t28\t-\t31\t-\n    //      D\t21\t17\t28\t-\t18\t19\t23\n    //      E\t-\t20\t-\t18\t-\t-\t11\n    //      F\t-\t-\t31\t19\t-\t-\t27\n    //      G\t-\t-\t-\t23\t11\t27\t-\n    //\n    // However, it is possible to optimise the network by removing some edges and still ensure that all points on the\n    // network remain connected. The network which achieves the maximum saving is shown below. It has a weight of 93,\n    // representing a saving of 243 \u2212 93 = 150 from the original network.\n    //\n    // Using network.txt (right click and 'Save Link/Target As...'), a 6K text file containing a network with forty\n    // vertices, and given in matrix form, find the maximum saving which can be achieved by removing redundant edges\n    // whilst ensuring that the network remains connected.\n    std::ifstream ifs(\"data/p107_network.txt\");\n\n    graphe::Kruskal::aretes A;\n    nombre i = 0;\n    std::string ligne;\n    while (ifs >> ligne) {\n        std::vector<std::string> strings;\n        boost::split(strings, ligne, boost::is_any_of(\",\"));\n\n        nombre j = 0;\n        for (auto &s: strings) {\n            if (s != \"-\" && i < j)\n                A.emplace_back(i, j, std::stoull(s));\n            ++j;\n        }\n        ++i;\n    }\n\n    graphe::Kruskal kruskal(A);\n    auto arbre_mini = kruskal.algorithme();\n\n    auto somme_poids = [](const nombre &r, const graphe::Kruskal::arete &a) { return r + std::get<2>(a); };\n\n    nombre resultat = std::accumulate(A.begin(), A.end(), 0ull, somme_poids) -\n                      std::accumulate(arbre_mini.begin(), arbre_mini.end(), 0ull, somme_poids);\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "193d824af71b223a9a0f1c788bd3ca97560070a0", "size": 2212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme107.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme1xx/probleme107.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme1xx/probleme107.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1111111111, "max_line_length": 117, "alphanum_fraction": 0.6021699819, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.646531127799777}}
{"text": "// Created by dinies on 03/07/2018.\n\n//Collection of static functions and useful types to perform geometric computations\n#pragma once\n\n#include <unistd.h>\n#include <vector>\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace MultiRobot{\n  class MyMath{\n\n  public:\n    // static Eigen::Isometry2d v2t(const std::vector<double> &t_vec);\n    // static std::vector<double> t2v(const Eigen::Isometry2d& t_transf);\n\n    static Eigen::Isometry2d v2t(const Eigen::Vector3d &t_vec);\n    static Eigen::Vector3d t2v(const Eigen::Isometry2d& t_transf);\n\n    static void rotate2D( Eigen::Vector2d &t_point, const double t_angle_rad );\n\n    static std::vector<double> vecSum(const std::vector<double> &t_first,const std::vector<double> &t_second);\n\n    static std::vector<double> vecMultEleWise(const std::vector<double> &t_first,const std::vector<double> &t_second);\n\n    static double boxMinusAngleRad(const double t_ref,const double t_actual);\n    static double boxPlusAngleRad(const double t_ref,const double t_actual);\n    static double computeAvg(const double t_prevAvg,const int t_numEntries,const double t_newValue);\n  };\n}\n", "meta": {"hexsha": "acf23643c5fea0b71ec5768b522fd835aaa5caa4", "size": 1145, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code/src/utils/MyMath.hpp", "max_stars_repo_name": "dinies/MultiRobot", "max_stars_repo_head_hexsha": "eaf3cb34ce7baf5653bf54b31bffe02426885060", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/src/utils/MyMath.hpp", "max_issues_repo_name": "dinies/MultiRobot", "max_issues_repo_head_hexsha": "eaf3cb34ce7baf5653bf54b31bffe02426885060", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/src/utils/MyMath.hpp", "max_forks_repo_name": "dinies/MultiRobot", "max_forks_repo_head_hexsha": "eaf3cb34ce7baf5653bf54b31bffe02426885060", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.696969697, "max_line_length": 118, "alphanum_fraction": 0.7493449782, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.646531120297188}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <shz/math/quaternion.hpp>\n\n#define ROUND_ERROR 0.00001\n\nBOOST_AUTO_TEST_CASE(quaternionConstructors)\n{\n\tshz::math::quaternion<shz::math::f64> q1;\n\tq1.x = 1.0;\n\tq1.y = 0.0;\n\tq1.z = 0.0;\n\tq1.w = 1.0;\n\tBOOST_CHECK_EQUAL(q1.data[0], q1.x);\n\tBOOST_CHECK_EQUAL(q1.data[1], q1.y);\n\tBOOST_CHECK_EQUAL(q1.data[2], q1.z);\n\tBOOST_CHECK_EQUAL(q1.data[3], q1.w);\n\n\tshz::math::quaternion<shz::math::f64> q2(q1);\n\tBOOST_CHECK_EQUAL(q1.data[0], q2.x);\n\tBOOST_CHECK_EQUAL(q1.data[1], q2.y);\n\tBOOST_CHECK_EQUAL(q1.data[2], q2.z);\n\tBOOST_CHECK_EQUAL(q1.data[3], q2.w);\n\n\tshz::math::vector<shz::math::f64, 3> v;\n\tv.data[0] = 0.0;\n\tv.data[1] = 1.0;\n\tv.data[2] = 0.0;\n\tq2 = shz::math::quaternion<shz::math::f64>(v, shz::math::HALF_PI);\n\tBOOST_CHECK_CLOSE(0.0, q2.x, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(0.70710679664085752, q2.y, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(0.0, q2.z, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(0.70710679664085752, q2.w, ROUND_ERROR);\n\n\tq2 = shz::math::quaternion<shz::math::f64>(0.0, 1.0, 0.0, shz::math::HALF_PI);\n\tBOOST_CHECK_CLOSE(0.0, q2.x, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(0.70710679664085752, q2.y, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(0.0, q2.z, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(0.70710679664085752, q2.w, ROUND_ERROR);\n}\n\nBOOST_AUTO_TEST_CASE(quaternionToMatrix)\n{\n\tshz::math::quaternion<shz::math::f64> q1(0.0, 1.0, 0.0, shz::math::HALF_PI);\n\tshz::math::matrix<shz::math::f64, 4, 4> matrix;\n\n\tq1.to_matrix(matrix);\n\t\n\tshz::math::matrix<shz::math::f32, 4, 4> m = shz::math::matrix<shz::math::f32, 4, 4>::from_rotation(0.f, 1.f, 0.f, shz::math::HALF_PI);\n\n\tBOOST_CHECK_CLOSE(matrix[0], m[0], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[1], m[1], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[2], m[2], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[3], m[3], ROUND_ERROR);\n\t\n\tBOOST_CHECK_CLOSE(matrix[4], m[4], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[5], m[5], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[6], m[6], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[7], m[7], ROUND_ERROR);\n\t\n\tBOOST_CHECK_CLOSE(matrix[8], m[8], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[9], m[9], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[10], m[10], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[11], m[11], ROUND_ERROR);\n\t\n\tBOOST_CHECK_CLOSE(matrix[12], m[12], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[13], m[13], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[14], m[14], ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(matrix[15], m[15], ROUND_ERROR);\n\t\n}\n\n\nBOOST_AUTO_TEST_CASE(quaternionMuls)\n{\n\tshz::math::quaternion<shz::math::f64> q1(0.0, 1.0, 0.0, shz::math::HALF_PI);\n\tshz::math::quaternion<shz::math::f64> q2(0.0, 1.0, 0.0, shz::math::HALF_PI);\n\tshz::math::quaternion<shz::math::f64> q3(0.0, 1.0, 0.0, shz::math::PI);\n\n\tshz::math::quaternion<shz::math::f64> q12 = q1 * q2;\n\n\tBOOST_CHECK_CLOSE(q12.x, q3.x, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(q12.y, q3.y, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(q12.z, q3.z, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(q12.w, q3.w, ROUND_ERROR);\n\n\tq12 = q1;\n\tq12 *= q2;\n\n\tBOOST_CHECK_CLOSE(q12.x, q3.x, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(q12.y, q3.y, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(q12.z, q3.z, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(q12.w, q3.w, ROUND_ERROR);\n}\n\nBOOST_AUTO_TEST_CASE(quaternionSlerp)\n{\n\tshz::math::quaternion<shz::math::f64> q1(0.0, 1.0, 0.0, 0.0);\n\tshz::math::quaternion<shz::math::f64> q2(0.0, 1.0, 0.0, shz::math::HALF_PI/2);\n\tshz::math::quaternion<shz::math::f64> q3(0.0, 1.0, 0.0, shz::math::HALF_PI);\n\n\tauto half = shz::math::quaternion<shz::math::f64>::slerp(q1, q3, 0.5);\n\n\tBOOST_CHECK_CLOSE(half.x, q2.x, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(half.y, q2.y, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(half.z, q2.z, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(half.w, q2.w, ROUND_ERROR);\n\n\thalf = shz::math::quaternion<shz::math::f64>::slerp(q1, q1, 0.5);\n\tBOOST_CHECK_CLOSE(half.x, q1.x, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(half.y, q1.y, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(half.z, q1.z, ROUND_ERROR);\n\tBOOST_CHECK_CLOSE(half.w, q1.w, ROUND_ERROR);\n}", "meta": {"hexsha": "d37f98c3bb7ce1f2fd343304bf1450ca7b2662f6", "size": 3916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Math/quaternion_tests.cpp", "max_stars_repo_name": "TraxNet/ShadingZenCpp", "max_stars_repo_head_hexsha": "46860da3249900259941bf64f4a46347500b65fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-04-30T15:41:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-28T05:47:18.000Z", "max_issues_repo_path": "tests/Math/quaternion_tests.cpp", "max_issues_repo_name": "TraxNet/ShadingZenCpp", "max_issues_repo_head_hexsha": "46860da3249900259941bf64f4a46347500b65fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/Math/quaternion_tests.cpp", "max_forks_repo_name": "TraxNet/ShadingZenCpp", "max_forks_repo_head_hexsha": "46860da3249900259941bf64f4a46347500b65fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6548672566, "max_line_length": 135, "alphanum_fraction": 0.7037793667, "num_tokens": 1458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6464779651820012}}
{"text": "#include <ctime>\n#include <gtest/gtest.h>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n\n#include \"slick/math/so3.h\"\n#include \"slick/test/unittest/util.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace slick;\n\n// constructors tests ==========================================================\ntemplate <typename T>\nvoid DefaultConstructor_Test() {\n  // for double precision\n  SO3Group<T> rot;\n  EXPECT_MATRIX_NEAR(Eigen::Matrix<T, 3, 3>::Identity(), rot.get_matrix(),\n                     Gap<T>());\n}\n\nTEST(SO3Test, DefaultConstructor) {\n  DefaultConstructor_Test<double>();\n  DefaultConstructor_Test<float>();\n}\n\ntemplate <typename T>\nvoid FromMatrixConstructor_Test() {\n  Eigen::Matrix<T, 3, 1> aaxis = Eigen::Matrix<T, 3, 1>::Random();\n  aaxis.normalize();\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n  Eigen::Matrix<T, 3, 3> m;\n  m = Eigen::AngleAxis<T>(angle, aaxis);\n\n  SO3Group<T> rot(m);\n  EXPECT_MATRIX_NEAR(m, rot.get_matrix(), Gap<T>());\n}\n\nTEST(SO3Test, FromMatrixConstructor) {\n  FromMatrixConstructor_Test<double>();\n  FromMatrixConstructor_Test<float>();\n}\n\ntemplate <typename T>\nvoid FromAngleAxisConstructor_Test() {\n  Eigen::Matrix<T, 3, 1> aaxis = Eigen::Matrix<T, 3, 1>::Random();\n  aaxis.normalize();\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n  Eigen::Matrix<T, 3, 3> m;\n  m = Eigen::AngleAxis<T>(angle, aaxis);\n\n  aaxis *= angle;\n  SO3Group<T> rot(aaxis);\n#if 0  // NOTE: Eigen implementation of rotation matrix is not as accurate as \\\n       // ours\n    EXPECT_MATRIX_NEAR(m, rot.get_matrix(), Gap<T>());\n    std::cout << \"gt:\\n\" << m << std::endl;\n    std::cout << \"est:\\n\" << rot.get_matrix() << std::endl;\n\n\n    std::cout << \"(rot.inverse()*rot).get_matrix():\\n\" << (rot.inverse()*rot).get_matrix() << std::endl;\n    EXPECT_MATRIX_NEAR(Eigen::Matrix<T, 3, 3>::Identity(),\n     (rot.inverse()*rot).get_matrix(), Gap<T>());\n\n\n    std::cout << \"m*m.transpose():\\n\" << m*m.transpose() << std::endl;\n    EXPECT_MATRIX_NEAR(Eigen::Matrix<T, 3, 3>::Identity(),\n     m*m.transpose(), Gap<T>());\n#else\n  EXPECT_MATRIX_NEAR(Eigen::Matrix<T, 3, 3>::Identity(),\n                     (rot.inverse() * rot).get_matrix(), Gap<T>());\n#endif\n}\n\nTEST(SO3Test, FromAngleAxisConstructor) {\n  FromAngleAxisConstructor_Test<double>();\n  FromAngleAxisConstructor_Test<float>();\n}\n\n// template<typename T>\n// void FromListInitializerConstructor_Test() {\n//   SO3Group<T> rot {1, 0, 0, 1};\n//   EXPECT_MATRIX_NEAR(Eigen::Matrix<T, 3, 3>::Identity(), rot.get_matrix(),\n// Gap<T>());\n\n//   EXPECT_NEAR(0.0, rot.ln(), Gap<T>());\n// }\n\n// TEST(SO3Test, FromListInitializerConstructor) {\n//   FromListInitializerConstructor_Test<double>();\n//   FromListInitializerConstructor_Test<float>();\n// }\n\n// so2 specific functions ======================================================\n\ntemplate <typename T>\nvoid Ln_Test() {\n  Eigen::Matrix<T, 3, 1> aaxis = Eigen::Matrix<T, 3, 1>::Random();\n  aaxis.normalize();\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand()) / T(RAND_MAX) * 2 * M_PI;\n  aaxis *= angle;\n\n  SO3Group<T> rot(aaxis);\n  auto est_axis = rot.ln();\n\n  // std::cout << \"gt: \" << aaxis.transpose()\n  //           << \"  est:\" << est_axis.transpose() << std::endl;\n\n  T d = est_axis.dot(aaxis);\n  if (d < 0) {\n    auto a = -est_axis.norm() + 2 * M_PI;\n    est_axis = -est_axis.normalized() * a;\n  }\n  EXPECT_MATRIX_NEAR(aaxis, est_axis, Gap<T>());\n}\n\nTEST(SO3Test, Ln) {\n  Ln_Test<double>();\n  Ln_Test<float>();\n}\n\ntemplate <typename T>\nvoid Inverse_Test() {\n  Eigen::Matrix<T, 3, 1> aaxis = Eigen::Matrix<T, 3, 1>::Random();\n  aaxis.normalize();\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n  aaxis *= angle;\n  SO3Group<T> rot(aaxis);\n  Eigen::Matrix<T, 3, 3> m_inv = rot.get_matrix().inverse();\n  EXPECT_MATRIX_NEAR(m_inv, rot.inverse().get_matrix(), Gap<T>());\n}\n\nTEST(SO3Test, Inverse) {\n  Inverse_Test<double>();\n  Inverse_Test<float>();\n}\n\ntemplate <typename T>\nvoid SO3RightHandMulOperator_Test() {\n  Eigen::Matrix<T, 3, 1> aaxis = Eigen::Matrix<T, 3, 1>::Random();\n  aaxis.normalize();\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n#if 0  // NOTE: Eigen::AngleAxis has less accuracy than ours \n    Eigen::Matrix<T, 3, 3> mrot1;\n    mrot1 = Eigen::AngleAxis<T>(angle, aaxis);\n\n    aaxis *= angle;\n    SO3Group<T> rot1(aaxis);\n\n    aaxis = Eigen::Matrix<T, 3, 1>::Random();\n    aaxis.normalize();\n    std::srand(std::time(0));  // use current time as seed for random generator\n    angle = T(std::rand());\n\n    Eigen::Matrix<T, 3, 3> mrot2;\n    mrot2 = Eigen::AngleAxis<T>(angle, aaxis);\n\n    aaxis *= angle;\n    SO3Group<T> rot2(aaxis);\n\n    EXPECT_MATRIX_NEAR(mrot1 * mrot2, (rot1 * rot2).get_matrix(), Gap<T>());\n#else\n  aaxis *= angle;\n  SO3Group<T> rot1(aaxis);\n  Eigen::Matrix<T, 3, 1> t = -aaxis;\n  SO3Group<T> rot2(t);\n\n  EXPECT_MATRIX_NEAR(Eigen::Matrix<T, 3, 3>::Identity(),\n                     (rot1 * rot2).get_matrix(), Gap<T>());\n#endif\n}\n\nTEST(SO3Test, SO3RightHandMulOperator) {\n  SO3RightHandMulOperator_Test<double>();\n  SO3RightHandMulOperator_Test<float>();\n}\n\ntemplate <typename T>\nvoid MatrixRightHandMulOperator_Test() {\n  Eigen::Matrix<T, 3, 1> aaxis = Eigen::Matrix<T, 3, 1>::Random();\n  aaxis.normalize();\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n#if 0  // NOTE: Eigen::AngleAxis has less accuracy than ours\n    Eigen::Matrix<T, 3, 3> mrot1;\n    mrot1 = Eigen::AngleAxis<T>(angle, aaxis);\n\n    aaxis *= angle;\n    SO3Group<T> rot1(aaxis);\n\n    Eigen::Matrix<T, 3, 3> mrand = Eigen::Matrix<T, 3, 3>::Random();\n\n    EXPECT_MATRIX_NEAR(mrot1 * mrand, rot1 * mrand, Gap<T>());\n#else\n  aaxis *= angle;\n  SO3Group<T> rot1(aaxis);\n\n  Eigen::Matrix<T, 3, 3> mrand = Eigen::Matrix<T, 3, 3>::Random();\n\n  EXPECT_MATRIX_NEAR(rot1.get_matrix() * mrand, rot1 * mrand, Gap<T>());\n\n#endif\n}\n\nTEST(SO3Test, MatrixRightHandMulOperator) {\n  MatrixRightHandMulOperator_Test<double>();\n  MatrixRightHandMulOperator_Test<float>();\n}\n\ntemplate <typename T>\nvoid MatrixLeftHandMulOperator_Test() {\n  Eigen::Matrix<T, 3, 1> aaxis = Eigen::Matrix<T, 3, 1>::Random();\n  aaxis.normalize();\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n#if 0  // NOTE: Eigen::AngleAxis has less accuracy than ours\n    Eigen::Matrix<T, 3, 3> mrot1;\n    mrot1 = Eigen::AngleAxis<T>(angle, aaxis);\n\n    aaxis *= angle;\n    SO3Group<T> rot1(aaxis);\n\n    Eigen::Matrix<T, 3, 3> mrand = Eigen::Matrix<T, 3, 3>::Random();\n\n    EXPECT_MATRIX_NEAR(mrand * mrot1, mrand * rot1, Gap<T>());\n#else\n\n  aaxis *= angle;\n  SO3Group<T> rot1(aaxis);\n\n  Eigen::Matrix<T, 3, 3> mrand = Eigen::Matrix<T, 3, 3>::Random();\n\n  EXPECT_MATRIX_NEAR(mrand * rot1.get_matrix(), mrand * rot1, Gap<T>());\n#endif\n}\n\nTEST(SO3Test, MatrixLeftHandMulOperator) {\n  MatrixLeftHandMulOperator_Test<double>();\n  MatrixLeftHandMulOperator_Test<float>();\n}\n\nint main(int argc, char** argv) {\n  std::vector<char*> vars(argc+1);\n  for (int i = 0; i < argc; ++i)\n    vars[i] = argv[i];\n  char ca[50];\n  sprintf(ca, \"--gtest_repeat=%d\", NSAMPLES);\n  vars[argc] = ca;\n  argc++;\n  ::testing::InitGoogleTest(&argc, &vars.front());\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "ae34aa02d788a5ddd153bd8fb1d231848ddea7e9", "size": 7465, "ext": "cc", "lang": "C++", "max_stars_repo_path": "slick/test/unittest/math_so3_unittest.cc", "max_stars_repo_name": "williammc/Slick", "max_stars_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-13T05:26:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-13T05:26:40.000Z", "max_issues_repo_path": "slick/test/unittest/math_so3_unittest.cc", "max_issues_repo_name": "williammc/Slick", "max_issues_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slick/test/unittest/math_so3_unittest.cc", "max_forks_repo_name": "williammc/Slick", "max_forks_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_forks_repo_licenses": ["BSD-3-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.3840304183, "max_line_length": 104, "alphanum_fraction": 0.6332217013, "num_tokens": 2233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6464779556262797}}
{"text": "/**\n * @file mixedfemwave_test.cc\n * @author Erick Schulz\n * @date 24.07.2020\n * @copyright Developed at SAM, ETH Zurich\n */\n\n#include \"../mixedfemwave.h\"\n\n#include <gtest/gtest.h>\n#include <lf/io/io.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/refinement/mesh_hierarchy.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <iostream>\n#include <memory>\n\nnamespace MixedFEMWave::test {\n\nTEST(MixedFEMWave_computeMQ, test) {\n  // LOADING COARSE MESH\n  auto mesh_factory_init = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader_init(std::move(mesh_factory_init),\n                                 CURRENT_SOURCE_DIR\n                                 \"/../../meshes/unitsquare_unitest.msh\");\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = reader_init.mesh();\n\n  // Vector dofhandler for the finite element space Q\n  lf::assemble::UniformFEDofHandler dofh_Q(mesh_p,\n                                           {{lf::base::RefEl::kPoint(), 0},\n                                            {lf::base::RefEl::kSegment(), 0},\n                                            {lf::base::RefEl::kTria(), 2},\n                                            {lf::base::RefEl::kQuad(), 2}});\n\n  Eigen::SparseMatrix<double> M_Q_sparse = computeMQ(dofh_Q);\n  Eigen::MatrixXd M_Q_dense = Eigen::MatrixXd(M_Q_sparse);\n  Eigen::MatrixXd M_Q_dense_ref = Eigen::MatrixXd::Zero(8, 8);\n  for (int i = 0; i < 8; i++) {\n    M_Q_dense_ref(i, i) = 0.25;\n  }\n\n  double tol = 1.0e-8;\n  Eigen::MatrixXd difference = M_Q_dense - M_Q_dense_ref;\n  ASSERT_NEAR(0.0, difference.lpNorm<Eigen::Infinity>(), tol);\n}\n\nTEST(MixedFEMWave_computeMV, test) {\n  auto rho = [](Eigen::Vector2d x) -> double { return 1.0; };\n  // LOADING COARSE MESH\n  auto mesh_factory_init = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader_init(std::move(mesh_factory_init),\n                                 CURRENT_SOURCE_DIR\n                                 \"/../../meshes/unitsquare_unitest.msh\");\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = reader_init.mesh();\n\n  // Scalar finite element space for lowest-order Lagrangian finite elements\n  std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> fe_space_V =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n  Eigen::SparseMatrix<double> M_V_sparse = computeMV(fe_space_V, rho);\n  Eigen::MatrixXd M_V_dense = Eigen::MatrixXd(M_V_sparse);\n  Eigen::MatrixXd M_V_dense_ref = Eigen::MatrixXd::Zero(5, 5);\n  for (int i = 0; i < 4; i++) {\n    M_V_dense_ref(i, i) = 0.1 + 0.2 / 3.0;\n  }\n  M_V_dense_ref(4, 4) = 1.0 / 3.0;\n\n  double tol = 1.0e-8;\n  Eigen::MatrixXd difference = M_V_dense - M_V_dense_ref;\n  ASSERT_NEAR(0.0, difference.lpNorm<Eigen::Infinity>(), tol);\n}\n\nTEST(MixedFEMWave_computeB, test) {\n  auto rho = [](Eigen::Vector2d x) -> double { return 1.0; };\n  // LOADING COARSE MESH\n  auto mesh_factory_init = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader_init(std::move(mesh_factory_init),\n                                 CURRENT_SOURCE_DIR\n                                 \"/../../meshes/unitsquare_unitest.msh\");\n  std::shared_ptr<lf::mesh::Mesh> mesh_p = reader_init.mesh();\n\n  // Scalar finite element space for lowest-order Lagrangian finite elements\n  std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> fe_space_V =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  // Scalar dofhandler as built along with the finite-element space for V\n  const lf::assemble::DofHandler &dofh_V = fe_space_V->LocGlobMap();\n\n  // Vector dofhandler for the finite element space Q\n  lf::assemble::UniformFEDofHandler dofh_Q(mesh_p,\n                                           {{lf::base::RefEl::kPoint(), 0},\n                                            {lf::base::RefEl::kSegment(), 0},\n                                            {lf::base::RefEl::kTria(), 2},\n                                            {lf::base::RefEl::kQuad(), 2}});\n\n  Eigen::SparseMatrix<double> B_sparse = computeB(dofh_V, dofh_Q);\n  Eigen::MatrixXd B_dense = Eigen::MatrixXd(B_sparse);\n  Eigen::MatrixXd B_dense_ref = Eigen::MatrixXd::Zero(8, 5);\n  B_dense_ref(1, 4) = 0.5;\n  B_dense_ref(2, 4) = 0.5;\n  B_dense_ref(4, 4) = -0.5;\n  B_dense_ref(7, 4) = -0.5;\n\n  double tol = 1.0e-8;\n  Eigen::MatrixXd difference = B_dense - B_dense_ref;\n  ASSERT_NEAR(0.0, difference.lpNorm<Eigen::Infinity>(), tol);\n}\n\n}  // namespace MixedFEMWave::test\n", "meta": {"hexsha": "a9b57a2573ce578db106fefcce120e760f6ffe39", "size": 4495, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MixedFEMWave/templates/test/mixedfemwave_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/MixedFEMWave/templates/test/mixedfemwave_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/MixedFEMWave/templates/test/mixedfemwave_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 40.1339285714, "max_line_length": 80, "alphanum_fraction": 0.6164627364, "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6464779468851681}}
{"text": "/**\n * @file TrajectoryGenerator.hpp\n * @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de)\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft.\n * @date 2019-10-08\n */\n\n#pragma once\n\n#include <vector>\n#include <Eigen/Eigen>\n#include <yaml-cpp/yaml.h>\n\nnamespace momentumopt\n{\n  enum class InterpolationMethod {\n    PiecewiseLinear,\n    PiecewiseConstant,\n  };\n\n  // Class to generate trajectories around way-points in position, velocity and acceleration\n  class Interpolator\n  {\n    public:\n\t  typedef Eigen::Matrix<double,Eigen::Dynamic,2> InterpMat;\n\n    public:\n\t  Interpolator(){}\n\t  ~Interpolator(){}\n      void initialize(const InterpMat& pos_des, const InterpMat& vel_des, const InterpMat& acc_des);\n      void interpolate(const double time, double& position, double& velocity, double& acceleration);\n\n    private:\n      double cons_size_;\n\t  std::vector<double> time_span_;\n\t  Eigen::MatrixXd regression_matrix_;\n\t  Eigen::VectorXd regression_vector_, regression_coeffs_;\n  };\n\n  // Class to generate 3d continuous and smooth trajectories\n  class TrajectoryGenerator\n  {\n    public:\n\t  TrajectoryGenerator(){};\n      ~TrajectoryGenerator(){};\n      void initialize(const double tini, const Eigen::Vector3d& ini_position,\n                      const double tend, const Eigen::Vector3d& end_position,\n                      const Eigen::Vector3d& via_position);\n      void update(const double time);\n\n\t  const Eigen::Vector3d& desPos() const { return pos_des_; }\n\t  const Eigen::Vector3d& desVel() const { return vel_des_; }\n\t  const Eigen::Vector3d& desAcc() const { return acc_des_; }\n\n    private:\n\t  Interpolator traj_interp_[3];\n\t  Eigen::Vector3d pos_des_, vel_des_, acc_des_;\n  };\n}\n", "meta": {"hexsha": "b729f2900cb827c5cbcbdf00e6846e34d7eca2d9", "size": 1766, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "momentumopt/include/momentumopt/utilities/TrajectoryGenerator.hpp", "max_stars_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_stars_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T17:39:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T00:38:22.000Z", "max_issues_repo_path": "momentumopt/include/momentumopt/utilities/TrajectoryGenerator.hpp", "max_issues_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_issues_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-11T19:54:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T13:41:47.000Z", "max_forks_repo_path": "momentumopt/include/momentumopt/utilities/TrajectoryGenerator.hpp", "max_forks_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_forks_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-15T14:36:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T10:42:19.000Z", "avg_line_length": 28.9508196721, "max_line_length": 100, "alphanum_fraction": 0.7027180068, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6464473167198064}}
{"text": "#include <QatGenericFunctions/Variable.h>\n#include <QatGenericFunctions/Parameter.h>\n#include <QatGenericFunctions/Square.h>\n#include <QatGenericFunctions/Sqrt.h>\n#include <QatGenericFunctions/Exp.h>\n#include <QatDataAnalysis/Hist1D.h>\n#include <QatDataAnalysis/Table.h>\n#include <QatDataModeling/TableLikelihoodFunctional.h>\n#include <QatDataModeling/MinuitMinimizer.h>\n#include <QatPlotWidgets/PlotView.h>\n#include <QatPlotWidgets/MultipleViewWindow.h>\n#include <QatPlotting/PlotStream.h>\n#include <QatPlotting/PlotHist1D.h>\n#include <QatPlotting/PlotFunction1D.h>\n#include <QatPlotting/PlotProfile.h>\n#include <QatPlotting/PlotKey.h>\n#include <Eigen/Dense>\n#include <QApplication>\n#include <QMainWindow>\n#include <QAction>\n#include <QToolBar>\n#include <QFont>\n#include <cmath>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <random>\n\nPlotView *createPlotView(const std::string& title, const std::string& xLabel, const std::string yLabel, const PRectF& viewRange);\n\ntypedef std::vector<double> Data;\ntypedef std::vector<double> XList;\ntypedef std::vector<double> YList;\n\nData readData(const std::string& file);\nHist1D binData(const Data& data);\nTable tableData(const Data& data);\n\nconst std::string dataFileName = \"../data01.dat\";\nconst std::string coarseResultFile = \"coarse-result.dat\";\nconst double nBin = 400;\nconst bool verbose = false;\nconst int SUCCESS = 3;\nconst size_t nTrial = 100;\nconst double wScale = 0.05;\nconst double nEffTrial = 1 * nTrial;\nconst double Precision = 32;\n\n// Coarse Search\nconst double fMin = 0.01;\nconst double fMax = 0.99;\nconst double mu1Min = 80;\nconst double mu1Max = 120;\nconst double mu2Min = mu1Min;\nconst double mu2Max = mu1Max;\nconst double gamma1Min = 0.01;\nconst double gamma1Max = 1;\nconst double gamma2Min = gamma1Min;\nconst double gamma2Max = gamma1Max;\nconst double pNBins = 200;\nconst std::string searchType = \"Coarse\";\nconst std::string fileExt = searchType + \".png\";\n\n\nint main(int argc, char **argv)\n{\n    QApplication app(argc, argv);\n    MultipleViewWindow window;\n\n    Genfun::Square qPow2;\n    Genfun::Sqrt qSqrt;\n    Genfun::Exp qExp;\n\n    const Data data = readData(dataFileName);\n    Hist1D dataHist = binData(data);\n    Table dataTable = tableData(data);\n    TableLikelihoodFunctional objFunc(dataTable);\n    Genfun::Variable X = dataTable.symbol(\"E\");\n\n//  Prepare View\n    const double viewXMin = dataHist.binLowerEdge(0) - 10;\n    const double viewXMax = dataHist.binUpperEdge(nBin-1) + 10;\n    const double viewYMin = 1e-2;\n    const double viewYMax = dataHist.maxContents() * 3;\n    PRectF viewRange(viewXMin, viewXMax, viewYMin, viewYMax);\n    PlotView *view = createPlotView(\"Spectrum\", \"Energy / eV\", \"\", viewRange);\n    view->setLogY(true);\n    window.add(view, \"Fit\");\n\n    PlotKey legend(viewXMin, viewYMax);\n    legend.setFont(QFont(\"Times\", 25, QFont::Bold));\n    view->add(&legend);\n\n// Plot Data\n    PlotHist1D dataHistPlot(dataHist);\n    {\n        PlotHist1D::Properties prop;\n        prop.plotStyle = PlotHist1D::Properties::SYMBOLS;\n        prop.symbolSize = 10;\n        prop.pen.setWidth(1.9);\n        dataHistPlot.setProperties(prop);\n    }\n    view->add(&dataHistPlot);\n    legend.add(&dataHistPlot, \"Data\");\n\n\n//  Lorentz Fit\n    Genfun::Parameter pMu1(\"Mu1\", 80, dataHist.min(), dataHist.max());\n    Genfun::Parameter pMu2(\"Mu2\", 120, dataHist.min(), dataHist.max());\n    Genfun::Parameter pGamma1(\"Gamma1\", 0.5, 0, 10*std::sqrt(dataHist.variance()));\n    Genfun::Parameter pGamma2(\"Gamma2\", 0.5, 0, 10*std::sqrt(dataHist.variance()));\n    Genfun::Parameter pF(\"fraction\", 0.5, 0, 1);\n\n    Genfun::GENFUNCTION LorentzPDF1 = 1 / (M_PI * pGamma1 * (1 + qPow2((X - pMu1)/pGamma1)));\n    Genfun::GENFUNCTION LorentzPDF2 = 1 / (M_PI * pGamma2 * (1 + qPow2((X - pMu2)/pGamma2)));\n    Genfun::GENFUNCTION Lorentz = dataHist.sum() * (pF * LorentzPDF1 + (1-pF) * LorentzPDF2);\n\n    std::cout << searchType + \" Search\" << std::endl;\n\n    std::random_device rndDev;\n    std::mt19937_64 rndEng(rndDev());\n    std::uniform_real_distribution<double> mu1Dist(mu1Min, mu1Max);\n    std::uniform_real_distribution<double> mu2Dist(mu2Min, mu2Max);\n    std::uniform_real_distribution<double> gamma1Dist(gamma1Min, gamma1Max);\n    std::uniform_real_distribution<double> gamma2Dist(gamma2Min, gamma2Max);\n    std::uniform_real_distribution<double> fDist(fMin, fMax);\n    Hist1D mu1Hist(\"Mu1\", pNBins, mu1Min, mu1Max);\n    Hist1D mu2Hist(\"Mu2\", pNBins, mu2Min, mu2Max);\n    Hist1D gamma1Hist(\"Gamma1\", pNBins, gamma1Min, gamma1Max);\n    Hist1D gamma2Hist(\"Gamma2\", pNBins, gamma2Min, gamma2Max);\n    Hist1D fHist(\"Fraction\", pNBins, fMin, fMax);\n    double count = nTrial;\n    while (count > 0)\n    {\n        double mu10 = mu1Dist(rndEng);\n        double mu20 = mu2Dist(rndEng);\n        double gamma10 = gamma1Dist(rndEng);\n        double gamma20 = gamma2Dist(rndEng);\n        double f0 = fDist(rndEng);\n\n        pMu1.setValue(mu10);\n        pMu2.setValue(mu20);\n        pGamma1.setValue(gamma10);\n        pGamma2.setValue(gamma20);\n        pF.setValue(f0);\n\n        MinuitMinimizer lorentzMinimizer(verbose);\n        lorentzMinimizer.addParameter(&pMu1);\n        lorentzMinimizer.addParameter(&pMu2);\n        lorentzMinimizer.addParameter(&pGamma1);\n        lorentzMinimizer.addParameter(&pGamma2);\n        lorentzMinimizer.addParameter(&pF);\n        lorentzMinimizer.addStatistic(&objFunc, &Lorentz);\n        lorentzMinimizer.minimize();\n        \n        if (lorentzMinimizer.getStatus() == SUCCESS)\n        {\n            --count;\n\n            Eigen::MatrixXd errMat = lorentzMinimizer.getErrorMatrix();\n            double weight = wScale / std::sqrt(errMat.trace());\n  \n            if (pMu1.getValue() <= pMu2.getValue())\n            {\n                mu1Hist.accumulate(pMu1.getValue(), weight);\n                mu2Hist.accumulate(pMu2.getValue(), weight);\n                gamma1Hist.accumulate(pGamma1.getValue(), weight);\n                gamma2Hist.accumulate(pGamma2.getValue(), weight);\n                fHist.accumulate(pF.getValue(), weight);\n            }else\n            {\n                mu1Hist.accumulate(pMu2.getValue(),weight);\n                mu2Hist.accumulate(pMu1.getValue(), weight);\n                gamma1Hist.accumulate(pGamma2.getValue(), weight);\n                gamma2Hist.accumulate(pGamma1.getValue(), weight);\n                fHist.accumulate(1 - pF.getValue(), weight);\n            }\n        }\n    }\n    \n    std::cout << \"Mu1 :\" << mu1Hist.mean() << \" +/- \" << std::sqrt(mu1Hist.variance()) << std::endl;\n    std::cout << \"Mu2 :\" << mu2Hist.mean() << \" +/- \" << std::sqrt(mu2Hist.variance()) << std::endl;\n    std::cout << \"Gamma1 :\" << gamma1Hist.mean() << \" +/- \" << std::sqrt(gamma1Hist.variance()) << std::endl;\n    std::cout << \"Gamma2 :\" << gamma2Hist.mean() << \" +/- \" << std::sqrt(gamma2Hist.variance()) << std::endl;\n    std::cout << \"Fraction :\" << fHist.mean() << \" +/- \" << std::sqrt(fHist.variance()) << std::endl;\n\n    std::ofstream oFile(coarseResultFile);\n    oFile << std::setprecision(Precision) << mu1Hist.mean() << \"\\t\";\n    oFile << std::setprecision(Precision) << std::sqrt(mu1Hist.variance()) << std::endl;\n    oFile << std::setprecision(Precision) << mu2Hist.mean() << \"\\t\";\n    oFile << std::setprecision(Precision) << std::sqrt(mu2Hist.variance()) << std::endl;\n    oFile << std::setprecision(Precision) << gamma1Hist.mean() << \"\\t\";\n    oFile << std::setprecision(Precision) << std::sqrt(gamma1Hist.variance()) << std::endl;\n    oFile << std::setprecision(Precision) << gamma2Hist.mean() << \"\\t\";\n    oFile << std::setprecision(Precision) << std::sqrt(gamma2Hist.variance()) << std::endl;\n    oFile << std::setprecision(Precision) << fHist.mean() << \"\\t\";\n    oFile << std::setprecision(Precision) << std::sqrt(fHist.variance()) << std::endl;\n    oFile.close();\n\n    pMu1.setValue(mu1Hist.mean());\n    pMu2.setValue(mu2Hist.mean());\n    pGamma1.setValue(gamma1Hist.mean());\n    pGamma2.setValue(gamma2Hist.mean());\n    pF.setValue(fHist.mean());\n\n    \n    PlotFunction1D LorentzPlot(Lorentz);\n    {\n        PlotFunction1D::Properties prop;\n        prop.pen.setWidth(2);\n        prop.pen.setColor(Qt::red);\n        LorentzPlot.setProperties(prop);\n    }\n    view->add(&LorentzPlot);\n    legend.add(&LorentzPlot, \"Lorentz\");\n    view->save(\"Lorentz\" + fileExt);\n\n    PlotView *mu1View = createPlotView(\"Mu1\", \"\", \"\", PRectF(mu1Min, mu2Max, 0, nEffTrial));\n    PlotHist1D mu1Plot(mu1Hist);\n    mu1View->add(&mu1Plot);\n    window.add(mu1View, \"Mu1\");\n    mu1View->save(\"Mu1\" + fileExt);\n\n    PlotView *mu2View = createPlotView(\"Mu2\", \"\", \"\", PRectF(mu2Min, mu2Max, 0, nEffTrial));\n    PlotHist1D mu2Plot(mu2Hist);\n    mu2View->add(&mu2Plot);\n    window.add(mu2View, \"Mu2\");\n    mu2View->save(\"Mu2\" + fileExt);\n\n    PlotView *gamma1View = createPlotView(\"Gamma1\", \"\", \"\", PRectF(gamma1Min, gamma2Max, 0, nEffTrial));\n    PlotHist1D gamma1Plot(gamma1Hist);\n    gamma1View->add(&gamma1Plot);\n    window.add(gamma1View, \"Gamma1\");\n    gamma1View->save(\"Gamma1\" + fileExt);\n    \n    PlotView *gamma2View = createPlotView(\"Gamma2\", \"\", \"\", PRectF(gamma2Min, gamma2Max, 0, nEffTrial));\n    PlotHist1D gamma2Plot(gamma2Hist);\n    gamma2View->add(&gamma2Plot);\n    window.add(gamma2View, \"Gamma2\");\n    gamma2View->save(\"Gamma2\" + fileExt);\n\n    PlotView *fView = createPlotView(\"Fraction\", \"\", \"\", PRectF(fMin, fMax, 0, nEffTrial));\n    PlotHist1D fPlot(fHist);\n    fView->add(&fPlot);\n    window.add(fView, \"Fraction\");\n    fView->save(\"Fraction\" + fileExt);\n\n/*\n\tQToolBar *toolBar = window.addToolBar(\"Tools\");\n\t\n    QAction *quitAction = toolBar->addAction(\"Quit (q)\");\n    quitAction->setShortcut(QKeySequence(\"q\"));\n\tQObject::connect(quitAction, SIGNAL(triggered()), &app, SLOT(quit()));\n    \n    QAction *saveAction = toolBar->addAction(\"Save as (s)\");\n    saveAction->setShortcut(QKeySequence(\"s\"));\n    QObject::connect(saveAction, SIGNAL(triggered()), view, SLOT(save()));\n*/\n\twindow.show();\n\tapp.exec();\n\n    return 0;\n}\n\n\n//////////////////////////////////////////////////////////////////////////////\n\nData readData(const std::string& file)\n{\n    std::ifstream dataFile(file);\n    double dataIn;\n    Data data;\n\n    while (dataFile >> dataIn)\n    {\n        data.push_back(dataIn);\n    }\n    \n    return data;\n}\n\nHist1D binData(const Data& data)\n{\n    std::pair<Data::const_iterator,Data::const_iterator> MIN_MAX_Iter = std::minmax_element(data.begin(), data.end());\n    double dataMin = *(MIN_MAX_Iter.first);\n    double dataMax = *(MIN_MAX_Iter.second);\n\n    std::cout << \"Data Num: \" << data.size() << std::endl;\n    std::cout << \"Data Min: \" << dataMin << std::endl;\n    std::cout << \"Data Max: \" << dataMax << std::endl;\n    \n    Hist1D dataHist(nBin, std::floor(dataMin-1), std::ceil(dataMax+1));\n    for (size_t i = 0; i < data.size(); i++)\n    {\n        dataHist.accumulate(data[i]);\n    }\n    \n    std::cout << \"Data Mean: \" << dataHist.mean() << std::endl;\n    std::cout << \"Data Variance: \" << dataHist.variance() << std::endl;\n    std::cout << \"Data Sigma: \" << std::sqrt(dataHist.variance()) << std::endl;\n    std::cout << std::endl;\n\n    return dataHist;\n}\n\nTable tableData(const Data& data)\n{\n    Table dataTable(\"Data Table\");\n\n    for (size_t i = 0; i < data.size(); i++)\n    {\n        dataTable.add(\"E\", data[i]);\n        dataTable.capture();\n    }\n    \n    return dataTable;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n\nPlotView *createPlotView(const std::string& title, const std::string& xLabel, const std::string yLabel, const PRectF& viewRange)\n{\n    PlotView *view_ptr = new PlotView(viewRange);\n    view_ptr->setFixedWidth(1200);\n    view_ptr->setFixedHeight(800);\n\n    PlotStream titleStream(view_ptr->titleTextEdit());\n    titleStream << PlotStream::Clear()\n                << PlotStream::Center()\n                << PlotStream::Family(\"Sans Serif\")\n                << PlotStream::Size(24)\n                << title\n                << PlotStream::EndP();\n\n    PlotStream xLabelStream(view_ptr->xLabelTextEdit());\n    xLabelStream << PlotStream::Clear()\n                << PlotStream::Center()\n                << PlotStream::Family(\"Sans Serif\")\n                << PlotStream::Size(24)\n                << xLabel\n                << PlotStream::EndP();\n\n    PlotStream yLabelStream(view_ptr->yLabelTextEdit());\n    yLabelStream << PlotStream::Clear()\n                << PlotStream::Center()\n                << PlotStream::Family(\"Sans Serif\")\n                << PlotStream::Size(24)\n                << yLabel\n                << PlotStream::EndP();\n    \n    return view_ptr;\n}", "meta": {"hexsha": "487bc7c1caea72ff96997cc9b852058aeecf0278", "size": 12614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Assignments/Assignments_12/EX3/b/coarse/main.cpp", "max_stars_repo_name": "CaoSY/PittCompMethods", "max_stars_repo_head_hexsha": "853c36676df140eecd249bd9905eb9fa704f1585", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignments/Assignments_12/EX3/b/coarse/main.cpp", "max_issues_repo_name": "CaoSY/PittCompMethods", "max_issues_repo_head_hexsha": "853c36676df140eecd249bd9905eb9fa704f1585", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignments/Assignments_12/EX3/b/coarse/main.cpp", "max_forks_repo_name": "CaoSY/PittCompMethods", "max_forks_repo_head_hexsha": "853c36676df140eecd249bd9905eb9fa704f1585", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5323943662, "max_line_length": 129, "alphanum_fraction": 0.6308863168, "num_tokens": 3548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.646447312371696}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid main() {\n\n\t{\n\t\tMatrix2f m;\n\t\tm << 1, 2, 3, 4;\n\t\tcout << m << endl;\n\n\t\tRowVectorXd vec1(3);\n\t\tvec1 << 1, 2, 3;\n\t\tcout << \"vec1 : \" << vec1 << endl;\n\n\t\tRowVectorXd vec2(4);\n\t\tvec2 << 1, 4, 9, 16;\n\t\tcout << \"vec2 : \" << vec2 << endl;\n\n\t\tRowVectorXd joined(7);\n\t\tjoined << vec1, vec2;\n\t\tcout << \"joined = \" << joined << endl;\n\n\t\tMatrixXf matA(2, 2); matA << 1, 2, 3, 4;\n\t\tMatrixXf matB(4, 4);\n\t\tmatB << matA, matA / 10, matA / 10, matA;\n\t\tcout << \"matA: \\n\" << matA << endl;\n\t\tcout << \"matB: \\n\" << matB << endl;\n\t}\n\t{\n\t\tMatrix3f m;\n\t\tm.row(0) << 1, 2, 3;\n\t\tm.block(1, 0, 2, 2) << 4, 5, 7, 8;\n\t\tm.col(2).tail(2) << 6, 9;\n\t\tcout << m << endl;\n\t}\n\t{\n\t\tcout << \"A fixed-size array:\\n\";\n\t\tArray33f a1 = Array33f::Zero();\n\t\tcout << a1 << endl;\n\n\t\tcout << \"A one-dimensional dynamic-size array: \\n\";\n\t\tArrayXf a2 = ArrayXf::Zero(3);\n\t\tcout << a2 << endl;\n\n\t\tcout << \"A two-dimensional dynamic-size array:\\n\";\n\t\tArrayXXf a3 = ArrayXXf::Zero(3, 4);\n\t\tcout << a3 << endl;\n\t}\n\t{\n\t\tfloat M_PI = 3.14;\n\t\tArrayXXf table(10, 4);\n\t\ttable.col(0) = ArrayXf::LinSpaced(10, 0, 90);\n\t\ttable.col(1) = M_PI / 180 * table.col(0);\n\t\ttable.col(2) = table.col(1).sin();\n\t\ttable.col(3) = table.col(1).cos();\n\t\tstd::cout << \"  Degrees   Radians      Sine    Cosine\\n\";\n\t\tstd::cout << table << std::endl;\n\t}\n\n\tsystem(\"pause\");\n}", "meta": {"hexsha": "958731d62bad763cbbe0fdea7beb26b7eef5414e", "size": 1389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/advanced_initialization/advanced_initialization.cpp", "max_stars_repo_name": "quanhua92/learning-notes", "max_stars_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/eigen/eigen/advanced_initialization/advanced_initialization.cpp", "max_issues_repo_name": "quanhua92/learning-notes", "max_issues_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/eigen/eigen/advanced_initialization/advanced_initialization.cpp", "max_forks_repo_name": "quanhua92/learning-notes", "max_forks_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.703125, "max_line_length": 59, "alphanum_fraction": 0.5421166307, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6463174152363081}}
{"text": "// Copyright Paul A. Bristow 2017, 2018\n// Copyright John Z. Maddock 2017\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or\n//  copy at http ://www.boost.org/LICENSE_1_0.txt).\n\n/*! \\brief Graph showing differences of Lambert W function double from nearest representable values.\n\n\\details\n\n*/\n\n#include <boost/math/special_functions/lambert_w.hpp>\nusing boost::math::lambert_w0;\nusing boost::math::lambert_wm1;\n#include <boost/math/special_functions.hpp>\nusing boost::math::isfinite;\n#include <boost/svg_plot/svg_2d_plot.hpp>\nusing namespace boost::svg;\n\n// For higher precision computation of Lambert W.\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/math/special_functions/next.hpp> // For float_distance.\nusing boost::math::float_distance;\n\n#include <iostream>\n// using std::cout;\n// using std::endl;\n#include <exception>\n#include <stdexcept>\n#include <string>\n#include <array>\n#include <vector>\n#include <utility>\nusing std::pair;\n#include <map>\nusing std::map;\n#include <set>\nusing std::multiset;\n#include <limits>\nusing std::numeric_limits;\n#include <cmath> // exp\n\n/*!\n*/\n\n\nint main()\n{\n  try\n  {\n    std::cout << \"Lambert W errors graph.\" << std::endl;\n    using boost::multiprecision::cpp_bin_float_50; \n    using boost::multiprecision::cpp_bin_float_quad; \n\n    typedef cpp_bin_float_quad HPT; // High precision type.\n\n    using boost::math::float_distance;\n    using boost::math::policies::precision;\n    using boost::math::policies::digits10;\n    using boost::math::policies::digits2;\n    using boost::math::policies::policy;\n\n    std::cout.precision(std::numeric_limits<double>::max_digits10);\n\n    //[lambert_w_graph_1\n\n    //] [/lambert_w_graph_1]\n    {\n      std::map<const double, double> w0s;   // Lambert W0 branch values, default double precision, digits2 = 53.\n      std::map<const double, double> w0s_50;   // Lambert W0 branch values digits2 = 50.\n\n      int max_distance = 0;\n      int total_distance = 0;\n      int count = 0;\n      const int bits = 7;\n      double min_z = -0.367879; // Close to singularity at -0.3678794411714423215955237701614608727 -exp(-1)\n      //double min_z = 0.06; // Above 0.05 switch point.\n      double max_z = 99.99;\n      double step_z = 0.05;\n\n      for (HPT z = min_z; z < max_z; z += step_z)\n      {\n        double zd = static_cast<double>(z);\n        double w0d = lambert_w0(zd); // double result from same default.\n        HPT w0_best = lambert_w0<HPT>(z);\n        double w0_best_d = static_cast<double>(w0_best); // reference result.\n       // w0s[zd] = (w0d - w0_best_d); // absolute difference.\n        // w0s[z] = 100 * (w0 - w0_best) / w0_best; // difference relative % .\n        w0s[zd] = float_distance<double>(w0d, w0_best_d); // difference in bits.\n        double fd = float_distance<double>(w0d, w0_best_d);\n        int distance = static_cast<int>(fd);\n        int abs_distance = abs(distance);\n\n         // std::cout << count << \" \" << zd << \" \" << w0d << \" \" << w0_best_d\n         //   << \", Difference = \" << w0d - w0_best_d << \", % = \" << (w0d - w0_best_d) / w0d << \", Distance = \" << distance << std::endl;\n\n        total_distance += abs_distance;\n        if (abs_distance > max_distance)\n        {\n          max_distance = abs_distance;\n        }\n        count++;\n      } // for z\n      std::cout << \"points \" << count << std::endl;\n      std::cout.precision(3);\n      std::cout << \"max distance \" << max_distance << \", total distances = \" << total_distance\n        << \", mean distance \" << (float)total_distance / count << std::endl;\n\n      typedef std::map<const double, double>::const_iterator Map_Iterator;\n\n   /* for (std::map<const double, double>::const_iterator it = w0s.begin(); it != w0s.end(); ++it)\n      {\n        std::cout  << \" \" << *(it) << \"\\n\";\n      }\n  */\n      svg_2d_plot data_plot_0; // <-0.368, -46> <-0.358, -4> <-0.348, 1>...\n\n      data_plot_0.title(\"Lambert W0 function differences from 'best' for double.\")\n        .title_font_size(11)\n        .x_size(400)\n        .y_size(200)\n        .legend_on(false)\n        //.legend_font_weight(1)\n        .x_label(\"z\")\n        .y_label(\"W0 difference (bits)\")\n        //.x_label_on(true)\n        //.y_label_on(true)\n        //.xy_values_on(false)\n        .x_range(-1, 100.)\n        .y_range(-4., +4.)\n        .x_major_interval(10.)\n        .y_major_interval(2.)\n        .x_major_grid_on(true)\n        .y_major_grid_on(true)\n        .x_label_font_size(9)\n        .y_label_font_size(9)\n        //.x_values_on(true)\n        //.y_values_on(true)\n        .y_values_rotation(horizontal)\n        //.plot_window_on(true)\n        .x_values_precision(3)\n        .y_values_precision(3)\n        .coord_precision(3) // Needed to avoid stepping on curves.\n        //.coord_precision(4) // Needed to avoid stepping on curves.\n        .copyright_holder(\"Paul A. Bristow\")\n        .copyright_date(\"2018\")\n        //.background_border_color(black);\n        ;\n\n\n      data_plot_0.plot(w0s, \"W0 branch\").line_color(red).shape(none).line_on(true).bezier_on(false).line_width(0.2);\n      //data_plot.plot(wm1s, \"W-1 branch\").line_color(blue).shape(none).line_on(true).bezier_on(false).line_width(1);\n      data_plot_0.write(\"./lambert_w0_errors_graph\");\n\n    } // end W0 branch plot.\n    { // Repeat for Lambert W-1 branch.\n\n      std::map<const double, double> wm1s;   // Lambert W-1 branch values.\n      std::map<const double, double> wm1s_50;   // Lambert Wm1 branch values digits2 = 50.\n\n      int max_distance = 0;\n      int total_distance = 0;\n      int count = 0;\n      const int bits = 7;\n      double min_z = -0.367879; // Close to singularity at -0.3678794411714423215955237701614608727 -exp(-1)\n                                //double min_z = 0.06; // Above 0.05 switch point.\n      double max_z = -0.0001;\n      double step_z = 0.001;\n\n      for (HPT z = min_z; z < max_z; z += step_z)\n      {\n        if (z > max_z)\n        {\n          break;\n        }\n        double zd = static_cast<double>(z);\n        double wm1d = lambert_wm1(zd); // double result from same default.\n        HPT wm1_best = lambert_wm1<HPT>(z);\n        double wm1_best_d = static_cast<double>(wm1_best); // reference result.\n                                                         // wm1s[zd] = (wm1d - wm1_best_d); // absolute difference.\n                                                         // wm1s[z] = 100 * (wm1 - wm1_best) / wm1_best; // difference relative % .\n        wm1s[zd] = float_distance<double>(wm1d, wm1_best_d); // difference in bits.\n        double fd = float_distance<double>(wm1d, wm1_best_d);\n        int distance = static_cast<int>(fd);\n        int abs_distance = abs(distance);\n\n         //std::cout << count << \" \" << zd << \" \" << wm1d << \" \" << wm1_best_d\n         //  << \", Difference = \" << wm1d - wm1_best_d << \", % = \" << (wm1d - wm1_best_d) / wm1d << \", Distance = \" << distance << std::endl;\n\n        total_distance += abs_distance;\n        if (abs_distance > max_distance)\n        {\n          max_distance = abs_distance;\n        }\n        count++;\n\n      } // for z\n      std::cout << \"points \" << count << std::endl;\n      std::cout.precision(3);\n      std::cout << \"max distance \" << max_distance << \", total distances = \" << total_distance\n        << \", mean distance \" << (float)total_distance / count << std::endl;\n\n      typedef std::map<const double, double>::const_iterator Map_Iterator;\n\n      /* for (std::map<const double, double>::const_iterator it = wm1s.begin(); it != wm1s.end(); ++it)\n      {\n      std::cout  << \" \" << *(it) << \"\\n\";\n      }\n      */\n      svg_2d_plot data_plot_m1; // <-0.368, -46> <-0.358, -4> <-0.348, 1>...\n\n      data_plot_m1.title(\"Lambert W-1 function differences from 'best' for double.\")\n        .title_font_size(11)\n        .x_size(400)\n        .y_size(200)\n        .legend_on(false)\n        //.legend_font_weight(1)\n        .x_label(\"z\")\n        .y_label(\"W-1 difference (bits)\")\n        .x_range(-0.39, +0.0001)\n        .y_range(-4., +4.)\n        .x_major_interval(0.1)\n        .y_major_interval(2.)\n        .x_major_grid_on(true)\n        .y_major_grid_on(true)\n        .x_label_font_size(9)\n        .y_label_font_size(9)\n        //.x_values_on(true)\n        //.y_values_on(true)\n        .y_values_rotation(horizontal)\n        //.plot_window_on(true)\n        .x_values_precision(3)\n        .y_values_precision(3)\n        .coord_precision(3) // Needed to avoid stepping on curves.\n                            //.coord_precision(4) // Needed to avoid stepping on curves.\n        .copyright_holder(\"Paul A. Bristow\")\n        .copyright_date(\"2018\")\n        //.background_border_color(black);\n        ;\n        data_plot_m1.plot(wm1s, \"W-1 branch\").line_color(darkblue).shape(none).line_on(true).bezier_on(false).line_width(0.2);\n        data_plot_m1.write(\"./lambert_wm1_errors_graph\");\n    }\n  }\n  catch (std::exception& ex)\n  {\n    std::cout << ex.what() << std::endl;\n  }\n}  // int main()\n\n   /*\n   //[lambert_w_errors_graph_1_output\n   Lambert W errors graph.\n   points 2008\n   max distance 46, total distances = 717, mean distance 0.357\n\n   points 368\n   max distance 23, total distances = 329, mean distance 0.894\n\n   //] [/lambert_w_errors_graph_1_output]\n   */\n", "meta": {"hexsha": "45baa200ce90bf62c8af303d78ac1c5eb1144888", "size": 9234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/lambert_w_errors_graph.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/math/tools/lambert_w_errors_graph.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/math/tools/lambert_w_errors_graph.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 35.1102661597, "max_line_length": 141, "alphanum_fraction": 0.5965995235, "num_tokens": 2587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.6463174147153901}}
{"text": "// SPDX-License-Identifier: MIT\n// Copyright (c) 2020 Thomas Vanderbruggen <th.vanderbruggen@gmail.com>\n\n#ifndef SCICPP_CORE_INTERPOLATE\n#define SCICPP_CORE_INTERPOLATE\n\n#include \"scicpp/core/functional.hpp\"\n#include \"scicpp/core/macros.hpp\"\n#include \"scicpp/core/meta.hpp\"\n#include \"scicpp/linalg/utils.hpp\"\n\n#include <Eigen/Core>\n#include <unsupported/Eigen/Splines>\n#include <utility>\n\nnamespace scicpp::interpolate {\n\n// Interpolation with degree zero doesn't work\nenum InterpKind : int { /* ZERO = 0, */ SLINEAR = 1, QUADRATIC = 2, CUBIC = 3 };\n\nnamespace detail {\n\n// https://stackoverflow.com/questions/29822041/eigen-spline-interpolation-how-to-get-spline-y-value-at-arbitray-point-x\n\ntemplate <InterpKind kind>\nclass SplineFunction {\n  public:\n    template <class EigenVector>\n    SplineFunction(const EigenVector &x, const EigenVector &y)\n        : x_min(x.minCoeff()), x_max(x.maxCoeff()),\n          // Spline fitting here. X values are scaled down to [0, 1] for this.\n          m_spline(Eigen::SplineFitting<Eigen::Spline<double, 1>>::Interpolate(\n              y.transpose(),\n              std::min<int>(int(x.rows() - 1), kind),\n              scaled_values(x))) {\n        scicpp_require(x.size() == y.size());\n        scicpp_require(x_max > x_min);\n    }\n\n    template <typename T>\n    auto operator()(T x) const {\n        // x values need to be scaled down in extraction as well.\n        return m_spline(scaled_value(x))(0);\n    }\n\n  private:\n    template <typename T>\n    auto scaled_value(T x) const {\n        return (x - T(x_min)) / (T(x_max) - T(x_min));\n    }\n\n    template <class EigenVector>\n    auto scaled_values(const EigenVector &v) const {\n        return v.unaryExpr([this](double x) { return scaled_value(x); })\n            .transpose();\n    }\n\n    double x_min, x_max;\n    Eigen::Spline<double, 1> m_spline;\n};\n\n} // namespace detail\n\ntemplate <InterpKind kind = SLINEAR>\nstruct interp1d {\n    template <typename Array1, typename Array2>\n    interp1d(const Array1 &x, const Array2 &y)\n        : s(linalg::to_eigen_array(x), linalg::to_eigen_array(y)) {}\n\n    template <typename T>\n    auto operator()(T &&x) const {\n        if constexpr (meta::is_iterable_v<T>) {\n            return map(s, std::forward<T>(x));\n        } else {\n            return s(x);\n        }\n    }\n\n  private:\n    detail::SplineFunction<kind> s;\n};\n\n} // namespace scicpp::interpolate\n\n#endif // SCICPP_CORE_INTERPOLATE\n", "meta": {"hexsha": "8eea28a5912114a9bb7a213a4f99a5a6b85178a3", "size": 2420, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "scicpp/core/interpolate.hpp", "max_stars_repo_name": "tvanderbruggen/SciCpp", "max_stars_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-02T09:03:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T11:58:05.000Z", "max_issues_repo_path": "scicpp/core/interpolate.hpp", "max_issues_repo_name": "tvanderbruggen/SciCpp", "max_issues_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scicpp/core/interpolate.hpp", "max_forks_repo_name": "tvanderbruggen/SciCpp", "max_forks_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1395348837, "max_line_length": 120, "alphanum_fraction": 0.6462809917, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.646284511126388}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_CONSTANTS_HPP\n#define STAN_MATH_PRIM_FUN_CONSTANTS_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/fun/inv.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\n// TODO(anyone) Use constexpr when moving to C++17\n\n/**\n * Return the base of the natural logarithm.\n *\n * @return Base of natural logarithm.\n */\nstatic constexpr double e() { return boost::math::constants::e<double>(); }\n\n/**\n * Return the Euler's gamma constant.\n *\n * @return Euler's Gamma.\n */\nstatic constexpr double egamma() {\n  return boost::math::constants::euler<double>();\n}\n\n/**\n * Return the value of pi.\n *\n * @return Pi.\n */\nstatic constexpr double pi() { return boost::math::constants::pi<double>(); }\n\n/**\n * Smallest positive value.\n */\nstatic constexpr double EPSILON = std::numeric_limits<double>::epsilon();\n\n/**\n * Positive infinity.\n */\nstatic constexpr double INFTY = std::numeric_limits<double>::infinity();\n\n/**\n * Negative infinity.\n */\nstatic constexpr double NEGATIVE_INFTY = -INFTY;\n\n/**\n * (Quiet) not-a-number value.\n */\nstatic constexpr double NOT_A_NUMBER = std::numeric_limits<double>::quiet_NaN();\n\n/**\n * Twice the value of \\f$ \\pi \\f$,\n * \\f$ 2\\pi \\f$.\n */\nstatic constexpr double TWO_PI = boost::math::constants::two_pi<double>();\n\n/**\n * The natural logarithm of 0,\n * \\f$ \\log 0 \\f$.\n */\nstatic constexpr double LOG_ZERO = -INFTY;\n\n/**\n * The natural logarithm of machine precision \\f$ \\epsilon \\f$,\n * \\f$ \\log \\epsilon \\f$.\n */\nconst double LOG_EPSILON = std::log(EPSILON);\n\n/**\n * The natural logarithm of \\f$ \\pi \\f$,\n * \\f$ \\log \\pi \\f$.\n */\nconst double LOG_PI = std::log(pi());\n\n/**\n * The natural logarithm of 2,\n * \\f$ \\log 2 \\f$.\n */\nstatic constexpr double LOG_TWO = boost::math::constants::ln_two<double>();\n\n/**\n * The natural logarithm of 0.5,\n * \\f$ \\log 0.5 = \\log 1 - \\log 2 \\f$.\n */\nstatic constexpr double LOG_HALF = -LOG_TWO;\n\n/**\n * The natural logarithm of 2 plus the natural logarithm of \\f$ \\pi \\f$,\n * \\f$ \\log(2\\pi) \\f$.\n */\nconst double LOG_TWO_PI = LOG_TWO + LOG_PI;\n\n/**\n * The value of one quarter the natural logarithm of \\f$ \\pi \\f$,\n * \\f$ \\log(\\pi) / 4 \\f$.\n */\nconst double LOG_PI_OVER_FOUR = 0.25 * LOG_PI;\n\n/**\n * The natural logarithm of the square root of \\f$ \\pi \\f$,\n * \\f$ \\log(sqrt{\\pi}) \\f$.\n */\nconst double LOG_SQRT_PI = std::log(boost::math::constants::root_pi<double>());\n\n/**\n * The natural logarithm of 10,\n * \\f$ \\log 10 \\f$.\n */\nstatic constexpr double LOG_TEN = boost::math::constants::ln_ten<double>();\n\n/**\n * The value of the square root of 2,\n * \\f$ \\sqrt{2} \\f$.\n */\nstatic constexpr double SQRT_TWO = boost::math::constants::root_two<double>();\n\n/**\n * The value of the square root of \\f$ \\pi \\f$,\n * \\f$ \\sqrt{\\pi} \\f$.\n */\nstatic constexpr double SQRT_PI = boost::math::constants::root_pi<double>();\n\n/**\n * The value of the square root of \\f$ 2\\pi \\f$,\n * \\f$ \\sqrt{2\\pi} \\f$.\n */\nstatic constexpr double SQRT_TWO_PI\n    = boost::math::constants::root_two_pi<double>();\n\n/**\n * The square root of 2 divided by the square root of \\f$ \\pi \\f$,\n * \\f$ \\sqrt{2} / \\sqrt{\\pi} \\f$.\n */\nstatic constexpr double SQRT_TWO_OVER_SQRT_PI = SQRT_TWO / SQRT_PI;\n\n/**\n * The value of 1 over the square root of 2,\n * \\f$ 1 / \\sqrt{2} \\f$.\n */\nstatic constexpr double INV_SQRT_TWO\n    = boost::math::constants::one_div_root_two<double>();\n\n/**\n * The value of 1 over the square root of \\f$ \\pi \\f$,\n * \\f$ 1 / \\sqrt{\\pi} \\f$.\n */\nstatic constexpr double INV_SQRT_PI\n    = boost::math::constants::one_div_root_pi<double>();\n\n/**\n * The value of 1 over the square root of \\f$ 2\\pi \\f$,\n * \\f$ 1 / \\sqrt{2\\pi} \\f$.\n */\nstatic constexpr double INV_SQRT_TWO_PI\n    = boost::math::constants::one_div_root_two_pi<double>();\n\n/**\n * The value of 2 over the square root of \\f$ \\pi \\f$,\n * \\f$ 2 / \\sqrt{\\pi} \\f$.\n */\nstatic constexpr double TWO_OVER_SQRT_PI\n    = boost::math::constants::two_div_root_pi<double>();\n\n/**\n * The value of half the natural logarithm 2,\n * \\f$ \\log(2) / 2 \\f$.\n */\nstatic constexpr double HALF_LOG_TWO = 0.5 * LOG_TWO;\n\n/**\n * The value of half the natural logarithm \\f$ 2\\pi \\f$,\n * \\f$ \\log(2\\pi) / 2 \\f$.\n */\nconst double HALF_LOG_TWO_PI = 0.5 * LOG_TWO_PI;\n\n/**\n * The value of minus the natural logarithm of the square root of \\f$ 2\\pi \\f$,\n * \\f$ -\\log(\\sqrt{2\\pi}) \\f$.\n */\nconst double NEG_LOG_SQRT_TWO_PI = -std::log(SQRT_TWO_PI);\n\n/**\n * Largest rate parameter allowed in Poisson RNG\n */\nconst double POISSON_MAX_RATE = std::pow(2.0, 30);\n\n/**\n * Return positive infinity.\n *\n * @return Positive infinity.\n */\nstatic constexpr inline double positive_infinity() { return INFTY; }\n\n/**\n * Return negative infinity.\n *\n * @return Negative infinity.\n */\nstatic constexpr inline double negative_infinity() { return NEGATIVE_INFTY; }\n\n/**\n * Return (quiet) not-a-number.\n *\n * @return Quiet not-a-number.\n */\nstatic constexpr inline double not_a_number() { return NOT_A_NUMBER; }\n\n/**\n * Returns the difference between 1.0 and the next value\n * representable.\n *\n * @return Minimum positive number.\n */\nstatic constexpr inline double machine_precision() { return EPSILON; }\n\n/**\n * Returns the natural logarithm of ten.\n *\n * @return Natural logarithm of ten.\n */\nstatic constexpr inline double log10() { return LOG_TEN; }\n\n/**\n * Returns the square root of two.\n *\n * @return Square root of two.\n */\nstatic constexpr inline double sqrt2() { return SQRT_TWO; }\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "e7f483ce7f7daafade3bfd2375afddec04f4a227", "size": 5494, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/constants.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/fun/constants.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/fun/constants.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7966804979, "max_line_length": 80, "alphanum_fraction": 0.6543502002, "num_tokens": 1600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6462383654146713}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2016 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_FORMULAS_GNOMONIC_INTERSECTION_HPP\n#define BOOST_GEOMETRY_FORMULAS_GNOMONIC_INTERSECTION_HPP\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/cs.hpp>\n\n#include <boost/geometry/arithmetic/cross_product.hpp>\n#include <boost/geometry/formulas/gnomonic_spheroid.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace boost { namespace geometry { namespace formula\n{\n\n/*!\n\\brief The intersection of two geodesics using spheroidal gnomonic projection\n       as proposed by Karney.\n\\author See\n    - Charles F.F Karney, Algorithms for geodesics, 2011\n      https://arxiv.org/pdf/1109.4448.pdf\n    - GeographicLib forum thread: Intersection between two geodesic lines\n      https://sourceforge.net/p/geographiclib/discussion/1026621/thread/21aaff9f/\n*/\ntemplate\n<\n    typename CT,\n    template <typename, bool, bool, bool, bool, bool> class Inverse,\n    template <typename, bool, bool, bool, bool> class Direct\n>\nclass gnomonic_intersection\n{\npublic:\n    template <typename T1, typename T2, typename Spheroid>\n    static inline bool apply(T1 const& lona1, T1 const& lata1,\n                             T1 const& lona2, T1 const& lata2,\n                             T2 const& lonb1, T2 const& latb1,\n                             T2 const& lonb2, T2 const& latb2,\n                             CT & lon, CT & lat,\n                             Spheroid const& spheroid)\n    {\n        CT const lon_a1 = lona1;\n        CT const lat_a1 = lata1;\n        CT const lon_a2 = lona2;\n        CT const lat_a2 = lata2;\n        CT const lon_b1 = lonb1;\n        CT const lat_b1 = latb1;\n        CT const lon_b2 = lonb2;\n        CT const lat_b2 = latb2;\n\n        return apply(lon_a1, lat_a1, lon_a2, lat_a2, lon_b1, lat_b1, lon_b2, lat_b2, lon, lat, spheroid);\n    }\n\n    template <typename Spheroid>\n    static inline bool apply(CT const& lona1, CT const& lata1,\n                             CT const& lona2, CT const& lata2,\n                             CT const& lonb1, CT const& latb1,\n                             CT const& lonb2, CT const& latb2,\n                             CT & lon, CT & lat,\n                             Spheroid const& spheroid)\n    {\n        typedef gnomonic_spheroid<CT, Inverse, Direct> gnom_t;\n\n        lon = (lona1 + lona2 + lonb1 + lonb2) / 4;\n        lat = (lata1 + lata2 + latb1 + latb2) / 4;\n        // TODO: consider normalizing lon\n\n        for (int i = 0; i < 10; ++i)\n        {\n            CT xa1, ya1, xa2, ya2;\n            CT xb1, yb1, xb2, yb2;\n            CT x, y;\n            double lat1, lon1;\n\n            bool ok = gnom_t::forward(lon, lat, lona1, lata1, xa1, ya1, spheroid)\n                   && gnom_t::forward(lon, lat, lona2, lata2, xa2, ya2, spheroid)\n                   && gnom_t::forward(lon, lat, lonb1, latb1, xb1, yb1, spheroid)\n                   && gnom_t::forward(lon, lat, lonb2, latb2, xb2, yb2, spheroid)\n                   && intersect(xa1, ya1, xa2, ya2, xb1, yb1, xb2, yb2, x, y)\n                   && gnom_t::inverse(lon, lat, x, y, lon1, lat1, spheroid);\n\n            if (! ok)\n            {\n                return false;\n            }\n\n            if (math::equals(lat1, lat) && math::equals(lon1, lon))\n            {\n                break;\n            }\n\n            lat = lat1;\n            lon = lon1;\n        }\n\n        // NOTE: true is also returned if the number of iterations is too great\n        //       which means that the accuracy of the result is low\n        return true;\n    }\n\nprivate:\n    static inline bool intersect(CT const& xa1, CT const& ya1, CT const& xa2, CT const& ya2,\n                                 CT const& xb1, CT const& yb1, CT const& xb2, CT const& yb2,\n                                 CT & x, CT & y)\n    {\n        typedef model::point<CT, 3, cs::cartesian> v3d_t;\n\n        CT const c0 = 0;\n        CT const c1 = 1;\n\n        v3d_t const va1(xa1, ya1, c1);\n        v3d_t const va2(xa2, ya2, c1);\n        v3d_t const vb1(xb1, yb1, c1);\n        v3d_t const vb2(xb2, yb2, c1);\n\n        v3d_t const la = cross_product(va1, va2);\n        v3d_t const lb = cross_product(vb1, vb2);\n        v3d_t const p = cross_product(la, lb);\n\n        CT const z = get<2>(p);\n\n        if (math::equals(z, c0))\n        {\n            // degenerated or collinear segments\n            return false;\n        }\n\n        x = get<0>(p) / z;\n        y = get<1>(p) / z;\n\n        return true;\n    }\n};\n\n}}} // namespace boost::geometry::formula\n\n\n#endif // BOOST_GEOMETRY_FORMULAS_GNOMONIC_INTERSECTION_HPP\n", "meta": {"hexsha": "33c2fe62b610f78a0af2d5f8c63e511adda558e9", "size": 4881, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/gnomonic_intersection.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/gnomonic_intersection.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/gnomonic_intersection.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 32.7583892617, "max_line_length": 105, "alphanum_fraction": 0.5666871543, "num_tokens": 1419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.646238356315639}}
{"text": "/*\n * StokesM2L.cpp\n *\n *  Created on: Oct 12, 2016\n *      Author: wyan\n */\n\n#include \"SVD_pvfmm.hpp\"\n\n#include <Eigen/Dense>\n\n#include <iomanip>\n#include <iostream>\n\n#define DIRECTLAYER 2\n#define PI314 (3.1415926535897932384626433)\n\nnamespace Stokes2D3D {\n\ninline double ERFC(double x) { return std::erfc(x); }\ninline double ERF(double x) { return std::erf(x); }\n\n/*\n * def AEW(xi,rvec):\n r=np.sqrt(rvec.dot(rvec))\n A = 2*(xi*np.exp(-(xi**2)*(r**2))/(np.sqrt(np.pi)*r**2)+ss.erfc(xi*r)/(2*r**3))\n *(r*r*np.identity(3)+np.outer(rvec,rvec)) -\n 4*xi/np.sqrt(np.pi)*np.exp(-(xi**2)*(r**2))*np.identity(3)\n return A\n *\n * */\ninline Eigen::Matrix3d AEW(const double xi, const Eigen::Vector3d &rvec) {\n    const double r = rvec.norm();\n    Eigen::Matrix3d A =\n        2 *\n            (xi * exp(-(xi * xi) * (r * r)) / (sqrt(PI314) * r * r) +\n             erfc(xi * r) / (2 * r * r * r)) *\n            (r * r * Eigen::Matrix3d::Identity() + (rvec * rvec.transpose())) -\n        4 * xi / sqrt(PI314) * exp(-(xi * xi) * (r * r)) *\n            Eigen::Matrix3d::Identity();\n    return A;\n}\n\ninline double lbda(double k, double xi, double z) {\n    return exp(-k * k / (4 * xi * xi) - (xi * xi) * (z * z));\n}\n\ninline double thetaplus(double k, double xi, double z) {\n    return exp(k * z) * ERFC(k / (2 * xi) + xi * z);\n}\n\ninline double thetaminus(double k, double xi, double z) {\n    return exp(-k * z) * ERFC(k / (2 * xi) - xi * z);\n}\n\ninline double J00(double k, double xi, double z) {\n    return sqrt(PI314) * lbda(k, xi, z) * xi;\n}\n\ninline double J10(double k, double xi, double z) {\n    return PI314 * (thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (4 * k);\n}\n\ninline double J20(double k, double xi, double z) {\n    return sqrt(PI314) * lbda(k, xi, z) / (4 * k * k * xi) +\n           PI314 *\n               ((thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (8 * k * k * k) +\n                (thetaminus(k, xi, z) - thetaplus(k, xi, z)) * z / (8 * k * k) -\n                (thetaplus(k, xi, z) + thetaminus(k, xi, z)) /\n                    (16 * k * (xi * xi)));\n}\n\ninline double J12(double k, double xi, double z) {\n    return PI314 * (-thetaplus(k, xi, z) - thetaminus(k, xi, z)) * k / 4 +\n           sqrt(PI314) * lbda(k, xi, z) * xi;\n}\n\ninline double J22(double k, double xi, double z) {\n    return PI314 * ((thetaplus(k, xi, z) + thetaminus(k, xi, z)) * k /\n                        (16 * xi * xi) +\n                    (thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (8 * k) +\n                    (thetaplus(k, xi, z) - thetaminus(k, xi, z)) * z / 8) -\n           sqrt(PI314) * lbda(k, xi, z) / (4 * xi);\n}\n\ninline double K11(double k, double xi, double z) {\n    return PI314 * ((thetaminus(k, xi, z) - thetaplus(k, xi, z))) / 4;\n}\n\ninline double K12(double k, double xi, double z) {\n    return PI314 *\n           ((thetaplus(k, xi, z) - thetaminus(k, xi, z)) / (16 * xi * xi) +\n            (thetaminus(k, xi, z) + thetaplus(k, xi, z)) * z / (8 * k));\n}\n\ninline void QI(const Eigen::Vector3d &kvec, double xi, double z,\n               Eigen::Matrix3d &QI) {\n    // 3*3 tensor\n    // kvec: np.array([k1,k2,0])\n    double knorm = sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1]);\n    QI = 2 * (J00(knorm, xi, z) / (4 * xi * xi) + J10(knorm, xi, z)) *\n         Eigen::Matrix3d::Identity();\n}\n\ninline void Qkk(const Eigen::Vector3d &kvec, double xi, double z,\n                Eigen::Matrix3d &Qreal, Eigen::Matrix3d &Qimg) {\n    double k1 = kvec[0];\n    double k2 = kvec[1];\n    double knorm = sqrt(k1 * k1 + k2 * k2);\n    auto j10 = J10(knorm, xi, z);\n    auto j20 = J20(knorm, xi, z);\n    auto j12 = J12(knorm, xi, z);\n    auto j22 = J22(knorm, xi, z);\n\n    auto k11 = K11(knorm, xi, z);\n    auto k12 = K12(knorm, xi, z);\n    Qreal.setZero();\n    Qreal(0, 0) = k1 * k1;\n    Qreal(1, 1) = k2 * k2;\n    Qreal(0, 1) = k1 * k2;\n    Qreal(1, 0) = k1 * k2;\n\n    Qreal *= (j10 / (4 * (xi * xi)) + j20);\n    Qreal(2, 2) = (j12 / (4 * xi * xi) + j22);\n    Qreal *= -2;\n\n    Qimg.setZero();\n    Qimg(0, 2) = k1;\n    Qimg(1, 2) = k2;\n    Qimg(2, 0) = k1;\n    Qimg(2, 1) = k2;\n    // Qimg=np.array([[0,0,k1],[0,0,k2],[k1,k2,0]])*( k11/(4*xi**2) + k12 )\n    Qimg *= (k11 / (4 * xi * xi) + k12);\n    Qimg *= -2;\n}\n\n// inline Eigen::Matrix3d uFk0(double xi, double zmn) {\n//\tEigen::Matrix3d wavek0;\n//\twavek0 = -(4.0 / 1) * (PI314 * (zmn) * ERF(zmn * xi) + sqrt(PI314) / (2\n//* xi) * exp(-zmn * zmn * xi * xi));\n//\treturn wavek0;\n//\n//}\n\ninline void GkernelEwald(const Eigen::Vector3d &rvecIn, Eigen::Matrix3d &Gsum) {\n    const double xi = 2;\n    Eigen::Vector3d rvec = rvecIn;\n    rvec[0] = rvec[0] - floor(rvec[0]);\n    rvec[1] = rvec[1] - floor(rvec[1]); // reset to a periodic cell\n\n    const double r = rvec.norm();\n    Eigen::Matrix3d real = Eigen::Matrix3d::Zero();\n    const int N = 5;\n    if (r < 1e-14) {\n        auto Gself = -4 * xi / sqrt(PI314) *\n                     Eigen::Matrix3d::Identity(); // the self term\n        for (int i = -N; i < N + 1; i++) {\n            for (int j = -N; j < N + 1; j++) {\n                if (i == 0 && j == 0) {\n                    continue;\n                }\n                real = real + AEW(xi, rvec + Eigen::Vector3d(i, j, 0));\n            }\n        }\n        real += Gself;\n    } else {\n        for (int i = -N; i < N + 1; i++) {\n            for (int j = -N; j < N + 1; j++) {\n                real = real + AEW(xi, rvec + Eigen::Vector3d(i, j, 0));\n            }\n        }\n    }\n\n    // k\n    Eigen::Matrix3d wave = Eigen::Matrix3d::Zero();\n\n    double zmn = rvec[2];\n    Eigen::Vector3d rhomn = rvec;\n    rhomn[2] = 0;\n    Eigen::Matrix3d Qreal;\n    Eigen::Matrix3d Qimg;\n    Eigen::Matrix3d QImat;\n    for (int i = -N; i < N + 1; i++) {\n        for (int j = -N; j < N + 1; j++) {\n            Eigen::Vector3d kvec(2 * PI314 * i, 2 * PI314 * j, 0);\n            if (i == 0 and j == 0) {\n                continue;\n            }\n            Qkk(kvec, xi, zmn, Qreal, Qimg);\n            QI(kvec, xi, zmn, QImat);\n            wave = wave + (QImat + Qreal) * cos(kvec.dot(rhomn)) -\n                   (Qimg)*sin(kvec.dot(rhomn));\n        }\n    }\n    wave *= 4;\n\n    // k=0\n    Eigen::Matrix3d waveK0;\n    waveK0.setZero();\n    /*\n     *   I2fn=force\n     I2fn[2]=0\n     wavek0=-(4/1)*(np.pi*(zmn)*ss.erf(zmn*xi)+np.sqrt(np.pi)/(2*xi)*np.exp(-zmn**2*xi**2))*I2fn\n     *\n     * */\n    waveK0 = -(4 / 1.0) *\n             (PI314 * (zmn)*ERF(zmn * xi) +\n              sqrt(PI314) / (2 * xi) * exp(-zmn * zmn * xi * xi)) *\n             Eigen::Matrix3d::Identity();\n    waveK0(2, 2) = 0;\n\n    Gsum = real + wave + waveK0;\n}\n\ninline void Gkernel(const Eigen::Vector3d &target,\n                    const Eigen::Vector3d &source, Eigen::Matrix3d &answer) {\n    auto rst = target - source;\n    double rnorm = rst.norm();\n    if (rnorm < 1e-14) {\n        answer = Eigen::Matrix3d::Zero();\n        return;\n    }\n    auto part2 = rst * rst.transpose() / (rnorm * rnorm * rnorm);\n    auto part1 = Eigen::Matrix3d::Identity() / rnorm;\n    answer = part1 + part2;\n}\n\n// Out of Layer 1\ninline void GkernelEwaldO1(const Eigen::Vector3d &rvec,\n                           Eigen::Matrix3d &GsumO1) {\n    Eigen::Matrix3d Gfree = Eigen::Matrix3d::Zero();\n    GkernelEwald(rvec, GsumO1);\n    const int N = DIRECTLAYER;\n    for (int i = -N; i < N + 1; i++) {\n        for (int j = -N; j < N + 1; j++) {\n            Gkernel(rvec, Eigen::Vector3d(i, j, 0), Gfree);\n            GsumO1 -= Gfree;\n        }\n    }\n}\n\n/**\n * \\brief Returns the coordinates of points on the surface of a cube.\n * \\param[in] p Number of points on an edge of the cube is (n+1)\n * \\param[in] c Coordinates to the centre of the cube (3D array).\n * \\param[in] alpha Scaling factor for the size of the cube.\n * \\param[in] depth Depth of the cube in the octree.\n * \\return Vector with coordinates of points on the surface of the cube in the\n * format [x0 y0 z0 x1 y1 z1 .... ].\n */\n\ntemplate <class Real_t>\nstd::vector<Real_t> surface(int p, Real_t *c, Real_t alpha, int depth) {\n    size_t n_ = (6 * (p - 1) * (p - 1) + 2); // Total number of points.\n\n    std::vector<Real_t> coord(n_ * 3);\n    coord[0] = coord[1] = coord[2] = -1.0;\n    size_t cnt = 1;\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = -1.0;\n            coord[cnt * 3 + 1] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = (2.0 * j - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * i - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = -1.0;\n            coord[cnt * 3 + 2] = (2.0 * (j + 1) - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = (2.0 * j - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = -1.0;\n            cnt++;\n        }\n    for (size_t i = 0; i < (n_ / 2) * 3; i++)\n        coord[cnt * 3 + i] = -coord[i];\n\n    Real_t r = 0.5 * pow(0.5, depth);\n    Real_t b = alpha * r;\n    for (size_t i = 0; i < n_; i++) {\n        coord[i * 3 + 0] = (coord[i * 3 + 0] + 1.0) * b + c[0];\n        coord[i * 3 + 1] = (coord[i * 3 + 1] + 1.0) * b + c[1];\n        coord[i * 3 + 2] = (coord[i * 3 + 2] + 1.0) * b + c[2];\n    }\n    return coord;\n}\n\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n    Eigen::setNbThreads(1);\n    const int pEquiv = atoi(argv[1]); // (8-1)^2*6 + 2 points\n    const int pCheck = atoi(argv[1]);\n    const double scaleEquiv = 1.05;\n    const double scaleCheck = 2.95;\n    const double pCenterEquiv[3] = {\n        -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2};\n    const double pCenterCheck[3] = {\n        -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2};\n\n    const double scaleLEquiv = 1.05;\n    const double scaleLCheck = 2.95;\n    const double pCenterLEquiv[3] = {\n        -(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2};\n    const double pCenterLCheck[3] = {\n        -(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2};\n\n    auto pointMEquiv = surface(\n        pEquiv, (double *)&(pCenterEquiv[0]), scaleEquiv,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointMCheck = surface(\n        pCheck, (double *)&(pCenterCheck[0]), scaleCheck,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    auto pointLEquiv = surface(\n        pEquiv, (double *)&(pCenterLCheck[0]), scaleLCheck,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointLCheck = surface(\n        pCheck, (double *)&(pCenterLEquiv[0]), scaleLEquiv,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    //\tfor (int i = 0; i < pointLEquiv.size() / 3; i++) {\n    //\t\tstd::cout << pointLEquiv[3 * i] << \" \" << pointLEquiv[3 * i + 1]\n    //<< \" \" << pointLEquiv[3 * i + 2] << \" \"\n    //\t\t\t\t<< std::endl;\n    //\t}\n    //\n    //\tfor (int i = 0; i < pointLCheck.size() / 3; i++) {\n    //\t\tstd::cout << pointLCheck[3 * i] << \" \" << pointLCheck[3 * i + 1]\n    //<< \" \" << pointLCheck[3 * i + 2] << \" \"\n    //\t\t\t\t<< std::endl;\n    //\t}\n\n    // const int imageN = 100; // images to sum\n    // calculate the operator M2L with least square\n    const int equivN = pointMEquiv.size() / 3;\n    const int checkN = pointLCheck.size() / 3;\n    Eigen::MatrixXd M2L(3 * equivN, 3 * equivN);\n    Eigen::MatrixXd A(3 * checkN, 3 * equivN);\n#pragma omp parallel for\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Matrix3d G = Eigen::Matrix3d::Zero();\n        Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1],\n                               pointLCheck[3 * k + 2]);\n        for (int l = 0; l < equivN; l++) {\n            const Eigen::Vector3d Lpoint(pointLEquiv[3 * l],\n                                         pointLEquiv[3 * l + 1],\n                                         pointLEquiv[3 * l + 2]);\n            Gkernel(Cpoint, Lpoint, G);\n            A.block<3, 3>(3 * k, 3 * l) = G;\n        }\n    }\n    Eigen::MatrixXd ApinvU(A.cols(), A.rows());\n    Eigen::MatrixXd ApinvVT(A.cols(), A.rows());\n    pinv(A, ApinvU, ApinvVT);\n\n#pragma omp parallel for\n    for (int i = 0; i < equivN; i++) {\n        const Eigen::Vector3d Mpoint(pointMEquiv[3 * i], pointMEquiv[3 * i + 1],\n                                     pointMEquiv[3 * i + 2]);\n        //\t\tstd::cout<<\"debug:\"<<Mpoint<<std::endl;\n        // assemble linear system\n        Eigen::MatrixXd f(3 * checkN, 3);\n        for (int k = 0; k < checkN; k++) {\n            Eigen::Matrix3d temp = Eigen::Matrix3d::Zero();\n            Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1],\n                                   pointLCheck[3 * k + 2]);\n            //\t\t\tstd::cout<<\"debug:\"<<k<<std::endl;\n            // sum the images\n            // use 3D Ewald subtract the first layer\n            GkernelEwaldO1(Cpoint - Mpoint, temp);\n            f.block<3, 3>(3 * k, 0) = temp;\n        }\n\n        M2L.block(0, 3 * i, 3 * equivN, 3) =\n            (ApinvU.transpose() * (ApinvVT.transpose() * f));\n    }\n\n    // dump M2L\n    for (int i = 0; i < 3 * equivN; i++) {\n        for (int j = 0; j < 3 * equivN; j++) {\n            std::cout << i << \" \" << j << \" \" << std::scientific\n                      << std::setprecision(18) << M2L(i, j) << std::endl;\n        }\n    }\n\n    /*\n     * pointForce=[(np.array([1.0,0,0]),np.array([0.1,0.55,0.2]))\n     ,(np.array([-1.0,1.0,1.0]),np.array([0.5,0.1,0.3]))\n     ,(np.array([0.0,0.0,-1.0]),np.array([0.8,0.5,0.7]))]\n     * */\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>\n        forcePoint(3);\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>\n        forceValue(3);\n    forcePoint[0] = Eigen::Vector3d(0.1, 0.5, 0.5);\n    forceValue[0] = Eigen::Vector3d(1, 0, 0);\n    forcePoint[1] = Eigen::Vector3d(0.9, 0.5, 0.5);\n    forceValue[1] = Eigen::Vector3d(-1, 0, 0);\n    forcePoint[2] = Eigen::Vector3d(0.0, 0.0, 0.0);\n    forceValue[2] = Eigen::Vector3d(0, 0, 0);\n\n    // solve M\n    A.resize(3 * checkN, 3 * equivN);\n    ApinvU.resize(A.cols(), A.rows());\n    ApinvVT.resize(A.cols(), A.rows());\n    Eigen::VectorXd f(3 * checkN);\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Vector3d temp = Eigen::Vector3d::Zero();\n        Eigen::Matrix3d G = Eigen::Matrix3d::Zero();\n        Eigen::Vector3d Cpoint(pointMCheck[3 * k], pointMCheck[3 * k + 1],\n                               pointMCheck[3 * k + 2]);\n        for (size_t p = 0; p < forcePoint.size(); p++) {\n            Gkernel(Cpoint, forcePoint[p], G);\n            temp = temp + G * (forceValue[p]);\n        }\n        f.block<3, 1>(3 * k, 0) = temp;\n        for (int l = 0; l < equivN; l++) {\n            Eigen::Vector3d Mpoint(pointMEquiv[3 * l], pointMEquiv[3 * l + 1],\n                                   pointMEquiv[3 * l + 2]);\n            Gkernel(Cpoint, Mpoint, G);\n            A.block<3, 3>(3 * k, 3 * l) = G;\n        }\n    }\n    pinv(A, ApinvU, ApinvVT);\n    Eigen::VectorXd Msource = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n    // impose net charge equal\n    double fx = 0, fy = 0, fz = 0;\n    for (int i = 0; i < equivN; i++) {\n        fx += Msource[3 * i];\n        fy += Msource[3 * i + 1];\n        fz += Msource[3 * i + 2];\n    }\n    std::cout << \"fx svd before correction: \" << fx << std::endl;\n    std::cout << \"fy svd before correction: \" << fy << std::endl;\n    std::cout << \"fz svd before correction: \" << fz << std::endl;\n    double fnetx = 0;\n    double fnety = 0;\n    double fnetz = 0;\n    for (size_t p = 0; p < forcePoint.size(); p++) {\n        fnetx += (forceValue[p][0]);\n        fnety += (forceValue[p][1]);\n        fnetz += (forceValue[p][2]);\n    }\n\n    std::cout << \"Msource: \" << Msource << std::endl;\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>\n        forcePointExt(0);\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>\n        forceValueExt(0);\n    for (size_t p = 0; p < forcePoint.size(); p++) {\n        for (int i = -DIRECTLAYER; i < DIRECTLAYER + 1; i++) {\n            for (int j = -DIRECTLAYER; j < DIRECTLAYER + 1; j++) {\n                forcePointExt.push_back(Eigen::Vector3d(i, j, 0) +\n                                        forcePoint[p]);\n                forceValueExt.push_back(forceValue[p]);\n            }\n        }\n    }\n\n    Eigen::VectorXd M2Lsource = M2L * (Msource);\n\n    Eigen::Vector3d samplePoint(0.4, 0.5, 0.5);\n    Eigen::Vector3d Usample(0, 0, 0);\n    Eigen::Vector3d UsampleSP(0, 0, 0);\n    Eigen::Matrix3d G;\n    for (size_t p = 0; p < forcePointExt.size(); p++) {\n        Gkernel(samplePoint, forcePointExt[p], G);\n        Usample = Usample + G * (forceValueExt[p]);\n    }\n    std::cout << \"Usample Direct:\" << Usample << std::endl;\n    for (int p = 0; p < equivN; p++) {\n        Eigen::Vector3d Lpoint(pointLEquiv[3 * p], pointLEquiv[3 * p + 1],\n                               pointLEquiv[3 * p + 2]);\n        Eigen::Vector3d Fpoint(M2Lsource[3 * p], M2Lsource[3 * p + 1],\n                               M2Lsource[3 * p + 2]);\n        Gkernel(samplePoint, Lpoint, G);\n        UsampleSP = UsampleSP + G * (Fpoint);\n    }\n\n    std::cout << \"Usample M2L:\" << UsampleSP << std::endl;\n    std::cout << \"Usample M2L total:\" << UsampleSP + Usample << std::endl;\n\n    Eigen::Vector3d UsampleDirect = 0 * Usample;\n    for (size_t p = 0; p < forcePoint.size(); p++) {\n        GkernelEwald(samplePoint - forcePoint[p], G);\n        UsampleDirect += G * (forceValue[p]);\n    }\n    std::cout << \"Usample Ewald:\" << UsampleDirect << std::endl;\n\n    std::cout << \"error\" << UsampleSP + Usample - UsampleDirect << std::endl;\n\n    return 0;\n}\n\n} // namespace Stokes2D3D\n\n#undef DIRECTLAYER\n#undef PI314\n", "meta": {"hexsha": "28e34ea7b98878317102b00496f96192349ea4ef", "size": 17858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2LStokes/src/Stokes2D3D.cpp", "max_stars_repo_name": "blackwer/PeriodicFMM", "max_stars_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-06-14T02:07:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T04:41:34.000Z", "max_issues_repo_path": "M2LStokes/src/Stokes2D3D.cpp", "max_issues_repo_name": "blackwer/PeriodicFMM", "max_issues_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "M2LStokes/src/Stokes2D3D.cpp", "max_forks_repo_name": "blackwer/PeriodicFMM", "max_forks_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:30:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T20:26:36.000Z", "avg_line_length": 35.3623762376, "max_line_length": 96, "alphanum_fraction": 0.4967521559, "num_tokens": 6415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6462169743185256}}
{"text": "#include \"../include/Jabc.hpp\"\n#include <armadillo>\n#include <iostream>\n#include <cmath>\n\n\nusing namespace std;\nusing namespace arma;\n\n\nvoid transform_xlogx_mat(cx_mat &X)\n{\n  cx_mat U, V;\n  vec s, sp;\n\n  svd_econ(U, s, V, X);\n\n  sp = s;\n\n  for (int i=0; i<s.size(); i++)\n    {\n      sp(i) = -2.0*s(i) * log(s(i));\n    }\n\n  transform_xlogx_vec(s);\n  X = U * diagmat(s) * V.t();\n}\n\nvoid transform_xlogx_vec(vec &s)\n{\n  for (int i=0; i<s.size(); i++)\n    {\n      s(i) = -2.0*s(i) * log(s(i));\n    }\n}\n\nint log2_int(int n)\n{\n  int k=-1;\n  while (n>0)\n    {\n      n/=2;\n      k++;\n    }\n  return k;\n}\n\n// |\\psi\\rangle \\to K_X|\\psi\\rangle, where X is the first k qubits.\n// (Note that this is equal to K_{\\bar{X}})|\\psi\\rangle).\n// n: Number of qubits\n// Input format: psi should be a column vector.\nvoid apply_modular_op(int k, int n, cx_mat &psi)\n{\n  psi.reshape(1<<k, 1<<(n-k));\n  transform_xlogx_mat(psi);\n  psi.reshape(1<<n,1);\n}\n\n\n// Given |\\psi>_{ABCD}, return \\log \\rho_{AB} |\\psi>_{ABCD}\n// a, b, c: Number of bits in A, B, C.\n// Format: First a bits are A. Next b bits are B. The next c bits are C.\nvoid transform_ab(int a, int b, int c, cx_mat &psi)\n{\n  int dim = psi.size();\n  int n = log2_int(dim);\n  apply_modular_op(a+b, n, psi);\n}\n\n// Given |\\psi>_{ABCD}, return \\log \\rho_{BC} |\\psi>_{ABCD}\n// a, b, c: Number of bits in A, B, C.\n// Format: First a bits are A. Next b bits are B. The next c bits are C.\nvoid transform_bc(int a, int b, int c, cx_mat &psi)\n{\n  int dim = psi.size();\n  int n = log2_int(dim);\n  psi.reshape(1<<a, 1<<(n-a));\n  psi = psi.st();\n  psi.reshape(1<<n,1);\n  apply_modular_op(b+c, n, psi);\n  psi.reshape(1<<(n-a), 1<<a);\n  psi = psi.st();\n  psi.reshape(1<<n,1);\n}\n\n\ndouble Jabc(int a, int b, int c, cx_mat &psi)\n{\n  cx_mat psi_cpy = psi;\n\n  transform_ab(a,b,c,psi);  \n  transform_bc(a,b,c,psi_cpy);\n  \n  cx_mat result = psi_cpy.t() * psi;\n\n  cout << \"result\" << endl;\n  cout << result << endl;\n  \n  cx_double inner_product = result(0,0);\n  return inner_product.imag() / 2;  \n}\n", "meta": {"hexsha": "875066dd14db94dab8b50704c67575b75fb676f6", "size": 2010, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Jabc.cpp", "max_stars_repo_name": "ikim-quantum/Jabc", "max_stars_repo_head_hexsha": "e98278ecb5daa7f239daadf573a2de36997aa644", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Jabc.cpp", "max_issues_repo_name": "ikim-quantum/Jabc", "max_issues_repo_head_hexsha": "e98278ecb5daa7f239daadf573a2de36997aa644", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Jabc.cpp", "max_forks_repo_name": "ikim-quantum/Jabc", "max_forks_repo_head_hexsha": "e98278ecb5daa7f239daadf573a2de36997aa644", "max_forks_repo_licenses": ["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.7058823529, "max_line_length": 72, "alphanum_fraction": 0.584079602, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6462102561755216}}
{"text": "#include <Eigen/Dense>\n#include <map>\n\nnamespace costmap\n{\n\nstruct TerrainData\n{\n    Eigen::Vector3d meanPosition;\n    Eigen::Vector3d centroidPosition;\n    Eigen::Vector3d normal;\n    double curvature;\n    Eigen::Matrix3d covarianceMatrix;\n    std::map<std::pair<double, double>, double> heightMap;\n    std::map<double, std::map<double, double>> costMap;\n    double minHeight;\n    double resolution;\n};\n}", "meta": {"hexsha": "c7a88139057970c042e5c33f29cdaa16264465a9", "size": 405, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/data.hpp", "max_stars_repo_name": "RajPShinde/footstep_affordance", "max_stars_repo_head_hexsha": "6e8863c098fc4f6e789e0eee56adcee5df061454", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-23T04:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T11:39:30.000Z", "max_issues_repo_path": "include/data.hpp", "max_issues_repo_name": "RajPShinde/footstep_affordance", "max_issues_repo_head_hexsha": "6e8863c098fc4f6e789e0eee56adcee5df061454", "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/data.hpp", "max_forks_repo_name": "RajPShinde/footstep_affordance", "max_forks_repo_head_hexsha": "6e8863c098fc4f6e789e0eee56adcee5df061454", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T13:43:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T06:13:57.000Z", "avg_line_length": 21.3157894737, "max_line_length": 58, "alphanum_fraction": 0.7037037037, "num_tokens": 101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6462102533054328}}
{"text": "//\n//  cal_ke.hpp\n//  hybrid_fem_bie\n//\n//  Created by Max on 2/7/18.\n//\n//\n\n#ifndef cal_ke_hpp\n#define cal_ke_hpp\n\n#include <stdio.h>\n#include <Eigen/Eigen>\n\nusing namespace Eigen;\n\nvoid cal_ke(MatrixXd coord ,double E, double nu, MatrixXd &ke);\n\n#endif /* cal_ke_hpp */\n", "meta": {"hexsha": "cc4ad0bf297e007efb93262b5782dbcd809098f2", "size": 272, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fem/cal_ke.hpp", "max_stars_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_stars_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "src/fem/cal_ke.hpp", "max_issues_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_issues_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fem/cal_ke.hpp", "max_forks_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_forks_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 13.6, "max_line_length": 63, "alphanum_fraction": 0.6801470588, "num_tokens": 80, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.899121366457407, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6461035667583647}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_PREC_RNG_HPP\r\n#define STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_PREC_RNG_HPP\r\n\r\n#include <stan/math/prim/meta.hpp>\r\n#include <stan/math/prim/mat/err/check_pos_definite.hpp>\r\n#include <stan/math/prim/mat/err/check_symmetric.hpp>\r\n#include <stan/math/prim/mat/fun/Eigen.hpp>\r\n#include <stan/math/prim/scal/err/check_finite.hpp>\r\n#include <stan/math/prim/scal/err/check_positive.hpp>\r\n#include <boost/random/normal_distribution.hpp>\r\n#include <boost/random/variate_generator.hpp>\r\n\r\nnamespace stan {\r\nnamespace math {\r\n\r\n/**\r\n * Return a multivariate normal random variate with the given location\r\n * and precision using the specified random number generator.\r\n *\r\n * mu can be either an Eigen::VectorXd, an Eigen::RowVectorXd, or a\r\n * std::vector of either of those types.\r\n *\r\n * @tparam T_loc Type of location paramater\r\n * @tparam RNG Type of pseudo-random number generator\r\n * @param mu (Sequence of) location parameter(s)\r\n * @param S Precision matrix\r\n * @param rng random number generator\r\n * @throw std::domain_error if S is not positive definite, or\r\n * std::invalid_argument if the length of (each) mu is not equal to\r\n * the number of rows and columns in S\r\n */\r\ntemplate <typename T_loc, class RNG>\r\ninline typename StdVectorBuilder<true, Eigen::VectorXd, T_loc>::type\r\nmulti_normal_prec_rng(const T_loc &mu, const Eigen::MatrixXd &S, RNG &rng) {\r\n  using boost::normal_distribution;\r\n  using boost::variate_generator;\r\n\r\n  static const char *function = \"multi_normal_prec_rng\";\r\n\r\n  check_positive(function, \"Precision matrix rows\", S.rows());\r\n  check_finite(function, \"Precision matrix\", S);\r\n  check_symmetric(function, \"Precision matrix\", S);\r\n\r\n  Eigen::LLT<Eigen::MatrixXd> llt_of_S = S.llt();\r\n  check_pos_definite(function, \"precision matrix argument\", llt_of_S);\r\n\r\n  vector_seq_view<T_loc> mu_vec(mu);\r\n  check_positive(function, \"number of location parameter vectors\",\r\n                 mu_vec.size());\r\n  size_t size_mu = mu_vec[0].size();\r\n\r\n  size_t N = mu_vec.size();\r\n\r\n  for (size_t i = 1; i < N; i++) {\r\n    int size_mu_new = mu_vec[i].size();\r\n    check_size_match(function,\r\n                     \"Size of one of the vectors of \"\r\n                     \"the location variable\",\r\n                     size_mu_new,\r\n                     \"Size of another vector of the \"\r\n                     \"location variable\",\r\n                     size_mu);\r\n  }\r\n\r\n  for (size_t i = 0; i < N; i++) {\r\n    check_finite(function, \"Location parameter\", mu_vec[i]);\r\n  }\r\n\r\n  check_size_match(function, \"Rows of location parameter\", size_mu, \"Rows of S\",\r\n                   S.rows());\r\n\r\n  StdVectorBuilder<true, Eigen::VectorXd, T_loc> output(N);\r\n\r\n  variate_generator<RNG &, normal_distribution<>> std_normal_rng(\r\n      rng, normal_distribution<>(0, 1));\r\n\r\n  for (size_t n = 0; n < N; ++n) {\r\n    Eigen::VectorXd z(S.cols());\r\n    for (int i = 0; i < S.cols(); i++)\r\n      z(i) = std_normal_rng();\r\n\r\n    output[n] = Eigen::VectorXd(mu_vec[n]) + llt_of_S.matrixU().solve(z);\r\n  }\r\n\r\n  return output.data();\r\n}\r\n\r\n}  // namespace math\r\n}  // namespace stan\r\n#endif\r\n", "meta": {"hexsha": "241cd8fda7f5c03f59f7136ca1325baf92064849", "size": 3123, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/math/prim/mat/prob/multi_normal_prec_rng.hpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "src/stan/math/prim/mat/prob/multi_normal_prec_rng.hpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "src/stan/math/prim/mat/prob/multi_normal_prec_rng.hpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3186813187, "max_line_length": 81, "alphanum_fraction": 0.6634646174, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6460948668117195}}
{"text": "#include \"MeshMorph.h\"\n#include <cstring>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace boost::numeric::ublas;\n\n#define RBF_KERNEL RBF_multiquadric\n//#define RBF_KERNEL RBF_inv_quadric\n//#define RBF_KERNEL RBF_inv_multiquadric\n\n /* Matrix inversion routine.\n Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */\ntemplate<class T>\nbool InvertMatrix(const matrix<T>& input, matrix<T>& inverse)\n{\n\ttypedef permutation_matrix<std::size_t> pmatrix;\n\n\t// create a working copy of the input\n\tmatrix<T> A(input);\n\n\t// create a permutation matrix for the LU-factorization\n\tpmatrix pm(A.size1());\n\n\t// perform LU-factorization\n\tint res = lu_factorize(A, pm);\n\tif (res != 0)\n\t\treturn false;\n\n\t// create identity matrix of \"inverse\"\n\tinverse.assign(identity_matrix<T> (A.size1()));\n\n\t// backsubstitute to get the inverse\n\tlu_substitute(A, pm, inverse);\n\n\treturn true;\n}\n\n\nMeshMorph::MeshMorph() : Wx(0),Wy(0),Wz(0)\n{\n}\n\n\nMeshMorph::~MeshMorph(void)\n{\n}\n\nvoid MeshMorph::init(float* vertexData_, unsigned short vertexNum_, unsigned short* featureIndices_, unsigned short featureNum_)\n{\n\tvertexNum = vertexNum_;\n\tvertexData = new float[3 * vertexNum];\n\tmemcpy(vertexData, vertexData_, vertexNum * 3 * sizeof(float));\n\tfeatureNum = featureNum_;\n\tfeatureIndices = new unsigned short[featureNum];\n\tmemcpy(featureIndices, featureIndices_, featureNum * sizeof(unsigned short));\n\n\t//std::cout << RBFmInv << std::endl<< std::endl;\n\n\t//unsigned short* indices = new unsigned short[featureNum_];\n\t//for(unsigned short i = 0; i < featureNum_; ++i)\n\t//{\n\t//\tindices[i] = i;\n\t//}\n\t//solveRBF(indices, featureNum_, newFeaturePos_);\t\n\t//delete indices;\n}\n\nfloat MeshMorph::dist2(float* p1, float* p2)\n{\n\treturn (p1[0]-p2[0]) * (p1[0]-p2[0]) + (p1[1]-p2[1]) * (p1[1]-p2[1]) + (p1[2]-p2[2]) * (p1[2]-p2[2]);\n}\n\nvoid  MeshMorph::getMorphedData(float* out, float* newFeaturePos_)\n{\n\tunsigned short* indices = new unsigned short[featureNum];\n\tfor(unsigned short i = 0; i < featureNum; ++i)\n\t{\n\t\tindices[i] = i;\n\t}\n\tsolveRBF(indices, featureNum, newFeaturePos_);\t\n\tdelete indices;\n\tfor(int i = 0; i < vertexNum; ++i)\n\t{\n\t\tout[i*3 + 0] = 0;\n\t\tout[i*3 + 1] = 0;\n\t\tout[i*3 + 2] = 0;\n\t\tfor(int j = 0; j < featureNum; ++j)\n\t\t{\n\t\t\tfloat d2 = dist2(&vertexData[i*3], &vertexData[featureIndices[j]*3]);\n\t\t\tout[i*3 + 0] += RBF_KERNEL(d2, minDist2[j]) * Wx[j];\n\t\t\tout[i*3 + 1] += RBF_KERNEL(d2, minDist2[j]) * Wy[j];\n\t\t\tout[i*3 + 2] += RBF_KERNEL(d2, minDist2[j]) * Wz[j];\n\t\t}\n\t}\n}\n\nvoid MeshMorph::getMorphedData(float* out, unsigned short* vertexIndices, unsigned short vertexNum_, unsigned short* featureIndices_, unsigned short featureNum_, float* newFeaturePos_, bool morphAllVertices)\n{\n\tsolveRBF(featureIndices_, featureNum_, newFeaturePos_);\n\tif(morphAllVertices)\n\t{\n\t\t//Copy all vertex positions\n\t\tmemcpy(out, vertexData, vertexNum * 3 * sizeof(float));\n\t\tfor(int i = 0; i < vertexNum_; ++i)\n\t\t{\n\t\t\tout[vertexIndices[i]*3 + 0] = 0;\n\t\t\tout[vertexIndices[i]*3 + 1] = 0;\n\t\t\tout[vertexIndices[i]*3 + 2] = 0;\n\t\t\tfor(int j = 0; j < featureNum_; ++j)\n\t\t\t{\n\t\t\t\tfloat d2 = dist2(&vertexData[vertexIndices[i]*3], &vertexData[featureIndices[featureIndices_[j]]*3]);\n\t\t\t\tout[vertexIndices[i]*3 + 0] += RBF_KERNEL(d2, minDist2[j]) * Wx[j];\n\t\t\t\tout[vertexIndices[i]*3 + 1] += RBF_KERNEL(d2, minDist2[j]) * Wy[j];\n\t\t\t\tout[vertexIndices[i]*3 + 2] += RBF_KERNEL(d2, minDist2[j]) * Wz[j];\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t//only output the morphed vertices\n\t\tfor(int i = 0; i < vertexNum_; ++i)\n\t\t{\n\t\t\tout[i*3 + 0] = 0;\n\t\t\tout[i*3 + 1] = 0;\n\t\t\tout[i*3 + 2] = 0;\n\t\t\tfor(int j = 0; j < featureNum_; ++j)\n\t\t\t{\n\t\t\t\tfloat d2 = dist2(&vertexData[vertexIndices[i]*3], &vertexData[featureIndices[featureIndices_[j]]*3]);\n\t\t\t\tout[i*3 + 0] += RBF_KERNEL(d2, minDist2[j]) * Wx[j];\n\t\t\t\tout[i*3 + 1] += RBF_KERNEL(d2, minDist2[j]) * Wy[j];\n\t\t\t\tout[i*3 + 2] += RBF_KERNEL(d2, minDist2[j]) * Wz[j];\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid MeshMorph::solveRBF(unsigned short* featureIndices_, unsigned short featureNum_, float* newFeaturePos_)\n{\n\tmatrix<float> RBFm(featureNum_, featureNum_);\n\tminDist2 = new float[featureNum_];\t\n\tfor(int i = 0; i < featureNum_; ++i)\n\t{\n\t\tminDist2[i] = FLT_MAX;\n\t\tfor(int j = 0; j < featureNum_; ++j)\n\t\t{\n\t\t\tfloat d2 = dist2(&vertexData[featureIndices[featureIndices_[i]] * 3], &vertexData[featureIndices[featureIndices_[j]] * 3]);\n\t\t\tRBFm(i, j) = d2;\n\t\t\tif(i != j && d2 < minDist2[i])\n\t\t\t\tminDist2[i] = d2;\n\t\t}\n\t}\n\t//std::cout << RBFm << std::endl << std::endl;\n\tfor(int i = 0; i < featureNum_; ++i)\n\t{\n\t\tfor(int j = 0; j < featureNum_; ++j)\n\t\t{\n\t\t\tRBFm(i, j) = RBF_KERNEL(RBFm(i, j), minDist2[i]);\n\t\t}\n\t}\n\n\t//std::cout << RBFm << std::endl<< std::endl;\n\n\tRBFmInv.resize(featureNum_, featureNum_);\n\t\n\tInvertMatrix(RBFm, RBFmInv);\n\n\tif(Wx != 0) delete Wx;\n\tif(Wy != 0) delete Wy;\n\tif(Wz != 0) delete Wz;\n\tWx = new float[featureNum_];\n\tWy = new float[featureNum_];\n\tWz = new float[featureNum_];\n\n\tfor(int i = 0; i < featureNum_; ++i)\n\t{\n\t\tWx[i] = 0;\n\t\tWy[i] = 0;\n\t\tWz[i] = 0;\n\t\tfor(int j = 0; j < featureNum_; ++j)\n\t\t{\n\t\t\tWx[i] += RBFmInv(j,i) * newFeaturePos_[featureIndices_[j]*3];\n\t\t\tWy[i] += RBFmInv(j,i) * newFeaturePos_[featureIndices_[j]*3+1];\n\t\t\tWz[i] += RBFmInv(j,i) * newFeaturePos_[featureIndices_[j]*3+2];\n\t\t}\n\t}\n}\n\ninline float MeshMorph::RBF_multiquadric(float dist2, float eps)\n{\n\treturn sqrt(eps + dist2);\n}\ninline float MeshMorph::RBF_inv_quadric(float dist2, float eps)\n{\n\treturn 1.0 / (eps + dist2);//sqrt(eps + dist2 > (100*eps) ? 100 * eps : dist2);\n}\ninline float MeshMorph::RBF_inv_multiquadric(float dist2, float eps)\n{\n\treturn 1.0 / sqrt(eps * 10 + dist2);\n}\n", "meta": {"hexsha": "8e605519878209a038f567275a1adb5f3ed8ed75", "size": 5580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Qt-GL-Simple-Scene-master/MeshMorph.cpp", "max_stars_repo_name": "nacsa/Retopology", "max_stars_repo_head_hexsha": "03c009462db3d73dbb73ea543952d421ecc1416e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Qt-GL-Simple-Scene-master/MeshMorph.cpp", "max_issues_repo_name": "nacsa/Retopology", "max_issues_repo_head_hexsha": "03c009462db3d73dbb73ea543952d421ecc1416e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Qt-GL-Simple-Scene-master/MeshMorph.cpp", "max_forks_repo_name": "nacsa/Retopology", "max_forks_repo_head_hexsha": "03c009462db3d73dbb73ea543952d421ecc1416e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6237623762, "max_line_length": 207, "alphanum_fraction": 0.6501792115, "num_tokens": 1946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6460765025670908}}
{"text": "#include \"math_unit_test.hpp\"\n#include <boost/math/fft/algorithms.hpp>\n\nusing namespace boost::math::fft;\n\nvoid test_is_prime()\n{\n  CHECK_EQUAL(false,detail::is_prime(1));\n  CHECK_EQUAL(true,detail::is_prime(2));\n  CHECK_EQUAL(true,detail::is_prime(3));\n  CHECK_EQUAL(false,detail::is_prime(4));\n  CHECK_EQUAL(true,detail::is_prime(5));\n  CHECK_EQUAL(false,detail::is_prime(6));\n  CHECK_EQUAL(true,detail::is_prime(7));\n  CHECK_EQUAL(false,detail::is_prime(8));\n  CHECK_EQUAL(false,detail::is_prime(9));\n  CHECK_EQUAL(false,detail::is_prime(10));\n  \n  // factorial primes \n  CHECK_EQUAL(true,detail::is_prime(719));\n  CHECK_EQUAL(true,detail::is_prime(5039));\n  CHECK_EQUAL(true,detail::is_prime(39916801));\n  CHECK_EQUAL(true,detail::is_prime(479001599));\n}\nvoid test_primitive_root()\n{\n  for(auto p : std::vector<long>{3,5,7,11,13,17,23,29})\n  {\n    const long r = detail::primitive_root(p);\n    std::cerr << \"p = \" << p << \", root = \" << r << '\\n';\n    const long phi = p-1;\n    \n    long r_p = r;\n    for(int i=1;i<phi;++i)\n    {\n      CHECK_EQUAL(false,r_p == 1);\n      r_p = (r_p * r) % p;\n    }\n      CHECK_EQUAL(true,r_p == 1);\n  }\n}\n\nvoid test_power2()\n{\n  CHECK_EQUAL(false,detail::is_power2(-4));   \n  CHECK_EQUAL(false,detail::is_power2(-3));   \n  CHECK_EQUAL(false,detail::is_power2(-2));   \n  CHECK_EQUAL(false,detail::is_power2(-1));   \n  CHECK_EQUAL(false,detail::is_power2(0));   \n  CHECK_EQUAL(false,detail::is_power2(3));   \n  CHECK_EQUAL(false,detail::is_power2(5));   \n  CHECK_EQUAL(false,detail::is_power2(6));   \n  CHECK_EQUAL(false,detail::is_power2(7));   \n  \n  for(int i=9;i<16;++i)\n    CHECK_EQUAL(false,detail::is_power2(i));   \n  \n  CHECK_EQUAL(true,detail::is_power2(1));   \n  CHECK_EQUAL(true,detail::is_power2(2));   \n  CHECK_EQUAL(true,detail::is_power2(4));   \n  CHECK_EQUAL(true,detail::is_power2(8));   \n  CHECK_EQUAL(true,detail::is_power2(16));   \n  \n  for(int i=-20;i<=0;++i)\n    CHECK_EQUAL(0,detail::lower_bound_power2(i));   \n    \n  CHECK_EQUAL(1,detail::lower_bound_power2(1));   \n  CHECK_EQUAL(2,detail::lower_bound_power2(2));   \n  CHECK_EQUAL(2,detail::lower_bound_power2(3));   \n  CHECK_EQUAL(4,detail::lower_bound_power2(4));   \n  CHECK_EQUAL(4,detail::lower_bound_power2(5));   \n  CHECK_EQUAL(4,detail::lower_bound_power2(6));   \n  CHECK_EQUAL(4,detail::lower_bound_power2(7));   \n  for(int i=8;i<16;++i)\n    CHECK_EQUAL(8,detail::lower_bound_power2(i));   \n  for(int i=16;i<32;++i)\n    CHECK_EQUAL(16,detail::lower_bound_power2(i));   \n  \n  for(int i=-20;i<=0;++i)\n    CHECK_EQUAL(1,detail::upper_bound_power2(i));   \n    \n  CHECK_EQUAL(1,detail::upper_bound_power2(1));   \n  CHECK_EQUAL(2,detail::upper_bound_power2(2));   \n  CHECK_EQUAL(4,detail::upper_bound_power2(3));   \n  CHECK_EQUAL(4,detail::upper_bound_power2(4));   \n  CHECK_EQUAL(8,detail::upper_bound_power2(5));   \n  CHECK_EQUAL(8,detail::upper_bound_power2(6));   \n  CHECK_EQUAL(8,detail::upper_bound_power2(7));   \n  CHECK_EQUAL(8,detail::upper_bound_power2(8));   \n  for(int i=9;i<=16;++i)\n    CHECK_EQUAL(16,detail::upper_bound_power2(i));   \n  for(int i=17;i<=32;++i)\n    CHECK_EQUAL(32,detail::upper_bound_power2(i));   \n  CHECK_EQUAL(0,detail::upper_bound_power2(std::numeric_limits<int>::max()));   \n  CHECK_EQUAL(0,detail::upper_bound_power2((1<<30)+1));   \n  CHECK_EQUAL(1<<30,detail::upper_bound_power2(1<<30));   \n  CHECK_EQUAL(1<<30,detail::upper_bound_power2((1<<30) - 1));   \n}\n\nint main()\n{\n  test_power2();\n  test_is_prime(); \n  test_primitive_root();\n  return boost::math::test::report_errors();\n}\n\n", "meta": {"hexsha": "ae3caac59e534a7551af635113c2d356ca8fc7fa", "size": 3530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fft_auxiliary_functions.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/fft_auxiliary_functions.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_auxiliary_functions.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 32.6851851852, "max_line_length": 80, "alphanum_fraction": 0.6705382436, "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6460473972966803}}
{"text": "/* boost histogram.cpp graphical verification of distribution functions\n *\n * Copyright Jens Maurer 2000\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id: histogram.cpp 60755 2010-03-22 00:45:06Z steven_watanabe $\n *\n * This test program allows to visibly examine the results of the\n * distribution functions.\n */\n\n#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n#include <string>\n#include <boost/random.hpp>\n\n\nvoid plot_histogram(const std::vector<int>& slots, int samples,\n                    double from, double to)\n{\n  int m = *std::max_element(slots.begin(), slots.end());\n  const int nRows = 20;\n  std::cout.setf(std::ios::fixed|std::ios::left);\n  std::cout.precision(5);\n  for(int r = 0; r < nRows; r++) {\n    double y = ((nRows - r) * double(m))/(nRows * samples);\n    std::cout << std::setw(10) << y << \"  \";\n    for(unsigned int col = 0; col < slots.size(); col++) {\n      char out = ' ';\n      if(slots[col]/double(samples) >= y)\n        out = 'x';\n      std::cout << out;\n    }\n    std::cout << std::endl;\n  }\n  std::cout << std::setw(12) << \" \"\n            << std::setw(10) << from;\n  std::cout.setf(std::ios::right, std::ios::adjustfield);\n  std::cout << std::setw(slots.size()-10) << to << std::endl;\n}\n\n// I am not sure whether these two should be in the library as well\n\n// maintain sum of NumberGenerator results\ntemplate<class NumberGenerator, \n  class Sum = typename NumberGenerator::result_type>\nclass sum_result\n{\npublic:\n  typedef NumberGenerator base_type;\n  typedef typename base_type::result_type result_type;\n  explicit sum_result(const base_type & g) : gen(g), _sum(0) { }\n  result_type operator()() { result_type r = gen(); _sum += r; return r; }\n  base_type & base() { return gen; }\n  Sum sum() const { return _sum; }\n  void reset() { _sum = 0; }\nprivate:\n  base_type gen;\n  Sum _sum;\n};\n\n\n// maintain square sum of NumberGenerator results\ntemplate<class NumberGenerator, \n  class Sum = typename NumberGenerator::result_type>\nclass squaresum_result\n{\npublic:\n  typedef NumberGenerator base_type;\n  typedef typename base_type::result_type result_type;\n  explicit squaresum_result(const base_type & g) : gen(g), _sum(0) { }\n  result_type operator()() { result_type r = gen(); _sum += r*r; return r; }\n  base_type & base() { return gen; }\n  Sum squaresum() const { return _sum; }\n  void reset() { _sum = 0; }\nprivate:\n  base_type gen;\n  Sum _sum;\n};\n\n\ntemplate<class RNG>\nvoid histogram(RNG base, int samples, double from, double to, \n               const std::string & name)\n{\n  typedef squaresum_result<sum_result<RNG, double>, double > SRNG;\n  SRNG gen((sum_result<RNG, double>(base)));\n  const int nSlots = 60;\n  std::vector<int> slots(nSlots,0);\n  for(int i = 0; i < samples; i++) {\n    double val = gen();\n    if(val < from || val >= to)    // early check avoids overflow\n      continue;\n    int slot = int((val-from)/(to-from) * nSlots);\n    if(slot < 0 || slot > (int)slots.size())\n      continue;\n    slots[slot]++;\n  }\n  std::cout << name << std::endl;\n  plot_histogram(slots, samples, from, to);\n  double mean = gen.base().sum() / samples;\n  std::cout << \"mean: \" << mean\n            << \" sigma: \" << std::sqrt(gen.squaresum()/samples-mean*mean)\n            << \"\\n\" << std::endl;\n}\n\ntemplate<class PRNG, class Dist>\ninline boost::variate_generator<PRNG&, Dist> make_gen(PRNG & rng, Dist d)\n{\n  return boost::variate_generator<PRNG&, Dist>(rng, d);\n}\n\ntemplate<class PRNG>\nvoid histograms()\n{\n  PRNG rng;\n  using namespace boost;\n  histogram(make_gen(rng, uniform_smallint<>(0, 5)), 100000, -1, 6,\n            \"uniform_smallint(0,5)\");\n  histogram(make_gen(rng, uniform_int<>(0, 5)), 100000, -1, 6,\n            \"uniform_int(0,5)\");\n  histogram(make_gen(rng, uniform_real<>(0,1)), 100000, -0.5, 1.5,\n            \"uniform_real(0,1)\");\n  histogram(make_gen(rng, bernoulli_distribution<>(0.2)), 100000, -0.5, 1.5,\n            \"bernoulli(0.2)\");\n  histogram(make_gen(rng, binomial_distribution<>(4, 0.2)), 100000, -1, 5,\n            \"binomial(4, 0.2)\");\n  histogram(make_gen(rng, triangle_distribution<>(1, 2, 8)), 100000, 0, 10,\n            \"triangle(1,2,8)\");\n  histogram(make_gen(rng, geometric_distribution<>(5.0/6.0)), 100000, 0, 10,\n            \"geometric(5/6)\");\n  histogram(make_gen(rng, exponential_distribution<>(0.3)), 100000, 0, 10,\n            \"exponential(0.3)\");\n  histogram(make_gen(rng, cauchy_distribution<>()), 100000, -5, 5,\n            \"cauchy\");\n  histogram(make_gen(rng, lognormal_distribution<>(3, 2)), 100000, 0, 10,\n            \"lognormal\");\n  histogram(make_gen(rng, normal_distribution<>()), 100000, -3, 3,\n            \"normal\");\n  histogram(make_gen(rng, normal_distribution<>(0.5, 0.5)), 100000, -3, 3,\n            \"normal(0.5, 0.5)\");\n  histogram(make_gen(rng, poisson_distribution<>(1.5)), 100000, 0, 5,\n            \"poisson(1.5)\");\n  histogram(make_gen(rng, poisson_distribution<>(10)), 100000, 0, 20,\n            \"poisson(10)\");\n  histogram(make_gen(rng, gamma_distribution<>(0.5)), 100000, 0, 0.5,\n            \"gamma(0.5)\");\n  histogram(make_gen(rng, gamma_distribution<>(1)), 100000, 0, 3,\n            \"gamma(1)\");\n  histogram(make_gen(rng, gamma_distribution<>(2)), 100000, 0, 6,\n            \"gamma(2)\");\n}\n\n\nint main()\n{\n  histograms<boost::mt19937>();\n  // histograms<boost::lagged_fibonacci607>();\n}\n\n", "meta": {"hexsha": "11ad00c3f32bf367fe8701b4e4b1039cefaa2a5c", "size": 5437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/histogram.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "libs/random/test/histogram.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "libs/random/test/histogram.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 32.7530120482, "max_line_length": 76, "alphanum_fraction": 0.6288394335, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6460473777899415}}
{"text": "#pragma once\n#include \"coordinate_transform.hpp\"\n#include \"integrate.hpp\"\n#include \"shape.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <functional>\n\n//! Computes the H^1 differences between\n//! u1 (considered as coefficients for the shape functions)\n//! and u2grad.\ndouble computeH1Difference(const Eigen::MatrixXd &vertices,\n                           const Eigen::MatrixXi &triangles,\n                           const Eigen::VectorXd &u1,\n                           const std::function<Eigen::Vector2d(double, double)> &u2grad) {\n\tconst int numberOfElements = triangles.rows();\n\n\tdouble error = 0;\n\tfor (int i = 0; i < numberOfElements; ++i) {\n\t\tauto &indexSet = triangles.row(i);\n\n\t\tconst int i0 = indexSet(0);\n\t\tconst int i1 = indexSet(1);\n\t\tconst int i2 = indexSet(2);\n\n\t\tconst auto &a = vertices.row(i0);\n\t\tconst auto &b = vertices.row(i1);\n\t\tconst auto &c = vertices.row(i2);\n\n\t\tauto            coordinateTransform = makeCoordinateTransform(b - a, c - a);\n\t\tauto            volumeFactor        = std::abs(coordinateTransform.determinant());\n\t\tEigen::Matrix2d elementMap          = coordinateTransform.inverse().transpose();\n\n\t\terror += integrate([&](double x, double y) {\n\t\t\tEigen::Vector2d z = coordinateTransform * Eigen::Vector2d(x, y) + Eigen::Vector2d(a(0), a(1));\n\n\t\t\tEigen::Vector2d approximate_grad = u1(i0) * elementMap * gradientLambda(0, x, y) + u1(i1) * elementMap * gradientLambda(1, x, y) + u1(i2) * elementMap * gradientLambda(2, x, y);\n\t\t\tEigen::Vector2d difference_grad  = u2grad(z(0), z(1)) - approximate_grad;\n\t\t\treturn difference_grad.dot(difference_grad) * volumeFactor;\n\t\t});\n\t}\n\n\treturn std::sqrt(error);\n}\n", "meta": {"hexsha": "90bce007fef43de337b32ebf9f62566f9e204ade", "size": 1651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2/2d-linFEM/H1_norm.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series2/2d-linFEM/H1_norm.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series2/2d-linFEM/H1_norm.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6888888889, "max_line_length": 180, "alphanum_fraction": 0.6535433071, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6460438401645787}}
{"text": "//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//% Code implementing the paper \"Accelerated Quadratic Proxy for Geometric Optimization\", SIGGRAPH 2016.\n//% Disclaimer: The code is provided as-is for academic use only and without any guarantees. \n//%             Please contact the author to report any bugs.\n//% Written by Shahar Kovalsky (http://www.wisdom.weizmann.ac.il/~shaharko/)\n//%            Meirav Galun (http://www.wisdom.weizmann.ac.il/~/meirav/)\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n#include \"mex.h\"\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include \"mexHelpers.cpp\"\n\nusing namespace Eigen;\n\nvoid computeMeshTranformationCoeffsFullDim(const MatrixXd& F, const MatrixXd& V, SparseMatrix<double> &T, VectorXd& areas)\n{\n\t// init\n\tint n_tri = F.rows();\n\tint d_simplex = F.cols();\n\tint n_vert = V.rows();\n\tint dim = V.cols();\n\tint T_rows = n_tri*dim*dim;\n\tint T_cols = n_vert*dim;\n\tint T_nnz = n_tri*dim*dim*d_simplex;\n\n\n\t// prepare centering matrix\n\tMatrixXd B = MatrixXd::Identity(d_simplex, d_simplex);\n\tB = B.array() - (1.0 / d_simplex);\n\n\t// prepare output matrix\n\tT.resize(T_cols, T_rows);\n\tT.reserve(VectorXi::Constant(T_rows, d_simplex));\n\tareas.resize(n_tri);\n\n\t// calculate differential coefficients for each element\n\tMatrixXd currV(d_simplex, dim);\n\tMatrixXd currT(dim, d_simplex);\n\tint curr_row = 0;\n\tfor (int ii = 0; ii < n_tri; ii++)\n\t{\n\t\t// calculate current element\n\t\tfor (int jj = 0; jj < d_simplex; jj++)\n\t\t{\n\t\t\tcurrV.row(jj) = V.row(F(ii, jj));\n\t\t}\n\t\tcurrV = B*currV; // center\n\t\tcurrT = currV.fullPivLu().solve(B); // solver\n\n\t\t// fill into the correct places of T\n\t\tfor (int cd = 0; cd < dim; cd++)\n\t\tfor (int cr = 0; cr < dim; cr++)\n\t\t{\n\t\t\tfor (int cc = 0; cc < d_simplex; cc++)\n\t\t\t\tT.insert(F(ii, cc) + (cd*n_vert), curr_row) = currT(cr, cc);\n\t\t\tcurr_row += 1;\n\t\t}\n\n\t\t// calculate area\n\t\tareas(ii) = (currV.bottomRows(dim).rowwise() - currV.row(0)).determinant() / 2;\n\t}\n\n\t// compress\n\tT.makeCompressed();\n\tT = T.transpose();\n}\n\n\nvoid orth(const MatrixXd &A, MatrixXd &Q)\n{\n\n\t//perform svd on A = U*S*V' (V is not computed and only the thin U is computed)\n\tEigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeThinU);\n\tEigen::MatrixXd U = svd.matrixU();\n\tconst Eigen::VectorXd S = svd.singularValues();\n\n\t//get rank of A\n\tint m = A.rows();\n\tint n = A.cols();\n\tdouble tol = std::max(m, n) * S.maxCoeff() *  2.2204e-16;\n\tint r = 0;\n\tfor (int i = 0; i < S.rows(); ++r, ++i)\n\t{\n\t\tif (S[i] < tol)\n\t\t\tbreak;\n\t}\n\n\t//keep r first columns of U\n\tQ = U.block(0, 0, U.rows(), r);\n}\n\nvoid compute2dEmbedding(const MatrixXd& V, MatrixXd& A)\n{\n\t// given a nXn matrix whose columns are the vertices of a (n-1)-D simplex,\n\t// returns the transformation A, s.t A*V gives embedding in (n-1)-D\n\n\tMatrixXd ctrV(V.rows() - 1, V.cols());\n\tctrV = -V.bottomRows(V.rows() - 1);\n\tctrV.rowwise() += V.row(0);\n\tctrV.transpose();\n\torth(ctrV, A);\n\t//if (((ctrV*A).determinant()) < 0)\n\t//\tA.col(0).swap(A.col(1));\n\tA.transpose();\n}\n\nvoid embedTriangle(const MatrixXd& V, MatrixXd& flatV, double& area)\n{\n\tVectorXd v1 = V.row(1) - V.row(0);\n\tVectorXd v2 = V.row(2) - V.row(0);\n\n\tdouble norm_v1 = v1.norm();\n\tdouble norm_v2 = v2.norm();\n\tdouble cos_theta = v1.dot(v2) / (norm_v1*norm_v2);\n\tdouble sin_theta = sqrt(1 - cos_theta*cos_theta);\n\n\tflatV << 0, 0,\n\t\tnorm_v1, 0,\n\t\tnorm_v2*cos_theta, norm_v2*sin_theta;\n\n\tarea = norm_v1*norm_v2*sin_theta / 2;\n}\n\nvoid computeMeshTranformationCoeffsFlatenning(const MatrixXd& F, const MatrixXd& V, SparseMatrix<double> &T, VectorXd& areas)\n{\n\t// init\n\tint n_tri = F.rows();\n\tint d_simplex = F.cols();\n\tint n_vert = V.rows();\n\tint dim = V.cols();\n\tint d_diff = dim - 1;\n\tint T_rows = n_tri*d_diff*d_diff;\n\tint T_cols = n_vert*d_diff;\n\tint T_nnz = n_tri*d_diff*d_diff*d_simplex;\n\n\tassert(d_simplex == 3 && dim == 3);\n\n\t// prepare centering matrix\n\tMatrixXd B = MatrixXd::Identity(d_simplex, d_simplex);\n\tB = B.array() - (1.0 / d_simplex);\n\n\t// prepare output matrix\n\tT.resize(T_cols, T_rows);\n\tT.reserve(VectorXi::Constant(T_rows, d_simplex));\n\tareas.resize(n_tri);\n\n\t// calculate differential coefficients for each element\n\tMatrixXd currV(d_simplex, dim);\n\tMatrixXd currT(dim, d_simplex);\n\tMatrixXd RFlat(dim, d_diff);\n\tMatrixXd currVFlat(d_simplex, d_diff);\n\tint curr_row = 0;\n\tfor (int ii = 0; ii < n_tri; ii++)\n\t{\n\t\t// calculate current element\n\t\tfor (int jj = 0; jj < d_simplex; jj++)\n\t\t{\n\t\t\tcurrV.row(jj) = V.row(F(ii, jj));\n\t\t}\n\t\t// transform to plane\n\t\tembedTriangle(currV, currVFlat, areas(ii)); // this only works for triangles\n\t\t// compute\n\t\tcurrVFlat = B*currVFlat; // center\n\t\tcurrT = currVFlat.fullPivLu().solve(B); // solver\n\n\t\t// fill into the correct places of T\n\t\tfor (int cd = 0; cd < d_diff; cd++)\n\t\tfor (int cr = 0; cr < d_diff; cr++)\n\t\t{\n\t\t\tfor (int cc = 0; cc < d_simplex; cc++)\n\t\t\t\tT.insert(F(ii, cc) + (cd*n_vert), curr_row) = currT(cr, cc);\n\t\t\tcurr_row += 1;\n\t\t}\n\t}\n\n\t// compress\n\tT.makeCompressed();\n\tT = T.transpose();\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[],\n\tint nrhs, const mxArray*prhs[])\n{\n\t// assign input\n\tint n_tri = mxGetM(prhs[0]); // # rows of F\n\tint d_simplex = mxGetN(prhs[0]); // # cols of F\n\tint n_vert = mxGetM(prhs[1]); // # rows of V\n\tint dim = mxGetN(prhs[1]); // # cols of V\n\tconst Map<MatrixXd, Aligned> Fmatlab(mxGetPr(prhs[0]), n_tri, d_simplex);\n\tconst Map<MatrixXd, Aligned> V(mxGetPr(prhs[1]), n_vert, dim);\n\t\n\t// update index numbers to 0-base\n\tMatrixXd F (Fmatlab);\n\tF = F.array() - 1;\t\n\n\t// compute\n\tSparseMatrix<double> T;\n\tVectorXd areas;\n\tif (d_simplex == 3 && dim == 2)\n\t{\n\t\t// Planar triangulation\n\t\tcomputeMeshTranformationCoeffsFullDim(F, V, T, areas);\n\t}\n\telse if (d_simplex == 4 && dim == 3)\n\t{\n\t\t// Tet mesh\n\t\tcomputeMeshTranformationCoeffsFullDim(F, V, T, areas);\n\t}\n\telse if (d_simplex == 3 && dim == 3)\n\t{\n\t\t// 3D surface\n\t\tcomputeMeshTranformationCoeffsFlatenning(F, V, T, areas);\n\t}\n\telse\n\t\tmexErrMsgIdAndTxt(\"MATLAB:invalidInputs\", \"Invalid input dimensions or mesh type not supported\");\n\n\n\t// assign outputs\n\tmapSparseMatrixToMex(T, &(plhs[0]));\n\tmapDenseMatrixToMex(areas, &(plhs[1]));\n}", "meta": {"hexsha": "21aa529445004efdf7f96c5856ff0ca070a0037e", "size": 6087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/2D/lib/mex/computeMeshTranformationCoeffsMex.cpp", "max_stars_repo_name": "ErisZhang/BCQN", "max_stars_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-06-08T11:12:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T06:45:26.000Z", "max_issues_repo_path": "code/2D/lib/mex/computeMeshTranformationCoeffsMex.cpp", "max_issues_repo_name": "ErisZhang/BCQN", "max_issues_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T12:12:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T12:12:18.000Z", "max_forks_repo_path": "code/2D/lib/mex/computeMeshTranformationCoeffsMex.cpp", "max_forks_repo_name": "ErisZhang/BCQN", "max_forks_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T06:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-27T09:58:32.000Z", "avg_line_length": 27.4189189189, "max_line_length": 125, "alphanum_fraction": 0.6369311648, "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.6460246721718393}}
{"text": "#include <mex.h> \n#include <math.h>\n#include <Eigen/Dense>\n#include <iostream>\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\ndouble amips_param;\ndouble energy_min;\ndouble energy_max = 10;\ndouble c1_param;\ndouble c2_param;\ndouble d1_param;\n\n\nVector3d color_map(double v)\n{\n\tVector3d c;\n    \n    c[0] = c[1] = c[2] = 1;\n\n\tdouble dv;\n\n\tif (v < energy_min)\n\t\tv = energy_min;\n\tif (v > energy_max)\n\t\tv = energy_max;\n\tdv = energy_max - energy_min;\n\n\tif (v < (energy_min + 0.25 * dv)) {\n\t\tc[0] = 0;\n\t\tc[1] = 4 * (v - energy_min) / dv;\n\t}\n\telse if (v < (energy_min + 0.5 * dv)) {\n\t\tc[0] = 0;\n\t\tc[2] = 1 + 4 * (energy_min + 0.25 * dv - v) / dv;\n\t}\n\telse if (v < (energy_min + 0.75 * dv)) {\n\t\tc[0] = 4 * (v - energy_min - 0.5 * dv) / dv;\n\t\tc[2] = 0;\n\t}\n\telse {\n\t\tc[1] = 1 + 4 * (energy_min + 0.75 * dv - v) / dv;\n\t\tc[2] = 0;\n\t}\n\n\treturn c;\n}\n\n\nvoid set_energy_min(int type)\n{\n\n    switch(type)\n    {\n        case 0: //arap\n            energy_min = 0;\n            break;\n            \n        case 1: // mips\n            energy_min = 2;\n            break;\n            \n        case 2: // iso\n            energy_min = 4;\n            break;\n            \n        case 3: // amips\n            energy_min = exp(amips_param * 2);\n            break;\n            \n        case 4: // conf\n            energy_min = 1;\n            break;\n            \n        case 5: \n            energy_min = -c1_param - 2 * c2_param;\n            break;\n    }\n    \n}\n\n\ndouble energy_value(int type, Vector2d S)\n{\n    \n    double value = 0;\n    double J;\n    double l1;\n    double l2;\n    \n    switch(type)\n    {\n        case 0: //arap\n            value = (S[0] - 1) * (S[0] - 1) + (S[1] - 1) * (S[1] - 1);\n            break;\n            \n        case 1: // mips\n            value = S[0] / S[1] + S[1] / S[0];\n            break;\n            \n        case 2: // iso\n            value = S[0] * S[0] + 1.0 / (S[0] * S[0]) + S[1] * S[1] + 1.0 / (S[1] * S[1]);\n            break;\n            \n        case 3: // amips\n            value = exp(amips_param * (S[0] / S[1] + S[1] / S[0]));\n            break;\n            \n        case 4: // conf\n            value = S[0] / S[1];\n            value *= value;\n            break;\n            \n        case 5: // gmr\n            J = S[0] * S[1];\n            l1 = S[0] * S[0] + S[1] * S[1];\n            l2 = S[0] * S[0] * S[1] * S[1];\n            \n            value = c1_param * (pow(J, -2.0 / 3.0) * l1 - 3) + c2_param * (pow(J, -4.0 / 3.0) * l2 - 3) + d1_param * (J - 1) * (J - 1);\n            break;\n            \n        case 6: // olg\n            \n            value = max(S[0], 1.0 / S[1]);\n            break;\n    }\n    \n    return value;\n\n}\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n    \n    mxArray *output_mex;\n    const int *dims;\n    double *tri_num, *X_g_inv, *tri_areas, *obj_tri, *q_target, *type, *amips_s, *c1, *c2, *d1;\n    double *output;\n    \n    tri_num = mxGetPr(prhs[0]);\n    X_g_inv = mxGetPr(prhs[1]);\n    tri_areas = mxGetPr(prhs[2]);\n    obj_tri = mxGetPr(prhs[3]);\n    q_target = mxGetPr(prhs[4]);\n    type = mxGetPr(prhs[5]);\n    amips_s = mxGetPr(prhs[6]);\n    c1 = mxGetPr(prhs[7]);\n    c2 = mxGetPr(prhs[8]);\n    d1 = mxGetPr(prhs[9]);   \n    \n    int tri_n = tri_num[0];\n    int energy_type = type[0];\n    amips_param = amips_s[0];\n    c1_param = c1[0];\n    c2_param = c2[0];\n    d1_param = d1[0];\n    \n    output_mex = plhs[0] = mxCreateDoubleMatrix(tri_n, 1, mxREAL);\n    \n    output = mxGetPr(output_mex);\n    \n    \n    int tri[3];\n    double tri_area;\n    \n    \n    Matrix2d B, X_f, A;\n    Vector2d S;\n    Matrix2d U, V;\n \n    for(int i = 0; i < tri_n; i++)\n    {\n        //mexPrintf(\"%d %d %d\\n\", (int)obj_tri[i], (int)obj_tri[i + tri_n], (int)obj_tri[i + 2 * tri_n]);\n        tri[0] = obj_tri[i] - 1; \n        tri[1] = obj_tri[i + tri_n] - 1; \n        tri[2] = obj_tri[i + 2 * tri_n] - 1; \n        tri_area = tri_areas[i];\n        \n        B(0, 0) = X_g_inv[i];\n        B(0, 1) = X_g_inv[i + tri_n * 2];\n        B(1, 0) = X_g_inv[i + tri_n];\n        B(1, 1) = X_g_inv[i + tri_n * 3];\n        \n        X_f(0, 0) = q_target[2 * tri[1]] - q_target[2 * tri[0]];\n        X_f(1, 0) = q_target[2 * tri[1] + 1] - q_target[2 * tri[0] + 1];  \n        X_f(0, 1) = q_target[2 * tri[2]] - q_target[2 * tri[0]];\n        X_f(1, 1) = q_target[2 * tri[2] + 1] - q_target[2 * tri[0] + 1];\n        \n        A = X_f * B;\n        \n        if(A.determinant() <= 0)\n        {\n            //mexPrintf(\"element inverted\");\n        }\n        \n        JacobiSVD<Matrix2d> svd(A, ComputeFullU | ComputeFullV);\n        \n        S = svd.singularValues();\n        U = svd.matrixU();\n        V = svd.matrixV();\n        \n        output[i] = energy_value(energy_type, S);\n        \n    }\n    \n    return;\n    \n}", "meta": {"hexsha": "118ca0b244d8eee8e97aa468a96861e7fc6a8325", "size": 4747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/2D/lib/mex/energy_color_mex.cpp", "max_stars_repo_name": "ErisZhang/BCQN", "max_stars_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T16:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T11:47:42.000Z", "max_issues_repo_path": "code/2D/lib/mex/energy_color_mex.cpp", "max_issues_repo_name": "ErisZhang/BCQN", "max_issues_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T12:12:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T12:12:18.000Z", "max_forks_repo_path": "code/2D/lib/mex/energy_color_mex.cpp", "max_forks_repo_name": "ErisZhang/BCQN", "max_forks_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T06:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-27T09:58:32.000Z", "avg_line_length": 22.2863849765, "max_line_length": 135, "alphanum_fraction": 0.4415420265, "num_tokens": 1698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6459271679767884}}
{"text": "#include \"maxwellJuttner.h\"\n\n#include <fmath/mathFunctions.h>\n#include <fmath/physics.h>\n#include <boost/math/special_functions/bessel.hpp>\n\n\ndouble f_norm(double g, double norm_temp)\n{\n\tdouble beta = sqrt(1.0-1.0/P2(g));\n\t\n\treturn P2(g)*beta*exp(-g/norm_temp); \n\t\n}\n\ndouble maxwellRel(double gamma, double norm_temp, double norm)\n{\n\t\t\n\tdouble beta = sqrt(1.0-1.0/(gamma*gamma));\n\t\n\tdouble K2 =  boost::math::cyl_bessel_k(2, 1.0/norm_temp); //bessk(2, 1.0/norm_temp);\n\t\n\tdouble dist_g = gamma*gamma*beta*exp(-gamma/norm_temp) / (K2*norm_temp);\n\n\treturn  dist_g*norm;\n\n}", "meta": {"hexsha": "cd8a03018e3eb918f88ea57924c454b7125152b4", "size": 569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/maxwellJuttner.cpp", "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_issues_repo_path": "src/adaf/maxwellJuttner.cpp", "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adaf/maxwellJuttner.cpp", "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0740740741, "max_line_length": 85, "alphanum_fraction": 0.7012302285, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6459271525162664}}
{"text": "#ifndef BOOST_METAPARSE_GETTING_STARTED_7_HPP\r\n#define BOOST_METAPARSE_GETTING_STARTED_7_HPP\r\n\r\n// Automatically generated header file\r\n\r\n// Definitions before section 6.2\r\n#include \"6_2.hpp\"\r\n\r\n// Definitions of section 6.2\r\n#include <boost/mpl/minus.hpp>\r\n\r\ntemplate <class L, char Op, class R> struct eval_binary_op;\r\n\r\ntemplate <class L, class R> struct eval_binary_op<L, '+', R> : boost::mpl::plus<L, R>::type {};\r\n\r\ntemplate <class L, class R> struct eval_binary_op<L, '-', R> : boost::mpl::minus<L, R>::type {};\r\n\r\n// query:\r\n//    eval_binary_op<boost::mpl::int_<11>, '+', boost::mpl::int_<2>>::type\r\n\r\n// query:\r\n//    eval_binary_op<boost::mpl::int_<13>, '-', boost::mpl::int_<2>>::type\r\n\r\ntemplate <class S, class Item> \r\n struct binary_op : \r\n   eval_binary_op< \r\n     S, \r\n     boost::mpl::at_c<Item, 0>::type::value, \r\n     typename boost::mpl::at_c<Item, 1>::type \r\n   > \r\n   {};\r\n\r\n// query:\r\n//    binary_op<boost::mpl::int_<11>, boost::mpl::vector<boost::mpl::char_<'+'>, boost::mpl::int_<2>>>::type\r\n\r\nusing exp_parser13 = \r\n build_parser< \r\n   foldl_start_with_parser< \r\n     sequence<one_of<plus_token, minus_token>, int_token>, \r\n     int_token, \r\n     boost::mpl::quote2<binary_op> \r\n   > \r\n >;\r\n\r\n// query:\r\n//    exp_parser13::apply<BOOST_METAPARSE_STRING(\"1 + 2 - 3\")>::type\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "4c7e592c47614519109eaee491e2b42e1d1cbab0", "size": 1314, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/getting_started/7.hpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/getting_started/7.hpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/metaparse/example/getting_started/7.hpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 26.28, "max_line_length": 109, "alphanum_fraction": 0.6339421613, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6458633248916319}}
{"text": "/**\n    @file Project_1.cpp\n\n    @author Terence Henriod\n\n    Project 1: Bayesion Minimum Error Classification\n\n    @brief The driver program for use of a Bayesian Minimum Error Classifier.\n\n    @version Original Code 1.00 (3/8/2014) - T. Henriod\n\n    UNOFFICIALLY:\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\n\nCompilation notes:\ng++ -I /home/thenriod/Desktop/cpp_libs/Eigen_lib/ Project_1.cpp\n\n*/\n\n/*==============================================================================\n=======     HEADER FILES     ===================================================\n==============================================================================*/\n#include <cmath>\n#include <iostream>\n\n#include \"bayes_classifier.cpp\"\n#include <Eigen/Dense>  // -I /home/thenriod/Desktop/cpp_libs/Eigen_lib\n\nusing namespace std;\n\n/*==============================================================================\n=======     USER DEFINED TYPES     =============================================\n==============================================================================*/\n\n\n\n/*==============================================================================\n=======     CONSTANTS / MACROS     =============================================\n==============================================================================*/\n\n\n/*==============================================================================\n=======     GLOBAL VARIABLES     ===============================================\n==============================================================================*/\n  // none\n\n/*==============================================================================\n=======     FUNCTION PROTOTYPES     ============================================\n==============================================================================*/\n \n\n\n\n/*==============================================================================\n=======     MAIN FUNCTION     ==================================================\n==============================================================================*/\n\n/**\nmain\n\nThe main driver\n\n@param\n\n@return\n\n@pre\n-#\n\n@post\n-#\n\n@code\n@endcode\n*/\n\nint main( int argc, char** argv )\n{\n  // variables\n  BayesClassifier problem_solver;\n  double part_A_prior_probability = 0.5;\n  double part_B_prior_probability = 0.3;\n  Eigen::Vector2d part_one_mean_one;\n    part_one_mean_one << 1.502, 1.484;\n  Eigen::Vector2d part_one_mean_two;\n    part_one_mean_two << 2.499, 2.497;\n  Eigen::Vector2d part_two_mean_one;\n    part_two_mean_one << 1, 2;\n  Eigen::Vector2d part_two_mean_two;\n    part_two_mean_two << 1, 4;\n  Eigen::Matrix2d part_one_covariance_one;\n    part_one_covariance_one << 1.099, 0,\n                               0, 1.099;\n  Eigen::Matrix2d part_one_covariance_two;\n    part_one_covariance_two << 1.813, 0,\n                               0, 1.813;\n  Eigen::Matrix2d part_two_covariance_one;\n    part_two_covariance_one << 1, 0,\n                               0, 1;\n  Eigen::Matrix2d part_two_covariance_two;\n    part_two_covariance_two << 3, 0,\n                               0, 2;\n\n  // setup for problem 1\n  problem_solver.setMean( part_one_mean_one, CLASS_ONE );\n  problem_solver.setMean( part_one_mean_two, CLASS_TWO );\n  problem_solver.setCovariance( part_one_covariance_one, CLASS_ONE );\n  problem_solver.setCovariance( part_one_covariance_two, CLASS_TWO );\n  problem_solver.setPriorProbabilities( part_A_prior_probability );\n  problem_solver.setAssumptionCase( CASE_ONE );\n\n  // solve 1.a\n//  problem_solver.performAnalysis( \"P1_data.txt\", \"test_1A_output.txt\" );\nproblem_solver.performAnalysis( \"Bebis11.txt\", \"Bebis1A.txt\" );\n\n  // solve 1.b\n  problem_solver.setPriorProbabilities( part_B_prior_probability );\n//  problem_solver.performAnalysis( \"P1_data.txt\", \"test_1B_output.txt\" );\nproblem_solver.performAnalysis( \"Bebis11.txt\", \"Bebis1B.txt\" );\n\n  // setup for problem 2\n  problem_solver.setMean( part_two_mean_one, CLASS_ONE );\n  problem_solver.setMean( part_two_mean_two, CLASS_TWO );\n  problem_solver.setCovariance( part_two_covariance_one, CLASS_ONE );\n  problem_solver.setCovariance( part_two_covariance_two, CLASS_TWO );\n  problem_solver.setPriorProbabilities( part_A_prior_probability );\n  problem_solver.setAssumptionCase( CASE_THREE );\n\n  // solve 2.a\n//  problem_solver.performAnalysis( \"P2_data.txt\", \"test_2A_output.txt\" );\nproblem_solver.performAnalysis( \"Bebis21.txt\", \"Bebis2A.txt\" );\n\n  // solve 2.b\n  problem_solver.setPriorProbabilities( part_B_prior_probability );\n//  problem_solver.performAnalysis( \"P2_data.txt\", \"test_2B_output.txt\" );\nproblem_solver.performAnalysis( \"Bebis21.txt\", \"Bebis2B.txt\" );\n\n  // end program\n  return 0;\n}\n\n/*==============================================================================\n=======     FUNCTION IMPLEMENTATIONS     =======================================\n==============================================================================*/\n\n\n", "meta": {"hexsha": "7842dad357eb849a9f1441641e5519a916aadd87", "size": 5507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CS479/Project_1/code_files/Project_1.cpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "CS479/Project_1/code_files/Project_1.cpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "CS479/Project_1/code_files/Project_1.cpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 34.41875, "max_line_length": 80, "alphanum_fraction": 0.5184310877, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6458633203391138}}
{"text": "#define BOOST_TEST_MODULE test_opencellcad\n\n#include <boost/test/unit_test.hpp>\n\n#include <carl/core/MultivariatePolynomial.h>\n#include <carl/core/Variable.h>\n#include <carl/formula/model/ran/RealAlgebraicPoint.h>\n\n#include <smtrat-mcsat/explanations/onecellcad/OpenCAD.h>\n\n/**\n  * References:\n  * [1] Christopher W. Brown. 2013. Constructing a single open cell in a\n  * cylindrical algebraic decomposition. In Proceedings of the 38th\n  * International Symposium on Symbolic and Algebraic Computation (ISSAC '13).\n  * ACM\n  */\n\nnamespace {\n  using std::cout;\n  using std::endl;\n  using std::optional;\n\n  using smtrat::Rational;\n  using namespace smtrat::onecellcad;\n  using carl::Variable;\n  using MultiPoly = carl::MultivariatePolynomial<Rational>;\n\tusing RAN = carl::RealAlgebraicNumber<Rational>;\n\tusing RANPoint = carl::RealAlgebraicPoint<Rational>;\n\nstruct VariableFixture {\n  Variable x = carl::freshRealVariable(\"x\");\n  Variable y = carl::freshRealVariable(\"y\");\n  Variable z = carl::freshRealVariable(\"z\");\n};\n\nBOOST_FIXTURE_TEST_CASE(polylevel, VariableFixture) {\n  BOOST_TEST_MESSAGE(\"Test polyLevel\");\n\n  std::vector<Variable> variableOrder {x,y,z};\n  BOOST_CHECK(levelOf(MultiPoly(1),variableOrder) == 0);\n  BOOST_CHECK(levelOf(MultiPoly(x)*Rational(0),variableOrder) == 0);\n  BOOST_CHECK(levelOf(MultiPoly(x*y)*Rational(0),variableOrder) == 0);\n  BOOST_CHECK(levelOf(MultiPoly(x),variableOrder) == 1);\n  BOOST_CHECK(levelOf(MultiPoly(y),variableOrder) == 2);\n  BOOST_CHECK(levelOf(MultiPoly(x*y),variableOrder) == 2);\n  BOOST_CHECK(levelOf(MultiPoly(z),variableOrder) == 3);\n  BOOST_CHECK(levelOf(MultiPoly(x*z),variableOrder) == 3);\n  BOOST_CHECK(levelOf(MultiPoly(x*y*z),variableOrder) == 3);\n}\n\nBOOST_FIXTURE_TEST_CASE(cell2d, VariableFixture) {\n  BOOST_TEST_MESSAGE(\"Test 2D example from [1]\");\n  MultiPoly p = MultiPoly(x*x) + MultiPoly(y*y) - Rational(1) ;\n  MultiPoly q = MultiPoly(y*y)*Rational(2) - MultiPoly(x*x) * (MultiPoly(x)*Rational(2) + Rational(3)) ;\n  MultiPoly r = MultiPoly(y) + MultiPoly(x)*Rational(0.5) - Rational(0.5) ;\n\n  std::vector<MultiPoly> polys {p,q,r};\n  RANPoint alpha { RAN(Rational(-1)/3), RAN(Rational(1)/3) };\n  std::vector<Variable> variableOrder {x,y};\n\n  optional<OpenCADCell> c = createOpenCADCell(polys, alpha, variableOrder);\n\n  BOOST_CHECK(c);\n}\n\n\n\n} // namespace\n", "meta": {"hexsha": "0371001a52296edda2e202541c1b6d37a6683b25", "size": 2321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/onecellcad/Test_OpenCad.cpp", "max_stars_repo_name": "minemebarsha/smtrat", "max_stars_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/onecellcad/Test_OpenCad.cpp", "max_issues_repo_name": "minemebarsha/smtrat", "max_issues_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/onecellcad/Test_OpenCad.cpp", "max_forks_repo_name": "minemebarsha/smtrat", "max_forks_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_forks_repo_licenses": ["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.1571428571, "max_line_length": 104, "alphanum_fraction": 0.7294269711, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6458633171647472}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE getGravitationalAttraction\n\n#include <boost/test/unit_test.hpp>\n#include \"math/constant.hpp\"\n#include \"math/getGravitationalAttraction.hpp\"\n\nBOOST_AUTO_TEST_CASE(test_getGravitationalAttraction_1)\n{\n    BOOST_CHECK_MESSAGE(static_cast<long int>(my::math::ga::getGravitationalAttraction<long double>(10000, 20000, 30000)) == static_cast<long int>(0),\n        static_cast<long int>(my::math::ga::getGravitationalAttraction<long double>(10000, 20000, 30000)) << \" instead: \" << static_cast<long int>(0));\n}\nBOOST_AUTO_TEST_CASE(test_getGravitationalAttraction_2)\n{\n    BOOST_CHECK_MESSAGE(static_cast<long int>(my::math::ga::getGravitationalAttraction<long double>(0, 0, 1)) == static_cast<long int>(0),\n        static_cast<long int>(my::math::ga::getGravitationalAttraction<long double>(0, 0, 1)) << \" instead: \" << static_cast<long int>(0));\n}", "meta": {"hexsha": "ddadbeb960c3e1b666ed714b264818dc096504df", "size": 896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/math/test_getGravitationalAttraction.cpp", "max_stars_repo_name": "Pcornat/BenLib", "max_stars_repo_head_hexsha": "5ec30f5eb0bbf827d4d3fd00c8cca1064109fb4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/math/test_getGravitationalAttraction.cpp", "max_issues_repo_name": "Pcornat/BenLib", "max_issues_repo_head_hexsha": "5ec30f5eb0bbf827d4d3fd00c8cca1064109fb4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/math/test_getGravitationalAttraction.cpp", "max_forks_repo_name": "Pcornat/BenLib", "max_forks_repo_head_hexsha": "5ec30f5eb0bbf827d4d3fd00c8cca1064109fb4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 52.7058823529, "max_line_length": 151, "alphanum_fraction": 0.7611607143, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6458631580404341}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2015 Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include <rokko/rokko.hpp>\n#include <rokko/lapack.h>\n#include <boost/lexical_cast.hpp>\n\ntypedef rokko::localized_vector<double> vector_t;\ntypedef rokko::localized_matrix<std::complex<double>, rokko::matrix_col_major> matrix_t;\n\nint main(int argc, char *argv[]) {\n  int info;\n  int m = 6;\n  int n = 4;\n  if (argc > 2) {\n    m = boost::lexical_cast<int>(argv[1]);\n    n = boost::lexical_cast<int>(argv[2]);\n  }\n  std::cout << \"m = \" << m << \"\\nn = \" << n << std::endl;\n  int k = std::min(m, n);\n\n  // generate random martix\n  matrix_t mat = matrix_t::Random(m, n);\n  std::cout << \"Input random matrix A:\\n\" << mat << std::endl;\n\n  // singular value decomposition\n  matrix_t a = mat; // 'a' will be destroyed by dgesvd\n  vector_t s(k), superb(k);\n  matrix_t u(m, k), vt(k, n);\n  info = LAPACKE_zgesvd(LAPACK_COL_MAJOR, 'S', 'S', m, n, &a(0, 0), m, &s(0),\n                         &u(0, 0), m, &vt(0, 0), k, &superb(0));\n  std::cout << \"U:\\n\" << u << std::endl;\n  std::cout << \"S:\\n\" << s << std::endl;\n  std::cout << \"Vt:\\n\" << vt << std::endl;\n\n  // check correctness of SVD\n  matrix_t smat = matrix_t::Zero(k, k);\n  for (int i = 0; i < k; ++i) smat(i, i) = s(i);\n  matrix_t check = u * smat * vt;\n  std::cout << \"U * S * Vt:\\n\" << check << std::endl;\n  std::cout << \"| A - U * S * Vt | = \" << (mat - check).norm() << std::endl;\n}\n", "meta": {"hexsha": "54c685f7719a224d4767b9304043a1abed5e9ed8", "size": 1794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cxx/lapack/svd_c.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/cxx/lapack/svd_c.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/cxx/lapack/svd_c.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1764705882, "max_line_length": 88, "alphanum_fraction": 0.5451505017, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6458228170766732}}
{"text": "// Copyright John Maddock 2006.\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// test_gamma_dist.cpp\n\n// http://en.wikipedia.org/wiki/Gamma_distribution\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda366b.htm\n// Also:\n// Weisstein, Eric W. \"Gamma Distribution.\"\n// From MathWorld--A Wolfram Web Resource.\n// http://mathworld.wolfram.com/GammaDistribution.html\n\n#include <pch.hpp> // include directory libs/math/src/tr1/ is needed.\n\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\n#include <boost/test/test_exec_monitor.hpp> // Boost.Test\n#include <boost/test/floating_point_comparison.hpp>\n\n#include <boost/math/distributions/gamma.hpp>\n    using boost::math::gamma_distribution;\n#include <boost/math/tools/test.hpp>\n\n#include <iostream>\n   using std::cout;\n   using std::endl;\n   using std::setprecision;\n#include <limits>\n  using std::numeric_limits;\n\ntemplate <class RealType>\nRealType NaivePDF(RealType shape, RealType scale, RealType x)\n{\n   // Deliberately naive PDF calculator again which\n   // we'll compare our pdf function.  However some\n   // published values to compare against would be better....\n   using namespace std;\n   RealType result = log(x) * (shape - 1) - x / scale - boost::math::lgamma(shape) - log(scale) * shape;\n   return exp(result);\n}\n\ntemplate <class RealType>\nvoid check_gamma(RealType shape, RealType scale, RealType x, RealType p, RealType q, RealType tol)\n{\n   BOOST_CHECK_CLOSE(\n      ::boost::math::cdf(\n         gamma_distribution<RealType>(shape, scale),    // distribution.\n         x),                                            // random variable.\n         p,                                             // probability.\n         tol);                                          // %tolerance.\n   BOOST_CHECK_CLOSE(\n      ::boost::math::cdf(\n         complement(\n            gamma_distribution<RealType>(shape, scale), // distribution.\n            x)),                                        // random variable.\n         q,                                             // probability complement.\n         tol);                                          // %tolerance.\n   if(p < 0.999)\n   {\n      BOOST_CHECK_CLOSE(\n         ::boost::math::quantile(\n            gamma_distribution<RealType>(shape, scale),    // distribution.\n            p),                                            // probability.\n            x,                                             // random variable.\n            tol);                                          // %tolerance.\n   }\n   if(q < 0.999)\n   {\n      BOOST_CHECK_CLOSE(\n         ::boost::math::quantile(\n            complement(\n               gamma_distribution<RealType>(shape, scale), // distribution.\n               q)),                                        // probability complement.\n            x,                                             // random variable.\n            tol);                                          // %tolerance.\n   }\n   // PDF:\n   BOOST_CHECK_CLOSE(\n      boost::math::pdf(\n         gamma_distribution<RealType>(shape, scale),    // distribution.\n         x),                                            // random variable.\n         NaivePDF(shape, scale, x),                     // PDF\n         tol);                                          // %tolerance.\n}\n\ntemplate <class RealType>\nvoid test_spots(RealType)\n{\n   // Basic sanity checks\n   //\n   // 15 decimal places expressed as a persentage.\n   // The first tests use values generated by MathCAD,\n   // and should be accurate to around double precision.\n   //\n   RealType tolerance = (std::max)(RealType(5e-14f), std::numeric_limits<RealType>::epsilon() * 20) * 100;\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \" %\" << endl;\n\n   check_gamma(\n      static_cast<RealType>(0.5),\n      static_cast<RealType>(1),\n      static_cast<RealType>(0.5),\n      static_cast<RealType>(0.682689492137085),\n      static_cast<RealType>(1-0.682689492137085),\n      tolerance);\n   check_gamma(\n      static_cast<RealType>(2),\n      static_cast<RealType>(1),\n      static_cast<RealType>(0.5),\n      static_cast<RealType>(0.090204010431050),\n      static_cast<RealType>(1-0.090204010431050),\n      tolerance);\n   check_gamma(\n      static_cast<RealType>(40),\n      static_cast<RealType>(1),\n      static_cast<RealType>(10),\n      static_cast<RealType>(7.34163631456064E-13),\n      static_cast<RealType>(1-7.34163631456064E-13),\n      tolerance);\n\n   //\n   // Some more test data generated by the online\n   // calculator at http://espse.ed.psu.edu/edpsych/faculty/rhale/hale/507Mat/statlets/free/pdist.htm\n   // This has the advantage of supporting the scale parameter as well\n   // as shape, but has only a few digits accuracy, and produces\n   // some deeply suspect values if the shape parameter is < 1\n   // (it doesn't agree with MathCAD or this implementation).\n   // To be fair the incomplete gamma is tricky to get right in this area...\n   //\n   tolerance = 1e-5f * 100; // 5 decimal places as a persentage\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \" %\" << endl;\n\n   check_gamma(\n      static_cast<RealType>(2),\n      static_cast<RealType>(1)/5,\n      static_cast<RealType>(0.1),\n      static_cast<RealType>(0.090204),\n      static_cast<RealType>(1-0.090204),\n      tolerance);\n   check_gamma(\n      static_cast<RealType>(2),\n      static_cast<RealType>(1)/5,\n      static_cast<RealType>(0.5),\n      static_cast<RealType>(1-0.287298),\n      static_cast<RealType>(0.287298),\n      tolerance);\n   check_gamma(\n      static_cast<RealType>(3),\n      static_cast<RealType>(2),\n      static_cast<RealType>(1),\n      static_cast<RealType>(0.014388),\n      static_cast<RealType>(1-0.014388),\n      tolerance * 10); // one less decimal place in the test value\n   check_gamma(\n      static_cast<RealType>(3),\n      static_cast<RealType>(2),\n      static_cast<RealType>(5),\n      static_cast<RealType>(0.456187),\n      static_cast<RealType>(1-0.456187),\n      tolerance);\n\n\n    RealType tol2 = boost::math::tools::epsilon<RealType>() * 5 * 100;  // 5 eps as a persentage\n    gamma_distribution<RealType> dist(8, 3);\n    RealType x = static_cast<RealType>(0.125);\n    using namespace std; // ADL of std names.\n    // mean:\n    BOOST_CHECK_CLOSE(\n       mean(dist)\n       , static_cast<RealType>(8*3), tol2);\n    // variance:\n    BOOST_CHECK_CLOSE(\n       variance(dist)\n       , static_cast<RealType>(8*3*3), tol2);\n    // std deviation:\n    BOOST_CHECK_CLOSE(\n       standard_deviation(dist)\n       , sqrt(static_cast<RealType>(8*3*3)), tol2);\n    // hazard:\n    BOOST_CHECK_CLOSE(\n       hazard(dist, x)\n       , pdf(dist, x) / cdf(complement(dist, x)), tol2);\n    // cumulative hazard:\n    BOOST_CHECK_CLOSE(\n       chf(dist, x)\n       , -log(cdf(complement(dist, x))), tol2);\n    // coefficient_of_variation:\n    BOOST_CHECK_CLOSE(\n       coefficient_of_variation(dist)\n       , standard_deviation(dist) / mean(dist), tol2);\n    // mode:\n    BOOST_CHECK_CLOSE(\n       mode(dist)\n       , static_cast<RealType>(7 * 3), tol2);\n    // skewness:\n    BOOST_CHECK_CLOSE(\n       skewness(dist)\n       , 2 / sqrt(static_cast<RealType>(8)), tol2);\n    // kertosis:\n    BOOST_CHECK_CLOSE(\n       kurtosis(dist)\n       , 3 + 6 / static_cast<RealType>(8), tol2);\n    // kertosis excess:\n    BOOST_CHECK_CLOSE(\n       kurtosis_excess(dist)\n       , 6 / static_cast<RealType>(8), tol2);\n\n    BOOST_CHECK_CLOSE(\n       median(dist), static_cast<RealType>(23.007748327502412), // double precision test value\n       (std::max)(tol2, static_cast<RealType>(std::numeric_limits<double>::epsilon() * 2 * 100))); // 2 eps as persent\n    // Rely on default definition in derived accessors.\n\n} // template <class RealType>void test_spots(RealType)\n\nint test_main(int, char* [])\n{\n   // Basic sanity-check spot values.\n   // (Parameter value, arbitrarily zero, only communicates the floating point type).\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n  test_spots(0.0L); // Test long double.\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\n#endif\n#else\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\n      \"either because the long double overloads of the usual math functions are \"\n      \"not available at all, or because they are too inaccurate for these tests \"\n      \"to pass.</note>\" << std::cout;\n#endif\n\n   return 0;\n} // int test_main(int, char* [])\n\n\n/*\n\nOutput:\n\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_gamma_dist.exe\"\nRunning 1 test case...\nTolerance for type float is 0.000238419 %\nTolerance for type float is 0.001 %\nTolerance for type double is 5e-012 %\nTolerance for type double is 0.001 %\nTolerance for type long double is 5e-012 %\nTolerance for type long double is 0.001 %\nTolerance for type class boost::math::concepts::real_concept is 5e-012 %\nTolerance for type class boost::math::concepts::real_concept is 0.001 %\n*** No errors detected\n\n*/\n\n\n", "meta": {"hexsha": "4b58157931e7538a98615313c551e565bc12b606", "size": 9365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_gamma_dist.cpp", "max_stars_repo_name": "boostpro/boost-release", "max_stars_repo_head_hexsha": "017a2654a11f50e7f1c4a662aec2cf3cd9d4fb1c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T23:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T17:41:27.000Z", "max_issues_repo_path": "libs/math/test/test_gamma_dist.cpp", "max_issues_repo_name": "boostpro/boost-release", "max_issues_repo_head_hexsha": "017a2654a11f50e7f1c4a662aec2cf3cd9d4fb1c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/test/test_gamma_dist.cpp", "max_forks_repo_name": "boostpro/boost-release", "max_forks_repo_head_hexsha": "017a2654a11f50e7f1c4a662aec2cf3cd9d4fb1c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-11-08T01:56:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T09:02:49.000Z", "avg_line_length": 36.1583011583, "max_line_length": 118, "alphanum_fraction": 0.613027229, "num_tokens": 2336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6458228170766732}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/hypot.hpp>\n#include <test/unit/math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdHypot,Fvar) {\n  using stan::math::fvar;\n  using boost::math::hypot;\n  using std::isnan;\n\n  fvar<double> x(0.5,1.0);\n  fvar<double> y(2.3,2.0);\n\n  fvar<double> a = hypot(x, y);\n  EXPECT_FLOAT_EQ(hypot(0.5, 2.3), a.val_);\n  EXPECT_FLOAT_EQ((0.5 * 1.0 + 2.3 * 2.0) / hypot(0.5, 2.3), a.d_);\n\n  fvar<double> z(0.0,1.0);\n  fvar<double> w(-2.3,2.0);\n  fvar<double> b = hypot(x, z);\n\n  EXPECT_FLOAT_EQ(0.5, b.val_);\n  EXPECT_FLOAT_EQ(1.0, b.d_);\n\n  fvar<double> c = hypot(x, w);\n  isnan(c.val_);\n  isnan(c.d_);\n\n  fvar<double> d = hypot(z, x);\n  EXPECT_FLOAT_EQ(0.5, d.val_);\n  EXPECT_FLOAT_EQ(1.0, d.d_);\n}\n\nTEST(AgradFwdHypot,FvarFvarDouble) {\n  using stan::math::fvar;\n  using boost::math::hypot;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 3.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 6.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = hypot(x,y);\n\n  EXPECT_FLOAT_EQ(hypot(3.0,6.0), a.val_.val_);\n  EXPECT_FLOAT_EQ(3.0 / hypot(3.0,6.0), a.val_.d_);\n  EXPECT_FLOAT_EQ(6.0 / hypot(3.0,6.0), a.d_.val_);\n  EXPECT_FLOAT_EQ(-0.059628479, a.d_.d_);\n}\n\nstruct hypot_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return hypot(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdHypot, nan) {\n  hypot_fun hypot_;\n  test_nan_fwd(hypot_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "8d04861d6cc8b5c6b9ca04d112ba91c721f8c51d", "size": 1549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/hypot_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/hypot_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/hypot_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7794117647, "max_line_length": 67, "alphanum_fraction": 0.6371852808, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6458227865951349}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_MATH_UNITY_ROOT_HPP\n#define CRYPTO3_MATH_UNITY_ROOT_HPP\n\n#include <type_traits>\n#include <complex>\n\n#include <boost/math/constants/constants.hpp>\n#include <nil/crypto3/algebra/fields/params.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace math {\n\n            template<typename FieldType>\n            constexpr typename std::enable_if<std::is_same<typename FieldType::value_type, std::complex<double>>::value,\n                                              typename FieldType::value_type>::type\n                unity_root(const std::size_t n) {\n                const double PI = boost::math::constants::pi<double>();\n\n                return typename FieldType::value_type(cos(2 * PI / n), sin(2 * PI / n));\n            }\n\n            template<typename FieldType>\n            constexpr\n                typename std::enable_if<!std::is_same<typename FieldType::value_type, std::complex<double>>::value,\n                                        typename FieldType::value_type>::type\n                unity_root(const std::size_t n) {\n\n                typedef typename FieldType::value_type value_type;\n\n                const std::size_t logn = std::ceil(std::log2(n));\n\n                if (n != (1u << logn)) {\n                    throw std::invalid_argument(\"expected n == (1u << logn)\");\n                }\n                if (logn > algebra::fields::arithmetic_params<FieldType>::s) {\n                    throw std::invalid_argument(\"expected logn <= arithmetic_params<FieldType>::s\");\n                }\n\n                value_type omega = value_type(algebra::fields::arithmetic_params<FieldType>::root_of_unity);\n                for (std::size_t i = algebra::fields::arithmetic_params<FieldType>::s; i > logn; --i) {\n                    omega *= omega;\n                }\n\n                return omega;\n            }\n        }    // namespace math\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_MATH_UNITY_ROOT_HPP\n", "meta": {"hexsha": "86fa55fae1a5f3f7047c4aac50fbc797f46da3c3", "size": 3357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/math/algorithms/unity_root.hpp", "max_stars_repo_name": "NilFoundation/fft", "max_stars_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nil/crypto3/math/algorithms/unity_root.hpp", "max_issues_repo_name": "NilFoundation/fft", "max_issues_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/nil/crypto3/math/algorithms/unity_root.hpp", "max_forks_repo_name": "NilFoundation/fft", "max_forks_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5974025974, "max_line_length": 120, "alphanum_fraction": 0.6064938934, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6458082162012212}}
{"text": "#include \"edlib/EDP/ConstructSparseMat.hpp\"\n#include \"edlib/EDP/LocalHamiltonian.hpp\"\n#include \"utils.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n#include <unsupported/Eigen/KroneckerProduct>\n\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include <Spectra/SymEigsSolver.h>\n\n#include <catch2/catch.hpp>\n\n#include <algorithm>\n#include <cassert>\n#include <iostream>\n#include <random>\n\ntemplate<typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>\ntwoQubitOp(int N, int pos1, int pos2, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v1,\n           const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v2)\n{\n    using namespace Eigen;\n\n    assert(pos1 < pos2); // NOLINT\n\n    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> res(1, 1);\n    res(0, 0) = 1.0;\n\n    for(int i = 0; i < pos1; i++)\n    {\n        res = Eigen::kroneckerProduct(MatrixXd::Identity(2, 2), res).eval();\n    }\n\n    res = Eigen::kroneckerProduct(v1, res).eval();\n    for(int i = pos1 + 1; i < pos2; i++)\n    {\n        res = Eigen::kroneckerProduct(MatrixXd::Identity(2, 2), res).eval();\n    }\n    res = Eigen::kroneckerProduct(v2, res).eval();\n    for(int i = pos2 + 1; i < N; i++)\n    {\n        res = Eigen::kroneckerProduct(MatrixXd::Identity(2, 2), res).eval();\n    }\n    return res;\n}\n\ntemplate<typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>\nsingleQubitOp(int N, int pos, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v)\n{\n    using namespace Eigen;\n    using MatrixT = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\n    MatrixT res(1, 1);\n    res(0, 0) = 1.0;\n\n    for(int i = 0; i < pos; i++)\n    {\n        res = Eigen::kroneckerProduct(MatrixT::Identity(2, 2), res).eval();\n    }\n\n    res = Eigen::kroneckerProduct(v, res).eval();\n    for(int i = pos + 1; i < N; i++)\n    {\n        res = Eigen::kroneckerProduct(MatrixT::Identity(2, 2), res).eval();\n    }\n    return res;\n}\n\nclass GraphGenerator\n{\nprivate:\n    int numVertices_;\n    std::vector<std::pair<int, int>> allEdges_;\n    std::vector<int> allVertices_;\n\npublic:\n    explicit GraphGenerator(int numVertices) : numVertices_{numVertices}\n    {\n        for(int i = 0; i < numVertices - 1; ++i)\n        {\n            for(int j = i + 1; j < numVertices; ++j)\n            {\n                allEdges_.emplace_back(i, j);\n            }\n        }\n        for(int i = 0; i < numVertices_; ++i)\n        {\n            allVertices_.emplace_back(i);\n        }\n    }\n\n    template<typename RandomEngine>\n    std::vector<std::pair<int, int>> createRandomGraph(RandomEngine& re, int numEdges)\n    {\n        std::vector<std::pair<int, int>> edges = allEdges_;\n        std::shuffle(edges.begin(), edges.end(), re);\n        edges.resize(numEdges);\n        return edges;\n    }\n\n    template<typename RandomEngine> std::vector<int> createRandomVertexSet(RandomEngine& re, int n)\n    {\n        std::vector<int> v = allVertices_;\n        std::shuffle(v.begin(), v.end(), re);\n        v.resize(n);\n        return v;\n    }\n};\n\nconstexpr uint32_t N = 10;\nTEST_CASE(\"Test single qubit operators\", \"[LocalHamSingle]\")\n{\n    std::random_device rd;\n    std::default_random_engine re{rd()};\n    std::uniform_int_distribution<> uid(0, N - 1);\n    std::uniform_real_distribution<> urd;\n\n    using cx_double = std::complex<double>;\n\n    SECTION(\"Test constructing Pauli X\")\n    {\n        edp::LocalHamiltonian<double> lh(N, 2);\n        for(int n = 0; n < 100; ++n)\n        {\n            lh.clearTerms();\n            int idx = uid(re);\n            double val = urd(re);\n            lh.addOneSiteTerm(idx, val * getSX());\n            auto mat1 = Eigen::MatrixXd(edp::constructSparseMat<double>(1U << N, lh));\n            auto mat2 = singleQubitOp<double>(N, idx, val * getSX());\n            REQUIRE((mat1 - mat2).squaredNorm() < 1e-8);\n        }\n    }\n    SECTION(\"Test constructing Pauli Z\")\n    {\n        edp::LocalHamiltonian<double> lh(N, 2);\n        for(int n = 0; n < 100; ++n)\n        {\n            lh.clearTerms();\n            int idx = uid(re);\n            double val = urd(re);\n            lh.addOneSiteTerm(idx, val * getSZ());\n            auto mat1 = Eigen::MatrixXd(edp::constructSparseMat<double>(1U << N, lh));\n            auto mat2 = singleQubitOp<double>(N, idx, val * getSZ());\n            REQUIRE((mat1 - mat2).squaredNorm() < 1e-8);\n        }\n    }\n    SECTION(\"Test constructing Pauli Y\")\n    {\n        edp::LocalHamiltonian<cx_double> lh(N, 2);\n        for(int n = 0; n < 100; ++n)\n        {\n            lh.clearTerms();\n            int idx = uid(re);\n            double val = urd(re);\n            lh.addOneSiteTerm(idx, val * getSY());\n            auto mat1 = Eigen::MatrixXcd(edp::constructSparseMat<cx_double>(1U << N, lh));\n            auto mat2 = singleQubitOp<cx_double>(N, idx, val * getSY());\n            REQUIRE((mat1 - mat2).squaredNorm() < 1e-8);\n        }\n    }\n}\n\nTEST_CASE(\"Test 2-local Hamiltonians\", \"[LocalHam2loc]\")\n{\n    std::random_device rd;\n    std::mt19937_64 re{rd()};\n    std::uniform_int_distribution<> uid(0, N - 1);\n    std::uniform_int_distribution<> numEdgesRd(1, N * (N - 1) / 2);\n    std::uniform_real_distribution<> urd;\n\n    using cx_double = std::complex<double>;\n\n    GraphGenerator ggen{N};\n\n    SECTION(\"Random XYZ Hamiltonian\")\n    {\n        edp::LocalHamiltonian<double> lh(N, 2);\n\n        for(int n = 0; n < 10; ++n)\n        {\n            lh.clearTerms();\n            int numEdges = numEdgesRd(re);\n            auto edges = ggen.createRandomGraph(re, numEdges);\n\n            auto matEx = Eigen::MatrixXd(1U << N, 1U << N);\n            matEx.setZero();\n\n            for(const auto& edge : edges)\n            {\n                double v1 = urd(re);\n                double v2 = urd(re);\n                double v3 = urd(re);\n                lh.addTwoSiteTerm(edge, v1 * getSXX());\n                lh.addTwoSiteTerm(edge, v2 * getSYY());\n                lh.addTwoSiteTerm(edge, v3 * getSZZ());\n\n                matEx += v1 * twoQubitOp<double>(N, edge.first, edge.second, getSX(), getSX());\n                auto matYY = twoQubitOp<cx_double>(N, edge.first, edge.second, getSY(), getSY());\n                matEx += v2 * matYY.real();\n                matEx += v3 * twoQubitOp<double>(N, edge.first, edge.second, getSZ(), getSZ());\n            }\n            auto mat = Eigen::MatrixXd(edp::constructSparseMat<double>(1U << N, lh));\n            REQUIRE((mat - matEx).squaredNorm() < 1e-8);\n        }\n    }\n    SECTION(\"Random Field Ising Hamiltonian\")\n    {\n        edp::LocalHamiltonian<double> lh(N, 2);\n\n        for(int n = 0; n < 20; ++n)\n        {\n            lh.clearTerms();\n            int numEdges = numEdgesRd(re);\n            auto edges = ggen.createRandomGraph(re, numEdges);\n\n            auto matEx = Eigen::MatrixXd(1U << N, 1U << N);\n            matEx.setZero();\n\n            for(const auto& edge : edges)\n            {\n                double v = urd(re);\n                lh.addTwoSiteTerm(edge, v * getSZZ());\n\n                matEx += v * twoQubitOp<double>(N, edge.first, edge.second, getSZ(), getSZ());\n            }\n\n            auto numFields = uid(re);\n            auto vs = ggen.createRandomVertexSet(re, numFields);\n\n            for(auto v : vs)\n            {\n                double h1 = urd(re);\n                double h3 = urd(re);\n\n                lh.addOneSiteTerm(v, h1 * getSX());\n                lh.addOneSiteTerm(v, h3 * getSZ());\n\n                matEx += h1 * singleQubitOp<double>(N, v, getSX());\n                matEx += h3 * singleQubitOp<double>(N, v, getSZ());\n            }\n\n            auto mat = Eigen::MatrixXd(edp::constructSparseMat<double>(1U << N, lh));\n            REQUIRE((mat - matEx).squaredNorm() < 1e-8);\n        }\n    }\n}\n", "meta": {"hexsha": "392ea1c509a17a0761b8e2a9adb1d47660217544", "size": 7684, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_local_ham.cpp", "max_stars_repo_name": "cecri/ExactDiagonalization", "max_stars_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_local_ham.cpp", "max_issues_repo_name": "cecri/ExactDiagonalization", "max_issues_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_local_ham.cpp", "max_forks_repo_name": "cecri/ExactDiagonalization", "max_forks_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4920634921, "max_line_length": 99, "alphanum_fraction": 0.5467204581, "num_tokens": 2128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6458082134569397}}
{"text": "// File: vector_norm.cpp\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    typedef std::complex<double>  cdouble;\n    dense_vector<cdouble>         v(10000);\n\n    // Initialize vector\n    for (unsigned i= 0; i < size(v); i++)\n\tv[i]= cdouble(i+1, 10000-i);\n\n    std::cout << \"one_norm(v) is \" << one_norm(v)<< \"\\n\";\n    \n    std::cout << \"two_norm(v) is \" << two_norm(v)<< \"\\n\";\n    \n    std::cout << \"infinity_norm(v) is \" << infinity_norm(v)<< \"\\n\";\n    \n    // Unroll computation of two-norm to 6 independent statements\n    std::cout << \"two_norm<6>(v) is \" << two_norm<6>(v)<< \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "eacd809798a86854955532118c67312b6d72d855", "size": 666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/vector_norm.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/vector_norm.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/vector_norm.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 23.7857142857, "max_line_length": 67, "alphanum_fraction": 0.5720720721, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6457233967367652}}
{"text": "/** @file main.cpp Demonstrates arbitrary-precision factorial and Fibonacci\n  * functions using Boost.Multiprecision.\n  *\n  * @note This implementation uses output parameters to allow reuse of\n  * previously allocated memory.  The technique also supports the potential\n  * future use of custom allocators, since the caller of each function\n  * allocates and configures the result object.  Moreover, the use of in-place\n  * operators for assignments avoids the creation of unnecessary temporary\n  * objects.\n  *\n  * @todo Memoize functions.  They currently require O(n) time per call.\n  */\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <iostream>\n\nusing big_int = boost::multiprecision::cpp_int;\n\nusing std::swap;\n\nvoid factorial(big_int* r, int n)\n{\n    for (*r = 1; n > 1; --n) {\n        *r *= n;\n    }\n}\n\nvoid fibonacci(big_int* r, int n)\n{\n    *r = 1;\n    for (big_int s = 1; n > 0; --n) {\n        swap(*r, s);\n        s += *r;\n    }\n}\n\nint main()\n{\n    big_int r;\n    for (int i = 0; i < 100; ++i) {\n        factorial(&r, i);\n        std::cout << i << ' ' << r << ' ';\n        fibonacci(&r, i);\n        std::cout << r << '\\n';\n    }\n}\n", "meta": {"hexsha": "cdddf9cb00b81bc34da7009378127db91af6b200", "size": 1147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/control.cpp", "max_stars_repo_name": "jeffs/fac-fib", "max_stars_repo_head_hexsha": "53b93389f123c726e28424bf8b0c31058366317b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/control.cpp", "max_issues_repo_name": "jeffs/fac-fib", "max_issues_repo_head_hexsha": "53b93389f123c726e28424bf8b0c31058366317b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/control.cpp", "max_forks_repo_name": "jeffs/fac-fib", "max_forks_repo_head_hexsha": "53b93389f123c726e28424bf8b0c31058366317b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4042553191, "max_line_length": 78, "alphanum_fraction": 0.6129032258, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6456891666156742}}
{"text": "#include <iostream>\n#include <iomanip>\nusing namespace std;\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\nusing namespace Eigen;\n\n#include <pangolin/pangolin.h>\n\nstruct RotationMatrix\n{\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 TranslationVector\n{\n    Vector3d trans = Vector3d(0,0,0);\n};\n\nostream& operator << (ostream& out, const TranslationVector& t)\n{\n    out<<\"=[\"<<t.trans(0)<<','<<t.trans(1)<<','<<t.trans(2)<<\"]\";\n    return out;\n}\n\nistream& operator >> ( istream& in, TranslationVector& t)\n{\n    return in;\n}\n\nstruct QuaternionDraw\n{\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\nint main ( int argc, char** argv )\n{\n    pangolin::CreateWindowAndBind ( \"visualize geometry\", 1000, 600 );\n    glEnable ( GL_DEPTH_TEST );\n    pangolin::OpenGlRenderState s_cam (\n        pangolin::ProjectionMatrix ( 1000, 600, 420, 420, 500, 300, 0.1, 1000 ),\n        pangolin::ModelViewLookAt ( 3,3,3,0,0,0,pangolin::AxisY )\n    );\n    \n    const int UI_WIDTH = 500;\n    \n    pangolin::View& d_cam = pangolin::CreateDisplay().SetBounds(0.0, 1.0, pangolin::Attach::Pix(UI_WIDTH), 1.0, -1000.0f/600.0f).SetHandler(new pangolin::Handler3D(s_cam));\n    \n    // ui\n    pangolin::Var<RotationMatrix> rotation_matrix(\"ui.R\", RotationMatrix());\n    pangolin::Var<TranslationVector> translation_vector(\"ui.t\", TranslationVector());\n    pangolin::Var<TranslationVector> euler_angles(\"ui.rpy\", TranslationVector());\n    pangolin::Var<QuaternionDraw> quaternion(\"ui.q\", QuaternionDraw());\n    pangolin::CreatePanel(\"ui\")\n        .SetBounds(0.0, 1.0, 0.0, pangolin::Attach::Pix(UI_WIDTH));\n    \n    while ( !pangolin::ShouldQuit() )\n    {\n        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n        \n        d_cam.Activate( s_cam );\n        \n        pangolin::OpenGlMatrix matrix = s_cam.GetModelViewMatrix();\n        Matrix<double,4,4> m = matrix;\n        // m = m.inverse();\n        RotationMatrix R; \n        for (int i=0; i<3; i++)\n            for (int j=0; j<3; j++)\n                R.matrix(i,j) = m(j,i);\n        rotation_matrix = R;\n        \n        TranslationVector t;\n        t.trans = Vector3d(m(0,3), m(1,3), m(2,3));\n        t.trans = -R.matrix*t.trans;\n        translation_vector = t;\n        \n        TranslationVector euler;\n        euler.trans = R.matrix.transpose().eulerAngles(2,1,0);\n        euler_angles = euler;\n        \n        QuaternionDraw quat;\n        quat.q = Quaterniond(R.matrix);\n        quaternion = quat;\n        \n        glColor3f(1.0,1.0,1.0);\n        \n        pangolin::glDrawColouredCube();\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", "meta": {"hexsha": "a9ed43784938042ace7cd0c04ff7b555957058a2", "size": 3654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/visualizeGeometry/visualizeGeometry.cpp", "max_stars_repo_name": "Cc19245/slambook_mylearn", "max_stars_repo_head_hexsha": "7c589a80706d4268bf5d661a4f0f12890ec490bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5684.0, "max_stars_repo_stars_event_min_datetime": "2016-06-27T14:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:42:00.000Z", "max_issues_repo_path": "ch3/visualizeGeometry/visualizeGeometry.cpp", "max_issues_repo_name": "Cc19245/slambook_mylearn", "max_issues_repo_head_hexsha": "7c589a80706d4268bf5d661a4f0f12890ec490bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 265.0, "max_issues_repo_issues_event_min_datetime": "2016-11-08T09:00:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T12:46:39.000Z", "max_forks_repo_path": "ch3/visualizeGeometry/visualizeGeometry.cpp", "max_forks_repo_name": "Cc19245/slambook_mylearn", "max_forks_repo_head_hexsha": "7c589a80706d4268bf5d661a4f0f12890ec490bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3243.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T12:36:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T20:48:41.000Z", "avg_line_length": 27.2686567164, "max_line_length": 172, "alphanum_fraction": 0.5730706076, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6456891617028255}}
{"text": "//  (C) Copyright Nick Thompson 2018.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_TOOLS_BIVARIATE_STATISTICS_HPP\n#define BOOST_MATH_TOOLS_BIVARIATE_STATISTICS_HPP\n\n#include <iterator>\n#include <tuple>\n#include <boost/math/tools/assert.hpp>\n#include <boost/math/tools/header_deprecated.hpp>\n\nBOOST_MATH_HEADER_DEPRECATED(\"<boost/math/statistics/bivariate_statistics.hpp>\");\n\nnamespace boost{ namespace math{ namespace tools {\n\ntemplate<class Container>\nauto means_and_covariance(Container const & u, Container const & v)\n{\n    using Real = typename Container::value_type;\n    using std::size;\n    BOOST_MATH_ASSERT_MSG(size(u) == size(v), \"The size of each vector must be the same to compute covariance.\");\n    BOOST_MATH_ASSERT_MSG(size(u) > 0, \"Computing covariance requires at least one sample.\");\n\n    // See Equation III.9 of \"Numerically Stable, Single-Pass, Parallel Statistics Algorithms\", Bennet et al.\n    Real cov = 0;\n    Real mu_u = u[0];\n    Real mu_v = v[0];\n\n    for(size_t i = 1; i < size(u); ++i)\n    {\n        Real u_tmp = (u[i] - mu_u)/(i+1);\n        Real v_tmp = v[i] - mu_v;\n        cov += i*u_tmp*v_tmp;\n        mu_u = mu_u + u_tmp;\n        mu_v = mu_v + v_tmp/(i+1);\n    }\n\n    return std::make_tuple(mu_u, mu_v, cov/size(u));\n}\n\ntemplate<class Container>\nauto covariance(Container const & u, Container const & v)\n{\n    auto [mu_u, mu_v, cov] = boost::math::tools::means_and_covariance(u, v);\n    return cov;\n}\n\ntemplate<class Container>\nauto correlation_coefficient(Container const & u, Container const & v)\n{\n    using Real = typename Container::value_type;\n    using std::size;\n    BOOST_MATH_ASSERT_MSG(size(u) == size(v), \"The size of each vector must be the same to compute covariance.\");\n    BOOST_MATH_ASSERT_MSG(size(u) > 0, \"Computing covariance requires at least two samples.\");\n\n    Real cov = 0;\n    Real mu_u = u[0];\n    Real mu_v = v[0];\n    Real Qu = 0;\n    Real Qv = 0;\n\n    for(size_t i = 1; i < size(u); ++i)\n    {\n        Real u_tmp = u[i] - mu_u;\n        Real v_tmp = v[i] - mu_v;\n        Qu = Qu + (i*u_tmp*u_tmp)/(i+1);\n        Qv = Qv + (i*v_tmp*v_tmp)/(i+1);\n        cov += i*u_tmp*v_tmp/(i+1);\n        mu_u = mu_u + u_tmp/(i+1);\n        mu_v = mu_v + v_tmp/(i+1);\n    }\n\n    // If both datasets are constant, then they are perfectly correlated.\n    if (Qu == 0 && Qv == 0)\n    {\n        return Real(1);\n    }\n    // If one dataset is constant and the other isn't, then they have no correlation:\n    if (Qu == 0 || Qv == 0)\n    {\n        return Real(0);\n    }\n\n    // Make sure rho in [-1, 1], even in the presence of numerical noise.\n    Real rho = cov/sqrt(Qu*Qv);\n    if (rho > 1) {\n        rho = 1;\n    }\n    if (rho < -1) {\n        rho = -1;\n    }\n    return rho;\n}\n\n}}}\n#endif\n", "meta": {"hexsha": "40f51dcc383770a5b7a0b323a6896036bffff017", "size": 2898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/tools/bivariate_statistics.hpp", "max_stars_repo_name": "mscastanho/math", "max_stars_repo_head_hexsha": "e149c340089e937949ea9566f88df30428d119b8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "include/boost/math/tools/bivariate_statistics.hpp", "max_issues_repo_name": "mscastanho/math", "max_issues_repo_head_hexsha": "e149c340089e937949ea9566f88df30428d119b8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "include/boost/math/tools/bivariate_statistics.hpp", "max_forks_repo_name": "mscastanho/math", "max_forks_repo_head_hexsha": "e149c340089e937949ea9566f88df30428d119b8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 29.2727272727, "max_line_length": 113, "alphanum_fraction": 0.626984127, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6456891565290201}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nnamespace dr {\n\n/// Interpolate linearly between two vectors.\n/**\n * At factor 0, the first vector is returned, at factor 1 the second.\n */\ntemplate<typename Derived1, typename Derived2>\nauto interpolateVector(\n\tEigen::MatrixBase<Derived1> const & a, ///< The first vector.\n\tEigen::MatrixBase<Derived2> const & b, ///< The second vector.\n\tdouble factor                          ///< The interpolation factor.\n) -> decltype(a + factor * (b - a)) {\n\treturn a + factor * (b - a);\n}\n\n/// Interpolate spherical linearly between two rotations.\n/**\n * At factor 0, the first rotation is returned, at factor 1 the second.\n */\ntemplate<typename T>\nEigen::AngleAxis<T> interpolateRotation(\n\tEigen::AngleAxis<T> const & a, ///< The first rotation.\n\tEigen::AngleAxis<T> const & b, ///< The second rotation.\n\tdouble factor                  ///< The interpolation factor.\n) {\n\tEigen::AngleAxis<T> difference = b * a.inverse();\n\tdifference.angle() *= factor;\n\treturn difference * a;\n}\n\n/// Interpolate spherical linearly between two rotations.\n/**\n * At factor 0, the first rotation is returned, at factor 1 the second.\n */\ntemplate<typename T>\nEigen::Quaternion<T> interpolateRotation(\n\tEigen::Quaternion<T> const & a, ///< The first rotation.\n\tEigen::Quaternion<T> const & b, ///< The second rotation.\n\tdouble factor                   ///< The interpolation factor.\n) {\n\treturn a.slerp(factor, b);\n}\n\n/// Interpolate spherical linearly between two rotations.\n/**\n * At factor 0, the first rotation is returned, at factor 1 the second.\n */\ntemplate<typename Derived1, typename Derived2>\nEigen::Quaternion<typename Eigen::MatrixBase<Derived1>::Scalar> interpolateRotation(\n\tEigen::MatrixBase<Derived1> const & a, ///< The first rotation.\n\tEigen::MatrixBase<Derived2> const & b, ///< The second rotation.\n\tdouble factor                          ///< The interpolation factor.\n) {\n\tusing Scalar1 = typename Eigen::MatrixBase<Derived1>::Scalar;\n\tusing Scalar2 = typename Eigen::MatrixBase<Derived2>::Scalar;\n\treturn interpolateRotation<Scalar1>(Eigen::Quaternion<Scalar1>(a), Eigen::Quaternion<Scalar2>(b), factor);\n}\n\n/// Interpolate spherical linearly between two isometries.\n/**\n * At factor 0, the first isometry is returned, at factor 1 the second.\n * The translation will be interpolated linearly and the rotation spherial linearly.\n */\nEigen::Isometry3d interpolateIsometry(\n\tEigen::Isometry3d const & a, ///< The first isometry.\n\tEigen::Isometry3d const & b, ///< The second isometry.\n\tdouble factor                ///< The interpolation factor.\n) {\n\treturn Eigen::Translation3d{interpolateVector(a.translation(), b.translation(), factor)}\n\t\t* interpolateRotation(Eigen::Quaterniond{a.rotation()}, Eigen::Quaterniond{b.rotation()}, factor);\n}\n\n}\n", "meta": {"hexsha": "e9105d39137de51a7332150088ed7a62a70b0fa7", "size": 2786, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dr_eigen/interpolate.hpp", "max_stars_repo_name": "delftrobotics/dr_eigen", "max_stars_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-06-02T14:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-02T14:14:37.000Z", "max_issues_repo_path": "include/dr_eigen/interpolate.hpp", "max_issues_repo_name": "delftrobotics/dr_eigen", "max_issues_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dr_eigen/interpolate.hpp", "max_forks_repo_name": "delftrobotics/dr_eigen", "max_forks_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1818181818, "max_line_length": 107, "alphanum_fraction": 0.6966977746, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6456891516161717}}
{"text": "/*!\n * Created by leanne on 3/20/21.\n */\n#include \"HydraulicLib/ConvEigen.h\"\n#include <Eigen/QR>\n#include <fstream>\n#include <iostream>\n#include <sstream> // std::stringstream\n#include <stdexcept> // std::runtime_error\n#include <utility> // std::pair\n#include <string>\n#include <vector>\n//#include \"include/read_write.h\"\n//#include \"include/conv.h\"\n#include \"HydraulicLib/NetworkSolve.h\"\nusing Eigen::VectorXd;\nusing std::cerr;\nusing std::cout;\n\nMatrixXd calculateSoln() {\n    MatrixXd data;\n\n    // load the matrix from the file\n    // data = openData(\"/home/leanne/CLionProjects/SimpleHydraulicNetwork/inputs/matrix.csv\");\n    data = openData(\"inputs/matrix.csv\");\n    VectorXd Demand_A = data.col(0);\n    VectorXd Demand_B = data.col(1);\n    VectorXd Demand_C = data.col(2);\n    VectorXd Demand_D = data.col(3);\n    VectorXd Demand_E = data.col(4);\n    VectorXd Demand_F = data.col(5);\n    VectorXd Demand_z0(8760);\n    Demand_z0.setZero();\n    VectorXd Demand_z4(8760);\n    Demand_z4.setZero();\n\n    Demand_A = Demand_A/4.2/15;\n    Demand_B = Demand_B/4.2/15;\n    Demand_C = Demand_C/4.2/15;\n    Demand_D = Demand_D/4.2/15;\n    Demand_E = Demand_E/4.2/15;\n    Demand_F = Demand_F/4.2/15;\n\n    //   cerr << Demand_C.size() << \"\\n\";\n    MatrixXd B(8760, 8);\n    B << Demand_z0, Demand_C, Demand_B, Demand_D, Demand_z4, Demand_A, Demand_E, Demand_F;\n    //   cerr << B << \"\\n\";\n\n    MatrixXd Q = MatrixXd::Zero(8760, 8);\n    Q.col(1) = Demand_C;\n    Q.col(2) = Demand_B;\n    Q.col( 3) = Demand_D;\n    Q.col(4) = Demand_A + Demand_E + Demand_F;\n    Q.col(5) = Demand_A;\n    Q.col(6) = Demand_E;\n    Q.col(7) = Demand_F;\n    Q.col(0) = Demand_C + Demand_B + Demand_D + Demand_A + Demand_E + Demand_F;\n    return Q;\n}\nvoid NetworkSolve() {\n    auto result = calculateSoln();\n    saveData(\"outputs/flowQ.csv\", result);\n}\n\n/*\n * Our accuracy are good but we are getting some systematic error as the solutions from Matlab and C++ deviate.\n * This might due to the non-empty nullspace. If our matrix is rank deficient the solution may have an arbitrary large component added in the null space.\n * In other words if Ax = b then the computed solution might be x' = x* + x0, where A*x0 = 0, so r = A*x'-b = 0.\n * So, we could have perfect accuracy but still produce different solutions due to the non-empty nullspace.\n * If my system is well-conditioned, I will not need to worry about that.  If it isn't, it might help explain the systematic error I'm getting.\n *\n */\n\n/*\n * Precision could be lost when reading/writing CSV file\n * Residual error (or existence of solutions)\n * Rank deficiency\n * Well conditionness\n */\n\n", "meta": {"hexsha": "923d1d1f2c4e2198035bda65b71d8c395697798d", "size": 2613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HydraulicLib/src/NetworkSolve.cpp", "max_stars_repo_name": "leannejdong/SimpleHydraulicNetwork", "max_stars_repo_head_hexsha": "9cf7c9c7093e3758c669153a667a61f8589a2006", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-16T09:37:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T09:37:24.000Z", "max_issues_repo_path": "HydraulicLib/src/NetworkSolve.cpp", "max_issues_repo_name": "leannejdong/SimpleHydraulicNetwork", "max_issues_repo_head_hexsha": "9cf7c9c7093e3758c669153a667a61f8589a2006", "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": "HydraulicLib/src/NetworkSolve.cpp", "max_forks_repo_name": "leannejdong/SimpleHydraulicNetwork", "max_forks_repo_head_hexsha": "9cf7c9c7093e3758c669153a667a61f8589a2006", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-19T19:03:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T19:03:17.000Z", "avg_line_length": 32.2592592593, "max_line_length": 153, "alphanum_fraction": 0.6735553004, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.645684267756399}}
{"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_LOG10_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_LOG10_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing log10 capabilities\n\n    base ten logarithm function. For integer input types log10 return the truncation\n    of the real result.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = log10(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = log(x)/log(10);\n    @endcode\n\n    - log10(x) return Nan for negative enties (peculiarly Mzero\n    for floating numbers).\n\n    @par Decorators\n\n    std_ for floating entries\n\n    @see log, log2, log1p, is_negative, Mzero\n\n  **/\n  Value log10(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/log10.hpp>\n#include <boost/simd/function/simd/log10.hpp>\n\n#endif\n", "meta": {"hexsha": "ca01be69e3b9526d122ed58a5659248740f9cac6", "size": 1269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/log10.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/log10.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/log10.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.8793103448, "max_line_length": 100, "alphanum_fraction": 0.5941686367, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6456842652322471}}
{"text": "#include \"OpenICV/Core/icvFunction.h\"\r\n#include \"OpenICV/Core/icvFunctionFactory.h\"\r\n#include \"OpenICV/Core/icvSubscriber.h\"\r\n#include \"OpenICV/Core/icvPublisher.h\"\r\n#include \"OpenICV/Basis/icvPrimitiveData.hxx\"\r\n\r\n#include <boost/thread/thread.hpp>\r\n\r\nusing namespace icv;\r\nusing namespace icv::core;\r\n\r\nclass PolynomialFunction : public icvFunction\r\n{\r\npublic:\r\n    PolynomialFunction(icv_shared_ptr<const icvMetaData> info) : icvFunction(1, 1, info)\r\n    {\r\n        if (_information.Contains(\"coefficients\"))\r\n        {\r\n            auto arr = _information.GetArray(\"coefficients\");\r\n            for (int i = 0; i < arr.Size(); i++)\r\n                _coeffs.push_back(arr.GetDecimal(i));\r\n            _information.Remove(\"coefficients\");\r\n        }\r\n    }\r\n    PolynomialFunction() : PolynomialFunction(ICV_NULLPTR) {}\r\n\r\n\r\n\r\n    virtual void Execute(icvDataObject** inData, icvDataObject** outData) ICV_OVERRIDE\r\n    {\r\n        double data = *static_cast<icvDoubleData*>(inData[0]);\r\n        double result = data;\r\n        for (double coeff : _coeffs) result = result * coeff + data;\r\n        outData[0]->As<icvDoubleData>() = result;\r\n\r\n        ICV_LOG_TRACE << \"Filter Data from \" << data << \" to \" << result;\r\n    }\r\nprivate:\r\n    std::vector<double> _coeffs;\r\n};\r\n\r\nICV_REGISTER_FUNCTION(PolynomialFunction)\r\n\r\n", "meta": {"hexsha": "ca3c147d0c09e0729000e0e8ba5d54ceb85e470e", "size": 1319, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "Branch/Deprecated/Deprecated Examples/SimplePipeline/PolynomialFunction.hxx", "max_stars_repo_name": "Tsinghua-OpenICV/OpenICV", "max_stars_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-12-17T08:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T03:13:10.000Z", "max_issues_repo_path": "Branch/Deprecated/Deprecated Examples/SimplePipeline/PolynomialFunction.hxx", "max_issues_repo_name": "Tsinghua-OpenICV/OpenICV", "max_issues_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Branch/Deprecated/Deprecated Examples/SimplePipeline/PolynomialFunction.hxx", "max_forks_repo_name": "Tsinghua-OpenICV/OpenICV", "max_forks_repo_head_hexsha": "37bf88122414d0c766491460248f61fa1a9fd78c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-12-17T08:17:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T15:53:57.000Z", "avg_line_length": 29.9772727273, "max_line_length": 89, "alphanum_fraction": 0.6436694466, "num_tokens": 320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6456842601839433}}
{"text": "//\n// This file is part of the Oxford RSE CMake Course\n// (https://github.com/OxfordRSE/CMakeCourse) which is released under the MIT\n// license. See accompanying LICENSE for copyright notice and full details.\n//\n\n\n#include \"MyLibrary.hpp\"\n\n#include \"Exception.hpp\"\n\n#include <boost/math/special_functions/prime.hpp>\n\nnamespace cpp_template {\n\nint get_nth_prime(int n) {\n  namespace bm = boost::math;\n  namespace b = boost;\n\n  if (n < 0) {\n    throw Exception(\"non-negative argument required\");\n  }\n\n  if (static_cast<b::uint32_t>(n) > bm::max_prime) {\n    throw Exception(\"argument less than \" + std::to_string(bm::max_prime) +\n                    \" required\");\n  }\n\n  return static_cast<int>(boost::math::prime(static_cast<unsigned>(n)));\n}\n\n} // namespace cpp_template\n", "meta": {"hexsha": "e0da1ad3530e5ac7e1a82cf1507a494e6fc65657", "size": 771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MyLibrary.cpp", "max_stars_repo_name": "OxfordRSE/CMakeCourse", "max_stars_repo_head_hexsha": "ff5d2a2a7707a1d45a6201ff6f351c74b11f7a94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MyLibrary.cpp", "max_issues_repo_name": "OxfordRSE/CMakeCourse", "max_issues_repo_head_hexsha": "ff5d2a2a7707a1d45a6201ff6f351c74b11f7a94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MyLibrary.cpp", "max_forks_repo_name": "OxfordRSE/CMakeCourse", "max_forks_repo_head_hexsha": "ff5d2a2a7707a1d45a6201ff6f351c74b11f7a94", "max_forks_repo_licenses": ["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.3636363636, "max_line_length": 77, "alphanum_fraction": 0.6874189364, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6456842600778291}}
{"text": "#include \"Constraint.h\"\n#include \"AttachmentConstraint.h\"\n#include <Eigen/Dense>\n#include <iostream>\nusing namespace FEM;\nAttachmentConstraint::\nAttachmentConstraint(const double& stiffness,int i0,const Eigen::Vector2d& p)\n\t:Constraint(stiffness),mi0(i0),mp(p)\n{\n\n}\n\ndouble\nAttachmentConstraint::\nEvalPotentialEnergy(const Eigen::VectorXd& x)\n{\n\tEigen::Vector2d x_p0 = x.block<2,1>(mi0*2,0) - mp;\n\n    return 0.5*mStiffness*x_p0.squaredNorm();\n}\nvoid\nAttachmentConstraint::\nEvalGradient(const Eigen::VectorXd& x, Eigen::VectorXd& gradient)\n{\n\tEigen::Vector2d x_p0 = x.block<2,1>(mi0*2,0) - mp;\n\tgradient.block<2,1>(mi0*2,0) += mStiffness*x_p0;\n}\n\nvoid\nAttachmentConstraint::\nEvalHessian(const Eigen::VectorXd& x, const Eigen::VectorXd& dx, Eigen::VectorXd& dg)\n{\n\t//Compute H*x\n\tdg.block<2,1>(mi0*2,0) += mStiffness*dx.block<2,1>(mi0*2,0);\n}\n\nvoid\nAttachmentConstraint::\nEvaluateDVector(int index, const Eigen::VectorXd& x,Eigen::VectorXd& d)\n{\n\td.block<2,1>(2*index,0) = mp;\n}\nvoid\nAttachmentConstraint::\nEvaluateJMatrix(int index, std::vector<Eigen::Triplet<double>>& J_triplets)\n{\n\tJ_triplets.push_back(Eigen::Triplet<double>(2*mi0, 2*index, mStiffness));\n\tJ_triplets.push_back(Eigen::Triplet<double>(2*mi0+1, 2*index+1, mStiffness));\n}\nvoid\nAttachmentConstraint::\nEvaluateLMatrix(std::vector<Eigen::Triplet<double>>& L_triplets)\n{\n\tL_triplets.push_back(Eigen::Triplet<double>(2*mi0+0, 2*mi0+0, mStiffness));\n\tL_triplets.push_back(Eigen::Triplet<double>(2*mi0+1, 2*mi0+1, mStiffness));\n}\n\nint\nAttachmentConstraint::\nGetDof()\n{\n\treturn 1;\n}\nint\nAttachmentConstraint::\nGetNumHessianTriplets()\n{\n\treturn 2;\n}\n\n\nConstraintType \nAttachmentConstraint::\nGetType()\t   \n{\n\treturn ConstraintType::ATTACHMENT; \n}\nvoid \nAttachmentConstraint::\nAddOffset(const int& offset) \n{\n\tmi0+=offset;\n}\n\nEigen::Vector2d& \nAttachmentConstraint::\nGetP() \n{\n\treturn mp;\n}\nint&\t\t\t \nAttachmentConstraint::\nGetI0()\t   \n{\n\treturn mi0;\n}", "meta": {"hexsha": "40ebafef6942e74530d0035b4d059f0d942148d3", "size": 1908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fem2D/Constraint/AttachmentConstraint.cpp", "max_stars_repo_name": "snumrl/volcon2D", "max_stars_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fem2D/Constraint/AttachmentConstraint.cpp", "max_issues_repo_name": "snumrl/volcon2D", "max_issues_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fem2D/Constraint/AttachmentConstraint.cpp", "max_forks_repo_name": "snumrl/volcon2D", "max_forks_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.875, "max_line_length": 85, "alphanum_fraction": 0.7316561845, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6456842599717146}}
{"text": "// =========================================================================\n// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co)\n// =========================================================================\n\n#include <iostream>\n\n#include <boost/program_options.hpp>\n\n#include <PUJ_ML/Helpers/CSV.h>\n#include <PUJ_ML/Model/Linear.h>\n#include <PUJ_ML/Optimizer/GradientDescent.h>\n\n// -- Types\nusing TScalar = double;\nusing TModel = PUJ_ML::Model::Linear< TScalar >;\nusing TMatrix = TModel::TMatrix;\nnamespace po = boost::program_options;\n\n// -- Main --\nint main( int argc, char** argv )\n{\n  std::string csv = \"[NO INPUT FILE]\";\n  TScalar alpha = 1e-2;\n  TScalar lambda = 0;\n  TScalar epsilon = std::numeric_limits< TScalar >::epsilon( );\n  unsigned long long epochs = 10000;\n  unsigned long long debug_step = 100;\n  bool use_LASSO = false;\n\n  po::options_description desc( \"Allowed parameters\" );\n  desc.add_options( )\n    ( \"help,h\", \"Help message\" )\n    ( \"alpha,a\", po::value( &alpha )->default_value( alpha ), \"Learning rate\" )\n    ( \"lambda,l\", po::value( &lambda )->default_value( lambda ), \"Regularization\" )\n    ( \"LASSO\", po::bool_switch( &use_LASSO )->default_value( use_LASSO ), \"Use LASSO?\" )\n    ( \"epsilon,e\", po::value( &epsilon )->default_value( epsilon ), \"Epsilon\" )\n    ( \"epochs\", po::value( &epochs )->default_value( epochs ), \"Epochs\" )\n    ( \"debug_step\", po::value( &debug_step )->default_value( debug_step ), \"Debug step\" )\n    ( \"csv\", po::value( &csv )->default_value( csv ), \"Input file\" )\n    ;\n\n  po::variables_map vm;\n  po::store( po::parse_command_line( argc, argv, desc ), vm );\n  po::notify( vm );\n  if( vm.count( \"help\" ) )\n  {  \n    std::cerr << desc << std::endl;\n    return( EXIT_FAILURE );\n  } // end if\n\n  auto D = PUJ_ML::Helpers::CSV::Read< TMatrix >( csv, true, \",\" );\n  unsigned long long p = 1;\n  unsigned long long m = D.rows( );\n  unsigned long long n = D.cols( ) - p;\n  TMatrix X = D.block( 0, 0, m, n );\n  TMatrix Y = D.block( 0, n, m, p );\n\n  TModel model;\n  model.SetParameters( TModel::TCol::Zero( n + 1 ) );\n  TModel::Cost cost( &model, X, Y );\n\n  PUJ_ML::Optimizer::GradientDescent< TModel > opt;\n  opt.SetCost( cost );\n  opt.SetLearningRate( alpha );\n  opt.SetRegularizationCoefficient( lambda );\n  if( use_LASSO ) opt.SetRegularizationToLASSO( );\n  else            opt.SetRegularizationToRidge( );\n  opt.SetEpsilon( epsilon );\n  opt.SetNumberOfEpochs( epochs );\n  opt.SetDebugStep( debug_step );\n\n  TScalar final_cost;\n  unsigned long long final_epochs;\n  opt.SetDebug(\n    [&]( unsigned long long i, TScalar J, bool show ) -> bool\n    {\n      if( show )\n        std::cout << i << \" \" << J << std::endl;\n      final_cost = J;\n      final_epochs = i;\n      return( false );\n    }\n    );\n  opt.Fit( );\n\n  std::cout << \"---------------------\" << std::endl;\n  std::cout << \"Fitted model : \" << model << std::endl;\n  std::cout << \"Final cost   : \" << final_cost << std::endl;\n  std::cout << \"Final epochs : \" << final_epochs << std::endl;\n  std::cout << \"---------------------\" << std::endl;\n\n  /* TODO\n     std::cout << X.colwise( ).minCoeff( ) << std::endl;\n     std::cout << X.colwise( ).maxCoeff( ) << std::endl;\n     TModel::TCol L = TModel::TCol::LinSpaced( 100, -10, 10 );\n  */\n\n  return( EXIT_SUCCESS );\n}\n\n// eof - $RCSfile$\n", "meta": {"hexsha": "134bbd9836996bed9f18067c9ac6f88450121a97", "size": 3294, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "examples/LinearModel_FitGradientDescent_00.cxx", "max_stars_repo_name": "florez-l/PUJ_ML", "max_stars_repo_head_hexsha": "ee634d798fcf26e0b56ee804012a4eca9a997c7f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-01T09:20:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:16:37.000Z", "max_issues_repo_path": "examples/LinearModel_FitGradientDescent_00.cxx", "max_issues_repo_name": "florez-l/PUJ_ML", "max_issues_repo_head_hexsha": "ee634d798fcf26e0b56ee804012a4eca9a997c7f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/LinearModel_FitGradientDescent_00.cxx", "max_forks_repo_name": "florez-l/PUJ_ML", "max_forks_repo_head_hexsha": "ee634d798fcf26e0b56ee804012a4eca9a997c7f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:38:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T23:17:44.000Z", "avg_line_length": 32.2941176471, "max_line_length": 89, "alphanum_fraction": 0.5783242259, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6456721834427387}}
{"text": "/**\n * @file radauthreetimestepping.cc\n * @brief NPDE homework RadauThreeTimestepping\n * @author Erick Schulz, edited by Oliver Rietmann\n * @date 08/04/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"radauthreetimestepping.h\"\n\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <iostream>\n#include <unsupported/Eigen/KroneckerProduct>\n\nnamespace RadauThreeTimestepping {\n\n/**\n * @brief Implementation of the right hand side (time dependent) source vector\n * for the parabolic heat equation\n * @param dofh A reference to the DOFHandler\n * @param time The time at which to evaluate the source vector\n * @returns The source vector at time `time`\n */\n/* SAM_LISTING_BEGIN_1 */\nEigen::VectorXd rhsVectorheatSource(const lf::assemble::DofHandler &dofh,\n                                    double time) {\n  // Dimension of finite element space\n  const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n  // Right-hand side vector has to be set to zero initially\n  Eigen::VectorXd phi(N_dofs);\n#if SOLUTION\n  // Functor for computing the source function at 2d coordinates\n  auto f = [time](Eigen::Vector2d x) -> double {\n    const double PI = 3.14159265358979323846;\n    Eigen::Vector2d v(std::cos(time * PI), std::sin(time * PI));\n    return ((x - 0.5 * v).norm() < 0.5) ? 1.0 : 0.0;\n  };\n  auto mesh_p = dofh.Mesh();  // pointer to current mesh\n  phi.setZero();\n\n  /* Assembling right-hand side source vector */\n  // Initialize object taking care of local computations on all cells.\n  TrapRuleLinFEElemVecProvider<decltype(f)> elvec_builder(f);\n  // Computing right hand side vector\n  // Invoke assembly on cells (codim == 0 as first agrument)\n  lf::assemble::AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n  /* Enforce the zero Dirichlet boundary conditions */\n  // Obtain an array of boolean flags for the vertices of the mesh: 'true'\n  // indicates that the vertex lies on the boundary. This predicate will\n  // guarantee that the computations are carried only on the boundary vertices\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 2)};\n  // Creating predicate that will guarantee that the computations are carried\n  // only on the vertices of the mesh using the boundary flags\n  auto vertices_predicate =\n      [&bd_flags](const lf::mesh::Entity &vertex) -> bool {\n    return bd_flags(vertex);\n  };\n  // Assigning zero to the boundary values of phi\n  for (const lf::mesh::Entity *vertex : mesh_p->Entities(2)) {\n    if (bd_flags(*vertex)) {\n      auto dof_idx = dofh.GlobalDofIndices(*vertex);\n      LF_ASSERT_MSG(\n          dofh.NumLocalDofs(*vertex) == 1,\n          \"Too many global indices were returned for a vertex entity!\");\n      phi(dof_idx[0]) = 0.0;\n    }\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return phi;\n}\n/* SAM_LISTING_END_1 */\n\n/**\n * @brief Heat evolution solver: the solver obtains the\n * discrete evolution operator from the Radau3MOLTimestepper class and\n * repeatedly iterates its applicaiton starting from the initial condition\n * @param dofh The DOFHandler object\n * @param m is total number of steps until final time final_time (double)\n * @param final_time The duration for which to solve the PDE\n * @returns The solution at the final timestep\n */\n/* SAM_LISTING_BEGIN_6 */\nEigen::VectorXd solveHeatEvolution(const lf::assemble::DofHandler &dofh,\n                                   unsigned int m, double final_time) {\n  Eigen::VectorXd discrete_heat_sol(dofh.NumDofs());\n#if SOLUTION\n  double tau = final_time / m;                          // step size\n  const lf::uscalfe::size_type N_dofs(dofh.NumDofs());  // dim. of FE space\n\n  std::cout << \"*********************************************************\"\n            << std::endl;\n  std::cout << \"\\n>>> SolveHeatEvolution: m = \" << m << \", N = \" << N_dofs\n            << std::endl;\n  /* Setting up the problem information */\n  // Precomputing the required data for the Runge-Kutta method\n  // Assemble the Runge-Kutta Radau IIA 2-stages method solver (order 3)\n  Radau3MOLTimestepper radau_solver(dofh);\n  // Starting with the zero initial condition vector\n  Eigen::VectorXd discrete_solution_cur =\n      radau_solver.discreteEvolutionOperator(0.0, tau,\n                                             Eigen::VectorXd::Zero(N_dofs));\n\n  std::cout << \"\\n>> Iterating the action of discreteEvolutionOperator\"\n            << std::endl;\n  /* Evolving the parabolic heat system */\n  // While less elegant, we use a current and next step solution vector in the\n  // iteration to stay away from potential harming aliasing effects of putting\n  // an Eigen::Vector on both sides of an assignment statement.\n  Eigen::VectorXd discrete_solution_next;\n  for (int i = 1; i < m; i++) {\n    discrete_solution_next = radau_solver.discreteEvolutionOperator(\n        i * tau, tau, discrete_solution_cur);\n    discrete_solution_cur = discrete_solution_next;\n  }\n  discrete_heat_sol = discrete_solution_cur;\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return discrete_heat_sol;\n}\n/* SAM_LISTING_END_6 */\n\n/* Implementing member function Eval of class LinFEMassMatrixProvider*/\nEigen::Matrix<double, 3, 3> LinFEMassMatrixProvider::Eval(\n    const lf::mesh::Entity &tria) {\n  Eigen::Matrix<double, 3, 3> elMat;\n#if SOLUTION\n  // Throw error in case no triangular cell\n  LF_VERIFY_MSG(tria.RefEl() == lf::base::RefEl::kTria(),\n                \"Unsupported cell type \" << tria.RefEl());\n  // Compute the area of the triangle cell\n  const double area = lf::geometry::Volume(*(tria.Geometry()));\n  // Assemble the mass element matrix over the cell\n  // clang-format off\n  elMat << 2.0, 1.0, 1.0,\n           1.0, 2.0, 1.0,\n           1.0, 1.0, 2.0;\n  // clang-format on\n  elMat *= area / 12.0;\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return elMat;  // return the local mass element matrix\n}\n\n/* Implementing constructor of class Radau3MOLTimestepper */\n/* SAM_LISTING_BEGIN_4 */\nRadau3MOLTimestepper::Radau3MOLTimestepper(const lf::assemble::DofHandler &dofh)\n    : dofh_(dofh) {\n#if SOLUTION\n  std::cout << \"\\n>> Constructing SRadau3MOLTimestepper \" << std::endl;\n  auto mesh_p = dofh.Mesh();  // pointer to current mesh\n\n  // Instantiating Galerkin matrices to be pre-computed\n  // Dimension of finite element space\n  const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n  // Matrices in triplet format holding Galerkin matrices, zero initially.\n  lf::assemble::COOMatrix<double> A_COO(N_dofs,\n                                        N_dofs);  // element matrix Laplace\n  lf::assemble::COOMatrix<double> M_COO(N_dofs,\n                                        N_dofs);  // element mass matrix\n\n  std::cout << \"> Initializing the Galerking local matrices builders\"\n            << std::endl;\n  // Initialize classes containing the information required for the\n  // local computations of the Galerkin matrices. Simple implementations of\n  // LinFEMassMatrixProvider and TrapRuleLinFEElemVecProvider adapted to this\n  // particular problem was written to spare some of the overhead calculations\n  // involved in the use of the more general LehrFEM++ matrices providers.\n  lf::uscalfe::LinearFELaplaceElementMatrix elLapMat_builder;\n  LinFEMassMatrixProvider elMassMat_builder;\n\n  std::cout << \"> Assembling Galerking matrices in COO format\" << std::endl;\n  // Compute the Galerkin matrices\n  // Invoke assembly on cells (co-dimension = 0 as first argument)\n  // Information about the mesh and the local-to-global map is passed through\n  // a Dofhandler object, argument 'dofh'. This function call adds triplets to\n  // the internal COO-format representation of the sparse matrices A and M.\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elLapMat_builder, A_COO);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elMassMat_builder, M_COO);\n\n  // Enforcing zero Dirichlet boundary conditions\n  // Obtain an array of boolean flags for the vertices of the mesh: 'true'\n  // indicates that the vertex lies on the boundary.\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 2)};\n  // Index predicate for the selectvals FUNCTOR of dropMatrixRowsColumns\n  auto bdy_vertices_selector = [&bd_flags, &dofh](unsigned int idx) -> bool {\n    return bd_flags(dofh.Entity(idx));\n  };\n  dropMatrixRowsColumns(bdy_vertices_selector, A_COO);\n  dropMatrixRowsColumns(bdy_vertices_selector, M_COO);\n\n  std::cout << \"> Converting triplets to sparse matrices\" << std::endl;\n  // Creating the private Galerkin stiffness and mass matrices\n  A_ = A_COO.makeSparse();\n  Eigen::SparseMatrix<double> M = M_COO.makeSparse();\n\n  // Runge-Kutta matrices defining the 2-stage Radau timestepping. In the\n  // Butcher tableau, this corresponds to c = (1/3 1)^T (top-left column\n  // vector), b^T = (3/4 1/4) (bottom-right row vector), U_11 = 5/12, U_12 =\n  // -1/12, U_21 = 3/4, U_22 = 1/4 (top-right block); values are fixed in\n  // time\n  // clang-format off\n    U_ << 5.0/12.0, -1.0/12.0,\n              0.75,      0.25;\n    c_ << 1.0/3.0, 1.0;\n    b_ << 0.75, 0.25;\n  // clang-format on\n  // Precomputing the kronecker products involved in the implicit linear system\n  // for the increments of the RADAU-2 method\n  M_Kp_ = Eigen::kroneckerProduct(Eigen::Matrix<double, 2, 2>::Identity(), M);\n  A_Kp_ = Eigen::kroneckerProduct(U_, A_);\n#else\n  //====================\n  // Your code goes here\n  // Add any additional members you need in the header file\n  //====================\n#endif\n}\n/* SAM_LISTING_END_4 */\n\n/* Implementation of Radau3MOLTimestepper member functions */\n// The function discreteEvolutionOperator() returns the discretized evolution\n// operator as obtained from the Runge-Kutta Radau IIA 2-stages method using the\n// Butcher table as stored in the Radau3MOLTimestepper class\n/* SAM_LISTING_BEGIN_5 */\nEigen::VectorXd Radau3MOLTimestepper::discreteEvolutionOperator(\n    double time, double tau, const Eigen::VectorXd &mu) const {\n  Eigen::VectorXd discrete_evolution_operator(dofh_.NumDofs());\n#if SOLUTION\n  // Dimension of finite element space\n  const lf::uscalfe::size_type N_dofs(dofh_.NumDofs());\n  LF_VERIFY_MSG(N_dofs == mu.size(),\n                \"Dimension mismatch between the number of degrees of freedom \"\n                \"and the dimension of the argument vector.\");\n\n  // Building the linear system for the implicitely defined increments\n  // Assembling the right hand side using block initialization\n  Eigen::VectorXd linSys_rhs(2 * N_dofs);\n  Eigen::VectorXd rhs_subtraction_term = A_ * mu;  // precomputation\n  linSys_rhs << rhsVectorheatSource(dofh_, time + c_[0] * tau) -\n                    rhs_subtraction_term,\n      rhsVectorheatSource(dofh_, time + tau) - rhs_subtraction_term;\n\n  // Implicit Runge-Kutta methods lead to systems of equations that must be\n  // solved in order to obtained the increments.\n  Eigen::SparseMatrix<double> linSys_mat;\n  // Assembling the system right hand side matrix using the (unfortunately\n  // officially not supported) Eigen Kronecker product\n  linSys_mat = M_Kp_ + tau * A_Kp_;\n  LF_VERIFY_MSG(linSys_mat.rows() == linSys_mat.cols(),\n                \"The linSys_mat Eigen matrix is not squared.\");\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(linSys_mat);\n  LF_VERIFY_MSG(solver.info() == Eigen::Success, \"LU decomposition failed\");\n\n  // Solve linear system using Eigen's sparse direct elimination\n  Eigen::VectorXd k_vec = solver.solve(linSys_rhs);\n  LF_VERIFY_MSG(solver.info() == Eigen::Success, \"Solving LSE failed\");\n\n  // Compute action of the discrete evolution operator on argument vec\n  discrete_evolution_operator = mu + tau * (b_[0] * k_vec.topRows(N_dofs) +\n                                            b_[1] * k_vec.bottomRows(N_dofs));\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return discrete_evolution_operator;\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace RadauThreeTimestepping\n", "meta": {"hexsha": "fd910f0aefbc945f42058906b30088db746a761b", "size": 12141, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/RadauThreeTimestepping/mastersolution/radauthreetimestepping.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/RadauThreeTimestepping/mastersolution/radauthreetimestepping.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/RadauThreeTimestepping/mastersolution/radauthreetimestepping.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 41.7216494845, "max_line_length": 80, "alphanum_fraction": 0.6837986986, "num_tokens": 3212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6456721724684702}}
{"text": "/*!\n * @file     multivariate_normal_eigen_test.cpp\n * @author   Giuseppe Rizzi\n * @date     21.07.2020\n * @version  1.0\n * @brief    description\n */\n\n#include \"mppi/sampler/multivariate_normal_eigen.h\"\n#include <gtest/gtest.h>\n#include <math.h>\n#include <Eigen/Dense>\n#include <array>\n#include <chrono>\n\nTEST(MultivaritateNormal, Sample1D) {\n  Eigen::MatrixXd covar(1, 1);\n  Eigen::VectorXd mean(1);\n  covar << 10.0;\n  mean << 3.0;\n  auto mn = mppi::multivariate_normal(mean, covar);\n  ASSERT_TRUE(mn().size() == 1);\n\n  std::map<int, int> hist{};\n  for (size_t i = 0; i < 10000; i++) ++hist[std::round(mn()(0))];\n\n  std::cout << \"Mean=\" << mean(0) << \", covar=\" << covar(0, 0) << std::endl;\n  for (auto p : hist) {\n    std::cout << std::setw(2) << p.first << ' '\n              << std::string(p.second / 10, '*') << '\\n';\n  }\n}\n\nTEST(MultivaritateNormal, Sample2D) {\n  Eigen::MatrixXd covar(2, 2);\n  Eigen::VectorXd mean(2);\n  covar << 20.0, 0.0, 0.0, 5.0;\n  mean << 3.0, -1.0;\n  auto mn = mppi::multivariate_normal(mean, covar);\n  ASSERT_TRUE(mn().size() == 2);\n\n  std::map<int, int> hist1{};\n  std::map<int, int> hist2{};\n\n  for (size_t i = 0; i < 10000; i++) {\n    ++hist1[std::round(mn()(0))];\n    ++hist2[std::round(mn()(1))];\n  }\n  std::cout << std::endl;\n\n  std::cout << \"First variable: mean=\" << mean(0) << \", covar=\" << covar(0, 0)\n            << std::endl;\n  for (auto p : hist1) {\n    std::cout << std::setw(2) << p.first << ' '\n              << std::string(p.second / 10, '*') << '\\n';\n  }\n\n  std::cout << \"Second variable: mean=\" << mean(1) << \", covar=\" << covar(1, 1)\n            << std::endl;\n  for (auto p : hist2) {\n    std::cout << std::setw(2) << p.first << ' '\n              << std::string(p.second / 10, '*') << '\\n';\n  }\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "cca8a61b1128e588246b1e2230a4a6c9a480abfa", "size": 1852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mppi/unittest/multivariate_normal_eigen_test.cpp", "max_stars_repo_name": "ethz-asl/mppi_mobile_manipulation", "max_stars_repo_head_hexsha": "1ec4b792f05b9cab97f149d41ad97573a77fc749", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-06T17:44:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T13:22:56.000Z", "max_issues_repo_path": "mppi/unittest/multivariate_normal_eigen_test.cpp", "max_issues_repo_name": "ethz-asl/mppi_mobile_manipulation", "max_issues_repo_head_hexsha": "1ec4b792f05b9cab97f149d41ad97573a77fc749", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mppi/unittest/multivariate_normal_eigen_test.cpp", "max_forks_repo_name": "ethz-asl/mppi_mobile_manipulation", "max_forks_repo_head_hexsha": "1ec4b792f05b9cab97f149d41ad97573a77fc749", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-04-20T12:27:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-23T02:38:25.000Z", "avg_line_length": 26.4571428571, "max_line_length": 79, "alphanum_fraction": 0.5410367171, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6456050275660665}}
{"text": "//\n// Copyright (c) 2018 CNRS\n//\n\n#include \"pinocchio/fwd.hpp\"\n#include \"pinocchio/spatial/se3.hpp\"\n#include \"pinocchio/spatial/motion.hpp\"\n#include \"pinocchio/spatial/explog.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\ntemplate<typename Vector3Like>\nEigen::Matrix<typename Vector3Like::Scalar,3,3,0>\ncomputeV(const Eigen::MatrixBase<Vector3Like> & v3)\n{\n  typedef typename Vector3Like::Scalar Scalar;\n  typedef Eigen::Matrix<Scalar,3,3,0> ReturnType;\n  typedef ReturnType Matrix3;\n  \n  Scalar t2 = v3.squaredNorm();\n  const Scalar t = pinocchio::math::sqrt(t2);\n  Scalar alpha, beta, zeta;\n  \n  if (t < 1e-4)\n  {\n    alpha = Scalar(1) + t2/Scalar(6) - t2*t2/Scalar(120);\n    beta = Scalar(1)/Scalar(2) - t2/Scalar(24);\n    zeta = Scalar(1)/Scalar(6) - t2/Scalar(120);\n  }\n  else\n  {\n    Scalar st,ct; pinocchio::SINCOS(t,&st,&ct);\n    alpha = st/t;\n    beta = (1-ct)/t2;\n    zeta = (1 - alpha)/(t2);\n  }\n  \n  Matrix3 V\n  = alpha * Matrix3::Identity()\n  + beta * pinocchio::skew(v3)\n  + zeta * v3 * v3.transpose();\n  \n  return V;\n}\n\ntemplate<typename Vector3Like>\nEigen::Matrix<typename Vector3Like::Scalar,3,3,0>\ncomputeVinv(const Eigen::MatrixBase<Vector3Like> & v3)\n{\n  typedef typename Vector3Like::Scalar Scalar;\n  typedef Eigen::Matrix<Scalar,3,3,0> ReturnType;\n  typedef ReturnType Matrix3;\n  \n  Scalar t2 = v3.squaredNorm();\n  const Scalar t = pinocchio::math::sqrt(t2);\n  \n  Scalar alpha, beta;\n  if (t < 1e-4)\n  {\n    alpha = Scalar(1) - t2/Scalar(12) - t2*t2/Scalar(720);\n    beta = Scalar(1)/Scalar(12) + t2/Scalar(720);\n  }\n  else\n  {\n    Scalar st,ct; pinocchio::SINCOS(t,&st,&ct);\n    alpha = t*st/(Scalar(2)*(Scalar(1)-ct));\n    beta = Scalar(1)/t2 - st/(Scalar(2)*t*(Scalar(1)-ct));\n  }\n  \n  Matrix3 Vinv\n  = alpha * Matrix3::Identity()\n  - 0.5 * pinocchio::skew(v3)\n  + beta * v3 * v3.transpose();\n  \n  return Vinv;\n}\n\nBOOST_AUTO_TEST_CASE(test_log3)\n{\n  using CppAD::AD;\n  using CppAD::NearEqual;\n\n  typedef double Scalar;\n  typedef AD<Scalar> ADScalar;\n\n  typedef pinocchio::SE3Tpl<Scalar> SE3;\n  typedef pinocchio::MotionTpl<Scalar> Motion;\n  typedef pinocchio::SE3Tpl<ADScalar> ADSE3;\n  typedef pinocchio::MotionTpl<ADScalar> ADMotion;\n\n  Motion v(Motion::Zero());\n  SE3 M(SE3::Random()); M.translation().setZero();\n\n  SE3::Matrix3 rot_next = M.rotation() * pinocchio::exp3(v.angular());\n\n  SE3::Matrix3 Jlog3;\n  pinocchio::Jlog3(M.rotation(), Jlog3);\n\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> Matrix;\n  typedef Eigen::Matrix<ADScalar,Eigen::Dynamic,1> ADVector;\n\n  ADMotion ad_v(v.cast<ADScalar>());\n  ADSE3 ad_M(M.cast<ADScalar>());\n  ADSE3::Matrix3 rot = ad_M.rotation();\n\n  ADVector X(3);\n\n  X = ad_v.angular();\n\n  CppAD::Independent(X);\n  ADMotion::Vector3 X_ = X;\n\n  ADSE3::Matrix3 ad_rot_next = rot * pinocchio::exp3(X_);\n  ADMotion::Vector3 log_R_next = pinocchio::log3(ad_rot_next);\n\n  ADVector Y(3);\n  Y = log_R_next;\n\n  CppAD::ADFun<Scalar> map(X,Y);\n\n  CPPAD_TESTVECTOR(Scalar) x(3);\n  Eigen::Map<Motion::Vector3>(x.data()).setZero();\n\n  CPPAD_TESTVECTOR(Scalar) nu_next_vec = map.Forward(0,x);\n  Motion::Vector3 nu_next(Eigen::Map<Motion::Vector3>(nu_next_vec.data()));\n\n  SE3::Matrix3 rot_next_from_map = pinocchio::exp3(nu_next);\n\n  CPPAD_TESTVECTOR(Scalar) jac = map.Jacobian(x);\n\n  Matrix jacobian = Eigen::Map<PINOCCHIO_EIGEN_PLAIN_ROW_MAJOR_TYPE(Matrix)>(jac.data(),3,3);\n\n  BOOST_CHECK(rot_next_from_map.isApprox(rot_next));\n  BOOST_CHECK(jacobian.isApprox(Jlog3));\n}\n\nBOOST_AUTO_TEST_CASE(test_explog_translation)\n{\n  using CppAD::AD;\n  using CppAD::NearEqual;\n  \n  typedef double Scalar;\n  typedef AD<Scalar> ADScalar;\n  \n  typedef pinocchio::SE3Tpl<Scalar> SE3;\n  typedef pinocchio::MotionTpl<Scalar> Motion;\n  typedef pinocchio::SE3Tpl<ADScalar> ADSE3;\n  typedef pinocchio::MotionTpl<ADScalar> ADMotion;\n  \n  Motion v(Motion::Zero());\n  SE3 M(SE3::Random()); //M.rotation().setIdentity();\n  \n  {\n    Motion::Vector3 v3_test; v3_test.setRandom();\n    SE3::Matrix3 V = computeV(v3_test);\n    SE3::Matrix3 Vinv = computeVinv(v3_test);\n    \n    BOOST_CHECK((V*Vinv).isIdentity());\n  }\n  \n  SE3 M_next = M * pinocchio::exp6(v);\n//  BOOST_CHECK(M_next.rotation().isIdentity());\n  \n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> Matrix;\n  typedef Eigen::Matrix<ADScalar,Eigen::Dynamic,1> ADVector;\n  \n  ADMotion ad_v(v.cast<ADScalar>());\n  ADSE3 ad_M(M.cast<ADScalar>());\n  \n  ADVector X(6);\n  \n  X = ad_v.toVector();\n  \n  CppAD::Independent(X);\n  ADMotion::Vector6 X_ = X;\n  \n  pinocchio::MotionRef<ADMotion::Vector6> ad_v_ref(X_);\n  ADSE3 ad_M_next = ad_M * pinocchio::exp6(ad_v_ref);\n\n  ADVector Y(6);\n  Y.head<3>() = ad_M_next.translation();\n  Y.tail<3>() = ad_M.translation() + ad_M.rotation() * computeV(ad_v_ref.angular()) * ad_v_ref.linear();\n  \n  CppAD::ADFun<Scalar> map(X,Y);\n  \n  CPPAD_TESTVECTOR(Scalar) x((size_t)X.size());\n  Eigen::Map<Motion::Vector6>(x.data()).setZero();\n  \n  CPPAD_TESTVECTOR(Scalar) translation_vec = map.Forward(0,x);\n  Motion::Vector3 translation1(Eigen::Map<Motion::Vector3>(translation_vec.data()));\n  Motion::Vector3 translation2(Eigen::Map<Motion::Vector3>(translation_vec.data()+3));\n  BOOST_CHECK(translation1.isApprox(M_next.translation()));\n  BOOST_CHECK(translation2.isApprox(M_next.translation()));\n  \n  CPPAD_TESTVECTOR(Scalar) jac = map.Jacobian(x);\n  \n  Matrix jacobian = Eigen::Map<PINOCCHIO_EIGEN_PLAIN_ROW_MAJOR_TYPE(Matrix)>(jac.data(),Y.size(),X.size());\n  \n  BOOST_CHECK(jacobian.topLeftCorner(3,3).isApprox(M.rotation()));\n  \n}\n\n\nBOOST_AUTO_TEST_CASE(test_explog)\n{\n  using CppAD::AD;\n  using CppAD::NearEqual;\n\n  typedef double Scalar;\n  typedef AD<Scalar> ADScalar;\n\n  typedef pinocchio::SE3Tpl<Scalar> SE3;\n  typedef pinocchio::MotionTpl<Scalar> Motion;\n  typedef pinocchio::SE3Tpl<ADScalar> ADSE3;\n  typedef pinocchio::MotionTpl<ADScalar> ADMotion;\n\n  Motion v(Motion::Zero());\n  SE3 M(SE3::Random()); //M.translation().setZero();\n\n  SE3::Matrix6 Jlog6;\n  pinocchio::Jlog6(M, Jlog6);\n\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> Matrix;\n  typedef Eigen::Matrix<ADScalar,Eigen::Dynamic,1> ADVector;\n\n  ADMotion ad_v(v.cast<ADScalar>());\n  ADSE3 ad_M(M.cast<ADScalar>());\n\n  ADVector X(6);\n\n  X.segment<3>(Motion::LINEAR) = ad_v.linear();\n  X.segment<3>(Motion::ANGULAR) = ad_v.angular();\n\n  CppAD::Independent(X);\n  ADMotion::Vector6 X_ = X;\n  pinocchio::MotionRef< ADMotion::Vector6> v_X(X_);\n\n  ADSE3 ad_M_next = ad_M * pinocchio::exp6(v_X);\n  ADMotion ad_log_M_next = pinocchio::log6(ad_M_next);\n\n  ADVector Y(6);\n  Y.segment<3>(Motion::LINEAR) = ad_log_M_next.linear();\n  Y.segment<3>(Motion::ANGULAR) = ad_log_M_next.angular();\n\n  CppAD::ADFun<Scalar> map(X,Y);\n\n  CPPAD_TESTVECTOR(Scalar) x(6);\n  Eigen::Map<Motion::Vector6>(x.data()).setZero();\n\n  CPPAD_TESTVECTOR(Scalar) nu_next_vec = map.Forward(0,x);\n  Motion nu_next(Eigen::Map<Motion::Vector6>(nu_next_vec.data()));\n\n  CPPAD_TESTVECTOR(Scalar) jac = map.Jacobian(x);\n\n  Matrix jacobian = Eigen::Map<PINOCCHIO_EIGEN_PLAIN_ROW_MAJOR_TYPE(Matrix)>(jac.data(),6,6);\n\n  // Check using finite differencies\n  Motion dv(Motion::Zero());\n  typedef Eigen::Matrix<Scalar,6,6> Matrix6;\n  Matrix6 Jlog6_fd(Matrix6::Zero());\n  Motion v_plus, v0(log6(M));\n\n  const Scalar eps = 1e-8;\n  for(int k = 0; k < 6; ++k)\n  {\n    dv.toVector()[k] = eps;\n    SE3 M_plus = M * exp6(dv);\n    v_plus = log6(M_plus);\n    Jlog6_fd.col(k) = (v_plus-v0).toVector()/eps;\n    dv.toVector()[k] = 0;\n  }\n  \n  SE3::Matrix6 Jlog6_analytic;\n  pinocchio::Jlog6(M, Jlog6_analytic);\n  \n  BOOST_CHECK(Jlog6.isApprox(Jlog6_analytic));\n  BOOST_CHECK(Jlog6_fd.isApprox(Jlog6,pinocchio::math::sqrt(eps)));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7405346836bcca07c87bf5c6607999232b6c3d64", "size": 7704, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/cppad-spatial.cpp", "max_stars_repo_name": "mkatliar/pinocchio", "max_stars_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/cppad-spatial.cpp", "max_issues_repo_name": "mkatliar/pinocchio", "max_issues_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/cppad-spatial.cpp", "max_forks_repo_name": "mkatliar/pinocchio", "max_forks_repo_head_hexsha": "b755b9cf2567eab39de30a68b2a80fac802a4042", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9370629371, "max_line_length": 107, "alphanum_fraction": 0.6887331256, "num_tokens": 2466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6456050265292178}}
{"text": "#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_binary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include \"g2o/EXTERNAL/ceres/autodiff.h\"\n#include <g2o/core/auto_differentiation.h>\n\n#include <g2o/core/robust_kernel_impl.h>\n#include <iostream>\n\n#include \"common.h\"\n#include <sophus/se3.hpp>\n#include <sophus/so3.hpp>\n#include <ceres/rotation.h>\n#include <Eigen/Dense>\n\nusing namespace Sophus;\nusing namespace Eigen;\nusing namespace std;\n\n\n\nclass VertexCamera: public g2o::BaseVertex<9, Eigen::Matrix<double, 9, 1>>      //  here the camera is parameterized as a 9-vector (angle axis, t, f, k1, k2) \n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    virtual void setToOriginImpl() override {\n        _estimate = Eigen::Matrix<double, 9, 1>::Zero();\n    }\n\n    virtual void oplusImpl(const double *update) override {\n        _estimate += Eigen::Map<const Eigen::Matrix<double, 9, 1>>(update);\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n};\n\nclass VertexLandmark: public g2o::BaseVertex<3, Eigen::Vector3d>\n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    virtual void setToOriginImpl() override {\n        _estimate = Eigen::Vector3d::Zero();       \n    }\n\n    virtual void oplusImpl(const double *update) override {\n        _estimate += Eigen::Map<const Eigen::Vector3d>(update);\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n};\n\n\nclass EdgeReprojection: public g2o::BaseBinaryEdge<2, Eigen::Vector2d, VertexCamera, VertexLandmark>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    EdgeReprojection() { }\n\n    template <class T>\n    bool operator() (const T* camera, const T* landmark, T* residuals) const \n    {\n        T Xc[3];\n        ceres::AngleAxisRotatePoint(camera, landmark, Xc);\n        Xc[0] += camera[3];\n        Xc[1] += camera[4];\n        Xc[2] += camera[5];\n\n        T Xp[2];\n        Xp[0] = Xc[0] / Xc[2];\n        Xp[1] = Xc[1] / Xc[2];\n\n        T n2 = Xp[0] * Xp[0] + Xp[1] * Xp[1];\n        T r = T(1.0) + n2 * (camera[7] + n2 * camera[8]);\n\n        T uv[2];\n        uv[0] = -Xp[0] * camera[6] * r;\n        uv[1] = -Xp[1] * camera[6] * r;\n\n        residuals[0] = T(_measurement[0]) - uv[0];\n        residuals[1] = T(_measurement[1]) - uv[1];\n        return true;\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n    \n    G2O_MAKE_AUTO_AD_FUNCTIONS  // use autodiff\n\n};\n\n\nint main(int argc, char **argv) {\n\n    if (argc != 2) {\n        cout << \"usage: bundle_adjustment_g2o bal_data.txt\" << endl;\n        return 1;\n    }\n\n    BALProblem dataset(argv[1]);\n    dataset.Normalize();\n    dataset.Perturb(0.1, 0.5, 0.5);\n    dataset.WriteToPLYFile(\"initial_pc.ply\");\n\n    std::cout << \"\\n\";\n    std::cout << \"nb cameras: \" << dataset.num_cameras() << std::endl;\n    std::cout << \"nb landmarks: \" << dataset.num_points() << std::endl;\n    std::cout << \"nb observations: \" << dataset.num_observations() << std::endl;\n    std::cout << \"nb parameters: \" << dataset.num_parameters() << std::endl;\n    std::cout << \"check: \" << dataset.num_cameras() * 9 + dataset.num_points()*3 << std::endl;\n\n\n    // pose dimension 9, landmark is 3\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<9, 3>> BlockSolverType;\n    typedef g2o::LinearSolverCSparse<BlockSolverType::PoseMatrixType> LinearSolverType;\n\n    auto solver = new g2o::OptimizationAlgorithmLevenberg(\n        g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>())\n    );\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    optimizer.setVerbose(true);\n\n\n    auto* cameras = dataset.mutable_cameras();\n    std::vector<VertexCamera*> camera_vertices;\n    for (int i = 0; i < dataset.num_cameras(); ++i)\n    {\n        auto *c = new VertexCamera();\n        c->setId(i);\n        c->setEstimate(Eigen::Map<Eigen::Matrix<double, 9, 1>>(cameras + (i*dataset.camera_block_size())));\n        optimizer.addVertex(c);\n        camera_vertices.push_back(c);\n    }\n    \n    auto* landmarks = dataset.mutable_points();\n    std::vector<VertexLandmark*> landmark_vertices;\n    for (int i = 0; i < dataset.num_points(); ++i)\n    {\n        auto* l = new VertexLandmark();\n        l->setId(dataset.num_cameras() + i);\n        l->setEstimate(Eigen::Map<Eigen::Vector3d>(landmarks + i*dataset.point_block_size()));\n        l->setMarginalized(true);\n        optimizer.addVertex(l);\n        landmark_vertices.push_back(l);\n    }\n\n    auto* observations = dataset.observations();\n    auto* cam_indices = dataset.camera_index();\n    auto* landmark_indices = dataset.point_index();\n    for (int i = 0; i < dataset.num_observations(); ++i)\n    {\n        auto* e = new EdgeReprojection();\n        e->setVertex(0, camera_vertices[cam_indices[i]]);\n        e->setVertex(1, landmark_vertices[landmark_indices[i]]);\n        e->setMeasurement(Eigen::Map<const Eigen::Vector2d>(observations + i*2));\n        e->setInformation(Eigen::Matrix2d::Identity());\n        optimizer.addEdge(e);\n    }\n\n    optimizer.initializeOptimization();\n    optimizer.optimize(40);\n\n\n    for (int i = 0; i < dataset.num_cameras(); ++i)\n    {\n        Eigen::Matrix<double, 9, 1> in = camera_vertices[i]->estimate();\n        double *out = cameras + i * dataset.camera_block_size();\n        for (int i = 0; i < 9; ++i)\n        {\n            out[i] = in[i];\n        }\n    }\n    for (int i = 0; i < dataset.num_points(); ++i)\n    {\n        Eigen::Vector3d X = landmark_vertices[i]->estimate();\n        landmarks[i*3] = X.x();\n        landmarks[i*3+1] = X.y();\n        landmarks[i*3+2] = X.z();\n    }\n\n    dataset.WriteToPLYFile(\"after_ba_g2o.ply\");\n\n    return 0;\n}\n", "meta": {"hexsha": "c9ac4f46ff1385777e5025b885add8bfe9a9e934", "size": 5838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch9/bundle_adjustment_g2o_custom_autodiff.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch9/bundle_adjustment_g2o_custom_autodiff.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch9/bundle_adjustment_g2o_custom_autodiff.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.40625, "max_line_length": 158, "alphanum_fraction": 0.6216169921, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6455935394541912}}
{"text": "/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <random>\n#include <cmath>\n#include <boost/math/special_functions/jacobi.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing std::abs;\nusing boost::math::jacobi;\nusing boost::math::jacobi_derivative;\n\ntemplate<typename Real>\nvoid test_to_quadratic()\n{\n    Real h = 1/Real(8);\n    for (Real alpha = -1 + h; alpha < 2; alpha += h) {\n        for (Real beta = -1 + h; beta < 2; beta += h) {\n            for (Real x = -1; x < 1; x += h) {\n                Real expected = 1;\n                Real computed = jacobi(0, alpha, beta, x);\n                CHECK_ULP_CLOSE(expected, computed, 0);\n\n                expected = (alpha + 1) + (alpha + beta +2)*(x-1)/2;\n                computed = jacobi(1, alpha, beta, x);\n                CHECK_ULP_CLOSE(expected, computed, 0);\n\n                expected = (alpha + 1)*(alpha+2)/2 + (alpha + 2)*(alpha + beta + 3)*(x-1)/2 + (alpha + beta + 3)*(alpha + beta + 4)*(x-1)*(x-1)/8;\n                computed = jacobi(2, alpha, beta, x);\n                CHECK_ULP_CLOSE(expected, computed, 1);\n\n            }\n        }\n    }\n}\n\ntemplate<typename Real>\nvoid test_symmetry()\n{\n    Real h = 1/Real(4);\n    for (Real alpha = -1 + h; alpha < 2; alpha += h) {\n        for (Real beta = -1 + h; beta < 2; beta += h) {\n            for (Real x = -1; x < 1; x += h) {\n                for (size_t n = 0; n < 20; n += 2)\n                {\n                    Real expected = jacobi(n, beta, alpha , -x);\n                    Real computed = jacobi(n, alpha, beta, x);\n                    CHECK_ULP_CLOSE(expected, computed, 0);\n\n                    expected = jacobi(n+1, beta, alpha, -x);\n                    computed = -jacobi(n+1, alpha, beta, x);\n                    CHECK_ULP_CLOSE(expected, computed, 0);\n                }\n            }\n        }\n    }\n}\n\ntemplate<typename Real>\nvoid test_derivative()\n{\n    Real h = 1/Real(4);\n    for (Real alpha = -1 + h; alpha < 2; alpha += h) {\n        for (Real beta = -1 + h; beta < 2; beta += h) {\n            for (Real x = -1; x < 1; x += h) {\n                Real expected = 0;\n                Real computed = jacobi_derivative(0, alpha, beta, x, 1);\n                CHECK_ULP_CLOSE(expected, computed, 0);\n\n                expected = (alpha + beta + 2)/2;\n                computed = jacobi_derivative(1, alpha, beta, x, 1);\n                CHECK_ULP_CLOSE(expected, computed, 0);\n\n                expected = (alpha + 2)*(alpha + beta + 3)/2 + (alpha + beta + 3)*(alpha + beta + 4)*(x-1)/4;\n                computed = jacobi_derivative(2, alpha, beta, x, 1);\n                CHECK_ULP_CLOSE(expected, computed, 0);\n\n                expected = (alpha + beta + 3)*(alpha + beta + 4)/4;\n                computed = jacobi_derivative(2, alpha, beta, x, 2);\n                CHECK_ULP_CLOSE(expected, computed, 0);\n            }\n        }\n    }\n}\n\nint main()\n{\n    test_to_quadratic<double>();\n    test_to_quadratic<long double>();\n\n    test_symmetry<float>();\n    test_symmetry<double>();\n    test_symmetry<long double>();\n\n    test_derivative<float>();\n    test_derivative<double>();\n    test_derivative<long double>();\n\n#ifdef BOOST_HAS_FLOAT128\n    test_to_quadratic<boost::multiprecision::float128>();\n    test_symmetry<boost::multiprecision::float128>();\n    test_derivative<boost::multiprecision::float128>();\n#endif\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "f546fa1563af3cd6004dcd4a780d617c5c601a2e", "size": 3712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/test/jacobi_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T15:15:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T15:15:28.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/jacobi_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T20:49:05.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/jacobi_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 31.7264957265, "max_line_length": 146, "alphanum_fraction": 0.5417564655, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6455935296173024}}
{"text": "//\n//  Copyright (c) 2018, Cem Bassoy, cem.bassoy@gmail.com\n//  Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  Google and Fraunhofer IOSB, Ettlingen, Germany\n//\n\n\n#include <boost/numeric/ublas/tensor.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <ostream>\n\nint main()\n{\n  namespace ublas = boost::numeric::ublas;\n  using value   = float;\n  using tensor = ublas::tensor_dynamic<value>;\n  using matrix = ublas::matrix<value>;\n  using vector = ublas::vector<value>;\n  using shape   = tensor::extents_type;\n\n  try {\n\n\n    auto A = tensor{3,4,2};\n    auto B = A = 2;\n\n    // Calling overloaded operators\n    // and using simple tensor expression templates.\n    if( A != (B+1) ){\n      A += 2*B - 1;\n    }\n\n    // formatted output\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"A=\" << A << \";\" << std::endl << std::endl;\n\n    auto n = shape{3,4};\n    auto D = matrix(n[0],n[1],1);\n    auto e = vector(n[1],1);\n    auto f = vector(n[0],2);\n\n    // Calling constructor with\n    // vector expression templates\n    tensor C = 2*f;\n    // formatted output\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"C=\" << C << \";\" << std::endl << std::endl;\n\n\n    // Calling overloaded operators\n    // and mixing simple tensor and matrix expression templates\n    tensor F = 3*C + 4*prod(2*D,e);\n\n    // formatted output\n    std::cout << \"% --------------------------- \" << std::endl;\n    std::cout << \"% --------------------------- \" << std::endl << std::endl;\n    std::cout << \"F=\" << F << \";\" << std::endl << std::endl;\n\n  }  catch (const std::exception& e) {\n    std::cerr << \"Cought exception \" << e.what();\n    std::cerr << \"in the main function of simple expression.\" << std::endl;\n  }\n\n}\n", "meta": {"hexsha": "81c6e1cf805661db92919f4903d9e33aa9ba4617", "size": 2182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tensor/simple_expressions.cpp", "max_stars_repo_name": "samd2/ublas", "max_stars_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T10:15:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T18:31:02.000Z", "max_issues_repo_path": "examples/tensor/simple_expressions.cpp", "max_issues_repo_name": "samd2/ublas", "max_issues_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 105.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T09:01:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T06:10:39.000Z", "max_forks_repo_path": "examples/tensor/simple_expressions.cpp", "max_forks_repo_name": "samd2/ublas", "max_forks_repo_head_hexsha": "dae5364e44e981698f3de1b0f46b06256ddaf56b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T13:35:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:27.000Z", "avg_line_length": 29.4864864865, "max_line_length": 76, "alphanum_fraction": 0.5444546288, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6455774409763977}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXcd X = MatrixXcd::Random(4,4);\nMatrixXcd A = X + X.adjoint();\ncout << \"Here is a random self-adjoint 4x4 matrix:\" << endl << A << endl << endl;\n\nTridiagonalization<MatrixXcd> triOfA(A);\nMatrixXd T = triOfA.matrixT();\ncout << \"The tridiagonal matrix T is:\" << endl << T << endl << endl;\n\ncout << \"We can also extract the diagonals of T directly ...\" << endl;\nVectorXd diag = triOfA.diagonal();\ncout << \"The diagonal is:\" << endl << diag << endl; \nVectorXd subdiag = triOfA.subDiagonal();\ncout << \"The subdiagonal is:\" << endl << subdiag << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "4fe9efcc361dded2afc77daf03d21cef06b85186", "size": 703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_diagonal.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_diagonal.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_diagonal.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0384615385, "max_line_length": 81, "alphanum_fraction": 0.6600284495, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6455774306042017}}
{"text": "#include <stan/math.hpp>\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n#include <cmath>\n#include <vector>\n\n// This test fixture swallows output to std::cout\nclass Math : public ::testing::Test {\n public:\n  void SetUp() {\n    output_.str(\"\");\n    cout_backup_ = std::cout.rdbuf();\n    std::cout.rdbuf(output_.rdbuf());\n  }\n\n  void TearDown() {\n    std::cout.rdbuf(cout_backup_);\n    stan::math::recover_memory();\n  }\n\n  std::stringstream output_;\n  std::streambuf* cout_backup_;\n};\n\nTEST_F(Math, paper_example_1) {\n  using std::pow;\n  double y = 1.3;\n  stan::math::var mu = 0.5, sigma = 1.2;\n\n  stan::math::var lp = 0;\n  lp -= 0.5 * log(2 * stan::math::pi());\n  lp -= log(sigma);\n  lp -= 0.5 * pow((y - mu) / sigma, 2);\n  std::cout << \"f(mu, sigma) = \" << lp.val() << std::endl;\n\n  lp.grad();\n  std::cout << \" d.f / d.mu = \" << mu.adj()\n            << \" d.f / d.sigma = \" << sigma.adj() << std::endl;\n}\n\nTEST_F(Math, paper_example_2) {\n  double y = 1.3;\n  stan::math::var mu = 0.5, sigma = 1.2;\n\n  stan::math::var lp = 0;\n  lp -= 0.5 * log(2 * stan::math::pi());\n  lp -= log(sigma);\n  lp -= 0.5 * pow((y - mu) / sigma, 2);\n\n  std::vector<stan::math::var> theta;\n  theta.push_back(mu);\n  theta.push_back(sigma);\n  std::vector<double> g;\n  lp.grad(theta, g);\n  std::cout << \" d.f / d.mu = \" << g[0] << \" d.f / d.sigma = \" << g[1]\n            << std::endl;\n}\n\nnamespace paper {  // paper_example_3\ntemplate <typename T1, typename T2, typename T3>\ninline stan::return_type_t<T1, T2, T3> normal_log(const T1& y, const T2& mu,\n                                                  const T3& sigma) {\n  using std::log;\n  using std::pow;\n  return -0.5 * pow((y - mu) / sigma, 2.0) - log(sigma)\n         - 0.5 * log(2 * stan::math::pi());\n}\n}  // namespace paper\n\nTEST_F(Math, paper_example_3) {\n  double y = 1.3;\n  stan::math::var mu = 0.5, sigma = 1.2;\n\n  stan::math::var lp = normal_log(y, mu, sigma);\n  EXPECT_FLOAT_EQ(-1.323482, lp.val());\n}\n\n// paper_example_4: remove 'paper::' when including in the paper\nnamespace paper {\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\n\nstruct normal_ll {\n  const Matrix<double, Dynamic, 1> y_;\n\n  explicit normal_ll(const Matrix<double, Dynamic, 1>& y) : y_(y) {}\n\n  template <typename T>\n  T operator()(const Matrix<T, Dynamic, 1>& theta) const {\n    T mu = theta[0];\n    T sigma = theta[1];\n    T lp = 0;\n    for (int n = 0; n < y_.size(); ++n)\n      lp += paper::normal_log(y_[n], mu, sigma);\n    return lp;\n  }\n};\n}  // namespace paper\n\nTEST_F(Math, paper_example_4) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using paper::normal_ll;\n\n  Matrix<double, Dynamic, 1> y(3);\n  y << 1.3, 2.7, -1.9;\n  normal_ll f(y);\n\n  Matrix<double, Dynamic, 1> theta(2);\n  theta << 1.3, 2.9;\n\n  double fx;\n  Matrix<double, Dynamic, 1> grad_fx;\n  stan::math::gradient(f, theta, fx, grad_fx);\n}\n\nnamespace paper_example_5 {\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\n\nstruct functor {\n  const Matrix<double, Dynamic, 1> y_;\n\n  explicit functor(const Matrix<double, Dynamic, 1>& y) : y_(y) {}\n\n  template <typename T>\n  Matrix<T, Dynamic, 1> operator()(const Matrix<T, Dynamic, 1>& theta) const {\n    Matrix<T, Dynamic, 1> lp(y_.size());\n    T mu = theta[0];\n    T sigma = theta[1];\n    for (int n = 0; n < y_.size(); ++n)\n      lp[n] = paper::normal_log(y_[n], mu, sigma);\n    return lp;\n  }\n};\n\n}  // namespace paper_example_5\n\nTEST_F(Math, paper_example_5) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using stan::math::var;\n\n  Matrix<double, Dynamic, 1> y(3);\n  y << 1.3, 2.7, -1.9;\n  paper_example_5::functor f(y);\n\n  Matrix<double, Dynamic, 1> x(2);\n  x << 1.3, 2.9;\n\n  // paper_example_5 starts with the next line\n  // Matrix<double, Dynamic, 1> x = ...;   // inputs\n\n  Matrix<var, Dynamic, 1> x_var(x.size());\n  for (int i = 0; i < x.size(); ++i)\n    x_var(i) = x(i);\n\n  Matrix<var, Dynamic, 1> f_x_var = f(x_var);\n\n  Matrix<double, Dynamic, 1> f_x(f_x_var.size());\n  for (int i = 0; i < f_x.size(); ++i)\n    f_x(i) = f_x_var(i).val();\n\n  Matrix<double, Dynamic, Dynamic> J(f_x_var.size(), x_var.size());\n  for (int i = 0; i < f_x_var.size(); ++i) {\n    if (i > 0)\n      stan::math::set_zero_all_adjoints();\n    f_x_var(i).grad();\n    for (int j = 0; j < x_var.size(); ++j)\n      J(i, j) = x_var(j).adj();\n  }\n}\n\nTEST_F(Math, paper_example_6) {\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using stan::math::var;\n\n  Matrix<double, Dynamic, 1> y(3);\n  y << 1.3, 2.7, -1.9;\n  paper_example_5::functor f(y);\n\n  Matrix<double, Dynamic, 1> x(2);\n  x << 1.3, 2.9;\n\n  // paper_example_6\n  Matrix<double, Dynamic, Dynamic> J;\n  Matrix<double, Dynamic, 1> f_x;\n  stan::math::jacobian(f, x, f_x, J);\n}\n", "meta": {"hexsha": "dc407d470a0a3341434fff794b71b2ffeeb6ed02", "size": 4626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math_include_test.cpp", "max_stars_repo_name": "bayesmix-dev/math", "max_stars_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math_include_test.cpp", "max_issues_repo_name": "bayesmix-dev/math", "max_issues_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T12:45:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T20:43:03.000Z", "max_forks_repo_path": "test/unit/math_include_test.cpp", "max_forks_repo_name": "bayesmix-dev/math", "max_forks_repo_head_hexsha": "3616f7195adc95ef8e719a2af845d61102bc9272", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 24.219895288, "max_line_length": 78, "alphanum_fraction": 0.5851707739, "num_tokens": 1574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276224, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6455774211376658}}
{"text": "/**\n * @date Tue Jan 18 17:07:26 2011 +0100\n * @author Andr\u00e9 Anjos <andre.anjos@idiap.ch>\n * @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>\n *\n * @brief Principal Component Analysis implemented with Singular Value\n * Decomposition or using the Covariance Method. Both are implemented using\n * LAPACK. Implementation.\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <algorithm>\n#include <blitz/array.h>\n#include <boost/format.hpp>\n#include <bob.math/stats.h>\n#include <bob.math/svd.h>\n#include <bob.math/eig.h>\n\n#include <bob.learn.linear/pca.h>\n\nnamespace bob { namespace learn { namespace linear {\n\n  PCATrainer::PCATrainer(bool use_svd)\n    : m_use_svd(use_svd), m_safe_svd(false)\n  {\n  }\n\n  PCATrainer::PCATrainer(const PCATrainer& other)\n    : m_use_svd(other.m_use_svd), m_safe_svd(other.m_safe_svd)\n  {\n  }\n\n  PCATrainer::~PCATrainer() {}\n\n  PCATrainer& PCATrainer::operator= (const PCATrainer& other) {\n    if (this != &other) {\n      m_use_svd = other.m_use_svd;\n      m_safe_svd = other.m_safe_svd;\n    }\n    return *this;\n  }\n\n  bool PCATrainer::operator== (const PCATrainer& other) const {\n\n    return m_use_svd == other.m_use_svd &&\n      m_safe_svd == other.m_safe_svd;\n\n  }\n\n  bool PCATrainer::operator!= (const PCATrainer& other) const {\n\n    return !(this->operator==(other));\n\n  }\n\n  /**\n   * Sets up the machine calculating the PC's via the Covariance Matrix\n   */\n  static void pca_via_covmat(Machine& machine,\n      blitz::Array<double,1>& eigen_values, const blitz::Array<double,2>& X,\n      int rank) {\n\n    /**\n     * computes the covariance matrix (X-mu)(X-mu)^T / (len(X)-1) and then solves\n     * the generalized eigen-value problem taking into consideration the\n     * covariance matrix is symmetric (and, by extension, hermitian).\n     */\n    blitz::Array<double,1> mean(X.extent(1));\n    blitz::Array<double,2> Sigma(X.extent(1), X.extent(1));\n    bob::math::scatter_(X, Sigma, mean);\n    Sigma /= (X.extent(0)-1); //unbiased variance estimator\n\n    blitz::Array<double,2> U(X.extent(1), X.extent(1));\n    blitz::Array<double,1> e(X.extent(1));\n    bob::math::eigSym_(Sigma, U, e);\n    e.reverseSelf(0);\n    U.reverseSelf(1);\n\n    /**\n     * sets the linear machine with the results:\n     */\n    machine.setInputSubtraction(mean);\n    machine.setInputDivision(1.0);\n    machine.setBiases(0.0);\n    if (e.size() == eigen_values.size()) {\n      eigen_values = e;\n      machine.setWeights(U);\n    }\n    else {\n      eigen_values = e(blitz::Range(0,rank-1));\n      machine.setWeights(U(blitz::Range::all(), blitz::Range(0,rank-1)));\n    }\n\n  }\n\n  /**\n   * Sets up the machine calculating the PC's via SVD\n   */\n  static void pca_via_svd(Machine& machine, blitz::Array<double,1>& eigen_values,\n      const blitz::Array<double,2>& X, int rank, bool safe_svd) {\n\n    // removes the empirical mean from the training data\n    blitz::Array<double,2> data(X.extent(1), X.extent(0));\n    blitz::Range a = blitz::Range::all();\n    for (int i=0; i<X.extent(0); ++i) data(a,i) = X(i,a);\n\n    // computes the mean of the training data\n    blitz::secondIndex j;\n    blitz::Array<double,1> mean(X.extent(1));\n    mean = blitz::mean(data, j);\n\n    // applies the training data mean\n    for (int i=0; i<X.extent(0); ++i) data(a,i) -= mean;\n\n    /**\n     * computes the singular value decomposition using lapack\n     *\n     * note: Lapack already organizes the U,Sigma,V**T matrixes so that the\n     * singular values in Sigma are organized by decreasing order of magnitude.\n     * You **don't** need sorting after this.\n     */\n    const int rank_1 = (rank == (int)X.extent(1))? X.extent(1) : X.extent(0);\n    blitz::Array<double,2> U(X.extent(1), rank_1);\n    blitz::Array<double,1> sigma(rank_1);\n    bob::math::svd_(data, U, sigma, safe_svd);\n\n    /**\n     * sets the linear machine with the results:\n     *\n     * note: eigen values are sigma^2/X.extent(0) diagonal\n     *       eigen vectors are the rows of U\n     */\n    machine.setInputSubtraction(mean);\n    machine.setInputDivision(1.0);\n    machine.setBiases(0.0);\n    blitz::Range up_to_rank(0, rank-1);\n    machine.setWeights(U(a,up_to_rank));\n\n    //weight normalization (if necessary):\n    //norm_factor = blitz::sum(blitz::pow2(V(all,i)))\n\n    // finally, we set also the eigen values in this version\n    eigen_values = (blitz::pow2(sigma)/(X.extent(0)-1))(up_to_rank);\n  }\n\n  void PCATrainer::train(Machine& machine, blitz::Array<double,1>& eigen_values,\n      const blitz::Array<double,2>& X) const {\n\n    // data is checked now and conforms, just proceed w/o any further checks.\n    const int rank = output_size(X);\n\n    // Checks that the dimensions are matching\n    if (machine.inputSize() != (size_t)X.extent(1)) {\n      boost::format m(\"Number of features at input data set (%d columns) does not match machine input size (%d)\");\n      m % X.extent(1) % machine.inputSize();\n      throw std::runtime_error(m.str());\n    }\n    if (machine.outputSize() != (size_t)rank) {\n      boost::format m(\"Number of outputs of the given machine (%d) does not match the maximum covariance rank, i.e., min(#samples-1,#features) = min(%d, %d) = %d\");\n      m % machine.outputSize() % (X.extent(0)-1) % X.extent(1) % rank;\n      throw std::runtime_error(m.str());\n    }\n    if (eigen_values.extent(0) != rank) {\n      boost::format m(\"Number of eigenvalues on the given 1D array (%d) does not match the maximum covariance rank, i.e., min(#samples-1,#features) = min(%d,%d) = %d\");\n      m % eigen_values.extent(0) % (X.extent(0)-1) % X.extent(1) % rank;\n      throw std::runtime_error(m.str());\n    }\n\n    if (m_use_svd) pca_via_svd(machine, eigen_values, X, rank, m_safe_svd);\n    else pca_via_covmat(machine, eigen_values, X, rank);\n  }\n\n  void PCATrainer::train(Machine& machine, const blitz::Array<double,2>& X) const {\n    blitz::Array<double,1> throw_away_eigen_values(output_size(X));\n    train(machine, throw_away_eigen_values, X);\n  }\n\n  size_t PCATrainer::output_size (const blitz::Array<double,2>& X) const {\n    return (size_t)std::min(X.extent(0)-1,X.extent(1));\n  }\n\n}}}\n", "meta": {"hexsha": "fa21bc447ee09c57f5ec6ccb1fef797670f825f5", "size": 6090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/learn/linear/cpp/pca.cpp", "max_stars_repo_name": "bioidiap/bob.learn.linear", "max_stars_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-10-14T08:06:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:02:13.000Z", "max_issues_repo_path": "bob/learn/linear/cpp/pca.cpp", "max_issues_repo_name": "bioidiap/bob.learn.linear", "max_issues_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-18T05:27:50.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-25T15:30:27.000Z", "max_forks_repo_path": "bob/learn/linear/cpp/pca.cpp", "max_forks_repo_name": "bioidiap/bob.learn.linear", "max_forks_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-17T12:58:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-09T14:30:27.000Z", "avg_line_length": 33.097826087, "max_line_length": 168, "alphanum_fraction": 0.6489326765, "num_tokens": 1742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6455774185446168}}
{"text": "#pragma once\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <cudd/cplusplus/cuddObj.hh>\n#include <vector>\n\n#include \"number_representation.hpp\"\n\nnamespace abo::error_metrics {\n\n/**\n * @brief Computes the maximum relative difference between f and f_hat for any input\n * It is defined as the maximum of |f(x) - f_hat(x)| / max(1, |f(x)|) over all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * The computation is performed with ADDs and might be quite slow\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param num_rep The number representation for f and f_hat\n * @return the maximum relative difference of the inputs\n */\ndouble wcre_add(const Cudd& mgr, const std::vector<BDD>& f,\n              const std::vector<BDD>& f_hat,\n              const abo::util::NumberRepresentation num_rep\n                = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief Computes bounds on the maximum relative value of f in relation to g\n * It is defined as the maximum of |f(x)| / max(1, |g(x)|) over all inputs x\n * This function returns a range in which the actual relative value is guaranteed to lie\n * The computed bounds are always within a factor of 2, meaning that the maximum bound\n * returned by this function is at most twice the minimum bound\n * @param mgr The BDD object manager\n * @param f The function to compute the maximum relative value of (must be an unsigned integer)\n * @param g The function to use as a relation. Must have the same number of bits as f (must be an\n * unsigned integer)\n * @return {min, max}, the lower and upper bound on the maximum relative value\n */\nstd::pair<boost::multiprecision::cpp_dec_float_100,\n            boost::multiprecision::cpp_dec_float_100>\nmaximum_relative_value_bounds(const Cudd& mgr, const std::vector<BDD>& f,\n                              const std::vector<BDD>& g);\n\n/**\n * @brief Computes bounds on the maximum relative difference between f and f_hat\n * It is defined as the maximum of |f(x) - f_hat(x)| / max(1, |f(x)|) over all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * This function returns a range in which the actual maximum relative error is guaranteed to lie\n * The computed bounds are always within a factor of 2, meaning that the maximum error\n * returned by this function is at most twice the minimum error\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param num_rep The number representation for f and f_hat\n * @return {min, max}, the lower and upper bound on the maximum relative error\n */\nstd::pair<boost::multiprecision::cpp_dec_float_100,\n            boost::multiprecision::cpp_dec_float_100>\n    wcre_bounds(\n        const Cudd& mgr,\n        const std::vector<BDD>& f,\n        const std::vector<BDD>& f_hat,\n        const abo::util::NumberRepresentation num_rep\n            = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief Computes the maximum relative difference between f and f_hat for any input\n * It is defined as the maximum of |f(x) - f_hat(x)| / max(1, |f(x)|) over all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * The computation is performed with BDDs using a binary search to find the maximum value\n * If the correct value is found, the search is aborted. Otherwise, it is run until the desired\n * precision is reached\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param num_extra_bits The number of additional bits used during the search to represent values\n * smaller than one\n * @param precision The desired precision of the result if the correct value is not found during the\n * binary search Do not set it lower than 2^-num_extra_bits\n * @param num_rep The number representation for f and f_hat\n * @return the maximum relative difference of the inputs\n */\ndouble wcre_search(\n        const Cudd& mgr, const std::vector<BDD>& f,\n        const std::vector<BDD>& f_hat,\n        unsigned int num_extra_bits = 16,\n        double precision = 0.0001,\n        const abo::util::NumberRepresentation num_rep\n            = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief Computes the maximum relative difference between f and f_hat for any input\n * It is defined as the maximum of |f(x) - f_hat(x)| / max(1, |f(x)|) over all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * The computation is performed with BDDs using a binary search to find the maximum value\n * If the correct value is found, the search is aborted. Otherwise, it is run until the desired\n * precision is reached\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param samples The number of random input samples drawn in each iteration\n * @param num_rep The number representation for f and f_hat\n * @return the maximum relative difference of the inputs as a fraction [numerator, denominator]\n */\nstd::pair<long, long> wcre_randomized_search(\n        const Cudd& mgr, const std::vector<BDD>& f,\n        const std::vector<BDD>& f_hat,\n        unsigned int samples = 1,\n        const abo::util::NumberRepresentation num_rep\n        = abo::util::NumberRepresentation::BaseTwo);\n/**\n * @brief Computes the maximum relative difference between f and f_hat for any input\n * It is defined as the maximum of |f(x) - f_hat(x)| / max(1, |f(x)|) over all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * The computation is performed with BDDs using a symbolic division and might be quite slow\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param num_extra_bits The number of additional fixed precision bits to use during the division\n * As the result of each division is not an integer, the result is described as a fixed point number\n * with exactly num_extra_bits bits with a lower significance than one. Roughly correlates the the\n * precision of the result\n * @param num_rep The number representation for f and f_hat\n * @return the maximum relative difference of the inputs\n */\nboost::multiprecision::cpp_dec_float_100 wcre_symbolic_division(\n        const Cudd& mgr, const std::vector<BDD>& f,\n        const std::vector<BDD>& f_hat,\n        unsigned int num_extra_bits = 16,\n        const abo::util::NumberRepresentation num_rep\n            = abo::util::NumberRepresentation::BaseTwo);\n\n} // namespace abo::error_metrics\n", "meta": {"hexsha": "88e6e0d7ac224e657d6fd5e79bcd4f7a1783c9ae", "size": 6825, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/worst_case_relative_error.hpp", "max_stars_repo_name": "keszocze/abo", "max_stars_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/error_metrics/worst_case_relative_error.hpp", "max_issues_repo_name": "keszocze/abo", "max_issues_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/error_metrics/worst_case_relative_error.hpp", "max_forks_repo_name": "keszocze/abo", "max_forks_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T14:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T14:50:31.000Z", "avg_line_length": 50.9328358209, "max_line_length": 100, "alphanum_fraction": 0.7245421245, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324611869563, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6454794066424291}}
{"text": "#include <Eigen/Core>\r\n#include <iostream>\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\n// define a custom template binary functor\r\ntemplate<typename Scalar> struct MakeComplexOp {\r\n  EIGEN_EMPTY_STRUCT_CTOR(MakeComplexOp)\r\n  typedef complex<Scalar> result_type;\r\n  complex<Scalar> operator()(const Scalar& a, const Scalar& b) const { return complex<Scalar>(a,b); }\r\n};\r\n\r\nint main(int, char**)\r\n{\r\n  Matrix4d m1 = Matrix4d::Random(), m2 = Matrix4d::Random();\r\n  cout << m1.binaryExpr(m2, MakeComplexOp<double>()) << endl;\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "b8951d11d188d6f8bb2075c499549f426c637d95", "size": 544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/class_CwiseBinaryOp.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/class_CwiseBinaryOp.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/doc/examples/class_CwiseBinaryOp.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": 28.6315789474, "max_line_length": 102, "alphanum_fraction": 0.7022058824, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6454793808083613}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearfeelementmatrix.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix<double, 4, 4> MyLinearFEElementMatrix::Eval(\n    const lf::mesh::Entity &cell) {\n  // Topological type of the cell\n  const lf::base::RefEl ref_el{cell.RefEl()};\n\n  // Obtain the vertex coordinates of the cell, which completely\n  // describe its shape.\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n  // Matrix storing corner coordinates in its columns\n  auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n  // Matrix for returning element matrix\n  Eigen::Matrix<double, 4, 4> elem_mat;\n\n  //====================\n  // Your code goes here\n  // eval member function returns the lememt matrix for the finite elemet space and the bilinear form \n  // in the weak formulation of 2.8.4\n  Eigen::Matrix<double, 4,4> elment_mat_lap; \n  Eigen::Matrix<double,4,4> element_mat_mass; \n\n  // define the class\n  lf::uscalfe::LinearFELaplaceElementMatrix laplace_elem_builder; \n  element_mat_lap = laplace_elem_builder.Eval(*cell); \n\n  // computations differ depending on the type of the cell\n  case lf::base:RefEl::kTria():{\n    double area = 0.5*((vertices(0,1)-vertices(0,0))*(vertices(1,2)-vertices(1,0)\n    )-(vertices(1,1)-vertices(1,0))*(vertices(0,2)-vertices(0,0))); \n    element_mat_mass >> 2.,1.,1.,0.,\n     1.,2.,1.,0., \n     1.,1.,2.,0.,\n     0.,0.,0.,0.; \n    element_mat_mass = area/12*elemet_mat_mass; \n    break; \n\n  } case lf::base::RefEl::Kquad():{\n    double area = (vertices(0,1)-vertices(0,0))*(vertices(1,3)-vertices(1,0)); \n    element_mat_mass >> 4.,2.,1.,2.,\n    2.,4.,2.,1.,\n    1.,2.,4.,2.,\n    2.,1.,2.,4.; \n    element_mat_mass = area/36*element_mat_mass;\n    break; \n  }\n\n  elem_mat = element_mat_mass + element_mat_lap; \n\n  // \n  //====================\n\n  return elem_mat;\n}\n/* SAM_LISTING_END_1 */\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "5cd1fc5757ed1d440be3cf1eb3e21a598465c310", "size": 2213, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5066666667, "max_line_length": 102, "alphanum_fraction": 0.6647085404, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726381, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6454793776020623}}
{"text": "#pragma once\n\n// Armadillo\n#include <armadillo>\n\nnamespace mant {\n  arma::mat hammersleySet(\n      const arma::uvec& bases,\n      const arma::uvec& seeds,\n      const arma::uword numberOfElements);\n  arma::mat hammersleySet(\n      const arma::uvec& bases,\n      const arma::uword numberOfElements);\n\n  arma::mat haltonSequence(\n      const arma::uvec& bases,\n      const arma::uvec& seeds,\n      const arma::uword numberOfElements);\n  arma::mat haltonSequence(\n      const arma::uvec& bases,\n      const arma::uword numberOfElements);\n\n  arma::vec vanDerCorputSequence(\n      const arma::uword base,\n      const arma::uword seed,\n      const arma::uword numberOfElements);\n  arma::vec vanDerCorputSequence(\n      const arma::uword base,\n      const arma::uword numberOfElements);\n}\n", "meta": {"hexsha": "fd9ab520e0b41c5f3c3b3852251c3ef0f6bb06e8", "size": 782, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mantella_bits/numberTheory.hpp", "max_stars_repo_name": "OpusV/AstroMechanics", "max_stars_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T22:06:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T22:06:56.000Z", "max_issues_repo_path": "include/mantella_bits/numberTheory.hpp", "max_issues_repo_name": "OpusV/AstroMechanics", "max_issues_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mantella_bits/numberTheory.hpp", "max_forks_repo_name": "OpusV/AstroMechanics", "max_forks_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2258064516, "max_line_length": 42, "alphanum_fraction": 0.6726342711, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6453988136889957}}
{"text": "/*\n   Copyright (C) 2016-2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n                              Chihiro Kondo <chihiro.kondo@phys.s.u-tokyo.ac.jp>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n// Density of state of square lattice Ising model\n\n#pragma once\n\n#include <cmath>\n#include <limits>\n#include <vector>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/differentiation/autodiff.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <lattice/graph.hpp>\n\nnamespace ising {\nnamespace dos {\nnamespace square {\n\ntypedef unsigned long uint_t;\n\nstd::vector<uint_t> count(uint_t Lx, uint_t Ly) {\n  auto basis = lattice::basis::simple(2);\n  auto unitcell = lattice::unitcell(2);\n  unitcell.add_site(lattice::coordinate(0, 0), 0);\n  unitcell.add_bond(0, 0, lattice::offset(1, 0), 0);\n  unitcell.add_bond(0, 0, lattice::offset(0, 1), 0);\n  auto graph = lattice::graph(basis, unitcell, lattice::extent(Lx, Ly));\n  if (graph.num_bonds() >= std::numeric_limits<uint_t>::digits)\n    throw std::range_error(\"Error: system size is too large\\n\");\n  \n  std::vector<uint_t> dos(graph.num_bonds() + 1, 0);\n  uint_t num_states = 1 << graph.num_sites();\n  for (uint_t c = 0; c < num_states; ++c) {\n    uint_t energy = 0;\n    for (uint_t b = 0; b < graph.num_bonds(); ++b) {\n      uint_t ci = (c >> graph.source(b)) & 1;\n      uint_t cj = (c >> graph.target(b)) & 1;\n      energy += (ci ^ cj);\n    }\n    ++dos[energy];\n  }\n  return dos;\n}\n\n// Density of state of square lattice Ising model\n\n// Ref: P. Beale, Phys. Rev. Lett. 76, 78-81 (1996)\n\nnamespace {\n  \ntemplate<typename T>\nT zero(const T& x) { return 0 * x; }\n\ntemplate<typename T>\nT one(const T& x) { return 1 + zero(x); }\n\ntemplate<typename T>\nT power_n(const T& x, unsigned n) {\n  auto res = one(x);\n  for (unsigned i = 0; i < n; ++i) res *= x;\n  return res;\n}\n\ntemplate<typename T>\nT alpha(const T& x, const T& beta, unsigned n, unsigned k) {\n  using std::cos;\n  auto pi = boost::math::constants::pi<typename T::root_type>();\n  return power_n(1 + x * x, 2) - beta * cos(pi * k / n);\n}\n\n}\n\nusing namespace boost::math;\nusing namespace boost::math::differentiation;\nnamespace mp = boost::multiprecision;\ntypedef mp::cpp_int int_type;\n  \ntemplate<unsigned Order, unsigned Digits10, class ExponentType = boost::int32_t>\nstd::vector<mp::cpp_int> finite(uint_t m, uint_t n) {\n  typedef mp::number<mp::cpp_dec_float<Digits10, ExponentType>> real_type;\n  std::cout << std::setprecision(std::numeric_limits<real_type>::max_digits10);\n\n  auto const x = make_fvar<real_type, Order>(0);\n  auto const xpo = make_fvar<real_type, Order>(-1);\n  auto const xmo = make_fvar<real_type, Order>(+1);\n\n  auto beta = 2 * x * xpo * xmo;\n  auto beta_m = power_n(beta, m);\n  auto c0 = power_n(xmo, m) + power_n(x * xpo, m);\n  auto s0 = power_n(xmo, m) - power_n(x * xpo, m);\n  auto cn = power_n(xpo, m) + power_n(x * xmo, m);\n  auto sn = power_n(xpo, m) - power_n(x * xmo, m);\n\n  auto z1 = zero(x);\n  auto z2 = zero(x);\n  auto z3 = zero(x);\n  auto z4 = zero(x);\n  if ((n & 1) == 0) {\n    z1 = one(x) / 2;\n    z2 = one(x) / 2;\n    z3 = c0 * cn / 2;\n    z4 = s0 * sn / 2;\n  } else {\n    z1 = cn / 2;\n    z2 = sn / 2;\n    z3 = c0 / 2;\n    z4 = s0 / 2;\n  }\n  for (unsigned k = 1; k < n; ++k) {\n    auto ak = alpha(x, beta, n, k);\n    auto v = zero(x);\n    for (unsigned j = 0; j <= m; j += 2)\n      v += binomial_coefficient<real_type>(m, j)\n        * power_n(ak * ak - beta * beta, j/2) * power_n(ak, m-j);\n    if ((k & 1) == 1) {\n      z1 *= (v + beta_m) / power_n(real_type(2), m - 1);\n      z2 *= (v - beta_m) / power_n(real_type(2), m - 1);\n    } else {\n      z3 *= (v + beta_m) / power_n(real_type(2), m - 1);\n      z4 *= (v - beta_m) / power_n(real_type(2), m - 1);\n    }\n  }\n  auto zmn = z1 + z2 + z3 + z4;\n\n  std::vector<int_type> dos;\n  for (unsigned i = 0; i <= 2 * m * n; ++i) dos.push_back(int_type(zmn.at(i) + 0.01));\n  auto sum = std::accumulate(dos.begin(), dos.end(), int_type(0));\n  if (sum != power_n(int_type(2), m * n)) {\n    std::cerr << \"Error: result check failed\\n\";\n    throw(0);\n  }\n  return dos;\n}\n\n}\n}\n}\n", "meta": {"hexsha": "6c3eea9d5fdff386a7e6a840db8a7334c2ceeff9", "size": 4745, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ising/dos/square.hpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "ising/dos/square.hpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "ising/dos/square.hpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4166666667, "max_line_length": 86, "alphanum_fraction": 0.6282402529, "num_tokens": 1528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6453988099698644}}
{"text": "// test_minimum.cpp\n// (c) Tivole\n\n#include <boost/test/unit_test.hpp>\n#include \"../src/numerary.hpp\"\n\nnamespace numerary\n{\n    \n    BOOST_AUTO_TEST_SUITE(TestMinimum)\n    \n    BOOST_AUTO_TEST_CASE(test_minimum_bisection)\n    {\n        const double eps = 1.e-9;\n        double answer;\n        double expected_answer;\n        short int result;\n        short int expected_result;\n\n        // Testing sin function\n        expected_result = 1;\n        expected_answer = -1.0 * M_PI_2;\n        result = Numerary::minimum(sin, -3, 3, &answer, \"bisection\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);\n\n\t    // Testing log function\n        expected_result = 1;\n        expected_answer = 0.5;\n        result = Numerary::minimum(log, 0.5, 4, &answer, \"bisection\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);\n    }\n\n\n    BOOST_AUTO_TEST_CASE(test_minimum_golden_ratio)\n    {\n        const double eps = 1.e-9;\n        double answer;\n        double expected_answer;\n        short int result;\n        short int expected_result;\n\n        // Testing sin function\n        expected_result = 1;\n        expected_answer = -1.0 * M_PI_2;\n        result = Numerary::minimum(sin, -3, 3, &answer, \"golden_ratio\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);\n\n\t    // Testing cos function\n        expected_result = 1;\n        expected_answer = 0.5;\n        result = Numerary::minimum(log, 0.5, 4, &answer, \"golden_ratio\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n}\n\n", "meta": {"hexsha": "ef6c63ed6975cca555d6b9c886a1162879d7809b", "size": 1782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_minimum.cpp", "max_stars_repo_name": "tivole/Numerary", "max_stars_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-02-21T06:09:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T10:00:06.000Z", "max_issues_repo_path": "test/test_minimum.cpp", "max_issues_repo_name": "tivole/Ti_Numerary", "max_issues_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_minimum.cpp", "max_forks_repo_name": "tivole/Ti_Numerary", "max_forks_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T11:12:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T11:12:27.000Z", "avg_line_length": 28.7419354839, "max_line_length": 78, "alphanum_fraction": 0.6251402918, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.645398809039921}}
{"text": "// HelloWorld.cpp : main project file.\r\n//#define _CRTDBG_MAP_ALLOC\r\n//#include <stdlib.h>\r\n//#include <crtdbg.h>\r\n#include \"stdafx.h\"\r\n#include <NTL/ZZ_pXFactoring.h>\r\n#include \"Shamir.h\"\r\n#include \"string.h\"\r\n#include \"ShamirShare.h\"\r\n#include \"BenalohLeichter.h\"\r\n//#include \"AccessStructure.h\"\r\n//#include \"Trustee.h\"\r\n#include \"ISecretShare.h\"\r\n#include \"NonInteractiveChaumPedersen.h\"\r\n#include \"NTLHelper.h\"\r\n#include \"PrimeGenerator.h\"\r\n#include <vector>\r\n#include \"Schoenmakers.h\"\r\n#include \"PublicKeyEncryption.h\"\r\n#include <tuple>\r\n//#include \"vld.h\"\r\nusing namespace System;\r\nusing namespace std;\r\nusing namespace NTL;\r\nusing namespace System::Collections::Generic;\r\nusing namespace SecretSharingCore::Algorithms;\r\nusing namespace SecretSharingCore::Algorithms::PVSS;\r\nusing namespace SecretSharingCore::Algorithms::PKE;\r\nusing namespace SecretSharingCore::Common;\r\nusing namespace SecretSharingCore::Algorithms::GeneralizedAccessStructure;\r\nusing namespace SecretSharing::OptimalThreshold::Models;\r\nusing namespace SecretSharing::OptimalThreshold;\r\nusing namespace SecretSharingCore::ZKProtocols;\r\nusing namespace SecretSharingCore;\r\n\r\nvoid MarshalString(String ^ s, string& os)\r\n{\r\n\tusing namespace Runtime::InteropServices;\r\n\tconst char* chars =\r\n\t\t(const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();\r\n\tos = chars;\r\n\tMarshal::FreeHGlobal(IntPtr((void*)chars));\r\n}\r\n\r\n\r\nvoid runByteChunkShare(){\r\n\tint k = 3;\r\n\tint n = 10;\r\n\tByte chunkSize = 16;\r\n\tString^ secret = \"1234567812345678\";\r\n\tarray<Byte>^ bytes = Encoding::UTF8->GetBytes(secret->ToCharArray());\r\n\tShamir^ secretshare = gcnew Shamir();\r\n#ifdef calcPrimeTime\r\n\tdouble a = 0;\r\n\tList<IShareCollection^>^ shares = secretshare->DivideSecret(k, n, bytes,chunkSize,a);\r\n#else\r\n\tList<IShareCollection^>^ shares = secretshare->DivideSecret(k, n, bytes, chunkSize);\r\n#endif\r\n\t//List<IShareCollection^>^ sharesStr = secretshare->DivideSecret(k, n,secret);\r\n\tdelete bytes;\r\n\tfor (int i = 0; i < k; i++)\r\n\t{\r\n\t\tIShareCollection^ col = shares[i];\r\n\t\t//IShareCollection^ colstr = sharesStr[i];\r\n\r\n\t\tConsole::WriteLine(col->ToString());\r\n\t\t//Console::WriteLine(colstr->ToString()); \r\n\r\n\t/*\tfor (int j = 0; j < col->GetCount(); j++)\r\n\t\t{\r\n\t\t\tIShare^ share = col->GetShare(j);\r\n\t\t\tIShare^ shareStr = colstr->GetShare(j);\r\n\t\t\tConsole::WriteLine(share->ToString());\r\n\t\t\tConsole::WriteLine(shareStr->ToString());\r\n\t\t}*/\r\n\t}\r\n\r\n\tList<IShareCollection^>^ recshares = shares->GetRange(0, k);\r\n\tarray<Byte>^ recoveredSecret = secretshare->ReconstructSecret(recshares, chunkSize);\r\n\t//List<IShareCollection^>^ recsharesstr = sharesStr->GetRange(0, k);\r\n\t//String^ recoveredSecretstr = secretshare->ReconstructSecret(recsharesstr);\r\n\r\n\tConsole::WriteLine(\"Secret:\"+Encoding::UTF8->GetString(recoveredSecret));\r\n\tfor (int i = 0; i < recshares->Count; i++)\r\n\t{\r\n\t\tdelete recshares[i];\r\n\t}\r\n\t//Console::WriteLine(\"SecretStr:\" + recoveredSecretstr);\r\n}\r\n\r\n\r\nvoid PrintIShares(List<IShare^>^ shares){\r\n\tfor (int j = 0; j < shares-> Count; j++)\r\n\t{\r\n\t\tConsole::WriteLine(shares[j]->ToString());\r\n\t}\r\n}\r\n\r\nint main(array<System::String ^> ^args)\r\n{\r\n\t//PrimeGenerator^ pg = gcnew PrimeGenerator();\r\n\t//ZZ p = ZZ(263);\r\n\t//ZZ_p::init(p);\r\n\t//cout<< pg->IsGeneratorOfP(p, ZZ_p(5));\r\n\t//Console::Read();\r\n\r\n\tSchoenmakers^ sch = gcnew Schoenmakers();\r\n\tsch->SelectPrimeAndGenerators(1);\r\n\tZZ_p g = sch->Getg();\r\n\tZZ_p G = sch->GetG();\r\n\tZZ q = sch->Getq();\r\n\tcout <<\"g:\"<<g <<'\\n';\r\n\tcout << \"G:\" << G << '\\n';\r\n\tcout << \"q:\" << q << '\\n';\r\n\t\r\n\tint n = 5;\r\n\t// generate n keypairs\r\n\tvector<ZZ_p> publickeys;\r\n\tvector<tuple<ZZ_p, ZZ_p>> keypairs;\r\n\tPublicKeyEncryption^ pke = gcnew PublicKeyEncryption();\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\ttuple<ZZ_p,ZZ_p> pair= pke->GenerateKeyPair(q, G);\r\n\t\tkeypairs.push_back(pair);\r\n\t\t//cout <<\"x:\"<< get<0>(pair)<<\" y:\"<<get<1>(pair)<<'\\n';\r\n\t\tpublickeys.push_back(get<1>(pair));\r\n\t}\r\n\t\r\n\r\n\tint t = 3;\r\n\t\r\n\tvector<ZZ_p> encryptedShares;\r\n\tvector<ZZ_p> commitments;\r\n\tvector<ZZ_p> c,r;\r\n\tZZ_p secret;\r\n\t//provide public keys to schoenmakers\r\n\tsch->SetPublicKeys(publickeys);\r\n\r\n\tList<array<Byte>^>^ commitsList = gcnew List<array<Byte>^>();\r\n\tarray<Byte>^ secretB;\r\n\tarray<Byte>^ U;\r\n\tarray<Byte>^ sigma = Encoding::UTF8->GetBytes(\"4\");\r\n\tList<SchoenmakersShare^>^ shares =  sch->Distribute(t, n,sigma, commitsList, secretB,U);\r\n\tList<SchoenmakersShare^>^ poolesshares = gcnew List<SchoenmakersShare^> ();\r\n\tint i = 0;\r\n\tfor each (SchoenmakersShare^ share in shares)\r\n\t{\r\n\t\tSchoenmakersShare^ pooledshare = share;\r\n\t\tsch->PoolShare(gcnew Tuple<array<Byte>^, array<Byte>^>(NTLHelper::ZZpToByte(get<0>(keypairs.at(i))), NTLHelper::ZZpToByte(get<1>(keypairs.at(i)))), pooledshare);\r\n\t\tpoolesshares->Add(pooledshare);\r\n\t\ti++;\r\n\t}\r\n\tarray<Byte>^ reconed = sch->Reconstruct(t, poolesshares, U);\r\n\t//Console::Read();\r\n\r\n\tsch->Distribute(t, n, encryptedShares, commitments, r, c,secret);\r\n\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\tbool verified = sch->VerifyDistributedShare(i+1, r.at(i), c.at(i), encryptedShares.at(i), commitments, publickeys.at(i));\r\n\t\tcout << \"share i:\" << i+1 << \" verified status:\" << verified<<'\\n';\r\n\t\t//if (!verified) throw gcnew Exception(\"Failed to verify the share!\");\r\n\t}\r\n\tvector<ZZ_p> rshares;\r\n\tvector<ZZ_p> cshares;\r\n\tvector<ZZ_p> S;\r\n\tfor (int i = 0; i < encryptedShares.size(); i++)\r\n\t{\r\n\t\tZZ_p rshare, cshare;\r\n\t\t//each party pool his share and compute zero knowledge r and c\r\n\t\tZZ_p Si = sch->PoolShare(get<0>(keypairs.at(i)), get<1>(keypairs.at(i)), encryptedShares.at(i), rshare, cshare);\r\n\t\trshares.push_back(rshare);\r\n\t\tcshares.push_back(cshare);\r\n\t\tS.push_back(Si);\r\n\t}\r\n\t//dealer, at this point can verify decrypted shares\r\n\tbool verifyConstruction = sch->VerifyPooledShares(t, S, encryptedShares, rshares, cshares);\r\n\tcout << \"Construction verified:\" << verifyConstruction<<'\\n';\r\n\r\n\tif (verifyConstruction){\r\n\t\tZZ_p secret = sch->Reconstruct(t,S);\r\n\t\tcout <<\"secret:\" <<secret<<'\\n';\r\n\t}\r\n\tConsole::Read();\r\n\treturn 0;\r\n\r\n\tagain:\r\n\tarray<Byte>^ Prime =   NTLHelper::NumberToZZByte(17);\r\n\tNTLHelper::InitZZ_p(Prime);\r\n\r\n\tarray<Byte>^ Base1 = NTLHelper::NumberToZZpByte(3);\r\n\tarray<Byte>^ Base2 = NTLHelper::NumberToZZpByte(5); \r\n    array<Byte>^ Result1 = NTLHelper::NumberToZZpByte((long)pow(3,7));\r\n\tarray<Byte>^ Result2 = NTLHelper::NumberToZZpByte((long)pow(5,7));\r\n\tarray<Byte>^ Secret = NTLHelper::NumberToZZpByte(7);\r\n\tarray<Byte>^ R;\r\n\tarray<Byte>^ C;\r\n\r\n\t\r\n\t\r\n\tNonInteractiveChaumPedersen^ NICP = gcnew NonInteractiveChaumPedersen(Prime);\r\n\tNICP->ComputeProofs(Base1,Base2,Result1,Result2,Secret,R,C);\r\n\tbool Proved = NICP ->VerifyProofs(Base1,Base2,Result1,Result2,R,C);\r\n\tcout << \"Proved:\" << Proved<<'\\n';\r\n\tConsole::Read();\r\n\tgoto again;\r\n\r\n\t/*ZZ prime = ZZ(17);\r\n\tZZ_p::init(prime);\r\n\tNonInteractiveChaumPedersen^ nicp = gcnew NonInteractiveChaumPedersen(prime);\r\n\tZZ_p base1 = ZZ_p(3);\r\n\tZZ_p base2 = ZZ_p(5);\r\n\tZZ secret = ZZ(7);\r\n\tZZ_p result1 = power(base1, secret);\r\n\tZZ_p result2 = power(base2, secret);\r\n\tZZ_p c;\r\n\tZZ_p r;\r\n\tnicp->ComputeProofs(base1, base2, result1, result2, to_ZZ_p(secret), r, c);\r\n\r\n\tcout <<\"r: \"<< r<<'\\n';\r\n\tcout << \"c: \" << c << '\\n';\r\n\r\n\tbool proved = nicp->VerifyProofs(base1, base2, result1, result2, r, c);\r\n\tcout << \"proved:\" << proved<<'\\n';\r\n\tConsole::Read();\r\n\r\n\tgoto again;*/\r\n\r\n\t/*BenalohLeichter^ benaloh = gcnew BenalohLeichter();\r\n\tAccessStructure^ access = gcnew AccessStructure(\"p1^p2^p3,p2^p3^p4,p1^p3^p4,p1^p2^p4\");\r\n\taccess = ThresholdHelper::OptimiseAccessStructure(access, true);\r\n\tarray<Byte>^ secretBytes = Encoding::UTF8->GetBytes(\"12345678\");\r\n\tList<IShareCollection^>^ shares =  benaloh->DivideSecret(secretBytes, access);\r\n\tarray<Byte>^ reconSecretBytes = benaloh->ReconstructSecret(shares[0]);\r\n\tConsole::WriteLine(Encoding::UTF8->GetString(reconSecretBytes));\r\n*/\r\n\t//_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);\r\n\r\n\t/*Vec<ZZ_p> y = vec_ZZ_p();\r\n\tVec<ZZ_p> x = vec_ZZ_p();\r\n\r\n\tZZ_p::init(ZZ(199));\r\n\tZZ_p y1 = ZZ_p(68);\r\n\tZZ_p y2 = ZZ_p(2);\r\n\tZZ_p y3 = ZZ_p(92);\r\n\r\n\r\n\r\n\t\tx.append(ZZ_p(1));\r\n\t\tx.append(ZZ_p(2));\r\n\t\tx.append(ZZ_p(3));\r\n\r\n\r\n\t\ty.append(y1);\r\n\t\ty.append(y2);\r\n\t\ty.append(y3);\r\n\t\t\r\n\r\n\tZZ_pX interpolatedf = interpolate(x, y);\r\n\tcout << \"interpol g(x):\" << interpolatedf;*/\r\n\r\n\t//runByteChunkShare();\r\n\r\n\t//IShare^ sharezz = gcnew ShamirShare(1, &ZZ_p(2));\r\n\r\n\t/*\r\n\tint k = 4;\r\n\tint n = 10;\r\n\tString^ secret = \"1234\";\r\n\r\n\r\n\r\n\tShamir^ secretshare = gcnew Shamir();\r\n\tList<IShareCollection^>^ shares = secretshare->DivideSecret(k, n, secret);\r\n\t\r\n\t\r\n\tfor (int i = 0; i < shares->Count; i++)\r\n\t{\r\n\t\tIShareCollection^ col = shares[i];\r\n\t\tConsole::WriteLine(col->ToString());\r\n\t\tfor (int j = 0; j < col->GetCount(); j++)\r\n\t\t{\r\n\t\t\tIShare^ share = col->GetShare(j);\r\n\t\t\tConsole::WriteLine(share->ToString());\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tList<IShareCollection^>^ frecshares = shares->GetRange(0, k - 1);\r\n\tString^ frecoveredSecret = secretshare ->ReconstructSecret(frecshares);\r\n\tConsole::WriteLine(\"recovered secret with k-1 shares:{0} secret:{1}\", frecshares->Count, frecoveredSecret);\r\n\r\n\r\n\tList<IShareCollection^>^ recshares = shares->GetRange(0, k);\r\n\tString^ recoveredSecret = secretshare->ReconstructSecret(recshares);\r\n\tConsole::WriteLine(\"recovered secret with k shares:{0} secret:{1}\", recshares->Count, recoveredSecret);*/\r\n\r\n\t/*\r\n\tint a1 = 166;\r\n\tint a2 = 94;\r\n\r\n\tint p = 1613;\r\n\r\n\tZZ_p::init(ZZ(p));\r\n\r\n\tZZ_pX f;\r\n\tf.SetLength( k-1);\r\n\tSetCoeff(f, 0, ZZ_p(secret));\r\n\tSetCoeff(f, 1, ZZ_p(a1));\r\n\tSetCoeff(f, 2, ZZ_p(a2));\r\n\r\n\tcout << f;\r\n\r\n\tZZ_p d1 = eval(f, ZZ_p(1));\r\n\tZZ_p d2 = eval(f, ZZ_p(2));\r\n\tZZ_p d3 = eval(f, ZZ_p(3));\r\n\tZZ_p d4 = eval(f, ZZ_p(4));\r\n\tZZ_p d5 = eval(f, ZZ_p(5));\r\n\tZZ_p d6 = eval(f, ZZ_p(6));\r\n\r\n\tcout << '\\n' << d1 << '\\n' << d2 << '\\n' << d3 << '\\n' << d4 << '\\n' << d5 << '\\n' << d6;\r\n\r\n\tVec<ZZ_p> x = vec_ZZ_p();\r\n\tfor (int i = 1; i < 4; i++)\r\n\t{\r\n\t\tx.append(ZZ_p(i));\r\n\t}\r\n\t\r\n\tVec<ZZ_p> y = vec_ZZ_p();\r\n\ty.append(d1);\r\n\ty.append(d2);\r\n\ty.append(d3);\r\n\tZZ_pX interpolatedf = interpolate(x, y);\r\n\tcout << \"secret is:\" << eval(interpolatedf, ZZ_p(0));\r\n\r\n\t/*ZZ p;\r\n\tGenPrime(p, 10);\r\n\tlong val = RandomPrime_long(8);\r\n\tcout << p << \"/n\";\r\n\tcout << val;\r\n\tcin >> p;\r\n\tZZ_p::init(p);\r\n\r\n\t\r\n\r\n\tZZ_pX f;\r\n\tcin >> f;\r\n\r\n\tVec< Pair< ZZ_pX, long > > factors;\r\n\r\n\tCanZass(factors, f);  // calls \"Cantor/Zassenhaus\" algorithm\r\n\r\n\tcout << factors << \"\\n\";\r\n\t*/\t//_CrtDumpMemoryLeaks(); \r\n}\r\n", "meta": {"hexsha": "76e50d07bfc77fb0a05495da28c95b60e23cc345", "size": 10310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SecretSharing.Core/Main.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SecretSharing.Core/Main.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SecretSharing.Core/Main.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9606741573, "max_line_length": 164, "alphanum_fraction": 0.6526673133, "num_tokens": 3211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759583, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6453988062504112}}
{"text": "\n// solving A * X = B\n// using driver function gesv()\n\n#include <cstddef>\n#include <iostream>\n#include <vector>\n#include <boost/numeric/bindings/lapack/gesv.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/std_vector.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef ublas::matrix<double, ublas::column_major> m_t;\n\nint main() {\n\n  cout << endl; \n\n  size_t n = 5;   \n  m_t a (n, n);   // system matrix \n\n  size_t nrhs = 2; \n  m_t x (n, nrhs), b (n, nrhs);  // b -- right-hand side matrix\n\n  init_symm (a); \n  //     [n   n-1 n-2  ... 1]\n  //     [n-1 n   n-1  ... 2]\n  // a = [n-2 n-1 n    ... 3]\n  //     [        ...       ]\n  //     [1   2   ...  n-1 n]\n\n  m_t aa (a); // copy of a, because a is `lost' after gesv()\n\n  ublas::matrix_column<m_t> xc0 (x, 0), xc1 (x, 1); \n  for (int i = 0; i < xc0.size(); ++i) {\n    xc0 (i) = 1.;\n    xc1 (i) = 2.; \n  }\n  b = prod (a, x); \n\n  print_m (a, \"A\"); \n  cout << endl; \n  print_m (b, \"B\"); \n  cout << endl; \n\n  lapack::gesv (a, b);  // solving the system, b contains x \n\n  print_m (b, \"X\");\n  cout << endl; \n\n  x = prod (aa, b); \n  print_m (x, \"B = A X\"); \n\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "70dd07e02b181d394684d92c7a336deb8d72e4e1", "size": 1359, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gesv2.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gesv2.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gesv2.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 20.5909090909, "max_line_length": 63, "alphanum_fraction": 0.5540838852, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7341195210831258, "lm_q1q2_score": 0.6453987992767989}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2020 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file momentbasedgaussianpolynomial.hpp\n    \\brief Gaussian quadrature defined by the moments of the distribution\n*/\n\n#ifndef quantlib_moment_based_gaussian_polynomial_hpp\n#define quantlib_moment_based_gaussian_polynomial_hpp\n\n#include <ql/math/comparison.hpp>\n#include <ql/math/integrals/gaussianorthogonalpolynomial.hpp>\n#include <ql/errors.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <vector>\n\nnamespace QuantLib {\n    /*! References:\n        Gauss quadratures and orthogonal polynomials\n\n        G.H. Gloub and J.H. Welsch: Calculation of Gauss quadrature rule.\n        Math. Comput. 23 (1986), 221-230,\n        http://web.stanford.edu/class/cme335/spr11/S0025-5718-69-99647-1.pdf\n\n        M. Morandi Cecchi and M. Redivo Zaglia, Computing the coefficients\n        of a recurrence formula for numerical integration by moments and\n        modified moments.\n        http://ac.els-cdn.com/0377042793901522/1-s2.0-0377042793901522-main.pdf?_tid=643d5dca-a05d-11e6-9a56-00000aab0f27&acdnat=1478023545_cf7c87cba4cc9e37a136e68a2564d411\n    */\n\n    template <class mp_real>\n    class MomentBasedGaussianPolynomial\n            : public GaussianOrthogonalPolynomial {\n      public:\n        MomentBasedGaussianPolynomial();\n\n        Real mu_0() const;\n        Real alpha(Size i) const;\n        Real beta(Size i) const;\n\n        virtual mp_real moment(Size i) const = 0;\n\n      private:\n        mp_real alpha_(Size i) const;\n        mp_real beta_(Size i) const;\n\n        mp_real z(Integer k, Integer i) const;\n\n        mutable std::vector<mp_real> b_, c_;\n        mutable std::vector<std::vector<mp_real> > z_;\n    };\n\n    template <class mp_real> inline\n    MomentBasedGaussianPolynomial<mp_real>::MomentBasedGaussianPolynomial()\n    : z_(1, std::vector<mp_real>()) {}\n\n    template <class mp_real> inline\n    mp_real MomentBasedGaussianPolynomial<mp_real>::z(Integer k, Integer i) const {\n        if (k == -1) return mp_real(0.0);\n\n        const Integer rows = z_.size();\n        const Integer cols = z_[0].size();\n\n        if (cols <= i) {\n            for (Integer l=0; l<rows; ++l)\n                z_[l].resize(i+1, std::numeric_limits<mp_real>::quiet_NaN());\n        }\n        if (rows <= k) {\n            z_.resize(k+1, std::vector<mp_real>(\n                z_[0].size(), std::numeric_limits<mp_real>::quiet_NaN()));\n        }\n\n        if (boost::math::isnan(z_[k][i])) {\n            if (k == 0)\n                z_[k][i] = moment(i);\n            else {\n                const mp_real tmp = z(k-1, i+1)\n                    - alpha_(k-1)*z(k-1, i) - beta_(k-1)*z(k-2, i);\n                z_[k][i] = tmp;\n            }\n        }\n\n        return z_[k][i];\n    };\n\n    template <class mp_real> inline\n    mp_real MomentBasedGaussianPolynomial<mp_real>::alpha_(Size u) const {\n\n        if (b_.size() <= u)\n            b_.resize(u+1, std::numeric_limits<mp_real>::quiet_NaN());\n\n        if (boost::math::isnan(b_[u])) {\n            if (u == 0)\n                b_[u] = moment(1);\n            else {\n                const Integer iu(u);\n                const mp_real tmp =\n                    -z(iu-1, iu)/z(iu-1, iu-1) + z(iu, iu+1)/z(iu, iu);\n                b_[u] = tmp;\n            }\n        }\n        return b_[u];\n    }\n\n    template <class mp_real> inline\n    mp_real MomentBasedGaussianPolynomial<mp_real>::beta_(Size u) const {\n        if (u == 0)\n            return mp_real(1.0);\n\n        if (c_.size() <= u)\n            c_.resize(u+1, std::numeric_limits<mp_real>::quiet_NaN());\n\n        if (boost::math::isnan(c_[u])) {\n            const Integer iu(u);\n            const mp_real tmp = z(iu, iu) / z(iu-1, iu-1);\n            c_[u] = tmp;\n        }\n        return c_[u];\n    }\n\n    template <> inline\n    Real MomentBasedGaussianPolynomial<Real>::alpha(Size u) const {\n        return alpha_(u);\n    }\n\n    template <class mp_real> inline\n    Real MomentBasedGaussianPolynomial<mp_real>::alpha(Size u) const {\n        return alpha_(u).template convert_to<Real>();\n    }\n\n    template <> inline\n    Real MomentBasedGaussianPolynomial<Real>::beta(Size u) const {\n        return beta_(u);\n    }\n\n    template <class mp_real> inline\n    Real MomentBasedGaussianPolynomial<mp_real>::beta(Size u) const {\n        mp_real b = beta_(u);\n        return b.template convert_to<Real>();\n    }\n\n    template <> inline\n    Real MomentBasedGaussianPolynomial<Real>::mu_0() const {\n        const Real m0 = moment(0);\n        QL_REQUIRE(close_enough(m0, 1.0), \"zero moment must by one.\");\n\n        return moment(0);\n    }\n\n    template <class mp_real> inline\n    Real MomentBasedGaussianPolynomial<mp_real>::mu_0() const {\n        return moment(0).template convert_to<Real>();\n    }\n}\n\n#endif\n", "meta": {"hexsha": "ba3a6eca41428cd9538cc412b704ff9a545d9391", "size": 5504, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/integrals/momentbasedgaussianpolynomial.hpp", "max_stars_repo_name": "urgu00/QuantLib", "max_stars_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-13T09:57:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T09:57:04.000Z", "max_issues_repo_path": "ql/math/integrals/momentbasedgaussianpolynomial.hpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T08:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:06:53.000Z", "max_forks_repo_path": "ql/math/integrals/momentbasedgaussianpolynomial.hpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-04T15:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T08:24:37.000Z", "avg_line_length": 31.8150289017, "max_line_length": 172, "alphanum_fraction": 0.6157340116, "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.645398794162752}}
{"text": "#include <SOperations.h>\n#include <assert.h>                  // for assert\n#include <algorithm>                 // for min\n#include <boost/core/enable_if.hpp>  // for enable_if_c<>::type\n#include <stdexcept>                 // for out_of_range\n\nusing namespace boost ;\n\n\n//https://stackoverflow.com/questions/35971827/c-boost-rational-class-floor-function\nnamespace boost {\n    template <typename IntType>\n    constexpr IntType floor(rational<IntType> const &num) {\n        return static_cast<IntType>(num.numerator() / num.denominator());\n    }\n    template <typename IntType>\n    constexpr IntType ceil(rational<IntType> const &num) {\n        auto inum = static_cast<IntType>(num.numerator() / num.denominator());\n        return (num == inum) ? inum : ((num.numerator() > 0) ? ++ inum : --inum) ;\n    }\n}\n\n/*\nfor i in range(0,10):\n     if floor(i*delta)==floor((i+1)*delta):\n         print B[i-int(floor((i+1)*delta))],\n     else:\n         print A[int(floor(i*delta))],\n\ndeltaC = (deltaA*deltaB)/(deltaA+deltaB)\n*/\n\nrational<int> deltaHash(const rational<int> &arg1, const rational<int> &arg2) {\n    assert(arg1 + arg2 != 0);\n    return (arg1 * arg2) / (arg1 + arg2);\n}\n\nbool Hash(const rational<int> &deltaA, const rational<int> &deltaB, const int i, int &retPos) {\n    assert(deltaA > 0);\n    assert(deltaB > 0);\n    const rational<int> delta = deltaB / (deltaA + deltaB) ;\n    bool ret = floor(delta * i) == floor(delta * (i + 1));\n\n    if (ret) {\n        retPos = i - (floor((i + 1) * delta));        //B\n    } else {\n        retPos = floor(i * delta);    //A\n    }\n\n    return ret ;\n}\n\n/*\n#hash - begin\ndelta=deltaB/(deltaA+deltaB)\n\nfor i in range(0,24):\n    if int(i*delta)==int((i+1)*delta):\n        C.append( B[i-int((i+1)*delta)] )\n    else:\n        C.append( A[int(i*delta)] )\n#hash - end\n\n#div - begin\ndeltaC=(deltaA*deltaB)/(deltaA+deltaB)\n\ndeltaA_ = deltaB*deltaC/(deltaB-deltaC)\nassert(deltaA_ == deltaA)\nfrom math import ceil\nfor i in range(0,5) :\n    print C[i+int(ceil((i+1)*deltaA/deltaB))],    <--- tu jest to div\n#Output: 1 2 3 4 5\n\n#div- end\n*/\n\nint Div(const boost::rational<int> &deltaA, const boost::rational<int> &deltaB, const int i) {\n    return i + ceil((i + 1) * deltaA / deltaB);\n}\n\n/*\n#hash - begin\ndelta=deltaB/(deltaA+deltaB)\n\nfor i in range(0,24):\n    if int(i*delta)==int((i+1)*delta):\n        C.append( B[i-int((i+1)*delta)] )\n    else:\n        C.append( A[int(i*delta)] )\n\n#hash - end\n\n#mod - begin\ndeltaC=(deltaA*deltaB)/(deltaA+deltaB)\n\ndeltaB_ = deltaA*deltaC/(deltaA-deltaC)\nassert(deltaB_ == deltaB)\nfor i in range(0,10) :\n    print C[i+int(i*deltaB/deltaA)],                <--- tu jest mod\n#Output: a b c d e f g h i j#\n\n#mod - end\n*/\n\n\nint Mod(const boost::rational<int> &deltaA, const boost::rational<int> &deltaB, const int i) {\n    return i + floor(i * deltaB / deltaA);\n}\n\n/* Ta funkcja jest taka sama dla obu operacji */\n\nrational<int> deltaDivMod(const rational<int> &arg1, const rational<int> &arg2) {\n    assert(arg1 != arg2);\n\n    if (arg1 == arg2) {\n        throw std::out_of_range(\"Delta are equal in DehashDiv - undefinied.\");\n    }\n\n    return (arg1 * arg2) / abs(arg1 - arg2);\n}\n\n/*\nfrom math import ceil\nfor i in range(0,10):\n    if deltaA > deltaB :\n        print C[int(ceil(i*deltaA/deltaB))][0],\n    else:\n        print C[i][0],\n*/\n\nrational<int> deltaSubstract(const rational<int> &arg1) {\n    return arg1 ;\n}\n//todo\nint Substract(const rational<int> &deltaA, const rational<int> &deltaB, const int i) {\n    return ceil(i * deltaA / deltaB);\n}\n\nrational<int> deltaAdd(const rational<int> &arg1, const rational<int> &arg2) {\n    return std::min(arg1, arg2) ;\n}\n\n/*\ndeltaC = min( deltaA,deltaB )\nfor i in range(0,10):\n     if deltaC == deltaA:\n         print str(A[i])+B[int(i*deltaA/deltaB)],\n     else:\n         print str(A[int(i*deltaB/deltaA)])+B[i],\n*/\n\n\nrational<int> deltaTimemove(const rational<int> &arg1, const rational<int> &arg2) {\n    return arg1 ;\n}\n\nint agse(int offset, int step) {\n    return floor(boost::rational<int> (offset) / boost::rational<int> (step));\n}\n\nvoid SOperations_regtest() {\n    boost::rational<int> a(1, 2) ;\n    boost::rational<int> b(1, 3) ;\n    boost::rational<int> c(2, 3) ;\n    boost::rational<int> d(5, 4) ;\n    boost::rational<int> e(1) ;\n    boost::rational<int> f(0) ;\n    boost::rational<int> g(-2, 3);\n    boost::rational<int> h(-1);\n    boost::rational<int> j(-5, 4);\n    assert(floor(a) == 0);\n    assert(floor(b) == 0);\n    assert(floor(c) == 0);\n    assert(floor(d) == 1);\n    assert(floor(e) == 1);\n    assert(floor(f) == 0);\n    assert(floor(g) == 0);\n    assert(floor(h) == -1);\n    assert(floor(j) == -1);\n    assert(ceil(a) == 1);\n    assert(ceil(b) == 1);\n    assert(ceil(c) == 1);\n    assert(ceil(d) == 2);\n    assert(ceil(e) == 1);\n    assert(ceil(f) == 0);\n    assert(ceil(g) == -1);\n    assert(ceil(h) == -1);\n    assert(ceil(j) == -2);\n}", "meta": {"hexsha": "a61038d4ccea2fda96ab89a46178044870580818", "size": 4863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/share/SOperations.cpp", "max_stars_repo_name": "fossabot/retractordb", "max_stars_repo_head_hexsha": "b926c93fdb0fbe3897d85335d483e91573192bfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/share/SOperations.cpp", "max_issues_repo_name": "fossabot/retractordb", "max_issues_repo_head_hexsha": "b926c93fdb0fbe3897d85335d483e91573192bfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/share/SOperations.cpp", "max_forks_repo_name": "fossabot/retractordb", "max_forks_repo_head_hexsha": "b926c93fdb0fbe3897d85335d483e91573192bfd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7301587302, "max_line_length": 95, "alphanum_fraction": 0.5924326547, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6453987918382145}}
{"text": "/**\n * @file getBoundingBox.cpp\n */\n#include <pcl/common/centroid.h>\n#include <pcl/point_types.h>\n#include <pcl/common/common.h>\n#include <pcl/common/transforms.h>\n#include <Eigen/Eigenvalues>\n#include <pcl/visualization/pcl_visualizer.h>\n\n#include \"getBoundingBox.h\"\n\n/**\n * @function getBoundingBox\n * @brief Shows a visualizer with the bounding box and prints out its dimensions\n */\ntemplate<typename PointType>\nvoid getBoundingBox( const boost::shared_ptr< pcl::PointCloud<PointType> > &_input  ) { \n \n  // Compute principal direction\n  Eigen::Vector4f centroid;\n  pcl::compute3DCentroid( *_input, centroid );\n\n  Eigen::Matrix3f covariance;\n  pcl::computeCovarianceMatrixNormalized( *_input, \n\t\t\t\t\t  centroid, \n\t\t\t\t\t  covariance);\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigenSolver( covariance, \n\t\t\t\t\t\t\t      Eigen::ComputeEigenvectors);\n  Eigen::Matrix3f eigDx = eigenSolver.eigenvectors();\n  eigDx.col(2) = eigDx.col(0).cross( eigDx.col(1));\n  \n  // Move the points to that reference frame\n  Eigen::Matrix4f p2w( Eigen::Matrix4f::Identity() );\n\n  // [Rt, -Rt*T]\n  p2w.block<3,3>(0,0) = eigDx.transpose();\n  p2w.block<3,1>(0,3) = -1.0*( p2w.block<3,3>(0,0) )*(centroid.head<3>());\n  pcl::PointCloud<pcl::PointXYZ> input_p;\n  pcl::transformPointCloud( *_input, input_p, p2w );\n  \n  //-- Get max and min\n  pcl::PointXYZ minP, maxP;\n  pcl::getMinMax3D( input_p, minP, maxP );\n  const Eigen::Vector3f meanDiag( 0.5*(minP.x + maxP.x), \n\t\t\t\t  0.5*(minP.y + maxP.y), \n\t\t\t\t  0.5*(minP.z + maxP.z));\n  \n  //-- Final transform\n  const Eigen::Quaternionf qfinal( eigDx );\n  const Eigen::Vector3f tfFinal = eigDx*meanDiag + centroid.head<3>();\n\n  //-- Box Dimensions\n  double bx = maxP.x - minP.x;\n  double by = maxP.y - minP.y;\n  double bz = maxP.z - minP.z;\n\n  //-- Center of 6 box's faces\n  Eigen::VectorXf bc[6];\n  bc[0] = tfFinal + eigDx.col(0)*bx / 2.0;\n  bc[1] = tfFinal - eigDx.col(0)*bx / 2.0;\n  bc[2] = tfFinal + eigDx.col(1)*by / 2.0;\n  bc[3] = tfFinal - eigDx.col(1)*by / 2.0;\n  bc[4] = tfFinal + eigDx.col(2)*bz / 2.0;\n  bc[5] = tfFinal - eigDx.col(2)*bz / 2.0;\n\n\n  //-- Print info\n  std::cout << \" * Centroid: \"<< centroid.head(3).transpose() << std::endl;\n  std::cout << \" * Dimensions: \"<<bx<< \", \"<<by<<\", \"<<bz<< std::endl; \n\n  //-- Show visualizer\n\n  pcl::visualization::PCLVisualizer viewer;\n  viewer.addPointCloud( _input );\n  viewer.addCube( tfFinal, qfinal, bx, by, bz );\n\n  // Add center of box faces\n  for( int i = 0; i < 6; ++i ) {\n      pcl::PointXYZ p; \n      p.x = bc[i](0); p.y = bc[i](1); p.z = bc[i](2);\n      char name[30];\n      sprintf( name, \"sphere%d\", i );\n      viewer.addSphere( p, 0.02, 1.0, 0.0, 0.0, name );\n  }\n\n  //viewer.addCoordinateSystem(1.0);\n  viewer.spin();\n\n  return;\n}\n", "meta": {"hexsha": "f46e593c9c828fb2344dc7f52c020345f4a49c6f", "size": 2726, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pcl_programs/src/getBoundingBox.hpp", "max_stars_repo_name": "ana-GT/utils", "max_stars_repo_head_hexsha": "c903555647ebf3fd4fb2b1dc46c3f8f2b7cbca18", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T13:22:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-29T07:58:41.000Z", "max_issues_repo_path": "pcl_programs/src/getBoundingBox.hpp", "max_issues_repo_name": "ana-GT/utils", "max_issues_repo_head_hexsha": "c903555647ebf3fd4fb2b1dc46c3f8f2b7cbca18", "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": "pcl_programs/src/getBoundingBox.hpp", "max_forks_repo_name": "ana-GT/utils", "max_forks_repo_head_hexsha": "c903555647ebf3fd4fb2b1dc46c3f8f2b7cbca18", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6304347826, "max_line_length": 88, "alphanum_fraction": 0.6294937638, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6453478162761752}}
{"text": "#ifndef USE_CUDA\n\n#include <kernel_vectormath.hpp>\n#include <Eigen/Dense>\n\n// C++ Version\nnamespace Kernel\n{\n    // sets vf := v\n    // vf is a vectorfield\n    // v is a vector\n    void fill(vectorfield & vf, const Vector3 & v)\n    {\n        for (unsigned int i=0; i<vf.size(); ++i)\n        {\n            vf[i] = v;\n        }\n    }\n\n    void scale(vectorfield & vf, const scalar & sc)\n    {\n        for (unsigned int i=0; i<vf.size(); ++i)\n        {\n            vf[i] *= sc;\n        }\n    }\n\n\n\t// computes the inner product of two vectorfields v1 and v2\n\tscalar dot(const vectorfield & v1, const vectorfield & v2)\n\t{\n\t\tscalar x = 0;\n\t\tfor (unsigned int i = 0; i<v1.size(); ++i)\n\t\t{\n\t\t\tx += v1[i].dot(v2[i]);\n\t\t}\n\t\treturn x;\n\t}\n\n    // computes the inner products of vectors in v1 and v2\n    // v1 and v2 are vectorfields\n    void dot(const vectorfield & v1, const vectorfield & v2, scalarfield & out)\n    {\n        for (unsigned int i=0; i<v1.size(); ++i)\n        {\n\t\t\tout[i] = v1[i].dot(v2[i]);\n        }\n    }\n\n    // computes the vector (cross) products of vectors in v1 and v2\n    // v1 and v2 are vector fields\n    void cross(const vectorfield & v1, const vectorfield & v2, vectorfield & out)\n    {\n        for (unsigned int i=0; i<v1.size(); ++i)\n        {\n            out[i] = v1[i].cross(v2[i]);\n        }\n    }\n\n\n    // out[i] += c*a\n    void add_c_a(const scalar & c, const Vector3 & a, vectorfield & out)\n    {\n        for(unsigned int idx = 0; idx < out.size(); ++idx)\n        {\n            out[idx] += c*a;\n        }\n    }\n\n    // out[i] += c*a[i]\n    void add_c_a(const scalar & c, const vectorfield & a, vectorfield & out)\n    {\n        for(unsigned int idx = 0; idx < out.size(); ++idx)\n        {\n            out[idx] += c*a[idx];\n        }\n    }\n\n\n    // out[i] += c * a*b[i]\n    void add_c_dot(const scalar & c, const Vector3 & a, const vectorfield & b, scalarfield & out)\n    {\n        for(unsigned int idx = 0; idx < out.size(); ++idx)\n        {\n            out[idx] += c*a.dot(b[idx]);\n        }\n    }\n\n    // out[i] += c * a[i]*b[i]\n    void add_c_dot(const scalar & c, const vectorfield & a, const vectorfield & b, scalarfield & out)\n    {\n        for(unsigned int idx = 0; idx < out.size(); ++idx)\n        {\n            out[idx] += c*a[idx].dot(b[idx]);\n        }\n    }\n\n\n    // out[i] += c * a x b[i]\n    void add_c_cross(const scalar & c, const Vector3 & a, const vectorfield & b, vectorfield & out)\n    {\n        for(unsigned int idx = 0; idx < out.size(); ++idx)\n        {\n            out[idx] += c*a.cross(b[idx]);\n        }\n    }\n\n    // out[i] += c * a[i] x b[i]\n    void add_c_cross(const scalar & c, const vectorfield & a, const vectorfield & b, vectorfield & out)\n    {\n        for(unsigned int idx = 0; idx < out.size(); ++idx)\n        {\n            out[idx] += c*a[idx].cross(b[idx]);\n        }\n    }\n\n}\n\n#endif", "meta": {"hexsha": "f1d60cd5d0590774d5a4d61c271df6ed9aab0e8e", "size": 2847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kernel_vectormath.cpp", "max_stars_repo_name": "GPMueller/vectorfield", "max_stars_repo_head_hexsha": "5fc3eedab8c0a381692a5c136037953421c392f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-22T15:02:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-22T15:02:26.000Z", "max_issues_repo_path": "src/kernel_vectormath.cpp", "max_issues_repo_name": "GPMueller/vectorfield", "max_issues_repo_head_hexsha": "5fc3eedab8c0a381692a5c136037953421c392f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kernel_vectormath.cpp", "max_forks_repo_name": "GPMueller/vectorfield", "max_forks_repo_head_hexsha": "5fc3eedab8c0a381692a5c136037953421c392f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-03T01:45:34.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-29T12:47:04.000Z", "avg_line_length": 23.9243697479, "max_line_length": 103, "alphanum_fraction": 0.5015806112, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.645275103246296}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"matplotlibcpp.h\"\n#include <boost/numeric/odeint.hpp>\n\nusing namespace boost::numeric::odeint;\n\n// Define a abbreviation for state type\ntypedef std::vector< double > state_type;\n\nnamespace plt = matplotlibcpp;\n\nconst double sigma = 10.0;\nconst double R = 28.0;\nconst double b = 8.0 / 3.0;\n\n// the system function can be a classical functions\nvoid lorenz( state_type &x , state_type &dxdt , double t )\n{                                                         \n    dxdt[0] = sigma * ( x[1] - x[0] );\n    dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n    dxdt[2] = x[0]*x[1] - b * x[2];\n}\n\nint main(int argc, char const *argv[])\n{\n    state_type x( 3 );\n    x[0] = x[1] = x[2] = 10.0;\n    const double dt = 0.01;\n    integrate_const( runge_kutta4< state_type >() , lorenz , x , 0.0 , 10.0 , dt );\n    \n    return 0;\n}\n", "meta": {"hexsha": "2e0669d984d231048f1e412be9f89130ba8ff572", "size": 863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lectures/Lec5/main.cpp", "max_stars_repo_name": "amirnn/Engineering-Mathematics", "max_stars_repo_head_hexsha": "99dd270dba8ca3357259afb9195a9136b33510d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lectures/Lec5/main.cpp", "max_issues_repo_name": "amirnn/Engineering-Mathematics", "max_issues_repo_head_hexsha": "99dd270dba8ca3357259afb9195a9136b33510d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/Lec5/main.cpp", "max_forks_repo_name": "amirnn/Engineering-Mathematics", "max_forks_repo_head_hexsha": "99dd270dba8ca3357259afb9195a9136b33510d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3823529412, "max_line_length": 83, "alphanum_fraction": 0.5747392816, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6452599874071528}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n\tMatrix3f A;\n\tA << 1, 2, 1,\n\t    2, 1, 0,\n\t    -1, 1, 2;\n\tcout << A << endl;\n\tcout << A * A * A * A * A * A * A << endl;\n\tcout << A.inverse() << endl;\n\tcout << A.determinant() << endl;\n\n\tMatrixXf B = MatrixXf::Random(5, 3);\n\tcout << B << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "7497373cb4d64c11417fd0c975f3fa675feca761", "size": 360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snippets/eigen/test_eigen.cpp", "max_stars_repo_name": "qeedquan/misc_utilities", "max_stars_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T18:17:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:02:53.000Z", "max_issues_repo_path": "snippets/eigen/test_eigen.cpp", "max_issues_repo_name": "qeedquan/misc_utilities", "max_issues_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snippets/eigen/test_eigen.cpp", "max_forks_repo_name": "qeedquan/misc_utilities", "max_forks_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:10:59.000Z", "avg_line_length": 15.652173913, "max_line_length": 43, "alphanum_fraction": 0.5416666667, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.645255694282497}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    typedef mtl::dense2D<double>       Matrix;\n    typedef mtl::dense_vector<double>  Vector;\n    \n    Matrix                             A(4, 4), L(4, 4), U(4, 4), AA(4, 4);\n    Vector\t       \t\t       v(4);\n    double \t\t\t       c=1.0;   \n  \n    for (unsigned i= 0; i < 4; i++)\n\tfor(unsigned j= 0; j < 4; j++) {\n\t    U[i][j]= i <= j ? c * (i+j+2) : (0);\n\t    L[i][j]= i > j ? c * (i+j+1) : (i == j ? (1) : (0));\n\t}\n    \n    std::cout << \"L is:\\n\" << L << \"U is:\\n\" << U;\n    A= L * U;\n    std::cout << \"A is:\\n\" << A;\n    AA= adjoint(A);\n   \n    for (unsigned i= 0; i < 4; i++)\n\tv[i]= double(i);\n\n    Vector b( A*v ), b2( adjoint(A)*v );\n\n    Matrix LU(A);\n    lu(LU);\n    std::cout << \"LU decomposition of A is:\\n\" << LU;\n\n    Matrix B( lu_f(A) );\n    std::cout << \"LU decomposition of A (as function result) is:\\n\" << B;\n    \n    Vector v1( lu_solve_straight(A, b) );\n    std::cout << \"v1 is \" << v1 << \"\\n\";\n\n    Vector v2( lu_solve(A, b) );\n    std::cout << \"v2 is \" << v2 << \"\\n\";\n    \n    mtl::dense_vector<unsigned> P;\n    lu(A, P);\n    std::cout << \"LU with pivoting is \\n\" << with_format(A, 5, 2) << \"Permutation is \" << P << \"\\n\";\n    Vector v3( lu_apply(A, P, b) );\n    std::cout << \"v3 is \" << v3 << \"\\n\";\n    \n    Vector v4(lu_adjoint_apply(A, P, b2));\n    std::cout << \"v4 is \" << v4 << \"\\n\";\n   \n    Vector v5(lu_adjoint_solve(AA, b));\n    std::cout << \"v5 is \" << v5 << \"\\n\";\n       \n    return 0;\n}\n", "meta": {"hexsha": "f21a99202fa14f973ca01c9228c9f6afe38f78df", "size": 1498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/lu_example.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/lu_example.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/lu_example.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 26.75, "max_line_length": 100, "alphanum_fraction": 0.4506008011, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6452556922106188}}
{"text": "//\n// Created by senbaikang on 21.05.21.\n//\n\n#include <cmath>\n#include <config.h>\n\n#include <boost/math/special_functions/digamma.hpp>\n\n#include \"probabilities.h\"\n\ndouble logBetaBinCountsTerm(\n    double sup,\n    double cov\n    )\n{\n  return std::lgamma(cov + 1.0) -  std::lgamma(sup + 1.0) - std::lgamma(cov - sup + 1.0);\n}\n\ndouble logBetaBinMixedTerm(\n    double sup,\n    double cov,\n    double mean,\n    double overDis\n    )\n{\n  return std::lgamma(sup + mean * overDis) + std::lgamma(cov - sup + overDis * (1.0 - mean)) - std::lgamma(cov + overDis);\n}\n\ndouble logBetaBinParamsTerm(\n    double mean,\n    double overDis\n    )\n{\n  return std::lgamma(overDis) - std::lgamma(mean * overDis) - std::lgamma(overDis * (1.0 - mean));\n}\n\ndouble logBetaBinPDF(\n    double sup,\n    double cov,\n    double mean,\n    double overDis\n)\n{\n  if (cov == 0)\n    return 0;\n\n  return logBetaBinCountsTerm(sup, cov) +\n         logBetaBinMixedTerm(sup, cov, mean, overDis) +\n         logBetaBinParamsTerm(mean, overDis);\n}\n\ndouble computeRawWildLogScore(\n    Config const &config,\n    double altCount,\n    double coverage\n    )\n{\n  return logBetaBinPDF(\n      altCount,\n      coverage,\n      config.getEffectiveSeqErrRate() / 3.0,\n      config.getWildOverdispersion()\n      );\n//  return logBetaBinPDF(\n//      altCount,\n//      coverage,\n//      config.getEffectiveSeqErrRate(),\n//      config.getWildOverdispersion()\n//  );\n}\n\ndouble computeRawHeteroMutLogScore(\n    Config const &config,\n    double altCount,\n    double coverage\n    )\n{\n  return logBetaBinPDF(\n      altCount,\n      coverage,\n      0.5 - config.getEffectiveSeqErrRate() / 3.0,\n      config.getMuOverdispersion()\n      );\n//  return logBetaBinPDF(\n//      altCount,\n//      coverage,\n//      0.5 - (2.0 / 3.0 * config.getEffectiveSeqErrRate()),\n//      config.getMuOverdispersion()\n//  );\n}\n\ndouble computeRawHomoMutLogScore(\n    Config const &config,\n    double covMinusSup,\n    double coverage\n    )\n{\n  return logBetaBinPDF(\n      covMinusSup,\n      coverage,\n      config.getEffectiveSeqErrRate(),\n      config.getWildOverdispersion()\n      );\n}\n\n// Add two values in real space by first exponentiating\ndouble addLogProb(double x, double y)\n{\n  double maxScore;\n  double minScore;\n\n  if (x > y)\n  {\n    maxScore = x;\n    minScore = y;\n  }\n  else\n  {\n    maxScore = y;\n    minScore = x;\n  }\n\n  return std::log(1.0 + std::exp(minScore - maxScore)) + maxScore;\n}\n\ndouble logNChoose2(u_int32_t numMut)\n{\n  return log(static_cast<double>(numMut)) + log((static_cast<double>(numMut) - 1.0) / 2.0);\n}\n\ndouble logNChooseK(u_int32_t n, u_int32_t k, double logNChoosekMinusOne)\n{\n  if (k == 0)\n    return 0;\n\n  return logNChoosekMinusOne + log(static_cast<double>(n + 1 - k) / static_cast<double>(k));\n}\n\ndouble logNChooseK(u_int32_t n, u_int32_t k)\n{\n  if (k == 0)\n    return 0;\n\n  return std::lgamma(n + 1) - std::lgamma(k + 1) - std::lgamma(n - k + 1);\n}\n\nOptimizeBetaBinMeanOverDis::OptimizeBetaBinMeanOverDis(\n    const std::vector<std::pair<u_int32_t, u_int32_t>> &counts\n    ):\n        counts(counts)\n{}\n\ndouble OptimizeBetaBinMeanOverDis::operator()(const dlib::matrix<double,0,1> &x) const\n{\n  double result = 0;\n  for (const auto & count : this->counts)\n    result += logBetaBinPDF(count.first, count.second, x(0), x(1));\n\n  return result;\n}\n\nOptimizeBetaBinMeanOverDisDerivates::OptimizeBetaBinMeanOverDisDerivates(\n    const std::vector<std::pair<u_int32_t , u_int32_t>> &counts\n    ):\n    counts(counts)\n{}\n\ndlib::matrix<double> OptimizeBetaBinMeanOverDisDerivates::operator()(const dlib::matrix<double,0,1> &x) const\n{\n  double mean = x(0);\n  double overDis = x(1);\n  dlib::matrix<double,0,1> res = {0,0};\n\n  double temp = 0;\n  unsigned counter = 0;\n  for (const auto & count : this->counts)\n  {\n    unsigned k = count.first;\n    unsigned n = count.second;\n    temp += overDis *  boost::math::digamma(k + mean * overDis)\n            - overDis *  boost::math::digamma(n - k + overDis - overDis * mean);\n    ++counter;\n  }\n  res(0) = counter * (-overDis *  boost::math::digamma(mean * overDis) + overDis *  boost::math::digamma(overDis - overDis * mean)) + temp;\n\n  temp = 0;\n  for (const auto & count : this->counts)\n  {\n    unsigned k = count.first;\n    unsigned n = count.second;\n    temp += mean * boost::math::digamma(k + mean * overDis) +\n            (1.0 - mean) * boost::math::digamma(n - k + overDis - overDis * mean) -\n            boost::math::digamma(n + overDis);\n  }\n  res(1) = counter * (boost::math::digamma(overDis) - mean * boost::math::digamma(mean * overDis) - (1.0 - mean) * boost::math::digamma(overDis - overDis * mean)) + temp;\n\n  return res;\n}\n\nOptimizeBetaBinOverDis::OptimizeBetaBinOverDis(\n    const std::vector<std::pair<u_int32_t, u_int32_t>> &counts,\n    double meanFilter\n):\n    counts(counts),\n    meanFilter(meanFilter)\n{}\n\ndouble OptimizeBetaBinOverDis::operator()(const dlib::matrix<double,0,1> &x) const\n{\n  double result = 0;\n  for (const auto & count : this->counts)\n    result += logBetaBinPDF(count.first, count.second, meanFilter, x(0));\n\n  return result;\n}\n\nOptimizeBetaBinOverDisDerivates::OptimizeBetaBinOverDisDerivates(\n    const std::vector<std::pair<u_int32_t, u_int32_t>> &counts,\n    double meanFilter\n    ):\n    counts(counts),\n    meanFilter(meanFilter)\n{}\n\ndlib::matrix<double> OptimizeBetaBinOverDisDerivates::operator()(const dlib::matrix<double,0,1> &x) const\n{\n  double mean = this->meanFilter;\n  double overDis = x(0);\n  dlib::matrix<double,0,1> res = {0};\n\n  double temp = 0;\n  u_int32_t counter = 0;\n  for (const auto & count : this->counts)\n  {\n    unsigned k = count.first;\n    unsigned n = count.second;\n    temp += mean * boost::math::digamma(k + mean * overDis) +\n            (1.0 - mean) * boost::math::digamma(n - k + overDis - overDis * mean) -\n            boost::math::digamma(n + overDis);\n    ++counter;\n  }\n  res(0) = counter * (boost::math::digamma(overDis) - mean * boost::math::digamma(mean * overDis) - (1.0 - mean) * boost::math::digamma(overDis - overDis * mean)) + temp;\n\n  return res;\n}\n", "meta": {"hexsha": "1b26b0b3f620ec0e9a386cc27dd11c6380cfe912", "size": 6020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/probabilities.cpp", "max_stars_repo_name": "senbaikang/DataFilter", "max_stars_repo_head_hexsha": "cd3c1e30edfff235a325de6c560941f4f31bc01f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/probabilities.cpp", "max_issues_repo_name": "senbaikang/DataFilter", "max_issues_repo_head_hexsha": "cd3c1e30edfff235a325de6c560941f4f31bc01f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/probabilities.cpp", "max_forks_repo_name": "senbaikang/DataFilter", "max_forks_repo_head_hexsha": "cd3c1e30edfff235a325de6c560941f4f31bc01f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3724696356, "max_line_length": 170, "alphanum_fraction": 0.6428571429, "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.6451700209512456}}
{"text": "#include <vector>\n\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/calculate_SVD.hpp\"\n#include <Eigen/SVD>\nusing namespace Eigen;\n\nnamespace caffe {\n\ntemplate <typename Dtype>\nvoid CalculateSVD(const Dtype* weight,\n    Dtype* weight_mut, int num_neurons, int dim_features, int k_value) {\n  \n\n  //FM: SVD\n  //const Dtype* weight = this->blobs_[0]->cpu_data();\n  //Dtype* weight_mut = this->blobs_[0]->mutable_cpu_data();\n\n  //Instantiate the weight matrix\n  MatrixXf m = MatrixXf::Random(num_neurons, dim_features);\n  int counter = 0;\n  for (int i = 0; i < num_neurons; ++i) {\n\t  for (int j = 0; j < dim_features; ++j) {\n\t\t  m(i, j) = weight[counter];\n\t\t  counter++;\n\t  }\n\n  }\n\n  //Perform SVD\n  // cout << \"Here is the matrix m:\" << endl << m << endl;\n  JacobiSVD<MatrixXf> svd(m, ComputeThinU | ComputeThinV);\n\n  // Set with the new values\n  counter = 0;\n  //MatrixXf m_inner = svd.matrixU() * (svd.singularValues().asDiagonal() * svd.matrixV().transpose()); //original\n  int u_rows = svd.matrixU().rows();\n  int v_rows = svd.matrixV().rows();\n  int s_cols = svd.singularValues().cols();\n  //MatrixXf m_inner = svd.matrixU().block<u_rows, k>(0, 0) * (svd.singularValues().asDiagonal() * svd.matrixV().transpose()); //low-rank decomposition\n  MatrixXf m_inner = svd.matrixU().block(0, 0, u_rows, k_value) * (svd.singularValues().block(0, 0, k_value, s_cols).asDiagonal() * svd.matrixV().block(0, 0, v_rows, k_value).transpose()); //low-rank decomposition\n  \n  #ifdef _DEBUG\n\t  MatrixXf diff = m_inner - m;\n\t  cout << \"diff:\\n\" << diff.array().abs().sum() << \"\\n\";\n  #endif\n\n  for (int i = 0; i < num_neurons; ++i) {\n\t  for (int j = 0; j < dim_features; ++j) {\n\t\t  weight_mut[counter] = m_inner(i, j);\n\t\t  counter++;\n\t  }\n\n  }\n  // FM: End of SVD\n}\n\ntemplate void CalculateSVD<float>(const float* weight, float* weight_mut, int num_neurons, int dim_features, int k_value);\ntemplate void CalculateSVD<double>(const double* weight, double* weight_mut, int num_neurons, int dim_features, int k_value);\n\n}  // namespace caffe\n", "meta": {"hexsha": "988927e7f2940ee9ec3c00e0d1cf8297bddce613", "size": 2035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code_caffe-rc3_fvmtl_ccelc/src/caffe/util/calculate_SVD.cpp", "max_stars_repo_name": "markatopoulou/fvmtl-ccelc", "max_stars_repo_head_hexsha": "4c6e0ac2e4c0cc6181f0836151a871bbff257ddb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T12:12:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-07T13:59:18.000Z", "max_issues_repo_path": "code_caffe-rc3_fvmtl_ccelc/src/caffe/util/calculate_SVD.cpp", "max_issues_repo_name": "markatopoulou/fvmtl-ccelc", "max_issues_repo_head_hexsha": "4c6e0ac2e4c0cc6181f0836151a871bbff257ddb", "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": "code_caffe-rc3_fvmtl_ccelc/src/caffe/util/calculate_SVD.cpp", "max_forks_repo_name": "markatopoulou/fvmtl-ccelc", "max_forks_repo_head_hexsha": "4c6e0ac2e4c0cc6181f0836151a871bbff257ddb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8225806452, "max_line_length": 213, "alphanum_fraction": 0.6624078624, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6451064669643072}}
{"text": "/*\n * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT)\n *\n * This software may be modified and distributed under the terms of the\n * BSD 3-Clause license. See the accompanying LICENSE file for details.\n */\n\n#include <BayesFilters/LTIStateModel.h>\n\n#include <Eigen/Dense>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nLTIStateModel::LTIStateModel(const Ref<const MatrixXd>& transition_matrix, const Ref<const MatrixXd>& noise_covariance_matrix) :\n    F_(transition_matrix), Q_(noise_covariance_matrix)\n{\n    if ((F_.rows() == 0) || (F_.cols() == 0))\n        throw std::runtime_error(\"ERROR::LTISTATEMODEL::CTOR\\nERROR:\\n\\tState transition matrix dimensions cannot be 0.\");\n    else if ((Q_.rows() == 0) || (Q_.cols() == 0))\n        throw std::runtime_error(\"ERROR::LTISTATEMODEL::CTOR\\nERROR:\\n\\tNoise covariance matrix dimensions cannot be 0.\");\n    else if (F_.rows() != F_.cols())\n        throw std::runtime_error(\"ERROR::LTISTATEMODEL::CTOR\\nERROR:\\n\\tState transition matrix must be a square matrix.\");\n    else if (Q_.rows() != Q_.cols())\n        throw std::runtime_error(\"ERROR::LTISTATEMODEL::CTOR\\nERROR:\\n\\tNoise covariance matrix must be a square matrix.\");\n    else if (F_.rows() != Q_.rows())\n        throw std::runtime_error(\"ERROR::LTISTATEMODEL::CTOR\\nERROR:\\n\\tNumber of rows of the state transition matrix must be the same as the size of the noise covariance matrix.\");\n}\n\n\nvoid LTIStateModel::propagate(const Eigen::Ref<const Eigen::MatrixXd>& cur_states, Eigen::Ref<Eigen::MatrixXd> prop_states)\n{\n    prop_states = F_ * cur_states;\n}\n\n\nEigen::MatrixXd LTIStateModel::getNoiseCovarianceMatrix()\n{\n    return Q_;\n}\n\n\nEigen::MatrixXd LTIStateModel::getStateTransitionMatrix()\n{\n    return F_;\n}\n\n\nbool LTIStateModel::setProperty(const std::string& property)\n{\n    return false;\n}\n\n\nEigen::MatrixXd LTIStateModel::getJacobian()\n{\n    return F_;\n}\n", "meta": {"hexsha": "d5f3ae9d3438636cf0f3d687574c8898da66971c", "size": 1877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/LTIStateModel.cpp", "max_stars_repo_name": "vesor/bayes-filters-lib", "max_stars_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T02:52:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T07:06:39.000Z", "max_issues_repo_path": "src/BayesFilters/src/LTIStateModel.cpp", "max_issues_repo_name": "vesor/bayes-filters-lib", "max_issues_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BayesFilters/src/LTIStateModel.cpp", "max_forks_repo_name": "vesor/bayes-filters-lib", "max_forks_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T08:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T08:20:28.000Z", "avg_line_length": 31.2833333333, "max_line_length": 181, "alphanum_fraction": 0.7112413426, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6451064559733756}}
{"text": "/*\n * Refs:\n * https://eigen.tuxfamily.org/dox/index.html\n * https://dritchie.github.io/csci2240/assignments/eigen_tutorial.pdf\n * */\n\n#include <iostream>\n#include <Eigen/Dense>\n\n#define PRINT(x) std::cout << #x << \": \" << std::endl << (x) << std::endl << std::endl\n#define PRINT_SIZE(x) std::cout << #x << \" is of size \" << x.rows() << \"x\" << x.cols() << std::endl << std::endl\n#define SECTION(x) std::cout << \"======================== \" << x << \" =======================\" << std::endl << std::endl\n\nint main() {\n\n  using namespace Eigen;\n\n  SECTION(\"Initialisations\");\n  // Different ways to initialise matrix\n  Matrix<double , Dynamic, Dynamic, 0, 6, 8> m0 = Matrix4d::Ones();\n  // the last three are optional, so we don't have to worry about it most of the time.\n  // isRowMajor=0: default is column major, MaxRowsAtCompileTime, MaxColsAtCompileTime\n  PRINT(m0);\n  MatrixXd m1(4, 4); // typedef Matrix<double, Dynamic, Dynamic> MatrixXd;\n  m1 = Matrix4d::Zero();\n  PRINT(m1);\n  // fix size matrix\n  Matrix4d m2 = Matrix4d::Random(); // [-1, 1]\n  PRINT(m2);\n  Vector4d m3(1.0, 2.0, 3.0, 4.0); // typedef Matrix<double, 4, 1> Vector3d;\n  PRINT(m3);\n  MatrixXd v = Vector4d::Ones(); // vectors just one dimensional matrices\n  PRINT(v);\n  VectorXd m4 = Vector4d::Constant(108.5); // column vector\n  PRINT(m4);\n  RowVectorXd m4r = Vector4d::Constant(108.5); // row vector\n  PRINT(m4r);\n\n  SECTION(\"Store orders\");\n  // store orders\n  // https://eigen.tuxfamily.org/dox/group__TopicStorageOrders.html\n  Matrix<double, 4, 4, RowMajor> m5;\n  m5 << 1, 2, 3, 4,  5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16; // comma-initializer syntax\n  PRINT(m5);\n  std::cout << \"In memory (row-major):\" << std::endl;\n  for (int i = 0; i < m5.size(); i++)\n    std::cout << *(m5.data() + i) << \"  \";\n  std::cout << std::endl << std::endl;\n\n  Matrix<double, 4, 4, ColMajor> m6;\n  m6 << 1, 2, 3, 4,  5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;\n  PRINT(m6);\n  std::cout << \"In memory (column-major):\" << std::endl;\n  for (int i = 0; i < m6.size(); i++)\n    std::cout << *(m6.data() + i) << \"  \";\n  std::cout << std::endl << std::endl;\n\n  Matrix<double, 4, 4> m7; // default is Column major\n  m7 << 1, 2, 3, 4,  5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;\n  PRINT(m7);\n  std::cout << \"In memory (column-major) is default:\" << std::endl;\n  for (int i = 0; i < m7.size(); i++)\n    std::cout << *(m7.data() + i) << \"  \";\n  std::cout << std::endl << std::endl;\n\n  // ref: https://eigen.tuxfamily.org/dox/group__TutorialAdvancedInitialization.html\n  MatrixXd m8(4, 8);\n  m8 << m6, m7;\n  PRINT(m8);\n\n  MatrixXd m9(8, 4);\n  m9 << m6, m7;\n  PRINT(m9);\n\n  SECTION(\"Block Operation\");\n  // block operation https://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html\n  MatrixXd m10(5, 9);\n  m10.row(0) << RowVectorXd::Ones(9)*100;\n  m10.block(1, 0, 4, 4) << m6;\n  m10.block<4, 4>(1, 4) = m7*2;\n  m10.col(8).tail(4) << VectorXd::Ones(4)*99; // col and row are special case of block\n  PRINT(m10);\n  // some other keywords:\n  // topLeftCorner, bottomLeftCorner, topRightCorner, bottomRightCorner, topRows, bottomRows, leftCols, rightCols.\n  PRINT(m5);\n  PRINT(m5.leftCols(2));\n  PRINT(m5.bottomRows<2>());\n  m5.topLeftCorner(1,3) = m5.bottomRightCorner(3,1).transpose();\n  PRINT(m5);\n  VectorXd v0(6);\n  v0 << 1, 2, 3, 4, 5, 6;\n  PRINT(v0.head(3));\n  PRINT(v0.tail<3>());\n  v0.segment(1,4) *= 2;\n  PRINT(v0);\n\n  SECTION(\"Diagonal\");\n  // Coefficient accessors\n  m0(2, 2) = 100;\n  PRINT(m0);\n  PRINT(m0.diagonal());\n  MatrixXd m0d1 = m0.diagonal().asDiagonal();\n  // https://eigen.tuxfamily.org/dox/classEigen_1_1MatrixBase.html#a14235b62c90f93fe910070b4743782d0\n  PRINT(m0d1);\n  DiagonalMatrix<double, Dynamic> m0d2;\n  // http://eigen.tuxfamily.org/dox/classEigen_1_1DiagonalMatrix.html\n  m0d2.diagonal() = m0.diagonal();\n  PRINT(MatrixXd(m0d2));\n\n  m1 = Matrix4d::Identity(); // overwrite matrix values\n  PRINT(m1);\n\n  SECTION(\"Vector operations\");\n  // Vector operations\n  Vector3f v1, v2;\n  v1 = Vector3f::Random();\n  v2 = Vector3f::Random();\n  PRINT(v1);\n  PRINT(v2);\n  PRINT(v1 * v2.transpose());\n  PRINT(v1.transpose() * v2);\n  PRINT(v1.dot(v2));\n  PRINT(v1.cross(Vector3f(3., 4., 6.).normalized()));\n  PRINT(v1.cross(v2));\n\n  Vector4f v3 = v1.homogeneous();\n  PRINT(v3);\n  PRINT(v3.hnormalized());\n  // element-wise similar to matrix\n  PRINT(v1.array().sin());\n\n  SECTION(\"Matrix Operations\");\n  // Matrix Operations\n  PRINT(m0 + m1);\n  PRINT(m0 * m1);\n  PRINT(m1 += m1);\n  PRINT(m1 *= 2);\n  PRINT(m0 - m1 * 2.2);\n  // Check if two matrices are the same\n  PRINT(m0 * m1 == m0 - m1 * 2.2);\n  PRINT(m1 == Matrix4d::Identity()*4);\n\n  PRINT(m6.transpose()); // this doesn't modify m6\n  // NEVER DO \"a = a.transpose()\" aliasing issue: https://eigen.tuxfamily.org/dox/group__TutorialMatrixArithmetic.html\n  // but matrix operation is fine, no problem! a = a*a;\n  // https://eigen.tuxfamily.org/dox/group__TopicAliasing.html\n  m6.transposeInPlace(); // we can do this instead\n  PRINT(m6);\n  PRINT(m6.inverse()); // if not invertible then shows NaN\n\n  SECTION(\"Element-Wise\");\n  // element-wise\n  PRINT(m6.array().square());\n  PRINT(m6.array() * m6.transpose().array());\n  PRINT(((m0 * m1).array() == (m0 - m1 * 2.2).array()));\n\n  SECTION(\"Basic arithmetic reduction operations\");\n  // Basic arithmetic reduction operations\n  // https://eigen.tuxfamily.org/dox/group__TutorialMatrixArithmetic.html\n  // https://eigen.tuxfamily.org/dox/group__TutorialReductionsVisitorsBroadcasting.html\n  PRINT(m1);\n  PRINT(m1.sum());\n  PRINT(m1.prod());\n  PRINT(m1.mean());\n  PRINT(m1.minCoeff());\n  PRINT(m1.maxCoeff());\n  PRINT(m1.trace());\n  // visitors\n  MatrixXd::Index maxRow, maxCol;\n  double maxOfm1 = m1.maxCoeff(&maxRow, &maxCol);\n  std::cout << maxOfm1 << \" is at position: (\" << maxRow << \",\" << maxCol << \")\" << std::endl << std::endl;\n  std::ptrdiff_t i, j;\n  double minOfm1 = m1.minCoeff(&i, &j);\n  std::cout << minOfm1 << \" is at position: (\" << i << \",\" << j << \")\" << std::endl << std::endl;\n  // partial reductions\n  PRINT(m1.colwise().maxCoeff());\n  PRINT(m1.rowwise().maxCoeff());\n  PRINT(m1.cwiseSqrt());\n  PRINT(m1.cwiseSqrt().colwise().maxCoeff());\n\n  SECTION(\"Norm\");\n  PRINT(m1.squaredNorm());\n  PRINT(m1.norm());\n  // lp-norm\n  PRINT(m1.lpNorm<2>());\n  PRINT(m1.lpNorm<1>());\n  PRINT(m1.lpNorm<Infinity>());\n  // Operator norm: https://en.wikipedia.org/wiki/Operator_norm\n  // 1-norm(m1)\n  PRINT(m1.cwiseAbs().colwise().sum().maxCoeff());\n  PRINT(m1.colwise().lpNorm<1>().maxCoeff());\n  // Infinity-norm(m1)\n  PRINT(m1.cwiseAbs().rowwise().sum().maxCoeff());\n  PRINT(m1.rowwise().lpNorm<1>().maxCoeff());\n\n  PRINT(m6);\n  MatrixXd::Index maxIndex;\n  double maxNorm = m6.colwise().sum().maxCoeff(&maxIndex);\n  std::cout << \"Maximum sum at position \" << maxIndex << std::endl\n            << \"The corresponding vector is: \" << std::endl\n            << m6.col(maxIndex) << std::endl\n            << \"And its sum is is: \" << maxNorm << std::endl << std::endl;\n\n  SECTION(\"Broadcasting\");\n  // https://eigen.tuxfamily.org/dox/group__TutorialReductionsVisitorsBroadcasting.html\n  MatrixXd mb = MatrixXd::Zero(2, 4);\n  VectorXd vb = Vector2d(0, 1);\n  PRINT(mb);\n  PRINT(vb);\n  mb.colwise() += vb;\n  PRINT(mb);\n  mb.setZero();\n  vb = Vector4d(0, 1, 2, 3);\n  mb.rowwise() += vb.transpose();\n  PRINT(mb);\n  PRINT(vb);\n  // find nearest neighbour\n  mb.setRandom();\n  vb.setRandom(2);\n  PRINT(mb);\n  PRINT(vb);\n  MatrixXf::Index index;\n  (mb.colwise() - vb).colwise().squaredNorm().minCoeff(&index);\n  std::cout << \"Nearest neighbour is column \" << index << \":\" << std::endl;\n  std::cout << mb.col(index) << std::endl;\n\n  SECTION(\"Resizing\");\n  // resizing\n  // https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html\n  VectorXd v4 = Vector4d::Ones()*100;\n  PRINT(v4);\n  v4.conservativeResize(6); // this leave the old value untouched\n  PRINT(v4);\n  v4.resize(8);\n  PRINT(v4);\n\n  PRINT_SIZE(m1);\n  m1 = MatrixXd::Identity(6, 6); // copy and resize of matrix with dynamic size\n  PRINT(m1);\n  PRINT_SIZE(m1);\n\n  // change type of matrix\n  MatrixXf m11 = m1.cast<float>();\n  PRINT(m11);\n\n  SECTION(\"Temporary objects\");\n  // using comma-initializer as temporary objects\n  // https://eigen.tuxfamily.org/dox/group__TutorialAdvancedInitialization.html\n  MatrixXf mat = MatrixXf::Random(2, 3);\n  PRINT(mat);\n  mat = (MatrixXf(2,2) << 0, 1, 1, 0).finished() * mat;\n  PRINT(mat);\n  // https://eigen.tuxfamily.org/dox/structEigen_1_1CommaInitializer.html#a3cf9e2b8a227940f50103130b2d2859a\n\n}\n", "meta": {"hexsha": "b9c8bb308941ba6bcfb533e0108bd640ce9f3113", "size": 8450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/102_Matrix/main.cpp", "max_stars_repo_name": "GeneKao/Eigen-Cpp-Notes", "max_stars_repo_head_hexsha": "fbc558af3926cb2f033a44403923af621fee1e92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/102_Matrix/main.cpp", "max_issues_repo_name": "GeneKao/Eigen-Cpp-Notes", "max_issues_repo_head_hexsha": "fbc558af3926cb2f033a44403923af621fee1e92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/102_Matrix/main.cpp", "max_forks_repo_name": "GeneKao/Eigen-Cpp-Notes", "max_forks_repo_head_hexsha": "fbc558af3926cb2f033a44403923af621fee1e92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0078125, "max_line_length": 120, "alphanum_fraction": 0.6282840237, "num_tokens": 2872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.6450856510616332}}
{"text": "#include <map>\n#include <string>\n#include <iostream>\n#include <Eigen/Dense>\n#include \"../simple_lib/include/two_layer_net.h\"\n#include \"../datasets/include/mnist.h\"\n\nusing namespace Eigen;\n\nint main(){\n    using std::map;\n    using std::cout;\n    using std::endl;\n    using std::string;\n    using namespace MyDL;\n\n    int batch_size = 5;\n    int input_size = 28*28;\n    int hidden_size = 100;\n    int output_size = 10;\n\n    MnistEigenDataset mnist(batch_size);\n\n    MatrixXd train_X = MatrixXd::Zero(batch_size, input_size);\n    MatrixXd train_y = MatrixXd::Zero(batch_size, output_size);\n    bool one_hot_label = true;\n\n    TwoLayerNet net(input_size, hidden_size, output_size, 0.01);\n    // mnist.next_train(train_X, train_y, one_hot_label);\n    mnist.next_train(train_X, train_y);\n\n    MatrixXd pred_y;\n    double loss, accuracy;\n    map<string, MatrixXd> grads;\n\n    pred_y = net.predict(train_X);\n    loss = net.loss(train_X, train_y);\n    accuracy = net.accuracy(train_X, train_y);\n    grads = net.gradient(train_X, train_y);\n\n    cout << \"Prediction: \" << pred_y << endl;\n    cout << \"Loss: \" << loss << endl;\n    cout << \"Accuracy: \" << accuracy << endl;\n    cout << \"Gradient W1: \" << grads[\"dW1\"] << endl;\n\n    return 0;\n}", "meta": {"hexsha": "00c30b54f96d08211ff1887419003500d3634699", "size": 1231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/mnist_two_layer_net.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch4/mnist_two_layer_net.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/mnist_two_layer_net.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1914893617, "max_line_length": 64, "alphanum_fraction": 0.6563769293, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6450788001928057}}
{"text": "// Copyright (C) 2009  Davis E. King (davis@dlib.net)\r\n// License: Boost Software License   See LICENSE.txt for the full license.\r\n\r\n\r\n#include <dlib/matrix.h>\r\n#include <sstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <ctime>\r\n#include <vector>\r\n#include \"../stl_checked.h\"\r\n#include \"../array.h\"\r\n#include \"../rand.h\"\r\n#include <dlib/string.h>\r\n\r\n#include \"tester.h\"\r\n\r\nnamespace  \r\n{\r\n\r\n    using namespace test;\r\n    using namespace dlib;\r\n    using namespace std;\r\n\r\n    logger dlog(\"test.matrix_qr\");\r\n\r\n    dlib::rand rnd;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    template <typename mat_type>\r\n    const matrix<typename mat_type::type> symm(const mat_type& m) { return m*trans(m); }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    template <typename type>\r\n    const matrix<type> randmat(long r, long c)\r\n    {\r\n        matrix<type> m(r,c);\r\n        for (long row = 0; row < m.nr(); ++row)\r\n        {\r\n            for (long col = 0; col < m.nc(); ++col)\r\n            {\r\n                m(row,col) = static_cast<type>(rnd.get_random_double()); \r\n            }\r\n        }\r\n\r\n        return m;\r\n    }\r\n\r\n    template <typename type, long NR, long NC>\r\n    const matrix<type,NR,NC> randmat()\r\n    {\r\n        matrix<type,NR,NC> m;\r\n        for (long row = 0; row < m.nr(); ++row)\r\n        {\r\n            for (long col = 0; col < m.nc(); ++col)\r\n            {\r\n                m(row,col) = static_cast<type>(rnd.get_random_double()); \r\n            }\r\n        }\r\n\r\n        return m;\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    template <typename matrix_type>\r\n    void test_qr ( const matrix_type& m)\r\n    {\r\n        typedef typename matrix_type::type type;\r\n        const type eps = 10*max(abs(m))*sqrt(std::numeric_limits<type>::epsilon());\r\n        dlog << LDEBUG << \"test_qr():  \" << m.nr() << \" x \" << m.nc() << \"  eps: \" << eps;\r\n        print_spinner();\r\n\r\n\r\n        qr_decomposition<matrix_type> test(m);\r\n\r\n\r\n        DLIB_TEST(test.nr() == m.nr());\r\n        DLIB_TEST(test.nc() == m.nc());\r\n\r\n\r\n        type temp;\r\n        DLIB_TEST_MSG( (temp= max(abs(test.get_q()*test.get_r() - m))) < eps,temp);\r\n\r\n        // none of the matrices we should be passing in to test_qr() should be non-full rank.  \r\n        DLIB_TEST(test.is_full_rank() == true);\r\n\r\n        if (m.nr() == m.nc())\r\n        {\r\n            matrix<type> m2;\r\n            matrix<type,0,1> col;\r\n\r\n            m2 = identity_matrix<type>(m.nr());\r\n            DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2)));\r\n            m2 = randmat<type>(m.nr(),5);\r\n            DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2)));\r\n            m2 = randmat<type>(m.nr(),1);\r\n            DLIB_TEST_MSG(equal(m*test.solve(m2), m2,eps),max(abs(m*test.solve(m2)- m2)));\r\n            col = randmat<type>(m.nr(),1);\r\n            DLIB_TEST_MSG(equal(m*test.solve(col), col,eps),max(abs(m*test.solve(m2)- m2)));\r\n        }\r\n        else\r\n        {\r\n            DLIB_TEST_MSG(dlib::equal(pinv(m), test.solve(identity_matrix<type>(m.nr())), eps), \r\n                        max(abs(pinv(m) - test.solve(identity_matrix<type>(m.nr())))) );\r\n        }\r\n\r\n        // now make us a non-full rank matrix\r\n        if (m.nc() > 1)\r\n        {\r\n            matrix<type> sm(m);\r\n            set_colm(sm,0) = colm(sm,1);\r\n\r\n            qr_decomposition<matrix_type> test2(sm);\r\n            DLIB_TEST_MSG( (temp= max(abs(test.get_q()*test.get_r() - m))) < eps,temp);\r\n\r\n            if (test2.nc() < 100)\r\n            {\r\n                DLIB_TEST_MSG(test2.is_full_rank() == false,\"eps: \" << eps);\r\n            }\r\n\r\n        }\r\n\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    void matrix_test_double()\r\n    {\r\n\r\n        test_qr(10*randmat<double>(1,1));\r\n        test_qr(10*randmat<double>(2,2));\r\n        test_qr(10*symm(randmat<double>(2,2)));\r\n        test_qr(10*randmat<double>(4,4));\r\n        test_qr(10*randmat<double>(9,4));\r\n        test_qr(10*randmat<double>(15,15));\r\n        test_qr(2*symm(randmat<double>(15,15)));\r\n        test_qr(10*randmat<double>(100,100));\r\n        test_qr(10*randmat<double>(237,200));\r\n        test_qr(10*randmat<double>(200,101));\r\n\r\n        test_qr(10*randmat<double,1,1>());\r\n        test_qr(10*randmat<double,2,2>());\r\n        test_qr(10*randmat<double,4,3>());\r\n        test_qr(10*randmat<double,4,4>());\r\n        test_qr(10*randmat<double,9,4>());\r\n        test_qr(10*randmat<double,15,15>());\r\n        test_qr(10*randmat<double,100,100>());\r\n\r\n        typedef matrix<double,0,0,default_memory_manager, column_major_layout> mat;\r\n        test_qr(mat(3*randmat<double>(9,4)));\r\n        test_qr(mat(3*randmat<double>(9,9)));\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    void matrix_test_float()\r\n    {\r\n\r\n\r\n        test_qr(3*randmat<float>(1,1));\r\n        test_qr(3*randmat<float>(2,2));\r\n        test_qr(3*randmat<float>(4,4));\r\n        test_qr(3*randmat<float>(9,4));\r\n        test_qr(3*randmat<float>(237,200));\r\n\r\n        test_qr(3*randmat<float,1,1>());\r\n        test_qr(3*randmat<float,2,2>());\r\n        test_qr(3*randmat<float,4,3>());\r\n        test_qr(3*randmat<float,4,4>());\r\n        test_qr(3*randmat<float,9,4>());\r\n\r\n        typedef matrix<float,0,0,default_memory_manager, column_major_layout> mat;\r\n        test_qr(mat(3*randmat<float>(9,4)));\r\n        test_qr(mat(3*randmat<float>(9,9)));\r\n    }\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n    class matrix_tester : public tester\r\n    {\r\n    public:\r\n        matrix_tester (\r\n        ) :\r\n            tester (\"test_matrix_qr\",\r\n                    \"Runs tests on the matrix QR component.\")\r\n        {\r\n            //rnd.set_seed(cast_to_string(time(0)));\r\n        }\r\n\r\n        void perform_test (\r\n        )\r\n        {\r\n            dlog << LINFO << \"seed string: \" << rnd.get_seed();\r\n\r\n            dlog << LINFO << \"begin testing with double\";\r\n            matrix_test_double();\r\n            dlog << LINFO << \"begin testing with float\";\r\n            matrix_test_float();\r\n        }\r\n    } a;\r\n\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "28ab42befe0024d874f67668f03bcb407f92efc5", "size": 6368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dlib/test/matrix_qr.cpp", "max_stars_repo_name": "cpearce/HARM", "max_stars_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-11T18:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-11T18:37:52.000Z", "max_issues_repo_path": "src/dlib/test/matrix_qr.cpp", "max_issues_repo_name": "wsgan001/HARM", "max_issues_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-27T22:58:45.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-28T04:46:52.000Z", "max_forks_repo_path": "src/dlib/test/matrix_qr.cpp", "max_forks_repo_name": "wsgan001/HARM", "max_forks_repo_head_hexsha": "1e629099bbaa0203b19fe9007a71d9ab9c938be0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-19T06:15:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-02T11:11:57.000Z", "avg_line_length": 30.4688995215, "max_line_length": 97, "alphanum_fraction": 0.471419598, "num_tokens": 1621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.8056321889812553, "lm_q1q2_score": 0.6450632503483475}}
{"text": "//\n/// \\file lognormal_test.cpp\n/// \\package how_much_data\n//\n/// \\author Created by Joseph Dunn on 1/25/19.\n/// \\copyright \u00a9 2019 Joseph Dunn. All rights reserved.\n//\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n#include <iomanip>\nusing std::setw;\nusing std::setprecision;\nusing std::fixed;\n#include <vector>\nusing std::vector;\n#include <fstream>\nusing std::ofstream;\n#include <boost/timer/timer.hpp>\nusing boost::timer::auto_cpu_timer;\nusing boost::timer::cpu_timer;\n#include \"lognormal_distribution.h\"\n\nint main(int argc, const char * argv[]) {\n  Kronrod<double> k_big(10);\n  int noext = 0;\n  double epsabs_double = std::numeric_limits<double>::epsilon()/128;\n  double epsrel_double = boost::math::tools::root_epsilon<double>();\n  int limit = 1000;\n  int verbose_integration = 0;\n  IntegrationController<double> cf_ctl(noext, k_big,\n                                       epsabs_double, epsrel_double,\n                                       limit, verbose_integration);\n\n  string ofile_name{\"../output/lognormal_test_fourier_integrand.out\"};\n  cout << \"Writing to file \" << ofile_name << endl;\n  ofstream trace(ofile_name);\n  lognormal_distribution<>::print_fourier_integrand(trace, 1000,\n                                            complex<double>(128,0.), .1);\n\n  vector<double> sigmas = {.01, .1, 1, 5, 10};\n  vector<complex<double> > omegas;\n  omegas.push_back(0.);\n  complex<double> i{0,1};\n  for (int j=-512; j<=512; j++)\n    omegas.push_back(pow(2,j/8.));\n  \n  vector<complex<double> > cfs_std;\n  vector<complex<double> > cfprimes_std;\n  \n  vector<string> names = {\"fourier_lnx\", \"fourier\", \"lambert_w\",\"fourier_mixed\", \"adj_series\"};\n  vector<int> types ={2, 5, 3,4,1};\n  \n  for (auto type : types)\n  {\n    string ofile_name{\"../output/lognormal_test_\"+names.at(type-1)+\".out\"};\n    cout << \"Writing to file \" << ofile_name << endl;\n    ofstream out(ofile_name);\n    auto_cpu_timer timer;\n    out << setw(11) << \"sigma,\"\n    << setw(14) << \"omega,\"\n    << setw(17) << \"cf_Re,\"\n    << setw(17) << \"cf_Im,\"\n    << setw(17) << \"Abs(cf-cf_std),\"\n    << setw(17) << \"Integ_err,\"\n    << setw(11) << \"# eval,\"\n    << setw(17) << \"Abs(cf) -1\"\n    << setw(17) << \"cfprime_Re,\"\n    << setw(17) << \"cfprime_Im,\"\n    << setw(17) << \"Abs(cfp-cfp_std),\"\n    << setw(17) << \"Integ_err,\"\n    << setw(11) << \"# eval\"\n    << endl;\n\n    int j = 0;\n    for (auto sigma : sigmas) {\n      lognormal_distribution<> lnd(0, sigma, cf_ctl, type);\n      for (auto omega : omegas ) {\n        double cf_integ_err;\n        double cf_l1_norm;\n        int cf_neval;\n        bool adjusted = (type==5 || type==6);\n        double mean = adjusted ? 0 : lnd.mean();\n        complex<double> fac = exp(- i * mean * omega);\n        complex<double> cf = fac* lnd.characteristic_function(omega,\n                                                              &cf_integ_err,\n                                                              &cf_l1_norm,\n                                                              &cf_neval\n                                                              );\n        bool std = type == types.at(0);\n        complex<double> cf_std = std ? cf : cfs_std.at(j);\n        if (std) cfs_std.push_back(cf);\n        double cfp_integ_err;\n        double cfp_l1_norm;\n        int cfp_neval;\n        complex<double> cfprime = fac*lnd.characteristic_function_prime(omega,\n                                                                        &cfp_integ_err,\n                                                                        &cfp_l1_norm,\n                                                                        &cfp_neval\n                                                                        )-i*mean*cf;\n        complex<double> cfprime_std = std ? cfprime : cfprimes_std.at(j++);\n        if (std) cfprimes_std.push_back(cfprime);\n        out << setw(10) << setprecision(2) << sigma << \",\"\n        << setw(13) << setprecision(4) << omega << \",\"\n        << setw(16) << setprecision(8) << real(cf) << \",\"\n        << setw(16) << setprecision(8) << imag(cf) << \",\"\n        << setw(16) << setprecision(8) << abs(cf-cf_std) << \",\"\n        << setw(16) << setprecision(8) << cf_integ_err << \",\"\n        << setw(10) << cf_neval << \",\"\n        << setw(16) << setprecision(8) << abs(cf) - 1. << \",\"\n        << setw(16) << setprecision(8) << real(cfprime) << \",\"\n        << setw(16) << setprecision(8) << imag(cfprime) << \",\"\n        << setw(16) << setprecision(8) << abs(cfprime-cfprime_std) << \",\"\n        << setw(16) << setprecision(8) << cfp_integ_err << \",\"\n        << setw(10) << cfp_neval\n        << endl;\n      }\n    }\n    out << endl;\n  }\n\n}\n", "meta": {"hexsha": "ba836cfcd6ad820da0388b2017a2dc5cd28e055a", "size": 4638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lognormal_test/lognormal_test.cpp", "max_stars_repo_name": "JoeDunnStable/how_much_data", "max_stars_repo_head_hexsha": "5ec528c143c554bb11798e93ce69ef17ef2b42d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lognormal_test/lognormal_test.cpp", "max_issues_repo_name": "JoeDunnStable/how_much_data", "max_issues_repo_head_hexsha": "5ec528c143c554bb11798e93ce69ef17ef2b42d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lognormal_test/lognormal_test.cpp", "max_forks_repo_name": "JoeDunnStable/how_much_data", "max_forks_repo_head_hexsha": "5ec528c143c554bb11798e93ce69ef17ef2b42d9", "max_forks_repo_licenses": ["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.4032258065, "max_line_length": 95, "alphanum_fraction": 0.5120741699, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6450523989908445}}
{"text": "#include <iostream>\n#include <vector>\n#include <alglib/graph/directed_graph.h>\n\nusing namespace std;\nusing namespace alglib::graph;\n\nint main() {\n\n    directed_graph<string, int> G;\n\n    string c1 = \"Bikaner\";\n    string c2 = \"Bangalore\";\n    string c3 = \"Jaipur\";\n    string c4 = \"Hanumangarh\";\n    string c5 = \"Jodhpur\";\n\n\n    G.add_vertex(c2);\n    G.add_vertex(c1);\n    G.add_vertex(c3);\n    G.add_vertex(c4);\n    G.add_vertex(c5);\n\n    G.add_edge(c1, c2, 100);\n    G.add_edge(c5, c1, 250);\n    G.add_edge(c2, c3, 110);\n    G.add_edge(c1, c4, 40);\n   \n    cout << \"\\nAll the cities: \";\n    for(auto it = G.vbegin(); it != G.vend(); it++)\n        cout << *it << \"\\t\";\n    cout << endl;\n    \n    cout << \"\\nCities adjacent to Bikaner: \";\n    for(auto it = G.avbegin(c1); it != G.avend(c1); it++)\n        cout << *it << \"\\t\";\n\n    cout << endl;\n\n    cout << \"\\n\\nDirected graph with unweighted edges:\\n\";\n    // unweighted (or graph with unattributed edges) graph\n    directed_graph<int> G1;\n    G1.add_vertex(3);\n    G1.add_vertex(10);\n\n    G1.add_edge(3, 10); // OK\n    // G1.add_edge(3, 10, 10);  // Error\n    \n    cout << \"\\nAll the vertices: \";\n    for(auto it = G1.vbegin(); it != G1.vend(); it++)\n        cout << *it << \"\\t\";\n    cout << endl;\n}\n", "meta": {"hexsha": "3a36263bd37ce805e2d3a827c739890e54846f56", "size": 1253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/graph/directed_graph.cpp", "max_stars_repo_name": "divkakwani/alglib", "max_stars_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-26T13:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-02T12:30:03.000Z", "max_issues_repo_path": "test/graph/directed_graph.cpp", "max_issues_repo_name": "divkakwani/alglib", "max_issues_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/graph/directed_graph.cpp", "max_forks_repo_name": "divkakwani/alglib", "max_forks_repo_head_hexsha": "464441c26ff802e0c7eb58106201c840dc37047b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T14:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T10:30:28.000Z", "avg_line_length": 22.7818181818, "max_line_length": 58, "alphanum_fraction": 0.5562649641, "num_tokens": 402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6450072405492786}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/ql.hpp\n *\n * \\brief The QL matrix decomposition.\n *\n * Given an \\f$m\\f$-by-\\f$n\\f$ matrix \\f$A\\f$, its QL-decomposition is a matrix\n * decomposition of the form:\n * \\f[\n *   A=QL\n * \\f]\n * where \\f$L\\f$ is an m-by-n lower trapezoidal (or, when \\f$m \\ge n\\f$,\n * triangular) matrix and \\f$Q\\f$ is an m-by-m orthogonal (or unitary) matrix,\n * that is one satisfying:\n * \\f[\n *  Q^{T}Q=I\n * \\f]\n  where \\f$Q^{T}\\f$ is the transpose of \\f$Q\\f$ and \\f$I\\f$ is the identity\n * matrix.\n *\n * For the special case of \\f$m \\ge n\\f$, the factorization can be rewritten as:\n * \\f[\n *  A=\\begin{pmatrix}\n *     Q_1 & Q_2\n *     \\end{pmatrix}\n *     \\begin{pmatrix}\n *     L_1 \\\\\n *     L_2 \\\\\n *     \\end{pmatrix}\n *   =\\begin{pmatrix}\n *     Q_1 & Q_2\n *     \\end{pmatrix}\n *     \\begin{pmatrix}\n *     0 \\\\\n *     L_2 \\\\\n *     \\end{pmatrix}\n *   = Q_2 L_2\n * \\f] \n * where \\f$Q_1\\f$ is an m-by-(m-n) matrix, \\f$Q_2\\f$ is an m-by-n matrix,\n * \\f$L_1\\f$ is an (m-n)-by-n zero matrix, and \\f$L_2\\f$ is an n-by-n lower\n * triangular matrix.\n *\n * The QL factorization is particular useful for computing minimum-phase\n * filters.\n *\n * <hr/>\n *\n * Copyright (c) 2010, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_QL_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_QL_HPP\n\n\n#include <algorithm>\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/numeric/bindings/lapack/computational/geqlf.hpp>\n#include <boost/numeric/bindings/lapack/computational/orgql.hpp>\n#include <boost/numeric/bindings/lapack/computational/ormql.hpp>\n#include <boost/numeric/bindings/lapack/computational/ungql.hpp>\n#include <boost/numeric/bindings/ublas.hpp>\n#include <boost/numeric/bindings/tag.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/ublas/detail/temporary.hpp>\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/fwd.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublasx/operation/num_columns.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n#include <boost/numeric/ublasx/operation/size.hpp>\n#include <boost/numeric/ublasx/traits/layout_type.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <complex>\n#include <cstddef>\n#include <stdint.h>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\nnamespace detail { namespace /*<unnamed>*/ {\n\nstruct ql_decomposition_impl_common;\n\n/**\n * \\brief Type-oriented operations for QL decomposition.\n *\n * \\tparam IsComplex Logical parameter telling if the we are doing either a real\n *  or a complex QL decomposition.\n *\n * This class makes distinction between the real and the complex case.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <bool IsComplex>\nstruct ql_decomposition_impl;\n\n\n/**\n * \\brief Common operations for QL decomposition.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\nstruct ql_decomposition_impl_common\n{\n\t/// Performan QL decomposition of the given input matrix \\a A\n\t/// (row-major case).\n\ttemplate <typename AMatrixT, typename TauVectorT>\n\t\tstatic void decompose(AMatrixT& A, TauVectorT& tau, row_major_tag)\n\t{\n\t\tmatrix<typename matrix_traits<AMatrixT>::value_type, column_major> tmp_A(A);\n\n\t\tdecompose(tmp_A, tau, column_major_tag());\n\n\t\tA = tmp_A;\n\t}\n\n\n\t/// Performan QL decomposition of the given input matrix \\a A\n\t/// (column-major case).\n\ttemplate <typename AMatrixT, typename TauVectorT>\n\t\tstatic void decompose(AMatrixT& A, TauVectorT& tau, column_major_tag)\n\t{\n\t\ttypedef typename matrix_traits<AMatrixT>::size_type size_type;\n\n\t\tsize_type m = num_rows(A);\n\t\tsize_type n = num_columns(A);\n\t\tsize_type k = ::std::min(m,n);\n\n\t\tif (size(tau) != k)\n\t\t{\n\t\t\ttau.resize(k, false);\n\t\t}\n\n\t\t::boost::numeric::bindings::lapack::geqlf(A, tau);\n\t}\n\n\n\t/// Extract the L matrix from a previously computing QL decomposition\n\t/// (row-major case).\n\ttemplate <typename QLMatrixT, typename LMatrixT>\n\t\tstatic void extract_L(QLMatrixT const& QL, LMatrixT& L, bool full, row_major_tag)\n\t{\n\t\tmatrix<typename matrix_traits<QLMatrixT>::value_type, column_major> tmp_QL(QL);\n\t\tmatrix<typename matrix_traits<LMatrixT>::value_type, column_major> tmp_L(L);\n\n\t\textract_L(tmp_QL, tmp_L, full, column_major_tag());\n\n\t\tL = tmp_L;\n\t}\n\n\n\t/**\n\t * \\brief Extract the L matrix from a previously computing QL decomposition\n\t * (column-major case).\n\t *\n\t * Let QL be an m-by-n matrix, then the L matrix is built as:\n\t * - If m >= n, the lower triangle of the submatrix QL(m-n+1:m,1:n)\n\t *   contains the n-by-n lower triangular matrix L;\n\t * - if m <= n, the elements on and below the (n-m)-th\n\t *   superdiagonal contain the m-by-n lower trapezoidal matrix L.\n\t * .\n\t */\n\ttemplate <typename QLMatrixT, typename LMatrixT>\n\t\tstatic void extract_L(QLMatrixT const& QL, LMatrixT& L, bool full, column_major_tag)\n\t{\n\t\ttypedef typename matrix_traits<LMatrixT>::size_type size_type;\n\t\ttypedef typename matrix_traits<LMatrixT>::value_type value_type;\n\n\t\tsize_type m = num_rows(QL);\n\t\tsize_type n = num_columns(QL);\n\t\tsize_type nr = full ? m : ::std::min(m,n);\n\n\t\tif (num_rows(L) != nr && num_columns(L) != n)\n\t\t{\n\t\t\tL.resize(nr, n, false);\n\t\t}\n\n\t\t//::std::fill(L.data().begin(), L.data().end(), value_type/*zero*/());\n\t\tif (m >= n)\n\t\t{\n\t\t\tsize_type k = m-n;\n\t\t\tsize_type kr = k;\n\n\t\t\t// Set to zero the first m-n rows\n\t\t\tif (full)\n\t\t\t{\n\t\t\t\tsubrange(L, 0, k, 0, n) = scalar_matrix<value_type>(k, n, value_type/*zero*/());\n//\t\t\t\tfor (size_type row = 0; row < k; ++row)\n//\t\t\t\t{\n//\t\t\t\t\tfor(size_type col = 0; col < n; ++col)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tL(row,col) = value_type/*zero*/();\n//\t\t\t\t\t}\n//\t\t\t\t}\n\t\t\t\tkr = 0;\n\t\t\t}\n\t\t\t// the lower triangle of the submatrix QL(m-n+1:m,1:n) contains the\n\t\t\t// n-by-n lower triangular matrix L\n\t\t\tfor (size_type row = k; row < m; ++row)\n\t\t\t{\n\t\t\t\tfor (size_type col = 0; col < n; ++col)\n\t\t\t\t{\n\t\t\t\t\tif (col <= (row-k))\n\t\t\t\t\t{\n\t\t\t\t\t\tL(row-kr,col) = QL(row,col);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tL(row-kr,col) = value_type/*zero*/();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t // the elements on and below the (n-m)-th\n\t\t\t // superdiagonal contain the m-by-n lower trapezoidal matrix L.\n\t\t\tsize_type k = n-m;\n\t\t\tfor (size_type row = 0; row < m; ++row)\n\t\t\t{\n\t\t\t\tfor(size_type col = 0; col < n; ++col)\n\t\t\t\t{\n\t\t\t\t\tif (col <= (row+k))\n\t\t\t\t\t{\n\t\t\t\t\t\tL(row,col) = QL(row,col);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tL(row,col) = value_type/*zero*/();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/**\n\t * \\brief Multiply the given \\a C matrix by the \\c Q matrix obtained from\n\t *  the QL decomposition.\n\t *\n\t * \\tparam QLMatrixT The type of the \\a QL matrix.\n\t * \\tparam TAUMatrixT The type of the \\a tau vector.\n\t * \\tparam CMatrixT The type of the \\a C matrix.\n\t *\n\t * \\param QL The matrix obtained by the QL decomposition such that the i-th\n\t *  column contains the vector which defines the elementary reflector\n\t *  \\f$H(i)\\f$, for \\f$i = 1,2,\\ldots,k\\f$.\n\t * \\param tau The vector obtained by the QL decomposition containing the\n\t *  scalar factors of the elementary reflectors \\f$H(i)\\f$, for\n\t *  \\f$i=1,2,\\ldots,k\\f$.\n\t * \\param left_Q A boolean value indicating which side of the product the\n\t *  matrix \\c Q will occupy. A \\c true value indicates that \\c Q is the left\n\t *  operand, while a \\c false value indicates that \\c Q is the right\n\t *  operand.\n\t * \\param trans_Q A boolean value indicating if the matrix \\c Q is to be\n\t *  transposed. A \\c true value indicates that \\c Q is to be transposed,\n\t *  while a \\c false value indicates that \\c Q is to be taken as-is.\n\t * \\param orientation The matrix orientation fixed to row-major.\n\t *\n\t * Let \\c Q be the matrix obtained from the QL decomposition represented\n\t * by the \\a QL matrix and the \\a tau vector parameters. \n\t * Then this function computes the following matrix product:\n\t * \\f{equation*}{\n\t *   \\begin{cases}\n\t *   Q C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n\t *   Q^T C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{true}}, \\\\\n\t *   C Q, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n\t *   C Q^T, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{true}}.\n\t *  \\end{cases}\n\t * \\f}\n\t */\n\ttemplate <typename QLMatrixT, typename TAUVectorT, typename CMatrixT>\n\t\tstatic void prod(QLMatrixT& QL, TAUVectorT const& tau, CMatrixT& C, bool left_Q, bool trans_Q, row_major_tag)\n\t{\n\t\t//NOTE: QL cannot be const since LAPACK::ORMQL modified it, restoring\n\t\t//      it at the end of the function.\n\n\t\tmatrix<typename matrix_traits<QLMatrixT>::value_type, column_major> tmp_QL(QL);\n\t\tmatrix<typename matrix_traits<CMatrixT>::value_type, column_major> tmp_C(C);\n\n\t\tprod(tmp_QL, tau, tmp_C, left_Q, trans_Q, column_major_tag());\n\n\t\tC = tmp_C;\n\t}\n\n\n\t/**\n\t * \\brief Multiply the given \\a C matrix by the \\c Q matrix obtained from\n\t *  the QL decomposition.\n\t *\n\t * \\tparam QLMatrixT The type of the \\a QL matrix.\n\t * \\tparam TAUMatrixT The type of the \\a tau vector.\n\t * \\tparam CMatrixT The type of the \\a C matrix.\n\t *\n\t * \\param QL The matrix obtained by the QL decomposition such that the i-th\n\t *  column contains the vector which defines the elementary reflector\n\t *  \\f$H(i)\\f$, for \\f$i = 1,2,\\ldots,k\\f$.\n\t * \\param tau The vector obtained by the QL decomposition containing the\n\t *  scalar factors of the elementary reflectors \\f$H(i)\\f$, for\n\t *  \\f$i=1,2,\\ldots,k\\f$.\n\t * \\param left_Q A boolean value indicating which side of the product the\n\t *  matrix \\c Q will occupy. A \\c true value indicates that \\c Q is the left\n\t *  operand, while a \\c false value indicates that \\c Q is the right\n\t *  operand.\n\t * \\param trans_Q A boolean value indicating if the matrix \\c Q is to be\n\t *  transposed. A \\c true value indicates that \\c Q is to be transposed,\n\t *  while a \\c false value indicates that \\c Q is to be taken as-is.\n\t * \\param orientation The matrix orientation fixed to column-major.\n\t *\n\t * Let \\c Q be the matrix obtained from the QL decomposition represented\n\t * by the \\a QL matrix and the \\a tau vector parameters. \n\t * Then this function computes the following matrix product:\n\t * \\f{equation*}{\n\t *   \\begin{cases}\n\t *   Q C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n\t *   Q^T C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{true}}, \\\\\n\t *   C Q, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n\t *   C Q^T, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{true}}.\n\t *  \\end{cases}\n\t * \\f}\n\t */\n\ttemplate <typename QLMatrixT, typename TAUVectorT, typename CMatrixT>\n\t\tstatic void prod(QLMatrixT& QL, TAUVectorT const& tau, CMatrixT& C, bool left_Q, bool trans_Q, column_major_tag /*orientation*/)\n\t{\n\t\t//NOTE: QL cannot be const since LAPACK::ORMQL modified it, restoring\n\t\t//      it at the end of the function.\n\n//\t\ttypedef typename matrix_traits<QLMatrixT>::value_type value_type;\n//\t\ttypedef typename matrix_traits<QLMatrixT>::size_type size_type;\n//\t\ttypedef typename type_traits<value_type>::real_type real_type;\n//\n//\t\tconst ::fortran_int_t m = num_rows(C);\n//\t\tconst ::fortran_int_t n = num_columns(C);\n//\t\tconst ::fortran_int_t k = size(tau);\n//\t\tconst ::fortran_int_t lda = num_rows(QL);\n//\t\tconst ::fortran_int_t ldc = m;\n//\t\treal_type* work;\n//\t\treal_type opt_work_size;\n//\t\t::fortran_int_t lwork;\n//\t\t::std::ptrdiff_t info;\n\n\t\tif (left_Q)\n\t\t{\n\t\t\tif (trans_Q)\n\t\t\t{\n//\t\t\t\t//FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\t&opt_work_size,\n//\t\t\t\t\t-1\n//\t\t\t\t);\n//\t\t\t\tlwork = static_cast< ::fortran_int_t >(opt_work_size);\n//\t\t\t\twork = new real_type[lwork];\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\twork,\n//\t\t\t\t\tlwork\n//\t\t\t\t);\n//\t\t\t\tdelete[] work;\n\t\t\t\t::boost::numeric::bindings::lapack::ormql(\n\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n\t\t\t\t\t::boost::numeric::bindings::trans(QL),\n\t\t\t\t\ttau,\n\t\t\t\t\tC\n\t\t\t\t);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n//\t\t\t\t//FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::no_transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\t&opt_work_size,\n//\t\t\t\t\t-1\n//\t\t\t\t);\n//\t\t\t\tlwork = static_cast< ::fortran_int_t >(opt_work_size);\n//\t\t\t\twork = new real_type[lwork];\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::no_transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\twork,\n//\t\t\t\t\tlwork\n//\t\t\t\t);\n//\t\t\t\tdelete[] work;\n\t\t\t\t::boost::numeric::bindings::lapack::ormql(\n\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n\t\t\t\t\tQL,\n\t\t\t\t\ttau,\n\t\t\t\t\tC\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (trans_Q)\n\t\t\t{\n//\t\t\t\t//FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\t&opt_work_size,\n//\t\t\t\t\t-1\n//\t\t\t\t);\n//\t\t\t\tlwork = static_cast< ::fortran_int_t >(opt_work_size);\n//\t\t\t\twork = new real_type[lwork];\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\twork,\n//\t\t\t\t\tlwork\n//\t\t\t\t);\n//\t\t\t\tdelete[] work;\n\t\t\t\t::boost::numeric::bindings::lapack::ormql(\n\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n\t\t\t\t\t::boost::numeric::bindings::trans(QL),\n\t\t\t\t\ttau,\n\t\t\t\t\tC\n\t\t\t\t);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n//\t\t\t\t//FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::no_transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\t&opt_work_size,\n//\t\t\t\t\t-1\n//\t\t\t\t);\n//\t\t\t\tlwork = static_cast< ::fortran_int_t >(opt_work_size);\n//\t\t\t\twork = new real_type[lwork];\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::no_transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\twork,\n//\t\t\t\t\tlwork\n//\t\t\t\t);\n//\t\t\t\tdelete[] work;\n\t\t\t\t::boost::numeric::bindings::lapack::ormql(\n\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n\t\t\t\t\tQL,\n\t\t\t\t\ttau,\n\t\t\t\t\tC\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n};\n\n\n/**\n * \\brief QL decomposition operations for non-complex types.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <>\nstruct ql_decomposition_impl<false>: public ql_decomposition_impl_common\n{\n\t/// Extract the Q matrix from a previously computing QL decomposition\n\t/// (row-major case).\n\ttemplate <typename QLMatrixT, typename TauVectorT, typename QMatrixT>\n\t\tstatic void extract_Q(QLMatrixT const& QL, TauVectorT const& tau, QMatrixT& Q, bool full, row_major_tag)\n\t{\n\t\tmatrix<typename matrix_traits<QLMatrixT>::value_type, column_major> tmp_QL(QL);\n\t\tmatrix<typename matrix_traits<QMatrixT>::value_type, column_major> tmp_Q(Q);\n\n\t\textract_Q(tmp_QL, tau, tmp_Q, full, column_major_tag());\n\n\t\tQ = tmp_Q;\n\t}\n\n\n\t/// Extract the Q matrix from a previously computing QL decomposition\n\t/// (column-major case).\n\ttemplate <typename QLMatrixT, typename TauVectorT, typename QMatrixT>\n\t\tstatic void extract_Q(QLMatrixT const& QL, TauVectorT& tau, QMatrixT& Q, bool full, column_major_tag)\n\t{\n\t\ttypedef typename matrix_traits<QMatrixT>::size_type size_type;\n\t\ttypedef typename matrix_traits<QMatrixT>::value_type value_type;\n\n\t\tsize_type m = num_rows(QL);\n\t\tsize_type n = num_columns(QL);\n\t\tsize_type nc = full ? m : ::std::min(m,n);\n\n\t\tif (num_rows(Q) != m || num_columns(Q) != nc)\n\t\t{\n\t\t\tQ.resize(m, nc, false);\n\t\t}\n\n\t\tif (m > n)\n\t\t{\n\t\t\tif (full)\n\t\t\t{\n\t\t\t\tsubrange(Q, 0, m, 0, m-n) = scalar_matrix<value_type>(m, m-n, value_type/*zero*/());\n\t\t\t\tsubrange(Q, 0, m, m-n, m) = QL;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tQ = QL;\n\t\t\t}\n\t\t}\n\t\telse if (m < n)\n\t\t{\n\t\t\tsubrange(Q, 0, m-1, 0, 1) = scalar_matrix<value_type>(m-1, 1, value_type/*zero*/());\n\t\t\tsubrange(Q, m-1, m, 0, m) = scalar_matrix<value_type>(1, m, value_type/*zero*/());\n\t\t\tsubrange(Q, 0, m-1, 1, m) = subrange(QL, 0, m-1, n-m+1, n);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQ = QL;\n\t\t}\n\n\t\t::boost::numeric::bindings::lapack::orgql(Q, tau);\n/*\n\t\t// Compute Q without LAPACK\n\t\t//\n\t\t// The matrix Q is represented as a product of elementary reflectors\n\t\t//   Q = H(k) . . . H(2) H(1), where k = min(m,n).\n\t\t// Each H(i) has the form\n\t\t//   H(i) = I - tau * v * v'\n\t\t// where tau is a real scalar, and v is a real vector with\n\t\t// v(m-k+i+1:m) = 0 and v(m-k+i) = 1; v(1:m-k+i-1) is stored on exit in\n\t\t// A(1:m-k+i-1,n-k+i), and tau in TAU(i).\n\n\t\tsize_type k = std::min(m, n);\n\n\t\tif (num_rows(Q) != m || num_columns(Q) != m)\n\t\t{\n\t\t\tQ.resize(m, m, false);\n\t\t}\n\n\t\tidentity_matrix<value_type> I(m);\n\n\t\tQ = I;\n\t\tfor (size_type i = k-1; (i+1) > 0; --i)\n\t\t{\n\t\t\t// Build v = [ A(1:m-k+i-1,n-k+i) 1 0 ... 0 ]\n\n\t\t\tvector<value_type> v(m, value_type());\n\t\t\tfor (size_type j = 0; j < m-k+i; ++j)\n\t\t\t{\n\t\t\t\tv(j) = QL(j,i);\n\t\t\t}\n\t\t\tv(m-k+i) = value_type(1);\n\n\t\t\tmatrix<value_type, column_major> H = I - tau(i)*outer_prod(v, v);\n\t\t\tQ = prod(Q, H);\n\t\t}\n*/\n\t}\n};\n\n\n/**\n * \\brief QL decomposition operations for complex types.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <>\nstruct ql_decomposition_impl<true>: public ql_decomposition_impl_common\n{\n\t/// Extract the Q matrix from a previously computing QL decomposition\n\t/// (row-major case).\n\ttemplate <typename QLMatrixT, typename TauVectorT, typename QMatrixT>\n\t\tstatic void extract_Q(QLMatrixT const& QL, TauVectorT const& tau, QMatrixT& Q, bool full, row_major_tag)\n\t{\n\t\tmatrix<typename matrix_traits<QLMatrixT>::value_type, column_major> tmp_QL(QL);\n\t\tmatrix<typename matrix_traits<QMatrixT>::value_type, column_major> tmp_Q(Q);\n\n\t\textract_Q(tmp_QL, tau, tmp_Q, full, column_major_tag());\n\n\t\tQ = tmp_Q;\n\t}\n\n\n\t/// Extract the Q matrix from a previously computing QL decomposition\n\t/// (column-major case).\n\ttemplate <typename QLMatrixT, typename TauVectorT, typename QMatrixT>\n\t\tstatic void extract_Q(QLMatrixT const& QL, TauVectorT& tau, QMatrixT& Q, bool full, column_major_tag)\n\t{\n\t\ttypedef typename matrix_traits<QMatrixT>::size_type size_type;\n\t\ttypedef typename matrix_traits<QMatrixT>::value_type value_type;\n\n\t\tsize_type m = num_rows(QL);\n\t\tsize_type n = num_columns(QL);\n\t\tsize_type nc = full ? m : std::min(m,n);\n\n\t\tif (num_rows(Q) != m || num_columns(Q) != nc)\n\t\t{\n\t\t\tQ.resize(m, nc, false);\n\t\t}\n\n\t\tif (m > n)\n\t\t{\n\t\t\tif (full)\n\t\t\t{\n\t\t\t\tsubrange(Q, 0, m, 0, m-n) = scalar_matrix<value_type>(m, m-n, 0);\n\t\t\t\tsubrange(Q, 0, m, m-n, m) = QL;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tQ = QL;\n\t\t\t}\n\t\t}\n\t\telse if (m < n)\n\t\t{\n\t\t\tsubrange(Q, 0, m-1, 0, 1) = scalar_matrix<value_type>(m-1, 1, 0);\n\t\t\tsubrange(Q, m-1, m, 0, m) = scalar_matrix<value_type>(1, m, 0);\n\t\t\tsubrange(Q, 0, m-1, 1, m) = subrange(QL, 0, m-1, n-m+1, n);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQ = QL;\n\t\t}\n\n\t\t::boost::numeric::bindings::lapack::ungql(Q, tau);\n/*\n\t\t// Compute Q without LAPACK\n\t\t//\n\t\t// The matrix Q is represented as a product of elementary reflectors\n\t\t//   Q = H(k) . . . H(2) H(1), where k = min(m,n).\n\t\t// Each H(i) has the form\n\t\t//   H(i) = I - tau * v * v'\n\t\t// where tau is a real scalar, and v is a real vector with\n\t\t// v(m-k+i+1:m) = 0 and v(m-k+i) = 1; v(1:m-k+i-1) is stored on exit in\n\t\t// A(1:m-k+i-1,n-k+i), and tau in TAU(i).\n\n\t\tsize_type k = std::min(m, n);\n\n\t\tif (num_rows(Q) != m || num_columns(Q) != m)\n\t\t{\n\t\t\tQ.resize(m, m, false);\n\t\t}\n\n\t\tidentity_matrix<value_type> I(m);\n\n\t\tQ = I;\n\t\tfor (size_type i = k-1; (i+1) > 0; --i)\n\t\t{\n\t\t\t// Build v = [ A(1:m-k+i-1,n-k+i) 1 0 ... 0 ]\n\n\t\t\tvector<value_type> v(m, value_type());\n\t\t\tfor (size_type j = 0; j < m-k+i; ++j)\n\t\t\t{\n\t\t\t\tv(j) = QL(j,i);\n\t\t\t}\n\t\t\tv(m-k+i) = value_type(1);\n\n\t\t\tmatrix<value_type, column_major> H = I - tau(i)*outer_prod(v, v);\n\t\t\tQ = prod(Q, H);\n\t\t}\n*/\n\t}\n};\n\n\n/// Free function performing the QL decomposition of the given matrix expression \\a A.\ntemplate<typename MatrixExprT, typename QMatrixT, typename LMatrixT, typename OrientationT>\nvoid ql_decompose_impl(matrix_expression<MatrixExprT> const& A, QMatrixT& Q, LMatrixT& L, bool full, OrientationT orientation)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\n\tmatrix<value_type, typename layout_type<MatrixExprT>::type> tmp_QL(A);\n\tvector<value_type> tmp_tau;\n\n\tql_decomposition_impl<\n\t\t\t::boost::is_complex<value_type>::value\n\t\t>::template decompose(tmp_QL, tmp_tau, orientation);\n\n\n\tql_decomposition_impl<\n\t\t\t::boost::is_complex<value_type>::value\n\t\t>::template extract_Q(tmp_QL, tmp_tau, Q, full, orientation);\n\n\n\tql_decomposition_impl<\n\t\t\t::boost::is_complex<value_type>::value\n\t\t>::template extract_L(tmp_QL, L, full, orientation);\n}\n\n}} // Namespace detail::<unnamed>\n\n\n/**\n * \\brief QL decomposition.\n *\n * \\tparam ValueT The type of the elements stored in the input matrices.\n *\n * \\todo Currently, the type of the L matrix is a dense matrix.\n *  Can we use a better matrix structure?\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename ValueT>\nclass ql_decomposition\n{\n\tpublic: typedef ValueT value_type;\n\tprivate: typedef matrix<value_type, column_major> work_matrix_type;\n\tprivate: typedef vector<value_type> tau_vector_type;\n\tpublic: typedef work_matrix_type QL_matrix_type;\n\tpublic: typedef work_matrix_type Q_matrix_type;\n\tpublic: typedef work_matrix_type L_matrix_type;//TODO: Can I use a special matrix\n\n\n\t/// Default constructor.\n\tpublic: ql_decomposition()\n\t{\n\t\t// empty\n\t}\n\n\n\t/// Decompose the given matrix expression \\a A.\n\tpublic: template <typename MatrixExprT>\n\t\tql_decomposition(matrix_expression<MatrixExprT> const& A)\n\t\t: QL_(A)\n\t{\n\t\tdecompose();\n\t}\n\n\n\t/// Decompose the given matrix expression \\a A.\n\tpublic: template <typename MatrixExprT>\n\t\tvoid decompose(matrix_expression<MatrixExprT> const& A)\n\t{\n\t\tQL_ = A;\n\n\t\tdecompose();\n\t}\n\n\n\t/**\n\t * \\brief Extract the \\c Q matrix.\n\t * \\param full If \\c false enables the economy-size mode whereby a\n\t *  reduced (rectangular) Q matrix is returned instead of full (square) one.\n\t * \\return The \\c Q matrix.\n\t *\n\t * The <em>economy-size</em> mode is useful when \\f$m > n\\f$ (where \\f$m\\f$\n\t * and \\f$n\\f$ are the number of rows and columns of the decomposed matrix\n\t * \\f$A\\f$).\n\t * As a matter of fact, in this case, the QL factorization can be viewed as:\n\t * \\f[\n\t *   A = QL = \\begin{pmatrix} Q_1 & Q_2 \\end{pmatrix} \\begin{pmatrix} 0 \\\\ L \\end{pmatrix} = Q_2 L\n\t * \\f]\n\t * where \\f$Q_2\\f$ is an m-by-n matrix containing the n trailing columns of\n\t * \\f$Q\\f$.\n\t */\n\tpublic: Q_matrix_type Q(bool full = true) const\n\t{\n\t\tQ_matrix_type tmp_Q;\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template extract_Q(QL_, tau_, tmp_Q, full, column_major_tag());\n\n\t\treturn tmp_Q;\n\t}\n\n\n\t/**\n\t * \\brief Extract the \\c L matrix.\n\t * \\param full If \\c false enables the economy-size mode whereby a\n\t *  reduced \\f$\\min(m,n)\\f$-by\\f$n\\f$ \\c L matrix is returned instead of the\n\t *  full \\f$m\\f$-by-\\f$n\\f$ one.\n\t * \\return The \\c L matrix.\n\t *\n\t * The <em>economy-size</em> mode is useful when \\f$m > n\\f$ (where \\f$m\\f$\n\t * and \\f$n\\f$ are the number of rows and columns of the decomposed matrix\n\t * \\f$A\\f$).\n\t * As a matter of fact, in this case, the QL factorization can be viewed as:\n\t * \\f[\n\t *   A = QL = \\begin{pmatrix} Q_1 & Q_2 \\end{pmatrix} \\begin{pmatrix} 0 \\\\ L \\end{pmatrix} = Q_2 L\n\t * \\f]\n\t * where \\f$Q_2\\f$ is an m-by-n matrix containing the n trailing columns of\n\t * \\f$Q\\f$.\n\t */\n\tpublic: L_matrix_type L(bool full = true) const\n\t{\n\t\tL_matrix_type tmp_L;\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template extract_L(QL_, tmp_L, full, column_major_tag());\n\n\t\treturn tmp_L;\n\t}\n\n\n\t/// Perform the product \\f$Q C\\f$ and store the result in \\a C.\n\tpublic: template <typename CMatrixT>\n\t\tvoid lprod_inplace(CMatrixT& C) const\n\t{\n\t\ttypedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;\n\n\t\tlprod_inplace(C, orientation_category());\n\t}\n\n\n\t/// Perform the product \\f$C Q\\f$ and store the result in \\a C.\n\tpublic: template <typename CMatrixT>\n\t\tvoid rprod_inplace(CMatrixT& C) const\n\t{\n\t\ttypedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;\n\n\t\trprod_inplace(C, orientation_category());\n\t}\n\n\n\t/// Perform the product \\f$Q^T C\\f$ and store the result in \\a C.\n\tpublic: template <typename CMatrixT>\n\t\tvoid tlprod_inplace(CMatrixT& C) const\n\t{\n\t\ttypedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;\n\n\t\ttlprod_inplace(C, orientation_category());\n\t}\n\n\n\t/// Perform the product \\f$C Q^T\\f$ and store the result in \\a C.\n\tpublic: template <typename CMatrixT>\n\t\tvoid trprod_inplace(CMatrixT& C) const\n\t{\n\t\ttypedef typename matrix_traits<CMatrixT>::orientation_category orientation_category;\n\n\t\ttrprod_inplace(C, orientation_category());\n\t}\n\n\n\t/// Perform the product \\f$Q C\\f$ and return the result.\n\tpublic: template <typename CMatrixExprT>\n\t\ttypename matrix_temporary_traits<CMatrixExprT>::type lprod(matrix_expression<CMatrixExprT> const& C) const\n\t{\n\t\ttypename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);\n\n\t\tlprod_inplace(tmp_C);\n\n\t\treturn tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$C Q\\f$ and return the result.\n\tpublic: template <typename CMatrixExprT>\n\t\ttypename matrix_temporary_traits<CMatrixExprT>::type rprod(matrix_expression<CMatrixExprT> const& C) const\n\t{\n\t\ttypename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);\n\n\t\trprod_inplace(tmp_C);\n\n\t\treturn tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$Q^T C\\f$ and return the result.\n\tpublic: template <typename CMatrixExprT>\n\t\ttypename matrix_temporary_traits<CMatrixExprT>::type tlprod(matrix_expression<CMatrixExprT> const& C) const\n\t{\n\t\ttypename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);\n\n\t\ttlprod_inplace(tmp_C);\n\n\t\treturn tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$C Q^T\\f$ and return the result.\n\tpublic: template <typename CMatrixExprT>\n\t\ttypename matrix_temporary_traits<CMatrixExprT>::type trprod(matrix_expression<CMatrixExprT> const& C) const\n\t{\n\t\ttypename matrix_temporary_traits<CMatrixExprT>::type tmp_C(C);\n\n\t\ttrprod_inplace(tmp_C);\n\n\t\treturn tmp_C;\n\t}\n\n\n\tprivate: void decompose()\n\t{\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template decompose(QL_, tau_, column_major_tag());\n\t}\n\n\n\t/// Perform the product \\f$Q C\\f$ and store the result in \\a C (column-major\n\t/// case).\n\tprivate: template <typename CMatrixT>\n\t\tvoid lprod_inplace(CMatrixT& C, column_major_tag) const\n\t{\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template prod(QL_, tau_, C, true, false, column_major_tag());\n\t}\n\n\n\t/// Perform the product \\f$Q C\\f$ and store the result in \\a C (row-major\n\t/// case).\n\tprivate: template <typename CMatrixT>\n\t\tvoid lprod_inplace(CMatrixT& C, row_major_tag) const\n\t{\n\t\twork_matrix_type tmp_C(C);\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template prod(QL_, tau_, tmp_C, true, false, column_major_tag());\n\n\t\tC = tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$C Q\\f$ and store the result in \\a C (column-major\n\t/// case).\n\tprivate: template <typename CMatrixT>\n\t\tvoid rprod_inplace(CMatrixT& C, column_major_tag) const\n\t{\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template prod(QL_, tau_, C, false, false, column_major_tag());\n\t}\n\n\n\t/// Perform the product \\f$C Q\\f$ and store the result in \\a C (row-major\n\t/// case).\n\tprivate: template <typename CMatrixT>\n\t\tvoid rprod_inplace(CMatrixT& C, row_major_tag) const\n\t{\n\t\twork_matrix_type tmp_C(C);\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template prod(QL_, tau_, tmp_C, false, false, column_major_tag());\n\n\t\tC = tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$Q^T C\\f$ and store the result in \\a C\n\t/// (column-major case).\n\tprivate: template <typename CMatrixT>\n\t\tvoid tlprod_inplace(CMatrixT& C, column_major_tag) const\n\t{\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template prod(QL_, tau_, C, true, true, column_major_tag());\n\t}\n\n\n\t/// Perform the product \\f$Q^T C\\f$ and store the result in \\a C\n\t/// (row-major case).\n\tprivate: template <typename CMatrixT>\n\t\tvoid tlprod_inplace(CMatrixT& C, row_major_tag) const\n\t{\n\t\twork_matrix_type tmp_C(C);\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template prod(QL_, tau_, tmp_C, true, true, column_major_tag());\n\n\t\tC = tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$C Q^T\\f$ and store the result in \\a C\n\t/// (column-major case).\n\tprivate: template <typename CMatrixT>\n\t\tvoid trprod_inplace(CMatrixT& C, column_major_tag) const\n\t{\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template prod(QL_, tau_, C, false, true, column_major_tag());\n\t}\n\n\n\t/// Perform the product \\f$C Q^T\\f$ and store the result in \\a C\n\t/// (row-major case).\n\tprivate: template <typename CMatrixT>\n\t\tvoid trprod_inplace(CMatrixT& C, row_major_tag) const\n\t{\n\t\twork_matrix_type tmp_C(C);\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex<value_type>::value\n\t\t\t>::template prod(QL_, tau_, tmp_C, false, true, column_major_tag());\n\n\t\tC = tmp_C;\n\t}\n\n\n\t// NOTE: the 'mutable' keyword is needed in order to make 'const' the\n\t//       '?prod' methods ('lprod', 'tlprod', 'rprod', 'trprod').\n\t//       Indeed, these methods call the respective '?prod_inplace' methods\n\t//       which, in turns, call the LAPACK::ORMQL function which temporarily\n\t//       changes the QL matrix (and restores it before returning).\n\tprivate: mutable QL_matrix_type QL_;\n\tprivate: tau_vector_type tau_;\n};\n\n\n/// Free function performing the QL decomposition of the given matrix expression \\a A.\ntemplate<typename MatrixExprT, typename OutMatrix1T, typename OutMatrix2T>\nBOOST_UBLAS_INLINE\nvoid ql_decompose(matrix_expression<MatrixExprT> const& A, OutMatrix1T& Q, OutMatrix2T& L, bool full = true)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::orientation_category orientation_category1;\n\ttypedef typename matrix_traits<OutMatrix1T>::orientation_category orientation_category2;\n\ttypedef typename matrix_traits<OutMatrix2T>::orientation_category orientation_category3;\n\n\t// precondition: same orientation category\n\tBOOST_MPL_ASSERT(\n\t\t(::boost::mpl::and_<\n\t\t\t::boost::is_same<orientation_category1,orientation_category2>,\n\t\t\t::boost::is_same<orientation_category1,orientation_category3>\n\t\t>)\n\t);\n\n\tdetail::ql_decompose_impl(A, Q, L, full, orientation_category1());\n}\n\n\n/// Free function performing the QL decomposition of the given matrix expression \\a A.\ntemplate<typename MatrixExprT>\nBOOST_UBLAS_INLINE\nql_decomposition<typename matrix_traits<MatrixExprT>::value_type> ql_decompose(matrix_expression<MatrixExprT> const& A)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\n\treturn ql_decomposition<value_type>(A);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_QL_HPP\n", "meta": {"hexsha": "444417d952fe4a0453b2b692de9f372ba854ed6b", "size": 32591, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/ql.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/ublasx/operation/ql.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/ublasx/operation/ql.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3348334833, "max_line_length": 130, "alphanum_fraction": 0.65797306, "num_tokens": 10128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.645007225936918}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[length\r\n    //` The following simple example shows the calculation of the length of a linestring containing three points\r\n\r\n#include <iostream>\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n\r\n\r\nint main()\r\n{\r\n    using namespace boost::geometry;\r\n    model::linestring<model::d2::point_xy<double> > line;\r\n    read_wkt(\"linestring(0 0,1 1,4 8,3 2)\", line);\r\n    std::cout << \"linestring length is \"\r\n        << length(line)\r\n        << \" units\" << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[length_output\r\n/*`\r\nOutput:\r\n[pre\r\nlinestring length is 15.1127 units\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "cde1447d4e43b246b873ad8c85e4454fbb593b17", "size": 1057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/length.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/length.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/length.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 24.5813953488, "max_line_length": 113, "alphanum_fraction": 0.6726584674, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6448625186331018}}
{"text": "#include <catch.hpp>\n\n#define BOOST_LOG_DYN_LINK 1\n#include <boost/log/trivial.hpp>\n\n#include \"class_vec_3d.hpp\"\n\nTEST_CASE( \"UNIT TEST: vector class {Vec_3D<T>}\", \"[core]\" )\n{\n    BOOST_LOG_TRIVIAL(info) << \"vector class {Vec_3D<T>}\";\n\n    Vec_3D<double> vec_d(sqrt(2.), -sqrt(2.), sqrt(5.));\n    Vec_3D<float> vec_f(sqrt(2.f), -sqrt(2.f), sqrt(5.f));\n    Vec_3D<int> vec_i(3,0,-4);\n    CHECK( vec_d.norm() == Approx(3.) );\n    CHECK( vec_f.norm() == Approx(3.) );\n    CHECK( vec_i.norm() == Approx(5) );\n\n    REQUIRE( vec_f[0] == Approx(sqrt(2.f)) );\n    REQUIRE( vec_f[2] == Approx(sqrt(5.)) );\n\n    vec_d.fill(-1.345E1);\n    REQUIRE( vec_d[0] == -1.345E1 );\n    REQUIRE( vec_d[2] == -13.45 );\n\n    vec_i.fill(0);\n    vec_i+=Vec_3D<int>(2, 3, -4);\n    REQUIRE ( (vec_i[0] + vec_i[1] + vec_i[2]) == Approx(1) );\n    // Vec_3D<double> vec_d2 = vec_i + Vec_3D<double>(1., 1.5, -3.5)*2.;\n    // REQUIRE( vec_d2[0] == Approx(4.) );\n    // REQUIRE( vec_d2[1] == Approx(6.) );\n    // REQUIRE( vec_d2[2] == Approx(-11.) );\n\n    // double sumd = 0;\n    double sumi = 0;\n\n    // for (double val : vec_d2) sumd += val;\n    for (int val : vec_i) sumi += val;\n\n    // CHECK( sumd == Approx(-1.) );\n    CHECK( sumi == 1 );\n\n    CHECK( Vec_3D<int>(4, -3, 8) ==  Vec_3D<int>(4, -3, 8) );\n    CHECK_FALSE( Vec_3D<int>(4, -3, 8) !=  Vec_3D<int>(4, -3, 8) );\n    CHECK( Vec_3D<int>(4, -3, 8) <=  Vec_3D<int>(6, 0, 8) );\n    CHECK_FALSE( Vec_3D<int>(4, -3, 8) <  Vec_3D<int>(2, 0, 10) );\n    CHECK_FALSE( Vec_3D<int>(4, -3, 8) >  Vec_3D<int>(4, 0, 8) );\n}", "meta": {"hexsha": "ca65280ebde6388f5ba391f16a29c23bbf9a730f", "size": 1538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/data/tests/test_vec_3d.cpp", "max_stars_repo_name": "vrastil/Adhesion-Approximation", "max_stars_repo_head_hexsha": "02619dc5aae0627e4a2e87bc3577c75d4b1e42c2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/data/tests/test_vec_3d.cpp", "max_issues_repo_name": "vrastil/Adhesion-Approximation", "max_issues_repo_head_hexsha": "02619dc5aae0627e4a2e87bc3577c75d4b1e42c2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2017-06-27T07:34:02.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-17T07:36:21.000Z", "max_forks_repo_path": "src/data/tests/test_vec_3d.cpp", "max_forks_repo_name": "vrastil/Adhesion-Approximation", "max_forks_repo_head_hexsha": "02619dc5aae0627e4a2e87bc3577c75d4b1e42c2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-20T13:15:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-03T12:48:40.000Z", "avg_line_length": 32.0416666667, "max_line_length": 72, "alphanum_fraction": 0.5416124837, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6448625186331017}}
{"text": "/**\n * @file test_getSchwarzschild.cpp\n * @author Bensuperpc (bensuperpc@gmail.com)\n * @brief \n * @version 1.0.0\n * @date 2021-04-01\n * \n * MIT License\n * \n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE getSchwarzschild\n#include <boost/test/unit_test.hpp>\n#include \"math/constant.hpp\"\n#include \"math/getSchwarzschild_imp.hpp\"\n\nnamespace schwarzschild = my::math::schwarzschild;\n\nBOOST_AUTO_TEST_CASE(test_getSchwarzschild_1)\n{\n    BOOST_CHECK_MESSAGE(static_cast<long int>(schwarzschild::getSchwarzschild<long double>(SUN_MASS)) == static_cast<long int>(2953),\n        static_cast<long int>(schwarzschild::getSchwarzschild<long double>(SUN_MASS)) << \" instead: \" << static_cast<long int>(2953));\n\n    BOOST_CHECK_MESSAGE(static_cast<long int>(schwarzschild::getSchwarzschild<long double>(JUPITER_MASS)) == static_cast<long int>(2),\n        static_cast<long int>(schwarzschild::getSchwarzschild<long double>(JUPITER_MASS)) << \" instead: \" << static_cast<long int>(2));\n\n    BOOST_CHECK_MESSAGE(static_cast<long int>(schwarzschild::getSchwarzschild<long double>(SAGITTARIUS_A_STAR)) == static_cast<long int>(12267767406),\n        static_cast<long int>(schwarzschild::getSchwarzschild<long double>(SAGITTARIUS_A_STAR)) << \" instead: \" << static_cast<long int>(12267767406));\n\n    BOOST_CHECK_MESSAGE(static_cast<long int>(schwarzschild::getSchwarzschild<long double>(TON_618)) == static_cast<long int>(194913974199883),\n        static_cast<long int>(schwarzschild::getSchwarzschild<long double>(TON_618)) << \" instead: \" << static_cast<long int>(194913974199883));\n}\nBOOST_AUTO_TEST_CASE(test_getSchwarzschild_2)\n{\n    BOOST_REQUIRE_MESSAGE(static_cast<long int>(schwarzschild::getSchwarzschild<long double>(0)) == static_cast<long int>(0),\n        static_cast<long int>(schwarzschild::getSchwarzschild<long double>(0)) << \" instead: \" << static_cast<long int>(0));\n}\n/*\nBOOST_AUTO_TEST_CASE(my_test2) {\n  // seven ways to detect and report the same error:\n  BOOST_CHECK(add(2, 2) == 4); // #1 continues on error\n\n  BOOST_REQUIRE(add(2, 2) == 4); // #2 throws on error\n\n  if (add(2, 2) != 4)\n    BOOST_ERROR(\"Ouch...\"); // #3 continues on error\n\n  if (add(2, 2) != 4)\n    BOOST_FAIL(\"Ouch...\"); // #4 throws on error\n\n  if (add(2, 2) != 4)\n    throw \"Ouch...\"; // #5 throws on error\n\n  BOOST_CHECK_MESSAGE(add(2, 2) == 4, // #6 continues on error\n                      \"add(..) result: \" << add(2, 2));\n\n  BOOST_CHECK_EQUAL(add(2, 2), 4); // #7 continues on error\n}\n*/\n", "meta": {"hexsha": "1eea3c617503bf2d0c0306ad75283185f43b05ec", "size": 2478, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/math/test_getSchwarzschild.cpp", "max_stars_repo_name": "Bensuperpc/BenLib", "max_stars_repo_head_hexsha": "1708a27e272a54f437cda50b2ca98ed92f03d721", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-12-02T21:17:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T19:57:42.000Z", "max_issues_repo_path": "src/test/math/test_getSchwarzschild.cpp", "max_issues_repo_name": "bensuperpc/BenLib", "max_issues_repo_head_hexsha": "1708a27e272a54f437cda50b2ca98ed92f03d721", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/math/test_getSchwarzschild.cpp", "max_forks_repo_name": "bensuperpc/BenLib", "max_forks_repo_head_hexsha": "1708a27e272a54f437cda50b2ca98ed92f03d721", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-28T08:43:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-28T08:43:46.000Z", "avg_line_length": 40.6229508197, "max_line_length": 151, "alphanum_fraction": 0.7054075868, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.6448293281358277}}
{"text": "/******************************************************************************\\\n* Author: Matthew Beauregard Smith                                             *\n* Affiliation: The University of Texas at Austin                               *\n* Department: Oden Institute and Institute for Cellular and Molecular Biology  *\n* PI: Edward Marcotte                                                          *\n* Project: Protein Fluorosequencing                                            *\n\\******************************************************************************/\n\n// Boost unit test framework (recommended to be the first include):\n#include <boost/test/unit_test.hpp>\n\n// File under test:\n#include \"normal-distribution-fitter.h\"\n\n// Standard C++ library headers:\n#include <cmath>\n\n// Local project headers:\n#include \"common/error-model.h\"\n\nnamespace whatprot {\n\nnamespace {\nusing boost::unit_test::tolerance;\nusing std::sqrt;\nconst double TOL = 0.000000001;\n}  // namespace\n\nBOOST_AUTO_TEST_SUITE(hmm_suite)\nBOOST_AUTO_TEST_SUITE(fit_suite)\nBOOST_AUTO_TEST_SUITE(normal_distribution_fitter_suite)\n\nBOOST_AUTO_TEST_CASE(constructor_test, *tolerance(TOL)) {\n    NormalDistributionFitter ndf;\n    BOOST_TEST(ndf.w_sum_x == 0.0);\n    BOOST_TEST(ndf.w_sum_x_sq_over_n == 0.0);\n    BOOST_TEST(ndf.w_sum_n == 0.0);\n    BOOST_TEST(ndf.total_weight == 0.0);\n}\n\nBOOST_AUTO_TEST_CASE(add_sample_once_n_eq_1_test, *tolerance(TOL)) {\n    NormalDistributionFitter ndf;\n    double x = 1.277;\n    int n = 1;\n    double w = 0.98;\n    ndf.add_sample(x, n, w);\n    BOOST_TEST(ndf.w_sum_x == x * w);\n    BOOST_TEST(ndf.w_sum_x_sq_over_n == x * x * w / (double)n);\n    BOOST_TEST(ndf.w_sum_n == (double)n * w);\n    BOOST_TEST(ndf.total_weight == w);\n}\n\nBOOST_AUTO_TEST_CASE(add_sample_once_n_gt_1_test, *tolerance(TOL)) {\n    NormalDistributionFitter ndf;\n    double x = 3.1415928;\n    int n = 3;\n    double w = 0.979;\n    ndf.add_sample(x, n, w);\n    BOOST_TEST(ndf.w_sum_x == x * w);\n    BOOST_TEST(ndf.w_sum_x_sq_over_n == x * x * w / (double)n);\n    BOOST_TEST(ndf.w_sum_n == (double)n * w);\n    BOOST_TEST(ndf.total_weight == w);\n}\n\nBOOST_AUTO_TEST_CASE(add_sample_twice_n_eq_1_test, *tolerance(TOL)) {\n    NormalDistributionFitter ndf;\n    double x1 = 1.277;\n    int n1 = 1;\n    double w1 = 0.98;\n    double x2 = 1.166;\n    int n2 = 1;\n    double w2 = 0.49;\n    ndf.add_sample(x1, n1, w1);\n    ndf.add_sample(x2, n2, w2);\n    BOOST_TEST(ndf.w_sum_x == x1 * w1 + x2 * w2);\n    BOOST_TEST(ndf.w_sum_x_sq_over_n\n               == x1 * x1 * w1 / (double)n1 + x2 * x2 * w2 / (double)n2);\n    BOOST_TEST(ndf.w_sum_n == (double)n1 * w1 + (double)n2 * w2);\n    BOOST_TEST(ndf.total_weight == w1 + w2);\n}\n\nBOOST_AUTO_TEST_CASE(add_sample_twice_n_gt_1_test, *tolerance(TOL)) {\n    NormalDistributionFitter ndf;\n    double x1 = 3.43;\n    int n1 = 3;\n    double w1 = 0.98;\n    double x2 = 4.91;\n    int n2 = 5;\n    double w2 = 0.49;\n    ndf.add_sample(x1, n1, w1);\n    ndf.add_sample(x2, n2, w2);\n    BOOST_TEST(ndf.w_sum_x == x1 * w1 + x2 * w2);\n    BOOST_TEST(ndf.w_sum_x_sq_over_n\n               == x1 * x1 * w1 / (double)n1 + x2 * x2 * w2 / (double)n2);\n    BOOST_TEST(ndf.w_sum_n == (double)n1 * w1 + (double)n2 * w2);\n    BOOST_TEST(ndf.total_weight == w1 + w2);\n}\n\nBOOST_AUTO_TEST_CASE(get_type_test, *tolerance(TOL)) {\n    NormalDistributionFitter ndf;\n    BOOST_TEST(ndf.get_type() == DistributionType::NORMAL);\n}\n\nBOOST_AUTO_TEST_CASE(get_mu_one_sample_test, *tolerance(TOL)) {\n    NormalDistributionFitter ndf;\n    double x1 = 3.43;\n    int n1 = 3;\n    double w1 = 0.98;\n    ndf.add_sample(x1, n1, w1);\n    BOOST_TEST(ndf.get_mu() == x1 / (double)n1);\n}\n\nBOOST_AUTO_TEST_CASE(get_mu_two_samples_test, *tolerance(TOL)) {\n    NormalDistributionFitter ndf;\n    double x1 = 3.43;\n    int n1 = 3;\n    double w1 = 0.98;\n    double x2 = 4.91;\n    int n2 = 5;\n    double w2 = 0.49;\n    ndf.add_sample(x1, n1, w1);\n    ndf.add_sample(x2, n2, w2);\n    BOOST_TEST(ndf.get_mu()\n               == (x1 * w1 + x2 * w2) / ((double)n1 * w1 + (double)n2 * w2));\n}\n\nBOOST_AUTO_TEST_CASE(get_sigma_one_sample_test, *tolerance(TOL)) {\n    NormalDistributionFitter ndf;\n    double x1 = 3.43;\n    int n1 = 3;\n    double w1 = 0.98;\n    ndf.add_sample(x1, n1, w1);\n    double mu = ndf.get_mu();\n    BOOST_TEST(ndf.get_sigma() == sqrt((x1 - n1 * mu) * (x1 - n1 * mu) / n1));\n}\n\nBOOST_AUTO_TEST_CASE(get_sigma_two_samples_test, *tolerance(TOL)) {\n    NormalDistributionFitter ndf;\n    double x1 = 3.43;\n    int n1 = 3;\n    double w1 = 0.98;\n    double x2 = 4.91;\n    int n2 = 5;\n    double w2 = 0.49;\n    ndf.add_sample(x1, n1, w1);\n    ndf.add_sample(x2, n2, w2);\n    double mu = ndf.get_mu();\n    BOOST_TEST(ndf.get_sigma()\n               == sqrt(((x1 - (double)n1 * mu) * (x1 - (double)n1 * mu) * w1\n                                / (double)n1\n                        + (x2 - (double)n2 * mu) * (x2 - (double)n2 * mu) * w2\n                                  / (double)n2)\n                       / (w1 + w2)));\n}\n\nBOOST_AUTO_TEST_SUITE_END()  // normal_distribution_fitter_suite\nBOOST_AUTO_TEST_SUITE_END()  // fit_suite\nBOOST_AUTO_TEST_SUITE_END()  // hmm_suite\n\n}  // namespace whatprot\n", "meta": {"hexsha": "90222fd89dfab115b06fc75f79c9ed0f6438a53e", "size": 5152, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cc_code/src/hmm/fit/normal-distribution-fitter.test.cc", "max_stars_repo_name": "erisyon/whatprot", "max_stars_repo_head_hexsha": "176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cc_code/src/hmm/fit/normal-distribution-fitter.test.cc", "max_issues_repo_name": "erisyon/whatprot", "max_issues_repo_head_hexsha": "176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-12T00:50:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-15T17:59:12.000Z", "max_forks_repo_path": "cc_code/src/hmm/fit/normal-distribution-fitter.test.cc", "max_forks_repo_name": "erisyon/whatprot", "max_forks_repo_head_hexsha": "176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-11T19:34:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T19:34:43.000Z", "avg_line_length": 32.0, "max_line_length": 80, "alphanum_fraction": 0.5933618012, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6448293232711588}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[for_each_point\n//` Convenient usage of for_each_point, rounding all points of a geometry\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/domains/gis/io/wkt/wkt.hpp>\n\n\n\ntemplate <typename Point>\nclass round_coordinates\n{\nprivate :\n    typedef typename boost::geometry::coordinate_type<Point>::type coordinate_type;\n    coordinate_type factor;\n\n    inline coordinate_type round(coordinate_type value)\n    {\n        return floor(0.5 + (value / factor)) * factor;\n    }\n\npublic :\n    round_coordinates(coordinate_type f)\n        : factor(f)\n    {}\n\n    inline void operator()(Point& p)\n    {\n        using boost::geometry::get;\n        using boost::geometry::set;\n        set<0>(p, round(get<0>(p)));\n        set<1>(p, round(get<1>(p)));\n    }\n};\n\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<double> point;\n    boost::geometry::model::polygon<point> poly;\n    boost::geometry::read_wkt(\"POLYGON((0 0,1.123 9.987,8.876 2.234,0 0),(3.345 4.456,7.654 8.765,9.123 5.432,3.345 4.456))\", poly);\n    boost::geometry::for_each_point(poly, round_coordinates<point>(0.1));\n    std::cout << \"Rounded: \" << boost::geometry::wkt(poly) << std::endl;\n    return 0;\n}\n\n//]\n\n\n//[for_each_point_output\n/*`\nOutput:\n[pre\n Rounded: POLYGON((0 0,1.1 10,8.9 2.2,0 0),(3.3 4.5,7.7 8.8,9.1 5.4,3.3 4.5))\n]\n*/\n//]\n", "meta": {"hexsha": "1380864134a0bc25f2bf509cdb55c77a7faeca9d", "size": 1765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/for_each_point.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/for_each_point.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/for_each_point.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2142857143, "max_line_length": 132, "alphanum_fraction": 0.671388102, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6448293181453756}}
{"text": "#pragma once\n\n#include <vector>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <cmath>\n#include \"SAMSON.hpp\"\n#include \"ADNConstants.hpp\"\n\n\nnamespace ublas = boost::numeric::ublas;\n\nnamespace ADNVectorMath {\n  using namespace ublas;\n\n  ublas::vector<double> CreateBoostVector(std::vector<double> vec);\n  std::vector<double> CreateStdVector(ublas::vector<double> vec);\n  ublas::matrix<double> CreateBoostMatrix(std::vector<std::vector<double>> vecovec);\n  ublas::vector<double> CalculateCM(ublas::matrix<double> positions);\n  ublas::vector<double> CalculateCM(ublas::matrix<double> weightedPositions, double totalMass);\n  ublas::vector<double> CrossProduct(ublas::vector<double> v, ublas::vector<double> w);\n  ublas::vector<double> DirectionVector(ublas::vector<double> p, ublas::vector<double> q);\n  double DegToRad(double degree);\n  ublas::matrix<double> MakeRotationMatrix(ublas::vector<double> dir, double angle);\n  ublas::matrix<double> SkewMatrix(ublas::vector<double> v);\n  ublas::vector<double> InitializeVector(size_t size);  // deprecated, use constructor\n  ublas::matrix<double> InitializeMatrix(size_t sz_r, size_t sz_c);  // deprecated, use constructor\n  ublas::matrix<double> InitializeMatrix(size_t sz);  // deprecated, use constructor\n  ublas::matrix<double> Translate(ublas::matrix<double> input, ublas::vector<double> t_vector);\n  ublas::matrix<double> Rotate(ublas::matrix<double> input, ublas::matrix<double> rot_matrix);  // deprecated, use ApplyTransformation\n  ublas::matrix<double> CenterSystem(ublas::matrix<double> input);\n  void AddRowToMatrix(ublas::matrix<double> &input, ublas::vector<double> r);\n  ublas::vector<double> CalculatePlane(ublas::matrix<double> mat);\n  ublas::matrix<double> FindOrthogonalSubspace(ublas::vector<double> z);\n  ublas::matrix<double> InvertMatrix(const ublas::matrix<double>& input);\n  double Determinant(ublas::matrix<double> mat);\n  bool IsNearlyZero(double n, double tol = 0.000000001);\n  double CalculateVectorNorm(ublas::vector<double> v);\n  /*!\n    * Applies the transformation given by t_mat to a set of points\n    * \\param the transformation matrix\n    * \\param a matrix holding coordinates of points\n    * \\return a matrix with the coordinates after the transformation\n  */\n  ublas::matrix<double> ApplyTransformation(ublas::matrix<double> t_mat, ublas::matrix<double> points);\n\n  ublas::vector<double> Spherical2Cartesian(ublas::vector<double> spher);\n\n  // SAMSON types operations\n  SBVector3 SBCrossProduct(SBVector3 v, SBVector3 w);\n  double SBInnerProduct(SBVector3 v, SBVector3 w);\n\n  //! Calculation of parameters of dna nanotubes\n  SBQuantity::length CalculateNanotubeRadius(int numDs);\n  int CalculateNanotubeDoubleStrands(SBQuantity::length radius);\n\n  //! Bezier curves\n  //! Calculates the length of a quadratic Bezier curve\n  SBQuantity::length LengthQuadraticBezier(SBPosition3 P0, SBPosition3 P1, SBPosition3 P2);\n  SBPosition3 QuadraticBezierPoint(SBPosition3 P0, SBPosition3 P1, SBPosition3 P2, double t);\n  SBVector3 DerivativeQuadraticBezier(SBPosition3 P0, SBPosition3 P1, SBPosition3 P2, double t);\n};", "meta": {"hexsha": "7fa34617d8363cc5a683edd715e93fd43f15abd0", "size": 3218, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AdenitaCoreSE/include/ADNVectorMath.hpp", "max_stars_repo_name": "edellano/Adenita-SAMSON-Edition-Win-", "max_stars_repo_head_hexsha": "6df8d21572ef40fe3fc49165dfaa1d4318352a69", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-07T20:48:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T05:49:59.000Z", "max_issues_repo_path": "AdenitaCoreSE/include/ADNVectorMath.hpp", "max_issues_repo_name": "edellano/Adenita-SAMSON-Edition-Linux", "max_issues_repo_head_hexsha": "a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-04-05T18:39:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T14:28:55.000Z", "max_forks_repo_path": "AdenitaCoreSE/include/ADNVectorMath.hpp", "max_forks_repo_name": "edellano/Adenita-SAMSON-Edition-Linux", "max_forks_repo_head_hexsha": "a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-13T12:58:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T13:52:00.000Z", "avg_line_length": 50.28125, "max_line_length": 134, "alphanum_fraction": 0.766314481, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.6447396006314169}}
{"text": "#include \"ssd_ros_tracking/ssd_ekf.h\"\n#include <Eigen/Dense>\n#include <pcl/point_types.h>\n\n// association param\n#define PRE_SIZE 5\n\n// dynamic detector param\n#define MIN_VELOCITY 0.3\n#define MAX_VELOCITY 2\n\nusing namespace std;\nusing namespace Eigen;\n\nMatrixXf EKF::move(MatrixXf x, MatrixXf u, float dt)\n{\n\t/* \u52d5\u4f5c\u4e88\u6e2c\n\t * x : \u72b6\u614b\n\t * u : \u5236\u5fa1\n\t * dt: \u524d\u30b9\u30c6\u30c3\u30d7\u3068\u306e\u6642\u9593\u5dee\n\t */\n\tMatrixXf A(3,1);\n\tMatrixXf I = MatrixXf::Identity(3,3);\n\tMatrixXf B(3,2);\n\n\tfloat theta = x.coeffRef(2,0) + u.coeffRef(1,0)*dt/2;\n\t\n\tB << dt*cos(theta),  0,\n\t\t dt*sin(theta),  0,\n\t\t             0, dt;\n\t\n\tA = I*x + B*u;\n\t\n\treturn A;\n}\n\nMatrixXf EKF::jacobF(MatrixXf x, MatrixXf u, float dt)\n{\n\t/* \u30e4\u30b3\u30d3\u884c\u5217\n\t * x : \u72b6\u614b\n\t * u : \u5236\u5fa1\n\t * dt: \u524d\u30b9\u30c6\u30c3\u30d7\u3068\u306e\u6642\u9593\u5dee\n\t */\n\tMatrixXf F(3,3);\n\tfloat b     = dt*u.coeffRef(0,0);\n\tfloat theta = x.coeffRef(2,0); \n\t\n\tF << 1, 0, -b*sin(theta),\n\t\t 0, 1,  b*cos(theta),\n\t\t 0, 0,             1;\n\n\treturn F;\n}\n\nMatrixXf EKF::jacobG(MatrixXf x, MatrixXf u, float dt)\n{\n\t/* \u30e4\u30b3\u30d3\u884c\u5217\n\t * x : \u72b6\u614b\n\t * u : \u5236\u5fa1\n\t * dt: \u524d\u30b9\u30c6\u30c3\u30d7\u3068\u306e\u6642\u9593\u5dee\n\t */\n\tMatrixXf G(3,3);\n\tfloat b     = u.coeffRef(0,0)*dt;\n\tfloat theta = u.coeffRef(1,0)*dt/2 + x.coeffRef(2,0);\n\n\tG << 1, 0, -b*sin(theta),\n\t\t 0, 1,  b*cos(theta),\n\t\t 0, 0,             1;\n\treturn G;\n}\n\nMatrixXf EKF::jacobV(MatrixXf x, MatrixXf u, float dt)\n{\n\t/* \u30e4\u30b3\u30d3\u884c\u5217\n\t * x : \u72b6\u614b\n\t * u : \u5236\u5fa1\n\t * dt: \u524d\u30b9\u30c6\u30c3\u30d7\u3068\u306e\u6642\u9593\u5dee\n\t */\n\tMatrixXf V(3,2);\n\tfloat theta = u.coeffRef(1,0)*dt/2 + x.coeffRef(2,0);\n\tfloat v     = u.coeffRef(0,0);\n\t\n\tV << dt*cos(theta), (-v*dt*dt)*sin(theta)/2,\n\t\t dt*sin(theta),  (v*dt*dt)*cos(theta)/2,\n\t\t             0,                      dt;\n\t\t \n\treturn V;\n}\n\nMatrixXf EKF::jacobM(MatrixXf u, double s_input[])\n{\n\t/* \u30e4\u30b3\u30d3\u884c\u5217\n\t * u : \u5236\u5fa1\n\t * s_input: \u5236\u5fa1\u7cfb\u306e\u8a08\u6e2c\u8aa4\u5dee\u30d1\u30e9\u30e1\u30fc\u30bf\n\t */\n\tMatrixXf M(2,2);\n\tfloat v  = u.coeffRef(0,0);\n\tfloat w  = u.coeffRef(1,0);\n\tfloat a1 = (float)s_input[0];\n\tfloat a2 = (float)s_input[1];\n\tfloat a3 = (float)s_input[2];\n\tfloat a4 = (float)s_input[3];\n\t\n\tM << a1*v*v + a2*w*w,               0,\n\t\t               0, a3*v*v + a4*w*w;\n\t\t \n\treturn M;\n}\n\nMatrixXf EKF::jacobH(MatrixXf x)\n{\n\t/* \u30e4\u30b3\u30d3\u884c\u5217\n\t * x : \u72b6\u614b\n\t */\n\tMatrixXf H(3,3);\n\n\tH<< 1, 0, 0,\n\t    0, 1, 0,\n\t    0, 0, 1;\n\t \n\t return H;\n}\n\nvoid initCluster( clusterInfo& cluster,\n\t\t\t\t  PointI& init_pt)\n{\n\t// float init_r      = 0.01; // \u89b3\u6e2c\u8aa4\u5dee\n\tfloat init_p      = 0.001;  //\u521d\u671f\u4f4d\u7f6e\u306e\u5206\u6563\u5024\n\tfloat init_theta = 0;\n\t// cluster.x << init_pt.x, init_pt.y, 0.0, 0.0;\n\tcluster.x << init_pt.x, init_pt.y, init_theta;\n\tcluster.P << init_p,    0.0,   0.0,\n\t\t \t\t    0.0, init_p,   0.0,\n\t\t \t\t    0.0,    0.0, init_p;\n\t// cluster.R << init_r,    0.0,\n\t// \t\t\t    0.0, init_r;\n\tcluster.pre_vel.x       = 0;\n\tcluster.pre_vel.y       = 0;\n\tcluster.u               = Eigen::VectorXf::Zero(2);\n\tcluster.track_num       = 1;\n\tcluster.confidence      = 1;\n\tcluster.width           = init_pt.normal_x;\n\tcluster.length          = init_pt.normal_y;\n\tcluster.height          = init_pt.normal_z;\n\tcluster.count           = 0;\n\tcluster.pre_position.resize(PRE_SIZE);\n\tcluster.pre_position[0] = init_pt;\n\tcluster.label = 0; // static: 0  dynamic: 1\n\tcluster.update_comp_flag = true;\n\tcluster.init_flag = true;\n\n\tcluster.velocity = 0;\n}\n\nvoid Prediction( clusterInfo& cluster,\n\t\t\t\t double dt,\n\t\t\t\t double s_input[])\n{\n\tEKF ekf;\n\t/* u   : (v, w)\u306e\u8ee2\u7f6e\u884c\u5217\u3000v:\u4e26\u9032\u901f\u5ea6, w:\u89d2\u901f\u5ea6\n\t * x   : (x, y, \u03b8)\u306e\u8ee2\u7f6e\u884c\u5217\n\t * dt\t   : \u524d\u30b9\u30c6\u30c3\u30d7\u304b\u3089\u306e\u7d4c\u904e\u6642\u9593\n\t * s_input : \u52d5\u4f5c\u30e2\u30c7\u30eb\u306e\u30ce\u30a4\u30ba\u30d1\u30e9\u30e1\u30fc\u30bf\n\t */\n\n\n\tMatrixXf Gt = MatrixXf::Zero(3,3);\n\tMatrixXf Vt = MatrixXf::Zero(3,2);\n\tMatrixXf Mt = MatrixXf::Zero(2,2);\n\t\n\n\t// Gt = ekf.jacobG(cluster.x, cluster.u, dt, pitch);\n\tGt = ekf.jacobF(cluster.x, cluster.u, dt);\n\tVt = ekf.jacobV(cluster.x, cluster.u, dt);\n\tMt = ekf.jacobM(cluster.u, s_input);\n\n\n\tcluster.x = ekf.move(cluster.x, cluster.u, dt);\n\tcluster.P = Gt*cluster.P*Gt.transpose() + Vt*Mt*Vt.transpose();\n\n\t// cluster.label = 1;\n}\n\nvoid MeasurementUpdate(\tclusterInfo& cluster,\n\t\t\t\t\t\tPointI& obj_centroid,\n\t\t\t\t\t\tdouble dt,\n\t\t\t\t\t\tdouble s_measurement[])\n{\n\t/* x\t: \u72b6\u614b(x, y, yaw)\u306e\u8ee2\u7f6e\u884c\u5217\n\t * u\t: \u5236\u5fa1(v, w)\u306e\u8ee2\u7f6e\u884c\u5217\n\t * s_measurement: \u89b3\u6e2c\u30ce\u30a4\u30ba\n\t * sigma: \u63a8\u5b9a\u8aa4\u5dee\n\t */\n\n\tEKF ekf;\n\n\n\tMatrixXf Z = MatrixXf::Zero(3,1);\t// \u89b3\u6e2c (x,y,\u03b8)\n\tMatrixXf Q = MatrixXf::Zero(3,3);\n\tMatrixXf H = MatrixXf::Zero(3,3);\n\tMatrixXf y = MatrixXf::Zero(3,1);\n\tMatrixXf S = MatrixXf::Zero(3,3);\n\tMatrixXf K = MatrixXf::Zero(3,3);\n\tMatrixXf I = MatrixXf::Identity(3,3);\n\n\tZ.coeffRef(0,0) = obj_centroid.x;\n\tZ.coeffRef(1,0) = obj_centroid.y;\n\tZ.coeffRef(2,0) = atan2((obj_centroid.y-cluster.x[1]), (obj_centroid.x-cluster.x[0]));\n\n\n\t// cluster.u[0] = sqrt(pow((obj_centroid.y-cluster.x[1]), 2) + pow((obj_centroid.x-cluster.x[0]), 2))/dt;\n\tcluster.u[0] = sqrt(pow((obj_centroid.y-cluster.x[1]), 2) + pow((obj_centroid.x-cluster.x[0]), 2))/dt;\n\n\tif(cluster.init_flag){\n\t// cluster.u[1] = atan2((obj_centroid.y-cluster.x[1]), (obj_centroid.x-cluster.x[0]))/dt;\n\tcluster.u[1] = 0;\n\tcluster.init_flag = false;\n\t}\n\n\t// else cluster.u[1] = (atan2((obj_centroid.y-cluster.x[1]), (obj_centroid.x-cluster.x[0])) - cluster.x[2])/dt;\n\telse cluster.u[1] = (Z.coeffRef(2,0) - cluster.x[2])/dt;\n\t\n\tQ.coeffRef(0,0) = (float)s_measurement[0];\n\tQ.coeffRef(1,1) = (float)s_measurement[1];\n\tQ.coeffRef(2,2) = (float)s_measurement[2];\n\n\tH = ekf.jacobH(cluster.x);\n\ty = Z - H*cluster.x;\n\tS = H*cluster.P*H.transpose() + Q;\n\tK = cluster.P*H.transpose()*S.inverse();\n\n\tcluster.x = cluster.x + K*y;\n\tcluster.P = (I - K*H)*cluster.P;\n\n\n\t// \u4eca\u307e\u3067\u5ea7\u6a19\u3092PRE_SIZE\u306e\u6570\u3060\u3051\u683c\u7d0d\n\tfor (int i=0; i<(PRE_SIZE-1); i++) cluster.pre_position[i+1] = cluster.pre_position[i];\n\tcluster.pre_position[0].x = cluster.x(0);\n\tcluster.pre_position[0].y = cluster.x(1);\n\tcluster.pre_position[0].z = cluster.x(2);\n\n\tif(cluster.pre_position[PRE_SIZE-1].x != 0.0){\n\t\tcluster.velocity = sqrt(pow((cluster.pre_position[0].x-cluster.pre_position[PRE_SIZE-1].x), 2.0) + pow((cluster.pre_position[0].y-cluster.pre_position[PRE_SIZE-1].y), 2.0));\n\t}\n\n\tif(cluster.velocity > 0.1 && cluster.velocity < 1) cluster.label = 1;\n\n\t// cout<<\"pre_position = \"<<cluster.pre_position.size()<<endl;\n\t\t// for (int j=0; j<cluster.pre_position.size(); j++){\n\t\t// \t// cout<<\"label = \"<<clusters[i].label<<endl;\n        //\n\t\t\t// if(cluster.confidence > 0 && cluster.label == 1){ // label 0:static 1:dynamic\n\t\t// \t\tcout<<\" confidence = \"<<cluster.confidence<<\" pre_pos[\"<<j<<\"] x = \"<<cluster.pre_position[j].x<<\" y = \"<<cluster.pre_position[j].y<<endl;\n\t\t// \t}\n\t\t// }\n}\n", "meta": {"hexsha": "b149ab9a31a991d26fc1ec37fc8432de3210750b", "size": 6230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ssd_ros_tracking/src/ssd_ekf.cpp", "max_stars_repo_name": "Sadaku1993/ssd_ros", "max_stars_repo_head_hexsha": "88e280678e6a6b1814ed811bee7d0eaaafd97b56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ssd_ros_tracking/src/ssd_ekf.cpp", "max_issues_repo_name": "Sadaku1993/ssd_ros", "max_issues_repo_head_hexsha": "88e280678e6a6b1814ed811bee7d0eaaafd97b56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ssd_ros_tracking/src/ssd_ekf.cpp", "max_forks_repo_name": "Sadaku1993/ssd_ros", "max_forks_repo_head_hexsha": "88e280678e6a6b1814ed811bee7d0eaaafd97b56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-24T16:40:17.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-24T16:40:17.000Z", "avg_line_length": 24.2412451362, "max_line_length": 175, "alphanum_fraction": 0.5974317817, "num_tokens": 2498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766225, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.6447330526387889}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Boost Graph Library along with the software; see the file LICENSE.\r\n// If not, contact Office of Research, Indiana University,\r\n// Bloomington, IN 47405.\r\n//\r\n// Permission to modify the code and to distribute the code is\r\n// granted, provided the text of this NOTICE is retained, a notice if\r\n// the code was modified is included with the above COPYRIGHT NOTICE\r\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\r\n// LICENSE file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n#include <boost/config.hpp>\r\n#include <vector>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\r\n\r\nusing namespace boost;\r\n\r\ntemplate < typename Graph, typename ParentMap > \r\nstruct edge_writer\r\n{\r\n  edge_writer(const Graph & g, const ParentMap & p)\r\n  : m_g(g), m_parent(p)\r\n  {\r\n  }\r\n\r\n  template < typename Edge >\r\n    void operator() (std::ostream & out, const Edge & e) const\r\n  {\r\n    out << \"[label=\\\"\" << get(edge_weight, m_g, e) << \"\\\"\";\r\n    typename graph_traits < Graph >::vertex_descriptor\r\n      u = source(e, m_g), v = target(e, m_g);\r\n    if (m_parent[v] == u)\r\n        out << \", color=\\\"black\\\"\";\r\n    else\r\n        out << \", color=\\\"grey\\\"\";\r\n      out << \"]\";\r\n  }\r\n  const Graph & m_g;\r\n  ParentMap m_parent;\r\n};\r\ntemplate < typename Graph, typename Parent >\r\nedge_writer < Graph, Parent >\r\nmake_edge_writer(const Graph & g, const Parent & p)\r\n{\r\n  return edge_writer < Graph, Parent > (g, p);\r\n}\r\n\r\nint\r\nmain()\r\n{\r\n  enum { u, v, x, y, z, N };\r\n  char name[] = { 'u', 'v', 'x', 'y', 'z' };\r\n  typedef std::pair < int, int >E;\r\n  const int n_edges = 10;\r\n  E edge_array[] = { E(u, y), E(u, x), E(u, v), E(v, u),\r\n      E(x, y), E(x, v), E(y, v), E(y, z), E(z, u), E(z,x) };\r\n  int weight[n_edges] = { -4, 8, 5, -2, 9, -3, 7, 2, 6, 7 };\r\n\r\n  typedef adjacency_list < vecS, vecS, directedS,\r\n    no_property, property < edge_weight_t, int > > Graph;\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  // VC++ can't handle the iterator constructor\r\n  Graph g(N);\r\n  for (std::size_t j = 0; j < n_edges; ++j)\r\n    add_edge(edge_array[j].first, edge_array[j].second, g);\r\n#else\r\n  Graph g(edge_array, edge_array + n_edges, N);\r\n#endif\r\n  graph_traits < Graph >::edge_iterator ei, ei_end;\r\n  property_map<Graph, edge_weight_t>::type weight_pmap = get(edge_weight, g);\r\n  int i = 0;\r\n  for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei, ++i)\r\n    weight_pmap[*ei] = weight[i];\r\n\r\n  std::vector<int> distance(N, std::numeric_limits < short >::max());\r\n  std::vector<std::size_t> parent(N);\r\n  for (i = 0; i < N; ++i)\r\n    parent[i] = i;\r\n  distance[z] = 0;\r\n\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  bool r = bellman_ford_shortest_paths\r\n    (g, int(N), weight_pmap, &parent[0], &distance[0], \r\n     closed_plus<int>(), std::less<int>(), default_bellman_visitor());\r\n#else\r\n  bool r = bellman_ford_shortest_paths\r\n    (g, int (N), weight_map(weight_pmap).distance_map(&distance[0]).\r\n     predecessor_map(&parent[0]));\r\n#endif\r\n\r\n  if (r)\r\n    for (i = 0; i < N; ++i)\r\n      std::cout << name[i] << \": \" << std::setw(3) << distance[i]\r\n        << \" \" << name[parent[i]] << std::endl;\r\n  else\r\n    std::cout << \"negative cycle\" << std::endl;\r\n\r\n  std::ofstream dot_file(\"figs/bellman-eg.dot\");\r\n  dot_file << \"digraph D {\\n\"\r\n    << \"  rankdir=LR\\n\"\r\n    << \"  size=\\\"5,3\\\"\\n\"\r\n    << \"  ratio=\\\"fill\\\"\\n\"\r\n    << \"  edge[style=\\\"bold\\\"]\\n\" << \"  node[shape=\\\"circle\\\"]\\n\";\r\n\r\n  {\r\n    for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\r\n      graph_traits < Graph >::edge_descriptor e = *ei;\r\n      graph_traits < Graph >::vertex_descriptor\r\n        u = source(e, g), v = target(e, g);\r\n      // VC++ doesn't like the 3-argument get function, so here\r\n      // we workaround by using 2-nested get()'s.\r\n      dot_file << name[u] << \" -> \" << name[v]\r\n        << \"[label=\\\"\" << get(get(edge_weight, g), e) << \"\\\"\";\r\n      if (parent[v] == u)\r\n        dot_file << \", color=\\\"black\\\"\";\r\n      else\r\n        dot_file << \", color=\\\"grey\\\"\";\r\n      dot_file << \"]\";\r\n    }\r\n  }\r\n  dot_file << \"}\";\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "ddc450812bd70af2a8e29359bfec3aaf7b70782b", "size": 4873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/bellman-example.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/bellman-example.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/graph/example/bellman-example.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8071428571, "max_line_length": 78, "alphanum_fraction": 0.5836240509, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.6446899080594065}}
{"text": "\r\n#include <NTL/ZZ_pEXFactoring.h>\r\n#include <NTL/FacVec.h>\r\n#include <NTL/fileio.h>\r\n#include <NTL/new.h>\r\n\r\n\r\nNTL_START_IMPL\r\n\r\n\r\n\r\nstatic\r\nvoid IterPower(ZZ_pE& c, const ZZ_pE& a, long n)\r\n{\r\n   ZZ_pE res;\r\n\r\n   long i;\r\n\r\n   res = a;\r\n\r\n   for (i = 0; i < n; i++)\r\n      power(res, res, ZZ_p::modulus());\r\n\r\n   c = res;\r\n}\r\n   \r\n\r\n\r\nvoid SquareFreeDecomp(vec_pair_ZZ_pEX_long& u, const ZZ_pEX& ff)\r\n{\r\n   ZZ_pEX f = ff;\r\n\r\n   if (!IsOne(LeadCoeff(f)))\r\n      LogicError(\"SquareFreeDecomp: bad args\");\r\n\r\n   ZZ_pEX r, t, v, tmp1;\r\n   long m, j, finished, done;\r\n\r\n   u.SetLength(0);\r\n\r\n   if (deg(f) == 0)\r\n      return;\r\n\r\n   m = 1;\r\n   finished = 0;\r\n\r\n   do {\r\n      j = 1;\r\n      diff(tmp1, f);\r\n      GCD(r, f, tmp1);\r\n      div(t, f, r);\r\n\r\n      if (deg(t) > 0) {\r\n         done = 0;\r\n         do {\r\n            GCD(v, r, t);\r\n            div(tmp1, t, v);\r\n            if (deg(tmp1) > 0) append(u, cons(tmp1, j*m));\r\n            if (deg(v) > 0) {\r\n               div(r, r, v);\r\n               t = v;\r\n               j++;\r\n            }\r\n            else\r\n               done = 1;\r\n         } while (!done);\r\n         if (deg(r) == 0) finished = 1;\r\n      }\r\n\r\n      if (!finished) {\r\n         /* r is a p-th power */\r\n\r\n         long k, d;\r\n         long p = to_long(ZZ_p::modulus()); \r\n\r\n         d = deg(r)/p;\r\n         f.rep.SetLength(d+1);\r\n         for (k = 0; k <= d; k++) \r\n            IterPower(f.rep[k], r.rep[k*p], ZZ_pE::degree()-1);\r\n         m = m*p;\r\n      }\r\n   } while (!finished);\r\n}\r\n         \r\n\r\n\r\nstatic\r\nvoid AbsTraceMap(ZZ_pEX& h, const ZZ_pEX& a, const ZZ_pEXModulus& F)\r\n{\r\n   ZZ_pEX res, tmp;\r\n\r\n   long k = NumBits(ZZ_pE::cardinality())-1;\r\n\r\n   res = a;\r\n   tmp = a;\r\n\r\n   long i;\r\n   for (i = 0; i < k-1; i++) {\r\n      SqrMod(tmp, tmp, F);\r\n      add(res, res, tmp);\r\n   }\r\n\r\n   h = res;\r\n}\r\n\r\nvoid FrobeniusMap(ZZ_pEX& h, const ZZ_pEXModulus& F)\r\n{\r\n   PowerXMod(h, ZZ_pE::cardinality(), F);\r\n}\r\n\r\n\r\nstatic\r\nvoid RecFindRoots(vec_ZZ_pE& x, const ZZ_pEX& f)\r\n{\r\n   if (deg(f) == 0) return;\r\n\r\n   if (deg(f) == 1) {\r\n      long k = x.length();\r\n      x.SetLength(k+1);\r\n      negate(x[k], ConstTerm(f));\r\n      return;\r\n   }\r\n      \r\n   ZZ_pEX h;\r\n\r\n   ZZ_pEX r;\r\n\r\n   \r\n   {\r\n      ZZ_pEXModulus F;\r\n      build(F, f);\r\n\r\n      do {\r\n         random(r, deg(F));\r\n         if (IsOdd(ZZ_pE::cardinality())) {\r\n            PowerMod(h, r, RightShift(ZZ_pE::cardinality(), 1), F);\r\n            sub(h, h, 1);\r\n         }\r\n         else {\r\n            AbsTraceMap(h, r, F);\r\n         }\r\n         GCD(h, h, f);\r\n      } while (deg(h) <= 0 || deg(h) == deg(f));\r\n   }\r\n\r\n   RecFindRoots(x, h);\r\n   div(h, f, h); \r\n   RecFindRoots(x, h);\r\n}\r\n\r\nvoid FindRoots(vec_ZZ_pE& x, const ZZ_pEX& ff)\r\n{\r\n   ZZ_pEX f = ff;\r\n\r\n   if (!IsOne(LeadCoeff(f)))\r\n      LogicError(\"FindRoots: bad args\");\r\n\r\n   x.SetMaxLength(deg(f));\r\n   x.SetLength(0);\r\n   RecFindRoots(x, f);\r\n}\r\n\r\nvoid split(ZZ_pEX& f1, ZZ_pEX& g1, ZZ_pEX& f2, ZZ_pEX& g2,\r\n           const ZZ_pEX& f, const ZZ_pEX& g, \r\n           const vec_ZZ_pE& roots, long lo, long mid)\r\n{\r\n   long r = mid-lo+1;\r\n\r\n   ZZ_pEXModulus F;\r\n   build(F, f);\r\n\r\n   vec_ZZ_pE lroots(INIT_SIZE, r);\r\n   long i;\r\n\r\n   for (i = 0; i < r; i++)\r\n      lroots[i] = roots[lo+i];\r\n\r\n\r\n   ZZ_pEX h, a, d;\r\n   BuildFromRoots(h, lroots);\r\n   CompMod(a, h, g, F);\r\n\r\n\r\n   GCD(f1, a, f);\r\n   \r\n   div(f2, f, f1);\r\n\r\n   rem(g1, g, f1);\r\n   rem(g2, g, f2);\r\n}\r\n\r\nvoid RecFindFactors(vec_ZZ_pEX& factors, const ZZ_pEX& f, const ZZ_pEX& g,\r\n                    const vec_ZZ_pE& roots, long lo, long hi)\r\n{\r\n   long r = hi-lo+1;\r\n\r\n   if (r == 0) return;\r\n\r\n   if (r == 1) {\r\n      append(factors, f);\r\n      return;\r\n   }\r\n\r\n   ZZ_pEX f1, g1, f2, g2;\r\n\r\n   long mid = (lo+hi)/2;\r\n\r\n   split(f1, g1, f2, g2, f, g, roots, lo, mid);\r\n\r\n   RecFindFactors(factors, f1, g1, roots, lo, mid);\r\n   RecFindFactors(factors, f2, g2, roots, mid+1, hi);\r\n}\r\n\r\n\r\nvoid FindFactors(vec_ZZ_pEX& factors, const ZZ_pEX& f, const ZZ_pEX& g,\r\n                 const vec_ZZ_pE& roots)\r\n{\r\n   long r = roots.length();\r\n\r\n   factors.SetMaxLength(r);\r\n   factors.SetLength(0);\r\n\r\n   RecFindFactors(factors, f, g, roots, 0, r-1);\r\n}\r\n\r\nvoid IterFindFactors(vec_ZZ_pEX& factors, const ZZ_pEX& f,\r\n                     const ZZ_pEX& g, const vec_ZZ_pE& roots)\r\n{\r\n   long r = roots.length();\r\n   long i;\r\n   ZZ_pEX h;\r\n\r\n   factors.SetLength(r);\r\n\r\n   for (i = 0; i < r; i++) {\r\n      sub(h, g, roots[i]);\r\n      GCD(factors[i], f, h);\r\n   }\r\n}\r\n\r\n\r\nvoid TraceMap(ZZ_pEX& w, const ZZ_pEX& a, long d, const ZZ_pEXModulus& F, \r\n              const ZZ_pEX& b)\r\n\r\n{\r\n   if (d < 0) LogicError(\"TraceMap: bad args\");\r\n\r\n   ZZ_pEX y, z, t;\r\n\r\n   z = b;\r\n   y = a;\r\n   clear(w);\r\n\r\n   while (d) {\r\n      if (d == 1) {\r\n         if (IsZero(w)) \r\n            w = y;\r\n         else {\r\n            CompMod(w, w, z, F);\r\n            add(w, w, y);\r\n         }\r\n      }\r\n      else if ((d & 1) == 0) {\r\n         Comp2Mod(z, t, z, y, z, F);\r\n         add(y, t, y);\r\n      }\r\n      else if (IsZero(w)) {\r\n         w = y;\r\n         Comp2Mod(z, t, z, y, z, F);\r\n         add(y, t, y);\r\n      }\r\n      else {\r\n         Comp3Mod(z, t, w, z, y, w, z, F);\r\n         add(w, w, y);\r\n         add(y, t, y);\r\n      }\r\n\r\n      d = d >> 1;\r\n   }\r\n}\r\n\r\n\r\nvoid PowerCompose(ZZ_pEX& y, const ZZ_pEX& h, long q, const ZZ_pEXModulus& F)\r\n{\r\n   if (q < 0) LogicError(\"PowerCompose: bad args\");\r\n\r\n   ZZ_pEX z(INIT_SIZE, F.n);\r\n   long sw;\r\n\r\n   z = h;\r\n   SetX(y);\r\n\r\n   while (q) {\r\n      sw = 0;\r\n\r\n      if (q > 1) sw = 2;\r\n      if (q & 1) {\r\n         if (IsX(y))\r\n            y = z;\r\n         else\r\n            sw = sw | 1;\r\n      }\r\n\r\n      switch (sw) {\r\n      case 0:\r\n         break;\r\n\r\n      case 1:\r\n         CompMod(y, y, z, F);\r\n         break;\r\n\r\n      case 2:\r\n         CompMod(z, z, z, F);\r\n         break;\r\n\r\n      case 3:\r\n         Comp2Mod(y, z, y, z, z, F);\r\n         break;\r\n      }\r\n\r\n      q = q >> 1;\r\n   }\r\n}\r\n\r\n\r\nlong ProbIrredTest(const ZZ_pEX& f, long iter)\r\n{\r\n   long n = deg(f);\r\n\r\n   if (n <= 0) return 0;\r\n   if (n == 1) return 1;\r\n\r\n   ZZ_pEXModulus F;\r\n\r\n   build(F, f);\r\n\r\n   ZZ_pEX b, r, s;\r\n\r\n   FrobeniusMap(b, F);\r\n\r\n   long all_zero = 1;\r\n\r\n   long i;\r\n\r\n   for (i = 0; i < iter; i++) {\r\n      random(r, n);\r\n      TraceMap(s, r, n, F, b);\r\n\r\n      all_zero = all_zero && IsZero(s);\r\n\r\n      if (deg(s) > 0) return 0;\r\n   }\r\n\r\n   if (!all_zero || (n & 1)) return 1;\r\n\r\n   PowerCompose(s, b, n/2, F);\r\n   return !IsX(s);\r\n}\r\n\r\n\r\nNTL_THREAD_LOCAL long ZZ_pEX_BlockingFactor = 10;\r\n\r\n\r\n\r\n\r\nvoid RootEDF(vec_ZZ_pEX& factors, const ZZ_pEX& f, long verbose)\r\n{\r\n   vec_ZZ_pE roots;\r\n   double t;\r\n\r\n   if (verbose) { cerr << \"finding roots...\"; t = GetTime(); }\r\n   FindRoots(roots, f);\r\n   if (verbose) { cerr << (GetTime()-t) << \"\\n\"; }\r\n\r\n   long r = roots.length();\r\n   factors.SetLength(r);\r\n   for (long j = 0; j < r; j++) {\r\n      SetX(factors[j]);\r\n      sub(factors[j], factors[j], roots[j]);\r\n   }\r\n}\r\n\r\nvoid EDFSplit(vec_ZZ_pEX& v, const ZZ_pEX& f, const ZZ_pEX& b, long d)\r\n{\r\n   ZZ_pEX a, g, h;\r\n   ZZ_pEXModulus F;\r\n   vec_ZZ_pE roots;\r\n   \r\n   build(F, f);\r\n   long n = F.n;\r\n   long r = n/d;\r\n   random(a, n);\r\n   TraceMap(g, a, d, F, b);\r\n   MinPolyMod(h, g, F, r);\r\n   FindRoots(roots, h);\r\n   FindFactors(v, f, g, roots);\r\n}\r\n\r\nvoid RecEDF(vec_ZZ_pEX& factors, const ZZ_pEX& f, const ZZ_pEX& b, long d,\r\n            long verbose)\r\n{\r\n   vec_ZZ_pEX v;\r\n   long i;\r\n   ZZ_pEX bb;\r\n\r\n   if (verbose) cerr << \"+\";\r\n\r\n   EDFSplit(v, f, b, d);\r\n   for (i = 0; i < v.length(); i++) {\r\n      if (deg(v[i]) == d) {\r\n         append(factors, v[i]);\r\n      }\r\n      else {\r\n         ZZ_pEX bb;\r\n         rem(bb, b, v[i]);\r\n         RecEDF(factors, v[i], bb, d, verbose);\r\n      }\r\n   }\r\n}\r\n         \r\n\r\nvoid EDF(vec_ZZ_pEX& factors, const ZZ_pEX& ff, const ZZ_pEX& bb,\r\n         long d, long verbose)\r\n\r\n{\r\n   ZZ_pEX f = ff;\r\n   ZZ_pEX b = bb;\r\n\r\n   if (!IsOne(LeadCoeff(f)))\r\n      LogicError(\"EDF: bad args\");\r\n\r\n   long n = deg(f);\r\n   long r = n/d;\r\n\r\n   if (r == 0) {\r\n      factors.SetLength(0);\r\n      return;\r\n   }\r\n\r\n   if (r == 1) {\r\n      factors.SetLength(1);\r\n      factors[0] = f;\r\n      return;\r\n   }\r\n\r\n   if (d == 1) {\r\n      RootEDF(factors, f, verbose);\r\n      return;\r\n   }\r\n\r\n   \r\n   double t;\r\n   if (verbose) { \r\n      cerr << \"computing EDF(\" << d << \",\" << r << \")...\"; \r\n      t = GetTime(); \r\n   }\r\n\r\n   factors.SetLength(0);\r\n\r\n   RecEDF(factors, f, b, d, verbose);\r\n\r\n   if (verbose) cerr << (GetTime()-t) << \"\\n\";\r\n}\r\n\r\n\r\nvoid SFCanZass(vec_ZZ_pEX& factors, const ZZ_pEX& ff, long verbose)\r\n{\r\n   ZZ_pEX f = ff;\r\n\r\n   if (!IsOne(LeadCoeff(f)))\r\n      LogicError(\"SFCanZass: bad args\");\r\n\r\n   if (deg(f) == 0) {\r\n      factors.SetLength(0);\r\n      return;\r\n   }\r\n\r\n   if (deg(f) == 1) {\r\n      factors.SetLength(1);\r\n      factors[0] = f;\r\n      return;\r\n   }\r\n\r\n   factors.SetLength(0);\r\n\r\n   double t;\r\n\r\n   \r\n   ZZ_pEXModulus F;\r\n   build(F, f);\r\n\r\n   ZZ_pEX h;\r\n\r\n   if (verbose) { cerr << \"computing X^p...\"; t = GetTime(); }\r\n   FrobeniusMap(h, F);\r\n   if (verbose) { cerr << (GetTime()-t) << \"\\n\"; }\r\n\r\n   vec_pair_ZZ_pEX_long u;\r\n   if (verbose) { cerr << \"computing DDF...\"; t = GetTime(); }\r\n   NewDDF(u, f, h, verbose);\r\n   if (verbose) { \r\n      t = GetTime()-t; \r\n      cerr << \"DDF time: \" << t << \"\\n\";\r\n   }\r\n\r\n   ZZ_pEX hh;\r\n   vec_ZZ_pEX v;\r\n\r\n   long i;\r\n   for (i = 0; i < u.length(); i++) {\r\n      const ZZ_pEX& g = u[i].a;\r\n      long d = u[i].b;\r\n      long r = deg(g)/d;\r\n\r\n      if (r == 1) {\r\n         // g is already irreducible\r\n\r\n         append(factors, g);\r\n      }\r\n      else {\r\n         // must perform EDF\r\n\r\n         if (d == 1) {\r\n            // root finding\r\n            RootEDF(v, g, verbose);\r\n            append(factors, v);\r\n         }\r\n         else {\r\n            // general case\r\n            rem(hh, h, g);\r\n            EDF(v, g, hh, d, verbose);\r\n            append(factors, v);\r\n         }\r\n      }\r\n   }\r\n}\r\n   \r\nvoid CanZass(vec_pair_ZZ_pEX_long& factors, const ZZ_pEX& f, long verbose)\r\n{\r\n   if (!IsOne(LeadCoeff(f)))\r\n      LogicError(\"CanZass: bad args\");\r\n\r\n   double t;\r\n   vec_pair_ZZ_pEX_long sfd;\r\n   vec_ZZ_pEX x;\r\n\r\n   \r\n   if (verbose) { cerr << \"square-free decomposition...\"; t = GetTime(); }\r\n   SquareFreeDecomp(sfd, f);\r\n   if (verbose) cerr << (GetTime()-t) << \"\\n\";\r\n\r\n   factors.SetLength(0);\r\n\r\n   long i, j;\r\n\r\n   for (i = 0; i < sfd.length(); i++) {\r\n      if (verbose) {\r\n         cerr << \"factoring multiplicity \" << sfd[i].b \r\n              << \", deg = \" << deg(sfd[i].a) << \"\\n\";\r\n      }\r\n\r\n      SFCanZass(x, sfd[i].a, verbose);\r\n\r\n      for (j = 0; j < x.length(); j++)\r\n         append(factors, cons(x[j], sfd[i].b));\r\n   }\r\n}\r\n\r\nvoid mul(ZZ_pEX& f, const vec_pair_ZZ_pEX_long& v)\r\n{\r\n   long i, j, n;\r\n\r\n   n = 0;\r\n   for (i = 0; i < v.length(); i++)\r\n      n += v[i].b*deg(v[i].a);\r\n\r\n   ZZ_pEX g(INIT_SIZE, n+1);\r\n\r\n   set(g);\r\n   for (i = 0; i < v.length(); i++)\r\n      for (j = 0; j < v[i].b; j++) {\r\n         mul(g, g, v[i].a);\r\n      }\r\n\r\n   f = g;\r\n}\r\n\r\n\r\nlong BaseCase(const ZZ_pEX& h, long q, long a, const ZZ_pEXModulus& F)\r\n{\r\n   long b, e;\r\n   ZZ_pEX lh(INIT_SIZE, F.n);\r\n\r\n   lh = h;\r\n   b = 1;\r\n   e = 0;\r\n   while (e < a-1 && !IsX(lh)) {\r\n      e++;\r\n      b *= q;\r\n      PowerCompose(lh, lh, q, F);\r\n   }\r\n\r\n   if (!IsX(lh)) b *= q;\r\n\r\n   return b;\r\n}\r\n\r\n\r\n\r\nvoid TandemPowerCompose(ZZ_pEX& y1, ZZ_pEX& y2, const ZZ_pEX& h, \r\n                        long q1, long q2, const ZZ_pEXModulus& F)\r\n{\r\n   ZZ_pEX z(INIT_SIZE, F.n);\r\n   long sw;\r\n\r\n   z = h;\r\n   SetX(y1);\r\n   SetX(y2);\r\n\r\n   while (q1 || q2) {\r\n      sw = 0;\r\n\r\n      if (q1 > 1 || q2 > 1) sw = 4;\r\n\r\n      if (q1 & 1) {\r\n         if (IsX(y1))\r\n            y1 = z;\r\n         else\r\n            sw = sw | 2;\r\n      }\r\n\r\n      if (q2 & 1) {\r\n         if (IsX(y2))\r\n            y2 = z;\r\n         else\r\n            sw = sw | 1;\r\n      }\r\n\r\n      switch (sw) {\r\n      case 0:\r\n         break;\r\n\r\n      case 1:\r\n         CompMod(y2, y2, z, F);\r\n         break;\r\n\r\n      case 2:\r\n         CompMod(y1, y1, z, F);\r\n         break;\r\n\r\n      case 3:\r\n         Comp2Mod(y1, y2, y1, y2, z, F);\r\n         break;\r\n\r\n      case 4:\r\n         CompMod(z, z, z, F);\r\n         break;\r\n\r\n      case 5:\r\n         Comp2Mod(z, y2, z, y2, z, F);\r\n         break;\r\n\r\n      case 6:\r\n         Comp2Mod(z, y1, z, y1, z, F);\r\n         break;\r\n\r\n      case 7:\r\n         Comp3Mod(z, y1, y2, z, y1, y2, z, F);\r\n         break;\r\n      }\r\n\r\n      q1 = q1 >> 1;\r\n      q2 = q2 >> 1;\r\n   }\r\n}\r\n\r\n\r\nlong RecComputeDegree(long u, const ZZ_pEX& h, const ZZ_pEXModulus& F,\r\n                      FacVec& fvec)\r\n{\r\n   if (IsX(h)) return 1;\r\n\r\n   if (fvec[u].link == -1) return BaseCase(h, fvec[u].q, fvec[u].a, F);\r\n\r\n   ZZ_pEX h1, h2;\r\n   long q1, q2, r1, r2;\r\n\r\n   q1 = fvec[fvec[u].link].val; \r\n   q2 = fvec[fvec[u].link+1].val;\r\n\r\n   TandemPowerCompose(h1, h2, h, q1, q2, F);\r\n   r1 = RecComputeDegree(fvec[u].link, h2, F, fvec);\r\n   r2 = RecComputeDegree(fvec[u].link+1, h1, F, fvec);\r\n   return r1*r2;\r\n}\r\n\r\n   \r\n\r\n\r\nlong RecComputeDegree(const ZZ_pEX& h, const ZZ_pEXModulus& F)\r\n   // f = F.f is assumed to be an \"equal degree\" polynomial\r\n   // h = X^p mod f\r\n   // the common degree of the irreducible factors of f is computed\r\n{\r\n   if (F.n == 1 || IsX(h)) \r\n      return 1;\r\n\r\n   FacVec fvec;\r\n\r\n   FactorInt(fvec, F.n);\r\n\r\n   return RecComputeDegree(fvec.length()-1, h, F, fvec);\r\n}\r\n\r\n\r\nvoid FindRoot(ZZ_pE& root, const ZZ_pEX& ff)\r\n// finds a root of ff.\r\n// assumes that ff is monic and splits into distinct linear factors\r\n\r\n{\r\n   ZZ_pEXModulus F;\r\n   ZZ_pEX h, h1, f;\r\n   ZZ_pEX r;\r\n\r\n   f = ff;\r\n   \r\n   if (!IsOne(LeadCoeff(f)))\r\n      LogicError(\"FindRoot: bad args\");\r\n\r\n   if (deg(f) == 0)\r\n      LogicError(\"FindRoot: bad args\");\r\n\r\n\r\n   while (deg(f) > 1) {\r\n      build(F, f);\r\n      random(r, deg(F));\r\n      if (IsOdd(ZZ_pE::cardinality())) {\r\n         PowerMod(h, r, RightShift(ZZ_pE::cardinality(), 1), F);\r\n         sub(h, h, 1);\r\n      }\r\n      else {\r\n         AbsTraceMap(h, r, F);\r\n      }\r\n      GCD(h, h, f);\r\n      if (deg(h) > 0 && deg(h) < deg(f)) {\r\n         if (deg(h) > deg(f)/2)\r\n            div(f, f, h);\r\n         else\r\n            f = h;\r\n      }\r\n   }\r\n \r\n   negate(root, ConstTerm(f));\r\n}\r\n\r\n\r\nstatic\r\nlong power(long a, long e)\r\n{\r\n   long i, res;\r\n\r\n   res = 1;\r\n   for (i = 1; i <= e; i++)\r\n      res = res * a;\r\n\r\n   return res;\r\n}\r\n\r\n\r\nstatic\r\nlong IrredBaseCase(const ZZ_pEX& h, long q, long a, const ZZ_pEXModulus& F)\r\n{\r\n   long e;\r\n   ZZ_pEX X, s, d;\r\n\r\n   e = power(q, a-1);\r\n   PowerCompose(s, h, e, F);\r\n   SetX(X);\r\n   sub(s, s, X);\r\n   GCD(d, F.f, s);\r\n   return IsOne(d);\r\n}\r\n\r\n\r\nstatic\r\nlong RecIrredTest(long u, const ZZ_pEX& h, const ZZ_pEXModulus& F,\r\n                 const FacVec& fvec)\r\n{\r\n   long  q1, q2;\r\n   ZZ_pEX h1, h2;\r\n\r\n   if (IsX(h)) return 0;\r\n\r\n   if (fvec[u].link == -1) {\r\n      return IrredBaseCase(h, fvec[u].q, fvec[u].a, F);\r\n   }\r\n\r\n\r\n   q1 = fvec[fvec[u].link].val; \r\n   q2 = fvec[fvec[u].link+1].val;\r\n\r\n   TandemPowerCompose(h1, h2, h, q1, q2, F);\r\n   return RecIrredTest(fvec[u].link, h2, F, fvec) \r\n          && RecIrredTest(fvec[u].link+1, h1, F, fvec);\r\n}\r\n\r\nlong DetIrredTest(const ZZ_pEX& f)\r\n{\r\n   if (deg(f) <= 0) return 0;\r\n   if (deg(f) == 1) return 1;\r\n\r\n   ZZ_pEXModulus F;\r\n\r\n   build(F, f);\r\n   \r\n   ZZ_pEX h;\r\n\r\n   FrobeniusMap(h, F);\r\n\r\n   ZZ_pEX s;\r\n   PowerCompose(s, h, F.n, F);\r\n   if (!IsX(s)) return 0;\r\n\r\n   FacVec fvec;\r\n\r\n   FactorInt(fvec, F.n);\r\n\r\n   return RecIrredTest(fvec.length()-1, h, F, fvec);\r\n}\r\n\r\n\r\n\r\nlong IterIrredTest(const ZZ_pEX& f)\r\n{\r\n   if (deg(f) <= 0) return 0;\r\n   if (deg(f) == 1) return 1;\r\n\r\n   ZZ_pEXModulus F;\r\n\r\n   build(F, f);\r\n   \r\n   ZZ_pEX h;\r\n\r\n   FrobeniusMap(h, F);\r\n\r\n   long CompTableSize = 2*SqrRoot(deg(f));\r\n\r\n   ZZ_pEXArgument H;\r\n\r\n   build(H, h, F, CompTableSize);\r\n\r\n   long i, d, limit, limit_sqr;\r\n   ZZ_pEX g, X, t, prod;\r\n\r\n\r\n   SetX(X);\r\n\r\n   i = 0;\r\n   g = h;\r\n   d = 1;\r\n   limit = 2;\r\n   limit_sqr = limit*limit;\r\n\r\n   set(prod);\r\n\r\n\r\n   while (2*d <= deg(f)) {\r\n      sub(t, g, X);\r\n      MulMod(prod, prod, t, F);\r\n      i++;\r\n      if (i == limit_sqr) {\r\n         GCD(t, f, prod);\r\n         if (!IsOne(t)) return 0;\r\n\r\n         set(prod);\r\n         limit++;\r\n         limit_sqr = limit*limit;\r\n         i = 0;\r\n      }\r\n\r\n      d = d + 1;\r\n      if (2*d <= deg(f)) {\r\n         CompMod(g, g, H, F);\r\n      }\r\n   }\r\n\r\n   if (i > 0) {\r\n      GCD(t, f, prod);\r\n      if (!IsOne(t)) return 0;\r\n   }\r\n\r\n   return 1;\r\n}\r\n\r\nstatic\r\nvoid MulByXPlusY(vec_ZZ_pEX& h, const ZZ_pEX& f, const ZZ_pEX& g)\r\n// h represents the bivariate polynomial h[0] + h[1]*Y + ... + h[n-1]*Y^k,\r\n// where the h[i]'s are polynomials in X, each of degree < deg(f),\r\n// and k < deg(g).\r\n// h is replaced by the bivariate polynomial h*(X+Y) (mod f(X), g(Y)).\r\n\r\n{\r\n   long n = deg(g);\r\n   long k = h.length()-1;\r\n\r\n   if (k < 0) return;\r\n\r\n   if (k < n-1) {\r\n      h.SetLength(k+2);\r\n      h[k+1] = h[k];\r\n      for (long i = k; i >= 1; i--) {\r\n         MulByXMod(h[i], h[i], f);\r\n         add(h[i], h[i], h[i-1]);\r\n      }\r\n      MulByXMod(h[0], h[0], f);\r\n   }\r\n   else {\r\n      ZZ_pEX b, t;\r\n\r\n      b = h[n-1];\r\n      for (long i = n-1; i >= 1; i--) {\r\n         mul(t, b, g.rep[i]);\r\n         MulByXMod(h[i], h[i], f);\r\n         add(h[i], h[i], h[i-1]);\r\n         sub(h[i], h[i], t);\r\n      }\r\n      mul(t, b, g.rep[0]);\r\n      MulByXMod(h[0], h[0], f);\r\n      sub(h[0], h[0], t);\r\n   }\r\n\r\n   // normalize\r\n\r\n   k = h.length()-1;\r\n   while (k >= 0 && IsZero(h[k])) k--;\r\n   h.SetLength(k+1);\r\n}\r\n\r\n\r\nstatic\r\nvoid IrredCombine(ZZ_pEX& x, const ZZ_pEX& f, const ZZ_pEX& g)\r\n{\r\n   if (deg(f) < deg(g)) {\r\n      IrredCombine(x, g, f);\r\n      return;\r\n   }\r\n\r\n   // deg(f) >= deg(g)...not necessary, but maybe a little more\r\n   //                    time & space efficient\r\n\r\n   long df = deg(f);\r\n   long dg = deg(g);\r\n   long m = df*dg;\r\n\r\n   vec_ZZ_pEX h(INIT_SIZE, dg);\r\n\r\n   long i;\r\n   for (i = 0; i < dg; i++) h[i].SetMaxLength(df);\r\n\r\n   h.SetLength(1);\r\n   set(h[0]);\r\n\r\n   vec_ZZ_pE a;\r\n\r\n   a.SetLength(2*m);\r\n\r\n   for (i = 0; i < 2*m; i++) {\r\n      a[i] = ConstTerm(h[0]);\r\n      if (i < 2*m-1)\r\n         MulByXPlusY(h, f, g);\r\n   }\r\n\r\n   MinPolySeq(x, a, m);\r\n}\r\n\r\n\r\nstatic\r\nvoid BuildPrimePowerIrred(ZZ_pEX& f, long q, long e)\r\n{\r\n   long n = power(q, e);\r\n\r\n   do {\r\n      random(f, n);\r\n      SetCoeff(f, n);\r\n   } while (!IterIrredTest(f));\r\n}\r\n\r\nstatic\r\nvoid RecBuildIrred(ZZ_pEX& f, long u, const FacVec& fvec)\r\n{\r\n   if (fvec[u].link == -1)\r\n      BuildPrimePowerIrred(f, fvec[u].q, fvec[u].a);\r\n   else {\r\n      ZZ_pEX g, h;\r\n      RecBuildIrred(g, fvec[u].link, fvec);\r\n      RecBuildIrred(h, fvec[u].link+1, fvec);\r\n      IrredCombine(f, g, h);\r\n   }\r\n}\r\n\r\n\r\nvoid BuildIrred(ZZ_pEX& f, long n)\r\n{\r\n   if (n <= 0)\r\n      LogicError(\"BuildIrred: n must be positive\");\r\n\r\n   if (NTL_OVERFLOW(n, 1, 0)) ResourceError(\"overflow in BuildIrred\");\r\n\r\n   if (n == 1) {\r\n      SetX(f);\r\n      return;\r\n   }\r\n\r\n   FacVec fvec;\r\n\r\n   FactorInt(fvec, n);\r\n\r\n   RecBuildIrred(f, fvec.length()-1, fvec);\r\n}\r\n\r\n\r\n\r\n#if 0\r\nvoid BuildIrred(ZZ_pEX& f, long n)\r\n{\r\n   if (n <= 0)\r\n      LogicError(\"BuildIrred: n must be positive\");\r\n\r\n   if (n == 1) {\r\n      SetX(f);\r\n      return;\r\n   }\r\n\r\n   ZZ_pEX g;\r\n\r\n   do {\r\n      random(g, n);\r\n      SetCoeff(g, n);\r\n   } while (!IterIrredTest(g));\r\n\r\n   f = g;\r\n\r\n}\r\n#endif\r\n\r\n\r\n\r\nvoid BuildRandomIrred(ZZ_pEX& f, const ZZ_pEX& g)\r\n{\r\n   ZZ_pEXModulus G;\r\n   ZZ_pEX h, ff;\r\n\r\n   build(G, g);\r\n   do {\r\n      random(h, deg(g));\r\n      IrredPolyMod(ff, h, G);\r\n   } while (deg(ff) < deg(g));\r\n\r\n   f = ff;\r\n}\r\n\r\n\r\n/************* NEW DDF ****************/\r\n\r\nNTL_THREAD_LOCAL long ZZ_pEX_GCDTableSize = 4;\r\nNTL_THREAD_LOCAL double ZZ_pEXFileThresh = NTL_FILE_THRESH;\r\nNTL_THREAD_LOCAL static vec_ZZ_pEX *BabyStepFile=0;\r\nNTL_THREAD_LOCAL static vec_ZZ_pEX *GiantStepFile=0;\r\nNTL_THREAD_LOCAL static long use_files;\r\n\r\n\r\nstatic\r\ndouble CalcTableSize(long n, long k)\r\n{\r\n   double sz = ZZ_p::storage();\r\n   sz = sz*ZZ_pE::degree();\r\n   sz = sz + NTL_VECTOR_HEADER_SIZE + sizeof(vec_ZZ_p);\r\n   sz = sz*n;\r\n   sz = sz + NTL_VECTOR_HEADER_SIZE + sizeof(vec_ZZ_pE);\r\n   sz = sz * k;\r\n   sz = sz/1024;\r\n   return sz;\r\n}\r\n\r\n\r\nstatic\r\nvoid GenerateBabySteps(ZZ_pEX& h1, const ZZ_pEX& f, const ZZ_pEX& h, long k,\r\n                       FileList& flist, long verbose)\r\n\r\n{\r\n   double t;\r\n\r\n   if (verbose) { cerr << \"generating baby steps...\"; t = GetTime(); }\r\n\r\n   ZZ_pEXModulus F;\r\n   build(F, f);\r\n\r\n   ZZ_pEXArgument H;\r\n\r\n#if 0\r\n   double n2 = sqrt(double(F.n));\r\n   double n4 = sqrt(n2);\r\n   double n34 = n2*n4;\r\n   long sz = long(ceil(n34/sqrt(sqrt(2.0))));\r\n#else\r\n   long sz = 2*SqrRoot(F.n);\r\n#endif\r\n\r\n   build(H, h, F, sz);\r\n\r\n\r\n   h1 = h;\r\n\r\n   long i;\r\n\r\n   if (!use_files) {\r\n      (*BabyStepFile).SetLength(k-1);\r\n   }\r\n\r\n   for (i = 1; i <= k-1; i++) {\r\n      if (use_files) {\r\n         ofstream s;\r\n         OpenWrite(s, FileName(\"baby\", i), flist);\r\n         s << h1 << \"\\n\";\r\n         CloseWrite(s);\r\n      }\r\n      else\r\n         (*BabyStepFile)(i) = h1;\r\n\r\n      CompMod(h1, h1, H, F);\r\n      if (verbose) cerr << \"+\";\r\n   }\r\n\r\n   if (verbose)\r\n      cerr << (GetTime()-t) << \"\\n\";\r\n\r\n}\r\n\r\n\r\nstatic\r\nvoid GenerateGiantSteps(const ZZ_pEX& f, const ZZ_pEX& h, long l, \r\n                        FileList& flist, long verbose)\r\n{\r\n\r\n   double t;\r\n\r\n   if (verbose) { cerr << \"generating giant steps...\"; t = GetTime(); }\r\n\r\n   ZZ_pEXModulus F;\r\n   build(F, f);\r\n\r\n   ZZ_pEXArgument H;\r\n\r\n#if 0\r\n   double n2 = sqrt(double(F.n));\r\n   double n4 = sqrt(n2);\r\n   double n34 = n2*n4;\r\n   long sz = long(ceil(n34/sqrt(sqrt(2.0))));\r\n#else\r\n   long sz = 2*SqrRoot(F.n);\r\n#endif\r\n\r\n   build(H, h, F, sz);\r\n\r\n   ZZ_pEX h1;\r\n\r\n   h1 = h;\r\n\r\n   long i;\r\n\r\n   if (!use_files) {\r\n      (*GiantStepFile).SetLength(l);\r\n   }\r\n\r\n   for (i = 1; i <= l-1; i++) {\r\n      if (use_files) {\r\n         ofstream s;\r\n         OpenWrite(s, FileName(\"giant\", i), flist);\r\n         s << h1 << \"\\n\";\r\n         CloseWrite(s);\r\n      }\r\n      else\r\n        (*GiantStepFile)(i) = h1;\r\n\r\n      CompMod(h1, h1, H, F);\r\n      if (verbose) cerr << \"+\";\r\n   }\r\n\r\n   if (use_files) {\r\n      ofstream s;\r\n      OpenWrite(s, FileName(\"giant\", i), flist);\r\n      s << h1 << \"\\n\";\r\n      CloseWrite(s);\r\n   }\r\n   else\r\n      (*GiantStepFile)(i) = h1;\r\n\r\n   if (verbose)\r\n      cerr << (GetTime()-t) << \"\\n\";\r\n\r\n}\r\n\r\n\r\nstatic\r\nvoid NewAddFactor(vec_pair_ZZ_pEX_long& u, const ZZ_pEX& g, long m, long verbose)\r\n{\r\n   long len = u.length();\r\n\r\n   u.SetLength(len+1);\r\n   u[len].a = g;\r\n   u[len].b = m;\r\n\r\n   if (verbose) {\r\n      cerr << \"split \" << m << \" \" << deg(g) << \"\\n\";\r\n   }\r\n}\r\n\r\n   \r\n\r\n\r\nstatic\r\nvoid NewProcessTable(vec_pair_ZZ_pEX_long& u, ZZ_pEX& f, const ZZ_pEXModulus& F,\r\n                     vec_ZZ_pEX& buf, long size, long StartInterval,\r\n                     long IntervalLength, long verbose)\r\n\r\n{\r\n   if (size == 0) return;\r\n\r\n   ZZ_pEX& g = buf[size-1];\r\n\r\n   long i;\r\n\r\n   for (i = 0; i < size-1; i++)\r\n      MulMod(g, g, buf[i], F);\r\n\r\n   GCD(g, f, g);\r\n\r\n   if (deg(g) == 0) return;\r\n\r\n   div(f, f, g);\r\n\r\n   long d = (StartInterval-1)*IntervalLength + 1;\r\n   i = 0;\r\n   long interval = StartInterval;\r\n\r\n   while (i < size-1 && 2*d <= deg(g)) {\r\n      GCD(buf[i], buf[i], g);\r\n      if (deg(buf[i]) > 0) {\r\n         NewAddFactor(u, buf[i], interval, verbose);\r\n         div(g, g, buf[i]);\r\n      }\r\n\r\n      i++;\r\n      interval++;\r\n      d += IntervalLength;\r\n   }\r\n\r\n   if (deg(g) > 0) {\r\n      if (i == size-1)\r\n         NewAddFactor(u, g, interval, verbose);\r\n      else\r\n         NewAddFactor(u, g, (deg(g)+IntervalLength-1)/IntervalLength, verbose);\r\n   }\r\n}\r\n\r\n\r\nstatic\r\nvoid FetchGiantStep(ZZ_pEX& g, long gs, const ZZ_pEXModulus& F)\r\n{\r\n   if (use_files) {\r\n      ifstream s;\r\n      OpenRead(s, FileName(\"giant\", gs));\r\n      NTL_INPUT_CHECK_ERR(s >> g);\r\n   }\r\n   else\r\n      g = (*GiantStepFile)(gs);\r\n\r\n\r\n   rem(g, g, F);\r\n}\r\n\r\n\r\nstatic\r\nvoid FetchBabySteps(vec_ZZ_pEX& v, long k)\r\n{\r\n   v.SetLength(k);\r\n\r\n   SetX(v[0]);\r\n\r\n   long i;\r\n   for (i = 1; i <= k-1; i++) {\r\n      if (use_files) {\r\n         ifstream s;\r\n         OpenRead(s, FileName(\"baby\", i));\r\n         NTL_INPUT_CHECK_ERR(s >> v[i]);\r\n      }\r\n      else\r\n         v[i] = (*BabyStepFile)(i);\r\n   }\r\n}\r\n      \r\n\r\n\r\nstatic\r\nvoid GiantRefine(vec_pair_ZZ_pEX_long& u, const ZZ_pEX& ff, long k, long l,\r\n                 long verbose)\r\n\r\n{\r\n   double t;\r\n\r\n   if (verbose) {\r\n      cerr << \"giant refine...\";\r\n      t = GetTime();\r\n   }\r\n\r\n   u.SetLength(0);\r\n\r\n   vec_ZZ_pEX BabyStep;\r\n\r\n   FetchBabySteps(BabyStep, k);\r\n\r\n   vec_ZZ_pEX buf(INIT_SIZE, ZZ_pEX_GCDTableSize);\r\n\r\n   ZZ_pEX f;\r\n   f = ff;\r\n\r\n   ZZ_pEXModulus F;\r\n   build(F, f);\r\n\r\n   ZZ_pEX g;\r\n   ZZ_pEX h;\r\n\r\n   long size = 0;\r\n\r\n   long first_gs;\r\n\r\n   long d = 1;\r\n\r\n   while (2*d <= deg(f)) {\r\n\r\n      long old_n = deg(f);\r\n\r\n      long gs = (d+k-1)/k;\r\n      long bs = gs*k - d;\r\n\r\n      if (bs == k-1) {\r\n         size++;\r\n         if (size == 1) first_gs = gs;\r\n         FetchGiantStep(g, gs, F);\r\n         sub(buf[size-1], g, BabyStep[bs]);\r\n      }\r\n      else {\r\n         sub(h, g, BabyStep[bs]);\r\n         MulMod(buf[size-1], buf[size-1], h, F);\r\n      }\r\n\r\n      if (verbose && bs == 0) cerr << \"+\";\r\n\r\n      if (size == ZZ_pEX_GCDTableSize && bs == 0) {\r\n         NewProcessTable(u, f, F, buf, size, first_gs, k, verbose);\r\n         if (verbose) cerr << \"*\";\r\n         size = 0;\r\n      }\r\n\r\n      d++;\r\n\r\n      if (2*d <= deg(f) && deg(f) < old_n) {\r\n         build(F, f);\r\n\r\n         long i;\r\n         for (i = 1; i <= k-1; i++) \r\n            rem(BabyStep[i], BabyStep[i], F);\r\n      }\r\n   }\r\n\r\n   if (size > 0) {\r\n      NewProcessTable(u, f, F, buf, size, first_gs, k, verbose);\r\n      if (verbose) cerr << \"*\";\r\n   }\r\n\r\n   if (deg(f) > 0) \r\n      NewAddFactor(u, f, 0, verbose);\r\n\r\n   if (verbose) {\r\n      t = GetTime()-t;\r\n      cerr << \"giant refine time: \" << t << \"\\n\";\r\n   }\r\n}\r\n\r\n\r\nstatic\r\nvoid IntervalRefine(vec_pair_ZZ_pEX_long& factors, const ZZ_pEX& ff,\r\n                    long k, long gs, const vec_ZZ_pEX& BabyStep, long verbose)\r\n\r\n{\r\n   vec_ZZ_pEX buf(INIT_SIZE, ZZ_pEX_GCDTableSize);\r\n\r\n   ZZ_pEX f;\r\n   f = ff;\r\n\r\n   ZZ_pEXModulus F;\r\n   build(F, f);\r\n\r\n   ZZ_pEX g;\r\n\r\n   FetchGiantStep(g, gs, F);\r\n\r\n   long size = 0;\r\n\r\n   long first_d;\r\n\r\n   long d = (gs-1)*k + 1;\r\n   long bs = k-1;\r\n\r\n   while (bs >= 0 && 2*d <= deg(f)) {\r\n\r\n      long old_n = deg(f);\r\n\r\n      if (size == 0) first_d = d;\r\n      rem(buf[size], BabyStep[bs], F);\r\n      sub(buf[size], buf[size], g);\r\n      size++;\r\n\r\n      if (size == ZZ_pEX_GCDTableSize) {\r\n         NewProcessTable(factors, f, F, buf, size, first_d, 1, verbose);\r\n         size = 0;\r\n      }\r\n\r\n      d++;\r\n      bs--;\r\n\r\n      if (bs >= 0 && 2*d <= deg(f) && deg(f) < old_n) {\r\n         build(F, f);\r\n         rem(g, g, F);\r\n      }\r\n   }\r\n\r\n   NewProcessTable(factors, f, F, buf, size, first_d, 1, verbose);\r\n\r\n   if (deg(f) > 0) \r\n      NewAddFactor(factors, f, deg(f), verbose);\r\n}\r\n   \r\n\r\n\r\n\r\nstatic\r\nvoid BabyRefine(vec_pair_ZZ_pEX_long& factors, const vec_pair_ZZ_pEX_long& u,\r\n                long k, long l, long verbose)\r\n\r\n{\r\n   double t;\r\n\r\n   if (verbose) {\r\n      cerr << \"baby refine...\";\r\n      t = GetTime();\r\n   }\r\n\r\n   factors.SetLength(0);\r\n\r\n   vec_ZZ_pEX BabyStep;\r\n\r\n   long i;\r\n   for (i = 0; i < u.length(); i++) {\r\n      const ZZ_pEX& g = u[i].a;\r\n      long gs = u[i].b;\r\n\r\n      if (gs == 0 || 2*((gs-1)*k+1) > deg(g))\r\n         NewAddFactor(factors, g, deg(g), verbose);\r\n      else {\r\n         if (BabyStep.length() == 0)\r\n            FetchBabySteps(BabyStep, k);\r\n         IntervalRefine(factors, g, k, gs, BabyStep, verbose);\r\n      }\r\n   }\r\n\r\n   if (verbose) {\r\n      t = GetTime()-t;\r\n      cerr << \"baby refine time: \" << t << \"\\n\";\r\n   }\r\n}\r\n\r\n      \r\n      \r\n\r\n      \r\n\r\nvoid NewDDF(vec_pair_ZZ_pEX_long& factors,\r\n            const ZZ_pEX& f,\r\n            const ZZ_pEX& h,\r\n            long verbose)\r\n\r\n{\r\n   if (!IsOne(LeadCoeff(f)))\r\n      LogicError(\"NewDDF: bad args\");\r\n\r\n   if (deg(f) == 0) {\r\n      factors.SetLength(0);\r\n      return;\r\n   }\r\n\r\n   if (deg(f) == 1) {\r\n      factors.SetLength(0);\r\n      append(factors, cons(f, 1L));\r\n      return;\r\n   }\r\n\r\n   long B = deg(f)/2;\r\n   long k = SqrRoot(B);\r\n   long l = (B+k-1)/k;\r\n\r\n   ZZ_pEX h1;\r\n\r\n   if (CalcTableSize(deg(f), k + l - 1) > ZZ_pEXFileThresh)\r\n      use_files = 1;\r\n   else\r\n      use_files = 0;\r\n\r\n\r\n   FileList flist;\r\n\r\n   vec_ZZ_pEX local_BabyStepFile;\r\n   vec_ZZ_pEX local_GiantStepFile;\r\n\r\n   BabyStepFile = &local_BabyStepFile;\r\n   GiantStepFile = &local_GiantStepFile;\r\n\r\n\r\n   GenerateBabySteps(h1, f, h, k, flist, verbose);\r\n\r\n   GenerateGiantSteps(f, h1, l, flist, verbose);\r\n\r\n   vec_pair_ZZ_pEX_long u;\r\n   GiantRefine(u, f, k, l, verbose);\r\n   BabyRefine(factors, u, k, l, verbose);\r\n}\r\n\r\nlong IterComputeDegree(const ZZ_pEX& h, const ZZ_pEXModulus& F)\r\n{\r\n   long n = deg(F);\r\n\r\n   if (n == 1 || IsX(h)) return 1;\r\n\r\n   long B = n/2;\r\n   long k = SqrRoot(B);\r\n   long l = (B+k-1)/k;\r\n\r\n\r\n   ZZ_pEXArgument H;\r\n\r\n#if 0\r\n   double n2 = sqrt(double(n));\r\n   double n4 = sqrt(n2);\r\n   double n34 = n2*n4;\r\n   long sz = long(ceil(n34/sqrt(sqrt(2.0))));\r\n#else\r\n   long sz = 2*SqrRoot(F.n);\r\n#endif\r\n\r\n   build(H, h, F, sz);\r\n\r\n   ZZ_pEX h1;\r\n   h1 = h;\r\n\r\n   vec_ZZ_pEX baby;\r\n   baby.SetLength(k);\r\n\r\n   SetX(baby[0]);\r\n\r\n   long i;\r\n\r\n   for (i = 1; i <= k-1; i++) {\r\n      baby[i] = h1;\r\n      CompMod(h1, h1, H, F);\r\n      if (IsX(h1)) return i+1;\r\n   }\r\n\r\n   build(H, h1, F, sz);\r\n\r\n   long j;\r\n\r\n   for (j = 2; j <= l; j++) {\r\n      CompMod(h1, h1, H, F);\r\n\r\n      for (i = k-1; i >= 0; i--) {\r\n         if (h1 == baby[i])\r\n            return j*k-i;\r\n      }\r\n   }\r\n\r\n   return n;\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "4f58b5ba6d376543d7e1923d1c153fa64be0fa67", "size": 29688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/ZZ_pEXFactoring.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WinNTL-8_1_2/src/ZZ_pEXFactoring.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WinNTL-8_1_2/src/ZZ_pEXFactoring.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6131661442, "max_line_length": 82, "alphanum_fraction": 0.4672258151, "num_tokens": 9858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6446899073000464}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[closure\r\n//` Examine if a polygon is defined as \"should be closed\"\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n\r\nint main()\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<double> point_type;\r\n    typedef boost::geometry::model::polygon<point_type> polygon_type;\r\n\r\n    boost::geometry::closure_selector clos = boost::geometry::closure<polygon_type>::value;\r\n    \r\n    std::cout << \"closure: \" << clos << std::endl\r\n        << \"(open = \" << boost::geometry::open\r\n        << \", closed = \" << boost::geometry::closed \r\n        << \") \"<< std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[closure_output\r\n/*`\r\nOutput:\r\n[pre\r\nclosure: 1\r\n(open = 0, closed = 1)\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "c0ea9a8d276ceeab939b7ed0f8c03e8bcd5f93f4", "size": 1128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/core/closure.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/geometry/doc/src/examples/core/closure.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/geometry/doc/src/examples/core/closure.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5217391304, "max_line_length": 92, "alphanum_fraction": 0.6453900709, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.8128673110375458, "lm_q1q2_score": 0.6446899019069042}}
{"text": "#include <gtest/gtest.h>\n#include <Eigen/Geometry>\n#include \"slick/geometry/line2d.h\"\n#include \"slick/test/unittest/util.h\"\n\nconst int N = 10;\n\ntemplate <typename T>\nvoid check_on_line(const slick::Line2DBase<T> &line,\n                   const Eigen::Matrix<T, 2, 1> &pt) {\n  const auto lv = (line.point2() - line.point1()).normalized();\n  const T t = (pt - line.point1()).normalized().dot(lv);\n  EXPECT_NEAR(std::fabs(t), 1.0, slick::Gap<T>());\n};\n\n// line2d specific functions ===================================================\ntemplate <typename T> void Project_Test() {\n  std::srand(\n      std::time(nullptr)); // use current time as seed for random generator\n  slick::Line2DBase<T> line(slick::GenRandPoint2D<T>(N),\n                            slick::GenRandPoint2D<T>(N));\n  const auto pr = line.project(slick::GenRandPoint2D<T>(N));\n  const auto lv = (line.point2() - line.point1()).normalized();\n  const T t = (pr - line.point1()).normalized().dot(lv);\n  EXPECT_NEAR(std::fabs(t), 1.0, slick::Gap<T>());\n}\n\nTEST(Line2DBaseTest, Project) {\n  Project_Test<double>();\n  Project_Test<float>();\n}\n\ntemplate <typename T> void perpendicular_distance_Test(T gap) {\n  std::srand(\n      std::time(nullptr)); // use current time as seed for random generator\n  slick::Line2DBase<T> line(slick::GenRandPoint2D<T>(N),\n                            slick::GenRandPoint2D<T>(N));\n  const auto pt = slick::GenRandPoint2D<T>(N);\n  const auto pr = line.project(pt);\n  const T t = line.perpendicular_distance(pt);\n  EXPECT_NEAR(t, (pt - pr).norm(), gap);\n}\n\nTEST(Line2DBaseTest, perpendicular_distance) {\n  perpendicular_distance_Test<double>(slick::Gap<double>());\n  perpendicular_distance_Test<float>(1.e-3);\n}\n\ntemplate <typename T> void perpendicular_sqdistance_Test(T gap) {\n  std::srand(\n      std::time(nullptr)); // use current time as seed for random generator\n  slick::Line2DBase<T> line(slick::GenRandPoint2D<T>(N),\n                            slick::GenRandPoint2D<T>(N));\n  const auto pt = slick::GenRandPoint2D<T>(N);\n  const auto pr = line.project(pt);\n  const T t = line.perpendicular_sqdistance(pt);\n  EXPECT_NEAR(t, (pt - pr).squaredNorm(), gap);\n}\n\nTEST(Line2DBaseTest, perpendicular_sqdistance) {\n  perpendicular_sqdistance_Test<double>(slick::Gap<double>());\n  // perpendicular_sqdistance_Test<float>(1.e-3);\n}\n\ntemplate <typename T> void intersect_line_Test() {\n  std::srand(\n      std::time(nullptr)); // use current time as seed for random generator\n  slick::Line2DBase<T> line1(slick::GenRandPoint2D<T>(N),\n                               slick::GenRandPoint2D<T>(N));\n  slick::Line2DBase<T> line2(slick::GenRandPoint2D<T>(N),\n                               slick::GenRandPoint2D<T>(N));\n  auto pt = line1.intersect(line2);\n  if (pt) {\n    check_on_line(line1, *pt);\n    check_on_line(line1, *pt);\n    check_on_line(line2, *pt);\n    check_on_line(line2, *pt);\n  }\n}\n\nTEST(Line2DBaseTest, intersect_line) {\n  intersect_line_Test<double>();\n  intersect_line_Test<float>();\n}\n\nint main(int argc, char **argv) {\n  std::vector<char *> vars(argc + 1);\n  for (int i = 0; i < argc; ++i)\n    vars[i] = argv[i];\n  char ca[50];\n  sprintf(ca, \"--gtest_repeat=%d\", NSAMPLES);\n  vars[argc] = ca;\n  argc++;\n  ::testing::InitGoogleTest(&argc, &vars.front());\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "c42abcbfab5dfafdf0429668f29edf4ac371dc38", "size": 3282, "ext": "cc", "lang": "C++", "max_stars_repo_path": "slick/test/unittest/geometry_line2d_unittest.cc", "max_stars_repo_name": "williammc/Slick", "max_stars_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-13T05:26:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-13T05:26:40.000Z", "max_issues_repo_path": "slick/test/unittest/geometry_line2d_unittest.cc", "max_issues_repo_name": "williammc/Slick", "max_issues_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slick/test/unittest/geometry_line2d_unittest.cc", "max_forks_repo_name": "williammc/Slick", "max_forks_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_forks_repo_licenses": ["BSD-3-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.8350515464, "max_line_length": 80, "alphanum_fraction": 0.6404631322, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6443937876970838}}
{"text": "#pragma once\n#include <tuple>\n#include <Eigen/Dense>\n\nnamespace filter_bay\n{\n/*!\nModel of a gaussian measurement.\nThe equation ist:\n\\f[\n  y_k = H x_k + v_k\n\\f]\nWhere \\f$x_k\\f$ is the state and \\f$v_k\\f$ the measurement noise at step k.\nThe measurement noise is assumed to be a constant white noise.\n\nSee https://en.wikipedia.org/wiki/Kalman_filter#Update for further explanation.\n*/\ntemplate <size_t state_size, size_t observation_size>\nstruct GaussianObservationModel\n{\n  /*! \\f$x_k\\f$ */\n  using State = typename Eigen::Matrix<double, state_size, 1>;\n  /*! \\f$P_k\\f$ */\n  using StateCovariance = typename Eigen::Matrix<double, state_size, state_size>;\n  /*! \\f$y_k\\f$ */\n  using Observation = typename Eigen::Matrix<double, observation_size, 1>;\n  /*! \\f$H\\f$ */\n  using ObservationMatrix = typename Eigen::Matrix<double, observation_size, state_size>;\n  /*! \\f$R\\f$ */\n  using NoiseCovariance = typename Eigen::Matrix<double, observation_size, observation_size>;\n  /*! \\f$K\\f$ */\n  using KalmanGain = typename Eigen::Matrix<double, state_size, observation_size>;\n\n  /*! Observatin matrix of the state */\n  ObservationMatrix H;\n  /*! Measurement covariance matrix */\n  NoiseCovariance R;\n\n  GaussianObservationModel() {}\n\n  GaussianObservationModel(ObservationMatrix h, NoiseCovariance r)\n      : H(std::move(h)), R(std::move(r)) {}\n\n  /*!\n  Calculates the expected measurement for the given state.\n  \\param x current state\n  */\n  Observation calculate_measurement(const State &x) const\n  {\n    return H * x;\n  }\n\n  /*!\n  Calculates the kalman gain via the observation model.\n  \\param P the current covariance of the state (serves as confidence)\n  */\n  KalmanGain calculate_gain(const StateCovariance &P) const\n  {\n    // Calculate P * H^T only once\n    Eigen::Matrix<double, state_size, observation_size> PH_T = P * H.transpose();\n    Eigen::Matrix<double, observation_size, observation_size> S = R + H * PH_T;\n    return PH_T * S.inverse();\n  }\n\n  /*!\n  Calculates the update of the state with the given observation model.\n  \\param x current (predicted) state\n  \\param y current measurement\n  \\param K kalman gain for the (predicted) state covariance\n  */\n  State update_state(const State &x, const Observation &y, KalmanGain &K) const\n  {\n    Observation residual = y - calculate_measurement(x);\n    return x + K * residual;\n  }\n\n  StateCovariance update_covariance(const StateCovariance &P,\n                                    const KalmanGain &K) const\n  {\n    // P = (I-KH)P(I-KH)^T + KRK^T\n    // This is more numerically stable and works for non-optimal K vs the equation\n    // P = (I - KH) P usually seen in the literature.\n    // https://github.com/rlabbe/filterpy/blob/master/filterpy/kalman/kalman_filter.py\n    StateCovariance I = StateCovariance::Identity();\n    auto I_KH = I - K * H;\n    return I_KH * P * I_KH.transpose() + K * R * K.transpose();\n  }\n};\n} // namespace filter_bay", "meta": {"hexsha": "758e4d9f1d6d3680c6ae57acd5b4aefe1fd745db", "size": 2899, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/filter_bay/model/gaussian_observation_model.hpp", "max_stars_repo_name": "Tuebel/filter_bay", "max_stars_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/filter_bay/model/gaussian_observation_model.hpp", "max_issues_repo_name": "Tuebel/filter_bay", "max_issues_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-10T14:36:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-21T10:10:08.000Z", "max_forks_repo_path": "include/filter_bay/model/gaussian_observation_model.hpp", "max_forks_repo_name": "Tuebel/filter_bay", "max_forks_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5730337079, "max_line_length": 93, "alphanum_fraction": 0.6905829596, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6443937827072803}}
{"text": "#include <csv.h>\n#include <Eigen/Dense>\n\n#include <experimental/filesystem>\n#include <iostream>\n#include <string>\n\nnamespace fs = std::experimental::filesystem;\n\ntemplate <std::size_t... Idx, typename T, typename R>\nbool read_row_help(std::index_sequence<Idx...>, T& row, R& r) {\n  return r.read_row(std::get<Idx>(row)...);\n}\n\ntemplate <std::size_t... Idx, typename T>\nvoid fill_values(std::index_sequence<Idx...>,\n                 T& row,\n                 std::vector<double>& data) {\n  data.insert(data.end(), {std::get<Idx>(row)...});\n}\n\nint main(int argc, char** argv) {\n  if (argc > 1) {\n    auto file_path = fs::path(argv[1]);\n    if (fs::exists(file_path)) {\n      const uint32_t columns_num = 5;\n      io::CSVReader<columns_num> csv_reader(file_path);\n\n      std::vector<std::string> categorical_column;\n      std::vector<double> values;\n      using RowType = std::tuple<double, double, double, double, std::string>;\n      RowType row;\n\n      uint32_t rows_num = 0;\n      try {\n        bool done = false;\n        while (!done) {\n          done = !read_row_help(\n              std::make_index_sequence<std::tuple_size<RowType>::value>{}, row,\n              csv_reader);\n          if (!done) {\n            categorical_column.push_back(std::get<4>(row));\n            fill_values(std::make_index_sequence<columns_num - 1>{}, row,\n                        values);\n            ++rows_num;\n          }\n        }\n      } catch (const io::error::no_digit& err) {\n        // ignore bad formated samples\n        std::cerr << err.what() << std::endl;\n      }\n\n      auto x_data = Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic,\n                                             Eigen::Dynamic, Eigen::RowMajor>>(\n          values.data(), rows_num, columns_num - 1);\n\n      std::cout << x_data << std::endl;\n\n      // Feature-scaling(Normalization):\n      // Standardization - zero mean + 1 std\n      Eigen::Array<double, 1, Eigen::Dynamic> std_dev =\n          ((x_data.rowwise() - x_data.colwise().mean())\n               .array()\n               .square()\n               .colwise()\n               .sum() /\n           (x_data.rows() - 1))\n              .sqrt();\n\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> x_data_std =\n          (x_data.rowwise() - x_data.colwise().mean()).array().rowwise() /\n          std_dev;\n\n      std::cout << x_data_std << std::endl;\n\n      // Min-Max normalization\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> x_data_min_max =\n          (x_data.rowwise() - x_data.colwise().minCoeff()).array().rowwise() /\n          (x_data.colwise().maxCoeff() - x_data.colwise().minCoeff()).array();\n\n      std::cout << x_data_min_max << std::endl;\n\n      // Average normalization\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> x_data_avg =\n          (x_data.rowwise() - x_data.colwise().mean()).array().rowwise() /\n          (x_data.colwise().maxCoeff() - x_data.colwise().minCoeff()).array();\n\n      std::cout << x_data_avg << std::endl;\n\n    } else {\n      std::cout << \"File path is incorrect \" << file_path << \"\\n\";\n    }\n  } else {\n    std::cout << \"Please provide a path to a dataset file\\n\";\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "9b50be09c8093f5f7686cf043f14d4c5c6662dfe", "size": 3164, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter02/csv/cpp/csv.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter02/csv/cpp/csv.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter02/csv/cpp/csv.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 31.9595959596, "max_line_length": 79, "alphanum_fraction": 0.5600505689, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6443937777566605}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00c3\u00a4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\nusing namespace std;\n\nint main(int , char** ) \n{\n    typedef mtl::compressed2D<double> matrix_type;\n    typedef mtl::dense_vector<double> vector_type;\n\n    const int size= 10;\n    matrix_type A(size, size);\n\n    // Set up a non-singular tridiagonal matrix\n    {\n\tmtl::mat::inserter<matrix_type> ins(A, 3);\n\tfor (int i= 0; i < size; i++) {\n\t    if (i > 0) ins[i][i-1] << -0.8;\n\t    ins[i][i] << 3;\n\t    if (i+2 < size) ins[i][i+1] << -0.8;\n\t}\n    }\n    cout << \"A is\\n\" << A;\n\n    vector_type x(size), b(size, 1.0);\n    \n    itl::pc::ilu_0<matrix_type>   P(A);\n    x= solve(P, b);\n\n    cout << \"x is \" << x << '\\n'\n\t << \"A*x is \" << vector_type(A*x) << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "e2f7adff831a8d853c8f32e1ee5d0d237bb97446", "size": 1215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/tridiagonal_solve.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/experimental/tridiagonal_solve.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/experimental/tridiagonal_solve.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 25.3125, "max_line_length": 94, "alphanum_fraction": 0.6049382716, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.644393767796645}}
{"text": "#include <iostream>\r\n#include <cmath>\r\n#include <Eigen/Dense>\r\n#include \"LCPSolve.h\"\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\n// Forward declarations.\r\nbool checkCompatability(const MatrixXd &M, const int &dim);\r\nbool checkTrivialSol(const VectorXd &q);\r\nMatrixXd constructTableau(const MatrixXd &M, const VectorXd &q);\r\nvoid pivot(MatrixXd &tableau, const int &row, const int &col);\r\nint initializeTableau(MatrixXd &tableau);\r\nVectorXd basicVars(const MatrixXd &tableau);\r\nbool checkSol(const MatrixXd &tableau);\r\nbool checkRayTermination(const MatrixXd &tableu, const int &pivotCol);\r\nint minRatioTest(const MatrixXd &tableau, const int &pivotCol);\r\nMatrixXd extractSolution(const MatrixXd &tableau);\r\n\r\n// Solve LCP by Lemke's Method.\r\nLCP LCPSolve(MatrixXd M, VectorXd q) {\r\n    const int dim = q.size();\r\n\r\n    // Initialize LCP data structure.\r\n    LCP solution {};\r\n    solution.M = M;\r\n    solution.q = q;\r\n\r\n    // Check that inputs are compatable.\r\n    bool compatable = checkCompatability(M, dim);\r\n    if (!compatable) {\r\n        solution.exitCond = 2;\r\n        return solution;\r\n    }\r\n\r\n    // Check for trivial solution.\r\n    bool trivial = checkTrivialSol(q);\r\n    if (trivial) {\r\n        solution.z = VectorXd::Zero(dim);\r\n        solution.w = q;\r\n        solution.exitCond = 0;\r\n        return solution;\r\n    }\r\n\r\n    // Construct & initialize tableau.\r\n    MatrixXd tableau = constructTableau(M, q);\r\n    VectorXd index = VectorXd::LinSpaced(dim, 0, dim-1);\r\n\r\n    int pivotCol = initializeTableau(tableau);\r\n    int pivotRow = pivotCol - dim;\r\n    index(pivotRow) = 2*dim;\r\n\r\n    // Now, the tableau is initialized with a feasible basis. Pivot until there is a feasible basis w/o z0.\r\n    const int maxIter {pow(2, dim)};\r\n    int iter {0};\r\n    bool solFound = false;\r\n    while ((!solFound) && (iter < maxIter)) {\r\n        // Check for ray termination.\r\n        bool rayTermination = checkRayTermination(tableau, pivotCol);\r\n        if (rayTermination) {\r\n            solFound = true;\r\n        } else {\r\n            // Minimum ratio test to determine the pivot row (blocked/dropped variable).\r\n            pivotRow = minRatioTest(tableau, pivotCol);\r\n            pivot(tableau, pivotRow, pivotCol);\r\n            int drop = index(pivotRow);\r\n            index(pivotRow) = pivotCol;\r\n            \r\n            // Find next entering variable (pivotCol). Dropped variable is pivotRow.\r\n            if (drop > dim-1) {\r\n                pivotCol = drop - dim;\r\n            } else {\r\n                pivotCol = drop + dim;\r\n            }\r\n\r\n            // Check for solution.\r\n            solFound = checkSol(tableau);\r\n            iter++;\r\n        }\r\n    }\r\n\r\n    // Return solution.\r\n    if (solFound) {\r\n        MatrixXd sols = extractSolution(tableau);\r\n        solution.z = sols.col(0);\r\n        solution.w = sols.col(1);\r\n        solution.exitCond = 0;\r\n    } else {\r\n        MatrixXd sols = extractSolution(tableau);\r\n        solution.z = sols.col(0);\r\n        solution.w = sols.col(1);\r\n        solution.exitCond = 3;\r\n    }\r\n    \r\n    return solution;\r\n}\r\n\r\n\r\n// Check that the inputs M and q are compatable.\r\nbool checkCompatability(const MatrixXd &M, const int &dim) {\r\n    const int rows = M.rows();\r\n    const int cols = M.cols();\r\n\r\n    if (rows != cols)\r\n        return false;\r\n    else if (rows != dim)\r\n        return false;\r\n    else\r\n        return true;\r\n}\r\n\r\n// Check for trivial solution where q is positive.\r\nbool checkTrivialSol(const VectorXd &q) {\r\n    const int dim = q.size();\r\n    for (int i = 0; i < dim; i++)\r\n        if (q[i] <= 0)\r\n            return false;\r\n    return true;\r\n}\r\n\r\n// Construct Lemke tableau with auxilillary variable.\r\nMatrixXd constructTableau(const MatrixXd &M, const VectorXd &q) {\r\n    const int dim = q.size();\r\n    MatrixXd tableau = MatrixXd::Zero(dim, 2*dim + 2); // Initialize with zeros.\r\n    VectorXd auxVar = -VectorXd::Ones(dim); // Auxillary variable z_0 = {-1, -1, ... -1}.\r\n    tableau.topLeftCorner(dim, dim) = MatrixXd::Identity(dim, dim); // Enter identity matrix on left side (w_1, w_2, etc).\r\n    tableau.middleCols(dim, dim) = -M; // Enter I-M (z_1, z_2, etc).\r\n    tableau.col(2*dim) = auxVar; // Enter auxiliary variable.\r\n    tableau.col(2*dim + 1) = q; // Enter q.\r\n    return tableau;\r\n}\r\n\r\n// Pivot function.\r\nvoid pivot(MatrixXd &tableau, const int &row, const int &col) {\r\n    const int dim = tableau.rows();\r\n    double pivotElement = tableau(row, col);\r\n    VectorXd newPivotRow = (1/pivotElement)*tableau.row(row);\r\n    tableau.row(row) = newPivotRow;\r\n    \r\n    VectorXd newNonPivotRow {};\r\n    for (int i = 0; i < dim; i++) {\r\n        if (i != row) {\r\n            newNonPivotRow = tableau.row(i) - tableau(i, col)*tableau.row(row);\r\n            tableau.row(i) = newNonPivotRow;\r\n        }\r\n    }\r\n}\r\n\r\n// Initialize tableau.\r\nint initializeTableau(MatrixXd &tableau) {\r\n    const int dim = tableau.rows();\r\n    const int cols = 2*dim +2;\r\n\r\n    // Pivot row of min element of q w.r.t. aux column.\r\n    int minRow {0}; \r\n    double minVal = tableau.coeff(minRow, cols-1);\r\n    for (int i = 1; i < dim; i++) {\r\n        if (tableau.coeff(i, cols-1) < minVal) {\r\n            minRow = i;\r\n            minVal = tableau(minRow, cols-1);\r\n        }\r\n    }\r\n\r\n    pivot(tableau, minRow, cols-2);\r\n\r\n    // Return the next entering variable, which is the complement to the non-basic variable.\r\n    int newPivotCol = minRow + dim;\r\n    return newPivotCol;\r\n}\r\n\r\n// Return which variables are basic.\r\nVectorXd basicVars(const MatrixXd &tableau) {\r\n    int cols = tableau.cols();\r\n    double varNorm {};\r\n    VectorXd isBasic = VectorXd::Zero(cols - 1);\r\n\r\n    double err {1e-8};\r\n    for (int i = 0; i < cols - 1; i++) {\r\n        varNorm = tableau.col(i).norm();\r\n        if (abs(1 - varNorm) < err) {\r\n            isBasic[i] = true;\r\n        } else {\r\n            isBasic[i] = false;\r\n        }\r\n    }\r\n\r\n    return isBasic;\r\n}\r\n\r\n// Check for solution.\r\nbool checkSol(const MatrixXd &tableau) {\r\n\r\n    // Determine basic variables.\r\n    VectorXd isBasic = basicVars(tableau);\r\n\r\n    // Size information and initialize q & z0.\r\n    bool solFound {false};\r\n    int dim = tableau.rows();\r\n    int cols = 2*dim + 2;\r\n    VectorXd q = tableau.col(cols-1);\r\n    VectorXd z0 = tableau.col(cols-2);\r\n    \r\n    // No solution if any element of q is negative.\r\n    for (int i = 0; i <= dim-1; i++) {\r\n        if (q[i] < 0) {\r\n            return solFound;\r\n        }\r\n    }\r\n    \r\n    // No solution if auxillary variable z0 is basic.\r\n    if (isBasic[cols-2] == 1) {\r\n        return solFound;\r\n    }\r\n    \r\n    // If q is positive and z0 is non-basic, solution has been found.\r\n    solFound = true;\r\n    return solFound;\r\n}\r\n\r\n// Check for secondary ray termination.\r\nbool checkRayTermination(const MatrixXd &tableu, const int &pivotCol) {\r\n    VectorXd column = tableu.col(pivotCol);\r\n    int negTestSum {0};\r\n    for (int i {0}; i < column.size(); i++) {\r\n        if (column(i) <= 0) {\r\n            negTestSum++;\r\n        }\r\n    }\r\n\r\n    if (negTestSum == column.size()) {\r\n        return true;\r\n    } else {\r\n        return false;\r\n    }\r\n}\r\n\r\n// Minimum ratio test to determine pivot row.\r\nint minRatioTest(const MatrixXd &tableau, const int &pivotCol) {\r\n    const int dim = tableau.rows();\r\n\r\n    VectorXd ratioTest = VectorXd::Zero(dim);\r\n    for (int i = 0; i < dim; i++) {\r\n        ratioTest[i] = tableau.coeff(i, 2*dim + 1) / tableau.coeff(i, pivotCol);\r\n        if (ratioTest[i] < 0) {\r\n            ratioTest[i] = 1e10;\r\n        }\r\n    }\r\n    \r\n    int pivotRow {0};\r\n    double minRatio = ratioTest[0];\r\n    for (int i = 1; i < dim; i++) {\r\n        if (ratioTest[i] < minRatio) {\r\n            minRatio = ratioTest[i];\r\n            pivotRow = i;\r\n        }\r\n    }\r\n\r\n    return pivotRow;\r\n}\r\n\r\n// Extract solution from tableau.\r\nMatrixXd extractSolution(const MatrixXd &tableau) {\r\n    const int dim = tableau.rows();\r\n    MatrixXd A = MatrixXd::Zero(dim, 2*dim);\r\n    VectorXd z = VectorXd::Zero(dim);\r\n    VectorXd w = VectorXd::Zero(dim);\r\n    VectorXd isBasic = basicVars(tableau);\r\n    \r\n    for (int i = 0; i < 2*dim; i++)\r\n        if (isBasic[i] == 1)\r\n            A.col(i) = tableau.col(i);\r\n\r\n    for (int i = 0; i < 2*dim; i++) {\r\n        if (i < dim) {\r\n            w[i] = A.col(i).dot(tableau.col(2*dim + 1));\r\n        } else {\r\n            z[i-dim] = A.col(i).dot(tableau.col(2*dim + 1));\r\n        }\r\n    }\r\n\r\n    MatrixXd sols = MatrixXd::Zero(dim, 2);\r\n    sols.col(0) = z;\r\n    sols.col(1) = w;\r\n    return sols;\r\n}\r\n", "meta": {"hexsha": "8f5da3404484ef0ff97fe8866d4dee62426d9740", "size": 8535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LCPSolve.cpp", "max_stars_repo_name": "Tom-Forsyth/LCPSolve", "max_stars_repo_head_hexsha": "046312adbc3dec07b9c58a65d54eea89aec89c12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LCPSolve.cpp", "max_issues_repo_name": "Tom-Forsyth/LCPSolve", "max_issues_repo_head_hexsha": "046312adbc3dec07b9c58a65d54eea89aec89c12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LCPSolve.cpp", "max_forks_repo_name": "Tom-Forsyth/LCPSolve", "max_forks_repo_head_hexsha": "046312adbc3dec07b9c58a65d54eea89aec89c12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7386759582, "max_line_length": 123, "alphanum_fraction": 0.5681312244, "num_tokens": 2257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6443532441146725}}
{"text": "// Boost.Geometry\n// Unit Test\n\n// Copyright (c) 2019 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2019.\n// Modifications copyright (c) 2019, 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#include <geometry_test_common.hpp>\n\n#include <boost/geometry/algorithms/detail/make/make.hpp>\n#include <boost/geometry/geometries/infinite_line.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/util/math.hpp>\n\nnamespace\n{\n    // Boost.Test does not support BOOST_CHECK_CLOSE for integral types\n    template <typename T>\n    bool is_small(T const& value)\n    {\n        static long double const epsilon = 1.0e-5;\n        return bg::math::abs(value) < epsilon;\n    }\n}\n\ntemplate <typename T, typename C>\nvoid verify_point_on_line(bg::model::infinite_line<T> const& line,\n                          C const& x, C const& y)\n{\n    BOOST_CHECK_MESSAGE(is_small(line.a * x + line.b * y + line.c),\n                        \"Point is not located on the line\");\n}\n\ntemplate <typename T>\nvoid test_make()\n{\n    typedef bg::model::infinite_line<T> line_type;\n\n    // Horizontal through origin\n    line_type line = bg::detail::make::make_infinite_line<T>(0, 0, 10, 0);\n    verify_point_on_line(line, 0, 0);\n    verify_point_on_line(line, 10, 0);\n\n    // Horizontal line above origin\n    line = bg::detail::make::make_infinite_line<T>(0, 5, 10, 5);\n    verify_point_on_line(line, 0, 5);\n    verify_point_on_line(line, 10, 5);\n\n    // Vertical through origin\n    line = bg::detail::make::make_infinite_line<T>(0, 0, 0, 10);\n    verify_point_on_line(line, 0, 0);\n    verify_point_on_line(line, 0, 10);\n\n    // Vertical line left from origin\n    line = bg::detail::make::make_infinite_line<T>(5, 0, 5, 10);\n    verify_point_on_line(line, 5, 0);\n    verify_point_on_line(line, 5, 10);\n\n    // Diagonal through origin\n    line = bg::detail::make::make_infinite_line<T>(0, 0, 8, 10);\n    verify_point_on_line(line, 0, 0);\n    verify_point_on_line(line, 8, 10);\n\n    // Diagonal not through origin\n    line = bg::detail::make::make_infinite_line<T>(5, 2, -8, 10);\n    verify_point_on_line(line, 5, 2);\n    verify_point_on_line(line, -8, 10);\n}\n\n\ntemplate <typename T>\nvoid test_all()\n{\n    test_make<T>();\n}\n\nint test_main(int, char* [])\n{\n    test_all<double>();\n    test_all<long double>();\n    test_all<float>();\n    test_all<int>();\n    return 0;\n}\n", "meta": {"hexsha": "a69b43137e81735b06ce54b392590e558a424f8e", "size": 2628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/geometries/infinite_line.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": "test/geometries/infinite_line.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/test/geometries/infinite_line.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": 28.8791208791, "max_line_length": 79, "alphanum_fraction": 0.6731354642, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6443532439399907}}
{"text": "/*\n utils.hxx\n\n Copyright (c) 2018 Guy Skinner\n\n This file is distributed under the terms of the MIT license.\n Please see the file 'LICENCE.txt' in the root directory\n or http://opensource.org/licenses/mit-license.php for information.\n*/\n\n#pragma once\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/range/numeric.hpp>\n#include <functional>\n#include <vector>\n\nnamespace ublas = boost::numeric::ublas;\n\ndouble det3(ublas::matrix<double> a);\n\nublas::vector<double> cross3(ublas::vector<double> a,\n                             ublas::vector<double> b);\n\nublas::matrix<double> inv3(ublas::matrix<double> a);\n\nlong linear_search(const std::vector<double>& vec,\n\t\t   double a,\n\t\t   double tol);\n\ninline long product(ublas::vector<long> vec) {\n  return boost::accumulate(vec,1,std::multiplies<long>());\n}\n", "meta": {"hexsha": "915a7a0b4efee519cddc01cba4e3b79342e5a264", "size": 851, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/utils.hxx", "max_stars_repo_name": "gcgs1/cxx.sqs", "max_stars_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.hxx", "max_issues_repo_name": "gcgs1/cxx.sqs", "max_issues_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.hxx", "max_forks_repo_name": "gcgs1/cxx.sqs", "max_forks_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3142857143, "max_line_length": 67, "alphanum_fraction": 0.7074030552, "num_tokens": 210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6443532390079888}}
{"text": "\r\n//  (C) Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_SPECIAL_LEGENDRE_HPP\r\n#define BOOST_MATH_SPECIAL_LEGENDRE_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n#include <boost/math/special_functions/factorials.hpp>\r\n#include <boost/math/tools/config.hpp>\r\n\r\nnamespace boost{\r\nnamespace math{\r\n\r\n// Recurrance relation for legendre P and Q polynomials:\r\ntemplate <class T1, class T2, class T3>\r\ninline typename tools::promote_args<T1, T2, T3>::type\r\n   legendre_next(unsigned l, T1 x, T2 Pl, T3 Plm1)\r\n{\r\n   typedef typename tools::promote_args<T1, T2, T3>::type result_type;\r\n   return ((2 * l + 1) * result_type(x) * result_type(Pl) - l * result_type(Plm1)) / (l + 1);\r\n}\r\n\r\nnamespace detail{\r\n\r\n// Implement Legendre P and Q polynomials via recurrance:\r\ntemplate <class T, class Policy>\r\nT legendre_imp(unsigned l, T x, const Policy& pol, bool second = false)\r\n{\r\n   static const char* function = \"boost::math::legrendre_p<%1%>(unsigned, %1%)\";\r\n   // Error handling:\r\n   if((x < -1) || (x > 1))\r\n      return policies::raise_domain_error<T>(\r\n         function,\r\n         \"The Legendre Polynomial is defined for\"\r\n         \" -1 <= x <= 1, but got x = %1%.\", x, pol);\r\n\r\n   T p0, p1;\r\n   if(second)\r\n   {\r\n      // A solution of the second kind (Q):\r\n      p0 = (boost::math::log1p(x, pol) - boost::math::log1p(-x, pol)) / 2;\r\n      p1 = x * p0 - 1;\r\n   }\r\n   else\r\n   {\r\n      // A solution of the first kind (P):\r\n      p0 = 1;\r\n      p1 = x;\r\n   }\r\n   if(l == 0)\r\n      return p0;\r\n\r\n   unsigned n = 1;\r\n\r\n   while(n < l)\r\n   {\r\n      std::swap(p0, p1);\r\n      p1 = boost::math::legendre_next(n, x, p0, p1);\r\n      ++n;\r\n   }\r\n   return p1;\r\n}\r\n\r\n} // namespace detail\r\n\r\ntemplate <class T, class Policy>\r\ninline typename boost::enable_if_c<policies::is_policy<Policy>::value, typename tools::promote_args<T>::type>::type\r\n   legendre_p(int l, T x, const Policy& pol)\r\n{\r\n   typedef typename tools::promote_args<T>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   static const char* function = \"boost::math::legendre_p<%1%>(unsigned, %1%)\";\r\n   if(l < 0)\r\n      return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_imp(-l-1, static_cast<value_type>(x), pol, false), function);\r\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_imp(l, static_cast<value_type>(x), pol, false), function);\r\n}\r\n\r\ntemplate <class T>\r\ninline typename tools::promote_args<T>::type \r\n   legendre_p(int l, T x)\r\n{\r\n   return boost::math::legendre_p(l, x, policies::policy<>());\r\n}\r\n\r\ntemplate <class T, class Policy>\r\ninline typename boost::enable_if_c<policies::is_policy<Policy>::value, typename tools::promote_args<T>::type>::type\r\n   legendre_q(unsigned l, T x, const Policy& pol)\r\n{\r\n   typedef typename tools::promote_args<T>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_imp(l, static_cast<value_type>(x), pol, true), \"boost::math::legendre_q<%1%>(unsigned, %1%)\");\r\n}\r\n\r\ntemplate <class T>\r\ninline typename tools::promote_args<T>::type \r\n   legendre_q(unsigned l, T x)\r\n{\r\n   return boost::math::legendre_q(l, x, policies::policy<>());\r\n}\r\n\r\n// Recurrence for associated polynomials:\r\ntemplate <class T1, class T2, class T3>\r\ninline typename tools::promote_args<T1, T2, T3>::type \r\n   legendre_next(unsigned l, unsigned m, T1 x, T2 Pl, T3 Plm1)\r\n{\r\n   typedef typename tools::promote_args<T1, T2, T3>::type result_type;\r\n   return ((2 * l + 1) * result_type(x) * result_type(Pl) - (l + m) * result_type(Plm1)) / (l + 1 - m);\r\n}\r\n\r\nnamespace detail{\r\n// Legendre P associated polynomial:\r\ntemplate <class T, class Policy>\r\nT legendre_p_imp(int l, int m, T x, T sin_theta_power, const Policy& pol)\r\n{\r\n   // Error handling:\r\n   if((x < -1) || (x > 1))\r\n      return policies::raise_domain_error<T>(\r\n      \"boost::math::legendre_p<%1%>(int, int, %1%)\",\r\n         \"The associated Legendre Polynomial is defined for\"\r\n         \" -1 <= x <= 1, but got x = %1%.\", x, pol);\r\n   // Handle negative arguments first:\r\n   if(l < 0)\r\n      return legendre_p_imp(-l-1, m, x, sin_theta_power, pol);\r\n   if(m < 0)\r\n   {\r\n      int sign = (m&1) ? -1 : 1;\r\n      return sign * boost::math::tgamma_ratio(static_cast<T>(l+m+1), static_cast<T>(l+1-m), pol) * legendre_p_imp(l, -m, x, sin_theta_power, pol);\r\n   }\r\n   // Special cases:\r\n   if(m > l)\r\n      return 0;\r\n   if(m == 0)\r\n      return boost::math::legendre_p(l, x, pol);\r\n\r\n   T p0 = boost::math::double_factorial<T>(2 * m - 1, pol) * sin_theta_power;\r\n\r\n   if(m&1)\r\n      p0 *= -1;\r\n   if(m == l)\r\n      return p0;\r\n\r\n   T p1 = x * (2 * m + 1) * p0;\r\n\r\n   int n = m + 1;\r\n\r\n   while(n < l)\r\n   {\r\n      std::swap(p0, p1);\r\n      p1 = boost::math::legendre_next(n, m, x, p0, p1);\r\n      ++n;\r\n   }\r\n   return p1;\r\n}\r\n\r\ntemplate <class T, class Policy>\r\ninline T legendre_p_imp(int l, int m, T x, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   // TODO: we really could use that mythical \"pow1p\" function here:\r\n   return legendre_p_imp(l, m, x, static_cast<T>(pow(1 - x*x, T(abs(m))/2)), pol);\r\n}\r\n\r\n}\r\n\r\ntemplate <class T, class Policy>\r\ninline typename tools::promote_args<T>::type\r\n   legendre_p(int l, int m, T x, const Policy& pol)\r\n{\r\n   typedef typename tools::promote_args<T>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_p_imp(l, m, static_cast<value_type>(x), pol), \"bost::math::legendre_p<%1%>(int, int, %1%)\");\r\n}\r\n\r\ntemplate <class T>\r\ninline typename tools::promote_args<T>::type\r\n   legendre_p(int l, int m, T x)\r\n{\r\n   return boost::math::legendre_p(l, m, x, policies::policy<>());\r\n}\r\n\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif // BOOST_MATH_SPECIAL_LEGENDRE_HPP\r\n\r\n\r\n\r\n", "meta": {"hexsha": "dc0154238ab98a40cd89bbf535a8feea9bd92f33", "size": 6167, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/legendre.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/legendre.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/legendre.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 31.6256410256, "max_line_length": 176, "alphanum_fraction": 0.6377493108, "num_tokens": 1821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6443532390079887}}
{"text": "#include \"srrg_geometry/geometry3d.h\"\n#include <iostream>\n#include <Eigen/StdVector>\n#include \"srrg_autodiff/ad_multivariate.h\"\n\nusing namespace std;\nusing namespace srrg2_core;\nusing namespace srrg2_core::geometry3d;\n\nusing namespace Eigen;\n\ntypedef srrg2_core::Vector2ad<float> Vector2adf;\ntypedef srrg2_core::Vector3ad<float> Vector3adf;\ntypedef srrg2_core::Vector6ad<float> Vector6adf;\ntypedef srrg2_core::Matrix3ad<float> Matrix3adf;\ntypedef srrg2_core::DualValue_<float> DualValuef;\ntypedef srrg2_core::Isometry3ad<float> Isometry3adf;\n\n\n\n  \ntemplate <typename Scalar_>\nclass TransformPoint: public MultivariateFunction<Scalar_, 6, 3>{\npublic:\n  void operator()(Scalar_* output, const Scalar_* input){\n\n    // this maps the memory area in the input array to an\n    // Eigen vector of dimension 6\n    // if you feel uncomfy, you can\n    // allocate an array\n    //   Vector6<Scalar_> robot_pose;\n    // fill the elements with a for loop\n    //    for (int i=0; i<6; i++) robot_pose[i]=input[i];\n    Eigen::Map<const Eigen::Matrix<Scalar_,6,1> > robot_pose(input);\n\n    // this maps the memory area in the output array to an\n    // Eigen vector of dimension 3\n    // Changing the Eigen object would result\n    // in doing side effect to the memory area\n    Eigen::Map<Eigen::Matrix<Scalar_,3,1> > projected_point(output);\n\n    \n    // compute the rotation matrix and translation vector\n    // encoded in robot_pose\n    Isometry3_<Scalar_> robot_pose_matrix=v2t<Scalar_>(robot_pose);\n   \n    // compute the positionof the point w.r.t. the world,\n    // by multiplying it by a transformation matrix \n    projected_point=robot_pose_matrix*point;\n  }\n\n  // this is the parameter\n  Eigen::Matrix<Scalar_, 3, 1> point;\n};\n\n\n// this is our function that supports the multivariate autodiff\nADMultivariateFunction<double, TransformPoint> ad_project_point;\n\n\n  \ntemplate <typename Scalar_>\nclass TransformMovingPoint: public MultivariateFunction<Scalar_, 9, 3>{\npublic:\n  void operator()(Scalar_* output, const Scalar_* input){\n\n    // this maps the memory area in the input array to an\n    // Eigen vector of dimension 6\n    // if you feel uncomfy, you can\n    // allocate an array\n    //   Vector6<Scalar_> robot_pose;\n    // fill the elements with a for loop\n    //    for (int i=0; i<6; i++) robot_pose[i]=input[i];\n    Eigen::Map<const Eigen::Matrix<Scalar_,6,1> > robot_pose(input);\n    Eigen::Map<const Eigen::Matrix<Scalar_,3,1> > point(input+6);\n\n    \n    // this maps the memory area in the output array to an\n    // Eigen vector of dimension 3\n    // Changing the Eigen object would result\n    // in doing side effect to the memory area\n    Eigen::Map<Eigen::Matrix<Scalar_,3,1> > projected_point(output);\n\n    \n    // compute the rotation matrix and translation vector\n    // encoded in robot_pose\n    Isometry3_<Scalar_> robot_pose_matrix=v2t<Scalar_>(robot_pose);\n   \n    // compute the positionof the point w.r.t. the world,\n    // by multiplying it by a transformation matrix \n    projected_point=robot_pose_matrix*point;\n  }\n};\n\ntemplate <typename Scalar_>\nclass TransformMovingPoint2: public MultivariateFunction<Scalar_, 9, 3>{\npublic:\n  void operator()(Scalar_* output, const Scalar_* input){\n\n    // this maps the memory area in the input array to an\n    // Eigen vector of dimension 6\n    // if you feel uncomfy, you can\n    // allocate an array\n    //   Vector6<Scalar_> robot_pose;\n    // fill the elements with a for loop\n    //    for (int i=0; i<6; i++) robot_pose[i]=input[i];\n    Eigen::Map<const Eigen::Matrix<Scalar_,6,1> > robot_pose_pert(input);\n    Eigen::Map<const Eigen::Matrix<Scalar_,3,1> > point_pert(input+6);\n\n    \n    // this maps the memory area in the output array to an\n    // Eigen vector of dimension 3\n    // Changing the Eigen object would result\n    // in doing side effect to the memory area\n    Eigen::Map<Eigen::Matrix<Scalar_,3,1> > projected_point(output);\n\n    \n    // compute the rotation matrix and translation vector\n    // encoded in robot_pose\n    Isometry3_<Scalar_> robot_pose_matrix=v2t<Scalar_>(robot_pose_pert)*_robot_pose;\n   \n    // compute the positionof the point w.r.t. the world,\n    // by multiplying it by a transformation matrix \n    projected_point=robot_pose_matrix*(_point+point_pert);\n  }\n  Isometry3_<Scalar_> _robot_pose;\n  Vector3_<Scalar_> _point;\n};\n\n\n\n// this is our function that supports the multivariate autodiff\nADMultivariateFunction<double, TransformMovingPoint> ad_move_point;\n\nADMultivariateFunction<double, TransformMovingPoint2> ad_move_point_manifold;\n\nint main(int argc, char** argv){\n  ad_project_point.point<<1,2,3;\n  ad_project_point.point<<1,2,3;\n\n  Eigen::Matrix<double, 6, 1> v;\n  v << 0,0,0,0,0,0;\n  \n  Eigen::Matrix<double, 3, 1> output;\n  Eigen::Matrix<double, 3, 6> jacobian;\n  \n  ad_project_point(&output[0], &v[0]);\n  jacobian=ad_project_point.jacobian(&v[0]);\n\n  cerr << \"output: \" << endl;\n  cerr << output.transpose() << endl;\n  cerr << \"jacobian: \" << endl;\n  cerr << jacobian << endl;\n\n  cerr << endl  << endl;\n  Eigen::Matrix<double, 9, 1> pose_and_point;\n  Eigen::Matrix<double, 3, 9> jacobian_move;\n  pose_and_point.head<6>()=v;\n  pose_and_point.tail<3>() << 1,2,3;\n  cerr << \"pose_and_point: \" <<pose_and_point.transpose() << endl;\n  ad_move_point(&output[0], &pose_and_point[0]);\n  jacobian_move=ad_move_point.jacobian(&pose_and_point[0]);\n  cerr << \"jacobian: \" << endl;\n  cerr << jacobian_move << endl;\n\n  cerr << \"pose_and_point (zero pert): \" <<pose_and_point.transpose() << endl;\n  ad_move_point_manifold._robot_pose.setIdentity();\n  ad_move_point_manifold._point << 1,2,3;\n  ad_move_point_manifold(&output[0]);\n  jacobian_move=ad_move_point_manifold.jacobian();\n  cerr << \"jacobian: \" << endl;\n  cerr << jacobian_move << endl;\n\n}\n", "meta": {"hexsha": "26c3064af5bff6f19aadd8440e5fc755049c1d4c", "size": 5749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/deprecated/srrg_autodiff_multivariate_example.cpp", "max_stars_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_stars_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/deprecated/srrg_autodiff_multivariate_example.cpp", "max_issues_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_issues_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/srrg2_core/srrg2_core/deprecated/srrg_autodiff_multivariate_example.cpp", "max_forks_repo_name": "laaners/progetto-labiagi_pick_e_delivery", "max_forks_repo_head_hexsha": "3453bfbc1dd7562c78ba06c0f79b069b0a952c0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8514285714, "max_line_length": 84, "alphanum_fraction": 0.7051661158, "num_tokens": 1563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.644353238658624}}
{"text": "// SGFilter.h \n// \n// Implenetation of the Savitzky-Golay Filter in cpp (Arduino/Teensy) \n//\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <unistd.h>\n#include <iostream>\n\nnamespace openvslam\n{\n\n    class SGFilter\n    {\n\tpublic:\n        struct DATA \n\t\t{\n\t    float yRaw = 0.0F;\n            float y = 0.0F;\n            float yDot = 0.0F;\n\t\t};\n\n        // Methods\n        SGFilter(uint32_t poly_order, uint32_t filter_size);\n\n        void update(float new_time_float, float new_val);\n        void debug_print_A(void);\n        float powFast(float x, uint32_t n);    \n\n        // Attributes\n        uint32_t poly_order_;\n        uint32_t filter_size_;\n\n        uint32_t filter_iter_;\n        uint32_t current_line_;\n\n        float zero_time_;\n        float filter_value_;\n\n        Eigen::VectorXf f_; // Vector of function values \n        Eigen::VectorXf t_; // Vector of time slots\n        Eigen::MatrixXf A_; // Matrix of Least-Squares coefficients \n        Eigen::VectorXf c_; // Vector of Polynomial coefficients\n        DATA data_;\n    };\n}", "meta": {"hexsha": "ed655f342f1b32c9d4572044916eaac77d1eecb6", "size": 1069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/openvslam/helper/SGFilter.hpp", "max_stars_repo_name": "surfii3z/openvslam", "max_stars_repo_head_hexsha": "0547607fff7363619163cf017bec0886e9c7083c", "max_stars_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-11-29T10:53:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:12:45.000Z", "max_issues_repo_path": "src/openvslam/helper/SGFilter.hpp", "max_issues_repo_name": "surfii3z/openvslam", "max_issues_repo_head_hexsha": "0547607fff7363619163cf017bec0886e9c7083c", "max_issues_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-30T08:31:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T12:28:57.000Z", "max_forks_repo_path": "src/openvslam/helper/SGFilter.hpp", "max_forks_repo_name": "surfii3z/openvslam", "max_forks_repo_head_hexsha": "0547607fff7363619163cf017bec0886e9c7083c", "max_forks_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-05-05T12:46:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T12:21:38.000Z", "avg_line_length": 22.2708333333, "max_line_length": 70, "alphanum_fraction": 0.6117867166, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6443532342506683}}
{"text": "/*******************************************************************************\n *         Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II\n *         Copyright 2009 & onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n *\n *          Distributed under the Boost Software License, Version 1.0.\n *                 See accompanying file LICENSE.txt or copy at\n *                     http://www.boost.org/LICENSE_1_0.txt\n ******************************************************************************/\n#ifndef NT2_SDK_MEMORY_META_IS_POWER_OF_2_HPP_INCLUDED\n#define NT2_SDK_MEMORY_META_IS_POWER_OF_2_HPP_INCLUDED\n\n#include <cstddef>\n#include <boost/mpl/bool.hpp>\n\nnamespace nt2 { namespace meta\n{\n  //////////////////////////////////////////////////////////////////////////////\n  // Boolean meta-function checking if a Integral Constant is a power of 2\n  // Documentation: is_power_of_2.rst\n  //////////////////////////////////////////////////////////////////////////////\n  template<std::size_t N>\n  struct is_power_of_2_c : boost::mpl::bool_<(!(N & (N - 1)) && N)> {};\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Boolean meta-function checking if a compile-time integral is a power of 2\n  // Documentation: is_power_of_2_c.rst\n  //////////////////////////////////////////////////////////////////////////////\n  template<class N>\n  struct is_power_of_2 : is_power_of_2_c<N::value> {};\n} }\n\n#endif\n", "meta": {"hexsha": "29e2220e3eaf8641c22718b8a034b20ef447bf52", "size": 1444, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/sdk/include/nt2/sdk/memory/meta/is_power_of_2.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/sdk/include/nt2/sdk/memory/meta/is_power_of_2.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/sdk/include/nt2/sdk/memory/meta/is_power_of_2.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7575757576, "max_line_length": 80, "alphanum_fraction": 0.4626038781, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.6443340163541174}}
{"text": "#include \"InfiniteRoots.h\"\n#include \"HomotopyContinuation.h\"\n#include <boost/math/tools/polynomial.hpp>\n\nusing namespace boost::math;\nusing namespace boost::math::tools; // for polynomial\n\nInfiniteRoots::InfiniteRoots(int L, int M) {\n    _L = L;\n    _M = M;\n    _roots.resize(M);\n}\n\nstd::vector<var_t>& InfiniteRoots::getRoot(int m)\n{\n    if (_roots[m-1].size() == 0) {\n        computeRoots(m);\n    }\n    \n    return _roots[m-1];\n}\n\nstd::vector<var_t> InfiniteRoots::equationSolver(std::vector<var_t> &coefs, std::vector<var_t> &out) {\n    if (coefs.size() == 2) {\n        return { -coefs[0]/coefs[1] };\n    }\n    if (coefs.size() <= 1) {\n        return {};\n    }\n    \n    PolynomialFunction target(coefs);\n    UnityEquation start(1, coefs.size() - 1);\n    \n    SimpleHomotopy hom(&start, &target);\n    hom.setSteps(coefs.size() * 300);\n    hom.setRandSeed(coefs.size());\n    SimpleHomotopyContinuation hc;\n    \n    std::vector<var_t> ret;\n    \n    for (int i = 0; i < start.numberOfRoots(); i++) {\n        Vector root = start.getRoot(i);\n        Solution sol(root);\n        hc.solve(hom, sol);\n        bool found = false;\n        for (int j = 0; j < ret.size(); j++) {\n            if (std::abs(ret[j] - sol.get(0)) < EPS) {\n                found = true;\n                break;\n            }\n        }\n        if (!found) {\n            ret.push_back(sol.get(0));\n        }\n    }\n    \n    // it produced some duplicated roots\n    if (ret.size() < start.numberOfRoots()) {\n        polynomial<var_t> eq(coefs.begin(), coefs.end());\n        polynomial<var_t> eq2 {{var_t(1.0L, 0.0L)}};\n        for (int i = 0; i < ret.size(); i++) {\n            polynomial<var_t> solved {{-ret[i], var_t(1.0L, 0)}}; \n            eq2 *= solved;\n        }\n        polynomial<var_t> eq3 = eq / eq2;\n        out = eq3.data();\n    }\n    return ret;\n}\n\nvoid InfiniteRoots::computeRoots(int m) {\n    std::vector<var_t> coefs(m + 1);\n    elem_t r = 1.0L;\n    int R = _L - 2 * _M + 2 * m;\n    for (int i = 0; i <= m; i++) {\n        coefs[i] = var_t(r, 0.0L);\n        r *= -(m-i) * (2 * _L) / (elem_t)((R - i) *  (i+1));\n    }\n    reverse(coefs.begin(), coefs.end());\n    while (true) {\n        std::vector<var_t> remain;\n        std::vector<var_t> res = equationSolver(coefs, remain);\n        _roots[m-1].insert(_roots[m-1].end(), res.begin(), res.end());\n//        std::cout << \"roots=\" << _roots[m-1] << \" remain=\" << remain << std::endl;\n        if (remain.size() <= 1) break;\n        coefs = remain;\n    }\n}\n", "meta": {"hexsha": "1dd49a8f91b5f7b28433b8b9d7ed253c37d05dfc", "size": 2482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/InfiniteRoots.cpp", "max_stars_repo_name": "gaolichen/bethesolver", "max_stars_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/InfiniteRoots.cpp", "max_issues_repo_name": "gaolichen/bethesolver", "max_issues_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/InfiniteRoots.cpp", "max_forks_repo_name": "gaolichen/bethesolver", "max_forks_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8876404494, "max_line_length": 102, "alphanum_fraction": 0.5221595488, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6443331785530416}}
{"text": "\r\n#include <SDKApplication.hpp>\r\n\r\n#include <float.h>\r\n#include <vector>\r\n#include <map>\r\n\r\n#include <boost/program_options.hpp>\r\n\r\n#include <clutil.h>\r\n#include <CMat.h>\r\n\r\nusing namespace std;\r\n\r\n#define PROGRAM_FILE \"matvec.cl\"\r\n#define KERNEL_FUNC \"matvec_mult\"\r\n\r\n#define NROUND 64\r\n\r\nbool Near(float t1, float t2, float div = 10000)\r\n{\r\n    return  fabs(t1-t2) < t1/div;\r\n}\r\n\r\nclass MatVec: public SDKSample\r\n{\r\npublic:\r\n    ClContextPtr   pContext;\r\n    ClKernelPtr pKernel, pKrnMult, pKrnSum, pKernelMatMat;\r\n    ClCmdQPtr   pCmdQ;\r\n    ClProgramPtr pProgram;\r\n    ClDevice     *pDevice;\r\n    const cl_uint M, N, K;\r\n    cl_uint       RM, RN, RK;\r\n    CMat<float> mat, vec, result, correct;\r\n    ClMemPtr mat_mem, vec_mem, res_mem;\r\n    int timer;\r\n    cl_double gpuTime, cpuTime;\r\n    MatVec(const char *name):\r\n        SDKSample(name)\r\n//            , M(8), N(10), K(10)\r\n      ,M(1024), N(1024), K(1024)\r\n      , RM(clCeiling<NROUND>(M)), RN(clCeiling<NROUND>(N)), RK(clCeiling<NROUND>(K))\r\n      , mat((unsigned long)RM,(unsigned long)RN)\r\n      , vec((unsigned long)RN, (unsigned long)RK)\r\n      , result((unsigned long)RM, (unsigned long)RK)\r\n      , correct((unsigned long)M, (unsigned long)K){}\r\n\r\n    virtual int setup()\r\n    {\r\n        std::vector<ClKernelPtr> vecKrn;\r\n        vecKrn = ClPlatform::createSimpleKernel(std::cout, platformId, PROGRAM_FILE, \"matmat_mult\");\r\n        if(vecKrn.size() == 0) {\r\n            printf(\"Failed to create kernel!\\n\");\r\n            return SDK_FAILURE;\r\n        }\r\n        pKernel = vecKrn[0];\r\n        pProgram = pKernel->pProgram;\r\n        pContext =  pProgram->pContext;\r\n        pDevice = pContext->devices[deviceId];\r\n        pCmdQ = pContext->createCmdQ(pDevice);\r\n        if( sizeof(float)*(M*N+N*K+M*K) >= pContext->devices[deviceId]->maxMemAllocSize ) {\r\n            printf(\"Larger than device maxMemAllocSize %ld >= %ld\\n\", sizeof(float)*(M*N+N*K+M*K), pDevice->maxMemAllocSize);\r\n            return SDK_FAILURE;\r\n        }\r\n        if( NULL == (pKernelMatMat = pProgram->createKernel(\"matmat_mult\") ) ) {\r\n            cout << \"failed to created kernel matmat_mult\" << endl;\r\n            return SDK_FAILURE;\r\n        }\r\n\r\n        if( NULL == (pKrnMult = pProgram->createKernel(\"matvecmult_mult\") ) ) {\r\n            cout << \"failed to created kernel matvecmult_mult\" << endl;\r\n            return SDK_FAILURE;\r\n        }\r\n        if( NULL == (pKrnSum = pProgram->createKernel(\"matvecmult_sum\") ) ) {\r\n            cout << \"failed to created kernel matvecmult_sum\" << endl;\r\n            return SDK_FAILURE;\r\n        }\r\n\r\n        /* Initialize data to be processed by the kernel */\r\n        mat = (float)0.0;\r\n        vec = (float)0.0;\r\n        for(int i=0; i<N; ++i) {\r\n            for(int j=0; j<M; ++j)\r\n                mat(j,i)  = (i+j) *2.0;\r\n            for(int j=0; j<K; ++j)\r\n                vec(i,j) = i*3.0;\r\n        }\r\n        timer = sampleCommon->createTimer();\r\n        sampleCommon->resetTimer(timer);\r\n\r\n        sampleCommon->startTimer(timer);\r\n        correct = mat * vec;\r\n        double t = mat(0,0) *vec(0,0);\r\n//        for(int i=0;i<M; ++i)\r\n//            for(int j=0; j<K; ++j) {\r\n//                float *cor = &correct(i,j), *a = &mat(i,0);\r\n//                cor[0] = 0;\r\n//                for(int k=0; k<N; ++k, ++a)\r\n//                    cor[0] += a[0] * vec.ptr()[k*N + j];\r\n//            }\r\n        sampleCommon->stopTimer(timer);\r\n        cpuTime = sampleCommon->readTimer(timer);\r\n        sampleCommon->resetTimer(timer);\r\n        cout << \"Matrix size: (\" <<M << \",\" <<N <<\",\" <<K << \")    CPU time:\" << cpuTime << endl;\r\n\r\n\r\n        mat_mem = pContext->createMem(CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(float)*RM*RN, &mat[0]);\r\n        if( ! mat_mem ) {\r\n            printf(\"Failed to create mat_mem!\\n\");\r\n            return SDK_FAILURE;\r\n        }\r\n        vec_mem = pContext->createMem(CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float)*RN*RK, &vec[0]);\r\n        res_mem = pContext->createMem(CL_MEM_WRITE_ONLY, sizeof(float)*RM*RK, NULL);\r\n        if( ! res_mem ) {\r\n            printf(\"Failed to create res_mem!\\n\");\r\n            return SDK_FAILURE;\r\n        }\r\n\r\n\r\n        return SDK_SUCCESS;\r\n\r\n    }\r\n\r\n    virtual int initialize()\r\n    {\r\n        // Call base class Initialize to get default configuration\r\n        if(this->SDKSample::initialize())\r\n            return SDK_FAILURE;\r\n        return SDK_SUCCESS;\r\n    }\r\n    int runMatVec()\r\n    {\r\n        size_t globalsize;\r\n        sampleCommon->startTimer(timer);\r\n        if( CL_SUCCESS  != pKernel->setArgs(0, mat_mem, vec_mem, res_mem, M, N) ) {\r\n            printf(\"Failed to set arg!\\n\");\r\n            return SDK_FAILURE;\r\n        }\r\n        globalsize = M;\r\n        cl_event evts[3];\r\n        pCmdQ->enqueue(pKernel, 1, NULL, &globalsize, NULL, 0, NULL, &evts[0] );\r\n        pCmdQ->enqueueRead(res_mem, CL_FALSE, 0, sizeof(float)*M, &result[0], 1, &evts[0], &evts[1]);\r\n        clWaitForEvents(1, &evts[1]);\r\n        for(int i=0; i < 2; ++i)\r\n            clReleaseEvent(evts[i]);\r\n\r\n        sampleCommon->stopTimer(timer);\r\n        cl_double gpuTime = sampleCommon->readTimer(timer);\r\n        cout << \" Device Timing:\" << gpuTime << endl;\r\n        return SDK_SUCCESS;\r\n    }\r\n    int runMatMat()\r\n    {\r\n        cl_int status=CL_SUCCESS;\r\n        bool USE_MAP = true;\r\n\r\n        const size_t NDIM = 2;\r\n        size_t globalsize[NDIM] = {RM/4, RK/4};\r\n        size_t localsize[NDIM] = {16, 16};\r\n\r\n        ExecKernel exKrn(pKernelMatMat, pCmdQ, NDIM, globalsize, localsize);\r\n        MapMem     exMap(pKernelMatMat, pCmdQ, res_mem);\r\n        ReadWriteMem    exRead(pKernelMatMat, pCmdQ, res_mem, &result[0], true);\r\n\r\n        status = pKernelMatMat->validSizes(deviceId, NDIM, globalsize, localsize);\r\n        CHECK_OPENCL_ERROR(status, \"invalid localsize\");\r\n\r\n        sampleCommon->resetTimer(timer);\r\n        sampleCommon->startTimer(timer);\r\n        status = pKernelMatMat->setArgs(0, mat_mem, vec_mem, res_mem, RM, RN, RK);\r\n        CHECK_OPENCL_ERROR(status, \"Failed to set Args\");\r\n        CHECK_OPENCL_ERROR(exKrn(), \"Failed to execute kernel\");\r\n\r\n        if( !USE_MAP ) {\r\n            CHECK_OPENCL_ERROR(exRead(), \"Failed to read mem\");\r\n        }else{\r\n\r\n            CHECK_OPENCL_ERROR(exMap.map(), \"Failed to map read mem\");\r\n            memcpy(&result[0], exMap.ptr, sizeof(cl_float) * RM  * RK);\r\n            CHECK_OPENCL_ERROR(exMap.unmap(), \"Failed to unmap read mem\");\r\n        }\r\n\r\n\r\n        sampleCommon->stopTimer(timer);\r\n        cl_double gpuTime = sampleCommon->readTimer(timer);\r\n        cout << \" Device Timing:\" << gpuTime << endl;\r\n        return SDK_SUCCESS;\r\n    }\r\n    int runMultiStage()\r\n    {\r\n        size_t globalsize;\r\n        /* Data and buffers */\r\n        if( CL_SUCCESS  != pKrnMult->setArgs(0, mat_mem, vec_mem,  M, N) )\r\n        {\r\n            printf(\"Failed to set arg!\\n\");\r\n            return SDK_FAILURE;\r\n        }\r\n        if( CL_SUCCESS  != pKrnSum->setArgs(0, mat_mem, res_mem,  M, N) )\r\n        {\r\n            printf(\"Failed to set arg!\\n\");\r\n            return SDK_FAILURE;\r\n        }\r\n\r\n        globalsize= M*N;\r\n        cl_event evts[3];\r\n\r\n        pCmdQ->enqueue(pKrnMult, 1, NULL, &globalsize, NULL, 0, NULL, &evts[0]);\r\n        globalsize= M;\r\n        pCmdQ->enqueue(pKrnSum, 1, NULL, &globalsize, NULL, 1, &evts[0], &evts[1]);\r\n\r\n        pCmdQ->enqueueRead(res_mem, CL_TRUE, 0, sizeof(float)*M, &result[0], 2, &evts[0], &evts[2]);\r\n\r\n        pCmdQ->flush();\r\n\r\n        clWaitForEvents(1, &evts[2]);\r\n        for(int i=0; i < 3; ++i)\r\n            clReleaseEvent(evts[i]);\r\n\r\n        sampleCommon->stopTimer(timer);\r\n        gpuTime = sampleCommon->readTimer(timer);\r\n        cout << \" Device Timing:\" << gpuTime << endl;\r\n        return SDK_SUCCESS;\r\n    }\r\n\r\n    virtual int run() {\r\n        if( K == 1 ){\r\n            //            return runMatVec();\r\n            //            return runMultiStage();\r\n            return runMatMat();\r\n        }else{\r\n            return runMatMat();\r\n        }\r\n    }\r\n\r\n    virtual int verifyResults(){\r\n        bool ok = true;\r\n        for(int i=0;i<M; ++i) {\r\n            for(int j=0;j<K; ++j)\r\n                if( !Near(result(i,j), correct(i,j)) ) {\r\n                    ok = false;\r\n                    printf(\"(%d,%d) ERROR %f != %f \\n\", i, j,result(i,j), correct(i,j));\r\n                }else{\r\n//                    printf(\"(%d,%d) ERROR %f = %f \\n\", i, j,result(i,j), correct(i,j));\r\n                }\r\n        }\r\n        if( ok) printf(\"GPU computation is correct!\\n\");\r\n        return SDK_SUCCESS;\r\n    }\r\n    virtual int genBinaryImage(){\r\n        return SDK_SUCCESS;\r\n    }\r\n    virtual int cleanup(){\r\n        return SDK_SUCCESS;\r\n    }\r\n    void printStats()\r\n    {\r\n    }\r\n};\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n//    ClPlatform::createSimpleKernel(std::cout);\r\n    MatVec app(\"OpenCL MatVec\");\r\n\r\n    if(app.initialize() != SDK_SUCCESS)\r\n        return SDK_FAILURE;\r\n\r\n    if(app.parseCommandLine(argc, argv) != SDK_SUCCESS)\r\n        return SDK_FAILURE;\r\n\r\n    if(app.isDumpBinaryEnabled())\r\n    {\r\n        return app.genBinaryImage();\r\n    }\r\n    else\r\n    {\r\n        if(app.setup() != SDK_SUCCESS)\r\n            return SDK_FAILURE;\r\n\r\n        if(app.run() != SDK_SUCCESS)\r\n            return SDK_FAILURE;\r\n\r\n        if(app.verifyResults() != SDK_SUCCESS)\r\n            return SDK_FAILURE;\r\n\r\n        if(app.cleanup() != SDK_SUCCESS)\r\n            return SDK_FAILURE;\r\n\r\n        app.printStats();\r\n    }\r\n\r\n    return SDK_SUCCESS;\r\n\r\n}\r\n", "meta": {"hexsha": "0b949954200c241e0856937dcf5ac7bfdfc80981", "size": 9525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Ch1_matvec/MatVec.cpp", "max_stars_repo_name": "adenzhang/OpenCLinAction", "max_stars_repo_head_hexsha": "fc0f93cd0249f5258e21eafb2394022f5ea6482a", "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": "Ch1_matvec/MatVec.cpp", "max_issues_repo_name": "adenzhang/OpenCLinAction", "max_issues_repo_head_hexsha": "fc0f93cd0249f5258e21eafb2394022f5ea6482a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ch1_matvec/MatVec.cpp", "max_forks_repo_name": "adenzhang/OpenCLinAction", "max_forks_repo_head_hexsha": "fc0f93cd0249f5258e21eafb2394022f5ea6482a", "max_forks_repo_licenses": ["Apache-2.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.1790540541, "max_line_length": 126, "alphanum_fraction": 0.5327034121, "num_tokens": 2509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6443331640447557}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra. Eigen itself is part of the KDE project.\r\n//\r\n// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include \"main.h\"\r\n#include <Eigen/SVD>\r\n\r\ntemplate<typename MatrixType> void svd(const MatrixType& m)\r\n{\r\n  /* this test covers the following files:\r\n     SVD.h\r\n  */\r\n  int rows = m.rows();\r\n  int cols = m.cols();\r\n\r\n  typedef typename MatrixType::Scalar Scalar;\r\n  typedef typename NumTraits<Scalar>::Real RealScalar;\r\n  MatrixType a = MatrixType::Random(rows,cols);\r\n  Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> b =\r\n    Matrix<Scalar, MatrixType::RowsAtCompileTime, 1>::Random(rows,1);\r\n  Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> x(cols,1), x2(cols,1);\r\n\r\n  RealScalar largerEps = test_precision<RealScalar>();\r\n  if (ei_is_same_type<RealScalar,float>::ret)\r\n    largerEps = 1e-3f;\r\n\r\n  {\r\n    SVD<MatrixType> svd(a);\r\n    MatrixType sigma = MatrixType::Zero(rows,cols);\r\n    MatrixType matU  = MatrixType::Zero(rows,rows);\r\n    sigma.block(0,0,cols,cols) = svd.singularValues().asDiagonal();\r\n    matU.block(0,0,rows,cols) = svd.matrixU();\r\n    VERIFY_IS_APPROX(a, matU * sigma * svd.matrixV().transpose());\r\n  }\r\n\r\n\r\n  if (rows==cols)\r\n  {\r\n    if (ei_is_same_type<RealScalar,float>::ret)\r\n    {\r\n      MatrixType a1 = MatrixType::Random(rows,cols);\r\n      a += a * a.adjoint() + a1 * a1.adjoint();\r\n    }\r\n    SVD<MatrixType> svd(a);\r\n    svd.solve(b, &x);\r\n    VERIFY_IS_APPROX(a * x,b);\r\n  }\r\n\r\n\r\n  if(rows==cols)\r\n  {\r\n    SVD<MatrixType> svd(a);\r\n    MatrixType unitary, positive;\r\n    svd.computeUnitaryPositive(&unitary, &positive);\r\n    VERIFY_IS_APPROX(unitary * unitary.adjoint(), MatrixType::Identity(unitary.rows(),unitary.rows()));\r\n    VERIFY_IS_APPROX(positive, positive.adjoint());\r\n    for(int i = 0; i < rows; i++) VERIFY(positive.diagonal()[i] >= 0); // cheap necessary (not sufficient) condition for positivity\r\n    VERIFY_IS_APPROX(unitary*positive, a);\r\n\r\n    svd.computePositiveUnitary(&positive, &unitary);\r\n    VERIFY_IS_APPROX(unitary * unitary.adjoint(), MatrixType::Identity(unitary.rows(),unitary.rows()));\r\n    VERIFY_IS_APPROX(positive, positive.adjoint());\r\n    for(int i = 0; i < rows; i++) VERIFY(positive.diagonal()[i] >= 0); // cheap necessary (not sufficient) condition for positivity\r\n    VERIFY_IS_APPROX(positive*unitary, a);\r\n  }\r\n}\r\n\r\nvoid test_eigen2_svd()\r\n{\r\n  for(int i = 0; i < g_repeat; i++) {\r\n    CALL_SUBTEST_1( svd(Matrix3f()) );\r\n    CALL_SUBTEST_2( svd(Matrix4d()) );\r\n    CALL_SUBTEST_3( svd(MatrixXf(7,7)) );\r\n    CALL_SUBTEST_4( svd(MatrixXd(14,7)) );\r\n    // complex are not implemented yet\r\n//     CALL_SUBTEST( svd(MatrixXcd(6,6)) );\r\n//     CALL_SUBTEST( svd(MatrixXcf(3,3)) );\r\n    SVD<MatrixXf> s;\r\n    MatrixXf m = MatrixXf::Random(10,1);\r\n    s.compute(m);\r\n  }\r\n}\r\n", "meta": {"hexsha": "dc405f56915b2a98ef92edd6bb6b0fd430c11f3d", "size": 3054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/eigen3.2.10/test/eigen2/eigen2_svd.cpp", "max_stars_repo_name": "rgijsen/opengl_tmp_poc", "max_stars_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thirdparty/eigen3.2.10/test/eigen2/eigen2_svd.cpp", "max_issues_repo_name": "rgijsen/opengl_tmp_poc", "max_issues_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/eigen3.2.10/test/eigen2/eigen2_svd.cpp", "max_forks_repo_name": "rgijsen/opengl_tmp_poc", "max_forks_repo_head_hexsha": "93e3a08e30ed100475034281208200ed724db5d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-04T15:41:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T15:41:53.000Z", "avg_line_length": 34.7045454545, "max_line_length": 132, "alphanum_fraction": 0.6538965291, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6443002194798187}}
{"text": "// Copyright (c) 2014 Max Planck Society\n\n#include \"math_tools.h\"\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <stdexcept>\n#include <cmath>\n#include <cstdint>\n\nnamespace math_tools {\n\n\nEigen::MatrixXd squareDistance(const Eigen::MatrixXd& a,\n                               const Eigen::MatrixXd& b) {\n  int aRows = a.rows();\n  int aCols = a.cols();\n  int bCols = b.cols();\n\n  Eigen::MatrixXd am(aRows, aCols);    // mean-corrected a\n  Eigen::MatrixXd bm(aRows, bCols);    // mean-corrected b\n  // final result, aCols x bCols\n  Eigen::MatrixXd result(aCols, bCols);\n\n  Eigen::VectorXd mean(aRows);\n\n  /*  If the two Matrices have the same address, it means the function was\n      called from the overloaded version, and thus the mean only has to be\n      computed once.\n   */\n  if (&a == &b) {  // Same address?\n    mean = a.rowwise().mean();\n    am = a.colwise() - mean;\n    bm = am;\n  } else {\n    if (aRows != b.rows()) {\n      throw std::runtime_error(\"Matrix dimension incorrect.\");\n    }\n\n    mean = static_cast<double>(aCols) / (aCols + bCols) * a.rowwise().mean() +\n      static_cast<double>(bCols) / (bCols + aCols) * b.rowwise().mean();\n\n    // The mean of the two Matrices is subtracted beforehand, because the\n    // squared error is independent of the mean and this makes the squares\n    // smaller.\n    am = a.colwise() - mean;\n    bm = b.colwise() - mean;\n  }\n\n  Eigen::MatrixXd a_square =\n    am.array().square().colwise()\n    .sum().transpose().rowwise() .replicate(bCols);\n\n  Eigen::MatrixXd b_square = bm.array().square().colwise().sum().colwise()\n                             .replicate(aCols);\n\n  Eigen::MatrixXd twoab = 2 * (am.transpose()) * bm;\n\n  return (a_square.matrix() + b_square.matrix()) - twoab;\n}\n\nEigen::MatrixXd squareDistance(const Eigen::MatrixXd& a) {\n  return squareDistance(a, a);\n}\n\nEigen::MatrixXd generate_random_sequence(int d, int n) {\n  // x = randn(d,1); % starting sample\n  Eigen::VectorXd x = math_tools::generate_normal_random_matrix(d, 1);\n\n  Eigen::VectorXd t = math_tools::generate_normal_random_matrix(d, 1);\n\n  return generate_random_sequence(n, x, t);\n}\n\nEigen::MatrixXd generate_random_sequence(int n, Eigen::VectorXd x,\n    Eigen::VectorXd t) {\n// function X = GPanimation(d,n)\n// % returns a matrix X of size [d,n], representing a grand circle on the\n// % unit d-sphere in n steps, starting at a random location. Given a kernel\n// % matrix K, this can be turned into a tour through the sample space, simply\n// % by calling chol(K)\u2019 * X;\n// %\n// % Philipp Hennig, September 2012\n\n\n// r = sqrt(sum(x.^2));\n  double r = std::sqrt(x.transpose() * x);\n\n// x = x ./ r; % project onto sphere\n  x = x / r;\n\n// t = randn(d,1); % sample tangent direction\n\n// t = t - (t'*x) * x; % orthogonalise by Gram-Schmidt.\n  double tmp = t.adjoint() * x;\n  t = t - tmp * x;\n\n// t = t ./ sqrt(sum(t.^2)); % standardise\n  t = t / std::sqrt(t.transpose() * t);\n\n// s = linspace(0,2*pi,n+1); s = s(1:end-1); % space to span\n  Eigen::VectorXd s(n + 1);\n  s.setLinSpaced(n + 1, 0, 2 * M_PI);\n  s.conservativeResize(s.rows() - 1);\n\n// t = bsxfun(@times,s,t); % span linspace in direction of t\n//     std::cout << (s.transpose().replicate(t.rows(),1)).format(OctaveFmt) <<\n// std::endl;\n//     std::cout << (t.replicate(1,s.rows())).format(OctaveFmt) <<\n// std::endl;\n\n  Eigen::MatrixXd T = s.transpose().replicate(t.rows(), 1)\n                      .cwiseProduct(t.replicate(1, s.rows()));\n\n// X = r.* exp_map(x,t); % project onto sphere, re-scale\n  Eigen::MatrixXd X = r * exp_map(x, T);\n// end\n  return X;\n}\n\nEigen::MatrixXd exp_map(const Eigen::VectorXd& mu, const Eigen::MatrixXd& E) {\n// D = size(E,1);\n  int D = E.rows();\n\n// theta = sqrt(sum((E.^2)));\n  Eigen::MatrixXd theta = E.array().pow(2).colwise().sum().sqrt();\n\n// M = mu * cos(theta) + E .* repmat(sin(theta)./theta, D, 1);\n  Eigen::MatrixXd M = mu * theta.array().cos().matrix() +\n                      E.cwiseProduct(\n                        (theta.array().sin() / theta.array())\n                        .matrix().replicate(D, 1));\n\n// if (any (abs (theta) <= 1e-7))\n// for a = find (abs (theta) <= 1e-7)\n// M (:, a) = mu;\n// end % for\n// end % if\n  for (int i = 0; i < theta.cols(); i++) {\n    if (theta(0, i) < MINIMAL_THETA) {\n      M.col(i) = mu;\n    }\n  }\n\n// end % function\n  return M;\n}\n\nEigen::MatrixXd generate_uniform_random_matrix_0_1(\n    const size_t n,\n    const size_t m) {\n  Eigen::MatrixXd result = Eigen::MatrixXd(n, m);\n  result.setRandom();\n  Eigen::MatrixXd temp = result.array() + 1;\n  result = temp / 2.0;\n  result = result.array().max(1e-10);\n  result = result.array().min(1.0);\n  return result;\n}\n\nEigen::MatrixXd box_muller(const Eigen::VectorXd &vRand) {\n  size_t n = vRand.rows();\n  size_t m = n / 2;\n\n  Eigen::ArrayXd rand1 = vRand.head(m);\n  Eigen::ArrayXd rand2 = vRand.tail(m);\n\n  /* Implemented according to\n   * http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform\n   */\n\n  rand1 = rand1.max(1e-10);\n  rand1 = rand1.min(1.0);\n\n  rand1 = -2 * rand1.log();\n  rand1 = rand1.sqrt();\n\n  rand2 = rand2 * 2 * M_PI;\n\n  Eigen::MatrixXd result(2 * m, 1);\n  Eigen::MatrixXd res1 = (rand1 * rand2.cos()).matrix();\n  Eigen::MatrixXd res2 = (rand1 * rand2.sin()).matrix();\n  result << res1, res2;\n\n  return result;\n}\n\nEigen::MatrixXd generate_normal_random_matrix(\n    const size_t n,\n    const size_t m) {\n  // if n*m is odd, we need one random number extra!\n  // therefore, we have to round up here.\n  size_t N = static_cast<size_t>(std::ceil(n * m / 2.0));\n\n  Eigen::MatrixXd result(2 * N, 1);\n  // push random samples through the Box-Muller transform\n  result = box_muller(generate_uniform_random_matrix_0_1(2 * N, 1));\n  result.conservativeResize(n, m);\n  return result;\n}\n\ndouble generate_normal_random_double() {\n  Eigen::MatrixXd randomMatrix = generate_normal_random_matrix(1, 1);\n  return randomMatrix(0,0);\n}\n\n}  // namespace math_tools\n\n\n\n\n\n", "meta": {"hexsha": "887bb1f613a5a8b13b46f35045af943f0bcb3352", "size": 5885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contributions/MPI_IS_gaussian_process/tools/math_tools.cpp", "max_stars_repo_name": "iphantomsky/open-phd-guiding", "max_stars_repo_head_hexsha": "41f6f277cd2a2efd25dc198eae3206cf95102608", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contributions/MPI_IS_gaussian_process/tools/math_tools.cpp", "max_issues_repo_name": "iphantomsky/open-phd-guiding", "max_issues_repo_head_hexsha": "41f6f277cd2a2efd25dc198eae3206cf95102608", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contributions/MPI_IS_gaussian_process/tools/math_tools.cpp", "max_forks_repo_name": "iphantomsky/open-phd-guiding", "max_forks_repo_head_hexsha": "41f6f277cd2a2efd25dc198eae3206cf95102608", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7594339623, "max_line_length": 78, "alphanum_fraction": 0.6178419711, "num_tokens": 1733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6442606236361217}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include \"jefflib.h\" \n#include <boost/tokenizer.hpp>\n\nusing namespace std;\n\nint getHundred(int x){\n    string s = to_string(x);\n    if(s.size()>= 3){\n        return stoi(s.substr(s.size() - 3, 1));\n    }\n    else{\n        return 0;\n    }\n}\n\nint main()\n{\n    int rack = 0;\n    int pwr = 0;\n    int maxPwr = 0;\n    int maxX = 0;\n    int maxY = 0;\n    int serialNum = 2568;\n    int grid[301][301];\n\n    for(int x = 1; x <= 300; x++){\n        for(int y = 1; y <= 300; y++){\n            rack = x + 10;\n            pwr = rack * y;\n            pwr += serialNum;\n            pwr *= rack;\n            pwr = getHundred(pwr) - 5;\n            grid[x][y] = pwr;\n        }\n    }\n\n    for(int x = 1; x <= 298; x++){\n        for(int y = 1; y <= 298; y++){\n            pwr = grid[x][y] + grid[x+1][y] + grid[x+2][y];\n            pwr = pwr + grid[x][y+1] + grid[x+1][y+1] + grid[x+2][y+1];\n            pwr = pwr + grid[x][y+2] + grid[x+1][y+2] + grid[x+2][y+2];\n            if(pwr > maxPwr){\n                maxPwr = pwr;\n                maxX = x;\n                maxY = y;\n            }\n        }\n    }\n    cout << \"Part 1: Max power cell = \" << maxX << \", \" << maxY << endl; \n\n    // Part 2\n    maxPwr = 0;\n    int maxSz = 0;\n    for(int x = 1; x <= 300; x++){\n        cout << x << \": \";\n        for(int y = 1; y <= 300; y++){\n            cout << y;\n            // For each cell, calc power for all the valid square sizes\n            int maxDim = 0;\n            int maxXDim = 300 - x + 1;\n            int maxYDim = 300 - y + 1;\n            if(maxXDim > maxYDim){\n                maxDim = maxYDim;\n            } \n            else{\n                maxDim = maxXDim;\n            }\n\n            for(int sz = 1; sz <= maxDim; sz++){\n                pwr = 0;\n                for(int row = 0; row < sz; row++){\n                    for(int col = 0; col < sz; col++){\n                        pwr = pwr + grid[x+col][y+row];\n                    }\n                }\n                if(pwr > maxPwr){\n                    maxPwr = pwr;\n                    maxSz = sz;\n                    maxX = x;\n                    maxY = y;\n                }\n            }\n        }\n        cout << endl;\n    }\n    cout << \"Part 2: Max power cell = \" << maxX << \",\" << maxY << \",\" << maxSz << endl;\n}\n\n\n", "meta": {"hexsha": "cddcefa903d8120b94b3644836ceb05502fd9144", "size": 2317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jeff/day-11/part-1.cpp", "max_stars_repo_name": "jeffphi/advent-of-code-2018", "max_stars_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-23T01:40:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-23T01:40:07.000Z", "max_issues_repo_path": "jeff/day-11/part-1.cpp", "max_issues_repo_name": "jeffphi/advent-of-code-2018", "max_issues_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jeff/day-11/part-1.cpp", "max_forks_repo_name": "jeffphi/advent-of-code-2018", "max_forks_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9139784946, "max_line_length": 87, "alphanum_fraction": 0.369011653, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6442348395116625}}
{"text": "#include \"kak.hpp\"\n#include \"IRProvider.hpp\"\n#include \"xacc.hpp\"\n#include \"xacc_service.hpp\"\n#include <Eigen/Eigenvalues>\n#include <unsupported/Eigen/KroneckerProduct>\n#include <unsupported/Eigen/MatrixFunctions>\n#include \"PauliOperator.hpp\"\n\nnamespace {\nconstexpr std::complex<double> I { 0.0, 1.0 };\nint getTempId()\n{\n  static int tempIdCounter = 0;\n  tempIdCounter++;\n  return tempIdCounter;\n}\n\n// Define some special matrices\nconst Eigen::MatrixXcd& KAK_MAGIC() \n{\n  static Eigen::MatrixXcd KAK_MAGIC(4, 4);\n  static bool init = false;\n  if (!init)\n  {\n    KAK_MAGIC <<  1, 0, 0, I,\n                  0, I, 1, 0,\n                  0, I, -1, 0,\n                  1, 0, 0, -I;\n    KAK_MAGIC = KAK_MAGIC * std::sqrt(0.5); \n    init = true;\n  }\n\n  return KAK_MAGIC;\n}\n\nconst Eigen::MatrixXcd& KAK_MAGIC_DAG() \n{\n  static Eigen::MatrixXcd KAK_MAGIC_DAG = KAK_MAGIC().adjoint();\n  return KAK_MAGIC_DAG;\n}\n           \nconst Eigen::MatrixXcd& KAK_GAMMA()\n{\n  static Eigen::MatrixXcd KAK_GAMMA(4, 4);\n  static bool init = false;\n  if (!init)\n  {\n    KAK_GAMMA << 1, 1, 1, 1,\n                1, 1, -1, -1,\n                -1, 1, -1, 1,\n                1, -1, -1, 1;\n    KAK_GAMMA = 0.25 * KAK_GAMMA;\n    init = true;\n  }\n\n  return KAK_GAMMA;\n}\n\n// Splits i = 0...length into approximate equivalence classes\n// determine by the predicate\nstd::vector<std::pair<int, int>> contiguousGroups(int in_length, std::function<bool(int,int)> in_predicate)\n{\n  int start = 0;\n  std::vector<std::pair<int, int>> result;\n  while(start < in_length)\n  {\n    auto past = start + 1;\n    while ((past < in_length) && in_predicate(start, past))\n    {\n      past++; \n    }\n    result.emplace_back(start, past);\n    start = past;\n  }\n  return result;\n}\n\nEigen::MatrixXd blockDiag(const Eigen::MatrixXd& in_first, const Eigen::MatrixXd& in_second)\n{\n  Eigen::MatrixXd bdm = Eigen::MatrixXd::Zero(in_first.rows() + in_second.rows(), in_first.cols() + in_second.cols());\n  bdm.block(0, 0, in_first.rows(), in_first.cols()) = in_first;\n  bdm.block(in_first.rows(), in_first.cols(), in_second.rows(), in_second.cols()) = in_second;\n  return bdm;\n}\n\ninline bool isSquare(const Eigen::MatrixXcd& in_mat)\n{\n  return in_mat.rows() == in_mat.cols();\n}\n\n// If the matrix is finite: no NaN elements\ntemplate<typename Derived>\ninline bool isFinite(const Eigen::MatrixBase<Derived>& x)\n{\n  return ((x - x).array() == (x - x).array()).all();\n}\n\nbool isDiagonal(const Eigen::MatrixXcd& in_mat, double in_tol = 1e-9)\n{\n  if (!isFinite(in_mat))\n  {\n    return false;\n  }\n\n  for (int i = 0; i < in_mat.rows(); ++i)\n  {\n    for (int j = 0; j < in_mat.cols(); ++j)\n    {\n      if (i != j)\n      {\n        if (std::abs(in_mat(i,j)) > in_tol)\n        {\n          return false;\n        }\n      }\n    }\n  }\n\n  return true;\n}\n\nbool allClose(const Eigen::MatrixXcd& in_mat1, const Eigen::MatrixXcd& in_mat2, double in_tol = 1e-9)\n{\n  if (!isFinite(in_mat1) || !isFinite(in_mat2))\n  {\n    return false;\n  }\n\n  if (in_mat1.rows() == in_mat2.rows() && in_mat1.cols() == in_mat2.cols())\n  {\n    for (int i = 0; i < in_mat1.rows(); ++i)\n    {\n      for (int j = 0; j < in_mat1.cols(); ++j)\n      {\n        if (std::abs(in_mat1(i,j) - in_mat2(i, j)) > in_tol)\n        {\n          return false;\n        }\n      }\n    }\n\n    return true;\n  }\n  return false;\n}\n\nbool isHermitian(const Eigen::MatrixXcd& in_mat)\n{\n  if (!isSquare(in_mat) || !isFinite(in_mat))\n  {\n    return false;\n  }\n  return allClose(in_mat, in_mat.adjoint());\n}\n\nbool isUnitary(const Eigen::MatrixXcd& in_mat)\n{\n  if (!isSquare(in_mat) || !isFinite(in_mat))\n  {\n    return false;\n  }\n\n  Eigen::MatrixXcd Id = Eigen::MatrixXcd::Identity(in_mat.rows(), in_mat.cols());\n\n  return allClose(in_mat * in_mat.adjoint(), Id);\n}\n\nbool isOrthogonal(const Eigen::MatrixXcd& in_mat, double in_tol = 1e-9)\n{\n  if (!isSquare(in_mat) || !isFinite(in_mat))\n  {\n    return false;\n  }\n\n  // Is real \n  for (int i = 0; i < in_mat.rows(); ++i)\n  {\n    for (int j = 0; j < in_mat.cols(); ++j)\n    {\n      if (std::abs(in_mat(i,j).imag()) > in_tol)\n      {\n        return false;\n      }\n    }\n  }\n  // its transpose is its inverse\n  return allClose(in_mat.inverse(), in_mat.transpose(), in_tol);\n}\n// Is Orthogonal and determinant == 1\nbool isSpecialOrthogonal(const Eigen::MatrixXcd& in_mat, double in_tol = 1e-9)\n{\n  return isOrthogonal(in_mat, in_tol) && (std::abs(std::abs(in_mat.determinant()) - 1.0) < in_tol);\n}\n\nbool isCanonicalized(double x, double y, double z)\n{\n  // 0 \u2264 abs(z) \u2264 y \u2264 x \u2264 pi/4\n  // if x = pi/4, z >= 0\n  const double TOL = 1e-9;\n  if (std::abs(z) >= 0 && y >= std::abs(z) && x >= y && x <= M_PI_4 + TOL)\n  {\n    if (std::abs(x - M_PI_4) < TOL)\n    {\n      return (z >= 0);\n    }\n    return true;\n  }\n  return false;\n}\n// Compute exp(i(x XX + y YY + z ZZ)) matrix\nEigen::Matrix4cd interactionMatrixExp(double x, double y, double z)\n{\n  Eigen::MatrixXcd X { Eigen::MatrixXcd::Zero(2, 2)};      \n  Eigen::MatrixXcd Y { Eigen::MatrixXcd::Zero(2, 2)};       \n  Eigen::MatrixXcd Z { Eigen::MatrixXcd::Zero(2, 2)}; \n  X << 0, 1, 1, 0;\n  Y << 0, -I, I, 0;\n  Z << 1, 0, 0, -1;\n  auto XX = Eigen::kroneckerProduct(X, X);\n  auto YY = Eigen::kroneckerProduct(Y, Y);\n  auto ZZ = Eigen::kroneckerProduct(Z, Z);\n  Eigen::MatrixXcd herm = x*XX + y*YY + z*ZZ;\n  herm = I*herm;\n  Eigen::MatrixXcd unitary = herm.exp();\n  return unitary;\n}\n\n// Simplify the Z-Y-Z decomposition:\n// i.e. combining rotations and removing trivial rotation\nstd::shared_ptr<xacc::CompositeInstruction> simplifySingleQubitSeq(double zAngleBefore, double yAngle, double zAngleAfter, size_t bitIdx)\n{\n  auto zExpBefore = zAngleBefore / M_PI - 0.5;\n  auto  middleExp = yAngle / M_PI;\n  std::string  middlePauli = \"Rx\";\n  auto  zExpAfter = zAngleAfter / M_PI + 0.5;\n  \n  // Helper functions:\n  const auto isNearZeroMod = [](double a, double period) -> bool {\n    const auto halfPeriod = period / 2;\n    const double TOL = 1e-8;\n    return std::abs(fmod(a + halfPeriod, period) - halfPeriod) <  TOL;\n  };\n    \n  const auto toQuarterTurns = [](double in_exp) -> int {\n    return static_cast<int>(round(2 * in_exp)) % 4;\n  }; \n\n  const auto isCliffordRotation = [&](double in_exp) -> bool {\n    return isNearZeroMod(in_exp, 0.5);\n  };\n\n  const auto isQuarterTurn = [&](double in_exp) -> bool {\n    return (isCliffordRotation(in_exp) && toQuarterTurns(in_exp) % 2 == 1);\n  };\n\n  const auto isHalfTurn = [&](double in_exp) -> bool {\n    return (isCliffordRotation(in_exp) && toQuarterTurns(in_exp) == 2);\n  };\n\n  const auto isNoTurn = [&](double in_exp) -> bool {\n    return (isCliffordRotation(in_exp) && toQuarterTurns(in_exp) == 0);\n  };\n\n  // Clean up angles\n  if (isCliffordRotation(zExpBefore)) \n  {\n    if ((isQuarterTurn(zExpBefore) || isQuarterTurn(zExpAfter)) != (isHalfTurn(middleExp) && isNoTurn(zExpBefore-zExpAfter)))\n    {\n      zExpBefore += 0.5;\n      zExpAfter -= 0.5;\n      middlePauli = \"Ry\";\n    }\n    if (isHalfTurn(zExpBefore) || isHalfTurn(zExpAfter))\n    {\n      zExpBefore -= 1;\n      zExpAfter += 1;\n      middleExp = -middleExp;\n    }    \n  }\n  if (isNoTurn(middleExp))\n  {\n    zExpBefore += zExpAfter;\n    zExpAfter = 0;\n  }  \n  else if (isHalfTurn(middleExp))\n  {\n    zExpAfter -= zExpBefore;\n    zExpBefore = 0;\n  }\n  \n  auto gateRegistry = xacc::getService<xacc::IRProvider>(\"quantum\");   \n  auto composite = gateRegistry->createComposite(\"__TEMP__COMPOSITE__\" + std::to_string(getTempId()));\n  \n  if (!isNoTurn(zExpBefore))\n  {\n    composite->addInstruction(gateRegistry->createInstruction(\"Rz\", { bitIdx }, { zExpBefore * M_PI }));\n  }\n  if (!isNoTurn(middleExp))\n  {\n    composite->addInstruction(gateRegistry->createInstruction(middlePauli, { bitIdx }, { middleExp * M_PI }));\n  }\n  if (!isNoTurn(zExpAfter))\n  {\n    composite->addInstruction(gateRegistry->createInstruction(\"Rz\", { bitIdx }, { zExpAfter * M_PI }));\n  }\n\n  return composite;\n}\n\n\nstd::shared_ptr<xacc::CompositeInstruction> singleQubitGateGen(const Eigen::Matrix2cd& in_mat, size_t in_bitIdx) \n{\n  using GateMatrix = Eigen::Matrix2cd;\n  auto gateRegistry = xacc::getService<xacc::IRProvider>(\"quantum\");\n\n  // Use Z-Y decomposition of Nielsen and Chuang (Theorem 4.1).\n  // An arbitrary one qubit gate matrix can be written as\n  // U = [ exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)\n  //       exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]\n  // where a,b,c,d are real numbers.\n  const auto singleQubitGateDecompose = [](const Eigen::Matrix2cd& matrix) -> std::tuple<double, double, double, double> {\n    if (allClose(matrix, GateMatrix::Identity()))\n    {\n      return std::make_tuple(0.0, 0.0, 0.0, 0.0);\n    }\n    const auto checkParams = [&matrix](double a, double bHalf, double cHalf, double dHalf) {\n      GateMatrix U;\n      U << std::exp(I*(a-bHalf-dHalf))*std::cos(cHalf),\n          -std::exp(I*(a-bHalf+dHalf))*std::sin(cHalf),\n          std::exp(I*(a+bHalf-dHalf))*std::sin(cHalf),\n          std::exp(I*(a+bHalf+dHalf))*std::cos(cHalf);\n\n      return allClose(U, matrix);    \n    };\n    \n    double a, bHalf, cHalf, dHalf;\n    const double TOLERANCE = 1e-9;\n    if (std::abs(matrix(0, 1)) < TOLERANCE)\n    {\n      auto two_a = fmod(std::arg(matrix(0, 0)*matrix(1, 1)), 2*M_PI);\n      a = (std::abs(two_a) < TOLERANCE || std::abs(two_a) > 2*M_PI-TOLERANCE) ? 0 : two_a/2.0;\n      auto dHalf = 0.0;  \n      auto b = std::arg(matrix(1, 1))-std::arg(matrix(0, 0));\n      std::vector<double> possibleBhalf { fmod(b/2.0, 2 * M_PI), fmod(b/2.0 + M_PI, 2.0 * M_PI) };\n      std::vector<double> possibleChalf { 0.0, M_PI };\n      bool found = false;\n      for (int i = 0; i < possibleBhalf.size(); ++i)\n      {\n        for (int j = 0; j < possibleChalf.size(); ++j)\n        {\n          bHalf = possibleBhalf[i];\n          cHalf = possibleChalf[j];\n          if (checkParams(a, bHalf, cHalf, dHalf))\n          {\n            found = true;\n            break;\n          }\n        }\n        if (found)\n        {\n          break;\n        }\n      }\n      assert(found);\n    }\n    else if (std::abs(matrix(0, 0)) < TOLERANCE)\n    {\n      auto two_a = fmod(std::arg(-matrix(0, 1)*matrix(1, 0)), 2*M_PI);\n      a = (std::abs(two_a) < TOLERANCE || std::abs(two_a) > 2*M_PI-TOLERANCE) ? 0 : two_a/2.0;\n      dHalf = 0;  \n      auto b = std::arg(matrix(1, 0))-std::arg(matrix(0, 1)) + M_PI;\n      std::vector<double> possibleBhalf { fmod(b/2., 2*M_PI), fmod(b/2.+M_PI, 2*M_PI) };\n      std::vector<double> possibleChalf { M_PI/2., 3./2.*M_PI };\n      bool found = false;\n      for (int i = 0; i < possibleBhalf.size(); ++i)\n      {\n        for (int j = 0; j < possibleChalf.size(); ++j)\n        {\n          bHalf = possibleBhalf[i];\n          cHalf = possibleChalf[j];\n          if (checkParams(a, bHalf, cHalf, dHalf))\n          {\n            found = true;\n            break;\n          }\n        }\n        if (found)\n        {\n          break;\n        }\n      }\n      assert(found);\n    }     \n    else\n    {\n      auto two_a = fmod(std::arg(matrix(0, 0)*matrix(1, 1)), 2*M_PI);\n      a = (std::abs(two_a) < TOLERANCE || std::abs(two_a) > 2*M_PI-TOLERANCE) ? 0 : two_a/2.0;\n      auto two_d = 2.*std::arg(matrix(0, 1))-2.*std::arg(matrix(0, 0));\n      std::vector<double> possibleDhalf { fmod(two_d/4., 2*M_PI),\n                        fmod(two_d/4.+M_PI/2., 2*M_PI),\n                        fmod(two_d/4.+M_PI, 2*M_PI),\n                        fmod(two_d/4.+3./2.*M_PI, 2*M_PI) };\n      auto two_b = 2.*std::arg(matrix(1, 0))-2.*std::arg(matrix(0, 0));\n      std::vector<double> possibleBhalf { fmod(two_b/4., 2*M_PI),\n                        fmod(two_b/4.+M_PI/2., 2*M_PI),\n                        fmod(two_b/4.+M_PI, 2*M_PI),\n                        fmod(two_b/4.+3./2.*M_PI, 2*M_PI) };\n      auto tmp = std::acos(std::abs(matrix(1, 1)));\n      std::vector<double> possibleChalf { fmod(tmp, 2*M_PI),\n                        fmod(tmp+M_PI, 2*M_PI),\n                        fmod(-1.*tmp, 2*M_PI),\n                        fmod(-1.*tmp+M_PI, 2*M_PI) };\n      bool found = false;\n      for (int i = 0; i < possibleBhalf.size(); ++i)\n      {\n        for (int j = 0; j < possibleChalf.size(); ++j)\n        {\n          for (int k = 0; k < possibleDhalf.size(); ++k)\n          {\n            bHalf = possibleBhalf[i];\n            cHalf = possibleChalf[j];\n            dHalf = possibleDhalf[k];\n            if (checkParams(a, bHalf, cHalf, dHalf))\n            {\n              found = true;\n              break;\n            }\n          }\n          if (found)\n          {\n            break;\n          }\n        }\n        if (found)\n        {\n          break;\n        }\n      }\n      assert(found);\n    }\n        \n    // Final check:\n    assert(checkParams(a, bHalf, cHalf, dHalf));    \n    return std::make_tuple(a, bHalf, cHalf, dHalf);\n  };\n  // Use Z-Y decomposition of Nielsen and Chuang (Theorem 4.1).\n  // An arbitrary one qubit gate matrix can be writen as\n  // U = [ exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)\n  //       exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]\n  // where a,b,c,d are real numbers.\n  // Then U = exp(j*a) Rz(b) Ry(c) Rz(d).\n  auto [a, bHalf, cHalf, dHalf] = singleQubitGateDecompose(in_mat);\n  // Validate U = exp(j*a) Rz(b) Ry(c) Rz(d).\n  const auto validate = [](const GateMatrix& in_mat, double a, double b, double c, double d) {\n    GateMatrix Rz_b, Ry_c, Rz_d;\n    Rz_b << std::exp(-I*b/2.0), 0, 0, std::exp(I*b/2.0);\n    Rz_d << std::exp(-I*d/2.0), 0, 0, std::exp(I*d/2.0);\n    Ry_c << std::cos(c/2), -std::sin(c/2), std::sin(c/2), std::cos(c/2);\n    auto mat = std::exp(I*a)*Rz_b*Ry_c*Rz_d;\n    return allClose(in_mat, mat);\n  };\n  // Validate the *raw* decomposition\n  assert(validate(in_mat, a, 2*bHalf, 2*cHalf, 2*dHalf));\n  \n  // Simplify/optimize the sequence:\n  auto composite = simplifySingleQubitSeq(2 * dHalf, 2 * cHalf, 2 * bHalf, in_bitIdx);\n\n  // Validate the *simplified* sequence\n  const auto validateSimplifiedSequence = [](const std::shared_ptr<xacc::CompositeInstruction>& in_composite, const GateMatrix& in_mat) {\n    const auto Rx = [](double angle) {\n      GateMatrix result;\n      result << std::cos(angle/2.0), -I*std::sin(angle/2.0), -I*std::sin(angle/2.0), std::cos(angle/2.0);\n      return result;\n    };\n    const auto Ry = [](double angle) {\n      GateMatrix result;\n      result << std::cos(angle/2), -std::sin(angle/2), std::sin(angle/2), std::cos(angle/2);\n      return result;\n    };\n    const auto Rz = [](double angle) {\n      GateMatrix result;\n      result << std::exp(-I*angle/2.0), 0, 0, std::exp(I*angle/2.0);\n      return result;\n    };\n\n    GateMatrix totalU = GateMatrix::Identity();\n    for (size_t i = 0; i < in_composite->nInstructions(); ++i)\n    {\n      auto inst = in_composite->getInstruction(i);\n      assert(inst->name() == \"Rx\" || inst->name() == \"Ry\" || inst->name() == \"Rz\");\n      const auto angle = inst->getParameter(0).as<double>();\n      if (inst->name() == \"Rx\")\n      {\n        totalU =  Rx(angle) * totalU;\n      }\n      if (inst->name() == \"Ry\")\n      {\n        totalU = Ry(angle) * totalU;\n      }\n      if (inst->name() == \"Rz\")\n      {\n        totalU = Rz(angle) * totalU;\n      }\n    }\n\n    // Normalize the upto global phase:\n    // Find index of the largest element:\n    size_t colIdx = 0;\n    size_t rowIdx = 0;\n    double maxVal = std::abs(totalU(0,0));\n    for (size_t i = 0; i < totalU.rows(); ++i)\n    {\n      for (size_t j = 0; j < totalU.cols(); ++j)\n      {\n        if (std::abs(totalU(i,j)) > maxVal)\n        {\n          maxVal = std::abs(totalU(i,j));\n          colIdx = j;\n          rowIdx = i;\n        }\n      }\n    }\n\n    const std::complex<double> globalFactor = in_mat(rowIdx, colIdx) / totalU(rowIdx, colIdx);\n    totalU = globalFactor * totalU;\n    return allClose(in_mat, totalU, 1e-6);\n  };\n\n  assert(validateSimplifiedSequence(composite, in_mat));\n  return composite; \n}\n}\n\nusing namespace xacc;\nusing namespace xacc::quantum;\n\nnamespace xacc {\nnamespace circuits {\nconst std::vector<std::string> KAK::requiredKeys() \n{\n  return { \"unitary\" };\n}\n\nbool KAK::expand(const HeterogeneousMap& parameters) \n{\n  Eigen::Matrix4cd unitary;\n  if (parameters.keyExists<Eigen::Matrix4cd>(\"unitary\"))\n  {\n    unitary = parameters.get<Eigen::Matrix4cd>(\"unitary\");\n  }\n  else if (parameters.keyExists<std::vector<std::complex<double>>>(\"unitary\"))\n  {\n    auto matAsVec = parameters.get<std::vector<std::complex<double>>>(\"unitary\");\n    // Correct size: 4 x 4\n    if (matAsVec.size() == 16)\n    {\n      for (int row = 0; row < 4; ++row)\n      {\n        for (int col = 0; col < 4; ++col)\n        {\n          // Expect row-by-row layout\n          unitary(row, col) = matAsVec[4*row + col];\n        }\n      }\n    }\n  }\n  \n  if (!isUnitary(unitary))\n  {\n    xacc::error(\"Input matrix is not a 4x4 unitary matrix\");\n    return false;\n  }\n  \n  // Vector of qubits: \n  // Default is {0, 1}\n  // This can be specified if needed.\n  std::vector<size_t> bits {0, 1};\n  if (parameters.keyExists<std::vector<int>>(\"qubits\"))\n  {\n    auto qubitVec = parameters.get<std::vector<int>>(\"qubits\");\n    if (qubitVec.size() != 2)\n    {\n      xacc::error(\"Expected 2 qubits.\");\n      return false;\n    }\n    bits[0] = qubitVec[0];\n    bits[1] = qubitVec[1];\n  }\n\n  auto result = kakDecomposition(unitary);\n  if (!result.has_value())\n  {\n    return false;\n  }\n\n  auto composite = result->toGates(bits[0], bits[1]);\n  addInstructions(composite->getInstructions());\n  return true;\n}\n\nstd::optional<KAK::KakDecomposition> KAK::kakDecomposition(const InputMatrix& in_matrix) const\n{\n  assert(isUnitary(in_matrix));\n  Eigen::MatrixXcd mInMagicBasis = KAK_MAGIC_DAG() * in_matrix * KAK_MAGIC();\n  auto [left, diag, right] = bidiagonalizeUnitary(mInMagicBasis);\n  // Recover pieces.\n  auto [a1, a0] = so4ToMagicSu2s(left.transpose());                        \n  auto [b1, b0] = so4ToMagicSu2s(right.transpose());\n  assert(isUnitary(a0));\n  assert(isUnitary(a1));\n  assert(isUnitary(b0));\n  assert(isUnitary(b1));\n\n  Eigen::Vector4cd angles;\n  for (size_t i = 0; i < 4; ++i)\n  {\n    angles(i) = std::arg(diag[i]);\n  }\n  auto factors = KAK_GAMMA() * angles;\n  KakDecomposition result;\n  {\n    result.g = std::exp(I * factors(0));\n    result.a0 = a0;\n    result.a1 = a1;\n    result.b0 = b0;\n    result.b1 = b1;\n    result.x = factors(1).real();\n    assert(std::abs(factors(1).imag()) < 1e-9);\n    result.y = factors(2).real();\n    assert(std::abs(factors(2).imag()) < 1e-9);\n    result.z = factors(3).real();\n    assert(std::abs(factors(3).imag()) < 1e-9);\n  }\n\n  const bool validateMatrix = allClose(result.toMat(), in_matrix);  \n  // Failed to validate\n  if (!validateMatrix)\n  {\n    return std::nullopt;\n  }\n\n  auto canonicalizedInteraction = canonicalizeInteraction(result.x, result.y, result.z);\n\n  // Combine the single-qubit blocks:\n  result.b1 = canonicalizedInteraction.b1 * result.b1;\n  result.b0 = canonicalizedInteraction.b0 * result.b0;\n  result.a1 = result.a1 * canonicalizedInteraction.a1;\n  result.a0 = result.a0 * canonicalizedInteraction.a0;\n  result.g = result.g * canonicalizedInteraction.g;\n  result.x = canonicalizedInteraction.x;\n  result.y = canonicalizedInteraction.y;\n  result.z = canonicalizedInteraction.z;\n\n  assert(isCanonicalized(result.x, result.y, result.z));\n  assert(allClose(result.toMat(), in_matrix));\n\n  return result;\n}\n\nEigen::MatrixXcd KAK::KakDecomposition::toMat() const\n{\n  auto before = Eigen::kroneckerProduct(b1, b0);\n  auto after = Eigen::kroneckerProduct(a1, a0);\n  Eigen::MatrixXcd unitary = interactionMatrixExp(x, y, z);\n  auto total = g * after * unitary * before;\n  return total;\n}\n\nstd::shared_ptr<CompositeInstruction> KAK::KakDecomposition::toGates(size_t in_bit1, size_t in_bit2) const\n{\n  auto gateRegistry = xacc::getService<IRProvider>(\"quantum\");\n  const auto generateInteractionComposite = [&](size_t bit1, size_t bit2, double x, double y, double z) {\n    const double TOL = 1e-8;\n    // Full decomposition is required\n    if (std::abs(z) >= TOL)\n    {\n      const double xAngle = M_PI * (x * -2 / M_PI + 0.5);\n      const double yAngle = M_PI * (y * -2 / M_PI + 0.5);\n      const double zAngle = M_PI * (z * -2 / M_PI + 0.5);\n      auto composite = gateRegistry->createComposite(\"__TEMP__INTERACTION_COMPOSITE__\" + std::to_string(getTempId()));\n      \n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit2, bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"Rz\", { bit1 }, { zAngle }));\n      composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit1 }, { M_PI_2 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit2 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit1, bit2 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit2 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"Ry\", { bit1 }, { yAngle }));\n      composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { xAngle }));\n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit1, bit2 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { -M_PI_2 }));\n\n      const auto validateGateSequence = [&](const Eigen::Matrix4cd& in_target){\n        const auto H = []() {\n          GateMatrix result;\n          result << 1.0/std::sqrt(2), 1.0/std::sqrt(2), 1.0/std::sqrt(2), -1.0/std::sqrt(2);\n          return result;\n        };\n        const auto Rx = [](double angle) {\n          GateMatrix result;\n          result << std::cos(angle/2.0), -I*std::sin(angle/2.0), -I*std::sin(angle/2.0), std::cos(angle/2.0);\n          return result;\n        };\n        const auto Ry = [](double angle) {\n          GateMatrix result;\n          result << std::cos(angle/2), -std::sin(angle/2), std::sin(angle/2), std::cos(angle/2);\n          return result;\n        };\n        const auto Rz = [](double angle) {\n          GateMatrix result;\n          result << std::exp(-I*angle/2.0), 0, 0, std::exp(I*angle/2.0);\n          return result;\n        };\n        const auto CZ = []() {\n          Eigen::Matrix4cd cz;\n          cz << 1, 0, 0, 0, \n                0, 1, 0, 0,\n                0, 0, 1, 0,\n                0, 0, 0, -1;\n          return cz;\n        };\n        \n        Eigen::Matrix2cd IdMat = Eigen::Matrix2cd::Identity();\n        Eigen::Matrix4cd totalU = Eigen::Matrix4cd::Identity();\n        totalU *= Eigen::kroneckerProduct(IdMat, Rx(-M_PI_2));\n        totalU *= Eigen::kroneckerProduct(H(), IdMat);\n        totalU *= CZ();\n        totalU *= Eigen::kroneckerProduct(H(), IdMat);\n        totalU *= Eigen::kroneckerProduct(IdMat, Rx(xAngle));\n        totalU *= Eigen::kroneckerProduct(Ry(yAngle), IdMat);\n        totalU *= Eigen::kroneckerProduct(IdMat, H());\n        totalU *= CZ();\n        totalU *= Eigen::kroneckerProduct(IdMat, H());\n        totalU *= Eigen::kroneckerProduct(Rx(M_PI_2), IdMat);\n        totalU *= Eigen::kroneckerProduct(Rz(zAngle), IdMat);\n        totalU *= Eigen::kroneckerProduct(H(), IdMat);\n        totalU *= CZ();\n        totalU *= Eigen::kroneckerProduct(H(), IdMat);      \n        // Find index of the largest element:\n        size_t colIdx = 0;\n        size_t rowIdx = 0;\n        double maxVal = std::abs(totalU(0,0));\n        for (size_t i = 0; i < totalU.rows(); ++i)\n        {\n          for (size_t j = 0; j < totalU.cols(); ++j)\n          {\n            if (std::abs(totalU(i,j)) > maxVal)\n            {\n              maxVal = std::abs(totalU(i,j));\n              colIdx = j;\n              rowIdx = i;\n            }\n          }\n        }\n\n        const std::complex<double> globalFactor = in_target(rowIdx, colIdx) / totalU(rowIdx, colIdx);\n        totalU = globalFactor * totalU;\n        return allClose(totalU, in_target);\n      };\n      \n      assert(validateGateSequence(interactionMatrixExp(x, y, z)));\n      return composite;\n    }\n    // ZZ interaction is near zero: only XX and YY\n    else if (y >= TOL)\n    {\n      const double xAngle = -2 * x;\n      const double yAngle = -2 * y;\n      auto composite = gateRegistry->createComposite(\"__TEMP__INTERACTION_COMPOSITE__\" + std::to_string(getTempId()));  \n      composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { M_PI_2 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit2, bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"Ry\", { bit1 }, { yAngle }));\n      composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { xAngle }));\n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit1, bit2 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { -M_PI_2 }));\n\n      const auto validateGateSequence = [&](const Eigen::Matrix4cd& in_target){\n        const auto H = []() {\n          GateMatrix result;\n          result << 1.0/std::sqrt(2), 1.0/std::sqrt(2), 1.0/std::sqrt(2), -1.0/std::sqrt(2);\n          return result;\n        };\n        const auto Rx = [](double angle) {\n          GateMatrix result;\n          result << std::cos(angle/2.0), -I*std::sin(angle/2.0), -I*std::sin(angle/2.0), std::cos(angle/2.0);\n          return result;\n        };\n        const auto Ry = [](double angle) {\n          GateMatrix result;\n          result << std::cos(angle/2), -std::sin(angle/2), std::sin(angle/2), std::cos(angle/2);\n          return result;\n        };\n        const auto Rz = [](double angle) {\n          GateMatrix result;\n          result << std::exp(-I*angle/2.0), 0, 0, std::exp(I*angle/2.0);\n          return result;\n        };\n        const auto CZ = []() {\n          Eigen::Matrix4cd cz;\n          cz << 1, 0, 0, 0, \n                0, 1, 0, 0,\n                0, 0, 1, 0,\n                0, 0, 0, -1;\n          return cz;\n        };\n        \n        Eigen::Matrix2cd IdMat = Eigen::Matrix2cd::Identity();\n        Eigen::Matrix4cd totalU = Eigen::Matrix4cd::Identity();\n        totalU *= Eigen::kroneckerProduct(IdMat, Rx(-M_PI_2));\n        totalU *= Eigen::kroneckerProduct(H(), IdMat);\n        totalU *= CZ();\n        totalU *= Eigen::kroneckerProduct(H(), IdMat);\n        totalU *= Eigen::kroneckerProduct(IdMat, Rx(xAngle));\n        totalU *= Eigen::kroneckerProduct(Ry(yAngle), IdMat);\n        totalU *= Eigen::kroneckerProduct(H(), IdMat);\n        totalU *= CZ();\n        totalU *= Eigen::kroneckerProduct(H(), IdMat);      \n        totalU *= Eigen::kroneckerProduct(IdMat, Rx(M_PI_2));\n\n        // Find index of the largest element:\n        size_t colIdx = 0;\n        size_t rowIdx = 0;\n        double maxVal = std::abs(totalU(0,0));\n        for (size_t i = 0; i < totalU.rows(); ++i)\n        {\n          for (size_t j = 0; j < totalU.cols(); ++j)\n          {\n            if (std::abs(totalU(i,j)) > maxVal)\n            {\n              maxVal = std::abs(totalU(i,j));\n              colIdx = j;\n              rowIdx = i;\n            }\n          }\n        }\n\n        const std::complex<double> globalFactor = in_target(rowIdx, colIdx) / totalU(rowIdx, colIdx);\n        totalU = globalFactor * totalU;\n        return allClose(totalU, in_target);\n      };\n      \n      assert(validateGateSequence(interactionMatrixExp(x, y, z)));\n      return composite;\n    }\n    // only XX is significant\n    else \n    {\n      const double xAngle = -2 * x;\n      auto composite = gateRegistry->createComposite(\"__TEMP__INTERACTION_COMPOSITE__\" + std::to_string(getTempId()));\n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit2, bit1 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { xAngle }));\n      composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit1, bit2 }));\n      composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n      \n      const auto validateGateSequence = [&](const Eigen::Matrix4cd& in_target){\n        const auto H = []() {\n          GateMatrix result;\n          result << 1.0/std::sqrt(2), 1.0/std::sqrt(2), 1.0/std::sqrt(2), -1.0/std::sqrt(2);\n          return result;\n        };\n        const auto Rx = [](double angle) {\n          GateMatrix result;\n          result << std::cos(angle/2.0), -I*std::sin(angle/2.0), -I*std::sin(angle/2.0), std::cos(angle/2.0);\n          return result;\n        };\n        const auto Ry = [](double angle) {\n          GateMatrix result;\n          result << std::cos(angle/2), -std::sin(angle/2), std::sin(angle/2), std::cos(angle/2);\n          return result;\n        };\n        const auto Rz = [](double angle) {\n          GateMatrix result;\n          result << std::exp(-I*angle/2.0), 0, 0, std::exp(I*angle/2.0);\n          return result;\n        };\n        const auto CZ = []() {\n          Eigen::Matrix4cd cz;\n          cz << 1, 0, 0, 0, \n                0, 1, 0, 0,\n                0, 0, 1, 0,\n                0, 0, 0, -1;\n          return cz;\n        };\n        \n        Eigen::Matrix2cd IdMat = Eigen::Matrix2cd::Identity();\n        Eigen::Matrix4cd totalU = Eigen::Matrix4cd::Identity();\n        \n        totalU *= Eigen::kroneckerProduct(H(), IdMat);\n        totalU *= CZ();\n        totalU *= Eigen::kroneckerProduct(IdMat, Rx(xAngle));\n        totalU *= CZ();\n        totalU *= Eigen::kroneckerProduct(H(), IdMat);      \n\n        // Find index of the largest element:\n        size_t colIdx = 0;\n        size_t rowIdx = 0;\n        double maxVal = std::abs(totalU(0,0));\n        for (size_t i = 0; i < totalU.rows(); ++i)\n        {\n          for (size_t j = 0; j < totalU.cols(); ++j)\n          {\n            if (std::abs(totalU(i,j)) > maxVal)\n            {\n              maxVal = std::abs(totalU(i,j));\n              colIdx = j;\n              rowIdx = i;\n            }\n          }\n        }\n\n        const std::complex<double> globalFactor = in_target(rowIdx, colIdx) / totalU(rowIdx, colIdx);\n        totalU = globalFactor * totalU;\n        return allClose(totalU, in_target);\n      };\n      \n      assert(validateGateSequence(interactionMatrixExp(x, y, z)));\n      return composite; \n    }\n  };\n\n  auto a0Comp = singleQubitGateGen(a0, in_bit2);\n  auto a1Comp = singleQubitGateGen(a1, in_bit1);\n  auto b0Comp = singleQubitGateGen(b0, in_bit2);\n  auto b1Comp = singleQubitGateGen(b1, in_bit1);\n  auto interactionComp = generateInteractionComposite(in_bit2, in_bit1, x, y, z);\n  auto totalComposite = gateRegistry->createComposite(\"__TEMP__KAK_COMPOSITE__\" + std::to_string(getTempId()));\n  // U = g x (Gate A1 Gate A0) x exp(i(xXX + yYY + zZZ))x(Gate b1 Gate b0)\n  // Before:\n  totalComposite->addInstructions(b0Comp->getInstructions());\n  totalComposite->addInstructions(b1Comp->getInstructions());\n  // Interaction:\n  totalComposite->addInstructions(interactionComp->getInstructions());\n  // After:\n  totalComposite->addInstructions(a0Comp->getInstructions());\n  totalComposite->addInstructions(a1Comp->getInstructions());\n  // Ignore global phase\n  return totalComposite;\n}\n\nKAK::BidiagResult KAK::bidiagonalizeUnitary(const InputMatrix& in_matrix) const\n{\n  Eigen::Matrix4d realMat;\n  Eigen::Matrix4d imagMat;\n  for (int row = 0; row < in_matrix.rows(); ++row)\n  {\n    for (int col = 0; col < in_matrix.cols(); ++col)\n    {\n      realMat(row, col) = in_matrix(row, col).real();\n      imagMat(row, col) = in_matrix(row, col).imag();\n    }\n  }\n  // Assert A X B.T and A.T X B are hermitian\n  assert(isHermitian(realMat * imagMat.transpose()));\n  assert(isHermitian(realMat.transpose() * imagMat));\n\n  auto [left, right] = bidiagonalizeRealMatrixPairWithSymmetricProducts(realMat, imagMat);\n\n  // Convert to special orthogonal w/o breaking diagonalization.\n  if (left.determinant() < 0)\n  {\n    for (int i = 0; i < left.cols(); ++i)\n    {\n      left(0, i) = -left(0, i);\n    }\n  }\n  if (right.determinant() < 0)\n  {\n    for (int i = 0; i < right.rows(); ++i)\n    {\n      right(i, 0) = -right(i, 0);\n    }\n  }\n\n  auto diag = left * in_matrix * right;\n  // Validate:\n  assert(isDiagonal(diag));\n  \n  std::vector<std::complex<double>> diagVec;\n  for (int i = 0; i < diag.rows(); ++i)\n  {\n    diagVec.emplace_back(diag(i, i));\n  }\n\n  return std::make_tuple(left, diagVec, right);\n}\n\nstd::tuple<std::complex<double>, KAK::GateMatrix, KAK::GateMatrix> KAK::kronFactor(const InputMatrix& in_matrix) const\n{\n  KAK::GateMatrix f1 = KAK::GateMatrix::Zero();\n  KAK::GateMatrix f2 = KAK::GateMatrix::Zero();\n  \n  // Get row and column of the max element\n  size_t a = 0;\n  size_t b = 0;\n  double maxVal = std::abs(in_matrix(a, b));\n  for (int row = 0; row < in_matrix.rows(); ++row)\n  {\n    for (int col = 0; col < in_matrix.cols(); ++col)\n    {\n      if (std::abs(in_matrix(row, col)) > maxVal)\n      {\n        a = row;\n        b = col;\n        maxVal = std::abs(in_matrix(a, b));\n      }\n    }\n  }\n  \n  // Extract sub-factors touching the reference cell.\n  for (int i = 0; i < 2; ++i)\n  {\n    for (int j = 0; j < 2; ++j)\n    {\n      f1((a >> 1) ^ i, (b >> 1) ^ j) = in_matrix(a ^ (i << 1), b ^ (j << 1));\n      f2((a & 1) ^ i, (b & 1) ^ j) = in_matrix(a ^ i, b ^ j);\n    }\n  }\n\n  // Rescale factors to have unit determinants.\n  f1 /= (std::sqrt(f1.determinant()));\n  f2 /= (std::sqrt(f2.determinant()));\n\n  //Determine global phase.\n  std::complex<double> g = in_matrix(a, b) / (f1(a >> 1, b >> 1) * f2(a & 1, b & 1));\n  if (g.real() < 0.0)\n  {\n    f1 *= -1;\n    g = -g;\n  }\n\n  // Validate:\n  Eigen::Matrix4cd testMat = g * Eigen::kroneckerProduct(f1, f2);\n  assert(allClose(testMat, in_matrix));\n\n  return std::make_tuple(g, f1, f2);\n}\n\nstd::pair<KAK::GateMatrix, KAK::GateMatrix> KAK::so4ToMagicSu2s(const InputMatrix& in_matrix) const\n{\n  assert(isSpecialOrthogonal(in_matrix));\n  auto matInMagicBasis = KAK_MAGIC() * in_matrix * KAK_MAGIC_DAG();\n  auto [g, f1, f2] = kronFactor(matInMagicBasis);\n  return std::make_pair(f1, f2);\n}\n\nEigen::MatrixXd KAK::diagonalizeRealSymmetricMatrix(const Eigen::MatrixXd& in_mat) const\n{ \n  assert(isHermitian(in_mat));\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(in_mat);\n  Eigen::MatrixXd p = solver.eigenvectors();\n  // Orthogonal basis (Hermitian/symmetric matrix)  \n  assert(isOrthogonal(p));\n  // An orthogonal matrix P such that PT x matrix x P is diagonal.\n  assert(isDiagonal(p.transpose() * in_mat * p));\n  return p;\n}\n\nEigen::MatrixXd KAK::diagonalizeRealSymmetricAndSortedDiagonalMatrices(const Eigen::MatrixXd& in_symMat, const Eigen::MatrixXd& in_diagMat) const\n{\n  assert(isDiagonal(in_diagMat));\n  assert(isHermitian(in_symMat));\n  const auto similarSingular = [&in_diagMat](int i, int j) {\n    return std::abs(in_diagMat(i,i) - in_diagMat(j,j)) < 1e-5;\n  };\n\n  const auto ranges = contiguousGroups(in_diagMat.rows(), similarSingular);\n  Eigen::MatrixXd p = Eigen::MatrixXd::Zero(in_symMat.rows(), in_symMat.cols());\n\n  for (const auto& [start, end]: ranges)\n  {\n    const int blockSize = end - start;\n    \n    Eigen::MatrixXd block = Eigen::MatrixXd(blockSize, blockSize);\n    for (int i = 0; i < blockSize; ++i)\n    {\n      for (int j = 0; j < blockSize; ++j)\n      {\n        block(i,j) = in_symMat(i + start, j + start);\n      }\n    }\n    auto blockDiag = diagonalizeRealSymmetricMatrix(block);\n\n    for (int i = 0; i < blockSize; ++i)\n    {\n      for (int j = 0; j < blockSize; ++j)\n      {\n        p(i + start, j + start) = blockDiag(i,j);\n      }\n    }\n  }\n\n  // P.T x symmetric_matrix x P is diagonal\n  assert(isDiagonal(p.transpose() * in_symMat * p));\n  // and P.T x diagonal_matrix x P = diagonal_matrix\n  assert(allClose(p.transpose() * in_diagMat * p, in_diagMat));\n\n  return p;\n}\n\nstd::pair<Eigen::Matrix4d, Eigen::Matrix4d> KAK::bidiagonalizeRealMatrixPairWithSymmetricProducts(const Eigen::Matrix4d& in_mat1, const Eigen::Matrix4d& in_mat2) const\n{\n  const auto svd = [](const Eigen::MatrixXd& in_mat) -> std::tuple<Eigen::MatrixXd, Eigen::VectorXd, Eigen::MatrixXd> {\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(in_mat, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    return std::make_tuple(svd.matrixU(), svd.singularValues(), svd.matrixV().adjoint());\n  };\n  // Use SVD to bi-diagonalize the first matrix.\n  auto [baseLeft, baseDiagVec, baseRight] = svd(in_mat1);\n  \n  Eigen::MatrixXd baseDiag = Eigen::MatrixXd::Zero(baseDiagVec.size(), baseDiagVec.size());\n  for (int i = 0; i < baseDiagVec.size(); ++i)\n  {\n    baseDiag(i, i) = baseDiagVec(i);\n  }\n\n  // Determine where we switch between diagonalization-fixup strategies.\n  const auto dim = baseDiag.rows();\n  auto rank = dim;\n  while (rank > 0 && std::abs(baseDiag(rank - 1, rank - 1) < 1e-5))\n  {\n    rank--;\n  } \n  Eigen::MatrixXd baseDiagTrim = Eigen::MatrixXd::Zero(rank, rank);\n  for (int i = 0; i < rank; ++i)\n  {\n    for (int j = 0; j < rank; ++j)\n    {\n      baseDiagTrim(i, j) = baseDiag(i, j);\n    }\n  }\n\n  // Try diagonalizing the second matrix with the same factors as the first.\n  auto semiCorrected = baseLeft.transpose() * in_mat2 * baseRight.transpose();\n  \n  Eigen::MatrixXd overlap = Eigen::MatrixXd::Zero(rank, rank);\n  for (int i = 0; i < rank; ++i)\n  {\n    for (int j = 0; j < rank; ++j)\n    {\n      overlap(i, j) = semiCorrected(i, j);\n    }\n  }\n\n  auto overlapAdjust = diagonalizeRealSymmetricAndSortedDiagonalMatrices(overlap, baseDiagTrim);\n  \n  const auto extraSize = dim - rank;\n  Eigen::MatrixXd extra(extraSize, extraSize);\n  for (int i = 0; i < extraSize; ++i)\n  {\n    for (int j = 0; j < extraSize; ++j)\n    {\n      extra(i, j) = semiCorrected(i + rank, j + rank);\n    }\n  } \n  \n  static const auto emptySvdResult = std::make_tuple(Eigen::MatrixXd::Zero(0,0), Eigen::VectorXd::Zero(0), Eigen::MatrixXd::Zero(0,0));\n  auto [extraLeftAdjust, extraDiag, extraRightAdjust] = (dim > rank) ? svd(extra): emptySvdResult;\n  \n  auto leftAdjust = blockDiag(overlapAdjust, extraLeftAdjust);\n  auto rightAdjust = blockDiag(overlapAdjust.transpose(), extraRightAdjust);\n  auto left = leftAdjust.transpose() * baseLeft.transpose();\n  auto right = baseRight.transpose() * rightAdjust.transpose(); \n  // L x mat1 x R and L x mat2 x R are diagonal matrices.\n  assert(isDiagonal(left * in_mat1 * right));\n  assert(isDiagonal(left * in_mat2 * right));\n  return std::make_pair(left, right);\n}\n\nKAK::KakDecomposition KAK::canonicalizeInteraction(double x, double y, double z) const\n{\n  // Accumulated global phase.\n  std::complex<double> phase = 1.0; \n  //Per-qubit left factors.\n  std::vector<GateMatrix> left { GateMatrix::Identity(), GateMatrix::Identity() };  \n  // Per-qubit right factors.\n  std::vector<GateMatrix> right { GateMatrix::Identity(), GateMatrix::Identity() }; \n  // Remaining XX/YY/ZZ interaction vector.\n  std::vector<double> v { x, y, z };  \n\n  std::vector<GateMatrix> flippers {\n    (GateMatrix() << 0, I, I, 0).finished(),\n    (GateMatrix() << 0, 1, -1, 0).finished(),\n    (GateMatrix() << I, 0, 0, -I).finished()\n  };\n\n  std::vector<GateMatrix> swappers {\n    (GateMatrix() << I*M_SQRT1_2, M_SQRT1_2, -M_SQRT1_2, -I*M_SQRT1_2).finished(),\n    (GateMatrix() << I*M_SQRT1_2, I*M_SQRT1_2, I*M_SQRT1_2, -I*M_SQRT1_2).finished(),\n    (GateMatrix() << 0, I*M_SQRT1_2 + M_SQRT1_2, I*M_SQRT1_2 - M_SQRT1_2, 0).finished()\n  };\n\n  const auto shift = [&](int k, int step) {\n    v[k] += step * M_PI_2;\n    phase *= std::pow(I, step);\n    const auto expFact = ((step % 4) + 4) % 4;\n    const GateMatrix mat = flippers[k].array().pow(expFact); \n    right[0] = mat * right[0];\n    right[1] = mat * right[1];\n  };\n\n  const auto negate = [&](int k1, int k2) {\n    v[k1] *= -1;\n    v[k2] *= -1;\n    phase *= -1;\n    const auto& s = flippers[3 - k1 - k2]; \n    left[1] = left[1] * s;\n    right[1] = s * right[1];\n  };\n\n  const auto swap = [&](int k1, int k2) {\n    std::iter_swap(v.begin() + k1, v.begin() + k2);\n    const auto& s = swappers[3 - k1 - k2]; \n    left[0] = left[0] * s;\n    left[1] = left[1] * s;\n    right[0] = s * right[0];\n    right[1] = s * right[1];\n  };\n\n  const auto canonicalShift = [&](int k) {\n    while (v[k] <= -M_PI_4)\n    {\n      shift(k, +1);\n    }\n    while (v[k] > M_PI_4)\n    {\n      shift(k, -1);\n    }\n  };\n\n  const auto sort = [&](){\n    if (std::abs(v[0]) < std::abs(v[1]))\n    {\n      swap(0, 1);\n    }\n    if (std::abs(v[1]) < std::abs(v[2]))\n    {\n      swap(1, 2);\n    }\n    if (std::abs(v[0]) < std::abs(v[1]))\n    {\n      swap(0, 1);\n    }\n  };\n\n  canonicalShift(0);\n  canonicalShift(1);\n  canonicalShift(2);\n  sort();\n\n  if (v[0] < 0)\n  {\n    negate(0, 2);\n  }\n  if (v[1] < 0)\n  {\n    negate(1, 2);\n  }\n  canonicalShift(2);\n\n  if ((v[0] > M_PI_4 - 1e-9) && (v[2] < 0))\n  {\n    shift(0, -1);\n    negate(0, 2);\n  }\n      \n  assert(isCanonicalized(v[0], v[1], v[2]));\n  \n  KakDecomposition result;\n  {\n    result.g = phase;\n    result.a0 = left[1];\n    result.a1 = left[0];\n    result.b0 = right[1];\n    result.b1 = right[0];\n    result.x = v[0];\n    result.y = v[1];\n    result.z = v[2];\n  }\n\n  assert(allClose(result.toMat(), interactionMatrixExp(x, y, z)));\n  return result;\n}\nbool ZYZ::expand(const xacc::HeterogeneousMap& runtimeOptions) \n{\n  Eigen::Matrix2cd unitary;\n  if (runtimeOptions.keyExists<Eigen::Matrix2cd>(\"unitary\"))\n  {\n    unitary = runtimeOptions.get<Eigen::Matrix2cd>(\"unitary\");\n  }\n  else if (runtimeOptions.keyExists<std::vector<std::complex<double>>>(\"unitary\"))\n  {\n    auto matAsVec = runtimeOptions.get<std::vector<std::complex<double>>>(\"unitary\");\n    // Correct size: 2 x 2\n    if (matAsVec.size() == 4)\n    {\n      for (int row = 0; row < 2; ++row)\n      {\n        for (int col = 0; col < 2; ++col)\n        {\n          // Expect row-by-row layout\n          unitary(row, col) = matAsVec[2*row + col];\n        }\n      }\n    }\n  }\n  else\n  {\n    xacc::error(\"unitary matrix is required.\");\n    return false;\n  }\n\n  assert(isUnitary(unitary));\n  auto decomposed = singleQubitGateGen(unitary, 0);\n  addInstructions(decomposed->getInstructions());\n  return true;\n}\n} // namespace circuits\n} // namespace xacc\n", "meta": {"hexsha": "320fac404782f4c867c4d201a9bfc2ea01db3fa6", "size": 42363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "artifacts/old_dataset_versions/minimal_commits_v02/xacc/xacc#309_B/after/kak.cpp", "max_stars_repo_name": "MattePalte/Bugs-Quantum-Computing-Platforms", "max_stars_repo_head_hexsha": "0c1c805fd5dfce465a8955ee3faf81037023a23e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-08T11:46:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T10:13:38.000Z", "max_issues_repo_path": "artifacts/minimal_bugfixes/xacc/xacc#309_B/after/kak.cpp", "max_issues_repo_name": "MattePalte/Bugs-Quantum-Computing-Platforms", "max_issues_repo_head_hexsha": "0c1c805fd5dfce465a8955ee3faf81037023a23e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-09T14:57:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T12:35:58.000Z", "max_forks_repo_path": "artifacts/old_dataset_versions/minimal_commits_v02/xacc/xacc#309_B/after/kak.cpp", "max_forks_repo_name": "MattePalte/Bugs-Quantum-Computing-Platforms", "max_forks_repo_head_hexsha": "0c1c805fd5dfce465a8955ee3faf81037023a23e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8998493976, "max_line_length": 167, "alphanum_fraction": 0.5852512806, "num_tokens": 13117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6442348268110522}}
{"text": "#ifndef CALIBRATOR_PROCESSES_GENERAL_HULLWHITEPROCESS_HPP\n#define CALIBRATOR_PROCESSES_GENERAL_HULLWHITEPROCESS_HPP\n\n#include <boost/bind.hpp>\n\n#include <ql/stochasticprocess.hpp>\n#include <ql/processes/forwardmeasureprocess.hpp>\n#include <ql/math/integrals/simpsonintegral.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n\n#include <calibrator/global.hpp>\n#include <calibrator/models/integrableparameter.hpp>\n\nnamespace HJCALIBRATOR\n{\n\t//! Time-dependent Hull-White process class\n\t/*! This class describes the time-dependent Hull-White process governed by\n\t\\f[\n\tdr(t) = (\\theta(t) - a(t)r(t)) dt + \\sigma(t) dW_t.\n\t\\f]\n\n\tDerivation Reference, Eq. numbering quoted from SSRN-id1514192\n\n\t\\ingroup processes\n\t*/\n\tclass GeneralizedHullWhiteProcess : public StochasticProcess1D\n\t{\n\tpublic :\n\t\tGeneralizedHullWhiteProcess( const Handle<YieldTermStructure>& h,\n\t\t\t\t\t\t\t\t\t const IntegrableParameter& a, // must be an IntegrableParameter\n\t\t\t\t\t\t\t\t\t const Parameter& sigma );\n\t\t\n\t\t//! \\name StochasticProcess1D interface\n\t\t//@{\n\t\tReal x0() const override { return r0_; }\n\t\tReal drift( Time t, Rate r ) const override;\n\t\tReal diffusion( Time t, Rate r ) const override;\n\t\tReal variance( Time t0, Rate r0, Time dt ) const override;\n\t\tReal expectation( Time t0, Rate r0, Time dt ) const override;\n\t\tReal stdDeviation( Time t0, Rate r0, Time dt ) const override;\n\t\t//@}\n\n\t\tIntegrableParameter a() { return a_; }\n\t\tParameter sigma() { return sigma_; }\n\n\t\tReal a( Time t ) { return a_( t ); }\n\t\tReal sigma( Time t ) { return sigma_( t ); }\n\n\t\tReal bondPrice( Time t, Time T, Rate r )const;\n\n\tprivate :\n\t\tReal A( Time t, Time T ) const;\n\t\tReal B( Time t, Time T ) const;\n\n\t\tReal theta( Time t ) const;\n\t\tReal E( Time t, Real multiplier = 1. ) const;\n\t\tReal alpha( Time t ) const;\n\n\t\tReal DVIntegrand( Time u, Time t ) const;\n\t\tReal VrIntegrand( Time t ) const;\n\t\tReal alphaIntegrand( Time u, Time t ) const;\n\n\t\tHandle<YieldTermStructure> termStructure_;\n\t\tIntegrableParameter a_;\n\t\tParameter sigma_;\n\t\tReal r0_;\n\n\t\tSimpsonIntegral integrator_;\n\t\tboost::function<Real( Real )> Vrintegrand_; // variance integrand\n\t\tboost::function<Real( Real )> OneOverEintegrand_; // Eq. 31 integrand\n\n\t};\n\n\t//! Time-dependent Hull-White Forward-Rate process class\n\t/*\n\tDerivation Reference, Eq. numbering quoted from SSRN-id1514192\n\n\t\\ingroup processes\n\t*/\n\t/*\n\tclass GeneralizedHullwhiteForwardProcess : public ForwardMeasureProcess1D\n\t{\n\t\tGeneralizedHullwhiteForwardProcess( const Handle<YieldTermStructure>& h,\n\t\t\t\t\t\t\t\t\t\t\tconst IntegrableParameter& a, // must be an IntegrableParameter\n\t\t\t\t\t\t\t\t\t\t\tconst Parameter& sigma );\n\n\t\t//! \\name StochasticProcess1D interface\n\t\t//@{\n\t\tReal x0() const override;\n\t\tReal drift( Time t, Rate r ) const override;\n\t\tReal diffusion( Time t, Rate r ) const override;\n\t\tReal variance( Time t0, Rate r0, Time dt ) const override;\n\t\tReal expectation( Time t0, Rate r0, Time dt ) const override;\n\t\tReal stdDeviation( Time t0, Rate r0, Time dt ) const override;\n\t\t//@}\n\n\tprivate :\n\t\tboost::shared_ptr<GeneralizedHullWhiteProcess> hwprocess_;\n\t};\n\t*/\n\n\t// inline definitions\n\n\tinline Real GeneralizedHullWhiteProcess::drift( Time t, Rate r ) const\n\t{\n\t\treturn theta( t ) - a_( t ) * r;\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::diffusion( Time t, Rate r ) const\n\t{\n\t\treturn sigma_( t );\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::variance( Time t0, Rate r0, Time dt ) const\n\t{\n\t\tReal Et = E( t0 + dt );\n\n\t\treturn integrator_( Vrintegrand_, t0, t0 + dt ) / (Et * Et);\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::stdDeviation( Time t0, Rate r0, Time dt ) const\n\t{\n\t\treturn sqrt( variance( t0, r0, dt ) );\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::expectation( Time t0, Rate r0, Time dt ) const\n\t{\n\t\t/* A part of eq.35 */\n\t\tTime s = t0;\n\t\tTime t = t0 + dt;\n\n\t\tReal RE = E( s ) / E( t );\n\n\t\treturn RE * r0 + alpha( t ) - RE * alpha( s );\n\t}\n\n\tReal GeneralizedHullWhiteProcess::bondPrice( Time t, Time T, Rate r) const\n\t{\n\t\treturn A( t, T ) * exp( -(B( t, T ) * r) );\n\t}\n\n\tReal GeneralizedHullWhiteProcess::A( Time t, Time T ) const\n\t{\n\t\t/* Modefication of the eq. 43 so that we have the general affine form P = Aexp(-Br)\n\t\t\\f[\n\t\tA(t,T) = \\frac{P(0,T)}{P(0,t)} + exp\\left{B(t,T)f(0,t) - \\frac{1}{2}B^2(t,T)V_r(0,t)\\right}\n\t\t\\f]\n\t\t*/\n\t\tReal discount_t = termStructure_->discount( t );\n\t\tReal discount_T = termStructure_->discount( T );\n\t\tReal forward = termStructure_->forwardRate( t, t, Continuous, NoFrequency );\n\n\t\tReal BtT = B( t, T );\n\t\tReal Vrt = variance( 0, 0, t );\n\n\t\treturn (discount_T / discount_t) * exp( BtT*forward - 0.5 * BtT * BtT * Vrt );\n\t}\n\n\tReal GeneralizedHullWhiteProcess::B( Time t, Time T ) const\n\t{\n\t\t/* eq. 31\n\t\t\\f[\n\t\tB(t,T) = E(t) \\int_t^T \\frac{du}{E(u)}\n\t\t\\f]\n\t\t*/\n\t\treturn E( t ) * integrator_( OneOverEintegrand_, t, T );\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::theta( Time t ) const\n\t{\n\t\tconst Real dt = 0.000001; // Should it be variable?\n\t\tReal f = termStructure_->forwardRate( t, t, Continuous, NoFrequency );\n\t\tReal fup = termStructure_->forwardRate( t + dt, t + dt, Continuous, NoFrequency );\n\t\tReal f_prime = (fup - f) / dt;\n\n\t\tboost::function<Real( Real )> integrand;\n\t\tintegrand = boost::bind( &GeneralizedHullWhiteProcess::DVIntegrand, this, _1, t );\n\t\tReal IntI = integrator_( integrand, 0, t );\n\n\t\tReal Et = E( t );\n\t\tReal at = a_( t );\n\n\t\tReal DV = (2. / Et) * IntI;\n\t\tReal D2V = 2.*variance( 0, 0, t ) - (2*at / Et) * IntI;\n\n\t\t/* eq. 39 */\n\t\treturn f_prime + a_( t ) * f + 0.5 * (D2V + at * DV);\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::E( Time t, Real multiplier ) const\n\t{\n\t\t/* eq. 30\n\t\t\\f[\n\t\tE(t) = exp(\\int_0^t{a(u)du})\n\t\t\\f]\n\n\t\t\n\t\tThe multiplier is given to deal with the integrand of the eq. 31 (\\f$ B(t,T) \\f$)\n\t\t*/\n\t\treturn exp( multiplier * a_.integral( 0, t ) );\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::DVIntegrand( Time u, Time t ) const\n\t{\n\t\t/* Integrand of \\f$ \\partial V(0,t) /\\partial t \\f$ in its derived form\n\t\t\\f[\n\t\t\\partial V(0,t) /\\partial t = \\frac{2}{E(t)\\int_0^t \\sigma(u,t)\\sigma(u)E(u)du\n\t\t\\f]\n\n\t\tHere, we takes \\f$ I(u,t) = \\sigma(u,t)\\sigma(u)E(u) \\f$\n\t\tso we have \n\t\t\\f[\n\t\t\\partial V(0,t) /\\partial t = \\frac{2}{E(t)\\int_0^t I(u,t)du\n\t\t\\partial^2 V(0,t) /\\partial t^2 = -\\frac{a(t)}{E(t)}\\int_0^t I(u,t)du + 2*V_r(0,t)\n\t\t\\f]\n\n\t\twhere \\f$ V_r(0,t \\f$ is the variance of the short rate.\n\t\t\\f]\n\t\t*/\n\n\t\tReal sigma_u = sigma_( u );\n\n\t\treturn (sigma_u * B( u, t )) * sigma_u * E( u );\n\t}\n\n\tReal GeneralizedHullWhiteProcess::VrIntegrand( Time t ) const\n\t{\n\t\t/* Integrand of eq. 37\n\t\t\\f[\n\t\tI(t) =  E^2(t)\\sigam^2(t)\n\t\t\\f]\n\t\t*/\n\t\tReal Et = E( t );\n\t\tReal sigmat = sigma_( t );\n\n\t\treturn Et * Et * sigmat * sigmat;\n\t}\n\n\tReal GeneralizedHullWhiteProcess::alpha( Time t ) const\n\t{\n\t\t/* eq. 36 \n\t\t\\f[\n\t\t\\alpha = f(0,t) + \\frac{1}{E(t)}\\int_0^t E(u)\\sigma(u)B(u,t)du\n\t\t*/\n\t\tboost::function<Real( Real )> integrand;\n\t\tintegrand = boost::bind( &GeneralizedHullWhiteProcess::alphaIntegrand, this, _1, t );\n\t\tReal IntI = integrator_( integrand, 0, t );\n\t\tReal forward = termStructure_->forwardRate( t, t, Continuous, NoFrequency );\n\n\t\treturn forward + IntI / E( t );\n\t}\n\n\tReal GeneralizedHullWhiteProcess::alphaIntegrand( Time u, Time t ) const\n\t{\n\t\tReal sigma_t = sigma_( t );\n\t\t\n\t\treturn E( t ) * sigma_t * sigma_t * B( u, t );\n\t}\n}\n\n#endif // !CALIBRATOR_PROCESSES_GENERAL_HULLWHITEPROCESS_HPP\n\n", "meta": {"hexsha": "ab98f204d382506a27d8b1d4d4a89367735e699e", "size": 7280, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "calibrator/obsolete/generalhullwhiteprocess.hpp", "max_stars_repo_name": "hanjin-kim/gaussian-n-factor", "max_stars_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-25T05:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T04:10:19.000Z", "max_issues_repo_path": "calibrator/obsolete/generalhullwhiteprocess.hpp", "max_issues_repo_name": "hanjin-kim/gaussian-n-factor", "max_issues_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calibrator/obsolete/generalhullwhiteprocess.hpp", "max_forks_repo_name": "hanjin-kim/gaussian-n-factor", "max_forks_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-27T04:10:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T04:10:42.000Z", "avg_line_length": 27.680608365, "max_line_length": 93, "alphanum_fraction": 0.6589285714, "num_tokens": 2471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6442348256860672}}
{"text": "#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main () {\n    using namespace boost::numeric::ublas;\n    vector<double> u(3), v(3);\n    for (unsigned i = 0; i < v.size (); ++ i) {\n        u(i) = 3*i + 1;\n        v(i) = i;\n    }\n    std::cout << u << std::endl << v << std::endl;\n    double t = inner_prod(u, v);\n    std::cout << t << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "c365035818cda892b59912992f107feb05a91fa1", "size": 398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Boost/Vector/boost_vector.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Boost/Vector/boost_vector.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Boost/Vector/boost_vector.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 24.875, "max_line_length": 50, "alphanum_fraction": 0.5226130653, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582995, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6442274780571386}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <cmath>\n\ndouble calculate_anisotropy(const arma::mat &m) {\n\n    const double iso = arma::mean(arma::eig_sym(m));\n    double aniso = arma::accu(m % m);\n    aniso = std::sqrt(std::abs(1.5*(aniso - (3.0*iso*iso))));\n\n    return aniso;\n}\n\nint main() {\n\n    arma::mat tensor(3, 3, arma::fill::zeros);\n\n    tensor(0, 0) = 12;\n    tensor(1, 1) = 12;\n    tensor(2, 2) = -0;\n\n    arma::vec principal_components;\n    arma::mat orientation;\n\n    arma::eig_sym(principal_components, orientation, tensor);\n\n    principal_components.print(\"principal components (real)\");\n    orientation.print(\"orientation (real)\");\n\n    double isotropic = arma::mean(principal_components);\n    std::cout << \"isotropic  : \" << isotropic << std::endl;\n    double anisotropic = calculate_anisotropy(tensor);\n    std::cout << \"anisotropic: \" << anisotropic << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "1dfbad98d231d56a3f8e55d65230d97eb62b6b75", "size": 904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/armadillo/arma_diag.cpp", "max_stars_repo_name": "berquist/eg", "max_stars_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/armadillo/arma_diag.cpp", "max_issues_repo_name": "berquist/eg", "max_issues_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/armadillo/arma_diag.cpp", "max_forks_repo_name": "berquist/eg", "max_forks_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4324324324, "max_line_length": 62, "alphanum_fraction": 0.639380531, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.6442274739017324}}
{"text": "/*\n *  (C) Copyright Nick Thompson 2018.\n *  Use, modification and distribution are subject to the\n *  Boost Software License, Version 1.0. (See accompanying file\n *  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n#ifndef BOOST_INTEGER_MOD_INVERSE_HPP\n#define BOOST_INTEGER_MOD_INVERSE_HPP\n#include <stdexcept>\n#include <boost/throw_exception.hpp>\n#include <boost/integer/extended_euclidean.hpp>\n\nnamespace boost { namespace integer {\n\n// From \"The Joy of Factoring\", Algorithm 2.7.\n// Here's some others names I've found for this function:\n// PowerMod[a, -1, m] (Mathematica)\n// mpz_invert (gmplib)\n// modinv (some dude on stackoverflow)\n// Would mod_inverse be sometimes mistaken as the modular *additive* inverse?\n// In any case, I think this is the best name we can get for this function without agonizing.\ntemplate<class Z>\nZ mod_inverse(Z a, Z modulus)\n{\n    if (modulus < Z(2))\n    {\n        BOOST_THROW_EXCEPTION(std::domain_error(\"mod_inverse: modulus must be > 1\"));\n    }\n    // make sure a < modulus:\n    a = a % modulus;\n    if (a == Z(0))\n    {\n        // a doesn't have a modular multiplicative inverse:\n        return Z(0);\n    }\n    boost::integer::euclidean_result_t<Z> u = boost::integer::extended_euclidean(a, modulus);\n    if (u.gcd > Z(1))\n    {\n        return Z(0);\n    }\n    // x might not be in the range 0 < x < m, let's fix that:\n    while (u.x <= Z(0))\n    {\n        u.x += modulus;\n    }\n    // While indeed this is an inexpensive and comforting check,\n    // the multiplication overflows and hence makes the check itself buggy.\n    //BOOST_ASSERT(u.x*a % modulus == 1);\n    return u.x;\n}\n\n}}\n#endif\n", "meta": {"hexsha": "04b6e819320f32c13014adea8eef36192c8a3f5e", "size": 1651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/integer/mod_inverse.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/integer/mod_inverse.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/integer/mod_inverse.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 30.5740740741, "max_line_length": 93, "alphanum_fraction": 0.6650514839, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6442101562047695}}
{"text": "#include <Eigen/Dense>\r\n#include <Eigen/Core>\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <utility>\r\n#include <cmath>\r\n#include <experimental/random>\r\n\r\n#include <cstdlib>\r\n#include <Eigen/unsupported/Eigen/FFT>\r\n\r\n\r\nusing namespace Eigen;\r\n\r\n#include \"kshape.h\"\r\n\r\ntypedef Matrix<long double,Dynamic,Dynamic> MatrixXld;\r\ntypedef Matrix< std::complex< long double >, Dynamic, Dynamic > MatrixXcld;\r\ntypedef Matrix< long double, Dynamic, 1 > VectorXld;\r\ntypedef Matrix< std::complex< long double >, Dynamic, 1 > VectorXcld;\r\n\r\n\r\nVectorXld coefWiseDivision(VectorXld x, VectorXld y){\r\n    VectorXld ans(x.size());\r\n    for (int i=0;i<x.size();++i){\r\n          ans(i) = x(i)/y(i);\r\n    }\r\n    return ans;\r\n}\r\n\r\nVectorXld circshift(VectorXld vec,int shift)\r\n{\r\n  if (shift==0)\r\n\t{\r\n\t\treturn vec;\r\n\t}\r\n\r\n\tint n = vec.size();\r\n\tVectorXld y(n);\r\n  y.setZero();\r\n\r\n\r\n\tif (shift > 0) // shift right\r\n\t{\r\n\t\ty.head(shift) = vec.tail(shift);\r\n\t\ty.tail(n - shift) = vec.head(n - shift);\r\n\t}\r\n\r\n  if(shift<0) // shift left\r\n\t{\r\n\t\ty.head(n + shift) = vec.tail(n + shift);\r\n\t\ty.tail(abs(shift)) = vec.head(abs(shift));\r\n\r\n\t}\r\n\r\n\treturn y;\r\n}\r\n\r\n\r\nVectorXld shiftWithZeors(VectorXld vec, int shift){\r\n  int n = vec.size();\r\n  VectorXld newvec(n);\r\n  newvec.setZero();\r\n  if (shift==0)\r\n\t{\r\n    newvec.array() = vec.array();\r\n\t\treturn newvec;\r\n\t}\r\n\r\n  if (std::abs(shift)>n){\r\n    return newvec;\r\n  }\r\n\r\n\t if (shift > 0) // shift right\r\n\t{\r\n\t\tnewvec.tail(n - shift) = vec.head(n - shift);\r\n    //vec.head(shift).setZero();\r\n\t}\r\n\r\n  if(shift<0) // shift left\r\n\t{\r\n\t\tnewvec.head(n + shift) = vec.tail(n + shift);\r\n\t\t//vec.tail(abs(shift)).setZero();\r\n\t}\r\n\r\n\treturn newvec;\r\n}\r\n\r\nVectorXld NCC(VectorXld x, VectorXld y){\r\n    long double normed =  x.norm()*y.norm();\r\n    if (normed == 0){\r\n        normed =  1000000000000.0 ;\r\n    }\r\n\r\n    int x_len = x.size();\r\n\r\n    int fft_size = 1 << (int)ceil(log2((2*x_len - 1)));\r\n\r\n    FFT<long double> fft;\r\n    VectorXcld x_out;\r\n\r\n    VectorXld transformed_x(fft_size);\r\n    transformed_x.setZero();\r\n\r\n    transformed_x.head(x_len) = x;\r\n    fft.fwd(x_out, transformed_x);\r\n\r\n    VectorXcld y_out;\r\n    VectorXld transformed_y(fft_size);\r\n    transformed_y.setZero();\r\n    transformed_y.head(y.size()) = y;\r\n    fft.fwd(y_out, transformed_y);\r\n\r\n    VectorXld cc_out;\r\n    VectorXcld inter =  x_out.cwiseProduct( y_out.conjugate() );\r\n    fft.inv(cc_out, inter);\r\n\r\n    VectorXld cc(2*x_len - 1);\r\n    cc.setZero();\r\n    cc.head(x_len-1) = cc_out.tail(x_len-1);\r\n    cc.tail(x_len) = cc_out.head(x_len);\r\n\r\n    return cc.real() / normed;\r\n}\r\n\r\nstd::vector<MatrixXld> NCC3D(MatrixXld x, MatrixXld y){\r\n    VectorXld x_norm = x.rowwise().norm();\r\n    VectorXld y_norm = y.rowwise().norm();\r\n    MatrixXld den(x_norm.size(),y_norm.size());\r\n    for (int i = 0;i<x_norm.size();++i){\r\n          den.row(i) = x_norm(i)*(y_norm);\r\n    }\r\n    den = den.unaryExpr([](long double v) { return v==0.0 ? 1000000000.0 : v; });\r\n    int x_len = x.cols();\r\n    int y_len = y.cols();\r\n\r\n    int fft_size = 1 << (int)ceil(log2((2*x_len - 1)));\r\n\r\n    FFT<long double> fft;\r\n\r\n    MatrixXcld x_out;\r\n    MatrixXcld y_out;\r\n\r\n    std::vector<MatrixXld> cc(y.rows());\r\n\r\n    for (int k=0;k<y.rows();++k){\r\n\r\n      VectorXld y_in(fft_size);\r\n      y_in.setZero();\r\n      VectorXcld fft_y_out;\r\n\r\n      y_in.head(y_len) = y.row(k);\r\n      fft.fwd(fft_y_out, y_in);\r\n\r\n      MatrixXld cc_row(x.rows(), 2*x_len-1);\r\n      for (int j=0;j<x.rows();++j){\r\n          VectorXld x_in(fft_size);\r\n          x_in.setZero();\r\n          VectorXcld fft_x_out;\r\n\r\n          x_in.head(x_len) = x.row(j);\r\n          fft.fwd(fft_x_out, x_in);\r\n          VectorXld inverted_product;\r\n          VectorXcld t1 = fft_x_out.cwiseProduct(fft_y_out.conjugate());\r\n          fft.inv(inverted_product, t1);\r\n\r\n          cc_row.row(j).head(x_len-1) = inverted_product.tail(x_len-1);\r\n          cc_row.row(j).tail(x_len) = inverted_product.head(x_len);\r\n          cc_row.row(j) = cc_row.row(j).array() / den.coeff(j,k);\r\n      }\r\n      cc[k]=cc_row;\r\n    }\r\n\r\n    return cc;\r\n}\r\n\r\n\r\n\r\nstd::pair<long double,VectorXld> SBD (VectorXld x, VectorXld y){\r\n      VectorXld ncc = NCC(x, y);\r\n      int idx;\r\n      long double dist = 1.0 - ncc.maxCoeff(&idx);\r\n\r\n      VectorXld yshift = shiftWithZeors(y, (idx+1)-std::max(x.size(),y.size()));\r\n\r\n     return std::make_pair(dist, yshift);\r\n}\r\n\r\nMatrixXld z_norm(MatrixXld a, int axis = 0,int ddof=0){\r\n      VectorXld means;\r\n      VectorXld sstd;\r\n      if (axis == 0){\r\n        means = a.colwise().mean();\r\n        int n = means.size();\r\n\r\n        VectorXld sstd = VectorXld(n);\r\n        for (int i=0;i<n;++i){\r\n          sstd(i)=((a.col(i).array()-means(i)).pow(2).colwise().sum().sum()/(a.rows()-ddof));\r\n        }\r\n\r\n        sstd = sstd.array().pow(0.5);\r\n\r\n\r\n        MatrixXld temp = (a.rowwise()-means.transpose());\r\n        for (int i=0;i<n;i++){\r\n\r\n          temp.col(i) = (temp.col(i)/(sstd(i)));\r\n        }\r\n\r\n        return temp;\r\n      }\r\n      else {\r\n        means = a.rowwise().mean();\r\n        int n = means.size();\r\n        VectorXld sstd = VectorXld(n);\r\n        for (int i=0;i<n;++i){\r\n          sstd(i)=((a.row(i).array()-means(i)).pow(2).rowwise().sum().sum()/(a.cols()-ddof));\r\n        }\r\n\r\n        sstd = sstd.array().pow(0.5);\r\n\r\n\r\n        MatrixXld temp = (a.colwise()-means);\r\n        for (int i=0;i<n;i++){\r\n          temp.row(i) = (temp.row(i)/(sstd(i)));\r\n        }\r\n\r\n        return temp;\r\n      }\r\n}\r\n\r\nVectorXld extractShape(MatrixXld cluster, VectorXld cur_center){\r\n    if (cluster.rows()==1){\r\n      return cluster.row(0);\r\n    }\r\n\r\n      for (int i=0;i<cluster.rows();++i){\r\n          if (cur_center.sum()!=0.0){\r\n              cluster.row(i) = SBD(cur_center,cluster.row(i)).second;\r\n          }\r\n    }\r\n    MatrixXld y = z_norm(cluster, 1,1);\r\n    MatrixXld s = y.transpose()*y;\r\n\r\n    int columns = cluster.cols();\r\n\r\n    MatrixXld p(columns, columns);\r\n    p.array() = 1.0/(long double)columns;\r\n\r\n    p = MatrixXld::Identity(columns, columns) - p;\r\n\r\n    MatrixXld m = (p.transpose()*s)*p;\r\n    SelfAdjointEigenSolver<MatrixXld> eigensolver(m);\r\n    MatrixXcld eigenVectors = eigensolver.eigenvectors();\r\n    int cols = eigenVectors.cols();\r\n    VectorXcld eigenvalues = eigensolver.eigenvalues();\r\n\r\n    VectorXld centroid = eigenVectors.col(cols-1).real();\r\n\r\n    long double dist1 = (cluster.row(0)-centroid.transpose()).array().pow(2).sum();\r\n    long double dist2 = (cluster.row(0)+centroid.transpose()).array().pow(2).sum();\r\n\r\n    if (dist1>=dist2){\r\n      centroid.array() *= -1.0;\r\n    }\r\n\r\n    return z_norm(centroid,0,1);\r\n\r\n  }\r\n\r\n\r\nstd::pair<std::vector<int>, MatrixXld> kshape(MatrixXld x, int k, int runs_to_average_over){\r\n    int m = x.rows();\r\n    int n = x.cols();\r\n\r\n    std::vector<int> vidx(m);\r\n    std::vector<int> bestidx(m);\r\n\r\n    MatrixXld bestcentroids(k,n);\r\n    bestcentroids.setZero();\r\n\r\n    int number_in_center[k];\r\n    long double bestdist=0.0;\r\n\r\n    for (int run=0;run<runs_to_average_over;++run){\r\n          MatrixXld centroids(k,n);\r\n          centroids.setZero();\r\n\r\n          bool changed;\r\n          long double dist;\r\n          memset(number_in_center,0,sizeof(number_in_center));\r\n\r\n          for (int i=0;i<m;i++){\r\n            int rint = std::experimental::randint(0, k-1);\r\n            vidx[i] = rint;\r\n            number_in_center[rint] += 1;\r\n          }\r\n\r\n          for (int iter=0;iter<100;++iter){\r\n            std::cout << \"Commence Iteration \" << iter;\r\n            for (int j=0;j<k;++j){\r\n                int center_j_size = number_in_center[j];\r\n                MatrixXld center_j = MatrixXld(center_j_size, n);\r\n                int row = 0;\r\n                for (int l=0;l<m;++l){\r\n                    if (vidx[l]==j){\r\n                        center_j.row(row) = x.row(l);\r\n                        ++row;\r\n                    }\r\n                }\r\n\r\n                if (row==0){\r\n                  centroids.row(j).array() = 0;\r\n                }\r\n                else {\r\n                  centroids.row(j) = extractShape(center_j, centroids.row(j)).transpose();\r\n                }\r\n\r\n            }\r\n\r\n            std::vector<MatrixXld> x_corr = NCC3D(x, centroids);\r\n\r\n            MatrixXld distances(m, k);\r\n\r\n            for (int i=0;i<k;++i){\r\n              distances.col(i) = 1 - x_corr[i].rowwise().maxCoeff().array();\r\n            }\r\n            memset(number_in_center,0,sizeof(number_in_center));\r\n            changed = false;\r\n            dist = 0.0;\r\n            for (int i=0;i<x.rows();++i){\r\n              int tempi;\r\n              dist+=std::abs(distances.row(i).minCoeff(&tempi));\r\n              if (vidx[i]!=tempi){\r\n                vidx[i]=tempi;\r\n                changed = true;\r\n              }\r\n              number_in_center[tempi]++;\r\n            }\r\n\r\n            std::cout << \"\\r\";\r\n            if (!changed){\r\n              if (dist>bestdist){\r\n                bestdist=dist;\r\n                bestidx=vidx;\r\n                bestcentroids = centroids;\r\n              }\r\n              break;\r\n            }\r\n          }\r\n\r\n          if (changed){\r\n            if (dist>bestdist){\r\n              bestdist=dist;\r\n              bestidx=vidx;\r\n              bestcentroids = centroids;\r\n            }\r\n          }\r\n    }\r\n\r\n    return std::make_pair(bestidx, bestcentroids);\r\n}\r\n\r\nMatrixXld read_csv(std::string filename, int rows, int cols){\r\n      std::ifstream file(filename);\r\n      MatrixXld mat(rows,cols);\r\n\r\n      std::string line;\r\n      long double val; int row=0;\r\n\r\n      while(std::getline(file, line))\r\n      {\r\n          std::stringstream ss(line);\r\n          // Keep track of the current column index\r\n          int col = 0;\r\n          // Extract each integer\r\n          while(ss >> val){\r\n              // Add the current integer to the 'colIdx' column's values vector\r\n              mat(row,col) = val;\r\n              // If the next token is a comma, ignore it and move on\r\n              if(ss.peek() == ',') ss.ignore();\r\n              // Increment the column index\r\n              col++;\r\n          }\r\n        row++;\r\n      }\r\n\r\n      file.close();\r\n\r\n      return z_norm(mat,1,1);\r\n}\r\n\r\nvoid write_csv(std::string filename, MatrixXld mat){\r\n      std::ofstream file(filename);\r\n\r\n      for(int i = 0; i < mat.rows(); ++i)\r\n      {\r\n          for(int j = 0; j < mat.cols(); ++j)\r\n          {\r\n              file << mat(i,j);\r\n              if(j != mat.cols() - 1) file << \",\";\r\n          }\r\n          file << \"\\n\";\r\n      }\r\n      file.close();\r\n\r\n}\r\n\r\nvoid write_csv(std::string filename, std::vector<int> v){\r\n      std::ofstream file(filename);\r\n\r\n      for(int j = 0; j < v.size(); ++j){\r\n            file << v[j];\r\n            if(j != v.size() - 1) file << \",\";\r\n      }\r\n      file << \"\\n\";\r\n      file.close();\r\n}\r\n\r\n\r\nint main(int argc, char* argv[]){\r\n\r\n  if (argc < 6){\r\n    std::cerr << \"Need to speficy a csv, and its number of rows and columns, as well as K and a number of runs\" << std::endl;\r\n    return 1;\r\n  }\r\n\r\n  std::string csv_filename = std::string(argv[1]);\r\n  int rows = atoi(argv[2]), cols = atoi(argv[3]), k = atoi(argv[4]), runs=atoi(argv[5]);\r\n\r\n  MatrixXld mat = read_csv(csv_filename, rows, cols);\r\n  mat = z_norm(mat, 1,1);\r\n  std::pair<std::vector<int>, MatrixXld> result = kshape(mat, k, runs);\r\n  write_csv(\"out_centroids.csv\", result.second);\r\n  write_csv(\"out_indices.csv\", result.first);\r\n  std::vector<int> cluster_counts(k);\r\n  for (auto i: result.first) cluster_counts[i]++;\r\n  std::cout << std::endl;\r\n  for (int i=0;i<k;++i){\r\n    std::cout << i << \": \" << cluster_counts[i] << std::endl;\r\n  }\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "df3458efee26313ca336c8cf19b69648f6c8c60a", "size": 11619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kshape.cpp", "max_stars_repo_name": "andrew-nash/KShape-", "max_stars_repo_head_hexsha": "2b0aa8e11589292116654c52826e59a7c845bd90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-01T00:19:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T00:19:42.000Z", "max_issues_repo_path": "kshape.cpp", "max_issues_repo_name": "andrew-nash/KShape-cpp", "max_issues_repo_head_hexsha": "2b0aa8e11589292116654c52826e59a7c845bd90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kshape.cpp", "max_forks_repo_name": "andrew-nash/KShape-cpp", "max_forks_repo_head_hexsha": "2b0aa8e11589292116654c52826e59a7c845bd90", "max_forks_repo_licenses": ["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.0515695067, "max_line_length": 126, "alphanum_fraction": 0.5200103279, "num_tokens": 3145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.644210136337691}}
{"text": "/*\n    Boost Competency Test - GSoC 2020\n    digu_J - Digvijay Janartha\n    NIT Hamirpur - INDIA\n*/\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <utility>\n\n#include <boost/geometry/geometry.hpp>\n\nnamespace bg = boost::geometry;\n\nnamespace algo1\n{\n// Solves 2D convex hull in O(n * h) complexity for Multipoint concept\n// Where n is the total input points and h is the total points in convex hull\ntemplate <typename MultiPoint, typename Size>\nclass ConvexHull {\n\n    private:\n        MultiPoint hull;\n        Size n;\n\n    public:\n        ConvexHull(MultiPoint mp, Size sz);\n        void print_hull();\n};\n\ntemplate <typename MultiPoint, typename Size>\nConvexHull<MultiPoint, Size>::ConvexHull(MultiPoint mp, Size sz)\n{\n    hull = mp;\n    n = sz;\n}\n\n// To print the convex hull\ntemplate <typename MultiPoint, typename Size>\nvoid ConvexHull<MultiPoint, Size>::print_hull()\n{\n    std::cout << \"Resulting points of Convex Hull are: \" << std::endl;\n    for (Size i = 0; i < n; ++i)\n    {\n        std::cout << bg::get<0>(hull[i]) << \" \" << bg::get<1>(hull[i]) << std::endl;\n    }\n}\n\n// This method returns true if the points are oriented in counter-clockwise manner\ntemplate <typename Point>\nstatic inline bool check(Point a, Point b, Point c)\n{   \n    typedef typename bg::coordinate_type<Point>::type c_type;\n\n    c_type value = (bg::get<1>(b) - bg::get<1>(a)) * (bg::get<0>(c) - bg::get<0>(b))\n                   - (bg::get<0>(b) - bg::get<0>(a)) * (bg::get<1>(c) - bg::get<1>(b));\n\n    return (value < 0);\n}\n\n// Sorts input in increasing order of x values and in case of ties, increasing y values\ntemplate <typename Range>\nstatic inline void sort(Range& range)\n{\n    typedef typename boost::range_value<Range>::type point_type;\n    typedef boost::geometry::less<point_type> comparator;\n\n    std::sort(boost::begin(range), boost::end(range), comparator());\n}\n\n// Driver code\ntemplate <typename MultiPoint>\ninline void GiftWrapping(MultiPoint input, MultiPoint& hull)\n{\n    typedef typename boost::range_size<MultiPoint>::type size_type;\n\n    size_type n = boost::size(input);\n\n    sort(input);\n\n    // Algorithm starts from leftmost point, which is the first point in input\n    size_type p = 0;\n    size_type q = 0;\n    while (true)\n    {\n        bg::append(hull, input[p]);\n        q = (p + 1) % n;\n        for (size_type i = 0; i < n; ++i)\n        {\n            if (check(input[p], input[i], input[q]))\n            {\n                q = i;\n            }\n        }\n        if (q == 0)\n        {\n            bg::append(hull, input[q]);\n            // Ends when counter reaches leftmost point again\n            break;\n        }\n        p = q;\n    }\n\n    // Uncomment lines below to print the current convex hull\n    // size_type h = boost::size(hull);\n    // ConvexHull<MultiPoint, size_type> debug(hull, h);\n    // debug.print_hull();\n}\n\n} // namespace algo1\n", "meta": {"hexsha": "2988ffe29729e53edaff75239402967c5d9d59ca", "size": 2880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "includes/convex_hull_gift_wrapping.hpp", "max_stars_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_stars_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "includes/convex_hull_gift_wrapping.hpp", "max_issues_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_issues_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "includes/convex_hull_gift_wrapping.hpp", "max_forks_repo_name": "digu-007/Boost_Geometry_Competency_Test_2020", "max_forks_repo_head_hexsha": "53a75c82ddf29bc7f842e653e2a1664839113b53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7142857143, "max_line_length": 87, "alphanum_fraction": 0.6131944444, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6441969511088842}}
{"text": "#ifndef ELASTY_FEM_HPP\n#define ELASTY_FEM_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\n// References:\n//\n// [1] Eftychios Sifakis and Jernej Barbic. 2012. FEM simulation of 3D deformable solids: a practitioner's guide to\n// theory, discretization and model reduction. In ACM SIGGRAPH 2012 Courses (SIGGRAPH '12). Association for Computing\n// Machinery, New York, NY, USA, Article 20, 1\u201350. DOI:https://doi.org/10.1145/2343483.2343501\n//\n// [2] Theodore Kim and David Eberle. 2020. Dynamic deformables: implementation and production practicalities. In ACM\n// SIGGRAPH 2020 Courses (SIGGRAPH '20). Association for Computing Machinery, New York, NY, USA, Article 23, 1\u2013182.\n// DOI:https://doi.org/10.1145/3388769.3407490\n\nnamespace elasty::fem\n{\n    /// \\brief Extract the rotational part of the given square matrix by performing polar decomposion.\n    ///\n    /// \\details This implementation is based on SVD. It checks the determinant to avoid any reflection.\n    template <typename Derived>\n    Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>\n    extractRotation(const Eigen::MatrixBase<Derived>& F)\n    {\n        const auto svd   = F.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n        const auto Sigma = svd.singularValues();\n        const auto U     = svd.matrixU();\n        const auto V     = svd.matrixV();\n        const auto R     = (U * V.transpose()).eval();\n\n        assert(std::abs(std::abs(R.determinant()) - 1.0) < 1e-04);\n\n        if constexpr (Derived::RowsAtCompileTime == 2)\n        {\n            // Just ignore reflection (if any)\n            // TODO: Discuss whether this is a good strategy, or not\n            return R;\n        }\n        else if constexpr (Derived::RowsAtCompileTime == 3)\n        {\n            // Correct reflection (if any)\n            return (R.determinant() > 0) ? R : -R;\n        }\n    }\n\n    /// \\brief Calculate the first Lame parameter, $\\lambda$.\n    ///\n    /// \\details Reference: [1]\n    template <typename Scalar> constexpr Scalar calcFirstLame(const Scalar youngs_modulus, const Scalar poisson_ratio)\n    {\n        return youngs_modulus * poisson_ratio / ((1.0 + poisson_ratio) * (1.0 - 2.0 * poisson_ratio));\n    }\n\n    /// \\brief Calculate the second Lame parameter, $\\mu$.\n    ///\n    /// \\details Reference: [1]\n    template <typename Scalar> constexpr Scalar calcSecondLame(const Scalar youngs_modulus, const Scalar poisson_ratio)\n    {\n        return youngs_modulus / (2.0 * (1.0 + poisson_ratio));\n    }\n\n    /// \\brief Calculate either the \"deformed\" shape matrix (D_s) or \"reference\" shape matrix (D_m) of a triangle.\n    ///\n    /// \\param x_0 A 2D vector.\n    ///\n    /// \\param x_1 A 2D vector.\n    ///\n    /// \\param x_2 A 2D vector.\n    ///\n    /// \\details Reference: [1]\n    template <typename Derived>\n    Eigen::Matrix<typename Derived::Scalar, 2, 2> calc2dShapeMatrix(const Eigen::MatrixBase<Derived>& x_0,\n                                                                    const Eigen::MatrixBase<Derived>& x_1,\n                                                                    const Eigen::MatrixBase<Derived>& x_2)\n    {\n        using Mat = Eigen::Matrix<typename Derived::Scalar, 2, 2>;\n\n        Mat shape_matrix;\n        shape_matrix.col(0) = x_1 - x_0;\n        shape_matrix.col(1) = x_2 - x_0;\n\n        return shape_matrix;\n    }\n\n    /// \\brief Calculate either the \"deformed\" shape matrix (D_s) or \"reference\" shape matrix (D_m) of a tetrahedron.\n    ///\n    /// \\param x_0 A 3D vector.\n    ///\n    /// \\param x_1 A 3D vector.\n    ///\n    /// \\param x_2 A 3D vector.\n    ///\n    /// \\param x_3 A 3D vector.\n    ///\n    /// \\details Reference: [1]\n    template <typename Derived>\n    Eigen::Matrix<typename Derived::Scalar, 3, 3> calc3dShapeMatrix(const Eigen::MatrixBase<Derived>& x_0,\n                                                                    const Eigen::MatrixBase<Derived>& x_1,\n                                                                    const Eigen::MatrixBase<Derived>& x_2,\n                                                                    const Eigen::MatrixBase<Derived>& x_3)\n    {\n        using Mat = Eigen::Matrix<typename Derived::Scalar, 3, 3>;\n\n        Mat shape_matrix;\n        shape_matrix.col(0) = x_1 - x_0;\n        shape_matrix.col(1) = x_2 - x_0;\n        shape_matrix.col(2) = x_3 - x_0;\n\n        return shape_matrix;\n    }\n\n    /// \\brief Calculate the area of a triangle in 2D\n    template <typename Derived>\n    typename Derived::Scalar calc2dTriangleArea(const Eigen::MatrixBase<Derived>& x_0,\n                                                const Eigen::MatrixBase<Derived>& x_1,\n                                                const Eigen::MatrixBase<Derived>& x_2)\n    {\n        const auto r_1 = x_1 - x_0;\n        const auto r_2 = x_2 - x_0;\n\n        return 0.5 * std::abs(r_1(0) * r_2(1) - r_2(0) * r_1(1));\n    }\n\n    /// \\brief Calculate the volume of a tetrahedron\n    template <typename Derived>\n    typename Derived::Scalar calcTetrahedronVolume(const Eigen::MatrixBase<Derived>& x_0,\n                                                   const Eigen::MatrixBase<Derived>& x_1,\n                                                   const Eigen::MatrixBase<Derived>& x_2,\n                                                   const Eigen::MatrixBase<Derived>& x_3)\n    {\n        const auto r_1 = x_1 - x_0;\n        const auto r_2 = x_2 - x_0;\n        const auto r_3 = x_3 - x_0;\n\n        return std::abs(r_1.dot(r_2.cross(r_3))) / 6.0;\n    }\n\n    /// \\brief Calculate the diagonal elements of the lumped mass matrix.\n    ///\n    /// \\details This function takes the \"barycentric\" approach. See https://www.alecjacobson.com/weblog/?p=1146 .\n    template <typename DerivedV, typename DerivedF>\n    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1>\n    calcTriangleMeshLumpedMass(const Eigen::MatrixBase<DerivedV>& verts,\n                               const Eigen::MatrixBase<DerivedF>& elems,\n                               const typename DerivedV::Scalar    total_mass)\n    {\n        using Scalar = typename DerivedV::Scalar;\n        using Vec    = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\n        assert(verts.cols() == 1);\n        assert(verts.size() % 2 == 0);\n        assert(elems.rows() == 3);\n\n        const auto num_verts = verts.size() / 2;\n\n        Scalar total_area = 0;\n        Vec    masses     = Vec::Zero(verts.size());\n\n        for (std::size_t elem_index = 0; elem_index < elems.cols(); ++elem_index)\n        {\n            const auto& indices = elems.col(elem_index);\n\n            const Scalar area = calc2dTriangleArea(verts.template segment<2>(2 * indices[0]),\n                                                   verts.template segment<2>(2 * indices[1]),\n                                                   verts.template segment<2>(2 * indices[2]));\n\n            const Scalar one_third_area = (1.0 / 3.0) * area;\n\n            masses(2 * indices[0] + 0) += one_third_area;\n            masses(2 * indices[0] + 1) += one_third_area;\n            masses(2 * indices[1] + 0) += one_third_area;\n            masses(2 * indices[1] + 1) += one_third_area;\n            masses(2 * indices[2] + 0) += one_third_area;\n            masses(2 * indices[2] + 1) += one_third_area;\n\n            total_area += area;\n        }\n\n        assert(total_mass > 0);\n        assert(total_area > 0);\n\n        return (total_mass / total_area) * masses;\n    }\n\n    /// \\brief Calculate the diagonal elements of the lumped mass matrix.\n    template <typename DerivedV, typename DerivedF>\n    Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1>\n    calcTetraMeshLumpedMass(const Eigen::MatrixBase<DerivedV>& verts,\n                            const Eigen::MatrixBase<DerivedF>& elems,\n                            const typename DerivedV::Scalar    total_mass)\n    {\n        using Scalar = typename DerivedV::Scalar;\n        using Vec    = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\n        assert(verts.cols() == 1);\n        assert(verts.size() % 3 == 0);\n        assert(elems.rows() == 4);\n\n        const auto num_verts = verts.size() / 3;\n        const auto num_elems = elems.cols();\n\n        Scalar total_vol = 0;\n        Vec    masses    = Vec::Zero(verts.size());\n\n        for (std::size_t elem_index = 0; elem_index < num_elems; ++elem_index)\n        {\n            const auto& indices = elems.col(elem_index);\n\n            const Scalar vol = calcTetrahedronVolume(verts.template segment<3>(3 * indices[0]),\n                                                     verts.template segment<3>(3 * indices[1]),\n                                                     verts.template segment<3>(3 * indices[2]),\n                                                     verts.template segment<3>(3 * indices[3]));\n\n            const Scalar one_fourth_vol = (1.0 / 4.0) * vol;\n\n            masses.template segment<3>(3 * indices[0]) += one_fourth_vol * Eigen::Vector3d::Ones();\n            masses.template segment<3>(3 * indices[1]) += one_fourth_vol * Eigen::Vector3d::Ones();\n            masses.template segment<3>(3 * indices[2]) += one_fourth_vol * Eigen::Vector3d::Ones();\n            masses.template segment<3>(3 * indices[3]) += one_fourth_vol * Eigen::Vector3d::Ones();\n\n            total_vol += vol;\n        }\n\n        assert(total_mass > 0);\n        assert(total_vol > 0);\n        assert(masses.minCoeff() > 0.0);\n\n        return (total_mass / total_vol) * masses;\n    }\n\n    /// \\brief Calculate the Green strain tensor for a finite element.\n    ///\n    /// \\param deform_grad The deformation gradient matrix, which should be either 2-by-2 (2D element in 2D), 3-by-3 (3D\n    /// element in 3D), or 3-by-2 (2D element in 3D).\n    template <typename Derived>\n    Eigen::Matrix<typename Derived::Scalar, Derived::ColsAtCompileTime, Derived::ColsAtCompileTime>\n    calcGreenStrain(const Eigen::MatrixBase<Derived>& deform_grad)\n    {\n        using Mat = Eigen::Matrix<typename Derived::Scalar, Derived::ColsAtCompileTime, Derived::ColsAtCompileTime>;\n\n        return 0.5 * (deform_grad.transpose() * deform_grad - Mat::Identity());\n    }\n\n    /// \\details Eq. 3.4 in [1]\n    template <typename Derived>\n    typename Derived::Scalar calcCoRotationalEnergyDensity(const Eigen::MatrixBase<Derived>& deform_grad,\n                                                           const typename Derived::Scalar    first_lame,\n                                                           const typename Derived::Scalar    second_lame)\n    {\n        using Mat = Eigen::Matrix<typename Derived::Scalar, Derived::ColsAtCompileTime, Derived::ColsAtCompileTime>;\n\n        const auto R     = extractRotation(deform_grad);\n        const auto S     = R.transpose() * deform_grad;\n        const auto I     = Mat::Identity();\n        const auto trace = (S - I).trace();\n\n        assert(deform_grad.isApprox(R * S));\n\n        return second_lame * (deform_grad - R).squaredNorm() + 0.5 * first_lame * trace * trace;\n    }\n\n    /// \\details Eq. 3.5 in [1]\n    template <typename Derived>\n    Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>\n    calcCoRotationalPiolaStress(const Eigen::MatrixBase<Derived>& deform_grad,\n                                const typename Derived::Scalar    first_lame,\n                                const typename Derived::Scalar    second_lame)\n    {\n        using Mat = Eigen::Matrix<typename Derived::Scalar, Derived::ColsAtCompileTime, Derived::ColsAtCompileTime>;\n\n        const auto R     = extractRotation(deform_grad);\n        const auto S     = R.transpose() * deform_grad;\n        const auto I     = Mat::Identity();\n        const auto trace = (S - I).trace();\n\n        assert(deform_grad.isApprox(R * S));\n\n        return 2.0 * second_lame * (deform_grad - R) + first_lame * trace * R;\n    }\n\n    /// \\details The first equation in Sec. 3.3 in [1]\n    template <typename Derived>\n    typename Derived::Scalar calcStVenantKirchhoffEnergyDensity(const Eigen::MatrixBase<Derived>& deform_grad,\n                                                                const typename Derived::Scalar    first_lame,\n                                                                const typename Derived::Scalar    second_lame)\n    {\n        const auto E     = calcGreenStrain(deform_grad);\n        const auto trace = E.trace();\n\n        return second_lame * E.squaredNorm() + 0.5 * first_lame * trace * trace;\n    }\n\n    /// \\details Eq. 3.3 in [1]\n    template <typename Derived>\n    Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, Derived::ColsAtCompileTime>\n    calcStVenantKirchhoffPiolaStress(const Eigen::MatrixBase<Derived>& deform_grad,\n                                     const typename Derived::Scalar    first_lame,\n                                     const typename Derived::Scalar    second_lame)\n    {\n        const auto E = calcGreenStrain(deform_grad);\n\n        return 2.0 * second_lame * deform_grad * E + first_lame * E.trace() * deform_grad;\n    }\n\n    template <typename DerivedVec, typename DerivedMat>\n    Eigen::Matrix<typename DerivedVec::Scalar, 2, 2>\n    calc2dTriangleDeformGrad(const Eigen::MatrixBase<DerivedVec>& x_0,\n                             const Eigen::MatrixBase<DerivedVec>& x_1,\n                             const Eigen::MatrixBase<DerivedVec>& x_2,\n                             const Eigen::MatrixBase<DerivedMat>& rest_shape_mat_inv)\n    {\n        const auto D_s = elasty::fem::calc2dShapeMatrix(x_0, x_1, x_2);\n        const auto F   = D_s * rest_shape_mat_inv;\n\n        return F;\n    }\n\n    template <typename DerivedVec, typename DerivedMat>\n    Eigen::Matrix<typename DerivedVec::Scalar, 3, 3>\n    calcTetrahedronDeformGrad(const Eigen::MatrixBase<DerivedVec>& x_0,\n                              const Eigen::MatrixBase<DerivedVec>& x_1,\n                              const Eigen::MatrixBase<DerivedVec>& x_2,\n                              const Eigen::MatrixBase<DerivedVec>& x_3,\n                              const Eigen::MatrixBase<DerivedMat>& rest_shape_mat_inv)\n    {\n        const auto D_s = elasty::fem::calc3dShapeMatrix(x_0, x_1, x_2, x_3);\n        const auto F   = D_s * rest_shape_mat_inv;\n\n        return F;\n    }\n\n    /// \\brief Calculate analytic partial derivatives of the deformation gradient $\\mathbf{F}$ with respect to the\n    /// vertex positions $\\mathbf{x}$ (i.e., $\\frac{\\partial \\mathbf{F}}{\\partial \\mathbf{x}}$) and return it in the\n    /// \"flattened\" format.\n    ///\n    /// \\details The result is a 2-by-2-by-6 third-order tensor but flattened into a 4-by-6 matrix.\n    ///\n    /// Reference: [2, Appendix D]\n    template <typename Derived>\n    Eigen::Matrix<typename Derived::Scalar, 4, 6>\n    calcVecTrianglePartDeformGradPartPos(const Eigen::MatrixBase<Derived>& rest_shape_mat_inv)\n    {\n        using Scalar = typename Derived::Scalar;\n\n        // Analytics partial derivatives $\\frac{\\partial \\mathbf{D}_\\text{s}{\\partial x_{i}}$\n        Eigen::Matrix<Scalar, 2, 2> PDsPx[6];\n\n        // x[0] (= x_0)\n        PDsPx[0] << -1.0, -1.0, 0.0, 0.0;\n\n        // x[1] (= y_0)\n        PDsPx[1] << 0.0, 0.0, -1.0, -1.0;\n\n        // x[2] (= x_1)\n        PDsPx[2] << 1.0, 0.0, 0.0, 0.0;\n\n        // x[3] (= y_1)\n        PDsPx[3] << 0.0, 0.0, 1.0, 0.0;\n\n        // x[4] (= x_2)\n        PDsPx[4] << 0.0, 1.0, 0.0, 0.0;\n\n        // x[5] (= y_2)\n        PDsPx[5] << 0.0, 0.0, 0.0, 1.0;\n\n        Eigen::Matrix<Scalar, 4, 6> vec_PFPx;\n        for (std::size_t i = 0; i < 6; ++i)\n        {\n            const Eigen::Matrix<Scalar, 2, 2> PFPx_i = PDsPx[i] * rest_shape_mat_inv;\n\n            vec_PFPx.col(i) = Eigen::Map<const Eigen::Matrix<Scalar, 4, 1>>(PFPx_i.data(), PFPx_i.size());\n        }\n\n        return vec_PFPx;\n    }\n\n    /// \\brief Calculate analytic partial derivatives of the deformation gradient $\\mathbf{F}$ with respect to the\n    /// vertex positions $\\mathbf{x}$ (i.e., $\\frac{\\partial \\mathbf{F}}{\\partial \\mathbf{x}}$) and return it in the\n    /// \"flattened\" format.\n    ///\n    /// \\details The result is a 3-by-3-by-12 third-order tensor but flattened into a 9-by-12 matrix.\n    ///\n    /// Reference: [2, Appendix D]\n    template <typename Derived>\n    Eigen::Matrix<typename Derived::Scalar, 9, 12>\n    calcVecTetrahedronPartDeformGradPartPos(const Eigen::MatrixBase<Derived>& rest_shape_mat_inv)\n    {\n        using Scalar = typename Derived::Scalar;\n\n        // Analytics partial derivatives $\\frac{\\partial \\mathbf{D}_\\text{s}{\\partial x_{i}}$\n        Eigen::Matrix<Scalar, 3, 3> PDsPx[12];\n\n        PDsPx[0] << -1.0, -1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n        PDsPx[1] << 0.0, 0.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0;\n        PDsPx[2] << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, -1.0, -1.0;\n\n        PDsPx[3] << 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n        PDsPx[4] << 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n        PDsPx[5] << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0;\n\n        PDsPx[6] << 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n        PDsPx[7] << 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0;\n        PDsPx[8] << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0;\n\n        PDsPx[9] << 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n        PDsPx[10] << 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0;\n        PDsPx[11] << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0;\n\n        Eigen::Matrix<Scalar, 9, 12> vec_PFPx;\n        for (std::size_t i = 0; i < 12; ++i)\n        {\n            const Eigen::Matrix<Scalar, 3, 3> PFPx_i = PDsPx[i] * rest_shape_mat_inv;\n\n            vec_PFPx.col(i) = Eigen::Map<const Eigen::Matrix<Scalar, 9, 1>>(PFPx_i.data(), PFPx_i.size());\n        }\n\n        return vec_PFPx;\n    }\n} // namespace elasty::fem\n\n#endif // ELASTY_FEM_HPP\n", "meta": {"hexsha": "490fe43c4dd012e0a88db58697f7b7300c715373", "size": 17749, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/elasty/fem.hpp", "max_stars_repo_name": "yuki-koyama/elasty", "max_stars_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T00:45:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:15:45.000Z", "max_issues_repo_path": "include/elasty/fem.hpp", "max_issues_repo_name": "yuki-koyama/elasty", "max_issues_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2019-04-27T00:00:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T07:01:12.000Z", "max_forks_repo_path": "include/elasty/fem.hpp", "max_forks_repo_name": "yuki-koyama/elasty", "max_forks_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T01:09:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:30:41.000Z", "avg_line_length": 41.8608490566, "max_line_length": 120, "alphanum_fraction": 0.5649895769, "num_tokens": 5055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6441728519485446}}
{"text": "\r\n\r\n#include <d3dx9.h>\r\n#include <d3d9.h>\r\n\r\n#include <iostream>\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/vector.hpp>\r\n\r\n\r\ntypedef boost::numeric::ublas::vector<float>  Vector3;\r\ntypedef boost::numeric::ublas::matrix<float>  Matrix44;\r\n\r\n\r\nint main()\r\n{\r\n\tVector3  vector(4);\r\n\tMatrix44 matrix(4, 4);\r\n\tD3DXVECTOR3 dVector3;\r\n\tD3DXMATRIX dMatrix44;\r\n\r\n\tfor (int i = 0; i < vector.size(); ++i) {\r\n\t\tvector(i) = i;\r\n\t}\r\n\r\n\tfor (int i = 0; i < 4; ++i) {\r\n\t\tfor (int j = 0; j < 4; ++j) {\r\n\t\t\tmatrix(i, j) = 4 * i + j;\r\n\t\t\tdMatrix44.m[i][j] = matrix(i, j);\r\n\t\t}\r\n\t}\r\n\r\n\tstd::cout << vector << std::endl;\r\n\tstd::cout << matrix << std::endl;\r\n\t//std::cout << dMatrix44 << std::endl;\r\n\tfor (int i = 0; i < 4; ++i) {\r\n\t\tfor (int j = 0; j < 4; ++j) {\r\n\t\t\tstd::cout << dMatrix44.m[i][j] << \" \";\r\n\t\t}\r\n\t}\r\n\tstd::cout << std::endl;\r\n\r\n\tVector3 multipul = boost::numeric::ublas::prod(matrix, vector);\r\n\t//Vector3 multipul = boost::numeric::ublas::prod(vector, matrix);\r\n\r\n\tstd::cout << multipul << std::endl;\r\n\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "2a24215e9b358e6edcb12064677a3b4adfb205f4", "size": 1095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/MatrixTest/AxisTest.cpp", "max_stars_repo_name": "taku-xhift/labo", "max_stars_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/MatrixTest/AxisTest.cpp", "max_issues_repo_name": "taku-xhift/labo", "max_issues_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/MatrixTest/AxisTest.cpp", "max_forks_repo_name": "taku-xhift/labo", "max_forks_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5535714286, "max_line_length": 67, "alphanum_fraction": 0.5652968037, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.644172839787666}}
{"text": "#include <cmath>\r\n#include <iostream>\r\n#include <random>\r\n#include <vector>\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics.hpp>\r\n#include <boost/accumulators/statistics/weighted_mean.hpp>\r\n#include <boost/accumulators/statistics/weighted_variance.hpp>\r\n#include <gtest/gtest.h>\r\n\r\n// Assumes discrete distributions\r\nusing Value = int;\r\nusing Probability = double;\r\nusing Mean = double;\r\nusing ProbabilityDensity = std::vector<Probability>;\r\nconstexpr std::mt19937::result_type GlobalSeed = 123;\r\n\r\ntemplate <typename T>\r\nProbabilityDensity MakeDistribution(Value maxNumber, Value trialSize, T& dist) {\r\n    std::mt19937 gen{GlobalSeed};\r\n    ProbabilityDensity prob(maxNumber + 1);\r\n    const Probability unit = 1.0 / trialSize;\r\n    for(auto i = decltype(trialSize){0}; i < trialSize; ++i) {\r\n        Value num = std::round(dist(gen));\r\n        if ((num >= 0) && (num <= maxNumber)) {\r\n            prob.at(num) += unit;\r\n        }\r\n    }\r\n\r\n    return prob;\r\n}\r\n\r\nProbabilityDensity MakeNormalDistribution(Mean mean, Mean variance, Value maxNumber, Value trialSize) {\r\n    std::mt19937 gen{GlobalSeed};\r\n    std::normal_distribution<Probability> dist(mean, std::sqrt(variance));\r\n    return MakeDistribution(maxNumber, trialSize, dist);\r\n}\r\n\r\nProbabilityDensity MakePoissonDistribution(Mean mean, Value maxNumber, Value trialSize) {\r\n    std::mt19937 gen{GlobalSeed};\r\n    std::poisson_distribution<Value> dist(mean);\r\n    return MakeDistribution(maxNumber, trialSize, dist);\r\n}\r\n\r\nProbabilityDensity MakeNegativeBinomialDistribution(Value size, Mean prob, Value maxNumber, Value trialSize) {\r\n    std::mt19937 gen{GlobalSeed};\r\n    std::negative_binomial_distribution<Value> dist(size, prob);\r\n    return MakeDistribution(maxNumber, trialSize, dist);\r\n}\r\n\r\n// Probability density from 0 to n (n+1 elements)\r\nProbabilityDensity MergeProbabilityDensity(const ProbabilityDensity& lhs, const ProbabilityDensity& rhs) {\r\n    if (lhs.empty()) {\r\n        return rhs;\r\n    }\r\n\r\n    if (rhs.empty()) {\r\n        return lhs;\r\n    }\r\n\r\n    const auto maxLeft = lhs.size() - 1;\r\n    const auto maxRight = rhs.size() - 1;\r\n    const auto maxJoint = maxLeft + maxRight;\r\n    ProbabilityDensity jointProb(maxJoint + 1);\r\n\r\n    for(auto iRight = decltype(maxRight){0}; iRight <= maxRight; ++iRight) {\r\n        const auto probRight = rhs.at(iRight);\r\n        for(auto iLeft = decltype(maxLeft){0}; iLeft <= maxLeft; ++iLeft) {\r\n            jointProb.at(iLeft + iRight) += lhs.at(iLeft) * probRight;\r\n        }\r\n    }\r\n\r\n    return jointProb;\r\n}\r\n\r\nstruct Moments {\r\n    Mean mean {0};\r\n    Mean variance {0};\r\n};\r\n\r\nMoments GetMeanVariance(const ProbabilityDensity& dist, Probability epsilon) {\r\n    using namespace boost::accumulators;\r\n    EXPECT_NEAR(1.0, std::accumulate(dist.begin(), dist.end(), 0.0), epsilon);\r\n\r\n    Mean value = 0;\r\n    Mean actualMeanBasic = 0.0;\r\n    for (const auto& prob : dist) {\r\n        actualMeanBasic += value * prob;\r\n        value += 1.0;\r\n    }\r\n\r\n    value = 0;\r\n    Mean actualVarianceBasic = 0.0;\r\n    for (const auto& prob : dist) {\r\n        actualVarianceBasic += (value - actualMeanBasic) * (value - actualMeanBasic) * prob;\r\n        value += 1.0;\r\n    }\r\n\r\n    // Not weighted\r\n    accumulator_set<Mean, stats<tag::mean, tag::variance>> accBase;\r\n    value = 0;\r\n    for (const auto& prob : dist) {\r\n        Value count = static_cast<decltype(count)>(prob * 10000000);\r\n        for(Value i=0; i<count; ++i) {\r\n            accBase(value);\r\n        }\r\n        value += 1.0;\r\n    }\r\n    constexpr Mean EpsilonAccBase = 0.01;\r\n    EXPECT_NEAR(actualMeanBasic, mean(accBase), EpsilonAccBase);\r\n    EXPECT_NEAR(actualVarianceBasic, variance(accBase), EpsilonAccBase);\r\n\r\n    // Must set the third type and have weighted_variance take (lazy)\r\n    accumulator_set<Mean, stats<tag::weighted_mean, tag::weighted_variance(lazy)>, Mean> acc;\r\n    value = 0;\r\n    for (const auto& prob : dist) {\r\n        // Do not omit the weight below\r\n        acc(value, weight = prob);\r\n//      acc(value, prob);\r\n        value += 1.0;\r\n    }\r\n    const Mean actualMean = weighted_mean(acc);\r\n    const Mean actualVariance = weighted_variance(acc);\r\n    constexpr Mean EpsilonAcc = 0.000001;\r\n    EXPECT_NEAR(actualMeanBasic, actualMean, EpsilonAcc);\r\n    EXPECT_NEAR(actualVarianceBasic, actualVariance, EpsilonAcc);\r\n\r\n    // weighted_variance without lazy does not work\r\n    accumulator_set<Mean, stats<tag::weighted_mean, tag::weighted_variance>, Mean> accNonLazy;\r\n    value = 0;\r\n    for (const auto& prob : dist) {\r\n        accNonLazy(value, weight = prob);\r\n        value += 1.0;\r\n    }\r\n    EXPECT_NEAR(actualMeanBasic, weighted_mean(accNonLazy), EpsilonAcc);\r\n//  EXPECT_NEAR(actualVarianceBasic, weighted_variance(accNonLazy), EpsilonAcc);\r\n\r\n    // If we forget weight = ...\r\n    accumulator_set<Mean, stats<tag::mean>> accWrong;\r\n    value = 0;\r\n    for (const auto& prob : dist) {\r\n        // Do not omit the weight below!\r\n        accWrong(value, prob);\r\n        value += 1.0;\r\n    }\r\n//  EXPECT_NEAR(actualMeanBasic, mean(accWrong), EpsilonAcc);\r\n\r\n    // Replacing tag::weighted_mean to tag::mean works\r\n    accumulator_set<Mean, stats<tag::mean>, Mean> accPlain;\r\n    value = 0;\r\n    for (const auto& prob : dist) {\r\n        accPlain(value, weight = prob);\r\n        value += 1.0;\r\n    }\r\n    EXPECT_NEAR(actualMeanBasic, mean(accPlain), EpsilonAcc);\r\n\r\n    // But if we omit the third type argument...\r\n    accumulator_set<Mean, stats<tag::mean>> accPlainWrong;\r\n    value = 0;\r\n    for (const auto& prob : dist) {\r\n        accPlainWrong(value, weight = prob);\r\n        value += 1.0;\r\n    }\r\n//  EXPECT_NEAR(actualMeanBasic, mean(accPlainWrong), EpsilonAcc);\r\n\r\n    Moments result {actualMeanBasic, actualVarianceBasic};\r\n    return result;\r\n}\r\n\r\nclass TestMergeProbabilityDensity : public ::testing::Test {};\r\n\r\nTEST_F(TestMergeProbabilityDensity, Normal) {\r\n    constexpr Mean expectedMean = 100;\r\n    constexpr Mean expectedVariance = 25;\r\n    constexpr Value maxNumber = 200;\r\n    constexpr Value trialSize = 1000000;\r\n\r\n    const auto dist = MakeNormalDistribution(expectedMean, expectedVariance, maxNumber, trialSize);\r\n    const auto actual = GetMeanVariance(dist, 0.001);\r\n    EXPECT_EQ(expectedMean, std::round(actual.mean));\r\n    EXPECT_EQ(std::round(expectedVariance), std::round(actual.variance));\r\n}\r\n\r\nTEST_F(TestMergeProbabilityDensity, Poisson) {\r\n    constexpr Mean expectedMean = 10;\r\n    constexpr Mean expectedVariance = expectedMean;\r\n    constexpr Value maxNumber = 200;\r\n    constexpr Value trialSize = 1000000;\r\n\r\n    const auto dist = MakePoissonDistribution(expectedMean, maxNumber, trialSize);\r\n    const auto actual = GetMeanVariance(dist, 0.001);\r\n    EXPECT_EQ(expectedMean, std::round(actual.mean));\r\n    EXPECT_EQ(std::round(expectedVariance), std::round(actual.variance));\r\n}\r\n\r\nTEST_F(TestMergeProbabilityDensity, NegativeBinomial) {\r\n    constexpr Value size = 10;\r\n    constexpr Mean probToSuccess = 0.4;\r\n    constexpr Mean expectedMean = static_cast<Mean>(size) * (1.0 - probToSuccess) / probToSuccess;\r\n    constexpr Mean expectedVariance = expectedMean / probToSuccess;\r\n    constexpr Value maxNumber = 200;\r\n    constexpr Value trialSize = 1000000;\r\n\r\n    const auto dist = MakeNegativeBinomialDistribution(size, probToSuccess, maxNumber, trialSize);\r\n    const auto actual = GetMeanVariance(dist, 0.001);\r\n    EXPECT_EQ(expectedMean, std::round(actual.mean));\r\n    EXPECT_EQ(std::round(expectedVariance), std::round(actual.variance));\r\n}\r\n\r\nTEST_F(TestMergeProbabilityDensity, SumNormals) {\r\n    const std::vector<Moments> testCases {{410, 16}, {450, 25}, {460, 36}, {470, 49}};\r\n    const std::vector<Moments>::size_type testCaseSize = testCases.size();\r\n    constexpr Value maxNumber = 900;\r\n    constexpr Value trialSize = 1000000;\r\n\r\n    for(auto size = decltype(testCaseSize){1}; size <= testCaseSize; ++size) {\r\n        ProbabilityDensity accumDist;\r\n        Mean expectedMean = 0.0;\r\n        Mean expectedVariance = 0.0;\r\n        for(auto i = decltype(size){0}; i < size; ++i) {\r\n            auto mean = testCases.at(i).mean;\r\n            auto variance = testCases.at(i).variance;\r\n            expectedMean += mean;\r\n            expectedVariance += variance;\r\n            const auto dist = MakeNormalDistribution(mean, variance, maxNumber, trialSize);\r\n            accumDist = MergeProbabilityDensity(accumDist, dist);\r\n        }\r\n\r\n        const auto actual = GetMeanVariance(accumDist, 0.1);\r\n        EXPECT_TRUE(((expectedMean - 1) < actual.mean) && (actual.mean < (expectedMean + 1)));\r\n        EXPECT_TRUE(((expectedVariance - 1) < actual.variance) && (actual.variance < (expectedVariance + 1)));\r\n    }\r\n}\r\n\r\nTEST_F(TestMergeProbabilityDensity, SumPoisson) {\r\n    const std::vector<Mean> testCases {4, 8, 12, 16};\r\n    const std::vector<Moments>::size_type testCaseSize = testCases.size();\r\n    constexpr Value maxNumber = 255;\r\n    constexpr Value trialSize = 100000;\r\n\r\n    for(auto size = decltype(testCaseSize){1}; size <= testCaseSize; ++size) {\r\n        ProbabilityDensity accumDist;\r\n        Mean expected = 0.0;\r\n        for(auto i = decltype(size){0}; i < size; ++i) {\r\n            auto mean = testCases.at(i);\r\n            expected += mean;\r\n            const auto dist = MakePoissonDistribution(mean, maxNumber, trialSize);\r\n            accumDist = MergeProbabilityDensity(accumDist, dist);\r\n        }\r\n\r\n        const auto actual = GetMeanVariance(accumDist, 0.1);\r\n        EXPECT_TRUE(((expected - 1) < actual.mean) && (actual.mean < (expected + 1)));\r\n        EXPECT_TRUE(((expected - 1) < actual.variance) && (actual.variance < (expected + 1)));\r\n    }\r\n}\r\n\r\nTEST_F(TestMergeProbabilityDensity, SumNegativeBinomial) {\r\n    struct Params {\r\n        Value size {0};\r\n        Mean probToSuccess {0.0};\r\n    };\r\n\r\n    const std::vector<Params> testCases {{3, 0.8}, {8, 0.6}, {10, 0.45}, {20, 0.7}};\r\n    const std::vector<Params>::size_type testCaseSize = testCases.size();\r\n    constexpr Value maxNumber = 200;\r\n    constexpr Value trialSize = 100000;\r\n\r\n    for(auto size = decltype(testCaseSize){1}; size <= testCaseSize; ++size) {\r\n        ProbabilityDensity accumDist;\r\n        Mean expectedMean = 0.0;\r\n        Mean expectedVariance = 0.0;\r\n        for(auto i = decltype(size){0}; i < size; ++i) {\r\n            const auto& testCase = testCases[i];\r\n            auto mean = static_cast<Mean>(testCase.size) * (1.0 - testCase.probToSuccess) / testCase.probToSuccess;\r\n            auto variance = mean / testCase.probToSuccess;\r\n            expectedMean += mean;\r\n            expectedVariance += variance;\r\n            const auto dist = MakeNegativeBinomialDistribution(testCase.size, testCase.probToSuccess, maxNumber, trialSize);\r\n            accumDist = MergeProbabilityDensity(accumDist, dist);\r\n        }\r\n\r\n        const auto actual = GetMeanVariance(accumDist, 0.1);\r\n        EXPECT_TRUE(((expectedMean - 1) < actual.mean) && (actual.mean < (expectedMean + 1)));\r\n        EXPECT_TRUE(((expectedVariance - 1) < actual.variance) && (actual.variance < (expectedVariance + 1)));\r\n    }\r\n}\r\n\r\nclass TestBoostAccumulators : public ::testing::Test {};\r\n\r\nTEST_F(TestBoostAccumulators, Weighted) {\r\n    using namespace boost::accumulators;\r\n    constexpr Mean EpsilonAcc = 0.001;\r\n\r\n    accumulator_set<Mean, stats<tag::weighted_mean, tag::weighted_variance(lazy)>, Mean> accLazy;\r\n    accLazy(-3.0, weight = 1.0);\r\n    accLazy(-1.0, weight = 3.0);\r\n    accLazy(1.0, weight = 6.0);\r\n    accLazy(5.0, weight = 0.0);\r\n    EXPECT_NEAR(0.0, mean(accLazy), EpsilonAcc);\r\n    EXPECT_NEAR(1.8, variance(accLazy), EpsilonAcc);\r\n\r\n    accumulator_set<Mean, stats<tag::weighted_mean, tag::weighted_variance>, Mean> accNonLazy;\r\n    accNonLazy(4.0, weight = 0.1);\r\n    accNonLazy(6.0, weight = 0.3);\r\n    accNonLazy(8.0, weight = 0.6);\r\n    accNonLazy(12.0, weight = 0.0);\r\n    EXPECT_NEAR(7.0, mean(accNonLazy), EpsilonAcc);\r\n    EXPECT_NEAR(1.8, variance(accNonLazy), EpsilonAcc);\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n    ::testing::InitGoogleTest(&argc, argv);\r\n    return RUN_ALL_TESTS();\r\n}\r\n\r\n/*\r\nLocal Variables:\r\nmode: c++\r\ncoding: utf-8-dos\r\ntab-width: nil\r\nc-file-style: \"stroustrup\"\r\nEnd:\r\n*/\r\n", "meta": {"hexsha": "0a8a67d7b1676c5cc329daad247fe4a61d5d5916", "size": 12229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scripts/merge_density/merge_density.cpp", "max_stars_repo_name": "zettsu-t/cPlusPlusFriend", "max_stars_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-04-15T00:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-10T05:11:14.000Z", "max_issues_repo_path": "scripts/merge_density/merge_density.cpp", "max_issues_repo_name": "zettsu-t/cPlusPlusFriend", "max_issues_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/merge_density/merge_density.cpp", "max_forks_repo_name": "zettsu-t/cPlusPlusFriend", "max_forks_repo_head_hexsha": "5399065abe2c0eda2b9aec26e6435d8c27cda9cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-23T22:47:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-23T22:47:08.000Z", "avg_line_length": 37.7438271605, "max_line_length": 125, "alphanum_fraction": 0.6510753128, "num_tokens": 3090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6441728346833335}}
{"text": "/*\n * CNN demo for MNIST dataset\n * Author: Kai Han (kaihana@163.com)\n * Details in https://github.com/iamhankai/mini-dnn-cpp\n * Copyright 2018 Kai Han\n */\n#include <Eigen/Dense>\n#include <algorithm>\n#include <iostream>\n\n#include \"src/layer.h\"\n#include \"src/layer/conv.h\"\n#include \"src/layer/fully_connected.h\"\n#include \"src/layer/ave_pooling.h\"\n#include \"src/layer/max_pooling.h\"\n#include \"src/layer/relu.h\"\n#include \"src/layer/sigmoid.h\"\n#include \"src/layer/softmax.h\"\n#include \"src/loss.h\"\n#include \"src/loss/mse_loss.h\"\n#include \"src/loss/cross_entropy_loss.h\"\n#include \"src/mnist.h\"\n#include \"src/network.h\"\n#include \"src/optimizer.h\"\n#include \"src/optimizer/sgd.h\"\n\n\nint main() {\n  // data\n  MNIST dataset(\"../data/mnist/\");\n  dataset.read();\n  int n_train = dataset.train_data.cols();\n  int dim_in = dataset.train_data.rows();\n  std::cout << \"mnist train number: \" << n_train << std::endl;\n  std::cout << \"mnist test number: \" << dataset.test_labels.cols() << std::endl;\n  // dnn\n  Network dnn;\n  Layer* conv1 = new Conv(1, 28, 28, 4, 5, 5, 2, 2, 2);\n  Layer* pool1 = new MaxPooling(4, 14, 14, 2, 2, 2);\n  Layer* conv2 = new Conv(4, 7, 7, 16, 5, 5, 1, 2, 2);\n  Layer* pool2 = new MaxPooling(16, 7, 7, 2, 2, 2);\n  Layer* fc3 = new FullyConnected(pool2->output_dim(), 32);\n  Layer* fc4 = new FullyConnected(32, 10);\n  Layer* relu1 = new ReLU;\n  Layer* relu2 = new ReLU;\n  Layer* relu3 = new ReLU;\n  Layer* softmax = new Softmax;\n  dnn.add_layer(conv1);\n  dnn.add_layer(relu1);\n  dnn.add_layer(pool1);\n  dnn.add_layer(conv2);\n  dnn.add_layer(relu2);\n  dnn.add_layer(pool2);\n  dnn.add_layer(fc3);\n  dnn.add_layer(relu3);\n  dnn.add_layer(fc4);\n  dnn.add_layer(softmax);\n  // loss\n  Loss* loss = new CrossEntropy;\n  dnn.add_loss(loss);\n  // train & test\n  SGD opt(0.001, 5e-4, 0.9, true);\n  // SGD opt(0.001);\n  const int n_epoch = 5;\n  const int batch_size = 128;\n  for (int epoch = 0; epoch < n_epoch; epoch ++) {\n    shuffle_data(dataset.train_data, dataset.train_labels);\n    for (int start_idx = 0; start_idx < n_train; start_idx += batch_size) {\n      int ith_batch = start_idx / batch_size;\n      Matrix x_batch = dataset.train_data.block(0, start_idx, dim_in,\n                                    std::min(batch_size, n_train - start_idx));\n      Matrix label_batch = dataset.train_labels.block(0, start_idx, 1,\n                                    std::min(batch_size, n_train - start_idx));\n      Matrix target_batch = one_hot_encode(label_batch, 10);\n      if (false && ith_batch % 10 == 1) {\n        std::cout << ith_batch << \"-th grad: \" << std::endl;\n        dnn.check_gradient(x_batch, target_batch, 10);\n      }\n      dnn.forward(x_batch);\n      dnn.backward(x_batch, target_batch);\n      // display\n      if (ith_batch % 50 == 0) {\n        std::cout << ith_batch << \"-th batch, loss: \" << dnn.get_loss()\n        << std::endl;\n      }\n      // optimize\n      dnn.update(opt);\n    }\n    // test\n    dnn.forward(dataset.test_data);\n    float acc = compute_accuracy(dnn.output(), dataset.test_labels);\n    std::cout << std::endl;\n    std::cout << epoch + 1 << \"-th epoch, test acc: \" << acc << std::endl;\n    std::cout << std::endl;\n  }\n  return 0;\n}\n\n", "meta": {"hexsha": "2a71bcb4ec052a9a81f4825d3664ab391d0a5bba", "size": 3164, "ext": "cc", "lang": "C++", "max_stars_repo_path": "demo.cc", "max_stars_repo_name": "iamhankai/mini-dnn-cpp", "max_stars_repo_head_hexsha": "e56e07d26fb9f498513f18822ddaf6d12b8f82ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2019-02-09T15:25:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T00:58:22.000Z", "max_issues_repo_path": "demo.cc", "max_issues_repo_name": "iamhankai/mini-dnn-cpp", "max_issues_repo_head_hexsha": "e56e07d26fb9f498513f18822ddaf6d12b8f82ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-11T16:57:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-09T00:21:22.000Z", "max_forks_repo_path": "demo.cc", "max_forks_repo_name": "iamhankai/mini-dnn-cpp", "max_forks_repo_head_hexsha": "e56e07d26fb9f498513f18822ddaf6d12b8f82ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-10-21T13:23:54.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T05:30:04.000Z", "avg_line_length": 31.9595959596, "max_line_length": 80, "alphanum_fraction": 0.6270543616, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248157222395, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6441235666124716}}
{"text": "/*\nCopyright (c) 2018 Inverse Palindrome\nApophis - Conversions.hpp\nInversePalindrome.com\n*/\n\n\n#pragma once\n\n#include <boost/math/constants/constants.hpp>\n\n\nnamespace Conversions\n{\n    template<typename T>\n    T degreesToRadians(T degrees)\n    {\n        return degrees * boost::math::constants::pi<T>() / (T)180;\n    }\n\n    template<typename T>\n    T radiansToDegrees(T radians)\n    {\n        return radians * (T)180 / boost::math::constants::pi<T>();\n    }\n}", "meta": {"hexsha": "291de7886c60d3a926643f47187b4e01d9020ea1", "size": 458, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Classes/Conversions.hpp", "max_stars_repo_name": "InversePalindrome/Apophis", "max_stars_repo_head_hexsha": "c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-20T17:28:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-05T15:19:31.000Z", "max_issues_repo_path": "Classes/Conversions.hpp", "max_issues_repo_name": "InversePalindrome/JATR66", "max_issues_repo_head_hexsha": "c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Classes/Conversions.hpp", "max_forks_repo_name": "InversePalindrome/JATR66", "max_forks_repo_head_hexsha": "c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T12:02:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-25T12:02:03.000Z", "avg_line_length": 17.6153846154, "max_line_length": 66, "alphanum_fraction": 0.6528384279, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.644103369120188}}
{"text": "#include <iostream>\n#include <typeinfo>\r\n#define BOOST_TEST_MODULE DenseMIASolveTests\n\r\n\n\n#include \"MIAConfig.h\"\n\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\n\r\n#include \"DenseMIA.h\"\n#include \"Index.h\"\n\r\ntemplate<class _data_type>\r\nvoid solve_work(size_t dim1,size_t dim2){\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n    LibMIA::MIAINDEX l;\r\n    LibMIA::MIAINDEX m;\r\n    LibMIA::MIAINDEX n;\r\n    LibMIA::MIAINDEX o;\r\n    LibMIA::MIAINDEX p;\n\n    LibMIA::DenseMIA<_data_type,4> a(dim1,dim1,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> a2(dim2,dim2,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> b(dim1,dim1,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> b2(dim2,dim2,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> c(dim1,dim1,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> d(dim1,dim1,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> d2(dim1,dim1,dim1,dim1);\r\n\r\n    a.randu(-30,30); //we can invert these, b/c random matrices are non-singular with probability one (almost surely)\r\n    b.randu(-30,30);\r\n    a2.randu(-30,30);\r\n    b2.randu(-30,30);\r\n\r\n    c(i,j,m,n)=a(i,j,k,l)|b(k,l,m,n);\r\n    d(k,l,m,n)=a(i,j,k,l)*c(i,j,m,n);\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(b,test_precision<_data_type>()),std::string(\"Inner/Outer Product Inverse 1 for \")+typeid(_data_type).name() );\r\n\r\n    c(i,j,m,n)=a(i,k,j,l)|b(k,l,m,n);\r\n    d(k,l,m,n)=a(i,k,j,l)*c(i,j,m,n);\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(b,test_precision<_data_type>()),std::string(\"Inner/Outer Product Inverse 2 for \")+typeid(_data_type).name() );\r\n\r\n    c(i,j,l,m)=a(i,!j,k,!l)|b(k,!j,!l,m);\r\n    d(k,j,l,m)=a(i,!j,k,!l)*c(i,!j,!l,m);\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(b,test_precision<_data_type>()),std::string(\"Inner/Outer/Inter Product Inverse 1 for \")+typeid(_data_type).name() );\r\n\r\n    c(i,j,l,m)=a(!i,!j,k,l)|b(m,!j,k,!i);\r\n    d(m,j,k,i)=a(!i,!j,k,l)*c(!i,!j,l,m);\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(b,test_precision<_data_type>()),std::string(\"Inner/Outer/Inter Product Inverse 2 for \")+typeid(_data_type).name() );\r\n\r\n\r\n    c(i,j,m,n)=a2(k,l,i,j)|b2(k,l,m,n);\r\n    //test with normal equations\r\n    d(o,p,m,n)=a2(k,l,o,p)*a2(k,l,i,j)*c(i,j,m,n);\r\n    d2(i,j,m,n)=a2(k,l,i,j)*b2(k,l,m,n);\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(d2,test_precision<_data_type>()),std::string(\"Inner/Outer Product Least Squares 1 for \")+typeid(_data_type).name() );\r\n\r\n    c(i,j,k,l)=a(!i,!j,!k,!l)|b(!k,!j,!l,!i);\r\n    d(k,j,l,i)=a(!i,!j,!k,!l)*c(!i,!j,!k,!l);\r\n    BOOST_CHECK_MESSAGE(d.fuzzy_equals(b,test_precision<_data_type>()),std::string(\"Pure Inter-product Inverse 1 for \")+typeid(_data_type).name() );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( DenseMIASolveTests )\n{\n\n\r\n\r\n    solve_work<double>(8,10);\r\n\n    solve_work<float>(8,10);\r\n\r\n\r\n\r\n\r\n\n\n}\n", "meta": {"hexsha": "262e2719930a435807edb33c5ee35fc7f1eae437", "size": 2833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/DenseMIA/dense_mia_solve_test.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/DenseMIA/dense_mia_solve_test.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/DenseMIA/dense_mia_solve_test.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 32.5632183908, "max_line_length": 157, "alphanum_fraction": 0.6410165902, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6441033668991594}}
{"text": "//\n//  GrowthHelper.hpp\n//  Elasticity\n//\n//  Created by Wim van Rees on 8/17/16.\n//  Copyright \u00a9 2016 Wim van Rees. All rights reserved.\n//\n\n#ifndef GrowthHelper_hpp\n#define GrowthHelper_hpp\n\n#include \"common.hpp\"\n#include \"TriangleInfo.hpp\"\n\n#include <Eigen/Eigenvalues>\n#include <unsupported/Eigen/MatrixFunctions>\n\n\nclass DecomposedGrowthState\n{\nprotected:\n    Real s1, s2;\n    Eigen::Vector3d v1, v2;\n    \n    void decompose_metric(const Eigen::MatrixXd & rxy, const Eigen::Matrix2d & metric)\n    {\n        // decompute metric\n        const Eigen::Matrix2d a_i = rxy.transpose() * rxy;\n        \n        // compute delta_metric\n        const Eigen::Matrix2d delta_a = a_i.inverse() * metric;\n        \n        // eigensolver\n        Eigen::EigenSolver<Eigen::Matrix2d> es(delta_a);\n        const Eigen::Vector2d evals = es.eigenvalues().real();\n        const Eigen::Matrix2d evecs = es.eigenvectors().real();\n        \n        // evecs is the V-matrix (generalized eigen-vectors) but not appropriately normalized yet -- normalize\n        // const Eigen::Matrix2d shouldBeI = evecs.transpose() * a_i * evecs;\n        // const Eigen::Matrix2d V = evecs * shouldBeI.inverse().sqrt();\n        \n        const Eigen::MatrixXd v12_evec = rxy * evecs;\n        Eigen::Vector3d v1_evec = v12_evec.col(0).normalized();\n        Eigen::Vector3d v2_evec = v12_evec.col(1).normalized();\n        \n        // note: for everything else here we assume that v1 and v2 are orthogonal\n        // however if s1==s2 --> the values of v1 and v2 are arbitrary and so from whatever we do above, they might turn out to not be orthogonal\n        // so, in this case we orthogonalize them by hand (they are already normalized)\n        // but since we can still have them equal, instead we set them equal to rxy_1 and rxy_2 first and orthogonalize second\n        if(std::abs(evals(0) - evals(1)) < 1e-12)\n        {\n            v1_evec = rxy.col(0);\n            v2_evec = rxy.col(1);\n            \n            v1_evec.normalize();\n            v2_evec = v2_evec - v1_evec.dot(v2_evec)*v1_evec;\n            v2_evec.normalize();\n        }\n        \n        // finally we assign\n        s1 = std::sqrt(evals(0));\n        s2 = std::sqrt(evals(1));\n        v1 = v1_evec;\n        v2 = v2_evec;\n        \n        if(s2 > s1) // make sure that s1 is the biggest (does not matter really, just convention -- will still give the same matrix)\n        {\n            std::swap(s1,s2);\n            v1.swap(v2);\n        }\n#ifndef NDEBUG\n        if(not checkVectorValidity())\n        {\n            std::cout << \"decomposition is not valid : the eigenvectors are not unit length and/or not orthogonal\" << std::endl;\n            print();\n            printf(\"computed eigenvalues are %10.10e \\t %10.10e\\n\", evals(0), evals(1));\n            printf(\"computed evec1 is %10.10e \\t %10.10e\\n\", evecs(0,0), evecs(1,0));\n            printf(\"computed evec2 is %10.10e \\t %10.10e\\n\", evecs(0,1), evecs(1,1));\n            printf(\"input rxy_1 is %10.10e \\t %10.10e \\t %10.10e\\n\", rxy(0,0), rxy(1,0), rxy(2,0));\n            printf(\"input rxy_2 is %10.10e \\t %10.10e \\t %10.10e\\n\", rxy(0,1), rxy(1,1), rxy(2,1));\n            printf(\"input metric is %10.10e \\t %10.10e \\t %10.10e\\n\", metric(0,0), metric(0,1), metric(1,1));\n            \n            assert(checkVectorValidity());\n        }\n#endif\n    }\n    \npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW // https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\n    \n    DecomposedGrowthState(const Real s1_in, const Real s2_in, const Eigen::Vector3d & v1_in, const Eigen::Vector3d & v2_in):\n    s1(s1_in),\n    s2(s2_in),\n    v1(v1_in),\n    v2(v2_in)\n    {}\n    \n    DecomposedGrowthState(const Eigen::MatrixXd & rxy, const Eigen::Matrix2d & metric)\n    {\n        decompose_metric(rxy, metric);\n    }\n    \n    void changeMetric(const Eigen::MatrixXd & rxy, const Eigen::Matrix2d & metric)\n    {\n        decompose_metric(rxy, metric);\n    }\n    \n    bool checkVectorValidity(const Real tol = 1e-9) const\n    {\n        const bool unit_v1 = std::abs(v1.dot(v1) - 1) < tol;\n        const bool unit_v2 = std::abs(v2.dot(v2) - 1) < tol;\n        const bool ortho = std::abs(v1.dot(v2)) < tol;\n        return (unit_v1 and unit_v2 and ortho);\n    }\n    \n    void print() const\n    {\n        printf(\"s1/s2 : %10.10e \\t %10.10e \\t\\t v1 : %10.10e, %10.10e, %10.10e \\t v2 : %10.10e, %10.10e, %10.10e\\n\",s1,s2,v1(0),v1(1),v1(2),v2(0),v2(1),v2(2));\n    }\n    \n    Eigen::Matrix2d computeMetric(const Eigen::MatrixXd & rxy) const\n    {\n        const Eigen::Matrix2d a_i = rxy.transpose() * rxy;\n        const Eigen::Matrix2d Lsq = (Eigen::Matrix2d() << s1*s1,0,0,s2*s2).finished();\n        Eigen::MatrixXd v12(3,2);\n        v12 << v1,v2;\n        const Eigen::Matrix2d V = (v12.transpose() * rxy).inverse();\n        const Eigen::Matrix2d a_f = a_i * V * Lsq * V.transpose() * a_i;\n        return a_f;\n    }\n    \n    Real get_s1() const {return s1;}\n    Real get_s2() const {return s2;}\n    Eigen::Vector3d get_v1() const {return v1;}\n    Eigen::Vector3d get_v2() const {return v2;}\n};\n\nclass GrowthState\n{\nprotected:\n    const Eigen::MatrixXd rxy_base;\n    const Eigen::Matrix2d a_final;\n    const DecomposedGrowthState decomposed_final;\n    Eigen::Matrix2d a_init;\n    DecomposedGrowthState decomposed_init;\n    \npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW // https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\n    \n    GrowthState(const Eigen::MatrixXd & rxy_base_in, const Eigen::Matrix2d & a_final_in):\n    rxy_base(rxy_base_in),\n    a_final(a_final_in),\n    decomposed_final(rxy_base, a_final),\n    a_init(rxy_base.transpose() * rxy_base),\n    decomposed_init(rxy_base, a_init)\n    {\n    }\n    \n    GrowthState(const Eigen::MatrixXd & rxy_base_in, const Eigen::Matrix2d & a_init_in, const Eigen::Matrix2d & a_final_in):\n    rxy_base(rxy_base_in),\n    a_final(a_final_in),\n    decomposed_final(rxy_base, a_final),\n    a_init(a_init_in),\n    decomposed_init(rxy_base, a_init)\n    {\n    }\n    \n    \n    void changeInitialState(const Eigen::Matrix2d & a_init_in)\n    {\n        a_init = a_init_in;\n        decomposed_init.changeMetric(rxy_base, a_init);\n    }\n    \n    Eigen::Matrix2d interpolate_from_iso(const Real t) const\n    {\n        // we start from isotropic : just interpolate the growth factors\n        const Real s1_interp = (1.0 - t) * decomposed_init.get_s1() + t*decomposed_final.get_s1();\n        const Real s2_interp = (1.0 - t) * decomposed_init.get_s2() + t*decomposed_final.get_s2();\n        \n        const DecomposedGrowthState decomposed_intermediate(s1_interp, s2_interp, decomposed_final.get_v1(), decomposed_final.get_v2());\n        return decomposed_intermediate.computeMetric(rxy_base);\n    }\n    \n    Eigen::Matrix2d interpolate_from_iso_logeucl(const Real t) const\n    {\n        // we start from isotropic : just interpolate the growth factors\n        const Real s1_interp = std::exp( (1.0 - t) * std::log(decomposed_init.get_s1()) + t*std::log(decomposed_final.get_s1()) );\n        const Real s2_interp = std::exp( (1.0 - t) * std::log(decomposed_init.get_s2()) + t*std::log(decomposed_final.get_s2()) );\n        \n        const DecomposedGrowthState decomposed_intermediate(s1_interp, s2_interp, decomposed_final.get_v1(), decomposed_final.get_v2());\n        return decomposed_intermediate.computeMetric(rxy_base);\n    }\n    \n    Eigen::Matrix2d interpolate(const Real t) const\n    {\n        if(std::abs(decomposed_init.get_s1() - decomposed_init.get_s2()) < 1e-12) return interpolate_from_iso(t);\n        \n        // t between 0 and 1\n        return (1.0 - t)*a_init + t*a_final;\n    }\n    \n    Eigen::Matrix2d interpolateLogEucl(const Real t) const\n    {\n        if(std::abs(decomposed_init.get_s1() - decomposed_init.get_s2()) < 1e-12) return interpolate_from_iso_logeucl(t);\n        \n        // t between 0 and 1\n        return ((1.0 - t)*a_init.log() + t * a_final.log()).exp();\n    }\n    \n    Eigen::Matrix2d getInitGrowthMetric() const\n    {\n        return a_init;\n    }\n    \n    Eigen::Matrix2d getFinalGrowthMetric() const\n    {\n        return a_final;\n    }\n    \n    const DecomposedGrowthState & getDecomposedInitState() const\n    {\n        return decomposed_init;\n    }\n    \n    const DecomposedGrowthState & getDecomposedFinalState() const\n    {\n        return decomposed_final;\n    }\n};\n\n\n\ntemplate<typename tMesh>\nstruct GrowthHelper\n{\n    static void anglesToVectors(const Eigen::Ref<const Eigen::VectorXd> angles, Eigen::Ref<Eigen::MatrixXd> vectors, const Real phase = 0)\n    {\n        const int nFaces = angles.rows();\n        for(int i=0;i<nFaces;++i)\n        {\n            const Real phi = angles(i);\n            const Eigen::Vector3d dir = (Eigen::Vector3d() <<  std::cos(phi + phase), std::sin(phi + phase), 0).finished();\n            for(int d=0;d<3;++d)\n                vectors(i,d) = dir(d);\n        }\n    }\n    \n    static void anglesToVectors(const Eigen::Ref<const Eigen::VectorXd> angles, const Eigen::Ref<const Eigen::VectorXd> lengths, Eigen::Ref<Eigen::MatrixXd> vectors, const Real phase = 0)\n    {\n        const int nFaces = angles.rows();\n        for(int i=0;i<nFaces;++i)\n        {\n            const Real phi = angles(i);\n            const Eigen::Vector3d dir = (Eigen::Vector3d() <<  std::cos(phi + phase), std::sin(phi + phase), 0).finished();\n            for(int d=0;d<3;++d)\n                vectors(i,d) = lengths(i)*dir(d);\n        }\n    }\n    \n    static void vectorsToAngles(const Eigen::Ref<const Eigen::MatrixXd> dir1, const Eigen::Ref<const Eigen::MatrixXd> dir2, Eigen::Ref<Eigen::VectorXd> angles, Eigen::Ref<Eigen::VectorXd> growthRates1, Eigen::Ref<Eigen::VectorXd> growthRates2)\n    {\n        const int nFaces = dir1.rows();\n        for(int i=0;i<nFaces;++i)\n        {\n            const Eigen::Vector3d & dir1_i = dir1.row(i);\n            const Eigen::Vector3d & dir2_i = dir2.row(i);\n            \n            const Real mag_dir1_i = dir1_i.norm();\n            const Real mag_dir2_i = dir2_i.norm();\n\n            const Real angle_i = std::atan2(dir1_i(1), dir1_i(0));\n            \n            // fill the arrays\n            angles(i) = angle_i;\n            growthRates1(i) = mag_dir1_i;\n            growthRates2(i) = mag_dir2_i;\n\n        }\n    }\n    static void computeAbarsIsoGrowth(const tMesh & mesh, const Eigen::Ref<const Eigen::VectorXd> growthRates, tVecMat2d & aforms)\n    {\n        const int nFaces = mesh.getNumberOfFaces();\n        const auto & topo = mesh.getTopology();\n        const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n        \n        aforms.resize(nFaces);\n        \n        for(int i=0;i<nFaces;++i)\n        {\n            const TriangleInfo info = reststate.getTriangleInfoLite(topo, i);\n            const Real growth = std::pow(1 + growthRates(i),2);\n            \n            const Eigen::Vector3d dir_p = (Eigen::Vector3d() << 1, 0, 0).finished();\n            const Eigen::Vector3d dir_o = (Eigen::Vector3d() << 0, 1, 0).finished();\n            \n            const Real e1_p = (info.e1).dot(dir_p);\n            const Real e1_o = (info.e1).dot(dir_o);\n            \n            const Real e2_p = (info.e2).dot(dir_p);\n            const Real e2_o = (info.e2).dot(dir_o);\n            \n            const Real a11 = (e1_p*e1_p + e1_o*e1_o)*growth;\n            const Real a12 = (e1_p*e2_p + e1_o*e2_o)*growth;\n            const Real a22 = (e2_p*e2_p + e2_o*e2_o)*growth;\n            \n            aforms[i](0,0) = a11;\n            aforms[i](0,1) = aforms[i](1,0) = a12;\n            aforms[i](1,1) = a22;\n        }\n    }\n    \n    static void computeAbarsIsoGrowth_Gradient(const tMesh & mesh, const Eigen::Ref<const Eigen::VectorXd> growthRates, const Eigen::Ref<const Eigen::MatrixXd> gradEng_abar, Eigen::Ref<Eigen::VectorXd> gradEng_rate)\n    {\n        // compute gradient abar wrt growth\n        const int nFaces = mesh.getNumberOfFaces();\n        const auto & topo = mesh.getTopology();\n        const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n        \n        for(int i=0;i<nFaces;++i)\n        {\n            const TriangleInfo info = reststate.getTriangleInfoLite(topo, i);\n            const Real dgrowth = 2.0*(1 + growthRates(i));\n            \n            const Eigen::Vector3d dir_p = (Eigen::Vector3d() << 1, 0, 0).finished();\n            const Eigen::Vector3d dir_o = (Eigen::Vector3d() << 0, 1, 0).finished();\n            \n            const Real e1_p = (info.e1).dot(dir_p);\n            const Real e1_o = (info.e1).dot(dir_o);\n            \n            const Real e2_p = (info.e2).dot(dir_p);\n            const Real e2_o = (info.e2).dot(dir_o);\n            \n            const Real da11 = (e1_p*e1_p + e1_o*e1_o)*dgrowth;\n            const Real da12 = (e1_p*e2_p + e1_o*e2_o)*dgrowth;\n            const Real da22 = (e2_p*e2_p + e2_o*e2_o)*dgrowth;\n            \n            gradEng_rate(i) = gradEng_abar(i,0)*da11 + gradEng_abar(i,1)*da12 + gradEng_abar(i,2)*da22;\n        }\n    }\n    \n    static void computeAbarsOrthoGrowth(const tMesh & mesh, const Eigen::Ref<const Eigen::VectorXd> growthAngles, const Eigen::Ref<const Eigen::VectorXd> growthRates_p, const Eigen::Ref<const Eigen::VectorXd> growthRates_o, tVecMat2d & aforms)\n    {\n        const int nFaces = mesh.getNumberOfFaces();\n        const auto & topo = mesh.getTopology();\n        const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n        \n        aforms.resize(nFaces);\n        \n        for(int i=0;i<nFaces;++i)\n        {\n            const TriangleInfo info = reststate.getTriangleInfoLite(topo, i);\n            \n            const Real growth_p = std::pow(1 + growthRates_p(i),2);\n            const Real growth_o = std::pow(1 + growthRates_o(i),2);\n            const Real phi = growthAngles(i);\n            \n            const Eigen::Vector3d dir_p = (Eigen::Vector3d() <<  std::cos(phi), std::sin(phi), 0).finished();\n            const Eigen::Vector3d dir_o = (Eigen::Vector3d() << -std::sin(phi), std::cos(phi), 0).finished();\n\n//          new edges are the following\n//          const Eigen::Vector3d e0_new = (1.0 + growthRate_p)*(e0.dot(dir_p))*dir_p + (1.0 + growthRate_o)*(e0.dot(dir_o))*dir_o;\n//          const Eigen::Vector3d e1_new = (1.0 + growthRate_p)*(e1.dot(dir_p))*dir_p + (1.0 + growthRate_o)*(e1.dot(dir_o))*dir_o;\n//          const Eigen::Vector3d e2_new = (1.0 + growthRate_p)*(e2.dot(dir_p))*dir_p + (1.0 + growthRate_o)*(e2.dot(dir_o))*dir_o;\n//          a11 = e1_new.dot(e1_new), a12 = e1_new.dot(e2_new), a22 = e2_new.dot(e2_new)\n//          also : e0_new + e1_new + e2_new = 0\n            \n            const Real e1_p = (info.e1).dot(dir_p);\n            const Real e1_o = (info.e1).dot(dir_o);\n            \n            const Real e2_p = (info.e2).dot(dir_p);\n            const Real e2_o = (info.e2).dot(dir_o);\n            \n            const Real a11 = e1_p*e1_p*growth_p + e1_o*e1_o*growth_o;\n            const Real a12 = e1_p*e2_p*growth_p + e1_o*e2_o*growth_o;\n            const Real a22 = e2_p*e2_p*growth_p + e2_o*e2_o*growth_o;\n            \n            aforms[i](0,0) = a11;\n            aforms[i](0,1) = aforms[i](1,0) = a12;\n            aforms[i](1,1) = a22;\n        }\n    }\n    \n    static void computeAbarsOrthoGrowth_Gradient(const tMesh & mesh, const Eigen::Ref<const Eigen::VectorXd> growthAngles, const Eigen::Ref<const Eigen::VectorXd> growthRates_p, const Eigen::Ref<const Eigen::VectorXd> growthRates_o, const Eigen::Ref<const Eigen::MatrixXd> gradEng_abar, Eigen::Ref<Eigen::VectorXd> gradEng_angle, Eigen::Ref<Eigen::VectorXd> gradEng_rate_p, Eigen::Ref<Eigen::VectorXd> gradEng_rate_o)\n    {\n        // compute gradient abar wrt growth\n        const int nFaces = mesh.getNumberOfFaces();\n        const auto & topo = mesh.getTopology();\n        const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n        \n        for(int i=0;i<nFaces;++i)\n        {\n            const TriangleInfo info = reststate.getTriangleInfoLite(topo, i);\n            \n            const Real growth_p = std::pow(1 + growthRates_p(i),2);\n            const Real growth_o = std::pow(1 + growthRates_o(i),2);\n            const Real phi = growthAngles(i);\n\n            const Eigen::Vector3d dir_p = (Eigen::Vector3d() <<  std::cos(phi), std::sin(phi), 0).finished();\n            const Eigen::Vector3d dir_o = (Eigen::Vector3d() << -std::sin(phi), std::cos(phi), 0).finished();\n\n            // derivatives\n            const Real dgrowth_p = 2.0*(1 + growthRates_p(i));\n            const Real dgrowth_o = 2.0*(1 + growthRates_o(i));\n            \n            const Eigen::Vector3d ddir_p = (Eigen::Vector3d() << -std::sin(phi),  std::cos(phi), 0).finished();\n            const Eigen::Vector3d ddir_o = (Eigen::Vector3d() << -std::cos(phi), -std::sin(phi), 0).finished();\n            \n            \n            const Real e1_p = (info.e1).dot(dir_p);\n            const Real e1_o = (info.e1).dot(dir_o);\n            \n            const Real e2_p = (info.e2).dot(dir_p);\n            const Real e2_o = (info.e2).dot(dir_o);\n            \n            const Real e1_dp = (info.e1).dot(ddir_p);\n            const Real e1_do = (info.e1).dot(ddir_o);\n            \n            const Real e2_dp = (info.e2).dot(ddir_p);\n            const Real e2_do = (info.e2).dot(ddir_o);\n\n            const Real da11_dphi = 2.0*e1_p*e1_dp*growth_p + 2.0*e1_o*e1_do*growth_o;\n            const Real da12_dphi = (e1_p*e2_dp + e1_dp*e2_p)*growth_p + (e1_o*e2_do + e1_do*e2_o)*growth_o;\n            const Real da22_dphi = 2.0*e2_p*e2_dp*growth_p + 2.0*e2_o*e2_do*growth_o;\n            \n            const Real da11_dgrowth_p = e1_p*e1_p*dgrowth_p;\n            const Real da12_dgrowth_p = e1_p*e2_p*dgrowth_p;\n            const Real da22_dgrowth_p = e2_p*e2_p*dgrowth_p;\n            \n            const Real da11_dgrowth_o = e1_o*e1_o*dgrowth_o;\n            const Real da12_dgrowth_o = e1_o*e2_o*dgrowth_o;\n            const Real da22_dgrowth_o = e2_o*e2_o*dgrowth_o;\n            \n            gradEng_angle(i)  = gradEng_abar(i,0)*da11_dphi      + gradEng_abar(i,1)*da12_dphi      + gradEng_abar(i,2)*da22_dphi;\n            gradEng_rate_p(i) = gradEng_abar(i,0)*da11_dgrowth_p + gradEng_abar(i,1)*da12_dgrowth_p + gradEng_abar(i,2)*da22_dgrowth_p;\n            gradEng_rate_o(i) = gradEng_abar(i,0)*da11_dgrowth_o + gradEng_abar(i,1)*da12_dgrowth_o + gradEng_abar(i,2)*da22_dgrowth_o;\n        }\n    }\n    \n    \n    static void computeAbarsOrthoGrowth_GradientVertices(const tMesh & mesh, const Eigen::Ref<const Eigen::VectorXd> growthAngles, const Eigen::Ref<const Eigen::VectorXd> growthRates_p, const Eigen::Ref<const Eigen::VectorXd> growthRates_o, const Eigen::Ref<const Eigen::MatrixXd> gradEng_abar, Eigen::Ref<Eigen::MatrixXd> gradEng_verts)\n    {\n        // compute gradient abar wrt growth\n        const int nFaces = mesh.getNumberOfFaces();\n        const auto & topo = mesh.getTopology();\n        const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n        \n        for(int i=0;i<nFaces;++i)\n        {\n            const TriangleInfo info = reststate.getTriangleInfoLite(topo, i);\n            \n            const Real growth_p = std::pow(1 + growthRates_p(i),2);\n            const Real growth_o = std::pow(1 + growthRates_o(i),2);\n            const Real phi = growthAngles(i);\n            \n            const Eigen::Vector3d dir_p = (Eigen::Vector3d() <<  std::cos(phi), std::sin(phi), 0).finished();\n            const Eigen::Vector3d dir_o = (Eigen::Vector3d() << -std::sin(phi), std::cos(phi), 0).finished();\n            \n            // e1 = v2 - v1\n            // e2 = v0 - v2\n            const Real e1_p = (info.e1).dot(dir_p);\n            const Real e1_o = (info.e1).dot(dir_o);\n            \n            const Real e2_p = (info.e2).dot(dir_p);\n            const Real e2_o = (info.e2).dot(dir_o);\n            \n//            const Real a11 = e1_p*e1_p*growth_p + e1_o*e1_o*growth_o;\n//            const Real a12 = e1_p*e2_p*growth_p + e1_o*e2_o*growth_o;\n//            const Real a22 = e2_p*e2_p*growth_p + e2_o*e2_o*growth_o;\n            \n            const Eigen::Vector3d gradv0_a12 = e1_p*growth_p*dir_p + e1_o*growth_o*dir_o;\n            const Eigen::Vector3d gradv0_a22 = 2.0*(e2_p*growth_p*dir_p + e2_o*growth_o*dir_o);\n            \n            const Eigen::Vector3d gradv1_a11 = -2.0*(e1_p*growth_p*dir_p + e1_o*growth_o*dir_o);\n            const Eigen::Vector3d gradv1_a12 = -e2_p*growth_p*dir_p - e2_o*growth_o*dir_o;\n            \n            const Eigen::Vector3d gradv2_a11 = 2.0*(e1_p*growth_p*dir_p + e1_o*growth_o*dir_o);\n            const Eigen::Vector3d gradv2_a12 = growth_p*(e2_p - e1_p)*dir_p + growth_o*(e2_o - e1_o)*dir_o;\n            const Eigen::Vector3d gradv2_a22 = -2.0*(e2_p*growth_p*dir_p + e2_o*growth_o*dir_o);\n            \n            for(int d=0;d<2;++d)\n            {\n                gradEng_verts(info.idx_v0,d) += gradEng_abar(i,1)*gradv0_a12(d) + gradEng_abar(i,2)*gradv0_a22(d);\n                gradEng_verts(info.idx_v1,d) += gradEng_abar(i,0)*gradv1_a11(d) + gradEng_abar(i,1)*gradv1_a12(d);\n                gradEng_verts(info.idx_v2,d) += gradEng_abar(i,0)*gradv2_a11(d) + gradEng_abar(i,1)*gradv2_a12(d) + gradEng_abar(i,2)*gradv2_a22(d);\n            }\n            \n        }\n    }\n\n    \n    \n    static void computeAbarsOrthoGrowthShell(const tMesh & mesh, const Eigen::Ref<const Eigen::MatrixXd> growthdirs_1, const Eigen::Ref<const Eigen::VectorXd> growthRates_1, const Eigen::Ref<const Eigen::VectorXd> growthRates_2, tVecMat2d & aforms)\n    {\n        const int nFaces = mesh.getNumberOfFaces();\n        const auto & topo = mesh.getTopology();\n        const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n        \n        aforms.resize(nFaces);\n        \n        for(int i=0;i<nFaces;++i)\n        {\n            const TriangleInfo info = reststate.getTriangleInfoLite(topo, i);\n            \n            const Real growth_1 = std::pow(1 + growthRates_1(i),2);\n            const Real growth_2 = std::pow(1 + growthRates_2(i),2);\n            const Eigen::Vector3d dir_1 = growthdirs_1.row(i).normalized(); // should be normalized already but do it again just to be sure\n            \n            // get the face normal to compute dir_2\n            const Eigen::Vector3d facenormal = (info.e2).cross(info.e0).normalized();\n            const Eigen::Vector3d dir_2 = (facenormal.cross(dir_1)).normalized(); // so that dir_1 cross dir_2 = facenormal\n            \n            const Real e1_1 = (info.e1).dot(dir_1);\n            const Real e1_2 = (info.e1).dot(dir_2);\n            \n            const Real e2_1 = (info.e2).dot(dir_1);\n            const Real e2_2 = (info.e2).dot(dir_2);\n            \n            const Real a11 = e1_1*e1_1*growth_1 + e1_2*e1_2*growth_2;\n            const Real a12 = e1_1*e2_1*growth_1 + e1_2*e2_2*growth_2;\n            const Real a22 = e2_1*e2_1*growth_1 + e2_2*e2_2*growth_2;\n            \n            aforms[i](0,0) = a11;\n            aforms[i](0,1) = aforms[i](1,0) = a12;\n            aforms[i](1,1) = a22;\n        }\n    }\n    \n    \n    \n    \n    \n    \n    \n    \n    static void computeAbarsIsoGrowthPerEdge(const tMesh & mesh, const Eigen::Ref<const Eigen::VectorXd> growthRates, tVecMat2d & aforms)\n    {\n        // now the growth rates are prescribed per-edge\n        const int nFaces = mesh.getNumberOfFaces();\n        const auto & topo = mesh.getTopology();\n        const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n        \n        aforms.resize(nFaces);\n        \n        for(int i=0;i<nFaces;++i)\n        {\n            const TriangleInfo info = reststate.getTriangleInfoLite(topo, i);\n            const Real growth_e0 = std::pow(1 + growthRates(info.idx_e0), 2);\n            const Real growth_e1 = std::pow(1 + growthRates(info.idx_e1), 2);\n            const Real growth_e2 = std::pow(1 + growthRates(info.idx_e2), 2);\n            \n            const Real e0_magsq = (info.e0).dot(info.e0);\n            const Real e1_magsq = (info.e1).dot(info.e1);\n            const Real e2_magsq = (info.e2).dot(info.e2);\n            \n            const Real a11 = growth_e1 * e1_magsq;\n            const Real a12 = -0.5*( growth_e1 * e1_magsq + growth_e2 * e2_magsq - growth_e0 * e0_magsq ); // checked : this is correct\n            const Real a22 = growth_e2 * e2_magsq;\n            \n            aforms[i](0,0) = a11;\n            aforms[i](0,1) = aforms[i](1,0) = a12;\n            aforms[i](1,1) = a22;\n        }\n    }\n    \n    static void computeAbarsIsoGrowthPerEdge_Gradient(const tMesh & mesh, const Eigen::Ref<const Eigen::VectorXd> growthRates, const Eigen::Ref<const Eigen::MatrixXd> gradEng_abar, Eigen::Ref<Eigen::VectorXd> gradEng_rate)\n    {\n        // compute gradient abar wrt growth\n        const int nFaces = mesh.getNumberOfFaces();\n        const auto & topo = mesh.getTopology();\n        const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n        \n        for(int i=0;i<nFaces;++i)\n        {\n            const TriangleInfo info = reststate.getTriangleInfoLite(topo, i);\n            \n            const Real dgrowth_e0 = 2 * (1 + growthRates(info.idx_e0));\n            const Real dgrowth_e1 = 2 * (1 + growthRates(info.idx_e1));\n            const Real dgrowth_e2 = 2 * (1 + growthRates(info.idx_e2));\n            \n            const Real e0_magsq = (info.e0).dot(info.e0);\n            const Real e1_magsq = (info.e1).dot(info.e1);\n            const Real e2_magsq = (info.e2).dot(info.e2);\n            \n            const Real da11_e1 = dgrowth_e1 * e1_magsq;\n\n            const Real da12_e0 =  0.5 * dgrowth_e0 * e0_magsq;\n            const Real da12_e1 = -0.5 * dgrowth_e1 * e1_magsq;\n            const Real da12_e2 = -0.5 * dgrowth_e2 * e2_magsq;\n\n            const Real da22_e2 = dgrowth_e2 * e2_magsq;\n\n            gradEng_rate(info.idx_e0) += gradEng_abar(i,1)*da12_e0;\n            gradEng_rate(info.idx_e1) += gradEng_abar(i,0)*da11_e1 + gradEng_abar(i,1)*da12_e1;\n            gradEng_rate(info.idx_e2) += gradEng_abar(i,1)*da12_e2 + gradEng_abar(i,2)*da22_e2;\n        }\n    }\n    \n    \n    \n    \n    \n    static void computeAbarsIsoGrowthPerVertex(const tMesh & mesh, const Eigen::Ref<const Eigen::VectorXd> growthRates, tVecMat2d & aforms)\n    {\n        // now the growth rates are prescribed per-edge\n        const int nFaces = mesh.getNumberOfFaces();\n        const auto & topo = mesh.getTopology();\n        const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n        \n        aforms.resize(nFaces);\n        \n        for(int i=0;i<nFaces;++i)\n        {\n            const TriangleInfo info = reststate.getTriangleInfoLite(topo, i);\n            const Real growth_v0 = 1 + growthRates(info.idx_v0);\n            const Real growth_v1 = 1 + growthRates(info.idx_v1);\n            const Real growth_v2 = 1 + growthRates(info.idx_v2);\n            \n            const Real growth_e1 = 0.5*(growth_v2 + growth_v1);\n            const Real growth_e2 = 0.5*(growth_v0 + growth_v2);\n            \n            const Eigen::Vector3d dir_p = (Eigen::Vector3d() << 1, 0, 0).finished();\n            const Eigen::Vector3d dir_o = (Eigen::Vector3d() << 0, 1, 0).finished();\n            \n            const Real e1_p = (info.e1).dot(dir_p);\n            const Real e1_o = (info.e1).dot(dir_o);\n            \n            const Real e2_p = (info.e2).dot(dir_p);\n            const Real e2_o = (info.e2).dot(dir_o);\n            \n            const Real e1_p_growth = e1_p * growth_e1;\n            const Real e1_o_growth = e1_o * growth_e1;\n            const Real e2_p_growth = e2_p * growth_e2;\n            const Real e2_o_growth = e2_o * growth_e2;\n            \n            const Real a11 = e1_p_growth*e1_p_growth + e1_o_growth*e1_o_growth;\n            const Real a12 = e1_p_growth*e2_p_growth + e1_o_growth*e2_o_growth;\n            const Real a22 = e2_p_growth*e2_p_growth + e2_o_growth*e2_o_growth;\n            \n            aforms[i](0,0) = a11;\n            aforms[i](0,1) = aforms[i](1,0) = a12;\n            aforms[i](1,1) = a22;\n        }\n    }\n    \n    static void computeAbarsIsoGrowthPerVertex_Gradient(const tMesh & mesh, const Eigen::Ref<const Eigen::VectorXd> growthRates, const Eigen::Ref<const Eigen::MatrixXd> gradEng_abar, Eigen::Ref<Eigen::VectorXd> gradEng_rate)\n    {\n        // compute gradient abar wrt growth\n        const int nFaces = mesh.getNumberOfFaces();\n        const auto & topo = mesh.getTopology();\n        const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n        \n        for(int i=0;i<nFaces;++i)\n        {\n            const TriangleInfo info = reststate.getTriangleInfoLite(topo, i);\n            const Real growth_v0 = 1 + growthRates(info.idx_v0);\n            const Real growth_v1 = 1 + growthRates(info.idx_v1);\n            const Real growth_v2 = 1 + growthRates(info.idx_v2);\n            \n            const Real growth_e1 = 0.5*(growth_v2 + growth_v1);\n            const Real growth_e2 = 0.5*(growth_v0 + growth_v2);\n            \n            const Eigen::Vector3d dir_p = (Eigen::Vector3d() << 1, 0, 0).finished();\n            const Eigen::Vector3d dir_o = (Eigen::Vector3d() << 0, 1, 0).finished();\n            \n            const Real e1_p = (info.e1).dot(dir_p);\n            const Real e1_o = (info.e1).dot(dir_o);\n            \n            const Real e2_p = (info.e2).dot(dir_p);\n            const Real e2_o = (info.e2).dot(dir_o);\n            \n            const Real e1_p_growth = e1_p * growth_e1;\n            const Real e1_o_growth = e1_o * growth_e1;\n            const Real e2_p_growth = e2_p * growth_e2;\n            const Real e2_o_growth = e2_o * growth_e2;\n            \n            const Real da11_e1 = 2.0*(e1_p_growth * e1_p + e1_o_growth * e1_o);\n            const Real da12_e1 = e1_p * e2_p_growth + e1_o * e2_o_growth;\n            const Real da12_e2 = e1_p_growth * e2_p + e1_o_growth * e2_o;\n            const Real da22_e2 = 2.0*(e2_p_growth * e2_p + e2_o_growth * e2_o);\n            \n            const Real da12_v0 = 0.5*da12_e2;\n            const Real da22_v0 = 0.5*da22_e2;\n\n            const Real da11_v1 = 0.5*da11_e1;\n            const Real da12_v1 = 0.5*da12_e1;\n            \n            const Real da11_v2 = 0.5*da11_e1;\n            const Real da12_v2 = 0.5*(da12_e1 + da12_e2);\n            const Real da22_v2 = 0.5*da22_e2;\n            \n            gradEng_rate(info.idx_v0) += gradEng_abar(i,1)*da12_v0 + gradEng_abar(i,2)*da22_v0;\n            gradEng_rate(info.idx_v1) += gradEng_abar(i,0)*da11_v1 + gradEng_abar(i,1)*da12_v1;\n            gradEng_rate(info.idx_v2) += gradEng_abar(i,0)*da11_v2 + gradEng_abar(i,1)*da12_v2 + gradEng_abar(i,2)*da22_v2;\n        }\n    }\n};\n\n#endif /* GrowthHelper_hpp */\n", "meta": {"hexsha": "1e8bc55d023a7cb82a92659d23de6e09a0f43341", "size": 30835, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libshell/GrowthHelper.hpp", "max_stars_repo_name": "mvlab/growth_SM2018", "max_stars_repo_head_hexsha": "3ad411c4f7082e7bffc2ed3ea9bc96b9a51da73a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-09-05T16:05:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T10:30:15.000Z", "max_issues_repo_path": "src/libshell/GrowthHelper.hpp", "max_issues_repo_name": "mvlab/growth_SM2018", "max_issues_repo_head_hexsha": "3ad411c4f7082e7bffc2ed3ea9bc96b9a51da73a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-08T17:13:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-15T17:11:53.000Z", "max_forks_repo_path": "src/libshell/GrowthHelper.hpp", "max_forks_repo_name": "mvlab/growth_SM2018", "max_forks_repo_head_hexsha": "3ad411c4f7082e7bffc2ed3ea9bc96b9a51da73a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T13:01:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-09T17:03:02.000Z", "avg_line_length": 44.05, "max_line_length": 417, "alphanum_fraction": 0.5894275985, "num_tokens": 8986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.6440838329099644}}
{"text": "#include <nobody/energy.hpp>\n\n#include <Eigen/Dense>\n\n#include <nobody/euler_integrator.hpp>\n\nnamespace nobody {\n\nfloat kinetic_energy(const std::vector<particle>& particles) {\n  float energy = 0.0f;\n  for (const auto& p : particles) energy += p.mass * p.velocity.squaredNorm();\n  return 0.5f * energy;\n}\n\nfloat potential_energy(const std::vector<particle>& particles) {\n  float energy = 0.0f;\n  for (std::size_t i = 0; i < particles.size(); ++i) {\n    for (std::size_t j = 0; j < i; ++j) {\n      energy += particles[i].mass * particles[j].mass /\n                (particles[i].position - particles[j].position).norm();\n    }\n  }\n  return -gravitation_const * energy;\n}\n\nEigen::Vector3f angular_momentum(const std::vector<particle>& particles) {\n  Eigen::Vector3f result(0, 0, 0);\n  for (const auto& particle : particles) {\n    result += particle.mass * particle.position.cross(particle.velocity);\n  }\n  return result;\n}\n\n}  // namespace nobody", "meta": {"hexsha": "911d320d38500bbfce86da9eb58ada9732358cab", "size": 943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nobody/energy.cpp", "max_stars_repo_name": "lyrahgames/nobody", "max_stars_repo_head_hexsha": "868b1a6c872f051f76c6ee852a977053e1ac35d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-05T08:48:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-05T08:48:05.000Z", "max_issues_repo_path": "nobody/energy.cpp", "max_issues_repo_name": "lyrahgames/nobody", "max_issues_repo_head_hexsha": "868b1a6c872f051f76c6ee852a977053e1ac35d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T14:48:22.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-14T23:32:50.000Z", "max_forks_repo_path": "nobody/energy.cpp", "max_forks_repo_name": "lyrahgames/nobody", "max_forks_repo_head_hexsha": "868b1a6c872f051f76c6ee852a977053e1ac35d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7352941176, "max_line_length": 78, "alphanum_fraction": 0.6638388123, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6440412218703051}}
{"text": "//\n//  ExtraCirProcesses.cpp\n//  Master Thesis\n//\n//  Created by Magnus Mencke on 25/05/2021.\n//  Copyright \u00a9 2021 Magnus Mencke. All rights reserved.\n//\n\n#include \"ExtraCirProcesses.hpp\"\n\n\n#include <boost/math/distributions/non_central_chi_squared.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n\nnamespace QuantLib {\n    Real CirProcess::x0() const {\n        return x0_;\n    }\n    \n    Real CirProcess::speed() const {\n        return speed_;\n    }\n    \n    Real CirProcess::volatility() const {\n        return volatility_;\n    }\n    \n    Real CirProcess::level() const {\n        return level_;\n    }\n    \n    Real CirProcess::drift(Time, Real x) const {\n        return speed_ * (level_ - x);\n    }\n    \n    Real CirProcess::diffusion(Time, Real) const {\n        return volatility_;\n    }\n    \n    Real CirProcess::expectation(Time, Real x0,\n                                        Time dt) const {\n        return level_ + (x0 - level_) * std::exp(-speed_*dt);\n    }\n    \n    Real CirProcess::stdDeviation(Time t, Real x0,\n                                         Time dt) const {\n        return std::sqrt(variance(t,x0,dt));\n    }\n\n    //Full truncation scheme (as in Brigo, Morini and Pallavicini)\n    //Inspired by Heston implementation\n    //  see Lord, R., R. Koekkoek and D. van Dijk (2006),\n    // \"A Comparison of biased simulation schemes for\n    //  stochastic volatility models\",\n    // Working Paper, Tinbergen Institute\n    Real CirProcess::evolve (Time t0,\n                                    Real x0,\n                                    Time dt,\n                                    Real dw) const {\n        Real resultTrunc;\n        switch (discretization_) {\n            case None: {\n                resultTrunc=apply(expectation(t0,x0,dt),stdDeviation(t0,x0,dt)*dw);\n                break;\n            }\n            case FullTruncation: {\n                Real x0_trunc = x0>0.0 ? x0 : 0.0;\n                \n                Real result = apply( expectation(t0, x0_trunc, dt),stdDeviation(t0,x0_trunc,dt)*dw);\n                \n                resultTrunc = result>0.0 ? result : 0.0;\n                \n                break;\n            }\n            case QuadraticExponential: {\n                // for details of the quadratic exponential discretization scheme\n                // see Leif Andersen,\n                // Efficient Simulation of the Heston Stochastic Volatility Model\n                const Real ex = std::exp(-speed_*dt);\n                \n                const Real m  =  level_+(x0-level_)*ex;\n                const Real s2 =  x0*volatility_*volatility_*ex/speed_*(1-ex)\n                + level_*volatility_*volatility_/(2*speed_)*(1-ex)*(1-ex);\n                const Real psi = s2/(m*m);\n                \n                if (psi <= 1.5) {\n                    const Real b2 = 2/psi-1+std::sqrt(2/psi*(2/psi-1));\n                    const Real b  = std::sqrt(b2);\n                    const Real a  = m/(1+b2);\n                    \n                    resultTrunc = a*(b+dw)*(b+dw);\n                }\n                else {\n                    const Real p = (psi-1)/(psi+1);\n                    const Real beta = (1-p)/m;\n                    \n                    const Real u = CumulativeNormalDistribution()(dw);\n                    \n                    resultTrunc = ((u <= p) ? 0.0 : std::log((1-p)/(1-u))/beta);\n                }\n                break;\n            }\n            case Exact: {\n                CumulativeNormalDistribution dwDist; //despite the name, dw is standard normal\n                Real uniform= dwDist(dw); //transforming normal to uniform\n                \n                Real c=(4*speed_)/(volatility_*volatility_*(1-std::exp(-speed_*dt)));\n                Real nu=(4*speed_*level_)/(volatility_*volatility_);\n                Real eta=c*x0*std::exp(-speed_*dt);\n                \n                //we had some strange errors using QuantLib's Chi2 distribution, so we use the one from boost\n                boost::math::non_central_chi_squared_distribution<double,  boost::math::policies::policy<>> chi2(nu, eta);\n                //InverseNonCentralCumulativeChiSquareDistribution chi2(nu, eta);\n                \n                resultTrunc = quantile(chi2,uniform)/c;\n            }\n        }\n        \n        return resultTrunc;\n    }\n    \n    \n    CirProcess::CirProcess(Real speed,\n                                                     Volatility vol,\n                                                     Real x0,\n                                                     Real level,\n                                                     Discretization d)\n    : x0_(x0), speed_(speed), level_(level), volatility_(vol), discretization_(d) {\n        QL_REQUIRE(volatility_ >= 0.0, \"negative volatility given\");\n    }\n    \n    Real CirProcess::variance(Time, Real, Time dt) const {\n        Real exponent1 = std::exp(-speed_ * dt);\n        Real exponent2 = std::exp(-2 * speed_ * dt);\n        Real fraction = (volatility_ * volatility_) / speed_;\n        \n        return x0_ * fraction * (exponent1 - exponent2) + level_ * fraction * (1 - exponent1) * (1 - exponent1);\n    }\n    \n}\n", "meta": {"hexsha": "10bc2158ac47179121438e2ee34e5e1b3ec7a71e", "size": 5143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CppFiles/ExtraCirProcesses.cpp", "max_stars_repo_name": "mmencke/MasterThesis", "max_stars_repo_head_hexsha": "45b197b45ab452180109a66367dd9cf283b20aba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CppFiles/ExtraCirProcesses.cpp", "max_issues_repo_name": "mmencke/MasterThesis", "max_issues_repo_head_hexsha": "45b197b45ab452180109a66367dd9cf283b20aba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CppFiles/ExtraCirProcesses.cpp", "max_forks_repo_name": "mmencke/MasterThesis", "max_forks_repo_head_hexsha": "45b197b45ab452180109a66367dd9cf283b20aba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-06T08:04:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T08:04:14.000Z", "avg_line_length": 36.475177305, "max_line_length": 122, "alphanum_fraction": 0.4921252187, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6440412036751285}}
{"text": "#include <socialgraph.h>\n#include <math.h>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/bc_clustering.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\nGraph createGraph(std::ifstream &fin){\n\tfacebook::Name name;\n\tfacebook::Data data = facebook::readFile(fin, name);\n\n\tfacebook::Map map = facebook::createMap(data);\n\n\tGraph g = facebook::createGraph(data, map);\n\t\n\treturn g;\n}\n\nWeightedGraph createWeightedGraph(Graph g){\n\tWeightedGraph wg(num_vertices(g));\n\t\n\tproperty_map<WeightedGraph, edge_weight_t>::type weightmap = get(edge_weight, wg);\n\tEdgeIterator e, e_end;\n\tfor(tie(e, e_end) = edges(g); e != e_end; e++){\n\t\tWeightedEdgeDescriptor e1; bool inserted;\n\t\ttie(e1, inserted) = add_edge(source(*e, g), target(*e, g), wg);\n\t\tweightmap[e1] = 1;\n\t}\n\t\n\treturn wg;\n}\n\nMatrix createAllPairsShortestPaths(WeightedGraph wg){\n\tint V = num_vertices(wg);\n\tMatrix D(V, std::vector<int>(V));\n\tjohnson_all_pairs_shortest_paths(wg, D);\n\t\n\treturn D;\n}\n\n//have to corresponding vertices\nEdges newEdgeList(Graph g, Graph g2){\n\tEdges edges;\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tfor(int j=i+1; j<num_vertices(g); j++){\n\t\t\tif(edge(i, j, g).second == 0){\n\t\t\t\tif(edge(i, j, g2).second == 1){\n\t\t\t\t\tEdge e(i, j);\n\t\t\t\t\tedges.push_back(e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn edges;\n}\n\nMatrix newList2Matrix(Graph g, Edges edges){\n\tMatrix matrix(num_vertices(g));\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tstd::vector<int> temp(num_vertices(g), 0);\n\t\tmatrix[i] = temp;\n\t}\n\tfor(int i=0; i<edges.size(); i++){\n\t\tmatrix[edges[i].first][edges[i].second] = 1;\n\t\tmatrix[edges[i].second][edges[i].first] = 1;\n\t}\n\treturn matrix;\n}\n\nMatrixScore initializeScore(Graph g){\n\tMatrixScore scores(num_vertices(g));\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tstd::vector<double> score(num_vertices(g), 0.0);\n\t\tscores[i] = score;\n\t}\n\treturn scores;\n}\n\nstd::vector<double> sortDouble(std::vector<double> scores){\n\tstd::vector<double> temps;\n\tfor(int i=0; i<scores.size(); i++){\n\t\tif(scores[i] > 0)\n\t\t\ttemps.push_back(scores[i]);\n\t}\n\tstd::sort(temps.begin(), temps.end());\n\treturn temps;\n}\n\nbool comparisonSort(Score i, Score j){\n\tif(i.first < j.first) return false;\n\tif(j.first < i.first) return true;\n\treturn j.second.first < i.second.first;\n}\n\nScores SortScores(MatrixScore mscores){\n\tScores scores;\n\n\tfor(int i=0; i<mscores.size(); i++){\n\t\tfor(int j=i+1; j<mscores.size(); j++){\n\t\t\tscores.push_back(Score(mscores[i][j], Edge(i,j)));\n\t\t}\n\t}\n\tstd::sort(scores.begin(), scores.end(), comparisonSort);\n\n\treturn scores;\n}\n\nScores SortIndividualScores(MatrixScore mscores, int node){\n\tScores scores;\n\n\tfor(int i=0; i<mscores.size(); i++){\n\t\tscores.push_back(Score(mscores[node][i], Edge(node, i)));\n\t}\n\n\tstd::sort(scores.begin(), scores.end(), comparisonSort);\n\n\treturn scores;\n}\n\nfloat AvgDegree(Graph g){\n\tfloat avg=0.0;\n\n\tfor(int i=0; i<num_vertices(g); i++)\n\t\tavg += out_degree(i,g);\n\n\tavg = avg / num_vertices(g);\n\t\n\treturn avg;\n}\n\nMatrixScore ExtAdamicAdar(Graph g){\n\tGraph temp_g = g;\n\tWeightedGraph wg = createWeightedGraph(temp_g);\n\tMatrix distance = createAllPairsShortestPaths(wg);\n\tMatrixScore scores = initializeScore(g);\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tfor(int j=0; j<num_vertices(g); j++){\n\t\t\tif(edge(i,j,g).second == 1)\n\t\t\t\tscores[i][j] = 1;\n\t\t}\n\t}\n\n\tfloat avg = AvgDegree(g);\n\tfloat thresh = (float)avg/log(2);\n\t\n\tfor(int k=0; k<2; k++){\n\n\tfor(int x=0; x<num_vertices(temp_g); x++){\n\t\tfor(int y=0; y<num_vertices(temp_g); y++){\n\t\t\tif(distance[x][y] == 2){\n\t\t\t\tfor(int i=0; i<num_vertices(g); i++){\n\t\t\t\t\tif(distance[x][i] == 1 && distance[i][y] == 1){\n\t\t\t\t\t\tscores[x][y] += (double)(scores[x][i] * scores[y][i])/log(out_degree(i,g));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(scores[x][y] > thresh)\n\t\t\t\t\tscores[x][y] = 1.0;\n\t\t\t\telse\n\t\t\t\t\tscores[x][y] = scores[x][y] / thresh;\n\t\t\t\tadd_edge(x,y,temp_g);\n\t\t\t}\n\t\t}\n\t}\n\twg = createWeightedGraph(temp_g);\n\tdistance = createAllPairsShortestPaths(wg);\n\n\t}\n\n\treturn scores;\n}\n\nMatrixScore AdamicAdar(Graph g){\n\tMatrix distance = createAllPairsShortestPaths(createWeightedGraph(g));\n\tMatrixScore scores = initializeScore(g);\n\n\tfor(int x=0; x<num_vertices(g); x++){\n\t\t#pragma omp parallel for\n\t\tfor(int y=x+1; y<num_vertices(g); y++){\n\t\t\tif(distance[x][y] == 2){\n\t\t\t\tfor(int i=0; i<num_vertices(g); i++){\n\t\t\t\t\tif(x!=i && y!=i && out_degree(i,g) > 1){\n\t\t\t\t\t\tint d = distance[x][i] + distance[y][i];\n\t\t\t\t\t\tif(d == distance[x][y])\n\t\t\t\t\t\t\tscores[x][y] += (double)1/log(out_degree(i,g));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn scores;\n}\n\nvoid normalize(MatrixScore scores, Graph g){\n\t//mean\n\tint count=0;\n\tdouble avg=0.0;\n\tfor(int x=0; x<num_vertices(g); x++){\n\t\tfor(int y=x+1; y<num_vertices(g); y++){\n\t\t\tif(edge(x,y,g).second == 0){\n\t\t\t\tavg += scores[x][y];\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\tavg = avg/count;\n\n\tdouble dev=0.0;\n\tfor(int x=0; x<num_vertices(g); x++){\n\t\tfor(int y=x+1; y<num_vertices(g); y++){\n\t\t\tif(edge(x,y,g).second == 0){\n\t\t\t\tdev += pow(scores[x][y] - avg, 2);\n\t\t\t}\n\t\t}\n\t}\n\tdev = sqrt(dev/count);\n\tstd::cout << avg << \" \" << dev << std::endl;\n}\n\nMatrixScore MultiTimeAdamicAdar(Graph g, Matrix distance, Matrix new_matrix){\n\tMatrixScore scores(num_vertices(g));\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tstd::vector<double> score(num_vertices(g), 0.0);\n\t\tscores[i] = score;\n\t}\n\n\tstd::vector<int> is_new(num_vertices(g), 0);\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tfor(int j=0; j<num_vertices(g); j++){\n\t\t\tif(new_matrix[i][j] == 1){\n\t\t\t\tis_new[i] = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(int s=0; s<num_vertices(g); s++){\n\t\tfor(int t=s+1; t<num_vertices(g); t++){\n\t\t\tif(distance[s][t] == 2){\n\t\t\t\tfor(int i=0; i<num_vertices(g); i++){\n\t\t\t\t\tif(distance[s][i] == 1 && distance[t][i] == 1){\n\t\t\t\t\t\tfloat si = (new_matrix[s][i] == 1)?1.5:1;\n\t\t\t\t\t\tfloat ti = (new_matrix[t][i] == 1)?1.5:1;\n\t\t\t\t\t\tscores[s][t] += (si*ti)/log10(out_degree(i,g));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn scores;\n}\n\nfloat AvgDegreeAA(Graph g, Edges new_edges, Matrix distance){\n\tint count=0; float temp_avg=0.0;\n\tfor(int i=0; i<new_edges.size(); i++){\n\t\tint s = new_edges[i].first;\n\t\tint t = new_edges[i].second;\n\n\t\tif(distance[s][t] == 2){\n\t\t\tfor(int j=0; j<num_vertices(g); j++){\n\t\t\t\tif(distance[s][j] + distance[j][t] == distance[s][t]){\n\t\t\t\t\ttemp_avg += out_degree(j,g);\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn temp_avg/count;\n}\n\nMatrix createMatrix(Graph g){\n\tMatrix matrix(num_vertices(g));\n\n\t#pragma omp parallel for\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tstd::vector<int> list(num_vertices(g));\n\t\tfor(int j=0; j<num_vertices(g); j++){\n\t\t\tif(edge(i,j,g).second == 1)\n\t\t\t\tlist[j] = 1;\n\t\t\telse\n\t\t\t\tlist[j] = 0;\n\t\t}\n\t\tmatrix[i] = list;\n\t}\n\n\treturn matrix;\n}\n\nMatrix multiplyMatrix(Matrix A, Matrix B){\n\tMatrix matrix(A.size());\n\n\t#pragma omp parallel for\n\tfor(int i=0; i<A.size(); i++){\n\t\tstd::vector<int> list(A.size(), 0);\n\t\tfor(int j=0; j<A.size(); j++){\n\t\t\tfor(int k=0; k<A.size(); k++){\n\t\t\t\tlist[j] += A[i][k] * B[k][j];\n\t\t\t}\n\t\t}\n\t\tmatrix[i] = list;\n\t}\n\n\treturn matrix;\n}\n\nstd::vector<double> VertexBetweennessCentrality(Graph g, std::vector<double> &v_centrality_vec, std::vector<double> &e_centrality_vec){\n\tStdEdgeIndexMap my_e_index;\n\tEdgeIndexMap e_index(my_e_index);\n\tint i=0;\n\tBGL_FORALL_EDGES(edge, g, Graph){\n\t\tmy_e_index.insert(std::pair<EdgeDescriptor, int>(edge,i));\n\t\t++i;\n\t}\n\n\t//std::vector<double>e_centrality_vec(num_edges(g), 0.0);\n\titerator_property_map<std::vector<double>::iterator, EdgeIndexMap> e_centrality_map(e_centrality_vec.begin(), e_index);\n\n\tVertexIndexMap v_index = get(vertex_index, g);\n\t//std::vector<double> v_centrality_vec(num_vertices(g), 0.0);\n\titerator_property_map<std::vector<double>::iterator, VertexIndexMap> v_centrality_map(v_centrality_vec.begin(), v_index);\n\tbrandes_betweenness_centrality(g, v_centrality_map, e_centrality_map);\n\t//relative_betweenness_centrality(g, v_centrality_map);\n\n\treturn v_centrality_vec;\n}\n\nMatrixScore BCBasedLP(Graph g, Matrix distance, std::vector<double> v_centrality_vec, float beta){\n\tMatrixScore score = initializeScore(g);\n\t//Matrix distance = createAllPairsShortestPaths(createWeightedGraph(g));\n\n\t#pragma omp parallel for\n\tfor(int x=0; x<num_vertices(g); x++){\n\t\tfor(int y=x+1; y<num_vertices(g); y++){\n\t\t/*\n\t\t\tif(distance[x][y] == 3){\n\t\t\n\t\t\tstd::vector<float> z;\n\t\t\tdouble avg=0.0;\n\t\t\tfor(int i=0; i<num_vertices(g); i++){\n\t\t\t\tif((distance[x][i] + distance[i][y] == distance[x][y]) && x!=i && y!=i){\n\t\t\t\t\tz.push_back(v_centrality_vec[i]);\n\t\t\t\t\tavg += v_centrality_vec[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tavg = avg/z.size();\n\n\t\t\tfor(int i=0; i<z.size(); i++){\n\t\t\t\tscore[x][y] += pow(avg - z[i],2);\n\t\t\t}\n\n\t\t\tif(score[x][y] != 0)\n\t\t\t\tscore[x][y] = sqrt(score[x][y]);\n\t\t\telse{\n\t\t\t\tdouble tavg = (v_centrality_vec[x] + v_centrality_vec[y])/2;\n\t\t\t\ttavg = pow(v_centrality_vec[x]-tavg,2) + pow(v_centrality_vec[y]-tavg,2);\n\t\t\t\tscore[x][y] = sqrt(tavg);\n\t\t\t}\n\n\t\t\t}\n\t\t*/\n\n\t\t\tfor(int i=0; i<num_vertices(g); i++){\n\t\t\t\tif((distance[x][i] + distance[i][y] == distance[x][y]) \n\t\t\t\t&& x!=i && y!=i){\n\t\t\t\t\t//score[x][y] += 1/v_centrality_vec[i];\n\t\t\t\t\t//score[x][y] += 1/pow(v_centrality_vec[i],2);\n\t\t\t\t\t//score[x][y] += 1/log(v_centrality_vec[i]);\n\t\t\t\t\t//score[x][y] += 1/log(1+v_centrality_vec[i]);\n\t\t\t\t\tscore[x][y] += 1/(pow(log(1+v_centrality_vec[i]),2));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(distance[x][y] >= 2)\n\t\t\t\tscore[x][y] *= pow(beta, distance[x][y]-2);\n\t\t}\n\t}\n\n\treturn score;\n}\n\nfloat BCBasedLPst(Graph g, Matrix distance, std::vector<double> v_centrality_vec, float beta, int s, int t){\n\n\tfloat score=0.0;\n\tint count=0;\n\tstd::vector<float> z;\n\tdouble avg=0.0;\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tif((distance[s][i] + distance[i][t] == distance[s][t]) && s!=i && t!=i){\n\t\t\t//score += v_centrality_vec[i];\n\t\t\tz.push_back(v_centrality_vec[i]);\n\t\t\tavg += v_centrality_vec[i];\n\t\t\t//count++;\n\t\t}\n\t}\n\n\tavg = avg/z.size();\n\n\treturn avg;\n\n\t/*\n\tfor(int i=0; i<z.size(); i++){\n\t\tscore += pow(avg - z[i],2);\n\t}\n\n\tscore = sqrt(score/z.size());\n\n\treturn score;\n\t*/\n}\n\n/*\n\tMatrix distance = createAllPairsShortestPaths(createWeightedGraph(g));\n\n\tMatrixScore score = initializeScore(g);\n\n\tMatrixList ml;\n\tml.push_back(createMatrix(g));\n\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tfor(int j=i+1; j<num_vertices(g); j++){\n\t\t\tif(distance[i][j] > 1 && distance[i][j] < num_vertices(g)){\n\t\t\t\twhile(distance[i][j] > ml.size())\n\t\t\t\t\tml.push_back(multiplyMatrix(ml[0], ml[ml.size()-1]));\n\n\t\t\t\tint num = ml[distance[i][j]-1][i][j];\n\n\t\t\t\tfor(int k=0; k<num_vertices(g); k++){\n\t\t\t\t\tif(distance[i][k] + distance[k][j] == distance[i][j] && k!=i && k!=j){\n\t\t\t\t\t\tscore[i][j] += (float)(ml[distance[i][k]-1][i][k] * ml[distance[k][j]-1][k][j])/num;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn score;\n*/\n\nGraph ClusterEdgeCentrality(Graph g, double max_centrality){\n\tGraph cg = g;\n\tStdEdgeIndexMap my_e_index;\n\tEdgeIndexMap e_index(my_e_index);\n\tint i=0;\n\tBGL_FORALL_EDGES(edge, cg, Graph){\n\t\tmy_e_index.insert(std::pair<EdgeDescriptor, int>(edge, i));\n\t\t++i;\n\t}\n\n\tstd::vector<double>e_centrality_vec(num_edges(cg), 0.0);\n\titerator_property_map<std::vector<double>::iterator, EdgeIndexMap> e_centrality_map(e_centrality_vec.begin(), e_index);\n\n\tbc_clustering_threshold<double>terminate(max_centrality, cg, false);\n\tbetweenness_centrality_clustering(cg, terminate, e_centrality_map);\n\n\tfor(int i=0; i<num_vertices(cg); i++){\n\t\tfor(int j=0; j<num_vertices(cg); j++){\n\t\t\tif(edge(i, j, cg).second == 1){\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn cg;\n}\n\nGraph EdgesMST(Graph g, std::vector<double> ebc){\n\tMatrixScore weights = initializeScore(g);\n\n\tint k=0;\n\tBGL_FORALL_EDGES(e, g, Graph){\n\t\tint s = source(e, g);\n\t\tint t = target(e, g);\n\t\tif(s < t)\n\t\t\tweights[s][t] += ebc[k];\n\t\telse if(t < s)\n\t\t\tweights[t][s] += ebc[k];\n\t\tk++;\n\t}\n\t\n\tfor(int i=0; i<num_vertices(g); i++){\n\t\tfor(int j=i+1; j<num_vertices(g); j++){\n\t\t\tweights[i][j] = weights[i][j]/2;\n\t\t\tweights[j][i] = weights[i][j];\n\t\t}\n\t}\n\n\tUndirectedGraph ug(num_vertices(g));\n\n\tproperty_map<UndirectedGraph, edge_weight_t>::type weightmap = get(edge_weight,ug);\n\n\tBGL_FORALL_EDGES(e, g, Graph){\n\t\tint s = source(e, g);\n\t\tint t = target(e, g);\n\t\tif(edge(s,t,ug).second != 1){\n\t\t\tUndirectedEdgeDescriptor ue;\n\t\t\tbool inserted;\n\t\t\ttie(ue, inserted) = add_edge(s,t,ug);\n\t\t\tweightmap[ue] = (size_t)weights[s][t];\n\t\t}\n\t}\n\n\tstd::vector<UndirectedEdgeDescriptor> spanning_tree;\n\tkruskal_minimum_spanning_tree(ug, std::back_inserter(spanning_tree));\n\n\tGraph tempg(num_vertices(g));\n\tfor(int i=0; i<spanning_tree.size(); i++){\n\t\tint s = source(spanning_tree[i], ug);\n\t\tint t = target(spanning_tree[i], ug);\n\n\t\tadd_edge(s,t,tempg);\n\t\tadd_edge(t,s,tempg);\n\t}\n\n\treturn tempg;\n}\n\nMatrixScore EdgeCentrality(Graph g, std::vector<double> ebc){\n\tMatrixScore score = initializeScore(g);\n\n\tint k=0;\n\tBGL_FORALL_EDGES(e, g, Graph){\n\t\tint s = source(e, g);\n\t\tint t = target(e, g);\n\t\tscore[s][t] = ebc[k];\n\t\tscore[t][s] = ebc[k];\n\t\tk++;\n\t}\n\n\treturn score;\n}\n\nvoid NormalizePr(MatrixScore &scores, Matrix distance){\n\t//mean\n\tint count=0;\n\tdouble avg=0.0;\n\tfor(int x=0; x<scores.size(); x++){\n\t\tfor(int y=x+1; y<scores[x].size(); y++){\n\t\t\tif(distance[x][y] == 2){\n\t\t\t\tavg += scores[x][y];\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\n\tavg = avg/count;\n\n\tdouble dev=0.0;\n\tfor(int x=0; x<scores.size(); x++){\n\t\tfor(int y=x+1; y<scores[x].size(); y++){\n\t\t\tif(distance[x][y] == 2){\n\t\t\t\tdev += pow(scores[x][y] - avg, 2);\n\t\t\t}\n\t\t}\n\t}\n\tdev = sqrt(dev/count);\n\n\tcount =0;\n\n\tfor(int x=0; x<scores.size(); x++){\n\t\tfor(int y=x+1; y<scores[x].size(); y++){\n\t\t\tif(distance[x][y] == 2){\n\t\t\t\tscores[x][y] = (scores[x][y] - avg)/dev;\n\t\t\t\tscores[y][x] = scores[x][y];\n\t\t\t\tif(scores[x][y] >= 1.0)\n\t\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\tstd::cout << \"number of scores above 1: \" << count << std::endl;\n}\n", "meta": {"hexsha": "dbad6ba27b39999649f46eae6e8ab5f8ea8a5dfe", "size": 13472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graph.cpp", "max_stars_repo_name": "yishihara/Social-Network", "max_stars_repo_head_hexsha": "505c08f544a03bbd32ea1c48a437f5de63c51523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/graph.cpp", "max_issues_repo_name": "yishihara/Social-Network", "max_issues_repo_head_hexsha": "505c08f544a03bbd32ea1c48a437f5de63c51523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graph.cpp", "max_forks_repo_name": "yishihara/Social-Network", "max_forks_repo_head_hexsha": "505c08f544a03bbd32ea1c48a437f5de63c51523", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4703832753, "max_line_length": 135, "alphanum_fraction": 0.6205463183, "num_tokens": 4366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6440411977010986}}
{"text": "\n#include <Eigen/Dense>\n#include <iostream>\n\n\nclass Kalman {\n    public:\n        \n        Kalman(){\n            is_init = false;\n        }\n\n        ~Kalman(){\n            ;\n        }\n\n        bool isInit(){\n            return is_init;\n        }\n\n        // \u521d\u59cb\u5316\u72b6\u6001\u5411\u91cf\n        void init(Eigen::VectorXd x_in){\n            x_ = x_in;\n            is_init = true;\n        }\n\n        // \u72b6\u6001\u8f6c\u79fb\u77e9\u9635\n        void setF(Eigen::MatrixXd F_in){\n            F_ = F_in;\n        }\n\n        // \u7cfb\u7edf\u7684\u4e0d\u786e\u5b9a\u5ea6\n        void setP(Eigen::MatrixXd P_in){\n            P_ = P_in;\n        }\n\n        // \u8fc7\u7a0b\u566a\u58f0 \uff08\u4e00\u822c\u4e3a\u5355\u4f4d\u77e9\u9635\uff09\n        void setQ(Eigen::MatrixXd Q_in){\n            Q_ = Q_in;\n        }\n\n        // \u6d4b\u91cf\u77e9\u9635\n        void setH(Eigen::MatrixXd H_in){\n            H_ = H_in;\n        }\n\n         // \u6d4b\u91cf\u566a\u58f0\u77e9\u9635\uff08\u4e00\u822c\u7531\u4f20\u611f\u5668\u5382\u5bb6\u63d0\u4f9b\uff09\n        void setR(Eigen::MatrixXd R_in){\n            R_ = R_in;\n        }\n\n        // \u8ba1\u7b97\u9884\u6d4b\u503c\n        void predict(){\n            x_ = F_ * x_;\n            // std::cout << x_ << std::endl;\n            //printf(\"predict ok, x_ shape is %d %d\\n\", x_.rows(), x_.cols());\n            P_ = F_*P_*F_.transpose();\n            //printf(\"predict ok, P_ shape is %d %d\\n\", P_.rows(), P_.cols());\n        }\n\n        // \u89c2\u6d4b\n        void measurement_update(const Eigen::VectorXd &z){\n            // \u89c2\u6d4b\u503cz\u4e0e\u9884\u6d4b\u503cx\u7684\u5dee\u503cy\n            Eigen::VectorXd y = z - H_ * x_;\n            //printf(\"update ok, y_ shape is %d %d\\n\", y.rows(), y.cols());\n            // \u6c42\u89e3\u5361\u5c14\u66fc\u589e\u76cak\uff0c\u5dee\u503cy\u7684\u6743\u91cd\n            Eigen::MatrixXd S_ = H_ * P_ * H_.transpose() + R_;\n            //printf(\"update ok, S_ shape is %d %d\\n\", S_.rows(), S_.cols());\n            Eigen::MatrixXd K_ = P_ * H_.transpose() * S_.inverse();\n            //printf(\"update ok, K_ shape is %d %d\\n\", K_.rows(), K_.cols());\n            // \u66f4\u65b0\u72b6\u6001\u5411\u91cf\uff0c\u8003\u8651\u4e86\u6d4b\u91cf\u503c\uff0c\u9884\u6d4b\u503c\uff0c\u6574\u4e2a\u7cfb\u7edf\u7684\u566a\u58f0\n            x_ = x_ + K_ * y;\n            int size = x_.size();\n            Eigen::MatrixXd I = Eigen::MatrixXd::Identity(size, size);\n            P_ = (I - K_ * H_) * P_;\n        }\n\n        Eigen::VectorXd getX(){\n            return x_;\n        }\n\n    private:\n        bool is_init;\n        Eigen::VectorXd x_;\n        Eigen::MatrixXd F_, P_, Q_, H_, R_;\n};\n\n\nint main(int argc, char* argv[]){\n\n    Kalman kalman;\n\n    int iter=0;\n    double mx = 1.0, my = 1.0, dt=0.1;\n    while (iter++ < 1070)\n    {\n        \n        if (!kalman.isInit())\n        {\n            Eigen::VectorXd x_in(4, 1);\n            x_in << mx, my, 0.0, 0.0;\n            kalman.init(x_in);\n\n            Eigen::MatrixXd P_in(4, 4);\n            P_in << 1.0, 0.0, 0.0, 0.0,\n                    0.0, 1.0, 0.0, 0.0,\n                    0.0, 0.0, 100.0, 0.0,\n                    0.0, 0.0, 0.0, 100.0;\n            kalman.setP(P_in);\n\n\n            Eigen::MatrixXd Q_in(4, 4);\n            Q_in << 1.0, 0.0, 0.0, 0.0,\n                    0.0, 1.0, 0.0, 0.0,\n                    0.0, 0.0, 1.0, 0.0,\n                    0.0, 0.0, 0.0, 1.0;\n\n            kalman.setQ(Q_in);\n\n            Eigen::MatrixXd H_in(2, 4);\n            H_in << 1.0, 0.0, 0.0, 0.0,\n                    0.0, 1.0, 0.0, 0.0;\n\n            kalman.setH(H_in);\n\n            Eigen::MatrixXd R_in(2, 2);\n            R_in << 0.0225, 0.0,\n                    0.0, 0.0225;\n            \n            kalman.setR(R_in);\n            continue;\n        }\n        \n        Eigen::MatrixXd F_in(4, 4);\n        F_in << 1.0, 0.0, dt, 0.0,\n                0.0, 1.0, 0.0, dt,\n                0.0, 0.0, 1.0, 0.0,\n                0.0, 0.0, 0.0, 1.0;\n\n        kalman.setF(F_in);\n        kalman.predict();\n\n        Eigen::VectorXd z(2, 1);\n        z << mx, my;\n        kalman.measurement_update(z);\n\n\n        Eigen::VectorXd x_out = kalman.getX();\n        std::cout << \"x: \" << x_out(0) << \", y:\" << x_out(1) << std::endl;\n        // std::cout << \"vx: \" << x_out(2) << \", vy:\" << x_out(3) << std::endl;\n\n        std::cout << \"mx: \" << mx << \", my:\" << my << std::endl;\n        \n\n        // dt = 0.1;\n        mx += 0.3;\n        my += 0.4;\n\n        if(iter == 998) mx = 1, my = 1;\n        if(iter == 999) mx = 10, my = 10;\n    }\n    \n\n\n\n    return 0;\n}", "meta": {"hexsha": "8cdb6c6f69d9f26b07ddb9a962769feae8bb8233", "size": 4009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algorithm/kalman.cpp", "max_stars_repo_name": "fulincao/algorithm-review", "max_stars_repo_head_hexsha": "601a5a4cfc3e40ba11a04e8e19b921491a75648a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithm/kalman.cpp", "max_issues_repo_name": "fulincao/algorithm-review", "max_issues_repo_head_hexsha": "601a5a4cfc3e40ba11a04e8e19b921491a75648a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithm/kalman.cpp", "max_forks_repo_name": "fulincao/algorithm-review", "max_forks_repo_head_hexsha": "601a5a4cfc3e40ba11a04e8e19b921491a75648a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.005988024, "max_line_length": 79, "alphanum_fraction": 0.3978548266, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6439837719139898}}
{"text": "\n#include <fmt/core.h>\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n#include <cassert>\n#include <iostream>\n#include <vector>\n\n#include \"NumpySaver.hpp\"\n#include \"Timer.hpp\"\n#include \"YAMLUtils.hpp\"\n#include \"bsplines.hpp\"\n\nusing namespace Eigen;\nusing std::cout, std::endl, std::cerr;\n\nvoid test_bsplines(double x = .1, Index order = 3, Index nknots = 11) {\n  std::vector<double> std_knots(nknots);\n  Map<ArrayXd> knots(std_knots.data(), std_knots.size());\n  knots = ArrayXd::LinSpaced(nknots, 0, 1);\n\n  auto [values, index] = bsplines::bsplines(x, std_knots, order);\n\n  Map<VectorXd> values_eigen(values.data(), values.size());\n  auto sum = values_eigen.sum();\n  if (std::abs(sum - 1) > 1e-15) {\n    cerr << \"The knots are: \" << knots.transpose() << endl;\n    cerr << \"The spline value at \" << x << \" is: \" << values_eigen.transpose()\n         << endl;\n    cerr << \"Summing all spline values (should be 1): \" << sum << endl;\n  }\n}\n\nSparseMatrix<double> build_matrix(const std::vector<double>& knots,\n                                  std::size_t order = 3) {\n  auto n = knots.size();\n\n  SparseMatrix<double> matrix(n + 1, n + order - 2);\n  matrix.reserve(order * (n + 1) - 2);\n\n  auto [deriv_0, _index] = bsplines::ndx_bsplines(knots[0], knots, order, 2);\n  for (int col = 0; col < int(order) - 1; col++)\n    matrix.insert(0, col) = deriv_0[col + 1];\n\n  for (int row = 1; row < int(n); row++) {\n    auto [deriv, index] = bsplines::ndx_bsplines(knots[row], knots, order, 2);\n    for (int col = row - 1; col < row - 1 + int(order); col++)\n      matrix.insert(row, col) = deriv[col - row + 2];\n  }\n\n  auto [deriv_last, __index] =\n      bsplines::ndx_bsplines(knots[n - 1], knots, order, 1);\n  matrix.insert(n, n + order - 3) = deriv_last[order];\n  matrix.insert(n, n + order - 4) = deriv_last[order - 1];\n\n  return matrix;\n}\n\ndouble rho_uniform_sphere(double r, double R, double q) {\n  if (r <= R) return q / (4. * M_PI / 3. * R * R * R);\n\n  return 0;\n}\n\ndouble rho_uniform_shell(double r, double R1, double R2, double q) {\n  if (r < R1) return 0;\n  if (r <= R2) return q / (4. * M_PI / 3. * (R2 * R2 * R2 - R1 * R1 * R1));\n\n  return 0;\n}\n\ndouble rho_hydrogen_ground_state(double r, double e, double r_bohr = 1) {\n  return e / M_PI / (r_bohr * r_bohr * r_bohr) * std::exp(-2 * r / r_bohr);\n}\n\nVectorXd build_rhs(const std::vector<double>& knots,\n                   std::function<double(double)>& rho) {\n  auto n = knots.size();\n  VectorXd rhs(n + 1);\n  for (std::size_t i = 0; i < n; i++) {\n    rhs[i] = -knots[i] * 4 * M_PI * rho(knots[i]);\n  }\n\n  rhs[n] = 0;\n\n  return rhs;\n}\n\ndouble evaluate_spline(const double& x, const std::vector<double>& knots,\n                       const VectorXd& weights, std::size_t order = 3) {\n  auto n = knots.size();\n  assert(int(n + order) - 1 == weights.size());\n\n  auto [values, index] = bsplines::bsplines(x, knots, order);\n\n  double sum = 0;\n  for (std::size_t i = 0; i <= order; i++)\n    sum += values[i] * weights[index + i];\n\n  return sum;\n}\n\nVectorXd evaluate_spline(const VectorXd& x, const std::vector<double>& knots,\n                         const VectorXd& weights, std::size_t order = 3) {\n  auto n = x.size();\n  VectorXd ret(n);\n  for (Index i = 0; i < n; i++) {\n    ret[i] = evaluate_spline(x[i], knots, weights, order);\n  }\n  return ret;\n}\n\nvoid solve_problem(YAML::Node node) {\n  using namespace std::placeholders;\n\n  auto name = node[\"name\"].as<std::string>();\n  auto R = node[\"R\"].as<double>();\n  auto R1 = node[\"R1\"].as<double>();\n  auto R2 = node[\"R2\"].as<double>();\n  auto q = node[\"q\"].as<double>();\n  auto e = node[\"e\"].as<double>();\n  auto r_bohr = node[\"r_bohr\"].as<double>();\n\n  YAML::Node knot_node = node[\"knots\"];\n  auto knots = get_yaml_values<double>(knot_node);\n\n  auto matrix = build_matrix(knots);\n\n  std::vector<std::tuple<const char*, std::function<double(double)>>> rhos = {\n      {\"uniform_sphere\", std::bind(rho_uniform_sphere, _1, R, q)},\n      {\"uniform_shell\", std::bind(rho_uniform_shell, _1, R1, R2, q)},\n      {\"hydrogen\", std::bind(rho_hydrogen_ground_state, _1, e, r_bohr)},\n  };\n\n  if (knots.size() < 30) {\n    cout << \"Knots = \";\n    for (std::size_t i = 0; i < knots.size(); i++) cout << knots[i] << \", \";\n    cout << \"\\n\";\n  }\n\n  // first do the (sparse) LU decomposition\n  Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>\n      solver;\n  solver.analyzePattern(matrix);\n  solver.factorize(matrix);\n\n  VectorXd x = VectorXd::LinSpaced(1000, knots[0], knots[knots.size() - 1]);\n\n  for (std::size_t i = 0; i < rhos.size(); i++) {\n    auto rho_name = std::get<0>(rhos[i]);\n    auto rho = std::get<1>(rhos[i]);\n\n    cout << \"\\nProblem = \" << rho_name << \"\\n\";\n\n    auto rhs = build_rhs(knots, rho);\n    auto solution = solver.solve(rhs);\n    if (knots.size() < 30) {\n      cout << \"rhs vector: \" << rhs.transpose() << \"\\n\";\n      cout << \"solution vector: \" << solution.transpose() << \"\\n\";\n    }\n\n    VectorXd weights(solution.size() + 1);\n    weights << 0, solution;\n\n    VectorXd sol = evaluate_spline(x, knots, weights);\n\n    NumpySaver(fmt::format(\"build/output/solution_{}_{}.npy\", name, rho_name))\n        << x << sol;\n  }\n  cout << \"\\n\";\n}\n\nvoid plot_bsplines(std::size_t order = 3) {\n  std::vector<double> std_knots(11);\n  Map<ArrayXd> knots(std_knots.data(), std_knots.size());\n  knots = ArrayXd::LinSpaced(11, 0, 1);\n  VectorXd xs = VectorXd::LinSpaced(1000, knots[0], knots[knots.size() - 1]);\n  MatrixXd spline(xs.size(), order + 1);\n  MatrixXd dspline(xs.size(), order + 1);\n  MatrixXd ddspline(xs.size(), order + 1);\n\n  for (Index i = 0; i < xs.size(); i++) {\n    auto [x_spline, index_0] = bsplines::bsplines(xs[i], std_knots, order);\n    auto [x_dspline, index_1] =\n        bsplines::ndx_bsplines(xs[i], std_knots, order, 1);\n    auto [x_ddspline, index_2] =\n        bsplines::ndx_bsplines(xs[i], std_knots, order, 2);\n    for (std::size_t j = 0; j < order + 1; j++) {\n      spline(i, j) = x_spline[j];\n      dspline(i, j) = x_dspline[j];\n      ddspline(i, j) = x_ddspline[j];\n    }\n  }\n  NumpySaver saver(\"build/output/plot_splines.npy\");\n  saver << xs;\n  for (std::size_t j = 0; j < order + 1; j++) saver << spline.col(j);\n  for (std::size_t j = 0; j < order + 1; j++) saver << dspline.col(j);\n  for (std::size_t j = 0; j < order + 1; j++) saver << ddspline.col(j);\n}\n\nint main() {\n  cout << \"Testing if all spline values at each point sum to 1, no error means \"\n          \"it worked.\"\n       << endl;\n  for (double x = 0; x <= 1; x += .001) {\n    test_bsplines(x, 3, 11);\n  }\n\n  std::vector<double> std_knots(11);\n  Map<ArrayXd> knots(std_knots.data(), std_knots.size());\n  knots = ArrayXd::LinSpaced(11, 0, 1);\n\n  cout << \"Testing Matrix creation...\" << endl;\n  auto matrix = build_matrix(std_knots);\n  cout << \"Matrix size is \" << matrix.rows() << \"x\" << matrix.cols() << endl;\n  cout << matrix << endl;\n\n  YAML::Node config = YAML::LoadFile(\"config.yaml\");\n\n  for (std::size_t i = 0; i < config.size(); i++) {\n    cout << \"\\n\\n*****************************************\\n\"\n         << fmt::format(\"Running simulation {}/{}\", i + 1, config.size())\n         << endl;\n    solve_problem(config[i]);\n  }\n\n  plot_bsplines();\n  return 0;\n}\n", "meta": {"hexsha": "bc471bfa7c9f0c7cb4a05831e45bf2c1d89b62a7", "size": 7165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project04-BSplinesPoisson/bsplinespoisson.cpp", "max_stars_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_stars_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project04-BSplinesPoisson/bsplinespoisson.cpp", "max_issues_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_issues_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project04-BSplinesPoisson/bsplinespoisson.cpp", "max_forks_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_forks_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0173160173, "max_line_length": 80, "alphanum_fraction": 0.5903698535, "num_tokens": 2313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6439631359804748}}
{"text": "#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues> \n\n#include <unsupported/Eigen/KroneckerProduct>\n\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include <Spectra/SymEigsSolver.h>\n\n#include <iostream>\n#include <cassert>\n#include <random>\n#include <algorithm>\n\n#include \"edlib/EDP/LocalHamiltonian.hpp\"\n#include \"edlib/EDP/ConstructSparseMat.hpp\"\n\nEigen::SparseMatrix<double> getSX()\n{\n\tEigen::SparseMatrix<double> res(2,2);\n\tres.insert(0,1) = 1.0;\n\tres.insert(1,0) = 1.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<std::complex<double> > getSY()\n{\n\tEigen::SparseMatrix<std::complex<double> > res(2,2);\n\tconstexpr std::complex<double> I(0., 1.);\n\tres.insert(0,1) = -I;\n\tres.insert(1,0) = I;\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<double> getSZ()\n{\n\tEigen::SparseMatrix<double> res(2,2);\n\tres.insert(0,0) = 1.0;\n\tres.insert(1,1) = -1.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\ntemplate<typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> \ntwoQubitOp(int N, int pos1, int pos2,\n\t\tconst Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v1,\n\t\tconst Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v2)\n{\n\tusing namespace Eigen;\n\tconst uint32_t dim = (1<<N);\n\n\tassert(pos1 < pos2);\n\n\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> res(1,1);\n\tres(0,0) = 1.0;\n\n\tfor(int i = 0; i < pos1; i++)\n\t{\n\t\tres = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval();\n\t}\n\n\tres = Eigen::kroneckerProduct(v1, res).eval();\n\tfor(int i = pos1+1; i < pos2; i++)\n\t{\n\t\tres = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval();\n\t}\n\tres = Eigen::kroneckerProduct(v2, res).eval();\n\tfor(int i = pos2+1; i < N; i++)\n\t{\n\t\tres = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval();\n\t}\n\treturn res;\n}\n\ntemplate<typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> \nsingleQubitOp(int N, int pos, \n\t\tconst Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v)\n{\n\tusing namespace Eigen;\n\tconst uint32_t dim = (1<<N);\n\n\tusing MatrixT = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> ;\n\tMatrixT res(1,1);\n\tres(0,0) = 1.0;\n\n\tfor(int i = 0; i < pos; i++)\n\t{\n\t\tres = Eigen::kroneckerProduct(MatrixT::Identity(2,2), res).eval();\n\t}\n\n\tres = Eigen::kroneckerProduct(v, res).eval();\n\tfor(int i = pos+1; i < N; i++)\n\t{\n\t\tres = Eigen::kroneckerProduct(MatrixT::Identity(2,2), res).eval();\n\t}\n\treturn res;\n}\n\nEigen::SparseMatrix<double> getSXXYY()\n{\n\tEigen::SparseMatrix<double> res(4,4);\n\tres.insert(1,2) = 2.0;\n\tres.insert(2,1) = 2.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<double> getSXX()\n{\n\tEigen::SparseMatrix<double> res(4,4);\n\tres.insert(0,3) = 1.0;\n\tres.insert(1,2) = 1.0;\n\tres.insert(2,1) = 1.0;\n\tres.insert(3,0) = 1.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<double> getSYY()\n{\n\tEigen::SparseMatrix<double> res(4,4);\n\tres.insert(0,3) = -1.0;\n\tres.insert(1,2) = 1.0;\n\tres.insert(2,1) = 1.0;\n\tres.insert(3,0) = -1.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<double> getSZZ()\n{\n\tEigen::SparseMatrix<double> res(4,4);\n\tres.insert(0,0) = 1.0;\n\tres.insert(1,1) = -1.0;\n\tres.insert(2,2) = -1.0;\n\tres.insert(3,3) = 1.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\nclass GraphGenerator\n{\nprivate:\n\tint numVertices_;\n\tstd::vector<std::pair<int,int> > allEdges_;\n\tstd::vector<int> allVertices_;\n\npublic:\n\tGraphGenerator(int numVertices)\n\t\t: numVertices_{numVertices}\n\t{\n\t\tfor(int i = 0; i < numVertices-1; ++i)\n\t\t{\n\t\t\tfor(int j = i+1; j < numVertices; ++j)\n\t\t\t{\n\t\t\t\tallEdges_.emplace_back(i,j);\n\t\t\t}\n\t\t}\n\t\tfor(int i = 0; i < numVertices_; ++i)\n\t\t{\n\t\t\tallVertices_.emplace_back(i);\n\t\t}\n\t}\n\n\tstd::vector<std::pair<int,int> > createRandomGraph(int numEdges)\n\t{\n\t\tstd::vector<std::pair<int,int> > edges = allEdges_;\n\t\tstd::random_shuffle(edges.begin(), edges.end());\n\t\tedges.resize(numEdges);\n\t\treturn edges;\n\t}\n\n\tstd::vector<int> createRandomVertexSet(int n)\n\t{\n\t\tstd::vector<int> v = allVertices_;\n\t\tstd::random_shuffle(v.begin(), v.end());\n\t\tv.resize(n);\n\t\treturn v;\n\t}\n};\n\nconstexpr int N = 10;\nTEST_CASE(\"Test single qubit operators\", \"[LocalHamSingle]\") {\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\tstd::uniform_int_distribution<> uid(0, N-1);\n\tstd::uniform_real_distribution<> urd;\n\n\tusing cx_double = std::complex<double>;\n\n\tSECTION(\"Test contructing pauli X\") {\n\t\tedp::LocalHamiltonian<double> lh(N,2);\n\t\tfor(int n = 0; n < 100; ++n)\n\t\t{\n\t\t\tlh.clearTerms();\n\t\t\tint idx = uid(re);\n\t\t\tdouble val = urd(re);\n\t\t\tlh.addOneSiteTerm(idx, val*getSX());\n\t\t\tauto mat1 = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh));\n\t\t\tauto mat2 = singleQubitOp<double>(N, idx, val*getSX()) ;\n\t\t\tREQUIRE((mat1-mat2).squaredNorm() < 1e-8);\n\t\t}\n\t}\n\tSECTION(\"Test contructing pauli Z\") {\n\t\tedp::LocalHamiltonian<double> lh(N,2);\n\t\tfor(int n = 0; n < 100; ++n)\n\t\t{\n\t\t\tlh.clearTerms();\n\t\t\tint idx = uid(re);\n\t\t\tdouble val = urd(re);\n\t\t\tlh.addOneSiteTerm(idx, val*getSZ());\n\t\t\tauto mat1 = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh));\n\t\t\tauto mat2 = singleQubitOp<double>(N, idx, val*getSZ()) ;\n\t\t\tREQUIRE((mat1-mat2).squaredNorm() < 1e-8);\n\t\t}\n\t}\n\tSECTION(\"Test contructing pauli Y\") {\n\t\tedp::LocalHamiltonian<cx_double> lh(N,2);\n\t\tfor(int n = 0; n < 100; ++n)\n\t\t{\n\t\t\tlh.clearTerms();\n\t\t\tint idx = uid(re);\n\t\t\tdouble val = urd(re);\n\t\t\tlh.addOneSiteTerm(idx, val*getSY());\n\t\t\tauto mat1 = Eigen::MatrixXcd(edp::constructSparseMat<cx_double>(1<<N, lh));\n\t\t\tauto mat2 = singleQubitOp<cx_double>(N, idx, val*getSY()) ;\n\t\t\tREQUIRE((mat1-mat2).squaredNorm() < 1e-8);\n\t\t}\n\t}\n}\n\nTEST_CASE(\"Test 2-local Hamiltonians\", \"[LocalHam2loc]\") {\n\tstd::random_device rd;\n\tstd::default_random_engine re{rd()};\n\tstd::uniform_int_distribution<> uid(0, N-1);\n\tstd::uniform_int_distribution<> numEdgesRd(1, N*(N-1)/2);\n\tstd::uniform_real_distribution<> urd;\n\n\tusing cx_double = std::complex<double>;\n\n\tGraphGenerator ggen{N};\n\n\tSECTION(\"Random XYZ Hamiltonian\") {\n\t\tedp::LocalHamiltonian<double> lh(N,2);\n\n\t\tfor(int n = 0; n < 10; ++n)\n\t\t{\n\t\t\tlh.clearTerms();\n\t\t\tint numEdges = numEdgesRd(re);\n\t\t\tauto edges = ggen.createRandomGraph(numEdges);\n\n\t\t\tauto matEx = Eigen::MatrixXd(1<<N, 1<<N);\n\t\t\tmatEx.setZero();\n\n\t\t\tfor(const auto& edge: edges)\n\t\t\t{\n\t\t\t\tdouble v1 = urd(re);\n\t\t\t\tdouble v2 = urd(re);\n\t\t\t\tdouble v3 = urd(re);\n\t\t\t\tlh.addTwoSiteTerm(edge, v1*getSXX());\n\t\t\t\tlh.addTwoSiteTerm(edge, v2*getSYY());\n\t\t\t\tlh.addTwoSiteTerm(edge, v3*getSZZ());\n\n\t\t\t\tmatEx += v1*twoQubitOp<double>(N, edge.first, edge.second, getSX(), getSX());\n\t\t\t\tauto matYY = twoQubitOp<cx_double>(N, edge.first, edge.second, getSY(), getSY());\n\t\t\t\tmatEx += v2*matYY.real();\n\t\t\t\tmatEx += v3*twoQubitOp<double>(N, edge.first, edge.second, getSZ(), getSZ());\n\t\t\t}\n\t\t\tauto mat = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh));\n\t\t\tREQUIRE((mat-matEx).squaredNorm() < 1e-8);\n\t\t}\n\t}\n\tSECTION(\"Random Field Ising Hamiltonian\") {\n\t\tedp::LocalHamiltonian<double> lh(N,2);\n\n\t\tfor(int n = 0; n < 20; ++n)\n\t\t{\n\t\t\tlh.clearTerms();\n\t\t\tint numEdges = numEdgesRd(re);\n\t\t\tauto edges = ggen.createRandomGraph(numEdges);\n\n\t\t\tauto matEx = Eigen::MatrixXd(1<<N, 1<<N);\n\t\t\tmatEx.setZero();\n\n\t\t\tfor(const auto& edge: edges)\n\t\t\t{\n\t\t\t\tdouble v = urd(re);\n\t\t\t\tlh.addTwoSiteTerm(edge, v*getSZZ());\n\n\t\t\t\tmatEx += v*twoQubitOp<double>(N, edge.first, edge.second, getSZ(), getSZ());\n\t\t\t}\n\t\t\t\n\t\t\tauto numFields = uid(re);\n\t\t\tauto vs = ggen.createRandomVertexSet(numFields);\n\n\t\t\tfor(auto v: vs)\n\t\t\t{\n\t\t\t\tdouble h1 = urd(re);\n\t\t\t\tdouble h3 = urd(re);\n\n\t\t\t\tlh.addOneSiteTerm(v, h1*getSX());\n\t\t\t\tlh.addOneSiteTerm(v, h3*getSZ());\n\n\t\t\t\tmatEx += h1*singleQubitOp<double>(N, v, getSX());\n\t\t\t\tmatEx += h3*singleQubitOp<double>(N, v, getSZ());\n\t\t\t}\n\n\t\t\tauto mat = Eigen::MatrixXd(edp::constructSparseMat<double>(1<<N, lh));\n\t\t\tREQUIRE((mat-matEx).squaredNorm() < 1e-8);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "947a85f61825eec5c0801f30004ef88198c36edb", "size": 7756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_local_ham.cpp", "max_stars_repo_name": "chaeyeunpark/ExactDiagonalization", "max_stars_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T08:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:47:05.000Z", "max_issues_repo_path": "tests/test_local_ham.cpp", "max_issues_repo_name": "chaeyeunpark/ExactDiagonalization", "max_issues_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T19:02:14.000Z", "max_forks_repo_path": "tests/test_local_ham.cpp", "max_forks_repo_name": "chaeyeunpark/ExactDiagonalization", "max_forks_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-22T18:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T18:59:11.000Z", "avg_line_length": 24.3134796238, "max_line_length": 85, "alphanum_fraction": 0.647885508, "num_tokens": 2602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6439631290429172}}
{"text": "#include <iostream>\n#include <functional>   \n#include <numeric> \n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <map>\n#include <Eigen\\dense>\n\n#include \"markov.h\"\n#include \"TransitionMatrix.h\"\n\nint main() {\n\n\tSetTransitionMatrix();\n\tsetGameMatrix();\n\n\t//Output Vector\n\tv.setZero();\n\tv(0) = 1.0;\n\n\t// Print Results to File\n\tstd::ofstream myfile;\n\tstd::ofstream myfile2;\n\tmyfile.open(\"markov_results.txt\");\n\tmyfile2.open(\"GameMatrix_results.txt\");\n\n\n\t// TODO add Markov vector - Matrix multiplication\n\tfor (int i = 0; i < 101; i++) {\n\n\tv = v.transpose() * TransitionMatrix;\n\tstd::cout << v << std::endl; //this is just a sample, becareful how you print to file so you can mine useful stats\n\tmyfile << v << std::endl;\n\tmyfile << \"*************\" << std::endl;\n\t}\n\t\n\tv.setZero();\n\tv(0) = 1.0;\n\n\tfor (int i = 0; i < 100; i++) {\n\t\tv = v.transpose() * GameMatrix;\n\t\tfor (int j = 0; j < size - 1; j++)\n\t\tmyfile2 << v(j) << std::endl;\n\t\tstd::cout << v << std::endl; //this is just a sample, becareful how you print to file so you can mine useful stats\n\t\tmyfile2 << \"*************\" << std::endl;\n\t}\n\n\t\n\t\n\t\n\tmyfile.close();\n\tmyfile2.close();\n\n\n  return 1;\n}", "meta": {"hexsha": "274b2d71c8d71bc9181f3ccdc6d35a8c272b9be4", "size": 1164, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SnakesAndLadders/test_markov.cpp", "max_stars_repo_name": "Zenologos/IDS6938-SimulationTechniques", "max_stars_repo_head_hexsha": "b3630852b2edb3ec4e176b26f0de56b77b460a2a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SnakesAndLadders/test_markov.cpp", "max_issues_repo_name": "Zenologos/IDS6938-SimulationTechniques", "max_issues_repo_head_hexsha": "b3630852b2edb3ec4e176b26f0de56b77b460a2a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SnakesAndLadders/test_markov.cpp", "max_forks_repo_name": "Zenologos/IDS6938-SimulationTechniques", "max_forks_repo_head_hexsha": "b3630852b2edb3ec4e176b26f0de56b77b460a2a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4210526316, "max_line_length": 116, "alphanum_fraction": 0.616838488, "num_tokens": 344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920386, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6439214912085484}}
{"text": "///\n/// @file\n/// @copyright Copyright (C) Fredrik Orderud\n///\n/// @brief Copied from: http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?LU_Matrix_Inversion\n///\n#ifndef INVERT_MATRIX_HPP_\n#define INVERT_MATRIX_HPP_\n\n// REMEMBER to update \"lu.hpp\" header includes from boost-CVS\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n/**\n * Matrix inversion routine.\n * Uses lu_factorize and lu_substitute in uBLAS to invert a matrix\n */\ntemplate<class T>\nbool InvertMatrix(const boost::numeric::ublas::matrix<T>& input, boost::numeric::ublas::matrix<T>& inverse)\n{\n    using namespace boost::numeric::ublas;\n    typedef permutation_matrix<std::size_t> pmatrix;\n    // create a working copy of the input\n    matrix<T> A(input);\n    // create a permutation matrix for the LU-factorization\n    pmatrix pm(A.size1());\n    // perform LU-factorization\n    int res = lu_factorize(A,pm);\n    if( res != 0 ) return false;\n    // create identity matrix of \"inverse\"\n    inverse.assign(boost::numeric::ublas::identity_matrix<T>(A.size1()));\n    // backsubstitute to get the inverse\n    lu_substitute(A, pm, inverse);\n    return true;\n}\n\n#endif  // INVERT_MATRIX_HPP_\n", "meta": {"hexsha": "5c0ec4b4272ec582965bda499896f85c145caa9e", "size": 1369, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "airsim_ros_interface/include/invert_matrix.hpp", "max_stars_repo_name": "JonathanSchmalhofer/RecursiveStereoUAV", "max_stars_repo_head_hexsha": "005642f5afbfe719c632ce81411af9ac5e8522f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-04-07T18:07:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T11:48:34.000Z", "max_issues_repo_path": "airsim_ros_interface/include/invert_matrix.hpp", "max_issues_repo_name": "JonathanSchmalhofer/RecursiveStereoUAV", "max_issues_repo_head_hexsha": "005642f5afbfe719c632ce81411af9ac5e8522f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-21T12:55:07.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-21T14:33:09.000Z", "max_forks_repo_path": "airsim_ros_interface/include/invert_matrix.hpp", "max_forks_repo_name": "JonathanSchmalhofer/RecursiveStereoUAV", "max_forks_repo_head_hexsha": "005642f5afbfe719c632ce81411af9ac5e8522f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-10-11T09:10:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T06:28:24.000Z", "avg_line_length": 32.5952380952, "max_line_length": 107, "alphanum_fraction": 0.7216946676, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6439142610599355}}
{"text": "//  (C) Copyright Nick Thompson 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#ifndef BOOST_MATH_TOOLS_QUARTIC_ROOTS_HPP\n#define BOOST_MATH_TOOLS_QUARTIC_ROOTS_HPP\n#include <array>\n#include <cmath>\n#include <boost/math/tools/cubic_roots.hpp>\n\nnamespace boost::math::tools {\n\nnamespace detail {\n\n// Make sure the nans are always at the back of the array:\ntemplate<typename Real>\nbool comparator(Real r1, Real r2) {\n   using std::isnan;\n   if (isnan(r2)) { return true; }\n   return r1 < r2;\n}\n\ntemplate<typename Real>\nstd::array<Real, 4> polish_and_sort(Real a, Real b, Real c, Real d, Real e, std::array<Real, 4>& roots) {\n    // Polish the roots with a Halley iterate.\n    using std::fma;\n    using std::abs;\n    for (auto &r : roots) {\n        Real df = fma(4*a, r, 3*b);\n        df = fma(df, r, 2*c);\n        df = fma(df, r, d);\n        Real d2f = fma(12*a, r, 6*b);\n        d2f = fma(d2f, r, 2*c);\n        Real f = fma(a, r, b);\n        f = fma(f,r,c);\n        f = fma(f,r,d);\n        f = fma(f,r,e);\n        Real denom = 2*df*df - f*d2f;\n        if (abs(denom) > (std::numeric_limits<Real>::min)())\n        {\n            r -= 2*f*df/denom;\n        }\n    }\n    std::sort(roots.begin(), roots.end(), detail::comparator<Real>);\n    return roots;\n}\n\n}\n// Solves ax^4 + bx^3 + cx^2 + dx + e = 0.\n// Only returns the real roots, as these are the only roots of interest in ray intersection problems.\n// Follows Graphics Gems V: https://github.com/erich666/GraphicsGems/blob/master/gems/Roots3And4.c\ntemplate<typename Real>\nstd::array<Real, 4> quartic_roots(Real a, Real b, Real c, Real d, Real e) {\n    using std::abs;\n    using std::sqrt;\n    auto nan = std::numeric_limits<Real>::quiet_NaN();\n    std::array<Real, 4> roots{nan, nan, nan, nan};\n    if (abs(a) <= (std::numeric_limits<Real>::min)()) {\n        auto cbrts = cubic_roots(b, c, d, e);\n        roots[0] = cbrts[0];\n        roots[1] = cbrts[1];\n        roots[2] = cbrts[2];\n        if (b == 0 && c == 0 && d == 0 && e == 0) {\n           roots[3] = 0;\n        }\n        return detail::polish_and_sort(a, b, c, d, e, roots);\n    }\n    if (abs(e) <= (std::numeric_limits<Real>::min)()) {\n        auto v = cubic_roots(a, b, c, d);\n        roots[0] = v[0];\n        roots[1] = v[1];\n        roots[2] = v[2];\n        roots[3] = 0;\n        return detail::polish_and_sort(a, b, c, d, e, roots);\n    }\n    // Now solve x^4 + Ax^3 + Bx^2 + Cx + D = 0.\n    Real A = b/a;\n    Real B = c/a;\n    Real C = d/a;\n    Real D = e/a;\n    Real Asq = A*A;\n    // Let x = y - A/4:\n    // Mathematica: Expand[(y - A/4)^4 + A*(y - A/4)^3 + B*(y - A/4)^2 + C*(y - A/4) + D]\n    // We now solve the depressed quartic y^4 + py^2 + qy + r = 0.\n    Real p = B - 3*Asq/8;\n    Real q = C - A*B/2 + Asq*A/8;\n    Real r = D - A*C/4 + Asq*B/16 - 3*Asq*Asq/256;\n    if (abs(r) <= (std::numeric_limits<Real>::min)()) {\n        auto [r1, r2, r3] = cubic_roots(Real(1), Real(0), p, q);\n        r1 -= A/4;\n        r2 -= A/4;\n        r3 -= A/4;\n        roots[0] = r1;\n        roots[1] = r2;\n        roots[2] = r3;\n        roots[3] = -A/4;\n        return detail::polish_and_sort(a, b, c, d, e, roots);\n    }\n    // Biquadratic case:\n    if (abs(q) <= (std::numeric_limits<Real>::min)()) {\n        auto [r1, r2] = quadratic_roots(Real(1), p, r);\n        if (r1 >= 0) {\n           Real rtr = sqrt(r1);\n           roots[0] = rtr - A/4;\n           roots[1] = -rtr - A/4;\n        }\n        if (r2 >= 0) {\n           Real rtr = sqrt(r2);\n           roots[2] = rtr - A/4;\n           roots[3] = -rtr - A/4;\n        }\n        return detail::polish_and_sort(a, b, c, d, e, roots);\n    }\n\n    // Now split the depressed quartic into two quadratics:\n    // y^4 + py^2 + qy + r = (y^2 + sy + u)(y^2 - sy + v) = y^4 + (v+u-s^2)y^2 + s(v - u)y + uv\n    // So p = v+u-s^2, q = s(v - u), r = uv.\n    // Then (v+u)^2 - (v-u)^2 = 4uv = 4r = (p+s^2)^2 - q^2/s^2.\n    // Multiply through by s^2 to get s^2(p+s^2)^2 - q^2 - 4rs^2 = 0, which is a cubic in s^2.\n    // Then we let z = s^2, to get\n    // z^3 + 2pz^2 + (p^2 - 4r)z - q^2 = 0.\n    auto z_roots = cubic_roots(Real(1), 2*p, p*p - 4*r, -q*q);\n    // z = s^2, so s = sqrt(z).\n    // No real roots:\n    if (z_roots.back() <= 0) {\n      return roots;\n    }\n    Real s = sqrt(z_roots.back());\n\n    // s is nonzero, because we took care of the biquadratic case.\n    Real v = (p + s*s + q/s)/2;\n    Real u = v - q/s;\n    // Now solve y^2 + sy + u = 0:\n    auto [root0, root1] = quadratic_roots(Real(1), s, u);\n\n    // Now solve y^2 - sy + v = 0:\n    auto [root2, root3] = quadratic_roots(Real(1), -s, v);\n    roots[0] = root0;\n    roots[1] = root1;\n    roots[2] = root2;\n    roots[3] = root3;\n\n    for (auto& r : roots) {\n        r -= A/4;\n    }\n    return detail::polish_and_sort(a, b, c, d, e, roots);\n}\n\n}\n#endif\n", "meta": {"hexsha": "1394e7fae9db008138ab18db20b112e1c2d67267", "size": 4913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/tools/quartic_roots.hpp", "max_stars_repo_name": "jamesfolberth/math", "max_stars_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/math/tools/quartic_roots.hpp", "max_issues_repo_name": "jamesfolberth/math", "max_issues_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/math/tools/quartic_roots.hpp", "max_forks_repo_name": "jamesfolberth/math", "max_forks_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5364238411, "max_line_length": 105, "alphanum_fraction": 0.5169957256, "num_tokens": 1801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6439142593019902}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"uranus/Matrix.hpp\"\n#include \"uranus/un-constrained.hpp\"\n\nint main()\n{\n\tproblem<2> f;\t  // f = x_1^2 + 4x_2^2\n\n\tf.matirx_Jacobian_ << 2, 0, 0, 8; \n\n    uranus::Vector<2> x0; \n\tx0 << 1, 1;                   // \u521d\u59cb\u70b9\n\n\turanus::Vector<2> y = BFGS<2>(f,x0,0.001,true); // \u7528BFGS\u6c42\u89e3\n\n    std::cout <<\"zuiyoujie:\\n\" << y <<\"\\n\";\n\n    // dasds\n    problem<2> f2;\n    f2.matirx_Jacobian_ << 2, 0, 0, 2;\n    uranus::Vector<2> x2;\n    x2 << 5,5;\n\n    double M_k = 0.1;                          // init M_k > 0\t\n    uranus::Vector<2> x3;\n    double a;\n\tdo{\n\t\tM_k = 10 * M_k;                         // update M_k\n\t\tf2.matirx_Jacobian_(1,1) = 2 + M_k;     // update J mat\n        cout << \"M_k=============================\\n\"<<M_k<<\"\\n\";\n\t\tx3 = BFGS(f2, x2, 0.001, true);       // min f\n\n        a = M_k * pow(x3(1)-1, 2);\n        std::cout <<\"x3: \\n\" << x3 <<\"\\n\";\n\t}\n\twhile(a > 0.01);\n\n    std::cout <<\"x3: \\n\" << x3 <<\"\\n\";\n\n    return 0;\n}", "meta": {"hexsha": "bce1822ffc51599140df48c56f74b0f67dfb4ba1", "size": 978, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/BFGS.cc", "max_stars_repo_name": "hackath/Uranus", "max_stars_repo_head_hexsha": "415db5b23afdae52ed59c7d4ab08b671e2122485", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T02:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-03T07:47:10.000Z", "max_issues_repo_path": "examples/BFGS.cc", "max_issues_repo_name": "hackath/Uranus", "max_issues_repo_head_hexsha": "415db5b23afdae52ed59c7d4ab08b671e2122485", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/BFGS.cc", "max_forks_repo_name": "hackath/Uranus", "max_forks_repo_head_hexsha": "415db5b23afdae52ed59c7d4ab08b671e2122485", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2857142857, "max_line_length": 64, "alphanum_fraction": 0.4560327198, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.6439142553129306}}
{"text": "#pragma once\n\n#include <polyfem/Types.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nnamespace polyfem\n{\n\n\t// Show some stats about the matrix M: det, singular values, condition number, etc\n\tvoid show_matrix_stats(const Eigen::MatrixXd &M);\n\n\ttemplate <typename T>\n\tT determinant(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, 0, 3, 3> &mat)\n\t{\n\t\tassert(mat.rows() == mat.cols());\n\n\t\tif (mat.rows() == 1)\n\t\t\treturn mat(0);\n\t\telse if (mat.rows() == 2)\n\t\t\treturn mat(0, 0) * mat(1, 1) - mat(0, 1) * mat(1, 0);\n\t\telse if (mat.rows() == 3)\n\t\t\treturn mat(0, 0) * (mat(1, 1) * mat(2, 2) - mat(1, 2) * mat(2, 1)) - mat(0, 1) * (mat(1, 0) * mat(2, 2) - mat(1, 2) * mat(2, 0)) + mat(0, 2) * (mat(1, 0) * mat(2, 1) - mat(1, 1) * mat(2, 0));\n\n\t\tassert(false);\n\t\treturn T(0);\n\t}\n\n\ttemplate <typename T>\n\tbool read_matrix(const std::string &path, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &mat);\n\n\ttemplate <typename T>\n\tbool read_matrix_binary(const std::string &path, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &mat);\n\n\ttemplate <typename Mat>\n\tbool write_matrix_binary(const std::string &path, const Mat &mat);\n\n\tclass SpareMatrixCache\n\t{\n\tpublic:\n\t\tSpareMatrixCache() {}\n\t\tSpareMatrixCache(const size_t size);\n\t\tSpareMatrixCache(const size_t rows, const size_t cols);\n\t\tSpareMatrixCache(const SpareMatrixCache &other);\n\n\t\tvoid init(const size_t size);\n\t\tvoid init(const size_t rows, const size_t cols);\n\t\tvoid init(const SpareMatrixCache &other);\n\n\t\tvoid set_zero();\n\n\t\tinline void reserve(const size_t size) { entries_.reserve(size); }\n\t\tinline size_t entries_size() const { return entries_.size(); }\n\t\tinline size_t capacity() const { return entries_.capacity(); }\n\t\tinline size_t non_zeros() const { return mapping_.empty() ? mat_.nonZeros() : values_.size(); }\n\n\t\tvoid add_value(const int i, const int j, const double value);\n\t\tStiffnessMatrix get_matrix(const bool compute_mapping = true);\n\t\tvoid prune();\n\n\t\tSpareMatrixCache operator+(const SpareMatrixCache &a) const;\n\t\tvoid operator+=(const SpareMatrixCache &o);\n\n\tprivate:\n\t\tsize_t size_;\n\t\tStiffnessMatrix tmp_, mat_;\n\t\tstd::vector<Eigen::Triplet<double>> entries_;\n\t\tstd::vector<std::vector<std::pair<int, size_t>>> mapping_;\n\t\tstd::vector<int> inner_index_, outer_index_;\n\t\tstd::vector<double> values_;\n\t};\n\n} // namespace polyfem\n", "meta": {"hexsha": "dc5938415df62459f6548d348dd917c617feb879", "size": 2312, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/MatrixUtils.hpp", "max_stars_repo_name": "Huangzizhou/polyfem", "max_stars_repo_head_hexsha": "db2bd4fb78848257f3d6cdb5241c9bca04165bf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-04-09T12:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-30T07:16:46.000Z", "max_issues_repo_path": "src/utils/MatrixUtils.hpp", "max_issues_repo_name": "Huangzizhou/polyfem", "max_issues_repo_head_hexsha": "db2bd4fb78848257f3d6cdb5241c9bca04165bf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/MatrixUtils.hpp", "max_forks_repo_name": "Huangzizhou/polyfem", "max_forks_repo_head_hexsha": "db2bd4fb78848257f3d6cdb5241c9bca04165bf8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8266666667, "max_line_length": 194, "alphanum_fraction": 0.6833910035, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.643914250151907}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_IEEE_FUNCTION_SCALAR_ULPDIST_HPP_INCLUDED\n#define NT2_TOOLBOX_IEEE_FUNCTION_SCALAR_ULPDIST_HPP_INCLUDED\n#include <nt2/sdk/constant/eps_related.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/constant/digits.hpp>\n#include <boost/fusion/tuple.hpp>\n\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/tofloat.hpp>\n#include <nt2/include/functions/ldexp.hpp>\n#include <nt2/include/functions/frexp.hpp>\n#include <nt2/include/functions/max.hpp>\n#include <nt2/include/functions/dist.hpp>\n#include <nt2/include/functions/is_nan.hpp>\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ulpdist_, tag::cpu_,\n                         (A0)(A1),\n                         (arithmetic_<A0>)(arithmetic_<A1>)\n                        )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::ulpdist_(tag::arithmetic_,tag::arithmetic_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n    struct result<This(A0,A1)> :\n      std::tr1::result_of<meta::arithmetic(A0,A1)>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return dist(a0, a1);\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is bool_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ulpdist_, tag::cpu_,\n                         (A0)(A1),\n                         (bool_<A0>)(bool_<A1>)\n                        )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::ulpdist_(tag::bool_,tag::bool_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n    struct result<This(A0,A1)> :\n      std::tr1::result_of<meta::arithmetic(A0,A1)>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      return dist(a0, is_nez(a1));\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is real_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ulpdist_, tag::cpu_,\n                         (A0)(A1),\n                         (real_<A0>)(real_<A1>)\n                        )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::ulpdist_(tag::real_,tag::real_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n    struct result<This(A0,A1)> :\n      std::tr1::result_of<meta::arithmetic(A0,A1)>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typedef typename std::tr1::result_of<meta::arithmetic(A0, A1) >::type type;\n      typedef typename meta::as_integer<A0>::type itype;\n      if (a0 == a1)               return Zero<type>();\n      if (is_nan(a0)&&is_nan(a1)) return Zero<type>();\n      itype e1, e2;\n      type m1, m2;\n      boost::fusion::tie(m1, e1) = nt2::frexp(type(a0));\n      boost::fusion::tie(m2, e2) = nt2::frexp(type(a1));\n      itype expo = -nt2::max(e1, e2);\n      double e = (e1 == e2) ? nt2::abs(m1-m2)\n      : nt2::abs(nt2::ldexp(a0, expo)-nt2::ldexp(a1, expo));\n      return e/Eps<type>();\n    }\n  };\n} }\n\n#endif\n// modified by jt the 26/12/2010\n", "meta": {"hexsha": "b2561403c4aa0070b149ba5dfebe74543014f406", "size": 3970, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/scalar/ulpdist.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/scalar/ulpdist.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/ieee/include/nt2/toolbox/ieee/function/scalar/ulpdist.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.224137931, "max_line_length": 81, "alphanum_fraction": 0.5171284635, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6438692610738569}}
{"text": "// inverse_gamma_example.cpp\n\n// Copyright Paul A. Bristow 2010.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Example 1 of using inverse gamma functions.\n\n#include <boost/math/special_functions/gamma.hpp>\n\nusing boost::math::gamma_p_inv; // Compute x given a\n//using boost::math::gamma_q_inv;\n//using boost::math::gamma_p_inva; // Compute a given x\n//using boost::math::gamma_q_inva;\n\n#include <iostream>\n   using std::cout;    using std::endl;\n#include <iomanip>\n   using std::setprecision;\n#include <cmath>\n   using std::sqrt;\n#include <limits>\n\nint main()\n{\n  cout << \"Example 1 using Inverse Gamma function. \" << endl;\n\n  #ifdef BOOST_NO_CXX11_NUMERIC_LIMITS\n  int max_digits10 = 2 + (boost::math::policies::digits<double, boost::math::policies::policy<> >() * 30103UL) / 100000UL;\n  cout << \"BOOST_NO_CXX11_NUMERIC_LIMITS is defined\" << endl;\n#else\n  int max_digits10 = std::numeric_limits<double>::max_digits10;\n#endif\n  cout << \"Show all potentially significant decimal digits std::numeric_limits<double>::max_digits10 = \"\n    << max_digits10 << endl;\n  cout.precision(max_digits10); //\n\n  double x = 1.;\n  double a = 10;\n\n  double r = boost::math::gamma_q_inv(a ,x);\n\n  cout << \" x = \" << x << \", = gamma_q_inv(a,x)\" << r << endl; //\n\n  return 0;\n}  // int main()\n\n/*\n\nOutput is:\n\n*/\n", "meta": {"hexsha": "b9d119b4dfd4ec3431e7776d2d68efe66b1877db", "size": 1443, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/inverse_gamma_example.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/inverse_gamma_example.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/inverse_gamma_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": 25.7678571429, "max_line_length": 122, "alphanum_fraction": 0.6888426888, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870288, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.643658564532977}}
{"text": "/**\n * File: random_var.cpp\n * Date: Mon Nov  9 10:31:35 CET 2020\n * Author: Open Risk  (www.openriskmanagement.com)\n *\n * Examples of using the tailRisk library to compute tail risk measures\n *\n */\n\n#include <armadillo>\n#include \"random_var.h\"\n\nint main(int argc, char *argv[]) {\n\n    // Reading in some data for a type 0 representation (discrete distribution)\n    int LossGrid = 1000;\n    int DataType = 0;\n    RandomVar L(LossGrid, DataType);\n    L.ReadFromJSON(\"../../data/example5.json\");\n    L.Print();\n\n    // Calculate various measures\n    double alpha = 0.8;\n    int threshold = 0;\n\n    std::cout << \"Mean Value: \" << L.Mean() << std::endl;\n    std::cout << \"Median Value: \" << L.Median() << std::endl;\n    std::cout << \"STD Value: \" << L.StandardDeviation() << std::endl;\n    std::cout << \"Kurtosis: \" << L.Kurtosis() << std::endl;\n    std::cout << \"Skeweness: \" << L.Skeweness() << std::endl;\n    std::cout << \"Quantile @ \" << alpha << \": \" << L.Quantile(alpha) << std::endl;\n    std::cout << \"Quantile Index @ \" << alpha << \": \" << L.Quantile_Index(alpha) << std::endl;\n    std::cout << \"VaR @ \" << alpha << \": \" << L.VaR(alpha) << std::endl;\n    std::cout << \"Expected Shortfall @ \" << alpha << \": \" << L.ExpectedShortFall(alpha) << std::endl;\n    std::cout << \"Exceedance Probability: \" << L.ExceedanceProbability(threshold) << std::endl;\n    std::cout << \"Mean Excess: \" << L.MeanExcess(threshold ) << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "3ea3353c04d506e9e60b5953b14a2c6ddb0c921b", "size": 1444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "open-risk/tailRisk", "max_stars_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-26T07:25:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T07:25:15.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "open-risk/tailRisk", "max_issues_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "open-risk/tailRisk", "max_forks_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-05T11:47:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T11:47:13.000Z", "avg_line_length": 37.0256410256, "max_line_length": 101, "alphanum_fraction": 0.5921052632, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6435588788659804}}
{"text": "//=======================================================================\n// Copyright (c) 2014 Andrzej Pacuk\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file performance_measures.hpp\n * @brief\n * @author Andrzej Pacuk\n * @version 1.0\n * @date 2014-10-22\n */\n#ifndef PALL_PERFORMANCE_MEASURES_HPP\n#define PALL_PERFORMANCE_MEASURES_HPP\n\n#include <boost/range/combine.hpp>\n#include <boost/range/empty.hpp>\n#include <boost/range/size.hpp>\n#include <boost/tuple/tuple.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <utility>\n\nnamespace paal {\n\n/**\n * @brief\n *\n * @tparam FloatType\n * @tparam Probs\n * @tparam TestResults\n *\n * @param probs\n * @param test_results\n */\ntemplate<typename FloatType = double,\n         typename Probs, typename TestResults>\nFloatType log_loss(Probs &&probs, TestResults &&test_results) {\n    assert(boost::size(probs) == boost::size(test_results));\n    assert(!boost::empty(probs));\n\n    FloatType loss{};\n    static FloatType EPSILON{1e-6};\n    for(auto prob_result : boost::combine(probs, test_results)) {\n        FloatType prob, result;\n        boost::tie(prob, result) = prob_result;\n        loss -= std::log(std::max(result ? prob : 1 - prob,\n                                  EPSILON));\n    }\n\n    return loss / boost::size(probs);\n}\n\n/**\n * @brief\n *\n * @tparam FloatType\n * @param log_loss\n *\n * @return\n */\ntemplate<typename FloatType>\nFloatType likelihood_from_log_loss(FloatType log_loss) {\n    return std::exp(-log_loss);\n}\n\n/**\n * @brief\n *\n * @tparam FloatType\n * @tparam Probs\n * @tparam TestResults\n *\n * @param probs\n * @param test_results\n */\ntemplate<typename FloatType = double,\n         typename Probs, typename TestResults>\nFloatType likelihood(Probs &&probs, TestResults &&test_results) {\n    return likelihood_from_log_loss(log_loss<FloatType>(std::forward<Probs>(probs),\n                                    std::forward<TestResults>(test_results)));\n}\n\n/**\n * @brief\n *\n * @tparam FloatType\n * @tparam Probs\n * @tparam TestResults\n *\n * @param probs\n * @param test_results\n */\ntemplate<typename FloatType = double,\ntypename Probs, typename TestResults>\nFloatType mean_absolute_error(Probs &&probs, TestResults &&test_results) {\n    assert(boost::size(probs) == boost::size(test_results));\n    assert(!boost::empty(probs));\n\n    FloatType loss{};\n    for(auto prob_result : boost::combine(probs, test_results)) {\n        FloatType prob, result;\n        boost::tie(prob, result) = prob_result;\n        loss += std::abs(prob - result);\n    }\n\n    return loss / boost::size(probs);\n}\n\n} //! paal\n\n#endif /* PALL_PERFORMANCE_MEASURES_HPP */\n\n", "meta": {"hexsha": "ec609506ae2c7159f5e290cb8f3f2952b5b7ddff", "size": 2790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/utils/performance_measures.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/paal/utils/performance_measures.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/paal/utils/performance_measures.hpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 23.8461538462, "max_line_length": 83, "alphanum_fraction": 0.6311827957, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891435927269, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.6434965932924764}}
{"text": "#pragma once\n\n#include <vector>\n#include <cassert>\n\n#include <iostream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n\n//! \\file rkintegrator.hpp Solution for Problem 1, implementing RkIntegrator class\n\n//! \\brief Implements a Runge-Kutta explicit solver for a given Butcher tableau for autonomous ODEs\n//! \\tparam State a type representing the space in which the solution lies, e.g. R^d, represented by e.g. Eigen::VectorXd.\ntemplate <class State>\nclass RKIntegrator {\npublic:\n    //! \\brief Constructor for the RK method.\n    //! Performs size checks and copies A and b into internal storage\n    //! \\param[in] A matrix containing coefficents of Butcher tableau, must be (strictly) lower triangular (no check)\n    //! \\param[in] b vector containing coefficients of lower part of Butcher tableau\n    RKIntegrator(const Eigen::MatrixXd & A, const Eigen::VectorXd & b)\n        : A(A), b(b), s(b.size()) {\n        assert( A.cols() == A.rows() && \"Matrix must be square.\");\n        assert( A.cols() == b.size() && \"Incompatible matrix/vector size.\");\n    }\n    \n    //! \\brief Perform the solution of the ODE\n    //! Solve an autonomous ODE y' = f(y), y(0) = y0, using a RK scheme given in the Butcher tableau provided in the\n    //! constructor. Performs N equidistant steps upto time T with initial data y0\n    //! \\tparam Function type for function implementing the rhs function. Must have State operator()(State x)\n    //! \\param[in] f function handle for rhs in y' = f(y), e.g. implemented using lambda funciton\n    //! \\param[in] T final time T\n    //! \\param[in] y0 initial data y(0) = y0 for y' = f(y)\n    //! \\param[in] N number of steps to perform. Step size is h = T / N. Steps are equidistant.\n    //! \\return vector containing all steps y^n (for each n) including initial and final value\n    template <class Function>\n    std::vector<State> solve(const Function &f, double T, const State & y0, unsigned int N) const {\n        // Iniz step size\n        double h = T / N;\n        \n        // Will contain all steps, reserve memory for efficiency\n        std::vector<State> res;\n        res.reserve(N+1);\n        \n        // Store initial data\n        res.push_back(y0);\n        \n        // Initialize some memory to store temporary values\n        State ytemp1 = y0;\n        State ytemp2 = y0;\n        // Pointers to swap previous value\n        State * yold = &ytemp1;\n        State * ynew = &ytemp2;\n        \n        // Loop over all fixed steps\n        for(unsigned int k = 0; k < N; ++k) {\n            // Compute, save and swap next step\n            step(f, h, *yold, *ynew);\n            res.push_back(*ynew);\n            std::swap(yold, ynew);\n        }\n        \n        return res;\n    }\n    \nprivate:\n    \n    //! \\brief Perform a single step of the RK method for the solution of the autonomous ODE\n    //! Compute a single explicit RK step y^{n+1} = y_n + \\sum ... starting from value y0 and storing next value in y1\n    //! \\tparam Function type for function implementing the rhs. Must have State operator()(State x)\n    //! \\param[in] f function handle for ths f, s.t. y' = f(y)\n    //! \\param[in] h step size\n    //! \\param[in] y0 initial state \n    //! \\param[out] y1 next step y^{n+1} = y^n + ...\n    template <class Function>\n    void step(const Function &f, double h, const State & y0, State & y1) const {\n        // create vector holding next value\n        y1 = y0;\n        \n        // Reserve space for increments\n        std::vector<State> k;\n        k.reserve(s);\n        \n        // Loop over the size of RK\n        for(unsigned int i = 0; i < s; ++i) {\n            // Compute increments and save them to k\n            State incr = y0;\n            for(unsigned int j = 0; j < i; ++j) {\n                incr += h*A(i,j)*k.at(j);\n            }\n            k.push_back( f( incr ) );\n            y1 += h * b(i) * k.back();\n        }\n    }\n    \n    //! Matrix A in Butcher scheme\n    const Eigen::MatrixXd A;\n    //! Vector b in Butcher scheme\n    const Eigen::VectorXd b;\n    //! Size of Butcher matrix and vector A and b\n    unsigned int s;\n};\n", "meta": {"hexsha": "d515801f82fc6269a01e623ab4e463c36bc34ef6", "size": 4064, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/rkintegrator.hpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/rkintegrator.hpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/rkintegrator.hpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0769230769, "max_line_length": 122, "alphanum_fraction": 0.5971948819, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6434965777585246}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_GaussRadauQuadratureSet.cpp\n//! \\author Luke Kersting\n//! \\brief  Gauss-Radau quadrature set\n//!\n//---------------------------------------------------------------------------//\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"Utility_GaussRadauQuadratureSet.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_ContractException.hpp\"\n\nnamespace Utility{\n\n// Constructor\nGaussRadauQuadratureSet::GaussRadauQuadratureSet( \n                              boost::function<double (double, int)>\n                                polynomial_expansion_function,\n                              const double error_tol,\n                              const int polynomial_order )\n  : d_polynomial_expansion_function( polynomial_expansion_function ),\n    d_error_tol( error_tol ),\n    d_polynomial_order( polynomial_order )\n{\n  // Make sure the error tolerances are valid\n  testPrecondition( error_tol >= 0.0 );\n\n  // Make sure the work space size is valid\n  testPrecondition( polynomial_order > 0 );\n}\n\n// Caluclate the nth order Jacobi Polynomial at x\n/* \\details The Jacobi Polynomials can be calculated by the following recursion \n * relationship:\n * a1_n P_{n+1}^{\\alpha,\\beta}(x) = (a2_n + a3_n x)P_n^{\\alpha,\\beta}(x) - a4_n P_{n-1}^{\\alpha,\\beta}(x)\n * where: \n * a1_n = 2(n+1)(n+\\alpha+\\beta+1)(2n+\\alpha+\\beta)\n * a2_n = (2n+\\alpha+\\beta+1)(\\alpha^2-\\beta^2)\n * a3_n = (2n + \\alpha + \\beta)(2n + \\alpha + \\beta + 1)(2n + \\alpha +\\beta + 2)\n * a4_n = 2(n+\\alpha)(n+\\beta)(2n+\\alpha+\\beta+2)\n */\ndouble GaussRadauQuadratureSet::getJacobiPolynomial( \n                              double x,\n                              int n, \n                              int alpha,\n                              int beta ) const\n{\n  // Calculate the first two polynomials\n  double P_0 = 1.0;\n  double P_1 = 0.5*( alpha - beta + ( alpha + beta + 2 )* x );\n\n  if (n==0)\n  {\n    return P_0;\n  }\n  if (n==1)\n  {\n    return P_1;\n  }\n  else\n  {\n    int a_b = alpha + beta;\n    int a_b_1 = a_b + 1;\n    int a_b_2 = a_b + 2;\n\n    double p_i_minus_2 = P_0;\n    double p_i_minus_1 = P_1;\n    double p_i;\n\n    // Use recursion relation to calculate higher order Jacobi polynomials\n    for (int i = 1; i < n; ++i)\n    {\n      int two_i = 2*i;\n\n      // Calculate the Jacobi coefficients\n      double a1_i = 2.0*( i + 1.0 )*( i + a_b_1 )*( two_i + a_b );\n      double a2_i = ( two_i + a_b_1 )*( alpha*alpha - beta*beta );\n      double a3_i = ( two_i + a_b )*( two_i + a_b_1 )*( two_i + a_b_2 );\n      double a4_i = 2.0*( i + alpha )*( i + beta )*( two_i + a_b_2 );\n\n      // Calculate new P_n value\n      p_i = 1.0/a1_i*( ( a2_i + a3_i*x )*p_i_minus_1 - a4_i*p_i_minus_2 );\n\n      // Update P_n_minus_1 and P_n_minus_2 for next value on n\n      p_i_minus_2 = p_i_minus_1;\n      p_i_minus_1 = p_i;\n    }\n\n  return p_i;\n  }\n}\n\ndouble GaussRadauQuadratureSet::getLegendrePolynomial( \n                                        double x,\n                                        int n ) const\n{\n  return getJacobiPolynomial( x, n, 0, 0 );\n}\n\n// Calculate the derivative of the nth order Jacobi Polynomial at x\n/* \\details The Jacobi Polynomials can be calculated by the following recursion \n * relationship:\n * 1/2( n + \\alpha + \\beta + 1 )P_{n-1}^{\\alpha + 1,\\beta + 1}(x) \n */\ndouble GaussRadauQuadratureSet::getJacobiPolynomialDerivative( \n                              double x,\n                              int n, \n                              int alpha,\n                              int beta ) const\n{\n\n  if (n==0)\n  {\n    return 0.0;\n  }\n  if (n==1)\n  {\n    return 0.5*( alpha + beta + 2.0 );\n  }\n  else\n  {\n    return 0.5 * (alpha + beta + n + 1.0) * getJacobiPolynomial( x,  \n                                                                 n-1, \n                                                                 alpha + 1, \n                                                                 beta + 1 );\n  }\n}\n\n// Estimate the roots of the Jacobi Polynomial\n/* \\details The roots of the Jacobi Polynomials can be estimated by the roots of \n * the Chebyshev Polynomials which are given by the relationship:\n * x_k = cos( (2k - 1)\\pi/2n ) , k = 1, ... , n \n */\nvoid GaussRadauQuadratureSet::getJacobiPolynomialRoots( \n                                 Teuchos::Array<double>& roots,\n                                 const int n, \n                                 int alpha,\n                                 int beta ) const\n{\n  // Max number of allowed iterations\n  int max_iterations = 200;\n\n  int iteration;\n  double root_k, s, jacobi, jacobi_derivative, delta_root;\n\n  // Iterate through all n roots ( 0 < k < n ) \n  for (int k = 0; k < n; k++)\n  {\n    // Make an initial guess that the roots are equal to the roots of the Chebyshev Polynomial\n    root_k = -cos( ( 2.0*k + 1.0 )/( 2.0 * n )* PhysicalConstants::pi );\n\n    // Actual root is known to be inbetween roots of Chebyshev Polynomial\n    if (k > 0)\n    {\n      root_k = ( root_k + roots[k-1] )/2.0;\n    }\n\n    iteration = 0;\n\n    // Iterate until you converge on root\n    do\n    {\n      s = 0;\n      \n      for (int i = 0; i < k; i++)\n      {\n        s += 1.0/( root_k - roots[i] );\n      }\n      \n      // Get error\n      jacobi = getJacobiPolynomial( root_k, n, alpha, beta );\n      jacobi_derivative = \n               getJacobiPolynomialDerivative( root_k, n, alpha, beta );\\\n  \n      delta_root = -jacobi/( jacobi_derivative - jacobi*s );\n\n      // Update root value\n      root_k += delta_root;\n      \n      // Update iteration\n      ++iteration;\n   \n      if ( iteration > max_iterations )\n         break;\n/*  \n      TEST_FOR_EXCEPTION( iteration > max_iterations, \n\t\t          RadauQuadratueError, \n\t\t          \"Error: the root of the Jacobi Polynomial \"\n                          \"did not converge\" );\n*/\n    }\n    while ( fabs(delta_root) > d_error_tol );\n\n    roots[k] = root_k;\n  }\n}\n\n// Find the Radau nodes and wieghts including at end point -1 or 1\nvoid GaussRadauQuadratureSet::findNodesAndWeights(\n                            double end_point, \n                            Teuchos::Array<double>& nodes,\n                            Teuchos::Array<double>& weights ) const\n{\n  // Make sure end_point is either -1 or 1\n  testPrecondition( fabs(end_point) == 1.0 );\n\n  int n = d_polynomial_order;\n  int alpha = 0;\n  int beta = 1;\n  double jacobi_derivative;\n\n  Teuchos::Array<double> roots( n );\n\n  // Calculate the roots of the Jacobi Polynomial\n  getJacobiPolynomialRoots( roots, n, alpha, beta );\n\n  // Check to see if the end point is the first node\n  if ( end_point < roots[0] )\n  {\n    nodes[0] = end_point;\n    weights[0] = findWeightAtEndPoint( end_point, n );\n\n    // Iterate through the all nodes and weights\n    for ( int i = 0; i < n; ++i )\n    {\n      nodes[i+1] = roots[i];\n\n      weights[i+1] = findWeightAtNode( roots[i], end_point, n );\n    }\n  }\n  else\n  {\n    nodes[n] = end_point;\n    weights[n] = findWeightAtEndPoint( end_point, n );\n\n    // Iterate through all other nodes and weights\n    for ( int i = 0; i < n; ++i )\n    {\n      nodes[i] = roots[i];\n       \n      weights[i] = findWeightAtNode( roots[i], end_point, n );\n    }\n  }\n}\n\n// Find the Radau nodes and wieghts including at end point -1 or 1\nvoid GaussRadauQuadratureSet::findNodesAndPositiveWeights(\n                            double end_point, \n                            Teuchos::Array<double>& nodes,\n                            Teuchos::Array<double>& weights ) const\n{\n  // Make sure end_point is either -1 or 1\n  testPrecondition( fabs(end_point) == 1.0 );\n\n  int n = d_polynomial_order;\n  int alpha = 0;\n  int beta = 1;\n  double jacobi_derivative;\n\n  Teuchos::Array<double> roots( n );\n\n  // Calculate the roots of the Jacobi Polynomial\n  getJacobiPolynomialRoots( roots, n, alpha, beta );\n\n  // Check to see if the end point is the first node\n  if ( end_point < roots[0] )\n  {\n    nodes[0] = end_point;\n    weights[0] = findWeightAtEndPoint( end_point, n );\n\n    // Iterate through the all nodes and weights\n    for ( int i = 0; i < n; ++i )\n    {\n      nodes[i+1] = roots[i];\n\n      jacobi_derivative = \n              getJacobiPolynomialDerivative( nodes[i+1], n, alpha, beta );\n\n      weights[i+1] = findWeightAtNode( roots[i], end_point, n );\n    }\n  }\n  else\n  {\n    nodes[n] = end_point;\n    weights[n] = findWeightAtEndPoint( -end_point, n );\n\n    // Iterate through all other nodes and weights\n    for ( int i = 0; i < n; ++i )\n    {\n      nodes[n-1-i] = -roots[i];\n\n      // Get the derivative of the Jacobi Polynomial of order n\n      jacobi_derivative = \n              getJacobiPolynomialDerivative( roots[i], \n                                             n, \n                                             alpha, beta );\n       \n      weights[n-1-i] = findWeightAtNode( roots[i], -end_point, n );\n    }\n  }\n}\n\n// Create the integrand function for the weight at the end point -1 or 1\ndouble GaussRadauQuadratureSet::getFixedWeightIntegrand( \n                               double end_point,\n                               int n ) const\n{\n  return d_polynomial_expansion_function( end_point, n )*getJacobiPolynomial( end_point, n );\n}\n\n// Create the integrand function for the weight at a given node with end point -1 or 1\ndouble GaussRadauQuadratureSet::getWeightIntegrand(\n                               double x,\n                               double node,\n                               double end_point, \n                               int n ) const\n{\n  return getFixedWeightIntegrand( x, n )*( x - end_point )/( x - node );\n}\n\n// Find the Radau wieght for the function at the end point -1 or 1\ndouble GaussRadauQuadratureSet::findWeightAtEndPoint( double end_point,\n                                                         int n ) const\n{\n  // Make sure end_point is either -1 or 1\n  testPrecondition( fabs(end_point) == 1.0 );\n  // Make sure n is positive\n  testPrecondition( n > 0.0 );\n\n  boost::function<double (double x)> weight_function =\n    boost::bind<double>( &GaussRadauQuadratureSet::getFixedWeightIntegrand,\n\t\t\t boost::cref( *this ),\n\t\t\t _1,\n\t\t\t n );\n\n  double abs_error, result;\n  double precision = 1e-12;\n    \n  Utility::GaussKronrodIntegrator integrator( precision );\n\n  integrator.integrateAdaptively<15>(\n\t\t\t\t\tweight_function,\n\t\t\t\t\t-1.0,\n\t\t\t\t\t1.0,\n\t\t\t\t\tresult,\n\t\t\t\t\tabs_error );\n\n  return result/getJacobiPolynomial( end_point, n );\n\n}\n\n// Find the Radau wieght for the function at a given node\ndouble GaussRadauQuadratureSet::findWeightAtNode( double node,\n                                                     double end_point,\n                                                     int n ) const\n{\n  // Make sure end_point is either -1 or 1\n  testPrecondition( fabs(end_point) == 1.0 );\n  // Make sure node is between -1 and 1\n  testPrecondition( node < 1.0 );\n  testPrecondition( node > -1.0 );\n  // Make sure n is positive\n  testPrecondition( n > 0.0 );\n\n  boost::function<double (double x)> weight_function =\n    boost::bind<double>( &GaussRadauQuadratureSet::getWeightIntegrand,\n\t\t\t boost::cref( *this ),\n\t\t\t _1,\n                         node,\n                         end_point,\n\t\t\t n );\n\n  double abs_error, result;\n  double precision = 1e-12;\n    \n  Utility::GaussKronrodIntegrator integrator( precision );\n\n  integrator.integrateAdaptively<15>(\n\t\t\t\t\tweight_function,\n\t\t\t\t\t-1.0,\n\t\t\t\t\t1.0,\n\t\t\t\t\tresult,\n\t\t\t\t\tabs_error );\n  return result/\n           ( getJacobiPolynomialDerivative( node, n ) * ( node - end_point) );\n\n}\n\n} // end Utility namespace\n\n//---------------------------------------------------------------------------//\n// end Utility_GaussRadauQuadratureSet.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "98e8cecc752ddef7df62fe9dc5c0758ef5389850", "size": 11798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/integrator/src/Utility_GaussRadauQuadratureSet.cpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/utility/integrator/src/Utility_GaussRadauQuadratureSet.cpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/utility/integrator/src/Utility_GaussRadauQuadratureSet.cpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5689223058, "max_line_length": 105, "alphanum_fraction": 0.5475504323, "num_tokens": 3173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6434666611574752}}
{"text": "/* Implementation of the algorithm\n * \n  D. Conte, L. Ixaru, B. Paternoster, G. Santomauro:\n    Exponentially-fitted Gauss\u2013Laguerre quadrature rule for integrals over an unbounded interval.\n    \n  https://hpcquantlib.wordpress.com/2020/05/17/optimized-heston-model-integration-exponentially-fitted-gauss-laguerre-quadrature-rule/\n \n  \n    Copyright (c) 2020, Klaus Spanderen\n    All rights reserved.\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice, this\n    list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright notice,\n    this list of conditions and the following disclaimer in the documentation\n    and/or other materials provided with the distribution.\n    \n    3. Neither the names of the copyright holders nor the names of the QuantLib   \n    Group and its contributors may be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \n*/\n\n#include <ql/math/integrals/gaussianquadratures.hpp>\n\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <queue>\n\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/thread.hpp>\n#include <boost/bind.hpp>\n\n\nusing namespace boost::numeric::ublas;\n\n//typedef boost::multiprecision::number<\n//            boost::multiprecision::cpp_dec_float<400> > Float;\n\ntypedef boost::multiprecision::number<\n            boost::multiprecision::gmp_float<600> > Float;\n\n\ntemplate <class real>\nboost::numeric::ublas::vector<real> lu(\n    const boost::numeric::ublas::matrix<real>& A,\n    const boost::numeric::ublas::vector<real>& b) {\n\n    matrix<real> A_fac = A;\n\n    permutation_matrix<std::size_t> piv(b.size());\n    int singular = lu_factorize(A_fac, piv);\n\n    if (singular) \n        throw std::runtime_error(\"lu: A is singular.\");\n\n    vector<real> x = b;\n    lu_substitute(A_fac, piv, x); \n\n    return x;\n}\n\ntemplate <class real>\nboost::numeric::ublas::matrix<real> inv(\n    const boost::numeric::ublas::matrix<real>& A) {\n    \n    using namespace boost::numeric::ublas;\n\n    matrix<real> A_fac = A;\n\n    permutation_matrix<std::size_t> piv(A.size1());\n    int singular = lu_factorize(A_fac, piv);\n\n    if (singular) \n        throw std::runtime_error(\"lu: A is singular.\");\n    \n    matrix<real> inverse = identity_matrix<real>(A.size1());\n    \n    lu_substitute(A_fac, piv, inverse);\n    \n    return inverse;\n}\n\nFloat pow_c(const Float& x, int n) {\n\n    if (n == 0)\n        return Float(1.0);\n\n    if (n == 1)\n        return x;\n\n    typedef std::pair<int, Float> key_type;\n\n    typedef boost::unordered_map<key_type, Float> ResultMap;\n\n    static boost::mutex mutex;\n\n    static std::size_t maxCacheSize = 16384;\n\n    static ResultMap results;\n    static std::queue<key_type> fifo;\n\n    const key_type key(n, x);\n    {\n        boost::lock_guard<boost::mutex> lock(mutex);\n\n        const typename ResultMap::const_iterator iter = results.find(key);\n\n        if (iter != results.end())\n            return iter->second;\n    }\n\n    const Float result = (n < 0)\n                ? Float(1.0)/pow_c(x, -n)\n                : Float(pow_c(x, n/2) * pow_c(x, n/2) * pow_c(x, n - 2*(n/2)));\n\n    boost::lock_guard<boost::mutex> lock(mutex);\n\n    results.emplace(key, result);\n    fifo.push(key);\n\n    while(fifo.size() > maxCacheSize) {\n        results.erase(fifo.front());\n        fifo.pop();\n    }\n\n    return result;\n}\n\nFloat pow_i(long n) {\n    if (n < 0)\n        return pow_c(Float(2), n);\n    else if (n < 8*sizeof(unsigned long))\n        return Float(1uL << n);\n    else\n        return pow_c(Float(2), n);\n}\n\n\ntemplate <class result_type, class float_type>            \nresult_type eta(int m, float_type Z) {\n    \n    typedef std::pair<int, float_type> key_type;\n    typedef boost::unordered_map<key_type, result_type> ResultMap;\n\n    static boost::mutex mutex;\n\n    static std::size_t maxCacheSize = 16384;\n        \n    static ResultMap results;\n    static std::queue<key_type> fifo;\n\n    const key_type key(m, Z);\n    {\n        boost::lock_guard<boost::mutex> lock(mutex);\n        const typename ResultMap::const_iterator iter = results.find(key);\n\n        if (iter != results.end()) {\n            return iter->second;\n        }\n    }\n\n    result_type result;\n\n    if (m == 0) {\n        if (Z < 0) {\n            const result_type sz = sqrt(-Z);\n            result = sin(sz)/sz;\n        }\n        else if (Z > 0) {\n            const result_type sz = sqrt(Z);\n            result = sinh(sz)/sz;\n        }\n        else\n            result = result_type(1.0);\n    }\n    else if (m == -1)\n        if (Z <= 0)\n            result = cos(sqrt(-Z));\n        else\n            result = cosh(sqrt(Z));\n    else\n        result = (eta<result_type, float_type>(m-2, Z) \n            - (2*m-1)*eta<result_type, float_type>(m-1, Z))/Z;\n    \n    boost::lock_guard<boost::mutex> lock(mutex);\n    results.emplace(key, result);\n    fifo.push(key);\n   \n    while(fifo.size() > maxCacheSize) {\n        results.erase(fifo.front());\n        fifo.pop();\n    }\n        \n    return result;        \n}\n\ntemplate <class real>\nreal factorial(std::size_t n) {\n    static std::vector<real> cache(1, real(1));\n\n    if (cache.size() > n)\n        return cache[n];\n        \n    const real val = real(n) * factorial<real>(n-1);\n    cache.resize(n+1);\n    \n    return cache[n] = val;\n}\n\n\ntemplate <class real>\nvector<real> w_lin(const vector<real>& x, const real& Z) {\n    const int N = x.size();\n    \n    const int s = N/2;\n    const int r = N-s;\n    \n    matrix<real> A(N, N);\n    int row = 0;\n    \n    vector<real> b(x.size());\n    \n    for (int n=r+1; n <= N; ++n) {\n        for (int k=0; k < N; ++k)\n            A(row, k) = pow_c(x(k), 2*n-2)*eta<real, real>(n-2, x(k)*x(k)*Z);\n        \n        b(row) = pow_i(n-1)*factorial<real>(n-1)/pow_c(1.0-Z, n);\n        ++row;\n    }\n    \n    for (int n=s+1; n <= N; ++n) {\n        for (int k=0; k < N; ++k)\n            A(row, k) = pow_c(x(k), 2*n-1)*eta<real, real>(n-1, x(k)*x(k)*Z);\n\n        b(row) = pow_i(n-1)*factorial<real>(n-1)/pow_c(1.0-Z, n);\n        ++row;\n    }\n    \n    return lu(A,b);\n}\n\n\nclass WorkerJxA {\n  public:\n    WorkerJxA(\n        matrix<Float>& JxA, const vector<Float>& w,\n        const vector<Float>& x, const Float& Z)\n    : JxA_(JxA), w_(w), x_(x), Z_(Z) {}\n\n    void run() const {\n        const int N = JxA_.size1();\n        const int s = N/2;\n        const int r = N-s;\n\n        for (int j=0; j < N; ++j) {\n            const Float xxZ = x_(j)*x_(j)*Z_;\n\n            for (int i=1; i <= N; ++i) {\n                JxA_(i-1, j) = (i <= s)\n                    ? pow_c(x_(j), 2*(i+r)-3)*(\n                        2*(i+r-1)*eta<Float, Float>(i+r-2, xxZ)\n                        + xxZ*eta<Float, Float>(i+r-1, xxZ))\n                    : pow_c(x_(j), 2*(i-1))*(\n                        (2*i-1)*eta<Float, Float>(i-1, xxZ)\n                        + xxZ*eta<Float, Float>(i, xxZ));\n                JxA_(i-1, j) *= -w_(j);\n            }\n        }\n    }\n\n  private:\n    matrix<Float>& JxA_;\n    const vector<Float>& w_, x_;\n    const Float& Z_;\n};\n\nclass WorkerInvA {\n  public:\n    WorkerInvA(matrix<Float>& A, const vector<Float>& x, const Float& Z)\n    : A_(A), x_(x), Z_(Z) { }\n\n    void run() const {\n        const int N = A_.size1();\n        const int s = N/2;\n        const int r = N-s;\n\n        for (int j=0; j < N; ++j) {\n            const Float xxZ = x_(j)*x_(j)*Z_;\n            for (int i=1; i <= N; ++i)\n                A_(i-1, j) = (i <= s)\n                   ? pow_c(x_(j), 2*(i+r-1))*eta<Float, Float>(i+r-2, xxZ)\n                   : pow_c(x_(j), 2*i-1    )*eta<Float, Float>(i-1,   xxZ);\n        }\n\n        A_ = inv(A_);\n    }\n\n  private:\n    matrix<Float>& A_;\n    const vector<Float>& x_;\n    const Float& Z_;\n};\n\nclass WorkerC {\n  public:\n    WorkerC(matrix<Float>& C, const vector<Float>& w,\n            const vector<Float>& x, const Float& Z)\n    : C_(C), w_(w), x_(x), Z_(Z) {}\n\n    void run() const {\n        const int N = C_.size1();\n        const int s = N/2;\n        const int r = N-s;\n\n        for (int k=0; k < N; ++k) {\n            const Float xxZ = x_(k)*x_(k)*Z_;\n            for (int i=1; i <= N; ++i) {\n                C_(i-1, k) = (i <= r)\n                    ? pow_c(x_(k), 2*i-3)*( (2*i-2)*eta<Float, Float>(i-2, xxZ)\n                        + xxZ*eta<Float, Float>(i-1, xxZ) )\n                    : pow_c(x_(k), 2*(i-r-1))*( (2*(i-r)-1)*eta<Float, Float>(i-r-1, xxZ)\n                        + xxZ*eta<Float, Float>(i-r, xxZ) );\n                C_(i-1, k) *= w_(k);\n            }\n        }\n    }\n  private:\n    matrix<Float>& C_;\n    const vector<Float>& w_, x_;\n    const Float& Z_;\n};\n\nclass WorkerD {\n  public:\n    WorkerD(matrix<Float>& D, vector<Float>& dZ, const vector<Float>& x, const Float& Z)\n    : D_(D), dZ_(dZ), x_(x), Z_(Z) {}\n\n    void run() const {\n        const int N = D_.size1();\n        const int s = N/2;\n        const int r = N-s;\n\n        for (int k=0; k < N; ++k) {\n            const Float xxZ = x_(k)*x_(k)*Z_;\n            for (int i=1; i <= N; ++i)\n                D_(i-1, k) = ( i <= r)\n                    ? pow_c(x_(k), 2*i-2)    *eta<Float, Float>(i-2, xxZ)\n                    : pow_c(x_(k), 2*(i-r)-1)*eta<Float, Float>(i-r-1, xxZ);\n        }\n\n        const Float omz(1-Z_);\n\n        for (int i=1; i <= N; ++i)\n            dZ_(i-1) = (i <= r)\n                ? pow_i(i-1)*factorial<Float>(i-1) / pow_c(omz, i)\n                : pow_i(i-r-1)*factorial<Float>(i-r-1) / pow_c(omz, i-r);\n    }\n\n  private:\n    matrix<Float>& D_;\n    vector<Float>& dZ_;\n    const vector<Float>& x_;\n    const Float& Z_;\n};\n\n\ntemplate <class real>\nvector<real> newton_iter(const vector<real>& w, const vector<real>& x, const real& Z) {\n    const int N = x.size();\n    const int s = N/2;\n    const int r = N-s;\n    \n    matrix<real> invA(N, N);\n    WorkerInvA workerInvA(invA, x, Z);\n\n    boost::thread invA_thread(&WorkerInvA::run, &workerInvA);\n\n    matrix<real> JxA(N, N);\n\n    WorkerJxA workerJxA(JxA, w, x, Z);\n    boost::thread JxA_thread(&WorkerJxA::run, &workerJxA);\n\n    matrix<real> C(N, N);\n    WorkerC workerC(C, w, x, Z);\n    boost::thread C_thread(&WorkerC::run, &workerC);\n\n    matrix<real> D(N, N);\n    vector<real> dZ(N);\n    WorkerD workerD(D, dZ, x, Z);\n    boost::thread D_thread(&WorkerD::run, &workerD);\n\n\n    JxA_thread.join();\n    invA_thread.join();\n    const matrix<real> JxW = prod(invA, JxA);\n\n    C_thread.join();\n    D_thread.join();\n    \n    const matrix<real> B = C + prod(D, JxW);\n\n    return lu(B, vector<real>(prod(D, w) - dZ));\n}\n    \n    \ntemplate <class real>\nvector<real> newton(vector<real>& x, real Z) {\n    const static real eps = Float(1e-300);\n\n    const std::size_t N = x.size();\n    \n    vector<real> w(N), dx;\n\n    do {\n        w = w_lin(x, Z);\n\n        dx = newton_iter(w, x, Z);           \n\n        x = x - dx;\n        \n        std::cout << norm_2(dx) << std::endl;\n\n        for (std::size_t i=0; i < N; ++i)\n            if (x(i) < 0.0) {\n                return vector<real>();\n            }\n    }\n    while (norm_2(dx) > eps);\n    \n    return w;\n}\n\n\nbool greaterThan(vector<Float>& x, vector<Float>& y) {\n    bool f = false;\n    \n    for (std::size_t i=0; i < x.size(); ++i) {\n        if (x[i] >= y[i]) {\n            f = true;\n        }\n    }\n    return f;\n}\n\n\nint main() {\n    \n    const std::size_t n = 64;\n    const std::size_t maxOrder = 45;\n    \n    const QuantLib::Array x_laguerre = \n        QuantLib::GaussLaguerreIntegration(n).x();\n    const QuantLib::Array w_laguerre = \n        QuantLib::GaussLaguerreIntegration(n).weights();\n                \n    std::vector<vector<Float> > x(maxOrder, vector<Float>(n));\n    std::copy(x_laguerre.begin(), x_laguerre.end(), x[0].begin());\n\n    std::ofstream f(\"values.txt\");\n    f << std::setprecision(std::numeric_limits<double>::digits10 + 1)\n        << \"{ 0.0\";\n    for (std::size_t i = 0; i < n; ++i)\n        f << \", \" << x_laguerre[i];\n    for (std::size_t i = 0; i < n; ++i)\n        f << \", \" << w_laguerre[i];\n    f << \" },\" << std::endl;        \n    f.flush();\n\n    \n    vector<Float> xGuess;\n    std::vector<Float> o(maxOrder, Float(0.0));\n    o[0] = 0.01;\n    \n    std::size_t iter = 0;\n    \n    vector<Float> w;\n    w = newton(x[0], Float(-o[0]*o[0]));\n    \n    while (o[0] < 50.0) {\n\n        ++iter;\n        const std::size_t order = std::min(maxOrder, iter);\n        \n        vector<Float> xTest(n);\n        \n        const Float m1 = o[0] + Float(0.01);\n        const Float m2 = o[0]*(1 + 0.0075);\n        \n        Float nomega = (m1 > m2)? m1 : m2;\n        \n        do {\n            const Float z = -nomega*nomega;\n                        \n            for (std::size_t i=0; i < order; ++i) {\n                Float l=1.0;\n                for (std::size_t j=0; j < order; ++j) \n                    if (i != j)\n                        l *= (nomega-o[j])/(o[i]-o[j]);\n                                    \n                xTest += x[i]*l;\n            }\n            \n            xGuess = xTest;\n\n            w = newton(xTest, z);        \n            \n            if (w.size() == 0) {\n                std::cout << \"opps, monotocity violation \" << nomega;\n                nomega = o[0] + 0.5*(nomega - o[0]);\n                std::cout << \" new \" << nomega << std::endl;\n            }\n        } while (w.size() == 0);\n        \n        std::cout << \"start norm \" << nomega << \" \" << norm_2(xGuess - xTest) << std::endl;\n        \n        if (greaterThan(xTest, x[0]))\n            std::cout << \"wrong direction\" << std::endl;\n        \n        for (int i=std::min(maxOrder-1, order); i > 0; --i) {\n            x[i] = x[i-1];\n            o[i] = o[i-1];\n        }\n        \n        x[0] = xTest;\n        o[0] = nomega;\n                \n        Float s=0;\n        for (std::size_t i=0; i < n; ++i)\n            s+=w(i)*(x[0](i)*cos(o[0]*x[0](i)) + x[0](i)*sin(o[0]*x[0](i)));\n\n        const Float expected = (1+2*o[0]-o[0]*o[0])/(1+o[0]*o[0])/(1+o[0]*o[0]);\n        if (abs(s - expected) > 1e-16) {\n            std::cout << \"integration error \" << abs(s - expected) << std::endl;\n            exit(-1);\n        }\n        \n        f << std::setprecision(std::numeric_limits<double>::digits10 + 1)\n            << \"{ \" << o[0];\n        for (std::size_t i = 0; i < n; ++i)\n            f << \", \" << x[0](i);\n        for (std::size_t i = 0; i < n; ++i)\n            f << \", \" << exp(x[0](i))*w(i);\n        f << \" },\" << std::endl;        \n        f.flush();\n    }\n    f.close();\n}\n", "meta": {"hexsha": "a61ba9e2f2cd7d44e32042c2866811e4f78201d9", "size": 15537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exponential_fitting/ef_laguerre.cpp", "max_stars_repo_name": "klausspanderen/HestonExponentialFitting", "max_stars_repo_head_hexsha": "a06e596340820b181699eb105c90b854246c26b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exponential_fitting/ef_laguerre.cpp", "max_issues_repo_name": "klausspanderen/HestonExponentialFitting", "max_issues_repo_head_hexsha": "a06e596340820b181699eb105c90b854246c26b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exponential_fitting/ef_laguerre.cpp", "max_forks_repo_name": "klausspanderen/HestonExponentialFitting", "max_forks_repo_head_hexsha": "a06e596340820b181699eb105c90b854246c26b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-28T10:57:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:57:06.000Z", "avg_line_length": 27.3538732394, "max_line_length": 134, "alphanum_fraction": 0.519727103, "num_tokens": 4627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.6433551984793934}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include \"datatypes.hpp\"\n#include <Eigen/Eigen>\n#include \"profile.hpp\"\n#include \"integration.hpp\"\n#include \"transformation.hpp\"\n\nnamespace gd {\n\nusing namespace std;\nUSING_PART_OF_NAMESPACE_EIGEN\n\nclass Mesh1d {\npublic:\n\tvirtual int findindex(double) { return 0; }\n\tvirtual double indexto_x(int) { return 0; }\n\t//virtual void indexto_x(int) { return 0; }\n\tvirtual bool inrange(double) { return false; }\n\tvirtual int length() {return 0;}\n};\n\ntemplate<class Base=Mesh1d>\nclass Mesh1dRegular : public Base {\npublic:\n\tMesh1dRegular(double x1, double x2, int length) : x1(x1), x2(x2), _length(length) {}\n\tint findindex(double x) {\n\t\treturn x < x1 ? 0 :\n\t\t\t(x >= x2 ? _length-1 : (int)((x-x1)/(x2-x1)*(_length)));\n\t}\n\tdouble indexto_x(int i) {\n\t\treturn x1 + (x2-x1)/length()*i;\n\t}\n\tbool inrange(double r) {\n\t\treturn (r >= x1) && (r < x2); \n\t}\n\tint length() { return _length; }\n\tdouble x1, x2;\n\tint _length;\n};\n\ntemplate<class T=double>\nclass BasisTriLeft {\npublic:\n\tT operator()(T x) {\n\t\treturn x >= -1 ? (x < 0 ? (x+1) : 0) : 0;\n\t}\n};\n\ntemplate<class T=double>\nclass BasisTriRight {\npublic:\n\tT operator()(T x) {\n\t\treturn x >= 0 ? (x < 1 ? (1-x) : 0) : 0;\n\t}\n};\n\n\t\n\ntemplate<class T=double>\nclass BasisTriMesh1dRegular {\npublic:\n\tBasisTriMesh1dRegular(T _x1, T _x2, int _n_nodes) : x1(_x1), x2(_x2), n_nodes(_n_nodes), mesh(_x1, _x2, _n_nodes), ctrans(_n_nodes+1,_n_nodes+1) {\n\t\tMatrixXd m = MatrixXd::Zero(_n_nodes+1,_n_nodes+1);\n\t\t//m.setZero();\n\t\tm(0,0) = 1./3;\n\t\tm(_n_nodes,_n_nodes) = 1./3;\n\t\tfor(int i = 1; i < (_n_nodes+1); i++) {\n\t\t\tm(i, i-1) = 1./6;\n\t\t\tm(i-1, i) = 1./6;\n\t\t}  \n\t\tfor(int i = 1; i < (_n_nodes); i++) {\n\t\t\tm(i, i) = 2./3;\n\t\t}  \n\t\tT scale = (x2-x1)/n_nodes;\n\t\tm = m * scale;\n\t\t//cout << m << endl;\n\t\tctrans = m.inverse();\n\t\t//cout << ctrans << endl;\n\t}\n\tvoid testprofile(Profile* profile, double_vector v, bool dotrans) {\n\t\tdouble* vp = v.data().begin();\n\t\tdouble* array = vp;\n\t\t//int size = x.size();\n\t\t//double scale = 1./size;\n\t\t//cout << \"size = \" << size << endl;\n\t\tfor(int i = 0; i < n_nodes; i++) {\n\t\t\tdouble integral = 0;\n\t\t\tT xleft = mesh.indexto_x(i);\n\t\t\tT xright = mesh.indexto_x(i+1);\n\t\t\tT dx = (xright-xleft);\n\t\t\t{\n\t\t\t\tBasisTriRight<T> triright;\n\t\t\t\tauto f = [&](double x) { return triright((x-xleft)/dx) * profile->densityr(x); };\n\t\t\t\tIntegratorGSL<> integratorGSL(f); // the integrator\n\t\t\t\tintegral = integratorGSL.integrate(xleft, xright);\n\t\t\t\tarray[i] +=  integral;\n\t\t\t}\n\t\t\t{\n\t\t\t\tBasisTriLeft<T> trileft;\n\t\t\t\tauto f = [&](double x) { return trileft((x-xleft)/dx-1) * profile->densityr(x); };\n\t\t\t\tIntegratorGSL<> integratorGSL(f); // the integrator\n\t\t\t\tintegral = integratorGSL.integrate(xleft, xright);\n\t\t\t\tarray[i+1] +=  integral;\n\t\t\t}\n\t\t}\n\t\tif(dotrans) {\n\t\t\tVectorXd v_alias = VectorXd::Map(v.data().begin(), v.size());\n\t\t\tVectorXd vtrans = ctrans * v_alias;\n\t\t\tVectorXd::Map(v.data().begin(), v.size()) = vtrans;\n\t\t}\n\t}\n\n\tvoid test(double_vector x, double_vector y, double_vector v, bool dotrans) {\n\t\tdouble* xp = x.data().begin();\n\t\tdouble* yp = y.data().begin();\n\t\tdouble* vp = v.data().begin();\n\t\tint size = x.size();\n\t\tdouble scale = 1./size * (x2-x1);\n\t\t//cout << \"size = \" << size << endl;\n\t\tfor(int i = 0; i < size; i++) {\n\t\t\t//cout << \"i = \" << i << endl;\n\t\t\tthis->operator()(xp[i], yp[i]*scale, vp);\n\t\t\t\n\t\t}\n\t\tif(dotrans) {\n\t\t\tVectorXd v_alias = VectorXd::Map(v.data().begin(), v.size());\n\t\t\tVectorXd vtrans = ctrans * v_alias;\n\t\t\tVectorXd::Map(v.data().begin(), v.size()) = vtrans;\n\t\t}\n\t}\n\n\n\ttemplate<class A>\n\tT operator()(T x, T y, A array) {\n\t\tif(mesh.inrange(x)) {\n\t\t\tint indexleft = mesh.findindex(x);\n\t\t\tT xleft = mesh.indexto_x(indexleft);\n\t\t\tT xright = mesh.indexto_x(indexleft+1);\n\t\t\tT fraction = (x-xleft)/(xright-xleft);\n\t\t\t//cout << \"x = \" << x << \" xleft = \" << xleft << \" xright = \" << xright << \" fraction = \" << fraction << endl;\n\t\t\tBasisTriLeft<T> trileft;\n\t\t\tBasisTriRight<T> triright;\n\t\t\t//cout << \"y = \" << y << \" triright(fraction) = \" << triright(fraction) << \" trileft (fraction-1) = \" << trileft (fraction-1) << endl;\n\t\t\tarray[indexleft]   +=  triright(fraction) * y;\n\t\t\tarray[indexleft+1] +=  trileft (fraction-1) * y;\n\t\t\t// TODO: use trileft(fraction) + triright(fraction) == 1\n\t\t}\n\t\treturn 0; // TODO: not finished.., remove code? \n\t}\n\t\n\tT x1, x2;\n\tint n_nodes;\n\tMesh1dRegular<> mesh;\n\tMatrixXd ctrans;\n};\n\ntemplate<class Basis, class T=double>\nclass MeshRegularNodal1d {\npublic:\n\ttypedef Basis basis_type;\n\tT x1, x2;\n\tint n_cells;\n\tMesh1dRegular<> mesh;\n\tMatrixXd ctrans;\n\tTransformation1d_in_3d* transformation;\n\tint dof;\n\tenum { dof_per_cell = Basis::degree+1 };\n\n\tint get_dof() { return dof;}\n\tint get_n_cells() { return n_cells;}\n\tint dof_index(int cell_index, int local_index) {\n\t\treturn  cell_index*(dof_per_cell-1)+local_index;\n\t}\n\n\n\ttemplate<int I, class B=Basis>\n\tstruct util {\n\t\ttypedef util<I-1, typename B::next_type> next_type;\n\t\tnext_type next;\n\t\tT integrate(int i, double xleft, double xright, double dx, Profile* profile) {\n\t\t\tif(i == I) {  \n\t\t\t\tB basis;\n\t\t\t\tauto f = [&](double x) { return basis((x-xleft)/dx) * profile->densityr(x); };\n\t\t\t\tIntegratorGSL<> integratorGSL(f); // the integrator\n\t\t\t\treturn integratorGSL.integrate(xleft, xright);\n\t\t\t} else {\n\t\t\t\treturn next.integrate(i, xleft, xright, dx, profile);\n\t\t\t}\n\t\t}\n\t\ttemplate<class F>\n\t\tT integrate2(int i, double xleft, double xright, double dx, F f) {\n\t\t\tif(i == I) {  \n\t\t\t\tB basis;\n\t\t\t\tauto f2 = [&](double x) { return basis((x-xleft)/dx) * f(x); };\n\t\t\t\tIntegratorGSL<> integratorGSL(f2); // the integrator\n\t\t\t\treturn integratorGSL.integrate(xleft, xright);\n\t\t\t} else {\n\t\t\t\treturn next.integrate2(i, xleft, xright, dx, f);\n\t\t\t}\n\t\t}\n\t\ttemplate<class Array>\n\t\tT eval(Array& array, int index, double xleft, double dx, double x) {\n\t\t\tB basis;\n\t\t\t//cout << \"eval: \" << index << \" \" << xleft << \" \" << dx << \" \" << x << \" u=\" << ((x-xleft)/dx) << \" \" << basis((x-xleft)/dx) << \" \" << array(index) << endl;\n\t\t\treturn basis((x-xleft)/dx) * array(index) + next.eval(array, index-1, xleft, dx, x);\n\t\t}\n\t\ttemplate<class Array>\n\t\tT gradient(Array& array, int index, double xleft, double dx, double x) {\n\t\t\tB basis;\n\t\t\t//cout << \"grad: \" << index << \" \" << xleft << \" \" << dx << \" \" << x << \" u=\" << ((x-xleft)/dx) << \" \" << basis((x-xleft)/dx) << \" \" << basis.dfdx((x-xleft)/dx) << \" \" << array(index) << endl;\n\t\t\treturn basis.dfdx((x-xleft)/dx)/dx * array(index) + next.gradient(array, index-1, xleft, dx, x);\n\t\t}\n\t};\n\ttemplate<class B>\n\tstruct util<-1, B> {\n\t\tT integrate(int, double, double, double, Profile*) {\n\t\t\treturn 0;\n\t\t}\n\t\ttemplate<class F>\n\t\tT integrate2(int, double, double, double, F) {\n\t\t\treturn 0;\n\t\t}\n\t\ttemplate<class Array>\n\t\tT eval(Array&, int, double, double, double) {\n\t\t\treturn 0;\n\t\t}\n\t\ttemplate<class Array>\n\t\tT gradient(Array&, int, double, double, double) {\n\t\t\treturn 0;\n\t\t}\n\t};\n\n\ttemplate<int I, int J, class B1=Basis, class B2=Basis>\n\tstruct selfintegrator {\n\t\ttypedef selfintegrator<I-1, J, typename B1::next_type, B2> next_typeI;\n\t\ttypedef selfintegrator<I, J-1, B1, typename B2::next_type> next_typeJ;\n\t\tnext_typeI nextI;\n\t\tnext_typeJ nextJ;\n\t\tT integrate(int i, int j) {\n\t\t\tif((i == I)) { // first search for right i\n\t\t\t\tif(j == J) { // then right j\n\t\t\t\t\tB1 basis1;\n\t\t\t\t\tB2 basis2;\n\t\t\t\t\tauto f = [&](double x) { return basis1(x) * basis2(x); };\n\t\t\t\t\tIntegratorGSL<> integratorGSL(f);\n\t\t\t\t\treturn integratorGSL.integrate(0, 1);\n\t\t\t\t}  else {\n\t\t\t\t\treturn nextJ.integrate(i, j);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn nextI.integrate(i, j);\n\t\t\t}\n\t\t}\n\t\tT integrate_grad(int i, int j, double xleft, double xright, double dx, Transformation1d_in_3d* transformation) {\n\t\t\tif((i == I)) { // first search for right i\n\t\t\t\tif(j == J) { // then right j\n\t\t\t\t\tB1 basis1;\n\t\t\t\t\tB2 basis2;\n\t\t\t\t\t//auto f = [&](double x) { return basis1.dfdx((x-xleft)/dx) / dx * basis2.dfdx((x-xleft)/dx) / dx *  x * x;}; //*/; };\n\t\t\t\t\tauto f = [&](double x) -> double {\n\t\t\t\t\t\t//double r = tan(u*M_PI/2);\n\t\t\t\t\t\tdouble u = x;\n\t\t\t\t\t\t//double t = tan(u*M_PI/2);\n\t\t\t\t\t\t//double c = cos(u*M_PI/2);\n\t\t\t\t\t\t//return 16./2 * basis1.dfdx((x-xleft)/dx) / dx * basis2.dfdx((x-xleft)/dx) / dx * t * t * c * c;\n\t\t\t\t\t\treturn basis1.dfdx((x-xleft)/dx) / dx * basis2.dfdx((x-xleft)/dx) / dx * transformation->laplace_u1_1_times_d3xdu(u) * transformation->laplace_u1_2(u);\n\t\t\t\t\t}; //*/; };\n\t\t\t\t\tIntegratorGSL<> integratorGSL(f);\n\t\t\t\t\treturn integratorGSL.integrate(xleft, xright);\n\t\t\t\t}  else {\n\t\t\t\t\treturn nextJ.integrate_grad(i, j, xleft, xright, dx, transformation);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn nextI.integrate_grad(i, j, xleft, xright, dx, transformation);\n\t\t\t}\n\t\t}\n\t};\n\ttemplate<int I, class B1, class B2>\n\tstruct selfintegrator<I, -1, B1, B2> {\n\t\tT integrate(int, int) {\n\t\t\treturn 0;\n\t\t}\n\t\tT integrate_grad(int, int, double, double, double, Transformation1d_in_3d*) {\n\t\t\treturn 0;\n\t\t}\n\t};\n\ttemplate<int J, class B1, class B2>\n\tstruct selfintegrator<-1, J, B1, B2> {\n\t\tT integrate(int, int) {\n\t\t\treturn 0;\n\t\t}\n\t\tT integrate_grad(int, int, double, double, double, Transformation1d_in_3d* ) {\n\t\t\treturn 0;\n\t\t}\n\t};\n\n\tdouble integrate_gradshape(int cell_index, int i, int j) {\n\t\ttypedef selfintegrator<Basis::degree, Basis::degree> selfintegrator_type;\n\t\tselfintegrator_type si; \n\t\tT xleft = mesh.indexto_x(cell_index);\n\t\tT xright = mesh.indexto_x(cell_index+1);\n\t\tT dx = (xright-xleft);\n\t\t//cout << \"integrate: \" << cell_index << \" i \" << i << \" \"  << xleft << \" to \" << xright << endl;\n\t\treturn si.integrate_grad(i, j, xleft, xright, dx, transformation);\n\t}\n\n\ttemplate<class F>\n\tdouble integrate_shape(int cell_index, int i, F f) {\n\t\tT xleft = mesh.indexto_x(cell_index);\n\t\tT xright = mesh.indexto_x(cell_index+1);\n\t\tT dx = (xright-xleft);\n\t\tutil<Basis::degree, Basis> integrator;\n\t\t//cout << \"integrate shape: \" << cell_index << \" i \" << i << \" \" << xleft << \" to \" << xright << endl;\n\t\treturn integrator.integrate2(i, xleft, xright, dx, f);\n\t\t//return -integrator.integrate2(dof_per_cell-1-i, xright, xleft, dx, f);\n\t}\n\n\tdouble eval(VectorXd& solution, double x) {\n\t\tint cell_index = mesh.findindex(x);\n\t\tT xleft = mesh.indexto_x(cell_index);\n\t\tT xright = mesh.indexto_x(cell_index+1);\n\t\tT dx = xright-xleft;\n\t\tdouble v = 0;\n\t\tutil<Basis::degree, Basis> util;\n\t\tif(mesh.inrange(x))\n\t\t\tv = util.eval(solution, dof_index(cell_index, dof_per_cell-1), xleft, dx, x);\n\t\t//cout << \"eval: \" << v << endl;\n\t\treturn v;\n\t\t/*for(int i = 0; i < dof_per_cell; i++) {\n\t\t\tev\n\t\t}*/\n\t}\n\n\tdouble gradient(VectorXd& solution, double x) {\n\t\tint cell_index = mesh.findindex(x);\n\t\tT xleft = mesh.indexto_x(cell_index);\n\t\tT xright = mesh.indexto_x(cell_index+1);\n\t\tT dx = xright-xleft;\n\t\tdouble v = 0;\n\t\tutil<Basis::degree, Basis> util;\n\t\tif(mesh.inrange(x))\n\t\t\tv = util.gradient(solution, dof_index(cell_index, dof_per_cell-1), xleft, dx, x);\n\t\t//cout << \"grad: \" << \" \" << cell_index << \" \" << n_cells << \" \" << v << endl;\n\t\treturn v;\n\t\t/*for(int i = 0; i < dof_per_cell; i++) {\n\t\t\tev\n\t\t}*/\n\t}\n\n\n\tMeshRegularNodal1d(T _x1, T _x2, int n_cells, Transformation1d_in_3d* transformation) : x1(_x1), x2(_x2), n_cells(n_cells), mesh(_x1, _x2, n_cells), ctrans(1, 1), transformation(transformation) {\n\t\tif(Basis::degree == 0) {\n\t\t\t//dof_per_cell = 1;\n\t\t\tdof = n_cells;\n\t\t} else {\n\t\t\tdof = 1 + n_cells + (dof_per_cell-2)*n_cells; // 1 dof per border + dofs inside the cel\n\t\t}\n\t\t//cout << \"n_cells = \" << n_cells << \" dof = \" << dof << \" dof_per_cell = \" << dof_per_cell << endl;\n\t\tMatrixXd m = MatrixXd::Zero(dof, dof);\n\t\tctrans.resize(dof, dof);\n\t\tT scale = (x2-x1)/n_cells;\n\n\t\tT integrals[dof_per_cell][dof_per_cell];\n\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\tfor(int k = 0; k < (j+1); k++) {\n\t\t\t\ttypedef selfintegrator<Basis::degree, Basis::degree> selfintegrator_type;\n\t\t\t\tselfintegrator_type si; \n\t\t\t\tdouble integral = si.integrate(j,k);\n\t\t\t\t//cout << j << \" \" << k << \" \" << integral << endl;\n\t\t\t\tintegrals[j][k] = integral;\n\t\t\t\tintegrals[k][j] = integral;\n\t\t\t}\n\t\t}\n\t\tfor(int i = 0; i < n_cells; i++) {\n\t\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\t\tfor(int k = 0; k < dof_per_cell; k++) {\n\t\t\t\t\tint i1 = i*(dof_per_cell-1)+j;\n\t\t\t\t\tint i2 = i*(dof_per_cell-1)+k;\n\t\t\t\t\tm(i1, i2) = m(i1, i2) + integrals[j][k];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//cout << m << endl;\n\t\tm = m * scale;\n\t\tctrans = m.inverse();\n\t}\n\tvoid testprofile(Profile* profile, double_vector v, bool dotrans) {\n\t\tdouble* vp = v.data().begin();\n\t\tassert((int)v.size() == dof);\n\t\tdouble* array = vp;\n\t\t//int size = x.size();\n\t\t//double scale = 1./size;\n\t\t//cout << \"size = \" << size << endl;\n\t\tfor(int i = 0; i < n_cells; i++) {\n\t\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\t\tT xleft = mesh.indexto_x(i);\n\t\t\t\tT xright = mesh.indexto_x(i+1);\n\t\t\t\tT dx = (xright-xleft);\n\t\t\t\tutil<Basis::degree, Basis> integrator;\n\t\t\t\tdouble integral = integrator.integrate(j, xleft, xright, dx, profile);\n\t\t\t\t/**/\n\t\t\t\tcout << \"> \" << i << \" \" << j << \" \" << (i*(dof_per_cell-1)+j) << \" \" << integral << endl; \n\t\t\t\t//array[i*(dof_per_cell-1)+(dof_per_cell-1-j)] += integral;\n\t\t\t\tarray[i*(dof_per_cell-1)+j] += integral;\n\t\t\t\t\n\t\t\t} \n\t\t}\n\t\tif(dotrans) {\n\t\t\tVectorXd v_alias = VectorXd::Map(v.data().begin(), v.size());\n\t\t\tVectorXd vtrans = ctrans * v_alias;\n\t\t\tVectorXd::Map(v.data().begin(), v.size()) = vtrans;\n\t\t}\n\t}\n\n\tvoid test(double_vector x, double_vector y, double_vector v, bool dotrans) {\n\t\t/*double* xp = x.data().begin();\n\t\tdouble* yp = y.data().begin();\n\t\tdouble* vp = v.data().begin();\n\t\tint size = x.size();\n\t\tdouble scale = 1./size * (x2-x1);\n\t\t//cout << \"size = \" << size << endl;\n\t\tfor(int i = 0; i < size; i++) {\n\t\t\t//cout << \"i = \" << i << endl;\n\t\t\tthis->operator()(xp[i], yp[i]*scale, vp);\n\t\t\t\n\t\t}\n\t\tif(dotrans) {\n\t\t\tVectorXd v_alias = VectorXd::Map(v.data().begin(), v.size());\n\t\t\tVectorXd vtrans = ctrans * v_alias;\n\t\t\tVectorXd::Map(v.data().begin(), v.size()) = vtrans;\n\t\t}*/\n\t}\n\n\n\ttemplate<class A>\n\tT operator()(T x, T y, A array) {\n\t\t/*if(mesh.inrange(x)) {\n\t\t\tint indexleft = mesh.findindex(x);\n\t\t\tT xleft = mesh.indexto_x(indexleft);\n\t\t\tT xright = mesh.indexto_x(indexleft+1);\n\t\t\tT fraction = (x-xleft)/(xright-xleft);\n\t\t\t//cout << \"x = \" << x << \" xleft = \" << xleft << \" xright = \" << xright << \" fraction = \" << fraction << endl;\n\t\t\tBasisTriLeft<T> trileft;\n\t\t\tBasisTriRight<T> triright;\n\t\t\t//cout << \"y = \" << y << \" triright(fraction) = \" << triright(fraction) << \" trileft (fraction-1) = \" << trileft (fraction-1) << endl;\n\t\t\tarray[indexleft]   +=  triright(fraction) * y;\n\t\t\tarray[indexleft+1] +=  trileft (fraction-1) * y;\n\t\t\t// TODO: use trileft(fraction) + triright(fraction) == 1\n\t\t}*/\n\t}\n\t\n};\n\n\n}", "meta": {"hexsha": "a8595ee923bc1e6bd120934f85b6263b336d784f", "size": 14389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/mesh.hpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/mesh.hpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdfast/src/mesh.hpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5548245614, "max_line_length": 196, "alphanum_fraction": 0.6010841615, "num_tokens": 4936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6433017399730409}}
{"text": "#ifndef _ROBOT_PLUGIN_HH_\n#define _ROBOT_PLUGIN_HH_\n\n#include <ros/ros.h>\n#include <ros/callback_queue.h>\n#include <ros/subscribe_options.h>\n#include <gazebo/gazebo.hh>\n#include <gazebo/physics/physics.hh>\n#include <gazebo_braitenberg_robot/Sensor.h>\n#include <thread>\n#include <math.h>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Matrix<float, 2, 4> Matrix2_4f; // custom Matrix otherwise initialization doesn't seem to be working\n\nnamespace gazebo{\n\n  /// \\brief A plugin to control a MyRobot sensor.\n  class RobotPlugin : public ModelPlugin{\n\n  private:\n    /// \\brief Pointer to the model.\n    physics::ModelPtr model;\n\n    /// \\brief A node use for ROS transport\n    unique_ptr<ros::NodeHandle> rosNode;\n\n    /// \\brief A ROS subscriber\n    ros::Subscriber rosSub;\n\n    /// \\brief A ROS callbackqueue that helps process messages\n    ros::CallbackQueue rosQueue;\n\n    /// \\brief A thread the keeps running the rosQueue\n    thread rosQueueThread;\n\n    /// \\brief Matrix used for each iteration\n    Matrix2f cst;\n    Matrix2_4f coeff;\n    \n    int MAX_SPEED; // speed in radian/s of wheels\n\n    int BEHAVIOR; // behavior of robot (following/avoiding light)\n  \n  public:\n    /// \\brief tied to behavior\n    const static int FOLLOW = 0;\n    const static int AVOID = 1;\n    \n    /// \\brief Constructor\n    RobotPlugin() {}\n\n    /// \\brief The load function is called by Gazebo when the plugin is\n    /// inserted into simulation\n    /// \\param[in] _model A pointer to the model that this plugin is\n    /// attached to.\n    /// \\param[in] _sdf A pointer to the plugin's SDF element.\n    virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf){\n      // Safety check\n      if(_model->GetJointCount() == 0){\n\tcerr << \"Invalid joint count, MyRobot plugin not loaded\\n\";\n\treturn;\n      }\n\n      // Store the model pointer for convenience.\n      this->model = _model;\n\n      // Check that the sdf elements exist, then read the values\n      if (_sdf->HasElement(\"velocity\"))\n\tMAX_SPEED = _sdf->Get<int>(\"velocity\");\n      if (_sdf->HasElement(\"behavior\"))\n\tBEHAVIOR = _sdf->Get<int>(\"behavior\");\n\n      // Set up matrix\n      cst << 1, 1,\n\t1, -1;\n      switch(BEHAVIOR){\n      case FOLLOW :\n\tcoeff << 4, 6, 6, 4, \n\t  -4, -4, 4, 4;\n\tbreak;\n      case AVOID :\n\tcoeff << 4, 6, 6, 4, \n\t  4, 4, -4, -4;\n\tbreak;\n      default:\n\t// FOLLOW\n\tcoeff << 4, 6, 6, 4, \n\t  -4, -4, 4, 4;\n\tbreak;\n      }\n      \n      // Initialize ros, if it has not already bee initialized.\n      if(!ros::isInitialized()){\n\tint argc = 0;\n\tchar **argv = NULL;\n\tros::init(argc, argv, \"gazebo\",\n\t\t  ros::init_options::NoSigintHandler);\n      }\n\n      // Create our ROS node. This acts in a similar manner to\n      // the Gazebo node\n      this->rosNode.reset(new ros::NodeHandle(\"gazebo_client\"));\n\n      // Create a named topic, and subscribe to it.\n      ros::SubscribeOptions so =\n\tros::SubscribeOptions::create<gazebo_braitenberg_robot::Sensor>(\n\t\t\t\t\t\t\t\t\t\"/lightSensor\",\n\t\t\t\t\t\t\t\t\t100,\n\t\t\t\t\t\t\t\t\tboost::bind(&RobotPlugin::onRosMsg, this, _1),\n\t\t\t\t\t\t\t\t\tros::VoidPtr(), &this->rosQueue);\n      this->rosSub = this->rosNode->subscribe(so);\n\n      // Spin up the queue helper thread.\n      this->rosQueueThread =\n\tthread(bind(&RobotPlugin::QueueThread, this));\n    }\n\n    /// \\brief Handle an incoming message from ROS\n    /// \\param[in] data Sensors data that is used to set the velocity\n    /// of the MyRobot.\n    void onRosMsg(const gazebo_braitenberg_robot::SensorConstPtr &msg){\n      VectorXf sensors(msg->data.size());\n      for(int i = 0; i < msg->data.size(); i++)\n\tsensors(i) = msg->data[i] / 60;\n\n      Vector2f vel = coeff * sensors;\n      Vector2f wheel_speed = cst * vel;\n      \n      float k = max(wheel_speed(0), wheel_speed(1)); // scale wheel speed on MAX_SPEED\n      if(k == 0)\n\tk = 1;\n      setVelocity(wheel_speed(0) * MAX_SPEED / k, wheel_speed(1) * MAX_SPEED / k);\n    }\n\n    /// \\brief Set the velocity of the MyRobot\n    /// \\param[in] l New left target velocity\n    /// \\param[in] r New right target velocity\n    void setVelocity(const double &l, const double &r){\n      this->model->GetJoint(\"my_robot::left_wheel_hinge\")->SetVelocity(0, l);\n      this->model->GetJoint(\"my_robot::right_wheel_hinge\")->SetVelocity(0, r);\n    }\n\n  private:\n    /// \\brief ROS helper function that processes messages\n    void QueueThread(){\n      static const double timeout = 0.01;\n      while (this->rosNode->ok())\n\t{\n\t  this->rosQueue.callAvailable(ros::WallDuration(timeout));\n\t}\n    }\n  };\n\n  // Tell Gazebo about this plugin, so that Gazebo can call Load on this plugin.\n  GZ_REGISTER_MODEL_PLUGIN(RobotPlugin)\n}\n#endif\n", "meta": {"hexsha": "849bcb52041130c7285668db2b2479275903822b", "size": 4634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/robot_plugin.cpp", "max_stars_repo_name": "merlin24u/Gazebo_Braitenberg_Robot", "max_stars_repo_head_hexsha": "5c58d64411c6aee5d071b67f498977205d1490f8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/robot_plugin.cpp", "max_issues_repo_name": "merlin24u/Gazebo_Braitenberg_Robot", "max_issues_repo_head_hexsha": "5c58d64411c6aee5d071b67f498977205d1490f8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/robot_plugin.cpp", "max_forks_repo_name": "merlin24u/Gazebo_Braitenberg_Robot", "max_forks_repo_head_hexsha": "5c58d64411c6aee5d071b67f498977205d1490f8", "max_forks_repo_licenses": ["BSD-3-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.6049382716, "max_line_length": 108, "alphanum_fraction": 0.6426413466, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6432530122885766}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_ATAN2D_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATAN2D_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing atan2d capabilities\n\n    atan2d function : atan2 in degrees.\n\n    @par Semantic:\n\n    For every parameters of same floating type\n\n    @code\n    auto r = atan2d(y, x);\n    @endcode\n\n    is similar  to:\n\n    @code\n    T r =  indeg(atan2(y, x));\n    @endcode\n\n    For any real arguments @c x and @c y not both equal to zero, <tt>atan2d(y, x)</tt>\n    is the angle in degrees between the positive x-axis of a plane and the point\n    given by the coordinates  <tt>(x, yx)</tt>.\n\n    It is also the angle in \\f$[-180,180[\\f$ for which\n    \\f$x/\\sqrt{x^2+y^2}\\f$ and \\f$y/\\sqrt{x^2+y^2}\\f$\n    are respectively the sine and the cosine.\n\n    @see atand, atan2, atan\n\n  **/\n  Value atan2d(Value const& x, Value const& y );\n} }\n#endif\n\n#include <boost/simd/function/scalar/atan2d.hpp>\n#include <boost/simd/function/simd/atan2d.hpp>\n\n#endif\n", "meta": {"hexsha": "c5dff5470668c1720565fab5b2fa831b0cfd622a", "size": 1453, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/atan2d.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/function/atan2d.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/atan2d.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 25.0517241379, "max_line_length": 100, "alphanum_fraction": 0.5877494838, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.64319617888732}}
{"text": "/** @file SymmetricBetaDist.cpp\n * @author Mark J. Olah (mjo\\@cs.unm DOT edu)\n * @date 2017-2019\n * @brief SymmetricBetaDist class definition\n * \n */\n#include \"PriorHessian/SymmetricBetaDist.h\"\n#include \"PriorHessian/PriorHessianError.h\"\n\n#include <sstream>\n#include <cmath>\n#include <limits>\n\n#include <boost/math/special_functions/beta.hpp>\n\nnamespace prior_hessian {\n\nconst StringVecT SymmetricBetaDist::_param_names = { \"beta\" };\nconst SymmetricBetaDist::NparamsVecT SymmetricBetaDist::_param_lbound = { 0 }; //Lower bound on valid parameter values \nconst SymmetricBetaDist::NparamsVecT SymmetricBetaDist::_param_ubound = { INFINITY }; //Upper bound on valid parameter values\n\n/* Constructors */\nSymmetricBetaDist::SymmetricBetaDist(double beta) \n    : UnivariateDist(),\n      _beta(checked_beta(beta)),\n      llh_const_initialized(false)\n{ }\n\n/* Non-static member functions */\nvoid  SymmetricBetaDist::set_beta(double val) \n{ \n    _beta = checked_beta(val); \n    llh_const_initialized = false;\n}\n\ndouble SymmetricBetaDist::cdf(double x) const\n{\n    if(x==0) return 0;\n    if(x==1) return 1;\n    return boost::math::ibeta(_beta, _beta, x);\n}\n\ndouble SymmetricBetaDist::icdf(double u) const\n{\n    if(u==0) return 0;\n    if(u==1) return 1;\n    return boost::math::ibeta_inv(_beta, _beta, u);\n}\n\ndouble SymmetricBetaDist::pdf(double x) const\n{\n   return boost::math::ibeta_derivative(_beta, _beta, x);\n}\n\ndouble SymmetricBetaDist::llh(double x) const \n{ \n    if(!llh_const_initialized) initialize_llh_const();\n    return rllh(x) + llh_const; \n}\n\nvoid SymmetricBetaDist::initialize_llh_const() const\n{\n    llh_const = compute_llh_const(beta());\n    llh_const_initialized = true;\n}\n\ndouble SymmetricBetaDist::compute_llh_const(double beta)\n{\n    return -2*lgamma(beta) - lgamma(2*beta);//log(1/Beta(beta,beta))\n}\n\ndouble SymmetricBetaDist::checked_beta(double val)\n{\n    if(val<=0 || !std::isfinite(val)) {\n        std::ostringstream msg;\n        msg<<\"SymmetricBetaDist: got bad beta value:\"<<val;\n        throw ParameterValueError(msg.str());\n    }\n    return val;\n}\n  \n} /* namespace prior_hessian */\n", "meta": {"hexsha": "c69c4a4363131a19dec0b03b4ed6c50d045ca984", "size": 2103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SymmetricBetaDist.cpp", "max_stars_repo_name": "markjolah/PriorHessianLib", "max_stars_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-20T07:40:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T07:40:29.000Z", "max_issues_repo_path": "src/SymmetricBetaDist.cpp", "max_issues_repo_name": "markjolah/PriorHessianLib", "max_issues_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SymmetricBetaDist.cpp", "max_forks_repo_name": "markjolah/PriorHessianLib", "max_forks_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_forks_repo_licenses": ["Apache-2.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.3373493976, "max_line_length": 125, "alphanum_fraction": 0.7104136947, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6431519543581257}}
{"text": "#ifndef IGLP_HPP\n#define IGLP_HPP\n\n#include <glpk.h>\n#include <Eigen/Eigen>\n\n#include <cstdio>\n#include <cstdlib>\n#include <string>\n\nnamespace iglp\n{\n\ninline double linprog(const Eigen::VectorXd &c,\n                      const Eigen::MatrixXd &A,\n                      const Eigen::VectorXd &b,\n                      Eigen::VectorXd &x,\n                      bool ipm = false,\n                      bool verbose = false)\n// linprog:\n//         min cTx s.t. Ax<=b\n// input:\n//         c: d*1 objective coeffs\n//         A: m*d constraint matrix\n//         b: m*1 constraint bound\n//         ipm: use interior point method\n//              or simplex method\n//         verbose: show details\n// output:\n//         x: d*1 decision variables\n// return:\n//         inf: No feasible solution or fail\n//        -inf: Unbounded problem\n//         real: minimum objective function\n{\n    int d = c.size();\n    int m = b.size();\n    int dm = d * m;\n    x = Eigen::VectorXd::Zero(d);\n\n    glp_prob *lp;\n    int *ia = new int[dm + 1];\n    int *ja = new int[dm + 1];\n    double *ar = new double[dm + 1];\n    int s;\n    double z;\n\n    lp = glp_create_prob();\n    glp_set_prob_name(lp, \"lp\");\n    glp_set_obj_dir(lp, GLP_MIN);\n\n    glp_add_rows(lp, m);\n    for (int i = 1; i <= m; i++)\n    {\n        glp_set_row_name(lp, i, (std::to_string(i) + \"y\").c_str());\n        glp_set_row_bnds(lp, i, GLP_UP, 0.0, b(i - 1));\n    }\n\n    glp_add_cols(lp, d);\n    for (int i = 1; i <= d; i++)\n    {\n        glp_set_col_name(lp, i, (std::to_string(i) + \"x\").c_str());\n        glp_set_col_bnds(lp, i, GLP_FR, 0.0, 0.0);\n        glp_set_obj_coef(lp, i, c(i - 1));\n    }\n\n    int k = 1;\n    for (int i = 1; i <= m; i++)\n    {\n        for (int j = 1; j <= d; j++)\n        {\n            ia[k] = i;\n            ja[k] = j;\n            ar[k] = A(i - 1, j - 1);\n            k++;\n        }\n    }\n    glp_load_matrix(lp, dm, ia, ja, ar);\n\n    if (!ipm)\n    {\n        glp_smcp param;\n        glp_init_smcp(&param);\n        param.msg_lev = verbose ? GLP_MSG_ALL : GLP_MSG_OFF;\n        glp_simplex(lp, &param);\n        s = glp_get_status(lp);\n        z = INFINITY;\n        if (s == GLP_OPT || s == GLP_UNBND)\n        {\n            z = (s == GLP_UNBND) ? -INFINITY : glp_get_obj_val(lp);\n            for (int i = 1; i <= d; i++)\n            {\n                x(i - 1) = glp_get_col_prim(lp, i);\n            }\n        }\n    }\n    else\n    {\n        glp_iptcp param;\n        glp_init_iptcp(&param);\n        param.msg_lev = verbose ? GLP_MSG_ALL : GLP_MSG_OFF;\n        glp_interior(lp, &param);\n        s = glp_ipt_status(lp);\n        z = INFINITY;\n        if (s == GLP_OPT)\n        {\n            z = glp_ipt_obj_val(lp);\n            for (int i = 1; i <= d; i++)\n            {\n                x(i - 1) = glp_ipt_col_prim(lp, i);\n            }\n        }\n    }\n\n    glp_delete_prob(lp);\n    delete[] ia;\n    delete[] ja;\n    delete[] ar;\n\n    return z;\n}\n\n} // namespace iglp\n\n#endif", "meta": {"hexsha": "21a4dd778d36230306d6e4d32eb0521c27eca275", "size": 2932, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "iglp.hpp", "max_stars_repo_name": "ZJU-FAST-Lab/GLPK_Interface", "max_stars_repo_head_hexsha": "810eac17e67dff1a8a67251393900fb42a781481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-09T02:10:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T02:10:40.000Z", "max_issues_repo_path": "iglp.hpp", "max_issues_repo_name": "ZJU-FAST-Lab/GLPK_Interface", "max_issues_repo_head_hexsha": "810eac17e67dff1a8a67251393900fb42a781481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "iglp.hpp", "max_forks_repo_name": "ZJU-FAST-Lab/GLPK_Interface", "max_forks_repo_head_hexsha": "810eac17e67dff1a8a67251393900fb42a781481", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.456, "max_line_length": 67, "alphanum_fraction": 0.471691678, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6431519486827599}}
{"text": "//  (C) Copyright Christopher Kormanyos 1999 - 2021.\n//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_CCMATH_FREXP_HPP\n#define BOOST_MATH_CCMATH_FREXP_HPP\n\n#include <cmath>\n#include <limits>\n#include <type_traits>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isfinite.hpp>\n\nnamespace boost::math::ccmath {\n\nnamespace detail\n{\n\ntemplate <typename Real>\ninline constexpr Real frexp_zero_impl(Real arg, int* exp)\n{\n    *exp = 0;\n    return arg;\n}\n\ntemplate <typename Real>\ninline constexpr Real frexp_impl(Real arg, int* exp)\n{\n    const bool negative_arg = (arg < Real(0));\n    \n    Real f = negative_arg ? -arg : arg;\n    int e2 = 0;\n    constexpr Real two_pow_32 = Real(4294967296);\n\n    while (f >= two_pow_32)\n    {\n        f = f / two_pow_32;\n        e2 += 32;\n    }\n\n    while(f >= Real(1))\n    {\n        f = f / Real(2);\n        ++e2;\n    }\n    \n    if(exp != nullptr)\n    {\n        *exp = e2;\n    }\n\n    return !negative_arg ? f : -f;\n}\n\n} // namespace detail\n\ntemplate <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>\ninline constexpr Real frexp(Real arg, int* exp)\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))\n    {\n        return arg == Real(0)  ? detail::frexp_zero_impl(arg, exp) : \n               arg == Real(-0) ? detail::frexp_zero_impl(arg, exp) :\n               boost::math::ccmath::isinf(arg) ? detail::frexp_zero_impl(arg, exp) : \n               boost::math::ccmath::isnan(arg) ? detail::frexp_zero_impl(arg, exp) :\n               boost::math::ccmath::detail::frexp_impl(arg, exp);\n    }\n    else\n    {\n        using std::frexp;\n        return frexp(arg, exp);\n    }\n}\n\ntemplate <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>\ninline constexpr double frexp(Z arg, int* exp)\n{\n    return boost::math::ccmath::frexp(static_cast<double>(arg), exp);\n}\n\ninline constexpr float frexpf(float arg, int* exp)\n{\n    return boost::math::ccmath::frexp(arg, exp);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr long double frexpl(long double arg, int* exp)\n{\n    return boost::math::ccmath::frexp(arg, exp);\n}\n#endif\n\n}\n\n#endif // BOOST_MATH_CCMATH_FREXP_HPP\n", "meta": {"hexsha": "88b520c1ec193d3b299178788635fd2cdb10b409", "size": 2393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/frexp.hpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "include/boost/math/ccmath/frexp.hpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "include/boost/math/ccmath/frexp.hpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 24.1717171717, "max_line_length": 85, "alphanum_fraction": 0.647722524, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.643151943007394}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <cstddef>\n#include <cassert>\n#include <limits>\n#include <Eigen/Sparse>\n\nusing namespace std;\n\nclass Array2D\n{\nprivate:\n\tvector<double> m_data;\n\tsize_t m_Nx, m_Ny;\n\npublic:\n\tArray2D(size_t nx, size_t ny, double val = 0.0) : m_Nx(nx), m_Ny(ny), m_data(nx*ny, val) {}\n\n\t// 0-based indexing\n\tdouble &at(int i, int j)\n\t{\n\t\tint idx = i + m_Nx * j;\n\t\treturn m_data[idx];\n\t}\n\n\tdouble at(int i, int j) const\n\t{\n\t\tint idx = i + m_Nx * j;\n\t\treturn m_data[idx];\n\t}\n\n\t// 1-based indexing\n\tdouble &operator()(int i, int j)\n\t{\n\t\treturn at(i - 1, j - 1);\n\t}\n\n\tdouble operator()(int i, int j) const\n\t{\n\t\treturn at(i - 1, j - 1);\n\t}\n};\n\nconst size_t WIDTH = 16;\nconst size_t DIGITS = 7;\n\nconst double L = 0.5; // m\nconst double D = 0.01; // m\nconst double Ue = 1.0; // m/s\nconst double Pe = 0.0;\nconst double rho = 1.225; // Kg/m3\nconst double mu = 3.737e-5; // Kg/m/s\n\nconst int Nx = 21, Ny = 11;\nconst double dx = L / (Nx - 1), dy = D / (Ny - 1);\nconst double dx2 = 2 * dx, dy2 = 2 * dy;\nconst double dxdx = dx * dx, dydy = dy * dy;\nvector<double> x(Nx, 0.0), y(Ny, 0.0);\n\nconst double dt = 0.001;\ndouble t = 0.0;\nint iter_cnt = 0;\nconst int MAX_ITER_NUM = 2000;\n\nconst double a = 2 * (dt / dxdx + dt / dydy);\nconst double b = -dt / dxdx;\nconst double c = -dt / dydy;\ndouble d_min = numeric_limits<double>::max(), d_max = numeric_limits<double>::min(), d_15_5 = 0.0;\n\nArray2D p(Nx, Ny, Pe), p_star(Nx, Ny, Pe), p_prime(Nx, Ny, 0.0);\nArray2D u(Nx + 1, Ny, 0.0), u_wedge(Nx + 1, Ny, 0.0), u_star(Nx + 1, Ny, 0.0), u_prime(Nx + 1, Ny, 0.0);\nArray2D v(Nx + 2, Ny + 1, 0.0), v_wedge(Nx + 2, Ny + 1, 0.0), v_star(Nx + 2, Ny + 1, 0.0), v_prime(Nx + 2, Ny + 1, 0.0);\n\n// Full flowfield in TECPLOT ASCII Format.\nvoid output1(void)\n{\n\tArray2D u_interp(Nx, Ny, 0.0);\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tu_interp(i, 1) = 0.0; // Bottom\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 1; i <= Nx; ++i)\n\t\t\tu_interp(i, j) = (u(i, j) + u(i + 1, j)) / 2; // Inner\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tu_interp(i, Ny) = Ue; // Top\n\n\tArray2D v_interp(Nx, Ny, 0.0);\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tv_interp(i, 1) = 0.0; // Bottom\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t{\n\t\tv_interp(1, j) = 0.0; // Left\n\t\tfor (int i = 3; i <= Nx + 1; ++i)\n\t\t\tv_interp(i - 1, j) = (v(i, j) + v(i, j + 1)) / 2; // Inner and Right\n\t}\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tv_interp(i, Ny) = 0.0; // Top\n\n\t// Create Tecplot data file.\n\tofstream result(\"flow\" + to_string(iter_cnt) + \".dat\");\n\tif (!result)\n\t\tthrow(\"Failed to create data file!\");\n\n\t// Header\n\tresult << \"TITLE = \\\"t=\" << t << \"\\\"\" << endl;\n\tresult << \"VARIABLES = \\\"X\\\", \\\"Y\\\", \\\"P\\\", \\\"U\\\", \\\"V\\\"\" << endl;\n\tresult << \"ZONE I=\" << Nx << \", J=\" << Ny << \", F=POINT\" << endl;\n\n\t// Flowfield data\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfor (int i = 1; i <= Nx; ++i)\n\t\t{\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << x[i - 1];\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << y[j - 1];\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << p(i, j);\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << u_interp(i, j);\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << v_interp(i, j);\n\t\t\tresult << endl;\n\t\t}\n\n\t// Finalize\n\tresult.close();\n}\n\n// Statistics at (15, 5) and i=15\nvoid output2(int iter)\n{\n\tstatic const string fn(\"history_at_15_5.txt\");\n\n\tofstream fout;\n\tif (iter == 0)\n\t{\n\t\tfout.open(fn, ios::out);\n\t\tif (!fout)\n\t\t\tthrow(\"Failed to open history file.\");\n\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t\tfout << setw(WIDTH) << setprecision(DIGITS) << y[j];\n\t\tfout << endl;\n\t}\n\telse\n\t{\n\t\tfout.open(fn, ios::app);\n\t\tif (!fout)\n\t\t\tthrow(\"Failed to open history file.\");\n\t}\n\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfout << setw(WIDTH) << setprecision(DIGITS) << u(15, j);\n\tfout << endl;\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfout << setw(WIDTH) << setprecision(DIGITS) << v(15, j);\n\tfout << endl;\n\tfout << d_15_5 << endl;\n\n\tfout.close();\n}\n\nvoid init(void)\n{\n\tcout << \"mu=\" << mu << endl;\n\tcout << \"dt=\" << dt << endl;\n\n\t// Init\n\tfor (int i = 1; i < Nx; ++i)\n\t\tx[i] = L * i / (Nx - 1); // X-Coordinates\n\tfor (int j = 1; j < Ny; ++j)\n\t\ty[j] = D * j / (Ny - 1); // Y-Coordinates\n\n\tfor (int i = 1; i <= Nx + 1; ++i)\n\t\tu(i, Ny) = u_wedge(i, Ny) = u_star(i, Ny) = Ue; // U at top\n\tv(15, 5) = v_wedge(15, 5) = v_star(15, 5) = 0.5; // Initial peak to ensure 2D flow structure\n}\n\n// Solve the pressure equation.\nvoid ImplicitMethod1()\n{\n\ttypedef Eigen::SparseMatrix<double> SpMat;\n\ttypedef Eigen::Triplet<double> T;\n\n\tconst int m = Nx * Ny;\n\tvector<T> coef;\n\tEigen::VectorXd rhs(m);\n\tSpMat A(m, m);\n\n\t// Calculating coefficients\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tconst int id_w = id - 1;\n\t\t\tconst int id_e = id + 1;\n\t\t\tconst int id_n = id + Nx;\n\t\t\tconst int id_s = id - Nx;\n\n\t\t\tif (i == 0 || i == Nx - 1) // Inlet and Outlet\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id, 1.0));\n\t\t\t\trhs(id) = Pe;\n\t\t\t}\n\t\t\telse if (j == 0) // Bottom\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id_n, 1.0));\n\t\t\t\tcoef.push_back(T(id, id, -1.0));\n\t\t\t\tconst double ddvddx = 0.0;\n\t\t\t\t//const double ddvddy = 4.0 / 3 * (v_wedge.at(i + 1, j + 2) - 3 * v_wedge.at(i + 1, j + 1)) / dydy; \n\t\t\t\tconst double ddvddy = 0.0;\n\t\t\t\trhs(id) = mu * (ddvddx + ddvddy) * dy;\n\t\t\t}\n\t\t\telse if (j == Ny - 1) // Top\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id, 1.0));\n\t\t\t\tcoef.push_back(T(id, id_s, -1.0));\n\t\t\t\tconst double ddvddx = 0.0;\n\t\t\t\t//const double ddvddy = 4.0 / 3 * (v_wedge.at(i + 1, j - 1) - 3 * v_wedge.at(i + 1, j)) / dydy;\n\t\t\t\tconst double ddvddy = 0.0;\n\t\t\t\trhs(id) = mu * (ddvddx + ddvddy) * dy;\n\t\t\t}\n\t\t\telse // Inner\n\t\t\t{\n\t\t\t\t// Use 0-based interface\n\t\t\t\tconst double d = (rho*u_wedge.at(i + 1, j) - rho * u_wedge.at(i, j)) / dx + (rho*v_wedge.at(i + 1, j + 1) - rho * v_wedge.at(i + 1, j)) / dy;\n\n\t\t\t\tcoef.push_back(T(id, id, a));\n\t\t\t\tcoef.push_back(T(id, id_w, b));\n\t\t\t\tcoef.push_back(T(id, id_e, b));\n\t\t\t\tcoef.push_back(T(id, id_n, c));\n\t\t\t\tcoef.push_back(T(id, id_s, c));\n\t\t\t\trhs(id) = -d;\n\t\t\t}\n\t\t}\n\n\t// Construct sparse matrix\n\tA.setFromTriplets(coef.begin(), coef.end());\n\n\t// Solve the linear system: Ax = rhs\n\tEigen::SimplicialCholesky<SpMat> chol(A);\n\tEigen::VectorXd x = chol.solve(rhs);\n\n\t// Update p\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tp.at(i, j) = x(id);\n\t\t}\n}\n\n// Solve the pressure-correction equation\nvoid ImplicitMethod2()\n{\n\ttypedef Eigen::SparseMatrix<double> SpMat;\n\ttypedef Eigen::Triplet<double> T;\n\n\tconst int m = Nx * Ny;\n\tvector<T> coef;\n\tEigen::VectorXd rhs(m);\n\tSpMat A(m, m);\n\n\t// Calculating coefficients\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tconst int id_w = id - 1;\n\t\t\tconst int id_e = id + 1;\n\t\t\tconst int id_n = id + Nx;\n\t\t\tconst int id_s = id - Nx;\n\n\t\t\tif (i == 0 || i == Nx - 1) // Inlet and Outlet\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id, 1.0));\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse if (j == 0) // Bottom\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id, 1.0));\n\t\t\t\tcoef.push_back(T(id, id_n, -1.0));\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse if (j == Ny - 1) // Top\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id, 1.0));\n\t\t\t\tcoef.push_back(T(id, id_s, -1.0));\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse // Inner\n\t\t\t{\n\t\t\t\t// Use 0-based interface\n\t\t\t\tconst double d = (rho*u_star.at(i + 1, j) - rho * u_star.at(i, j)) / dx + (rho * v_star.at(i + 1, j + 1) - rho * v_star.at(i + 1, j)) / dy;\n\t\t\t\tif (d > d_max)\n\t\t\t\t\td_max = d;\n\t\t\t\tif (d < d_min)\n\t\t\t\t\td_min = d;\n\t\t\t\tif (i == 15 && j == 5)\n\t\t\t\t\td_15_5 = d;\n\n\t\t\t\tcoef.push_back(T(id, id, a));\n\t\t\t\tcoef.push_back(T(id, id_w, b));\n\t\t\t\tcoef.push_back(T(id, id_e, b));\n\t\t\t\tcoef.push_back(T(id, id_n, c));\n\t\t\t\tcoef.push_back(T(id, id_s, c));\n\t\t\t\trhs(id) = -d;\n\t\t\t}\n\t\t}\n\n\t// Construct sparse matrix\n\tA.setFromTriplets(coef.begin(), coef.end());\n\n\t// Solve the linear system: Ax = rhs\n\tEigen::SimplicialCholesky<SpMat> chol(A);\n\tEigen::VectorXd x = chol.solve(rhs);\n\n\t// Update p_prime\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tp_prime.at(i, j) = x(id);\n\t\t}\n}\n\nvoid SIMPLER(void)\n{\n\t// u_wedge at inner points\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 2; i <= Nx; ++i)\n\t\t{\n\t\t\tdouble v_bar1 = 0.5*(v(i, j + 1) + v(i + 1, j + 1));\n\t\t\tdouble v_bar2 = 0.5*(v(i, j) + v(i + 1, j));\n\n\t\t\tdouble t11 = rho * pow(u(i + 1, j), 2) - rho * pow(u(i - 1, j), 2);\n\t\t\tdouble t12 = rho * u(i, j + 1)*v_bar1 - rho * u(i, j - 1)*v_bar2;\n\t\t\tdouble t21 = u(i + 1, j) - 2 * u(i, j) + u(i - 1, j);\n\t\t\tdouble t22 = u(i, j + 1) - 2 * u(i, j) + u(i, j - 1);\n\t\t\tdouble A = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tu_wedge(i, j) = (rho * u(i, j) + A * dt) / rho;\n\t\t}\n\n\t// v_wedge at inner points\n\tfor (int i = 3; i <= Nx; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tdouble u_bar1 = 0.5 *(u(i, j - 1) + u(i, j));\n\t\t\tdouble u_bar2 = 0.5 *(u(i - 1, j - 1) + u(i - 1, j));\n\n\t\t\tdouble t11 = rho * v(i + 1, j) * u_bar1 - rho * v(i - 1, j) * u_bar2;\n\t\t\tdouble t12 = rho * pow(v(i, j + 1), 2) - rho * pow(v(i, j - 1), 2);\n\t\t\tdouble t21 = v(i + 1, j) - 2 * v(i, j) + v(i - 1, j);\n\t\t\tdouble t22 = v(i, j + 1) - 2 * v(i, j) + v(i, j - 1);\n\t\t\tdouble B = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tv_wedge(i, j) = (rho * v(i, j) + B * dt) / rho;\n\t\t}\n\n\t// Solve p\n\tImplicitMethod1();\n\n\t// Set p_star to p\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfor (int i = 1; i <= Nx; ++i)\n\t\t\tp_star(i, j) = p(i, j);\n\n\t// u_star at inner points\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 2; i <= Nx; ++i)\n\t\t{\n\t\t\tdouble v_bar1 = 0.5*(v(i, j + 1) + v(i + 1, j + 1));\n\t\t\tdouble v_bar2 = 0.5*(v(i, j) + v(i + 1, j));\n\n\t\t\tdouble t11 = rho * pow(u(i + 1, j), 2) - rho * pow(u(i - 1, j), 2);\n\t\t\tdouble t12 = rho * u(i, j + 1)*v_bar1 - rho * u(i, j - 1)*v_bar2;\n\t\t\tdouble t21 = u(i + 1, j) - 2 * u(i, j) + u(i - 1, j);\n\t\t\tdouble t22 = u(i, j + 1) - 2 * u(i, j) + u(i, j - 1);\n\t\t\tdouble A = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tu_star(i, j) = (rho * u(i, j) + A * dt - dt / dx * (p_star(i, j) - p_star(i - 1, j))) / rho;\n\t\t}\n\n\t// v_star at inner points\n\tfor (int i = 3; i <= Nx + 1; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tdouble u_bar1 = 0.5 *(u(i, j - 1) + u(i, j));\n\t\t\tdouble u_bar2 = 0.5 *(u(i - 1, j - 1) + u(i - 1, j));\n\n\t\t\tdouble t11 = rho * v(i + 1, j) * u_bar1 - rho * v(i - 1, j) * u_bar2;\n\t\t\tdouble t12 = rho * pow(v(i, j + 1), 2) - rho * pow(v(i, j - 1), 2);\n\t\t\tdouble t21 = v(i + 1, j) - 2 * v(i, j) + v(i - 1, j);\n\t\t\tdouble t22 = v(i, j + 1) - 2 * v(i, j) + v(i, j - 1);\n\t\t\tdouble B = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tv_star(i, j) = (rho * v(i, j) + B * dt - dy / dy * (p_star(i - 1, j) - p_star(i - 1, j - 1))) / rho;\n\t\t}\n\n\td_min = numeric_limits<double>::max();\n\td_max = numeric_limits<double>::min();\n\tImplicitMethod2();\n\n\t// Correct u at inner nodes\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 2; i <= Nx; ++i)\n\t\t{\n\t\t\tu_prime(i, j) = -dt / dx * (p_prime(i, j) - p_prime(i - 1, j)) / rho; // u_prime\n\t\t\tu(i, j) = u_star(i, j) + u_prime(i, j);\n\t\t}\n\n\t// Linear extrapolation of u at virtual nodes\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t{\n\t\tu(1, j) = 2 * u(2, j) - u(3, j);\n\t\tu(Nx + 1, j) = 2 * u(Nx, j) - u(Nx - 1, j);\n\t}\n\n\t// Correct v at inner nodes\n\tfor (int i = 3; i <= Nx + 1; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tv_prime(i, j) = -dt / dy * (p_prime(i - 1, j) - p_prime(i - 1, j - 1)) / rho; // v_prime\n\t\t\tv(i, j) = v_star(i, j) + v_prime(i, j);\n\t\t}\n\n\t// Linear extrapolation of v at both top and bottom virtual nodes\n\t// No-Penetration at both top and bottom\n\tfor (int i = 2; i <= Nx + 1; ++i)\n\t{\n\t\tv(i, 1) = -v(i, 2);\n\t\tv(i, Ny + 1) = -v(i, Ny);\n\t}\n\n\t// Linear extrapolation of v at right virtual nodes\n\tfor (int j = 2; j <= Ny; ++j)\n\t\tv(Nx + 2, j) = 2 * v(Nx + 1, j) - v(Nx, j);\n}\n\nbool check_convergence(void)\n{\n\t// Statistics of the mass flux residue\n\tcout << \"Max(d)=\" << d_max << \" Min(d)=\" << d_min << endl;\n\n\t// Statistics of u\n\tdouble u_max = numeric_limits<double>::min();\n\tdouble u_min = numeric_limits<double>::max();\n\tfor (int i = 2; i <= Nx; ++i)\n\t\tfor (int j = 1; j <= Ny; ++j)\n\t\t{\n\t\t\tu_max = max(u_max, u(i, j));\n\t\t\tu_min = min(u_min, u(i, j));\n\t\t}\n\tcout << \"Max(u)=\" << u_max << \" Min(u)=\" << u_min << endl;\n\n\t// Statistics of v\n\tdouble v_max = numeric_limits<double>::min();\n\tdouble v_min = numeric_limits<double>::max();\n\tfor (int i = 2; i <= Nx + 1; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tv_max = max(v_max, v(i, j));\n\t\t\tv_min = min(v_min, v(i, j));\n\t\t}\n\tcout << \"Max(v)=\" << v_max << \" Min(v)=\" << v_min << endl;\n\n\t// Statistics of p\n\tdouble p_max = numeric_limits<double>::min();\n\tdouble p_min = numeric_limits<double>::max();\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tfor (int j = 1; j <= Ny; ++j)\n\t\t{\n\t\t\tp_max = max(p_max, p(i, j));\n\t\t\tp_min = min(p_min, p(i, j));\n\t\t}\n\tcout << \"Max(p)=\" << p_max << \" Min(p)=\" << p_min << endl;\n\n\treturn iter_cnt > MAX_ITER_NUM || max(abs(d_max), abs(d_min)) < 1e-4;\n}\n\nvoid loop(void)\n{\n\tbool converged = false;\n\twhile (!converged)\n\t{\n\t\t++iter_cnt;\n\t\tcout << \"Iter\" << iter_cnt << \":\" << endl;\n\n\t\tSIMPLER();\n\t\tt += dt;\n\n\t\toutput1();\n\t\toutput2(iter_cnt);\n\n\t\tconverged = check_convergence();\n\t}\n}\n\nint main(int argc, char *argv[])\n{\n\t// Initialize\n\tinit();\n\n\t// Output I.C.\n\toutput1();\n\toutput2(0);\n\n\t// Solve\n\tloop();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "0711d69018c9ad2fd00576850398e869c31aecdd", "size": 13262, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Couette/2D/SIMPLER/main.cc", "max_stars_repo_name": "cangyu/CFD-book-of-Anderson", "max_stars_repo_head_hexsha": "cd8bd49b5e169c360d789054abe58c7139a3a9e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-07-22T14:20:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T10:36:38.000Z", "max_issues_repo_path": "Couette/2D/SIMPLER/main.cc", "max_issues_repo_name": "cangyu/CFD-book-of-Anderson", "max_issues_repo_head_hexsha": "cd8bd49b5e169c360d789054abe58c7139a3a9e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Couette/2D/SIMPLER/main.cc", "max_forks_repo_name": "cangyu/CFD-book-of-Anderson", "max_forks_repo_head_hexsha": "cd8bd49b5e169c360d789054abe58c7139a3a9e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-04T06:54:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T06:54:56.000Z", "avg_line_length": 25.8015564202, "max_line_length": 145, "alphanum_fraction": 0.5200573066, "num_tokens": 5434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6431519430073939}}
{"text": "/*!=======================================================\n  |                                                     |\n  |                 test_tensor.cpp                     |\n  |                                                     |\n  -------------------------------------------------------\n  | The unit test file for tensor.h/cpp.                |\n  | This file tests the classes and functions defined   |\n  | in tensor.h/cpp.                                    |\n  |                                                     |\n  | Generated files:                                    |\n  |    Results.tex:  A LaTeX file which contains the    |\n  |                  results as they will be included   |\n  |                  in the generated report.           |\n  =======================================================\n  | Dependencies:                                       |\n  | Eigen: An implementation of various matrix          |\n  |        commands. The implementation of the data     |\n  |        matrix uses such a matrix.                   |\n  =======================================================*/\n  \n#include <functional>\n#include <iostream>\n#include <fstream>\n#include <numeric>\n#include <vector>\n#include <Eigen/Dense>\n#include <tensor.h>\n#include <ctime>\n\nint test_tensor_functionality(std::ofstream &results){\n    /*!====================================\n    |       test_tensor_functionality   |\n    =====================================\n    \n    A test of some of the basic tensor functionality. \n    This should show that tensors of different orders \n    can be generated and manipulated.*/\n\n    int  test_num        = 6;\n    std::vector<bool> test_results(test_num,false);\n    \n    //Define a test vector\n    std::vector< int > v_shape;                 //Vector shape vector\n    v_shape.resize(1);                          //Resizing the shape vector to have only one index\n    v_shape[0] = 6;                             //Setting the vector size\n    tensor::Tensor V(v_shape);                  //Form the vector\n    \n    Eigen::MatrixXd V_compare(6,1); //Initialize the comparison matrix\n    \n    V_compare << 1,2,3,4,5,6;  //Set the initial values\n    \n    double inc = 1; //Set an initial increment vector\n    \n    //!Compare expected storage pattern vs. actual for a vector\n    for(int i=0; i<v_shape[0]; i++){//Iterate through the vector setting the required values\n        V(i) = inc;                 //Set the i'th value of V equal to inc\n        inc++;                      //Increment inc\n    }\n    \n    test_results[0] = V_compare.isApprox(V.data); //Check the results of the test\n    \n    //!Setting index test for a vector\n    V_compare(3) = -1; //Set the 4th index value to -1\n    V(3)         = -1; //Do the same for the tensor\n    \n    test_results[1] = V_compare.isApprox(V.data); //Check the results of the test\n    \n    //Define a test matrix\n    std::vector < int > m_shape; //Matrix shape vector\n    m_shape.resize(2);           //Resizing the shape vector to having two indices\n    \n    m_shape[0] = 3;              //Create a 3x3 matrix\n    m_shape[1] = 3;\n    \n    tensor::Tensor M(m_shape);   //Initialize the matrix\n    \n    Eigen::MatrixXd M_compare(3,3); //Initialize the comparison matrix\n    M_compare << 1,2,3,4,5,6,7,8,9;  //Set the initial values\n    \n    \n    //!Compare expected storage pattern to actual for a 2nd order tensor\n    inc = 1; //Set an initial increment vector\n    \n    for(int i=0; i<m_shape[0]; i++){\n        for(int j=0; j<m_shape[1]; j++){\n            M(i,j) = inc;\n            inc++;\n        }\n    }\n    \n    test_results[2] =  M_compare.isApprox(M.data); //Check the results of the test\n    \n    //!Setting index test for a 2nd order tensor\n    M_compare(2,1) = -8;\n    M(2,1)         = -8;\n    \n    test_results[3] =  M_compare.isApprox(M.data); //Check the results of the test\n    \n    //Define a test 3rd order tensor\n    std::vector < int > t_shape;                //Initialize the the tensor shape vector\n    t_shape.resize(3);                          //Resize the shape vector of the tensor\n    \n    t_shape[0] = 4;                             //Initialize the tensor size\n    t_shape[1] = 3;\n    t_shape[2] = 7;\n    \n    tensor::Tensor T(t_shape);                  //Initialize the tensor\n    \n    Eigen::MatrixXd T_compare(4,21); //Initialize the comparison tensor\n    T_compare <<  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,\n                 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,\n                 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,\n                 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84;\n    \n    //!Compare expected storage pattern to actual for a 3rd order tensor\n    inc = 1; //Set an initial increment vector\n    \n    for(int i=0; i<t_shape[0]; i++){\n        for(int j=0; j<t_shape[1]; j++){\n            for(int k=0; k<t_shape[2]; k++){\n                T(i,j,k) = inc;\n                inc++;\n            }\n        }\n    }\n    \n    test_results[4] =  T_compare.isApprox(T.data); //Check the results of the test\n    \n    //!Setting index test for a 3nd order tensor\n    T_compare(2,13) = -8;\n    T(2,1,6)        = -8;\n    \n    test_results[5] =  T_compare.isApprox(T.data); //Check the results of the test\n    \n    //std::cout << \"\\nT_compare:\\n\" << T_compare << \"\\n\" << \"T:\\n\" << T.data << \"\\n\";\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_tensor_functionality & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_tensor_functionality & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n    return 1;\n    \n}\n\nint test_eye(std::ofstream &results){\n    /*!========================\n    |       test_eye       |\n    ========================\n    \n    A test of the generation of the second\n    order identity tensor. Note that with \n    different storage schemes this tensor \n    may not always be the same in terms of \n    the way it is stored.*/\n    \n    //Initialize the results\n    int  test_num        = 2;\n    std::vector<bool> test_results(test_num,false);\n    \n    //Compute the identity tensor\n    tensor::Tensor23 I = tensor::eye();\n    \n    //Define a test matrix\n    std::vector < int > m_shape; //Matrix shape vector\n    m_shape.resize(2);           //Resizing the shape vector to having two indices\n    \n    m_shape[0] = 3;              //Create a 3x3 tensor\n    m_shape[1] = 3;\n    \n    tensor::Tensor M = tensor::Tensor(m_shape); //Initialize the matrix\n    M.data << 1,2,3,4,5,6,7,8,9;  //Set the initial values\n    \n    //!Run multiplication tests\n    tensor::Tensor R1 = tensor::Tensor(m_shape); //Initialize the first results matrix\n    tensor::Tensor R2 = tensor::Tensor(m_shape); //Initialize the second results matrix\n    for(int i=0; i<3; i++){\n        for(int j=0; j<3; j++){\n            for(int k=0; k<3; k++){\n                R1(i,j) += I(i,k)*M(k,j);\n                R2(i,j) += M(i,k)*I(k,j);\n            }\n        }\n    }\n    \n    //Check the results of the tests\n    test_results[0] = R1.data.isApprox(M.data);\n    test_results[1] = R2.data.isApprox(M.data);\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_eye & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_eye & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n}\n\nint test_FOT_eye(std::ofstream &results){\n    /*!========================\n    |     test_FOT_eye     |\n    ========================\n    \n    A test of the generation of the fourth\n    order identity tensor. Note that with \n    different storage schemes this tensor \n    may not always be the same in terms of \n    the way it is stored.*/\n    \n    //Initialize the results\n    int  test_num        = 2;\n    std::vector<bool> test_results(test_num,false);\n    \n    //Compute the identity tensor\n    tensor::Tensor43 FOTI = tensor::FOT_eye();\n    \n    //Define a test matrix\n    std::vector < int > m_shape; //Matrix shape vector\n    m_shape.resize(4);           //Resizing the shape vector to having two indices\n    \n    m_shape[0] = 3;              //Create a 3x3x3x3 tensor\n    m_shape[1] = 3;\n    m_shape[2] = 3;\n    m_shape[3] = 3;\n    \n    tensor::Tensor FOT = tensor::Tensor(m_shape); //Initialize the matrix\n    FOT.data << 2,4,3,5,1,3,4,6,1,\n                4,5,2,7,2,5,3,5,7,\n                6,2,8,3,6,2,6,4,5,\n                7,2,9,1,5,3,7,3,5,\n                9,8,9,4,1,2,4,3,5,\n                4,2,5,6,2,7,4,5,3,\n                6,6,5,2,4,1,5,4,8,\n                9,1,3,2,2,4,5,6,7,\n                5,2,1,2,1,1,4,5,6;\n    \n    //!Run multiplication tests\n    tensor::Tensor R1 = tensor::Tensor(m_shape); //Initialize the first results matrix\n    tensor::Tensor R2 = tensor::Tensor(m_shape); //Initialize the second results matrix\n    for(int i=0; i<3; i++){\n        for(int j=0; j<3; j++){\n            for(int k=0; k<3; k++){\n                for(int l=0; l<3; l++){\n                    for(int m=0; m<3; m++){\n                        for(int n=0; n<3; n++){\n                            R1(i,j,k,l) += FOTI(i,j,m,n)*FOT(m,n,k,l);\n                            R2(i,j,k,l) += FOT(i,j,m,n)*FOTI(m,n,k,l);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    //Check the results of the tests\n    test_results[0] = R1.data.isApprox(FOT.data);\n    test_results[1] = R2.data.isApprox(FOT.data);\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_FOT_eye & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_FOT_eye & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    \n}\n\nint test_inverse(std::ofstream &results){\n    /*!========================\n    |     test_inverse     |\n    ========================\n    \n    A test of the inverse of the tensor computation. \n    Several different tensor formulations are compared \n    and examined to make sure that the product of the \n    inverse and the original tensor is the identity \n    tensor.*/\n    \n    int  test_num               = 2;\n    std::vector<bool> test_results(test_num,false);\n    \n    /*!Test the inverse of a second order tensor*/\n    std::vector< int > m_shape; //Initialize the shape vector\n    m_shape.resize(2);          //Resize the shape vector to a second order tensor\n    \n    m_shape[0] = 3;             //Set the tensor dimensions\n    m_shape[1] = 3;\n    \n    tensor::Tensor T = tensor::Tensor(m_shape); //Initialize and populate the tensor\n    T.data << 2,4,3,5,1,3,4,6,1;\n    \n    tensor::Tensor Tinv = T.inverse(); //Invert the tensor\n    \n    tensor::Tensor product = tensor::Tensor(m_shape); //Compute the product of the tensor and its inverse\n    \n    for(int i=0; i<3; i++){\n        for(int j=0; j<3; j++){\n            for(int k=0; k<3; k++){\n                product(i,j) += T(i,k)*Tinv(k,j);\n            }\n        }\n    }\n    \n    tensor::Tensor23 I = tensor::eye(); //Get the second order identity tensor\n    \n    test_results[0] = I.data.isApprox(product.data);\n    \n    /*!Test the inverse of a fourth order tensor*/\n    std::vector< int > fot_shape; //Initialize the shape vector\n    fot_shape.resize(4);          //Resize the shape vector to a fourth order tensor\n    \n    fot_shape[0] = 3;             //Set the tensor dimensions\n    fot_shape[1] = 3;\n    fot_shape[2] = 3;\n    fot_shape[3] = 3;\n    \n    tensor::Tensor FOT = tensor::Tensor(fot_shape); //Initialize and populate the tensor\n    \n    FOT.data << 2,4,3,5,1,3,4,6,1,\n                4,5,2,7,2,5,3,5,7,\n                6,2,8,3,6,2,6,4,5,\n                7,2,9,1,5,3,7,3,5,\n                9,8,9,4,1,2,4,3,5,\n                4,2,5,6,2,7,4,5,3,\n                6,6,5,2,4,1,5,4,8,\n                9,1,3,2,2,4,5,6,7,\n                5,2,1,2,1,1,4,5,6;\n    \n    tensor::Tensor FOTinv = FOT.inverse(); //Invert the tensor\n    \n    tensor::Tensor productFOT = tensor::Tensor(fot_shape); //Compute the product of the tensor and its inverse\n    \n    for(int i=0; i<3; i++){\n        for(int j=0; j<3; j++){\n            for(int k=0; k<3; k++){\n                for(int l=0; l<3; l++){\n                    for(int m=0; m<3; m++){\n                        for(int n=0; n<3; n++){\n                            productFOT(i,j,k,l) += FOT(i,j,m,n)*FOTinv(m,n,k,l);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    tensor::Tensor43 FOTI = tensor::FOT_eye();\n    test_results[1] = FOTI.data.isApprox(productFOT.data);\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_inverse & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_inverse & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    return 1;\n}\n\nint test_det(std::ofstream &results){\n    /*!========================\n    |       test_det       |\n    ========================\n    \n    A test of the determinant of the tensor computation. \n    Tensors with known determinants are compared to \n    those computed.*/\n    \n    int  test_num               = 2;\n    std::vector<bool> test_results(test_num,false);\n    \n    /*!Test the determinant of a second order tensor*/\n    std::vector< int > m_shape; //Initialize the shape vector\n    m_shape.resize(2);          //Resize the shape vector to a second order tensor\n    \n    m_shape[0] = 3;             //Set the tensor dimensions\n    m_shape[1] = 3;\n    \n    tensor::Tensor T = tensor::Tensor(m_shape); //Initialize and populate the tensor\n    T.data << 2,4,3,5,1,3,4,6,1;\n    \n    double Tdet = T.det(); //Compute the determinant\n    \n    if(fabs(Tdet-72.)<1e-6){test_results[0] = true;}\n    \n    /*!Test the determinant of a fourth order tensor*/\n    std::vector< int > fot_shape; //Initialize the shape vector\n    fot_shape.resize(4);          //Resize the shape vector to a fourth order tensor\n    \n    fot_shape[0] = 3;             //Set the tensor dimensions\n    fot_shape[1] = 3;\n    fot_shape[2] = 3;\n    fot_shape[3] = 3;\n    \n    tensor::Tensor FOT = tensor::Tensor(fot_shape); //Initialize and populate the tensor\n    \n    FOT.data << 2,4,3,5,1,3,4,6,1,\n                4,5,2,7,2,5,3,5,7,\n                6,2,8,3,6,2,6,4,5,\n                7,2,9,1,5,3,7,3,5,\n                9,8,9,4,1,2,4,3,5,\n                4,2,5,6,2,7,4,5,3,\n                6,6,5,2,4,1,5,4,8,\n                9,1,3,2,2,4,5,6,7,\n                5,2,1,2,1,1,4,5,6;\n    \n    double FOTdet = FOT.det(); //Compute the determinant\n    \n    tensor::Tensor productFOT = tensor::Tensor(fot_shape); //Compute the product of the tensor and its inverse\n    \n    if(fabs(FOTdet-226209.)<1e-6){test_results[1] = true;}\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_inverse & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_inverse & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    return 1;\n}\n\nint test_operators(std::ofstream &results){\n    /*!==============================\n    |       test_operators       |\n    ==============================\n    \n    A test of the operators on the tensor \n    object. These include, addition, subtraction, \n    +=, and -=*/\n    \n    //Define a test matrix\n    std::vector < int > m_shape1; //Matrix shape vector\n    m_shape1.resize(2);           //Resizing the shape vector to having two indices\n    \n    m_shape1[0] = 3;              //Create a 3x3 tensor\n    m_shape1[1] = 3;\n    \n    tensor::Tensor M1 = tensor::Tensor(m_shape1); //Initialize the matrix\n    M1.data << 1,2,3,4,5,6,7,8,9;  //Set the initial values\n    \n    //Define a second test matrix\n    std::vector < int > m2_shape; //Matrix shape vector\n    m2_shape.resize(2);           //Resizing the shape vector to having two indices\n    \n    m2_shape[0] = 3;              //Create a 3x3 tensor\n    m2_shape[1] = 3;\n    \n    tensor::Tensor M2 = tensor::Tensor(m2_shape); //Initialize the matrix\n    M2.data << 6,2,2,7,2,1,3,9,0;  //Set the initial values\n    \n    //Compute the values\n    tensor::Tensor Tsum =  M1+M2;\n    tensor::Tensor Tsub =  M1-M2;\n    tensor::Tensor Tneg = -M1;\n    M1 += M2;\n    M2 -= M2;\n    \n    //Set the answers\n    Eigen::MatrixXd MA1 = Eigen::MatrixXd(3,3);\n    MA1 << 1+6,2+2,3+2,4+7,5+2,6+1,7+3,8+9,9+0;\n    Eigen::MatrixXd MA2 = Eigen::MatrixXd(3,3);\n    MA2 << 1-6,2-2,3-2,4-7,5-2,6-1,7-3,8-9,9-0;\n    Eigen::MatrixXd MA3 = Eigen::MatrixXd(3,3);\n    MA3 << -1,-2,-3,-4,-5,-6,-7,-8,-9;\n    Eigen::MatrixXd MA4 = Eigen::MatrixXd(3,3);\n    MA4 << 1+6,2+2,3+2,4+7,5+2,6+1,7+3,8+9,9+0;\n    Eigen::MatrixXd MA5 = Eigen::MatrixXd::Zero(3,3);\n    \n    //Compare the results to the solutions\n    int test_num = 5;\n    std::vector<bool> test_results = {false,false,false,false,false};\n    \n    test_results[0] = MA1.isApprox(Tsum.data);\n    test_results[1] = MA2.isApprox(Tsub.data);\n    test_results[2] = MA3.isApprox(Tneg.data);\n    test_results[3] = MA4.isApprox(M1.data);\n    test_results[4] = MA5.isApprox(M2.data);\n    \n    //Compare all test results\n    bool tot_result = true;\n    for(int i = 0; i<test_num; i++){\n        //std::cout << \"\\nSub-test \" << i+1 << \" result: \" << test_results[i] << \"\\n\";\n        if(!test_results[i]){\n            tot_result = false;\n        }\n    }\n    \n    if(tot_result){\n        results << \"test_inverse & True\\\\\\\\\\n\\\\hline\\n\";\n    }\n    else{\n        results << \"test_inverse & False\\\\\\\\\\n\\\\hline\\n\";\n    }\n    return 1;\n}\n\nint main(){\n    /*!==========================\n    |         main            |\n    ===========================\n    \n    The main loop which runs the tests defined in the \n    accompanying functions. Each function should output\n    the function name followed by & followed by True or \n    False if the test passes or fails respectively.*/\n    \n    std::ofstream results;\n    //Open the results file\n    results.open (\"results.tex\");\n        \n    //!Run the test functions\n    test_tensor_functionality(results);\n    test_inverse(results);\n    test_eye(results);\n    test_FOT_eye(results);\n    test_det(results);\n    test_operators(results);\n    \n    //Close the results file\n    results.close();\n}\n\n", "meta": {"hexsha": "c7cb1225ac30a37ac3dd35fbe0a6cb4415dd976b", "size": 19118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/tests/tensor/test_tensor.cpp", "max_stars_repo_name": "lanl/tardigrade-micromorphic-element", "max_stars_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/tests/tensor/test_tensor.cpp", "max_issues_repo_name": "lanl/tardigrade-micromorphic-element", "max_issues_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/tests/tensor/test_tensor.cpp", "max_forks_repo_name": "lanl/tardigrade-micromorphic-element", "max_forks_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6584507042, "max_line_length": 110, "alphanum_fraction": 0.5076890888, "num_tokens": 5537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272544, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6431519411474294}}
{"text": "#include \"sine_series.h\"\n#include <Eigen/Dense>\n#include <benchmark/benchmark.h>\n#include <cmath>\n\nusing Scalar = double;\nconstexpr Scalar angle = 1.2345;\n\nstatic void BM_Sine_Series_Naive(benchmark::State& state) {\n    // Perform setup here\n    for (auto _ : state) {\n        // This code gets timed\n        Eigen::Matrix<Scalar, 5, 1> sines;\n        generate_odd_sine_series_reference(5, angle, sines.data());\n        benchmark::DoNotOptimize(sines.sum());\n    }\n}\nBENCHMARK(BM_Sine_Series_Naive);\n\nstatic void BM_Sine_Series_Custom(benchmark::State& state) {\n    // Perform setup here\n    for (auto _ : state) {\n        // This code gets timed\n        Eigen::Matrix<Scalar, 5, 1> sines;\n        generate_odd_sine_series(5, angle, sines.data());\n        benchmark::DoNotOptimize(sines.sum());\n    }\n}\nBENCHMARK(BM_Sine_Series_Custom);\n\n// Run the benchmark\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "50f5f08e66b36a5774fe3e92acfd66cf39e5744b", "size": 877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/sine_series_benchmark.cpp", "max_stars_repo_name": "mark-berobot/motor_sim", "max_stars_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T00:20:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T01:33:11.000Z", "max_issues_repo_path": "util/sine_series_benchmark.cpp", "max_issues_repo_name": "INKSureIT/motor_sim", "max_issues_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/sine_series_benchmark.cpp", "max_forks_repo_name": "INKSureIT/motor_sim", "max_forks_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T01:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T13:35:23.000Z", "avg_line_length": 26.5757575758, "max_line_length": 67, "alphanum_fraction": 0.6738882554, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6431519392874645}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include \"mtao/iterator/enumerate.hpp\"\n\nnamespace mtao::eigen {\n    //Packs a ColVector type matrix V and writes it to a new matrix according to an indexer indices\n    template <typename Derived>\n        auto index_packer(const Eigen::EigenBase<Derived>& V, const std::vector<int>& indices) {\n            Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, Eigen::Dynamic> R(V.rows(), indices.size());\n            for(auto&& [i,v]: indices) {\n                R.col(i) = V.col(v);\n            }\n            return R;\n        }\n    //Packs a ColVector type matrix V and writes it to a new matrix according to an indexer indices\n    template <typename Derived, int D>\n        auto index_packer(const Eigen::EigenBase<Derived>& V, const std::array<int,D>& indices) {\n            Eigen::Matrix<typename Derived::Scalar, Derived::RowsAtCompileTime, D> R(V.rows(), indices.size());\n            for(auto&& [i,v]: indices) {\n                R.col(i) = V.col(v);\n            }\n            return R;\n        }\n}\n", "meta": {"hexsha": "779ba555dd411804917377e63423a6925706f9ca", "size": 1053, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/eigen/index_packer.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/eigen/index_packer.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/eigen/index_packer.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.12, "max_line_length": 124, "alphanum_fraction": 0.6049382716, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6431519392874645}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2020 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"weighted_alpha_complex\"\n#include <boost/test/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <CGAL/Epeck_d.h>\n\n#include <vector>\n#include <random>\n#include <array>\n#include <cmath> // for std::fabs\n\n#include <gudhi/Alpha_complex.h>\n#include <gudhi/Alpha_complex_3d.h>\n#include <gudhi/Simplex_tree.h>\n\nBOOST_AUTO_TEST_CASE(Weighted_alpha_complex_3d_comparison) {\n  // check that for random weighted 3d points in safe mode the 3D and dD codes give the same result with some tolerance\n\n  // Random points construction\n  using Kernel_dD = CGAL::Epeck_d< CGAL::Dimension_tag<3> >;\n  using Bare_point_d = typename Kernel_dD::Point_d;\n  using Weighted_point_d = typename Kernel_dD::Weighted_point_d;\n  std::vector<Weighted_point_d> w_points_d;\n\n  using Exact_weighted_alpha_complex_3d =\n    Gudhi::alpha_complex::Alpha_complex_3d<Gudhi::alpha_complex::complexity::EXACT, true, false>;\n  using Bare_point_3 = typename Exact_weighted_alpha_complex_3d::Bare_point_3;\n  using Weighted_point_3 = typename Exact_weighted_alpha_complex_3d::Weighted_point_3;\n  std::vector<Weighted_point_3> w_points_3;\n\n  std::uniform_real_distribution<double> rd_pts(-10., 10.);\n  std::uniform_real_distribution<double> rd_wghts(-0.5, 0.5);\n  std::random_device rand_dev;\n  std::mt19937 rand_engine(rand_dev());\n  for (int idx = 0; idx < 20; idx++) {\n    std::vector<double> point {rd_pts(rand_engine), rd_pts(rand_engine), rd_pts(rand_engine)};\n    double weight = rd_wghts(rand_engine);\n    w_points_d.emplace_back(Bare_point_d(point.begin(), point.end()), weight);\n    w_points_3.emplace_back(Bare_point_3(point[0], point[1], point[2]), weight);\n  }\n\n  // Structures necessary for comparison\n  using Points = std::vector<std::array<double,3>>;\n  using Points_and_filtrations = std::map<Points, double>;\n  Points_and_filtrations pts_fltr_dD;\n  Points_and_filtrations pts_fltr_3d;\n\n  // Weighted alpha complex for dD version\n  Gudhi::alpha_complex::Alpha_complex<Kernel_dD, true> alpha_complex_dD_from_weighted_points(w_points_d);\n  Gudhi::Simplex_tree<> w_simplex_d;\n  BOOST_CHECK(alpha_complex_dD_from_weighted_points.create_complex(w_simplex_d));\n\n  std::clog << \"Iterator on weighted alpha complex dD simplices in the filtration order, with [filtration value]:\"\n            << std::endl;\n  for (auto f_simplex : w_simplex_d.filtration_simplex_range()) {\n    Points points;\n    for (auto vertex : w_simplex_d.simplex_vertex_range(f_simplex)) {\n      CGAL::NT_converter<Kernel_dD::RT, double> cgal_converter;\n      Bare_point_d pt = alpha_complex_dD_from_weighted_points.get_point(vertex).point();\n      points.push_back({cgal_converter(pt[0]), cgal_converter(pt[1]), cgal_converter(pt[2])});\n    }\n    std::clog << \"   ( \";\n    std::sort (points.begin(), points.end());\n    for (auto point : points) {\n      std::clog << point[0] << \" \" << point[1] << \" \" << point[2] << \" | \";\n    }\n    std::clog << \") -> \" << \"[\" << w_simplex_d.filtration(f_simplex) << \"] \";\n    std::clog << std::endl;\n    pts_fltr_dD[points] = w_simplex_d.filtration(f_simplex);\n  }\n\n  // Weighted alpha complex for 3D version\n  Exact_weighted_alpha_complex_3d alpha_complex_3D_from_weighted_points(w_points_3);\n  Gudhi::Simplex_tree<> w_simplex_3;\n  BOOST_CHECK(alpha_complex_3D_from_weighted_points.create_complex(w_simplex_3));\n\n  std::clog << \"Iterator on weighted alpha complex 3D simplices in the filtration order, with [filtration value]:\"\n            << std::endl;\n  for (auto f_simplex : w_simplex_3.filtration_simplex_range()) {\n    Points points;\n    for (auto vertex : w_simplex_3.simplex_vertex_range(f_simplex)) {\n      Bare_point_3 pt = alpha_complex_3D_from_weighted_points.get_point(vertex).point();\n      CGAL::NT_converter<Exact_weighted_alpha_complex_3d::Kernel::RT, double> cgal_converter;\n      points.push_back({cgal_converter(pt[0]), cgal_converter(pt[1]), cgal_converter(pt[2])});\n    }\n    std::clog << \"   ( \";\n    std::sort (points.begin(), points.end());\n    for (auto point : points) {\n      std::clog << point[0] << \" \" << point[1] << \" \" << point[2] << \" | \";\n    }\n    std::clog << \") -> \" << \"[\" << w_simplex_3.filtration(f_simplex) << \"] \" << std::endl;\n    pts_fltr_3d[points] = w_simplex_d.filtration(f_simplex);\n  }\n\n  // Compares structures\n  auto d3_itr = pts_fltr_3d.begin();\n  auto dD_itr = pts_fltr_dD.begin();\n  for (; d3_itr != pts_fltr_3d.end() && dD_itr != pts_fltr_dD.end(); ++d3_itr) {\n    if (d3_itr->first != dD_itr->first) {\n      for(auto point : d3_itr->first)\n        std::clog << point[0] << \" \" << point[1] << \" \" << point[2] << \" | \";\n      std::clog << \" versus \";\n      for(auto point : dD_itr->first)\n        std::clog << point[0] << \" \" << point[1] << \" \" << point[2] << \" | \";\n      std::clog << std::endl;\n      BOOST_CHECK(false);\n    }\n    // In safe mode, relative error is less than 1e-5 (can be changed with set_relative_precision_of_to_double)\n    if (std::fabs(d3_itr->second - dD_itr->second) > 1e-5 * (std::fabs(d3_itr->second) + std::fabs(dD_itr->second))) {\n      std::clog << d3_itr->second << \" versus \" << dD_itr->second << \" diff \"\n                << std::fabs(d3_itr->second - dD_itr->second) << std::endl;\n      BOOST_CHECK(false);\n    }\n    ++dD_itr;\n  }\n}", "meta": {"hexsha": "875704ee73ddf79b2ed8f4e40c1fc2b0f279bef2", "size": 5603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Alpha_complex/test/Weighted_alpha_complex_unit_test.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Alpha_complex/test/Weighted_alpha_complex_unit_test.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Alpha_complex/test/Weighted_alpha_complex_unit_test.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 44.1181102362, "max_line_length": 119, "alphanum_fraction": 0.6858825629, "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6431519336120985}}
{"text": "#include <bits/stdc++.h>\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nnamespace GaussianElimination\n{\n    ///------------------------------------------------------------\n    constexpr int MAX_EQ = 500;\n    constexpr int MAX_VAR = 500;\n\n    using T = boost::multiprecision::cpp_int;\n\n    rational<T> A[MAX_EQ + 1][MAX_VAR + 1];\n    rational<T> B[MAX_EQ + 1][MAX_VAR + 1];\n\n    rational<T> solutions[MAX_VAR + 1];\n\n    int N, M;\n    ///------------------------------------------------------------\n\n    ///------------------------------------------------------------\n    void clear()\n    {\n        for (int i = 0; i <= MAX_EQ; ++i)\n            for (int j = 0; j <= MAX_VAR; ++j)\n                A[i][j] = B[i][j] = 0;\n\n        for (int j = 0; j <= MAX_VAR; ++j)\n            solutions[j] = 0;\n    }\n\n    void makeIdentity()\n    {\n        for (int i = 1; i <= N; ++i)\n            B[i][i] = 1;\n    }\n\n    bool checkIfInvertible()\n    {\n        assert(N == M);\n\n        for (int i = 1; i <= N; ++i)\n            if (A[i][i] != 1)\n                return false;\n\n        return true;\n    }\n    ///------------------------------------------------------------\n\n    ///------------------------------------------------------------\n    void swapLines(int x, int y) /// swap(X, Y)\n    {\n        swap(A[x], A[y]);\n        swap(B[x], B[y]);\n\n        cerr << \"SWAP LINES : \" << x << \" \" << y << endl;\n    }\n\n    void divideLine(int line, rational<T> rat) /// X = X / rat\n    {\n        assert(rat != 0);\n\n        for (int j = 1; j <= M; ++j)\n            A[line][j] /= rat;\n\n        for (int j = 1; j <= M; ++j)\n            B[line][j] /= rat;\n\n        cerr << \"DIVIDE LINE_\" << line << \" BY \" << rat << endl;\n    }\n\n    void changeLines(int x, int y, rational<T> rat) /// X = X - rat * Y\n    {\n        for (int i = 1; i <= M; ++i)\n            A[x][i] -= rat * A[y][i];\n\n        for (int i = 1; i <= M; ++i)\n            B[x][i] -= rat * B[y][i];\n\n        cerr << \"ADD TO LINE_\" << x << \" => LINE_\" << y << \" x \" << -rat << endl;\n    }\n    ///------------------------------------------------------------\n\n    void rowEchelonForm()\n    {\n        cerr << \"START ROW ECHELON\" << endl;\n\n        int i = 1, j = 1;\n\n        while (i <= N && j <= M)\n        {\n            int k = i;\n\n            while (k <= N && A[k][j] == 0)\n                k++;\n\n            if (k == N + 1)\n            {\n                j++;\n                continue;\n            }\n\n            if (k != i)\n                swapLines(k, i);\n\n            assert(A[i][j] != 0);\n            divideLine(i, A[i][j]);\n\n            for (int l = i + 1; l <= N; ++l)\n                changeLines(l, i, A[l][j]);\n\n            i++;\n            j++;\n        }\n\n        cerr << \"FINISH ROW ECHELON\" << endl << endl;\n    }\n\n    void reducedRowEchelonForm()\n    {\n        cerr << \"START REDUCED ROW ECHELON\" << endl;\n\n        for (int i = N; i >= 1; i--)\n        {\n            int j = 1;\n\n            while (j <= M && A[i][j] == 0)\n                j++;\n\n            if (j <= M)\n            {\n                for (int k = i - 1; k >= 1; k--)\n                    changeLines(k, i, A[k][j]);\n            }\n        }\n\n        cerr << \"FINISH REDUCED ROW ECHELON\" << endl << endl;\n    }\n\n    vector<vector<double>> getInverse(const vector<vector<int>> &coef, ostream &out = cout)\n    {\n        assert(coef.size() >= 1);\n        assert(coef[0].size() >= 1);\n\n        GaussianElimination::N = coef.size();\n        GaussianElimination::M = coef[0].size();\n\n        if (N != M)\n        {\n            out << \"Matrix not invertible : N != M (non-square)\\n\";\n            return {};\n        }\n\n        clear();\n\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < M; ++j)\n                A[i + 1][j + 1] = coef[i][j];\n\n        makeIdentity();\n        rowEchelonForm();\n\n        if (checkIfInvertible() == false)\n        {\n            out << \"Matrix not invertible\\n\";\n            return {};\n        }\n\n        reducedRowEchelonForm();\n\n        vector<vector<double>> inverse(N + 2);\n\n        for (int i = 1; i <= N; ++i)\n        {\n            inverse[i - 1].resize(M + 1);\n\n            for (int j = 1; j <= M; ++j)\n            {\n                inverse[i - 1][j - 1] = boost::rational_cast<double>(B[i][j]);\n                out << B[i][j] << \" \";\n            }\n\n            out << endl;\n        }\n\n        return inverse;\n    }\n\n    vector<double> solveSystemEquations(const vector<vector<int>> &coef, const vector<int> &bs, ostream &out = cout)\n    {\n        assert(coef.size() >= 1);\n        assert(coef[0].size() >= 1);\n\n        GaussianElimination::N = coef.size();\n        GaussianElimination::M = coef[0].size();\n\n        assert(static_cast<int>(bs.size()) == GaussianElimination::N);\n\n        clear();\n\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < M; ++j)\n                A[i + 1][j + 1] = coef[i][j];\n\n        for (int i = 0; i < N; ++i)\n            B[i + 1][1] = bs[i];\n\n        rowEchelonForm();\n        reducedRowEchelonForm();\n\n        for (int i = N; i >= 1; i--)\n        {\n            int j = 1;\n\n            while (j <= M && A[i][j] == 0)\n                j++;\n\n            if (j == M + 1)\n            {\n                if (B[i][1] != 0)\n                {\n                    out << \"Impossible!\" << endl;\n                    return {};\n                }\n            }\n            else\n            {\n                solutions[i] = B[i][1];\n\n                for (int p = j + 1; p <= M; ++p)\n                    solutions[i] -= A[i][p] * solutions[p];\n            }\n        }\n\n        vector<double> solution(M);\n\n        for (int j = 0; j < M; ++j)\n            solution[j] = boost::rational_cast<double>(solutions[j + 1]);\n\n        for (int j = 1; j <= M; ++j)\n            out << solutions[j] << \" \";\n\n        out << endl;\n\n        return solution;\n    }\n}\n\nint main()\n{\n    ifstream in(\"data.in\");\n\n    assert(in.is_open());\n\n    vector<vector<int>> A;\n    int n, m;\n\n    in >> n >> m;\n    A.resize(n);\n    vector<int> bs(n);\n\n    for (int i = 0; i < n; ++i)\n    {\n        A[i].resize(m);\n\n        for (int j = 0; j < m; ++j)\n            in >> A[i][j];\n\n        in >> bs[i];\n    }\n\n    vector<double> xs = GaussianElimination::solveSystemEquations(A, bs);\n\n    return 0;\n}\n", "meta": {"hexsha": "cf439eb9d3c36d8dac0e9ccc16315f8f42f621af", "size": 6311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Number-Theory/Gaussian elimination (namespace).cpp", "max_stars_repo_name": "Fresher001/Competitive-Programming-2", "max_stars_repo_head_hexsha": "e1e953bb1d4ade46cc670b2d0432f68504538ed2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T23:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T21:57:34.000Z", "max_issues_repo_path": "Number-Theory/Gaussian elimination (namespace).cpp", "max_issues_repo_name": "Fresher001/Competitive-Programming-2", "max_issues_repo_head_hexsha": "e1e953bb1d4ade46cc670b2d0432f68504538ed2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-04-13T09:38:36.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-13T09:38:36.000Z", "max_forks_repo_path": "Number-Theory/Gaussian elimination (namespace).cpp", "max_forks_repo_name": "Fresher001/Competitive-Programming-2", "max_forks_repo_head_hexsha": "e1e953bb1d4ade46cc670b2d0432f68504538ed2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T07:25:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T12:13:50.000Z", "avg_line_length": 22.6200716846, "max_line_length": 116, "alphanum_fraction": 0.363175408, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6431082527936364}}
{"text": "#include \"MatrixMultiply.hpp\"\n\n\n#include <iostream>\n#include <exception>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <numeric>\n#include <stdlib.h>\n\n# define ROWMATRIXPOS(rowSize , row, col) (rowSize * row) + col\n# define COLMATRIXPOS(colSize , row, col) (colSize * col) + row\n\n\nscottgs::MatrixMultiply::MatrixMultiply()\n{\n\t;\n}\n\nscottgs::MatrixMultiply::~MatrixMultiply()\n{\n\t;\n}\n\n\nscottgs::FloatMatrix scottgs::MatrixMultiply::operator()(const scottgs::FloatMatrix& lhs, const scottgs::FloatMatrix& rhs) const\n{\n\t// Verify acceptable dimensions\n\tif (lhs.size2() != rhs.size1())\n\t\tthrow std::logic_error(\"matrix incompatible lhs.size2() != rhs.size1()\");\n\n\tscottgs::FloatMatrix result(lhs.size1(),rhs.size2());\n\n\tint lhsSize1 = lhs.size1();\n\tint lhsSize2 = lhs.size2();\n\tint rhsSize1 = rhs.size1();\n\tint rhsSize2 = rhs.size2();\n\tfloat sum = 0;\n\n\n\tconst float* lef = &lhs(0,0);\n\n\n\tfloat* right = new float[rhsSize1*rhsSize2];\n\tconst float * rightHolder = &rhs(0,0);\n\n\tfor(int i = 0; i < rhsSize1; i++){\n\t\tfor(int j = 0; j < rhsSize2; j++){\n\t\t\tright[COLMATRIXPOS(rhsSize1,i,j)] = rightHolder[ROWMATRIXPOS(rhsSize2,i,j)];\n\t\t}\n\t}\n\n\n\tfor(int i = 0; i < lhsSize1; i++){\n\t\tfor(int j = 0; j < rhsSize2; j++){\n\t\t\tsum = 0;\n\t\t\tfor(int k = 0; k < lhsSize2; k++){\n\n\t\t\t\tsum += lef[ROWMATRIXPOS(lhsSize2,i,k)] * right[COLMATRIXPOS(rhsSize1,k,j)];\n\t\t\t}\n\n\t\t\tresult(i,j) = sum;\n\n\t\t}\n\t}\n\n\n\tdelete[] right;\n\n\treturn result;\n}\n\nscottgs::FloatMatrix scottgs::MatrixMultiply::multiply(const scottgs::FloatMatrix& lhs, const scottgs::FloatMatrix& rhs) const\n{\n\t// Verify acceptable dimensions\n\tif (lhs.size2() != rhs.size1())\n\t\tthrow std::logic_error(\"matrix incompatible lhs.size2() != rhs.size1()\");\n\n\treturn boost::numeric::ublas::prod(lhs,rhs);\n}\n\n", "meta": {"hexsha": "e148dfcca38597e221c5967473d931d41f183c3e", "size": 1781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Matrix-Multiplication-Speedup/src/MatrixMultiply.cpp", "max_stars_repo_name": "samkreter/High-Performance-Computing", "max_stars_repo_head_hexsha": "cb8c944fa0ed39aaea41ee4ecb202dd2c18a52a2", "max_stars_repo_licenses": ["MIT"], "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-Multiplication-Speedup/src/MatrixMultiply.cpp", "max_issues_repo_name": "samkreter/High-Performance-Computing", "max_issues_repo_head_hexsha": "cb8c944fa0ed39aaea41ee4ecb202dd2c18a52a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Matrix-Multiplication-Speedup/src/MatrixMultiply.cpp", "max_forks_repo_name": "samkreter/High-Performance-Computing", "max_forks_repo_head_hexsha": "cb8c944fa0ed39aaea41ee4ecb202dd2c18a52a2", "max_forks_repo_licenses": ["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.7195121951, "max_line_length": 128, "alphanum_fraction": 0.6704098821, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6431082463080862}}
{"text": "#include \"Gaussian.h\"\n#include <boost/math/distributions/normal.hpp>\n\nBaseDistributionGaussian::BaseDistributionGaussian(const Options& iOptions, const Data& iData) : BaseDistribution(iOptions, iData) {\n\n}\nfloat BaseDistributionGaussian::getCdf(float iX, const std::vector<float>& iMoments) const {\n   assert(iMoments.size() == 2);\n   float mean     = iMoments[0];\n   float variance = iMoments[1];\n   if(variance == 0) {\n      return Global::MV;\n   }\n   boost::math::normal dist(mean, sqrt(variance));\n   return boost::math::cdf(dist, iX);\n}\nfloat BaseDistributionGaussian::getPdf(float iX, const std::vector<float>& iMoments) const {\n   assert(iMoments.size() == 2);\n   float mean     = iMoments[0];\n   float variance = iMoments[1];\n   if(variance == 0) {\n      return Global::MV;\n   }\n   boost::math::normal dist(mean, sqrt(variance));\n   return boost::math::pdf(dist, iX);\n}\nfloat BaseDistributionGaussian::getInv(float iCdf, const std::vector<float>& iMoments) const {\n   assert(iMoments.size() == 2);\n   float mean     = iMoments[0];\n   float variance = iMoments[1];\n   if(variance == 0) {\n      return Global::MV;\n   }\n   boost::math::normal dist(mean, sqrt(variance));\n   return boost::math::quantile(dist, iCdf);\n\n}\nint BaseDistributionGaussian::getNumMoments() const {\n   return 2;\n}\n", "meta": {"hexsha": "bff52fe8de9c1e56d00238de9e1498234f01cc33", "size": 1293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BaseDistributions/Gaussian.cpp", "max_stars_repo_name": "dsiuta/Comps", "max_stars_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BaseDistributions/Gaussian.cpp", "max_issues_repo_name": "dsiuta/Comps", "max_issues_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BaseDistributions/Gaussian.cpp", "max_forks_repo_name": "dsiuta/Comps", "max_forks_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5365853659, "max_line_length": 132, "alphanum_fraction": 0.6782675947, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6431082335998978}}
{"text": "/**\n * ravg.hpp\n *\n * 2021 Gabriel A. Moreira\n *\n * gmoreira at isr.tecnico.ulisboa.pt\n * https://github.com/gabmoreira/maks\n *\n * This software and the related documents  are provided as  is,  with no express\n * or implied  warranties,  other  than those  that are  expressly stated  in the\n * License.\n */\n\n#ifndef RAVG_HPP\n#define RAVG_HPP\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n\n/**\n * Cycle Solver in SO(3).\n *\n * Closed-form cycle graph rotation averaging solver in SO(3).\n *\n * @param pairwise (input) Eigen::MatrixXd - 3 x 3n Eigen matrix with SO(3) blocks.\n * @param num_nodes (input) int - number of variables.\n * @param R (output) Eigen::MatrixXd - 3n x 3 Eigen matrix containing optimal solution.\n */\nvoid cycleSolverSO3(const Eigen::Ref<Eigen::MatrixXd> pairwise,\n                    int num_nodes,\n                    Eigen::Ref<Eigen::MatrixXd> R);\n\n\n/**\n * Rotation averaging Primal-Dual method in SO(3).\n *\n * Primal-dual update method for averaging rotations in SO(3).\n *\n * @param Rtilde (input) Eigen::SparseMatrix<double> - 3n x 3n sparse rotation adjacency matrix.\n * @param R (output) Eigen::MatrixXd - 3n x 3 solution.\n * @param A (input/output) Eigen::SparseMatrix<double> - 3n x 3n symmetric and sparse graph adjacency matrix.\n * @param num_nodes (input) Int - number of variables.\n * @param maxiter (input) int - maxiter.\n * @param dual (output) Double - dual problem.\n * @param eta (input) Double - minimum eigenvalue stopping criterion.\n * @param sigma (input) Double - spectral shift.\n */\nvoid primalDualSO3(const Eigen::SparseMatrix<double>& Rtilde,\n                   const Eigen::SparseMatrix<double>& A,\n                   Eigen::Ref<Eigen::MatrixXd> R,\n                   int num_nodes,\n                   int maxiter,\n                   double& dual,\n                   double eta,\n                   double sigma);\n\n\n#endif /* RAVG_HPP */\n", "meta": {"hexsha": "8cf2028e3442801b73f17b2b11344e545a6badd6", "size": 1886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ravg.hpp", "max_stars_repo_name": "rjanvier/maks", "max_stars_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2020-12-15T10:15:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:19:07.000Z", "max_issues_repo_path": "include/ravg.hpp", "max_issues_repo_name": "rjanvier/maks", "max_issues_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T12:24:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:47:43.000Z", "max_forks_repo_path": "include/ravg.hpp", "max_forks_repo_name": "rjanvier/maks", "max_forks_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-06T07:22:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T09:31:30.000Z", "avg_line_length": 31.4333333333, "max_line_length": 109, "alphanum_fraction": 0.6463414634, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6430970099752449}}
{"text": "// MIT License\n//\n// Copyright (c) 2020 Lennart Braun\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include \"linear_algebra.h\"\n\n#include <cassert>\n\n#include <Eigen/Core>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n#include \"tensor/tensor_op.h\"\n\nnamespace MOTION {\n\ntemplate <typename T>\nvoid matrix_multiply(std::size_t dim_l, std::size_t dim_m, std::size_t dim_n, const T* A,\n                     const T* B, T* output) {\n  using MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n  Eigen::Map<MatrixType> matrix_output(output, dim_l, dim_n);\n  Eigen::Map<const MatrixType> matrix_A(A, dim_l, dim_m);\n  Eigen::Map<const MatrixType> matrix_B(B, dim_m, dim_n);\n  matrix_output = matrix_A * matrix_B;\n}\n\ntemplate <typename T>\nstd::vector<T> matrix_multiply(std::size_t dim_l, std::size_t dim_m, std::size_t dim_n,\n                               const std::vector<T>& A, const std::vector<T>& B) {\n  assert(A.size() == dim_l * dim_m);\n  assert(B.size() == dim_m * dim_n);\n  std::vector<T> output(dim_l * dim_n);\n  matrix_multiply(dim_l, dim_m, dim_n, A.data(), B.data(), output.data());\n  return output;\n}\n\ntemplate <typename T>\nvoid matrix_multiply(const tensor::GemmOp& gemm_op, const T* A, const T* B, T* output) {\n  using MatrixType = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n  assert(gemm_op.verify());\n  Eigen::Map<MatrixType> matrix_output(output, gemm_op.output_shape_[0], gemm_op.output_shape_[1]);\n  Eigen::Map<const MatrixType> matrix_A(A, gemm_op.input_A_shape_[0], gemm_op.input_A_shape_[1]);\n  Eigen::Map<const MatrixType> matrix_B(B, gemm_op.input_B_shape_[0], gemm_op.input_B_shape_[1]);\n\n  if (gemm_op.transA_ && gemm_op.transB_) {\n    matrix_output = matrix_A.transpose() * matrix_B.transpose();\n  } else if (gemm_op.transA_) {\n    matrix_output = matrix_A.transpose() * matrix_B;\n  } else if (gemm_op.transB_) {\n    matrix_output = matrix_A * matrix_B.transpose();\n  } else {\n    matrix_output = matrix_A * matrix_B;\n  }\n}\n\ntemplate void matrix_multiply(std::size_t, std::size_t, std::size_t, const std::uint8_t*,\n                              const std::uint8_t*, std::uint8_t*);\ntemplate void matrix_multiply(std::size_t, std::size_t, std::size_t, const std::uint16_t*,\n                              const std::uint16_t*, std::uint16_t*);\ntemplate void matrix_multiply(std::size_t, std::size_t, std::size_t, const std::uint32_t*,\n                              const std::uint32_t*, std::uint32_t*);\ntemplate void matrix_multiply(std::size_t, std::size_t, std::size_t, const std::uint64_t*,\n                              const std::uint64_t*, std::uint64_t*);\ntemplate std::vector<std::uint8_t> matrix_multiply(std::size_t, std::size_t, std::size_t,\n                                                   const std::vector<std::uint8_t>&,\n                                                   const std::vector<std::uint8_t>&);\ntemplate std::vector<std::uint16_t> matrix_multiply(std::size_t, std::size_t, std::size_t,\n                                                    const std::vector<std::uint16_t>&,\n                                                    const std::vector<std::uint16_t>&);\ntemplate std::vector<std::uint32_t> matrix_multiply(std::size_t, std::size_t, std::size_t,\n                                                    const std::vector<std::uint32_t>&,\n                                                    const std::vector<std::uint32_t>&);\ntemplate std::vector<std::uint64_t> matrix_multiply(std::size_t, std::size_t, std::size_t,\n                                                    const std::vector<std::uint64_t>&,\n                                                    const std::vector<std::uint64_t>&);\ntemplate std::vector<__uint128_t> matrix_multiply(std::size_t, std::size_t, std::size_t,\n                                                  const std::vector<__uint128_t>&,\n                                                  const std::vector<__uint128_t>&);\ntemplate void matrix_multiply(const tensor::GemmOp&, const std::uint8_t*, const std::uint8_t*,\n                              std::uint8_t*);\ntemplate void matrix_multiply(const tensor::GemmOp&, const std::uint16_t*, const std::uint16_t*,\n                              std::uint16_t*);\ntemplate void matrix_multiply(const tensor::GemmOp&, const std::uint32_t*, const std::uint32_t*,\n                              std::uint32_t*);\ntemplate void matrix_multiply(const tensor::GemmOp&, const std::uint64_t*, const std::uint64_t*,\n                              std::uint64_t*);\ntemplate void matrix_multiply(const tensor::GemmOp&, const __uint128_t*, const __uint128_t*,\n                              __uint128_t*);\n\ntemplate <typename T>\nvoid convolution(const tensor::Conv2DOp& conv_op, const T* input_buffer, const T* kernel_buffer,\n                 T* output_buffer) {\n  using TensorType3 = Eigen::Tensor<T, 3, Eigen::RowMajor>;\n  using CTensorType3 = Eigen::Tensor<const T, 3, Eigen::RowMajor>;\n  using CTensorType4 = Eigen::Tensor<const T, 4, Eigen::RowMajor>;\n  assert(conv_op.verify());\n  const auto& output_shape = conv_op.output_shape_;\n  const auto& input_shape = conv_op.input_shape_;\n  const auto& kernel_shape = conv_op.kernel_shape_;\n\n  Eigen::TensorMap<CTensorType3> input(input_buffer, input_shape[0], input_shape[1],\n                                       input_shape[2]);\n  Eigen::TensorMap<CTensorType4> kernel(kernel_buffer, kernel_shape[0], kernel_shape[1],\n                                        kernel_shape[2], kernel_shape[3]);\n  Eigen::TensorMap<TensorType3> output(output_buffer, output_shape[0], output_shape[1],\n                                       output_shape[2]);\n  const std::array<Eigen::Index, 2> kernel_matrix_dimensions = {\n      static_cast<Eigen::Index>(kernel_shape[1] * kernel_shape[2] * kernel_shape[3]),\n      static_cast<Eigen::Index>(kernel_shape[0])};\n  const std::array<Eigen::Index, 2> input_matrix_dimensions = {\n      static_cast<Eigen::Index>(output_shape[1] * output_shape[2]),\n      static_cast<Eigen::Index>(kernel_shape[1] * kernel_shape[2] * kernel_shape[3])};\n\n  auto kernel_matrix =\n      kernel.shuffle(std::array<int, 4>{3, 2, 1, 0}).reshape(kernel_matrix_dimensions);\n\n  auto input_matrix =\n      input.shuffle(Eigen::array<Eigen::Index, 3>{2, 1, 0})\n          .extract_image_patches(kernel_shape[2], kernel_shape[3], conv_op.strides_[0],\n                                 conv_op.strides_[1], conv_op.dilations_[0], conv_op.dilations_[1],\n                                 1, 1, conv_op.pads_[0], conv_op.pads_[2], conv_op.pads_[1],\n                                 conv_op.pads_[3], 0)\n          .reshape(input_matrix_dimensions);\n\n  const std::array<Eigen::IndexPair<Eigen::Index>, 1> contraction_dimensions = {\n      Eigen::IndexPair<Eigen::Index>(1, 0)};\n  auto output_matrix =\n      kernel_matrix.shuffle(std::array<Eigen::Index, 2>{1, 0})\n          .contract(input_matrix.shuffle(std::array<Eigen::Index, 2>{1, 0}), contraction_dimensions)\n          .shuffle(std::array<Eigen::Index, 2>{1, 0});\n\n  const std::array<Eigen::Index, 3> rev_output_dimensions = {\n      output.dimension(2), output.dimension(1), output.dimension(0)};\n  output =\n      output_matrix.reshape(rev_output_dimensions).shuffle(Eigen::array<Eigen::Index, 3>{2, 1, 0});\n}\n\ntemplate <typename T>\nstd::vector<T> convolution(const tensor::Conv2DOp& conv_op, const std::vector<T>& input_buffer,\n                           const std::vector<T>& kernel_buffer) {\n  assert(conv_op.verify());\n  assert(input_buffer.size() == conv_op.compute_input_size());\n  assert(kernel_buffer.size() == conv_op.compute_kernel_size());\n  std::vector<T> output_buffer(conv_op.compute_output_size());\n  convolution(conv_op, input_buffer.data(), kernel_buffer.data(), output_buffer.data());\n  return output_buffer;\n}\n\nvoid convolution(const tensor::Conv2DOp&, const std::uint8_t*, const std::uint8_t*, std::uint8_t*);\nvoid convolution(const tensor::Conv2DOp&, const std::uint16_t*, const std::uint16_t*,\n                 std::uint16_t*);\nvoid convolution(const tensor::Conv2DOp&, const std::uint32_t*, const std::uint32_t*,\n                 std::uint32_t*);\nvoid convolution(const tensor::Conv2DOp&, const std::uint64_t*, const std::uint64_t*,\n                 std::uint64_t*);\ntemplate std::vector<std::uint8_t> convolution(const tensor::Conv2DOp&,\n                                               const std::vector<std::uint8_t>&,\n                                               const std::vector<std::uint8_t>&);\ntemplate std::vector<std::uint16_t> convolution(const tensor::Conv2DOp&,\n                                                const std::vector<std::uint16_t>&,\n                                                const std::vector<std::uint16_t>&);\ntemplate std::vector<std::uint32_t> convolution(const tensor::Conv2DOp&,\n                                                const std::vector<std::uint32_t>&,\n                                                const std::vector<std::uint32_t>&);\ntemplate std::vector<std::uint64_t> convolution(const tensor::Conv2DOp&,\n                                                const std::vector<std::uint64_t>&,\n                                                const std::vector<std::uint64_t>&);\ntemplate std::vector<__uint128_t> convolution(const tensor::Conv2DOp&,\n                                              const std::vector<__uint128_t>&,\n                                              const std::vector<__uint128_t>&);\n\ntemplate <typename T>\nvoid sum_pool(const tensor::AveragePoolOp& avgpool_op, const T* input, T* output) {\n  assert(avgpool_op.verify());\n  using TensorType3C = Eigen::Tensor<const T, 3, Eigen::RowMajor>;\n  using TensorType3 = Eigen::Tensor<T, 3, Eigen::RowMajor>;\n  const auto in_channels = static_cast<Eigen::Index>(avgpool_op.input_shape_[0]);\n  const auto in_rows = static_cast<Eigen::Index>(avgpool_op.input_shape_[1]);\n  const auto in_columns = static_cast<Eigen::Index>(avgpool_op.input_shape_[2]);\n  const auto out_channels = static_cast<Eigen::Index>(avgpool_op.output_shape_[0]);\n  const auto out_rows = static_cast<Eigen::Index>(avgpool_op.output_shape_[1]);\n  const auto out_columns = static_cast<Eigen::Index>(avgpool_op.output_shape_[2]);\n  const auto kernel_rows = static_cast<Eigen::Index>(avgpool_op.kernel_shape_[0]);\n  const auto kernel_columns = static_cast<Eigen::Index>(avgpool_op.kernel_shape_[1]);\n  const auto stride_rows = static_cast<Eigen::Index>(avgpool_op.strides_[0]);\n  const auto stride_columns = static_cast<Eigen::Index>(avgpool_op.strides_[1]);\n\n  Eigen::TensorMap<TensorType3C> tensor_src(input, in_channels, in_rows, in_columns);\n  Eigen::TensorMap<TensorType3> tensor_dst(output, out_channels, out_rows, out_columns);\n\n  tensor_dst = tensor_src.shuffle(Eigen::array<Eigen::Index, 3>{2, 1, 0})\n                   .extract_image_patches(kernel_rows, kernel_columns, stride_rows, stride_columns,\n                                          1, 1, 1, 1, 0, 0, 0, 0, T(0))\n                   .sum(Eigen::array<Eigen::Index, 2>{1, 2})\n                   .reshape(Eigen::array<Eigen::Index, 3>{out_columns, out_rows, out_channels})\n                   .shuffle(Eigen::array<Eigen::Index, 3>{2, 1, 0});\n}\n\ntemplate void sum_pool(const tensor::AveragePoolOp&, const std::uint8_t*, std::uint8_t*);\ntemplate void sum_pool(const tensor::AveragePoolOp&, const std::uint16_t*, std::uint16_t*);\ntemplate void sum_pool(const tensor::AveragePoolOp&, const std::uint32_t*, std::uint32_t*);\ntemplate void sum_pool(const tensor::AveragePoolOp&, const std::uint64_t*, std::uint64_t*);\ntemplate void sum_pool(const tensor::AveragePoolOp&, const __uint128_t*, __uint128_t*);\n\n}  // namespace MOTION\n", "meta": {"hexsha": "a1563aafabd8e35ef9f3ca510d90fece6389e2c7", "size": 12659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/motioncore/utility/linear_algebra.cpp", "max_stars_repo_name": "Udbhavbisarya23/MOTION2NX", "max_stars_repo_head_hexsha": "eb26f639d8c1729cebfa85dd3bf41b770cebe92b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T00:39:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T16:42:55.000Z", "max_issues_repo_path": "src/motioncore/utility/linear_algebra.cpp", "max_issues_repo_name": "Udbhavbisarya23/MOTION2NX", "max_issues_repo_head_hexsha": "eb26f639d8c1729cebfa85dd3bf41b770cebe92b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-11-07T06:53:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T11:46:40.000Z", "max_forks_repo_path": "src/motioncore/utility/linear_algebra.cpp", "max_forks_repo_name": "Udbhavbisarya23/MOTION2NX", "max_forks_repo_head_hexsha": "eb26f639d8c1729cebfa85dd3bf41b770cebe92b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-11-04T12:01:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T12:15:23.000Z", "avg_line_length": 56.7668161435, "max_line_length": 100, "alphanum_fraction": 0.6376491034, "num_tokens": 3090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6430969947609735}}
{"text": "#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/AutoDiff>\n#include <iostream>\n\n// Computes the energy terms into costs. The first part contains termes related to edge length variation,\n// and the second to angle variations.\ntemplate<typename Scalar>\nvoid ikLikeCosts(const Eigen::Matrix<Scalar,Eigen::Dynamic,1>& curve, const Eigen::VectorXd& targetAngles, const Eigen::VectorXd& targetLengths, double beta,\n                 Eigen::Matrix<Scalar,Eigen::Dynamic,1>& costs)\n{\n    using namespace Eigen;\n    using std::atan2;\n\n    typedef Matrix<Scalar,2,1> Vec2;\n    int nb = curve.size()/2;\n\n    costs.setZero();\n    for(int k=1;k<nb-1;++k)\n    {\n        Vec2 pk0 = curve.template segment<2>(2*(k-1));\n        Vec2 pk  = curve.template segment<2>(2*k);\n        Vec2 pk1 = curve.template segment<2>(2*(k+1));\n\n        if(k+1<nb-1) {\n            costs((nb-2)+(k-1)) = (pk1-pk).norm() - targetLengths(k-1);\n        }\n       \n\n        Vec2 v0 = (pk-pk0).normalized();\n        Vec2 v1 = (pk1-pk).normalized();\n\n        costs(k-1) = beta * (atan2(-v0.y() * v1.x() + v0.x() * v1.y(), v0.x() * v1.x() + v0.y() * v1.y()) - targetAngles(k-1));\n    }\n}\n\n// Generic functor\ntemplate<typename _Scalar>\nstruct Functor\n{\n    typedef _Scalar Scalar;\n    enum {\n        InputsAtCompileTime = Eigen::Dynamic,\n        ValuesAtCompileTime = Eigen::Dynamic\n                          };\n    typedef Eigen::Matrix<Scalar,InputsAtCompileTime,1> InputType;\n    typedef Eigen::Matrix<Scalar,ValuesAtCompileTime,1> ValueType;\n    typedef Eigen::Matrix<Scalar,ValuesAtCompileTime,InputsAtCompileTime> JacobianType;\n\n    const int m_inputs, m_values;\n\n    Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n    Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n    int inputs() const { return m_inputs; } // number of degree of freedom (= 2*nb_vertices)\n    int values() const { return m_values; } // number of energy terms (= nb_vertices + nb_edges)\n\n    // you should define that in the subclass :\n    //    void operator() (const InputType& x, ValueType* v, JacobianType* _j=0) const;\n};\n\n// Specialized functor warping the ikLikeCosts function\nstruct iklike_functor : Functor<double>\n{\n    typedef Eigen::AutoDiffScalar<Eigen::Matrix<Scalar,Eigen::Dynamic,1> > ADS;\n    typedef Eigen::Matrix<ADS, Eigen::Dynamic, 1> VectorXad;\n\n    // pfirst and plast are the two extremities of the curve\n    iklike_functor(const Eigen::VectorXd& targetAngles, const Eigen::VectorXd& targetLengths, double beta, const Eigen::Vector2d pfirst, const Eigen::Vector2d plast)\n        :   Functor<double>(targetAngles.size()*2-4,targetAngles.size()*2-1),\n            m_targetAngles(targetAngles), m_targetLengths(targetLengths), m_beta(beta),\n            m_pfirst(pfirst), m_plast(plast)\n    {}\n\n    // input = x = {  ..., x_i, y_i, ....}\n    // output = fvec = the value of each term\n    int operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fvec)\n    {\n        using namespace Eigen;\n        VectorXd curves(this->inputs()+8);\n\n        curves.segment(4,this->inputs()) = x;\n\n        Vector2d d(1,0);\n        curves.segment<2>(0)                   = m_pfirst - d;\n        curves.segment<2>(2)                   = m_pfirst;\n        curves.segment<2>(this->inputs()+4)    = m_plast;\n        curves.segment<2>(this->inputs()+6)    = m_plast + d;\n\n        ikLikeCosts(curves, m_targetAngles, m_targetLengths, m_beta, fvec);\n        return 0;\n    }\n\n    // Compute the jacobian into fjac for the current solution x\n    int df(const Eigen::VectorXd &x, Eigen::MatrixXd &fjac)\n    {\n        using namespace Eigen;\n        VectorXad curves(this->inputs()+8);\n\n        // Compute the derivatives of each degree of freedom\n        // -> grad( x_i ) = (0, ..., 0, 1, 0, ..., 0) ; 1 is in position i\n        for(int i=0; i<this->inputs();++i)\n            curves(4+i) = ADS(x(i), this->inputs(), i);\n\n        Vector2d d(1,0);\n        curves.segment<2>(0)                   = (m_pfirst - d).cast<ADS>();\n        curves.segment<2>(2)                   = (m_pfirst).cast<ADS>();\n        curves.segment<2>(this->inputs()+4)    = (m_plast).cast<ADS>();\n        curves.segment<2>(this->inputs()+6)    = (m_plast + d).cast<ADS>();\n\n        VectorXad v(this->values());\n\n        ikLikeCosts(curves, m_targetAngles, m_targetLengths, m_beta, v);\n\n        // copy the gradient of each energy term into the Jacobian\n        for(int i=0; i<this->values();++i)\n            fjac.row(i) = v(i).derivatives();\n\n        return 0;\n    }\n\n    const Eigen::VectorXd& m_targetAngles;\n    const Eigen::VectorXd& m_targetLengths;\n    double m_beta;\n    Eigen::Vector2d m_pfirst, m_plast;\n};\n\n\n\nvoid draw_vecX(const Eigen::VectorXd& res)\n{\n  for( int i = 0; i < (res.size()/2) ; i++ )\n  {\n    std::cout << res.segment<2>(2*i).transpose() << \"\\n\";\n  }\n}\n\n\nusing namespace Eigen;\n\nint main()\n{\n    Eigen::Vector2d pfirst(-5., 0.);\n    Eigen::Vector2d plast ( 5., 0.);\n\n    // rest pose is a straight line starting between first and last point\n    const int nb_points = 30;\n    Eigen::VectorXd targetAngles (nb_points);\n    targetAngles.fill(0);\n\n    Eigen::VectorXd targetLengths(nb_points-1);\n    double val = (pfirst-plast).norm() / (double)(nb_points-1);\n    targetLengths.fill(val);\n\n\n    // get initial solution\n    Eigen::VectorXd x((nb_points-2)*2);\n    for(int i = 1; i < (nb_points - 1); i++)\n    {\n        double s = (double)i / (double)(nb_points-1);\n        x.segment<2>((i-1)*2) = plast * s + pfirst * (1. - s);\n    }\n\n    // move last point\n    plast = Eigen::Vector2d(4., 1.);\n\n    // Create the functor object\n    iklike_functor func(targetAngles, targetLengths, 0.1, pfirst, plast);\n\n    // construct the solver\n    Eigen::LevenbergMarquardt<iklike_functor> lm(func);\n\n    // adjust tolerance\n    lm.parameters.ftol *= 1e-2;\n    lm.parameters.xtol *= 1e-2;\n    lm.parameters.maxfev = 2000;\n\n\n    int a = lm.minimize(x);\n    std::cerr << \"info = \" << a  << \" \" << lm.nfev << \" \" << lm.njev << \" \"  <<  \"\\n\";\n\n    std::cout << pfirst.transpose() << \"\\n\";\n    draw_vecX( x);\n    std::cout << plast.transpose() << \"\\n\";\n}", "meta": {"hexsha": "7fe6ec4a499f22f20c75d0031b7ec8aba478f9f1", "size": 6153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/model/tools/solver/src/exampleDiff.cpp", "max_stars_repo_name": "chukhanhhoang/SorotokiCode", "max_stars_repo_head_hexsha": "e8c3c76c6768db1fcf9fce5235863b0ce3c6e6f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-01-29T11:56:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T08:21:59.000Z", "max_issues_repo_path": "src/model/tools/solver/src/exampleDiff.cpp", "max_issues_repo_name": "chukhanhhoang/SorotokiCode", "max_issues_repo_head_hexsha": "e8c3c76c6768db1fcf9fce5235863b0ce3c6e6f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-02T09:09:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:09:17.000Z", "max_forks_repo_path": "src/model/tools/solver/src/exampleDiff.cpp", "max_forks_repo_name": "chukhanhhoang/SorotokiCode", "max_forks_repo_head_hexsha": "e8c3c76c6768db1fcf9fce5235863b0ce3c6e6f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-10T11:40:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:38:17.000Z", "avg_line_length": 33.2594594595, "max_line_length": 165, "alphanum_fraction": 0.6078335771, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6430969913563526}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2020 Tinko Bartels, Berlin, Germany.\n\n// Contributed and/or modified by Tinko Bartels,\n//   as part of Google Summer of Code 2020 program.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_EXPRESSIONS_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_EXPRESSIONS_HPP\n\n#include <boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/expression_tree.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace detail { namespace generic_robust_predicates\n{\n\ntemplate\n<\n    typename A11, typename A12,\n    typename A21, typename A22\n>\nusing det2x2 = difference\n    <\n        product<A11, A22>,\n        product<A12, A21>\n    >;\n\nusing orient2d = det2x2\n        <\n            difference <_1, _5>, difference<_2, _6>,\n            difference <_3, _5>, difference<_4, _6>\n        >;\n\ntemplate\n<\n    typename A11, typename A12, typename A13,\n    typename A21, typename A22, typename A23,\n    typename A31, typename A32, typename A33\n>\nstruct det3x3_helper\n{\nprivate:\n    using minor1 = product<A11, det2x2<A22, A23, A32, A33>>;\n    using minor2 = product<A21, det2x2<A12, A13, A32, A33>>;\n    using minor3 = product<A31, det2x2<A12, A13, A22, A23>>;\npublic:\n    using type = sum<minor1, sum<minor2, minor3>>;\n};\n\ntemplate\n<\n    typename A11, typename A12, typename A13,\n    typename A21, typename A22, typename A23,\n    typename A31, typename A32, typename A33\n>\nusing det3x3 = typename det3x3_helper\n    <\n        A11, A12, A13,\n        A21, A22, A23,\n        A31, A32, A33\n    >::type;\n\nusing orient3d = det3x3\n    <\n        difference<_1, _10>, difference<_2, _11>, difference<_3, _12>,\n        difference<_4, _10>, difference<_5, _11>, difference<_6, _12>,\n        difference<_7, _10>, difference<_8, _11>, difference<_9, _12>\n    >;\n\nstruct incircle_helper\n{\nprivate:\n    using adx = difference<_1, _7>;\n    using ady = difference<_2, _8>;\n    using bdx = difference<_3, _7>;\n    using bdy = difference<_4, _8>;\n    using cdx = difference<_5, _7>;\n    using cdy = difference<_6, _8>;\n    using alift = sum<product<adx, adx>, product<ady, ady>>;\n    using blift = sum<product<bdx, bdx>, product<bdy, bdy>>;\n    using clift = sum<product<cdx, cdx>, product<cdy, cdy>>;\npublic:\n    using type = det3x3\n        <\n            alift, adx, ady,\n            blift, bdx, bdy,\n            clift, cdx, cdy\n        >;\n};\n\nusing incircle = incircle_helper::type;\n\n}} // namespace detail::generic_robust_predicates\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_GENERIC_ROBUST_PREDICATES_STRATEGIES_CARTESIAN_DETAIL_EXPRESSIONS_HPP\n", "meta": {"hexsha": "6042b1834ec8f8f4e8d7f1367b119ff3e9a097f8", "size": 2900, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/expressions.hpp", "max_stars_repo_name": "BoostGSoC20/geometry", "max_stars_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T20:30:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T08:14:05.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/expressions.hpp", "max_issues_repo_name": "Srutip04/geometry", "max_issues_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/expressions.hpp", "max_forks_repo_name": "Srutip04/geometry", "max_forks_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:43:59.000Z", "avg_line_length": 27.8846153846, "max_line_length": 110, "alphanum_fraction": 0.6862068966, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6430969884836601}}
{"text": "#ifndef TRIUMF_NMR_HEBEL_SLICHTER_HPP\n#define TRIUMF_NMR_HEBEL_SLICHTER_HPP\n\n#include <cmath>\n#include <complex>\n\n#include <boost/math/quadrature/exp_sinh.hpp>\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n\n#include <triumf/constants/codata_2018.hpp>\n#include <triumf/statistical_mechanics/fermi_dirac.hpp>\n#include <triumf/superconductivity/bcs.hpp>\n#include <triumf/superconductivity/dynes.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// Nuclear Magnetic Resonance (NMR)\nnamespace nmr {\n\n// Hebel-Slichter\nnamespace hebel_slichter {\n\ntemplate <typename T = double>\nT integrand(T energy, T temperature, T critical_temperature, T gap_meV, T alpha,\n            T Gamma) {\n  // alias some values\n  T Delta = triumf::superconductivity::bcs::gap<T>(\n      temperature, critical_temperature, gap_meV);\n  constexpr T E_0 = 0.0;\n  constexpr T E_F = 0.0;\n  //\n  T E = energy;\n  T E_p = E + alpha * gap_meV;\n\n  // calculate the Fermi factors\n  // Note: 1e-3 used to convert energyies from meV to eV\n  T f_E = triumf::statistical_mechanics::fermi_dirac::distribution<T>(\n      temperature, E * 1e-3, E_0, E_F);\n  T f_E_p = triumf::statistical_mechanics::fermi_dirac::distribution<T>(\n      temperature, E_p * 1e-3, E_0, E_F);\n\n  //\n  return (triumf::superconductivity::dynes::N(E, Gamma * gap_meV, Delta) *\n              triumf::superconductivity::dynes::N(E_p, Gamma * gap_meV, Delta) +\n          triumf::superconductivity::dynes::M(E, Gamma * gap_meV, Delta) *\n              triumf::superconductivity::dynes::M(E_p, Gamma * gap_meV,\n                                                  Delta)) *\n         f_E * (1.0 - f_E_p);\n}\n\n// ratio of SLR rates in the superconducting and normal states\ntemplate <typename T = double>\nT slr_ratio(T temperature, T critical_temperature, T gap_meV, T alpha,\n            T Gamma) {\n  // define some convenience values\n  T reduced_temperature = temperature / critical_temperature;\n  constexpr T k_B =\n      1e3 *\n      triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<T>::value();\n  T beta = 1.0 / (k_B * temperature);\n  // return limiting values...\n  // if (temperature >= critical_temperature) {\n  //   return 1.0;\n  // } else if (temperature <= 0.0) {\n  //  return 0.0;\n  if (temperature <= 0.0) {\n    return 0.0;\n    // ...before attempting to evaluate the intergral!\n  } else {\n    // define the integrand\n    auto hs_integrand = [&](T E) -> T {\n      return integrand<T>(E, temperature, critical_temperature, gap_meV, alpha,\n                          Gamma);\n    };\n    // setup values for numeric integration\n    // const T tolerance = std::numeric_limits<T>::epsilon();\n    // const T tolerance = std::pow(std::numeric_limits<T>::epsilon(), 2.0\n    // / 3.0);\n    const T tolerance = std::sqrt(std::numeric_limits<T>::epsilon());\n\n    const std::size_t max_refinements = 15;\n    static boost::math::quadrature::exp_sinh<T> hs_integrator(max_refinements);\n    return 2.0 * beta *\n           hs_integrator.integrate(hs_integrand, tolerance, nullptr, nullptr,\n                                   nullptr);\n    /*\n    const unsigned max_depth = 15;\n    return 2.0 * beta *\n           boost::math::quadrature::gauss_kronrod<T, 61>::integrate(\n               hs_integrand, 0.0, std::numeric_limits<T>::infinity(), max_depth,\n               tolerance, nullptr, nullptr);\n    */\n  }\n}\n\n} // namespace hebel_slichter\n\n} // namespace nmr\n\n} // namespace triumf\n\n#endif // TRIUMF_NMR_HEBEL_SLICHTER_HPP\n", "meta": {"hexsha": "5b8e2f17b298a30e3a9f1ec2b7bdc151cf26f29c", "size": 3466, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/nmr/hebel_slichter.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/triumf/nmr/hebel_slichter.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/triumf/nmr/hebel_slichter.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3269230769, "max_line_length": 80, "alphanum_fraction": 0.6532025389, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6430969840151814}}
{"text": "//\n// Project: Delaunay\n// File: Delaunay.hpp\n//\n// Copyright (c) 2021 Miika 'Lehdari' Lehtim\u00e4ki\n// You may use, distribute and modify this code under the terms\n// of the licence specified in file LICENSE which is distributed\n// with this source code package.\n//\n\n#ifndef DELAUNAY_DELAUNAY_HPP\n#define DELAUNAY_DELAUNAY_HPP\n\n\n#include <vector>\n#include <cstdint>\n\n\n#define DELAUNAY_BACKEND_EIGEN 1\n//#define DELAUNAY_BACKEND_OTHER 2 // add more enumerations for more supported backends\n\n// definitions for Eigen backend\n#if DELAUNAY_BACKEND == DELAUNAY_BACKEND_EIGEN\n    #include <Eigen/Dense>\n\n    #define DELAUNAY_VEC Eigen::Matrix<T_Scalar, 2, 1>\n    #define DELAUNAY_VEC_ACCESS(V, D) V(D)\n    #define DELAUNAY_DETERMINANT\n#endif\n\n// Check for macro definitions\n#ifndef DELAUNAY_VEC\n    #error \"DELAUNAY_VEC not defined\"\n#endif\n#ifndef DELAUNAY_VEC_ACCESS\n    #error \"DELAUNAY_VEC_ACCESS not defined\"\n#endif\n#ifndef DELAUNAY_DETERMINANT\n    #error \"DELAUNAY_DETERMINANT not defined\"\n#endif\n\n#ifdef DELAUNAY_INLINE\n    #error \"DELAUNAY_INLINE already defined\"\n#endif\n#define DELAUNAY_INLINE inline __attribute__((always_inline))\n\n\nnamespace delaunay {\n\nnamespace {\n\nstruct Triangle {\n    int neighbours[3]; // indices of neighbouring triangles\n    int vertices[3]; // indices of corner vertices\n\n    Triangle(int t1, int t2, int t3, int v1, int v2, int v3) :\n        neighbours  {t1, t2, t3},\n        vertices    {v1, v2, v3}\n    {}\n};\n\ntemplate <typename T_Scalar>\nDELAUNAY_INLINE bool ccw(\n    const DELAUNAY_VEC& a,\n    const DELAUNAY_VEC& b,\n    const DELAUNAY_VEC& c)\n{\n#if DELAUNAY_BACKEND == DELAUNAY_BACKEND_EIGEN\n    Eigen::Matrix<T_Scalar, 3, 3>   m;\n    m <<\n        a.transpose(),  1.0,\n        b.transpose(),  1.0,\n        c.transpose(),  1.0;\n    return m.determinant() > 0.0;\n#else\n    return DELAUNAY_DETERMINANT(\n        DELAUNAY_VEC_ACCESS(a,0), DELAUNAY_VEC_ACCESS(a,1), (T_Scalar)1.0,\n        DELAUNAY_VEC_ACCESS(b,0), DELAUNAY_VEC_ACCESS(b,1), (T_Scalar)1.0,\n        DELAUNAY_VEC_ACCESS(c,0), DELAUNAY_VEC_ACCESS(c,1), (T_Scalar)1.0) > 0.0;\n#endif\n}\n\n// is d inside of circumcircle of abc?\ntemplate <typename T_Scalar>\nDELAUNAY_INLINE bool inCircle(\n    const DELAUNAY_VEC& a,\n    const DELAUNAY_VEC& b,\n    const DELAUNAY_VEC& c,\n    const DELAUNAY_VEC& d)\n{\n    T_Scalar dx2 = DELAUNAY_VEC_ACCESS(d,0)*DELAUNAY_VEC_ACCESS(d,0);\n    T_Scalar dy2 = DELAUNAY_VEC_ACCESS(d,1)*DELAUNAY_VEC_ACCESS(d,1);\n#if DELAUNAY_BACKEND == DELAUNAY_BACKEND_EIGEN\n    Eigen::Matrix<T_Scalar, 3, 3>   m;\n    m <<\n        DELAUNAY_VEC_ACCESS(a,0)-DELAUNAY_VEC_ACCESS(d,0),\n        DELAUNAY_VEC_ACCESS(a,1)-DELAUNAY_VEC_ACCESS(d,1),\n        (DELAUNAY_VEC_ACCESS(a,0)*DELAUNAY_VEC_ACCESS(a,0)-dx2)+(DELAUNAY_VEC_ACCESS(a,1)*DELAUNAY_VEC_ACCESS(a,1)-dy2),\n        DELAUNAY_VEC_ACCESS(b,0)-DELAUNAY_VEC_ACCESS(d,0),\n        DELAUNAY_VEC_ACCESS(b,1)-DELAUNAY_VEC_ACCESS(d,1),\n        (DELAUNAY_VEC_ACCESS(b,0)*DELAUNAY_VEC_ACCESS(b,0)-dx2)+(DELAUNAY_VEC_ACCESS(b,1)*DELAUNAY_VEC_ACCESS(b,1)-dy2),\n        DELAUNAY_VEC_ACCESS(c,0)-DELAUNAY_VEC_ACCESS(d,0),\n        DELAUNAY_VEC_ACCESS(c,1)-DELAUNAY_VEC_ACCESS(d,1),\n        (DELAUNAY_VEC_ACCESS(c,0)*DELAUNAY_VEC_ACCESS(c,0)-dx2)+(DELAUNAY_VEC_ACCESS(c,1)*DELAUNAY_VEC_ACCESS(c,1)-dy2);\n    return m.determinant() > 0.0;\n#else\n    return DELAUNAY_DETERMINANT(\n        DELAUNAY_VEC_ACCESS(a,0)-DELAUNAY_VEC_ACCESS(d,0),\n        DELAUNAY_VEC_ACCESS(a,1)-DELAUNAY_VEC_ACCESS(d,1),\n        (DELAUNAY_VEC_ACCESS(a,0)*DELAUNAY_VEC_ACCESS(a,0)-dx2)+(DELAUNAY_VEC_ACCESS(a,1)*DELAUNAY_VEC_ACCESS(a,1)-dy2),\n        DELAUNAY_VEC_ACCESS(b,0)-DELAUNAY_VEC_ACCESS(d,0),\n        DELAUNAY_VEC_ACCESS(b,1)-DELAUNAY_VEC_ACCESS(d,1),\n        (DELAUNAY_VEC_ACCESS(b,0)*DELAUNAY_VEC_ACCESS(b,0)-dx2)+(DELAUNAY_VEC_ACCESS(b,1)*DELAUNAY_VEC_ACCESS(b,1)-dy2),\n        DELAUNAY_VEC_ACCESS(c,0)-DELAUNAY_VEC_ACCESS(d,0),\n        DELAUNAY_VEC_ACCESS(c,1)-DELAUNAY_VEC_ACCESS(d,1),\n        (DELAUNAY_VEC_ACCESS(c,0)*DELAUNAY_VEC_ACCESS(c,0)-dx2)+(DELAUNAY_VEC_ACCESS(c,1)*DELAUNAY_VEC_ACCESS(c,1)-dy2))\n        > 0.0;\n#endif\n}\n\n// initial primitive construction functions for edges and triangles\ntemplate <template <typename, typename> class T_Vector, typename T_Scalar, typename T_Allocator>\nDELAUNAY_INLINE void createEdge(const T_Vector<DELAUNAY_VEC, T_Allocator>& points,\n    std::vector<Triangle>& triangles, int v1, int v2, int& firstTriangle, int& lastTriangle)\n{\n    int s = triangles.size();\n    triangles.emplace_back(s+1, s+1, s+1, v1, v2, -1); // edge is presented by 2 ghost triangles (3rd vertex -1)\n    triangles.emplace_back(s, s, s, v2, v1, -1);\n\n    firstTriangle = s;\n    lastTriangle = s;\n}\n\ntemplate <template <typename, typename> class T_Vector, typename T_Scalar, typename T_Allocator>\nDELAUNAY_INLINE void createTriangle(\n    T_Vector<DELAUNAY_VEC, T_Allocator>& points,\n    std::vector<Triangle>& triangles, int v1, int v2, int v3, int& firstTriangle, int& lastTriangle)\n{\n    int s = triangles.size();\n    if (!ccw(points[v1], points[v2], points[v3])) {\n        std::swap(v2, v3);\n        lastTriangle = s+2;\n    }\n    else\n        lastTriangle = s+3;\n    triangles.emplace_back(s+1, s+2, s+3, v1, v2, v3);\n    triangles.emplace_back(s, s+3, s+2, v2, v1, -1);\n    triangles.emplace_back(s, s+1, s+3, v3, v2, -1);\n    triangles.emplace_back(s, s+2, s+1, v1, v3, -1);\n\n    firstTriangle = s+3;\n}\n\n// update neighbour of a triangle\n// t: triangle neighbour of which is to be updated\n// current: current neighbour triangle id to be changed\n// updated: triangle id of the new neighbour\nDELAUNAY_INLINE void updateNeighbour(Triangle& t, int current, int updated)\n{\n    if (t.neighbours[0] == current) {\n        t.neighbours[0] = updated;\n        return;\n    }\n    if (t.neighbours[1] == current) {\n        t.neighbours[1] = updated;\n        return;\n    }\n    if (t.neighbours[2] == current) {\n        t.neighbours[2] = updated;\n        return;\n    }\n}\n\n// rotate triangle indices so that vertex id of -1 is at index 2, no-op for non-ghost or correct ghost triangles\nDELAUNAY_INLINE void correctGhost(Triangle& t)\n{\n    if (t.vertices[0] == -1) {\n        int tempVertex = t.vertices[2];\n        int tempNeighbour = t.neighbours[2];\n        t.vertices[2] = t.vertices[0];\n        t.neighbours[2] = t.neighbours[0];\n        t.vertices[0] = t.vertices[1];\n        t.neighbours[0] = t.neighbours[1];\n        t.vertices[1] = tempVertex;\n        t.neighbours[1] = tempNeighbour;\n    }\n    else if (t.vertices[1] == -1) {\n        int tempVertex = t.vertices[2];\n        int tempNeighbour = t.neighbours[2];\n        t.vertices[2] = t.vertices[1];\n        t.neighbours[2] = t.neighbours[1];\n        t.vertices[1] = t.vertices[0];\n        t.neighbours[1] = t.neighbours[0];\n        t.vertices[0] = tempVertex;\n        t.neighbours[0] = tempNeighbour;\n    }\n}\n\n// flip an edge between two triangles\ninline void flip(std::vector<Triangle>& triangles, int t1, int t2)\n{\n    Triangle& triangle1 = triangles[t1];\n    Triangle& triangle2 = triangles[t2];\n\n    int t1EdgeId = 0; // id of the t1 edge connecting to t2\n    if (triangle1.neighbours[1] == t2)\n        t1EdgeId = 1;\n    else if (triangle1.neighbours[2] == t2)\n        t1EdgeId = 2;\n\n    int t2EdgeId = 0; // id of the t2 edge connecting to t1\n    if (triangle2.neighbours[1] == t1)\n        t2EdgeId = 1;\n    else if (triangle2.neighbours[2] == t1)\n        t2EdgeId = 2;\n\n    Triangle triangle1temp = triangle1;\n    Triangle triangle2temp = triangle2;\n\n    // update neighbour indexing\n    updateNeighbour(triangles[triangle1temp.neighbours[(t1EdgeId+1)%3]], t1, t2);\n    updateNeighbour(triangles[triangle2temp.neighbours[(t2EdgeId+1)%3]], t2, t1);\n\n    // update vertex and neighbour indexing of t1 and t2\n    triangle1.vertices[(t1EdgeId+1)%3] = triangle2temp.vertices[(t2EdgeId+2)%3];\n    triangle1.neighbours[t1EdgeId] = triangle2temp.neighbours[(t2EdgeId+1)%3];\n    triangle1.neighbours[(t1EdgeId+1)%3] = t2;\n\n    triangle2.vertices[(t2EdgeId+1)%3] = triangle1temp.vertices[(t1EdgeId+2)%3];\n    triangle2.neighbours[t2EdgeId] = triangle1temp.neighbours[(t1EdgeId+1)%3];\n    triangle2.neighbours[(t2EdgeId+1)%3] = t1;\n\n    // correct ghost indexing in case either of the triangles is a ghost\n    correctGhost(triangle1);\n    correctGhost(triangle2);\n}\n\n// get vertex of triangle t opposing neighbour neighbour\nDELAUNAY_INLINE int getOpposingVertex(Triangle& t, int neighbour)\n{\n    if (t.neighbours[0] == neighbour)\n        return t.vertices[2];\n    if (t.neighbours[1] == neighbour)\n        return t.vertices[0];\n    if (t.neighbours[2] == neighbour)\n        return t.vertices[1];\n\n    // should never be reached\n    return -1; // neighbour not neighbour of t\n}\n\n// get the triangle ID of right neighbour w.r.t to a vertex id\nDELAUNAY_INLINE int getRightNeighbour(Triangle& t, int v)\n{\n    if (t.vertices[0] == v)\n        return t.neighbours[2];\n    if (t.vertices[1] == v)\n        return t.neighbours[0];\n    if (t.vertices[2] == v)\n        return t.neighbours[1];\n\n    // should never be reached\n    return -1; // v not a vertex of t\n}\n\n// get the triangle ID of left neighbour w.r.t to a vertex id\nDELAUNAY_INLINE int getLeftNeighbour(Triangle& t, int v)\n{\n    if (t.vertices[0] == v)\n        return t.neighbours[0];\n    if (t.vertices[1] == v)\n        return t.neighbours[1];\n    if (t.vertices[2] == v)\n        return t.neighbours[2];\n\n    // should never be reached\n    return -1; // v not a vertex of t\n}\n\n// ghost triangle adding functions required in ends of a \"seam\"\nDELAUNAY_INLINE int addGhostTriangle(std::vector<Triangle>& triangles, int v1, int v2, int n2, int n3)\n{\n    int s = triangles.size();\n    triangles.emplace_back(-1, n2, n3, v1, v2, -1);\n    triangles[n2].neighbours[2] = s;\n    triangles[n3].neighbours[1] = s;\n    return s;\n}\n\nDELAUNAY_INLINE int addGhostTriangle(std::vector<Triangle>& triangles, int v1, int v2, int n1, int n2, int n3)\n{\n    int s = triangles.size();\n    triangles.emplace_back(n1, n2, n3, v1, v2, -1);\n    triangles[n2].neighbours[2] = s;\n    triangles[n3].neighbours[1] = s;\n    return s;\n}\n\ntemplate <template <typename, typename> class T_Vector, typename T_Scalar, typename T_Allocator>\nvoid merge(T_Vector<DELAUNAY_VEC, T_Allocator>& points,\n    std::vector<Triangle>& triangles, int& firstLeft, int lastLeft, int firstRight, int& lastRight)\n{\n    // keep track of end vertices in case the end triangles change\n    int firstVertex = triangles[firstLeft].vertices[0];\n    int lastVertex = triangles[lastRight].vertices[1];\n\n    // find the lower common tangent\n    int iterId = 0;\n    while (true) {\n        int nOps = 0;\n        int leftNext = triangles[lastLeft].neighbours[1]; // next ghost triangle on the left mesh boundary\n        int rightNext = triangles[firstRight].neighbours[2]; // next ghost triangle on the right mesh boundary\n        if (ccw(\n            points[triangles[leftNext].vertices[0]],\n            points[triangles[leftNext].vertices[1]],\n            points[triangles[firstRight].vertices[0]])) {\n            lastLeft = leftNext;\n            ++nOps;\n        }\n        if (ccw(\n            points[triangles[rightNext].vertices[0]],\n            points[triangles[rightNext].vertices[1]],\n            points[triangles[lastLeft].vertices[1]])) {\n            firstRight = rightNext;\n            ++nOps;\n        }\n        if (nOps == 0) {\n            // opposing triangles are right of the edge of both ghost triangles,\n            // lower common tangent has been found\n            break;\n        }\n        if (++iterId > points.size()) // maximum number of iterations reached, sign of numerical instability\n            break;\n    }\n\n    bool leftValid = true;\n    bool rightValid = true;\n    int baseLeftVertex = triangles[lastLeft].vertices[1];\n    int baseRightVertex = triangles[firstRight].vertices[0];\n\n    // add new ghost triangle to the beginning of the seam\n    int firstGhost = addGhostTriangle(triangles, baseRightVertex, baseLeftVertex,\n        triangles[lastLeft].neighbours[1], triangles[firstRight].neighbours[2]);\n    // check if the ghost overrides either of the end triangles - in that case update their indices\n    if (triangles[firstGhost].vertices[0] == firstVertex)\n        firstLeft = firstGhost;\n    if (triangles[firstGhost].vertices[1] == lastVertex)\n        lastRight = firstGhost;\n\n    int lastConnectedSide = -1; // required for adding the end ghost, 0: left, 1: right\n    int lastConnectedTriangle = -1;\n\n    // merge loop\n    iterId = 0;\n    while (leftValid || rightValid) {\n        auto& baseLeft = points[baseLeftVertex];\n        auto& baseRight = points[baseRightVertex];\n\n        // find connective candidates for both sides, delete non-delaunay edges by flipping\n        int leftCand = triangles[lastLeft].vertices[0];\n        leftValid = ccw(baseLeft, baseRight, points[leftCand]);\n        if (leftValid) {\n            int leftNeighbour = getRightNeighbour(triangles[lastLeft], baseLeftVertex);\n            int leftNeighbourCand = getOpposingVertex(triangles[leftNeighbour], lastLeft);\n            while (leftNeighbourCand != -1 &&\n                inCircle(baseLeft, baseRight, points[leftCand], points[leftNeighbourCand])) {\n                flip(triangles, lastLeft, leftNeighbour);\n                lastLeft = leftNeighbour;\n                leftCand = leftNeighbourCand;\n                leftNeighbour = getRightNeighbour(triangles[lastLeft], baseLeftVertex);\n                leftNeighbourCand = getOpposingVertex(triangles[leftNeighbour], lastLeft);\n            }\n        }\n\n        int rightCand = triangles[firstRight].vertices[1];\n        rightValid = ccw(baseLeft, baseRight, points[rightCand]);\n        if (rightValid) {\n            int rightNeighbour = getLeftNeighbour(triangles[firstRight], baseRightVertex);\n            int rightNeighbourCand = getOpposingVertex(triangles[rightNeighbour], firstRight);\n            while (rightNeighbourCand != -1 &&\n                inCircle(baseLeft, baseRight, points[rightCand], points[rightNeighbourCand])) {\n                flip(triangles, firstRight, rightNeighbour);\n                rightCand = rightNeighbourCand;\n                rightNeighbour = getLeftNeighbour(triangles[firstRight], baseRightVertex);\n                rightNeighbourCand = getOpposingVertex(triangles[rightNeighbour], firstRight);\n            }\n        }\n\n        if (!leftValid && !rightValid)\n            break;\n\n        if (!leftValid || (rightValid && inCircle(points[leftCand], baseLeft, baseRight, points[rightCand]))) {\n            int rightNext = triangles[firstRight].neighbours[1];\n\n            if (firstGhost != -1) { // update first ghost\n                triangles[firstGhost].neighbours[0] = firstRight;\n                triangles[firstRight].neighbours[2] = firstGhost;\n                firstGhost = -1;\n            }\n            else { // connect left side triangle in case it was previously added\n                if (lastConnectedSide == 0) {\n                    triangles[lastConnectedTriangle].neighbours[2] = firstRight;\n                    triangles[firstRight].neighbours[2] = lastConnectedTriangle;\n                }\n            }\n\n            // connect edge\n            triangles[firstRight].vertices[2] = baseLeftVertex;\n            lastConnectedTriangle = firstRight;\n            firstRight = rightNext;\n            baseRightVertex = rightCand;\n\n            lastConnectedSide = 1;\n        }\n        else {\n            int leftNext = triangles[lastLeft].neighbours[2];\n\n            if (firstGhost != -1) { // update first ghost\n                triangles[firstGhost].neighbours[0] = lastLeft;\n                triangles[lastLeft].neighbours[1] = firstGhost;\n                firstGhost = -1;\n            }\n            else { // connect right side triangle in case it was previously added\n                if (lastConnectedSide == 1) {\n                    triangles[lastConnectedTriangle].neighbours[1] = lastLeft;\n                    triangles[lastLeft].neighbours[1] = lastConnectedTriangle;\n                }\n            }\n\n            // connect edge\n            triangles[lastLeft].vertices[2] = baseRightVertex;\n            lastConnectedTriangle = lastLeft;\n            lastLeft = leftNext;\n            baseLeftVertex = leftCand;\n\n            lastConnectedSide = 0;\n        }\n\n        if (++iterId > points.size()) // maximum number of iterations reached, sign of numerical instability\n            break;\n    }\n\n    // add new ghost triangle to the end of the seam\n    int lastGhost;\n    if (lastConnectedSide == 0) {\n        int lastConnect = triangles[lastLeft].neighbours[1];\n        lastGhost = addGhostTriangle(triangles, baseLeftVertex, baseRightVertex, lastConnect, firstRight, lastLeft);\n        triangles[lastConnect].neighbours[2] = lastGhost;\n    }\n    else {\n        int lastConnect = triangles[firstRight].neighbours[2];\n        lastGhost = addGhostTriangle(triangles, baseLeftVertex, baseRightVertex, lastConnect, firstRight, lastLeft);\n        triangles[lastConnect].neighbours[1] = lastGhost;\n    }\n\n    // check if the ghost overrides either of the end triangles - in that case update their indices\n    if (triangles[lastGhost].vertices[0] == firstVertex)\n        firstLeft = lastGhost;\n    if (triangles[lastGhost].vertices[1] == lastVertex)\n        lastRight = lastGhost;\n}\n\ntemplate <template <typename, typename> class T_Vector, typename T_Scalar, typename T_Allocator>\nvoid construct(T_Vector<DELAUNAY_VEC, T_Allocator>& points,\n    int begin, int end, std::vector<Triangle>& triangles, int& firstTriangle, int& lastTriangle)\n{\n    int d = end-begin;\n    if (d == 2) { // initial primitives, edge\n        createEdge(points, triangles, begin, begin+1, firstTriangle, lastTriangle);\n    }\n    else if (d == 3) { // initial primitives, triangle\n        createTriangle(points, triangles, begin, begin+1, begin+2, firstTriangle, lastTriangle);\n    }\n    else {\n        // recursive construction and merge\n        auto half = begin+d/2;\n        int firstLeft; int lastLeft;\n        construct(points, begin, half, triangles, firstLeft, lastLeft);\n        int firstRight; int lastRight;\n        construct(points, half, end, triangles, firstRight, lastRight);\n\n        merge(points, triangles, firstLeft, lastLeft, firstRight, lastRight);\n\n        firstTriangle = firstLeft;\n        lastTriangle = lastRight;\n    }\n}\n\n} // namespace\n\ntemplate <template <typename, typename> class T_Vector, typename T_Scalar, typename T_Allocator>\nstd::vector<int32_t> triangulate(T_Vector<DELAUNAY_VEC, T_Allocator>& points)\n{\n    // sort points primarily along x-axis (and along y-axis in case of equal x)\n    std::sort(points.begin(), points.end(), [](\n        const DELAUNAY_VEC& a,\n        const DELAUNAY_VEC& b){\n        return DELAUNAY_VEC_ACCESS(a,0) == DELAUNAY_VEC_ACCESS(b,0) ?\n            DELAUNAY_VEC_ACCESS(a,1) < DELAUNAY_VEC_ACCESS(b,1) :\n            DELAUNAY_VEC_ACCESS(a,0) < DELAUNAY_VEC_ACCESS(b,0);\n    });\n\n    std::vector<Triangle> triangles;\n    triangles.reserve(2*points.size());\n\n    int firstTriangle, lastTriangle;\n    construct(points, 0, points.size(), triangles, firstTriangle, lastTriangle);\n\n    // list indices into output vector\n    std::vector<int32_t> indices;\n    indices.reserve(triangles.size()*3);\n    for (auto& t : triangles) {\n        indices.emplace_back(t.vertices[0]);\n        indices.emplace_back(t.vertices[1]);\n        indices.emplace_back(t.vertices[2]);\n    }\n    return indices;\n}\n\n} // namespace delaunay\n\n\n// undefine macros\n#undef DELAUNAY_VEC\n#undef DELAUNAY_VEC_ACCESS\n#undef DELAUNAY_DETERMINANT\n#undef DELAUNAY_INLINE\n\n\n#endif //DELAUNAY_DELAUNAY_HPP\n", "meta": {"hexsha": "7e138130c94ee0809a94eef5414171464b2db970", "size": 19551, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Delaunay.hpp", "max_stars_repo_name": "Lehdari/Delaunay", "max_stars_repo_head_hexsha": "64cbbdd4f7ce608ed3e609052e0862280c8927a9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T14:39:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T14:39:22.000Z", "max_issues_repo_path": "include/Delaunay.hpp", "max_issues_repo_name": "Lehdari/Delaunay", "max_issues_repo_head_hexsha": "64cbbdd4f7ce608ed3e609052e0862280c8927a9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Delaunay.hpp", "max_forks_repo_name": "Lehdari/Delaunay", "max_forks_repo_head_hexsha": "64cbbdd4f7ce608ed3e609052e0862280c8927a9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8192090395, "max_line_length": 120, "alphanum_fraction": 0.6563347143, "num_tokens": 5443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6430833198117936}}
{"text": "/*\n * @Description: ceres residual block for map matching pose measurement\n * @Author: Ge Yao\n * @Date: 2020-11-29 15:47:49\n */\n#ifndef LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_MAP_MATCHING_POSE_HPP_\n#define LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_MAP_MATCHING_POSE_HPP_\n\n#include <ceres/ceres.h>\n\n#include <Eigen/Eigen>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <sophus/so3.hpp>\n\n#include \"glog/logging.h\"\n\nnamespace sliding_window {\n\nclass FactorPRVAGMapMatchingPose : public ceres::SizedCostFunction<6, 15> {\npublic:\n\tstatic const int INDEX_P = 0;\n\tstatic const int INDEX_R = 3;\n\n  FactorPRVAGMapMatchingPose(void) {};\n\n  void SetMeasurement(const Eigen::VectorXd &m) {\n\t\tm_ = m;\n\t}\n\n  void SetInformation(const Eigen::MatrixXd &I) {\n    I_ = I;\n  }\n\n  virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const {\n    //\n    // parse parameters:\n    //\n    // pose\n    Eigen::Map<const Eigen::Vector3d>     pos(&parameters[0][INDEX_P]);\n    Eigen::Map<const Eigen::Vector3d> log_ori(&parameters[0][INDEX_R]);\n    const Sophus::SO3d                    ori = Sophus::SO3d::exp(log_ori);\n\n    //\n    // parse measurement:\n    // \n\t\tconst Eigen::Vector3d     &pos_prior = m_.block<3, 1>(INDEX_P, 0);\n\t\tconst Eigen::Vector3d &log_ori_prior = m_.block<3, 1>(INDEX_R, 0);\n    const Sophus::SO3d         ori_prior = Sophus::SO3d::exp(log_ori_prior);\n\n    //\n    // TODO: get square root of information matrix:\n    //\n\n    //\n    // TODO: compute residual:\n    //\n\n    //\n    // TODO: compute jacobians:\n    //\n    if ( jacobians ) {\n      if ( jacobians[0] ) {\n        // implement jacobian computing:\n      }\n    }\n\n    //\n    // TODO: correct residual by square root of information matrix:\n    //\n\t\t\n    return true;\n  }\n\nprivate:\n  static Eigen::Matrix3d JacobianRInv(const Eigen::Vector3d &w) {\n      Eigen::Matrix3d J_r_inv = Eigen::Matrix3d::Identity();\n\n      double theta = w.norm();\n\n      if ( theta > 1e-5 ) {\n          Eigen::Vector3d k = w.normalized();\n          Eigen::Matrix3d K = Sophus::SO3d::hat(k);\n          \n          J_r_inv = J_r_inv \n                    + 0.5 * K\n                    + (1.0 - (1.0 + std::cos(theta)) * theta / (2.0 * std::sin(theta))) * K * K;\n      }\n\n      return J_r_inv;\n  }\n\n  Eigen::VectorXd m_;\n  Eigen::MatrixXd I_;\n};\n\n} // namespace sliding_window\n\n#endif // LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_FACTOR_PRVAG_MAP_MATCHING_POSE_HPP_\n", "meta": {"hexsha": "027f06e8b2df3b75520b2abb129cacb4f470c946", "size": 2464, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/factors/factor_prvag_map_matching_pose.hpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/factors/factor_prvag_map_matching_pose.hpp", "max_issues_repo_name": "lanqing30/SensorFusionCourse", "max_issues_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/factors/factor_prvag_map_matching_pose.hpp", "max_forks_repo_name": "lanqing30/SensorFusionCourse", "max_forks_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T01:05:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T01:05:31.000Z", "avg_line_length": 24.396039604, "max_line_length": 103, "alphanum_fraction": 0.6310876623, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6430833022622165}}
{"text": "#include <iostream>\n#include <vector>\n#include <unordered_set>\n#include <set>\n#include <chrono>\n#include <queue>\n#include <utility>\n#include <new>\n#include <algorithm>\n#include <stack>\n#include <random>\n#include <cmath>\n#include <fstream>\n/*\nused for plotting routes\n#include <boost/tuple/tuple.hpp>\n#include \"gnuplot-iostream.h\"\n*/\n\n// writes a vector of pairs to a given file name\nvoid WriteToFile(std::string file_name, std::vector< std::pair<double, double> > array) {\n  std::ofstream fout(file_name);\n  for(int i = 0;i < array.size(); i++) {\n    fout<<array[i].first<<','<<array[i].second<<'\\n';\n  }\n}\n\n// represents each solution/chromosome\nstruct State{\n  std::vector< std::pair <double,double> > permutation;\n  double cost;\n  int operator ==(State b) const {\n    return (permutation == b.permutation) && (cost == b.cost);\n  }\n};\n\n// a hash function for random_states\nstruct StateHash {\n    size_t operator()(const State &v) const {\n        size_t seed = 0;\n      \tfor(auto t = v.permutation.begin();t != v.permutation.end();t++) {\n            size_t h1 = std::hash<double>()((*t).first);\n            size_t h2 = std::hash<double>()((*t).second);\n            seed ^= (h1 ^ (h2 << 1));\n        }\n        return seed;\n    }\n};\n\n// a hash function for random_states used for unordered_set\nstruct PairHash {\n    size_t operator()(const std::pair<double,double> &v) const {\n        size_t seed = 0;\n        size_t h1 = std::hash<double>()(v.first);\n        size_t h2 = std::hash<double>()(v.second);\n        seed = (h1 ^ (h2 << 1));\n        return seed;\n    }\n};\n\n// two states are compared by their path cost\nbool CompareState(State first, State second) {\n    return (first.cost < second.cost);\n}\n// forward declaring functions\ndouble StateCost(State);\n\nState BeamSearch(State);\n\nState SimulatedAnnealing(State);\n\nState GeneticAlgorithm(State);\n\n//  lists to store best, worst and best of each generation\nstd::vector<std::pair<double,double>> best_of_generation;\n\nstd::vector<std::pair<double,double>> worst_of_generation;\n\nstd::vector<std::pair<double,double>> average_of_generation;\n\n// probability bins for rank selection\nstd::vector< int > pool_probability_bins;\n\nint main() {\n  // used for plotting route\n  //Gnuplot gp;\n  // recieve city Coordinates\n  std::vector<std::pair<double, double> > points;\n\tint n;\n\tdouble x,y;\n\tstd::string method;\n\tState nodes;\n\tState result;\n\tstd::cout<<\"Enter X and Y Coordinates of Initial Node:\\n\";\n  std::cin>>x>>y;\n  nodes.permutation.push_back(std::make_pair(x,y));\n\tstd::cout<<\"Enter Number of Nodes other than the Initial Node:\\n\";\n\tstd::cin>>n;\n    std::cout<<\"Enter X and Y Coordinates of the Nodes:\\n\";\n    for(int i = 0; i < n;i++) {\n\t\tstd::cin>>x>>y;\n\t\tnodes.permutation.push_back(std::make_pair(x,y));\n\t}\n  // create initial state / permutation\n\tnodes.cost = StateCost(nodes);\n  // run the selected method\n\tstd::cout<<\"Enter Beam, SA or GA\\n\";\n\tstd::cin>>method;\n  // start timer\n  auto start = std::chrono::high_resolution_clock::now();\n\tif(method == \"Beam\") {\n\t\tresult = BeamSearch(nodes);\n\t}\n\tif(method == \"SA\") {\n\t\tresult = SimulatedAnnealing(nodes);\n\t}\n\tif(method == \"GA\") {\n\t\tresult = GeneticAlgorithm(nodes);\n\t}\n  // stop timer and print the time it took and the best route cost\n\tauto finish = std::chrono::high_resolution_clock::now();\n\tstd::chrono::duration<double>elapsed = finish - start;\n\tstd::cout<<\"Duration: \"<<elapsed.count()<<'\\n'<<result.cost;\n\n  // plot best route\n  /*\n  for(int i = 0;i<result.permutation.size();i++) {\n        points.push_back(result.permutation[i]);\n\t}\n\tpoints.push_back(result.permutation[0]);\n*/\n  //gp << \"set xrange [0:1000]\\nset yrange [0:100]\\n\";\n\t//gp << \"plot\" << gp.file1d(average_of_generation) << \"with lines title 'average',\"<<std::endl;\n\t//gp << \"plot\" << gp.file1d(best_of_generation) << \"with lines title 'best',\"<<std::endl;\n\t//gp << \"plot\" << gp.file1d(worst_of_generation) << \"with lines title 'worst',\"<<std::endl;\n\n  // write generation results to files\n  //WriteToFile(\"average_of_generation1000k1000g.txt\",average_of_generation);\n  //WriteToFile(\"best_of_generation1000k1000g.txt\",best_of_generation);\n  //WriteToFile(\"worst_of_generation1000k1000g.txt\",worst_of_generation);\n  return 0;\n}\n\nint Factorial(int num) {\n    int res = 1;\n    for(int i = num;i>1;i--) {\n        res*=i;\n    }\n    return res;\n}\n\n// computes cost of permutation\ndouble StateCost (State nodes) {\n    double cost = 0;\n    for(int i = 0;i<nodes.permutation.size()-1;i++) {\n        cost += sqrt(pow((nodes.permutation[i].first - nodes.permutation[i+1].first),2) + pow((nodes.permutation[i].second - nodes.permutation[i+1].second),2));\n    }\n    cost += sqrt(pow((nodes.permutation[0].first - nodes.permutation[nodes.permutation.size()-1].first),2) +\n                 pow((nodes.permutation[0].second - nodes.permutation[nodes.permutation.size()-1].second),2));\n    return cost;\n}\n\n// a binary search to find index/bin which the input belongs to\nint FindIndex(int input) {\n  int l = 0;\n  int r = pool_probability_bins.size()-1;\n  int m;\n  while(l<r) {\n    m = (l+r)/2;\n    if(pool_probability_bins[m] == input) {\n      break;\n    }\n    else if(input > pool_probability_bins[m]) {\n      if(input < pool_probability_bins[m+1]) {\n        break;\n      }\n      else {\n        l = m+1;\n      }\n    }\n    else {\n      if(input > pool_probability_bins[m-1]) {\n        m--;\n        break;\n      }\n      else {\n        r = m-1;\n      }\n    }\n  }\n  return m;\n}\n\n// creates random permutations and adds greedy state to poputlation\nstd::vector < State > RandomPopulation(State nodes , int size_of_population = -1) {\n\tstd::unordered_set < State , StateHash > random_states;\n\tState new_state;\n\tunsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n\tstd::default_random_engine generator (seed);\n\tif(size_of_population == -1) {\n        size_of_population = std::min(std::max(1,int(1e5/pow(nodes.permutation.size(),2))),int((nodes.permutation.size()-1 > 9) ? 1e6 : Factorial(nodes.permutation.size()-1)));\n\t}\n\telse {\n\t    size_of_population = std::min(size_of_population,int((nodes.permutation.size()-1 > 9) ? 1e6 : Factorial(nodes.permutation.size()-1)));\n\t}\n\tfor(int k = 0;k < size_of_population-1;k++) {\n\t    new_state = nodes;\n\t    for(int i = 1;i<nodes.permutation.size()-1;i++) {\n\t        std::uniform_int_distribution<int> distribution(i,nodes.permutation.size()-1);\n\t        int j = distribution(generator);\n\t        std::swap(new_state.permutation[i],new_state.permutation[j]);\n\t    }\n\t    new_state.cost = StateCost(new_state);\n\t    random_states.insert(new_state);\n  }\n  // computing greedy route/permutaion by finding closest city at each step\n  std::set < int > visited;\n  State greedy;\n  visited.insert(0);\n  int current = 0;\n  greedy.permutation.push_back(nodes.permutation[0]);\n  for(int i = 0; i < nodes.permutation.size()-1; i++){\n    int closest = -1;\n    double min_distnace = 99999;\n    for(int j = 0; j < nodes.permutation.size()-1; j++){\n      if(!visited.count(j)){\n        if(pow((nodes.permutation[current].first - nodes.permutation[j].first),2) +\n           pow((nodes.permutation[current].second - nodes.permutation[j].second),2) < min_distnace){\n          min_distnace = pow((nodes.permutation[current].first - nodes.permutation[j].first),2) +\n                        pow((nodes.permutation[current].second - nodes.permutation[j].second),2);\n          closest = j;\n         }\n      }\n    }\n    visited.insert(closest);\n    greedy.permutation.push_back(nodes.permutation[closest]);\n    current = closest;\n  }\n  greedy.cost = StateCost(greedy);\n  std::cerr<<greedy.cost<<'\\n';\n  std::vector < State > return_states;\n  return_states.push_back(greedy);\n  for(auto state = random_states.begin();state != random_states.end();state++) {\n    return_states.push_back(*state);\n  }\n\treturn return_states;\n}\n\n\n// applies HillClimb on given state/permutation\n// neighbours are produced by swapping two cities\nState HillClimb (State nodes) {\n    State min_neighbour;\n    bool min_defined = false;\n    do{\n        if(min_defined == true) {\n            nodes = min_neighbour;\n            min_defined = false;\n        }\n        for(int i = 1;i<nodes.permutation.size();i++) {\n            for(int j = i+1;j<nodes.permutation.size();j++) {\n                State neighbour_state = nodes;\n                swap(neighbour_state.permutation[i],neighbour_state.permutation[j]);\n                neighbour_state.cost = StateCost(neighbour_state);\n                if(min_defined == false) {\n                    min_neighbour = neighbour_state;\n                    min_defined = true;\n                }\n                else if(neighbour_state.cost < min_neighbour.cost) {\n                    min_neighbour = neighbour_state;\n                }\n            }\n        }\n    }while(min_neighbour.cost < nodes.cost);\n    return nodes;\n}\n\n// missleading name. it basically does HillClimb on each state in RandomPopulation\nState BeamSearch(State nodes) {\n    std::vector < State > initial_states = RandomPopulation(nodes,1);\n    State final_state;\n    bool final_defined = false;\n    double final_state_cost = 0;\n    for(auto state = initial_states.begin();state != initial_states.end();state++) {\n        State local_min = HillClimb(*state);\n        if(final_defined == false) {\n            final_state = local_min;\n            final_defined = true;\n        }\n        else if(local_min.cost < final_state.cost) {\n            final_state = local_min;\n        }\n    }\n    return final_state;\n}\n\n// a simple mutation function swapping two indexes\nState RandomNeighbour(State nodes) {\n  // choose two random numbers to swap\n\tState new_state;\n\tunsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n\tstd::default_random_engine generator (seed);\n  new_state = nodes;\n  std::uniform_int_distribution<int> distribution(1,nodes.permutation.size()-1);\n  int j = distribution(generator);\n  int i = distribution(generator);\n  // swap chosen indexes\n  std::swap(new_state.permutation[i],new_state.permutation[j]);\n  new_state.cost = StateCost(new_state);\n\treturn new_state;\n}\n\n// SimulatedAnnealing\nState SimulatedAnnealing(State nodes) {\n    double temperature = 400;\n    double cooling_factor = 0.99999;\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_real_distribution<> dis(0.0, 1.0);\n    while(temperature > 1e-9) {\n        State neighbour = RandomNeighbour(nodes);\n        if(neighbour.cost < nodes.cost) {\n            nodes = neighbour;\n        }\n        else if(exp((neighbour.cost-nodes.cost)/temperature) < dis(gen)) {\n             nodes = neighbour;\n        }\n        temperature *= cooling_factor;\n    }\n    return nodes;\n}\n\n// uses rank selection to generate breeding_pool\nstd::vector< State > RankSelection(std::vector< State > population,int kPopulationSize) {\n  std::vector<State> breeding_pool;\n  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n  std::default_random_engine generator (seed);\n  std::uniform_int_distribution<int> distribution(0,(kPopulationSize*(kPopulationSize+1))/2);\n  for(int i = 0; i<kPopulationSize;i++) {\n    int j = distribution(generator);\n    // finds index of chosen number in pool_probability_bins\n    int chosen = FindIndex(j);\n    breeding_pool.push_back(population[chosen]);\n  }\n  return breeding_pool;\n}\n\n// an order recombination based Cross Over function\nState CrossOver(State parent1 ,State parent2) {\n  // choose two random points for recombination\n  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n\tstd::default_random_engine generator (seed);\n  std::uniform_int_distribution<int> distribution(1,parent1.permutation.size()-1);\n  std::unordered_set < std::pair<double,double> , PairHash > seen;\n  int a = distribution(generator);\n  int b = distribution(generator);\n  // fill offspring with the a-b cut of first parent\n  State new_state;\n  for(int i = std::min(a,b);i<=std::max(a,b);i++) {\n    new_state.permutation.push_back(parent1.permutation[i]);\n    seen.insert(parent1.permutation[i]);\n  }\n  // fill the rest of offspring with rest of second parent\n  int k=-1;\n  for(int i = 0;i<std::min(a,b);i++) {\n    while(seen.count(parent2.permutation[++k])) {}\n    new_state.permutation.insert(new_state.permutation.begin(),parent2.permutation[k]);\n  }\n  for(int i = new_state.permutation.size();i<parent1.permutation.size();i++) {\n    while(seen.count(parent2.permutation[++k])) {}\n    new_state.permutation.push_back(parent2.permutation[k]);\n  }\n  new_state.cost = StateCost(new_state);\n  return new_state;\n}\n\nState GeneticAlgorithm(State nodes) {\n  const double kElitePercentage = 0.1;\n  const double kMutationRate = 0.01;\n  const int kGenerations = 1000;\n  const int kPopulationSize = 500;\n  std::vector < State > population = RandomPopulation(nodes, kPopulationSize);\n  const int kEliteSize = int(kElitePercentage*population.size());\n  State min_state;\n  min_state.cost = 1000000;\n  // rank based selection bins\n  pool_probability_bins.push_back(0);\n  for(int k = 0;k<kPopulationSize;k++) {\n    int temp = pool_probability_bins[k];\n    pool_probability_bins.push_back(temp + kPopulationSize - k);\n  }\n\n  // execute GeneticAlgorithm with specified number of generations\n  for(int k = 0;k<kGenerations;k++) {\n    std::vector < State > new_population;\n    std::vector < State >  breeding_pool;\n    std::vector < State >  offsprings;\n    // sort current population\n    std::sort(population.begin(),population.end(),CompareState);\n    // save best and worst of population\n    best_of_generation.push_back(std::make_pair(k, (*(population.begin())).cost));\n    worst_of_generation.push_back(std::make_pair(k, (population[population.size()-1]).cost));\n\n    double temp_avg = 0;\n    int temp_counter = 1;\n    // calculate average fitness of population\n    for(auto it = population.begin();it != population.end();it++) {\n      temp_avg = temp_avg / temp_counter * (temp_counter-1) + (*it).cost / temp_counter;\n      temp_counter++;\n    }\n    // save average fitness of population\n    average_of_generation.push_back(std::make_pair(k, temp_avg));\n    // add elites to new population\n    for(int i = 0;i<kEliteSize;i++) {\n      new_population.push_back(population[i]);\n    }\n    // get breeding pool with RankSelection\n    breeding_pool = RankSelection(population,kPopulationSize);\n    for(int t = 0;t<population.size()-kEliteSize;t++) {\n      // choose two random states from breeding_pool\n      unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n      std::default_random_engine generator (seed);\n      std::uniform_int_distribution<int> distribution(0,breeding_pool.size()-1);\n      int j = distribution(generator);\n      int i = distribution(generator);\n      // create offspring of two parents using CrossOver\n      State offspring = CrossOver(breeding_pool[i],breeding_pool[j]);\n      offsprings.push_back(offspring);\n    }\n    // mutates an offspring with given probability\n    for(auto it = offsprings.begin();it != offsprings.end();it++) {\n      std::random_device rd;\n      std::mt19937 gen(rd());\n      std::uniform_real_distribution<> dis(0.0, 1.0);\n      if(dis(gen) < kMutationRate) {\n        State mutant = RandomNeighbour(*it);\n        new_population.push_back(mutant);\n      }\n      else {\n        new_population.push_back(*it);\n      }\n    }\n    breeding_pool.erase(breeding_pool.begin(),breeding_pool.end());\n    for(int it = 0;it < population.size();it++) {\n      population[it]=new_population[it];\n    }\n    new_population.erase(new_population.begin(),new_population.end());\n  }\n  State result = population[0];\n  for(int it = 0;it < population.size();it++) {\n    if (result.cost > population[it].cost) {\n      result = population[it];\n    }\n  }\n  return result;\n}\n", "meta": {"hexsha": "8b4965b03e68d37f5e6ec1505950beab9493b4bc", "size": 15725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TSP.cpp", "max_stars_repo_name": "KhashayarSH/Traveling_Salesperson_Problem_Using_GA_SA_HC", "max_stars_repo_head_hexsha": "fed5ac88d43fea15c6e8d283c1ffc0adfdc0c424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TSP.cpp", "max_issues_repo_name": "KhashayarSH/Traveling_Salesperson_Problem_Using_GA_SA_HC", "max_issues_repo_head_hexsha": "fed5ac88d43fea15c6e8d283c1ffc0adfdc0c424", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TSP.cpp", "max_forks_repo_name": "KhashayarSH/Traveling_Salesperson_Problem_Using_GA_SA_HC", "max_forks_repo_head_hexsha": "fed5ac88d43fea15c6e8d283c1ffc0adfdc0c424", "max_forks_repo_licenses": ["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.409190372, "max_line_length": 176, "alphanum_fraction": 0.6587599364, "num_tokens": 3932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6430832947685762}}
{"text": "/**\n * regression test\n * @author Tobias Weber <tweber@ill.fr>\n * @date feb-19\n * @license GPLv3, see 'LICENSE' file\n *\n * g++ -std=c++20 -o leastsq leastsq.cpp\n * g++ -std=c++20 -DUSE_LAPACK -I/usr/include/lapacke -I/usr/local/opt/lapack/include -L/usr/local/opt/lapack/lib -o leastsq leastsq.cpp -llapacke\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE Least Squares Test\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n#include <iostream>\n#include <vector>\n\n#include \"libs/maths.h\"\nusing namespace tl2_ops;\n\n\nusing t_types = std::tuple<double, float>;\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_leastsq, t_real, t_types)\n{\n\t//using t_cplx = std::complex<t_real>;\n\tusing t_vec = tl2::vec<t_real, std::vector>;\n\t//using t_mat = tl2::mat<t_real, std::vector>;\n\t//using t_vec_cplx = tl2::vec<t_cplx, std::vector>;\n\t//using t_mat_cplx = tl2::mat<t_cplx, std::vector>;\n\n\n\tauto x = tl2::create<t_vec>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10});\n\tauto y = tl2::create<t_vec>({5, 5, 7, 9, 9.5, 10.5, 10.5, 12, 13.5, 14});\n\n\tauto [params, ok] = tl2::leastsq<t_vec>(x, y, 1);\n\tstd::cout << \"ok: \" << ok << \", params: \" << params << std::endl;\n\n\tBOOST_TEST(ok);\n\tBOOST_TEST(params[0] == 3.9, testtools::tolerance(1e-3));\n\tBOOST_TEST(params[1] == 1.036, testtools::tolerance(1e-3));\n}\n", "meta": {"hexsha": "684c5e9f0fcea3fd849b7a75ad6b5634f3ab2377", "size": 2336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/leastsq.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/leastsq.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/leastsq.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 37.0793650794, "max_line_length": 146, "alphanum_fraction": 0.6327054795, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6430832923029046}}
{"text": "/**\n * UnscentedKalmanFilterX.hpp\n * @author koide\n * 16/02/01\n **/\n#ifndef KKL_UNSCENTED_KALMAN_FILTER_X_HPP\n#define KKL_UNSCENTED_KALMAN_FILTER_X_HPP\n\n#include <random>\n#include <Eigen/Dense>\n#include <kalman/kalman_filter.hpp>\n\n/**\n * @brief Unscented Kalman Filter class\n * @param T        scaler type\n * @param System   system class to be estimated\n */\ntemplate<typename T, class System>\nclass UnscentedKalmanFilterX  : public KalmanFilter<T, System>\n{\n  typedef Eigen::Matrix<T, Eigen::Dynamic, 1> VectorXt;    //\u5217\u5411\u91cf\n  typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> MatrixXt;\n  using KalmanFilter<T, System>::state_dim;\n  using KalmanFilter<T, System>::N;\n  using KalmanFilter<T, System>::input_dim;\n  using KalmanFilter<T, System>::measurement_dim;\n  using KalmanFilter<T, System>::M;\n  using KalmanFilter<T, System>::mean;\n  using KalmanFilter<T, System>::cov;\n  using KalmanFilter<T, System>::system;\n  using KalmanFilter<T, System>::process_noise;\n  using KalmanFilter<T, System>::measurement_noise;\n  using KalmanFilter<T, System>::kalman_gain;\npublic:\n  /**\n   * @brief constructor\n   * @param system               system to be estimated\n   * @param state_dim            state vector dimension\n   * @param input_dim            input vector dimension\n   * @param measurement_dim      measurement vector dimension\n   * @param process_noise        process noise covariance (state_dim x state_dim)\n   * @param measurement_noise    measurement noise covariance (measurement_dim x measuremend_dim)\n   * @param mean                 initial mean\n   * @param cov                  initial covariance\n   */\n  UnscentedKalmanFilterX(const System& _system, int _state_dim, int _input_dim, int _measurement_dim, \n                         const MatrixXt& _process_noise, const MatrixXt& _measurement_noise, \n                         const VectorXt& _mean, const MatrixXt& _cov):\n    KalmanFilter<T, System>(_system, _state_dim, _input_dim, _measurement_dim, _process_noise, _measurement_noise, _mean, _cov),\n    S(2 * state_dim + 1),\n    lambda(1)\n  {\n    weights.resize(S, 1);\n    sigma_points.resize(S, N);\n    ext_weights.resize(2 * (N + M) + 1, 1);\n    ext_sigma_points.resize(2 * (N + M) + 1, N + M);\n    expected_measurements.resize(2 * (N + M) + 1, M);\n\n    // initialize weights for unscented filter\n    weights[0] = lambda / (N + lambda);\n    for (int i = 1; i < 2 * N + 1; i++) {\n      weights[i] = 1 / (2 * (N + lambda));\n    }\n\n    // weights for extended state space which includes error variances\n    ext_weights[0] = lambda / (N + M + lambda);\n    for (int i = 1; i < 2 * (N + M) + 1; i++) {\n      ext_weights[i] = 1 / (2 * (N + M + lambda));\n    }\n  }\n\n  /**\n   * @brief predict  \u9884\u6d4b\u51fd\u6570\n   * @param control  input vector\n   */\n  virtual void predict(const VectorXt& control) override\n  {\n    // calculate sigma points\n    this->ensurePositiveFinite(cov);\n    computeSigmaPoints(mean, cov, sigma_points); //\u6839\u636e\u4e0a\u4e00\u65f6\u523b\u7684\u5747\u503c\u548c\u65b9\u5dee\u8ba1\u7b97sigma\u70b9\n    for (int i = 0; i < S; i++) {\n      sigma_points.row(i) = system.f(sigma_points.row(i), control); //\u6839\u636e\u7cfb\u7edf\u65b9\u7a0b\u4f20\u64adsigma\u70b9\n    }\n\n    const auto& Q = process_noise; //\u7cfb\u7edf\u566a\u58f0|\u8fc7\u7a0b\u566a\u58f0\n\n    // unscented transform\n    VectorXt mean_pred(mean.size());\n    MatrixXt cov_pred(cov.rows(), cov.cols());\n\n    mean_pred.setZero();\n    cov_pred.setZero();\n    for (int i = 0; i < S; i++) {\n      mean_pred += weights[i] * sigma_points.row(i);   //\u4f20\u64ad\u540e\u7684sigma\u70b9\u96c6\u5747\u503c\n    }\n    for (int i = 0; i < S; i++) {\n      VectorXt diff = sigma_points.row(i).transpose() - mean_pred;\n      cov_pred += weights[i] * diff * diff.transpose(); //\u4f20\u64ad\u540e\u7684sigma\u70b9\u96c6\u65b9\u5dee\n    }\n    cov_pred += Q;                                      //\u52a0\u4e0a\u8fc7\u7a0b\u566a\u58f0\n\n    //\u5f97\u5230\u9884\u6d4b\u503c\u548c\u9884\u6d4b\u534f\u65b9\u5dee\n    mean = mean_pred;\n    cov = cov_pred;\n  }\n\n  /**\n   * @brief correct      \u6821\u6b63\u51fd\u6570\n   * @param measurement  \u89c2\u6d4b\u503c\n   */\n  virtual void correct(const VectorXt& measurement) override\n  {\n    // create extended state space which includes error variances\n    VectorXt ext_mean_pred = VectorXt::Zero(N + M, 1);\n    MatrixXt ext_cov_pred = MatrixXt::Zero(N + M, N + M);\n    ext_mean_pred.topLeftCorner(N, 1) = VectorXt(mean);\n    ext_cov_pred.topLeftCorner(N, N) = MatrixXt(cov);\n    ext_cov_pred.bottomRightCorner(M, M) = measurement_noise;\n\n    this->ensurePositiveFinite(ext_cov_pred);\n    computeSigmaPoints(ext_mean_pred, ext_cov_pred, ext_sigma_points); //\u6839\u636e\u9884\u6d4b\u5747\u503c\u548c\u534f\u65b9\u5dee\u4ee5\u53ca\u6d4b\u91cf\u566a\u58f0\u8ba1\u7b97sigma\u70b9\n                                                                       //\u6b64\u65f6\u6d4b\u91cf\u8bef\u5dee\u5e76\u672a\u6dfb\u52a0\u5230sigama\u4e3b\u4f53,\u800c\u662f\u5b58\u653e\u4e8e\u62d3\u5c55\u90e8\u5206\n\n    // unscented transform\n    expected_measurements.setZero();\n    for (int i = 0; i < ext_sigma_points.rows(); i++) {\n      expected_measurements.row(i) = system.h(ext_sigma_points.row(i).transpose().topLeftCorner(N, 1));     //\u89c2\u6d4b\u65b9\u7a0b\u4f20\u64adsigama\u70b9\u96c6\n      expected_measurements.row(i) += VectorXt(ext_sigma_points.row(i).transpose().bottomRightCorner(M, 1));//\u6dfb\u52a0\u6d4b\u91cf\u566a\u58f0\n    }\n\n    VectorXt expected_measurement_mean = VectorXt::Zero(M);\n    for (int i = 0; i < ext_sigma_points.rows(); i++) {\n      expected_measurement_mean += ext_weights[i] * expected_measurements.row(i);  //\u4f20\u64ad\u540e\u7684sigama\u70b9\u96c6\u5747\u503c\n    }\n    MatrixXt expected_measurement_cov = MatrixXt::Zero(M, M);\n    for (int i = 0; i < ext_sigma_points.rows(); i++) {\n      VectorXt diff = expected_measurements.row(i).transpose() - expected_measurement_mean;\n      expected_measurement_cov += ext_weights[i] * diff * diff.transpose();        //\u4f20\u64ad\u540e\u7684sigama\u70b9\u96c6\u534f\u65b9\u5dee\n    }\n\n    // calculated transformed covariance\n    MatrixXt sigma = MatrixXt::Zero(N + M, M);\n    for (int i = 0; i < ext_sigma_points.rows(); i++) {\n      auto diffA = (ext_sigma_points.row(i).transpose() - ext_mean_pred);\n      auto diffB = (expected_measurements.row(i).transpose() - expected_measurement_mean);\n      sigma += ext_weights[i] * (diffA * diffB.transpose());\n    }\n\n    kalman_gain = sigma * expected_measurement_cov.inverse();                       //\u8ba1\u7b97\u5361\u5c14\u66fc\u589e\u76ca\n\n    VectorXt ext_mean = ext_mean_pred + kalman_gain * (measurement - expected_measurement_mean); //\u6700\u4f18\u4f30\u8ba1\n    MatrixXt ext_cov = ext_cov_pred - kalman_gain * expected_measurement_cov * kalman_gain.transpose();    //\u6700\u4f18\u4f30\u8ba1\u7684\u534f\u65b9\u5dee\n\n    mean = ext_mean.topLeftCorner(N, 1);\n    cov = ext_cov.topLeftCorner(N, N);\n  }\n\n  const MatrixXt& getSigmaPoints() const { return sigma_points; }\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n  T lambda;\n  const int S; //sigma\u70b9\u4e2a\u6570\n  VectorXt weights;\n  MatrixXt sigma_points;\n  VectorXt ext_weights;\n  MatrixXt ext_sigma_points;\n  MatrixXt expected_measurements;\n\nprivate:\n  /**\n   * @brief compute sigma points\n   * @param mean          mean\n   * @param cov           covariance\n   * @param sigma_points  calculated sigma points\n   */\n  void computeSigmaPoints(const VectorXt& mean, const MatrixXt& cov, MatrixXt& sigma_points) {\n    const int n = mean.size();\n    assert(cov.rows() == n && cov.cols() == n);\n\n    Eigen::LLT<MatrixXt> llt;   //Cholesky\u5206\u89e3\uff0c\u5c06\u5bf9\u79f0\u6b63\u5b9a\u77e9\u9635\u8868\u793a\u6210\u4e00\u4e2a\u4e0b\u4e09\u89d2\u77e9\u9635L\u548c\u5176\u8f6c\u7f6e\u7684\u4e58\u79ef\u7684\u5206\u89e3 M = L*L.transpose()\n    llt.compute((n + lambda) * cov);\n    MatrixXt l = llt.matrixL();\n\n    sigma_points.row(0) = mean;\n    for (int i = 0; i < n; i++) {\n      sigma_points.row(1 + i * 2) = mean + l.col(i);\n      sigma_points.row(1 + i * 2 + 1) = mean - l.col(i);\n    }\n  }\n};\n\n\n#endif\n", "meta": {"hexsha": "f6e94e781d42fec968418a676a42bcfbccedbd8b", "size": 7119, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kalman/unscented_kalman_filter.hpp", "max_stars_repo_name": "CastielLiu/hdl_localization", "max_stars_repo_head_hexsha": "c958f78b0dc2dd2eeb9a50aad9eff0f23e662ab2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/kalman/unscented_kalman_filter.hpp", "max_issues_repo_name": "CastielLiu/hdl_localization", "max_issues_repo_head_hexsha": "c958f78b0dc2dd2eeb9a50aad9eff0f23e662ab2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/kalman/unscented_kalman_filter.hpp", "max_forks_repo_name": "CastielLiu/hdl_localization", "max_forks_repo_head_hexsha": "c958f78b0dc2dd2eeb9a50aad9eff0f23e662ab2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5076923077, "max_line_length": 128, "alphanum_fraction": 0.6481247366, "num_tokens": 2146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6430641141671284}}
{"text": "// std includes\n#include <vector>\n#include <iostream>\n#include <random> // random_device, default_random_engine, uniform_real_distribution\n#include <memory> // shared_ptr\n#include <cmath> // sin, cos\n// thirdparty includes\n#include <Eigen/Dense>\n// lib includes\n#include \"m0sh/uniform.h\"\n#include \"m0sh/structured_sub.h\"\n#include \"p0l/interpolation.h\"\n\nusing TypeScalar = double;\n// Space\nconst unsigned int DIM = 2;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\ntemplate<typename ...Args>\nusing TypeRef = Eigen::Ref<Args...>;\n// Mesh\ntemplate<typename ...Args>\nusing TypeContainer = std::vector<Args...>;\nusing TypeMeshStructured = m0sh::Structured<TypeVector, TypeRef, TypeContainer>;\nusing TypeMeshStructuredSub = m0sh::StructuredSub<TypeVector, TypeRef, TypeContainer>;\nusing TypeMeshStructuredUniform = m0sh::Uniform<TypeVector, TypeRef, TypeContainer>;\n// Data\nconst std::size_t np = 5;\nconst std::size_t n = 100;\nconst double l = 2 * M_PI;\n\ndouble f(const double x, const double y) {\n    return std::cos(x) + std::sin(y);\n}\n\nvoid print(const std::shared_ptr<TypeMeshStructured>& sMesh, const TypeContainer<TypeScalar> q, std::uniform_real_distribution<TypeScalar>& uniform, std::default_random_engine& e) {\n    const TypeVector x = {uniform(e), uniform(e)};\n    const double analy = f(x[0], x[1]);\n    double interp = p0l::lagrangeMeshPoint<TypeMeshStructured, TypeContainer, double, TypeVector, TypeRef, TypeMeshStructuredSub>(sMesh, q, x, np);\n    double error = std::abs(analy - interp);\n    double relative = error / analy;\n    std::cout << \"Interpolation using \" << np << \" grid points (\" << std::pow(np, DIM) << \" points).\" << \" x : \\n\" << x << \"\\n Analy : \" << analy << \" Result : \" << interp << \" | error = \" << error << \" | relative = \" << relative << std::endl;\n}\n\nint main() { \n    // Init\n    std::shared_ptr<TypeMeshStructured> sMesh = std::make_shared<TypeMeshStructuredUniform>(TypeContainer<std::size_t>(DIM, n), TypeContainer<TypeScalar>(DIM, l), TypeVector::Constant(0.0), TypeContainer<bool>(DIM, true));\n    TypeContainer<TypeScalar> q(sMesh->nbPoints());\n    for(std::size_t pointIndex = 0; pointIndex < q.size(); pointIndex++) {\n        TypeVector x = sMesh->positionPoint(pointIndex);\n        q[pointIndex] = f(x[0], x[1]);\n    }\n    // Random setup\n    std::random_device r;\n    std::default_random_engine e(r());\n    std::uniform_real_distribution<TypeScalar> uniform(0, l);\n    // Print\n    print(sMesh, q, uniform, e);\n    print(sMesh, q, uniform, e);\n    print(sMesh, q, uniform, e);\n    print(sMesh, q, uniform, e);\n    print(sMesh, q, uniform, e);\n    print(sMesh, q, uniform, e);\n}\n", "meta": {"hexsha": "9e22bdb96fe84a9654b15e299165bb6d89122bea", "size": 2628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/mesh/main.cpp", "max_stars_repo_name": "C0PEP0D/p0l", "max_stars_repo_head_hexsha": "090bfebd558c98e44ee5ecc583dad198a25e676b", "max_stars_repo_licenses": ["MIT"], "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/mesh/main.cpp", "max_issues_repo_name": "C0PEP0D/p0l", "max_issues_repo_head_hexsha": "090bfebd558c98e44ee5ecc583dad198a25e676b", "max_issues_repo_licenses": ["MIT"], "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/mesh/main.cpp", "max_forks_repo_name": "C0PEP0D/p0l", "max_forks_repo_head_hexsha": "090bfebd558c98e44ee5ecc583dad198a25e676b", "max_forks_repo_licenses": ["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.0625, "max_line_length": 243, "alphanum_fraction": 0.6834094368, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6430579828544801}}
{"text": "/**\n This homework problem consists of reading a simple, gmesh generated, mesh on\n the unit square and solving a simple reaction diffusion system using LehrFEM++\n */\n\n#include <cmath>\n#include <iostream>\n#include <memory>\n\n#include <Eigen/Core>\n\n#include <lf/base/base.h>\n#include <lf/mesh/mesh.h>\n#include <lf/refinement/refinement.h>\n\n#include \"linfereactdiff.h\"\n\nint main() {\n  const lf::base::size_type num_levels = 5;\n  std::shared_ptr<lf::refinement::MeshHierarchy> multi_mesh_p =\n      LinFeReactDiff::generateMeshHierarchy(num_levels);\n  lf::refinement::MeshHierarchy &multi_mesh{*multi_mesh_p};\n  // get pointer to finest mesh used as ground truth\n  std::shared_ptr<const lf::mesh::Mesh> mesh_p =\n      multi_mesh.getMesh(num_levels - 1);\n  Eigen::VectorXd finest_sol = LinFeReactDiff::solveFE(mesh_p);\n  double ground_truth_energy =\n      LinFeReactDiff::computeEnergy(mesh_p, finest_sol);\n\n  // compute error for the other meshes\n  for (int i = 0; i < num_levels - 1; i++) {\n    mesh_p = multi_mesh.getMesh(i);\n    Eigen::VectorXd sol = LinFeReactDiff::solveFE(mesh_p);\n    double energy = LinFeReactDiff::computeEnergy(mesh_p, sol);\n    std::cout << \"Mesh \" << i + 1\n              << \" error: \" << std::abs(energy - ground_truth_energy) << \"\\n\";\n  }\n}\n", "meta": {"hexsha": "c5ebfb4a47981b3195997278efbec138fb2e0a53", "size": 1264, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/LinFeReactDiff/templates/linfereactdiff_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/LinFeReactDiff/templates/linfereactdiff_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/LinFeReactDiff/templates/linfereactdiff_main.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4102564103, "max_line_length": 79, "alphanum_fraction": 0.7009493671, "num_tokens": 332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.643057978106087}}
{"text": "// Author: Daisuke Kanaizumi\n// Affiliation: Department of Applied Mathematics, Waseda University\n\n// verification program for q-Laguerre polynomials\n// References\n\n// Ismail, M. E., & Zhang, R. (2016).\n// Integral and Series Representations of $ q $-Polynomials and Functions: Part I.\n// arXiv preprint arXiv:1604.08441.\n// Y. Chen , M. E. Ismail, & K. A. Muttalib. Asymptotics of basic Bessel functions and q-Laguerre polynomials, Lemma 2\n// Journal of Computational and Applied Mathematics, 54(3), 263-272 (1994).\n\n//Koekoek, R., & Swarttouw, R. F. (1996). The Askey-scheme of hypergeometric orthogonal polynomials and its q-analogue. arXiv preprint math/9602214.\n\n#ifndef QLAGUERRE_HPP\n#define QLAGUERRE_HPP\n \n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/constants.hpp>\n#include <kv/Pochhammer.hpp>\n#include <kv/QHypergeometric.hpp>\n#include <cmath>\n#include <limits>\n#include <kv/convert.hpp> // this was included to use complex numbers\n#include <kv/complex.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/psa.hpp>\nnamespace ub = boost::numeric::ublas;\nnamespace kv {\n  template <class T> complex<interval<T> > qLpoly(const complex<interval<T> >& x,const interval<T>& q,const int n,const complex<interval<T> >& alpha){\n    complex<interval<T> >res,sum;\n    if(n<=1000){\n      sum=0.;\n      for(int k=0;k<=n;k++){\n\tsum=sum+pow(q,alpha*k+k*k)*pow(-x,k)\n\t  /qPochhammer(q,q,k)/qPochhammer(q,q,n-k)/qPochhammer(pow(q,alpha+1),q,k);\n      }\n      sum=sum*qPochhammer(pow(q,alpha+1),q,n);\n      res=sum;\n    }\n    else{\n      ub::vector<complex<interval<T> > >a(1),b(2);\n      a(0)=pow(q,alpha+n+1);\n      b(0)=pow(q,alpha+1);\n      b(1)=-x*pow(q,n+alpha+1);\n      \n      res=qPochhammer(pow(q,alpha+1),q,n)/qPochhammer(q,q,n)\n\t*infinite_qPochhammer(complex<interval<T> >(-x*pow(q,alpha+n+1)),interval<T>(q))\n\t*QHypergeom(ub::vector<complex<interval<T> > >(a),ub::vector<complex<interval<T> > >(b),interval<T>(q),complex<interval<T> >(-x*pow(q,alpha+1)));\n      \n      //std::cout<<QHypergeom(ub::vector<complex<interval<T> > >(a),ub::vector<complex<interval<T> > >(b),interval<T>(q),complex<interval<T> >(-x*pow(q,alpha+1)))<<std::endl;\n    }\n    if((abs(res)).upper()==std::numeric_limits<T>::infinity()){\n      res=infinite_qPochhammer(complex<interval<T> >(-x*pow(q,n+alpha+1)),interval<T> (q))\n\t/infinite_qPochhammer(complex<interval<T> >(pow(q,n+alpha+1)),interval<T> (q))/qPochhammer(q,q,n)\n\t*_1phi_1(complex<interval<T> >(-x),complex<interval<T> >(-x*pow(q,n+alpha+1)),interval<T>(q),complex<interval<T> >(pow(q,alpha+1)));\n    }\n    return res;\n  }\n  template <class T> interval<T>  qLpoly(const interval<T> & x,const interval<T>& q,const int n,const interval<T> & alpha){\n    interval<T> res,sum;\n    if(n<=1000){\n      sum=0.;\n      for(int k=0;k<=n;k++){\n\tsum=sum+pow(q,alpha*k+k*k)*pow(-x,k)\n\t  /qPochhammer(q,q,k)/qPochhammer(q,q,n-k)/qPochhammer(pow(q,alpha+1),q,k);\n      }\n      sum=sum*qPochhammer(pow(q,alpha+1),q,n);\n      res=sum;\n    }\n    else{\n      ub::vector<interval<T>  >a(1),b(2);\n      a(0)=pow(q,alpha+n+1);\n      b(0)=pow(q,alpha+1);\n      b(1)=-x*pow(q,n+alpha+1);\n      \n      res=qPochhammer(pow(q,alpha+1),q,n)/qPochhammer(q,q,n)\n\t*infinite_qPochhammer(interval<T> (-x*pow(q,alpha+n+1)),interval<T>(q))\n\t*QHypergeom(ub::vector<interval<T>  >(a),ub::vector<interval<T>  >(b),interval<T>(q),interval<T> (-x*pow(q,alpha+1)));\n      \n      //std::cout<<QHypergeom(ub::vector<complex<interval<T> > >(a),ub::vector<complex<interval<T> > >(b),interval<T>(q),complex<interval<T> >(-x*pow(q,alpha+1)))<<std::endl;\n    }\n    if((abs(res)).upper()==std::numeric_limits<T>::infinity()){\n      res=infinite_qPochhammer(interval<T> (-x*pow(q,n+alpha+1)),interval<T> (q))\n\t/infinite_qPochhammer(interval<T> (pow(q,n+alpha+1)),interval<T> (q))/qPochhammer(q,q,n)\n\t*_1phi_1(interval<T> (-x),interval<T> (-x*pow(q,n+alpha+1)),interval<T>(q),interval<T> (pow(q,alpha+1)));\n    }\n    return res;\n  }\n  template <class T> interval<T>  qLpoly_psa(const interval<T> & x,const interval<T>& q,const int n,const interval<T> & alpha){\n    interval<T> res;\n    \n    kv::psa<interval<T> >a,b,c;\n    a.v.resize(n+1);\n    b.v.resize(n+1);\n    c.v.resize(n+1);\n    for(int i=0;i<=n;i++){\n      a.v(i)=qPochhammer(-x,q,i)*std::pow(-1,i)*pow(q,i*(i+1)*0.5)*pow(q,alpha*i)/qPochhammer(q,q,i);\n    }\n    for(int j=0;j<=n;j++){\n      b.v(j)=std::pow(-1,j)*pow(q,j*(j-1)*0.5)/qPochhammer(q,q,j);\n    }\n    c=a/b;\n    res=c.v(n);\n    return res;\n}\n  template <class T> interval<T>  qLpoly_rec(const interval<T> & x,const interval<T>& q,const int n,const interval<T> & alpha){\n    interval<T> res,xx;\n    xx=mid(x);\n    ub::vector<interval<T>  >L(2*n);\n    L(0)=1.;\n    L(1)=(1-pow(q,alpha+1))*(1+pow(q,alpha+1)/(1-pow(q,alpha+1))*(-x))/(1-q);\n    for(int i=1;i<=n-1;i++){\n      L(i+1)=((1-pow(q,i+1)+q*(1-pow(q,i+alpha))-pow(q,2*i+alpha+1)*x)*L(i)-q*(1-pow(q,i+alpha))*L(i-1))/(1-pow(q,i+1));\n    }\n  res=L(n);\n  return res;\n  }\n}\n#endif\n", "meta": {"hexsha": "ac7b6b58c7706e8c94d79c50fdef784f48c40fe9", "size": 5005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qLaguerre.hpp", "max_stars_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_stars_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T20:55:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T12:26:00.000Z", "max_issues_repo_path": "qLaguerre.hpp", "max_issues_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_issues_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-03-07T04:32:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-05T01:48:57.000Z", "max_forks_repo_path": "qLaguerre.hpp", "max_forks_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_forks_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6910569106, "max_line_length": 174, "alphanum_fraction": 0.621978022, "num_tokens": 1722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523327, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6430068659567627}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\ninline bool close(double x, double y) \n{ \n    using std::abs;\n    return abs(x - y) < 0.001;\n}\n\nint main(int , char**)\n{\n    using namespace std;\n    using mtl::lazy;\n    \n    double                d, rho, alpha= 7.8, beta, gamma;\n    std::complex<double>  z;\n\n    mtl::dense_vector<double> v(6, 1.0), w(6), r(6, 6.0), q(6, 2.0), x(6);\n    mtl::dense2D<double>      A(6, 6);\n    A= 2.0;\n    mtl::compressed2D<double>      B(6, 6);\n    B= 2.0;\n\n    (lazy(w)= A * v) || (lazy(d) = lazy_dot(w, v));\n    cout << \"w = \" << w << \", d = \" << d << \"\\n\";\n    MTL_THROW_IF(!close(d, 12), mtl::runtime_error(\"wrong dot\"));    \n\n    (lazy(w)= B * v) || (lazy(d) = lazy_dot(w, v));\n    cout << \"w = \" << w << \", d = \" << d << \"\\n\";\n    MTL_THROW_IF(!close(d, 12), mtl::runtime_error(\"wrong dot\"));\n\n    (lazy(r)-= alpha * q) || (lazy(rho)= lazy_unary_dot(r)); \n    cout << \"r = \" << r << \", rho = \" << rho << \"\\n\";\n    MTL_THROW_IF(!close(rho, 552.96), mtl::runtime_error(\"wrong unary_dot\"));\n\n    (lazy(x)= 7.0) || (lazy(beta)= lazy_unary_dot(x)); \n    cout << \"x = \" << x << \", beta = \" << beta << \"\\n\";\n    MTL_THROW_IF(!close(beta, 294), mtl::runtime_error(\"wrong unary_dot\"));\n    \n    (lazy(x)= 7.0) || (lazy(beta)= lazy_one_norm(x)); \n    cout << \"x = \" << x << \", beta = \" << beta << \"\\n\";\n    MTL_THROW_IF(!close(beta, 42), mtl::runtime_error(\"wrong one_norm\"));\n    \n    (lazy(x)= 7.0) || (lazy(beta)= lazy_two_norm(x)); \n    cout << \"x = \" << x << \", beta = \" << beta << \"\\n\";\n    MTL_THROW_IF(!close(beta, 17.1464), mtl::runtime_error(\"wrong two_norm\"));\n    \n    (lazy(x)= 7.0) || (lazy(beta)= lazy_infinity_norm(x)); \n    cout << \"x = \" << x << \", beta = \" << beta << \"\\n\";\n    MTL_THROW_IF(!close(beta, 7), mtl::runtime_error(\"wrong one_norm\"));\n    \n    (lazy(x)= 7.0) || (lazy(beta)= lazy_sum(x)); \n    cout << \"x = \" << x << \", beta = \" << beta << \"\\n\";\n    MTL_THROW_IF(!close(beta, 42), mtl::runtime_error(\"wrong sum\"));\n    \n    (lazy(x)= 7.0) || (lazy(beta)= lazy_product(x)); \n    cout << \"x = \" << x << \", beta = \" << beta << \"\\n\";\n    MTL_THROW_IF(!close(beta, 117649), mtl::runtime_error(\"wrong sum\"));\n    \n    (lazy(x)= 2.0) || (lazy(gamma)= lazy_dot(r, x)); \n    cout << \"x = \" << x << \", gamma = \" << gamma << \"\\n\";\n    MTL_THROW_IF(!close(gamma, -115.2), mtl::runtime_error(\"wrong dot\"));\n    \n    (lazy(r)= alpha * q) || (lazy(rho)= lazy_dot(r, q)); \n    cout << \"r = \" << r << \", rho = \" << rho << \"\\n\";\n    MTL_THROW_IF(!close(rho, 187.2), mtl::runtime_error(\"wrong dot\"));\n\n    (lazy(r)= alpha * q) || (lazy(v)= 8.6 * q) || (lazy(x)= 2.2 * q); \n    cout << \"r = \" << r << \", v = \" << v << \", x = \" << x << \"\\n\";\n    MTL_THROW_IF(!close(r[0], 15.6) || !close(v[0], 17.2) || !close(x[0], 4.4), \n\t\t mtl::runtime_error(\"wrong vector scaling\"));\n\n    return 0;\n}\n", "meta": {"hexsha": "3a2d4f68ed998acd7b0f39d71bdb65d35c60d21a", "size": 3282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/fuse_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/fuse_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/fuse_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 37.724137931, "max_line_length": 94, "alphanum_fraction": 0.521023766, "num_tokens": 1130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6430068483651973}}
{"text": "#ifndef SOPHUS_ROTATION_MATRIX_HPP\n#define SOPHUS_ROTATION_MATRIX_HPP\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\n#include \"types.hpp\"\n\nnamespace Sophus {\n\n// Takes in arbiray square matrix and returns true if it is\n// orthogonal.\ntemplate <class D>\nSOPHUS_FUNC bool isOrthogonal(Eigen::MatrixBase<D> const& R) {\n  using Scalar = typename D::Scalar;\n  static int const N = D::RowsAtCompileTime;\n  static int const M = D::ColsAtCompileTime;\n\n  static_assert(N == M, \"must be a square matrix\");\n  static_assert(N >= 2, \"must have compile time dimension >= 2\");\n\n  return (R * R.transpose() - Matrix<Scalar, N, N>::Identity()).norm() <\n         Constants<Scalar>::epsilon();\n}\n\n// Takes in arbiray square matrix and returns true if it is\n// \"scaled-orthogonal\" with positive determinant.\n//\ntemplate <class D>\nSOPHUS_FUNC bool isScaledOrthogonalAndPositive(Eigen::MatrixBase<D> const& sR) {\n  using Scalar = typename D::Scalar;\n  static int const N = D::RowsAtCompileTime;\n  static int const M = D::ColsAtCompileTime;\n  using std::pow;\n  using std::sqrt;\n\n  Scalar det = sR.determinant();\n\n  if (det <= Scalar(0)) {\n    return false;\n  }\n\n  Scalar scale_sqr = pow(det, Scalar(2. / N));\n\n  static_assert(N == M, \"must be a square matrix\");\n  static_assert(N >= 2, \"must have compile time dimension >= 2\");\n\n  return (sR * sR.transpose() - scale_sqr * Matrix<Scalar, N, N>::Identity())\n             .template lpNorm<Eigen::Infinity>() <\n         sqrt(Constants<Scalar>::epsilon());\n}\n\n// Takes in arbiray square matrix (2x2 or larger) and returns closest\n// orthogonal matrix with positive determinant.\ntemplate <class D>\nSOPHUS_FUNC enable_if_t<\n    std::is_floating_point<typename D::Scalar>::value,\n    Matrix<typename D::Scalar, D::RowsAtCompileTime, D::RowsAtCompileTime>>\nmakeRotationMatrix(Eigen::MatrixBase<D> const& R) {\n  using Scalar = typename D::Scalar;\n  static int const N = D::RowsAtCompileTime;\n  static int const M = D::ColsAtCompileTime;\n\n  static_assert(N == M, \"must be a square matrix\");\n  static_assert(N >= 2, \"must have compile time dimension >= 2\");\n\n  Eigen::JacobiSVD<Matrix<Scalar, N, N>> svd(\n      R, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n  // Determine determinant of orthogonal matrix U*V'.\n  Scalar d = (svd.matrixU() * svd.matrixV().transpose()).determinant();\n  // Starting from the identity matrix D, set the last entry to d (+1 or\n  // -1),  so that det(U*D*V') = 1.\n  Matrix<Scalar, N, N> Diag = Matrix<Scalar, N, N>::Identity();\n  Diag(N - 1, N - 1) = d;\n  return svd.matrixU() * Diag * svd.matrixV().transpose();\n}\n\n}  // namespace Sophus\n\n#endif  // SOPHUS_ROTATION_MATRIX_HPP\n", "meta": {"hexsha": "3bea28325404146fd650037e91b3b8694167b134", "size": 2623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sophus/rotation_matrix.hpp", "max_stars_repo_name": "jian-li/sophus", "max_stars_repo_head_hexsha": "13fb3288311485dc94e3226b69c9b59cd06ff94e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 127.0, "max_stars_repo_stars_event_min_datetime": "2019-04-23T07:06:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:36:37.000Z", "max_issues_repo_path": "sophus/rotation_matrix.hpp", "max_issues_repo_name": "jian-li/sophus", "max_issues_repo_head_hexsha": "13fb3288311485dc94e3226b69c9b59cd06ff94e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-06-29T15:05:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T23:32:29.000Z", "max_forks_repo_path": "sophus/rotation_matrix.hpp", "max_forks_repo_name": "jian-li/sophus", "max_forks_repo_head_hexsha": "13fb3288311485dc94e3226b69c9b59cd06ff94e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T18:51:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T01:54:06.000Z", "avg_line_length": 31.987804878, "max_line_length": 80, "alphanum_fraction": 0.6877621045, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.642990701641583}}
{"text": "#include <aslam/cameras/Triangulation.hpp>\n#include <Eigen/Dense>\n\nnamespace aslam {\nnamespace cameras {\n\nvoid triangulate(const Eigen::Vector3d & point1, const Eigen::Vector3d & ray1,\n                 const Eigen::Vector3d & point2, const Eigen::Vector3d & ray2,\n                 Eigen::Vector3d & outTriangulatedPoint, double & outGap,\n                 double & outS1, double & outS2) {\n\n  Eigen::Vector3d t12 = point2 - point1;\n\n  Eigen::Vector2d b;\n  b[0] = t12.dot(ray1);\n  b[1] = t12.dot(ray2);\n  Eigen::Matrix2d A;\n  A(0, 0) = ray1.dot(ray1);\n  A(1, 0) = ray1.dot(ray2);\n  A(0, 1) = -A(1, 0);\n  A(1, 1) = -ray2.dot(ray2);\n  Eigen::Vector2d lambda = A.inverse() * b;\n  Eigen::Vector3d xm = point1 + lambda[0] * ray1;\n  Eigen::Vector3d xn = point2 + lambda[1] * ray2;\n  t12 = (xm - xn);\n\n  outGap = t12.norm();\n  outTriangulatedPoint = xn + 0.5 * t12;\n  outS1 = lambda[0];\n  outS2 = lambda[1];\n\n}\n\n}  // namespace cameras\n}  // namespace aslam\n", "meta": {"hexsha": "b72d80c0e7f48aa830d3f19b25413054b88f047e", "size": 949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_cv/aslam_cameras/src/Triangulation.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": "aslam_cv/aslam_cameras/src/Triangulation.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": "aslam_cv/aslam_cameras/src/Triangulation.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": 26.3611111111, "max_line_length": 78, "alphanum_fraction": 0.6080084299, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6429906922168972}}
{"text": "#include <iostream>\n#include <functional>\n\n#include <Eigen/Dense>\n#include <EigenRand/EigenRand>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n\tRand::Vmt19937_64 urng{4212};\n\tVector4f mean{0, 1, 2, 3};\n\tMatrix4f cov;\n\tcov << 1, 1, 0, 0,\n\t\t1, 2, 0, 0,\n\t\t0, 0, 3, 1,\n\t\t0, 0, 1, 2;\n\n\t// constructs MvNormalGen with Scalar=float, Dim=4\n\tRand::MvNormalGen<float, 4> gen1{mean, cov};\n\n\t// or you can use `make-` helper function. It can deduce the type of generator to be created.\n\tauto gen2 = Rand::makeMvNormGen(mean, cov);\n\n\t// generates one sample ( shape (4, 1) )\n\tVector4f sample = gen1.generate(urng);\n\n\t// generates 10 samples ( shape (4, 10) )\n\tMatrixXf samples = gen1.generate(urng, 10);\n\t// or you can just use `MatrixXf` type\n\n\tcout << sample << endl;\n\tcout << samples << endl;\n\n\tRand::StdNormalGen<float> stdnorm;\n\tfor (int i = 0; i < 10; ++i)\n\t{\n\t\tcout << stdnorm.generate<Matrix<float, 4, -1>>(4, 1, urng) << endl;\n\t};\n};\n", "meta": {"hexsha": "5c0918ab13b15d51a9231beec54227cfb1e1bd04", "size": 943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Multivariate/normal/src.cpp", "max_stars_repo_name": "kilasuelika/EigenRand", "max_stars_repo_head_hexsha": "ef8acc146340c39a8cd06166c0f8ac5772d3f071", "max_stars_repo_licenses": ["MIT"], "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/Multivariate/normal/src.cpp", "max_issues_repo_name": "kilasuelika/EigenRand", "max_issues_repo_head_hexsha": "ef8acc146340c39a8cd06166c0f8ac5772d3f071", "max_issues_repo_licenses": ["MIT"], "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/Multivariate/normal/src.cpp", "max_forks_repo_name": "kilasuelika/EigenRand", "max_forks_repo_head_hexsha": "ef8acc146340c39a8cd06166c0f8ac5772d3f071", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-28T22:52:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T22:52:38.000Z", "avg_line_length": 22.4523809524, "max_line_length": 94, "alphanum_fraction": 0.6479321315, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.642990690856648}}
{"text": "//\n// Created by cheyulin on 12/17/16.\n//\n\n#include <cassert>\n\n#include <boost/type_traits.hpp>\n#include <boost/mpl/arithmetic.hpp>\n#include <boost/mpl/logical.hpp>\n#include <boost/mpl/comparison.hpp>\n#include <boost/mpl/next_prior.hpp>\n#include <boost/mpl/if.hpp>\n\nusing namespace boost;\nusing namespace boost::mpl;\n\nvoid DemoIntegerUsage() {\n    using i2=int_<2>;\n    using s2=integral_c<short, 2>;\n\n    assert(i2::value == 2);\n    assert(i2::value == s2::value);\n\n    assert((is_same<i2::type, i2>::value));\n    assert((is_same<s2::value_type, short>::value));\n\n    assert(i2::next::value == 3);\n    assert(prior<s2>::type::value == 1);\n\n    i2 two1;\n    s2 two2;\n    int i = two1 + two2;\n    assert(i == int_<4>());\n}\n\nvoid DemoBoolUsage() {\n    assert(true_::value == true);\n    assert(false_::value == false);\n\n    assert((is_same<true_::type, bool_<true>>::value));\n    assert((is_same<false_::value_type, bool>::value));\n}\n\nvoid DemoCalculation() {\n    using i2= int_<2>;\n    using i5= int_<5>;\n    using i7= int_<7>;\n\n    assert((plus<i2, i5, i7>::type::value == 14));\n    assert((equal_to<minus<i7, i5>::type, i2>::type::value));\n\n    assert((less<i2, i7>::type::value));\n    assert((is_same<greater<i5, i2>::type, true_>::value));\n\n    assert((not_<and_<true_, false_>::type>::type::value));\n    assert((or_<true_, false_>::type()));\n}\n\nvoid DemoBranching() {\n    using mdata1= if_c<true, int, long>::type;\n    assert((is_same<mdata1, int>::value));\n\n    using mdata2= if_<false_, float, double>::type;\n    assert((is_same<mdata2, double>::value));\n\n    using mdata3 = if_<is_integral<mdata2>, integral_promotion<mdata2>::type, floating_point_promotion<mdata2>::type>::type;\n    assert((is_same<mdata3, double>::value));\n}\n\nvoid DemoEvalBranching() {\n    using mdata1=eval_if_c<true, identity<int>, identity<long>>::type;\n    assert((is_same<mdata1, int>::value));\n\n    using mdata2=eval_if<false_, identity<float>, identity<double>>::type;\n    assert((is_same<mdata2, double>::value));\n\n    using mdata3= eval_if<is_integral<mdata2>, integral_promotion<mdata2>, floating_point_promotion<mdata2>>::type;\n    assert((is_same<mdata3, double>::value));\n}\n\nint main() {\n    DemoIntegerUsage();\n    DemoBoolUsage();\n    DemoCalculation();\n    DemoBranching();\n    DemoEvalBranching();\n}", "meta": {"hexsha": "b06d5049bd4cfbe1958eef52fb47a1cb96494328", "size": 2292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MetaProgrammingLib/mpl_basics_demo.cpp", "max_stars_repo_name": "YcheLanguageStudio/STL-Study", "max_stars_repo_head_hexsha": "ac8ad4ef2c3b381b40c29f63ffc651550ec0949a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-02-07T07:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-29T06:01:51.000Z", "max_issues_repo_path": "MetaProgrammingLib/mpl_basics_demo.cpp", "max_issues_repo_name": "CheYulin/STL-Study", "max_issues_repo_head_hexsha": "ac8ad4ef2c3b381b40c29f63ffc651550ec0949a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MetaProgrammingLib/mpl_basics_demo.cpp", "max_forks_repo_name": "CheYulin/STL-Study", "max_forks_repo_head_hexsha": "ac8ad4ef2c3b381b40c29f63ffc651550ec0949a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-11T09:46:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T04:55:54.000Z", "avg_line_length": 26.3448275862, "max_line_length": 124, "alphanum_fraction": 0.6509598604, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.642990690200788}}
{"text": "/*--\r\n  Open3DMotion \r\n  Copyright (c) 2004-2012.\r\n  All rights reserved.\r\n  See LICENSE.txt for more information.\r\n--*/\r\n\r\n#include \"Open3DMotion/Maths/Matrix3x3.h\"\r\n\r\n#ifndef OPEN3DMOTION_LINEAR_ALGEBRA_EIGEN\r\nextern \"C\"\r\n{\r\n#include <f2clibs/f2c.h>\r\n#include <clapack.h>\r\n}\r\n#else\r\n#include <Eigen/Dense>\r\n#include <Eigen/SVD>\r\n#endif\r\n\r\nnamespace Open3DMotion\r\n{\r\n\tvoid Matrix3x3::SVD(double* U, double* s, double* VT, const double* A)\r\n  {\r\n#ifndef OPEN3DMOTION_LINEAR_ALGEBRA_EIGEN\r\n    long three(3);\r\n    Matrix3x3 Acpy(A);\r\n    long lwork(256);\r\n    double work[256];\r\n    long info(0);\r\n\r\n    // use lapack routine\r\n    // - note U and VT are swapped\r\n    // - this is because of the fortran column-major\r\n    //   ordering for matrices - it turns out that\r\n    //   using a row major matrix here corresponds to\r\n    //   swapping U and VT\r\n    dgesvd_(\r\n      \"A\",  // all of U\r\n      \"A\",  // all of VT\r\n      &three, // rows\r\n      &three, // cols\r\n      Acpy,   // input/output matrix\r\n      &three, // leading dimension of Acpy\r\n      s,      // singular values\r\n      VT,      // left orthonormal matrix\r\n      &three, // leading dimension of left\r\n      U,      // right orthonormal matrix\r\n      &three, // leading dimension of right \r\n      work,   // workspace\r\n      &lwork, // size of workspace\r\n      &info);   // returned error codes\r\n    \r\n#else\r\n\t\tEigen::Map< const Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > _A(A, 3, 3);\r\n    Eigen::Map< Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > _U(U, 3, 3);\r\n    Eigen::Map< Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > _VT(VT, 3, 3);\r\n    Eigen::Map< Eigen::Matrix<double, 3, 1> > _s(s, 3, 1);\r\n    Eigen::JacobiSVD< Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > svd(_A, Eigen::ComputeFullU | Eigen::ComputeFullV);\r\n    _U = svd.matrixU();\r\n    _VT = svd.matrixV().transpose();\r\n    _s = svd.singularValues();\r\n#endif\r\n\r\n  }\r\n}\r\n\r\n", "meta": {"hexsha": "c665d3553b74ef2be155eeb781b5e531fbf309a3", "size": 1906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Maths/Matrix3x3.cpp", "max_stars_repo_name": "mitkof6/BTKCore", "max_stars_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_stars_repo_licenses": ["Barr", "Unlicense"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-04-21T20:40:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:35:03.000Z", "max_issues_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Maths/Matrix3x3.cpp", "max_issues_repo_name": "mitkof6/BTKCore", "max_issues_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_issues_repo_licenses": ["Barr", "Unlicense"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2018-03-11T15:14:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T18:13:48.000Z", "max_forks_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Maths/Matrix3x3.cpp", "max_forks_repo_name": "mitkof6/BTKCore", "max_forks_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_forks_repo_licenses": ["Barr", "Unlicense"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2015-05-11T11:04:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T20:37:04.000Z", "avg_line_length": 28.0294117647, "max_line_length": 121, "alphanum_fraction": 0.5960125918, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.6429906800717128}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <cstdlib>\n#include <ctime>\n#include <sys/time.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <cfloat>\n\n#include \"time_bench.hpp\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::ublas;\nusing namespace boost::numeric;\n\ntemplate <class T>\ninline double norm(ublas::vector<T> v){\n  /* \u30d9\u30af\u30c8\u30eb\u306e\u30ce\u30eb\u30e0\u3092\u8a08\u7b97\u3059\u308b */\n  double sum = 0;\n  for(unsigned int i = 0; i < v.size(); ++i){\n    sum += v[i] * v[i];\n  }\n  return sqrt(sum);\n}\n\ntemplate <class T>\ninline double dist(ublas::vector<T> x, ublas::vector<T> y){\n  /* \u30d9\u30af\u30c8\u30eb\u306e\u30ce\u30eb\u30e0\u304b\u3089\u8ddd\u96e2\u3092\u5b9a\u7fa9 */\n  ublas::vector<T> v = x - y;\n  return norm(v); \n}\n\ninline double dist(ublas::matrix<double> mat1, unsigned int r1,\n\t\t   ublas::matrix<double> mat2, unsigned int r2){\n  /* mat1\u306er1\u884c\u76ee\u306e\u30d9\u30af\u30c8\u30eb\u3068, mat2\u306er2\u884c\u76ee\u306e\u30d9\u30af\u30c8\u30eb\u306e\u8ddd\u96e2\u3092\u8a08\u7b97 */\n  if(mat1.size2() != mat2.size2()){\n    return -1;\n  }else{\n    double sum = 0;\n    for(unsigned int i = 0; i < mat1.size2(); ++i){\n      sum += (mat1(r1, i) - mat2(r2, i)) * (mat1(r1, i) - mat2(r2, i));\n    }\n    return sqrt(sum);\n  }\n}\n\ntemplate <class T>\ninline unsigned int argmin(ublas::vector<T> v){\n  if(v.empty()){ return -1; /* \u30a8\u30e9\u30fc */    \n  }else{\n    int argmin = 0; T minval = v[argmin];\n    for(unsigned int i = 0; i < v.size(); ++i){\n      if(v[i] < minval){\n\targmin = i; minval = v[i];\n      }\n    }\n    return argmin;\n  }\n}\n\ntemplate <class T>\ninline unsigned int argmax(ublas::vector<T> v){\n  if(v.empty()){ return -1; /* \u30a8\u30e9\u30fc */    \n  }else{\n    int argmax = 0; T maxval = v[argmax];\n    for(unsigned int i = 0; i < v.size(); ++i){\n      if(v[i] > maxval){\n\targmax = i; maxval = v[i];\n      }\n    }\n    return argmax;\n  }\n}\n\n\ntemplate <class T>\ninline T min(ublas::vector<T> v){\n  if(v.empty()){ return -1; /* \u30a8\u30e9\u30fc */    \n  }else{\n    T minval = v[0];\n    for(unsigned int i = 0; i < v.size(); ++i){\n      if(v.at(i) < minval){\t\n\tminval = v.at(i);\n      }\n    }\n    return minval;\n  }\n}\n\ntemplate <class T>\ninline T min2(ublas::vector<T> v){\n  /* vector v\u306e\u8981\u7d20\u30672\u756a\u76ee\u306b\u5c0f\u3055\u3044\u8981\u7d20\u3092\u898b\u3064\u3051\u308b */\n  if(v.size() < 2){ return -1; /* \u30a8\u30e9\u30fc */\n  }else{\n    T min1 = v[0], min2 = v[1];\n    if(min1 > min2){ /* swap \u3059\u308b */\n      T temp = min1; min1 = min2; min2 = temp;\n    }\n    for(unsigned int i = 2; i < v.size(); ++i){\n      if(v[i] <= min1){       /* \u6700\u5c0f\u5024\u304c\u767a\u898b\u3055\u308c\u305f */\n\tmin2 = min1; min1 = v[i];\t\n      }else if(v[i] <= min2){ /* \u6e96\u6700\u5c0f\u5024\u304c\u767a\u898b\u3055\u308c\u305f */\n\tmin2 = v[i];\n      }\n    }\n    return min2;\n  }\n}\ninline void Hamerly_update_ul(const unsigned int n, const unsigned int k,\n\t\t\t      const ublas::matrix <double> data,\n\t\t\t      const ublas::matrix <double> c,       /* \u30af\u30e9\u30b9\u30bf\u306e\u91cd\u5fc3 */\n\t\t\t      const ublas::vector <unsigned int> a, /* \u5404\u70b9x_i\u304c\u5c5e\u3059\u308b\u30af\u30e9\u30b9\u30bf */\n\t\t\t      ublas::vector<double> &u,            /* upper bound */\n\t\t\t      ublas::vector<double> &l             /* lower bound */){\n  ublas::vector<double> dist_xc(k, 0); /* x[i] \u3068\u30af\u30e9\u30b9\u30bf\u30fc\u4e2d\u5fc3\u3068\u306e\u8ddd\u96e2*/\n  for(unsigned int i = 0; i < n; ++i){\n    for(unsigned int j = 0; j < k; ++j){\n      dist_xc[j] = dist(data, i, c, j);\n    }\n    u[i] = dist_xc[a[i]]; /* u[i] = d(x[i], c[a[i]])*/\n    l[i] = min2(dist_xc); /* l[i] = min2_j d(x[i], c[j]) */\n    /* l\u306fx[i]\u304b\u30892\u756a\u76ee\u306b\u8fd1\u3044\u30af\u30e9\u30b9\u30bf\u91cd\u5fc3\u307e\u3067\u306e\u8ddd\u96e2 */\n    //cerr << i << \": \" << u[i] << \"\\t\" << l[i] << \"\\t\" << dist_xc << endl;\n  }\n  //cerr << u << endl;\n  //cerr << l << endl;\n  return;\n}\n\nbool Hamerly_repeat(const unsigned int n, const unsigned int d, const unsigned int k,\n\t\t    const ublas::matrix <double> data,\n\t\t    ublas::vector<unsigned int> &q, /* \u30af\u30e9\u30b9\u30bf\u4e2d\u306e\u70b9\u306e\u6570 */\n\t\t    ublas::matrix<double> &c,       /* \u30af\u30e9\u30b9\u30bf\u306e\u91cd\u5fc3 */\n\t\t    ublas::matrix<double> &c_sum,   /* \u30af\u30e9\u30b9\u30bf\u306e\u30d9\u30af\u30c8\u30eb\u548c*/\n\t\t    ublas::vector<double> &s,       /* \u6700\u8fd1\u63a5\u30af\u30e9\u30b9\u30bf\u306e\u91cd\u5fc3\u3068\u306e\u8ddd\u96e2 */\n\t\t    ublas::vector<unsigned int> &a, /* \u5404\u70b9x_i\u304c\u5c5e\u3059\u308b\u30af\u30e9\u30b9\u30bf */\n\t\t    ublas::vector<double> &u,       /* upper bound */\n\t\t    ublas::vector<double> &l        /* lower bound */){\n  /* Hamerly\u306e\u7e70\u308a\u8fd4\u3057\u30b9\u30c6\u30c3\u30d7 \u30af\u30e9\u30b9\u30bf\u91cd\u5fc3\u306e\u66f4\u65b0\u306e\u6709\u7121\u3092boolean\u3067\u8fd4\u3059 */\n  /* \u3053\u306e\u7e70\u308a\u8fd4\u3057\u30b9\u30c6\u30c3\u30d7\u3067\u4f55\u3089\u304b\u306e\u66f4\u65b0\u304c\u3042\u3063\u305f\u304b */\n  volatile bool updated = false;\n\n  /* \u30af\u30e9\u30b9\u30bf\u30fc\u4e2d\u5fc3\u306e\u5909\u5316\u304c\u3042\u3063\u305f\u304b */\n  ublas::vector<bool> cluster_unchanged(k, true);\n\n  /* \u307e\u305as[j]\u3092\u66f4\u65b0 \n   * s[j] = min_{jj != j} dist(c[jj], c[j])\n   *      = min2_jj dist(c[j], c[jj]) */   \n  for(unsigned int j = 0; j < k; ++j){\n    ublas::vector<double> distance(k, 0);\n    for(unsigned int jj = 0; jj < k; ++jj){\n      distance[jj] = dist(c, j, c, jj);\n    }\n    s[j] = min2(distance);\n  }\n\n  //cerr << \"s: \" << s << endl;\n  \n  /* \u5404\u70b9x[i]\u306b\u3064\u3044\u3066\uff0cHamerly\u306e\u547d\u984c\u306e\u6761\u4ef6\u3092\u307f\u305f\u3059\u304b\u78ba\u8a8d\u3057\u306a\u304c\u3089\n   * (\u3064\u307e\u308a\uff0c\u9069\u5b9c\u679d\u5208\u308a\u3092\u5b9f\u884c\u3057\u306a\u304c\u3089)\n   * \u6700\u8fd1\u63a5\u30af\u30e9\u30b9\u30bf\u306e\u518d\u5272\u5f53\u3066\u3092\u884c\u3046 \n   * \u540c\u6642\u306b\uff0c\u306e\u3061\u306e\u30af\u30e9\u30b9\u30bf\u91cd\u5fc3\u306e\u66f4\u65b0\u306e\u305f\u3081\u306b\n   * c_sum[], q[] \u3092\u6b63\u3057\u3044\u5024\u306b\u4fdd\u3064 */\n  for(unsigned int i = 0; i < n; ++i){\n    double m = max((s[a[i]] / 2.0), l[i]);\n    //cerr << \"i = \" << i << \", m = \" << m << \", u[i] = \" << u[i] << endl;\n    if(u[i] > m){     /* Hamerly\u306e\u547d\u984c\u306e\u6761\u4ef6\u3092\u6e80\u305f\u3055\u306a\u3044 */\n      //cerr << i << u[i] << \" -> \";\n      u[i] = dist(data,i,c,a[i]);  /* upper bound\u3092\u53b3\u5bc6\u306a\u5024\u306b\u66f4\u65b0 */\n      //cerr << u[i] << endl;\n      if(u[i] > m){   /* Hamerly\u306e\u547d\u984c\u306e\u6761\u4ef6\u3092\u6e80\u305f\u3055\u306a\u3044 */\n\tunsigned int aa = a[i]; /* \u6700\u8fd1\u63a5\u30af\u30e9\u30b9\u30bf\u304c\u5909\u5316\u3057\u305f\u304b\u8abf\u3079\u308b */\n\t{ /* \u6700\u8fd1\u63a5\u30af\u30e9\u30b9\u30bf\u3092\u518d\u8a08\u7b97 */\n\t  ublas::vector<double> distance(k);\n\t  for(unsigned int j = 0; j < k; ++j){\n\t    distance[j] = dist(data,i,c,j);\n\t  }\n\t  a[i] = argmin(distance);\n\t}\n\tif(aa != a[i]){ /* \u6700\u8fd1\u63a5\u30af\u30e9\u30b9\u30bf\u306e\u5909\u5316\u306b\u3088\u308b\u30d1\u30e9\u30e1\u30bf\u306e\u66f4\u65b0*/\n\t  /* \u70b9x[i]\u306e\u6700\u8fd1\u63a5\u30af\u30e9\u30b9\u30bf\u306f\uff0caa \u304b\u3089 a[i] \u306b\u5909\u5316\u3057\u305f */\n\t  updated = true; /* \u3053\u306e\u7e70\u308a\u8fd4\u3057\u30b9\u30c6\u30c3\u30d7\u66f4\u65b0\u304c\u3042\u3063\u305f */\n\t  /* \u5f8c\u306e\u30af\u30e9\u30b9\u30bf\u30fc\u91cd\u5fc3\u306e\u66f4\u65b0\u306e\u305f\u3081\u306b q, c_sum \u306e\u66f4\u65b0\u304c\u5fc5\u8981 \n\t   * \u540c\u6642\u306b\u3001\u66f4\u65b0\u304c\u3042\u3063\u305f\u30af\u30e9\u30b9\u30bf\u30fc\u306eindex\u3092\u30e1\u30e2\u3057\u3066\u304a\u304f */\n\t  row(c_sum,aa)   -= row(data,i); q[aa]--;\n\t  row(c_sum,a[i]) += row(data,i); q[a[i]]++;\n\t  cluster_unchanged[aa] = false;\n\t  cluster_unchanged[a[i]] = false;\n\t  {\n\t    ublas::vector<double> dist_xc(k, 0);\n\t    /* x[i] \u3068\u30af\u30e9\u30b9\u30bf\u30fc\u4e2d\u5fc3\u3068\u306e\u8ddd\u96e2*/\n\t    for(unsigned int j = 0; j < k; ++j){\n\t      dist_xc[j] = dist(data, i, c, j);\n\t    }\n\t    u[i] = dist_xc[a[i]]; /* u[i] = d(x[i], c[a[i]])*/\n\t    l[i] = min2(dist_xc); /* l[i] = min2_j d(x[i], c[j]) */\n\t  }\n\t}\n      }\n    }\n  }\n\n  ublas::matrix<double> c_prev = c; /* \u5909\u5316\u524d\u306e\u30af\u30e9\u30b9\u30bf\u91cd\u5fc3 */\n  if(updated){ /* \u3044\u305a\u308c\u304b\u306e\u30c7\u30fc\u30bf\u70b9\u306e\u6700\u8fd1\u63a5\u30af\u30e9\u30b9\u30bf\u304c\u5909\u5316\u3057\u305f\u5834\u5408 */\n    ublas::vector<double> p(k, 0); /* \u5404\u30af\u30e9\u30b9\u30bf\u306e\u91cd\u5fc3\u306e\u79fb\u52d5\u8ddd\u96e2 */\n    for(unsigned int j = 0; j < k; ++j){\n      if(!cluster_unchanged[j]){ /* j\u756a\u76ee\u306e\u30af\u30e9\u30b9\u30bf\u91cd\u5fc3\u304c\u79fb\u52d5\u3057\u3066\u3044\u305f\u5834\u5408 */\n\trow(c,j) = row(c_sum,j) / q[j]; /* \u30af\u30e9\u30b9\u30bf\u91cd\u5fc3\u3092\u66f4\u65b0 */\n\tp[j] = dist(c_prev, j, c, j); /* \u30af\u30e9\u30b9\u30bf\u30fc\u91cd\u5fc3\u306e\u79fb\u52d5\u8ddd\u96e2 */\n      }\n    }\n    unsigned int r = argmax(p);\n    for(unsigned int i = 0; i < n; ++i){\n      u[i] += p[a[i]];  l[i] -= p[r];\n    }\n  }\n\n  return updated; /* \u30c7\u30fc\u30bf\u70b9\u306e\u6700\u8fd1\u63a5\u30af\u30e9\u30b9\u30bf\u306b\u5909\u5316\u304c\u3042\u3063\u305f\u304b\u3092\u8fd4\u3059 */\n}\n\nvoid Hamerly_init(const unsigned int n, const unsigned int d, const unsigned int k,\n\t\t  const ublas::matrix <double> data,\n\t\t  ublas::vector<unsigned int> &q,   /* \u30af\u30e9\u30b9\u30bf\u4e2d\u306e\u70b9\u306e\u6570 */\n\t\t  ublas::matrix<double> &c,         /* \u30af\u30e9\u30b9\u30bf\u306e\u91cd\u5fc3 */\n\t\t  ublas::matrix<double> &c_sum,     /* \u30af\u30e9\u30b9\u30bf\u306e\u30d9\u30af\u30c8\u30eb\u548c*/\n\t\t  ublas::vector<unsigned int> &a,   /* \u5404\u70b9x_i\u304c\u5c5e\u3059\u308b\u30af\u30e9\u30b9\u30bf */\n\t\t  ublas::vector<double> &u,         /* upper bound */\n\t\t  ublas::vector<double> &l          /* lower bound */){\n  /* \u5404\u30af\u30e9\u30b9\u30bf\u306e\u4ee3\u8868\u70b9\u3092\u30e9\u30f3\u30c0\u30e0\u306b\u9078\u629e */\n  for(unsigned int j = 0; j < k; ++j){\n    ublas::zero_vector<double> zero(d);\n    row(c,j) = row(data, j);\n    /* j\u756a\u76ee\u306e\u30af\u30e9\u30b9\u30bf\u4e2d\u5fc3\u3092j\u756a\u76ee\u306e\u30c7\u30fc\u30bf\u70b9\u3068\u4e00\u81f4\u3055\u305b\u3066\u521d\u671f\u5316\u3057\u305f */\n  }\n\n  /* \u5168\u3066\u306e\u30c7\u30fc\u30bf\u70b9\u306b\u3064\u3044\u3066\uff0c\u521d\u671f\u30af\u30e9\u30b9\u30bfa[i]\u3092\u8a08\u7b97 */\n  for(unsigned int i = 0; i < n; ++i){\n    { /* argmin_j dist(x(i), c(j))\u306e\u8a08\u7b97 */\n      ublas::vector<double> distance(k);\n      for(unsigned int j = 0; j < k; ++j){\n\tdistance[j] = dist(data,i,c,j);\n      }\n      a[i] = argmin(distance);\n    }\n    /* \u30af\u30e9\u30b9\u30bf\u5185\u306e\u70b9\u306e\u6570\uff0c\u30af\u30e9\u30b9\u30bf\u306e\u70b9\u306e\u30d9\u30af\u30c8\u30eb\u548c\u3082\u66f4\u65b0 */\n    q[a[i]]++;  row(c_sum,a[i]) += row(data,i);    \n  }\n  \n  /* upper bound, lower bound \u306e\u66f4\u65b0 */\n  Hamerly_update_ul(n, k, data, c, a, u, l);\n\n  /* \u521d\u671f\u30af\u30e9\u30b9\u30bf\u4e2d\u5fc3\u306b\u5bfe\u3059\u308b\u30c7\u30fc\u30bf\u5272\u308a\u5f53\u3066\u306b\u5bfe\u5fdc\u3057\u3066\uff0c\n   * \u30af\u30e9\u30b9\u30bf\u30fc\u4e2d\u5fc3\u306e\u66f4\u65b0\u3084\uff0c\u5404\u30c7\u30fc\u30bf\u70b9\u306eu[i],l[i]\u306e\u66f4\u65b0\u304c\u5fc5\u8981 */\n  \n  ublas::matrix<double> c_prev = c; /* \u5909\u5316\u524d\u306e\u30af\u30e9\u30b9\u30bf\u91cd\u5fc3 */\n\n  ublas::vector<double> p(k, 0); /* \u5404\u30af\u30e9\u30b9\u30bf\u306e\u91cd\u5fc3\u306e\u79fb\u52d5\u8ddd\u96e2 */\n  for(unsigned int j = 0; j < k; ++j){  \n    row(c,j) = row(c_sum,j) / q[j]; /* \u30af\u30e9\u30b9\u30bf\u91cd\u5fc3\u3092\u66f4\u65b0 */\n    p[j] = dist(c_prev, j, c, j); /* \u30af\u30e9\u30b9\u30bf\u30fc\u91cd\u5fc3\u306e\u79fb\u52d5\u8ddd\u96e2 */\n  }\n  unsigned int r = argmax(p);\n\n  for(unsigned int i = 0; i < n; ++i){\n    u[i] += p[a[i]];  l[i] -= p[r];\n  }\n\n  \n  return;\n}\n\ndouble Hamerly_sqerr(const unsigned int n, const unsigned int k,\n\t\t     const ublas::matrix<double>data,\n\t\t     const ublas::matrix<double> c,       /* \u30af\u30e9\u30b9\u30bf\u306e\u91cd\u5fc3 */\n\t\t     const ublas::vector<unsigned int> a  /* \u5404\u70b9x_i\u304c\u5c5e\u3059\u308b\u30af\u30e9\u30b9\u30bf */){\n  /* \u30af\u30e9\u30b9\u30bf\u30ea\u30f3\u30b0\u7d50\u679c\u306b\u57fa\u3065\u304d\u4e8c\u4e57\u5e73\u5747\u4e8c\u4e57\u8aa4\u5dee\u3092\u8a08\u7b97\u3057\u3066\u8fd4\u3059 */\n  double sum = 0;\n  for(unsigned int i = 0; i < n; ++i){\n    sum += dist(data,i,c,a[i]) * dist(data,i,c,a[i]);\n  }\n  return (sum / n);\n}\n\n\nvoid Hamerly(const unsigned int n, const unsigned int d, const unsigned int k,\n\t     const ublas::matrix<double> data){\n  if(n < k){\n    cerr << \"data size n is smaller than cluster size d\" << endl;\n    exit(1);\n  }else{\n    struct timeval t_start, t_end;\n    gettimeofday(&t_start, NULL); /* \u6642\u9593\u8a08\u6e2c\u958b\u59cb */\n\n    /* j\u756a\u76ee\u306e\u30af\u30e9\u30b9\u30bf\u3092\u4e3b\u8a9e\u3068\u3059\u308b\u8a18\u53f7  */\n    ublas::vector<unsigned int> q(k,0); /* \u30af\u30e9\u30b9\u30bf\u4e2d\u306e\u70b9\u306e\u6570 */\n    ublas::matrix<double> c(k,d,0);     /* \u30af\u30e9\u30b9\u30bf\u306e\u91cd\u5fc3 */\n    ublas::matrix<double> c_sum(k,d,0); /* \u30af\u30e9\u30b9\u30bf\u4e2d\u306e\u30d9\u30af\u30c8\u30eb\u306e\u7dcf\u548c */\n    ublas::vector<double> s(k,0);       /* \u6700\u8fd1\u63a5\u30af\u30e9\u30b9\u30bf\u306e\u91cd\u5fc3\u3068\u306e\u8ddd\u96e2 */\n    \n    /* i\u756a\u76ee\u306e\u30c7\u30fc\u30bf\u70b9\u3092\u4e3b\u8a9e\u3068\u3059\u308b\u8a18\u53f7 */\n    ublas::vector<unsigned int> a(n, 0);  /* \u5404\u70b9x_i\u304c\u5c5e\u3059\u308b\u30af\u30e9\u30b9\u30bf */\n    ublas::vector<double> u(n, 0);        /* upper bound */\n    ublas::vector<double> l(n, 0);        /* lower bound */   \n\n    Hamerly_init(n, d, k, data, q, c, c_sum, a, u, l);\n\n    int t = 0; /* \u7e70\u308a\u8fd4\u3057\u30b9\u30c6\u30c3\u30d7\u3092\u4f55\u56de\u7e70\u308a\u8fd4\u3057\u305f\u304b */\n    \n    //cerr << \"a: \" << a << \": t = \" << t << endl;\n    \n    while(Hamerly_repeat(n, d, k, data, q, c, c_sum, s, a, u, l)){\n      t++;\n      //cerr << \"a: \" << a << \": t = \" << t << endl;\n    }\n    t++; /* \u66f4\u65b0\u3055\u308c\u306a\u304b\u3063\u305f\u6700\u5f8c\u306e1\u56de\u3082\u5b9f\u884c\u3055\u308c\u3066\u3044\u308b */\n\n    gettimeofday(&t_end, NULL); /* \u6642\u9593\u8a08\u6e2c\u7d42\u4e86 */\n\n\n    { /* \u7d50\u679c\u3092\u51fa\u529b */\n      ofstream fs(\"Hamerly_\"\n\t\t  + std::to_string(n) + \"_\"\n\t\t  + std::to_string(d) + \"_\"\n\t\t  + std::to_string(k) + \".txt\");\n      if(fs.fail()){ exit(1); }\n      fs << \"a: \" << a << endl;\n      fs << c << endl;\n      fs.close();\n    }\n    \n    cout << n << \"\\t\"                               /* \u30b5\u30f3\u30d7\u30eb\u6570 */\n\t << d << \"\\t\"                               /* \u6b21\u5143 */\n      \t << k << \"\\t\"                               /* \u30af\u30e9\u30b9\u30bf\u6570 */\n\t << diff_timeval(t_start, t_end) << \"\\t\"    /* \u5b9f\u884c\u6642\u9593(us) */\n\t << Hamerly_sqerr(n, k, data, c, a) << \"\\t\" /* \u5e73\u5747\u4e8c\u4e57\u8aa4\u5dee */\n\t << t << endl;                              /* \u7e70\u308a\u8fd4\u3057\u56de\u6570*/\n\n    return;\n  }\n}\n\nint main(int argc, char *argv[]){\n  if(argc < 5){\n    cerr << \"usage: \" << argv[0]\n\t << \" <n: data num> <d: dimension> <k: cluster num> <data file>\" << endl;\n    exit(1);\n  }else{\n    unsigned int n = atoi(argv[1]), d = atoi(argv[2]), k = atoi(argv[3]);\n    char *file = argv[4];\n    ublas::matrix<double> data(n, d); /* n\u500b\u306ed\u6b21\u5143\u30c7\u30fc\u30bf\u3092\u8aad\u307f\u8fbc\u3080 */\n    {\n      ifstream fs(file);\n      if(fs.fail()){ exit(1); }\n      for(unsigned int i = 0; i < n; ++i){\n\tfor(unsigned int j = 0; j < d; ++j){\n\t  fs >> data(i,j);\n\t}\n      }\n      fs.close();\n    }\n    Hamerly(n, d, k, data);\n    return 0;\n  }\n}\n", "meta": {"hexsha": "eae01a45a57fe2507d711bf68d0c533e9a9dd604", "size": 10773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "program_old/Hamerly.cpp", "max_stars_repo_name": "yk-tanigawa/201503_clustering", "max_stars_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "program_old/Hamerly.cpp", "max_issues_repo_name": "yk-tanigawa/201503_clustering", "max_issues_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-26T16:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-26T16:53:14.000Z", "max_forks_repo_path": "program_old/Hamerly.cpp", "max_forks_repo_name": "yk-tanigawa/201503_clustering", "max_forks_repo_head_hexsha": "43a11e707c08f1576e5765824c74330b6730e7e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9596774194, "max_line_length": 85, "alphanum_fraction": 0.5298431263, "num_tokens": 4438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6429323465885483}}
{"text": "#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n\nint main() {\n    //\n    // check multiprecision/doc/html/boost_multiprecision/tut/ints/cpp_int.html\n    // for checked & unchecked types\n    //\n\n    // integer number type\n    using boost::multiprecision::cpp_int;   // unlimited precision\n    using boost::multiprecision::int1024_t;\n    using boost::multiprecision::uint1024_t;\n\n    using boost::multiprecision::checked_cpp_int;\n    using boost::multiprecision::checked_int1024_t;\n    using boost::multiprecision::checked_uint1024_t;\n\n    // rational number type\n    using boost::multiprecision::cpp_rational;\n\n    // floating point number type\n    using boost::multiprecision::cpp_dec_float_100;\n    using cpp_dec_float_200 = boost::multiprecision::number < boost::multiprecision::cpp_dec_float < 200 > > ;\n\n\n    //\n    // real code below\n    //\n\n    // calculate factorial of 50\n    cpp_int factorial{ 1 };\n    // cpp_int factorial{ \"1\" }; also works\n    for (cpp_int i{ 1 }; i <= 50; ++i)\n        factorial *= i;\n\n    std::cout << \"Factorial of 50 is\\n\\t\" << factorial << \"\\n\\n\";\n\n\n    cpp_rational rational{ cpp_int{ 321 }, cpp_int{ 123 } };\n    // cpp_rational rational{ \"321/123\" }; also works\n    rational *= 10;\n    // print 50 numbers of rational\n    std::cout << rational << \" is \\n\\t\"\n        << rational.convert_to<cpp_dec_float_100>().str(50) << \"\\n\\n\";\n\n\n    // calculate square root of 2\n    std::cout << \"sqrt(2)\\n\\t\"\n        << std::setprecision(std::numeric_limits<cpp_dec_float_200>::digits10)\n        << boost::multiprecision::sqrt(cpp_dec_float_200{ 2 });\n}\n", "meta": {"hexsha": "27265fcb8996ea8800e07c29664b8f3f66954883", "size": 1645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/MultiprecisionExamples.cpp", "max_stars_repo_name": "so61pi/examples", "max_stars_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-01T07:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T00:05:06.000Z", "max_issues_repo_path": "cpp/MultiprecisionExamples.cpp", "max_issues_repo_name": "so61pi/examples", "max_issues_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-02-24T13:04:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T10:19:48.000Z", "max_forks_repo_path": "cpp/MultiprecisionExamples.cpp", "max_forks_repo_name": "so61pi/examples", "max_forks_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-30T07:29:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-30T07:29:58.000Z", "avg_line_length": 29.9090909091, "max_line_length": 110, "alphanum_fraction": 0.6601823708, "num_tokens": 437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6429323272138647}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n#include <time.h>\n#include \"re3q3/re3q3.h\"\n\n#define TEST(FUNC) if(!FUNC()) { std::cout << #FUNC\"\\033[1m\\033[31m FAILED!\\033[0m\\n\"; } else { std::cout << #FUNC\"\\033[1m\\033[32m PASSED!\\033[0m\\n\"; passed++;} num_tests++; \n#define REQUIRE(COND) if(!(COND)) { std::cout << \"Failure: \"#COND\" was not satisfied.\\n\"; return false; }\n\n\nvoid compute_equation_residuals(const Eigen::Matrix<double, 3, 10> & coeffs, const Eigen::Matrix<double, 3, 8> & solution, int n_sols, double res[8]) {\n\tEigen::Matrix<double, 10, 1> mons;\n\n\tfor (int i = 0; i < n_sols; i++) {\n\t\tdouble x = solution(0, i);\n\t\tdouble y = solution(1, i);\n\t\tdouble z = solution(2, i);\n\t\tmons << x * x, x* y, x* z, y* y, y* z, z* z, x, y, z, 1.0;\n\t\tEigen::Matrix<double, 3, 1> residuals = coeffs * mons;\n\t\tres[i] = residuals.cwiseAbs().maxCoeff();\n\t}\n}\n\nbool verify_solutions(const Eigen::Matrix<double, 3, 10> &coeffs,\n\t\t\t\t\tconst Eigen::Matrix<double, 3, 8> &solutions,\n\t\t\t\t\tint n_sols, double tol) {\n\tbool ok = true;\n\n\tdouble res[8];\n\tcompute_equation_residuals(coeffs, solutions, n_sols, res);\n\n\tfor (int i = 0; i < n_sols; i++) {\t\t\n\t\tok &= res[i] < tol;\n\t}\n\treturn ok;\n}\n\n\nbool test_random_coefficients() {\n\tEigen::Matrix<double, 3, 10> coeffs;\n\tEigen::Matrix<double, 3, 8> solutions;\n\n\tcoeffs.setRandom();\n\n\t//std::cout << \"coeffs: \" << coeffs << \"\\n\";\n\n\tint n_sols = re3q3::re3q3(coeffs, &solutions);\n\t\n\treturn verify_solutions(coeffs, solutions, n_sols, 1e-8);\n}\n\n\nbool test_degenerate_for_x() {\n\tEigen::Matrix<double, 3, 10> coeffs;\n\tEigen::Matrix<double, 3, 8> solutions;\n\n\tcoeffs.setRandom();\n\tcoeffs.col(3) = 0.5 * (coeffs.col(5) + coeffs.col(4));\n\n\tint n_sols = re3q3::re3q3(coeffs, &solutions);\n\n\treturn verify_solutions(coeffs, solutions, n_sols, 1e-8);\n}\n\n\nbool test_degenerate_for_y() {\n\tEigen::Matrix<double, 3, 10> coeffs;\n\tEigen::Matrix<double, 3, 8> solutions;\n\n\tcoeffs.setRandom();\n\tcoeffs.col(0) = 0.5 * (coeffs.col(5) + coeffs.col(2));\n\n\tint n_sols = re3q3::re3q3(coeffs, &solutions);\n\n\treturn verify_solutions(coeffs, solutions, n_sols, 1e-8);\n}\n\nbool test_degenerate_for_z() {\n\tEigen::Matrix<double, 3, 10> coeffs;\n\tEigen::Matrix<double, 3, 8> solutions;\n\n\tcoeffs.setRandom();\n\tcoeffs.col(0) = 0.5 * (coeffs.col(1) + coeffs.col(3));\n\n\tint n_sols = re3q3::re3q3(coeffs, &solutions);\n\n\treturn verify_solutions(coeffs, solutions, n_sols, 1e-8);\n}\n\nbool test_degenerate_for_xy() {\n\tEigen::Matrix<double, 3, 10> coeffs;\n\tEigen::Matrix<double, 3, 8> solutions;\n\n\tcoeffs.setRandom();\n\tcoeffs.col(0) = 0.5 * (coeffs.col(5) + coeffs.col(2));\n\tcoeffs.col(3) = 0.5 * (coeffs.col(5) + coeffs.col(4));\n\n\tint n_sols = re3q3::re3q3(coeffs, &solutions);\n\n\treturn verify_solutions(coeffs, solutions, n_sols, 1e-8);\n}\n\n\nbool test_pure_squares() {\n\tEigen::Matrix<double, 3, 10> coeffs;\n\tEigen::Matrix<double, 3, 8> solutions;\n\n\tcoeffs.setZero();\n\tcoeffs(0, 0) = 1.0;\n\tcoeffs(0, 9) = -1.0;\n\tcoeffs(1, 3) = 1.0;\n\tcoeffs(1, 9) = -1.0;\n\tcoeffs(2, 5) = 1.0;\n\tcoeffs(2, 9) = -1.0;\n\t\t\n\tint ok = 0;\n\n\t// We run multiple tests here since the change of variables is random.\n\tfor(int test = 0; test < 1000; ++test) {\n\t\tint n_sols = re3q3::re3q3(coeffs, &solutions);\n\t\t\n\n\t\tREQUIRE(n_sols == 8);\n\n\t\tif(verify_solutions(coeffs, solutions, n_sols, 1e-8))\n\t\t\t++ok;\n\t}\t\n\treturn ok == 1000;\n}\n\nbool benchmark_random_coeffs() {\n\n\tstd::vector<double> residuals;\n\tresiduals.reserve(10000 * 8);\n\n\tfor (int iter = 0; iter < 10000; ++iter) {\n\t\tEigen::Matrix<double, 3, 10> coeffs;\n\t\tEigen::Matrix<double, 3, 8> solutions;\n\t\tcoeffs.setRandom();\n\t\t\n\t\tint n_sols = re3q3::re3q3(coeffs, &solutions);\n\n\t\tdouble res[8];\n\t\tcompute_equation_residuals(coeffs, solutions, n_sols, res);\n\t\tfor (int i = 0; i < n_sols; ++i)\n\t\t\tresiduals.push_back(std::log10(res[i]));\n\t}\n\n\n\tstd::sort(residuals.begin(), residuals.end());\n\n\tdouble q90 = residuals[static_cast<int>(residuals.size() * 0.90)];\n\tdouble q95 = residuals[static_cast<int>(residuals.size() * 0.95)];\n\tdouble q99 = residuals[static_cast<int>(residuals.size() * 0.99)];\n\n\n\tstd::cout << \"q90: \" << q90 << \", q95: \" << q95 << \", q99: \" << q99 << \"\\n\";\n\t\n\treturn q99 < -6;\n}\n\n\nbool benchmark_degen_rotation_homogeneous() {\n\n\tstd::vector<double> residuals;\n\tresiduals.reserve(10000 * 8);\n\n\tEigen::Matrix<double, 3, 10> coeffs;\n\tEigen::Matrix<double, 3, 9> Rcoeffs;\n\tEigen::Matrix<double, 4, 8> solutions;\n\n\tfor (int iter = 0; iter < 10000; ++iter) {\n\n\t\t// Generate random 180 degree rotation\n\t\tEigen::Quaterniond q_gt;\n\t\tq_gt.coeffs().setRandom();\n\t\tq_gt.coeffs()(0) = 0.0;\n\t\tq_gt.coeffs().normalize();\n\n\t\t// Problem is x1'*R*x2 = 0\n\t\t// => kron(x2',x1') * vec(R) = 0\n\n\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\tEigen::Vector3d x1, x2, v;\n\t\t\tx2.setRandom().normalize();\n\t\t\tv.setRandom();\n\t\t\tx1 = v.cross(q_gt.toRotationMatrix() * x2).normalized();\n\n\t\t\tRcoeffs.row(i) << x2(0) * x1.transpose(), x2(1)* x1.transpose(), x2(2)* x1.transpose();\n\t\t}\n\n\t\t\n\t\tint n_sols = re3q3::re3q3_rotation(Rcoeffs, &solutions);\n\t\t\n\t\tdouble res = 1.0;\t\t\n\t\tfor (int i = 0; i < n_sols; ++i) {\t\t\t\n\t\t\tEigen::Vector4d q = solutions.col(i);\n\t\t\tEigen::Matrix3d R = Eigen::Quaterniond(q).toRotationMatrix();\t\t\t\n\t\t\tres = std::min(res, (R - q_gt.toRotationMatrix()).norm());\n\t\t}\n\t\tresiduals.push_back(std::log10(res));\n\t}\n\n\n\tstd::sort(residuals.begin(), residuals.end());\n\n\tdouble q90 = residuals[static_cast<int>(residuals.size() * 0.90)];\n\tdouble q95 = residuals[static_cast<int>(residuals.size() * 0.95)];\n\tdouble q99 = residuals[static_cast<int>(residuals.size() * 0.99)];\n\n\n\tstd::cout << \"q90: \" << q90 << \", q95: \" << q95 << \", q99: \" << q99 << \"\\n\";\n\n\treturn q99 < -6;\n}\n\n\nbool benchmark_degen_rotation_inhomogeneous() {\n\n\tstd::vector<double> residuals;\n\tresiduals.reserve(10000 * 8);\n\n\tEigen::Matrix<double, 3, 10> coeffs;\n\tEigen::Matrix<double, 3, 10> Rcoeffs;\n\tEigen::Matrix<double, 4, 8> solutions;\n\n\tfor (int iter = 0; iter < 10000; ++iter) {\n\n\t\t// Generate random 180 degree rotation\n\t\tEigen::Quaterniond q_gt;\n\t\tq_gt.coeffs().setRandom();\n\t\tq_gt.coeffs()(0) = 0.0;\n\t\tq_gt.coeffs().normalize();\n\n\t\t// Problem is x1'*R*x2 = d\n\t\t// => kron(x2',x1') * vec(R) = d\n\n\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\tEigen::Vector3d x1, x2, v;\n\t\t\tx2.setRandom().normalize();\n\t\t\tx1.setRandom().normalize();\n\t\t\tdouble d = -x1.dot(q_gt.toRotationMatrix() * x2);\n\t\t\tRcoeffs.row(i) << x2(0) * x1.transpose(), x2(1)* x1.transpose(), x2(2)* x1.transpose(), d;\n\t\t}\n\n\n\t\tint n_sols = re3q3::re3q3_rotation(Rcoeffs, &solutions);\n\n\t\tdouble res = 1.0;\n\t\tfor (int i = 0; i < n_sols; ++i) {\n\t\t\tEigen::Vector4d q = solutions.col(i);\n\t\t\tEigen::Matrix3d R = Eigen::Quaterniond(q).toRotationMatrix();\n\t\t\tres = std::min(res, (R - q_gt.toRotationMatrix()).norm());\n\t\t}\n\t\tresiduals.push_back(std::log10(res));\n\t}\n\n\n\tstd::sort(residuals.begin(), residuals.end());\n\n\tdouble q90 = residuals[static_cast<int>(residuals.size() * 0.90)];\n\tdouble q95 = residuals[static_cast<int>(residuals.size() * 0.95)];\n\tdouble q99 = residuals[static_cast<int>(residuals.size() * 0.99)];\n\n\n\tstd::cout << \"q90: \" << q90 << \", q95: \" << q95 << \", q99: \" << q99 << \"\\n\";\n\n\treturn q99 < -6;\n}\n\nint main() {\n\t\n\tunsigned int seed = (unsigned int)time(0);\t\t\n\tsrand(seed);\n\n\tstd::cout << \"Running tests... (seed = \" << seed << \")\\n\\n\";\n\n\tint passed = 0;\n\tint num_tests = 0;\n\t\n\tTEST(test_random_coefficients);\n\tTEST(test_degenerate_for_x);\n\tTEST(test_degenerate_for_y);\n\tTEST(test_degenerate_for_z);\n\tTEST(test_degenerate_for_xy);\n\tTEST(test_pure_squares);\n\tTEST(benchmark_random_coeffs);\n\tTEST(benchmark_degen_rotation_homogeneous);\n\tTEST(benchmark_degen_rotation_inhomogeneous);\n\n\tstd::cout << \"\\nDone! Passed \" << passed << \"/\" << num_tests << \" tests.\\n\";\n}\n", "meta": {"hexsha": "33ed9b211319ac2c0b6a20f1fe42f845334e8cf3", "size": 7598, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test_re3q3.cc", "max_stars_repo_name": "vlarsson/re3q3", "max_stars_repo_head_hexsha": "ab03d271f0a30f516f052d750773b0277898751f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T09:30:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T10:14:01.000Z", "max_issues_repo_path": "test_re3q3.cc", "max_issues_repo_name": "vlarsson/re3q3", "max_issues_repo_head_hexsha": "ab03d271f0a30f516f052d750773b0277898751f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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_re3q3.cc", "max_forks_repo_name": "vlarsson/re3q3", "max_forks_repo_head_hexsha": "ab03d271f0a30f516f052d750773b0277898751f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-18T06:19:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-18T06:19:02.000Z", "avg_line_length": 25.9317406143, "max_line_length": 174, "alphanum_fraction": 0.6385891024, "num_tokens": 2666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6429323173593013}}
{"text": "//!\n//! Contains the interface for the multivariate Gaussian distribution.\n//!\n//! \\file distrib/multigaussian.hpp\n//! \\author Alistair Reid\n//! \\date April 2014\n//! \\license Affero General Public License version 3 or later\n//! \\copyright (c) 2014, NICTA\n//!\n\n#pragma once\n\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n\nnamespace obsidian\n{\n  namespace distrib\n  {\n    //! Represents a multivariate Gaussian distribution.\n    //!\n    struct MultiGaussian\n    {\n      //! Create a multivariate Gaussian distribution.\n      //!\n      //! \\param mu The means of each dimension of the distribution.\n      //! \\param sigma The covariance matrix.\n      //!\n      MultiGaussian(const Eigen::VectorXd& mu, const Eigen::MatrixXd& sigma);\n\n      //! Create a multivariate Gaussian distribution.\n      //!\n      //! \\param mu The means of each dimension of the distribution.\n      //! \\param sigma The covariance matrix.\n      //! \\param w, h The shape of the distribution.\n      //!\n      MultiGaussian(const Eigen::VectorXd& mu, const Eigen::MatrixXd& sigma, int w, int h);\n\n      //! The means of each dimension.\n      Eigen::VectorXd mu;\n      Eigen::MatrixXd sigLInv;\n      Eigen::MatrixXd sigL;\n\n      //! The covariance matrix.\n      Eigen::MatrixXd sigma;\n\n      //! The shape of the distribution.\n      std::pair<uint, uint> shape;\n    };\n\n    //! \n    MultiGaussian coupledGaussianBlock(const Eigen::MatrixXd& mean, double coupledSD, double decoupledSD);\n\n    double crankNicolsonLogPDF(const Eigen::VectorXd& theta, const MultiGaussian& input, const Eigen::VectorXd& thetaMin, const Eigen::VectorXd& thetaMax, const double& ro);\n\n    //! Compute the log PDF of a multivariate Gaussian distribution\n    double logPDF(const Eigen::MatrixXd& theta, const MultiGaussian& input, const Eigen::MatrixXd& thetaMin,\n                  const Eigen::MatrixXd& thetaMax);\n\n    //! Compute the log PDF of a multivariate Gaussian distribution\n    double logPDF(const Eigen::VectorXd& theta, const MultiGaussian& input, const Eigen::VectorXd& thetaMin,\n                  const Eigen::VectorXd& thetaMax);\n\n    double uniformLogPDF(const Eigen::MatrixXd& theta, const MultiGaussian& input, const Eigen::MatrixXd& thetaMins,\n                         const Eigen::MatrixXd& thetaMaxs);\n\n    //! Draw a sample from a multivariate Gaussian distribution.\n    //\n    Eigen::MatrixXd drawValues(const MultiGaussian &input, std::mt19937 &gen);\n\n    //! Draw a sample from a multivariate Gaussian distribution.\n    //\n    std::vector<Eigen::MatrixXd> drawFrom(const std::vector<distrib::MultiGaussian>& prior, std::mt19937& gen,\n                                          const std::vector<Eigen::MatrixXd>& mins, const std::vector<Eigen::MatrixXd>& maxs,\n                                          const std::vector<bool>& uniformFlags);\n\n    //! Draw a sample from a multivariate Gaussian distribution.\n    //\n    std::vector<Eigen::VectorXd> drawVectorFrom(const std::vector<distrib::MultiGaussian>& prior, std::mt19937& gen,\n                                                const std::vector<Eigen::VectorXd>& mins, const std::vector<Eigen::VectorXd>& maxs);\n\n  }\n}\n", "meta": {"hexsha": "1eb8a8a06029089f0666183be47eeff7e895bf2a", "size": 3204, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/distrib/multigaussian.hpp", "max_stars_repo_name": "divad-nhok/obsidian_fork", "max_stars_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-08T16:28:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T14:55:59.000Z", "max_issues_repo_path": "src/distrib/multigaussian.hpp", "max_issues_repo_name": "divad-nhok/obsidian_fork", "max_issues_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-16T00:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-16T00:46:58.000Z", "max_forks_repo_path": "src/distrib/multigaussian.hpp", "max_forks_repo_name": "divad-nhok/obsidian_fork", "max_forks_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-02-26T01:03:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T02:31:37.000Z", "avg_line_length": 36.8275862069, "max_line_length": 173, "alphanum_fraction": 0.654494382, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6428272573476204}}
{"text": "//==============================================================================\n//         Copyright 2015 J.T. Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#include <boost/simd/arithmetic/include/functions/tenpower.hpp>\n#include <boost/dispatch/functor/meta/call.hpp>\n#include <nt2/sdk/unit/tests/ulp.hpp>\n#include <nt2/sdk/unit/tests/type_expr.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/oneo_10.hpp>\n#include <boost/simd/include/constants/zero.hpp>\n#include <boost/simd/include/constants/mone.hpp>\n#include <boost/simd/include/constants/hundred.hpp>\n#include <boost/simd/include/functions/sqr.hpp>\n\n\nNT2_TEST_CASE_TPL ( tenpower_unsigned_int, BOOST_SIMD_UNSIGNED_TYPES)\n{\n\n  using boost::simd::tenpower;\n  using boost::simd::tag::tenpower_;\n  typedef typename boost::dispatch::meta::call<tenpower_(T)>::type r_t;\n  typedef typename boost::dispatch::meta::as_floating<T>::type  wished_r_t;\n\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::One<T>()), boost::simd::Ten<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Two<T>()), boost::simd::Hundred<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Zero<T>()), boost::simd::One<r_t>(), 0.5);\n} // end of test for unsigned_int_\n\nNT2_TEST_CASE_TPL ( tenpower_signed_int,  BOOST_SIMD_INTEGRAL_SIGNED_TYPES)\n{\n\n  using boost::simd::tenpower;\n  using boost::simd::tag::tenpower_;\n  typedef typename boost::dispatch::meta::call<tenpower_(T)>::type r_t;\n  typedef typename boost::dispatch::meta::as_floating<T>::type  wished_r_t;\n\n  NT2_TEST_TYPE_IS(r_t, wished_r_t);\n\n  // specific values tests\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Mone<T>()), boost::simd::Oneo_10<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::One<T>()), boost::simd::Ten<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Two<T>()), boost::simd::Hundred<r_t>(), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Mtwo<T>()), boost::simd::sqr(boost::simd::Oneo_10<r_t>()), 0.5);\n  NT2_TEST_ULP_EQUAL(tenpower(boost::simd::Zero<T>()), boost::simd::One<r_t>(), 0.5);\n} // end of test for signed_int_\n", "meta": {"hexsha": "53777dcb8ae48656941bb8c54a6ee4702be978c5", "size": 2432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/unit/arithmetic/scalar/tenpower.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/unit/arithmetic/scalar/tenpower.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/unit/arithmetic/scalar/tenpower.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 45.037037037, "max_line_length": 107, "alphanum_fraction": 0.6689967105, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.642795657000302}}
{"text": "#include <Eigen/Dense>\n\ntemplate<typename T>\nDenseMatrix<T>::DenseMatrix(int m, int n)\n{\n    data = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Zero(m, n);\n}\n\ntemplate<typename T>\nDenseMatrix<T>::DenseMatrix(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& data_):\ndata(data_)\n{\n\n}\n\ntemplate<typename T>\nDenseMatrix<T>::DenseMatrix(const DenseMatrix<T>& B):\ndata(B.copy())\n{\n\n}\n\ntemplate<typename T>\nDenseMatrix<T>& DenseMatrix<T>::operator=(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& data_)\n{\n    if (&data != &data_) data = data_;\n\n    return *this;\n}\n\ntemplate<typename T>\nDenseMatrix<T>& DenseMatrix<T>::operator=(const DenseMatrix<T>& B)\n{\n    if (this != &B) data = B.copy();\n\n    return *this;\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::identity(int m, int n)\n{\n    return DenseMatrix<T>(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Identity(m, n));\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::ones(int m, int n)\n{\n    return DenseMatrix<T>(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Ones(m, n));\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::constant(int m, int n, const T& x)\n{\n    return DenseMatrix<T>(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Constant(m, n, x));\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::random(int m, int n)\n{\n    return DenseMatrix<T>(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Random(m, n));\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::transpose() const\n{\n    return DenseMatrix<T>(data.transpose());\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::conjugate() const\n{\n    return DenseMatrix<T>(data.conjugate());\n}\n\ntemplate<typename T>\nint DenseMatrix<T>::nRows() const\n{\n    return (int)data.rows();\n}\n\ntemplate<typename T>\nint DenseMatrix<T>::nCols() const\n{\n    return (int)data.cols();\n}\n\ntemplate<typename T>\ndouble DenseMatrix<T>::norm(int n) const\n{\n    if (n == 0) return data.template lpNorm<Eigen::Infinity>();\n    else if (n == 1) return data.template lpNorm<1>();\n    return data.norm();\n}\n\ntemplate<typename T>\ndouble DenseMatrix<T>::rank() const\n{\n    Eigen::ColPivHouseholderQR<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> qr(data);\n    return qr.rank();\n}\n\ntemplate<typename T>\nT DenseMatrix<T>::sum() const\n{\n    return data.sum();\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::subMatrix(int r0, int r1, int c0, int c1) const\n{\n    return DenseMatrix<T>(data.block(r0, c0, r1 - r0, c1 - c0));\n}\n\ntemplate<typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> DenseMatrix<T>::copy() const\n{\n    return data;\n}\n\ntemplate<typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& DenseMatrix<T>::toEigen()\n{\n    return data;\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::operator*(const T& s)\n{\n    return DenseMatrix<T>(data*s);\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::operator+(DenseMatrix<T> *B)\n{\n    return DenseMatrix<T>(data + B->data);\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::operator-(DenseMatrix<T> *B)\n{\n    return DenseMatrix<T>(data - B->data);\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::operator*(DenseMatrix<T> *B)\n{\n    return DenseMatrix<T>(data*B->data);\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::operator-()\n{\n    return DenseMatrix<T>(data*T(-1.0));\n}\n\ntemplate<typename T>\nvoid DenseMatrix<T>::operator*=(const T& s)\n{\n    data *= s;\n}\n\ntemplate<typename T>\nvoid DenseMatrix<T>::operator+=(DenseMatrix<T> *B)\n{\n    data += B->data;\n}\n\ntemplate<typename T>\nvoid DenseMatrix<T>::operator-=(DenseMatrix<T> *B)\n{\n    data -= B->data;\n}\n\ntemplate<typename T>\nT DenseMatrix<T>::get(int r, int c) const\n{\n    return data(r, c);\n}\n\ntemplate<typename T>\nvoid DenseMatrix<T>::set(int r, int c, const T& s)\n{\n    data(r, c) = s;\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::hcat(DenseMatrix<T> *B)\n{\n    int m = data.rows();\n    int n1 = data.cols();\n    int n2 = B->data.cols();\n    DenseMatrix<T> C(m, n1 + n2);\n    \n    for (int i = 0; i < m; i++) {\n        for (int j = 0; j < n1; j++) {\n            C.set(i, j, data(i, j));\n        }\n        \n        for (int j = 0; j < n2; j++) {\n            C.set(i, n1 + j, B->data(i, j));\n        }\n    }\n    \n    return C;\n}\n\ntemplate<typename T>\nDenseMatrix<T> DenseMatrix<T>::vcat(DenseMatrix<T> *B)\n{\n    int m1 = data.rows();\n    int m2 = B->data.rows();\n    int n = data.cols();\n    DenseMatrix<T> C(m1 + m2, n);\n    \n    for (int j = 0; j < n; j++) {\n        for (int i = 0; i < m1; i++) {\n            C.set(i, j, data(i, j));\n        }\n        \n        for (int i = 0; i < m2; i++) {\n            C.set(m1 + i, j, B->data(i, j));\n        }\n    }\n    \n    return C;\n}\n", "meta": {"hexsha": "3988e93872658a42d7b90b1c00212c8bc15a78b6", "size": 4690, "ext": "inl", "lang": "C++", "max_stars_repo_path": "c++/eigen-wrapper/DenseMatrix.inl", "max_stars_repo_name": "rohan-sawhney/linear-algebra-js", "max_stars_repo_head_hexsha": "439411af400e2d58384ed3dd88e00d0eb4effeaa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 65.0, "max_stars_repo_stars_event_min_datetime": "2017-09-12T22:37:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T21:15:53.000Z", "max_issues_repo_path": "c++/eigen-wrapper/DenseMatrix.inl", "max_issues_repo_name": "amandaghassaei/linear-algebra-js", "max_issues_repo_head_hexsha": "8cdd36ddecbce49118bd0c9ecbafb8a6cf92de07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-02-15T17:51:00.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-16T11:34:14.000Z", "max_forks_repo_path": "c++/eigen-wrapper/DenseMatrix.inl", "max_forks_repo_name": "amandaghassaei/linear-algebra-js", "max_forks_repo_head_hexsha": "8cdd36ddecbce49118bd0c9ecbafb8a6cf92de07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-12T19:26:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-16T00:41:34.000Z", "avg_line_length": 20.6607929515, "max_line_length": 104, "alphanum_fraction": 0.6253731343, "num_tokens": 1363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6427956312531635}}
{"text": "/* **********************************************************************\n * Demonstration code for NPDE lecture & homeworks\n ********************************************************************** */\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(int, char **) {\n  cout << \"Demonstration of initialization of sparse matrix in eigen\" << endl;\n\n  /* SAM_LISTING_BEGIN_1 */\n  const int n = 20, m = 10;\n  // Set up zero sparse matrix with row major storage format\n  // This format is essential for being able to set the maximal\n  // number of non-zero entries \\textbf{per row}.\n  Eigen::SparseMatrix<int, Eigen::RowMajor> X(n, m);\n  // Reserve space for at most nnz\\_row non-zero entries per row\n  const std::size_t nnz_row = 3;\n  X.reserve(Eigen::VectorXi::Constant(n, nnz_row));\n  // Initialize nnz\\_row  entries per row\n  for (int row_idx = 0; row_idx < n; ++row_idx) {\n    for (int k = 0; k < nnz_row; ++k) {\n      X.coeffRef(row_idx, (row_idx * k) % m) += 1;\n    }\n  }\n  /* SAM_LISTING_END_1 */\n  Eigen::MatrixXi X_dense = X;\n  cout << \"Matrix X = \" << endl << X_dense << endl;\n  return 0;\n}\n", "meta": {"hexsha": "648421d9990b03bd52ea5865f67e54210b990421", "size": 1163, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lecturecodes/EigenSparseMatrix/eigensparseinit.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T10:59:19.000Z", "max_issues_repo_path": "lecturecodes/EigenSparseMatrix/eigensparseinit.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lecturecodes/EigenSparseMatrix/eigensparseinit.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2285714286, "max_line_length": 78, "alphanum_fraction": 0.5743766122, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594353, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6427956292714493}}
{"text": "/*\n * solvers.cpp\n *\n *  Created on: Sep 29, 2016\n *      Author: george\n */\n\n#include \"solvers.hpp\"\n\n#include <gecode/int.hh>\n#include <gecode/float.hh>\n#include <gecode/search.hh>\n#include <gecode/gist.hh>\n\n\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace Gecode;\n\nclass LinearEqSysSolver : public Space {\nprotected:\n  IntVarArray x;\npublic:\n  LinearEqSysSolver(\n      const std::vector<std::vector<int>>& A,\n      const std::vector<int>& y) throw (InvalidArgumentException)\n    : x(*this, y.size(), 1, Int::Limits::max) {\n\n    const size_t n_actors = y.size();\n    const size_t n_channels = A.size();\n\n    for (size_t i=0; i<n_channels; i++ ) {\n      IntArgs c(n_actors);\n      IntVarArgs xs(n_actors);\n      for (size_t j=0; j<n_actors; j++ ) {\n        c[j]  = A[i][j];\n        xs[j] = x[j];\n      }\n\n      linear(*this, c, xs, IRT_EQ, y[i]);\n    }\n    branch(*this, x, INT_VAR_SIZE_MIN(), INT_VAL_MIN());\n  }\n\n  LinearEqSysSolver(bool share, LinearEqSysSolver& s) : Space(share, s) {\n    x.update(*this, share, s.x);\n  }\n\n  virtual Space* copy(bool share) {\n    return new LinearEqSysSolver(share,*this);\n  }\n\n  void print(void) const {\n    std::cout << x << std::endl;\n  }\n\n  vector<int> getSolution(void) const {\n    vector<int> tmp_sol;\n    for (int i=0; i<x.size(); i++) {\n      //if x[i].assigned()\n      tmp_sol.push_back(x[i].val());\n      //...else something is wrong\n    }\n    return tmp_sol;\n  }\n\n  // constrain function\n  virtual void constrain(const Space& _b) {\n    const LinearEqSysSolver& b = static_cast<const LinearEqSysSolver&>(_b);\n\n    int sum = 0;\n    IntVarArgs xs(b.x.size());\n    for (int i=0; i<b.x.size(); i++) {\n      sum += b.x[i].val();\n      xs[i] = x[i];\n    }\n    linear(*this, xs, IRT_LE, sum);\n  }\n};\n\n\nclass FloatSysSolver : public Space {\nprotected:\n  FloatVarArray x;\npublic:\n  FloatSysSolver(\n      const std::vector<std::vector<int>>& A,\n      const std::vector<int>& y) throw (InvalidArgumentException)\n    : x(*this, y.size(), 1, Float::Limits::max) {\n\n    const size_t n_actors = y.size();\n    const size_t n_channels = A.size();\n\n    for (size_t i=0; i<n_channels; i++ ) {\n      FloatValArgs c(n_actors);\n      FloatVarArgs xs(n_actors);\n      for (size_t j=0; j<n_actors; j++ ) {\n        c[j]  = A[i][j];\n        xs[j] = x[j];\n      }\n\n      linear(*this, c, xs, FRT_EQ, y[i]);\n    }\n    branch(*this, x, FLOAT_VAR_SIZE_MIN(), FLOAT_VAL_SPLIT_MIN());\n  }\n\n  FloatSysSolver(bool share, FloatSysSolver& s) : Space(share, s) {\n    x.update(*this, share, s.x);\n  }\n\n  virtual Space* copy(bool share) {\n    return new FloatSysSolver(share,*this);\n  }\n\n  void print(void) const {\n    std::cout << x << std::endl;\n  }\n\n  vector<double> getSolution(void) const {\n    vector<double> tmp_sol;\n    for (int i=0; i<x.size(); i++) {\n      //if x[i].assigned()\n      tmp_sol.push_back(x[i].val().min());\n      //...else something is wrong\n    }\n    return tmp_sol;\n  }\n\n  // constrain function\n  virtual void constrain(const Space& _b) {\n    const FloatSysSolver& b = static_cast<const FloatSysSolver&>(_b);\n\n    double sum = 0;\n    FloatVarArgs xs(b.x.size());\n    for (int i=0; i<b.x.size(); i++) {\n      sum += b.x[i].val().max();\n      xs[i] = x[i];\n    }\n    linear(*this, xs, FRT_LE, sum);\n  }\n};\n\n\n\nvector<int> tools::solveLinearEqSys(\n    const std::vector<std::vector<int>>& A,\n    const std::vector<int>& y) throw (InvalidArgumentException) {\n\n  LinearEqSysSolver* m = new LinearEqSysSolver(A,y);\n  //Gist::bab(m);\n  BAB<LinearEqSysSolver> e(m);\n  delete m;\n\n  std::vector<int> solutions;\n  while (LinearEqSysSolver* s = e.next()) {\n    s->print();\n    solutions = s->getSolution();\n    delete s;\n  }\n  //if solutions.size() = 0, SDFG is probably not consistent!\n  return solutions;\n}\n\nvector<double> tools::solveFloatSys(\n    const std::vector<std::vector<int>>& A,\n    const std::vector<int>& y) throw (InvalidArgumentException) {\n\n  FloatSysSolver* m = new FloatSysSolver(A,y);\n  //Gist::bab(m);\n  BAB<FloatSysSolver> e(m);\n  delete m;\n\n  std::vector<double> solutions;\n  while (FloatSysSolver* s = e.next()) {\n    s->print();\n    solutions = s->getSolution();\n    delete s;\n  }\n  //if solutions.size() = 0, SDFG is probably not consistent!\n  return solutions;\n}\n\n", "meta": {"hexsha": "220d67c63f95f650d990d652c699ea35bbbf7957", "size": 4219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tools/solvers.cpp", "max_stars_repo_name": "forsyde/DeSyDe", "max_stars_repo_head_hexsha": "48c55861ed78dd240451787258ee286b0f46aea5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-09-06T14:00:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T04:40:13.000Z", "max_issues_repo_path": "src/tools/solvers.cpp", "max_issues_repo_name": "forsyde/DeSyDe", "max_issues_repo_head_hexsha": "48c55861ed78dd240451787258ee286b0f46aea5", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-19T13:02:40.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-17T15:27:52.000Z", "max_forks_repo_path": "src/tools/solvers.cpp", "max_forks_repo_name": "forsyde/DeSyDe", "max_forks_repo_head_hexsha": "48c55861ed78dd240451787258ee286b0f46aea5", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-10-05T10:04:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-12T18:20:44.000Z", "avg_line_length": 23.0546448087, "max_line_length": 75, "alphanum_fraction": 0.6001422138, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6427454195998806}}
{"text": "// Copyright (c) 2017 Evan S Weinberg\n// Test code for a real operator.\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <complex>\n#include <random>\n\n// Borrow dense matrix eigenvalue routines.\n#include <Eigen/Dense>\n\n#include \"blas/generic_vector.h\"\n\n#include \"square_laplace.h\"\n\nusing namespace std; \nusing namespace Eigen;\n\ntypedef Matrix<std::complex<double>, Dynamic, Dynamic, ColMajor> cMatrix;\ntypedef Matrix<double, Dynamic, Dynamic, ColMajor> dMatrix;\n\nint main(int argc, char** argv)\n{  \n  double *rhs_real;\n  double *rhs_real_indef;\n  complex<double> *rhs_cplx;\n  complex<double> *rhs_cplx_indef;\n  complex<double> *gauge_links;\n\n  // Set output precision to be long.\n  cout << setprecision(10);\n\n  // RNG related things.\n  std::mt19937 generator (1337u); // RNG, 1337u is the seed. \n  double inv_variance = 6.0; // inverse of variance for gaussian non-compact U(1) links.\n\n  // Basic information about the lattice.\n  int length = 8;\n  double m_sq = 0.001;\n  \n  // Some start-up.\n  int volume = length*length;\n  int wilson_volume = 2*volume;\n  \n  // Create a random compact U(1) link.\n  gauge_links = allocate_vector<complex<double>>(2*length*length);\n  gaussian_real(gauge_links, 2*length*length, generator, 1.0/inv_variance);\n  polar(gauge_links, 2*length*length);\n  \n  // Vectors. \n  rhs_real = allocate_vector<double>(volume);\n  rhs_real_indef = allocate_vector<double>(volume);\n  rhs_cplx = allocate_vector<complex<double>>(volume);\n  rhs_cplx_indef = allocate_vector<complex<double>>(wilson_volume);\n\n  // Zero out the vector.\n  zero_vector(rhs_real, length*length);\n  zero_vector(rhs_real_indef, length*length);\n  zero_vector(rhs_cplx, length*length);\n  zero_vector(rhs_cplx_indef, 2*length*length);\n\n  //////////////////////////\n  // REAL, SYMMETRIC CASE //\n  //////////////////////////\n\n  std::cout << \"Real, Symmetric case.\\n\\n\";\n\n  // Structure which gets passed to the function.\n  laplace_struct lapstr;\n  lapstr.length = length;\n  lapstr.m_sq = m_sq;\n\n  // Allocate a sufficiently gigantic matrix.\n  dMatrix mat_real = dMatrix::Zero(volume, volume);\n\n  // Form matrix elements. This is where it's important that\n  // dMatrix and cMatrix are column major.\n  // I should probably make this safer by using a \"Map\".\n  for (int i = 0; i < volume; i++)\n  {\n    // Set a point on the rhs for a matrix element.\n    zero_vector(rhs_real, volume);\n    rhs_real[i] = 1.0;\n\n    // Where we put the result of the matrix element.\n    double* mptr = &(mat_real(i*volume));\n\n    square_laplacian(mptr, rhs_real, &lapstr);\n  }\n\n  // This should be the matrix. Let's print it to make sure.\n\n  if (volume <= 16)\n  {\n    std::cout << mat_real << \"\\n\";\n  }\n\n  // Get the eigenvalues.\n  SelfAdjointEigenSolver<dMatrix> eigsolve_real(volume);\n  eigsolve_real.compute(mat_real);\n\n  std::cout << \"The eigenvalues are:\\n\" << eigsolve_real.eigenvalues() << \"\\n\";\n\n  /////////////////////////////\n  // COMPLEX, HERMITIAN CASE //\n  /////////////////////////////\n\n  std::cout << \"\\n\\nComplex, Symmetric case.\\n\\n\";\n\n  // Structure which gets passed to the function.\n  laplace_gauged_struct lapstr_gauged;\n  lapstr_gauged.length = length;\n  lapstr_gauged.m_sq = m_sq;\n  lapstr_gauged.gauge_links = gauge_links; \n\n  // Allocate a sufficiently gigantic matrix.\n  cMatrix mat_cplx = cMatrix::Zero(volume, volume);\n\n  // Form matrix elements. This is where it's important that\n  // dMatrix and cMatrix are column major.\n  // I should probably make this safer by using a \"Map\".\n  for (int i = 0; i < volume; i++)\n  {\n    // Set a point on the rhs for a matrix element.\n    zero_vector(rhs_cplx, volume);\n    rhs_cplx[i] = 1.0;\n\n    // Where we put the result of the matrix element.\n    complex<double>* mptr = &(mat_cplx(i*volume));\n\n    square_laplacian_gauged(mptr, rhs_cplx, &lapstr_gauged);\n  }\n\n  // This should be the matrix. Let's print it to make sure.\n\n  if (volume <= 9)\n  {\n    std::cout << mat_cplx << \"\\n\";\n  }\n\n  // Get the eigenvalues.\n  SelfAdjointEigenSolver<cMatrix> eigsolve_cplx(volume);\n  eigsolve_cplx.compute(mat_cplx);\n\n  std::cout << \"The eigenvalues are:\\n\" << eigsolve_cplx.eigenvalues() << \"\\n\";\n\n  ///////////////////////////\n  // REAL, INDEFINITE CASE //\n  ///////////////////////////\n\n  std::cout << \"\\n\\nReal, Indefinite case.\\n\\n\";\n\n  // Allocate a sufficiently gigantic matrix.\n  dMatrix mat_real_indef = dMatrix::Zero(volume, volume);\n\n  // Form matrix elements. This is where it's important that\n  // dMatrix and cMatrix are column major.\n  // I should probably make this safer by using a \"Map\".\n  for (int i = 0; i < volume; i++)\n  {\n    // Set a point on the rhs for a matrix element.\n    zero_vector(rhs_real_indef, volume);\n    rhs_real_indef[i] = 1.0;\n\n    // Where we put the result of the matrix element.\n    double* mptr = &(mat_real_indef(i*volume));\n\n    square_staggered(mptr, rhs_real_indef, &lapstr);\n  }\n\n  // This should be the matrix. Let's print it to make sure.\n\n  if (volume <= 16)\n  {\n    std::cout << mat_real_indef << \"\\n\";\n  }\n\n  // Get the eigenvalues.\n  EigenSolver<dMatrix> eigsolve_real_indef(wilson_volume);\n  eigsolve_real_indef.compute(mat_real_indef);\n\n  std::cout << \"The eigenvalues are:\\n\" << eigsolve_real_indef.eigenvalues() << \"\\n\";\n\n  //////////////////////////////\n  // COMPLEX, INDEFINITE CASE //\n  //////////////////////////////\n\n  std::cout << \"\\n\\nComplex, Indefinite case.\\n\\n\";\n\n  // Allocate a sufficiently gigantic matrix.\n  cMatrix mat_cplx_indef = cMatrix::Zero(wilson_volume, wilson_volume);\n\n  // Form matrix elements. This is where it's important that\n  // dMatrix and cMatrix are column major.\n  // I should probably make this safer by using a \"Map\".\n  for (int i = 0; i < wilson_volume; i++)\n  {\n    // Set a point on the rhs for a matrix element.\n    zero_vector(rhs_cplx_indef, wilson_volume);\n    rhs_cplx_indef[i] = 1.0;\n\n    // Where we put the result of the matrix element.\n    complex<double>* mptr = &(mat_cplx_indef(i*wilson_volume));\n\n    square_wilson_gauged(mptr, rhs_cplx_indef, &lapstr_gauged);\n  }\n\n  // This should be the matrix. Let's print it to make sure.\n\n  if (volume <= 9)\n  {\n    std::cout << mat_cplx_indef << \"\\n\";\n  }\n\n  // Get the eigenvalues.\n  ComplexEigenSolver<cMatrix> eigsolve_cplx_indef(wilson_volume);\n  eigsolve_cplx_indef.compute(mat_cplx_indef);\n\n  std::cout << \"The eigenvalues are:\\n\" << eigsolve_cplx_indef.eigenvalues() << \"\\n\";\n\n  //////////////\n  // CLEAN UP //\n  //////////////\n\n  // Free the lattice.\n  //delete[] lattice;\n  deallocate_vector(&rhs_real);\n  deallocate_vector(&rhs_real_indef);\n  deallocate_vector(&rhs_cplx);\n  deallocate_vector(&rhs_cplx_indef);\n  deallocate_vector(&gauge_links);\n  return 0;\n}\n\n\n", "meta": {"hexsha": "e9d4657de2f362014a7897aef1fd382cb1c4bcaf", "size": 6692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/n06_square_laplace_eigen/square_laplace.cpp", "max_stars_repo_name": "weinbe2/quantum-linalg", "max_stars_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/n06_square_laplace_eigen/square_laplace.cpp", "max_issues_repo_name": "weinbe2/quantum-linalg", "max_issues_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/n06_square_laplace_eigen/square_laplace.cpp", "max_forks_repo_name": "weinbe2/quantum-linalg", "max_forks_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 88, "alphanum_fraction": 0.660938434, "num_tokens": 1868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.6427454098337233}}
{"text": "\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//! \\file\r\n//!\\brief Tests for the cylindrical bessel function of (fixed_point) for a small digit range.\r\n\r\n#define BOOST_TEST_MODULE test_negatable_math_cyl_bessel_j_small\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/math/special_functions/bessel.hpp>\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_math_cyl_bessel_j_small)\r\n{\r\n  typedef boost::fixed_point::negatable<  std::numeric_limits<int>::digits,\r\n                                        -(std::numeric_limits<long double>::digits - std::numeric_limits<int>::digits)>\r\n  fixed_point_type;\r\n\r\n  typedef fixed_point_type::float_type float_point_type;\r\n\r\n  const fixed_point_type tol = ldexp(fixed_point_type(1), fixed_point_type::resolution + 6);\r\n\r\n  BOOST_CONSTEXPR int i_max = 4;\r\n\r\n  // Check small arguments in the region of Taylor series expansion.\r\n  for(int i = 1; i <= i_max; ++i)\r\n  {\r\n    // Use an integer-valued order wrapped in the fixed-point type in order\r\n    // to force a high level of compiler work but simultaneously avoid\r\n    // potentially lossy tgamma calculations (requiring Bernoulli numbers).\r\n\r\n    const fixed_point_type x = boost::math::cyl_bessel_j(fixed_point_type(2), fixed_point_type(i) / boost::math::constants::e<fixed_point_type>());\r\n    const fixed_point_type y = boost::math::cyl_bessel_j(float_point_type(2), float_point_type(i) / boost::math::constants::e<float_point_type>());\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n}\r\n", "meta": {"hexsha": "432e682085b7d067670eef54e254d1ef87543b0c", "size": 1945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_math_cyl_bessel_j_small.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_math_cyl_bessel_j_small.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_math_cyl_bessel_j_small.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2826086957, "max_line_length": 148, "alphanum_fraction": 0.6997429306, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6427202118909998}}
{"text": "#ifndef TRIUMF_STATISTICAL_MECHANICS_FERMI_DIRAC_HPP\n#define TRIUMF_STATISTICAL_MECHANICS_FERMI_DIRAC_HPP\n\n#include <cmath>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <triumf/constants/codata_2018.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n//\nnamespace statistical_mechanics {\n\n// Fermi-Dirac statistics\nnamespace fermi_dirac {\n\n// chemical potential of a Fermi gas\ntemplate <typename T> T chemical_potential(T temperature, T E_0, T E_F) {\n  /*\n  // Sommerfeld expansion\n  constexpr T k_B =\n      triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<T>::value();\n  T fraction = (k_B * temperature) / E_F;\n  return E_0 +\n         E_F * (1.0 -\n                std::pow(boost::math::constants::pi<T>() * fraction, 2) / 12.0 -\n                std::pow(boost::math::constants::pi<T>() * fraction, 4) / 80.0);\n  */\n  return E_0 + E_F;\n}\n\n// Fermi-Dirac distribution\ntemplate <typename T> T distribution(T temperature, T energy, T E_0, T E_F) {\n  constexpr T k_B =\n      triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<T>::value();\n  T mu = chemical_potential<T>(temperature, E_0, E_F);\n  T arg = (energy - mu) / (k_B * temperature);\n  return 1.0 / (std::exp(arg) + 1.0);\n}\n\n// Fermi-Dirac function\ntemplate <typename T> T function(T temperature, T energy, T E_0, T E_F) {\n  T f_E = distribution<T>(temperature, energy, E_0, E_F);\n  return f_E * (1.0 - f_E);\n}\n\n} // namespace fermi_dirac\n\n} // namespace statistical_mechanics\n\n} // namespace triumf\n\n#endif // TRIUMF_STATISTICAL_MECHANICS_FERMI_DIRAC_HPP\n", "meta": {"hexsha": "f98a059b6bfb4f598504015ef5ddbcfc6f103673", "size": 1561, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/statistical_mechanics/fermi_dirac.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/triumf/statistical_mechanics/fermi_dirac.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/triumf/statistical_mechanics/fermi_dirac.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.875, "max_line_length": 80, "alphanum_fraction": 0.6950672646, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6427077903707062}}
{"text": "/// \\file\n// --------------------------------------------------------------------------\n// This file is part of the reference implementation for the paper\n//    QFib: Fast and Efficient Brain Tractogram Compression\n//    C. Mercier*, S. Rousseau*, P. Gori, I. Bloch and T. Boubekeur\n//    NeuroInformatics 2020\n//    DOI: 10.1007/s12021-020-09452-0\n//\n// All rights reserved. Use of this source code is governed by a\n// MIT license that can be found in the LICENSE file.\n// --------------------------------------------------------------------------\n#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <bitset>\n\n#include \"oct.hpp\"\n#include \"sfibonacci.h\"\n#include \"bitvalue.hpp\"\n#include \"parallel.hpp\"\n\nusing namespace Eigen;\n\n//struct CompressedVector {Bitvalue<T>pv;};\ntemplate<typename T>\nusing CompressedVector = Bitvalue<T>;\n\ntemplate<typename T>\nstruct CompressedFiber\n{\n\tVector3f origin;\n\tVector3f second;\n\tstd::vector<CompressedVector<T>> data;\n};\n\nfloat epsMapping = 0.08f;\n\nenum QuantizationMethod\n{\n\tOCTAHEDRAL,\n\tSPHERICALFIBONACCI\n};\n\nQuantizationMethod quantizationMethod = QuantizationMethod::SPHERICALFIBONACCI;\n\nnamespace fc\n{\ntemplate<typename T>\nVector3f unquantize(const CompressedVector<T> & cvec)\n{\n\tswitch(quantizationMethod)\n\t{\n\tfloat vec[3];\n\tcase(QuantizationMethod::OCTAHEDRAL):\n\t\toctDecode(cvec, vec);\n\t\treturn Vector3f(vec[0], vec[1], vec[2]).normalized();\n\tcase(QuantizationMethod::SPHERICALFIBONACCI):\n\t\tstatic uint32_t nbFiboPoints = 1 << (bitcount);\n\t\treturn fib::SF(cvec, nbFiboPoints);\n\tdefault :\n\t\tstd::cerr << \"ERROR: Quantization Method not handled !\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t\tbreak;\n\n\t}\n}\n\ntemplate<typename T>\nvoid quantize(const Vector3f & vec, CompressedVector<T> & cvec)\n{\n\tswitch(quantizationMethod)\n\t{\n\tcase(QuantizationMethod::OCTAHEDRAL) :\n\t\toctEncode(vec.data(), cvec);\n\t\tbreak;\n\tcase(QuantizationMethod::SPHERICALFIBONACCI):\n\t\tstatic uint32_t nbFiboPoints = 1 << (bitcount);\n\t\tcvec.setCombinedValue(fib::inverseSF<T>(vec, nbFiboPoints));\n\t\tbreak;\n\tdefault:\n\t\tstd::cerr << \"ERROR: Quantization Method not handled !\" << std::endl;\n\t\texit(EXIT_FAILURE);\n\t\tbreak;\n\t}\n}\n\n///\n/// \\brief uniformMapping Uniform mapping from uniquant (Fast lossy compression of 3d unit vectors)\n/// \\param v Vector to map\n/// \\param axis Axis to use for the spherical cap\n/// \\param ratio Ratio to use for the mapping\n/// \\return The mapped vector\n///\nVector3f uniformMapping(const Vector3f & v, const Vector3f & axis, const float ratio)\n{\n\tVector3d dv = v.cast<double>();\n\tVector3d daxis = axis.cast<double>();\n\tdv.normalize();\n\tdaxis.normalize();\n\n\tdouble K = 1.0 / ratio;\n\tdouble c = dv.dot(daxis);\n\n\t// numerical instabilities\n\tif (c > 1.0)\n\t\tc = 1.0;\n\tif (c < -1.0)\n\t\tc = -1.0;\n\tVector3d p1 = (dv - c * daxis).normalized();\n\tdouble delta = (1.0 - ((1.0 - c) / K));\n\treturn  ((p1 * std::sqrt(1.0 - delta * delta) + delta * daxis).cast<float>()).normalized();\n}\n\n///\n/// \\brief inverseUniformMapping Inverse uniform mapping from uniquant (Fast lossy compression of 3d unit vectors)\n/// \\param v Vector to unmap\n/// \\param axis Axis to use for the spherical cap\n/// \\param ratio Ratio to use for the mapping\n/// \\return The unmapped vector\n///\n\nVector3f inverseUniformMapping(const Vector3f & v, const Vector3f & axis, const float ratio)\n{\n\t//return v;\n\tVector3d v2 = v.cast<double>();\n\tVector3d axis2 = axis.cast<double>();\n\tv2.normalize();\n\taxis2.normalize();\n\n\tdouble K = ratio;\n\tdouble c = v2.dot(axis2);\n\n\t/// numerical instabilities\n\tif (c > 1.0)\n\t\tc = 1.0;\n\tif (c < -1.0)\n\t\tc = -1.0;\n\tVector3d p1 = (v2 - c * axis2).normalized();\n\tdouble delta = (1.0 - ((1.0 - c) / K));\n\treturn  ((p1 * std::sqrt(1.0 - delta * delta) + delta * axis2).cast<float>()).normalized();\n}\n\n///\n/// \\brief computeRatio Compute the minimum dot product of the input fiber (only one)\n/// \\param fiber Fiber from which to compute the minimum dot product\n/// \\return Minimum dot product of the unique fiber\n///\n\nfloat computeRatio(const std::vector<Vector3f> & fibers)\n{\n\tVector3f v1, v2;\n\tfloat mindot = 2.f;\n\tv1 = (fibers[1] - fibers[0]).normalized();\n\tfor(unsigned p = 2; p < fibers.size(); ++p)\n\t{\n\t\tv2 = (fibers[p] - fibers[p-1]).normalized();\n\t\tfloat dot = v2.dot(v1);\n\t\tmindot = (dot <  mindot) ? dot : mindot;\n\t\tv1 = v2;\n\t}\n\n\treturn mindot;\n}\n\n///\n/// \\brief computeRatioVerif Compute the ratio of the input fibers and verify that stepsizes are almost constant\n/// \\param fibers Fibers from which to compute the ratio\n/// \\param verbose Parameter to display the maximum angle if true\n/// \\param totalNbPts Variable that will contain the total number of points in the bundle, used for average error computation\n/// \\return Ratio of the bundle of fibers\n///\n\nfloat computeRatioVerif(const std::vector<std::vector<Vector3f> > & fibers, bool verbose, uint64_t & totalNbPts)\n{\n\tunsigned maxThreads = std::max(unsigned(1), std::thread::hardware_concurrency());\n\tstd::vector<uint64_t> nbPts(maxThreads, 0);\n\tstd::vector<float> mindot(maxThreads, 2.0f);\n\tstd::vector<float> maxStep(maxThreads, 0.0f);\n\tstd::vector<float> minStep(maxThreads, std::numeric_limits<float>::max());\n#ifdef USE_OPENMP\n#pragma omp parallel for\n\tfor(int f = 0; f < fibers.size(); ++f)\n\t{\n\t\tnbPts[omp_get_thread_num()] += fibers[f].size();\n\t\tVector3f v1, v2;\n\t\tfloat v2norm;\n\t\tv1 = (fibers[f][1] - fibers[f][0]).normalized();\n\t\tfor(unsigned p = 2; p < fibers[f].size(); ++p)\n\t\t{\n\t\t\tv2 = (fibers[f][p] - fibers[f][p-1]);\n\t\t\tv2norm = v2.norm();\n\t\t\tmaxStep[omp_get_thread_num()] = (v2norm > maxStep[omp_get_thread_num()]) ? v2norm : maxStep[omp_get_thread_num()];\n\t\t\tminStep[omp_get_thread_num()] = (v2norm < minStep[omp_get_thread_num()]) ? v2norm : minStep[omp_get_thread_num()];\n\t\t\tfloat dot = (v2 / v2norm).dot(v1);\n\t\t\tmindot[omp_get_thread_num()] = (dot <  mindot[omp_get_thread_num()]) ? dot : mindot[omp_get_thread_num()];\n\t\t\tv1 = v2 / v2norm;\n\t\t}\n\t}\n#else\n\tparallel.For<unsigned>(0, fibers.size(), 1, [&](unsigned f)\n\t{\n\t\tnbPts[parallel.getID()] += fibers[f].size();\n\t\tVector3f v1, v2;\n\t\tfloat v2norm;\n\t\tv1 = (fibers[f][1] - fibers[f][0]).normalized();\n\t\tfor(unsigned p = 2; p < fibers[f].size(); ++p)\n\t\t{\n\t\t\tv2 = (fibers[f][p] - fibers[f][p-1]);\n\t\t\tv2norm = v2.norm();\n\t\t\tmaxStep[parallel.getID()] = (v2norm > maxStep[parallel.getID()]) ? v2norm : maxStep[parallel.getID()];\n\t\t\tminStep[parallel.getID()] = (v2norm < minStep[parallel.getID()]) ? v2norm : minStep[parallel.getID()];\n\t\t\tfloat dot = (v2 / v2norm).dot(v1);\n\t\t\tmindot[parallel.getID()] = (dot <  mindot[parallel.getID()]) ? dot : mindot[parallel.getID()];\n\t\t\tv1 = v2 / v2norm;\n\t\t}\n\t});\n#endif\n\tfloat mdot = mindot[0], maxS = maxStep[0], minS = minStep[0];\n\ttotalNbPts=nbPts[0];\n\tfor (unsigned int i=1; i<mindot.size(); i++)\n\t{\n\t\ttotalNbPts += nbPts[i];\n\t\tmdot = (mindot[i] < mdot) ? mindot[i] : mdot;\n\t\tmaxS = (maxStep[i] > maxS) ? maxStep[i] : maxS;\n\t\tminS = (minStep[i] < minS) ? minStep[i] : minS;\n\t}\n\tfloat diff = maxS - minS;\n\n\tif (verbose)\n\t{\n\t\tstd::cout << \"Max angle: \" << acos(mdot) * 180 / fib::PI << \"\u00b0\" << std::endl;\n\t\tstd::cout << \"Max length between segments: \" << maxS << std::endl;\n\t\tstd::cout << \"Min length between segments: \" << minS << std::endl;\n\t\tstd::cout << \"Difference: \" << diff << std::endl;\n\t}\n\n\tif (diff > 0.1f * (maxS + minS) / 2.0f)\n\t{\n\t\tstd::cerr << std::endl << \"-------------!ERROR!--------------\" << std::endl;\n\t\tstd::cerr << \"Difference in segments length too big (\" << diff << \"), no compression possible\" << std::endl;\n\t\tstd::cerr << \"Try to resample your data with a constant stepsize before compression\" << std::endl;\n\t\tstd::cerr << \"-------------!ERROR!--------------\" << std::endl << std::endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tepsMapping = 0.f;\n\tfor(unsigned i = 0; i < 20; ++i)\n\t\tepsMapping = 3 * sqrt(2) * pow(2, -bitcount/2.f) * ((1 - (mdot))/2+epsMapping);\n\t//Error maximization proportionaly to itself (epsMapping < 1)\n\tepsMapping = sqrt(epsMapping);\n\treturn std::min(1.f, (1.f - mdot) / 2.f + epsMapping);\n}\n\n///\n/// \\brief computeRatioVerif Compute the ratio of the input fibers without verifying that stepsizes are almost constant\n/// \\param fibers Fibers from which to compute the ratio\n/// \\param verbose Parameter to display the maximum angle if true\n/// \\param totalNbPts Variable that will contain the total number of points in the bundle, used for average error computation\n/// \\return Ratio of the bundle of fibers\n///\n\nfloat computeRatio(const std::vector<std::vector<Vector3f> > & fibers, bool verbose, uint64_t & totalNbPts)\n{\n\tunsigned maxThreads = std::max(unsigned(1), std::thread::hardware_concurrency());\n\tstd::vector<uint64_t> nbPts(maxThreads, 0);\n\tstd::vector<float> mindot(maxThreads, 2.0f);\n\n#ifdef USE_OPENMP\n#pragma omp parallel for\n\tfor(int f = 0; f < fibers.size(); ++f)\n\t{\n\t\tnbPts[omp_get_thread_num()] += fibers[f].size();\n\t\tVector3f v1, v2;\n\t\tfloat v2norm;\n\t\tv1 = (fibers[f][1] - fibers[f][0]).normalized();\n\t\tfor(unsigned p = 2; p < fibers[f].size(); ++p)\n\t\t{\n\t\t\tv2 = (fibers[f][p] - fibers[f][p-1]).normalized();\n\t\t\tfloat dot = v2.dot(v1);\n\t\t\tmindot[omp_get_thread_num()] = (dot <  mindot[omp_get_thread_num()]) ? dot : mindot[omp_get_thread_num()];\n\t\t\tv1 = v2;\n\t\t}\n\t}\n#else\n\tparallel.For<unsigned>(0, fibers.size(), 1, [&](unsigned f)\n\t{\n\t\tnbPts[parallel.getID()] += fibers[f].size();\n\t\tVector3f v1, v2;\n\t\tfloat v2norm;\n\t\tv1 = (fibers[f][1] - fibers[f][0]).normalized();\n\t\tfor(unsigned p = 2; p < fibers[f].size(); ++p)\n\t\t{\n\t\t\tv2 = (fibers[f][p] - fibers[f][p-1]).normalized();\n\t\t\tfloat dot = v2.dot(v1);\n\t\t\tmindot[parallel.getID()] = (dot <  mindot[parallel.getID()]) ? dot : mindot[parallel.getID()];\n\t\t\tv1 = v2;\n\t\t}\n\t});\n#endif\n\tfloat mdot=mindot[0];\n\ttotalNbPts=nbPts[0];\n\tfor (unsigned int i=1; i<mindot.size(); i++)\n\t{\n\t\ttotalNbPts += nbPts[i];\n\t\tmdot = (mindot[i] < mdot) ? mindot[i] : mdot;\n\t}\n\n\tif (verbose)\n\t\tstd::cout << \"Max angle: \" << acos(mdot) * 180 / fib::PI << \"\u00b0\" << std::endl;\n\n\tepsMapping = 0.f;\n\tfor(unsigned i = 0; i < 20; ++i)\n\t\tepsMapping = 3 * sqrt(2) * pow(2, -bitcount/2.f) * ((1 - (mdot))/2+epsMapping);\n\t//Error maximization proportionaly to itself (epsMapping < 1)\n\tepsMapping = sqrt(epsMapping);\n\treturn std::min(1.f, (1.f - mdot) / 2.f + epsMapping);\n}\n\n///\n/// \\brief compressFiber Compression of the fiber considering its ratio\n/// \\param fiber Fiber to compress\n/// \\param ratio Ratio to use for the compression\n/// \\param cfiber Fiber compressed\n/// \\param template T is the type of the compressed data, either int8 or int16 depending on the precision asked\n///\n\ntemplate<typename T>\nvoid compressFiber(const std::vector<Vector3f> & fiber, const float ratio, CompressedFiber<T> & cfiber)\n{\n\tassert(fiber.size() > 1);\n\n\t//encode the first two points\n\tcfiber.origin = fiber[0];\n\tcfiber.second = fiber[1];\n\n\tcfiber.data.resize(fiber.size() - 2);\n\n\t//compute the first unit vector and the stepsize\n\tVector3f axis = (fiber[1] - fiber[0]).normalized();\n\tfloat stepsize = (fiber[1] - fiber[0]).norm();\n\tVector3f currentpoint = fiber[1];\n\n\t//compress the rest of the fiber\n\tVector3f v;\n\tconstexpr float eps = 0.00000001;\n\tfor(unsigned i = 2; i < fiber.size(); ++i)\n\t{\n\t\tv = (fiber[i] - currentpoint).normalized();\n\t\tif(((1.f - v.dot(axis)) / 2.f) > ratio) //Conservative mapping in case the epsilon is not enough\n\t\t{\n\t\t\tfc::quantize((-((1.0 - eps) * axis) + (eps * v)).normalized(), cfiber.data[i-2]);\n\t\t}\n\t\telse //Otherwise, general case\n\t\t{\n\t\t\tif(abs(v.dot(axis)) < 1.f)\n\t\t\t\tfc::quantize(fc::inverseUniformMapping(v, axis, ratio), cfiber.data[i-2]);\n\t\t\telse\n\t\t\t{\n\t\t\t\tfc::quantize(v, cfiber.data[i-2]);\n\t\t\t}\n\t\t}\n\t\taxis = fc::uniformMapping(fc::unquantize(cfiber.data[i-2]), axis, ratio);\n\t\tcurrentpoint += (stepsize * axis);\n\t\t//currentpoint = fiber[i]; //Uncomment if you want to disable error propagation !!\n\t}\n}\n\n///\n/// \\brief compressFiber Compression of the fiber considering its ratio, computing the obtained error at the same time\n/// \\param fiber Fiber to compress\n/// \\param ratio Ratio to use for the compression\n/// \\param cfiber Fiber compressed\n/// \\param maxError Maximum error (at point level) when compressing the fiber\n/// \\param meanError Average error (at point level) when compressing the fiber\n/// \\param template T is the type of the compressed data, either int8 or int16 depending on the precision asked\n///\n\ntemplate<typename T>\nvoid compressFiber(const std::vector<Vector3f> & fiber, const float ratio, CompressedFiber<T> & cfiber, float & maxError, double & meanError)\n{\n\tassert(fiber.size() > 1);\n\n\t//encode the first two points\n\tcfiber.origin = fiber[0];\n\tcfiber.second = fiber[1];\n\n\tcfiber.data.resize(fiber.size() - 2);\n\n\t//compute the first unit vector and the stepsize\n\tVector3f axis = (fiber[1] - fiber[0]).normalized();\n\tfloat stepsize = (fiber[1] - fiber[0]).norm();\n\tVector3f currentpoint = fiber[1];\n\n\t//compress the rest of the fiber\n\tVector3f v;\n\tconstexpr float eps = 0.00000001;\n\tfor(unsigned i = 2; i < fiber.size(); ++i)\n\t{\n\t\tv = (fiber[i] - currentpoint).normalized();\n\t\tif(((1.f - v.dot(axis)) / 2.f) > ratio) //Conservative mapping in case the epsilon is not enough\n\t\t{\n\t\t\tfc::quantize((-((1.0 - eps) * axis) + (eps * v)).normalized(), cfiber.data[i-2]);\n\t\t}\n\t\telse //Otherwise, general case\n\t\t{\n\t\t\tif(abs(v.dot(axis)) < 1.f)\n\t\t\t\tfc::quantize(fc::inverseUniformMapping(v, axis, ratio), cfiber.data[i-2]);\n\t\t\telse\n\t\t\t\tfc::quantize(v, cfiber.data[i-2]);\n\t\t}\n\t\taxis = fc::uniformMapping(fc::unquantize(cfiber.data[i-2]), axis, ratio);\n\t\tcurrentpoint += (stepsize * axis);\n\t\tfloat err = (fiber[i] - currentpoint).norm();\n\t\tmaxError = err > maxError ? err : maxError;\n\t\tmeanError += err;\n\t}\n}\n\n///\n/// \\brief decompressFiber Decompress the input fiber\n/// \\param cfiber Compressed fiber to decompress\n/// \\param ratio Ratio to use for decompression (same than for compression)\n/// \\param fiber Decompressed fiber\n///\n\ntemplate<typename T>\nvoid decompressFiber(const CompressedFiber<T> & cfiber, const float ratio, std::vector<Vector3f> & fiber)\n{\n\tfiber.reserve(cfiber.data.size() + 2);\n\tfiber.push_back(cfiber.origin);\n\tfiber.push_back(cfiber.second);\n\n\tfloat stepsize = (cfiber.second - cfiber.origin).norm();\n\tVector3f axis = (fiber[1] - fiber[0]).normalized();\n\n\tfor(unsigned i = 0; i < cfiber.data.size(); ++i)\n\t{\n\t\tVector3f v = fc::unquantize(cfiber.data[i]);\n\t\tif(abs(v.dot(axis)) < 1.f)\n\t\t\tv = fc::uniformMapping(v, axis, ratio);\n\n\t\tfiber.push_back(fiber[i+1] + stepsize * v);\n\t\taxis = v;\n\t}\n}\n}\n", "meta": {"hexsha": "332fafbe4cf6f9d9814a91c0c6349e1a323d539c", "size": 14374, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sources/compression.hpp", "max_stars_repo_name": "syrousseau/qfib", "max_stars_repo_head_hexsha": "72987f025d2158ed3f325055c2ae5b37c49be786", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-02-14T14:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:23:00.000Z", "max_issues_repo_path": "sources/compression.hpp", "max_issues_repo_name": "syrousseau/qfib", "max_issues_repo_head_hexsha": "72987f025d2158ed3f325055c2ae5b37c49be786", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-02-06T14:54:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-16T14:58:35.000Z", "max_forks_repo_path": "sources/compression.hpp", "max_forks_repo_name": "syrousseau/qfib", "max_forks_repo_head_hexsha": "72987f025d2158ed3f325055c2ae5b37c49be786", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-04T16:10:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-04T16:10:22.000Z", "avg_line_length": 31.9422222222, "max_line_length": 141, "alphanum_fraction": 0.6564630583, "num_tokens": 4353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6427077839478347}}
{"text": "/*\n * Copyright Nick Thompson, 2021\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <random>\n#include <boost/math/tools/quartic_roots.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing boost::math::tools::quartic_roots;\nusing std::cbrt;\nusing std::sqrt;\n\ntemplate<class Real>\nvoid test_zero_coefficients()\n{\n    Real a = 0;\n    Real b = 0;\n    Real c = 0;\n    Real d = 0;\n    Real e = 0;\n    auto roots = quartic_roots(a,b,c,d,e);\n    CHECK_EQUAL(roots[0], Real(0));\n    CHECK_EQUAL(roots[1], Real(0));\n    CHECK_EQUAL(roots[2], Real(0));\n    CHECK_EQUAL(roots[3], Real(0));\n\n    b = 1;\n    e = 1;\n    // x^3 + 1 = 0:\n    roots = quartic_roots(a,b,c,d,e);\n    CHECK_EQUAL(roots[0], Real(-1));\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n    CHECK_NAN(roots[3]);\n    e = -1;\n    // x^3 - 1 = 0:\n    roots = quartic_roots(a,b,c,d,e);\n    CHECK_EQUAL(roots[0], Real(1));\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n    CHECK_NAN(roots[3]);\n\n    e = -2;\n    // x^3 - 2 = 0\n    roots = quartic_roots(a,b,c,d,e);\n    CHECK_ULP_CLOSE(roots[0], cbrt(Real(2)), 2);\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n    CHECK_NAN(roots[3]);\n\n    // x^4 -1 = 0\n    // x = \\pm 1:\n    roots = quartic_roots<Real>(1, 0, 0, 0, -1);\n    CHECK_ULP_CLOSE(Real(-1), roots[0], 3);\n    CHECK_ULP_CLOSE(Real(1), roots[1], 3);\n    CHECK_NAN(roots[2]);\n    CHECK_NAN(roots[3]);\n\n    // x^4 - 2 = 0 \\implies x = \\pm sqrt(sqrt(2))\n    roots = quartic_roots<Real>(1,0,0,0,-2);\n    CHECK_ULP_CLOSE(-sqrt(sqrt(Real(2))), roots[0], 3);\n    CHECK_ULP_CLOSE(sqrt(sqrt(Real(2))), roots[1], 3);\n    CHECK_NAN(roots[2]);\n    CHECK_NAN(roots[3]);\n\n    \n    // x(x-1)(x-2)(x-3) = x^4 - 6x^3 + 11x^2 - 6x\n    roots = quartic_roots(Real(1), Real(-6), Real(11), Real(-6), Real(0));\n    CHECK_ULP_CLOSE(roots[0], Real(0), 2);\n    CHECK_ULP_CLOSE(roots[1], Real(1), 2);\n    CHECK_ULP_CLOSE(roots[2], Real(2), 2);\n    CHECK_ULP_CLOSE(roots[3], Real(3), 2);\n\n     // (x-1)(x-2)(x-3)(x-4) = x^4 - 10x^3 + 35x^2 - (2*3*4 + 1*3*4 + 1*2*4 + 1*2*3)x + 1*2*3*4  \n    roots = quartic_roots<Real>(1, -10, 35, -24 - 12 - 8 - 6, 1*2*3*4);\n    CHECK_ULP_CLOSE(Real(1), roots[0], 2);\n    CHECK_ULP_CLOSE(Real(2), roots[1], 2);\n    CHECK_ULP_CLOSE(Real(3), roots[2], 2);\n    CHECK_ULP_CLOSE(Real(4), roots[3], 2);\n    \n    // Double root:\n    // (x+1)^2(x-2)(x-3) = x^4 - 3x^3 -3x^2 + 7x + 6\n    // Note: This test is unstable wrt to perturbations!\n    roots = quartic_roots(Real(1), Real(-3), Real(-3), Real(7), Real(6));\n    CHECK_ULP_CLOSE(Real(-1), roots[0], 2);\n    CHECK_ULP_CLOSE(Real(-1), roots[1], 2);\n    CHECK_ULP_CLOSE(Real(2), roots[2], 2);\n    CHECK_ULP_CLOSE(Real(3), roots[3], 2);\n\n     \n    std::uniform_real_distribution<Real> dis(-2,2);\n    std::mt19937 gen(12343);\n    // Expected roots\n    std::array<Real, 4> r;\n    int trials = 10;\n    for (int i = 0; i < trials; ++i) {\n        // Mathematica:\n        // Expand[(x - r0)*(x - r1)*(x - r2)*(x-r3)]\n        // r0 r1 r2 r3 - (r0 r1 r2 + r0 r1 r3 + r0 r2 r3 + r1r2r3)x\n        // + (r0 r1 + r0 r2 + r0 r3 + r1 r2 + r1r3 + r2 r3)x^2 - (r0 + r1 + r2 + r3) x^3 + x^4\n        for (auto & root : r) {\n            root = static_cast<Real>(dis(gen));\n        }\n        std::sort(r.begin(), r.end());\n        Real a = 1;\n        Real b = -(r[0] + r[1] + r[2] + r[3]);\n        Real c = r[0]*r[1] + r[0]*r[2] + r[0]*r[3] + r[1]*r[2] + r[1]*r[3] + r[2]*r[3];\n        Real d = -(r[0]*r[1]*r[2] + r[0]*r[1]*r[3] + r[0]*r[2]*r[3] + r[1]*r[2]*r[3]);\n        Real e = r[0]*r[1]*r[2]*r[3];\n\n        auto roots = quartic_roots(a, b, c, d, e);\n        // I could check the condition number here, but this is fine right?\n        CHECK_ULP_CLOSE(r[0], roots[0], 160);\n        CHECK_ULP_CLOSE(r[1], roots[1], 260);\n        CHECK_ULP_CLOSE(r[2], roots[2], 160);\n        CHECK_ULP_CLOSE(r[3], roots[3], 160);\n    }\n}\n\n\nint main()\n{\n    test_zero_coefficients<float>();\n    test_zero_coefficients<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_zero_coefficients<long double>();\n#endif\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "60f98252bcb52835b85e45a8baa928044b593268", "size": 4318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/quartic_roots_test.cpp", "max_stars_repo_name": "grlee77/math", "max_stars_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/quartic_roots_test.cpp", "max_issues_repo_name": "grlee77/math", "max_issues_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/quartic_roots_test.cpp", "max_forks_repo_name": "grlee77/math", "max_forks_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5182481752, "max_line_length": 97, "alphanum_fraction": 0.5634553034, "num_tokens": 1669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6427077770032988}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <ceres/ceres.h>\n#include <chrono>\n#include <fstream>\n#include \"CommonCurve.h\" //std::left std::setw std::setfill\n#include \"CeresCost.h\" \n#include <boost/program_options.hpp>\n#include <algorithm>\n#include <iterator>\n#include <filesystem>\nnamespace fs = std::filesystem;\nusing namespace boost;\nnamespace po = boost::program_options;\n\n\nint main ( int argc, char** argv )\n{\n    std::string dataFile = \"readDataCeres.txt\";\n    std::string parameter = \"parametersCeres.txt\";\n    std::string path = \"./result/\";\n    // create directory if not exist\n    struct stat info;\n    if( stat( path.c_str(), &info ) != 0 )fs::create_directories(path);\n    std::string pathRealData = path + za::getCurrentTime() + dataFile;\n    std::string pathParameter = path + za::getCurrentTime() + parameter;\n  \n    // True parameter value to be estimated \n    double a, b, c;  \n\n    // Total number of data point       \n    int N, iterate ;   \n\n    // Noise Sigma value                       \n    double w_sigma; \n    // Cammand line parser \n\ttry \n\t\t{\n\t\t\tpo::options_description desc(\"Allowed options\");\n\t\t\tdesc.add_options()\n\t\t\t\t(\"help,h\", \"produce help message\")\n\t\t\t\t(\"first,a\", po::value<double>(),\n\t\t\t\t\t\"first parameter\")\t\t\t\n                (\"second,b\", po::value<double>(),\n\t\t\t\t\t\"second parameter\")\n\t\t\t\t(\"third,c\", po::value<double>(),\n\t\t\t\t\t\"third parameter\")\t\t\t\t\n                (\"number,n\", po::value<int>(&N)->default_value(100)->implicit_value(500),\n\t\t\t\t\t\"number of data\")                \n                (\"iteration,i\", po::value<int>(&iterate)->default_value(100)->implicit_value(200),\n\t\t\t\t\t\"number of iterations\")\n\t\t\t\t(\"noise,s\", po::value<double>(&w_sigma)->default_value(1)->implicit_value(5),\n\t\t\t\t\t\"noise added\");\t\t\n                    \n\t\n\t\t\t/* Point out that all unknown values \u200b\u200bshould be converted to the value of the \"input-file\" option.\n\t\t\t\t\t* Also use the command_line_parser class instead of parse_command_line */\n\t\t\tpo::variables_map vm;        \n\t\t\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\t\t\tpo::notify(vm);  \n\n\t\t\tif (vm.count(\"help\")) \n\t\t\t{\n\t\t\t\tstd::cout << \"Usage: options_description [options]\\n\";\n\t\t\t\tstd::cout << desc;\n\t\t\t\treturn 0;\n\t\t\t}\n \t\t\tif (vm.count(\"first\") ) \n        \t{\n\n                a =  vm[\"first\"].as<double>();\n        \t} \n        \telse \n       \t\t{\n            \tstd::cout << \"First parameter not set.\\n\";\n\t\t\t\treturn -1;\n        \t}\t\t\t\n \t\t\tif (vm.count(\"second\") ) \n        \t{\n\n                b =  vm[\"second\"].as<double>();\n        \t} \n        \telse \n       \t\t{\n            \tstd::cout << \"Second parameter not set.\\n\";\n\t\t\t\treturn -1;\n        \t}\t\t\t\n \t\t\tif (vm.count(\"third\") ) \n        \t{\n\n                a =  vm[\"third\"].as<double>();\n        \t} \n        \telse \n       \t\t{\n            \tstd::cout << \"Third parameter not set.\\n\";\n\t\t\t\treturn -1;\n        \t}\t\t\t\n        }// end of try\n\t\t\t\n        catch(std::exception& e)\n\t\t{\n\t\t\tstd::cout << e.what() << \"\\n\";\n\t\t\treturn 1;\n\t\t}\n\n\n    // OpenCV random number generator               \n    cv::RNG rng;       \n\n    // abc Estimated value of the parameter                 \n    double abc[3] = {0,0,0};            \n\n   // set of x and y data \n    std::vector<double> x_data, y_data;      \n    std::ofstream myfile;\n    const int nameWidth     = 6;\n    const int numWidth      = 8;\n    myfile.open (&pathRealData[0]);\n    for(int i = 0; i < 25; i++) za::printElement(\"-\", 1, myfile);\n    myfile <<\"\\n\";\n    za::printElement(\"|\", 1, myfile);\n    za::printElement(\"N\", nameWidth, myfile);\n    za::printElement(\"|\", 1, myfile);\n    za::printElement(\"X\", nameWidth, myfile);\n    za::printElement(\"|\", 1, myfile);\n    za::printElement(\"Y\", 10, myfile);\n    za::printElement(\"|\", 1, myfile);\n    myfile <<\"\\n\";\n    for(int i = 0; i < 25; i++) za::printElement(\"-\", 1, myfile);\n    myfile <<\"\\n\";\n    std::cout<<\"Generating data: \\n\";\n    \n    for ( int i=0; i<N; i++ )\n    {\n        // x data \n        double x = i/100.0;\n        x_data.push_back ( x );\n\n        // y data\n        y_data.push_back (\n            exp ( a*x*x + b*x + c ) + rng.gaussian ( w_sigma )\n        );\n\n        za::printElement(\"|\", 1, myfile);\n        za::printElement(i+1, nameWidth, myfile);\n        za::printElement(\"|\", 1, myfile);\n        za::printElement(x_data[i], nameWidth, myfile);\n        za::printElement(\"|\", 1, myfile);\n        za::printElement(y_data[i], 10, myfile);\n        za::printElement(\"|\", 1, myfile);\n        myfile <<\"\\n\";\n        for(int i = 0; i < 25; i++) za::printElement(\"-\", 1, myfile);\n        myfile <<\"\\n\";\n\n    }\n    myfile.close();\n    // Constructing the Least Squares Problem\n    ceres::Problem problem;\n    for ( int i=0; i<N; i++ )\n    {\n    // Add an error term to the question\n    // Use automatic derivation, template parameters: \n    // error type, output dimension, input dimension, dimension should be consistent with the previous struct\n        problem.AddResidualBlock (   \n            new ceres::AutoDiffCostFunction<za::CURVE_FITTING_COST, 1, 3> ( \n                new za::CURVE_FITTING_COST ( x_data[i], y_data[i] )\n            ),\n            nullptr,            // Kernel function, not used here, empty\n            abc                 // Parameters to be estimated\n        );\n    }\n\n    //Configure solver\n\n    ceres::Solver::Options options;   \n\n    // How to solve the incremental equation  \n    options.linear_solver_type = ceres::DENSE_QR;  \n\n    // Output to std::cout\n    options.minimizer_progress_to_stdout = true;   \n    options.max_num_iterations = iterate;   \n\n    // Optimization information\n    ceres::Solver::Summary summary;      \n\n    // Timer to compute solving time         \n    std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();\n\n    // Start to optimize\n    ceres::Solve ( options, &problem, &summary );  \n    std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();\n    std::chrono::duration<double> time_used = std::chrono::duration_cast<std::chrono::duration<double>>( t2-t1 );\n    std::cout<<\"solve time cost = \"<<time_used.count()<<\" seconds. \\n\";\n    std::ofstream mySol;\n    mySol.open (&pathParameter[0]);\n    // Output result\n    std::cout<<summary.BriefReport() << \"\\n\";\n    mySol<<\"Estimated a,b,c =\";\n    for ( auto val:abc ) mySol<<val<<\" \";\n    mySol<<\"\\n\";\n    mySol.close();\n\n    return 0;\n}\n\n", "meta": {"hexsha": "bb84d37fede10048deeeb510e7123e97bb0bd965", "size": 6328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ceres/demoCeres.cpp", "max_stars_repo_name": "zoumson/CurveFitting", "max_stars_repo_head_hexsha": "bf115ce0e98478a8a1e6962e8a124582e0a7be4b", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ceres/demoCeres.cpp", "max_issues_repo_name": "zoumson/CurveFitting", "max_issues_repo_head_hexsha": "bf115ce0e98478a8a1e6962e8a124582e0a7be4b", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ceres/demoCeres.cpp", "max_forks_repo_name": "zoumson/CurveFitting", "max_forks_repo_head_hexsha": "bf115ce0e98478a8a1e6962e8a124582e0a7be4b", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5700483092, "max_line_length": 113, "alphanum_fraction": 0.5538874842, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6425851826750976}}
{"text": "/**\n * math lib and lapack test\n * @author Tobias Weber <tweber@ill.fr>\n * @date feb-19\n * @license GPLv3, see 'LICENSE' file\n *\n * g++-10 -std=c++20 -DUSE_LAPACK -I.. -I/usr/include/lapacke -I/usr/local/opt/lapack/include -L/usr/local/opt/lapack/lib -o mat0 mat0.cpp -llapacke\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE Mat0\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n#include <iostream>\n#include <vector>\n\n#include \"libs/maths.h\"\n\n\nusing t_types = std::tuple<double, float>;\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_mat0, t_real, t_types)\n{\n\tusing namespace tl2_ops;\n\n\tusing t_cplx = std::complex<t_real>;\n\tusing t_vec = tl2::vec<t_real, std::vector>;\n\tusing t_mat = tl2::mat<t_real, std::vector>;\n\tusing t_vec_cplx = tl2::vec<t_cplx, std::vector>;\n\tusing t_mat_cplx = tl2::mat<t_cplx, std::vector>;\n\n\tt_real eps = std::pow(std::numeric_limits<t_real>::epsilon(), 1./2.);\n\tstd::cout << \"eps = \" << eps << std::endl;\n\n\n\tauto M = tl2::create<t_mat>({1, 2, 3, 3, 2, 6, 4, 2, 4});\n\tauto Z = tl2::create<t_mat_cplx>({1, 2, 3, 3, 2, 6, 4, 2, 4});\n\tstd::cout << \"M = \" << M << std::endl;\n\tstd::cout << \"Z = \" << Z << std::endl;\n\n\n\t{\n\t\tauto [ok, Q, R] = tl2::qr<t_mat, t_vec>(M);\n\t\tt_real d = tl2::det<t_mat>(Q);\n\t\tauto QR = Q*R;\n\n\t\tstd::cout << \"\\nok = \" << std::boolalpha << ok << std::endl;\n\t\tstd::cout << \"Q = \" << Q << std::endl;\n\t\tstd::cout << \"R = \" << R << std::endl;\n\t\tstd::cout << \"det(Q) = \" << d << std::endl;\n\t\tstd::cout << \"QR = \" << QR << std::endl;\n\n\t\tBOOST_TEST(ok);\n\t\tBOOST_TEST(tl2::equals<t_real>(d, 1, eps));\n\t\tBOOST_TEST(tl2::equals(QR, M, eps));\n\n#ifdef USE_LAPACK\n\t\tauto [ok2, P, L, U] = tl2_la::lu<t_mat>(M);\n\t\tauto PLU = P*L*U;\n\n\t\tstd::cout << \"\\nok2 = \" << std::boolalpha << ok2 << std::endl;\n\t\tstd::cout << \"P = \" << P << std::endl;\n\t\tstd::cout << \"L = \" << L << std::endl;\n\t\tstd::cout << \"U = \" << U << std::endl;\n\t\tstd::cout << \"PLU = \" << PLU << std::endl;\n\n\t\tBOOST_TEST(ok2);\n\t\tBOOST_TEST(tl2::equals(PLU, M, eps));\n#endif\n\t}\n\n\t{\n\t\tauto [ok, Q, R] = tl2::qr<t_mat_cplx, t_vec_cplx>(Z);\n\t\tt_cplx d = tl2::det<t_mat_cplx>(Q);\n\t\tauto QR = Q*R;\n\n\t\tstd::cout << \"\\nok = \" << std::boolalpha << ok << std::endl;\n\t\tstd::cout << \"Q = \" << Q << std::endl;\n\t\tstd::cout << \"R = \" << R << std::endl;\n\t\tstd::cout << \"det(Q) = \" << d << std::endl;\n\t\tstd::cout << \"QR = \" << QR << std::endl;\n\n\t\tBOOST_TEST(ok);\n\t\tBOOST_TEST(tl2::equals<t_cplx>(d, 1, eps));\n\t\tBOOST_TEST(tl2::equals(QR, Z, eps));\n\n#ifdef USE_LAPACK\n\t\tauto [ok2, P, L, U] = tl2_la::lu<t_mat_cplx>(Z);\n\t\tauto PLU = P*L*U;\n\n\t\tstd::cout << \"\\nok2 = \" << std::boolalpha << ok2 << std::endl;\n\t\tstd::cout << \"P = \" << P << std::endl;\n\t\tstd::cout << \"L = \" << L << std::endl;\n\t\tstd::cout << \"U = \" << U << std::endl;\n\t\tstd::cout << \"PLU = \" << PLU << std::endl;\n\n\t\tBOOST_TEST(ok2);\n\t\tBOOST_TEST(tl2::equals(PLU, Z, eps));\n#endif\n\t}\n\n#ifdef USE_LAPACK\n\t{\n\t\tauto [ok, evals, evecs] =\n\t\t\ttl2_la::eigenvec<t_mat_cplx, t_vec_cplx, t_cplx>(Z, 0, 0, 1);\n\t\tstd::cout << \"\\nok = \" << std::boolalpha << ok << std::endl;\n\t\tfor(std::size_t i=0; i<evals.size(); ++i)\n\t\t\tstd::cout << \"eval: \" << evals[i] << \", evec: \" << evecs[i] << std::endl;\n\n\n\t\tauto [ok2, U, Vh, vals] = tl2_la::singval<t_mat_cplx>(Z);\n\t\tstd::cout << \"\\nok = \" << std::boolalpha << ok2 << std::endl;\n\t\tstd::cout << \"singvals: \";\n\t\tfor(std::size_t i=0; i<vals.size(); ++i)\n\t\t\tstd::cout << vals[i] << \" \";\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"U = \" << U << \"\\nVh = \" << Vh << std::endl;\n\n\t\tstd::cout << \"diag{vals} * UVh = \" << U*tl2::diag<t_mat_cplx>(vals)*Vh << std::endl;\n\n\n\t\tauto [inva, ok3a] = tl2_la::pseudoinv<t_mat_cplx>(Z);\n\t\tauto [invb, ok3b] = tl2::inv<t_mat_cplx>(Z);\n\t\tstd::cout << \"\\nok = \" << std::boolalpha << ok3a << \", \" << ok3b << std::endl;\n\t\tstd::cout << \"pseudoinv = \" << inva << std::endl;\n\t\tstd::cout << \"      inv  = \" << invb << std::endl;\n\n\t\tBOOST_TEST(ok);\n\t\tBOOST_TEST(ok2);\n\t\tBOOST_TEST(ok3a);\n\t\tBOOST_TEST(ok3b);\n\n\t\tauto ident = tl2::unit<t_mat_cplx>(Z.size1(), Z.size2());\n\t\tauto mata1 = inva*Z;\n\t\tauto mata2 = Z*inva;\n\t\tauto matb1 = invb*Z;\n\t\tauto matb2 = Z*invb;\n\t\tBOOST_TEST(tl2::equals(mata1, ident, eps));\n\t\tBOOST_TEST(tl2::equals(matb1, ident, eps));\n\t\tBOOST_TEST(tl2::equals(mata2, ident, eps));\n\t\tBOOST_TEST(tl2::equals(matb2, ident, eps));\n\t}\n\n\t{\n\t\tauto [ok, evals_re, evals_im, evecs_re, evecs_im] =\n\t\t\ttl2_la::eigenvec<t_mat, t_vec, t_real>(M, 0, 0, 1);\n\t\tstd::cout << \"\\nok = \" << std::boolalpha << ok << std::endl;\n\t\tfor(std::size_t i=0; i<evals_re.size(); ++i)\n\t\t\tstd::cout << \"eval: \" << evals_re[i] << \" + i*\" << evals_im[i]\n\t\t\t<< \", evec: \" << evecs_re[i] << \" +i*\" << evecs_im[i] << std::endl;\n\n\n\t\tauto [ok2, U, Vt, vals] = tl2_la::singval<t_mat>(M);\n\t\tstd::cout << \"\\nok = \" << std::boolalpha << ok2 << std::endl;\n\t\tstd::cout << \"singvals: \";\n\t\tfor(std::size_t i=0; i<vals.size(); ++i)\n\t\t\tstd::cout << vals[i] << \" \";\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"U = \" << U << \"\\nVt = \" << Vt << std::endl;\n\n\t\tstd::cout << \"diag{vals} * UVt = \" << U*tl2::diag<t_mat>(vals)*Vt << std::endl;\n\n\n\t\tauto [inva, ok3a] = tl2_la::pseudoinv<t_mat>(M);\n\t\tauto [invb, ok3b] = tl2::inv<t_mat>(M);\n\t\tstd::cout << \"\\nok = \" << std::boolalpha << ok3a << \", \" << ok3b << std::endl;\n\t\tstd::cout << \"pseudoinv = \" << inva << std::endl;\n\t\tstd::cout << \"      inv  = \" << invb << std::endl;\n\n\t\tBOOST_TEST(ok);\n\t\tBOOST_TEST(ok2);\n\t\tBOOST_TEST(ok3a);\n\t\tBOOST_TEST(ok3b);\n\n\t\tauto ident = tl2::unit<t_mat>(M.size1(), M.size2());\n\t\tauto mata = inva*M;\n\t\tauto matb = invb*M;\n\t\tBOOST_TEST(tl2::equals(mata, ident, eps));\n\t\tBOOST_TEST(tl2::equals(matb, ident, eps));\n\t}\n\n\t// test rotation\n\tfor(std::size_t iteration=0; iteration<1000; ++iteration)\n\t{\n\t\tt_vec axis = tl2::create<t_vec>({\n\t\t\ttl2::get_rand<t_real>(-10., 10.),\n\t\t\ttl2::get_rand<t_real>(-10., 10.),\n\t\t\ttl2::get_rand<t_real>(-10., 10.) });\n\t\taxis /= tl2::norm<t_vec>(axis);\n\t\tt_real angle = tl2::get_rand<t_real>(-tl2::pi<t_real>, tl2::pi<t_real>);\n\t\tt_mat rot = tl2::rotation<t_mat, t_vec>(axis, angle, 1);\n\n\t\tauto [ok, evals_re, evals_im, evecs_re, evecs_im] =\n\t\t\ttl2_la::eigenvec<t_mat, t_vec, t_real>(rot, 0, 0, 1);\n\t\t//std::cout << \"\\nok = \" << std::boolalpha << ok << std::endl;\n\n\t\tbool axis_found = false;\n\t\tfor(std::size_t i=0; i<evals_re.size(); ++i)\n\t\t{\n\t\t\tif(tl2::equals<t_real>(evals_re[i], 1., eps) && tl2::equals_0<t_real>(evals_im[i], eps))\n\t\t\t{\n\t\t\t\tbool evec_ok = (tl2::equals<t_vec>(axis, evecs_re[i], eps) ||\n\t\t\t\t\ttl2::equals<t_vec>(-axis, evecs_re[i], eps)) &&\n\t\t\t\t\ttl2::equals_0<t_vec>(evecs_im[i], eps);\n\t\t\t\taxis_found = true;\n\t\t\t\tBOOST_TEST((evec_ok));\n\n\t\t\t\tif(!evec_ok)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"rotation axis: \" << axis << \", angle: \" << angle << std::endl;\n\t\t\t\t\tfor(std::size_t j=0; j<evals_re.size(); ++j)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cerr << \"eval: \" << evals_re[j] << \" + i*\" << evals_im[j]\n\t\t\t\t\t\t\t<< \", evec: \" << evecs_re[j] << \" +i*\" << evecs_im[j] \n\t\t\t\t\t\t\t<< std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tBOOST_TEST((axis_found));\n\t\tif(!axis_found)\n\t\t{\n\t\t\tstd::cerr << \"Error: axis not found!\" << std::endl;\n\t\t\tstd::cerr << \"rotation axis: \" << axis << \", angle: \" << angle << std::endl;\n\t\t\tfor(std::size_t i=0; i<evals_re.size(); ++i)\n\t\t\t{\n\t\t\t\tstd::cerr << \"eval: \" << evals_re[i] << \" + i*\" << evals_im[i]\n\t\t\t\t\t<< \", evec: \" << evecs_re[i] << \" +i*\" << evecs_im[i] \n\t\t\t\t\t<< std::endl;\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\tstd::cout << \"--------------------------------------------------------------------------------\\n\" << std::endl;\n}\n", "meta": {"hexsha": "ee53cb9e4025ddd6ab46703b1b6320d6d5627b28", "size": 8423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/mat0.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/mat0.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/mat0.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 32.6472868217, "max_line_length": 148, "alphanum_fraction": 0.5534845067, "num_tokens": 3005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6425638051078442}}
{"text": "#include <cstdint>\n#include <memory>\n#include <vector>\n#include <string>\n#include <numeric>\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n#include <fstream>\n#include <omp.h>\n#include <valarray>\n\n#include <typeinfo>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n#include <boost/range/combine.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n#include <posit/posit>\n// Posit Arithmetic FPGA accelerator library\n#include <positarith.h>\n\n#include \"main.hpp\"\n#include \"defines.hpp\"\n#include \"utils.hpp\"\n#include \"blas.hpp\"\n#include \"vector_utils.hpp\"\n#include \"matrix_utils.hpp\"\n\nusing namespace std;\nusing namespace sw::unum;\nusing boost::multiprecision::cpp_dec_float_100;\n\nvoid normalizeVector(vector<posit<NBITS,ES>>& vec) {\n    posit<NBITS,ES> sum;\n    for(posit<NBITS,ES>& el : vec) {\n        sum += el * el;\n    }\n    double sq = sqrt((double)sum);\n    for(posit<NBITS,ES>& el : vec) {\n        el = el / sq;\n    }\n}\n\ntemplate<typename T>\nvoid normalizeVector(valarray<T>& vec) {\n    T sum;\n    for(T& el : vec) {\n        sum += el * el;\n    }\n    T sq = sqrt((T)sum);\n    for(T& el : vec) {\n        el = el / sq;\n    }\n}\n\nvector<posit<NBITS, ES> > sumProj(vector<vector<posit<NBITS,ES> > >& v, vector<vector<posit<NBITS,ES> > >& u, int i) {\n        int k = 0;\n        vector<posit<NBITS,ES> > result(u[0].size());\n\n        while (k < i)\n        {\n                posit<NBITS,ES> dot_u_u;\n                vector_dot(u[k], u[k], dot_u_u);\n\n                posit<NBITS,ES> dot_v_u;\n                vector_dot(v[i], u[k], dot_v_u);\n\n                posit<NBITS,ES> factor = dot_v_u / dot_u_u;\n\n                vector<posit<NBITS,ES> > factor_u;\n                vector_mult(u[k], factor, factor_u);\n                vector_add(result, factor_u, result);\n\n                k++;\n        }\n\n        return result;\n}\n\ntemplate<typename T>\nvalarray<T> sumProj(valarray<valarray<T>> v, valarray<valarray<T>> u, int i) {\n    int k = 0;\n    valarray<T> result(v[0].size());\n\n    while (k < i)\n    {\n        T dot_u_u = (u[k] * u[k]).sum();\n        T dot_v_u = (v[i] * u[k]).sum();\n        T factor = dot_v_u / dot_u_u;\n        valarray<T> factor_u = factor * u[k];\n        result += factor * u[k];\n        k++;\n    }\n\n    return result;\n}\n\n// valarray<posit<NBITS,ES>> sumProj(valarray<valarray<posit<NBITS,ES>>> v, valarray<valarray<posit<NBITS,ES>>> u, int i) {\n//     int k = 0;\n//     valarray<posit<NBITS,ES>> result(v[0].size());\n//\n//     while (k < i)\n//     {\n//         posit<NBITS,ES> dot_u_u = (u[k] * u[k]).sum();\n//         posit<NBITS,ES> dot_v_u = (v[i] * u[k]).sum();\n//         posit<NBITS,ES> factor = dot_v_u / dot_u_u;\n//         valarray<posit<NBITS,ES>> factor_u = factor * u[k];\n//         result += factor * u[k];\n//\n//         k++;\n//     }\n//\n//     return result;\n// }\n\nint main(int argc, char ** argv)\n{\n    vector<int> lengths = {10, 20, 30, 40, 50, 100, 200, 300, 400, 500, 1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 100000, 200000, 300000, 400000, 500000, 1000000};\n\n    std::string t_dot, t_sum, t_add, t_add_scalar, t_subtract, t_subtract_scalar, t_mult, t_mult_scalar;\n\n    for(int length : lengths) {\n        t_dot = test_dot_product(length);\n        t_sum = test_sum(length);\n        t_add = test_add(length);\n        t_add_scalar = test_add_scalar(length);\n        t_subtract = test_subtract(length);\n        t_subtract_scalar = test_subtract_scalar(length);\n        t_mult = test_mult(length);\n        t_mult_scalar = test_mult_scalar(length);\n\n        ofstream outfile(\"positarith_es\" + std::to_string(ES) + \"_\" + std::to_string(length) + \".txt\", ios::out);\n        outfile << t_dot << endl;\n        outfile << t_sum << endl;\n        outfile << t_add << endl;\n        outfile << t_add_scalar << endl;\n        outfile << t_subtract << endl;\n        outfile << t_subtract_scalar << endl;\n        outfile << t_mult << endl;\n        outfile << t_mult_scalar << endl;\n        outfile.close();\n    }\n\n    // vector<int> vectors_vec = {2, 5, 10, 50, 100};\n    // vector<int> gram_length = {10, 20, 30, 40, 50, 100, 200, 300, 400, 500, 1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 100000};\n    //\n    // std::string t_gram;\n    //\n    // for(int vectors : vectors_vec) {\n    //     for(int length : gram_length) {\n    //         t_gram = test_gram(3, length);\n    //\n    //         ofstream outfile(\"positarith_gram_es\" + std::to_string(ES) + \"_\" + std::to_string(vectors) + \"_\" + std::to_string(length) + \".txt\", ios::out);\n    //         outfile << t_gram << endl;\n    //         outfile.close();\n    //     }\n    // }\n\n    return 0;\n}\n\nstd::string test_dot_product(int length) {\n    int i;\n    double t_fpga, t_sw, t_float;\n    double stop, start;\n    // Vector Dot Product\n    std::vector<posit<NBITS,ES>> vec1, vec2;\n    posit<NBITS,ES> result;\n\n    for(i = 0; i < length; i++) {\n        vec1.push_back(1);\n        vec2.push_back(i);\n    }\n    t_fpga = 0;//vector_dot(vec1, vec2, result);\n\n    start = omp_get_wtime();\n    posit<NBITS,ES> res = 0;\n    // for(i = 0; i < length; i++) {\n    //     res = res + vec1[i] * vec2[i];\n    // }\n    res = sw::hprblas::dot(length, vec1, 1, vec2, 1);\n    stop = omp_get_wtime();\n    t_sw = stop - start;\n\n    float res_f = 0;\n    std::vector<float> vec1_f, vec2_f;\n    for(i = 0; i < length; i++) {\n        vec1_f.push_back(1);\n        vec2_f.push_back(i);\n    }\n    start = omp_get_wtime();\n    #pragma omp parallel private(i) num_threads(8)\n    {\n        #pragma omp for reduction(+:res_f)\n        for(i = 0; i < length; i++) {\n            res_f += vec1_f[i] * vec2_f[i];\n        }\n    }\n    stop = omp_get_wtime();\n    t_float = stop - start;\n\n    // std::vector<cpp_dec_float_100> vec1_dec, vec2_dec;\n    // for(i = 0; i < length; i++) {\n    //     vec1_dec.push_back(1);\n    //     vec2_dec.push_back(i);\n    // }\n    // for(i = 0; i < length; i++) {\n    //     res_dec = res_dec + vec1_dec[i] * vec2_dec[i];\n    // }\n\n    return to_string_precision(t_fpga) + \",\" + to_string_precision(t_sw) + \",\" + to_string_precision(t_float);\n}\n\nstd::string test_add(int length) {\n    int i;\n    double t_fpga, t_sw, t_float;\n    double stop, start;\n    // Vector Add\n    std::vector<posit<NBITS,ES>> vec1, vec2;\n    std::vector<posit<NBITS,ES>> result;\n    result.resize(length);\n\n    for(i = 0; i < length; i++){\n        vec1.push_back(i);\n        vec2.push_back(i);\n    }\n    t_fpga = 0;//vector_add(vec1, vec2, result);\n\n    start = omp_get_wtime();\n    for(i = 0; i < length; i++) {\n        result[i] = vec1[i] + vec2[i];\n    }\n    stop = omp_get_wtime();\n    t_sw = stop - start;\n\n    std::vector<float> vec1_f, vec2_f;\n    std::vector<float> res_f;\n    res_f.resize(length);\n    for(i = 0; i < length; i++) {\n        vec1_f.push_back(i);\n        vec2_f.push_back(i);\n    }\n    start = omp_get_wtime();\n    #pragma omp parallel private(i) num_threads(8)\n    {\n        for(i = 0; i < length; i++) {\n            res_f[i] = vec1_f[i] + vec2_f[i];\n        }\n    }\n    stop = omp_get_wtime();\n    t_float = stop - start;\n\n    // std::vector<cpp_dec_float_100> vec1_dec, vec2_dec;\n    // std::vector<cpp_dec_float_100> res_dec;\n    // res_dec.resize(length);\n    // for(i = 0; i < length; i++) {\n    //     vec1_dec.push_back(i);\n    //     vec2_dec.push_back(i);\n    // }\n    // for(i = 0; i < length; i++) {\n    //     res_dec[i] = vec1_dec[i] * vec2_dec[i];\n    // }\n\n    return to_string_precision(t_fpga) + \",\" + to_string_precision(t_sw) + \",\" + to_string_precision(t_float);\n}\n\nstd::string test_add_scalar(int length) {\n    int i;\n    double t_fpga, t_sw, t_float;\n    double stop, start;\n    // Vector Add Scalar\n    std::vector<posit<NBITS,ES>> vec1;\n    std::vector<posit<NBITS,ES>> result;\n    posit<NBITS,ES> scalar;\n    result.resize(length);\n\n    for(i = 0; i < length; i++){\n        vec1.push_back(i);\n    }\n    scalar = 5;\n    t_fpga = 0;//vector_add(vec1, scalar, result);\n\n    start = omp_get_wtime();\n    for(i = 0; i < length; i++) {\n        result[i] = vec1[i] + scalar;\n    }\n    stop = omp_get_wtime();\n    t_sw = stop - start;\n\n    std::vector<float> vec1_f;\n    std::vector<float> res_f;\n    res_f.resize(length);\n    for(i = 0; i < length; i++) {\n        vec1_f.push_back(i);\n    }\n    start = omp_get_wtime();\n    #pragma omp parallel private(i) num_threads(8)\n    {\n        for(i = 0; i < length; i++) {\n            res_f[i] = vec1_f[i] + 5.0;\n        }\n    }\n    stop = omp_get_wtime();\n    t_float = stop - start;\n\n    // std::vector<cpp_dec_float_100> vec1_dec;\n    // std::vector<cpp_dec_float_100> res_dec;\n    // res_dec.resize(length);\n    // for(i = 0; i < length; i++) {\n    //     vec1_dec.push_back(i);\n    // }\n    // for(i = 0; i < length; i++) {\n    //     res_dec[i] = vec1_dec[i] + 5.0;\n    // }\n\n    return to_string_precision(t_fpga) + \",\" + to_string_precision(t_sw) + \",\" + to_string_precision(t_float);\n}\n\nstd::string test_subtract(int length) {\n    int i;\n    double t_fpga, t_sw, t_float;\n    double stop, start;\n    // Vector Subtract\n    std::vector<posit<NBITS,ES>> vec1, vec2;\n    std::vector<posit<NBITS,ES>> result;\n    result.resize(length);\n\n    for(i = 0; i < length; i++){\n        vec1.push_back(i);\n        vec2.push_back(i);\n    }\n    t_fpga = 0;//vector_sub(vec1, vec2, result);\n\n    start = omp_get_wtime();\n    for(i = 0; i < length; i++) {\n        result[i] = vec1[i] - vec2[i];\n    }\n    stop = omp_get_wtime();\n    t_sw = stop - start;\n\n    std::vector<float> vec1_f, vec2_f;\n    std::vector<float> res_f;\n    res_f.resize(length);\n    for(i = 0; i < length; i++) {\n        vec1_f.push_back(i);\n        vec2_f.push_back(i);\n    }\n    start = omp_get_wtime();\n    #pragma omp parallel private(i) num_threads(8)\n    {\n        for(i = 0; i < length; i++) {\n            res_f[i] = vec1_f[i] - vec2_f[i];\n        }\n    }\n    stop = omp_get_wtime();\n    t_float = stop - start;\n\n    // std::vector<cpp_dec_float_100> vec1_dec, vec2_dec;\n    // std::vector<cpp_dec_float_100> res_dec;\n    // res_dec.resize(length);\n    // for(i = 0; i < length; i++) {\n    //     vec1_dec.push_back(i);\n    //     vec2_dec.push_back(i);\n    // }\n    // for(i = 0; i < length; i++) {\n    //     res_dec[i] = vec1_dec[i] - vec2_dec[i];\n    // }\n\n    return to_string_precision(t_fpga) + \",\" + to_string_precision(t_sw) + \",\" + to_string_precision(t_float);\n}\n\nstd::string test_subtract_scalar(int length) {\n    int i;\n    double t_fpga, t_sw, t_float;\n    double stop, start;\n    // Vector Subtract Scalar\n    std::vector<posit<NBITS,ES>> vec1;\n    std::vector<posit<NBITS,ES>> result;\n    posit<NBITS,ES> scalar;\n    result.resize(length);\n\n    for(i = 0; i < length; i++){\n        vec1.push_back(i);\n    }\n    scalar = 5;\n    t_fpga = 0;//vector_sub(vec1, scalar, result);\n\n    start = omp_get_wtime();\n    for(i = 0; i < length; i++) {\n        result[i] = vec1[i] - scalar;\n    }\n    stop = omp_get_wtime();\n    t_sw = stop - start;\n\n    std::vector<float> vec1_f;\n    std::vector<float> res_f;\n    res_f.resize(length);\n    for(i = 0; i < length; i++) {\n        vec1_f.push_back(i);\n    }\n    start = omp_get_wtime();\n    #pragma omp parallel private(i) num_threads(8)\n    {\n        for(i = 0; i < length; i++) {\n            res_f[i] = vec1_f[i] - 5.0;\n        }\n    }\n    stop = omp_get_wtime();\n    t_float = stop - start;\n\n    // std::vector<cpp_dec_float_100> vec1_dec;\n    // std::vector<cpp_dec_float_100> res_dec;\n    // res_dec.resize(length);\n    // for(i = 0; i < length; i++) {\n    //     vec1_dec.push_back(i);\n    // }\n    // for(i = 0; i < length; i++) {\n    //     res_dec[i] = vec1_dec[i] - 5.0;\n    // }\n\n    return to_string_precision(t_fpga) + \",\" + to_string_precision(t_sw) + \",\" + to_string_precision(t_float);\n}\n\nstd::string test_sum(int length) {\n    int i;\n    double t_fpga, t_sw, t_float;\n    double stop, start;\n    // Vector Sum\n    std::vector<posit<NBITS,ES>> vec1;\n    posit<NBITS,ES> result;\n\n    for(i = 0; i < length; i++){\n        vec1.push_back(i);\n    }\n    t_fpga = 0;//vector_sum(vec1, result);\n\n    start = omp_get_wtime();\n    // for(i = 0; i < length; i++) {\n    //     result = result + vec1[i];\n    // }\n    result = sw::hprblas::asum(length, vec1, 1);\n    stop = omp_get_wtime();\n    t_sw = stop - start;\n\n    std::vector<float> vec1_f;\n    float res_f = 0.0;\n    for(i = 0; i < length; i++) {\n        vec1_f.push_back(i);\n    }\n    start = omp_get_wtime();\n    #pragma omp parallel private(i) num_threads(8)\n    {\n        for(i = 0; i < length; i++) {\n            res_f = res_f + vec1_f[i];\n        }\n    }\n    stop = omp_get_wtime();\n    t_float = stop - start;\n\n    // std::vector<cpp_dec_float_100> vec1_dec;\n    // cpp_dec_float_100 res_dec = 0.0;\n    // for(i = 0; i < length; i++) {\n    //     vec1_dec.push_back(i);\n    // }\n    // for(i = 0; i < length; i++) {\n    //     res_dec = res_dec + vec1_dec[i];\n    // }\n\n    return to_string_precision(t_fpga) + \",\" + to_string_precision(t_sw) + \",\" + to_string_precision(t_float);\n}\n\nstd::string test_mult(int length) {\n    int i;\n    double t_fpga, t_sw, t_float;\n    double stop, start;\n    // Vector Multiplication\n    std::vector<posit<NBITS,ES>> vec1, vec2;\n    std::vector<posit<NBITS,ES>> result;\n    result.resize(length);\n\n    for(i = 0; i < length; i++){\n        vec1.push_back(i);\n        vec2.push_back(i);\n    }\n    t_fpga = 0;//vector_mult(vec1, vec2, result);\n\n    start = omp_get_wtime();\n    for(i = 0; i < length; i++) {\n        result[i] = vec1[i] * vec2[i];\n    }\n    stop = omp_get_wtime();\n    t_sw = stop - start;\n\n    std::vector<float> vec1_f, vec2_f;\n    std::vector<float> res_f;\n    res_f.resize(length);\n    for(i = 0; i < length; i++) {\n        vec1_f.push_back(i);\n        vec2_f.push_back(i);\n    }\n    start = omp_get_wtime();\n    #pragma omp parallel private(i) num_threads(8)\n    {\n        for(i = 0; i < length; i++) {\n            res_f[i] = vec1_f[i] * vec2_f[i];\n        }\n    }\n    stop = omp_get_wtime();\n    t_float = stop - start;\n\n    // std::vector<cpp_dec_float_100> vec1_dec, vec2_dec;\n    // std::vector<cpp_dec_float_100> res_dec;\n    // res_dec.resize(length);\n    // for(i = 0; i < length; i++) {\n    //     vec1_dec.push_back(i);\n    //     vec2_dec.push_back(i);\n    // }\n    // for(i = 0; i < length; i++) {\n    //     res_dec[i] = vec1_dec[i] * vec2_dec[i];\n    // }\n\n    return to_string_precision(t_fpga) + \",\" + to_string_precision(t_sw) + \",\" + to_string_precision(t_float);\n}\n\nstd::string test_mult_scalar(int length) {\n    int i;\n    double t_fpga, t_sw, t_float;\n    double start, stop;\n    // Vector Multiplication Scalar\n    std::vector<posit<NBITS,ES>> vec1;\n    std::vector<posit<NBITS,ES>> result;\n    posit<NBITS,ES> scalar;\n    result.resize(length);\n\n    for(i = 0; i < length; i++){\n        vec1.push_back(i);\n    }\n    scalar = 5;\n    t_fpga = 0;//vector_mult(vec1, scalar, result);\n\n    start = omp_get_wtime();\n    for(i = 0; i < length; i++){\n        result[i] = vec1[i] * scalar;\n    }\n    stop = omp_get_wtime();\n    t_sw = stop - start;\n\n    std::vector<float> vec_f;\n    std::vector<float> result_f;\n    result_f.resize(length);\n    for(i = 0; i < length; i++){\n        vec_f.push_back(i);\n    }\n    start = omp_get_wtime();\n    #pragma omp parallel private(i) num_threads(8)\n    {\n        for(i = 0; i < length; i++){\n            result_f[i] = vec_f[i] * 5.0;\n        }\n    }\n    stop = omp_get_wtime();\n    t_float = stop - start;\n\n    // std::vector<cpp_dec_float_100> vec_dec;\n    // std::vector<cpp_dec_float_100> result_dec;\n    // result_dec.resize(length);\n    // for(i = 0; i < length; i++){\n    //     vec_dec.push_back(i);\n    // }\n    // for(i = 0; i < length; i++){\n    //     result_dec[i] = vec_dec[i] * 5.0;\n    // }\n\n    return to_string_precision(t_fpga) + \",\" + to_string_precision(t_sw) + \",\" + to_string_precision(t_float);\n}\n\n\n// template<typename T>\n// cpp_dec_float_100 aggregateGram(vector<vector<T > >& u) {\n//     cpp_dec_float_100 a = 0.0;\n//     for(vector<T>& u_vec : u) {\n//         a += (cpp_dec_float_100)u_vec.sum();\n//     }\n//     return a;\n// }\n//\n// template<typename T>\n// cpp_dec_float_100 aggregateGram(valarray<valarray<T > >& u) {\n//     cpp_dec_float_100 a = 0.0;\n//     for(valarray<T>& u_vec : u) {\n//         a += (cpp_dec_float_100)u_vec.sum();\n//     }\n// }\n\n// std::string test_gram(int n, int m) {\n//     int i;\n//     double stop, start;\n//     double t_sw = 0.0, t_fpga = 0.0, t_float = 0.0;\n//     cpp_dec_float_100 a_dec = 0.0, a_sw = 0.0, a_fpga = 0.0, a_float = 0.0;\n//     cpp_dec_float_100 da_sw = 0.0, da_hw = 0.0, da_float = 0.0;\n//\n//     // Gram Matrix Test\n//\n//     // POSIT FPGA\n//     vector<vector<posit<NBITS, ES> > > v(n);\n//     vector<vector<posit<NBITS, ES> > > u(n); // Orthogonal set\n//\n//     for(i = 0; i < n; i++) {\n//         u[i].resize(m);\n//     }\n//\n//     // // Fill vectors\n//     // for(i = 0; i < n; i++) {\n//     //     vector<posit<NBITS, ES>> vec(m);\n//     //     for(int j = 0; j < m; j++) {\n//     //         vec[j] = sqrt(2)/2;\n//     //     }\n//     //     v[i] = vec;\n//     // }\n//     //\n//     // // Start\n//     // start = omp_get_wtime();\n//     // u[0] = v[0];\n//     // i = 0;\n//     // do {\n//     //         vector<posit<NBITS,ES> > sum = sumProj(v, u, i);\n//     //         vector_sub(v[i], sum, u[i]);\n//     //         i++;\n//     // } while(i < n);\n//     // stop = omp_get_wtime();\n//     // t_fpga = stop - start;\n//     //\n//     // a_fpga = aggregateGram(u);\n//\n//     // POSIT SW\n//     valarray<valarray<posit<NBITS,ES> > > v_posit(n);\n//     valarray<valarray<posit<NBITS,ES> > > u_posit(n);\n//     u_posit.resize(n);\n//     // Fill vectors\n//     for(i = 0; i < n; i++) {\n//         valarray<posit<NBITS,ES>> vec(m);\n//         for(int j = 0; j < m; j++) {\n//             vec[j] = sqrt(2)/2;\n//         }\n//         v_posit[i] = vec;\n//     }\n//\n//     for(i = 0; i < n; i++) {\n//         u_posit[i].resize(m);\n//     }\n//\n//     start = omp_get_wtime();\n//     u_posit[0] = v_posit[0];\n//     i = 0;\n//     do {\n//             valarray<posit<NBITS,ES>> sum = sumProj(v_posit, u_posit, i);\n//             u_posit[i] = v_posit[i] - sum;\n//             i++;\n//     } while(i < n);\n//     stop = omp_get_wtime();\n//     t_sw = stop - start;\n//\n//     a_sw = aggregateGram(u_posit);\n//\n//     // FLOAT\n//     valarray<valarray<float > > v_float(n);\n//     valarray<valarray<float > > u_float(n);\n//\n//     // Fill vectors\n//     for(i = 0; i < n; i++) {\n//         valarray<float> vec(m);\n//         for(int j = 0; j < m; j++) {\n//             vec[j] = sqrt(2)/2;\n//         }\n//         v_float[i] = vec;\n//     }\n//\n//     for(i = 0; i < n; i++) {\n//         u_float[i].resize(m);\n//     }\n//\n//     start = omp_get_wtime();\n//     u_float[0] = v_float[0];\n//     i = 0;\n//     do {\n//             valarray<float> sum = sumProj(v_float, u_float, i);\n//             u_float[i] = v_float[i] - sum;\n//             i++;\n//     } while(i < n);\n//     stop = omp_get_wtime();\n//     t_float = stop - start;\n//\n//     a_float = aggregateGram(u_float);\n//\n//     // cpp_dec_float_100\n//     valarray<valarray<cpp_dec_float_100 > > v_dec(n);\n//     valarray<valarray<cpp_dec_float_100 > > u_dec(n);\n//\n//     // Fill vectors\n//     for(i = 0; i < n; i++) {\n//         valarray<cpp_dec_float_100> vec(m);\n//         for(int j = 0; j < m; j++) {\n//             vec[j] = sqrt(2)/2;\n//         }\n//         v_dec[i] = vec;\n//     }\n//\n//     for(i = 0; i < n; i++) {\n//         u_dec[i].resize(m);\n//     }\n//\n//     u_dec[0] = v_dec[0];\n//     i = 0;\n//     do {\n//             valarray<cpp_dec_float_100> sum = sumProj(v_dec, u_dec, i);\n//             u_dec[i] = v_dec[i] - sum;\n//             i++;\n//     } while(i < n);\n//\n//     a_dec = aggregateGram(u_dec);\n//\n//     // Calculate decimal accuracy\n//     da_hw = decimal_accuracy(a_dec, a_fpga);\n//     da_sw = decimal_accuracy(a_dec, a_sw);\n//     da_float = decimal_accuracy(a_dec, a_float);\n//\n//     return to_string_precision(t_fpga) + \",\" + to_string_precision(t_sw) + \",\" + to_string_precision(t_float) + \",\" + to_string_precision(da_hw) + \",\" + to_string_precision(da_sw) + \",\" + to_string_precision(da_float);\n// }\n", "meta": {"hexsha": "c3f520ce6bded8479fa71f44433419a8336d5fde", "size": 20152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/benchmark/src/main.cpp", "max_stars_repo_name": "lvandam/posit_blas_hdl", "max_stars_repo_head_hexsha": "4427bcf13cede86f626772903c546cbeae42457e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-31T10:22:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-31T22:24:22.000Z", "max_issues_repo_path": "examples/benchmark/src/main.cpp", "max_issues_repo_name": "lvandam/posit_blas_hdl", "max_issues_repo_head_hexsha": "4427bcf13cede86f626772903c546cbeae42457e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-01T12:49:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-01T12:49:45.000Z", "max_forks_repo_path": "examples/benchmark/src/main.cpp", "max_forks_repo_name": "lvandam/posit_blas_hdl", "max_forks_repo_head_hexsha": "4427bcf13cede86f626772903c546cbeae42457e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5677154583, "max_line_length": 221, "alphanum_fraction": 0.5340909091, "num_tokens": 6344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6425638009061361}}
{"text": "#include \"nth_prime.h\"\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <stdexcept>\n\nBOOST_AUTO_TEST_CASE(first)\n{\n    BOOST_REQUIRE_EQUAL(2, prime::nth(1));\n}\n\n\nBOOST_AUTO_TEST_CASE(second)\n{\n    BOOST_REQUIRE_EQUAL(3, prime::nth(2));\n}\n\nBOOST_AUTO_TEST_CASE(sixth)\n{\n    BOOST_REQUIRE_EQUAL(13, prime::nth(6));\n}\n\nBOOST_AUTO_TEST_CASE(big_prime)\n{\n    BOOST_REQUIRE_EQUAL(104743, prime::nth(10001));\n}\n\nBOOST_AUTO_TEST_CASE(weird_case)\n{\n    BOOST_REQUIRE_THROW(prime::nth(0), std::domain_error);\n}\n\n#if defined(EXERCISM_RUN_ALL_TESTS)\n#endif\n", "meta": {"hexsha": "40e41ebcd8b13e22af8547aa8fdd2d20471a3cab", "size": 565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/nth-prime/nth_prime_test.cpp", "max_stars_repo_name": "mayurdw/exercism", "max_stars_repo_head_hexsha": "05e1440aba45ba18e47c40149b7f47adbac8e4c5", "max_stars_repo_licenses": ["MIT"], "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/nth-prime/nth_prime_test.cpp", "max_issues_repo_name": "mayurdw/exercism", "max_issues_repo_head_hexsha": "05e1440aba45ba18e47c40149b7f47adbac8e4c5", "max_issues_repo_licenses": ["MIT"], "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/nth-prime/nth_prime_test.cpp", "max_forks_repo_name": "mayurdw/exercism", "max_forks_repo_head_hexsha": "05e1440aba45ba18e47c40149b7f47adbac8e4c5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.6176470588, "max_line_length": 58, "alphanum_fraction": 0.7469026549, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.6425538752089898}}
{"text": "/**\n * @file\n * @author lkoppel\n */\n\n#ifndef WAVE_GEOMETRY_UTIL_MATH_HPP\n#define WAVE_GEOMETRY_UTIL_MATH_HPP\n\n#include <Eigen/Core>\n#include <random>\n\nnamespace wave {\n\n/** Generate a random real number on the closed interval [a, b] */\ntemplate <typename Real>\nReal uniformRandom(Real a, Real b) {\n    // Use Mersenne Twister pseudo-random number generator, seeded by system random device\n    static std::mt19937 rng{std::random_device{}()};\n\n    // The distribution is normally open on one end [a, b). Do this to close it\n    const auto closed_b = std::nextafter(b, std::numeric_limits<Real>::max());\n\n    // Pick a real from the distribution\n    return std::uniform_real_distribution<Real>{a, closed_b}(rng);\n}\n\n\n/** Generate a random unit quaternion on SO(3)\n *\n * Implements Algorithm 2 from Kuffner, James J. \"Effective Sampling and Distance Metrics\n * for 3D Rigid Body Path Planning.\"\n * https://www.ri.cmu.edu/pub_files/pub4/kuffner_james_2004_1/kuffner_james_2004_1.pdf\n */\ntemplate <typename Real>\nEigen::Quaternion<Real> randomQuaternion() {\n    const Real s = uniformRandom(Real{0}, Real{1});\n    const Real s1 = std::sqrt(1 - s);\n    const Real s2 = std::sqrt(s);\n    const Real t1 = Real{2 * M_PI} * uniformRandom(Real{0}, Real{1});\n    const Real t2 = Real{2 * M_PI} * uniformRandom(Real{0}, Real{1});\n    return Eigen::Quaternion<Real>{\n      std::cos(t2) * s2, std::sin(t1) * s1, std::cos(t1) * s1, std::sin(t2) * s2};\n}\n\n/** Go from a skew-symmetric (cross) matrix to a compact vector\n *\n * Also known as the \"vee\" operator.\n */\ntemplate <typename Derived>\nauto uncrossMatrix(const Eigen::MatrixBase<Derived> &skew)\n  -> Eigen::Matrix<typename Eigen::internal::traits<Derived>::Scalar, 3, 1> {\n    EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Derived, 3, 3);\n    return Eigen::Matrix<typename Eigen::internal::traits<Derived>::Scalar, 3, 1>{\n      skew(2, 1), skew(0, 2), skew(1, 0)};\n}\n\n}  // namespace wave\n\n#endif  // WAVE_GEOMETRY_UTIL_MATH_HPP\n", "meta": {"hexsha": "73abb3ea9a63d51084587578ff2245317472d0db", "size": 1963, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/wave/geometry/src/util/math/math.hpp", "max_stars_repo_name": "wavelab/wave_geometry", "max_stars_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2018-05-07T00:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:14:07.000Z", "max_issues_repo_path": "include/wave/geometry/src/util/math/math.hpp", "max_issues_repo_name": "wavelab/wave_geometry", "max_issues_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-08-02T20:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T17:45:29.000Z", "max_forks_repo_path": "include/wave/geometry/src/util/math/math.hpp", "max_forks_repo_name": "wavelab/wave_geometry", "max_forks_repo_head_hexsha": "aabcad44a490fc6393b35e63db9ad8908cf46dec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-05-27T01:08:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T13:46:31.000Z", "avg_line_length": 32.7166666667, "max_line_length": 90, "alphanum_fraction": 0.6923076923, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6425538742410085}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file testQPSolver.cpp\n * @brief Test simple QP solver for a linear inequality constraint\n * @date Apr 10, 2014\n * @author Duy-Nguyen Ta\n */\n\n#include <gtsam/base/Testable.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/inference/FactorGraph-inst.h>\n#include <gtsam/linear/VectorValues.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam_unstable/linear/EqualityFactorGraph.h>\n#include <gtsam_unstable/linear/InequalityFactorGraph.h>\n#include <gtsam_unstable/linear/InfeasibleInitialValues.h>\n#include <CppUnitLite/TestHarness.h>\n#include <boost/foreach.hpp>\n#include <boost/range/adaptor/map.hpp>\n\n#include <gtsam_unstable/linear/LPSolver.h>\n#include <gtsam_unstable/linear/LPInitSolver.h>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace gtsam::symbol_shorthand;\n\nstatic const Vector kOne = Vector::Ones(1), kZero = Vector::Zero(1);\n\n/* ************************************************************************* */\n/**\n * min -x1-x2\n * s.t.   x1 + 2x2 <= 4\n *       4x1 + 2x2 <= 12\n *       -x1 +  x2 <= 1\n *       x1, x2 >= 0\n */\nLP simpleLP1() {\n  LP lp;\n  lp.cost = LinearCost(1, Vector2(-1., -1.));  // min -x1-x2 (max x1+x2)\n  lp.inequalities.push_back(\n      LinearInequality(1, Vector2(-1, 0), 0, 1));  // x1 >= 0\n  lp.inequalities.push_back(\n      LinearInequality(1, Vector2(0, -1), 0, 2));  //  x2 >= 0\n  lp.inequalities.push_back(\n      LinearInequality(1, Vector2(1, 2), 4, 3));  //  x1 + 2*x2 <= 4\n  lp.inequalities.push_back(\n      LinearInequality(1, Vector2(4, 2), 12, 4));  //  4x1 + 2x2 <= 12\n  lp.inequalities.push_back(\n      LinearInequality(1, Vector2(-1, 1), 1, 5));  //  -x1 + x2 <= 1\n  return lp;\n}\n\n/* ************************************************************************* */\nnamespace gtsam {\n\nTEST(LPInitSolver, infinite_loop_single_var) {\n  LP initchecker;\n  initchecker.cost = LinearCost(1, Vector3(0, 0, 1));  // min alpha\n  initchecker.inequalities.push_back(\n      LinearInequality(1, Vector3(-2, -1, -1), -2, 1));  //-2x-y-alpha <= -2\n  initchecker.inequalities.push_back(\n      LinearInequality(1, Vector3(-1, 2, -1), 6, 2));  // -x+2y-alpha <= 6\n  initchecker.inequalities.push_back(\n      LinearInequality(1, Vector3(-1, 0, -1), 0, 3));  // -x - alpha <= 0\n  initchecker.inequalities.push_back(\n      LinearInequality(1, Vector3(1, 0, -1), 20, 4));  // x - alpha <= 20\n  initchecker.inequalities.push_back(\n      LinearInequality(1, Vector3(0, -1, -1), 0, 5));  // -y - alpha <= 0\n  LPSolver solver(initchecker);\n  VectorValues starter;\n  starter.insert(1, Vector3(0, 0, 2));\n  VectorValues results, duals;\n  boost::tie(results, duals) = solver.optimize(starter);\n  VectorValues expected;\n  expected.insert(1, Vector3(13.5, 6.5, -6.5));\n  CHECK(assert_equal(results, expected, 1e-7));\n}\n\nTEST(LPInitSolver, infinite_loop_multi_var) {\n  LP initchecker;\n  Key X = symbol('X', 1);\n  Key Y = symbol('Y', 1);\n  Key Z = symbol('Z', 1);\n  initchecker.cost = LinearCost(Z, kOne);  // min alpha\n  initchecker.inequalities.push_back(\n      LinearInequality(X, -2.0 * kOne, Y, -1.0 * kOne, Z, -1.0 * kOne, -2,\n                       1));  //-2x-y-alpha <= -2\n  initchecker.inequalities.push_back(\n      LinearInequality(X, -1.0 * kOne, Y, 2.0 * kOne, Z, -1.0 * kOne, 6,\n                       2));  // -x+2y-alpha <= 6\n  initchecker.inequalities.push_back(LinearInequality(\n      X, -1.0 * kOne, Z, -1.0 * kOne, 0, 3));  // -x - alpha <= 0\n  initchecker.inequalities.push_back(LinearInequality(\n      X, 1.0 * kOne, Z, -1.0 * kOne, 20, 4));  // x - alpha <= 20\n  initchecker.inequalities.push_back(LinearInequality(\n      Y, -1.0 * kOne, Z, -1.0 * kOne, 0, 5));  // -y - alpha <= 0\n  LPSolver solver(initchecker);\n  VectorValues starter;\n  starter.insert(X, kZero);\n  starter.insert(Y, kZero);\n  starter.insert(Z, Vector::Constant(1, 2.0));\n  VectorValues results, duals;\n  boost::tie(results, duals) = solver.optimize(starter);\n  VectorValues expected;\n  expected.insert(X, Vector::Constant(1, 13.5));\n  expected.insert(Y, Vector::Constant(1, 6.5));\n  expected.insert(Z, Vector::Constant(1, -6.5));\n  CHECK(assert_equal(results, expected, 1e-7));\n}\n\nTEST(LPInitSolver, initialization) {\n  LP lp = simpleLP1();\n  LPInitSolver initSolver(lp);\n\n  GaussianFactorGraph::shared_ptr initOfInitGraph =\n      initSolver.buildInitOfInitGraph();\n  VectorValues x0 = initOfInitGraph->optimize();\n  VectorValues expected_x0;\n  expected_x0.insert(1, Vector::Zero(2));\n  CHECK(assert_equal(expected_x0, x0, 1e-10));\n\n  double y0 = initSolver.compute_y0(x0);\n  double expected_y0 = 0.0;\n  DOUBLES_EQUAL(expected_y0, y0, 1e-7);\n\n  Key yKey = 2;\n  LP::shared_ptr initLP = initSolver.buildInitialLP(yKey);\n  LP expectedInitLP;\n  expectedInitLP.cost = LinearCost(yKey, kOne);\n  expectedInitLP.inequalities.push_back(LinearInequality(\n      1, Vector2(-1, 0), 2, Vector::Constant(1, -1), 0, 1));  // -x1 - y <= 0\n  expectedInitLP.inequalities.push_back(LinearInequality(\n      1, Vector2(0, -1), 2, Vector::Constant(1, -1), 0, 2));  // -x2 - y <= 0\n  expectedInitLP.inequalities.push_back(\n      LinearInequality(1, Vector2(1, 2), 2, Vector::Constant(1, -1), 4,\n                       3));  //  x1 + 2*x2 - y <= 4\n  expectedInitLP.inequalities.push_back(\n      LinearInequality(1, Vector2(4, 2), 2, Vector::Constant(1, -1), 12,\n                       4));  //  4x1 + 2x2 - y <= 12\n  expectedInitLP.inequalities.push_back(\n      LinearInequality(1, Vector2(-1, 1), 2, Vector::Constant(1, -1), 1,\n                       5));  //  -x1 + x2 - y <= 1\n  CHECK(assert_equal(expectedInitLP, *initLP, 1e-10));\n  LPSolver lpSolveInit(*initLP);\n  VectorValues xy0(x0);\n  xy0.insert(yKey, Vector::Constant(1, y0));\n  VectorValues xyInit = lpSolveInit.optimize(xy0).first;\n  VectorValues expected_init;\n  expected_init.insert(1, Vector::Ones(2));\n  expected_init.insert(2, Vector::Constant(1, -1));\n  CHECK(assert_equal(expected_init, xyInit, 1e-10));\n\n  VectorValues x = initSolver.solve();\n  CHECK(lp.isFeasible(x));\n}\n}\n\n/* ************************************************************************* */\n/**\n * TEST gtsam solver with an over-constrained system\n *  x + y = 1\n *  x - y = 5\n *  x + 2y = 6\n */\nTEST(LPSolver, overConstrainedLinearSystem) {\n  GaussianFactorGraph graph;\n  Matrix A1 = Vector3(1, 1, 1);\n  Matrix A2 = Vector3(1, -1, 2);\n  Vector b = Vector3(1, 5, 6);\n  JacobianFactor factor(1, A1, 2, A2, b, noiseModel::Constrained::All(3));\n  graph.push_back(factor);\n\n  VectorValues x = graph.optimize();\n  // This check confirms that gtsam linear constraint solver can't handle\n  // over-constrained system\n  CHECK(factor.error(x) != 0.0);\n}\n\nTEST(LPSolver, overConstrainedLinearSystem2) {\n  GaussianFactorGraph graph;\n  graph.emplace_shared<JacobianFactor>(1, I_1x1, 2, I_1x1, kOne,\n                                 noiseModel::Constrained::All(1));\n  graph.emplace_shared<JacobianFactor>(1, I_1x1, 2, -I_1x1, 5 * kOne,\n                                 noiseModel::Constrained::All(1));\n  graph.emplace_shared<JacobianFactor>(1, I_1x1, 2, 2 * I_1x1, 6 * kOne,\n                                 noiseModel::Constrained::All(1));\n  VectorValues x = graph.optimize();\n  // This check confirms that gtsam linear constraint solver can't handle\n  // over-constrained system\n  CHECK(graph.error(x) != 0.0);\n}\n\n/* ************************************************************************* */\nTEST(LPSolver, simpleTest1) {\n  LP lp = simpleLP1();\n  LPSolver lpSolver(lp);\n  VectorValues init;\n  init.insert(1, Vector::Zero(2));\n\n  VectorValues x1 =\n      lpSolver.buildWorkingGraph(InequalityFactorGraph(), init).optimize();\n  VectorValues expected_x1;\n  expected_x1.insert(1, Vector::Ones(2));\n  CHECK(assert_equal(expected_x1, x1, 1e-10));\n\n  VectorValues result, duals;\n  boost::tie(result, duals) = lpSolver.optimize(init);\n  VectorValues expectedResult;\n  expectedResult.insert(1, Vector2(8. / 3., 2. / 3.));\n  CHECK(assert_equal(expectedResult, result, 1e-10));\n}\n\n/* ************************************************************************* */\nTEST(LPSolver, testWithoutInitialValues) {\n  LP lp = simpleLP1();\n  LPSolver lpSolver(lp);\n  VectorValues result, duals, expectedResult;\n  expectedResult.insert(1, Vector2(8. / 3., 2. / 3.));\n  boost::tie(result, duals) = lpSolver.optimize();\n  CHECK(assert_equal(expectedResult, result));\n}\n\n/**\n * TODO: More TEST cases:\n * - Infeasible\n * - Unbounded\n * - Underdetermined\n */\n/* ************************************************************************* */\nTEST(LPSolver, LinearCost) {\n  LinearCost cost(1, Vector3(2., 4., 6.));\n  VectorValues x;\n  x.insert(1, Vector3(1., 3., 5.));\n  double error = cost.error(x);\n  double expectedError = 44.0;\n  DOUBLES_EQUAL(expectedError, error, 1e-100);\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "a105a39f0af63ccd1d17de1e45d4dc17d172eac3", "size": 9316, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_unstable/linear/tests/testLPSolver.cpp", "max_stars_repo_name": "kvmanohar22/gtsam", "max_stars_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-12-11T18:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:52:45.000Z", "max_issues_repo_path": "gtsam_unstable/linear/tests/testLPSolver.cpp", "max_issues_repo_name": "kvmanohar22/gtsam", "max_issues_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "gtsam_unstable/linear/tests/testLPSolver.cpp", "max_forks_repo_name": "kvmanohar22/gtsam", "max_forks_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T16:24:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T11:10:49.000Z", "avg_line_length": 36.390625, "max_line_length": 80, "alphanum_fraction": 0.602189781, "num_tokens": 2877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7690802264851918, "lm_q1q2_score": 0.6425538553384637}}
{"text": "#include <stan/math/rev/arr.hpp>\n#include <gtest/gtest.h>\n\n\n#include <iostream>\n#include <sstream>\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n\n\n\n#include <test/unit/math/rev/arr/functor/util.hpp>\n\n#include <test/unit/math/prim/arr/functor/harmonic_oscillator.hpp>\n#include <test/unit/math/prim/arr/functor/lorenz.hpp>\n\n\ntemplate <typename F, typename T_y0, typename T_theta>\nvoid sho_value_test(F harm_osc,\n                    std::vector<double>& y0,\n                    double t0,\n                    std::vector<double>& ts,\n                    std::vector<double>& theta,\n                    std::vector<double>& x,\n                    std::vector<int>& x_int) {\n  \n  using stan::math::var;\n  using stan::math::promote_scalar;\n\n  std::vector<std::vector<var> >  ode_res_vd\n    = stan::math::integrate_ode_rk45(harm_osc, promote_scalar<T_y0>(y0), t0,\n                                     ts, promote_scalar<T_theta>(theta), x, x_int,\n                                     0);\n  EXPECT_NEAR(0.995029, ode_res_vd[0][0].val(), 1e-5);\n  EXPECT_NEAR(-0.0990884, ode_res_vd[0][1].val(), 1e-5);\n\n  EXPECT_NEAR(-0.421907, ode_res_vd[99][0].val(), 1e-5);\n  EXPECT_NEAR(0.246407, ode_res_vd[99][1].val(), 1e-5);\n\n}\n\nvoid sho_finite_diff_test(double t0) {\n  using stan::math::var;  \n  harm_osc_ode_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n\n  test_ode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8,1e-4);\n\n  sho_value_test<harm_osc_ode_fun,double,var>(harm_osc, y0, t0, ts, theta, x, x_int);\n  sho_value_test<harm_osc_ode_fun,var,double>(harm_osc, y0, t0, ts, theta, x, x_int);\n  sho_value_test<harm_osc_ode_fun,var,var>(harm_osc, y0, t0, ts, theta, x, x_int);\n}\n\nvoid sho_data_finite_diff_test(double t0) {\n  using stan::math::var;  \n  harm_osc_ode_data_fun harm_osc;\n\n  std::vector<double> theta;\n  theta.push_back(0.15);\n\n  std::vector<double> y0;\n  y0.push_back(1.0);\n  y0.push_back(0.0);\n\n\n  std::vector<double> ts;\n  for (int i = 0; i < 100; i++)\n    ts.push_back(t0 + 0.1 * (i + 1));\n\n  std::vector<double> x(3,1);\n  std::vector<int> x_int(2,0);\n\n  test_ode(harm_osc, t0, ts, y0, theta, x, x_int, 1e-8,1e-4);\n\n  sho_value_test<harm_osc_ode_data_fun,double,var>(harm_osc, y0, t0, ts, theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun,var,double>(harm_osc, y0, t0, ts, theta, x, x_int);\n  sho_value_test<harm_osc_ode_data_fun,var,var>(harm_osc, y0, t0, ts, theta, x, x_int);\n  \n}\n\n\nTEST(StanAgradRevOde_integrate_ode_rk45, harmonic_oscillator_finite_diff) {\n  sho_finite_diff_test(0);\n  sho_finite_diff_test(1.0);\n  sho_finite_diff_test(-1.0);\n\n  sho_data_finite_diff_test(0);\n  sho_data_finite_diff_test(1.0);\n  sho_data_finite_diff_test(-1.0);\n}\n\n\n\nTEST(StanAgradRevOde_integrate_ode_rk45, lorenz_finite_diff) {\n  lorenz_ode_fun lorenz;\n\n  std::vector<double> y0;\n  std::vector<double> theta;\n  double t0;\n  std::vector<double> ts;\n\n  t0 = 0;\n\n  theta.push_back(10.0);\n  theta.push_back(28.0);\n  theta.push_back(8.0/3.0);\n  y0.push_back(10.0);\n  y0.push_back(1.0);\n  y0.push_back(1.0);\n\n  std::vector<double> x;\n  std::vector<int> x_int;\n\n  for (int i = 0; i < 100; i++)\n    ts.push_back(0.1*(i+1));\n\n  test_ode(lorenz, t0, ts, y0, theta, x, x_int, 1e-8, 1e-1);\n}\n", "meta": {"hexsha": "1d0d3e1bf744c920028a25f2137e288ab807e6a6", "size": 3425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/arr/functor/integrate_ode_rk45_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/arr/functor/integrate_ode_rk45_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/arr/functor/integrate_ode_rk45_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5597014925, "max_line_length": 90, "alphanum_fraction": 0.6481751825, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6425431192657377}}
{"text": "//\n//  EVD.hpp\n//\n//  Created by r. on 08/05/14\n//\n\n#ifndef round1_EVD_hpp\n#define round1_EVD_hpp\n\n// GSL\n#include <gsl/gsl_eigen.h>\n\n// Boost\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n//#include <boost/numeric/ublas/vector_sparse.hpp>\n//#include <boost/numeric/ublas/vector_proxy.hpp>\n//#include <boost/numeric/ublas/matrix_sparse.hpp>\n//#include <boost/numeric/ublas/operation.hpp>\n//#include <boost/numeric/ublas/operation_sparse.hpp>\n\nnamespace gsl\n{\n\tstruct EVD\n\t{\n\tpublic:\n\t\ttypedef boost::numeric::ublas::matrix<double> matrix;\n\t\ttypedef boost::numeric::ublas::vector<double> vector;\n\tpublic:\n\t\t// These should not be changed from outside\n\t\tunsigned int n;\n\t\tmatrix V;\n\t\tvector d;\n\tpublic:\n\t\tEVD() : n(0), V(0,0), d(0) { }\n\tprivate:\n\t\t/*//\n\t\t void testV(const matrix& AE, const matrix& ME) const\n\t\t {\n\t\t namespace ublas = boost::numeric::ublas;\n\t\t \n\t\t vector u(n);\n\t\t for (unsigned int i = 0; i != u.size(); ++i) u(i) = i;\n\t\t double j = 1, k = 2;\n\t\t \n\t\t cout << \"A: \" << AE << endl;\n\t\t cout << \"M: \" << ME << endl;\n\t\t cout << \"V: \" << V << endl;\n\t\t cout << \"d: \" << d << endl;\n\t\t matrix W = ublas::trans(V);\n\t\t matrix AV = ublas::prod(AE, V), MV = ublas::prod(ME, V);\n\t\t cout << \"Vt A V: \" << ublas::prod(W, AV) << endl;\n\t\t cout << \"Vt M V: \" << ublas::prod(W, MV) << endl;\n\t\t \n\t\t vector f1(n);\n\t\t {\n\t\t f1 = ublas::prod(j*AE + k*ME, u);\n\t\t }\n\t\t vector f2(n);\n\t\t {\n\t\t f2 = ublas::prod(ME, u);\n\t\t f2 = ublas::prod(ublas::trans(V), f2);\n\t\t for (unsigned int i = 0; i != f2.size(); ++i)\n\t\t {\n\t\t f2(i) *= (j * d(i) + k);\n\t\t }\n\t\t f2 = ublas::prod(V, f2);\n\t\t f2 = ublas::prod(ME, f2);\n\t\t }\n\t\t cout << f1 << endl;\n\t\t cout << f2 << endl;\n\t\t cout << \"testV residual: \" << ublas::norm_inf(f1 - f2) << endl;\n\t\t assert(ublas::norm_inf(f1 - f2) <= 1e-6);\n\t\t }\n\t\t //*/\n\t\t\n\tpublic:\n\t\tEVD(const matrix& AE, const matrix& ME)\n\t\t:\n\t\tn(0), V(0,0), d(0)\n\t\t// Pre: AE and ME are square matrices of equal size\n\t\t{\n\t\t\t// Thanks to:\n\t\t\t// http://sector7.xray.aps.anl.gov/~dohnarms/programming/gsl/gsl-ref.pdf\n\t\t\t// http://www.ryolab.com/soft/aper/dd/d99/_2utility_2algorithm_2eigen_2eigentest_2main_8cpp-example.html\n\t\t\t\n\t\t\tn = (unsigned int)(AE.size1());\n\t\t\t\n\t\t\tassert((AE.size1() == n) && (AE.size2() == n));\n\t\t\tassert((ME.size1() == n) && (ME.size2() == n));\n\t\t\t\n\t\t\tgsl_eigen_gensymmv_workspace * w = gsl_eigen_gensymmv_alloc(n);\n\t\t\t\n\t\t\tmatrix A(n, n); A = AE;\n\t\t\tmatrix M(n, n); M = ME;\n\t\t\tgsl_matrix_view a = gsl_matrix_view_array(&A.data()[0], n, n);\n\t\t\tgsl_matrix_view m = gsl_matrix_view_array(&M.data()[0], n, n);\n\t\t\tgsl_matrix * U = gsl_matrix_alloc(n , n);\n\t\t\tgsl_vector * c = gsl_vector_alloc(n);\n\t\t\tgsl_eigen_gensymmv(&a.matrix, &m.matrix, c, U, w);\n\t\t\tgsl_eigen_gensymmv_sort(c, U, GSL_EIGEN_SORT_ABS_ASC);\n\t\t\t\n\t\t\tV = matrix(n, n);\n\t\t\td = vector(n);\n\t\t\tstd::copy(U->data, U->data + (n*n), &(V.data()[0]));\n\t\t\tstd::copy(c->data, c->data + n, &(d.data()[0]));\n\t\t\t\n\t\t\tgsl_vector_free(c);\n\t\t\tgsl_matrix_free(U);\n\t\t\tgsl_eigen_gensymmv_free(w);\n\t\t\t\n\t\t\t// M-normalize V\n\t\t\tfor (unsigned int i = 0; i != n; ++i)\n\t\t\t{\n\t\t\t\tnamespace ublas = boost::numeric::ublas;\n\t\t\t\tauto c = ublas::column(V, i);\n\t\t\t\tdouble norm = ublas::inner_prod(c, ublas::prod(ME, c));\n\t\t\t\t//cout << \"norm: \" << norm << endl;\n\t\t\t\tc *= (1/sqrt(norm));\n\t\t\t}\n\t\t\t\n\t\t\t//testV(AE, ME);\n\t\t}\n\t\t\n\t\tEVD& operator=(const EVD&) = default;\n\t};\n} // namespace tools\n\n#endif\n", "meta": {"hexsha": "e6c78bd47a2c2704f51e14e3aaa8fc9022b6c2f0", "size": 3447, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "parawt/c++/include/EVD.hpp", "max_stars_repo_name": "numpde/parabolic", "max_stars_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "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": "parawt/c++/include/EVD.hpp", "max_issues_repo_name": "numpde/parabolic", "max_issues_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "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": "parawt/c++/include/EVD.hpp", "max_forks_repo_name": "numpde/parabolic", "max_forks_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9172932331, "max_line_length": 107, "alphanum_fraction": 0.5860168262, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6425431186232601}}
{"text": "#include <iostream>\n#include <math.h>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\n\nvoid printString(cpp_int n,cpp_int m)\n{\n    /*\n    long long int Mm = 0;\n    long long int Res = (n*m);\n    long long int new_m = m;\n    */\n    cpp_int Mm = 0;\n    cpp_int Res = (n*m);\n    cpp_int new_m = m;\n\n    cpp_dec_float<100> temp = 0.0;\n\n//cout<<\"Res \"<<Res<<endl;\n\n    while(Res>=n)\n    {\n        temp = 1.0*new_m;\n        Mm = floor(log10(temp )/log10(2));\n\n        //Mm = floor(log10(1.0*new_m )/log10(2));\n\n        Res -= (n<<Mm);\n        new_m = Res/n;\n\n\n        if(Res > 0) cout<<\"(\"<<n<<\"<<\"<<Mm<<\") + \";\n\n        if(Res == 0) cout<<\"(\"<<n<<\"<<\"<<Mm<<\")\\n\";\n    }\n}\n\n\nint main()\n{\n    long int T; \n    //long long int N;\n    //long long int M;\n    cpp_int N;\n    cpp_int M;\n\n    cin >> T;\n\n    for(long int tt=0;tt<T;tt++)\n    {\n        cin >> N >> M;\n        printString(N,M);\n    }\n\n\n    //cout<<\"(\"<<N<<\"<<|log(\"<<M<<\")|) \"<<(N<<Mm) <<endl<<endl;\n\n    //cout<<\"(\"<<N<<\"*\"<<M<<\") \"<< N*M <<endl;\n\n}\n", "meta": {"hexsha": "8d53fe5fe6042af6dd53fe3db41e6932379073c0", "size": 1060, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Mattey.cpp", "max_stars_repo_name": "valbuenaster/hackerEarthCodes", "max_stars_repo_head_hexsha": "ce95294e16327b6de12a3a5e45694140ba6e2f00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Mattey.cpp", "max_issues_repo_name": "valbuenaster/hackerEarthCodes", "max_issues_repo_head_hexsha": "ce95294e16327b6de12a3a5e45694140ba6e2f00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Mattey.cpp", "max_forks_repo_name": "valbuenaster/hackerEarthCodes", "max_forks_repo_head_hexsha": "ce95294e16327b6de12a3a5e45694140ba6e2f00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.5625, "max_line_length": 63, "alphanum_fraction": 0.4698113208, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391600697869, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6423967877824538}}
{"text": "/**\n * crystal matrix text\n * @author Tobias Weber <tweber@ill.fr>\n * @date feb-19\n * @license GPLv3, see 'LICENSE' file\n *\n * g++ -std=c++20 -o cryst cryst.cpp\n * g++ -std=c++20 -DUSE_LAPACK -I.. -I/usr/include/lapacke -I/usr/local/opt/lapack/include -L/usr/local/opt/lapack/lib -o cryst cryst.cpp -llapacke\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE Xtal Test\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n\n#include <iostream>\n#include <vector>\n\n#include \"libs/maths.h\"\nusing namespace tl2_ops;\n\n\n#ifdef USE_LAPACK\n\tusing t_types = std::tuple<double, float>;\n#else\n\tusing t_types = std::tuple<long double, double, float>;\n#endif\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_xtal, t_real, t_types)\n{\n\tstd::cout << \"Test 1\" << std::endl;\n\n\tusing t_vec = tl2::vec<t_real, std::vector>;\n\tusing t_mat = tl2::mat<t_real, std::vector>;\n\t//using t_cplx = std::complex<t_real>;\n\t//using t_vec_cplx = std::vector<t_cplx>;\n\t//using t_mat_cplx = tl2::mat<t_cplx, std::vector>;\n\n\tauto A = tl2::A_matrix<t_mat, t_real>(\n\t\t4.56, 4.56, 4.56,\n\t\t90. / 180. * tl2::pi<t_real>,\n\t\t90. / 180. * tl2::pi<t_real>,\n\t\t90. / 180. * tl2::pi<t_real>);\n\tauto B = tl2::B_matrix<t_mat, t_real>(\n\t\t4.56, 4.56, 4.56,\n\t\t90. / 180. * tl2::pi<t_real>,\n\t\t90. / 180. * tl2::pi<t_real>,\n\t\t90. / 180. * tl2::pi<t_real>);\n\tauto [B2, ok] = tl2::inv<t_mat>(A);\n\tB2 = 2.*tl2::pi<t_real> * tl2::trans<t_mat>(B2);\n\tauto G = tl2::metric<t_mat>(B);\n\n\tt_vec vec1 = tl2::create<t_vec>({1, 1, 0});\n\tt_vec vec2 = tl2::create<t_vec>({1, -1, 0});\n\tt_vec vec3 = tl2::cross<t_mat, t_vec>(B, vec1, vec2);\n\tt_mat UB = tl2::UB_matrix<t_mat, t_vec>(B, vec1, vec2, vec3);\n\n\tstd::cout << \"A  = \" << A << std::endl;\n\tstd::cout << \"B  = \" << B << std::endl;\n\tstd::cout << \"B2 = \" << B2 << std::endl;\n\tstd::cout << \"G = \" << G << std::endl;\n\tstd::cout << \"UB = \" << UB << std::endl;\n\t//std::cout << tl2::levi<t_mat>(B, {0,1,2}) << std::endl;\n\t//std::cout << tl2::levi<t_mat>(B, {0,2,1}) << std::endl;\n\t//std::cout << tl2::levi<t_mat>(B, {1,2,1}) << std::endl;\n\n\tt_real ki = 1.5;\n\tt_real kf = 1.4;\n\tt_vec Q = tl2::create<t_vec>({1, -1, 0});\n\tauto [anglesok, a3, a4, dist] = tl2::calc_tas_a3a4<t_mat, t_vec>(B, ki, kf, Q, vec1, vec3);\n\tstd::cout << \"a3 = \" << a3 / tl2::pi<t_real> * 180.\n\t\t<< \", a4 = \" << a4 / tl2::pi<t_real> * 180.\n\t\t<< std::endl;\n\tstd::cout << \"distance of Q to scattering plane: \" << dist << std::endl;\n\n\n\t// calculate back to Q\n\tt_real Qlen = tl2::calc_tas_Q_len<t_real>(ki, kf, a4);\n\tstd::optional<t_vec> Qhkl = tl2::calc_tas_hkl<t_mat, t_vec>(B, ki, kf, Qlen, a3, vec1, vec3);\n\tstd::cout << \"Q = \" << *Qhkl << std::endl;\n\n\n\tBOOST_TEST(ok);\n\tBOOST_TEST(tl2::equals(B, B2, std::numeric_limits<t_real>::epsilon()*1e2));\n\tBOOST_TEST(tl2::equals<t_real>(dist, 0, std::numeric_limits<t_real>::epsilon()*1e2));\n\tBOOST_TEST(tl2::equals<t_real>(a3/tl2::pi<t_real>*180., 44.359, 1e-3));\n\tBOOST_TEST(tl2::equals<t_real>(a4/tl2::pi<t_real>*180., 84.359, 1e-3));\n\tBOOST_TEST((Qhkl.operator bool()));\n\tBOOST_TEST(tl2::equals<t_vec>(Q, *Qhkl, 1e-3));\n\n\tstd::cout << std::endl;\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_xtal2, t_real, t_types)\n{\n\tstd::cout << \"Test 2\" << std::endl;\n\n\tusing t_vec = tl2::vec<t_real, std::vector>;\n\tusing t_mat = tl2::mat<t_real, std::vector>;\n\n\tauto B = tl2::B_matrix<t_mat, t_real>(\n\t\t5., 6., 7.,\n\t\t60. / 180. * tl2::pi<t_real>,\n\t\t60. / 180. * tl2::pi<t_real>,\n\t\t60. / 180. * tl2::pi<t_real>);\n\n\tt_vec vec1 = tl2::create<t_vec>({1, 0, 0});\n\tt_vec vec2 = tl2::create<t_vec>({0, 1, 0});\n\tt_vec vec3 = tl2::cross<t_mat, t_vec>(B, vec1, vec2);\n\tt_mat UB = tl2::UB_matrix<t_mat, t_vec>(B, vec1, vec2, vec3);\n\tstd::cout << \"vec1 = \" << vec1 << std::endl;\n\tstd::cout << \"vec2 = \" << vec2 << std::endl;\n\tstd::cout << \"vec3 = \" << vec3 << std::endl;\n\tstd::cout << \"UB = \" << UB << std::endl;\n\n\tt_real ki = 1.4;\n\tt_real kf = 1.5;\n\tt_vec Q = tl2::create<t_vec>({1, 1, 0});\n\tt_real a3_offs = tl2::pi<t_real>*0.5;\n\tauto [anglesok, a3, a4, dist] = tl2::calc_tas_a3a4<t_mat, t_vec, t_real>(\n\t\tB, ki, kf, Q, vec1, vec3, 1., a3_offs);\n\tstd::cout << \"a3 = \" << a3 / tl2::pi<t_real> * 180.\n\t\t<< \", a4 = \" << a4 / tl2::pi<t_real> * 180.\n\t\t<< std::endl;\n\tstd::cout << \"distance of Q to scattering plane: \" << dist << std::endl;\n\n\t// calculate back to Q\n\tt_real Qlen = tl2::calc_tas_Q_len<t_real>(ki, kf, a4);\n\tstd::optional<t_vec> Qhkl = tl2::calc_tas_hkl<t_mat, t_vec, t_real>(\n\t\tB, ki, kf, Qlen, a3, vec1, vec3, 1., a3_offs);\n\tstd::cout << \"Q = \" << *Qhkl << std::endl;\n\n\n\tBOOST_TEST(tl2::equals<t_real>(dist, 0, std::numeric_limits<t_real>::epsilon()*1e2));\n\tBOOST_TEST(tl2::equals<t_real>(a3/tl2::pi<t_real>*180., -15.84, 1e-3));\n\tBOOST_TEST(tl2::equals<t_real>(a4/tl2::pi<t_real>*180., 68.895, 1e-3));\n\tBOOST_TEST((Qhkl.operator bool()));\n\tBOOST_TEST(tl2::equals<t_vec>(Q, *Qhkl, 1e-3));\n\n\tstd::cout << std::endl;\n}\n", "meta": {"hexsha": "3214c6080dd5035c36f6a4729f5501705971ceda", "size": 5850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/cryst.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/cryst.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/cryst.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 35.4545454545, "max_line_length": 147, "alphanum_fraction": 0.605982906, "num_tokens": 2096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6423858251662803}}
{"text": "// Copyright 2020 Josh Pieper, jjp@pobox.com.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"base/fit_plane.h\"\n\n#include <Eigen/Dense>\n\nnamespace mjmech {\nnamespace base {\n\nPlane FitPlane(const std::vector<Eigen::Vector3d>& points) {\n  Eigen::MatrixXd A(points.size(), 3);\n  Eigen::MatrixXd B(points.size(), 1);\n\n  for (size_t i = 0; i < points.size(); i++) {\n    A(i, 0) = points[i].x();\n    A(i, 1) = points[i].y();\n    A(i, 2) = 1.0;\n    B(i) = points[i].z();\n  }\n\n  Eigen::MatrixXd result = A.bdcSvd(\n      Eigen::ComputeThinU | Eigen::ComputeThinV).solve(B);\n  return Plane{result(0), result(1), result(2)};\n}\n\n}\n}\n", "meta": {"hexsha": "4cb5ac0fb01be8e6d7b1aea745d44169d778c610", "size": 1142, "ext": "cc", "lang": "C++", "max_stars_repo_path": "base/fit_plane.cc", "max_stars_repo_name": "rkb-1/quad", "max_stars_repo_head_hexsha": "66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2017-01-18T15:12:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T08:28:11.000Z", "max_issues_repo_path": "base/fit_plane.cc", "max_issues_repo_name": "rkb-1/quad", "max_issues_repo_head_hexsha": "66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-11T14:39:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-03T16:49:57.000Z", "max_forks_repo_path": "base/fit_plane.cc", "max_forks_repo_name": "rkb-1/quad", "max_forks_repo_head_hexsha": "66ae3bc5ccb6db070bc1e32a3b9386f6d01a049e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-01-11T09:48:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T16:20:35.000Z", "avg_line_length": 28.55, "max_line_length": 75, "alphanum_fraction": 0.6742556918, "num_tokens": 313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6423769409655522}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"miMaS/field.h\"\n#include \"miMaS/weno.h\"\n#include \"miMaS/fft.h\"\n#include \"miMaS/array_view.h\"\n#include \"miMaS/poisson.h\"\n\nnamespace math = boost::math::constants;\n\n#define SQ(X) ((X)*(X))\n#define Xi(i) (i*f.step.dx+f.range.x_min)\n#define Vk(k) (k*f.step.dv+f.range.v_min)\n\nstruct err\n{\n  double infty=0.;\n  double one=0.;\n  double dt=0. , dx=0. , dv=0.;\n  std::size_t n=16;\n  std::size_t nb_iter=0;\n};\n\nstd::ostream &\noperator << ( std::ostream & os , err const& e ) {\n  os << e.n << \" \" << \" \" << e.nb_iter << \" \" << e.dx << \" \" << e.dt << \" \" << e.one << \" \" << e.infty;\n  return os;\n}\n\nerr\nrotation ( std::size_t N , int q=-2 )\n{\n\tstd::size_t Nx = N, Nv = N;\n\tfield<double,1> f(boost::extents[Nv][Nx]);\n  field<double,1> f_sol(boost::extents[Nv][Nx]);\n\n\tf.range.v_min = -10.; f.range.v_max = 10;\n\tf.step.dv = (f.range.v_max-f.range.v_min)/Nv;\n\tf.range.x_min = -10.; f.range.x_max = 10.;\n\tf.step.dx = (f.range.x_max-f.range.x_min)/Nx;\n\n\n\tconst double dt = (math::pi<double>()*std::pow(2,q))*f.step.dv/f.range.v_max;\n\t\n\n\tublas::vector<double> v (Nv,0.); for ( std::size_t k=0 ; k<Nv ; ++k ) { v[k] =  Vk(k); }\n  ublas::vector<double> E (Nx,0.); for ( std::size_t i=0 ; i<Nx ; ++i ) { E[i] = -Xi(i); }\n  \n\tconst double l = f.range.x_max-f.range.x_min;\n\tublas::vector<double> kx(Nx);\n  for ( auto i=0 ; i<Nx/2 ; ++i ) { kx[i] = 2.*math::pi<double>()*i/l; }\n  for ( int i=-Nx/2 ; i<0 ; ++i ) { kx[Nx+i] = 2.*math::pi<double>()*i/l; }\n\t\n  for (field<double,2>::size_type k=0 ; k<f.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<f.size(1) ; ++i ) {\n      f[k][i] = std::exp(-SQ(Xi(i)-3)/0.5 - SQ(Vk(k))/2.);\n      f_sol[k][i] = f[k][i];\n    }\n  }\n\n  double Tf = 2*math::pi<double>();\n  int i_t=0;\n\n  while ( i_t*dt < Tf ) {\n    field<double,1> Edvf = weno::trp_v(f,E);\n    field<double,1> f1=f,f2=f;\n\t  fft::spectrum hf(Nx),hf1(Nx),hf2(Nx),hEdvf(Nx);\n\n\t  for ( auto k=0 ; k<f.size(0) ; ++k ) {\n\t  \thf.fft(&(f[k][0]));\n\t  \thEdvf.fft(&(Edvf[k][0]));\n\n\t  \tfor ( auto i=0 ; i<Nx ; ++i ) {\n\t  \t\tauto re = hf[i][fft::re] , im = hf[i][fft::im];\n\t  \t\thf1[i][fft::re] = std::cos(v(k)*kx[i]*dt)*(re-dt*hEdvf[i][fft::re]) + std::sin(v(k)*kx[i]*dt)*(im-dt*hEdvf[i][fft::im]);\n\t  \t\thf1[i][fft::im] = std::cos(v(k)*kx[i]*dt)*(im-dt*hEdvf[i][fft::im]) - std::sin(v(k)*kx[i]*dt)*(re-dt*hEdvf[i][fft::re]);\n\t  \t}\n\t  \thf1.ifft(&(f1[k][0]));\n\t  }\n\n    Edvf = weno::trp_v(f1,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf1.fft(&(f1[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        auto re = hf[i][fft::re] , im = hf[i][fft::im];\n        hf2[i][fft::re] = 0.75*(std::cos(0.5*v(k)*kx[i]*dt)*re + std::sin(0.5*v(k)*kx[i]*dt)*im) + 0.25*( std::cos(0.5*v(k)*kx[i]*dt)*(hf1[i][fft::re]-dt*hEdvf[i][fft::re]) - std::sin(0.5*v(k)*kx[i]*dt)*(hf1[i][fft::im]-dt*hEdvf[i][fft::im]) );\n        hf2[i][fft::im] = 0.75*(std::cos(0.5*v(k)*kx[i]*dt)*im - std::sin(0.5*v(k)*kx[i]*dt)*re) + 0.25*( std::cos(0.5*v(k)*kx[i]*dt)*(hf1[i][fft::im]-dt*hEdvf[i][fft::im]) + std::sin(0.5*v(k)*kx[i]*dt)*(hf1[i][fft::re]-dt*hEdvf[i][fft::re]) );\n      }\n      hf2.ifft(&(f2[k][0]));\n    }\n\n    Edvf = weno::trp_v(f2,E);\n    for ( auto k=0 ; k<f.size(0) ; ++k ) {\n      hf.fft(&(f[k][0]));\n      hf2.fft(&(f2[k][0]));\n      hEdvf.fft(&(Edvf[k][0]));\n\n      for ( auto i=0 ; i<Nx ; ++i ) {\n        auto re = hf[i][fft::re] , im = hf[i][fft::im];\n        hf[i][fft::re] = (1./3.)*(std::cos(v(k)*kx[i]*dt)*re + std::sin(v(k)*kx[i]*dt)*im) + (2./3.)*( std::cos(0.5*v(k)*kx[i]*dt)*(hf2[i][fft::re]-dt*hEdvf[i][fft::re]) + std::sin(0.5*v(k)*kx[i]*dt)*(hf2[i][fft::im]-dt*hEdvf[i][fft::im]) );\n        hf[i][fft::im] = (1./3.)*(std::cos(v(k)*kx[i]*dt)*im - std::sin(v(k)*kx[i]*dt)*re) + (2./3.)*( std::cos(0.5*v(k)*kx[i]*dt)*(hf2[i][fft::im]-dt*hEdvf[i][fft::im]) - std::sin(0.5*v(k)*kx[i]*dt)*(hf2[i][fft::re]-dt*hEdvf[i][fft::re]) );\n      }\n      hf.ifft(&(f[k][0]));\n    }\n\n    ++i_t;\n\t}\n\n  err e;\n  e.dt = dt;\n  e.dx = f.step.dx;\n  e.dv = f.step.dv;\n  e.n = N;\n  e.nb_iter = i_t;\n  for ( auto k=0 ; k<Nv ; ++k ) {\n    for (auto i=0 ; i<Nx ; ++i ) {\n      e.one += std::abs(f[k][i]-f_sol[k][i])*f.step.dv*f.step.dx;\n      e.infty = std::max(std::abs(f[k][i]-f_sol[k][i]),e.infty);\n    }\n  }\n\n\treturn e;\n}\n\nint\nmain ( int argc , char** argv )\n{\n  for ( std::size_t exp=5 ; exp<11 ; ++exp ) {\n    std::size_t n=1<<exp;\n    err e = rotation(n);\n    std::cout << e << std::endl;\n  }\n  \n  return 0;\n}\n\n", "meta": {"hexsha": "14dd7777e2acc1feb7188a57ce4057d652c21216", "size": 4664, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/rotation.cc", "max_stars_repo_name": "Kivvix/miMaS", "max_stars_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-03T22:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-29T06:12:07.000Z", "max_issues_repo_path": "code/rotation.cc", "max_issues_repo_name": "Kivvix/miMaS", "max_issues_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/rotation.cc", "max_forks_repo_name": "Kivvix/miMaS", "max_forks_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-29T06:17:16.000Z", "avg_line_length": 31.5135135135, "max_line_length": 244, "alphanum_fraction": 0.5077186964, "num_tokens": 1935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6423641120958491}}
{"text": "#include \"mex.h\"\n\n#include <igl/local_basis.h>\n#include <igl/copyleft/comiso/nrosy.h>\n\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/parse_rhs.h>\n\n#include <igl/PI.h>\n\n#include <Eigen/Core>\n\n// Mesh\nEigen::MatrixXd V;\nEigen::MatrixXi F;\n\n// Constrained faces id\nEigen::VectorXi b;\n\n// Cosntrained faces representative vector\nEigen::MatrixXd bc;\n\n// Degree of the N-RoSy field\nint N = 6;\n\n// Converts a representative vector per face in the full set of vectors that describe\n// an N-RoSy field\nvoid representative_to_nrosy(\n  const Eigen::MatrixXd& V,\n  const Eigen::MatrixXi& F,\n  const Eigen::MatrixXd& R,\n  const int N,\n  Eigen::MatrixXd& Y)\n{\n  using namespace Eigen;\n  using namespace std;\n  MatrixXd B1, B2, B3;\n\n  igl::local_basis(V,F,B1,B2,B3);\n\n  Y.resize(F.rows()*N,3);\n  for (unsigned i=0;i<F.rows();++i)\n  {\n    double x = R.row(i) * B1.row(i).transpose();\n    double y = R.row(i) * B2.row(i).transpose();\n    double angle = atan2(y,x);\n\n    for (unsigned j=0; j<N;++j)\n    {\n      double anglej = angle + 2*igl::PI*double(j)/double(N);\n      double xj = cos(anglej);\n      double yj = sin(anglej);\n      Y.row(i*N+j) = xj * B1.row(i) + yj * B2.row(i);\n    }\n  }\n}\n\n/* The gateway function */\nvoid mexFunction( int nlhs, mxArray *plhs[],\n                  int nrhs, const mxArray *prhs[])\n{ \n    igl::matlab::parse_rhs_double(prhs,V);\n    igl::matlab::parse_rhs_index(prhs+1,F);\n    \n    // Threshold faces with high anisotropy\n    b.resize(1);\n    b << 0;\n    bc.resize(1,3);\n    bc << 1,1,1;\n\n    // Runs the nrosy\n    MatrixXd R; //output field\n    VectorXd S; //output singularities \n\n    igl::copyleft::comiso::nrosy(V,F,b,bc,VectorXi(),VectorXd(),MatrixXd(),N,0.5,R,S);\n    \n    Eigen::MatrixXd Y;\n    representative_to_nrosy(V, F, R, N, Y);\n    \n    // Return the matrices to matlab\n      switch(nlhs)\n      {\n        case 2:\n          igl::matlab::prepare_lhs_double(S,plhs+1);\n        case 1:\n          igl::matlab::prepare_lhs_double(Y,plhs);\n        default: break;\n      }\n}", "meta": {"hexsha": "4b442c10835e32f741740eb5669b3a36f29e35b3", "size": 2008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "05.Lineament_Analysis/mex/nrosy/nrosy_mex.cpp", "max_stars_repo_name": "LSgeo/earth_blender", "max_stars_repo_head_hexsha": "3b60eb47e4471c65ce1b5910aea303e2959c25e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T08:29:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T07:10:44.000Z", "max_issues_repo_path": "05.Lineament_Analysis/mex/nrosy/nrosy_mex.cpp", "max_issues_repo_name": "LSgeo/earth_blender", "max_issues_repo_head_hexsha": "3b60eb47e4471c65ce1b5910aea303e2959c25e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "05.Lineament_Analysis/mex/nrosy/nrosy_mex.cpp", "max_forks_repo_name": "LSgeo/earth_blender", "max_forks_repo_head_hexsha": "3b60eb47e4471c65ce1b5910aea303e2959c25e8", "max_forks_repo_licenses": ["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.5617977528, "max_line_length": 86, "alphanum_fraction": 0.6145418327, "num_tokens": 625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.642364104896947}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2003 RiskMap srl\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef quantlib_test_integrals_hpp\n#define quantlib_test_integrals_hpp\n\n#include <boost/test/unit_test.hpp>\n\n/* remember to document new and/or updated tests in the Doxygen\n   comment block of the corresponding class */\n\nclass IntegralTest {\n  public:\n    static void testSegment();\n    static void testTrapezoid();\n    static void testMidPointTrapezoid();\n    static void testSimpson();\n    static void testGaussKronrodAdaptive();\n    static void testGaussKronrodNonAdaptive();\n    static void testGaussLobatto();\n    static void testTwoDimensionalIntegration();\n    static void testFolinIntegration();\n    static void testDiscreteIntegrals();\n    static void testDiscreteIntegrator();\n    static void testPiecewiseIntegral();\n    static boost::unit_test_framework::test_suite* suite();\n};\n\n\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2003 RiskMap srl\n Copyright (C) 2015 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include \"utilities.hpp\"\n#include <ql/math/functional.hpp>\n#include <ql/math/integrals/filonintegral.hpp>\n#include <ql/math/integrals/segmentintegral.hpp>\n#include <ql/math/integrals/simpsonintegral.hpp>\n#include <ql/math/integrals/trapezoidintegral.hpp>\n#include <ql/math/integrals/kronrodintegral.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/math/integrals/discreteintegrals.hpp>\n#include <ql/math/interpolations/bilinearinterpolation.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/termstructures/volatility/abcd.hpp>\n#include <ql/math/integrals/twodimensionalintegral.hpp>\n#include <ql/experimental/math/piecewisefunction.hpp>\n#include <ql/experimental/math/piecewiseintegral.hpp>\n\n#include <boost/make_shared.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/assign/std/vector.hpp>\n\nusing namespace QuantLib;\nusing namespace boost::assign;\nusing boost::unit_test_framework::test_suite;\n\nnamespace {\n\n    Real Tolerance = 1.0e-6;\n\n    template <class T>\n    void testSingle(const T& I, const std::string& tag,\n                    const boost::function<Real (Real)>& f,\n                    Real xMin, Real xMax, Real expected) {\n        Real calculated = I(f,xMin,xMax);\n        if (std::fabs(calculated-expected) > Tolerance) {\n            BOOST_FAIL(std::setprecision(10)\n                       << \"integrating \" << tag\n                       << \"    calculated: \" << calculated\n                       << \"    expected:   \" << expected);\n        }\n    }\n\n    template <class T>\n    void testSeveral(const T& I) {\n        testSingle(I, \"f(x) = 0\",\n                   constant<Real,Real>(0.0), 0.0, 1.0, 0.0);\n        testSingle(I, \"f(x) = 1\",\n                   constant<Real,Real>(1.0), 0.0, 1.0, 1.0);\n        testSingle(I, \"f(x) = x\",\n                   QuantLib::identity<Real>(),           0.0, 1.0, 0.5);\n        testSingle(I, \"f(x) = x^2\",\n                   square<Real>(),             0.0, 1.0, 1.0/3.0);\n        testSingle(I, \"f(x) = sin(x)\",\n                   std::ptr_fun<Real,Real>(std::sin), 0.0, M_PI, 2.0);\n        testSingle(I, \"f(x) = cos(x)\",\n                   std::ptr_fun<Real,Real>(std::cos), 0.0, M_PI, 0.0);\n        testSingle(I, \"f(x) = Gaussian(x)\",\n                   NormalDistribution(), -10.0, 10.0, 1.0);\n        testSingle(I, \"f(x) = Abcd2(x)\",\n                   AbcdSquared(0.07, 0.07, 0.5, 0.1, 8.0, 10.0), 5.0, 6.0,\n                   AbcdFunction(0.07, 0.07, 0.5, 0.1).covariance(5.0, 6.0, 8.0, 10.0));\n    }\n\n    template <class T>\n    void testDegeneratedDomain(const T& I) {\n        testSingle(I, \"f(x) = 0 over [1, 1 + macheps]\",\n                   constant<Real, Real>(0.0), 1.0, 1.0 + QL_EPSILON, 0.0);\n    }\n\n}\n\n\nvoid IntegralTest::testSegment() {\n    BOOST_TEST_MESSAGE(\"Testing segment integration...\");\n    testSeveral(SegmentIntegral(10000));\n    testDegeneratedDomain(SegmentIntegral(10000));\n}\n\nvoid IntegralTest::testTrapezoid() {\n    BOOST_TEST_MESSAGE(\"Testing trapezoid integration...\");\n    testSeveral(TrapezoidIntegral<Default>(Tolerance, 10000));\n    testDegeneratedDomain(TrapezoidIntegral<Default>(Tolerance, 10000));\n}\n\nvoid IntegralTest::testMidPointTrapezoid() {\n    BOOST_TEST_MESSAGE(\"Testing mid-point trapezoid integration...\");\n    testSeveral(TrapezoidIntegral<MidPoint>(Tolerance, 10000));\n    testDegeneratedDomain(TrapezoidIntegral<MidPoint>(Tolerance, 10000));\n}\n\nvoid IntegralTest::testSimpson() {\n    BOOST_TEST_MESSAGE(\"Testing Simpson integration...\");\n    testSeveral(SimpsonIntegral(Tolerance, 10000));\n    testDegeneratedDomain(SimpsonIntegral(Tolerance, 10000));\n}\n\nvoid IntegralTest::testGaussKronrodAdaptive() {\n    BOOST_TEST_MESSAGE(\"Testing adaptive Gauss-Kronrod integration...\");\n    Size maxEvaluations = 1000;\n    testSeveral(GaussKronrodAdaptive(Tolerance, maxEvaluations));\n    testDegeneratedDomain(GaussKronrodAdaptive(Tolerance, maxEvaluations));\n}\n\nvoid IntegralTest::testGaussLobatto() {\n    BOOST_TEST_MESSAGE(\"Testing adaptive Gauss-Lobatto integration...\");\n    Size maxEvaluations = 1000;\n    testSeveral(GaussLobattoIntegral(maxEvaluations, Tolerance));\n    // on degenerated domain [1,1+macheps] an exception is thrown\n    // which is also ok, but not tested here\n}\n\nvoid IntegralTest::testGaussKronrodNonAdaptive() {\n    BOOST_TEST_MESSAGE(\"Testing non-adaptive Gauss-Kronrod integration...\");\n    Real precision = Tolerance;\n    Size maxEvaluations = 100;\n    Real relativeAccuracy = Tolerance;\n    GaussKronrodNonAdaptive gaussKronrodNonAdaptive(precision, maxEvaluations,\n                                                    relativeAccuracy);\n    testSeveral(gaussKronrodNonAdaptive);\n    testDegeneratedDomain(gaussKronrodNonAdaptive);\n}\n\nvoid IntegralTest::testTwoDimensionalIntegration() {\n    BOOST_TEST_MESSAGE(\"Testing two dimensional adaptive \"\n                       \"Gauss-Lobatto integration...\");\n\n    const Size maxEvaluations = 1000;\n    const Real calculated = TwoDimensionalIntegral(\n        boost::shared_ptr<Integrator>(\n            new TrapezoidIntegral<Default>(Tolerance, maxEvaluations)),\n        boost::shared_ptr<Integrator>(\n            new TrapezoidIntegral<Default>(Tolerance, maxEvaluations)))(\n        std::multiplies<Real>(),\n        std::make_pair(0.0, 0.0), std::make_pair(1.0, 2.0));\n\n    const Real expected = 1.0;\n    if (std::fabs(calculated-expected) > Tolerance) {\n        BOOST_FAIL(std::setprecision(10)\n                   << \"two dimensional integration: \"\n                   << \"\\n    calculated: \" << calculated\n                   << \"\\n    expected:   \" << expected);\n    }\n}\n\nnamespace {\n\n    class sineF {\n      public:\n        Real operator()(Real x) const {\n            return std::exp(-0.5*(x - M_PI_2/100));\n        }\n    };\n\n    class cosineF {\n      public:\n        Real operator()(Real x) const {\n            return std::exp(-0.5*x);\n        }\n    };\n\n}\n\nvoid IntegralTest::testFolinIntegration() {\n    BOOST_TEST_MESSAGE(\"Testing Folin's integral formulae...\");\n\n    // Examples taken from\n    // http://www.tat.physik.uni-tuebingen.de/~kokkotas/Teaching/Num_Methods_files/Comp_Phys5.pdf\n    const Size nr[] = { 4, 8, 16, 128, 256, 1024, 2048 };\n    const Real expected[] = { 4.55229440e-5,4.72338540e-5, 4.72338540e-5,\n                              4.78308678e-5,4.78404787e-5, 4.78381120e-5,\n                              4.78381084e-5};\n\n    const Real t = 100;\n    const Real o = M_PI_2/t;\n\n    const Real tol = 1e-12;\n\n    for (Size i=0; i < LENGTH(nr); ++i) {\n        const Size n = nr[i];\n        const Real calculatedCosine\n            = FilonIntegral(FilonIntegral::Cosine, t, n)(cosineF(),0,2*M_PI);\n        const Real calculatedSine\n            = FilonIntegral(FilonIntegral::Sine, t, n)\n                (sineF(), o,2*M_PI + o);\n\n        if (std::fabs(calculatedCosine-expected[i]) > tol) {\n            BOOST_FAIL(std::setprecision(10)\n                << \"Filon Cosine integration failed: \"\n                << \"\\n    calculated: \" << calculatedCosine\n                << \"\\n    expected:   \" << expected[i]);\n        }\n        if (std::fabs(calculatedSine-expected[i]) > tol) {\n            BOOST_FAIL(std::setprecision(10)\n                << \"Filon Sine integration failed: \"\n                << \"\\n    calculated: \" << calculatedCosine\n                << \"\\n    expected:   \" << expected[i]);\n        }\n    }\n}\n\nnamespace {\n\n    Real f1(Real x) {\n        return 1.2*x*x+3.2*x+3.1;\n    }\n\n    Real f2(Real x) {\n        return 4.3*(x-2.34)*(x-2.34)-6.2*(x-2.34) + f1(2.34);\n    }\n\n}\n\nvoid IntegralTest::testDiscreteIntegrals() {\n    BOOST_TEST_MESSAGE(\"Testing discrete integral formulae...\");\n\n    Array x(6), f(6);\n    x[0] = 1.0; x[1] = 2.02; x[2] = 2.34; x[3] = 3.3; x[4] = 4.2; x[5] = 4.6;\n\n    std::transform(x.begin(), x.begin()+3, f.begin(),   f1);\n    std::transform(x.begin()+3, x.end(),   f.begin()+3, f2);\n\n    const Real expectedSimpson =\n        16.0401216 + 30.4137528 + 0.2*f2(4.2) + 0.2*f2(4.6);\n    const Real expectedTrapezoid =\n          0.5*(f1(1.0)  + f1(2.02))*1.02\n        + 0.5*(f1(2.02) + f1(2.34))*0.32\n        + 0.5*(f2(2.34) + f2(3.3) )*0.96\n        + 0.5*(f2(3.3)  + f2(4.2) )*0.9\n        + 0.5*(f2(4.2)  + f2(4.6) )*0.4;\n\n    const Real calculatedSimpson =  DiscreteSimpsonIntegral()(x, f);\n    const Real calculatedTrapezoid = DiscreteTrapezoidIntegral()(x, f);\n\n    const Real tol = 1e-12;\n    if (std::fabs(calculatedSimpson-expectedSimpson) > tol) {\n        BOOST_FAIL(std::setprecision(16)\n            << \"discrete Simpson integration failed: \"\n            << \"\\n    calculated: \" << calculatedSimpson\n            << \"\\n    expected:   \" << expectedSimpson);\n    }\n\n    if (std::fabs(calculatedTrapezoid-expectedTrapezoid) > tol) {\n        BOOST_FAIL(std::setprecision(16)\n            << \"discrete Trapezoid integration failed: \"\n            << \"\\n    calculated: \" << calculatedTrapezoid\n            << \"\\n    expected:   \" << expectedTrapezoid);\n    }\n}\n\nvoid IntegralTest::testDiscreteIntegrator() {\n    BOOST_TEST_MESSAGE(\"Testing discrete integrator formulae...\");\n\n    testSeveral(DiscreteSimpsonIntegrator(300));\n    testSeveral(DiscreteTrapezoidIntegrator(3000));\n}\n\nnamespace {\n\nstd::vector<Real> x, y;\n\nReal pw_fct(const Real t) { return QL_PIECEWISE_FUNCTION(x, y, t); }\n\nvoid pw_check(const Integrator &in, const Real a, const Real b,\n              const Real expected) {\n    Real calculated = in(pw_fct, a, b);\n    if (!close(calculated, expected))\n        BOOST_FAIL(std::setprecision(16)\n                   << \"piecewise integration over [\" << a << \",\" << b\n                   << \"] failed: \"\n                   << \"\\n   calculated: \" << calculated\n                   << \"\\n   expected:   \" << expected\n                   << \"\\n   difference: \" << (calculated - expected));\n}\n} // empty namespace\n\nvoid IntegralTest::testPiecewiseIntegral() {\n    BOOST_TEST_MESSAGE(\"Testing piecewise integral...\");\n    x += 1.0, 2.0, 3.0, 4.0, 5.0;\n    y += 1.0, 2.0, 3.0, 4.0, 5.0, 6.0;\n    boost::shared_ptr<Integrator> segment =\n        boost::make_shared<SegmentIntegral>(1);\n    boost::shared_ptr<Integrator> piecewise =\n        boost::make_shared<PiecewiseIntegral>(segment, x);\n    pw_check(*piecewise, -1.0, 0.0, 1.0);\n    pw_check(*piecewise, 0.0, 1.0, 1.0);\n    pw_check(*piecewise, 0.0, 1.5, 2.0);\n    pw_check(*piecewise, 0.0, 2.0, 3.0);\n    pw_check(*piecewise, 0.0, 2.5, 4.5);\n    pw_check(*piecewise, 0.0, 3.0, 6.0);\n    pw_check(*piecewise, 0.0, 4.0, 10.0);\n    pw_check(*piecewise, 0.0, 5.0, 15.0);\n    pw_check(*piecewise, 0.0, 6.0, 21.0);\n    pw_check(*piecewise, 0.0, 7.0, 27.0);\n    pw_check(*piecewise, 3.5, 4.5, 4.5);\n    pw_check(*piecewise, 5.0, 10.0, 30.0);\n    pw_check(*piecewise, 9.0, 10.0, 6.0);\n}\n\ntest_suite* IntegralTest::suite() {\n    test_suite* suite = BOOST_TEST_SUITE(\"Integration tests\");\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testSegment));\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testTrapezoid));\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testMidPointTrapezoid));\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testSimpson));\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testGaussKronrodAdaptive));\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testGaussKronrodNonAdaptive));\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testGaussLobatto));\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testTwoDimensionalIntegration));\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testFolinIntegration));\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testDiscreteIntegrals));\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testDiscreteIntegrator));\n    suite->add(QUANTLIB_TEST_CASE(&IntegralTest::testPiecewiseIntegral));\n    return suite;\n}\n\n#endif\n", "meta": {"hexsha": "4fe2ce2e5f178526d6f0e4a23616793c90643f16", "size": 14122, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test-suite/integrals.hpp", "max_stars_repo_name": "markxio/Quantuccia", "max_stars_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T14:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:00:52.000Z", "max_issues_repo_path": "test-suite/integrals.hpp", "max_issues_repo_name": "markxio/Quantuccia", "max_issues_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-04-02T14:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T05:31:12.000Z", "max_forks_repo_path": "test-suite/integrals.hpp", "max_forks_repo_name": "markxio/Quantuccia", "max_forks_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T05:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:30:20.000Z", "avg_line_length": 36.9685863874, "max_line_length": 97, "alphanum_fraction": 0.6384364821, "num_tokens": 4089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.8152324848629215, "lm_q1q2_score": 0.6423471065249698}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nusing Eigen::Matrix;\nusing Eigen::Dynamic;\n\nTEST(ProbDistributionsMultinomial,RNGSize) {\n  boost::random::mt19937 rng;\n  Matrix<double,Dynamic,1> theta(5);\n  // error in 2.1.0 due to overflow in binomial call due to division\n  theta << 0.3, 0.1, 0.2, 0.2, 0.2;  \n  std::vector<int> sample = stan::math::multinomial_rng(theta,10,rng);\n  // bug in 2.1.0 returned 10 rather than 5 for returned size\n  EXPECT_EQ(5U, sample.size());  \n}\n\nTEST(ProbDistributionsMultinomial,Multinomial) {\n  std::vector<int> ns;\n  ns.push_back(1);\n  ns.push_back(2);\n  ns.push_back(3);\n  Matrix<double,Dynamic,1> theta(3,1);\n  theta << 0.2, 0.3, 0.5;\n  EXPECT_FLOAT_EQ(-2.002481, stan::math::multinomial_log(ns,theta));\n}\nTEST(ProbDistributionsMultinomial,Propto) {\n  std::vector<int> ns;\n  ns.push_back(1);\n  ns.push_back(2);\n  ns.push_back(3);\n  Matrix<double,Dynamic,1> theta(3,1);\n  theta << 0.2, 0.3, 0.5;\n  EXPECT_FLOAT_EQ(0.0, stan::math::multinomial_log<true>(ns,theta));\n}\n\nusing stan::math::multinomial_log;\n\nTEST(ProbDistributionsMultinomial, error) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  double inf = std::numeric_limits<double>::infinity();\n\n  std::vector<int> ns;\n  ns.push_back(1);\n  ns.push_back(2);\n  ns.push_back(3);\n  Matrix<double,Dynamic,1> theta(3,1);\n  theta << 0.2, 0.3, 0.5;\n  \n  EXPECT_NO_THROW(multinomial_log(ns, theta));\n  \n  ns[1] = 0;\n  EXPECT_NO_THROW(multinomial_log(ns, theta));\n  ns[1] = -1;\n  EXPECT_THROW(multinomial_log(ns, theta), std::domain_error);\n  ns[1] = 1;\n\n  theta(0) = 0.0;\n  EXPECT_THROW(multinomial_log(ns, theta), std::domain_error);\n  theta(0) = nan;\n  EXPECT_THROW(multinomial_log(ns, theta), std::domain_error);\n  theta(0) = inf;\n  EXPECT_THROW(multinomial_log(ns, theta), std::domain_error);\n  theta(0) = -inf;\n  EXPECT_THROW(multinomial_log(ns, theta), std::domain_error);\n  theta(0) = -1;\n  theta(1) = 1.5;\n  theta(2) = 0.5;\n  EXPECT_THROW(multinomial_log(ns, theta), std::domain_error);\n  theta(0) = 0.2;\n  theta(1) = 0.3;\n  theta(2) = 0.5;\n  \n  ns.resize(2);\n  EXPECT_THROW(multinomial_log(ns, theta), std::invalid_argument);\n}\n\nTEST(ProbDistributionsMultinomial, zeros) {\n  double result;\n  std::vector<int> ns;\n  ns.push_back(0);\n  ns.push_back(1);\n  ns.push_back(2);\n  Matrix<double,Dynamic,1> theta(3,1);\n  theta << 0.2, 0.3, 0.5;\n\n  result = multinomial_log(ns, theta);\n  EXPECT_FALSE(std::isnan(result));\n\n  std::vector<int> ns2;\n  ns2.push_back(0);\n  ns2.push_back(0);\n  ns2.push_back(0);\n  \n  double result2 = multinomial_log(ns2, theta);\n  EXPECT_FLOAT_EQ(0.0, result2);\n}\n\nTEST(ProbDistributionsMultinomial, error_check) {\n  boost::random::mt19937 rng;\n\n  Matrix<double,Dynamic,1> theta(3);\n  theta << 0.15, 0.45, 0.40;\n\n  EXPECT_THROW(stan::math::multinomial_rng(theta,-3,rng), std::domain_error);\n\n  theta << 0.15, 0.45, 0.50;\n  EXPECT_THROW(stan::math::multinomial_rng(theta,3,rng), std::domain_error);\n}\n\nTEST(ProbDistributionsMultinomial, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int M = 10;\n  int trials = 1000;\n  int N = M * trials;\n\n  int K = 3;\n  Matrix<double,Dynamic,1> theta(K);\n  theta << 0.2, 0.35, 0.45;\n  boost::math::chi_squared mydist(K-1);\n\n  double expect[K];\n  for (int i = 0 ; i < K; ++i)\n    expect[i] = N * theta(i);\n\n  int bin[K];\n  for (int i = 0; i < K; ++i)\n    bin[i] = 0;\n\n  for (int count = 0; count < M; ++count) {\n    std::vector<int> a = stan::math::multinomial_rng(theta,trials,rng);\n    for (int i = 0; i < K; ++i)\n      bin[i] += a[i];\n  }\n\n  double chi = 0;\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j])) / expect[j];\n  \n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n", "meta": {"hexsha": "c85ff291d044dc5b4ee85343e53302cb54f7dbc0", "size": 3789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/multinomial_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/multinomial_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/multinomial_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4965034965, "max_line_length": 77, "alphanum_fraction": 0.6584850884, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.787931185683219, "lm_q1q2_score": 0.6423471019426036}}
{"text": "/*\ndiscrete fourier transform for extension fields\n*/\n\n\n#ifndef DFT\n#define DFT \n\n#include <boost/operators.hpp>\n#include <iostream>\n#include <ostream>\n#include <vector>\n#include <cassert>\n#include \"polynomial.hpp\"\n\nusing namespace std;\n\n// class to compute the powers of an element a in an extention field, \n// via a lookup table \ntemplate<class co_t>\nclass fieldpower{\n\npublic:\nunsigned n; // max power  \nco_t nm;\n\nprivate:\nco_t a; // a is an element of order n\nco_t am; // the inverse of a; also has order n\nvector<co_t> powers_a; // the lookup table for the powers of a\nvector<co_t> powers_am; // the lookup table for the powers of a^(-1)\n\npublic: \n\tfieldpower(){};\n\tfieldpower(const unsigned n_, const co_t& a_){\n\t\ta = a_;\n\t\tn = n_;\n\t\t\n\t\tnm = co_t(n);\n\t\tnm = pow( (co_t) nm,-1  );\n\n\t\t// initialize powers_a\n\t\tpowers_a.resize( n );\n\t\tpowers_a[0] = co_t(1);\n\t\tpowers_a[1] =\ta;\n\t\tfor(int i =2;i < powers_a.size();++i)\n\t\t\tpowers_a[i] = powers_a[i-1]*a;\n\n\t\t// initialize powers_am\n\t\tam = pow( (co_t) a,-1);\n\t\tpowers_am.resize( n );\n\t\tpowers_am[0] = co_t(1);\n\t\tpowers_am[1] =\tam;\n\t\tfor(int i =2;i < powers_am.size();++i)\n\t\t\tpowers_am[i] = powers_am[i-1]*am;\n\t\t\n\t\tcout << \"filedpower: lookup tables generated.. \" << endl;\n\t}\n\n\tco_t copow(int powe) const {\n\t\tif(powe >= 0){\n\t\t\treturn powers_a[ powe % n ];\n\t\t} else\n\t\t\treturn powers_am[(-powe) % n ];\n\t}\n\n};\n\n\ntemplate<class co_t>\nvoid dft_primitive( const vector<co_t>& xv, vector<co_t>& Xv, fieldpower<co_t>& fp, int prefac){\n\t//assert(xv.size() == Xv.size());\n\tfor(int j=0; j < Xv.size();++j){\n\t\t// compute Xv[j]\n\t\tXv[j] = co_t(0);\n\t\tfor(int i=0;i < xv.size(); ++i){\n\t\t\t//Xv[j] += xv[i]*pow( (coeff_t)  a, (int)  i*j);\n\t\t\tif(prefac<0)\n\t\t\t\tXv[j] += fp.nm*xv[i]*fp.copow(-i*j);\n\t\t\telse\n\t\t\t\tXv[j] += xv[i]*fp.copow(i*j);\n\t\t}\n\t}\n};\n\n// prefac = 1: normal fft, prefac =-1: inverse fft\ntemplate<class co_t>\nvoid fft( const vector<co_t>& xv, vector<co_t>& Xv, const fieldpower<co_t>& fp, int prefac, unsigned Q, unsigned P){\n\tassert(Q*P == xv.size());\n\n\t// compute y_p^(r)\n\tvector<vector< co_t> > Y(Q,vector< co_t >(P, co_t(0) ));\n\tfor(unsigned r=0;r<Q;++r){\n\t\t// for each r, a Fourier transform..\n\t\tfor(unsigned p=0;p<P;++p){\n\t\t\tfor(unsigned q=0;q<Q;++q){\n\t\t\t\tY[r][p] += xv[P*q+p]*fp.copow(prefac*P*q*r);\n\t\t\t}\n\t\t\tY[r][p] *= fp.copow(prefac*p*r);\n\t\t}\n\t}\n\t// compute A_{Qs+r}\n\tfor(unsigned r=0;r<Q;r++){\n\tfor(unsigned s=0;s<P;s++){\n\t\tXv[Q*s+r] = co_t(0);\n\t\tfor(unsigned p=0;p<P;++p){\n\t\t\tXv[Q*s+r] += Y[r][p]*fp.copow(prefac*Q*s*p); \n\t\t}\n\t\tif(prefac == -1) Xv[Q*s+r] *= fp.nm;\n\t}\n\t}\n}\n\n\n////////////////////////////////////////////////\n// FFT implementaion, uses fieldpower \ntemplate<class co_t>\nclass DFT_FFT{\nprivate:\nfieldpower<co_t> fp;\nunsigned n; // the length of the dft\nunsigned P;\nunsigned Q;\n\npublic: \n\tDFT_FFT(const unsigned n_, const co_t& a_,unsigned P_, unsigned Q_){\n\t\tP = P_;\n\t\tQ = Q_;\n\t\tfp = fieldpower<co_t>(n_,a_);\n\t}\n\tDFT_FFT(){}; \n\n\tvoid dft( const vector<co_t>& xv, vector<co_t>& Xv) const {\n\t\tfft<co_t>(xv,Xv,fp,1,P,Q);\n\t};\n\n\tvoid idft(vector<co_t>& xv, const vector<co_t>& Xv) const {\n\t\tfft<co_t>(Xv,xv,fp,-1,P,Q);\n\t}\n\n};\n\n////////////////////////////////////////////////\n\n\n\n// DFT implementation of certain lenth that uses a precomputed lookup table to compute the powers of a\ntemplate<class co_t>\nclass DFT_LA{\nprivate:\nco_t a; // the Fourier kernal\nco_t am;\nunsigned n; // the length of the dft\nco_t nm;\nvector<co_t> powers_a; // the lookup table for the powers of a\nvector<co_t> powers_am; // the lookup table for the powers of a^(-1)\n\npublic: \n\tDFT_LA(const unsigned n_, const co_t& a_){\n\t\ta = a_;\n\t\tn = n_;\n\t\t\n\t\tnm = co_t(n);\n\t\tnm = pow( (co_t) nm,-1  );\n\n\t\t// initialize powers_a\n\t\tpowers_a.resize( ((n-1)*(n-1)+1) );\n\t\tpowers_a[0] = co_t(1);\n\t\tpowers_a[1] =\ta;\n\t\tfor(int i =2;i < powers_a.size();++i)\n\t\t\tpowers_a[i] = powers_a[i-1]*a;\n\n\t\t// initialize powers_am\n\t\tam = pow( (co_t) a,-1);\n\t\tpowers_am.resize( ((n-1)*(n-1)+1) );\n\t\tpowers_am[0] = co_t(1);\n\t\tpowers_am[1] =\tam;\n\t\tfor(int i =2;i < powers_am.size();++i)\n\t\t\tpowers_am[i] = powers_am[i-1]*am;\n\t\t\n\t\tcout << \"lookup tables generated.. \" << endl;\n\t}\n\n\tvoid dft( vector<co_t>& xv, vector<co_t>& Xv) const {\n\t\t//assert(xv.size() == Xv.size());\n\t\tfor(int j=0; j < Xv.size();++j){\n\t\t\t// compute Xv[j]\n\t\t\tXv[j] = co_t(0);\n\t\t\tfor(int i=0;i < xv.size(); ++i){\n\t\t\t\t//Xv[j] += xv[i]*pow( (coeff_t)  a, (int)  i*j);\n\t\t\t\tXv[j] += xv[i]*powers_a[i*j];\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid idft(vector<co_t>& xv, vector<co_t>& Xv) const {\n\t\tassert(xv.size() == Xv.size());\n\t\tfor(int j=0; j < xv.size();++j){\n\t\t\t// compute Xv[j]\n\t\t\t//cout << \"adf\"<< endl;\n\t\t\txv[j] = co_t(0);\n\t\t\t//cout << j << endl;\n\t\t\tfor(int i=0;i < Xv.size(); ++i){\n\t\t\t\t//cout << \"--\" << i << endl;\n\t\t\t\t//cout << i << \"-- Xv: \" <<  Xv[i] << \" powers \" << powers_am[i*j] << endl;\n\t\t\t\t//cout << \"-- xv: \" << xv[j] << endl; \n\t\t\t\txv[j] += nm*Xv[i]*powers_am[i*j];\n\t\t\t}\n\t\t}\n\t}\n\n};\n\n// primitive DFT \ntemplate<class co_t>\nclass DFT_PRIM{\nprivate:\nco_t a; // the Fourier kernal\nco_t am;\nunsigned n; // the length of the dft\nco_t nm;\n\npublic: \n\tDFT_PRIM(){};\n\tDFT_PRIM(const unsigned n_, const co_t& a_){\n\t\ta = a_;\n\t\tn = n_;\n\t\t\n\t\tnm = co_t(n);\n\t\tnm = pow( (co_t) nm,-1  );\n\t}\n\n\tvoid dft( vector<co_t>& xv, vector<co_t>& Xv) const {\n\n\t\t//assert(xv.size() == Xv.size());\n\t\tfor(int j=0; j < Xv.size();++j){\n\t\t\t// compute Xv[j]\n\t\t\tXv[j] = co_t(0);\n\t\t\tfor(int i=0;i < xv.size(); ++i){\n\t\t\t\t//Xv[j] += xv[i]*pow( (coeff_t)  a, (int)  i*j);\n\t\t\t\tXv[j] += xv[i]*pow( (co_t) a, i*j);\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid idft(vector<co_t>& xv, vector<co_t>& Xv) const {\n\t\tfor(int j=0; j < Xv.size();++j){\n\t\t\t// compute Xv[j]\n\t\t\txv[j] = co_t(0);\n\t\t\tfor(int i=0;i < xv.size(); ++i)\n\t\t\t\txv[j] += nm*Xv[i]*pow( (co_t) a,i*j);\n\t\t}\n\t}\n\n};\n\n\n// to do: implement the faster FFT\ntemplate<class coeff_t>\nvoid dft( vector<coeff_t>& xv, vector<coeff_t>& Xv, coeff_t a ){\n\n\t\n\tcout << \"startcomplookup\" << endl; \n\tunsigned nn = Xv.size();\n\t//compute lookup table\n\tvector<coeff_t> powers( ((nn-1)*(nn-1)+1) );\n\tpowers[0] = coeff_t(1);\n\tpowers[1] =\ta;\n\tfor(int i =2;i < powers.size();++i)\n\t\tpowers[i] = powers[i-1]*a;\n\tcout << \"finishcomplookup\" << endl; \n\n\t\n\tassert(xv.size() == Xv.size());\n\tfor(int j=0; j < Xv.size();++j){\n\t\t// compute Xv[j]\n\t\tXv[j] = coeff_t(0);\n\t\tfor(int i=0;i < xv.size(); ++i){\n\t\t\t//Xv[j] += xv[i]*pow( (coeff_t)  a, (int)  i*j);\n\t\t\tXv[j] += xv[i]*powers[i*j];\n\t\t}\n\t}\n};\n\n\n// nm: n^-1 ,where n is the lenght of the dft\n// am: a^-1, where a is an element of order n\n/*\ntemplate <class coeff_t>\nvoid idft(vector<coeff_t>& xv, vector<coeff_t>& Xv,coeff_t am, coeff_t nm ){\n\tassert(xv.size() == Xv.size());\n\tfor(int j=0; j < Xv.size();++j){\n\t\t// compute Xv[j]\n\t\txv[j] = coeff_t(0);\n\t\tfor(int i=0;i < xv.size(); ++i)\n\t\t\txv[j] += nm*Xv[i]*pow( (coeff_t) am, (int)  i*j);\n\t}\n\t\n}\n*/\n\n\ntemplate <class coeff_t>\nvoid idft(vector<coeff_t>& xv, vector<coeff_t>& Xv,coeff_t a ){\n\tassert(xv.size() == Xv.size());\n\n\tunsigned nn = xv.size();\n\tcoeff_t n = coeff_t(nn);\n\tcout << \"n: \" << n << endl;\n\tn = pow(n,-1);\n\t\n\t\n\t//compute lookup table\n\tcout << \"startcomplookup\" << endl; \n\tcoeff_t am = pow( (coeff_t) a,-1);\n\tvector<coeff_t> powers( ((nn-1)*(nn-1)+1) );\n\tpowers[0] = coeff_t(1);\n\tpowers[1] =\tam;\n\tfor(int i =2;i < powers.size();++i)\n\t\tpowers[i] = powers[i-1]*am;\n\n\tcout << \"finishlookuptable.. \" << endl;\n\n\tfor(int j=0; j < Xv.size();++j){\n\t\t// compute Xv[j]\n\t\txv[j] = coeff_t(0);\n\t\tfor(int i=0;i < xv.size(); ++i){\n\t\t\t\n\t\t\t//xv[j] += n*Xv[i]*pow( (coeff_t) am, (int)  i*j);\n\t\t\txv[j] += n*Xv[i]*powers[i*j];\n\t\t}\n\t}\n\t\n}\n\n#endif\n", "meta": {"hexsha": "709cb4494cc5b791255043f47fdc0f2595089c87", "size": 7455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/DFT.hpp", "max_stars_repo_name": "zhaofeng-shu33/dna_data_storage", "max_stars_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-12-12T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T17:58:00.000Z", "max_issues_repo_path": "include/DFT.hpp", "max_issues_repo_name": "zhaofeng-shu33/dna_data_storage", "max_issues_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-22T19:55:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T19:55:28.000Z", "max_forks_repo_path": "include/DFT.hpp", "max_forks_repo_name": "zhaofeng-shu33/dna_data_storage", "max_forks_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-21T23:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-21T23:57:51.000Z", "avg_line_length": 22.1216617211, "max_line_length": 116, "alphanum_fraction": 0.5639168343, "num_tokens": 2766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6423307507926251}}
{"text": "/*=============================================================================\nCopyright 2020 Syed Ali Hasan <alihasan9922@gmail.com>\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile License.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n\n#define BOOST_TEST_MODULE utility\n\n#include <iostream>\n#include <boost/units/io.hpp>\n#include <boost/units/systems/angle/degrees.hpp>\n\n#include <boost/astronomy/coordinate/coord_sys/horizon_coord.hpp>\n#include <boost/astronomy/coordinate/coord_sys/ecliptic_coord.hpp>\n#include <boost/astronomy/coordinate/coord_sys/galactic_coord.hpp>\n#include <boost/astronomy/coordinate/coord_sys/equatorial_ra_coord.hpp>\n#include <boost/astronomy/coordinate/coord_sys/equatorial_ha_coord.hpp>\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/astronomy/coordinate/utility/utility.hpp>\n\n#include <boost/astronomy/time/parser.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/astronomy/time/time_conversions.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace boost::units;\nusing namespace boost::units::si;\nusing namespace boost::astronomy::coordinate;\n\nnamespace bud = boost::units::degree;\nnamespace bac = boost::astronomy::coordinate;\n\nusing namespace boost::numeric::ublas;\nnamespace bnu = boost::numeric::ublas;\n\nusing namespace boost::gregorian;\nusing namespace boost::posix_time;\n\nBOOST_AUTO_TEST_SUITE(utility)\n\nBOOST_AUTO_TEST_CASE(column_vector) {\n\n  quantity<bud::plane_angle, double> u = 97.638119 * bud::degree;\n  quantity<bud::plane_angle, double> v = -17.857969 * bud::degree;\n\n  bac::column_vector<double, quantity<bud::plane_angle>, double> vec(u,v);\n\n  BOOST_CHECK_CLOSE(vec.get()(0,0), -0.126512, 0.001);\n  BOOST_CHECK_CLOSE(vec.get()(1,0), 0.943374, 0.001);\n  BOOST_CHECK_CLOSE(vec.get()(2,0), -0.306658, 0.001);\n}\n\nBOOST_AUTO_TEST_CASE(ha_dec_horizon) {\n\n  /**\n   * What are the Horizon Coordinated (Altitude and Azimuth)\n   * of a star whose Hour Angle is 5h 51m 44s and\n   * Declination is +23\u25e6 13\u2032 10\u2032\u2032?\n   * The observer\u2019s latitude is 52\u25e6 N.\n   */\n\n  double ha = decimal_hour(5,51,44).get() * 15.0;\n  double declination = 23.21944444;\n  quantity<bud::plane_angle, double> phi1 = 52.0 * bud::degree;\n\n  equatorial_ha_coord<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>>\n      eha(ha * bud::degrees, declination * bud::degrees);\n\n  bac::column_vector<double, quantity<bud::plane_angle>, double> vec1(eha.get_ha(),eha.get_dec());\n\n  matrix<double> resultant_vector1 = prod(bac::ha_dec_horizon<double, quantity<bud::plane_angle>, double>(phi1).get(),vec1.get());\n\n  auto coordinates1 = bac::extract_coordinates(resultant_vector1).get_coordinates();\n  auto theta1 = coordinates1.first;\n  auto gama1 = coordinates1.second;\n\n  BOOST_CHECK_CLOSE(theta1.value() * 180.0 / PI, -76.728973, 0.001);\n  BOOST_CHECK_CLOSE(gama1.value() * 180.0 / PI, 19.33434444, 0.001);\n\n  /**\n   * What are the Equatorial Coordinates (Hour Angle and Declination)\n   * of a star that is observed by an observer at latitude 52\u25e6 N to\n   * have an Altitude of 19\u25e6 20\u2032 03.64\u2032\u2032 and an Azimuth of 283\u25e6 16\u2032 15.7\u2032\n   */\n\n  double altitude_a = 19.334344;\n  double azimuth_A = 283.271028;\n  quantity<bud::plane_angle, double> phi2 = 52.0 * bud::degree;\n\n  horizon_coord<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>>\n      hc(altitude_a * bud::degrees, azimuth_A * bud::degrees);\n\n  bac::column_vector<double, quantity<bud::plane_angle>, double> vec2(hc.get_azimuth(),hc.get_altitude());\n\n  matrix<double> resultant_vector2 = prod(bac::ha_dec_horizon<double, quantity<bud::plane_angle>, double>(phi2).get(),vec2.get());\n\n  auto coordinates2 = bac::extract_coordinates(resultant_vector2).get_coordinates();\n  auto theta2 = coordinates2.first;\n  auto gama2 = coordinates2.second;\n\n  BOOST_CHECK_CLOSE(theta2.value() * 180.0 / PI, 87.933334, 0.001);\n  BOOST_CHECK_CLOSE(gama2.value() * 180.0 / PI, 23.219444, 0.001);\n}\n\nBOOST_AUTO_TEST_CASE(ha_dec_ra_dec) {\n\n  /**\n   * What was the Local Hour Angle of a star whose Right Ascension\n   * was 18h 32m 21s on local calendar date 22 April 1980 when\n   * observed in time zone \u22124 h from\n   * Longitude 64\u25e6 W at local time 14h 36m 51.67s?\n   */\n  double ra = decimal_hour(18,32,21).get() * 15.0;\n  double declination = 23.21944444;\n\n  std::string ts1(\"1980-04-22 14:36:51.67\");\n  ptime t1(time_from_string(ts1));\n\n  decimal_hour d1 = LST(64,DIRECTION::WEST, t1);\n\n  quantity<bud::plane_angle, double> ST = (d1.get() + 4) * 15 * bud::degree;\n\n  equatorial_ra_coord<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>>\n      era(ra * bud::degrees, declination * bud::degrees);\n\n  bac::column_vector<double, quantity<bud::plane_angle>, double> vec1(era.get_ra(),era.get_dec());\n\n  matrix<double> resultant_vector1 = prod(bac::ha_dec_ra_dec<double, quantity<bud::plane_angle>, double>(ST).get(),vec1.get());\n\n  auto coordinates1 = bac::extract_coordinates(resultant_vector1).get_coordinates();\n  auto theta1 = coordinates1.first;\n  auto gama1 = coordinates1.second;\n\n  //Hour Angle converted from degree to hour\n  BOOST_CHECK_CLOSE((theta1.value() * 180.0 / PI) / 15.0, 9.873239, 1);\n  BOOST_CHECK_CLOSE(gama1.value() * 180.0 / PI, 23.219444, 0.001);\n\n  /**\n   * What was the Right Ascension of a star whose Local Hour Angle\n   * was 9h 52m 23.66s on local calendar date 22 April 1980 when\n   * observed in time zone \u22124 h from\n   * Longitude 64\u25e6 W at local time 14h 36m 51.67s?\n   */\n  double ha = decimal_hour(9,52,23.66).get() * 15.0;\n\n  equatorial_ha_coord<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>>\n      eha(ha * bud::degrees, declination * bud::degrees);\n\n  bac::column_vector<double, quantity<bud::plane_angle>, double> vec2(eha.get_ha(),eha.get_dec());\n\n  matrix<double> resultant_vector2 = prod(bac::ha_dec_ra_dec<double, quantity<bud::plane_angle>, double>(ST).get(),vec2.get());\n\n  auto coordinates2 = bac::extract_coordinates(resultant_vector2).get_coordinates();\n  auto theta2 = coordinates2.first;\n  auto gama2 = coordinates2.second;\n\n  // Right Ascension converted from degree to hour\n  // If Right Ascension negative, add 24.\n  long double theta = (theta2.value() * 180.0 / PI) / 15.0;\n  long double ra_result = ( theta ) < 0 ? theta + 24.0 : theta;\n\n  BOOST_CHECK_CLOSE(ra_result, 18.539165, 1);\n  BOOST_CHECK_CLOSE(gama2.value() * 180.0 / PI, 23.219444, 0.001);\n}\n\nBOOST_AUTO_TEST_CASE(ecliptic_to_ra_dec) {\n\n  /**\n   * What were the Right Ascension and the declination of a planet\n   * whose ecliptic coordinates were longitude 139\u25e6 41\u2032 10\u2032\u2032 and\n   * latitude 4\u25e6 52\u2032 31\u2032\u2032 on 6 July 2009?\n   */\n  double longitude = 139.6861111;\n  double latitude = 4.87527778;\n\n  std::string s(\"2009-07-6\");\n  date d(from_simple_string(s));\n\n  auto obliquity = obliquity_of_ecliptic(d).get();\n  BOOST_CHECK_CLOSE(obliquity.value() * 180.0 / PI, 23.43805531 , 0.001);\n\n  ecliptic_coord<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>>\n      ec(longitude * bud::degrees, latitude * bud::degrees);\n\n  bac::column_vector<double, quantity<bud::plane_angle>, double> vec(ec.get_lat(),ec.get_lon());\n\n  matrix<double> resultant_vector1 = prod(bac::ecliptic_to_ra_dec<>(obliquity).get(),vec.get());\n\n  auto coordinates = bac::extract_coordinates(resultant_vector1).get_coordinates();\n  auto theta = coordinates.first;\n  auto gama = coordinates.second;\n\n  BOOST_CHECK_CLOSE((theta.value() * 180.0 / PI), 143.722173, 0.001);\n  BOOST_CHECK_CLOSE(gama.value() * 180.0 / PI, 19.535003, 0.001);\n}\n\nBOOST_AUTO_TEST_CASE(ra_dec_to_ecliptic) {\n  /**\n   * What are the Ecliptic Coordinates of a planet whose\n   * Right Ascension and Declination are given as\n   * \u03b1 = 9h 34m 53.32s and \u03b4 = 19\u25e6 32\u2032 6.01\u2032\u2032\n   * when the Greenwich calendar date is 6July2009?\n   */\n\n  double ra = decimal_hour(9,34,53.32).get() * 15.0;\n  double declination = 19.535003;\n\n  std::string s(\"2009-07-6\");\n  date d(from_simple_string(s));\n\n  auto obliquity = obliquity_of_ecliptic(d).get();\n  BOOST_CHECK_CLOSE(obliquity.value() * 180.0 / PI, 23.43805531 , 0.001);\n\n  equatorial_ra_coord<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>>\n      era(ra * bud::degrees, declination * bud::degrees);\n\n  bac::column_vector<double, quantity<bud::plane_angle>, double> vec(era.get_ra(),era.get_dec());\n\n  matrix<double> resultant_vector = prod(bac::ra_dec_to_ecliptic<>(obliquity).get(),vec.get());\n\n  auto coordinates = bac::extract_coordinates(resultant_vector).get_coordinates();\n  auto theta = coordinates.first;\n  auto gama = coordinates.second;\n\n  BOOST_CHECK_CLOSE((theta.value() * 180.0 / PI), 139.686106, 0.001);\n  BOOST_CHECK_CLOSE(gama.value() * 180.0 / PI, 4.875276, 0.001);\n}\n\nBOOST_AUTO_TEST_CASE(ra_dec_to_galactic) {\n\n  /**\n   * What are the Galactic Coordinates of a star whose\n   * right ascension and declination are\n   * \u03b1 = 10h 21m 00s and \u03b4 = 10\u25e6 03\u2032 11\u2032\u2032?\n   */\n\n  double ra = decimal_hour(10,21,0).get() * 15.0;\n  double declination = 10.053056;\n\n  equatorial_ra_coord<double, quantity<bud::plane_angle>, quantity<bud::plane_angle>>\n      era(ra * bud::degrees, declination * bud::degrees);\n\n  bac::column_vector<double, quantity<bud::plane_angle>, double> vec(era.get_ra(),era.get_dec());\n\n  matrix<double> resultant_vector = prod(bac::ra_dec_to_galactic<double>().get(),vec.get());\n\n  auto coordinates = bac::extract_coordinates(resultant_vector).get_coordinates();\n  auto theta = coordinates.first;\n  auto gama = coordinates.second;\n\n  long double longitude_result = theta.value() * 180.0 / PI;\n  long double longitude = ( longitude_result ) < 0 ? longitude_result + 360.0 : longitude_result;\n\n  BOOST_CHECK_CLOSE(longitude, 232.247881, 0.001);\n  BOOST_CHECK_CLOSE(gama.value() * 180.0 / PI, 51.122268, 0.001);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7c8f6787abdf97834e6060ed4f815512715a40f2", "size": 9912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/coordinate/utility.cpp", "max_stars_repo_name": "lpranam/Astronomy", "max_stars_repo_head_hexsha": "63aa055a3ce849210680451d81db4cc1ddc8d402", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-14T08:23:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T05:26:19.000Z", "max_issues_repo_path": "test/coordinate/utility.cpp", "max_issues_repo_name": "Zyro9922/astronomy", "max_issues_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_issues_repo_licenses": ["BSL-1.0"], "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/coordinate/utility.cpp", "max_forks_repo_name": "Zyro9922/astronomy", "max_forks_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_forks_repo_licenses": ["BSL-1.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.5454545455, "max_line_length": 130, "alphanum_fraction": 0.7095439871, "num_tokens": 2915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6422513890440383}}
{"text": "//\n// Created by Vlad Argunov on 17/01/2022.\n//\n\n#include \"OptimalExecution.h\"\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <random>\n#include <string>\n#include <cmath>\n#include \"Simulation.h\"\n\nOptimalExecution::OptimalExecution(double a_coeff_, double b_coeff_, double sigma_coeff_, double k_coeff_, double phi_coeff_) {\n    a_coeff = a_coeff_;\n    b_coeff = b_coeff_;\n    sigma_coeff = sigma_coeff_;\n    k_coeff = k_coeff_;\n    phi_coeff = phi_coeff_;\n}\n\n\nvoid OptimalExecution::compute_liquidation(const std::string& trading_speed, double impact_nonlinearity) {\n    int num_rows = num_diff_q + 1;\n    int num_cols = num_diff_t + 1;\n    sim = Simulation();\n    value_matrix.resize(num_rows, num_cols);\n    optimal_speed_matrix.resize(num_rows, num_cols);\n    double diff_q = 1.0 / num_diff_q;\n    double diff_t = 1.0 / num_diff_t;\n    double quantity;\n    double h_diff_q_up;\n    double h_diff_q_down;\n    double partial_diff_q;\n\n    Eigen::VectorXd diffusion; diffusion.resize(num_cols - 1);\n    diffusion = sim.generate_normal_variable(num_cols - 1, 0, pow(diff_t, 2));\n\n    stock.resize(num_cols); inventory.resize(num_cols);\n    cash.resize(num_cols); optimal_speed.resize(num_cols);\n    value_full.resize(num_cols);\n\n    if (trading_speed == \"Nonlinear\" || trading_speed == \"Linear\") {\n\n        // That part computes the matrix of value_matrix function for each value of time and quantity.\n        for (int col = (num_cols - 1); col > -1; --col) { // Time space\n            for (int row = 0; row < num_rows; ++row) { // Stock space\n                quantity = row * diff_q;\n\n                if (trading_speed == \"Linear\"){\n                    double gamma = sqrt(phi_coeff / k_coeff);\n                    double zeta = (a_coeff - 0.5 * b_coeff + sqrt(k_coeff * phi_coeff)) / (a_coeff - 0.5 * b_coeff - sqrt(k_coeff * phi_coeff));\n                    double remaining_time = (num_cols - col) * diff_t;\n                    optimal_speed_matrix(row, col) = gamma * (zeta * exp(gamma * remaining_time) + exp(- gamma * remaining_time)) / (zeta * exp(gamma) - exp(- gamma));\n                }\n\n                if (col == (num_cols - 1)){\n                    value_matrix(row, col) = - a_coeff * quantity * quantity;\n\n                    if (trading_speed == \"Nonlinear\") {\n                        optimal_speed_matrix(row, col) = pow(abs(-(b_coeff * quantity - 2 * a_coeff * quantity) / ((1 + a_coeff) * k_coeff))\n                                ,1.0 / impact_nonlinearity);\n                    }\n                } else {\n\n                    if (row == 0){\n                        h_diff_q_up =  value_matrix(row + 1, col + 1);\n                        h_diff_q_down =  value_matrix(row, col + 1);\n                        partial_diff_q = (h_diff_q_up - h_diff_q_down) / (diff_q);\n                    } else if (row == (num_rows - 1)) {\n                        h_diff_q_up =  value_matrix(row, col + 1);\n                        h_diff_q_down =  value_matrix(row - 1, col + 1);\n                        partial_diff_q = (h_diff_q_up - h_diff_q_down) / (diff_q);\n                    } else {\n                        h_diff_q_up =  value_matrix(row + 1, col + 1);\n                        h_diff_q_down =  value_matrix(row - 1, col + 1);\n                        partial_diff_q = (h_diff_q_up - h_diff_q_down) / (2 * diff_q);\n                    }\n\n                    value_matrix(row, col) = value_matrix(row, col + 1) -\n                            diff_t * (phi_coeff * pow(quantity, 2) - a_coeff * k_coeff *\n                            pow(abs(-(b_coeff * quantity + partial_diff_q ) / ((1 + a_coeff) * k_coeff))\n                                ,1.0 + 1.0/ impact_nonlinearity));\n\n\n                    if (trading_speed == \"Nonlinear\"){\n                        optimal_speed_matrix(row, col) = pow(abs(-(b_coeff * quantity + partial_diff_q) / ((1 + a_coeff) * k_coeff))\n                                ,1.0 / impact_nonlinearity);\n                    }\n\n                }\n            }\n        }\n\n        // That part simulates stock, cash, and inventory processes\n        for (int step = 0; step < num_cols; ++step) {\n            if (step == 0){\n                inventory(step) = 1;\n                stock(step) = 1;\n                cash(step) = 0;\n\n                optimal_speed(step) = optimal_speed_matrix(num_rows - 1, step);\n                value_full(step) = cash(step) + inventory(step) * stock(step) + value_matrix(num_rows - 1, step);\n\n\n            } else {\n                inventory(step) = std::max(inventory(step - 1) - optimal_speed(step - 1) * diff_t, 0.0);\n                stock(step) = stock(step - 1) - b_coeff * optimal_speed(step - 1) * diff_t\n                        + sigma_coeff * diffusion(step - 1);\n                cash(step) = cash(step - 1) + (stock(step - 1)\n                        - k_coeff * pow(optimal_speed(step - 1), impact_nonlinearity)) * optimal_speed(step - 1) * diff_t;\n\n                // Determine the relevant trading speed and value function\n                for (int row = 0; row < num_rows; ++row) {\n                    if ((row * diff_q <= inventory(step)) && ((row + 1) * diff_q > inventory(step))){\n                        if (row != (num_rows - 1)){\n                            optimal_speed(step) =\n                                    (((row + 1) * diff_q - inventory(step)) / diff_q) * optimal_speed_matrix(row, step) +\n                                    ((inventory(step) - row * diff_q) / diff_q) * optimal_speed_matrix(row + 1, step);\n\n\n                            value_full(step) = cash(step) + inventory(step) * stock(step) +\n                                    (((row + 1) * diff_q - inventory(step)) / diff_q) * value_matrix(row, step) +\n                                    ((inventory(step) - row * diff_q) / diff_q) * value_matrix(row + 1, step);\n                        } else {\n                            optimal_speed(step) = optimal_speed_matrix(num_rows - 1, step);\n                            value_full(step) = cash(step) + inventory(step) * stock(step) + value_matrix(num_rows - 1, step);\n                        }\n\n                    }\n                }\n            }\n        }\n    }\n\n    if (inventory(num_cols - 1) > 0.0){\n        cash(num_cols - 1) += inventory(num_cols - 1) * (stock(num_cols - 1) - a_coeff * inventory(num_cols - 1));\n    }\n    }\n\n\n\n\n\nvoid OptimalExecution::set_num_steps(int num_diff_t_, int num_diff_q_) {\n    num_diff_t = num_diff_t_;\n    num_diff_q = num_diff_q_;\n}\n", "meta": {"hexsha": "23ef1342651da332e097214b151b61c91b79713c", "size": 6470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OptimalExecution.cpp", "max_stars_repo_name": "vladargunov/QuantKit", "max_stars_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/OptimalExecution.cpp", "max_issues_repo_name": "vladargunov/QuantKit", "max_issues_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OptimalExecution.cpp", "max_forks_repo_name": "vladargunov/QuantKit", "max_forks_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4228187919, "max_line_length": 167, "alphanum_fraction": 0.5193199382, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6422513744104762}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2018-2019, LAAS-CNRS\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_UTILS_MATH_HPP_\n#define CROCODDYL_CORE_UTILS_MATH_HPP_\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <limits>\n\ntemplate <typename MatrixType>\nMatrixType pseudoInverse(const MatrixType& a, double epsilon = std::numeric_limits<double>::epsilon()) {\n  Eigen::JacobiSVD<MatrixType> svd(a, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  double tolerance =\n      epsilon * static_cast<double>(std::max(a.cols(), a.rows())) * svd.singularValues().array().abs()(0);\n  return svd.matrixV() *\n         (svd.singularValues().array().abs() > tolerance)\n             .select(svd.singularValues().array().inverse(), 0)\n             .matrix()\n             .asDiagonal() *\n         svd.matrixU().adjoint();\n}\n\n#endif  // CROCODDYL_CORE_UTILS_MATH_HPP_\n", "meta": {"hexsha": "e4d56bd93f51b81d1d95519c96b4745464ca4aa9", "size": 1085, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/utils/math.hpp", "max_stars_repo_name": "paLeziart/crocoddyl", "max_stars_repo_head_hexsha": "c31a27432f9f2b365faec31b5e7cb37d90b7abb0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-25T13:17:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-25T13:17:23.000Z", "max_issues_repo_path": "include/crocoddyl/core/utils/math.hpp", "max_issues_repo_name": "paLeziart/crocoddyl", "max_issues_repo_head_hexsha": "c31a27432f9f2b365faec31b5e7cb37d90b7abb0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crocoddyl/core/utils/math.hpp", "max_forks_repo_name": "paLeziart/crocoddyl", "max_forks_repo_head_hexsha": "c31a27432f9f2b365faec31b5e7cb37d90b7abb0", "max_forks_repo_licenses": ["BSD-3-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.1666666667, "max_line_length": 106, "alphanum_fraction": 0.5889400922, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.6422513681691339}}
{"text": "\n#include \"ros_utils.hpp\"\n#include \"kinematics.hpp\"\n#include <boost/array.hpp>\n\n#include <casadi/casadi.hpp>\n\n#include <mhe_estimator/CanData.h>\n#include <mhe_estimator/ArticulatedAngles.h>\n#include \"std_msgs/String.h\"\n#include \"geometry_msgs/PoseWithCovarianceStamped.h\"\n#include \"ackermann_msgs/AckermannDrive.h\"\n\n\nnamespace mhe_estimator\n{\n    using namespace casadi;\n\n    void mheSetupCar(casadi::Function& solver, const mhe_estimator::CarParams& params, const mhe_estimator::MheParams& mheParams,const long unsigned int N_mhe)\n    {\n        \n        double A = N_mhe;\n        double B = N_mhe+1;\n        SX theta = SX::sym(\"theta\"); SX x = SX::sym(\"x\"); SX y = SX::sym(\"y\"); SX beta0 = SX::sym(\"beta0\");  \n        SX u1 = SX::sym(\"u1\"); SX u2 = SX::sym(\"u2\"); \n\n        SX states = vertcat(theta, x, y, beta0); \n        SX controls = vertcat(u1, u2);  //u1 =dbeta     u2= linear vel \n        unsigned int n_states = states.size1(); unsigned int n_controls = controls.size1();\n\n        SX rhs = vertcat(u2*(1/params.L)*tan(beta0), u2*cos(theta), u2*sin(theta), u1); //system r.h.s  theta, x, y, beta0\n        Function f = Function(\"f\",{states,controls}, {rhs}); //nonlinear mapping function f(x,u)\n        \n        SX U = SX::sym(\"U\",n_controls,A);     //A = N_MHE \n        SX X = SX::sym(\"X\",n_states,B);       //B = N_MHE +1\n        SX P = SX::sym(\"P\",n_states,B+A+B+A); //state,control,covOfState,covOfControl \n        \n        SX obj = 0;\n        SX g;\n\n        for(int k = 0; k < B; k++) // Create states objective function \n        {\n            SX h_x = vertcat(X(0,k), X(1,k), X(2,k), X(3,k));\n            SX y_tilde = vertcat(P(0,k), P(1,k), P(2,k), P(3,k));\n            SX V = SX::zeros(n_states,n_states);\n            V(0,0) = P(0,B+A+k); \n            V(1,1) = P(1,B+A+k); \n            V(2,2) = P(2,B+A+k); \n            V(3,3) = P(3,B+A+k);\n            obj = obj + mtimes(mtimes(((y_tilde - h_x).T()), V), (y_tilde - h_x));\n        }\n        for(int k = 0; k < A; k++) // Create control objective function \n        {\n            SX con = vertcat(U(0,k), U(1,k));\n            SX u_tilde = vertcat(P(0,B+k), P(1,B+k));\n            SX W = SX::zeros(n_controls,n_controls);\n            W(0,0) = P(0,B+A+B+k); \n            W(1,1) = P(1,B+A+B+k); \n            obj = obj + mtimes(mtimes(((u_tilde - con).T()), W), (u_tilde - con));\n        }\n\n        for(int k = 0; k < A; k++) //  multiple shooting constraints\n        {\n            SX con = vertcat(U(0,k), U(1,k));\n            SX st = vertcat(X(0,k), X(1,k), X(2,k), X(3,k));\n            SX st_next = vertcat(X(0,k+1), X(1,k+1), X(2,k+1), X(3,k+1));\n            SXVector func = f(SXVector{st,con});\n            SX f_value = SX::vertcat(func);\n            SX st_next_euler = st + ((1/mheParams.loopRate)*f_value);\n            g = vertcat(g, (st_next-st_next_euler));\n        }\n\n        SX OPT_variables; //optimization variable\n\n        for(int j = 0; j < X.size2(); j++) //reshape X and apend\n        {\n            for(int i = 0; i < X.size1(); i++)\n            {\n                OPT_variables = vertcat(OPT_variables, X(i,j));\n            }\n        }\n        for(int j = 0; j < U.size2(); j++) //reshape U and apend\n        {\n            for(int i = 0; i < U.size1(); i++)\n            {\n                OPT_variables = vertcat(OPT_variables, U(i,j));\n            }\n        }\n\n        \n        SXDict nlp = {{\"f\", obj}, {\"x\", OPT_variables}, {\"g\", g}, {\"p\", P}};\n        Dict opts;\n        /*\n        opts[\"qpsol\"] = \"qpoases\";\n//      opts[\"max_iter\"] =2;\n\n        opts[\"print_iteration\"] = true;\n        Dict qopts;\n        qopts[\"sparse\"]=true;\n\n        opts[\"qpsol_options\"] = qopts;\n\n        */\n        opts[\"ipopt.max_iter\"] = 2000;\n        opts[\"ipopt.print_level\"] = 0;\n        opts[\"print_time\"] = false;\n        opts[\"ipopt.acceptable_tol\"] = 1e-6;\n        opts[\"ipopt.acceptable_obj_change_tol\"] = 1e-4;\n        opts[\"ipopt.print_timing_statistics\"] = \"no\";\n        opts[\"ipopt.print_info_string\"] = \"no\";\n\n        solver = nlpsol(\"nlpsol\", \"ipopt\", nlp, opts);\n\n\n        //solver = nlpsol(\"nlpsol\", \"sqpmethod\", nlp, opts);\n        \n    }\n\n    void mheSetupTrailer(casadi::Function& solver,const mhe_estimator::CarParams& params,const mhe_estimator::MheParams& mheParams,const long unsigned int N_mhe)\n    {\n        double A = N_mhe;\n        double B = N_mhe+1;\n        SX beta1 = SX::sym(\"beta1\"); SX theta = SX::sym(\"theta\"); SX x = SX::sym(\"x\"); SX y = SX::sym(\"y\"); SX beta0 = SX::sym(\"beta0\"); \n        SX u1 = SX::sym(\"u1\"); SX u2 = SX::sym(\"u2\"); \n\n        SX states1 = vertcat(beta1,theta, x); \n        SX states2 = vertcat(y, beta0); \n        SX states = vertcat(states1, states2); // due to casadi limitation\n        SX controls = vertcat(u1, u2);  //u1 =dbeta     u2= linear vel \n        unsigned int n_states = states.size1(); unsigned int n_controls = controls.size1();\n\n        SX rhs;\n        SX k1 = (1/params.L1)*tan(beta1 - atan((params.Lh1/params.L)*tan(beta0)));\n        if(!params.moveGuidancePoint)  //OneTrailerKinematicsGPRear\n        {\n            SX dq0 = u2 * (sin(beta1)/params.Lh1 - (1 + (params.L1/params.Lh1)*cos(beta1))*(k1)); //beta1\n            SX dq1 = u2 * k1; //theta\n            SX dq2 = u2 * cos(theta); //x\n            SX dq3 = u2 * sin(theta); //y\n            SX dq4 = u1; //beta0\n            \n            SX rhs1 = vertcat(dq0, dq1, dq2); //due to casadi limitation \n            SX rhs2 = vertcat(dq3, dq4);\n            rhs = vertcat(rhs1, rhs2); //system r.h.s\n        } \n        else    //OneTrailerKinematicsGPFront\n        {\n            SX dq0 = u2 * (sin(beta1)/params.Lh1 - (1 + (params.L1/params.Lh1)*cos(beta1))*k1); //beta1\n            SX dq1 = u2 * ( -(params.L1/params.Lh1)*cos(beta1)*k1 + sin(beta1)/params.Lh1 ); //theta\n            SX dq2 = u2 * cos(theta) * ( params.L1*sin(beta1)*k1 + cos(beta1) ); //x\n            SX dq3 = u2 * sin(theta) * ( params.L1*sin(beta1)*k1 + cos(beta1) ); //y\n            SX dq4 = u1; //beta0\n            \n            \n            SX rhs1 = vertcat(dq0, dq1, dq2); //due to casadi limitation \n            SX rhs2 = vertcat(dq3, dq4);\n            rhs = vertcat(rhs1, rhs2); //system r.h.s\n        }\n            \n        //ROS_INFO_STREAM(\"rhstRAILER: \" << rhs <<\" \");\n        \n        Function f = Function(\"f\",{states,controls}, {rhs}); //nonlinear mapping function f(x,u)\n        \n        SX U = SX::sym(\"U\",n_controls,A); //A = N_MHE \n        SX X = SX::sym(\"X\",n_states,B); //B = N_MHE +1\n        SX P = SX::sym(\"P\",n_states,B+A+B+A); \n            \n        SX obj = 0;\n        SX g;\n        \n        for(int k = 0; k < B; k++) // Create states objective function \n        {\n            SX h_x1 = vertcat(X(0,k), X(1,k), X(2,k));\n            SX h_x2 = vertcat(X(3,k), X(4,k) );\n            SX h_x = vertcat(h_x1, h_x2);\n\n            SX y_tilde1 = vertcat(P(0,k), P(1,k), P(2,k));\n            SX y_tilde2 = vertcat(P(3,k), P(4,k));\n            SX y_tilde = vertcat(y_tilde1, y_tilde2);\n\n            SX V = SX::zeros(n_states,n_states);\n            V(0,0) = P(0,B+A+k); \n            V(1,1) = P(1,B+A+k); \n            V(2,2) = P(2,B+A+k); \n            V(3,3) = P(3,B+A+k);\n            V(4,4) = P(4,B+A+k);\n            obj = obj + mtimes(mtimes(((y_tilde - h_x).T()), V), (y_tilde - h_x));\n        }\n        for(int k = 0; k < A; k++) // Create control objective function \n        {\n            SX con = vertcat(U(0,k), U(1,k));\n            SX u_tilde = vertcat(P(0,B+k), P(1,B+k));\n            SX W = SX::zeros(n_controls,n_controls);\n            W(0,0) = P(0,B+A+B+k); \n            W(1,1) = P(1,B+A+B+k); \n            obj = obj + mtimes(mtimes(((u_tilde - con).T()), W), (u_tilde - con));\n        }\n\n        for(int k = 0; k < A; k++) //  multiple shooting constraints\n        {\n            SX con = vertcat(U(0,k), U(1,k));\n\n            SX st1 = vertcat(X(0,k), X(1,k), X(2,k));\n            SX st2 = vertcat(X(3,k), X(4,k));\n            SX st = vertcat(st1,st2);\n\n\n            SX st_next1 = vertcat(X(0,k+1), X(1,k+1), X(2,k+1));\n            SX st_next2 = vertcat(X(3,k+1), X(4,k+1));\n            SX st_next = vertcat(st_next1, st_next2);\n\n            SXVector func = f(SXVector{st,con});\n            SX f_value = SX::vertcat(func);\n            SX st_next_euler = st + ((1/mheParams.loopRate)*f_value);\n            g = vertcat(g, (st_next-st_next_euler));\n        }\n\n        //ROS_INFO_STREAM(\"g \" << g <<\" \");\n        \n        SX OPT_variables; //optimization variable\n        \n        for(int j = 0; j < X.size2(); j++) //reshape X and apend\n        {\n            for(int i = 0; i < X.size1(); i++)\n            {\n                OPT_variables = vertcat(OPT_variables, X(i,j));\n            }\n        }\n        for(int j = 0; j < U.size2(); j++) //reshape U and apend\n        {\n            for(int i = 0; i < U.size1(); i++)\n            {\n                OPT_variables = vertcat(OPT_variables, U(i,j));\n            }\n        }\n        //ROS_INFO_STREAM(\"g.size \" << g.size1() <<\" \");\n\n        \n        SXDict nlp = {{\"f\", obj}, {\"x\", OPT_variables}, {\"g\", g}, {\"p\", P}};\n        Dict opts;\n\n//        opts[\"qpsol\"] = \"gurobi\";\n//        opts[\"hessian_approximation\"] = \"limited-memory\";\n\n//        opts[\"max_iter\"] =10;\n\n//        opts[\"print_iteration\"] = true;\n//        opts[\"warn_initial_bounds\"] = true;\n//        Dict qopts;\n//       qopts[\"gurobi.Threads\"]=4;\n//       qopts[\"verbose\"]=false;\n\n////        qopts[\"sparse\"]=true;\n////         qopts[\"printLevel\"]=\"low\";\n//        qopts[\"linsol_plugin\"]=\"gurobi\";\n\n//        opts[\"qpsol_options\"] = qopts;\n//       opts[\"qpsol_options\"] = qopts;\n\n\n\n\n\n        opts[\"ipopt.max_iter\"] = 2000;\n        opts[\"ipopt.print_level\"] = 0;\n        opts[\"print_time\"] = false;\n        opts[\"ipopt.acceptable_tol\"] = 1e-6;\n        opts[\"ipopt.acceptable_obj_change_tol\"] = 1e-4;\n        opts[\"ipopt.print_timing_statistics\"] = \"no\";\n        opts[\"ipopt.print_info_string\"] = \"no\";\n\n        solver = nlpsol(\"nlpsol\", \"ipopt\", nlp, opts);\n    }\n  \n  ////////////////////////////////////////////////////////////////////////////////////////////////////////\n    template <class T, class T2, long unsigned int A, long unsigned int B>\n    void estimateMhe(casadi::DM& argx0, const boost::array<T, B>& q4wLoc,\n        const boost::array<T2, A>& control2w,const boost::array<T, B>& q4wCov,\n        const boost::array<T2, A>& control2wCov, const mhe_estimator::CarParams& carParams,\n        const mhe_estimator::MheParams& mheParams,const casadi::Function& solver)  \n    {\n        unsigned int n_states = 4; unsigned int n_controls = 2;\n        std::map<std::string, DM> arg, res;\n        arg[\"lbg\"] = SX::zeros(n_states*A); //size = n_state * N_Mhe\n        arg[\"ubg\"] = SX::zeros(n_states*A);\n        \n        std::vector<double> lbx((n_controls*A)+(n_states*B), 0.0);\n        std::vector<double> ubx((n_controls*A)+(n_states*B), 0.0);\n        \n        for(int i = 0; i < (n_states*B); i += n_states) \n        {\n            lbx[i] = carParams.lowerTh;  //theta lower bound\n            lbx[i+1]   = carParams.lowerX;    //x lower bound\n            lbx[i+2] = carParams.lowerY;  //y lower bound\n            lbx[i+3] = -carParams.steeringLimit;\n        \n        \n            ubx[i] = carParams.upperTh;   //theta upper bound\n            ubx[i+1]   = carParams.upperX;    //x upper bound\n            ubx[i+2] = carParams.upperY;  //y upper bound\n            ubx[i+3] = carParams.steeringLimit; //beta upper bound\n        \n        }\n        for(int i = ((n_states*B)); i < ((n_controls*A)+(n_states*B)); i += n_controls) \n        {\n            lbx[i] = -carParams.SteeringVelLimit;    //v lower bound\n            lbx[i+1] = -carParams.LinearVelLimit;  //beta lower bound\n        \n\n            ubx[i] = carParams.SteeringVelLimit;    //v upper bound\n            ubx[i+1] = carParams.LinearVelLimit;  //beta upper bound        \n            \n        }\n        arg[\"lbx\"] = lbx;\n        arg[\"ubx\"] = ubx;\n        //--------------ALL OF THE ABOVE IS JUST A PROBLEM SET UP-------------//\n        \n        \n        DM argp = SX::zeros(n_states,B+A+B+A);\n        for(int j = 0; j < B; j++) //measured states\n        {\n            boost::array<double, 4> qloc = q4wLoc[j];\n            argp(0,j) = qloc[0];\n            argp(1,j) = qloc[1];\n            argp(2,j) = qloc[2];\n            argp(3,j) = qloc[3];\n        }\n        for(int j = 0; j < A; j++) //measured controls\n        {\n            boost::array<double, 2> qctr = control2w[j];\n            //argp(0,j + B) = 0.0;   //we do not have measured control dbeta \n            argp(1,B+j) = qctr[1];\n        }\n        for(int j = 0; j < B; j++) //state cov matrix\n        {\n            boost::array<double, 4> qCov = q4wCov[j];\n            argp(0,B+A+j) = qCov[0];\n            argp(1,B+A+j) = qCov[1];\n            argp(2,B+A+j) = qCov[2];\n            argp(3,B+A+j) = qCov[3];\n        }\n        for(int j = 0; j < A; j++) //control cov matrix\n        {\n            boost::array<double, 2> ctrCov = control2wCov[j];\n            argp(0,B+A+B+j) = 0.0;   //we do not have measured control dbeta \n            argp(1,B+A+B+j) = ctrCov[1];\n        }\n\n        arg[\"p\"] = argp;\n        arg[\"x0\"] = argx0; //Comes as function parameter\n\n        res = solver(arg); // solve MHE\n        argx0 = res.at(\"x\");\n        \n    }\n\n    template <class T, class T2, long unsigned int A, long unsigned int B>\n    void estimateMheTrailer(casadi::DM& argx0Trailer,const boost::array<T, B>& q5wLocTrailer,\n        const boost::array<T2, A>& control2wTrailer,const boost::array<T, B>& q5wCovTrailer,\n        const boost::array<T2, A>& control2wCovTrailer,const mhe_estimator::CarParams& carParams,\n        const mhe_estimator::MheParams& mheParams,const casadi::Function& solver)  //check the ref and const\n    {\n        \n        unsigned int n_states = 5; unsigned int n_controls = 2;\n        std::map<std::string, DM> arg, res;\n        arg[\"lbg\"] = SX::zeros(n_states*A); //size = n_state * N_Mhe \n        arg[\"ubg\"] = SX::zeros(n_states*A);\n        \n        std::vector<double> lbx((n_controls*A)+(n_states*B), 0.0);\n        std::vector<double> ubx((n_controls*A)+(n_states*B), 0.0);\n        \n        for(int i = 0; i < (n_states*B); i += n_states) \n        {\n            lbx[i] = -carParams.trailer1Limit; \n            lbx[i+1] = carParams.lowerTh;   //theta lower bound\n            lbx[i+2] = carParams.lowerX;    //x lower bound\n            lbx[i+3] = carParams.lowerY;    //y lower bound\n            lbx[i+4] = -carParams.steeringLimit;\n        \n            ubx[i] = carParams.trailer1Limit; \n            ubx[i+1] = carParams.upperTh;   //theta upper bound\n            ubx[i+2] = carParams.upperX;    //x upper bound\n            ubx[i+3] = carParams.upperY;    //y upper bound\n            ubx[i+4] = carParams.steeringLimit; \n        }\n\n        ////////////////////////////////////////////\n\n        for(int i = (n_states*B); i < ((n_controls*A)+(n_states*B)); i += n_controls) \n        {\n            lbx[i] = -carParams.SteeringVelLimit;    //dbeta lower bound\n            lbx[i+1] = -carParams.LinearVelLimit;  //linear.vel lower bound\n\n            ubx[i] = carParams.SteeringVelLimit;  //dbeta upper bound\n            ubx[i+1] = carParams.LinearVelLimit;  //linear.vel upper bound  \n        }\n        arg[\"lbx\"] = lbx;\n        arg[\"ubx\"] = ubx;\n        //--------------ALL OF THE ABOVE IS JUST A PROBLEM SET UP-------------//\n\n        DM argp = SX::zeros(n_states,B+A+B+A);\n        for(int j = 0; j < B; j++) //measured state\n        {\n            boost::array<double, 5> qloc = q5wLocTrailer[j];\n            argp(0,j) = qloc[0]; //beta1\n            argp(1,j) = qloc[1]; //theta\n            argp(2,j) = qloc[2]; //x\n            argp(3,j) = qloc[3]; //y\n            argp(4,j) = qloc[4]; //beta0\n        }\n        for(int j = 0; j < A; j++) //measured control\n        {\n            boost::array<double, 2> qctr = control2wTrailer[j];\n            //argp(0,j+B) = 0.0;   //we do not have measured control dbeta \n            argp(1,j+B) = qctr[1];\n        }\n        for(int j = 0; j < B; j++) //state cov matrix\n        {\n            boost::array<double, 5> qCov = q5wCovTrailer[j];\n            argp(0,B+A+j) = qCov[0]; //beta1\n            argp(1,B+A+j) = qCov[1]; //theta\n            argp(2,B+A+j) = qCov[2]; //x\n            argp(3,B+A+j) = qCov[3]; //y\n            argp(4,B+A+j) = qCov[4]; //beta0\n        }\n        for(int j = 0; j < A; j++) //control cov matrix\n        {\n            boost::array<double, 2> ctrCov = control2wCovTrailer[j];\n            argp(0,B+A+B+j) = 0.0;   //we do not have measured control dbeta \n            argp(1,B+A+B+j) = ctrCov[1];\n        }\n\n\n        arg[\"p\"] = argp;\n        arg[\"x0\"] = argx0Trailer; //Comes as parameter\n\n        try\n        {\n          res = solver(arg); // solve MHE\n          argx0Trailer = res.at(\"x\");\n        } catch (casadi::CasadiException& ex)\n        {\n          ROS_ERROR_STREAM(ex.what());\n\n        }\n\n\n    \n    }\n    \n    void estimateEst(Vec3& qCarEst,const Vec3& qLoc,const Vec3& qPred,const MheParams& estParams)\n    {   \n           \n        qCarEst[0] = estParams.WeightTh*qPred[0] + (1-estParams.WeightTh)*qLoc[0];\n        qCarEst[1] = estParams.WeightPos*qPred[1] + (1-estParams.WeightPos)*qLoc[1];\n        qCarEst[2] = estParams.WeightPos*qPred[2] + (1-estParams.WeightPos)*qLoc[2];\n        \n    }\n\n    void estimateEstTrailer(Vec4& qTrailerEst,const Vec4& qTrailerLoc,const Vec4& qTrailerPred,const MheParams& estParams)\n    {   qTrailerEst[0] = estParams.WeightTrailer1*qTrailerPred[0] + (1-estParams.WeightTrailer1)*qTrailerLoc[0];           \n        qTrailerEst[1] = estParams.WeightTh*qTrailerPred[1] + (1-estParams.WeightTh)*qTrailerLoc[1];\n        qTrailerEst[2] = estParams.WeightPos*qTrailerPred[2] + (1-estParams.WeightPos)*qTrailerLoc[2];\n        qTrailerEst[3] = estParams.WeightPos*qTrailerPred[3] + (1-estParams.WeightPos)*qTrailerLoc[3];\n    }\n\n\n}\n", "meta": {"hexsha": "d486a90ebcd2f75d9732310e0ab3d7be0b65d958", "size": 17841, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mhe_estimator/estimators.hpp", "max_stars_repo_name": "crt-adas/mhe_estimator", "max_stars_repo_head_hexsha": "e96669c84c1eae76d13f03b2f5123e099419f2c7", "max_stars_repo_licenses": ["MIT"], "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/mhe_estimator/estimators.hpp", "max_issues_repo_name": "crt-adas/mhe_estimator", "max_issues_repo_head_hexsha": "e96669c84c1eae76d13f03b2f5123e099419f2c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mhe_estimator/estimators.hpp", "max_forks_repo_name": "crt-adas/mhe_estimator", "max_forks_repo_head_hexsha": "e96669c84c1eae76d13f03b2f5123e099419f2c7", "max_forks_repo_licenses": ["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.0405117271, "max_line_length": 161, "alphanum_fraction": 0.5003643294, "num_tokens": 5616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6422513597769139}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// kernel::example::mono_bw_kernel_rp.cpp                                    //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n/////////////////////////////////////////////////////////////////////////////// \n#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <boost/range.hpp>\n#include <boost/foreach.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/math/special_functions/fpclassify.hpp> //needed?\n#include <boost/math/tools/precision.hpp>\n\n#include <boost/statistics/detail/kernel/kernels/scalar/gaussian.hpp>\n#include <boost/statistics/detail/kernel/kernels/multivariate/mono_bw.hpp>\n#include <boost/statistics/detail/kernel/estimation/rp_visitor.hpp>\n#include <boost/statistics/detail/kernel/estimation/estimator.hpp>\n#include <libs/statistics/detail/kernel/example/scalar_rp.h>\n\nvoid example_mv_mono_bw_rp(std::ostream& out){\n    out << \"-> example_mono_bw_kernel_rp : \";\n\n\n    // This example shows how to compute a Rosenblatt-Parzen estimate of the \n    // density, p(x). The type used for each data-unit, x, is a vector of \n    // doubles, and the kernel uses the same bandwidth throughout all \n    // coordinates\n\n    using namespace boost;\n    namespace kernel = boost::statistics::detail::kernel;\n    \n    // Types\n    typedef double                                          val_;\n    typedef std::vector<val_>                               vec_;\n    typedef vec_                                            x_;\n    typedef std::vector<x_>                                 dataset_;\n    typedef mt19937                                         urng_;\n    typedef normal_distribution<val_>                       norm_;\n    typedef variate_generator<urng_&,norm_>                 gen_;\n    typedef kernel::scalar::gaussian_kernel<val_>                  gauss_k_;\n\n    const unsigned dim = 2;\n    typedef kernel::multivariate::mono_bw_kernel<gauss_k_,dim> mono_bw_kernel_k_;\n    // Use of a const reference is not necessary but probably improves speed\n    typedef kernel::rp_visitor<mono_bw_kernel_k_,const x_&>  rp_visitor_;\n    \n    // Constants\n    const val_ bandwidth = 0.5;\n    const val_ eps = math::tools::epsilon<val_>();\n    const unsigned n = 10;\n    \n    // Generate n samples, each drawn from prod{N(0,1):i=1,...,dim}\n    dataset_ dataset; dataset.reserve(n);\n    vec_ vec_rp; vec_rp.reserve(n);\n    urng_ urng;\n    norm_ norm;\n    gen_ gen(urng,norm);\n    for(unsigned i = 0; i<n; i++){\n        vec_ tmp(dim);\n        std::generate_n(\n            boost::begin(tmp),\n            dim,\n            gen\n        );\n        dataset.push_back( tmp );\n    }\n\n    // Density estimate for each x in dataset\n    BOOST_FOREACH(const x_& x,dataset){\n        val_ rp = std::for_each(\n            boost::begin(dataset),\n            boost::end(dataset),\n            rp_visitor_(bandwidth,x)\n        ).estimate();\n        vec_rp.push_back(rp);\n    } \n    typedef sub_range<dataset_> sub_;\n    typedef kernel::estimator<\n        sub_,\n        kernel::rp_visitor,\n        mono_bw_kernel_k_\n    > estimator_;\n    estimator_ estimator(bandwidth); \n    estimator.train(sub_(dataset));\n    vec_ vec_rp2; vec_rp2.reserve(n);\n\n    // Same as previous but calls estimator instead of for_each\n    for(unsigned i = 0; i<n; i++){\n        x_ x = dataset[i];\n        val_ rp = vec_rp[i];\n        val_ rp2 = estimator.predict(x);\n        BOOST_ASSERT(fabs(rp-rp2)<eps);\n    } \n    out << \"<-\" << std::endl;\n}\n", "meta": {"hexsha": "868c76ac40712c87864bd67a742575e707fb677c", "size": 3877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/libs/statistics/detail/kernel/example/mv_mono_bw_rp.cpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/libs/statistics/detail/kernel/example/mv_mono_bw_rp.cpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/libs/statistics/detail/kernel/example/mv_mono_bw_rp.cpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3861386139, "max_line_length": 81, "alphanum_fraction": 0.5733814805, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.6422327563641279}}
{"text": "#include \"Eigen/Dense\"\n#include <Eigen/Eigenvalues>\n#include <cmath>\n#include <vector>\n#include <cstdio>\n#include <fstream>\n#include <iostream>\n#include <string>\n\ntypedef Eigen::Matrix< double , Eigen::Dynamic , Eigen::Dynamic > MatrixXd;\n\nvoid load_int_scalar(int &in, std::string filename) {\n  std::ifstream input_file(filename);\n  input_file >> in;\n}\n\nvoid load_double_scalar(double &in, std::string filename) {\n  std::ifstream input_file(filename);\n  input_file >> in;\n}\n\nvoid load_double(std::vector<double> &in, std::string filename) {\n  std::ifstream input_file(filename);\n  double temp_val;\n  std::string line;\n  while (std::getline(input_file, line)) {\n    std::istringstream ss(line);\n    while (ss >> temp_val) {\n      in.push_back(temp_val);\n    }\n  }\n}\n\nsize_t idx2(size_t &i, size_t &j) {\n  if (i >= j) {\n    return i * (i + 1) / 2 + j;\n  } else {\n    return j * (j + 1) / 2 + i;\n  }\n}\n\nsize_t idx4(size_t &i, size_t &j, size_t &k, size_t &l) {\n  size_t temp_ij = idx2(i, j);\n  size_t temp_kl = idx2(k, l);\n  return idx2(temp_ij, temp_kl);\n}\n\nint main(int argc, char const *argv[]) {\n  int iteration_max;\n  int num_elec_alpha;\n  int num_elec_beta;\n  int num_ao;\n\n  load_int_scalar(num_elec_alpha, \"../../data/num_elec_alpha.txt\");\n  load_int_scalar(num_elec_beta, \"../../data/num_elec_beta.txt\");\n  load_int_scalar(iteration_max, \"../../data/iteration_max.txt\");\n  load_int_scalar(num_ao, \"../../data/num_ao.txt\");\n\n  std::vector<double> S_vec;\n  load_double(S_vec, \"../../data/S.txt\");\n  Eigen::Map<MatrixXd> S(S_vec.data(), num_ao, num_ao);\n\n  std::vector<double> T_vec;\n  load_double(T_vec, \"../../data/T.txt\");\n  Eigen::Map<MatrixXd> T(T_vec.data(), num_ao, num_ao);\n\n  std::vector<double> V_vec;\n  load_double(V_vec, \"../../data/V.txt\");\n  Eigen::Map<MatrixXd> V(V_vec.data(), num_ao, num_ao);\n\n  std::vector<double> eri_vec;\n  load_double(eri_vec, \"../../data/eri.txt\");\n  Eigen::Map<MatrixXd> eri(eri_vec.data(),45150,1);\n\n  double convergence_DM;\n  load_double_scalar(convergence_DM, \"../../data/convergence_DM.txt\");\n  double convergence_E;\n  load_double_scalar(convergence_DM, \"../../data/convergence_E.txt\");\n  double E_nuc;\n  load_double_scalar(E_nuc, \"../../data/E_nuc.txt\");\n  \n  MatrixXd D = MatrixXd::Zero(num_ao,num_ao);\n  MatrixXd D_last = MatrixXd::Zero(num_ao,num_ao);\n  // loop variables\n  int iteration_num = 0;\n  double E_total = 0.0;\n  double E_elec = 0.0;\n  double E_elec_last = 0.0;\n  double iteration_E_diff = 0.0;\n  double iteration_rmsc_dm = 0.0;\n  bool converged = false;\n  bool exceeded_iterations = false;\n  Eigen::SelfAdjointEigenSolver<MatrixXd> eigen_solver(num_ao);\n  eigen_solver.compute(S);\n  auto s = eigen_solver.eigenvalues().transpose();\n  auto L = eigen_solver.eigenvectors();\n  MatrixXd X = MatrixXd::Zero(num_ao,num_ao);\n  for (size_t i = 0; i < s.size(); i++) {\n    X(i, i) = 1.0 / std::sqrt(s(i));\n  }\n  X = L*X*L.transpose();\n  auto H = T + V;\n  MatrixXd G = MatrixXd::Zero(num_ao,num_ao);\n  MatrixXd F = MatrixXd::Zero(num_ao,num_ao);\n  MatrixXd F_prime = MatrixXd::Zero(num_ao,num_ao);\n  MatrixXd C = MatrixXd::Zero(num_ao,num_ao);\n  while (!converged && !exceeded_iterations) {\n    E_elec_last = E_elec;\n    D_last = D;\n\n    iteration_num++;\n    // form G matrix\n    MatrixXd G = MatrixXd::Zero(num_ao,num_ao);\n    for (size_t i = 0; i < num_ao; i++) {\n      for (size_t j = 0; j < num_ao; j++) {\n        for (size_t k = 0; k < num_ao; k++) {\n          for (size_t l = 0; l < num_ao; l++) {\n            G(i, j) += D(k, l) * ((2.0 * (eri(idx4(i, j, k, l)))) - (eri(idx4(i, k, j, l))));\n          }\n        }\n      }\n    }\n\n    F = H + G;\n    F_prime = X*F*X;\n    \n    eigen_solver.compute(F_prime);\n    auto E_orbitals = eigen_solver.eigenvalues().transpose();\n    auto C_prime = eigen_solver.eigenvectors();\n\n    C = X*C_prime;\n    D.setZero();\n    \n    for (size_t i = 0; i < num_ao; i++) {\n      for (size_t j = 0; j < num_ao; j++) {\n        for (size_t k = 0; k < num_elec_alpha; k++) {\n          D(i, j) += C(i, k) * C(j, k);\n        }\n      }\n    }\n    E_elec = D.cwiseProduct(H + F).sum();\n    iteration_E_diff = std::abs(E_elec - E_elec_last);\n    iteration_rmsc_dm = std::sqrt((D-D_last).cwiseProduct(D-D_last).sum());\n    if (iteration_E_diff < convergence_E &&\n        iteration_rmsc_dm < convergence_DM) {\n      converged = true;\n    }\n    if (iteration_num == iteration_max) {\n      exceeded_iterations = true;\n    }\n  }\n  E_total = E_elec + E_nuc;\n  printf(\"%20.15f\\n\", E_total);\n  return 0;\n}\n", "meta": {"hexsha": "d14f7afb71643538f8db457603cf51c87727cc90", "size": 4472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hf_rosetta/c++_eigen/hf.cpp", "max_stars_repo_name": "shivupa/hf_rosetta", "max_stars_repo_head_hexsha": "19a4f497fa097bc53aea0c7f39582af5888018b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-18T14:01:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-03T12:30:17.000Z", "max_issues_repo_path": "hf_rosetta/c++_eigen/hf.cpp", "max_issues_repo_name": "shivupa/hf_rosetta", "max_issues_repo_head_hexsha": "19a4f497fa097bc53aea0c7f39582af5888018b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hf_rosetta/c++_eigen/hf.cpp", "max_forks_repo_name": "shivupa/hf_rosetta", "max_forks_repo_head_hexsha": "19a4f497fa097bc53aea0c7f39582af5888018b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T14:30:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-18T14:30:45.000Z", "avg_line_length": 28.6666666667, "max_line_length": 93, "alphanum_fraction": 0.626118068, "num_tokens": 1399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6421987303236864}}
{"text": "#include \"Lshape.hpp\"\n#include \"convergence.hpp\"\n#include \"fem_solve.hpp\"\n#include \"stiffness_matrix.hpp\"\n#include \"writer.hpp\"\n#include <Eigen/Core>\n#include <sstream>\n#include <tuple>\n\n// constant sigma\ndouble sigma(double x, double y) {\n\tstd::ignore = x;\n\tstd::ignore = y;\n\treturn 1.0;\n}\n\n// Data for square\ndouble f_square(double x, double y) {\n\treturn 2 * M_PI * M_PI * sin(M_PI * x) * sin(M_PI * y);\n}\n\ndouble g_square(double x, double y) {\n\tstd::ignore = x;\n\tstd::ignore = y;\n\treturn 0;\n}\n\ndouble uex_square(double x, double y) {\n\treturn sin(M_PI * x) * sin(M_PI * y);\n}\n\nEigen::Vector2d uex_grad_square(double x, double y) {\n\tEigen::Vector2d grad;\n\tgrad << M_PI * cos(M_PI * x) * sin(M_PI * y),\n\t    M_PI * sin(M_PI * x) * cos(M_PI * y);\n\treturn grad;\n}\n\nEigen::Vector2d u_square_ex_grad(double x, double y) {\n\tEigen::Vector2d gradient;\n\tgradient << M_PI * cos(M_PI * x) * sin(M_PI * y), M_PI * sin(M_PI * x) * cos(M_PI * y);\n\treturn gradient;\n}\n\nint main(int, char **) {\n\ttry {\n\t\tsolveL(0.5);\n\n\t\tstd::cout << \"Convergence Analysis\" << std::endl;\n\t\tconvergenceAnalysis(\"square\", 7, f_square, sigma, g_square, 0, uex_square, uex_grad_square);\n\t\tconvergenceAnalysis(\"Lshape\", 7, f_lshape, sigma, g_lshape, 0, g_lshape, g_grad_lshape);\n\t} catch (std::runtime_error &e) {\n\t\tstd::cerr << \"An error occurred. Error message: \" << std::endl;\n\t\tstd::cerr << \"    \\\"\" << e.what() << \"\\\"\" << std::endl;\n\t\treturn EXIT_FAILURE;\n\t} catch (...) {\n\t\tstd::cerr << \"An unknown error occurred.\" << std::endl;\n\t\tthrow;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "e721e312031a0c4822d35a636b3f3510832d450b", "size": 1535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series2/2d-linFEM/fem2d.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/2d-linFEM/fem2d.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/2d-linFEM/fem2d.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": 24.3650793651, "max_line_length": 94, "alphanum_fraction": 0.6436482085, "num_tokens": 478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6421531318594227}}
{"text": "#include <boost/numeric/interval.hpp>\n\n// Exception codes\n#define EXC_NONE                          0\n#define EXC_UNDEFINED_OPERATION          -1\n#define EXC_POSSIBLY_UNDEFINED_OPERATION -2\n#define EXC_INTERVAL_PART_OF_NAI         -3\n#define EXC_INVALID_OPERAND              -4\n\nusing namespace boost::numeric;\nusing namespace interval_lib;\n\ntypedef interval<double,\n                 policies<save_state<rounded_transc_std<double> >,\n                          checking_base<double> > > I;\n\nextern \"C\" {\n\nvoid test_boost_setup() {\n}\n\nint test_boost_neg(I* x, I* r) {\n    *r = - *x;\n    return EXC_NONE;\n}\n\nint test_boost_add(I* x, I* y, I* r) {\n    *r = *x + *y;\n    return EXC_NONE;\n}\n\nint test_boost_sub(I* x, I* y, I* r) {\n    *r = *x - *y;\n    return EXC_NONE;\n}\n\nint test_boost_mul(I* x, I* y, I* r) {\n    *r = *x * *y;\n    return EXC_NONE;\n}\n\nint test_boost_div(I* x, I* y, I* r) {\n    *r = *x / *y;\n    return EXC_NONE;\n}\n\nint test_boost_recip(I* x, I* r) {\n    *r = multiplicative_inverse( *x );\n    return EXC_NONE;\n}\n\nint test_boost_sqrt(I* x, I* r) {\n    *r = sqrt( *x ) ;\n    return EXC_NONE;\n}\n\nint test_boost_hypot(I* x, I *y, I* r) {\n    *r = sqrt( square( *x ) + square( *y ));\n    return EXC_NONE;\n}\n\nint test_boost_fma(I* x, I *y, I *z, I* r) {\n    *r = *x * *y + *z;\n    return EXC_NONE;\n}\n\nint test_boost_sqr(I* x, I* r) {\n    *r = square( *x );\n    return EXC_NONE;\n}\n\nint test_boost_pown(I* x, int *p, I* r) {\n    *r = pow( *x, *p );\n    return EXC_NONE;\n}\n\n//int test_boost_pow(I* x, int *y, I* r) {\n//    return EXC_NONE;\n//}\n\nint test_boost_exp(I* x, I* r) {\n    *r = exp( *x );\n    return EXC_NONE;\n}\n\n//int test_boost_exp2(I* x, I* r) {\n//    return EXC_NONE;\n//}\n\n//int test_boost_exp10(I* x, I* r) {\n//    return EXC_NONE;\n//}\n\nint test_boost_log(I* x, I* r) {\n    *r = log( *x );\n    return EXC_NONE;\n}\n\n//int test_boost_log2(I* x, I* r) {\n//    return EXC_NONE;\n//}\n\n//int test_boost_log10(I* x, I* r) {\n//}\n\nint test_boost_sin(I* x, I* r) {\n    *r = sin( *x );\n    return EXC_NONE;\n}\n\nint test_boost_cos(I* x, I* r) {\n    *r = cos( *x );\n    return EXC_NONE;\n}\n\nint test_boost_tan(I* x, I* r) {\n    *r = tan( *x );\n    return EXC_NONE;\n}\n\nint test_boost_asin(I* x, I* r) {\n    *r = asin( *x );\n    return EXC_NONE;\n}\n\nint test_boost_acos(I* x, I* r) {\n    *r = acos( *x );\n    return EXC_NONE;\n}\n\nint test_boost_atan(I* x, I* r) {\n    *r = atan( *x );\n    return EXC_NONE;\n}\n\n//int test_boost_atan2(I* x, I *y, I* r) {\n//    return EXC_NONE;\n//}\n\nint test_boost_sinh(I* x, I* r) {\n    *r = sinh( *x );\n    return EXC_NONE;\n}\n\nint test_boost_cosh(I* x, I* r) {\n    *r = cosh( *x );\n    return EXC_NONE;\n}\n\nint test_boost_tanh(I* x, I* r) {\n    *r = tanh( *x );\n    return EXC_NONE;\n}\n\nint test_boost_asinh(I* x, I* r) {\n    *r = asinh( *x );\n    return EXC_NONE;\n}\n\nint test_boost_acosh(I* x, I* r) {\n    *r = acosh( *x );\n    return EXC_NONE;\n}\n\nint test_boost_atanh(I* x, I* r) {\n    *r = atanh( *x );\n    return EXC_NONE;\n}\n\n//int test_boost_sign(I* x, I* r) {\n//    return EXC_NONE;\n//}\n\n//int test_boost_ceil(I* x, I* r) {\n//    return EXC_NONE;\n//}\n\n//int test_boost_floor(I* x, I* r) {\n//    return EXC_NONE;\n//}\n\n//int test_boost_round(I* x, I* r) {\n//    return EXC_NONE;\n//}\n\n//int test_boost_trunc(I* x, I* r) {\n//    return EXC_NONE;\n//}\n\nint test_boost_abs(I* x, I* r) {\n    *r = abs( *x );\n    return EXC_NONE;\n}\n\nint test_boost_min(I* x, I *y, I* r) {\n    *r = min( *x, *y );\n    return EXC_NONE;\n}\n\nint test_boost_max(I* x, I *y, I* r) {\n    *r = max( *x, *y );\n    return EXC_NONE;\n}\n\nint test_boost_intersection(I* x, I *y, I* r) {\n    *r = intersect( *x, *y );\n    return EXC_NONE;\n}\n\nint test_boost_convexHull(I* x, I *y, I* r) {\n    *r = hull( *x, *y );\n    return EXC_NONE;\n}\n\n}\n", "meta": {"hexsha": "efd687f8f33b8e72a2ef34830e453af9ef6d8c94", "size": 3731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "p1788-launcher-java/target/classes/net/java/jinterval/p1788/testBoost.cpp", "max_stars_repo_name": "DmitryGerasimenko/jinterval", "max_stars_repo_head_hexsha": "f44a489b59812c062cd4c4610f4f94a99ab06fa2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-08-26T14:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T12:23:49.000Z", "max_issues_repo_path": "p1788-launcher-java/target/classes/net/java/jinterval/p1788/testBoost.cpp", "max_issues_repo_name": "DmitryGerasimenko/jinterval", "max_issues_repo_head_hexsha": "f44a489b59812c062cd4c4610f4f94a99ab06fa2", "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": "p1788-launcher-java/target/classes/net/java/jinterval/p1788/testBoost.cpp", "max_forks_repo_name": "DmitryGerasimenko/jinterval", "max_forks_repo_head_hexsha": "f44a489b59812c062cd4c4610f4f94a99ab06fa2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-10-29T09:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-07T13:20:51.000Z", "avg_line_length": 17.2731481481, "max_line_length": 66, "alphanum_fraction": 0.5491825248, "num_tokens": 1342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162772, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6421531262678879}}
{"text": "//  Copyright John Maddock 2006\r\n//  Copyright Paul A. Bristow 2007\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <pch.hpp>\r\n\r\n#ifdef _MSC_VER\r\n#  pragma warning(disable : 4267) // conversion from 'size_t' to 'const unsigned int', possible loss of data\r\n#  pragma warning(disable : 4180) // qualifier applied to function type has no meaning; ignored\r\n#  pragma warning(disable : 4224) // nonstandard extension used : formal parameter 'function_ptr' was previously defined as a type\r\n#  pragma warning(disable : 4100) // unreferenced formal parameter (in ublas/functional)\r\n#endif\r\n\r\n#include <boost/math/tools/remez.hpp>\r\n#include <boost/test/test_exec_monitor.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/math/special_functions/expm1.hpp>\r\n\r\n\r\nvoid test_polynomial()\r\n{\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n   double (*f)(double) = boost::math::expm1<double>;\r\n#else\r\n   double (*f)(double) = boost::math::expm1;\r\n#endif\r\n   std::cout << \"Testing expm1 approximation, pinned to origin, abolute error, 6 term polynomial\\n\";\r\n   boost::math::tools::remez_minimax<double> approx1(f, 6, 0, -1, 1, true, false);\r\n   std::cout << \"Interpolation Error: \" << approx1.max_error() << std::endl;\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx1.iterate();\r\n      std::cout << approx1.error_term() << \" \" << approx1.max_error() << \" \" << approx1.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n   std::cout << \"Testing expm1 approximation, pinned to origin, relative error, 6 term polynomial\\n\";\r\n   boost::math::tools::remez_minimax<double> approx2(f, 6, 0, -1, 1, true, true);\r\n   std::cout << \"Interpolation Error: \" << approx1.max_error() << std::endl;\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx2.iterate();\r\n      std::cout << approx2.error_term() << \" \" << approx2.max_error() << \" \" << approx2.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n\r\n   f = std::exp;\r\n   std::cout << \"Testing exp approximation, not pinned to origin, abolute error, 6 term polynomial\\n\";\r\n   boost::math::tools::remez_minimax<double> approx3(f, 6, 0, -1, 1, false, false);\r\n   std::cout << \"Interpolation Error: \" << approx1.max_error() << std::endl;\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx3.iterate();\r\n      std::cout << approx3.error_term() << \" \" << approx3.max_error() << \" \" << approx3.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n   std::cout << \"Testing exp approximation, not pinned to origin, relative error, 6 term polynomial\\n\";\r\n   boost::math::tools::remez_minimax<double> approx4(f, 6, 0, -1, 1, false, true);\r\n   std::cout << \"Interpolation Error: \" << approx1.max_error() << std::endl;\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx4.iterate();\r\n      std::cout << approx4.error_term() << \" \" << approx4.max_error() << \" \" << approx4.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n\r\n   f = std::cos;\r\n   std::cout << \"Testing cos approximation, not pinned to origin, abolute error, 5 term polynomial\\n\";\r\n   boost::math::tools::remez_minimax<double> approx5(f, 5, 0, -1, 1, false, false);\r\n   std::cout << \"Interpolation Error: \" << approx1.max_error() << std::endl;\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx5.iterate();\r\n      std::cout << approx5.error_term() << \" \" << approx5.max_error() << \" \" << approx5.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n   std::cout << \"Testing cos approximation, not pinned to origin, relative error, 5 term polynomial\\n\";\r\n   boost::math::tools::remez_minimax<double> approx6(f, 5, 0, -1, 1, false, true);\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx6.iterate();\r\n      std::cout << approx6.error_term() << \" \" << approx6.max_error() << \" \" << approx6.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n\r\n   f = std::sin;\r\n   std::cout << \"Testing sin approximation, pinned to origin, abolute error, 4 term polynomial\\n\";\r\n   boost::math::tools::remez_minimax<double> approx7(f, 4, 0, 0, 1, true, false);\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx7.iterate();\r\n      std::cout << approx7.error_term() << \" \" << approx7.max_error() << \" \" << approx7.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n   std::cout << \"Testing sin approximation, pinned to origin, relative error, 4 term polynomial\\n\";\r\n   boost::math::tools::remez_minimax<double> approx8(f, 4, 0, 0, 1, true, true);\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx8.iterate();\r\n      std::cout << approx8.error_term() << \" \" << approx8.max_error() << \" \" << approx8.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n}\r\n\r\nvoid test_rational()\r\n{\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n   double (*f)(double) = boost::math::expm1<double>;\r\n#else\r\n   double (*f)(double) = boost::math::expm1;\r\n#endif\r\n   std::cout << \"Testing expm1 approximation, pinned to origin, abolute error, 3+3 term rational\\n\";\r\n   boost::math::tools::remez_minimax<double> approx1(f, 3, 3, -1, 1, true, false);\r\n   std::cout << \"Interpolation Error: \" << approx1.max_error() << std::endl;\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx1.iterate();\r\n      std::cout << approx1.error_term() << \" \" << approx1.max_error() << \" \" << approx1.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n#if 0\r\n   //\r\n   // This one causes UBLAS to fail on some systems, so disabled for now.\r\n   //\r\n   std::cout << \"Testing expm1 approximation, pinned to origin, relative error, 3+3 term rational\\n\";\r\n   boost::math::tools::remez_minimax<double> approx2(f, 3, 3, -1, 1, true, true);\r\n   std::cout << \"Interpolation Error: \" << approx1.max_error() << std::endl;\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx2.iterate();\r\n      std::cout << approx2.error_term() << \" \" << approx2.max_error() << \" \" << approx2.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n#endif\r\n   f = std::exp;\r\n   std::cout << \"Testing exp approximation, not pinned to origin, abolute error, 3+3 term rational\\n\";\r\n   boost::math::tools::remez_minimax<double> approx3(f, 3, 3, -1, 1, false, false);\r\n   std::cout << \"Interpolation Error: \" << approx1.max_error() << std::endl;\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx3.iterate();\r\n      std::cout << approx3.error_term() << \" \" << approx3.max_error() << \" \" << approx3.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n   std::cout << \"Testing exp approximation, not pinned to origin, relative error, 3+3 term rational\\n\";\r\n   boost::math::tools::remez_minimax<double> approx4(f, 3, 3, -1, 1, false, true);\r\n   std::cout << \"Interpolation Error: \" << approx1.max_error() << std::endl;\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx4.iterate();\r\n      std::cout << approx4.error_term() << \" \" << approx4.max_error() << \" \" << approx4.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n\r\n   f = std::cos;\r\n   std::cout << \"Testing cos approximation, not pinned to origin, abolute error, 2+2 term rational\\n\";\r\n   boost::math::tools::remez_minimax<double> approx5(f, 2, 2, 0, 1, false, false);\r\n   std::cout << \"Interpolation Error: \" << approx1.max_error() << std::endl;\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx5.iterate();\r\n      std::cout << approx5.error_term() << \" \" << approx5.max_error() << \" \" << approx5.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n   std::cout << \"Testing cos approximation, not pinned to origin, relative error, 2+2 term rational\\n\";\r\n   boost::math::tools::remez_minimax<double> approx6(f, 2, 2, 0, 1, false, true);\r\n   std::cout << \"Interpolation Error: \" << approx1.max_error() << std::endl;\r\n   for(unsigned i = 0; i < 7; ++i)\r\n   {\r\n      approx6.iterate();\r\n      std::cout << approx6.error_term() << \" \" << approx6.max_error() << \" \" << approx6.max_change() << std::endl;\r\n   }\r\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n   test_polynomial();\r\n   test_rational();\r\n   return 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "4fc82c95776cfb5ca0f91c0ae127ed12949fa75e", "size": 8599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_remez.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/math/test/test_remez.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/math/test/test_remez.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 46.4810810811, "max_line_length": 131, "alphanum_fraction": 0.5762297942, "num_tokens": 2537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6421531167760928}}
{"text": "/* integrate.hpp header file\r\n *\r\n * Copyright Jens Maurer 2000\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation,\r\n *\r\n * Jens Maurer makes no representations about the suitability of this\r\n * software for any purpose. It is provided \"as is\" without express or\r\n * implied warranty.\r\n *\r\n * $Id: integrate.hpp,v 1.4 2001/11/19 22:13:04 jmaurer Exp $\r\n *\r\n * Revision history\r\n *   01 April 2001: Modified to use new <boost/limits.hpp> header. (JMaddock)\r\n */\r\n\r\n#ifndef INTEGRATE_HPP\r\n#define INTEGRATE_HPP\r\n\r\n#include <boost/limits.hpp>\r\n\r\ntemplate<class UnaryFunction>\r\ninline typename UnaryFunction::result_type \r\ntrapezoid(UnaryFunction f, typename UnaryFunction::argument_type a,\r\n          typename UnaryFunction::argument_type b, int n)\r\n{\r\n  typename UnaryFunction::result_type tmp = 0;\r\n  for(int i = 1; i <= n-1; ++i)\r\n    tmp += f(a+(b-a)/n*i);\r\n  return (b-a)/2/n * (f(a) + f(b) + 2*tmp);\r\n}\r\n\r\ntemplate<class UnaryFunction>\r\ninline typename UnaryFunction::result_type \r\nsimpson(UnaryFunction f, typename UnaryFunction::argument_type a,\r\n        typename UnaryFunction::argument_type b, int n)\r\n{\r\n  typename UnaryFunction::result_type tmp1 = 0;\r\n  for(int i = 1; i <= n-1; ++i)\r\n    tmp1 += f(a+(b-a)/n*i);\r\n  typename UnaryFunction::result_type tmp2 = 0;\r\n  for(int i = 1; i <= n ; ++i)\r\n    tmp2 += f(a+(b-a)/2/n*(2*i-1));\r\n\r\n  return (b-a)/6/n * (f(a) + f(b) + 2*tmp1 + 4*tmp2);\r\n}\r\n\r\n// compute b so that f(b) = y; assume f is monotone increasing\r\ntemplate<class UnaryFunction>\r\ninline typename UnaryFunction::argument_type\r\ninvert_monotone_inc(UnaryFunction f, typename UnaryFunction::result_type y,\r\n                    typename UnaryFunction::argument_type lower = -1,\r\n                    typename UnaryFunction::argument_type upper = 1)\r\n{\r\n  while(upper-lower > 1e-6) {\r\n    double middle = (upper+lower)/2;\r\n    if(f(middle) > y)\r\n      upper = middle;\r\n    else\r\n      lower = middle;\r\n  }\r\n  return (upper+lower)/2;\r\n}\r\n\r\n// compute b so that  I(f(x), a, b) == y\r\ntemplate<class UnaryFunction>\r\ninline typename UnaryFunction::argument_type\r\nquantil(UnaryFunction f, typename UnaryFunction::argument_type a,\r\n        typename UnaryFunction::result_type y,\r\n        typename UnaryFunction::argument_type step)\r\n{\r\n  typedef typename UnaryFunction::result_type result_type;\r\n  if(y >= 1.0)\r\n    return std::numeric_limits<result_type>::infinity();\r\n  typename UnaryFunction::argument_type b = a;\r\n  for(result_type result = 0; result < y; b += step)\r\n    result += step*f(b);\r\n  return b;\r\n}\r\n\r\n\r\n#endif /* INTEGRATE_HPP */\r\n", "meta": {"hexsha": "006d5cf51eb4d765f99b18913550e51f0875b37c", "size": 2774, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/random/integrate.hpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/random/integrate.hpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/random/integrate.hpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6352941176, "max_line_length": 78, "alphanum_fraction": 0.6708723864, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6420822382754068}}
{"text": "/*\n * MathUtils.hpp\n *\n *  Created on: August 22, 2020\n *      Author: Quincy Jones\n *\n * Copyright (c) <2020> <Quincy Jones - quincy@implementedrobotics.com/>\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the Software\n * is furnished to do so, subject to the following conditions:\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#ifndef NOMAD_COMMON_MATHUTILS_H\n#define NOMAD_COMMON_MATHUTILS_H\n\n// C System Files\n#include <math.h>\n\n// C++ System Files\n\n// Third Party Includes\n#include <Eigen/Dense>\n// Project Include Files\n\nnamespace Common::Math\n{\n    template <typename T>\n    int sgn(T val)\n    {\n        return (T(0) < val) - (val < T(0));\n    }\n\n    // https://en.wikipedia.org/wiki/Skew-symmetric_matrix#Cross_product\n    Eigen::Matrix3d SkewSymmetricCrossProduct(const Eigen::Vector3d& a);\n\n    void rpyToR(Eigen::Matrix3d &R, double *rpy_in);\n\n        // Convert Rotation -> Euler RPY\n    Eigen::Vector3d RotationMatrixToEuler(const Eigen::Matrix3d& R);\n\n    // Convert Euler RPY -> Rotation Matrix.  TODO: Add support for rotation order\n    Eigen::Matrix3d EulerToRotationMatrix(const Eigen::Vector3d& euler);\n    \n    // Convert Euler RPY -> Quaternion.  TODO: Add support for rotation order\n    Eigen::Quaterniond EulerToQuaternion(const Eigen::Vector3d& euler);\n\n    // Convert Euler RPY -> Quaternion.  TODO: Add support for rotation order\n    Eigen::Vector3d QuaterionToEuler(const Eigen::Quaterniond& q);\n\n    // Compute Orientation Error between 2 Euler orientations\n    Eigen::Vector3d ComputeOrientationError(const Eigen::Vector3d& theta_1, const Eigen::Vector3d& theta_2);\n    \n    Eigen::Matrix3d RotationX(double rad);\n    Eigen::Matrix3d RotationY(double rad);\n    Eigen::Matrix3d RotationZ(double rad);\n\n    namespace EigenHelpers\n    {\n\n        // Typedefs\n        typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMatrixXd;\n        // TODO: Make this more generic\n        // Block Matrix Class\n        class BlockMatrixXd\n        {\n        public:\n            BlockMatrixXd() {}\n            BlockMatrixXd(const unsigned int Rows, const unsigned int Cols, const unsigned int BlockHeight, const unsigned int BlockWidth, const int init_val);\n            BlockMatrixXd(const unsigned int Rows, const unsigned int Cols, const unsigned int BlockHeight, const unsigned int BlockWidth, Eigen::MatrixXd &matrix);\n            BlockMatrixXd(const unsigned int Rows, const unsigned int Cols, const unsigned int BlockHeight, const unsigned int BlockWidth);\n\n            friend std::ostream &operator<<(std::ostream &os, BlockMatrixXd const &bm) { return os << bm.Matrix_; }\n            // Operator Overload:\n            void operator()(const unsigned int Row, const unsigned int Col, const Eigen::MatrixXd &block_val);\n\n            // TODO: Fix Templated Hack so we can set this directly... i.e. matrix(1,1) = block\n            Eigen::Block<Eigen::MatrixXd, -1, -1, false> operator()(const unsigned int Row, const unsigned int Col);\n\n            // Cast Overload\n            operator Eigen::MatrixXd() { return Matrix_; }\n\n            Eigen::MatrixXd MatrixXd() const { return Matrix_; }\n            // Set Block Matrix Value\n            // TODO: Should be Matrix(1,1) = value\n            void SetBlock(const unsigned int Row, const unsigned int Col, const Eigen::MatrixXd &block_val);\n\n            // Fill Diagonal with a block\n            void FillDiagonal(const Eigen::MatrixXd &block_val, const int k = 0);\n\n        protected:\n            unsigned int Rows_;\n            unsigned int Cols_;\n            unsigned int BlockWidth_;\n            unsigned int BlockHeight_;\n\n            Eigen::MatrixXd Matrix_;\n\n        };\n    } // namespace EigenHelpers\n    \n    \n} // namespace Common::Math\n#endif // NOMAD_COMMON_STATISTICS_H", "meta": {"hexsha": "056e570301c04b5423de6988c2a8050e46bb8f33", "size": 4673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Software/Common/include/Common/Math/MathUtils.hpp", "max_stars_repo_name": "implementedrobotics/Nomad", "max_stars_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T18:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T01:22:55.000Z", "max_issues_repo_path": "Software/Common/include/Common/Math/MathUtils.hpp", "max_issues_repo_name": "implementedrobotics/Nomad", "max_issues_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2019-05-29T12:57:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-29T02:26:06.000Z", "max_forks_repo_path": "Software/Common/include/Common/Math/MathUtils.hpp", "max_forks_repo_name": "implementedrobotics/Nomad", "max_forks_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T03:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T05:34:16.000Z", "avg_line_length": 40.9912280702, "max_line_length": 164, "alphanum_fraction": 0.6873528782, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6420822360421786}}
{"text": "///\n/// File:   eigen.cpp\n/// Author: Open Risk\n///\n\n#include <iostream>\n#include <sstream>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, const char **argv) {\n\n    //\n    // Get eigen library version\n    //\n\n    std::stringstream ss;\n    ss.str(\"\");\n    ss << EIGEN_MAJOR_VERSION;\n    ss << \".\";\n    ss << EIGEN_MINOR_VERSION;\n    std::string eigen_version = ss.str();\n    std::cout << eigen_version << std::endl;\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    cout << \"The least-squares solution is:\\n\"\n         << A.bdcSvd(ComputeThinU | ComputeThinV).solve(b) << endl;\n\n    return 0;\n}", "meta": {"hexsha": "a73e358baaa10f25ce2c7abfc385d865f3385260", "size": 780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen.cpp", "max_stars_repo_name": "open-risk/numpymatrix", "max_stars_repo_head_hexsha": "d152f5c10b9260e4bfd35dbbe2b1dafbdfc0cef0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eigen.cpp", "max_issues_repo_name": "open-risk/numpymatrix", "max_issues_repo_head_hexsha": "d152f5c10b9260e4bfd35dbbe2b1dafbdfc0cef0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigen.cpp", "max_forks_repo_name": "open-risk/numpymatrix", "max_forks_repo_head_hexsha": "d152f5c10b9260e4bfd35dbbe2b1dafbdfc0cef0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2857142857, "max_line_length": 67, "alphanum_fraction": 0.5935897436, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6420822296484686}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\nstruct poisson2D_dirichlet\n{\n    poisson2D_dirichlet(int m, int n) : m(m), n(n) {}\n\n    template <typename Vector>\n    Vector operator*(const Vector& v) const\n    {\n\tassert(int(size(v)) == m * n);\n\tVector w(m * n, typename Vector::value_type(0));\n\t\n\tfor (int i= 0; i < m; i++)\n\t    for (int j= 0; j < n; j++) {\n\t\tint k= i * n + j; // offset\n\t\tw[k]= 4 * v[k];\n\t\tif (i > 0) w[k]-= v[k-n];   // upper neighbor\n\t\tif (i < m-1) w[k]-= v[k+n]; // lower neighbor\n\t\tif (j > 0) w[k]-= v[k-1];   // left neighbor\n\t\tif (j < n-1) w[k]-= v[k+1]; // right neighbor\n\t    }\n\treturn w;\n    }\n    int m, n;\n};\n\nnamespace mtl { namespace ashape {\n    template <> struct ashape_aux<poisson2D_dirichlet> \n    {\ttypedef nonscal type;    };\n}}\n\n\nint main()\n{\n    mtl::vampir_trace<9999> tracer;\n  // For a more realistic example set size to 1000 or larger\n  const int size = 10, N = size * size;\n\n  poisson2D_dirichlet A(size, size);\n\n  itl::pc::identity<poisson2D_dirichlet>     P(A);\n\n  mtl::dense_vector<double> x(N, 1.0), b(N);\n\n  b = A * x;\n  x= 0;\n  itl::cyclic_iteration<double> iter(b, 100, 1.e-11, 0.0, 5);\n  cg(A, x, b, P, iter);\n\n  return 0;\n}\n", "meta": {"hexsha": "cab837cce9640ce243c2204744adc451afbdaa66", "size": 1670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/cg_matrix_free_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/itl/test/cg_matrix_free_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/itl/test/cg_matrix_free_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 25.303030303, "max_line_length": 94, "alphanum_fraction": 0.6119760479, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.64196793758182}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/test/minimal.hpp>\n\n#include <boost/numeric/mtl/mtl.hpp>\n \nusing namespace std;  \n\ntemplate <typename T, typename F>\nmtl::maybe<T> inline bisection(T a, T b, const F& f, const T& tau)\n{\n    if (f(a) * f(b) > 0) \n\treturn false;\n    while (b - a > tau) {\n\tT m= (a + b) / 2;\n\t// cout << \"f(m) is \" << f(m) << '\\n';\n\tif (f(m) * f(a) < 0)\n\t    b= m;\n\telse\n\t    a= m;\n    }\n    return (a + b) / 2;\n}\n\n\nclass caterpillar\n{\npublic:\n    caterpillar(double r, double K, double a, double b) : r(r), K(K), a(a), b(b) {}\n    \n    double operator()(double N) const\n    {\n\treturn r * N * (1. - N / K) - a * N * N / (b + N * N);\n    }\nprivate:\n    double r, K, a, b;\n};\n\n\ntemplate <typename Matrix>\nclass ev_bisection\n{\n    typedef typename mtl::Collection<Matrix>::value_type value_type;\npublic:\n    explicit ev_bisection(const Matrix& A) : A(A), D(A), Q(A), R(A)\n    {\n\tassert(num_rows(A) == num_cols(A));\n    }\n\n    value_type operator()(const value_type& lambda)\n    {\n\t// D= A - lamdda * identity\n\tD= -lambda; D+= A;\n \n\treturn lambda; // to make it compile answer is nonsense\n    }\n\nprivate:\n    const Matrix &A;\n    Matrix D, Q, R;\n};\n\n\nvoid inline find_eigenvalue(const ev_bisection<mtl::dense2D<double> >& bis, double a, double b)\n{\n    cout << \"Search eigenvalue in interval [\" << a << \", \" << b << \"]\\n\"; \n    //mtl::maybe<double> lambda= ;\n}\n\nint test_main(int argc, char* argv[])\n{\n#if 0\n    caterpillar population1(1.3, 100, 20, 50);\n    cout << \"Equilibrium of population 1 in interval [0.1, 10] is \" << bisection(0.1, 10.0, population1, 0.0001).value() << '\\n';\n    cout << \"Equilibrium of population 1 in interval [10, 20] is \" << bisection(10.0, 20.0, population1, 0.0001).value() << '\\n';\n    cout << \"Equilibrium of population 1 in interval [20, 100] is \" << bisection(20.0, 100.0, population1, 0.0001).value() << '\\n';\n\n    caterpillar population2(2.0, 80, 25, 10);\n    cout << \"\\nEquilibrium of population 2 in interval [0.1, 10] is \" << bisection(0.1, 10.0, population2, 0.0001).value() << '\\n';\n    cout << \"Equilibrium of population 2 in interval [10, 20] is \" << bisection(10.0, 20.0, population2, 0.0001).value() << '\\n';\n    cout << \"Equilibrium of population 2 in interval [20, 100] is \" << bisection(20.0, 100.0, population2, 0.0001).value() << '\\n';\n#endif    \n\n    mtl::dense2D<double> A(3, 3);\n    A= 0.0; A[0][0]= 1.0; A[1][1]= 2.0; A[2][2]= 3;\n    \n    ev_bisection<mtl::dense2D<double> > bis(A);\n    find_eigenvalue(bis, 0, 1.5);\n\n    return 0;\n}\n", "meta": {"hexsha": "7c5bbd4f663074251fdb293fa2aa7356223cf83a", "size": 2945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/bisection.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/experimental/bisection.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/experimental/bisection.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 28.5922330097, "max_line_length": 131, "alphanum_fraction": 0.6016977929, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6419679191893163}}
{"text": "// system includes -----------------------------------------------\n#include <boost/math/constants/constants.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n#include <tuple>\n// own includes --------------------------------------------------\n#include <base/eigen2hdf.hpp>\n#include <base/init.hpp>\n#include <fft/fft2.hpp>\n#include <ridgelet/ridgelet_cell_array.hpp>\n#include <ridgelet/ridgelet_frame.hpp>\n#include <ridgelet/rt.hpp>\n\n#include <operators/operators.hpp>\n#include <solver/cg.hpp>\n#include <solver/ridgelet_solver.hpp>\n\nusing namespace std;\n\ntypedef RT<> RT_t;\ntypedef RT_t::array_t array_t;\ntypedef RT_t::complex_array_t complex_array_t;\ntypedef RT_t::rt_coeff_t rt_coeff_t;\ntypedef FFTr2c<PlannerR2COD> fft_t;\n\nconst double tol = 1e-9;\nconst int maxit = 400;\ndouble pi = boost::math::constants::pi<double>();\nbool save = false;\n\nvoid dump_frc(const std::vector<rt_coeff_t>& f_rc, const RidgeletFrame& rt, std::string ffname)\n{\n  const char* fname = ffname.c_str();\n  hid_t file = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  for (unsigned int i = 0; i < f_rc.size(); ++i) {\n    stringstream ss;\n    ss << rt.lambdas()[i];\n    string slam = ss.str();\n    eigen2hdf::save(file, slam, f_rc[i]);\n  }\n  H5Fclose(file);\n  cout << \"Written f(lambda, t) to \" << fname << \"\\n\";\n}\n\n// --------------------------------------------------------------------------------\n// solve in Ridgelet domain\ntemplate <typename ARRAY_T>\nstd::tuple<int, double> solve_rt(\n    ARRAY_T& Fh, const RidgeletFrame& rf, const double dt, Eigen::Vector2d& v, bool log)\n{\n  const unsigned int Nx = rf.Nx();  // #cols\n  const unsigned int Ny = rf.Ny();  // #rows\n\n  RT_t rt(rf);\n  typedef RidgeletCellArray<rt_coeff_t> rca_t;\n  rca_t rt_cell_array(rf);\n  auto& rt_coeffs = rt_cell_array.coeffs();\n  rt.rt(rt_coeffs, Fh);\n\n  double vx = v[0];\n  double vy = v[1];\n\n  // since vx, vy = 0, this has no effect\n  double Lx = 1;\n  double Ly = 1;\n\n  // initialize operators\n  AhAOp AhA(vx, vy, Lx, Ly, Nx, Ny, dt);\n  PTransportOp<RT_t> A(rt, AhA, vx, vy);\n\n  RidgeletSolver<rt_coeff_t> rt_solver(rf, vx, vy, dt);\n  // assert(vx == 0);\n  // assert(vy == 0);\n  // have to apply A.T to rhs otherwise!!!\n\n  /////////////\n  // b = A*x //\n  /////////////\n  rca_t x(rf);\n  x.resize(rt_cell_array);\n  rca_t b(rf);\n  b.resize(rt_cell_array);\n  x = rt_cell_array;\n\n  // b = A*x\n  // Note if v=[0,0]: A is the identity operator\n  b = x;\n\n  /* cout << \"RT_SOLVER::tol  : \" << tol << \"\\n\"; */\n  /* cout << \"RT_SOLVER::maxit: \" << maxit << \"\\n\"; */\n  Logger::GetInstance().push_prefix(\"RTCG\");\n  rt_solver.set_log(log);\n  rt_solver.solve(x, A, b, tol, maxit);\n  Logger::GetInstance().clear_prefix();\n\n  if (save) {\n    rt.irt(Fh, x.coeffs());\n    ARRAY_T Fh2 = ftcut(Fh, Ny / 2, Nx / 2);\n    Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> X(Ny / 2, Nx / 2);\n    fft_t fft;\n    fft.ift(X, Fh2);\n    hid_t file = H5Fcreate(\"cg-result.h5\", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n    eigen2hdf::save(file, \"X\", X);\n    H5Fclose(file);\n  }\n\n  return std::make_tuple(rt_solver.iter(), rt_solver.relres());\n\n  /* cout << \"RT CG::RELRES \" << rt_solver.relres() << \"\\n\" */\n  /*      << \"RT CG::ITER \"   << rt_solver.iter() << \"\\n\"; */\n}\n\n// --------------------------------------------------------------------------------\n// solve in Ridgelet domain\ntemplate <typename ARRAY_T>\nstd::tuple<int, double> solve_rtnop(\n    ARRAY_T& Fh, const RidgeletFrame& rf, const double dt, Eigen::Vector2d& v, bool log)\n{\n  const unsigned int Nx = rf.Nx();  // #cols\n  const unsigned int Ny = rf.Ny();  // #rows\n\n  RT_t rt(rf);\n  typedef RidgeletCellArray<rt_coeff_t> rca_t;\n  rca_t rt_cell_array(rf);\n  auto& rt_coeffs = rt_cell_array.coeffs();\n  rt.rt(rt_coeffs, Fh);\n\n  double vx = v[0];\n  double vy = v[1];\n\n  // since vx, vy = 0, this has no effect\n  double Lx = 1;\n  double Ly = 1;\n\n  // initialize operators\n  AhAOp AhA(vx, vy, Lx, Ly, Nx, Ny, dt);\n  PTransportOpId<RT_t> A(rt, AhA, vx, vy);\n\n  RidgeletSolverNOP<rt_coeff_t> rt_solver(rf, vx, vy, dt);\n  // assert(vx == 0);\n  // assert(vy == 0);\n  // have to apply A.T to rhs otherwise!!!\n\n  /////////////\n  // b = A*x //\n  /////////////\n  rca_t x(rf);\n  x.resize(rt_cell_array);\n  rca_t b(rf);\n  b.resize(rt_cell_array);\n  x = rt_cell_array;\n\n  // b = A*x\n  // Note if v=[0,0]: A is the identity operator\n  b = x;\n\n  /* cout << \"RT_SOLVER::tol  : \" << tol << \"\\n\"; */\n  /* cout << \"RT_SOLVER::maxit: \" << maxit << \"\\n\"; */\n  Logger::GetInstance().push_prefix(\"RTCGNOP\");\n  rt_solver.set_log(log);\n  rt_solver.solve(x, A, b, tol, maxit);\n  Logger::GetInstance().clear_prefix();\n\n  return std::make_tuple(rt_solver.iter(), rt_solver.relres());\n\n  /* cout << \"RT CG::RELRES \" << rt_solver.relres() << \"\\n\" */\n  /*      << \"RT CG::ITER \"   << rt_solver.iter() << \"\\n\"; */\n}\n\n// --------------------------------------------------------------------------------\n// solve in Fourier domain\ntemplate <typename ARRAY_T>\nstd::tuple<int, double> solve_ft(ARRAY_T& Fh, const double dt, Eigen::Vector2d& v, bool log)\n{\n  const unsigned int Nx = Fh.cols();  // #cols\n  const unsigned int Ny = Fh.rows();  // #rows\n\n  double vx = v[0];\n  double vy = v[1];\n  // since vx, vy = 0, this has no effect\n  double Lx = 1;\n  double Ly = 1;\n\n  // initialize operators\n  AhAOp A(vx, vy, Lx, Ly, Nx, Ny, dt);\n\n  /////////////\n  // b = A*x //\n  /////////////\n  ARRAY_T x(Ny, Nx);\n  x = Fh;\n\n  ARRAY_T b(Ny, Nx);\n  b = x;\n\n  Logger::GetInstance().push_prefix(\"FTCG\");\n  CG cg;\n  cg.set_log(log);\n  cg.solve(x, A, b, tol, maxit);\n  Logger::GetInstance().clear_prefix();\n\n  return std::make_tuple(cg.iter(), cg.relres());\n\n  /* cout << \"FT CG::RELRES \" << cg.relres() << \"\\n\" */\n  /*      << \"FT CG::ITER \"  << cg.iter() << \"\\n\"; */\n}\n\nint main(int argc, char* argv[])\n{\n  SOURCE_INFO();\n\n  namespace po = boost::program_options;\n\n  unsigned int Jx, Jy, rho_x, rho_y;\n  int nv;\n  double dt, r;\n  bool log;\n\n  po::options_description options(\"options\");\n  options.add_options()(\"help\", \"produce help message\")\n      (\"Jx,i\", po::value<unsigned int>(&Jx)->default_value(3), \"Jx\")\n      (\"Jy,j\", po::value<unsigned int>(&Jy)->default_value(3), \"Jy\")\n      (\"rx,x\", po::value<unsigned int>(&rho_x)->default_value(1), \"rho_x\")\n      (\"ry,y\", po::value<unsigned int>(&rho_y)->default_value(1), \"rho_x\")\n      (\"rad,r\", po::value<double>(&r)->default_value(1), \"|v|\")\n      /* (\"vx\", po::value<double>(&vx)->default_value(1), \"vx\") */\n      /* (\"vy\", po::value<double>(&vy)->default_value(0), \"vy\") */\n      (\"dt,t\", po::value<double>(&dt)->default_value(0.1), \"dt\")\n      (\"nv\", po::value<int>(&nv)->default_value(6), \"#directons in velocity\")\n      (\"log\", po::value<bool>(&log)->default_value(false), \"log cg history\")\n      (\"smooth\", \"use smooth initial condition\")\n      (\"save\", \"save solution\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << options << \"\\n\";\n    return 0;\n  }\n\n  if (vm.count(\"save\")) save = true;\n\n  cout << setw(20) << \"Jx\"\n       << \": \" << Jx << \"\\n\"\n       << setw(20) << \"Jy\"\n       << \": \" << Jy << \"\\n\"\n       << setw(20) << \"rho_x\"\n       << \": \" << rho_x << \"\\n\"\n       << setw(20) << \"rho_y\"\n       << \": \" << rho_y << \"\\n\"\n       << setw(20) << \"dt\"\n       << \": \" << dt << \"\\n\"\n       << setw(20) << \"|v|\"\n       << \": \" << r << \"\\n\";\n\n  RidgeletFrame rf(Jx, Jy, rho_x, rho_y);\n\n  const unsigned int Nx = rf.Nx();  // #cols\n  const unsigned int Ny = rf.Ny();  // #rows\n  cout << \"Nx: \" << Nx << \"\\n\";\n  cout << \"Ny: \" << Ny << \"\\n\";\n\n  auto phi = 2 * pi * Eigen::VectorXd::LinSpaced(nv + 1, 0, 1);\n\n  for (int i = 0; i < nv; ++i) {\n    cout << \"---------- phi = \" << phi[i] << \" ----------\\n\";\n    const double vx = std::cos(phi[i]) * r;\n    const double vy = std::sin(phi[i]) * r;\n    Eigen::Vector2d v;\n    v[0] = vx;\n    v[1] = vy;\n\n    Eigen::ArrayXd xi = Eigen::ArrayXd::LinSpaced(Nx, 0, 1);\n    Eigen::ArrayXd yi = Eigen::ArrayXd::LinSpaced(Ny, 0, 1);\n    array_t F(Ny, Nx);\n    F = (-100 * ((yi - 0.5)).cwiseAbs2()).exp().replicate(1, xi.rows()) *\n        (-100 * ((xi - 0.5).cwiseAbs2())).exp().transpose().replicate(yi.rows(), 1);\n    if (!vm.count(\"smooth\")) {\n      F = (((yi - 0.5).replicate(1, xi.rows()) * vy -\n            (xi - 0.5).transpose().replicate(yi.rows(), 1) * vx) <=\n           0).select(F, Eigen::ArrayXXd::Zero(Ny, Nx));\n    }\n\n    hid_t file = H5Fcreate(\"cg.h5\", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n    eigen2hdf::save(file, \"x0\", F);\n    H5Fclose(file);\n\n    // F.setOnes();\n\n    // ----------------------------------------\n    /* double n[2] = {1,1}; */\n    /* F = ((n[0]*(yi.replicate(1, xi.rows())-0.5*pi) + n[1]*(xi.transpose().replicate(yi.rows(),\n     * 1)-0.5*pi)) > 1e-8) */\n    /*   .select(F, array_t::Zero(Ny, Nx)); */\n    fft_t fft;\n    complex_array_t Fh(Ny, Nx);\n    fft.ft(Fh, F, false);\n\n    auto ret_rt = solve_rt(Fh, rf, dt, v, log);\n    auto ret_ft = solve_ft(Fh, dt, v, log);\n    auto ret_rtnop = solve_rtnop(Fh, rf, dt, v, log);\n\n    cout << \"RTCG \" << std::scientific << std::setprecision(3) << std::setw(7) << vx << \" \"\n         << std::setw(7) << vy << \" \" << std::setw(7) << std::get<1>(ret_rt) << \" \" << std::setw(7)\n         << std::get<0>(ret_rt) << \"\\n\";\n    cout << \"RTCGNOP \" << std::scientific << std::setprecision(3) << std::setw(7) << vx << \" \"\n         << std::setw(7) << vy << \" \" << std::setw(7) << std::get<1>(ret_rtnop) << \" \"\n         << std::setw(7) << std::get<0>(ret_rtnop) << \"\\n\";\n    cout << \"FTCG \" << std::scientific << std::setprecision(3) << std::setw(7) << vx << \" \"\n         << std::setw(7) << vy << \" \" << std::setw(7) << std::get<1>(ret_ft) << \" \" << std::setw(7)\n         << std::get<0>(ret_ft) << \"\\n\";\n\n    /* std::vector<double> diagp = make_inv_diagonal_preconditioner(rf, dt*vx, dt*vy); */\n    /* cout  << \"\\n\"; */\n    /* for (int i = 0; i < diagp.size(); ++i) { */\n    /*   cout << diagp[i] << \"\\n\"; */\n    /* } */\n    /* cout << \"\\n\"; */\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "f5aad26f7aa9e2243a136f3c30177a9acc6a16c9", "size": 9999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main_cg.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "test/main_cg.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/main_cg.cpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 30.8611111111, "max_line_length": 99, "alphanum_fraction": 0.5376537654, "num_tokens": 3262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6419271394871833}}
{"text": "#include \"shiftinvert_solver.hpp\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <complex>\n#include <fmt/format.h>\n\nusing namespace Eigen;\n\nShiftinvertSolver::ShiftinvertSolver(const Ref<const MatrixXd> &matA,\n                                     const Ref<const MatrixXd> &matB,\n                                     int maxiter, double tol)\n    : ndim_(matA.rows()), matA_(matA), matB_(matB), maxiter_(maxiter),\n      tol_(tol) {}\n\nstd::complex<double> ShiftinvertSolver::compute(std::complex<double> sigma) {\n  MatrixXcd matL = matA_ - sigma * matB_;\n  auto lhh = matL.householderQr();\n  VectorXcd x = VectorXcd::Random(ndim_);\n  std::complex<double> lamb;\n  std::complex<double> lamb_pre = 1.0e10;\n  for (int i = 0; i < maxiter_; ++i) {\n    VectorXcd u = x / x.norm();\n    VectorXcd vecR = matB_ * u;\n    x = lhh.solve(vecR);\n    lamb = u.dot(x);\n    lamb = 1.0 / lamb + sigma;\n    double diff = std::abs(lamb - lamb_pre);\n    // fmt::print(\"{:d} {:12.5f}{:12.5f}({:12.5e})\\n\", i, lamb.real(),\n    // lamb.imag(),\n    //            diff);\n    if (diff < tol_) {\n      break;\n    } else {\n      lamb_pre = lamb;\n    }\n  }\n  return lamb;\n}", "meta": {"hexsha": "8efc6ab829738e01322fb4918076f41db2ce0d62", "size": 1143, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/shiftinvert_solver.cc", "max_stars_repo_name": "pan3rock/shift-invert", "max_stars_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/shiftinvert_solver.cc", "max_issues_repo_name": "pan3rock/shift-invert", "max_issues_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shiftinvert_solver.cc", "max_forks_repo_name": "pan3rock/shift-invert", "max_forks_repo_head_hexsha": "cb5c3f5242a2e8083ac1f8bc79070c837a85e322", "max_forks_repo_licenses": ["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.3076923077, "max_line_length": 77, "alphanum_fraction": 0.5748031496, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6419271246379091}}
{"text": "\r\n#include \"cor_algorithm/sources/utilities.h\"\r\n#include \"cor_system/sources/logger.h\"\r\n//#include \"cor_type/sources/math/vector2_tmpl_impl.h\"\r\n//#include \"cor_type/sources/primitive/box_tmpl_impl.h\"\r\n#include \"cor_type/sources/primitive/box.h\"\r\n\r\n#define BOOST_TEST_NO_LIB\r\n#include <boost/test/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_SUITE(box)\r\n\r\nBOOST_AUTO_TEST_CASE(box2d)\r\n{\r\n\r\n    typedef cor::type::Box2F Box;\r\n\r\n    Box b0(0.0f, 0.0f, 1.0f, 1.0f);\r\n\r\n    cor::RInt32 i;\r\n    cor::RInt32 j;\r\n\r\n    for(i = 0 ; i < 2 ; i++)\r\n    {\r\n        for(j = 0 ; j < 2 ; j++)\r\n        {\r\n            Box b1(j - 0.5f, i - 0.5f, 1.0f, 1.0f);\r\n            BOOST_CHECK(b0.is_cross(b1));\r\n        }\r\n\r\n    }\r\n\r\n    for(i = 0 ; i < 2 ; i++)\r\n    {\r\n        for(j = 0 ; j < 2 ; j++)\r\n        {\r\n            Box b1(j * 3 - 1.5f, i * 3 - 1.5f, 1.0f, 1.0f);\r\n            BOOST_CHECK(!b0.is_cross(b1));\r\n        }\r\n\r\n    }\r\n\r\n\r\n\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(box2d_distance)\r\n{\r\n\r\n    typedef cor::type::Box2F Box;\r\n    typedef cor::type::Vector2F V;\r\n\r\n    Box b0(0.0f, 0.0f, 1.0f, 1.0f);\r\n    V v(2.0f, 2.0f);\r\n\r\n    auto d = b0.get_distance(v);\r\n    BOOST_CHECK_CLOSE(d, sqrtf(2.0f), 0.0001f);\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "4e0ddfd47f3f84a02bd6aafe873ddb46de37103e", "size": 1210, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/sources/math/box_test.cpp", "max_stars_repo_name": "rmake/cor-engine", "max_stars_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T09:55:02.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-10T03:42:23.000Z", "max_issues_repo_path": "tests/unit/sources/math/box_test.cpp", "max_issues_repo_name": "rmake/cor-engine", "max_issues_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/unit/sources/math/box_test.cpp", "max_forks_repo_name": "rmake/cor-engine", "max_forks_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T02:30:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T06:56:49.000Z", "avg_line_length": 19.5161290323, "max_line_length": 60, "alphanum_fraction": 0.5371900826, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.641927119254361}}
{"text": "// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n#include <OpenTissue/core/spline/spline.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <boost/test/auto_unit_test.hpp>\r\n\r\n// Boost Test declaration and Checking macros\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\ntypedef OpenTissue::spline::MathTypes<double, size_t>    math_types;\r\ntypedef math_types::vector_type                                vector_type;\r\ntypedef std::vector<double>                                    knot_container;\r\ntypedef std::vector<vector_type>                               point_container;\r\n\r\ntypedef OpenTissue::spline::NUBSpline<knot_container, point_container> spline_type;\r\n\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_spline_compute_derivatives);\r\n\r\nBOOST_AUTO_TEST_CASE(test_compute_derivatives)\r\n{\r\n  knot_container U;\r\n\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);  //k = 3\r\n  U.push_back(1.0);\r\n  U.push_back(2.0);\r\n  U.push_back(3.0);\r\n  U.push_back(4.0);  // n = 6  => |P| = 7\r\n  U.push_back(5.0);\r\n  U.push_back(5.0);\r\n  U.push_back(5.0);  // m = 9  => |U| = 10\r\n\r\n  // Indices of basis functions belongs to the interval [0..n]\r\n\r\n  point_container P;\r\n  vector_type p0(2);  p0(0) = 0.0; p0(1) = 0.0;\r\n  vector_type p1(2);  p1(0) = 1.0; p1(1) = 0.0;\r\n  vector_type p2(2);  p2(0) = 2.0; p2(1) = 0.0;\r\n  vector_type p3(2);  p3(0) = 3.0; p3(1) = 0.0;\r\n  vector_type p4(2);  p4(0) = 4.0; p4(1) = 0.0;\r\n  vector_type p5(2);  p5(0) = 5.0; p5(1) = 0.0;\r\n  vector_type p6(2);  p6(0) = 6.0; p6(1) = 0.0;\r\n\r\n  P.push_back(p0);\r\n  P.push_back(p1);\r\n  P.push_back(p2);\r\n  P.push_back(p3);\r\n  P.push_back(p4);\r\n  P.push_back(p5);\r\n  P.push_back(p6);\r\n\r\n  spline_type spline(3,U,P);\r\n\r\n  double const tolerance = 0.00001;\r\n\r\n  point_container dC0;\r\n  point_container dC1;\r\n  point_container dC2;\r\n  point_container dC3;\r\n  point_container dC4;\r\n  point_container dC5;\r\n  point_container dC6;\r\n\r\n  double const du = 5.0/6.0;\r\n  double u = 0.0;\r\n  OpenTissue::spline::compute_spline_derivatives(spline, u, 1, dC0, math_types() );\r\n  u += du;\r\n  OpenTissue::spline::compute_spline_derivatives(spline, u, 1, dC1, math_types());\r\n  u += du;\r\n  OpenTissue::spline::compute_spline_derivatives(spline, u, 1, dC2, math_types());\r\n  u += du;\r\n  OpenTissue::spline::compute_spline_derivatives(spline, u, 1, dC3, math_types());\r\n  u += du;\r\n  OpenTissue::spline::compute_spline_derivatives(spline, u, 1, dC4, math_types());\r\n  u += du;\r\n  OpenTissue::spline::compute_spline_derivatives(spline, u, 1, dC5, math_types());\r\n  u += du;\r\n  OpenTissue::spline::compute_spline_derivatives(spline, u, 1, dC6, math_types());\r\n\r\n  BOOST_CHECK_CLOSE( dC0[0](1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( dC1[0](1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( dC2[0](1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( dC3[0](1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( dC4[0](1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( dC5[0](1), 0.0, tolerance );\r\n  BOOST_CHECK_CLOSE( dC6[0](1), 0.0, tolerance );\r\n\r\n  //BOOST_CHECK( dC0[0](0) > 0.0 ); // why is this zero?\r\n  BOOST_CHECK( dC1[0](0) > 0.0 );\r\n  BOOST_CHECK( dC2[0](0) > 0.0 );\r\n  BOOST_CHECK( dC3[0](0) > 0.0 );\r\n  BOOST_CHECK( dC4[0](0) > 0.0 );\r\n  BOOST_CHECK( dC5[0](0) > 0.0 );\r\n  BOOST_CHECK( dC6[0](0) > 0.0 );\r\n\r\n  //std::cout << dC0[0](0) << \" \" << dC0[0](1) << std::endl;\r\n  //std::cout << dC1[0](0) << \" \" << dC1[0](1) << std::endl;\r\n  //std::cout << dC2[0](0) << \" \" << dC2[0](1) << std::endl;\r\n  //std::cout << dC3[0](0) << \" \" << dC3[0](1) << std::endl;\r\n  //std::cout << dC4[0](0) << \" \" << dC4[0](1) << std::endl;\r\n  //std::cout << dC5[0](0) << \" \" << dC5[0](1) << std::endl;\r\n  //std::cout << dC6[0](0) << \" \" << dC6[0](1) << std::endl;\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE(test_bezier_curve_case)\r\n{\r\n  knot_container U;\r\n\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);  \r\n  U.push_back(0.0);   \r\n  U.push_back(1.0);\r\n  U.push_back(1.0);\r\n  U.push_back(1.0);  \r\n  U.push_back(1.0);  \r\n\r\n  // k = 4\r\n  // n = 3  => |P| = 4\r\n  // m = 7  => |U| = 8\r\n\r\n  point_container P;\r\n  vector_type p0(2);  p0(0) = 0.0; p0(1) = 0.0;\r\n  vector_type p1(2);  p1(0) = 1.0; p1(1) = 1.0;\r\n  vector_type p2(2);  p2(0) = 2.0; p2(1) = 1.0;\r\n  vector_type p3(2);  p3(0) = 3.0; p3(1) = 0.0;\r\n\r\n  P.push_back(p0);\r\n  P.push_back(p1);\r\n  P.push_back(p2);\r\n  P.push_back(p3);\r\n\r\n  spline_type bezier(4,U,P);\r\n\r\n  double const tolerance = 10e-15;\r\n\r\n  // Now we have constructed the equivalent of a bezier curve\r\n  //\r\n  //   B(t) =     a t^3 +   b t^2 + c t + d\r\n  //   B'(t) =  3 a t^2 + 2 b t   + c \r\n  //\r\n  //   B(0) = p0  = d\r\n  //   B(1) = p3  = a + b + c + d\r\n  //   B'(0) = 3*(p1-p0) = c\r\n  //   B'(1) = 3*(p1-p0) = 3 a + 2 b + c\r\n  //\r\n  //  working out the equations one would get\r\n  vector_type a = -1*p0 + 3*p1 - 3*p2 + 1*p3;\r\n  vector_type b =  3*p0 - 6*p1 + 3*p2;\r\n  vector_type c = -3*p0 + 3*p1;\r\n  vector_type d =  1*p0;\r\n\r\n  double u = 0.0;\r\n  int const N = 11;\r\n  double const du = 1.0 / (N-1);\r\n  for(int i=0;i<N;++i)\r\n  {\r\n    point_container dC;\r\n    // ask for zero'th, first and second order derivatives\r\n    OpenTissue::spline::compute_spline_derivatives(bezier, u, 2, dC, math_types() );\r\n\r\n    vector_type q(2);\r\n    q = (u*u*u)*a + (u*u)*b + u*c + d;\r\n\r\n    vector_type dq(2);\r\n    dq = 3*(u*u)*a + 2*(u)*b + c;\r\n\r\n    vector_type ddq(2);\r\n    ddq = 6*u*a + 2*b;\r\n\r\n    BOOST_CHECK( std::fabs( dC[0](0) - q(0) ) < tolerance );\r\n    BOOST_CHECK( std::fabs( dC[0](1) - q(1) ) < tolerance );\r\n\r\n    BOOST_CHECK( std::fabs( dC[1](0) - dq(0) ) < tolerance );\r\n    BOOST_CHECK( std::fabs( dC[1](1) - dq(1) ) < tolerance );\r\n\r\n    BOOST_CHECK( std::fabs( dC[2](0) - ddq(0) ) < tolerance );\r\n    BOOST_CHECK( std::fabs( dC[2](1) - ddq(1) ) < tolerance );\r\n    u += du;\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "2fa7ede4228a5edbb796593e8e26fc1501fd6beb", "size": 5964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/spline/compute_derivatives/src/unit_compute_derivatives.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/spline/compute_derivatives/src/unit_compute_derivatives.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/spline/compute_derivatives/src/unit_compute_derivatives.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 31.0625, "max_line_length": 85, "alphanum_fraction": 0.5764587525, "num_tokens": 2289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6419271164735522}}
{"text": "#include \"convex_hull.hpp\"\n#include <Eigen/Geometry>\n#include \"ear/helpers/assert.hpp\"\n\nnamespace ear {\n\n  std::vector<Facet> convex_hull(const std::vector<Eigen::Vector3d> &positions,\n                                 double tolerance) {\n    using Vec = Eigen::Vector3d;\n    using Tri = std::array<size_t, 3>;\n\n    // the mean point, guaranteed to be inside the convex hull\n    Vec inside_point = Vec::Zero();\n    for (auto &pos : positions) inside_point += pos;\n    inside_point /= (double)positions.size();\n\n    // find all triangles on the convex hull:\n    // - iterate through all possible triangles\n    // - find the triangle normal, checking for collinearity\n    // - it's on the convex hull if:\n    //    - the inside point is not on the plane of the triangle\n    //    - all points are on the same side of the plane of the triangle as the\n    //    inside point\n    std::vector<Tri> hull_tris;\n    std::vector<Vec> hull_tri_normals;\n\n    for (size_t i = 0; i < positions.size(); i++)\n      for (size_t j = i + 1; j < positions.size(); j++)\n        for (size_t k = j + 1; k < positions.size(); k++) {\n          Vec normal =\n              (positions[j] - positions[i]).cross(positions[k] - positions[i]);\n          ear_assert(normal.squaredNorm() > tolerance,\n                     \"collinear points in convex hull\");\n          normal.normalize();  // XXX: not really required, but helps make\n                               // tolerances consistent\n\n          double dot_inside = normal.dot(inside_point - positions[i]);\n\n          if (std::abs(dot_inside) < tolerance)\n            continue;  // tri coplanar with inside point\n\n          bool points_on_same_side_as_inside = true;\n          for (auto &pos : positions) {\n            double dot_point = normal.dot(pos - positions[i]);\n\n            // check if signs are equal, with tolerance\n            if (!(dot_inside > 0 ? dot_point > -tolerance\n                                 : dot_point < tolerance)) {\n              points_on_same_side_as_inside = false;\n              break;\n            }\n          }\n\n          if (points_on_same_side_as_inside) {\n            hull_tris.push_back({i, j, k});\n            hull_tri_normals.push_back(normal);\n          }\n        }\n\n    // merge coplanar triangles into facets\n    std::vector<Facet> hull_facets;\n    std::vector<Vec> hull_facet_normals;\n\n    for (size_t tri_i = 0; tri_i < hull_tris.size(); tri_i++) {\n      const Vec &tri_point = positions[hull_tris[tri_i][0]];\n      const Vec &tri_norm = hull_tri_normals[tri_i];\n\n      // check each facet to see if this triangle is on the same plane.\n      // if it is, add the points to the facet. if no facet is found, make a\n      // new facet.\n      bool found_facet = false;\n      for (size_t facet_i = 0; facet_i < hull_facets.size(); facet_i++) {\n        const Vec &facet_norm = hull_facet_normals[facet_i];\n        const Vec &facet_point = positions[*hull_facets[facet_i].begin()];\n\n        // they are on the same plane if the line between the test points is\n        // not along the normal, and if the normals point in the same or\n        // opposite direction. alternatively, we could just test all tri\n        // vertices.\n        if (std::abs((tri_point - facet_point).dot(facet_norm)) < tolerance &&\n            facet_norm.cross(tri_norm).squaredNorm() < tolerance) {\n          for (size_t corner_idx : hull_tris[tri_i]) {\n            hull_facets[facet_i].insert((Facet::value_type)corner_idx);\n          }\n\n          found_facet = true;\n          break;\n        }\n      }\n\n      if (!found_facet) {\n        Facet f;\n        for (size_t corner_idx : hull_tris[tri_i])\n          f.insert((Facet::value_type)corner_idx);\n        hull_facets.push_back(std::move(f));\n        hull_facet_normals.push_back(tri_norm);\n      }\n    }\n\n    return hull_facets;\n  }\n}  // namespace ear\n", "meta": {"hexsha": "ace4f405e8b7cfe0ecc1e1228e28ddfd6e03d14d", "size": 3839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/convex_hull.cpp", "max_stars_repo_name": "rsjtaylor/libear", "max_stars_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-07-30T17:58:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T15:33:36.000Z", "max_issues_repo_path": "src/common/convex_hull.cpp", "max_issues_repo_name": "rsjtaylor/libear", "max_issues_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T18:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T10:24:52.000Z", "max_forks_repo_path": "src/common/convex_hull.cpp", "max_forks_repo_name": "rsjtaylor/libear", "max_forks_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-07-30T15:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T16:22:43.000Z", "avg_line_length": 37.2718446602, "max_line_length": 79, "alphanum_fraction": 0.5946861162, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6418628576947638}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_REM_PIO2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_PIO2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing rem_pio2 capabilities\n\n    Computes the remainder modulo \\f$\\pi/2\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r;\n    as_integer<T> n;\n    std::tie(n, r) = rem_pio2(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    as_integer<T> n = div(inearbyint, x, Pio_2<T>());\n    T r =  remainder(x, Pio_2<T>());\n    @endcode\n\n  **/\n  std::pair<IntegerValue, Value> rem_pio2(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem_pio2.hpp>\n#include <boost/simd/function/simd/rem_pio2.hpp>\n\n#endif\n", "meta": {"hexsha": "de0fbcdaa9857aae08d161a617c0607d7f4823e0", "size": 1172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/rem_pio2.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/rem_pio2.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/rem_pio2.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": 22.9803921569, "max_line_length": 100, "alphanum_fraction": 0.5742320819, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6418628452700901}}
{"text": "/*\n * Copyright Evan Miller, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <pch_light.hpp>\n#include <boost/math/concepts/real_concept.hpp>\n#include \"test_jacobi_theta.hpp\"\n\n// Test file for the Jacobi Theta functions, a.k.a the four horsemen of the\n// Jacobi elliptic integrals. At the moment only Wolfrma Alpha spot checks are\n// used. We should generate extra-precise numbers with NTL::RR or some such.\n\nvoid expected_results()\n{\n   //\n   // Define the max and mean errors expected for\n   // various compilers and platforms.\n   //\n   //\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                  // test type(s)\n      \".*Small Tau.*\",      // test data group\n      \".*\", 1000, 200);  // test function\n\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                  // test type(s)\n      \".*Wolfram Alpha.*\",      // test data group\n      \".*\", 60, 15);  // test function\n\n   // Catch all cases come last:\n   //\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                  // test type(s)\n      \".*\",      // test data group\n      \".*\", 20, 5);  // test function\n   //\n   // Finish off by printing out the compiler/stdlib/platform names,\n   // we do this to make it easier to mark up expected error rates.\n   //\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \"\n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE( test_main )\n{\n    expected_results();\n    BOOST_MATH_CONTROL_FP;\n    BOOST_MATH_STD_USING\n\n    using namespace boost::math;\n\n    BOOST_CHECK_THROW(jacobi_theta1(0.0, 0.0), std::domain_error);\n    BOOST_CHECK_THROW(jacobi_theta1(0.0, 1.0), std::domain_error);\n\n    BOOST_CHECK_THROW(jacobi_theta2(0.0, 0.0), std::domain_error);\n    BOOST_CHECK_THROW(jacobi_theta2(0.0, 1.0), std::domain_error);\n\n    BOOST_CHECK_THROW(jacobi_theta3(0.0, 0.0), std::domain_error);\n    BOOST_CHECK_THROW(jacobi_theta3(0.0, 1.0), std::domain_error);\n\n    BOOST_CHECK_THROW(jacobi_theta4(0.0, 0.0), std::domain_error);\n    BOOST_CHECK_THROW(jacobi_theta4(0.0, 1.0), std::domain_error);\n\n    BOOST_CHECK_THROW(jacobi_theta1tau(0.0, 0.0), std::domain_error);\n    BOOST_CHECK_THROW(jacobi_theta1tau(0.0, -1.0), std::domain_error);\n\n    BOOST_CHECK_THROW(jacobi_theta2tau(0.0, 0.0), std::domain_error);\n    BOOST_CHECK_THROW(jacobi_theta2tau(0.0, -1.0), std::domain_error);\n\n    BOOST_CHECK_THROW(jacobi_theta3tau(0.0, 0.0), std::domain_error);\n    BOOST_CHECK_THROW(jacobi_theta3tau(0.0, -1.0), std::domain_error);\n\n    BOOST_CHECK_THROW(jacobi_theta4tau(0.0, 0.0), std::domain_error);\n    BOOST_CHECK_THROW(jacobi_theta4tau(0.0, -1.0), std::domain_error);\n\n    double eps = std::numeric_limits<double>::epsilon();\n    for (double q=0.0078125; q<1.0; q += 0.0078125) { // = 1/128\n        for (double z=-8.0; z<=8.0; z += 0.125) {\n            test_periodicity(z, q, 100 * eps);\n            test_argument_translation(z, q, 100 * eps);\n            test_sums_of_squares(z, q, 100 * eps);\n            // The addition formula is complicated, cut it some extra slack\n            test_addition_formulas(z, constants::ln_two<double>(), q, sqrt(sqrt(eps)));\n            test_duplication_formula(z, q, 100 * eps);\n            test_transformations_of_nome(z, q, 100 * eps);\n            test_watsons_identities(z, 0.5, q, 101 * eps);\n            test_landen_transformations(z, -log(q)/constants::pi<double>(), sqrt(eps));\n            test_elliptic_functions(z, q, 5 * sqrt(eps));\n        }\n        test_elliptic_integrals(q, 10 * eps);\n    }\n\n    test_special_values(eps);\n\n    for (double s=0.125; s<3.0; s+=0.125) {\n        test_mellin_transforms(2.0 + s, eps, 3 * eps);\n        test_laplace_transforms(s, eps, 4 * eps);\n    }\n\n    test_spots(0.0F, \"float\");\n    test_spots(0.0, \"double\");\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_spots(0.0L, \"long double\");\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\n    test_spots(concepts::real_concept(0), \"real_concept\");\n#endif\n#else\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\n      \"either because the long double overloads of the usual math functions are \"\n      \"not available at all, or because they are too inaccurate for these tests \"\n      \"to pass.</note>\" << std::endl;\n#endif\n}\n", "meta": {"hexsha": "86d28efb4c9e5b0c024712c937cde261f566535b", "size": 4779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_jacobi_theta.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/test_jacobi_theta.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/test_jacobi_theta.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 37.9285714286, "max_line_length": 87, "alphanum_fraction": 0.6032642812, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6417678852444371}}
{"text": "#include <boost/lexical_cast.hpp>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\nusing boost::lexical_cast;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n/*\r\nJust a normal bruteforce, we'll generate the first couple dozen thousand cubes, sort them as strings (to match permutations) into a vector, then run a count on them.\r\n*/\r\n\r\nint main(int argc, char *argv[]) {\r\n\tvector<string> permutations;\r\n\t// Generate all cubes.\r\n\tfor(int i = 0; i < 10'000; i++) {\r\n\t\tcpp_int cube = boost::multiprecision::pow((cpp_int)i, 3);\r\n\t\tstring t = lexical_cast<string>(cube);\r\n\t\tsort(t.begin(), t.end());\r\n\t\tpermutations.push_back(t);\r\n\t}\r\n\t// Go through it and count occurances of each string, break when we find what we need.\r\n\tfor(int i = 0; i < permutations.size(); i++) {\r\n\t\tint existingPermutations = count(permutations.begin(), permutations.end(), permutations[i]);\r\n\t\tif(existingPermutations == 5) {\r\n\t\t\tcpp_int cube = boost::multiprecision::pow((cpp_int)i, 3);\r\n\t\t\tcout << cube << endl;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}", "meta": {"hexsha": "371d1530739e700a04e341ecaf317f049f8d858b", "size": 1093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/51-100/62/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/51-100/62/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/51-100/62/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 32.1470588235, "max_line_length": 166, "alphanum_fraction": 0.6797804209, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6417678827694581}}
{"text": "#ifndef Circumference_hpp\n#define Circumference_hpp\n\n#include <shapes/Circle.hpp>\n#include <shapes/Rectangle.hpp>\n\n#include <boost/math/constants/constants.hpp>\nnamespace bmc = boost::math::constants;\n\nfloat\ncircumference( Rectangle const & r )\n{\n  return 2 * r.width + 2 * r.height;\n}\n\nfloat\ncircumference( Circle const & c )\n{\n  return 2 * bmc::pi<float>() * c.radius;\n}\n\n#endif // Circumference_hpp\n", "meta": {"hexsha": "d4ae37c4c60d34c162aa3822cd7790c569d3f87b", "size": 402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/shapes/Circumference.hpp", "max_stars_repo_name": "cesiumsolutions/dynamic_generic_visitor", "max_stars_repo_head_hexsha": "da8fe928bf77270e1a64beae0051bfadba7ea256", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/shapes/Circumference.hpp", "max_issues_repo_name": "cesiumsolutions/dynamic_generic_visitor", "max_issues_repo_head_hexsha": "da8fe928bf77270e1a64beae0051bfadba7ea256", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/shapes/Circumference.hpp", "max_forks_repo_name": "cesiumsolutions/dynamic_generic_visitor", "max_forks_repo_head_hexsha": "da8fe928bf77270e1a64beae0051bfadba7ea256", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4782608696, "max_line_length": 45, "alphanum_fraction": 0.7213930348, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6417576403765854}}
{"text": "//  (C) Copyright 2005 Daniel Egloff, Eric Niebler\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    // matlab\n    // >> samples = [1:5];\n    // >> mean(samples)\n    // ans = 3\n    // >> sum(samples .* samples) / length(samples)\n    // ans = 11\n    // >> sum(samples .* samples) / length(samples) - mean(samples)^2\n    // ans = 2\n\n    // lazy variance, now lazy with syntactic sugar, thanks to Eric\n    accumulator_set<int, stats<tag::variance(lazy)> > acc1;\n\n    acc1(1);\n    acc1(2);\n    acc1(3);\n    acc1(4);\n    acc1(5);\n\n    BOOST_CHECK_EQUAL(5u, count(acc1));\n    BOOST_CHECK_CLOSE(3., mean(acc1), 1e-5);\n    BOOST_CHECK_CLOSE(11., moment<2>(acc1), 1e-5);\n    BOOST_CHECK_CLOSE(2., variance(acc1), 1e-5);\n\n    // immediate variance\n    accumulator_set<int, stats<tag::variance> > acc2;\n\n    acc2(1);\n    acc2(2);\n    acc2(3);\n    acc2(4);\n    acc2(5);\n\n    BOOST_CHECK_EQUAL(5u, count(acc2));\n    BOOST_CHECK_CLOSE(3., mean(acc2), 1e-5);\n    BOOST_CHECK_CLOSE(2., variance(acc2), 1e-5);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"variance test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n", "meta": {"hexsha": "07dba9e61b01247b73e22c8e872a9fc2e6a9db3e", "size": 1870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/accumulators/test/variance.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/accumulators/test/variance.cpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/accumulators/test/variance.cpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1014492754, "max_line_length": 79, "alphanum_fraction": 0.6080213904, "num_tokens": 499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6416997355615228}}
{"text": "#include <vector>\n#include <boost/math/distributions/lognormal.hpp>\n#include \"lognormal_dist.h\"\n\nstochastic::LognormalDistribution::LognormalDistribution(double mean, double std_dev)\n  : Distribution(),\n    mean_{mean},\n    std_dev_{std_dev},\n    distribution_{mean, std_dev_}\n{}\n\nstd::vector<double> stochastic::LognormalDistribution::cumulative_dist_func(\n    const std::vector<double>& locations) const {\n  std::vector<double> evaluations(locations.size());\n\n  for (unsigned int i = 0; i < locations.size(); ++i) {\n    evaluations[i] = cdf(distribution_, locations[i]);\n  }\n\n  return evaluations;\n}\n\nstd::vector<double> stochastic::LognormalDistribution::inv_cumulative_dist_func(\n    const std::vector<double>& probabilities) const {\n  std::vector<double> evaluations(probabilities.size());\n\n  for (unsigned int i = 0; i < probabilities.size(); ++i) {\n    evaluations[i] = quantile(distribution_, probabilities[i]);\n  }\n\n  return evaluations;\n}\n", "meta": {"hexsha": "8e1f525af4d92f2444e25e70fe76c2d65d5238ef", "size": 949, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/lognormal_dist.cc", "max_stars_repo_name": "charlesxwang/smelt", "max_stars_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "src/lognormal_dist.cc", "max_issues_repo_name": "charlesxwang/smelt", "max_issues_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "src/lognormal_dist.cc", "max_forks_repo_name": "charlesxwang/smelt", "max_forks_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 28.7575757576, "max_line_length": 85, "alphanum_fraction": 0.7239199157, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6416771612688955}}
{"text": "#ifndef AMT_ML_MODEL_LINEAR_REGRESSION_OPTIMIZER_HPP\n#define AMT_ML_MODEL_LINEAR_REGRESSION_OPTIMIZER_HPP\n\n#include <armadillo>\n#include <functional>\n#include <cmath>\n\nnamespace amt::classification{\n    \n    struct default_opt{\n\n    //     auto operator()(arma::Mat<double>& beta, arma::Mat<double> const& x, arma::Mat<double> const& y, double lm) const {\n    //         // x_t = x^T\n    //         auto x_t = x.t();\n            \n    //         // xt_y = x^T * y\n    //         auto xt_y = x_t * y;\n\n    //         if( lm == 0 ){\n    //             // xt_x = x^T * x\n    //             auto xt_x = x_t * x;\n\n    //             // (X * X^T) * B = X^T * Y\n    //             beta = arma::solve(xt_x,xt_y,arma::solve_opts::fast);\n    //         }else{\n                \n    //             arma::Mat<double> l_I = arma::eye(x.n_cols, x.n_cols) * lm;\n\n    //             // xt_x = x^T * x + l_I\n    //             auto xt_x_lI = ( x_t * x ) + l_I;\n\n    //             // (X * X^T) * B = X^T * Y\n    //             beta = arma::solve(xt_x_lI,xt_y,arma::solve_opts::fast);\n    //         }\n\n    //     }\n\n    };\n    \n    struct gradient_descent{\n\n        gradient_descent() = default;\n        gradient_descent(gradient_descent const&  other) = default;\n        gradient_descent(gradient_descent &&  other) = default;\n        gradient_descent& operator=(gradient_descent const&  other) = default;\n        gradient_descent& operator=(gradient_descent &&  other) = default;\n        ~gradient_descent() = default;\n        \n        template<typename Fn>\n        gradient_descent(double alpha, std::size_t iter, Fn&& fn)\n            : alpha(alpha)\n            , iteration(iter)\n            , fn(std::move(fn))\n        {}\n\n        gradient_descent(double alpha, std::size_t iter = 300000)\n            : alpha(alpha)\n            , iteration(iter)\n        {}\n\n        auto operator()(arma::Mat<double>& beta, arma::Mat<double> const& x, arma::Mat<double> const& y) const {\n            beta = arma::zeros(x.n_cols, 1ul);\n            eval(beta,x,y);\n        }\n\n        void eval(arma::Mat<double>& beta, arma::Mat<double> const& x, arma::Mat<double> const& y) const{\n            auto m = alpha / static_cast<double>(x.n_rows);\n            auto x_t = x.t();\n            for( auto i = 0u; i < iteration; ++i ){\n                auto p = ( x * beta );\n                auto h = apply_fn(p,fn);\n                arma::Mat<double> grad = ( x_t * (h - y) );\n                beta -= ( m * grad );\n            }\n        }\n\n        arma::Mat<double> apply_fn(arma::Mat<double> const& mat, std::function<double(double)> const& f) const{\n            arma::Mat<double> res(mat.n_rows, mat.n_cols);\n            for(auto i = 0u; i < mat.n_rows; ++i)\n                for(auto j = 0u; j < mat.n_cols; ++j)\n                    res(i,j) = f(mat(i,j));\n            return res;\n        }\n\n\n        double alpha{0.1};\n        std::size_t iteration{300000};\n        std::function<double(double)> fn = [](double el){\n            return 1.0 / ( 1.0 + std::exp(-el) );\n        };\n        std::function<double(double)> diff_fn = [](double el){\n            auto temp = std::exp(-el);\n            return temp / ( 1.0 + temp );\n        };\n    };\n\n    template<typename T>\n    inline static constexpr bool is_default_opt_v = std::is_same_v<T,default_opt>;\n\n    template<typename T>\n    inline static constexpr bool is_gradient_descent_v = std::is_same_v<T,gradient_descent>;\n\n} // namespace amt::classification\n\n\n#endif\n", "meta": {"hexsha": "1edd507871ad732c8b3d455fa12e02c670d9fe95", "size": 3468, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/model/LogisticRegression/optimizer.hpp", "max_stars_repo_name": "amitsingh19975/ML-v2", "max_stars_repo_head_hexsha": "0201ff66a25635d8d165f0299a18b3843bdbbc97", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-13T07:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T07:59:05.000Z", "max_issues_repo_path": "include/model/LogisticRegression/optimizer.hpp", "max_issues_repo_name": "amitsingh19975/ML-v2", "max_issues_repo_head_hexsha": "0201ff66a25635d8d165f0299a18b3843bdbbc97", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/model/LogisticRegression/optimizer.hpp", "max_forks_repo_name": "amitsingh19975/ML-v2", "max_forks_repo_head_hexsha": "0201ff66a25635d8d165f0299a18b3843bdbbc97", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4112149533, "max_line_length": 126, "alphanum_fraction": 0.5060553633, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6416450182123473}}
{"text": "#include \"ExperimentAmbientCube.h\"\n\n#include <Eigen/Eigen>\n#include <Eigen/nnls.h>\n\nnamespace Probulator {\n\nExperimentAmbientCube::AmbientCube ExperimentAmbientCube::solveAmbientCubeLeastSquares(const ImageBase<vec3>& directions, const Image& irradiance)\n{\n\tusing namespace Eigen;\n\n\tAmbientCube ambientCube;\n\n\tconst u64 sampleCount = directions.getPixelCount();\n\n\tMatrixXf A;\n\tA.resize(sampleCount, 6);\n\n\tfor (u64 sampleIt = 0; sampleIt < sampleCount; ++sampleIt)\n\t{\n\t\tconst vec3& direction = directions.at(sampleIt);\n\t\tvec3 dirSquared = direction * direction;\n\n\t\tif (direction.x < 0)\n\t\t{\n\t\t\tA(sampleIt, 0) = dirSquared.x;\n\t\t\tA(sampleIt, 1) = 0.0f;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tA(sampleIt, 0) = 0.0f;\n\t\t\tA(sampleIt, 1) = dirSquared.x;\n\t\t}\n\n\t\tif (direction.y < 0)\n\t\t{\n\t\t\tA(sampleIt, 2) = dirSquared.y;\n\t\t\tA(sampleIt, 3) = 0.0f;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tA(sampleIt, 2) = 0.0f;\n\t\t\tA(sampleIt, 3) = dirSquared.y;\n\t\t}\n\n\t\tif (direction.z < 0)\n\t\t{\n\t\t\tA(sampleIt, 4) = dirSquared.z;\n\t\t\tA(sampleIt, 5) = 0.0f;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tA(sampleIt, 4) = 0.0f;\n\t\t\tA(sampleIt, 5) = dirSquared.z;\n\t\t}\n\t}\n\n\tNNLS<MatrixXf> solver(A);\n\n\tVectorXf b;\n\tb.resize(sampleCount);\n\n\tfor (u32 channelIt = 0; channelIt < 3; ++channelIt)\n\t{\n\t\tfor (u64 sampleIt = 0; sampleIt < sampleCount; ++sampleIt)\n\t\t{\n\t\t\tb[sampleIt] = irradiance.at(sampleIt)[channelIt];\n\t\t}\n\n\t\tsolver.solve(b);\n\t\tVectorXf x = solver.x();\n\n\t\tfor (u64 basisIt = 0; basisIt < 6; ++basisIt)\n\t\t{\n\t\t\tambientCube.irradiance[basisIt][channelIt] = x[basisIt];\n\t\t}\n\t}\n\n\treturn ambientCube;\n}\n\nExperimentAmbientCube::AmbientCube ExperimentAmbientCube::solveAmbientCubeProjection(const Image& irradiance)\n{\n\tAmbientCube ambientCube;\n\n\tvec3 cubeDirections[6] =\n\t{\n\t\tvec3(-1.0f, 0.0f, 0.0f),\n\t\tvec3(+1.0f, 0.0f, 0.0f),\n\t\tvec3(0.0f, -1.0f, 0.0f),\n\t\tvec3(0.0f, +1.0f, 0.0f),\n\t\tvec3(0.0f, 0.0f, -1.0f),\n\t\tvec3(0.0f, 0.0f, +1.0f),\n\t};\n\n\tfor(u32 i=0; i<6; ++i)\n\t{\n\t\tvec2 texcoord = cartesianToLatLongTexcoord(cubeDirections[i]);\n\t\tambientCube.irradiance[i] = (vec3)irradiance.sampleNearest(texcoord);\n\t}\n\n\treturn ambientCube;\n}\n\nvoid ExperimentAmbientCube::run(SharedData& data)\n{\n\tAmbientCube ambientCube;\n\n\tif (m_projectionEnabled)\n\t{\n\t\tambientCube = solveAmbientCubeProjection(m_input->m_irradianceImage);\n\t}\n\telse\n\t{\n\t\tambientCube = solveAmbientCubeLeastSquares(data.m_directionImage, m_input->m_irradianceImage);\n\t}\n\n\tm_radianceImage = Image(data.m_outputSize);\n\tm_irradianceImage = Image(data.m_outputSize);\n\n\tdata.m_directionImage.forPixels2D([&](const vec3& direction, ivec2 pixelPos)\n\t{\n\t\tvec3 sampleIrradianceH = ambientCube.evaluate(direction);\n\t\tm_irradianceImage.at(pixelPos) = vec4(sampleIrradianceH, 1.0f);\n\t\tm_radianceImage.at(pixelPos) = vec4(0.0f);\n\t});\n}\n\n}\n", "meta": {"hexsha": "0698c013fe1dfe13306c3a1bd3aacccb47b6e7e3", "size": 2677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/Probulator/ExperimentAmbientCube.cpp", "max_stars_repo_name": "kayru/Probulator", "max_stars_repo_head_hexsha": "b8adb56850fdeac62061d1d733718ee0763f29b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 362.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T20:03:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:15:37.000Z", "max_issues_repo_path": "Source/Probulator/ExperimentAmbientCube.cpp", "max_issues_repo_name": "kayru/Probulator", "max_issues_repo_head_hexsha": "b8adb56850fdeac62061d1d733718ee0763f29b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T14:55:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-07T07:04:46.000Z", "max_forks_repo_path": "Source/Probulator/ExperimentAmbientCube.cpp", "max_forks_repo_name": "kayru/Probulator", "max_forks_repo_head_hexsha": "b8adb56850fdeac62061d1d733718ee0763f29b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2016-03-31T01:12:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:55:30.000Z", "avg_line_length": 20.5923076923, "max_line_length": 146, "alphanum_fraction": 0.682106836, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.6416004239008443}}
{"text": "#include \"math_helper.h\"\n\n#include <iostream>\n#include <Eigen/LU>\n#include <Eigen/Dense>\n\nnamespace recon\n{\n\nnamespace MathHelper\n{\n\nvoid getTopViewHomography(const double* cparams, int src_w, int src_h, int dst_w, int dst_h, \n                          const Eigen::Vector4d& plane, Eigen::Matrix3d& H)\n{\n  double fx = cparams[0];\n  double fy = cparams[1];\n  double cx = cparams[2];\n  double cy = cparams[3];\n\n  Eigen::Vector3d n;\n  n << plane[0], plane[1], plane[2];\n  double d = plane[3];\n  if(d < 0.0) {\n    throw \"Error!\\n\";\n  }\n  std::cout << \"n = \\n\" << n << \"\\n\\n\";\n  std::cout << \"d = \" << d << \"\\n\\n\";\n\n  Eigen::Matrix3d K1 = Eigen::Matrix3d::Identity();\n  K1(0,0) = fx;\n  K1(1,1) = fy;\n  K1(0,2) = cx;\n  K1(1,2) = cy;\n  Eigen::Matrix3d K1_inv = K1.inverse();\n\n  Eigen::Vector3d q1a;\n  Eigen::Vector3d q1b;\n  q1a << (double) 0.0, (double) src_h - 1.0, 1.0;\n  q1b << (double) src_w - 1.0, (double) src_h - 1.0, 1.0;\n  q1a = K1_inv * q1a;\n  q1b = K1_inv * q1b;\n\n  Eigen::Vector3d Q1a, Q1b;\n  Q1a = (-d * q1a) / n.dot(q1a);\n  Q1b = (-d * q1b) / n.dot(q1b);\n  std::cout << \"Q1a:\\n\" << Q1a << \"\\nQ1b:\\n\" << Q1b << \"\\n\\n\";\n\n  // determine R matrix\n  Eigen::Matrix3d R;\n  //Eigen::Vector3d Q1diff = Q1a - Q1b;\n  Eigen::Vector3d Q1diff = Q1b - Q1a;\n  std::cout << Q1diff << \"\\n\";\n  R.row(0) = Q1diff / Q1diff.norm();\n  R.row(2) = -n;\n  R.row(1) = -(R.row(0).cross(R.row(2)));\n\n  std::cout << \"0 == \" << Q1diff.dot(n) << \"\\n\";\n\n  //double Ty = -10.0 - (R.row(1) * Q1a);\n  double Ty = 10.0 - (R.row(1) * Q1a);\n  std::cout << \"Ty = \" << Ty << \"\\n\";\n  Eigen::Vector3d t;\n  t << 0.0, Ty, 0.0;\n\n  Eigen::Vector3d Q2a = R * Q1a + t;\n  Eigen::Vector3d Q2b = R * Q1b + t;\n  std::cout << \"Q2a:\\n\" << Q2a << \"\\nQ2b:\\n\" << Q2b << \"\\n\\n\";;\n  double dst_cx = dst_w / 2.0;\n  double dst_cy = dst_h / 2.0;\n  double f2 = (dst_cy - 1.0) * (Q2a[2] / Q2a[1]);\n\n  Eigen::Matrix3d K2;\n  K2 << f2,   0.0,  dst_cx,\n        0.0,  f2,   dst_cy,\n        0.0,  0.0,  1.0;\n  std::cout << \"K2:\\n\" << K2 << \"\\n\";\n  std::cout << \"q2a:\\n\" << (K2 * Q2a) / Q2a[2] << \"\\nq2b:\\n\" << (K2 * Q2b) / Q2b[2] << \"\\n\\n\";;\n\n  //std::cout << \"d = \" << d << \"\\n\";\n  //std::cout << \"<n,Q1a> = \" << n.dot(Q1a) << \"\\n\\n\";\n  Eigen::Matrix3d H_n = R - ((t * n.transpose()) / d);\n  std::cout << \"Q2a_H:\\n\" << H_n * Q1a << \"\\n\\n\";\n  H = K2 * H_n * K1_inv;\n  Eigen::Vector3d q2a_H = H * q1a;\n  q2a_H = q2a_H / q2a_H[2];\n  std::cout << \"q2a_H:\\n\" << q2a_H << \"\\n\\n\";\n}\n\nvoid debugTopViewHomography(const double* cparams, int src_w, int src_h, int dst_w, int dst_h,\n                            const Eigen::Vector4d& plane, pcl::visualization::PCLVisualizer& viewer)\n{\n  double fx = cparams[0];\n  double fy = cparams[1];\n  double cx = cparams[2];\n  double cy = cparams[3];\n\n  Eigen::Vector3d n;\n  n << plane[0], plane[1], plane[2];\n  double d = plane[3];\n  if(d < 0.0) {\n    throw \"Error!\\n\";\n  }\n  std::cout << \"n = \\n\" << n << \"\\n\\n\";\n  std::cout << \"d = \" << d << \"\\n\\n\";\n\n  Eigen::Matrix3d K1 = Eigen::Matrix3d::Identity();\n  K1(0,0) = fx;\n  K1(1,1) = fy;\n  K1(0,2) = cx;\n  K1(1,2) = cy;\n  Eigen::Matrix3d K1_inv = K1.inverse();\n\n  Eigen::Vector3d q1a;\n  Eigen::Vector3d q1b;\n  q1a << (double) 0.0, (double) src_h - 1.0, 1.0;\n  q1b << (double) src_w - 1.0, (double) src_h - 1.0, 1.0;\n  q1a = K1_inv * q1a;\n  q1b = K1_inv * q1b;\n\n  Eigen::Vector3d Q1a, Q1b;\n  Q1a = (-d * q1a) / n.dot(q1a);\n  Q1b = (-d * q1b) / n.dot(q1b);\n  std::cout << \"Q1a:\\n\" << Q1a << \"\\nQ1b:\\n\" << Q1b << \"\\n\\n\";\n\n  pcl::PointXYZ pt1, pt2;\n  for(int i = 0; i < 3; i++) {\n    pt1.data[i] = Q1a[i];\n    pt2.data[i] = Q1b[i];\n  }\n  viewer.addLine<pcl::PointXYZ, pcl::PointXYZ>(pt1, pt2, 0, 200, 0, \"line1\");\n}\n\nvoid projectPoint(const double* cam_params, Eigen::Vector3d& point, Eigen::Vector2d& proj)\n{\n  double fx = cam_params[0];\n  double fy = cam_params[1];\n  double cx = cam_params[2];\n  double cy = cam_params[3];\n\n  proj[0] = point[0] / point[2];\n  proj[1] = point[1] / point[2];\n  proj[0] = fx * proj[0] + cx;\n  proj[1] = fy * proj[1] + cy;\n}\n\nvoid setTransform2DEM(Eigen::Vector4d& plane_model, Eigen::Matrix4d& transform)\n{\n  Eigen::Vector3d n1, n2;\n  for(int i = 0; i < 3; i++) {\n    n1[i] = plane_model[i];\n    n2[i] = 0.0;\n  }\n  n2[1] = 1.0;\n  // find axis with cross product\n\n  // find angle with dot product\n\n  // move Y with d after rotation\n}\n\nvoid createPolyFromPlane(const Eigen::Vector4d& plane, pcl::PointCloud<pcl::PointXYZ>::Ptr poly_cloud)\n{\n  double a = plane[0];\n  double b = plane[1];\n  double c = plane[2];\n  double d = plane[3];\n\n  double x[4] = {-20, 20, 20, -20};\n  double z[4] = {  0,  0, 100, 100};\n  for(int i = 0; i < 4; i++) {\n    double y = (a*x[i] + c*z[i] + d) / (-b);\n    pcl::PointXYZ pt(x[i], y, z[i]);\n    poly_cloud->points.push_back(pt);\n  }\n}\n\nvoid triangulate(const double (&cam_params)[5], double x, double y, double disp, cv::Mat& pt3d)\n{\n  double f = cam_params[0];\n  double cx = cam_params[2];\n  double cy = cam_params[3];\n  double b = cam_params[4];\n\n  pt3d.at<double>(0) = (x - cx) * b / disp;\n  pt3d.at<double>(1) = (y - cy) * b / disp;\n  pt3d.at<double>(2) = f * b / disp;\n  pt3d.at<double>(3) = 1.0;\n}\n\nvoid getSignedDistancesToModel(const Eigen::Vector4d& plane, const pcl::PointCloud<pcl::PointXYZ>::Ptr pc,\n                                           std::vector<double>& distances)\n{\n  distances.assign(pc->points.size(), 0.0);\n  double a = plane[0];\n  double b = plane[1];\n  double c = plane[2];\n  double d = plane[3];\n  double norm = std::sqrt(a*a + b*b + c*c);\n  for(size_t i = 0; i < pc->points.size(); i++) {\n    pcl::PointXYZ pt = pc->points[i];\n    double p = a*pt.x + b*pt.y + c*pt.z + d;\n    distances[i] = p / norm;\n  }\n}\n\nvoid getDistancesToModel(const Eigen::Vector4d& plane, const pcl::PointCloud<pcl::PointXYZ>::Ptr pc,\n                         std::vector<double>& distances)\n{\n  distances.assign(pc->points.size(), 0.0);\n  double a = plane[0];\n  double b = plane[1];\n  double c = plane[2];\n  double d = plane[3];\n  double norm = std::sqrt(a*a + b*b + c*c);\n  for(size_t i = 0; i < pc->points.size(); i++) {\n    pcl::PointXYZ pt = pc->points[i];\n    double p = a*pt.x + b*pt.y + c*pt.z + d;\n    distances[i] = std::abs(p / norm);\n  }\n}\n\n}\n\n}\n", "meta": {"hexsha": "d55d9abc3331766213de4ec1726dd903062b3a32", "size": 6133, "ext": "cc", "lang": "C++", "max_stars_repo_path": "reconstruction/pcl/math_helper.cc", "max_stars_repo_name": "bartn8/stereo-vision", "max_stars_repo_head_hexsha": "1180045fe560478e5c441e75202cc899fe90ec3d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2016-04-02T18:18:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T11:47:58.000Z", "max_issues_repo_path": "reconstruction/pcl/math_helper.cc", "max_issues_repo_name": "bartn8/stereo-vision", "max_issues_repo_head_hexsha": "1180045fe560478e5c441e75202cc899fe90ec3d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-08-01T14:36:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T08:15:50.000Z", "max_forks_repo_path": "reconstruction/pcl/math_helper.cc", "max_forks_repo_name": "bartn8/stereo-vision", "max_forks_repo_head_hexsha": "1180045fe560478e5c441e75202cc899fe90ec3d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2016-08-25T11:28:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T12:17:47.000Z", "avg_line_length": 27.1371681416, "max_line_length": 106, "alphanum_fraction": 0.5442687103, "num_tokens": 2479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6415601640658691}}
{"text": "#include <NTL/mat_poly_lzz_p.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\nstatic\nvoid HessCharPoly(zz_pX& g, const zz_pX& a, const zz_pX& f)\n{\n   long n = deg(f);\n   if (n <= 0 || deg(a) >= n)\n      Error(\"HessCharPoly: bad args\");\n\n   mat_zz_p M;\n   M.SetDims(n, n);\n\n   long i, j;\n\n   zz_pX t;\n   t = a;\n\n   for (i = 0; i < n; i++) {\n      for (j = 0; j < n; j++) \n         M[i][j] = coeff(t, j);\n\n      if (i < n-1) \n         MulByXMod(t, t, f);\n   }\n\n   CharPoly(g, M);\n}\n\nvoid CharPolyMod(zz_pX& g, const zz_pX& a, const zz_pX& ff)\n{\n   zz_pX f = ff;\n   MakeMonic(f);\n   long n = deg(f);\n\n   if (n <= 0 || deg(a) >= n) \n      Error(\"CharPoly: bad args\");\n\n   if (IsZero(a)) {\n      clear(g);\n      SetCoeff(g, n);\n      return;\n   }\n\n   if (n > 90 || (zz_p::PrimeCnt() <= 1 && n > 45)) {\n      zz_pX h;\n      MinPolyMod(h, a, f);\n      if (deg(h) == n) {\n         g = h;\n         return;\n      }\n   }\n\n   if (zz_p::modulus() < n+1) {\n      HessCharPoly(g, a, f);\n      return;\n   }\n\n   vec_zz_p u(INIT_SIZE, n+1), v(INIT_SIZE, n+1);\n\n   zz_pX h, h1;\n   negate(h, a);\n   long i;\n\n   for (i = 0; i <= n; i++) {\n      u[i] = i;\n      add(h1, h, u[i]);\n      resultant(v[i], f, h1);\n   }\n\n   interpolate(g, u, v);\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "87dfda6ebc9ab404a6b080be7111873ec76b6aff", "size": 1228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/lzz_pXCharPoly.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T20:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:52:14.000Z", "max_issues_repo_path": "RUNETag/WinNTL/src/lzz_pXCharPoly.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/src/lzz_pXCharPoly.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 15.7435897436, "max_line_length": 59, "alphanum_fraction": 0.4600977199, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6414869480051827}}
{"text": "/*\n2019.03.29 by Aurora. Contact:fanyi@mail.ustc.edu.cn\n\nUtilities functions.\n\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n/*#include <complex.h>*/\n#include <algorithm>\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n#include \"struct.h\"\n\n/*****************MACRO FOR DEBUG*****************/\n#define DEBUG_UTIL\n\n#ifdef DEBUG_UTIL\n#define printf_d printf\n#else\n#define printf_d //\n#endif\n/***************MACRO FOR DEBUG END***************/\n\n#define PI 3.141592653589793238462643383279\n\n\ndouble s_r(double r_ij, parameters_info_struct * parameters_info)\n{\n    double result;\n    double rc = parameters_info->cutoff_2;\n    double rcs = parameters_info->cutoff_1;\n    result = (r_ij >= rc) ? 0 : ((r_ij >= rcs) ? 1 / r_ij * (0.5 * cos((r_ij - rcs) / (rc - rcs) * PI) + 0.5) : 1 / r_ij);\n    return result;\n}\n\ndouble fastpow2(double number, int dummy)\n{\n    return number * number;\n}\n\ndouble fastpown(double number, int power)\n{\n    int i;\n    double result = 1;\n    int N = power;\n    if (power == 0)\n    {\n        return 1;\n    }\n    if (power < 0)\n    {\n        N *= -1;\n    }\n    for (i = 1; i <= N; i++)\n    {\n        result *= number;\n    }\n    if (power < 0)\n    {\n        return 1.0 / result;\n    }\n    else\n    {\n        return result;\n    }\n    \n}\n\ndouble f_c(double r_ij, double r_c)\n{\n    double result;\n    double rc = r_c;\n    result = (r_ij <= rc) ? 0.5 * tanh(1 - r_ij / rc) * tanh(1 - r_ij / rc) * tanh(1 - r_ij / rc) : 0;\n    return result;\n}\n\ndouble d_f_c_d_r(double r_ij, double r_c)\n{\n    double result;\n    double rc = r_c;\n    result = (r_ij <= rc) ? (-3.0 / cosh(1 - r_ij / rc) / cosh(1 - r_ij / rc) * tanh(1 - r_ij / rc) * tanh(1 - r_ij / rc) / 2.0 / rc ) : (0);\n    return result;\n}\n\ndouble R_sup_n(double r_ij, double n, double r_c)\n{\n    double f_c(double r_ij, double r_c);\n\n    double result;\n    return fastpown(r_ij, (int)n) * f_c(r_ij, r_c);\n}\n\ndouble d_R_sup_n_d_r(double r_ij, double n, double r_c)\n{\n    double f_c(double r_ij, double r_c);\n    double d_f_c_d_r(double r_ij, double r_c);\n    double result;\n\n    result = n * fastpown(r_ij, (int)(n - 1)) * f_c(r_ij, r_c) + fastpown(r_ij, (int)n) * d_f_c_d_r(r_ij, r_c);\n    return result;\n}\n\ndouble factorial(int n)\n{\n    if (n < 0)\n    {\n        printf(\"From factorial: n must be positive!\\n\");\n        exit(999);\n    }\n    return ((n == 0)||(n == 1)) ? 1 : factorial(n - 1) * n;\n}\n\n/*double P_LM(double x, int l, int m)\n{\n    double factorial(int n);\n\n    if (m < 0)\n    {\n        return pow(-1, -m) * factorial(l + m) / factorial(l - m) * P_LM(x, l, (-1) * m);\n    }\n\n    switch (l)\n    {\n        case 0:\n        {\n            return 1.0;\n        }\n        case 1:\n        {\n            switch (m)\n            {\n                case 0:\n                {\n                    return x;\n                }\n                case 1:\n                {\n                    return -1 * sqrt(1 - x * x);\n                }\n            }\n        }\n        case 2:\n        {\n            switch (m)\n            {\n                case 0:\n                {\n                    return 0.5 * (3 * x * x - 1);\n                }\n                case 1:\n                {\n                    return -3 * x * sqrt(1 - x * x);\n                }\n                case 2:\n                {\n                    return 3 * (1 - x * x);\n                }\n            }\n        }\n        case 3:\n        {\n            switch (m)\n            {\n                case 0:\n                {\n                    return 0.5 * x * (5 * x * x - 3);\n                }\n                case 1:\n                {\n                    return 1.5 * (1 - 5 * x * x) * sqrt(1 - x * x);\n                }\n                case 2:\n                {\n                    return 15 * x * (1 - x * x);\n                }\n                case 3:\n                {\n                    return -15 * sqrt(1 - x * x) * sqrt(1 - x * x) * sqrt(1 - x * x);\n                }\n            }\n        }\n        case 4:\n        {\n            switch (m)\n            {\n                case 0:\n                {\n                    return 0.125 * (35 * x * x * x * x - 30 * x * x + 3);\n                }\n                case 1:\n                {\n                    return 2.5 * x * (3 - 7 * x * x) * sqrt(1 - x * x); \n                }\n                case 2:\n                {\n                    return 7.5 * (7 * x * x - 1) * (1 - x * x);\n                }\n                case 3:\n                {\n                    return -105 * x * sqrt(1 - x * x) * sqrt(1 - x * x) * sqrt(1 - x * x);\n                }\n                case 4:\n                {\n                    return 105 * (1 - x * x) * (1 - x * x);\n                }\n            }\n        }\n        case 5:\n        {\n            switch (m)\n            {\n                case 0:\n                {\n                    return 0.125 * x * (63 * x * x * x * x - 70 * x * x + 15);\n                }\n            }\n        }\n        default:\n        {\n            printf(\"From P_LM: Invalid value of l and m!\\n\");\n            exit(999);\n        }\n    }\n}*/\n\n/*double complex Y_LM(double * r_ij, int l, int m)//here r_ij is a vector\n{\n    double P_LM(double cos_theta, int l, int m);\n    double factorial(int n);\n\n    double complex result;\n    double theta, phi;\n    double r = sqrt(r_ij[0] * r_ij[0] + r_ij[1] * r_ij[1] + r_ij[2] * r_ij[2]);\n    theta = acos(r_ij[2] / r);\n    phi = atan(r_ij[1] / r_ij[0]);\n    result = sqrt((2 * l + 1) / (4 * PI) * factorial(l - m) / factorial(l + m)) * P_LM(cos(theta), l, m) * cexp(m * phi * I);\n    return result;\n}*/\n\ndouble Y_LM_r(double * coord_ij, int L, int m)//here L is n of the boost::math::spherical_harmonics\n{\n    double theta, phi;\n    double r = sqrt(coord_ij[0] * coord_ij[0] + coord_ij[1] * coord_ij[1] + coord_ij[2] * coord_ij[2]);\n    double result_r;\n    theta = acos(coord_ij[2] / r);\n    phi = atan(coord_ij[1] / coord_ij[0]);\n    result_r = boost::math::spherical_harmonic_r(L, m, theta, phi);\n    return result_r;\n}\ndouble Y_LM_i(double * coord_ij, int L, int m)//here L is n of the boost::math::spherical_harmonics\n{\n    double theta, phi;\n    double r = sqrt(coord_ij[0] * coord_ij[0] + coord_ij[1] * coord_ij[1] + coord_ij[2] * coord_ij[2]);\n    double result_i;\n    theta = acos(coord_ij[2] / r);\n    phi = atan(coord_ij[1] / coord_ij[0]);\n    result_i = boost::math::spherical_harmonic_i(L, m, theta, phi);\n    return result_i;\n}\nstd::complex<double> Y_LM(double * coord_ij, int L, int m)\n{\n    double theta, phi;\n    double r = sqrt(coord_ij[0] * coord_ij[0] + coord_ij[1] * coord_ij[1] + coord_ij[2] * coord_ij[2]);\n    std::complex<double> result;\n    theta = acos(coord_ij[2] / r);\n    phi = atan(coord_ij[1] / coord_ij[0]);\n    if (phi < 0)\n    {\n        phi += (2 * PI);\n    }\n    //printf_d(\"L, m, theta, phi: %d, %d, %.6lf, %.6lf\\n\", L, m, theta, phi);\n    result = boost::math::spherical_harmonic(L, m, theta, phi);\n    return result;\n}\nstd::complex<double> d_Y_LM_d_theta(double * coord_ij, int L, int m)\n{\n    double theta, phi;\n    double r = sqrt(coord_ij[0] * coord_ij[0] + coord_ij[1] * coord_ij[1] + coord_ij[2] * coord_ij[2]);\n    std::complex<double> result;\n    std::complex<double> I(0.0, 1.0);\n    theta = acos(coord_ij[2] / r);\n    phi = atan(coord_ij[1] / coord_ij[0]);\n    if (phi < 0)\n    {\n        phi += (2 * PI);\n    }\n    /*\\partial Y/\\partial \\theta = m * cot(\\theta) * Y_LM(\\theta, \\phi) + \\sqrt((L-m) * (L + m + 1)) * exp(- I * \\phi) * Y_L(M+1)(\\theta, \\phi)*/\n    result = m * tan((double)PI / 2.0 - theta) * boost::math::spherical_harmonic(L, m, theta, phi) + sqrt((L-m) * (L + m + 1)) * exp(-I * phi) * boost::math::spherical_harmonic(L, m + 1, theta, phi);\n    return result;\n}\nstd::complex<double> d_Y_LM_d_phi(double * coord_ij, int L, int m)\n{\n    double theta, phi;\n    double r = sqrt(coord_ij[0] * coord_ij[0] + coord_ij[1] * coord_ij[1] + coord_ij[2] * coord_ij[2]);\n    std::complex<double> result;\n    std::complex<double> I(0.0, 1.0);\n    theta = acos(coord_ij[2] / r);\n    phi = atan(coord_ij[1] / coord_ij[0]);\n    if (phi < 0)\n    {\n        phi += (2 * PI);\n    }\n    /*\\partial Y/\\partial \\phi = I * m * Y_LM(\\theta, \\phi)*/\n    result = I * (double)m * boost::math::spherical_harmonic(L, m, theta, phi);\n    return result;\n}\n\ndouble cos_bond_angle(double * coord_i, double * coord_j, double * coord_k)//centered at i\n{\n    double coord_ji[3];// In DeePMD type sym_coord, r_ji means r_(j - i). Here we keep the same.\n    double coord_ki[3];\n    double norm_ji, norm_ki;//norm = (x^2 + y^2 + z^2)\n    double dot_jiki = 0;\n    double result = 0;\n    int i, j, k;\n    norm_ji =0; norm_ki = 0;\n    for (i = 0; i <= 2; i++)\n    {\n        coord_ji[i] = coord_j[i] - coord_i[i];\n        coord_ki[i] = coord_k[i] - coord_i[i];\n        norm_ji += (coord_ji[i] * coord_ji[i]);\n        norm_ki += (coord_ki[i] * coord_ki[i]);\n        dot_jiki += (coord_ji[i] * coord_ki[i]);\n    }\n    /*cos(\\theta_ijk_centered_i) = dot_prod(coord_ji, coord_ki) / \\sqrt(norm_ji * norm_ki)*/\n    result = dot_jiki / sqrt(norm_ji * norm_ki);\n    return result;\n}\nint d_cos_bond_angle_d_coord(double * coord_i, double * coord_j, double * coord_k, double * result)\n{\n    double fastpown(double number, int power);\n\n    double coord_ji[3];// In DeePMD type sym_coord, r_ji means r_(j - i). Here we keep the same.\n    double coord_ki[3];\n    double norm_ji = 0;\n    double norm_ki = 0;//norm = (x^2 + y^2 + z^2)\n    double dot_jiki = 0;\n    //double result = 0;\n    int i, j, k;\n    //norm_ji =0; norm_ki = 0;\n    for (i = 0; i <= 2; i++)\n    {\n        coord_ji[i] = coord_j[i] - coord_i[i];\n        coord_ki[i] = coord_k[i] - coord_i[i];\n        norm_ji += (coord_ji[i] * coord_ji[i]);\n        norm_ki += (coord_ki[i] * coord_ki[i]);\n        dot_jiki += (coord_ji[i] * coord_ki[i]);\n    }\n    double dist_ji = sqrt(norm_ji);\n    double dist_ki = sqrt(norm_ki);\n    /*dxi, yi, zi, xj, yj, zj, xk, yk, zk*/\n    result[0] = (- coord_ji[0] - coord_ki[0]) / (dist_ji * dist_ki) - (dot_jiki * (- 2 * coord_ki[0] * norm_ji - 2 * coord_ji[0] * norm_ki)) / ( 2 * fastpown((dist_ji * dist_ki), 3));\n    result[1] = (- coord_ji[1] - coord_ki[1]) / (dist_ji * dist_ki) - (dot_jiki * (- 2 * coord_ki[1] * norm_ji - 2 * coord_ji[1] * norm_ki)) / ( 2 * fastpown((dist_ji * dist_ki), 3));\n    result[2] = (- coord_ji[2] - coord_ki[2]) / (dist_ji * dist_ki) - (dot_jiki * (- 2 * coord_ki[2] * norm_ji - 2 * coord_ji[2] * norm_ki)) / ( 2 * fastpown((dist_ji * dist_ki), 3));\n    result[3] = coord_ki[0] / (dist_ji * dist_ki) - coord_ji[0] * norm_ki * dot_jiki / fastpown((dist_ji * dist_ki), 3);\n    result[4] = coord_ki[1] / (dist_ji * dist_ki) - coord_ji[1] * norm_ki * dot_jiki / fastpown((dist_ji * dist_ki), 3);\n    result[5] = coord_ki[2] / (dist_ji * dist_ki) - coord_ji[1] * norm_ki * dot_jiki / fastpown((dist_ji * dist_ki), 3);\n    result[6] = coord_ji[0] / (dist_ji * dist_ki) - coord_ki[0] * norm_ki * dot_jiki / fastpown((dist_ji * dist_ki), 3);\n    result[7] = coord_ji[1] / (dist_ji * dist_ki) - coord_ki[1] * norm_ki * dot_jiki / fastpown((dist_ji * dist_ki), 3);\n    result[8] = coord_ji[2] / (dist_ji * dist_ki) - coord_ki[1] * norm_ki * dot_jiki / fastpown((dist_ji * dist_ki), 3);\n    \n    return 0;\n}\n\n\nint cross_prod(double * vec1, double * vec2, double * vec_result)\n{\n    vec_result[0] = (vec1[1] * vec2[2] - vec1[2] * vec2[1]);\n    vec_result[1] = (vec1[2] * vec2[0] - vec1[0] * vec2[2]);\n    vec_result[2] = (vec1[0] * vec2[1] - vec1[1] * vec2[0]);\n    return 0;\n}\ndouble cos_dihedral_angle(double * coord_i, double * coord_j, double * coord_k, double * coord_l)//centered at i and j, plane_ijk and plane_ijl\n{\n    int cross_prod(double * vec1, double * vec2, double * vec_result);\n\n    /*Use coord_ki, ji to calculate norm_vec of plane_kij = ji \\times ki; Use coord_ij, lj to calculate norm_vec of plane_ijl = ij \\times lj*/\n    double coord_ki[3];// In DeePMD type sym_coord, r_ji means r_(j - i). Here we keep the same.\n    double coord_ji[3];\n    double coord_ij[3];\n    double coord_lj[3];\n    double norm_vec_kij[3];\n    double norm_vec_ijl[3];\n    double norm_norm_vec_kij = 0;//norm = (x^2 + y^2 + z^2)\n    double norm_norm_vec_ijl = 0;\n    double dot_kij_ijl = 0;\n    double result;\n    int error_code;\n    int i, j, k;\n    for (i = 0; i <= 2; i++)\n    {\n        coord_ki[i] = coord_k[i] - coord_i[i];\n        coord_ji[i] = coord_j[i] - coord_i[i];\n        coord_ij[i] = coord_i[i] - coord_j[i];\n        coord_lj[i] = coord_l[i] - coord_j[i];\n    }\n    error_code = cross_prod(coord_ji, coord_ki, norm_vec_kij);\n    error_code = cross_prod(coord_ij, coord_lj, norm_vec_ijl);\n    for (i = 0 ; i <= 2; i++)\n    {\n        norm_norm_vec_kij += (norm_vec_kij[i] * norm_vec_kij[i]);\n        norm_norm_vec_ijl += (norm_vec_ijl[i] * norm_vec_ijl[i]);\n        dot_kij_ijl += norm_vec_kij[i] * norm_vec_ijl[i];\n    }\n    if (norm_norm_vec_kij * norm_norm_vec_ijl == 0)//three points are on a line; no plane is formed.\n    {\n        return 999;\n    }\n    result = dot_kij_ijl / sqrt(norm_norm_vec_kij * norm_norm_vec_ijl) * ((double)-1.0);\n    return result;\n}\n\nint d_cos_dihedral_angle_d_coord(double * coord_i, double * coord_j, double * coord_k, double * coord_l, double * result)//centered at i and j, plane_ijk and plane_ijl\n{\n    int cross_prod(double * vec1, double * vec2, double * vec_result);\n\n    /*Use coord_ki, ji to calculate norm_vec of plane_kij = ji \\times ki; Use coord_ij, lj to calculate norm_vec of plane_ijl = ij \\times lj*/\n    double coord_ki[3];// In DeePMD type sym_coord, r_ji means r_(j - i). Here we keep the same.\n    double coord_ji[3];\n    double coord_ij[3];\n    double coord_lj[3];\n    double norm_vec_kij[3];\n    double norm_vec_ijl[3];\n    double norm_norm_vec_kij = 0;//norm = (x^2 + y^2 + z^2)\n    double norm_norm_vec_ijl = 0;\n    double dot_kij_ijl = 0;\n    double xi, yi, zi, xj, yj, zj, xk, yk, zk, xl, yl, zl;\n    xi = coord_i[0]; yi = coord_i[1]; zi=coord_i[2];\n    xj = coord_j[0]; yj = coord_j[1]; zj=coord_j[2];\n    xk = coord_k[0]; yk = coord_k[1]; zk=coord_k[2];\n    xl = coord_l[0]; yl = coord_l[1]; zl=coord_l[2];\n    //double result;\n    int error_code;\n    int i, j, k;\n    for (i = 0; i <= 2; i++)\n    {\n        coord_ki[i] = coord_k[i] - coord_i[i];\n        coord_ji[i] = coord_j[i] - coord_i[i];\n        coord_ij[i] = coord_i[i] - coord_j[i];\n        coord_lj[i] = coord_l[i] - coord_j[i];\n    }\n    error_code = cross_prod(coord_ji, coord_ki, norm_vec_kij);\n    error_code = cross_prod(coord_ij, coord_lj, norm_vec_ijl);\n    for (i = 0 ; i <= 2; i++)\n    {\n        norm_norm_vec_kij += (norm_vec_kij[i] * norm_vec_kij[i]);\n        norm_norm_vec_ijl += (norm_vec_ijl[i] * norm_vec_ijl[i]);\n        dot_kij_ijl += norm_vec_kij[i] * norm_vec_ijl[i];\n    }\n    /*dxi, yi, zi, xj, yj, zj, xk, yk, zk, xl, yl, zl*/\n    result[0] = (-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-yj+yl))-(yj-yk)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*(zj-zl)-(-zj+zk)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)))-((-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))*((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(2*(-yj+yl)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl))+2*(zj-zl)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl)))+(2*(yj-yk)*(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))+2*(-zj+zk)*((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk)))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2))))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5));\n    result[1] = (-((xj-xl)*(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk)))-(-xj+xk)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-zj+zl)-(zj-zk)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)))-((-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))*((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(2*(xj-xl)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl))+2*(-zj+zl)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))+(2*(-xj+xk)*(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))+2*(zj-zk)*(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk)))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2))))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5));\n    result[2] = (-((-xj+xl)*((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk)))-(yj-yl)*(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))-(xj-xk)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-yj+yk)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)))-((-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))*((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(2*(-xj+xl)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))+2*(yj-yl)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))+(2*(xj-xk)*((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))+2*(-yj+yk)*(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk)))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2))))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5));\n    result[3] = (-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(yi-yl))-(-yi+yk)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*(-zi+zl)-(zi-zk)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)))-((-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))*((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(2*(yi-yl)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl))+2*(-zi+zl)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl)))+(2*(-yi+yk)*(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))+2*(zi-zk)*((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk)))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2))))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5));\n    result[4] = (-((-xi+xl)*(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk)))-(xi-xk)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(zi-zl)-(-zi+zk)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)))-((-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))*((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(2*(-xi+xl)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl))+2*(zi-zl)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))+(2*(xi-xk)*(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))+2*(-zi+zk)*(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk)))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2))))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5));\n    result[5] = (-((xi-xl)*((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk)))-(-yi+yl)*(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))-(-xi+xk)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(yi-yk)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)))-((-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))*((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(2*(xi-xl)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))+2*(-yi+yl)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))+(2*(-xi+xk)*((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))+2*(yi-yk)*(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk)))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2))))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5));\n    result[6] = -((2*(yi-yj)*(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))+2*(-zi+zj)*((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk)))*(-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5))+(-((yi-yj)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-(-zi+zj)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)));\n    result[7] = -((2*(-xi+xj)*(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))+2*(zi-zj)*(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk)))*(-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5))+(-((-xi+xj)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-(zi-zj)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)));\n    result[8] = -((2*(xi-xj)*((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))+2*(-yi+yj)*(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk)))*(-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5))+(-((xi-xj)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl)))-(-yi+yj)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)));\n    result[9] = -((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(2*(-yi+yj)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl))+2*(zi-zj)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl)))*(-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl))))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5))+(-((-yi+yj)*(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk)))-(zi-zj)*((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)));\n    result[10] = -((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(2*(xi-xj)*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl))+2*(-zi+zj)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))*(-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl))))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5))+(-((xi-xj)*(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk)))-(-zi+zj)*(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)));\n    result[11] = -((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(2*(-xi+xj)*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))+2*(yi-yj)*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl)))*(-((-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk))*(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl)))-((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk))*((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl))-(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk))*(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl))))/(2.*pow((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)),1.5))+(-((-xi+xj)*((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk)))-(yi-yj)*(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk)))/sqrt((pow(-((-xi+xk)*(-yi+yj))+(-xi+xj)*(-yi+yk),2)+pow((-xi+xk)*(-zi+zj)+(xi-xj)*(-zi+zk),2)+pow(-((-yi+yk)*(-zi+zj))+(-yi+yj)*(-zi+zk),2))*(pow(-((-xj+xl)*(yi-yj))+(xi-xj)*(-yj+yl),2)+pow((-xj+xl)*(zi-zj)+(-xi+xj)*(-zj+zl),2)+pow(-((-yj+yl)*(zi-zj))+(yi-yj)*(-zj+zl),2)));\n    //result = dot_kij_ijl / sqrt(norm_norm_vec_kij * norm_norm_vec_ijl) * ((double)-1.0);\n    return 0;\n}\n\n\nint calc_N_neigh_inter(int K, int N)// total N types; K body interaction; MULTIPLY N to the return value to get correct answer!!!\n{\n    int i;\n    int result = 0;\n    if (K == 1) return 1;\n    if (N == 1) return 1;\n    for (i = 1; i <= N; i++)\n    {\n        result += calc_N_neigh_inter(K - 1, i);\n    }\n    return result;\n}\n\nint compare_Nei_type(int N_neighb_atom, int * current_type, int * params_type)//For example, current_type = {1, 8, 8}, params_type = {8, 1, 8}, then return 1\n{\n    int i, j, k;\n    int sum = 0;\n    /*std::vector<int> current_type_ (current_type, current_type + N_neighb_atom);\n    std::vector<int> params_type_ (params_type, params_type + N_neighb_atom);*/\n    for (i = 0; i <= N_neighb_atom - 1; i++)\n    {\n        if (current_type[i] == -1)\n        {\n            return 0;\n        }\n    }\n    if (params_type[0] == -1)\n    {\n        return 1;\n    }\n    /*std::sort(current_type_.begin(), current_type_.end());\n    std::sort(params_type_.begin(), params_type_.end());\n    for (i = 0; i <= N_neighb_atom - 1; i++)\n    {\n        sum += ((current_type_[i] - params_type_[i]) * (current_type_[i] - params_type_[i]));\n    }\n    return ( sum == 0 ? 1 : 0);*/\n    switch (N_neighb_atom)\n    {\n        case 1://two body\n        {\n            if (current_type[0] == params_type[0])\n            {\n                return 1;\n            }\n            break;\n        }\n        case 2://three body\n        {\n            if ((((current_type[0] == params_type[0])&&(current_type[1] == params_type[1]))) || (((current_type[0] == params_type[1])&&(current_type[1] == params_type[0]))))\n            {\n                return 1;\n            }\n            break;\n        }\n        case 3://four body\n        {\n            int mul1 = current_type[0] * current_type[1] * current_type[2];\n            int mul2 = params_type[0] * params_type[1] * params_type[2];\n            int sum1 = current_type[0] + current_type[1] + current_type[2];\n            int sum2 = params_type[0] + params_type[1] + params_type[2];\n            if ((mul1 == mul2)&&(sum1 == sum2))\n            {\n                return 1;\n            }\n            break;\n        }\n    }\n    return 0;\n}\n\nint find_index_int(int target, int * array, int array_length)\n{\n    std::vector<int> array_ (array, array + array_length);\n    std::vector<int>::iterator it = std::find(array_.begin(), array_.end(), target);\n    int index = std::distance(array_.begin(), it);\n    return index;\n}\n\ndouble **** calloc_params_LASP(int dim1, int dim2, int ** dim3_, int ** dim4_)\n{\n    int N_types_all_frame = dim1;\n    int N_PTSD_types = dim2;\n    int ** N_cutoff_radius = dim3_;\n    int ** N_neigh_inter = dim4_;\n    int i, j, k, l;\n    double **** result = NULL;\n    result = (double ****)calloc(dim1, sizeof(double ***));\n    for (i = 0; i <= dim1 - 1; i++)\n    {\n        result[i] = (double ***)calloc(dim2, sizeof(double **));\n        for (j = 0 ; j <= dim2 - 1; j++)\n        {\n            result[i][j] = (double **)calloc(N_cutoff_radius[i][j], sizeof(double *));\n            for (k = 0; k <= N_cutoff_radius[i][j] - 1; k++)\n            {\n                result[i][j][k] = (double *)calloc(N_neigh_inter[i][j], sizeof(double));\n            }\n        }\n    }\n    return result;\n}\n\nint free_params_LASP(double **** target, int dim1, int dim2, int ** dim3_, int ** dim4_)\n{\n    return 1;\n}\n\nint free_sym_coord(void * sym_coord_, int sym_coord_type, parameters_info_struct * parameters_info)\n{\n    switch (sym_coord_type)\n    {\n        case 1:\n        {\n            int i, j;\n            sym_coord_DeePMD_struct * sym_coord_DeePMD = (sym_coord_DeePMD_struct *)sym_coord_;\n            for (i = 0; i <= parameters_info->Nframes_tot - 1; i++)\n            {\n                //free(sym_coord_DeePMD[i].type);\n                for (j = 0; j <= sym_coord_DeePMD[i].N_Atoms - 1; j++)\n                {\n                    free(sym_coord_DeePMD[i].coord_converted[j]);\n                    free(sym_coord_DeePMD[i].d_to_center_x[j]);\n                    free(sym_coord_DeePMD[i].d_to_center_y[j]);\n                    free(sym_coord_DeePMD[i].d_to_center_z[j]);\n                }\n\n                free(sym_coord_DeePMD[i].coord_converted);\n                free(sym_coord_DeePMD[i].d_to_center_x);\n                free(sym_coord_DeePMD[i].d_to_center_y);\n                free(sym_coord_DeePMD[i].d_to_center_z);\n            }\n            free(sym_coord_DeePMD);\n            return 0;\n            break;\n        }\n        case 2:\n        {\n            int i, j, k;\n            sym_coord_LASP_struct * sym_coord_LASP = (sym_coord_LASP_struct *)sym_coord_;\n            for (i = 0; i <= parameters_info->Nframes_tot - 1; i++)\n            {\n                //free(sym_coord_DeePMD[i].type);\n                for (j = 0; j <= sym_coord_LASP[i].N_Atoms - 1; j++)\n                {\n                    free(sym_coord_LASP[i].coord_converted[j]);\n                    for (k = 0; k <= parameters_info->N_sym_coord - 1; k++)\n                    {\n                        free(sym_coord_LASP[i].idx_nei[j][k]);\n                        free(sym_coord_LASP[i].d_x[j][k]);\n                        free(sym_coord_LASP[i].d_y[j][k]);\n                        free(sym_coord_LASP[i].d_z[j][k]);\n                    }\n                    free(sym_coord_LASP[i].idx_nei[j]);\n                    free(sym_coord_LASP[i].d_x[j]);\n                    free(sym_coord_LASP[i].d_y[j]);\n                    free(sym_coord_LASP[i].d_z[j]);\n                    /*Not completed\n                    free(sym_coord_LASP[i].d_to_center_x[j]);\n                    free(sym_coord_LASP[i].d_to_center_y[j]);\n                    free(sym_coord_LASP[i].d_to_center_z[j]);*/\n                }\n\n                free(sym_coord_LASP[i].coord_converted);\n                free(sym_coord_LASP[i].idx_nei);\n                free(sym_coord_LASP[i].d_x);\n                free(sym_coord_LASP[i].d_y);\n                free(sym_coord_LASP[i].d_z);\n                /*Not completed\n                free(sym_coord_LASP[i].d_to_center_x);\n                free(sym_coord_LASP[i].d_to_center_y);\n                free(sym_coord_LASP[i].d_to_center_z);*/\n            }\n            free(sym_coord_LASP);\n            return 0;\n            break;\n        }\n        default:\n        {\n            break;\n        }\n    }\n    return 0;\n\n}\n\nint cart_to_frac(double * cart, double box[3][3], double * frac)\n{\n    double a1 = box[0][0], a2 = box[0][1], a3 = box[0][2], b1 = box[1][0], b2 = box[1][1], b3 = box[1][2], c1 = box[2][0], c2 = box[2][1], c3 = box[2][2];\n    double denominator = (a1 * b2 * c3 + b1 * c2 * a3 + c1 * a2 * b3 - c1 * b2 * a3 - b1 * a2 * c2 - a1 * c2 * b3);\n    if (denominator == 0)\n    {\n        return 1;//Two or more box vectors are parallel.\n    }\n    /*Don't forget the tranpose in the reverse-matrix formula!*/\n    double prefact = 1.0 / denominator;\n    double rev_a1 = prefact * (b2 * c3 - c2 * b3);\n    double rev_b1 = prefact * (c1 * b3 - b1 * c3);\n    double rev_c1 = prefact * (b1 * c2 - c1 * b2);\n    double rev_a2 = prefact * (c2 * a3 - a2 * c3);\n    double rev_b2 = prefact * (a1 * c3 - c1 * a3);\n    double rev_c2 = prefact * (c1 * a2 - a1 * c2);\n    double rev_a3 = prefact * (a2 * b3 - b2 * a3);\n    double rev_b3 = prefact * (b1 * a3 - a1 * b3);\n    double rev_c3 = prefact * (a1 * b2 - b1 * a2);\n    double x = cart[0], y = cart[1], z = cart[2];\n    *frac = rev_a1 * x + rev_b1 * y + rev_c1 * z;\n    *(frac + 1) = rev_a2 * x + rev_b2 * y + rev_c2 * z;\n    *(frac + 2) = rev_a3 * x + rev_b3 * y + rev_c3 * z;\n    return 0;\n}\nint frac_to_cart(double * cart, double box[3][3], double * frac)\n{\n    double a1 = box[0][0], a2 = box[0][1], a3 = box[0][2], b1 = box[1][0], b2 = box[1][1], b3 = box[1][2], c1 = box[2][0], c2 = box[2][1], c3 = box[2][2];\n    double x_ = frac[0], y_ = frac[1], z_ = frac[2];\n    *cart = a1 * x_ + b1 * y_ + c1 * z_;\n    *(cart + 1) = a2 * x_ + b2 * y_ + c2 * z_;\n    *(cart + 2) = a3 * x_ + b3 * y_ + c3 * z_;\n    return 0;\n}\n\ndouble max(double a, double b)\n{\n    return (a >= b ? a : b);\n}\n\n\n\n", "meta": {"hexsha": "819c7a3c47fdc9a54b9d24aa8c46fa09a62053e1", "size": 38677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c/Utilities.cpp", "max_stars_repo_name": "auroraustc/Torch-NNMD", "max_stars_repo_head_hexsha": "1023b0cb063700094990637efe0ddba2fd22798c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-15T15:30:42.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-15T15:30:42.000Z", "max_issues_repo_path": "c/Utilities.cpp", "max_issues_repo_name": "auroraustc/TorchANN", "max_issues_repo_head_hexsha": "1023b0cb063700094990637efe0ddba2fd22798c", "max_issues_repo_licenses": ["MIT"], "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/Utilities.cpp", "max_forks_repo_name": "auroraustc/TorchANN", "max_forks_repo_head_hexsha": "1023b0cb063700094990637efe0ddba2fd22798c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.4111747851, "max_line_length": 1488, "alphanum_fraction": 0.4816557644, "num_tokens": 15940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6414869372652258}}
{"text": "// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n#include <OpenTissue/core/spline/spline.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <boost/test/auto_unit_test.hpp>\r\n\r\n// Boost Test declaration and Checking macros\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\ntypedef OpenTissue::spline::MathTypes<double, size_t>    math_types;\r\ntypedef math_types::matrix_type                                matrix_type;\r\ntypedef std::vector<double>                                    knot_container;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_spline_compute_basis_derivatives);  \r\n\r\nBOOST_AUTO_TEST_CASE(test_compute_basis_derivatives)\r\n{\r\n  knot_container U;\r\n\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);  //k = 3\r\n  U.push_back(1.0);\r\n  U.push_back(2.0);\r\n  U.push_back(3.0);\r\n  U.push_back(4.0);  // n = 6  => |P| = 7\r\n  U.push_back(5.0);\r\n  U.push_back(5.0);\r\n  U.push_back(5.0);  // m = 9  => |U| = 10\r\n\r\n  // Indices of basis functions belongs to the interval [0..n]\r\n\r\n  double const tolerance = 0.00001;\r\n\r\n  // u-parameter at half-way\r\n  {\r\n    double const u = 2.5;\r\n\r\n    matrix_type dQ;\r\n    BOOST_CHECK_NO_THROW( OpenTissue::spline::detail::compute_basis_derivatives(u, 2, 3, U, dQ) );\r\n\r\n    BOOST_CHECK_CLOSE(dQ(0,0), 1.0/8.0,  tolerance);\r\n    BOOST_CHECK_CLOSE(dQ(0,1), 6.0/8.0,  tolerance);\r\n    BOOST_CHECK_CLOSE(dQ(0,2), 1.0/8.0,  tolerance);\r\n    BOOST_CHECK_CLOSE(dQ(1,0), -1.0/2.0, tolerance);\r\n    BOOST_CHECK_CLOSE(dQ(1,1), 0.0,    tolerance);\r\n    BOOST_CHECK_CLOSE(dQ(1,2), 1.0/2.0,  tolerance);\r\n    BOOST_CHECK_CLOSE(dQ(2,0), 1.0,    tolerance);\r\n    BOOST_CHECK_CLOSE(dQ(2,1), -2.0,   tolerance);\r\n    BOOST_CHECK_CLOSE(dQ(2,2), 1.0,    tolerance);\r\n  }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "c4f69f0f807433fa92cbf7ca81c87b89de5ecd5c", "size": 1957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/spline/compute_basis_derivatives/src/unit_comp_basis_deriv.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/spline/compute_basis_derivatives/src/unit_comp_basis_deriv.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/spline/compute_basis_derivatives/src/unit_comp_basis_deriv.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 32.0819672131, "max_line_length": 99, "alphanum_fraction": 0.6586612161, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6414869321236573}}
{"text": "#include \"matrix.h\"\n#include \"mex.h\"\n\n\n#include <iostream>\n#include <math.h>\n#include <chrono>\n#include <random>\n#include <vector>\n\n#include <Eigen\\Eigen>\n#include <Eigen\\LU>\n#include <Eigen\\Dense>\n#include <Eigen\\SVD>\n\n#include \"SampleConsensusProblem.hpp\"\n#include \"SampleConsensus.hpp\"\n#include \"Ransac.hpp\"\n#include \"Msac.hpp\"\n#include \"Prosac.hpp\"\n#include \"Lmeds.hpp\"\n\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace aslam;\n\n\nclass HomographyEstimatorProblem : public aslam::SampleConsensusProblem <MatrixXd>\n{\npublic:\n\tHomographyEstimatorProblem() { }\n\tvirtual ~HomographyEstimatorProblem() { }\n\n\tsize_t numElements() const{ return points1_.rows(); }\n\n\tvirtual int getSampleSize() const { return 4; }\n\n\t// Take a subset of size 4 of points and estimate homography matrix using them\n\tvirtual bool computeModelCoefficients(const std::vector<int> & indices, MatrixXd& model) const\n\t{\n\t\tif (indices.size() != getSampleSize())\n\t\t{\n\t\t\tmexPrintf(\"Invalid set of sample points given (%d)!\\n\", indices.size());\n\t\t\treturn false;\n\t\t}\n\n\t\tMatrixXd p1(indices.size(), 3);\n\t\tMatrixXd p2(indices.size(), 3);\n\t\tfor (int i = 0; i < indices.size(); i++)\n\t\t{\n\t\t\tp1.row(i) = points1_.row(indices[i]);\n\t\t\tp2.row(i) = points2_.row(indices[i]);\n\t\t}\n\t\tauto H = calculateHomography(p1, p2);\n\n\t\tmodel = H;\n\t\t// end calculate homography\n\t\treturn true;\n\t}\n\n\tvirtual void optimizeModelCoefficients(const vector<int> & inliers, const MatrixXd& model, MatrixXd& optimized_model)\n\t{\n\t\toptimized_model = model;\n\t}\n\n\t// It will return a matrix H, the homography matrix, such that x1=H*x2\n\t// Note: points are assumed to be normalized and in homogeneous coordinate\n\t// Sizes of two sets of points must be equal. for performace purposes, this condition is not checked in this function\n\t// Note: since normalise2Dpoints works in-place on the points matrix, normalizing points inside this function will \n\t// harm our collection of points. But because of two observations, we are allowed to normalise points inside this function\n\t// and it will cause no harm:\n\t//\t1) Points from each step of ransac will be passed to this function to calculate the homography matrix. To do so, we will \n\t//\t   copy those points from the main point matrix to temporary matrices. So normalisation won't affect the original matrix.\n\t//  2) After exhausting the SAC operation, the final Homography matrix will be calculated using all of the inliers. After this\n\t//\t   calculation, the program will return. So affecting the data points, won't do harm.\n\tMatrixXd calculateHomography(MatrixXd& x1, MatrixXd& x2) const\n\t{\n\t\tMatrixXd T1, T2;\n\t\tnormalize2Dpoints(x1, T1);\n\t\tnormalize2Dpoints(x2, T2);\n\t\tMatrixXd A = MatrixXd::Zero(3 * x1.rows(), 9);\n\t\tfor (int i = 0; i < x1.rows(); i++)\n\t\t{\n\t\t\tA(3 * i, 3) = -x1(i, 0);\n\t\t\tA(3 * i, 4) = -x1(i, 1);\n\t\t\tA(3 * i, 5) = -x1(i,2);\n\t\t\tA(3 * i, 6) = x2(i, 1) * x1(i, 0);\n\t\t\tA(3 * i, 7) = x2(i, 1) * x1(i, 1);\n\t\t\tA(3 * i, 8) = x2(i, 1) * x1(i, 2);\n\n\t\t\tA(3 * i + 1, 0) = x1(i, 0);\n\t\t\tA(3 * i + 1, 1) = x1(i, 1);\n\t\t\tA(3 * i + 1, 2) = x1(i, 2);\n\t\t\tA(3 * i + 1, 6) = -x2(i, 0) * x1(i, 0);\n\t\t\tA(3 * i + 1, 7) = -x2(i, 0) * x1(i, 1);\n\t\t\tA(3 * i + 1, 8) = -x2(i, 0) * x1(i, 2);\n\n\t\t\tA(3 * i + 2, 0) = x2(i, 1) * x1(i, 0);\n\t\t\tA(3 * i + 2, 1) = x2(i, 1) * x1(i, 1);\n\t\t\tA(3 * i + 2, 2) = x2(i, 1) * x1(i, 2);\n\t\t\tA(3 * i + 2, 3) = x2(i, 0) * x1(i, 0);\n\t\t\tA(3 * i + 2, 4) = x2(i, 0) * x1(i, 1);\n\t\t\tA(3 * i + 2, 5) = x2(i, 0) * x1(i, 2);\n\t\t}\n\t\tJacobiSVD<MatrixXd> svd(A, ComputeThinV);\n\t\tsvd.computeV();\n\t\tMatrixXd minEigenVector = MatrixXd(svd.matrixV().col(8));\n\t\tminEigenVector.resize(3, 3);\n\t\tauto H = T2.inverse() * minEigenVector * T1;\n\t\treturn H;\n\t}\n\n\t// As the final step, estimate the homography matrix using all of the inlier correspondences\n\tvoid calculateModelUsingAllInliers(const vector<int>& inliers, MatrixXd& finalModel)\n\t{\n\t\tMatrixXd p1(inliers.size(), 3);\n\t\tMatrixXd p2(inliers.size(), 3);\n\t\tfor (int i = 0; i < inliers.size(); i++)\n\t\t{\n\t\t\tp1.row(i) = points1_.row(inliers[i]);\n\t\t\tp2.row(i) = points2_.row(inliers[i]);\n\t\t}\n\t\tauto H = calculateHomography(p1, p2);\n\n\t\tfinalModel = H;\n\t}\n\n\t/// evaluate the score for the elements at indices based on this model.\n\t/// low scores mean a good fit.\n\tvirtual void getSelectedDistancesToModel(const MatrixXd& model, const vector<int> & indices, vector<double> & scores) const\n\t{\n\t\tscores.resize(indices.size());\n\t\t// Iterate through correspondences and calculate the projection error\n\t\t\n\t\tauto H = model;\n\t\tfor (size_t i = 0; i < indices.size(); ++i)\n\t\t{\n\t\t\tauto x1 = points1_.row(indices[i]);\n\t\t\tauto x2 = points2_.row(indices[i]);\n\t\t\tauto Hx1 = H * x1;\n\t\t\tauto invHx2 = H.inverse() * x2;\n\t\t\tx1 /= x1(2);\n\t\t\tx2 /= x2(2);\n\t\t\tHx1 /= Hx1(2);\n\t\t\tinvHx2 /= invHx2(2);\n\t\t\tscores[i] = (x1 - invHx2).unaryExpr([](double a) {return a*a; }).sum() + (x2 - Hx1).unaryExpr([](double a) {return a*a; }).sum();\n\t\t}\n\t}\n\n\t// normalize 2d points so that they would have a zero mean and their mean distance from origin would be sqrt(2)\n\tvoid normalize2Dpoints(MatrixXd& points, MatrixXd& normalizationMat) const\n\t{\n\t\tdouble meanx = points.col(0).mean();\n\t\tdouble meany = points.col(1).mean();\n\t\t/*auto colx = points.col(0).unaryExpr([meanx](double x) { return x - meanx; });\n\t\tauto coly = points.col(1).unaryExpr([meany](double y) { return y - meany; });\n\t\tauto dist = (colx.unaryExpr([](double x) { return x*x; }) + coly.unaryExpr([](double y) {return y*y; })).unaryExpr([](double d) {return sqrt(d); });*/\n\t\tdouble meandist = (points.col(0).unaryExpr([meanx](double x) { return (x - meanx)*(x - meanx); }) + points.col(1).unaryExpr([meany](double y) { return (y - meany)*(y - meany); }))\n\t\t\t.unaryExpr([](double d){return sqrt(d); }).mean();\n\t\tdouble scale = sqrt(2) / meandist;\n\n\t\tMatrixXd T(3, 3);\n\t\tT << scale, 0, -scale*meanx\n\t\t\t, 0, scale, -scale*meany\n\t\t\t, 0, 0, 1;\n\t\tpoints = (T*points.transpose()).transpose();\n\t\tnormalizationMat = T;\n\t}\n\n\tMatrixXd points1_;\n\tMatrixXd norm1_;\n\tMatrixXd points2_;\n\tMatrixXd norm2_;\n};\n\n\n// This is the entry point from MATLAB to this routine\n// plhs and prhs represent a pointer to the left hand side (output) and a pointer to the right hand side (input) respectively\n// matlab function signature: H = homography_estimator(points1, points2, 'mode')\n// H -> 9-by-9 homography matrix as output\n// points1 -> n-by-2 matrix, coordinates of the keypoints of the first image\n// points2 -> n-by-2 matrix, coordinates of the keypoints of the second image\n// 'mode' -> {'ransac', 'prosac', 'mlesac'}\nvoid mexFunction(int nlhs, mxArray *plhs [], int nrhs, const mxArray*prhs [])\n{\n\tif (nlhs != 1)\n\t{\n\t\tmexPrintf(\"Only one output expected\\n\");\n\t\treturn;\n\t}\n\tif (nrhs != 3)\n\t{\n\t\tmexPrintf(\"Only three inputs expected\\n\");\n\t\treturn;\n\t}\n\n\tconst mwSize *dims1, *dims2;\n\tchar* modeStr;\n\tdouble *points1, *points2;\n\n\n\tdims1 = mxGetDimensions(prhs[0]);\n\tdims2 = mxGetDimensions(prhs[1]);\n\n\tint dim1y = (int) dims1[0]; int dim1x = (int) dims1[1];\n\tint dim2y = (int) dims2[0]; int dim2x = (int) dims2[1];\n\n\tif (dim1x != dim2x || dim1y != dim2y)\n\t{\n\t\tmexPrintf(\"Error! two input points arrays must be of the same size\\n\");\n\t\treturn;\n\t}\n\n\tif (dim1x != 2 || dim2x != 2)\n\t{\n\t\tmexPrintf(\"Error! Points must be 2-D!\\n\");\n\t\treturn;\n\t}\n\n\tif (dim1y < 4)\n\t{\n\t\tmexPrintf(\"Not enough correspondences provided\\n\");\n\t\treturn;\n\t}\n\n\tmodeStr = mxArrayToString(prhs[2]);\n\n\tif (!modeStr || mxGetDimensions(prhs[2])[0] != 1)\n\t{\n\t\tmexPrintf(\"Error! Last argument must be an string!\\n\");\n\t\treturn;\n\t}\n\n\tmexPrintf(\"string:\\n%s\\n\", modeStr);\n\tmexPrintf(\"dimx = %d, dimy = %d\\n\", dim1x, dim1y);\n\t//vector<Correspondence> correspondences(dim1y);\n\tpoints1 = mxGetPr(prhs[0]);\n\tpoints2 = mxGetPr(prhs[1]);\n\n\tboost::shared_ptr<HomographyEstimatorProblem> homoproblem_ptr(new HomographyEstimatorProblem);\n\tHomographyEstimatorProblem& homoproblem = *homoproblem_ptr;\n\thomoproblem.points1_.resize(dim1y, 3);\n\thomoproblem.points1_.col(2).setOnes();\n\thomoproblem.points2_.resize(dim1y, 3);\n\thomoproblem.points2_.col(2).setOnes();\n\thomoproblem.setUniformIndices(dim1y);\n\n\n\n\tfor (size_t j = 0; j < dim1y; j++)\n\t{\n\t\t/*Correspondence corr;\n\t\tcorr.p1.x = points1[j];\n\t\tcorr.p2.x = points2[j];\n\t\tcorr.p1.y = points1[dim1y + j];\n\t\tcorr.p2.y = points2[dim1y + j];*/\n\t\t//correspondences[j] = Correspondence(points1[j], points1[dim1y + j], points2[j], points2[dim1y + j]);\n\t\t//  mexPrintf(\"correspondence[%d] = (%lf, %lf; %lf, %lf)\\n\", j, points1[j], points1[dim1y + j], points2[j], points2[dim1y + j]);\n\t\t// mexPrintf(\"correspondence[%d] = (%lf, %lf; %lf, %lf)\\n\", j, correspondences[j].p1.x, correspondences[j].p1.y, correspondences[j].p2.x, correspondences[j].p2.y);\n\t\thomoproblem.points1_(j, 0) = points1[j];\n\t\thomoproblem.points1_(j, 1) = points1[dim1y + j];\n\t\thomoproblem.points2_(j, 0) = points2[j];\n\t\thomoproblem.points2_(j, 1) = points2[dim1y + j];\n\t}\n\n\n\thomoproblem.normalize2Dpoints(homoproblem.points1_, homoproblem.norm1_);\n\thomoproblem.normalize2Dpoints(homoproblem.points2_, homoproblem.norm2_);\n\n\n\t// HomographyEstimatorProblem *homoproblem = new HomographyEstimatorProblem();\n\n\tSampleConsensus<HomographyEstimatorProblem> *sac;\n\tif (!strcmp(\"ransac\", modeStr))\n\t{\n\t\tsac = new Ransac<HomographyEstimatorProblem>(1000, 0.1, 0.9);\n\t}\n\telse if (!strcmp(\"lmeds\", modeStr))\n\t{\n\t\tsac = new Lmeds<HomographyEstimatorProblem>(1000, 0.1, 0.9);\n\t}\n\telse if (!strcmp(\"msac\", modeStr))\n\t{\n\t\tsac = new Msac<HomographyEstimatorProblem>(1000, 0.1, 0.9);\n\t}\n\telse if (!strcmp(\"prosac\", modeStr))\n\t{\n\t\tsac = new Prosac<HomographyEstimatorProblem>(1000, 0.1, 0.9);\n\t}\n\telse\n\t{\n\t\tmexPrintf(\"Error! unknown estimation mode selected!\\n\");\n\t\treturn;\n\t}\n\t// if(!strcmp(\"rmsac\", modeStr))\n\t// {\n\t// \tsac = new Rmsac<HomographyEstimatorProblem>(1000, 0.1, 0.9);\n\t// }\n\n\t// Msac<HomographyEstimatorProblem> ransac(1000, 0.1, 0.9);\n\n\tsac->sac_model_ = homoproblem_ptr;\n\tsac->computeModel(4);\n\tauto homographyModel = sac->model_coefficients_;\n\tmexPrintf(\"Number of iterations: %d\\n\", sac->iterations_);\n\tmexPrintf(\"Inliers size: %d (out of %d input correspondences)\\n\", sac->inliers_.size(), homoproblem.points1_.rows());\n\n\thomoproblem.calculateModelUsingAllInliers(sac->inliers_, homographyModel);\n\tauto H = homoproblem.norm2_.inverse() * homographyModel * homoproblem.norm1_;\n\n\tauto outArray = mxCreateDoubleMatrix(3, 3, mxREAL);\n\tdouble *outp = mxGetPr(outArray);\n\n\t// for (size_t i = 0; i < 3; i++)\n\t// {\n\t// \tfor (size_t j = 0; j < 3; j++)\n\t// \t{\n\t// \t\tmexPrintf(\"homography matrix(%d, %d) = %lf\\n\", i, j, ransac.model_coefficients_.Matrix[j*3+i]);\n\t// \t}\n\t// }\n\n\t// Copy the estimated homography matrix to the output matrix, note the difference between MATLAB's column-wise arrays vs. C's row-wise arrays convention\n\tfor (size_t i = 0; i < 3; i++)\n\t{\n\t\tfor (size_t j = 0; i < 3; j++)\n\t\t{\n\t\t\toutp[i + 3 * j] = H(i, j);\n\t\t}\n\t}\n\n\tplhs[0] = outArray;\n}\n", "meta": {"hexsha": "b59a2970dc95625bb8abbc4a639bcd27b1bfee0c", "size": 10744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PCL SAC + Boost/homography_estimator_pcl.cpp", "max_stars_repo_name": "erfannoury/sac", "max_stars_repo_head_hexsha": "7e4c183a91bf16803bc78536476bba594bfba109", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-10-19T12:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T08:19:24.000Z", "max_issues_repo_path": "PCL SAC + Boost/homography_estimator_pcl.cpp", "max_issues_repo_name": "erfannoury/sac", "max_issues_repo_head_hexsha": "7e4c183a91bf16803bc78536476bba594bfba109", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PCL SAC + Boost/homography_estimator_pcl.cpp", "max_forks_repo_name": "erfannoury/sac", "max_forks_repo_head_hexsha": "7e4c183a91bf16803bc78536476bba594bfba109", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1676646707, "max_line_length": 181, "alphanum_fraction": 0.6585070737, "num_tokens": 3691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6414869288093681}}
{"text": "/**\n * math lib test\n * @author Tobias Weber <tweber@ill.fr>\n * @date mar-21\n * @license GPLv3, see 'LICENSE' file\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE La1\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n#include <iostream>\n#include <vector>\n\n#include \"libs/maths.h\"\n\n\nusing t_types = std::tuple<double, float>;\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_mat2, t_real, t_types)\n{\n\tusing namespace tl2_ops;\n\n\tusing t_cplx = std::complex<t_real>;\n\tusing t_vec = tl2::vec<t_real, std::vector>;\n\tusing t_mat = tl2::mat<t_real, std::vector>;\n\tusing t_vec_cplx = tl2::vec<t_cplx, std::vector>;\n\tusing t_mat_cplx = tl2::mat<t_cplx, std::vector>;\n\n\n\t{\n\t\tauto M = tl2::create<t_mat>({\n\t\t\t1., 2., 3.,\n\t\t\t3., 1., 4.,\n\t\t\t9., -4., 2.\n\t\t});\n\n\t\t// test determinant\n\t\tt_real det = tl2::det(M);\n\t\tstd::cout << \"M = \" << M << std::endl;\n\t\tstd::cout << \"|M| = \" << det << std::endl;\n\n\t\tBOOST_TEST(tl2::equals<t_real>(det, 15., 1e-4));\n\t}\n\n\n\t{\n\t\tauto M = tl2::create<t_mat>({\n\t\t\t1., 3., 2.,\n\t\t\t3., 4., 1.,\n\t\t\t9., 2., -4.\n\t\t});\n\n\t\t// test determinant\n\t\tt_real det = tl2::det(M);\n\t\tstd::cout << \"M = \" << M << std::endl;\n\t\tstd::cout << \"|M| = \" << det << std::endl;\n\n\t\tBOOST_TEST(tl2::equals<t_real>(det, -15., 1e-4));\n\t}\n\n\n\t{\n\t\tauto M = tl2::create<t_mat_cplx>({\n\t\t\t1., 2., 3.,\n\t\t\t3., 1., 4.,\n\t\t\t9., -4., 2\n\t\t});\n\n\t\t// test determinant\n\t\tt_cplx det = tl2::det(M);\n\t\tstd::cout << \"M = \" << M << std::endl;\n\t\tstd::cout << \"|M| = \" << det << std::endl;\n\n\t\tBOOST_TEST(tl2::equals<t_cplx>(det, 15., 1e-4));\n\t}\n}\n", "meta": {"hexsha": "fe86b5cc6a0d5605dc09d2b4fcbe08e2cbb3783c", "size": 2567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/mat2.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/mat2.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/mat2.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 26.193877551, "max_line_length": 79, "alphanum_fraction": 0.5792754188, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6414286505158614}}
{"text": "//  (C) Copyright Evan Miller 2020.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <boost/math/tools/ulps_plot.hpp>\n#include <boost/core/demangle.hpp>\n#include <boost/math/special_functions/jacobi_theta.hpp>\n\nusing boost::math::tools::ulps_plot;\n\nint main() {\n    using PreciseReal = long double;\n    using CoarseReal = float;\n\n    CoarseReal q = 0.5;\n\n    auto jacobi_theta1_coarse = [=](CoarseReal z) {\n        return boost::math::jacobi_theta1<CoarseReal>(z, q);\n    };\n    auto jacobi_theta1_precise = [=](PreciseReal z) {\n        return boost::math::jacobi_theta1<PreciseReal>(z, q);\n    };\n    auto jacobi_theta2_coarse = [=](CoarseReal z) {\n        return boost::math::jacobi_theta2<CoarseReal>(z, q);\n    };\n    auto jacobi_theta2_precise = [=](PreciseReal z) {\n        return boost::math::jacobi_theta2<PreciseReal>(z, q);\n    };\n    auto jacobi_theta3_coarse = [=](CoarseReal z) {\n        return boost::math::jacobi_theta3m1<CoarseReal>(z, q);\n    };\n    auto jacobi_theta3_precise = [=](PreciseReal z) {\n        return boost::math::jacobi_theta3m1<PreciseReal>(z, q);\n    };\n    auto jacobi_theta4_coarse = [=](CoarseReal z) {\n        return boost::math::jacobi_theta4m1<CoarseReal>(z, q);\n    };\n    auto jacobi_theta4_precise = [=](PreciseReal z) {\n        return boost::math::jacobi_theta4m1<PreciseReal>(z, q);\n    };\n\n    int samples = 2500;\n    int width = 800;\n    PreciseReal clip = 100;\n\n    std::string filename1 = \"jacobi_theta1_\" + boost::core::demangle(typeid(CoarseReal).name()) + \".svg\";\n    auto plot1 = ulps_plot<decltype(jacobi_theta1_precise), PreciseReal, CoarseReal>(jacobi_theta1_precise, 0.0, boost::math::constants::two_pi<CoarseReal>(), samples);\n    plot1.clip(clip).width(width);\n    std::string title1 = \"jacobi_theta1(x, 0.5) ULP plot at \" + boost::core::demangle(typeid(CoarseReal).name()) + \" precision\";\n    plot1.title(title1);\n    plot1.vertical_lines(10);\n    plot1.add_fn(jacobi_theta1_coarse);\n    plot1.write(filename1);\n\n    std::string filename2 = \"jacobi_theta2_\" + boost::core::demangle(typeid(CoarseReal).name()) + \".svg\";\n    auto plot2 = ulps_plot<decltype(jacobi_theta2_precise), PreciseReal, CoarseReal>(jacobi_theta2_precise, 0.0, boost::math::constants::two_pi<CoarseReal>(), samples);\n    plot2.clip(clip).width(width);\n    std::string title2 = \"jacobi_theta2(x, 0.5) ULP plot at \" + boost::core::demangle(typeid(CoarseReal).name()) + \" precision\";\n    plot2.title(title2);\n    plot2.vertical_lines(10);\n    plot2.add_fn(jacobi_theta2_coarse);\n    plot2.write(filename2);\n\n    std::string filename3 = \"jacobi_theta3_\" + boost::core::demangle(typeid(CoarseReal).name()) + \".svg\";\n    auto plot3 = ulps_plot<decltype(jacobi_theta3_precise), PreciseReal, CoarseReal>(jacobi_theta3_precise, 0.0, boost::math::constants::two_pi<CoarseReal>(), samples);\n    plot3.clip(clip).width(width);\n    std::string title3 = \"jacobi_theta3m1(x, 0.5) ULP plot at \" + boost::core::demangle(typeid(CoarseReal).name()) + \" precision\";\n    plot3.title(title3);\n    plot3.vertical_lines(10);\n    plot3.add_fn(jacobi_theta3_coarse);\n    plot3.write(filename3);\n\n    std::string filename4 = \"jacobi_theta4_\" + boost::core::demangle(typeid(CoarseReal).name()) + \".svg\";\n    auto plot4 = ulps_plot<decltype(jacobi_theta4_precise), PreciseReal, CoarseReal>(jacobi_theta4_precise, 0.0, boost::math::constants::two_pi<CoarseReal>(), samples);\n    plot4.clip(clip).width(width);\n    std::string title4 = \"jacobi_theta4m1(x, 0.5) ULP plot at \" + boost::core::demangle(typeid(CoarseReal).name()) + \" precision\";\n    plot4.title(title4);\n    plot4.vertical_lines(10);\n    plot4.add_fn(jacobi_theta4_coarse);\n    plot4.write(filename4);\n}\n", "meta": {"hexsha": "a31c30eb201746f31ce22b56f3f5dc66da8bb5d0", "size": 3839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reporting/accuracy/plot_jacobi_theta_x.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "reporting/accuracy/plot_jacobi_theta_x.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": "reporting/accuracy/plot_jacobi_theta_x.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 45.7023809524, "max_line_length": 168, "alphanum_fraction": 0.6908048971, "num_tokens": 1181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6414286494908007}}
{"text": "#include <cstdio> \n#include <cstdlib> \n#include <iostream>\n#include <fstream> \n#include <vector> \n#include <chrono>\n\n#include <getopt.h>\n\n#include \"Sampling_Matrix.hpp\"\n#include \"Alpert_Matrix.hpp\"\n#include \"Utils.hpp\"\n#include \"ccstomp.hpp\"\n\n#include <boost/numeric/bindings/blas/blas.h>\n\nusing namespace std;\n\nint main(int argc, char** argv) {\n    \n  if(argc == 1 ){\n    cout << argv[0] << \" usage is:\" << endl;\n    cout << argv[0] << \" --seed 'seed_value' --reduction 'reduction_value' [mesh input_file] [data input_file]\" << endl;\n    cout << \"If the data input file is provided it should have the same number of points as the mesh, if not a default data field will be assigned\" << endl;\n    cout << \"Please refer to README.txt in this folder for more info\" << endl;\n    exit (0);\n  }\n\n\n  /*Seed is overwritten if set as a command line option*/\n    unsigned seed = chrono::system_clock::now().time_since_epoch().count();\n    chrono::duration <double> duration;\n\n    int d, N;\n    double R=10.0e0;\n    int c;\n    double alpha=1.0e0, beta=0.0e0;\n    int inc=1;\n    \n    {\n          static struct option long_options[] =\n        {\n          /* These options set a flag. */\n          /* These options don\u2019t set a flag.\n             We distinguish them by their indices. */\n          {\"seed\",  required_argument, 0, 's'},\n          {\"reduction\",  required_argument, 0, 'r'},\n          {0, 0, 0, 0}\n        };\n      /* getopt_long stores the option index here. */\n      int option_index = 0;\n\n      while (c = getopt_long (argc, argv, \"s\",\n\t\t\t      long_options, &option_index) != -1){\n\n\tif(option_index == 0 && optarg){\n\t  seed  = atoi(optarg); \n\t  cout << \"Seed set to \" << seed << endl;\n\t}\n\tif(option_index == 1 && optarg){\n\t  R  = atof(optarg); \n\t  cout << \"Reduction set to \" << R << endl;\n\t}\n      }\n\n    }\n\n\n    if(optind >= argc ) {\n      cout << \"Expected an input file name \" << endl;\n      exit(0);\n    }       \n    \n    cout << \"Reading mesh input file\" << argv[optind] << endl;\n    ifstream f(argv[optind]);\n    f >> N >> d;\n\n    cout << \"Number of Points \" << N << endl;\n    cout << \"Number of dimensions \" << d << endl;\n    cout << \"R \" << R << endl;\n        \n    int M=ceil(double(N)/R);\n    int NR=N-M;\n    \n    vector<vector<double> >p(N, vector<double>(d));\n    \n    // Read mesh into array\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < d; j++)\n            f >> p[i][j];\n    \n    f.close();\n    \n    // Setting Wavelet orders\n    vector<int> ki(d);\n    for (int j = 0; j < d; j++)\n      ki[j] = 5;\n    \n    cout << \"Constructing Alpert Matrix\" << endl;\n    boost::numeric::ublas::compressed_matrix <double>  U(N, N);\n    chrono::system_clock::time_point t1 = chrono::system_clock::now();\n    boostbuild_Alpert_matrix(p, ki,  U, -1, N);\n    chrono::system_clock::time_point t2 = chrono::system_clock::now();\n    duration=t2-t1;\n    cout << \"Total wavelet matrix construction time \" << duration.count() << endl;\n    \n    boost::numeric::ublas::vector<double> x(N);\n    boost::numeric::ublas::vector<double> w(N);\n    boost::numeric::ublas::vector<double> xw(N);\n    boost::numeric::ublas::vector<double> ys(N);\n    \n    // Setting data, this step can be replaced by some commands to read an external data file\n    double pi=4.0e0*atan(1.0e0);\n    if (argc>6) {\n      cout << \"Reading data input file\" << argv[optind+1] << endl;\n      f.open(argv[optind+1]);\n      for (int i = 0; i < N; i++)\n\tf >> x(i);\n    }\n    else\n      for (int i = 0; i < N; i++) x(i)=(4.0e0*sin(8.0e0*pi*p[i][0]))*(4.0e0*sin(7.0e0*pi*p[i][1]) )*3.0e0*sin(6.0e0*pi*p[i][0]);\n//     for (int i = 0; i < N; i++) x[i]=(4.0*sin(2.0*pi*p[i][0]) - 4.0*sin(2.0*pi*p[i][1]))*3.0*sin(2.0*pi*p[i][0]);\n    \n    // Forward wavelet transform\n    t1 = chrono::system_clock::now();\n    boost::numeric::ublas::axpy_prod(U, x, w, true);    \n    \n    // Sorting, wavelet compression and inverse wavelet transform\n    vector<double> yv(N);\n    vector<size_t> iyv(N);\n    for (int i = 0; i < N; i++) {yv[i]=fabs(w(i));iyv[i]=i;}\n    sortandindices(yv, iyv);\n    for (int i = NR; i < N; i++) ys(iyv[i])=w(iyv[i]);\n    t2 = chrono::system_clock::now();\n    duration=t2-t1;\n    cout << \"Total wavelet compression time \" << duration.count() << endl;\n    \n    // xw is the reconstruction by wavelets\n    boost::numeric::ublas::axpy_prod(ys, U, xw, true);\n    \n    cout << \"Constructing Bernoulli Sampling Matrix\" << endl;\n    boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> P(N,M,0.0e0);\n    t1 = chrono::system_clock::now();\n    ConstructBernoulliMatrix(M, N, seed, P);\n    t2 = chrono::system_clock::now();\n    duration=t2-t1;\n    cout << \"Total compression matrix construction time \" << duration.count() << endl;\n    \n    cout << \"Performing CS compression\" << endl;\n    boost::numeric::ublas::vector<double> y(M);\n    t1 = chrono::system_clock::now();\n    BLAS_DGEMV(\"T\", &N, &M, &alpha, &P(0,0), &N, &x(0), &inc, &beta, &y(0), &inc);\n    t2 = chrono::system_clock::now();\n    duration=t2-t1;     \n    cout << \"Total CS compression time \" << duration.count() << endl;\n\n    cout << \"Constructing Alpert-Bernoulli Matrix product\" << endl;\n    t1 = chrono::system_clock::now();\n    build_Alpert_Sampling_product(U,P,P);\n    t2 = chrono::system_clock::now();\n    duration=t2-t1;     \n    cout << \"Alpert-Compression matrix product time \" << duration.count() << endl;\n\n    // Computing incoherence between sampling and wavelet matrices\n    double maxT=0.0;\n    for (int j = 0; j < M; j++) \n      for (int i = 0; i < N; i++) \n\tif (fabs(P(i,j))>maxT)\n\t  maxT=fabs(P(i,j));\n\t\n    \n    cout << \"Performing StOMP\" << endl;\n    t1 = chrono::system_clock::now();\n    boost::numeric::ublas::vector<double> ywp(N);\n    int * asize= new int[2]; asize[0]=M; asize[1]=N;\n    int * rsize= new int[2]; rsize[0]=M; rsize[1]=1;\n    int niter=0, nywp=0;\n    double *activeSet=NULL;\n    double *aresult=NULL;\n    // activeSet and aresult are the initial guess of the solution, here we assume the coefficient\n    // vector is empty\n    cc_solve_stomp(&P(0,0), &y(0), asize, rsize, 1.0e-8, 50, &niter, &nywp, &ywp(0), activeSet, aresult);\n    \n    boost::numeric::ublas::vector<double> xs(N);\n    boost::numeric::ublas::axpy_prod(ywp, U, xs, true);\n    t2 = chrono::system_clock::now();\n    duration=t2-t1;     \n    cout << \"StOMP time \" << duration.count() << endl;\n    \n    // Computing NRMSE\n    double es=0.0e0, ew=0.0e0;\n    for (int i = 0; i < N; i++) {\n      ew+=pow(x(i)-xw(i),2.0e0);\n      es+=pow(x(i)-xs(i),2.0e0); \n    }\n    \n    // Computing min and max values in the data x\n    double mx=x(0);\n    double mn=x(0);\n    for (int i = 0; i < N; i++) {\n      if (x(i)>mx)\n\tmx=x(i);\n      if (x(i)<mn)\n\tmn=x(i);\n    }\n    \n    es=sqrt(es/double(N))/(mx-mn);\n    ew=sqrt(ew/double(N))/(mx-mn);\n    \n    cout << \"Alpert Wavelets Compression NRMSE = \" << ew << endl;\n    cout << \"CS Compression NRMSE = \" << es << endl;\n}\n", "meta": {"hexsha": "cbcc3e29aa9721f7cbe7df58d3da52e2312e3624", "size": 6911, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "swinzip-v2.0/examples/compress_reconstruct/main.cpp", "max_stars_repo_name": "msalloum80/SWinzip", "max_stars_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-17T07:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T07:58:23.000Z", "max_issues_repo_path": "swinzip-v2.5/examples/compress_reconstruct/main.cpp", "max_issues_repo_name": "msalloum80/SWinzip", "max_issues_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swinzip-v2.5/examples/compress_reconstruct/main.cpp", "max_forks_repo_name": "msalloum80/SWinzip", "max_forks_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-05T20:18:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T20:18:25.000Z", "avg_line_length": 32.4460093897, "max_line_length": 156, "alphanum_fraction": 0.5712632036, "num_tokens": 2183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6414286349323317}}
{"text": "/*\n * Copyright Nick Thompson, 2017\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n#define BOOST_TEST_MODULE catmull_rom_test\n\n#include <array>\n#include <random>\n#include <boost/cstdfloat.hpp>\n#include <boost/type_index.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/interpolators/catmull_rom.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\nusing std::abs;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::math::catmull_rom;\n\ntemplate<class Real>\nvoid test_alpha_distance()\n{\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::array<Real, 3> v1 = {0,0,0};\n    std::array<Real, 3> v2 = {1,0,0};\n    Real alpha = 0.5;\n    Real d = boost::math::detail::alpha_distance<std::array<Real, 3>>(v1, v2, alpha);\n    BOOST_CHECK_CLOSE_FRACTION(d, 1, tol);\n\n    d = boost::math::detail::alpha_distance<std::array<Real, 3>>(v1, v2, 0.0);\n    BOOST_CHECK_CLOSE_FRACTION(d, 1, tol);\n\n    d = boost::math::detail::alpha_distance<std::array<Real, 3>>(v1, v2, 1.0);\n    BOOST_CHECK_CLOSE_FRACTION(d, 1, tol);\n\n    v2[0] = 2;\n    d = boost::math::detail::alpha_distance<std::array<Real, 3>>(v1, v2, alpha);\n    BOOST_CHECK_CLOSE_FRACTION(d, pow(2, (Real)1/ (Real) 2), tol);\n\n    d = boost::math::detail::alpha_distance<std::array<Real, 3>>(v1, v2, 0.0);\n    BOOST_CHECK_CLOSE_FRACTION(d, 1, tol);\n\n    d = boost::math::detail::alpha_distance<std::array<Real, 3>>(v1, v2, 1.0);\n    BOOST_CHECK_CLOSE_FRACTION(d, 2, tol);\n}\n\n\ntemplate<class Real>\nvoid test_linear()\n{\n    std::cout << \"Testing that the Catmull-Rom spline interpolates linear functions correctly on type \"\n              << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    Real tol = 10*std::numeric_limits<Real>::epsilon();\n    std::vector<std::array<Real, 3>> v(4);\n    v[0] = {0,0,0};\n    v[1] = {1,0,0};\n    v[2] = {2,0,0};\n    v[3] = {3,0,0};\n    catmull_rom<std::array<Real, 3>> cr(std::move(v));\n\n    // Test that the interpolation condition is obeyed:\n    BOOST_CHECK_CLOSE_FRACTION(cr.max_parameter(), 3, tol);\n    auto p0 = cr(0.0);\n    BOOST_CHECK_SMALL(p0[0], tol);\n    BOOST_CHECK_SMALL(p0[1], tol);\n    BOOST_CHECK_SMALL(p0[2], tol);\n    auto p1 = cr(1.0);\n    BOOST_CHECK_CLOSE_FRACTION(p1[0], 1, tol);\n    BOOST_CHECK_SMALL(p1[1], tol);\n    BOOST_CHECK_SMALL(p1[2], tol);\n\n    auto p2 = cr(2.0);\n    BOOST_CHECK_CLOSE_FRACTION(p2[0], 2, tol);\n    BOOST_CHECK_SMALL(p2[1], tol);\n    BOOST_CHECK_SMALL(p2[2], tol);\n\n\n    auto p3 = cr(3.0);\n    BOOST_CHECK_CLOSE_FRACTION(p3[0], 3, tol);\n    BOOST_CHECK_SMALL(p3[1], tol);\n    BOOST_CHECK_SMALL(p3[2], tol);\n\n    Real s = cr.parameter_at_point(0);\n    BOOST_CHECK_SMALL(s, tol);\n\n    s = cr.parameter_at_point(1);\n    BOOST_CHECK_CLOSE_FRACTION(s, 1, tol);\n\n    s = cr.parameter_at_point(2);\n    BOOST_CHECK_CLOSE_FRACTION(s, 2, tol);\n\n    s = cr.parameter_at_point(3);\n    BOOST_CHECK_CLOSE_FRACTION(s, 3, tol);\n\n    // Test that the function is linear on the interval [1,2]:\n    for (double s = 1; s < 2; s += 0.01)\n    {\n        auto p = cr(s);\n        BOOST_CHECK_CLOSE_FRACTION(p[0], s, tol);\n        BOOST_CHECK_SMALL(p[1], tol);\n        BOOST_CHECK_SMALL(p[2], tol);\n\n        auto tangent = cr.prime(s);\n        BOOST_CHECK_CLOSE_FRACTION(tangent[0], 1, tol);\n        BOOST_CHECK_SMALL(tangent[1], tol);\n        BOOST_CHECK_SMALL(tangent[2], tol);\n    }\n\n}\n\ntemplate<class Real>\nvoid test_circle()\n{\n    using boost::math::constants::pi;\n    using std::cos;\n    using std::sin;\n\n    std::cout << \"Testing that the Catmull-Rom spline interpolates circles correctly on type \"\n              << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    Real tol = 10*std::numeric_limits<Real>::epsilon();\n    std::vector<std::array<Real, 2>> v(20*sizeof(Real));\n    std::vector<std::array<Real, 2>> u(20*sizeof(Real));\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        Real theta = ((Real) i/ (Real) v.size())*2*pi<Real>();\n        v[i] = {cos(theta), sin(theta)};\n        u[i] = v[i];\n    }\n    catmull_rom<std::array<Real, 2>> circle(std::move(v), true);\n\n    // Interpolation condition:\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        Real s = circle.parameter_at_point(i);\n        auto p = circle(s);\n        Real x = p[0];\n        Real y = p[1];\n        if (abs(x) < std::numeric_limits<Real>::epsilon())\n        {\n            BOOST_CHECK_SMALL(u[i][0], tol);\n        }\n        if (abs(y) < std::numeric_limits<Real>::epsilon())\n        {\n            BOOST_CHECK_SMALL(u[i][1], tol);\n        }\n        else\n        {\n            BOOST_CHECK_CLOSE_FRACTION(x, u[i][0], tol);\n            BOOST_CHECK_CLOSE_FRACTION(y, u[i][1], tol);\n        }\n    }\n\n    Real max_s = circle.max_parameter();\n    for(Real s = 0; s < max_s; s += 0.01)\n    {\n        auto p = circle(s);\n        Real x = p[0];\n        Real y = p[1];\n        BOOST_CHECK_CLOSE_FRACTION(x*x+y*y, 1, 0.001);\n    }\n}\n\n\ntemplate<class Real, size_t dimension>\nvoid test_affine_invariance()\n{\n    std::cout << \"Testing that the Catmull-Rom spline is affine invariant in dimension \"\n              << dimension << \" on type \"\n              << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    Real tol = 1000*std::numeric_limits<Real>::epsilon();\n    std::vector<std::array<Real, dimension>> v(100);\n    std::vector<std::array<Real, dimension>> u(100);\n    std::mt19937_64 gen(438232);\n    Real inv_denom = (Real) 100/( (Real) (gen.max)() + (Real) 2);\n    for(size_t j = 0; j < dimension; ++j)\n    {\n        v[0][j] = gen()*inv_denom;\n        u[0][j] = v[0][j];\n    }\n\n    for (size_t i = 1; i < v.size(); ++i)\n    {\n        for(size_t j = 0; j < dimension; ++j)\n        {\n            v[i][j] = v[i-1][j] + gen()*inv_denom;\n            u[i][j] = v[i][j];\n        }\n    }\n    std::array<Real, dimension> affine_shift;\n    for (size_t j = 0; j < dimension; ++j)\n    {\n        affine_shift[j] = gen()*inv_denom;\n    }\n\n    catmull_rom<std::array<Real, dimension>> cr1(std::move(v));\n\n    for(size_t i = 0; i< u.size(); ++i)\n    {\n        for(size_t j = 0; j < dimension; ++j)\n        {\n            u[i][j] += affine_shift[j];\n        }\n    }\n\n    catmull_rom<std::array<Real, dimension>> cr2(std::move(u));\n\n    BOOST_CHECK_CLOSE_FRACTION(cr1.max_parameter(), cr2.max_parameter(), tol);\n\n    Real ds = cr1.max_parameter()/1024;\n    for (Real s = 0; s < cr1.max_parameter(); s += ds)\n    {\n        auto p0 = cr1(s);\n        auto p1 = cr2(s);\n        auto tangent0 = cr1.prime(s);\n        auto tangent1 = cr2.prime(s);\n        for (size_t j = 0; j < dimension; ++j)\n        {\n            BOOST_CHECK_CLOSE_FRACTION(p0[j] + affine_shift[j], p1[j], tol);\n            if (abs(tangent0[j]) > 5000*tol)\n            {\n                BOOST_CHECK_CLOSE_FRACTION(tangent0[j], tangent1[j], 5000*tol);\n            }\n        }\n    }\n}\n\ntemplate<class Real>\nvoid test_helix()\n{\n    using boost::math::constants::pi;\n    std::cout << \"Testing that the Catmull-Rom spline interpolates helices correctly on type \"\n              << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    Real tol = 0.001;\n    std::vector<std::array<Real, 3>> v(400*sizeof(Real));\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        Real theta = ((Real) i/ (Real) v.size())*2*pi<Real>();\n        v[i] = {cos(theta), sin(theta), theta};\n    }\n    catmull_rom<std::array<Real, 3>> helix(std::move(v));\n\n    // Interpolation condition:\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        Real s = helix.parameter_at_point(i);\n        auto p = helix(s);\n        Real t = p[2];\n\n        Real x = p[0];\n        Real y = p[1];\n        if (abs(x) < tol)\n        {\n            BOOST_CHECK_SMALL(cos(t), tol);\n        }\n        if (abs(y) < tol)\n        {\n            BOOST_CHECK_SMALL(sin(t), tol);\n        }\n        else\n        {\n            BOOST_CHECK_CLOSE_FRACTION(x, cos(t), tol);\n            BOOST_CHECK_CLOSE_FRACTION(y, sin(t), tol);\n        }\n    }\n\n    Real max_s = helix.max_parameter();\n    for(Real s = helix.parameter_at_point(1); s < max_s; s += 0.01)\n    {\n        auto p = helix(s);\n        Real x = p[0];\n        Real y = p[1];\n        Real t = p[2];\n        BOOST_CHECK_CLOSE_FRACTION(x*x+y*y, (Real) 1, (Real) 0.01);\n        if (abs(x) < 0.01)\n        {\n            BOOST_CHECK_SMALL(cos(t),  (Real) 0.05);\n        }\n        if (abs(y) < 0.01)\n        {\n            BOOST_CHECK_SMALL(sin(t), (Real) 0.05);\n        }\n        else\n        {\n            BOOST_CHECK_CLOSE_FRACTION(x, cos(t), (Real) 0.05);\n            BOOST_CHECK_CLOSE_FRACTION(y, sin(t), (Real) 0.05);\n        }\n    }\n}\n\n\ntemplate<class Real>\nclass mypoint3d\n{\npublic:\n    // Must define a value_type:\n    typedef Real value_type;\n\n    // Regular constructor:\n    mypoint3d(Real x, Real y, Real z)\n    {\n        m_vec[0] = x;\n        m_vec[1] = y;\n        m_vec[2] = z;\n    }\n\n    // Must define a default constructor:\n    mypoint3d() {}\n\n    // Must define array access:\n    Real operator[](size_t i) const\n    {\n        return m_vec[i];\n    }\n\n    // Array element assignment:\n    Real& operator[](size_t i)\n    {\n        return m_vec[i];\n    }\n\n\nprivate:\n    std::array<Real, 3>  m_vec;\n};\n\n\n// Must define the free function \"size()\":\ntemplate<class Real>\nBOOST_CONSTEXPR std::size_t size(const mypoint3d<Real>& c)\n{\n    return 3;\n}\n\ntemplate<class Real>\nvoid test_data_representations()\n{\n    std::cout << \"Testing that the Catmull-Rom spline works with multiple data representations.\\n\";\n    mypoint3d<Real> p0(0.1, 0.2, 0.3);\n    mypoint3d<Real> p1(0.2, 0.3, 0.4);\n    mypoint3d<Real> p2(0.3, 0.4, 0.5);\n    mypoint3d<Real> p3(0.4, 0.5, 0.6);\n    mypoint3d<Real> p4(0.5, 0.6, 0.7);\n    mypoint3d<Real> p5(0.6, 0.7, 0.8);\n\n\n    // Tests initializer_list:\n    catmull_rom<mypoint3d<Real>> cat({p0, p1, p2, p3, p4, p5});\n\n    Real tol = 0.001;\n    auto p = cat(cat.parameter_at_point(0));\n    BOOST_CHECK_CLOSE_FRACTION(p[0], p0[0], tol);\n    BOOST_CHECK_CLOSE_FRACTION(p[1], p0[1], tol);\n    BOOST_CHECK_CLOSE_FRACTION(p[2], p0[2], tol);\n    p = cat(cat.parameter_at_point(1));\n    BOOST_CHECK_CLOSE_FRACTION(p[0], p1[0], tol);\n    BOOST_CHECK_CLOSE_FRACTION(p[1], p1[1], tol);\n    BOOST_CHECK_CLOSE_FRACTION(p[2], p1[2], tol);\n}\n\ntemplate<class Real>\nvoid test_random_access_container()\n{\n    std::cout << \"Testing that the Catmull-Rom spline works with multiple data representations.\\n\";\n    mypoint3d<Real> p0(0.1, 0.2, 0.3);\n    mypoint3d<Real> p1(0.2, 0.3, 0.4);\n    mypoint3d<Real> p2(0.3, 0.4, 0.5);\n    mypoint3d<Real> p3(0.4, 0.5, 0.6);\n    mypoint3d<Real> p4(0.5, 0.6, 0.7);\n    mypoint3d<Real> p5(0.6, 0.7, 0.8);\n\n    boost::numeric::ublas::vector<mypoint3d<Real>> u(6);\n    u[0] = p0;\n    u[1] = p1;\n    u[2] = p2;\n    u[3] = p3;\n    u[4] = p4;\n    u[5] = p5;\n\n    // Tests initializer_list:\n    catmull_rom<mypoint3d<Real>, decltype(u)> cat(std::move(u));\n\n    Real tol = 0.001;\n    auto p = cat(cat.parameter_at_point(0));\n    BOOST_CHECK_CLOSE_FRACTION(p[0], p0[0], tol);\n    BOOST_CHECK_CLOSE_FRACTION(p[1], p0[1], tol);\n    BOOST_CHECK_CLOSE_FRACTION(p[2], p0[2], tol);\n    p = cat(cat.parameter_at_point(1));\n    BOOST_CHECK_CLOSE_FRACTION(p[0], p1[0], tol);\n    BOOST_CHECK_CLOSE_FRACTION(p[1], p1[1], tol);\n    BOOST_CHECK_CLOSE_FRACTION(p[2], p1[2], tol);\n}\n\nBOOST_AUTO_TEST_CASE(catmull_rom_test)\n{\n#if !defined(TEST) || (TEST == 1)\n    test_data_representations<float>();\n    test_alpha_distance<double>();\n\n    test_linear<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_linear<long double>();\n#endif\n\n    test_circle<float>();\n    test_circle<double>();\n#endif\n#if !defined(TEST) || (TEST == 2)\n    test_helix<double>();\n\n    test_affine_invariance<double, 1>();\n    test_affine_invariance<double, 2>();\n    test_affine_invariance<double, 3>();\n    test_affine_invariance<double, 4>();\n\n    test_random_access_container<double>();\n#endif\n#if !defined(TEST) || (TEST == 3)\n    test_affine_invariance<cpp_bin_float_50, 4>();\n#endif\n}\n", "meta": {"hexsha": "78634687a0f70b193039a12dc7d27a491fc640e0", "size": 12241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/catmull_rom_test.cpp", "max_stars_repo_name": "anarthal/boost-unix-mirror", "max_stars_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-15T13:07:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T13:07:07.000Z", "max_issues_repo_path": "libs/math/test/catmull_rom_test.cpp", "max_issues_repo_name": "anarthal/boost-unix-mirror", "max_issues_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/test/catmull_rom_test.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:55:27.000Z", "avg_line_length": 28.4674418605, "max_line_length": 103, "alphanum_fraction": 0.5873703129, "num_tokens": 3855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6414286349323317}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_SPLITFACTOR_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_SPLITFACTOR_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Splitfactor Splitfactor (function template)\n\n  Generates a constant able to split IEEE values for precision issues\n\n  @headerref{<boost/simd/constant/splitfactor.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Splitfactor();\n      @endcode\n\n  2.  @code\n      template<typename T> T Splitfactor( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T that evaluates to the factor usable to split a IEEE754 value\n  into two parts in order to provide precision guarantee for some functions (like\n  [two_add](@ref real-two_add) or [two_prod](@ref real-two_prod).\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c as_integer_t<T> that evaluates to\n\n  | Type              | double                        | float         |\n  |:------------------|:------------------------------|---------------|\n  | **Values**        |   \\f$2^{27}\\f$                | \\f$2^{13}\\f$  |\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/splitfactor.hpp>\n#include <boost/simd/constant/simd/splitfactor.hpp>\n\n#endif\n", "meta": {"hexsha": "d810db6d7aed69499bae5ab75f29499c354d6b20", "size": 1928, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/splitfactor.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/splitfactor.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/splitfactor.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 33.8245614035, "max_line_length": 100, "alphanum_fraction": 0.5238589212, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6414286300795086}}
{"text": "//\n// Created by jcfei on 18-9-29.\n//\n\n#include <iostream>\n#include <vector>\n#include <complex>\n#include <math.h>\n#include \"time.h\"\nusing namespace std;\n//**********************************//\n#include <fftw3.h>\n#include \"mkl.h\"\n#include <omp.h>\n#include <armadillo>\n//**********************************//\n#include \"tensor.h\"\n#include \"tensor.cpp\"\n#include \"cp_als.cpp\"\n#include \"tucker_hosvd.cpp\"\n//**********************************//\n\ndouble gettime(){\n    struct timeval tv;\n    gettimeofday(&tv,NULL);\n    return tv.tv_sec*1000+tv.tv_usec/1000.0; //time:s\n};\n\nusing namespace std;\nusing namespace arma;\n\nint main() {\n    double t0,t1;\n    int I=3;\n    int rank=0.2*I; rank=1;\n\n    Tensor<float> a(I,I,I);\n    //initialization\n    for (int i = 0; i < a.n1; ++i) {\n        for (int j = 0; j < a.n2; ++j) {\n            for(int k=0; k< a.n3; ++k) {\n                a(i,j,k) = randu<float>();\n            }\n        }\n    }\n\n    t0=gettime();\n    tucker_core<float> result_tucker;\n    result_tucker = hosvd(a,rank,rank,rank);\n    t1=gettime();\n    cout << \"time:\" <<t1-t0 <<endl;\n\n    t0=gettime();\n    cp_mats<float> result;\n    result = cp_als(a,rank);\n    t1=gettime();\n    cout << \"time:\" <<t1-t0 <<endl;\n\n    return 0;\n\n}", "meta": {"hexsha": "42fd387ad3843fe6650c5f0faf30d650975cb8a8", "size": 1224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test.cpp", "max_stars_repo_name": "FreshHillyer/TensorLet_in_C_PlusPlus", "max_stars_repo_head_hexsha": "b27d4561d0335331bc28f1c6ea9bec7704664a66", "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.cpp", "max_issues_repo_name": "FreshHillyer/TensorLet_in_C_PlusPlus", "max_issues_repo_head_hexsha": "b27d4561d0335331bc28f1c6ea9bec7704664a66", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test.cpp", "max_forks_repo_name": "FreshHillyer/TensorLet_in_C_PlusPlus", "max_forks_repo_head_hexsha": "b27d4561d0335331bc28f1c6ea9bec7704664a66", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0655737705, "max_line_length": 53, "alphanum_fraction": 0.5147058824, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6414279395899537}}
{"text": "// gnuplot-c++ includes\n#include <gnuplot-iostream.h>\n\n// MLearn includes\n#include <MLearn/Core>\n#include <MLearn/Sampling/GaussianSampling.h>\n\n// STL includes\n#include <vector>\n#include <tuple>\n#include <string>\n#include <cmath>\n\n// Eigen includes\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\nint main(int argc, char** argv){\n\tstd::srand((unsigned int) time(0));\n\n\tGnuplot gp;\n\n\tusing namespace MLearn;\n\tusing namespace Sampling::Gaussian;\n\n\ttypedef double float_type;\n\ttypedef MLMatrix<float_type> Matrix;\n\ttypedef MLVector<float_type> Vector;\n\n\tuint DIM = 2;\n\tuint N = 5000;\n\n\t// compute a random covariance matrix\n\tMatrix random = Matrix::Random(DIM, DIM);\n\tEigen::JacobiSVD<Matrix> svd(random, \n\t\tEigen::ComputeFullU | Eigen::ComputeFullV );\n\tMatrix covariance = svd.matrixU();\n\tMatrix eig_val = (svd.singularValues().cwiseAbs().cwiseSqrt()).asDiagonal();\n\tcovariance = covariance*eig_val*eig_val;\n\tcovariance = covariance*(svd.matrixU().transpose());\n\t// compute mean\n\tVector mean = Vector::Random(DIM);\n\tmean.array() -= float_type(0.5);\n\t\n\t// sample\n\tMatrix samples = MultivariateGaussian<float_type>::sample(\n\t\tmean, covariance, N);\n\n\t// draw the samples\n\tstd::vector<std::pair<double, double> > xy_pts;\n\tfor(uint i = 0; i < N; ++i) {\n\t\txy_pts.push_back(std::make_pair(samples(0, i), samples(1, i)));\n\t}\n\tgp << \"set multiplot\\n\";\n\tgp << \"set xrange [-5:5]\\nset yrange [-5:5]\\n\";\n\tgp << \"plot '-' with points notitle\\n\";\n\tgp.send1d(xy_pts);\n\n\tgp << \"set parametric\\n\";\n\tgp << \"set trange [0:2*pi]\\n\";\n\tgp << \"fx(t)=\" + \n\t      std::to_string(svd.matrixU()(0,0)*eig_val(0,0)*1.96) +\n\t      \"*cos(t)+\" + \n\t      std::to_string(svd.matrixU()(0,1)*eig_val(1,1)*1.96) +\n\t      \"*sin(t)+\" + std::to_string(mean(0)) + \"\\n\";\n\tgp << \"fy(t) = \" + \n\t      std::to_string(svd.matrixU()(1,0)*eig_val(0,0)*1.96) +\n\t      \"*cos(t) + \" + \n\t      std::to_string(svd.matrixU()(1,1)*eig_val(1,1)*1.96) +\n\t      \"*sin(t) + \" + std::to_string(mean(1)) + \"\\n\"; \n\tgp << \"plot fx(t), fy(t) linecolor rgb \\\"blue\\\" notitle\\n\";\n\n\t\n\n\n\treturn 0;\n}", "meta": {"hexsha": "6b3159f3768c563424d45b5613587ece65cbd705", "size": 2024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/demo_sampling/multivariate_gaussian.cpp", "max_stars_repo_name": "phineasng/MLearn", "max_stars_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-11-14T19:37:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-05T02:29:35.000Z", "max_issues_repo_path": "demos/demo_sampling/multivariate_gaussian.cpp", "max_issues_repo_name": "phineasng/MLearn", "max_issues_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-01-23T17:49:50.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-25T22:43:30.000Z", "max_forks_repo_path": "demos/demo_sampling/multivariate_gaussian.cpp", "max_forks_repo_name": "phineasng/MLearn", "max_forks_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-23T18:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-23T18:17:14.000Z", "avg_line_length": 26.2857142857, "max_line_length": 77, "alphanum_fraction": 0.6378458498, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6414145406924081}}
{"text": "/*\n *  Copyright (C) 2003,2005 by Jarno Elonen\n *\n *  TPSDemo is Free Software / Open Source with a very permissive\n *  license:\n *\n *  Permission to use, copy, modify, distribute and sell this software\n *  and its documentation for any purpose is hereby granted without fee,\n *  provided that the above copyright notice appear in all copies and\n *  that both that copyright notice and this permission notice appear\n *  in supporting documentation.  The authors make no representations\n *  about the suitability of this software for any purpose.\n *  It is provided \"as is\" without express or implied warranty.\n */\n\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include \"spline.h\"\n#include \"ludecomposition.h\"\n\n#include <vector>\n#include <cmath>\n\nusing namespace boost::numeric::ublas;\n\n//-----------------------------------------------------------------------------\n\nstatic double tps_base_func(double r)\n{\n  if ( r == 0.0 )\n    return 0.0;\n  else\n    return r*r * log(r);\n}\n\n//-----------------------------------------------------------------------------\n\n/*\n *  Calculate Thin Plate Spline (TPS) weights from\n *  control points.\n */\ntpsdemo::Spline::Spline(const std::vector<Vec> & control_pts, double regularization)\n  : p(control_pts.size()),\n    control_points(control_pts),\n    mtx_v(p+3, 1),\n    mtx_orig_k(p, p)\n{\n  // You We need at least 3 points to define a plane\n  if ( control_points.size() < 3 )\n    throw std::runtime_error(\"need at least 3 points for thin plate spline\");\n\n  int id_number = rand() % 1000;\n\n  //unsigned p = control_points.size();\n\n  // Allocate the matrix and vector\n  matrix<double> mtx_l(p+3, p+3);\n  //matrix<double> mtx_v(p+3, 1);\n  //matrix<double> mtx_orig_k(p, p);\n\n  // Fill K (p x p, upper left of L) and calculate\n  // mean edge length from control points\n  //\n  // K is symmetrical so we really have to\n  // calculate only about half of the coefficients.\n  double a = 0.0;\n  for ( unsigned i=0; i<p; ++i )\n  {\n    for ( unsigned j=i+1; j<p; ++j )\n    {\n      Vec pt_i = control_points[i];\n      Vec pt_j = control_points[j];\n      pt_i.y = pt_j.y = 0;\n      double elen = (pt_i - pt_j).len();\n      mtx_l(i,j) = mtx_l(j,i) =\n        mtx_orig_k(i,j) = mtx_orig_k(j,i) =\n          tps_base_func(elen);\n      a += elen * 2; // same for upper & lower tri\n    }\n  }\n  a /= (double)(p*p);\n\n  // Fill the rest of L\n  for ( unsigned i=0; i<p; ++i )\n  {\n    // diagonal: reqularization parameters (lambda * a^2)\n    mtx_l(i,i) = mtx_orig_k(i,i) =\n      regularization * (a*a);\n\n    // P (p x 3, upper right)\n    mtx_l(i, p+0) = 1.0;\n    mtx_l(i, p+1) = control_points[i].x;\n    mtx_l(i, p+2) = control_points[i].z;\n\n    // P transposed (3 x p, bottom left)\n    mtx_l(p+0, i) = 1.0;\n    mtx_l(p+1, i) = control_points[i].x;\n    mtx_l(p+2, i) = control_points[i].z;\n  }\n  // O (3 x 3, lower right)\n  for ( unsigned i=p; i<p+3; ++i )\n    for ( unsigned j=p; j<p+3; ++j )\n      mtx_l(i,j) = 0.0;\n\n\n  // Fill the right hand vector V\n  for ( unsigned i=0; i<p; ++i )\n    mtx_v(i,0) = control_points[i].y;\n  mtx_v(p+0, 0) = mtx_v(p+1, 0) = mtx_v(p+2, 0) = 0.0;\n\n  // Solve the linear system \"inplace\"\n  if (0 != LU_Solve(mtx_l, mtx_v))\n  {\n    throw SingularMatrixError();\n  }\n}\n\n//-----------------------------------------------------------------------------\n\ndouble tpsdemo::Spline::interpolate_height(double x, double z) const\n{\n  double h = mtx_v(p+0, 0) + mtx_v(p+1, 0)*x + mtx_v(p+2, 0)*z;\n\n  Vec pt_i, pt_cur(x,0,z);\n  for ( unsigned i=0; i<p; ++i )\n  {\n    pt_i = control_points[i];\n    pt_i.y = 0;\n    h += mtx_v(i,0) * tps_base_func( ( pt_i - pt_cur ).len());\n  }\n  return h;\n}\n\n//-----------------------------------------------------------------------------\n\ndouble tpsdemo::Spline::compute_bending_energy() const\n{\n  matrix<double> w( p, 1 );\n  for ( unsigned i=0; i<p; ++i )\n    w(i,0) = mtx_v(i,0);\n  matrix<double> be = prod( prod<matrix<double> >( trans(w), mtx_orig_k ), w );\n  return be(0,0);\n}\n", "meta": {"hexsha": "f60464f1f052ae8cd44278118480537712ffbff1", "size": 3939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libmcc_lidar/tpsdemo/spline.cpp", "max_stars_repo_name": "rmsare/pymcc", "max_stars_repo_head_hexsha": "a41e52f97bf6ce8e4012576b296b71e89d0ff240", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-07-20T10:09:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T14:12:00.000Z", "max_issues_repo_path": "libmcc_lidar/tpsdemo/spline.cpp", "max_issues_repo_name": "rmsare/pymcc", "max_issues_repo_head_hexsha": "a41e52f97bf6ce8e4012576b296b71e89d0ff240", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-02-25T00:30:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-10T17:32:48.000Z", "max_forks_repo_path": "libmcc_lidar/tpsdemo/spline.cpp", "max_forks_repo_name": "rmsare/pymcc", "max_forks_repo_head_hexsha": "a41e52f97bf6ce8e4012576b296b71e89d0ff240", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T19:46:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-27T19:46:11.000Z", "avg_line_length": 27.3541666667, "max_line_length": 84, "alphanum_fraction": 0.5658796649, "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6413863077436631}}
{"text": "#include \"camera.hpp\"\n\n#include <Eigen/Geometry>\n\nMatrix4d worldFromCamera(const CameraExtrinsics& coordinates)\n{\n    auto world_from_camera = Matrix4d{Matrix4d::Identity()};\n    world_from_camera.col(3) << coordinates.x, coordinates.y, coordinates.z, 1.0;\n    using namespace Eigen;\n    auto R = Matrix3d{};\n    const auto R_flip  = AngleAxisd(3.14151965, Vector3d::UnitX());\n    const auto R_yaw   = AngleAxisd(coordinates.yaw, Vector3d::UnitY());\n    const auto R_pitch = AngleAxisd(coordinates.pitch, Vector3d::UnitX());\n    R = R_flip * R_yaw * R_pitch;\n    world_from_camera.topLeftCorner<3, 3>() = R;\n    return world_from_camera;\n}\n\nMatrix4d cameraFromWorld(const CameraExtrinsics& coordinates)\n{\n    return worldFromCamera(coordinates).inverse();\n}\n\nMatrix4d imageFromCamera(const CameraIntrinsics& c)\n{\n    auto image_from_camera = Matrix4d{};\n    image_from_camera <<\n        c.fx, 0.0, c.cx, 0.0,\n        0.0, c.fy, c.cy, 0.0,\n        0.0, 0.0, 0.0, 1.0,\n        0.0, 0.0, 1.0, 0.0;\n    return image_from_camera;\n}\n\nCameraIntrinsics makeCameraIntrinsics(size_t width, size_t height)\n{\n    auto intrinsics = CameraIntrinsics{};\n    intrinsics.fx = 0.5 * height;\n    intrinsics.fy = 0.5 * height;\n    intrinsics.cx = 0.5 * width;\n    intrinsics.cy = 0.5 * height;\n    intrinsics.width = width;\n    intrinsics.height = height;\n    return intrinsics;\n}\n", "meta": {"hexsha": "0eec304fa4f1cbfab5198511f54075004d0e2f4f", "size": 1361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/camera.cpp", "max_stars_repo_name": "mabur/rasterizer", "max_stars_repo_head_hexsha": "d896276f9e177decd4816f875b8e20d498f75dbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/camera.cpp", "max_issues_repo_name": "mabur/rasterizer", "max_issues_repo_head_hexsha": "d896276f9e177decd4816f875b8e20d498f75dbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/camera.cpp", "max_forks_repo_name": "mabur/rasterizer", "max_forks_repo_head_hexsha": "d896276f9e177decd4816f875b8e20d498f75dbe", "max_forks_repo_licenses": ["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.5869565217, "max_line_length": 81, "alphanum_fraction": 0.6796473181, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.641386298643767}}
{"text": "/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */\n\n#include \"cq/CQSpectrogram.h\"\n\n#include \"dsp/Window.h\"\n\n#include <cmath>\n#include <vector>\n#include <iostream>\n\nusing std::vector;\nusing std::cerr;\nusing std::endl;\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(TestCQFrequency)\n\n// The principle here is to feed a single windowed sinusoid into a\n// small CQ transform and check that the output has its peak bin at\n// the correct frequency. \n\n// Set up fs/2 = 50, frequency range 10 -> 40 i.e. 2 octaves, fixed\n// duration of 2 seconds\nstatic const cq_float sampleRate = 100;\nstatic const cq_float cqmin = 11.8921;\nstatic const cq_float cqmax = 40;\nstatic const cq_float bpo = 4;\nstatic const int duration = sampleRate * 2;\n\n// Threshold below which to ignore a column completely\nstatic const cq_float threshold = 0.08;\n\nint\nbinForFrequency(cq_float freq)\n{\n    int bin = (bpo * 2) - round(bpo * log2(freq / cqmin)) - 1;\n    return bin;\n}\n\nvoid\ncheckCQFreqColumn(int i, vector<cq_float> column,\n                  cq_float freq, CQSpectrogram::Interpolation interp)\n{\n    cq_float maxval = 0.0;\n    int maxidx = -1;\n    int height = column.size();\n\n    int nonZeroHeight = ((i % 2 == 1) ? height/2 : height);\n\n    for (int j = 0; j < nonZeroHeight; ++j) {\n        if (j == 0 || column[j] > maxval) {\n            maxval = column[j];\n            maxidx = j;\n        }\n    }\n\n    int expected = binForFrequency(freq);\n    if (maxval < threshold) {\n        return; // ignore these columns at start and end\n    } else if (expected < nonZeroHeight && maxidx != expected) {\n        cerr << \"ERROR: In column \" << i << \" with interpolation \" << interp\n             << \", maximum value for frequency \" << freq\n             << \"\\n       found at index \" << maxidx\n             << \" (expected index \" << expected << \")\" << endl;\n        cerr << \"column contains: \";\n        for (int j = 0; j < height; ++j) {\n            cerr << column[j] << \" \";\n        }\n        cerr << endl;\n        BOOST_CHECK_EQUAL(maxidx, expected);\n    }\n}\n\nvoid\ntestCQFrequencyWith(CQParameters params,\n                    CQSpectrogram::Interpolation interp,\n                    cq_float freq)\n{\n    CQSpectrogram cq(params, interp);\n\n    BOOST_CHECK_EQUAL(cq.getBinsPerOctave(), bpo);\n    BOOST_CHECK_EQUAL(cq.getOctaves(), 2);\n    BOOST_CHECK_CLOSE(cq.getBinFrequency(0), 40, 1e-10);\n    BOOST_CHECK_CLOSE(cq.getBinFrequency(4), 20, 1e-10);\n    BOOST_CHECK_CLOSE(cq.getBinFrequency(7), cqmin, 1e-3);\n    \n    vector<cq_float> input;\n    for (int i = 0; i < duration; ++i) {\n        input.push_back(sin((i * 2 * M_PI * freq) / sampleRate));\n    }\n    Window<cq_float>(HanningWindow, duration).cut(input.data());\n    \n    CQSpectrogram::RealBlock output = cq.process(input);\n    CQSpectrogram::RealBlock rest = cq.getRemainingOutput();\n    output.insert(output.end(), rest.begin(), rest.end());\n    \n    BOOST_CHECK_EQUAL(output[0].size(), \n                      cq.getBinsPerOctave() * cq.getOctaves());\n    \n    for (int i = 0; i < int(output.size()); ++i) {\n        checkCQFreqColumn(i, output[i], freq, interp);\n    }\n}\n\nvoid\ntestCQFrequency(cq_float freq)\n{\n    vector<CQSpectrogram::Interpolation> interpolationTypes;\n    interpolationTypes.push_back(CQSpectrogram::InterpolateZeros);\n    interpolationTypes.push_back(CQSpectrogram::InterpolateHold);\n    interpolationTypes.push_back(CQSpectrogram::InterpolateLinear);\n\n    for (int k = 0; k < int(interpolationTypes.size()); ++k) {\n        CQSpectrogram::Interpolation interp = interpolationTypes[k];\n        CQParameters params(sampleRate, cqmin, cqmax, bpo);\n        testCQFrequencyWith(params, interp, freq);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(freq_11) { testCQFrequency(11); }\nBOOST_AUTO_TEST_CASE(freq_17) { testCQFrequency(17); }\nBOOST_AUTO_TEST_CASE(freq_24) { testCQFrequency(24); }\nBOOST_AUTO_TEST_CASE(freq_27) { testCQFrequency(27); }\nBOOST_AUTO_TEST_CASE(freq_33) { testCQFrequency(33); }\nBOOST_AUTO_TEST_CASE(freq_40) { testCQFrequency(40); }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "5146c9933d52748a118025d446ff82f24bc02144", "size": 4099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/TestCQFrequency.cpp", "max_stars_repo_name": "ag4015/constant-q-cpp", "max_stars_repo_head_hexsha": "8bd538cf52b12884f2119d168bfe18f63656c60c", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/TestCQFrequency.cpp", "max_issues_repo_name": "ag4015/constant-q-cpp", "max_issues_repo_head_hexsha": "8bd538cf52b12884f2119d168bfe18f63656c60c", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/TestCQFrequency.cpp", "max_forks_repo_name": "ag4015/constant-q-cpp", "max_forks_repo_head_hexsha": "8bd538cf52b12884f2119d168bfe18f63656c60c", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8195488722, "max_line_length": 78, "alphanum_fraction": 0.6494266894, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6413862984403319}}
{"text": "// Copyright (C) 2012  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <dlib/filtering.h>\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <dlib/matrix.h>\n#include <dlib/rand.h>\n\n#include \"tester.h\"\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.filtering\");\n\n// ----------------------------------------------------------------------------------------\n\n    template <typename filter_type>\n    double test_filter (\n        filter_type kf,\n        int size\n    )\n    {\n        // This test has a point moving in a circle around the origin.  The point\n        // also gets a random bump in a random direction at each time step.\n\n        running_stats<double> rs;\n\n        dlib::rand rnd;\n        int count = 0;\n        const dlib::vector<double,3> z(0,0,1);\n        dlib::vector<double,2> p(10,10), temp;\n        for (int i = 0; i < size; ++i)\n        {\n            // move the point around in a circle\n            p += z.cross(p).normalize()/0.5;\n            // randomly drop measurements\n            if (rnd.get_random_double() < 0.7 || count < 4)\n            {\n                // make a random bump\n                dlib::vector<double,2> pp;\n                pp.x() = rnd.get_random_gaussian()/3;\n                pp.y() = rnd.get_random_gaussian()/3;\n\n                ++count;\n                kf.update(p+pp);\n            }\n            else\n            {\n                kf.update();\n                dlog << LTRACE << \"MISSED MEASUREMENT\";\n            }\n            // figure out the next position\n            temp = (p+z.cross(p).normalize()/0.5);\n            const double error = length(temp - rowm(kf.get_predicted_next_state(),range(0,1)));\n            rs.add(error);\n\n            dlog << LTRACE << temp << \"(\"<< error << \"): \" << trans(kf.get_predicted_next_state());\n\n            // test the serialization a few times.\n            if (count < 10)\n            {\n                ostringstream sout;\n                serialize(kf, sout);\n                istringstream sin(sout.str());\n                filter_type temp;\n                deserialize(temp, sin);\n                kf = temp;\n            }\n        }\n\n\n        return rs.mean();\n\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_kalman_filter()\n    {\n        matrix<double,2,2> R;\n        R = 0.3, 0,\n        0,  0.3;\n\n        // the variables in the state are \n        // x,y, x velocity, y velocity, x acceleration, and y acceleration\n        matrix<double,6,6> A;\n        A = 1, 0, 1, 0, 0, 0,\n        0, 1, 0, 1, 0, 0,\n        0, 0, 1, 0, 1, 0,\n        0, 0, 0, 1, 0, 1,\n        0, 0, 0, 0, 1, 0,\n        0, 0, 0, 0, 0, 1;\n\n        // the measurements only tell us the positions\n        matrix<double,2,6> H;\n        H = 1, 0, 0, 0, 0, 0,\n        0, 1, 0, 0, 0, 0;\n\n\n        kalman_filter<6,2> kf; \n        kf.set_measurement_noise(R);  \n        matrix<double> pn = 0.01*identity_matrix<double,6>();\n        kf.set_process_noise(pn);\n        kf.set_observation_model(H);\n        kf.set_transition_model(A);\n\n        DLIB_TEST(equal(kf.get_observation_model() , H));\n        DLIB_TEST(equal(kf.get_transition_model() , A));\n        DLIB_TEST(equal(kf.get_measurement_noise() , R));\n        DLIB_TEST(equal(kf.get_process_noise() , pn));\n        DLIB_TEST(equal(kf.get_current_estimation_error_covariance() , identity_matrix(pn)));\n\n        double kf_error = test_filter(kf, 300);\n\n        dlog << LINFO << \"kf error: \"<< kf_error;\n        DLIB_TEST_MSG(kf_error < 0.75, kf_error);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    void test_rls_filter()\n    {\n\n        rls_filter rls(10, 0.99, 0.1);\n\n        DLIB_TEST(rls.get_window_size() == 10);\n        DLIB_TEST(rls.get_forget_factor() == 0.99);\n        DLIB_TEST(rls.get_c() == 0.1);\n\n        double rls_error = test_filter(rls, 1000);\n\n        dlog << LINFO << \"rls error: \"<< rls_error;\n        DLIB_TEST_MSG(rls_error < 0.75, rls_error);\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class filtering_tester : public tester\n    {\n    public:\n        filtering_tester (\n        ) :\n            tester (\"test_filtering\",\n                    \"Runs tests on the filtering stuff (rls and kalman filters).\")\n        {}\n\n        void perform_test (\n        )\n        {\n            test_rls_filter();\n            test_kalman_filter();\n        }\n    } a;\n\n}\n\n\n", "meta": {"hexsha": "61dc88440373eda959749de9b7ad902718025a7c", "size": 4620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dlib/test/filtering.cpp", "max_stars_repo_name": "prathyusha12924/eye-gaze", "max_stars_repo_head_hexsha": "a80ad54b46e9cef4e743b53aaff035de83f27154", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "dlib/test/filtering.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "dlib/test/filtering.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 27.6646706587, "max_line_length": 99, "alphanum_fraction": 0.4772727273, "num_tokens": 1175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6413016928828927}}
{"text": "#include \"multiprecision/Multiprecision.h\"\n#include \"multiprecision/MPRotate.h\"\n#include \"multiprecision/MPReplicate.h\"\n#include \"algebra/Vector.hpp\"\n#include \"protocol/LR.hpp\"\n#include \"utils/timer.hpp\"\n#include <NTL/ZZ.h>\n#include <iostream>\n#include <map>\n\nint main() {\n    long m, p, r, P;\n    m = 5227;\n    p = 67499;\n    r = 1;\n    P = 1;\n    MPContext context(m, p, r, P);\n    context.buildModChain(8);\n    MPSecKey sk(context);\n    MPPubKey pk(sk);\n    MPEncArray ea(context);\n    printf(\"going to pack with %ld slots\\n\", ea.slots());\n    MDL::Vector<long> vec(13);\n    MDL::Matrix<long> mat(3, 3);\n    for (int i = 0; i < vec.dimension(); i++)\n        vec[i] = i;\n    mat[0][0] = 1; mat[0][1] = 2; mat[0][2] = 3;\n    mat[1][0] = 2; mat[1][1] = 3; mat[1][2] = 4;\n    mat[2][0] = 3; mat[2][1] = 4; mat[2][2] = 5;\n\n\tMPEncVector encVec(pk);\n    MPEncMatrix encMat, encMat2;\n    encVec.pack(vec, ea);\n    encMat.pack(mat, pk, ea);\n    encMat2.pack(mat, pk, ea);\n\n    // auto rep = repeat(encVec, ea, pk, vec.size(), vec.size());\n    // totalSums(rep, ea, vec.size());\n    // {\n    //     MDL::Vector<NTL::ZZ> res;\n    //     rep.unpack(res, sk, ea);\n    //     std::cout << res << \"\\n\";\n    // }\n    // MDL::Timer timer;\n    // timer.start();\n    // encMat = encMat.dot(encMat2, ea, pk, 3);\n    // timer.end();\n    // MDL::Matrix<NTL::ZZ> zzMat(3, 3);\n    // encMat.unpack(zzMat, sk, ea, true);\n    // std::cout << zzMat << \"\\n\";\n    // printf(\"mult %f\\n\", timer.second());\n    return 0;\n}\n", "meta": {"hexsha": "54298dcd69573d2102df925faf149f2d45544b6f", "size": 1494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_MPContext.cpp", "max_stars_repo_name": "fionser/MDLHElib", "max_stars_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T06:20:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-17T12:36:34.000Z", "max_issues_repo_path": "test/test_MPContext.cpp", "max_issues_repo_name": "fionser/MDLHElib", "max_issues_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_MPContext.cpp", "max_forks_repo_name": "fionser/MDLHElib", "max_forks_repo_head_hexsha": "3c686ab35d7b26a893213a6e9d4249cd46c2969d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-08-26T13:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-15T02:08:20.000Z", "avg_line_length": 27.6666666667, "max_line_length": 65, "alphanum_fraction": 0.5448460509, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.6412889006940006}}
{"text": "/**\n * @file benchmark_eigen_solver.cpp\n * @author remzerrr (remi.helleboid@gmail.com)\n * @brief\n * @version 0.1\n * @date 2021-09-25\n *\n * @copyright Copyright (c) 2021\n *\n */\n\n#include <benchmark/benchmark.h>\n\n#include <iostream>\n#include <random>\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n//  SIZE_SYSTEM is basically the number of nodes in the mesh\nstatic constexpr std::size_t SIZE_SYSTEM = 10;\n//  NUMBER_ITERATION is used to simulate the great number of time poisson equation will be solved in MonteCarlo process.\nstatic constexpr std::size_t NUMBER_ITERATION = 10'000;\n\n    Eigen::SparseMatrix<double>\n    create_laplacian_matrix(const std::size_t size) {\n    typedef Eigen::Triplet<double> T;\n    std::vector<T>                 tripletList;\n    const std::size_t              non_zero_estimation = 3 * size;\n    tripletList.reserve(non_zero_estimation);\n    //  Filling respectively the upper diagonal, the diagonal and the lower diagonal.\n    for (std::size_t index_row = 1; index_row < size - 1; ++index_row) {\n        tripletList.push_back(T(index_row, index_row + 1, -1.0));\n        tripletList.push_back(T(index_row, index_row, 2.0));\n        tripletList.push_back(T(index_row - 1, index_row, -1.0));\n    }\n    //  Filling the first and last line of the matrix\n    tripletList.push_back(T(0, 0, 2.0));\n    tripletList.push_back(T(size - 1, size - 1, 2.0));\n\n    Eigen::SparseMatrix<double> MatrixPoisson(size, size);\n    MatrixPoisson.setFromTriplets(tripletList.begin(), tripletList.end());\n\n    std::cout << MatrixPoisson << std::endl;\n    return MatrixPoisson;\n}\n\nEigen::VectorXd create_random_vector(const std::size_t size) {\n    Eigen::VectorXd RandomVector = Eigen::VectorXd::Random(size);\n    return RandomVector;\n}\n\nstatic void EIGEN_LU_BENCH(benchmark::State &state) {\n    Eigen::SparseMatrix<double> PoissonMatrix = create_laplacian_matrix(SIZE_SYSTEM);\n    Eigen::VectorXd RandomVector = create_random_vector(SIZE_SYSTEM);\n\n    Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int> > LU_Solver;\n    LU_Solver.analyzePattern(PoissonMatrix);\n    LU_Solver.factorize(PoissonMatrix);\n    for (auto _ : state) {\n        for (std::size_t iteration = 0; iteration < NUMBER_ITERATION; ++ iteration) {\n            LU_Solver.solve(RandomVector);\n        }\n    }\n}\n\nBENCHMARK(EIGEN_LU_BENCH);\n// Run the benchmark\nBENCHMARK_MAIN();", "meta": {"hexsha": "250de5a4818c928d111fbfa515ced5837a928c8e", "size": 2368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/benchmark_eigen_solver.cpp", "max_stars_repo_name": "RemiHelleboid/bench_linear_solver", "max_stars_repo_head_hexsha": "5f6182b93b75d94d582f75f2c3310090aa9e77fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmarks/benchmark_eigen_solver.cpp", "max_issues_repo_name": "RemiHelleboid/bench_linear_solver", "max_issues_repo_head_hexsha": "5f6182b93b75d94d582f75f2c3310090aa9e77fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/benchmark_eigen_solver.cpp", "max_forks_repo_name": "RemiHelleboid/bench_linear_solver", "max_forks_repo_head_hexsha": "5f6182b93b75d94d582f75f2c3310090aa9e77fb", "max_forks_repo_licenses": ["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.3188405797, "max_line_length": 120, "alphanum_fraction": 0.7005912162, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6412888964339294}}
{"text": "/********************************************************************\n\tcreated:\t2012/08/27\n\tcreated:\t27:8:2012   8:40\n\tfilename: \tE:\\Sync\\Dropbox\\Codes\\glycan_pipeline\\GAG\\src\\GAGPL\\SPECTRUM\\IsotopicDistribution.cpp\n\tfile path:\tE:\\Sync\\Dropbox\\Codes\\glycan_pipeline\\GAG\\src\\GAGPL\\SPECTRUM\n\tfile base:\tIsotopicDistribution\n\tfile ext:\tcpp\n\tauthor:\t\tHan Hu\n\t\n\tpurpose:\t\n*********************************************************************/\n#include \"GAGPL/SPECTRUM/IsotopicDistribution.h\"\n#include \"GAGPL/MISC/Param.h\"\n\n#include <time.h>\n#include <algorithm>\n#include <sstream>\n#include <fstream>\n\n#include <boost/make_shared.hpp>\n#include <boost/xpressive/xpressive.hpp>\n#include <boost/lexical_cast.hpp>\n\nnamespace gag\n{\n\tvoid IsotopicDistribution::createMonoPeak()\n\t{\n\t\t// Get the monoisotopic isotope for each element of the composition.\n\t\tmonopeak.mz = _compo.getMass();\n\n\t\tconst std::map<std::string, int> ele_count = _compo.get();\n\n\t\tstd::map<std::string, int>::const_iterator it = ele_count.begin();\n\n\t\tfor(; it != ele_count.end(); it++)\n\t\t{\n\t\t\t// For each element, get the value of prob^coef.\n\t\t\tPeriodicTable& ptable = PeriodicTable::Instance();\n\t\t\tIsotope iso = ptable.getIsotopeByRelativeShift(it->first);\n\t\t\tmonopeak.intensity += it->second * log(iso.abundance);\n\t\t}\n\t\tmonopeak.intensity = exp(monopeak.intensity);\n\n\t}\n\n\tdouble IsotopicDistribution::calculatePhiValue(size_t order)\n\t{\n\t\tdouble phi_value = 0.0;\n\n\t\t// For each element, get the phi factor.\n\t\tconst std::map<std::string, int> ele_count = _compo.get();\n\n\t\tstd::map<std::string, int>::const_iterator it = ele_count.begin();\n\n\t\t// Iterate over all elements.\n\t\tfor(; it != ele_count.end(); it++)\n\t\t{\n\t\t\tphi_value += _iso_const.getNthElementPowerSum(it->first, order) * it->second;\n\t\t}\n\n\t\treturn phi_value;\n\t}\n\n\t//PowerSumVec IsotopicDistribution::calculatePhiValueVec()\n\t//{\n\t//\tPowerSumVec phi_value_vec;\n\t//\t// phi(0) = 0.\n\t//\tphi_value_vec.push_back(0);\n\n\t//\tfor(size_t i=1; i<=_var_num; i++)\n\t//\t{\n\t//\t\tphi_value_vec.push_back(this->calculatePhiValue(i));\n\t//\t}\n\t//\t\t\n\t//\treturn phi_value_vec;\n\t//}\n\n\tEleSymPolyVec IsotopicDistribution::calculateProbabilityVec()\n\t{\n\t\t//clock_t t = clock(); clock_t last_t = t;\n\t\tPowerSumVec phi_vec = this->calculatePhiValueVec();\n\t\t//t = clock()-last_t; last_t = clock();\n\t\t//std::cout << \"Step 1: calculating phi value vec: \" << (double)t/CLOCKS_PER_SEC << \"s\\n\";\n\n\t\tNewtonGirardFormulae newton(_compo.getMaxNumVariants());\n\t\tEleSymPolyVec prob_vec;\n\t\tnewton.updateParameters(phi_vec, prob_vec);\n\t\t//t = clock()-last_t; last_t = clock();\n\t\t//std::cout << \"Step 2: newton: \" << (double)t/CLOCKS_PER_SEC << \"s\\n\";\n\n\t\tfor(size_t i=0; i<prob_vec.size(); i++)\n\t\t{\n\t\t\tint sign = (i%2 == 0 ? 1 : -1);\n\t\t\t// q(j) = q(0) * e(j) * (-1)^j.\n\t\t\tprob_vec[i] = prob_vec[i] * monopeak.intensity * sign;\n\t\t}\n\n\t\treturn prob_vec;\n\t}\n\n\tdouble IsotopicDistribution::calculateModifiedPhiValue(const std::string& symbol, size_t order)\n\t{\n\t\t\n\t\tdouble phi_value = phi_value_vec.at(order) - _iso_const.getNthElementPowerSum(symbol, order) + _iso_const.getNthModifiedElementPowerSum(symbol, order);\n\n\t\treturn phi_value;\n\t}\n\n\tPowerSumVec IsotopicDistribution::calculateModifiedPhiValueVec(const std::string& symbol)\n\t{\n\t\tPowerSumVec modified_phi_value_vec;\n\t\t// phi(0) = 1.\n\t\tmodified_phi_value_vec.push_back(0);\n\n\t\tfor(size_t i=1; i<=_var_num; i++)\n\t\t{\n\t\t\tmodified_phi_value_vec.push_back(this->calculateModifiedPhiValue(symbol, i));\n\t\t}\n\n\t\treturn modified_phi_value_vec;\n\t}\n\n\tstd::vector<double> IsotopicDistribution::calculateCenterMassVec(const EleSymPolyVec& prob_vec)\n\t{\n\t\tstd::vector<double> mass_vec;\n\n\t\tstd::map<std::string, int> ele_count = _compo.get();\n\n\t\tPeriodicTable& ptable = PeriodicTable::Instance();\n\n\t\tNewtonGirardFormulae newton(_compo.getMaxNumVariants());\n\n\t\tstd::map<std::string, EleSymPolyVec> esp_map;\n\t\t//clock_t t = clock(); \n\t\tfor(std::map<std::string, int>::const_iterator it = ele_count.begin();\n\t\t\tit != ele_count.end(); it++)\n\t\t{\n\t\t\tconst Isotope& mono = ptable.getIsotopeByRelativeShift(it->first);\n\n\t\t\tPowerSumVec& ps_vec = this->calculateModifiedPhiValueVec(it->first);\n\t\t\tEleSymPolyVec esp_vec;\n\t\t\tnewton.updateParameters(ps_vec, esp_vec);\n\n\t\t\tesp_map.insert(std::make_pair(it->first, esp_vec));\n\t\t}\n\t\t//t = clock()-t;\n\t\t//std::cout << \"Modified Phi Vec: \" << (double)t/CLOCKS_PER_SEC << \"s\\n\";\n\n\t\tfor(size_t i = 0; i <= _var_num; i++)\n\t\t{\n\t\t\tstd::map<std::string, EleSymPolyVec>::iterator it = esp_map.begin();\n\t\t\tint sign = (i%2 == 0 ? 1 : -1);\n\t\t\tdouble center_mass = 0.0;\n\t\t\tfor(; it != esp_map.end(); it++)\n\t\t\t{\n\t\t\t\tconst Isotope& mono = ptable.getIsotopeByRelativeShift(it->first);\n\n\t\t\t\tcenter_mass += ele_count[it->first] * sign * it->second.at(i) * monopeak.intensity * mono.mass;\n\t\t\t}\n\t\t\t// m(j) = sum(m(jk) * p(jk))/sum(p(jk))\n\t\t\tmass_vec.push_back(center_mass/prob_vec.at(i));\n\t\t}\n\n\t\treturn mass_vec;\n\t}\n\n\tvoid IsotopicDistribution::setOrder(int order)\n\t{\n\t\t// Controlling the number of variants, and prevent unnecessary calculation.\n\t\tsize_t max_num = _compo.getMaxNumVariants();\n\t\tif(order == 0) {\n\t\t\t// Default value calculated by formula 2.\t\t\t\n\t\t\tint heu = std::max((int)ceil(abs(2 * (_compo.getMass() - _compo.getAverageMass()))), 50);\n\t\t\t_var_num = (size_t)heu > max_num ? max_num : (size_t)heu;\n\t\t} else if(order > 0)\n\t\t\t_var_num = (size_t)order > max_num ? max_num : (size_t)order;\n\t\telse\n\t\t\tthrow std::runtime_error(\"Error: invalid order number.\");\n\n\t\t_var_num--;\n\n\t\t// Adding elements from the composition into _iso_const.\n\t\tupdateIsotopicConstants();\n\t}\n\n\tAggregatedIsotopicVariants IsotopicDistribution::getAggregatedIsotopicVariants(int charge /* = 0 */)\n\t{\n\t\t//clock_t t = clock(); clock_t last_t = t;\n\t\tEleSymPolyVec prob_vec = this->calculateProbabilityVec();\n\n\t\t//t = clock()-last_t; last_t = clock();\n\t\t//std::cout << \"Prob Vec: \" << (double)t/CLOCKS_PER_SEC << \"s\\n\";\n\n\t\tstd::vector<double> center_mass_vec = this->calculateCenterMassVec(prob_vec);\n\t\t//t = clock()-last_t; last_t = clock();\n\t\t//std::cout << \"Mass Vec: \" << (double)t/CLOCKS_PER_SEC << \"s\\n\";\n\n\t\tAggregatedIsotopicVariants peakset;\n\n\t\tavg_mass = 0.0; \n\t\tdouble sum(0.0);\n\n\n\t\tfor(size_t i=0; i<= _var_num; i++)\n\t\t{\n\t\t\tdouble adjusted_mz = (charge == 0 ? center_mass_vec.at(i): calculateMZ(center_mass_vec.at(i), charge));\n\n\t\t\tPeakPtr peak = boost::make_shared<Peak>(adjusted_mz, prob_vec.at(i));\n\t\t\tpeakset.addPeak(peak);\t\n\n\t\t\t// Code for calculating avg_mass\n\t\t\tavg_mass += adjusted_mz * prob_vec.at(i);\n\t\t\tsum += prob_vec.at(i);\n\t\t}\n\n\t\tavg_mass /= sum;\n\n\t\treturn peakset;\n\n\t}\n\n\tvoid IsotopicDistribution::updateIsotopicConstants()\n\t{\n\t\tconst std::map<std::string, int> ele_count = _compo.get();\n\n\t\tstd::map<std::string, int>::const_iterator it = ele_count.begin();\n\n\t\t// Build the constants for all elements.\n\t\tfor(; it != ele_count.end(); it++)\n\t\t\t_iso_const.addElement(it->first);\n\n\t\t_iso_const.updateOrder(_var_num);\n\t}\n\n\tvoid IsotopicDistribution::updatePhiValueVec()\n\t{\n\t\tphi_value_vec.clear();\n\t\tphi_value_vec.push_back(0);\n\t\tfor(size_t i=1; i<=_var_num; i++)\n\t\t{\n\t\t\tphi_value_vec.push_back(this->calculatePhiValue(i));\n\t\t}\n\t}\n\n\tdouble calculateMass( double mz, int charge)\n\t{\t\n\t\t// Be careful of the ion mode.\n\t\tparam::Param& param = param::Param::Instance();\n\t\tdouble electron_mass = param.getParameter<double>(\"electron_mass\").first;\n\n\t\treturn abs(charge) * mz - charge * (Composition(\"H\").getMass() -electron_mass);\n\t}\n\n\tdouble calculateMZ(double mass, int charge, int pre_charge /* = 0 */)\n\t{\n\t\tparam::Param& param = param::Param::Instance();\n\t\tdouble electron_mass = param.getParameter<double>(\"electron_mass\").first;\n\n\t\tint coef_h = (pre_charge == 0 ? charge : pre_charge);\n\n\t\t// TBD: this should be controlled by parameter.\n\t\t// int coef_e = (pre_charge == 0 ? 1 : 0);\n\t\treturn (mass + coef_h * (Composition(\"H\").getMass() - electron_mass))/abs(charge);\n\t}\n}", "meta": {"hexsha": "e9781cf3523cc4e2720299240892fc529b5f4690", "size": 7789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GAG/src/GAGPL/SPECTRUM/IsotopicDistribution.cpp", "max_stars_repo_name": "hh1985/multi_hs_seq", "max_stars_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-03T14:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-15T13:38:39.000Z", "max_issues_repo_path": "GAG/src/GAGPL/SPECTRUM/IsotopicDistribution.cpp", "max_issues_repo_name": "hh1985/multi_hs_seq", "max_issues_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GAG/src/GAGPL/SPECTRUM/IsotopicDistribution.cpp", "max_forks_repo_name": "hh1985/multi_hs_seq", "max_forks_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_forks_repo_licenses": ["Apache-2.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.3924528302, "max_line_length": 153, "alphanum_fraction": 0.6730003852, "num_tokens": 2358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759492, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6411997479968259}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2010 Klaus Spanderen\n \n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file extendedornsteinuhlenbeckprocess.hpp\n    \\brief extended Ornstein-Uhlenbeck process\n*/\n\n#ifndef quantlib_extended_ornstein_uhlenbeck_process_hpp\n#define quantlib_extended_ornstein_uhlenbeck_process_hpp\n\n#include <ql/stochasticprocess.hpp>\n\n#include <boost/function.hpp>\n\nnamespace QuantLib {\n\n    class OrnsteinUhlenbeckProcess;\n\n    //! Extended Ornstein-Uhlenbeck process class\n    /*! This class describes the Ornstein-Uhlenbeck process governed by\n        \\f[\n            dx = a (b(t) - x_t) dt + \\sigma dW_t.\n        \\f]\n\n        \\ingroup processes\n    */\n    class ExtendedOrnsteinUhlenbeckProcess : public StochasticProcess1D {\n      public:\n        enum Discretization { MidPoint, Trapezodial, GaussLobatto };\r\n\n        ExtendedOrnsteinUhlenbeckProcess(\n                                Real speed, Volatility sigma, Real x0,\n                                const boost::function<Real (Real)>& b,\n                                Discretization discretization = MidPoint,\n                                Real intEps = 1e-4);\n\n        //! \\name StochasticProcess interface\n        //@{\n        Real x0() const;\n        Real speed() const;\n        Real volatility() const;\n        Real drift(Time t, Real x) const;\n        Real diffusion(Time t, Real x) const;\n        Real expectation(Time t0, Real x0, Time dt) const;\n        Real stdDeviation(Time t0, Real x0, Time dt) const;\n        Real variance(Time t0, Real x0, Time dt) const;\n        //@}\n      private:\n        const Real speed_;\n        const Volatility vol_;\n        const boost::function<Real (Real)> b_;\n        const Real intEps_;\n        const boost::shared_ptr<OrnsteinUhlenbeckProcess> ouProcess_;\n        const Discretization discretization_;\n    };\n}\n\n\n#endif\n", "meta": {"hexsha": "282d9aed418675ca01e1cc3bbaf3f14fd5904d54", "size": 2548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/processes/extendedornsteinuhlenbeckprocess.hpp", "max_stars_repo_name": "grandtiger/quantlib", "max_stars_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "ql/experimental/processes/extendedornsteinuhlenbeckprocess.hpp", "max_issues_repo_name": "grandtiger/quantlib", "max_issues_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T18:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T18:49:22.000Z", "max_forks_repo_path": "ql/experimental/processes/extendedornsteinuhlenbeckprocess.hpp", "max_forks_repo_name": "grandtiger/quantlib", "max_forks_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 33.5263157895, "max_line_length": 79, "alphanum_fraction": 0.6616954474, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6411997440317108}}
{"text": "#include <armadillo>\n#include <chrono>\n#include <random>\n#include <stdlib.h>\n\nusing namespace std;\nusing namespace arma;\n\n//Test cases\n#define TEST_CREATE         1\n#define TEST_SCALE          2\n#define TEST_TRANSPOSE      3\n#define TEST_ADD            4\n#define TEST_SUB            5\n#define TEST_DOT            6\n#define TEST_DET            7\n#define TEST_EIGEN          8\n#define TEST_SVD            9\n#define TEST_CHOL           10\n", "meta": {"hexsha": "af951af5fe0f6df9f45261d442f23dddf6e31d9e", "size": 436, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "speed_tests/linalg_tests/cpp/mat_test.hpp", "max_stars_repo_name": "bayesiangopher/bayesiangopher", "max_stars_repo_head_hexsha": "d6787636312c8dee889ef260d57883b9e6fdb7cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-13T13:07:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T11:03:16.000Z", "max_issues_repo_path": "speed_tests/linalg_tests/cpp/mat_test.hpp", "max_issues_repo_name": "bayesiangopher/bayesiangopher", "max_issues_repo_head_hexsha": "d6787636312c8dee889ef260d57883b9e6fdb7cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-03-14T10:31:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T11:44:19.000Z", "max_forks_repo_path": "speed_tests/linalg_tests/cpp/mat_test.hpp", "max_forks_repo_name": "bayesiangopher/bayesiangopher", "max_forks_repo_head_hexsha": "d6787636312c8dee889ef260d57883b9e6fdb7cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-03-13T13:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-02T12:23:31.000Z", "avg_line_length": 21.8, "max_line_length": 30, "alphanum_fraction": 0.6077981651, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6411997435220692}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <autodiff/forward.hpp>\n#include <autodiff/forward/eigen.hpp>\n#include <cmath>\n\nnamespace ast\n{\ntypedef autodiff::dual Real;\ntypedef autodiff::VectorXdual Vec;\n\ntypedef double RealV;\ntypedef Eigen::MatrixXd Mat;\ntypedef Eigen::VectorXd VecV;\n\n\nconstexpr RealV epsilon = 0.001;\n\n\nusing namespace Eigen;\nusing namespace autodiff;\n\n//struct QBody : public Vec3\n//{\n//  QBody() : Vec3()\n//  {}\n\n//  QBody(Real th, Real x, Real y) : Vec3(th, x, y)\n//  {}\n\n//  template<typename OtherDerived>\n//  QBody(const Eigen::MatrixBase<OtherDerived>& other) : Vec3(other)\n//  { }\n\n//  template<typename OtherDerived>\n//  QBody& operator=(const Eigen::MatrixBase<OtherDerived>& other)\n//  {\n//     this->Vec3::operator=(other);\n//     return *this;\n//  }\n\n//  Real& th() { return this->data()[0]; }\n\n//  const Real& th() const { return this->data()[0]; }\n\n//  Real& theta() { return this->data()[0]; }\n\n//  const Real& theta() const { return this->data()[0]; }\n\n//  Real& x() { return this->data()[1]; }\n\n//  const Real& x() const { return this->data()[1]; }\n\n//  Real& y() { return this->data()[2]; }\n\n//  const Real& y() const { return this->data()[2]; }\n//};\n\n\ninline Real sat(Real x, Real lim)\n{\n  if(x > lim)\n    return lim;\n  else if(x < -lim)\n    return - lim;\n  else\n    return x;\n}\n\ninline Real clipToRange(Real x, Real rMin, Real rMax)\n{\n  if(x < rMin)\n    return  rMin;\n  else if (x > rMax)\n    return rMax;\n  else return x;\n}\n\ninline Real sq(Real x)\n{\n  return x*x;\n}\n\ninline Real cube(Real x)\n{\n  return x*x*x;\n}\n\ninline int sign(Real val)\n{\n  return (0 < val) - (val < 0);\n}\n\ntemplate <typename T>\ninline Real distance(const T& a , const T& b)\n{\n  return (b-a).norm();\n}\n\ninline RealV continuousAngle(RealV angle, RealV lastAngle)\n{\n    auto dAngle = fmod(angle, 2*M_PI) - fmod(lastAngle, 2*M_PI);\n\n    if (dAngle > M_PI)\n        return lastAngle + dAngle - 2.0 * M_PI;\n    else if (dAngle < -M_PI)\n        return lastAngle + dAngle + 2.0 * M_PI;\n    else\n        return lastAngle + dAngle;\n}\n\ninline Real discontinuousAngle(Real angle)\n{\n    return atan2(sin(angle), cos(angle));\n}\n\n\n}\n", "meta": {"hexsha": "7f6b88145694d1a2eff6b4d5d4a9e1b56abc72f3", "size": 2152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ast_ros/include/ast/math.hpp", "max_stars_repo_name": "tgawronput/automation_synthesis_toolkit", "max_stars_repo_head_hexsha": "78507222c6a6d428b3d4d11756aabb093270fec6", "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": "ast_ros/include/ast/math.hpp", "max_issues_repo_name": "tgawronput/automation_synthesis_toolkit", "max_issues_repo_head_hexsha": "78507222c6a6d428b3d4d11756aabb093270fec6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ast_ros/include/ast/math.hpp", "max_forks_repo_name": "tgawronput/automation_synthesis_toolkit", "max_forks_repo_head_hexsha": "78507222c6a6d428b3d4d11756aabb093270fec6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.7851239669, "max_line_length": 69, "alphanum_fraction": 0.6198884758, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6411997331556478}}
{"text": "#include <armadillo>\n#include <iostream>\n\nusing namespace arma;\n\nint main() {\n    mat A(3, 2, fill::randn);\n    A.print(\"A:\");\n    mat B(2, 4, fill::randn);\n    B.print(\"B:\");\n    mat C = A*B;\n    C.print(\"A*B:\");\n    return 0;\n}\n", "meta": {"hexsha": "58afc67f53cc38da6b4a087015c8f0ffd86142ba", "size": 230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Armadillo/matrix_product.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Armadillo/matrix_product.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Armadillo/matrix_product.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 15.3333333333, "max_line_length": 29, "alphanum_fraction": 0.5260869565, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6411986586323699}}
{"text": "/* \n   Program to solve the two-dimensional Ising model \n   with zero external field and no parallelization\n   Parallel version using MPI\n   The coupling constant J is set to J = 1\n   Boltzmann's constant = 1, temperature has thus dimension energy\n   Metropolis aolgorithm  is used as well as periodic boundary conditions.\n   The code needs an output file on the command line and the variables mcs, nspins,\n   initial temp, final temp and temp step.\n   Run as\n   ./executable Outputfile numberof spins number of MC cycles initial temp final temp tempstep\n   ./test.x Lattice 100 10000000 2.1 2.4 0.01\n   Compile and link as \n   c++ -O3 -std=c++11 -Rpass=loop-vectorize -o Ising.x IsingModel.cpp -larmadillo -lomp\n*/\n\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <cstdlib>\n#include <random>\n#include <armadillo>\n#include <string>\n#include \"omp.h\"\n#define NUM_THREADS 4\nusing namespace  std;\nusing namespace arma;\n// output file\nofstream ofile;\n\n// inline function for PeriodicBoundary boundary conditions\ninline int PeriodicBoundary(int i, int limit, int add) { \n  return (i+limit+add) % (limit);\n}\n// Function to initialise energy and magnetization\nvoid InitializeLattice(int, mat &, double&, double&);\n// The metropolis algorithm including the loop over Monte Carlo cycles\nvoid MetropolisSampling(int, int, double, vec &);\n// prints to file the results of the calculations  \nvoid WriteResultstoFile(int, int, double, vec);\n\n// Main program begins here\n\nint main(int argc, char* argv[])\n{\n  string filename;\n  int NSpins, MonteCarloCycles;\n  double InitialTemp, FinalTemp, TempStep;\n  if (argc <= 5) {\n    cout << \"Bad Usage: \" << argv[0] << \n      \" read output file, Number of spins, MC cycles, initial and final temperature and tempurate step\" << endl;\n    exit(1);\n  }\n  filename=argv[1];\n  // Initializations\n  NSpins = atoi(argv[2]); MonteCarloCycles = atoi(argv[3]); InitialTemp = atof(argv[4]);  FinalTemp = atof(argv[5]);  TempStep = atof(argv[6]);\n  string fileout = filename;\n  string argument = to_string(NSpins);\n  fileout.append(argument);\n  ofile.open(fileout);\n  cout << \"  C++/OpenMP version\" << endl;\n  cout << \"  Ising model with OpenMP\" << endl;\n  omp_set_num_threads(NUM_THREADS);\n    //  int thread_num = omp_get_max_threads ( );\n  cout << \"  The number of processors available = \" << omp_get_num_procs ( ) << endl;\n  // defining time and various variables needed for the integration\n  double wtime = omp_get_wtime ( );\n  // Monte Carlo cycles\n  for (double Temperature = InitialTemp; Temperature <= FinalTemp; Temperature+=TempStep){\n    vec ExpectationValues = zeros<mat>(5);\n    // Start Monte Carlo computation and get local expectation values\n    // This may need a fix!!  \n# pragma omp parallel for default(shared) reduction(+:ExpectationValues)\n    MetropolisSampling(NSpins, MonteCarloCycles, Temperature, ExpectationValues);\n    WriteResultstoFile(NSpins, MonteCarloCycles, Temperature, ExpectationValues);\n  }\n  wtime = omp_get_wtime ( ) - wtime;\n  cout << \"  Elapsed time in seconds = \" << wtime << endl;\n  ofile.close();  // close output file\n  return 0;\n}\n\n\n// The Monte Carlo part with the Metropolis algo with sweeps over the lattice\nvoid MetropolisSampling(int NSpins, int MonteCarloCycles, double Temperature, vec &ExpectationValues)\n{\n  // Initialize the seed and call the Mersienne algo\n  std::random_device rd;\n  std::mt19937_64 gen(rd());\n  // Set up the uniform distribution for x \\in [[0, 1]\n  std::uniform_real_distribution<double> RandomNumberGenerator(0.0,1.0);\n  // Initialize the lattice spin values\n  mat SpinMatrix = zeros<mat>(NSpins,NSpins);\n  //    initialize energy and magnetization \n  double Energy = 0.;     double MagneticMoment = 0.;\n  // initialize array for expectation values\n  InitializeLattice(NSpins, SpinMatrix, Energy, MagneticMoment);\n  // setup array for possible energy changes\n  vec EnergyDifference = zeros<mat>(17); \n  for( int de =-8; de <= 8; de+=4) EnergyDifference(de+8) = exp(-de/Temperature);\n  // Start Monte Carlo experiments\n  int AllSpins = NSpins*NSpins;\n  for (int cycles = 1; cycles <= MonteCarloCycles; cycles++){\n    // The sweep over the lattice, looping over all spin sites\n    for(int Spins =0; Spins < AllSpins; Spins++) {\n      int ix = (int) (RandomNumberGenerator(gen)*NSpins);\n      int iy = (int) (RandomNumberGenerator(gen)*NSpins);\n      int deltaE =  2*SpinMatrix(ix,iy)*\n\t(SpinMatrix(ix,PeriodicBoundary(iy,NSpins,-1))+\n\t SpinMatrix(PeriodicBoundary(ix,NSpins,-1),iy) +\n\t SpinMatrix(ix,PeriodicBoundary(iy,NSpins,1)) +\n\t SpinMatrix(PeriodicBoundary(ix,NSpins,1),iy));\n      if ( RandomNumberGenerator(gen) <= EnergyDifference(deltaE+8) ) {\n\tSpinMatrix(ix,iy) *= -1.0;  // flip one spin and accept new spin config\n\tMagneticMoment += 2.0*SpinMatrix(ix,iy);\n\tEnergy += (double) deltaE;\n      }\n    }\n    // update expectation values  for local node after a sweep through the lattice\n    ExpectationValues(0) += Energy;    ExpectationValues(1) += Energy*Energy;\n    ExpectationValues(2) += MagneticMoment;    \n    ExpectationValues(3) += MagneticMoment*MagneticMoment; \n    ExpectationValues(4) += fabs(MagneticMoment);\n  }\n} // end of Metropolis sampling over spins\n\n// function to initialise energy, spin matrix and magnetization\nvoid InitializeLattice(int NSpins, mat &SpinMatrix,  double& Energy, double& MagneticMoment)\n{\n  // setup spin matrix and initial magnetization using cold start, all spins pointing up or down\n  for(int x =0; x < NSpins; x++) {\n    for (int y= 0; y < NSpins; y++){\n      SpinMatrix(x,y) = 1.0; // spin orientation for the ground state\n      MagneticMoment +=  (double) SpinMatrix(x,y);\n    }\n  }\n  // setup initial energy\n  for(int x =0; x < NSpins; x++) {\n    for (int y= 0; y < NSpins; y++){\n      Energy -=  (double) SpinMatrix(x,y)*\n\t(SpinMatrix(PeriodicBoundary(x,NSpins,-1),y) +\n\t SpinMatrix(x,PeriodicBoundary(y,NSpins,-1)));\n    }\n  }\n}// end function initialize\n\n\n\nvoid WriteResultstoFile(int NSpins, int MonteCarloCycles, double temperature, vec ExpectationValues)\n{\n  double norm = 1.0/((double) (MonteCarloCycles));  // divided by  number of cycles \n  double E_ExpectationValues = ExpectationValues(0)*norm;\n  double E2_ExpectationValues = ExpectationValues(1)*norm;\n  double M_ExpectationValues = ExpectationValues(2)*norm;\n  double M2_ExpectationValues = ExpectationValues(3)*norm;\n  double Mabs_ExpectationValues = ExpectationValues(4)*norm;\n  // all expectation values are per spin, divide by 1/NSpins/NSpins\n  double AllSpins = 1.0/((double) NSpins*NSpins);\n  double HeatCapacity = (E2_ExpectationValues- E_ExpectationValues*E_ExpectationValues)*AllSpins/temperature/temperature;\n  double MagneticSusceptibility = (M2_ExpectationValues - M_ExpectationValues*M_ExpectationValues)*AllSpins/temperature;\n  ofile << setiosflags(ios::showpoint | ios::uppercase);\n  ofile << setw(15) << setprecision(8) << temperature;\n  ofile << setw(15) << setprecision(8) << E_ExpectationValues*AllSpins;\n  ofile << setw(15) << setprecision(8) << HeatCapacity;\n  ofile << setw(15) << setprecision(8) << M_ExpectationValues*AllSpins;\n  ofile << setw(15) << setprecision(8) << MagneticSusceptibility;\n  ofile << setw(15) << setprecision(8) << Mabs_ExpectationValues*AllSpins << endl;\n} // end output function\n\n\n\n    \n\n\n\n\n\n\n", "meta": {"hexsha": "29d12e0d9ae73075a55632a8fd1fde8cb5b0d33e", "size": 7287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Programs/ParallelizationOpenMP/OpenMPising.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/ParallelizationOpenMP/OpenMPising.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/ParallelizationOpenMP/OpenMPising.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": 40.4833333333, "max_line_length": 143, "alphanum_fraction": 0.7142857143, "num_tokens": 2005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6411986488784489}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <sstream>\n#include <vector>\n#include <assert.h>\n#include <cmath>\n#include \"multibody.h\"\n\n\n#define _USE_MATH_DEFINES\n \narma::mat bond(const int i, const int j, const int size){\n\tarma::mat adj = arma::zeros(size,size);\n\tadj(i,j) = 1.0;  adj(j,i) = 1.0;\n\treturn calcLaplacian(adj);\n}\n\n//Calculates the Laplacian from the Adjacency matrix\narma::mat calcLaplacian(const arma::mat &adj) {\n    return arma::diagmat(arma::sum(adj)) - adj;\n}\n \n//Calculates the radius of gyration matrix operator\narma::mat rg2mat(int N) {\n    arma::mat adj = arma::ones(N, N) - arma::eye(N, N);\n    return 1.0 / ((double)N*N)*calcLaplacian(adj);\n}\n \n//finds c^T lti c in 1D quickly\ndouble GaussSystem::omatfast(int i, int j, arma::mat &m) {\n    return m.at(i, i) + m.at(j, j) - 2.0*m.at(i, j);\n}\n\narma::mat readMatrix(std::string line, double *dim, double *eps, double *a) {\n        std::stringstream ss;\n        ss.str(line);\n        int width;\n        ss >> width; ss >> *dim; ss >> *eps >> *a;\n        arma::mat adjacency(width, width);\n        int i = 0;\n        while(1) {  //read in numbers\n            double elem;\n            ss >> elem;\n            if (ss) {\n                adjacency[i] = elem;\n                i++;\n            }\n            else {\n                break;\n            }\n        }\n        assert(i == width*width);\n        return adjacency;\n}\n\n/* \n\tCreate the adjacency matrix for a linear polymer\n*/\narma::mat linearAdjacencyMatrix(const int N) {\n\tarma::vec prototype = arma::zeros(N);\n\tprototype(1) = 1;\n\treturn arma::toeplitz(prototype);\n}\n \ndouble GaussSystem::triomatfast(const int i, const int j, const int u, const int v, arma::mat &m) {\n    //matrix assosciated with \\delta(r_i - r_j) \\delta(r_u - r_v)\n    //matrix is a reference to a pre-allocated matrix.  This function will be called a butt-ton of times\n    //so it should be fast if possible\n    mat2d(0, 0) = m(i, i) + m(j, j) - m(i, j) - m(j, i); mat2d(0, 1) = m(i, u) + m(j, v) - m(i, v) - m(j, u);\n    mat2d(1, 0) = m(u, i) + m(v, j) - m(v, i) - m(u, j); mat2d(1, 1) = m(u, u) + m(v, v) - m(u, v) - m(v, u);\n   \n    /*\n    manual verification\n    arma::mat cm = arma::zeros(10, 2);\n    cm(i, 0) = 1; cm(j, 0) = -1;\n    cm(u, 1) = 1; cm(v, 1) = -1;\n    std::cout << cm.t()*m*cm;\n    std::cout << mat2d << std::endl; */\n    return arma::det(mat2d);\n}\n\narma::mat GaussSystem::triomat(const int i, const int j, const int u, const int v, arma::mat &m) {\n    //matrix assosciated with \\delta(r_i - r_j) \\delta(r_u - r_v)\n    //matrix is a reference to a pre-allocated matrix.  This function will be called a butt-ton of times\n    //so it should be fast if possible\n    arma::mat rv(2,2);\n    rv(0, 0) = m(i, i) + m(j, j) - m(i, j) - m(j, i); rv(0, 1) = m(i, u) + m(j, v) - m(i, v) - m(j, u);\n    rv(1, 0) = m(u, i) + m(v, j) - m(v, i) - m(u, j); rv(1, 1) = m(u, u) + m(v, v) - m(u, v) - m(v, u);\n    return rv;\n}\n \ndouble GaussSystem::threeBondIrreducible(arma::mat &m) {\n\tarma::mat rv = arma::zeros(3,3);\n\tint size = m.n_cols;\t//size of matrix, it should be square\n\tarma::mat c = arma::zeros(size, 3); //c matrix for 3 delta functions\n\tarma::mat ct = arma::zeros(3, size); //c transpose\n\tdouble acc = 0; int dumb;\n\tfor(int i = 0; i < N-1; i++){\n\t\tfor(int j = i+1; j < N; j++) {\n\t\t\tfor(int k = 0; k < N; k++){ if(k != i && k != j) {\n\t\t\t\t// Stuff\n\t\t\t\tacc += std::pow(triomatfast(i,j,j,k, m), -D/2.0);\n\t\t\t}}\n\t\t}\n\t}\n\treturn acc;\n}\n \nGaussSystem::GaussSystem(arma::mat laplacian, double dimension, double seglen) {\n    N = laplacian.n_cols;   //Matrix size.  Assume it is square\n    D = dimension;\n    a = seglen;\n    lap = laplacian;   \n    lti = arma::inv(lap);\n    rg2 = rg2mat(N);\n    opm = lti*rg2*lti;\n    rg20 = arma::trace(lti*rg2);\n    mat2d = arma::zeros(2, 2);  //2x2 matrix for use in triomatfast\n}\n\ndouble GaussSystem::order1fractionalRg2O(const int i, const int j) {\n\tdouble o = omatfast(i, j, lti);\n\tdouble on = omatfast(i, j, opm);\n\treturn 1 - on/o/rg20;\n}\n\ndouble GaussSystem::order2fractionalRg2O(const int i, const int j, const int p, const int q) {\n\tarma::mat o = triomat(i, j, p, q, lti);\n\tarma::mat on = triomat(i, j, p, q, opm);\n\treturn 1 - arma::trace(arma::inv(o)*on)/rg20;\n}\n \ndouble GaussSystem::secondcorrection() {\n\tdouble acc = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = i+1; j < N; j++) {\n            acc += std::pow(omatfast(i, j, lti), -D/2.0);\n        }\n    }\n    return acc * std::pow(D/(2*M_PI*a*a), D/2.0);\n}\n\n/*\n Calculate third virial coefficient\n calculates pairs f_{i,j}f_{u,v} where i < j, v > j, u >= i\n a heavy goddamn calculation\n*/\ndouble GaussSystem::thirdcorrection() {\n    double sum = 0;\n    double factor = std::pow(D / (2*M_PI*a*a), D);\n    double det;\n    for (int i = 0; i < N - 1; i++) {\n        for (int j = i + 1; j < N; j++) {\n            for (int u = i; u < N - 1; u++) {\n                for (int v = u + 1; v < N; v++) {\n                    if (i < u || j < v) {\n                        det = triomatfast(i, j, u, v, lti);\n                        sum += std::pow(det, -D/2.0);\n                    }\n                }\n            }\n        }\n    }\n    return factor*sum;\n}\n\n//Calculates \\alpha - 1\ndouble GaussSystem::correction1() {\n    double acc = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = i+1; j < N; j++) {\n            acc += std::pow(omatfast(i, j, lti), -D/2.0);\n        }\n    }\n    return acc;\n}\n \n//Calculates \\alpha - 1\ndouble GaussSystem::term1() {\n    double acc = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = i+1; j < N; j++) {\n            acc += std::pow(omatfast(i, j, lti), -D/2.0)*(1 - order1fractionalRg2O(i,j));\n        }\n    }\n    return acc;\n}\n\ndouble GaussSystem::term2() {\n    double acc = 0;\n    for (int i = 0; i < N - 1; i++) {\n        for (int j = i + 1; j < N; j++) {\n            for (int u = i; u < N - 1; u++) {\n                for (int v = u + 1; v < N; v++) {\n                    if (i < u || j < v) {\n                        acc += std::pow(triomatfast(i, j, u, v, lti), -D/2.0)*(order2fractionalRg2O(i,j,u,v) - 1);\n                    }\n                }\n            }\n        }\n    }\n    return correction1()*term1() + acc;\n}\n\n//Calculates \\alpha - 1\ndouble GaussSystem::alpham1() {\n    double acc = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = i+1; j < N; j++) {\n            acc += omatfast(i, j, opm)*std::pow(omatfast(i, j, lti), -(1.0*D + 2.0) / 2.0) ;\n        }\n    }\n    return (2*std::pow(2.0*M_PI*a*a / D, -D / 2.0)/rg20)*acc;\n}\n\ndouble GaussSystem::isitz() {\n    double acc = 0;\n    for (int i = 0; i < N; i++) {\n        for (int j = i+1; j < N; j++) {\n            acc += std::pow(omatfast(i, j, lti), -1.0*D/2.0) ;\n        }\n    }\n    return (2*std::pow(2.0*M_PI*a*a / D, -D / 2.0))*acc;\n}\n\n//next order in \\alpha\n//requires previous order correction as parameter\ndouble GaussSystem::alpham2(double alpha1) {\n\tdouble term1 = 4*alpha1*secondcorrection();\n\tdouble term2 = 0;\n    arma::mat ok(2,2);\t//matrices needed for 3rd order calculation\n    arma::mat oki(2,2);\n    arma::mat okp(2,2);\n    //Horrid calculation\n    for (int i = 0; i < N - 1; i++) {\n        for (int j = i + 1; j < N; j++) {\n            for (int u = i; u < N - 1; u++) {\n                for (int v = u + 1; v < N; v++) {\n                    if (i < u || j < v) {\n                        ok = triomat(i, j, u, v, lti); //c^T L^{-1} c\n                        oki = arma::inv(ok);\t//invert it\n                        okp = triomat(i, j, u, v, opm); //c^T L^{-1} R_G^2 L^{-1}\n                        term2 += std::pow(arma::det(ok), -D/2.0)*arma::trace(oki*okp);\n                    }\n                }\n            }\n        }\n    }\n    return term1 - 4*term2/rg20*2.0*M_PI*a*a / D ; \n    \n}\n \n/*\nCalculate <R_G^2>_0\n*/\ndouble GaussSystem::z0R() {\n    if (_z0 < 0) {  //calculate z0 if have not done so already\n        _z0 = z0();\n    }\n    return _z0*rg20;\n}\n \n/*\nz0 returns the non-interacting partition function\n*/\ndouble GaussSystem::z0() {\n    double num = std::pow(2.0*M_PI*a*a / D, (double)N);\n    double den = arma::det(lap);\n    _z0 = std::pow(num / den, D / 2.0);\n    return _z0;\n}\n \n\n \n", "meta": {"hexsha": "26cfe6a030ba96e0bbf0fc0628b5656042f39ea2", "size": 8128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multibody.cpp", "max_stars_repo_name": "starside/multibody", "max_stars_repo_head_hexsha": "f0a60b740c13762ae94e307c20abcaa96dd9e6f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multibody.cpp", "max_issues_repo_name": "starside/multibody", "max_issues_repo_head_hexsha": "f0a60b740c13762ae94e307c20abcaa96dd9e6f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multibody.cpp", "max_forks_repo_name": "starside/multibody", "max_forks_repo_head_hexsha": "f0a60b740c13762ae94e307c20abcaa96dd9e6f9", "max_forks_repo_licenses": ["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.5563636364, "max_line_length": 114, "alphanum_fraction": 0.5045521654, "num_tokens": 2872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6411986430378481}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_ATAN2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATAN2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing atan2 capabilities\n\n    atan2 function.\n\n    @par Semantic:\n\n    For every parameters of floating type T:\n\n    @code\n    T r = atan2(y, x);\n    @endcode\n\n    is similar but not fully equivalent to:\n\n    @code\n    T r =  atan(y/x);;\n    @endcode\n\n    as it is quadrant aware.\n\n    @par Notes\n\n    - For any real arguments @c x and @c y not both equal to zero, <tt>atan2(y, xy)</tt>\n    is the angle in radians between the positive x-axis of a plane and the point\n    given by the coordinates  <tt>(y,x)</tt>.\n\n    - It is also the angle in \\f$[-\\pi,\\pi[\\f$ for which\n    \\f$x/\\sqrt{x^2+y^2}\\f$ and \\f$y/\\sqrt{x^2+y^2}\\f$\n    are respectively the sine and the cosine.\n\n    - Following IEEE norms\n     -  If y is \\f$\\pm0\\f$ and x is negative or -0,\\f$\\pm\\pi\\f$ is returned\n     -  If y is \\f$\\pm0\\f$ and x is positive or +0, \\f$\\pm0\\f$ is returned\n     -  If y is \\f$\\pm\\infty\\f$ and x is finite, \\f$\\pm\\pi/2\\f$ is returned\n     -  If y is \\f$\\pm\\infty\\f$ and x is \\f$-\\infty\\f$,\\f$\\pm3\\pi/4\\f$ is returned\n     -  If y is \\f$\\pm\\infty\\f$ and x is \\f$+\\infty\\f$, \\f$\\pm\\pi/4\\f$ is returned\n     -  If x is \\f$\\pm0\\f$ and y is negative, \\f$-\\pi/2\\f$ is returned\n     -  If x is \\f$\\pm0\\f$ and y is positive, \\f$+\\pi/2\\f$  is returned\n     -  If x is \\f$-\\infty\\f$ and y is finite and positive, \\f$+\\pi\\f$ is returned\n     -  If x is \\f$-\\infty\\f$ and y is finite and negative, \\f$-\\pi\\f$ is returned\n     -  If x is \\f$+\\infty\\f$ and y is finite and positive, +0 is returned\n     -  If x is \\f$+\\infty\\f$ and y is finite and negative, -0 is returned\n     -  If either x is Nan or y is Nan, Nan is returned\n\n    - If you want to gain some cycles a fast_ tag is provided. If you use it pairs (x, y)\n     where both are null or both are infinite will produce a Nan result which in fact\n     is not more absurd than the IEEE choices and will be conforming in all other cases.\n\n    @par Decorators\n\n    std_ for floating entries\n\n  @see atan, atand, atanpi\n\n  **/\n  const boost::dispatch::functor<tag::atan2_> atan2 = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/atan2.hpp>\n#include <boost/simd/function/simd/atan2.hpp>\n\n#endif\n", "meta": {"hexsha": "c13b465a0c04bd4c0d93e014d05f5629e117c6f1", "size": 2780, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/atan2.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/atan2.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/atan2.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7058823529, "max_line_length": 100, "alphanum_fraction": 0.5978417266, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.641123263728477}}
{"text": "/*\n* eigen3_impl.cpp\n*\n*  Created on: 18 oct. 2012\n*      Author: boubad\n*/\n/////////////////////////////////////////////////////////\n#if defined (__INTEL_COMPILER)\n#pragma warning (disable:2196)\n#endif\n/////////////////////////////\n#include <Eigen/Eigenvalues>\n///////////////////////////////////////////\n#include <cassert>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n//////////////////////////////////////////////\nnamespace info {\n\t//////////////////////////////////////////\n\tusing namespace Eigen;\n\t///////////////////////////////////////////////\n\tconst double EPSILON = 0.000001;\n\t////////////////////////////////////////////////\n\ttypedef std::pair<size_t, double> MyPair;\n\ttypedef Matrix<double, Dynamic, Dynamic> MyMatrix;\n\t//\n\tstruct MyComparePairDescFunc : public std::binary_function<MyPair, MyPair, bool> {\n\t\tbool operator()(const MyPair &v1, const MyPair &v2) const {\n\t\t\treturn (v1.second > v2.second);\n\t\t} // operator()\n\t};\n\t// MyComparePairFunc\n\t///////////////////////////////////////////////////\n\textern bool info_compute_eigen_impl(const int n, const double *pData,\n\t\tdouble *pVals, double *pVecs, int *pNbFacts /*= nullptr */) {\n\t\t//\n\t\tassert(n > 0);\n\t\tassert(pData != nullptr);\n\t\tassert(pVals != nullptr);\n\t\tassert(pVecs != nullptr);\n\t\t//\n\t\tMyMatrix m(n, n);\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfor (int j = 0; j <= i; ++j) {\n\t\t\t\tdouble v = pData[n * i + j];\n\t\t\t\tif (std::abs(v) < EPSILON) {\n\t\t\t\t\tv = 0;\n\t\t\t\t}\n\t\t\t\tm(i, j) = v;\n\t\t\t\tif (j != i) {\n\t\t\t\t\tm(j, i) = v;\n\t\t\t\t}\n\t\t\t}\t// j\n\t\t}\t// i\n\t\tEigenSolver<MyMatrix> solver(m);\n\t\ttypename EigenSolver<MyMatrix>::EigenvalueType val = solver.eigenvalues();\n\t\tint nx = (int)val.rows();\n\t\tint ny = (int)val.cols();\n\t\tMyMatrix rval(nx, ny);\n\t\tfor (int i = 0; i < nx; ++i) {\n\t\t\tfor (int j = 0; j < ny; ++j) {\n\t\t\t\trval(i, j) = val(i, j).real();\n\t\t\t}\t// j\n\t\t}\t// i\n\t\ttypename EigenSolver<MyMatrix>::EigenvectorsType vec =\n\t\t\tsolver.eigenvectors();\n\t\tnx = (int)vec.rows();\n\t\tny = (int)vec.cols();\n\t\tMyMatrix rvec(nx, ny);\n\t\tfor (int i = 0; i < nx; ++i) {\n\t\t\tfor (int j = 0; j < ny; ++j) {\n\t\t\t\trvec(i, j) = vec(i, j).real();\n\t\t\t}\t// j\n\t\t}\t// i\n\t\tstd::vector<MyPair> oPairs;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tdouble xx = rval(i, 0);\n\t\t\tif (xx > 0) {\n\t\t\t\tMyPair o((size_t)i, xx);\n\t\t\t\toPairs.push_back(o);\n\t\t\t}\n\t\t}\t\t\t\t// i\n\t\tint nFacts = (int)oPairs.size();\n\t\tbool bRet = (nFacts > 0);\n\t\tif (bRet) {\n\t\t\tstd::sort(oPairs.begin(), oPairs.end(), MyComparePairDescFunc());\n\t\t\tfor (int i = 0; i < nFacts; ++i) {\n\t\t\t\tconst MyPair &pp = oPairs[i];\n\t\t\t\tconst size_t ii = pp.first;\n\t\t\t\tdouble tt = pp.second;\n\t\t\t\tif (std::abs(tt) < EPSILON) {\n\t\t\t\t\ttt = 0;\n\t\t\t\t}\n\t\t\t\tpVals[i] = tt;\n\t\t\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t\t\tdouble xx = rvec(j, ii);\n\t\t\t\t\tif (std::abs(xx) < EPSILON) {\n\t\t\t\t\t\txx = 0;\n\t\t\t\t\t}\n\t\t\t\t\tpVecs[j * nFacts + i] = xx;\n\t\t\t\t}// j\n\t\t\t}\t\t\t\t// i\n\t\t}\t\t\t\t// bRet\n\t\tif (pNbFacts != nullptr) {\n\t\t\t*pNbFacts = nFacts;\n\t\t}\n\t\treturn (bRet);\n\t}// compute_eigen_impl\n\t //////////////////////////////////////////\n}\t// namespace info\n\t/////////////////////////////////////////////////\n", "meta": {"hexsha": "9ca8ab8e15da8dbb821bf0ccd3cc76f84ff1df33", "size": 3038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "infostat/src/eigen_impl.cpp", "max_stars_repo_name": "boubad/CygProjects", "max_stars_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "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": "infostat/src/eigen_impl.cpp", "max_issues_repo_name": "boubad/CygProjects", "max_issues_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "infostat/src/eigen_impl.cpp", "max_forks_repo_name": "boubad/CygProjects", "max_forks_repo_head_hexsha": "cdc0dc2cb6e34b94d1bafbf3fd216b32c320985d", "max_forks_repo_licenses": ["Apache-2.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.8849557522, "max_line_length": 83, "alphanum_fraction": 0.4726793943, "num_tokens": 971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6411232484174924}}
{"text": "#include \"bindings-math.h\"\n\n#include \"../luaapi/context.h\"\n#include \"../luaapi/types.h\"\n#include \"../luaapi/macros.h\"\n\n#include \"CVec.h\"\n#include \"util/angle.h\"\n#include \"util/math_func.h\"\n#include \"CodeAttributes.h\"\n\n#include <cmath>\n#include <cstdio>\n#include <string>\n#include <iostream>\n\nusing std::cerr;\nusing std::endl;\n#include <boost/lexical_cast.hpp>\n#include <boost/bind.hpp>\nusing boost::lexical_cast;\n\nnamespace LuaBindings\n{\n\nINLINE lua_Number luaL_checknumber(lua_State *L, int narg)\n{\n\tlua_Number d = lua_tonumber(L, narg);\n\t//if(d == 0 && !lua_isnumber(L, narg))\n\t//\t; // TODO: tag_error(L, narg, LUA_TNUMBER);\n\treturn d;\n}\n\n/*! sqrt(n)\n\n\tReturns the squareroot of n.\n*/\nint l_sqrt(lua_State* L)\n{\n\tlua_pushnumber(L, sqrt(luaL_checknumber(L, 1)));\n\treturn 1;\n}\n\n/*! abs(n)\n\n\tReturns the absolute value of n.\n*/\nint l_abs(lua_State* L)\n{\n\tlua_pushnumber(L, fabs(luaL_checknumber(L, 1)));\n\treturn 1;\n}\n\n/*! floor(n)\n\n\tReturns the number n rounded down towards infinity.\n*/\nint l_floor(lua_State* L)\n{\n\tlua_pushnumber(L, floor(luaL_checknumber(L, 1)));\n\treturn 1;\n}\n\nint l_round(lua_State* L)\n{\n\tint d = lua_tointeger(L, 2);\n\tchar buffer[256];\n\tsprintf(buffer, \"%.*f\", d, lua_tonumber(L, 1));\n\tlua_pushstring(L, buffer);\n\treturn 1;\n}\n\n/*! randomint(l, u)\n\n\tReturns a random integer in the interval [l, u].\n*/\nint l_randomint(lua_State* L)\n{\n\tint l = lua_tointeger(L, 1);\n\tint u = lua_tointeger(L, 2);\n\t\n\t//lua_pushnumber(L, l + (unsigned int)(rndgen()) % (u - l + 1));\n\tlua_pushinteger(L, l + rndInt(u - l + 1));\n\t\n\treturn 1;\n}\n\n/*! randomfloat(l, u)\n\n\tReturns a random floating point number in the interval [l, u].\n*/\nint l_randomfloat(lua_State* L)\n{\n\tlua_Number l = luaL_checknumber(L, 1);\n\tlua_Number u = luaL_checknumber(L, 2);\n\t\n\tlua_pushnumber(L, l + rnd() * (u - l));\n\t\n\treturn 1;\n}\n\n/*! to_time_string(v)\n\n\tConverts a frame count //v// to a string showing hours, minutes and seconds as HH:MM:SS.\n*/\nint l_toTimeString(lua_State* L)\n{\n\tlua_Integer v = lua_tointeger(L, 1);\n\t\n\tlua_Integer sec = v / 100;\n\t\n\tchar c[8];\n\tc[0] = ((sec / 36000) % 10) + '0';\n\tc[1] = ((sec / 3600) % 10) + '0';\n\tc[2] = ':';\n\tc[3] = ((sec / 600) % 6) + '0';\n\tc[4] = ((sec / 60) % 10) + '0';\n\tc[5] = ':';\n\tc[6] = ((sec / 10) % 6) + '0';\n\tc[7] = (sec % 10) + '0';\n\tlua_pushlstring(L, c, 8);\n\t\n\treturn 1;\n}\n\n/*! vector_diff(x1, y1, x2, y2)\n\n\tReturns a tuple equal to (x2 - x1, y2 - y1)\n*/\nint l_vector_diff(lua_State* L)\n{\n\tlua_pushnumber(L, lua_tonumber(L, 3) - lua_tonumber(L, 1));\n\tlua_pushnumber(L, lua_tonumber(L, 4) - lua_tonumber(L, 2));\n\t\n\treturn 2;\n}\n\n/*! vector_distance(x1, y1, x2, y2)\n\n\tReturns the distance from (x1, y1) to (x2, y2)\n*/\nint l_vector_distance(lua_State* L)\n{\n\tlua_Number vx = lua_tonumber(L, 3) - lua_tonumber(L, 1);\n\tlua_Number vy = lua_tonumber(L, 4) - lua_tonumber(L, 2);\n\tvx *= vx;\n\tvy *= vy;\n\tlua_pushnumber(L, sqrt(vx + vy));\n\t\n\treturn 1;\n}\n\n/*! vector_direction(x1, y1, x2, y2)\n\n\tReturns the angle between (x1, y1) and (x2, y2)\n\tin degrees.\n*/\nint l_vector_direction(lua_State* L)\n{\n\tlua_Number vx = lua_tonumber(L, 3) - lua_tonumber(L, 1);\n\tlua_Number vy = lua_tonumber(L, 4) - lua_tonumber(L, 2);\n\n\tlua_pushnumber(L, rad2deg((float)atan2(vx, -vy)) );\n\t\n\treturn 1;\n}\n\n/*! vector_add(x1, y1, x2, y2)\n\n\tReturns a tuple equal to (x1 + x2, y1 + y2)\n*/\nint l_vector_add(lua_State* L)\n{\n\tlua_pushnumber(L, lua_tonumber(L, 1) + lua_tonumber(L, 3));\n\tlua_pushnumber(L, lua_tonumber(L, 2) + lua_tonumber(L, 4));\n\t\n\treturn 2;\n}\n\n\n/*! angle_diff(a, b)\n\n\tReturns the relative angle in (-180, 180) between\n\tangle //a// and //b// such that (a + angle_diff(a, b)) = b (mod 360)\n*/\nint l_angle_diff(lua_State* L)\n{\n\tAngleDiff diff(AngleDiff(lua_tonumber(L, 1)).relative(AngleDiff(lua_tonumber(L, 2))));\n\t\n\tlua_pushnumber(L, diff.toDeg());\n\t\n\treturn 1;\n}\n\n/*! angle_clamp(angle)\n\n\tReturns //angle// normalized to [0, 360).\n*/\nint l_angle_clamp(lua_State* L)\n{\n\t//lua_Number ang = lua_tonumber(L, 1);\n\tAngle ang((double)lua_tonumber(L, 1));\n\t\n\tang.clamp();\n\t\n\tlua_pushnumber(L, ang.toDeg());\n\t\n\treturn 1;\n}\n\n/*! angle_vector(angle[, length = 1])\n\n\tReturns a tuple representing the angle\n\twith length //length//.\n*/\nint l_angle_vector(lua_State* L)\n{\n\tAngle ang((double)lua_tonumber(L, 1));\n\tlua_Number len = 1.0;\n\t\n\tif(lua_gettop(L) >= 2)\n\t\tlen = lua_tonumber(L, 2);\n\t\n\tVec vec(ang, len);\n\tlua_pushnumber(L, vec.x);\n\tlua_pushnumber(L, vec.y);\n\t\n\treturn 2;\n}\n\nvoid initMath(LuaContext& context)\n{\n\tcontext.functions()\n\t\t(\"sqrt\", l_sqrt)\n\t\t(\"abs\", l_abs)\n\t\t(\"floor\", l_floor)\n\t\t\n\t\t(\"round\", l_round)\n\t\n\t\t(\"randomint\", l_randomint)\n\t\t(\"randomfloat\", l_randomfloat)\n\t\t\n\t\t(\"to_time_string\", l_toTimeString)\n\t\n\t\t(\"vector_diff\", l_vector_diff)\n\t\t(\"vector_distance\", l_vector_distance)\n\t\t(\"vector_direction\", l_vector_direction)\n\t\t(\"vector_add\", l_vector_add)\n\t\n\t\t(\"angle_clamp\", l_angle_clamp)\n\t\t(\"angle_diff\", l_angle_diff)\n\t\t(\"angle_vector\", l_angle_vector)\n\t;\n}\n\n}\n", "meta": {"hexsha": "dfdbad5527867cf544cb77032b362c44fce66237", "size": 4873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gusanos/lua/bindings-math.cpp", "max_stars_repo_name": "JiPRA/openlierox", "max_stars_repo_head_hexsha": "1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 192.0, "max_stars_repo_stars_event_min_datetime": "2015-02-13T14:53:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:18:58.000Z", "max_issues_repo_path": "src/gusanos/lua/bindings-math.cpp", "max_issues_repo_name": "JiPRA/openlierox", "max_issues_repo_head_hexsha": "1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T22:00:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T18:22:46.000Z", "max_forks_repo_path": "src/gusanos/lua/bindings-math.cpp", "max_forks_repo_name": "JiPRA/openlierox", "max_forks_repo_head_hexsha": "1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2015-01-16T00:55:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T03:09:30.000Z", "avg_line_length": 18.9610894942, "max_line_length": 89, "alphanum_fraction": 0.6482659553, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.641107149808453}}
{"text": "//------------------------------------------------------------------------------\n/// \\file LeetCode_tests.cpp\n/// \\date 20201025 12:51\n//------------------------------------------------------------------------------\n#include \"QuestionsDEntrevue/LeetCode/LeetCodeQuestions.h\"\n\n#include <boost/test/unit_test.hpp>\n#include <optional>\n#include <string>\n#include <vector>\n\nusing QuestionsDEntrevue::LeetCode::check_palindrome;\nusing QuestionsDEntrevue::LeetCode::climb_stairs_iterative;\nusing QuestionsDEntrevue::LeetCode::coin_change_recursive;\nusing QuestionsDEntrevue::LeetCode::coin_change_top_down;\nusing QuestionsDEntrevue::LeetCode::coin_change_top_down_step;\nusing QuestionsDEntrevue::LeetCode::count_palindromic_substrings;\nusing QuestionsDEntrevue::LeetCode::count_palindromic_substrings_simple;\nusing QuestionsDEntrevue::LeetCode::find_even_size_palindromes;\nusing QuestionsDEntrevue::LeetCode::find_odd_size_palindromes;\nusing QuestionsDEntrevue::LeetCode::find_subrow_max;\nusing QuestionsDEntrevue::LeetCode::is_valid_parentheses;\nusing QuestionsDEntrevue::LeetCode::longest_valid_parentheses;\nusing QuestionsDEntrevue::LeetCode::max_profit;\nusing QuestionsDEntrevue::LeetCode::max_subarray;\nusing QuestionsDEntrevue::LeetCode::max_sum_submatrix;\nusing QuestionsDEntrevue::LeetCode::min_coin_change_recursive_step;\nusing std::make_optional;\nusing std::nullopt;\nusing std::optional;\nusing std::string;\nusing std::vector;\n\nBOOST_AUTO_TEST_SUITE(Entrevue)\nBOOST_AUTO_TEST_SUITE(LeetCode)\n\n//------------------------------------------------------------------------------\n/// \\url https://leetcode.com/problems/valid-parentheses/\n/// \\name 20. Valid Parentheses. Easy.\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(IsValidParentheseReturnsTrueForValidParentheses)\n{\n  {\n    string example {\"()\"};\n\n    BOOST_TEST(is_valid_parentheses(example));\n  }\n  {\n    string example {\"()[]{}\"};\n\n    BOOST_TEST(is_valid_parentheses(example));\n  }\n  {\n    string example {\"([)]\"};\n\n    BOOST_TEST(!is_valid_parentheses(example));\n  }\n  {\n    string example {\"{[]}\"};\n\n    BOOST_TEST(is_valid_parentheses(example));\n  }\n\n}\n\n//------------------------------------------------------------------------------\n/// \\url https://leetcode.com/problems/longest-valid-parentheses/\n/// \\name 32. Longest Valid Parentheses. Hard.\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(LongestValidParentheseReturnsCorrentValuesForBaseCases)\n{\n  {\n    string example {\"(()\"};\n\n    BOOST_TEST(longest_valid_parentheses(example) == 2);\n  }\n  {\n    string example {\"(())\"};\n\n    BOOST_TEST(longest_valid_parentheses(example) == 4);\n  }\n  {\n    string example {\")(\"};\n    BOOST_TEST(longest_valid_parentheses(example) == 0);\n  }\n  {\n    string example {\")((\"};\n    BOOST_TEST(longest_valid_parentheses(example) == 0);\n  }\n  {\n    string example {\")()())\"};\n\n    BOOST_TEST(longest_valid_parentheses(example) == 4);\n  }\n  {\n    string example {\"\"};\n\n    BOOST_TEST(longest_valid_parentheses(example) == 0);\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(\n  LongestValidParentheseReturnsLongestLengthOfValidParentheses)\n{\n  {\n    string example {\"()()()\"};\n\n    BOOST_TEST(longest_valid_parentheses(example) == 6);\n  }\n  {\n    string example {\"()(()\"};\n    BOOST_TEST(longest_valid_parentheses(example) == 2);\n  }\n}\n\n//------------------------------------------------------------------------------\n/// \\url https://leetcode.com/problems/maximum-subarray/\n/// \\name 53. Maximum Subarray.\n/// \\brief Given an integer array nums, find the contiguous subarray (containing\n/// at least one number) which has the largest sum and return its sum.\n///\n/// \\url https://youtu.be/2MmGzdiKR9Y\n///\n/// \\details Easy.\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(MaxSubArrayReturnsLargestSum)\n{\n  {\n    vector<int> example_1 {-2, 1, -3, 4, -1, 2, 1, -5, 4};\n\n    BOOST_TEST(max_subarray(example_1) == 6);\n  }\n  {\n    vector<int> example_2 {1};\n    BOOST_TEST(max_subarray(example_2) == 1);\n  }\n  {\n    vector<int> example_3 {0};\n    BOOST_TEST(max_subarray(example_3) == 0);\n  }\n  {\n    vector<int> example_4 {-1};\n    BOOST_TEST(max_subarray(example_4) == -1);\n\n  }\n  {\n    vector<int> example_5 {-2147483647};\n    BOOST_TEST(max_subarray(example_5) == -2147483647);\n  }\n}\n\n\n//------------------------------------------------------------------------------\n/// \\brief 70. Climbing Stairs.\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ClimbStairsIterativeFindsNumberOfDistinctWaysForBaseCases)\n{\n  BOOST_TEST(climb_stairs_iterative(1) == 1);\n  BOOST_TEST(climb_stairs_iterative(2) == 2);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ClimbStairsIterativeWorksForGreaterThan2)\n{\n  BOOST_TEST(climb_stairs_iterative(3) == 3);\n  BOOST_TEST(climb_stairs_iterative(4) == 5);\n\n  BOOST_TEST(climb_stairs_iterative(42) == 433494437);\n}\n\n//------------------------------------------------------------------------------\n/// \\brief 121. Best Time to Buy and Sell Stock\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(MaxProfitsCalculatesMaximumProfit)\n{\n  {\n    vector<int> input {7, 1, 5, 3, 6, 4};\n\n    BOOST_TEST(max_profit(input) == 5);\n  }\n  {\n    vector<int> input {7, 6, 4, 3, 1};\n\n    BOOST_TEST(max_profit(input) == 0);\n  }\n}\n\n//------------------------------------------------------------------------------\n/// \\url https://leetcode.com/problems/coin-change/\n/// \\name 322. Coin Change\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(StdOptionalUsageExample)\n{\n  {\n    const int amount {11};\n    vector<optional<int>> min_coins_for_amount (amount + 1, nullopt);\n    BOOST_TEST(min_coins_for_amount.size() == amount + 1);\n\n    BOOST_TEST(!min_coins_for_amount.at(0).has_value());\n    BOOST_TEST(!min_coins_for_amount.at(1).has_value());\n\n    min_coins_for_amount.at(0) = 42;\n    min_coins_for_amount.at(1) = 69;\n\n    BOOST_TEST(min_coins_for_amount.at(0).has_value());\n    BOOST_TEST(min_coins_for_amount.at(1).has_value());\n    BOOST_TEST(*min_coins_for_amount.at(0) == 42);\n    BOOST_TEST(*min_coins_for_amount.at(1) == 69);\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(CoinChangeTopDownReturnsCorrectValueForBaseCases)\n{\n  {\n    vector<int> example_1_coins {1, 2, 5};\n    const int amount {11};\n\n    BOOST_TEST(coin_change_top_down(example_1_coins, amount) == 3);\n  }\n  {\n    vector<int> example_2_coins {2};\n    const int amount {3};\n\n    BOOST_TEST(coin_change_top_down(example_2_coins, amount) == -1);\n  }\n  {\n    vector<int> example_3_coins {1};\n    const int amount {0};\n    BOOST_TEST(coin_change_top_down(example_3_coins, amount) == 0);\n  }\n  {\n    vector<int> example_4_coins {1};\n    const int amount {1};\n    BOOST_TEST(coin_change_top_down(example_4_coins, amount) == 1);\n  }\n  {\n    vector<int> example_5_coins {1};\n    const int amount {2};\n    BOOST_TEST(coin_change_top_down(example_5_coins, amount) == 2);\n  }\n  {\n    vector<int> example_6_coins {186, 419, 83, 408};\n    const int amount {6249};\n    BOOST_TEST(coin_change_top_down(example_6_coins, amount) == 20);\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(MinCoinChangeRecursiveStepReturnsCorrectValueForBaseCases)\n{\n  {\n    vector<int> example_1_coins {1, 2, 5};\n    const int amount {11};\n    vector<optional<int>> min_coins_for_amount (amount + 1, nullopt);\n\n    BOOST_TEST(\n      min_coin_change_recursive_step(\n        example_1_coins,\n        1,\n        min_coins_for_amount,\n        amount) == 3);\n  }\n  {\n    vector<int> example_2_coins {2};\n    const int amount {3};\n    vector<optional<int>> min_coins_for_amount (amount + 1, nullopt);\n\n    BOOST_TEST(\n      min_coin_change_recursive_step(\n        example_2_coins,\n        2,\n        min_coins_for_amount,\n        amount) == -1);\n  }\n  {\n    vector<int> example_3_coins {1};\n    const int amount {0};\n    vector<optional<int>> min_coins_for_amount (amount + 1, nullopt);\n    min_coins_for_amount.at(0) = 0;\n\n    BOOST_TEST(\n      min_coin_change_recursive_step(\n        example_3_coins,\n        1,\n        min_coins_for_amount,\n        amount) == 0);\n  }\n  {\n    vector<int> example_4_coins {1};\n    const int amount {1};\n    vector<optional<int>> min_coins_for_amount (amount + 1, nullopt);\n    min_coins_for_amount.at(0) = 0;\n\n    BOOST_TEST(\n      min_coin_change_recursive_step(\n        example_4_coins,\n        1,\n        min_coins_for_amount,\n        amount) == 1);\n  }\n  {\n    vector<int> example_5_coins {1};\n    const int amount {2};\n    vector<optional<int>> min_coins_for_amount (amount + 1, nullopt);\n    min_coins_for_amount.at(0) = 0;\n\n    BOOST_TEST(\n      min_coin_change_recursive_step(\n        example_5_coins,\n        1,\n        min_coins_for_amount,\n        amount) == 2);\n  }\n}\n\n//------------------------------------------------------------------------------\n/// \\url https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/\n/// \\name 363. Max Sum of Rectangle No Larger Than K.\n/// \\ref https://www.youtube.com/watch?v=-FgseNO-6Gk\n/// Back To Back SWE, Maximum Sum Rectangle In A 2D Matrix - Kadane's Algorithm\n///\n/// Time complexity:\n/// Brute force O(row^2 * cols^2) because for each  choice of top left corner of\n/// a subrectangle (row * col), choose bottom right corner (row * col choices).\n//------------------------------------------------------------------------------\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(FindSubrowMaxProcessesSingleRow)\n{\n  vector<vector<int>> b2b_example {\n    {6, -5, -7, 4, -4},\n    {-9, 3, -6, 5, 2},\n    {-10, 4, 7, -6, 3},\n    {-8, 9, -3, 3, -7}};\n\n  BOOST_TEST(b2b_example.at(0).at(1) = -5);\n  BOOST_TEST(b2b_example.at(0).at(2) = -7);\n  BOOST_TEST(b2b_example.at(1).at(3) = 5);\n\n  {\n    const auto result = find_subrow_max(b2b_example.at(0));\n    BOOST_TEST(result.first == 6);\n    BOOST_TEST(result.second.first == 0);\n    BOOST_TEST(result.second.second == 0);\n  }\n  {\n    const auto result = find_subrow_max(b2b_example.at(1));\n    BOOST_TEST(result.first == 7);\n    BOOST_TEST(result.second.first == 3);\n    BOOST_TEST(result.second.second == 4);\n  }\n  {\n    const auto result = find_subrow_max(b2b_example.at(2));\n    BOOST_TEST(result.first == 11);\n    BOOST_TEST(result.second.first == 1);\n    BOOST_TEST(result.second.second == 2);\n  }\n  {\n    const auto result = find_subrow_max(b2b_example.at(3));\n    BOOST_TEST(result.first == 9);\n    BOOST_TEST(result.second.first == 1);\n    BOOST_TEST(result.second.second == 1);\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(MaxSumSubmatrixGetsMaxSum)\n{\n  {\n    vector<vector<int>> b2b_example {\n      {6, -5, -7, 4, -4},\n      {-9, 3, -6, 5, 2},\n      {-10, 4, 7, -6, 3},\n      {-8, 9, -3, 3, -7}};\n\n    BOOST_TEST(b2b_example.at(0).at(1) = -5);\n    BOOST_TEST(b2b_example.at(0).at(2) = -7);\n    BOOST_TEST(b2b_example.at(1).at(3) = 5);\n\n    const size_t M {b2b_example.size()};\n    BOOST_TEST(M == 4);\n\n    BOOST_TEST(max_sum_submatrix(b2b_example) == 17);\n  }\n\n}\n\n\n//------------------------------------------------------------------------------\n/// \\brief 647. Palindromic Substrings.\n//------------------------------------------------------------------------------\n\nstring example_1 {\"abc\"};\nstring example_2 {\"aaa\"};\n\nconst string example_str_a {\"madam\"};\nconst string example_str_b {\"tenet\"};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(StringManipulationWithIteratorsWorks)\n{\n  // Use this playground if necessary.\n\n  auto start_iter = example_1.begin();\n\n  --start_iter;\n  BOOST_TEST(distance(example_1.begin(), example_1.begin()) == 0);\n  BOOST_TEST(distance(example_1.begin(), start_iter) == -1);\n\n  // Distance between beginning and end of a string returns size of a string.\n  BOOST_TEST(example_str_a.size() ==\n    distance(example_str_a.begin(), example_str_a.end()));\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(CheckPalindromeWorksOnBaseCases)\n{\n  {\n    string example {\"a\"};\n\n    auto tail_iter = example.end();\n    --tail_iter;\n    BOOST_TEST(check_palindrome(example.begin(), tail_iter));\n  }\n  {\n    string example {\"ab\"};\n\n    auto tail_iter = example.end();\n    --tail_iter;\n    BOOST_TEST(!check_palindrome(example.begin(), tail_iter));\n\n    tail_iter = example.end();\n    tail_iter = tail_iter - 2;\n    BOOST_TEST(check_palindrome(example.begin(), tail_iter));\n\n    tail_iter = example.end();\n    --tail_iter;\n    BOOST_TEST(check_palindrome(example.begin() + 1, tail_iter));\n  }\n  {\n    string example {\"aa\"};\n    auto tail_iter = example.end();\n    --tail_iter;\n    BOOST_TEST(check_palindrome(example.begin(), tail_iter));\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(FindEvenSizePalindromesWorksOnBaseCases)\n{\n  {\n    string example {\"a\"};\n\n    BOOST_TEST(\n      find_even_size_palindromes(\n        example.begin(),\n        example.end(),\n        example.begin()) == 0);\n  }\n  {\n    string example {\"ab\"};\n\n    auto head_iter = example.begin();\n    BOOST_TEST(\n      find_even_size_palindromes(\n        example.begin(),\n        example.end(),\n        example.begin()) == 0);\n  }\n  {\n    string example {\"aa\"};\n    auto head_iter = example.begin();\n    BOOST_TEST(\n      find_even_size_palindromes(\n        example.begin(),\n        example.end(),\n        example.begin()) == 1);\n\n    ++head_iter;\n    BOOST_TEST(\n      find_even_size_palindromes(\n        example.begin(),\n        example.end(),\n        head_iter) == 0);\n  }\n  {\n    auto head_iter = example_2.begin();\n    BOOST_TEST(\n      find_even_size_palindromes(\n        example_2.begin(),\n        example_2.end(),\n        head_iter) == 1);\n    ++head_iter;\n    BOOST_TEST(\n      find_even_size_palindromes(\n        example_2.begin(),\n        example_2.end(),\n        head_iter) == 1);\n    ++head_iter;\n    \n    BOOST_TEST((head_iter != example_2.end()));\n    BOOST_TEST(\n      find_even_size_palindromes(\n        example_2.begin(),\n        example_2.end(),\n        head_iter) == 0);  \n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(FindOddSizePalindromesWorksOnBaseCases)\n{\n  {\n    string example {\"a\"};\n\n    BOOST_TEST(\n      find_odd_size_palindromes(\n        example.begin(),\n        example.end(),\n        example.begin()) == 1);\n  }\n  {\n    string example {\"ab\"};\n\n    auto head_iter = example.begin();\n    BOOST_TEST(\n      find_odd_size_palindromes(\n        example.begin(),\n        example.end(),\n        head_iter) == 1);\n    ++head_iter;\n    BOOST_TEST(\n      find_odd_size_palindromes(\n        example.begin(),\n        example.end(),\n        head_iter) == 1);\n  }\n  {\n    string example {\"aa\"};\n    auto head_iter = example.begin();\n    BOOST_TEST(\n      find_odd_size_palindromes(\n        example.begin(),\n        example.end(),\n        example.begin()) == 1);\n\n    ++head_iter;\n    BOOST_TEST(\n      find_odd_size_palindromes(\n        example.begin(),\n        example.end(),\n        head_iter) == 1);\n  }\n  {\n    auto head_iter = example_2.begin();\n    BOOST_TEST(\n      find_odd_size_palindromes(\n        example_2.begin(),\n        example_2.end(),\n        head_iter) == 1);\n    ++head_iter;\n    BOOST_TEST(\n      find_odd_size_palindromes(\n        example_2.begin(),\n        example_2.end(),\n        head_iter) == 2);\n    ++head_iter;\n    \n    BOOST_TEST((head_iter != example_2.end()));\n    BOOST_TEST(\n      find_odd_size_palindromes(\n        example_2.begin(),\n        example_2.end(),\n        head_iter) == 1);  \n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(CheckPalindromeWorksOnStrings)\n{\n  {\n    auto tail_iter = example_1.end();\n    --tail_iter;\n    BOOST_TEST(!check_palindrome(example_1.begin(), tail_iter));\n  }\n  {\n    auto tail_iter = example_2.end();\n    --tail_iter;\n    BOOST_TEST(check_palindrome(example_2.begin(), tail_iter));\n  }\n  {\n    auto tail_iter = example_str_a.end();\n    --tail_iter;\n    BOOST_TEST(check_palindrome(example_str_a.begin(), tail_iter));\n  }\n  {\n    auto tail_iter = example_str_b.end();\n    --tail_iter;\n    BOOST_TEST(check_palindrome(example_str_b.begin(), tail_iter));\n  }\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(CheckPalindromeWorksOnSubStrings)\n{\n  string example_1 {\"polymorphismreferstofunctioncalldependencyontype\"};\n  auto tail_iter = example_1.end();\n  --tail_iter;\n  BOOST_TEST(!check_palindrome(example_1.begin(), tail_iter));\n\n  auto head_iter = example_1.begin();\n  head_iter = head_iter + string{\"polymorphism\"}.size();\n  BOOST_TEST(check_palindrome(head_iter, head_iter + 4));\n  BOOST_TEST(check_palindrome(head_iter + 1, head_iter + 3));\n  BOOST_TEST(check_palindrome(head_iter + 2, head_iter + 2));\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(CountPalindromicSubstringsCountsCorrectly)\n{\n  BOOST_TEST(count_palindromic_substrings(example_1) == 3);\n  BOOST_TEST(count_palindromic_substrings(example_2) == 6);\n  BOOST_TEST(count_palindromic_substrings(example_str_a) == 7);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(CountPalindromicSubstringsSimpleCountsCorrectly)\n{\n  BOOST_TEST(count_palindromic_substrings_simple(example_1) == 3);\n  BOOST_TEST(count_palindromic_substrings_simple(example_2) == 6);\n  BOOST_TEST(count_palindromic_substrings_simple(example_str_a) == 7);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // LeetCode\nBOOST_AUTO_TEST_SUITE_END() // Entrevue", "meta": {"hexsha": "18abcef4511d24624ddfc7daed9a27f7fc7b6dbf", "size": 20236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Voltron/Source/UnitTests/Entrevue/LeetCode/LeetCode_tests.cpp", "max_stars_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_stars_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-02-09T19:44:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-09T19:44:51.000Z", "max_issues_repo_path": "Voltron/Source/UnitTests/Entrevue/LeetCode/LeetCode_tests.cpp", "max_issues_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_issues_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Voltron/Source/UnitTests/Entrevue/LeetCode/LeetCode_tests.cpp", "max_forks_repo_name": "ernestyalumni/HrdwCCppCUDA", "max_forks_repo_head_hexsha": "17ed937dea06431a4d5ca103f993ea69a6918734", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2481315396, "max_line_length": 80, "alphanum_fraction": 0.5146768136, "num_tokens": 4407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.8558511451289038, "lm_q1q2_score": 0.6411071491456587}}
{"text": "// This file is part of SWGANH which is released under the MIT license.\n// See file LICENSE or go to http://swganh.com/LICENSE\n\n#include <swganh/scripting/utility_python.h>\n#include <glm/glm.hpp>\n#include <glm/gtx/quaternion.hpp>\n\n#include <boost/python.hpp>\nusing namespace boost::python;\nnamespace swganh\n{\nnamespace utilities\n{\nstd::string pretty_print_vec3(glm::vec3 vector)\n{\n\tstd::stringstream ss;\n\tss << \"(x=\" << vector.x << \",y=\" << vector.y << \",z=\" << vector.z << \")\";\n\treturn ss.str();\n}\n\nstd::string pretty_print_quat(glm::quat quaternion)\n{\n\tstd::stringstream ss;\n\tss << \"(x=\" << quaternion.x << \",y=\" << quaternion.y << \",z=\" << quaternion.z << \",w=\" << quaternion.w << \")\";\n\treturn ss.str();\n}\n\nvoid define_class_glm_vec3()\n{\n\tclass_<glm::vec3>(\"vector3\",\n\t\t\"Stores a direction vector in three-dimensional space\")\n\t\t.def(init<glm::float_t, glm::float_t, glm::float_t>())\n\t\t.def(init<const glm::vec3&>())\n        .def_readwrite(\"x\", &glm::vec3::x)\n        .def_readwrite(\"y\", &glm::vec3::y)\n        .def_readwrite(\"z\", &glm::vec3::z)\n\t\t.def(\"__len__\", &utility::constant_len_len<glm::vec3, 3>)\n\t\t.def(\"__getitem__\", &utility::constant_len_get_item<glm::vec3, 3, glm::float_t>)\n\t\t.def(\"__setitem__\", &utility::constant_len_set_item<glm::vec3, 3, glm::float_t>)\n\t\t.def(\"__str__\", &pretty_print_vec3)\n\t\t.def(self == self)\n\t\t.def(self != self)\n\t\t.def(self + self)\n\t\t.def(self - self)\n\t\t.def(self * glm::float_t())\n\t\t.def(glm::float_t() * self)\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\t.def(self *= glm::float_t())\n\t\t.def(self /= glm::float_t());\n\t\t//.def(self_ns::str(self));\n}\nvoid define_class_glm_quat() \n{\n    class_<glm::quat>(\"quat\",\n\t\t\"Stores a quaternion\")\n\t\t.def(init<glm::float_t, glm::float_t, glm::float_t, glm::float_t>())\n\t\t.def(init<const glm::quat&>())\n        .def_readwrite(\"x\", &glm::quat::x)\n        .def_readwrite(\"y\", &glm::quat::y)\n        .def_readwrite(\"z\", &glm::quat::z)\n        .def_readwrite(\"w\", &glm::quat::w)\n\t\t.def(\"__len__\", &utility::constant_len_len<glm::quat, 4>)\n\t\t.def(\"__getitem__\", &utility::constant_len_get_item<glm::quat, 4, glm::float_t>)\n\t\t.def(\"__setitem__\", &utility::constant_len_set_item<glm::quat, 4, glm::float_t>)\n\t\t.def(\"__str__\", &pretty_print_quat)\n\t\t.def(self == self)\n\t\t.def(self != self)\n\t\t/*.def(self + self)\n\t\t.def(self - self)*/\n\t\t.def(self * glm::float_t())\n\t\t.def(glm::float_t() * self)\n\t\t/*.def(self += self)\n\t\t.def(self -= self)*/\n\t\t.def(self *= glm::float_t())\n\t\t.def(self /= glm::float_t());\n\t\t//.def(self_ns::str(self));\n}\n}} // namespace swganh::utilities", "meta": {"hexsha": "97b7f1acbd43bcd854e3a879a9cc438319103190", "size": 2538, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/swganh/utilities/glm_binding.cc", "max_stars_repo_name": "apathyboy/swganh", "max_stars_repo_head_hexsha": "665128efe9154611dec4cb5efc61d246dd095984", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-25T16:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-25T16:00:46.000Z", "max_issues_repo_path": "src/swganh/utilities/glm_binding.cc", "max_issues_repo_name": "apathyboy/swganh", "max_issues_repo_head_hexsha": "665128efe9154611dec4cb5efc61d246dd095984", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/swganh/utilities/glm_binding.cc", "max_forks_repo_name": "apathyboy/swganh", "max_forks_repo_head_hexsha": "665128efe9154611dec4cb5efc61d246dd095984", "max_forks_repo_licenses": ["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.1265822785, "max_line_length": 111, "alphanum_fraction": 0.6280535855, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6411071464429807}}
{"text": "#include <dlib/matrix.h>\n#include <dlib/svm.h>\n\n#include <iostream>\n#include <random>\n\nfloat func(float x) {\n  return 4.f + 0.3f * x;  // line coeficients\n}\n\nusing SampleType = dlib::matrix<double, 1, 1>;\nusing KernelType = dlib::linear_kernel<SampleType>;\n\nint main() {\n  using namespace dlib;\n  size_t n = 1000;\n  std::vector<matrix<double>> x(n);\n  std::vector<float> y(n);\n\n  std::random_device rd;\n  std::mt19937 re(rd());\n  std::uniform_real_distribution<float> dist(-1.5, 1.5);\n\n  // generate data\n  for (size_t i = 0; i < n; ++i) {\n    x[i].set_size(1, 1);\n    x[i](0, 0) = i;\n\n    y[i] = func(i) + dist(re);\n  }\n\n  //  // normalize data\n  vector_normalizer<matrix<double>> normalizer_x;\n  // let the normalizer learn the mean and standard deviation of the samples\n  normalizer_x.train(x);\n  // now normalize each sample\n  for (size_t i = 0; i < x.size(); ++i) {\n    x[i] = normalizer_x(x[i]);\n  }\n\n  krr_trainer<KernelType> trainer;\n  trainer.set_kernel(KernelType());\n  decision_function<KernelType> df = trainer.train(x, y);\n\n  // Generate new data\n  std::cout << \"Original data \\n\";\n  std::vector<matrix<double>> new_x(5);\n  for (size_t i = 0; i < 5; ++i) {\n    new_x[i].set_size(1, 1);\n    new_x[i](0, 0) = i;\n    new_x[i] = normalizer_x(new_x[i]);\n    std::cout << func(i) << std::endl;\n  }\n\n  std::cout << \"Predictions \\n\";\n  for (auto& v : new_x) {\n    auto prediction = df(v);\n    std::cout << prediction << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "ac770afbb947becd151e5df274a12c2c28ea083d", "size": 1455, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter01/dlib_samples/linreg_dlib.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter01/dlib_samples/linreg_dlib.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter01/dlib_samples/linreg_dlib.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 23.0952380952, "max_line_length": 76, "alphanum_fraction": 0.6130584192, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6411071457286867}}
{"text": "/*! \\file\n  \\brief Class for comparing floating point values to see if nearly equal.\n\n  \\details\n    Two types of comparison are provided:\n    FPC_STRONG, \"Very close\"   - Knuth equation 1', the default.\n    FPC_WEAK   \"Close enough\" - equation 2'.\n    equations in Dougles E. Knuth, Seminumerical algorithms (3rd Ed) section 4.2.4, Vol II,\n    pp 213-225, Addison-Wesley, 1997, ISBN: 0201896842.\n\n    Strong requires closeness relative to BOTH values being compared,\n    Weak only requires only closeness to EITHER ONE value.\n\n    This permits one to avoid some of the problems that can arise from comparing floating-point values\n    by circumnavigating the assumption that floating point operations always give exactly the same result.\n\n    See http://hal.archives-ouvertes.fr/docs/00/28/14/29/PDF/floating-point-article.pdf\n    for more about the pitfalls.\n\n\n  \\author Paul A. Bristow\n  \\date Aug 2009\n*/\n//  fp_compare.hpp\n//  Copyright Paul A. Bristow 2008\n//  derived from Copyright Gennadiy Rozental 2001-2007.\n\n//  Distributed under the Boost Software License, Version 1.0.\n//  (See accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n\n//  See http://www.boost.org/libs/test for the Boost.Test library home page.\n//  Deliberately removed any treatment of percent!\n\n#ifndef BOOST_TEST_FLOATING_POINT_COMPARISON_HPP\n#define BOOST_TEST_FLOATING_POINT_COMPARISON_HPP\n\n#include <boost/limits.hpp>  // for std::numeric_limits\n#include <boost/math/tools/precision.hpp> // for max_value, min_value & epsilon for floating_point type;\n\n// Check if two floating-point values are close within a chosen tolerance.\n//template<typename FPT> class close_to;\n\n// Check if floating-point value is smaller than a chosen small value.\n//template<typename FPT> class smallest;\n\n//! \\enum floating_point_comparison_type Two types of comparison of two floating point values.\nenum floating_point_comparison_type\n{ //!< Two types of comparison of two floating point values.\n  FPC_STRONG, //!< \"Very close\"   - Knuth equation 1',  the default.\n              //!< Strong requires closeness relative to BOTH values being compared,\n\n  FPC_WEAK    //!< \"Close enough\" - equation 2'.\n              //!< Weak only requires only closeness to EITHER ONE value.\n  // equations in Dougles E. Knuth, Seminumerical algorithms (3rd Ed) section 4.2.4, Vol II,\n  // pp 213-225, Addison-Wesley, 1997, ISBN: 0201896842.\n};\n\n// GNU int gsl_fcmp (double x, double y, double epsilon) provides similar function.\n// fcmp also provides a C implementation at https://sourceforge.net/projects/fcmp/\n// For IEEE floating-point types, some speedups are possible, for example see:\n// Taming the Floating-point Beast, Chris Lomont\n// www.lomont.org/Math/Papers/2005/CompareFloat.pdf\n// Alberto Squassabia, Comparing Floats:\n// How to determine if Floating-point quantities are close enough\n// once a tolerance has been reached:  C++ report March 2000.\n// Gennadiy Rozental, Floating_point comparison algorithms,\n// www.boost.org/libs/test/doc/components/test_tools/floating_point_comparison.html\n// Comparison of Floating Point Numbers, Matthias Ruppwww.mrupp.info/Data/2007floatingcomp.pdf, July 2007.\n// The pitfalls of verifying floating-point computations, David Monniaux\n// CNRS Ecole normale superieure, 1 Feb 2008, http://arxiv.org/abs/cs/0701192v4\n// submitted to ACM TOPLAS.\n\n// \\tparam FPT Floating-Point Type: float, double, long double, or User-Defined like NTL quad_float or RR.\n// from boost/math/tools/precision.hpp\ntemplate <class T> T max_value(T); //!< std::numeric_limits<>::max() or similar.\ntemplate <class T> T min_value(T); //!< std::numeric_limits<>::min() or similar.\ntemplate <class T> T epsilon(T); //!< std::numeric_limits<>::epsilon() or similar.\n\ntemplate<typename FPT> FPT\nfpt_abs(FPT arg)\n{ //! abs function (just in case abs is not defined for FPT).\n  return arg <static_cast<FPT>(0) ? -arg : arg;\n}\n\ntemplate<typename FPT> FPT\nsafe_fpt_division(FPT f1, FPT f2)\n{ //! Safe from under and overflow.\n  //! Both f1 and f2 must be unsigned here.\n\n  if( (f2 < static_cast<FPT>(1))  && (f1 > f2 * boost::math::tools::max_value<FPT>()) )\n  { // Avoid overflow.\n    return boost::math::tools::max_value<FPT>();\n  }\n\n  if( (f1 == static_cast<FPT>(0))\n    || ((f2 > static_cast<FPT>(1)) && (f1 < f2 * boost::math::tools::min_value<FPT>()) )\n    )\n  {  // Avoid underflow.\n    return static_cast<FPT>(0);\n  }\n  return f1 / f2;\n} // safe_fpt_division(FPT f1, FPT f2)\n\n//! Check two floating-point values are close within a chosen tolerance.\ntemplate<typename FPT = double>\nclass close_to\n{\npublic:\n\n  // One  only.\n  template<typename T>\n  explicit close_to(T tolerance,\n    floating_point_comparison_type fpc_type = FPC_STRONG)\n  :\n    fraction_tolerance_(tolerance),\n      strong_or_weak_(fpc_type)\n  { //! Constructor for fraction tolerance and strength of comparison.\n    //! Checks that tolerance isn't negative - which does not make sense,\n    //! and can be assumed to be a programmer error?\n    BOOST_ASSERT(tolerance >= static_cast<T>(0));\n  }\n\n  close_to()\n  :\n  fraction_tolerance_(2 * boost::math::tools::epsilon<FPT>()),\n    strong_or_weak_(FPC_STRONG)\n  { //! Default constructor is strong comparison to twice numeric_limits<double>::epsilon().\n  }\n\n  bool operator()(FPT left, FPT right) const\n  { //! Compare two floating point values\n    //! \\return true if they are effectively equal (approximately) within tolerance & comparison strength.\n    FPT diff = fpt_abs(left - right);\n    FPT d1   = safe_fpt_division(diff, fpt_abs(right));\n    FPT d2   = safe_fpt_division(diff, fpt_abs(left));\n\n    return strong_or_weak_\n      ? ((d1 <= fraction_tolerance_) && (d2 <= fraction_tolerance_)) // Strong.\n      : ((d1 <= fraction_tolerance_) || (d2 <= fraction_tolerance_)); // Weak.\n  }\n\n  FPT size()\n  { //! \\return fraction tolerance.\n    return fraction_tolerance_;\n  }\n\n  floating_point_comparison_type strength()\n  { //! \\return floating_point comparison type strength, FPC_STRONG or FPC_WEAK\n    return strong_or_weak_;\n  }\n\nprivate:\n    FPT fraction_tolerance_; //! Tolerance expressed as a fraction, 1% == 0.01\n    floating_point_comparison_type strong_or_weak_; //! floating_point comparison type strength, FPC_STRONG or FPC_WEAK\n\n}; // class close_to\n\n\n// David Monniaux, http://arxiv.org/abs/cs/0701192v4,\n// It is somewhat common for beginners to add a comparison check to 0 before\n// computing a division, in order to avoid possible division-by-zero exceptions or\n// the generation of infinite results. A first objection to this practise is that, anyway,\n// computing 1/x for x very close to zero will generate very large numbers\n// that will most probably result in overflows later.\n// Another objection, which few programmers know about and that we wish to draw attention\n// to, is that it may actually fail to work, depending on what the compiler\n// does - that is, the program may actually test that x 6= 0, then, further down,\n// find that x = 0 without any apparent change to x!\n\n//! Check floating-point value is smaller than a chosen small value.\ntemplate<typename FPT = double>\nclass smallest\n{ /*!< \\details\n    David Monniaux, http://arxiv.org/abs/cs/0701192v4,\n    It is somewhat common for beginners to add a comparison check to 0 before\n    computing a division, in order to avoid possible division-by-zero exceptions or\n    the generation of infinite results. A first objection to this practise is that, anyway,\n    computing 1/x for x very close to zero will generate very large numbers\n    that will most probably result in overflows later.\n    Another objection, which few programmers know about and that we wish to draw attention\n    to, is that it may actually fail to work, depending on what the compiler\n    does - that is, the program may actually test that x 6= 0, then, further down,\n    find that x = 0 without any apparent change to x!\n*/\npublic:\n  template<typename T>\n  explicit smallest(T s)\n  :\n  smallest_(s)\n  { // Constructor.\n  }\n\n  smallest()\n  :\n  smallest_(2 * boost::math::tools::min_value<FPT>())\n  { /*!< Default Constructor.\n      Default smallest_ =  2. * boost::math::tools::min_value<double>();\n      multiplier m = 2 (must be integer or static_cast<FPT>())\n      is chosen to allow for a few bits of computation error.\n      Pessimistic multiplier is the number of arithmetic operations,\n      assuming every operation causes a 1 least significant bit error,\n      but a more realistic average would be half this.\n    */\n  }\n\n  template<typename T>\n  bool operator()(T fp_value, T s)\n  { //!< \\return true if smaller than the given small value.\n    if (fpt_abs(fp_value) == static_cast<T>(0))\n    { // Test for zero first in case T is actually an integer type zero,\n      // when the comparison < below would fail because\n      // smallest_ could become zero when min_value converts to integer.\n      return true;\n    }\n    return fpt_abs(fp_value) < fpt_abs(s);\n  } // bool operator()\n\n  template<typename T>\n  bool operator()(T fp_value)\n  { //!< \\return true if smaller than the defined smallest effectively-zero value.\n    if (fpt_abs(fp_value) == static_cast<FPT>(0))\n    { // Test for zero first in case FPT is actually an integer type,\n      // when the comparison < below would fail because\n      // smallest could become zero.\n      return true;\n    }\n    return fpt_abs(fp_value) < fpt_abs(smallest_);\n  } // bool operator()\n\n  FPT size()\n  { //!< \\return smallest value that will be counted as effectively zero.\n    return smallest_;\n  }\n\nprivate:\n  //!< Smallest value that will be counted as effectively zero.\n  FPT smallest_;\n}; // class smallest\n\n// Since double and the default smallest value 2 * min_value = 4.45015e-308\n// is a very common requirement, provide an convenience alias for this:\ntypedef smallest<double> tiny; //!< A shorthand for twice std::numeric_limits<double>::min_value(), often 4.4e-308.\n\n// Since double and the default twice std::numeric_limits<double>::epsilon() = 2.220446e-016\n// is a very common requirement, provide an convenience alias for this:\ntypedef close_to<double> neareq; //!< A shorthand for twice std::numeric_limits<double>::epsilon(), often 2e-16.\n\n#endif // BOOST_FLOATING_POINT_COMPARISON_HPP\n", "meta": {"hexsha": "f95ecc15c56cafa103e993c291e6b16596c5e641", "size": 10230, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/svg_plot/detail/fp_compare.hpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "include/boost/svg_plot/detail/fp_compare.hpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "include/boost/svg_plot/detail/fp_compare.hpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 40.92, "max_line_length": 119, "alphanum_fraction": 0.7189638319, "num_tokens": 2571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173801068221, "lm_q2_score": 0.7981867849406659, "lm_q1q2_score": 0.6410827140232173}}
{"text": "// Small bench routine for Eigen available in Eigen\n// (C) Desire NUENTSA WAKAM, INRIA\n\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <Eigen/Jacobi>\n#include <Eigen/Householder>\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/LU>\n#include <unsupported/Eigen/SparseExtra>\n//#include <Eigen/SparseLU>\n#include <Eigen/SuperLUSupport>\n// #include <unsupported/Eigen/src/IterativeSolvers/Scaling.h>\n#include <bench/BenchTimer.h>\n#include <unsupported/Eigen/IterativeSolvers>\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char **args)\n{\n  SparseMatrix<double, ColMajor> A; \n  typedef SparseMatrix<double, ColMajor>::Index Index;\n  typedef Matrix<double, Dynamic, Dynamic> DenseMatrix;\n  typedef Matrix<double, Dynamic, 1> DenseRhs;\n  VectorXd b, x, tmp;\n  BenchTimer timer,totaltime; \n  //SparseLU<SparseMatrix<double, ColMajor> >   solver;\n//   SuperLU<SparseMatrix<double, ColMajor> >   solver;\n  ConjugateGradient<SparseMatrix<double, ColMajor>, Lower,IncompleteCholesky<double,Lower> > solver; \n  ifstream matrix_file; \n  string line;\n  int  n;\n  // Set parameters\n//   solver.iparm(IPARM_THREAD_NBR) = 4;\n  /* Fill the matrix with sparse matrix stored in Matrix-Market coordinate column-oriented format */\n  if (argc < 2) assert(false && \"please, give the matrix market file \");\n  \n  timer.start();\n  totaltime.start();\n  loadMarket(A, args[1]);\n  cout << \"End charging matrix \" << endl;\n  bool iscomplex=false, isvector=false;\n  int sym;\n  getMarketHeader(args[1], sym, iscomplex, isvector);\n  if (iscomplex) { cout<< \" Not for complex matrices \\n\"; return -1; }\n  if (isvector) { cout << \"The provided file is not a matrix file\\n\"; return -1;}\n  if (sym != 0) { // symmetric matrices, only the lower part is stored\n    SparseMatrix<double, ColMajor> temp; \n    temp = A;\n    A = temp.selfadjointView<Lower>();\n  }\n  timer.stop();\n  \n  n = A.cols();\n  // ====== TESTS FOR SPARSE TUTORIAL ======\n//   cout<< \"OuterSize \" << A.outerSize() << \" inner \" << A.innerSize() << endl; \n//   SparseMatrix<double, RowMajor> mat1(A); \n//   SparseMatrix<double, RowMajor> mat2;\n//   cout << \" norm of A \" << mat1.norm() << endl; ;\n//   PermutationMatrix<Dynamic, Dynamic, int> perm(n);\n//   perm.resize(n,1);\n//   perm.indices().setLinSpaced(n, 0, n-1);\n//   mat2 = perm * mat1;\n//   mat.subrows();\n//   mat2.resize(n,n); \n//   mat2.reserve(10);\n//   mat2.setConstant();\n//   std::cout<< \"NORM \" << mat1.squaredNorm()<< endl;  \n\n  cout<< \"Time to load the matrix \" << timer.value() <<endl;\n  /* Fill the right hand side */\n\n//   solver.set_restart(374);\n  if (argc > 2)\n    loadMarketVector(b, args[2]);\n  else \n  {\n    b.resize(n);\n    tmp.resize(n);\n//       tmp.setRandom();\n    for (int i = 0; i < n; i++) tmp(i) = i; \n    b = A * tmp ;\n  }\n//   Scaling<SparseMatrix<double> > scal; \n//   scal.computeRef(A);\n//   b = scal.LeftScaling().cwiseProduct(b);\n\n  /* Compute the factorization */\n  cout<< \"Starting the factorization \"<< endl; \n  timer.reset();\n  timer.start(); \n  cout<< \"Size of Input Matrix \"<< b.size()<<\"\\n\\n\";\n  cout<< \"Rows and columns \"<< A.rows() <<\" \" <<A.cols() <<\"\\n\";\n  solver.compute(A);\n//   solver.analyzePattern(A);\n//   solver.factorize(A);\n  if (solver.info() != Success) {\n    std::cout<< \"The solver failed \\n\";\n    return -1; \n  }\n  timer.stop(); \n  float time_comp = timer.value(); \n  cout <<\" Compute Time \" << time_comp<< endl; \n  \n  timer.reset();\n  timer.start();\n  x = solver.solve(b);\n//   x = scal.RightScaling().cwiseProduct(x);\n  timer.stop();\n  float time_solve = timer.value(); \n  cout<< \" Time to solve \" << time_solve << endl; \n \n  /* Check the accuracy */\n  VectorXd tmp2 = b - A*x;\n  double tempNorm = tmp2.norm()/b.norm();\n  cout << \"Relative norm of the computed solution : \" << tempNorm <<\"\\n\";\n//   cout << \"Iterations : \" << solver.iterations() << \"\\n\"; \n  \n  totaltime.stop();\n  cout << \"Total time \" << totaltime.value() << \"\\n\";\n//  std::cout<<x.transpose()<<\"\\n\";\n  \n  return 0;\n}", "meta": {"hexsha": "a1f4bac8afdb4aa03bc8f6201a93fc86f982d4e7", "size": 3974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/bench/spbench/sp_solver.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/bench/spbench/sp_solver.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/bench/spbench/sp_solver.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": 31.792, "max_line_length": 101, "alphanum_fraction": 0.6361348767, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6410504308717433}}
{"text": "\n#include <SFML/Graphics.hpp> //Contains sf::Image, which is our image loader/writer.\n#include <iostream>\n#include <string>\n#include <chrono> //Timing shit\n#include <utility> //std::pair\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/filesystem/convenience.hpp>\n#include <filesystem>\n#include <cstdlib>\n#include <algorithm>\n#define _USE_MATH_DEFINES\n#include <cmath> //std::abs std::sqrt std::pow pi\n\nusing namespace std;\n\nstruct HSV {\n\tint hue;\n\tint saturation;\n\tint value;\n};\n\nstruct RGBA{\n\tdouble r;\n\tdouble g;\n\tdouble b;\n\tdouble a;\n};\n\nstruct vertex_color_t {\n\tRGBA rgba;\n\tHSV hsv;\n\tbool bg;\n};\n\ndouble degToRad(int d){\n\treturn d*(M_PI/180);\n}\n\n//Implementation of algorithm found and documented on wikipedia\nHSV rgb2hsv(RGBA rgb){\n\tfloat MAX = max(max(rgb.r,rgb.g), rgb.b);\n\tfloat MIN = min(min(rgb.r,rgb.g), rgb.b);\n\tunsigned int hue=0;\n\tif(MAX==MIN){\n\t\thue = 0;\n\t}\n\telse if(MAX==rgb.r){\n\t\thue = 60*((rgb.g - rgb.b)/(MAX-MIN));\n\t}\n\telse if(MAX==rgb.g){\n\t\thue = 60*(2 + (rgb.b - rgb.r)/(MAX-MIN));\n\t}\n\telse if(MAX==rgb.b){\n\t\thue = 60*(4 + (rgb.r - rgb.g)/(MAX-MIN));\n\t}\n\tif(hue < 0)\n\t\thue+=360;\n\n\tint saturation = 0;\n\tif(MAX==0)\n\t\tsaturation = 0;\n\telse{\n\t\tsaturation = (MAX-MIN)/MAX * 100;\n\t}\n\n\tint value = (MAX + MIN)/2.0 * 100;\n\n\treturn HSV{hue,saturation,value};\n}\n\nsf::Color hsv2rgb(HSV){\n\treturn sf::Color::Black;\n}\n\n//Compares two colors and returns whether they're close in color.\nbool color_comp(RGBA c1, RGBA c2, float K){\n\n\t//This comparison algorithm is an implementation of the low-cost approximation described here: https://en.wikipedia.org/wiki/Color_difference\n\t//Color deltas.\n\tint rd = (c1.r*255 - c2.r*255);\n\tint gd = (c1.g*255 - c2.g*255);\n\tint bd = (c1.b*255 - c2.b*255);\n\n\tfloat rhat = (c1.r + c2.r)/256;\n\n\t//Components of the sqrt algorithm\n\tfloat rcomp = (2+rhat) * pow(rd,2);\n\tfloat gcomp = 4*pow(gd,2);\n\tfloat bcomp = (2+(255-rhat)/256) * pow(bd, 2);\n\tfloat color_delta = sqrt(rcomp + gcomp + bcomp);\n\n\tif(color_delta < K)\n\t\treturn true;\n\treturn false;\n}\n\nbool hcolor_comp(HSV c1, HSV c2, double delta){\n\t//Remember, these are coming in as\n\t// Hue 0-360\n\t// Saturation 0-100\n\t// Value 0 - 100\n\tdouble h1 = degToRad(c1.hue);\n\tdouble h2 = degToRad(c2.hue);\n\tdouble s1 = c1.saturation/100.0;\n\tdouble s2 = c2.saturation/100.0;\n\tdouble v1 = c1.value / 100.0;\n\tdouble v2 = c2.value / 100.0;\n\n\t//We're going to project the color value into the HSV color space and then measure the distance.\n\tdouble p1 = pow(sin(h1)*s1*v1 - sin(h2)*s2*v2,2);\n\tdouble p2 = pow(cos(h1)*s1*v1 - cos(h2)*s2*v2,2);\n\tdouble p3 = pow(v1 - v2,2);\n\tdouble dist2 = p1 + p2 + p3; //Our distance squared.\n\tdouble dist = sqrt(dist2);\n\n\tif(dist < delta)\n\t\treturn true;\n\treturn false;\n}\n\n// bool hcolor_comp(HSV c1, HSV c2, double delta){\n// \t//Remember, these are coming in as\n// \t// Hue 0-360\n// \t// Saturation 0-100\n// \t// Value 0 - 100\n//\n// \tdouble v1 = c1.value / 100.0;\n// \tdouble v2 = c2.value / 100.0;\n// \tdouble dist = abs(v1-v2);\n// \tif(dist < delta)\n// \t\treturn true;\n// \treturn false;\n// }\n//This function generates a component color based on the total components & component id.\n//For now we'll assume there are less than 255 components and scale up later if it becomes a problem.\nsf::Color getComponentColor(int component_id){\n\tint some_prime = 31907;\n\tsrand(component_id * some_prime);\n\tint r = rand() % 256;\n\tint g = rand() % 256;\n\tint b = rand() % 256;\n\treturn sf::Color(r,g,b,255);\n}\nint main(int argc, char **argv){\n\n\tif(argc!=3){\n\t\tstd::cout << \"Please use syntax ./prog image_name delta\" << std::endl;\n\t\treturn -1;\n\t}\n\tstd::string input_file = argv[1];\n\t//Load our image.\n\tsf::Image img;\n\tif(!img.loadFromFile(input_file)){\n\t\treturn -1;\n\t}\n\tdouble delta = stod(string(argv[2]));\n\t//Get image dimensions.\n\tunsigned int height = img.getSize().y;\n\tunsigned int width = img.getSize().x;\n\tsize_t total_pixels = height * width;\n\n\tcout << \"Loaded \" << width << \"x\" << height << \" file \" << argv[1] << endl;\n\tcout << \"Total pixels: \" << total_pixels << endl;\n\n\tbool bgcalc = false;\n\tfloat K = 50;\n\tfloat BK = K;\n\tfloat ar=0;\n\tfloat ag=0;\n\tfloat ab=0;\n\tfor(unsigned int i=0; i<height; i++){\n\t\tfor(unsigned int j=0; j<width; j++){\n\t\t\t//unsigned int index = (i*width) + j;\n\t\t\tsf::Color pixColor = img.getPixel(j,i);\n\t\t\tfloat g = (pixColor.r + pixColor.g + pixColor.b)/3;\n\t\t\t ar+=pixColor.r/255.0;\n\t\t\t ag+=pixColor.g/255.0;\n\t\t\t ab+=pixColor.b/255.0;\n\t\t\t// ar+=g/255.0;\n\t\t\t// ag+=g/255.0;\n\t\t\t// ab+=g/255.0;\n\t\t\t// img.setPixel(j,i, sf::Color(g,g,g,255));\n\t\t}\n\t}\n\tcout << \"Converted to greyscale\" << endl;\n\tar/=total_pixels;\n\tag/=total_pixels;\n\tab/=total_pixels;\n\tRGBA avg_color = { ar,ag,ab,1.0};\n\tcout << \"Average pixel color(prgb): \" << ar << \" \" << ag << \" \" << ab << endl;\n\tHSV avg_hsv = rgb2hsv(avg_color);\n\tcout << \"Average pixel color(hsv): \" << avg_hsv.hue << \" \" << avg_hsv.saturation << \" \" << avg_hsv.value << endl;\n\n\t//Get a pointer to the c style string of data.\n\tconst sf::Uint8* pixels = img.getPixelsPtr();\n\n\n\t//Generate our graph object type and link our color property to vertex properties.\n\ttypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS, vertex_color_t, boost::no_property> Graph;\n\n\t//Our actual graph object is going to have a number of vertices = total_pixels.\n\t//Graph graph(total_pixels);\n\tGraph graph;\n\n\t//Pixels are stored in a c style array in RGBA pixel format made of 8 bit integers.\n\t//Let's load them into our graph.\n\tauto start = chrono::high_resolution_clock::now();\n\tfor(unsigned int i=0; i<height; i++){\n\t\tfor(unsigned int j=0; j<width; j++){\n\t\t\t//We're i units down height wise, and for each we have passed the width once. Then we're j units over on the current line.\n\t\t\t// 0 0 0 1\n\t\t\t// 1 0 2 0\n\t\t\t// 2 0 X 0\n\t\t\t// X is at spot (2,2), with a width of 4, and j of 2, we would have index = (2*4)+2 = 10. Which is correct.\n\t\t\tunsigned int index = (i*width) + j;\n\t\t\t//Extract our colors from the index\n\t\t\tsf::Uint8 r = pixels[4*index];\n\t\t\tsf::Uint8 g = pixels[4*index+1];\n\t\t\tsf::Uint8 b = pixels[4*index+2];\n\t\t\tsf::Uint8 a = pixels[4*index+3];\n\t\t\tRGBA rgba = { int(r)/255.0, int(g)/255.0, int(b)/255.0, int(a)/255.0};\n\t\t\tHSV hsv = rgb2hsv(rgba);\n\t\t\t//Stuff the data into our graph.\n\t\t\tbool bbb = false;\n\t\t\t// if(color_comp(rgba, avg_color, BK))\n\t\t\t// \tbbb=true;\n\t\t\tif(hcolor_comp(hsv, avg_hsv, delta))\n\t\t\t\tbbb=true;\n\t\t\tboost::add_vertex(vertex_color_t{rgba, hsv, bbb}, graph);\n\t\t}\n\t}\n\n\tauto end = chrono::high_resolution_clock::now();\n\tchrono::duration<double,std::milli> elapsed = end-start;\n\tcout << \"Took : \" << elapsed.count() << \"ms to insert vertex colors\" << endl;\n\n\t//Now that we have our vertex colors filled in, we need to create edges based on whether they have a similar color.\n\t//We defined bool color_comp(sf::Color, sf::Color) up top with some parameters to vary.\n\tstart = chrono::high_resolution_clock::now();\n\t// for(unsigned int i=0; i<height; i++){\n\t// \tfor (unsigned int j=0; j<width; j++){\n\t// \t\tunsigned int index = (i*width) + j;\n\t// \t\t//We cast i & j to ints because our test will be incorrect if we go below 0 on unsigned since it wraps\n\t// \t\tif((int)(i)-1 > 0){\n\t// \t\t\tint up = ((i-1)*width + j);\n\t// \t\t\t// if(graph[index].bg==graph[up].bg)\n\t// \t\t\t\tif(color_comp(graph[index].rgba, graph[up].rgba,K))\n\t// \t\t\t\t\tboost::add_edge(index, up, graph);\n\t// \t\t}\n\t// \t\tif(i+1 < height){\n\t// \t\t\tint down = ((i+1)*width + j);\n\t// \t\t\t// if(graph[index].bg==graph[down].bg)\n\t// \t\t\t\tif(color_comp(graph[index].rgba, graph[down].rgba, K))\n\t// \t\t\t\t\tboost::add_edge(index, down, graph);\n\t// \t\t}\n\t// \t\tif((int)(j)-1 > 0){\n\t// \t\t\tint left = ((i)*width + j-1);\n\t// \t\t\t// if(graph[index].bg==graph[left].bg)\n\t// \t\t\t\tif(color_comp(graph[index].rgba, graph[left].rgba, K))\n\t// \t\t\t\t\tboost::add_edge(index, left, graph);\n\t// \t\t}\n\t// \t\tif(j+1 < width){\n\t// \t\t\tint right = ((i)*width + j+1);\n\t// \t\t\t// if(graph[index].bg==graph[right].bg)\n\t// \t\t\t\tif(color_comp(graph[index].rgba, graph[right].rgba, K))\n\t// \t\t\t\t\tboost::add_edge(index, right, graph);\n\t// \t\t}\n\t// \t}\n\t// }\n\tfor(unsigned int i=0; i<height; i++){\n\t\tfor (unsigned int j=0; j<width; j++){\n\t\t\tunsigned int index = (i*width) + j;\n\t\t\t//We cast i & j to ints because our test will be incorrect if we go below 0 on unsigned since it wraps\n\t\t\tif((int)(i)-1 > 0){\n\t\t\t\tint up = ((i-1)*width + j);\n\t\t\t\tif(bgcalc){\n\t\t\t\t\tif(graph[index].bg && graph[up].bg)\n\t\t\t\t\t\tboost::add_edge(index, up, graph);\n\t\t\t\t}\n\t\t\t\tif(hcolor_comp(graph[index].hsv, graph[up].hsv, delta))\n\t\t\t\t\tboost::add_edge(index, up, graph);\n\t\t\t}\n\t\t\tif(i+1 < height){\n\t\t\t\tint down = ((i+1)*width + j);\n\t\t\t\tif(bgcalc){\n\t\t\t\t\tif(graph[index].bg && graph[down].bg)\n\t\t\t\t\t\tboost::add_edge(index, down, graph);\n\t\t\t\t}\n\t\t\t\tif(hcolor_comp(graph[index].hsv, graph[down].hsv, delta))\n\t\t\t\t\tboost::add_edge(index, down, graph);\n\t\t\t}\n\t\t\tif((int)(j)-1 > 0){\n\t\t\t\tint left = ((i)*width + j-1);\n\t\t\t\tif(bgcalc){\n\t\t\t\t\tif(graph[index].bg && graph[left].bg)\n\t\t\t\t\t\tboost::add_edge(index, left, graph);\n\t\t\t\t}\n\t\t\t\tif(hcolor_comp(graph[index].hsv, graph[left].hsv, delta))\n\t\t\t\t\tboost::add_edge(index, left, graph);\n\t\t\t}\n\t\t\tif(j+1 < width){\n\t\t\t\tint right = ((i)*width + j+1);\n\t\t\t\tif(bgcalc){\n\t\t\t\t\tif(graph[index].bg && graph[right].bg)\n\t\t\t\t\t\tboost::add_edge(index, right, graph);\n\t\t\t\t}\n\t\t\t\tif(hcolor_comp(graph[index].hsv, graph[right].hsv, delta))\n\t\t\t\t\tboost::add_edge(index, right, graph);\n\t\t\t}\n\t\t}\n\t}\n\tend = chrono::high_resolution_clock::now();\n\telapsed = end-start;\n\tcout << \"Took \" << elapsed.count() << \"ms to add \" << boost::num_edges(graph) << \" edges\" << endl;\n\n\t//Detect our components. Theoretically, the only things connected should be similar.\n\t//Our component vector should be filled with integer ids of which component an individual vertex belongs to now.\n\tstd::vector<int> component(total_pixels);\n\tsize_t num_components = boost::connected_components(graph, &component[0]);\n\tcout << \"Number of components detected: \" << num_components << endl;\n\t// for(unsigned int i = 0; i<num_components; i++){\n\t// \tint count = std::count(component.begin(), component.end(), i);\n\t// \tcout << \"Number of IDs for \" << i << \" : \" << count << endl;\n\t// }\n\t//Write our output to a file. Let's do this by just going through the graph and creating a new c_string.\n\t//Create and fill our pixel array.\n\tsf::Uint8 out_pixels[total_pixels*4];\n\n\t//Filling our pixel array with new colors based on our connected components vector.\n\tauto vp = boost::vertices(graph);\n\tfor(auto iter = vp.first; iter!=vp.second; iter++){\n\t\tunsigned int index = *iter;\n\t\t//We use our getComponentColor(int,int) defined at the top to generate a new color for our component.\n\t\t//The function is a simple function of the component id & number of components. (Let's hope we don't have something over 255 types for simplicity sake)\n\t\tsf::Color index_color = getComponentColor(component[index]);\n\t\tif(graph[index].bg && bgcalc)\n\t\t\tindex_color = sf::Color::Black;\n\t\tout_pixels[4*index] = index_color.r;\n\t\tout_pixels[4*index+1] = index_color.g;\n\t\tout_pixels[4*index+2] = index_color.b;\n\t\tout_pixels[4*index+3] = index_color.a;\n\t}\n\n\t//Let's use std::filesystem to extract our file extension.\n\tstd::filesystem::path out_path(input_file);\n\tstd::string out_filename = \"output\";\n\tif(out_path.has_extension()){\n\t\tout_filename += out_path.extension().string();\n\t}\n\n\t//Proper writing to disk.\n  sf::Image out_image;\n\tout_image.create(width, height, out_pixels);\n\tout_image.saveToFile(out_filename);\n\timg.saveToFile(\"grey.jpg\");\n\treturn 0;\n}\n", "meta": {"hexsha": "7dd582879203699c6a99470fb9f529a5fa30b561", "size": 11439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "draft/src/test.cpp", "max_stars_repo_name": "wrathofrathma/image-segmentation", "max_stars_repo_head_hexsha": "a20562fa3e60c44d92d0d6ea571ac4004cf1b4ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "draft/src/test.cpp", "max_issues_repo_name": "wrathofrathma/image-segmentation", "max_issues_repo_head_hexsha": "a20562fa3e60c44d92d0d6ea571ac4004cf1b4ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "draft/src/test.cpp", "max_forks_repo_name": "wrathofrathma/image-segmentation", "max_forks_repo_head_hexsha": "a20562fa3e60c44d92d0d6ea571ac4004cf1b4ae", "max_forks_repo_licenses": ["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.6869806094, "max_line_length": 153, "alphanum_fraction": 0.6421890025, "num_tokens": 3535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.641013810132599}}
{"text": "/**\n * @ file PointEvaluationRhs_test.cc\n * @ brief NPDE homework PointEvaluationRhs code\n * @ author ?, Liaowang Huang (refactoring)\n * @ date ?, 06/01/2020 (refactoring)\n * @ copyright Developed at ETH Zurich\n */\n\n#include \"../pointevaluationrhs.h\"\n\n#include <gtest/gtest.h>\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"../pointevaluationrhs_norms.h\"\n\n/* SAM_LISTING_BEGIN_1 */\nvoid testGlobalInverseQuad(const lf::mesh::Entity &quad, Eigen::Vector2d xh) {\n  LF_ASSERT_MSG(quad.RefEl() == lf::base::RefEl::kQuad(),\n                \"Cell must be a quadrilateral\");\n  // get the coordinates of the corners of this cell\n  const lf::geometry::Geometry *geo_ptr = quad.Geometry();\n  auto vertices = lf::geometry::Corners(*geo_ptr);\n  // Image of point in unit square under parametric mapping\n  Eigen::Vector2d x = geo_ptr->Global(xh);\n  Eigen::Vector2d xh_comp = PointEvaluationRhs::GlobalInverseQuad(vertices, x);\n  EXPECT_NEAR((xh - xh_comp).norm(), 0.0, 1.0E-8)\n      << \"quadl \" << quad << \": Mismatch xh = \" << xh << \", x = \" << x\n      << \", xh_comp = \" << xh_comp << std::endl;\n}\n/* SAM_LISTING_END_1 */\n\n// This test checks whether the implemented inverse mappings\n// of the transformation from the reference element work correctly\n// for the cells of a general hybrid mesh.\nTEST(PoinEvaluationRhs, mapping_test) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(0);\n\n  // Point in reference element for testing\n  Eigen::Vector2d xh(0.27, 0.41);\n\n  for (auto cell : mesh_p->Entities(0)) {\n    // Get shape of cell\n    const lf::geometry::Geometry *geo_ptr = cell->Geometry();\n    // Get cordinates of vertices\n    auto vertices = lf::geometry::Corners(*geo_ptr);\n    // Global coordinates of testing point\n    Eigen::Vector2d x{geo_ptr->Global(xh)};\n    // Reference coordinates\n    Eigen::Vector2d xh_comp;\n    // Query type of cell\n    const lf::base::RefEl ref_el = cell->RefEl();\n    // Depending on the type of cell compute the pre-image of\n    // the point x\n    switch (ref_el) {\n      case lf::base::RefEl::kTria(): {\n        xh_comp = PointEvaluationRhs::GlobalInverseTria(vertices, x);\n        break;\n      }\n      case lf::base::RefEl::kQuad(): {\n        xh_comp = PointEvaluationRhs::GlobalInverseQuad(vertices, x);\n        break;\n      }\n      default: {\n        LF_ASSERT_MSG(false, \"Not implemented for \" << ref_el);\n        break;\n      }\n    }  // end switch\n\n    ASSERT_NEAR((xh - xh_comp).norm(), 0.0, 1.0E-8);\n  }  // end loop over cells\n}\n\nTEST(PoinEvaluationRhs, solution_test) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(1);\n\n  Eigen::VectorXd sol_vec;\n  lf::assemble::UniformFEDofHandler dofh(mesh_p,\n                                         {{lf::base::RefEl::kPoint(), 1}});\n  auto result = PointEvaluationRhs::normsSolutionPointLoadDirichletBVP(\n      dofh, Eigen::Vector2d(1.3, 1.7), sol_vec);\n\n  double eps = 1e-6;\n\n  // Test norms\n  EXPECT_NEAR(result.first, 0.290660239, eps);\n  EXPECT_NEAR(result.second, 0.39855911, eps);\n\n  // Test solution\n  Eigen::VectorXd correct_sol(15);\n\n  correct_sol << 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.166856, 0.0304501, 0.0521068,\n      0.10716, 0.172936, 0.152714;\n\n  for (int i = 0; i < sol_vec.size(); ++i) {\n    EXPECT_NEAR(sol_vec(i), correct_sol(i), eps);\n  }\n}\n", "meta": {"hexsha": "c8db8c9c44c0aa92c9c9a7eaa2c848a3451f0d6d", "size": 3451, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/PointEvaluationRhs/mastersolution/test/pointevaluationrhs_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/PointEvaluationRhs/mastersolution/test/pointevaluationrhs_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/PointEvaluationRhs/mastersolution/test/pointevaluationrhs_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 32.8666666667, "max_line_length": 79, "alphanum_fraction": 0.6566212692, "num_tokens": 1023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7956581073313275, "lm_q1q2_score": 0.6410077826900199}}
{"text": "#include <list>\n#include <boost/timer.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/Arr_segment_traits_2.h>\n#include <CGAL/Arr_polyline_traits_2.h>\n#include <CGAL/Arrangement_2.h>\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;\ntypedef CGAL::Arr_segment_traits_2<Kernel>                Segment_traits_2;\ntypedef CGAL::Arr_polyline_traits_2<Segment_traits_2>     Traits_2;\ntypedef Traits_2::Point_2                                 Point_2;\ntypedef Segment_traits_2::Curve_2                         Segment_2;\ntypedef Traits_2::Curve_2                                 Polyline_2;\ntypedef CGAL::Arrangement_2<Traits_2>                     Arrangement_2;\n\nint main(int argc, char* argv[])\n{\n  if (argc < 2) {\n    std::cout << \"Usage: \" << argv[0] << \" <number of points> [seed]\"\n              << std::endl;\n    return -1;\n  }\n  unsigned int number_of_points(boost::lexical_cast<unsigned int>(argv[1]));\n  std::list<Point_2> pts;\n  unsigned int seed;\n  if (argc == 3) {\n    seed = boost::lexical_cast<unsigned int>(argv[2]);\n    CGAL::Random rnd(seed);\n    CGAL::Random_points_in_square_2<Point_2> g(10, rnd);\n    for (unsigned int i = 1; i < number_of_points; ++i) pts.push_back(*g++);\n  }\n  else {\n    CGAL::Random rnd;\n    seed = rnd.get_seed();\n    CGAL::Random_points_in_square_2<Point_2> g(10, rnd);\n    for (unsigned int i = 1; i < number_of_points; ++i) pts.push_back(*g++);\n  }\n  std::cout << \"Seed to be used: \" << seed << std::endl;\n  Polyline_2 poly(pts.begin(), pts.end());\n  Arrangement_2 arr;\n  boost::timer timer;\n  insert(arr, poly);\n  double secs = timer.elapsed();\n\n  std::cout << \"Arrangement computation took: \" << secs << std::endl;\n  std::cout << \"The arrangement size:\" << std::endl\n            << \"   V = \" << arr.number_of_vertices()\n            << \",  E = \" << arr.number_of_edges()\n            << \",  F = \" << arr.number_of_faces() << std::endl;\n\n  // Output for org-mode table\n  std::cout << \"| | \"  << \" | \"\n            << number_of_points << \" | \"\n            << arr.number_of_vertices() << \" | \"\n            << arr.number_of_edges() << \" | \"\n            << arr.number_of_faces() << \" |\"\n            << secs << \" | \" << std::endl;\n\n\n  return 0;\n}\n", "meta": {"hexsha": "5def4cca9fbf9c8680ed93bbbdec6627a2662e3e", "size": 2300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Arrangement_on_surface_2/benchmark/Arrangement_on_surface_2/bench_random_arr_polylines.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Arrangement_on_surface_2/benchmark/Arrangement_on_surface_2/bench_random_arr_polylines.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Arrangement_on_surface_2/benchmark/Arrangement_on_surface_2/bench_random_arr_polylines.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 35.3846153846, "max_line_length": 76, "alphanum_fraction": 0.5973913043, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.640893485642922}}
{"text": "#include <iostream>\n#include <cmath>\n#include <chrono>\n#include <cassert>\n#include <vector>\n#include <NTL/ZZ.h>\n#include <NTL/vector.h>\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace NTL;\n\nvoid remainder_tree(Vec<ZZ> &C, Vec<ZZ> &A, Vec<ZZ> &m, ZZ const &root_value, int start, int end);\nvoid remainder_tree_v1(Vec<ZZ> &C, Vec<ZZ> &A, Vec<ZZ> &m, ZZ const &root_value, const int k);\nZZ getNode(int index, Vec<ZZ> &base, ZZ const &mod);\nvoid remainder_tree_v2(Vec<ZZ> &C, Vec<ZZ> &A, Vec<ZZ> &m, ZZ const &root_value, const int k);\nvoid print_tree(Vec<ZZ> tree);\nvoid complexity_graph(int N, int d);\n\n/* Tags:\n *\n * //DEBUG// for debug statements\n * Optimization idea for optimizations that havent been impemented yet\n */\n\nint main(){\n\t\n\t// complexity_graph(1<<20, 100);\n\t// return 0;\n\t// Test for Wilson theorem\n\tint bound = 1<<24;\n\n\tVec<ZZ> A;\n\tA.SetLength(bound);\n\tVec<ZZ> m;\n\tm.SetLength(bound);\n\n\tfor(int i = 0; i < bound; i++){\n\t\tA[i] = i+1;\n\t\tm[i] = ProbPrime(ZZ(i+1)) ? i+1 : 1;\n\t}\n\n\t/*\t\n\tfor(int i = 0; i < A.length(); i++){\n\t\tcout << A[i] << \" \";\n\t}\n\tcout << endl;\n\n\tfor(int i = 0; i < m.length(); i++){\n\t\tcout << m[i] << \" \";\n\t}\n\tcout << endl;\n\t*/\n\n\tVec<ZZ> C;\n\tC.SetLength(bound);\n\n\tremainder_tree_v1(C, A, m, ZZ(1), 2);\n\t\n\t/*\n\tfor(int i = 0; i < C.length(); i++){\n\t\tcout << C[i] << \" \";\n\t}\n\tcout << endl;\n\t*/\n}\n\n/*\n * Original Remainder Tree implementation\n */\nvoid remainder_tree(Vec<ZZ> &C, Vec<ZZ> &A, Vec<ZZ> &m, ZZ const &root_value = ZZ(1), int start = 0, int end = -1) {\n\t\n\t//DEBUG// cout << \"root_value: \" << root_value << endl;\n\t// set default value for end\n\tif (end == -1) end = C.length();\n\n\t// Assert that interval [start, end] exists in C, A and m\n\tassert(end <= C.length());\n\tassert(end <= A.length());\n\tassert(end <= m.length());\n\n\t// Set N = length of interval\n\tint N = end - start;\n\n\t// Change nothing if N = 0\n\tif (N == 0) {\n\t\treturn;\n\t}\n\n\t// Index of leaf at the bottom left\n\tint leftmost = 1 << ((int)ceil(log2(N)));\n\n\t// Declare trees (always of length 2N for any N)\n\tVec<ZZ> ATree;\n\tATree.SetLength(2 * N);\n\tVec<ZZ> mTree;\n\tmTree.SetLength(2 * N);\n\tVec<ZZ> CTree;\n\tCTree.SetLength(2 * N);\n\n\t/* \n\t * For example when N=11 the leaves are in this order:\n\t *     / \\       /\\   /\\    /\\\n\t *    /   \\     /  7 8  9 10  11\n\t *   /\\   /\\   /\\\n\t *  1  2 3  4 5  6\n\t *\n\t */\n\n\t// Initialize the leaves in ATree and mTree\n\tfor (int i = leftmost; i < 2 * N; i++) { // leaves on lowest layer\n\t\tATree[i] = A[i - leftmost + start];\n\t\tmTree[i] = m[i - leftmost + start];\n\t}\n\tfor (int i = N; i < leftmost; i++) { // leaves on second lowest layer\n\t\tATree[i] = A[i + N - leftmost + start];\n\t\tmTree[i] = m[i + N - leftmost + start];\n\t}\n\n\t// Calculate the rest of the product tree mTree\n\tfor (int i = N - 1; i > 0; i--) {\n\t\tmTree[i] = mTree[2 * i] * mTree[2 * i + 1]; // parent is product of leaves\n\t}\n\n\t// Calculate the rest of the product tree aTree, taking mod mTree[1] = m[0]*...*m[N-1]\n\tfor(int i = N - 1; i > 0; i--) {\n\t\tif ((i & (i+1)) != 0) { // Don't do calculation if on a node in right-most branch\n\t\t\tATree[i] = (ATree[2 * i] * ATree[2 * i + 1]) % mTree[1]; // parent is product of leaves mod mTree[1]\n\t\t\tATree[2 * i + 1].kill();\n\t\t}\n\t}\n\n\t// Calculate accumulating remainder tree\n\tCTree[1] = root_value % mTree[1];\n\t//DEBUG// cout << \"CTree root: \" << CTree[1] << endl;\n\tfor (int i = 1; i < N; i++) {\n\t\tCTree[2 * i] = CTree[i] % mTree[2 * i]; // Left branch\n\t\tCTree[2 * i + 1] = (CTree[i] * ATree[2 * i]) % mTree[2 * i + 1]; // Right branch\n\t\tCTree[i].kill();\n\t}\n\n\t//DEBUG// print_tree(ATree);\n\t//DEBUG// print_tree(mTree);\n\t//DEBUG// print_tree(CTree);\n\t\n\tfor (int i = leftmost; i < 2 * N; i++) {\n\t\tC[i - leftmost + start] = CTree[i];\n\t}\n\tfor (int i = N; i < leftmost; i++) {\n\t\tC[i + N - leftmost + start] = CTree[i];\n\t}\n\t\n\treturn;\n}\n\n/*\n * Implements Costa's optimization\n * Doesn't do intervals yet\n * k = layer at which we switch from recomputing to remainder tree on each subtree\n */\nvoid remainder_tree_v1(Vec<ZZ> &C, Vec<ZZ> &A, Vec<ZZ> &m, ZZ const &root_value = ZZ(1), const int k = 2){\n\t\n\t// Assert that lengths of A and m match\n\tassert(C.length() == A.length());\n\tassert(C.length() == m.length());\n\n\t// Set N = length of input arrays\n\tint N = C.length();\n\n\t// Change nothing if N = 0\n\tif (N == 0) {\n\t\treturn;\n\t}\n\n\t// Ensure that there are at least k layers\n\tassert(N >= (1<<k));\n\n\n\t// Index of leaf at the bottom left\n\tint leftmost = 1 << ((int)ceil(log2(N)));\n\n\t// Declare Ctree (always of length 2N for any N)\n\tVec<ZZ> CTree;\n\tCTree.SetLength(2 * N);\n\n\t/* \n\t * For example when N=11 the leaves are in this order:\n\t *     / \\       /\\   /\\    /\\\n\t *    /   \\     /  7 8  9 10  11\n\t *   /\\   /\\   /\\\n\t *  1  2 3  4 5  6\n\t *\n\t */\n\n\t// Calculate the product of all the mods to keep A's small\n\t// ZZ mProd = getNode(1, m, ZZ(0));\n\n\t//DEBUG// uint64_t start1 = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\n\t// Step 1: Calculate the kth layer by recomputing everything necessary\n\tCTree[1] = root_value % getNode(1, m, ZZ(0));\n\tfor (int i = 1; i < 1<<k; i++) {\n\t\tCTree[2 * i] = CTree[i] % getNode(2*i, m, ZZ(0)); // Left branch\n\t\tZZ mProd = getNode(2*i+1, m, ZZ(0)); // Calculate what modulo CTree[2i+1] reduces in\n\t\tCTree[2 * i + 1] = (CTree[i] * getNode(2*i, A, mProd)) % mProd; // Right branch\n\t\tCTree[i].kill();\n\t}\n\n\t//DEBUG// uint64_t end1 = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t//DEBUG// cout << \"Time taken for recursive step: \" << (end1-start1) << endl;\n\n\t//DEBUG// uint64_t start2 = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t\n\t// Step 2: Calculate the subproduct trees\n\t// Roots are CTree[2^k + i]: {CTree[2^k], ..., CTree[2^(k+1)-1]}\n\n\t// First find index of root in subtree with leaves in both layers\n\tint notfirstk = ((int)log2(2*N-1) - k); // (#bits in 2*N-1) minus k\n\tint special = (2*N-1 - leftmost) >> notfirstk; // firstk digits excluding the most significant digit\n\t\n\t// Subtrees with leaves in first layer\n\tfor(int i = 0; i < special; i++) {\n\t\t// Number of leaves: 2^notfirstk = leftmost/2^k\n\t\t//DEBUG// cout << \"Calculating interval: [\" << (i<<notfirstk) << \", \" << ((i+1)<<notfirstk) << \"]\" << endl; \n\t\tremainder_tree(C, A, m, CTree[(1<<k) + i], i<<notfirstk, (i+1)<<notfirstk);\n\t}\n\n\t// Subtree with leaves in both layers\n\t// First, calculate number of leaves in this subtree, stored in specialleaves\n\tint notfirstkdigits = (2*N-1) % (1<<notfirstk);\n\tint onenotfirstkdigits = (1<<notfirstk) + notfirstkdigits;\n\tint specialleaves = (onenotfirstkdigits+1)/2; \n\t//DEBUG// cout << \"Calculating interval: [\" << (special<<notfirstk) << \", \" << ((special<<notfirstk) + specialleaves) << \"]\" << endl;\n\tremainder_tree(C, A, m, CTree[(1<<k) + special], special<<notfirstk, (special<<notfirstk) + specialleaves);\n\n\t// Subtrees with leaves in second layer\n\tfor(int i = special+1; i < 1<<k; i++){\n\t\t//DEBUG// cout << \"Calculating interval: [\" << ((special<<notfirstk) + specialleaves + ((i - special-1)<<(notfirstk-1))) << \", \" << ((special<<notfirstk) + specialleaves + ((i - special)<<(notfirstk-1))) << \"]\" << endl; \n\t\tremainder_tree(C, A, m, CTree[(1<<k) + i], (special<<notfirstk) + specialleaves + ((i - special-1)<<(notfirstk-1)), (special<<notfirstk) + specialleaves + ((i - special)<<(notfirstk-1)));\n\t}\n\n\t//DEBUG// uint64_t end2 = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t//DEBUG// cout << \"Time taken for subtree step: \" << (end2-start2) << endl;\n\n\treturn;\n\n}\n\n/*\n * Returns the value of the node on the tree at index k with leaves having value base\n */\nZZ getNode(int i, Vec<ZZ> &base, ZZ const &mod = ZZ(0)) { // Optimization idea: pass in what you're taking a mod of as well so if the modulus ever gets bigger than the value, just return the value\n\tint N = base.length();\n\tint leftmost = 1 << ((int)ceil(log2(N)));\n\tif (mod == 0){\n\t\tif (i >= leftmost) return base[i - leftmost];\n\t\telse if (i >= N) return base[i + N - leftmost];\n\t\t\n\t\treturn getNode(2*i, base, ZZ(0))*getNode(2*i+1, base, ZZ(0));\n\t}\n\t\n\telse {\n\t\tif (i >= leftmost) return base[i - leftmost] % mod;\n\t\telse if (i >= N) return base[i + N - leftmost] % mod;\n\t\t\n\t\treturn (getNode(2*i, base, mod)*getNode(2*i+1, base, mod)) % mod;\n\t}\n}\n\n/*\n * Prints a tree given in Vec<ZZ> form\n */\nvoid print_tree(Vec<ZZ> tree){\n\tint top = 1;\n\tint counter = 0;\n\tfor(int i = 1; i < tree.length(); i++){\n\t\tcout << tree[i] << \" \";\n\t\tcounter++;\n\t\tif (counter == top){\n\t\t\tcout << endl;\n\t\t\tcounter = 0;\n\t\t\ttop *= 2;\n\t\t}\n\t}\n\tcout << endl;\n}\n\n/*\n * Gives data points on size of input vs. computation time.\n * N = max size of data, d = number of data points\n */\n\nvoid complexity_graph(int N, int d){\n\tvector<int> x;\n\tvector<int> y;\n\tvector<int> z;\n\n\tint interval = N/d;\n\tint B = 0;\n\twhile(B <= N){\n\n\t\tint testSize = B;\n\t\tint numSize = B;\n\t\t\n\t\tVec<ZZ> test_A;\n\t\ttest_A.SetLength(testSize);\n\t\tVec<ZZ> test_m;\n\t\ttest_m.SetLength(testSize);\n\t\tfor (int i = 0; i < testSize; i++) {\n\t\t\ttest_A[i] = rand() % numSize + 1;\n\t\t\ttest_m[i] = rand() % numSize + 1;\n\t\t}\n\n\t\tx.push_back(B);\n\n\t\tVec<ZZ> test_C;\n\t\ttest_C.SetLength(testSize);\n\n\t\tuint64_t start;\n\t\tuint64_t end;\n\t\t\n\t\tstart = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t\tremainder_tree(test_C, test_A, test_m);\n\t\tend = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\n\t\ty.push_back(end-start);\n\n\n\t\tstart = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t\tremainder_tree_v1(test_C, test_A, test_m, ZZ(1), 1);\n\t\tend = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t\t\n\t\tz.push_back(end-start);\n\n\t\tB += interval;\n\t}\n\n\tfor(int i = 0; i < x.size(); i++){\n\t\tcout << x[i] << \": \" << y[i] << \", \" << z[i] << endl;\n\t}\n\n\n}\n", "meta": {"hexsha": "55abd258f2754d6bc667ea77cb2448b76d1978fa", "size": 9733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "archives/to_incorporate/rem_tree_int_costa.cpp", "max_stars_repo_name": "adienes/remainder-tree", "max_stars_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "archives/to_incorporate/rem_tree_int_costa.cpp", "max_issues_repo_name": "adienes/remainder-tree", "max_issues_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "archives/to_incorporate/rem_tree_int_costa.cpp", "max_forks_repo_name": "adienes/remainder-tree", "max_forks_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2936046512, "max_line_length": 222, "alphanum_fraction": 0.5998150622, "num_tokens": 3297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6408934836864778}}
{"text": "#include <Eigen/Dense> // Eigen\u306e\u30a4\u30f3\u30af\u30eb\u30fc\u30c9\u30d1\u30b9\u306f\u3001\u300c-I \u30aa\u30d7\u30b7\u30e7\u30f3\u3067\u6e21\u3059\u8a2d\u5b9a\u306b\u3059\u308b\u300d\n#include <iostream>\n\nusing namespace Eigen;\n\nint main()\n{\n    using std::cout;\n    using std::endl;\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\n    cout << m << endl;\n\n    double *m_array = m.data(); // Eigen\u306e\u884c\u5217\u3092\u914d\u5217\u5316\n\n    cout << \"m_array menber[3]: \" << m_array[3] << endl;\n\n    cout << sizeof(m_array) / sizeof(m_array[0]) << endl;\n\n    cout << m.array() + 1 << endl;\n\n    // \u8981\u7d20\u3054\u3068\u306b\u6bd4\u8f03\u6f14\u7b97\u5b50\u3092\u9069\u7528\n    Matrix<bool, 2, 2> B = m.unaryExpr([](double p) {return (p > 0.0) ? true : false; });\n\n    cout << B << endl;\n\n    cout << m.unaryExpr([](double p) { return (p > 0.0) ? true : false; }) << endl;\n\n    return 0;\n}", "meta": {"hexsha": "7e6e7d8bb6269500bc1b10042b019d8e31e274a5", "size": 733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch2/check_eigen.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": "ch2/check_eigen.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": "ch2/check_eigen.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.9428571429, "max_line_length": 89, "alphanum_fraction": 0.5225102319, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6408541317592974}}
{"text": "#ifndef _NCTX_PY_DISTANCEFCTS_\n#define _NCTX_PY_DISTANCEFCTS_\n\n#include <boost/python/stl_iterator.hpp>\n\nnamespace nctx { namespace python {\n\n  template< typename T >\n  inline\n  std::vector< T > to_std_vector( const py::object& iterable )\n  {\n      return std::vector< T >( py::stl_input_iterator< T >( iterable ),\n                               py::stl_input_iterator< T >( ) );\n  }\n\n  inline void wrap_distances(){\n    py::def(\"kl_divergence\", +[](py::object& list1, py::object& list2){\n      auto l1 = to_std_vector<double_t>(list1);\n      auto l2 = to_std_vector<double_t>(list2);\n      return kl_divergence(l1.begin(), l1.end(), l2.begin(), l2.end());\n    }, (py::arg(\"list1\"), py::arg(\"list2\")),\"Obtain Kullback Leibler Divergence.\\n\\n\\n\\nA straightforward implementation of KL Divergence. Note that both lists must be probability distributions, i.e. they sum to one. This is not checked internally and will result in obscure results if not taken care of.\\n\\nThe KL Divergence does not fulfil triangle inequality and, hence, is no metric. See https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence for more information.\\nBoth lists feeded into this function must have the same length and contain only numeric values.\\n\\n\\n\\n\\nArgs:\\n    list1 (list): First list\\n    list2 (list): Second list\\n\\nReturns:\\n    double: KL Divergence between the two lists\\n\\nExample:\\n    >>> import numpy as np\\n    >>> list1 = np.abs(context_map[0])\\n    >>> list2 = [.1,.2,.3,.4,.5]\\n    >>> list1 = list1/np.sum(list1)\\n    >>> list2 = list2/np.sum(list2)\\n    >>> kl_divergence(list1, list2)\\n    0.38236213356053317\\n\\n\");\n\n    py::def(\"js_divergence\", +[](py::object& list1, py::object& list2){\n      auto l1 = to_std_vector<double_t>(list1);\n      auto l2 = to_std_vector<double_t>(list2);\n      return js_divergence(l1.begin(), l1.end(), l2.begin(), l2.end());\n    }, (py::arg(\"list1\"), py::arg(\"list2\")),\"Obtain Jenson Shannon Divergence.\\n\\n\\n\\nA straightforward implementation of JS Divergence. Note that both lists must be probability distributions, i.e. they sum to one. This is not checked internally and will result in obscure results if not taken care of.\\n\\nThe JS Divergence is based on the KL Divergence. Its square root yields a metric. See https://en.wikipedia.org/wiki/Jensen%E2%80%93Shannon_divergence for more information.\\nBoth lists feeded into this function must have the same length and contain only numeric values.\\n\\n\\n\\n\\nArgs:\\n    list1 (list): First list\\n    list2 (list): Second list\\n\\nReturns:\\n    double: JS Divergence between the two lists\\n\\nExample:\\n    >>> import numpy as np\\n    >>> list1 = np.abs(context_map[0])\\n    >>> list2 = [.1,.2,.3,.4,.5]\\n    >>> list1 = list1/np.sum(list1)\\n    >>> list2 = list2/np.sum(list2)\\n    >>> js_divergence(list1, list2)\\n    0.11794226754027952\\n\\n\");\n\n    py::def(\"euclidean_distance\", +[](py::object& list1, py::object& list2){\n      auto l1 = to_std_vector<double_t>(list1);\n      auto l2 = to_std_vector<double_t>(list2);\n      return euclidean_distance(l1.begin(), l1.end(), l2.begin(), l2.end());\n    }, (py::arg(\"list1\"), py::arg(\"list2\")),\"Obtain Euclidean Distance.\\n\\n\\n\\nA straightforward implementation of Euclidean Distance.\\n\\nSee https://en.wikipedia.org/wiki/Euclidean_distance for more information.\\nBoth lists feeded into this function must have the same length and contain only numeric values.\\n\\n\\n\\n\\nArgs:\\n    list1 (list): First list\\n    list2 (list): Second list\\n\\nReturns:\\n    double: Euclidean Distance between the two lists\\n\\nExample:\\n    >>> list1 = context_map.get_list(0)\\n    >>> list2 = [.1,.2,.3,.4,.5]\\n    >>> euclidean_distance(list1, list2)\\n    0.4063153090787592\\n\\n\");\n\n    py::def(\"cosine_similarity\", +[](py::object& list1, py::object& list2){\n      auto l1 = to_std_vector<double_t>(list1);\n      auto l2 = to_std_vector<double_t>(list2);\n      return cosine_similarity(l1.begin(), l1.end(), l2.begin(), l2.end());\n    }, (py::arg(\"list1\"), py::arg(\"list2\")),\"Obtain Cosine Similarity.\\n\\n\\n\\nA straightforward implementation of Cosine Similarity.\\n\\nSee https://en.wikipedia.org/wiki/Cosine_similarity for more information.\\nBoth lists feeded into this function must have the same length and contain only numeric values.\\n\\n\\n\\n\\nArgs:\\n    list1 (list): First list\\n    list2 (list): Second list\\n\\nReturns:\\n    double: Cosine Similarity between the two lists\\n\\nExample:\\n    >>> list1 = context_map.get_list(0)\\n    >>> list2 = [.1,.2,.3,.4,.5]\\n    >>> cosine_similarity(list1, list2)\\n    0.8368374907292926\\n\\n\");\n\n    py::def(\"angular_distance\", +[](py::object& list1, py::object& list2){\n      auto l1 = to_std_vector<double_t>(list1);\n      auto l2 = to_std_vector<double_t>(list2);\n      return angular_distance(l1.begin(), l1.end(), l2.begin(), l2.end());\n    }, (py::arg(\"list1\"), py::arg(\"list2\")),\"Obtain Angular Distance.\\n\\n\\n\\nA straightforward implementation of Angular Distance.\\n\\nThe Angular Distance is a metric based on the KL Divergence. See https://en.wikipedia.org/wiki/Cosine_similarity#Angular_distance_and_similarity for more information.\\nBoth lists feeded into this function must have the same length and contain only numeric values.\\n\\n\\n\\n\\nArgs:\\n    list1 (list): First list\\n    list2 (list): Second list\\n\\nReturns:\\n    double: Angular Distance between the two lists\\n\\nExample:\\n    >>> list1 = context_map.get_list(0)\\n    >>> list2 = [.1,.2,.3,.4,.5]\\n    >>> angular_distance(list1, list2)\\n    0.18440190063093045\\n\\n\");\n\n  }\n\n\n}} //nproc::python\n\n#endif", "meta": {"hexsha": "f35f12055df725f54025a249900e320296870d88", "size": 5534, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/python_defs/wrap_distances.hpp", "max_stars_repo_name": "nctx/py3nctx", "max_stars_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-28T10:12:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T04:04:30.000Z", "max_issues_repo_path": "src/python_defs/wrap_distances.hpp", "max_issues_repo_name": "nctx/py3nctx", "max_issues_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/python_defs/wrap_distances.hpp", "max_forks_repo_name": "nctx/py3nctx", "max_forks_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 106.4230769231, "max_line_length": 970, "alphanum_fraction": 0.6904589808, "num_tokens": 1574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619134371954, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6408541266052153}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2014, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** \\example lanczos.cpp\n*\n*   This tutorial shows how to calculate the largest eigenvalues of a matrix using Lanczos' method.\n*\n*   The Lanczos method is particularly attractive for use with large, sparse matrices, since the only requirement on the matrix is to provide a matrix-vector product.\n*   Although less common, the method is sometimes also with dense matrices.\n*\n*   We start with including the necessary headers:\n**/\n\n// include necessary system headers\n#include <iostream>\n\n#ifndef NDEBUG\n  #define BOOST_UBLAS_NDEBUG\n#endif\n\n#define VIENNACL_WITH_UBLAS\n\n//include basic scalar and vector types of ViennaCL\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n\n#include \"viennacl/linalg/lanczos.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n\n// Some helper functions for this tutorial:\n#include <iostream>\n#include <fstream>\n#include <limits>\n#include <string>\n#include <iomanip>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n\n\n/**\n*  We read a sparse matrix (from Boost.uBLAS) from a matrix-market file, then run the Lanczos method.\n*  Finally, the computed eigenvalues are printed.\n**/\nint main()\n{\n  // If you GPU does not support double precision, use `float` instead of `double`:\n  typedef double     ScalarType;\n\n  /**\n  *  Create the uBLAS-matrix and read the sparse matrix:\n  **/\n  boost::numeric::ublas::compressed_matrix<ScalarType> ublas_A;\n  if (!viennacl::io::read_matrix_market_file(ublas_A, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  /**\n  *  Create the configuration for the Lanczos method.\n  **/\n  viennacl::linalg::lanczos_tag ltag(0.75,    // Select a power of 0.75 as the tolerance for the machine precision.\n                                     10,      // Compute (approximations to) the 10 largest eigenvalues\n                                     viennacl::linalg::lanczos_tag::partial_reorthogonalization, // use partial reorthogonalization\n                                     1700);   // Maximum size of the Krylov space\n\n  /**\n  *  Run the Lanczos method by passing the tag to the routine viennacl::linalg::eig()\n  **/\n  std::cout << \"Running Lanczos algorithm (this might take a while)...\" << std::endl;\n  std::vector<double> lanczos_eigenvalues = viennacl::linalg::eig(ublas_A, ltag);\n\n  /**\n  *  Print the computed eigenvalues and exit:\n  **/\n  for (std::size_t i = 0; i< lanczos_eigenvalues.size(); i++)\n    std::cout << \"Eigenvalue \" << i+1 << \": \" << std::setprecision(10) << lanczos_eigenvalues[i] << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "6da07e1fb23361b43d2d7a4a64f4fbb8a7e4b1ea", "size": 3678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/lanczos.cpp", "max_stars_repo_name": "ddemidov/viennacl-dev", "max_stars_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-08-23T17:05:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-23T17:06:24.000Z", "max_issues_repo_path": "examples/tutorial/lanczos.cpp", "max_issues_repo_name": "ddemidov/viennacl-dev", "max_issues_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tutorial/lanczos.cpp", "max_forks_repo_name": "ddemidov/viennacl-dev", "max_forks_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0588235294, "max_line_length": 166, "alphanum_fraction": 0.6402936378, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.640850430124097}}
{"text": "#include <Eigen/Sparse>\n#include <vector>\n#include \"mesh/deform.h\"\n#include \"igl/cotmatrix.h\"\n#include \"util/require.h\"\n\nnamespace telef::mesh\n{\n\n    namespace\n    {\n        Eigen::VectorXf SolveLS(\n            const Eigen::SparseMatrix<double> &A,\n            const Eigen::VectorXd &b)\n        {\n            Eigen::SparseMatrix<double> ATWA = A.transpose()*A;\n            Eigen::VectorXd ATWb = A.transpose()*b;\n\n            Eigen::SparseLU<\n                Eigen::SparseMatrix<double>,\n                Eigen::COLAMDOrdering<int>> lu;\n            lu.analyzePattern(ATWA);\n            lu.factorize(ATWA);\n            TELEF_REQUIRE(Eigen::Success ==  lu.info());\n\n            return lu.solve(ATWb).cast<float>();\n        }\n    }\n    /* \n    Deform a mesh according to landmark constraint \n\n    linear least squares with soft laplacian constraint\n    */\n    Eigen::MatrixXf lmk2deformed(\n        const Eigen::MatrixXf &V, \n        const Eigen::MatrixXi &F,\n        telef::types::CloudConstPtrT landmark3d,\n        const std::vector<int> &lmkinds,\n        const float lmkweight)\n    {\n        Eigen::SparseMatrix<double> L;\n        igl::cotmatrix(V, F, L);\n        Eigen::SparseMatrix<double> L_super(3*L.rows()+2*lmkinds.size()+1, 3*L.cols());\n\n        // create diagonal L matrix (L_super) and add additinal rows for landmark constraints\n        std::vector<Eigen::Triplet<double>> L_super_elems;\n        //// Duplicate L three times\n        for(int i=0; i<L.outerSize(); i++)\n        {\n            for(Eigen::SparseMatrix<double>::InnerIterator it(L,i);\n                it; ++it)\n            {\n                int j = it.index();\n                for (int k=0; k<3; k++)\n                {\n                    L_super_elems.emplace_back(L.rows()*k + i, L.cols()*k + j, it.value());\n                }\n            }\n        }\n\n        Eigen::VectorXd b_super(3*L.rows()+2*lmkinds.size()+1);\n\n        //// Add landmark constraint\n        for (size_t i=0; i<lmkinds.size(); i++)\n        {\n            for (int k=0; k<2; k++)\n            {\n                L_super_elems.emplace_back(3*L.rows()+2*i+k, L.rows()*k+lmkinds[i], lmkweight);\n                if (k == 0)\n                {\n                    b_super(3*L.rows()+2*i+k) = lmkweight*landmark3d->points[i].x;\n                }\n                else\n                {\n                    b_super(3*L.rows()+2*i+k) = lmkweight*landmark3d->points[i].y;\n                }\n            }\n        }\n        L_super_elems.emplace_back(3*L.rows()+2*lmkinds.size(), 2*L.rows(), 1.0);\n        b_super(3*L.rows()+2*lmkinds.size()) = V(0,2);\n\n        // Create L_super\n        L_super.setFromTriplets(L_super_elems.begin(), L_super_elems.end());\n        Eigen::VectorXd V_flat = Eigen::Map<const Eigen::VectorXf>(V.data(), V.rows()*V.cols()).cast<double>();\n        b_super.segment(0,3*L.rows()) = (L_super*V_flat).segment(0,3*L.rows());\n\n\n        Eigen::VectorXf pos_flat = SolveLS(L_super, b_super);\n        \n        Eigen::MatrixXf pos = Eigen::Map<Eigen::MatrixXf>(pos_flat.data(), L.rows(), 3);\n\n        return pos;\n    }\n}\n", "meta": {"hexsha": "3335383142cf225dbfeae8982fb891e655c54ecc", "size": 3064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mesh/deform.cpp", "max_stars_repo_name": "ycjungSubhuman/Kinect-Face", "max_stars_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_stars_repo_licenses": ["CNRI-Python"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-12T22:05:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:39:32.000Z", "max_issues_repo_path": "src/mesh/deform.cpp", "max_issues_repo_name": "ycjungSubhuman/Kinect-Face", "max_issues_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_issues_repo_licenses": ["CNRI-Python"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mesh/deform.cpp", "max_forks_repo_name": "ycjungSubhuman/Kinect-Face", "max_forks_repo_head_hexsha": "b582bd8572e998617b5a0d197b4ac9bd4a9b42be", "max_forks_repo_licenses": ["CNRI-Python"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-14T08:29:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-01T07:11:17.000Z", "avg_line_length": 32.2526315789, "max_line_length": 111, "alphanum_fraction": 0.522845953, "num_tokens": 795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6408504164844493}}
{"text": "//#include <cstdlib>\n#include <Eigen/Dense>\n#include <iostream>\n#include <libnotify.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n#ifdef __clang__\n# define COMPILER \"clang++\"\n#else\n# define COMPILER \"g++\"\n#endif\n\n// NOTE: Eigen requires explicit variable types for the proper\n// compile-time template processing\n\nMatrixXd build_matrix(int n, double seed) {\n  ArrayXXd i_idxs = ArrayXXd::Zero(n, n);\n  i_idxs.colwise() = ArrayXd::LinSpaced(n, 0, n - 1);\n\n  ArrayXXd j_idxs = ArrayXXd::Zero(n, n);\n  j_idxs.rowwise() = ArrayXd::LinSpaced(n, 0, n - 1).transpose();\n\n  ArrayXXd result = (i_idxs - j_idxs) * (i_idxs + j_idxs) * (seed / n / n);\n  return result.matrix();\n}\n\ndouble calc(int n) {\n  n = n / 2 * 2;\n  MatrixXd a = build_matrix(n, 1.0);\n  MatrixXd b = build_matrix(n, 2.0);\n  MatrixXd d = a * b;\n  return d(n / 2, n / 2);\n}\n\nint main(int argc, char** argv) {\n  auto n = argc > 1 ? atoi(argv[1]) : 100;\n\n  auto left = calc(101);\n  auto right = -18.67;\n  if (fabs(left - right) > 0.1) {\n    cerr << left << \" != \" << right << endl;\n    exit(EXIT_FAILURE);\n  }\n\n  notify_with_pid(\"C++/\" COMPILER  \" (Eigen)\");\n\n  auto results = calc(n);\n\n  notify(\"stop\");\n\n  cout << results << endl;\n}\n", "meta": {"hexsha": "38db5c2b7e8cb1545f8100378dcba44f6237d4e6", "size": 1192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matmul/matmul.cpp", "max_stars_repo_name": "mkitto/benchmarks", "max_stars_repo_head_hexsha": "070e222ef648c23e645a8c3fafcb25fe2288d817", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2317.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T19:49:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:51:14.000Z", "max_issues_repo_path": "matmul/matmul.cpp", "max_issues_repo_name": "mkitto/benchmarks", "max_issues_repo_head_hexsha": "070e222ef648c23e645a8c3fafcb25fe2288d817", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 230.0, "max_issues_repo_issues_event_min_datetime": "2015-02-01T12:22:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:27:51.000Z", "max_forks_repo_path": "matmul/matmul.cpp", "max_forks_repo_name": "mkitto/benchmarks", "max_forks_repo_head_hexsha": "070e222ef648c23e645a8c3fafcb25fe2288d817", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 322.0, "max_forks_repo_forks_event_min_datetime": "2015-02-01T00:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T17:25:25.000Z", "avg_line_length": 21.6727272727, "max_line_length": 75, "alphanum_fraction": 0.6224832215, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.640813801914403}}
{"text": "/*\n * Copyright Nick Thompson, 2021\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <boost/math/tools/cubic_roots.hpp>\n#include <random>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing boost::math::tools::cubic_root_condition_number;\nusing boost::math::tools::cubic_root_residual;\nusing boost::math::tools::cubic_roots;\nusing std::cbrt;\n\ntemplate <class Real> void test_zero_coefficients() {\n    Real a = 0;\n    Real b = 0;\n    Real c = 0;\n    Real d = 0;\n    auto roots = cubic_roots(a, b, c, d);\n    CHECK_EQUAL(roots[0], Real(0));\n    CHECK_EQUAL(roots[1], Real(0));\n    CHECK_EQUAL(roots[2], Real(0));\n\n    a = 1;\n    roots = cubic_roots(a, b, c, d);\n    CHECK_EQUAL(roots[0], Real(0));\n    CHECK_EQUAL(roots[1], Real(0));\n    CHECK_EQUAL(roots[2], Real(0));\n\n    a = 1;\n    d = 1;\n    // x^3 + 1 = 0:\n    roots = cubic_roots(a, b, c, d);\n    CHECK_EQUAL(roots[0], Real(-1));\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n    d = -1;\n    // x^3 - 1 = 0:\n    roots = cubic_roots(a, b, c, d);\n    CHECK_EQUAL(roots[0], Real(1));\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n\n    d = -2;\n    // x^3 - 2 = 0\n    roots = cubic_roots(a, b, c, d);\n    CHECK_ULP_CLOSE(roots[0], cbrt(Real(2)), 2);\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n\n    d = -8;\n    roots = cubic_roots(a, b, c, d);\n    CHECK_EQUAL(roots[0], Real(2));\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n\n    // (x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x - 6\n    roots = cubic_roots(Real(1), Real(-6), Real(11), Real(-6));\n    CHECK_ULP_CLOSE(roots[0], Real(1), 2);\n    CHECK_ULP_CLOSE(roots[1], Real(2), 2);\n    CHECK_ULP_CLOSE(roots[2], Real(3), 2);\n\n    // Double root:\n    // (x+1)^2(x-2) = x^3 - 3x - 2:\n    // Note: This test is unstable wrt to perturbations!\n    roots = cubic_roots(Real(1), Real(0), Real(-3), Real(-2));\n    CHECK_ULP_CLOSE(Real(-1), roots[0], 2);\n    CHECK_ULP_CLOSE(Real(-1), roots[1], 2);\n    CHECK_ULP_CLOSE(Real(2), roots[2], 2);\n\n    std::uniform_real_distribution<Real> dis(-2, 2);\n    std::mt19937 gen(12345);\n    // Expected roots\n    std::array<Real, 3> r;\n    int trials = 10;\n    for (int i = 0; i < trials; ++i) {\n        // Mathematica:\n        // Expand[(x - r0)*(x - r1)*(x - r2)]\n        // - r0 r1 r2 + (r0 r1 + r0 r2 + r1 r2) x\n        // - (r0 + r1 + r2) x^2 + x^3\n        for (auto &root : r) {\n            root = static_cast<Real>(dis(gen));\n        }\n        std::sort(r.begin(), r.end());\n        Real a = 1;\n        Real b = -(r[0] + r[1] + r[2]);\n        Real c = r[0] * r[1] + r[0] * r[2] + r[1] * r[2];\n        Real d = -r[0] * r[1] * r[2];\n\n        auto roots = cubic_roots(a, b, c, d);\n        // I could check the condition number here, but this is fine right?\n        if (!CHECK_ULP_CLOSE(r[0], roots[0], 25)) {\n            std::cerr << \"  Polynomial x^3 + \" << b << \"x^2 + \" << c << \"x + \"\n                      << d << \" has roots {\";\n            std::cerr << r[0] << \", \" << r[1] << \", \" << r[2]\n                      << \"}, but the computed roots are {\";\n            std::cerr << roots[0] << \", \" << roots[1] << \", \" << roots[2]\n                      << \"}\\n\";\n        }\n        CHECK_ULP_CLOSE(r[1], roots[1], 25);\n        CHECK_ULP_CLOSE(r[2], roots[2], 25);\n        for (auto root : roots) {\n            auto res = cubic_root_residual(a, b, c, d, root);\n            CHECK_LE(abs(res[0]), res[1]);\n        }\n    }\n}\n\nvoid test_ill_conditioned() {\n    // An ill-conditioned root reported by SATovstun:\n    // \"Exact\" roots produced with a high-precision calcuation on Wolfram Alpha:\n    // NSolve[x^3 + 10000*x^2 + 200*x +1==0,x]\n    std::array<double, 3> expected_roots{-9999.97999997,\n                                         -0.010010015026300100757327057,\n                                         -0.009990014973799899662674923};\n    auto roots = cubic_roots<double>(1, 10000, 200, 1);\n    CHECK_ABSOLUTE_ERROR(expected_roots[0], roots[0],\n                         std::numeric_limits<double>::epsilon());\n    CHECK_ABSOLUTE_ERROR(expected_roots[1], roots[1], 1.01e-5);\n    CHECK_ABSOLUTE_ERROR(expected_roots[2], roots[2], 1.01e-5);\n    double cond =\n        cubic_root_condition_number<double>(1, 10000, 200, 1, roots[1]);\n    double r1 = expected_roots[1];\n    // The factor of 10 is a fudge factor to make the test pass.\n    // Nonetheless, it does show this is basically correct:\n    CHECK_LE(abs(r1 - roots[1]) / abs(r1),\n             10 * std::numeric_limits<double>::epsilon() * cond);\n\n    cond = cubic_root_condition_number<double>(1, 10000, 200, 1, roots[2]);\n    double r2 = expected_roots[2];\n    // The factor of 10 is a fudge factor to make the test pass.\n    // Nonetheless, it does show this is basically correct:\n    CHECK_LE(abs(r2 - roots[2]) / abs(r2),\n             10 * std::numeric_limits<double>::epsilon() * cond);\n\n    // See https://github.com/boostorg/math/issues/757:\n    // The polynomial is ((x+1)^2+1)*(x+1) which has roots -1, and two complex\n    // roots:\n    roots = cubic_roots<double>(1, 3, 4, 2);\n    CHECK_ULP_CLOSE(roots[0], -1.0, 3);\n    CHECK_NAN(roots[1]);\n    CHECK_NAN(roots[2]);\n    return;\n}\n\nint main() {\n    test_zero_coefficients<float>();\n    test_zero_coefficients<double>();\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_zero_coefficients<long double>();\n#endif\n    test_ill_conditioned();\n#ifdef BOOST_HAS_FLOAT128\n    // For some reason, the quadmath is way less accurate than the\n    // float/double/long double:\n    // test_zero_coefficients<float128>();\n#endif\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "6b77f12cef31424a307811cc8d62ad14099511ff", "size": 5784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cubic_roots_test.cpp", "max_stars_repo_name": "grlee77/math", "max_stars_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/cubic_roots_test.cpp", "max_issues_repo_name": "grlee77/math", "max_issues_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/cubic_roots_test.cpp", "max_forks_repo_name": "grlee77/math", "max_forks_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4285714286, "max_line_length": 80, "alphanum_fraction": 0.5722683264, "num_tokens": 1861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6408137864122904}}
{"text": "#include <math/rotation.h>\n\n#include <Eigen/Geometry>\n#include <Eigen/../unsupported/Eigen/EulerAngles>\n#include \"test_common.h\"\n\nnamespace {\n\nconstexpr double epsilon = 1e-4;\n\nstd::vector<Eigen::Vector3f> test_rotation_vectors = {\n    {3.f, 1.f, 2.f},\n    {0.5f, 0.1f, 0.3f},\n    {-0.03f, 2.f, -0.2f}\n};\n\nstd::vector<Eigen::Vector3f> test_scales = {\n    {1.f, 2.f, 0.3f},\n    {-1.f, 0.5f, 0.1f},\n    {-2.f, -0.1f, -0.8f}\n};\n\n}\n\nTEST(Rotation,TestAxisAngleRotation)\n{\n    for (const auto& vec : test_rotation_vectors) {\n        Eigen::AngleAxisf ref_rot(vec.norm(), vec.normalized());\n        EXPECT_TRUE(cpt::get_angle_axis_rotation_matrix(vec).isApprox(ref_rot.toRotationMatrix()));\n    }\n}\n\nTEST(Rotation,TestEulerXYZRotation)\n{\n    for (const auto& vec : test_rotation_vectors) {\n        Eigen::EulerAnglesZYXf ref_rot(vec(2), vec(1), vec(0));\n        EXPECT_TRUE(cpt::get_euler_xyz_rotation_matrix(vec).isApprox(ref_rot.toRotationMatrix()));\n    }\n}\n\nTEST(Rotation,TestDecomposeScaleRotation)\n{\n    for (const auto& rot: test_rotation_vectors) {\n        Eigen::AngleAxisf angleAxis(rot.norm(), rot.normalized());\n        for (const auto& scale : test_scales) {\n            Eigen::Affine3f xform;\n            xform.setIdentity();\n            xform.prescale(scale);\n            xform.prerotate(angleAxis);\n\n            Eigen::Matrix3f test_rot;\n            Eigen::Vector3f test_scale;\n            cpt::decompose_scale_rotation(xform.matrix().block(0,0,3,3), test_rot, test_scale);\n            EXPECT_TRUE((test_rot * test_scale.asDiagonal()).isApprox(xform.matrix().block(0,0,3,3)));\n            EXPECT_NEAR(test_rot.determinant(), 1.f, epsilon);\n        }\n    }\n}\n\nCREATE_GENERIC_TEST_MAIN\n", "meta": {"hexsha": "ef9f1c8d79dc84aab4c428fd59f1382937a58c55", "size": 1694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/rotation_test.cpp", "max_stars_repo_name": "b3h47pte/cuda-path-tracing", "max_stars_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/rotation_test.cpp", "max_issues_repo_name": "b3h47pte/cuda-path-tracing", "max_issues_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/rotation_test.cpp", "max_forks_repo_name": "b3h47pte/cuda-path-tracing", "max_forks_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7704918033, "max_line_length": 102, "alphanum_fraction": 0.6422668241, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.72487026428967, "lm_q1q2_score": 0.640813783372522}}
{"text": "// USAGE: eigen_benchmarks <subroutine> <size>\n//\n// Benchmarks BLAS subroutines using Eigen's implementation. Will\n// construct random size x size matrices and/or size x 1 vectors\n// to test the subroutine with.\n//\n// Accepted values for subroutine are:\n//    L1: scal, copy, axpy, dot, nrm2\n//    L2: gemv_notrans, gemv_trans\n//    L3: gemm_notrans, gemm_trans_A, gemm_trans_B, gemm_trans_AB\n//\n\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <Eigen/Eigen>\n#include \"clock.h\"\n#include \"macros.h\"\n\ntemplate<class T>\nstd::string type_name();\n\ntemplate<>\nstd::string type_name<float>() {return \"s\";}\n\ntemplate<>\nstd::string type_name<double>() {return \"d\";}\n\ntemplate<class T>\nstruct Benchmarks {\n    typedef T Scalar;\n    typedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vector;\n    typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Matrix;\n\n    Scalar random_scalar() {\n        Vector x(1);\n        x.setRandom();\n        return x[0];\n    }\n\n    Vector random_vector(int N) {\n        Vector x(N);\n        x.setRandom();\n        return x;\n    }\n\n    Matrix random_matrix(int N) {\n        Matrix A(N, N);\n        A.setRandom();\n        return A;\n    }\n\n    Benchmarks(std::string n) : name(n) {}\n\n    void run(std::string benchmark, int size) {\n        if (benchmark == \"copy\") {\n            bench_copy(size);\n        } else if (benchmark == \"scal\") {\n            bench_scal(size);\n        } else if (benchmark == \"axpy\") {\n            bench_axpy(size);\n        } else if (benchmark == \"dot\") {\n            bench_dot(size);\n        } else if (benchmark == \"asum\") {\n            bench_asum(size);\n        } else if (benchmark == \"gemv_notrans\") {\n            bench_gemv_notrans(size);\n        } else if (benchmark == \"gemv_trans\") {\n            bench_gemv_trans(size);\n        } else if (benchmark == \"ger\") {\n            bench_ger(size);\n        } else if (benchmark == \"gemm_notrans\") {\n            bench_gemm_notrans(size);\n        } else if (benchmark == \"gemm_transA\") {\n            bench_gemm_transA(size);\n        } else if (benchmark == \"gemm_transB\") {\n            bench_gemm_transB(size);\n        } else if (benchmark == \"gemm_transAB\") {\n            bench_gemm_transAB(size);\n        }\n    }\n\n    Scalar result;\n\n    L1Benchmark(copy, type_name<T>(), y = x);\n    L1Benchmark(scal, type_name<T>(), x = alpha * x);\n    L1Benchmark(axpy, type_name<T>(), y = alpha * x + y);\n    L1Benchmark(dot,  type_name<T>(), result = x.dot(y));\n    L1Benchmark(asum, type_name<T>(), result = x.array().abs().sum());\n\n    L2Benchmark(gemv_notrans, type_name<T>(), y = alpha * A * x + beta * y);\n    L2Benchmark(gemv_trans,   type_name<T>(), y = alpha * A.transpose() * x + beta * y);\n    L2Benchmark(ger,          type_name<T>(), A = alpha * x * y.transpose() + A);\n\n    L3Benchmark(gemm_notrans, type_name<T>(), C = alpha * A * B + beta * C);\n    L3Benchmark(gemm_transA, type_name<T>(), C = alpha * A.transpose() * B + beta * C);\n    L3Benchmark(gemm_transB, type_name<T>(), C = alpha * A * B.transpose() + beta * C);\n    L3Benchmark(gemm_transAB, type_name<T>(), C = alpha * A.transpose() * B.transpose() + beta * C);\n\n  private:\n    std::string name;\n};\n\nint main(int argc, char* argv[]) {\n    if (argc != 3) {\n        std::cout << \"USAGE: eigen_benchmarks <subroutine> <size>\\n\";\n        return 0;\n    }\n\n    std::string subroutine = argv[1];\n    char type = subroutine[0];\n    int  size = std::stoi(argv[2]);\n\n    subroutine = subroutine.substr(1);\n    if (type == 's') {\n        Benchmarks<float> (\"Eigen\").run(subroutine, size);\n    } else if (type == 'd') {\n        Benchmarks<double>(\"Eigen\").run(subroutine, size);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "b3558eab8796dfca906e01909b69bafb432f029b", "size": 3662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/linear_algebra/benchmarks/eigen_benchmarks.cpp", "max_stars_repo_name": "akifoezkan/Halide-HLS", "max_stars_repo_head_hexsha": "1eee3f38f32722f3e725c29a5b7a084275062a7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 107.0, "max_stars_repo_stars_event_min_datetime": "2018-08-16T05:32:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T19:44:25.000Z", "max_issues_repo_path": "apps/linear_algebra/benchmarks/eigen_benchmarks.cpp", "max_issues_repo_name": "akifoezkan/Halide-HLS", "max_issues_repo_head_hexsha": "1eee3f38f32722f3e725c29a5b7a084275062a7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2017-02-02T21:03:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-27T20:49:31.000Z", "max_forks_repo_path": "apps/linear_algebra/benchmarks/eigen_benchmarks.cpp", "max_forks_repo_name": "akifoezkan/Halide-HLS", "max_forks_repo_head_hexsha": "1eee3f38f32722f3e725c29a5b7a084275062a7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-04-16T11:44:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T13:27:10.000Z", "avg_line_length": 29.7723577236, "max_line_length": 100, "alphanum_fraction": 0.5783724741, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.6407081571838555}}
{"text": "//\n// Tests the iLQR Taylor expansions of the dynamics and the cost function.\n//\n\n#include <ilqr/ilqr_taylor_expansions.hh>\n#include <utils/math_utils.hh>\n#include <utils/debug_utils.hh>\n\n#include <Eigen/Dense>\n\nvoid test_nonlinear_dynamics_linearization(const int state_dim, const int control_dim)\n{\n    std::srand(1);\n    const Eigen::MatrixXd A_true = Eigen::MatrixXd::Random(state_dim, state_dim);\n    const Eigen::MatrixXd B_true = Eigen::MatrixXd::Random(state_dim, control_dim);\n    auto dyn = [&A_true, &B_true](const Eigen::VectorXd &x, const Eigen::VectorXd& u) -> Eigen::VectorXd\n    {\n        const int state_dim = x.size();\n        Eigen::VectorXd x_next = A_true * x.array().cos().matrix() + B_true * u.array().sin().matrix();\n        IS_EQUAL(x_next.size(), state_dim);\n        return x_next;\n    };\n    const Eigen::VectorXd x_star = Eigen::VectorXd::Random(state_dim);\n    const Eigen::VectorXd u_star = Eigen::VectorXd::Random(control_dim);\n    const ilqr::Dynamics dynamics = ilqr::linearize_dynamics(dyn, x_star, u_star);\n\n    // Next linearization point under true dynamics.\n    const Eigen::VectorXd xt1_star = dyn(x_star, u_star);\n\n    Eigen::MatrixXd rep_x = (x_star.replicate(1, state_dim)).transpose();\n    Eigen::MatrixXd rep_u = (u_star.replicate(1, state_dim)).transpose();\n    Eigen::MatrixXd J_x = -1.*(A_true.array()*rep_x.array().sin()); \n    Eigen::MatrixXd J_u = B_true.array()*rep_u.array().cos(); \n    IS_TRUE(math::is_equal(dynamics.A, J_x, 1e-3)); // high tolerance since finite differencing is not that great.\n    IS_TRUE(math::is_equal(dynamics.B, J_u, 1e-3));\n\n    const Eigen::VectorXd xt_test = x_star + 0.01*Eigen::VectorXd::Random(state_dim);\n    const Eigen::VectorXd ut_test = u_star + 0.01*Eigen::VectorXd::Random(control_dim);\n\n    Eigen::VectorXd xt_diff = xt_test- x_star;\n    const Eigen::VectorXd ut_diff = ut_test - u_star;\n\n    // Use the linearization to predict the next x_{t+1}. \n    const Eigen::VectorXd xt1_diff = dynamics.A*xt_diff + dynamics.B*ut_diff;\n    IS_LESS_EQUAL(((xt1_diff + xt1_star) - dyn(xt_test, ut_test)).norm(), 1e-3);\n}\n\nvoid test_linear_dynamics_linearization(const int state_dim, const int control_dim)\n{\n    IS_GREATER(state_dim, 0);\n    IS_GREATER(control_dim, 0);\n\n    std::srand(2);\n\n    // Test with linear dynamics first. The taylor expansion should produce\n    // nearly exactly the same result.\n    const Eigen::MatrixXd A_true = Eigen::MatrixXd::Random(state_dim, state_dim);\n    const Eigen::MatrixXd B_true = Eigen::MatrixXd::Random(state_dim, control_dim);\n    auto linear_dyn = [&A_true, &B_true](const Eigen::VectorXd &x, const Eigen::VectorXd& u) -> Eigen::VectorXd\n    {\n        const int state_dim = x.size();\n        Eigen::VectorXd x_next = A_true*x + B_true*u;\n        IS_EQUAL(x_next.size(), state_dim);\n        return x_next;\n    };\n    \n    const Eigen::VectorXd x_star = Eigen::VectorXd::Random(state_dim);\n    const Eigen::VectorXd u_star = Eigen::VectorXd::Random(control_dim);\n    const ilqr::Dynamics dynamics = ilqr::linearize_dynamics(linear_dyn, x_star, u_star);\n\n    IS_TRUE(math::is_equal(dynamics.A, A_true, 1e-10)); \n    IS_TRUE(math::is_equal(dynamics.B, B_true, 1e-10));\n\n    // Next linearization point under true dynamics.\n    const Eigen::VectorXd xt1_star = linear_dyn(x_star, u_star);\n\n    const Eigen::VectorXd xt_test= Eigen::VectorXd::Random(state_dim);\n    const Eigen::VectorXd ut_test = Eigen::VectorXd::Random(control_dim);\n\n    Eigen::VectorXd xt_diff = xt_test- x_star;\n    const Eigen::VectorXd ut_diff = ut_test - u_star;\n\n    // Use the linearization to predict the next x_{t+1}. \n    const Eigen::VectorXd xt1_diff = dynamics.A*xt_diff + dynamics.B*ut_diff;\n\n    IS_TRUE(math::is_equal(xt1_diff + xt1_star, linear_dyn(xt_test, ut_test), 1e-7));\n}\n\nvoid test_quadratic_cost_taylor_expansion(const int state_dim, const int control_dim)\n{\n    IS_GREATER(state_dim, 0);\n    IS_GREATER(control_dim, 0);\n\n    std::srand(3);\n\n    // Test with linear dynamics first. The taylor expansion should produce\n    // nearly exactly the same result.\n    Eigen::MatrixXd Q_true = Eigen::MatrixXd::Random(state_dim, state_dim);\n    Eigen::MatrixXd R_true = Eigen::MatrixXd::Random(control_dim, control_dim);\n    Q_true = math::project_to_psd((Q_true + Q_true.transpose()), 1e-5);\n    R_true = math::project_to_psd((R_true + R_true.transpose()), 1e-5);\n    auto cost_func = [&Q_true, &R_true](const Eigen::VectorXd &x, const Eigen::VectorXd& u) -> double\n    {\n        Eigen::VectorXd cost = 0.5*(x.transpose()*Q_true*x + u.transpose()*R_true*u);\n        IS_EQUAL(cost.size(), 1);\n        return cost(0);\n    };\n    // Compute the Taylor expansion at a nominal point.\n    const Eigen::VectorXd x_star = Eigen::VectorXd::Random(state_dim);\n    const Eigen::VectorXd u_star = Eigen::VectorXd::Random(control_dim);\n    const ilqr::Cost cost = ilqr::quadraticize_cost(cost_func, x_star, u_star);\n\n    IS_TRUE(math::is_equal(cost.Q, Q_true, 1e-4));\n    IS_TRUE(math::is_equal(cost.R, R_true, 1e-4));\n    IS_TRUE(math::is_equal(cost.P, Eigen::MatrixXd::Zero(state_dim, control_dim), 1e-4)); \n    IS_TRUE(math::is_equal(cost.g_x,  Q_true*x_star, 1e-10));\n    IS_TRUE(math::is_equal(cost.g_u,  R_true*u_star, 1e-3)); // high tolerance since numerical error from finite differencing.\n\n    // Next linearization point under true dynamics.\n    const Eigen::VectorXd xt_test= Eigen::VectorXd::Random(state_dim);\n    const Eigen::VectorXd ut_test = Eigen::VectorXd::Random(control_dim);\n\n    Eigen::VectorXd xt_diff = Eigen::VectorXd::Ones(state_dim);\n    xt_diff = xt_test- x_star;\n    const Eigen::VectorXd ut_diff = ut_test - u_star;\n    Eigen::VectorXd ct_pred = 0.5*(xt_diff.transpose() * cost.Q * xt_diff)\n            + (xt_diff.transpose()*cost.P*ut_diff)\n            + 0.5*(ut_diff.transpose() * cost.R * ut_diff)\n            + (cost.g_u.transpose() * ut_diff)\n            + (cost.g_x.transpose() * xt_diff);\n    ct_pred.array() += cost.c;\n    IS_EQUAL(ct_pred.size(), 1); \n    IS_ALMOST_EQUAL(ct_pred(0,0), cost_func(xt_test, ut_test), 1e-5);\n}\n\nvoid test_exp_cost_taylor_expansion(const int state_dim, const int control_dim)\n{\n    IS_GREATER(state_dim, 0);\n    IS_GREATER(control_dim, 0);\n\n    std::srand(3);\n\n    // Test with linear dynamics first. The taylor expansion should produce\n    // nearly exactly the same result.\n    Eigen::MatrixXd wx = Eigen::VectorXd::Random(state_dim);\n    Eigen::MatrixXd wu = Eigen::VectorXd::Random(control_dim);\n    auto cost_func = [&wx, &wu](const Eigen::VectorXd &x, const Eigen::VectorXd& u) -> double\n    {\n        const double norm_sq = x.squaredNorm();\n        const Eigen::VectorXd term = wx.transpose() * x + wu.transpose() * u * 0.5*norm_sq;\n        IS_EQUAL(term.size(), 1);\n        const double cost = std::exp(-1.*term(0));\n        return cost;\n    };\n\n    // Compute the Taylor expansion at a nominal point.\n    const Eigen::VectorXd x_star = Eigen::VectorXd::Random(state_dim);\n    const Eigen::VectorXd u_star = Eigen::VectorXd::Random(control_dim);\n    const ilqr::Cost cost = ilqr::quadraticize_cost(cost_func, x_star, u_star);\n\n    double ct_xu = cost_func(x_star, u_star);\n    const Eigen::VectorXd g_x_true = ct_xu * (-1.*wx - (wu.transpose()*u_star)[0]*x_star);\n    const Eigen::VectorXd g_u_true = ct_xu * (-0.5*wu*x_star.squaredNorm());\n    const Eigen::MatrixXd Hxx_true = ct_xu * -1.0*(wu.transpose()*u_star)[0]*Eigen::MatrixXd::Identity(state_dim, state_dim).array() \n        + (1.0/ct_xu) * (g_x_true * g_x_true.transpose()).array();\n    const Eigen::MatrixXd Huu_true =  1.0/ct_xu * (g_u_true * g_u_true.transpose()).array();\n    const Eigen::MatrixXd Hux_true = ct_xu * (-1.0*wu*x_star.transpose()).array() + (1.0/ct_xu) * (g_u_true * g_x_true.transpose()).array(); \n\n    // Since we may need to project to PSD cone, construct and project it.\n    Eigen::MatrixXd Q_true = math::project_to_psd(Hxx_true, 1e-11);\n    math::check_psd(Q_true, 1e-12);\n\n    Eigen::MatrixXd R_true = math::project_to_psd(Huu_true, 1e-8);\n    math::check_psd(R_true, 1e-9);\n\n    IS_TRUE(math::is_equal(cost.Q, Q_true, 1e-2));\n    IS_TRUE(math::is_equal(cost.R, R_true, 1e-2));\n    IS_TRUE(math::is_equal(cost.P, Hux_true.transpose(), 1e-2)); \n    IS_TRUE(math::is_equal(cost.g_u,  g_u_true, 1e-2)); // high tolerance since numerical error from finite differencing.\n    IS_TRUE(math::is_equal(cost.g_x,  g_x_true, 1e-2)); // high tolerance since numerical error from finite differencing.\n\n    constexpr double deviation = 1e-2;\n    const Eigen::VectorXd xt_test = x_star.array() + deviation;\n    const Eigen::VectorXd ut_test = u_star.array() + deviation;\n\n    Eigen::VectorXd xt_diff = xt_test- x_star;\n    const Eigen::VectorXd ut_diff = ut_test - u_star;\n    Eigen::VectorXd ct_pred = 0.5*(xt_diff.transpose() * cost.Q * xt_diff)\n            + (xt_diff.transpose()*cost.P*ut_diff)\n            + 0.5*(ut_diff.transpose() * cost.R * ut_diff)\n            + (cost.g_u.transpose() * ut_diff)\n            + (cost.g_x.transpose() * xt_diff);\n    ct_pred.array() += cost.c;\n    IS_EQUAL(ct_pred.size(), 1); \n    IS_ALMOST_EQUAL(ct_pred(0,0), cost_func(xt_test, ut_test), 5e-2);\n}\n\n\nint main()\n{\n    // Test linear dynamics linearization. \n    test_linear_dynamics_linearization(12, 12);\n    test_linear_dynamics_linearization(12, 5);\n    test_linear_dynamics_linearization(5, 12);\n    test_linear_dynamics_linearization(1, 5);\n    test_linear_dynamics_linearization(5, 1);\n    test_linear_dynamics_linearization(1, 1);\n\n\n    // Test nonlinear (cos & sin) dynamics linearization. \n    test_nonlinear_dynamics_linearization(12, 12);\n    test_nonlinear_dynamics_linearization(12, 5);\n    test_nonlinear_dynamics_linearization(5, 12);\n    test_nonlinear_dynamics_linearization(5, 3);\n    test_nonlinear_dynamics_linearization(1, 1);\n    test_nonlinear_dynamics_linearization(3, 3);\n\n\n    // Test quadratic cost function 2nd order taylor expansions. \n    test_quadratic_cost_taylor_expansion(12, 12);\n    test_quadratic_cost_taylor_expansion(12, 5);\n    test_quadratic_cost_taylor_expansion(5, 12);\n    test_quadratic_cost_taylor_expansion(1, 5);\n    test_quadratic_cost_taylor_expansion(5, 1);\n    test_quadratic_cost_taylor_expansion(1, 1);\n\n    // Test exponential cost function 2nd order taylor expansions. \n    // Larger dimensions 3 makes the tolerances higher in the test.\n    test_exp_cost_taylor_expansion(5,5);\n    test_exp_cost_taylor_expansion(3,5);\n    test_exp_cost_taylor_expansion(5,3);\n    test_exp_cost_taylor_expansion(3,1);\n    test_exp_cost_taylor_expansion(1,3);\n    test_exp_cost_taylor_expansion(1,1);\n\n    return 0;\n}\n", "meta": {"hexsha": "c5a22238b70b99403c574472d2ffa4cd9ca88b21", "size": 10590, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/test/test_ilqr_taylor_expansions.cc", "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/test/test_ilqr_taylor_expansions.cc", "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/test/test_ilqr_taylor_expansions.cc", "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": 44.4957983193, "max_line_length": 141, "alphanum_fraction": 0.6928234183, "num_tokens": 2925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.640708153945938}}
{"text": "// Copyright Louis Dionne 2013-2017\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/assert.hpp>\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/integral_constant.hpp>\r\n#include <boost/hana/minus.hpp>\r\nnamespace hana = boost::hana;\r\n\r\n\r\nint main() {\r\n    BOOST_HANA_CONSTANT_CHECK(hana::minus(hana::int_c<3>, hana::int_c<5>) == hana::int_c<-2>);\r\n    static_assert(hana::minus(1, 2) == -1, \"\");\r\n}\r\n", "meta": {"hexsha": "3ebb379f4cfed4c3db0f17f0bb511e41fa16b249", "size": 527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/minus.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/minus.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/hana/example/minus.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 32.9375, "max_line_length": 95, "alphanum_fraction": 0.6925996205, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6407081387088068}}
{"text": "/* @copyright The code is licensed under the MIT License\n *            <https://opensource.org/licenses/MIT>,\n *            Copyright (c) 2020 Christian Eskil Vaugelade Berg\n * @author Christian Eskil Vaugelade Berg\n*/\n#pragma once \n\n#include <orient/axis.hpp>\n\n#include <Eigen/Dense>\n\nnamespace orient::detail {\n\ntemplate<Axis axis>\nEigen::Matrix3d make_generator()\n{\n  Eigen::Matrix3d M = Eigen::Matrix3d::Zero();\n  if constexpr(axis == Axis::x){\n    M(1,2) = -1;\n    M(2,1) = 1;\n  }\n  else if constexpr(axis == Axis::y){\n    M(0,2) = 1;\n    M(2,0) = -1;\n  }\n  else {\n    M(0,1) = -1;\n    M(1,0) = 1;\n  }\n  return M;\n}\n\ntemplate<Axis axis>\nstatic const auto generator = make_generator<axis>();\n\n}\n", "meta": {"hexsha": "69100e33099d8f9395124ebb297ec1c1fe82d77b", "size": 699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orient/detail/so3_generator.hpp", "max_stars_repo_name": "Eskilade/orient", "max_stars_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T07:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T09:23:29.000Z", "max_issues_repo_path": "include/orient/detail/so3_generator.hpp", "max_issues_repo_name": "Eskilade/orient", "max_issues_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T02:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T01:42:47.000Z", "max_forks_repo_path": "include/orient/detail/so3_generator.hpp", "max_forks_repo_name": "Eskilade/orient", "max_forks_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T04:26:22.000Z", "avg_line_length": 18.8918918919, "max_line_length": 63, "alphanum_fraction": 0.6094420601, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6406792184115184}}
{"text": "#include \"discrete.hpp\"\n\n#include <gtest/gtest.h>\n\n#include <boost/random/mersenne_twister.hpp>\n\nusing namespace MultidimensionalArray;\nusing namespace ProbabilityDistributions;\n\nTEST(DiscreteTest, Likelihood) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  Discrete<5, double> dist;\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n\n  double likelihood1 = dist.log_likelihood(samples);\n\n  dist.MLE(samples);\n\n  double likelihood2 = dist.log_likelihood(samples);\n\n  EXPECT_GE(likelihood2, likelihood1);\n\n  auto p = dist.get_p();\n  double sum = 0;\n  for (size_t i = 0; i < p.size(); i++) {\n    EXPECT_LE(0, p[i]);\n    sum += p[i];\n  }\n  EXPECT_DOUBLE_EQ(1, sum);\n}\n\nTEST(DiscreteTest, MLE) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  Discrete<5, double> dist;\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n  dist.MLE(samples);\n\n  std::vector<double> p = dist.get_p();\n  double eps = 1e-2;\n  double ll = dist.log_likelihood(samples);\n\n  for (int i = 0; i < 5; i++) {\n    p[i] += eps;\n    dist.set_p(p);\n    EXPECT_GE(ll, dist.log_likelihood(samples));\n    p[i] -= 2* eps;\n    dist.set_p(p);\n    EXPECT_GE(ll, dist.log_likelihood(samples));\n    p[i] += eps;\n  }\n}\n\nTEST(DiscreteTest, Samples) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  {\n    Discrete<2, double> dist;\n    Array<double> samples;\n    dist.sample(samples, n_samples, rng);\n    size_t count_0 = 0, count_1 = 0;\n    for (size_t i = 0; i < n_samples; i++) {\n      if (samples(i,0) == 1)\n        count_0++;\n      if (samples(i,1) == 1)\n        count_1++;\n    }\n    EXPECT_EQ(n_samples, count_0 + count_1);\n    EXPECT_LT(0, count_0);\n    EXPECT_LT(0, count_1);\n  }\n  {\n    Discrete<2, double> dist({0,1});\n    Array<double> samples;\n    dist.sample(samples, n_samples, rng);\n    size_t count_0 = 0, count_1 = 0;\n    for (size_t i = 0; i < n_samples; i++) {\n      if (samples(i,0) == 1)\n        count_0++;\n      if (samples(i,1) == 1)\n        count_1++;\n    }\n    EXPECT_EQ(0, count_0);\n    EXPECT_EQ(n_samples, count_1);\n  }\n}\n", "meta": {"hexsha": "aa60f6328e0530a18622aa7eac923e08e58cd368", "size": 2099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/discrete.cpp", "max_stars_repo_name": "mirandaconrado/probability-distributions", "max_stars_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/discrete.cpp", "max_issues_repo_name": "mirandaconrado/probability-distributions", "max_issues_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/discrete.cpp", "max_forks_repo_name": "mirandaconrado/probability-distributions", "max_forks_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3222222222, "max_line_length": 52, "alphanum_fraction": 0.6241067175, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6406792184115183}}
{"text": "//=======================================================================\n// Copyright 2007 Aaron Windsor\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/ref.hpp>\n#include <vector>\n\n#include <boost/graph/make_biconnected_planar.hpp>\n#include <boost/graph/make_maximal_planar.hpp>\n#include <boost/graph/planar_face_traversal.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\n\n\n// This example shows how to start with a connected planar graph \n// and add edges to make the graph maximal planar (triangulated.)\n// Any maximal planar simple graph on n vertices has 3n - 6 edges and \n// 2n - 4 faces, a consequence of Euler's formula.\n\n\n\nusing namespace boost;\n\n\n// This visitor is passed to planar_face_traversal to count the \n// number of faces.\nstruct face_counter : public planar_face_traversal_visitor\n{\n  face_counter() : count(0) {}\n  void begin_face() { ++count; }\n  int count;\n};\n\n\nint main(int argc, char** argv)\n{\n\n  typedef adjacency_list\n    < vecS,\n      vecS,\n      undirectedS,\n      property<vertex_index_t, int>,\n      property<edge_index_t, int>\n    > \n    graph;\n\n  // Create the graph - a straight line\n  graph g(10);\n  add_edge(0,1,g);\n  add_edge(1,2,g);\n  add_edge(2,3,g);\n  add_edge(3,4,g);\n  add_edge(4,5,g);\n  add_edge(5,6,g);\n  add_edge(6,7,g);\n  add_edge(7,8,g);\n  add_edge(8,9,g);\n\n  std::cout << \"Since the input graph is planar with \" << num_vertices(g) \n            << \" vertices,\" << std::endl\n            << \"The output graph should be planar with \" \n            << 3*num_vertices(g) - 6 << \" edges and \"\n            << 2*num_vertices(g) - 4 << \" faces.\" << std::endl;\n\n  //Initialize the interior edge index\n  property_map<graph, edge_index_t>::type e_index = get(edge_index, g);\n  graph_traits<graph>::edges_size_type edge_count = 0;\n  graph_traits<graph>::edge_iterator ei, ei_end;\n  for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    put(e_index, *ei, edge_count++);\n  \n  \n  //Test for planarity; compute the planar embedding as a side-effect\n  typedef std::vector< graph_traits<graph>::edge_descriptor > vec_t;\n  std::vector<vec_t> embedding(num_vertices(g));\n  if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                                   boyer_myrvold_params::embedding = \n                                       &embedding[0]\n                                   )\n      )\n    std::cout << \"Input graph is planar\" << std::endl;\n  else\n    std::cout << \"Input graph is not planar\" << std::endl;\n  \n  make_biconnected_planar(g, &embedding[0]);\n\n  // Re-initialize the edge index, since we just added a few edges\n  edge_count = 0;\n  for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    put(e_index, *ei, edge_count++);\n\n\n  //Test for planarity again; compute the planar embedding as a side-effect\n  if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                                   boyer_myrvold_params::embedding = \n                                       &embedding[0]\n                                   )\n      )\n    std::cout << \"After calling make_biconnected, the graph is still planar\" \n              << std::endl;\n  else\n    std::cout << \"After calling make_biconnected, the graph is not planar\" \n              << std::endl;\n\n  make_maximal_planar(g, &embedding[0]);\n\n\n\n  // Re-initialize the edge index, since we just added a few edges\n  edge_count = 0;\n  for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    put(e_index, *ei, edge_count++);\n\n  // Test for planarity one final time; compute the planar embedding as a \n  // side-effect\n  std::cout << \"After calling make_maximal_planar, the final graph \";\n  if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n                                   boyer_myrvold_params::embedding = \n                                       &embedding[0]\n                                   )\n      )\n    std::cout << \"is planar.\" << std::endl;\n  else\n    std::cout << \"is not planar.\" << std::endl;\n  \n  std::cout << \"The final graph has \" << num_edges(g) \n            << \" edges.\" << std::endl;\n\n  face_counter count_visitor;\n  planar_face_traversal(g, &embedding[0], count_visitor);\n  std::cout << \"The final graph has \" << count_visitor.count << \" faces.\" \n            << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "70fd9b3f1f0ab6680e2a6c8d3a78634ba76aa893", "size": 4630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/make_maximal_planar.cpp", "max_stars_repo_name": "oudream/boost_1_42_0", "max_stars_repo_head_hexsha": "e92227bf374e478030e89876ec353de6eecaeac0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/graph/example/make_maximal_planar.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/example/make_maximal_planar.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 32.1527777778, "max_line_length": 77, "alphanum_fraction": 0.6030237581, "num_tokens": 1205, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527906914787, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6406792108497407}}
{"text": "/// @file  sphere.hpp\n/// @brief Declarations for methods to find sphere intersections.\n///\n/// The intersection of d spheres in R^d is either zero, one, or two points.\n/// More than d spheres can only intersect in zero or one points.\n/// The methods here provide alternative ways to compute the intersection.\n///\n/// sphere_intersection_gauss() is the fastest but least reliable. It requires\n/// exactly d spheres, expressed as centerpoints in A and radii in r, and will\n/// find an exact solution only when A is invertible. In particular, none of the\n/// centerpoints can be at the origin, as this would cause a zero column in A.\n///\n/// sphere_intersection_gauss() and sphere_intersection_orth() are both O(d^3),\n/// but sphere_intersection_orth() takes roughly twice as long. Its advantage is\n/// that sphere_intersection_orth() can handle non-invertible matrices A.\n///\n/// The final method, sphere_intersection_opt(), can also find a point close to\n/// all the spheres in the case that they do not intersect.\n/// It first runs sphere_intersection_orth(), and if the spheres intersect it\n/// will return that solution. If they do not intersect, it will run a\n/// Newton-Rhapson method to optimize a least-squares objective to choose the\n/// unique point \"closest\" to all the spheres, in the sense that it minimizes\n/// the sum of the squared Euclidean distances to the sphere boundaries.\n/// The optimization method generally converges in just a few iterations, so\n/// in practice sphere_intersection_opt() is generally not much slower than\n/// sphere_intersection_orth().\n///\n/// Ref: I. D. Coope, \u201cReliable computation of the points of intersection of $n$\n///   spheres in $R^n$,\u201d ANZIAM Journal, vol. 42, no. 0, pp. 461\u2013477, Dec. 2000.\n\n#pragma once\n#ifndef OGT_EMBED_SPHERE_HPP\n#define OGT_EMBED_SPHERE_HPP\n\n#include <ogt/config.hpp>\n#include <vector>\n#include <Eigen/Dense>\n\nnamespace OGT_NAMESPACE {\nnamespace embed {\n\n/// Find the two points where n spheres intersect in R^n by Gaussian\n/// elimination.\n/// center is nxn; its columns are the locations of the sphere centers.\n/// radius is nx1; d_i is the radius of the i'th sphere in center.\n/// 2*eps is the smallest permissible distance between intersection points to\n/// consider them distinct.\n/// If only one intersection point exists, the second vector will have size 0.\n/// If neither intersection point exists, both vectors will have size 0.\n///\n/// Throws std::invalid_argument if the matrix dimensions are incorrect.\n///\n/// @see sphere_intersection_orth(), sphere_intersection_opt()\nstd::vector<Eigen::VectorXd> sphere_intersection_gauss(\n\tconst Eigen::MatrixXd &center, const Eigen::VectorXd& radius, double eps);\n\n/// Find the two points where n spheres intersect in R^n by an orthogonal\n/// transformation. This method is more robust than sphere_intersection_gauss,\n/// but takes up to twice as long.\n///\n/// Throws std::invalid_argument if the matrix dimensions are incorrect.\n///\n/// @see sphere_intersection_gauss(), sphere_intersection_opt()\nstd::vector<Eigen::VectorXd> sphere_intersection_orth(\n\tconst Eigen::MatrixXd &center, const Eigen::VectorXd& radius, double eps);\n\n/// Find points close to n or more spheres in n dimensions. If the spheres\n/// intersect, the interesection points are returned. Otherwise, an optimization\n/// based approach is taken to find a point minimizing the distance to each\n/// sphere.\n///\n/// Throws std::invalid_argument if the matrix dimensions are incorrect.\n/// Throws ogt::EmbedErr if the embedding fails.\n///\n/// @see sphere_intersection_gauss(), sphere_intersection_orth()\nstd::vector<Eigen::VectorXd> sphere_intersection_opt(\n\tconst Eigen::MatrixXd &center, const Eigen::VectorXd& radius, double eps,\n\tdouble min_delta, size_t max_iter, bool verbose);\n\n/// Find a point within a certain margin of n or more spheres in n dimensions.\n/// If the spheres intersect, an interesection point is returned.\n/// Otherwise, a point is found to minimize the distance to each spherical\n/// shell, defined as points with distances radius +/- margin of the center.\n///\n/// Throws std::invalid_argument if the matrix dimensions are incorrect.\n/// Throws ogt::EmbedErr if the embedding fails.\n///\n/// @see sphere_intersection_gauss(), sphere_intersection_orth()\nstd::vector<Eigen::VectorXd> sphere_intersection_margin(\n\tconst Eigen::MatrixXd &center, const Eigen::VectorXd& radius,\n\tconst Eigen::VectorXd& margin, double eps,\n\tdouble min_delta, size_t max_iter, bool verbose);\n\n} // end namespace embed\n} // end namespace OGT_NAMESPACE\n#endif /* OGT_EMBED_SPHERE_HPP */\n", "meta": {"hexsha": "cecacfe109bd3abc3257c546e224dd2037fbc910", "size": 4575, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ogt/embed/sphere.hpp", "max_stars_repo_name": "jesand/lloe", "max_stars_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T21:31:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T09:23:04.000Z", "max_issues_repo_path": "include/ogt/embed/sphere.hpp", "max_issues_repo_name": "jesand/lloe", "max_issues_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ogt/embed/sphere.hpp", "max_forks_repo_name": "jesand/lloe", "max_forks_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T21:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-27T20:57:26.000Z", "avg_line_length": 47.1649484536, "max_line_length": 80, "alphanum_fraction": 0.7558469945, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6404627650462356}}
{"text": "#ifndef SignalProcessing_hpp\n#define SignalProcessing_hpp\n\n#include <QAlgorithm.hpp>\n#include <TSpectrum.h>\n#include <TMath.h>\n#include <alglib/fasttransforms.h>\n#include <armadillo>\n\nnamespace UMF {\n\tclass ReduceChannels : public QAlgorithm {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\tpublic:\n\t\tenum channels{\n\t\t\tinterleaved, \t// C1,C2,C3,C1,C2,C3,...\n\t\t\tseparated\t\t// C1,...,C1,C2,...,C2,C3,...,C3\n\t\t};\n\t\tQ_ENUM(channels)\n\t\t\n\t\tenum operation{\n\t\t\taverage\n\t\t};\n\t\tQ_ENUM(operation)\n\t\t\n\t\tQA_INPUT(QVector<double>, Signal)\n\t\tQA_PARAMETER(int, ChannelsArrangement, interleaved)\n\t\tQA_PARAMETER(int, Operation, average)\n\t\tQA_PARAMETER(int, NumberChannels, 2)\n\t\tQA_OUTPUT(QVector<double>, Signal)\n\t\t\n\t\tQA_CTOR_INHERIT\n\t\tQA_IMPL_CREATE(ReduceChannels)\n\t\t\n\tpublic:\n\t\tvoid run();\n\t};\n\t\n\tclass Windowing : public QAlgorithm {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\tpublic:\n\t\tenum function{\n\t\t\thann\n\t\t};\n\t\tQ_ENUM(function)\n\t\t\n\t\tQA_INPUT(QVector<double>, Signal)\n\t\tQA_PARAMETER(int, Type, hann)\n\t\tQA_PARAMETER(int, Length, 5)\n\t\tQA_OUTPUT(QVector<double>, Signal)\n\t\t\n\t\tQA_CTOR_INHERIT\n\t\tQA_IMPL_CREATE(Windowing)\n\t\t\n\tprivate:\n\t\tQVector<double> window;\n\t\t\n\tpublic:\n\t\tvoid run();\n\t\t\n\t\tvoid init();\n\t};\n\t\n\tclass ArrayPad : public QAlgorithm {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\tpublic:\n\t\tenum border_type {\n\t\t\tconstant,\t\t// iiiiii|abcdefgh|iiiiiii with some specified i\n\t\t\treplicate,\t\t// aaaaaa|abcdefgh|hhhhhhh\n\t\t\treflect,\t\t// fedcba|abcdefgh|hgfedcb\n\t\t\twrap,\t\t\t// cdefgh|abcdefgh|abcdefg\n\t\t\treflect_101\t\t// gfedcb|abcdefgh|gfedcba\n\t\t};\n\t\tQ_ENUM(border_type)\n\t\t\n\t\t/** Radius of the gaussian filter. */\n\t\tQA_PARAMETER(int, Radius, 5)\n\t\t/** Out of border interpolation mode. */\n\t\tQA_PARAMETER(int, BorderType, constant)\n\t\t/** Vector to be filtered. */\n\t\tQA_INPUT(QVector<double>, Signal)\n\t\t/** Filtered vector. */\n\t\tQA_OUTPUT(QVector<double>, Signal)\n\t\t\n\t\tQA_CTOR_INHERIT\n\t\tQA_IMPL_CREATE(ArrayPad)\n\t\t\n\tpublic:\n\t\tvoid run();\n\t\t\n\t\tvoid init();\n\t\t\n\t\t/** Compute interpolation coordinates.\n\t\t The function computes and returns the coordinate of a donor pixel corresponding\n\t\t to the specified extrapolated pixel when using the specified extrapolation border mode.\n\t\t \n\t\t If the border type is constant, then -1 is returned.\n\t\t \n\t\t There is no check whether the final result is out of bounds: it may happen\n\t\t that a pos too much out of bounds leads to negative returning value.\n\t\t */\n\t\tint borderInterpolate(const int& pos,\n\t\t\t\t\t\t\t  const int& len,\n\t\t\t\t\t\t\t  const border_type& bd);\n\t};\n\t\n\tclass GaussianFilter : public QAlgorithm {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\t\t/** Radius of the gaussian filter. */\n\t\tQA_PARAMETER(int, Radius, 5)\n\t\t/** Out of border interpolation mode. */\n\t\tQA_PARAMETER(int, BorderType, ArrayPad::constant)\n\t\t/** Vector to be filtered. */\n\t\tQA_INPUT(QVector<double>, Signal)\n\t\t/** Filtered vector. */\n\t\tQA_OUTPUT(QVector<double>, Signal)\n\t\t\n\t\tQA_CTOR_INHERIT\n\t\tQA_IMPL_CREATE(GaussianFilter)\n\t\t\n\tpublic:\n\t\tvoid init();\n\t\t\n\t\tvoid run();\n\t\t\n\tprivate:\n\t\tarma::vec kernel;\n\t};\n\t\n\tclass SpectrumMagnitude : public QAlgorithm {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\t\tQA_INPUT(QVector<double>, Signal)\n\t\tQA_OUTPUT(QVector<double>, Signal)\n\t\t\n\t\tQA_CTOR_INHERIT\n\t\tQA_IMPL_CREATE(SpectrumMagnitude)\n\t\t\n\tpublic:\n\t\tvoid run();\n\t};\n\t\n\tclass SpectrumRemoveBackground : public QAlgorithm {\n\t\t\n\t\tQ_OBJECT\n\t\t\n\tpublic:\n\t\tenum filterOrder {\n\t\t\tkBackOrder2 =0,\n\t\t\tkBackOrder4 =1,\n\t\t\tkBackOrder6 =2,\n\t\t\tkBackOrder8 =3\n\t\t};\n\t\tenum windowDirection {\n\t\t\tkBackIncreasingWindow =0,\n\t\t\tkBackDecreasingWindow =1\n\t\t};\n\t\tenum smoothingWindow {\n\t\t\tkBackSmoothing3 =3,\n\t\t\tkBackSmoothing5 =5,\n\t\t\tkBackSmoothing7 =7,\n\t\t\tkBackSmoothing9 =9,\n\t\t\tkBackSmoothing11 =11,\n\t\t\tkBackSmoothing13 =13,\n\t\t\tkBackSmoothing15 =15\n\t\t};\n\t\tQ_ENUM(filterOrder)\n\t\tQ_ENUM(windowDirection)\n\t\tQ_ENUM(smoothingWindow)\n\t\t\n\t\tQA_INPUT(QVector<double>, Signal)\n\t\tQA_PARAMETER(int, NumberIterations, 6)\n\t\tQA_PARAMETER(int, Direction, TSpectrum::kBackIncreasingWindow)\n\t\tQA_PARAMETER(int, FilterOrder, TSpectrum::kBackOrder2)\n\t\tQA_PARAMETER(bool, Smoothing, kFALSE)\n\t\tQA_PARAMETER(int, SmoothWindow, TSpectrum::kBackSmoothing3)\n\t\tQA_PARAMETER(bool, Compton, kFALSE)\n\t\tQA_OUTPUT(QVector<double>, Signal)\n\t\t\n\t\tQA_CTOR_INHERIT\n\t\tQA_IMPL_CREATE(SpectrumRemoveBackground)\n\t\t\n\tpublic:\n\t\tvoid run();\n\t\t\n\t\tvoid init();\n\t};\n}\n\n#endif /* SignalProcessing_hpp */\n", "meta": {"hexsha": "93d1f617b25531854d7ff6287080e4528542a87a", "size": 4192, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Headers/UMF/SignalProcessing.hpp", "max_stars_repo_name": "DottD/audioRec", "max_stars_repo_head_hexsha": "74c316974000fc7c9048f076de01c40ede85836c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Headers/UMF/SignalProcessing.hpp", "max_issues_repo_name": "DottD/audioRec", "max_issues_repo_head_hexsha": "74c316974000fc7c9048f076de01c40ede85836c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Headers/UMF/SignalProcessing.hpp", "max_forks_repo_name": "DottD/audioRec", "max_forks_repo_head_hexsha": "74c316974000fc7c9048f076de01c40ede85836c", "max_forks_repo_licenses": ["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.0653266332, "max_line_length": 90, "alphanum_fraction": 0.6999045802, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6404627399804719}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_BARYCOORDS_HPP\n#define MCL_BARYCOORDS_HPP 1\n\n#include <Eigen/Core>\n\nnamespace mcl\n{\n\n// vertex-edge barycoords, allows negative barys\ntemplate <typename T, int DIM>\nstatic inline Eigen::Matrix<T,2,1> point_edge_barys(\n\t\tconst Eigen::Matrix<T,DIM,1> &p,\n\t\tconst Eigen::Matrix<T,DIM,1> &p0,\n\t\tconst Eigen::Matrix<T,DIM,1> &p1)\n{\n\tEigen::Matrix<T,DIM,1> v0 = p1 - p0;\n\tEigen::Matrix<T,DIM,1> v2 = p - p0;\n\tT d00 = v0.dot(v0);\n\tif (d00 <= T(0))\n\t{\n\t\treturn Eigen::Matrix<T,2,1>(-1,0);\n\t}\n\tT d20 = v2.dot(v0);\n\tT invDenom = 1.0 / d00;\n\tEigen::Matrix<T,2,1> r;\n\tr[0] = (d00 - d20)*invDenom;\n\tr[1] = 1.0 - r[0];\n\treturn r;\n}\n\ntemplate <typename T, int DIM> // Compute barycentric coords for a point on a triangle\nstatic inline Eigen::Matrix<T,3,1> point_triangle_barys(\n\tconst Eigen::Matrix<T,DIM,1> &p,\n\tconst Eigen::Matrix<T,DIM,1> &p0,\n\tconst Eigen::Matrix<T,DIM,1> &p1,\n\tconst Eigen::Matrix<T,DIM,1> &p2)\n{\n\tEigen::Matrix<T,DIM,1> v0 = p1 - p0, v1 = p2 - p0, v2 = p - p0;\n\tT d00 = v0.dot(v0);\n\tT d01 = v0.dot(v1);\n\tT d11 = v1.dot(v1);\n\tT d20 = v2.dot(v0);\n\tT d21 = v2.dot(v1);\n\tT invDenom = 1.0 / (d00 * d11 - d01 * d01);\n\tEigen::Matrix<T,3,1> r;\n\tr[1] = (d11 * d20 - d01 * d21) * invDenom;\n\tr[2] = (d00 * d21 - d01 * d20) * invDenom;\n\tr[0] = 1.0 - r[1] - r[2];\n\treturn r;\n}\n\ntemplate <typename T> // Compute barycentric coords for a point in a tet (3D)\nstatic inline Eigen::Matrix<T,4,1> point_tet_barys(\n\tconst Eigen::Matrix<T,3,1> &p,\n\tconst Eigen::Matrix<T,3,1> &a,\n\tconst Eigen::Matrix<T,3,1> &b,\n\tconst Eigen::Matrix<T,3,1> &c,\n\tconst Eigen::Matrix<T,3,1> &d)\n{\t\t\n\tauto scalar_triple_product = [](\n\t\tconst Eigen::Matrix<T,3,1> &u,\n\t\tconst Eigen::Matrix<T,3,1> &v,\n\t\tconst Eigen::Matrix<T,3,1> &w ){\n\t\treturn u.dot(v.cross(w));\n\t};\n\tEigen::Matrix<T,3,1> vap = p - a;\n\tEigen::Matrix<T,3,1> vbp = p - b;\n\tEigen::Matrix<T,3,1> vab = b - a;\n\tEigen::Matrix<T,3,1> vac = c - a;\n\tEigen::Matrix<T,3,1> vad = d - a;\n\tEigen::Matrix<T,3,1> vbc = c - b;\n\tEigen::Matrix<T,3,1> vbd = d - b;\n\tT va6 = scalar_triple_product(vbp, vbd, vbc);\n\tT vb6 = scalar_triple_product(vap, vac, vad);\n\tT vc6 = scalar_triple_product(vap, vad, vab);\n\tT vd6 = scalar_triple_product(vap, vab, vac);\n\tT v6 = 1.0 / scalar_triple_product(vab, vac, vad);\n\treturn Eigen::Matrix<T,4,1>(va6*v6, vb6*v6, vc6*v6, vd6*v6);\n}\n\n} // end namespace mcl\n\n#endif\n", "meta": {"hexsha": "abbe7b0bb95d6e0c82cb5472944bae834e8523f4", "size": 2397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/Barycoords.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/Barycoords.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/Barycoords.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5517241379, "max_line_length": 86, "alphanum_fraction": 0.6287025448, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6404528704198481}}
{"text": "#include <boost/math/distribution.hpp>\n\nReal blackScholesMertonFwd(const Real& fwd, const Real& strike, const Volatility& vol,\n\t\t\t\t\t\t  const Rate& rf, const Rate& rf, const Time& tau, const Integer& phi)\n{\n\tboost::math::normal_distribution<> d(0.0, 1.0);\n\tReal dp, dm, stdDev, res, domDf, forDf;\n\t\n\tforDf = std::exp(-rf*tau);\n\tdomDf = std::exp(-rd*tau);\n\tstdDev = vol*std::sqrt(tau);\n\t\n\tdp = (std::log(fwd/strike) + 0.5 * stdDev * stdDev) / stdDev;\n\tdp = (std::log(fwd/strike) - 0.5 * stdDev * stdDev) / stdDev;\n\t\n\tres = phi*domDf*(fwd*cdf(d, phi*dp) - strike* cdf(d, phi*dm));\n\t\n\treturn res;\n}", "meta": {"hexsha": "ac3388acac67642532b77a813efaa36b8a22299d", "size": 594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/BSMobject.hpp", "max_stars_repo_name": "FinancialEngineerLab/fineSABRModel", "max_stars_repo_head_hexsha": "369da72be884a1a4a1dabe0392f5357f5d62891e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BSMobject.hpp", "max_issues_repo_name": "FinancialEngineerLab/fineSABRModel", "max_issues_repo_head_hexsha": "369da72be884a1a4a1dabe0392f5357f5d62891e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BSMobject.hpp", "max_forks_repo_name": "FinancialEngineerLab/fineSABRModel", "max_forks_repo_head_hexsha": "369da72be884a1a4a1dabe0392f5357f5d62891e", "max_forks_repo_licenses": ["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.2631578947, "max_line_length": 86, "alphanum_fraction": 0.6430976431, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9525741227833249, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.6404457785651306}}
{"text": "#include <NTL/mat_poly_ZZ_p.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\nstatic\nvoid HessCharPoly(ZZ_pX& g, const ZZ_pX& a, const ZZ_pX& f)\n{\n   long n = deg(f);\n   if (n <= 0 || deg(a) >= n)\n      Error(\"HessCharPoly: bad args\");\n\n   mat_ZZ_p M;\n   M.SetDims(n, n);\n\n   long i, j;\n\n   ZZ_pX t;\n   t = a;\n\n   for (i = 0; i < n; i++) {\n      for (j = 0; j < n; j++) \n         M[i][j] = coeff(t, j);\n\n      if (i < n-1) \n         MulByXMod(t, t, f);\n   }\n\n   CharPoly(g, M);\n}\n\nvoid CharPolyMod(ZZ_pX& g, const ZZ_pX& a, const ZZ_pX& ff)\n{\n   ZZ_pX f = ff;\n   MakeMonic(f);\n   long n = deg(f);\n\n   if (n <= 0 || deg(a) >= n) \n      Error(\"CharPoly: bad args\");\n\n   if (IsZero(a)) {\n      clear(g);\n      SetCoeff(g, n);\n      return;\n   }\n\n   if (n > 25) {\n      ZZ_pX h;\n      MinPolyMod(h, a, f);\n      if (deg(h) == n) {\n         g = h;\n         return;\n      }\n   }\n\n   if (ZZ_p::modulus() < n+1) {\n      HessCharPoly(g, a, f);\n      return;\n   }\n\n   vec_ZZ_p u(INIT_SIZE, n+1), v(INIT_SIZE, n+1);\n\n   ZZ_pX h, h1;\n   negate(h, a);\n   long i;\n\n   for (i = 0; i <= n; i++) {\n      u[i] = i;\n      add(h1, h, u[i]);\n      resultant(v[i], f, h1);\n   }\n\n   interpolate(g, u, v);\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "b80d1d30693f2fd01c57e43a4fe1a7f32f3bff2f", "size": 1190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/ZZ_pXCharPoly.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T20:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:52:14.000Z", "max_issues_repo_path": "RUNETag/WinNTL/src/ZZ_pXCharPoly.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/src/ZZ_pXCharPoly.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 15.2564102564, "max_line_length": 59, "alphanum_fraction": 0.4605042017, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6404166883012633}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n// This test is written by Jan Bos to test the convergence of complex linear systems\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\ntemplate <typename Matrix>\nvoid fill(Matrix& m)\n{\n  double s=19, u=21, p=16, e=5, r=18, l =12;\n\n  std::complex<double> delta(2,1);\n  mtl::mat::inserter<Matrix> sm(m);\n  // set diagonal\n  sm(0,0) << s;\n  sm(1,1) << u;\n  sm(2,2) << p;\n  sm(3,3) << e;\n  sm(4,4) << r;\n  // below diagonal\n  sm(1,0) << l+delta;\n  sm(4,0) << l;\n  sm(2,1) << l;\n  sm(4,1) << l+delta;\n  // above diagonal\n  sm(0,2) << u;\n  sm(0,3) << u+delta;\n  //sm(3,4) << u;\n  sm(3,4) << u + delta;\n}\n\nint main()\n{\n  // For a more realistic example set size to 1000 or larger\n  const int N = 5;\n\n  typedef mtl::compressed2D<std::complex<double> > matrix_type;\n  matrix_type                   A(N, N);\n\n  itl::pc::identity<matrix_type>     P(A);\n  mtl::dense_vector<std::complex<double> > b(N, std::complex<double>(1,1)), x(N);\n\n  fill(A);\n  x= 0;\n\n  itl::cyclic_iteration<double> iter(b, N, 1.e-6, 0.0, 5);\n  bicgstab(A, x, b, P, iter);\n \n  return 0;\n}\n", "meta": {"hexsha": "d822537c503f0ae610f9030c60d4be457c01e76c", "size": 1520, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/bicgstab_complex_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/itl/test/bicgstab_complex_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/itl/test/bicgstab_complex_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 24.5161290323, "max_line_length": 94, "alphanum_fraction": 0.6144736842, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6404072568111975}}
{"text": "// system includes -----------------------------------------------\n#include <boost/math/constants/constants.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n// own includes --------------------------------------------------\n#include <base/eigen2hdf.hpp>\n#include <base/init.hpp>\n#include <base/timer.hpp>\n#include <fft/fft2.hpp>\n#include <fft/fft2_r2c.hpp>\n#include <fft/planner.hpp>\n#include <ridgelet/ridgelet_frame.hpp>\n#include <ridgelet/rt.hpp>\n\nusing namespace std;\n\nconst char* fname = \"test_rt_random.h5\";\n\ntypedef RT<std::complex<double>, RidgeletFrame, FFTr2c<PlannerR2C> > RT_t;\n\ntypedef RT_t::array_t array_t;\ntypedef RT_t::complex_array_t complex_array_t;\ntypedef RT_t::rt_coeff_t rt_coeff_t;\n\nvoid dump_frc(const std::vector<rt_coeff_t>& f_rc, const RidgeletFrame& rt)\n{\n  const char* fname = \"f_rc_random.h5\";\n  hid_t file = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  for (unsigned int i = 0; i < f_rc.size(); ++i) {\n    stringstream ss;\n    ss << rt.lambdas()[i];\n    string slam = ss.str();\n    eigen2hdf::save(file, slam, f_rc[i]);\n  }\n  H5Fclose(file);\n  cout << \"Written f(lambda, t) to \" << fname << \"\\n\";\n}\n\nint main(int argc, char* argv[])\n{\n  SOURCE_INFO();\n\n  namespace po = boost::program_options;\n\n  unsigned int Jx, Jy, rho_x, rho_y, nrep;\n\n  po::options_description options(\"options\");\n  options.add_options()(\"help\", \"produce help message\")\n      (\"Jx,i\", po::value<unsigned int>(&Jx)->default_value(6), \"Jx\")\n      (\"Jy,j\", po::value<unsigned int>(&Jy)->default_value(6), \"Jy\")\n      (\"rx,x\", po::value<unsigned int>(&rho_x)->default_value(1), \"rho_x\")\n      (\"ry,y\", po::value<unsigned int>(&rho_y)->default_value(1), \"rho_x\")\n      (\"nrep,n\", po::value<unsigned int>(&nrep)->default_value(1), \"timings/nrep\")\n      (\"input,f\", po::value<std::string>(), \"input file\")\n      (\"measure\", \"use FFTW_MEASURE\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << options << \"\\n\";\n    return 0;\n  }\n\n  cout << setw(20) << \"Jx\"\n       << \": \" << Jx << \"\\n\"\n       << setw(20) << \"Jy\"\n       << \": \" << Jy << \"\\n\"\n       << setw(20) << \"rho_x\"\n       << \": \" << rho_x << \"\\n\"\n       << setw(20) << \"rho_y\"\n       << \": \" << rho_y << \"\\n\";\n\n  RDTSCTimer timer;\n\n  timer.start();\n  RidgeletFrame frame(Jx, Jy, rho_x, rho_y);\n  auto t_create_frame = timer.stop();\n  cout << \"TIMINGS::create_frame: \" << t_create_frame / 1e9 << \"\\n\";\n\n  const unsigned int ncols = frame.Nx();  // #cols\n  const unsigned int nrows = frame.Ny();  // #rows\n  cout << setw(20) << \"Ny\"\n       << \":\" << nrows << \"\\n\";\n  cout << setw(20) << \"Nx\"\n       << \":\" << ncols << \"\\n\";\n\n  RT_t rt(frame);\n  array_t F(nrows, ncols);\n  array_t Fo(nrows, ncols);\n\n  if (!vm.count(\"input\")) {\n    cout << \"generating random input\"\n         << \"\\n\";\n    F.setRandom();\n    F *= nrows * ncols;\n  } else {\n    std::string fname = vm[\"input\"].as<std::string>();\n    cout << \"read input from file: \" << fname << \"\\n\";\n    hid_t lfile = H5Fopen(fname.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n    eigen2hdf::load(lfile, \"R\", F);\n    // matlab is column major ...\n    F = F.transpose();\n    Fo = F;\n  }\n  typename RT_t::fft_t fft;\n  timer.start();\n  if (vm.count(\"measure\")) {\n    cout << \"using FFTW_MEASURE\"\n         << \"\\n\";\n    init_fftw(fft, FFTW_MEASURE, frame);\n  } else {\n    cout << \"using FFTW_ESTIMATE\"\n         << \"\\n\";\n    init_fftw(fft, FFTW_ESTIMATE, frame);\n  }\n\n  timer.print(cout, timer.stop(), \"FFTW plans\");\n\n  complex_array_t Fh(F.rows(), F.cols());\n  fft.ft(Fh, F);\n  std::vector<rt_coeff_t> rt_coeffs(frame.size());\n  timer.start();\n  for (unsigned int i = 0; i < nrep; ++i) {\n    rt.rt(rt_coeffs, Fh);\n  }\n  auto time_rt = timer.stop() / nrep;\n  timer.print(cout, time_rt, \"rt.rt\");\n  dump_frc(rt_coeffs, frame);\n\n  // -------------------- Inverse transform --------------------\n  complex_array_t Fh2(nrows, ncols);\n  timer.start();\n  for (unsigned int i = 0; i < nrep; ++i) {\n    rt.irt(Fh2, rt_coeffs);\n  }\n  auto time_irt = timer.stop() / nrep;\n  timer.print(cout, time_irt, \"rt.irt\");\n  hid_t file = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  eigen2hdf::save(file, \"Fh\", Fh);\n  eigen2hdf::save(file, \"R\", Fo);\n  eigen2hdf::save(file, \"Fh2\", Fh2);\n  H5Fclose(file);\n  cout << \"written results to \" << fname << \"\\n\";\n\n  complex_array_t diff = (ftcut(Fh2, nrows / 2, ncols / 2) - ftcut(Fh, nrows / 2, ncols / 2));\n  cout << \"avg diff (ft): \" << diff.abs().sum() / (nrows / 2 * ncols / 2) << \"\\n\";\n\n  array_t Fr(nrows / 2, ncols / 2);\n  array_t Fr2(nrows / 2, ncols / 2);\n\n  cout << \"nrows/2 * ncols/2: \" << (nrows / 2 * ncols / 2) << \"\\n\";\n\n  fft.ift(Fr, ftcut(Fh, nrows / 2, ncols / 2));\n  fft.ift(Fr2, ftcut(Fh2, nrows / 2, ncols / 2));\n\n  array_t diffr = Fr - Fr2;\n  cout << \"avg diff (real):\" << diffr.abs().sum() / (nrows / 2 * ncols / 2) << \"\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "07dbc76d8a4284001ddcbc6e76d07b4c151d1015", "size": 4914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main_test_rt_random.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "test/main_test_rt_random.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/main_test_rt_random.cpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 30.3333333333, "max_line_length": 94, "alphanum_fraction": 0.5761090761, "num_tokens": 1571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782094, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6404072470658783}}
{"text": "/*******************************************************************************\n * Copyright (c) 2014, 2015  IBM Corporation and others\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *******************************************************************************/\n\n#ifndef MathUtils_hpp\n#define MathUtils_hpp\n\n#include <cmath>\n#include <boost/math/distributions/students_t.hpp>\n\nclass DirectionalStatistics{\n    double mCircularMean;\n    double mCircularVariance;\n    \npublic:\n    DirectionalStatistics(double theta, double v){\n        this->mCircularMean = theta;\n        this->mCircularVariance = v;\n    }\n    double circularMean() const{\n        return mCircularMean;\n    }\n    double circularVariance() const{\n        return mCircularVariance;\n    }\n};\n\nclass NormalParameter{\nprotected:\n    double mMean;\n    double mStdev;\npublic:\n    NormalParameter() = default;\n    NormalParameter(double mean, double stdev){\n        this->mMean = mean;\n        this->mStdev = stdev;\n    }\n    ~NormalParameter() = default;\n    double mean() const{return mMean;}\n    double stdev() const{return mStdev;}\n};\n\nusing WrappedNormalParameter = NormalParameter;\n\nclass MathUtils{\n    \npublic:\n    static double probaNormal(double x, double mu, double sigma){\n        return 1.0/(std::sqrt(2.0*M_PI)*sigma)*std::exp(-std::pow(x-mu, 2)/(2*sigma*sigma));\n    }\n    \n    static double logProbaNormal(double x, double mu, double sigma){\n        return -1.0/2.0*std::log(2*M_PI) -1.0/2.0*std::log(sigma*sigma)\n        -std::pow(x-mu, 2)/(2.0*sigma*sigma);\n    }\n    \n    static std::function<double(double,double,double)> logProbatDistFunc(double nu) {\n        boost::math::students_t dist(nu);\n        return [=] (double x, double mu, double sigma){\n            double z = (x - mu) / sigma;\n            return std::log(boost::math::pdf(dist, z));\n        };\n    }\n    \n    static double mahalanobisDistance(double x, double mu, double sigma){\n        return std::pow(x-mu, 2)/(sigma*sigma);\n    }\n    \n    static double quantileChiSquaredDistribution(int degreeOfFreedom, double cumulativeDensity);\n    \n    static double normalizeOrientaion(double orientation){\n        double x = std::cos(orientation);\n        double y = std::sin(orientation);\n        return std::atan2(y,x);\n    }\n    \n    static DirectionalStatistics computeDirectionalStatistics(std::vector<double> orientations);\n    static WrappedNormalParameter computeWrappedNormalParameters(const std::vector<double>& orientations);\n};\n#endif /* MathUtils_hpp */\n", "meta": {"hexsha": "c6fce540fc122baabd646876d70aec350959174a", "size": 3535, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ble-cpp/src/utils/MathUtils.hpp", "max_stars_repo_name": "harsh-agarwal/blelocpp", "max_stars_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-06-13T20:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T17:29:32.000Z", "max_issues_repo_path": "ble-cpp/src/utils/MathUtils.hpp", "max_issues_repo_name": "harsh-agarwal/blelocpp", "max_issues_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-03-14T07:00:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-07T18:20:15.000Z", "max_forks_repo_path": "ble-cpp/src/utils/MathUtils.hpp", "max_forks_repo_name": "harsh-agarwal/blelocpp", "max_forks_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-02-03T07:41:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T10:03:48.000Z", "avg_line_length": 35.7070707071, "max_line_length": 106, "alphanum_fraction": 0.6625176803, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156295, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6404072468640436}}
{"text": "#include \"fgpg/geometrics.h\"\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <pcl/common/intersections.h>\n#include <vector>\n\n/**\n p0, u: line\n plane: plane\n @see http://geomalgorithms.com/a05-_intersect-1.html\n*/\nbool calcLinePlaneIntersection(\n  const TrianglePlaneData& plane, \n  const Eigen::Ref<const Eigen::Vector3d>&  p0, \n  const Eigen::Ref<const Eigen::Vector3d>&  u, ///< norm of point\n  Eigen::Ref<Eigen::Vector3d> p ///< result\n  )\n{\n  auto n = plane.normal;\n  if(n.dot(u) == 0.0)\n  {\n    return false;\n  }\n  Eigen::Vector3d w = p0 - plane.points[0];\n  double s = -n.dot(w) / n.dot(u);\n\n  // inverse direction\n  if(s<0)\n    return false;\n\n  p = p0 + s*u;\n\n  return true;\n}\n\n/**\n p0, u: line\n plane: plane\n @see http://geomalgorithms.com/a05-_intersect-1.html\n*/\ndouble calcLinePlaneDistance(\n  const TrianglePlaneData& plane, \n  const Eigen::Ref<const Eigen::Vector3d>&  p0, \n  const Eigen::Ref<const Eigen::Vector3d>&  u ///< norm of point\n  )\n{\n  auto n = plane.normal;\n  if(n.dot(u) == 0.0)\n  {\n    return false;\n  }\n  Eigen::Vector3d w = p0 - plane.points[0];\n  double s = -n.dot(w) / n.dot(u);\n  return s;\n}\n\n/// @see: http://blackpawn.com/texts/pointinpoly/default.html\nbool sameSide(const Eigen::Ref<const Eigen::Vector3d>&  p1,const Eigen::Ref<const Eigen::Vector3d>& p2, const Eigen::Ref<const Eigen::Vector3d>& a, const Eigen::Ref<const Eigen::Vector3d>& b)\n{\n  auto cp1 = (b-a).cross(p1-a);\n  auto cp2 = (b-a).cross(p2-a);\n  if (cp1.dot(cp2) >= 0.0) return true;\n  \n  return false;\n}\n\nbool pointInTriangle(const Eigen::Ref<const Eigen::Vector3d>& p, const TrianglePlaneData& plane)\n{\n  \n  auto a = plane.points[0];\n  auto b = plane.points[1];\n  auto c = plane.points[2];\n  \n  if(abs(plane.normal.dot(p-a)) + abs(plane.normal.dot(p-b)) + abs(plane.normal.dot(p-c)) > 1e-6) // not on the plane\n  {\n    return false;\n  }\n  // Compute vectors        \n  auto v0 = c - a;\n  auto v1 = b - a;\n  auto v2 = p - a;\n\n  // Compute dot products\n  double dot00 = v0.dot(v0);\n  double dot01 = v0.dot(v1);\n  double dot02 = v0.dot(v2);\n  double dot11 = v1.dot(v1);\n  double dot12 = v1.dot(v2);\n\n  // Compute barycentric coordinates\n  double inv_denom = 1 / (dot00 * dot11 - dot01 * dot01);\n  double u = (dot11 * dot02 - dot01 * dot12) * inv_denom;\n  double v = (dot00 * dot12 - dot01 * dot02) * inv_denom;\n\n  // Check if point is in triangle\n  return (u >= 0) && (v >= 0) && (u + v < 1);\n}\n\nEigen::Vector3d orthogonalVector3d(const Eigen::Ref<const Eigen::Vector3d>& n, const Eigen::Ref<const Eigen::Vector3d>& v0, double theta)\n{\n  Eigen::Vector3d v;\n  v.setZero();\n\n  v = Eigen::AngleAxisd(theta, n).matrix() * v0;\n  return v;\n}\n\n\nEigen::Vector3d getOrthogonalVector(const Eigen::Ref<const Eigen::Vector3d>& n)\n{\n  Eigen::Vector3d v;\n\n  int max_index = 0;\n  int new_index[3];\n  double max = 0;\n  for(int i=0; i<3; i++)\n  {\n    if(abs(n(i)) > max)\n    {\n      max = abs(n(i));\n      max_index = i;\n    }\n  }\n\n  int loc = 0;\n  new_index[2] = max_index;\n  for(int i=0; i<3; i++)\n  {\n    if(i == max_index) continue;\n\n    new_index[loc] = i;\n    loc++;\n  }\n\n  v(new_index[0]) = 1;\n  v(new_index[1]) = 1;\n  v(new_index[2]) = -(n(new_index[0])+n(new_index[1])) / n(new_index[2]);\n\n  v = v.normalized();\n\n  return v;\n}\n\n", "meta": {"hexsha": "e88ac445e0bb00c4656a765ab26f29d06a10f7fd", "size": 3224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometrics.cpp", "max_stars_repo_name": "jiyeongbaek/fgpg", "max_stars_repo_head_hexsha": "c2ac3badd683c3bf73cac3acc408f19d9b132c85", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-02-13T03:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-15T11:09:30.000Z", "max_issues_repo_path": "src/geometrics.cpp", "max_issues_repo_name": "jiyeongbaek/fgpg", "max_issues_repo_head_hexsha": "c2ac3badd683c3bf73cac3acc408f19d9b132c85", "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/geometrics.cpp", "max_forks_repo_name": "jiyeongbaek/fgpg", "max_forks_repo_head_hexsha": "c2ac3badd683c3bf73cac3acc408f19d9b132c85", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-12T05:52:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-27T09:21:19.000Z", "avg_line_length": 22.2344827586, "max_line_length": 191, "alphanum_fraction": 0.6172456576, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6404072466622083}}
{"text": "#define BOOST_TEST_MODULE Gpufit\n\n#define PI 3.1415926535897f\n\n#include \"Gpufit/gpufit.h\"\n\n#include <boost/test/included/unit_test.hpp>\n\n#include <array>\n\ntemplate<std::size_t SIZE>\nvoid generate_gauss_2d_rotated(std::array< float, SIZE>& values)\n{\n    int const size_x = int(std::sqrt(SIZE));\n    int const size_y = size_x;\n\n    float const a = 10.f;\n    float const x0 = (float(size_x) - 1.f) / 2.f;\n    float const y0 = (float(size_y) - 1.f) / 2.f;\n    float const sx = 0.4f;\n    float const sy = 0.5f;\n    float const b = 1.f;\n    float const r = PI / 16.f;\n\n    for (int point_index_y = 0; point_index_y < size_y; point_index_y++)\n    {\n        for (int point_index_x = 0; point_index_x < size_x; point_index_x++)\n        {\n            int const point_index = point_index_y * size_x + point_index_x;\n            float const arga = ((point_index_x - x0) * cosf(r)) - ((point_index_y - y0) * sinf(r));\n            float const argb = ((point_index_x - x0) * sinf(r)) + ((point_index_y - y0) * cosf(r));\n            float const ex = exp((-0.5f) * (((arga / sx) * (arga / sx)) + ((argb / sy) * (argb / sy))));\n            values[point_index] = a * ex + b;\n        }\n    }\n}\n\nBOOST_AUTO_TEST_CASE( Gauss_Fit_2D_Rotated )\n{\n    std::size_t const n_fits{ 1 } ;\n    std::size_t const n_points{ 64 } ;\n    std::array< float, n_points > data{};\n    generate_gauss_2d_rotated(data);\n    std::array< float, n_points > weights{};\n    std::fill(weights.begin(), weights.end(), 1.f);\n    std::array< float, 7 > initial_parameters{ { 8.f, 3.4f, 3.6f, 0.4f, 0.5f, 2.f, 0.f } };\n    float tolerance{ 0.001f };\n    int max_n_iterations{ 10 };\n    std::array< int, 7 > parameters_to_fit{ { 1, 1, 1, 1, 1, 1, 1 } };\n    std::array< float, 7 > output_parameters;\n    int output_states;\n    float output_chi_square;\n    int output_n_iterations;\n\n    int const status\n            = gpufit\n            (\n                n_fits,\n                n_points,\n                data.data(),\n                weights.data(),\n                GAUSS_2D_ROTATED,\n                initial_parameters.data(),\n                tolerance,\n                max_n_iterations,\n                parameters_to_fit.data(),\n                LSE,\n                0,\n                0,\n                output_parameters.data(),\n                &output_states,\n                &output_chi_square,\n                &output_n_iterations\n            ) ;\n\n    BOOST_CHECK( status == 0 ) ;\n}\n", "meta": {"hexsha": "55cd6821920c507080def75b39e1977d4e45acf2", "size": 2432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gpufit/tests/Gauss_Fit_2D_Rotated.cpp", "max_stars_repo_name": "yongdengzhang/Gpufit", "max_stars_repo_head_hexsha": "6e719585badff1c40488a1439fa04da1792e41b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Gpufit/tests/Gauss_Fit_2D_Rotated.cpp", "max_issues_repo_name": "yongdengzhang/Gpufit", "max_issues_repo_head_hexsha": "6e719585badff1c40488a1439fa04da1792e41b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gpufit/tests/Gauss_Fit_2D_Rotated.cpp", "max_forks_repo_name": "yongdengzhang/Gpufit", "max_forks_repo_head_hexsha": "6e719585badff1c40488a1439fa04da1792e41b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-18T15:13:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-18T15:13:27.000Z", "avg_line_length": 31.1794871795, "max_line_length": 104, "alphanum_fraction": 0.5505756579, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6404072369168893}}
{"text": "/*------------------------------------------------------------------------\n    Universidade do Estado do Rio de Janeiro\n    Autores: Anderson Zudio de Moraes\n             Victor Cracel Messner\n*   Teste de Primalidade AKS - NTL\n\n*   O c\u00f3digo apresentado faz parte do projeto de conclus\u00e3o de curso\n*   dos autores pelo t\u00edtulo de Bacharel, apresentado ao\n*   Intituto de Matem\u00e1tica e Estat\u00edstica,\n*   da Universidade do Estado do Rio de Janeiro.\n*   Voc\u00ea pode modificar e distribuir este c\u00f3digo livremente\n*   atrav\u00e9s dos termos do GNU General Public como publicado\n*   pelo Free Software Foundation atrav\u00e9s da vers\u00e3o 3 da licen\u00e7a,\n*   ou qualquer vers\u00e3o subsequente por op\u00e7\u00e3o sua.\n\n*   O objetivo deste c\u00f3digo \u00e9 fornecer uma implmementa\u00e7\u00e3o\n*   do AKS correta, r\u00e1pida e que suporte entradas\n*   maiores que a implementa\u00e7\u00e3o simples. Este c\u00f3digo\n*   utiliza a biblioteca NTL, que pode ser vista\n*   em < http://www.shoup.net/ntl/ >\n\n-----------------------------------------------------------------------*/\n\n#include <gmp.h>\n#include <NTL/ZZ.h>\n#include <NTL/RR.h>\n#include <NTL/ZZ_pX.h>\n/* -------------------------------------------\n--Header Default do NTL inclui por default:\n--<cstdlib>, <cmath> e <iostream>\n------------------------------------------- */\n\ninline void totiente_euler(long &resultado, long n);\n\n/* Observe que a fun\u00e7\u00e3o abaixo recebe a entrada\n*  em forma de STRING. Ela est\u00e1 esperando um string\n*  que contenha somente um n\u00famero inteiro natural,\n*  v\u00e1lido para a execu\u00e7\u00e3o do AKS. N\u00e3o h\u00e1 valida\u00e7\u00e3o\n*  de entrada no c\u00f3digo. */\nbool aks_ntl(const std::string n){ //Evita o programdor a utilizar I/O do NTL\n\t//Etapa 1\n    mpz_t mpz_n; // tipo utilizado pelo GMP\n    mpz_init(mpz_n);\n    mpz_set_str(mpz_n, n.c_str(), 10);\n    //O NTL nao oferece uma fun\u00e7\u00e3o para\n    //computar a etapa 1. O GMP oferece:\n    if(mpz_perfect_power_p(mpz_n))\n            return false;\n\t//Fim da Etapa 1\n\n\t//Etapas 2, 3 e 4\n\tNTL::ZZ ZZ_n;  // tipo utilizado pelo NTL, inteiro prec arbitr\u00e1ria\n\tZZ_n = to_ZZ(NTL::conv<NTL::ZZ>(n.c_str())); //N\u00e3o h\u00e1 valida\u00e7\u00e3o de entrada\n\tbool teste;\n    long k; //Overflow para n > 2^(32768*raiz(2))\n\tNTL::ZZ r(2), n_mod_r; //N muito grande pode causar overflow no r na etapa 5\n\n\tdouble logaritmo_n = log(ZZ_n)/log(2); //Precisa ser real, se nao for causa erros de calculo\n    double logaritmo_n_2 = logaritmo_n*logaritmo_n;\n\n    while(1){\n        if(r == ZZ_n){  //Etapa 4\n            return true;\n        }\n        if(IsOne(GCD(ZZ_n, r))){ //Verificando se n \u00e9 relativamente primo com q\n            teste = true;\n            rem(n_mod_r, ZZ_n, r);\n            for(k = 1; k <= logaritmo_n_2; ++k){\n                if(IsOne(PowerMod(n_mod_r, k, r))){ // (n^k)%r==1 --> n%r passado para evitar BAD_ARGUMENTS\n                    teste = false;                  // resolve um problema da biblioteca\n                    break;\n                }\n            }\n            if(teste) break; //Ordem menor que logaritmo_n_2\n        }\n        else //Etapa 3\n            return false;\n        ++r;\n    }\n    //Fim da Etapa 2, Etapa 3 e Etapa 4\n\n\t//Etapa 5\n\t//-- Cuidado: N muito grande pode causar overflow no grau do polinomio ZZ_pX --\n\t//-- Limitacao da biblioteca! Grau max (2^31-1) ... r vale no maximo log2(N)^5 ...\n\t//WARNING! Possivel Overflow para n > 2^(raiz[5](2^32 - 1)) (~23 d\u00edgitos)\n    long phi; //Funcao totiente de Euler\u0135\n    long r_long = NTL::conv<long>(r);\n    totiente_euler(phi, r_long);\n    long int constante = floor(sqrt(phi)*logaritmo_n); //piso de raiz(phi(n)) log2 (n)\n\n    NTL::ZZ_p::init(ZZ_n);//Ativa a modularidade com n para o NTL\n    NTL::ZZ_pX f(r_long, 1); f -= 1; //x^r - 1, polinomio para acelerar as contas\n    const NTL::ZZ_pXModulus modulo(f);  //internas do NTL com pre-computacao\n    NTL::ZZ_pX lado_direito(NTL::conv<long>(n_mod_r), 1); //p(x) = x^(n mod r)\n    NTL::ZZ_pX lado_esquerdo(1, 1); //p(x) = x\n\n    for(long a; a <= constante; ++a){\n        SetCoeff(lado_esquerdo, 1); lado_esquerdo += a;//p(x) = x + a\n        PowerMod(lado_esquerdo, lado_esquerdo, ZZ_n, modulo); //(lhs = (x + a)^n mod (x^r - 1, n)\n        lado_esquerdo -= a;\n\n        if(lado_esquerdo != lado_direito) return false;\n        clear(lado_esquerdo);\n    }\n    return true;\n\t//Fim Etapa 5\n\n}\n\n//Esta fun\u00e7\u00e3o \u00e9 exatamente a mesma utilizada\n//no AKS simples, ela \u00e9 bem r\u00e1pida\ninline void totiente_euler(long &resultado, long n){\n    resultado = n;\n\n    for (long i = 2; i*i<=n; ++i){\n        if ((n % i) == 0){\n            while ((n % i) == 0){\n                n /= i;\n            }\n            resultado -= resultado / i;\n        }\n    }\n    if (n > 1) {\n        resultado -= resultado / n;\n     }\n}\n", "meta": {"hexsha": "584dd8a02b7c0781989b1906871d2833820363a7", "size": 4628, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AKS/NTL.hpp", "max_stars_repo_name": "ildosrel/Projeto-Final", "max_stars_repo_head_hexsha": "3d3375f47029429a29d8ecea93d9af542a666f10", "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": "AKS/NTL.hpp", "max_issues_repo_name": "ildosrel/Projeto-Final", "max_issues_repo_head_hexsha": "3d3375f47029429a29d8ecea93d9af542a666f10", "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": "AKS/NTL.hpp", "max_forks_repo_name": "ildosrel/Projeto-Final", "max_forks_repo_head_hexsha": "3d3375f47029429a29d8ecea93d9af542a666f10", "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": 36.4409448819, "max_line_length": 107, "alphanum_fraction": 0.5875108038, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6404072344805594}}
{"text": "//\n//! Copyright \u00a9 2018\n//! Brandon Kohn\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#pragma once\n\n#include <geometrix/algebra/expression.hpp>\n#include <geometrix/primitive/point_traits.hpp>\n#include <boost/concept_check.hpp>\n\nnamespace geometrix {\n\n    enum class point_circle_orientation\n    {\n        outside = -1\n        cocircular = 0\n        inside = 1\n    };\n\n    template <typename Point1, typename Point2, typename Point3, typename Point4, typename NumberComparisonPolicy>\n    inline point_circle_orientation point_in_circumcircle(const Point1& a, const Point2& b, const Point3& c, const Point4& p, const NumberComparisonPolicy& cmp)\n    {\n\t\tBOOST_CONCEPT_ASSERT( (PointConcept<Point1>) );\n\t\tBOOST_CONCEPT_ASSERT( (PointConcept<Point2>) );\n\t\tBOOST_CONCEPT_ASSERT( (PointConcept<Point3>) );\n\t\tBOOST_CONCEPT_ASSERT( (PointConcept<Point4>) );\n\t\tBOOST_CONCEPT_ASSERT( (NumberComparisonPolicyConcept<NumberComparisonPolicy>) );\n        static_assert(dimension_of<Point1>::value == 2, \"point_in_cicumcircle is 2D only.\");\n        static_assert(dimension_of<Point2>::value == 2, \"point_in_cicumcircle is 2D only.\");\n        static_assert(dimension_of<Point3>::value == 2, \"point_in_cicumcircle is 2D only.\");\n        static_assert(dimension_of<Point4>::value == 2, \"point_in_cicumcircle is 2D only.\");\n\n        using length_t = typename arithmetic_type_of<Point1>::type;\n        using area_t = decltype(std::declval<length_t>()*std::declval<length_t>);\n\n        length_t apx = get<0>(a) - get<0>(p);\n        length_t apy = get<1>(a) - get<1>(p);\n        length_t bpx = get<0>(b) - get<0>(p);\n        length_t bpy = get<1>(b) - get<1>(p);\n        length_t cpx = get<0>(c) - get<0>(p);\n        length_t cpy = get<1>(c) - get<1>(p);\n\n        area_t abdet = adx * bdy - bdx * ady;\n        area_t bcdet = bdx * cdy - cdx * bdy;\n        area_t cadet = cdx * ady - adx * cdy;\n        area_t alift = adx * adx + ady * ady;\n        area_t blift = bdx * bdx + bdy * bdy;\n        area_t clift = cdx * cdx + cdy * cdy;\n\n        area_t r = alift * bcdet + blift * cadet + clift * abdet;\n        if(cmp.greater_than(r, constants::zero<area_t>())\n            return point_circle_orientation::inside;\n\n        if(cmp.less_than(r, constants::zero<area_t>())\n            return point_circle_orientation::outside;\n         \n        return point_circle_orientation::cocircular;\n    }\n\n}//! namespace geometrix;\n\n", "meta": {"hexsha": "ddbbe6090eeb2428aa217a5ddb11369dfb3674a2", "size": 2515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometrix/algorithm/point_in_circumcircle.hpp", "max_stars_repo_name": "brandon-kohn/Geometrix", "max_stars_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "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": "geometrix/algorithm/point_in_circumcircle.hpp", "max_issues_repo_name": "brandon-kohn/Geometrix", "max_issues_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometrix/algorithm/point_in_circumcircle.hpp", "max_forks_repo_name": "brandon-kohn/Geometrix", "max_forks_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "max_forks_repo_licenses": ["BSL-1.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.1060606061, "max_line_length": 160, "alphanum_fraction": 0.654473161, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213880824791, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6403831846379161}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2017-2018, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP\n\n\n#include <boost/geometry/algorithms/detail/convert_point_to_point.hpp>\n#include <boost/geometry/algorithms/detail/signed_size_type.hpp>\n#include <boost/geometry/arithmetic/arithmetic.hpp>\n#include <boost/geometry/arithmetic/dot_product.hpp>\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/strategies/densify.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace densify\n{\n\n\n/*!\n\\brief Densification of cartesian segment.\n\\ingroup strategies\n\\tparam CalculationType \\tparam_calculation\n\n\\qbk{\n[heading See also]\n[link geometry.reference.algorithms.densify.densify_4_with_strategy densify (with strategy)]\n}\n */\ntemplate\n<\n    typename CalculationType = void\n>\nclass cartesian\n{\npublic:\n    template <typename Point, typename AssignPolicy, typename T>\n    static inline void apply(Point const& p0, Point const& p1, AssignPolicy & policy, T const& length_threshold)\n    {\n        typedef typename AssignPolicy::point_type out_point_t;\n        typedef typename select_most_precise\n            <\n                typename coordinate_type<Point>::type,\n                typename coordinate_type<out_point_t>::type,\n                CalculationType\n            >::type calc_t;\n\n        typedef model::point<calc_t, geometry::dimension<Point>::value, cs::cartesian> calc_point_t;\n\n        calc_point_t cp0, cp1;\n        geometry::detail::conversion::convert_point_to_point(p0, cp0);\n        geometry::detail::conversion::convert_point_to_point(p1, cp1);\n\n        // dir01 = xy1 - xy0\n        calc_point_t dir01 = cp1;\n        geometry::subtract_point(dir01, cp0);\n        calc_t const dot01 = geometry::dot_product(dir01, dir01);\n        calc_t const len = math::sqrt(dot01);\n\n        BOOST_GEOMETRY_ASSERT(length_threshold > T(0));\n\n        signed_size_type n = signed_size_type(len / length_threshold);\n        if (n <= 0)\n        {\n            return;\n        }\n\n        // NOTE: Normalization will not work for integral coordinates\n        // normalize\n        //geometry::divide_value(dir01, len);\n\n        calc_t step = len / (n + 1);\n\n        calc_t d = step;\n        for (signed_size_type i = 0 ; i < n ; ++i, d += step)\n        {\n            // pd = xy0 + d * dir01\n            calc_point_t pd = dir01;\n\n            // without normalization\n            geometry::multiply_value(pd, calc_t(i + 1));\n            geometry::divide_value(pd, calc_t(n + 1));\n            // with normalization\n            //geometry::multiply_value(pd, d);\n\n            geometry::add_point(pd, cp0);\n\n            // NOTE: Only needed if types calc_point_t and out_point_t are different\n            // otherwise pd could simply be passed into policy\n            out_point_t p;\n            assert_dimension_equal<calc_point_t, out_point_t>();\n            geometry::detail::conversion::convert_point_to_point(pd, p);\n\n            policy.apply(p);\n        }\n    }\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <>\nstruct default_strategy<cartesian_tag>\n{\n    typedef strategy::densify::cartesian<> type;\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::densify\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP\n", "meta": {"hexsha": "a3ddeaf968df675ba50f4b1af2181fbaa102adbd", "size": 3823, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/strategies/cartesian/densify.hpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/strategies/cartesian/densify.hpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/strategies/cartesian/densify.hpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 28.5298507463, "max_line_length": 112, "alphanum_fraction": 0.6821867643, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.6403831692358439}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nEigen::MatrixXd StrassenMultiply(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B) {\n    if (A.rows() > 128) {\n        return A * B;\n    }\n\n    unsigned int rows = A.rows() / 2;\n    unsigned int cols = A.cols() / 2;\n\n    Eigen::MatrixXd a = A.topLeftCorner(rows, cols);\n    Eigen::MatrixXd b = A.topRightCorner(rows, cols);\n    Eigen::MatrixXd c = A.bottomLeftCorner(rows, cols);\n    Eigen::MatrixXd d = A.bottomRightCorner(rows, cols);\n    Eigen::MatrixXd e = B.topLeftCorner(rows, cols);\n    Eigen::MatrixXd f = B.topRightCorner(rows, cols);\n    Eigen::MatrixXd g = B.bottomLeftCorner(rows, cols);\n    Eigen::MatrixXd h = B.bottomRightCorner(rows, cols);\n\n    Eigen::MatrixXd P1 = StrassenMultiply(a, f - h);\n    Eigen::MatrixXd P2 = StrassenMultiply(a + b, h);\n    Eigen::MatrixXd P3 = StrassenMultiply(c + d, e);\n    Eigen::MatrixXd P4 = StrassenMultiply(d, g - e);\n    Eigen::MatrixXd P5 = StrassenMultiply(a + d, e + h);\n    Eigen::MatrixXd P6 = StrassenMultiply(b - d, g + h);\n    Eigen::MatrixXd P7 = StrassenMultiply(a - c, e + f);\n\n    Eigen::MatrixXd r = P5 + P4 - P2 + P6;\n    Eigen::MatrixXd s = P1 + P2;\n    Eigen::MatrixXd t = P3 + P4;\n    Eigen::MatrixXd u = P1 + P5 - P3 - P7;\n\n    Eigen::MatrixXd result = Eigen::MatrixXd::Zero(r.cols() + s.cols(), r.cols() + s.cols());\n    result.topLeftCorner(rows, cols) = r;\n    result.topRightCorner(rows, cols) = s;\n    result.bottomLeftCorner(rows, cols) = t;\n    result.bottomRightCorner(rows, cols) = h;\n\n    return result;\n}\n\nint main(int argc, char const *argv[]) {\n    Eigen::MatrixXd A = Eigen::MatrixXd::Random(2, 2);\n    Eigen::MatrixXd B = Eigen::MatrixXd::Random(2, 2);\n\n    Eigen::MatrixXd result = StrassenMultiply(A, B);\n    std::cout << \"Multiplication done !\" << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "b12919045222e695f35af83c06ebd91be736171c", "size": 1811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/semestre-3/maths-2/ex5/main.cpp", "max_stars_repo_name": "guillaume-haerinck/imac-c", "max_stars_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/semestre-3/maths-2/ex5/main.cpp", "max_issues_repo_name": "guillaume-haerinck/imac-c", "max_issues_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/semestre-3/maths-2/ex5/main.cpp", "max_forks_repo_name": "guillaume-haerinck/imac-c", "max_forks_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8269230769, "max_line_length": 93, "alphanum_fraction": 0.6322473771, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6403673666422274}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\ntypedef boost::numeric::ublas::matrix<float> Matrix44;\r\ntypedef boost::numeric::ublas::identity_matrix<float> IdentityMtx44;\r\n\r\n\r\nMatrix44 transposeMtx(const Matrix44 &matrix)\r\n{\r\n\tMatrix44 matrix_ = IdentityMtx44(4);\r\n\r\n\tmatrix_(0, 0) = matrix(0, 0);\r\n\tmatrix_(0, 1) = matrix(1, 0);\r\n\tmatrix_(0, 2) = matrix(2, 0);\r\n\tmatrix_(0, 3) = matrix(3, 0);\r\n\r\n\tmatrix_(1, 0) = matrix(0, 1);\r\n\tmatrix_(1, 1) = matrix(1, 1);\r\n\tmatrix_(1, 2) = matrix(2, 1);\r\n\tmatrix_(1, 3) = matrix(3, 1);\r\n\r\n\tmatrix_(2, 0) = matrix(0, 2);\r\n\tmatrix_(2, 1) = matrix(1, 2);\r\n\tmatrix_(2, 2) = matrix(2, 2);\r\n\tmatrix_(2, 3) = matrix(3, 2);\r\n\r\n\tmatrix_(3, 0) = matrix(0, 3);\r\n\tmatrix_(3, 1) = matrix(1, 3);\r\n\tmatrix_(3, 2) = matrix(2, 3);\r\n\tmatrix_(3, 3) = matrix(3, 3);\r\n\r\n\treturn matrix_;\r\n}\r\n\r\n\r\nint main()\r\n{\r\n\tMatrix44 matrix(4, 4);\r\n\r\n\tfor (int i = 0; i < 4; ++i) {\r\n\t\tfor (int j = 0; j < 4; ++j) {\r\n\t\t\tmatrix(i, j) = 4 * i + j;\r\n\t\t}\r\n\t}\r\n\r\n\tstd::cout << matrix << std::endl;\r\n\r\n\r\n\tmatrix = transposeMtx(matrix);\r\n\r\n\tstd::cout << matrix << std::endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n", "meta": {"hexsha": "41783be69f5596edac1f0abd986c67dbe3b8795c", "size": 1128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/MathTest/TransposeTest.cpp", "max_stars_repo_name": "taku-xhift/labo", "max_stars_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/MathTest/TransposeTest.cpp", "max_issues_repo_name": "taku-xhift/labo", "max_issues_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/MathTest/TransposeTest.cpp", "max_forks_repo_name": "taku-xhift/labo", "max_forks_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.1428571429, "max_line_length": 69, "alphanum_fraction": 0.5691489362, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6403572082643266}}
{"text": "/**\n * @file matode_main.cc\n * @brief NPDE homework MatODE code\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Dense>\n#include <iomanip>\n#include <iostream>\n\n#include \"matode.h\"\n\nint main(int /*argc*/, char** /*argv*/) {\n  /* SAM_LISTING_BEGIN_6 */\n  double h = 0.01;  // stepsize\n  Eigen::Vector3d norms;\n  // Build M\n  Eigen::Matrix3d M;\n  M << 8, 1, 6, 3, 5, 7, 9, 9, 2;\n  // Build A\n  Eigen::Matrix3d A;\n  A << 0, 1, 1, -1, 0, 1, -1, -1, 0;\n  Eigen::MatrixXd I = Eigen::Matrix3d::Identity();\n\n  auto QR = M.householderQr();\n\n  Eigen::Matrix3d Q = QR.householderQ() * Eigen::Matrix3d::Identity();\n\n  Eigen::Matrix3d explicit_euler, implicit_euler, implicit_midpoint;\n\n  explicit_euler = Q;\n  implicit_euler = Q;\n  implicit_midpoint = Q;\n\n\tstd::cout << (explicit_euler * explicit_euler.transpose() - I).norm() << \"\\t\"\n\t          <<  (implicit_euler * implicit_euler.transpose() - I).norm() << \"\\t\"\n\t          <<  (implicit_midpoint * implicit_midpoint.transpose() - I).norm() << std::endl;\n\n\tstd::cout << 0 << \"\\t\" <<(explicit_euler * explicit_euler.transpose() - I).norm() << \"\\t\"\n\t          <<  (implicit_euler * implicit_euler.transpose() - I).norm() << \"\\t\"\n\t          <<  (implicit_midpoint * implicit_midpoint.transpose() - I).norm() << std::endl;\n\n  for(int i = 0; i < 20; i++) {\n\texplicit_euler = MatODE::eeulstep(A, explicit_euler, h);\n\timplicit_euler = MatODE::ieulstep(A, implicit_euler, h);\n\timplicit_midpoint = MatODE::impstep(A, implicit_midpoint, h);\n\n\tstd::cout << i + 1 << \"\\t\" <<(explicit_euler * explicit_euler.transpose() - I).norm() << \"\\t\"\n\t\t\t\t<<  (implicit_euler * implicit_euler.transpose() - I).norm() << \"\\t\"\n\t\t\t\t<<  (implicit_midpoint * implicit_midpoint.transpose() - I).norm() << std::endl;\n\n\n  }\n\n\n\n\n\n  /* SAM_LISTING_END_6 */\n  return 0;\n}\n", "meta": {"hexsha": "8c533b9d624018dc5340585ae52fa5bd0bf868b4", "size": 1785, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MatODE/mysolution/matode_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/MatODE/mysolution/matode_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/MatODE/mysolution/matode_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": 28.7903225806, "max_line_length": 94, "alphanum_fraction": 0.6173669468, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6403352325900038}}
{"text": "//    boost asinh.hpp header file\r\n\r\n//  (C) Copyright Eric Ford 2001 & Hubert Holin.\r\n//  Distributed under the Boost Software License, Version 1.0. (See\r\n//  accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// See http://www.boost.org for updates, documentation, and revision history.\r\n\r\n#ifndef BOOST_ACOSH_HPP\r\n#define BOOST_ACOSH_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <cmath>\r\n#include <boost/config.hpp>\r\n#include <boost/math/tools/precision.hpp>\r\n#include <boost/math/policies/error_handling.hpp>\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n\r\n// This is the inverse of the hyperbolic cosine function.\r\n\r\nnamespace boost\r\n{\r\n    namespace math\r\n    {\r\n       namespace detail\r\n       {\r\n#if defined(__GNUC__) && (__GNUC__ < 3)\r\n        // gcc 2.x ignores function scope using declarations,\r\n        // put them in the scope of the enclosing namespace instead:\r\n        \r\n        using    ::std::abs;\r\n        using    ::std::sqrt;\r\n        using    ::std::log;\r\n        \r\n        using    ::std::numeric_limits;\r\n#endif\r\n        \r\n        template<typename T, typename Policy>\r\n        inline T    acosh_imp(const T x, const Policy& pol)\r\n        {\r\n            using    ::std::abs;\r\n            using    ::std::sqrt;\r\n            using    ::std::log;\r\n            \r\n            T const    one = static_cast<T>(1);\r\n            T const    two = static_cast<T>(2);\r\n            \r\n            static T const    taylor_2_bound = sqrt(tools::epsilon<T>());\r\n            static T const    taylor_n_bound = sqrt(taylor_2_bound);\r\n            static T const    upper_taylor_2_bound = one/taylor_2_bound;\r\n            \r\n            if(x < one)\r\n            {\r\n               return policies::raise_domain_error<T>(\r\n                  \"boost::math::acosh<%1%>(%1%)\",\r\n                  \"acosh requires x >= 1, but got x = %1%.\", x, pol);\r\n            }\r\n            else if    (x >= taylor_n_bound)\r\n            {\r\n                if    (x > upper_taylor_2_bound)\r\n                {\r\n                    // approximation by laurent series in 1/x at 0+ order from -1 to 0\r\n                    return( log( x*two) );\r\n                }\r\n                else\r\n                {\r\n                    return( log( x + sqrt(x*x-one) ) );\r\n                }\r\n            }\r\n            else\r\n            {\r\n                T    y = sqrt(x-one);\r\n                \r\n                // approximation by taylor series in y at 0 up to order 2\r\n                T    result = y;\r\n                \r\n                if    (y >= taylor_2_bound)\r\n                {\r\n                    T    y3 = y*y*y;\r\n                    \r\n                    // approximation by taylor series in y at 0 up to order 4\r\n                    result -= y3/static_cast<T>(12);\r\n                }\r\n                \r\n                return(sqrt(static_cast<T>(2))*result);\r\n            }\r\n        }\r\n       }\r\n\r\n        template<typename T, typename Policy>\r\n        inline typename tools::promote_args<T>::type acosh(const T x, const Policy& pol)\r\n        {\r\n           typedef typename tools::promote_args<T>::type result_type;\r\n           return detail::acosh_imp(\r\n              static_cast<result_type>(x), pol);\r\n        }\r\n        template<typename T>\r\n        inline typename tools::promote_args<T>::type acosh(const T x)\r\n        {\r\n           typedef typename tools::promote_args<T>::type result_type;\r\n           return detail::acosh_imp(\r\n              static_cast<result_type>(x), policies::policy<>());\r\n        }\r\n\r\n    }\r\n}\r\n\r\n#endif /* BOOST_ACOSH_HPP */\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "338db2fbf7070c25e7f9abf9b25b8b64e53b8cac", "size": 3611, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "windows/include/boost/math/special_functions/acosh.hpp", "max_stars_repo_name": "jaredhoberock/gotham", "max_stars_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "windows/include/boost/math/special_functions/acosh.hpp", "max_issues_repo_name": "jaredhoberock/gotham", "max_issues_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "windows/include/boost/math/special_functions/acosh.hpp", "max_forks_repo_name": "jaredhoberock/gotham", "max_forks_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_forks_repo_licenses": ["Apache-2.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.8632478632, "max_line_length": 89, "alphanum_fraction": 0.4901689283, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6403352280223862}}
{"text": "#include <gnuplot-iostream/gnuplot-iostream.h>\n#include <boost/tuple/tuple.hpp>\n#include <iostream>\n#include <iomanip>\n#include <functional>\n#include <vector>\n#include <cmath>\n#include \"Tools.hpp\"\nusing namespace std;\n\n\n/***********************************************************************\n\nThis program is for the first case of 1-Dimensional drag. The Euler1D\nclass is generalized to keep track of position and velocity. It accepts\na lambda as a generic euler step function. The only variable it depends\non is dt, generally used to change the accuracy and computation time.\n\nThe main function creates a Euler1D object called point with an initial\nvelocity of v_i and and an initial position (x) of 0. The main loop\nincrements t by dt each iteration, saving the x, v, and t in vectors and\napplying the euler step. The program then plots v vs t and x vs t in\nfiles VelTime.png and PosTime.png respectively. Then, the program uses\na few functions from Tools.hpp to find the percent error of the terminal\nvelocity and the rising and falling times of the object.\n\n***********************************************************************/\n\nconst double v_i = 5;\t\t\t// Initial velocity of the object\nconst double g = 9.8;\t\t\t// Gravitational acceleration (negative)\nconst double b = 1;\t\t\t\t// Generalized drag constant\nconst double dt = 0.001;//0.255;\t\t// Time step\nconst double SIM_TIME = 2;\t\t// Time to run the simulation (Should be large enough to let v = v_t)\n\nfunction<double(double,double)> dragStep = [](double x, double v){ return -g-b*v*abs(v); };\t// This is the lambda function used as the euler step. The type isn't auto because\\\n\t// it's passed as an argument to the Euler1D::update fuction and the compiler has to know parameter type.\n\nclass Euler1D{\t\t\t\t\t\t// Euler1D definition\npublic:\n\tEuler1D(double x_0, double v_0);// Constructor\n\tvoid update(function<double(double,double)>& f);// Euler step and updating x\n\tdouble getX() const;\t// Accessor methods\n\tdouble getV() const;\nprivate:\n\tdouble x;\t// Instance variables\n\tdouble v;\n};\n\nEuler1D::Euler1D(double x_0, double v_0){\t// Constructor just initializes position and velocity\n\tx = x_0;\n\tv = v_0;\n}\n\nvoid Euler1D::update(function<double(double,double)>& f){\t// Reference to Euler step lambda as argument for update function\n\tdouble eulerStep = f(x,v);\t// Calculate the step before updating anything\n\tx += v*dt;\t\t\t\t\t// Update x\n\tv += eulerStep*dt;\t\t\t// Update v\n}\n\ndouble Euler1D::getX() const { return x; }\t// Accessor methods for x and v\ndouble Euler1D::getV() const { return v; }\n\n\nvoid plotStuff(vector<double> x, vector<double> v, vector<double> t){\t// Plots the velocity v. time and position v. time graphs\n\tGnuplot gp;\t// Instance of gnuplot terminal stream\n\n\tgp << setprecision(3);\t// Velocity v. time graph...\n\tgp << \"set xrange [0:\" << SIM_TIME << \"]\\n\";\n\tgp << \"set yrange [\" << v[0] << \":\" << getMinVal(v)*1.1 << \"]\\n\";\n\tgp << \"set format y \\\"%.1f\\\"\\n\";\n\tgp << \"set term png size 720,480 font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set xlabel \\\"t (s)\\\"\\n\";\n\tgp << \"set ylabel \\\"v (m/s)\\\"\\n\";\n\tgp << \"set title \\\"Velocity vs. Time with Rayleigh's Drag Equation, b = \" << b << \"\\\"\\n\"; \n\tgp << \"set output \\\"VelTime.png\\\"\\n\";\n\tgp << \"plot '-' with dots lc rgb \\\"black\\\" notitle\\n\";\n\tgp.send1d(boost::make_tuple(t,v));\n\n\n\tgp << \"set xrange [0:\" << SIM_TIME << \"]\\n\";\t// Position v. time graph...\n\tgp << \"set yrange [0:\" << getMaxVal(x)*1.1 << \"]\\n\";\n\tgp << \"set xlabel \\\"t (s)\\\"\\n\";\n\tgp << \"set ylabel \\\"x (m)\\\"\\n\";\n\tgp << \"set title \\\"Position vs. Time with Rayleigh's Drag Equation, b = \" << b << \"\\\"\\n\"; \n\tgp << \"set output \\\"PosTime.png\\\"\\n\";\n\tgp << \"plot '-' with dots lc rgb \\\"black\\\" notitle\\n\";\n\tgp.send1d(boost::make_tuple(t,x));\n}\n\n\nint main(){\t\t\t\t\t// Main program!\n\tEuler1D point(0,v_i);\t// Create an Euler1D object, x=0 v=v_i\n\tvector<double> x_n;\t\t// Vectors for x, v, and t\n\tvector <double> v_n;\n\tvector <double> t_n;\n\n\tfor(double t = 0; t < SIM_TIME; t += dt){\t// Main loop\n\t\tx_n.push_back(point.getX());\t// Save point's x and v before modification\n\t\tv_n.push_back(point.getV());\n\t\tt_n.push_back(t);\t\t\t\t// Save the value of t for plotting\n\t\tpoint.update(dragStep);\t\t\t// Update the point using kinematic equations and Euler step\n\t}\n\n\tplotStuff(x_n, v_n, t_n);\t// Make the plots!\n\n\tdouble diff = pErr(g,b,v_n.back());\t// Calculate the percent error between accepted and estimated terminal velocities\n\tcout << \"Difference between calculated and final value: \" << diff*100 << \"%\\n\";\t// Display the percent error as a percentage\n\n\tdouble rising = sgnChangeTime(v_n, t_n);\t// Find the time when velocity changes sign, marking the peak of the trajectory and rising time\n\tdouble hitground = sgnChangeTime(x_n, t_n);\t// Find the time when position changes time, marking when the object returns to 0\n\tcout << \"Rising time: \" << rising << \"\\n\";\t// Output rising time\n\tcout << \"Falling time: \" << hitground-rising << \"\\n\";\t// Then falling time (they should be different if b!= 0)\n\n\treturn 0;\t// Everything went well, return 0!\n}", "meta": {"hexsha": "2bb60c344597e6107cd7df15c435ed073044379e", "size": 4985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Drag/FirstCase.cpp", "max_stars_repo_name": "GEslinger/PhysClass", "max_stars_repo_head_hexsha": "5e34167c34ca0e8779e4002063d95ffa24a24c9d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Drag/FirstCase.cpp", "max_issues_repo_name": "GEslinger/PhysClass", "max_issues_repo_head_hexsha": "5e34167c34ca0e8779e4002063d95ffa24a24c9d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Drag/FirstCase.cpp", "max_forks_repo_name": "GEslinger/PhysClass", "max_forks_repo_head_hexsha": "5e34167c34ca0e8779e4002063d95ffa24a24c9d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.347826087, "max_line_length": 175, "alphanum_fraction": 0.6631895687, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6403352265529705}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <boost/static_assert.hpp>\n\nnamespace kt84 {\n\ntemplate <class _Func, int _DimIn, int _DimOut>\nstruct FiniteDifferentiator {\n    typedef Eigen::Matrix<double, _DimIn , 1> Point;\n    typedef Eigen::Matrix<double, _DimOut, _DimIn> Gradient;\n    typedef Eigen::Matrix<double, _DimIn, _DimIn> Hessian;\n    \n    Gradient gradient_fd(const Point& point, double epsilon) const {\n        Gradient result;\n        const _Func& f = *reinterpret_cast<const _Func*>(this);\n        for (int i = 0; i < _DimIn; ++i) {\n            Point delta = Point::Unit(_DimIn, i) * epsilon;\n            result.col(i) = (f(point + delta) - f(point - delta)) / (2 * epsilon);\n        }\n        return result;\n    }\n    Hessian hessian_fd(const Point& point, double epsilon) const {\n        BOOST_STATIC_ASSERT(_DimOut == 1);\n        Hessian result;\n        for (int i = 0; i < _DimIn; ++i) {\n            Point delta = Point::Unit(_DimIn, i) * epsilon;\n            result.row(i) = (gradient_fd(point + delta, epsilon) - gradient_fd(point - delta, epsilon)) / (2 * epsilon);\n        }\n        return result;\n    }\n};\n\n}\n\n", "meta": {"hexsha": "5cc1321bd24fdefb0287b107604b273e2a93186a", "size": 1133, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/math/FiniteDifferentiator.hh", "max_stars_repo_name": "honoriocassiano/skbar", "max_stars_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kt84/math/FiniteDifferentiator.hh", "max_issues_repo_name": "honoriocassiano/skbar", "max_issues_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T12:16:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T12:21:41.000Z", "max_forks_repo_path": "src/kt84/math/FiniteDifferentiator.hh", "max_forks_repo_name": "honoriocassiano/skbar", "max_forks_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4722222222, "max_line_length": 120, "alphanum_fraction": 0.6063548102, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6403339030365822}}
{"text": "\n#pragma once\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/beta.hpp>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\n// digamma function\ndouble digamma(double x);\n// multivariate digamma function\ndouble digamma_mult(double x,uint32_t d);\n// cateorical distribution (Multionomial for one word)\ndouble Cat(uint32_t x, Row<double> pi);\n// log cateorical distribution (Multionomial for one word)\ndouble logCat(uint32_t x, Row<double> pi);\n// evaluate beta distribution at x\ndouble Beta(double x, double alpha, double beta);\n// log beta function\ndouble betaln(double alpha, double beta);\n// evaluate log beta distribution at x\ndouble logBeta(double x, double alpha, double beta);\ndouble logBeta(const Row<double>& x, double alpha, double beta);\ndouble logDir(const Row<double>& x, const Row<double>& alpha);\n\nvoid betaMode(Col<double>& v, const Col<double>& alpha, const Col<double>& beta);\nvoid betaMode(Row<double>& v, const Col<double>& alpha, const Col<double>& beta);\n// stick breaking proportions;  truncated stickbreaking -> stick breaks will be dim longer than proportions v \nvoid stickBreaking(Col<double>& prop, const Col<double>& v);\nvoid stickBreaking(Row<double>& prop, const Row<double>& v);\nuint32_t multinomialMode(const Row<double>& p);\nvoid dirMode(Row<double>& mode, const Row<double>& alpha);\nvoid dirMode(Col<double>& mode, const Col<double>& alpha);\n\ntemplate <class U>\nRow<uint32_t> size(Mat<U> A)\n{\n  Row<uint32_t> s(2);\n  s(0) = A.n_rows;\n  s(1) = A.n_cols;\n  return s;\n};\n\ntemplate <class U>\nRow<uint32_t> size(Col<U> A)\n{\n  Row<uint32_t> s(2);\n  s(0) = A.n_rows;\n  s(1) = 1;\n  return s;\n};\n\ntemplate <class U>\nRow<uint32_t> size(Row<U> A)\n{\n  Row<uint32_t> s(2);\n  s(0) = 1;\n  s(1) = A.n_cols;\n  return s;\n};\n", "meta": {"hexsha": "9cef4ee64164b4da8e753299cec6f49f3e962a62", "size": 1846, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/probabilityHelpers.hpp", "max_stars_repo_name": "jstraub/bnp", "max_stars_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T01:18:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T20:16:54.000Z", "max_issues_repo_path": "include/probabilityHelpers.hpp", "max_issues_repo_name": "jstraub/bnp", "max_issues_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-07-12T12:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-12T12:58:14.000Z", "max_forks_repo_path": "include/probabilityHelpers.hpp", "max_forks_repo_name": "jstraub/bnp", "max_forks_repo_head_hexsha": "11cd28b49e9cf1db96f349181aff57a17672b6a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-22T05:37:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-26T07:11:34.000Z", "avg_line_length": 28.84375, "max_line_length": 110, "alphanum_fraction": 0.7237269772, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6403338838062942}}
{"text": "#include \"multibrot_opencl_calculator.h\"\n\n#include <boost/format.hpp>\n#include <unordered_map>\n\nnamespace {\nstatic const char* kMainProgram = R\"(\n/*\nRequires a definition:\n- REAL_T floating point type (acceptable types are float and, if device supports, half and double),\n- RESULT_T - type of result pixel component (either uchar or ushort)\n- RESULT_MAX - max value accepted by RESULT_T (either CHAR_MAX or USHRT_MAX)\n- POWER_FUNC - name of a function that executes power of Z and adds C\n  Function must take the following parameters:\n  - Z = (zreal, zimg) - input and output number\n  - zlen_sqr - square of absolute value of Z (square)\n  - power\n  - C = (real, img) - the second addend\n  In general this function should do the following mathematical operation:\n  (zreal, zimg) = (zreal, zimg) ^ power + (real, img)\n  Different functions are used for optimisation purposes\n*/\n\n// Preprocessor magic based on https://stackoverflow.com/a/1489985\n#define PASTER_2(x,y) x ## y\n#define PASTER_3(x,y,z) x ## y ## z\n#define EVALUATOR_2(x,y)  PASTER_2(x,y)\n#define EVALUATOR_3(x,y,z)  PASTER_3(x,y,z)\n#define CONVERT EVALUATOR_3(convert_, RESULT_T, _sat)\n#define REAL_T4 EVALUATOR_2(REAL_T, 4)\n\n// Universal complex number power function, supports all real powers but the slowest\nvoid UniversalPowerOfComplex(\n    __private REAL_T* restrict zreal,\n    __private REAL_T* restrict zimg,\n    const REAL_T zlen_sqr,\n    const REAL_T power,\n    const REAL_T real,\n    const REAL_T img\n)\n{\n    // Formula for z^p is a multi-value function, by we use a basic plane only\n    REAL_T multiplier = powr( (REAL_T)(zlen_sqr), (REAL_T)(0.5*power) );\n    // TODO danger zone here - at first iteration atan2 gets zero as both arguments\n    // Fix UB somehow\n    REAL_T phi = atan2( *zimg, *zreal );\n    *zreal = multiplier * cos( power * phi ) + real;\n    *zimg = multiplier * sin( power * phi ) + img;\n}\n\n// Should be used when power is 1\nvoid Power1OfComplex(\n    __private REAL_T* restrict zreal,\n    __private REAL_T* restrict zimg,\n    const REAL_T zlen_sqr,\n    const REAL_T power,\n    const REAL_T real,\n    const REAL_T img\n)\n{\n    *zreal += real;\n    *zimg += img;\n}\n\n// Should be used when power is 2\nvoid SquareOfComplex(\n    __private REAL_T* restrict zreal,\n    __private REAL_T* restrict zimg,\n    const REAL_T zlen_sqr,\n    const REAL_T power,\n    const REAL_T real,\n    const REAL_T img\n)\n{\n    REAL_T zreal_new = (*zreal) * (*zreal) - (*zimg) * (*zimg) + real;\n    *zimg = 2 * (*zreal) * (*zimg) + img;\n    *zreal = zreal_new;\n}\n\n// Should be used when power is 3\nvoid CubeOfComplex(\n    __private REAL_T* restrict zreal,\n    __private REAL_T* restrict zimg,\n    const REAL_T zlen_sqr,\n    const REAL_T power,\n    const REAL_T real,\n    const REAL_T img\n)\n{\n    REAL_T zreal_new = pown(*zreal, 3) - 3 * (*zreal) * (*zimg) * (*zimg) + real;\n    *zimg = 3 * (*zreal) * (*zreal) * (*zimg) - pown(*zimg, 3) + img;\n    *zreal = zreal_new;\n}\n\n/*\n    Calculate number of iterations that point after which point\n    escaped the set.\n    Returns raw number of iterations.\n*/\nREAL_T CalcPointOnMultibrotSet( REAL_T real, REAL_T img, REAL_T power, ushort max_iter_number )\n{\n    REAL_T iter_number = 0;\n    REAL_T zreal = 0;\n    REAL_T zimg = 0;\n    REAL_T zlen_sqr = 0;\n    while ( zlen_sqr < 2*2 && iter_number < max_iter_number )\n    {\n        POWER_FUNC( &zreal, &zimg, zlen_sqr, power, real, img );\n\n        zlen_sqr = zreal*zreal + zimg*zimg;\n        iter_number += 1;\n    }\n    return iter_number;\n}\n\n#ifdef COLOR_ENABLED\n/*\n    Scales iteration number and picks a color.\n    May be used only when RESULT_T is uchar4 or ushort4.\n    Useful for building color images.\n*/\nRESULT_T ProcessIterationNumber( REAL_T iter_number, ushort max_iter_number )\n{\n    // Calculate a color in HSV\n    // This algorithm is based on https://www.codingame.com/playgrounds/2358/how-to-plot-the-mandelbrot-set/adding-some-colors\n    REAL_T value = iter_number < max_iter_number ? RESULT_MAX : 0;\n    REAL_T hue = ( RESULT_MAX / max_iter_number ) * iter_number;\n    // Saturation is always max.\n    // Convert to RGB\n    REAL_T hue_section = hue / ( RESULT_MAX / 6 ); // hue_section is in range [0; 6]\n    uchar i1 = convert_uchar_sat_rtz( hue_section / 2 );\n    uchar i2 = convert_uchar_sat_rtz( remainder( hue_section, 2 ) );\n    uchar ic = ( i1 + i2 ) % 3;\n    uchar ix = ( i1 - i2 + 1 ) % 3;\n\n    REAL_T rgb[3] = { 0 };\n    const REAL_T chroma = value; // * saturation\n    REAL_T second_color = chroma * ( 1 - fabs( remainder( hue_section, 2 ) - 1 ) );\n    rgb[ic] = chroma;\n    rgb[ix] = second_color;\n\n    REAL_T4 result = (REAL_T4)( vload3( 0, rgb ), RESULT_MAX );\n    return CONVERT( result );\n}\n#else\n/*\n    Scales iteration number so it uses all available values from 0 to max supported by a given\n    number type.\n    May be used only when RESULT_T is uchar or ushort.\n    Useful for building grayscale images.\n*/\nRESULT_T ProcessIterationNumber( REAL_T iter_number, ushort max_iter_number )\n{\n    iter_number = ( RESULT_MAX / max_iter_number ) * iter_number;\n    iter_number = RESULT_MAX - iter_number;\n    return CONVERT( iter_number );\n}\n#endif\n\n/*\n    Build an image of Mandelbrot or Multibrot set.\n\n    (rmin, imin) - complex value that corresponds to the left top corner of the image,\n    (rmax, imax) - right bottom corner.\n\n    Output is a pointer to buffer that will contain pixel data. Data format is defined by RESULT_T.\n\n    Must be called with two-dimensional work assignment, where dimensions are used as image\n    size (first dimension is width, second dimension is height).\n    Pixels are stored in row-major order.\n*/\n__kernel void MultibrotSetKernel(\n    REAL_T rmin, REAL_T imin,\n    REAL_T rmax, REAL_T imax,\n    REAL_T power,\n    ushort max_iter_number,\n    __global RESULT_T* restrict output\n)\n{\n    REAL_T rstep = ( rmax - rmin ) / get_global_size(0);\n    REAL_T istep = ( imax - imin ) / get_global_size(1);\n\n    size_t row_width = get_global_size(0);\n    size_t result_index = get_global_id(1) * row_width + get_global_id(0);\n\n    REAL_T real = rmin + get_global_id(0) * rstep;\n    REAL_T img = imin + get_global_id(1) * istep;\n    REAL_T multibrot_val = CalcPointOnMultibrotSet( real, img, power, max_iter_number );\n    RESULT_T result = ProcessIterationNumber( multibrot_val, max_iter_number );\n    output[result_index] = result;\n}\n)\";\n\ntemplate <typename T>\nstruct TempValueConstants {\n    static const char* opencl_type_name;\n    static const char* required_extension;\n};\n\nconst char* TempValueConstants<half_float::half>::opencl_type_name = \"half\";\nconst char* TempValueConstants<half_float::half>::required_extension = \"cl_khr_fp16\";\n\nconst char* TempValueConstants<float>::opencl_type_name = \"float\";\nconst char* TempValueConstants<float>::required_extension = \"\";\n\nconst char* TempValueConstants<double>::opencl_type_name = \"double\";\nconst char* TempValueConstants<double>::required_extension = \"cl_khr_fp64\";\n\ntemplate <typename P>\nstruct ResultTypeConstants {\n    static const char* result_type_name;\n    static const char* result_max_val_macro;\n    static const int result_max_val;\n    static const bool color_enabled;\n};\n\n// Grayscale 8 bit\nconst char* ResultTypeConstants<cl_uchar>::result_type_name = \"uchar\";\nconst char* ResultTypeConstants<cl_uchar>::result_max_val_macro = \"UCHAR_MAX\";\nconst int ResultTypeConstants<cl_uchar>::result_max_val = CL_UCHAR_MAX;\nconst bool ResultTypeConstants<cl_uchar>::color_enabled = false;\n\n// Grayscale 16 bit\nconst char* ResultTypeConstants<cl_ushort>::result_type_name = \"ushort\";\nconst char* ResultTypeConstants<cl_ushort>::result_max_val_macro = \"USHRT_MAX\";\nconst int ResultTypeConstants<cl_ushort>::result_max_val = CL_USHRT_MAX;\nconst bool ResultTypeConstants<cl_ushort>::color_enabled = false;\n\n// RGB 8 bit\nconst char* ResultTypeConstants<cl_uchar4>::result_type_name = \"uchar4\";\nconst char* ResultTypeConstants<cl_uchar4>::result_max_val_macro = \"UCHAR_MAX\";\nconst int ResultTypeConstants<cl_uchar4>::result_max_val = CL_UCHAR_MAX;\nconst bool ResultTypeConstants<cl_uchar4>::color_enabled = true;\n\n// RGB 16 bit\nconst char* ResultTypeConstants<cl_ushort4>::result_type_name = \"ushort4\";\nconst char* ResultTypeConstants<cl_ushort4>::result_max_val_macro = \"USHRT_MAX\";\nconst int ResultTypeConstants<cl_ushort4>::result_max_val = CL_USHRT_MAX;\nconst bool ResultTypeConstants<cl_ushort4>::color_enabled = true;\n}  // namespace\n\ntemplate <typename T, typename P>\nMultibrotOpenClCalculator<T, P>::MultibrotOpenClCalculator(\n    const boost::compute::device& device, const boost::compute::context& context,\n    size_t max_width_pix, size_t max_height_pix)\n    : device_(device),\n      context_(context),\n      queue_(context, device, boost::compute::command_queue::enable_profiling),\n      max_width_pix_(max_width_pix),\n      max_height_pix_(max_height_pix),\n      output_device_vector_(max_width_pix * max_height_pix, context) {\n    BuildKernels();\n}\n\ntemplate <typename T, typename P>\nstd::string MultibrotOpenClCalculator<T, P>::PrepareCompilerOptions(const std::string& power_func) {\n    return (boost::format(\"-Werror -DREAL_T=%1% -DRESULT_T=%2% -DRESULT_MAX=%3% \"\n                          \"-DPOWER_FUNC=%4% %5% \") %\n            TempValueConstants<T>::opencl_type_name % ResultTypeConstants<P>::result_type_name %\n            ResultTypeConstants<P>::result_max_val_macro % power_func %\n            (ResultTypeConstants<P>::color_enabled ? \"-DCOLOR_ENABLED\" : \"\"))\n        .str();\n}\n\ntemplate <typename T, typename P>\nvoid MultibrotOpenClCalculator<T, P>::BuildKernels() {\n    // Collecting required extensions\n    std::string required_extension = TempValueConstants<T>::required_extension;\n    std::vector<std::string> extensions;\n    if (!required_extension.empty()) {\n        extensions.push_back(required_extension);\n    }\n\n    static const std::unordered_map<double /* power */, std::string> kFixedPowerFunctions = {\n        {1.0, \"Power1OfComplex\"},\n        {2.0, \"SquareOfComplex\"},\n        {3.0, \"CubeOfComplex\"},\n    };\n\n    for (const auto& d : kFixedPowerFunctions) {\n        specialized_kernels_.emplace(\n            d.first, Utils::BuildKernel(\n                         \"MultibrotSetKernel\", context_, kMainProgram,\n                         PrepareCompilerOptions(d.second), extensions));\n    }\n\n    universal_kernel_ = Utils::BuildKernel(\n        \"MultibrotSetKernel\", context_, kMainProgram,\n        PrepareCompilerOptions(\"UniversalPowerOfComplex\"), extensions);\n}\n\ntemplate <typename T, typename P>\nvoid MultibrotOpenClCalculator<T, P>::ExecutePrecalculateChecks(\n    size_t width_pix, size_t height_pix, int max_iterations) {\n    EXCEPTION_ASSERT(width_pix <= max_width_pix_);\n    EXCEPTION_ASSERT(height_pix <= max_height_pix_);\n    // Verify that given max iterations is valid for given pixel bit depth\n    EXCEPTION_ASSERT(max_iterations <= ResultTypeConstants<P>::result_max_val);\n}\n", "meta": {"hexsha": "fc411dfc5d40be10ab77bbae7afcb6ea7df41a8f", "size": 10870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multibrot_opencl/multibrot_opencl_calculator.cpp", "max_stars_repo_name": "Kristian-Popov/opencl-benchmark-and-fractals", "max_stars_repo_head_hexsha": "b88fe08ea540c5743e9b590b160a995ead272a6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multibrot_opencl/multibrot_opencl_calculator.cpp", "max_issues_repo_name": "Kristian-Popov/opencl-benchmark-and-fractals", "max_issues_repo_head_hexsha": "b88fe08ea540c5743e9b590b160a995ead272a6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multibrot_opencl/multibrot_opencl_calculator.cpp", "max_forks_repo_name": "Kristian-Popov/opencl-benchmark-and-fractals", "max_forks_repo_head_hexsha": "b88fe08ea540c5743e9b590b160a995ead272a6e", "max_forks_repo_licenses": ["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.2333333333, "max_line_length": 126, "alphanum_fraction": 0.7086476541, "num_tokens": 2902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6403338828012464}}
{"text": "//  (C) Copyright Raffi Enficiaud 2019.\n//  Distributed under the Boost Software License, Version 1.0.\n//  (See accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n\n//  See http://www.boost.org/libs/test for the library home page.\n\n//[example_code\n#define BOOST_TEST_MODULE example84\n#include <boost/test/included/unit_test.hpp>\n#include <random>\n#include <cmath>\n\n// this function does not compute properly the polynomial root estimation\n// in the case of a double root.\ntemplate <class random_generator_t>\nstd::pair<double, double> estimate_polynomial_roots(\n  random_generator_t& gen,\n  std::function<double(double)> polynomial) {\n\n  using namespace std;\n\n  std::uniform_real_distribution<> dis(-10, 10);\n  double x1 = dis(gen);\n  double x2 = dis(gen);\n  double fx1 = polynomial(x1);\n  double fx2 = polynomial(x2);\n\n  BOOST_TEST_INFO_SCOPE(\"sample1 = \" << x1);\n  BOOST_TEST_INFO_SCOPE(\"sample2 = \" << x2);\n\n  // from Vieta formula\n  double minus_b = x2 + x1 - (fx2 - fx1) / (x2 - x1);\n  double c = (x1 * fx2 - x2 * fx1 + x2 * x1 * x1 - x1 * x2 * x2) / (x1 - x2);\n\n  BOOST_TEST(minus_b * minus_b >= 4*c);\n\n  return std::make_pair(\n    (minus_b - sqrt(minus_b * minus_b - 4 * c)) / 2,\n    (minus_b + sqrt(minus_b * minus_b - 4 * c)) / 2);\n}\n\nBOOST_AUTO_TEST_CASE(quadratic_estimation)\n{\n  std::random_device rd;\n  unsigned int seed = rd();\n  std::mt19937 gen(seed);\n  std::uniform_int_distribution<> dis(-10, 10);\n\n  BOOST_TEST_MESSAGE(\"Seed = \" << seed);\n\n  for(int i = 0; i < 50; i++) {\n    BOOST_TEST_INFO_SCOPE(\"trial \" << i+1);\n    int root1 = dis(gen);\n    int root2 = dis(gen);\n    if(root1 > root2) {\n      std::swap(root1, root2);\n    }\n    BOOST_TEST_INFO_SCOPE(\"root1 = \" << root1);\n    BOOST_TEST_INFO_SCOPE(\"root2 = \" << root2);\n\n    std::pair<double, double> estimated = estimate_polynomial_roots(\n      gen,\n      [root1, root2](double x) -> double { return (x - root1) * (x - root2); });\n\n    BOOST_TEST(estimated.first == double(root1), 10. % boost::test_tools::tolerance());\n    BOOST_TEST(estimated.second == double(root2), 10. % boost::test_tools::tolerance());\n  }\n}\n//]\n\nBOOST_AUTO_TEST_CASE(making_it_fail)\n{\n  // cheating a bit ... but shhhh, do not show in the docs ...\n  BOOST_FAIL(\"Making it fail always on all platforms\");\n}\n", "meta": {"hexsha": "f5162379961f9429edee3abebdba393fa0cdd683", "size": 2289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/boost_1_71_0/libs/test/doc/examples/example84_contexts.run-fail.cpp", "max_stars_repo_name": "anonymouscode1/djxperf", "max_stars_repo_head_hexsha": "b6073a761753aa7a6247f2618977ca3a2633e78a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T11:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T03:08:16.000Z", "max_issues_repo_path": "thirdparty/boost_1_71_0/libs/test/doc/examples/example84_contexts.run-fail.cpp", "max_issues_repo_name": "anonymouscode1/djxperf", "max_issues_repo_head_hexsha": "b6073a761753aa7a6247f2618977ca3a2633e78a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 266.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T02:03:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:22:12.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/test/doc/examples/example84_contexts.run-fail.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 185.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T18:09:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T18:07:05.000Z", "avg_line_length": 29.7272727273, "max_line_length": 88, "alphanum_fraction": 0.6609873307, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6402676399637782}}
{"text": "/**\n* @file: transition.hpp\n* @brief: to compute the transitivity closure.\n* @author: Changjiang Cai, ccai1@stevens.edu, caicj5351@gmail.com\n* @version: 0.0.1\n* @creation date: 17-12-2015\n* @last modified: Thu 10 Mar 2016 09:32:02 AM EST\n*/\n\n#ifndef transition_hpp__\n#define transition_hpp__\n\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <Eigen/Dense>\n\n//read matrix from the file, and generate the transition matrix.\nstd::vector<std::vector<double> > \ngenerateTransitionMatrix (const std::string &path, const int &n);    \n\n\nstd::vector<std::vector<double> > \ngenerateTransitionMatrix (const std::vector<std::vector<double> >& matrix);\n\nstd::vector<std::vector<double> >\ngenerateTransitionMatrix_Eigen(const std::vector<std::vector<double>>& matrix);\n\n#endif /* transition_hpp */\n", "meta": {"hexsha": "42d4d31b80c0694a7a6ac6b5124587a29296677d", "size": 799, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/transition.hpp", "max_stars_repo_name": "ccj5351/crowdsourcing", "max_stars_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/transition.hpp", "max_issues_repo_name": "ccj5351/crowdsourcing", "max_issues_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transition.hpp", "max_forks_repo_name": "ccj5351/crowdsourcing", "max_forks_repo_head_hexsha": "b0c2052ed4ae7ca42aa20436c271e6de5c5258a1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6333333333, "max_line_length": 79, "alphanum_fraction": 0.733416771, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7431679972357831, "lm_q1q2_score": 0.6402676362131786}}
{"text": "/*\n    This file is part of beautiful-bullet.\n\n    Copyright (c) 2021, 2022 Bernardo Fichera <bernardo.fichera@gmail.com>\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n*/\n\n#include <iostream>\n\n#include <Eigen/Core>\n\n#include <pinocchio/algorithm/frames.hpp>\n#include <pinocchio/algorithm/jacobian.hpp>\n#include <pinocchio/algorithm/joint-configuration.hpp>\n#include <pinocchio/algorithm/kinematics.hpp>\n#include <pinocchio/algorithm/rnea.hpp>\n#include <pinocchio/parsers/urdf.hpp>\n\nint main(int argc, char const* argv[])\n{\n    // Model\n    pinocchio::Model model;\n    pinocchio::urdf::buildModel(\"models/iiwa_bullet/model.urdf\", model);\n    pinocchio::Data data(model);\n\n    // Frame ID\n    const std::string name = \"lbr_iiwa_link_7\";\n    const int id = model.getFrameId(name);\n\n    // Random joint position and velocity\n    Eigen::Matrix<double, 7, 1> q = Eigen::VectorXd::Random(7),\n                                v = Eigen::VectorXd::Random(7);\n\n    // Forward Kinematics\n    pinocchio::forwardKinematics(model, data, q, v);\n    pinocchio::framesForwardKinematics(model, data, q);\n\n    // Jacobian\n    pinocchio::Data::Matrix6x J(6, model.nv);\n    J.setZero();\n    pinocchio::computeFrameJacobian(model, data, q, id, J);\n\n    // Pose\n    pinocchio::SE3 pose = data.oMf[id];\n    Eigen::Vector3d trans = pose.translation();\n    Eigen::Matrix3d rot = pose.rotation();\n\n    // Compare\n    std::cout << \"Jacobian derivation\" << std::endl;\n    std::cout << (J * v).transpose() << std::endl;\n\n    std::cout << \"Lie Algebra derivation\" << std::endl;\n    std::cout << pinocchio::log6(pose).toVector().transpose() << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "04f538a1b42ea9c95039b50fdc8b7ff8327e45da", "size": 2677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/liealgebra.cpp", "max_stars_repo_name": "nash169/beautiful-bullet", "max_stars_repo_head_hexsha": "8ee170803fc313dd97d0523da89c3ec587dd6b5b", "max_stars_repo_licenses": ["MIT"], "max_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/liealgebra.cpp", "max_issues_repo_name": "nash169/beautiful-bullet", "max_issues_repo_head_hexsha": "8ee170803fc313dd97d0523da89c3ec587dd6b5b", "max_issues_repo_licenses": ["MIT"], "max_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/liealgebra.cpp", "max_forks_repo_name": "nash169/beautiful-bullet", "max_forks_repo_head_hexsha": "8ee170803fc313dd97d0523da89c3ec587dd6b5b", "max_forks_repo_licenses": ["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.1756756757, "max_line_length": 82, "alphanum_fraction": 0.7000373552, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6402515940797032}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/spatial_sort.h>\n#include <CGAL/Spatial_sort_traits_adapter_3.h>\n#include <vector>\n#include <boost/iterator/counting_iterator.hpp>\n\ntypedef CGAL::Simple_cartesian<double>                  Kernel;\ntypedef Kernel::Point_3                                 Point_3;\ntypedef CGAL::Spatial_sort_traits_adapter_3<Kernel,\n          CGAL::Pointer_property_map<Point_3>::type > Search_traits_3;\n\nint main()\n{\n  std::vector<Point_3> points;\n  points.push_back(Point_3(1,3,11));\n  points.push_back(Point_3(14,34,46));\n  points.push_back(Point_3(414,34,4));\n  points.push_back(Point_3(4,2,56));\n  points.push_back(Point_3(744,4154,43));\n  points.push_back(Point_3(74,44,1));\n  \n  std::vector<std::size_t> indices;\n  indices.reserve(points.size());\n  \n  std::copy(boost::counting_iterator<std::size_t>(0),\n            boost::counting_iterator<std::size_t>(points.size()),\n            std::back_inserter(indices));\n  \n  CGAL::spatial_sort( indices.begin(),\n                      indices.end(),\n                      Search_traits_3(CGAL::make_property_map(points)) );\n\n  for (std::vector<std::size_t>::iterator it=indices.begin();it!=indices.end();++it)\n    std::cout << points[*it] << \"\\n\";\n\n  std::cout << \"done\" << std::endl;\n  \n  return 0;\n}\n", "meta": {"hexsha": "fdda1a6daaeb4760059ba5204a32ce837a3a7bb2", "size": 1279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Spatial_sorting/sp_sort_using_property_map_3.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Spatial_sorting/sp_sort_using_property_map_3.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Spatial_sorting/sp_sort_using_property_map_3.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 31.975, "max_line_length": 84, "alphanum_fraction": 0.6512900704, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6402515929053416}}
{"text": "/*\n * SWE_Plane_Normal_Modes.hpp\n *\n *  Created on: 17 Nov 2019\n *      Author: Pedro Peixoto <pedrosp@ime.usp.br>\n *\n *      based on previous implementation by Martin Schreiber in swe_plane.cpp\n *\n */\n\n#ifndef SRC_PROGRAMS_SWE_PLANE_NORMAL_MODES_HPP_\n#define SRC_PROGRAMS_SWE_PLANE_NORMAL_MODES_HPP_\n\n#include <rexi/EXPFunctions.hpp>\n#include <sweet/plane/PlaneData_Spectral.hpp>\n#include <sweet/plane/PlaneData_SpectralComplex.hpp>\n#include <sweet/SimulationVariables.hpp>\n#include <sweet/plane/PlaneOperators.hpp>\n#include <functional>\n#if SWEET_EIGEN\n#include <Eigen/Eigenvalues>\n#endif\n/**\n * SWE Plane normal mode\n */\nclass SWE_Plane_Normal_Modes\n{\npublic:\n\n#if SWEET_QUADMATH && 0\n\ttypedef __float128 T;\n#else\n\ttypedef double T;\n#endif\n\ttypedef std::complex<T> complex;\n\n\tstatic\n\tvoid add_normal_mode(\n\t\t\tstd::size_t ik0,\t\t\t\t//wavenumber in x\n\t\t\tstd::size_t ik1,\t\t\t\t// wavenumeber in y\n\t\t\tdouble geo_mode,    //Coeficient multiplying geostrophic mode\n\t\t\tdouble igwest_mode, //Coeficient multiplying west gravity mode\n\t\t\tdouble igeast_mode, //Coeficient multiplying east gravity mode\n\t\t\tPlaneData_Spectral &io_h, // h: surface height (perturbation)\n\t\t\tPlaneData_Spectral &io_u, // u: velocity in x-direction\n\t\t\tPlaneData_Spectral &io_v, // v: velocity in y-direction\n\t\t\tSimulationVariables &i_simVars // Simulation variables\n\t)\n\t{\n\n\t\tEXPFunctions<T> rexiFunctions;\n\n\t\tconst PlaneDataConfig *planeDataConfig = io_h.planeDataConfig;\n\n\t\tif (i_simVars.disc.space_grid_use_c_staggering)\n\t\t\tSWEETError(\"Staggering not supported\");\n\t\t\n\t\t//std::cout<<\"Adding mode to fields\"<<std::endl;\n\n\t\t//Check if k0 is in correct sprectral area\n\t\t//std::cout<< io_h.planeDataConfig->spectral_data_size[1] << std::endl;\n\t\tif( ik1<0 || ik1 >= planeDataConfig->spectral_data_size[1]) \n\t\t\tSWEETError(\"Normal_mode: mode not within reach\");\n\n\t\tif( ik0<0 || ik0 >= planeDataConfig->spectral_data_size[0]) \n\t\t\tSWEETError(\"Normal_mode: mode not within reach\");\n\t\n\t\t//Check for mirror effects\n\t\tT k0 = (T)ik0;\n\t\tT k1;\n\t\tif (ik1 < planeDataConfig->spectral_data_size[1]/2)\n\t\t\tk1 = (T)ik1;\n\t\telse\n\t\t\tk1 = (T)((int)ik1-(int)planeDataConfig->spectral_data_size[1]);\n\t\t\n\t\tcomplex v[3][3];\n\t\tcomplex lambda[3];\n\n\t\tSWE_Plane_Normal_Modes::sw_eigen_decomp(\n\t\t\t\tk0,\t\t\t\t//wavenumber in x\n\t\t\t\tk1,\t\t\t\t// wavenumeber in y\n\t\t\t\ti_simVars,  // Input Simulation variables\n\t\t\t\tfalse, // Direct EV matrix (not inverse)\n\t\t\t\tv , // EV matrix\n\t\t\t\tlambda // output eigen values */\n\t\t);\n\n\t\tcomplex U[3];\n\t\t// Set normal mode acording to desired wave type\n\t\t// These are weights for the modes\n\t\tU[0] = geo_mode;\n\t\tU[1] = igwest_mode;\n\t\tU[2] = igeast_mode;\n\n\n\t\t//Define normal mode as combination of eigen vectors\n\t\tcomplex UEV[3] = {0.0, 0.0, 0.0};\n\t\tfor (int k = 0; k < 3; k++)\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t\tUEV[k] += v[k][j] * U[j];\n\n\t\t//std::cout<<\"spectral before\"<< std::endl;\n\t\t//io_v.print_spectralIndex();\n\n\t\tcomplex h_add, u_add, v_add;\n\t\th_add = io_h.spectral_get(ik1, ik0)+UEV[0];\n\t\tu_add = io_u.spectral_get(ik1, ik0)+UEV[1];\n\t\tv_add = io_v.spectral_get(ik1, ik0)+UEV[2];\n\n\t\t/* Add normal mode to data */\n\t\tio_h.spectral_set(ik1, ik0, h_add);\n\t\tio_u.spectral_set(ik1, ik0, u_add);\n\t\tio_v.spectral_set(ik1, ik0, v_add);\n\n\t\tio_h.spectral_zeroAliasingModes();\n\t\tio_u.spectral_zeroAliasingModes();\n\t\tio_v.spectral_zeroAliasingModes();\n\n/*Debug output*/\n#if 0\n\n\t\tstd::cout<<\"EV matrix\"<<std::endl;\n\t\tfor (int j = 0; j < 3; j++)\t{\n\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t\tstd::cout<< v[j][i]<<\" \"; \n\t\t\tstd::cout<<std::endl;\n\t\t}\n\t\n\t\tstd::cout<<\"Eigen values\"<<std::endl;\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tstd::cout<< lambda[j]<<\" \"; \n\t\tstd::cout<<std::endl;\n\t\t\n\t\tstd::cout<<\"Adding normal mode\"<<std::endl;\n\t\tfor (int j = 0; j < 3; j++)\n\t\t\tstd::cout<< UEV[j]<<\" \"; \n\t\tstd::cout<<std::endl;\n\t\n\t\tstd::cout<<ik0<<\" \"<<ik1<< \" \"<< io_v.p_spectral_get(ik1, ik0) << UEV[2] << std::endl;\n\n#endif\n\t\treturn;\n\t}\n\n\n\tstatic\n\tvoid convert_allspectralmodes_to_normalmodes(\n\t\t\tPlaneData_Spectral &i_h, // h: surface height (perturbation)\n\t\t\tPlaneData_Spectral &i_u, // u: velocity in x-direction\n\t\t\tPlaneData_Spectral &i_v, // v: velocity in y-direction\n\t\t\tSimulationVariables &i_simVars, // Simulation variables\n\t\t\tPlaneData_Spectral &o_geo_mode,    //Output: Coeficients multiplying geostrophic mode\n\t\t\tPlaneData_Spectral &o_igwest_mode, //Output: Coeficients multiplying west gravity mode\n\t\t\tPlaneData_Spectral &o_igeast_mode //Output: Coeficients multiplying east gravity mode\n\t)\n\t{\n\t\tconst PlaneDataConfig *planeDataConfig = i_h.planeDataConfig;\n\n\t\to_geo_mode.spectral_set_zero();\n\t\to_igwest_mode.spectral_set_zero();\n\t\to_igeast_mode.spectral_set_zero();\n\n\t\tcomplex geo_mode_c;\n\t\tcomplex igwest_mode_c;\n\t\tcomplex igeast_mode_c;\n\t\tfor (std::size_t ik1 = 0; ik1 < planeDataConfig->spectral_data_size[1]; ik1++)\n\t\t{\n\t\t\tfor (std::size_t ik0 = 0; ik0 < planeDataConfig->spectral_data_size[0]; ik0++)\n\t\t\t{\n\t\t\t\t\n\t\t\t\tSWE_Plane_Normal_Modes::convert_spectralmode_to_normalmode(\n\t\t\t\t\t\t\t\t\tik0, ik1,\n\t\t\t\t\t\t\t\t\ti_h,\n\t\t\t\t\t\t\t\t\ti_u,\n\t\t\t\t\t\t\t\t\ti_v,\n\t\t\t\t\t\t\t\t\ti_simVars,\n\t\t\t\t\t\t\t\t\tgeo_mode_c,\n\t\t\t\t\t\t\t\t\tigwest_mode_c,\n\t\t\t\t\t\t\t\t\tigeast_mode_c\n\t\t\t\t\t\t\t);\n\t\t\t\to_geo_mode.spectral_set(ik1, ik0, geo_mode_c);\n\t\t\t\to_igwest_mode.spectral_set(ik1, ik0, igwest_mode_c);\n\t\t\t\to_igeast_mode.spectral_set(ik1, ik0, igeast_mode_c);\n\n\t\t\t}\n\t\t}\t\n\t\treturn;\n\t};\n\n\tstatic\n\tvoid convert_spectralmode_to_normalmode(\n\t\t\tstd::size_t ik0,\t\t\t\t//wavenumber in x\n\t\t\tstd::size_t ik1,\t\t\t\t// wavenumeber in y\n\t\t\tPlaneData_Spectral &i_h, // h: surface height (perturbation)\n\t\t\tPlaneData_Spectral &i_u, // u: velocity in x-direction\n\t\t\tPlaneData_Spectral &i_v, // v: velocity in y-direction\n\t\t\tSimulationVariables &i_simVars, // Simulation variables\n\t\t\tcomplex &o_geo_mode,    //Output: Coeficient multiplying geostrophic mode\n\t\t\tcomplex &o_igwest_mode, //Output: Coeficient multiplying west gravity mode\n\t\t\tcomplex &o_igeast_mode //Output: Coeficient multiplying east gravity mode\n\t)\n\t{\n\n\t\tEXPFunctions<T> rexiFunctions;\n\n\t\tconst PlaneDataConfig *planeDataConfig = i_h.planeDataConfig;\n\n\t\tif (i_simVars.disc.space_grid_use_c_staggering)\n\t\t\tSWEETError(\"Staggering not supported\");\n\t\t\n\t\t//std::cout<<\"Adding mode to fields\"<<std::endl;\n\n\t\t//Check if k0 is in correct sprectral area\n\t\t//std::cout<< io_h.planeDataConfig->spectral_data_size[1] << std::endl;\n\t\tif( ik1<0 || ik1 >= planeDataConfig->spectral_data_size[1]) \n\t\t\tSWEETError(\"Normal_mode: mode not within reach\");\n\n\t\tif( ik0<0 || ik0 >= planeDataConfig->spectral_data_size[0]) \n\t\t\tSWEETError(\"Normal_mode: mode not within reach\");\n\t\n\t\t//Check for mirror effects\n\t\tT k0 = (T)ik0;\n\t\tT k1;\n\t\tif (ik1 < planeDataConfig->spectral_data_size[1]/2)\n\t\t\tk1 = (T)ik1;\n\t\telse\n\t\t\tk1 = (T)((int)ik1-(int)planeDataConfig->spectral_data_size[1]);\n\t\t\n\t\tcomplex v[3][3];\n\t\tcomplex lambda[3];\n\n\t\tSWE_Plane_Normal_Modes::sw_eigen_decomp(\n\t\t\t\tk0,\t\t\t\t//wavenumber in x\n\t\t\t\tk1,\t\t\t\t// wavenumeber in y\n\t\t\t\ti_simVars,  // Input Simulation variables\n\t\t\t\ttrue, // Inverse ev matrix\n\t\t\t\tv , // inverse EV matrix\n\t\t\t\tlambda // output eigen values */\n\t\t);\n\n\t\tcomplex U[3];\n\t\t// Set (h,u,v) spectral coeficients\n\t\t// These are weights for the modes\n\t\tU[0] = i_h.spectral_get(ik1, ik0);\n\t\tU[1] = i_u.spectral_get(ik1, ik0);\n\t\tU[2] = i_v.spectral_get(ik1, ik0);\n\n\n\t\t//Apply inverse EV matrix to obtain data in EV space\n\t\tcomplex UEV[3] = {0.0, 0.0, 0.0};\n\t\tfor (int k = 0; k < 3; k++)\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t\tUEV[k] += v[k][j] * U[j];\n\n\t\t//Return the modes\n\t\to_geo_mode=UEV[0];\n\t\to_igwest_mode=UEV[1];\n\t\to_igeast_mode=UEV[2];\n\t\t//std::cout<< \" Geost: \"<< o_geo_mode<<std::endl;\n\t\t//std::cout<< \" IGWest: \"<< o_igwest_mode<<std::endl;\n\t\t//std::cout<< \" IGEast: \"<< o_igeast_mode<<std::endl;\n\n\t\treturn;\t\t\n\t}\n\n\t/* Get linear shallow water operator eigen decomposition */\n\tstatic\n\tvoid sw_eigen_decomp(\n\t\t\tT k0,\t\t\t\t//wavenumber in x\n\t\t\tT k1,\t\t\t\t// wavenumeber in y\n\t\t\tSimulationVariables &i_simVars, // Input Simulation variables\n\t\t\tbool i_inverse = false, // Input true, returns inverse matriz, false: returns direct\n\t\t\tcomplex o_v[3][3] = {0}, // output eigen vector (direct or inverse)\n\t\t\tcomplex o_evalues[3] =  0 // output eigen values (optional)\n\t)\n\t{\n\t\tEXPFunctions<T> rexiFunctions;\n\t\tbool i_evalues = false;\n\t\tif (o_evalues){\n\t\t\ti_evalues = true;\n\t\t\t//std::cout<<i_evalues<<\" \"<< o_evalues[0]   << std::endl;\n\t\t}\n\t\telse{\n\t\t\ti_evalues = false;\n\t\t}\n\t\t//std::cout<<o_evalues[1]<<std::endl;\n\t\t//std::cout<<i_inverse<<std::endl;\n\n\t\tif (i_simVars.disc.space_grid_use_c_staggering)\n\t\t\tSWEETError(\"Staggering not supported\");\n\t\t\n\t\tcomplex I(0.0, 1.0);\n\t\t//std::cout<<\"Calculating EV for mode (\" << k0 << \", \" << k1 << \")\" << std::endl;\n\t\t//std::cout<<\"hi\"<< std::endl;\n\t\tT s0 = i_simVars.sim.plane_domain_size[0];\n\t\tT s1 = i_simVars.sim.plane_domain_size[1];\n\n\t\tT f = i_simVars.sim.plane_rotating_f0;\n\t\tT h = i_simVars.sim.h0;\n\t\tT g = i_simVars.sim.gravitation;\n\n\t\tT sqrt_h = rexiFunctions.l_sqrt(h);\n\t\tT sqrt_g = rexiFunctions.l_sqrt(g);\n\n\t\tcomplex b = -k0*I;\t// d/dx exp(I*k0*x) = I*k0 exp(I*k0*x)\n\t\tcomplex c = -k1*I;\n\n\t\tb = b*rexiFunctions.pi2/s0;\n\t\tc = c*rexiFunctions.pi2/s1;\n\n\t\t/*\n\t\t * Matrix with Eigenvectors (column-wise)\n\t\t */\n\t\tcomplex v[3][3];\n\t\tcomplex v_inv[3][3];\n\n\t\t/*\n\t\t * Eigenvalues\n\t\t */\n\t\tcomplex lambda[3];\n\n\t\t\n\t\tif (i_simVars.sim.plane_rotating_f0 == 0)\n\t\t{\n\t\t\t/*\n\t\t\t * http://www.wolframalpha.com/input/?i=eigenvector%7B%7B0,h*b,h*c%7D,%7Bg*b,0,0%7D,%7Bg*c,0,0%7D%7D\n\t\t\t */\n\t\t\tif (k0 == 0 && k1 == 0)\n\t\t\t{\n\t\t\t\tv[0][0] = 1;\n\t\t\t\tv[1][0] = 0;\n\t\t\t\tv[2][0] = 0;\n\n\t\t\t\tv[0][1] = 0;\n\t\t\t\tv[1][1] = 1;\n\t\t\t\tv[2][1] = 0;\n\n\t\t\t\tv[0][2] = 0;\n\t\t\t\tv[1][2] = 0;\n\t\t\t\tv[2][2] = 1;\n\n\t\t\t\tif (i_evalues){\n\t\t\t\t\tlambda[0] = 0;\n\t\t\t\t\tlambda[1] = 0;\n\t\t\t\t\tlambda[2] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (k0 == 0)\n\t\t\t{\n\t\t\t\tv[0][0] = 0;\n\t\t\t\tv[1][0] = 1;\n\t\t\t\tv[2][0] = 0;\n\n\t\t\t\tv[0][1] = -sqrt_h/sqrt_g;\n\t\t\t\tv[1][1] = 0;\n\t\t\t\tv[2][1] = 1;\n\n\t\t\t\tv[0][2] = sqrt_h/sqrt_g;\n\t\t\t\tv[1][2] = 0;\n\t\t\t\tv[2][2] = 1;\n\n\t\t\t\tif (i_evalues){\n\t\t\t\t\tlambda[0] = 0;\n\t\t\t\t\tlambda[1] = -c*sqrt_g*sqrt_h;\n\t\t\t\t\tlambda[2] = c*sqrt_g*sqrt_h;;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (k1 == 0)\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * http://www.wolframalpha.com/input/?i=eigenvector%7B%7B0,h*b,h*c*0%7D,%7Bg*b,0,0%7D,%7Bg*c*0,0,0%7D%7D\n\t\t\t\t */\n\n\t\t\t\tv[0][0] = 0;\n\t\t\t\tv[1][0] = 0;\n\t\t\t\tv[2][0] = 1;\n\n\t\t\t\tv[0][1] = -sqrt_h/sqrt_g;\n\t\t\t\tv[1][1] = 1;\n\t\t\t\tv[2][1] = 0;\n\n\t\t\t\tv[0][2] = sqrt_h/sqrt_g;\n\t\t\t\tv[1][2] = 1;\n\t\t\t\tv[2][2] = 0;\n\n\t\t\t\tif (i_evalues){\n\t\t\t\t\tlambda[0] = 0;\n\t\t\t\t\tlambda[1] = -b*sqrt_g*sqrt_h;\n\t\t\t\t\tlambda[2] = b*sqrt_g*sqrt_h;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tv[0][0] = 0;\n\t\t\t\tv[1][0] = -c/b;\n\t\t\t\tv[2][0] = 1.0;\n\n\t\t\t\tv[0][1] = -(sqrt_h*rexiFunctions.l_sqrtcplx(b*b + c*c))/(c*sqrt_g);\n\t\t\t\tv[1][1] = b/c;\n\t\t\t\tv[2][1] = 1.0;\n\n\t\t\t\tv[0][2] = (sqrt_h*rexiFunctions.l_sqrtcplx(b*b + c*c))/(c*sqrt_g);\n\t\t\t\tv[1][2] = b/c;\n\t\t\t\tv[2][2] = 1.0;\n\n\t\t\t\tif (i_evalues){\n\t\t\t\t\tlambda[0] = 0.0;\n\t\t\t\t\tlambda[1] = -rexiFunctions.l_sqrtcplx(b*b + c*c)*sqrt_h*sqrt_g;\n\t\t\t\t\tlambda[2] = rexiFunctions.l_sqrtcplx(b*b + c*c)*sqrt_h*sqrt_g;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (k0 == 0 && k1 == 0)\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * http://www.wolframalpha.com/input/?i=eigenvector%7B%7B0,0,0%7D,%7B0,0,f%7D,%7B0,-f,0%7D%7D\n\t\t\t\t */\n\t\t\t\tv[0][0] = 0;\n\t\t\t\tv[1][0] = -I;\n\t\t\t\tv[2][0] = 1;\n\n\t\t\t\tv[0][1] = 0;\n\t\t\t\tv[1][1] = I;\n\t\t\t\tv[2][1] = 1;\n\n\t\t\t\tv[0][2] = 1;\n\t\t\t\tv[1][2] = 0;\n\t\t\t\tv[2][2] = 0;\n\n\t\t\t\tif (i_evalues){\n\t\t\t\t\tlambda[0] = I*f;\n\t\t\t\t\tlambda[1] = -I*f;\n\t\t\t\t\tlambda[2] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (k0 == 0)\n\t\t\t{\n\t\t\t\t/*\n\t\t\t\t * http://www.wolframalpha.com/input/?i=eigenvector%7B%7B0,h*b*0,h*c%7D,%7Bg*b*0,0,f%7D,%7Bg*c,-f,0%7D%7D\n\t\t\t\t */\n\t\t\t\tv[0][0] = f/(c*g);\n\t\t\t\tv[1][0] = 1;\n\t\t\t\tv[2][0] = 0;\n\n\t\t\t\tv[0][1] = -(c*h)/rexiFunctions.l_sqrtcplx(-f*f + c*c*g*h);\n\t\t\t\tv[1][1] =  -f/rexiFunctions.l_sqrtcplx(-f*f + c*c*g*h);\n\t\t\t\tv[2][1] = 1;\n\n\t\t\t\tv[0][2] = (c*h)/rexiFunctions.l_sqrtcplx(-f*f + c*c*g*h);\n\t\t\t\tv[1][2] = f/rexiFunctions.l_sqrtcplx(-f*f + c*c*g*h);\n\t\t\t\tv[2][2] = 1;\n\n\t\t\t\tif (i_evalues){\n\t\t\t\t\tlambda[0] = 0;\n\t\t\t\t\tlambda[1] = -rexiFunctions.l_sqrtcplx(c*c*g*h-f*f);\n\t\t\t\t\tlambda[2] = rexiFunctions.l_sqrtcplx(c*c*g*h-f*f);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (k1 == 0)\n\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * http://www.wolframalpha.com/input/?i=eigenvector%7B%7B0,h*b,h*c*0%7D,%7Bg*b,0,f%7D,%7Bg*c*0,-f,0%7D%7D\n\t\t\t\t\t */\n\t\t\t\tv[0][0] = -f/(b*g);\n\t\t\t\tv[1][0] = 0;\n\t\t\t\tv[2][0] = 1;\n\n\t\t\t\tv[0][1] = -(b*h)/f;\n\t\t\t\tv[1][1] = rexiFunctions.l_sqrtcplx(-f*f + b*b*g*h)/f;\n\t\t\t\tv[2][1] = 1;\n\n\t\t\t\tv[0][2] = -(b*h)/f;\n\t\t\t\tv[1][2] = -rexiFunctions.l_sqrtcplx(-f*f + b*b*g*h)/f;\n\t\t\t\tv[2][2] = 1;\n\n\t\t\t\tif (i_evalues){\n\t\t\t\t\tlambda[0] = 0;\n\t\t\t\t\tlambda[1] = -rexiFunctions.l_sqrtcplx(b*b*g*h-f*f);\n\t\t\t\t\tlambda[2] = rexiFunctions.l_sqrtcplx(b*b*g*h-f*f);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t/*\n\t\t\t\t\t * Compute EV's of\n\t\t\t\t\t * Linear operator\n\t\t\t\t\t *\n\t\t\t\t\t * [ 0  hb  hc ]\n\t\t\t\t\t * [ gb  0   f ]\n\t\t\t\t\t * [ gc -f   0 ]\n\t\t\t\t\t *\n\t\t\t\t\t * http://www.wolframalpha.com/input/?i=eigenvector%7B%7B0,h*b,h*c%7D,%7Bg*b,0,f%7D,%7Bg*c,-f,0%7D%7D\n\t\t\t\t\t */\n\n\t\t\t\t\tv[0][0] = -f/(b*g);\n\t\t\t\t\tv[1][0] = -c/b;\n\t\t\t\t\tv[2][0] = 1.0;\n\n\t\t\t\t\tv[0][1] = -(c*f*h + b*h*rexiFunctions.l_sqrtcplx(-f*f + b*b*g*h + c*c*g*h))/(b*c*g*h + f*rexiFunctions.l_sqrtcplx(-f*f + b*b*g*h + c*c*g*h));\n\t\t\t\t\tv[1][1] = -(f*f - b*b*g*h)/(b*c*g*h + f*rexiFunctions.l_sqrtcplx(-f*f + b*b*g*h + c*c*g*h));\n\t\t\t\t\tv[2][1] = 1.0;\n\n\t\t\t\t\tv[0][2] = -(-c*f*h + b*h*rexiFunctions.l_sqrtcplx(-f*f + b*b*g*h + c*c*g*h))/(-b*c*g*h + f*rexiFunctions.l_sqrtcplx(-f*f + b*b*g*h + c*c*g*h));\n\t\t\t\t\tv[1][2] =  -(-f*f + b*b*g*h)/(-b*c*g*h + f*rexiFunctions.l_sqrtcplx(-f*f + b*b*g*h + c*c*g*h));\n\t\t\t\t\tv[2][2] = 1.0;\n\n\t\t\t\t\tif (i_evalues){\n\t\t\t\t\t\tlambda[0] = 0.0;\n\t\t\t\t\t\tlambda[1] = -rexiFunctions.l_sqrtcplx(b*b*g*h + c*c*g*h - f*f);\n\t\t\t\t\t\tlambda[2] =  rexiFunctions.l_sqrtcplx(b*b*g*h + c*c*g*h - f*f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\n\t\t\t/*\n\t\t\t * Invert Eigenvalue matrix\n\t\t\t */\n\n\t\tif (i_inverse){\n\t\t\tv_inv[0][0] =  (v[1][1]*v[2][2] - v[1][2]*v[2][1]);\n\t\t\tv_inv[0][1] = -(v[0][1]*v[2][2] - v[0][2]*v[2][1]);\n\t\t\tv_inv[0][2] =  (v[0][1]*v[1][2] - v[0][2]*v[1][1]);\n\n\t\t\tv_inv[1][0] = -(v[1][0]*v[2][2] - v[1][2]*v[2][0]);\n\t\t\tv_inv[1][1] =  (v[0][0]*v[2][2] - v[0][2]*v[2][0]);\n\t\t\tv_inv[1][2] = -(v[0][0]*v[1][2] - v[0][2]*v[1][0]);\n\n\t\t\tv_inv[2][0] =  (v[1][0]*v[2][1] - v[1][1]*v[2][0]);\n\t\t\tv_inv[2][1] = -(v[0][0]*v[2][1] - v[0][1]*v[2][0]);\n\t\t\tv_inv[2][2] =  (v[0][0]*v[1][1] - v[0][1]*v[1][0]);\n\n\t\t\tcomplex s = v[0][0]*v_inv[0][0] + v[0][1]*v_inv[1][0] + v[0][2]*v_inv[2][0];\n\n\t\t\tfor (int j = 0; j < 3; j++)\t{\n\t\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t\t\tv_inv[j][i] /= s;\n\t\t\t}\n\t\t\t//Return inverse matrix\n\t\t\tfor (int j = 0; j < 3; j++)\t{\n\t\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t\t\to_v[j][i] = v_inv[j][i] ;\n\t\t\t}\n\t\t}\t\n\t\telse{\n\t\t\t//Return direct matrix\n\t\t\tfor (int j = 0; j < 3; j++)\t{\n\t\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t\t\to_v[j][i] = v[j][i] ;\n\t\t\t}\n\t\t}\n\t\tif (i_evalues){\n\t\t\tfor (int j = 0; j < 3; j++)\t{\n\t\t\t\to_evalues[j] = lambda[j] ;\n\t\t\t}\n\t\t}\n\t\treturn;\n}\n\n\n\ttemplate <typename TCallbackClass>\n\tstatic\n\tvoid normal_mode_analysis(\n\t\t\tPlaneData_Spectral &io_prog_h_pert, // h: surface height (perturbation)\n\t\t\tPlaneData_Spectral &io_prog_u, // u: velocity in x-direction\n\t\t\tPlaneData_Spectral &io_prog_v, // v: velocity in y-direction\n\t\t\tint number_of_prognostic_variables,\n\t\t\tSimulationVariables &i_simVars, // Simulation variables\n\t\t\tTCallbackClass *i_class,\n\t\t\tvoid(TCallbackClass::* const i_run_timestep_method)(void)\n\t)\n\t{\n\n\t\tconst PlaneDataConfig *planeDataConfig = io_prog_h_pert.planeDataConfig;\n\n\t\t// dummy time step to get time step size\n\t\tif (i_simVars.timecontrol.current_timestep_size <= 0)\n\t\t\tSWEETError(\"Normal mode analysis requires setting fixed time step size\");\n\n\t\t/*\n\t\t *\n\t\t * Mode-wise normal mode analysis\n\t\t *\n\t\t *\n\t\t */\n\n\t\tif (i_simVars.misc.normal_mode_analysis_generation == 4)\n\t\t{\n#if SWEET_EIGEN\n#if SWEET_USE_PLANE_SPECTRAL_DEALIASING\n\t\t\tSWEETError(\"SWE_Plane_Normal_Modes: This test was build for linear or linearized models, so please compile without dealising --plane-spectral-dealiasing=disable.\");\n#endif\n\n\n\t\t\t/*\n\t\t\t * Setup all output files\n\t\t\t */\n\t\t\tconst char* filename; //general filename\n\t\t\tchar buffer_real[1024];\n\n\t\t\tif (i_simVars.iodata.output_file_name == \"\")\n\t\t\t\tfilename = \"output_%s_t%020.8f.csv\";\n\t\t\telse\n\t\t\t\tfilename = i_simVars.iodata.output_file_name.c_str();\n\n\t\t\tsprintf(buffer_real, filename, \"normal_modes_plane\", i_simVars.timecontrol.current_timestep_size*i_simVars.iodata.output_time_scale);\n\t\t\tstd::ofstream file(buffer_real, std::ios_base::trunc);\n\t\t\tstd::cout << \"Writing normal mode analysis to files of the form '\" << buffer_real << \"'\" << std::endl;\n\n\t\t\t//Positive inertia-gravity modes\n\t\t\tsprintf(buffer_real, filename, \"normal_modes_plane_igpos\", i_simVars.timecontrol.current_timestep_size*i_simVars.iodata.output_time_scale);\n\t\t\tstd::ofstream file_igpos(buffer_real, std::ios_base::trunc);\n\n\t\t\t//Negative inertia-gravity modes\n\t\t\tsprintf(buffer_real, filename, \"normal_modes_plane_igneg\", i_simVars.timecontrol.current_timestep_size*i_simVars.iodata.output_time_scale);\n\t\t\tstd::ofstream file_igneg(buffer_real, std::ios_base::trunc);\n\n\t\t\t//Geostrophic modes\n\t\t\tsprintf(buffer_real, filename, \"normal_modes_plane_geo\", i_simVars.timecontrol.current_timestep_size*i_simVars.iodata.output_time_scale);\n\t\t\tstd::ofstream file_geo(buffer_real, std::ios_base::trunc);\n\n\t\t\t//std::cout << \"WARNING: OUTPUT IS TRANSPOSED!\" << std::endl;\n\n\t\t\t// use very high precision\n\t\t\tfile << std::setprecision(20);\n\t\t\tfile_igpos << std::setprecision(20);\n\t\t\tfile_igneg << std::setprecision(20);\n\t\t\tfile_geo << std::setprecision(20);\n\n\t\t\tfile << \"# dt \" << i_simVars.timecontrol.current_timestep_size << std::endl;\n\t\t\tfile << \"# g \" << i_simVars.sim.gravitation << std::endl;\n\t\t\tfile << \"# h \" << i_simVars.sim.h0 << std::endl;\n\t\t\tfile << \"# r \" << i_simVars.sim.sphere_radius << std::endl;\n\t\t\tfile << \"# f \" << i_simVars.sim.plane_rotating_f0 << std::endl;\n\n#if SWEET_USE_PLANE_SPECTRAL_SPACE\n\t\t\tint specmodes = planeDataConfig->get_spectral_iteration_range_area(0)+planeDataConfig->get_spectral_iteration_range_area(1);\n\t\t\tfile << \"# specnummodes \" << specmodes << std::endl;\n\t\t\tfile << \"# specrealresx \" << planeDataConfig->spectral_real_modes[0] << std::endl;\n\t\t\tfile << \"# specrealresy \" << planeDataConfig->spectral_real_modes[1] << std::endl;\n#endif\n\n\t\t\tfile << \"# physresx \" << planeDataConfig->physical_res[0] << std::endl;\n\t\t\tfile << \"# physresy \" << planeDataConfig->physical_res[1] << std::endl;\n\t\t\tfile << \"# normalmodegeneration \" << i_simVars.misc.normal_mode_analysis_generation << std::endl;\n\t\t\tfile << \"# antialiasing \";\n#if SWEET_USE_PLANE_SPECTRAL_DEALIASING\n\t\t\tfile << 1;\n#else\n\t\t\tfile << 0;\n#endif\n\t\t\tfile << std::endl;\n\n\t\t\tPlaneData_Spectral* prog[3] = {&io_prog_h_pert, &io_prog_u, &io_prog_v};\n\n\t\t\tint number_of_prognostic_variables = 3;\n\t\t\t//The basic state is with zero in all variables\n\t\t\t// The only non zero variable in the basic state is the total height\n\t\t\t//    for which the constant is added within run_timestep()\n\t\t\tio_prog_h_pert.spectral_set_zero();\n\t\t\tio_prog_u.spectral_set_zero();\n\t\t\tio_prog_v.spectral_set_zero();\n\n\t\t\t//int num_timesteps = 1;\n\n\t\t\t// Timestep and perturbation\n\t\t\tdouble dt = i_simVars.timecontrol.current_timestep_size;\n\t\t\tdouble eps = dt;\n\n\t\t\t//Matrix representing discrete linear operator in spectral space\n\t\t\tEigen::MatrixXcf A(3,3) ;\n\t\t\t//Eigen solver\n\t\t\tEigen::ComplexEigenSolver<Eigen::MatrixXcf> ces;\n\t\t\t//Final eigenvalues\n\t\t\tstd::complex<double> eval[3];\n\n\t\t\t//For each spectral mode\n\t\t\t//for (int r = 0; r < 2; r++) //only required to get the symmetric half of the spectrum\n\t\t\t//{\n\t\t\tint r = 0;\n\n\t\t\tfor (std::size_t i = planeDataConfig->spectral_data_iteration_ranges[r][0][0]; i < planeDataConfig->spectral_data_iteration_ranges[r][0][1]; i++)\n\t\t\t{\n\t\t\t\tstd::cout << \".\" << std::flush;\n\t\t\t\tfor (std::size_t j = planeDataConfig->spectral_data_iteration_ranges[r][1][0]; j < planeDataConfig->spectral_data_iteration_ranges[r][1][1]; j++)\n\t\t\t\t{\n\t\t\t\t\t//This is the mode to be analysed\n\t\t\t\t\t//std::cout << \"Mode (i,j)= (\" << i << \" , \" << j <<\")\"<< std::endl;\n\n\n\t\t\t\t\tfor (int outer_prog_id = 0; outer_prog_id < number_of_prognostic_variables; outer_prog_id++)\n\t\t\t\t\t{\n\n\t\t\t\t\t\t// reset time control\n\t\t\t\t\t\ti_simVars.timecontrol.current_timestep_nr = 0;\n\t\t\t\t\t\ti_simVars.timecontrol.current_simulation_time = 0;\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\tprog[inner_prog_id]->spectral_set_zero();\n\n\t\t\t\t\t\t// activate mode via real coefficient\n\t\t\t\t\t\tprog[outer_prog_id]->spectral_set(j, i, 1.0);\n\t\t\t\t\t\t//Activate the symetric couterpart of the mode (only needed if j>0 )\n\t\t\t\t\t\tif (j > 0)\n\t\t\t\t\t\t\tprog[outer_prog_id]->spectral_set(planeDataConfig->spectral_data_size[1]-j, i, 1.0);\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * RUN timestep\n\t\t\t\t\t\t */\n\t\t\t\t\t\t(i_class->*i_run_timestep_method)();\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * compute\n\t\t\t\t\t\t * 1/dt * (U(t+1) - U(t))\n\t\t\t\t\t\t */\n\n\t\t\t\t\t\tstd::complex<double> val = prog[outer_prog_id]->spectral_get(j, i);\n\t\t\t\t\t\tval = val - 1.0; //subtract U(0) from mode\n\t\t\t\t\t\tprog[outer_prog_id]->spectral_set(j, i, val);\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t(*prog[inner_prog_id]) /= eps;\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tA(inner_prog_id,outer_prog_id)=prog[inner_prog_id]->spectral_get(j, i);;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\t//std::cout << \"Lik matrix\" << std::endl;\n\t\t\t\t\t//std::cout << A << std::endl;\n\n\t\t\t\t\t//std::cout<<\"Normal modes\" << std::endl;\n\t\t\t\t\tces.compute(A);\n\t\t\t\t\tfor(int i=0; i<3; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\teval[i]=ces.eigenvalues()[i];\n\t\t\t\t\t\t//std::cout << \"Eigenvalue \"<< i << \" : \" << eval[i].real() <<\" \"<<eval[i].imag() << std::endl;\n\n\t\t\t\t\t}\n\t\t\t\t\t/* We will try to separate the modes in 3 types:\n\t\t\t\t\t * -positive inertia-gravity (imag>f) - we will adopt coriolis f to test as if > zero, since the exact freq is sqrt(f^2+cK*K)\n\t\t\t\t\t * -negative inertia-gravity (imag<-f)\n\t\t\t\t\t * -negative inertia-gravity (imag aprox 0) - we will fit all other modes here\n\t\t\t\t\t */\n\t\t\t\t\tint count_igpos=0;\n\t\t\t\t\tint count_igneg=0;\n\t\t\t\t\tint count_geo=0;\n\t\t\t\t\tfor(int i=0; i<3; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(eval[i].imag() > 0.5 * i_simVars.sim.plane_rotating_f0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//std::cout<< \"IG pos mode: \" << eval[i].imag() << std::endl;\n\t\t\t\t\t\t\t//file_igpos << eval[i].imag();\n\t\t\t\t\t\t\tfile_igpos << eval[i].real()<< \"\\t\" << eval[i].imag();\n\t\t\t\t\t\t\tfile_igpos << \"\\t\";\n\t\t\t\t\t\t\tcount_igpos++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(eval[i].imag() < - 0.5 * i_simVars.sim.plane_rotating_f0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//std::cout<< \"IG neg mode: \" << eval[i].imag() << std::endl;\n\t\t\t\t\t\t\t//file_igneg << eval[i].imag();\n\t\t\t\t\t\t\tfile_igneg << eval[i].real()<< \"\\t\" << eval[i].imag();\n\t\t\t\t\t\t\tfile_igneg << \"\\t\";\n\t\t\t\t\t\t\tcount_igneg++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(eval[i].imag() >= - 0.5 * i_simVars.sim.plane_rotating_f0 && eval[i].imag() <=  0.5 * i_simVars.sim.plane_rotating_f0 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//std::cout<< \"IG geo mode: \" << eval[i].imag() << std::endl;\n\t\t\t\t\t\t\t//file_geo << eval[i].imag();\n\t\t\t\t\t\t\tfile_geo << eval[i].real()<< \"\\t\" << eval[i].imag();\n\t\t\t\t\t\t\tfile_geo << \"\\t\";\n\t\t\t\t\t\t\tcount_geo++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t//Check if we got the correct modes\n\t\t\t\t\tif ( count_igpos * count_igneg * count_geo > 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tcount_igpos=0;\n\t\t\t\t\t\tcount_igneg=0;\n\t\t\t\t\t\tcount_geo=0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tSWEETError(\"SWE_Plane_Normal_Modes: Could not separate modes!!\");\n\t\t\t\t\t}\n\n\t\t\t\t\t//std::cout<<\"-------------------------\" << std::endl;\n\t\t\t\t}\n\t\t\t\tfile_igpos << std::endl;\n\t\t\t\tfile_igneg << std::endl;\n\t\t\t\tfile_geo << std::endl;\n\t\t\t}\n\n\t\t\t//}\n\t\t\t//std::cout<<\"-------------------------\" << std::endl;\n\t\t\t//SWEETError(\"still needs work...\");\n#else\n\t\t\tSWEETError(\"SWE_Plane_Normal_Modes: Cannot test this without Eigen library. Please compile with --eigen=enable\");\n#endif\n\t\t}\n\t\t/*\n\t\t * Do a normal mode analysis using perturbation, see\n\t\t * Hillary Weller, John Thuburn, Collin J. Cotter,\n\t\t * \"Computational Modes and Grid Imprinting on Five Quasi-Uniform Spherical C Grids\"\n\t\t */\n\t\telse\n\t\t{\n\n\t\t\t//run_timestep();\n\t\t\tconst char* filename;\n\t\t\tchar buffer_real[1024];\n\n\t\t\tif (i_simVars.iodata.output_file_name == \"\")\n\t\t\t\tfilename = \"output_%s_normalmodes.csv\";\n\t\t\telse\n\t\t\t\tfilename = i_simVars.iodata.output_file_name.c_str();\n\n\n\t\t\tsprintf(buffer_real, filename, \"normal_modes_physical\", i_simVars.timecontrol.current_timestep_size*i_simVars.iodata.output_time_scale);\n\t\t\tstd::ofstream file(buffer_real, std::ios_base::trunc);\n\t\t\tstd::cout << \"Writing normal mode analysis to file '\" << buffer_real << \"'\" << std::endl;\n\n\t\t\tstd::cout << \"WARNING: OUTPUT IS TRANSPOSED!\" << std::endl;\n\n\t\t\t// use very high precision\n\t\t\tfile << std::setprecision(20);\n\n\t\t\tPlaneData_Spectral* prog[3] = {&io_prog_h_pert, &io_prog_u, &io_prog_v};\n\n\t\t\t/*\n\t\t\t * Maximum number of prognostic variables\n\t\t\t *\n\t\t\t * Advection e.g. has only one\n\t\t\t */\n\t\t\tif (number_of_prognostic_variables <= 0)\n\t\t\t\tSWEETError(\"simVars.pde.number_of_prognostic_variables must be set!\");\n\n\t\t\tif (number_of_prognostic_variables == 3)\n\t\t\t{\n\t\t\t\tio_prog_h_pert.spectral_set_zero();\n\t\t\t\tio_prog_u.spectral_set_zero();\n\t\t\t\tio_prog_v.spectral_set_zero();\n\t\t\t}\n\t\t\telse if (number_of_prognostic_variables == 1)\n\t\t\t{\n\t\t\t\tio_prog_h_pert.spectral_set_zero();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tSWEETError(\"Not yet supported\");\n\t\t\t}\n\n#if 0\n\t\t\tif (i_simVars.disc.timestepping_method == SimulationVariables::Discretization::LEAPFROG_EXPLICIT)\n\t\t\t{\n\t\t\t\tSWEETError(\"Not yet tested and supported\");\n\t\t\t\tstd::cout << \"WARNING: Leapfrog time stepping doesn't make real sense since 1st step is based on RK-like method\" << std::endl;\n\t\t\t\tstd::cout << \"We'll do two Leapfrog time steps here to take the LF errors into account!\" << std::endl;\n\t\t\t\tstd::cout << \"Therefore, we also halve the time step size here\" << std::endl;\n\n\t\t\t\ti_simVars.timecontrol.current_timestep_size = 0.5*i_simVars.sim.CFL;\n\t\t\t\ti_simVars.sim.CFL = -i_simVars.timecontrol.current_timestep_size;\n\t\t\t}\n#endif\n\n\t\t\tint num_timesteps = 1;\n\t\t\tif (i_simVars.misc.normal_mode_analysis_generation >= 10)\n\t\t\t{\n\t\t\t\tif (i_simVars.timecontrol.max_timesteps_nr > 0)\n\t\t\t\t\tnum_timesteps = i_simVars.timecontrol.max_timesteps_nr;\n\t\t\t}\n\n\t\t\tif (i_simVars.timecontrol.max_simulation_time > 0)\n\t\t\t\tfile << \"# t \" << i_simVars.timecontrol.max_simulation_time << std::endl;\n\t\t\telse\n\t\t\t\tfile << \"# t \" << (num_timesteps*(-i_simVars.timecontrol.current_timestep_size)) << std::endl;\n\n\t\t\tfile << \"# g \" << i_simVars.sim.gravitation << std::endl;\n\t\t\tfile << \"# h \" << i_simVars.sim.h0 << std::endl;\n//\t\t\tfile << \"# r \" << i_simVars.sim.sphere_radius << std::endl;\n\t\t\tfile << \"# f \" << i_simVars.sim.plane_rotating_f0 << std::endl;\n\n#if SWEET_USE_PLANE_SPECTRAL_SPACE\n\t\t\tint specmodes = planeDataConfig->get_spectral_iteration_range_area(0)+planeDataConfig->get_spectral_iteration_range_area(1);\n\t\t\tfile << \"# specnummodes \" << specmodes << std::endl;\n\t\t\tfile << \"# specrealresx \" << planeDataConfig->spectral_real_modes[0] << std::endl;\n\t\t\tfile << \"# specrealresy \" << planeDataConfig->spectral_real_modes[1] << std::endl;\n#endif\n\n\t\t\tfile << \"# physresx \" << planeDataConfig->physical_res[0] << std::endl;\n\t\t\tfile << \"# physresy \" << planeDataConfig->physical_res[1] << std::endl;\n\t\t\tfile << \"# normalmodegeneration \" << i_simVars.misc.normal_mode_analysis_generation << std::endl;\n\t\t\tfile << \"# antialiasing \";\n\n#if SWEET_USE_PLANE_SPECTRAL_DEALIASING\n\t\t\tfile << 1;\n#else\n\t\t\tfile << 0;\n#endif\n\n\t\t\tfile << std::endl;\n\n\n\t\t\t// iterate over all prognostic variables\n\t\t\tfor (int outer_prog_id = 0; outer_prog_id < number_of_prognostic_variables; outer_prog_id++)\n\t\t\t{\n\t\t\t\tif (i_simVars.misc.normal_mode_analysis_generation == 1 || i_simVars.misc.normal_mode_analysis_generation == 11)\n\t\t\t\t{\n\t\t\t\t\t// iterate over physical space\n\t\t\t\t\tfor (std::size_t outer_i = 0; outer_i < planeDataConfig->physical_array_data_number_of_elements; outer_i++)\n\t\t\t\t\t{\n\t\t\t\t\t\t// reset time control\n\t\t\t\t\t\ti_simVars.timecontrol.current_timestep_nr = 0;\n\t\t\t\t\t\ti_simVars.timecontrol.current_simulation_time = 0;\n\n\t\t\t\t\t\tstd::cout << \".\" << std::flush;\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\tprog[inner_prog_id]->spectral_set_zero();\n\n\t\t\t\t\t\t// activate mode\n\t\t\t\t\t\tPlaneData_Physical tmp = prog[outer_prog_id]->toPhys();\n\t\t\t\t\t\ttmp.physical_space_data[outer_i] = 1;\n\t\t\t\t\t\tprog[outer_prog_id]->loadPlaneDataPhysical(tmp);\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * RUN timestep\n\t\t\t\t\t\t */\n\n\t\t\t\t\t\t(i_class->*i_run_timestep_method)();\n\n\t\t\t\t\t\tif (i_simVars.misc.normal_mode_analysis_generation == 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * compute\n\t\t\t\t\t\t\t * 1/dt * (U(t+1) - U(t))\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\ttmp = prog[outer_prog_id]->toPhys();\n\t\t\t\t\t\t\ttmp.physical_space_data[outer_i] -= 1.0;\n\t\t\t\t\t\t\tprog[outer_prog_id]->loadPlaneDataPhysical(tmp);\n\n\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\t(*prog[inner_prog_id]) /= i_simVars.timecontrol.current_timestep_size;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttmp = prog[outer_prog_id]->toPhys();\n\t\t\t\t\t\t\tfor (std::size_t k = 0; k < planeDataConfig->physical_array_data_number_of_elements; k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfile << tmp.physical_space_data[k];\n\t\t\t\t\t\t\t\tif (inner_prog_id != number_of_prognostic_variables-1 || k != planeDataConfig->physical_array_data_number_of_elements-1)\n\t\t\t\t\t\t\t\t\tfile << \"\\t\";\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tfile << std::endl;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n#if 1\n\t\t\t\telse if (i_simVars.misc.normal_mode_analysis_generation == 3 || i_simVars.misc.normal_mode_analysis_generation == 13)\n\t\t\t\t{\n#if !SWEET_USE_PLANE_SPECTRAL_SPACE\n\t\t\t\t\tSWEETError(\"Only available with if plane spectral space is activated during compile time!\");\n#else\n\n\t\t\t\t\t// iterate over spectral space\n\t\t\t\t\tfor (int r = 0; r < 2; r++)\n\t\t\t\t\t{\n\n\t\t\t\t\t\tfor (std::size_t j = planeDataConfig->spectral_data_iteration_ranges[r][1][0]; j < planeDataConfig->spectral_data_iteration_ranges[r][1][1]; j++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor (std::size_t i = planeDataConfig->spectral_data_iteration_ranges[r][0][0]; i < planeDataConfig->spectral_data_iteration_ranges[r][0][1]; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t// reset time control\n\t\t\t\t\t\t\t\ti_simVars.timecontrol.current_timestep_nr = 0;\n\t\t\t\t\t\t\t\ti_simVars.timecontrol.current_simulation_time = 0;\n\n\t\t\t\t\t\t\t\tstd::cout << \".\" << std::flush;\n\n\t\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\t\tprog[inner_prog_id]->spectral_set_zero();\n\n\t\t\t\t\t\t\t\t// activate mode via real coefficient\n\t\t\t\t\t\t\t\tprog[outer_prog_id]->spectral_set(j, i, 1.0);\n\n\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t * RUN timestep\n\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\t(i_class->*i_run_timestep_method)();\n\n\n\t\t\t\t\t\t\t\tif (i_simVars.misc.normal_mode_analysis_generation == 3)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\t * compute\n\t\t\t\t\t\t\t\t\t * 1/dt * (U(t+1) - U(t))\n\t\t\t\t\t\t\t\t\t */\n\n\t\t\t\t\t\t\t\t\tstd::complex<double> val = prog[outer_prog_id]->spectral_get(j, i);\n\t\t\t\t\t\t\t\t\tval = val - 1.0;\n\t\t\t\t\t\t\t\t\tprog[outer_prog_id]->spectral_set(j, i, val);\n\n\t\t\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\t\t\t(*prog[inner_prog_id]) /= i_simVars.timecontrol.current_timestep_size;\n\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\t * REAL\n\t\t\t\t\t\t\t\t\t */\n\n\t\t\t\t\t\t\t\t\tfor (int r = 0; r < 2; r++)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tfor (std::size_t j = planeDataConfig->spectral_data_iteration_ranges[r][1][0]; j < planeDataConfig->spectral_data_iteration_ranges[r][1][1]; j++)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tfor (std::size_t i = planeDataConfig->spectral_data_iteration_ranges[r][0][0]; i < planeDataConfig->spectral_data_iteration_ranges[r][0][1]; i++)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tfile << prog[inner_prog_id]->spectral_get(j, i).real();\n\t\t\t\t\t\t\t\t\t\t\t\tfile << \"\\t\";\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\t\t * IMAG\n\t\t\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\t\t\tint c = 0;\n\t\t\t\t\t\t\t\t\tfor (int r = 0; r < 2; r++)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tfor (std::size_t j = planeDataConfig->spectral_data_iteration_ranges[r][1][0]; j < planeDataConfig->spectral_data_iteration_ranges[r][1][1]; j++)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tfor (std::size_t i = planeDataConfig->spectral_data_iteration_ranges[r][0][0]; i < planeDataConfig->spectral_data_iteration_ranges[r][0][1]; i++)\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tfile << prog[inner_prog_id]->spectral_get(j, i).imag();\n\n\t\t\t\t\t\t\t\t\t\t\t\tif (inner_prog_id != number_of_prognostic_variables-1 || c != specmodes-1)\n\t\t\t\t\t\t\t\t\t\t\t\t\tfile << \"\\t\";\n\t\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\t\tfile << std::endl;\n\n\t\t\t\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n#endif\n\t\t\t\t}\n#else\n\t\t\t\telse if (i_simVars.misc.normal_mode_analysis_generation == 3 || i_simVars.misc.normal_mode_analysis_generation == 13)\n\t\t\t\t{\n\t\t\t\t\tPlaneDataComplex t1(planeDataConfig);\n\t\t\t\t\tPlaneDataComplex t2(planeDataConfig);\n\t\t\t\t\tPlaneDataComplex t3(planeDataConfig);\n\t\t\t\t\tPlaneDataComplex* prog_cplx[3] = {&t1, &t2, &t3};\n\n\t\t\t\t\t// iterate over spectral space\n\t\t\t\t\tfor (std::size_t outer_i = 0; outer_i < planeDataConfig->spectral_complex_array_data_number_of_elements; outer_i++)\n\t\t\t\t\t{\n\t\t\t\t\t\t// reset time control\n\t\t\t\t\t\ti_simVars.timecontrol.current_timestep_nr = 0;\n\t\t\t\t\t\ti_simVars.timecontrol.current_simulation_time = 0;\n\n\t\t\t\t\t\tstd::cout << \".\" << std::flush;\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\tprog_cplx[inner_prog_id]->spectral_set_zero();\n\n\t\t\t\t\t\t// activate mode via real coefficient\n\t\t\t\t\t\tprog_cplx[outer_prog_id]->request_data_spectral();\n\t\t\t\t\t\tprog_cplx[outer_prog_id]->spectral_space_data[outer_i].real(1);\n\n\t\t\t\t\t\t// convert PlaneDataComplex to PlaneData\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t*prog[inner_prog_id] = Convert_PlaneDataComplex_To_PlaneData::physical_convert(*prog_cplx[inner_prog_id]);\n\t\t\t\t\t\t\tprog[inner_prog_id]->spectral_zeroAliasingModes();\n\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * RUN timestep\n\t\t\t\t\t\t */\n\t\t\t\t\t\t(i_class->*i_run_timestep_method)();\n\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprog[inner_prog_id]->spectral_zeroAliasingModes();\n#warning \"update this physical_convert maybe to spectral_convert\"\n\n\t\t\t\t\t\t\t*prog_cplx[inner_prog_id] = Convert_PlaneData_To_PlaneDataComplex::physical_convert(*prog[inner_prog_id]);\n\n\t\t\t\t\t\t\tprog_cplx[inner_prog_id]->request_data_spectral();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (i_simVars.misc.normal_mode_analysis_generation == 3)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * compute\n\t\t\t\t\t\t\t * 1/dt * (U(t+1) - U(t))\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tprog_cplx[outer_prog_id]->request_data_spectral();\n\t\t\t\t\t\t\tprog_cplx[outer_prog_id]->spectral_space_data[outer_i] -= 1.0;\n\n\t\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t\t\tprog_cplx[inner_prog_id]->operator*=(1.0/i_simVars.timecontrol.current_timestep_size);\n\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t// convert PlaneDataComplex to PlaneData\n\t\t\t\t\t\tfor (int inner_prog_id = 0; inner_prog_id < number_of_prognostic_variables; inner_prog_id++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tprog_cplx[inner_prog_id]->request_data_spectral();\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * REAL\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tfor (std::size_t k = 0; k < planeDataConfig->spectral_complex_array_data_number_of_elements; k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfile << prog_cplx[inner_prog_id]->spectral_space_data[k].real();\n\t\t\t\t\t\t\t\tfile << \"\\t\";\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t * IMAG\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tfor (std::size_t k = 0; k < planeDataConfig->spectral_complex_array_data_number_of_elements; k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfile << prog_cplx[inner_prog_id]->spectral_space_data[k].imag();\n\n\t\t\t\t\t\t\t\tif (inner_prog_id != number_of_prognostic_variables-1 || k != planeDataConfig->spectral_complex_array_data_number_of_elements-1)\n\t\t\t\t\t\t\t\t\tfile << \"\\t\";\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tfile << std::endl;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n#endif\n\t\t\t}\n\t\t}\n\t}\n\n\n\t~SWE_Plane_Normal_Modes()\n\t{\n\n\t}\n};\n\n#endif /* SRC_PROGRAMS_SWE_PLANE_NORMAL_MODES_HPP_ */\n", "meta": {"hexsha": "dcb3f713611bc1cc1d769084a44bf77655858eb9", "size": 35788, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/unit_tests/test_plane_sw_normal_modes/SWE_Plane_Normal_Modes.hpp", "max_stars_repo_name": "schreibm/sweet", "max_stars_repo_head_hexsha": "a1b97e5862c3871177dff877dff825fd4b98a085", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/unit_tests/test_plane_sw_normal_modes/SWE_Plane_Normal_Modes.hpp", "max_issues_repo_name": "schreibm/sweet", "max_issues_repo_head_hexsha": "a1b97e5862c3871177dff877dff825fd4b98a085", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/unit_tests/test_plane_sw_normal_modes/SWE_Plane_Normal_Modes.hpp", "max_forks_repo_name": "schreibm/sweet", "max_forks_repo_head_hexsha": "a1b97e5862c3871177dff877dff825fd4b98a085", "max_forks_repo_licenses": ["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.7193133047, "max_line_length": 167, "alphanum_fraction": 0.6195093327, "num_tokens": 11890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6401311413413625}}
{"text": "#include <RcppEigen.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n\n// [[Rcpp::depends(RcppEigen)]]\nusing namespace Rcpp;\nusing Eigen::Map;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::DiagonalMatrix;\n\n\n// [[Rcpp::export]]\nfloat r_score(Eigen::MatrixXd x, Eigen::MatrixXd x0) {\n  int nr = x.rows();\n  int nc = x.cols();\n  int n0r = x0.rows();\n  Eigen::MatrixXd A  = x.transpose()*((x*x.transpose()+MatrixXd::Identity(nr, nr)*(1.0/nc)).inverse());\n  Eigen::MatrixXd IJ = MatrixXd::Identity(n0r, n0r)-(MatrixXd::Identity(n0r, n0r)*(1.0/n0r));\n  float q1 = n0r-1+(IJ*x0).array().square().sum();\n  Eigen::MatrixXd IJX0A = IJ*x0*A;\n  Eigen::MatrixXd IJX0AX = IJX0A*x;\n  float q2 = IJX0A.array().square().sum() + IJX0AX.array().square().sum();\n  float q12 = (x0.transpose()*IJX0AX).trace();\n  return q12/(sqrt(q1*q2));\n}\n\n\n\n// [[Rcpp::export]]\nfloat pev_score(Eigen::MatrixXd X, Eigen::MatrixXd X0){\n  int p = X.cols();\n  int n = X.rows();\n  int n0 = X0.rows();\n  Eigen::MatrixXd x(n,p+1);\n  x << (Eigen::ArrayXd::Zero(n)+1), X;\n  Eigen::MatrixXd x0(n0,p+1);\n  x0 << (Eigen::ArrayXd::Zero(n0)+1), X0;\n  return (x0*((x.transpose()*x+(Eigen::MatrixXd::Identity(p+1,p+1)*(1.0/p))).inverse())*x0.transpose()).trace();\n}\n\n\n\n// [[Rcpp::export]]\nfloat cd_score(Eigen::MatrixXd x, Eigen::MatrixXd x0){\n  int p = x.cols();\n  Eigen::MatrixXd cd = x0*(x.transpose()*x+(Eigen::MatrixXd::Identity(p,p)*1.0)).inverse()*x.transpose();\n  return (((cd*cd.transpose()).diagonal().array())/((x0*x0.transpose()).diagonal().array())).mean();\n}\n", "meta": {"hexsha": "9307fe082d742d2e72b1fbacd33784f2ce848a17", "size": 1533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/functions_cpp.cpp", "max_stars_repo_name": "oumarkme/TSDFGS", "max_stars_repo_head_hexsha": "38641ef805f07c7f8ce91127cb1f4d9b00d4613b", "max_stars_repo_licenses": ["MIT"], "max_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_cpp.cpp", "max_issues_repo_name": "oumarkme/TSDFGS", "max_issues_repo_head_hexsha": "38641ef805f07c7f8ce91127cb1f4d9b00d4613b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/functions_cpp.cpp", "max_forks_repo_name": "oumarkme/TSDFGS", "max_forks_repo_head_hexsha": "38641ef805f07c7f8ce91127cb1f4d9b00d4613b", "max_forks_repo_licenses": ["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.0588235294, "max_line_length": 112, "alphanum_fraction": 0.6314416177, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.6400328826285587}}
{"text": "#include <vector>\n#include <boost/math/distributions/students_t.hpp>\n#include \"students_t_dist.h\"\n\nstochastic::StudentstDistribution::StudentstDistribution(double mean,\n                                                         double std_dev,\n                                                         double dof)\n    : Distribution(),\n      mean_{mean},\n      std_dev_{std_dev},\n      dof_{dof},\n      distribution_{dof_}\n{}\n\nstd::vector<double> stochastic::StudentstDistribution::cumulative_dist_func(\n    const std::vector<double>& locations) const {\n  std::vector<double> evaluations(locations.size());\n\n  for (unsigned int i = 0; i < locations.size(); ++i) {\n    evaluations[i] = cdf(distribution_, (locations[i] - mean_) / std_dev_);\n  }\n\n  return evaluations;\n}\n\nstd::vector<double> stochastic::StudentstDistribution::inv_cumulative_dist_func(\n    const std::vector<double>& probabilities) const {\n  std::vector<double> evaluations(probabilities.size());\n\n  for (unsigned int i = 0; i < probabilities.size(); ++i) {\n    evaluations[i] =\n        std_dev_ * quantile(distribution_, probabilities[i]) + mean_;\n  }\n\n  return evaluations;\n}\n", "meta": {"hexsha": "7b44f6a6a83037d3121d7919c1b724814fcd00aa", "size": 1140, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/students_t_dist.cc", "max_stars_repo_name": "charlesxwang/smelt", "max_stars_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "src/students_t_dist.cc", "max_issues_repo_name": "charlesxwang/smelt", "max_issues_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "src/students_t_dist.cc", "max_forks_repo_name": "charlesxwang/smelt", "max_forks_repo_head_hexsha": "da1f66ec857dd8ff8e9de104fbb3ecbd0ec84367", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 30.8108108108, "max_line_length": 80, "alphanum_fraction": 0.6342105263, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6400142403791703}}
{"text": "#define ARMA_ALLOW_FAKE_GCC\n#define ARMA_NO_DEBUG\n\n#include \"TimeSeries.hpp\"\n\n#include <armadillo>\n#include <cmath>\n#include <iostream>\n#include <string>\n\nusing namespace arma;\n\nnamespace TimeSeries {\n\n/*\n * Discretize Normal for given grid.\n */\nvec discretizeNormal(vec grid,\n    const double mean,\n    const double sigma,\n    bool cutTails)\n{\n  uword sz = grid.n_elem;\n  vec prs(sz);\n\n  if (sz == 1) {\n    [[unlikely]] prs(0) = 1.0;\n    return prs;\n  } else if (sz == 2) {\n    [[unlikely]] prs(0) = normcdf((grid(0) + grid(1)) / 2.0, mean, sigma);\n    prs(1) = 1.0 - prs(0);\n    return prs;\n  }\n\n#pragma omp parallel for\n  for (uword ix = 1; ix < sz - 1; ++ix)\n    prs(ix) = normcdf((grid(ix) + grid(ix + 1)) / 2.0, mean, sigma) - normcdf((grid(ix - 1) + grid(ix)) / 2.0, mean, sigma);\n\n  if (cutTails) {\n    const double stepOut = (grid(1) - grid(0)) / 2.0;\n    prs(0) = normcdf(grid(0) + stepOut, mean, sigma) - normcdf(grid(0) - stepOut, mean, sigma);\n    prs(sz - 1) = normcdf(grid(sz - 1) + stepOut, mean, sigma) - normcdf(grid(sz - 1) - stepOut, mean, sigma);\n\n    prs /= sum(prs);\n  } else {\n    prs(0) = normcdf((grid(0) + grid(1)) / 2.0, mean, sigma);\n    prs(sz - 1) = 1.0 - normcdf((grid(sz - 2) + grid(sz - 1)) / 2.0, mean, sigma);\n  }\n\n  return prs;\n}\n\n/*\n * Discretize Normal over uniformly spaced grid\n * spanning +/- pmSigma standard deviations.\n */\nDiscreteRV\ndiscretizeNormal(const double mean,\n    const double sigma,\n    const uword n_elem,\n    const double pmSigma,\n    bool cutTails)\n{\n  DiscreteRV drv;\n  if (n_elem == 1) {\n    drv.support = { mean };\n    drv.probabilities = { 1.0 };\n  } else {\n    [[likely]] drv.support = linspace<vec>(mean - pmSigma * sigma, mean + pmSigma * sigma, n_elem);\n    drv.probabilities = discretizeNormal(drv.support, mean, sigma, cutTails);\n  }\n  return drv;\n}\n\n/*\n *\n * VAR(1)\n *\n */\nconst MvNormal\nVAR::conditional(vec& current) const\n{\n  MvNormal mvn;\n  mvn.mean = m_intercept + m_rho * current;\n  mvn.varCovar = m_sigma;\n  return mvn;\n}\n\nvoid VAR::findStationary()\n{\n  const cx_vec theEigs = eig_gen(m_rho);\n  if (any(abs(theEigs) >= 1.0)) {\n    [[unlikely]] cout << \"Eigenvalues exceeding 1 in abs value. Nonstationary.\"\n                      << endl;\n    is_stationary = false;\n    m_statMean.reset();\n    m_statSigma.reset();\n    return;\n  }\n\n  is_stationary = true;\n\n  const mat eyeRho = eye(m_size, m_size) - m_rho;\n  m_statMean = solve(eyeRho, m_intercept);\n\n  const mat kprod = kron(m_rho, m_rho);\n  const mat theEye(kprod.n_rows, kprod.n_cols, fill::eye);\n  const vec vecSigma = m_sigma.as_col();\n  const vec tmp = solve(theEye - kprod, vecSigma);\n  m_statSigma = reshape(tmp, m_rho.n_rows, m_rho.n_cols);\n}\n\nvec& VAR::stationaryMean()\n{\n  if (m_statMean.is_empty())\n    findStationary();\n  return m_statMean;\n}\n\nmat& VAR::stationarySigma()\n{\n  if (m_statSigma.is_empty())\n    findStationary();\n  return m_statSigma;\n}\n\nbool VAR::stationaryQ()\n{\n  if (m_statMean.is_empty())\n    findStationary();\n  return is_stationary;\n}\n\nvoid VAR::print()\n{\n  cout << \"Intercept: \" << endl;\n  intercept().print();\n  cout << \"Rho: \" << endl;\n  rho().print();\n  cout << \"Sigma: \" << endl;\n  sigma().print();\n\n  cout << \"Stationary: \" << endl;\n  stationaryMean().print();\n  cout << \"Stationary Sigma: \" << endl;\n  stationarySigma().print();\n}\n\n/*\n *\n * Markov Chain\n *\n */\nMarkovChain::MarkovChain(const AR process,\n    const uword sz,\n    const double pmMCsd,\n    bool expSupport)\n{\n  m_size = sz;\n  double pMean = process.stationaryMean();\n  double pSd = process.stationarySigma();\n  if (sz == 1)\n    m_support = { pMean };\n  else\n    [[likely]] m_support = linspace<rowvec>(pMean - pmMCsd * pSd, pMean + pmMCsd * pSd, sz);\n\n  m_tran.set_size(sz, sz);\n#pragma omp parallel for\n  for (uword rIx = 0; rIx < sz; ++rIx) {\n    double condMean = process.intercept() + process.rho() * m_support(rIx);\n    vec condPrs = discretizeNormal(m_support.t(), condMean, process.sigma());\n    m_tran.row(rIx) = condPrs.t();\n  }\n\n  if (expSupport)\n    m_support = exp(m_support);\n}\n\nrowvec\nstationaryDistribution(const mat& transitionMatrix)\n{\n  cx_vec eigval;\n  cx_mat eigvec;\n\n  const mat tranT = transitionMatrix.t();\n  const sp_mat sp_ver(tranT);\n\n  eigs_opts opts;\n  // opts.tol = 1.0E-6;\n  eigs_gen(eigval, eigvec, sp_ver, 1, 1.0001, opts);\n\n  const uword unitEigIx = (abs(abs(eigval) - 1.0)).index_min();\n\n  cout << \"Stationary eigenvalue \" << eigval(unitEigIx) << endl;\n\n  const rowvec stat = abs(eigvec.col(unitEigIx)).t();\n  return stat / sum(stat);\n}\n\nuvec simulateChain(const mat& transitionMatrix,\n    const uword initState,\n    const uword simSz)\n{\n  const mat cumMat = cumsum(transitionMatrix, 1);\n  const uword sz = transitionMatrix.n_rows;\n\n  uvec state(simSz);\n\n  state(0) = initState;\n  const vec draws(simSz, fill::randu);\n  for (uword tIx = 1; tIx < simSz; ++tIx) {\n    uword newState = 0;\n    for (uword stateIx = 1; stateIx < sz; ++stateIx)\n      if (cumMat(state(tIx - 1), stateIx) > draws(tIx)) {\n        newState = stateIx;\n        break;\n      }\n    state(tIx) = newState;\n  }\n\n  return state;\n}\n\nconst rowvec&\nMarkovChain::stationary()\n{\n  if (m_stationary.is_empty()) {\n    m_stationary = stationaryDistribution(m_tran);\n  }\n\n  return m_stationary;\n}\n\nvoid MarkovChain::save(const std::string fname) const\n{\n  m_support.save(hdf5_name(fname, \"MC/support\", hdf5_opts::replace));\n  m_stationary.save(hdf5_name(fname, \"MC/stationary\", hdf5_opts::replace));\n  m_tran.save(hdf5_name(fname, \"MC/transitions\", hdf5_opts::replace));\n}\n\nvoid MarkovChain::print() const\n{ /* TODO */\n}\n\nvoid trimMarkovChain(mat& grids, mat& transition)\n{\n  /*\n   * Based on Gordon 2020 wip.\n   */\n  rowvec probs = stationaryDistribution(transition);\n  uword sz = probs.n_elem;\n\n  uvec removePoints;\n  uword removeCount = 0;\n  for (uword ix = 0; ix < sz; ++ix)\n    if (probs(ix) <= minPr) {\n      [[likely]] removePoints.resize(removeCount + 1);\n      removePoints(removeCount) = ix;\n      removeCount++;\n    }\n\n  uword newSz = sz - removeCount;\n  cout << \"Removing \" << removeCount << \" points out of \" << sz << \".\" << endl;\n\n  grids.shed_rows(removePoints);\n  transition.shed_rows(removePoints);\n  transition.shed_cols(removePoints);\n#pragma omp parallel for\n  for (uword fIx = 0; fIx < newSz; ++fIx)\n    transition.row(fIx) = transition.row(fIx) / sum(transition.row(fIx));\n}\n\n/*\n *\n * Discretized VAR(1)\n *\n */\nvoid DiscreteVAR::impl(bool trimGrids, OrthoMethod method)\n{\n  // Sizing\n  m_size = m_var.size();\n  m_flatSize = prod(m_supportSizes);\n  m_grids.set_size(m_flatSize, m_size);\n  umat m_map(m_flatSize, m_size);\n\n  OrthogonalizedVAR ortho(m_var, method);\n  mat LL = ortho.getSupportRotationMatrix();\n  VAR orthog = ortho.getVAR();\n\n  const vec Atilde = orthog.intercept();\n  const mat Btilde = orthog.rho();\n  const vec DD = orthog.sigma().diag();\n\n  const vec uncondE = orthog.stationaryMean();\n  const vec uncondV = orthog.stationarySigma().diag();\n\n  // Prepare logical grids\n  field<vec> m_orthogGrids(m_size);\n#pragma omp parallel for\n  for (uword vIx = 0; vIx < m_size; ++vIx)\n    if (m_supportSizes(vIx) > 1) {\n      [[likely]] m_orthogGrids(vIx) = linspace<vec>(\n          uncondE(vIx) - pmSd * sqrt(uncondV(vIx)),\n          uncondE(vIx) + pmSd * sqrt(uncondV(vIx)),\n          m_supportSizes(vIx));\n    } else {\n      m_orthogGrids(vIx) = { uncondE(vIx) };\n    }\n\n    // Prepare flat grids\n#pragma omp parallel for\n  for (uword flatIx = 0; flatIx < m_flatSize; ++flatIx) {\n    uword tmp = flatIx;\n    for (uword vIx = 0; vIx < m_size; ++vIx) {\n      const vec logical = m_orthogGrids(vIx);\n      m_map(flatIx, vIx) = tmp % m_supportSizes(vIx);\n      m_grids(flatIx, vIx) = logical(m_map(flatIx, vIx));\n      tmp = tmp / m_supportSizes(vIx);\n    }\n  }\n\n  // Transition matrix\n  m_tran.set_size(m_flatSize, m_flatSize);\n  for (uword flatIx = 0; flatIx < m_flatSize; ++flatIx) {\n    const rowvec tmpVal = m_grids.row(flatIx);\n    const vec condMeans = Atilde + Btilde * tmpVal.t();\n    const vec condSd = sqrt(DD);\n    field<vec> condPrs(m_size);\n#pragma omp parallel for\n    for (uword vIx = 0; vIx < m_size; ++vIx)\n      condPrs(vIx) = discretizeNormal(m_orthogGrids(vIx), condMeans(vIx), condSd(vIx));\n\n#pragma omp parallel for\n    for (uword flatPrIx = 0; flatPrIx < m_flatSize; ++flatPrIx) {\n      double goPr = 1.0;\n      for (uword vPrIx = 0; vPrIx < m_size; ++vPrIx) {\n        vec tmpDist = condPrs(vPrIx);\n        goPr *= tmpDist(m_map(flatPrIx, vPrIx));\n      }\n      m_tran(flatIx, flatPrIx) = goPr;\n    }\n  }\n\n  // Adjust grids\n  m_grids = (LL * m_grids.t()).t();\n\n  if (trimGrids) {\n    trimMarkovChain(m_grids, m_tran);\n    m_flatSize = m_tran.n_rows;\n  }\n\n  // Finding midIx\n  vec distances(m_flatSize);\n  const vec target = m_var.stationaryMean();\n#pragma omp parallel for\n  for (uword flatIx = 0; flatIx < m_flatSize; ++flatIx) {\n    const vec tmp = target - m_grids.row(flatIx).t();\n    distances(flatIx) = sum(tmp % tmp);\n  }\n  m_midIx = distances.index_min();\n}\n\nvoid DiscreteVAR::print() const\n{\n  cout << \"Grid:\" << endl;\n  m_grids.print();\n  cout << endl\n       << \"Transition matrix: \" << endl;\n  m_tran.print();\n}\n\nvoid DiscreteVAR::save(const std::string fname) const\n{\n  uvec tmp = { m_midIx };\n  tmp.save(hdf5_name(fname, \"DVAR/midIx\", hdf5_opts::replace));\n  m_grids.save(hdf5_name(fname, \"DVAR/grids\", hdf5_opts::replace));\n  m_tran.save(hdf5_name(fname, \"DVAR/transitions\", hdf5_opts::replace));\n  m_var.intercept().save(\n      hdf5_name(fname, \"DVAR/varIntercept\", hdf5_opts::replace));\n  m_var.rho().save(hdf5_name(fname, \"DVAR/varRho\", hdf5_opts::replace));\n  m_var.sigma().save(hdf5_name(fname, \"DVAR/varSigma\", hdf5_opts::replace));\n}\n\n/*\n *\n * Stochastic volatility VAR\n *\n */\nvoid DiscreteStochVolVAR::impl(bool trimGrids)\n{\n  m_size = m_var.size();\n  uword justDimsSz = prod(m_supportSizes);\n  m_flatSize = justDimsSz * m_volGridSize;\n  m_grids.set_size(m_flatSize, m_size + 1);\n  umat m_map(m_flatSize, m_size + 1);\n\n  const MarkovChain volMC(m_vol, m_volGridSize, pmSd, true);\n  const rowvec& vols = volMC.support();\n  const mat& volTran = volMC.transition();\n\n  OrthogonalizedVAR ortho(m_var); // Default to Cholesky\n  mat rotationLL = ortho.getSupportRotationMatrix();\n  VAR orthog = ortho.getVAR();\n  const vec uncondE = orthog.stationaryMean();\n  const vec uncondV = orthog.stationarySigma().diag();\n\n  const vec Atilde = orthog.intercept();\n  const mat Btilde = orthog.rho();\n  const vec DD = orthog.sigma().diag();\n\n  // Prepare logical grids\n  field<vec> m_orthogGrids(m_size, m_volGridSize);\n#pragma omp parallel for collapse(2)\n  for (uword volIx = 0; volIx < m_volGridSize; ++volIx)\n    for (uword iIx = 0; iIx < m_size; ++iIx)\n      if (m_supportSizes(iIx) > 1) {\n        [[likely]] m_orthogGrids(iIx, volIx) = linspace<vec>(\n            uncondE(iIx) - pmSd * vols(volIx) * sqrt(uncondV(iIx)),\n            uncondE(iIx) + pmSd * vols(volIx) * sqrt(uncondV(iIx)),\n            m_supportSizes(iIx));\n      } else {\n        m_orthogGrids(iIx, volIx) = { uncondE(iIx) };\n      }\n\n      // Prepare flat grids\n#pragma omp parallel for collapse(2)\n  for (uword volIx = 0; volIx < m_volGridSize; ++volIx) {\n    for (uword flatIx = 0; flatIx < justDimsSz; ++flatIx) {\n      uword withV = justDimsSz * volIx + flatIx;\n\n      m_map(withV, m_size) = volIx;\n      m_grids(withV, m_size) = vols(volIx);\n\n      uword tmp = flatIx;\n      for (uword iIx = 0; iIx < m_size; ++iIx) {\n        const vec logical = m_orthogGrids(iIx, volIx);\n        m_map(withV, iIx) = tmp % m_supportSizes(iIx);\n        m_grids(withV, iIx) = logical(m_map(withV, iIx));\n        tmp /= m_supportSizes(iIx);\n      }\n    }\n  }\n\n  // Transition matrix\n  m_tran.set_size(m_flatSize, m_flatSize);\n  m_tran.fill(0.0);\n#pragma omp parallel for\n  for (uword flatIx = 0; flatIx < m_flatSize; ++flatIx) {\n    const uword thisVolIx = m_map(flatIx, m_size);\n    const rowvec thisValues = m_grids.row(flatIx).head(m_size);\n    const vec condMeans = Atilde + Btilde * thisValues.t();\n    const vec condSdReference = sqrt(DD);\n\n    field<vec> condPrs(m_size);\n    for (uword iIx = 0; iIx < m_size; ++iIx)\n      condPrs(iIx) = discretizeNormal(m_orthogGrids(iIx, thisVolIx), condMeans(iIx), vols(thisVolIx) * condSdReference(iIx));\n\n    for (uword flatPrIx = 0; flatPrIx < m_flatSize; ++flatPrIx) {\n      double goPr = 1.0;\n      for (uword iiIx = 0; iiIx < m_size; ++iiIx) {\n        const vec condPrVec = condPrs(iiIx);\n        goPr *= condPrVec(m_map(flatPrIx, iiIx));\n      }\n      const uword vPrIx = m_map(flatPrIx, m_size);\n      m_tran(flatIx, flatPrIx) = goPr * volTran(thisVolIx, vPrIx);\n    }\n  }\n\n  // Adjust grids\n  m_grids.cols(0, m_size - 1) = (rotationLL * m_grids.cols(0, m_size - 1).t()).t();\n\n  if (trimGrids) {\n    [[likely]] trimMarkovChain(m_grids, m_tran);\n    m_flatSize = m_tran.n_rows;\n  }\n\n  // Finding midIx\n  vec distances(m_flatSize);\n  vec uncondEextended(m_size + 1);\n  uncondEextended.head(m_size) = m_var.stationaryMean();\n  uncondEextended(m_size) = vols(m_volGridSize / 2);\n#pragma omp parallel for\n  for (uword flatIx = 0; flatIx < m_flatSize; ++flatIx) {\n    const vec tmp = uncondEextended - m_grids.row(flatIx).t();\n    distances(flatIx) = sum(tmp % tmp);\n  }\n  m_midIx = distances.index_min();\n}\n\nvoid DiscreteStochVolVAR::save(const std::string fname) const\n{\n  uvec tmp = { m_midIx };\n  tmp.save(hdf5_name(fname, \"DsvVAR/midIx\", hdf5_opts::replace));\n  m_grids.save(hdf5_name(fname, \"DsvVAR/grids\", hdf5_opts::replace));\n  m_tran.save(hdf5_name(fname, \"DsvVAR/transitions\", hdf5_opts::replace));\n  m_var.intercept().save(\n      hdf5_name(fname, \"DsvVAR/varIntercept\", hdf5_opts::replace));\n  m_var.rho().save(hdf5_name(fname, \"DsvVAR/varRho\", hdf5_opts::replace));\n  m_var.sigma().save(hdf5_name(fname, \"DsvVAR/varSigma\", hdf5_opts::replace));\n\n  vec volAR = { m_vol.intercept(), m_vol.rho(), m_vol.sigma() };\n  volAR.save(\n      hdf5_name(fname, \"DsvVAR/volatilityAR1params\", hdf5_opts::replace));\n}\n\nvoid DiscreteStochVolVAR::print() const\n{ /* TODO */\n}\n\n} // namespace TimeSeries\n", "meta": {"hexsha": "9f281f55c6822241f7a19a0465b169cdd6ea7140", "size": 13977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TimeSeries.cpp", "max_stars_repo_name": "gabrielgggg/DiscretizeVAR", "max_stars_repo_head_hexsha": "9d9bd2d05ff1fbf3b0575f900032c4c3244d278a", "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": "TimeSeries.cpp", "max_issues_repo_name": "gabrielgggg/DiscretizeVAR", "max_issues_repo_head_hexsha": "9d9bd2d05ff1fbf3b0575f900032c4c3244d278a", "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": "TimeSeries.cpp", "max_forks_repo_name": "gabrielgggg/DiscretizeVAR", "max_forks_repo_head_hexsha": "9d9bd2d05ff1fbf3b0575f900032c4c3244d278a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-13T11:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T11:28:29.000Z", "avg_line_length": 27.3522504892, "max_line_length": 125, "alphanum_fraction": 0.646347571, "num_tokens": 4497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6400142306949261}}
{"text": "\r\n\r\n#include \"cor_algorithm/sources/utilities.h\"\r\n#include \"cor_algorithm/sources/bit_operation.h\"\r\n#include \"cor_system/sources/logger.h\"\r\n\r\n#define BOOST_TEST_NO_LIB\r\n#include <boost/test/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_SUITE(bit_operation)\r\n\r\nBOOST_AUTO_TEST_CASE(bit_operation_count_one)\r\n{\r\n    {\r\n        auto f = [=](cor::RInt32 a, cor::RSize b){\r\n            auto v = a;\r\n            auto sz = cor::algorithm::BitOperation::count_one(v);\r\n            BOOST_CHECK_EQUAL(sz, b);\r\n        };\r\n\r\n        f(7, 3);\r\n        f(406959, 12);\r\n        f(0xf0000000, 4);\r\n    }\r\n\r\n    {\r\n        auto f = [=](cor::RInt64 a, cor::RSize b){\r\n            auto v = a;\r\n            auto sz = cor::algorithm::BitOperation::count_one(v);\r\n            BOOST_CHECK_EQUAL(sz, b);\r\n        };\r\n\r\n        f(0xf000000000000000, 4);\r\n    }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(bit_operation_ciel_pow_two)\r\n{\r\n    {\r\n        auto f = [=](cor::RInt32 a, cor::RSize b){\r\n            auto v = a;\r\n            auto sz = cor::algorithm::BitOperation::ciel_pow_two(v);\r\n            BOOST_CHECK_EQUAL(sz, b);\r\n        };\r\n\r\n        f(7, 3);\r\n        f(406959, 19);\r\n        f(0xf0000000, 32);\r\n    }\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n\r\n", "meta": {"hexsha": "04fc23a060a6ba6f635095768aaf52bae91a19ab", "size": 1204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit/sources/basic/bit_operation_test.cpp", "max_stars_repo_name": "rmake/cor-engine", "max_stars_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T09:55:02.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-10T03:42:23.000Z", "max_issues_repo_path": "tests/unit/sources/basic/bit_operation_test.cpp", "max_issues_repo_name": "rmake/cor-engine", "max_issues_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/unit/sources/basic/bit_operation_test.cpp", "max_forks_repo_name": "rmake/cor-engine", "max_forks_repo_head_hexsha": "d8920325db490d19dc8c116ab8e9620fe55e9975", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T02:30:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T06:56:49.000Z", "avg_line_length": 22.2962962963, "max_line_length": 69, "alphanum_fraction": 0.5398671096, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6400142295274965}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_EXP2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_EXP2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing exp2 capabilities\n\n    base two exponential function: \\f$2^{x}\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = exp2(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = pow(T(2), x);\n    @endcode\n\n    @par Note:\n\n    - provisions are made to obtain a flint result from a flint input\n\n    @par Decorators\n\n    std_ for floating entries\n\n    @see exp, exp10, pow, pow2\n\n  **/\n  const boost::dispatch::functor<tag::exp2_> exp2 = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/exp2.hpp>\n#include <boost/simd/function/simd/exp2.hpp>\n\n#endif\n", "meta": {"hexsha": "ad53e46ae61e1c2581b02c44da419e0507663dcd", "size": 1236, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/exp2.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/exp2.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/exp2.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9491525424, "max_line_length": 100, "alphanum_fraction": 0.5760517799, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7461389817407017, "lm_q1q2_score": 0.6400142258528039}}
{"text": "//\n//  main_picking.cpp\n//  HCI 557 Picking example\n//\n//  Created by Rafael Radkowski on 5/28/15.\n//  Copyright (c) 2015 -. All rights reserved.\n//\n\n// stl include\n#include <iostream>\n#include <string>\n#include <math.h>\n#include <map>\n\n\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues> \n\n#include <glm/gtx/transform.hpp> // after <glm/glm.hpp>\n\n\n#include \"Bezier.h\"\n\nusing namespace std;\n\n// stores all binomnal coefficents that have been calculated in this program.\n// [  n , [k, coeff] ]\nmap<unsigned int, map< unsigned int,  unsigned int> > binominal_coefficients;\n\n\n\n\n\nbool eigenvaluessort(pair<float, Eigen::Vector3f > i, pair<float, Eigen::Vector3f > j)\n{\n    return (i.first > j.first); // largest first\n}\n\n\n/*!\n@brief - calculate the eigenvectors for a given point using the points in its surrounding.\n@param centroid - the centroid of the eigenvectors\n@param points - all the other points\n@param eigenvectors - a 4x4 matrix which column vectors are the eigen vectors\n*/\n//static\nvoid calcEigenvectors(const glm::vec3& centroid, const vector<glm::vec3>& points, vector<glm::vec3>& eigenvectors)\n{\n    \n    \n    Eigen::Matrix3f cov;\n    cov << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n    \n    size_t size = points.size();\n    for (int i=0; i<size; i++) {\n        \n        glm::vec3 p = points[i];\n        cov(0,0) += (p[0] - centroid[0] ) * (p[0] - centroid[0]);\n        cov(0,1) += (p[0] - centroid[0] ) * (p[1] - centroid[1]);\n        cov(0,2) += (p[0] - centroid[0] ) * (p[2] - centroid[2]);\n        \n        cov(1,0) += (p[1] - centroid[1] ) * (p[0] - centroid[0]);\n        cov(1,1) += (p[1] - centroid[1] ) * (p[1] - centroid[1]);\n        cov(1,2) += (p[1] - centroid[1] ) * (p[2] - centroid[2]);\n        \n        cov(2,0) += (p[2] - centroid[2] ) * (p[0] - centroid[0]);\n        cov(2,1) += (p[2] - centroid[2] ) * (p[1] - centroid[1]);\n        cov(2,2) += (p[2] - centroid[2] ) * (p[2] - centroid[2]);\n    }\n    \n    cov(0,0) /= size;\n    cov(0,1) /= size;\n    cov(0,2) /= size;\n    \n    cov(1,0) /= size;\n    cov(1,1) /= size;\n    cov(1,2) /= size;\n    \n    cov(2,0) /= size;\n    cov(2,1) /= size;\n    cov(2,2) /= size;\n    \n    \n    Eigen::EigenSolver<Eigen::Matrix3f> es(cov);\n    \n    \n    \n    // Columns are the eigenvectors\n    Eigen::Matrix3f D = es.pseudoEigenvalueMatrix();\n    Eigen::Matrix3f V = es.pseudoEigenvectors();\n    \n    Eigen::Vector3f e0( V(0), V(1), V(2));\n    Eigen::Vector3f e1( V(3), V(4), V(5));\n    Eigen::Vector3f e2( V(6), V(7), V(8));\n    \n    //Eigen::Vector3f e0( V(0), V(3), V(6));\n    //Eigen::Vector3f e1( V(1), V(4), V(7));\n    //Eigen::Vector3f e2( V(2), V(5), V(8));\n    \n    float ev0 = D(0);\n    float ev1 = D(4);\n    float ev2 = D(8);\n    \n    \n    vector<pair<float, Eigen::Vector3f > > results(3);\n    results[0] = make_pair(ev0, e0);\n    results[1] = make_pair(ev1, e1);\n    results[2] = make_pair(ev2, e2);\n    \n    \n    // sort the vectors, largest first.\n    std::sort (results.begin(), results.end(), eigenvaluessort);\n    \n    eigenvectors = vector<glm::vec3>(3);\n    eigenvectors[0] = glm::vec3(results[0].second(0), results[0].second(1), results[0].second(2));\n    eigenvectors[1] = glm::vec3(results[1].second(0), results[1].second(1), results[1].second(2));\n    eigenvectors[2] = glm::vec3(results[2].second(0), results[2].second(1), results[2].second(2));\n    \n    \n   // cout << \"Covariance matrix:\" << endl << cov << endl;\n  //  cout << \"The eigenvalues of A are:\" << endl << es.eigenvalues() << endl;\n  //  cout << \"The matrix of eigenvectors, V, is:\" << endl << es.eigenvectors() << endl << endl;\n    \n    \n    return;\n    \n}\n\n\n\n/*!\n@brief Function to calculate all eigenvectors for all points\n@param all_matches -  the matches for all points in \"points\". The index of each matchs complies with the point index.\n@param points - all points\n@param eigenvectors_per_point - the result eigenvectors per point. The index of each matchs complies with the point index.\n*/\nvoid computeReferenceFrames( const int n, const int m, glm::vec3 up, const vector< vector<float> >& points, vector< vector<glm::vec3> >& eigenvector_per_point )\n{\n    \n\n    for(int i=0; i<m; i++)\n    {\n        for(int j=0; j<n; j++)\n        {\n            int current = i*n + j;\n            vector<float> p = points[current];\n            \n            // find neighbors.\n            vector< glm::vec3 > neighbors;\n            \n            const int box[8] = { -n-1, -1 ,n-1,\n                                -n ,       n,\n                                -n+1, +1, n+1};\n            \n            for(int k=0; k<8; k++)\n            {\n                int idx = i + box[k];\n                if(idx > 0 && idx < points.size() ) neighbors.push_back( glm::vec3(points[idx][0],points[idx][1], points[idx][2] ));\n            }\n            \n            glm::vec3 centroid(p[0], p[1], p[2]);\n            vector<glm::vec3> eigenvectors;\n            \n            calcEigenvectors(centroid, neighbors, eigenvectors);\n            \n            \n             ///////////////////////////////////////////////////////////////////\n            //\n            // Check for right-hand coordinate system.\n            //\n            // Calc the cross product between x, and y\n            glm::vec3 cp = cross(eigenvectors[0], eigenvectors[1]);\n            float angle = acos( dot(cp, eigenvectors[2]) );\n        \n            if( angle != angle ) // Check for NaN - tiny value, good.\n            {\n                // do not do anything. vector is fine.\n            }\n            else if(angle > 3.00)\n            {\n            //   cout << \"replace \" << i << \" a: \" << angle << endl;\n                eigenvectors[2] = cp; //replace with cp\n            }\n            \n            \n            ///////////////////////////////////////////////////////////////////\n            //\n            // Verify alignment and flip the coordinate system if it is not aligned with\n            // the alignment axis. (Should be the camera axis later. )\n            //\n            static glm::vec3 flip(-1,-1,-1);\n        \n            float angle_alignment = acos( dot(eigenvectors[2], up) );\n    \n            if(angle_alignment > 1.57)\n            {\n                eigenvectors[1] = flip * eigenvectors[1];\n                eigenvectors[2] = flip * eigenvectors[2];\n            \n            }\n\n            \n            // store the eigenvectors\n            eigenvector_per_point.push_back(eigenvectors);\n        }\n    }\n\n\n}\n\n\n\n/*!\n@brief - transfers an eigenvector into a matrix in homogenous coordinates.\n@param eigenvectors  - vector with eigenvectors sorted corresponding to the eigenvalues, largest first ev1 > ev2 > ev3\n@param matrix - the glm matrix.\nNotice that all matrix types are column-major rather than row-major.\n*/\n//static\nvoid Eigenvec2matrix(const vector< glm::vec3 >& eigenvectors, glm::mat4& matrix)\n{\n    matrix = glm::mat4();\n    \n    matrix[0][0] = eigenvectors[0][0];\n    matrix[0][1] = eigenvectors[0][1];\n    matrix[0][2] = eigenvectors[0][2];\n    \n    matrix[1][0] = eigenvectors[1][0];\n    matrix[1][1] = eigenvectors[1][1];\n    matrix[1][2] = eigenvectors[1][2];\n    \n    matrix[2][0] = eigenvectors[2][0];\n    matrix[2][1] = eigenvectors[2][1];\n    matrix[2][2] = eigenvectors[2][2];\n    \n    matrix[3][0] = 0.0;\n    matrix[3][1] = 0.0;\n    matrix[3][2] = 0.0;\n\n}\n\n\n\n\n/*!\nCalculates the factorial of a number\n@param x - the value that should be factorized.\n@return - the factor.\n*/\nint factorial(int x, int result) {\n  if (x == 1  || x == 0) return result;\n  else return factorial(x - 1, x * result);\n}\n\n\n\n/*!\nCalculate the binominal coefficient for n and k\n@param n - the number of line segments where the number of supporting points is n+1\n@param k - the current point\n*/\nint BinomialCoeff(int n, int k)\n{\n    int c = binominal_coefficients[n][k];\n    \n    if(c==0) // binominal coefficient is min = 1, 0! = 1\n    {\n        c = factorial(n)/ ( factorial(k) * factorial(n-k) );\n        binominal_coefficients[n][k] = c;\n    \n        return c;\n        \n    }\n    return c;\n    //return factorial(n)/ ( factorial(k) * factorial(n-k) );\n}\n\n\n\n/*!\nCalculate the bernstein polynom for P(x) = BC(n,k)  x^k (1-x)^{n-k}\n@param x - the interpolation variable x = [0,1]\n@param n - the number of line segments where the number of supporting points is n+1\n@param k - the current point\n*/\nfloat ComputeBernsteinP(float x, int n, int k)\n{\n    int c = BinomialCoeff(n,k);\n    \n    float p_x = float(c) * pow(x, k) *  pow((1.0-x), n-k);\n    \n    return p_x;\n}\n\n\n\n/*!\nComputes the points for a cubic spline\n@param control_points - a vector of four points in x,y or x,y,z.\n@param result - the output points\n@param num - the number of points that should be generated along the spline\n*/\nbool ComputeCubicSpline(const int num, const vector< vector<float> >& control_points, vector< vector<float> >& result)\n{\n    result.clear();\n    \n    float increment = 1.0/float(num-1);\n    \n    \n    vector<float> cp0 = control_points[0];\n    vector<float> cp1 = control_points[1];\n    vector<float> cp2 = control_points[2];\n    vector<float> cp3 = control_points[3];\n    \n    \n    for (int i=0; i<num; i++) {\n        \n        double t = increment * i;\n        \n        vector<float>p(3);\n        p[0] = cp0[0] * ComputeBernsteinP(t,3,0) + cp1[0] * ComputeBernsteinP(t,3,1) + cp2[0] * ComputeBernsteinP(t,3,2) + cp3[0] * ComputeBernsteinP(t,3,3);\n        p[1] = cp0[1] * ComputeBernsteinP(t,3,0) + cp1[1] * ComputeBernsteinP(t,3,1) + cp2[1] * ComputeBernsteinP(t,3,2) + cp3[1] * ComputeBernsteinP(t,3,3);\n        p[2] = cp0[2] * ComputeBernsteinP(t,3,0) + cp1[2] * ComputeBernsteinP(t,3,1) + cp2[2] * ComputeBernsteinP(t,3,2) + cp3[2] * ComputeBernsteinP(t,3,3);\n        \n        cout << t << \" :\\t\" << p[0] << \"\\t\" << p[1] << \"\\t\" << p[2] << endl;\n    \n        result.push_back(p);\n    }\n    \n    return true;\n}\n\n\n\n/*!\nComputes the points for a cubic spline\n@param control_points - a vector of four points in x,y or x,y,z.\n@param result - the output points\n@param num - the number of points that should be generated along the spline\n*/\nbool ComputeCubicSplineC(const int num, const vector< vector<float> >& control_points, vector< vector<float> >& result)\n{\n    result.clear();\n    \n    float increment = 1.0/float(num-1);\n    \n    \n    vector<float> cp0 = control_points[0];\n    vector<float> cp1 = control_points[1];\n    vector<float> cp2 = control_points[2];\n    vector<float> cp3 = control_points[3];\n    \n    // the bezier matrix\n    static vector< vector<float> > bm( 4, vector<float>(4, 0.0));\n    bm[0][0] = -1; bm[0][1] = 3;  bm[0][2] = -3; bm[0][3] = 1;\n    bm[1][0] = 3;  bm[1][1] = -6; bm[1][2] = 3;  bm[1][3] = 0;\n    bm[2][0] = -3; bm[2][1] = 3;  bm[2][2] = 0;  bm[2][3] = 0;\n    bm[3][0] = 1; bm[3][1] = 0;  bm[3][2] = 0;  bm[3][3] = 0;\n\n    \n    \n    \n    for (int i=0; i<num; i++) {\n        \n        float t = increment * i;\n        \n        float C0 = bm[0][0] * pow(t, 3) + bm[1][0] * pow(t, 2) + bm[2][0] * t + bm[3][0];\n        float C1 = bm[0][1] * pow(t, 3) + bm[1][1] * pow(t, 2) + bm[2][1] * t + bm[3][1];\n        float C2 = bm[0][2] * pow(t, 3) + bm[1][2] * pow(t, 2) + bm[2][2] * t + bm[3][2];\n        float C3 = bm[0][3] * pow(t, 3) + bm[1][3] * pow(t, 2) + bm[2][3] * t + bm[3][3];\n        \n        vector<float>p(3);\n        p[0] = C0 * cp0[0] + C1 * cp1[0] + C2 * cp2[0] +  C3 * cp3[0];\n        p[1] = C0 * cp0[1] + C1 * cp1[1] + C2 * cp2[1] +  C3 * cp3[1];\n        p[2] = C0 * cp0[2] + C1 * cp1[2] + C2 * cp2[2] +  C3 * cp3[2];\n        \n        cout << t << \" :\\t\" << p[0] << \"\\t\" << p[1] << \"\\t\" << p[2] << endl;\n        result.push_back(p);\n    }\n    \n    return true;\n}\n\n\n\n\n/*!\nComputes a cubic surface patch\n@param control_points - a vector of four points in x,y or x,y,z. \n@param result - the output points\n@param num - the number of points that should be generated along the spline.\n\nNOTE: This code is not fast, it is written that way for clarity. \nUsually, one would precomupute all values for BEZ * BEZ and put them into a table.\n\n*/\nbool ComputeCubicPatch(const int num, const vector< vector<float> >& control_points, vector< vector<float> >& result)\n{\n    result.clear();\n    float increment = 1.0/float(num-1);\n    \n    vector<float> cp00 = control_points[0];\n    vector<float> cp01 = control_points[1];\n    vector<float> cp02 = control_points[2];\n    vector<float> cp03 = control_points[3];\n    \n    \n    vector<float> cp10 = control_points[4];\n    vector<float> cp11 = control_points[5];\n    vector<float> cp12 = control_points[6];\n    vector<float> cp13 = control_points[7];\n    \n    vector<float> cp20 = control_points[8];\n    vector<float> cp21 = control_points[9];\n    vector<float> cp22 = control_points[10];\n    vector<float> cp23 = control_points[11];\n    \n    \n    vector<float> cp30 = control_points[12];\n    vector<float> cp31 = control_points[13];\n    vector<float> cp32 = control_points[14];\n    vector<float> cp33 = control_points[15];\n    \n    \n    // runs along the first coordinate\n    for (int i=0; i<num; i++) {\n        float t = increment * i;\n        \n        // runs along the second corrdinate\n        for (int j=0; j<num; j++) {\n            float v = increment * j;\n            \n            vector<float>p(3);\n        \n            // x-coordinate\n            float px0 =  cp00[0] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,0) + cp01[0] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,1) + cp02[0] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,2) + cp03[0] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,3);\n            float px1 =  cp10[0] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,0) + cp11[0] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,1) + cp12[0] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,2) + cp13[0] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,3);\n            float px2 =  cp20[0] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,0) + cp21[0] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,1) + cp22[0] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,2) + cp23[0] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,3);\n            float px3 =  cp30[0] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,0) + cp31[0] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,1) + cp23[0] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,2) + cp33[0] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,3);\n            p[0] = px0 + px1 + px2 + px3;\n            \n            // y-coordinate\n            float py0 =  cp00[1] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,0) + cp01[1] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,1) + cp02[1] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,2) + cp03[1] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,3);\n            float py1 =  cp10[1] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,0) + cp11[1] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,1) + cp12[1] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,2) + cp13[1] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,3);\n            float py2 =  cp20[1] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,0) + cp21[1] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,1) + cp22[1] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,2) + cp23[1] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,3);\n            float py3 =  cp30[1] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,0) + cp31[1] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,1) + cp23[1] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,2) + cp33[1] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,3);\n            p[1] = py0 + py1 + py2 + py3;\n            \n            // z-coordinate\n            float pz0 =  cp00[2] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,0) + cp01[2] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,1) + cp02[2] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,2) + cp03[2] * ComputeBernsteinP(v,3,0)  * ComputeBernsteinP(t,3,3);\n            float pz1 =  cp10[2] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,0) + cp11[2] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,1) + cp12[2] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,2) + cp13[2] * ComputeBernsteinP(v,3,1)  * ComputeBernsteinP(t,3,3);\n            float pz2 =  cp20[2] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,0) + cp21[2] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,1) + cp22[2] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,2) + cp23[2] * ComputeBernsteinP(v,3,2)  * ComputeBernsteinP(t,3,3);\n            float pz3 =  cp30[2] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,0) + cp31[2] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,1) + cp23[2] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,2) + cp33[2] * ComputeBernsteinP(v,3,3)  * ComputeBernsteinP(t,3,3);\n            p[2] = pz0 + pz1 + pz2 + pz3;\n        \n            cout << t << \", \" << v << \" :\\t\" << p[0] << \"\\t\" << p[1] << \"\\t\" << p[2] << endl;\n            result.push_back(p);\n            \n        }\n    }\n    \n    return true;\n}\n\n\n\n/*!\nComputes / reorganizes all points so they can be used as triangles to render a mesh\n@param n, m, the size of the mesh in number of points as columns n and rows m\n@param control_points, control points as vec3 <float> [x, y, x].\n\n     0------1-------2-------3\n     |      |       |       |\n     4------5-------6-------7\n     |      |       |       |\n     8------9-------10------11\n     |      |       |       |\n     12-----13------14------15\n\n@param vertices, the vertices in an vector. Three vertices in a row are one triangle\n@param normals, a normal vector for each point\n*/\nbool TriangulateCubicPatch(const int n, const int m, const vector< vector<float> >& points, const glm::vec3 up, vector< glm::vec3 >& vertices, vector< glm::vec3 >& normals )\n{\n    int num = (n * m) - n;\n    \n    vertices.clear();\n    normals.clear();\n    \n    // Here, we compute the normal vectors.\n    // Note, this can also be optimized in order to speedup the process.\n    // However, I compute everything in single steps so you guys can easily find and distinguish them.\n    vector< vector<glm::vec3> > eigenvector_per_point;\n    computeReferenceFrames( n, m, up, points, eigenvector_per_point);\n    \n    \n    // lets find the vertices and let's associate one normal vector per vertex.\n    for(int i=0; i<num; i++)\n    {\n        // suppose we have four control points per quad. We need two triangles per quad\n        /*\n            0--n--2n--3n\n            | /|\n            |/ |\n            1--n+1\n         \n        */\n        \n        // triangle 0\n        if( i%(n) < n-1 )\n        {\n            int idx0 = i;\n            int idx1 = i+1;\n            int idx2 = i + n;\n            \n            //cout << 0 <<\": \" << idx0 << \"\\t:\" << idx1 << \"\\t\" << idx2 << endl;\n            \n            vertices.push_back( glm::vec3( points[idx0][0], points[idx0][1], points[idx0][2]  ));\n            vertices.push_back( glm::vec3( points[idx1][0], points[idx1][1], points[idx1][2]  ));\n            vertices.push_back( glm::vec3( points[idx2][0], points[idx2][1], points[idx2][2]  ));\n    \n            normals.push_back(eigenvector_per_point[idx0][2]);\n            normals.push_back(eigenvector_per_point[idx1][2]);\n            normals.push_back(eigenvector_per_point[idx2][2]);\n        }\n        \n        // triangle 1\n        if( i%(n) < n-1 )\n        {\n            int idx0 = i+1;\n            int idx1 = idx0+n;\n            int idx2 = idx0+n-1;\n            \n            //cout << 1 <<\": \" << idx0 << \"\\t:\" << idx1 << \"\\t\" << idx2 << endl;\n            \n            vertices.push_back( glm::vec3( points[idx0][0], points[idx0][1], points[idx0][2]  ));\n            vertices.push_back( glm::vec3( points[idx1][0], points[idx1][1], points[idx1][2]  ));\n            vertices.push_back( glm::vec3( points[idx2][0], points[idx2][1], points[idx2][2]  ));\n            \n            normals.push_back(eigenvector_per_point[idx0][2]);\n            normals.push_back(eigenvector_per_point[idx1][2]);\n            normals.push_back(eigenvector_per_point[idx2][2]);\n        }\n    }\n    \n    \n    \n    return true;\n}\n\n", "meta": {"hexsha": "494f58ca39e7758e0d131dba00340f52cccb6a9f", "size": 20094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "28_Bezier_Surface/Bezier.cpp", "max_stars_repo_name": "lezhangisu/CprE_557-Fall_2018-ISU", "max_stars_repo_head_hexsha": "5dd57e948abecfc92461f32f912412054c0a07f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-08-27T14:14:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-05T18:40:46.000Z", "max_issues_repo_path": "28_Bezier_Surface/Bezier.cpp", "max_issues_repo_name": "lezhangisu/CprE_557-Fall_2018-ISU", "max_issues_repo_head_hexsha": "5dd57e948abecfc92461f32f912412054c0a07f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "28_Bezier_Surface/Bezier.cpp", "max_forks_repo_name": "lezhangisu/CprE_557-Fall_2018-ISU", "max_forks_repo_head_hexsha": "5dd57e948abecfc92461f32f912412054c0a07f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-08-25T21:26:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-12T21:59:23.000Z", "avg_line_length": 36.4682395644, "max_line_length": 283, "alphanum_fraction": 0.5554892008, "num_tokens": 6540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6399972725305881}}
{"text": "#include <fstream>\n#include <map>\n#include <set>\n#include <vector>\n\n#include <iostream>\n\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n\n#include <Eigen/Dense>\n#include <gmpxx.h>\n\n#include \"LinearAlgebra.hxx\"\n\ntypedef Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic> MatrixXq;\ntypedef Eigen::Matrix<mpq_class, Eigen::Dynamic, 1> VectorXq;\n\ntemplate<class Archive>\nvoid eval_mat::serialize (Archive & ar, unsigned int const) {\n  ar & values;\n}\n\nvoid eval_mat::save (std::string const & filename) const {\n  std::ofstream file;\n  file.open(filename);\n  boost::archive::text_oarchive oa {file};\n  oa << *this;\n}\n\nvoid eval_mat::load (std::string const & filename) {\n  std::ifstream file;\n  file.open(filename);\n  boost::archive::text_iarchive ia {file};\n  ia >> *this;\n}\n\nstd::set<size_t> eval_mat::row_set () const {\n  std::set<size_t> ret;\n  std::transform (values.cbegin(), values.cend(), std::inserter (ret, ret.begin()),\n    [] (auto const & v) {\n      return v.first.second;\n    });\n  return ret;\n}\n\nstd::set<size_t> findDependentVariables (std::set<std::pair<std::pair<size_t, size_t>, mpq_class>> const & matrix, size_t rows, size_t cols) {\n  MatrixXq mq(cols, rows);\n\n  std::for_each(matrix.cbegin(), matrix.cend(),\n    [&mq] (auto const & v) {\n      mq (v.first.second, v.first.first) = v.second;\n    });\n\n  Eigen::FullPivLU<MatrixXq> lu_decompq(mq);\n\n  std::cout << \"rank of the system : \" << lu_decompq.rank() << std::endl;\n\n  std::set<size_t> ret;\n  VectorXq vector = VectorXq::Zero (cols);\n  for (size_t counter = 0; counter < cols; ++counter) {\n    if (counter != 0) {\n      vector (cols - counter) = 0;\n    }\n    vector (cols - counter - 1) = 1;   \n    if (lu_decompq.solve(vector).isZero()) {\n      ret.insert (cols - counter - 1);\n    }\n  }\n\n  return ret;\n}\n\nstd::map<size_t, std::map<size_t, mpq_class>> solveLinearSystem (std::set<std::pair<std::pair<size_t, size_t>, mpq_class>> const & matrix, size_t rows, size_t cols) {\n  MatrixXq mq (rows, cols);\n\n  std::for_each (matrix.cbegin(), matrix.cend(),\n      [&mq] (auto const & v) {\n        mq (v.first.first, v.first.second) = v.second;\n      });\n\n  Eigen::FullPivLU<MatrixXq> lu_decompq(mq);\n\n  std::cout << \"rank of the system : \" << lu_decompq.rank() << std::endl;\n\n  std::cout << lu_decompq.kernel() << std::endl;\n\n  return {};\n\n}\n", "meta": {"hexsha": "9e5b0bd067d7b0433153cfd527110a858b2bcd61", "size": 2349, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/LinearAlgebra.cxx", "max_stars_repo_name": "nilsalex/tensor-trees", "max_stars_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LinearAlgebra.cxx", "max_issues_repo_name": "nilsalex/tensor-trees", "max_issues_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinearAlgebra.cxx", "max_forks_repo_name": "nilsalex/tensor-trees", "max_forks_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8131868132, "max_line_length": 166, "alphanum_fraction": 0.6458067263, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6399972621537194}}
{"text": "/**\n * @author Eric Cousineau <eacousineau@gmail.com>, member of Dr. Aaron\n * Ames's AMBER Lab\n */\n#ifndef EIGEN_UTILITIES_COMPARE_UTILITIES_H\n    #define EIGEN_UTILITIES_COMPARE_UTILITIES_H\n\n#include <Eigen/Dense>\n\nnamespace eigen_utilities\n{\n\n/**\n * @brief Ensure that two matrices have nans in the same spot.\n * To be used in conjunction with norm_nanless() \n */\n    template<typename Derived>\ninline bool nan_compare(const Eigen::MatrixBase<Derived> &A, const Eigen::MatrixBase<Derived> &B)\n{\n    return ((A.array() == A.array()) == (B.array() == B.array())).all();\n}\n\ninline double nan_compare(double a, double b)\n{\n    return std::isnan(a) == std::isnan(b);\n}\n\n/**\n * @brief Check if there are any NAN elements\n */\n    template<typename Derived>\ninline bool hasnan(const Eigen::MatrixBase<Derived> &X)\n{\n    return (X.array() != X.array()).any();\n}\n\n/**\n * @brief Check if all are NAN elements\n */\n    template<typename Derived>\ninline bool isnan(const Eigen::MatrixBase<Derived> &X)\n{\n    return (X.array() != X.array()).all();\n}\n\n/**\n * @brief Zero out all NAN matrix entries\n * @ref http://listengine.tuxfamily.org/lists.tuxfamily.org/eigen/2012/01/msg00020.html\n */\n    template<typename Derived>\ninline double norm_nanless(const Eigen::MatrixBase<Derived> &X)\n{\n    Eigen::MatrixXd temp = (X.array() == X.array()).select(X, 0);\n    return temp.norm();\n}\n\ninline double norm_nanless(double x)\n{\n    if (std::isnan(x))\n        return 0;\n    else\n        return std::fabs(x);\n}\n\n/**\n * @brief Zero NAN elements, take norm, compare (a) and (b). Return difference\n */\ntemplate<typename A>\ndouble norm_nanless_compare(const A &a, const A &b, bool relative = false)\n{\n    if (!nan_compare(a, b))\n        return INFINITY;\n    else\n    {\n        if (relative)\n            return (norm_nanless_compare(a, b));\n        else\n            return norm_nanless(a - b);\n    }\n}\n\n/**\n * @brief Return relative difference \n * @param A\n * @param B\n * @return \n *  (B - A) / A,    if (A != 0 & B != 0)\n *  (B - A),        if (A == 0)\n * @todo Also using B == 0 because for it will cause an issue for small values that may not matter\n */\ninline double diff_relative_nonzero(double a, double b)\n{\n    if (a == 0 || b == 0)\n        return b - a;\n    else\n        return (b - a) / a;\n}\n\n/**\n * @brief See documentation for scalar version\n */\n    template<typename DerivedA, typename DerivedB>\ninline Eigen::MatrixXd diff_relative_nonzero(const Eigen::MatrixBase<DerivedA> &A, const Eigen::MatrixBase<DerivedB> &B)\n{\n    return ((A.array() != 0) * (B.array() != 0)).select((B - A).array() / A.array(), B - A);\n}\n\ninline double set_nans(double &X, double value = 0.)\n{\n    if (std::isnan(X))\n        X = value;\n    return X;\n}\n\n/**\n * @brief Set all nan entries to a non-NAN value\n */\ntemplate<typename Derived>\ninline void set_nans(Eigen::MatrixBase<Derived> &X, double value = 0.)\n{\n    for (int i = 0; i < X.size(); ++i)\n        set_nans(X(i), value);\n}\n\n}\n\n#endif // EIGEN_UTILITIES_COMPARE_UTILITIES_H\n", "meta": {"hexsha": "1589782ad54ab1df34c65a0c90f2c8768e76127d", "size": 2991, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "eigen_utilities/include/eigen_utilities/compare_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/compare_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/compare_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": 23.3671875, "max_line_length": 120, "alphanum_fraction": 0.6325643597, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6398848675979136}}
{"text": "#ifndef TRIUMF_SUPERCONDUCTIVITY_BCS_HPP\n#define TRIUMF_SUPERCONDUCTIVITY_BCS_HPP\n\n#include <cmath>\n#include <limits>\n#include <tuple>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/quadrature/ooura_fourier_integrals.hpp>\n#include <boost/math/tools/roots.hpp>\n\n#include <triumf/constants/codata_2018.hpp>\n#include <triumf/superconductivity/phenomenology.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n//\nnamespace superconductivity {\n\n// Bardeen-Cooper-Schrieffer (BCS) theory of superconductivity\nnamespace bcs {\n\n/// Find the reduced gap Delta(t) for a given reduced temperature x = T / T_c.\ntemplate <typename T = double> T reduced_gap_solver(T x) {\n  // Use 1 as the initial guess for the Delta(t).\n  // This ensures that the first \"root\" is found as Delta(t) -> 0.0,\n  // otherwise the wrong solution is found when t >= 0.9.\n  T guess = 1.0;\n  // T guess = std::cos(boost::math::constants::half_pi<T>() * std::pow(x, 2));\n\n  // Bound the possible values for the gap.\n  // The adjustments by machine epsilon needed for \"exact\" results!?\n  T min = 0.0 - std::numeric_limits<T>::epsilon();\n  T max = 1.0 + std::numeric_limits<T>::epsilon();\n\n  // Maximum possible binary digits accuracy for type T.\n  const int digits = std::numeric_limits<T>::digits;\n\n  // Digits used to control how accurate to try to make the result.\n  // Accuracy triples with each step, so stop when just over one third of the\n  // digits are correct.\n  int get_digits = static_cast<int>(0.4 * digits);\n\n  // Limit the number of iterations taken to find the \"root\" of the expression.\n  // boost::uintmax_t max_iterations = 20;\n  boost::uintmax_t max_iterations =\n      std::numeric_limits<boost::uintmax_t>::max();\n\n  // Return the \"root\" of Thouless' Eqn. using both its 1st and 2nd derivatives.\n  T result = boost::math::tools::halley_iterate(\n      [x](const T &delta) {\n        // Return a tuple containing: f(delta), f'(delta), and  f''(delta).\n        T f = std::tanh(delta / x) - delta;\n        T df_dx = 1.0 / (x * std::pow(std::cosh(delta / x), 2)) - 1.0;\n        T df2_dx2 =\n            -2.0 * std::tanh(delta / x) / std::pow(x * std::cosh(delta / x), 2);\n        return std::make_tuple(f, df_dx, df2_dx2);\n      },\n      guess, min, max, get_digits, max_iterations);\n  //\n  return result;\n}\n\n/// temperature dependence of the (reduced) energy gap\ntemplate <typename T = double> T reduced_gap(T reduced_temperature) {\n  if (reduced_temperature >= 1.0) {\n    return 0.0;\n  } else if (reduced_temperature <= 0.0) {\n    return 1.0;\n  } else {\n    return reduced_gap_solver<T>(reduced_temperature);\n  }\n}\n\n/// temperature dependence of the (reduced) energy gap\ntemplate <typename T = double>\nT reduced_gap(T temperature, T critical_temperature) {\n  T reduced_temperature = temperature / critical_temperature;\n  return reduced_gap<T>(reduced_temperature);\n}\n\n/// temperature dependence of the energy gap\ntemplate <typename T = double>\nT gap(T temperature, T critical_temperature, T gap_meV) {\n  return gap_meV * reduced_gap<T>(temperature, critical_temperature);\n}\n\n/// energy gap at absolute zero\ntemplate <typename T = double> T gap_meV(T critical_temperature) {\n  // Boltzmann constant (meV / K)\n  constexpr T k_B_meV_per_K =\n      1e3 *\n      triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<T>::value();\n  //\n  return boost::math::constants::pi<T>() *\n         std::exp(-boost::math::constants::euler<T>()) * k_B_meV_per_K *\n         critical_temperature;\n}\n\n// energy gap ratio (at absolute zero)\ntemplate <typename T = double> T gap_ratio(T critical_temperature, T gap_meV) {\n  // Boltzmann constant (meV / K)\n  constexpr T k_B_meV_per_K =\n      1e3 *\n      triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<T>::value();\n  //\n  return (2.0 * gap_meV) / (k_B_meV_per_K * critical_temperature);\n}\n\n/// helper function for BCS Kernel\ntemplate <typename T = double>\nT a(T temperature, T critical_temperature, T gap_meV) {\n  return boost::math::constants::pi<T>() * 1e3 *\n         triumf::constants::codata_2018::Boltzmann_constant_in_eV_K<\n             T>::value() *\n         temperature / gap<T>(temperature, critical_temperature, gap_meV);\n}\n\n/// helper function for BCS Kernel\ntemplate <typename T = double>\nT f(T temperature, T critical_temperature, T gap_meV, T n) {\n  return std::sqrt(1.0 +\n                   std::pow(a<T>(temperature, critical_temperature, gap_meV) *\n                                (2.0 * n + 1.0),\n                            2));\n}\n\n/// temperature dependence of the BCS coherence length (helper function)\ntemplate <typename T = double>\nT coherence_length(T temperature, T critical_temperature, T gap_meV, T xi_0,\n                   T mean_free_path, T n) {\n  T fraction_1 = boost::math::constants::two_div_pi<T>() *\n                 f<T>(temperature, critical_temperature, gap_meV, n) *\n                 reduced_gap<T>(temperature, critical_temperature) / xi_0;\n  T fraction_2 = 1.0 / mean_free_path;\n  T fraction = fraction_1 + fraction_2;\n  // handle a some edge cases for very big/small args\n  if (std::isinf(fraction)) {\n    return 0.0;\n  } else if (fraction == 0.0) {\n    return std::numeric_limits<T>::infinity();\n  } else {\n    return 1.0 / fraction;\n  }\n}\n\n/// helper function for BCS Kernel\ntemplate <typename T = double>\nT Lambda(T temperature, T critical_temperature, T gap_meV, T xi_0,\n         T mean_free_path, T lambda_0, T exponent, T n) {\n  return std::pow(\n             lambda_0,\n             // triumf::superconductivity::phenomenology::penetration_depth<T>(\n             //    temperature, critical_temperature, exponent, lambda_0),\n             2) *\n         std::pow(f<T>(temperature, critical_temperature, gap_meV, n), 3) *\n         (1.0 + coherence_length<T>(temperature, critical_temperature, gap_meV,\n                                    xi_0, mean_free_path, n) /\n                    mean_free_path) /\n         (2.0 * a<T>(temperature, critical_temperature, gap_meV));\n}\n\n/// helper function for the BCS Kernel\ntemplate <typename T = double> T g(T x) {\n  // return correct result when x ~ 0.\n  if (x < 1.0e-4) {\n    return 1.0;\n  } else {\n    return (3.0 / 2.0) * ((1.0 + x * x) * std::atan(x) - x) / (x * x * x);\n  }\n}\n\n/// BCS Kernel\ntemplate <typename T = double>\nT kernel(T q, T temperature, T critical_temperature, T gap_meV, T xi_0,\n         T mean_free_path, T lambda_0, T exponent) {\n  //\n  T sum = 0.0;\n  T change = 0.0;\n  // const T precision = std::sqrt(std::numeric_limits<T>::epsilon());\n  const T precision = std::numeric_limits<T>::epsilon();\n  const T max_iterations = 100;\n  T n = 0.0;\n  do {\n    //\n    T x = q * coherence_length<T>(temperature, critical_temperature, gap_meV,\n                                  xi_0, mean_free_path, n);\n    //\n    change = g<T>(x) / Lambda<T>(temperature, critical_temperature, gap_meV,\n                                 xi_0, mean_free_path, lambda_0, exponent, n);\n    //\n    sum += change;\n    n += 1.0;\n  } while ((std::abs(change) > precision) and (n < max_iterations));\n  //\n  return sum;\n}\n\n/// (reduced) BCS Kernel\ntemplate <typename T = double>\nT reduced_kernel(T q, T temperature, T critical_temperature, T gap_meV, T xi_0,\n                 T mean_free_path, T lambda_0, T exponent) {\n  return kernel<T>(q, temperature, critical_temperature, gap_meV, xi_0,\n                   mean_free_path, lambda_0, exponent) /\n         kernel<T>(0.0, temperature, critical_temperature, gap_meV, xi_0,\n                   mean_free_path, lambda_0, exponent);\n}\n\n/// BCS magnetic penetration depth\ntemplate <typename T = double>\nT penetration_depth(T temperature, T critical_temperature, T gap_meV, T xi_0,\n                    T mean_free_path, T lambda_0, T exponent) {\n  T K_0 = kernel<T>(0.0, temperature, critical_temperature, gap_meV, xi_0,\n                    mean_free_path, lambda_0, exponent);\n  return std::sqrt(1.0 / K_0);\n}\n\n/// (reduced) BCS magnetic field penetration profile\ntemplate <typename T = double>\nT reduced_field_penetration(T z, T temperature, T critical_temperature,\n                            T gap_meV, T xi_0, T mean_free_path, T lambda_0,\n                            T exponent) {\n  //\n  if (z <= 0.0) {\n    return 1.0;\n  } else {\n    //\n    auto bcs_integrand = [&](T q) -> T {\n      T K = kernel<T>(q, temperature, critical_temperature, gap_meV, xi_0,\n                      mean_free_path, lambda_0, exponent);\n      return q / (q * q + K);\n    };\n    // create the integrator w/ default tolerance and evaluation levels\n    // (root_epsilon and eight levels for type double).\n    static boost::math::quadrature::ooura_fourier_sin<T> bcs_integrator =\n        boost::math::quadrature::ooura_fourier_sin<T>();\n    // evaluate the integral, which returns a pair\n    // (first = integral, second = relative error)\n    std::pair<T, T> result = bcs_integrator.integrate(bcs_integrand, z);\n    // return the integral multiplied by the prefactors to get B vs. z\n    return boost::math::constants::two_div_pi<T>() * result.first;\n  }\n}\n\n/// BCS magnetic field penetration proifile\ntemplate <typename T = double>\nT field_penetration(T z, T temperature, T critical_temperature, T gap_meV,\n                    T xi_0, T mean_free_path, T lambda_0, T exponent,\n                    T applied_field) {\n  return applied_field * reduced_field_penetration<T>(\n                             z, temperature, critical_temperature, gap_meV,\n                             xi_0, mean_free_path, lambda_0, exponent);\n}\n\n} // namespace bcs\n\n} // namespace superconductivity\n\n} // namespace triumf\n\n#endif // TRIUMF_SUPERCONDUCTIVITY_BCS_HPP\n", "meta": {"hexsha": "143cb4f008a83d3376b715d4e82c08f45a09bab4", "size": 9594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/superconductivity/bcs.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/triumf/superconductivity/bcs.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/triumf/superconductivity/bcs.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4790874525, "max_line_length": 80, "alphanum_fraction": 0.6480091724, "num_tokens": 2587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.639760443994877}}
{"text": "#include <stdio.h>\n#include <algorithm>\n#include <math.h>\n#include <float.h>\n\n#include \"timing.h\"\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main() {\n\n\tint n = 10000000;\n\tdouble xo = 0;\n\tdouble yo = 0;\n\tdouble zo = 0;\n\tdouble xd = 1;\n\tdouble yd = 0;\n\tdouble zd = 0;\n\t\n  ArrayXd xc(n);\n  ArrayXd yc(n);\n  ArrayXd zc(n);\n\n\tfor(int i = 0; i < n; i++) {\n\t\txc[i] = i;\n\t\tyc[i] = i;\n\t\tzc[i] = i;\n\t}\n\n  ArrayXd b(n);\n  ArrayXd c(n);\n  ArrayXd disc(n);\n    ArrayXd res(n);\n\tb.fill(0);\n\tc.fill(0);\n\tdisc.fill(0);\n\tres.fill(0);\n\tdouble begin = current_time();\n\n\tdouble a = 1;\n\t\t\n\tdouble r = DBL_MAX;\n\t\n  b = 2*(xd*(xo-xc)+yd*(yo-yc)+zd*(zo-zc));\n  c = (xo-xc)*(xo-xc)+(yo-yc)*(yo-yc)+(zo-zc)*(zo-zc)-1;\n  disc = b*b-4*c;\n  res = ((disc<0).select(((-b - disc.sqrt())/2),DBL_MAX)); //.min( (-b + disc)/2),DBL_MAX));\n  r = res.minCoeff();\n\n\tprintf(\"%f\\n\",r);\n\tprintf(\"Elapsed: %f\\n\", current_time()-begin);\n\treturn 0;\n}\n", "meta": {"hexsha": "27885736d1127dbd8012bf9a1c18d655cfa4321f", "size": 916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/benchmarks/raysphere_eigen.cpp", "max_stars_repo_name": "nie-game/terra", "max_stars_repo_head_hexsha": "36a544595e59c6066ab9e5b5fa923b82b4be0c41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1575.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T13:40:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-24T22:08:08.000Z", "max_issues_repo_path": "tests/benchmarks/raysphere_eigen.cpp", "max_issues_repo_name": "nie-game/terra", "max_issues_repo_head_hexsha": "36a544595e59c6066ab9e5b5fa923b82b4be0c41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 304.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T22:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-23T20:43:18.000Z", "max_forks_repo_path": "tests/benchmarks/raysphere_eigen.cpp", "max_forks_repo_name": "nie-game/terra", "max_forks_repo_head_hexsha": "36a544595e59c6066ab9e5b5fa923b82b4be0c41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 150.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T07:18:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-24T22:08:10.000Z", "avg_line_length": 16.3571428571, "max_line_length": 92, "alphanum_fraction": 0.5524017467, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.639748532631686}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <ayla/geometry/vector.hpp>\n#include <ayla/geometry/matrix.hpp>\n#include <ayla/geometry/rigid_transform.hpp>\n\n#include <glm/gtc/matrix_transform.hpp>\n\nBOOST_AUTO_TEST_SUITE(ayla)\nBOOST_AUTO_TEST_SUITE(matrix4)\n\nBOOST_AUTO_TEST_CASE( mat4_constructor16 ) {\n\tglm::mat4 testcase(1.0f,2.0f,3.0f,4.0f,\n\t\t\t5.0f,6.0f,7.0f,8.0f,\n\t\t\t9.0f,10.0f,11.0f,12.0f,\n\t\t\t13.0f,14.0f,15.0f,16.0f);\n\n\tFloat count=1.0f;\n\tfor (SizeType row = 0; row < 4; ++row) {\n\t\tfor (SizeType col = 0; col < 4; ++col) {\n\t\t\tBOOST_CHECK_EQUAL(testcase[row][col], count);\n\t\t\tcount += 1.0;\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE( mat4_scale_transformation_and_inverse ) {\n\tglm::mat4 scale = glm::scale(glm::mat4(1.0f), glm::vec3(2.0, 3.0, 5.0));\n\tglm::vec4 point(1.0,1.0,1.0,1.0);\n\n\tBOOST_CHECK_EQUAL( (scale*point).x, 2.0 );\n\tBOOST_CHECK_EQUAL( (scale*point).y, 3.0 );\n\tBOOST_CHECK_EQUAL( (scale*point).z, 5.0 );\n\tBOOST_CHECK_EQUAL( (scale*point).w, 1.0 );\n\n\tpoint = scale*point;\n\n\tBOOST_CHECK_EQUAL( (scale*point).x, 4.0 );\n\tBOOST_CHECK_EQUAL( (scale*point).y, 9.0 );\n\tBOOST_CHECK_EQUAL( (scale*point).z, 25.0 );\n\tBOOST_CHECK_EQUAL( (scale*point).w, 1.0 );\n\n\tpoint = scale*point;\n\n\tglm::mat4 scaleInv = glm::inverse(scale);\n\tscale = scaleInv;\n\n\tpoint = scaleInv*point;\n\tpoint = scale*point;\n\n\tBOOST_CHECK( glm::epsilonEqual(point.x, 1.0f, 0.00001f) );\n\tBOOST_CHECK( glm::epsilonEqual(point.y, 1.0f, 0.00001f) );\n\tBOOST_CHECK( glm::epsilonEqual(point.z, 1.0f, 0.00001f) );\n\tBOOST_CHECK( glm::epsilonEqual(point.w, 1.0f, 0.00001f) );\n\n\tconst glm::mat4 identity = scale*glm::inverse(scaleInv);\n\tBOOST_CHECK( epsilonEqual(identity, glm::mat4(1.0f), 0.00001f) );\n}\n\nBOOST_AUTO_TEST_CASE( mat4_constructor_from_rigid_transform_translate ) {\n\tRigidTransform t = RigidTransform::getIdentity();\n\tt.translate(glm::vec3(3.0,5.0,7.0));\n\n\tglm::mat4 mat4= t.toMatrix4();\n\n\tBOOST_CHECK_EQUAL( mat4,\n\t\tglm::mat4(\n\t\t\t1,0,0,0,\n\t\t\t0,1,0,0,\n\t\t\t0,0,1,0,\n\t\t\t3,5,7,1\n\t\t)\n\t);\n}\n\nBOOST_AUTO_TEST_CASE( mat4_constructor_from_rigid_transform_ytranslate ) {\n\tfor (SizeType i = 0; i < 360; ++i) {\n\t\tRigidTransform t = RigidTransform::getIdentity();\n\t\tconst Float rotationAmount = glm::radians(Float(i));\n\t\tt.rotate(rotationAmount,glm::vec3(0,1,0));\n\t\tconst glm::mat4 fromRigidTransform = t.toMatrix4();\n\t\tconst glm::mat4 rotateY = glm::rotate(glm::mat4(1.0f), rotationAmount, glm::vec3(0,1,0));\n\n\t\tBOOST_CHECK_MESSAGE( epsilonEqual(fromRigidTransform, rotateY,0.000001f), fromRigidTransform << \" != \" << rotateY);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE( mat4_constructor_from_rigid_transform_with_rotation_and_translation ) {\n\tfor (SizeType i = 0; i < 1; ++i) {\n\t\tRigidTransform t = RigidTransform::getIdentity();\n\t\tconst Float rotationAmount = glm::radians(Float(i));\n\t\tconst glm::vec3 translateAmount(glm::vec3(Float(3*i),Float(5*i),Float(7*i)));\n\t\tt.rotate(rotationAmount,glm::vec3(0,1,0));\n\t\tt.translate(translateAmount);\n\n\t\tconst glm::mat4 fromRigidTransform = t.toMatrix4();\n\n\t\tconst glm::mat4 fromMatrix = glm::rotate(\n\t\t\tglm::translate(glm::mat4(1.0f), translateAmount),\n\t\t\trotationAmount,\n\t\t\tglm::vec3(0,1,0)\n\t\t);\n\n\t\tBOOST_CHECK_MESSAGE( epsilonEqual(fromRigidTransform, fromMatrix, 0.000001f), fromRigidTransform << \" != \" << fromMatrix);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE( mat4_constructor_from_rigid_transform_lot_of_rotations_then_translate ) {\n\tRigidTransform t = RigidTransform::getIdentity();\n\tconst Float rotationAmountA = glm::radians(Float(13));\n\tconst Float rotationAmountB = glm::radians(Float(17));\n\n\tfor (SizeType i = 0; i < 5; ++i) {\n\t\tt.rotate(rotationAmountA,glm::vec3(0,1,0));\n\t\tt.translate(glm::vec3(2,3,5));\n\t\tt.rotate(rotationAmountB,glm::vec3(1,0,0));\n\t}\n\tglm::mat4 fromRigidTransform = t.toMatrix4();\n\n\tglm::mat4 fromMatrix = glm::mat4(1.0f);\n\tfor (SizeType i = 0; i < 5; ++i) {\n\t\tfromMatrix = glm::rotate(glm::mat4(1.0f), rotationAmountA, glm::vec3(0,1,0)) * fromMatrix; // glm::mat4::rotateY(rotationAmountA)*fromMatrix;\n\t\tfromMatrix = glm::rotate(glm::mat4(1.0f), rotationAmountB, glm::vec3(1,0,0)) * fromMatrix; //glm::mat4::rotateX(rotationAmountB)*fromMatrix;\n\t}\n\tfromMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(2*5,3*5,5*5))*fromMatrix;\n\n\t//High tolerance to errors because matrix accumulate a lot of numerical instability\n\tBOOST_CHECK_MESSAGE( epsilonEqual(fromRigidTransform, fromMatrix, 0.1f), fromRigidTransform << \" != \" << fromMatrix);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "d2fb16d89e96586131501f08add80aa248a29a19", "size": 4396, "ext": "cc", "lang": "C++", "max_stars_repo_path": "epoch/ayla/tests/matrix4.cc", "max_stars_repo_name": "oprogramadorreal/vize", "max_stars_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T14:36:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T07:44:54.000Z", "max_issues_repo_path": "epoch/ayla/tests/matrix4.cc", "max_issues_repo_name": "oprogramadorreal/vize", "max_issues_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "epoch/ayla/tests/matrix4.cc", "max_forks_repo_name": "oprogramadorreal/vize", "max_forks_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-01T01:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T13:06:09.000Z", "avg_line_length": 33.0526315789, "max_line_length": 143, "alphanum_fraction": 0.7065514104, "num_tokens": 1496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6396551291349197}}
{"text": "#pragma once\r\n#include <vector>\r\n#include <iostream>\r\n//#include \"Eigen/Eigen/Eigen\"\r\n\r\n#include <Eigen/Dense>\r\n#include<Eigen/Core>\r\n// fstream\r\n#include <fstream>\r\n#include<sstream>\r\n#include <stdlib.h>\r\n#include <iomanip>\r\n\r\n// math\r\n#include <math.h>\r\n//time \r\n#include <time.h>\r\n//algorithm \r\n#include <algorithm>\r\n// Define Infinite (Using INT_MAX caused overflow problems)\r\n#define INF 10000\r\nusing namespace Eigen;\r\nusing namespace std;\r\nclass generateSkymask\r\n{\r\npublic: // functions \r\n\t\tgenerateSkymask(string kml_dir, string saved_skymask_dir,bool mannually_set_ref_llh, double ref_lat,double ref_lon) // construct function\r\n\t{\r\n\t\tmannually_set_ref_llh_ = mannually_set_ref_llh;\r\n\t\tref_lat_fromlaunch = ref_lat;\r\n\t\tref_lon_fromlaunch = ref_lon;\r\n\t\t//readKml(\"G:/Dropbox/Dropbox/PNL/57HuaWei_WWS/Shadow_Matching_Huawei/Shadow_Matching_Huawei/NiuToujiao.kml\"); // demo_HK_TST_fix\r\n\t\t// readKml(\"/home/wenws/amsipolyu/src/rtklibros/app/generate_skymask/data/demo_HK_TST_fix.kml\"); // demo_HK_TST_fix\r\n\t\treadKml(kml_dir);\r\n\t\twait(5);\r\n\t\tstring2llh(builDataS); // parse llh from string\r\n\t\twait(5);\r\n\t\tprepareBuildingData(buildingLLHS);  // prepare buildingS to map_\r\n\t\twait(5);\r\n\r\n\t\t/*Eigen::MatrixXd ENU_;\r\n\t\tENU_.resize(1, 3);\r\n\t\tENU_(0) = 25;\r\n\t\tENU_(1) = 3;\r\n\t\tENU_(2) = 30;\r\n\t\tbool result = identifyPointInsideBuildingENU(map_, ENU_);*/\r\n\r\n\t\tEigen::MatrixXd LLH_;\r\n\t\tLLH_.resize(1, 3);\r\n\t\tLLH_(0) = 114.177911;\r\n\t\tLLH_(1) = 22.298642;\r\n\t\tLLH_(2) = 102;\r\n\t\tbool result = identifyPointInsideBuildingLLH(map_, LLH_);\r\n\t\tcout << \"result by convex hull (LLH):   \" << result << \"\\n\";\r\n\r\n\t\tEigen::MatrixXd ENU_;\r\n\t\tENU_.resize(1, 3);\r\n\t\tENU_(0) = 0;\r\n\t\tENU_(1) = -84;\r\n\t\tENU_(2) = 0;\r\n\t\tresult = identifyPointInsideBuildingENU(map_, ENU_);\r\n\t\tcout << \"result by convex hull (ENU):   \" << result << \"\\n\";\r\n\t\t\r\n\t\t// get the azimuth angle at a certain position (LLH) with a certain azimuth\r\n\t\tEigen::MatrixXd aziEleResult;\r\n\t\taziEleResult.resize(2,1);\r\n\r\n\t\tvector<double> elevationList;\r\n\t\tvector<double> builingIntersectionNumber;\r\n\t\tbool consistency = 1;\r\n\t\tbool onebuilding = 0; // only intersect with one building\r\n\r\n\t\tfor (double azi = 0; azi <= 360; azi = azi + map_.aziReso)\r\n\t\t{\r\n\t\t\taziEleResult = getMaskElevationFromLLH(map_, LLH_, azi);\r\n\t\t\televationList.push_back(aziEleResult(1));\r\n\t\t\tif (aziEleResult(1) > 0) // if \r\n\t\t\t{\r\n\t\t\t\tbuilingIntersectionNumber.push_back(aziEleResult(2));\r\n\t\t\t}\r\n\t\t\t\t\r\n\t\t}\r\n\r\n\t\tcreateSkymasks(); // generate skymasks\r\n\t\twait(5);\r\n\t\tsaveSkymasks2SCV(map_,saved_skymask_dir); // save skymask to CSV\r\n\t\twait(5);\r\n\t\t\r\n\t}\r\n\r\n\r\n\t~generateSkymask() // deconstruction function\r\n\t{\r\n\t}\r\n\r\npublic: // solve convex hull problem (https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain#C++)\r\n\t\t// Implementation of Andrew's monotone chain 2D convex hull algorithm.\r\n\t\t// Asymptotic complexity: O(n log n).\r\n\t\t// Practical performance: 0.5-1.0 seconds for n=1000000 on a 1GHz computer.\r\n\ttypedef double coord_t;         // coordinate type\r\n\ttypedef double coord2_t;  // must be big enough to hold 2*max(|coordinate|)^2\r\n\r\n\tstruct Point {\r\n\t\tcoord_t x, y;\r\n\r\n\t\tbool operator <(const Point &p) const {\r\n\t\t\treturn x < p.x || (x == p.x && y < p.y);\r\n\t\t}\r\n\t};\r\n\r\n\t// 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.\r\n\t// Returns a positive value, if OAB makes a counter-clockwise turn,\r\n\t// negative for clockwise turn, and zero if the points are collinear.\r\n\tcoord2_t cross(const Point &O, const Point &A, const Point &B)\r\n\t{\r\n\t\treturn (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);\r\n\t}\r\n\r\n\t// Returns a list of points on the convex hull in counter-clockwise order.\r\n\t// Note: the last point in the returned list is the same as the first one.\r\n\tvector<Point> convex_hull(vector<Point> P)\r\n\t{\r\n\t\tsize_t n = P.size(), k = 0;\r\n\t\tif (n <= 3) return P;\r\n\t\tvector<Point> H(2 * n);\r\n\r\n\t\t// Sort points lexicographically\r\n\t\tsort(P.begin(), P.end());\r\n\r\n\t\t// Build lower hull\r\n\t\tfor (size_t i = 0; i < n; ++i) {\r\n\t\t\twhile (k >= 2 && cross(H[k - 2], H[k - 1], P[i]) <= 0) k--;\r\n\t\t\tH[k++] = P[i];\r\n\t\t}\r\n\r\n\t\t// Build upper hull\r\n\t\tfor (size_t i = n - 1, t = k + 1; i > 0; --i) {\r\n\t\t\twhile (k >= t && cross(H[k - 2], H[k - 1], P[i - 1]) <= 0) k--;\r\n\t\t\tH[k++] = P[i - 1];\r\n\t\t}\r\n\r\n\t\tH.resize(k - 1);\r\n\t\treturn H;\r\n\t}\r\n\r\npublic: // solve the problem: if one point is inside the building\r\n\tstruct Point_\r\n\t{\r\n\t\tdouble x;\r\n\t\tdouble y;\r\n\t};\r\n\r\n\t// Given three colinear Point_s p, q, r, the function checks if\r\n\t// Point_ q lies on line segment 'pr'\r\n\tbool onSegment(Point_ p, Point_ q, Point_ r)\r\n\t{\r\n\t\tif (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) &&\r\n\t\t\tq.y <= max(p.y, r.y) && q.y >= min(p.y, r.y))\r\n\t\t\treturn true;\r\n\t\treturn false;\r\n\t}\r\n\r\n\t// To find orientation of ordered triplet (p, q, r).\r\n\t// The function returns following values\r\n\t// 0 --> p, q and r are colinear\r\n\t// 1 --> Clockwise\r\n\t// 2 --> Counterclockwise\r\n\tint orientation(Point_ p, Point_ q, Point_ r)\r\n\t{\r\n\t\tint val = (q.y - p.y) * (r.x - q.x) -\r\n\t\t\t(q.x - p.x) * (r.y - q.y);\r\n\r\n\t\tif (val == 0) return 0; // colinear\r\n\t\treturn (val > 0) ? 1 : 2; // clock or counterclock wise\r\n\t}\r\n\r\n\t// The function that returns true if line segment 'p1q1'\r\n\t// and 'p2q2' intersect.\r\n\tbool doIntersect(Point_ p1, Point_ q1, Point_ p2, Point_ q2)\r\n\t{\r\n\t\t// Find the four orientations needed for general and\r\n\t\t// special cases\r\n\t\tint o1 = orientation(p1, q1, p2);\r\n\t\tint o2 = orientation(p1, q1, q2);\r\n\t\tint o3 = orientation(p2, q2, p1);\r\n\t\tint o4 = orientation(p2, q2, q1);\r\n\r\n\t\t// General case\r\n\t\tif (o1 != o2 && o3 != o4)\r\n\t\t\treturn true;\r\n\r\n\t\t// Special Cases\r\n\t\t// p1, q1 and p2 are colinear and p2 lies on segment p1q1\r\n\t\tif (o1 == 0 && onSegment(p1, p2, q1)) return true;\r\n\r\n\t\t// p1, q1 and p2 are colinear and q2 lies on segment p1q1\r\n\t\tif (o2 == 0 && onSegment(p1, q2, q1)) return true;\r\n\r\n\t\t// p2, q2 and p1 are colinear and p1 lies on segment p2q2\r\n\t\tif (o3 == 0 && onSegment(p2, p1, q2)) return true;\r\n\r\n\t\t// p2, q2 and q1 are colinear and q1 lies on segment p2q2\r\n\t\tif (o4 == 0 && onSegment(p2, q1, q2)) return true;\r\n\r\n\t\treturn false; // Doesn't fall in any of the above cases\r\n\t}\r\n\r\n\t// Returns true if the Point_ p lies inside the polygon[] with n vertices\r\n\tbool isInside(vector<Point_> polygon, int n, Point_ p)\r\n\t{\r\n\t\t// There must be at least 3 vertices in polygon[]\r\n\t\tif (n < 3) return false;\r\n\r\n\t\t// Create a Point_ for line segment from p to infinite\r\n\t\tPoint_ extreme = { INF, p.y };\r\n\r\n\t\t// Count intersections of the above line with sides of polygon\r\n\t\tint count = 0, i = 0;\r\n\t\tdo\r\n\t\t{\r\n\t\t\tint next = (i + 1) % n;\r\n\r\n\t\t\t// Check if the line segment from 'p' to 'extreme' intersects\r\n\t\t\t// with the line segment from 'polygon[i]' to 'polygon[next]'\r\n\t\t\tif (doIntersect(polygon[i], polygon[next], p, extreme))\r\n\t\t\t{\r\n\t\t\t\t// If the Point_ 'p' is colinear with line segment 'i-next',\r\n\t\t\t\t// then check if it lies on segment. If it lies, return true,\r\n\t\t\t\t// otherwise false\r\n\t\t\t\tif (orientation(polygon[i], p, polygon[next]) == 0)\r\n\t\t\t\t\treturn onSegment(polygon[i], p, polygon[next]);\r\n\r\n\t\t\t\tcount++;\r\n\t\t\t}\r\n\t\t\ti = next;\r\n\t\t} while (i != 0);\r\n\r\n\t\t// Return true if count is odd, false otherwise\r\n\t\treturn count & 1; // Same as (count%2 == 1)\r\n\t}\r\n\r\n\r\npublic: // variables for particles\r\n\tdouble reserve;\r\n\ttypedef struct obs_Nav_epoch // reserved\r\n\t{\r\n\r\n\t};\r\n\r\n\ttypedef struct  // satellite information\r\n\t{\r\n\t\tdouble GNSS_time;\r\n\t\tdouble total_sv; // total satellite in this epoch\r\n\t\tdouble prn_satellites_index; // satellite prn \r\n\t\tdouble pseudorange; // satellite pseudorange\r\n\t\tdouble snr; // satellite snr\r\n\t\tdouble elevation; // satellite elevation \r\n\t\tdouble azimuth; // satellite azimuth \r\n\t\tdouble err_tropo; //satellite erro_tropo\r\n\t\tdouble err_iono; // satellite ono\r\n\t\tdouble sat_clk_err; // satellite clock bias \r\n\t\tdouble sat_pos_x; // satellite position x\r\n\t\tdouble sat_pos_y; // satellite position y\r\n\t\tdouble sat_pos_z; // satellite position z\r\n\t\tint visable; // satellite visability\r\n\t\tstd::string sat_system; // satellite system (\"GPS\", \"GLONASS\")\r\n\t}satelliteInfo;\r\n\r\n\ttypedef struct // single grid: determined in ENU coordiante system\r\n\t{\r\n\t\tdouble E_;\r\n\t\tdouble N_;\r\n\t\tdouble U_;\r\n\t\tdouble score;\r\n\t}grid;\r\n\r\n\ttypedef struct  //  grid sequences (grids)\r\n\t{\r\n\t\tstd::vector<grid> grids_;\r\n\t}grids;\r\n\r\n\ttypedef struct  // state for a particle\r\n\t{\r\n\t\tdouble GNSS_time = 0; // time stamps\r\n\t\t//satellites information \r\n\t\tstd::vector<satelliteInfo>  satInfo; // incluide pseudorange.etc\r\n\t\tint particle_ID; // the ID for particle\r\n\t\tdouble scores; // scores for this particle \r\n\t\t//position in llh\r\n\t\tdouble lon; // latitude\r\n\t\tdouble lat; // longtutude\r\n\t\tdouble altitude; // altitude\r\n\r\n\t\r\n\t\tgrids smGrids; \t//grid at present for shadow matching (plane)\r\n\t\tstd::vector<grids> smGridss; // all the grids from first epoch to last epoch (multi-plane)\r\n\r\n\t\t//position in ENU\r\n\t\tdouble E;\r\n\t\tdouble N;\r\n\t\tdouble U;\r\n\t\tdouble ini_lon;\r\n\t\tdouble ini_lat;\r\n\t\tdouble ini_alt;\r\n\r\n\t}particle;\r\n\tstd::vector<particle> particles; // all th particles at present\r\n\tstd::vector<std::vector<particle>> particless; // all the particles from first epoch to last epoch\r\npublic: // for reading data from kml file\r\n\tvector<string> builDataS; // building data in string format\r\n\ttypedef struct \r\n\t{\r\n\t\tdouble lon;\r\n\t\tdouble lat;\r\n\t\tdouble alt;\r\n\t}LLH;\r\n\tvector <LLH> buildingLLH; // determine a building with a set of lon lat alt\r\n\tvector<vector <LLH>> buildingLLHS; // all the buildings\r\n\r\npublic:  // for generate map\r\n\ttypedef struct\r\n\t{\r\n\t\tdouble E;\r\n\t\tdouble N;\r\n\t\tdouble U;\r\n\t}ENU;\r\n\ttypedef struct // struct for a processed building information\r\n\t{\r\n\t\tdouble center_E; // center position of the building in E direction\r\n\t\tdouble center_N; // center position of the building in N direction\r\n\t\tdouble center_U; // center position of the building in U direction\r\n\t\tdouble ini_lon; // initial reference position for ENU\r\n\t\tdouble ini_lat; // initial reference position for ENU\r\n\t\tdouble ini_alt; // initial reference position for ENU\r\n\t\tvector <LLH> buildingLLHV; // building node list (each node with respect to a vertex) in llh\r\n\t\tvector <ENU> buildingENUV; // building node list (each node with respect to a vertex) in ENU\r\n\t\tvector<Point> buildingHull; // building hull points (used for later check if the point is inside the building) in ENU\r\n\t\tdouble sAzimuth; // smallest azimuth\r\n\t\tdouble bAzimuth; // bigest azimuth\r\n\r\n\r\n\t} building;\r\n\tvector<building> buildingS; // processed building information\r\n\ttypedef struct  // struct a map\r\n\t{\r\n\t\tvector<building> buildingS_M; // processed building information save in a map struct\r\n\t\t// lon lat alt boundary \r\n\t\tdouble lonMax; // max longitude\r\n\t\tdouble latMax; // max latitude\r\n\t\tdouble altMax; // max altitude\r\n\t\tMatrixXd llhMax = MatrixXd::Random(3, 1); // available \r\n\r\n\t\tdouble lonMin; // min longitude\r\n\t\tdouble latMin; // min latitude\r\n\t\tdouble altMin; // min altitude\r\n\t\tMatrixXd llhMin = MatrixXd::Random(3, 1); // available \r\n\r\n\t\t// ENU boundary\r\n\t\tdouble EMax; // max E\r\n\t\tdouble NMax; // max N\r\n\t\tdouble UMax; // max U\r\n\t\tMatrixXd ENUMax = MatrixXd::Random(3, 1); // available \r\n\r\n\t\tdouble EMin; //  min E\r\n\t\tdouble NMin; //  min N\r\n\t\tdouble UMin; //  min U\r\n\t\tMatrixXd ENUMin = MatrixXd::Random(3, 1); // available \r\n\r\n\t\t// original llh\r\n\t\tdouble lonOri; // original lon of ENU (refers to reference point)\r\n\t\tdouble latOri; // original lat of ENU (refers to reference point)\r\n\t\tdouble altOri; // original alt of ENU (refers to reference point)\r\n\t\tMatrixXd llhOri = MatrixXd::Random(3, 1);\r\n\r\n\t\t// minimum elevation angle and corresponding maxinum searching distance\r\n\t\tdouble MinElevation = 15; // satellites with a elevation less than 15 degree will not be considered\r\n\t\tdouble maxSearDis; // the maximum searching distance when finding the insections\r\n\t\t// azimuth search resolution \r\n\t\tdouble aziReso = 1.0; // azimuth search resolution \r\n\t\tdouble disReso = 2.0; // grid resolution for skymasks\r\n\t}map;\r\n\tmap map_; // the map saving all the buildings\r\n\r\npublic:  // for generate sky mask\r\n\ttypedef struct // mask elevation\r\n\t{\r\n\t\tdouble azimuth; // the azimuth \r\n\t\tdouble elevation; // the mask elevation\r\n\t}elevationMask;\r\n\r\n\ttypedef struct\r\n\t{\r\n\t\tLLH posLLH; // pose in LLH\r\n\t\tENU poseENU; // pose in ENU\r\n\t\tdouble buildingNum; // how many this position can intersect: if point inside building (buildingNum =1)\r\n\t\tbool insideBuilding; // inside buildings (=1) , outside building (=0)\r\n\t\tvector<elevationMask> aziElemask; // a vector \r\n\t}skyMask; // the sky mask in a position (refers to the skyplot in one position)\r\n\tvector<skyMask> skyMaskS; // save all the skymsk in one vector \r\n\r\npublic: // identify the intersection\r\n\t// Function used to display X and Y coordinates\r\n\t// of a point\r\n\tvoid displayPoint(Point_ P)\r\n\t{\r\n\t\tcout << \"(\" << P.x << \", \" << P.y\r\n\t\t\t<< \")\" << endl;\r\n\t}\r\n\r\n\tPoint_ lineLineIntersection(Point_ A, Point_ B, Point_ C, Point_ D)\r\n\t{\r\n\t\tPoint_ result;\r\n\t\t// Line AB represented as a1x + b1y = c1\r\n\t\tdouble a1 = B.y - A.y;\r\n\t\tdouble b1 = A.x - B.x;\r\n\t\tdouble c1 = a1*(A.x) + b1*(A.y);\r\n\r\n\t\t// Line CD represented as a2x + b2y = c2\r\n\t\tdouble a2 = D.y - C.y;\r\n\t\tdouble b2 = C.x - D.x;\r\n\t\tdouble c2 = a2*(C.x) + b2*(C.y);\r\n\r\n\t\tdouble determinant = a1*b2 - a2*b1;\r\n\r\n\t\tdouble x = (b2*c1 - b1*c2) / determinant;\r\n\t\tdouble y = (a1*c2 - a2*c1) / determinant;\r\n\t\tresult.x = x;\r\n\t\tresult.y = y;\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\tdouble disPP(Point_ A, Point_ B)\r\n\t{\r\n\t\treturn (double ) sqrt(((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y)));\r\n\t}\r\n\r\npublic:  // time delay\r\n\tvoid wait(int seconds)\r\n\t{\r\n\t\tclock_t endwait,start;\r\n\t\tstart = clock();\r\n\t\tendwait = clock() + seconds * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < endwait) {\r\n\t\t\tif(clock() - start > CLOCKS_PER_SEC)\r\n\t\t\t{\r\n\t\t\t\tstart = clock();\r\n\t\t\t\tstd::cout<<\".......1 s\"<<std::endl;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\npublic: // functions \r\n\t\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk)\r\n\tfunction: read kml and extract one building lla into a string\r\n\tinput: kml file\r\n\toutput: vector<string> variable\r\n\t*/\r\n\tvoid readKml(string filepath) // read kml file \r\n\t{\r\n\t\t/* test code*/\r\n\t\t/*ifstream OpenFile(\"NiuToujiao.kml\");\r\n\t\tchar ch;\r\n\t\twhile (!openfile.eof())\r\n\t\t{\r\n\t\t\topenfile.get(ch);\r\n\t\t\tcout << ch;\r\n\t\t}\r\n\t\topenfile.close();*/\r\n\t\tstd::cout << \"[Function]->readkml read .kml files to strings...\" << std::endl;\r\n\t\tifstream in(filepath);\r\n\t\tstring filename;\r\n\t\tstring line; // save content of one line \r\n\t\tint lineNum = 0; // line number\r\n\t\tstring search = \"coordinates\"; // searching \r\n\t\tvector<int> cLine; // save line numbers\r\n\t\tvector<string> allLines; // save all the lines of the kml file\r\n\t\t\r\n\t \tif (in) // file is available   \r\n\t\t{\r\n\t\t\tstd::cout<<\"begin read kml files...\"<<std::endl;\r\n\t\t\t\twhile (getline(in, line)) // line not contain line break (enter)\r\n\t\t\t\t{\r\n\t\t\t\t\t\tlineNum++;\r\n\t\t\t\t\t\t//cout << line << endl;\r\n\t\t\t\t\t\t//std::cout << \"line number\" << lineNum << endl;\r\n\t\t\t\t\t\tallLines.push_back(line);\r\n\t\t\t\t\t\tif (line.find(search, 0) != string::npos) {\r\n\t\t\t\t\t\t\t//cout << \"found: \" << search << \"line number : \" << lineNum << endl;\r\n\t\t\t\t\t\t\tcLine.push_back(lineNum-1); //  save line number\r\n\t\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcout << \"building amounts:\" << cLine.size()/2 << endl; // amount of buildings\r\n\t\t\t\tfor (auto it = cLine.begin(); it != cLine.end(); it++) {\r\n\t\t\t\t\tint temp = *it;\r\n\t\t\t\t\t//cout << \"one building data: \" << allLines[temp+1] << endl;\r\n\t\t\t\t\tbuilDataS.push_back(allLines[temp + 1]);\r\n\t\t\t\t\tit++;\r\n\t\t\t\t}\r\n\t\t\t\tfor (auto it = builDataS.begin(); it != builDataS.end(); it++) {\r\n\t\t\t\t\tcout << \"-----------------------------------buildings--------------------------------\" << \"\\n\" << *it << \"\\n\" << endl;\r\n\t\t\t\t}\r\n\r\n\t\t}\r\n\t\telse // file is not available\r\n\t\t{\r\n\t\t\tcout << \"no such kml file\" << endl;\r\n\t\t}\r\n\t}\r\n\r\n\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk)\r\n\tfunction: parse llh from string \r\n\tinput: vector<string>\r\n\toutput: vector<vector <LLH>> buildingLLHS; // all the buildings\r\n\t\t\t\t// the first [] indicates the building index, the second [] indicates the lla index in one building\r\n\t*/\r\n\tvoid string2llh(vector<string> data)// extract the llh from the string for each building\r\n\t{\r\n\t\tstd::cout << \"[Function]->string2llh llh string to llh double...\" << std::endl;\r\n\t\tvector<string> aBuilding;\r\n\t\tfor (auto it = data.begin(); it != data.end(); it++) { // for one building\r\n\t\t\tstring temp = *it;\r\n\r\n\t\t\tstring result;\r\n\t\t\tstringstream input(temp); // split by blank\r\n\t\t\twhile (input >> result)\r\n\t\t\t\taBuilding.push_back(result);\r\n\t\t\tfor (int i = 0; i<aBuilding.size(); i++) { // for one building again \r\n\t\t\t\tcout << \"each lon lat alt:  \"<<aBuilding[i] << endl;\r\n\t\t\t\tcout << \"size of this building :  \" << aBuilding.size() << endl;\r\n\t\t\t\t//split the string 114.1772621294604,22.29842880200087,58 and save it to  :vector <LLH> buildingLLH; \r\n\t\t\t\tstd::stringstream ss(aBuilding[i]); // split into three string\r\n\t\t\t\tvector<string> result;\r\n\t\t\t\twhile (ss.good())\r\n\t\t\t\t{\r\n\t\t\t\t\tstring substr;\r\n\t\t\t\t\tgetline(ss, substr, ',');\r\n\t\t\t\t\tresult.push_back(substr);\r\n\t\t\t\t}\r\n\t\t\t\tLLH llh_;\r\n\t\t\t\tfor (int k = 0; k < result.size(); k++)\r\n\t\t\t\t{\r\n\t\t\t\t\t//std::cout<<\"string result: \" << result.at(k) << std::endl;\r\n\t\t\t\t\tstring word;\r\n\t\t\t\t\tword = result.at(k);\r\n\t\t\t\t\tdouble value = strtod(word.c_str(), NULL);\r\n\t\t\t\t\tstd::cout << std::setprecision(17);\r\n\t\t\t\t\t//std::cout<< \"double result: \" << value << '\\n';\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (k == 0) {\r\n\t\t\t\t\t\tllh_.lon = value;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (k == 1) llh_.lat = value;\r\n\t\t\t\t\telse if (k == 2) llh_.alt = value;\r\n\t\t\t\t}\r\n\t\t\t\tbuildingLLH.push_back(llh_);\t\r\n\t\t\t}\r\n\t\t\taBuilding.clear(); // clear this after process a building (very important)\r\n\t\t\tcout << \"size of llh vector save in one building llh: \" << buildingLLH.size() << \"\\n\" << endl;\r\n\t\t\tcout << \"finish one buildings.......................................................................................................................\" << endl;\r\n\t\t\tbuildingLLHS.push_back(buildingLLH); // each building save in this vector\r\n\t\t\tbuildingLLH.clear(); // clear this after fully finished one building (very important)\r\n\t\t\t\r\n\r\n\t\t}\r\n\t\tcout << \"finish all buildings, total building number is : \" << buildingLLHS.size()<<\"\\n\" << endl; // \r\n\t\tstd::cout << std::setprecision(17);\r\n\t\t// the first [] indicates the building index, the second [] indicates the lla index in one building\r\n\t\tcout << std::setprecision(17)<< \"test: \" << buildingLLHS[0][0].lat - buildingLLHS[0][1].lat << \"\\n\" << endl; \r\n\t\tcout << \"-----------------------------------------------3D city map have been read into vector buildingLLHS ----------------------------------------\\n\\n\\n\\n\\n\\n\\n\\n\" << endl; // \r\n\t}\r\n\r\n\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk)\r\n\tfunction: preparing building data\r\n\tinput:vector<vector <LLH>> data // the first [] indicates the building index, the second [] indicates the lla index in one building\r\n\toutput:  prepared building information\r\n\r\n\tNotation:\r\n\t\t\tfirst node of the first building will be choose as the initial reference point for ENU\r\n\t*/\r\n\tvoid prepareBuildingData(vector<vector <LLH>> data) // prepare the building information: do some pre-processing\r\n\t{\r\n\t\tstd::cout << \"[Function]->prepareBuildingData transfer builidngs points, convex hull solving...\" << std::endl;\r\n\t\t//center of the building\r\n\t\t\r\n\t\tfloat count = 0; \r\n\t\tdouble lonMa=-100000; // lon max \r\n\t\tdouble latMa=-100000; // lat max \r\n\t\tdouble altMa=-100000; // alt max\r\n\t\t\r\n\t\tdouble lonMi=1000000; // lon min \r\n\t\tdouble latMi=1000000; // lat min\r\n\t\tdouble altMi=1000000; // alt min\r\n\r\n\t\tfor (int i = 0; i < data.size() ; i++) // index all the buildings \r\n\t\t{\r\n\t\t\tbuilding building_; // processed: a buidling information\r\n\t\t\tbuilding_.ini_lon = data[0][0].lon; // original lon \r\n\t\t\tbuilding_.ini_lat = data[0][0].lat; // original lat\r\n\t\t\tbuilding_.ini_alt = 0; // original alt\r\n\t\t\tfor (int j = 0; j < data[i].size() ; j++) // index the llh in one buildings\r\n\t\t\t{\r\n\t\t\t\tcount++;\r\n\t\t\t\tbuilding_.buildingLLHV.push_back(data[i][j]); // save llh in struct\r\n\t\t\t\t// save ENU\r\n\t\t\t\t//****obtain ecef\r\n\t\t\t\tEigen::MatrixXd llh;\r\n\t\t\t\tllh.resize(3, 1);\r\n\t\t\t\tEigen::MatrixXd ecef;\r\n\t\t\t\tecef.resize(3, 1);\r\n\t\t\t\tllh(0) = data[i][j].lon;\r\n\t\t\t\tllh(1) = data[i][j].lat;\r\n\t\t\t\tllh(2) = data[i][j].alt;\r\n\t\t\t\tecef = llh2ecef(llh); // position in ecef\r\n\t\t\t\t\r\n\t\t\t\t//****obtain ENU\r\n\t\t\t\tEigen::MatrixXd llhO;  //original\r\n\t\t\t\tllhO.resize(3, 1);\r\n\t\t\t\t//llhO(0) = data[0][0].lon; //original lon for ENU reference \r\n\t\t\t\t//llhO(1) = data[0][0].lat; //original lat for ENU reference \r\n\t\t\t\t//llhO(2) = data[0][0].alt; //original alt for ENU reference \r\n\r\n\t\t\t\tllhO(0) = building_.ini_lon; //original lon for ENU reference \r\n\t\t\t\tllhO(1) = building_.ini_lat; //original lat for ENU reference \r\n\t\t\t\tllhO(2) = building_.ini_alt; //original alt for ENU reference \r\n\t\t\t\tEigen::MatrixXd enu;\r\n\t\t\t\tenu.resize(3, 1);\r\n\t\t\t\tenu = ecef2enu(llhO, ecef);\r\n\r\n\t\t\t\t//****save ENU into building struct\r\n\t\t\t\tENU ENU_;\r\n\t\t\t\tENU_.E = enu(0); // save E\r\n\t\t\t\tENU_.N = enu(1); // save N\r\n\t\t\t\tENU_.U = enu(2); // save U\r\n\t\t\t\tbuilding_.buildingENUV.push_back(ENU_); // save ENU to \r\n\t\t\t\t//cout << \"total llh->count: \" << count << \"    building number->data.size()\" << data.size() << \"      llh number->data[i].size()\" << data[i].size() << \"   ecef:->\" << ecef << \"    enu:->\" << enu << \"\\n\"<<endl;\r\n\t\t\t\t\r\n\t\t\t\t//obtain the boundary of all the buidlings\r\n\t\t\t\tif (llh(0) > lonMa) lonMa = llh(0); // save the largest lon\r\n\t\t\t\tif (llh(1) > latMa) latMa = llh(1); // save the largest lat\r\n\t\t\t\tif (llh(2) > altMa) altMa = llh(2); // save the largest alt\r\n\r\n\t\t\t\tif (llh(0) < lonMi) lonMi = llh(0); // save the smallest lon\r\n\t\t\t\tif (llh(1) < latMi) latMi = llh(1); // save the smallest lat\r\n\t\t\t\tif (llh(2) < altMi) altMi = llh(2); // save the smallest alt\r\n\r\n\t\t\t}\r\n\t\t\t// solve the convex hull probelm, extract the hull of the building in 2D domain (in ENU)\r\n\t\t\tvector<Point> buildingNodePointFormat;\r\n\t\t\tfor (int index = 0; index < building_.buildingENUV.size(); index++) // index all the buildings \r\n\t\t\t{\r\n\t\t\t\tPoint temp_;\r\n\t\t\t\ttemp_.x = building_.buildingENUV[index].E;\r\n\t\t\t\ttemp_.y = building_.buildingENUV[index].N;\r\n\t\t\t\tbuildingNodePointFormat.push_back(temp_); // save all the node (ENU) into the Point format\r\n\t\t\t\t//cout << \"temp_x:  \" << temp_.x<< \"     temp_y:  \" << temp_.y<<\"\\n\";\r\n\t\t\t}\r\n\t\t\tbuilding_.buildingHull = convex_hull(buildingNodePointFormat);\r\n\t\t\tcout << \"before convex hull : \" << buildingNodePointFormat.size() << \"      after convex hull: \" << building_.buildingHull.size()<<\"\\n\";\r\n\t\t\tcout << \"enu size -------------------------------------------- ->: \" << building_.buildingENUV.size() << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\r\n\t\t\tbuildingS.push_back(building_);\r\n\t\t}\r\n\t\tmap_.buildingS_M = buildingS; // save all the buildings into the map \r\n\t\t//save the boundary lon lat alt\r\n\t\tmap_.lonMax = lonMa;\r\n\t\tmap_.latMax = latMa;\r\n\t\tmap_.altMax = altMa;\r\n\t\tmap_.llhMax(0) = lonMa;\r\n\t\tmap_.llhMax(1) = latMa;\r\n\t\tmap_.llhMax(2) = altMa;\r\n\r\n\t\tmap_.maxSearDis = map_.llhMax(2) / tan(15 * (3.1415926 / 180.0)); // calculate the maximum searching distance \r\n\r\n\t\tmap_.lonMin = lonMi;\r\n\t\tmap_.latMin = latMi;\r\n\t\tmap_.altMin = altMi;\r\n\t\tmap_.llhMin(0) = lonMi;\r\n\t\tmap_.llhMin(1) = latMi;\r\n\t\tmap_.llhMin(2) = altMi;\r\n\r\n\t\t/* initialize the reference point of the map: two methods\r\n\t\t1. initialize by boundary of the 3D city maps\r\n\t\t2. initialize by the provided ref lat and lon from generateSkymask.launch \r\n\t\t*/\r\n\t\tif(mannually_set_ref_llh_ == false)\r\n\t\t{\r\n\t\t\tmap_.llhOri(0) = data[0][0].lon;\r\n\t\t\tmap_.llhOri(1) = data[0][0].lat;\r\n\t\t\tmap_.llhOri(2) = 0;\r\n\t\t}\r\n\t\telse if(mannually_set_ref_llh_ == true)\r\n\t\t{\r\n\t\t\tmap_.llhOri(0) = ref_lon_fromlaunch;\r\n\t\t\tmap_.llhOri(1) = ref_lat_fromlaunch;\r\n\t\t\tmap_.llhOri(2) = 0;\r\n\t\t}\r\n\t\t\r\n\t\t//cout << \"original point \" << map_.llhOri << \"\\n\";\r\n\t\t//save the boundary in ENU : boundary means the maximum and minmum\r\n\t\tEigen::MatrixXd ecefTemp; // save the max \r\n\t\tecefTemp.resize(3, 1);\r\n\t\tecefTemp = llh2ecef(map_.llhMax); // position in ecef\r\n\t\tmap_.ENUMax = ecef2enu(map_.llhOri, ecefTemp);\r\n\t\tcout << \"map enu max   \" << map_.ENUMax<<\"  map_.llhOri-> \"<<map_.llhOri<<\"\\n\";\r\n\r\n\t\tecefTemp.resize(3, 1); // save the min \r\n\t\tecefTemp = llh2ecef(map_.llhMin); // position in ecef\r\n\t\tmap_.ENUMin = ecef2enu(map_.llhOri, ecefTemp);\r\n\t\tcout << \"map enu min \" << map_.ENUMin << \"\\n\";\r\n\r\n\t\tcout << \"-----------map information--------\" << map_.buildingS_M.size() << endl;\r\n\t\t/*\r\n\t\tmap_.lonMax :-122.3002392264451      map_.latMax 37.901411108972418      \r\n\t\tmap_.lonMin :-122.302402266828      map_.latMin 37.900422296017631\r\n\t\t*/\r\n\t\tcout << \"map_.lonMax :\" << map_.lonMax << \"      map_.latMax \" << map_.latMax << \"      map_.lonMin :\" << map_.lonMin << \"      map_.latMin \" << map_.latMin<<\"\\n\\n\";\r\n\r\n\t\tcout << \"-------------------------------------------------finish preparing all the buildings information and is saved to a map struct: ->  map_------------------------------------------------\\n\\n\";\r\n\t}\r\n\r\n\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk)\r\n\tfunction: llh to ecef\r\n\tinput: llh (Matrix3d)\r\n\toutput: ecef (Matrix3d)\r\n\t*/\r\n\tEigen::MatrixXd llh2ecef(Eigen::MatrixXd data) // transform the llh to ecef\r\n\t{\r\n\t\tEigen::MatrixXd ecef; // the ecef for output\r\n\t\tecef.resize(3, 1);\r\n\t\tdouble a = 6378137.0;\r\n\t\tdouble b = 6356752.314;\r\n\t\tdouble n, Rx, Ry, Rz;\r\n\t\tdouble lon = (double)data(0) * 3.1415926 / 180.0; // lon to radis\r\n\t\tdouble lat  = (double)data(1) * 3.1415926 / 180.0; // lat to radis\r\n\t\tdouble alt  = (double)data(2); // altitude\r\n\t\tn = a * a / sqrt(a * a * cos(lat) * cos(lat) + b * b * sin(lat) * sin(lat));\r\n\t\tRx = (n + alt) * cos(lat) * cos(lon);\r\n\t\tRy = (n + alt) * cos(lat) * sin(lon);\r\n\t\tRz = (b * b / (a * a) * n + alt) * sin(lat);\r\n\t\tecef(0) = Rx; // return value in ecef\r\n\t\tecef(1) = Ry; // return value in ecef\r\n\t\tecef(2) = Rz; // return value in ecef\r\n\t\treturn ecef;\r\n\r\n\t\t/**************for test purpose*************************\r\n\t\tEigen::MatrixXd llh;\r\n\t\tllh.resize(3, 1);\r\n\t\tEigen::MatrixXd ecef;\r\n\t\tecef.resize(3, 1);\r\n\t\tllh(0) = 114.1772621294604;\r\n\t\tllh(1) = 22.29842880200087;\r\n\t\tllh(2) = 58;\r\n\t\tecef = llh2ecef(llh);\r\n\t\tcout << \"ecef ->: \" << ecef << \"\\n\";\r\n\t\t*/\r\n\t}\r\n\r\n\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk)\r\n\tfunction: ecef to llh\r\n\tinput: ecef (Matrix3d)\r\n\toutput: llh (Matrix3d)\r\n\t*/\r\n\tEigen::MatrixXd ecef2llh(Eigen::MatrixXd data) // transform the ecef to llh\r\n\t{\r\n\t\tEigen::MatrixXd llh; // the ecef for output\r\n\t\tdouble pi = 3.1415926; // pi\r\n\t\tllh.resize(3, 1);\r\n\t\tdouble x = data(0); // obtain ecef \r\n\t\tdouble y = data(1);\r\n\t\tdouble z = data(2);\r\n\t\tdouble x2 = pow(x, 2);\r\n\t\tdouble y2 = pow(y, 2);\r\n\t\tdouble z2 = pow(z, 2);\r\n\r\n\t\tdouble a = 6378137.0000; //earth radius in meters\r\n\t\tdouble b = 6356752.3142; // earth semiminor in meters\r\n\t\tdouble e = sqrt(1 - (b / a) * (b / a));\r\n\t\tdouble b2 = b*b;\r\n\t\tdouble e2 = e*e;\r\n\t\tdouble  ep = e*(a / b);\r\n\t\tdouble  r = sqrt(x2 + y2);\r\n\t\tdouble  r2 = r*r;\r\n\t\tdouble  E2 = a * a - b*b;\r\n\t\tdouble F = 54 * b2*z2;\r\n\t\tdouble G = r2 + (1 - e2)*z2 - e2*E2;\r\n\t\tdouble c = (e2*e2*F*r2) / (G*G*G);\r\n\t\tdouble s = (1 + c + sqrt(c*c + 2 * c));\r\n\t\ts = pow(s, 1 / 3);\r\n\t\tdouble P = F / (3 * ((s + 1 / s + 1)*(s + 1 / s + 1)) * G*G);\r\n\t\tdouble Q = sqrt(1 + 2 * e2*e2*P);\r\n\t\tdouble ro = -(P*e2*r) / (1 + Q) + sqrt((a*a / 2)*(1 + 1 / Q) - (P*(1 - e2)*z2) / (Q*(1 + Q)) - P*r2 / 2);\r\n\t\tdouble tmp = (r - e2*ro)*(r - e2*ro);\r\n\t\tdouble U = sqrt(tmp + z2);\r\n\t\tdouble V = sqrt(tmp + (1 - e2)*z2);\r\n\t\tdouble zo = (b2*z) / (a*V);\r\n\r\n\t\tdouble height = U*(1 - b2 / (a*V));\r\n\r\n\t\tdouble lat = atan((z + ep*ep*zo) / r);\r\n\r\n\t\tdouble temp = atan(y / x);\r\n\t\tdouble long_;\r\n\t\tif (x >= 0)\r\n\t\t\tlong_ = temp;\r\n\t\telse if ((x < 0) && (y >= 0))\r\n\t\t\tlong_ = pi + temp;\r\n\t\telse\r\n\t\t\tlong_ = temp - pi;\r\n\t\tllh(0) = (long_)*(180 / pi);\r\n\t\tllh(1) = (lat)*(180 / pi);\r\n\t\tllh(2) = height;\r\n\t\treturn llh;\r\n\r\n\t\t/**************for test purpose*************************\r\n\t\tEigen::MatrixXd ecef;\r\n\t\tecef.resize(3, 1);\r\n\t\tEigen::MatrixXd llh;\r\n\t\tllh.resize(3, 1);\r\n\t\tecef(0) = -2418080.9387265667;\r\n\t\tecef(1) = 5386190.3905763263;\r\n\t\tecef(2) = 2405041.9305451373;\r\n\t\tllh = ecef2llh(ecef);\r\n\t\tcout << \"llh ->: \" << llh << \"\\n\";\r\n\t\t*/\r\n\t}\r\n\r\n\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk)\r\n\tfunction: ecef to enu\r\n\tinput: original llh, and current ecef (Matrix3d)\r\n\toutput: enu (Matrix3d)\r\n\t*/\r\n\tEigen::MatrixXd ecef2enu(Eigen::MatrixXd originllh, Eigen::MatrixXd ecef) // transform the ecef to enu \r\n\t{\r\n\t\tdouble pi = 3.1415926; // pi \r\n\t\tdouble DEG2RAD = pi / 180.0;\r\n\t\tdouble RAD2DEG = 180.0 / pi;\r\n\t\t\r\n\t\tEigen::MatrixXd enu; // the enu for output\r\n\t\tenu.resize(3, 1); // resize to 3X1\r\n\t\tEigen::MatrixXd oxyz; // the original position \r\n\t\toxyz.resize(3, 1); // resize to 3X1\r\n\r\n\t\tdouble x, y, z; // save the x y z in ecef\r\n\t\tx = ecef(0);\r\n\t\ty = ecef(1);\r\n\t\tz = ecef(2);\r\n\r\n\t\tdouble ox, oy, oz; // save original reference position in ecef\r\n\t\toxyz = llh2ecef(originllh);\r\n\t\tox = oxyz(0); // obtain x in ecef \r\n\t\toy = oxyz(1); // obtain y in ecef\r\n\t\toz = oxyz(2); // obtain z in ecef\r\n\r\n\t\tdouble dx, dy, dz;\r\n\t\tdx = x - ox;\r\n\t\tdy = y - oy;\r\n\t\tdz = z - oz;\r\n\r\n\t\tdouble lonDeg, latDeg, _; // save the origin lon alt in llh\r\n\t\tlonDeg = originllh(0);\r\n\t\tlatDeg = originllh(1);\r\n\t\tdouble lon = lonDeg * DEG2RAD;\r\n\t\tdouble lat = latDeg * DEG2RAD;\r\n\r\n\t\t//save ENU\r\n\t\tenu(0) = -sin(lon) * dx + cos(lon) * dy;\r\n\t\tenu(1) = -sin(lat) * cos(lon) * dx - sin(lat) * sin(lon) * dy + cos(lat) * dz;\r\n\t\tenu(2) = cos(lat) * cos(lon) * dx + cos(lat) * sin(lon) * dy + sin(lat) * dz;\r\n\t\treturn enu;\r\n\r\n\t\t/**************for test purpose*****suqare distance is about 37.4 meters********************\r\n\t\tEigen::MatrixXd llh;  //original\r\n\t\tllh.resize(3, 1);\r\n\t\tllh(0) = 114.1775072541416;\r\n\t\tllh(1) = 22.29817969722738;\r\n\t\tllh(2) = 58;\r\n\t\tEigen::MatrixXd ecef;\r\n\t\tecef.resize(3, 1);\r\n\t\tecef(0) = -2418080.9387265667;\r\n\t\tecef(1) = 5386190.3905763263;\r\n\t\tecef(2) = 2405041.9305451373;\r\n\t\tEigen::MatrixXd enu;\r\n\t\tenu.resize(3, 1);\r\n\t\tenu = ecef2enu(llh, ecef);\r\n\t\tcout << \"enu ->: \" << enu << \"\\n\";\r\n\t\t*/\r\n\t}\r\n\r\n\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk) \r\n\tfunction: identify if one point (given in ENU) is inside a building\r\n\tinput: map mapInput, Eigen::MatrixXd ENU\r\n\toutput: yes or no (bool)\r\n\t*/\r\n\tbool identifyPointInsideBuildingENU(map mapInput, Eigen::MatrixXd ENU) // identify if one point is inside the building (ENU)\r\n\t{\r\n\t\t// \r\n\t\tbool result=0; // 1: inside a builidng\r\n\t\tPoint_  ENUPoint = { ENU (0),ENU(1)}; // prepare the pont needed to be identified\r\n\r\n\t\t//index all the buildings\r\n\t\tfor (int i = 0; i < mapInput.buildingS_M.size(); i++) // index all the buildings in the map struct \r\n\t\t{\r\n\t\t\t\tbuilding building_; // processed: a buidling information\r\n\t\t\t\tPoint_ pointTemp; // temp \r\n\t\t\t\tvector<Point_> buildingPolygon; // save all the convex hull node \r\n\t\t\t\tfor (int j = 0; j < mapInput.buildingS_M[i].buildingHull.size(); j++) // index the every point in building hull (ENU) in one buildings\r\n\t\t\t\t{\r\n\t\t\t\t\t//cout << \" ENU--------mapInput.buildingS_M[i].buildingHull[j].x> \" << mapInput.buildingS_M[i].buildingHull[j].x << \"       ENU--------mapInput.buildingS_M[i].buildingHull[j].x> \" << mapInput.buildingS_M[i].buildingHull[j].y<<\"\\n\";\r\n\t\t\t\t\tpointTemp.x = mapInput.buildingS_M[i].buildingHull[j].x;\r\n\t\t\t\t\tpointTemp.y = mapInput.buildingS_M[i].buildingHull[j].y;\r\n\t\t\t\t\tbuildingPolygon.push_back(pointTemp);\r\n\t\t\t\t}\r\n\t\t\t\tif (isInside(buildingPolygon, buildingPolygon.size(), ENUPoint))\r\n\t\t\t\t{\r\n\t\t\t\t\t//isInside(buildingPolygon, buildingPolygon.size(), ENUPoint) ? cout << \"Yes in building ->:  \\n\" : cout << \"Not in building \\n\";\r\n\t\t\t\t\treturn isInside(buildingPolygon, buildingPolygon.size(), ENUPoint);\r\n\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t//isInside(buildingPolygon, buildingPolygon.size(), ENUPoint) ? cout << \"Yes in building ->:  \\n\" : cout << \"Not in building \\n\";\r\n\t\t\t\t//cout << \"mapInput.buildingS_M[i].buildingHull.size()--------> \" << mapInput.buildingS_M[i].buildingHull.size() << \"\\n\\n\";\r\n\t\t}\r\n\r\n\r\n\r\n\t\t/**************for test purpose*************************\r\n\t\tvector<Point_> polygon1 = { { 0, 0 },{ 10, 0 },{ 10, 10 },{ 0, 10 } };\r\n\t\t//int n = sizeof(polygon1) / sizeof(polygon1[0]);\r\n\t\tint n = polygon1.size();\r\n\t\tPoint_ p = { 20, 20 };\r\n\t\tisInside(polygon1, n, p) ? cout << \"Yes \\n\" : cout << \"No \\n\";\r\n\r\n\t\tp = { 5, 5 };\r\n\t\tisInside(polygon1, n, p) ? cout << \"Yes \\n\" : cout << \"No \\n\";\r\n\r\n\t\tvector<Point_> polygon2 = { { 0, 0 },{ 5, 5 },{ 5, 0 } };\r\n\t\tp = { 3, 3 };\r\n\t\t//n = sizeof(polygon2) / sizeof(polygon2[0]);\r\n\t\tn = polygon2.size();\r\n\t\tisInside(polygon2, n, p) ? cout << \"Yes \\n\" : cout << \"No \\n\";\r\n\r\n\t\tp = { 5, 1 };\r\n\t\tisInside(polygon2, n, p) ? cout << \"Yes \\n\" : cout << \"No \\n\";\r\n\r\n\t\tp = { 8, 1 };\r\n\t\tisInside(polygon2, n, p) ? cout << \"Yes \\n\" : cout << \"No \\n\";\r\n\r\n\t\tvector<Point_> polygon3 = { { 0, 0 },{ 10, 0 },{ 10, 10 },{ 0, 10 } };\r\n\t\tp = { -1,10 };\r\n\t\t//n = sizeof(polygon3) / sizeof(polygon3[0]);\r\n\t\tn = polygon3.size();\r\n\t\tisInside(polygon3, n, p) ? cout << \"Yes \\n\" : cout << \"No \\n\";\r\n\t\t\r\n\t\t*/\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk)\r\n\tfunction: identify if one point (given in LLH) is inside a building\r\n\tinput: map mapInput, Eigen::MatrixXd LLH\r\n\toutput: yes or no (bool)\r\n\r\n\tNotation:\r\n\t\t1: change LLH into ENU\r\n\t\t2. use identifyPointInsideBuildingENU subsequently\r\n\t*/\r\n\tbool identifyPointInsideBuildingLLH(map mapInput, Eigen::MatrixXd LLH) // identify if one point is inside the building (LLH)\r\n\t{\r\n\t\t// \r\n\t\tbool result = 0; // 1: inside a builidng\r\n\t\t// obtain ENU\r\n\t\t//****obtain ecef\r\n\t\tEigen::MatrixXd ecef;\r\n\t\tecef.resize(3, 1);\r\n\t\tecef = llh2ecef(LLH); // position in ecef\r\n\r\n\t\t//****obtain ENU\r\n\t\tEigen::MatrixXd llhO;  //original\r\n\t\tllhO.resize(3, 1);\r\n\t\tllhO(0) = mapInput.llhOri(0); //original lon for ENU reference \r\n\t\tllhO(1) = mapInput.llhOri(1); //original lat for ENU reference \r\n\t\tllhO(2) = mapInput.llhOri(2); //original alt for ENU reference \r\n\t\tEigen::MatrixXd enu;\r\n\t\tenu.resize(3, 1);\r\n\t\tenu = ecef2enu(llhO, ecef);\r\n\r\n\t\tPoint_  ENUPoint = { enu(0),enu(1) }; // prepare the pont needed to be identified\r\n\t\tresult = identifyPointInsideBuildingENU(mapInput, enu);\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk)\r\n\tfunction: get the mask elevation angle at a position with certain azimuth\r\n\tinput: map mapInput, Eigen::MatrixXd LLH, double azimuth\r\n\toutput: Eigen::MatrixXd (azimuth, maximum elevation angle , nearest intersect building number)\r\n\r\n\t*/\r\n\tEigen::MatrixXd getMaskElevationFromLLH(map mapInput, Eigen::MatrixXd LLH, double azimuth) // get the maximum elevation angle at a certain position (LLH) with a certain azimuth\r\n\t{\r\n\t\tEigen::MatrixXd result; // result(0)->azimuth  result(1)->elevation \r\n\t\tresult.resize(3,1);\r\n\t\tresult(2) = 10000;\r\n\t\tdouble Maxelevation = 0;\r\n\t\tdouble minDistance = 10000;\r\n\r\n\t\t// obtain ENU\r\n\t\t//****obtain ecef\r\n\t\tEigen::MatrixXd ecef;\r\n\t\tecef.resize(3, 1);\r\n\t\tecef = llh2ecef(LLH); // position in ecef\r\n\r\n\t\t //****obtain ENU of the given position\r\n\t\tEigen::MatrixXd llhO;  //original\r\n\t\tllhO.resize(3, 1);\r\n\t\tllhO(0) = mapInput.llhOri(0); //original lon for ENU reference \r\n\t\tllhO(1) = mapInput.llhOri(1); //original lat for ENU reference \r\n\t\tllhO(2) = mapInput.llhOri(2); //original alt for ENU reference \r\n\t\tEigen::MatrixXd enu;\r\n\t\tenu.resize(3, 1);\r\n\t\tenu = ecef2enu(llhO, ecef);\r\n\r\n\t\tresult = getMaskElevationFromENU(mapInput, enu, azimuth);\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk)\r\n\tfunction: get the mask elevation angle at a position with certain azimuth\r\n\tinput: map mapInput, Eigen::MatrixXd ENU, double azimuth\r\n\toutput: Eigen::MatrixXd (azimuth, maximum elevation angle  , nearest intersect building number)\r\n\r\n\t*/\r\n\tEigen::MatrixXd getMaskElevationFromENU(map mapInput, Eigen::MatrixXd ENU, double azimuth) // get the maximum elevation angle at a certain position (LLH) with a certain azimuth\r\n\t{\r\n\t\tEigen::MatrixXd result; // result(0)->azimuth  result(1)->elevation \r\n\t\tresult.resize(3, 1);\r\n\t\tdouble Maxelevation = 0; // maximum elevation of blockage\r\n\t\tdouble minDistance = 10000;\r\n\r\n\t\t// obtain ENU\r\n\t\tEigen::MatrixXd enu;\r\n\t\tenu.resize(3, 1);\r\n\t\tenu = ENU;\r\n\r\n\t\tEigen::MatrixXd enuEnd; // the segment end\r\n\t\tenuEnd.resize(3, 1);\r\n\t\tenuEnd(0) = enu(0) + mapInput.maxSearDis * sin(azimuth * (3.1415926 / 180.0));\r\n\t\tenuEnd(1) = enu(1) + mapInput.maxSearDis * cos(azimuth * (3.1415926 / 180.0));\r\n\t\tPoint_ p1;\r\n\t\tPoint_ q1;\r\n\t\tPoint_ p2;\r\n\t\tPoint_ q2;\r\n\t\tp1.x = enu(0);\r\n\t\tp1.y = enu(1);\r\n\t\tq1.x = enuEnd(0);\r\n\t\tq1.y = enuEnd(1);\r\n\r\n\t\t\r\n\t\t////index all the buildings in the maps\r\n\t\tfor (int i = 0; i < mapInput.buildingS_M.size(); i++) // index all the buildings in the map struct \r\n\t\t{\r\n\t\t\tbuilding building_; // processed: a buidling information\r\n\t\t\tPoint_ p2; // temp \r\n\t\t\tvector<Point_> buildingPolygon; // save all the convex hull node \r\n\t\t\t\t\t\t\t\t\t\t\t//#pragma omp parallel for\r\n\t\t\tfor (int j = 0; j < mapInput.buildingS_M[i].buildingENUV.size() - 1; j++) // index the every point in building hull (ENU) in one buildings\r\n\t\t\t{\r\n\t\t\t\tp2.x = mapInput.buildingS_M[i].buildingENUV[j].E;\r\n\t\t\t\tp2.y = mapInput.buildingS_M[i].buildingENUV[j].N;\r\n\r\n\t\t\t\tq2.x = mapInput.buildingS_M[i].buildingENUV[j + 1].E;\r\n\t\t\t\tq2.y = mapInput.buildingS_M[i].buildingENUV[j + 1].N;\r\n\r\n\t\t\t\tif (doIntersect(p1, q1, p2, q2)) // identify if intersect between line segment p1q1 and line segment p2q2\r\n\t\t\t\t{\r\n\t\t\t\t\t// intersection is available\r\n\r\n\t\t\t\t\tresult.resize(3, 1);\r\n\t\t\t\t\tPoint_ intersection;\r\n\t\t\t\t\tintersection = lineLineIntersection(p1, q1, p2, q2); // obtain the intersection in ENU\r\n\t\t\t\t\tdouble height = mapInput.buildingS_M[i].buildingENUV[j].U;\r\n\t\t\t\t\tdouble disP12Insec = disPP(p1, intersection); // distance from p1 to intersection\r\n\t\t\t\t\tif (disP12Insec < minDistance)  result(2) = i; // the building with shortest distance to point with intersection\r\n\t\t\t\t\tdouble elevation_ = 180.0 / 3.1415926 * atan(height / disP12Insec); // calculate the elevation \r\n\t\t\t\t\t//cout << \"intersection available---------------------------------------------------: \"<< disP12Insec<<\"       elevationMax: \"<< elevation_ <<\"\\n\\n\";\r\n\t\t\t\t\tif (elevation_ > Maxelevation)  Maxelevation = elevation_;\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t}\r\n\t\tresult(0) = azimuth;\r\n\t\tresult(1) = Maxelevation;\r\n\t\t//cout << \"azimuth: \" << azimuth << \"             Maxelevation---------------------------------: \" << Maxelevation << \"\\n\\n\";\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk)\r\n\tfunction: create skymask \r\n\tinput: map mapInput\r\n\toutput: skymasks\r\n\r\n\t*/\r\n\tvoid createSkymasks() // generate all the skymask\r\n\t{\r\n\t\t//generater all the skymasks\r\n\t\tstd::cout << \"[Function]->createSkymasks begin generate skymask ..........\" << std::endl;\r\n\t\t//_sleep(10000); // pauses for 10 seconds\r\n\t\tdouble deltaE = map_.ENUMax(0) - map_.ENUMin(0);\r\n\t\tstd::cout<<\"map_.ENUMax(0)->\"<<map_.ENUMax(0)<<\"     map_.ENUMin(0)\"<<map_.ENUMin(0)<<std::endl;\r\n\t\tdouble deltaN = map_.ENUMax(1) - map_.ENUMin(1);\r\n\t\tdouble skymaskNum = deltaN*deltaE / (pow(map_.disReso, 2));\r\n\t\tdouble finishNum = 0;\r\n\t\tcout << \"delta E ->:  \" << deltaE << \"             delta N->\" << deltaN<<\"\\n\\n\\n\";\r\n\t\twait(1);\r\n\t\tfor (double N = map_.ENUMin(1); N <= map_.ENUMax(1); N = N + map_.disReso) // search in the by line (N direction)\r\n\t\t{\r\n\t\t\tfor (double E = map_.ENUMin(0); E <=map_.ENUMax(0); E = E + map_.disReso) // search in the by line (E direction)\r\n\t\t\t{\r\n\t\t//for (double N = map_.ENUMin(1); N <= map_.ENUMin(1) + 3; N = N + map_.disReso) // search in the by line (N direction)\r\n\t\t//{\r\n\t\t//\tfor (double E = map_.ENUMin(0); E <= map_.ENUMin(0) + 3; E = E + map_.disReso) // search in the by line (E direction)\r\n\t\t//\t{\r\n\t\t\t\tbool insideBuildings = 0; // inside buildings ?\r\n\t\t\t\t// generate the skymask of one position in 360 degree\r\n\t\t\t\tEigen::MatrixXd ENU;\r\n\t\t\t\tENU.resize(1, 3);\r\n\t\t\t\tENU(0) = E;\r\n\t\t\t\tENU(1) = N;\r\n\t\t\t\tENU(2) = 0;\r\n\t\t\t\tskyMask skyMask_;\r\n\r\n\t\t\t\tconst clock_t begin_time = clock();\r\n\r\n\t\t\t\t// identify if this point is inside the building first\r\n\t\t\t\tif (identifyPointInsideBuildingENU(map_, ENU)) // if a point is inside a building, set elevation (result(1)) to -1.\r\n\t\t\t\t{\r\n\t\t\t\t\tinsideBuildings = 1; // this justification rule sometimes does not wok,\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (insideBuildings != 1) // not inside the buildings\r\n\t\t\t\t{\r\n\t\t\t\t\tcout << \"outside the building      \";\r\n\t\t\t\t\tfor (double azi = 0; azi <= 360; azi = azi + map_.aziReso)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tEigen::MatrixXd aziEleResult;\r\n\t\t\t\t\t\taziEleResult.resize(3, 1);\r\n\t\t\t\t\t\televationMask elevation_;\r\n\t\t\t\t\t\taziEleResult = getMaskElevationFromENU(map_, ENU, azi);\r\n\t\t\t\t\t\televation_.azimuth = aziEleResult(0);\r\n\t\t\t\t\t\televation_.elevation = aziEleResult(1);\r\n\r\n\t\t\t\t\t\tskyMask_.poseENU.E = ENU(0);\r\n\t\t\t\t\t\tskyMask_.poseENU.N = ENU(1);\r\n\t\t\t\t\t\tskyMask_.poseENU.U = ENU(2);\r\n\t\t\t\t\t\tskyMask_.insideBuilding = 0; // outside the building \r\n\t\t\t\t\t\tskyMask_.aziElemask.push_back(elevation_);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (insideBuildings == 1) // inside the buildings\r\n\t\t\t\t{\r\n\t\t\t\t\tcout << \"inside the building      \";\r\n\t\t\t\t\tfor (double azi = 0; azi <= 360; azi = azi + map_.aziReso)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tEigen::MatrixXd aziEleResult;\r\n\t\t\t\t\t\taziEleResult.resize(2, 1);\r\n\t\t\t\t\t\televationMask elevation_;\r\n\t\t\t\t\t\taziEleResult(0) = azi;\r\n\t\t\t\t\t\taziEleResult(1) = -1;\r\n\t\t\t\t\t\televation_.azimuth = aziEleResult(0);\r\n\t\t\t\t\t\televation_.elevation = aziEleResult(1);\r\n\r\n\t\t\t\t\t\tskyMask_.poseENU.E = ENU(0);\r\n\t\t\t\t\t\tskyMask_.poseENU.N = ENU(1);\r\n\t\t\t\t\t\tskyMask_.poseENU.U = ENU(2);\r\n\t\t\t\t\t\tskyMask_.insideBuilding = 1; // inside the building\r\n\t\t\t\t\t\tskyMask_.aziElemask.push_back(elevation_);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tfinishNum++;\r\n\t\t\t\tskyMaskS.push_back(skyMask_);\r\n\t\t\t\tcout <<\"total skymasks-> \"<< skymaskNum << \"finish sky mask->  \" << skyMaskS.size() << \"      rest skymask-> \"<< skymaskNum - finishNum;\r\n\t\t\t\tstd::cout << \"       this sky mask used  time -> \" << float(clock() - begin_time) / CLOCKS_PER_SEC << \"\\n\\n\";\r\n\t\t\t}\r\n\t\t}\r\n\t\tcout << \"finishing generate skymask...\\n\";\r\n\t\t\t\r\n\r\n\t\t\r\n\t}\r\n\r\n\t//void saveSkymasks2SCV(map mapInput) // save all the skymask into a csv file\r\n\t//{\r\n\t//\tcout << \"save skymask to csv file\" << \"\\n\";\r\n\t//\tstd::ofstream out(\"skymask.txt\");\r\n\t//\tstd::ostringstream strs;\r\n\t//\t// index the \r\n\t//\tfor (int grid = 0; grid <skyMaskS.size(); grid = grid + 1) // index grid\r\n\t//\t{\r\n\t//\t\tstrs << \"<skymask>\";\r\n\t//\t\tstrs << \"\\n\";\r\n\t//\t\tstrs << skyMaskS[grid].poseENU.E;\r\n\t//\t\tstrs << \",\";\r\n\t//\t\tstrs << skyMaskS[grid].poseENU.N;\r\n\t//\t\tstrs << \"\\n\";\r\n\t//\t\tfor (double sk = 0; sk < skyMaskS[grid].aziElemask.size(); sk = sk + 1) // index skymask\r\n\t//\t\t{\r\n\t//\t\t\t//string content;\r\n\t//\t\t\tstrs << skyMaskS[grid].aziElemask[sk].azimuth;// save azimuth\r\n\t//\t\t\tstrs << \",\";\r\n\t//\t\t\tstrs<< skyMaskS[grid].aziElemask[sk].elevation;  // save elevation\r\n\t//\t\t\tstrs << \",\";\r\n\t//\t\t\tstrs << skyMaskS[grid].insideBuilding;  // inside building\r\n\t//\t\t\tstrs << \"  \";\r\n\t//\t\t}\r\n\t//\t\tstrs << \"\\n\";\r\n\t//\t\tstrs << \"<skymask>\";\r\n\t//\t\tstrs << \"\\n\";\r\n\t//\t\tstrs << \"\\n\";\r\n\t//\t}\r\n\t//\tstring head; // save the ENU\r\n\t//\thead = strs.str();\r\n\t//\tout << head;\r\n\t//\tout.close(); // finish save file\r\n\t//\t\r\n\t//\t\r\n\t//\r\n\t//\t////save data to txt (from double to string first)\r\n\t//\t//std::ofstream out(\"output.txt\");\r\n\t//\t//std::ostringstream strs;\r\n\t//\t//double a = value * 100000;\r\n\t//\t//strs << a;\r\n\t//\t//std::string str = strs.str();\r\n\t//\t//out << str;\r\n\t//\t//out.close();\r\n\t//\r\n\t//}\r\n\r\n\t/*\r\n\tauthor: WEN Weisong (17902061r@connect.polyu.hk)\r\n\tfunction: save skymask to CSV file\r\n\tinput: map mapInput\r\n\toutput: skymasks\r\n\r\n\t*/\r\n\tvoid saveSkymasks2SCV(map mapInput,string saved_skymask_dir) // save all the skymask into a csv file\r\n\t{\r\n\t\tstd::cout << \"[Function]->saveSkymasks2SCV save skymask to csv file..........\" << std::endl;\r\n\t\t/*std::ofstream out(\"skymask.txt\");\r\n\t\tstd::ostringstream strs;*/\r\n\t\t// index the \r\n\t\tfor (int grid = 0; grid <skyMaskS.size(); grid = grid + 1) // index grid \u00a3\u00a8one grid one skymask file\u00a3\u00a9  \r\n\t\t{\r\n\t\t\tstring filename;\t\r\n\t\t\tstd::ostringstream filenameStrs; //\r\n\t\t\t// filenameStrs << \"/home/wenws/amsipolyu/src/rtklibros/app/generate_skymask/skymask/\";\r\n\t\t\tfilenameStrs << saved_skymask_dir;\r\n\t\t\tfilenameStrs << int(skyMaskS[grid].poseENU.E);\r\n\t\t\tfilenameStrs << \" \";\r\n\t\t\tfilenameStrs << int(skyMaskS[grid].poseENU.N);\r\n\t\t\tfilenameStrs << \".txt\";\r\n\t\t\tfilename = filenameStrs.str();\r\n\t\t\tstd::ofstream out(filename);\r\n\t\t\tstd::ostringstream strs;\r\n\t\t\tstd::cout << std::setprecision(17);\r\n\t\t\tdouble lon = mapInput.altMax;\r\n\t\t\tstrs << map_.llhOri(0);\r\n\t\t\tstrs << \",\";\r\n\t\t\tstrs << map_.llhOri(1);\r\n\t\t\tstrs << \",\";\r\n\t\t\tstrs << map_.llhOri(2);\r\n\t\t\tstrs << \"\\n\";\r\n\t\t\tstrs << \"<skymask>\";\r\n\t\t\tstrs << \"\\n\";\r\n\t\t\tstrs << skyMaskS[grid].poseENU.E; // E in ENU\r\n\t\t\tstrs << \",\";\r\n\t\t\tstrs << skyMaskS[grid].poseENU.N; // N in ENU\r\n\t\t\tstrs << \",\";\r\n\t\t\tstrs << skyMaskS[grid].insideBuilding;  // inside building\r\n\t\t\tstrs << \",\";\r\n\t\t\tstrs << 1;  // azimuth resolution\r\n\t\t\tstrs << \"\\n\";\r\n\t\t\tfor (double sk = 0; sk < skyMaskS[grid].aziElemask.size(); sk = sk + 1) // index skymask\r\n\t\t\t{\r\n\t\t\t\t//string content;\r\n\t\t\t\tstrs << skyMaskS[grid].aziElemask[sk].elevation;  // save elevation\r\n\t\t\t\tstrs << \"  \";\r\n\t\t\t}\r\n\t\t\tstrs << \"\\n\";\r\n\t\t\tstrs << \"<skymask>\";\r\n\t\t\tstrs << \"\\n\";\r\n\t\t\tstrs << \"\\n\";\r\n\r\n\t\t\tif (!skyMaskS[grid].insideBuilding)\r\n\t\t\t{\r\n\t\t\t\tstring head; // save the ENU\r\n\t\t\t\thead = strs.str();\r\n\t\t\t\tout << head;\r\n\t\t\t\tout.close(); // finish save file\r\n\t\t\t}\r\n\r\n\t\t\t\r\n\t\t}\r\n\t\tstd::cout << \"saved all the skymasks to certain directory..........\" << std::endl;\r\n\t}\r\n\r\nprivate:\r\n\tint reserve1;\r\n\r\n\tbool mannually_set_ref_llh_;\r\n\tdouble ref_lat_fromlaunch;\r\n\tdouble ref_lon_fromlaunch;\r\n};\r\n\r\n", "meta": {"hexsha": "735f627c773a4d5ae105a4ccb23b7a851fbbc6dd", "size": 45290, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rtklibros/app/generate_skymask/generateSkymask.hpp", "max_stars_repo_name": "StanleyHusai/mapping", "max_stars_repo_head_hexsha": "60c984437c75e8eead95a8fb649e72066f8e5e8f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-27T05:31:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T02:16:46.000Z", "max_issues_repo_path": "rtklibros/app/generate_skymask/generateSkymask.hpp", "max_issues_repo_name": "yxw027/GNSS-INS", "max_issues_repo_head_hexsha": "e5c5b7901b270a9c4d3a0ffd5555843d969f4018", "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": "rtklibros/app/generate_skymask/generateSkymask.hpp", "max_forks_repo_name": "yxw027/GNSS-INS", "max_forks_repo_head_hexsha": "e5c5b7901b270a9c4d3a0ffd5555843d969f4018", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T07:47:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T03:24:46.000Z", "avg_line_length": 34.2328042328, "max_line_length": 237, "alphanum_fraction": 0.6051887834, "num_tokens": 14540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6396457305007531}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// contingency_table2.cpp                                                    //\n//                                                                           //\n//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#include <cmath>\n#include <string>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/vector/vector10.hpp>\n#include <boost/mpl/detail/wrapper.hpp>\n\n#include <boost/typeof/typeof.hpp>\n\n#include <boost/assign/list_of.hpp>\n\n#include <boost/fusion/container/map/detail/sequence_to_map.hpp>\n#include <boost/fusion/include/make_map.hpp>\n \n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/framework/parameters/weight.hpp>\n#include <boost/accumulators/framework/accumulator_set.hpp>\n#include <boost/accumulators/statistics/detail/weighted_count.hpp>\n\n#include <boost/statistics/detail/non_parametric/contingency_table/include/factor.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/include/pearson_chisq/independence.hpp>\n#include <boost/statistics/detail/non_parametric/contingency_table/include/pearson_chisq/common.hpp>\n\n// Analysis of a dataset, and check that the results agree with the R software.\n// Source : http://www.math.wustl.edu/~victor/classes/ma322/r-eg-20.txt\n\n/*\n# Read the count data for this problem\ncount<-scan()\n   12  34  23         4  47  11\n   35  31  11        34  10  18\n   12  32   9        18  13  19\n   12  12  14         9  33  25 \n\n# Create factor tags:r=rows, c=columns, t=tiers\nr <- factor(gl(4, 2*3, 2*3*4, labels=c(\"r1\",\"r2\", \"r3\", \"r4\")));  r\nc <- factor(gl(3, 1,   2*3*4, labels=c(\"c1\",\"c2\", \"c3\")));  c\nt <- factor(gl(2, 3,   2*3*4, labels=c(\"t1\",\"t2\")));  t\n\n# Cross-tabulation of counts:\nxtabs(count~r+c+t)           # all three factors\nxtabs(count~r+c)             # RC: sum over tiers\nxtabs(count~r+t)             # RT: sum over columns\nxtabs(count~c+t)             # CT: sum over rows\nxtabs(count~r)       # R: sum over columns and tiers\nxtabs(count~c)       # C: sum over rows and tiers\nxtabs(count~t)       # T: sum over rows and columns\n\n# 3-way Chi squared test of independence\nsummary(xtabs(count~r+c+t))\n# 2-way Chi squared test of partial independence: R versus CT\nsummary(xtabs(count~c+t))\n# 2-way Chi squared test of partial independence: C versus RT\nsummary(xtabs(count~r+t))\n# 2-way Chi squared test of partial independence: T versus RC\nsummary(xtabs(count~r+c))\n*/\n\nvoid test_contingency_table2()\n{\n\n\tnamespace ct = boost::statistics::detail::contingency_table;\n    namespace ps = ct::pearson_chi_square_statistic;\n\n    typedef double val_;\n    typedef boost::mpl::int_<0> r_; typedef std::string data_r_;\n    typedef boost::mpl::int_<1> c_; typedef std::string data_c_;\n    typedef boost::mpl::int_<2> t_; typedef std::string data_t_;\n \n    typedef boost::fusion::detail::sequence_to_map<\n        boost::mpl::vector6<r_,data_r_,c_,data_c_,t_,data_t_>\n    >::type sample_;\n\n    typedef boost::mpl::vector3<r_,c_,t_> all_three_factors_;\n    typedef boost::mpl::vector2<r_,c_> sum_over_tiers_;\n    typedef boost::mpl::vector2<r_,t_> sum_over_cols_;\n    typedef boost::mpl::vector2<c_,t_> sum_over_rows_;\n\n    typedef ps::tag::independence_between<all_three_factors_> indep_r_c_t_;\n    typedef ps::tag::independence_between<sum_over_tiers_> indep_r_c_;\n    typedef ps::tag::independence_between<sum_over_cols_> indep_r_t_;\n    typedef ps::tag::independence_between<sum_over_rows_> indep_c_t_;\n\n    typedef boost::accumulators::stats<\n        indep_r_c_t_,\n        indep_r_c_,\n        indep_r_t_,\n        indep_c_t_\n    > stats_;\n    typedef boost::accumulators::accumulator_set< sample_, stats_, long int > acc_;\n        \n    using namespace boost::assign;\n    acc_ acc(( ct::_map_of_levels = boost::fusion::make_map<r_,c_,t_>(\n        list_of(\"r1\")(\"r2\")(\"r3\")(\"r4\"), \n        list_of(\"c1\")(\"c2\")(\"c3\"), \n        list_of(\"t1\")(\"t2\") ) \n    ));\n\n    typedef boost::fusion::result_of::make_map<\n        r_,c_,t_,data_r_,data_c_,data_t_>::type result_of_make_map_;\n    typedef result_of_make_map_(*fp_)(const data_r_&,const data_c_&,const data_t_&);\n    \n    fp_ make_sample = boost::fusion::make_map<r_,c_,t_>;\n\n    { \n        using namespace boost::accumulators;\n\n        acc( make_sample( \"r1\", \"c1\", \"t1\" ), weight = 12 );\n        acc( make_sample( \"r1\", \"c1\", \"t2\" ), weight =  4 );\n        acc( make_sample( \"r1\", \"c2\", \"t1\" ), weight = 34 );\n        acc( make_sample( \"r1\", \"c2\", \"t2\" ), weight = 47 );\n        acc( make_sample( \"r1\", \"c3\", \"t1\" ), weight = 23 );\n        acc( make_sample( \"r1\", \"c3\", \"t2\" ), weight = 11 );\n        acc( make_sample( \"r2\", \"c1\", \"t1\" ), weight = 35 );\n        acc( make_sample( \"r2\", \"c1\", \"t2\" ), weight = 34 );\n        acc( make_sample( \"r2\", \"c2\", \"t1\" ), weight = 31 );\n        acc( make_sample( \"r2\", \"c2\", \"t2\" ), weight = 10 );\n        acc( make_sample( \"r2\", \"c3\", \"t1\" ), weight = 11 );\n        acc( make_sample( \"r2\", \"c3\", \"t2\" ), weight = 18 );\n        acc( make_sample( \"r3\", \"c1\", \"t1\" ), weight = 12 );\n        acc( make_sample( \"r3\", \"c1\", \"t2\" ), weight = 18 );\n        acc( make_sample( \"r3\", \"c2\", \"t1\" ), weight = 32 );\n        acc( make_sample( \"r3\", \"c2\", \"t2\" ), weight = 13 );\n        acc( make_sample( \"r3\", \"c3\", \"t1\" ), weight =  9 );\n        acc( make_sample( \"r3\", \"c3\", \"t2\" ), weight = 19 );\n        acc( make_sample( \"r4\", \"c1\", \"t1\" ), weight = 12 );\n        acc( make_sample( \"r4\", \"c1\", \"t2\" ), weight =  9 );\n        acc( make_sample( \"r4\", \"c2\", \"t1\" ), weight = 12 );\n        acc( make_sample( \"r4\", \"c2\", \"t2\" ), weight = 33 );\n        acc( make_sample( \"r4\", \"c3\", \"t1\" ), weight = 14 );\n        acc( make_sample( \"r4\", \"c3\", \"t2\" ), weight = 25 );\n    }\n\n    using namespace std;\n    val_ stat, p_value;\n    long df;    \n\n/*\n#### Output and interpretation (at significance level alpha=0.05):\n   # 3-way Chi squared test of independence\n   > summary(xtabs(count~r+c+t))\n   Call: xtabs(formula = count ~ r + c + t)\n   Number of cases in table: 478\n   Number of factors: 3\n   Test for independence of all factors:\n\t   Chisq = 102.17, df = 17, p-value = 3.514e-14\n#\n# ==> reject H0 in favor of \n#            HA: r,c,t are NOT mutually independent\n#\n*/\n\n   {\n        typedef boost::mpl::detail::wrapper<indep_r_c_t_> h0_;\n        df = ps::degrees_of_freedom( h0_(), acc);\n        stat = ps::value( h0_(), acc ); \n        p_value = cdf( complement( \n            ps::asy_distribution( h0_(), acc ), \n            stat\n        ) );\n        BOOST_CHECK( df == 17 );\n        BOOST_CHECK( fabs( stat - 102.17 ) < 0.01 );\n        BOOST_CHECK( fabs( p_value - 3.514e-14 ) < 0.001e-14 );\n    }\n\n/*\n   > # 2-way Chi squared test of partial independence: R versus CT\n   > summary(xtabs(count~c+t))\n   Call: xtabs(formula = count ~ c + t)\n   Number of cases in table: 478\n   Number of factors: 2\n   Test for independence of all factors:\n\t   Chisq = 2.3704, df = 2, p-value = 0.3057\n#\n# ==> do not reject H0: c,t are mutually independent\n#\n*/\n\n   {\n        typedef boost::mpl::detail::wrapper<indep_c_t_> h0_;\n        df = ps::degrees_of_freedom( h0_(), acc);\n        stat = ps::value( h0_(), acc ); \n        p_value = cdf( complement( \n            ps::asy_distribution( h0_(), acc ), \n            stat\n        ) );\n        BOOST_CHECK( df == 2 );\n        BOOST_CHECK( fabs( stat == 2.3704 )< 0.001 );\n        BOOST_CHECK( fabs( p_value - 0.3057 ) < 0.0001 );\n    }\n/*\n   >\n   > # 2-way Chi squared test of partial independence: C versus RT\n   > summary(xtabs(count~r+t))\n   Call: xtabs(formula = count ~ r + t)\n   Number of cases in table: 478\n   Number of factors: 2\n   Test for independence of all factors:\n\t   Chisq = 10.057, df = 3, p-value = 0.01809\n#\n# ==> reject H0 in favor of \n#            HA: r,t are NOT mutually independent\n\n*/\n    {\n        typedef boost::mpl::detail::wrapper<indep_r_t_> h0_;\n        df = ps::degrees_of_freedom( h0_(), acc);\n        stat = ps::value( h0_(), acc ); \n        p_value = cdf( complement( \n            ps::asy_distribution( h0_(), acc ), \n            stat\n        ) );\n        BOOST_CHECK( df == 3 );\n        BOOST_CHECK( fabs( stat - 10.057 ) < 0.001 );\n        BOOST_CHECK( fabs( p_value - 0.01809 ) < 0.00001 );\n    }\n/*\n   > # 2-way Chi squared test of partial independence: T versus RC\n   > summary(xtabs(count~r+c))\n   Call: xtabs(formula = count ~ r + c)\n   Number of cases in table: 478\n   Number of factors: 2\n   Test for independence of all factors:\n\t   Chisq = 58.67, df = 6, p-value = 8.363e-11\n\n#\n# ==> reject H0 in favor of \n#            HA: r,c are NOT mutually independent\n#\n*/\n\n   {\n        typedef boost::mpl::detail::wrapper<indep_r_c_> h0_;\n        df = ps::degrees_of_freedom( h0_(), acc);\n        stat = ps::value( h0_(), acc ); \n        p_value = cdf( complement( \n            ps::asy_distribution( h0_(), acc ), \n            stat\n        ) );\n        BOOST_CHECK( df == 6 );\n        BOOST_CHECK( fabs( stat - 58.67 ) < 0.01 );\n        BOOST_CHECK( fabs( p_value - 8.363e-11 ) < 0.001e-11 );\n    }\n\n}\n\n", "meta": {"hexsha": "cadac6b5e53f8174ce5f79346943e2c9065d7055", "size": 9325, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "non_parametric/libs/statistics/detail/non_parametric/test/contingency_table2.cpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_parametric/libs/statistics/detail/non_parametric/test/contingency_table2.cpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_parametric/libs/statistics/detail/non_parametric/test/contingency_table2.cpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.42578125, "max_line_length": 106, "alphanum_fraction": 0.5828418231, "num_tokens": 2855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101077, "lm_q2_score": 0.7799929104825007, "lm_q1q2_score": 0.6395109756338563}}
{"text": "/*\n\n [begin_description]\n Test case for issue 149:\n Error C2582 with msvc-10 when using iterator-based integration\n [end_description]\n\n Copyright 2011-2015 Karsten Ahnert\n Copyright 2011-2015 Mario Mulansky\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n// disable checked iterator warning for msvc\n\n#include <boost/config.hpp>\n#ifdef BOOST_MSVC\n    #pragma warning(disable:4996)\n#endif\n\n#define BOOST_TEST_MODULE odeint_regression_147\n\n#include <utility>\n#include <iostream>\n\n#include <boost/array.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/vector.hpp>\n#include <boost/range/algorithm/find_if.hpp>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/algebra/fusion_algebra.hpp>\n#include <boost/numeric/odeint/algebra/fusion_algebra_dispatcher.hpp>\n\n\n#include <boost/units/systems/si/length.hpp>\n#include <boost/units/systems/si/time.hpp>\n#include <boost/units/systems/si/velocity.hpp>\n#include <boost/units/systems/si/acceleration.hpp>\n#include <boost/units/systems/si/io.hpp>\n\n#include <boost/fusion/container.hpp>\n\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\nnamespace mpl = boost::mpl;\n\nnamespace fusion = boost::fusion;\nnamespace units = boost::units;\nnamespace si = boost::units::si;\n\ntypedef units::quantity< si::time , double > time_type;\ntypedef units::quantity< si::length , double > length_type;\ntypedef units::quantity< si::velocity , double > velocity_type;\ntypedef units::quantity< si::acceleration , double > acceleration_type;\ntypedef units::quantity< si::frequency , double > frequency_type;\n\ntypedef fusion::vector< length_type , velocity_type > state_type;\ntypedef fusion::vector< velocity_type , acceleration_type > deriv_type;\n\n\nstruct oscillator\n{\n    frequency_type m_omega;\n\n    oscillator( const frequency_type &omega = 1.0 * si::hertz ) : m_omega( omega ) { }\n\n    void operator()( const state_type &x , deriv_type &dxdt , time_type t ) const\n    {\n        fusion::at_c< 0 >( dxdt ) = fusion::at_c< 1 >( x );\n        fusion::at_c< 1 >( dxdt ) = - m_omega * m_omega * fusion::at_c< 0 >( x );\n    }\n};\n\n\nBOOST_AUTO_TEST_CASE( regression_168 )\n{\n    typedef runge_kutta_dopri5< state_type , double , deriv_type , time_type > stepper_type;\n\n    state_type x( 1.0 * si::meter , 0.0 * si::meter_per_second );\n\n    integrate_const( make_dense_output( 1.0e-6 , 1.0e-6 , stepper_type() ) , oscillator( 2.0 * si::hertz ) ,\n                     x , 0.0 * si::second , 100.0 * si::second , 0.1 * si::second);\n}", "meta": {"hexsha": "7cb87ef7df7b646acf00d6f6b3f81f5a1b04b885", "size": 2601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/numeric/odeint/test/regression/regression_168.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/libs/numeric/odeint/test/regression/regression_168.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/libs/numeric/odeint/test/regression/regression_168.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 28.9, "max_line_length": 108, "alphanum_fraction": 0.723952326, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6395092392080046}}
{"text": "#include \"expt.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include \"utility/itoa.hpp\"\n#include <boost/variant.hpp>\n#include <cmath>\n#include <stdexcept>\n#include <algorithm>\n#include <complex>\n\nnamespace HT\n{\n    void expt(PASTNode astnode, ParsersHelper& ph)\n    {\n        auto myParserHelper(ph);\n        if (astnode->ch.size()!=3)\n          throw std::runtime_error(\"expt should have exact 2 parameters\");\n        auto & thirdCh = *astnode->ch.rbegin();\n        auto & secondCh = *(++astnode->ch.begin());\n        ph.parse(secondCh);\n        ph.parse(thirdCh);\n        if (secondCh->token.tokenType!=Complex )\n          throw std::runtime_error(\"The arguments of expt should be Complex\");\n        \n        if (thirdCh->token.tokenType!=Complex )\n          throw std::runtime_error(\"The arguments of expt should be Complex\");\n\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        auto cast =boost::get<ComplexType>(secondCh->token.info);\n        auto third = boost::get<ComplexType>(thirdCh->token.info);\n        cast.toinexact();\n        third.toinexact();\n\n        if (cast == 0) \n            astnode->token.info = ComplexType(0.0);\n        else\n        {\n            // (a+bi)^(c+di) =\n            // r1^c * e^(-d*theta1) * e^((thera1*c + dln(r1))i)\n            std::complex<long double> a(cast.getRealD(), cast.getImagD());\n            std::complex<long double> b(third.getRealD(), third.getImagD());\n            auto ans = std::pow(a,b);\n    \n            astnode->token.info = \n                ComplexType(\n                            ans.real(),\n                            ans.imag()\n                           );\n        }\n\n\n        \n\n        astnode->remove();\n    }\n}\n\n\n", "meta": {"hexsha": "e7be1537c5447aa7b82a4efc1d2cf8f09ca1ee45", "size": 1738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/expt.cpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "funs/expt.cpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funs/expt.cpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4918032787, "max_line_length": 78, "alphanum_fraction": 0.5397008055, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.6394790353836098}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include \"math_utils.hpp\"\n#undef far\n#undef near\n\nnamespace vgl {\ntemplate <typename T>\nEigen::Matrix<T, 4, 4> orthographic_projection(double const left, double const right, double const top,\n                                             double const bottom, double const near, double const far) {\n    Eigen::Matrix<T, 4, 4> proj_mat = Eigen::Matrix<T, 4, 4>::Identity();\n    auto const width = right - left;\n    auto const height = top - bottom;\n    auto const depth = far - near;\n    proj_mat(0, 0) = static_cast<T>(2.0 / width);\n    proj_mat(1, 1) = static_cast<T>(2.0 / height);\n    proj_mat(2, 2) = static_cast<T>(-2.0 / depth);\n    proj_mat(0, 3) = static_cast<T>(-(right + left) / width);\n    proj_mat(1, 3) = static_cast<T>(-(top + bottom) / height);\n    proj_mat(2, 3) = static_cast<T>(-(far + near) / depth);\n    return proj_mat;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 4, 4> orthographic_projection(double const width, double const height, double const near,\n                                             double const far) {\n    Eigen::Matrix<T, 4, 4> proj_mat = Eigen::Matrix<T, 4, 4>::Identity();\n    proj_mat(0, 0) = static_cast<T>(2.0 / width);\n    proj_mat(1, 1) = static_cast<T>(2.0 / height);\n    auto const depth = far - near;\n    proj_mat(2, 2) = static_cast<T>(-2.0 / depth);\n    proj_mat(2, 3) = static_cast<T>(-(far + near) / depth);\n    return proj_mat;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 4, 4> frustum_projection(double const left, double const right, double const top, double const bottom,\n                                        double const near, double const far) {\n    Eigen::Matrix<T, 4, 4> proj_mat = Eigen::Matrix<T, 4, 4>::Identity();\n    auto const width = right - left;\n    auto const height = top - bottom;\n    auto const depth = far - near;\n    proj_mat(0, 0) = static_cast<T>(2.0 * near / width);\n    proj_mat(1, 1) = static_cast<T>(2.0 * near / height);\n    proj_mat(0, 2) = static_cast<T>((right + left) / width);\n    proj_mat(1, 2) = static_cast<T>((top + bottom) / height);\n    proj_mat(2, 2) = static_cast<T>(-(far + near) / depth);\n    proj_mat(2, 3) = static_cast<T>(-2.0 * far * near / depth);\n    proj_mat(3, 2) = static_cast<T>(-1.0);\n    return proj_mat;\n}\n\ntemplate <typename T>\nEigen::Matrix<T, 4, 4> perspective_projection(double const aspect_ratio, double const fovy, double const near,\n                                            double const far) {\n    Eigen::Matrix<T, 4, 4> proj_mat = Eigen::Matrix<T, 4, 4>::Identity();\n    auto const tan_half_fovy = math::to_radians(fovy / 2.0);\n    auto const depth = far - near;\n    proj_mat(0, 0) = static_cast<T>(1.0 / (aspect_ratio * tan_half_fovy));\n    proj_mat(1, 1) = static_cast<T>(1.0 / tan_half_fovy);\n    proj_mat(2, 2) = static_cast<T>(-(far + near) / depth);\n    proj_mat(2, 3) = static_cast<T>(-2.0 * far * near / depth);\n    proj_mat(3, 2) = static_cast<T>(-1.0);\n    return proj_mat;\n}\n\ntemplate <typename T>\nvoid change_aspect_ratio(Eigen::Matrix<T, 4, 4>& proj, double aspect_ratio) {\n    proj(0, 0) = static_cast<T>(proj(1, 1) / aspect_ratio);\n}\n\ntemplate <typename T>\nvoid change_fovy(Eigen::Matrix<T, 4, 4>& proj, double fovy) {\n    auto old = proj(1, 1);\n    auto tan_half = std::tan(fovy / 2.0);\n    proj(0, 0) = static_cast<T>(proj(0, 0) / old / tan_half);\n    proj(1, 1) = static_cast<T>(1.0 / tan_half);\n}\n} // namespace vgl\n", "meta": {"hexsha": "c40dd74853afe84330fcb845517abe091798053b", "size": 3390, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/vgl/math/projection.hpp", "max_stars_repo_name": "alexsr/vgl", "max_stars_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-18T18:27:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-18T18:27:19.000Z", "max_issues_repo_path": "src/vgl/math/projection.hpp", "max_issues_repo_name": "alexsr/vgl", "max_issues_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vgl/math/projection.hpp", "max_forks_repo_name": "alexsr/vgl", "max_forks_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8518518519, "max_line_length": 119, "alphanum_fraction": 0.6085545723, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6394340671874006}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_LOG_DIFF_EXP_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_LOG_DIFF_EXP_HPP\n\n#include <stan/math/prim/scal/fun/log1m_exp.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <boost/throw_exception.hpp>\n#include <limits>\n#include <stdexcept>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * The natural logarithm of the difference of the natural exponentiation\n     * of x1 and the natural exponentiation of x2\n     *\n     * This function is only defined for x<0\n     *\n     *\n       \\f[\n       \\mbox{log\\_diff\\_exp}(x, y) =\n       \\begin{cases}\n         \\textrm{NaN} & \\mbox{if } x \\leq y\\\\\n         \\ln(\\exp(x)-\\exp(y)) & \\mbox{if } x > y \\\\[6pt]\n         \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n       \\end{cases}\n       \\f]\n\n       \\f[\n       \\frac{\\partial\\, \\mbox{log\\_diff\\_exp}(x, y)}{\\partial x} =\n       \\begin{cases}\n         \\textrm{NaN} & \\mbox{if } x \\leq y\\\\\n         \\frac{\\exp(x)}{\\exp(x)-\\exp(y)} & \\mbox{if } x > y \\\\[6pt]\n         \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n       \\end{cases}\n       \\f]\n\n       \\f[\n       \\frac{\\partial\\, \\mbox{log\\_diff\\_exp}(x, y)}{\\partial y} =\n       \\begin{cases}\n         \\textrm{NaN} & \\mbox{if } x \\leq y\\\\\n         -\\frac{\\exp(y)}{\\exp(x)-\\exp(y)} & \\mbox{if } x > y \\\\[6pt]\n         \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n       \\end{cases}\n       \\f]\n     *\n     */\n    template <typename T1, typename T2>\n    inline typename boost::math::tools::promote_args<T1, T2>::type\n    log_diff_exp(const T1 x, const T2 y) {\n      if (x <= y)\n        return std::numeric_limits<double>::quiet_NaN();\n      return x + log1m_exp(y - x);\n    }\n\n  }\n}\n\n#endif\n", "meta": {"hexsha": "81e29591a800a9ba0730e9e0ed86357c1aaa8d60", "size": 1711, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/log_diff_exp.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/log_diff_exp.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/scal/fun/log_diff_exp.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5166666667, "max_line_length": 76, "alphanum_fraction": 0.5493863238, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6394340429689128}}
{"text": "#include <boost/multiprecision/cpp_dec_float.hpp> \n#include \"ARPoly.h\"\n#include \"GaussSeq.h\"\n#include \"utils.h\"\nusing utils::my_float;\n\n\n/*\n *  Constructors and destructors\n */\nARPoly::ARPoly(std::map<int, my_float> mp, std::map<int, my_float> powers):\n    ARSeq(mp),\n    powers{powers}\n{}\nARPoly::ARPoly(std::map<int, my_float> mp, std::map<int, my_float> powers, my_float bias):\n    ARSeq(mp, bias),\n    powers{powers}\n{}\n\n/*\n *  Member functions\n */\nmy_float ARPoly::next() {\n    namespace mp = boost::multiprecision;\n    std::vector<my_float> copy_prev = prev_val;\n\n    for (const auto& ele : powers) {\n        // subtract one since the zero-index is the previous value\n        copy_prev[ele.first - 1] = mp::pow(prev_val[ele.first - 1], ele.second);\n    }\n    // Since the lag coefficients are only non-zero at non-zero constants, take the dot-product\n    my_float result = utils::dot_product(copy_prev, lag_coeff) + g.next() + bias;\n    utils::shift_vector(prev_val);\n    prev_val[0] = result;\n    return result;\n}\n", "meta": {"hexsha": "07980896ea7423059f9fdfe82905705a07f26966", "size": 1021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aug-data/lib/ARPoly.cpp", "max_stars_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_stars_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aug-data/lib/ARPoly.cpp", "max_issues_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_issues_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aug-data/lib/ARPoly.cpp", "max_forks_repo_name": "kvathupo/Synthetic-Time-Series-Generator", "max_forks_repo_head_hexsha": "ac133d2b0beff7f93f686742ce59401bc3cd1b90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5945945946, "max_line_length": 95, "alphanum_fraction": 0.6709108717, "num_tokens": 277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6393674708811191}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n#include <OpenTissue/core/math/math_kmeans.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n#include <cmath>\n#include <iostream>\n\nusing namespace OpenTissue;\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_kmeans);\n\nBOOST_AUTO_TEST_CASE(simple_test)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  typedef math_types::matrix3x3_type                       matrix3x3_type;\n  typedef math_types::real_type                            real_type;\n  typedef math_types::index_type                           index_type;\n  typedef math_types::value_traits                         value_traits;\n  typedef std::vector<vector3_type>                        vector_container;\n  typedef std::vector<size_t>                              index_container;\n\n  vector_container features;\n  size_t index = 0;\n  features.resize(40);\n  real_type lower = - value_traits::half();\n  real_type upper = value_traits::half();\n\n  vector3_type center[4];\n  center[0] = vector3_type( value_traits::half(), value_traits::half(), -value_traits::two() );\n  center[1] = vector3_type( -value_traits::four(), value_traits::zero(), -value_traits::half() );\n  center[2] = vector3_type( value_traits::half(), value_traits::four(), value_traits::half() );\n  center[3] = vector3_type( value_traits::half(), -value_traits::two(), value_traits::four() );\n\n  for(size_t i = 0;i<10;++i,++index)\n  {\n    OpenTissue::math::random( features[index], lower, upper );\n    features[index] += center[0];\n  }\n  for(size_t i = 0;i<10;++i,++index)\n  {\n    OpenTissue::math::random( features[index], lower, upper );\n    features[index] += center[1];\n  }\n  for(size_t i = 0;i<10;++i,++index)\n  {\n    OpenTissue::math::random( features[index], lower, upper );\n    features[index] += center[2];\n  }\n  for(size_t i = 0;i<10;++i,++index)\n  {\n    OpenTissue::math::random( features[index], lower, upper );\n    features[index] += center[3];\n  }\n\n  vector_container cluster_centers;\n  index_container cluster_indexes;\n\n  size_t K = 4;\n  size_t iteration = 0u;\n  size_t max_iterations = 50u;\n\n  // K-means may get caught by local minimas, in such cases clusters\n  // seem to ``melt'' together unexpected.\n  //\n  // If k-means gets caught by a local minima then all the following\n  // unit-tests is likely to fail!\n  //\n  OpenTissue::math::kmeans( \n    features.begin()\n    , features.end()\n    , cluster_centers\n    , cluster_indexes\n    , K\n    , iteration\n    , max_iterations\n    );\n\n  BOOST_CHECK( iteration < max_iterations );\n\n  for(size_t i = 0;i<40;++i)\n    std::cout << cluster_indexes[i] << \" \";\n  std::cout << std::endl;\n\n  size_t cluster_order[4];\n  cluster_order[0] = cluster_indexes[0];\n  cluster_order[1] = cluster_indexes[10];\n  cluster_order[2] = cluster_indexes[20];\n  cluster_order[3] = cluster_indexes[30];\n\n  BOOST_CHECK( cluster_order[0] != cluster_order[1] );\n  BOOST_CHECK( cluster_order[0] != cluster_order[2] );\n  BOOST_CHECK( cluster_order[0] != cluster_order[3] );\n  BOOST_CHECK( cluster_order[1] != cluster_order[2] );\n  BOOST_CHECK( cluster_order[1] != cluster_order[3] );\n  BOOST_CHECK( cluster_order[2] != cluster_order[3] );\n\n  for(size_t i = 0;i<10;++i)\n    BOOST_CHECK( cluster_indexes[i] ==  cluster_order[0] );\n  for(size_t i = 10;i<20;++i)\n    BOOST_CHECK( cluster_indexes[i] ==  cluster_order[1] );\n  for(size_t i = 20;i<30;++i)\n    BOOST_CHECK( cluster_indexes[i] ==  cluster_order[2] );\n  for(size_t i = 30;i<40;++i)\n    BOOST_CHECK( cluster_indexes[i] ==  cluster_order[3] );\n\n  for(size_t c = 0;c<K;++c)\n  {\n    std::cout << cluster_centers[ cluster_order[c] ] << std::endl;\n    real_type dist = OpenTissue::math::length( center[c] - cluster_centers[ cluster_order[c] ] );\n    BOOST_CHECK(dist < value_traits::half() );\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "a71b528b1883796bff999998ff0dec9f7e554c2e", "size": 4339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/kmeans/src/unit_kmeans.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/kmeans/src/unit_kmeans.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/kmeans/src/unit_kmeans.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 33.6356589147, "max_line_length": 97, "alphanum_fraction": 0.6722747177, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6393674677120132}}
{"text": "#ifndef HYPSYS1D_MODEL_HPP\n#define HYPSYS1D_MODEL_HPP\n\n#include <cmath>\n#include <memory>\n\n#include <Eigen/Dense>\n#include <ancse/config.hpp>\n\n/// Interface for implementing different models,\n/// eg. Euler equations, Shallow-water equations\n///\n/// Add more functions to this interface if needed.\nclass Model {\n  public:\n    virtual ~Model() = default;\n\n    // Pure virtual functions:\n    virtual Eigen::VectorXd flux(const Eigen::VectorXd& u) const = 0;\n    virtual Eigen::VectorXd eigenvalues(const Eigen::VectorXd& u) const = 0;\n    virtual Eigen::MatrixXd eigenvectors(const Eigen::VectorXd& u) const = 0;\n    virtual double max_eigenvalue(const Eigen::VectorXd& u) const = 0;\n\n    virtual Eigen::VectorXd cons_to_prim(const Eigen::VectorXd& u) const = 0;\n    virtual Eigen::VectorXd prim_to_cons(const Eigen::VectorXd& u) const = 0;\n\n    virtual int get_nvars() const = 0;\n    virtual std::string get_name() const = 0;\n\n    // Virtual functions:\n    virtual std::pair<double, double> lo_hi_eigenvalues(const Eigen::VectorXd& u) const {}\n\n    virtual double rho(const Eigen::VectorXd& u_prim) const {}\n    virtual double v(const Eigen::VectorXd& u_prim) const {}\n    virtual double p(const Eigen::VectorXd& u_prim) const {}\n    virtual double m(const Eigen::VectorXd& u_prim) const {}\n    virtual double E(const Eigen::VectorXd& u_prim) const {}\n    virtual double c(const Eigen::VectorXd& u_prim) const {}\n    virtual double H(const Eigen::VectorXd& u_prim) const {}\n\n    virtual void set_gamma(const double gamma_) {}\n    virtual double get_gamma() const {}\n};\n\nclass Burgers : public Model {\n  public:\n\n    Eigen::VectorXd flux(const Eigen::VectorXd &u) const override\n    {\n        Eigen::VectorXd f(n_vars);\n        f(0) = 0.5*u(0)*u(0);\n\n        return f;\n    }\n\n    Eigen::VectorXd eigenvalues(const Eigen::VectorXd &u) const override\n    {\n        Eigen::VectorXd eigvals(n_vars);\n        eigvals(0) = u(0);\n\n        return eigvals;\n    }\n\n    Eigen::MatrixXd eigenvectors(const Eigen::VectorXd &) const override\n    {\n        Eigen::MatrixXd eigvecs(n_vars, n_vars);\n        eigvecs (0,0) = 1;\n\n        return eigvecs;\n    }\n\n    double max_eigenvalue(const Eigen::VectorXd &u) const override {\n        return (eigenvalues(u).cwiseAbs()).maxCoeff();\n    }\n\n    Eigen::VectorXd cons_to_prim(const Eigen::VectorXd &u) const override {\n        return u;\n    }\n\n    Eigen::VectorXd prim_to_cons(const Eigen::VectorXd &u) const override {\n        return u;\n    }\n\n    int get_nvars() const override\n    {\n        return n_vars;\n    }\n\n    std::string get_name() const override\n    {\n        return \"burgers\";\n    }\n\n  private:\n    int n_vars = 1;\n};\n\n/// Euler equations\nclass Euler : public Model {\n    public:\n\n        Eigen::VectorXd flux(const Eigen::VectorXd &u) const override\n        {\n            Eigen::VectorXd f(n_vars);\n            \n            f << rho(u) * v(u),\n                 rho(u) * v(u) * v(u) + p(u),\n                 (E(u) + p(u)) * v(u);\n                \n            return f;\n        }\n        \n        Eigen::VectorXd eigenvalues(const Eigen::VectorXd &u) const override\n        {\n            Eigen::VectorXd eigvals(n_vars);\n        \n            eigvals << v(u) - c(u),\n                       v(u),\n                       v(u) + c(u);\n\n            return eigvals;\n        }\n\n        Eigen::MatrixXd eigenvectors(const Eigen::VectorXd &u) const override\n        {\n            Eigen::MatrixXd eigvecs(n_vars, n_vars);\n            \n            eigvecs << 1.0,                    1.0,                 1.0,\n                       v(u) - c(u),            v(u),                v(u) + c(u),\n                       H(u) - v(u) * c(u),     0.5 * v(u) * v(u),   H(u) + (v(u) * c(u));\n\n            return eigvecs;\n        }\n       \n        double max_eigenvalue(const Eigen::VectorXd &u) const override\n        {\n            // actually max(abs(eigenvalues)):\n            return (eigenvalues(u).cwiseAbs()).maxCoeff();\n        }\n\n        Eigen::VectorXd cons_to_prim(const Eigen::VectorXd &u_cons) const override\n        {\n            Eigen::VectorXd u_prim(n_vars);\n            \n            u_prim << rho(u_cons),\n                      v(u_cons),\n                      p(u_cons);\n                      \n            return u_prim;\n        }\n        \n        Eigen::VectorXd prim_to_cons(const Eigen::VectorXd &u_prim) const override\n        {\n            Eigen::VectorXd u_cons(n_vars);\n\n            u_cons << u_prim(0),\n                      u_prim(0) * u_prim(1),\n                      u_prim(2) / (gamma - 1) + 0.5 * u_prim(0) * u_prim(1) * u_prim(1);\n\n            return u_cons;\n        }\n\n        inline void set_gamma(const double gamma_) override\n        {\n            gamma= gamma_;\n        }\n\n        inline double get_gamma() const override\n        {\n            return gamma;\n        }\n\n        inline int get_nvars() const override\n        {\n            return n_vars;\n        }\n\n        std::string get_name() const override\n        {\n            return name;\n        }\n\n    private:\n        // 3D:\n        const int n_vars= 3;\n        // Monatomic gas:\n        double gamma= 5./3.;\n\n        inline static const std::string name= \"euler\";\n\n\n        std::pair<double, double> lo_hi_eigenvalues(const Eigen::VectorXd &u) const override\n        {\n            // check if we want cwiseAbs here:\n            // return (eigenvalues(u).cwiseAbs()).minCoeff();\n            Eigen::VectorXd eigenvals= eigenvalues(u);\n            return {eigenvals.minCoeff(), eigenvals.maxCoeff()};\n        }\n\n        /// Helper functions to deal w/ common names for Euler eqn expressions\n        /// Vector u must contain conserved variables: u = (rho, m, E)\n        /// as given in tasks initial conditions\n        /// ------------------------------------------------------------------\n\n        /// Conserved variables:\n        // rho : density\n        inline double rho(const Eigen::VectorXd& u) const override\n        {\n            return u(0);\n        }\n\n        // m : momentum\n        inline double m(const Eigen::VectorXd& u) const override\n        {\n            return u(1);\n        }\n        \n        // E : total energy for ideal polytropic gas (internal energy + kinetic energy)\n        inline double E(const Eigen::VectorXd& u) const override\n        {\n            return u(2);\n        }\n\n        /// Primitive variables:\n        // rho : density\n        // same as for conserved variables\n\n        // v : velocity\n        inline double v(const Eigen::VectorXd& u) const override\n        {\n            return m(u) / rho(u);\n        }\n\n        // p : pressure\n        inline double p(const Eigen::VectorXd& u) const override\n        {\n            return (E(u) - 0.5 * m(u) * m(u) / rho(u)) * (gamma - 1);\n        }\n\n        /// c : speed of sound\n        inline double c(const Eigen::VectorXd& u) const override\n        {\n            return std::sqrt(gamma * p(u) / rho(u));\n        }\n\n        /// H : total specific enthalpy\n        inline double H(const Eigen::VectorXd& u) const override\n        {\n            return (E(u) + p(u)) / rho(u);\n        }\n};\n\nstd::shared_ptr<Model> make_model (const nlohmann::json &config);\n\n#endif // HYPSYS1D_MODEL_HPP", "meta": {"hexsha": "e7f89a00e92cc3049431f432d2308da2dd0eb5c7", "size": 7175, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/model.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/model.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/model.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 28.137254902, "max_line_length": 92, "alphanum_fraction": 0.5351916376, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.6926419958239131, "lm_q1q2_score": 0.6393356889871413}}
{"text": "#include <numbers>\n#include <stdexcept>\n\n#include \"catch2/catch.hpp\"\n\n#include <Eigen/Dense>\n\n#include \"scapin/hooke.hpp\"\n\ntemplate <int DIM>\ninline constexpr int sym = (DIM * (DIM + 1)) / 2;\n\ntemplate <int DIM>\nusing Vector = Eigen::Matrix<double, DIM, 1>;\n\ntemplate <int DIM>\nusing Tensor2 = Eigen::Matrix<double, sym<DIM>, 1>;\n\ntemplate <int DIM>\nusing Tensor4 = Eigen::Matrix<double, sym<DIM>, sym<DIM>>;\n\ntemplate <int DIM>\nstd::pair<int, int> unravel_index(int ij);\n\ntemplate <>\nstd::pair<int, int> unravel_index<2>(int ij) {\n  switch (ij) {\n    case 0:\n      return std::make_pair(0, 0);\n    case 1:\n      return std::make_pair(1, 1);\n    case 2:\n      return std::make_pair(0, 1);\n    default:\n      throw std::invalid_argument(\"unexpected value\");\n  }\n}\n\ntemplate <>\nstd::pair<int, int> unravel_index<3>(int ij) {\n  switch (ij) {\n    case 0:\n      return std::make_pair(0, 0);\n    case 1:\n      return std::make_pair(1, 1);\n    case 2:\n      return std::make_pair(2, 2);\n    case 3:\n      return std::make_pair(1, 2);\n    case 4:\n      return std::make_pair(2, 0);\n    case 5:\n      return std::make_pair(0, 1);\n    default:\n      throw std::invalid_argument(\"unexpected argument\");\n  }\n}\n\ntemplate <int DIM>\ndouble bulk_modulus(double mu, double nu);\n\ntemplate <>\ndouble bulk_modulus<2>(double mu, double nu) {\n  return mu / (1. - 2. * nu);\n}\n\ntemplate <>\ndouble bulk_modulus<3>(double mu, double nu) {\n  return 2. * mu * (1. + nu) / 3. / (1. - 2. * nu);\n}\n\ntemplate <int DIM>\nstd::pair<Tensor4<DIM>, Tensor4<DIM>> isotropic_projectors() {\n  Tensor2<DIM> I2 = Tensor2<DIM>::Zero();\n  for (int i = 0; i < DIM; i++) I2(i) = 1.;\n  Tensor4<DIM> I = Tensor4<DIM>::Identity();\n  Tensor4<DIM> J = I2 * I2.transpose() / DIM;\n  Tensor4<DIM> K = I - J;\n  return std::make_pair(J, K);\n}\n\nstd::vector<Vector<2>> gen_directions(int num_theta) {\n  double const delta_theta = std::numbers::pi / (num_theta - 1.);\n  std::vector<Vector<2>> directions;\n  for (int i = 0; i < num_theta; i++) {\n    double theta = i * delta_theta;\n    directions.push_back(Vector<2>{cos(theta), sin(theta)});\n  }\n  return directions;\n}\n\nstd::vector<Vector<3>> gen_directions(int num_theta, int num_phi) {\n  double const delta_theta = std::numbers::pi / (num_theta - 1.);\n  double const delta_phi = 2 * std::numbers::pi / double(num_phi);\n  std::vector<Vector<3>> directions{};\n  for (int i = 0; i < num_theta; i++) {\n    double const theta = i * delta_theta;\n    double const cos_theta = cos(theta);\n    double const sin_theta = sin(theta);\n    for (int j = 0; j < num_phi; j++) {\n      double const phi = j * delta_phi;\n      directions.push_back(\n          Vector<3>{sin_theta * cos(phi), sin_theta * sin(phi), cos_theta});\n    }\n  }\n  return directions;\n}\n\ntemplate <int DIM>\nTensor4<DIM> green_operator_matrix(Vector<DIM> const &n, double nu) {\n  Tensor4<DIM> out;\n  for (int ij = 0; ij < sym<DIM>; ij++) {\n    auto const [i, j] = unravel_index<DIM>(ij);\n    double const w_ij = ij < DIM ? 1. : std::numbers::sqrt2;\n    for (int kl = 0; kl < sym<DIM>; kl++) {\n      auto const [k, l] = unravel_index<DIM>(kl);\n      double const w_kl = kl < DIM ? 1. : std::numbers::sqrt2;\n      double const delta_ik = i == k ? 1. : 0.;\n      double const delta_il = i == l ? 1. : 0.;\n      double const delta_jk = j == k ? 1. : 0.;\n      double const delta_jl = j == l ? 1. : 0.;\n      out(ij, kl) = w_ij * w_kl *\n                    (0.25 * (delta_ik * n(j) * n(l) + delta_il * n(j) * n(k) +\n                             delta_jk * n(i) * n(l) + delta_jl * n(i) * n(k)) -\n                     0.5 * n(i) * n(j) * n(k) * n(l) / (1. - nu));\n    }\n  }\n  return out;\n}\n\ntemplate <int DIM>\nvoid test_hooke_apply() {\n  std::vector<double> norms{1.2, 3.4, 5.6};\n  scapin::Hooke<double, DIM> gamma{1.0, 0.3};\n  std::vector<Vector<DIM>> directions;\n  if constexpr (DIM == 2) {\n    directions = gen_directions(20);\n  } else if constexpr (DIM == 3) {\n    directions = gen_directions(10, 20);\n  }\n  for (auto n : directions) {\n    auto exp = green_operator_matrix<DIM>(n, gamma.nu);\n    Tensor4<DIM> act;\n    for (auto const norm : norms) {\n      Vector<DIM> k = norm * n;\n      for (int i = 0; i < sym<DIM>; i++) {\n        Tensor2<DIM> tau = Tensor2<DIM>::Zero();\n        tau(i) = 1.;\n        Tensor2<DIM> eps;\n        gamma.apply(k.data(), tau.data(), eps.data());\n        act.col(i) = eps;\n      }\n      for (int i = 0; i < sym<DIM>; ++i) {\n        for (int j = 0; j < sym<DIM>; ++j) {\n          REQUIRE(act(i, j) == Approx(exp(i, j)).epsilon(1e-12).margin(1e-12));\n        }\n      }\n    }\n  }\n}\n\ntemplate <int DIM>\nvoid test_apply_stiffness() {\n  scapin::Hooke<double, DIM> gamma{1.2, 0.3};\n  auto const [J, K] = isotropic_projectors<DIM>();\n  auto kappa = bulk_modulus<DIM>(gamma.mu, gamma.nu);\n  Tensor4<DIM> C_exp = DIM * kappa * J + 2 * gamma.mu * K;\n  Tensor4<DIM> C_act;\n  Tensor2<DIM> eps = Tensor2<DIM>::Zero();\n  Tensor2<DIM> sig = Tensor2<DIM>::Zero();\n  for (int i = 0; i < sym<DIM>; i++) {\n    eps(i) = 1.0;\n    gamma.apply_stiffness(eps.data(), sig.data());\n    C_act.col(i) = sig;\n    eps(i) = 0.0;\n  }\n\n  for (int i = 0; i < sym<DIM>; i++) {\n    for (int j = 0; j < sym<DIM>; j++) {\n      REQUIRE(C_act(i, j) == Approx(C_exp(i, j)).epsilon(1e-15).margin(1e-15));\n    }\n  }\n}\n\ntemplate <int DIM>\nvoid test_apply_compliance() {\n  scapin::Hooke<double, DIM> gamma{1.2, 0.3};\n  auto const [J, K] = isotropic_projectors<DIM>();\n  auto kappa = bulk_modulus<DIM>(gamma.mu, gamma.nu);\n  Tensor4<DIM> S_exp = J / (DIM * kappa) + K / (2 * gamma.mu);\n  Tensor4<DIM> S_act;\n  Tensor2<DIM> eps = Tensor2<DIM>::Zero();\n  Tensor2<DIM> sig = Tensor2<DIM>::Zero();\n  for (int i = 0; i < sym<DIM>; i++) {\n    sig(i) = 1.0;\n    gamma.apply_compliance(sig.data(), eps.data());\n    S_act.col(i) = eps;\n    sig(i) = 0.0;\n  }\n\n  for (int i = 0; i < sym<DIM>; i++) {\n    for (int j = 0; j < sym<DIM>; j++) {\n      REQUIRE(S_act(i, j) == Approx(S_exp(i, j)).epsilon(1e-15).margin(1e-15));\n    }\n  }\n}\n\nTEST_CASE(\"Continuous Green operator\") {\n  SECTION(\"Hooke model\") {\n    SECTION(\"Apply\") {\n      SECTION(\"2D\") { test_hooke_apply<2>(); }\n      SECTION(\"3D\") { test_hooke_apply<3>(); }\n    }\n    SECTION(\"apply_stiffness\") {\n      SECTION(\"2D\") { test_apply_stiffness<2>(); }\n      SECTION(\"3D\") { test_apply_stiffness<3>(); }\n    }\n    SECTION(\"apply_compliance\") {\n      SECTION(\"2D\") { test_apply_compliance<2>(); }\n      SECTION(\"3D\") { test_apply_compliance<3>(); }\n    }\n  }\n}\n", "meta": {"hexsha": "d7a955172cc10592659b6d75561818c7ed700dfd", "size": 6429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_scapin.cpp", "max_stars_repo_name": "sbrisard/gollum", "max_stars_repo_head_hexsha": "25d5b9aea63a8f2812c4b41850450fcbead64da7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_scapin.cpp", "max_issues_repo_name": "sbrisard/gollum", "max_issues_repo_head_hexsha": "25d5b9aea63a8f2812c4b41850450fcbead64da7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-09-24T07:32:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-01T08:06:00.000Z", "max_forks_repo_path": "tests/test_scapin.cpp", "max_forks_repo_name": "sbrisard/gollum", "max_forks_repo_head_hexsha": "25d5b9aea63a8f2812c4b41850450fcbead64da7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-02T18:05:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-02T18:05:15.000Z", "avg_line_length": 28.7008928571, "max_line_length": 79, "alphanum_fraction": 0.5744283714, "num_tokens": 2140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6392239768670931}}
{"text": "#include <ql/quantlib.hpp>\n\n#include <iostream>\n\n#include <iomanip>\n\n \n\n#include <boost/timer.hpp>\n\n \n\nusing namespace QuantLib;\n\nusing namespace std;\n\n \n\n#if defined(QL_ENABLE_SESSIONS)\n\n{\n\n        namespace QuantLib\n\n        {\n\n               Integer sessionId() { return 0; }\n\n        }\n\n#endif\n\n \n\nint main(int, char*[])\n\n{\n\n        try\n\n        {\n\n               boost::timer timer;\n\n               std::cout << std::endl;\n\n \n\n               Calendar calendar = TARGET();\n\n               Date settlementDate(6, Aug, 2021);\n\n               settlementDate = calendar.adjust(settlementDate);\n\n               Integer fixingDays = 1;\n\n               Natural settlementDays = 1;\n\n               Date todaysDate = calendar..advance(settlementDate, -fixingDays, Days);\n\n               Settings::instance().evaluationDate() = todaysDate;\n\n \n\n               // Treasury Bond Setting //\n\n               Real faceAmount = 100;\n\n               Real redemption = 100;\n\n               Date issueDate(17, May, 2021);\n\n               Date maturity(5, May, 2031);\n\n               Real couponRate = 0.01625; // 1 5/8\n\n               Real yield = 0.0165;\n\n \n\n               RelinkableHandle<YieldTermStructure> discountingTermStructure;\n\n               boost::shared_ptr<YieldTermStructure> flatTermStructure(new FlatForward(settlementDate, yield, ActualActual(ActualActual::Bond), Compounded, Semiannual));\n\n               discountingTermStructure.linkTo(flatTermStructure);\n\n \n\n               boost::shared_ptr<PricingEngine> bondEngine(new DiscountingBondEngine(discountingTermStructure));\n\n \n\n               Schedule fixedBondSchedule(issueDate, maturity, Period(Semiannual), UnitedStates(UnitedStates::GovernmentBond), Unadjusted, Unadjusted, DateGeneration::Rule::Backward, false);\n\n               FixedRateBond fixedRateBond(settlementDays, faceAmount, fixedBondSchedule, std::vector<Rate>(1, couponRate), ActualActual(ActualActual::Bond), Unadjusted, redemption, issueDate);\n\n \n\n               fixedRateBond.setPricingEngine(bondEngine);\n\n \n\n               std::cout << \"****** Inputs ******\" << std::endl;\n\n               //std::setprecision(20);\n\n               std::cout << \" Principal = \" << faceAmount << std::endl;\n\n               std::cout << \"Issue Date = \" << issueDate << std::endl;\n\n               std::cout << \" Maturity = \" << maturity << std::endl;\n\n               std::cout << \" Coupon  = \" << io::percent(couponRate) << std::endl;\n\n               std::cout << \" Yield To Maturity = \" << io::percent(yield) << std::endl;\n\n               std::cout << \"****** Result ******\" << std::endl;\n\n               std::cout << \" Fair Value = \" << fixedRateBond.NPV() << std::endl;\n\n               std::cout << \" Clean Price = \" << fixedRateBond.cleanPrice() << std::endl;\n\n               std::cout << \" Dirty Price = \" << fixedRateBond.dirtyPrice() << std::endl;\n\n               std::cout << \" Accured Coupon = \" << fixedRateBond.accruedAmount() << std::endl;\n\n               system(\"pause\");\n\n               return 0;\n\n        }\n\n        catch (std::exception& e)\n\n        {\n\n               std::cerr << e.what() << std::endl;\n\n               return 1;\n\n        }\n\n        catch (...)\n\n        {\n\n               std::cerr << \"Unknown Error\" << std::endl;\n\n               return 1;\n\n \n\n        }\n\n}\n\n \n", "meta": {"hexsha": "5469011a689bd15fe3a780a753b2808af1cb09ab", "size": 3299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ShineXecution/Treasurtybond/main.cpp", "max_stars_repo_name": "FinancialEngineerLab/fineQuantlib", "max_stars_repo_head_hexsha": "a07eb659a440964ded9e9f636de0fd379672f4c3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ShineXecution/Treasurtybond/main.cpp", "max_issues_repo_name": "FinancialEngineerLab/fineQuantlib", "max_issues_repo_head_hexsha": "a07eb659a440964ded9e9f636de0fd379672f4c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShineXecution/Treasurtybond/main.cpp", "max_forks_repo_name": "FinancialEngineerLab/fineQuantlib", "max_forks_repo_head_hexsha": "a07eb659a440964ded9e9f636de0fd379672f4c3", "max_forks_repo_licenses": ["BSD-3-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.8797468354, "max_line_length": 193, "alphanum_fraction": 0.5337981206, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6392157095525844}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <iostream>\n#include <boost/graph/edge_list.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n\nint\nmain()\n{\n  using namespace boost;\n  // ID numbers for the routers (vertices).\n  enum\n  { A, B, C, D, E, F, G, H, n_vertices };\n  const int n_edges = 11;\n  typedef std::pair < int, int >Edge;\n\n  // The list of connections between routers stored in an array.\n  Edge edges[] = {\n  Edge(A, B), Edge(A, C),\n        Edge(B, D), Edge(B, E), Edge(C, E), Edge(C, F), Edge(D, H),\n        Edge(D, E), Edge(E, H), Edge(F, G), Edge(G, H)\n  };\n\n  // Specify the graph type and declare a graph object\n  typedef edge_list < Edge*, Edge, std::ptrdiff_t, std::random_access_iterator_tag> Graph;\n  Graph g(edges, edges + n_edges);\n\n  // The transmission delay values for each edge.\n  float delay[] =\n    {5.0, 1.0, 1.3, 3.0, 10.0, 2.0, 6.3, 0.4, 1.3, 1.2, 0.5};\n\n  // Declare some storage for some \"external\" vertex properties.\n  char name[] = \"ABCDEFGH\";\n  int parent[n_vertices];\n  for (int i = 0; i < n_vertices; ++i)\n    parent[i] = i;\n  float distance[n_vertices];\n  std::fill(distance, distance + n_vertices, (std::numeric_limits < float >::max)());\n  // Specify A as the source vertex\n  distance[A] = 0;\n\n  bool r = bellman_ford_shortest_paths(g, int (n_vertices),\n                                       weight_map(make_iterator_property_map\n                                                  (&delay[0],\n                                                   get(edge_index, g),\n                                                   delay[0])).\n                                       distance_map(&distance[0]).\n                                       predecessor_map(&parent[0]));\n\n  if (r)\n    for (int i = 0; i < n_vertices; ++i)\n      std::cout << name[i] << \": \" << distance[i]\n        << \" \" << name[parent[i]] << std::endl;\n  else\n    std::cout << \"negative cycle\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "988e951bb54977e6bac38300852258608030b2a2", "size": 2282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/bellman-ford-internet.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/bellman-ford-internet.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/bellman-ford-internet.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 35.65625, "max_line_length": 90, "alphanum_fraction": 0.5236634531, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6392156946511686}}
{"text": "#include <iostream>\n#include <chrono>\n#include <random>\n#include <map>\n\n#include <opencv2/opencv.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"matplotlibcpp.h\"\n\n\nusing namespace std;\nusing namespace Eigen;\nnamespace plt = matplotlibcpp;\n\ndouble g(double x, double a, double b, double c)\n{\n  // return a*x*x+b*x+c;\n  return std::exp(a * x * x + b * x + c);\n}\n\nint main(int argc, char **argv) {\n  std::cout << \"Steepest-Descent \\n\";\n\n  double aa = 1.0, bb = 2.0, cc = 1.0;\n  double a = 2.0, b = -1.0, c = -5.0;\n\n  double obs_sigma = 1.0;\n  std::default_random_engine generator;\n  std::normal_distribution<double> obs_noise_distrib(0.0, obs_sigma);\n\n\n  int N = 100;\n  std::vector<double> x_data(N), y_data(N);\n  for (int i = 0; i < N; ++i)\n  {\n    x_data[i] = static_cast<double>(i) / 100.0;\n    y_data[i] = g(x_data[i], aa, bb, cc) + obs_noise_distrib(generator);\n\n  }\n\n  // Optimize\n  int max_iter = 100000;\n  for (int it = 0; it < max_iter; ++it)\n  {\n    std::cout << \"iter \" << it << \" : \";\n    std::cout << \"abc = \" << a << \" \" << b << \" \" << c << \"\\n\";\n    Eigen::Vector3d J(0.0, 0.0, 0.0);\n    double total_err = 0.0;\n    for (int i = 0; i < N; ++i)\n    {\n      double err = y_data[i] - g(x_data[i], a, b, c);\n      total_err += err*err;\n\n      // Compute derivative of F(x) = 0.5 * sum(f(x)^2) = 0.5 * sum((y-g(x))^2)\n      J[0] += -x_data[i] * x_data[i] * g(x_data[i], a, b, c) * err;\n      J[1] += -x_data[i] * g(x_data[i], a, b, c) * err;\n      J[2] += -g(x_data[i], a, b, c) * err;\n    }\n\n    std::cout << \"J = \" << J.transpose() << \"\\n\";\n    std::cout << \"total error: \" << total_err << \"\\n\";\n\n    if (J.norm() < 0.01)\n      break;\n\n    // Very small step\n    double S = 100000;\n    a -= J[0] / S;\n    b -= J[1] / S;\n    c -= J[2] / S;\n  }\n  std::cout << \"final = \" << a << \" \" << b << \" \" << c << \"\\n\";\n\n  vector<double> final_y_data(N);\n  for (int i = 0; i < N; ++i)\n  {\n    final_y_data[i] = g(x_data[i], a, b, c);\n  }\n\n  plt::scatter(x_data, y_data);\n  std::map<std::string, std::string> 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": "afcf2ab6cd5f7e8aced6c5d59fa59eaebf42779a", "size": 2143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/steepest_descent.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/steepest_descent.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/steepest_descent.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": 23.8111111111, "max_line_length": 79, "alphanum_fraction": 0.5272981801, "num_tokens": 783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.639215683488467}}
{"text": "/**\n * @file advectionfv2d_main.cc\n * @brief NPDE homework AdvectionFV2D code\n * @author Philipp Egg\n * @date 21.06.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/io/io.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/refinement/refinement.h>\n\n#include <Eigen/Core>\n#include <array>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"advectionfv2d.h\"\n\n// Use this function to plot your solution\nvoid write_vtk(const lf::assemble::DofHandler &dofh,\n               const Eigen::VectorXd &solution, std::string name) {\n  std::shared_ptr<const lf::mesh::Mesh> mesh_p = dofh.Mesh();\n  lf::io::VtkWriter vtk_writer(mesh_p, name + \".vtk\");\n  auto cell_data_ref =\n      lf::mesh::utils::make_CodimMeshDataSet<double>(mesh_p, 0);\n  for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n    int row = dofh.GlobalDofIndices(*cell)[0];\n    cell_data_ref->operator()(*cell) = solution[row];\n  }\n  vtk_writer.WriteCellData(name, *cell_data_ref);\n}\n\nint main() {\n  /* SAM_LISTING_BEGIN_1 */\n  // Define velocity field beta\n  // Note that the problem description requires ||B|| <= 1\n  auto beta = [](Eigen::Vector2d x) -> Eigen::Vector2d {\n    return Eigen::Vector2d(-x[1], x[0]) / std::sqrt(2.0);\n  };\n\n  // Functor for initial bump\n  auto u0 = [](Eigen::Vector2d x) -> double {\n    Eigen::Vector2d x0(0.8, 0.2);\n    double d = 0.2;\n    double dist = (x - x0).norm();\n    if (dist < d) {\n      double cos = std::cos(M_PI / (2.0 * d) * dist);\n      return cos * cos;\n    } else {\n      return 0.0;\n    }\n  };\n\n  // Task 8-8.o\n  // Generate a mesh hierarchy\n  double T = 1.0;\n\n  //////////////////////////////////////////////////////////////////////////////\n  // TODO inconsistancy: g vs. G\n  //////////////////////////////////////////////////////////////////////////////\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(0, 1.0 / 3.0);\n\n  auto mesh_seq_p{\n      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(mesh_p, 6)};\n\n  std::vector<int> vector_num_cells;\n  std::vector<double> vector_l2error;\n\n  // Iterate over mesh levels starting from thrid refinement\n  int num_meshes = mesh_seq_p->NumLevels();\n  for (int level = 3; level < num_meshes; ++level) {\n    std::cout << \"Computing L2Error for level: \" << level << std::endl;\n\n#if SOLUTION\n    // Get the current mesh\n    auto cur_mesh = mesh_seq_p->getMesh(level);\n\n    // Create a DOF Hander for the current mesh\n    const lf::assemble::UniformFEDofHandler cur_dofh(\n        cur_mesh, {{lf::base::RefEl::kPoint(), 0},\n                   {lf::base::RefEl::kSegment(), 0},\n                   {lf::base::RefEl::kTria(), 1},\n                   {lf::base::RefEl::kQuad(), 1}});\n    int N = cur_dofh.NumDofs();\n\n    // Compute cell normals\n    std::shared_ptr<lf::mesh::utils::CodimMeshDataSet<\n        Eigen::Matrix<double, 2, Eigen::Dynamic>>>\n        normal_vectors = AdvectionFV2D::computeCellNormals(cur_dofh.Mesh());\n\n    // Compute adjecent cells\n    std::shared_ptr<lf::mesh::utils::CodimMeshDataSet<\n        std::array<const lf::mesh::Entity *, 4>>>\n        adjacentCells = AdvectionFV2D::getAdjacentCellPointers(cur_dofh.Mesh());\n\n    // Get approximate solution from simulation\n    Eigen::VectorXd mu_approx = AdvectionFV2D::simulateAdvection(\n        cur_dofh, beta, u0, adjacentCells, normal_vectors, T);\n    write_vtk(cur_dofh, mu_approx, \"approx\" + std::to_string(level));\n\n    // Get exact solution at barycenters of cells\n    Eigen::VectorXd mu_exact = AdvectionFV2D::refSolution(cur_dofh, u0, T);\n    write_vtk(cur_dofh, mu_exact, \"exact\" + std::to_string(level));\n\n    // Compute L2 error in barycenter\n    double l2_error = 0;\n    for (const lf::mesh::Entity *cell : cur_mesh->Entities(0)) {\n      const lf::geometry::Geometry *geo_p = cell->Geometry();\n      double area = lf::geometry::Volume(*geo_p);\n      int idx = cur_dofh.GlobalDofIndices(*cell)[0];\n      l2_error += std::pow((mu_approx[idx] - mu_exact[idx]), 2) * area;\n    }\n    l2_error = std::sqrt(l2_error);\n#else\n    //====================\n    // Your code goes here\n    // Compute the number N of DOFs and the L2-error,\n    // and replace the lines below:\n    int N = 1;\n    double l2_error = 1.0;\n    // If you want, you can use the function write_vtk(...),\n    // defined in this file, to plot your solution.\n    //====================\n#endif\n\n    vector_num_cells.push_back(N);\n    vector_l2error.push_back(l2_error);\n  }\n\n  // Write Output file of Task 8-8.o\n  std::ofstream csv_file;\n  csv_file.open(\"advectionfv2d.csv\");\n  for (int i = 0; i < vector_num_cells.size(); ++i) {\n    std::cout << \"Cells: \" << vector_num_cells.at(i)\n              << \" | L2Error: \" << vector_l2error.at(i) << std::endl;\n    csv_file << vector_num_cells.at(i) << \",\" << vector_l2error.at(i) << \"\\n\";\n  }\n  csv_file.close();\n\n  std::system(\"python3 \" CURRENT_SOURCE_DIR\n              \"/advectionfv2d.py \" CURRENT_BINARY_DIR\n              \"/advectionfv2d.csv \" CURRENT_BINARY_DIR \"/solution.eps\");\n  /* SAM_LISTING_END_1 */\n\n  /* SAM_LISTING_BEGIN_2 */\n  // Task 8-8.q\n  // Compute threshold for fourth refinement level\n  int level = 4;\n  auto mesh = mesh_seq_p->getMesh(level);\n\n#if SOLUTION\n  // Create a DOF Hander for the current mesh\n  const lf::assemble::UniformFEDofHandler dofh(\n      mesh, {{lf::base::RefEl::kPoint(), 0},\n             {lf::base::RefEl::kSegment(), 0},\n             {lf::base::RefEl::kTria(), 1},\n             {lf::base::RefEl::kQuad(), 1}});\n\n  int threshold = AdvectionFV2D::findCFLthreshold(dofh, beta, T);\n  int cfl_thres = int((T / AdvectionFV2D::computeHmin(mesh) + 1));\n#else\n  //====================\n  // Your code goes here\n  // Replace the two variables below:\n  int threshold = 0.0;  // Threshold computed by findCFLthreshold(...)\n  int cfl_thres = 0.0;  // Threshold obtained from CLF using computeHmin(mesh)\n                        //====================\n#endif\n\n  std::cout << \"Threshold for level \" << level << \" is \" << threshold\n            << \" | Threshold from CFL is \" << cfl_thres << std::endl;\n  /* SAM_LISTING_END_2 */\n\n  return 0;\n}\n", "meta": {"hexsha": "b1b74521c8a296d827e12a62beeaddd2eafe8687", "size": 6276, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/AdvectionFV2D/mastersolution/advectionfv2d_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "developers/AdvectionFV2D/mastersolution/advectionfv2d_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "developers/AdvectionFV2D/mastersolution/advectionfv2d_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": 33.5614973262, "max_line_length": 80, "alphanum_fraction": 0.6131293818, "num_tokens": 1811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6392156750205386}}
{"text": "#include \"Classes.h\"\n#include <Eigen/Dense>\nusing namespace Eigen;\n\nint PlaneProjection::rotatePlane() {\n    ///\n    /// Function to rotate the PlaneProjection instance so as to get the normal parallel to z-axis\n    ///\n    Vector3d zaxis(0,0,1);\n    Vector3d norml(normal[0],normal[1],normal[2]);\n    // cout << \"Norml: \" << endl << norml << endl;\n    double costheta = zaxis.dot(norml);\n    double sintheta = zaxis.cross(norml).norm();\n    if(costheta < 0) {\n        costheta = 0-costheta;\n    }\n    Vector3d axis = zaxis.cross(norml);\n    Matrix3d id = Matrix3d::Identity();\n    // cout << \"Identity Matrix: \" << endl << id << endl;\n    Matrix3d ux;\n    ux << 0, -axis.z(), axis.y(),\n                axis.z(), 0, -axis.x(),\n                -axis.y(), axis.x(), 0;\n    // cout << \"UX Matrix: \" << endl << ux << endl;\n    Matrix3d tensorprod = axis*axis.transpose();\n    // cout << \"Tensor Product Matrix: \" << endl << tensorprod << endl;\n    Matrix3d rotmax = costheta*id + sintheta*ux + (1-costheta)*tensorprod;\n    for(auto i = 0; i < visibleEdges.size(); i++) {\n        Vector3d point1(visibleEdges[i].p1.x,visibleEdges[i].p1.y,visibleEdges[i].p1.z);\n        Vector3d point2(visibleEdges[i].p2.x,visibleEdges[i].p2.y,visibleEdges[i].p2.z);\n        point1 = rotmax*point1;\n        point2 = rotmax*point2;\n        visibleEdges[i].p1.x = point1.x();\n        visibleEdges[i].p1.y = point1.y();\n        visibleEdges[i].p1.z = point1.z();\n        visibleEdges[i].p2.x = point2.x();\n        visibleEdges[i].p2.y = point2.y();\n        visibleEdges[i].p2.z = point2.z();\n    }\n    for(auto i = 0; i < hiddenEdges.size(); i++) {\n        Vector3d point1(hiddenEdges[i].p1.x,hiddenEdges[i].p1.y,hiddenEdges[i].p1.z);\n        Vector3d point2(hiddenEdges[i].p2.x,hiddenEdges[i].p2.y,hiddenEdges[i].p2.z);\n        point1 = rotmax*point1;\n        point2 = rotmax*point2;\n        hiddenEdges[i].p1.x = point1.x();\n        hiddenEdges[i].p1.y = point1.y();\n        hiddenEdges[i].p1.z = point1.z();\n        hiddenEdges[i].p2.x = point2.x();\n        hiddenEdges[i].p2.y = point2.y();\n        hiddenEdges[i].p2.z = point2.z();\n    }\n}", "meta": {"hexsha": "fc13bae7d438259e1ff1c071040693848807a3f1", "size": 2119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PlaneProjection.cpp", "max_stars_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_stars_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-03-04T18:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T23:07:12.000Z", "max_issues_repo_path": "src/PlaneProjection.cpp", "max_issues_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_issues_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PlaneProjection.cpp", "max_forks_repo_name": "DivyanshuSaxena/COP290-Assignment", "max_forks_repo_head_hexsha": "dbf06f0aa29de9c3d4250c232fb2dd14eabe1b52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-09T10:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-28T08:53:33.000Z", "avg_line_length": 40.75, "max_line_length": 98, "alphanum_fraction": 0.5799905616, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6391985029256234}}
{"text": "// (C) Copyright Andrew Sutton 2007\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0 (See accompanying file\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\n\n//[inclusive_mean_geodesic_example\n#include <iostream>\n#include <iomanip>\n\n#include <boost/graph/directed_graph.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n#include <boost/graph/geodesic_distance.hpp>\n#include \"helper.hpp\"\n\nusing namespace std;\nusing namespace boost;\n\n// This template structure defines the function that we will apply\n// to compute both the per-vertex mean geodesic distances and the\n// graph's mean geodesic distance.\ntemplate < typename Graph, typename DistanceType, typename ResultType,\n    typename Divides = divides< ResultType > >\nstruct inclusive_average\n{\n    typedef DistanceType distance_type;\n    typedef ResultType result_type;\n\n    result_type operator()(distance_type d, const Graph& g)\n    {\n        if (d == numeric_values< distance_type >::infinity())\n        {\n            return numeric_values< result_type >::infinity();\n        }\n        else\n        {\n            return div(result_type(d), result_type(num_vertices(g)));\n        }\n    }\n    Divides div;\n};\n\n// The Page type stores the name of each vertex in the graph and\n// represents web pages that can be navigated to.\nstruct WebPage\n{\n    string name;\n};\n\n// The Link type stores an associated probability of traveling\n// from one page to another.\nstruct Link\n{\n    float probability;\n};\n\n// Declare the graph type and its vertex and edge types.\ntypedef directed_graph< WebPage, Link > Graph;\ntypedef graph_traits< Graph >::vertex_descriptor Vertex;\ntypedef graph_traits< Graph >::edge_descriptor Edge;\n\n// The name map provides an abstract accessor for the names of\n// each vertex. This is used during graph creation.\ntypedef property_map< Graph, string WebPage::* >::type NameMap;\n\n// Declare a matrix type and its corresponding property map that\n// will contain the distances between each pair of vertices.\ntypedef exterior_vertex_property< Graph, float > DistanceProperty;\ntypedef DistanceProperty::matrix_type DistanceMatrix;\ntypedef DistanceProperty::matrix_map_type DistanceMatrixMap;\n\n// Declare the weight map as an accessor into the bundled\n// edge property.\ntypedef property_map< Graph, float Link::* >::type WeightMap;\n\n// Declare a container and its corresponding property map that\n// will contain the resulting mean geodesic distances of each\n// vertex in the graph.\ntypedef exterior_vertex_property< Graph, float > GeodesicProperty;\ntypedef GeodesicProperty::container_type GeodesicContainer;\ntypedef GeodesicProperty::map_type GeodesicMap;\n\nstatic float exclusive_geodesics(const Graph&, DistanceMatrixMap, GeodesicMap);\nstatic float inclusive_geodesics(const Graph&, DistanceMatrixMap, GeodesicMap);\n\nint main(int argc, char* argv[])\n{\n    // Create the graph, a name map that providse abstract access\n    // to the web page names, and the weight map as an accessor to\n    // the edge weights (or probabilities).\n    Graph g;\n    NameMap nm(get(&WebPage::name, g));\n    WeightMap wm(get(&Link::probability, g));\n\n    // Read the weighted graph from standard input.\n    read_weighted_graph(g, nm, wm, cin);\n\n    // Compute the distances between all pairs of vertices using\n    // the Floyd-Warshall algorithm. The weight map was created\n    // above so it could be populated when the graph was read in.\n    DistanceMatrix distances(num_vertices(g));\n    DistanceMatrixMap dm(distances, g);\n    floyd_warshall_all_pairs_shortest_paths(g, dm, weight_map(wm));\n\n    // Create the containers and the respective property maps that\n    // will contain the mean geodesics averaged both including\n    // self-loop distances and excluding them.\n    GeodesicContainer exclude(num_vertices(g));\n    GeodesicContainer include(num_vertices(g));\n    GeodesicMap exmap(exclude, g);\n    GeodesicMap inmap(include, g);\n\n    float ex = exclusive_geodesics(g, dm, exmap);\n    float in = inclusive_geodesics(g, dm, inmap);\n\n    // Print the mean geodesic distance of each vertex and finally,\n    // the graph itself.\n    cout << setw(12) << setiosflags(ios::left) << \"vertex\";\n    cout << setw(12) << setiosflags(ios::left) << \"excluding\";\n    cout << setw(12) << setiosflags(ios::left) << \"including\" << endl;\n    graph_traits< Graph >::vertex_iterator i, end;\n    for (boost::tie(i, end) = vertices(g); i != end; ++i)\n    {\n        cout << setw(12) << setiosflags(ios::left) << g[*i].name << setw(12)\n             << get(exmap, *i) << setw(12) << get(inmap, *i) << endl;\n    }\n    cout << \"small world (excluding self-loops): \" << ex << endl;\n    cout << \"small world (including self-loops): \" << in << endl;\n\n    return 0;\n}\n\nfloat exclusive_geodesics(const Graph& g, DistanceMatrixMap dm, GeodesicMap gm)\n{\n    // Compute the mean geodesic distances, which excludes distances\n    // of self-loops by default. Return the measure for the entire graph.\n    return all_mean_geodesics(g, dm, gm);\n}\n\nfloat inclusive_geodesics(const Graph& g, DistanceMatrixMap dm, GeodesicMap gm)\n{\n    // Create a new measure object for computing the mean geodesic\n    // distance of all vertices. This measure will actually be used\n    // for both averages.\n    inclusive_average< Graph, float, float > m;\n\n    // Compute the mean geodesic distance using the inclusive average\n    // to account for self-loop distances. Return the measure for the\n    // entire graph.\n    return all_mean_geodesics(g, dm, gm, m);\n}\n//]\n", "meta": {"hexsha": "ef88a720ae4bca4405bc7f9f107b12fd90fd5a64", "size": 5571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/inclusive_mean_geodesic.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/inclusive_mean_geodesic.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/graph/example/inclusive_mean_geodesic.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 36.1753246753, "max_line_length": 79, "alphanum_fraction": 0.718362951, "num_tokens": 1306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6391984942109253}}
{"text": "#ifndef BAOBZI_TEMPLATE_HPP\n#define BAOBZI_TEMPLATE_HPP\n\n#include <fstream>\n#include <iostream>\n#include <mutex>\n#include <queue>\n#include <vector>\n\n#include <msgpack.hpp>\n#define EIGEN_MATRIX_PLUGIN \"baobzi/eigen_matrix_plugin.h\"\n\n#define EIGEN_MAX_ALIGN_BYTES 64\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n#include <baobzi/header.h>\n\n/// Namespace for baobzi\nnamespace baobzi {\n\ntemplate <int DIM, int ORDER, int ISET>\nclass Function;\n\n/// @brief Structure to represent geometric portion of Baobzi nodes\n/// @tparam D number of dimensions of box\n/// @tparam ISET Instruction set index (dummy variable to force alignment for different instruction sets)\ntemplate <int D, int ISET>\nstruct Box {\n    using VEC = Eigen::Vector<double, D>;\n    VEC center;      ///< Center of box\n    VEC half_length; ///< Half the dimension of the box\n    VEC inv_half_length; ///< 1.0 / half the dimension of the box\n\n    Box<D, ISET>() = default; ///< default constructor for msgpack happiness\n    /// @brief Constructor, just copies x, hl over\n    Box<D, ISET>(const VEC &x, const VEC &hl)\n        : center(x), half_length(hl), inv_half_length(VEC::Ones().array() / hl.array()) {}\n\n    /// @brief Check if point lies inside box\n    /// @param[in] x point to check\n    /// @returns true if point in box, false otherwise\n    bool contains(const VEC &x) const {\n        VEC dx = (x - center).array().abs();\n        return !((dx > half_length).any());\n    }\n\n    /// @brief MSGPACK serialization magic\n    MSGPACK_DEFINE(center, half_length, inv_half_length);\n};\n\n/// @brief Return an estimate of the error for a given set of coefficientsj\n/// @param[in] coeffs one or two dimensional Vector/Matrix of coefficients\n/// @returns estimation of error given those coefficients\ninline double standard_error(const Eigen::Ref<Eigen::MatrixXd> &coeffs) {\n    double maxcoeff = 0.0;\n    double scaling_factor = 1.0;\n    if (coeffs.cols() == 1) {\n        int n = coeffs.size();\n        for (auto i = n - 2; i < n; ++i)\n            maxcoeff = std::max(std::abs(coeffs(i, 0)), maxcoeff);\n        scaling_factor = std::max(scaling_factor, std::abs(coeffs(0, 0)));\n    } else {\n        int n = coeffs.rows();\n        for (auto i = 0; i < n; ++i)\n            maxcoeff = std::max(std::abs(coeffs(i, n - i - 1)), maxcoeff);\n\n        scaling_factor = std::max(scaling_factor, std::abs(coeffs(n - 1, 0)));\n        scaling_factor = std::max(scaling_factor, std::abs(coeffs(0, n - 1)));\n    }\n\n    return maxcoeff / scaling_factor;\n}\n\n/// @brief Evaluate chebyshev polynomial given a box and a point inside that box\n/// @tparam DIM dim of chebyshev polynomial to evaluate\n/// @tparam ORDER order of chebyshev polynomial to evaluate\n/// @tparam ISET Instruction set index (dummy variable to force alignment for different instruction sets)\n/// @param[in] x position of point to evaluate\n/// @param[in] box box that x lives in\n/// @param[in] coeffs_raw flat column-major vector of coefficients\n/// @returns value of interpolating function at x\ntemplate <int DIM, int ORDER, int ISET>\ninline double cheb_eval(const Eigen::Vector<double, DIM> &x, const Box<DIM, ISET> &box,\n                        const std::vector<double, Eigen::aligned_allocator<double>> &coeffs_raw);\n\ntemplate <int ORDER, int ISET>\ninline double cheb_eval(const Eigen::Vector<double, 1> &x, const Box<1, ISET> &box,\n                        const std::vector<double, Eigen::aligned_allocator<double>> &coeffs_raw) {\n    double xd = (x[0] - box.center[0]) * box.inv_half_length[0];\n\n    Eigen::Vector<double, ORDER> Tn;\n    Tn[0] = 1.0;\n    Tn[1] = xd;\n    xd *= 2.0;\n    for (int i = 2; i < ORDER; ++i)\n        Tn[i] = xd * Tn[i - 1] - Tn[i - 2];\n\n    Eigen::Map<const Eigen::Vector<double, ORDER>> coeffs(coeffs_raw.data());\n\n    return coeffs.dot(Tn);\n}\n\ntemplate <int ORDER, int ISET>\ninline double cheb_eval(const Eigen::Vector2d &x, const Box<2, ISET> &box,\n                        const std::vector<double, Eigen::aligned_allocator<double>> &coeffs_raw) {\n    Eigen::Vector2d xinterp = (x - box.center).array() * box.inv_half_length.array();\n    Eigen::Matrix<double, 2, ORDER> Tns;\n    Tns.col(0).setOnes();\n    Tns.col(1) = xinterp;\n    xinterp *= 2.0;\n    for (int i = 2; i < ORDER; ++i)\n        Tns.col(i) = xinterp.array() * Tns.col(i - 1).array() - Tns.col(i - 2).array();\n\n    Eigen::Map<const Eigen::Matrix<double, ORDER, ORDER>> coeffs(coeffs_raw.data());\n\n    return Tns.row(0).transpose().dot(coeffs * Tns.row(1).transpose());\n}\n\ntemplate <int ORDER, int ISET>\ninline double cheb_eval(const Eigen::Vector3d &x, const Box<3, ISET> &box,\n                        const std::vector<double, Eigen::aligned_allocator<double>> &coeffs_raw) {\n\n    Eigen::Vector3d xinterp = (x - box.center).array() * box.inv_half_length.array();\n\n    Eigen::Vector<double, ORDER> Tn[3];\n    Tn[0][0] = Tn[1][0] = Tn[2][0] = 1.0;\n    for (int i = 0; i < 3; ++i) {\n        Tn[i][1] = xinterp[i];\n        xinterp[i] *= 2.0;\n        for (int j = 2; j < ORDER; ++j)\n            Tn[i][j] = xinterp[i] * Tn[i][j - 1] - Tn[i][j - 2];\n    }\n\n    double res = 0.0;\n    using map_t = Eigen::Map<const Eigen::Matrix<double, ORDER, ORDER>>;\n    for (int i = 0; i < ORDER; ++i)\n        res += Tn[0][i] * Tn[1].dot(map_t(coeffs_raw.data() + i * ORDER * ORDER) * Tn[2]);\n\n    return res;\n}\n\n/// @brief Node in baobzi::FunctionTree. If leaf, contains evaluation data, otherwise children\n/// @tparam D dimension of function\n/// @tparam ORDER order of evaluation polynomial\n/// @tparam ISET instruction set index (dummy variable to force alignment for different instruction sets)\ntemplate <int D, int ORDER, int ISET>\nclass Node {\n  public:\n    using VEC = Eigen::Vector<double, D>; ///< D dimensional vector type\n    using CoeffVec = Eigen::Vector<double, ORDER>; ///< ORDER dimensional vector type\n    std::vector<double, Eigen::aligned_allocator<double>> coeffs_; ///< Flattened chebyshev coeffs\n    using Func = Function<D, ORDER, ISET>; ///< Type of boabzi function this belongs to\n    Box<D, ISET> box_;             ///< Geometric position/size of this node\n    uint64_t first_child_idx = -1; ///< First child's index in a flattened list of all nodes\n    bool leaf_ = false;            ///< Helper variable to determine if node is a leaf\n\n    Node<D, ORDER, ISET>() = default; ///< Default constructor for msgpack happiness\n\n    /// @brief Construct node from box (without fitting)\n    /// @param [in] box box this node represents\n    Node<D, ORDER, ISET>(const Box<D, ISET> &box) : box_(box) {}\n\n    /// @brief check if node is leaf\n    /// @return true if leaf, false otherwise\n    inline bool is_leaf() const { return leaf_; }\n\n    /// @brief Fit node to a given tolerance. If fit succeeds, set leaf and coeffs, otherwise ... don't\n    ///\n    /// Modifies: Node::leaf_, Node::coeffs_\n    /// @param[in] input parameters for fit (function, tol, etc)\n    /// @returns true if fit successful, false if not good enough\n    bool fit(const baobzi_input_t *input) {\n        if constexpr (D == 1) {\n            Eigen::Vector<double, ORDER> F;\n            CoeffVec xvec =\n                Func::get_cheb_nodes(box_.center[0] - box_.half_length[0], box_.center[0] + box_.half_length[0]);\n\n            for (int i = 0; i < ORDER; ++i)\n                F(i) = input->func(&xvec[i], input->data);\n\n            Eigen::Vector<double, ORDER> coeffs = Func::VLU_.solve(F);\n\n            if (standard_error(coeffs) > input->tol)\n                return false;\n\n            coeffs_.resize(coeffs.size());\n            for (int i = 0; i < coeffs.size(); ++i)\n                coeffs_[i] = coeffs(i);\n\n            leaf_ = true;\n            return true;\n        }\n        if constexpr (D == 2) {\n            Eigen::Matrix<double, ORDER, ORDER> F;\n            CoeffVec xvec =\n                Func::get_cheb_nodes(box_.center[0] - box_.half_length[0], box_.center[0] + box_.half_length[0]);\n            CoeffVec yvec =\n                Func::get_cheb_nodes(box_.center[1] - box_.half_length[1], box_.center[1] + box_.half_length[1]);\n\n            for (int i = 0; i < ORDER; ++i) {\n                for (int j = 0; j < ORDER; ++j) {\n                    double x[2] = {xvec[i], yvec[j]};\n                    F(i, j) = input->func(x, input->data);\n                }\n            }\n\n            Eigen::Matrix<double, ORDER, ORDER> coeffs = Func::VLU_.solve(F);\n            coeffs = Func::VLU_.solve(coeffs.transpose()).transpose();\n\n            if (standard_error(coeffs) > input->tol)\n                return false;\n\n            coeffs_.resize(coeffs.size());\n            for (int i = 0; i < coeffs.size(); ++i)\n                coeffs_[i] = coeffs(i);\n\n            leaf_ = true;\n            return true;\n        }\n        if constexpr (D == 3) {\n            Eigen::Tensor<double, 3> F(ORDER, ORDER, ORDER);\n\n            CoeffVec xvec =\n                Func::get_cheb_nodes(box_.center[0] - box_.half_length[0], box_.center[0] + box_.half_length[0]);\n            CoeffVec yvec =\n                Func::get_cheb_nodes(box_.center[1] - box_.half_length[1], box_.center[1] + box_.half_length[1]);\n            CoeffVec zvec =\n                Func::get_cheb_nodes(box_.center[2] - box_.half_length[2], box_.center[2] + box_.half_length[2]);\n\n            for (int i = 0; i < ORDER; ++i) {\n                for (int j = 0; j < ORDER; ++j) {\n                    for (int k = 0; k < ORDER; ++k) {\n                        double x[3] = {xvec[i], yvec[j], zvec[k]};\n                        F(i, j, k) = input->func(x, input->data);\n                    }\n                }\n            }\n\n            coeffs_.resize(ORDER * ORDER * ORDER);\n            Eigen::Tensor<double, 3> coeffs_tensor(ORDER, ORDER, ORDER);\n            using matrix_t = Eigen::Matrix<double, ORDER, ORDER>;\n            using map_t = Eigen::Map<matrix_t>;\n            using tensor_t = Eigen::Tensor<double, 2>;\n            for (int block = 0; block < ORDER; ++block) {\n                tensor_t F_block_tensor = F.chip(block, 2);\n                map_t F_block(F_block_tensor.data());\n\n                matrix_t coeffs_tmp = Func::VLU_.solve(F_block);\n                coeffs_tmp = Func::VLU_.solve(coeffs_tmp.transpose()).transpose();\n                coeffs_tensor.chip(block, 2) = Eigen::TensorMap<tensor_t>(coeffs_tmp.data(), ORDER, ORDER);\n            }\n            for (int block = 0; block < ORDER; ++block) {\n                Eigen::Tensor<double, 2> coeffs_tmp = coeffs_tensor.chip(block, 0);\n                map_t coeffs_ysolve(coeffs_tmp.data());\n                map_t(coeffs_.data() + block * ORDER * ORDER) = Func::VLU_.solve(coeffs_ysolve.transpose()).transpose();\n            }\n\n            for (int i = 0; i < ORDER; ++i) {\n                for (int j = 0; j < ORDER; ++j) {\n                    for (int k = 0; k < ORDER; ++k) {\n                        VEC point =\n                            (box_.center - box_.half_length).array() +\n                            2.0 * VEC{(double)i, (double)j, (double)k}.array() * box_.half_length.array() / ORDER;\n\n                        const double test_val = eval(point);\n                        const double actual_val = input->func(point.data(), input->data);\n                        const double rel_error = std::abs((actual_val - test_val) / actual_val);\n\n                        if (fabs(actual_val) > 1E-16 && rel_error > input->tol) {\n                            coeffs_.clear();\n                            coeffs_.shrink_to_fit();\n                            return false;\n                        }\n                    }\n                }\n            }\n\n            leaf_ = true;\n            return true;\n        }\n    }\n\n    /// @brief eval node at point x\n    /// @param[in] x point to evaluate at\n    /// @returns function approximation at x\n    inline double eval(const VEC &x) const { return cheb_eval<ORDER, ISET>(x, box_, coeffs_); }\n\n    /// @brief MSGPACK serialization magic\n    MSGPACK_DEFINE(box_, first_child_idx, leaf_, coeffs_);\n};\n\n/// @brief Represent a function in some domain as a tree of chebyshev nodes\n/// @tparam DIM dimension of function\n/// @tparam ORDER order of evaluation polynomial\n/// @tparam ISET instruction set index (dummy variable to force alignment for different instruction sets)\ntemplate <int DIM, int ORDER, int ISET>\nstruct FunctionTree {\n    static constexpr int NChild = 1 << DIM; ///< Number of children each node potentially has (2^D)\n    static constexpr int Dim = DIM; ///< Dimension of tree\n    static constexpr int Order = ORDER; ///< Order of tree\n\n    using VEC = Eigen::Vector<double, DIM>; ///< D dimensional vector type\n    std::vector<Node<DIM, ORDER, ISET>> nodes_; ///< Flat list of all nodes in Tree (leaf or otherwise)\n\n    /// @brief Construct tree\n    /// @param[in] input parameters for fit (function, tol, etc)\n    /// @param[in] box box that this tree lives in\n    FunctionTree<DIM, ORDER, ISET>(const baobzi_input_t *input, const Box<DIM, ISET> &box) {\n        std::queue<Box<DIM, ISET>> q;\n        VEC half_width = box.half_length * 0.5;\n        q.push(box);\n\n        uint64_t curr_child_idx = 1;\n        while (!q.empty()) {\n            int n_next = q.size();\n            int node_index = nodes_.size();\n            for (int i = 0; i < n_next; ++i) {\n                Box<DIM, ISET> box = q.front();\n                q.pop();\n\n                nodes_.push_back(Node<DIM, ORDER, ISET>(box));\n            }\n\n#pragma omp parallel for\n            for (size_t i = 0; i < n_next; ++i) {\n                auto &node = nodes_[i + node_index];\n                node.fit(input);\n            }\n\n            for (int i = 0; i < n_next; ++i) {\n                auto &node = nodes_[i + node_index];\n                if (!node.is_leaf()) {\n                    node.first_child_idx = curr_child_idx;\n                    curr_child_idx += NChild;\n\n                    VEC &center = node.box_.center;\n                    for (uint64_t child = 0; child < NChild; ++child) {\n                        VEC offset;\n\n                        // Extract sign of each offset component from the bits of child\n                        // Basically: permute all possible offsets\n                        for (int j = 0; j < DIM; ++j) {\n                            double signed_hw[2] = {-half_width[j], half_width[j]};\n                            offset[j] = signed_hw[(child >> j) & 1];\n                        }\n\n                        q.push(Box<DIM, ISET>(center + offset, half_width));\n                    }\n                }\n            }\n\n            half_width *= 0.5;\n        }\n    }\n\n    FunctionTree<DIM, ORDER, ISET>() = default; ///< Default constructor for msgpack happiness\n\n    /// @brief Find leaf node containing a point via standard pointer traversal\n    /// @param[in] x point that the node will contain\n    /// @return leaf node containing point x\n    inline const Node<DIM, ORDER, ISET> &find_node_traverse(const VEC &x) const {\n        auto *node = &nodes_[0];\n        while (!node->is_leaf()) {\n            uint64_t child_idx = 0;\n            for (int i = 0; i < DIM; ++i)\n                child_idx = child_idx | ((x[i] > node->box_.center[i]) << i);\n\n            node = &nodes_[node->first_child_idx + child_idx];\n        }\n\n        return *node;\n    }\n\n    /// @brief eval function approximation at point\n    /// @param[in] x point to evaluate function at\n    /// @returns function approximation at point x\n    inline double eval(const VEC &x) const { return find_node_traverse(x).eval(x); }\n\n    /// @brief msgpack serialization magic\n    MSGPACK_DEFINE(nodes_);\n};\n\n/// @brief Represents a function in some domain as a grid of baobzi::FunctionTree objects\n/// @tparam DIM dimension of function\n/// @tparam ORDER order of evaluation polynomial\n/// @tparam ISET instruction set index (dummy variable to force alignment for different instruction sets)\ntemplate <int DIM, int ORDER, int ISET = 0>\nclass Function {\n  public:\n    static constexpr int NChild = 1 << DIM; ///< Number of children each node potentially has (2^D)\n    static constexpr int Dim = DIM; ///< Input dimension of function\n    static constexpr int Order = ORDER; ///< Order of polynomial representation\n    static constexpr int ISet = ISET; ///< Instruction set (dummy param)\n    static std::mutex statics_mutex; ///< mutex for locking vandermonde/chebyshev initialization\n\n    using VEC = Eigen::Vector<double, DIM>; ///< D dimensional vector type\n    using CoeffVec = Eigen::Vector<double, ORDER>; ///< Order dimensional vector type\n    using VanderMat = Eigen::Matrix<double, ORDER, ORDER>; ///< VanderMonde Matrix type\n\n    using DBox = Box<DIM, ISET>; ///< D dimensional box type\n\n    static CoeffVec cosarray_;                  ///< Cached array of cosine values at chebyshev nodes\n    static Eigen::PartialPivLU<VanderMat> VLU_; ///< Cached LU decomposition of Vandermonde matrix\n\n    DBox box_;       ///< box representing the domain of our function\n    double tol_;     ///< Desired relative tolerance of our approximation\n    VEC lower_left_; ///< Bottom 'corner' of our domain\n\n    std::vector<FunctionTree<DIM, ORDER, ISET>> subtrees_; ///< Grid of FunctionTree objects that do the work\n    Eigen::Vector<int, DIM> n_subtrees_;                   ///< Number of subtrees in each linear dimension of our space\n    VEC bin_size_;                                         ///< Linear dimensions of the bins that our subtrees live\n\n    /// @brief calculate vandermonde matrix\n    /// @return Vandermonde matrix for chebyshev polynomials with order=ORDER\n    static VanderMat calc_vandermonde() {\n        VanderMat V;\n\n        for (int j = 0; j < ORDER; ++j) {\n            V(0, j) = 1;\n            V(1, j) = cosarray_(j);\n        }\n\n        for (int i = 2; i < ORDER; ++i) {\n            for (int j = 0; j < ORDER; ++j) {\n                V(i, j) = double(2) * V(i - 1, j) * cosarray_(j) - V(i - 2, j);\n            }\n        }\n\n        return V.transpose();\n    }\n\n    /// @brief calculate chebyshev nodes on bounds [lb, ub]\n    /// @param[in] lb lower bound\n    /// @param[in] ub upper bound\n    /// @returns vector of chebyshev nodes scaled within [lb, ub]\n    static inline CoeffVec get_cheb_nodes(double lb, double ub) {\n        return 0.5 * ((lb + ub) + (ub - lb) * cosarray_.array());\n    }\n\n    /// @brief initialize static class variables\n    ///\n    /// Modifies baobzi::Function::cosarray_, baobzi::Function::VLU_\n    static void init_statics() {\n        static bool is_initialized = false;\n        std::lock_guard<std::mutex> lock(statics_mutex);\n        if (is_initialized)\n            return;\n\n        for (int i = 0; i < ORDER; ++i)\n            cosarray_[ORDER - i - 1] = cos(M_PI * (i + 0.5) / ORDER);\n        VLU_ = Eigen::PartialPivLU<VanderMat>(calc_vandermonde());\n        is_initialized = true;\n    }\n\n    /// @brief Construct our Function object (fits recursively, can be slow)\n    /// @param[in] input parameters for fit (function, tol, etc)\n    /// @param[in] xp [dim] center of function domain\n    /// @param[in] lp [dim] half length of function domain\n    Function<DIM, ORDER, ISET>(const baobzi_input_t *input, const double *xp, const double *lp)\n        : box_(VEC(xp), VEC(lp)), tol_(input->tol) {\n        init_statics();\n\n        VEC l(lp);\n        VEC x(xp);\n        std::queue<DBox> q;\n\n        for (int i = 0; i < DIM; ++i)\n            n_subtrees_[i] = l[i] / l.minCoeff();\n\n        uint8_t max_depth_ = 0;\n        q.push(DBox(x, l));\n\n        // Half-width of next children\n        VEC half_width = l * 0.5;\n\n        // Breadth first search. Step through each level of the tree and test fit all of the nodes\n        // We exit when a level isn't completely filled with parent nodes (rather than leaves)\n        // This way we can always avoid redundant traversals by jumping straight to a root node of a subtree\n        while (!q.empty()) {\n            int n_next = q.size();\n\n            std::vector<Node<DIM, ORDER, ISET>> nodes;\n            for (int i = 0; i < n_next; ++i) {\n                DBox box = q.front();\n                q.pop();\n\n                nodes.emplace_back(Node<DIM, ORDER, ISET>(box));\n            }\n\n#pragma omp parallel for\n            for (int i = 0; i < nodes.size(); ++i)\n                nodes[i].fit(input);\n\n            for (auto &node : nodes) {\n                if (!node.is_leaf()) {\n                    VEC &center = node.box_.center;\n                    for (unsigned child = 0; child < NChild; ++child) {\n                        VEC offset;\n\n                        // Extract sign of each offset component from the bits of child\n                        // Basically: permute all possible offsets\n                        for (int j = 0; j < DIM; ++j) {\n                            double signed_hw[2] = {-half_width[j], half_width[j]};\n                            offset[j] = signed_hw[(child >> j) & 1];\n                        }\n\n                        q.push(DBox(center + offset, half_width));\n                    }\n                }\n            }\n\n            if (!q.empty())\n                max_depth_++;\n\n            half_width *= 0.5;\n            if ((1 << (DIM * max_depth_)) == q.size())\n                n_subtrees_ *= 2;\n            else\n                break;\n        }\n\n        for (int j = 0; j < DIM; ++j)\n            bin_size_[j] = 2.0 * box_.half_length[j] / n_subtrees_[j];\n        lower_left_ = box_.center - box_.half_length;\n\n        subtrees_.reserve(n_subtrees_.prod());\n        for (int i_bin = 0; i_bin < n_subtrees_.prod(); ++i_bin) {\n            Eigen::Vector<int, DIM> bins = get_bins(i_bin);\n\n            VEC parent_center = (bins.template cast<double>().array() + 0.5) * bin_size_.array() + lower_left_.array();\n\n            Box<DIM, ISET> root_box = {parent_center, 0.5 * bin_size_};\n            subtrees_.push_back(FunctionTree<DIM, ORDER, ISET>(input, root_box));\n        }\n    }\n\n    /// @brief default constructor for msgpack magic\n    Function<DIM, ORDER, ISET>() { init_statics(); };\n\n    /// @brief convert linear bin index to [dim] bin vector\n    /// @param[in] i_bin linear index\n    /// @returns [dim] bin vector\n    inline Eigen::Vector<int, DIM> get_bins(const int i_bin) const {\n        if constexpr (DIM == 1)\n            return Eigen::Vector<int, DIM>{i_bin};\n        else if constexpr (DIM == 2)\n            return Eigen::Vector<int, DIM>{i_bin % n_subtrees_[0], i_bin / n_subtrees_[0]};\n        else if constexpr (DIM == 3)\n            return Eigen::Vector<int, DIM>{i_bin % n_subtrees_[0], (i_bin / n_subtrees_[0]) % n_subtrees_[1],\n                                           i_bin / (n_subtrees_[0] * n_subtrees_[1])};\n    }\n\n    /// @brief find linear index of bin at a point\n    /// @param[in] x [1] position to find bin\n    /// @returns linear index of bin that x lives in\n    inline int get_linear_bin(const Eigen::Vector<double, 1> &x) const {\n        const double x_bin = x[0] - lower_left_[0];\n        return x_bin / bin_size_[0];\n    }\n\n    /// @brief find linear index of bin at a point\n    /// @param[in] x [2] position to find bin\n    /// @returns linear index of bin that x lives in\n    inline int get_linear_bin(const Eigen::Vector2d &x) const {\n        const VEC x_bin = x - lower_left_;\n        const Eigen::Vector<int, DIM> bin = (x_bin.array() / bin_size_.array()).template cast<int>();\n        return bin[0] + n_subtrees_[0] * bin[1];\n    }\n\n    /// @brief find linear index of bin at a point\n    /// @param[in] x [3] position to find bin\n    /// @returns linear index of bin that x lives in\n    inline int get_linear_bin(const Eigen::Vector3d &x) const {\n        const VEC x_bin = x - lower_left_;\n        const Eigen::Vector<int, DIM> bin = (x_bin.array() / bin_size_.array()).template cast<int>();\n        return bin[0] + n_subtrees_[0] * bin[1] + n_subtrees_[0] * n_subtrees_[1] * bin[2];\n    }\n\n    /// @brief get constant reference to leaf node that contains a point\n    /// @param[in] x point of interest\n    /// @returns constant reference to leaf node that contains x\n    inline const Node<DIM, ORDER, ISET> &find_node(const VEC &x) const {\n        return subtrees_[get_linear_bin(x)].find_node_traverse(x);\n    }\n\n    /// @brief eval function approximation at point\n    /// @param[in] x point to evaluate function at\n    /// @returns function approximation at point x\n    inline double eval(const VEC &x) const { return find_node(x).eval(x); }\n\n    /// @brief eval function approximation at point\n    /// @param[in] xp [DIM] point to evaluate function at\n    /// @returns function approximation at point xp\n    inline double eval(const double *xp) const { return eval(VEC(xp)); }\n\n    /// @brief eval function approximation at point\n    /// @param[in] x [DIM] point to evaluate function at\n    /// @returns function approximation at point x\n    inline double operator()(const VEC &x) const { return eval(x); }\n\n    /// @brief eval function approximation at point\n    /// @param[in] x point to evaluate function at\n    /// @returns function approximation at point x\n    inline double operator()(const double *x) const { return eval(x); }\n\n    /// @brief save function approximation to file\n    /// @param[in] filename path to save file at\n    void save(const char *filename) {\n        std::ofstream ofs(filename, std::ofstream::binary | std::ofstream::out);\n        baobzi_header_t params{Dim, Order, BAOBZI_HEADER_VERSION};\n        msgpack::pack(ofs, params);\n        msgpack::pack(ofs, *this);\n    }\n\n    /// @brief msgpack serialization magic\n    MSGPACK_DEFINE_MAP(box_, subtrees_, n_subtrees_, tol_, lower_left_, bin_size_);\n};\n\ntemplate <int DIM, int ORDER, int ISET>\nstd::mutex Function<DIM, ORDER, ISET>::statics_mutex;\n\ntemplate <int DIM, int ORDER, int ISET>\ntypename Function<DIM, ORDER, ISET>::CoeffVec Function<DIM, ORDER, ISET>::cosarray_;\n\ntemplate <int DIM, int ORDER, int ISET>\nEigen::PartialPivLU<typename Function<DIM, ORDER, ISET>::VanderMat> Function<DIM, ORDER, ISET>::VLU_;\n} // namespace baobzi\n\n#endif\n", "meta": {"hexsha": "9dbe8a2a29d679cfd7aecad7f635ef3c3d660c55", "size": 25945, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/baobzi_template.hpp", "max_stars_repo_name": "ahbarnett/baobzi", "max_stars_repo_head_hexsha": "9dd8e8d4b52bcfc85ce384ba3d96350048313401", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/baobzi_template.hpp", "max_issues_repo_name": "ahbarnett/baobzi", "max_issues_repo_head_hexsha": "9dd8e8d4b52bcfc85ce384ba3d96350048313401", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/baobzi_template.hpp", "max_forks_repo_name": "ahbarnett/baobzi", "max_forks_repo_head_hexsha": "9dd8e8d4b52bcfc85ce384ba3d96350048313401", "max_forks_repo_licenses": ["Apache-2.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.9873617694, "max_line_length": 120, "alphanum_fraction": 0.5800346888, "num_tokens": 6722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623015, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6391984876749011}}
{"text": "#include <blitz/timer.h>\n\nBZ_USING_NAMESPACE(blitz)\n\ndouble dot(const double* a, const double* b, int n)\n{\n    double result = 0.;\n    for (int i=0; i < n; ++i)\n        result += a[i] * b[i];\n\n    return result;\n}\n\ntemplate<class T>\nvoid sink(T&)\n{\n}\n\nvoid sink(double,double,double,double,double,double,double,double,double,double)\n{\n}\n\nvoid init(double* x, int n)\n{\n    // Completely arbitrary\n    for (int i=0; i < n; ++i)\n        x[i] = 3.4982938192839824982 * i;\n}\n\nconst int nmax = 40;\n\nint main()\n{\n    Timer timer;\n    const int iterations1 = 5000000;\n\n    double a1[nmax],a2[nmax],a3[nmax],a4[nmax],a5[nmax],a6[nmax],a7[nmax],a8[nmax],a9[nmax],\n        a10[nmax],b1[nmax],b2[nmax],b3[nmax],b4[nmax],b5[nmax],b6[nmax],b7[nmax],b8[nmax],\n        b9[nmax],b10[nmax];\n    init(a1,nmax);\n    init(a2,nmax);\n    init(a3,nmax);\n    init(a4,nmax);\n    init(a5,nmax);\n    init(a6,nmax);\n    init(a7,nmax);\n    init(a8,nmax);\n    init(a9,nmax);\n    init(a10,nmax);\n    init(b1,nmax);\n    init(b2,nmax);\n    init(b3,nmax);\n    init(b4,nmax);\n    init(b5,nmax);\n    init(b6,nmax);\n    init(b7,nmax);\n    init(b8,nmax);\n    init(b9,nmax);\n    init(b10,nmax);\n\n    for (int n=1; n < nmax; ++n)\n    {\n    int iterations = iterations1 / n;\n\n    timer.start();\n    for (int i=0; i < iterations; ++i)\n    {\n        double result1 = dot(a1,b1,n);\n        double result2 = dot(a2,b2,n);\n        double result3 = dot(a3,b3,n);\n        double result4 = dot(a4,b4,n);\n        double result5 = dot(a5,b5,n);\n        double result6 = dot(a6,b6,n);\n        double result7 = dot(a7,b7,n);\n        double result8 = dot(a8,b8,n);\n        double result9 = dot(a9,b9,n);\n        double result10 = dot(a10,b10,n);\n        sink(result1,result2,result3,result4,result5,result6,result7,result8,\n            result9,result10);\n    }\n    timer.stop();\n\n    double Mflops = 10.0 * (n + (n-1)) * iterations / 1e+6;\n    cout << n << '\\t' << (Mflops/timer.elapsedSeconds()) << endl;\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "f77829cbc3dd3465b471018091f51e34c043227d", "size": 1975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/dot2.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/dot2.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/dot2.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9444444444, "max_line_length": 92, "alphanum_fraction": 0.5635443038, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587668, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6391890152777421}}
{"text": "#include <iostream>\n#include \"linalg.h\"\n\nusing namespace std;\n\n#include <ctime>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n#define MATRIX_SIZE 10\n\n\nint main(int argc, char **argv) {\n    Matrix<float, MATRIX_SIZE, MATRIX_SIZE> A\n      = MatrixXf::Random(MATRIX_SIZE, MATRIX_SIZE);\n    A = A * A.transpose();\n    Matrix<float, MATRIX_SIZE, 1> b = MatrixXf::Random(MATRIX_SIZE, 1);\n\n    MatrixXf x = LinearEquationSolve(A, b);\n    cout << \"Result is \" << x.transpose() << endl;\n    return 0;\n}", "meta": {"hexsha": "ad6e1b1f5d13c81cb803065a40c6b09d2d436c60", "size": 517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_linalg.cpp", "max_stars_repo_name": "chiqunz/slambook2", "max_stars_repo_head_hexsha": "6827c2a5677026ec212b1f1802e2c00877c67282", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/tests/test_linalg.cpp", "max_issues_repo_name": "chiqunz/slambook2", "max_issues_repo_head_hexsha": "6827c2a5677026ec212b1f1802e2c00877c67282", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/tests/test_linalg.cpp", "max_forks_repo_name": "chiqunz/slambook2", "max_forks_repo_head_hexsha": "6827c2a5677026ec212b1f1802e2c00877c67282", "max_forks_repo_licenses": ["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.5416666667, "max_line_length": 71, "alphanum_fraction": 0.669245648, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.639142485096439}}
{"text": "//  (C) Copyright Jeremy Murphy 2015.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/config.hpp>\r\n#define BOOST_TEST_MAIN\r\n#include <boost/array.hpp>\r\n#include <boost/math/tools/polynomial.hpp>\r\n#include <boost/math/common_factor_rt.hpp>\r\n#include <boost/mpl/list.hpp>\r\n#include <boost/mpl/joint_view.hpp>\r\n#include <boost/test/test_case_template.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <boost/multiprecision/cpp_bin_float.hpp>\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n#include <utility>\r\n\r\nusing namespace boost::math::tools;\r\nusing namespace std;\r\n\r\ntemplate <typename T>\r\nstruct answer\r\n{\r\n    answer(std::pair< polynomial<T>, polynomial<T> > const &x) :\r\n    quotient(x.first), remainder(x.second) {}\r\n    \r\n    polynomial<T> quotient;\r\n    polynomial<T> remainder;\r\n};\r\n\r\nboost::array<double, 4> const d3a = {{10, -6, -4, 3}};\r\nboost::array<double, 4> const d3b = {{-7, 5, 6, 1}};\r\nboost::array<double, 4> const d3c = {{10.0/3.0, -2.0, -4.0/3.0, 1.0}};\r\nboost::array<double, 2> const d1a = {{-2, 1}};\r\nboost::array<double, 3> const d2a = {{-2, 2, 3}};\r\nboost::array<double, 3> const d2b = {{-7, 5, 6}};\r\nboost::array<double, 3> const d2c = {{31, -21, -22}};\r\nboost::array<double, 1> const d0a = {{6}};\r\nboost::array<double, 1> const d0b = {{3}};\r\n\r\nboost::array<int, 9> const d8 = {{-5, 2, 8, -3, -3, 0, 1, 0, 1}};\r\nboost::array<int, 9> const d8b = {{0, 2, 8, -3, -3, 0, 1, 0, 1}};\r\nboost::array<int, 7> const d6 = {{21, -9, -4, 0, 5, 0, 3}};\r\nboost::array<int, 3> const d2 = {{-6, 0, 9}};\r\nboost::array<int, 6> const d5 = {{-9, 0, 3, 0, -15}};\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_construction )\r\n{\r\n    polynomial<double> const a(d3a.begin(), d3a.end());\r\n    polynomial<double> const b(d3a.begin(), 3);\r\n    BOOST_CHECK_EQUAL(a, b);\r\n}\r\n\r\n\r\n#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\r\nBOOST_AUTO_TEST_CASE( test_initializer_list_construction )\r\n{\r\n    polynomial<double> a(begin(d3a), end(d3a));\r\n    polynomial<double> b = {10, -6, -4, 3};\r\n    polynomial<double> c{{10, -6, -4, 3}};\r\n    BOOST_CHECK_EQUAL(a, b);\r\n    BOOST_CHECK_EQUAL(b, c);\r\n}\r\n#endif\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_degree )\r\n{\r\n    polynomial<double> const zero = zero_element(std::multiplies< polynomial<double> >());\r\n    polynomial<double> const a(d3a.begin(), d3a.end());\r\n    BOOST_CHECK_THROW(zero.degree(), std::logic_error);\r\n    BOOST_CHECK_EQUAL(a.degree(), 3u);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_division_over_field )\r\n{\r\n    polynomial<double> const a(d3a.begin(), d3a.end());\r\n    polynomial<double> const b(d1a.begin(), d1a.end());\r\n    polynomial<double> const q(d2a.begin(), d2a.end());\r\n    polynomial<double> const r(d0a.begin(), d0a.end());\r\n    polynomial<double> const c(d3b.begin(), d3b.end());\r\n    polynomial<double> const d(d2b.begin(), d2b.end());\r\n    polynomial<double> const e(d2c.begin(), d2c.end());\r\n    polynomial<double> const f(d0b.begin(), d0b.end());\r\n    polynomial<double> const g(d3c.begin(), d3c.end());\r\n    polynomial<double> const zero = zero_element(std::multiplies< polynomial<double> >());\r\n    polynomial<double> const one = identity_element(std::multiplies< polynomial<double> >());\r\n\r\n    answer<double> result = quotient_remainder(a, b);\r\n    BOOST_CHECK_EQUAL(result.quotient, q);\r\n    BOOST_CHECK_EQUAL(result.remainder, r);\r\n    BOOST_CHECK_EQUAL(a, q * b + r); // Sanity check.\r\n    \r\n    result = quotient_remainder(a, c);\r\n    BOOST_CHECK_EQUAL(result.quotient, f);\r\n    BOOST_CHECK_EQUAL(result.remainder, e);\r\n    BOOST_CHECK_EQUAL(a, f * c + e); // Sanity check.\r\n    \r\n    result = quotient_remainder(a, f);\r\n    BOOST_CHECK_EQUAL(result.quotient, g);\r\n    BOOST_CHECK_EQUAL(result.remainder, zero);\r\n    BOOST_CHECK_EQUAL(a, g * f + zero); // Sanity check.\r\n    // Check that division by a regular number gives the same result.\r\n    BOOST_CHECK_EQUAL(a / 3.0, g);\r\n    BOOST_CHECK_EQUAL(a % 3.0, zero);\r\n\r\n    // Sanity checks.\r\n    BOOST_CHECK_EQUAL(a / a, one);\r\n    BOOST_CHECK_EQUAL(a % a, zero);\r\n    // BOOST_CHECK_EQUAL(zero / zero, zero); // TODO\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( test_division_over_ufd )\r\n{\r\n    polynomial<int> const zero = zero_element(std::multiplies< polynomial<int> >());\r\n    polynomial<int> const one = identity_element(std::multiplies< polynomial<int> >());\r\n    polynomial<int> const aa(d8.begin(), d8.end());\r\n    polynomial<int> const bb(d6.begin(), d6.end());\r\n    polynomial<int> const q(d2.begin(), d2.end());\r\n    polynomial<int> const r(d5.begin(), d5.end());\r\n    \r\n    answer<int> result = quotient_remainder(aa, bb);\r\n    BOOST_CHECK_EQUAL(result.quotient, q);\r\n    BOOST_CHECK_EQUAL(result.remainder, r);\r\n\r\n    // Sanity checks.\r\n    BOOST_CHECK_EQUAL(aa / aa, one);\r\n    BOOST_CHECK_EQUAL(aa % aa, zero);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_gcd )\r\n{\r\n    /* NOTE: Euclidean gcd is not yet customized to return THE greatest \r\n     * common polynomial divisor. If d is THE greatest common divisior of u and\r\n     * v, then gcd(u, v) will return d or -d according to the algorithm.\r\n     * By convention, it should return d, as for example Maxima and Wolfram \r\n     * Alpha do.\r\n     * This test is an example of the fact that it returns -d.\r\n     */\r\n    boost::array<double, 9> const d8 = {{105, 278, -88, -56, 16}};\r\n    boost::array<double, 7> const d6 = {{70, 232, -44, -64, 16}};\r\n    boost::array<double, 7> const d2 = {{-35, 24, -4}};\r\n    polynomial<double> const u(d8.begin(), d8.end());\r\n    polynomial<double> const v(d6.begin(), d6.end());\r\n    polynomial<double> const w(d2.begin(), d2.end());\r\n    polynomial<double> const d = boost::math::gcd(u, v);\r\n    BOOST_CHECK_EQUAL(w, d);\r\n}\r\n\r\n// Sanity checks to make sure I didn't break it.\r\ntypedef boost::mpl::list<int, long, boost::multiprecision::cpp_int> integral_test_types;\r\ntypedef boost::mpl::list<double, boost::multiprecision::cpp_rational, boost::multiprecision::cpp_bin_float_single, boost::multiprecision::cpp_dec_float_50> non_integral_test_types;\r\ntypedef boost::mpl::joint_view<integral_test_types, non_integral_test_types> all_test_types;\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_addition, T, all_test_types )\r\n{\r\n    polynomial<T> const a(d3a.begin(), d3a.end());\r\n    polynomial<T> const b(d1a.begin(), d1a.end());\r\n    polynomial<T> const zero = zero_element(multiplies< polynomial<T> >());\r\n    \r\n    polynomial<T> result = a + b; // different degree\r\n    boost::array<T, 4> tmp = {{8, -5, -4, 3}};\r\n    polynomial<T> expected(tmp.begin(), tmp.end());\r\n    BOOST_CHECK_EQUAL(result, expected);\r\n    BOOST_CHECK_EQUAL(a + zero, a);\r\n    BOOST_CHECK_EQUAL(a + b, b + a);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_subtraction, T, all_test_types )\r\n{\r\n    polynomial<T> const a(d3a.begin(), d3a.end());\r\n    polynomial<T> const zero = zero_element(multiplies< polynomial<T> >());\r\n\r\n    BOOST_CHECK_EQUAL(a - T(0), a);\r\n    BOOST_CHECK_EQUAL(T(0) - a, -a);\r\n    BOOST_CHECK_EQUAL(a - zero, a);\r\n    BOOST_CHECK_EQUAL(zero - a, -a);\r\n    BOOST_CHECK_EQUAL(a - a, zero);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_multiplication, T, all_test_types )\r\n{\r\n    polynomial<T> const a(d3a.begin(), d3a.end());\r\n    polynomial<T> const b(d1a.begin(), d1a.end());\r\n    polynomial<T> const zero = zero_element(multiplies< polynomial<T> >());\r\n    \r\n    BOOST_CHECK_EQUAL(a * T(0), zero);\r\n    BOOST_CHECK_EQUAL(a * zero, zero);\r\n    BOOST_CHECK_EQUAL(zero * T(0), zero);\r\n    BOOST_CHECK_EQUAL(zero * zero, zero);\r\n    BOOST_CHECK_EQUAL(a * b, b * a);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE( test_arithmetic_relations, T, all_test_types )\r\n{\r\n    polynomial<T> const a(d8b.begin(), d8b.end());\r\n    polynomial<T> const b(d1a.begin(), d1a.end());\r\n\r\n    BOOST_CHECK_EQUAL(a * T(2), a + a);\r\n    BOOST_CHECK_EQUAL(a - b, -b + a);\r\n    BOOST_CHECK_EQUAL(a, (a * a) / a);\r\n    BOOST_CHECK_EQUAL(a, (a / a) * a);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_non_integral_arithmetic_relations, T, non_integral_test_types )\r\n{\r\n    polynomial<T> const a(d8b.begin(), d8b.end());\r\n    polynomial<T> const b(d1a.begin(), d1a.end());\r\n    \r\n    BOOST_CHECK_EQUAL(a * T(0.5), a / T(2));\r\n}\r\n\r\n", "meta": {"hexsha": "870739ee56c6bd7b3cd3f092e38b647f8b09d5bc", "size": 8254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_polynomial.cpp", "max_stars_repo_name": "snichols/boost_1_61_0", "max_stars_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-06T09:03:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-06T09:03:52.000Z", "max_issues_repo_path": "libs/math/test/test_polynomial.cpp", "max_issues_repo_name": "snichols/boost_1_61_0", "max_issues_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/test/test_polynomial.cpp", "max_forks_repo_name": "snichols/boost_1_61_0", "max_forks_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "max_forks_repo_licenses": ["BSL-1.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.6894977169, "max_line_length": 181, "alphanum_fraction": 0.6515628786, "num_tokens": 2343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.6391017843949404}}
{"text": "\r\n// Copyright (C) 2008-2018 Lorenzo Caminiti\r\n// Distributed under the Boost Software License, Version 1.0 (see accompanying\r\n// file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).\r\n// See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html\r\n\r\n//[n1962_sqrt\r\n#include <boost/contract.hpp>\r\n#include <cmath>\r\n#include <cassert>\r\n\r\nlong lsqrt(long x) {\r\n    long result;\r\n    boost::contract::check c = boost::contract::function()\r\n        .precondition([&] {\r\n            BOOST_CONTRACT_ASSERT(x >= 0);\r\n        })\r\n        .postcondition([&] {\r\n            BOOST_CONTRACT_ASSERT(result * result <= x);\r\n            BOOST_CONTRACT_ASSERT((result + 1) * (result + 1) > x);\r\n        })\r\n    ;\r\n\r\n    return result = long(std::sqrt(double(x)));\r\n}\r\n\r\nint main() {\r\n    assert(lsqrt(4) == 2);\r\n    return 0;\r\n}\r\n//]\r\n\r\n", "meta": {"hexsha": "61176947ee52633007fc6efb6a9437766aa625c7", "size": 857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/contract/example/n1962/sqrt.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/contract/example/n1962/sqrt.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/contract/example/n1962/sqrt.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 25.9696969697, "max_line_length": 80, "alphanum_fraction": 0.5950991832, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.6391017748091002}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n/**\n * Test_PolyEval.cpp - Homomorphic Polynomial Evaluation\n */\n#include <NTL/ZZ.h>\nNTL_CLIENT\n#include \"polyEval.h\"\n#include \"EncryptedArray.h\"\n\n#ifdef DEBUG_PRINTOUT\nextern FHESecKey* dbgKey;\nextern EncryptedArray* dbgEa;\n#endif\n\nstatic bool noPrint = false;\n\nbool testEncrypted(long d, const EncryptedArray& ea,\n\t\t   const FHESecKey& secretKey)\n{\n  const FHEcontext& context = ea.getContext();\n  const FHEPubKey& publicKey = secretKey;\n  long p = publicKey.getPtxtSpace();\n  zz_pBak bak; bak.save(); zz_p::init(p);\n  zz_pXModulus phimX = conv<zz_pX>(context.zMStar.getPhimX());\n\n  // Choose random plaintext polynomials\n  zz_pX pX = random_zz_pX(deg(phimX)-1);\n  Vec<zz_pX> ppoly(INIT_SIZE, d);\n  for (long i=0; i<ppoly.length(); i++) random(ppoly[i], deg(phimX)-1);\n\n  // Evaluate the non-encrypted polynomial\n  zz_pX pres = (ppoly.length()>0)? ppoly[ppoly.length()-1] : zz_pX::zero();\n  for (long i=ppoly.length()-2; i>=0; i--) {\n    MulMod(pres, pres, pX, phimX);\n    pres += ppoly[i];\n  }\n\n  // Encrypt the random polynomials\n  Ctxt cX(publicKey);\n  Vec<Ctxt> cpoly(INIT_SIZE, d, cX);\n  secretKey.Encrypt(cX, conv<ZZX>(pX));\n  for (long i=0; i<ppoly.length(); i++)\n    secretKey.Encrypt(cpoly[i], conv<ZZX>(ppoly[i]));\n\n  // Evaluate the encrypted polynomial\n  polyEval(cX, cpoly, cX);\n\n  // Compare the results\n  ZZX ret;\n  secretKey.Decrypt(ret, cX);\n  zz_pX cres = conv<zz_pX>(ret);\n  bool success = (cres == pres);\n  if (success) std::cout << \" encrypted poly match, \";\n  else         std::cout << \" encrypted poly MISMATCH\\n\";\n  return success;\n}\n\nvoid testIt(long d, long k, long p, long r, long m, long L,\n\t    bool isMonic=false)\n{\n  FHEcontext context(m, p, r);\n  long p2r = context.alMod.getPPowR();\n  buildModChain(context, L, /*c=*/3);\n  EncryptedArray ea(context);\n\n  FHESecKey secretKey(context);\n  const FHEPubKey& publicKey = secretKey;\n  secretKey.GenSecKey(/*w=*/64);// A Hamming-weight-64 secret key\n  //  addSome1DMatrices(secretKey); // compute key-switching matrices\n\n#ifdef DEBUG_PRINTOUT\n  dbgEa = &ea;        // for debugging purposes\n  dbgKey = &secretKey;\n#endif\n\n  if (!noPrint) std::cout << (isDryRun()? \"* dry run, \" : \"* \")\n\t\t     << \"degree-\"<<d<<\", m=\"<<m<<\", L=\"<<L<<\", p^r=\"<<p2r<<endl;\n\n  // evaluate encrypted poly at encrypted point\n  if (!testEncrypted(d, ea, secretKey)) exit(0);\n\n  // evaluate at random points (at least one co-prime with p)\n  vector<long> x;\n  ea.random(x);\n  while (GCD(x[0],p)!=1) { x[0] = RandomBnd(p2r); }\n  Ctxt inCtxt(publicKey), outCtxt(publicKey);\n  ea.encrypt(inCtxt, publicKey, x);\n\n  ZZX poly;\n  for (long i=d; i>=0; i--)\n    SetCoeff(poly, i, RandomBnd(p2r)); // coefficients are random\n  if (isMonic) SetCoeff(poly, d);    // set top coefficient to 1\n\n  // Evaluate poly on the ciphertext\n  polyEval(outCtxt, poly, inCtxt, k);\n\n  // Check the result\n  vector<long> y;\n  ea.decrypt(outCtxt, secretKey, y);\n  for (long i=0; i<ea.size(); i++) {\n    long ret = polyEvalMod(poly, x[i], p2r);\n    if (ret != y[i]) {\n      std::cout << \"plaintext poly MISMATCH\\n\";\n      exit(0);\n    }\n  }\n  std::cout << \"plaintext poly match\\n\" << std::flush;\n}\n\nvoid usage(char *prog) \n{\n  std::cout << \"Usage: \"<<prog<<\" [ optional parameters ]...\\n\";\n  std::cout << \"  optional parameters have the form 'attr1=val1 attr2=val2 ...'\\n\";\n  std::cout << \"  dry=1 for dry run [default=0]\\n\";\n  std::cout << \"  p is the plaintext base [default=3]\" << endl;\n  std::cout << \"  r is the lifting [default=2]\" << endl;\n  std::cout << \"  m is a specific cyclotomic ring\\n\";\n  std::cout << \"  d is the polynomial degree [default=undefined]\" << endl;\n  std::cout << \"    d=undefined means trying a few powers d=1,...,4,25,...,34\"<<endl;\n  std::cout << \"  k is the baby-step parameter [default=undefined]\" << endl;\n  std::cout << \"    if k is undefined it is computed from d\" << endl;\n  std::cout << \"  noPrint suppresses printouts [default=0]\" << endl;\n  exit(0);\n}\n\nint main(int argc, char *argv[])\n{\n  argmap_t argmap;\n  argmap[\"p\"] = \"3\";\n  argmap[\"r\"] = \"2\";\n  argmap[\"m\"] = \"0\";\n  argmap[\"d\"] = \"-1\";\n  argmap[\"k\"] = \"0\";\n  argmap[\"dry\"] = \"0\";\n  argmap[\"noPrint\"] = \"0\";\n\n  // get parameters from the command line\n  if (!parseArgs(argc, argv, argmap)) usage(argv[0]);\n\n  long p = atoi(argmap[\"p\"]);\n  long r = atoi(argmap[\"r\"]);\n  long m = atoi(argmap[\"m\"]);\n  long d = atoi(argmap[\"d\"]);\n  long k = atoi(argmap[\"k\"]);\n  bool dry = atoi(argmap[\"dry\"]);\n  noPrint = atoi(argmap[\"noPrint\"]);\n\n  long max_d = (d<=0)? 35 : d;\n  long L = 5+NextPowerOfTwo(max_d);\n  if (m<2)\n    m = FindM(/*secprm=*/80, L, /*c=*/3, p, 1, 0, m, !noPrint);\n  setDryRun(dry);\n\n  // Test both monic and non-monic polynomials of this degree\n  if (d>=0) {\n    testIt(d, k, p, r, m, L, false);\n    testIt(d, k, p, r, m, L, true);\n    return 0;\n  }\n\n  // Test degrees 1 to 4 and 25 through 35\n  testIt(1, k, p, r, m, L, true);\n  testIt(3, k, p, r, m, L, true);\n  for (d=25; d<=33; d+=2)\n    testIt(d, k, p, r, m, L);\n\n  return 0;\n}\n", "meta": {"hexsha": "8b34b4c064e18e7bb9bcde535108f41914e59dc6", "size": 5590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Test_PolyEval.cpp", "max_stars_repo_name": "bryongloden/HElib", "max_stars_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-29T17:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T06:46:20.000Z", "max_issues_repo_path": "src/Test_PolyEval.cpp", "max_issues_repo_name": "bryongloden/HElib", "max_issues_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-10-17T08:04:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-28T06:36:40.000Z", "max_forks_repo_path": "src/Test_PolyEval.cpp", "max_forks_repo_name": "bryongloden/HElib", "max_forks_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-10-16T09:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-10T07:24:51.000Z", "avg_line_length": 31.2290502793, "max_line_length": 85, "alphanum_fraction": 0.6327370304, "num_tokens": 1805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.7981867753392728, "lm_q1q2_score": 0.639101774785242}}
{"text": "#include \"project/ExponentialSmoothing.hpp\"\n#include \"project/vecPush.hpp\"\n#include <armadillo>\n#include <math.h> \n\nExponentialSmoothing::ExponentialSmoothing(arma::vec &time_series, float alpha){\n    param_alpha = alpha;\n    ts = time_series;\n}\n\narma::vec calculateWeigths(float alpha, int length) {\n    arma::vec weigths = arma::zeros(length);\n    weigths(0) = alpha;\n    for (int ii = 1; ii < length; ii++){\n        weigths(ii) = alpha*pow((1-alpha),ii);\n    };\n\n    return weigths;\n}\n\nvoid ExponentialSmoothing::fit(){\n    weigths = calculateWeigths(param_alpha, ts.n_rows);\n}\n\nfloat weigthedMean(arma::vec &x, arma::vec &weigths){\n    float weigthed_mean = arma::sum(x%weigths)/arma::sum(weigths);\n    return weigthed_mean;\n}\n\nvoid vec_push(arma::vec &v, float value) {\n    arma::vec av(1);\n    av.at(0) = value;\n    v.insert_rows(v.n_rows, av.row(0));\n}\n\narma::vec ExponentialSmoothing::forecast(int horizon){\n    arma::vec forecast = arma::zeros(horizon);\n    arma::vec tmp_ts = ts;\n    for (int ii = 0; ii < horizon; ii++){\n        float point_forecast = weigthedMean(tmp_ts, weigths);\n        forecast(ii) = point_forecast;\n        vec_push(tmp_ts, )\n    }\n}", "meta": {"hexsha": "a299fa286969a0e776f1b2b443910c343e42e2d6", "size": 1167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ExponentialSmoothing.cpp", "max_stars_repo_name": "haruspex-machine/ts-forecast-cpp", "max_stars_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T06:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T06:27:15.000Z", "max_issues_repo_path": "src/ExponentialSmoothing.cpp", "max_issues_repo_name": "bklimowski/ts-forecast-cpp", "max_issues_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ExponentialSmoothing.cpp", "max_forks_repo_name": "bklimowski/ts-forecast-cpp", "max_forks_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5227272727, "max_line_length": 80, "alphanum_fraction": 0.6589545844, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.6390949820383366}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\ntypedef std::vector<vecteur> matrice;\n\nENREGISTRER_PROBLEME(99, \"Largest exponential\") {\n    // Comparing two numbers written in index form like 211 and 37 is not difficult, as any calculator would confirm\n    // that 2^11 = 2048 < 3^7 = 2187.\n    //\n    // However, confirming that 632382^518061 > 519432^525806 would be much more difficult, as both numbers contain over\n    // three million digits.\n    // \n    // Using base_exp.txt (right click and 'Save Link/Target As...'), a 22K text file containing one thousand lines with\n    // a base/exponent pair on each line, determine which line number has the greatest numerical value.\n    // \n    // NOTE: The first two lines in the file represent the numbers in the example given above.\n    std::ifstream ifs(\"data/p099_base_exp.txt\");\n    nombre resultat = 0;\n    nombre numero_ligne = 1;\n    std::string ligne;\n    long double maximum = 0;\n    while (ifs >> ligne) {\n        std::vector<std::string> v;\n        boost::split(v, ligne, boost::is_any_of(\",\"));\n        const long double log = std::log(std::stold(v.front())) * std::stold(v.back());\n        if (log > maximum) {\n            resultat = numero_ligne;\n            maximum = log;\n        }\n        ++numero_ligne;\n    }\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "d85013369f501febdffc7f52ba3a9367f8fd151d", "size": 1450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme099.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme099.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme0xx/probleme099.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": 37.1794871795, "max_line_length": 120, "alphanum_fraction": 0.6593103448, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6390949752660143}}
{"text": "#ifndef IP3_DET_MODEL_HPP_INCLUDED\n#define IP3_DET_MODEL_HPP_INCLUDED\n#include <vector>\n#include <iostream>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n#include \"astron_utility_functions.hpp\"\n//const double pi = boost::math::constants::pi<double>();\n\n//DECLATATIONS FOR IP3_SYSTEM\nclass IP3\n{\n   private:\n\n      double a2 = 0.2E-03;     //    0.2         1/(micro M * sec)\n      double d1 = 0.13;   //     0.13        micro M\n      double d2 = 1.049;  //     1.049       micro M\n      double d3 = 0.9434;   //   0.9434      micro M\n      double d5 = 0.08234; //    0.08234     micro M\n\n      double c0 = 2.0;  //       2.0         micro M\n      double c1 = 0.185;   //                Dimensionless\n      double v1 = 6.0E-03; //        6.0         1/sec\n      double v2 = 0.11E-03;//        0.11        1/sec\n      double v3 = 0.9E-03;     //    0.9         1/ (micro M * sec)\n      double k3 = 0.1;   //      0.1         micro M\n\n   public:\n\n      double CaER = 0.0;      // micro M (Calcium concentration in the ER)\n      double ip3_conc = 0.0;      // micro M (Given IP3 concentration in the cytosol)\n      double ca_conc = 0.0;\n\n      double ip3_tau = 0.0;\n      double ip3_rate = 0.0;\n      double ip3_thres = 0.0;\n      double ip3_gen = 0.0;\n      double ip3_equ = 0.0;\n\n//------------------ CONSTRUCTORS\n\n   /* IP3 class implicit constructor */\n   IP3(): CaER(0.0), ca_conc(0.0), ip3_conc(0.0)\n   {\n   };\n\n  /* ASTRO class explicit constructor */\n   IP3( double CaER_, double ca_conc_, double ip3_conc_ ): CaER(CaER_), ca_conc(ca_conc_), ip3_conc(ip3_conc_)\n   {\n   };\n//------------------ Function declarations\n   void set_CaER();\n\n   double m_inf();\n   double h_inf();\n   double h_tau();\n\n   template <class State, class Deriv >\n   void operator() ( const State &x, Deriv &dxdt , const double  t );\n};\n//--------------------m_inf Function\ndouble IP3::m_inf()\n{\n   double value =  ( ip3_conc / ( ip3_conc + d1 ) ) * ( ca_conc / (ca_conc + d5) ) ;\n   return value;\n};\n//--------------------h_tau Function\ndouble IP3::h_tau()\n{\n   double Q2 = d2 * ((ip3_conc + d1)/(ip3_conc + d3));\n   double value  = 1 / (a2 * (Q2 + ca_conc) );\n   return value;\n}\n\n//--------------------h_inf Function\ndouble IP3::h_inf()\n{\n   double Q2 = d2 * ((ip3_conc + d1)/(ip3_conc + d3));\n   double value = Q2/(Q2+ca_conc);\n   return value;\n};\n//--------------------Set CaER Function\nvoid IP3::set_CaER()\n{\n   this->CaER = (c0 - ca_conc) / c1;\n   //std::cout << \"Set_CaER = \" << (c0 - ca_conc)/c1 << \"\\t\" << CaER << \"\\n\";\n};\n//------- ASTRO class ODE Function\ntemplate <class State, class Deriv >\nvoid IP3::operator() ( const State &x_, Deriv &dxdt_ , const double t )\n{\n   typename boost::range_iterator< const State >::type x = boost::begin( x_ );\n   typename boost::range_iterator< Deriv >::type dxdt = boost::begin( dxdt_ );\n\n   //std::cout << CaER << \"\\n\";\n\n   ca_conc = x[1]; // Set Calcium concentration\n   ip3_conc = x[2]; // Set ip3 concentration\n\n   set_CaER(); // Update ER calcium level\n\n   dxdt[0] = ( h_inf() - x[0] ) / h_tau() ; // dh/dt\n\n   double JCh = ( c1 * v1 * pow(m_inf(),3) * pow(x[0],3) * (x[1] - CaER) ); //   J_channel\n   double JPump = ( v3 * pow(x[1],2) ) / ( pow(k3,2) + pow(x[1],2) ) ;   //    J_Pump\n   double JLeak = c1 * v2 * ( x[1] - CaER );   //    J_Leak\n\n   dxdt[1] = - (JCh + JPump + JLeak) ;// dCa/dt\n   dxdt[2] =  (1/ip3_tau) * (ip3_equ - x[2])  + (ip3_rate * heaviside(ip3_gen,ip3_thres)) ;//dip3/dt\n\n\n};\n\n#endif // IP3_DET_MODEL_HPP_INCLUDED\n", "meta": {"hexsha": "b5c27f7243b7346fe965c76a67c723aefc723ebb", "size": 3483, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/ip3_det_model.hpp", "max_stars_repo_name": "anupgp/astron", "max_stars_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/old/src/old/ip3_det_model.hpp", "max_issues_repo_name": "anupgp/astron", "max_issues_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/old/src/old/ip3_det_model.hpp", "max_forks_repo_name": "anupgp/astron", "max_forks_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2869565217, "max_line_length": 110, "alphanum_fraction": 0.5480907264, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6390949732339303}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * testTriangulation.cpp\n *\n *  Created on: July 30th, 2013\n *      Author: cbeall3\n */\n\n#include <gtsam/geometry/triangulation.h>\n#include <gtsam/geometry/PinholeCamera.h>\n#include <gtsam/geometry/StereoCamera.h>\n#include <gtsam/geometry/CameraSet.h>\n#include <gtsam/geometry/Cal3Bundler.h>\n#include <gtsam/slam/StereoFactor.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/nonlinear/ExpressionFactor.h>\n#include <CppUnitLite/TestHarness.h>\n\n\n#include <boost/assign.hpp>\n#include <boost/assign/std/vector.hpp>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace boost::assign;\n\n// Some common constants\n\nstatic const boost::shared_ptr<Cal3_S2> sharedCal = //\n    boost::make_shared<Cal3_S2>(1500, 1200, 0, 640, 480);\n\n// Looking along X-axis, 1 meter above ground plane (x-y)\nstatic const Rot3 upright = Rot3::Ypr(-M_PI / 2, 0., -M_PI / 2);\nstatic const Pose3 pose1 = Pose3(upright, gtsam::Point3(0, 0, 1));\nPinholeCamera<Cal3_S2> camera1(pose1, *sharedCal);\n\n// create second camera 1 meter to the right of first camera\nstatic const Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1, 0, 0));\nPinholeCamera<Cal3_S2> camera2(pose2, *sharedCal);\n\n// landmark ~5 meters infront of camera\nstatic const Point3 landmark(5, 0.5, 1.2);\n\n// 1. Project two landmarks into two cameras and triangulate\nPoint2 z1 = camera1.project(landmark);\nPoint2 z2 = camera2.project(landmark);\n\n//******************************************************************************\n// Simple test with a well-behaved two camera situation\nTEST( triangulation, twoPoses) {\n\n  vector<Pose3> poses;\n  Point2Vector measurements;\n\n  poses += pose1, pose2;\n  measurements += z1, z2;\n\n  double rank_tol = 1e-9;\n\n  // 1. Test simple DLT, perfect in no noise situation\n  bool optimize = false;\n  boost::optional<Point3> actual1 = //\n      triangulatePoint3(poses, sharedCal, measurements, rank_tol, optimize);\n  EXPECT(assert_equal(landmark, *actual1, 1e-7));\n\n  // 2. test with optimization on, same answer\n  optimize = true;\n  boost::optional<Point3> actual2 = //\n      triangulatePoint3(poses, sharedCal, measurements, rank_tol, optimize);\n  EXPECT(assert_equal(landmark, *actual2, 1e-7));\n\n  // 3. Add some noise and try again: result should be ~ (4.995, 0.499167, 1.19814)\n  measurements.at(0) += Point2(0.1, 0.5);\n  measurements.at(1) += Point2(-0.2, 0.3);\n  optimize = false;\n  boost::optional<Point3> actual3 = //\n      triangulatePoint3(poses, sharedCal, measurements, rank_tol, optimize);\n  EXPECT(assert_equal(Point3(4.995, 0.499167, 1.19814), *actual3, 1e-4));\n\n  // 4. Now with optimization on\n  optimize = true;\n  boost::optional<Point3> actual4 = //\n      triangulatePoint3(poses, sharedCal, measurements, rank_tol, optimize);\n  EXPECT(assert_equal(Point3(4.995, 0.499167, 1.19814), *actual4, 1e-4));\n}\n\n//******************************************************************************\n// Similar, but now with Bundler calibration\nTEST( triangulation, twoPosesBundler) {\n\n  boost::shared_ptr<Cal3Bundler> bundlerCal = //\n      boost::make_shared<Cal3Bundler>(1500, 0, 0, 640, 480);\n  PinholeCamera<Cal3Bundler> camera1(pose1, *bundlerCal);\n  PinholeCamera<Cal3Bundler> camera2(pose2, *bundlerCal);\n\n  // 1. Project two landmarks into two cameras and triangulate\n  Point2 z1 = camera1.project(landmark);\n  Point2 z2 = camera2.project(landmark);\n\n  vector<Pose3> poses;\n  Point2Vector measurements;\n\n  poses += pose1, pose2;\n  measurements += z1, z2;\n\n  bool optimize = true;\n  double rank_tol = 1e-9;\n\n  boost::optional<Point3> actual = //\n      triangulatePoint3(poses, bundlerCal, measurements, rank_tol, optimize);\n  EXPECT(assert_equal(landmark, *actual, 1e-7));\n\n  // Add some noise and try again\n  measurements.at(0) += Point2(0.1, 0.5);\n  measurements.at(1) += Point2(-0.2, 0.3);\n\n  boost::optional<Point3> actual2 = //\n      triangulatePoint3(poses, bundlerCal, measurements, rank_tol, optimize);\n  EXPECT(assert_equal(Point3(4.995, 0.499167, 1.19847), *actual2, 1e-4));\n}\n\n//******************************************************************************\nTEST( triangulation, fourPoses) {\n  vector<Pose3> poses;\n  Point2Vector measurements;\n\n  poses += pose1, pose2;\n  measurements += z1, z2;\n\n  boost::optional<Point3> actual = triangulatePoint3(poses, sharedCal,\n      measurements);\n  EXPECT(assert_equal(landmark, *actual, 1e-2));\n\n  // 2. Add some noise and try again: result should be ~ (4.995, 0.499167, 1.19814)\n  measurements.at(0) += Point2(0.1, 0.5);\n  measurements.at(1) += Point2(-0.2, 0.3);\n\n  boost::optional<Point3> actual2 = //\n      triangulatePoint3(poses, sharedCal, measurements);\n  EXPECT(assert_equal(landmark, *actual2, 1e-2));\n\n  // 3. Add a slightly rotated third camera above, again with measurement noise\n  Pose3 pose3 = pose1 * Pose3(Rot3::Ypr(0.1, 0.2, 0.1), Point3(0.1, -2, -.1));\n  PinholeCamera<Cal3_S2> camera3(pose3, *sharedCal);\n  Point2 z3 = camera3.project(landmark);\n\n  poses += pose3;\n  measurements += z3 + Point2(0.1, -0.1);\n\n  boost::optional<Point3> triangulated_3cameras = //\n      triangulatePoint3(poses, sharedCal, measurements);\n  EXPECT(assert_equal(landmark, *triangulated_3cameras, 1e-2));\n\n  // Again with nonlinear optimization\n  boost::optional<Point3> triangulated_3cameras_opt = triangulatePoint3(poses,\n      sharedCal, measurements, 1e-9, true);\n  EXPECT(assert_equal(landmark, *triangulated_3cameras_opt, 1e-2));\n\n  // 4. Test failure: Add a 4th camera facing the wrong way\n  Pose3 pose4 = Pose3(Rot3::Ypr(M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));\n  PinholeCamera<Cal3_S2> camera4(pose4, *sharedCal);\n\n#ifdef GTSAM_THROW_CHEIRALITY_EXCEPTION\n  CHECK_EXCEPTION(camera4.project(landmark), CheiralityException);\n\n  poses += pose4;\n  measurements += Point2(400, 400);\n\n  CHECK_EXCEPTION(triangulatePoint3(poses, sharedCal, measurements),\n      TriangulationCheiralityException);\n#endif\n}\n\n//******************************************************************************\nTEST( triangulation, fourPoses_distinct_Ks) {\n  Cal3_S2 K1(1500, 1200, 0, 640, 480);\n  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)\n  PinholeCamera<Cal3_S2> camera1(pose1, K1);\n\n  // create second camera 1 meter to the right of first camera\n  Cal3_S2 K2(1600, 1300, 0, 650, 440);\n  PinholeCamera<Cal3_S2> camera2(pose2, K2);\n\n  // 1. Project two landmarks into two cameras and triangulate\n  Point2 z1 = camera1.project(landmark);\n  Point2 z2 = camera2.project(landmark);\n\n  CameraSet<PinholeCamera<Cal3_S2> > cameras;\n  Point2Vector measurements;\n\n  cameras += camera1, camera2;\n  measurements += z1, z2;\n\n  boost::optional<Point3> actual = //\n      triangulatePoint3(cameras, measurements);\n  EXPECT(assert_equal(landmark, *actual, 1e-2));\n\n  // 2. Add some noise and try again: result should be ~ (4.995, 0.499167, 1.19814)\n  measurements.at(0) += Point2(0.1, 0.5);\n  measurements.at(1) += Point2(-0.2, 0.3);\n\n  boost::optional<Point3> actual2 = //\n      triangulatePoint3(cameras, measurements);\n  EXPECT(assert_equal(landmark, *actual2, 1e-2));\n\n  // 3. Add a slightly rotated third camera above, again with measurement noise\n  Pose3 pose3 = pose1 * Pose3(Rot3::Ypr(0.1, 0.2, 0.1), Point3(0.1, -2, -.1));\n  Cal3_S2 K3(700, 500, 0, 640, 480);\n  PinholeCamera<Cal3_S2> camera3(pose3, K3);\n  Point2 z3 = camera3.project(landmark);\n\n  cameras += camera3;\n  measurements += z3 + Point2(0.1, -0.1);\n\n  boost::optional<Point3> triangulated_3cameras = //\n      triangulatePoint3(cameras, measurements);\n  EXPECT(assert_equal(landmark, *triangulated_3cameras, 1e-2));\n\n  // Again with nonlinear optimization\n  boost::optional<Point3> triangulated_3cameras_opt = triangulatePoint3(cameras,\n      measurements, 1e-9, true);\n  EXPECT(assert_equal(landmark, *triangulated_3cameras_opt, 1e-2));\n\n  // 4. Test failure: Add a 4th camera facing the wrong way\n  Pose3 pose4 = Pose3(Rot3::Ypr(M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));\n  Cal3_S2 K4(700, 500, 0, 640, 480);\n  PinholeCamera<Cal3_S2> camera4(pose4, K4);\n\n#ifdef GTSAM_THROW_CHEIRALITY_EXCEPTION\n  CHECK_EXCEPTION(camera4.project(landmark), CheiralityException);\n\n  cameras += camera4;\n  measurements += Point2(400, 400);\n  CHECK_EXCEPTION(triangulatePoint3(cameras, measurements),\n      TriangulationCheiralityException);\n#endif\n}\n\n//******************************************************************************\nTEST( triangulation, outliersAndFarLandmarks) {\n  Cal3_S2 K1(1500, 1200, 0, 640, 480);\n  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)\n  PinholeCamera<Cal3_S2> camera1(pose1, K1);\n\n  // create second camera 1 meter to the right of first camera\n  Cal3_S2 K2(1600, 1300, 0, 650, 440);\n  PinholeCamera<Cal3_S2> camera2(pose2, K2);\n\n  // 1. Project two landmarks into two cameras and triangulate\n  Point2 z1 = camera1.project(landmark);\n  Point2 z2 = camera2.project(landmark);\n\n  CameraSet<PinholeCamera<Cal3_S2> > cameras;\n  Point2Vector measurements;\n\n  cameras += camera1, camera2;\n  measurements += z1, z2;\n\n  double landmarkDistanceThreshold = 10; // landmark is closer than that\n  TriangulationParameters params(1.0, false, landmarkDistanceThreshold); // all default except landmarkDistanceThreshold\n  TriangulationResult actual = triangulateSafe(cameras,measurements,params);\n  EXPECT(assert_equal(landmark, *actual, 1e-2));\n  EXPECT(actual.valid());\n\n  landmarkDistanceThreshold = 4; // landmark is farther than that\n  TriangulationParameters params2(1.0, false, landmarkDistanceThreshold); // all default except landmarkDistanceThreshold\n  actual = triangulateSafe(cameras,measurements,params2);\n  EXPECT(actual.farPoint());\n\n  // 3. Add a slightly rotated third camera above with a wrong measurement (OUTLIER)\n  Pose3 pose3 = pose1 * Pose3(Rot3::Ypr(0.1, 0.2, 0.1), Point3(0.1, -2, -.1));\n  Cal3_S2 K3(700, 500, 0, 640, 480);\n  PinholeCamera<Cal3_S2> camera3(pose3, K3);\n  Point2 z3 = camera3.project(landmark);\n\n  cameras += camera3;\n  measurements += z3 + Point2(10, -10);\n\n  landmarkDistanceThreshold = 10; // landmark is closer than that\n  double outlierThreshold = 100; // loose, the outlier is going to pass\n  TriangulationParameters params3(1.0, false, landmarkDistanceThreshold,outlierThreshold);\n  actual = triangulateSafe(cameras,measurements,params3);\n  EXPECT(actual.valid());\n\n  // now set stricter threshold for outlier rejection\n  outlierThreshold = 5; // tighter, the outlier is not going to pass\n  TriangulationParameters params4(1.0, false, landmarkDistanceThreshold,outlierThreshold);\n  actual = triangulateSafe(cameras,measurements,params4);\n  EXPECT(actual.outlier());\n}\n\n//******************************************************************************\nTEST( triangulation, twoIdenticalPoses) {\n  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)\n  PinholeCamera<Cal3_S2> camera1(pose1, *sharedCal);\n\n  // 1. Project two landmarks into two cameras and triangulate\n  Point2 z1 = camera1.project(landmark);\n\n  vector<Pose3> poses;\n  Point2Vector measurements;\n\n  poses += pose1, pose1;\n  measurements += z1, z1;\n\n  CHECK_EXCEPTION(triangulatePoint3(poses, sharedCal, measurements),\n      TriangulationUnderconstrainedException);\n}\n\n//******************************************************************************\nTEST( triangulation, onePose) {\n  // we expect this test to fail with a TriangulationUnderconstrainedException\n  // because there's only one camera observation\n\n  vector<Pose3> poses;\n  Point2Vector measurements;\n\n  poses += Pose3();\n  measurements += Point2(0,0);\n\n  CHECK_EXCEPTION(triangulatePoint3(poses, sharedCal, measurements),\n      TriangulationUnderconstrainedException);\n}\n\n//******************************************************************************\nTEST( triangulation, StereotriangulateNonlinear ) {\n\n  auto stereoK = boost::make_shared<Cal3_S2Stereo>(1733.75, 1733.75, 0, 689.645, 508.835, 0.0699612);\n\n  // two camera poses m1, m2\n  Matrix4 m1, m2;\n  m1 << 0.796888717,     0.603404026,   -0.0295271487, 46.6673779,\n      0.592783835,    -0.77156583,    0.230856632,   66.2186159,\n      0.116517574,   -0.201470143,     -0.9725393, -4.28382528,\n      0, 0, 0, 1;\n\n  m2 << -0.955959025,    -0.29288915,   -0.0189328569, 45.7169799,\n      -0.29277519,    0.947083213,    0.131587097, 65.843136,\n     -0.0206094928,   0.131334858,   -0.991123524, -4.3525033,\n     0, 0, 0, 1;\n\n  typedef CameraSet<StereoCamera> Cameras;\n  Cameras cameras;\n  cameras.push_back(StereoCamera(Pose3(m1), stereoK));\n  cameras.push_back(StereoCamera(Pose3(m2), stereoK));\n\n  StereoPoint2Vector measurements;\n  measurements += StereoPoint2(226.936, 175.212, 424.469);\n  measurements += StereoPoint2(339.571, 285.547, 669.973);\n\n  Point3 initial = Point3(46.0536958, 66.4621179, -6.56285929);  // error: 96.5715555191\n\n  Point3 actual = triangulateNonlinear(cameras, measurements, initial);\n\n  Point3 expected(46.0484569, 66.4710686, -6.55046613); // error: 0.763510644187\n\n  EXPECT(assert_equal(expected, actual, 1e-4));\n\n\n  // regular stereo factor comparison - expect very similar result as above\n  {\n    typedef GenericStereoFactor<Pose3,Point3> StereoFactor;\n\n    Values values;\n    values.insert(Symbol('x', 1), Pose3(m1));\n    values.insert(Symbol('x', 2), Pose3(m2));\n    values.insert(Symbol('l', 1), initial);\n\n    NonlinearFactorGraph graph;\n    static SharedNoiseModel unit(noiseModel::Unit::Create(3));\n    graph.emplace_shared<StereoFactor>(measurements[0], unit, Symbol('x',1), Symbol('l',1), stereoK);\n    graph.emplace_shared<StereoFactor>(measurements[1], unit, Symbol('x',2), Symbol('l',1), stereoK);\n\n    const SharedDiagonal posePrior = noiseModel::Isotropic::Sigma(6, 1e-9);\n    graph.addPrior(Symbol('x',1), Pose3(m1), posePrior);\n    graph.addPrior(Symbol('x',2), Pose3(m2), posePrior);\n\n    LevenbergMarquardtOptimizer optimizer(graph, values);\n    Values result = optimizer.optimize();\n\n    EXPECT(assert_equal(expected, result.at<Point3>(Symbol('l',1)), 1e-4));\n  }\n\n  // use Triangulation Factor directly - expect same result as above\n  {\n    Values values;\n    values.insert(Symbol('l', 1), initial);\n\n    NonlinearFactorGraph graph;\n    static SharedNoiseModel unit(noiseModel::Unit::Create(3));\n\n    graph.emplace_shared<TriangulationFactor<StereoCamera> >(cameras[0], measurements[0], unit, Symbol('l',1));\n    graph.emplace_shared<TriangulationFactor<StereoCamera> >(cameras[1], measurements[1], unit, Symbol('l',1));\n\n    LevenbergMarquardtOptimizer optimizer(graph, values);\n    Values result = optimizer.optimize();\n\n    EXPECT(assert_equal(expected, result.at<Point3>(Symbol('l',1)), 1e-4));\n  }\n\n  // use ExpressionFactor - expect same result as above\n  {\n    Values values;\n    values.insert(Symbol('l', 1), initial);\n\n    NonlinearFactorGraph graph;\n    static SharedNoiseModel unit(noiseModel::Unit::Create(3));\n\n    Expression<Point3> point_(Symbol('l',1));\n    Expression<StereoCamera> camera0_(cameras[0]);\n    Expression<StereoCamera> camera1_(cameras[1]);\n    Expression<StereoPoint2> project0_(camera0_, &StereoCamera::project2, point_);\n    Expression<StereoPoint2> project1_(camera1_, &StereoCamera::project2, point_);\n\n    graph.addExpressionFactor(unit, measurements[0], project0_);\n    graph.addExpressionFactor(unit, measurements[1], project1_);\n\n    LevenbergMarquardtOptimizer optimizer(graph, values);\n    Values result = optimizer.optimize();\n\n    EXPECT(assert_equal(expected, result.at<Point3>(Symbol('l',1)), 1e-4));\n  }\n}\n\n//******************************************************************************\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n//******************************************************************************\n", "meta": {"hexsha": "4f71a48dad409fb2bf3c8830dc1d6ea0e5ab7b83", "size": 16046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/tests/testTriangulation.cpp", "max_stars_repo_name": "zwn/gtsam", "max_stars_repo_head_hexsha": "3422c3bb66bef319d66a950857bb6ec073b43703", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "gtsam/geometry/tests/testTriangulation.cpp", "max_issues_repo_name": "zwn/gtsam", "max_issues_repo_head_hexsha": "3422c3bb66bef319d66a950857bb6ec073b43703", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "gtsam/geometry/tests/testTriangulation.cpp", "max_forks_repo_name": "zwn/gtsam", "max_forks_repo_head_hexsha": "3422c3bb66bef319d66a950857bb6ec073b43703", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 36.3854875283, "max_line_length": 121, "alphanum_fraction": 0.6750592048, "num_tokens": 4725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6390874885308283}}
{"text": "#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <fstream>\n\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include \"SpmvBase.h\"\n#include \"MaxSLiCInterface.h\"\n\n#include <dfesnippets/sparse/common.hpp>\n#include <dfesnippets/sparse/sparse_matrix.hpp>\n#include <dfesnippets/sparse/partition.hpp>\n\n#include \"fpga.hpp\"\n// #define DEBUG_PRINT_MATRICES\n// #define DEBUG_PARTITIONS\n\nusing namespace std;\n\nstring check_file(char **argv) {\n  string path{argv[2]};\n  ifstream f{path};\n  if (!f) {\n    cout << \"Error opening input file\" << endl;\n    exit(1);\n  }\n  return path;\n}\n\nint main(int argc, char** argv) {\n\n  cout << \"Program arguments:\" << endl;\n  for (int i = 0; i < argc; i++)\n    cout << \"   \" << argv[i] << endl;\n\n  string path = check_file(argv);\n  int num_repeat = boost::lexical_cast<int>(argv[3]);\n\n  // -- Design Parameters\n  int numPipes = SpmvBase_numPipes;\n\n  // -- Matrix Parameters\n  int n, nnzs;\n  double* values;\n  int *col_ind, *row_ptr;\n\n  read_ge_mm_csr((char *)path.c_str(), &n, &nnzs, &col_ind, &row_ptr, &values);\n\n  // adjust from 1 indexed CSR (used by MKL) to 0 indexed CSR\n  for (int i = 0; i < nnzs; i++)\n    col_ind[i]--;\n\n  using namespace boost::numeric;\n  // generate multiplicand\n  vector<double> v(n);\n  ublas::vector<double> vu(n);\n  for (int i = 1; i <=n; i++) {\n    v[i - 1] = i;\n    vu(i - 1) = i;\n  }\n\n  // -- load the CSR matrix\n  CsrMatrix<> inMatrix(n, n);\n\n  for (int i = 0; i < n; ++i)\n  {\n          int rowStart = row_ptr[i] - 1;\n          int rowEnd = row_ptr[i + 1] - 1;\n          for (int j = rowStart; j < rowEnd; ++j)\n          {\n                  inMatrix(i, col_ind[j]) = values[j];\n          }\n  }\n\n\n  auto res = ublas::prod(inMatrix, vu);\n  vector<double> bExp = SpMV_MKL_ge((char *)path.c_str(), v);\n\n  int partitionSize = min(SpmvBase_vectorCacheSize, n);\n  vector<CsrMatrix<double>> partitions = partition(inMatrix, partitionSize);\n  vector<double> dfe_res(n, 0);\n\n  AdjustedCsrMatrix<double> full_original_matrix(n);\n  full_original_matrix.load_from_csr(\n      &inMatrix.value_data()[0],\n      &inMatrix.index2_data()[0],\n      &inMatrix.index1_data()[0]);\n\n#ifdef DEBUG_PRINT_MATRICES\n  cout << \"Full original matrix \" << endl;\n  full_original_matrix.print_dense();\n  cout << \"Vector: \" << endl;\n  print_vector(v);\n#endif\n\n  int offset = 0;\n  for (size_t i = 0; i < partitions.size(); ++i) {\n    auto p = partitions[i];\n    AdjustedCsrMatrix<double> original_matrix(n);\n    original_matrix.load_from_csr(\n        &p.value_data()[0],\n        &p.index2_data()[0],\n        &p.index1_data()[0]\n        );\n\n#ifdef DEBUG_PRINT_MATRICES\n    original_matrix.print();\n    original_matrix.print_dense();\n#endif\n\n    // find expected result\n    vector<double> vblock(v.begin() + offset, v.begin() + offset + partitionSize);\n    auto b = SpMV_DFE(original_matrix, vblock, numPipes, num_repeat);\n    for (int j = 0; j < n; ++j)\n    {\n      dfe_res[j] += b[j];\n    }\n    offset += partitionSize;\n  }\n\n  cout << \"Checking ublas \" << endl;\n  for (int i = 0; i < n; ++i) {\n    if (!dfesnippets::numeric_utils::almost_equal(res(i), bExp[i])) {\n      cerr << \"Expected \" << bExp[i] << \" got: \" << res(i) << endl;\n      exit(1);\n    }\n  }\n  cout << \"Ran SPMV \" << endl;\n\n  int errors = 0;\n  for (size_t i = 0; i < dfe_res.size(); i++)\n    if (!dfesnippets::numeric_utils::almost_equal(bExp[i], dfe_res[i])) {\n      cerr << \"Expected [ \" << i << \" ] \" << bExp[i] << \" got: \" << dfe_res[i] << endl;\n      errors++;\n    }\n\n  if (errors != 0) {\n    cerr << \"Errors \" << errors <<endl;\n    return 1;\n  }\n\n  cout << \"Test passed!\" << endl;\n  return 0;\n}\n", "meta": {"hexsha": "533f0c2dc7252c94968ab81c04f20b30881e21c1", "size": 3694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/LinearAlgebra/AdjustedCSRSpMV/src/AdjustedCSRSpMVCpuCode.cpp", "max_stars_repo_name": "custom-computing-ic/dfe-snippets", "max_stars_repo_head_hexsha": "8721e6272c25f77360e2de423d8ff5a9299ee5b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T13:23:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T11:04:40.000Z", "max_issues_repo_path": "test/LinearAlgebra/AdjustedCSRSpMV/src/AdjustedCSRSpMVCpuCode.cpp", "max_issues_repo_name": "custom-computing-ic/dfe-snippets", "max_issues_repo_head_hexsha": "8721e6272c25f77360e2de423d8ff5a9299ee5b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2015-07-02T10:13:05.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-30T15:59:43.000Z", "max_forks_repo_path": "test/LinearAlgebra/AdjustedCSRSpMV/src/AdjustedCSRSpMVCpuCode.cpp", "max_forks_repo_name": "custom-computing-ic/dfe-snippets", "max_forks_repo_head_hexsha": "8721e6272c25f77360e2de423d8ff5a9299ee5b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-08T13:27:50.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-16T14:38:52.000Z", "avg_line_length": 24.7919463087, "max_line_length": 87, "alphanum_fraction": 0.6028695181, "num_tokens": 1125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6390603544062816}}
{"text": "/**\n * @file polynomial_gcd.hh\n * @author \u674e\u660a\u5764 (ker@pm.me)\n * @brief \u5b9a\u4e49polynomial_gcd\n*/\n#ifndef CLPOLY_POLYNOMIAL_GCD_HH\n#define CLPOLY_POLYNOMIAL_GCD_HH\n#include <clpoly/polynomial.hh>\n#include <clpoly/upolynomial.hh>\n#include <boost/math/special_functions/prime.hpp>\n#include <cmath>\n#include <cstdint>\n#include <vector>\n#include <cassert>\n#include <random>\n\nnamespace clpoly{ \n\n    template <class comp>\n    basic_monomial<comp> gcd(const basic_monomial<comp> &m1,const basic_monomial<comp> &m2)\n    {\n        assert(comp_consistent(m1.comp(),m2.comp()));\n        basic_monomial<comp> m(m1.comp_ptr());\n        if (m1.empty()|| m2.empty())\n        {\n            return m;\n        }\n        m.reserve(m1.size());\n        auto m1_ptr=m1.begin();\n        auto m2_ptr=m2.begin();\n        while (m1_ptr!=m1.end() && m2_ptr!=m2.end())\n        {\n            if (m1.comp(m1_ptr->first,m2_ptr->first))\n            {\n                ++m1_ptr;\n            }\n            else\n            {\n                if (m1_ptr->first==m2_ptr->first)\n                {\n                    m.push_back({m1_ptr->first,std::min(m1_ptr->second,m2_ptr->second)});\n                    ++m1_ptr;\n                }\n                ++m2_ptr;\n            }\n        }\n        return m;\n    }\n    template<class var_order>\n    polynomial_<ZZ,lex_<var_order>> cont(const polynomial_<ZZ,lex_<var_order>> &F_);\n    template<class var_order>\n    polynomial_<ZZ,lex_<var_order>> leadcoeff(const polynomial_<ZZ,lex_<var_order>> &F_);\n    template<class var_order>\n    int64_t  __polynomial_GCD(       polynomial_<Zp,lex_<var_order>> & Pout,\n                            const polynomial_<Zp,lex_<var_order>> & F,\n                            const polynomial_<Zp,lex_<var_order>> & G,\n                            const polynomial_<Zp,lex_<var_order>> & Lc_gcd,\n                            int64_t deg);\n    template<class var_order>\n    polynomial_<ZZ,lex_<var_order>> polynomial_GCD(polynomial_<ZZ,lex_<var_order>>  F, polynomial_<ZZ,lex_<var_order>>  G);\n    template <class compare>\n    inline polynomial_<ZZ,compare> polynomial_GCD(const polynomial_<ZZ,compare>  &F, const polynomial_<ZZ,compare> & G)\n    {\n        polynomial_<ZZ,lex> F_,G_;\n        poly_convert(F,F_);\n        poly_convert(G,G_);\n        polynomial_<ZZ,compare>  Pout(F.comp_ptr());\n        poly_convert(polynomial_GCD(std::move(F_),std::move(G_)),Pout);\n        return Pout;\n    }\n    template <class comp>\n    inline polynomial_<ZZ,comp> gcd(const polynomial_<ZZ,comp> &F,const polynomial_<ZZ,comp> & G)\n    {\n        return polynomial_GCD(F,G);\n    }\n    template<class var_order>\n    bool is_squarefree (const polynomial_<ZZ,lex_<var_order>> &  F)\n    {\n        if (F.empty())\n            return false;\n        if (is_number(F))\n            return true;\n        auto f_cont=cont(F);\n        if (is_squarefree(f_cont))\n        {\n            auto F_=F/f_cont;\n            auto F_1=polynomial_GCD(F_,derivative(F_));\n            if (is_number(F_1))\n                return true;\n        }\n        return false;\n    }\n    template<class comp>\n    bool is_squarefree (const polynomial_<ZZ,comp> &  F)\n    {\n        polynomial_<ZZ,lex> F_;\n        poly_convert(F,F_);\n        return is_squarefree(F_);\n    }\n    template<class var_order>\n    std::vector<std::pair<polynomial_<ZZ,lex_<var_order>>,uint64_t>> squarefreefactorize (const polynomial_<ZZ,lex_<var_order>> &  F)\n    {\n        // std::cout<<\"F:\"<<F<<std::endl;\n        if (F.empty())\n            return {};\n        if (is_number(F))\n            return {{F,1}};\n        auto f_cont=cont(F);\n        auto F_=F/f_cont;\n        auto lst=squarefreefactorize(f_cont);\n        polynomial_<ZZ,lex_<var_order>> F_1(F.comp_ptr()),F_2(F.comp_ptr()),F_3(F.comp_ptr());\n        for(uint64_t i=1;;++i)\n        {\n            // std::cout<<\"F_:\"<<F_<<std::endl;\n            // std::cout<<\"D(F_):\"<<derivative(F_)<<std::endl;\n            \n            F_1=polynomial_GCD(F_,derivative(F_));\n            // std::cout<<\"F_1:\"<<F_1<<std::endl;\n            if (is_number(F_1))\n            {\n                if (i>1 && F_!=F_3 )\n                {\n                    lst.push_back({F_3/F_,i-1});\n                }\n                lst.push_back({F_,i});\n                break;\n            }\n            F_2=F_/F_1;\n            // std::cout<<\"F_2:\"<<F_2<<std::endl;\n            if (F_2!=F_3)\n            {\n                if (i>1)\n                {\n                    lst.push_back({F_3/F_2,i-1});\n                }\n                F_3=std::move(F_2);\n                \n            }\n            F_=std::move(F_1);\n        }\n        return lst;\n    }\n    template <class comp>\n    std::vector<std::pair<polynomial_<ZZ,comp>,uint64_t>> squarefreefactorize (const polynomial_<ZZ,comp> &  F)\n    {\n        polynomial_<ZZ,lex> F_;\n        poly_convert(F,F_);\n        auto lst=squarefreefactorize(F_);\n        std::vector<std::pair<polynomial_<ZZ,comp>,uint64_t>> lst_(lst.size(),{polynomial_<ZZ,comp>(F.comp_ptr()),0});\n        for (uint64_t i=0;i<lst.size();++i)\n        {\n            poly_convert(lst[i].first,lst_[i].first);\n            lst_[i].second=lst[i].second;\n        }\n        return lst_;\n    }\n    template<class var_order>\n    std::pair<std::vector<polynomial_<ZZ,lex_<var_order>>>,\n              std::vector<std::vector<std::pair<uint64_t,uint64_t>>>>  \n    squarefreebasis (const std::vector<polynomial_<ZZ,lex_<var_order>>>&  F)\n    {\n        std::vector<polynomial_<ZZ,lex_<var_order>>> lst,lst_;\n        std::vector<std::vector<std::pair<uint64_t,uint64_t>>> I,I_;\n        for (size_t i=0;i<F.size();++i)\n        {\n            lst_.clear(); \n            I_.clear(); \n            std::vector<std::pair<polynomial_<ZZ,lex_<var_order>>,uint64_t>>  l_=squarefreefactorize(F[i]);\n            if (l_.empty())\n                continue;\n            auto l_ptr=l_.begin();\n            for (++l_ptr;l_ptr!=l_.end();++l_ptr)\n            {\n                auto tmp=std::move(l_ptr->first);\n                for (size_t j=0;j<lst.size();++j)\n                {\n                    auto F1=polynomial_GCD(lst[j],tmp);\n                    if (!is_number(F1))\n                    {\n                        tmp=tmp/F1;\n                        if (F1!=lst[j])\n                        {\n                            lst[j]=lst[j]/F1;\n                            lst_.push_back(std::move(F1));\n                            I_.push_back(I[j]);\n                            I_.back().push_back({i,l_ptr->second});\n                        }\n                        else{\n                            I[j].push_back({i,l_ptr->second});\n                        }\n                        if (is_number(tmp))\n                            break;\n                    }\n                }\n                if (!is_number(tmp))\n                {\n                    lst_.push_back(std::move(tmp));\n                    I_.push_back({{i,l_ptr->second}});\n                }\n            }\n            // lst.reserve(lst.size()+lst_.size());\n            lst.insert(lst.end(),lst_.begin(),lst_.end());\n            I.insert(I.end(),I_.begin(),I_.end());\n            // for (auto &j:lst_)\n            // {\n            //      lst.push_back(std::move(j));\n            // }\n        }\n        return {std::move(lst),std::move(I)};\n    }\n    \n    template <class comp>\n    std::pair<std::vector<polynomial_<ZZ,comp>>,\n              std::vector<std::vector<std::pair<uint64_t,uint64_t>>>>      \n    squarefreebasis (const std::vector<polynomial_<ZZ,comp>> &  F)\n    {\n        std::vector<polynomial_<ZZ,comp>> L;\n        if (F.empty())\n            return {{},{}};\n        std::vector<polynomial_<ZZ,lex>> lst;\n        polynomial_<ZZ,lex> p;\n        lst.reserve(F.size());\n        for (auto &i:F)\n        {\n            poly_convert(i,p);\n            lst.push_back(std::move(p));\n        }\n        auto l_=squarefreebasis(lst);\n        lst=std::move(l_.first);\n        L.reserve(lst.size());\n        polynomial_<ZZ,comp> p1(F.front().comp_ptr());\n        for (auto &i:lst)\n        {\n            poly_convert(i,p1);\n            L.push_back(std::move(p1));\n        }\n        return {std::move(L),std::move(l_.second)};\n    }\n    \n\n\n\n\n\n    template<class var_order>\n    polynomial_<ZZ,lex_<var_order>> polynomial_GCD(polynomial_<ZZ,lex_<var_order>>  F, polynomial_<ZZ,lex_<var_order>>  G)\n    {\n        assert(comp_consistent(F.comp(),G.comp()));\n        if (F.empty())\n            return G;\n        if (G.empty())\n            return F;\n        if (F.size()==1 || G.size()==1)\n        {\n            auto ptr=F.begin();\n            auto m=ptr->first;\n            auto c=ptr->second;\n            for(++ptr;ptr!=F.end();++ptr)\n            {\n                m=gcd(m,ptr->first);\n                c=gcd(c,ptr->second);\n            }\n            for(ptr=G.begin();ptr!=G.end();++ptr)\n            {\n                m=gcd(m,ptr->first);\n                c=gcd(c,ptr->second);\n            }\n            polynomial_<ZZ,lex_<var_order>> Pout(F.comp_ptr());\n            Pout={{m,c}};\n            return Pout;\n            \n        }\n        \n        variable ffv,gfv;\n        while ((ffv=get_first_var(F))!=(gfv=get_first_var(G)) || !ffv.serial())\n        {\n            if (!ffv.serial() || !gfv.serial())\n            {\n                ZZ cont=0;\n                for(auto &i:F)\n                    cont=gcd(cont,i.second);\n                for(auto &i:G)\n                    cont=gcd(cont,i.second);\n                polynomial_<ZZ,lex_<var_order>> Pout(F.comp_ptr());\n                Pout={{basic_monomial<lex_<var_order>>(F.comp_ptr()),cont}};\n                return Pout;    \n            }\n            if (F.comp(ffv,gfv))\n            {\n                F=cont(F);\n            }\n            else\n            {\n                G=cont(G);\n            }\n        }\n        polynomial_<ZZ,lex_<var_order>> F_cont=cont(F);\n        polynomial_<ZZ,lex_<var_order>> G_cont=cont(G);\n        polynomial_<ZZ,lex_<var_order>> cont_gcd=polynomial_GCD(cont(F),cont(G));\n\n        F=F/F_cont;G=G/G_cont;\n        polynomial_<ZZ,lex_<var_order>> lc_gcd=polynomial_GCD(leadcoeff(F),leadcoeff(G));\n       \n        \n        // std::cout<<\"F:\"<<F<<std::endl;\n        // std::cout<<\"G:\"<<G<<std::endl;\n        // std::cout<<\"cont_gcd:\"<<cont_gcd<<std::endl;\n        // std::cout<<\"lc_gcd:\"<<lc_gcd<<std::endl;\n        \n        std::uint32_t tmp_x=std::max(degree(F),degree(G));\n        if (tmp_x<2) tmp_x=2;\n        std::uint32_t p_index=tmp_x/std::log(tmp_x);\n        std::uint32_t prime=boost::math::prime(p_index);\n        while (prime <tmp_x)\n        {\n            prime=boost::math::prime(++p_index);\n        }\n\n        polynomial_<ZZ,lex_<var_order>> Pout_(F.comp_ptr()),tmp_Pout_(F.comp_ptr()),R(F.comp_ptr());\n        polynomial_<Zp,lex_<var_order>> Pout_mod(F.comp_ptr()),f_p(F.comp_ptr()),g_p(F.comp_ptr()),lc_gcd_p(F.comp_ptr());\n        polynomial_<ZZ,lex_<var_order>> tmp(F.comp_ptr());\n        ZZ Pout_prime;\n        std::int64_t Pout_d=INT64_MAX;\n        std::int64_t tmp_Pout_d=INT64_MAX;\n        \n        while (1)\n        {\n            \n            while (F.begin()->second % prime ==0 || G.begin()->second % prime ==0)\n            {\n                prime=boost::math::prime(++p_index);\n            }\n            f_p=polynomial_mod(F,prime);\n            g_p=polynomial_mod(G,prime);\n            lc_gcd_p=polynomial_mod(lc_gcd,prime);\n\n            // std::cout<<\"p:\"<<prime<<std::endl;\n            // std::cout<<\"f_p:\"<<f_p<<std::endl;\n            // std::cout<<\"g_p:\"<<g_p<<std::endl;\n            // std::cout<<\"lc_gcd_p:\"<<lc_gcd_p<<std::endl;\n\n            tmp_Pout_d=__polynomial_GCD(Pout_mod,f_p,g_p,lc_gcd_p,Pout_d);\n            if (tmp_Pout_d==-1)\n            {\n                prime=boost::math::prime(++p_index);\n                continue;\n            }\n            \n            // std::cout<<\"poly_mod:\"<<Pout_mod<<std::endl;\n            \n            if (tmp_Pout_d < Pout_d)\n            {\n                Pout_d=tmp_Pout_d;\n                Pout_prime=prime;\n                poly_convert(Pout_mod,Pout_);\n                for (auto &i:Pout_)\n                {\n                    i.second%=Pout_prime;\n                    if (i.second>Pout_prime/2)\n                    {\n                        i.second-=Pout_prime;\n                    }\n                }\n                \n                // std::cout<<\"Pout_:\"<<Pout_<<std::endl;\n                \n            }\n            else\n            {\n                Zp tmp_inv(Pout_prime,prime);\n                tmp_inv=tmp_inv.inv();\n                tmp_Pout_.clear();\n                tmp_Pout_.reserve(Pout_.size());\n                auto Pout_ptr=Pout_.begin();\n                auto Pout_end=Pout_.end();\n                auto Pm_ptr=Pout_mod.begin();\n                auto Pm_end=Pout_mod.end();\n                while (Pout_ptr!=Pout_end && Pm_ptr!=Pm_end)\n                {\n                    if (F.comp(Pout_ptr->first,Pm_ptr->first))\n                    {\n                        tmp_Pout_.push_back({Pout_ptr->first,Pout_ptr->second-Pout_ptr->second*tmp_inv.number()*Pout_prime});\n                        ++Pout_ptr;\n                    }\n                    else\n                    {\n                        if (Pout_ptr->first==Pm_ptr->first)\n                        {\n                            tmp_Pout_.push_back({std::move(Pm_ptr->first),Pout_ptr->second+\n                            (Pm_ptr->second.number()-Pout_ptr->second)*tmp_inv.number()*Pout_prime});\n                            ++Pout_ptr;\n                        }\n                        else\n                        {\n                            tmp_Pout_.push_back({std::move(Pm_ptr->first),Pm_ptr->second.number()*tmp_inv.number()*Pout_prime});\n                            \n                        }\n                        ++Pm_ptr;\n                    }\n                    \n                }\n                while (Pout_ptr!=Pout_end)\n                {\n                    tmp_Pout_.push_back({std::move(Pout_ptr->first),Pout_ptr->second-Pout_ptr->second*tmp_inv.number()*Pout_prime});\n                    ++Pout_ptr;\n                }\n                while (Pm_ptr!=Pm_end)\n                {\n                    tmp_Pout_.push_back({std::move(Pm_ptr->first),Pm_ptr->second.number()*tmp_inv.number()*Pout_prime});\n                    ++Pm_ptr;\n                }\n                Pout_prime*=prime; \n                for (auto &i:tmp_Pout_)\n                {\n                    i.second%=Pout_prime;\n                    if (i.second>Pout_prime/2)\n                    {\n                        i.second-=Pout_prime;\n                    }\n                    else if (i.second<-Pout_prime/2)\n                    {\n                        i.second+=Pout_prime;\n                    }\n                }\n                \n                // std::cout<<\"Pout_:\"<<tmp_Pout_<<std::endl;\n                \n                if (tmp_Pout_==Pout_)\n                {\n                    if (get_first_var(Pout_)==get_first_var(F))\n                    {\n                        auto cont_=cont(Pout_);\n                        // std::cout<<\"cont_:\"<<cont_<<std::endl;\n                        pair_vec_div(tmp.data(),tmp_Pout_.data(),cont_.data(),F.comp());\n                        std::swap(tmp,tmp_Pout_);\n                        \n                        // std::cout<<tmp_Pout_<<std::endl;\n                        \n                        pair_vec_div(tmp.data(),R.data(),F.data(),tmp_Pout_.data(),F.comp());\n                        if (R.empty())\n                        {\n                            pair_vec_div(tmp.data(),R.data(),G.data(),tmp_Pout_.data(),F.comp());\n                            if (R.empty())\n                            {\n                                pair_vec_multiplies(tmp.data(),tmp_Pout_.data(),cont_gcd.data(),F.comp());\n                                return tmp;\n                            }\n                        }\n                    }\n                    else\n                    {\n                        return cont_gcd;\n                    }\n                }\n                swap(tmp_Pout_.data(),Pout_.data());\n                       \n            }\n            prime=boost::math::prime(++p_index);\n        }  \n\n        \n    }\n\n    \n\n   \n    template<class var_order>\n    polynomial_<ZZ,lex_<var_order>> cont(const polynomial_<ZZ,lex_<var_order>> &F_)\n    {\n        // std::cout<<F_<<std::endl;\n        polynomial_<ZZ,lex_<var_order>>  cont(F_.comp_ptr()), tmp(F_.comp_ptr());\n        auto v=get_first_var(F_);\n        int64_t deg=get_first_deg(F_);\n        int64_t tmp_deg=deg;\n        basic_monomial<lex_<var_order>> m(F_.comp_ptr());\n        for (auto &i:F_)\n        {\n            if ((!i.first.empty() &&  i.first.front().first==v && i.first.front().second == tmp_deg) ||  \n                ((i.first.empty() || i.first.front().first!=v)  && tmp_deg==0))\n            {\n                m.clear();\n                m.reserve(i.first.size());\n                auto ptr=i.first.begin();\n                if (tmp_deg)\n                    ++ptr;\n                for (;ptr!=i.first.end();++ptr)\n                {\n                    m.push_back(*ptr);\n                }\n                tmp.push_back({std::move(m),i.second});\n            }\n            else{\n                if (tmp_deg==deg)\n                {\n                    cont=std::move(tmp);\n                    // std::cout<<\"c:\"<<cont<<std::endl;\n                }\n                else\n                {\n                    cont=polynomial_GCD(cont,tmp);\n                    // std::cout<<\"c:\"<<tmp<<std::endl;\n                    // std::cout<<\"c:\"<<cont<<std::endl;\n                }\n                tmp_deg=(!i.first.empty() && i.first.front().first==v )?i.first.front().second : 0;\n                tmp.clear();\n                m.clear();\n                m.reserve(i.first.size());\n                auto ptr=i.first.begin();\n                if (tmp_deg)\n                    ++ptr;\n                for (;ptr!=i.first.end();++ptr)\n                {\n                    m.push_back(*ptr);\n                }\n                tmp.push_back({std::move(m),i.second});\n            }\n        }\n        if (tmp_deg==deg)\n        {\n            cont=std::move(tmp);\n            // std::cout<<\"c:\"<<cont<<std::endl;\n        }\n        else\n        {\n            cont=polynomial_GCD(cont,tmp);\n            // std::cout<<\"c:\"<<tmp<<std::endl;\n            // std::cout<<\"c:\"<<cont<<std::endl;\n        }\n        return cont;\n    } \n    // polynomial_<ZZ,univariate_priority_order> cont(const polynomial_<ZZ,univariate_priority_order> &F_)\n    // {\n    //     auto & v_order=F_.comp();\n    //     polynomial_<ZZ,univariate_priority_order>  cont(&v_order),\n    //                                                cont_(&v_order),\n    //                                                tmp(&v_order);\n    //     int64_t deg=get_up_deg(F_);\n    //     int64_t tmp_deg=deg;\n    //     for (auto &i:F_)\n    //     {\n    //         if (get_up_deg(i.first)==tmp_deg)\n    //         {\n    //             tmp.push_back(i);\n    //             if (tmp_deg)\n    //                 tmp.back().first.pop_back();\n    //         }\n    //         else{\n    //             if (tmp_deg==deg)\n    //             {\n    //                 cont=std::move(tmp);\n                   \n    //             }\n    //             else\n    //             {\n    //                 cont=polynomial_GCD(cont,tmp);\n                    \n    //             }\n    //             tmp_deg=get_up_deg(i.first);\n    //             tmp.clear();\n    //             tmp.push_back(i);\n    //             if (tmp_deg)\n    //                 tmp.back().first.pop_back();\n    //         }\n    //     }\n    //     if (tmp_deg==deg)\n    //     {\n    //         cont=std::move(tmp);\n    //     }\n    //     else\n    //     {\n    //         cont=polynomial_GCD(cont,tmp);\n    //     }\n    //     return cont;\n    // } \n    \n    template<class var_order>\n    int64_t  __polynomial_GCD(       polynomial_<Zp,lex_<var_order>> & Pout,\n                            const polynomial_<Zp,lex_<var_order>> & F,\n                            const polynomial_<Zp,lex_<var_order>> & G,\n                            const polynomial_<Zp,lex_<var_order>> & Lc_gcd,\n                            int64_t deg)\n    {\n        int64_t deg_;\n        variable fvf,gvf;\n        assert(!F.empty() && !G.empty() && !Lc_gcd.empty());\n        fvf=get_first_var(F);\n        gvf=get_first_var(G);\n        assert(fvf==gvf);\n\n        if (!fvf.serial())\n        {\n            assert(Lc_gcd.size()==1 && Lc_gcd.begin()->first.empty());\n            Pout=Lc_gcd;\n            return 0;\n        }\n        auto flvd=get_last_var_deg(F);\n        auto glvd=get_last_var_deg(G);\n        polynomial_<Zp,lex_<var_order>> Pout_;\n        polynomial_<Zp,lex_<var_order>> Pout_1;\n        polynomial_<Zp,lex_<var_order>> Pout_2;\n        if (fvf==flvd.first && gvf==glvd.first)\n        {\n            Pout=G;\n            pair_vec_div(Pout_2.data(),Pout_1.data(),F.data(),Pout.data(),Pout.comp());\n            //std::cout<<Pout_1<<std::endl;\n            while(!Pout_1.empty())\n            {\n                swap(Pout.data(),Pout_.data());\n                swap(Pout.data(),Pout_1.data());\n                pair_vec_div(Pout_2.data(),Pout_1.data(),Pout_.data(),Pout.data(),Pout.comp());\n                //std::cout<<Pout_1<<std::endl;\n            }\n            assert(Lc_gcd.size()==1 && Lc_gcd.begin()->first.empty());\n            Zp lc_inv=Pout.front().second.inv()*Lc_gcd.begin()->second;\n            for (auto &i:Pout)\n                i.second*=lc_inv;\n            deg_=get_first_deg(Pout);\n            if (deg_<=deg)\n                return deg_;\n            else\n                return -1;\n        }\n        else\n        {\n            int64_t f_d=get_first_deg(F);\n            int64_t g_d=get_first_deg(G);\n            uint32_t prime=F.begin()->second.prime();\n            Zp p_(prime);\n            auto & comp=F.comp();\n            polynomial_<Zp,lex_<var_order>> F_v(F.comp_ptr());\n            polynomial_<Zp,lex_<var_order>> G_v(F.comp_ptr());\n            polynomial_<Zp,lex_<var_order>> lc_v(F.comp_ptr());\n            int64_t num_s=0;\n            int64_t v_d;\n            variable v;\n            if (flvd.first==glvd.first)\n            {\n                v=flvd.first;\n                v_d=std::max(flvd.second,glvd.second)+1;\n            }\n            else\n            {\n                v=comp(flvd.first,glvd.first)?glvd.first:flvd.first;\n                v_d=1;\n            }\n            std::vector<std::pair<basic_monomial<lex_<var_order>>,std::vector<Zp>>> _Pout,tmp_Pout;\n            std::vector<Zp> points;\n            std::vector<Zp> tmp_p;\n            points.reserve(v_d);\n            std::random_device rd; \n            std::mt19937 gen(rd());  \n            std::vector<int> v_bool(prime,1);  \n            uint32_t p_tmp;\n            for (int32_t i=0;i<prime;++i)\n            {\n                // p_.number()=i;\n                std::uniform_int_distribution<uint64_t> dis(1, prime-i);\n                p_tmp=dis(gen);\n                uint64_t j_tmp=0;\n                for (;p_tmp>0;p_tmp-=v_bool[j_tmp],++j_tmp);\n                v_bool[j_tmp-1]=0;p_.number()=j_tmp-1;\n\n                F_v=assign(F,v,p_);\n                G_v=assign(G,v,p_);\n                lc_v=assign(Lc_gcd,v,p_);\n                //std::cout<<v<<\"->\"<<p_<<std::endl;\n                //std::cout<<\"F_v:\"<<F_v<<std::endl;\n                //std::cout<<\"G_v:\"<<G_v<<std::endl;\n                //std::cout<<\"lc_v:\"<<Lc_gcd<<std::endl;\n\n                if (get_first_deg(F_v)==f_d && get_first_var(F_v)==fvf && get_first_deg(G_v)==g_d && get_first_var(G_v)==gvf )\n                {\n                    deg_=__polynomial_GCD(Pout_,F_v,G_v,lc_v,deg);\n                    //std::cout<<\"v:\"<<v<<\" deg:\"<<deg_<<\" GDD:\"<<Pout_<<std::endl;\n                    if (deg_!=-1 && deg_<=deg)\n                    {\n                        if (deg_<deg || !num_s)\n                        {\n                            deg=deg_;\n                            num_s=1;\n                            _Pout.clear();\n                            for (auto &i:Pout_)\n                            {\n                                _Pout.push_back({std::move(i.first),{i.second}});\n                            }\n                            points={p_};\n                        }\n                        else\n                        {\n                            ++num_s;\n                            tmp_Pout.clear();\n                            tmp_Pout.reserve(Pout_.size());\n                            points.push_back(p_);\n                            auto _P_ptr=_Pout.begin();\n                            auto _P_end=_Pout.end();\n                            auto P_ptr=Pout_.begin();\n                            auto P_end=Pout_.end();\n                            \n                            while (_P_ptr!=_P_end && P_ptr!=P_end)\n                            {\n                                if (comp(P_ptr->first,_P_ptr->first))\n                                {\n                                    tmp_p.clear();\n                                    tmp_p.resize(num_s,Zp(0,prime));\n                                    tmp_p.back()=P_ptr->second;\n                                    tmp_Pout.push_back({std::move(P_ptr->first),std::move(tmp_p)});\n                                    ++P_ptr;\n                                }\n                                else{\n                                    if (P_ptr->first==_P_ptr->first)\n                                    {\n                                        tmp_Pout.push_back(std::move(*_P_ptr));\n                                        tmp_Pout.back().second.push_back(P_ptr->second);\n                                        ++P_ptr;\n                                    }else\n                                    {\n                                        tmp_Pout.push_back(std::move(*_P_ptr));\n                                        tmp_Pout.back().second.push_back(Zp(0,prime));\n                                    }\n                                    ++_P_ptr;\n                                }\n                            }\n                            while (P_ptr!=P_end)\n                            {\n                                tmp_p.clear();\n                                tmp_p.resize(num_s,Zp(0,prime));\n                                tmp_p.back()=P_ptr->second;\n                                tmp_Pout.push_back({std::move(P_ptr->first),std::move(tmp_p)});\n                                ++P_ptr;\n                            }\n                            while (_P_ptr!=_P_end)\n                            {\n                                tmp_Pout.push_back(std::move(*_P_ptr));\n                                tmp_Pout.back().second.push_back(Zp(0,prime));\n                                ++_P_ptr;\n                            }  \n                            swap(tmp_Pout,_Pout);\n                            \n                        }\n                        if (num_s==v_d)\n                        {\n                            //std::cout<<std::endl;\n                            std::vector<Zp> lag;\n                            lag.resize(v_d*v_d);\n                            Zp tmp_inv;\n                            for (int64_t i=0;i<v_d;++i)\n                            {\n                                lag[i*v_d]=Zp(1,prime);\n                                for (int64_t j=1;j<v_d;++j)\n                                    lag[i*v_d+j]=Zp(0,prime);\n                                for (int64_t j=0;j<v_d;++j)\n                                    if (i!=j)\n                                    {\n                                        tmp_inv=(points[i]-points[j]).inv();\n                                        for (int64_t k=v_d-1;k>0;--k)\n                                        {\n                                            lag[i*v_d+k]=(lag[i*v_d+k-1]-lag[i*v_d+k]*points[j])*tmp_inv;\n                                        }\n                                        lag[i*v_d]=(-lag[i*v_d]*points[j])*tmp_inv;\n\n                                    }\n                                         \n                            }\n                            Pout.clear();\n                            Pout.reserve(_Pout.size());\n                            basic_monomial<lex_<var_order>> m(F.comp_ptr());\n                            for (auto &i:_Pout)\n                            {\n                                m=i.first;\n                                m.push_back({v,0});\n                                \n                                for (int64_t j=v_d-1;j>=0;--j)\n                                {\n                                    p_.number()=0;\n                                   \n                                    for (int64_t k=0;k<v_d;++k)\n                                    {\n                                        p_+=i.second[k]*lag[k*v_d+j];\n                                    }\n                                    if (p_)\n                                    {\n                                        if (j)\n                                        {\n                                            m.back().second=j;\n                                            m.deg()+=j;\n                                            Pout.push_back({m,p_});\n                                            m.deg()-=j;\n                                        }\n                                        else\n                                        {\n                                            Pout.push_back({std::move(i.first),p_});\n                                        }\n                                        \n                                    }  \n\n                                }\n\n                            }\n                            return deg;\n                        }\n                        \n                        \n                    }\n                    \n\n                }\n                if (prime<=i+v_d-num_s)\n                {\n                    return -1;\n                }\n            }\n            \n            return -1;\n\n        }\n\n    }\n    inline ZZ cont(const upolynomial_<ZZ> &G)\n    {\n        if (G.empty())\n            return 1;\n        auto ptr=G.begin();\n        ZZ c=(ptr++)->second;\n        for (;ptr!=G.end();++ptr)\n        {\n            c=gcd(c,ptr->second);\n        }\n        return c;\n\n    }\n\n    inline umonomial gcd(const umonomial & G,const umonomial& F)\n    {\n        return umonomial(std::min(G.deg(),F.deg()));\n    }\n    inline int64_t  __polynomial_GCD(upolynomial_<Zp> &Pout,\n                            const upolynomial_<Zp> &G,\n                            const upolynomial_<Zp> &F,\n                            const Zp & Lc_gcd,\n                            int64_t deg)\n    {\n        int64_t deg_;\n        assert(!F.empty() && !G.empty() );\n        upolynomial_<Zp> Pout_;\n        upolynomial_<Zp> Pout_1;\n        upolynomial_<Zp> Pout_2;\n        Pout=G;\n        pair_vec_div(Pout_2.data(),Pout_1.data(),F.data(),Pout.data(),Pout.comp());\n        //std::cout<<Pout_1<<std::endl;\n        while(!Pout_1.empty())\n        {\n            std::swap(Pout.data(),Pout_.data());\n            std::swap(Pout.data(),Pout_1.data());\n            pair_vec_div(Pout_2.data(),Pout_1.data(),Pout_.data(),Pout.data(),Pout.comp());\n            //std::cout<<Pout_1<<std::endl;\n        }\n        Zp lc_inv=Pout.front().second.inv()*Lc_gcd;\n        for (auto &i:Pout)\n            i.second*=lc_inv;\n        deg_=Pout.front().first.deg();\n        if (deg_<=deg)\n            return deg_;\n        else\n            return -1;\n    }\n    upolynomial_<ZZ>  polynomial_GCD(upolynomial_<ZZ> G,upolynomial_<ZZ> F);\n   \n}\n#endif", "meta": {"hexsha": "93311d2d1fadedfe05605f633a3f251c544bbcb4", "size": 31670, "ext": "hh", "lang": "C++", "max_stars_repo_path": "clpoly/polynomial_gcd.hh", "max_stars_repo_name": "lihaokun/CLPoly", "max_stars_repo_head_hexsha": "f75d043efbd5994d9e5f046b9a27f6aac4137e62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-15T14:15:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T08:47:00.000Z", "max_issues_repo_path": "clpoly/polynomial_gcd.hh", "max_issues_repo_name": "lihaokun/CLPoly", "max_issues_repo_head_hexsha": "f75d043efbd5994d9e5f046b9a27f6aac4137e62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clpoly/polynomial_gcd.hh", "max_forks_repo_name": "lihaokun/CLPoly", "max_forks_repo_head_hexsha": "f75d043efbd5994d9e5f046b9a27f6aac4137e62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-01T02:43:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T03:07:33.000Z", "avg_line_length": 36.4441887227, "max_line_length": 133, "alphanum_fraction": 0.3978844332, "num_tokens": 7179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6390603291536776}}
{"text": "#include <iostream>\r\n#define ARMA_DONT_USE_WRAPPER\r\n#include <armadillo>\r\n\r\nusing namespace std;\r\nusing namespace arma;\r\n\r\nint\r\nmain(int argc, char** argv)\r\n  {\r\n      \r\n      mat A(500,250, fill::randu);\r\n      cout << \"# Renglones: \" << A.n_rows << endl;\r\n      cout << \"# Columnas: \" << A.n_cols << endl;\r\n      cout << \"# Elementos: \" << A.n_elem << endl;\r\n      A.save(\"A.txt\", raw_ascii);\r\n      cout << \"Min = \" << min(min(A)) << endl;\r\n      cout << \"Max = \" << max(max(A)) << endl;\r\n      cout << \"Media = \" << mean(mean(A)) << endl;\r\n      cout << \"Mediana = \" << median(median(A)) << endl;\r\n      cout << \"Suma acumulada: \" << accu(A) << endl;\r\n      uvec q2 = find(A < 0.5);\r\n      q2.save(\"B.txt\", raw_ascii);\r\n      cout << \"Menores que 0.5: \" << q2.n_elem << endl;\r\n      uvec q3 = find(A > 0.5);\r\n      q3.save(\"C.txt\", raw_ascii);\r\n      cout << \"Mayores que 0.5: \" << q3.n_elem << endl;\r\n      \r\n      \r\n      return 0;\r\n      \r\n  }\r\n\r\n", "meta": {"hexsha": "91d7c941a081272a9f2e77501141010fc55e8959", "size": 954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "robotica/mat1.cpp", "max_stars_repo_name": "Jacobprojects/UACJ-Robotica", "max_stars_repo_head_hexsha": "62ef2adf02e615b8b1733045148401c98e28a663", "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": "robotica/mat1.cpp", "max_issues_repo_name": "Jacobprojects/UACJ-Robotica", "max_issues_repo_head_hexsha": "62ef2adf02e615b8b1733045148401c98e28a663", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "robotica/mat1.cpp", "max_forks_repo_name": "Jacobprojects/UACJ-Robotica", "max_forks_repo_head_hexsha": "62ef2adf02e615b8b1733045148401c98e28a663", "max_forks_repo_licenses": ["Apache-2.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.0588235294, "max_line_length": 57, "alphanum_fraction": 0.4842767296, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633915959134569, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6390603286435955}}
{"text": "//=======================================================================\r\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\r\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\r\n//          Doug Gregor, D. Kevin McGrath\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n\r\n#include <boost/config.hpp>\r\n#include <vector>\r\n#include <iostream>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/cuthill_mckee_ordering.hpp>\r\n#include <boost/graph/properties.hpp>\r\n#include <boost/graph/bandwidth.hpp>\r\n\r\n/*\r\n  Sample Output\r\n  original bandwidth: 8\r\n  Reverse Cuthill-McKee ordering starting at: 6\r\n    8 3 0 9 2 5 1 4 7 6 \r\n    bandwidth: 4\r\n  Reverse Cuthill-McKee ordering starting at: 0\r\n    9 1 4 6 7 2 8 5 3 0 \r\n    bandwidth: 4\r\n  Reverse Cuthill-McKee ordering:\r\n    0 8 5 7 3 6 4 2 1 9 \r\n    bandwidth: 4\r\n */\r\nint main(int , char* [])\r\n{\r\n  using namespace boost;\r\n  using namespace std;\r\n  typedef adjacency_list<vecS, vecS, undirectedS, \r\n     property<vertex_color_t, default_color_type,\r\n       property<vertex_degree_t,int> > > Graph;\r\n  typedef graph_traits<Graph>::vertex_descriptor Vertex;\r\n  typedef graph_traits<Graph>::vertices_size_type size_type;\r\n\r\n  typedef std::pair<std::size_t, std::size_t> Pair;\r\n  Pair edges[14] = { Pair(0,3), //a-d\r\n                     Pair(0,5),  //a-f\r\n                     Pair(1,2),  //b-c\r\n                     Pair(1,4),  //b-e\r\n                     Pair(1,6),  //b-g\r\n                     Pair(1,9),  //b-j\r\n                     Pair(2,3),  //c-d\r\n                     Pair(2,4),  //c-e\r\n                     Pair(3,5),  //d-f\r\n                     Pair(3,8),  //d-i\r\n                     Pair(4,6),  //e-g\r\n                     Pair(5,6),  //f-g\r\n                     Pair(5,7),  //f-h\r\n                     Pair(6,7) }; //g-h \r\n  \r\n  Graph G(10);\r\n  for (int i = 0; i < 14; ++i)\r\n    add_edge(edges[i].first, edges[i].second, G);\r\n\r\n  graph_traits<Graph>::vertex_iterator ui, ui_end;\r\n\r\n  property_map<Graph,vertex_degree_t>::type deg = get(vertex_degree, G);\r\n  for (boost::tie(ui, ui_end) = vertices(G); ui != ui_end; ++ui)\r\n    deg[*ui] = degree(*ui, G);\r\n\r\n  property_map<Graph, vertex_index_t>::type\r\n    index_map = get(vertex_index, G);\r\n\r\n  std::cout << \"original bandwidth: \" << bandwidth(G) << std::endl;\r\n\r\n  std::vector<Vertex> inv_perm(num_vertices(G));\r\n  std::vector<size_type> perm(num_vertices(G));\r\n  {\r\n    Vertex s = vertex(6, G);\r\n    //reverse cuthill_mckee_ordering\r\n    cuthill_mckee_ordering(G, s, inv_perm.rbegin(), get(vertex_color, G), \r\n                           get(vertex_degree, G));\r\n    cout << \"Reverse Cuthill-McKee ordering starting at: \" << s << endl;\r\n    cout << \"  \";    \r\n    for (std::vector<Vertex>::const_iterator i = inv_perm.begin();\r\n         i != inv_perm.end(); ++i)\r\n      cout << index_map[*i] << \" \";\r\n    cout << endl;\r\n\r\n    for (size_type c = 0; c != inv_perm.size(); ++c)\r\n      perm[index_map[inv_perm[c]]] = c;\r\n    std::cout << \"  bandwidth: \" \r\n              << bandwidth(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\r\n              << std::endl;\r\n  }\r\n  {\r\n    Vertex s = vertex(0, G);\r\n    //reverse cuthill_mckee_ordering\r\n    cuthill_mckee_ordering(G, s, inv_perm.rbegin(), get(vertex_color, G),\r\n                           get(vertex_degree, G));\r\n    cout << \"Reverse Cuthill-McKee ordering starting at: \" << s << endl;\r\n    cout << \"  \";\r\n    for (std::vector<Vertex>::const_iterator i=inv_perm.begin();\r\n       i != inv_perm.end(); ++i)\r\n      cout << index_map[*i] << \" \";\r\n    cout << endl;\r\n\r\n    for (size_type c = 0; c != inv_perm.size(); ++c)\r\n      perm[index_map[inv_perm[c]]] = c;\r\n    std::cout << \"  bandwidth: \" \r\n              << bandwidth(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\r\n              << std::endl;\r\n  }\r\n\r\n  {\r\n    //reverse cuthill_mckee_ordering\r\n    cuthill_mckee_ordering(G, inv_perm.rbegin());\r\n    \r\n    cout << \"Reverse Cuthill-McKee ordering:\" << endl;\r\n    cout << \"  \";\r\n    for (std::vector<Vertex>::const_iterator i=inv_perm.begin();\r\n       i != inv_perm.end(); ++i)\r\n      cout << index_map[*i] << \" \";\r\n    cout << endl;\r\n\r\n    for (size_type c = 0; c != inv_perm.size(); ++c)\r\n      perm[index_map[inv_perm[c]]] = c;\r\n    std::cout << \"  bandwidth: \" \r\n              << bandwidth(G, make_iterator_property_map(&perm[0], index_map, perm[0]))\r\n              << std::endl;\r\n  }\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "142b48ad056cff007db8233537fbb57c2708a634", "size": 4616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/test/cuthill_mckee_ordering.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/graph/test/cuthill_mckee_ordering.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/graph/test/cuthill_mckee_ordering.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 35.2366412214, "max_line_length": 88, "alphanum_fraction": 0.5348786828, "num_tokens": 1313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.7956581073313276, "lm_q1q2_score": 0.6390517501646483}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright Christopher Kormanyos 2016.\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// Test the fixed_point::negatable class.\n\n#include <iomanip>\n#include <iostream>\n#include <boost/fixed_point/fixed_point.hpp>\n\ntypedef boost::fixed_point::negatable<2, -2, boost::fixed_point::round::fastest>      fixed_point_type_round_fastest;\ntypedef boost::fixed_point::negatable<2, -2, boost::fixed_point::round::nearest_even> fixed_point_type_round_nearest_even;\n\nint main()\n{\n  fixed_point_type_round_fastest      x;\n  fixed_point_type_round_nearest_even y;\n\n  for(float input = 1.0F; input < 2.125F; input += 0.125F)\n  {\n    y = input;\n    x = input;\n\n    std::cout << \"Input: \"\n              << std::setprecision(3)\n              << std::fixed\n              << input\n              << 'F'\n              << \" : fastest \"\n              << std::setprecision(2)\n              << x\n              << \" : nearest_even \"\n              << y\n              << std::endl;\n\n  }\n}\n\n// The output of the program is:\n// \n// Input: 1.000F : fastest 1.00 : nearest_even 1.00\n// Input: 1.125F : fastest 1.00 : nearest_even 1.00\n// Input: 1.250F : fastest 1.25 : nearest_even 1.25\n// Input: 1.375F : fastest 1.25 : nearest_even 1.50\n// Input: 1.500F : fastest 1.50 : nearest_even 1.50\n// Input: 1.625F : fastest 1.50 : nearest_even 1.50\n// Input: 1.750F : fastest 1.75 : nearest_even 1.75\n// Input: 1.875F : fastest 1.75 : nearest_even 2.00\n// Input: 2.000F : fastest 2.00 : nearest_even 2.00\n", "meta": {"hexsha": "e97309b124f2c980ced69a9b2da43c96cbdc383e", "size": 1666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_rounding_simple.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_rounding_simple.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_rounding_simple.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.4339622642, "max_line_length": 122, "alphanum_fraction": 0.593637455, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6390517407215806}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <boost/numeric/odeint.hpp>\n#include <smooth/compat/odeint.hpp>\n#include <smooth/feedback/asif.hpp>\n\n#include <chrono>\n\n#ifdef ENABLE_PLOTTING\n#include <matplot/matplot.h>\n#endif\n\nusing namespace std::chrono_literals;\nusing namespace boost::numeric::odeint;\n\nusing Time = std::chrono::duration<double>;\n\ntemplate<typename T>\nusing G = Eigen::Matrix<T, 2, 1>;\ntemplate<typename T>\nusing U = Eigen::Matrix<T, 1, 1>;\n\nusing Gd = G<double>;\nusing Ud = U<double>;\n\nint main()\n{\n  // dynamics\n  auto f = []<typename T>(Time, const G<T> & x, const U<T> & u) -> smooth::Tangent<G<T>> {\n    return {x(1), u(0)};\n  };\n\n  // safety set\n  auto h = []<typename T>(T, const G<T> & g) -> Eigen::Vector2<T> {\n    return {T(3) - g(0), T(1.5) - g(1)};\n  };\n\n  // backup controller\n  auto bu = []<typename T>(T, const G<T> &) -> U<T> { return U<T>(-0.6); };\n\n  // parameters\n  smooth::feedback::ASIFilterParams<Ud> prm{\n    .T  = 0.5,\n    .nh = 2,\n    .ulim =\n      {\n        .A = U<double>{{1.}},\n        .l = U<double>{{-1.}},\n        .u = U<double>{{1.}},\n      },\n    .asif =\n      {\n        .K          = 50,\n        .alpha      = 1,\n        .dt         = 0.01,\n        .relax_cost = 100,\n      },\n    .qp =\n      {\n        .polish = false,\n      },\n  };\n\n  // create filter\n  smooth::feedback::ASIFilter<Time, Gd, Ud, decltype(f)> asif(f, prm);\n\n  // system variables\n  Gd g(-5, 1);\n  Ud udes = Ud(1), u;\n\n  // prepare for integrating the closed-loop system\n  runge_kutta4<Gd, double, smooth::Tangent<Gd>, double, vector_space_algebra> stepper{};\n  const auto ode = [&f, &u](const Gd & x, smooth::Tangent<Gd> & d, double t) {\n    d = f(Time(t), x, u);\n  };\n  std::vector<double> tvec, xvec, vvec, uvec;\n\n  // integrate closed-loop system\n  for (std::chrono::milliseconds t = 0s; t < 10s; t += 50ms) {\n    auto [u_asif, code] = asif(t, g, udes, h, bu);\n\n    u = u_asif;\n\n    if (code != smooth::feedback::QPSolutionStatus::Optimal) {\n      std::cerr << \"Solver failed with code \" << static_cast<int>(code) << std::endl;\n    }\n\n    // store data\n    tvec.push_back(duration_cast<Time>(t).count());\n    xvec.push_back(g.x());\n    vvec.push_back(g.y());\n    uvec.push_back(u.x());\n\n    // step dynamics\n    stepper.do_step(ode, g, 0, 0.05);\n  }\n\n#ifdef ENABLE_PLOTTING\n  using namespace matplot;\n\n  figure();\n  hold(on);\n\n  plot(tvec, xvec)->line_width(2);\n  plot(tvec, vvec)->line_width(2);\n  plot(tvec, transform(tvec, [&](auto) { return 3; }), \"--\")->line_width(2);\n  plot(tvec, transform(tvec, [&](auto) { return 1.5; }), \"--\")->line_width(2);\n  legend({\"x\", \"v\", \"x_{max}\", \"v_{max}\"});\n\n  figure();\n  hold(on);\n  title(\"Input\");\n  plot(tvec, uvec)->line_width(2);\n  plot(tvec, transform(tvec, [](auto) { return 1; }), \"--\")->line_width(2);\n\n  show();\n#else\n  std::cout << \"TRAJECTORY:\" << std::endl;\n  for (auto i = 0u; i != tvec.size(); ++i) {\n    std::cout << \"t=\" << tvec[i] << \": x=\" << xvec[i] << \", v=\" << vvec[i] << std::endl;\n  }\n#endif\n}\n", "meta": {"hexsha": "b7ded971ad2408bb9117340c256d13c0e925f566", "size": 4229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/asif_doubleintegrator.cpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "examples/asif_doubleintegrator.cpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "examples/asif_doubleintegrator.cpp", "max_forks_repo_name": "pettni/smooth_feedback", "max_forks_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 28.768707483, "max_line_length": 90, "alphanum_fraction": 0.6174036415, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6390016659485518}}
{"text": "#include <iostream>\n\n#include <Eigen/Dense>\n#include <fstream>\n#include <vector>\n#include <iomanip>      // std::setprecision\n\nusing Eigen::MatrixXd;\nint main() {\n\n    Eigen::Matrix<double, 2, 1> xi;\n    Eigen::Matrix<double, 2, 1> particle_size;\n\n    //! Dimension\n    const unsigned Dim = 2;\n    //! Nodes in GIMP function\n    // 16 for 2D 4 for 1D\n    const unsigned Nfunctions = 4;\n\n    //! To store shape functions\n    Eigen::Matrix<double, 16, 1> shapefn;\n\n    //! To store grad shape functions\n    Eigen::Matrix<double, 16, 2> grad_shapefn;\n\n    //! length of element in local coordinate\n    // Keep this value constant\n    const double element_length = 2.;\n\n    // Local coordinates of 2D GIMP cells\n    /*const Eigen::Matrix<double, Nfunctions, Dim> local_nodes =\n            (Eigen::Matrix<double, Nfunctions, Dim>() << -1., -1.,\n\n                    1., -1.,\n                    1.,  1.,\n                    -1.,  1.,\n                    -3., -3.,\n                    -1., -3.,\n                    1., -3.,\n                    3., -3.,\n                    3., -1.,\n                    3.,  1.,\n                    3.,  3.,\n                    1.,  3.,\n                    -1.,  3.,\n                    -3.,  3.,\n                    -3.,  1.,\n                    -3., -1.).finished();*/\n\n    // Local coordinates of 1D GIMP cells\n    const Eigen::Matrix<double, Nfunctions, Dim> local_nodes =\n            (Eigen::Matrix<double, Nfunctions, Dim>() << \n\n\t\t-3.,0.,\n\t\t-1.,0.,\n\t\t 1.,0.,\n\t\t 3.,0.\n\t\t).finished();\n\n\n    // particle location\n    xi << -4.0, 0.0;\n    // particle size\n    particle_size << 1.1, 1.1;\n\n    double interval = 0.05;\n\n    std::vector<double> function_store;\n    std::vector<double> gfunction_store;\n\n    \n    for (unsigned k = 0; k < 120; ++k) {\n\t\n\txi(0) += interval;\n\n\t//Function loop\n        for (unsigned n = 0; n < Nfunctions; ++n) {\n            Eigen::Matrix<double, 2, 1> sni;\n            Eigen::Matrix<double, 2, 1> dni;\n\n\t\t// GIMP conditional statement loop\n            for (unsigned i = 0; i < Dim; ++i) {\n\t\t//length of particle\n                double lp = particle_size(i) * 0.5;\n\t\t// active node\n                double ni = local_nodes(n, i);\n\t\t// local particle  - local node\n                double npni = xi(i) - ni;  \n                //! Conditional shape function statement\n                // see: Pruijn, N.S., 2016. Eq(4.30)\n                if (npni <= (-element_length - lp)) {\n                    sni(i) = 0.;\n                    dni(i) = 0.;\n                } else if ((-element_length - lp) < npni &&\n                           npni <= (-element_length + lp)) {\n\n                    sni(i) = std::pow(element_length + lp + npni, 2.) /\n                             (4. * (element_length * lp));\n                    dni(i) = (element_length + lp + npni) / (2. * element_length * lp);\n                } else if ((-element_length + lp) < npni && npni <= -lp) {\n                    sni(i) = 1. + (npni / element_length);\n                    dni(i) = 1. / element_length;\n                } else if (-lp < npni && npni <= lp) {\n                    sni(i) =\n                            1. - (((npni * npni) + (lp * lp)) / (2. * element_length * lp));\n                    dni(i) = -(npni / (element_length * lp));\n                } else if (lp < npni && npni <= (element_length - lp)) {\n                    sni(i) = 1. - (npni / element_length);\n                    dni(i) = -(1. / element_length);\n                } else if ((element_length - lp) < npni &&\n                           npni <= (element_length + lp)) {\n                    sni(i) = std::pow(element_length + lp - npni, 2.) /\n                             (4. * element_length * lp);\n                    dni(i) = -((element_length + lp - npni) / (2. * element_length * lp));\n                } else if ((element_length + lp) < npni) {\n                    sni(i) = 0.;\n                    dni(i) = 0.;\n                } else {\n                    throw std::runtime_error(\n                            \"GIMP grad shapefn: Point location outside area of influence\");\n                }\n            }\n            // 2D Shape\n            //shapefn(n) = sni(0) * sni(1);\n\n            // 1D Shape value @ node n\n\t    shapefn(n) = sni(0);\n\t\t\n\t    // store 1D shape function value at specific node (n)\n\t    if (n == 1 )\n\t    function_store.push_back(shapefn(n));\n           \n\n            // 2D Grad\n            //grad_shapefn(n, 0) = dni(0) * sni(1);\n            //grad_shapefn(n, 1) = dni(1) * sni(0);\n            \n            // 1D Grad\n            grad_shapefn(n, 0) = dni(0);\n\t    \n\t    // store 1D grad function value at specific node (n)\n\t    if (n == 1 )\n\t    gfunction_store.push_back(grad_shapefn(n,0));\n        }\n    }\n    std::cout << \"function store size: \" << function_store.size() << '\\n';\n    for (unsigned n = 0; n < Nfunctions; ++n) {\n        std::cout << n << \" \"\n                  << \" s(\" << local_nodes(n, 0) << \" , \" << local_nodes(n, 1)\n                  << \") : \" << shapefn(n) << '\\n';\n        //std::cout << n << \" \" << std::setprecision(9) << grad_shapefn(n,1) << '\\n';\n    }\n\n    //! Output file\n    std::string xvalfilename = \"snvals.txt\";\n    std::fstream xvalfile;\n    xvalfile.open(xvalfilename, std::ios::out);\n\n    if (xvalfile.is_open()) {\n        //! Write\n\t//function_store for shape function, gfunction_store for gradient\n        for (auto const& xvals : gfunction_store) {\n            xvalfile << xvals << '\\n';\n        }\n        xvalfile.close();\n    }\n}\n", "meta": {"hexsha": "8f4533f3e3ab5284cf998b8d87f4e0708fc53889", "size": 5488, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "cw646/GIMP_shape_function", "max_stars_repo_head_hexsha": "1e5ec2e9337b73956ee0c7dad405bb05993eb608", "max_stars_repo_licenses": ["MIT"], "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": "cw646/GIMP_shape_function", "max_issues_repo_head_hexsha": "1e5ec2e9337b73956ee0c7dad405bb05993eb608", "max_issues_repo_licenses": ["MIT"], "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": "cw646/GIMP_shape_function", "max_forks_repo_head_hexsha": "1e5ec2e9337b73956ee0c7dad405bb05993eb608", "max_forks_repo_licenses": ["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.6666666667, "max_line_length": 92, "alphanum_fraction": 0.444606414, "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.950410972802222, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.6389914242627561}}
{"text": "/**\n * @file mpc.h\n * @brief Finite-horizon Model Predictive Controller.\n * \n */\n\n#ifndef MPC_H\n#define MPC_H\n\n#include <Eigen/Dense>\n\nnamespace controller\n{\n\nclass MPC\n{\n    public:\n        MPC(const Eigen::MatrixXd& Q, const Eigen::MatrixXd& R, const double S);\n        ~MPC() {};\n\n        /**\n         * @brief An MPC based on the following problem statement:\n         * \n         *        min(U) with penalties on the current state, final state, and input signal (Q, P, and R, respectively).\n         * \n         *        s.t. x0 = x(t)\n         *             x(k + 1) = Ax(k) + Bu(k), k = 0, ... , N-1\n         *             u_min <= u <= u_max\n         *             y\u02d9 cos \u03b8 \u2212 x\u02d9 sin \u03b8 = 0 non-holonomic constraint\n         *             u(k) \u2208 U if sensor is in range.\n         *             x(k) \u2208 X if sensor is in range.\n         * \n         * @param A System dynamics matrix.\n         * @param B Input matrix.\n         * @param E State error.\n         * @param numIteration The length of online receding time window to search for a stable solution.\n         * @param tolarance The tolarance of the Riccati convergence.\n         * @param dt Timestamp.\n         * @return Eigen::MatrixXd cmd_vel\n         */\n        Eigen::MatrixXd computeDiscrete(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B, const Eigen::MatrixXd& E, const unsigned int numIteration, const double tolarance, const double dt);\n\n    private:\n        // Declare generic MAT for MPC computations.\n        Eigen::MatrixXd K;\n        Eigen::MatrixXd Q;\n        Eigen::MatrixXd R;\n        Eigen::MatrixXd I;\n        Eigen::MatrixXd P;\n        Eigen::MatrixXd P_new;\n\n        // Discrete MAT.\n        Eigen::MatrixXd Ad;\n        Eigen::MatrixXd Bd;\n\n        // Output.\n        Eigen::MatrixXd cmd_vel;\n        Eigen::MatrixXd controlUpdate;\n\n        // Flags.\n        double difference;\n        double saturation;\n        bool converged;\n};\n\n} // namespace controller\n\n#endif /* MPC_H */", "meta": {"hexsha": "fd6f967bdaca33eab704e0593da9c21a2a095b1b", "size": 1964, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/control_system/include/mpc.hpp", "max_stars_repo_name": "duckstarr/controller", "max_stars_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-05-15T21:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T04:34:54.000Z", "max_issues_repo_path": "src/control_system/include/mpc.hpp", "max_issues_repo_name": "duckstarr/controller", "max_issues_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/control_system/include/mpc.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": 28.8823529412, "max_line_length": 192, "alphanum_fraction": 0.549389002, "num_tokens": 470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897525789547, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6389643542448356}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n  Eigen::MatrixXf m(3,3);\n  m << 1,2,3,\n       4,5,6,\n       7,8,9;\n  cout << \"Here is the matrix m:\" << endl << m << endl;\n  cout << \"2nd Row: \" << m.row(1) << endl;\n  m.col(2) += 3 * m.col(0);\n  cout << \"After adding 3 times the first column into the third column, the matrix m is:\\n\";\n  cout << m << endl;\n}\n", "meta": {"hexsha": "2e7eb009b77010c5bc3aaf6fe2b0c5dbae143b7a", "size": 390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_BlockOperations_colrow.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_BlockOperations_colrow.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_BlockOperations_colrow.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": 21.6666666667, "max_line_length": 92, "alphanum_fraction": 0.5538461538, "num_tokens": 138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8056322076481139, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6389516944115863}}
{"text": "// Author: Diego Vergara\n#ifndef C_UTILS_H\n#define C_UTILS_H\n\n#include <iostream>\n#include <iomanip>  \n#include <cstdlib>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <opencv2/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <string>\n#include <fstream>\n#include <vector>\n#include <map>\n#include <set>\n#include <chrono>\n#include <random>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace cv;\n\ntypedef struct{\n  double precision;\n  double accuracy;\n  double recall;\n  double f1score;\n  double support;\n}Metrics;\n\nclass C_utils\n{\npublic:\n\tC_utils();\n\tdouble unif(double min, double max);\n\tVectorXd random_generator(int dimension);\n\tdouble random_uniform();\n\tVectorXd random_binomial(int n, VectorXd prob, int dim);\n    void writeToCSVfile(string name, MatrixXd matrix, bool append = false);\n    static void calculateAccuracyPercent(VectorXd labels,VectorXd predicted);\n    void printProgBar( int value, int max );\n    void dataPermutation(MatrixXd& X_train,VectorXd& Y_train);\n    void dataNormalization(MatrixXd& data,RowVectorXd& mean, RowVectorXd& std);\n    void dataStandardization(MatrixXd& data,RowVectorXd& max, RowVectorXd& min);\n    void testNormalization(MatrixXd& data,RowVectorXd mean, RowVectorXd std);\n    void testStandardization(MatrixXd& data,RowVectorXd max, RowVectorXd min);\n    void dataPartition(MatrixXd& data,VectorXd& labels, MatrixXd& X_train, MatrixXd& X_test, VectorXd& Y_train, VectorXd& Y_test, int partition);\n    VectorXi argMin(MatrixXd data, bool row = true);\n    VectorXi argMax(MatrixXd data, bool row = true);\n    VectorXd matrixDot(MatrixXd &A, VectorXd &x);\n    VectorXd sign(VectorXd &x);\n    VectorXd vecMax(double value, VectorXd &vec);\n    void read_Labels(const string& filename, VectorXi& labels);\n    void read_Labels(const string& filename, VectorXd& labels);\n\tvoid read_Labels(const string& filename, VectorXi& labels,int rows);\n\tvoid read_Labels(const string& filename, VectorXd& labels, int rows);\n\tvoid read_Data(const string& filename, MatrixXd& data);\n\tvoid read_Data(const string& filename, MatrixXd& data,int rows, int cols);\n\tvoid print(VectorXi &test, VectorXi &predicted);\n\tvoid classification_Report(VectorXi &test, VectorXd &predicted);\n\tvoid classification_Report(VectorXd &test, VectorXi &predicted);\n\tvoid classification_Report(VectorXi &test, VectorXi &predicted);\n\tint get_Rows(const string& filename);\n\tint get_Cols(const string& filename, char separator);\n\tvector<int> get_Classes(VectorXi labels);\n\tvector<int> get_Classes_d(VectorXd labels);\n\t\n\tmap<pair<int,int>, int> confusion_matrix(VectorXi &test, VectorXi &predicted, bool print=true);\n\tmap<pair<int,int>, int> confusion_matrix(VectorXi &test, VectorXd &predicted, bool print=true);\n\tmap<pair<int,int>, int> confusion_matrix(VectorXd &test, VectorXd &predicted, bool print=true);\n\t\n\tmap<int, double> precision_score(VectorXi &test, VectorXi &predicted, bool print=true);\n\tmap<int, double> precision_score(VectorXi &test, VectorXd &predicted, bool print=true);\n\tmap<int, double> precision_score(VectorXd &test, VectorXd &predicted, bool print=true);\n\tmap<int, double> precision_score(map<pair<int,int>, int> confusion_matrix, bool print=false);\n\n\tmap<int, double> accuracy_score(VectorXi &test, VectorXi &predicted, bool print=true);\n\tmap<int, double> accuracy_score(VectorXi &test, VectorXd &predicted, bool print=true);\n\tmap<int, double> accuracy_score(VectorXd &test, VectorXd &predicted, bool print=true);\n\tmap<int, double> accuracy_score(map<pair<int,int>, int> confusionMatrix, bool print=false);\n\t\n\tmap<int, double> recall_score(VectorXi &test, VectorXi &predicted, bool print=true);\n\tmap<int, double> recall_score(VectorXi &test, VectorXd &predicted, bool print=true);\n\tmap<int, double> recall_score(VectorXd &test, VectorXd &predicted, bool print=true);\n\tmap<int, double> recall_score(map<pair<int,int>, int> confusionMatrix, bool print=false);\n\n\tmap<int, double> f1_score(VectorXi &test, VectorXi &predicted, bool print=true);\n\tmap<int, double> f1_score(VectorXi &test, VectorXd &predicted, bool print=true);\n\tmap<int, double> f1_score(VectorXd &test, VectorXd &predicted, bool print=true);\n\tmap<int, double> f1_score(map<pair<int, int>, int> confusionMatrix, bool print=false);\n\n\tmap<int, double> support_score(VectorXi &test);\n\tmap<int, double> support_score(VectorXd &test);\n\tmap<int, double> support_score(map<pair<int, int>, int> confusionMatrix);\n\n\tmap<int, Metrics> report(VectorXi &test, VectorXi &predicted, bool print=true);\n\tmap<int, Metrics> report(VectorXi &test, VectorXd &predicted, bool print=true);\n\tmap<int, Metrics> report(VectorXd &test, VectorXd &predicted, bool print=true);\n\tmap<int, Metrics> report(map<pair<int, int>, int> confusionMatrix, bool print=true);\nprivate:\n\tbool initialized;\n};\n\n#endif\n", "meta": {"hexsha": "61af7115cb5228bc583e841ce5fe6b4e45058a42", "size": 4776, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/c_utils.hpp", "max_stars_repo_name": "fjorquerauribe/multitarget-tracking", "max_stars_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T13:55:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T20:49:10.000Z", "max_issues_repo_path": "src/utils/c_utils.hpp", "max_issues_repo_name": "fjorquerauribe/multitarget-tracking", "max_issues_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/c_utils.hpp", "max_forks_repo_name": "fjorquerauribe/multitarget-tracking", "max_forks_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-06-01T07:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T05:21:04.000Z", "avg_line_length": 45.0566037736, "max_line_length": 145, "alphanum_fraction": 0.759840871, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6388746153389105}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/zeta.hpp>\n\nTEST(AgradRev,digamma) {\n  AVAR a = 0.5;\n  AVAR f = digamma(a);\n  EXPECT_FLOAT_EQ(boost::math::digamma(0.5),f.val());\n\n  AVEC x = createAVEC(a);\n  VEC grad_f;\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(4.9348022005446793094, grad_f[0]);\n}  \n\nstruct digamma_fun {\n  template <typename T0>\n  inline T0\n  operator()(const T0& arg1) const {\n    return digamma(arg1);\n  }\n};\n\nTEST(AgradRev,digamma_NaN) {\n  digamma_fun digamma_;\n  test_nan(digamma_,false,true);\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a = 0.5;\n  test::check_varis_on_stack(stan::math::digamma(a));\n}\n", "meta": {"hexsha": "2f9ca0518637bb430e6d7c00298d8942aec76acb", "size": 823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/digamma_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/digamma_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/digamma_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8611111111, "max_line_length": 53, "alphanum_fraction": 0.7095990279, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6388745984506349}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_FFT_ALGORITHMS_HPP\n  #define BOOST_MATH_FFT_ALGORITHMS_HPP\n\n  #include <algorithm>\n  #include <numeric>\n  #include <cmath>\n  #include <vector>\n  #include <boost/math/constants/constants.hpp>\n  #include <boost/math/fft/discrete_maths.hpp>\n  #include <boost/container/static_vector.hpp>\n  \n\n\n  namespace boost { namespace math {  namespace fft {\n  \n  namespace detail {\n  \n  template<typename InputIterator1,\n           typename InputIterator2,\n           typename OutputIterator,\n           typename allocator_t >\n  void raw_convolution(InputIterator1 input1_begin,\n                   InputIterator1 input1_end,\n                   InputIterator2 input2_begin,\n                   OutputIterator output,\n                   const allocator_t& alloc);\n  \n  \n  template<class ComplexType>\n  ComplexType complex_root_of_unity(long n,long p=1)\n  /*\n    Computes exp(-i 2 pi p/n)\n  */\n  {\n    using real_value_type = typename ComplexType::value_type;\n    p = modulo(p,n);\n    \n    if(p==0)\n      return ComplexType(1,0);\n    \n    long g = gcd(p,n); \n    n/=g;\n    p/=g;\n    switch(n)\n    {\n      case 1:\n        return ComplexType(1,0);\n      case 2:\n        return p==0 ? ComplexType(1,0) : ComplexType(-1,0);\n      case 4:\n        return p==0 ? ComplexType(1,0) : \n               p==1 ? ComplexType(0,-1) :\n               p==2 ? ComplexType(-1,0) :\n                      ComplexType(0,1) ;\n    }\n    using std::sin;\n    using std::cos;\n    real_value_type phase = -2*p*boost::math::constants::pi<real_value_type>()/n;\n    return ComplexType(cos(phase),sin(phase));\n  }\n  template<class ComplexType>\n  ComplexType complex_inverse_root_of_unity(long n,long p=1)\n  /*\n    Computes exp(i 2 pi p/n)\n  */\n  {\n    return complex_root_of_unity<ComplexType>(n,-p);\n  }\n  \n  template<class complex_value_type>\n  inline void complex_dft_2(\n    const complex_value_type* in, \n    complex_value_type* out, int)\n  {\n    complex_value_type \n        o1 = in[0]+in[1], o2 = in[0]-in[1] ;\n    out[0] = o1;\n    out[1] = o2;\n  }\n  \n  template<class T>\n  void dft_prime_bruteForce_outofplace(const T* in_first, const T* in_last, T* out, const T w)\n  /*\n    assumptions: \n    - allocated memory in out is enough to hold distance(in_first,in_last) element,\n    - out!=in\n  */\n  {\n    const long N = static_cast<long>(std::distance(in_first,in_last));\n    if(N<=0)\n      return;\n    \n    out[0] = std::accumulate(in_first+1,in_last,in_first[0]);\n    \n    T wi=w;\n    for(long i=1;i<N;++i, wi*=w)\n    {\n      T wij{wi};\n      T sum{in_first[0]};\n      for(long j=1;j<N; ++j, wij*=wi)\n      {\n        sum += in_first[j]*wij;\n      }\n      out[i] = sum;\n    }\n  }\n  template<class T,class allocator_t>\n  void dft_prime_bruteForce_inplace(\n    T* in_first, \n    T* in_last, \n    const T w, \n    const allocator_t& alloc)\n  {\n    std::vector<T,allocator_t> work_space(in_first,in_last,alloc);\n    dft_prime_bruteForce_outofplace(in_first,in_last,work_space.data(),w);\n    std::copy(work_space.begin(),work_space.end(),in_first);\n  }\n  template<class T, class allocator_t>\n  void dft_prime_bruteForce(\n    const T* in_first, \n    const T* in_last, \n    T* out, \n    const T w, \n    const allocator_t& alloc)\n  {\n    if(in_first==out)\n      dft_prime_bruteForce_inplace(out,out+std::distance(in_first,in_last),w,alloc);\n    else\n      dft_prime_bruteForce_outofplace(in_first,in_last,out,w);\n  }\n  \n  template<class complex_value_type>\n  void complex_dft_prime_bruteForce_outofplace(\n    const complex_value_type* in_first, \n    const complex_value_type* in_last, \n    complex_value_type* out, int sign)\n  /*\n    assumptions: \n    - allocated memory in out is enough to hold distance(in_first,in_last) element,\n    - out!=in\n  */\n  {\n    const long N = static_cast<long>(std::distance(in_first,in_last));\n    if(N<=0)\n      return;\n    \n    out[0] = std::accumulate(in_first+1,in_last,in_first[0]);\n    \n    for(long i=1;i<N;++i)\n    {\n      complex_value_type sum{in_first[0]};\n      for(long j=1;j<N; ++j)\n      {\n        sum += in_first[j] * complex_root_of_unity<complex_value_type>(N,i*j*sign);\n      }\n      out[i] = sum;\n    }\n  }\n  \n  template<class complex_value_type,class Allocator_t>\n  void complex_dft_prime_bruteForce_inplace(\n    complex_value_type* in_first, \n    complex_value_type* in_last, \n    int sign,\n    const Allocator_t& alloc)\n  {\n    std::vector<complex_value_type,Allocator_t> work_space(in_first,in_last,alloc);\n    complex_dft_prime_bruteForce_outofplace(in_first,in_last,work_space.data(),sign);\n    std::copy(work_space.begin(),work_space.end(),in_first);\n  }\n  template<class complex_value_type, class Allocator_t>\n  void complex_dft_prime_bruteForce(\n    const complex_value_type* in_first, \n    const complex_value_type* in_last, \n    complex_value_type* out, \n    int sign,\n    const Allocator_t& alloc)\n  {\n    if(in_first==out)\n      complex_dft_prime_bruteForce_inplace(out,out+std::distance(in_first,in_last),sign,alloc);\n    else\n      complex_dft_prime_bruteForce_outofplace(in_first,in_last,out,sign);\n  }\n  \n  /*\n    Rader's FFT on prime sizes\n  */\n  template<class complex_value_type, class allocator_t>\n  void complex_dft_prime_rader(\n    const complex_value_type *in_first, \n    const complex_value_type *in_last, \n    complex_value_type* out, \n    int sign,\n    const allocator_t& alloc = allocator_t{})\n  // precondition: distance(in_first,in_last) is prime > 2\n  {\n    using allocator_type = allocator_t;\n    const long my_n = static_cast<long>(std::distance(in_first,in_last));\n\n    std::vector<complex_value_type,allocator_type> A(my_n-1,complex_value_type(),alloc);\n    std::vector<complex_value_type,allocator_type> W(my_n-1,complex_value_type(),alloc);\n    std::vector<complex_value_type,allocator_type> B(my_n-1,complex_value_type(),alloc);\n\n    const long g = primitive_root(my_n);\n    const long g_inv = power_mod(g,my_n-2,my_n);\n\n    for(long i=0;i<my_n-1;++i)\n    {\n      W[i] = complex_root_of_unity<complex_value_type>(my_n,sign*power_mod(g_inv,i,my_n));\n      A[i] = in_first[ power_mod(g,i+1,my_n) ];\n    }\n    \n    raw_convolution(A.begin(),A.end(),W.begin(),B.begin(),alloc);\n    \n    complex_value_type a0 = in_first[0];\n    complex_value_type sum_a {a0};\n    for(long i=1;i<my_n;++i)\n        sum_a += in_first[i];\n    \n    out[0] = sum_a;\n    for(long i=1;i<my_n;++i)\n    {\n      out[i]=a0;\n    }\n    for(long i=1;i<my_n;++i)\n    {\n      out[ power_mod(g_inv,i,my_n) ] += B[i-1];\n    }\n  }\n  \n  \n  template <class T, class allocator_t>\n  void dft_composite_outofplace(const T *in_first, \n                     const T *in_last, \n                     T* out, \n                     const T e,\n                     const allocator_t& alloc)\n  {\n    /*\n      Cooley-Tukey mapping, intrinsically out-of-place, Decimation in Time\n      composite sizes.\n    */\n    using allocator_type = allocator_t;\n    \n    const long n = static_cast<unsigned int>(std::distance(in_first,in_last));\n    if(n <=0 )\n      return;\n    \n    if (n == 1)\n    {\n        out[0]=in_first[0];\n        return;\n    }\n    std::array<int,32> prime_factors;\n    const int nfactors = prime_factorization(n,prime_factors.begin());\n    \n    // reorder input\n    for (long i = 0; i < n; ++i)\n    {\n        long j = 0, k = i;\n        for (int ip=0;ip<nfactors;++ip)\n        {\n            int p = prime_factors[ip];    \n            j = j * p + k % p;\n            k /= p;\n        }\n        out[j] = in_first[i];\n    }\n    \n    std::reverse(prime_factors.begin(), prime_factors.begin()+nfactors);\n    \n    // butterfly pattern\n    long len = 1;\n    for (int ip=0;ip<nfactors;++ip)\n    {\n      int p = prime_factors[ip];\n      long len_old = len;\n      len *= p;\n      T w_len = power(e, n / len);\n      T w_p = power(e,n/p);\n      \n      std::vector<T,allocator_type> tmp(p,T(),alloc);\n      for (long i = 0; i < n; i += len)\n      {\n        for(long k=0;k<len_old;++k)\n        {\n          for(long j=0;j<p;++j)\n            if(j==0 || k==0)\n              tmp[j] = out[i + j*len_old +k ];\n            else\n              tmp[j] = out[i + j*len_old +k ] * power(w_len,k*j);\n          \n          dft_prime_bruteForce_inplace(tmp.data(),tmp.data()+p,w_p,alloc);\n          \n          for(long j=0;j<p;++j)\n            out[i+ j*len_old + k] = tmp[j];\n        }\n      }\n    }\n  }\n  \n  template<class T,class Allocator_t>\n  void dft_composite_inplace(\n    T* in_first, \n    T* in_last, \n    const T e,\n    const Allocator_t& alloc)\n  {\n    std::vector<T,Allocator_t> work_space(in_first,in_last,alloc);\n    dft_composite_outofplace(in_first,in_last,work_space.data(),e,alloc);\n    std::copy(work_space.begin(),work_space.end(),in_first);\n  }\n  template<class T, class Allocator_t>\n  void dft_composite(\n    const T* in_first, \n    const T* in_last, \n    T* out, \n    const T e,\n    const Allocator_t& alloc)\n  {\n    if(in_first==out)\n      dft_composite_inplace(out,out+std::distance(in_first,in_last),e,alloc);\n    else\n      dft_composite_outofplace(in_first,in_last,out,e,alloc);\n  }\n  \n  template <class ComplexType, class allocator_t>\n  void complex_dft_composite_outofplace(const ComplexType *in_first, \n                             const ComplexType *in_last, \n                             ComplexType* out, \n                             int sign,\n                             const allocator_t& alloc)\n  {\n    /*\n      Cooley-Tukey mapping, intrinsically out-of-place, Decimation in Time\n      composite sizes.\n    */\n    using allocator_type = allocator_t;\n    const long n = static_cast<long>(std::distance(in_first,in_last));\n    if(n <=0 )\n      return;\n    \n    if (n == 1)\n    {\n        out[0]=in_first[0];\n        return;\n    }\n    std::array<int,32> prime_factors;\n    const int nfactors = prime_factorization(n,prime_factors.begin());\n    \n    // reorder input\n    for (long i = 0; i < n; ++i)\n    {\n        long j = 0, k = i;\n        for (int ip=0;ip<nfactors;++ip)\n        {\n            int p = prime_factors[ip];\n            j = j * p + k % p;\n            k /= p;\n        }\n        out[j] = in_first[i];\n    }\n    \n    std::reverse(prime_factors.begin(), prime_factors.begin()+nfactors);\n    \n    //auto show = [&] (const ComplexType* beg, const ComplexType* end)\n    //{\n    //  for(;beg!=end;++beg)\n    //  {\n    //    std::cout << *beg << \", \";\n    //  }\n    //  std::cout << \"\\n\";\n    //};\n    \n    // butterfly pattern\n    long len = 1;\n    for (int ip=0;ip<nfactors;++ip)\n    {\n      //std::cout << \"pass \" << ip << \"\\n\";\n      int p = prime_factors[ip];\n      long len_old = len;\n      len *= p;\n\n      std::vector<ComplexType,allocator_type> tmp(p,ComplexType(),alloc);\n\n      for (long i = 0; i < n; i += len)\n      {\n        //std::cout << \"    i = \" << i << \"\\n\";\n        for(long k=0;k<len_old;++k)\n        {\n          for(long j=0;j<p;++j)\n            if(j==0 || k==0)\n              tmp[j] = out[i + j*len_old +k ];\n            else\n              tmp[j] = out[i + j*len_old +k ] \n                * complex_root_of_unity<ComplexType>(len,k*j*sign);\n          \n          if(p==2)\n            complex_dft_2(tmp.data(),tmp.data(),sign);\n          else\n          {\n          //  complex_dft_prime_bruteForce(tmp.data(),tmp.data()+p,tmp.data(),sign);\n            complex_dft_prime_rader(tmp.data(),tmp.data()+p,tmp.data(),sign,alloc);\n          }\n          for(long j=0;j<p;++j)\n            out[i+ j*len_old + k] = tmp[j];\n        }\n        //show(out+i,out+i+len);\n      }\n    }\n  }\n  \n  template<class complex_value_type,class Allocator_t>\n  void complex_dft_composite_inplace(\n    complex_value_type* in_first, \n    complex_value_type* in_last, \n    int sign,\n    const Allocator_t& alloc)\n  {\n    std::vector<complex_value_type,Allocator_t> work_space(in_first,in_last,alloc);\n    complex_dft_composite_outofplace(in_first,in_last,work_space.data(),sign,alloc);\n    std::copy(work_space.begin(),work_space.end(),in_first);\n  }\n  template<class complex_value_type, class Allocator_t>\n  void complex_dft_composite(\n    const complex_value_type* in_first, \n    const complex_value_type* in_last, \n    complex_value_type* out, \n    int sign,\n    const Allocator_t& alloc)\n  {\n    if(in_first==out)\n      complex_dft_composite_inplace(out,out+std::distance(in_first,in_last),sign,alloc);\n    else\n      complex_dft_composite_outofplace(in_first,in_last,out,sign,alloc);\n  }\n  \n  \n  template <class T>\n  void dft_power2(const T *in_first, const T *in_last, T* out, const T e)\n  {\n    /*\n      Cooley-Tukey mapping, in-place Decimation in Time \n    */\n    const long ptrdiff = static_cast<long>(std::distance(in_first,in_last));\n    if(ptrdiff <=0 )\n      return;\n    const long n = lower_bound_power2(ptrdiff);\n    \n    if(in_first!=out)\n      std::copy(in_first,in_last,out);\n    \n    if (n == 1)\n        return;\n\n    // auto _1 = T{1};\n    \n    int nbits = 0;\n    ::boost::container::static_vector<T,32> e2{e};\n    for (int m = n / 2; m > 0; m >>= 1, ++nbits)\n      e2.push_back(e2.back() * e2.back());\n\n    std::reverse(e2.begin(), e2.end());\n\n    // Gold-Rader bit-reversal algorithm.\n    for(int i=0,j=0;i<n-1;++i)\n    { \n      if(i<j)\n        std::swap(out[i],out[j]);\n      for(int k=n>>1;!( (j^=k)&k );k>>=1);\n    }\n    \n    \n    for (int len = 2, k = 1; len <= n; len <<= 1, ++k)\n    {\n      for (int i = 0; i < n; i += len)\n      {\n        {\n          int j=0;\n          T* u = out + i + j, *v = out + i + j + len / 2;\n          T Bu = *u, Bv = *v;\n          *u = Bu + Bv;\n          *v = Bu - Bv;\n        }\n        \n        T ej = e2[k];\n        for (int j = 1; j < len / 2; ++j)\n        {\n          T* u = out + i + j, *v = out + i + j + len / 2;\n          T Bu = *u, Bv = *v * ej;\n          *u = Bu + Bv;\n          *v = Bu - Bv;\n          ej *= e2[k];\n        }\n      }\n    }\n  }\n  \n  template <class T>\n  void complex_dft_power2(const T *in_first, const T *in_last, T* out, int sign)\n  {\n    /*\n      Cooley-Tukey mapping, in-place Decimation in Time \n    */\n    const long ptrdiff = static_cast<long>(std::distance(in_first,in_last));\n    if(ptrdiff <=0 )\n      return;\n    const long n = lower_bound_power2(ptrdiff);\n    \n    if(in_first!=out)\n      std::copy(in_first,in_last,out);\n    \n    if (n == 1)\n        return;\n\n\n    // Gold-Rader bit-reversal algorithm.\n    for(int i=0,j=0;i<n-1;++i)\n    { \n      if(i<j)\n        std::swap(out[i],out[j]);\n      for(int k=n>>1;!( (j^=k)&k );k>>=1);\n    }\n    \n    \n    for (int len = 2, k = 1; len <= n; len <<= 1, ++k)\n    {\n      for (int i = 0; i < n; i += len)\n      {\n        {\n          int j=0;\n          T* u = out + i + j, *v = out + i + j + len / 2;\n          T Bu = *u, Bv = *v;\n          *u = Bu + Bv;\n          *v = Bu - Bv;\n        }\n        for (int j = 1; j < len / 2; ++j)\n        {\n          T cs{complex_root_of_unity<T>(1<<k,j*sign)};\n          \n          T* u = out + i + j, *v = out + i + j + len / 2;\n          T Bu = *u, Bv = *v * cs;\n          *u = Bu + Bv;\n          *v = Bu - Bv;\n        }\n      }\n    }\n  }\n  \n  template<class complex_value_type>\n  void complex_dft_power2_dif(\n    const complex_value_type *in_first, \n    const complex_value_type *in_last, \n    complex_value_type* out, \n    int sign)\n  {\n    // Naive in-place complex DFT.\n    const long ptrdiff = static_cast<long>(std::distance(in_first,in_last));\n    if(ptrdiff <=0 )\n      return;\n    const long my_n = lower_bound_power2(ptrdiff);\n    \n    if(in_first!=out)\n      std::copy(in_first,in_last,out);\n    \n    if (my_n == 1)\n        return;\n    \n    if(in_first!=out)\n      std::copy(in_first, in_last, out);\n\n    // Recursive decimation in frequency.\n    for(long m = my_n; m > 1; m /= 2)\n    {\n      long mh = m / 2;\n      \n      for(long j = 0; j < mh; ++j)\n      {\n        complex_value_type cs{complex_root_of_unity<complex_value_type>(m,j*sign)};\n\n        for (long t1=j; t1 < j + my_n; t1 += m)\n        {\n          complex_value_type u = out[t1];\n          complex_value_type v = out[t1 + mh];\n\n          out[t1]      =  u + v;\n          out[t1 + mh] = (u - v) * cs;\n        }\n      }\n    }\n\n    // data reordering:\n    for(long m = 1, j = 0; m < my_n - 1; ++m)\n    {\n      for(long k = my_n >> 1; (!((j^=k)&k)); k>>=1)\n      {\n        ;\n      }\n\n      if(j > m)\n      {\n        std::swap(out[m], out[j]);\n      }\n    }\n\n    // Normalize for backwards transform (done externally).\n  }\n  \n  template<typename InputIterator1,\n           typename InputIterator2,\n           typename OutputIterator,\n           typename allocator_t  >\n  void raw_convolution(InputIterator1 input1_begin,\n                   InputIterator1 input1_end,\n                   InputIterator2 input2_begin,\n                   OutputIterator output,\n                   const allocator_t& alloc)\n  {\n    using input_value_type = typename std::iterator_traits<InputIterator1>::value_type;\n    using real_value_type  = typename input_value_type::value_type;\n    using allocator_type   = allocator_t;\n    \n    const long N = std::distance(input1_begin,input1_end);\n    const long N_extended = detail::is_power2(N) ? N : detail::upper_bound_power2(2*N-1);\n\n    std::vector<input_value_type, allocator_type> In1(N_extended,input_value_type(),alloc);\n    std::vector<input_value_type, allocator_type> In2(N_extended,input_value_type(),alloc);\n    std::vector<input_value_type, allocator_type> Out(N_extended,input_value_type(),alloc);\n\n    std::copy(input1_begin,input1_end,In1.begin());\n\n    InputIterator2 input2_end{input2_begin};\n    std::advance(input2_end,N);\n    std::copy(input2_begin,input2_end,In2.begin());\n    \n    // padding\n    for(long i=N;i<N_extended;++i)\n      In1[i]=In2[i]=input_value_type{0};\n    \n    // fake N-periodicity\n    if(N!=N_extended)\n    for(long i=1;i<N;++i)\n      In2[N_extended-N+i] = In2[i];\n    \n    complex_dft_power2(In1.data(),In1.data()+In1.size(),In1.data(),1);\n    complex_dft_power2(In2.data(),In2.data()+In1.size(),In2.data(),1);\n    \n    // direct convolution\n    std::transform(In1.begin(),In1.end(),In2.begin(),Out.begin(),std::multiplies<input_value_type>()); \n    \n    complex_dft_power2(Out.data(),Out.data()+Out.size(),Out.data(),-1);\n    \n    const real_value_type inv_N = real_value_type{1}/N_extended;\n    for(auto & x : Out)\n        x *= inv_N;\n    \n    std::copy(Out.begin(),Out.begin() + N,output);\n  }\n  \n\n  } // namespace detail\n\n  } } } // namespace boost::math::fft\n\n#endif // BOOST_MATH_FFT_ALGORITHMS_HPP\n\n", "meta": {"hexsha": "b86885599a6a4c4d5e709ce1dd405a8f6c9c3c37", "size": 18656, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/fft/algorithms.hpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/math/fft/algorithms.hpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "include/boost/math/fft/algorithms.hpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 27.6385185185, "max_line_length": 103, "alphanum_fraction": 0.5709155232, "num_tokens": 5353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.7431679972357831, "lm_q1q2_score": 0.638874585090662}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <string>\n#include <vector>\nusing namespace boost::hana;\n\n\nint main() {\n\n{\n\n//! [operators]\nBOOST_HANA_CONSTANT_CHECK(int_<1> + int_<3> == int_<4>);\n\n// Mixed-type operations are supported, but only when it involves a\n// promotion, and not a conversion that could be lossy.\nBOOST_HANA_CONSTANT_CHECK(size_t<3> * ushort<5> == size_t<15>);\nBOOST_HANA_CONSTANT_CHECK(llong<15> == int_<15>);\n//! [operators]\n\n}{\n\n//! [times_loop_unrolling]\nstd::string s;\nfor (char c = 'x'; c <= 'z'; ++c)\n    int_<5>.times([&] { s += c; });\n\nBOOST_HANA_RUNTIME_CHECK(s == \"xxxxxyyyyyzzzzz\");\n//! [times_loop_unrolling]\n\n}{\n\n//! [as_static_member]\nstd::string s;\nfor (char c = 'x'; c <= 'z'; ++c)\n    decltype(int_<5>)::times([&] { s += c; });\n\nBOOST_HANA_RUNTIME_CHECK(s == \"xxxxxyyyyyzzzzz\");\n//! [as_static_member]\n\n}{\n\n//! [times_higher_order]\nstd::string s;\nBOOST_HANA_CONSTEXPR_LAMBDA auto functions = make<Tuple>(\n    [&] { s += \"x\"; },\n    [&] { s += \"y\"; },\n    [&] { s += \"z\"; }\n);\nfor_each(functions, int_<5>.times);\nBOOST_HANA_RUNTIME_CHECK(s == \"xxxxxyyyyyzzzzz\");\n//! [times_higher_order]\n\n}{\n\n//! [times_with_index_runtime]\nstd::vector<int> v;\nint_<5>.times.with_index([&](auto index) { v.push_back(index); });\n\nBOOST_HANA_RUNTIME_CHECK(v == std::vector<int>{0, 1, 2, 3, 4});\n//! [times_with_index_runtime]\n\n//! [times_with_index_compile_time]\nconstexpr auto xs = make<Tuple>(0, 1, 2);\nint_<3>.times.with_index([xs](auto index) {\n    static_assert(xs[index] == index, \"\");\n});\n//! [times_with_index_compile_time]\n\n}{\n\n//! [literals]\nusing namespace literals; // contains the _c suffix\n\nBOOST_HANA_CONSTANT_CHECK(1234_c == llong<1234>);\nBOOST_HANA_CONSTANT_CHECK(-1234_c == llong<-1234>);\nBOOST_HANA_CONSTANT_CHECK(1_c + (3_c * 4_c) == llong<1 + (3 * 4)>);\n//! [literals]\n\n}{\n\n//! [integral_constant]\nBOOST_HANA_CONSTANT_CHECK(integral_constant<int, 2> == int_<2>);\nstatic_assert(decltype(integral_constant<int, 2>)::value == 2, \"\");\n//! [integral_constant]\n\n}\n\n}\n", "meta": {"hexsha": "86889fb1c45271466829492ec04f874ac44b155f", "size": 2283, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/integral_constant.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/integral_constant.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/integral_constant.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0606060606, "max_line_length": 78, "alphanum_fraction": 0.6719229085, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303236047049, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6388016339972317}}
{"text": "/// @file  dist.hpp\n/// @brief Declarations for embedding methods using pairwise distances\n\n#pragma once\n#ifndef OGT_EMBED_DIST_HPP\n#define OGT_EMBED_DIST_HPP\n\n#include <ogt/config.hpp>\n#include <Eigen/Dense>\n\nnamespace OGT_NAMESPACE {\nnamespace embed {\n\n/// Produce an embedding of the specified dimensionality from the given\n/// Euclidean distance matrix.\n///\n/// Uses Classical MDS, as described in:\n/// [1] I. Borg & P. Groenen (1997): Modern multidimensional scaling: theory\n///     and applications. Springer.\nEigen::MatrixXd embedDistWithDims(const Eigen::MatrixXd& dist, size_t nDim);\n\n/// Produce an embedding from the given Euclidean distance matrix.\n/// The natural dimensionality is estimated, using all eigenvalues greater than\n/// or equal to the (non-negative) threshold lambda.\n///\n/// Uses Classical MDS, as described in:\n/// [1] I. Borg & P. Groenen (1997): Modern multidimensional scaling: theory\n///     and applications. Springer.\nEigen::MatrixXd embedDist(const Eigen::MatrixXd& dist,\n\tdouble lambda = 1e-12);\n\n/// Produce an embedding using Euclidean distances to a subset of the set.\n/// The matrix dist must be a n x (d+1) Euclidean distance matrix, where each\n/// column represents the distance to some reference vertex.\n/// The reference vertices must be the first (d+1) rows.\n/// The produced embedding will be in R^maxDim, or in fewer dimensions if the\n/// distances between reference vertices are not large enough to justify the\n/// full dimensionality.\n///\n/// Implements:\n/// [1]\tM. J. Sippl and H. A. Scheraga, \"Solution of the embedding problem and\n///     decomposition of symmetric matrices.,\" Proceedings of the National\n///     Academy of Sciences, Apr. 1985.\nEigen::MatrixXd embedDistWithCMReference(const Eigen::MatrixXd& dist,\n\tsize_t maxDim);\n\n/// Produce an embedding into the target dimensionality, attempting to preserve\n/// the total ordering of pairwise distances.\n/// An ordinal matrix is produced from the given distance matrix, and an\n/// eigendecomposition is used to embed the points.\n///\n/// Implements method from:\n/// [1] Dattorro, Jon, \"Convex Optimization and Euclidean Distance Geometry,\"\n///     Meboo Publishing, 2016.\nEigen::MatrixXd embedDistWithOrdEig(const Eigen::MatrixXd& dist, size_t nDim);\n\n\n} // end namespace embed\n} // end namespace OGT_NAMESPACE\n#endif /* OGT_EMBED_DIST_HPP */\n", "meta": {"hexsha": "a799d3842c1e964b230f269fda5f1f8ce89007b0", "size": 2350, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ogt/embed/dist.hpp", "max_stars_repo_name": "jesand/lloe", "max_stars_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T21:31:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T09:23:04.000Z", "max_issues_repo_path": "include/ogt/embed/dist.hpp", "max_issues_repo_name": "jesand/lloe", "max_issues_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ogt/embed/dist.hpp", "max_forks_repo_name": "jesand/lloe", "max_forks_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T21:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-27T20:57:26.000Z", "avg_line_length": 38.5245901639, "max_line_length": 79, "alphanum_fraction": 0.7425531915, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6387815624230716}}
{"text": "#pragma once\n\n#include <Eigen/Eigen>\n\n#include \"Shader.hpp\"\n#include \"math.hpp\"\n\nnamespace LRR\n{\n  namespace Rendering\n  {\n    using namespace Eigen;\n\n    class BasicShader : public Shader\n    {\n    public:\n      BasicShader() = delete;\n      BasicShader(float aspectRatio);\n      BasicShader(BasicShader const &other) = default;\n      ~BasicShader() = default;\n\n      VertexShaderOutput OnVertex() override;\n      FragmentShaderOutput OnFragment() override;\n\n      inline Matrix4f const &ModelMatrix() const\n      { return mModelMatrix; }\n\n      inline void ModelMatrix(Matrix4f const &model)\n      { mModelMatrix = model; }\n\n      inline Matrix4f const &ViewMatrix() const\n      { return mViewMatrix; }\n\n      inline void ViewMatrix(Matrix4f const &view)\n      { mViewMatrix = view; }\n\n      inline Matrix4f const &ProjectionMatrix() const\n      { return mProjectionMatrix; }\n\n      inline void ProjectionMatrix(Matrix4f const &projection)\n      { mProjectionMatrix = projection; }\n    private:\n      Matrix4f mModelMatrix = Matrix4f::Identity();\n      Matrix4f mViewMatrix = Matrix4f::Identity();\n      Matrix4f mProjectionMatrix;\n    };\n  }\n}", "meta": {"hexsha": "c6df914aae46e4a5c9bc5f799834755675d7c4c9", "size": 1146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "BasicShader.hpp", "max_stars_repo_name": "Lisoph/LowResRenderer", "max_stars_repo_head_hexsha": "1f86aca8bca680e8e10ef8695977cd22e79a1f0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BasicShader.hpp", "max_issues_repo_name": "Lisoph/LowResRenderer", "max_issues_repo_head_hexsha": "1f86aca8bca680e8e10ef8695977cd22e79a1f0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BasicShader.hpp", "max_forks_repo_name": "Lisoph/LowResRenderer", "max_forks_repo_head_hexsha": "1f86aca8bca680e8e10ef8695977cd22e79a1f0b", "max_forks_repo_licenses": ["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.875, "max_line_length": 62, "alphanum_fraction": 0.6692844677, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6387815587852551}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2015-2016, Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Licensed under the Boost Software License version 1.0.\r\n// http://www.boost.org/users/license.html\r\n\r\n#ifndef BOOST_GEOMETRY_UTIL_NORMALIZE_SPHEROIDAL_COORDINATES_HPP\r\n#define BOOST_GEOMETRY_UTIL_NORMALIZE_SPHEROIDAL_COORDINATES_HPP\r\n\r\n#include <boost/geometry/core/assert.hpp>\r\n#include <boost/geometry/core/cs.hpp>\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace math \r\n{\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail\r\n{\r\n\r\n\r\ntemplate <typename CoordinateType, typename Units>\r\nstruct constants_on_spheroid\r\n{\r\n    static inline CoordinateType period()\r\n    {\r\n        return math::two_pi<CoordinateType>();\r\n    }\r\n\r\n    static inline CoordinateType half_period()\r\n    {\r\n        return math::pi<CoordinateType>();\r\n    }\r\n\r\n    static inline CoordinateType min_longitude()\r\n    {\r\n        static CoordinateType const minus_pi = -math::pi<CoordinateType>();\r\n        return minus_pi;\r\n    }\r\n\r\n    static inline CoordinateType max_longitude()\r\n    {\r\n        return math::pi<CoordinateType>();\r\n    }\r\n\r\n    static inline CoordinateType min_latitude()\r\n    {\r\n        static CoordinateType const minus_half_pi\r\n            = -math::half_pi<CoordinateType>();\r\n        return minus_half_pi;\r\n    }\r\n\r\n    static inline CoordinateType max_latitude()\r\n    {\r\n        return math::half_pi<CoordinateType>();\r\n    }\r\n};\r\n\r\ntemplate <typename CoordinateType>\r\nstruct constants_on_spheroid<CoordinateType, degree>\r\n{\r\n    static inline CoordinateType period()\r\n    {\r\n        return CoordinateType(360.0);\r\n    }\r\n\r\n    static inline CoordinateType half_period()\r\n    {\r\n        return CoordinateType(180.0);\r\n    }\r\n\r\n    static inline CoordinateType min_longitude()\r\n    {\r\n        return CoordinateType(-180.0);\r\n    }\r\n\r\n    static inline CoordinateType max_longitude()\r\n    {\r\n        return CoordinateType(180.0);\r\n    }\r\n\r\n    static inline CoordinateType min_latitude()\r\n    {\r\n        return CoordinateType(-90.0);\r\n    }\r\n\r\n    static inline CoordinateType max_latitude()\r\n    {\r\n        return CoordinateType(90.0);\r\n    }\r\n};\r\n\r\n\r\ntemplate <typename Units, typename CoordinateType>\r\nclass normalize_spheroidal_coordinates\r\n{\r\n    typedef constants_on_spheroid<CoordinateType, Units> constants;\r\n\r\nprotected:\r\n    static inline CoordinateType normalize_up(CoordinateType const& value)\r\n    {\r\n        return\r\n            math::mod(value + constants::half_period(), constants::period())\r\n            - constants::half_period();            \r\n    }\r\n\r\n    static inline CoordinateType normalize_down(CoordinateType const& value)\r\n    {\r\n        return\r\n            math::mod(value - constants::half_period(), constants::period())\r\n            + constants::half_period();            \r\n    }\r\n\r\npublic:\r\n    static inline void apply(CoordinateType& longitude)\r\n    {\r\n        // normalize longitude\r\n        if (math::equals(math::abs(longitude), constants::half_period()))\r\n        {\r\n            longitude = constants::half_period();\r\n        }\r\n        else if (longitude > constants::half_period())\r\n        {\r\n            longitude = normalize_up(longitude);\r\n            if (math::equals(longitude, -constants::half_period()))\r\n            {\r\n                longitude = constants::half_period();\r\n            }\r\n        }\r\n        else if (longitude < -constants::half_period())\r\n        {\r\n            longitude = normalize_down(longitude);\r\n        }\r\n    }\r\n\r\n    static inline void apply(CoordinateType& longitude,\r\n                             CoordinateType& latitude,\r\n                             bool normalize_poles = true)\r\n    {\r\n#ifdef BOOST_GEOMETRY_NORMALIZE_LATITUDE\r\n        // normalize latitude\r\n        if (math::larger(latitude, constants::half_period()))\r\n        {\r\n            latitude = normalize_up(latitude);\r\n        }\r\n        else if (math::smaller(latitude, -constants::half_period()))\r\n        {\r\n            latitude = normalize_down(latitude);\r\n        }\r\n\r\n        // fix latitude range\r\n        if (latitude < constants::min_latitude())\r\n        {\r\n            latitude = -constants::half_period() - latitude;\r\n            longitude -= constants::half_period();\r\n        }\r\n        else if (latitude > constants::max_latitude())\r\n        {\r\n            latitude = constants::half_period() - latitude;\r\n            longitude -= constants::half_period();\r\n        }\r\n#endif // BOOST_GEOMETRY_NORMALIZE_LATITUDE\r\n\r\n        // normalize longitude\r\n        apply(longitude);\r\n\r\n        // finally normalize poles\r\n        if (normalize_poles)\r\n        {\r\n            if (math::equals(math::abs(latitude), constants::max_latitude()))\r\n            {\r\n                // for the north and south pole we set the longitude to 0\r\n                // (works for both radians and degrees)\r\n                longitude = CoordinateType(0);\r\n            }\r\n        }\r\n\r\n#ifdef BOOST_GEOMETRY_NORMALIZE_LATITUDE\r\n        BOOST_GEOMETRY_ASSERT(! math::larger(constants::min_latitude(), latitude));\r\n        BOOST_GEOMETRY_ASSERT(! math::larger(latitude, constants::max_latitude()));\r\n#endif // BOOST_GEOMETRY_NORMALIZE_LATITUDE\r\n\r\n        BOOST_GEOMETRY_ASSERT(math::smaller(constants::min_longitude(), longitude));\r\n        BOOST_GEOMETRY_ASSERT(! math::larger(longitude, constants::max_longitude()));\r\n    }\r\n};\r\n\r\n\r\n} // namespace detail\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n\r\n/*!\r\n\\brief Short utility to normalize the coordinates on a spheroid\r\n\\tparam Units The units of the coordindate system in the spheroid\r\n\\tparam CoordinateType The type of the coordinates\r\n\\param longitude Longitude\r\n\\param latitude Latitude\r\n\\ingroup utility\r\n*/\r\ntemplate <typename Units, typename CoordinateType>\r\ninline void normalize_spheroidal_coordinates(CoordinateType& longitude,\r\n                                             CoordinateType& latitude)\r\n{\r\n    detail::normalize_spheroidal_coordinates\r\n        <\r\n            Units, CoordinateType\r\n        >::apply(longitude, latitude);\r\n}\r\n\r\n\r\n/*!\r\n\\brief Short utility to normalize the longitude on a spheroid.\r\n       Note that in general both coordinates should be normalized at once.\r\n       This utility is suitable e.g. for normalization of the difference of longitudes.\r\n\\tparam Units The units of the coordindate system in the spheroid\r\n\\tparam CoordinateType The type of the coordinates\r\n\\param longitude Longitude\r\n\\ingroup utility\r\n*/\r\ntemplate <typename Units, typename CoordinateType>\r\ninline void normalize_longitude(CoordinateType& longitude)\r\n{\r\n    detail::normalize_spheroidal_coordinates\r\n        <\r\n            Units, CoordinateType\r\n        >::apply(longitude);\r\n}\r\n\r\n\r\n/*!\r\n\\brief Short utility to calculate difference between two longitudes\r\n       normalized in range (-180, 180].\r\n\\tparam Units The units of the coordindate system in the spheroid\r\n\\tparam CoordinateType The type of the coordinates\r\n\\param longitude1 Longitude 1\r\n\\param longitude2 Longitude 2\r\n\\ingroup utility\r\n*/\r\ntemplate <typename Units, typename CoordinateType>\r\ninline CoordinateType longitude_distance_signed(CoordinateType const& longitude1,\r\n                                                CoordinateType const& longitude2)\r\n{\r\n    CoordinateType diff = longitude2 - longitude1;\r\n    math::normalize_longitude<Units, CoordinateType>(diff);\r\n    return diff;\r\n}\r\n\r\n\r\n/*!\r\n\\brief Short utility to calculate difference between two longitudes\r\n       normalized in range [0, 360).\r\n\\tparam Units The units of the coordindate system in the spheroid\r\n\\tparam CoordinateType The type of the coordinates\r\n\\param longitude1 Longitude 1\r\n\\param longitude2 Longitude 2\r\n\\ingroup utility\r\n*/\r\ntemplate <typename Units, typename CoordinateType>\r\ninline CoordinateType longitude_distance_unsigned(CoordinateType const& longitude1,\r\n                                                  CoordinateType const& longitude2)\r\n{\r\n    typedef math::detail::constants_on_spheroid\r\n        <\r\n            CoordinateType, Units\r\n        > constants;\r\n\r\n    CoordinateType const c0 = 0;\r\n    CoordinateType diff = longitude_distance_signed<Units>(longitude1, longitude2);\r\n    if (diff < c0) // (-180, 180] -> [0, 360)\r\n    {\r\n        diff += constants::period();\r\n    }\r\n    return diff;\r\n}\r\n\r\n/*!\r\n\\brief The abs difference between longitudes in range [0, 180].\r\n\\tparam Units The units of the coordindate system in the spheroid\r\n\\tparam CoordinateType The type of the coordinates\r\n\\param longitude1 Longitude 1\r\n\\param longitude2 Longitude 2\r\n\\ingroup utility\r\n*/\r\ntemplate <typename Units, typename CoordinateType>\r\ninline CoordinateType longitude_difference(CoordinateType const& longitude1,\r\n                                           CoordinateType const& longitude2)\r\n{\r\n    return math::abs(math::longitude_distance_signed<Units>(longitude1, longitude2));\r\n}\r\n\r\ntemplate <typename Units, typename CoordinateType>\r\ninline CoordinateType longitude_interval_distance_signed(CoordinateType const& longitude_a1,\r\n                                                         CoordinateType const& longitude_a2,\r\n                                                         CoordinateType const& longitude_b)\r\n{\r\n    CoordinateType const c0 = 0;\r\n    CoordinateType dist_a12 = longitude_distance_signed<Units>(longitude_a1, longitude_a2);\r\n    CoordinateType dist_a1b = longitude_distance_signed<Units>(longitude_a1, longitude_b);\r\n    if (dist_a12 < c0)\r\n    {\r\n        dist_a12 = -dist_a12;\r\n        dist_a1b = -dist_a1b;\r\n    }\r\n    \r\n    return dist_a1b < c0 ? dist_a1b\r\n         : dist_a1b > dist_a12 ? dist_a1b - dist_a12\r\n         : c0;\r\n}\r\n\r\n} // namespace math\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_UTIL_NORMALIZE_SPHEROIDAL_COORDINATES_HPP\r\n", "meta": {"hexsha": "b48da8b7381e3f723a8a8e8927adae75f1af6526", "size": 9927, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "win32/boost_bak/include/boost/geometry/util/normalize_spheroidal_coordinates.hpp", "max_stars_repo_name": "FreeApe/embcaffe_3rdparty", "max_stars_repo_head_hexsha": "d929e23f68515d03ba08c38f0c165216a2771a13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T00:12:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T01:52:56.000Z", "max_issues_repo_path": "win32/boost_bak/include/boost/geometry/util/normalize_spheroidal_coordinates.hpp", "max_issues_repo_name": "FreeApe/embcaffe_3rdparty", "max_issues_repo_head_hexsha": "d929e23f68515d03ba08c38f0c165216a2771a13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-11T00:36:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T15:39:01.000Z", "max_forks_repo_path": "win32/boost_bak/include/boost/geometry/util/normalize_spheroidal_coordinates.hpp", "max_forks_repo_name": "FreeApe/embcaffe_3rdparty", "max_forks_repo_head_hexsha": "d929e23f68515d03ba08c38f0c165216a2771a13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-02-28T01:38:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-13T13:36:36.000Z", "avg_line_length": 30.5446153846, "max_line_length": 93, "alphanum_fraction": 0.6430945905, "num_tokens": 1985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6387815385845275}}
{"text": "/**\n * Decode binary space partitioning airline seating assignments, \n * and find your seat\n */\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <set>\n#include <sstream>\n\n#include <boost/algorithm/string.hpp>\n\nvoid decode(const std::string &spec, int &row, int &col)\n{\n    if(spec.length() != 10) { return; }\n\n    const std::string rowspec = spec.substr(0, 7);\n    const std::string colspec = spec.substr(7, 3);\n\n    row = 0;\n    for(int i=0; i<7; ++i)\n    {\n        row <<= 1;\n\n        //std::cout << rowspec.at(i) << std::endl;\n        if(rowspec.at(i) == 'F')\n        {\n            row |= 0;\n        }\n        else\n        {\n            row |= 1;\n        }\n    }\n\n    col = 0;\n    for(int i=0; i<3; ++i)\n    {\n        col <<= 1;\n\n        //std::cout << colspec.at(i) << std::endl;\n        if(colspec.at(i) == 'R')\n        {\n            col |= 1;\n        }\n        else\n        {\n            col |= 0;\n        }\n    }\n}\n\nvoid usage()\n{\n    std::cout << \"day5 <input.txt>\" << std::endl;\n}\n\nint main(int argc, char *argv[])\n{\n    if(argc != 2)\n    {\n        usage();\n        return EXIT_FAILURE;\n    }\n\n    int row, col;\n\n    struct seat\n    {\n        int row;\n        int col;\n        int id;\n    };\n    std::set<int> ids;\n\n    std::ifstream ifs(argv[1], std::ifstream::in);\n    std::string line;\n    while(std::getline(ifs, line))\n    {\n        decode(line, row, col);\n        int id = row * 8 + col;\n        ids.insert(id);\n    }\n\n    int lastId = *(ids.begin()) - 1;\n    for(std::set<int>::const_iterator it=ids.begin(); it!=ids.end(); ++it)\n    {\n        //std::cout << *it << std::endl;\n        if(*it != lastId + 1) \n        {\n            std::cout << \"missing id might be: \" << lastId + 1 << std::endl;\n        }\n        lastId = *it;\n    }\n\n    ifs.close();\n}\n", "meta": {"hexsha": "36c057cc144c39a83c0038217e1ba21981e485ef", "size": 1787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "day5/part2.cpp", "max_stars_repo_name": "deltj/advent_of_code_2020", "max_stars_repo_head_hexsha": "52d1eeeff6ba0df6bc49679ae9fc73e04a543ca1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "day5/part2.cpp", "max_issues_repo_name": "deltj/advent_of_code_2020", "max_issues_repo_head_hexsha": "52d1eeeff6ba0df6bc49679ae9fc73e04a543ca1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "day5/part2.cpp", "max_forks_repo_name": "deltj/advent_of_code_2020", "max_forks_repo_head_hexsha": "52d1eeeff6ba0df6bc49679ae9fc73e04a543ca1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2346938776, "max_line_length": 76, "alphanum_fraction": 0.4549524342, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6387441905851777}}
{"text": "\n// solving A * X = B\n// A symmetric\n// sytrf() & sytrs() \n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/lapack/sysv.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_symmetric.hpp>\n#include <boost/numeric/bindings/traits/std_vector.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cin;\nusing std::cout;\nusing std::endl; \n\ntypedef double real_t; \ntypedef std::complex<real_t> cmplx_t; \n\ntypedef ublas::matrix<real_t, ublas::column_major> m_t;\ntypedef ublas::matrix<cmplx_t, ublas::column_major> cm_t;\n\ntypedef ublas::symmetric_adaptor<m_t, ublas::lower> symml_t; \ntypedef ublas::symmetric_adaptor<m_t, ublas::upper> symmu_t; \n\ntypedef ublas::symmetric_adaptor<cm_t, ublas::lower> csymml_t; \ntypedef ublas::symmetric_adaptor<cm_t, ublas::upper> csymmu_t; \n\ntemplate <typename M>\nvoid init_symm2 (M& m) {\n  for (int i = 0; i < m.size1(); ++i) \n    for (int j = i; j < m.size1(); ++j)\n      m (i, j) = m (j, i) = 1 + j - i; \n}\n\nint main (int argc, char **argv) {\n  size_t n = 0;\n  if (argc > 1) {\n    n = atoi(argv [1]);\n  }\n\n  cout << endl; \n\n  // symmetric \n  cout << \"real symmetric\\n\" << endl; \n\n  if (n <= 0) {\n  cout << \"n -> \";\n  cin >> n;\n  }\n  if (n < 5) n = 5; \n  cout << \"min n = 5\" << endl << endl; \n  size_t nrhs = 2; \n  m_t al (n, n), au (n, n);  // matrices (storage)\n  symml_t sal (al);   // symmetric adaptor\n  symmu_t sau (au);   // symmetric adaptor\n  m_t x (n, nrhs);\n  m_t bl (n, nrhs), bu (n, nrhs);  // RHS matrices\n\n  init_symm2 (al); \n  swap (row (al, 1), row (al, 4)); \n  swap (column (al, 1), column (al, 4)); \n\n  print_m (al, \"al\"); \n  cout << endl; \n\n  init_symm2 (au); \n  swap (row (au, 2), row (au, 3)); \n  swap (column (au, 2), column (au, 3)); \n\n  print_m (au, \"au\"); \n  cout << endl; \n\n  for (int i = 0; i < x.size1(); ++i) {\n    x (i, 0) = 1.;\n    x (i, 1) = 2.; \n  }\n  bl = prod (sal, x); \n  bu = prod (sau, x); \n\n  print_m (bl, \"bl\"); \n  cout << endl; \n  print_m (bu, \"bu\"); \n  cout << endl; \n\n  m_t al1 (al), au1 (au);  // for part 2\n  m_t bl1 (bl), bu1 (bu); \n\n  std::vector<int> ipiv (n); \n  \n  int err = lapack::sytrf (sal, ipiv);  \n  if (err == 0) {\n    symml_t isal (sal);\n    lapack::sytrs (sal, ipiv, bl); \n    print_m (bl, \"xl\"); \n    lapack::sytri (isal, ipiv);\n    print_m (isal, \"isal\"); \n  } \n  cout << endl; \n\n  err = lapack::sytrf (sau, ipiv);  \n  if (err == 0) {\n    symmu_t isau (sau);\n    lapack::sytrs (sau, ipiv, bu); \n    print_m (bu, \"xu\"); \n    lapack::sytri (isau, ipiv);\n    print_m (isau, \"isau\"); \n  } \n  else \n    cout << \"?\" << endl; \n  cout << endl; \n\n  // part 2 \n\n  cout << endl << \"part 2\" << endl << endl; \n  \n  int lw = lapack::sytrf_block ('O', 'L', al1);\n  cout << \"nb = \" << lw << endl;\n  lw *= n; \n  cout << \"lw = \" << lw << \" == \" \n       << lapack::sytrf_work ('O', 'L', al1) << endl;\n  cout << \"mw = \" << lapack::sytrf_work ('M', 'L', al1) << endl;\n  std::vector<real_t> work (lw); \n  int mb = lapack::sytrf_block ('M', 'L', al1); \n  cout << \"mb = \" << mb << endl << endl;\n\n  err = lapack::sytrf ('L', al1, ipiv, work);  \n  if (err == 0) {\n    lapack::sytrs ('L', al1, ipiv, bl1); \n    print_m (al1, \"al1 factored\"); \n    cout << endl; \n    print_v (ipiv, \"ipiv\"); \n    cout << endl; \n    print_m (bl1, \"xl1\"); \n  }\n  else \n    cout << \"?\" << endl; \n  cout << endl; \n\n  lw = lapack::sytrf_block ('O', 'U', au1); \n  cout << \"nb = \" << lw << endl;\n  lw *= n; \n  cout << \"lw = \" << lw << \" == \" \n       << lapack::sytrf_work ('O', 'U', au1) << endl;\n  cout << \"mw = \" << lapack::sytrf_work ('M', 'U', au1) << endl;\n  if (lw != work.size())\n    work.resize (lw); \n  mb = lapack::sytrf_block ('M', 'U', au1);\n  cout << \"mb = \" << mb << endl << endl;\n\n  err = lapack::sytrf ('U', au1, ipiv, work);  \n  if (err == 0) {\n    lapack::sytrs ('U', au1, ipiv, bu1); \n    print_m (au1, \"au1 factored\"); \n    cout << endl; \n    print_v (ipiv, \"ipiv\"); \n    cout << endl; \n    print_m (bu1, \"xu1\"); \n  }\n  else \n    cout << \"?\" << endl; \n  cout << endl; \n  cout << endl; \n\n  //////////////////////////////////////////////////////////\n  cout << \"\\n==========================================\\n\" << endl; \n  cout << \"complex symmetric\\n\" << endl; \n\n  cm_t cal (n, n), cau (n, n);   // matrices (storage)\n  csymml_t scal (cal);   // symmetric adaptor \n  csymmu_t scau (cau);   // symmetric adaptor \n  cm_t cx (n, 1); \n  cm_t cbl (n, 1), cbu (n, 1);  // RHS\n\n  init_symm2 (cal); \n  init_symm2 (cau); \n  cal *= cmplx_t (1, 1); \n  cau *= cmplx_t (1, -0.5); \n\n  print_m (cal, \"cal\"); \n  cout << endl; \n  print_m (cau, \"cau\"); \n  cout << endl; \n\n  for (int i = 0; i < cx.size1(); ++i) \n    cx (i, 0) = cmplx_t (1, -1); \n  print_m (cx, \"cx\"); \n  cout << endl; \n  cbl = prod (scal, cx);\n  cbu = prod (scau, cx);\n  print_m (cbl, \"cbl\"); \n  cout << endl; \n  print_m (cbu, \"cbu\"); \n  cout << endl; \n\n  int ierr = lapack::sytrf (scal, ipiv); \n  if (ierr == 0) {\n    csymml_t iscal (scal);\n    lapack::sytrs (scal, ipiv, cbl); \n    print_m (cbl, \"cxl\"); \n    lapack::sytri (iscal, ipiv);\n    print_m (iscal, \"iscal\"); \n  }\n  else \n    cout << \"?\" << endl;\n  cout << endl; \n\n  lw = lapack::sytrf_block ('O', scau); \n  cout << \"nb = \" << lw << endl;\n  lw *= n; \n  cout << \"lw = \" << lw << \" == \" \n       << lapack::sytrf_work ('O', scau) << endl;\n  cout << \"mw = \" << lapack::sytrf_work ('M', scau) << endl;\n  std::vector<cmplx_t> cwork (lw); \n  mb = lapack::sytrf_block ('M', scau); \n  cout << \"mb = \" << mb << endl << endl;\n\n  ierr = lapack::sytrf (scau, ipiv, cwork); \n  if (ierr == 0) {\n    csymmu_t iscau (scau);\n    lapack::sytrs (scau, ipiv, cbu); \n    print_v (ipiv, \"ipiv\"); \n    cout << endl; \n    print_m (cbu, \"cxu\"); \n    lapack::sytri (iscau, ipiv);\n    print_m (iscau, \"iscau\"); \n  }\n  else \n    cout << \"?\" << endl;\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "17199b478c5008804fdf03f62e06d553c52fd139", "size": 5950, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/numeric/bindings/lapack/test/ublas_sytrf_sytrs.cc", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "libs/numeric/bindings/lapack/test/ublas_sytrf_sytrs.cc", "max_issues_repo_name": "dilawar/boost-numeric-bindings", "max_issues_repo_head_hexsha": "a99439c3289d9537ad7d5ab05c5fdebdbf7af853", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/bindings/lapack/test/ublas_sytrf_sytrs.cc", "max_forks_repo_name": "dilawar/boost-numeric-bindings", "max_forks_repo_head_hexsha": "a99439c3289d9537ad7d5ab05c5fdebdbf7af853", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-04-18T02:01:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-18T02:01:09.000Z", "avg_line_length": 24.6887966805, "max_line_length": 68, "alphanum_fraction": 0.5201680672, "num_tokens": 2302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6386570907078427}}
{"text": "#include <stan/math.hpp>\n#include <ostream>\n#include <boost/math/tools/promotion.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\nnamespace cambridgeModel_model_namespace {\n\ntemplate <typename T0__>\nstan::promote_args_t<stan::value_type_t<T0__>>\ndominant_eigenvalue_external(const T0__& A_arg__, std::ostream* pstream__){\n  //Return type\n  typedef typename stan::promote_args_t<stan::value_type_t<T0__>> scalar_t;\n  //inputtype\n  typedef T0__ matrix_t;\n\n  //Eigensolver\n  Eigen::EigenSolver<matrix_t> es(A_arg__);\n\n  //Eigenvalues\n  Eigen::Matrix<std::complex<scalar_t>, Eigen::Dynamic, 1> lambdas = es.eigenvalues();\n\n  //Just take the real parts\n  std::vector<scalar_t> lambdas_real(lambdas.rows());\n  for (int i = 0; i < lambdas.rows(); i++){\n    lambdas_real.at(i) = lambdas(i,0).real();\n  }\n\n\n  scalar_t returnValue;\n  //Maximum eigenvalue (basic reproduction number is positive so\n  //so we don't have to worry about sign)\n  returnValue = stan::math::max(lambdas_real);\n\n  return returnValue;\n\n}\n\n} //cambridgemodel_model_namespace\n", "meta": {"hexsha": "f7e486acd9f5e4bb22b59d0be252fc18a51a9b4b", "size": 1069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/models/dominant_eigenvalue_external.cpp", "max_stars_repo_name": "codatmo/Cambridge", "max_stars_repo_head_hexsha": "2b3ed73e88556e4bb5ef142c887284285ec40c88", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models/dominant_eigenvalue_external.cpp", "max_issues_repo_name": "codatmo/Cambridge", "max_issues_repo_head_hexsha": "2b3ed73e88556e4bb5ef142c887284285ec40c88", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/models/dominant_eigenvalue_external.cpp", "max_forks_repo_name": "codatmo/Cambridge", "max_forks_repo_head_hexsha": "2b3ed73e88556e4bb5ef142c887284285ec40c88", "max_forks_repo_licenses": ["BSD-3-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.0731707317, "max_line_length": 86, "alphanum_fraction": 0.7352666043, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7185943865443349, "lm_q1q2_score": 0.6386570799955953}}
{"text": "#include \"DenoiseSystem.h\"\n\n#include \"../Components/DenoiseData.h\"\n\n#include <_deps/imgui/imgui.h>\n\n#include <spdlog/spdlog.h>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\nusing namespace Ubpa;\n\nvoid DenoiseSystem::OnUpdate(Ubpa::UECS::Schedule& schedule) {\n\tschedule.RegisterCommand([](Ubpa::UECS::World* w) {\n\t\tauto data = w->entityMngr.GetSingleton<DenoiseData>();\n\t\tif (!data)\n\t\t\treturn;\n\n\t\tif (ImGui::Begin(\"Denoise\")) {\n\t\t\tif (ImGui::Button(\"Mesh to HEMesh\")) {\n\t\t\t\tdata->heMesh->Clear();\n\t\t\t\t[&]() {\n\t\t\t\t\tif (!data->mesh) {\n\t\t\t\t\t\tspdlog::warn(\"mesh is nullptr\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (data->mesh->GetSubMeshes().size() != 1) {\n\t\t\t\t\t\tspdlog::warn(\"number of submeshes isn't 1\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tdata->copy = *data->mesh;\n\n\t\t\t\t\tstd::vector<size_t> indices(data->mesh->GetIndices().begin(), data->mesh->GetIndices().end());\n\n\t\t\t\t\tdata->heMesh->Init(indices, 3);\n\t\t\t\t\tif (!data->heMesh->IsTriMesh())\n\t\t\t\t\t\tspdlog::warn(\"HEMesh init fail\");\n\t\t\t\t\t\n\t\t\t\t\tfor (size_t i = 0; i < data->mesh->GetPositions().size(); i++) {\n\t\t\t\t\t\tdata->heMesh->Vertices().at(i)->position = data->mesh->GetPositions().at(i);\n\t\t\t\t\t\tdata->heMesh->Vertices().at(i)->idx = -1;\n\t\t\t\t\t\tdata->heMesh->Vertices().at(i)->bidx = -1;\n\t\t\t\t\t}\n\n\t\t\t\t\tspdlog::info(\"Mesh to HEMesh success\");\n\t\t\t\t}();\n\t\t\t}\n\n\t\t\tif (ImGui::Button(\"Solve Minimal surface\")) {\n\t\t\t\t[&]() {\n\t\t\t\t\tif (!data->heMesh->IsTriMesh()) {\n\t\t\t\t\t\tspdlog::warn(\"HEMesh isn't triangle mesh\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst auto vertices = data->heMesh->Vertices();\n\t\t\t\t\tint totalPoints = static_cast<int>(vertices.size()), boundaryPoints = { 0 }, innerPoints = { 0 };\n\t\t\t\t\tfor (int i = 0; i < totalPoints; ++i) {\n\t\t\t\t\t\tvertices[i]->idx = i;\n\t\t\t\t\t\tif (vertices[i]->IsOnBoundary()) ++boundaryPoints;\n\t\t\t\t\t}\n\t\t\t\t\tinnerPoints = totalPoints - boundaryPoints;\n\n\t\t\t\t\tauto Idx = [&](int idx, int k) {\n\t\t\t\t\t\treturn k * totalPoints + idx;\n\t\t\t\t\t};\n\t\t\t\t\tauto ConsIdx = [&](int idx, int k) {\n\t\t\t\t\t\treturn 3 * totalPoints + idx * 3 + k;\n\t\t\t\t\t};\n\n\t\t\t\t\tEigen::SparseMatrix<float> A(3 * (totalPoints + boundaryPoints), 3 * totalPoints);\n\t\t\t\t\tEigen::SparseVector<float> b(3 * (totalPoints + boundaryPoints));\n\t\t\t\t\tspdlog::info(totalPoints);\n\t\t\t\t\t\n\t\t\t\t\tint b_idx = 0;\n\t\t\t\t\tfor (auto* v : data->heMesh->Vertices()) {\n\t\t\t\t\t\tconst auto P = v->position;\n\n\t\t\t\t\t\t// A_ij & x_i\n\t\t\t\t\t\tif (v->IsOnBoundary()) {\n\t\t\t\t\t\t\tfor (auto k : { 0, 1, 2 }) {\n\t\t\t\t\t\t\t\tb.coeffRef(ConsIdx(b_idx, k)) = P[k];\n\t\t\t\t\t\t\t\tA.coeffRef(ConsIdx(b_idx, k), Idx(v->idx, k)) = 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t++b_idx;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst auto& adj_v = v->AdjVertices();\n\t\t\t\t\t\tfor (auto k : { 0, 1, 2 }) \n\t\t\t\t\t\t\tA.coeffRef(Idx(v->idx, k), Idx(v->idx, k)) = v->AdjVertices().size();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tfor (auto* adj : adj_v) {\n\t\t\t\t\t\t\tfor (auto k : { 0, 1, 2 }) A.coeffRef(Idx(v->idx, k), Idx(adj->idx, k)) = -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tspdlog::info(\"Build Matrix successful\");\n\n\t\t\t\t\tEigen::ConjugateGradient<Eigen::SparseMatrix<float> > solver;\n\t\t\t\t\tsolver.setTolerance(1e-4);\n\t\t\t\t\tsolver.compute(A.transpose() * A);\n\t\t\t\t\tEigen::SparseVector<float> x(3 * totalPoints);\n\t\t\t\t\tx = solver.solve(A.transpose() * b);\n\n\t\t\t\t\tspdlog::info(\"Solve Matrix successful\");\n\n\t\t\t\t\tfor (auto* v : data->heMesh->Vertices()) {\n\t\t\t\t\t\tfor (auto k : { 0, 1, 2 }) {\n\t\t\t\t\t\t\tv->position[k] = x.coeffRef(Idx(v->idx, k));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tspdlog::info(\"Data transform successful\");\n\t\t\t\t}();\n\t\t\t}\n\n\t\t\tif (ImGui::Button(\"Parameterization\")) {\n\t\t\t\t[&]() {\n\t\t\t\t\tif (!data->heMesh->IsTriMesh()) {\n\t\t\t\t\t\tspdlog::warn(\"HEMesh isn't triangle mesh\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst auto vertices = data->heMesh->Vertices();\n\t\t\t\t\tint totalPoints = static_cast<int>(vertices.size()), boundaryPoints = { 0 }, innerPoints = { 0 };\n\t\t\t\t\tfor (int i = 0; i < totalPoints; ++i) vertices[i]->idx = i;\n\t\t\t\t\tint bpt;\n\t\t\t\t\tfor (int i = 0; i < totalPoints; ++i)\n\t\t\t\t\t\tif (vertices[i]->IsOnBoundary()) bpt = vertices[i]->idx; // start point\n\t\t\t\t\tdo {\n\t\t\t\t\t\tvertices[bpt]->bidx = boundaryPoints++;\n\t\t\t\t\t\tconst auto& adj_v = vertices[bpt]->AdjVertices();\n\t\t\t\t\t\tfor (auto* v : data->heMesh->Vertices()) {\n\t\t\t\t\t\t\tif (v->IsOnBoundary() && v->bidx < 0) {\n\t\t\t\t\t\t\t\tbpt = v->idx;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} while (vertices[bpt]->bidx < 0);\n\n\t\t\t\t\tinnerPoints = totalPoints - boundaryPoints;\n\n\t\t\t\t\tauto Idx = [&](int idx, int k) {\n\t\t\t\t\t\treturn k * totalPoints + idx;\n\t\t\t\t\t};\n\t\t\t\t\tauto ConsIdx = [&](int idx, int k) {\n\t\t\t\t\t\treturn 2 * totalPoints + idx * 2 + k;\n\t\t\t\t\t};\n\n\t\t\t\t\tEigen::SparseMatrix<float> A(2 * (totalPoints + boundaryPoints), 2 * totalPoints);\n\t\t\t\t\tEigen::SparseVector<float> b(2 * (totalPoints + boundaryPoints));\n\t\t\t\t\tspdlog::info(totalPoints);\n\n\t\t\t\t\tfor (auto* v : data->heMesh->Vertices()) {\n\t\t\t\t\t\tconst auto P = v->position;\n\n\t\t\t\t\t\t// A_ij & x_i\n\t\t\t\t\t\tif (v->IsOnBoundary()) {\n\t\t\t\t\t\t\t{ // project to UV surface\n\t\t\t\t\t\t\t\tfloat t = 4 * float(v->bidx) / float(boundaryPoints);\n\t\t\t\t\t\t\t\tfloat U = { 0.0f }, V = { 0.0f };\n\t\t\t\t\t\t\t\tif (t <= 1.0f) V = t;\n\t\t\t\t\t\t\t\telse if (t <= 2.0f) U = t - 1, V = 1.0f;\n\t\t\t\t\t\t\t\telse if (t <= 3.0f) U = 1.0f, V = 1.0f - (t - 2.0f);\n\t\t\t\t\t\t\t\telse U = 1.0f - (t - 3.0f);\n\n\t\t\t\t\t\t\t\tspdlog::info(std::to_string(U) + \" \" + std::to_string(V));\n\n\t\t\t\t\t\t\t\tb.coeffRef(ConsIdx(v->bidx, 0)) = U;\n\t\t\t\t\t\t\t\tb.coeffRef(ConsIdx(v->bidx, 1)) = V;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (auto k : { 0, 1 }) A.coeffRef(ConsIdx(v->bidx, k), Idx(v->idx, k)) = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst auto& adj_v = v->AdjVertices();\n\t\t\t\t\t\tfor (auto k : { 0, 1 })\n\t\t\t\t\t\t\tA.coeffRef(Idx(v->idx, k), Idx(v->idx, k)) = v->AdjVertices().size();\n\n\t\t\t\t\t\tfor (auto* adj : adj_v) {\n\t\t\t\t\t\t\tfor (auto k : { 0, 1 }) A.coeffRef(Idx(v->idx, k), Idx(adj->idx, k)) = -1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tspdlog::info(\"Build Matrix successful\");\n\n\t\t\t\t\tEigen::ConjugateGradient<Eigen::SparseMatrix<float> > solver;\n\t\t\t\t\tsolver.setTolerance(1e-2);\n\t\t\t\t\tsolver.compute(A.transpose() * A);\n\t\t\t\t\tEigen::SparseVector<float> x(2 * totalPoints);\n\t\t\t\t\tx = solver.solve(A.transpose() * b);\n\n\t\t\t\t\tspdlog::info(\"Solve Matrix successful\");\n\n\t\t\t\t\tfor (auto* v : data->heMesh->Vertices()) {\n\t\t\t\t\t\tv->uv = { x.coeffRef(Idx(v->idx, 0)), x.coeffRef(Idx(v->idx, 1)) };\n\t\t\t\t\t\tspdlog::info(std::to_string(v->uv[0]) + \" \" + std::to_string(v->uv[1]));\n\t\t\t\t\t}\n\n\t\t\t\t\tspdlog::info(\"Data transform successful\");\n\t\t\t\t}();\n\t\t\t}\n\n\t\t\tif (ImGui::Button(\"Set Normal to Color\")) {\n\t\t\t\t[&]() {\n\t\t\t\t\tif (!data->mesh) {\n\t\t\t\t\t\tspdlog::warn(\"mesh is nullptr\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tdata->mesh->SetToEditable();\n\t\t\t\t\tconst auto& normals = data->mesh->GetNormals();\n\t\t\t\t\tstd::vector<rgbf> colors;\n\t\t\t\t\tfor (const auto& n : normals)\n\t\t\t\t\t\tcolors.push_back((n.as<valf3>() + valf3{ 1.f }) / 2.f);\n\t\t\t\t\tdata->mesh->SetColors(std::move(colors));\n\n\t\t\t\t\tspdlog::info(\"Set Normal to Color Success\");\n\t\t\t\t}();\n\t\t\t}\n\n\t\t\tif (ImGui::Button(\"HEMesh to Mesh\")) {\n\t\t\t\t[&]() {\n\t\t\t\t\tif (!data->mesh) {\n\t\t\t\t\t\tspdlog::warn(\"mesh is nullptr\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!data->heMesh->IsTriMesh() || data->heMesh->IsEmpty()) {\n\t\t\t\t\t\tspdlog::warn(\"HEMesh isn't triangle mesh or is empty\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tdata->mesh->SetToEditable();\n\n\t\t\t\t\tconst size_t N = data->heMesh->Vertices().size();\n\t\t\t\t\tconst size_t M = data->heMesh->Polygons().size();\n\t\t\t\t\tstd::vector<Ubpa::pointf3> positions(N);\n\t\t\t\t\tstd::vector<Ubpa::pointf2> uvs(N);\n\t\t\t\t\tstd::vector<uint32_t> indices(M * 3);\n\t\t\t\t\tfor (size_t i = 0; i < N; i++) {\n\t\t\t\t\t\tpositions[i] = data->heMesh->Vertices().at(i)->position;\n\t\t\t\t\t\tuvs[i] = data->heMesh->Vertices().at(i)->uv;\n\t\t\t\t\t}\n\t\t\t\t\tfor (size_t i = 0; i < M; i++) {\n\t\t\t\t\t\tauto tri = data->heMesh->Indices(data->heMesh->Polygons().at(i));\n\t\t\t\t\t\tindices[3 * i + 0] = static_cast<uint32_t>(tri[0]);\n\t\t\t\t\t\tindices[3 * i + 1] = static_cast<uint32_t>(tri[1]);\n\t\t\t\t\t\tindices[3 * i + 2] = static_cast<uint32_t>(tri[2]);\n\t\t\t\t\t}\n\t\t\t\t\tdata->mesh->SetPositions(std::move(positions));\n\t\t\t\t\tdata->mesh->SetUV(std::move(uvs));\n\t\t\t\t\tdata->mesh->SetIndices(std::move(indices));\n\t\t\t\t\tdata->mesh->SetSubMeshCount(1);\n\t\t\t\t\tdata->mesh->SetSubMesh(0, { 0, M * 3 });\n\t\t\t\t\tdata->mesh->GenNormals();\n\t\t\t\t\tdata->mesh->GenTangents();\n\n\t\t\t\t\tspdlog::info(\"HEMesh to Mesh success\");\n\t\t\t\t}();\n\t\t\t}\n\n\t\t\tif (ImGui::Button(\"Recover Mesh\")) {\n\t\t\t\t[&]() {\n\t\t\t\t\tif (!data->mesh) {\n\t\t\t\t\t\tspdlog::warn(\"mesh is nullptr\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (data->copy.GetPositions().empty()) {\n\t\t\t\t\t\tspdlog::warn(\"copied mesh is empty\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t*data->mesh = data->copy;\n\n\t\t\t\t\tspdlog::info(\"recover success\");\n\t\t\t\t}();\n\t\t\t}\n\t\t}\n\t\tImGui::End();\n\t});\n}\n", "meta": {"hexsha": "99fad706c051511f1a53d65f97e1f47ca676b9f7", "size": 8369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homeworks/HW7/Systems/DenoiseSystem.cpp", "max_stars_repo_name": "g1n0st/GAMES102", "max_stars_repo_head_hexsha": "44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-10-23T16:33:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T23:49:36.000Z", "max_issues_repo_path": "homeworks/HW7/Systems/DenoiseSystem.cpp", "max_issues_repo_name": "g1n0st/GAMES102", "max_issues_repo_head_hexsha": "44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/HW7/Systems/DenoiseSystem.cpp", "max_forks_repo_name": "g1n0st/GAMES102", "max_forks_repo_head_hexsha": "44a8cf9db102109c8fd15c8dc06aa6ad1519a5eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-18T08:45:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-17T02:36:06.000Z", "avg_line_length": 29.9964157706, "max_line_length": 102, "alphanum_fraction": 0.5437925678, "num_tokens": 2702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6386570788740827}}
{"text": "#include <stdlib.h>\n#include <assert.h>\n#include <math.h>\n#include <complex.h>\n#include <time.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <NTL/mat_ZZ.h>\n#include <gmp.h>\n\n#include \"Random.h\"\n#include \"params.h\"\n\nusing namespace std;\nusing namespace NTL;\n\n\nvec_ZZ RandomVector()\n{\n    vec_ZZ w;\n    unsigned int i;\n    w.SetLength(N0);\n    for(i=0; i<N0; i++)\n    {\n        w[i] = conv<ZZ>(rand())%q1;\n    }\n    return w;\n}\n\n\n//==============================================================================\n//Generates a random polynomial of fixed degree\n//==============================================================================\nZZX RandomPoly(const unsigned int degree)\n{\n    unsigned int i;\n    ZZX f;\n    f.SetLength(degree+1);\n    for(i=0; i<=degree; i++)\n    {\n        f[i] = rand();\n    }\n    return f;\n}\n\n\n//==============================================================================\n//Generates a random polynomial of fixed degree and \"approximately\" fixed squared norm\n//==============================================================================\nZZX RandomPolyFixedSqNorm(const ZZ& SqNorm, const unsigned int degree)\n{\n    unsigned int i;\n    ZZ SqNorm0, Ratio;\n    ZZX f;\n    f.SetLength(degree+1);\n\n    RR_t sigma = sqrt( ( (double) conv<double>(SqNorm)/(degree+1) ) );\n\n    for(i=0; i<=degree; i++)\n    {\n        f[i] = conv<ZZ>(Sample3(sigma));\n    }\n    f[degree] |= 1;\n    return f;\n}\n\n", "meta": {"hexsha": "5d3649a536853f8715f3ce8c0bfa5697bb501295", "size": 1423, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Random.cc", "max_stars_repo_name": "Rbehnia/NTRUPEKS", "max_stars_repo_head_hexsha": "780d5ef54baaa6c09386185e4d4fce1dc2e394f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T01:54:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-25T06:55:49.000Z", "max_issues_repo_path": "Random.cc", "max_issues_repo_name": "Rbehnia/NTRUPEKS", "max_issues_repo_head_hexsha": "780d5ef54baaa6c09386185e4d4fce1dc2e394f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Random.cc", "max_forks_repo_name": "Rbehnia/NTRUPEKS", "max_forks_repo_head_hexsha": "780d5ef54baaa6c09386185e4d4fce1dc2e394f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-22T21:39:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-22T21:39:45.000Z", "avg_line_length": 21.2388059701, "max_line_length": 86, "alphanum_fraction": 0.4659170766, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460025, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6386570778782898}}
{"text": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/gamma.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/halfeps.hpp>\n#include <boost/simd/constant/eps.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/five.hpp>\n#include <boost/simd/function/rsqrt.hpp>\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid limit_test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  STF_ULP_EQUAL (bs::gamma(p_t(1))            , p_t(1), 0.5);\n  STF_IEEE_EQUAL(bs::gamma(p_t(0))            , p_t(bs::Inf<T>())        );\n  STF_IEEE_EQUAL(bs::gamma(p_t(bs::Inf<T>())) , bs::Inf<p_t>());\n  STF_IEEE_EQUAL(bs::gamma(p_t(bs::Minf<T>())), p_t(bs::Nan<T>())        );\n}\n\nSTF_CASE_TPL(\"Check gamma limit cases\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n  limit_test<T, N>($);\n  limit_test<T, N/2>($);\n  limit_test<T, N*2>($);\n}\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], b[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = (i%2) ? T(i) : -T(i);\n    b[i] = bs::gamma(a1[i]) ;\n  }\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n\n  STF_ULP_EQUAL(bs::gamma(aa1), bb, 0.5);\n}\n\nSTF_CASE_TPL(\"Check gamma on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n   test<T, N>($);\n   test<T, N/2>($);\n   test<T, N*2>($);\n}\n\n\n\nSTF_CASE_TPL (\" gamma\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::gamma;\n  using p_t = bs::pack<T>;\n\n  using r_t = decltype(gamma(p_t()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, p_t);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(gamma(bs::Minf<p_t>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(gamma(bs::Inf<p_t>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(gamma(bs::Nan<p_t>()), bs::Nan<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(gamma(bs::Zero<p_t>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(gamma(bs::Mzero<p_t>()), bs::Minf<r_t>(), 0);\n  STF_ULP_EQUAL(gamma(p_t(1)), p_t(1), 0);\n  STF_ULP_EQUAL(gamma(p_t(2)), p_t(1), 0);\n  STF_ULP_EQUAL(gamma(p_t(3)), p_t(2), 0);\n  STF_ULP_EQUAL(gamma(p_t(5)), p_t(24), 0);\n }\n", "meta": {"hexsha": "a31acb696f3feeca31831b0cf7508a75fc4b923f", "size": 3027, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/gamma.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "test/function/simd/gamma.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/simd/gamma.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 29.6764705882, "max_line_length": 100, "alphanum_fraction": 0.6029071688, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.638614629815635}}
{"text": "/*! \\file\n  \\brief Boxplot display of two example functions (compared to a 1-D plot).\n*/\n\n// demo_functions_boxplot.cpp\n\n// Copyright Paul A. Bristow 2008, 2009, 2021\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n#include <boost/svg_plot/svg_1d_plot.hpp> // For 1d plots.\n#include <boost/svg_plot/svg_boxplot.hpp>  // For boxplots.\n\n#include <vector>  // using std::vector as container for two function's data values.\n#include <cmath> // using ::sin;\n#include <iostream> // using std::cout; std::endl;\n\n//[boxplot_functions_1\n\n/*` Two example functions to show how they display as a 1-D plot and as a boxplot.\nOne function is effectively 1/x and the other is effectively sin(x), \nbut both are scaled to avoid too much overlap when displayed as a 1-D plot.\n*/\n\n// Effectively 1/x\ndouble f(double x)\n{\n    return 50 / (x);\n}\n\n// Effectively sin(x)\ndouble g(double x)\n{\n    return 60 + 25 * ::sin(x * 50);\n}\n//] [boxplot_functions_1]\n\nint main()\n{\n  using namespace boost::svg;  // For SVG colors.\n  try\n  {\n\n    std::vector<double> data1, data2;  // Container for two function data-series values.\n    for(double i = 0.1; i < 10; i += 0.1)\n    { // Fill our vectors with 100 values:\n      double fv = f(i);\n      double gv = g(i);\n      //std::cout << i << ' ' << fv << ' ' << gv << std::endl; // Optionally display values?\n      data1.push_back(fv);\n      data2.push_back(gv);\n    }\n\n    // First display as a 1D plot.\n    svg_1d_plot my_1d_plot;  // To hold a SVG 1-D plot.\n    my_1d_plot.title(\" 1D plots of example sin functions\")\n      .background_border_color(cyan)\n      .x_min(0).x_max(100.) // Range of values shown on plot.\n      .x_major_tick(10);\n\n    my_1d_plot.plot(data1, \"[50 / x]\").stroke_color(blue);  // 1/x function.\n    my_1d_plot.plot(data2, \"[60 + 25 * sin(50x)]\").stroke_color(red); // sin(x) function.\n\n    my_1d_plot.write(\"./demo_functions_1d_plot.svg\");  // Write out the plot.\n\n    // Repeat display as a boxplot.\n      svg_boxplot my_boxplot; // To hold a SVG boxplot.\n\n    my_boxplot.title(\"Boxplots of 1/x and sin(x) Functions\")\n      .background_border_color(magenta)\n      .x_label(\"Functions\")\n      .y_label(\"Population Size\");\n\n    my_boxplot.y_range(0, 100).y_major_interval(20); // Axis information.\n\n    my_boxplot.plot(data1, \"[50 / x]\"); // 1/x function.\n    my_boxplot.plot(data2, \"[60 + 25 * sin(50x)]\"); // sin(x) function.\n\n    my_boxplot.write(\"./demo_functions_boxplot.svg\");  // Write out the plot.\n  }\n  catch (const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n  \" << e.what() << std::endl;\n    return EXIT_FAILURE;\n  }\n  return EXIT_SUCCESS;\n} // int main()\n", "meta": {"hexsha": "e8df77964c680385e0737ac30becd5ceb3832925", "size": 3100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_functions_boxplot.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_functions_boxplot.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_functions_boxplot.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 31.6326530612, "max_line_length": 92, "alphanum_fraction": 0.6596774194, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.6386146274164314}}
{"text": "#include \"mex.h\"        // to compile in Matlab\n#include <iostream> \t// to check outputs here and there\n#include <cstdlib>    \t// to use srand (if you uncomment the relevant line)\n#include <string>   \t// to read in the kernel name\n#include <vector>       // to construct the index list\n#include <map>\t    \t// to map kernels to integers for the switch\n#include <Eigen/Core>   // to use basic Eigen structures\nusing namespace Eigen;\nusing namespace std; \n\n//Commented lines contain various checks on integrity\n\n//Date of last editing: Saturday 8th of September 2012\n\nfloat LinearInterpolation (VectorXf X , VectorXf Y, float X_PointOfInterest){\n//Produce Y_point_of_interest given X,Y and target X_point_of_interest\n//X : vector containing the X variables of the interpolant \n//Y : vector containing the Y variables of the interpolant \n//PointOfInterest : Point of X to estimate the new point of Y\n    \n  float   xk, xkp1, yk, ykp1;  //Points adjecent to the point of interpolation\n  if ( X.size() != Y.size() ){cout << \"Problem with vector sizes\" << endl; return(-1);}\n//cout <<  \" X(0): \" <<  X(0) <<\" X(Y.size()-1): \" <<X(Y.size()-1)   <<   \" Point of interest: \" << X_PointOfInterest<< endl;\n  if ( X_PointOfInterest < X(0) || X_PointOfInterest > X(Y.size()-1) ){cout << \"You interpolate out of the curve boundaries\" << endl; return(-1);}\n//Find the points right before and right after the point of interest\n  for (int i=1; i<X.size() ; i++){\n    if (X(i)>= X_PointOfInterest){\n      xkp1 = X(i);\n      xk = X(i-1);\n      ykp1 = Y(i);\n      yk = Y(i-1);\n      break;}\n  }\n//point-slope form for a line formula\n  float t = (X_PointOfInterest -xk)/(xkp1 -xk);\n  float yPOI = (1-t) * yk + t * ykp1;  // estimate point of interest\n// cout << \"(\" << xk << \",  \" << X_PointOfInterest << \" , \" << xkp1 << \") & (\" << yk << \", \" << yPOI  << \", \" << ykp1 << \")\"<< endl;\n  return (yPOI);   \n} \n\nVectorXf fnvalspapi(VectorXf X, VectorXf Y, VectorXf X_target){\n  //evaluate Y_target for X_target given X and Y\n    \n\tint N =  X_target.size();\n\tVectorXf rr(N); \n\tfor (int i=0; i<N ; i++){  \n      rr(i) =  LinearInterpolation(X, Y, X_target(i)) ;  }\n\treturn(rr);\n}\n\nint MonotonicityCheck(VectorXf X){\n   // evaluate vector monotonicity of vector X\n   int N =  X.size(); \n   for (int i=0; i<(N-1) ; i++){  \n     if ( X(i) >X (1+i) ) return (-1);   }\n   return (1);\n}\n\nfloat rttemp1( VectorXf t_reg,  VectorXf curvei, VectorXf curvek,int nknots, float lambda, VectorXf initial){\n  //Calculate the cost of the given warping\n  // t_reg  : time grid of y_reg\n  // curvei : query curve\n  // curvek : reference curve\n  // nknots : number of knots\n  // lambda : time distortion penalty parameter\n  // initial: position of knots on the simplex \n    \n  int N = t_reg.size();\n  VectorXf struct_ = VectorXf::LinSpaced( nknots+2, t_reg(0)  , t_reg.maxCoeff() ); \n  VectorXf hik(N);\n  VectorXf Q(2+ initial.size()) ;           //Solution with the placement of the knots on the simplex\n  Q(0) = t_reg(0) ; Q(1+ initial.size()) = t_reg.maxCoeff()  ; Q.segment(1, initial.size()) = initial;\n  hik =  fnvalspapi( struct_, Q , t_reg);   // compute the new internal time-scale  \n  \n  //cout << \"hik: \" << hik.transpose() << endl;\n  //cout << \"Monotonicity Checked on Hik: \" << MonotonicityCheck(hik) << endl;\n  //if(  MonotonicityCheck(hik) == -1) { cout <<\" Q.transpose()  is :\"<< Q.transpose()  << endl;}\n  \n  return ( (fnvalspapi(t_reg,curvei,hik)-fnvalspapi(t_reg,curvek ,t_reg)).array().pow(2).sum() + lambda * (hik - t_reg).array().pow(2).sum() );\n}\n\nVectorXf NewSolution( VectorXf x0 , float Step, int point, VectorXf t_reg){ \n    //generate new solution on the simplex defined in [t_reg(0)-x0-t_reg(N-1)] using a displacement of size Step\n    // x0   : initial solution\n    // Step : displacement size\n    // point: knot to perturb\n    // t_reg: time_grid\n    \n    VectorXf InitConf (2+ x0.size());\n    InitConf(0) = t_reg(0); InitConf( x0.size()+1) = t_reg.maxCoeff()  ; InitConf.segment(1, x0.size()) = x0; \n    float LowBou =  InitConf(point-1);\n    float UppBou =  InitConf(point+1);\n    float New_State = (UppBou - LowBou) * Step + LowBou; \n    InitConf(point) = New_State; \n    //if (  MonotonicityCheck( InitConf.segment(1, x0.size()) ) == -1) { \n    //    cout << \"We generated a unacceptable solutiion\" << endl << \"Initial seed was : \" << x0.transpose() \n    //         << endl << \" and we produced :\"<<InitConf.segment(1, x0.size()).transpose() << endl;}\n    return (InitConf.segment(1, x0.size()) ) ;\n  } \n    \n//====\ntypedef struct { float Val; VectorXf Mapping;} rthink_Output; //define structure that holds the results.\n//====\n\nrthink_Output rthik_SA(VectorXf t_reg,  VectorXf curvei, VectorXf curvek,int nknots, float lambda){\n  // Random Search solver for the optimization problem of pairwise warping\n  // t_reg : time_grid\n  // curvei: query curve\n  // curvek: reference curve \n  // nknots : number of knots\n  // lambda : time distortion penalty parameter\n    \n  int k=0; float OldSol, bk; \n  VectorXf xk(nknots);   \n  bk = (t_reg.maxCoeff() - t_reg(0))/(1+ float(nknots ));   //Distance between adjacent knots and edges-knots\n  xk  = VectorXf::LinSpaced(nknots , t_reg(0) + bk  ,  - bk + t_reg.maxCoeff()  ); //Initial candidate solution with equispaced knots \n  VectorXf xn(nknots);   VectorXf help(2+nknots); \n \n  float NewSol; \n  OldSol =  rttemp1(t_reg, curvei, curvek, nknots , lambda, xk);  //Cost of initial solution\n  int z= 99*nknots;                                               //Number of random search to do (proportional to the # of knots)\n  //srand(1);                                                     //Fix the seed to have reproducable behaviour\n  VectorXf Steps(z); Steps = (ArrayXf::Random(z)+1.)/2.;          //Generate possible random pertubations magnitude\n  VectorXi Posit(z); for (int u=0; u <z; u++ ) Posit(u) =1+ rand()%(nknots+0); //Generate list of positions to purturb\n \n  k=0;\n  while((OldSol > .0001) && (k<z)) {\n    xn = NewSolution(xk,Steps(k), Posit(k), t_reg );              //Get a new solution\n    NewSol = rttemp1(t_reg, curvei, curvek, nknots, lambda, xn);  //Cost of new solution\n    if (  (NewSol < OldSol)  ) {                                  //If it's better than the old one, use it.\n      OldSol= NewSol; xk= xn; \n    }\n  k++;\n}\n\n  VectorXf x3 =  VectorXf::LinSpaced(2+nknots, t_reg(0), t_reg( t_reg.size()-1)); \n  help(0) =  t_reg(0) ; help(nknots+1) = t_reg( t_reg.size()-1) ; help.segment(1,nknots) = xk;  \n\n  rthink_Output G;\n  G.Val = OldSol;\n  G.Mapping = fnvalspapi(  x3 , help  , t_reg);\n  return G ;\n}\n\n//Use with syntax :  [hik(indd,:),ftemp]=rthik_E( curvei.coefs,curvek.coefs,t_reg,nknots,lambda); \n#define IS_REAL_1D_FULL_DOUBLE(P) (!mxIsComplex(P) && mxGetNumberOfDimensions(P) == 2 && !mxIsSparse(P) && mxIsDouble(P))\n\nvoid mexFunction (int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) \n{    \n    #define p_curvei\tprhs[0]  \n\t#define p_curvek\tprhs[1]  \n\t#define p_treg\t\tprhs[2]  \n\t#define p_knots\t\tprhs[3]  \n\t#define p_lambda\tprhs[4]  \n               \n    #define p_hik         plhs[0]\n    #define p_f           plhs[1]        \n     \n    if(nrhs != 5)       // Check the number of input arguments  \n    mexErrMsgTxt(\"Wrong number of input arguments.\");            \n    else if(!IS_REAL_1D_FULL_DOUBLE(p_curvei))   //  Check lw\n     mexErrMsgTxt(\"curvei needs be a real 2D full double array.\"); \n    else if(!IS_REAL_1D_FULL_DOUBLE(p_curvek))   //  Check lw\n     mexErrMsgTxt(\"curvek needs be a real 2D full double array.\"); \n    else if(!IS_REAL_1D_FULL_DOUBLE(p_treg))   //  Check lw\n     mexErrMsgTxt(\"t_reg needs be a real 2D full double array.\");   \n   \n   const int LengthOfVector = mxGetN(p_treg); \n   \n   //Read in the variables\n   Map<VectorXd> CurvI(mxGetPr(p_curvei) , LengthOfVector); \n   Map<VectorXd> CurvK(mxGetPr(p_curvek) , LengthOfVector); \n   Map<VectorXd> T_Reg(mxGetPr(p_treg)   , LengthOfVector); \n        \n   int knots = *mxGetPr(p_knots);\n   double lamdba = *mxGetPr(p_lambda);\n   srand(12);    \n   //Past as floats cause really nobody cares about the small digits there.\n   rthink_Output Res = rthik_SA(T_Reg.cast<float>(),CurvI.cast<float>(),CurvK.cast<float>(), knots, float(lamdba));\n   \n  //Declare the outputs \n  p_hik = mxCreateDoubleMatrix(1, LengthOfVector, mxREAL);\n  p_f   = mxCreateDoubleMatrix(1, 1, mxREAL); \n  \n  double *hik = mxGetPr(p_hik );\n  double *f = mxGetPr(p_f );\n  for (int u=0; u< LengthOfVector; u++) { hik[u] = Res.Mapping(u);}\n  f[0] = Res.Val;\n \n}\n", "meta": {"hexsha": "ecc41c311d5aa2c09954a378066d3f516fcc858f", "size": 8466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Frameworks/PACE/PACE-WARP/rthik_E.cpp", "max_stars_repo_name": "ardywibowo/switching-gp", "max_stars_repo_head_hexsha": "23fc6344456dc230816521cc8f218f566cacfbe7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-28T20:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T20:37:37.000Z", "max_issues_repo_path": "Frameworks/PACE/PACE-WARP/rthik_E.cpp", "max_issues_repo_name": "ardywibowo/switching-gp", "max_issues_repo_head_hexsha": "23fc6344456dc230816521cc8f218f566cacfbe7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Frameworks/PACE/PACE-WARP/rthik_E.cpp", "max_forks_repo_name": "ardywibowo/switching-gp", "max_forks_repo_head_hexsha": "23fc6344456dc230816521cc8f218f566cacfbe7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-11T09:50:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T09:50:25.000Z", "avg_line_length": 44.3246073298, "max_line_length": 146, "alphanum_fraction": 0.6279234585, "num_tokens": 2678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6386146227519249}}
{"text": "#include \"RBGL.hpp\"\n#include \"Basic2DMatrix.hpp\"\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/edmonds_karp_max_flow.hpp>\n\nextern \"C\"\n{\n\n#include <Rdefines.h>\n\n    using namespace std;\n    using namespace boost;\n\n    typedef std::set<int> SubgraphAsSet;\n    typedef std::vector< SubgraphAsSet > CliqueVector;\n    typedef std::vector< CliqueVector > ResultCliquesType;\n\n    static void addNewClique(CliqueVector& cliques, int i, int j)\n    {\n        SubgraphAsSet s;\n        s.insert(i);\n        s.insert(j);\n        cliques.push_back(s);\n    }\n\n    static void findAllCliques(ResultCliquesType& rCliques,\n                               Basic2DMatrix<double>& D)\n    {\n        CliqueVector cliques;\n        SubgraphAsSet::iterator s;\n        CliqueVector::iterator ci, cj;\n        int i, j, k, N=0;\n        const int nv = D.numrows();\n\n        // N: max distance in given graph\n        for ( i = 0; i < nv; i++ )\n            for ( j = i+1; j < nv; j++ )\n            {\n                N = max(N, (int)D[i][j]);\n                // each edge is 1-clique\n                if ( D[i][j] == 1 ) addNewClique(cliques, i, j);\n            }\n\n        for ( k = 1; k <= N; k++ )\n        {\n            for ( i = 0; i < nv; i++ )\n            {\n                for ( ci = cliques.begin(); ci != cliques.end(); ci++ )\n                {\n                    // i is already in this clique\n                    if ( (*ci).find(i) != (*ci).end() ) continue;\n\n                    for ( s = (*ci).begin(); s != (*ci).end(); s++ )\n                    {\n                        if ( D[i][*s] > k || D[*s][i] > k ) break;\n                    }\n\n                    // add i to this clique\n                    if ( s == (*ci).end() )\n                    {\n                        (*ci).insert(i);\n\n                        // eliminate its subsequent subsets\n                        for ( cj = ci + 1; cj != cliques.end(); )\n                        {\n                            if (includes((*ci).begin(), (*ci).end(),\n                                         (*cj).begin(), (*cj).end()) )\n                                cj = cliques.erase(cj);\n                            else\n                                cj++;\n                        }\n                    }\n                }\n            }\n            rCliques.push_back(cliques);\n        }\n\n#if DEBUG\n        cout << \" Cliques: \" << endl;\n        for ( i = 0; i < rCliques.size(); i++ )\n        {\n            cout << i+1 << \" cliques: \" << endl;\n            for ( ci=rCliques[i].begin(); ci!=rCliques[i].end(); ci++ )\n            {\n                cout << \"    \";\n                for ( s = (*ci).begin(); s != (*ci).end(); s++ )\n                    cout << (*s)+1 << \" \";\n                cout << endl;\n            }\n        }\n#endif\n    }\n\n    SEXP kCliques(SEXP num_verts_in, SEXP num_edges_in,\n                  SEXP R_edges_in, SEXP R_weights_in)\n    {\n        // R_weights_in has to be INTEGER now\n        int nv = INTEGER(num_verts_in)[0];\n\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n        Basic2DMatrix<double> D(nv, nv);\n\n        // find out the shortest distance between any two nodes\n        johnson_all_pairs_shortest_paths(g, D);\n\n        // find k-cliques now\n        ResultCliquesType rCliques;\n        findAllCliques(rCliques, D);\n\n        ResultCliquesType::iterator ci;\n        CliqueVector::iterator vi;\n        SubgraphAsSet::iterator si;\n        int i, j, k;\n\n        SEXP ansList, cList, sList;\n        PROTECT(ansList = allocVector(VECSXP, (int)rCliques.size()));\n\n        for ( i = 0, ci = rCliques.begin(); ci != rCliques.end(); i++, ci++)\n        {\n            PROTECT(cList = allocVector(VECSXP, (*ci).size()));\n            for ( j = 0, vi = (*ci).begin(); vi != (*ci).end(); j++, vi++ )\n            {\n                PROTECT(sList = allocVector(INTSXP, (*vi).size()));\n                for ( k = 0, si = (*vi).begin(); si != (*vi).end(); k++, si++ )\n                {\n                    INTEGER(sList)[k] = *si;\n                }\n                SET_VECTOR_ELT(cList,j,sList);\n                UNPROTECT(1);\n            }\n            SET_VECTOR_ELT(ansList,i,cList);\n            UNPROTECT(1);\n        }\n        UNPROTECT(1);\n        return(ansList);\n    }\n\n    SEXP lambdaSets(SEXP num_verts_in, SEXP num_edges_in,\n                    SEXP R_edges_in, SEXP R_capacity_in)\n    {\n        using namespace boost;\n\n        typedef adjacency_list_traits<vecS, vecS, directedS> Tr;\n        typedef Tr::edge_descriptor Tr_edge_desc;\n\n        typedef adjacency_list<vecS, vecS, directedS, no_property,\n        property<edge_capacity_t, double,\n        property<edge_residual_capacity_t, double,\n        property<edge_reverse_t, Tr_edge_desc> > > >\n        FlowGraph;\n\n        typedef graph_traits<FlowGraph>::vertex_descriptor vertex_descriptor;\n\ttypedef graph_traits<FlowGraph>::edge_descriptor edge_descriptor;\n\n        FlowGraph flow_g;\n\n        property_map < FlowGraph, edge_capacity_t >::type\n        cap = get(edge_capacity, flow_g);\n        property_map < FlowGraph, edge_residual_capacity_t >::type\n        res_cap = get(edge_residual_capacity, flow_g);\n        property_map < FlowGraph, edge_reverse_t >::type\n        rev_edge = get(edge_reverse, flow_g);\n\n        edge_descriptor e1, e2;\n        bool in1, in2;\n\n        if (!isInteger(R_edges_in)) error(\"R_edges_in should be integer\");\n\n        int NV = INTEGER(num_verts_in)[0];\n        int NE = asInteger(num_edges_in);\n        int* edges_in = INTEGER(R_edges_in);\n\tint i, j, k, MaxC=0; \n\n        for (i = 0; i < NE ; i++, edges_in += 2)\n        {\n            tie(e1, in1) = boost::add_edge(*edges_in, *(edges_in+1), flow_g);\n            tie(e2, in2) = boost::add_edge(*(edges_in+1), *edges_in, flow_g);\n            if ( !in1 || !in2 )\n                error(\"unable to add edge: (%d, %d)\", *edges_in, *(edges_in+1));\n\n            // fill in capacity_map\n            cap[e1] = 1; \n            cap[e2] = 1; \n\n            // fill in reverse_edge_map\n            rev_edge[e1] = e2;\n            rev_edge[e2] = e1;\n        }\n\n        // ASSUMPTION: max_flow(u, v) = max_flow(v, u)\n        // compute edge connectivities between u and v, (u < v)\n\t// we only need lower-left triangle of the matrix w/o diagonal\n        Basic2DMatrix<int> CC(NV, NV);\n\n        for ( i = 0; i < NV; i++ )\n        {\n            vertex_descriptor s = vertex(i, flow_g);\n\n            for ( j = 0; j < i; j++ )\n            {\n                vertex_descriptor t = vertex(j, flow_g);\n\n                CC[i][j] = (int)edmonds_karp_max_flow(flow_g, s, t);\n                MaxC = max(MaxC, CC[i][j]);\n            }\n        }\n\n        // calc lambda sets by successively partition V\n        Basic2DMatrix<int> P(MaxC+1, NV);\n        for ( k = 0; k <= MaxC; k++ )\n        {\n            for ( i = 0; i < NV; i++ ) P[k][i] = i;\n\n            for ( i = 1; i < NV; i++ )\n                for ( j = 0; j < i; j++ )\n                    if ( CC[i][j] >= k )  P[k][i] = P[k][j];\n        }\n\n#if DEBUG\n        cout << \" edge-connectivity matrix: \" << endl;\n        for ( i = 0; i < NV; i++ )\n        {\n            for ( j = 0; j < NV; j++ ) cout << CC[i][j] << \" \";\n            cout << endl;\n        }\n\n        cout << \" P matrix: \" << endl;\n        for ( k = 0; k <= MaxC; k++ )\n        {\n            cout << \" k = \" << k << \": \";\n            for ( j = 0; j < NV; j++ ) cout << P[k][j] << \" \";\n            cout << endl;\n        }\n#endif\n\n        SEXP ansList, conn, eList;\n        PROTECT(ansList = allocVector(VECSXP,2));\n        PROTECT(conn = NEW_NUMERIC(1));\n        PROTECT(eList = allocMatrix(INTSXP, MaxC+1, NV));\n\n        REAL(conn)[0] = MaxC;\n\n        for ( i = 0, j = 0; j < NV; j++ )\n            for ( k = 0; k <= MaxC; k++ )\n                INTEGER(eList)[i++] = P[k][j];\n\n        SET_VECTOR_ELT(ansList,0,conn);\n        SET_VECTOR_ELT(ansList,1,eList);\n        UNPROTECT(3);\n\n        return(ansList);\n    }\n}\n\n", "meta": {"hexsha": "9313680aa5e051d41f75b21044475c4dd7199452", "size": 7947, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sna.cpp", "max_stars_repo_name": "cran/RBGL", "max_stars_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-29T11:20:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-29T11:20:31.000Z", "max_issues_repo_path": "src/sna.cpp", "max_issues_repo_name": "cran/RBGL", "max_issues_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sna.cpp", "max_forks_repo_name": "cran/RBGL", "max_forks_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.04296875, "max_line_length": 80, "alphanum_fraction": 0.4626903234, "num_tokens": 2106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6386146227519249}}
{"text": "#include <stan/math/prim.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n#include <limits>\n#include <vector>\n\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\n\nTEST(ProbDistributionsMultinomialLogit, RNGSize) {\n  boost::random::mt19937 rng;\n  Matrix<double, Dynamic, 1> beta(5);\n  beta << log(0.3), log(0.1), log(0.2), log(0.2), log(0.2);\n  std::vector<int> sample = stan::math::multinomial_logit_rng(beta, 10, rng);\n  EXPECT_EQ(5U, sample.size());\n}\n\nTEST(ProbDistributionsMultinomialLogit, MultinomialLogit) {\n  std::vector<int> ns;\n  ns.push_back(1);\n  ns.push_back(2);\n  ns.push_back(3);\n  Matrix<double, Dynamic, 1> beta(3, 1);\n  beta << log(0.2), log(0.3), log(0.5);\n  EXPECT_FLOAT_EQ(-2.002481, stan::math::multinomial_logit_log(ns, beta));\n}\nTEST(ProbDistributionsMultinomialLogit, Propto) {\n  std::vector<int> ns;\n  ns.push_back(1);\n  ns.push_back(2);\n  ns.push_back(3);\n  Matrix<double, Dynamic, 1> beta(3, 1);\n  beta << log(0.2), log(0.3), log(0.5);\n  EXPECT_FLOAT_EQ(0.0, stan::math::multinomial_logit_log<true>(ns, beta));\n}\n\nusing stan::math::multinomial_logit_log;\n\nTEST(ProbDistributionsMultinomialLogit, error) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  double inf = std::numeric_limits<double>::infinity();\n\n  std::vector<int> ns;\n  ns.push_back(1);\n  ns.push_back(2);\n  ns.push_back(3);\n  Matrix<double, Dynamic, 1> beta(3, 1);\n  beta << log(0.2), log(0.3), log(0.5);\n\n  EXPECT_NO_THROW(multinomial_logit_log(ns, beta));\n\n  ns[1] = 0;\n  EXPECT_NO_THROW(multinomial_logit_log(ns, beta));\n  ns[1] = -1;\n  EXPECT_THROW(multinomial_logit_log(ns, beta), std::domain_error);\n  ns[1] = 1;\n\n  beta(0) = nan;\n  EXPECT_THROW(multinomial_logit_log(ns, beta), std::domain_error);\n  beta(0) = inf;\n  EXPECT_THROW(multinomial_logit_log(ns, beta), std::domain_error);\n  beta(0) = -inf;\n  EXPECT_THROW(multinomial_logit_log(ns, beta), std::domain_error);\n\n  beta(0) = 0.2;\n  beta(1) = 0.3;\n  beta(2) = 0.5;\n\n  ns.resize(2);\n  EXPECT_THROW(multinomial_logit_log(ns, beta), std::invalid_argument);\n}\n\nTEST(ProbDistributionsMultinomialLogit, zeros) {\n  double result;\n  std::vector<int> ns;\n  ns.push_back(0);\n  ns.push_back(1);\n  ns.push_back(2);\n  Matrix<double, Dynamic, 1> beta(3, 1);\n  beta << log(0.2), log(0.3), log(0.5);\n\n  result = multinomial_logit_log(ns, beta);\n  EXPECT_FALSE(std::isnan(result));\n\n  std::vector<int> ns2;\n  ns2.push_back(0);\n  ns2.push_back(0);\n  ns2.push_back(0);\n\n  double result2 = multinomial_logit_log(ns2, beta);\n  EXPECT_FLOAT_EQ(0.0, result2);\n}\n\nTEST(ProbDistributionsMultinomialLogit, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int M = 10;\n  int trials = 1000;\n  int N = M * trials;\n\n  int K = 3;\n  Matrix<double, Dynamic, 1> beta(K);\n  beta << -1, 1, -10;\n  Eigen::VectorXd theta = stan::math::softmax(beta);\n  boost::math::chi_squared mydist(K - 1);\n\n  double expect[K];\n  for (int i = 0; i < K; ++i)\n    expect[i] = N * theta(i);\n\n  int bin[K];\n  for (int i = 0; i < K; ++i)\n    bin[i] = 0;\n\n  for (int count = 0; count < M; ++count) {\n    std::vector<int> a = stan::math::multinomial_logit_rng(beta, trials, rng);\n    for (int i = 0; i < K; ++i)\n      bin[i] += a[i];\n  }\n\n  double chi = 0;\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j])) / expect[j];\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n", "meta": {"hexsha": "199882085873e372397ffc972f175b42333a0d6a", "size": 3391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/multinomial_logit_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math/prim/prob/multinomial_logit_test.cpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/prim/prob/multinomial_logit_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 26.7007874016, "max_line_length": 78, "alphanum_fraction": 0.6579180183, "num_tokens": 1178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424256566558, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6386146058263505}}
{"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#define BOOST_TEST_MODULE lanczos_smoothing_test\n\n#include <random>\n#include <array>\n#include <boost/range.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/differentiation/lanczos_smoothing.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/math/special_functions/next.hpp> // for float_distance\n#include <boost/math/tools/condition_numbers.hpp>\n\nusing std::abs;\nusing std::pow;\nusing std::sqrt;\nusing std::sin;\nusing boost::math::constants::two_pi;\nusing boost::multiprecision::cpp_bin_float_50;\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::math::differentiation::discrete_lanczos_derivative;\nusing boost::math::differentiation::detail::discrete_legendre;\nusing boost::math::differentiation::detail::interior_velocity_filter;\nusing boost::math::differentiation::detail::boundary_velocity_filter;\nusing boost::math::tools::summation_condition_number;\n\ntemplate<class Real>\nvoid test_dlp_norms()\n{\n    std::cout << \"Testing Discrete Legendre Polynomial norms on type \" << typeid(Real).name() << \"\\n\";\n    Real tol = std::numeric_limits<Real>::epsilon();\n    auto dlp = discrete_legendre<Real>(1, Real(0));\n    BOOST_CHECK_CLOSE_FRACTION(dlp.norm_sq(0), 3, tol);\n    BOOST_CHECK_CLOSE_FRACTION(dlp.norm_sq(1), 2, tol);\n    dlp = discrete_legendre<Real>(2, Real(0));\n    BOOST_CHECK_CLOSE_FRACTION(dlp.norm_sq(0), Real(5)/Real(2), tol);\n    BOOST_CHECK_CLOSE_FRACTION(dlp.norm_sq(1), Real(5)/Real(4), tol);\n    BOOST_CHECK_CLOSE_FRACTION(dlp.norm_sq(2), Real(3*3*7)/Real(pow(2,6)), 2*tol);\n    dlp = discrete_legendre<Real>(200, Real(0));\n    for(size_t r = 0; r < 10; ++r)\n    {\n        Real calc = dlp.norm_sq(r);\n        Real expected = Real(2)/Real(2*r+1);\n        // As long as r << n, ||q_r||^2 -> 2/(2r+1) as n->infty\n        BOOST_CHECK_CLOSE_FRACTION(calc, expected, 0.05);\n    }\n\n}\n\ntemplate<class Real>\nvoid test_dlp_evaluation()\n{\n    std::cout << \"Testing evaluation of Discrete Legendre polynomials on type \" << typeid(Real).name() << \"\\n\";\n    Real tol = std::numeric_limits<Real>::epsilon();\n    size_t n = 25;\n    Real x = 0.72;\n    auto dlp = discrete_legendre<Real>(n, x);\n    Real q0 = dlp(x, 0);\n    BOOST_TEST(q0 == 1);\n    Real q1 = dlp(x, 1);\n    BOOST_TEST(q1 == x);\n    Real q2 = dlp(x, 2);\n    int N = 2*n+1;\n    Real expected = 0.5*(3*x*x - Real(N*N - 1)/Real(4*n*n));\n    BOOST_CHECK_CLOSE_FRACTION(q2, expected, tol);\n    Real q3 = dlp(x, 3);\n    expected = (x/3)*(5*expected - (Real(N*N - 4))/(2*n*n));\n    BOOST_CHECK_CLOSE_FRACTION(q3, expected, 2*tol);\n\n    // q_r(x) is even for even r, and odd for odd r:\n    for (size_t n = 8; n < 22; ++n)\n    {\n        dlp = discrete_legendre<Real>(n, x);\n        for(size_t r = 2; r <= n; ++r)\n        {\n            if (r & 1)\n            {\n                Real q1 = dlp(x, r);\n                Real q2 = -dlp(-x, r);\n                BOOST_CHECK_CLOSE_FRACTION(q1, q2, tol);\n            }\n            else\n            {\n                Real q1 = dlp(x, r);\n                Real q2 = dlp(-x, r);\n                BOOST_CHECK_CLOSE_FRACTION(q1, q2, tol);\n            }\n\n            Real l2_sq = 0;\n            for (int j = -(int)n; j <= (int) n; ++j)\n            {\n                Real y = Real(j)/Real(n);\n                Real term = dlp(y, r);\n                l2_sq += term*term;\n            }\n            l2_sq /= n;\n            Real l2_sq_expected = dlp.norm_sq(r);\n            BOOST_CHECK_CLOSE_FRACTION(l2_sq, l2_sq_expected, 20*tol);\n        }\n    }\n}\n\ntemplate<class Real>\nvoid test_dlp_next()\n{\n    std::cout << \"Testing Discrete Legendre polynomial 'next' function on type \" << typeid(Real).name() << \"\\n\";\n    Real tol = std::numeric_limits<Real>::epsilon();\n\n    for(size_t n = 2; n < 20; ++n)\n    {\n        for(Real x = -1; x <= 1; x += 0.1)\n        {\n            auto dlp = discrete_legendre<Real>(n, x);\n            for (size_t k = 2; k < n; ++k)\n            {\n                BOOST_CHECK_CLOSE(dlp.next(), dlp(x, k), tol);\n            }\n\n            dlp = discrete_legendre<Real>(n, x);\n            for (size_t k = 2; k < n; ++k)\n            {\n                BOOST_CHECK_CLOSE(dlp.next_prime(), dlp.prime(x, k), tol);\n            }\n        }\n    }\n}\n\n\ntemplate<class Real>\nvoid test_dlp_derivatives()\n{\n    std::cout << \"Testing Discrete Legendre polynomial derivatives on type \" << typeid(Real).name() << \"\\n\";\n    Real tol = 10*std::numeric_limits<Real>::epsilon();\n    int n = 25;\n    Real x = 0.72;\n    auto dlp = discrete_legendre<Real>(n, x);\n    Real q0p = dlp.prime(x, 0);\n    BOOST_TEST(q0p == 0);\n    Real q1p = dlp.prime(x, 1);\n    BOOST_TEST(q1p == 1);\n    Real q2p = dlp.prime(x, 2);\n    Real expected = 3*x;\n    BOOST_CHECK_CLOSE_FRACTION(q2p, expected, tol);\n}\n\ntemplate<class Real>\nvoid test_dlp_second_derivative()\n{\n    std::cout << \"Testing Discrete Legendre polynomial derivatives on type \" << typeid(Real).name() << \"\\n\";\n    int n = 25;\n    Real x = Real(1)/Real(3);\n    auto dlp = discrete_legendre<Real>(n, x);\n    Real q2pp = dlp.next_dbl_prime();\n    BOOST_TEST(q2pp == 3);\n}\n\n\ntemplate<class Real>\nvoid test_interior_velocity_filter()\n{\n    using boost::math::constants::half;\n    std::cout << \"Testing interior filter on type \" << typeid(Real).name() << \"\\n\";\n    Real tol = std::numeric_limits<Real>::epsilon();\n    for(int n = 1; n < 10; ++n)\n    {\n        for (int p = 1; p < n; p += 2)\n        {\n            auto f = interior_velocity_filter<Real>(n,p);\n            // Since we only store half the filter coefficients,\n            // we need to reindex the moment sums:\n            auto cond = summation_condition_number<Real>(0);\n            for (size_t j = 0; j < f.size(); ++j)\n            {\n                cond += j*f[j];\n            }\n            BOOST_CHECK_CLOSE_FRACTION(cond.sum(), half<Real>(), 2*cond()*tol);\n\n            for (int l = 3; l <= p; l += 2)\n            {\n                cond = summation_condition_number<Real>(0);\n                for (size_t j = 0; j < f.size() - 1; ++j)\n                {\n                    cond += pow(Real(j), l)*f[j];\n                }\n                Real expected = -pow(Real(f.size() - 1), l)*f[f.size()-1];\n                BOOST_CHECK_CLOSE_FRACTION(expected, cond.sum(), 7*cond()*tol);\n            }\n            //std::cout << \"(n,p) = (\" << n  << \",\" << p << \") = {\";\n            //for (auto & x : f)\n            //{\n            //    std::cout << x << \", \";\n            //}\n            //std::cout << \"}\\n\";\n        }\n    }\n}\n\ntemplate<class Real>\nvoid test_interior_lanczos()\n{\n    std::cout << \"Testing interior Lanczos on type \" << typeid(Real).name() << \"\\n\";\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v(500);\n    std::fill(v.begin(), v.end(), 7);\n\n    for (size_t n = 1; n < 10; ++n)\n    {\n        for (size_t p = 2; p < 2*n; p += 2)\n        {\n            auto dld = discrete_lanczos_derivative(Real(0.1), n, p);\n            for (size_t m = n; m < v.size() - n; ++m)\n            {\n                Real dvdt = dld(v, m);\n                BOOST_CHECK_SMALL(dvdt, tol);\n            }\n            auto dvdt = dld(v);\n            for (size_t m = n; m < v.size() - n; ++m)\n            {\n                BOOST_CHECK_SMALL(dvdt[m], tol);\n            }\n        }\n    }\n\n\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = 7*i+8;\n    }\n\n    for (size_t n = 1; n < 10; ++n)\n    {\n        for (size_t p = 2; p < 2*n; p += 2)\n        {\n            auto dld = discrete_lanczos_derivative(Real(1), n, p);\n            for (size_t m = n; m < v.size() - n; ++m)\n            {\n                Real dvdt = dld(v, m);\n                BOOST_CHECK_CLOSE_FRACTION(dvdt, 7, 2000*tol);\n            }\n            auto dvdt = dld(v);\n            for (size_t m = n; m < v.size() - n; ++m)\n            {\n                BOOST_CHECK_CLOSE_FRACTION(dvdt[m], 7, 2000*tol);\n            }\n        }\n    }\n\n    //std::random_device rd{};\n    //auto seed = rd();\n    //std::cout << \"Seed = \" << seed << \"\\n\";\n    std::mt19937 gen(4172378669);\n    std::normal_distribution<> dis{0, 0.01};\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = 7*i+8 + dis(gen);\n    }\n\n    for (size_t n = 1; n < 10; ++n)\n    {\n        for (size_t p = 2; p < 2*n; p += 2)\n        {\n            auto dld = discrete_lanczos_derivative(Real(1), n, p);\n            for (size_t m = n; m < v.size() - n; ++m)\n            {\n                BOOST_CHECK_CLOSE_FRACTION(dld(v, m), Real(7), Real(0.0042));\n            }\n        }\n    }\n\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = 15*i*i + 7*i+8 + dis(gen);\n    }\n\n    for (size_t n = 1; n < 10; ++n)\n    {\n        for (size_t p = 2; p < 2*n; p += 2)\n        {\n            auto dld = discrete_lanczos_derivative(Real(1), n, p);\n            for (size_t m = n; m < v.size() - n; ++m)\n            {\n                BOOST_CHECK_CLOSE_FRACTION(dld(v,m), Real(30*m + 7), Real(0.00008));\n            }\n        }\n    }\n\n    std::normal_distribution<> dis1{0, 0.0001};\n    Real omega = Real(1)/Real(16);\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = sin(i*omega) + dis1(gen);\n    }\n\n    for (size_t n = 10; n < 20; ++n)\n    {\n        for (size_t p = 3; p < 100 && p < n/2; p += 2)\n        {\n            auto dld = discrete_lanczos_derivative(Real(1), n, p);\n\n            for (size_t m = n; m < v.size() - n && m < n + 10; ++m)\n            {\n                BOOST_CHECK_CLOSE_FRACTION(dld(v,m), omega*cos(omega*m), Real(0.03));\n            }\n        }\n    }\n}\n\ntemplate<class Real>\nvoid test_boundary_velocity_filters()\n{\n    std::cout << \"Testing boundary filters on type \" << typeid(Real).name() << \"\\n\";\n    Real tol = std::numeric_limits<Real>::epsilon();\n    for(int n = 1; n < 5; ++n)\n    {\n        for (int p = 1; p < 2*n+1; ++p)\n        {\n            for (int s = -n; s <= n; ++s)\n            {\n                auto f = boundary_velocity_filter<Real>(n, p, s);\n                // Sum is zero:\n                auto cond = summation_condition_number<Real>(0);\n                for (size_t i = 0; i < f.size() - 1; ++i)\n                {\n                    cond += f[i];\n                }\n\n                BOOST_CHECK_CLOSE_FRACTION(cond.sum(), -f[f.size()-1], 6*cond()*tol);\n\n                cond = summation_condition_number<Real>(0);\n                for (size_t k = 0; k < f.size(); ++k)\n                {\n                    Real j = Real(k) - Real(n);\n                    // note the shifted index here:\n                    cond += (j-s)*f[k];\n                }\n                BOOST_CHECK_CLOSE_FRACTION(cond.sum(), 1, 6*cond()*tol);\n\n\n                for (int l = 2; l <= p; ++l)\n                {\n                    cond = summation_condition_number<Real>(0);\n                    for (size_t k = 0; k < f.size() - 1; ++k)\n                    {\n                        Real j = Real(k) - Real(n);\n                        // The condition number of this sum is infinite!\n                        // No need to get to worked up about the tolerance.\n                        cond += pow(j-s, l)*f[k];\n                    }\n\n                    Real expected = -pow(Real(f.size()-1) - Real(n) - Real(s), l)*f[f.size()-1];\n                    if (expected == 0)\n                    {\n                        BOOST_CHECK_SMALL(cond.sum(), cond()*tol);\n                    }\n                    else\n                    {\n                        BOOST_CHECK_CLOSE_FRACTION(expected, cond.sum(), 200*cond()*tol);\n                    }\n                }\n\n                //std::cout << \"(n,p,s) = (\"<< n << \", \" << p << \",\" << s << \") = {\";\n                //for (auto & x : f)\n                //{\n                //    std::cout << x << \", \";\n                //}\n                //std::cout << \"}\\n\";*/\n            }\n        }\n    }\n}\n\ntemplate<class Real>\nvoid test_boundary_lanczos()\n{\n    std::cout << \"Testing Lanczos boundary on type \" << typeid(Real).name() << \"\\n\";\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v(500, 7);\n\n    for (size_t n = 1; n < 10; ++n)\n    {\n        for (size_t p = 2; p < 2*n; ++p)\n        {\n            auto lsd = discrete_lanczos_derivative(Real(0.0125), n, p);\n            for (size_t m = 0; m < n; ++m)\n            {\n                Real dvdt = lsd(v,m);\n                BOOST_CHECK_SMALL(dvdt, 4*sqrt(tol));\n            }\n            for (size_t m = v.size() - n; m < v.size(); ++m)\n            {\n                Real dvdt = lsd(v,m);\n                BOOST_CHECK_SMALL(dvdt, 4*sqrt(tol));\n            }\n        }\n    }\n\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = 7*i+8;\n    }\n\n    for (size_t n = 3; n < 10; ++n)\n    {\n        for (size_t p = 2; p < 2*n; ++p)\n        {\n            auto lsd = discrete_lanczos_derivative(Real(1), n, p);\n            for (size_t m = 0; m < n; ++m)\n            {\n                Real dvdt = lsd(v,m);\n                BOOST_CHECK_CLOSE_FRACTION(dvdt, 7, sqrt(tol));\n            }\n\n            for (size_t m = v.size() - n; m < v.size(); ++m)\n            {\n                Real dvdt = lsd(v,m);\n                BOOST_CHECK_CLOSE_FRACTION(dvdt, 7, 4*sqrt(tol));\n            }\n        }\n    }\n\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = 15*i*i + 7*i+8;\n    }\n\n    for (size_t n = 1; n < 10; ++n)\n    {\n        for (size_t p = 2; p < 2*n; ++p)\n        {\n            auto lsd = discrete_lanczos_derivative(Real(1), n, p);\n            for (size_t m = 0; m < v.size(); ++m)\n            {\n                BOOST_CHECK_CLOSE_FRACTION(lsd(v,m), 30*m+7, 30*sqrt(tol));\n            }\n        }\n    }\n\n    // Demonstrate that the boundary filters are also denoising:\n    //std::random_device rd{};\n    //auto seed = rd();\n    //std::cout << \"seed = \" << seed << \"\\n\";\n    std::mt19937 gen(311354333);\n    std::normal_distribution<> dis{0, 0.01};\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] += dis(gen);\n    }\n\n    for (size_t n = 1; n < 10; ++n)\n    {\n        for (size_t p = 2; p < n; ++p)\n        {\n            auto lsd = discrete_lanczos_derivative(Real(1), n, p);\n            for (size_t m = 0; m < v.size(); ++m)\n            {\n                BOOST_CHECK_CLOSE_FRACTION(lsd(v,m), 30*m+7, 0.005);\n            }\n            auto dvdt = lsd(v);\n            for (size_t m = 0; m < v.size(); ++m)\n            {\n                BOOST_CHECK_CLOSE_FRACTION(dvdt[m], 30*m+7, 0.005);\n            }\n        }\n    }\n}\n\ntemplate<class Real>\nvoid test_acceleration_filters()\n{\n    Real eps = std::numeric_limits<Real>::epsilon();\n    for (size_t n = 1; n < 5; ++n)\n    {\n        for(size_t p = 3; p <= 2*n; ++p)\n        {\n            for(int64_t s = -int64_t(n); s <= 0; ++s)\n            {\n                auto g = boost::math::differentiation::detail::acceleration_filter<long double>(n,p,s);\n\n                std::vector<Real> f(g.size());\n                for (size_t i = 0; i < g.size(); ++i)\n                {\n                    f[i] = static_cast<Real>(g[i]);\n                }\n\n                auto cond = summation_condition_number<Real>(0);\n\n                for (size_t i = 0; i < f.size() - 1; ++i)\n                {\n                    cond += f[i];\n                }\n                BOOST_CHECK_CLOSE_FRACTION(cond.sum(), -f[f.size()-1], 10*cond()*eps);\n\n\n                cond = summation_condition_number<Real>(0);\n                for (size_t k = 0; k < f.size() -1; ++k)\n                {\n                    Real j = Real(k) - Real(n);\n                    cond += (j-s)*f[k];\n                }\n                Real expected = -(Real(f.size()-1)- Real(n) - s)*f[f.size()-1];\n                BOOST_CHECK_CLOSE_FRACTION(cond.sum(), expected, 10*cond()*eps);\n\n                cond = summation_condition_number<Real>(0);\n                for (size_t k = 0; k < f.size(); ++k)\n                {\n                    Real j = Real(k) - Real(n);\n                    cond += (j-s)*(j-s)*f[k];\n                }\n                BOOST_CHECK_CLOSE_FRACTION(cond.sum(), 2, 100*cond()*eps);\n                // See unlabelled equation in McDevitt, 2012, just after equation 26:\n                // It appears that there is an off-by-one error in that equation, since p + 1 moments don't vanish, only p.\n                // This test is itself suspect; the condition number of the moment sum is infinite.\n                // So the *slightest* error in the filter gets amplified by the test; in terms of the\n                // behavior of the actual filter, it's not a big deal.\n                for (size_t l = 3; l <= p; ++l)\n                {\n                    cond = summation_condition_number<Real>(0);\n                    for (size_t k = 0; k < f.size() - 1; ++k)\n                    {\n                        Real j = Real(k) - Real(n);\n                        cond += pow((j-s), l)*f[k];\n                    }\n                    Real expected = -pow(Real(f.size()- 1 - n -s), l)*f[f.size()-1];\n                    BOOST_CHECK_CLOSE_FRACTION(cond.sum(), expected, 1000*cond()*eps);\n                }\n            }\n        }\n    }\n}\n\ntemplate<class Real>\nvoid test_lanczos_acceleration()\n{\n    Real eps = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v(100, 7);\n    auto lanczos = discrete_lanczos_derivative<Real, 2>(Real(1), 4, 3);\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        BOOST_CHECK_SMALL(lanczos(v, i), eps);\n    }\n\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = 7*i + 6;\n    }\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        BOOST_CHECK_SMALL(lanczos(v,i), 200*eps);\n    }\n\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = 7*i*i + 9*i + 6;\n    }\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(lanczos(v, i), 14, 1500*eps);\n    }\n\n    // Now add noise, and kick up the smoothing of the Lanzcos derivative (increase n):\n    //std::random_device rd{};\n    //auto seed = rd();\n    //std::cout << \"seed = \" << seed << \"\\n\";\n    size_t seed = 2507134629;\n    std::mt19937 gen(seed);\n    Real std_dev = 0.1;\n    std::normal_distribution<Real> dis{0, std_dev};\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] += dis(gen);\n    }\n    lanczos = discrete_lanczos_derivative<Real, 2>(Real(1), 18, 3);\n    auto w = lanczos(v);\n    for (size_t i = 0; i < v.size(); ++i)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(w[i], 14, std_dev/200);\n    }\n}\n\ntemplate<class Real>\nvoid test_rescaling()\n{\n    std::cout << \"Test rescaling on type \" << typeid(Real).name() << \"\\n\";\n    Real tol = std::numeric_limits<Real>::epsilon();\n    std::vector<Real> v(500);\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = 7*i*i + 9*i + 6;\n    }\n    std::vector<Real> dvdt1(500);\n    std::vector<Real> dvdt2(500);\n    auto lanczos1 = discrete_lanczos_derivative(Real(1));\n    auto lanczos2 = discrete_lanczos_derivative(Real(2));\n\n    lanczos1(v, dvdt1);\n    lanczos2(v, dvdt2);\n\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(dvdt1[i], 2*dvdt2[i], tol);\n    }\n\n    auto lanczos3 = discrete_lanczos_derivative<Real, 2>(Real(1));\n    auto lanczos4 = discrete_lanczos_derivative<Real, 2>(Real(2));\n\n\n    std::vector<Real> dv2dt21(500);\n    std::vector<Real> dv2dt22(500);\n\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(dv2dt21[i], 4*dv2dt22[i], tol);\n    }\n}\n\ntemplate<class Real>\nvoid test_data_representations()\n{\n    std::cout << \"Test rescaling on type \" << typeid(Real).name() << \"\\n\";\n    Real tol = 150*std::numeric_limits<Real>::epsilon();\n    std::array<Real, 500> v;\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        v[i] = 9*i + 6;\n    }\n    std::array<Real, 500> dvdt;\n    auto lanczos = discrete_lanczos_derivative(Real(1));\n\n    lanczos(v, dvdt);\n\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(dvdt[i], 9, tol);\n    }\n\n    boost::numeric::ublas::vector<Real> w(500);\n    boost::numeric::ublas::vector<Real> dwdt(500);\n    for(size_t i = 0; i < w.size(); ++i)\n    {\n        w[i] = 9*i + 6;\n    }\n\n    lanczos(w, dwdt);\n\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(dwdt[i], 9, tol);\n    }\n\n    auto v1 = boost::make_iterator_range(v.begin(), v.end());\n    auto v2 = boost::make_iterator_range(dvdt.begin(), dvdt.end());\n    lanczos(v1, v2);\n\n    for(size_t i = 0; i < v2.size(); ++i)\n    {\n        BOOST_CHECK_CLOSE_FRACTION(v2[i], 9, tol);\n    }\n\n    auto lanczos2 = discrete_lanczos_derivative<Real, 2>(Real(1));\n\n    lanczos2(v1, v2);\n\n    for(size_t i = 0; i < v2.size(); ++i)\n    {\n        BOOST_CHECK_SMALL(v2[i], 10*tol);\n    }\n\n}\n\nBOOST_AUTO_TEST_CASE(lanczos_smoothing_test)\n{\n    test_dlp_second_derivative<double>();\n    test_dlp_norms<double>();\n    test_dlp_evaluation<double>();\n    test_dlp_derivatives<double>();\n    test_dlp_next<double>();\n\n    // Takes too long!\n    //test_dlp_norms<cpp_bin_float_50>();\n    test_boundary_velocity_filters<double>();\n    test_boundary_velocity_filters<long double>();\n    // Takes too long!\n    //test_boundary_velocity_filters<cpp_bin_float_50>();\n    test_boundary_lanczos<double>();\n    test_boundary_lanczos<long double>();\n    // Takes too long!\n    //test_boundary_lanczos<cpp_bin_float_50>();\n\n    test_interior_velocity_filter<double>();\n    test_interior_velocity_filter<long double>();\n    test_interior_lanczos<double>();\n\n    test_acceleration_filters<double>();\n\n    test_lanczos_acceleration<float>();\n    test_lanczos_acceleration<double>();\n\n    test_rescaling<double>();\n    test_data_representations<double>();\n}\n", "meta": {"hexsha": "f754f1217b807f1cfd3b116ed13eb054c3f321bd", "size": 21832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/test/lanczos_smoothing_test.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/test/lanczos_smoothing_test.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/test/lanczos_smoothing_test.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 30.7926657264, "max_line_length": 123, "alphanum_fraction": 0.4959692195, "num_tokens": 6369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6386144999745688}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <random>\n#include <set>\n\nconstexpr int seed = 1;\n\nusing Mat33_t = Eigen::Matrix3d;\nusing Vec3_t = Eigen::Vector3d;\nusing Vec2_t = Eigen::Vector2d;\n\ntemplate<typename T>\nusing eigen_vector = std::vector<T, Eigen::aligned_allocator<T>>;\n\neigen_vector<Vec3_t> gen_3Dpoints(const int n) {\n\n    std::mt19937 mt(seed);\n    const double z_dist = 3;\n    const double r = 1;\n    std::uniform_real_distribution<> rand(-r, r);\n\n    eigen_vector<Vec3_t> pts;\n    pts.reserve(n);\n    for (unsigned int i = 0; i < n; i++) {\n        const double x = rand(mt);\n        const double y = rand(mt);\n        const double z = rand(mt) + z_dist;\n        pts.emplace_back(x, y, z);\n    }\n    return pts;\n}\n\ntemplate<typename T>\nvoid generate_keypts(const int num_pts, const double outlier_ratio,\n                     T &kps_1, T &kps_2, std::vector<bool> &is_inliers) {\n\n    double data[9];\n    data[0] = 0.99875035875531126;\n    data[1] = 0.043232155011259037;\n    data[2] = 0.025073923889563768;\n    data[3] = -0.043243275321131029;\n    data[4] = 0.9990645671709939;\n    data[5] = -9.8807568748168046e-05;\n    data[6] = -0.025054740582133875;\n    data[7] = -0.00098559449940248617;\n    data[8] = 0.99968559486362751;\n\n    Mat33_t R(data);\n    Vec3_t t{-0.49, 0.12, -0.05};\n\n    eigen_vector<Vec3_t> pts = gen_3Dpoints(num_pts);\n\n    Mat33_t K;\n    K << 500, 0, 500,\n            0, 500, 250,\n            0, 0, 1;\n\n    kps_1.clear();\n    kps_1.reserve(num_pts);\n    kps_2.clear();\n    kps_2.reserve(num_pts);\n\n    std::mt19937 mt(seed);\n    const double r = 1;\n    std::uniform_real_distribution<> rand(-r, r);\n    const auto try_bernoulli = [&mt](const double p) {\n        std::uniform_real_distribution<> rand(0, 1);\n        return rand(mt) < p;\n    };\n\n    for (const auto &pos_w : pts) {\n\n        const double x = rand(mt);\n        const double y = rand(mt);\n        const double z = rand(mt);\n        const Vec3_t noise{x, y, z};\n\n        const bool is_outlier = try_bernoulli(outlier_ratio);\n\n\n        const Vec3_t &pos_1 = pos_w;\n        const Vec3_t pos_2 = R * pos_w + t\n                             + (is_outlier ? noise : Vec3_t::Zero());\n\n        kps_1.emplace_back((K * pos_1).hnormalized());\n        kps_2.emplace_back((K * pos_2).hnormalized());\n        is_inliers.push_back(!is_outlier);\n    }\n}\n\n// Fundamental solver; Modified version of eightpt solver from opengv\n// Reference:\n// https://github.com/laurentkneip/opengv/blob/91f4b19c73450833a40e463ad3648aae80b3a7f3/src/relative_pose/methods.cpp#L424\ntemplate<typename T>\nMat33_t solve_F(const T &kps_1, const T &kps_2) {\n    const int num_pts = kps_1.size();\n    Eigen::MatrixXd A(num_pts, 9);\n\n    for (unsigned int i = 0; i < num_pts; i++) {\n        A.block<1, 3>(i, 0) = kps_2.at(i)(0) * kps_1.at(i).homogeneous();\n        A.block<1, 3>(i, 3) = kps_2.at(i)(1) * kps_1.at(i).homogeneous();\n        A.block<1, 3>(i, 6) = kps_1.at(i).homogeneous();\n    }\n\n    const Eigen::JacobiSVD<Eigen::MatrixXd> SVD(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    const Eigen::Matrix<Mat33_t::Scalar, 9, 1> f = SVD.matrixV().col(8);\n    Mat33_t F_temp(3, 3);\n    F_temp.row(0) = f.block<3, 1>(0, 0).transpose();\n    F_temp.row(1) = f.block<3, 1>(3, 0).transpose();\n    F_temp.row(2) = f.block<3, 1>(6, 0).transpose();\n\n    const Eigen::JacobiSVD<Mat33_t> SVD2(F_temp, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n    Vec3_t s = SVD2.singularValues();\n    s(2) = 0.0;\n\n    const Mat33_t &U = SVD2.matrixU();\n    const Mat33_t S = s.asDiagonal();\n    const Mat33_t &V_T = SVD2.matrixV().transpose();\n\n    return U * S * V_T;\n}\n\ntemplate<typename T>\nstd::vector<bool> check_inlier(const Mat33_t &F, const T &kps_1, const T &kps_2) {\n    std::vector<bool> inl_flag(kps_1.size(), false);\n    for (int i = 0; i < kps_1.size(); i++) {\n        const double err = kps_2.at(i).homogeneous().dot(F * kps_1.at(i).homogeneous());\n        inl_flag.at(i) = std::abs(err) < 1e-8;\n    }\n    return inl_flag;\n}\n\n\n// Find F matrix by ransac\ntemplate<typename T>\nMat33_t estimate_F(const T &kps_1, const T &kps_2, const int num_trial) {\n    const auto num_pts = kps_1.size();\n    const auto num_sample = std::min<int>(8, num_pts);\n\n    std::uniform_int_distribution<> dist(0, num_pts - 1);\n    std::mt19937 mt(seed);\n\n    Mat33_t F;\n    int max_inl = 0;\n\n    for (unsigned int i = 0; i < num_trial; i++) {\n        std::set<int> sample_id;\n        while (sample_id.size() < num_sample) {\n            sample_id.insert(dist(mt));\n        }\n\n        T smpl1, smpl2;\n        for (const auto id: sample_id) {\n            smpl1.push_back(kps_1.at(id));\n            smpl2.push_back(kps_2.at(id));\n        }\n        const Mat33_t F_cand = solve_F(smpl1, smpl2);\n        const auto inl_flag = check_inlier(F_cand, kps_1, kps_2);\n        const int num_inl = std::count(inl_flag.begin(), inl_flag.end(), true);\n        if (max_inl < num_inl) {\n            max_inl = num_inl;\n            F = F_cand;\n        }\n    }\n\n    return F;\n}\n\ntemplate<typename T>\nvoid print_test_result(const T &is_inliers, const T &inl_flag) {\n    int true_pos = 0;\n    int true_neg = 0;\n    int false_pos = 0;\n    int false_neg = 0;\n\n    const auto num_pts = is_inliers.size();\n    for (int i = 0; i < num_pts; i++) {\n        const bool gt = is_inliers.at(i);\n        const bool est = inl_flag.at(i);\n        if (gt == est) {\n            if (gt) true_pos++;\n            else true_neg++;\n        } else {\n            if (est) false_pos++;\n            else false_neg++;\n        }\n    }\n\n    std::cout << std::endl;\n    std::cout << \"<< Confusion Matrix >>\" << std::endl;\n    std::cout << \" GT \\\\ est | inlier | outlier |\" << std::endl;\n\n    std::cout << \"  inlier  |  \";\n    std::cout << std::setw(4) << true_pos << \"  |  \";\n    std::cout << std::setw(4) << false_neg << \"   |\" << std::endl;\n\n    std::cout << \" outlier  |  \";\n    std::cout << std::setw(4) << false_pos << \"  |  \";\n    std::cout << std::setw(4) << true_neg << \"   |\" << std::endl;\n}\n\nint main() {\n    const int num_pts = 1000;\n    const double outlier_ratio = 0.3;\n\n    // \u30c6\u30b9\u30c8\u7528\u306e\u7279\u5fb4\u70b9\u3068\u5916\u308c\u5024\u304b\u3069\u3046\u304b\u306e\u6b63\u89e3\n    eigen_vector<Vec2_t> kps_1, kps_2;\n    std::vector<bool> is_inliers;\n    generate_keypts(num_pts, outlier_ratio, kps_1, kps_2, is_inliers);\n\n    // F\u884c\u5217\u3092\u63a8\u5b9a\n    // num_trial \u306f (1/(1-outlier_ratio)) ^ 8 \u3088\u308a\u5927\u304d\u304f\n    const Mat33_t F = estimate_F(kps_1, kps_2, 100);\n\n    // \u63a8\u5b9a\u3057\u305fF\u884c\u5217\u3092\u7528\u3044\u3066\u7279\u5fb4\u70b9\u30de\u30c3\u30c1\u306e\u30a4\u30f3\u30e9\u30a4\u30a2\u5224\u5b9a\uff08\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3067\u30de\u30c3\u30c1\uff09\n    const auto inl_flag = check_inlier(F, kps_1, kps_2);\n\n    // F\u884c\u5217\u3092\u7528\u3044\u305f\u30a4\u30f3\u30e9\u30a4\u30a2\u5224\u5b9a\u306e\u7d50\u679c\u306e\u8868\u793a\n    const auto num_inls = std::count(inl_flag.begin(), inl_flag.end(), true);\n    std::cout << \"#inlier: \" << num_inls << std::endl;\n\n    // F\u884c\u5217\u63a8\u5b9a\u306b\u3088\u308b\u5916\u308c\u5024\u691c\u51fa\u306e\u6b63\u5f53\u6027\u306e\u8868\u793a\n    print_test_result(is_inliers, inl_flag);\n}\n", "meta": {"hexsha": "b91fd974a25e558ce6349c700d626d33d89f0037", "size": 6740, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main.cc", "max_stars_repo_name": "MikiyaShibuya/FundamentalMatrix", "max_stars_repo_head_hexsha": "378b3e4985f0f1a8f67c21aff2263accddfa5010", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cc", "max_issues_repo_name": "MikiyaShibuya/FundamentalMatrix", "max_issues_repo_head_hexsha": "378b3e4985f0f1a8f67c21aff2263accddfa5010", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cc", "max_forks_repo_name": "MikiyaShibuya/FundamentalMatrix", "max_forks_repo_head_hexsha": "378b3e4985f0f1a8f67c21aff2263accddfa5010", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5614035088, "max_line_length": 122, "alphanum_fraction": 0.5962908012, "num_tokens": 2300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6386016227658148}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[envelope\r\n//` Shows how to calculate the bounding box of a polygon\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/box.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n\r\n/*<-*/ #include \"create_svg_two.hpp\" /*->*/\r\n\r\nint main()\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<double> point;\r\n\r\n    boost::geometry::model::polygon<point> polygon;\r\n\r\n    boost::geometry::read_wkt(\r\n        \"POLYGON((2 1.3,2.4 1.7,2.8 1.8,3.4 1.2,3.7 1.6,3.4 2,4.1 3,5.3 2.6,5.4 1.2,4.9 0.8,2.9 0.7,2 1.3)\"\r\n            \"(4.0 2.0, 4.2 1.4, 4.8 1.9, 4.4 2.2, 4.0 2.0))\", polygon);\r\n\r\n    boost::geometry::model::box<point> box;\r\n    boost::geometry::envelope(polygon, box);\r\n\r\n    std::cout << \"envelope:\" << boost::geometry::dsv(box) << std::endl;\r\n\r\n    /*<-*/ create_svg(\"envelope.svg\", polygon, box); /*->*/\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[envelope_output\r\n/*`\r\nOutput:\r\n[pre\r\nenvelope:((2, 0.7), (5.4, 3))\r\n\r\n[$img/algorithms/envelope.png]\r\n]\r\n*/\r\n//]\r\n\r\n", "meta": {"hexsha": "5e54b1f8934af0bbe40ec832bd97d0eb38fa4831", "size": 1440, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/envelope.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/envelope.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/envelope.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 25.7142857143, "max_line_length": 108, "alphanum_fraction": 0.6284722222, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.6386016207477879}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"types/ds/hash_functions.hpp\"\n#include <limits>\n#include <iostream>\n\nBOOST_AUTO_TEST_SUITE(TestHashFunctions)\n\n    BOOST_AUTO_TEST_CASE(hash_division_method_m_is_power_of_2)\n    {\n        const size_t num_of_buckets = 16;\n        Types::DS::HashModulo hash_func(num_of_buckets);\n        std::vector<size_t> stat(num_of_buckets, 0);\n        const auto max = static_cast<size_t>(std::numeric_limits<uint8_t>::max());\n        for (size_t i = 0; i < max; ++i) {\n            ++stat[hash_func(i)];\n        }\n\n//        std::cout << \"Test of hash function that uses division method. Num of buckets is \" <<\n//            \"power of 2: \" << num_of_buckets << std::endl;\n//        std::cout << \"Here is statistics that shows how many numbers [0, max(uchar)] would be \" <<\n//            \"assigned to the same bucket\" << std::endl;\n//        for (size_t i = 0; i < stat.size(); ++i) {\n//            std::cout << i << \": \" << stat[i] << std::endl;\n//        }\n    }\n\n    BOOST_AUTO_TEST_CASE(hash_multiplication_method)\n    {\n        const size_t num_of_buckets = 16;\n        Types::DS::HashMultiplication hash_func(num_of_buckets);\n        std::vector<size_t> stat(num_of_buckets, 0);\n        const auto max = static_cast<size_t>(std::numeric_limits<uint8_t>::max());\n        for (size_t i = 0; i < max; ++i) {\n            ++stat[hash_func(i)];\n        }\n\n//        std::cout << \"Test of hash function that uses multiplication method. Num of buckets is \" <<\n//                  \"power of 2: \" << num_of_buckets << std::endl;\n//        std::cout << \"Here is statistics that shows how many numbers [0, max(uchar)] would be \" <<\n//                  \"assigned to the same bucket\" << std::endl;\n//        for (size_t i = 0; i < stat.size(); ++i) {\n//            std::cout << i << \": \" << stat[i] << std::endl;\n//        }\n    }\n\n    BOOST_AUTO_TEST_CASE(hash_multiply_shift_method)\n    {\n        const size_t num_of_buckets = 16;\n        Types::DS::HashMultiplyShift hash_func(num_of_buckets);\n        std::vector<size_t> stat(num_of_buckets, 0);\n        const auto max = static_cast<int32_t>(std::numeric_limits<uint8_t>::max());\n        for (int32_t i = 1; i < max; ++i) {\n            ++stat[hash_func(i)];\n        }\n\n//        std::cout << \"Test of hash function that uses multiply-shift method. Num of buckets is \" <<\n//                  \"power of 2: \" << num_of_buckets << std::endl;\n//        std::cout << \"Here is statistics that shows how many numbers [0, max(uchar)] would be \" <<\n//                  \"assigned to the same bucket\" << std::endl;\n//        for (size_t i = 0; i < stat.size(); ++i) {\n//            std::cout << i << \": \" << stat[i] << std::endl;\n//        }\n    }\n\n    BOOST_AUTO_TEST_CASE(hash_multiply_add_shift_method)\n    {\n        const size_t num_of_buckets = 16;\n        Types::DS::HashMultiplyAddShift hash_func(num_of_buckets);\n        std::vector<size_t> stat(num_of_buckets, 0);\n        const auto max = static_cast<int32_t>(std::numeric_limits<uint8_t>::max());\n        for (int32_t i = 1; i < max; ++i) {\n            ++stat[hash_func(i)];\n        }\n\n//        std::cout << \"Test of hash function that uses multiply-add-shift method. Num of buckets is \" <<\n//                  \"power of 2: \" << num_of_buckets << std::endl;\n//        std::cout << \"Here is statistics that shows how many numbers [0, max(uchar)] would be \" <<\n//                  \"assigned to the same bucket\" << std::endl;\n//        for (size_t i = 0; i < stat.size(); ++i) {\n//            std::cout << i << \": \" << stat[i] << std::endl;\n//        }\n    }\n\n    BOOST_AUTO_TEST_CASE(hash_vector)\n    {\n        const size_t num_of_buckets = 16;\n        Types::DS::HashVector hash_func(num_of_buckets);\n        std::vector<size_t> stat(num_of_buckets, 0);\n\n        Types::DS::helpers::RandomGenerator size_generator(10);\n        Types::DS::helpers::RandomGenerator num_generator(8);\n        for (size_t i = 0; i < 100; ++i) {\n            std::vector<int32_t> v(size_generator.generate(), 0);\n            std::generate(\n                v.begin(), v.end(), [&num_generator](){ return num_generator.generate(); });\n\n            ++stat[hash_func(v)];\n        }\n\n//        std::cout << \"Test of hash function for vectors. Num of buckets is \" <<\n//                  \"power of 2: \" << num_of_buckets << std::endl;\n//        std::cout << \"Here is statistics that shows how many vectors would be \" <<\n//                  \"assigned to the same bucket\" << std::endl;\n//        for (size_t i = 0; i < stat.size(); ++i) {\n//            std::cout << i << \": \" << stat[i] << std::endl;\n//        }\n    }\n\n    BOOST_AUTO_TEST_CASE(hash_string)\n    {\n        const size_t num_of_buckets = 16;\n        Types::DS::HashString<char> hash_func(num_of_buckets);\n        std::vector<size_t> stat(num_of_buckets, 0);\n\n        Types::DS::helpers::RandomGenerator size_generator(10);\n        Types::DS::helpers::RandomGenerator char_generator(1, 127);\n        for (size_t i = 0; i < 100; ++i) {\n            std::string s(size_generator.generate(), '0');\n            std::generate(\n                s.begin(), s.end(), [&char_generator](){ return char_generator.generate(); });\n\n            ++stat[hash_func(s)];\n        }\n\n//        std::cout << \"Test of hash function for vectors. Num of buckets is \" <<\n//                  \"power of 2: \" << num_of_buckets << std::endl;\n//        std::cout << \"Here is statistics that shows how many vectors would be \" <<\n//                  \"assigned to the same bucket\" << std::endl;\n//        for (size_t i = 0; i < stat.size(); ++i) {\n//            std::cout << i << \": \" << stat[i] << std::endl;\n//        }\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "9afa474b118d5f1bf12e2e0c00b84fe81b5ad0b9", "size": 5680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/types/ds/test_hash_functions.cpp", "max_stars_repo_name": "iamantony/CppNotes", "max_stars_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T14:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-03T09:51:43.000Z", "max_issues_repo_path": "test/types/ds/test_hash_functions.cpp", "max_issues_repo_name": "iamantony/CppNotes", "max_issues_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T07:38:21.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-02T11:00:58.000Z", "max_forks_repo_path": "test/types/ds/test_hash_functions.cpp", "max_forks_repo_name": "iamantony/CppNotes", "max_forks_repo_head_hexsha": "2707db6560ad80b0e5e286a04b2d46e5c0280b3f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-10-11T14:10:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-27T08:53:50.000Z", "avg_line_length": 42.0740740741, "max_line_length": 105, "alphanum_fraction": 0.5536971831, "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6386016155519556}}
{"text": "/*\n * utilities_cumtrapz_test.cpp Test fixtures for the cumtrapz function\n *\n * Author:                   Tom Clark (thclark @ github)\n *\n * Copyright (c) 2016-9 Octue Ltd. All Rights Reserved.\n *\n */\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\n#include \"utilities/interp.h\"\n\n\nusing namespace utilities;\n\n\nclass InterpTest : public ::testing::Test {};\n\n\nTEST_F(InterpTest, test_linear_interp_double) {\n\n    Eigen::VectorXd x(5);\n    Eigen::VectorXd y(5);\n\n    x << 0, 1, 2, 3, 4;\n    y << 0, 2, 4, 6, 8;\n    double xi = 1.5;\n\n    utilities::LinearInterpolant s(x, y);\n    double yi = s(xi);\n\n    ASSERT_NEAR(yi, 3.0, 0.00001);\n\n}\n\nTEST_F(InterpTest, test_linear_interp_at_nodes) {\n\n    Eigen::VectorXd x(5);\n    Eigen::VectorXd y(5);\n    x << 0, 1, 2, 3, 4;\n    y << 0, 2, 4, 6, 8;\n    utilities::LinearInterpolant s(x, y);\n\n    // First node (endpoint)\n    double xi = 0.0;\n    double yi = s(xi);\n    ASSERT_NEAR(yi, 0.0, 0.00001);\n\n    // Any inter node\n    xi = 3.0;\n    yi = s(xi);\n    ASSERT_NEAR(yi, 6.0, 0.00001);\n\n    // Last node (endpoint)\n    xi = 4.0;\n    yi = s(xi);\n    ASSERT_NEAR(yi, 8.0, 0.00001);\n\n}\n\n\nTEST_F(InterpTest, test_linear_interp_beyond_endpoints) {\n\n    Eigen::VectorXd x(5);\n    Eigen::VectorXd y(5);\n    x << 0, 1, 2, 3, 4;\n    y << 0, 2, 4, 6, 8;\n    utilities::LinearInterpolant s(x, y);\n\n    double xi = -1.0;\n    double yi = s(xi);\n    ASSERT_NEAR(yi, 0.0, 0.00001);\n\n    xi = 5.0;\n    yi = s(xi);\n    ASSERT_NEAR(yi, 8.0, 0.00001);\n\n}\n\n\nTEST_F(InterpTest, test_linear_interp_vector) {\n\n    Eigen::ArrayXd x(5);\n    Eigen::ArrayXd xi(2);\n    Eigen::ArrayXd y(5);\n    Eigen::ArrayXd yi(2);\n    Eigen::ArrayXd yi_correct(2);\n\n    x << 0, 1, 2, 3, 4;\n    y << 0, 2, 4, 6, 8;\n    xi << 0.5, 1.5;\n    yi_correct << 1.0, 3.0;\n\n    utilities::LinearInterpolant s(x, y);\n    yi = s(xi);\n\n    ASSERT_TRUE(yi.isApprox(yi_correct));\n\n}\n\n\nTEST_F(InterpTest, test_cubic_interp_double) {\n\n    Eigen::VectorXd x(5);\n    Eigen::VectorXd y(5);\n\n    x << 0, 1, 2, 3, 4;\n    y << 0, 1, 4, 9, 16;\n    double xi = 1.5;\n\n    utilities::CubicSplineInterpolant s(x, y);\n    double yi = s(xi);\n\n    ASSERT_NEAR(yi, 2.25, 0.00001);\n\n}\n\n\nTEST_F(InterpTest, test_cubic_interp_vector) {\n\n    Eigen::VectorXd x(5);\n    Eigen::VectorXd xi(2);\n    Eigen::VectorXd y(5);\n    Eigen::VectorXd yi(2);\n    Eigen::VectorXd yi_correct(2);\n\n    x << 0, 1, 2, 3, 4;\n    y << 0, 1, 4, 9, 16;\n    xi << 0.5, 1.5;\n    yi_correct << 0.25, 2.25;\n\n    utilities::CubicSplineInterpolant s(x, y);\n    yi = s(xi);\n\n    ASSERT_TRUE(yi.isApprox(yi_correct));\n\n}\n", "meta": {"hexsha": "46371821e3bff6e628ea6e2b7099d2a87c8eab3a", "size": 2551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/utilities_interp_test.cpp", "max_stars_repo_name": "octue/es-flow", "max_stars_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_stars_repo_licenses": ["Intel", "MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-01-07T13:55:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-18T16:30:03.000Z", "max_issues_repo_path": "test/unit/utilities_interp_test.cpp", "max_issues_repo_name": "octue/es-flow", "max_issues_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_issues_repo_licenses": ["Intel", "MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-09-04T10:40:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-02T10:13:25.000Z", "max_forks_repo_path": "test/unit/utilities_interp_test.cpp", "max_forks_repo_name": "octue/es-flow", "max_forks_repo_head_hexsha": "fc53687a9e405c3d4fcac2dafa9f089fe9005b95", "max_forks_repo_licenses": ["Intel", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2214285714, "max_line_length": 70, "alphanum_fraction": 0.5719325755, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.8104789018037399, "lm_q1q2_score": 0.638601610141561}}
{"text": "\n#include \"eigen-helpers.hpp\"\n\n#include \"perceive/geometry/rotation.hpp\"\n\n#include <Eigen/SVD>\n\nusing std::stringstream;\n\nnamespace perceive\n{\n// ------------------------------------------------------------------- Is finite\n// Checks that an Eigen Matrix is finite\ntemplate<typename T> bool is_finiteT(const T& M)\n{\n   int n_rows = int(M.rows());\n   int n_cols = int(M.cols());\n   for(int i = 0; i < n_rows; ++i)\n      for(int j = 0; j < n_cols; ++j)\n         if(!std::isfinite(M(i, j))) return false;\n   return true;\n}\n\nbool is_finite(const Vector2r& M) { return is_finiteT(M); }\nbool is_finite(const Vector3r& M) { return is_finiteT(M); }\nbool is_finite(const Vector4r& M) { return is_finiteT(M); }\nbool is_finite(const Matrix3r& M) { return is_finiteT(M); }\nbool is_finite(const Matrix34r& M) { return is_finiteT(M); }\nbool is_finite(const MatrixXr& M) { return is_finiteT(M); }\n\n// -------------------------------------------------------------------- str(...)\n\nstd::string str(const Vector2r& M) { return format(\"[{}, {}]\", M(0), M(1)); }\nstd::string str(const Vector3r& M)\n{\n   return format(\"[{}, {}, {}]\", M(0), M(1), M(2));\n}\nstd::string str(const Vector4r& M)\n{\n   return format(\"[{}, {}, {}, {}]\", M(0), M(1), M(2), M(3));\n}\nstd::string str(const Matrix3r& M)\n{\n   stringstream ss(\"\");\n   ss << M;\n   return ss.str();\n}\nstd::string str(const Matrix34r& M)\n{\n   stringstream ss(\"\");\n   ss << M;\n   return ss.str();\n}\nstd::string str(const MatrixXr& M)\n{\n   stringstream ss(\"\");\n   ss << M;\n   return ss.str();\n}\n\nstd::string str(std::string name, const Matrix3r& M)\n{\n   stringstream ss(\"\");\n   ss << name << \" = \\n\" << M << \"\\n\";\n   return ss.str();\n}\nstd::string str(std::string name, const Matrix34r& M)\n{\n   stringstream ss(\"\");\n   ss << name << \" = \\n\" << M << \"\\n\";\n   return ss.str();\n}\nstd::string str(std::string name, const MatrixXr& M)\n{\n   stringstream ss(\"\");\n   ss << name << \" = \\n\" << M << \"\\n\";\n   return ss.str();\n}\n\n// ------------------------------------------------------------------------- SVD\n\n// -- Thin\n\nreal svd_thin(const MatrixXr& M, VectorXr& out)\n{\n   Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinV);\n   out = svd.matrixV().col(M.cols() - 1);\n   return svd.singularValues()(M.cols() - 1);\n}\n\nreal svd_thin(const Matrix3r& M, Vector3r& out)\n{\n   Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinV);\n   out = svd.matrixV().col(M.cols() - 1);\n   return svd.singularValues()(M.cols() - 1);\n}\n\n// real svd_thin(const Matrix3d& M, Vector3d& out)\n// {\n//     Eigen::JacobiSVD<MatrixXd> svd(M, Eigen::ComputeThinV);\n//     out = svd.matrixV().col(M.cols() - 1);\n//     return svd.singularValues()(M.cols() - 1);\n// }\n\n// real svd_thin(const MatrixXd& M, VectorXd& out)\n// {\n//     Eigen::JacobiSVD<MatrixXd> svd(M, Eigen::ComputeThinV);\n//     out = svd.matrixV().col(M.cols() - 1);\n//     return svd.singularValues()(M.cols() - 1);\n// }\n\nreal svd_thin(const MatrixXr& M, Vector6r& out)\n{\n   Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinV);\n   out = svd.matrixV().col(M.cols() - 1);\n   return svd.singularValues()(M.cols() - 1);\n}\n\n// -- UD\n\nvoid svd_UV(const MatrixXr& M, MatrixXr& U, MatrixXr& V)\n{\n   Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);\n   U = svd.matrixU();\n   V = svd.matrixV();\n}\n\nvoid svd_UV(const Matrix3r& M, Matrix3r& U, Matrix3r& V)\n{\n   Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);\n   U = svd.matrixU();\n   V = svd.matrixV();\n}\n\n// void svd_UV(const MatrixXd& M, MatrixXd& U, MatrixXd& V)\n// {\n//     Eigen::JacobiSVD<MatrixXd> svd(M,\n//     Eigen::ComputeThinU|Eigen::ComputeThinV); U = svd.matrixU(); V =\n//     svd.matrixV();\n// }\n\n// -- UDV\n\nvoid svd_UDV(const MatrixXr& M, MatrixXr& U, VectorXr& D, MatrixXr& V)\n{\n   Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);\n   U      = svd.matrixU();\n   V      = svd.matrixV();\n   auto s = svd.singularValues();\n   auto n = s.rows();\n   D.resize(n);\n   for(uint i = 0; i < n; ++i) D(i) = s(i);\n}\n\nvoid svd_UDV(const Matrix3r& M, Matrix3r& U, Vector3r& D, Matrix3r& V)\n{\n   Eigen::JacobiSVD<MatrixXr> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);\n   U      = svd.matrixU();\n   V      = svd.matrixV();\n   auto s = svd.singularValues();\n   for(uint i = 0; i < 3; ++i) D(i) = s(i);\n}\n\nvoid svd_UDV(const Matrix3r& M, Matrix3r& U, Matrix3r& D, Matrix3r& V)\n{\n   Vector3r d;\n   svd_UDV(M, U, d, V);\n   D = Matrix3r::Zero();\n   for(auto i = 0; i < 3; ++i) D(i, i) = d(i);\n}\n\n// void svd_UDV(const MatrixXd& M, MatrixXd& U, VectorXd& D, MatrixXd& V)\n// {\n//     Eigen::JacobiSVD<MatrixXd> svd(M,\n//     Eigen::ComputeThinU|Eigen::ComputeThinV); U = svd.matrixU(); V =\n//     svd.matrixV(); auto s = svd.singularValues(); auto n = s.rows();\n//     D.resize(n);\n//     for(uint i = 0; i < n; ++i)\n//         D(i) = s(i);\n// }\n\nMatrix3r SVD3DRet::Dm() const noexcept\n{\n   Matrix3r X = Matrix3r::Identity();\n   for(auto i = 0; i < 3; ++i) X(i, i) = D(i);\n   return X;\n}\n\nstring SVD3DRet::to_string() const noexcept\n{\n   std::stringstream ss{\"\"};\n   ss << format(\"U = \\n\") << U << \"\\n\\n\"\n      << format(\"D = \\n\") << Dm() << \"\\n\\n\"\n      << format(\"V = \\n\") << V << \"\\n\\n\";\n   return ss.str();\n}\n\nVector3r SVD3DRet::eigen_vector(int ind) const noexcept\n{\n   Expects(ind >= 0 && ind < 3);\n   return Vector3r(V(ind, 0), V(ind, 1), V(ind, 2));\n}\n\nQuaternion SVD3DRet::rot_vec() const noexcept\n{\n   return rot3x3_to_quaternion(V.transpose());\n}\n\ntemplate<typename J>\nusing MatrixXc_J\n    = Eigen::Matrix<std::complex<J>, Eigen::Dynamic, Eigen::Dynamic>;\ntemplate<typename J>\nusing VectorXc_J = Eigen::Matrix<std::complex<J>, Eigen::Dynamic, 1>;\n\ntemplate<typename T>\nvoid svd_UDV_T(const MatrixXc_J<T>& M,\n               MatrixXc_J<T>& U,\n               VectorXc_J<T>& D,\n               MatrixXc_J<T>& V)\n{\n   using MatrixXc = MatrixXc_J<T>;\n   // using VectorXc = VectorXc_J<T>;\n   Eigen::JacobiSVD<MatrixXc> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);\n   U      = svd.matrixU();\n   V      = svd.matrixV();\n   auto s = svd.singularValues();\n   auto n = s.rows();\n   D.resize(n, 1);\n   for(uint i = 0; i < n; ++i) D(i) = s(i);\n}\n\nvoid svd_UDV(const MatrixXc_J<long double>& M,\n             MatrixXc_J<long double>& U,\n             VectorXc_J<long double>& D,\n             MatrixXc_J<long double>& V)\n{\n   svd_UDV_T<long double>(M, U, D, V);\n}\n\nvoid svd_UDV(const MatrixXc_J<double>& M,\n             MatrixXc_J<double>& U,\n             VectorXc_J<double>& D,\n             MatrixXc_J<double>& V)\n{\n   svd_UDV_T<double>(M, U, D, V);\n}\n\nvoid svd_UDV(const MatrixXc_J<float>& M,\n             MatrixXc_J<float>& U,\n             VectorXc_J<float>& D,\n             MatrixXc_J<float>& V)\n{\n   svd_UDV_T<float>(M, U, D, V);\n}\n\ntemplate<typename T>\nvoid svd_UDV_T(const Eigen::Matrix<std::complex<T>, 3, 3>& M,\n               Eigen::Matrix<std::complex<T>, 3, 3>& U,\n               Eigen::Matrix<std::complex<T>, 3, 1>& D,\n               Eigen::Matrix<std::complex<T>, 3, 3>& V)\n{\n   using MatrixXc = MatrixXc_J<T>;\n   // using VectorXc = VectorXc_J<T>;\n\n   Eigen::JacobiSVD<MatrixXc> svd(M, Eigen::ComputeThinU | Eigen::ComputeThinV);\n   U      = svd.matrixU();\n   V      = svd.matrixV();\n   auto s = svd.singularValues();\n   auto n = s.rows();\n   D.resize(n, 1);\n   for(uint i = 0; i < n; ++i) D(i) = s(i);\n}\n\nvoid svd_UDV(const Eigen::Matrix<std::complex<long double>, 3, 3>& M,\n             Eigen::Matrix<std::complex<long double>, 3, 3>& U,\n             Eigen::Matrix<std::complex<long double>, 3, 1>& D,\n             Eigen::Matrix<std::complex<long double>, 3, 3>& V)\n{\n   svd_UDV_T(M, U, D, V);\n}\n\nvoid svd_UDV(const Eigen::Matrix<std::complex<double>, 3, 3>& M,\n             Eigen::Matrix<std::complex<double>, 3, 3>& U,\n             Eigen::Matrix<std::complex<double>, 3, 1>& D,\n             Eigen::Matrix<std::complex<double>, 3, 3>& V)\n{\n   svd_UDV_T(M, U, D, V);\n}\n\nvoid svd_UDV(const Eigen::Matrix<std::complex<float>, 3, 3>& M,\n             Eigen::Matrix<std::complex<float>, 3, 3>& U,\n             Eigen::Matrix<std::complex<float>, 3, 1>& D,\n             Eigen::Matrix<std::complex<float>, 3, 3>& V)\n{\n   svd_UDV_T(M, U, D, V);\n}\n\ntemplate<typename T, typename S> double bdcsvd_thin_TS(const T& M, S& out)\n{\n   Eigen::BDCSVD<T> svd(M, Eigen::ComputeThinV);\n   out = svd.matrixV().col(M.cols() - 1);\n   return svd.singularValues()(M.cols() - 1);\n}\n\n// double bdcsvd_thin(const MatrixXd& M, VectorXd& out)\n// { return bdcsvd_thin_TS(M, out); }\nreal bdcsvd_thin(const MatrixXr& M, VectorXr& out)\n{\n   return bdcsvd_thin_TS(M, out);\n}\n\n// ------------------------------------------------------------ condition-number\n\ntemplate<typename T> real condition_number_T(const T& M)\n{\n   Eigen::JacobiSVD<T> svd(M);\n   auto vals = svd.singularValues();\n   return vals(0) / vals(vals.rows() - 1);\n}\n\nreal condition_number(const MatrixXr& M) { return condition_number_T(M); }\n\nreal condition_number(const Matrix3r& M) { return condition_number_T(M); }\n\n// -------------------------------------------------------- Cross-product Matrix\n\ntemplate<typename T> void to_cross_product_matrix_T(const T& X, Matrix3r& M)\n{\n   M(0, 0) = M(1, 1) = M(2, 2) = 0.0;\n   M(0, 1)                     = -X(2);\n   M(1, 0)                     = X(2);\n   M(0, 2)                     = X(1);\n   M(2, 0)                     = -X(1);\n   M(1, 2)                     = -X(0);\n   M(2, 1)                     = X(0);\n}\n\nvoid to_cross_product_matrix(const Vector3r& X, Matrix3r& M)\n{\n   to_cross_product_matrix_T(X, M);\n}\n\nvoid to_cross_product_matrix(const Vector3& X, Matrix3r& M)\n{\n   to_cross_product_matrix_T(X, M);\n}\n\nMatrix3r make_cross_product_matrix(const Vector3& X)\n{\n   Matrix3r M;\n   to_cross_product_matrix_T(X, M);\n   return M;\n}\n\nMatrix3r make_cross_product_matrix(const Vector3r& X)\n{\n   Matrix3r M;\n   to_cross_product_matrix_T(X, M);\n   return M;\n}\n\n// --------------------------------------------------- Quadratic with Constraint\n\n// Minimize xGtGx such that Hx = h\n//  * G must have more rows than columns.\n//  * G.cols() == H.cols()\nMatrixXr minimize_with_constraint(const MatrixXr& G, const MatrixXr& H, real h)\n{\n   const unsigned n_vars      = unsigned(G.cols());\n   const unsigned n_equations = unsigned(G.rows());\n   MatrixXr sol               = MatrixXr::Zero(n_vars, 1);\n\n   if(G.rows() < G.cols()) {\n      LOG_ERR(format(\"Must have more equations than unknowns!\"));\n      return sol;\n   }\n\n   if(H.rows() != n_vars) {\n      LOG_ERR(format(\"G and H must have the same number of columns!\"));\n      return sol;\n   }\n\n   MatrixXr A = MatrixXr::Zero(n_vars + 1, n_vars + 1);\n   MatrixXr b = MatrixXr::Zero(n_vars + 1, 1); // Ax - b = 0\n\n   b(n_vars) = h;\n   for(unsigned row = 0; row < n_vars; ++row) {\n      A(row, n_vars) = H(row);\n      A(n_vars, row) = H(row);\n   }\n   A.block(0, 0, n_vars, n_vars) = G.transpose() * G;\n\n   if(false) {\n      MatrixXr U, V;\n      VectorXr D;\n      svd_UDV(A, U, D, V);\n\n      cout << str(\"A\\n\") << A << endl << endl;\n      cout << str(\"U\\n\") << U << endl << endl;\n      cout << str(\"D\\n\") << D << endl << endl;\n      cout << str(\"V\\n\") << V << endl << endl;\n   }\n\n   MatrixXr Ainv       = A.inverse();\n   MatrixXr sol_lambda = Ainv * b;\n   sol                 = sol_lambda.block(0, 0, n_vars, 1);\n\n   return sol;\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "811584c181607e0b8f97d50fdf7125db6247fd71", "size": 11270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/utils/eigen-helpers.cpp", "max_stars_repo_name": "prcvlabs/multiview", "max_stars_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T23:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:43:32.000Z", "max_issues_repo_path": "multiview/multiview_cpp/src/perceive/utils/eigen-helpers.cpp", "max_issues_repo_name": "prcvlabs/multiview", "max_issues_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:33:02.000Z", "max_forks_repo_path": "multiview/multiview_cpp/src/perceive/utils/eigen-helpers.cpp", "max_forks_repo_name": "prcvlabs/multiview", "max_forks_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-26T03:14:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T06:42:52.000Z", "avg_line_length": 27.354368932, "max_line_length": 80, "alphanum_fraction": 0.5637089618, "num_tokens": 3653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6385839226449658}}
{"text": "/**\n* Add Guassian Noise or Speckle Noise for 3-chanel-images\n*\n*/\n#include \"NoiseFilter.h\"\n#include <opencv2/opencv.hpp>\n#include <iostream>\n#include <Eigen/Eigen>\n\nusing namespace cv;\nusing namespace std;\n\n\n\n/**\n* Add Gaussian Noise for RGB CV_8U or CV_16U 3-channel-images\n*\n* @param img Input RGB CV_8U or CV_16U 3-channel-images.\n* @param mean Mean of Gaussian noise\n* @param sigma Standard deviation of Gaussian noise. range from 0 to 1.\n* @return noise  Image with guassian noise\n*/\ncv::Mat NoiseFilter::AddGaussianNoise(cv::Mat img, float mean, float sigma) {\n\tMat noise;\n\tnoise = img.clone();\n\tRNG rng;\n\tsigma = sigma * 255;\n\n\t// generate noise\n\trng.fill(noise, RNG::NORMAL, mean, sigma);\n\n\t// create a mask to make sure to only affect the area with color and not the empty background. \n\tcv::Mat grayscaleMat, mask;\n\tcvtColor(img, grayscaleMat, CV_RGB2GRAY);\n    cv::threshold(grayscaleMat, mask, 0.0, 255, CV_THRESH_BINARY); // 0.0 -> black background\n\n\t// add the noise\n\tcv::Mat out;\n\tadd( noise, img, out, mask);\n\n\treturn out;\n}\n\n/**\n* Add Speckle Noise for RGB CV_8U or CV_16U 3-channel-images\n*\n* @param img Input RGB CV_8U or CV_16U 3-channel-images.\n* @param dev Standard deviation of speckle noise. range from 0 to 1.\n* @return noise  Image with speckle noise\n*/\ncv::Mat NoiseFilter::AddSpeckleNoiseRGB(cv::Mat img, float dev) {\n\tMat res;\n\tres = img.clone();\n\tCvMat* pNoise = cvCreateMat(img.rows, img.cols, CV_32F);\n\tCvRNG rng(6);\n\n\tcout << img.type() << endl;\n\n\tcvRandArr(&rng, pNoise, CV_RAND_NORMAL, 1, dev);\n\tfor (int i = 0; i < img.rows; i++) {\n\t\tfor (int j = 0; j < img.cols; j++) {\n\t\t\tfloat tmp = pNoise->data.fl[img.cols*i + j];\n\t\t\tres.at<Vec3b>(i,j) = img.at<Vec3b>(i,j) * tmp;\n\t\t}\n\t}\n\treturn res;\n}\n\n", "meta": {"hexsha": "18e253a2213567628a9cc7567d554c3f64d70c72", "size": 1728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NoiseFilter.cpp", "max_stars_repo_name": "rafael-radkowski/setforge", "max_stars_repo_head_hexsha": "cfa42fc4fc77a3f74c0118a00e047a4c67a7452c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-19T16:06:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T08:40:52.000Z", "max_issues_repo_path": "src/NoiseFilter.cpp", "max_issues_repo_name": "rafael-radkowski/setforge", "max_issues_repo_head_hexsha": "cfa42fc4fc77a3f74c0118a00e047a4c67a7452c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-14T20:30:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-20T14:29:41.000Z", "max_forks_repo_path": "src/NoiseFilter.cpp", "max_forks_repo_name": "rafael-radkowski/DNNHelpers", "max_forks_repo_head_hexsha": "cfa42fc4fc77a3f74c0118a00e047a4c67a7452c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T19:45:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T19:45:57.000Z", "avg_line_length": 25.0434782609, "max_line_length": 96, "alphanum_fraction": 0.6857638889, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6385713311194945}}
{"text": "#include <math.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <iostream>\n#include <armadillo>\n#include <cmath>\n#include <cstdlib>\n#include <iomanip>\n#include <time.h>\nusing namespace std;\n\narma::vec init_func(arma::vec Y, double alpha, double t);\ndouble dx1dt(double x2);\ndouble dx2dt(double x1, double p2, double alpha, double t);\ndouble dp1dt(double x1, double p2, double alpha, double t);\ndouble dp2dt(double p1);\n\narma::vec init_func(arma::vec Function, double alpha, double t) {\n    arma::vec ODE(static_cast<arma::uword>(4), arma::fill::zeros);\n\n    ODE(0) = dx1dt(Function(1));\n    ODE(1) = dx2dt(Function(0), Function(3), alpha, t);\n    ODE(2) = dp1dt(Function(0), Function(3), alpha, t);\n    ODE(3) = dp2dt(Function(2));\n\n    return ODE;\n}\n\ndouble dx1dt(double x2) {\n    return x2;\n}\n\ndouble dx2dt(double x1, double p2, double alpha, double t) {\n    return p2 / 2 - sqrt(2) * x1 * exp(-alpha*t);\n}\n\ndouble dp1dt(double x1, double p2, double alpha, double t) {\n    return 2*x1 + sqrt(2) * p2 * exp(-alpha*t);\n}\n\ndouble dp2dt(double p1) {\n    return -p1;\n}\n", "meta": {"hexsha": "9f22786840210211462fb46ebe5b95f3f4b1d3f2", "size": 1109, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "7th-half/2nd-task/progs/c/func.hpp", "max_stars_repo_name": "pmpavl/workshop", "max_stars_repo_head_hexsha": "8b86dec69916146ff11569a1a7a250b237e94613", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "7th-half/2nd-task/progs/c/func.hpp", "max_issues_repo_name": "pmpavl/workshop", "max_issues_repo_head_hexsha": "8b86dec69916146ff11569a1a7a250b237e94613", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "7th-half/2nd-task/progs/c/func.hpp", "max_forks_repo_name": "pmpavl/workshop", "max_forks_repo_head_hexsha": "8b86dec69916146ff11569a1a7a250b237e94613", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1086956522, "max_line_length": 66, "alphanum_fraction": 0.6636609558, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6385617738384306}}
{"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* Convex Non-Negative Matrix Factorization                                 *\r\n***************************************************************************/\r\n\r\n#ifndef CNNMF_HPP\r\n#define CNNMF_HPP\r\n\r\n#include <Eigen/Dense>\r\n#include <cmath>\r\n#include \"NNMF.hpp\"\r\n\r\n// [1] C. Ding and T. Li and M. Jordan, \"Convex and Semi-Nonnegative Matrix\r\n//     Factorizations\", IEEE Transactions on Pattern Analysis and Machine\r\n//     Intelligence, Vol. 99(1), 2008.\r\n\r\nusing namespace Eigen;\r\n\r\nclass CNNMF\r\n{\r\npublic:\r\n\tCNNMF(const int maxIterations = 200, const double threshold = 1e-4, const double tolerance = 1e-4, const bool verbose = false);\r\n\t\r\n\ttemplate<class Derived>\r\n\tvoid compute(const MatrixBase<Derived> &dataset, const int K);\r\n\ttemplate<class Derived>\r\n\tvoid compute(const MatrixBase<Derived> &dataset, const MatrixXd &G0, const MatrixXd &H0);\r\n\t\r\n\tMatrixXd G() const { return m_G; }\r\n\tMatrixXd H() const { return m_H; }\r\n\t\r\nprivate:\r\n\tvoid cnnmf_mur(const MatrixXd &dataset);\r\n\t\r\n\tMatrixXd m_G;\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\nCNNMF::CNNMF(const int maxIterations, const double threshold, const double tolerance, const bool verbose)\r\n: m_G(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<class Derived>\r\nvoid CNNMF::compute(const MatrixBase<Derived> &dataset, const int K)\r\n{\r\n\tif (K >= dataset.cols() || K >= dataset.rows())\r\n\t{\r\n\t\tm_G = MatrixXd::Identity(dataset.cols(), K);\r\n\t\tm_H = MatrixXd::Identity(K, dataset.cols());\r\n\t\treturn;\r\n\t}\r\n\t\r\n\t// Initialize G and H matrices\r\n\tNNMF nnmf(m_maxIterations, m_threshold, m_tolerance, true);\r\n\tnnmf.compute(dataset, K);\r\n\t\r\n\tm_H = nnmf.H();\r\n\tm_G = m_H.transpose().fullPivHouseholderQr().solve(MatrixXd::Identity(dataset.cols(), dataset.cols())).transpose().cwiseMax(0);\r\n\t\r\n\t// Set components\r\n\tm_components = K;\r\n\t\r\n\t// Compute Convex Non-Negative Matrix Factorization decomposition\r\n\tcnnmf_mur(dataset.cast<double>());\r\n}\r\n\r\ntemplate<typename T>\r\nvoid CNNMF::compute(const MatrixBase<T> &dataset, const MatrixXd &G0, const MatrixXd &H0)\r\n{\r\n\t// Initialize W and H matrices\r\n\tm_components = G0.cols();\r\n\tm_G = G0;\r\n\tm_H = H0;\r\n\t\r\n\t// Compute Convex Non-Negative Matrix Factorization decomposition\r\n\tcnnmf_mur(dataset.cast<double>());\r\n}\r\n\r\n// Multiplicative Updated Rules\r\nvoid CNNMF::cnnmf_mur(const MatrixXd &dataset)\r\n{\r\n\t// Set dimension variables\r\n\tconst double NM = (double) (dataset.rows() * dataset.cols());\r\n\r\n\t// Set usefull matrices\t\r\n\tconst MatrixXd VtV = dataset.transpose() * dataset;\r\n\tconst MatrixXd Yp = (VtV.cwiseAbs() + VtV) / 2.0;\r\n\tconst MatrixXd Yn = (VtV.cwiseAbs() - VtV) / 2.0;\r\n\tMatrixXd num, den;\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\\tThreshold\\n\");\r\n\t\tmexPrintf(\"-----------------------------------------------------------------------------\\n\");\r\n\t}\r\n\t\r\n\t// Declare previous iteration matrices and error\r\n\tdouble dnorm0 = 0;\r\n\t\r\n\tfor (int i = 0; i < m_maxIterations; ++i)\r\n\t{\r\n\t\t// Update G\r\n\t\tnum = (Yp + (Yn * m_G * m_H)) * m_H.transpose();\r\n\t\tden = (Yn + (Yp * m_G * m_H)) * m_H.transpose();\r\n\t\tm_G = m_G.cwiseProduct(num.cwiseQuotient(den).cwiseSqrt()).cwiseMax(0).eval();\r\n\t\r\n\t\t// Update H\r\n\t\tnum = m_G.transpose() * (Yp + (Yn * m_G * m_H));\r\n\t\tden = m_G.transpose() * (Yn + (Yp * m_G * m_H));\r\n\t\tm_H = m_H.cwiseProduct(num.cwiseQuotient(den).cwiseSqrt()).cwiseMax(0).eval();\r\n\t\t\r\n\t\t// Compute squared error\r\n\t\tconst ArrayXXd d = dataset - (dataset * m_G * m_H.transpose());\r\n\t\tconst double dnorm = std::sqrt((d * d).sum() / NM);\t\t\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\\n\", i+1, m_maxIterations, dnorm, (dnorm0 - dnorm), (m_threshold * std::max(1.0, dnorm0)));\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 (dnorm0 - dnorm <= (m_threshold * std::max(1.0, dnorm0)))\r\n\t\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tdnorm0 = dnorm;\r\n\t}\r\n}\r\n\r\n#endif", "meta": {"hexsha": "76a1c7836033c674024c2e9c435035f6a479e879", "size": 4664, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CNNMF.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": "CNNMF.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": "CNNMF.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": 32.1655172414, "max_line_length": 152, "alphanum_fraction": 0.570754717, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.6385063669456602}}
{"text": "#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"rj_geometry/transform_matrix.hpp\"\n\nusing namespace rj_geometry;\n\nTEST(TransformMatrix, Convert) {\n    // Test conversion to/from Eigen\n    TransformMatrix transform(Point(0, 1), 1.0);\n    Eigen::Matrix<double, 3, 3> transform_eigen = transform;\n    EXPECT_EQ(transform_eigen * Eigen::Vector3d(0, 0, 1), Eigen::Vector3d(0, 1, 1));\n    TransformMatrix transformed_back = transform_eigen;\n    EXPECT_EQ(transform * Point(0, 1), transformed_back * Point(0, 1));\n    EXPECT_EQ(transform * Point(1, 0), transformed_back * Point(1, 0));\n}\n\nTEST(TransformMatrix, Compose) {\n    // Test composition: self-compose a 90-degree rotation with an offset from\n    // the origin\n    TransformMatrix transform1(Point(0, 1), M_PI / 2);\n    TransformMatrix transform2(Point(1, 0), M_PI / 2);\n\n    EXPECT_LT(\n        ((transform1 * transform2) * Point(1, 0) - transform1 * (transform2 * Point(1, 0))).mag(),\n        1e-6)\n        << \"Composition should be associative!\";\n\n    EXPECT_LT(\n        ((transform2 * transform1) * Point(1, 0) - transform2 * (transform1 * Point(1, 0))).mag(),\n        1e-6)\n        << \"Composition should be associative!\";\n}\n\nTEST(TransformMatrix, Reconstruct) {\n    Eigen::Matrix<double, 3, 3> transform_eigen;\n    transform_eigen << 0, 1, 0, -1, 0, 1, 0, 0, 1;\n    TransformMatrix transform = transform_eigen;\n    EXPECT_EQ(transform.origin(), Point(0, 1));\n    EXPECT_NEAR(transform.rotation(), -M_PI / 2 + 2 * M_PI, 1e-6);\n}\n", "meta": {"hexsha": "313f49aa78b219f656515f8b6939893c2cb8fe77", "size": 1494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rj_geometry/testing/transform_matrix_test.cpp", "max_stars_repo_name": "xiaoqingyu0113/robocup-software", "max_stars_repo_head_hexsha": "6127d25fc455051ef47610d0e421b2ca7330b4fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 200.0, "max_stars_repo_stars_event_min_datetime": "2015-01-26T01:45:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:05:31.000Z", "max_issues_repo_path": "rj_geometry/testing/transform_matrix_test.cpp", "max_issues_repo_name": "xiaoqingyu0113/robocup-software", "max_issues_repo_head_hexsha": "6127d25fc455051ef47610d0e421b2ca7330b4fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1254.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T01:57:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T06:32:21.000Z", "max_forks_repo_path": "rj_geometry/testing/transform_matrix_test.cpp", "max_forks_repo_name": "xiaoqingyu0113/robocup-software", "max_forks_repo_head_hexsha": "6127d25fc455051ef47610d0e421b2ca7330b4fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 206.0, "max_forks_repo_forks_event_min_datetime": "2015-01-21T02:03:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T17:57:46.000Z", "avg_line_length": 35.5714285714, "max_line_length": 98, "alphanum_fraction": 0.6606425703, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6384928563307093}}
{"text": "/*\n * Author: Mario L\u00fcder\n * Date: Nov. 2018\n */\n\n#ifndef UKF_HPP\n#define UKF_HPP\n\n#include <Eigen/Dense>\n\nclass UkfBase\n{\n\n};\n\ntemplate<typename PROCESSMODEL_T>\nclass Ukf\n{\npublic:\n   Ukf()\n      : m_n_x(PROCESSMODEL_T::m_n_x)\n      , m_n_x_aug(PROCESSMODEL_T::m_n_x_aug)\n      , m_lambda(3 - PROCESSMODEL_T::m_n_x_aug)\n      , m_weights(calculateWeights())\n      , m_x(m_n_x)\n      , m_P(m_n_x, m_n_x)\n      , m_previousTimestampUs(0)\n   {\n      m_x.setZero();\n      m_P.setIdentity();\n   }\n\n   ~Ukf() {}\n\n   // delete this as this class as an read only interface\n   Ukf(const Ukf & rhs) = delete;\n   Ukf & operator=(Ukf & ukf) = delete;\n   Ukf & operator=(Ukf && ukf) = delete;\n\n   template<typename MEASUREMENT_T, typename MEASUREMENTMODEL_T>\n   void processMeasurement(const MEASUREMENT_T & z_measurement, MEASUREMENTMODEL_T & measurementModel, int64_t timestamp_us)\n   {\n      const int64_t dt_us = setNewTime(timestamp_us);\n\n      if (dt_us > 0)\n      {\n         // do update step\n         // if some time passed since last measurement\n         const double dt_s = dt_us / 1000000.0;\t//dt - expressed in seconds\n\n         // generate augumented sigma points from last state\n         Eigen::MatrixXd XSigmaPoints;\n         generateAugumentedSigmaPoints(m_x, m_P, m_std, XSigmaPoints);\n\n         // predict sigma points\n         PROCESSMODEL_T::predictSigmaPoints(XSigmaPoints, dt_s, m_XSigmaPointsPred);\n\n         // predict object covariance and\n         // predict object state\n         m_x_pred.setZero(PROCESSMODEL_T::m_n_x);\n         m_P_pred.setZero(PROCESSMODEL_T::m_n_x, PROCESSMODEL_T::m_n_x);\n\n         predict<PROCESSMODEL_T>(m_XSigmaPointsPred, m_x_pred, m_P_pred);\n      }\n\n      Eigen::MatrixXd Z_pred;\n      measurementModel.predictMeasurement(m_XSigmaPointsPred, Z_pred);\n\n      Eigen::VectorXd z_pred;\n      weightedMean(Z_pred, z_pred);\n\n      Eigen::MatrixXd S_cov;\n      measurementModel.predictCovar(*this, Z_pred, z_pred, S_cov);\n\n      //\n      // update\n      //\n\n\n      // Cross Correlation Matrix\n      Eigen::MatrixXd Tc;\n      calculateCrosscorrelationMatix<MEASUREMENTMODEL_T>(m_XSigmaPointsPred, Z_pred, m_x_pred, z_pred, Tc);\n\n      // Kalman Gain\n      Eigen::MatrixXd K;\n      calculateKalmanGain(Tc, S_cov, K);\n\n      // update state and covariance matrix\n      Eigen::VectorXd z_residual = z_measurement.value - z_pred;\n      MEASUREMENTMODEL_T::normalize(z_residual);\n\n      updateState(K, z_residual, m_x_pred);\n      updateCovariance(K, S_cov, m_P_pred);\n\n      // compute NIS\n      measurementModel.m_nis = computeNIS(z_residual, S_cov);\n\n      std::swap(m_x_pred, m_x);\n      std::swap(m_P_pred, m_P);\n   }\n\n   template<typename MODEL_T>\n   void predictCovar(const Eigen::MatrixXd & SigmaPoints, const Eigen::VectorXd & vector, Eigen::MatrixXd & Covariance) const\n   {\n      Eigen::MatrixXd SigmaPointsDiff = SigmaPoints.colwise() - vector;\n\n      for (long colIdx = 0; colIdx < PROCESSMODEL_T::m_nSigmaPoints; ++colIdx)\n      {\n         MODEL_T::normalize(colIdx, SigmaPointsDiff);\n\n         Eigen::MatrixXd cov_pred_sigmaPoint = (SigmaPointsDiff.col(colIdx).array() * m_weights(colIdx)).matrix() *\n               SigmaPointsDiff.col(colIdx).transpose();\n\n         Covariance += cov_pred_sigmaPoint;\n      }\n   }\n\n   // set standard deviation - process noise\n   void setStd(const Eigen::VectorXd & std) { m_std = std; }\n\n   // constant 2 * PI\n   static constexpr double TWO_PI = 2 * M_PI;\n\nprivate:\n   //set state dimension\n   const long m_n_x;\n\n   //set augumented state dimension\n   const long m_n_x_aug;\n\npublic:\n   // Read only interface\n   const Eigen::VectorXd & x = m_x;\n   const Eigen::MatrixXd & P = m_P;\n\nprotected:\n   void generateSigmaPoints(const Eigen::VectorXd &x_, const Eigen::MatrixXd & P_, Eigen::MatrixXd & XSigmaPoints)\n   {\n      //create sigma point matrix\n      XSigmaPoints.setZero(m_n_x, 2 * m_n_x + 1);\n\n      //calculate square root of P\n      Eigen::MatrixXd A = P_.llt().matrixL();\n\n      //set first column of sigma point matrix\n      XSigmaPoints.col(0)  = x_;\n\n      //set remaining sigma points\n      for (int i = 0; i < m_n_x; i++)\n      {\n         XSigmaPoints.col(i+1)       = x_ + sqrt(m_lambda+m_n_x) * A.col(i);\n         XSigmaPoints.col(i+1+m_n_x) = x_ - sqrt(m_lambda+m_n_x) * A.col(i);\n      }\n   }\n\n\n   void generateAugumentedSigmaPoints(const Eigen::VectorXd &x_, const Eigen::MatrixXd & P_, const Eigen::VectorXd &std, Eigen::MatrixXd & XSigmaPoints)\n   {\n      //create augmented mean vector\n      Eigen::VectorXd x_aug;\n      x_aug.setZero(m_n_x_aug);\n      x_aug.head(m_n_x) = x_;\n\n      //create augmented state covariance\n      Eigen::MatrixXd P_aug;\n      P_aug.setZero(m_n_x_aug, m_n_x_aug);\n      P_aug.topLeftCorner(m_n_x, m_n_x) = P_;\n\n      for (long i = m_n_x; i < m_n_x_aug; ++i)\n      {\n         P_aug(i, i) = pow(std(i - m_n_x),2);\n      }\n\n      //create sigma point matrix\n      XSigmaPoints.setZero(m_n_x_aug, 2 * m_n_x_aug + 1);\n\n      //calculate square root of P\n      Eigen::MatrixXd A = P_aug.llt().matrixL();\n\n      //set first column of sigma point matrix\n      XSigmaPoints.col(0)  = x_aug;\n\n      //set remaining sigma points\n      for (int i = 0; i < m_n_x_aug; i++)\n      {\n         XSigmaPoints.col(i+1)           = x_aug + sqrt(m_lambda+m_n_x_aug) * A.col(i);\n         XSigmaPoints.col(i+1+m_n_x_aug) = x_aug - sqrt(m_lambda+m_n_x_aug) * A.col(i);\n      }\n   }\n\n\n   inline void weightedMean(const Eigen::MatrixXd & XSigmaPoints, Eigen::VectorXd &x_pred)\n   {\n      x_pred = (XSigmaPoints.array().rowwise() * m_weights.transpose()).rowwise().sum();\n   }\n\n   template<typename MEASUREMENTMODEL_T>\n   inline void calculateCrosscorrelationMatix(const Eigen::MatrixXd & XSigmaPointsPred, const Eigen::MatrixXd & ZSigmaPointsPred, const Eigen::VectorXd & x_mean, const Eigen::VectorXd & z_mean, Eigen::MatrixXd & T)\n   {\n      Eigen::MatrixXd X = (XSigmaPointsPred.colwise() - x_mean);\n      // MEASUREMENTMODEL_T::normalize(X);\n      Eigen::MatrixXd Z = (ZSigmaPointsPred.colwise() - z_mean);\n      // MEASUREMENTMODEL_T::normalize(Z);\n      const Eigen::MatrixXd X_weighted = X.array().rowwise() * m_weights.transpose();\n      T = (X_weighted * Z.transpose());\n   }\n\n   inline void calculateKalmanGain(const Eigen::MatrixXd & T, const Eigen::MatrixXd & S, Eigen::MatrixXd & K)\n   {\n      K = T * S.inverse();\n   }\n\n   inline void updateState(const Eigen::MatrixXd & K, const Eigen::VectorXd & z_residual, Eigen::VectorXd & x_pred)\n   {\n      Eigen::VectorXd & x_update = x_pred;\n      x_update = x_pred + K * z_residual;\n   }\n\n   inline void updateCovariance(const Eigen::MatrixXd & K, const Eigen::MatrixXd & S, Eigen::MatrixXd & P_pred) const\n   {\n      Eigen::MatrixXd & P_update = P_pred;\n      P_update = P_pred - K * S * K.transpose();\n   }\n\n   template<typename MODEL_T>\n   inline void predict(const Eigen::MatrixXd & XSigmaPoints, Eigen::VectorXd &x_pred, Eigen::MatrixXd & P_pred)\n   {\n      weightedMean(XSigmaPoints, x_pred);\n      predictCovar<MODEL_T>(XSigmaPoints, x_pred, P_pred);\n   }\n\n\n   // set the new measurement time and compute the difference\n   inline int64_t setNewTime(const int64_t timestamp_us)\n   {\n      //compute the time elapsed between the current and previous measurements\n      int64_t dt = timestamp_us - m_previousTimestampUs;\n      m_previousTimestampUs = timestamp_us;\n      return dt;\n   }\n\n   inline double computeNIS(const Eigen::VectorXd z_diff, const Eigen::MatrixXd & S)\n   {\n      const double nis = z_diff.transpose() * S.inverse() * z_diff;\n      return nis;\n   }\n\n   //define spreading parameter\n   const double m_lambda;\n\n   // weights for prediction\n   const Eigen::ArrayXd m_weights;\n\n   // set standard deviation - process noise\n   Eigen::VectorXd m_std;\n\n   // object state\n   Eigen::VectorXd m_x;\n\n   // object covariance matrix\n   Eigen::MatrixXd m_P;\n\n   // predicted object state\n   Eigen::VectorXd m_x_pred;\n\n   // predicted object covariance matrix\n   Eigen::MatrixXd m_P_pred;\n\n   // predicted Sigma Points\n   Eigen::MatrixXd m_XSigmaPointsPred;\n\nprivate:\n   const Eigen::ArrayXd calculateWeights()\n   {\n      Eigen::ArrayXd weights(PROCESSMODEL_T::m_nSigmaPoints);\n\n      weights(0) = m_lambda / (m_lambda + m_n_x_aug);\n\n      for (int i = 1; i < PROCESSMODEL_T::m_nSigmaPoints; ++i)\n      {\n         weights(i) = 0.5 / (m_lambda + m_n_x_aug);\n      }\n\n      return  weights;\n   }\n\n   int64_t m_previousTimestampUs;\n};\n\n#endif // UKF_HPP\n", "meta": {"hexsha": "b44f793b93681a66e9a4bdbeaf259ea85dadeed2", "size": 8419, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Ukf.hpp", "max_stars_repo_name": "monsieurmona/CarND-Unscented-Kalman-Filter-Project", "max_stars_repo_head_hexsha": "6ac3f2248e03fb363292b90f62a03dc453ac73cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-18T12:23:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-18T12:23:59.000Z", "max_issues_repo_path": "src/Ukf.hpp", "max_issues_repo_name": "monsieurmona/CarND-Unscented-Kalman-Filter-Project", "max_issues_repo_head_hexsha": "6ac3f2248e03fb363292b90f62a03dc453ac73cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Ukf.hpp", "max_forks_repo_name": "monsieurmona/CarND-Unscented-Kalman-Filter-Project", "max_forks_repo_head_hexsha": "6ac3f2248e03fb363292b90f62a03dc453ac73cd", "max_forks_repo_licenses": ["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.9312714777, "max_line_length": 214, "alphanum_fraction": 0.6536405749, "num_tokens": 2250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6384888050686988}}
{"text": "#include <algorithm>\n#include <fstream>\n#include <vector>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n#include <Eigen/Core>\n#include <Eigen/Householder>\n#include <Eigen/SparseCore>\n#include <Euclid/Descriptor/HKS.h>\n#include <Euclid/Descriptor/Histogram.h>\n#include <Euclid/IO/OffIO.h>\n#include <Euclid/IO/PlyIO.h>\n#include <Euclid/MeshUtil/CGALMesh.h>\n#include <Euclid/Geometry/Spectral.h>\n#include <Euclid/Util/Color.h>\n\n#include <config.h>\n\nusing Kernel = CGAL::Simple_cartesian<double>;\nusing Point_3 = Kernel::Point_3;\nusing Mesh = CGAL::Surface_mesh<Point_3>;\nusing Mat = Eigen::MatrixXd;\nusing Vec = Eigen::VectorXd;\nusing SpMat = Eigen::SparseMatrix<double>;\nusing Arr = Eigen::ArrayXXd;\n\nvoid eigs_to_color(const std::string& prefix,\n                   const std::vector<double>& positions,\n                   const std::vector<unsigned>& indices,\n                   const Mat& eigenfunctions)\n{\n    auto nv = positions.size() / 3;\n    for (int i = 0; i < 6; ++i) {\n        std::vector<double> eigenvector(nv);\n        Vec::Map(eigenvector.data(), nv) = eigenfunctions.col(i);\n        std::vector<uint8_t> colors;\n        Euclid::colormap(igl::COLOR_MAP_TYPE_JET, eigenvector, colors, true);\n        std::string fout(TMP_DIR);\n        fout.append(prefix)\n            .append(\"_eigenfunction_\")\n            .append(std::to_string(i))\n            .append(\".ply\");\n        Euclid::write_ply<3>(\n            fout, positions, nullptr, nullptr, &indices, &colors);\n    }\n}\n\nvoid eigs_recon(const std::string& prefix,\n                const std::vector<double>& positions,\n                const std::vector<unsigned>& indices,\n                const Mat& eigenfunctions)\n{\n    auto nv = positions.size() / 3;\n    Eigen::Map<const Mat> xyz(positions.data(), 3, nv);\n    EASSERT(xyz(1, 0) == positions[1]);\n    EASSERT(xyz(0, 1) == positions[3]);\n    Mat embedding = xyz * eigenfunctions;\n    std::vector<int> neigs{ 5, 20, 50, 100, 200, 300 };\n    for (auto ne : neigs) {\n        Mat xyz_recon =\n            embedding.leftCols(ne) * eigenfunctions.transpose().topRows(ne);\n        std::vector<double> recon(nv * 3);\n        Mat::Map(recon.data(), 3, nv) = xyz_recon;\n        std::string fout(TMP_DIR);\n        fout.append(prefix)\n            .append(\"_recon_\")\n            .append(std::to_string(ne))\n            .append(\".ply\");\n        Euclid::write_ply<3>(fout, recon, nullptr, nullptr, &indices, nullptr);\n    }\n}\n\nvoid hks_to_color(const std::vector<double>& positions,\n                  const std::vector<unsigned>& indices,\n                  const Arr& signatures,\n                  int vidx)\n{\n    std::vector<double> distances(signatures.cols());\n    for (int i = 0; i < signatures.cols(); ++i) {\n        distances[i] = Euclid::chi2(signatures.col(vidx), signatures.col(i));\n    }\n    std::vector<uint8_t> colors;\n    Euclid::colormap(\n        igl::COLOR_MAP_TYPE_JET, distances, colors, true, false, true);\n    std::string fout(TMP_DIR);\n    fout.append(\"hks_\").append(std::to_string(vidx)).append(\".ply\");\n    Euclid::write_ply<3>(fout, positions, nullptr, nullptr, &indices, &colors);\n}\n\nvoid hks_to_csv(const Arr& signatures)\n{\n    std::string fout(TMP_DIR);\n    fout.append(\"hks.csv\");\n    std::ofstream ofs(fout);\n    for (int i = 0; i < signatures.rows(); ++i) {\n        for (int j = 0; j < signatures.cols(); ++j) {\n            ofs << signatures(i, j) << \",\";\n        }\n        ofs << std::endl;\n    }\n}\n\nint main()\n{\n    // read and build mesh\n    std::vector<double> positions;\n    std::vector<unsigned> indices;\n    std::string fmesh(DATA_DIR);\n    fmesh.append(\"bumpy.off\");\n    Euclid::read_off<3>(fmesh, positions, nullptr, &indices, nullptr);\n    Mesh mesh;\n    Euclid::make_mesh<3>(mesh, positions, indices);\n\n    // solving eigenvalue problem\n    int k = 300;\n    Vec lambdas_lbo, lambdas_gl;\n    Mat phis_lbo, phis_gl;\n    Euclid::spectrum(\n        mesh, k, lambdas_lbo, phis_lbo, Euclid::SpecOp::mesh_laplacian);\n    Euclid::spectrum(\n        mesh, k, lambdas_gl, phis_gl, Euclid::SpecOp::graph_laplacian);\n\n    // eigenvectors of mesh laplacian need to be orthonormalized for recon\n    phis_lbo = phis_lbo.householderQr().householderQ();\n\n    // output eigenfunctions to colors\n    eigs_to_color(\"lbo\", positions, indices, phis_lbo);\n    eigs_to_color(\"gl\", positions, indices, phis_gl);\n\n    // eigen embedding and reconstruction\n    eigs_recon(\"lbo\", positions, indices, phis_lbo);\n    eigs_recon(\"gl\", positions, indices, phis_gl);\n\n    // use eigenstructures to compute heat kernel signature\n    Euclid::HKS<Mesh> hks;\n    hks.build(mesh, &lambdas_lbo, &phis_lbo);\n    Eigen::ArrayXXd hks_sigs;\n    hks.compute(hks_sigs, 100);\n    hks_to_color(positions, indices, hks_sigs, 240); // tip\n    hks_to_color(positions, indices, hks_sigs, 3);   // cube corner\n    hks_to_csv(hks_sigs);\n}\n", "meta": {"hexsha": "224670823288b83104b551e075c81f102e6383f8", "size": 4837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/spectral/main.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "examples/spectral/main.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/spectral/main.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 33.8251748252, "max_line_length": 79, "alphanum_fraction": 0.6295224313, "num_tokens": 1351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6384887973450967}}
{"text": "#include <inttypes.h>\n#include <iostream>\n#include <iomanip>\n#include <cstdlib>\n#include <cerrno>\n#include <NTL/mat_GF2.h>\n#include <NTL/GF2.h>\n#include <NTL/matrix.h>\n#include <vector>\n#include \"calc_tvalue.hpp\"\n\nusing namespace std;\nusing namespace NTL;\n\n//#define DEBUG\n\nnamespace {\n    Mat<GF2> Ident;\n    bool make_mat(Mat<GF2>& mat, uint64_t num);\n    size_t calc_order(Mat<GF2>& mat, size_t max);\n}\n\nint main(int argc, char * argv[])\n{\n\n    if (argc < 4) {\n        cout << argv[0] << \" s m max_tvalue\" << endl;\n        return -1;\n    }\n    errno = 0;\n    int s = strtoul(argv[1], NULL, 10);\n    int m = strtoul(argv[2], NULL, 10);\n    int max_tvalue = strtoul(argv[3], NULL, 10);\n    if (errno) {\n        cout << \" s, m and max_tvalue should be numbers\" << endl;\n        return -1;\n    }\n    cout << \"# s = \" << dec << s << endl;\n    cout << \"# m = \" << dec << m << endl;\n    cout << \"# max_tvalue = \" << dec << max_tvalue << endl;\n    ident(Ident, m);\n#if defined(DEBUG)\n    cout << \"main step 0.1\" << endl;\n#endif\n    int64_t max = 1 << (m * m);\n    Mat<GF2> mat;\n    mat.SetDims(m, m);\n    Mat<GF2> array[s];\n#if defined(DEBUG)\n    cout << \"main step 0.2\" << endl;\n#endif\n    vector<vector<int> >to;\n    to.resize(max_tvalue + 1);\n#if defined(DEBUG)\n    cout << \"main step 1\" << endl;\n#endif\n    for (int i = 0; i <= max_tvalue; i++) {\n        to[i].resize(max);\n        for (int64_t j = 0; j < max; j++) {\n            to[i][j] = 0;\n        }\n    }\n#if defined(DEBUG)\n    cout << \"main step 2\" << endl;\n#endif\n    for (int64_t cnt = 1; cnt < max; cnt++) {\n        if (!make_mat(mat, cnt)) {\n            continue;\n        }\n        int order = calc_order(mat, max - 1);\n        if (order < s) {\n            continue;\n        }\n        array[0] = mat;\n        for (int j = 1; j < s; j++) {\n            array[j] = array[j - 1] * mat;\n        }\n        int tvalue = calc_tvalue(array, s, max_tvalue);\n        if (tvalue > max_tvalue || tvalue < 0) {\n            continue;\n        }\n        to[tvalue][order] += 1;\n        if (tvalue == 0 && order == max -1) {\n            cout << \"found!\" << endl;\n            cout << \"cnt = \" << dec << cnt << endl;\n            cout << \"tvalue = \" << dec << tvalue << endl;\n            cout << \"order = \" << dec << order << endl;\n            cout << mat;\n        }\n    }\n    cout << \"(tvalue, order) = cnt\" << endl;\n    for (int i = 0; i <= max_tvalue; i++) {\n        for (int64_t j = 0; j < max; j++) {\n            if (to[i][j] == 0) {\n                continue;\n            }\n            cout << \"(\" << dec << i << \",\"\n                 << j << \") = \" << to[i][j] << endl;\n        }\n    }\n    return 0;\n}\n\nnamespace {\n    bool make_mat(Mat<GF2>& mat, uint64_t num)\n    {\n#if defined(DEBUG)\n        cout << \"start make_mat\" << endl;\n#endif\n        //cout << \"num = \" << dec << num << endl;\n        int m = mat.NumRows();\n        const uint64_t mask = ~UINT64_C(0) >> (64 - m);\n        for (int i = 0; i < m; i++) {\n            uint64_t row = num & mask;\n            if (row == 0) {\n#if defined(DEBUG)\n                cout << \"end make_mat\" << endl;\n#endif\n                return false;\n            }\n            for (int j = 0; j < m; j++) {\n                //cout << \"mat.put(\" << i << \",\" << j << \",\" << (row & 1) << \")\"\n                //     << endl;\n                mat.put(i, j, row & 1);\n                row = row >> 1;\n            }\n            num = num >> m;\n        }\n        //cout << \"make_mat 1:\" << mat << endl;\n        Mat<GF2> w = mat;\n        if (gauss(w) != m) {\n#if defined(DEBUG)\n            cout << \"end make_mat\" << endl;\n#endif\n            return false;\n        }\n        //cout << \"make_mat 2:\\n\" << mat << endl;\n#if defined(DEBUG)\n        cout << \"end make_mat\" << endl;\n#endif\n        return true;\n    }\n\n    size_t calc_order(Mat<GF2>& mat, size_t max)\n    {\n        Mat<GF2> w = mat;\n        for (size_t i = 1; i <= max; i++) {\n            w = w * mat;\n            if (w == mat) {\n                return i;\n            }\n        }\n        return max;\n    }\n}\n", "meta": {"hexsha": "b9b8d5512febd9d3323acc22813857b94ff670aa", "size": 4027, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/order_test.cpp", "max_stars_repo_name": "MSaito/ntl-test1", "max_stars_repo_head_hexsha": "e9aed985dad50a49510c435007c610ac7066df21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/order_test.cpp", "max_issues_repo_name": "MSaito/ntl-test1", "max_issues_repo_head_hexsha": "e9aed985dad50a49510c435007c610ac7066df21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/order_test.cpp", "max_forks_repo_name": "MSaito/ntl-test1", "max_forks_repo_head_hexsha": "e9aed985dad50a49510c435007c610ac7066df21", "max_forks_repo_licenses": ["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.8141025641, "max_line_length": 80, "alphanum_fraction": 0.4370499131, "num_tokens": 1208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.6384636257058824}}
{"text": "#include \"drakeGeometryUtil.h\"\n#include <iostream>\n#include <cmath>\n#include <limits>\n#include <stdexcept>\n#include <Eigen/Sparse>\n#include \"expmap2quat.h\"\n\nusing namespace Eigen;\n\n\ndouble angleDiff(double phi1, double phi2)\n{\n  double d = phi2-phi1;\n  if(d>0.0)\n  {\n    d = fmod(d+M_PI,2*M_PI)-M_PI;\n  }\n  else\n  {\n    d = fmod(d-M_PI,2*M_PI)+M_PI;\n  }\n  return d;\n}\n\n\nVector4d quatConjugate(const Eigen::Vector4d& q)\n{\n  Vector4d q_conj;\n  q_conj << q(0), -q(1), -q(2), -q(3);\n  return q_conj;\n}\n\nEigen::Matrix4d dquatConjugate()\n{\n  Matrix4d dq_conj = Matrix4d::Identity();\n  dq_conj(1, 1) = -1.0;\n  dq_conj(2, 2) = -1.0;\n  dq_conj(3, 3) = -1.0;\n  return dq_conj;\n}\n\nEigen::Vector4d quatProduct(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2)\n{\n  double w1 = q1(0);\n  double w2 = q2(0);\n  const auto& v1 = q1.tail<3>();\n  const auto& v2 = q2.tail<3>();\n  Vector4d r;\n  r << w1 * w2 - v1.dot(v2), v1.cross(v2) + w1 * v2 + w2 * v1;\n  return r;\n}\n\nEigen::Matrix<double, 4, 8> dquatProduct(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2)\n{\n  double w1 = q1(0);\n  double w2 = q2(0);\n  const auto& v1 = q1.tail<3>();\n  const auto& v2 = q2.tail<3>();\n\n  Matrix<double, 4, 8> dr;\n  dr.row(0) << w2, -v2.transpose(), w1, -v1.transpose();\n  dr.row(1) << q2(1), q2(0), q2(3), -q2(2), q1(1), q1(0), -q1(3), q1(2);\n  dr.row(2) << q2(2), -q2(3), q2(0), q2(1), q1(2), q1(3), q1(0), -q1(1);\n  dr.row(3) << q2(3), q2(2), -q2(1), q2(0), q1(3), -q1(2), q1(1), q1(0);\n  return dr;\n}\n\nEigen::Vector3d quatRotateVec(const Eigen::Vector4d& q, const Eigen::Vector3d& v)\n{\n  Vector4d v_quat;\n  v_quat << 0, v;\n  Vector4d q_times_v = quatProduct(q, v_quat);\n  Vector4d q_conj = quatConjugate(q);\n  Vector4d v_rot = quatProduct(q_times_v, q_conj);\n  Vector3d r = v_rot.bottomRows<3>();\n  return r;\n}\n\nEigen::Matrix<double, 3, 7> dquatRotateVec(const Eigen::Vector4d& q, const Eigen::Vector3d& v)\n{\n  Matrix<double, 4, 7> dq;\n  dq << Matrix4d::Identity(), MatrixXd::Zero(4, 3);\n  Matrix<double, 4, 7> dv = Matrix<double, 4, 7>::Zero();\n  dv.bottomRightCorner<3, 3>() = Matrix3d::Identity();\n  Matrix<double, 8, 7> dqdv;\n  dqdv << dq, dv;\n\n  Vector4d v_quat;\n  v_quat << 0, v;\n  Vector4d q_times_v = quatProduct(q, v_quat);\n  Matrix<double, 4, 8> dq_times_v_tmp = dquatProduct(q, v_quat);\n  Matrix<double, 4, 7> dq_times_v = dq_times_v_tmp * dqdv;\n\n  Matrix<double, 4, 7> dq_conj = dquatConjugate() * dq;\n  Matrix<double, 8, 7> dq_times_v_dq_conj;\n  dq_times_v_dq_conj << dq_times_v, dq_conj;\n  Matrix<double, 4, 8> dv_rot_tmp = dquatProduct(q_times_v, quatConjugate(q));\n  Matrix<double, 4, 7> dv_rot = dv_rot_tmp * dq_times_v_dq_conj;\n  Eigen::Matrix<double, 3, 7> dr = dv_rot.bottomRows(3);\n  return dr;\n}\n\nEigen::Vector4d quatDiff(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2)\n{\n  return quatProduct(quatConjugate(q1), q2);\n}\n\nEigen::Matrix<double, 4, 8> dquatDiff(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2)\n{\n  auto dr = dquatProduct(quatConjugate(q1), q2);\n  dr.block<4, 3>(0, 1) = -dr.block<4, 3>(0, 1);\n  return dr;\n}\n\ndouble quatDiffAxisInvar(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2, const Eigen::Vector3d& u)\n{\n  Vector4d r = quatDiff(q1, q2);\n  double e = -2.0 + 2 * r(0) * r(0) + 2 * pow(u(0) * r(1) + u(1) * r(2) + u(2) * r(3), 2);\n  return e;\n}\n\nEigen::Matrix<double, 1, 11> dquatDiffAxisInvar(const Eigen::Vector4d& q1, const Eigen::Vector4d& q2, const Eigen::Vector3d& u)\n{\n  Vector4d r = quatDiff(q1, q2);\n  Matrix<double, 4, 8> dr = dquatDiff(q1, q2);\n  Matrix<double, 1, 11> de;\n  const auto& rvec = r.tail<3>();\n  de << 4.0 * r(0) * dr.row(0) + 4.0 * u.transpose() * rvec *u.transpose() * dr.block<3, 8>(1, 0), 4.0 * u.transpose() * rvec * rvec.transpose();\n  return de;\n}\n\ndouble quatNorm(const Eigen::Vector4d& q)\n{\n  return std::acos(q(0));\n}\n\nVector4d uniformlyRandomAxisAngle(std::default_random_engine& generator)\n{\n  std::normal_distribution<double> normal;\n  std::uniform_real_distribution<double> uniform(-M_PI, M_PI);\n  double angle = uniform(generator);\n  Vector3d axis = Vector3d(normal(generator), normal(generator), normal(generator));\n  axis.normalize();\n  Vector4d a;\n  a << axis, angle;\n  return a;\n}\n\nVector4d uniformlyRandomQuat(std::default_random_engine& generator)\n{\n  return axis2quat(uniformlyRandomAxisAngle(generator));\n}\n\nEigen::Matrix3d uniformlyRandomRotmat(std::default_random_engine& generator)\n{\n  return axis2rotmat(uniformlyRandomAxisAngle(generator));\n}\n\nEigen::Vector3d uniformlyRandomRPY(std::default_random_engine& generator)\n{\n  return axis2rpy(uniformlyRandomAxisAngle(generator));\n}\n\ntemplate <typename Derived>\nEigen::Matrix<typename Derived::Scalar, 3, 1> quat2rpy(const Eigen::MatrixBase<Derived>& q)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 4);\n  auto q_normalized = q.normalized();\n  auto w = q_normalized(0);\n  auto x = q_normalized(1);\n  auto y = q_normalized(2);\n  auto z = q_normalized(3);\n\n  Eigen::Matrix<typename Derived::Scalar, 3, 1> ret;\n  ret << std::atan2(2.0*(w*x + y*z), w*w + z*z -(x*x +y*y)),\n      std::asin(2.0*(w*y - z*x)),\n      std::atan2(2.0*(w*z + x*y), w*w + x*x-(y*y+z*z));\n  return ret;\n}\n\ntemplate <typename Derived>\nEigen::Matrix<typename Derived::Scalar, 3, 3> quat2rotmat(const Eigen::MatrixBase<Derived>& q)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 4);\n  auto q_normalized = q.normalized();\n  auto w = q_normalized(0);\n  auto x = q_normalized(1);\n  auto y = q_normalized(2);\n  auto z = q_normalized(3);\n\n  Eigen::Matrix<typename Derived::Scalar, 3, 3> M;\n  M.row(0) << w * w + x * x - y * y - z * z, 2.0 * x * y - 2.0 * w * z, 2.0 * x * z + 2.0 * w * y;\n  M.row(1) << 2.0 * x * y + 2.0 * w * z, w * w + y * y - x * x - z * z, 2.0 * y * z - 2.0 * w * x;\n  M.row(2) << 2.0 * x * z - 2.0 * w * y, 2.0 * y * z + 2.0 * w * x, w * w + z * z - x * x - y * y;\n\n  return M;\n}\n\ntemplate <typename Derived>\nEigen::Matrix<typename Derived::Scalar, 4, 1> quat2axis(const Eigen::MatrixBase<Derived>& q)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 4);\n  auto q_normalized = q.normalized();\n  auto s = std::sqrt(1.0 - q_normalized(0) * q_normalized(0)) + std::numeric_limits<typename Derived::Scalar>::epsilon();\n  Eigen::Matrix<typename Derived::Scalar, 4, 1> a;\n\n  a << q_normalized.template tail<3>() / s, 2.0 * std::acos(q_normalized(0));\n  return a;\n}\n\ntemplate <typename Derived>\nEigen::Vector4d axis2quat(const Eigen::MatrixBase<Derived>& a)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 4);\n  auto axis = a.template head<3>();\n  auto angle = a(3);\n  auto arg = 0.5 * angle;\n  auto c = std::cos(arg);\n  auto s = std::sin(arg);\n  Eigen::Vector4d ret;\n  ret << c, s * axis;\n  return ret;\n}\n\ntemplate <typename Derived>\nEigen::Matrix<typename Derived::Scalar, 3, 3> axis2rotmat(const Eigen::MatrixBase<Derived>& a)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 4);\n  const auto& axis = (a.template head<3>())/(a.template head<3>()).norm();\n  const auto& theta = a(3);\n  auto x = axis(0);\n  auto y = axis(1);\n  auto z = axis(2);\n  auto ctheta = std::cos(theta);\n  auto stheta = std::sin(theta);\n  auto c = 1 - ctheta;\n  Eigen::Matrix<typename Derived::Scalar, 3, 3> R;\n  R <<\n      ctheta + x * x * c , x * y * c - z * stheta, x * z * c + y * stheta,\n      y * x * c + z * stheta, ctheta + y * y * c, y * z * c - x * stheta,\n      z * x * c - y * stheta, z * y * c + x * stheta, ctheta + z * z * c;\n\n  return R;\n}\n\ntemplate <typename Derived>\nEigen::Matrix<typename Derived::Scalar, 3, 1> axis2rpy(const Eigen::MatrixBase<Derived>& a)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 4);\n  return quat2rpy(axis2quat(a));\n}\n\ntemplate <typename Derived>\nEigen::Matrix<typename Derived::Scalar, 4, 1> rotmat2axis(const Eigen::MatrixBase<Derived>& R)\n{\n  EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 3, 3);\n\n  typename Derived::Scalar theta = std::acos((R.trace() - 1.0) / 2.0);\n  Vector4d a;\n  if (theta > std::numeric_limits<typename Derived::Scalar>::epsilon()) {\n    a << R(2, 1) - R(1, 2), R(0, 2) - R(2, 0), R(1, 0) - R(0, 1), theta;\n    a.head<3>() *= 1.0 / (2.0 * std::sin(theta));\n  }\n  else {\n    a << 1.0, 0.0, 0.0, 0.0;\n  }\n  return a;\n}\n\ntemplate <typename Derived>\nEigen::Matrix<typename Derived::Scalar, 4, 1> rotmat2quat(const Eigen::MatrixBase<Derived>& M)\n{\n  EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 3, 3);\n  using namespace std;\n\n  Matrix<typename Derived::Scalar, 4, 3> A;\n  A.row(0) << 1.0, 1.0, 1.0;\n  A.row(1) << 1.0, -1.0, -1.0;\n  A.row(2) << -1.0, 1.0, -1.0;\n  A.row(3) << -1.0, -1.0, 1.0;\n  Matrix<typename Derived::Scalar, 4, 1> B = A * M.diagonal();\n  typename Matrix<typename Derived::Scalar, 4, 1>::Index ind, max_col;\n  typename Derived::Scalar val = B.maxCoeff(&ind, &max_col);\n\n  typename Derived::Scalar w, x, y, z;\n  switch (ind) {\n  case 0: {\n    // val = trace(M)\n    w = sqrt(1.0 + val) / 2.0;\n    typename Derived::Scalar w4 = w * 4.0;\n    x = (M(2, 1) - M(1, 2)) / w4;\n    y = (M(0, 2) - M(2, 0)) / w4;\n    z = (M(1, 0) - M(0, 1)) / w4;\n    break;\n  }\n  case 1: {\n    // val = M(1,1) - M(2,2) - M(3,3)\n    double s = 2.0 * sqrt(1.0 + val);\n    w = (M(2, 1) - M(1, 2)) / s;\n    x = 0.25 * s;\n    y = (M(0, 1) + M(1, 0)) / s;\n    z = (M(0, 2) + M(2, 0)) / s;\n    break;\n  }\n  case 2: {\n    //  % val = M(2,2) - M(1,1) - M(3,3)\n    double s = 2.0 * (sqrt(1.0 + val));\n    w = (M(0, 2) - M(2, 0)) / s;\n    x = (M(0, 1) + M(1, 0)) / s;\n    y = 0.25 * s;\n    z = (M(1, 2) + M(2, 1)) / s;\n    break;\n  }\n  default: {\n    // val = M(3,3) - M(2,2) - M(1,1)\n    double s = 2.0 * (sqrt(1.0 + val));\n    w = (M(1, 0) - M(0, 1)) / s;\n    x = (M(0, 2) + M(2, 0)) / s;\n    y = (M(1, 2) + M(2, 1)) / s;\n    z = 0.25 * s;\n    break;\n  }\n  }\n\n  Eigen::Matrix<typename Derived::Scalar, 4, 1> q;\n  q << w, x, y, z;\n  return q;\n}\n\ntemplate<typename Derived>\nEigen::Matrix<typename Derived::Scalar, 3, 1> rotmat2rpy(const Eigen::MatrixBase<Derived>& R)\n{\n  EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 3, 3);\n  using namespace std;\n\n  Eigen::Matrix<typename Derived::Scalar, 3, 1> rpy;\n  rpy << atan2(R(2, 1), R(2, 2)), atan2(-R(2, 0), sqrt(pow(R(2, 1), 2.0) + pow(R(2, 2), 2.0))), atan2(R(1, 0), R(0, 0));\n  return rpy;\n}\n\ntemplate<typename Derived>\nDLLEXPORT Eigen::Matrix<typename Derived::Scalar, Eigen::Dynamic, 1> rotmat2Representation(const Eigen::MatrixBase<Derived>& R, int rotation_type)\n{\n  typedef typename Derived::Scalar Scalar;\n  Eigen::Matrix<Scalar, Eigen::Dynamic, 1> ret;\n  switch (rotation_type) {\n  case 0:\n    return Eigen::Matrix<Scalar, Eigen::Dynamic, 1>(0, 1);\n  case 1:\n    return rotmat2rpy(R);\n  case 2:\n    return rotmat2quat(R);\n  default:\n    throw std::runtime_error(\"rotation representation type not recognized\");\n  }\n}\n\ntemplate<typename Scalar>\nDLLEXPORT GradientVar<Scalar, Eigen::Dynamic, 1> rotmat2Representation(const GradientVar<Scalar, SPACE_DIMENSION, SPACE_DIMENSION>& R, int rotation_type)\n{\n  GradientVar<Scalar, Eigen::Dynamic, 1> ret(rotationRepresentationSize(rotation_type), 1, R.getNumVariables(), R.maxOrder());\n  switch (rotation_type) {\n  case 0:\n    // empty matrix, already done\n    break;\n  case 1:\n    ret.value() = rotmat2rpy(R.value());\n    if (R.hasGradient()) {\n      ret.gradient().value() = drotmat2rpy(R.value(), R.gradient().value());\n    }\n    break;\n  case 2:\n    ret.value() = rotmat2quat(R.value());\n    if (R.hasGradient()) {\n      ret.gradient().value() = drotmat2quat(R.value(), R.gradient().value());\n    }\n    break;\n  default:\n    throw std::runtime_error(\"rotation representation type not recognized\");\n  }\n  return ret;\n}\n\ntemplate <typename Derived>\nGradientVar<typename Derived::Scalar, QUAT_SIZE, 1> expmap2quat(const Eigen::MatrixBase<Derived>& v, const int gradient_order)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 3);\n  GradientVar<typename Derived::Scalar, QUAT_SIZE, 1> ret(QUAT_SIZE, 1, EXPMAP_SIZE,gradient_order);\n  auto theta = v.norm();\n  if (theta < pow(std::numeric_limits<typename Derived::Scalar>::epsilon(),0.25)) {\n    ret.value() = expmap2quatDegenerate(v, theta);\n    if(gradient_order>0)\n    {\n      ret.gradient().value() = dexpmap2quatDegenerate(v, theta);\n      if(gradient_order>1)\n      {\n        ret.gradient().gradient().value() = ddexpmap2quatDegenerate(v, theta);\n        if(gradient_order>2)\n        {\n          throw std::runtime_error(\"expmap2quat does not support gradient order larger than 2\");\n        }\n      }\n    }\n  } else {\n    ret.value() = expmap2quatNonDegenerate(v, theta);\n    if(gradient_order>0)\n    {\n      ret.gradient().value() = dexpmap2quatNonDegenerate(v, theta);\n      if(gradient_order>1)\n      {\n        ret.gradient().gradient().value() = ddexpmap2quatNonDegenerate(v, theta);\n        if(gradient_order>2)\n        {\n          throw std::runtime_error(\"expmap2quat does not support gradient order larger than 2\");\n        }\n      }\n    }\n  }\n  return ret;\n}\n\nDLLEXPORT int rotationRepresentationSize(int rotation_type)\n{\n  switch (rotation_type) {\n  case 0:\n    return 0;\n    break;\n  case 1:\n    return 3;\n    break;\n  case 2:\n    return 4;\n    break;\n  default:\n    throw std::runtime_error(\"rotation representation type not recognized\");\n  }\n}\n\ntemplate<typename Derived>\nEigen::Matrix<typename Derived::Scalar, 4, 1> rpy2axis(const Eigen::MatrixBase<Derived>& rpy)\n{\n  return quat2axis(rpy2quat(rpy));\n}\n\ntemplate<typename Derived>\nEigen::Matrix<typename Derived::Scalar, 4, 1> rpy2quat(const Eigen::MatrixBase<Derived>& rpy)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 3);\n  auto rpy_2 = (rpy / 2.0).array();\n  auto s = rpy_2.sin();\n  auto c = rpy_2.cos();\n\n  Vector4d q;\n  q << c(0)*c(1)*c(2) + s(0)*s(1)*s(2),\n        s(0)*c(1)*c(2) - c(0)*s(1)*s(2),\n        c(0)*s(1)*c(2) + s(0)*c(1)*s(2),\n        c(0)*c(1)*s(2) - s(0)*s(1)*c(2);\n\n  q /= q.norm() + std::numeric_limits<typename Derived::Scalar>::epsilon();\n  return q;\n}\n\ntemplate<typename Derived>\nEigen::Matrix<typename Derived::Scalar, 3, 3> rpy2rotmat(const Eigen::MatrixBase<Derived>& rpy)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 3);\n  auto rpy_array = rpy.array();\n  auto s = rpy_array.sin();\n  auto c = rpy_array.cos();\n\n  Eigen::Matrix<typename Derived::Scalar, 3, 3> R;\n  R.row(0) << c(2) * c(1), c(2) * s(1) * s(0) - s(2) * c(0), c(2) * s(1) * c(0) + s(2) * s(0);\n  R.row(1) << s(2) * c(1), s(2) * s(1) * s(0) + c(2) * c(0), s(2) * s(1) * c(0) - c(2) * s(0);\n  R.row(2) << -s(1), c(1) * s(0), c(1) * c(0);\n\n  return R;\n}\n\nMatrix3d rotz(double theta) {\n  // returns 3D rotation matrix (about the z axis)\n  Matrix3d M;\n  double c=cos(theta);\n  double s=sin(theta);\n  M << c,-s, 0,\n     s, c, 0,\n     0, 0, 1;\n  return M;\n}\n\n\nvoid rotz(double theta, Matrix3d &M, Matrix3d &dM, Matrix3d &ddM)\n{\n  double c=cos(theta), s=sin(theta);\n  M << c,-s,0, s,c,0, 0,0,1;\n  dM << -s,-c,0, c,-s,0, 0,0,0;\n  ddM << -c,s,0, -s,-c,0, 0,0,0;\n}\n\ntemplate<typename Derived>\nEigen::Matrix<typename Derived::Scalar,9,3> drpy2rotmat(const Eigen::MatrixBase<Derived>& rpy)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, 3);\n  auto rpy_array = rpy.array();\n  auto s = rpy_array.sin();\n  auto c = rpy_array.cos();\n\n\tEigen::Matrix<typename Derived::Scalar, 9, 3> dR;\n\tdR.row(0) << 0, c(2)*-s(1), c(1)*-s(2);\n\tdR.row(1) << 0, -s(1)*s(2), c(2)*c(1);\n\tdR.row(2) << 0, -c(1), 0;\n\tdR.row(3) << c(2)*s(1)*c(0)-s(2)*-s(0), c(2)*c(1)*s(0), -s(2)*s(1)*s(0)-c(2)*c(0);\n\tdR.row(4) << s(2)*s(1)*c(0)+c(2)*-s(0), s(2)*c(1)*s(0), c(2)*s(1)*s(0)-s(2)*c(0);\n\tdR.row(5) << c(1)*c(0), -s(1)*s(0),0;\n\tdR.row(6) << c(2)*s(1)*-s(0)+s(2)*c(0), c(2)*c(1)*c(0), -s(2)*s(1)*c(0)+c(2)*s(0);\n\tdR.row(7) << s(2)*s(1)*-s(0)-c(2)*c(0), s(2)*c(1)*c(0), c(2)*s(1)*c(0)+s(2)*s(0);\n\tdR.row(8) << c(1)*-s(0), -s(1)*c(0), 0; \n\n\treturn dR;\n}\n\n// NOTE: not reshaping second derivative to Matlab geval output format!\ntemplate <typename Derived>\nvoid normalizeVec(\n    const Eigen::MatrixBase<Derived>& x,\n    typename Derived::PlainObject& x_norm,\n    typename Gradient<Derived, Derived::RowsAtCompileTime, 1>::type* dx_norm,\n    typename Gradient<Derived, Derived::RowsAtCompileTime, 2>::type* ddx_norm) {\n\n  typename Derived::Scalar xdotx = x.squaredNorm();\n  typename Derived::Scalar norm_x = std::sqrt(xdotx);\n  x_norm = x / norm_x;\n\n  if (dx_norm) {\n    dx_norm->setIdentity(x.rows(), x.rows());\n    (*dx_norm) -= x * x.transpose() / xdotx;\n    (*dx_norm) /= norm_x;\n\n    if (ddx_norm) {\n      auto dx_norm_transpose = transposeGrad(*dx_norm, x.rows());\n      auto ddx_norm_times_norm = -matGradMultMat(x_norm, x_norm.transpose(), (*dx_norm), dx_norm_transpose);\n      auto dnorm_inv = -x.transpose() / (xdotx * norm_x);\n      (*ddx_norm) = ddx_norm_times_norm / norm_x;\n      auto temp = (*dx_norm) * norm_x;\n      typename Derived::Index n = x.rows();\n      for (int col = 0; col < n; col++) {\n        auto column_as_matrix = (dnorm_inv(0, col) * temp);\n        for (int row_block = 0; row_block < n; row_block++) {\n          ddx_norm->block(row_block * n, col, n, 1) += column_as_matrix.col(row_block);\n        }\n      }\n    }\n  }\n}\n\n\n\ntemplate <typename Derived>\ntypename Gradient<Matrix<typename Derived::Scalar, 3, 3>, QUAT_SIZE>::type dquat2rotmat(const Eigen::MatrixBase<Derived>& q)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, QUAT_SIZE);\n\n  typename Gradient<Matrix<typename Derived::Scalar, 3, 3>, QUAT_SIZE>::type ret;\n  typename Eigen::MatrixBase<Derived>::PlainObject qtilde;\n  typename Gradient<Derived, QUAT_SIZE>::type dqtilde;\n  normalizeVec(q, qtilde, &dqtilde);\n\n  typedef typename Derived::Scalar Scalar;\n  Scalar w=qtilde(0);\n  Scalar x=qtilde(1);\n  Scalar y=qtilde(2);\n  Scalar z=qtilde(3);\n\n  ret << w, x, -y, -z, z, y, x, w, -y, z, -w, x, -z, y, x, -w, w, -x, y, -z, x, w, z, y, y, z, w, x, -x, -w, z, y, w, -x, -y, z;\n  ret *= 2.0;\n  ret *= dqtilde;\n  return ret;\n}\n\ntemplate <typename DerivedR, typename DerivedDR>\ntypename Gradient<Eigen::Matrix<typename DerivedR::Scalar, RPY_SIZE, 1>, DerivedDR::ColsAtCompileTime>::type drotmat2rpy(\n    const Eigen::MatrixBase<DerivedR>& R,\n    const Eigen::MatrixBase<DerivedDR>& dR)\n{\n  EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Eigen::MatrixBase<DerivedR>, SPACE_DIMENSION, SPACE_DIMENSION);\n  EIGEN_STATIC_ASSERT(Eigen::MatrixBase<DerivedDR>::RowsAtCompileTime == RotmatSize, THIS_METHOD_IS_ONLY_FOR_MATRICES_OF_A_SPECIFIC_SIZE);\n\n  typename DerivedDR::Index nq = dR.cols();\n  typedef typename DerivedR::Scalar Scalar;\n  typedef typename Gradient<Eigen::Matrix<Scalar, RPY_SIZE, 1>, DerivedDR::ColsAtCompileTime>::type ReturnType;\n  ReturnType drpy(RPY_SIZE, nq);\n\n  auto dR11_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 0, 0, R.rows());\n  auto dR21_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 1, 0, R.rows());\n  auto dR31_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 2, 0, R.rows());\n  auto dR32_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 2, 1, R.rows());\n  auto dR33_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 2, 2, R.rows());\n\n  Scalar sqterm = R(2,1) * R(2,1) + R(2,2) * R(2,2);\n\n  using namespace std;\n  // droll_dq\n  drpy.row(0) = (R(2, 2) * dR32_dq - R(2, 1) * dR33_dq) / sqterm;\n\n  // dpitch_dq\n  Scalar sqrt_sqterm = sqrt(sqterm);\n  drpy.row(1) = (-sqrt_sqterm * dR31_dq + R(2, 0) / sqrt_sqterm * (R(2, 1) * dR32_dq + R(2, 2) * dR33_dq)) / (R(2, 0) * R(2, 0) + R(2, 1) * R(2, 1) + R(2, 2) * R(2, 2));\n\n  // dyaw_dq\n  sqterm = R(0, 0) * R(0, 0) + R(1, 0) * R(1, 0);\n  drpy.row(2) = (R(0, 0) * dR21_dq - R(1, 0) * dR11_dq) / sqterm;\n  return drpy;\n}\n\ntemplate <typename DerivedR, typename DerivedDR>\ntypename Gradient<Eigen::Matrix<typename DerivedR::Scalar, QUAT_SIZE, 1>, DerivedDR::ColsAtCompileTime>::type drotmat2quat(\n    const Eigen::MatrixBase<DerivedR>& R,\n    const Eigen::MatrixBase<DerivedDR>& dR)\n{\n  EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Eigen::MatrixBase<DerivedR>, SPACE_DIMENSION, SPACE_DIMENSION);\n  EIGEN_STATIC_ASSERT(Eigen::MatrixBase<DerivedDR>::RowsAtCompileTime == RotmatSize, THIS_METHOD_IS_ONLY_FOR_MATRICES_OF_A_SPECIFIC_SIZE);\n\n  typedef typename DerivedR::Scalar Scalar;\n  typedef typename Gradient<Eigen::Matrix<Scalar, QUAT_SIZE, 1>, DerivedDR::ColsAtCompileTime>::type ReturnType;\n  typename DerivedDR::Index nq = dR.cols();\n\n  auto dR11_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 0, 0, R.rows());\n  auto dR12_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 0, 1, R.rows());\n  auto dR13_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 0, 2, R.rows());\n  auto dR21_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 1, 0, R.rows());\n  auto dR22_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 1, 1, R.rows());\n  auto dR23_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 1, 2, R.rows());\n  auto dR31_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 2, 0, R.rows());\n  auto dR32_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 2, 1, R.rows());\n  auto dR33_dq = getSubMatrixGradient<DerivedDR::ColsAtCompileTime>(dR, 2, 2, R.rows());\n\n  Matrix<Scalar, 4, 3> A;\n  A.row(0) << 1.0, 1.0, 1.0;\n  A.row(1) << 1.0, -1.0, -1.0;\n  A.row(2) << -1.0, 1.0, -1.0;\n  A.row(3) << -1.0, -1.0, 1.0;\n  Matrix<Scalar, 4, 1> B = A * R.diagonal();\n  typename Matrix<Scalar, 4, 1>::Index ind, max_col;\n  Scalar val = B.maxCoeff(&ind, &max_col);\n\n  ReturnType dq(QUAT_SIZE, nq);\n  using namespace std;\n  switch (ind) {\n  case 0: {\n    // val = trace(M)\n    auto dvaldq = dR11_dq + dR22_dq + dR33_dq;\n    auto dwdq = dvaldq / (4.0 * sqrt(1.0 + val));\n    auto w = sqrt(1.0 + val) / 2.0;\n    auto wsquare4 = 4.0 * w * w;\n    dq.row(0) = dwdq;\n    dq.row(1) = ((dR32_dq - dR23_dq) * w - (R(2, 1) - R(1, 2)) * dwdq) / wsquare4;\n    dq.row(2) = ((dR13_dq - dR31_dq) * w - (R(0, 2) - R(2, 0)) * dwdq) / wsquare4;\n    dq.row(3) = ((dR21_dq - dR12_dq) * w - (R(1, 0) - R(0, 1)) * dwdq) / wsquare4;\n    break;\n  }\n  case 1: {\n    // val = M(1,1) - M(2,2) - M(3,3)\n    auto dvaldq = dR11_dq - dR22_dq - dR33_dq;\n    auto s = 2.0 * sqrt(1.0 + val);\n    auto ssquare = s * s;\n    auto dsdq = dvaldq / sqrt(1.0 + val);\n    dq.row(0) = ((dR32_dq - dR23_dq) * s - (R(2, 1) - R(1, 2)) * dsdq) / ssquare;\n    dq.row(1) = .25 * dsdq;\n    dq.row(2) = ((dR12_dq + dR21_dq) * s - (R(0, 1) + R(1, 0)) * dsdq) / ssquare;\n    dq.row(3) = ((dR13_dq + dR31_dq) * s - (R(0, 2) + R(2, 0)) * dsdq) / ssquare;\n    break;\n  }\n  case 2: {\n    // val = M(2,2) - M(1,1) - M(3,3)\n    auto dvaldq = -dR11_dq + dR22_dq - dR33_dq;\n    auto s = 2.0 * (sqrt(1.0 + val));\n    auto ssquare = s * s;\n    auto dsdq = dvaldq / sqrt(1.0 + val);\n    dq.row(0) = ((dR13_dq - dR31_dq) * s - (R(0, 2) - R(2, 0)) * dsdq) / ssquare;\n    dq.row(1) = ((dR12_dq + dR21_dq) * s - (R(0, 1) + R(1, 0)) * dsdq) / ssquare;\n    dq.row(2) = .25 * dsdq;\n    dq.row(3) = ((dR23_dq + dR32_dq) * s - (R(1, 2) + R(2, 1)) * dsdq) / ssquare;\n    break;\n  }\n  default: {\n    // val = M(3,3) - M(2,2) - M(1,1)\n    auto dvaldq = -dR11_dq - dR22_dq + dR33_dq;\n    auto s = 2.0 * (sqrt(1.0 + val));\n    auto ssquare = s * s;\n    auto dsdq = dvaldq / sqrt(1.0 + val);\n    dq.row(0) = ((dR21_dq - dR12_dq) * s - (R(1, 0) - R(0, 1)) * dsdq) / ssquare;\n    dq.row(1) = ((dR13_dq + dR31_dq) * s - (R(0, 2) + R(2, 0)) * dsdq) / ssquare;\n    dq.row(2) = ((dR23_dq + dR32_dq) * s - (R(1, 2) + R(2, 1)) * dsdq) / ssquare;\n    dq.row(3) = .25 * dsdq;\n    break;\n  }\n  }\n  return dq;\n}\n\ntemplate<typename Derived>\nEigen::Matrix<typename Derived::Scalar, 3, 3> vectorToSkewSymmetric(const Eigen::MatrixBase<Derived>& p)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<Derived>, SPACE_DIMENSION);\n  Eigen::Matrix<typename Derived::Scalar, 3, 3> ret;\n  ret << 0.0, -p(2), p(1), p(2), 0.0, -p(0), -p(1), p(0), 0.0;\n  return ret;\n}\n\ntemplate <typename DerivedA, typename DerivedB>\nEigen::Matrix<typename DerivedA::Scalar, 3, Eigen::Dynamic> dcrossProduct(\n    const Eigen::MatrixBase<DerivedA>& a,\n    const Eigen::MatrixBase<DerivedB>& b,\n    const typename Gradient<DerivedA, Eigen::Dynamic>::type& da,\n    const typename Gradient<DerivedB, Eigen::Dynamic>::type& db)\n{\n  Eigen::Matrix<typename DerivedA::Scalar, 3, Eigen::Dynamic> ret(3, da.cols());\n  ret.noalias() = da.colwise().cross(b);\n  ret.noalias() -= db.colwise().cross(a);\n  return ret;\n}\n\ntemplate <typename DerivedQ, typename DerivedM, typename DerivedDM>\nvoid angularvel2quatdotMatrix(const Eigen::MatrixBase<DerivedQ>& q,\n    Eigen::MatrixBase<DerivedM>& M,\n    Eigen::MatrixBase<DerivedDM>* dM)\n{\n  // note: not normalizing to match MATLAB implementation\n  M.resize(QUAT_SIZE, SPACE_DIMENSION);\n  M.row(0) << -q(1), -q(2), -q(3);\n  M.row(1) << q(0), q(3), -q(2);\n  M.row(2) << -q(3), q(0), q(1);\n  M.row(3) << q(2), -q(1), q(0);\n  M *= 0.5;\n\n  if (dM) {\n    (*dM) << 0.0, -0.5, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, -0.5, 0.0, 0.0, 0.5, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0;\n  }\n}\n\ntemplate<typename DerivedQ, typename DerivedM>\nvoid quatdot2angularvelMatrix(const Eigen::MatrixBase<DerivedQ>& q, Eigen::MatrixBase<DerivedM>& M, typename Gradient<DerivedM, QUAT_SIZE, 1>::type* dM)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<DerivedQ>, QUAT_SIZE);\n  EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Eigen::MatrixBase<DerivedM>, SPACE_DIMENSION, QUAT_SIZE);\n\n  typename DerivedQ::PlainObject qtilde;\n  if (dM) {\n    typename Gradient<DerivedQ, QUAT_SIZE>::type dqtilde;\n    normalizeVec(q, qtilde, &dqtilde);\n    (*dM) << 0.0, -2.0, 0.0, 0.0, 0.0, 0.0, -2.0, 0.0, 0.0, 0.0, 0.0, -2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, -2.0, 0.0, 0.0, 0.0, 0.0, -2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, -2.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0;\n    (*dM) *= dqtilde;\n  } else {\n    normalizeVec(q, qtilde);\n  }\n  M << -qtilde(1), qtilde(0), -qtilde(3), qtilde(2), -qtilde(2), qtilde(3), qtilde(0), -qtilde(1), -qtilde(3), -qtilde(2), qtilde(1), qtilde(0);\n  M *= 2.0;\n}\n\ntemplate<typename DerivedRPY, typename DerivedPhi, typename DerivedDPhi, typename DerivedDDPhi>\nvoid angularvel2rpydotMatrix(const Eigen::MatrixBase<DerivedRPY>& rpy,\n    typename Eigen::MatrixBase<DerivedPhi>& phi,\n    typename Eigen::MatrixBase<DerivedDPhi>* dphi,\n    typename Eigen::MatrixBase<DerivedDDPhi>* ddphi)\n{\n  phi.resize(RPY_SIZE, SPACE_DIMENSION);\n\n  typedef typename DerivedRPY::Scalar Scalar;\n  Scalar p = rpy(1);\n  Scalar y = rpy(2);\n\n  using namespace std;\n  Scalar sy = sin(y);\n  Scalar cy = cos(y);\n  Scalar sp = sin(p);\n  Scalar cp = cos(p);\n  Scalar tp = sp / cp;\n\n  phi << cy / cp, sy / cp, 0.0, -sy, cy, 0.0, cy * tp, tp * sy, 1.0;\n  if (dphi) {\n    dphi->resize(phi.size(), RPY_SIZE);\n    Scalar sp2 = sp * sp;\n    Scalar cp2 = cp * cp;\n    (*dphi) << 0.0, (cy * sp) / cp2, -sy / cp, 0.0, 0.0, -cy, 0.0, cy + (cy * sp2) / cp2, -(sp * sy) / cp, 0.0, (sp * sy) / cp2, cy / cp, 0.0, 0.0, -sy, 0.0, sy + (sp2 * sy) / cp2, (cy * sp) / cp, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n\n    if (ddphi) {\n      ddphi->resize(dphi->size(), RPY_SIZE);\n      Scalar cp3 = cp2 * cp;\n      (*ddphi) << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -(cy * (cp2 - 2.0)) / cp3, (sp * sy) / (sp2 - 1.0), 0.0, 0.0, 0.0, 0.0, (2.0 * cy * sp) / cp3, sy / (sp2 - 1.0), 0.0, (2.0 * sy - cp2 * sy)\n          / cp3, (cy * sp) / cp2, 0.0, 0.0, 0.0, 0.0, (2.0 * sp * sy) / cp3, cy / cp2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, (sp * sy) / (sp2 - 1.0), -cy / cp, 0.0, 0.0, sy, 0.0, sy / (sp2 - 1.0), -(cy * sp) / cp, 0.0, (cy * sp) / cp2, -sy / cp, 0.0, 0.0, -cy, 0.0, cy / cp2, -(sp * sy)\n          / cp, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n    }\n  }\n}\n\ntemplate<typename Derived>\nDLLEXPORT GradientVar<typename Derived::Scalar, Eigen::Dynamic, SPACE_DIMENSION> angularvel2RepresentationDotMatrix(\n    int rotation_type, const Eigen::MatrixBase<Derived>& qrot, int gradient_order)\n{\n  // note: gradients w.r.t. qrot\n  GradientVar<typename Derived::Scalar, Eigen::Dynamic, SPACE_DIMENSION> ret(qrot.rows(), SPACE_DIMENSION, qrot.rows(), gradient_order);\n  switch (rotation_type) {\n  case 0:\n    // done\n    break;\n  case 1: {\n    if (gradient_order > 1) {\n      angularvel2rpydotMatrix(qrot, ret.value(), &ret.gradient().value(), &ret.gradient().gradient().value());\n    }\n    else if (gradient_order > 0) {\n      angularvel2rpydotMatrix(qrot, ret.value(), &ret.gradient().value(), (MatrixXd*) nullptr);\n    }\n    else {\n      angularvel2rpydotMatrix(qrot, ret.value(), (MatrixXd*) nullptr, (MatrixXd*) nullptr);\n    }\n    break;\n  }\n  case 2: {\n    if (gradient_order > 1) {\n      ret.gradient().gradient().value().setZero();\n    }\n    if (gradient_order > 0) {\n      angularvel2quatdotMatrix(qrot, ret.value(), &ret.gradient().value());\n    }\n    else {\n      angularvel2quatdotMatrix(qrot, ret.value(), (MatrixXd*) nullptr);\n    }\n    break;\n  }\n  default:\n    throw std::runtime_error(\"rotation representation type not recognized\");\n  }\n  return ret;\n}\n\ntemplate<typename DerivedRPY, typename DerivedE>\nvoid rpydot2angularvelMatrix(const Eigen::MatrixBase<DerivedRPY>& rpy,\n\t\tEigen::MatrixBase<DerivedE>& E,\n\t\ttypename Gradient<DerivedE,RPY_SIZE,1>::type* dE)\n{\n  EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Eigen::MatrixBase<DerivedRPY>, RPY_SIZE);\n  EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Eigen::MatrixBase<DerivedE>, SPACE_DIMENSION,RPY_SIZE);\n  typedef typename DerivedRPY::Scalar Scalar;\n  Scalar p = rpy(1);\n  Scalar y = rpy(2);\n  Scalar sp = sin(p);\n  Scalar cp = cos(p);\n  Scalar sy = sin(y);\n  Scalar cy = cos(y);\n\n  using namespace std;\n  E << cp*cy, -sy, 0.0, cp*sy, cy, 0.0, -sp, 0.0, 1.0;\n  if(dE)\n  {\n    (*dE)<< 0.0, -sp*cy, -cp*sy, 0.0, -sp*sy, cp*cy, 0.0, -cp, 0.0, 0.0, 0.0, -cy, 0.0, 0.0, -sy, 0.0, 0.0, 0.0,  0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n  }\n}\n\ntemplate<typename DerivedM>\ntypename TransformSpatial<DerivedM>::type transformSpatialMotion(\n    const Eigen::Transform<typename DerivedM::Scalar, 3, Eigen::Isometry>& T,\n    const Eigen::MatrixBase<DerivedM>& M) {\n  Eigen::Matrix<typename DerivedM::Scalar, TWIST_SIZE, DerivedM::ColsAtCompileTime> ret(TWIST_SIZE, M.cols());\n  ret.template topRows<3>().noalias() = T.linear() * M.template topRows<3>();\n  ret.template bottomRows<3>().noalias() = -ret.template topRows<3>().colwise().cross(T.translation());\n  ret.template bottomRows<3>().noalias() += T.linear() * M.template bottomRows<3>();\n  return ret;\n}\n\ntemplate<typename DerivedF>\ntypename TransformSpatial<DerivedF>::type transformSpatialForce(\n    const Eigen::Transform<typename DerivedF::Scalar, 3, Eigen::Isometry>& T,\n    const Eigen::MatrixBase<DerivedF>& F) {\n  Eigen::Matrix<typename DerivedF::Scalar, TWIST_SIZE, DerivedF::ColsAtCompileTime> ret(TWIST_SIZE, F.cols());\n  ret.template bottomRows<3>().noalias() = T.linear() * F.template bottomRows<3>().eval();\n  ret.template topRows<3>() = -ret.template bottomRows<3>().colwise().cross(T.translation());\n  ret.template topRows<3>().noalias() += T.linear() * F.template topRows<3>();\n  return ret;\n}\n\ntemplate<typename DerivedI>\nGradientVar<typename DerivedI::Scalar, TWIST_SIZE, TWIST_SIZE> transformSpatialInertia(\n    const Eigen::Transform<typename DerivedI::Scalar, SPACE_DIMENSION, Eigen::Isometry>& T_current_to_new,\n    const typename Gradient<typename Eigen::Transform<typename DerivedI::Scalar, SPACE_DIMENSION, Eigen::Isometry>::MatrixType, Eigen::Dynamic>::type* dT_current_to_new,\n    const Eigen::MatrixBase<DerivedI>& I)\n{\n  int gradient_order;\n  typename DerivedI::Index nq;\n  if (dT_current_to_new) {\n    gradient_order = 1;\n    nq = dT_current_to_new->cols();\n  }\n  else {\n    nq = 0;\n    gradient_order = 0;\n  }\n\n  GradientVar<typename DerivedI::Scalar, TWIST_SIZE, TWIST_SIZE> ret(TWIST_SIZE, TWIST_SIZE, nq, gradient_order);\n  auto I_half_transformed = transformSpatialForce(T_current_to_new, I);\n\n  ret.value() = transformSpatialForce(T_current_to_new, I_half_transformed.transpose());\n\n  if (gradient_order > 0) {\n    auto dI = Eigen::Matrix<typename DerivedI::Scalar, DerivedI::SizeAtCompileTime, Eigen::Dynamic>::Zero(I.size(), nq).eval(); // TODO: would be better not to evaluate and make another explicit instantiation\n    auto dI_half_transformed = dTransformSpatialForce(T_current_to_new, I, *dT_current_to_new, dI);\n    auto dI_half_transformed_transpose = transposeGrad(dI_half_transformed, I_half_transformed.rows());\n    ret.gradient().value() = dTransformSpatialForce(T_current_to_new, I_half_transformed.transpose(), *dT_current_to_new, dI_half_transformed_transpose);\n  }\n  return ret;\n}\n\ntemplate<typename DerivedA, typename DerivedB>\ntypename TransformSpatial<DerivedB>::type crossSpatialMotion(\n  const Eigen::MatrixBase<DerivedA>& a,\n  const Eigen::MatrixBase<DerivedB>& b) {\n  typename TransformSpatial<DerivedB>::type ret(TWIST_SIZE, b.cols());\n  ret.template topRows<3>() = -b.template topRows<3>().colwise().cross(a.template topRows<3>());\n  ret.template bottomRows<3>() = -b.template topRows<3>().colwise().cross(a.template bottomRows<3>());\n  ret.template bottomRows<3>() -= b.template bottomRows<3>().colwise().cross(a.template topRows<3>());\n  return ret;\n}\n\ntemplate<typename DerivedA, typename DerivedB>\ntypename TransformSpatial<DerivedB>::type crossSpatialForce(\n  const Eigen::MatrixBase<DerivedA>& a,\n  const Eigen::MatrixBase<DerivedB>& b) {\n  typename TransformSpatial<DerivedB>::type ret(TWIST_SIZE, b.cols());\n  ret.template topRows<3>() = -b.template topRows<3>().colwise().cross(a.template topRows<3>());\n  ret.template topRows<3>() -= b.template bottomRows<3>().colwise().cross(a.template bottomRows<3>());\n  ret.template bottomRows<3>() = -b.template bottomRows<3>().colwise().cross(a.template topRows<3>());\n  return ret;\n}\n\ntemplate<typename DerivedA, typename DerivedB>\nEigen::Matrix<typename DerivedA::Scalar, TWIST_SIZE, Eigen::Dynamic> dCrossSpatialMotion(\n  const Eigen::MatrixBase<DerivedA>& a,\n  const Eigen::MatrixBase<DerivedB>& b,\n  const typename Gradient<DerivedA, Eigen::Dynamic>::type& da,\n  const typename Gradient<DerivedB, Eigen::Dynamic>::type& db) {\n  Eigen::Matrix<typename DerivedA::Scalar, TWIST_SIZE, Eigen::Dynamic> ret(TWIST_SIZE, da.cols());\n  ret.row(0) = -da.row(2)*b[1] + da.row(1)*b[2] - a[2]*db.row(1) + a[1]*db.row(2);\n  ret.row(1) =  da.row(2)*b[0] - da.row(0)*b[2] + a[2]*db.row(0) - a[0]*db.row(2);\n  ret.row(2) = -da.row(1)*b[0] + da.row(0)*b[1] - a[1]*db.row(0) + a[0]*db.row(1);\n  ret.row(3) = -da.row(5)*b[1] + da.row(4)*b[2] - da.row(2)*b[4] + da.row(1)*b[5] - a[5]*db.row(1) + a[4]*db.row(2) - a[2]*db.row(4) + a[1]*db.row(5);\n  ret.row(4) =  da.row(5)*b[0] - da.row(3)*b[2] + da.row(2)*b[3] - da.row(0)*b[5] + a[5]*db.row(0) - a[3]*db.row(2) + a[2]*db.row(3) - a[0]*db.row(5);\n  ret.row(5) = -da.row(4)*b[0] + da.row(3)*b[1] - da.row(1)*b[3] + da.row(0)*b[4] - a[4]*db.row(0) + a[3]*db.row(1) - a[1]*db.row(3) + a[0]*db.row(4);\n  return ret;\n}\n\ntemplate<typename DerivedA, typename DerivedB>\nEigen::Matrix<typename DerivedA::Scalar, TWIST_SIZE, Eigen::Dynamic> dCrossSpatialForce(\n  const Eigen::MatrixBase<DerivedA>& a,\n  const Eigen::MatrixBase<DerivedB>& b,\n  const typename Gradient<DerivedA, Eigen::Dynamic>::type& da,\n  const typename Gradient<DerivedB, Eigen::Dynamic>::type& db) {\n  Eigen::Matrix<typename DerivedA::Scalar, TWIST_SIZE, Eigen::Dynamic> ret(TWIST_SIZE, da.cols());\n  ret.row(0) =  da.row(2)*b[1] - da.row(1)*b[2] + da.row(5)*b[4] - da.row(4)*b[5] + a[2]*db.row(1) - a[1]*db.row(2) + a[5]*db.row(4) - a[4]*db.row(5);\n  ret.row(1) = -da.row(2)*b[0] + da.row(0)*b[2] - da.row(5)*b[3] + da.row(3)*b[5] - a[2]*db.row(0) + a[0]*db.row(2) - a[5]*db.row(3) + a[3]*db.row(5);\n  ret.row(2) =  da.row(1)*b[0] - da.row(0)*b[1] + da.row(4)*b[3] - da.row(3)*b[4] + a[1]*db.row(0) - a[0]*db.row(1) + a[4]*db.row(3) - a[3]*db.row(4);\n  ret.row(3) =  da.row(2)*b[4] - da.row(1)*b[5] + a[2]*db.row(4) - a[1]*db.row(5);\n  ret.row(4) = -da.row(2)*b[3] + da.row(0)*b[5] - a[2]*db.row(3) + a[0]*db.row(5);\n  ret.row(5) =  da.row(1)*b[3] - da.row(0)*b[4] + a[1]*db.row(3) - a[0]*db.row(4);\n  ret = -ret;\n  return ret;\n}\n\ntemplate<typename DerivedS, typename DerivedQdotToV>\ntypename DHomogTrans<DerivedQdotToV>::type dHomogTrans(\n    const Eigen::Transform<typename DerivedQdotToV::Scalar, 3, Eigen::Isometry>& T,\n    const Eigen::MatrixBase<DerivedS>& S,\n    const Eigen::MatrixBase<DerivedQdotToV>& qdot_to_v) {\n  const int nq_at_compile_time = DerivedQdotToV::ColsAtCompileTime;\n  typename DerivedQdotToV::Index nq = qdot_to_v.cols();\n  auto qdot_to_twist = (S * qdot_to_v).eval();\n\n  const int numel = HOMOGENEOUS_TRANSFORM_SIZE;\n  Eigen::Matrix<typename DerivedQdotToV::Scalar, numel, nq_at_compile_time> ret(numel, nq);\n\n  const auto& Rx = T.linear().col(0);\n  const auto& Ry = T.linear().col(1);\n  const auto& Rz = T.linear().col(2);\n\n  const auto& qdot_to_omega_x = qdot_to_twist.row(0);\n  const auto& qdot_to_omega_y = qdot_to_twist.row(1);\n  const auto& qdot_to_omega_z = qdot_to_twist.row(2);\n\n  ret.template middleRows<3>(0) = -Rz * qdot_to_omega_y + Ry * qdot_to_omega_z;\n  ret.row(3).setZero();\n\n  ret.template middleRows<3>(4) = Rz * qdot_to_omega_x - Rx * qdot_to_omega_z;\n  ret.row(7).setZero();\n\n  ret.template middleRows<3>(8) = -Ry * qdot_to_omega_x + Rx * qdot_to_omega_y;\n  ret.row(11).setZero();\n\n  ret.template middleRows<3>(12) = T.linear() * qdot_to_twist.bottomRows(3);\n  ret.row(15).setZero();\n\n  return ret;\n}\n\ntemplate<typename DerivedDT>\ntypename DHomogTrans<DerivedDT>::type dHomogTransInv(\n    const Eigen::Transform<typename DerivedDT::Scalar, 3, Eigen::Isometry>& T,\n    const Eigen::MatrixBase<DerivedDT>& dT) {\n  typename DerivedDT::Index nq = dT.cols();\n\n  const auto& R = T.linear();\n  const auto& p = T.translation();\n\n  std::array<int, 3> rows = {0, 1, 2};\n  std::array<int, 3> R_cols = {0, 1, 2};\n  std::array<int, 1> p_cols = {3};\n\n  auto dR = getSubMatrixGradient<Eigen::Dynamic>(dT, rows, R_cols, T.Rows);\n  auto dp = getSubMatrixGradient<Eigen::Dynamic>(dT, rows, p_cols, T.Rows);\n\n  auto dinvT_R = transposeGrad(dR, R.rows());\n  auto dinvT_p = (-R.transpose() * dp - matGradMult(dinvT_R, p)).eval();\n\n  const int numel = HOMOGENEOUS_TRANSFORM_SIZE;\n  Eigen::Matrix<typename DerivedDT::Scalar, numel, DerivedDT::ColsAtCompileTime> ret(numel, nq);\n  setSubMatrixGradient<Eigen::Dynamic>(ret, dinvT_R, rows, R_cols, T.Rows);\n  setSubMatrixGradient<Eigen::Dynamic>(ret, dinvT_p, rows, p_cols, T.Rows);\n\n  // zero out gradient of elements in last row:\n  const int last_row = 3;\n  for (int col = 0; col < T.HDim; col++) {\n    ret.row(last_row + col * T.Rows).setZero();\n  }\n\n  return ret;\n}\n\ntemplate <typename Scalar, typename DerivedX, typename DerivedDT, typename DerivedDX>\ntypename Gradient<DerivedX, DerivedDX::ColsAtCompileTime, 1>::type dTransformSpatialMotion(\n    const Eigen::Transform<Scalar, 3, Eigen::Isometry>& T,\n    const Eigen::MatrixBase<DerivedX>& X,\n    const Eigen::MatrixBase<DerivedDT>& dT,\n    const Eigen::MatrixBase<DerivedDX>& dX) {\n  assert(dT.cols() == dX.cols());\n  typename DerivedDT::Index nq = dT.cols();\n\n  const auto& R = T.linear();\n  const auto& p = T.translation();\n\n  std::array<int, 3> rows = {0, 1, 2};\n  std::array<int, 3> R_cols = {0, 1, 2};\n  std::array<int, 1> p_cols = {3};\n\n  auto dR = getSubMatrixGradient<Eigen::Dynamic>(dT, rows, R_cols, T.Rows);\n  auto dp = getSubMatrixGradient<Eigen::Dynamic>(dT, rows, p_cols, T.Rows);\n\n  typename Gradient<DerivedX, DerivedDX::ColsAtCompileTime, 1>::type ret(X.size(), nq);\n  std::array<int, 3> Xomega_rows = {0, 1, 2};\n  std::array<int, 3> Xv_rows = {3, 4, 5};\n  for (int col = 0; col < X.cols(); col++) {\n    auto Xomega_col = X.template block<3, 1>(0, col);\n    auto Xv_col = X.template block<3, 1>(3, col);\n\n    auto RXomega_col = (R * Xomega_col).eval();\n\n    std::array<int, 1> col_array = {col};\n    auto dXomega_col = getSubMatrixGradient<Eigen::Dynamic>(dX, Xomega_rows, col_array, X.rows());\n    auto dXv_col = getSubMatrixGradient<Eigen::Dynamic>(dX, Xv_rows, col_array, X.rows());\n\n    auto domega_part_col = (R * dXomega_col + matGradMult(dR, Xomega_col)).eval();\n    auto dv_part_col = (R * dXv_col + matGradMult(dR, Xv_col)).eval();\n    dv_part_col += dp.colwise().cross(RXomega_col);\n    dv_part_col -= domega_part_col.colwise().cross(p);\n\n    setSubMatrixGradient<Eigen::Dynamic>(ret, domega_part_col, Xomega_rows, col_array, X.rows());\n    setSubMatrixGradient<Eigen::Dynamic>(ret, dv_part_col, Xv_rows, col_array, X.rows());\n  }\n  return ret;\n}\n\ntemplate <typename Scalar, typename DerivedX, typename DerivedDT, typename DerivedDX>\ntypename Gradient<DerivedX, DerivedDX::ColsAtCompileTime>::type dTransformSpatialForce(\n    const Eigen::Transform<Scalar, 3, Eigen::Isometry>& T,\n    const Eigen::MatrixBase<DerivedX>& X,\n    const Eigen::MatrixBase<DerivedDT>& dT,\n    const Eigen::MatrixBase<DerivedDX>& dX) {\n  assert(dT.cols() == dX.cols());\n  typename DerivedDT::Index nq = dT.cols();\n\n  const auto& R = T.linear();\n  const auto& p = T.translation();\n\n  std::array<int, 3> rows = {0, 1, 2};\n  std::array<int, 3> R_cols = {0, 1, 2};\n  std::array<int, 1> p_cols = {3};\n\n  auto dR = getSubMatrixGradient<Eigen::Dynamic>(dT, rows, R_cols, T.Rows);\n  auto dp = getSubMatrixGradient<Eigen::Dynamic>(dT, rows, p_cols, T.Rows);\n\n  typename Gradient<DerivedX, DerivedDX::ColsAtCompileTime>::type ret(X.size(), nq);\n  std::array<int, 3> Xomega_rows = {0, 1, 2};\n  std::array<int, 3> Xv_rows = {3, 4, 5};\n  for (int col = 0; col < X.cols(); col++) {\n    auto Xomega_col = X.template block<3, 1>(0, col);\n    auto Xv_col = X.template block<3, 1>(3, col);\n\n    auto RXv_col = (R * Xv_col).eval();\n\n    std::array<int, 1> col_array = {col};\n    auto dXomega_col = getSubMatrixGradient<Eigen::Dynamic>(dX, Xomega_rows, col_array, X.rows());\n    auto dXv_col = getSubMatrixGradient<Eigen::Dynamic>(dX, Xv_rows, col_array, X.rows());\n\n    auto domega_part_col = (R * dXomega_col).eval();\n    domega_part_col += matGradMult(dR, Xomega_col);\n    auto dv_part_col = (R * dXv_col).eval();\n    dv_part_col += matGradMult(dR, Xv_col);\n    domega_part_col += dp.colwise().cross(RXv_col);\n    domega_part_col -= dv_part_col.colwise().cross(p);\n\n    setSubMatrixGradient<Eigen::Dynamic>(ret, domega_part_col, Xomega_rows, col_array, X.rows());\n    setSubMatrixGradient<Eigen::Dynamic>(ret, dv_part_col, Xv_rows, col_array, X.rows());\n  }\n  return ret;\n}\n\ntemplate<typename Scalar >\nDLLEXPORT void cylindrical2cartesian(const Matrix<Scalar,3,1> &m_cylinder_axis, const Matrix<Scalar,3,1> &m_cylinder_x_dir, const Matrix<Scalar,3,1> &cylinder_origin, const Matrix<Scalar,6,1> &x_cylinder, const Matrix<Scalar,6,1> &v_cylinder, Matrix<Scalar,6,1> &x_cartesian, Matrix<Scalar,6,1> &v_cartesian, Matrix<Scalar,6,6> &J, Matrix<Scalar,6,1> &Jdotv)\n{\n  Matrix<Scalar,3,1> cylinder_axis = m_cylinder_axis/m_cylinder_axis.norm();\n  Matrix<Scalar,3,1> cylinder_x_dir = m_cylinder_x_dir/m_cylinder_x_dir.norm();\n  Matrix<Scalar,3,3> R_cylinder2cartesian;\n  R_cylinder2cartesian.col(0) = cylinder_x_dir;\n  R_cylinder2cartesian.col(1) = cylinder_axis.cross(cylinder_x_dir);\n  R_cylinder2cartesian.col(2) = cylinder_axis;\n  double radius = x_cylinder(0);\n  double theta = x_cylinder(1);\n  double c_theta = cos(theta);\n  double s_theta = sin(theta);\n  double height = x_cylinder(2);\n  double radius_dot = v_cylinder(0);\n  double theta_dot = v_cylinder(1);\n  double height_dot = v_cylinder(2);\n  Matrix<Scalar,3,1> x_pos_cartesian;\n  x_pos_cartesian << radius*c_theta, radius*s_theta, height;\n  x_pos_cartesian = R_cylinder2cartesian*x_pos_cartesian+cylinder_origin;\n  Matrix<Scalar,3,1> v_pos_cartesian;\n  v_pos_cartesian << radius*-s_theta*theta_dot+radius_dot*c_theta, radius*c_theta*theta_dot+radius_dot*s_theta, height_dot;\n  v_pos_cartesian = R_cylinder2cartesian*v_pos_cartesian;\n  Vector3d x_rpy_cylinder = x_cylinder.block(3,0,3,1);\n  Matrix<Scalar,3,3> R_tangent = rpy2rotmat(x_rpy_cylinder);\nMatrix<Scalar,3,3> R_tangent2cylinder;\n  Matrix<Scalar,3,3> dR_tangent2cylinder;\n  Matrix<Scalar,3,3> ddR_tangent2cylinder;\n  rotz(theta-M_PI/2,R_tangent2cylinder,dR_tangent2cylinder, ddR_tangent2cylinder);\n  Matrix<Scalar,3,3> dR_tangent2cylinder_dtheta = dR_tangent2cylinder;\n  Matrix<Scalar,3,3> R_cylinder = R_tangent2cylinder*R_tangent;\n  Matrix<Scalar,3,3> R_cartesian = R_cylinder2cartesian*R_cylinder;\n  Matrix<Scalar,3,1> x_rpy_cartesian = rotmat2rpy(R_cartesian);\n  x_cartesian.block(0,0,3,1) = x_pos_cartesian;\n  x_cartesian.block(3,0,3,1) = x_rpy_cartesian;\n  v_cartesian.block(0,0,3,1) = v_pos_cartesian;\n  v_cartesian.block(3,0,3,1) = theta_dot*R_cylinder2cartesian.col(2)+R_cylinder2cartesian*R_tangent2cylinder*v_cylinder.block(3,0,3,1);\n  J = Matrix<Scalar,6,6>::Zero();\n  J.block(0,0,3,1) << c_theta,s_theta,0;\n  J.block(0,1,3,1) << radius*-s_theta,radius*c_theta,0;\n  J.block(0,2,3,1) << 0,0,1;\n  J.block(0,0,3,3) = R_cylinder2cartesian*J.block(0,0,3,3);\n  J.block(3,1,3,1) = R_cylinder2cartesian.col(2);\n  J.block(3,3,3,3) = R_cylinder2cartesian*R_tangent2cylinder;\n  Matrix<Scalar,3,3> dJ1_dradius = Matrix<Scalar,3,3>::Zero();\n  dJ1_dradius(0,1) = -s_theta;\n  dJ1_dradius(1,1) = c_theta;\n  Matrix<Scalar,3,3> dJ1_dtheta = Matrix<Scalar,3,3>::Zero();\n  dJ1_dtheta(0,0) = -s_theta;\n  dJ1_dtheta(0,1) = -radius*c_theta;\n  dJ1_dtheta(1,0) = c_theta;\n  dJ1_dtheta(1,1) = -radius*s_theta;\n  Jdotv.block(0,0,3,1) = R_cylinder2cartesian*(dJ1_dradius*radius_dot+dJ1_dtheta*theta_dot)*v_cylinder.block(0,0,3,1);\n  Jdotv.block(3,0,3,1) = R_cylinder2cartesian*dR_tangent2cylinder_dtheta*theta_dot*v_cylinder.block(3,0,3,1);\n}\n\ntemplate <typename Scalar>\nDLLEXPORT  void cartesian2cylindrical(const Eigen::Matrix<Scalar,3,1> &m_cylinder_axis, const Eigen::Matrix<Scalar,3,1> &m_cylinder_x_dir, const Eigen::Matrix<Scalar,3,1> & cylinder_origin, const Eigen::Matrix<Scalar,6,1> &x_cartesian, const Eigen::Matrix<Scalar,6,1> &v_cartesian, Eigen::Matrix<Scalar,6,1> &x_cylinder, Eigen::Matrix<Scalar,6,1> &v_cylinder, Eigen::Matrix<Scalar,6,6> &J, Eigen::Matrix<Scalar,6,1> &Jdotv )\n{\n  Matrix<Scalar,3,1> cylinder_axis = m_cylinder_axis/m_cylinder_axis.norm();\n  Matrix<Scalar,3,1> cylinder_x_dir = m_cylinder_x_dir/m_cylinder_x_dir.norm();\n  Matrix<Scalar,3,3> R_cylinder2cartesian;\n  R_cylinder2cartesian.col(0) = cylinder_x_dir;\n  R_cylinder2cartesian.col(1) = cylinder_axis.cross(cylinder_x_dir);\n  R_cylinder2cartesian.col(2) = cylinder_axis;\n  Matrix<Scalar,3,3> R_cartesian2cylinder = R_cylinder2cartesian.transpose();\n  Matrix<Scalar,3,1> x_pos_cylinder = R_cartesian2cylinder*(x_cartesian.block(0,0,3,1)-cylinder_origin);\n  Matrix<Scalar,3,1> v_pos_cylinder = R_cartesian2cylinder*v_cartesian.block(0,0,3,1);\n  double radius = sqrt(pow(x_pos_cylinder(0),2)+pow(x_pos_cylinder(1),2));\n  double radius_dot = (x_pos_cylinder(0)*v_pos_cylinder(0)+x_pos_cylinder(1)*v_pos_cylinder(1))/radius;\n  double theta = atan2(x_pos_cylinder(1),x_pos_cylinder(0));\n  double radius_square = pow(radius,2);\n  double radius_cubic = pow(radius,3);\n  double radius_quad = pow(radius,4);\n  double theta_dot = (-x_pos_cylinder(1)*v_pos_cylinder(0)+x_pos_cylinder(0)*v_pos_cylinder(1))/radius_square;\n  double height = x_pos_cylinder(2);\n  double height_dot = v_pos_cylinder(2);\n  x_cylinder(0) = radius;\n  x_cylinder(1) = theta;\n  x_cylinder(2) = height;\n  v_cylinder(0) = radius_dot;\n  v_cylinder(1) = theta_dot;\n  v_cylinder(2) = height_dot;\n  Matrix<Scalar,3,3> R_tangent2cylinder;\n  Matrix<Scalar,3,3> dR_tangent2cylinder;\n  Matrix<Scalar,3,3> ddR_tangent2cylinder;\n  rotz(theta-M_PI/2,R_tangent2cylinder,dR_tangent2cylinder, ddR_tangent2cylinder);\n  Matrix<Scalar,3,3> R_cylinder2tangent = R_tangent2cylinder.transpose();\n  Vector3d x_rpy_cartesian = x_cartesian.block(3,0,3,1);\n  Matrix<Scalar,3,3> R_cartesian = rpy2rotmat(x_rpy_cartesian);\n  x_cylinder.block(3,0,3,1) = rotmat2rpy(R_cylinder2tangent*R_cartesian2cylinder*R_cartesian);\n  J = Matrix<Scalar,6,6>::Zero();\n  Matrix<Scalar,6,6> Jdot = Matrix<Scalar,6,6>::Zero();\n  J(0,0) = x_pos_cylinder(0)/radius;\n  J(0,1) = x_pos_cylinder(1)/radius;\n  J(1,0) = -x_pos_cylinder(1)/radius_square;\n  J(1,1) = x_pos_cylinder(0)/radius_square;\n  J(2,2) = 1.0;\n  J.block(0,0,3,3) = J.block(0,0,3,3)*R_cartesian2cylinder;\n  Jdot(0,0) = pow(x_pos_cylinder(1),2)/radius_cubic*v_pos_cylinder(0)-x_pos_cylinder(0)*x_pos_cylinder(1)/radius_cubic*v_pos_cylinder(1);\n  Jdot(0,1) = -x_pos_cylinder(0)*x_pos_cylinder(1)/radius_cubic*v_pos_cylinder(0)+pow(x_pos_cylinder(0),2)/radius_cubic*v_pos_cylinder(1);\n  Jdot(1,0) = 2*x_pos_cylinder(0)*x_pos_cylinder(1)/radius_quad*v_pos_cylinder(0)+(pow(x_pos_cylinder(1),2)-pow(x_pos_cylinder(0),2))/radius_quad*v_pos_cylinder(1);\n  Jdot(1,1) = (pow(x_pos_cylinder(1),2)-pow(x_pos_cylinder(0),2))/radius_quad*v_pos_cylinder(0)-2*x_pos_cylinder(0)*x_pos_cylinder(1)/radius_quad*v_pos_cylinder(1);\n  Jdot.block(0,0,3,3) = Jdot.block(0,0,3,3)*R_cartesian2cylinder;\n  v_cylinder.block(3,0,3,1) = R_cylinder2tangent*R_cartesian2cylinder*v_cartesian.block(3,0,3,1)-theta_dot*R_cylinder2tangent.col(2);\n  J.block(3,0,3,3) = R_cylinder2tangent.col(2)*-J.block(1,0,1,3);\n  J.block(3,3,3,3) = R_cylinder2tangent*R_cartesian2cylinder;\n  Jdot.block(3,0,3,3) = dR_tangent2cylinder.row(2).transpose()*-J.block(1,0,1,3)*theta_dot+R_cylinder2tangent.col(2)*-Jdot.block(1,0,1,3);\n  Jdot.block(3,3,3,3) = dR_tangent2cylinder.transpose()*theta_dot*R_cartesian2cylinder;\n  Jdotv = Jdot*v_cartesian;\n}\n\nDLLEXPORT GradientVar<double,3,1> quat2expmap(const Ref<const Vector4d> &q, int gradient_order)\n{\n  double t = sqrt(1-q(0)*q(0));\n  bool is_degenerate=(t*t<std::numeric_limits<double>::epsilon());\n  double s = is_degenerate?2.0:2.0*acos(q(0))/t;\n  GradientVar<double,3,1> ret(3,1,4,gradient_order);\n  ret.value() = s*q.tail(3);\n  if(gradient_order>0)\n  {\n    ret.gradient().value() = Matrix<double,3,4>::Zero();\n    double dsdq1 = is_degenerate?0.0: (-2*t+2*acos(q(0))*q(0))/pow(t,3);\n    ret.gradient().value().col(0) = q.tail(3)*dsdq1;\n    ret.gradient().value().block(0,1,3,3) = Matrix3d::Identity()*s;\n  }\n  else if(gradient_order>1)\n  {\n    throw std::runtime_error(\"gradient_order>1 is not supported in quat2expmap\");\n  }\n  return ret;\n}\n\nDLLEXPORT GradientVar<double,3,1> flipExpmap(const Ref<const Vector3d> &expmap, int gradient_order)\n{\n  if(gradient_order>1)\n  {\n    throw std::runtime_error(\"gradient_order>1 is not supported in flipExpmap\");\n  }\n  double expmap_norm = expmap.norm();\n  bool is_degenerate=(expmap_norm<std::numeric_limits<double>::epsilon());\n  GradientVar<double,3,1> ret(3,1,3,gradient_order);\n  Matrix3d eye3 = Matrix3d::Identity();\n  if(is_degenerate)\n  {\n    ret.value() = expmap;\n    if(gradient_order>0)\n    {\n      ret.gradient().value() = eye3;\n    }\n  }\n  else\n  {\n    ret.value() = expmap-expmap/expmap_norm*2*M_PI;\n    if(gradient_order>0)\n    {\n      ret.gradient().value() = eye3-(expmap_norm*expmap_norm*eye3-expmap*expmap.transpose())/pow(expmap_norm,3)*2*M_PI;\n    }\n  }\n  return ret;\n}\n\nDLLEXPORT GradientVar<double, 3,1> unwrapExpmap(const Ref<const Vector3d> & expmap1, const Ref<const Vector3d> &expmap2, int gradient_order)\n{\n  auto expmap2_flip = flipExpmap(expmap2,gradient_order);\n  double distance1 = (expmap1-expmap2).squaredNorm();\n  double distance2 = (expmap1-expmap2_flip.value()).squaredNorm();\n  if(distance1>distance2)\n  {\n    return expmap2_flip;\n  }\n  else\n  {\n    GradientVar<double,3,1> ret(3,1,3,gradient_order);\n    ret.value() = expmap2;\n    if(gradient_order>0)\n    {\n      ret.gradient().value() = Matrix3d::Identity();\n    }\n    return ret;\n  }\n}\n\n\nvoid quat2expmapSequence(const Ref<const Matrix<double,4,Dynamic>> &quat, const Ref<const Matrix<double,4,Dynamic>> &quat_dot, Ref<Matrix<double,3,Dynamic>> expmap, Ref<Matrix<double,3,Dynamic>> expmap_dot)\n{\n  int N = quat.cols();\n  if(quat_dot.cols() != N)\n  {\n    throw std::runtime_error(\"quat_dot must have the same number of columns as quat in quat2expmapSequence\");\n  }\n  expmap.resize(3,N);\n  expmap_dot.resize(3,N);\n  for(int i = 0;i<N;i++)\n  {\n    auto expmap_grad = quat2expmap(quat.col(i),1);\n    expmap.col(i) = expmap_grad.value();\n    expmap_dot.col(i) = expmap_grad.gradient().value()*quat_dot.col(i);\n    if(i>=1)\n    {\n      auto unwrap_grad = unwrapExpmap(expmap.col(i-1),expmap.col(i),1);\n      expmap.col(i) = unwrap_grad.value();\n      expmap_dot.col(i) = unwrap_grad.gradient().value()*expmap_dot.col(i);\n    }\n  }\n}\n\n// explicit instantiations\ntemplate DLLEXPORT void normalizeVec(\n    const MatrixBase< Vector3d >& x,\n    Vector3d& x_norm,\n    Gradient<Vector3d, 3, 1>::type*,\n    Gradient<Vector3d, 3, 2>::type*);\n\ntemplate DLLEXPORT void normalizeVec(\n    const MatrixBase< Vector4d >& x,\n    Vector4d& x_norm,\n    Gradient<Vector4d, 4, 1>::type*,\n    Gradient<Vector4d, 4, 2>::type*);\n\ntemplate DLLEXPORT void normalizeVec(\n    const MatrixBase< Map<Vector4d> >& x,\n    Vector4d& x_norm,\n    Gradient<Vector4d, 4, 1>::type*,\n    Gradient<Vector4d, 4, 2>::type*);\n\ntemplate DLLEXPORT void normalizeVec(\n    const MatrixBase< Eigen::Block<Eigen::Ref<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 0, Eigen::InnerStride<1> > const, 4, 1, false> >& x,\n    Vector4d& x_norm,\n    Gradient<Vector4d, 4, 1>::type*,\n    Gradient<Vector4d, 4, 2>::type*);\n\ntemplate DLLEXPORT Vector4d quat2axis(const MatrixBase<Vector4d>&);\ntemplate DLLEXPORT Matrix3d quat2rotmat(const MatrixBase<Vector4d>& q);\ntemplate DLLEXPORT Matrix3d quat2rotmat(const MatrixBase<Eigen::Block<Eigen::Ref<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 0, Eigen::InnerStride<1> > const, 4, 1, false> >& q);\ntemplate DLLEXPORT Vector3d quat2rpy(const MatrixBase<Vector4d>&);\n\ntemplate DLLEXPORT Vector4d axis2quat(const MatrixBase<Vector4d>&);\ntemplate DLLEXPORT Matrix3d axis2rotmat(const MatrixBase<Vector4d>&);\ntemplate DLLEXPORT Vector3d axis2rpy(const MatrixBase<Vector4d>&);\n\ntemplate DLLEXPORT Vector4d rotmat2axis(const MatrixBase<Matrix3d>&);\ntemplate DLLEXPORT Vector4d rotmat2quat(const MatrixBase<Matrix3d>&);\ntemplate DLLEXPORT Vector3d rotmat2rpy(const MatrixBase<Matrix3d>&);\n\ntemplate DLLEXPORT Eigen::Matrix<Eigen::Block<Eigen::Matrix<double, 4, 4, 0, 4, 4>, 3, 3, false>::Scalar, -1, 1, 0, -1, 1> rotmat2Representation<Eigen::Block<Eigen::Matrix<double, 4, 4, 0, 4, 4>, 3, 3, false> >(Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 4, 4, 0, 4, 4>, 3, 3, false> > const&, int);\n\ntemplate DLLEXPORT GradientVar<double, Eigen::Dynamic, 1> rotmat2Representation(\n    const GradientVar<double, SPACE_DIMENSION, SPACE_DIMENSION>& R,\n    int rotation_type);\n\ntemplate DLLEXPORT GradientVar<double, QUAT_SIZE, 1> expmap2quat(const MatrixBase<Vector3d>& v, const int gradient_order);\ntemplate DLLEXPORT GradientVar<double, QUAT_SIZE, 1> expmap2quat(const MatrixBase<Map<Vector3d>>& v, const int gradient_order);\n\ntemplate DLLEXPORT Vector4d rpy2axis(const Eigen::MatrixBase<Vector3d>&);\ntemplate DLLEXPORT Vector4d rpy2quat(const Eigen::MatrixBase<Vector3d>&);\ntemplate DLLEXPORT Matrix3d rpy2rotmat(const Eigen::MatrixBase<Vector3d>&);\ntemplate DLLEXPORT Matrix3d rpy2rotmat(const Eigen::MatrixBase<Eigen::Block<Eigen::Ref<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 0, Eigen::InnerStride<1> > const, 3, 1, false>>&);\n\ntemplate DLLEXPORT Matrix<double,9,3> drpy2rotmat(const Eigen::MatrixBase<Vector3d>&);\ntemplate DLLEXPORT Matrix<double,9,3> drpy2rotmat(const Eigen::MatrixBase<Eigen::Block<Eigen::Ref<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 0, Eigen::InnerStride<1> > const, 3, 1, false>>&);\n\ntemplate DLLEXPORT Vector4d quat2axis(const MatrixBase< Map<Vector4d> >&);\ntemplate DLLEXPORT Matrix3d quat2rotmat(const MatrixBase< Map<Vector4d> >& q);\ntemplate DLLEXPORT Vector3d quat2rpy(const MatrixBase< Map<Vector4d> >&);\n\ntemplate DLLEXPORT Vector4d axis2quat(const MatrixBase< Map<Vector4d> >&);\ntemplate DLLEXPORT Matrix3d axis2rotmat(const MatrixBase< Map<Vector4d> >&);\ntemplate DLLEXPORT Vector3d axis2rpy(const MatrixBase< Map<Vector4d> >&);\n\ntemplate DLLEXPORT Vector4d rotmat2axis(const MatrixBase< Map<Matrix3d> >&);\ntemplate DLLEXPORT Vector4d rotmat2quat(const MatrixBase< Map<Matrix3d> >&);\ntemplate DLLEXPORT Vector3d rotmat2rpy(const MatrixBase< Map<Matrix3d> >&);\n\ntemplate DLLEXPORT Vector4d rpy2axis(const Eigen::MatrixBase< Map<Vector3d> >&);\ntemplate DLLEXPORT Vector4d rpy2quat(const Eigen::MatrixBase< Map<Vector3d> >&);\ntemplate DLLEXPORT Matrix3d rpy2rotmat(const Eigen::MatrixBase< Map<Vector3d> >&);\ntemplate DLLEXPORT Matrix<double,9,3> drpy2rotmat(const Eigen::MatrixBase< Map<Vector3d> >&);\n\n\ntemplate DLLEXPORT Eigen::Matrix<double, TWIST_SIZE, Eigen::Dynamic> transformSpatialMotion(\n    const Eigen::Isometry3d&,\n    const Eigen::MatrixBase< Eigen::Matrix<double, TWIST_SIZE, Eigen::Dynamic> >&);\n\ntemplate DLLEXPORT Eigen::Matrix<double, TWIST_SIZE, 1> transformSpatialMotion(\n    const Eigen::Isometry3d&,\n    const Eigen::MatrixBase< Eigen::Matrix<double, TWIST_SIZE, 1> >&);\n\ntemplate DLLEXPORT TransformSpatial< MatrixXd >::type transformSpatialMotion<MatrixXd>(\n    const Eigen::Isometry3d&,\n    const Eigen::MatrixBase< MatrixXd >&);\n\ntemplate DLLEXPORT TransformSpatial<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, 6, -1, false> >::type transformSpatialMotion(\n    const Eigen::Isometry3d& T,\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, 6, -1, false> >& M);\n\ntemplate DLLEXPORT TransformSpatial< Matrix<double, TWIST_SIZE, Eigen::Dynamic> >::type transformSpatialForce<Matrix<double, TWIST_SIZE, Eigen::Dynamic>>(\n    const Eigen::Isometry3d&,\n    const Eigen::MatrixBase< Matrix<double, TWIST_SIZE, Eigen::Dynamic> >&);\n\ntemplate DLLEXPORT TransformSpatial< MatrixXd >::type transformSpatialForce<MatrixXd>(\n    const Eigen::Isometry3d&,\n    const Eigen::MatrixBase< MatrixXd >&);\n\ntemplate DLLEXPORT TransformSpatial<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 6, -1, true>>::type transformSpatialForce(\n    const Eigen::Isometry3d&,\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 6, -1, true> >&);\n\ntemplate DLLEXPORT TransformSpatial<Eigen::Matrix<double, 6, 1, 0, 6, 1> >::type transformSpatialForce(\n    const Eigen::Isometry3d&,\n    const Eigen::MatrixBase<Eigen::Matrix<double, 6, 1, 0, 6, 1> >&);\n\ntemplate DLLEXPORT TransformSpatial<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1> const, 6, 1, true> >::type transformSpatialForce(\n    const Eigen::Transform<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1> const, 6, 1, true>::Scalar, 3, 1, 0> &,\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1> const, 6, 1, true> > &);\n\ntemplate DLLEXPORT TransformSpatial<Map<Matrix<double, 6, 1, 0, 6, 1> const, 0, Stride<0, 0> > >::type transformSpatialForce<Map<Matrix<double, 6, 1, 0, 6, 1> const, 0, Stride<0, 0> >>(\n    const Eigen::Isometry3d&,\n    const Eigen::MatrixBase<Map<Matrix<double, 6, 1, 0, 6, 1> const, 0, Stride<0, 0> > >&);\n\ntemplate DLLEXPORT GradientVar<double, TWIST_SIZE, TWIST_SIZE> transformSpatialInertia(\n    const Eigen::Transform<double, SPACE_DIMENSION, Eigen::Isometry>& T_current_to_new,\n    const Gradient<Eigen::Transform<double, SPACE_DIMENSION, Eigen::Isometry>::MatrixType, Eigen::Dynamic>::type* dT_current_to_new,\n    const Eigen::MatrixBase< Eigen::Matrix<double, TWIST_SIZE, TWIST_SIZE> >& I);\n\ntemplate DLLEXPORT GradientVar<double, TWIST_SIZE, TWIST_SIZE> transformSpatialInertia(\n    const Eigen::Transform<double, SPACE_DIMENSION, Eigen::Isometry>& T_current_to_new,\n    const Gradient<Eigen::Transform<double, SPACE_DIMENSION, Eigen::Isometry>::MatrixType, Eigen::Dynamic>::type* dT_current_to_new,\n    const Eigen::MatrixBase< Eigen::MatrixXd >& I);\n\ntemplate DLLEXPORT Eigen::Matrix<double, TWIST_SIZE, Eigen::Dynamic> dCrossSpatialMotion(\n  const Eigen::MatrixBase<Eigen::Matrix<double, 6, 1, 0, 6, 1> >& a,\n  const Eigen::MatrixBase<Eigen::Matrix<double, 6, 1, 0, 6, 1> >& b,\n  const Gradient<Eigen::Matrix<double, 6, 1, 0, 6, 1>, Eigen::Dynamic>::type& da,\n  const Gradient<Eigen::Matrix<double, 6, 1, 0, 6, 1>, Eigen::Dynamic>::type& db);\n\ntemplate DLLEXPORT Eigen::Matrix<double, TWIST_SIZE, Eigen::Dynamic> dCrossSpatialForce(\n  const Eigen::MatrixBase<Eigen::Matrix<double, 6, 1, 0, 6, 1> >& a,\n  const Eigen::MatrixBase<Eigen::Matrix<double, 6, 1, 0, 6, 1> >& b,\n  const Gradient<Eigen::Matrix<double, 6, 1, 0, 6, 1>, Eigen::Dynamic>::type& da,\n  const Gradient<Eigen::Matrix<double, 6, 1, 0, 6, 1>, Eigen::Dynamic>::type& db);\n\ntemplate DLLEXPORT Gradient<Matrix3d, QUAT_SIZE>::type dquat2rotmat(const Eigen::MatrixBase<Vector4d>&);\ntemplate DLLEXPORT Gradient<Matrix3d, QUAT_SIZE>::type dquat2rotmat(const Eigen::MatrixBase< Map<Vector4d> >&);\ntemplate DLLEXPORT Gradient<Matrix3d, QUAT_SIZE>::type dquat2rotmat(const Eigen::MatrixBase<Eigen::Block<Eigen::Ref<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 0, Eigen::InnerStride<1> > const, 4, 1, false> >&);\n\ntemplate DLLEXPORT Gradient<Vector3d, Dynamic>::type drotmat2rpy(\n    const Eigen::MatrixBase<Matrix3d>&,\n    const Eigen::MatrixBase< Matrix<double, RotmatSize, Dynamic> >&);\n\ntemplate DLLEXPORT Gradient<Vector3d, 6>::type drotmat2rpy(\n    const Eigen::MatrixBase<Matrix3d>&,\n    const Eigen::MatrixBase< Matrix<double, RotmatSize, 6> >&);\n\ntemplate DLLEXPORT Gradient<Vector4d, Dynamic>::type drotmat2quat(\n    const Eigen::MatrixBase<Matrix3d>&,\n    const Eigen::MatrixBase< Matrix<double, RotmatSize, Dynamic> >&);\n\ntemplate DLLEXPORT\nEigen::Matrix<double, 3, 3> vectorToSkewSymmetric(const Eigen::MatrixBase<Eigen::Vector3d>&);\n\ntemplate DLLEXPORT Eigen::Matrix<double, 3, Eigen::Dynamic> dcrossProduct(\n    const Eigen::MatrixBase<Vector3d>& a,\n    const Eigen::MatrixBase<Vector3d>& b,\n    const Gradient<Vector3d, Eigen::Dynamic>::type& da,\n    const Gradient<Vector3d, Eigen::Dynamic>::type& db);\n\ntemplate DLLEXPORT Eigen::Matrix<double, 3, Eigen::Dynamic> dcrossProduct(\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 3, -1, 0, 3, -1>, 3, 1, true>>& a,\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 3, 1, false>>& b,\n    const Gradient<Eigen::Block<Eigen::Matrix<double, 3, -1, 0, 3, -1>, 3, 1, true>, Eigen::Dynamic>::type& da,\n    const Gradient<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 3, 1, false>, Eigen::Dynamic>::type& db);\n\ntemplate DLLEXPORT Eigen::Matrix<double, 3, Eigen::Dynamic> dcrossProduct(\n    const Eigen::MatrixBase< Eigen::Block<Eigen::Matrix<double, 3, -1, 0, 3, -1>, 3, 1, true> >& a,\n    const Eigen::MatrixBase< Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1> const, 3, 1, false> >& b,\n    const Gradient< Eigen::Block<Eigen::Matrix<double, 3, -1, 0, 3, -1>, 3, 1, true>, Eigen::Dynamic>::type& da,\n    const Gradient< Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1> const, 3, 1, false>, Eigen::Dynamic>::type& db);\n\ntemplate DLLEXPORT Eigen::Matrix<double, 3, Eigen::Dynamic> dcrossProduct(\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1> const, 3, 1, false>>& a,\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, 3, -1, false>, 3, 1, true>>& b,\n    const Gradient<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1> const, 3, 1, false>, Eigen::Dynamic>::type& da,\n    const Gradient<Eigen::Block<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, 3, -1, false>, 3, 1, true>, Eigen::Dynamic>::type& db);\n\ntemplate DLLEXPORT Eigen::Matrix<double, 3, Eigen::Dynamic> dcrossProduct(\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1> const, 3, 1, false>>& a,\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 3, -1, 0, 3, -1>, 3, 1, true>>& b,\n    const Gradient<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1> const, 3, 1, false>, Eigen::Dynamic>::type& da,\n    const Gradient<Eigen::Block<Eigen::Matrix<double, 3, -1, 0, 3, -1>, 3, 1, true>, Eigen::Dynamic>::type& db);\n\ntemplate DLLEXPORT Eigen::Matrix<double, 3, Eigen::Dynamic> dcrossProduct(\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>>& a,\n    const Eigen::MatrixBase<Eigen::Matrix<double, 3, 1, 0, 3, 1>>& b,\n    const Gradient<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>, Eigen::Dynamic>::type& da,\n    const Gradient<Eigen::Matrix<double, 3, 1, 0, 3, 1>, Eigen::Dynamic>::type& db);\n\ntemplate DLLEXPORT Eigen::Matrix<double, 3, Eigen::Dynamic> dcrossProduct(\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1>, 3, 1, false>>& a,\n    const Eigen::MatrixBase<Eigen::Matrix<double, 3, 1, 0, 3, 1>>& b,\n    const Gradient<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1>, 3, 1, false>, Eigen::Dynamic>::type& da,\n    const Gradient<Eigen::Matrix<double, 3, 1, 0, 3, 1>, Eigen::Dynamic>::type& db);\n\ntemplate DLLEXPORT Eigen::Matrix<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>::Scalar, 3, -1, 0, 3, -1> dcrossProduct<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>,\n    Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 3, 1, false> >(Eigen::MatrixBase<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true> > const&, Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 3, 1, false> > const&,\n    Gradient<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>, -1, 1>::type const&, Gradient<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 3, 1, false>, -1, 1>::type const&);\n\ntemplate DLLEXPORT Eigen::Matrix<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>::Scalar, 3, -1, 0, 3, -1> dcrossProduct<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>,\n    Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1> const, 3, 1, false> >(Eigen::MatrixBase<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true> > const&,\n    Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1> const, 3, 1, false> > const&, Gradient<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>, -1, 1>::type const&,\n    Gradient<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1> const, 3, 1, false>, -1, 1>::type const&);\n\ntemplate DLLEXPORT Eigen::Matrix<double, 3, -1, 0, 3, -1> dcrossProduct<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1> const, 3, 1, false>, Eigen::Block<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1>, 3, 1, false>, 3, 1, true> >(\n    Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1> const, 3, 1, false> > const&, Eigen::MatrixBase<Eigen::Block<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1>, 3, 1, false>, 3, 1, true> > const&,\n    Gradient<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1> const, 3, 1, false>, -1, 1>::type const&, Gradient<Eigen::Block<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1>, 3, 1, false>, 3, 1, true>, -1, 1>::type const&);\n\ntemplate DLLEXPORT Eigen::Matrix<double, 3, -1, 0, 3, -1> dcrossProduct<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1> const, 3, 1, false>, Eigen::Block<Eigen::Matrix<double, 3, 1, 0, 3, 1>, 3, 1, true> >(\n    Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1> const, 3, 1, false> > const&, Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 3, 1, 0, 3, 1>, 3, 1, true> > const&, Gradient<Eigen::Block<Eigen::Matrix<double, 6, 1, 0, 6, 1> const, 3, 1, false>, -1, 1>::type const&,\n    Gradient<Eigen::Block<Eigen::Matrix<double, 3, 1, 0, 3, 1>, 3, 1, true>, -1, 1>::type const&);\n\ntemplate DLLEXPORT Eigen::Matrix<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>::Scalar, 3, -1, 0, 3, -1> dcrossProduct<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>,\n    Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1>, 3, 1, false> >(Eigen::MatrixBase<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true> > const&, Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1>, 3, 1, false> > const&,\n    Gradient<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>, -1, 1>::type const&, Gradient<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1>, 3, 1, false>, -1, 1>::type const&);\n\ntemplate DLLEXPORT Eigen::Matrix<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>::Scalar, 3, -1, 0, 3, -1> dcrossProduct<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>,\n    Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, 3, 1, false> >(Eigen::MatrixBase<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true> > const&, Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, 3, 1, false> > const&,\n    Gradient<Eigen::Block<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 3, -1, false>, 3, 1, true>, -1, 1>::type const&, Gradient<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, 3, 1, false>, -1, 1>::type const&);\n\ntemplate DLLEXPORT DHomogTrans<MatrixXd>::type dHomogTrans(\n    const Isometry3d&,\n    const MatrixBase< Matrix<double, TWIST_SIZE, Dynamic> >&,\n    const MatrixBase< MatrixXd >&);\n\ntemplate DLLEXPORT DHomogTrans<Matrix<double, HOMOGENEOUS_TRANSFORM_SIZE, Dynamic>>::type dHomogTransInv(\n    const Isometry3d&,\n    const MatrixBase< Matrix<double, HOMOGENEOUS_TRANSFORM_SIZE, Dynamic> >&);\n\ntemplate DLLEXPORT Gradient< Matrix<double, TWIST_SIZE, Dynamic>, Dynamic, 1>::type dTransformSpatialMotion(\n    const Isometry3d&,\n    const MatrixBase< Matrix<double, TWIST_SIZE, Dynamic> >&,\n    const MatrixBase< Matrix<double, HOMOGENEOUS_TRANSFORM_SIZE, Dynamic> >&,\n    const MatrixBase<MatrixXd>&);\n\ntemplate DLLEXPORT Gradient< Matrix<double, TWIST_SIZE, 1>, Dynamic, 1>::type dTransformSpatialMotion(\n    const Isometry3d&,\n    const MatrixBase< Matrix<double, TWIST_SIZE, 1> >&,\n    const MatrixBase< Matrix<double, HOMOGENEOUS_TRANSFORM_SIZE, Dynamic> >&,\n    const MatrixBase< Matrix<double, TWIST_SIZE, Eigen::Dynamic> >&);\n\ntemplate DLLEXPORT TransformSpatial<Eigen::Matrix<double, TWIST_SIZE, 1>>::type crossSpatialMotion(\n  const Eigen::MatrixBase<Eigen::Matrix<double, TWIST_SIZE, 1> >& a,\n  const Eigen::MatrixBase<Eigen::Matrix<double, TWIST_SIZE, 1> >& b);\n\ntemplate DLLEXPORT TransformSpatial<Eigen::Matrix<double, TWIST_SIZE, TWIST_SIZE>>::type crossSpatialMotion(\n  const Eigen::MatrixBase<Eigen::Matrix<double, TWIST_SIZE, 1> >& a,\n  const Eigen::MatrixBase<Eigen::Matrix<double, TWIST_SIZE, TWIST_SIZE> >& b);\n\ntemplate DLLEXPORT TransformSpatial<Eigen::Matrix<double, TWIST_SIZE, Eigen::Dynamic>>::type crossSpatialMotion(\n  const Eigen::MatrixBase<Eigen::Matrix<double, TWIST_SIZE, 1> >& a,\n  const Eigen::MatrixBase<Eigen::Matrix<double, TWIST_SIZE, Eigen::Dynamic> >& b);\n\ntemplate DLLEXPORT TransformSpatial<Eigen::Matrix<double, TWIST_SIZE, 1>>::type crossSpatialForce(\n  const Eigen::MatrixBase<Eigen::Matrix<double, TWIST_SIZE, 1> >& a,\n  const Eigen::MatrixBase<Eigen::Matrix<double, TWIST_SIZE, 1> >& b);\n\ntemplate DLLEXPORT TransformSpatial<Eigen::Matrix<double, TWIST_SIZE, TWIST_SIZE>>::type crossSpatialForce(\n  const Eigen::MatrixBase<Eigen::Matrix<double, TWIST_SIZE, 1> >& a,\n  const Eigen::MatrixBase<Eigen::Matrix<double, TWIST_SIZE, TWIST_SIZE> >& b);\n\ntemplate DLLEXPORT Gradient< Matrix<double, TWIST_SIZE, Dynamic>, Dynamic, 1>::type dTransformSpatialForce(\n    const Isometry3d&,\n    const MatrixBase< Matrix<double, TWIST_SIZE, Dynamic> >&,\n    const MatrixBase< Matrix<double, HOMOGENEOUS_TRANSFORM_SIZE, Dynamic> >&,\n    const MatrixBase<MatrixXd>&);\n\ntemplate DLLEXPORT Gradient< Matrix<double, TWIST_SIZE, Dynamic>, Dynamic, 1>::type dTransformSpatialForce(\n    const Isometry3d&,\n    const MatrixBase< Matrix<double, TWIST_SIZE, Dynamic> >&,\n    const MatrixBase<MatrixXd>&,\n    const MatrixBase<MatrixXd>&);\n\ntemplate DLLEXPORT Gradient<Eigen::Matrix<double, 6, 1, 0, 6, 1>, Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 6, -1, true>::ColsAtCompileTime>::type dTransformSpatialForce(\n    const Isometry3d& T,\n    const Eigen::MatrixBase<Eigen::Matrix<double, 6, 1, 0, 6, 1> >& X,\n    const Eigen::MatrixBase<Eigen::Matrix<double, 16, -1, 0, 16, -1> >& dT,\n    const Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, 6, -1, 0, 6, -1>, 6, -1, true> >& dX);\n\ntemplate DLLEXPORT Gradient<Eigen::Matrix<double, 6, 1, 0, 6, 1>, Eigen::Matrix<double, 6, -1, 0, 6, -1>::ColsAtCompileTime>::type dTransformSpatialForce(\n    const Isometry3d& T,\n    const Eigen::MatrixBase<Eigen::Matrix<double, 6, 1, 0, 6, 1>>& X,\n    const Eigen::MatrixBase<Eigen::Matrix<double, 16, -1, 0, 16, -1>>& dT,\n    const Eigen::MatrixBase<Eigen::Matrix<double, 6, -1, 0, 6, -1>>& dX);\n\ntemplate DLLEXPORT  void cylindrical2cartesian(const Matrix<double,3,1> &cylinder_axis, const Matrix<double,3,1> &cylinder_x_dir, const Matrix<double,3,1> & cylinder_origin, const Matrix<double,6,1> &x_cylinder, const Matrix<double,6,1> &v_cylinder, Matrix<double,6,1> &x_cartesian, Matrix<double,6,1> &v_cartesian, Matrix<double,6,6> &J, Matrix<double,6,1> &Jdotv );\n\ntemplate DLLEXPORT  void cartesian2cylindrical(const Matrix<double,3,1> &cylinder_axis, const Matrix<double,3,1> &cylinder_x_dir, const Matrix<double,3,1> & cylinder_origin, const Matrix<double,6,1> &x_cartesian, const Matrix<double,6,1> &v_cartesian, Matrix<double,6,1> &x_cylinder, Matrix<double,6,1> &v_cylinder, Matrix<double,6,6> &J, Matrix<double,6,1> &Jdotv );\n\ntemplate DLLEXPORT void angularvel2quatdotMatrix(const Eigen::MatrixBase<Vector4d>& q,\n    Eigen::MatrixBase< Matrix<double, QUAT_SIZE, SPACE_DIMENSION> >& M,\n    Eigen::MatrixBase< Gradient<Matrix<double, QUAT_SIZE, SPACE_DIMENSION>, QUAT_SIZE, 1>::type>* dM);\ntemplate DLLEXPORT void angularvel2quatdotMatrix(const Eigen::MatrixBase<Map<Vector4d>>& q,\n    Eigen::MatrixBase< Matrix<double, QUAT_SIZE, SPACE_DIMENSION> >& M,\n    Eigen::MatrixBase< Gradient<Matrix<double, QUAT_SIZE, SPACE_DIMENSION>, QUAT_SIZE, 1>::type>* dM);\ntemplate DLLEXPORT void angularvel2quatdotMatrix(const Eigen::MatrixBase< Eigen::Block<Eigen::Ref<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 0, Eigen::InnerStride<1> > const, 4, 1, false> >& q,\n    Eigen::MatrixBase< Matrix<double, QUAT_SIZE, SPACE_DIMENSION> >& M,\n    Eigen::MatrixBase< Gradient<Matrix<double, QUAT_SIZE, SPACE_DIMENSION>, QUAT_SIZE, 1>::type>* dM);\n\ntemplate DLLEXPORT void angularvel2rpydotMatrix(const Eigen::MatrixBase<Vector3d>& rpy,\n    Eigen::MatrixBase< Matrix<double, RPY_SIZE, SPACE_DIMENSION> >& phi,\n    Eigen::MatrixBase< Gradient<Matrix<double, RPY_SIZE, SPACE_DIMENSION>, RPY_SIZE, 1>::type>* dphi,\n    Eigen::MatrixBase< Gradient<Matrix<double, RPY_SIZE, SPACE_DIMENSION>, RPY_SIZE, 2>::type>* ddphi);\n\ntemplate DLLEXPORT void angularvel2rpydotMatrix(const Eigen::MatrixBase<Vector3d>& rpy,\n    Eigen::MatrixBase< Matrix<double, RPY_SIZE, SPACE_DIMENSION> >& phi,\n    Eigen::MatrixBase< Matrix<double, Eigen::Dynamic, Eigen::Dynamic> >* dphi,\n    Eigen::MatrixBase< Matrix<double, Eigen::Dynamic, Eigen::Dynamic> >* ddphi);\n\ntemplate DLLEXPORT void rpydot2angularvelMatrix(const Eigen::MatrixBase<Vector3d>& rpy,\n    Eigen::MatrixBase<Eigen::Matrix<double, SPACE_DIMENSION, RPY_SIZE> >& E,\n    Gradient<Matrix<double,SPACE_DIMENSION,RPY_SIZE>,RPY_SIZE,1>::type* dE);\ntemplate DLLEXPORT void rpydot2angularvelMatrix(const Eigen::MatrixBase<Map<Vector3d>>& rpy,\n    Eigen::MatrixBase<Eigen::Matrix<double, SPACE_DIMENSION, RPY_SIZE> >& E,\n    Gradient<Matrix<double,SPACE_DIMENSION,RPY_SIZE>,RPY_SIZE,1>::type* dE);\ntemplate DLLEXPORT void rpydot2angularvelMatrix(const Eigen::MatrixBase< Eigen::Block<Eigen::Ref<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 0, Eigen::InnerStride<1> > const, 3, 1, false> >& rpy,\n    Eigen::MatrixBase<Eigen::Matrix<double, SPACE_DIMENSION, RPY_SIZE> >& E,\n    Gradient<Matrix<double,SPACE_DIMENSION,RPY_SIZE>,RPY_SIZE,1>::type* dE);\n\ntemplate DLLEXPORT GradientVar<double, Eigen::Dynamic, SPACE_DIMENSION> angularvel2RepresentationDotMatrix(\n    int rotation_type, const Eigen::MatrixBase<VectorXd>& qrot, int gradient_order);\ntemplate DLLEXPORT GradientVar<double, Eigen::Dynamic, SPACE_DIMENSION> angularvel2RepresentationDotMatrix(\n    int rotation_type, const Eigen::MatrixBase< Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, -1, 1, false> >& qrot, int gradient_order);\ntemplate DLLEXPORT GradientVar<double, -1, 3> angularvel2RepresentationDotMatrix<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1>, -1, 1, false> >(int, Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1>, -1, 1, false> > const&, int);\ntemplate DLLEXPORT GradientVar<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, -1, 1, false>::Scalar, -1, 3> angularvel2RepresentationDotMatrix<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, -1, 1, false> >(int,\n    Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, -1, 1, false> > const&, int);\ntemplate DLLEXPORT GradientVar<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1> const, -1, 1, false>::Scalar, -1, 3> angularvel2RepresentationDotMatrix<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1> const, -1, 1, false> >(int,\n    Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1> const, -1, 1, false> > const&, int);\n\n\ntemplate DLLEXPORT void quatdot2angularvelMatrix(const Eigen::MatrixBase<Vector4d>& q,\n    Eigen::MatrixBase< Matrix<double, SPACE_DIMENSION, QUAT_SIZE> >& M,\n    Gradient<Matrix<double, SPACE_DIMENSION, QUAT_SIZE>, QUAT_SIZE, 1>::type* dM);\ntemplate DLLEXPORT void quatdot2angularvelMatrix(const Eigen::MatrixBase<Map<Vector4d>>& q,\n    Eigen::MatrixBase< Matrix<double, SPACE_DIMENSION, QUAT_SIZE> >& M,\n    Gradient<Matrix<double, SPACE_DIMENSION, QUAT_SIZE>, QUAT_SIZE, 1>::type* dM);\ntemplate DLLEXPORT void quatdot2angularvelMatrix(const Eigen::MatrixBase< Eigen::Block<Eigen::Ref<Eigen::Matrix<double, -1, 1, 0, -1, 1> const, 0, Eigen::InnerStride<1> > const, 4, 1, false> >& q,\n    Eigen::MatrixBase< Matrix<double, SPACE_DIMENSION, QUAT_SIZE> >& M,\n    Gradient<Matrix<double, SPACE_DIMENSION, QUAT_SIZE>, QUAT_SIZE, 1>::type* dM);\n\n\n", "meta": {"hexsha": "10e2cf26909ae67a6bb1c3e65dc569260d11aa50", "size": 78484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/drakeGeometryUtil.cpp", "max_stars_repo_name": "jacob-izr/drake", "max_stars_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/drakeGeometryUtil.cpp", "max_issues_repo_name": "jacob-izr/drake", "max_issues_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/drakeGeometryUtil.cpp", "max_forks_repo_name": "jacob-izr/drake", "max_forks_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.9401913876, "max_line_length": 424, "alphanum_fraction": 0.671003007, "num_tokens": 28275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6384636061630823}}
{"text": "/*\n* compile with flags:   g++ test.cc softmax_classifier.cc   ../datasets/datasets.cc -std=c++14 -larmadillo -I ../../include/\n* author: Yuzhen Liu\n* Date: 2019.4.16 21:35\n*/\n\n#include <iostream>\n#include <armadillo>\n#include <cmath>\n#include <factorization/fm.h>\n#include <datasets/datasets.h>\n\nusing namespace std;\nusing namespace arma;\n\n\n\nint main() {\n    Datasets dataset = Datasets(\"iris\");\n\n    // Logistic classifier testing\n    vec y = dataset.y.subvec(0, 99);\n    mat x = dataset.x.submat(0, 0, 3, 99);\n    uvec field(4, fill::ones);\n    FM fm = FM();\n    fm.train(x, field, y);\n    // vec res = fm.predict(mat({{6.1, 2.9, 4.7, 1.4}, {5.1, 3.5, 1.4, 0.2}}).t());\n    vec res = fm.predict(x, field);\n    (res - y).print();\n\n    return 0;\n}\n\n", "meta": {"hexsha": "91fabc9433fb5185f930c452728512cf22699875", "size": 750, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/factorization_test.cc", "max_stars_repo_name": "codestorm04/Machine_Learning_CPP", "max_stars_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-06-05T09:31:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T13:37:44.000Z", "max_issues_repo_path": "examples/factorization_test.cc", "max_issues_repo_name": "codestorm04/Machine_Learning_CPP", "max_issues_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/factorization_test.cc", "max_forks_repo_name": "codestorm04/Machine_Learning_CPP", "max_forks_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-15T04:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T15:59:30.000Z", "avg_line_length": 22.0588235294, "max_line_length": 124, "alphanum_fraction": 0.604, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034426, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.6384044293631802}}
{"text": "#include <iostream>\r\n#include <NTL/lzz_p.h>\r\n#include <NTL/lzz_pX.h>\r\n\r\nusing namespace NTL;\r\n\r\nint main()\r\n{\r\n  int n = 24680;\r\n  n -= 1;\r\n  long mod = 1020202009;  \r\n  int fac_n = 1;\r\n  for (int i = 2; i <= n; i++) {\r\n    fac_n = (long)fac_n * i % mod; \r\n  }\r\n  zz_p::init(mod);\r\n  zz_pX den;\r\n  den.SetLength(n);\r\n  int inv_f = InvMod(fac_n,mod);\r\n  for (int i = n; i; i--) {\r\n    switch (i % 4) {\r\n      case 1: SetCoeff(den, i, mod-inv_f); break;\r\n      case 3: SetCoeff(den, i, inv_f); break;\r\n    }\r\n    inv_f = (long)inv_f * i % mod;\r\n  }\r\n  SetCoeff(den,0, 1);\r\n  zz_pX egf = InvTrunc(den,n+1);\r\n  std::cout << zz_p(fac_n) * coeff(egf,n) << std::endl;\r\n}", "meta": {"hexsha": "6e81d8a68660bf83cb2b9b353f5b68a50a502f7a", "size": 663, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "700-800/709.cpp", "max_stars_repo_name": "Thomaw/Project-Euler", "max_stars_repo_head_hexsha": "bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "700-800/709.cpp", "max_issues_repo_name": "Thomaw/Project-Euler", "max_issues_repo_head_hexsha": "bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "700-800/709.cpp", "max_forks_repo_name": "Thomaw/Project-Euler", "max_forks_repo_head_hexsha": "bcad5d8a1fd3ebaa06fa52d92d286607e9372a8d", "max_forks_repo_licenses": ["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.1, "max_line_length": 56, "alphanum_fraction": 0.5294117647, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133531922389, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6383691224550989}}
{"text": "#include <iostream>\n#include <cmath>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n\n\nint main() {\n\n  Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n\n  Eigen::AngleAxisd rotation_vector(M_PI / 4, Eigen::Vector3d(0, 0, 1));\n  std::cout << \"rotation_matrix = \\n\" << rotation_vector.matrix() << std::endl << std::endl;\n\n  rotation_matrix = rotation_vector.toRotationMatrix();\n\n  Eigen::Vector3d v(1, 0, 0);\n  Eigen::Vector3d v_rotated = rotation_vector * v;\n  std::cout << \"(1, 0, 0) after rotation = \" << v_rotated.transpose() << std::endl << std::endl;\n\n  v_rotated = rotation_matrix * v;\n  std::cout << \"(1, 0, 0) after rotation = \" << v_rotated.transpose() << std::endl << std::endl;\n\n  Eigen::Vector3d euler_angles = rotation_matrix.eulerAngles(2, 1, 0);\n  std::cout << \"yaw pitch roll = \" << euler_angles.transpose() << std::endl << std::endl;\n\n  Eigen::Isometry3d t = Eigen::Isometry3d::Identity();\n  t.rotate(rotation_vector);\n  t.pretranslate(Eigen::Vector3d(1, 3, 4));\n  std::cout << \"Transform matrix = \\n\" << t.matrix() << std::endl << std::endl;\n\n  Eigen::Vector3d v_transformed = t * v;\n  std::cout << \"v transformed = \" << v_transformed.transpose() << std::endl << std::endl;\n\n\n  Eigen::Quaterniond q = Eigen::Quaterniond(rotation_vector);\n  std::cout << \"quaternion = \\n\" << q.coeffs() << std::endl << std::endl;\n\n  q = Eigen::Quaterniond(rotation_matrix);\n  std::cout << \"quaternion = \\n\" << q.coeffs() << std::endl << std::endl;\n\n  v_rotated = q * v;\n  std::cout << \"(1, 0, 0) after rotation = \" << v_rotated.transpose() << std::endl << std::endl;\n\n\n  return 0;\n}\n", "meta": {"hexsha": "1cc857d7109c3a2fb6533f74f35509711c370f64", "size": 1598, "ext": "cc", "lang": "C++", "max_stars_repo_path": "VisionSLAM14/ch3/UsingGeometry/using_geometry.cc", "max_stars_repo_name": "DLonng/Go", "max_stars_repo_head_hexsha": "a67ac6d6501f9fadadec6a6cf766d4b4a356d572", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2020-04-10T01:53:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T03:43:10.000Z", "max_issues_repo_path": "VisionSLAM14/ch3/UsingGeometry/using_geometry.cc", "max_issues_repo_name": "DLonng/Go", "max_issues_repo_head_hexsha": "a67ac6d6501f9fadadec6a6cf766d4b4a356d572", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-10T07:08:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-14T07:47:01.000Z", "max_forks_repo_path": "VisionSLAM14/ch3/UsingGeometry/using_geometry.cc", "max_forks_repo_name": "DLonng/Go", "max_forks_repo_head_hexsha": "a67ac6d6501f9fadadec6a6cf766d4b4a356d572", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-04-05T11:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T10:23:37.000Z", "avg_line_length": 32.612244898, "max_line_length": 96, "alphanum_fraction": 0.6382978723, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.638339072667467}}
{"text": "//    Copyright 2017 Rainer Gemulla\n// \n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n// \n//        http://www.apache.org/licenses/LICENSE-2.0\n// \n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n#include <iostream>\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/random/uniform_real.hpp>\n\n#include <util/evaluation.h>\n#include <util/io.h>\n\n#include <mf/mf.h>\n\nusing namespace std;\nusing namespace mf;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\n\n#define NDIM 4\n\nint main() {\n\tmf_size_type n = 4;\n\n\t// coefficient matrix\n\tDenseMatrixCM a(n, n), aLu(n,n), aQr(n,n), aS(n,n);\n\ta(0,0) = 1.0;\n\ta(0,1) = -1.0;\n\ta(0,2) = 2.0;\n\ta(0,3) = -1.0;\n\ta(1,0) = 2.0;\n\ta(1,1) = -2.0;\n\ta(1,2) = 3.0;\n\ta(1,3) = -3.0;\n\ta(2,0) = 1.0;\n\ta(2,1) = 1.0;\n\ta(2,2) = 1.0;\n\ta(2,3) = 0.0;\n\ta(3,0) = 1.0;\n\ta(3,1) = -1.0;\n\ta(3,2) = 4.0;\n\ta(3,3) = 3.0;\n\n\t// right hand side\n\tboost::numeric::ublas::vector<double> b(n), x(n), tau(n);\n\tb[0] = -8.0;\n\tb[1] = -20.0;\n\tb[2] = -2.0;\n\tb[3] = 4.0;\n\n\t// print\n\tcout << \"A = \" << a << endl;\n\tcout << \"b = \" << b << endl;\n\n\t// compute LU factorization\n\tboost::numeric::ublas::vector<clapack::integer> ipiv(n);\n\taLu = a;\n\tcout << lu(aLu, ipiv) << endl;\n\tcout << \"A(LU) = \" << aLu << endl;\n\tcout << \"Row permutations = \" << ipiv << endl;\n\n\t// solve LP\n\tx = b;\n\tcout << lpLu(aLu, ipiv, &x.data()[0]) << endl;\n\n\t// print\n\tcout << \"x = \" << x << endl;\n\tcout << \"Ax = \" << prod(a, x) << endl;\n\n\t// qr decomposition\n\taQr = a;\n\tcout << qr(aQr, tau) << endl;\n\tcout << \"A(QR) = \" << aQr << endl;\n\tcout << \"tau = \" << tau << endl;\n\n\t// solve least squares problem\n\tstd::pair<clapack::integer, clapack::integer> swork = llsWork(n,n);\n\tboost::numeric::ublas::vector<double> s(n); // singular values\n\tboost::numeric::ublas::vector<double> work(swork.first);\n\tboost::numeric::ublas::vector<clapack::integer> iwork(swork.second);\n\taS = a;\n\tx = b;\n\tcout << lls(aS, x.data().begin(), s, work, iwork) << endl;\n\tcout << \"A(S) = \" << aS << endl;\n\tcout << \"s = \" << s << endl;\n\tcout << \"x = \" << x << endl;\n\tcout << \"Ax = \" << prod(a, x) << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "154643f02a3d1253418f2c4018ac1b6d03e2c878", "size": 2616, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/lapack-wrapper.cc", "max_stars_repo_name": "Hui-Li/DSGDPP", "max_stars_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T11:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T23:03:55.000Z", "max_issues_repo_path": "examples/mf/lapack-wrapper.cc", "max_issues_repo_name": "Hui-Li/DSGDPP", "max_issues_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/mf/lapack-wrapper.cc", "max_forks_repo_name": "Hui-Li/DSGDPP", "max_forks_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-10-27T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T15:10:56.000Z", "avg_line_length": 25.1538461538, "max_line_length": 78, "alphanum_fraction": 0.5948012232, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6381869453595012}}
{"text": "// Unit test for the computeTimeStep function in fvm_1d_functions.cpp\n// This function calculates the time step based on the fastest speed in the system, delta x, and the CFL number\n// COMPLETE. This function works as intended. 2021/11/22\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"../main/fvm_1D_functions.h\" \n#include \"../main/testing_functions.h\" \n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n    \n    // Print what we are doing\n    cout << \"------------------------------------- \" << \\\n    \"This is a test of the computeTimeStep function.\" << \\\n    \" -------------------------------------\" << endl;    \n\n    // Set the input parameters to the cons2prim function\n    double gasGamma = 5./3.;   // Use standard gasGamma of 5/3\n    double CFL = 0.9;          // Set CFL number\n    double dx = 0.5;           // Set delta x\n\n    // Make an array of primitive variables such that there are two elements in each 1D array\n    Array<ArrayXd, 3, 1> V;\n    V(0) = ArrayXd::Zero(2);\n    V(0)(0) = 5.;\n    V(0)(1) = 1.;\n    V(1) = ArrayXd::Zero(2);\n    V(1)(0) = 1.0;\n    V(1)(1) = -0.2;\n    V(2) = ArrayXd::Zero(2);\n    V(2)(0) = 12.;\n    V(2)(1) = 27./5.;\n\n    // Set the exact value of the time step. Calculated by hand based on input values chosen\n    double dt_exact = 0.140625;\n\n    // Calculate the time step    \n    double dt = computeTimeStep(CFL, dx, gasGamma, V);\n\n    // Set the acceptable tolerance. (Somewhat arbitrarily chosen)\n    double TOL = 1e-14;    \n\n    // Determine if the two values are equal\n    bool boolVal = isEqualDouble(dt, dt_exact, TOL);    \n\n    // Get the minimum value of the boolean array.\n    // If it is 0, then at least one value in this array is incorrect    \n    if (boolVal == 1) {\n        cout << \"Test of computeTimeStep is a success.\" << endl;            \n    }\n    else  {\n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n            << \"Test of computeTimeStep is a failure.\" << endl \\\n            << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    }    \n    cout << endl << endl;\n}", "meta": {"hexsha": "072cfbb55e92862c2730039051f62f44fd3eec82", "size": 2046, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FVM_1D/unitTests/test_computeTimeStep.cpp", "max_stars_repo_name": "Aquadorf/computational-skolar", "max_stars_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FVM_1D/unitTests/test_computeTimeStep.cpp", "max_issues_repo_name": "Aquadorf/computational-skolar", "max_issues_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FVM_1D/unitTests/test_computeTimeStep.cpp", "max_forks_repo_name": "Aquadorf/computational-skolar", "max_forks_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1, "max_line_length": 111, "alphanum_fraction": 0.5571847507, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.7718434873426303, "lm_q1q2_score": 0.6380921207535053}}
{"text": "/*=================================================================================\n *\t                    Copyleft! 2018 William Yu\n *          Some rights reserved\uff1aCC(creativecommons.org)BY-NC-SA\n *                      Copyleft! 2018 William Yu\n *      \u7248\u6743\u90e8\u5206\u6240\u6709\uff0c\u9075\u5faaCC(creativecommons.org)BY-NC-SA\u534f\u8bae\u6388\u6743\u65b9\u5f0f\u4f7f\u7528\n *\n * Filename                : \n * Description             : \u89c6\u89c9SLAM\u5341\u56db\u8bb2/ch3/useEigen/eigenMatrix.cpp \u5b66\u4e60\u8bb0\u5f55\n\t\t\t\t\t\t\t\tEigen\u77e9\u9635\u5e93                    \n * Reference               : \n * Programmer(s)           : William Yu, windmillyucong@163.com\n * Company                 : HUST, DMET\u56fd\u5bb6\u91cd\u70b9\u5b9e\u9a8c\u5ba4FOCUS\u56e2\u961f\n * Modification History\t   : ver1.0, 2018.03.26, William Yu\n                            \n=================================================================================*/\n/// Include Files\n#include<iostream>\n#include<ctime>\n#include <Eigen/Core>\n//\u7a20\u5bc6\u77e9\u9635\u7684\u4ee3\u6570\u8fd0\u7b97\uff08\u6c42\u9006\uff0c\u7279\u5f81\u503c\u7b49\uff09\n#include <Eigen/Dense>\n\nusing namespace std;\n\n\n/// Global Variables\n#define MATRIX_SIZE 50 //\u77e9\u9635\u5927\u5c0f\n\n\n\n/// Function Definitions\n\n\n/**\n * @function main\n * @author William Yu\n * @brief Eigen\u57fa\u672c\u7c7b\u578b\u4f7f\u7528\u793a\u4f8b\n * @param  None\n * @retval None\n */\nint main(int argc, char** argv )\n{\n    //---------------------------------------------------------------------------\n    //  \u521b\u5efa\u77e9\u9635&\u521d\u59cb\u5316\u64cd\u4f5c\n    //----------------------------------------------------------------\n    // \u58f0\u660e\u4e00\u4e2a2*3\u7684float\u77e9\u9635\n    Eigen::Matrix<float,2,3> matrix_23;\n    \n    // \u58f0\u660e\u4e00\u4e2a3*1\u7684\u77e9\u9635\n    Eigen::Matrix<float,3,1>vd_3d;\n    // \u6216\u8005\u4e0b\u5217\u65b9\u5f0f\u4e5f\u53ef\u4ee5\n    Eigen::Vector3d v_3d;\n    \n    // Matrix3d \u5b9e\u8d28\u4e0a\u662f Eigen::Matrix<double, 3, 3>\n    Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero(); //\u521d\u59cb\u5316\u4e3a\u96f6\n\n    // \u5efa\u7acb\u52a8\u6001\u5927\u5c0f\u7684\u77e9\u9635\n    Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > matrix_dynamic;\n    // \u66f4\u7b80\u5355\u7684\u5199\u6cd5\n    Eigen::MatrixXd matrix_x;\n    \n    // \u968f\u673a\u6570\u77e9\u9635Random\u586b\u5145\n    matrix_33 = Eigen::Matrix3d::Random();\n    cout << \"\u521b\u5efa\u968f\u673a\u77e9\u9635\" << endl;\n    cout << matrix_33 << endl << endl;\n    \n\n\n\n\n\n    //---------------------------------------------------------------------------\n    //  \u77e9\u9635\u5143\u7d20\u64cd\u4f5c\n    //----------------------------------------------------------------\n    // \u8f93\u5165\u6570\u636e\uff08\u521d\u59cb\u5316\uff09\n    matrix_23 << 1, 2, 3, 4, 5, 6;\n    // \u76f4\u63a5\u6574\u4f53\u8f93\u51fa\n    cout << \"matrix_23:\" << endl;\n    cout << matrix_23 << endl;\n    // \u7528for()\u8bbf\u95ee\u77e9\u9635\u4e2d\u7684\u5143\u7d20\n    for (int i=0; i<2; i++) {\n        for (int j=0; j<3; j++)\n            cout<<matrix_23(i,j)<<\"\\t\";\n        cout<<endl;\n    }\n    \n\n\n\n\n    //---------------------------------------------------------------------------\n    //  \u77e9\u9635\u8fd0\u7b97\n    //----------------------------------------------------------------\n    // \u77e9\u9635\u548c\u5411\u91cf\u76f8\u4e58\uff08\u5b9e\u9645\u4e0a\u4ecd\u662f\u77e9\u9635\u548c\u77e9\u9635\u76f8\u4e58\uff09\n    v_3d << 3, 2, 1;\n    vd_3d << 4, 5, 6;\n    // \u4f46\u662f\u5728Eigen\u91cc\u4f60\u4e0d\u80fd\u6df7\u5408\u4e24\u79cd\u4e0d\u540c\u7c7b\u578b\u7684\u77e9\u9635\uff0c\u50cf\u8fd9\u6837\u662f\u9519\u7684\n    // Eigen::Matrix<double, 2, 1> result_wrong_type = matrix_23 * v_3d;\n    // \u5e94\u8be5\u663e\u5f0f\u8f6c\u6362\n    Eigen::Matrix<double, 2, 1> result = matrix_23.cast<double>() * v_3d;\n    cout << result << endl;\n\n    Eigen::Matrix<float, 2, 1> result2 = matrix_23 * vd_3d;\n    cout << result2 << endl;\n    // \u540c\u6837\u4f60\u4e0d\u80fd\u641e\u9519\u77e9\u9635\u7684\u7ef4\u5ea6\n    // \u8bd5\u7740\u53d6\u6d88\u4e0b\u9762\u7684\u6ce8\u91ca\uff0c\u770b\u770bEigen\u4f1a\u62a5\u4ec0\u4e48\u9519\n    // Eigen::Matrix<double, 2, 3> result_wrong_dimension = matrix_23.cast<double>() * v_3d;\n\n\n    //-- \u77e9\u9635\u8fd0\u7b97\n    // \u56db\u5219\u8fd0\u7b97\u5c31\u4e0d\u6f14\u793a\u4e86\uff0c\u76f4\u63a5\u7528+-*/\u5373\u53ef\u3002\n    cout << matrix_33.transpose() << endl;      // \u8f6c\u7f6e\n    cout << matrix_33.sum() << endl;            // \u5404\u5143\u7d20\u548c\n    cout << matrix_33.trace() << endl;          // \u8ff9\n    cout << 10*matrix_33 << endl;               // \u6570\u4e58\n    cout << matrix_33.inverse() << endl;        // \u9006\n    cout << matrix_33.determinant() << endl;    // \u884c\u5217\u5f0f\n    \n\n\n\n\n\n    //---------------------------------------------------------------------------\n    //  \u7279\u5f81\u503c\u6c42\u89e3\n    //----------------------------------------------------------------\n    // \u5b9e\u5bf9\u79f0\u77e9\u9635\u53ef\u4ee5\u4fdd\u8bc1\u5bf9\u89d2\u5316\u6210\u529f\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigen_solver ( matrix_33.transpose()*matrix_33 );\n    cout << \"Eigen values = \\n\" << eigen_solver.eigenvalues() << endl;\n    cout << \"Eigen vectors = \\n\" << eigen_solver.eigenvectors() << endl;\n\n    \n\n\n\n    //---------------------------------------------------------------------------\n    //  \u77e9\u9635\u65b9\u7a0b\n    //----------------------------------------------------------------\n    // \u6c42\u89e3 matrix_NN * x = v_Nd \u8fd9\u4e2a\u65b9\u7a0b\n    // N\u7684\u5927\u5c0f\u5728\u524d\u8fb9\u7684\u5b8f\u91cc\u5b9a\u4e49\uff0c\u5b83\u7531\u968f\u673a\u6570\u751f\u6210\n    // \u76f4\u63a5\u6c42\u9006\u81ea\u7136\u662f\u6700\u76f4\u63a5\u7684\uff0c\u4f46\u662f\u6c42\u9006\u8fd0\u7b97\u91cf\u5927\n    Eigen::Matrix< double, MATRIX_SIZE, MATRIX_SIZE > matrix_NN;\n    matrix_NN = Eigen::MatrixXd::Random( MATRIX_SIZE, MATRIX_SIZE );\n    Eigen::Matrix< double, MATRIX_SIZE,  1> v_Nd;\n    v_Nd = Eigen::MatrixXd::Random( MATRIX_SIZE,1 );\n    \n    clock_t time_stt = clock(); // \u8ba1\u65f6\u51fd\u6570\n    //[1]-- \u76f4\u63a5\u6c42\u9006\n    Eigen::Matrix<double,MATRIX_SIZE,1> 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    //[2]-- \u901a\u5e38\u7528\u77e9\u9635\u5206\u89e3\u6765\u6c42\uff0c\u4f8b\u5982QR\u5206\u89e3\uff0c\u901f\u5ea6\u4f1a\u5feb\u5f88\u591a\n    time_stt = clock();\n    x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n    cout <<\"time use in Qr decomposition is \" <<1000*  (clock() - time_stt)/(double)CLOCKS_PER_SEC <<\"ms\" << endl;\n\n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "322b704fb939216a672ead3b823577318bbf065f", "size": 4844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3.\u4e09\u7ef4\u7a7a\u95f4\u521a\u4f53\u8fd0\u52a8/useEigen/eigenMatrix_test.cpp", "max_stars_repo_name": "HustRobot/VSLAM", "max_stars_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T06:35:49.000Z", "max_issues_repo_path": "3.\u4e09\u7ef4\u7a7a\u95f4\u521a\u4f53\u8fd0\u52a8/useEigen/eigenMatrix_test.cpp", "max_issues_repo_name": "HustRobot/VSLAM", "max_issues_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3.\u4e09\u7ef4\u7a7a\u95f4\u521a\u4f53\u8fd0\u52a8/useEigen/eigenMatrix_test.cpp", "max_forks_repo_name": "HustRobot/VSLAM", "max_forks_repo_head_hexsha": "e6759dc3769b3cca6ecf551a3bf120b0edeaeaa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-09-17T15:56:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T07:27:34.000Z", "avg_line_length": 29.9012345679, "max_line_length": 114, "alphanum_fraction": 0.4659372419, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6380493562827093}}
{"text": "//Author: Dr. Shantanu Shahane\n#include <stdio.h>\n#include <math.h>\n#include <stdlib.h>\n#include <time.h>\n#include <float.h>\n#include <string.h>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include \"class.hpp\"\n#include \"coefficient_computations.hpp\"\n#include <unistd.h>\n#include <limits.h>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/SparseExtra>\n#include <Eigen/SparseLU>\n#include <Eigen/OrderingMethods>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Spectra/GenEigsSolver.h>\n#include <Spectra/MatOp/SparseGenMatProd.h>\n#include <Spectra/GenEigsRealShiftSolver.h>\n#include <Spectra/MatOp/SparseGenRealShiftSolve.h>\n#include \"nanoflann.hpp\"\nusing namespace std;\n\nSOLIDIFICATION::SOLIDIFICATION(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, int temporal_order1)\n{\n    temporal_order = temporal_order1;\n    if (temporal_order != 1 && temporal_order != 2)\n    {\n        printf(\"\\n\\nERROR from SOLIDIFICATION::SOLIDIFICATION temporal_order should be either '1' or '2'; current value: %i\\n\\n\", temporal_order);\n        throw bad_exception();\n    }\n    if (temporal_order == 2)\n        T_old_old = Eigen::VectorXd::Zero(points.nv), fs_old_old = Eigen::VectorXd::Zero(points.nv);\n    dfs_dT = Eigen::VectorXd::Zero(points.nv);\n    T_source = Eigen::VectorXd::Zero(points.nv);\n}\n\nvoid SOLIDIFICATION::single_timestep_2d(POINTS &points, CLOUD &cloud, PARAMETERS &parameters, Eigen::VectorXd &T_new, Eigen::VectorXd &T_old, Eigen::VectorXd &fs_new, Eigen::VectorXd &fs_old, int it)\n{\n    if (temporal_order == 1 || it == 0)\n    {\n        T_source = T_old + (parameters.dt * alpha * (points.laplacian_matrix_EIGEN * T_old));\n        T_source = T_source - ((Lf / Cp) * dfs_dT.cwiseProduct(T_old));\n        T_source = T_source.cwiseQuotient(Eigen::VectorXd::Ones(points.nv) - ((Lf / Cp) * dfs_dT));\n    }\n    else\n    {\n        T_source = T_old + (parameters.dt * alpha * (points.laplacian_matrix_EIGEN * (1.5 * T_old - 0.5 * T_old_old)));\n        T_source = T_source - ((1.5 * Lf / Cp) * dfs_dT.cwiseProduct(T_old));\n        T_source = T_source + ((0.5 * Lf / Cp) * (3 * fs_old - 4 * fs_old + fs_old_old));\n        T_source = T_source.cwiseQuotient(Eigen::VectorXd::Ones(points.nv) - ((1.5 * Lf / Cp) * dfs_dT));\n    }\n\n    for (int iv = 0; iv < points.nv; iv++)\n        if (!points.boundary_flag[iv]) //boundary points should have dirichlet\n            T_new[iv] = T_source[iv];  //non-boundary points only\n\n    double fs_hat = 1.0 - pow((Tsol + Teps - Tf) / (Tliq - Tf), 1.0 / (k_partition - 1.0));\n    for (int iv = 0; iv < points.nv; iv++)\n    {\n        if (T_new[iv] <= Tsol)\n            fs_new[iv] = 1.0;\n        else if (T_new[iv] >= Tliq)\n            fs_new[iv] = 0.0;\n        else\n            fs_new[iv] = 1.0 - pow((T_new[iv] - Tf) / (Tliq - Tf), 1.0 / (k_partition - 1.0));\n        if ((T_new[iv] <= Tsol - Teps) || (T_new[iv] >= Tliq))\n            dfs_dT[iv] = 0.0;\n        else if ((T_new[iv] >= Tsol - Teps) && (T_new[iv] <= Tsol + Teps))\n            dfs_dT[iv] = -(1.0 - fs_hat) / (2.0 * Teps);\n        else\n        {\n            dfs_dT[iv] = pow((T_new[iv] - Tf) / (Tliq - Tf), (2.0 - k_partition) / (k_partition - 1.0));\n            dfs_dT[iv] = -dfs_dT[iv] / ((k_partition - 1.0) * (Tliq - Tf));\n        }\n    }\n    if (temporal_order == 2)\n        T_old_old = T_old, fs_old_old = fs_old;\n}", "meta": {"hexsha": "a45c5b2ac101c9ddf49e802da508cbd9ae3881ad", "size": 3369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "header_files/solidification.cpp", "max_stars_repo_name": "shahaneshantanu/memphys", "max_stars_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "header_files/solidification.cpp", "max_issues_repo_name": "shahaneshantanu/memphys", "max_issues_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "header_files/solidification.cpp", "max_forks_repo_name": "shahaneshantanu/memphys", "max_forks_repo_head_hexsha": "1b95afa505808f302d2dd4689faa45bb6480e8d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-07T00:32:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T00:32:37.000Z", "avg_line_length": 40.1071428571, "max_line_length": 199, "alphanum_fraction": 0.6182843574, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6380250241423612}}
{"text": "#include \"average_case_relative_error.hpp\"\n#include \"average_case_error.hpp\"\n#include \"cudd_helpers.hpp\"\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing abo::util::NumberRepresentation;\nusing boost::multiprecision::cpp_dec_float_100;\nusing boost::multiprecision::uint256_t;\n\nnamespace abo::error_metrics {\n\nstd::pair<cpp_dec_float_100, cpp_dec_float_100>\n    average_relative_value(const Cudd& mgr,\n                           const std::vector<BDD>& f,\n                           const std::vector<BDD>& g)\n{\n\n    BDD zero_so_far = mgr.bddOne();\n\n    cpp_dec_float_100 min_average_result = 0;\n    cpp_dec_float_100 max_average_result = 0;\n    std::vector<BDD> max_one = abo::util::bdd_max_one(mgr, g);\n    for (int i = int(g.size()) - 1; i >= 0; i--)\n    {\n        std::vector<BDD> partial_result;\n        partial_result.reserve(max_one.size());\n        BDD modifier = zero_so_far & max_one[i];\n        for (const BDD& b : f)\n        {\n            partial_result.push_back(b & modifier);\n        }\n        auto average = average_value(partial_result);\n        min_average_result += average / (std::pow(2.0, i + 1) - 1);\n        max_average_result += average / std::pow(2.0, i);\n\n        zero_so_far &= !max_one[i];\n    }\n\n    return {min_average_result, max_average_result};\n}\n\nstd::pair<cpp_dec_float_100, cpp_dec_float_100>\n    acre_bounds(const Cudd& mgr, const std::vector<BDD>& f,\n              const std::vector<BDD>& f_hat,\n              const util::NumberRepresentation num_rep)\n{\n\n    std::vector<BDD> absolute_difference =\n        abo::util::bdd_absolute_difference(mgr, f, f_hat, num_rep);\n    std::vector<BDD> f_absolute = abo::util::bdd_abs(mgr, f, num_rep);\n    return average_relative_value(mgr, absolute_difference, f_absolute);\n}\n\ncpp_dec_float_100\n    acre_add(const Cudd& mgr,\n            const std::vector<BDD>& f,\n            const std::vector<BDD>& f_hat,\n            const NumberRepresentation num_rep)\n{\n\n    ADD diff = abo::util::absolute_difference_add(mgr, f, f_hat, num_rep);\n    std::vector<BDD> f_absolute = abo::util::bdd_abs(mgr, f, num_rep);\n    ADD respective_diff = diff.Divide(\n        abo::util::bdd_forest_to_add(mgr, f_absolute).Maximum(mgr.addOne()));\n    std::vector<std::pair<double, unsigned long>> terminal_values =\n        abo::util::add_terminal_values(respective_diff);\n\n    cpp_dec_float_100 sum = 0;\n    uint256_t path_sum = 0;\n    for (auto p : terminal_values)\n    {\n        cpp_dec_float_100 value(p.first);\n        sum += value * p.second;\n        path_sum += p.second;\n    }\n    return cpp_dec_float_100(sum) /\n           cpp_dec_float_100(path_sum);\n}\n\ncpp_dec_float_100\n    acre_symbolic_division(const Cudd& mgr,\n                            const std::vector<BDD>& f,\n                            const std::vector<BDD>& f_hat,\n                            unsigned int num_extra_bits,\n                            const NumberRepresentation num_rep)\n{\n\n    std::vector<BDD> absolute_difference =\n        abo::util::bdd_absolute_difference(mgr, f, f_hat, num_rep);\n\n    std::vector<BDD> f_absolute = abo::util::bdd_abs(mgr, f, num_rep);\n    std::vector<BDD> no_zero = abo::util::bdd_max_one(mgr, f_absolute);\n    std::vector<BDD> divided =\n        abo::util::bdd_divide(mgr, absolute_difference,\n                              no_zero, num_extra_bits);\n\n    return average_value(divided) / std::pow(2.0, num_extra_bits);\n}\n\n} // namespace abo::error_metrics\n", "meta": {"hexsha": "8c7146ab2fbbec25d2bd2b79c25f3b94c12162d2", "size": 3414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/average_case_relative_error.cpp", "max_stars_repo_name": "keszocze/abo", "max_stars_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/error_metrics/average_case_relative_error.cpp", "max_issues_repo_name": "keszocze/abo", "max_issues_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/error_metrics/average_case_relative_error.cpp", "max_forks_repo_name": "keszocze/abo", "max_forks_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T14:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T14:50:31.000Z", "avg_line_length": 33.801980198, "max_line_length": 77, "alphanum_fraction": 0.6359109549, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.63802302702213}}
{"text": "#include \"pch.h\"\n#include \"ssdsMath.h\"\n#include \"ssdsTypes.h\"\n#include <Eigen/Eigenvalues>\n\nnamespace ssds {\n\nstatic float4x4 calcRegistrationT(span<float3> s, span<float3> d)\n{\n    size_t num_points = s.size();\n    double3 cs{}, cd{}; // double for precision\n    for (size_t i = 0; i < num_points; ++i) {\n        cs += s[i];\n        cd += d[i];\n    }\n    return translate(float3((cd - cs) / double(num_points)));\n}\n\nstatic float4x4 calcRegistrationRT(span<float3> s, span<float3> d)\n{\n    size_t num_points = s.size();\n    double3 cs{}, cd{}; // double for precision\n    for (size_t i = 0; i < num_points; ++i) {\n        cs += s[i];\n        cd += d[i];\n    }\n    cs /= double(num_points);\n    cd /= double(num_points);\n    if (num_points < 3)\n        return translate(cd - cs);\n\n    Eigen::Matrix<double, 4, 4> moment;\n    {\n        auto sit = s.data();\n        auto dit = d.data();\n        double sxx = 0, sxy = 0, sxz = 0, syx = 0, syy = 0, syz = 0, szx = 0, szy = 0, szz = 0;\n        for (int i = 0; i < num_points; ++i, ++sit, ++dit) {\n            sxx += (sit->x - cs.x) * (dit->x - cd.x);\n            sxy += (sit->x - cs.x) * (dit->y - cd.y);\n            sxz += (sit->x - cs.x) * (dit->z - cd.z);\n            syx += (sit->y - cs.y) * (dit->x - cd.x);\n            syy += (sit->y - cs.y) * (dit->y - cd.y);\n            syz += (sit->y - cs.y) * (dit->z - cd.z);\n            szx += (sit->z - cs.z) * (dit->x - cd.x);\n            szy += (sit->z - cs.z) * (dit->y - cd.y);\n            szz += (sit->z - cs.z) * (dit->z - cd.z);\n        }\n        moment(0, 0) = sxx + syy + szz;\n        moment(0, 1) = syz - szy;        moment(1, 0) = moment(0, 1);\n        moment(0, 2) = szx - sxz;        moment(2, 0) = moment(0, 2);\n        moment(0, 3) = sxy - syx;        moment(3, 0) = moment(0, 3);\n        moment(1, 1) = sxx - syy - szz;\n        moment(1, 2) = sxy + syx;        moment(2, 1) = moment(1, 2);\n        moment(1, 3) = szx + sxz;        moment(3, 1) = moment(1, 3);\n        moment(2, 2) = -sxx + syy - szz;\n        moment(2, 3) = syz + szy;        moment(3, 2) = moment(2, 3);\n        moment(3, 3) = -sxx - syy + szz;\n    }\n\n    float4x4 transform;\n    if (moment.norm() > 0) {\n        Eigen::EigenSolver<Eigen::Matrix<double, 4, 4>> es(moment);\n        int maxi = 0;\n        for (int i = 1; i < 4; ++i) {\n            if (es.eigenvalues()(maxi).real() < es.eigenvalues()(i).real()) {\n                maxi = i;\n            }\n        }\n\n        quatf rot = {\n            (float)es.eigenvectors()(0, maxi).real(),\n            (float)es.eigenvectors()(1, maxi).real(),\n            (float)es.eigenvectors()(2, maxi).real(),\n            (float)es.eigenvectors()(3, maxi).real(),\n        };\n        transform = to_mat4x4(rot);\n    }\n    float3 cs0 = mul_p(transform, float3(cs));\n    (float3&)transform[3] = cd - cs0;\n    return transform;\n}\n\n#if 0\nfloat4x4 calcRegistrationSRT(span<float3> s, span<float3> d)\n{\n    size_t num_points = s.size();\n    const int num_iterations = 50;\n    const double threshold = 1.0e-8;\n    const double scaleLowerBound = 1.0e-3;\n    float4x4 transform = calcRegistrationRT(s, d);\n\n    float3 scale = float3::one();\n    float3 denom = float3::zero();\n    {\n        auto sit = s.data();\n        for (int i = 0; i < num_points; ++i, ++sit) {\n            denom[0] += (*sit)[0] * (*sit)[0];\n            denom[1] += (*sit)[1] * (*sit)[1];\n            denom[2] += (*sit)[2] * (*sit)[2];\n        }\n    }\n\n    std::vector<float3> sstm(num_points);\n    {\n        auto sit = s.data();\n        for (int i = 0; i < num_points; ++i, ++sit) {\n            sstm[i][0] = (*sit)[0];\n            sstm[i][1] = (*sit)[1];\n            sstm[i][2] = (*sit)[2];\n        }\n    }\n\n    std::vector<float3> dstm(num_points);\n    for (size_t l = 0; l < num_iterations; ++l) {\n        float4x4 im = invert(transform);\n        auto dit = d.data();\n        for (size_t i = 0; i < num_points; ++i, ++dit)\n            dstm[i] = mul_p(im, *dit);\n\n        for (size_t d = 0; d < 3; ++d) {\n            double ds = 0.0;\n            auto sit = s.data();\n            for (size_t i = 0; i < num_points; ++i, ++sit) {\n                ds += (*sit)[d] * dstm[i][d];\n            }\n            scale[d] = denom[d] < threshold ? 1.0 : ds / denom[d];\n            sit = s.data();\n            for (size_t i = 0; i < num_points; ++i, ++sit) {\n                sstm[i][d] = scale[d] * (*sit)[d];\n            }\n        }\n        transform = calcRegistrationRT(num_points, sstm.begin(), pd);\n    }\n    double sv[3] = { scale[0], scale[1], scale[2] };\n    transform.setScale(sv, MSpace::kTransform);\n    return transform;\n}\n\nusing RegistrationFunc = float4x4(*)(span<float3> ps, span<float3> pd);\n\nstatic RegistrationFunc registrationFuncs[3] = {\n    calcRegistrationT,\n    calcRegistrationRT,\n    calcRegistrationSRT\n};\n\nvoid computeSamplePoints(std::vector<float3>& sample, int sid, int joint, const Output& output, const Input& input)\n{\n    const int num_vertices = input.num_vertices;\n    const int& num_indices = output.num_indices;\n\n    for (int v = 0; v < num_vertices; ++v) {\n        sample[v] = input.sample[sid * num_vertices + v];\n        const float3& s = input.rest_shape[v];\n        for (int i = 0; i < num_indices; ++i) {\n            const int jnt = output.skin_indices[v * num_indices + i];\n            if (jnt >= 0 && jnt != joint) {\n                const double w = output.skin_weights[v * num_indices + i];\n                const float4x4& at = output.skinMatrix[sid * input.num_joints + jnt];\n                sample[v] -= w * (s * at.asMatrix());\n            }\n        }\n    }\n}\n\nvoid subtractCentroid(std::vector<float3>& model, std::vector<float3>& sample, float3& corModel, float3& corSample, const Eigen::VectorXd& weight, const Output& output, const Input& input)\n{\n    const int num_vertices = input.num_vertices;\n\n    double wsqsum = 0;\n    corModel = {};\n    corSample = {};\n    for (int v = 0; v < num_vertices; ++v) {\n        const double w = weight[v];\n        corModel += w * w * input.restShape[v];\n        corSample += w * sample[v];\n        wsqsum += w * w;\n    }\n    corModel = corModel / wsqsum;\n    corSample = corSample / wsqsum;\n    for (int v = 0; v < num_vertices; ++v) {\n        model[v] = weight[v] * (input.restShape[v] - corModel);\n        sample[v] -= weight[v] * corSample;\n    }\n}\n\n\nclass JointTransformUpdator\n{\nprivate:\n    Output* output;\n    const Input* input;\n    const Eigen::VectorXd* weight;\n    int transformType;\n    int joint;\n\npublic:\n    JointTransformUpdator(Output* output_, const Input* input_,\n        const Eigen::VectorXd* weight_, int joint_, int transformType_)\n        : output(output_), input(input_),\n        weight(weight_), joint(joint_), transformType(transformType_)\n    {\n    }\n\n    void operator ()(const tbb::blocked_range<int>& range) const\n    {\n        std::vector<float3> model(input->num_vertices);\n        std::vector<float3> sample(input->num_vertices);\n        for (int s = range.begin(); s != range.end(); ++s) {\n            if (s == 0) {\n                output->skinMatrix[joint] = float4x4::identity;\n                continue;\n            }\n            computeSamplePoints(sample, s, joint, *output, *input);\n            float3 corModel(0, 0, 0), corSample(0, 0, 0);\n            subtractCentroid(model, sample, corModel, corSample, *weight, *output, *input);\n            float4x4 transform = registrationFuncs[transformType](model.size(), model.begin(), sample.begin());\n            float3 d = corSample - corModel * transform.asMatrix();\n            transform.setTranslation(d + transform.getTranslation(MSpace::kTransform), MSpace::kTransform);\n            output->skinMatrix[s * input->num_joints + joint] = transform;\n        }\n    }\n};\n\nvoid updateJointTransformProc(Output& output, int transformType, const Input& input, int selection = -1)\n{\n    const int num_vertices = input.sample.front().points.size();\n    const int num_samples  = input.sample.size();\n    const int num_joints    = output.num_joints;\n    const int num_indices  = output.num_indices;\n\n    Eigen::VectorXd weight = Eigen::VectorXd::Zero(num_vertices);\n    int begin = selection < 0 ? 0 : selection;\n    int end = selection < 0 ? num_joints : selection + 1;\n    for (int joint = begin; joint < end; ++joint) {\n        for (int v = 0; v < num_vertices; ++v) {\n            weight[v] = 0.0;\n            for (int i = 0; i < num_indices; ++i) {\n                int jnt = output.skin_indices[v * num_indices + i];\n                if (jnt == joint) {\n                    weight[v] = output.skin_weights[v * num_indices + i];\n                    break;\n                }\n            }\n        }\n        double wsqsum = weight.dot(weight);\n        if (wsqsum > 1.0e-8) {\n            tbb::blocked_range<int> blockedRange(0, num_samples);\n            JointTransformUpdator transformUpdator(&output, &input, &weight, joint, transformType);\n            tbb::parallel_for(blockedRange, transformUpdator);\n        }\n        else {\n            for (int s = 0; s < num_samples; ++s) {\n                output.skinMatrix[s * input.num_joints + joint] = float4x4::identity;\n            }\n            char buf[256];\n            printf(buf, \"Fixed joint #%d\", joint);\n        }\n    }\n}\n\nstatic PyObject* updateJointTransform(PyObject *self, PyObject *args)\n{\n    PyObject* pin            = PyTuple_GET_ITEM(args, 0);\n    PyObject* pout           = PyTuple_GET_ITEM(args, 1);\n    const int transformType = PyInt_AsLong(PyTuple_GET_ITEM(args, 2));\n    Input* const input   = reinterpret_cast<Input*>(PyCapsule_GetPointer(pin, \"SSDSInput\"));\n    Output* const output = reinterpret_cast<Output*>(PyCapsule_GetPointer(pout, \"SSDSOutput\"));\n    updateJointTransformProc(*output, transformType, *input);\n    return Py_None;\n}\n\n\n// see https://sites.google.com/view/fumiyanarita/project/la_ssdr_mdmc\nstatic void detectNeighborClusters(const Input& input, Output& output)\n{\n    MGlobal::displayInfo(\"Detecting neighbor clusters\");\n    const int& num_indices = output.num_indices;\n\n    std::vector<std::set<int>> clusters(output.num_joints);\n    for (int v = 0; v < input.num_vertices; ++v) {\n        const int primjid = output.skinIndex[v * num_indices];\n        if (input.numRings == 0) {\n            for (int j = 0; j < output.num_joints; ++j) {\n                for (int v = 0; v < output.num_joints; ++v) {\n                    clusters[j].insert(v);\n                }\n            }\n        }\n        else {\n            clusters[primjid].insert(0);\n            clusters[primjid].insert(primjid);\n            // one-ring neighbors\n            for (auto nvit = input.neighbor[v].begin(); nvit != input.neighbor[v].end(); ++nvit) {\n                const int nvid = nvit->first;\n                clusters[primjid].insert(output.skinIndex[nvid * num_indices]);\n                if (input.numRings == 1) {\n                    continue;\n                }\n                // two-ring neighbors\n                for (auto nnvit = input.neighbor[nvid].begin(); nnvit != input.neighbor[nvid].end(); ++nnvit) {\n                    const int nnvid = nnvit->first;\n                    clusters[primjid].insert(output.skinIndex[nnvid * num_indices]);\n                }\n            }\n        }\n    }\n    for (int v = 0; v < input.num_vertices; ++v) {\n        const int primjid = output.skinIndex[v * num_indices];\n        output.vertCluster[v] = std::vector<int>(clusters[primjid].begin(), clusters[primjid].end());\n    }\n}\n\nint bindVertexToJoint(Output& output, const Input& input)\n{\n    const int num_vertices = input.num_vertices;\n    const int num_samples  = input.num_samples;\n    const int num_indices  = output.num_indices;\n\n    std::vector<int> numJointVertices(output.num_joints, 0);\n    for (int v = 0; v < num_vertices; ++v) {\n        int bestJoint = 0;\n        double minErr = std::numeric_limits<double>::max();\n        const float3& restShapePos = input.restShape[v];\n        for (int j = 0; j < output.num_joints; ++j) {\n            double errsq = 0;\n            for (int s = 0; s < num_samples; ++s) {\n                float4x4 am = output.skinMatrix[s * input.num_joints + j].asMatrix();\n                float3 diff = input.sample[s * num_vertices + v] - restShapePos * am;\n                errsq += diff * diff;\n            }\n            errsq *= (input.restShape[v] - output.restJointPos[j]).length();\n            if (errsq < minErr) {\n                bestJoint = j;\n                minErr = errsq;\n            }\n        }\n        ++numJointVertices[bestJoint];\n        output.skinIndex[v * num_indices + 0] = bestJoint;\n    }\n\n    std::vector<int>::iterator smallestBoneSize = std::min_element(numJointVertices.begin(), numJointVertices.end());\n    while (*smallestBoneSize <= 0) {\n        const int smallestBone = static_cast<int>(smallestBoneSize - numJointVertices.begin());\n        numJointVertices.erase(numJointVertices.begin() + smallestBone);\n        output.restJointPos.erase(output.restJointPos.begin() + smallestBone);\n        for (int s = 0; s < input.num_samples; ++s) {\n            for (int j = output.num_joints - 2; j >= smallestBone; --j) {\n                output.skinMatrix[s * input.num_joints + j] = output.skinMatrix[s * input.num_joints + j + 1];\n            }\n        }\n        for (int v = 0; v < num_vertices; ++v) {\n            if (output.skinIndex[v * num_indices + 0] >= smallestBone) {\n                --output.skinIndex[v * num_indices + 0];\n            }\n        }\n        --output.num_joints;\n        smallestBoneSize = std::min_element(numJointVertices.begin(), numJointVertices.end());\n    }\n    return static_cast<int>(numJointVertices.size());\n}\n\nint findMostStableVertex(const Input& input)\n{\n    const int num_vertices = input.num_vertices;\n    const int num_samples = input.num_samples;\n    double minErrorSq = std::numeric_limits<double>::max();\n    int mostStableVertex = -1;\n    for (int v = 0; v < num_vertices; ++v) {\n        double errSq = 0;\n        for (int s = 0; s < num_samples; ++s) {\n            float3 diff = input.sample[s * num_vertices + v] - input.restShape[v];\n            errSq += diff * diff;\n        }\n        if (errSq < minErrorSq) {\n            minErrorSq = errSq;\n            mostStableVertex = v;\n        }\n    }\n    return mostStableVertex;\n}\n\nint findDistantVertex(const Input& input, const Output& output, const std::set<int>& covered)\n{\n    const int num_vertices = input.num_vertices;\n    const int num_samples  = input.num_samples;\n    const int num_indices  = output.num_indices;\n    double maxErrorSq      = -std::numeric_limits<double>::max();\n    int mostDistantVertex = -1;\n    for (int v = 0; v < num_vertices; ++v) {\n        if (covered.find(v) != covered.end()) {\n            continue;\n        }\n        int index = output.skinIndex[v * num_indices + 0];\n        double errSq = 0;\n        for (int s = 0; s < num_samples; ++s) {\n            float4x4 bm = output.skinMatrix[s * input.num_joints + index].asMatrix();\n            float3 diff = input.sample[s * num_vertices + v] - input.restShape[v] * bm;\n            errSq += diff * diff;\n        }\n        if (errSq > maxErrorSq) {\n            maxErrorSq = errSq;\n            mostDistantVertex = v;\n        }\n    }\n    return mostDistantVertex;\n}\n\n\n// solving p-center problem\nstatic void clusterVerticesPcenter(Output& output, const Input& input, int transformType)\n{\n    const int& num_indices = output.num_indices;\n\n    output.num_joints = input.num_joints;\n    std::fill(output.skinIndex.begin(), output.skinIndex.end(), -1);\n    std::fill(output.skinWeight.begin(), output.skinWeight.end(), 0.0);\n    std::fill(output.skinMatrix.begin(), output.skinMatrix.end(), float4x4::identity);\n    std::fill(output.restJointPos.begin(), output.restJointPos.end(), float3::origin);\n\n    char buf[512];\n    int stable_vertex = findMostStableVertex(input);\n    output.weights[stable_vertex * num_indices] = { 0, 1.0f };\n    output.restJointPos[0] = input.restShape[stable_vertex];\n    std::vector<int> joint_vertices(output.num_joints);\n    joint_vertices[0] = stable_vertex;\n    sprintf(buf, \"Added to Vertex %d (stable)\", stable_vertex);\n\n    for (int jid = 1; jid < input.num_joints; ++jid) {\n        double max_dist = -1.0;\n        int distant_vertex = -1;\n        for (int i = 0; i < input.num_vertices; ++i) {\n            if (std::find(joint_vertices.begin(), joint_vertices.end(), i) != joint_vertices.end()) {\n                continue;\n            }\n            double mindist = std::numeric_limits<double>::max();\n            for (int j = 0; j < jid; ++j) {\n                const int joint = joint_vertices[j];\n                float3 v = input.restShape[i] - input.restShape[joint];\n                if (mindist > v.length()) {\n                    mindist = v.length();\n                }\n            }\n            if (mindist > max_dist)\n            {\n                max_dist = mindist;\n                distant_vertex = i;\n            }\n        }\n        output.restJointPos[jid] = input.restShape[distant_vertex];\n        joint_vertices[jid] = distant_vertex;\n        sprintf(buf, \"Added to Vertex %d, %f\", distant_vertex, max_dist);\n    }\n\n    for (int i = 0; i < input.num_vertices; ++i) {\n        double min_dist = std::numeric_limits<double>::max();\n        int nearest_joint = -1;\n        for (int j = 0; j < output.num_joints; ++j) {\n            const int joint = joint_vertices[j];\n            float3 v = input.restShape[i] - input.restShape[joint];\n            if (v.length() < min_dist) {\n                min_dist = v.length();\n                nearest_joint = j;\n            }\n        }\n        output.skinIndex[i * num_indices] = nearest_joint;\n        output.skinWeight[i * num_indices] = 1.0;\n    }\n    detectNeighborClusters(input, output);\n    updateJointTransformProc(output, transformType, input);\n}\n\nstatic void clusterVerticesAdaptive(Output& output, const Input& input, int transformType)\n{\n    const int& num_indices = output.num_indices;\n\n    output.num_joints = 0;\n    std::fill(output.skinIndex.begin(), output.skinIndex.end(), -1);\n    std::fill(output.skinWeight.begin(), output.skinWeight.end(), 0.0);\n    std::fill(output.skinMatrix.begin(), output.skinMatrix.end(), float4x4::identity);\n    output.restJointPos.clear();\n\n    std::set<int> covered;\n    char buf[512];\n\n    int stable_vertex = findMostStableVertex(input);\n    output.skinIndex[stable_vertex * num_indices] = 0;\n    output.skinWeight[stable_vertex * num_indices] = 1.0;\n    output.restJointPos.push_back(input.restShape[stable_vertex]);\n    covered.insert(stable_vertex);\n    sprintf(buf, \"Added to Vertex %d (stable)\", stable_vertex);\n\n    for (int i = 0; i < input.neighbor[stable_vertex].size(); ++i) {\n        int neighbor = input.neighbor[stable_vertex][i].first;\n        if (neighbor < 0) {\n            continue;\n        }\n        output.skinIndex[neighbor * num_indices] = 0;\n        output.skinWeight[neighbor * num_indices] = 1.0;\n        covered.insert(neighbor);\n    }\n    updateJointTransformProc(output, transformType, input, 0);\n    for (int v = 0; v < input.num_vertices; ++v) {\n        output.skinIndex[v * num_indices] = 0;\n        output.skinWeight[v * num_indices] = 1.0;\n    }\n    output.num_joints = 1;\n\n    for (int iteration = 0; iteration < input.num_joints + 10; ++iteration) {\n        if (output.num_joints >= input.num_joints || covered.size() >= input.num_vertices) {\n            break;\n        }\n        int distant_vertex = findDistantVertex(input, output, covered);\n        output.skinIndex[distant_vertex * num_indices] = output.num_joints;\n        output.restJointPos.push_back(input.restShape[distant_vertex]);\n        covered.insert(distant_vertex);\n        for (int i = 0; i < input.neighbor[distant_vertex].size(); ++i) {\n            int neighbor = input.neighbor[distant_vertex][i].first;\n            if (neighbor < 0) {\n                continue;\n            }\n            output.skinIndex[neighbor * num_indices] = output.num_joints;\n            covered.insert(neighbor);\n        }\n        updateJointTransformProc(output, transformType, input, output.num_joints);\n        ++output.num_joints;\n        output.num_joints = bindVertexToJoint(output, input);\n\n        sprintf(buf, \"Added to Vertex %d\", distant_vertex);\n    }\n    detectNeighborClusters(input, output);\n}\n\nstatic void initialize(Output& output, Input& input)\n{\n    PyArrayObject* initPos = reinterpret_cast<PyArrayObject*>(PyTuple_GET_ITEM(args, 0));\n    PyArrayObject* shapeSample = reinterpret_cast<PyArrayObject*>(PyTuple_GET_ITEM(args, 1));\n    PyArrayObject* neighborVertices = reinterpret_cast<PyArrayObject*>(PyTuple_GET_ITEM(args, 2));\n    const long numJoints = PyInt_AsLong(PyTuple_GET_ITEM(args, 3));\n    const long numIndices = PyInt_AsLong(PyTuple_GET_ITEM(args, 4));\n    const long numRings = PyInt_AsLong(PyTuple_GET_ITEM(args, 5));\n    const long numVertices = static_cast<long>(initPos->dimensions[0]);\n    const long numSamples = static_cast<long>(shapeSample->dimensions[0]);\n    // allocation\n    input.numVertices = numVertices;\n    input.numSamples = numSamples;\n    input.numJoints = numJoints;\n    input.numRings = numRings;\n    input.rest_shape.points.resize(numVertices);\n    input.sample.resize(numSamples);\n    input.neighbor.resize(numVertices);\n\n    output.joints.resize(numJoints);\n    for (auto& jd : output.joints) {\n        jd.weights.resize(numVertices);\n        jd.matrix.resize(numSamples);\n    }\n\n    output.skinMatrix = std::vector<MTransformationMatrix>(numSamples * numJoints, MTransformationMatrix::identity);\n    output.restJointPos = std::vector<MPoint>(numJoints);\n    output.vertCluster = std::vector<std::vector<int>>(numVertices);\n\n    // size normalization\n    MVector centroid(0, 0, 0);\n    MVector minPos(1.0e10, 1.0e10, 1.0e10), maxPos(-1.0e10, -1.0e10, -1.0e10);\n    for (int v = 0; v < numVertices; ++v) {\n        MVector p(GET_DOUBLE2(initPos, v, 0),\n            GET_DOUBLE2(initPos, v, 1),\n            GET_DOUBLE2(initPos, v, 2));\n        input->restShape[v] = p;\n        centroid += p;\n        for (int i = 0; i < 3; ++i) {\n            minPos[i] = std::min(minPos[i], p[i]);\n            maxPos[i] = std::max(maxPos[i], p[i]);\n        }\n    }\n    centroid /= numVertices;\n    double scale = std::max(std::max(maxPos.x - minPos.x, maxPos.y - minPos.y), maxPos.z - minPos.z);\n    MMatrix m = MMatrix::identity;\n    m(0, 0) = m(1, 1) = m(2, 2) = 1.0 / scale;\n    m(3, 0) = -centroid.x / scale;\n    m(3, 1) = -centroid.y / scale;\n    m(3, 2) = -centroid.z / scale;\n    input->normalizer = m;\n    // normalized samples\n    for (int v = 0; v < numVertices; ++v) {\n        input->restShape[v] = input->restShape[v] * input->normalizer;\n        for (int s = 0; s < numSamples; ++s) {\n            MPoint p(GET_DOUBLE3(shapeSample, s, v, 0),\n                GET_DOUBLE3(shapeSample, s, v, 1),\n                GET_DOUBLE3(shapeSample, s, v, 2));\n            input->sample[s * numVertices + v] = p * input->normalizer;\n        }\n    }\n\n    // one-ring neighbor [Le and Deng 2014]\n    for (int v = 0; v < numVertices; ++v) {\n        double lv = 0.0;\n        for (int i = 0; i < neighborVertices->dimensions[1]; ++i) {\n            long n = GET_LONG2(neighborVertices, v, i);\n            if (n < 0) {\n                continue;\n            }\n            double len = (input->restShape[v] - input->restShape[n]).length();\n            if (len > 0) {\n                // [Le and Deng 2014]\n                double dsqsum = 0;\n                for (int s = 0; s < input->numSamples; ++s) {\n                    float diff = (input->restShape[v] - input->restShape[n]).length()\n                        - (input->sample[s * numVertices + v] - input->sample[s * numVertices + n]).length();\n                    dsqsum += diff * diff;\n                }\n                dsqsum += 1.0e-10;\n                double dvn = 1.0 / std::sqrt(dsqsum / input->numSamples);\n                input->neighbor[v].push_back(std::make_pair(n, dvn));\n                lv += dvn;\n            }\n        }\n        for (int n = 0; n < input->neighbor[v].size(); ++n) {\n            input->neighbor[v][n].second /= -lv;\n        }\n    }\n}\n#endif\n\n} // namespace ssds\n", "meta": {"hexsha": "37ff14e32eb11af9a27f5ed8d5e86b42a5e06eec", "size": 24097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libSSDS/src/libSSDS/libSSDS.cpp", "max_stars_repo_name": "i-saint/WebAlembicViewer", "max_stars_repo_head_hexsha": "258bc4657d6d37bef6e5ee8c9dc2cdcf0e5d3128", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T11:19:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T10:07:39.000Z", "max_issues_repo_path": "src/libSSDS/src/libSSDS/libSSDS.cpp", "max_issues_repo_name": "i-saint/WebAlembicViewer", "max_issues_repo_head_hexsha": "258bc4657d6d37bef6e5ee8c9dc2cdcf0e5d3128", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libSSDS/src/libSSDS/libSSDS.cpp", "max_forks_repo_name": "i-saint/WebAlembicViewer", "max_forks_repo_head_hexsha": "258bc4657d6d37bef6e5ee8c9dc2cdcf0e5d3128", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T19:59:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T19:59:07.000Z", "avg_line_length": 38.4322169059, "max_line_length": 188, "alphanum_fraction": 0.5649250944, "num_tokens": 6590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6380230270221299}}
{"text": "\n#include <mex.h>\n#include <igl/C_STR.h>\n#include <igl/matlab/mexErrMsgTxt.h>\n#undef assert\n#define assert( isOK ) ( (isOK) ? (void)0 : (void) mexErrMsgTxt(C_STR(__FILE__<<\":\"<<__LINE__<<\": failed assertion `\"<<#isOK<<\"'\"<<std::endl) ) )\n\n#include <igl/matlab/MexStream.h>\n#include <igl/matlab/parse_rhs.h>\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/validate_arg.h>\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n// From libshell by Etienne Vouga\ndouble angle(const Eigen::Vector3d &v, const Eigen::Vector3d &w, const Eigen::Vector3d &axis,\n    Eigen::Matrix<double, 1, 6> *derivative, // v, w\n    Eigen::Matrix<double, 6, 6> *hessian\n)\n{\n  const auto crossMatrix = [](Eigen::Vector3d v)->Eigen::Matrix3d \n  {\n      Eigen::Matrix3d ret;\n      ret << 0, -v(2), v(1),\n          v(2), 0, -v(0),\n          -v(1), v(0), 0;\n      return ret;\n  };\n\n  // This is a bad idea, if v and w are colinear, this derivatives below still\n  // make sense but this will make axis 0 and nuke everything.\n  //// This is unnecessary if the caller would promise that axis is unit and\n  //// orthogonal to v and w\n  const Eigen::Vector3d vcrossw = v.cross(w);\n  //const Eigen::Vector3d axis = ((vcrossw.dot(in_axis)>0?1:-1) * vcrossw).eval().normalized();\n  //std::cout<<\"in: \"<<in_axis.transpose()<<std::endl;\n  //std::cout<<\"vcrossw: \"<<vcrossw.transpose()<<std::endl;\n  //std::cout<<\"ef: \"<<axis.transpose()<<std::endl;\n\n    double theta = 2.0 * atan2((vcrossw.dot(axis)), v.dot(w) + v.norm() * w.norm());\n\n    if (derivative)\n    {\n        derivative->segment(0, 3) = -axis.cross(v) / v.squaredNorm();\n        derivative->segment(3, 3) = axis.cross(w) / w.squaredNorm();\n    }\n    if (hessian)\n    {\n        hessian->setZero();\n        hessian->block(0, 0, 3, 3) += 2.0 * (axis.cross(v))*v.transpose() / v.squaredNorm() / v.squaredNorm();\n        hessian->block(3, 3, 3, 3) += -2.0 * (axis.cross(w))*w.transpose() / w.squaredNorm() / w.squaredNorm();\n        hessian->block(0, 0, 3, 3) += -crossMatrix(axis) / v.squaredNorm();\n        hessian->block(3, 3, 3, 3) += crossMatrix(axis) / w.squaredNorm();\n\n        double sigma = 1.0;\n        if (v.cross(w).dot(axis) < 0)\n            sigma = -1.0;\n\n        double vwnorm = v.cross(w).norm();\n        if (vwnorm > 1e-8)\n        {\n            Eigen::Matrix3d da = sigma * (1.0 / vwnorm * Eigen::Matrix3d::Identity() - 1.0 / vwnorm / vwnorm / vwnorm * (v.cross(w)) * (v.cross(w)).transpose());\n            hessian->block(0, 0, 3, 3) += crossMatrix(v) / v.squaredNorm() * da * -crossMatrix(w);\n            hessian->block(3, 0, 3, 3) += crossMatrix(v) / v.squaredNorm() * da * crossMatrix(v);\n            hessian->block(0, 3, 3, 3) += -crossMatrix(w) / w.squaredNorm() * da * -crossMatrix(w);\n            hessian->block(3, 3, 3, 3) += -crossMatrix(w) / w.squaredNorm() * da * crossMatrix(v);\n        }\n    }\n\n    return theta;\n}\n \nvoid mexFunction(\n         int          nlhs,\n         mxArray      *plhs[],\n         int          nrhs,\n         const mxArray *prhs[]\n         )\n{\n  //mexPrintf(\"Compiled at %s on %s\\n\",__TIME__,__DATE__);\n  using namespace igl;\n  using namespace igl::matlab;\n  using namespace Eigen;\n  igl::matlab::MexStream mout;        \n  std::streambuf *outbuf = std::cout.rdbuf(&mout);\n\n  Eigen::MatrixXd V,W,A;\n  mexErrMsgTxt(nrhs>=2,\"nrhs should be == 2\");\n  parse_rhs_double(prhs+0,V);\n  parse_rhs_double(prhs+1,W);\n  mexErrMsgTxt(V.cols()==W.cols(),\"dims should be the same\");\n  mexErrMsgTxt(V.rows()==W.rows(),\"dims should be the same\");\n  const int n = V.rows();\n  const int dim = V.cols();\n  if(dim == 3)\n  {\n    mexErrMsgTxt(nrhs>=3,\"nrhs should be == 3\");\n    parse_rhs_double(prhs+2,A);\n  }else if(dim == 2)\n  {\n    V.conservativeResize(V.rows(),3);\n    W.conservativeResize(W.rows(),3);\n    V.col(2).setZero();\n    W.col(2).setZero();\n    A.resize(n,3);\n    A.col(0).setConstant(0);\n    A.col(1).setConstant(0);\n    A.col(2).setConstant(1);\n  }\n  Eigen::MatrixXd theta(n,1);\n  Eigen::MatrixXd dthetadV(n,dim);\n  Eigen::MatrixXd dthetadW(n,dim);\n  Eigen::MatrixXd d2thetadV2(n,dim==2?3:6);\n  Eigen::MatrixXd d2thetadW2(n,dim==2?3:6);\n  Eigen::MatrixXd d2thetadVW(n,dim==2?3:6);\n  const Eigen::MatrixXi voigt2 = \n    (Eigen::MatrixXi(3,2)<<0,0,1,1,0,1).finished();\n  const Eigen::MatrixXi voigt = (dim==2? voigt2 :\n    (Eigen::MatrixXi(6,2)<<0,0,1,1,2,2,1,2,0,2,0,1).finished());\n  for(int i = 0;i<n;i++)\n  {\n    Eigen::Matrix<double, 1, 6> derivative;\n    Eigen::Matrix<double, 6, 6> hessian;\n    theta(i) = angle(\n        V.row(i).transpose(),W.row(i).transpose(),A.row(i).transpose(),\n        &derivative,&hessian);\n    dthetadV.row(i) = derivative.segment(0,dim);\n    dthetadW.row(i) = derivative.segment(3,dim);\n    for(int b = 0;b<voigt2.rows();b++)\n    {\n      const int bi = voigt2(b,0);\n      const int bj = voigt2(b,1);\n      const auto & block = hessian.block(bi*3,bj*3,dim,dim);\n      for(int v = 0;v<voigt.rows();v++)\n      {\n        const int vi = voigt(v,0);\n        const int vj = voigt(v,1);\n        const double h = block(vi,vj);\n        switch(b)\n        {\n          case 0: d2thetadV2(i,v) = h; break;\n          case 1: d2thetadW2(i,v) = h; break;\n          case 2: d2thetadVW(i,v) = h; break;\n        }\n      }\n    }\n  }\n\n  switch(nlhs)\n  {\n    case 6:\n      prepare_lhs_double(d2thetadVW,plhs+5);\n    case 5:\n      prepare_lhs_double(d2thetadW2,plhs+4);\n    case 4:\n      prepare_lhs_double(d2thetadV2,plhs+3);\n    case 3:\n      prepare_lhs_double(dthetadW,plhs+2);\n    case 2:\n      prepare_lhs_double(dthetadV,plhs+1);\n    case 1:\n      prepare_lhs_double(theta,plhs+0);\n    default:break;\n  }\n\n\n  // Restore the std stream buffer Important!\n  std::cout.rdbuf(outbuf);\n  return;\n}\n", "meta": {"hexsha": "8b8c7518f9ff8fc60ec464a82b6627263d5b0961", "size": 5734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gplottoolbox/mex/angle_derivatives.cpp", "max_stars_repo_name": "karlic-luka/Spectral-clustering", "max_stars_repo_head_hexsha": "711042281c9fbedea1f12be822c9f55b629cc854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gplottoolbox/mex/angle_derivatives.cpp", "max_issues_repo_name": "karlic-luka/Spectral-clustering", "max_issues_repo_head_hexsha": "711042281c9fbedea1f12be822c9f55b629cc854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gplottoolbox/mex/angle_derivatives.cpp", "max_forks_repo_name": "karlic-luka/Spectral-clustering", "max_forks_repo_head_hexsha": "711042281c9fbedea1f12be822c9f55b629cc854", "max_forks_repo_licenses": ["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.7657142857, "max_line_length": 161, "alphanum_fraction": 0.5865015696, "num_tokens": 1941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6379307477010026}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008-2012 Gael Guennebaud <gael.guennebaud@inria.fr>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"main.h\"\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\ntemplate<typename Scalar> void check_all_var(const Matrix<Scalar,3,1>& ea)\n{\n  typedef Matrix<Scalar,3,3> Matrix3;\n  typedef Matrix<Scalar,3,1> Vector3;\n  typedef AngleAxis<Scalar> AngleAxisx;\n  using std::abs;\n  \n  #define VERIFY_EULER(I,J,K, X,Y,Z) { \\\n    Matrix3 m(AngleAxisx(ea[0], Vector3::Unit##X()) * AngleAxisx(ea[1], Vector3::Unit##Y()) * AngleAxisx(ea[2], Vector3::Unit##Z())); \\\n    Vector3 eabis = m.eulerAngles(I,J,K); \\\n    Matrix3 mbis(AngleAxisx(eabis[0], Vector3::Unit##X()) * AngleAxisx(eabis[1], Vector3::Unit##Y()) * AngleAxisx(eabis[2], Vector3::Unit##Z())); \\\n    VERIFY_IS_APPROX(m,  mbis); \\\n    /* If I==K, and ea[1]==0, then there no unique solution. */ \\\n    /* The remark apply in the case where I!=K, and |ea[1]| is close to pi/2. */ \\\n    if( (I!=K || ea[1]!=0) && (I==K || !internal::isApprox(abs(ea[1]),Scalar(M_PI/2),test_precision<Scalar>())) ) VERIFY((ea-eabis).norm() <= test_precision<Scalar>()); \\\n  }\n  VERIFY_EULER(0,1,2, X,Y,Z);\n  VERIFY_EULER(0,1,0, X,Y,X);\n  VERIFY_EULER(0,2,1, X,Z,Y);\n  VERIFY_EULER(0,2,0, X,Z,X);\n\n  VERIFY_EULER(1,2,0, Y,Z,X);\n  VERIFY_EULER(1,2,1, Y,Z,Y);\n  VERIFY_EULER(1,0,2, Y,X,Z);\n  VERIFY_EULER(1,0,1, Y,X,Y);\n\n  VERIFY_EULER(2,0,1, Z,X,Y);\n  VERIFY_EULER(2,0,2, Z,X,Z);\n  VERIFY_EULER(2,1,0, Z,Y,X);\n  VERIFY_EULER(2,1,2, Z,Y,Z);\n}\n\ntemplate<typename Scalar> void eulerangles()\n{\n  typedef Matrix<Scalar,3,3> Matrix3;\n  typedef Matrix<Scalar,3,1> Vector3;\n  typedef Array<Scalar,3,1> Array3;\n  typedef Quaternion<Scalar> Quaternionx;\n  typedef AngleAxis<Scalar> AngleAxisx;\n\n  Scalar a = internal::random<Scalar>(-Scalar(M_PI), Scalar(M_PI));\n  Quaternionx q1;\n  q1 = AngleAxisx(a, Vector3::Random().normalized());\n  Matrix3 m;\n  m = q1;\n  \n  Vector3 ea = m.eulerAngles(0,1,2);\n  check_all_var(ea);\n  ea = m.eulerAngles(0,1,0);\n  check_all_var(ea);\n  \n  ea = (Array3::Random() + Array3(1,1,0))*Scalar(M_PI)*Array3(0.5,0.5,1);\n  check_all_var(ea);\n  \n  ea[2] = ea[0] = internal::random<Scalar>(0,Scalar(M_PI));\n  check_all_var(ea);\n  \n  ea[0] = ea[1] = internal::random<Scalar>(0,Scalar(M_PI));\n  check_all_var(ea);\n  \n  ea[1] = 0;\n  check_all_var(ea);\n  \n  ea.head(2).setZero();\n  check_all_var(ea);\n  \n  ea.setZero();\n  check_all_var(ea);\n}\n\nvoid test_geo_eulerangles()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( eulerangles<float>() );\n    CALL_SUBTEST_2( eulerangles<double>() );\n  }\n}\n", "meta": {"hexsha": "5445cd81a9e7d46fbbdf5fb73a10d07eea7d6aa4", "size": 2832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Externals/eigen/test/geo_eulerangles.cpp", "max_stars_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_stars_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-10-23T17:11:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T12:48:39.000Z", "max_issues_repo_path": "src/Externals/eigen/test/geo_eulerangles.cpp", "max_issues_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_issues_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-06-08T19:55:40.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-08T19:55:40.000Z", "max_forks_repo_path": "src/Externals/eigen/test/geo_eulerangles.cpp", "max_forks_repo_name": "benjaminlarson/SCIRunGUIPrototype", "max_forks_repo_head_hexsha": "ed34ee11cda114e3761bd222a71a9f397517914d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-10T10:39:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T10:39:55.000Z", "avg_line_length": 30.7826086957, "max_line_length": 170, "alphanum_fraction": 0.6475988701, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6379307340746876}}
{"text": "\n// BLAS level 3 -- complex numbers\n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/atlas/cblas3.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#ifdef F_USE_STD_VECTOR\n#include <vector>\n#include <boost/numeric/bindings/traits/std_vector.hpp> \n#endif \n#include \"utils.h\" \n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::cout;\nusing std::endl; \n\ntypedef double real_t;\ntypedef std::complex<real_t> cmplx_t; \n\n#ifndef F_USE_STD_VECTOR\ntypedef ublas::matrix<cmplx_t, ublas::row_major> m_t;\n#else\ntypedef ublas::matrix<cmplx_t, ublas::column_major, std::vector<cmplx_t> > m_t;\n#endif \n\nint main() {\n\n  cout << endl; \n\n  m_t a (2, 2);\n  a (0, 0) = cmplx_t (1., 0.);\n  a (0, 1) = cmplx_t (2., 0.);\n  a (1, 0) = cmplx_t (3., 0.);\n  a (1, 1) = cmplx_t (4., 0.);\n  print_m (a, \"A\"); \n  cout << endl; \n\n  m_t b (2, 3);\n  b (0, 0) = cmplx_t (1., 0.);\n  b (0, 1) = cmplx_t (2., 0.);\n  b (0, 2) = cmplx_t (3., 0.);\n  b (1, 0) = cmplx_t (1., 0.);\n  b (1, 1) = cmplx_t (2., 0.);\n  b (1, 2) = cmplx_t (3., 0.);\n  print_m (b, \"B\"); \n  cout << endl; \n  \n  m_t c (2, 3);\n\n  // c = a b\n  atlas::gemm (a, b, c); \n  print_m (c, \"A B\"); \n  cout << endl; \n\n  a (0, 0) = cmplx_t (0., 1.);\n  a (0, 1) = cmplx_t (0., 2.);\n  a (1, 0) = cmplx_t (0., 3.);\n  a (1, 1) = cmplx_t (0., 4.);\n  print_m (a, \"A\"); \n  cout << endl; \n  \n  // c = a b\n  atlas::gemm (CblasNoTrans, CblasNoTrans, 1.0, a, b, 0.0, c); \n  print_m (c, \"A B\"); \n  cout << endl; \n\n  // c = a^T b\n  atlas::gemm (CblasTrans, CblasNoTrans, 1.0, a, b, 0.0, c); \n  print_m (c, \"A^T B\"); \n  cout << endl; \n\n  // c = a^H b\n  atlas::gemm (CblasConjTrans, CblasNoTrans, 1.0, a, b, 0.0, c); \n  print_m (c, \"A^H B\"); \n\n  cout << endl; \n\n}\n", "meta": {"hexsha": "86f4acf5be98df97c048cf1ac0f7243a839f25e1", "size": 1858, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_cmatr3.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_cmatr3.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_cmatr3.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 21.8588235294, "max_line_length": 79, "alphanum_fraction": 0.5785791173, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6379307296579104}}
{"text": "#include \"model-magick/MeshStatsCalculator.h\"\n\n#include <cmath>\n\n#include <Eigen/Geometry>\n\nnamespace ModelMagick\n{\n\nusing namespace std;\nusing namespace oneapi::tbb;\nusing namespace oneapi::tbb::flow;\n\nEigen::VectorXf calculateSolidAnglesForPlanarTriangles(\n    const Mesh& mesh,\n    const Eigen::RowVector3f& queryPoint)\n{\n    // https://igl.ethz.ch/projects/winding-number/robust-inside-outside-segmentation-using-generalized-winding-numbers-siggraph-2013-jacobson-et-al.pdf\n    // Eq. 6.\n\n    Eigen::VectorXf solidAngles;\n    const int m = mesh.numFaces();\n    solidAngles.resize(m);\n    parallel_for(\n        blocked_range<size_t>(0, m),\n        [&solidAngles, &mesh, &queryPoint](const blocked_range<size_t>& r) {\n            for (size_t i = r.begin(); i != r.end(); ++i) {\n                // triangle points in 3x3 matrix\n                //       [a1, a2, a3]\n                // abc = [b1, b2, b3]\n                //       [c1, c2, c3]\n                const Eigen::Matrix3f abc\n                    = mesh.vertices(mesh.indices(i, Eigen::all), Eigen::all).rowwise() - queryPoint;\n                // row norms in column vector\n                const Eigen::Vector3f normAbc = abc.rowwise().norm();\n                const float d0 = normAbc.prod();\n                const float d1 = abc.row(0).dot(abc.row(1)) * normAbc(2);\n                const float d2 = abc.row(1).dot(abc.row(2)) * normAbc(0);\n                const float d3 = abc.row(0).dot(abc.row(2)) * normAbc(1);\n                solidAngles(i) = 2 * std::atan2(abc.determinant(), d0 + d1 + d2 + d3);\n            }\n        });\n    return solidAngles;\n}\n\nEigen::VectorXf calculateGeneralizedWindingNumber(\n    const Mesh& mesh,\n    const Eigen::MatrixX3f& queryPoints)\n{\n    Eigen::VectorXf windingNumbers;\n    const int numQuery = queryPoints.rows();\n    windingNumbers.resize(numQuery, 1);\n    parallel_for(\n        blocked_range<size_t>(0, numQuery),\n        [&windingNumbers, &mesh, &queryPoints](const blocked_range<size_t>& r) {\n            for (size_t i = r.begin(); i != r.end(); ++i) {\n                windingNumbers(i)\n                    = 0.25 * M_1_PI\n                      * calculateSolidAnglesForPlanarTriangles(mesh, queryPoints.row(i)).sum();\n            }\n        });\n    return windingNumbers;\n}\n\n// oneapi::tbb::flow::function_node<Mesh, Eigen::MatrixX3f, Eigen::VectorXf>\n// createGeneralizedWindingNumberCalculator(\n//     oneapi::tbb::flow::graph& graph,\n//     std::size_t concurrency = oneapi::tbb::flow::unlimited);\n\n}  // namespace ModelMagick\n", "meta": {"hexsha": "782adb3d09dbd53b9a5cea0edec193a6cc542ad1", "size": 2530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/model-magick/GeneralizedWindingNumberCalculator.cpp", "max_stars_repo_name": "balintfodor/model-magick", "max_stars_repo_head_hexsha": "dac07b94739c741942487fcad4e19b7f2aca5529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/model-magick/GeneralizedWindingNumberCalculator.cpp", "max_issues_repo_name": "balintfodor/model-magick", "max_issues_repo_head_hexsha": "dac07b94739c741942487fcad4e19b7f2aca5529", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T15:47:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T15:54:42.000Z", "max_forks_repo_path": "src/model-magick/GeneralizedWindingNumberCalculator.cpp", "max_forks_repo_name": "balintfodor/model-magick", "max_forks_repo_head_hexsha": "dac07b94739c741942487fcad4e19b7f2aca5529", "max_forks_repo_licenses": ["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.6338028169, "max_line_length": 152, "alphanum_fraction": 0.5940711462, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6378781278053796}}
{"text": "// TODO: Change from BOOST to LEMON\n#define BOOST_TEST_MODULE sub_graph_iso_test\n\n#include <boost/test/included/unit_test.hpp> // Testing\n\n#include <boost/graph/adjacency_list.hpp> // Boost Graph\n#include <boost/graph/graphviz.hpp>\n\n#include \"sub_graph_iso/sub_graph_iso.hpp\" // Modified Boost sub_graph_iso file\n\n#include \"lib/complete_graph.hpp\" // Helper to create complete graphs.\n\nusing namespace boost;\n\nBOOST_AUTO_TEST_SUITE( test_sub_graph_induced )\n\nBOOST_AUTO_TEST_CASE( small_sub_graph_finds_iso )\n{\n\n\ttypedef adjacency_list< setS, vecS, undirectedS > graph_type;\n\n\t// Build graph\n\tint num_vertices1 = 8;\n\tgraph_type sub(num_vertices1);\n\tadd_edge(0, 6, sub);\n\tadd_edge(0, 7, sub);\n\tadd_edge(1, 5, sub);\n\tadd_edge(1, 7, sub);\n\tadd_edge(2, 4, sub);\n\tadd_edge(2, 5, sub);\n\tadd_edge(2, 6, sub);\n\tadd_edge(3, 4, sub);\n\n\t// Build sub\n\tint num_vertices2 = 9;\n\tgraph_type graph(num_vertices2);\n\tadd_edge(0, 6, graph);\n\tadd_edge(0, 8, graph);\n\tadd_edge(1, 5, graph);\n\tadd_edge(1, 7, graph);\n\tadd_edge(2, 4, graph);\n\tadd_edge(2, 7, graph);\n\tadd_edge(2, 8, graph);\n\tadd_edge(3, 4, graph);\n\tadd_edge(3, 5, graph);\n\tadd_edge(3, 6, graph);\n\n\t// Create callback to print mappings\n\tvf2_empty_callback < graph_type, graph_type > callback(sub, graph);\n\n\t// Print out all subgraph isomorphism mappings between graph and sub.\n\t// Vertices and edges are assumed to be always equivalent.\n\tconst bool result = vf2_subgraph_mono(sub, graph, callback);\n\n\tBOOST_TEST(result);\n\n}\n\n// Test complete graph K4 embedding in K7.\nBOOST_AUTO_TEST_CASE( K4_K7_finds_iso )\n{\n\n\ttypedef adjacency_list< setS, vecS, undirectedS > graph_type;\n\n\tgraph_type graph_K7 = complete_undirected(7);\n\t\n\tgraph_type graph_K4 = complete_undirected(4);\n\n\tvf2_empty_callback < graph_type, graph_type > callback(graph_K4, graph_K7);\n\n\tconst bool result = vf2_subgraph_mono(graph_K4, graph_K7, callback);\n\n\tBOOST_TEST(result);\n\n}\n\n// Test medium-sized embedding of K6 into K9.\nBOOST_AUTO_TEST_CASE ( K6_K9_finds_iso ) \n{\n\n\ttypedef adjacency_list< setS, vecS, undirectedS > graph_type;\n\n\tgraph_type graph_K9 = complete_undirected(9);\n\tgraph_type graph_K6 = complete_undirected(6);\n\n\tvf2_empty_callback < graph_type, graph_type > callback(graph_K6, graph_K9);\n\n\tconst bool result = vf2_subgraph_mono(graph_K6, graph_K9, callback);\n\n\tBOOST_TEST(result);\n}\n\n// Test no embedding of K4 into complete bipartite graph KB3,4.\nBOOST_AUTO_TEST_CASE ( K4_bipartite_no_iso )\n{\n\n\ttypedef adjacency_list< setS, vecS, undirectedS > graph_type;\n\n\tgraph_type graph_KB3c4(7);\n\tfor (int i = 0; i <= 3; i++) {\n\t\tfor (int j = 4; j <= 7; j++) {\n\t\t\tadd_edge(i, j, graph_KB3c4);\n\t\t}\n\t}\n\t\n\tgraph_type graph_K4 = complete_undirected(4);\n\n\tvf2_empty_callback < graph_type, graph_type > callback(graph_K4, graph_KB3c4);\n\n\tconst bool result = vf2_subgraph_mono(graph_K4, graph_KB3c4, callback);\n\n\tBOOST_TEST(result == false);\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\nBOOST_AUTO_TEST_SUITE( test_sub_graph_non_induced )\n\n// Test sqaure embeds in K4.\nBOOST_AUTO_TEST_CASE( square_K4_finds_iso )\n{\n\t\n\ttypedef adjacency_list< setS, vecS, undirectedS > graph_type;\n\n\tgraph_type graph_square(4);\n\tadd_edge(0, 1, graph_square);\n\tadd_edge(1, 2, graph_square);\n\tadd_edge(2, 3, graph_square);\n\tadd_edge(3, 0, graph_square);\n\n\tgraph_type graph_K4 = complete_undirected(4);\n\n\tvf2_empty_callback < graph_type, graph_type > callback(graph_square, graph_K4);\n\n\tconst bool result = vf2_subgraph_mono(graph_square, graph_K4, callback);\n\n\tBOOST_TEST(result);\n\n}\n\n\n// Test almost complete graph K4 embedding in K7.\nBOOST_AUTO_TEST_CASE( almost_K4_K7_finds_iso )\n{\n\n\ttypedef adjacency_list< setS, vecS, undirectedS > graph_type;\n\n\tgraph_type graph_K7 = complete_undirected(7);\n\t\n\tgraph_type graph_almost_K4 = complete_undirected(4);\n\tremove_edge(0, 1, graph_almost_K4);\n\n\t// Create callback to print mappings\n\tvf2_empty_callback < graph_type, graph_type > callback(graph_almost_K4, graph_K7);\n\n\t// Find subgraph isomorphism mappings between K7 and K4.\n\t// Vertices and edges are assumed to be always equivalent.\n\tconst bool result = vf2_subgraph_mono(graph_almost_K4, graph_K7, callback);\n\n\tBOOST_TEST(result);\n\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c05baaa8849c301341e68be08c366caa82054ecd", "size": 4143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_old.cpp", "max_stars_repo_name": "DamianJLin/QubitAllocator", "max_stars_repo_head_hexsha": "9dc32b988c5d8e865fbe5644caf7e933da18ba38", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_old.cpp", "max_issues_repo_name": "DamianJLin/QubitAllocator", "max_issues_repo_head_hexsha": "9dc32b988c5d8e865fbe5644caf7e933da18ba38", "max_issues_repo_licenses": ["BSL-1.0"], "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_old.cpp", "max_forks_repo_name": "DamianJLin/QubitAllocator", "max_forks_repo_head_hexsha": "9dc32b988c5d8e865fbe5644caf7e933da18ba38", "max_forks_repo_licenses": ["BSL-1.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.6607142857, "max_line_length": 83, "alphanum_fraction": 0.7523533671, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.637878123309147}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nTEST(ProbDistributionBinomiali, error_check) {\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::binomial_rng(4, 0.6, rng));\n  EXPECT_THROW(stan::math::binomial_rng(-4, 0.6, rng),std::domain_error);\n  EXPECT_THROW(stan::math::binomial_rng(4,-0.6, rng),std::domain_error);\n  EXPECT_THROW(stan::math::binomial_rng(4, 2.6, rng),std::domain_error);\n  EXPECT_THROW(stan::math::binomial_rng(4,stan::math::positive_infinity(), rng),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsBinomial, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::binomial_distribution<>dist (100, 0.6);\n  boost::math::chi_squared mydist(K-1);\n\n  int loc[K - 1];\n  for(int i = 1; i < K; i++)\n    loc[i - 1] = i - 1;\n\n  int count = 0;\n  int bin [K];\n  double expect [K];\n  for(int i = 0 ; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N * pdf(dist, i);\n  }\n  expect[K-1] = N * (1 - cdf(dist, K-2));\n\n  while (count < N) {\n    int a = stan::math::binomial_rng(100, 0.6, rng);\n    int i = 0;\n    while (i < K-1 && a > loc[i]) \n      ++i;\n    ++bin[i];\n    count++;\n   }\n\n  double chi = 0;\n\n  for(int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\n", "meta": {"hexsha": "606a8ddd2305c8708a3170e25c71e42b3fa5ec1b", "size": 1477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/prob/binomial_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/prob/binomial_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/prob/binomial_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8679245283, "max_line_length": 80, "alphanum_fraction": 0.6086662153, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6378781063029189}}
{"text": "#include <cstring>\n#include <iostream>\n#include <fstream>\n#include <armadillo>\n\n#include \"lap3d.h\"\n#include \"shiftengine3d.h\"\n\nusing namespace arma;\n\nfloat CG_PSNR3D(CubeType Base_image, CubeType Recon_image);\n\nint main(int argc, char *argv[])\n{\n\tstd::string firstImagePath;\n\tstd::string secondImagePath;\n\tstd::string resultImagePath;\n\n\tSizeType rows;\n\tSizeType cols;\n\tSizeType slices;\n\n\tColType i1_v;\n\tColType i2_v;\n\n\tif (argc < 2) {\n\t\tstd::cerr << \"Usage: \" << std::endl;\n\t\tstd::cerr << std::endl;\n\t\tstd::cerr << \"  \" << argv[0] << \" <path-to-image1> <path-to-image2> <path-to-result-image> <image-rows> <image-columns> <image-slices>\" << std::endl;\n\t\tstd::cerr << \"  \" << argv[0] << \" <pointer-to-image1> <pointer-to-image2> <pointer-to-result-image>, <image-rows> <image-columns> <image-slices>\" << std::endl;\n\t\tstd::cerr << std::endl;\n\t\tstd::cerr << \"Run '\" << argv[0] << \" --help' for more information\" << std::endl;\n\t\tstd::cerr << std::endl;\n\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t// Output help string and exit (otherwise segmentation fault!)\n\tif (strcmp(argv[1], \"--help\") == 0) {\n\t\tstd::cout << \"There are no more information implemented yet.\" << std::endl;\n\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tfirstImagePath = argv[1];\n\tsecondImagePath = argv[2];\n\tresultImagePath = argv[3];\n\n\trows = strtol(argv[4], NULL, 10);\n\tcols = strtol(argv[5], NULL, 10);\n\tslices = strtol(argv[6], NULL, 10);\n\n\t//Load iamges (saved as raw ascii)\n\ti1_v.load(firstImagePath, raw_binary);\n\ti2_v.load(secondImagePath, raw_binary);\n\n\t//Shape them to 3D pictures with correct dimensions\n\tCubeType i1(i1_v.memptr(), rows, cols, slices);\n\tCubeType i2(i2_v.memptr(), rows, cols, slices);\n\n\ti1.subcube(span(0,3),span(0,3),span(0,3)).print(\"i1\");\n\n\t//Construct two 3D Images\n\t//Construct the LocalAllpass Algorithm Object with Level min and max\n\tGadgetron::LAP3D mLAP3D(i1, i2, 0, 4);\n\n\tfield<CubeType> flow_estimation = mLAP3D.exec();\n\n\t//Shift first image according to estimated optical flow\n\tGadgetron::ShiftEngine3D shifter(i1, flow_estimation(0), flow_estimation(1), flow_estimation(2));\n\tCubeType i_hat_fast = shifter.execCubicShift();\n\t//Save result image\n\tCol<PixelType> i_hat_fast_v = vectorise(i_hat_fast);\n\ti_hat_fast_v.save(resultImagePath, raw_ascii);\n\n\tstd::cout << \"PSNR_uB_Fast: \" << CG_PSNR3D(i2, i_hat_fast) << std::endl;\n\n\treturn EXIT_SUCCESS;\n}\n\nfloat CG_PSNR3D(CubeType Base_image, CubeType Recon_image)\n{\n\tint m = Recon_image.n_rows;\n\tint n = Recon_image.n_cols;\n\tint p = Recon_image.n_slices;\n\n\tfloat Max_I = arma::max(arma::abs(vectorise(Base_image)));\n\n\tfloat MSE = accu(arma::pow(arma::abs(Base_image-Recon_image),2)) / (n*m*p);\n\n\tfloat PSNR = 10 * std::log10(std::pow(Max_I, 2) / MSE);\n\n\treturn PSNR;\n}\n", "meta": {"hexsha": "16799de6974a70a6707702872f83fe7f5f393a24", "size": 2687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reconstruction/gadgetron/CS_LAB_Gadget/src/LAP_GADGET/main.cpp", "max_stars_repo_name": "noonelikechu/Shearlet", "max_stars_repo_head_hexsha": "532d86368303523c450b6a7b38c7822a8ddee701", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 83.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T09:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T03:08:00.000Z", "max_issues_repo_path": "reconstruction/gadgetron/CS_LAB_Gadget/src/LAP_GADGET/main.cpp", "max_issues_repo_name": "noonelikechu/Shearlet", "max_issues_repo_head_hexsha": "532d86368303523c450b6a7b38c7822a8ddee701", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-09-19T23:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T11:25:18.000Z", "max_forks_repo_path": "reconstruction/gadgetron/CS_LAB_Gadget/src/LAP_GADGET/main.cpp", "max_forks_repo_name": "noonelikechu/Shearlet", "max_forks_repo_head_hexsha": "532d86368303523c450b6a7b38c7822a8ddee701", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T18:41:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-25T08:25:44.000Z", "avg_line_length": 28.2842105263, "max_line_length": 161, "alphanum_fraction": 0.6907331597, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6378069899784498}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EVecPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\n#include \"smooth/feedback/compat/ipopt.hpp\"\n#include \"smooth/feedback/ocp.hpp\"\n\ntemplate<typename T>\nusing Vec = Eigen::VectorX<T>;\n\n/// @brief Objective function\nconst auto theta = []<typename T>(T, const Vec<T> &, const Vec<T> &, const Vec<T> & q) -> T {\n  return q.x();\n};\n\n/// @brief Dynamics\nconst auto f = []<typename T>(T, const Vec<T> & x, const Vec<T> & u) -> Vec<T> {\n  return Vec<T>{{x.y(), u.x()}};\n};\n\n/// @brief Integrals\nconst auto g = []<typename T>(T, const Vec<T> & x, const Vec<T> & u) -> Vec<T> {\n  return Vec<T>{{x.squaredNorm() + u.squaredNorm()}};\n};\n\n/// @brief Running constraints\nconst auto cr = []<typename T>(T, const Vec<T> &, const Vec<T> & u) -> Vec<T> {\n  return Vec<T>{{u.x()}};\n};\n\n/// @brief End constraints\nconst auto ce =\n  []<typename T>(T tf, const Vec<T> & x0, const Vec<T> & xf, const Vec<T> &) -> Vec<T> {\n  Vec<T> ret(5);\n  ret << tf, x0, xf;\n  return ret;\n};\n\n/// @brief Range to std::vector\nconst auto r2v = []<std::ranges::range R>(const R & r) {\n  return std::vector(std::ranges::begin(r), std::ranges::end(r));\n};\n\nTEST(OcpIpopt, Solve)\n{\n  // define optimal control problem\n  smooth::feedback::FlatOCP<decltype(theta), decltype(f), decltype(g), decltype(cr), decltype(ce)>\n    ocp{\n      .nx    = 2,\n      .nu    = 1,\n      .nq    = 1,\n      .ncr   = 1,\n      .nce   = 5,\n      .theta = theta,\n      .f     = f,\n      .g     = g,\n      .cr    = cr,\n      .crl   = Vec<double>{{-1}},\n      .cru   = Vec<double>{{1}},\n      .ce    = ce,\n      .cel   = Vec<double>{{3, 1, 1, 0, 0}},\n      .ceu   = Vec<double>{{6, 1, 1, 0, 0}},\n    };\n\n  // define mesh\n  smooth::feedback::Mesh mesh;\n  mesh.refine_ph(0, 4 * 5);\n  const auto [nodes, weights] = mesh.all_nodes_and_weights();\n\n  // transcribe optimal control problem to nonlinear programming problem\n  const auto nlp = smooth::feedback::ocp_to_nlp(ocp, mesh);\n\n  // solve nonlinear programming problem\n  const auto nlp_sol = smooth::feedback::solve_nlp_ipopt(\n    nlp,\n    std::nullopt,\n    {\n      {\"print_level\", 0},\n    },\n    {\n      {\"linear_solver\", \"mumps\"},\n      {\"hessian_approximation\", \"limited-memory\"},\n    },\n    {\n      {\"tol\", 1e-8},\n    });\n\n  ASSERT_EQ(nlp_sol.status, smooth::feedback::NLPSolution::Status::Optimal);\n\n  // convert solution of nlp insto solution of ocp\n  const auto ocp_sol = smooth::feedback::nlpsol_to_ocpsol(ocp, mesh, nlp_sol);\n\n  const auto nlp_sol_copy = smooth::feedback::ocpsol_to_nlpsol(ocp, mesh, ocp_sol);\n\n  ASSERT_LE((nlp_sol_copy.x - nlp_sol.x).norm(), 1e-8);\n  ASSERT_LE((nlp_sol_copy.zl - nlp_sol.zl).norm(), 1e-8);\n  ASSERT_LE((nlp_sol_copy.zu - nlp_sol.zu).norm(), 1e-8);\n  ASSERT_LE((nlp_sol_copy.lambda - nlp_sol.lambda).norm(), 1e-8);\n\n  // solve again with warmstart\n  const auto nlp_sol_warm = smooth::feedback::solve_nlp_ipopt(\n    nlp,\n    nlp_sol_copy,\n    {\n      {\"print_level\", 0},\n    },\n    {\n      {\"linear_solver\", \"mumps\"},\n      {\"hessian_approximation\", \"limited-memory\"},\n    },\n    {\n      {\"tol\", 1e-8},\n    });\n\n  ASSERT_LE(nlp_sol_warm.iter, 6);\n}\n", "meta": {"hexsha": "6a68861fab43a673b8dd3c431d1daeba3428e6ca", "size": 4355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_ocp_ipopt.cpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "tests/test_ocp_ipopt.cpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "tests/test_ocp_ipopt.cpp", "max_forks_repo_name": "pettni/smooth_feedback", "max_forks_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 30.6690140845, "max_line_length": 98, "alphanum_fraction": 0.6399540758, "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6378069899784496}}
{"text": "/*\n   Copyright (C) 2015-2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n// Free energy, energy, and specific heat of triangular lattice Ising model\n\n// reference: R. M. F. Houtappel, Physica 16, 425 (1950)\n\n#pragma once\n\n#include <cmath>\n#include <stdexcept>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/differentiation/autodiff.hpp>\n#include <standards/simpson.hpp>\n#include \"common.hpp\"\n\nnamespace ising {\nnamespace free_energy {\nnamespace triangular {\n\nnamespace {\n\ntemplate<typename T, typename FVAR>\nstruct functor {\n  functor(T Ja, T Jb, T Jc, FVAR beta) {\n    using std::cosh; using std::sinh;\n    T pi = boost::math::constants::pi<T>();\n    c_ = 1 / (8 * pi * pi);\n    sh2a_ = sinh(2 * beta * Ja);\n    sh2b_ = sinh(2 * beta * Jb);\n    sh2c_ = sinh(2 * beta * Jc);\n    cshabc_ = cosh(2 * beta * Ja) * cosh(2 * beta * Jb) * cosh(2 * beta * Jc)\n      + sh2a_ * sh2b_ * sh2c_;\n  }\n  FVAR operator()(T t1, T t2) const {\n    using std::cos; using std::log;\n    return c_ * log(cshabc_ - sh2a_ * cos(t1) - sh2b_ * cos(t2) - sh2c_ * cos(t1 + t2));\n  }\n  T c_;\n  FVAR sh2a_, sh2b_, sh2c_, cshabc_;\n};\n\ntemplate<typename T, typename FVAR>\nfunctor<T, FVAR> func(T Ja, T Jb, T Jc, FVAR beta) {\n  return functor<T, FVAR>(Ja, Jb, Jc, beta);\n}\n\n}\n\ntemplate<typename T, typename U>\ninline U infinite(T Ja, T Jb, T Jc, U beta) {\n  const unsigned long max_n = 1 << 16;\n  typedef T real_t;\n  if (Ja * Jb * Jc <= 0)\n    throw(std::invalid_argument(\"Ja * Jb * Jc should be positive\"));\n  if (beta <= 0)\n    throw(std::invalid_argument(\"beta should be positive\"));\n  real_t pi = boost::math::constants::pi<real_t>();\n  auto logZ = log(real_t(2)) +\n    standards::simpson_2d(func(Ja, Jb, Jc, beta), real_t(0), real_t(0), 2*pi, 2*pi, 8, 8);\n  auto pz = logZ;\n  auto pe = abs(beta * beta * logZ.derivative(2) / logZ);\n  for (unsigned long n = 16; n <= max_n; n *= 2) {\n    logZ = log(real_t(2)) +\n      standards::simpson_2d(func(Ja, Jb, Jc, beta), real_t(0), real_t(0), 2*pi, 2*pi, n, n);\n    auto pn = abs(beta * beta * (logZ - pz).derivative(2) / logZ);\n    if (pn < 2 * std::numeric_limits<real_t>::epsilon() || pn > pe) break;\n    if (n == max_n) std::cerr << \"Warning: integration not converge with n = \" << max_n << std::endl;\n    pz = logZ;\n    pe = pn;\n  }\n  return - logZ / beta;\n}\n\n} // end namespace triangular\n} // end namespace free_energy\n} // end namespace ising\n", "meta": {"hexsha": "999e17a9219e983ce5cedca4750ba302f5efe8de", "size": 2942, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ising/free_energy/triangular.hpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "ising/free_energy/triangular.hpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "ising/free_energy/triangular.hpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3296703297, "max_line_length": 101, "alphanum_fraction": 0.6464989803, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6377370390823823}}
{"text": "// Statistical Computing //\r\n\r\n// Load typical packages\r\n#include<cmath>\r\n#include<iostream>\r\n#include<iomanip>\r\n\r\n// Typiccal C libraries\r\n#include<cmath>\r\n#include<cstdlib>\r\n\r\n// C++ Data Structures\r\n#include<set>\r\n#include<map>\r\n\r\n// Include Eigen Package for Matrices\r\n#include <Eigen/Core>\r\n\r\n// To calculate Time\r\n#include<ctime>\r\n\r\n// Load Matrix615 header file to read in from file\r\n#include \"Matrix615.h\"\r\n\r\nusing namespace std;\r\n// we avoid using namespace Eigen to be able to clearly see where we are calling the Eigen Package\r\n\r\n// Driver Code\r\nint main(int argc, char* argv[]) {\r\n\r\n\t// Steps corresponding to the commented code is associated with the following documents:\r\n\t\r\n\t// Tentative Read Matrix using Matrix615.h\r\n\t\r\n\tMatrix615<double> read_Design; // throw-away Matrices to read in data\r\n\tMatrix615<double> read_Y;\r\n\tMatrix615<double> read_ID;\r\n\r\n\t// Read the data in\r\n\tread_Design.readFromFile(argv[3]); // t\r\n\tread_Y.readFromFile(argv[2]);\r\n\tread_ID.readFromFile(argv[1]);\r\n\r\n\t// Step (1): Store the design matrix, response, and Id into an Eigen Matrix\r\n\tEigen::MatrixXd\tdesign_X;\r\n\tEigen::MatrixXd outcome_Y;\r\n\r\n\tread_Design.cloneToEigen(design_X);\r\n\tread_Y.cloneToEigen(outcome_Y);\r\n\r\n\t// cout << Weights.rows() << endl << endl;\r\n\t// cout << Weights << endl;\r\n\tEigen::MatrixXd Weights(outcome_Y.rows(), 1);\r\n\t// Weights.setOnes();\r\n\r\n\t// cout << \"argc is \" << argc << endl;\r\n\r\n\tif (int (argc) == 5) {\r\n\t\tMatrix615<double> read_Weights;\r\n\t\tread_Weights.readFromFile(argv[4]);\r\n\r\n\t\tEigen::MatrixXd Weights;\r\n\t\tread_Weights.cloneToEigen(Weights);\r\n\t}\r\n\r\n\telse {\r\n\t\tWeights.setOnes();\r\n\t}\r\n\r\n\r\n\t// Step (2): Count number of unique ID's, patients\r\n\tEigen::MatrixXd ID_Mat;\r\n\tread_ID.cloneToEigen(ID_Mat);\r\n\r\n\tstd::set<int> unique_ID; // to dynamically count n\r\n\tstd::map<int, int> m_map; // to dynamically count m\r\n\tstd::map<int, double> weight_map;\r\n\r\n\tfor (int i = 0; i < int(ID_Mat.rows()); ++i) {\r\n\t\tunique_ID.insert(  ID_Mat(i,0) );\r\n\t\tm_map[ID_Mat(i, 0)] += 1;\r\n\t\tweight_map[ID_Mat(i, 0)] = Weights(i, 0); \r\n\t}\r\n\r\n\t// int n = int( unique_ID.size() );\r\n\t\r\n\t// cout << \"n is << \" << n << endl;\r\n\r\n\t// cout << \"size of the id to m map is \" << m_map.size() << endl;\r\n\r\n\t// cout << \"m of 1st patient is \" << m_map[1] << \" \" << m_map[100] << \" \" << m_map[2] << endl << endl;\r\n\t// cout << \"size of weight map \" << weight_map.size() << endl;\r\n\r\n\t// q = (p + 1) : # number of paramters to be estimated using GEE\r\n\tint q = int ( design_X.cols() );\r\n\r\n\t// cout << \"q is \" << q << endl;\r\n\r\n\t// Correlation Structure\r\n\r\n\t// Step : Weights\r\n\r\n\t// Step (3): Initialize betas *********** Should we incorporate the beta's that come from a fast linear regression or no?\r\n\r\n\tEigen::MatrixXd Betas_new(q , 1); // dimensions (p+1)  x 1\r\n\tBetas_new.setZero();\r\n\r\n\t// cout << \"Betas ***********************\" << endl;\r\n\t// cout << Betas_new << endl << endl;\r\n\r\n\t// Step (4): Initialize rho and phi (rho: off diagonals of correlation structure & phi: )\r\n\tdouble rho = 0.0;\r\n\t// double phi = 0.0;\r\n\r\n\t// Step (5): Set up variables for iteration convergence check\r\n\r\n\t// Should we make this dynamic? \r\n\r\n\tdouble diff_beta = 1; // updated difference in beta estimation {beta (new) - beta (old)}\r\n\t\r\n\tdouble diff_threshold = 0.00000010; // threshold for the update difference in betas\r\n\t\r\n\tint iteration_threshold = 1000; // threshold on how many iterations there will be\r\n\r\n\t// Step (6): Initialize the iteration\r\n\tint iteration_count = 0;\r\n\r\n\t// Step (7): Assign appropriate value to n*\r\n\tdouble n_star_sum = 0.0;\r\n\tdouble m_sum = 0.0;\r\n\r\n\t// calculate n_star_sum\r\n\r\n\t// for (std::set<int>::iterator iter = unique_ID.begin(); iter != unique_ID.end(); ++iter) {\r\n\t// \tn_star_sum = n_star_sum + (0.5) * double(m_map[*iter]) * double(double(m_map[*iter]) - double(1.0));\r\n\t// }\r\n\r\n\t// Step (8): Start the GEE Estimation\r\n\r\n\tEigen::MatrixXd Betas_updated = Betas_new;\r\n\r\n\tEigen::MatrixXd sandwhich_Mat;\r\n\r\n\tEigen::MatrixXd tempGI(q, q);\r\n\r\n\t// // cout << Betas_updated << endl << endl;\r\n\r\n\tint before_EE = clock();\r\n\r\n\t// Step (10)\r\n\twhile ( (diff_beta > diff_threshold) && (iteration_count < iteration_threshold) ) {\r\n\t\t// (1)\r\n\t\tBetas_updated = Betas_new;\r\n\r\n\t\t// (2) Vector EE ((px1) x 1) or (q x 1)\r\n\t\tEigen::MatrixXd EE(q, 1);\r\n\t\tEE.setZero();\r\n\r\n\t\t// (3) Matrix GI (q x q)\r\n\t\tEigen::MatrixXd GI(q, q);\r\n\t\tGI.setZero();\r\n\r\n\t\t// // (4) Matrix G ( (p+1) x (p+1) )\r\n\t\t// // Meat of the Sandwhich Estimator\r\n\t\t// Eigen::MatrixXd G(q , q);\r\n\t\t// G.setZero();\r\n\r\n\t\t// (5) Initialize phi(sum) and tau(sum)\r\n\t\tlong double phi_sum = 0.0;\r\n\t\tlong double tau_sum = 0.0;\r\n\r\n\t\t// (6) Initialize indexes for block matrix multiplications\r\n\t\tint start = 0;\r\n\t\tint end = -1;\r\n\r\n\t\t// inner loop, we will loop using the unique_ID set (size = n)\r\n\t\t// Therefore, it loops n times\r\n\t\tfor (std::set<int>::iterator iter = unique_ID.begin(); iter != unique_ID.end(); ++iter) {\r\n\r\n\t\t\tint m = m_map[*iter];\r\n\t\t\tstart = end + 1;\r\n\t\t\tend = start + m - 1;\r\n\r\n\t\t\tn_star_sum = n_star_sum + (0.5) * double(m) * double(double(m) - 1.0);\r\n\t\t\tm_sum = m_sum + double(m);\r\n\r\n\t\t\t// cout << \"start is \" << start << endl;\r\n\t\t\t// cout << \"end is \" << end << endl << endl;\r\n\r\n\t\t\t// assign mu for ith observation\r\n\t\t\t// Eigen.block(starting_row = , starting_col = , dim_row = , dim_col = )\r\n\t\t\tEigen::MatrixXd mu_i = design_X.block(start, 0, m, q) * Betas_updated;\r\n\r\n\t\t\t// cout << \"mu_i is here \" << endl;\r\n\t\t\t// cout << mu_i << endl << endl;\r\n\r\n\t\t\t// assign r_i (mi x 1)\r\n\t\t\tEigen::MatrixXd r_i = outcome_Y.block(start, 0, m, 1) - mu_i;\r\n\r\n\t\t\t// cout << \"r_i is here \" << endl;\r\n\t\t\t// cout << r_i << endl;\r\n\r\n\t\t\t// add r_i ^2 to phi_sum from the ith observation\r\n\t\t\tfor (int j = 0; j < int(m); ++j) {\r\n\t\t\t\tphi_sum = phi_sum + (r_i(j,0) * r_i(j,0));\r\n\t\t\t}\r\n\r\n\t\t\t// cout << \"phi_sum is \" << phi_sum << endl; \r\n\r\n\t\t\t// add to tau_sum\r\n\t\t\tfor (int j = 0; j < ( int(m) - 1 ); ++j) {\r\n\t\t\t\tfor (int k = (j + 1); k < int(m); ++k) {\r\n\t\t\t\t\t// cout << \" j is \" << j << \" and k is \" << k << endl;\r\n\t\t\t\t\ttau_sum = tau_sum + (r_i(j,0) * r_i(k,0));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// cout << \"tau_sum is \" << tau_sum << endl;\r\n\r\n\t\t\t// create R matrix (mi x mi) for each observation\r\n\t\t\tEigen::MatrixXd R(m, m);\r\n\t\t\tR.setConstant(rho);\r\n\t\t\tfor (int d = 0; d < int(m); ++d) {\r\n\t\t\t\tR(d, d) = 1;\r\n\t\t\t}\r\n\r\n\t\t\t// cout << R << endl << endl << endl;\r\n\t\t\t// update EE ((p+1) x 1)\r\n\t\t\tEE = EE + ((design_X.block(start, 0, m, q).transpose()) * (R.inverse() * (r_i) )); // weight_map\r\n\r\n\t\t\t// update GI ((p+1) x (p+1)) or (q x q)\r\n\t\t\tGI = GI + ((design_X.block(start, 0, m, q).transpose()) * R.inverse() *  design_X.block(start, 0, m, q));\r\n\r\n\t\t\t// update G ((p+1) x (p+1)) or (q x q)\r\n\t\t\t// G = G + ((design_X.block(start, 0, m, q).transpose()) * ( ((R.inverse()) * r_i) * (r_i.transpose()*(R.inverse())) ) * design_X.block(start, 0, m, q));\r\n\r\n\t\t}\r\n\r\n\t\t// Update beta using Newton Raphson method\r\n\t\tBetas_new = Betas_updated + (GI.inverse() * EE);\r\n\r\n\t\t// calculate the difference in the betas\r\n\t\tdiff_beta = (Betas_new - Betas_updated).norm();\r\n\t\t// diff_beta = (Betas_new - Betas_updated).array().abs().sum();\r\n\r\n\t\t// update rho\r\n\t\t// cout << \"tau_sum is \" << tau_sum << endl;\r\n\t\t// cout << \"phi_sum is \" << phi_sum << endl;\r\n\r\n\t\trho = ( (( double(m_sum) - double(q) ) * tau_sum) / ( (double(n_star_sum) - double(q) ) * phi_sum) );\r\n\r\n\t\t// cout << \"rho is \" << rho << endl << endl;\r\n\r\n\t\t// sandwhich_Mat = GI.inverse() * G * GI.inverse();\r\n\t\ttempGI = GI;\r\n\r\n\t\titeration_count += 1;\r\n\r\n\t}\r\n\r\n\t// (4) Matrix G ( (p+1) x (p+1) )\r\n\t// Meat of the Sandwhich Estimator\r\n\tEigen::MatrixXd G(q , q);\r\n\tG.setZero();\r\n\r\n\t// To calculate the sandwhich estimator\r\n\t// for (std::set<int>::iterator iter = unique_ID.begin(); iter != unique_ID.end(); ++iter) {\r\n\t// \tn_star_sum = n_star_sum + (0.5) * double(m_map[*iter]) * double(double(m_map[*iter]) - double(1.0));\r\n\t// }\r\n\r\n\tint start = 0;\r\n\tint end = -1;\r\n\r\n\tfor (std::set<int>::iterator iter = unique_ID.begin(); iter != unique_ID.end(); ++iter) {\r\n\t\tint m = m_map[*iter];\r\n\t\tstart = end + 1;\r\n\t\tend = start + m - 1;\r\n\r\n\t\tEigen::MatrixXd mu_i = design_X.block(start, 0, m, q) * Betas_updated;\r\n\r\n\t\t// cout << \"mu_i is here \" << endl;\r\n\t\t// cout << mu_i << endl << endl;\r\n\r\n\t\t// assign r_i (mi x 1)\r\n\t\tEigen::MatrixXd r_i = outcome_Y.block(start, 0, m, 1) - mu_i;\r\n\r\n\t\tEigen::MatrixXd R(m, m);\r\n\r\n\t\tR.setConstant(rho);\r\n\r\n\t\tfor (int d = 0; d < int(m); ++d) {\r\n\t\t\tR(d, d) = 1;\r\n\t\t}\r\n\r\n\t\t// update G ((p+1) x (p+1)) or (q x q)\r\n\t\tG = G + ((design_X.block(start, 0, m, q).transpose()) * ( ((R.inverse()) * r_i) * (r_i.transpose()*(R.inverse())) ) * design_X.block(start, 0, m, q));\r\n\t}\r\n\r\n\tsandwhich_Mat = tempGI.inverse() * G * tempGI.inverse();\r\n\r\n\tint after_EE = clock();\r\n\r\n\r\n\t// cout << \" n start sum ended up being \" << n_star_sum << endl;\r\n\t// cout << \"m sum ended up being \" << m_sum << endl;\r\n\tcout << \"**************** GEE Results ****************\" << endl;\r\n\tcout << endl << endl << \"Iteration count at: \" << iteration_count << endl;\r\n\r\n\tcout << \"The correlation parameter: \" << rho << endl;\r\n\r\n\tcout << endl << \"Estimated Betas are: \" << endl;\r\n\tcout << Betas_new.transpose() << endl << endl << endl;\r\n\r\n\t// cout << \"The sandwhich matrix is: \" << endl << endl;\r\n\t// cout << sandwhich_Mat << endl << endl;\r\n\r\n\tcout << \"The beta Robust S.E.'s are: \" << endl << endl;\r\n\tcout << sandwhich_Mat.diagonal().array().sqrt() << endl << endl;\r\n\r\n\tcout << \" Estimated convergence time for EE is: \" << endl;\r\n\tcout << \" Time (secs): \" << (after_EE - before_EE) / double(CLOCKS_PER_SEC) << endl;\r\n\t\r\n\treturn 0;\r\n\r\n}", "meta": {"hexsha": "212421ce4ac3a9597046e2d9ae0806f57c69da96", "size": 9472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gee/geec_twoloop.cpp", "max_stars_repo_name": "hengshiyu/geeCpp", "max_stars_repo_head_hexsha": "bdcc54dd7fc0c28e4d27326c52670f2c4b2e0ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gee/geec_twoloop.cpp", "max_issues_repo_name": "hengshiyu/geeCpp", "max_issues_repo_head_hexsha": "bdcc54dd7fc0c28e4d27326c52670f2c4b2e0ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gee/geec_twoloop.cpp", "max_forks_repo_name": "hengshiyu/geeCpp", "max_forks_repo_head_hexsha": "bdcc54dd7fc0c28e4d27326c52670f2c4b2e0ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1446153846, "max_line_length": 157, "alphanum_fraction": 0.5770692568, "num_tokens": 2921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6377370342300395}}
{"text": "#include \"pinocchio/spatial/fwd.hpp\"\r\n#include \"pinocchio/spatial/se3.hpp\"\r\n#include \"pinocchio/multibody/visitor.hpp\"\r\n#include \"pinocchio/multibody/model.hpp\"\r\n#include \"pinocchio/multibody/data.hpp\"\r\n#include \"pinocchio/algorithm/crba.hpp\"\r\n#include \"pinocchio/algorithm/centroidal.hpp\"\r\n#include \"pinocchio/algorithm/aba.hpp\"\r\n#include \"pinocchio/algorithm/rnea.hpp\"\r\n#include \"pinocchio/algorithm/cholesky.hpp\"\r\n#include \"pinocchio/algorithm/jacobian.hpp\"\r\n#include \"pinocchio/algorithm/center-of-mass.hpp\"\r\n#include \"pinocchio/algorithm/compute-all-terms.hpp\"\r\n#include \"pinocchio/algorithm/kinematics.hpp\"\r\n#include \"pinocchio/parsers/urdf.hpp\"\r\n#include \"pinocchio/parsers/sample-models.hpp\"\r\n\r\n#include <stdlib.h>\r\n#include <stdio.h>\r\n#include <unistd.h>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <sstream>\r\n\r\n#include \"csv_reader.h\"\r\n\r\n#define SMOOTH(s) for(size_t _smooth=0;_smooth<s;++_smooth)\r\n\r\n#define ERROR_RETURN(retval) { fprintf(stderr, \"Error %d %s:line %d: \\n\", retval,__FILE__,__LINE__);  exit(retval); }\r\n\r\n#define TRESHOLD (0.00001)\r\n\r\n#include <Eigen/StdVector>\r\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::VectorXd)\r\n\r\nint main() {\r\n\r\n  using namespace Eigen;\r\n  using namespace pinocchio;\r\n  \r\n  // Set robot model\r\n  bool floating_base;\r\n  std::string robot_model = ROBOT_MODEL;\r\n\r\n  if (robot_model == \"iiwa\")\r\n  {\r\n    std::cout << \"Robot Model = \" << robot_model << std::endl;\r\n    floating_base = false;\r\n  }\r\n  else if ((robot_model == \"hyq\")|(robot_model == \"atlas\"))\r\n  {\r\n    std::cout << \"Robot Model = \" << robot_model << std::endl;\r\n    floating_base = true;\r\n  }\r\n  else\r\n  {\r\n    std::cerr << \"Invalid robot model: \" << robot_model << \"\\nChoices are: iiwa, hyq, atlas\" << std::endl;\r\n    return 2;\r\n  }\r\n\r\n  // Import URDF model\r\n  Model model;\r\n  std::string urdf_filename;\r\n  urdf_filename = RBD_BENCHMARKS_DIR\"/description/urdf/\"+robot_model+\".urdf\";\r\n  if (floating_base)\r\n    pinocchio::urdf::buildModel(urdf_filename,JointModelFreeFlyer(),model);\r\n  else\r\n    pinocchio::urdf::buildModel(urdf_filename,model);\r\n  \r\n  model.gravity = Eigen::Vector3d(0, 0, 0);\r\n  Data data(model);\r\n  int dof = model.nv;\r\n  std::cout << \"dof = \" << dof << std::endl;\r\n\r\n  // Import CSV inputs\r\n  std::string input_filename;\r\n  input_filename = RBD_BENCHMARKS_DIR\"/csv/pinocchio/\"+robot_model+\"_inputs.csv\";\r\n  std::ifstream input_csv(input_filename.c_str());\r\n\r\n  CSVRow row;\r\n  VectorXd qs     = VectorXd::Zero(model.nq);\r\n  VectorXd qdots  = VectorXd::Zero(model.nv);\r\n  VectorXd qddots = VectorXd::Zero(model.nv);\r\n  VectorXd taus   = VectorXd::Zero(model.nv);\r\n\r\n  input_csv >> row;\r\n  int tot_q, tot_qdot; // FIXME: What vector sizes do I expect from each model?\r\n  tot_q    = model.nq;\r\n  tot_qdot = model.nv;\r\n  std::cout << \"qs, qdots = \" << tot_q << \", \" << tot_qdot << std::endl;\r\n  int col, start_col;\r\n  input_csv >> row;\r\n  start_col = 0.0;                 // 0\r\n  for(int j=0;j<tot_q;++j)\r\n  {\r\n    col = start_col+j;\r\n    qs[j] = atof(row[col].c_str());\r\n  }\r\n  //qs.segment<4>(3) /= qs.segment<4>(3).norm();\r\n  start_col = tot_q;               // 1xQ\r\n  for(int j=0;j<tot_qdot;++j)\r\n  {\r\n    col = start_col+j;\r\n    qdots[j] = atof(row[col].c_str());\r\n  }\r\n  start_col = tot_q+tot_qdot;      // 1xQ+1xQd\r\n  for(int j=0;j<tot_qdot;++j)\r\n  {\r\n    col = start_col+j;\r\n    qddots[j] = atof(row[col].c_str());\r\n  }\r\n  start_col = tot_q+2*tot_qdot;  // 1xQ+2xQd\r\n  for(int j=0;j<tot_qdot;++j)\r\n  {\r\n    col = start_col+j;\r\n    taus[j] = atof(row[col].c_str());\r\n  }\r\n\r\n\r\n  std::cout << \"--\" << std::endl;\r\n\r\n  // Dynamics Algorithms\r\n#ifdef RNEA_ALG\r\n  std::cout << \"RNEA\" << std::endl;\r\n  const VectorXd& returned_value = rnea(model,data,qs,qdots,qddots);\r\n  std::string nmcsv = \"_inverse_dynamics_expected.csv\";\r\n#elif  CRBA_ALG\r\n  std::cout << \"CRBA\" << std::endl;\r\n  const MatrixXd& returned_value = crba(model,data,qs);\r\n  std::string nmcsv = \"_mass_matrix_expected.csv\";\r\n#elif  ABA_ALG\r\n  std::cout << \"ABA\" << std::endl;\r\n  const VectorXd& returned_value = aba(model,data,qs,qdots, taus);\r\n  std::string nmcsv = \"_dynamics_expected.csv\";\r\n#endif /* Dynamics Algorithms */\r\n  std::cout << \"--\" << std::endl;\r\n\r\n  std::cout << \"TEST RESULTS\" << std::endl;\r\n\r\n  // Import CSV output\r\n  std::string output_filename = RBD_BENCHMARKS_DIR\"/csv/pinocchio/\"+robot_model+nmcsv;\r\n  std::ifstream output_csv(output_filename.c_str());\r\n  output_csv >> row;\r\n\r\n  bool flag_wrong = false;\r\n#ifdef RNEA_ALG\r\n  for(int j=0;j<tot_qdot;++j)\r\n  {\r\n    double result = returned_value[j];\r\n    double truth  = atof(row[j].c_str());\r\n#elif  CRBA_ALG\r\n  for(int j=0;j<tot_qdot * tot_qdot;++j)\r\n  {\r\n    if((j/tot_qdot) < (j%tot_qdot)) //Only the uper triangle of the matrix is computed\r\n      continue;\r\n\r\n    double result = returned_value(j);\r\n    double truth  = atof(row[j].c_str());\r\n#elif  ABA_ALG\r\n  for(int j=0;j<tot_qdot;++j)\r\n  {\r\n    double result = returned_value[j];\r\n    double truth  = atof(row[j].c_str());\r\n#endif \r\n\r\n    printf(\"%f == %f\\n\", result, truth);\r\n    double delta = fabs(truth - result);\r\n    printf(\"%f\\n\", delta);\r\n    if(delta > TRESHOLD)\r\n      flag_wrong=true;\r\n  }\r\n  if(flag_wrong){\r\n    std::cout << \"Wrong results!!!\" << std::endl;\r\n    return 1;\r\n  }\r\n  else\r\n    std::cout << \"All the results were good\" << std::endl;\r\n\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "ce34d5d33bf68c31f9f25e7d60b76b01dead8567", "size": 5314, "ext": "cc", "lang": "C++", "max_stars_repo_path": "testbenches/pinocchio/check_pinocchio/check_pinocchio.cc", "max_stars_repo_name": "CobbledSteel/rbd-benchmarks-riscv", "max_stars_repo_head_hexsha": "7bbc80252901cc2ac7845945db19b77c38d6a6f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-10-15T09:56:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T12:24:30.000Z", "max_issues_repo_path": "testbenches/pinocchio/check_pinocchio/check_pinocchio.cc", "max_issues_repo_name": "CobbledSteel/rbd-benchmarks-riscv", "max_issues_repo_head_hexsha": "7bbc80252901cc2ac7845945db19b77c38d6a6f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-02-01T19:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-01T19:15:16.000Z", "max_forks_repo_path": "testbenches/pinocchio/check_pinocchio/check_pinocchio.cc", "max_forks_repo_name": "CobbledSteel/rbd-benchmarks-riscv", "max_forks_repo_head_hexsha": "7bbc80252901cc2ac7845945db19b77c38d6a6f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-02T11:21:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T03:15:20.000Z", "avg_line_length": 29.1978021978, "max_line_length": 118, "alphanum_fraction": 0.634926609, "num_tokens": 1590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6377370315446981}}
{"text": "/*\n * Copyright Nick Thompson, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <iomanip>\n#include <iostream>\n#include <cmath>\n#include <boost/core/demangle.hpp>\n#include <boost/hana/for_each.hpp>\n#include <boost/hana/ext/std/integer_sequence.hpp>\n#include <boost/math/quadrature/wavelet_transforms.hpp>\n#include <boost/math/tools/minima.hpp>\n#include <boost/math/quadrature/trapezoidal.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\n\nusing boost::math::constants::pi;\nusing boost::math::constants::root_two;\nusing boost::math::quadrature::daubechies_wavelet_transform;\nusing boost::math::quadrature::trapezoidal;\n\ntemplate<typename Real, int p>\nvoid test_wavelet_transform()\n{\n    std::cout << \"Testing wavelet transform of \" << p << \" vanishing moment Daubechies wavelet on type \" << boost::core::demangle(typeid(Real).name()) << \"\\n\";\n    auto psi = boost::math::daubechies_wavelet<Real, p>();\n\n    auto abs_psi = [&psi](Real x) {\n        return abs(psi(x));\n    };\n    auto [a, b] = psi.support();\n    auto psil1 = trapezoidal(abs_psi, a, b, 100*std::numeric_limits<Real>::epsilon());\n    Real psi_sup_norm = 0;\n    for (double x = a; x < b; x += 0.00001)\n    {\n        Real y = psi(x);\n        if (std::abs(y) > psi_sup_norm)\n        {\n            psi_sup_norm = std::abs(y);\n        }\n    }\n    // An even function:\n    auto f = [](Real x) {\n        return std::exp(-abs(x));\n    };\n    Real fmax = 1;\n    Real fl2 = 1;\n    Real fl1 = 2;\n\n    auto Wf = daubechies_wavelet_transform(f, psi);\n    for (double s = 0; s < 10; s += 0.01)\n    {\n        Real w1 = Wf(s, 0.0);\n        Real w2 = Wf(-s, 0.0);\n        // Since f is an even function, we get w1 = w2:\n        CHECK_ULP_CLOSE(w1, w2, 12);\n    }\n\n    // The wavelet transform with respect to Daubechies wavelets \n    for (double s = -10; s < 10; s += 0.1)\n    {\n        for (double t = -10; t < 10; t+= 0.1)\n        {\n            Real w = Wf(s, t);\n            // Integral inequality:\n            Real r1 = sqrt(abs(s))*fmax*psil1;\n            if (!CHECK_LE(abs(w), r1))\n            {\n                std::cerr << \"  Integral inequality |W[f](s,t)| <= ||f||_infty ||psi||_1 is violated.\\n\";\n            }\n            if (!CHECK_LE(abs(w), fl2))\n            {\n                std::cerr << \"  Integral inequality | int f psi_s,t| <= ||f||_2 ||psi||_2 violated.\\n\";\n            }\n            Real r4 = sqrt(abs(s))*fl1*psi_sup_norm;\n            if (!CHECK_LE(abs(w), r4))\n            {\n                std::cerr << \"  Integral inequality |W[f](s,t)| <= sqrt(|s|)||f||_1 ||psi||_infty is violated.\\n\";\n            }\n            Real r5 = sqrt(abs(s))*fmax*psil1;\n            if (!CHECK_LE(abs(w), r5))\n            {\n                std::cerr << \"  Integral inequality |W[f](s,t)| <= sqrt(|s|)||f||_infty ||psi||_1 is violated.\\n\";\n            }\n            if (s != 0)\n            {\n                Real r2 = fl1*psi_sup_norm/sqrt(abs(s));\n                if(!CHECK_LE(abs(w), r2))\n                {\n                    std::cerr << \"  Integral inequality |W[f](s,t)| <= ||f||_1 ||psi||_infty/sqrt(|s|) is violated.\\n\";\n                }\n            }\n\n        }\n    }\n\n    if (p > 5)\n    {\n        // Wavelet transform of a constant is zero.\n        // The quadrature sum is horribly ill-conditioned (technically infinite),\n        // so we'll only test on the more rapidly converging sums.\n        auto g = [](Real ) { return Real(7); };\n        auto Wg = daubechies_wavelet_transform(g, psi);\n        for (double s = -10; s < 10; s += 0.1)\n        {\n            for (double t = -10; t < 10; t+= 0.1)\n            {\n                Real w = Wg(s, t);\n                if (!CHECK_LE(abs(w), 10*sqrt(std::numeric_limits<Real>::epsilon())))\n                {\n                    std::cerr << \"  Wavelet transform of constant with respect to \" << p << \" vanishing moment Daubechies wavelet is insufficiently small\\n\";\n                }\n\n            }\n        }\n        // Wavelet transform of psi evaluated at s = 1, t = 0 is L2 norm of psi:\n        auto Wpsi = daubechies_wavelet_transform(psi, psi);\n        CHECK_MOLLIFIED_CLOSE(Real(1), Wpsi(1,0), 2*sqrt(std::numeric_limits<Real>::epsilon()));\n    }\n\n}\n\nint main()\n{\n    try{\n       test_wavelet_transform<double, 2>();\n       test_wavelet_transform<double, 8>();\n       test_wavelet_transform<double, 16>();\n       // All these tests pass, but the compilation takes too long on CI:\n       //boost::hana::for_each(std::make_index_sequence<17>(), [&](auto i) {\n       //    test_wavelet_transform<double, i+3>();\n       //});\n    }\n    catch (std::bad_alloc const & e)\n    {\n        std::cerr << \"Ran out of memory in wavelet transform test: \" << e.what() << \"\\n\";\n       // not much we can do about this, this test uses lots of memory!\n    }\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "2d4a092cfdf8e5b0146e1ca3b40972a20059de2c", "size": 5101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/wavelet_transform_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/wavelet_transform_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/wavelet_transform_test.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 33.5592105263, "max_line_length": 159, "alphanum_fraction": 0.5479317781, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.637737031285528}}
{"text": "#pragma once\n\n#include <numeric>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\n#include <Eigen/Dense>\n\n\nnamespace pcv\n{\n\ntemplate<class NumericType>\ndouble getLineModelError(\n    const Eigen::Vector2d &model,\n    const Eigen::Matrix<NumericType, 2, 1> point)\n{\n    static_assert(std::is_arithmetic<NumericType>::value,\n                  \"Must have a numerical point type.\");\n\n    double yEstimate = (1.0 - model[0]*point.x())/model[1];\n\n    return std::pow(yEstimate-point.y(), 2);\n}\n\ntemplate<class NumericType>\nEigen::Vector2d\nfindLineModelFromPoints(\n    std::vector<Eigen::Matrix<NumericType, 2, 1>> points)\n{\n    static_assert(std::is_arithmetic<NumericType>::value,\n                  \"Must have a numerical point type.\");\n\n    if (points.size() < 2)\n    {\n        throw std::runtime_error(\"There must be at least the minimum number of \"\n                                 \"data points required by modeling function.\");\n    }\n\n    Eigen::Matrix<double, 2, 2> linearEquationsLhs;\n    linearEquationsLhs << points[0].x(), points[0].y(),\n                          points[1].x(), points[1].y();\n\n    Eigen::Vector2d linearEquationsRhs;\n    linearEquationsRhs << 1, 1;\n\n    Eigen::Vector2d model =\n        linearEquationsLhs.colPivHouseholderQr().solve(linearEquationsRhs);\n\n    return model;\n}\n\n} // end namespace pcv\n", "meta": {"hexsha": "35a6052243ca9bc555b5d40f2db54d8a043f0614", "size": 1332, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/Solvers/include/Solvers/Line.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/Line.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/Line.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": 24.2181818182, "max_line_length": 80, "alphanum_fraction": 0.6426426426, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6377370218400124}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearloadvector.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n\n#include <Eigen/Core>\n#include <functional>\n\nnamespace ElementMatrixComputation {\n\nnamespace {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector4d computeLoadVector(\n    const Eigen::MatrixXd &vertices,\n    std::function<double(const Eigen::Vector2d &)> f) {\n  // Number of nodes of the element: triangles = 3, rectangles = 4\n  const int num_nodes = vertices.cols();\n  // Vector for returning element vector\n  Eigen::Vector4d elem_vec = Eigen::Vector4d::Zero();\n  double area; \n  Eigen::Matrix midpoints(2, num_nodes); \n\n  //====================\n  // Your code goes here\n  // supply a builder type for the element vector \n  // arising from the linear form \n  // use the composite edge midpoint rule with the local definition \n  switch (num_nodes){\n    case 3:{\n      area = 0.5 *(vertices(0,1)-vertices(0,0))*((vertices(1,2)-vertices(1,0))-(vertices(1,1)-vertices(1,0))*(vertices(0,2)*vertices(0,0))); \n      midpoints << vertices(0,0)+vertices(0,1), \n      vertices(0,1)+vertices(0,1),\n      vertices(0,0)+vertices(0,2),\n      vertices(1,0)+vertices(1,1), \n      vertices(1,1)+vertices(1,2), \n      vertices(1,0)+vertices(1,2);\n\n\n    }\n  } case 4:{\n    area = (vertices(0,1)-vertices(0,0))*(vertices(1,3)-vertices(1,0)); \n    midpoints << vertices(0,0)+vertices(0,1), \n    vertices(0,1)+vertices(0,2), \n    vertices(0,2)+vertices(0,3), \n    vertices(0,3)+vertices(0,0), \n    vertices(1,0)+vertices(1,1), \n    vertices(1,1)+vertices(1,2), \n    vertices(1,2)+vertices(1,3), \n    vertices(1,3)+vertices(1,0), \n  }\n\n  Eigen::VectorXd fal(num_nodes); \n  for (int i =0; i < num_nodes; i++){\n    fal[i] = f(midpoints.col[i]); \n  }\n\n  for (int k=0; k<num_nodes; k++){\n    elem_vec[k] = 0.5*fal[k]; \n    elem_vec[(k+1)% num_nodes] = 0.5*fal[k]; \n  }\n  \n  elem_vec *= area/num_nodes; \n  \n  //====================\n\n  return elem_vec;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace\n\nEigen::Vector4d MyLinearLoadVector::Eval(const lf::mesh::Entity &cell) {\n  // Topological type of the cell\n  const lf::base::RefEl ref_el{cell.RefEl()};\n  const lf::base::size_type num_nodes{ref_el.NumNodes()};\n\n  // Obtain the vertex coordinates of the cell, which completely\n  // describe its shape.\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n\n  // Matrix storing corner coordinates in its columns\n  auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n\n  return computeLoadVector(vertices, f_);\n}\n\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "e3039d960fea76dc9ff7bc57ae59e423ccff7a36", "size": 2722, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7755102041, "max_line_length": 141, "alphanum_fraction": 0.6487876561, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6376885073699669}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/vcm_estimate_edges.h>\n#include <CGAL/property_map.h>\n#include <CGAL/IO/read_off_points.h>\n\n#include <utility> // defines std::pair\n#include <vector>\n#include <fstream>\n\n#include <boost/foreach.hpp>\n\n// Types\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::Point_3 Point;\ntypedef Kernel::Vector_3 Vector;\n\n// Point with normal vector stored in a std::pair.\ntypedef std::pair<Point, Vector> PointVectorPair;\ntypedef std::vector<PointVectorPair> PointList;\n\ntypedef CGAL::cpp11::array<double,6> Covariance;\n\nint main (int , char**) {\n    // Reads a .xyz point set file in points[].\n    std::list<PointVectorPair> points;\n    std::ifstream stream(\"data/fandisk.off\");\n    if (!stream ||\n        !CGAL::read_off_points(stream,\n                               std::back_inserter(points),\n                               CGAL::First_of_pair_property_map<PointVectorPair>()))\n    {\n        std::cerr << \"Error: cannot read file data/fandisk.off\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    // Estimates covariance matrices per points.\n    double R = 0.2,\n           r = 0.1;\n    std::vector<Covariance> cov;\n    CGAL::First_of_pair_property_map<PointVectorPair> point_pmap;\n\n    CGAL::compute_vcm(points.begin(), points.end(), point_pmap, cov, R, r, Kernel());\n\n    // Find the points on the edges.\n    // Note that this step is not expensive and can be done several time to get better results\n    double threshold = 0.16;\n    std::ofstream output(\"points_on_edges.xyz\");\n    int i = 0;\n    BOOST_FOREACH(const PointVectorPair& p, points)\n    {\n      if (CGAL::vcm_is_on_feature_edge(cov[i], threshold))\n          output << p.first << \"\\n\";\n      ++i;\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "afab79de1bd9795f1d10d60d214058d5ec3740ec", "size": 1791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Point_set_processing_3/edges_example.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Point_set_processing_3/edges_example.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Point_set_processing_3/edges_example.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 30.3559322034, "max_line_length": 94, "alphanum_fraction": 0.6661083194, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6376884998006745}}
{"text": "/*\n * Copyright 2015-2017 Guillermo Frontera <guillermo.frontera@upm.es>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include \"algorithms_2d.h\"\n\n#include <boost/geometry.hpp>\n\n#include <log/logger.h>\n#include <exc/exception.h>\n\n#include \"polygon_traits.h\"\n\nusing namespace ues::geom;\n\nconst std::string component_name = \"2D Geometric Algorithms\";\n\n\npoint<2> ues::geom::segment_intersection ( const point<2> & s1p1,\n                                           const point<2> & s1p2,\n                                           const point<2> & s2p1,\n                                           const point<2> & s2p2,\n                                           const ues::math::numeric_type & epsilon )\n{\n    point<2> result;\n    if ( check_segment_intersection ( s1p1, s1p2, s2p1, s2p2, result, epsilon ) )\n    {\n        return result;\n    }\n    else\n    {\n        std::ostringstream error;\n        error << \"No intersection found between segments ( \" << s1p1 << \", \" << s1p2 << \" ) and ( \" << s2p1 << \", \" << s2p2 << \" )\";\n        throw ues::exc::exception ( error.str(), UES_CONTEXT );\n    }\n}\n\n\nbool ues::geom::check_segment_intersection ( const point<2> & s1p1,\n                                             const point<2> & s1p2,\n                                             const point<2> & s2p1,\n                                             const point<2> & s2p2,\n                                             point<2> & result,\n                                             const ues::math::numeric_type & epsilon ) noexcept\n{\n    ues::log::logger lg;\n\n    const ues::math::numeric_type & x1 = s1p1.get_x(), & y1 = s1p1.get_y(),\n    & x2 = s1p2.get_x(), & y2 = s1p2.get_y(),\n    & x3 = s2p1.get_x(), & y3 = s2p1.get_y(),\n    & x4 = s2p2.get_x(), & y4 = s2p2.get_y();\n\n    ues::math::numeric_type denominator = ( x1 - x2 ) * ( y3 - y4 ) - ( y1 - y2 ) * ( x3 - x4 );\n\n    if ( denominator != 0 )\n    {\n        ues::math::numeric_type denominator_inv = 1 / denominator;\n        ues::math::numeric_type first_factor = ( x1 * y2 - y1 * x2 );\n        ues::math::numeric_type second_factor = ( x3 * y4 - y3 * x4 );\n        ues::math::numeric_type x, y;\n        x = ( first_factor * ( x3 - x4 ) - ( x1 - x2 ) * second_factor ) * denominator_inv;\n        y = ( first_factor * ( y3 - y4 ) - ( y1 - y2 ) * second_factor ) * denominator_inv;\n\n        result = { x, y };\n\n        if ( x + epsilon >= std::max ( std::min ( x1, x2 ), std::min ( x3, x4 ) ) &&\n                x - epsilon <= std::min ( std::max ( x1, x2 ), std::max ( x3, x4 ) ) &&\n                y + epsilon >= std::max ( std::min ( y1, y2 ), std::min ( y3, y4 ) ) &&\n                y - epsilon <= std::min ( std::max ( y1, y2 ), std::max ( y3, y4 ) ) )\n        {\n\n            if ( lg.min_level() <= ues::log::TRACE_LVL )\n            {\n                ues::log::event e ( ues::log::TRACE_LVL, component_name, \"Segment intersection found\" );\n                e.message() << \"Intersection between segments ( \" << s1p1 << \", \" << s1p2 << \" ) and ( \" << s2p1 << \", \" << s2p2 << \" ) is \" << result << \".\\n\";\n                lg.record ( std::move ( e ) );\n            }\n\n\n            return true;\n        }\n    }\n\n    if ( lg.min_level() <= ues::log::TRACE_LVL )\n    {\n        ues::log::event e ( ues::log::TRACE_LVL, component_name, \"Segment intersection not found\" );\n        e.message() << \"No intersection found between segments ( \" << s1p1 << \", \" << s1p2 << \" ) and ( \" << s2p1 << \", \" << s2p2 << \" ).\\n\";\n        if ( denominator != 0 )\n        {\n            e.message() << \"Lines containing segments intersect at \" << result << \", which is out of the boundaries of the segments.\\n\";\n        }\n        else\n        {\n            e.message() << \"Segments are parallel.\\n\";\n        }\n        lg.record ( std::move ( e ) );\n    }\n\n    return false;\n}\n\n\nues::math::numeric_type ues::geom::point_to_segment_distance ( const point<2> & origin_point,\n                                                    const point<2> & segment_point1,\n                                                    const point<2> & segment_point2,\n                                                    const ues::math::numeric_type & angle,\n                                                    const ues::math::numeric_type & epsilon )\n{\n    point<2> s1 = segment_point1;\n    point<2> s2 = segment_point2;\n\n    ues::math::matrix transform = rotation_matrix_2d ( -angle ) *\n                       translation_matrix_2d ( -origin_point.get_x(), -origin_point.get_y() );\n    s1.transform ( transform );\n    s2.transform ( transform );\n\n    if ( ( s1.get_y() > epsilon && s2.get_y() > epsilon ) ||\n            ( s1.get_y() < -epsilon && s2.get_y() < -epsilon ) )\n    {\n        std::ostringstream out;\n        out << \"The angle provided (\" << ( angle > ues::math::pi ? angle - 2 * ues::math::pi : angle ) << \" rad) from point \" << origin_point;\n        out << \" does not intersect segment \" << segment_point1 << \"-\" << segment_point2;\n\n        throw ues::exc::exception ( out.str(), UES_CONTEXT );\n    }\n\n    if ( std::abs ( s1.get_y() ) < ues::math::epsilon && std::abs ( s2.get_y() ) < ues::math::epsilon )\n    {\n        // The segment is perpendicular.\n        return std::min ( s1.get_x(), s2.get_x() );\n    }\n\n    ues::math::numeric_type w1, w2;\n    if ( s1.get_y() > 0 && s2.get_y() > 0 )\n    {\n        if ( s1.get_y() > s2.get_y() )\n        {\n            w1 = 0;\n            w2 = 1;\n        }\n        else\n        {\n            w1 = 1;\n            w2 = 0;\n        }\n    }\n    else if ( s1.get_y() < 0 && s2.get_y() < 0 )\n    {\n        if ( s1.get_y() > s2.get_y() )\n        {\n            w1 = 1;\n            w2 = 0;\n        }\n        else\n        {\n            w1 = 0;\n            w2 = 1;\n        }\n    }\n    else\n    {\n        ues::math::numeric_type inv_segment_height = 1 / std::abs ( s1.get_y() - s2.get_y() );\n        w1 = std::abs ( s2.get_y() ) * inv_segment_height;\n        w2 = std::abs ( s1.get_y() ) * inv_segment_height;\n    }\n\n    ues::math::numeric_type intersection_distance = w1 * s1.get_x() + w2 * s2.get_x();\n\n    // Return distance from point to segment.\n    return intersection_distance;\n}\n\n\nbool ues::geom::check_polygon_intersection ( const polygon & poly1, const polygon & poly2 ) noexcept\n{\n    return boost::geometry::intersects ( poly1, poly2 );\n}\n\n\nues::math::matrix ues::geom::translation_matrix_2d ( const ues::math::numeric_type & x, const ues::math::numeric_type & y ) noexcept\n{\n    // A 3x3 matrix for homogeneous 2D transformation\n    ues::math::matrix::fixed<3, 3> transform = { 1, 0, 0, 0, 1, 0, x, y, 1 };\n    return transform;\n}\n\n\nues::math::matrix ues::geom::rotation_matrix_2d ( const ues::math::numeric_type & angle ) noexcept\n{\n\n    // Compute the transformation matrix\n    ues::math::numeric_type sine = std::sin ( angle );\n    ues::math::numeric_type cosine = std::cos ( angle );\n\n    // A 3x3 matrix for homogeneous 2D transformation\n    ues::math::matrix::fixed<3, 3> transform = { cosine, sine, 0, -sine, cosine, 0, 0, 0, 1 };\n    return transform;\n}\n", "meta": {"hexsha": "3fecf77bf3b08509c37aa254fdd30889cf1156ec", "size": 7539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geom/algorithms_2d.cpp", "max_stars_repo_name": "gfrontera/pathfinding-benchmark", "max_stars_repo_head_hexsha": "d8fb1cb2af6924933759886765b4e8916b7bd8dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T07:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T17:30:10.000Z", "max_issues_repo_path": "geom/algorithms_2d.cpp", "max_issues_repo_name": "gfrontera/pathfinding-benchmark", "max_issues_repo_head_hexsha": "d8fb1cb2af6924933759886765b4e8916b7bd8dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geom/algorithms_2d.cpp", "max_forks_repo_name": "gfrontera/pathfinding-benchmark", "max_forks_repo_head_hexsha": "d8fb1cb2af6924933759886765b4e8916b7bd8dc", "max_forks_repo_licenses": ["Apache-2.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.5613207547, "max_line_length": 160, "alphanum_fraction": 0.5149224035, "num_tokens": 2122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6376884869685606}}
{"text": "#ifndef EIGHTPOINTALGO_H\n#define EIGHTPOINTALGO_H\n#include <vector>\n#include <string>\n#include <math.h>\n#include <opencv2/opencv.hpp>\n//#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace cv;\n//using namespace Eigen;\n\nclass EightPointAlgorithm\n{\n    public:\n        EightPointAlgorithm(bool d = false);\n        int getID();\n\n        Mat F_Matrix_Eight_Point(vector<Point2d>&, vector<Point2d>&, bool norm = false);\n        Mat F_Matrix_Normalized_Eight_Point(vector<Point2d>&, vector<Point2d>&);\n        void Plot_Epipolar_lines(vector<Point2d>&, vector<Point2d>&, Mat&, Mat&);\n    private:\n        int id;\n        bool debug;\n\n        Mat Get_Homogen(vector<Point2d>&);\n        Mat Get_Y(Mat&,Mat&);\n        Mat Get_NormMat2d(Mat&);\n        Mat Get_DrawLines(vector<Point2d>&,Mat&,vector<cv::Vec3d>&, Mat&);\n};\n#endif", "meta": {"hexsha": "497464bbf2097f41d092a4f0e019953ca42802ca", "size": 826, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "EightPointAlgorithm.hpp", "max_stars_repo_name": "husmen/Eight-Point-Algorithm-Cpp", "max_stars_repo_head_hexsha": "9019128948437c48c166eec5e7d6ccf2774bf80e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EightPointAlgorithm.hpp", "max_issues_repo_name": "husmen/Eight-Point-Algorithm-Cpp", "max_issues_repo_head_hexsha": "9019128948437c48c166eec5e7d6ccf2774bf80e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EightPointAlgorithm.hpp", "max_forks_repo_name": "husmen/Eight-Point-Algorithm-Cpp", "max_forks_repo_head_hexsha": "9019128948437c48c166eec5e7d6ccf2774bf80e", "max_forks_repo_licenses": ["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.6451612903, "max_line_length": 88, "alphanum_fraction": 0.6682808717, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.63768848401221}}
{"text": "#include \"testing/testing.hpp\"\n\n#include \"base/math.hpp\"\n\n#include <limits>\n\n#include <boost/math/special_functions/next.hpp>\n\nnamespace\n{\n// Returns the next representable floating point value without using conversion to integer.\ntemplate <typename Float>\nFloat NextFloat(Float const x, int dir = 1)\n{\n  return boost::math::float_advance(x, dir);\n}\n\ntemplate <typename Float>\nvoid TestMaxULPs()\n{\n  for (unsigned int logMaxULPs = 0; logMaxULPs <= 8; ++logMaxULPs)\n  {\n    unsigned int const maxULPs = (1 << logMaxULPs) - 1;\n    for (int base = -1; base <= 1; ++base)\n    {\n      for (int dir = -1; dir <= 1; dir += 2)\n      {\n        Float const x = base;\n        Float y = x;\n        for (unsigned int i = 0; i <= maxULPs; ++i)\n        {\n          TEST(base::AlmostEqualULPs(x, y, maxULPs), (x, y, maxULPs, x - y, dir));\n          Float const nextY = NextFloat(y, dir);\n          TEST_NOT_EQUAL(y, nextY, (i, base, dir));\n          y = nextY;\n        }\n        TEST(!base::AlmostEqualULPs(x, y, maxULPs), (x, y, maxULPs, x - y));\n      }\n    }\n  }\n}\n}  // namespace\n\nUNIT_TEST(PowUInt)\n{\n  TEST_EQUAL(base::PowUint(3, 10), 59049, ());\n}\n\nUNIT_TEST(AlmostEqualULPs_double)\n{\n  TEST_ALMOST_EQUAL_ULPS(3.0, 3.0, ());\n  TEST_ALMOST_EQUAL_ULPS(+0.0, -0.0, ());\n\n  double const eps = std::numeric_limits<double>::epsilon();\n  double const dmax = std::numeric_limits<double>::max();\n\n  TEST_ALMOST_EQUAL_ULPS(1.0 + eps, 1.0, ());\n  TEST_ALMOST_EQUAL_ULPS(1.0 - eps, 1.0, ());\n  TEST_ALMOST_EQUAL_ULPS(1.0 - eps, 1.0 + eps, ());\n\n  TEST_ALMOST_EQUAL_ULPS(dmax, dmax, ());\n  TEST_ALMOST_EQUAL_ULPS(-dmax, -dmax, ());\n  TEST_ALMOST_EQUAL_ULPS(dmax/2.0, dmax/2.0, ());\n  TEST_ALMOST_EQUAL_ULPS(1.0/dmax, 1.0/dmax, ());\n  TEST_ALMOST_EQUAL_ULPS(-1.0/dmax, -1.0/dmax, ());\n\n  TEST(!base::AlmostEqualULPs(1.0, -1.0), ());\n  TEST(!base::AlmostEqualULPs(2.0, -2.0), ());\n  TEST(!base::AlmostEqualULPs(dmax, -dmax), ());\n  TEST(!base::AlmostEqualULPs(0.0, eps), ());\n}\n\nUNIT_TEST(AlmostEqualULPs_float)\n{\n  TEST_ALMOST_EQUAL_ULPS(3.0f, 3.0f, ());\n  TEST_ALMOST_EQUAL_ULPS(+0.0f, -0.0f, ());\n\n  float const eps = std::numeric_limits<float>::epsilon();\n  float const dmax = std::numeric_limits<float>::max();\n\n  TEST_ALMOST_EQUAL_ULPS(1.0f + eps, 1.0f, ());\n  TEST_ALMOST_EQUAL_ULPS(1.0f - eps, 1.0f, ());\n  TEST_ALMOST_EQUAL_ULPS(1.0f - eps, 1.0f + eps, ());\n\n  TEST_ALMOST_EQUAL_ULPS(dmax, dmax, ());\n  TEST_ALMOST_EQUAL_ULPS(-dmax, -dmax, ());\n  TEST_ALMOST_EQUAL_ULPS(dmax/2.0f, dmax/2.0f, ());\n  TEST_ALMOST_EQUAL_ULPS(1.0f/dmax, 1.0f/dmax, ());\n  TEST_ALMOST_EQUAL_ULPS(-1.0f/dmax, -1.0f/dmax, ());\n\n  TEST(!base::AlmostEqualULPs(1.0f, -1.0f), ());\n  TEST(!base::AlmostEqualULPs(2.0f, -2.0f), ());\n  TEST(!base::AlmostEqualULPs(dmax, -dmax), ());\n  TEST(!base::AlmostEqualULPs(0.0f, eps), ());\n}\n\nUNIT_TEST(AlmostEqual_Smoke)\n{\n  double const small = 1e-18;\n  double const eps = 1e-10;\n\n  TEST(base::AlmostEqualAbs(0.0, 0.0 + small, eps), ());\n  TEST(!base::AlmostEqualRel(0.0, 0.0 + small, eps), ());\n  TEST(!base::AlmostEqualULPs(0.0, 0.0 + small), ());\n\n  TEST(base::AlmostEqualAbs(1.0, 1.0 + small, eps), ());\n  TEST(base::AlmostEqualRel(1.0, 1.0 + small, eps), ());\n  TEST(base::AlmostEqualULPs(1.0, 1.0 + small), ());\n\n  TEST(base::AlmostEqualRel(123456789.0, 123456780.0, 1e-7), ());\n}\n\nUNIT_TEST(AlmostEqualULPs_MaxULPs_double)\n{\n  TestMaxULPs<double>();\n}\n\nUNIT_TEST(AlmostEqualULPs_MaxULPs_float)\n{\n  TestMaxULPs<float>();\n}\n\nUNIT_TEST(TEST_FLOAT_DOUBLE_EQUAL_macros)\n{\n  float const fx = 3;\n  float const fy = NextFloat(NextFloat(NextFloat(fx)));\n  TEST_ALMOST_EQUAL_ULPS(fx, fy, ());\n  TEST_NOT_ALMOST_EQUAL_ULPS(fx, 2.0f, ());\n\n  double const dx = 3;\n  double const dy = NextFloat(NextFloat(NextFloat(dx)));\n  TEST_ALMOST_EQUAL_ULPS(dx, dy, ());\n  TEST_NOT_ALMOST_EQUAL_ULPS(dx, 2.0, ());\n}\n\nUNIT_TEST(GCD)\n{\n  TEST_EQUAL(base::GCD(6, 3), 3, ());\n  TEST_EQUAL(base::GCD(14, 7), 7, ());\n  TEST_EQUAL(base::GCD(100, 100), 100, ());\n  TEST_EQUAL(base::GCD(7, 3), 1, ());\n  TEST_EQUAL(base::GCD(8, 3), 1, ());\n  TEST_EQUAL(base::GCD(9, 3), 3, ());\n}\n\nUNIT_TEST(LCM)\n{\n  TEST_EQUAL(base::LCM(6, 3), 6, ());\n  TEST_EQUAL(base::LCM(14, 7), 14, ());\n  TEST_EQUAL(base::LCM(100, 100), 100, ());\n  TEST_EQUAL(base::LCM(7, 3), 21, ());\n  TEST_EQUAL(base::LCM(8, 3), 24, ());\n  TEST_EQUAL(base::LCM(9, 3), 9, ());\n}\n\nUNIT_TEST(Sign)\n{\n  TEST_EQUAL(1, base::Sign(1), ());\n  TEST_EQUAL(1, base::Sign(10.4), ());\n\n  TEST_EQUAL(0, base::Sign(0), ());\n  TEST_EQUAL(0, base::Sign(0.0), ());\n\n  TEST_EQUAL(-1, base::Sign(-11), ());\n  TEST_EQUAL(-1, base::Sign(-10.4), ());\n}\n", "meta": {"hexsha": "047cd0f08bd8b055b3f055a01ac86cf5d96072d1", "size": 4558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "base/base_tests/math_test.cpp", "max_stars_repo_name": "sthirvela/organicmaps", "max_stars_repo_head_hexsha": "14885ba070ac9d1b7241ebb89eeefa46c9fdc1e4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3062.0, "max_stars_repo_stars_event_min_datetime": "2021-04-09T16:51:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:02:51.000Z", "max_issues_repo_path": "base/base_tests/math_test.cpp", "max_issues_repo_name": "MAPSWorks/organicmaps", "max_issues_repo_head_hexsha": "b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1396.0, "max_issues_repo_issues_event_min_datetime": "2021-04-08T07:26:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:27:46.000Z", "max_forks_repo_path": "base/base_tests/math_test.cpp", "max_forks_repo_name": "MAPSWorks/organicmaps", "max_forks_repo_head_hexsha": "b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 242.0, "max_forks_repo_forks_event_min_datetime": "2021-04-10T17:10:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:41:07.000Z", "avg_line_length": 27.2934131737, "max_line_length": 91, "alphanum_fraction": 0.6263712154, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6376824222216027}}
{"text": "#include \"../common.hpp\"\n#include \"../program_options.hpp\"\n#include <crab/analysis/dataflow/assertion_crawler.hpp>\n\n#include <boost/range/iterator_range.hpp>\n\nusing namespace std;\nusing namespace crab::cfg;\nusing namespace crab::cg;\nusing namespace crab::cfg_impl;\nusing namespace crab::domain_impl;\n\nz_cfg_t *prog(variable_factory_t &vfac) {\n  /*\n     i := 0;\n     x := 1;\n     y := 0;\n     z := 3;\n     w := 3;\n     while (i < 100) {\n       x  := x + y;\n       y  := y + 1;\n       nd := *;\n       z  := z xor nd;\n       w  := w xor nd;\n       i  := i + 1;\n     }\n     assert(i >= 100);\n   */\n  // Definining program variables\n  z_var i(vfac[\"i\"], crab::INT_TYPE, 32);\n  z_var x(vfac[\"x\"], crab::INT_TYPE, 32);\n  z_var y(vfac[\"y\"], crab::INT_TYPE, 32);\n  z_var z(vfac[\"z\"], crab::INT_TYPE, 32);\n  z_var w(vfac[\"w\"], crab::INT_TYPE, 32);\n  z_var nd1(vfac[\"nd1\"], crab::INT_TYPE, 32);\n  z_var nd2(vfac[\"nd2\"], crab::INT_TYPE, 32);\n  // entry and exit block\n  function_decl<z_number, varname_t> decl(\"main\", {}, {});  \n  z_cfg_t *cfg = new z_cfg_t(\"entry\", \"ret\", decl);\n  // adding blocks\n  z_basic_block_t &entry = cfg->insert(\"entry\");\n  z_basic_block_t &bb1 = cfg->insert(\"bb1\");\n  z_basic_block_t &bb1_t = cfg->insert(\"bb1_t\");\n  z_basic_block_t &bb1_f = cfg->insert(\"bb1_f\");\n  z_basic_block_t &bb2 = cfg->insert(\"bb2\");\n  z_basic_block_t &exit = cfg->insert(\"exit\");\n  z_basic_block_t &ret = cfg->insert(\"ret\");\n  // adding control flow\n  entry >> bb1;\n  bb1 >> bb1_t;\n  bb1 >> bb1_f;\n  bb1_t >> bb2;\n  bb2 >> bb1;\n  bb1_f >> exit;\n  exit >> ret;\n  // adding statements\n  entry.assign(i, 0);\n  entry.assign(x, 1);\n  entry.assign(y, 0);\n  entry.assign(z, 3);\n  entry.assign(w, 3);\n  bb1_t.assume(i <= 99);\n  bb1_f.assume(i >= 100);\n  bb2.callsite(\"bar\",{x,y}, {x,y,z,w});\n  bb2.add(i, i, 1);\n  exit.assume(x <= y);\n  exit.assertion(w >= 0);\n  exit.assertion(x >= y);\n  exit.assertion(i >= 0);    \n  return cfg;\n}\n\nz_cfg_t *foo_cfg(variable_factory_t &vfac) {\n  // Definining program variables\n  z_var i1(vfac[\"i1\"], crab::INT_TYPE, 32);\n  z_var i2(vfac[\"i2\"], crab::INT_TYPE, 32);\n  z_var i3(vfac[\"i3\"], crab::INT_TYPE, 32);\n  z_var i4(vfac[\"i4\"], crab::INT_TYPE, 32);\n  z_var o1(vfac[\"o1\"], crab::INT_TYPE, 32);\n  z_var o2(vfac[\"o2\"], crab::INT_TYPE, 32);  \n\n  z_var tmp1(vfac[\"tmp1\"], crab::INT_TYPE, 32);\n  z_var tmp2(vfac[\"tmp2\"], crab::INT_TYPE, 32);  \n  \n  // entry and exit block\n   z_cfg_t *cfg = new z_cfg_t(\"entry\", \"exit\",\n\t\t\t      function_decl<z_number, varname_t>(\"foo\", {i1,i2,i3,i4}, {o1,o2}));\n  // adding blocks\n  z_basic_block_t &entry = cfg->insert(\"entry\");\n  z_basic_block_t &exit = cfg->insert(\"exit\");  \n\n  entry >> exit;\n  entry.add(tmp1, i1,i2);\n  entry.add(tmp2, i3,i4);\n  \n  exit.assign(o1, tmp1);\n  exit.assign(o2, tmp2);\n  \n  return cfg;\n}\n\nz_cfg_t *bar_cfg(variable_factory_t &vfac) {\n#if 0   \n  // Definining program variables\n  z_var a1(vfac[\"a1\"], crab::INT_TYPE, 32);\n  z_var a2(vfac[\"a2\"], crab::INT_TYPE, 32);\n  z_var a3(vfac[\"a3\"], crab::INT_TYPE, 32);\n  z_var a4(vfac[\"a4\"], crab::INT_TYPE, 32);\n  z_var b1(vfac[\"b1\"], crab::INT_TYPE, 32);\n  z_var b2(vfac[\"b2\"], crab::INT_TYPE, 32);  \n\n  // entry and exit block\n   z_cfg_t *cfg = new z_cfg_t(\"entry\", \"exit\",\n\t\t\t      function_decl<z_number, varname_t>(\"bar\", {a1,a2,a3,a4}, {b1,b2}));\n  // adding blocks\n  z_basic_block_t &entry = cfg->insert(\"entry\");\n  z_basic_block_t &exit = cfg->insert(\"exit\");\n  entry >> exit;\n  entry.callsite(\"foo\", {b1,b2}, {a1,a2,a3,a4});\n  exit.assertion(b1 >= 0);\n  exit.assertion(b2 >= 0);      \n#else\n  // Definining program variables\n  z_var i1(vfac[\"i1\"], crab::INT_TYPE, 32);\n  z_var i2(vfac[\"i2\"], crab::INT_TYPE, 32);\n  z_var i3(vfac[\"i3\"], crab::INT_TYPE, 32);\n  z_var i4(vfac[\"i4\"], crab::INT_TYPE, 32);\n  z_var o1(vfac[\"o1\"], crab::INT_TYPE, 32);\n  z_var o2(vfac[\"o2\"], crab::INT_TYPE, 32);  \n\n  // entry and exit block\n   z_cfg_t *cfg = new z_cfg_t(\"entry\", \"exit\",\n  \t\t\t      function_decl<z_number, varname_t>(\"bar\", {i1,i2,i3,i4}, {o1,o2}));\n  // adding blocks\n  z_basic_block_t &entry = cfg->insert(\"entry\");\n  z_basic_block_t &exit = cfg->insert(\"exit\");\n  entry >> exit;\n  entry.callsite(\"foo\", {o1,o2}, {i1,i2,i3,i4});\n  exit.assertion(o1 >= 0);\n  exit.assertion(o2 >= 0);      \n#endif\n  \n  return cfg;\n}\n\nint main(int argc, char **argv) {\n  bool stats_enabled = false;\n  if (!crab_tests::parse_user_options(argc, argv, stats_enabled)) {\n    return 0;\n  }\n  using callgraph_t = call_graph<z_cfg_ref_t>;\n  variable_factory_t vfac;\n\n  z_cfg_t *p1 = prog(vfac);\n  crab::outs() << *p1 << \"\\n\";\n\n  z_cfg_t *p2 = foo_cfg(vfac);\n  crab::outs() << *p2 << \"\\n\";\n\n  z_cfg_t *p3 = bar_cfg(vfac);\n  crab::outs() << *p3 << \"\\n\";\n  \n  vector<z_cfg_ref_t> cfgs({*p1, *p2, *p3});\n  callgraph_t cg(cfgs);\n  \n  using crawler_t = crab::analyzer::inter_assertion_crawler<callgraph_t>;\n  crawler_t crawler(cg);\n  crawler.run();\n\n  auto print_results = [&crawler](z_cfg_t &cfg) {\n    // Print results in DFS to enforce a fixed order\n    std::set<crab::cfg_impl::basic_block_label_t> visited;\n    std::vector<crab::cfg_impl::basic_block_label_t> worklist;\n    worklist.push_back(cfg.entry());\n    visited.insert(cfg.entry());\n    while (!worklist.empty()) {\n      auto cur_label = worklist.back();\n      worklist.pop_back();\n      auto results = crawler.get_results(cfg, cur_label);\n      crab::outs() << crab::basic_block_traits<crab::cfg_impl::z_basic_block_t>::to_string(cur_label)\n\t\t   << \"=\" << results << \"\\n\";\n      auto const &cur_node = cfg.get_node(cur_label);\n      for (auto const& kid_label :\n         boost::make_iterator_range(cur_node.next_blocks())) {\n\tif (visited.insert(kid_label).second) {\n\t  worklist.push_back(kid_label);\n\t}\n      }\n    }};\n\n  crab::outs() << \"Assertion Crawler Analysis for main\\n\";\n  print_results(*p1);\n  crab::outs() << \"Assertion Crawler Analysis for bar\\n\";  \n  print_results(*p3);\n  crab::outs() << \"Assertion Crawler Analysis for foo\\n\";    \n  print_results(*p2);\n  \n  //crawler.write(crab::outs());\n\n  delete p1;\n  delete p2;\n  delete p3;\n  return 0;\n}\n", "meta": {"hexsha": "a9586aa4c2efd37a141725b178e0a70db2bd17e2", "size": 6020, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests/assertion_crawler/crawler-2.cc", "max_stars_repo_name": "LinerSu/crab", "max_stars_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 152.0, "max_stars_repo_stars_event_min_datetime": "2016-02-28T06:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:44:56.000Z", "max_issues_repo_path": "tests/assertion_crawler/crawler-2.cc", "max_issues_repo_name": "LinerSu/crab", "max_issues_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-07-03T06:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:09:32.000Z", "max_forks_repo_path": "tests/assertion_crawler/crawler-2.cc", "max_forks_repo_name": "LinerSu/crab", "max_forks_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-11-22T15:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T00:46:57.000Z", "avg_line_length": 29.2233009709, "max_line_length": 101, "alphanum_fraction": 0.6182724252, "num_tokens": 2031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198946, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6376824193323186}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2012, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n               \n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n\n/*\n* \n*   Tutorial: QR factorization of matrices from ViennaCL or Boost.uBLAS (qr.cpp and qr.cu are identical, the latter being required for compilation using CUDA nvcc)\n*\n*/\n\n// activate ublas support in ViennaCL\n#define VIENNACL_WITH_UBLAS \n\n//\n// include necessary system headers\n//\n#include <iostream>\n\n//\n// ViennaCL includes: We only need the qr-header\n//\n#include \"viennacl/linalg/qr.hpp\"\n\n//\n// Boost includes\n//\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n\n//\n// Testing\n//\n#include \"viennacl/range.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/matrix_proxy.hpp\"\n\n\n//\n// A helper function checking the result\n//\ntemplate <typename MatrixType>\ndouble check(MatrixType const & qr, MatrixType const & ref)\n{\n  bool do_break = false;\n  double max_error = 0;\n  for (std::size_t i=0; i<ref.size1(); ++i)\n  {\n    for (std::size_t j=0; j<ref.size2(); ++j)\n    {\n      if (qr(i,j) != 0.0 && ref(i,j) != 0.0)\n      {\n        double rel_err = fabs(qr(i,j) - ref(i,j)) / fabs(ref(i,j) );\n        \n        if (rel_err > max_error)\n          max_error = rel_err;\n      }\n      \n      \n      if (qr(i,j) != qr(i,j))\n      {\n        std::cout << \"!!!\" << std::endl;\n        std::cout << \"!!! NaN detected at i=\" << i << \" and j=\" << j << std::endl;\n        std::cout << \"!!!\" << std::endl;\n        do_break = true;\n        break;\n      }\n    }\n    if (do_break)\n      break;\n  }\n  return max_error;\n}\n\n\nint main (int, const char **)\n{\n  typedef double               ScalarType;     //feel free to change this to 'double' if supported by your hardware\n  typedef boost::numeric::ublas::matrix<ScalarType>        MatrixType;\n  typedef boost::numeric::ublas::vector<ScalarType>        VectorType;\n  typedef viennacl::matrix<ScalarType, viennacl::column_major>        VCLMatrixType;\n  typedef viennacl::vector<ScalarType>        VCLVectorType;\n\n  std::size_t rows = 113;   //number of rows in the matrix\n  std::size_t cols = 54;   //number of columns\n  \n  //\n  // Create matrices with some data\n  //\n  MatrixType ublas_A(rows, cols);\n  MatrixType Q(rows, rows);\n  MatrixType R(rows, cols);\n  \n  // Some random data with a bit of extra weight on the diagonal\n  for (std::size_t i=0; i<rows; ++i)\n  {\n    for (std::size_t j=0; j<cols; ++j)\n    {\n      ublas_A(i,j) = -1.0 + (i+1)*(j+1)\n                     + ( (rand() % 1000) - 500.0) / 1000.0;\n\n      if (i == j)\n        ublas_A(i,j) += 10.0;\n                     \n      R(i,j) = 0.0;\n    }\n    \n    for (std::size_t j=0; j<rows; ++j)\n      Q(i,j) = 0.0;\n  }\n  \n  // keep initial input matrix for comparison\n  MatrixType ublas_A_backup(ublas_A);\n  \n  \n  //\n  // Setup the matrix in ViennaCL:\n  //\n  VCLVectorType dummy(10);\n  VCLMatrixType vcl_A(ublas_A.size1(), ublas_A.size2());\n  \n  viennacl::copy(ublas_A, vcl_A);\n  \n  //\n  // Compute QR factorization of A. A is overwritten with Householder vectors. Coefficients are returned and a block size of 3 is used.\n  // Note that at the moment the number of columns of A must be divisible by the block size\n  //\n\n  std::cout << \"--- Boost.uBLAS ---\" << std::endl;\n  std::vector<ScalarType> ublas_betas = viennacl::linalg::inplace_qr(ublas_A);  //computes the QR factorization\n  \n  //\n  // A check for the correct result:\n  //\n  viennacl::linalg::recoverQ(ublas_A, ublas_betas, Q, R); \n  MatrixType ublas_QR = prod(Q, R);\n  double ublas_error = check(ublas_QR, ublas_A_backup);\n  std::cout << \"Max rel error (ublas): \" << ublas_error << std::endl;\n  \n  //\n  // QR factorization in ViennaCL using Boost.uBLAS for the panel factorization\n  //\n  std::cout << \"--- Hybrid (default) ---\" << std::endl;\n  viennacl::copy(ublas_A_backup, vcl_A);\n  std::vector<ScalarType> hybrid_betas = viennacl::linalg::inplace_qr(vcl_A);\n  \n\n  //\n  // A check for the correct result:\n  //\n  viennacl::copy(vcl_A, ublas_A);\n  Q.clear(); R.clear();\n  viennacl::linalg::recoverQ(ublas_A, hybrid_betas, Q, R); \n  double hybrid_error = check(ublas_QR, ublas_A_backup);\n  std::cout << \"Max rel error (hybrid): \" << hybrid_error << std::endl;\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": "5bb2035c17b44d2b9af6e10c1490bc308b3828fa", "size": 5036, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/qr.cpp", "max_stars_repo_name": "bollig/viennacl", "max_stars_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T08:33:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T08:33:10.000Z", "max_issues_repo_path": "examples/tutorial/qr.cpp", "max_issues_repo_name": "bollig/viennacl", "max_issues_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tutorial/qr.cpp", "max_forks_repo_name": "bollig/viennacl", "max_forks_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6703296703, "max_line_length": 163, "alphanum_fraction": 0.5802223987, "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6376824185744574}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"Werk/Math/SimpleLinearRegression.hpp\"\n\nBOOST_AUTO_TEST_SUITE(SimpleLinearRegressionTest)\n\nBOOST_AUTO_TEST_CASE(TestEmpty)\n{\n\tWerk::SimpleLinearRegression r;\n    BOOST_REQUIRE_EQUAL(r.count(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(TestBasic)\n{\n    Werk::SimpleLinearRegression r;\n\n    r.sample(1.0, 4.0);\n    r.sample(3.0, 8.0);\n    BOOST_REQUIRE_EQUAL(r.count(), 2);\n    BOOST_REQUIRE_EQUAL(r.beta(), 2.0);\n    BOOST_REQUIRE_EQUAL(r.correlation(), 1.0);\n\n    r.sample(5.0, 12.0);\n    BOOST_REQUIRE_EQUAL(r.count(), 3);\n    BOOST_REQUIRE_EQUAL(r.correlation(), 1.0);\n    BOOST_REQUIRE_CLOSE(r.beta(), 2.0, 0.000000001);\n    BOOST_REQUIRE_CLOSE(r.alpha(), 2.0, 0.000000001);\n\n    r.reset();\n    BOOST_REQUIRE_EQUAL(r.count(), 0);\n}\n\nBOOST_AUTO_TEST_CASE(TestZero)\n{\n    Werk::SimpleLinearRegression r;\n\n    r.sample(-1.0, 3.0);\n    r.sample(0.0, 0.0);\n    r.sample(1.0, 3.0);\n    BOOST_REQUIRE_EQUAL(r.count(), 3);\n    BOOST_REQUIRE_EQUAL(r.correlation(), 0.0);\n    BOOST_REQUIRE_EQUAL(r.beta(), 0.0);\n    BOOST_REQUIRE_CLOSE(r.alpha(), 2.0, 0.000000001);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "179b9977bc6fb8b073ee293bb40add6e774fb0dc", "size": 1121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/WerkTest/Math/SimpleLinearRegression.cpp", "max_stars_repo_name": "mish24/werk", "max_stars_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/WerkTest/Math/SimpleLinearRegression.cpp", "max_issues_repo_name": "mish24/werk", "max_issues_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WerkTest/Math/SimpleLinearRegression.cpp", "max_forks_repo_name": "mish24/werk", "max_forks_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3695652174, "max_line_length": 53, "alphanum_fraction": 0.687778769, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6376824048858977}}
{"text": "#include <random>\n#include <Eigen/Dense>\n#include \"HODLR_Tree.hpp\"\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <squaredeMat.hpp> //squared exponential kernel\n#include <squaredeP1Mat.hpp>\n\nusing std::normal_distribution;\nnamespace py = pybind11;\n\nEigen::MatrixXd predict(Eigen::MatrixXd X, Eigen::MatrixXd Y, Eigen::MatrixXd Xtest, Eigen::VectorXd sig_samps, Eigen::VectorXd rho_samps, Eigen::VectorXd tau_samps, double multiplier, int M, double tol, int nsamps) {\n  /*\n      \n     Sample a draw of the GP function f*|f, sig, rho, tau, x*.\n     Assume a squared exponential Gaussian Process based on \n     observed function f at new test points x*.\n     Temporarily assumes fit method was called with regression = true. \n\n  */ \n\n    // Create the standard normal generator\n    normal_distribution<double> norm(0, 1);\n    std::mt19937 rng;\n    auto r_std_normal = bind(norm, rng);\n    \n    int Ntest =  Xtest.rows();  \n    int N =  X.rows();\n    int D =  X.cols();\n   \n\n    // HODLR details\n    int n_levels = log(N / M) / log(2);\n    bool is_sym = true;\n    bool is_pd  = true;\n\n    double tau;\n    double rho; \n    double sig; \n    \n    double sigsq; \n    double tmpSSR;\n    \n    // Allocate space for output\n    Eigen::MatrixXd fstarsamp(nsamps, Ntest);\n    Eigen::VectorXd KobsNew(N);\n    \n    for (int s = 0; s < nsamps; s++) {\n\n      sig = sig_samps(s);\n      tau = tau_samps(s);\n      rho = rho_samps(s);\n\n      sigsq = pow(sig, 2.0);\n\n      // HODLR approximation \n      SQRExponentialP1_Kernel* L  = new SQRExponentialP1_Kernel(X, N, sig, rho, tau);\n      HODLR_Tree* T = new HODLR_Tree(n_levels, tol, L); // With noise (i.e. Sigma + I/tau)\n      T->assembleTree(is_sym, is_pd);\n      T->factorize();\n\n      for (int i = 0; i < Ntest; i++) {\n        Eigen::RowVectorXd Xtest_i = Xtest.row(i);\n\n        // Get covariance between X and Xtest\n        for (int j = 0; j < N; j++) {\n          Eigen::RowVectorXd tmp = X.row(j) - Xtest_i;\n          tmpSSR = 0.0;\n          for (int d = 0; d < D; d++) {\n            tmpSSR = tmpSSR + pow(tmp(d), 2.0);\n          }\n          KobsNew(j) = sigsq * exp(- tmpSSR * rho);\n        }\n\n        // Get variance at Xtest\n        double kNewNew = sigsq + 1e-8;\n\n        // Get posterior mean and variance of f* at point xtest(i)\n        double sdstar = pow(kNewNew - (multiplier * KobsNew.transpose() * T->solve(tau * KobsNew))(0, 0), 0.5);\n        double mustar = (multiplier * KobsNew.transpose() * T->solve(tau * Y))(0, 0);\n\n        auto normal_samp = r_std_normal();\n\n        fstarsamp(s, i) =  sdstar * normal_samp + mustar;\n      }\n    }    \n    return fstarsamp;\n}\n\nvoid predict_module(py::module &m) {\n    m.def(\"predict_f\", &predict, \"predicted samples of f at new X\");\n}", "meta": {"hexsha": "9dc97e63f1312f8a4b80091897bc140aa30d23e8", "size": 2742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fifa_gp/predict.cpp", "max_stars_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_stars_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fifa_gp/predict.cpp", "max_issues_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_issues_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fifa_gp/predict.cpp", "max_forks_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_forks_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8043478261, "max_line_length": 217, "alphanum_fraction": 0.5988329686, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.6375741189929912}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n#include <test_lib.h>\n\nusing std::cout;\nusing std::endl;\nusing Eigen::MatrixXd;\n\nint main() {\n  test_lib::test_lib_func();\n  MatrixXd X(2, 2);\n  X << 1, 2, 3, 4;\n  cout << X << endl;\n  return 0;\n}\n", "meta": {"hexsha": "0b25f5cd1213895ae40f80338cc2b53cae3dbc01", "size": 241, "ext": "cc", "lang": "C++", "max_stars_repo_path": "example/example.cc", "max_stars_repo_name": "EricCousineau-TRI/kythe_super", "max_stars_repo_head_hexsha": "4aa92eb8fb7530f14c404f20a5658169996833e8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/example.cc", "max_issues_repo_name": "EricCousineau-TRI/kythe_super", "max_issues_repo_head_hexsha": "4aa92eb8fb7530f14c404f20a5658169996833e8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/example.cc", "max_forks_repo_name": "EricCousineau-TRI/kythe_super", "max_forks_repo_head_hexsha": "4aa92eb8fb7530f14c404f20a5658169996833e8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.1764705882, "max_line_length": 28, "alphanum_fraction": 0.622406639, "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6375514326627664}}
{"text": "#ifndef CLASSICAL_MDS_HPP\n#define CLASSICAL_MDS_HPP\n\n#include <vector>\n#include <utility>\n#include <cassert>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\nnamespace mathtoolbox\n{\n    // This function computes low-dimensional embedding by using classical multi-dimensional scaling (MDS)\n    // - Input:  A distance (dissimilarity) matrix and a target dimension for embedding\n    // - Output: A coordinate matrix whose i-th column corresponds to the embedded coordinates of the i-th entry\n    extern inline Eigen::MatrixXd ComputeClassicalMds(const Eigen::MatrixXd& D, unsigned dim);\n\n    /////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    // This function extract the N-largest eigen values and eigen vectors\n    inline void ExtractNLargestEigens(unsigned n, Eigen::VectorXd& S, Eigen::MatrixXd& V)\n    {\n        // Note: m is the original dimension\n        const unsigned m = S.rows();\n\n        // Copy the original matrix\n        const Eigen::MatrixXd original_V = V;\n\n        // Sort by eigenvalue\n        constexpr double epsilon = 1e-16;\n        std::vector<std::pair<double, unsigned>> index_value_pairs(m);\n        for (unsigned i = 0; i < m; ++ i) index_value_pairs[i] = std::make_pair(std::max(S(i), epsilon), i);\n        std::partial_sort(index_value_pairs.begin(), index_value_pairs.begin() + n, index_value_pairs.end(), std::greater<std::pair<double, unsigned>>());\n\n        // Resize matrices\n        S.resize(n);\n        V.resize(m, n);\n\n        // Set values\n        for (unsigned i = 0; i < n; ++ i)\n        {\n            S(i)     = index_value_pairs[i].first;\n            V.col(i) = original_V.col(index_value_pairs[i].second);\n        }\n    }\n\n    inline Eigen::MatrixXd ComputeClassicalMds(const Eigen::MatrixXd& D, unsigned dim)\n    {\n        assert(D.rows() == D.cols());\n        assert(D.rows() >= dim);\n        const unsigned n = D.rows();\n        const Eigen::MatrixXd H = Eigen::MatrixXd::Identity(n, n) - (1.0 / static_cast<double>(n)) * Eigen::VectorXd::Ones(n) * Eigen::VectorXd::Ones(n).transpose();\n        const Eigen::MatrixXd K = - 0.5 * H * D.cwiseAbs2() * H;\n        const Eigen::EigenSolver<Eigen::MatrixXd> solver(K);\n        Eigen::VectorXd S = solver.eigenvalues().real();\n        Eigen::MatrixXd V = solver.eigenvectors().real();\n        ExtractNLargestEigens(dim, S, V);\n        const Eigen::MatrixXd X = Eigen::DiagonalMatrix<double, Eigen::Dynamic>(S.cwiseSqrt()) * V.transpose();\n        return X;\n    }\n}\n\n#endif // CLASSICAL_MDS_HPP\n", "meta": {"hexsha": "472bcc614a6c3f545453e2554f8ce36f1e3ce505", "size": 2548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/classical-mds.hpp", "max_stars_repo_name": "josefgraus/self_similiarity", "max_stars_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T09:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T09:35:14.000Z", "max_issues_repo_path": "include/mathtoolbox/classical-mds.hpp", "max_issues_repo_name": "josefgraus/self_similiarity", "max_issues_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mathtoolbox/classical-mds.hpp", "max_forks_repo_name": "josefgraus/self_similiarity", "max_forks_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-22T13:02:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-08T00:21:36.000Z", "avg_line_length": 40.4444444444, "max_line_length": 165, "alphanum_fraction": 0.612244898, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6375315249082515}}
{"text": "#ifndef TBODEINT_HPP_\n#define TBODEINT_HPP_\n\n/* Boost libs/numeric/odeint/examples/solar_system.cpp\n Copyright 2010-2012 Karsten Ahnert\n Copyright 2011 Mario Mulansky\n Solar system example for Hamiltonian stepper\n Distributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n#include <iostream>\n#include <array.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\n//#include \"point_type.hpp\"\n#include \"body.hpp\"\n#include \"threebodies.hpp\"\n#include <glm/vec3.hpp>\nclass Body;\n\n\nclass TB_odeint {\n public:\n  static void updateSystem(ThreeBodies system, float deltaTime);\n private:\n  friend OpenGLWindow;\n\n  //Define universal gravitation constant\n  double G = 6.67408e-11; //N-m2/kg2\n\n  const size_t n = 3;\n\n  typedef glm::vec3 point_type;\n  typedef boost::array< point_type , n > container_type;\n  typedef boost::array< double , n > mass_type;\n    //]\n\n  //[ coordinate_function\n  //const double gravitational_constant = 2.95912208286e-4;\n  const double gravitational_constant = 1.0;\n\n  struct tb_system_coor{\n    const mass_type &m_masses;\n\n    tb_system_coor( const mass_type &masses ) : m_masses( masses ) { }\n\n    void operator()( const container_type &p , container_type &dqdt ) const\n    {\n        for( size_t i=0 ; i<n ; ++i )\n            dqdt[i] = p[i] / m_masses[i];\n    }\n  };\n    //]\n\n\n    //[ momentum_function\n  struct tb_system_momentum{\n    const mass_type &m_masses;\n\n    tb_system_momentum( const mass_type &masses ) : m_masses( masses ) { }\n\n    void operator()( const container_type &q , container_type &dpdt ) const\n    {\n        const size_t n = q.size();\n        for( size_t i=0 ; i<n ; ++i )\n        {\n            dpdt[i] = 0.0;\n            for( size_t j=0 ; j<i ; ++j )\n            {\n                point_type diff = q[j] - q[i];\n                double d = abs( diff );\n                diff *= ( gravitational_constant * m_masses[i] * m_masses[j] / d / d / d );\n                dpdt[i] += diff;\n                dpdt[j] -= diff;\n            }\n        }\n    }\n  };\n    //]\n\n  //[ streaming_observer\n  struct streaming_observer{\n    std::ostream& m_out;\n\n    streaming_observer( std::ostream &out ) : m_out( out ) { }\n\n    template< class State >\n    void operator()( const State &x , double t ) const\n    {\n        container_type &q = x.first;\n        m_out << t;\n        for( size_t i=0 ; i<q.size() ; ++i ) m_out << \"\\t\" << q[i];\n        m_out << \"\\n\";\n    }\n  };\n//]\n\n  point_type center_of_mass( const container_type &x , const mass_type &m );\n  double energy( const container_type &q , const container_type &p , const mass_type &masses );\n};\n\n#endif", "meta": {"hexsha": "cf32233cae856662c93ac4a9b31bab445f722600", "size": 2659, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/threebodies/tb_odeint.hpp", "max_stars_repo_name": "Lucas-Muniz/abcg", "max_stars_repo_head_hexsha": "fd0e8d583a8a17554578d5d4cfa2e29959f47f80", "max_stars_repo_licenses": ["MIT"], "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/threebodies/tb_odeint.hpp", "max_issues_repo_name": "Lucas-Muniz/abcg", "max_issues_repo_head_hexsha": "fd0e8d583a8a17554578d5d4cfa2e29959f47f80", "max_issues_repo_licenses": ["MIT"], "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/threebodies/tb_odeint.hpp", "max_forks_repo_name": "Lucas-Muniz/abcg", "max_forks_repo_head_hexsha": "fd0e8d583a8a17554578d5d4cfa2e29959f47f80", "max_forks_repo_licenses": ["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.0849056604, "max_line_length": 95, "alphanum_fraction": 0.616773223, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6375315212334469}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <utility>\n#include <cmath>\n// #include <boost/test/minimal.hpp>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n#include <boost/numeric/itl/smoother/gauss_seidel.hpp>\n\nusing namespace std;  \n   \nint main(int, char**)\n{\n    using namespace mtl;\n\n    const int s= 10;\n    typedef mtl::dense_vector<double> Vector;\n    typedef mtl::compressed2D<double> Matrix;\n    Vector       x(s*s, 8), b(s*s);\n    Matrix   A;\n    laplacian_setup(A, s, s);\n    if (s < 10)\n      std::cout<< \"x= \" << x << \"\\n\";\n    \n    b= A*x;\n    x= 0;\n\n    itl::gauss_seidel<Matrix> gs(A);\n    for (int i =0 ; i< 30; i++)\n        gs(x, b);\n    \n    if (s < 10) {\n      std::cout<< \"x=\" << x << \"\\n\";\n      Vector tmp(b-A*x);\n      assert(two_norm(tmp) < 1.0e-4);\n    }\n    \n    return 0;\n}\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "11acb5403620fc120501355ee39365d981bc87dc", "size": 1275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/gauss_seidel_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/itl/test/gauss_seidel_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/itl/test/gauss_seidel_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 19.0298507463, "max_line_length": 94, "alphanum_fraction": 0.5960784314, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6375204552209613}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\n\nint main(){\n\tEigen::MatrixXd X(2,2);\n\tX << 2,1,-1, 3;\n\tstd::cout << X << std::endl;\n\tEigen::VectorXd y;\n\ty=Eigen::MatrixXd::Map(X.data(),4,1);\n\tstd::cout << y << std::endl;\n\treturn 0;\t\n}\n", "meta": {"hexsha": "2f1802c391b61a7d28b7375ab28bca547363d75c", "size": 232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS2/test.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/PS2/test.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/PS2/test.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": 16.5714285714, "max_line_length": 38, "alphanum_fraction": 0.5818965517, "num_tokens": 81, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6374942656078854}}
{"text": "#include \"problemes.h\"\n#include \"chiffres.h\"\n#include \"utilitaires.h\"\n\n#include <boost/rational.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\ntypedef boost::rational<nombre> fraction;\n\nnamespace {\n    void test(const std::vector<fraction> &n, std::set<nombre> &p) {\n        if (n.size() == 1) {\n            if (n.front().numerator() % n.front().denominator() == 0)\n                p.insert(n.front().numerator() / n.front().denominator());\n            return;\n        }\n        for (nombre i = 0; i < n.size(); ++i)\n            for (nombre j = i + 1; j < n.size(); ++j) {\n                fraction a = n[i];\n                fraction b = n[j];\n                auto m = n;\n                m.erase(std::next(m.begin(), j));\n                m[i] = a + b;\n                test(m, p);\n                m[i] = a * b;\n                test(m, p);\n                if (a >= b) {\n                    m[i] = a - b;\n                    test(m, p);\n                }\n                if (a <= b) {\n                    m[i] = b - a;\n                    test(m, p);\n                }\n                if (a != nullptr) {\n                    m[i] = b / a;\n                    test(m, p);\n                }\n                if (b != nullptr) {\n                    m[i] = a / b;\n                    test(m, p);\n                }\n            }\n    }\n\n}\n\nENREGISTRER_PROBLEME(93, \"Arithmetic expressions\") {\n    // By using each of the digits from the set, {1, 2, 3, 4}, exactly once, and making use of the four arithmetic\n    // operations (+, \u2212, *, /) and brackets/parentheses, it is possible to form different positive integer targets.\n    //\n    // For example,\n    // \n    //      8 = (4 * (1 + 3)) / 2\n    //      14 = 4 * (3 + 1 / 2)\n    //      19 = 4 * (2 + 3) \u2212 1\n    //      36 = 3 * 4 * (2 + 1)\n    //\n    // Note that concatenations of the digits, like 12 + 34, are not allowed.\n    //\n    // Using the set, {1, 2, 3, 4}, it is possible to obtain thirty-one different target numbers of which 36 is the\n    // maximum, and each of the numbers 1 to 28 can be obtained before encountering the first non-expressible number.\n    // \n    // Find the set of four distinct digits, a < b &lt c < d, for which the longest set of consecutive positive integers,\n    // 1 to n, can be obtained, giving your answer as a string: abcd.\n    vecteur iteration;\n    for (nombre n = 1; n < 10000; ++n) iteration.push_back(n);\n    vecteur resultat;\n    nombre maximum = 0;\n    for (nombre a = 0; a < 10; ++a)\n        for (nombre b = a + 1; b < 10; ++b)\n            for (nombre c = b + 1; c < 10; ++c)\n                for (nombre d = c + 1; d < 10; ++d) {\n                    std::vector<fraction> v = {a, b, c, d};\n                    std::set<nombre> e;\n                    test(v, e);\n\n                    vecteur difference;\n                    std::set_difference(iteration.begin(), iteration.end(), e.begin(), e.end(),\n                                        std::inserter(difference, difference.begin()));\n                    if (difference.front() > maximum) {\n                        maximum = difference.front();\n                        resultat = {a, b, c, d};\n                    }\n                }\n\n    return std::to_string(chiffres::conversion_nombre<nombre>(resultat.begin(), resultat.end()));\n}\n", "meta": {"hexsha": "9618bf5543e0e45cbf337ff376c884da9c625008", "size": 3309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme093.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme093.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme0xx/probleme093.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7666666667, "max_line_length": 121, "alphanum_fraction": 0.4517981263, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.7122321903471562, "lm_q1q2_score": 0.6372978673365532}}
{"text": "#include <boost/container/static_vector.hpp>\n#include <gtest/gtest.h>\n#include <glm/glm.hpp>\n\n#include <optional>\n\n#include \"../src/tridexel.h\"\n#include \"../src/IO.h\"\n\nnamespace {\n\tstruct Sphere {\n\t\tglm::vec3 center;\n\t\tfloat radius;\n\t};\n\n\tauto solveQuadraticEquation(double a, double b, double c) -> boost::container::static_vector<double, 2> {\n\t\tconst double discriminat = std::pow(b, 2) - 4 * a * c;\n\t\tif (discriminat < 0)\n\t\t\treturn {};\n\n\t\tif (discriminat == 0)\n\t\t\treturn { -b / 2 * a };\n\n\t\tconst auto x1 = (-b - std::sqrt(discriminat)) / 2 * a;\n\t\tconst auto x2 = (-b + std::sqrt(discriminat)) / 2 * a;\n\t\treturn { x1, x2 };\n\t}\n\n\tvoid extractSphere(int resolution) {\n\t\tconst auto sphere = Sphere{glm::vec3{0, 0, 0}, 5};\n\t\tconst auto box = BoundingBox{sphere.center - sphere.radius, sphere.center + sphere.radius};\n\t\tconst auto triangles = tridexel(box, resolution, [&](Ray ray, HitCallback hc) {\n\t\t\t// from https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-sphere-intersection\n\t\t\t// solve quadratic equation\n\t\t\tconst auto L = ray.origin - sphere.center;\n\t\t\tconst auto a = 1.0;\n\t\t\tconst auto b = 2 * glm::dot(ray.direction, L);\n\t\t\tconst auto c = glm::dot(L, L) - std::pow(sphere.radius, 2);\n\t\t\tconst auto solutions = solveQuadraticEquation(a, b, c);\n\t\t\tfor (const auto& t : solutions) {\n\t\t\t\tconst auto point = ray.origin + (float)t * ray.direction;\n\t\t\t\tconst auto normal = glm::normalize(point - sphere.center);\n\t\t\t\thc(glm::dot(ray.origin, ray.direction) + (float)t, normal);\n\t\t\t}\n\t\t});\n\t\tsaveTriangles(\"sphere\" + std::to_string(resolution) + \".stl\", triangles);\n\t}\n}\n\nTEST(sphere, extract5) {\n\textractSphere(5);\n}\n\nTEST(sphere, extract10) {\n\textractSphere(10);\n}\n\nTEST(sphere, extract100) {\n\textractSphere(100);\n}\n\nTEST(sphere, extract200) {\n\textractSphere(200);\n}\n", "meta": {"hexsha": "d812657c61d8f358331412e95975eb9e1c83aa7c", "size": 1820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sphere.cpp", "max_stars_repo_name": "bernhardmgruber/tridexel", "max_stars_repo_head_hexsha": "3769d8f8be277a3104c12d683f62cd6bd96daf64", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-27T09:27:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-27T09:27:17.000Z", "max_issues_repo_path": "test/sphere.cpp", "max_issues_repo_name": "bernhardmgruber/tridexel", "max_issues_repo_head_hexsha": "3769d8f8be277a3104c12d683f62cd6bd96daf64", "max_issues_repo_licenses": ["BSL-1.0"], "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/sphere.cpp", "max_forks_repo_name": "bernhardmgruber/tridexel", "max_forks_repo_head_hexsha": "3769d8f8be277a3104c12d683f62cd6bd96daf64", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0, "max_line_length": 134, "alphanum_fraction": 0.6637362637, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6372978593435172}}
{"text": "// Testing PPR\n#include \"pauli_product.cpp\"\n#include \"decode.cpp\"\n#include <armadillo>\n#include <chrono>\n#include <iostream>\n#include <stdlib.h>\n\nusing namespace std;\nusing namespace arma;\n\n// Checking if the optimized overlap function is working properly.\nint main()\n{\n  int n = 256;\n  int n_itt = 100;\n  unsigned int x, z;\n\n\n  cx_vec psi, psi_cpy;\n  psi.randn(n);\n  psi = normalise(psi, 2);\n\n  double a1, a2, a3, theta;\n\n  for (int x=0;x<n;x++)\n    {\n      for (int z=0;z<n;z++)\n\t{\n\t  a1 = coeff_a1(0, psi);\n\t  a2 = coeff_a2(0, x, psi);\n\t  a3 = coeff_a3(0, x, z, psi);\t  \n\t  theta = optimized_theta(0, x, z, psi);\n\t  apply_ppr(x, z, theta, psi);\n\t  double my_overlap = optimal_overlap(0, x, z, psi);\n\t  double actual_overlap = coeff_a1(0, psi);\n\t  apply_ppr(x, z, -theta, psi);\n\n\t  if (abs(actual_overlap-my_overlap)>0.00001)\n\t    {\n\t      cout << psi << endl;\n\t      cout << \"x, z=\" << x << \", \" << z << endl;\n\t      cout << \"a1=\" << a1 << endl;\n\t      cout << \"a2=\" << a2 << endl;\n\t      cout << \"a3=\" << a3 << endl;\n\t      cout << \"theta_opt=\" << theta << endl;\n\t      cout << \"optimal_overlap=\" << my_overlap << endl;\n\t      cout << \"actual overlap after the update: \" << actual_overlap << endl;\n\t    }\n\t}\n    }\n   \n}\n", "meta": {"hexsha": "a941455405ecbd4d9a74e280bb3bd7b8bb8f8bf6", "size": 1224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/test_overlap.cpp", "max_stars_repo_name": "ikim-quantum/DecodeInterior", "max_stars_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/test_overlap.cpp", "max_issues_repo_name": "ikim-quantum/DecodeInterior", "max_issues_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/test_overlap.cpp", "max_forks_repo_name": "ikim-quantum/DecodeInterior", "max_forks_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_forks_repo_licenses": ["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.6666666667, "max_line_length": 77, "alphanum_fraction": 0.5637254902, "num_tokens": 389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6372978578744739}}
{"text": "#include <bits/stdc++.h>\n#include <armadillo>\n#include \"logistic_regression.hpp\"\n\nusing namespace std;\n//constructor to initialize number of dependent variables\nLogisticRegression::LogisticRegression(int num){\n    number_of_variables = num;\n    weights = arma::mat(number_of_variables + 1, 1);\n    weights.randu();\n}\n\narma::mat LogisticRegression::predict(arma::mat X_predict){\n    arma::mat x = X_predict;\n    x.insert_cols(0, arma::ones<arma::mat>(X_predict.n_rows, 1));\n    arma::mat regpred = x * weights;\n    \n    for(int i=0;i<X_predict.n_rows;i++)\n    {\n        regpred(i,0)=(1/(1+exp(-regpred(i,0))));\n    }\n    return regpred;\n}\n\narma::mat LogisticRegression::getMatrix() {\n\treturn X_mat;\n}\n\nvoid LogisticRegression::train(arma::mat X_train, arma::mat y_train, float alpha, int epochs){\n        arma::mat x = X_train;\n        x.insert_cols(0, arma::ones<arma::mat>(X_train.n_rows, 1));\n        for(int i=1;i<=epochs;i++)\n        {   \n             //updating weights using gradient descent method\n            arma::mat delta=(x.t() * (predict(X_train)-y_train));\n            weights -= ((alpha * delta)/X_train.n_rows);\n            cout<<\"Epoch completed = \"<<i<<weights<< \" \" << endl;\n        }\n}", "meta": {"hexsha": "a69e0fa9a477e88f6e7e4121e2d15be3905ac01b", "size": 1205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/logistic_regression/logistic_regression.cpp", "max_stars_repo_name": "owais34/Mlplus", "max_stars_repo_head_hexsha": "3c208a44e543e6a0f1d9927139065c19fd7d57c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-16T13:36:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-16T13:36:16.000Z", "max_issues_repo_path": "src/methods/logistic_regression/logistic_regression.cpp", "max_issues_repo_name": "owais34/Mlplus", "max_issues_repo_head_hexsha": "3c208a44e543e6a0f1d9927139065c19fd7d57c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/methods/logistic_regression/logistic_regression.cpp", "max_forks_repo_name": "owais34/Mlplus", "max_forks_repo_head_hexsha": "3c208a44e543e6a0f1d9927139065c19fd7d57c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-28T19:29:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-28T19:29:28.000Z", "avg_line_length": 30.8974358974, "max_line_length": 94, "alphanum_fraction": 0.6290456432, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6372978553469989}}
{"text": "/*\n(c) 2019 M. Werner - Part of the GIS++ tutorial \n- https://www.martinwerner.de/teaching/spatial-cpp\n- https://github.com/mwernerds/spatial-cpp\n\nProgram: Points\nCompile: g++ -I $(BOOST_DIR) -Wall -std=c++11  -o 01_sphere 01_sphere.cpp\n*/\n\n\n#include<iostream>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\nusing namespace boost::geometry;\n\n\ntypedef boost::geometry::model::point\n    <\n        double, 2, boost::geometry::cs::spherical_equatorial<boost::geometry::degree>\n    > spherical_point;\n\n\ntypedef boost::geometry::model::point\n    <\n        double, 3, boost::geometry::cs::cartesian\n    > cartesian_point;\n\n\ntypedef boost::geometry::model::point\n    <\n        double, 2, boost::geometry::cs::geographic<boost::geometry::degree>\n    > geographic_point;\n\n    \nspherical_point amsterdam(4.90, 52.37);\nspherical_point paris(2.35, 48.86);\n\ndouble const earth_radius = 6371; // now km\n\n\nstd::ostream &operator<< (std::ostream &os, const cartesian_point &p)\n{\n    os << \"(\" << get<0>(p) << \";\" << get<1>(p) << \";\" << get<2>(p)<< \")\";\n    return os;\n}\nstd::ostream &operator<< (std::ostream &os, const geographic_point &p)\n{\n    os << \"(\" << get<0>(p) << \";\" << get<1>(p) << \")\";\n    return os;\n}\n\n\n\n\nint main(int argc, char **argv)\n{\n    std::cout << \"Distance in miles: \" << distance(amsterdam, paris) * earth_radius << std::endl;\n    cartesian_point paris3d, amsterdam3d;\n    transform(paris, paris3d);\n    transform(amsterdam, amsterdam3d);\n    \n    std::cout << \"Paris 3D (on unit sphere)\" << paris3d << std::endl;\n    std::cout << \"Amsterdam 3D (on unit sphere)\" << amsterdam3d << std::endl;\n    std::cout << \"Distance (drill hole): \" << distance(paris3d,amsterdam3d)*earth_radius << \" miles\" << std::endl;\n\n    // Let us test some intuitive things like north to south pole\n\n    // transformer: a functional trick\n    auto tf = [](const spherical_point &p)->cartesian_point { cartesian_point ret; transform(p,ret); return ret;};\n    \n    std::cout << \"North Pole: \" << tf(spherical_point(0,90)) << std::endl;\n    std::cout << \"South Pole: \" << tf(spherical_point(0,-90)) << std::endl;\n    std::cout << \"Distance: \" << distance(tf(spherical_point(0,90)), tf(spherical_point(0,-90)))*earth_radius << std::endl;\n\n\n    // an \"external\" cast without recalculating (which is not supported!)\n    auto cast = [](const spherical_point &p) {return geographic_point(get<0>(p),get<1>(p));};\n    std::cout << \"Amsterdam (geo)\" << cast(amsterdam) << std::endl;\n    std::cout << \"Paris (geo)\" << cast(paris) << std::endl;\n    // Geodesic distance\n    std::cout << distance(cast(amsterdam),cast(paris)) << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "0f08c7b64738fb7799b4ba93bc8e1c4ef1b36973", "size": 2708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "02_geo/01_sphere.cpp", "max_stars_repo_name": "mwernerds/spatial-cpp", "max_stars_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02_geo/01_sphere.cpp", "max_issues_repo_name": "mwernerds/spatial-cpp", "max_issues_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02_geo/01_sphere.cpp", "max_forks_repo_name": "mwernerds/spatial-cpp", "max_forks_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-08T23:57:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T23:57:30.000Z", "avg_line_length": 31.1264367816, "max_line_length": 123, "alphanum_fraction": 0.6414327917, "num_tokens": 778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6372673578693449}}
{"text": "#ifndef DISTRIBUTION_HPP\n#define DISTRIBUTION_HPP\n\n#include <math.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <iostream>\n#include <memory>\n#include <random>\n#include <vector>\n\nnamespace ds {\nenum DIRECTION { INCREASE, DECREASE };\nclass DrProcess {\n public:\n  int totallClass;\n  Eigen::VectorXd params;\n  int sum;\n  double alpha;  // para for  new class;\n\n  DrProcess(double alpha) : totallClass(0), alpha(alpha), sum(0) {}\n\n  double calProb(int classNum) {\n    if (classNum > totallClass)\n      return 0.0;\n    else if (classNum == totallClass)\n      return alpha / (sum + alpha);\n    else\n      return params(classNum) / (sum + alpha);\n  }\n  bool update(int classNum, DIRECTION drc) {\n    if (classNum >= totallClass) {\n      return false;\n    }\n    if (drc == INCREASE) {\n      params(classNum)++;\n      sum++;\n      return true;\n    } else {\n      params(classNum)--;\n      sum--;\n      if (params(classNum) < 0)\n        params(classNum) = 0;\n      if (sum < 0)\n        sum = 0;\n      return true;\n    }\n  }\n  bool newClass() {\n    totallClass++;\n    params.resize(totallClass);\n    params(totallClass - 1) = 1.0;\n    sum++;\n  }\n};\nclass DirDS {\n private:\n  int totallClass;  // num of categories;\n  Eigen::VectorXd params;\n  Eigen::VectorXd samples;\n  std::gamma_distribution<double> gamma;\n  std::default_random_engine generator;\n\n public:\n  explicit DirDS(int totallClass)\n      : totallClass(totallClass),\n        params(Eigen::VectorXd::Zero(totallClass)),\n        samples(Eigen::VectorXd::Zero(totallClass)),\n        gamma(1.0, 1.0),\n        generator() {}\n\n  bool update(int classNum) {\n    if (classNum >= totallClass) {\n      std::cerr << \"more than totallClass\\n\";\n      return false;\n    } else {\n      ++params(classNum);\n      return true;\n    }\n  }\n\n  Eigen::VectorXd sampling() {\n    samples.resize(totallClass);\n    for (int i = 0; i < totallClass; i++) {\n      gamma.param(std::gamma_distribution<double>::param_type(params(i), 1.0));\n      samples(i) = gamma(generator);\n    }\n    double sum = samples.sum();\n    samples = samples / sum;\n    return samples;\n  }\n};\n\nclass CatDS {\n private:\n  int totallClass;\n  Eigen::VectorXd params;\n  DirDS dir;\n\n public:\n  CatDS(int totallClass)\n      : totallClass(totallClass),\n        params(Eigen::VectorXd::Zero(totallClass)),\n        dir(totallClass) {}\n\n  bool update(int classNum) {\n    dir.update(classNum);\n    params = dir.sampling();\n    return true;\n  }\n  double calProb(int classNum) {\n    if (classNum >= totallClass)\n      return 0.0;\n    else {\n      return params(classNum);\n    }\n  }\n  void maxPro(int& classNum, double& pro) {\n    Eigen::VectorXd::Index maxClass;\n    pro = params.maxCoeff(&maxClass);\n    classNum = int(maxClass);\n    return;\n  }\n};\n};  // namespace ds\n\n#endif  // DISTRIBUTION_HPP\n", "meta": {"hexsha": "78cc7c25d34bbbe89588bb5f95b5b14e9f92ee8b", "size": 2791, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "object_slam/include/distribution.hpp", "max_stars_repo_name": "tiev-tongji/quadric_slam", "max_stars_repo_head_hexsha": "2789cf553d947c87bd601659e60c50b63be09b76", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2019-07-28T15:41:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T07:48:47.000Z", "max_issues_repo_path": "object_slam/include/distribution.hpp", "max_issues_repo_name": "lucianzhong/quadric_slam", "max_issues_repo_head_hexsha": "f1b8f98b1c8d6d4cb36d238ec3a93cb2090611fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T07:19:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-25T09:08:49.000Z", "max_forks_repo_path": "object_slam/include/distribution.hpp", "max_forks_repo_name": "lucianzhong/quadric_slam", "max_forks_repo_head_hexsha": "f1b8f98b1c8d6d4cb36d238ec3a93cb2090611fc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-08-05T02:03:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T02:36:29.000Z", "avg_line_length": 21.8046875, "max_line_length": 79, "alphanum_fraction": 0.614833393, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6372673497140416}}
{"text": "#pragma once\n\n#include <array>\n#include <cstdint>\n#include <cmath>\n#include <crest/geometry/vertex.hpp>\n#include <crest/quadrature/rules.hpp>\n\n#include <Eigen/Dense>\n\nnamespace crest\n{\n    template <typename Scalar>\n    class ReferenceTriangleTransform\n    {\n    public:\n        ReferenceTriangleTransform(Vertex<Scalar> v0, Vertex<Scalar> v1, Vertex<Scalar> v2);\n\n        Vertex<Scalar> transform_from_reference(const Scalar & x, const Scalar & y) const;\n        Scalar absolute_determinant() const { return _absdet; }\n\n        Eigen::Matrix<Scalar, 2, 2> jacobian() const;\n\n    private:\n        Vertex<Scalar> _v0;\n        Vertex<Scalar> _v1;\n        Vertex<Scalar> _v2;\n        Scalar _absdet;\n    };\n\n    template <typename S>\n    ReferenceTriangleTransform<S>::ReferenceTriangleTransform(Vertex<S> v0,\n                                                              Vertex<S> v1,\n                                                              Vertex<S> v2)\n            : _v0(v0), _v1(v1), _v2(v2)\n    {\n        _absdet = S(1.0 / 4.0) * std::abs(_v1.x * _v2.y - _v1.y * _v2.x);\n    }\n\n    /**\n     *The reference triangle the quadrature rules are defined on is given by the vertices\n     *(-1, 1), (-1, -1), (1, -1),\n     *so for a triangle with corners A, B, C, we have that each coordinate x in R^2 is given by the relation\n     *\n     * x = 1/2 (A + B) + 1/2 * (A - C) z_1 + 1/2 * (B - C) z_2\n     *\n     * for a reference coordinate z = (z_1, z_2) in R^2. This implies the following mapping:\n     *  A <-> ( 1, -1)\n     *  B <-> (-1,  1)\n     *  C <-> (-1, -1)\n     */\n    template <typename S>\n    Vertex<S> ReferenceTriangleTransform<S>::transform_from_reference(const S & x, const S & y) const\n    {\n\n        return S(0.5) * (_v0 + x * _v1 + y * _v2);\n    }\n\n    template <typename Scalar>\n    Eigen::Matrix<Scalar, 2, 2> ReferenceTriangleTransform<Scalar>::jacobian() const\n    {\n        Eigen::Matrix<Scalar, 2, 2> J;\n        J(0, 0) = Scalar(0.5) * _v1.x;\n        J(0, 1) = Scalar(0.5) * _v2.x;\n        J(1, 0) = Scalar(0.5) * _v1.y;\n        J(1, 1) = Scalar(0.5) * _v2.y;\n        return J;\n    };\n\n    /**\n     *\n     * Returns an instance of a ReferenceTriangleTransform<Scalar>, which transforms points from\n     * the reference triangle used by triquad to points in the triangle defined by the vertices (a, b, c).\n     *\n     * @param a\n     * @param b\n     * @param c\n     * @return An instance of ReferenceTriangleTransform<Scalar>.\n     */\n    template <typename Scalar>\n    ReferenceTriangleTransform<Scalar> triquad_transform(const Vertex<Scalar> & a,\n                                                         const Vertex<Scalar> & b,\n                                                         const Vertex<Scalar> & c)\n    {\n        const auto v0 = a + b;\n        const auto v1 = a - c;\n        const auto v2 = b - c;\n\n        return ReferenceTriangleTransform<Scalar>(v0, v1, v2);\n    };\n\n    /**\n     * Computes the integral of the function f(x, y) -> R on the reference triangled defined by the vertices\n     * (-1, 1), (-1, -1), (1, -1).\n     * @param f\n     * @return\n     */\n    template <unsigned int Strength, typename Scalar, typename Function2D>\n    constexpr inline Scalar triquad_ref(const Function2D & f)\n    {\n        using quadrature = ::crest::quadrature_rules::quadrature<Scalar, Strength>;\n        constexpr auto quad = quadrature();\n\n        Scalar result = static_cast<Scalar>(0.0);\n        for (unsigned int i = 0; i < quadrature::num_points; ++i)\n        {\n            result += quad.w[i] * f(quad.x[i], quad.y[i]);\n        }\n\n        return result;\n    };\n\n\n    /**\n     * Computes the integral of the function f over the triangle determined by the vertices a, b and c,\n     * using Gauss quadrature rules of the given Strength.\n     *\n     * The Strength of the quadrature rule determines the highest degree polynomial that the quadrature rule\n     * is able to integrate *exactly*. For example, a Strength of 4 indicates that triquad computes the exact\n     * integral of any polynomial function of *total degree* 4.\n     * @param f A callable function f(x, y) that operates on real numbers.\n     * @param a\n     * @param b\n     * @param c\n     * @return\n     */\n    template <unsigned int Strength, typename Scalar, typename Function2D>\n    constexpr inline Scalar triquad(\n            const Function2D & f,\n            const Vertex<Scalar> & a,\n            const Vertex<Scalar> & b,\n            const Vertex<Scalar> & c)\n    {\n        const auto transform = triquad_transform(a, b, c);\n        const auto f_transformed = [&f, &transform] (auto x, auto y)\n        {\n            const auto coords = transform.transform_from_reference(x, y);\n            return f(coords.x, coords.y);\n        };\n        return transform.absolute_determinant() * triquad_ref<Strength, Scalar>(f_transformed);\n    };\n}\n", "meta": {"hexsha": "07d1dd14cbf7de5f6e72af99d800b3a095014528", "size": 4843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crest/quadrature/triquad.hpp", "max_stars_repo_name": "Andlon/crest", "max_stars_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crest/quadrature/triquad.hpp", "max_issues_repo_name": "Andlon/crest", "max_issues_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-01-24T10:45:27.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-27T16:21:37.000Z", "max_forks_repo_path": "include/crest/quadrature/triquad.hpp", "max_forks_repo_name": "Andlon/crest", "max_forks_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8671328671, "max_line_length": 109, "alphanum_fraction": 0.5711335949, "num_tokens": 1272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048444, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6371376051249352}}
{"text": "#include <iostream>\n#include \"problem_0001.h\"\n\nusing namespace euler;\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE Project_Euler_Problem_0001\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_CASE(sum_multiples_of_3_or_5_below_1000) \n{\n    const std::vector<int> multof   = {3,5};\n    constexpr int below             = 1000;\n    int res = sum_mults(multof, below);\n    BOOST_TEST( 233168 == res );\n}", "meta": {"hexsha": "68d2b4acf207017e66b7d93498003786b0a3a110", "size": 417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/src/test_0001.cpp", "max_stars_repo_name": "tdaileygithub/project_euler", "max_stars_repo_head_hexsha": "631e098f6e974a156a254f8c1a58b90ae1c2f400", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/src/test_0001.cpp", "max_issues_repo_name": "tdaileygithub/project_euler", "max_issues_repo_head_hexsha": "631e098f6e974a156a254f8c1a58b90ae1c2f400", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/src/test_0001.cpp", "max_forks_repo_name": "tdaileygithub/project_euler", "max_forks_repo_head_hexsha": "631e098f6e974a156a254f8c1a58b90ae1c2f400", "max_forks_repo_licenses": ["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.0625, "max_line_length": 57, "alphanum_fraction": 0.7314148681, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6371375968031426}}
{"text": "////////////////////////////////////////////////////////////////////////////////////////////////////\n//                               This file is part of CosmoScout VR                               //\n//      and may be used under the terms of the MIT license. See the LICENSE file for details.     //\n//                        Copyright: (c) 2019 German Aerospace Center (DLR)                       //\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#ifndef CS_UTILS_CONVERSIONS_HPP\n#define CS_UTILS_CONVERSIONS_HPP\n\n#include \"cs_utils_export.hpp\"\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#include <glm/glm.hpp>\n#include <glm/gtc/quaternion.hpp>\n\n/// This namespace contains utility functions for converting numbers between different units of\n/// measuring. Most of the coordinate system conversion methods are based on the code from the\n/// excellent book \"3D Engine Design for Virtual Globes\" by Patrick Cozzi and Kevin Ring\n/// (http://virtualglobebook.com/).\nnamespace cs::utils::convert {\n\ntemplate <typename T>\nT lightyearsToMeters(T lightyears) {\n  return lightyears * 9460730472580800.0;\n}\n\ntemplate <typename T>\nT metersToLightyears(T meters) {\n  return meters / 9460730472580800.0;\n}\n\n/// Converts AU to meters. One AU is equivalent to the average distance between the Earth and the\n///// Sun.\ntemplate <typename T>\nT astronomicalUnitsToMeters(T astronomicalUnits) {\n  return astronomicalUnits * 149597870700.0;\n}\n\n/// Converts meters to AU. One AU is equivalent to the average distance between the Earth and the\n/// Sun.\ntemplate <typename T>\nT metersToAstronomicalUnits(T meters) {\n  return meters / 149597870700.0;\n}\n\ntemplate <typename T>\nT toRadians(T degrees) {\n  return static_cast<T>(degrees * glm::pi<double>() / 180.0);\n}\n\ntemplate <typename T>\nT toDegrees(T radians) {\n  return static_cast<T>(radians * 180.0 / glm::pi<double>());\n}\n\n/// Projects an arbitrary cartesian point to the surface of an origin-centered ellipsoid with the\n/// given radii. The projection happens towards the center of the ellipsoid.\nCS_UTILS_EXPORT glm::dvec3 scaleToGeocentricSurface(\n    glm::dvec3 const& cartesian, glm::dvec3 const& radii);\n\n/// Projects an arbitrary cartesian point to the surface of an origin-centered ellipsoid with the\n/// given radii. The projection happens along the surface normal of the ellipsoid. This is\n/// potentially a rather expensive operation, as it involes an iterative search for the correct\n/// surface normal.\nCS_UTILS_EXPORT glm::dvec3 scaleToGeodeticSurface(\n    glm::dvec3 const& cartesian, glm::dvec3 const& radii);\n\n/// Computes longitude and geodetic latitude for a given surface point on an origin-centered\n/// ellipsoid with the given radii.\nCS_UTILS_EXPORT glm::dvec2 surfaceToLngLat(glm::dvec3 const& cartesian, glm::dvec3 const& radii);\n\n/// Computes longitude and geodetic latitude for an arbitrary cartesian point relative to a\n/// origin-centered ellipsoid with the given radii. This is potentially a rather expensive\n/// operation, as it involes scaleToGeodeticSurface().\nCS_UTILS_EXPORT glm::dvec2 cartesianToLngLat(glm::dvec3 const& cartesian, glm::dvec3 const& radii);\n\n/// Same as above, but returns the distance to the surface of the ellipsoid as well.\nCS_UTILS_EXPORT glm::dvec3 cartesianToLngLatHeight(\n    glm::dvec3 const& cartesian, glm::dvec3 const& radii);\n\n/// Transforms longitude and geodetic latitude and elevation height to cartesian (x,y,z)\n/// coordinates for an origin-centered ellipsoid with the given radii. Height is an\n/// offset along the geodetic normal of the ellipsoid at lngLat.\nCS_UTILS_EXPORT glm::dvec3 toCartesian(\n    glm::dvec2 const& lngLat, glm::dvec3 const& radii, double height = 0.0);\n\n/// Returns the geodetic normal vector with unit length at geodetic coordinates (lng, lat) lngLat.\nCS_UTILS_EXPORT glm::dvec3 lngLatToNormal(glm::dvec2 const& lngLat);\n\n/// Returns the geodetic normal vector with unit length for a given point on the surface of an\n/// origin-centered ellipsoid with the given radii.\nCS_UTILS_EXPORT glm::dvec3 surfaceToNormal(glm::dvec3 const& cartesian, glm::dvec3 const& radii);\n\n/// Returns the geodetic normal vector with unit length for an arbitrary cartesian point relative to\n/// an origin-centered ellipsoid with the given radii. This is potentially a rather expensive\n/// operation, as it involes scaleToGeodeticSurface().\nCS_UTILS_EXPORT glm::dvec3 cartesianToNormal(glm::dvec3 const& cartesian, glm::dvec3 const& radii);\n\n/// Time in CosmoScout VR is passed around in different formats.\n/// * Strings usually store time in the ISO format YYYY-MM-DDTHH:MM:SS.fffZ. The 'Z' suffix is not\n///   really required on the C++ side, as time strings are always considered to be in UTC. This\n///   format is also directly convertible to JavaScript Dates, here however the 'Z' is required!\n///   Else the Date object will be in your local time zone. So it's a good practice to always append\n///   the 'Z'.\n/// * boost::posix_time::ptime is used for conversions and is also always in UTC.\n/// * SPICE time is stored in doubles representing Barycentric Dynamical Time (TDB, seconds since\n///   2000-01-01 12:00:00). Note that this is not the same as UTC seconds since 2000-01-01 12:00:00\n///   because TDB considers leap seconds. The conversion methods below take this into account.\nnamespace time {\n\n/// Converts boost::posix_time::ptime to spice time, which is defined by the Barycentric Dynamical\n/// Time. Be aware, that SPICE kernels with leap seconds have to be loaded for this method to work.\n/// This means, SolarSystem::init() must have been called before.\nCS_UTILS_EXPORT double toSpice(boost::posix_time::ptime const& tIn);\n\n/// Converts a time string to spice time, which is defined by the Barycentric Dynamical Time. The\n/// string can be in the format YYYY-MM-DD HH:MM:SS.fff, YYYY-MM-DDTHH:MM:SS.fff, or\n/// YYYY-MM-DDTHH:MM:SS.fffZ and is always interpreted as UTC. Be aware, that SPICE kernels with\n/// leap seconds have to be loaded for this method to work. This means, SolarSystem::init() must\n/// have been called before.\nCS_UTILS_EXPORT double toSpice(std::string const& tIn);\n\n/// Converts a time string to boost::posix_time time. The string can be in the format\n/// YYYY-MM-DD HH:MM:SS.fff, YYYY-MM-DDTHH:MM:SS.fff, or YYYY-MM-DDTHH:MM:SS.fffZ and is always\n/// interpreted as UTC.\nCS_UTILS_EXPORT boost::posix_time::ptime toPosix(std::string const& tIn);\n\n/// Converts a Barycentric Dynamical Time to boost::posix_time::ptime. Be aware, that SPICE kernels\n/// with leap seconds have to be loaded for this method to work. This means, SolarSystem::init()\n/// must have been called before.\nCS_UTILS_EXPORT boost::posix_time::ptime toPosix(double tIn);\n\n/// Converts a Barycentric Dynamical Time time to a time string in the format\n/// YYYY-MM-DDTHH:MM:SS.fffZ. Be aware, that SPICE kernels with leap seconds have to be loaded for\n/// this method to work. This means, SolarSystem::init() must have been called before.\nCS_UTILS_EXPORT std::string toString(double tIn);\n\n/// Converts a boost::posix_time::ptime time to a time string in the format\n/// YYYY-MM-DDTHH:MM:SS.fffZ.\nCS_UTILS_EXPORT std::string toString(boost::posix_time::ptime const& tIn);\n\n} // namespace time\n\n} // namespace cs::utils::convert\n\n#endif // CS_UTILS_CONVERSIONS_HPP\n", "meta": {"hexsha": "546490eca2646b33bce9a3c0c479014f6aa16539", "size": 7393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cs-utils/convert.hpp", "max_stars_repo_name": "FellegaraR/cosmoscout-vr", "max_stars_repo_head_hexsha": "e04e1ac9c531106693a965bb03d3064f3a6179c6", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "MIT"], "max_stars_count": 302.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T08:05:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T22:35:21.000Z", "max_issues_repo_path": "src/cs-utils/convert.hpp", "max_issues_repo_name": "Tubbz-alt/cosmoscout-vr", "max_issues_repo_head_hexsha": "d9fe671857b1ca906febddb59175422fc083441a", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "MIT"], "max_issues_count": 230.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T13:26:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T11:21:06.000Z", "max_forks_repo_path": "src/cs-utils/convert.hpp", "max_forks_repo_name": "Tubbz-alt/cosmoscout-vr", "max_forks_repo_head_hexsha": "d9fe671857b1ca906febddb59175422fc083441a", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "MIT"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2019-07-22T08:00:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T10:55:17.000Z", "avg_line_length": 49.6174496644, "max_line_length": 100, "alphanum_fraction": 0.7279859326, "num_tokens": 1811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6371375968031426}}
{"text": "#include <Eigen/Dense>\n#include <ancse/cfl_condition.hpp>\n#include <gtest/gtest.h>\n\n//// ANCSE_CUT_START_TEMPLATE\n// This will check the CFL condition for Burgers equation.\nvoid check_cfl_condition(const CFLCondition &cfl_condition,\n                         const Grid &grid,\n                         double cfl_number) {\n    int n_ghost = grid.n_ghost;\n    int n_cells = grid.n_cells;\n\n    Eigen::VectorXd u(n_cells);\n    for (int i = 0; i < n_cells; ++i) {\n        u[i] = -i * i;\n    }\n    double max_abs_u = (n_cells - n_ghost - 1) * (n_cells - n_ghost - 1);\n\n    for (int i = 0; i < n_ghost; ++i) {\n        u[i] = 2.0 * max_abs_u;\n        u[n_cells - n_ghost + i] = 2.0 * max_abs_u;\n    }\n\n    double dt_cfl_approx = cfl_condition(u);\n    double dt_cfl_exact = cfl_number * grid.dx / max_abs_u;\n\n    ASSERT_DOUBLE_EQ(dt_cfl_approx, dt_cfl_exact);\n}\n\nTEST(CFLCondition, Example) {\n    auto n_ghost = 2;\n    auto n_cells = 10 + 2 * n_ghost;\n    auto grid = Grid({0.9, 1.0}, n_cells, n_ghost);\n    auto model = Model();\n    double cfl_number = 0.5;\n\n    auto cfl_condition = StandardCFLCondition(grid, model, cfl_number);\n    check_cfl_condition(cfl_condition, grid, cfl_number);\n}\n//// ANCSE_END_TEMPLATE\n", "meta": {"hexsha": "5cce30b39c2b53c967e251b17f3ae154dec10890", "size": 1207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series1_solution/fvm_scalar_1d/tests/test_cfl_condition.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series1_solution/fvm_scalar_1d/tests/test_cfl_condition.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series1_solution/fvm_scalar_1d/tests/test_cfl_condition.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": 29.4390243902, "max_line_length": 73, "alphanum_fraction": 0.6263463132, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808498, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6371375953481353}}
{"text": "#include <PCP/Common/Option.h>\n#include <PCP/Common/Log.h>\n#include <PCP/Common/Progress.h>\n#include <PCP/Common/String.h>\n\n#include <PCP/Geometry/Geometry.h>\n#include <PCP/Geometry/PLY.h>\n\n#include <PCP/SpacePartitioning/KdTree.h>\n\n#include <Eigen/Eigenvalues>\n\nusing namespace pcp;\n\nint main(int argc, char *argv[])\n{\n    Option opt(argc, argv);\n    const String in_input  = opt.get_string(\"input\",  \"i\").set_required();\n    const String in_output = opt.get_string(\"output\", \"o\").set_default(\"output\");\n    const Scalar in_scale  = opt.get_float( \"scale\"     ).set_default(0.01);\n    const int    in_iter   = opt.get_int(   \"iter\"      ).set_default(30);\n    const int    in_every  = opt.get_int(   \"every\"     ).set_default(30);\n\n    bool ok = opt.ok();\n    if(!ok) return 1;\n    info() << opt;\n\n    Geometry g;\n    ok = PLY::load(in_input, g);\n    if(!ok) return 1;\n    PCP_ASSERT(g.has_normals());\n    Geometry g2 = g;\n\n    const auto aabb = g.aabb();\n    const auto aabb_diag = aabb.diagonal().norm();\n    const auto radius = in_scale * aabb_diag;\n    info() << \"radius = \" << radius;\n\n    auto prog = Progress(in_iter);\n    const int digits = std::to_string(in_iter).size();\n\n    for(int iter=1; iter<=in_iter; ++iter)\n    {\n        g.build_kdtree();\n\n        #pragma omp parallel for\n        for(int i=0; i<g.size(); ++i)\n        {\n            Matrix3 C    = Matrix3::Zero();\n            Vector3 m    = Vector3::Zero();\n            Scalar sum_w = 0;\n\n            for(int j : g.kdtree().range_neighbors(g[i], radius))\n            {\n                const Vector3 p = g[j] - g[i];\n\n                Scalar w = p.norm() / radius;\n                w = (w*w - 1);\n                w = w*w;\n\n                C += w * p * p.transpose();\n                m += w * p;\n                sum_w += w;\n            }\n            m /= sum_w;\n            C = C/sum_w - m * m.transpose();\n\n            Eigen::SelfAdjointEigenSolver<Matrix3> solver(C);\n            Vector3 N = solver.eigenvectors().col(0); // vector of least eigenvalue\n\n            // re-orient if necessary (used only for rendering)\n            if(N.dot(g.normal(i)) < 0) N *= -1;\n\n            const Vector3 P = g[i] + m;\n\n            // projection on plane {P,N}\n            g2.point(i) = g[i] - N.dot(g[i] - P) * N;\n            g2.normal(i) = N;\n        }\n        std::swap(g, g2);\n\n        // save\n        if(iter % in_every == 0 || iter == in_iter)\n        {\n            PLY::save(in_output + \"_\" + str::to_string(iter,digits) + \".ply\", g, false);\n        }\n\n        ++prog;\n    }\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "2cbf016c19f3e62f63eb6cb65880fb2c73e60473", "size": 2556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "figures/app/Figures/ComputeFlowPlane.cpp", "max_stars_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_stars_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T18:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T12:42:52.000Z", "max_issues_repo_path": "figures/app/Figures/ComputeFlowPlane.cpp", "max_issues_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_issues_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-12T08:51:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T09:38:17.000Z", "max_forks_repo_path": "figures/app/Figures/ComputeFlowPlane.cpp", "max_forks_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_forks_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T08:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T11:40:21.000Z", "avg_line_length": 26.9052631579, "max_line_length": 88, "alphanum_fraction": 0.515258216, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6371375912552806}}
{"text": "// Exercise generating random data\n\n#include \"GHFilter.h\"\n\n#include <iostream>\n#include <vector>\n#include <random>\n#include <cmath>\n#include <Eigen/Dense>\n#include <sciplot/sciplot.hpp>\n\nusing namespace sciplot;\n\nstd::vector<float> randomised_data(std::vector<float>& data, float noise_factor){\n    std::random_device rd;\n    std::mt19937 gen(rd());\n\n    std::normal_distribution<float> dis(2, 4);\n    std::vector<float> randomised;\n    for(auto val: data){\n        randomised.push_back(val + dis(gen));\n    }\n\n    return randomised;\n}\n\nstd::vector<float> data_gen(float start, float step, int count){\n    std::vector<float> data;\n    float accel = 9;\n    for(int i = 0; i < count; i++){\n        data.push_back(start + accel * pow(i, 2));\n    }\n    return data;\n}\nint main(){\n    // get data\n    std::vector<float> data_ = data_gen(10, 0, 20);\n    std::vector<float> data = randomised_data(data_, 2);\n\n    GHFilter filter(data, 150 ,0.5, 0.4, 0.04, 1);\n\n    std::vector<float> filtered = filter.get_sensored();\n\n    Vec x = linspace(0.0, data.size(), data.size());\n\n    Plot plt;\n    plt.palette(\"set2\");\n    plt.legend()\n        .atOutsideBottom()\n        .displayHorizontal()\n        .displayExpandWidthBy(2);\n    plt.drawPoints(x, data).label(\"Measurements\");\n    plt.drawCurve(x, filtered).label(\"Filtered Data\");\n    plt.save(\"./plots/test_2_accel.pdf\");\n    plt.save(\"./plots/test_2_accel.png\");\n    plt.show();\n\n}\n", "meta": {"hexsha": "0523a436072b8ce54d6f0d3bea0dca30a67e579c", "size": 1421, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_2.cpp", "max_stars_repo_name": "SuhrudhSarathy/filters", "max_stars_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_2.cpp", "max_issues_repo_name": "SuhrudhSarathy/filters", "max_issues_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_2.cpp", "max_forks_repo_name": "SuhrudhSarathy/filters", "max_forks_repo_head_hexsha": "25b025a97e1edcf31a0195cb956c41f6d82e7764", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0847457627, "max_line_length": 81, "alphanum_fraction": 0.6347642505, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6371375905277769}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/ml/clustering/spectral_embedding.hpp>\n#include <boost/program_options.hpp>\n\nusing namespace boost;\nusing namespace frovedis;\n\nint main(int argc, char** argv) {\n  use_frovedis use(argc,argv);\n\n  using namespace boost::program_options;\n\n  options_description opt(\"option\");\n  opt.add_options()\n      (\"help,h\", \"produce help message\")\n      (\"input,i\" , value<std::string>(), \"input rowmajor matrix data.\")\n      (\"n-components\" , value<int>(), \"number of eigenvectors to use for the spectral embedding.[default = 2]\")\n      (\"gamma,g\", value<double>(), \"kernel coefficient for rbf, poly, sigmoid, laplacian and chi2 kernels.[default = 1.0]\")\n      (\"norm-laplacian\", value<bool>(), \"[default: true]\")\n      (\"precomputed\", value<bool>(), \"[default: false]\")\n      (\"drop-first\", value<bool>(), \"[default: false]\")\n      (\"mode\", value<int>(), \"[default: 1]\")\n      (\"verbose\", \"set loglevel to DEBUG\")\n      (\"verbose2\", \"set loglevel to TRACE\");\n\n  variables_map argmap;\n  store(command_line_parser(argc,argv).options(opt).allow_unregistered().\n        run(), argmap);\n  notify(argmap);\n\n  int n_comp = 2;\n  double gamma = 1.0;\n  bool norm_laplacian = true;\n  bool precomputed = false;\n  bool drop_first = false;\n  int mode = 1;\n  std::string data_p;\n\n  if(argmap.count(\"help\")){\n    std::cerr << opt << std::endl;\n    exit(1);\n  }  \n  if(argmap.count(\"n-components\")){\n    n_comp = argmap[\"n-components\"].as<int>();\n  }\n  if(argmap.count(\"gamma\")){\n    gamma = argmap[\"gamma\"].as<double>();\n  }\n  if(argmap.count(\"norm-laplacian\")){\n    norm_laplacian = argmap[\"norm-laplacian\"].as<bool>();\n  }\n  if(argmap.count(\"precomputed\")){\n    precomputed = argmap[\"precomputed\"].as<bool>();\n  }  \n  if(argmap.count(\"drop-first\")){\n    drop_first = argmap[\"drop-first\"].as<bool>();\n  }\n  if(argmap.count(\"mode\")){\n    mode = argmap[\"mode\"].as<int>();\n  }\n  if(argmap.count(\"input\")){\n    data_p = argmap[\"input\"].as<std::string>();\n  }else {\n    std::cerr << \"input is not specified\" << std::endl;\n    std::cerr << opt << std::endl;\n    exit(1);\n  }\n\n  auto mat = make_rowmajor_matrix_load<double>(data_p); //./test_data\n\n  // hyper-parameters\n  time_spent embed(INFO);\n  embed.lap_start();\n  auto model = spectral_embedding<double>(std::move(mat), n_comp, norm_laplacian,\n                                          precomputed, drop_first, gamma, mode);  \n  embed.lap_stop();\n  embed.show_lap(\"embedding time: \");\n\n  std::cout << \"\\n embedding matrix: \\n\";\n  model.embed_matrix.debug_print();\n  return 0;\n}\n", "meta": {"hexsha": "aaabb84ee9c739a546940f85aba01aae3e2f2c15", "size": 2541, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/spectral_embedding/embedding.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "samples/spectral_embedding/embedding.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "samples/spectral_embedding/embedding.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 30.6144578313, "max_line_length": 123, "alphanum_fraction": 0.6284927194, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6371361841381702}}
{"text": "\n#include \"graph.h\"\n\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\nnamespace filters::pose_graph {\n\nAbstractFactor::~AbstractFactor() {}\n\nGraph::Graph()\n\t: _x0(values::Zero(1)), _sol(values::Zero(1)), _sol_cov(hessian::Zero(1, 1)), _factors({}),\n\t  _factor_counter(0) {}\n\nGraph::~Graph() {\n\tfor (auto f : _factors) {\n\t\tdelete f;\n\t}\n}\n\nint Graph::add(AbstractFactor* f) {\n\tf->id = _factor_counter++;\n\t_factors.push_back(f);\n\treturn f->id;\n}\n\ndouble Graph::eval(const values& x) {\n\tdouble sum = 0.0;\n\tfor (auto f : _factors)\n\t\tsum += f->eval(x);\n\treturn sum;\n}\n\nvoid Graph::solve(const values& x0, double alpha, int maxiters, double tol) {\n\t_x0 = x0;\n\tvalues x = x0;\n\tdouble error = 2 * tol;\n\tint i = 0;\n\tint N = x0.size();\n\twhile (error > tol && i < maxiters) {\n\t\tvalues grad = values::Zero(N);\n\t\thessian hess = hessian::Zero(N, N);\n\t\tfor (auto f : _factors) {\n\t\t\tgrad += f->gradient_at(x);\n\t\t\thess += f->hessian_at(x);\n\t\t}\n\t\tfor (int j = 0; j < N; j++) {\n\t\t\t// Presumably we have no factors affecting this variable\n\t\t\tif (hess(j, j) == 0)\n\t\t\t\thess(j, j) = 0.001; // avoid singular matrix\n\t\t}\n\t\tx -= alpha * (hess.inverse() * grad);\n\t\terror = sqrt(grad.transpose() * grad);\n\t\ti += 1;\n\t\tif (i % 100 == 0)\n\t\t\tstd::cout << \"Graph::solve Iteration \" << i << \": \" << error << std::endl;\n\t}\n\t_sol = x;\n\n\thessian hess = hessian::Zero(N, N);\n\tfor (auto f : _factors)\n\t\thess += f->hessian_at(_sol);\n\tfor (int j = 0; j < N; j++) {\n\t\tif (hess(j, j) == 0)\n\t\t\thess(j, j) = 0.001; // Again, avoid singular matrix\n\t}\n\t_sol_cov = hess.inverse();\n}\n\nvalues Graph::x0() {\n\treturn _x0;\n}\n\nvalues Graph::solution() {\n\treturn _sol;\n}\n\nhessian Graph::covariance() {\n\treturn _sol_cov;\n}\n\nvoid Graph::deleteFactor(int id) {\n\tauto it = _factors.begin();\n\twhile (it != _factors.end()) {\n\t\tif ((*it)->id == id) {\n\t\t\tdelete *it;\n\t\t\tit = _factors.erase(it);\n\t\t\treturn;\n\t\t} else {\n\t\t\t++it;\n\t\t}\n\t}\n}\n\nvoid Graph::shiftIndices(int poseSize, int firstPoseIdx) {\n\tauto it = _factors.begin();\n\twhile (it != _factors.end()) {\n\t\tif (!(*it)->shiftIndices(poseSize, firstPoseIdx)) {\n\t\t\tdelete *it;\n\t\t\tit = _factors.erase(it);\n\t\t} else {\n\t\t\t++it;\n\t\t}\n\t}\n}\n\n} // namespace filters::pose_graph\n", "meta": {"hexsha": "51a8768e65ed2a59a45af5947856aa0df9da2cc4", "size": 2187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filters/pose_graph/graph.cpp", "max_stars_repo_name": "huskyroboticsteam/Resurgence", "max_stars_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-23T23:31:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:17:41.000Z", "max_issues_repo_path": "src/filters/pose_graph/graph.cpp", "max_issues_repo_name": "huskyroboticsteam/Resurgence", "max_issues_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-22T05:33:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T07:01:47.000Z", "max_forks_repo_path": "src/filters/pose_graph/graph.cpp", "max_forks_repo_name": "huskyroboticsteam/Resurgence", "max_forks_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7027027027, "max_line_length": 92, "alphanum_fraction": 0.5953360768, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6371361594718143}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd X = MatrixXd::Random(5,5);\nMatrixXd A = X + X.transpose();\ncout << \"Here is a random symmetric 5x5 matrix:\" << endl << A << endl << endl;\n\nVectorXd diag(5);\nVectorXd subdiag(4);\ninternal::tridiagonalization_inplace(A, diag, subdiag, true);\ncout << \"The orthogonal matrix Q is:\" << endl << A << endl;\ncout << \"The diagonal of the tridiagonal matrix T is:\" << endl << diag << endl;\ncout << \"The subdiagonal of the tridiagonal matrix T is:\" << endl << subdiag << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "fe61b84cc5fac10eb2df10df10f82e20f8979781", "size": 626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_decomposeInPlace.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_decomposeInPlace.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_decomposeInPlace.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2173913043, "max_line_length": 85, "alphanum_fraction": 0.6709265176, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6370690530605193}}
{"text": "\ufeff/*\n*Topic: Implementation of Sequential Quadratic Programming in C++\n*Library: Eigen, a c++ matrix operation library.\n*Author: Muqian, Chen\n*Current Date: 31.01.2021\n*Log: The function to calculate a quadratic optimal programming constrainted by inequation \n*        conditions are totally implemnted. It did take a long time because I am not familiar \n*        with lots of implicit mechamism of c++. But I feel so lucky that I really started to\n*        program with it. I think that I am moving towards to the aim that I really implement\n*        something based on ROS. The next task is to cover the case of equation constraints\n*        and add a function which automatically calculates the initial working set. Over.\n*/\n\n#include <iostream>\n#include <Eigen>\n#include <typeinfo>\n#include <iomanip>\n\nusing namespace std;\nusing namespace Eigen;\nVectorXd eqpCalculation(MatrixXd A, VectorXd b, MatrixXd G,\n\t\t\t\t\t\tVectorXd d, VectorXd theta);\ndouble calculationAlpha(MatrixXd& A_working, VectorXd& b_working,\n\t\t\t\t\t\tMatrixXd& A_deactive,VectorXd& b_deactive, \n\t\t\t\t\t\tVectorXd stepLength, VectorXd theta);\n\n\n//\u8fd9\u91cc\u82e5\u662f\u52a0\u4e0a&\u5c31\u4f1a\u53d8\u6210\u6309\u5f15\u7528\u4f20\u9012\u4e86\u4eb2\uff0c\u5df2\u7ecf\u7528test\u68c0\u9a8c\u8fc7\u4e86\u3002\nVectorXd eqpCalculation(MatrixXd A, VectorXd b, MatrixXd G, \n\t                    VectorXd d, VectorXd theta) {\n\tVectorXd g, h;\n\tg = d + G * theta;\n\th = A * theta - b;\n\tIndex g_row = g.rows();\n\tIndex h_row = h.rows();\n\n\t//catenate the A and G as KKT Matrix\n\tIndex A_row = A.rows();\n\tIndex A_col = A.cols();\n\tIndex G_row = G.rows();\n\n\t//first catenate them in horizont direction\n\tMatrixXd K1(G_row, A_row + G_row);\n\tK1 << G, A.transpose();\n\tMatrixXd zeros = MatrixXd::Zero(A_row, A_row);\n\tMatrixXd K2(A_row, A_col + A_row);\n\tK2 << A, zeros;\n\tMatrixXd K(A_row + G_row, A_row + G_row);\n\tK << K1, K2;\n\n\t//then catenate [g;h] \n\tVectorXd g_h(g_row + h_row, 1);\n\tg_h << g, h;\n\t//for debug\n\t//cout << \"[INFO]Current KKT Matrix is:\" << endl << K << endl;\n\t//cout << \"[INFO]Current g_h is:\" << endl << g_h << endl;\n\n\t//calculate KKT-Equation \n\tVectorXd result(G_row + A_row, 1);\n\tresult = K.inverse() * g_h;\n\t\n\treturn result;\n\t};\n\n//implementation of a function template for removing a specific row from MatrixXf or VectorXf\n//After validation, this function could work at situation MatrixXf or VectorXf\ntemplate <typename T1, typename T2> void removeRow(T1& a, T2 b) {\n\t// a: Matrix or Vector which need to remove the row\n\t// b: the row number of the removed row.\n\n\tconst int newRow = a.rows() - 1;\n\tconst int newCol = a.cols();\n\n\tif (b < a.rows()) {\n\t\ta.block(b, 0, newRow - b, a.cols()) =\n\t\t\ta.block(b + 1, 0, newRow - b, a.cols());\n\t}\n\telse {\n\t\tcout << \"[INFO] The row to remove is out of boundary of input !\" << endl;\n\t};\n\ta.conservativeResize(newRow, newCol);\n}\n\n//Implementation of a function template for adding a trivial but dimension-matched row into\n//MatrixXf or VectorXf\ntemplate <typename T1, typename T2> void addRow(T1& a, T2 b) {\n\t// a: the target Matrix or Vector \n\t// b: added row into target\n\t// column number should be unchanged.\n\n\tint newRow = a.rows() + 1;\n\tint newCol = b.cols();\n\n\ta.conservativeResize(newRow, newCol);\n\ta.block(newRow - 1, 0, 1, newCol) = b;\n};\n\n\n//Implementation of a fucntion template \nvoid setInitial(MatrixXd A, MatrixXd& A_working,  MatrixXd& A_deactive, VectorXd b, VectorXd& b_working, \n\t\t\t    VectorXd& b_deactive, VectorXd  initialTheta, int f) {\n\t//f: amount of inequations\n\tVectorXd result(f ,1);\n\tresult = A * initialTheta - b;\n\tArrayXd resultArray;\n\tresultArray = result.array().abs();\n\tfor (int i = 0; i < f; i++) {\n\t\tif ( result(i, 0) < 1e-7) {\n\t\t\t//add the matched constraints into working set\n\t\t\taddRow(A_working, A.row(i));\n\t\t\taddRow(b_working, b.row(i));\n\t\t}\n\t\telse {\n\t\t\t//add the unmatched constraints into deacitve set\n\t\t\taddRow(A_deactive, A.row(i));\n\t\t\taddRow(b_deactive, b.row(i));\n\t\t}\n\t}\n}\n\n\n//Pass by reference could be used here for updating the working set.\ndouble calculationAlpha(MatrixXd& A_working, VectorXd& b_working, \n\t\t\t\t\t   MatrixXd& A_deactive, VectorXd& b_deactive, VectorXd stepLength, VectorXd theta, int i) {\n\tdouble alpha = -1;\n\tint deactRow = A_deactive.rows();\n\tint deactCol = A_deactive.cols();\n\n\tVectorXd resultAiP(deactRow, 1);\n\tresultAiP = A_deactive * stepLength;\n\t\n\tVectorXd resultAiTheta(deactRow, 1);\n\tresultAiTheta = b_deactive - A_deactive * theta;\n\n\tArrayXd result(deactRow, 1);\n\tArrayXd resultUp(deactRow, 1);\n\tArrayXd resultDown(deactRow, 1);\n\tresultUp = resultAiTheta.array();\n\tresultDown = resultAiP.array();\n\t//for debug\n\t//cout << \"[INFO]: current resultUp is:\" << endl << resultUp << endl;\n\t//cout << \"[INFO]: current resultDown is:\" << endl << resultDown << endl;\n\t\n\n\tfor (int i = 0; i < deactRow; i++) {\n\t\tif (resultDown(i,0)< 0) {\n\t\t\tresult(i, 0) = resultUp(i, 0) / resultDown(i, 0);\n\t\t}\n\t\telse {\n\t\t\tresult(i, 0) = 1000.0;\n\t\t}\n\t}\n\t//for debug\n\t//cout << \"[INFO]: current result is:\" << endl << result << endl;\n\n\n\tIndex minRow, minCol;\n\tdouble min = 0;\n\tmin = result.matrix().minCoeff(&minRow, &minCol);\n\n\t//=============================Attention\uff01\uff01\uff01\uff01======================================\n\t//\u8fd9\u91cc\u6709\u4e2a\u5751\uff0c\u5c31\u662fc++\u4e2d\u9664\u53f7/\u51fa\u6765\u7684\u7ed3\u679c\u4f1a\u76f4\u63a5\u820d\u5f03\u5c0f\u6570\u70b9\u540e\u9762\u7684\u6570\uff0c\u6bd4\u5982\u8fd9\u91ccmin\u5e94\u8be5\u662f1.429\n\t//\u4f46\u662f\u53ea\u8f93\u51fa1\uff0c\u4f46\u662f\u5728\u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u6211\u53ef\u4ee5\u4e0d\u7528\u7ba1\u8fd9\u4e2a\u95ee\u9898\uff0c\u56e0\u4e3a\u4e4b\u540e\u662f\u8981\u62ff\u53bb\u8ddf1\u505a\u6bd4\u8f83\u7684\u3002\n\t//\u4e0d\u5bf9\u554a\uff0c\u6211\u5f97\u7ba1\uff0c\u56e0\u4e3a\u4e4b\u540ealpha\u82e5\u662f\u7b97\u51fa\u5c0f\u4e8e\u4e00\u5219\u6309\u7167\u8fd9\u4e2a\u89c4\u5219\u76f4\u63a5\u5c31\u662f\u96f6\u4e86\u3002\u3002\u3002\n\t//\u906d\u91cd\u4e86\uff0c\u5f97\u628a\u6240\u6709\u77e9\u9635\u90fd\u6539\u6210double\u7c7b\u578b\u3002\n\t//\u5168\u90e8\u90fd\u6539\u6210\u4e5f\u4e0d\u884c\uff0c\u5f53\u4f60\u4f7f\u7528mat.array()\u7684\u65f6\u5019\u5b83\u4f1a\u81ea\u52a8\u5c06\u7c7b\u578b\u6362\u6389\uff08\u6216\u8005\u6709\u522b\u7684\u6211\u4e0d\u61c2\u7684\u5185\n\t//\u9690\u64cd\u4f5c\uff09\uff0c\u901a\u8fc7\u5b9e\u9a8c\u5f97\u51fa\uff0c\u5fc5\u987b\u8981\u53e6\u5916\u58f0\u660eArrayXd\u53d8\u91cf\u6765\u50a8\u5b58mat.array()\u7684\u7ed3\u679c\uff0c\u8fd9\u6837\u624d\u80fd\u5728\n\t//\u76f8\u9664\u64cd\u4f5c\u4e2d\u5f97\u5230\u5b8c\u7f8e\u7684\u5c0f\u6570\u70b9\u540e\u9762\u7684\u6570\u3002                    \n\t//-----31.01.2021\n\t//ArrayXd result(deactRow, 1);\n\t//ArrayXd resultUp(deactRow, 1);\n\t//ArrayXd resultDown(deactRow, 1);\n\t//resultUp = resultAiTheta.array();\n\t//resultDown = resultAiP.array();\n\t//result = resultUp / resultDown;\n\t//cout << \"[INFO]Current result is :\" << result << endl;\n\t//=============================Attention\uff01\uff01\uff01\uff01======================================\n\n\tif (min < 1) {\n\t\talpha = min;\n\n\t\t//add the blocking constraint into working set\n\t\taddRow(A_working, A_deactive.row(minRow));\n\t\taddRow(b_working, b_deactive.row(minRow));\n\t\tcout << \"[INFO] \" << i << \". loop. A constraint is added to working set and deleted from deactive set.\" << endl;\n\n\t\t//delete the blocking constraint from deactive set\n\t\tremoveRow(A_deactive, minRow);\n\t\tremoveRow(b_deactive, minRow);\n\n\t\treturn alpha;\n\t}\n\telse {\n\t\talpha = 1;\n\t\treturn alpha;\n\t}\n}\n\n\nint main(int argc, char** argv)\n{\n\t//define G and d of objective function\n\tMatrixXd G(2,2);\n\tG << 2.0, 0.0, \n\t\t 0.0, 2.0;\n\tVectorXd d(2,1);\n\td << -2.0, \n\t\t -5.0;\n\n\t//define initialized theta\n\tVectorXd theta(2, 1);\n\ttheta(0) = 2.0;\n\ttheta(1) = 0.0;\n\tint ParameterNum = theta.rows();\n\n\t//define equation constraints\n\tMatrixXd AEquation(0, ParameterNum);\n\tVectorXd bEquation(0, 1);\n\n\n\t//define inequation constraints\n\tMatrixXd AInequation(5, ParameterNum);\n\tAInequation << 1.0, -2.0, \n\t\t\t\t  -1.0, -2.0, \n\t\t\t\t  -1.0,  2.0, \n\t\t\t\t   1.0,  0.0,\n\t\t\t\t   0.0,  1.0;\n\n\tint AInitialRowNum = AInequation.rows();\n\n\tVectorXd bInequation(5, 1);\n\tbInequation << -2.0, \n\t\t\t\t   -6.0, \n\t\t\t\t   -2.0, \n\t\t\t\t    0.0, \n\t\t\t\t    0.0;\n\n\n\n\n\t//define working set\n\tMatrixXd A_working(0, ParameterNum);\n\tVectorXd b_working(0, 1);\n\n\tA_working = AEquation;\n\tb_working = bEquation;\n\n\n\tMatrixXd A_deactive(0, ParameterNum);\n\tVectorXd b_deactive(0, 1);\n\n\tsetInitial(AInequation, A_working, A_deactive, bInequation, \n\t\t\t   b_working, b_deactive, theta, AInitialRowNum);\n\n\t//for debug\n\t//cout << \"[INFO]Current A inequation constraints is:\" << endl << A_working << endl;\n\t//cout << \"[INFO]Current b inequation constraints is:\" << endl << b_working << endl;\n\t//define the main variable during the calculating loop\n\tIndex constraintsNumber = b_working.rows();\n\tIndex thetaNumber = theta.rows();\n\t\n\tVectorXd result(thetaNumber+constraintsNumber, 1);\n\tVectorXd stepLength(thetaNumber, 1);\n\tVectorXd lambdaStar(constraintsNumber, 1);\n\n\tint i = 1;\n\n\twhile (true) {\n\t\t\n\n\t\tresult = eqpCalculation(A_working, b_working, G, d, theta);\n\n\t\tconstraintsNumber = b_working.rows();\n\t\tstepLength << -result.head(thetaNumber);\n\t\tlambdaStar = result.tail(constraintsNumber);\n\t\t//for debug\n\t\tcout << \"[INFO]: current stepLength is:\" << endl << stepLength << endl;\n\t\tcout << \"[INFO]: current lambdaStar is:\" << endl << lambdaStar << endl;\n\n\t\tif ( ( stepLength.array().abs() < 1e-10 ).all() == 1 ) {\n\t\t\tif ((lambdaStar.array() > 0).all() == 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tVectorXf::Index minRow, minCol;\n\t\t\t\tfloat min_lambda = lambdaStar.minCoeff(&minRow, &minCol);\n\n\t\t\t\t//add the deleted constraints into deactive set\n\t\t\t\taddRow(A_deactive, A_working.row(minRow));\n\t\t\t\taddRow(b_deactive, b_working.row(minRow));\n\n\t\t\t\t//delete the constraints from working set\n\t\t\t\tremoveRow(A_working, minRow);\n\t\t\t\tremoveRow(b_working, minRow);\n\t\t\t\tcout << \"[INFO] \" << i << \". loop. A constraint is deleted from working set and added in deactive set.\" << endl;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfloat alpha = 0.0;\n\t\t\talpha = calculationAlpha(A_working, b_working, A_deactive, b_deactive, stepLength, theta, i);\n\t\t\tcout << \"[INFO]\" << i << \". loop.Current alpha is :\" << endl << alpha << endl;\n\t\t\ttheta = theta + alpha * stepLength;\n\t\t\tcout << \"[INFO]\" << i << \". loop.Current Theta is :\" <<endl << theta << endl;\n\t\t\ti++;\n\t\t}\n\t}\n\t\n\n\n}\n", "meta": {"hexsha": "4d126aa685b7a0eb25b70589be038733dea9c327", "size": 9039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/SQP/SQP.cpp", "max_stars_repo_name": "monstermuqian/optimization_study", "max_stars_repo_head_hexsha": "49ac8654c5e3a79c4fce513a6c9174bb5f877c3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-05-16T22:00:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T12:14:12.000Z", "max_issues_repo_path": "cpp/SQP/SQP.cpp", "max_issues_repo_name": "monstermuqian/optimization_study", "max_issues_repo_head_hexsha": "49ac8654c5e3a79c4fce513a6c9174bb5f877c3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-18T12:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-18T19:01:42.000Z", "max_forks_repo_path": "cpp/SQP/SQP.cpp", "max_forks_repo_name": "monstermuqian/optimization_study", "max_forks_repo_head_hexsha": "49ac8654c5e3a79c4fce513a6c9174bb5f877c3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-23T18:46:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-12T07:14:10.000Z", "avg_line_length": 28.9711538462, "max_line_length": 116, "alphanum_fraction": 0.6560460228, "num_tokens": 2873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6370690530605193}}
{"text": "// -*- coding: utf-8 -*-\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <doctest/doctest.h>\r\n#include <netoptim/min_cycle_ratio.hpp>\r\n#include <netoptim/neg_cycle.hpp> // import negCycleFinder\r\n#include <py2cpp/nx2bgl.hpp>\r\n#include <utility> // for std::pair\r\n\r\nusing graph_t = boost::adjacency_list<boost::listS, boost::vecS,\r\n    boost::directedS, boost::no_property,\r\n    boost::property<boost::edge_weight_t, int,\r\n        boost::property<boost::edge_index_t, int>>>;\r\nusing Vertex = boost::graph_traits<graph_t>::vertex_descriptor;\r\nusing Edge_it = boost::graph_traits<graph_t>::edge_iterator;\r\n\r\nstatic xn::grAdaptor<graph_t> create_test_case1()\r\n{\r\n    using Edge = std::pair<int, int>;\r\n    const auto num_nodes = 5;\r\n    enum nodes\r\n    {\r\n        A,\r\n        B,\r\n        C,\r\n        D,\r\n        E\r\n    };\r\n    static Edge edge_array[] = {\r\n        Edge {A, B}, Edge {B, C}, Edge {C, D}, Edge {D, E}, Edge {E, A}};\r\n    int weights[] = {-5, 1, 1, 1, 1};\r\n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\r\n    auto g =\r\n        graph_t(edge_array, edge_array + num_arcs, weights, num_nodes);\r\n    return xn::grAdaptor<graph_t> {std::move(g)};\r\n}\r\n\r\nstatic xn::grAdaptor<graph_t> create_test_case2()\r\n{\r\n    using Edge = std::pair<int, int>;\r\n    const auto num_nodes = 5;\r\n    enum nodes\r\n    {\r\n        A,\r\n        B,\r\n        C,\r\n        D,\r\n        E\r\n    };\r\n    static Edge edge_array[] = {\r\n        Edge {A, B}, Edge {B, C}, Edge {C, D}, Edge {D, E}, Edge {E, A}};\r\n    int weights[] = {2, 1, 1, 1, 1};\r\n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\r\n    auto g =\r\n        graph_t(edge_array, edge_array + num_arcs, weights, num_nodes);\r\n    return xn::grAdaptor<graph_t> {std::move(g)};\r\n}\r\n\r\nstatic auto create_test_case_timing() -> xn::grAdaptor<graph_t>\r\n{\r\n    using Edge = std::pair<int, int>;\r\n    constexpr auto num_nodes = 3;\r\n    enum nodes\r\n    {\r\n        A,\r\n        B,\r\n        C\r\n    };\r\n    static Edge edge_array[] = {Edge {A, B}, Edge {B, A}, Edge {B, C},\r\n        Edge {C, B}, Edge {B, C}, Edge {C, B}, Edge {C, A}, Edge {A, C}};\r\n    int weights[] = {7, 0, 3, 1, 6, 4, 2, 5};\r\n    constexpr int num_arcs = sizeof(edge_array) / sizeof(Edge);\r\n    auto g =\r\n        graph_t(edge_array, edge_array + num_arcs, weights, num_nodes);\r\n    return xn::grAdaptor<graph_t> {std::move(g)};\r\n}\r\n\r\nstatic auto create_test_case_timing2() -> xn::grAdaptor<graph_t>\r\n{\r\n    using Edge = std::pair<int, int>;\r\n    constexpr auto num_nodes = 3;\r\n    enum nodes\r\n    {\r\n        A,\r\n        B,\r\n        C\r\n    };\r\n    static Edge edge_array[] = {Edge {A, B}, Edge {B, A}, Edge {B, C},\r\n        Edge {C, B}, Edge {B, C}, Edge {C, B}, Edge {C, A}, Edge {A, C}};\r\n    int weights[] = {3, -4, -1, -3, 2, 0, -2, 1};\r\n    constexpr int num_arcs = sizeof(edge_array) / sizeof(Edge);\r\n    auto g =\r\n        graph_t(edge_array, edge_array + num_arcs, weights, num_nodes);\r\n    return xn::grAdaptor<graph_t> {std::move(g)};\r\n}\r\n\r\nauto do_case(const xn::grAdaptor<graph_t>& G) -> bool\r\n{\r\n    using edge_t = decltype(*(std::begin(G.edges())));\r\n\r\n    const auto get_weight = [&](const edge_t& e) -> int\r\n    {\r\n        const auto& weightmap = boost::get(boost::edge_weight, G);\r\n        return weightmap[e];\r\n    };\r\n\r\n    auto dist = std::vector<int>(G.number_of_nodes(), 0);\r\n    auto N = negCycleFinder<xn::grAdaptor<graph_t>> {G};\r\n    const auto cycle = N.find_neg_cycle(dist, get_weight);\r\n    return !cycle.empty();\r\n}\r\n\r\nauto do_case_float(const xn::grAdaptor<graph_t>& G) -> bool\r\n{\r\n    using edge_t = decltype(*(std::begin(G.edges())));\r\n\r\n    const auto get_weight = [&](const edge_t& e) -> double\r\n    {\r\n        const auto& weightmap = boost::get(boost::edge_weight, G);\r\n        return weightmap[e];\r\n    };\r\n\r\n    auto dist = std::vector<double>(G.number_of_nodes(), 0.0);\r\n    auto N = negCycleFinder<xn::grAdaptor<graph_t>> {G};\r\n    const auto cycle = N.find_neg_cycle(dist, get_weight);\r\n    return !cycle.empty();\r\n}\r\n\r\nTEST_CASE(\"Test Negative Cycle (boost)\")\r\n{\r\n    const auto G = create_test_case1();\r\n    const auto hasNeg = do_case(G);\r\n    CHECK(hasNeg);\r\n}\r\n\r\nTEST_CASE(\"Test No Negative Cycle (boost)\")\r\n{\r\n    const auto G = create_test_case2();\r\n    const auto hasNeg = do_case(G);\r\n    CHECK(!hasNeg);\r\n}\r\n\r\nTEST_CASE(\"Test Timing Graph (boost)\")\r\n{\r\n    const auto G = create_test_case_timing();\r\n    const auto hasNeg = do_case(G);\r\n    CHECK(!hasNeg);\r\n}\r\n\r\nTEST_CASE(\"Test Timing Graph 2 (boost)\")\r\n{\r\n    const auto G = create_test_case_timing2();\r\n    const auto hasNeg = do_case(G);\r\n    CHECK(hasNeg);\r\n}\r\n\r\nTEST_CASE(\"Test Timing Graph float (boost)\")\r\n{\r\n    const auto G = create_test_case_timing();\r\n    const auto hasNeg = do_case_float(G);\r\n    CHECK(!hasNeg);\r\n}\r\n\r\nTEST_CASE(\"Test Timing Graph 2 (boost)\")\r\n{\r\n    const auto G = create_test_case_timing2();\r\n    const auto hasNeg = do_case_float(G);\r\n    CHECK(hasNeg);\r\n}\r\n", "meta": {"hexsha": "ebac75a8dd1ad2e47f70e6db5339fa36bb630d6c", "size": 4936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/test/src/test_neg_cycle_boost.cpp", "max_stars_repo_name": "luk036/ellcpp", "max_stars_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-26T04:58:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T06:29:59.000Z", "max_issues_repo_path": "lib/test/src/test_neg_cycle_boost.cpp", "max_issues_repo_name": "luk036/ellcpp", "max_issues_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/test/src/test_neg_cycle_boost.cpp", "max_forks_repo_name": "luk036/ellcpp", "max_forks_repo_head_hexsha": "3415e7ffb70b63edb9ce4d6c2b9fee92898538bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-06-03T08:20:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-30T10:41:49.000Z", "avg_line_length": 29.0352941176, "max_line_length": 74, "alphanum_fraction": 0.5881280389, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6370019216534994}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/core.hpp>\n#include <eve/module/special.hpp>\n#include <boost/math/special_functions/erf.hpp>\n\n//==================================================================================================\n// Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of erf_inv\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n\n  TTS_EXPR_IS( eve::erf_inv(T())  , T);\n  TTS_EXPR_IS( eve::erf_inv(v_t()), v_t);\n};\n\n//==================================================================================================\n// erf_inv  tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of erf_inv on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(-1.0, 1.0))\n        )\n<typename T>(T const& a0 )\n{\n  using v_t = eve::element_type_t<T>;\n  using eve::erf_inv;\n  using eve::as;\n  TTS_ULP_EQUAL( erf_inv(a0),  map([](auto e){return boost::math::erf_inv(e);}, a0), 2);\n  auto derf_inv = [](auto e){return v_t(0.886226925452758013649)*std::exp(eve::sqr(erf_inv(e)));};\n  TTS_ULP_EQUAL( eve::diff(erf_inv)(a0),  map(derf_inv, a0), 2);\n\n\n  TTS_ULP_EQUAL(erf_inv(T(0.5)), T(boost::math::erf_inv(v_t(0.5))), 1. );\n\n  if constexpr(eve::platform::supports_denormals)\n  {\n    TTS_ULP_EQUAL ( erf_inv(T(eve::smallestposval(as<T>())))\n                  , T(boost::math::erf_inv(eve::smallestposval(as<v_t>())))\n                  , 0.5\n                  );\n  }\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_IEEE_EQUAL(erf_inv(eve::nan(eve::as<T>()))  , eve::nan(eve::as<T>()) );\n    TTS_IEEE_EQUAL(erf_inv(eve::inf(eve::as<T>()))  , eve::nan(eve::as<T>()) );\n    TTS_IEEE_EQUAL(erf_inv(eve::minf(eve::as<T>())) , eve::nan(eve::as<T>()) );\n  }\n\n  TTS_ULP_EQUAL(erf_inv(T(35)), eve::nan(eve::as<T>()), 0.5);\n  TTS_ULP_EQUAL(erf_inv(T(-35)), eve::nan(eve::as<T>()), 0.5);\n\n  TTS_IEEE_EQUAL(erf_inv(T( 0 )),T(0)  );\n  TTS_IEEE_EQUAL(erf_inv(T(-0.)), T(0) );\n  TTS_ULP_EQUAL(erf_inv(T( 0.1 )), T( boost::math::erf_inv(0.1)), 0.5 );\n  TTS_ULP_EQUAL(erf_inv(T( 0.2 )), T( boost::math::erf_inv(0.2)), 0.5 );\n  TTS_ULP_EQUAL(erf_inv(T( 0.3 )), T( boost::math::erf_inv(0.3)), 0.5 );\n  TTS_ULP_EQUAL(erf_inv(T( 0.5 )), T( boost::math::erf_inv(0.5)),  1 );\n  TTS_ULP_EQUAL(erf_inv(T( 0.15)), T( boost::math::erf_inv(0.15)), 0.5 );\n  TTS_ULP_EQUAL(erf_inv(T( 0.75)), T( boost::math::erf_inv(0.75)), 0.5 );\n  TTS_ULP_EQUAL(erf_inv(T(- 0.1 )), T( boost::math::erf_inv(-0.1)), 0.5 );\n  TTS_ULP_EQUAL(erf_inv(T( -0.2 )), T( boost::math::erf_inv(-0.2)), 0.5 );\n  TTS_ULP_EQUAL(erf_inv(T( -0.3 )), T( boost::math::erf_inv(-0.3)), 0.5 );\n  TTS_ULP_EQUAL(erf_inv(T( -0.5 )), T( boost::math::erf_inv(-0.5)),  1 );\n  TTS_ULP_EQUAL(erf_inv(T( -0.15)), T( boost::math::erf_inv(-0.15)), 0.5 );\n  TTS_ULP_EQUAL(erf_inv(T( -0.75)), T( boost::math::erf_inv(-0.75)), 0.5 );\n};\n", "meta": {"hexsha": "115799da27463b43946069589201fa9f0e5f5404", "size": 3381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/special/erf_inv.cpp", "max_stars_repo_name": "clayne/eve", "max_stars_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/special/erf_inv.cpp", "max_issues_repo_name": "clayne/eve", "max_issues_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/special/erf_inv.cpp", "max_forks_repo_name": "clayne/eve", "max_forks_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7974683544, "max_line_length": 100, "alphanum_fraction": 0.4983732623, "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6369378485102573}}
{"text": "/*\r\n * wahet.cpp\r\n *\r\n * Author: P. Wild (pwild@cosy.sbg.ac.at)\r\n *\r\n * Iris segmentation tool extracting the iris texture out of an eye image and mapping it into doubly dimensionless coordinates.\r\n * The software implements the following technique:\r\n *\r\n * Weighted Adaptive Hough and Ellipsopolar Transform\r\n *\r\n * see:\r\n *\r\n * A. Uhl and P. Wild. Weighted Adaptive Hough and Ellipsopolar Transforms for Real-time Iris Segmentation.\r\n * In Proceedings of the 5th International Conference on Biometrics (ICB'12), 8 pages, New Delhi, India,\r\n * March 29 - April 1, 2012.\r\n *\r\n */\r\n#define _USE_MATH_DEFINES\r\n#include <cmath>\r\n\r\n#ifdef _WIN32 \r\n#include <boost\\math\\special_functions\\fpclassify.hpp>\r\n#ifndef INFINITY\r\n#define INFINITY (DBL_MAX+DBL_MAX)\r\n#endif\r\n#ifndef NAN\r\n#define NAN (INFINITY-INFINITY)\r\n#endif\r\n#endif\r\n\r\n#include \"version.h\"\r\n#include <cstdio>\r\n#include <map>\r\n#include <vector>\r\n#include <string>\r\n#include <cstring>\r\n#include <ctime>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <opencv2/core/core.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <opencv2/photo/photo.hpp>\r\n#include <boost/regex.hpp>\r\n#include <boost/filesystem.hpp>\r\n#include <boost/date_time/posix_time/posix_time_types.hpp>\r\n#ifndef M_PI\r\n#define M_PI 3.14159265358979323846\r\n#endif\r\n\r\nusing namespace std;\r\nusing namespace cv;\r\n\r\n/** no globbing in win32 mode **/\r\nint _CRT_glob = 0;\r\n\r\n/** Program modes **/\r\nstatic const int MODE_MAIN = 1, MODE_HELP = 2;\r\n\r\n/*\r\n * Print command line usage for this program\r\n */\r\nvoid printUsage() {\r\n    printVersion();\r\n\tprintf(\"+-----------------------------------------------------------------------------+\\n\");\r\n\tprintf(\"| wahet - Weighted Adaptive Hough and Ellipsopolar Transform                  |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| MODES                                                                       |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n    printf(\"| (# 1) iris texture extraction from eye images                               |\\n\");\r\n    printf(\"| (# 2) usage                                                                 |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| ARGUMENTS                                                                   |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"| Name | Parameters | # | ? | Description                                     |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"| -i   | infile     | 1 | N | input eye image (use * as wildcard, all other   |\\n\");\r\n    printf(\"|      |            |   |   | file parameters may refer to n-th * with ?n)    |\\n\");\r\n    printf(\"| -o   | outfile    | 1 | N | output iris texture image                       |\\n\");\r\n\tprintf(\"| -m   | maskfile   | 1 | N | output iris noise mask image                    |\\n\");\r\n    printf(\"| -s   | wdth hght  | 1 | Y | size, i.e. width and height, of output (512x64) |\\n\");\r\n    printf(\"| -e   |            | 1 | Y | enhance iris texture on (off)                   |\\n\");\r\n    printf(\"| -q   |            | 1 | Y | quiet mode on (off)                             |\\n\");\r\n    printf(\"| -t   |            | 1 | Y | time progress on (off)                          |\\n\");\r\n    printf(\"| -rm  | rmaskfile  | 1 | Y | write source reflection mask (off)              |\\n\");\r\n    printf(\"| -rr  | rremovfile | 1 | Y | write image with removed reflections (off)      |\\n\");\r\n    printf(\"| -em  | emaskfile  | 1 | Y | write image masking boundary edges (off)        |\\n\");\r\n    printf(\"| -gr  | gradfile   | 1 | Y | write gradient magnitude and phase image (off)  |\\n\");\r\n    printf(\"| -ic  | icentfile  | 1 | Y | write result of initial center detection (off)  |\\n\");\r\n    printf(\"| -po  | polarfile  | 1 | Y | write polar image (off)                         |\\n\");\r\n    printf(\"| -fb  | fboundfile | 1 | Y | write first boundary in polar coords (off)      |\\n\");\r\n    printf(\"| -ep  | ellpolfile | 1 | Y | write ellipsopolar image (off)                  |\\n\");\r\n    printf(\"| -ib  | iboundfile | 1 | Y | write inner boundary candidate (off)            |\\n\");\r\n    printf(\"| -ob  | oboundfile | 1 | Y | write outer boundary candidate (off)            |\\n\");\r\n    printf(\"| -bm  | binmaskfile| 1 | Y | write binary segmentation mask (off)            |\\n\");\r\n    printf(\"| -sr  | segresfile | 1 | Y | write segmentation result (off)                 |\\n\");\r\n    printf(\"| -lt  | thickness  | 1 | Y | thickness for lines to be drawn (1)             |\\n\");\r\n    printf(\"| -h   |            | 2 | N | prints usage                                    |\\n\");\r\n    printf(\"| -so  | scale fac. | 1 | N | scale the area of the outer ellipse (def.=1.0)  |\\n\");\r\n    printf(\"| -si  | scale fac. | 1 | N | scale the area of the inner ellipse (def.=1.0)  |\\n\");\r\n    printf(\"| -tr  | translate  | 1 | N | horizontal translation of ellipses (def.=0.0)   |\\n\");\r\n    printf(\"|      |            |   |   | the factor is by iris radius(x) (-1 would be a  |\\n\");\r\n    printf(\"|      |            |   |   | translation by iris radius to the left)         |\\n\");\r\n    printf(\"| -l   | logfile    | 1 | N | log parameters for unrolling to this file.      |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| EXAMPLE USAGE                                                               |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| -i *.tiff -o ?1_texture.png -s 512 32 -e -q -t                              |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| AUTHOR                                                                      |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| Peter Wild (pwild@cosy.sbg.ac.at)                                           |\\n\");\r\n    printf(\"| Heinz Hofbauer (hhofbaue@cosy.sbg.ac.at)                                    |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| JPEG2000 Hack                                                               |\\n\");\r\n    printf(\"| Thomas Bergmueller (thomas.bergmueller@authenticvision.com)                 |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| COPYRIGHT                                                                   |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| (C) 2012 All rights reserved. Do not distribute without written permission. |\\n\");\r\n    printf(\"+-----------------------------------------------------------------------------+\\n\");\r\n}\r\n\r\n/** ------------------------------- OpenCV helpers ------------------------------- **/\r\n\r\n/**\r\n * Visualizes a CV_32FC1 image (using peak normalization)\r\n *\r\n * filename: name of the file to be stored\r\n * norm: CV_32FC1 image\r\n *\r\n * returning imwrite result code\r\n */\r\nbool imwrite2f(const string filename, const Mat& src){\r\n\tMat norm(src.rows,src.cols,CV_8UC1);\r\n\tMatConstIterator_<float> it;\r\n\tMatIterator_<uchar> it2;\r\n\tfloat maxAbs = 0;\r\n\tfor (it = src.begin<float>(); it < src.end<float>(); it++){\r\n\t\tif (std::abs(*it) > maxAbs) maxAbs = std::abs(*it);\r\n\t}\r\n\tfor (it = src.begin<float>(), it2 = norm.begin<uchar>(); it < src.end<float>(); it++, it2++){\r\n\t\t*it2 = saturate_cast<uchar>(cvRound(127 + (*it / maxAbs) * 127));\r\n\t}\r\n\treturn imwrite(filename,norm);\r\n}\r\n\r\n/**\r\n * Calculate a standard uniform upper exclusive lower inclusive 256-bin histogram for range [0,256]\r\n *\r\n * src: CV_8UC1 image\r\n * histogram: CV_32SC1 1 x 256 histogram matrix\r\n */\r\nvoid hist2u(const Mat& src, Mat& histogram){\r\n\thistogram.setTo(0);\r\n\tMatConstIterator_<uchar> s = src.begin<uchar>();\r\n\tMatConstIterator_<uchar> e = src.end<uchar>();\r\n\tint * p = (int *)histogram.data;\r\n\tfor (; s!=e; s++){\r\n\t\tp[*s]++;\r\n\t}\r\n}\r\n\r\n/**\r\n * Calculate a standard uniform upper exclusive lower inclusive 256-bin histogram for range [0,256]\r\n *\r\n * src: CV_32FC1 image\r\n * histogram: CV_32SC1 1 x 256 histogram matrix\r\n * min: minimal considered value (inclusive)\r\n * max: maximum considered value (exclusive)\r\n */\r\nvoid hist2f(const Mat& src, Mat& histogram, const float min = 0, const float max = 256){\r\n\thistogram.setTo(0);\r\n\tMatConstIterator_<float> s = src.begin<float>();\r\n\tMatConstIterator_<float> e = src.end<float>();\r\n\tint bins = histogram.rows * histogram.cols;\r\n\tfloat binsize = (max-min) / bins;\r\n\tint * p = (int *)histogram.data;\r\n\tfor (; s!=e; s++){\r\n\t\tif (*s >= min) {\r\n\t\t\tif (*s < max){\r\n\t\t\t\tint idx = cvFloor((*s-min) / binsize);\r\n\t\t\t\tp[(idx < 0) ? 0 : ((idx > bins-1) ? bins-1 : idx)]++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Computate upper exclusive lower inclusive uniform histogram quantile, i.e. quantile * 100% are\r\n * less than returned value, and c(1-quantile) * 100 % are greater or equal than returned value.\r\n *\r\n * histogram: CV_32SC1 1 x 256 histogram matrix\r\n * count: histogram member count\r\n * quantile:  quantile between 0 and 1\r\n *\r\n * returning quantile bin between 0 and 256\r\n */\r\nint histquant2u(const Mat& histogram, const int count, const float quantile){\r\n\tint * s = (int *)histogram.data;\r\n\tint left = max(0,min(count,cvRound(quantile * count)));\r\n\tint sum = 0;\r\n\tint p = 0;\r\n\tfor (; sum < left; p++) {\r\n\t\tsum += s[p];\r\n\t}\r\n\tif (p > 0 && (sum - left > left - sum + s[p-1])) p--;\r\n\treturn p;\r\n}\r\n\r\n/** ------------------------------- Clahe ------------------------------- **/\r\n\r\n/*\r\n * Retrieves the (bilinear) interpolated byte from 4 bytes\r\n *\r\n * x: distance to left byte\r\n * y: distance to right byte\r\n * r: distance to upper byte\r\n * s: distance to lower byte\r\n * b1: upper left byte\r\n * b2: upper right byte\r\n * b3: lower left byte\r\n * b4: lower right byte\r\n */\r\nuchar interp(const double x, const double y, const double r, const double s, const uchar b1, const uchar b2, const uchar b3, const uchar b4) {\r\n  double w1 = (x + y);\r\n  double w2 = x / w1;\r\n  w1 = y / w1;\r\n  double w3 = (r + s);\r\n  double w4 = r / w3;\r\n  w3 = s / w3;\r\n  return saturate_cast<uchar>(w3 * (w1 * b1 + w2 * b2) + w4 * (w1 * b3 + w2 * b4));\r\n}\r\n\r\n/*\r\n * Retrieves the bilinear interpolated byte from 2 bytes\r\n *\r\n * x:  distance to left byte\r\n * y:  distance to right byte\r\n * b1: left byte\r\n * b2: right byte\r\n */\r\nuchar interp(const double x, const double y, const uchar b1, const uchar b2) {\r\n  double w1 = (x + y);\r\n  double w2 = x / w1;\r\n  w1 = y / w1;\r\n  return saturate_cast<uchar>(w1 * b1 + w2 * b2);\r\n}\r\n\r\n/*\r\n * Inplace histogram clipping according to Zuiderveld (counts excess and redistributes excess by adding the average increment)\r\n *\r\n * hist: CV_32SC1 1 x 256 histogram matrix\r\n * clipFactor: between 0 (maximum slope M/N, where M #pixel in window, N #bins) and 1 (maximum slope M)\r\n * pixelCount: number of pixels in window\r\n */\r\nvoid clipHistogram(Mat& hist, const float clipFactor, const int pixelCount) {\r\n\tdouble minSlope = ((double) pixelCount) / 256;\r\n\tint clipLimit = std::min(pixelCount, std::max(1, cvCeil(minSlope + clipFactor * (pixelCount - minSlope))));\r\n\tint distributeCount = 0;\r\n\tMatIterator_<int> p = hist.begin<int>();\r\n\tMatIterator_<int> e = hist.end<int>();\r\n\tfor (; p!=e; p++){\r\n\t\tint binsExcess = *p - clipLimit;\r\n\t\tif (binsExcess > 0) {\r\n\t\t\tdistributeCount += binsExcess;\r\n\t\t\t*p = clipLimit;\r\n\t\t}\r\n\t}\r\n\tint avgInc = distributeCount / 256;\r\n\tint maxBins = clipLimit - avgInc;\r\n\tfor (p = hist.begin<int>(); p!=e; p++){\r\n\t\tif (*p <= maxBins) {\r\n\t\t\tdistributeCount -= avgInc;\r\n\t\t\t*p += avgInc;\r\n\t\t}\r\n\t\telse if (*p < clipLimit) {\r\n\t\t\tdistributeCount -= (clipLimit - *p);\r\n\t\t\t*p = clipLimit;\r\n\t\t}\r\n\t}\r\n\twhile (distributeCount > 0) {\r\n\t\tfor (p = hist.begin<int>(); p!=e && distributeCount > 0; p++){\r\n\t\t\tif (*p < clipLimit) {\r\n\t\t\t\t(*p)++;\r\n\t\t\t\tdistributeCount--;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/*\r\n * Contrast-limited adaptive histogram equalization (supports in-place)\r\n *\r\n * src: CV_8UC1 image\r\n * dst: CV_8UC1 image (in-place operation is possible)\r\n * cellWidth: patch size in x direction (greater or equal to 2)\r\n * cellHeight: patch size in y direction (greater or equal to 2)\r\n * clipFactor: histogram clip factor between 0 and 1\r\n */\r\nvoid clahe(const Mat& src, Mat& dst, const int cellWidth = 10, const int cellHeight = 10, const float clipFactor = 1.){\r\n\tMat hist(1,256,CV_32SC1);\r\n\tMat roi;\r\n\tuchar * sp, * dp;\r\n\tint height = src.rows;\r\n\tint width = src.cols;\r\n\tint gridWidth = width / cellWidth + (width % cellWidth == 0 ? 0 : 1);\r\n\tint gridHeight = height / cellHeight + (height % cellHeight == 0 ? 0 : 1);\r\n\tint bufSize = (gridWidth + 2)*256;\r\n\tint bufOffsetLeft = bufSize - 256;\r\n\tint bufOffsetTop = bufSize - gridWidth * 256;\r\n\tint bufOffsetTopLeft = bufSize - (gridWidth + 1) * 256;\r\n\tMat buf(1, bufSize, CV_8UC1);\r\n\tMatIterator_<uchar> pbuf = buf.begin<uchar>(), ebuf = buf.end<uchar>();\r\n\tMatIterator_<int> phist, ehist = hist.end<int>();\r\n\tuchar * curr, * topleft, * top, * left;\r\n\tint pixelCount, cX, cY, cWidth, cHeight, cellOrigin, cellOffset;\r\n\tdouble sum;\r\n\t// process first row, first cell\r\n\tcX = 0;\r\n\tcY = 0;\r\n\tcWidth = min(cellWidth, width);\r\n\tcHeight = min(cellHeight, height);\r\n\tpixelCount = cWidth*cHeight;\r\n\tsum = 0;\r\n\troi = Mat(src,Rect(cX,cY,cWidth,cHeight));\r\n\thist2u(roi,hist);\r\n\tif (clipFactor < 1) clipHistogram(hist,clipFactor,pixelCount);\r\n\t// equalization\r\n\tfor(phist = hist.begin<int>(); phist!=ehist; phist++, pbuf++){\r\n\t\tsum += *phist;\r\n\t\t*pbuf = saturate_cast<uchar>(sum * 255 / pixelCount);\r\n\t}\r\n\t// paint first corner cell\r\n\tcWidth = min(cellWidth / 2, cWidth);\r\n\tcHeight = min(cellHeight / 2, cHeight);\r\n\tcellOrigin = src.step * cY + cX;\r\n\tcellOffset = src.step - cWidth;\r\n\tsp = (uchar *)(src.data + cellOrigin);\r\n\tdp = (uchar *)(dst.data + cellOrigin);\r\n\tcurr = buf.data;\r\n\tfor (int b=0; b < cHeight; b++, sp+= cellOffset, dp += cellOffset){\r\n\t  for (int a=0; a < cWidth; a++, sp++, dp++){\r\n\t\t*dp = curr[*sp];\r\n\t  }\r\n\t}\r\n\t// process first row, other cells\r\n\tfor (int x = 1; x < gridWidth; x++) {\r\n\t\tcX = x*cellWidth;\r\n\t\tcWidth = min(cellWidth, width - x*cellWidth);\r\n\t\tcHeight = min(cellHeight, height);\r\n\t\tpixelCount = cWidth*cHeight;\r\n\t\tsum = 0;\r\n\t\troi.release();\r\n\t\troi = Mat(src,Rect(cX,cY,cWidth,cHeight));\r\n\t\thist2u(roi,hist);\r\n\t\tif (clipFactor < 1) clipHistogram(hist,clipFactor,pixelCount);\r\n\t\t// equalization\r\n\t\tfor(phist = hist.begin<int>(); phist!=ehist; phist++, pbuf++){\r\n\t\t\tsum += *phist;\r\n\t\t\t*pbuf = saturate_cast<uchar>(sum * 255 / pixelCount);\r\n\t\t}\r\n\t\t// paint first row, other cells\r\n\t\tcX += cellWidth/2 - cellWidth;\r\n\t\tcWidth = min(cellWidth, width - x*cellWidth + cellWidth/2);\r\n\t\tcHeight = min(cellHeight / 2, height);\r\n\t\tcellOrigin = src.step * cY + cX;\r\n\t\tcellOffset = src.step - cWidth;\r\n\t\tsp = (uchar *)(src.data + cellOrigin);\r\n\t\tdp = (uchar *)(dst.data + cellOrigin);\r\n\t\tcurr = buf.data + (curr - buf.data + 256) % bufSize;\r\n\t\tleft = buf.data + (curr - buf.data + bufOffsetLeft) % bufSize;\r\n\t\tfor (int b=0; b < cHeight; b++, sp+= cellOffset, dp += cellOffset){\r\n\t\t  for (int a=0; a < cWidth; a++, sp++, dp++){\r\n\t\t\t  *dp = interp(a,cWidth-a,left[*sp], curr[*sp]);\r\n\t\t  }\r\n\t\t}\r\n\t}\r\n\t// process (i.e. paint) first row, last cell (only if necessary)\r\n\tif (width % cellWidth > cellWidth / 2 || width % cellWidth == 0) {\r\n\t\tcWidth = (width - cellWidth / 2) % cellWidth;\r\n\t\tcHeight = min(cellHeight / 2, height);\r\n\t\tcX = width-cWidth;\r\n\t\tcellOrigin = src.step * cY + cX;\r\n\t\tcellOffset = src.step - cWidth;\r\n\t\tsp = (uchar *)(src.data + cellOrigin);\r\n\t\tdp = (uchar *)(dst.data + cellOrigin);\r\n\t\tfor (int b=0; b < cHeight; b++, sp+= cellOffset, dp += cellOffset){\r\n\t\t  for (int a=0; a < cWidth; a++, sp++, dp++){\r\n\t\t\t*dp = curr[*sp];\r\n\t\t  }\r\n\t\t}\r\n\t}\r\n\t// process rest of rows\r\n\tfor (int y = 1; y < gridHeight; y++) {\r\n\t\t// process other rows, first cell\r\n\t\tcX = 0;\r\n\t\tcY = y*cellHeight;\r\n\t\tcWidth = min(cellWidth, width);\r\n\t\tcHeight = min(cellHeight, height - y*cellHeight);\r\n\t\tpixelCount = cWidth*cHeight;\r\n\t\tsum = 0;\r\n\t\troi.release();\r\n\t\troi = Mat(src,Rect(cX,cY,cWidth,cHeight));\r\n\t\thist2u(roi,hist);\r\n\t\tif (clipFactor < 1) clipHistogram(hist,clipFactor,pixelCount);\r\n\t\t// equalization\r\n\t\tif (pbuf == ebuf) pbuf = buf.begin<uchar>();\r\n\t\tfor(phist = hist.begin<int>(); phist!=ehist; phist++, pbuf++){\r\n\t\t\tsum += *phist;\r\n\t\t\t*pbuf = saturate_cast<uchar>(sum * 255 / pixelCount);\r\n\t\t}\r\n\t\t// paint other rows, first cell\r\n\t\tcY += cellHeight/2 - cellHeight;\r\n\t\tcWidth = min(cellWidth / 2, width);\r\n\t\tcHeight = min(cellHeight, height - y*cellHeight + cellHeight/2);\r\n\t\tcellOrigin = src.step * cY + cX;\r\n\t\tcellOffset = src.step - cWidth;\r\n\t\tsp = (uchar *)(src.data + cellOrigin);\r\n\t\tdp = (uchar *)(dst.data + cellOrigin);\r\n\t\tcurr = buf.data + (curr - buf.data + 256) % bufSize;\r\n\t\ttop = buf.data + (curr - buf.data + bufOffsetTop) % bufSize;\r\n\t\tfor (int b=0; b < cHeight; b++, sp+= cellOffset, dp += cellOffset){\r\n\t\t  for (int a=0; a < cWidth; a++, sp++, dp++){\r\n\t\t\t  *dp = interp(b,cHeight-b,top[*sp], curr[*sp]);\r\n\t\t  }\r\n\t\t}\r\n\t\t// process other rows, rest of cells\r\n\t\tfor (int x = 1; x < gridWidth; x++) {\r\n\t\t\tcX = x*cellWidth;\r\n\t\t\tcY = y*cellHeight;\r\n\t\t\tcWidth = min(cellWidth, width - x*cellWidth);\r\n\t\t\tcHeight = min(cellHeight, height - y*cellHeight);\r\n\t\t\tpixelCount = cWidth*cHeight;\r\n\t\t\tsum = 0;\r\n\t\t\troi.release();\r\n\t\t\troi = Mat(src,Rect(cX,cY,cWidth,cHeight));\r\n\t\t\thist2u(roi,hist);\r\n\t\t\tif (clipFactor < 1) clipHistogram(hist,clipFactor,pixelCount);\r\n\t\t\t// equalization\r\n\t\t\tif (pbuf == ebuf) pbuf = buf.begin<uchar>();\r\n\t\t\tfor(phist = hist.begin<int>(); phist!=ehist; phist++, pbuf++){\r\n\t\t\t\tsum += *phist;\r\n\t\t\t\t*pbuf = saturate_cast<uchar>(sum * 255 / pixelCount);\r\n\t\t\t}\r\n\t\t\t// paint other rows, rest of cells\r\n\t\t\tcX += cellWidth/2 - cellWidth;\r\n\t\t\tcY += cellHeight/2 - cellHeight;\r\n\t\t\tcWidth = min(cellWidth, width - x*cellWidth + cellWidth/2);\r\n\t\t\tcHeight = min(cellHeight, height - y*cellHeight + cellHeight/2);\r\n\t\t\tcellOrigin = src.step * cY + cX;\r\n\t\t\tcellOffset = src.step - cWidth;\r\n\t\t\tsp = (uchar *)(src.data + cellOrigin);\r\n\t\t\tdp = (uchar *)(dst.data + cellOrigin);\r\n\t\t\tcurr = buf.data + (curr - buf.data + 256) % bufSize;\r\n\t\t\ttop = buf.data + (curr - buf.data + bufOffsetTop) % bufSize;\r\n\t\t\ttopleft = buf.data + (curr - buf.data + bufOffsetTopLeft) % bufSize;\r\n\t\t\tleft = buf.data + (curr - buf.data + bufOffsetLeft) % bufSize;\r\n\t\t\tfor (int b=0; b < cHeight; b++, sp+= cellOffset, dp += cellOffset){\r\n\t\t\t  for (int a=0; a < cWidth; a++, sp++, dp++){\r\n\t\t\t\t  *dp = interp(a, cWidth-a,b,cHeight-b,topleft[*sp],top[*sp],left[*sp],curr[*sp]);\r\n\t\t\t  }\r\n\t\t\t}\r\n\t\t}\r\n\t\t// process (i.e. paint) other rows, last cell (only if necessary)\r\n\t\tif (width % cellWidth > cellWidth / 2 || width % cellWidth == 0) {\r\n\t\t\tcWidth = (width - cellWidth / 2) % cellWidth;\r\n\t\t\tcHeight = min(cellHeight, height - y*cellHeight + cellHeight/2);\r\n\t\t\tcX = width-cWidth;\r\n\t\t\tcellOrigin = src.step * cY + cX;\r\n\t\t\tcellOffset = src.step - cWidth;\r\n\t\t\tsp = (uchar *)(src.data + cellOrigin);\r\n\t\t\tdp = (uchar *)(dst.data + cellOrigin);\r\n\t\t\ttop = buf.data + (curr - buf.data + bufOffsetTop) % bufSize;\r\n\t\t\tfor (int b=0; b < cHeight; b++, sp+= cellOffset, dp += cellOffset){\r\n\t\t\t  for (int a=0; a < cWidth; a++, sp++, dp++){\r\n\t\t\t\t  *dp = interp(b,cHeight-b,top[*sp], curr[*sp]);\r\n\t\t\t  }\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t// process (i.e. paint) last row (only if necessary)\r\n\tif (height % cellHeight > cellHeight / 2 || height % cellHeight == 0) {\r\n\t\t// paint last row, first cell\r\n\t\tcWidth =  min(cellWidth / 2, width);\r\n\t\tcHeight = (height - cellHeight / 2) % cellHeight;\r\n\t\tcX = 0;\r\n\t\tcY = height-cHeight;\r\n\t\tcellOrigin = src.step * cY + cX;\r\n\t\tcellOffset = src.step - cWidth;\r\n\t\tsp = (uchar *)(src.data + cellOrigin);\r\n\t\tdp = (uchar *)(dst.data + cellOrigin);\r\n\t\tcurr = buf.data + (curr - buf.data + bufOffsetTop + 256) % bufSize;\r\n\t\tfor (int b=0; b < cHeight; b++, sp+= cellOffset, dp += cellOffset){\r\n\t\t  for (int a=0; a < cWidth; a++, sp++, dp++){\r\n\t\t\t*dp = curr[*sp];\r\n\t\t  }\r\n\t\t}\r\n\t\t// paint last row, other cells\r\n\t\tfor (int x = 1; x < gridWidth; x++) {\r\n\t\t\tcX = (x-1)*cellWidth + cellWidth/2;\r\n\t\t\tcWidth = min(cellWidth, width - x*cellWidth + cellWidth/2);\r\n\t\t\tcHeight = (height - cellHeight / 2) % cellHeight;\r\n\t\t\tcellOrigin = src.step * cY + cX;\r\n\t\t\tcellOffset = src.step - cWidth;\r\n\t\t\tsp = (uchar *)(src.data + cellOrigin);\r\n\t\t\tdp = (uchar *)(dst.data + cellOrigin);\r\n\t\t\tleft = curr;\r\n\t\t\tcurr = buf.data + (curr - buf.data + 256) % bufSize;\r\n\t\t\tfor (int b=0; b < cHeight; b++, sp+= cellOffset, dp += cellOffset){\r\n\t\t\t  for (int a=0; a < cWidth; a++, sp++, dp++){\r\n\t\t\t\t  *dp = interp(a,cWidth-a,left[*sp], curr[*sp]);\r\n\t\t\t  }\r\n\t\t\t}\r\n\t\t}\r\n\t\t// paint last row, last cell (only if necessary)\r\n\t\tif (width % cellWidth > cellWidth / 2 || width % cellWidth == 0) {\r\n\t\t\tcWidth = (width - cellWidth / 2) % cellWidth;\r\n\t\t\tcHeight = (height - cellHeight / 2) % cellHeight;\r\n\t\t\tcX = width-cWidth;\r\n\t\t\tcellOrigin = src.step * cY + cX;\r\n\t\t\tcellOffset = src.step - cWidth;\r\n\t\t\tsp = (uchar *)(src.data + cellOrigin);\r\n\t\t\tdp = (uchar *)(dst.data + cellOrigin);\r\n\t\t\tfor (int b=0; b < cHeight; b++, sp+= cellOffset, dp += cellOffset){\r\n\t\t\t  for (int a=0; a < cWidth; a++, sp++, dp++){\r\n\t\t\t\t  *dp = curr[*sp];\r\n\t\t\t  }\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/** ------------------------------- Mask generation ------------------------------- **/\r\n\r\n/*\r\n * Masks a region of interest within a floating point matrix\r\n *\r\n * src: CV_32FC1 matrix\r\n * dst: CV_32FC1 matrix\r\n * mask: CV_8UC1 region of interest matrix\r\n * onread: for any p: dst[p] := set if mask[p] = onread, otherwise dst[p] = src[p]\r\n * set: set value for onread in mask, see onread\r\n */\r\nvoid maskValue(const Mat& src, Mat& dst, const Mat& mask, const uchar onread = 0, const uchar set = 0){\r\n\r\n\tMatConstIterator_<float> s = src.begin<float>();\r\n\tMatIterator_<float> d = dst.begin<float>();\r\n\tMatConstIterator_<float> e = src.end<float>();\r\n\tMatConstIterator_<uchar> r = mask.begin<uchar>();\r\n\tfor (; s!=e; s++, d++, r++){\r\n\t\t*d = (*r == onread) ? set : *s;\r\n\t}\r\n}\r\n\r\n/**\r\n * Generates destination regions map from source image\r\n *\r\n * src: CV_8UC1 image\r\n * dst: CV_32SC1 regions map image (same size as src)\r\n * count: outputs number of regions\r\n */\r\nvoid regionsmap(const Mat& src, Mat& dst, int& count){\r\n\tint width = src.cols;\r\n\tint height = src.rows;\r\n\tint labelsCount = 0;\r\n\tint maxRegions = ((width / 2) + 1) * ((height/2)+1)+1;\r\n\tMat regsmap(1,maxRegions,CV_32SC1);\r\n\tint * map = (int *)regsmap.data;\r\n\tfor (int i=0; i< maxRegions; i++) map[i] = i; // identity mapping\r\n\tuchar * psrc = src.data;\r\n\tint * pdst = (int *)(dst.data);\r\n\tint srcoffset = src.step - src.cols;\r\n\tint srcline = src.step;\r\n\tint dstoffset = dst.step / sizeof(int) - dst.cols;\r\n\tint dstline = dst.step / sizeof(int);\r\n\tdst.setTo(0);\r\n\t// 1) processing first row\r\n\tif (*psrc != 0) *pdst = ++labelsCount;\r\n\tif (width > 1) {\r\n\t\tpsrc++; pdst++;\r\n\t}\r\n\tfor (int x=1; x < width; x++, psrc++, pdst++){\r\n\t\tif (*psrc != 0) {// if pixel is a region pixel, check left neightbor\r\n\t\t\tif (psrc[-1] != 0){ // label like left neighbor\r\n\t\t\t\t*pdst = pdst[-1];\r\n\t\t\t}\r\n\t\t\telse { // label new region\r\n\t\t\t\t *pdst = ++labelsCount;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (height > 1){\r\n\t\tpsrc += srcoffset;\r\n\t\tpdst += dstoffset;\r\n\t}\r\n\t// 2) for all other rows\r\n\tfor (int y=1; y < height; y++, psrc+= srcoffset, pdst += dstoffset){\r\n\t\t// first pixel in row only checks upper and upper-right pixels\r\n\t\tif (*psrc != 0){\r\n\t\t\tif (psrc[-srcline] != 0){ // check upper pixel\r\n\t\t\t\t*pdst = pdst[-dstline];\r\n\t\t\t}\r\n\t\t\telse if (1 < width && psrc[1-srcline] != 0){ // check upper right\r\n\t\t\t\t*pdst = pdst[1-dstline];\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t*pdst = ++labelsCount;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (width > 1){\r\n\t\t\tpsrc++;\r\n\t\t\tpdst++;\r\n\t\t}\r\n\t\t// all other pixels in the row check for left and three upper pixels\r\n\t\tfor (int x=1; x < width-1; x++, psrc++, pdst++){\r\n\t\t\tif (*psrc != 0){\r\n\t\t\t\tif (psrc[-1] != 0){// check left neighbor\r\n\t\t\t\t\t*pdst = pdst[-1];\r\n\t\t\t\t}\r\n\t\t\t\telse if (psrc[-1-srcline] != 0){// label like left upper\r\n\t\t\t\t\t*pdst = pdst[-1-dstline];\r\n\t\t\t\t}\r\n\t\t\t\telse if (psrc[-srcline] != 0){// check upper\r\n\t\t\t\t\t*pdst = pdst[-dstline];\r\n\t\t\t\t}\r\n\t\t\t\tif (psrc[1-srcline] != 0){\r\n\t\t\t\t\tif (*pdst == 0){ // label pixel as the above right\r\n\t\t\t\t\t\t*pdst = pdst[1-dstline];\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tint label1 = *pdst;\r\n\t\t\t\t\t\tint label2 = pdst[1-dstline];\r\n\t\t\t\t\t\tif ((label1 != label2) && (map[label1] != map[label2])){\r\n\t\t\t\t\t\t\tif (map[label1] == label1){ // map unmapped to already mapped\r\n\t\t\t\t\t\t\t\tmap[label1] = map[label2];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (map[label2] == label2){ // map unmapped to already mapped\r\n\t\t\t\t\t\t\t\tmap[label2] = map[label1];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse { // both values are already mapped\r\n\t\t\t\t\t\t\t\tmap[map[label1]] = map[label2];\r\n\t\t\t\t\t\t\t\tmap[label1] = map[label2];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t// reindexing\r\n\t\t\t\t\t\t\tfor (int i=1; i <= labelsCount; i++){\r\n\t\t\t\t\t\t\t\tif (map[i] != i){\r\n\t\t\t\t\t\t\t\t\tint j = map[i];\r\n\t\t\t\t\t\t\t\t\twhile (j != map[j]){\r\n\t\t\t\t\t\t\t\t\t\tj = map[j];\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\tmap[i] = j;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (*pdst == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\t*pdst = ++labelsCount;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (*psrc != 0){\r\n\t\t\tif (psrc[-1] != 0){// check left neighbor\r\n\t\t\t\t*pdst = pdst[-1];\r\n\t\t\t}\r\n\t\t\telse if (psrc[-1-srcline] != 0){// label like left upper\r\n\t\t\t\t*pdst = pdst[-1-dstline];\r\n\t\t\t}\r\n\t\t\telse if (psrc[-srcline] != 0){// check upper\r\n\t\t\t\t*pdst = pdst[-dstline];\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t*pdst = ++labelsCount;\r\n\t\t\t}\r\n\t\t}\r\n\t\tpsrc++;\r\n\t\tpdst++;\r\n\t}\r\n\tMat regsremap(1,maxRegions,CV_32SC1);\r\n\tint * remap = (int *)regsremap.data;\r\n\tcount = 0;\r\n\tfor (int i=1; i <= labelsCount; i++){\r\n\t\tif (map[i] == i) {\r\n\t\t\tremap[i] = ++count;\r\n\t\t}\r\n\t}\r\n\tremap[0] = 0;\r\n\t// complete remapping\r\n\tfor (int i=1; i <= labelsCount; i++){\r\n\t\tif (map[i] != i) remap[i] = remap[map[i]];\r\n\t}\r\n\tpdst = (int *) (dst.data);\r\n\tfor (int y=0; y < height; y++, pdst += dstoffset){\r\n\t\tfor (int x=0; x < width; x++, pdst++){\r\n\t\t\t*pdst = remap[*pdst];\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Filters out too large or too small binary large objects (regions) in a region map\r\n *\r\n * regmap:  CV_32SC1 regions map (use regionsmap() to calculate this object)\r\n * mask:    CV_8UC1 output mask with filtered regions (same size as regmap)\r\n * count:   number of connected components in regmap\r\n * minSize: only regions larger or equal than minSize are kept\r\n * maxSize: only regions smaller or equal than maxSize are kept\r\n */\r\nvoid maskRegsize(const Mat& regmap, Mat& mask, const int count, const int minSize = INT_MIN, const int maxSize = INT_MAX){\r\n\tMat regs(1,count+1,CV_32SC1);\r\n\tint * map = (int *)regs.data;\r\n\t// resetting map to now count region size\r\n\tfor (int i=0; i<count+1; i++) map[i] = 0;\r\n\tint width = regmap.cols;\r\n\tint height = regmap.rows;\r\n\tint * pmap = (int *) (regmap.data);\r\n\tint mapoffset = regmap.step / sizeof(int) - regmap.cols;\r\n\tfor (int y=0; y < height; y++, pmap += mapoffset){\r\n\t\tfor (int x=0; x < width; x++, pmap++){\r\n\t\t\tif (*pmap > 0){\r\n\t\t\t\tmap[*pmap]++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t// delete too large and too small regions\r\n\tpmap = (int *) (regmap.data);\r\n\tuchar * pmask = mask.data;\r\n\tint maskoffset = mask.step - mask.cols;\r\n\tfor (int y=0; y < height; y++, pmap += mapoffset, pmask += maskoffset){\r\n\t\tfor (int x=0; x < width; x++, pmap++, pmask++){\r\n\t\t\tif (*pmap > 0){\r\n\t\t\t\tint size = map[*pmap];\r\n\t\t\t\tif (size < minSize || size > maxSize) *pmask = 0; else *pmask = 255;\r\n\t\t\t} else *pmask = 0;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Computes mask for reflections in image\r\n *\r\n * src: CV_8UC1 input image\r\n * mask: CV_8UC1 output image (same size as src)\r\n * roiPercent: parameter for the number of highest pixel intensities in percent\r\n * maxSize: maximum size of reflection region between 0 and 1\r\n * dilateSize: size of circular structuring element for dilate operation\r\n * dilateIterations: iterations of dilate operation\r\n */\r\nvoid createReflectionMask(const Mat& src, Mat& mask, const float roiPercent = 20, const float maxSizePercent = 3, const int dilateSize = 11, const int dilateIterations = 1){\r\n\tCV_Assert(src.type() == CV_8UC1);\r\n\tCV_Assert(mask.type() == CV_8UC1);\r\n\tCV_Assert(mask.size() == src.size());\r\n\tMat regions(mask.rows,mask.cols,CV_32SC1);\r\n\t//Mat src2(src.rows,src.cols,CV_8UC1);\r\n\t//blur(src,src2,Size(3,3));\r\n\tadaptiveThreshold(src,mask,255,ADAPTIVE_THRESH_MEAN_C,THRESH_BINARY,23,-60);\r\n\tint count = 0;\r\n\tregionsmap(mask,regions,count);\r\n\tmaskRegsize(regions,mask,count,10,1000);\r\n\tMat kernel(dilateSize,dilateSize,CV_8UC1);\r\n\tkernel.setTo(0);\r\n\tcircle(kernel,Point(dilateSize/2,dilateSize/2),dilateSize/2,Scalar(255),CV_FILLED);\r\n\tdilate(mask,mask,kernel,Point(-1,-1),dilateIterations);\r\n}\r\n\r\n/**\r\n * Main eye mask selecting pupillary and limbic boundary pixels\r\n *\r\n * src: CV_8UC1 image\r\n * mask: CV_8UC1 mask (same size as src)\r\n * gradX: CV_32FC1 gradient image in x-direction\r\n * gradY: CV_32FC1 gradient image in y-direction\r\n * mag: CV_32FC1 gradient magnitude\r\n */\r\nvoid createBoundaryMask(const Mat& src, Mat& mask, const Mat& gradX, const Mat& gradY, const Mat& mag){\r\n\tconst float roiPercent = 20; // was 20\r\n\tconst int histbins = 1000;\r\n\tint width = mask.cols;\r\n\tint height = mask.rows;\r\n\tint cellWidth = width/30;\r\n\tint cellHeight = height/30;\r\n\tint gridWidth = width / cellWidth + (width % cellWidth == 0 ? 0 : 1);\r\n\tint gridHeight = height / cellHeight + (height % cellHeight == 0 ? 0 : 1);\r\n\tMatConstIterator_<float> pmag = mag.begin<float>();\r\n\tMatConstIterator_<float> emag = mag.end<float>();\r\n\tfloat max = 0;\r\n\tfor (; pmag!=emag; pmag++){\r\n\t\tif (*pmag > max) max = *pmag;\r\n\t}\r\n\tMat hist(1,histbins,CV_32SC1);\r\n\tfloat histmax = max + max/histbins;\r\n\thist2f(mag,hist,0,histmax);\r\n\tfloat minval = histquant2u(hist,width*height,(100-roiPercent)*0.01) * histmax / histbins;\r\n\tMatIterator_<uchar> smask = mask.begin<uchar>();\r\n\tpmag = mag.begin<float>();\r\n\tfor (; pmag!=emag; pmag++, smask++){\r\n\t\t*smask = (*pmag >= minval) ? 255 : 0;\r\n\t}\r\n\tint stepx = (gradX.step/sizeof(float));\r\n\tint stepy = (gradY.step/sizeof(float));\r\n\tint stepmag = (mag.step/sizeof(float));\r\n\tfor (int y = 0; y < gridHeight; y++) {\r\n\t\tfor (int x = 0; x < gridWidth; x++) {\r\n\t\t\tint cX = x*cellWidth;\r\n\t\t\tint cY = y*cellHeight;\r\n\t\t\tint cWidth = min(cellWidth, width - x*cellWidth);\r\n\t\t\tint cHeight = min(cellHeight, height - y*cellHeight);\r\n\t\t\tfloat * pgradX = ((float *) (gradX.data)) + stepx*cY + cX;\r\n\t\t\tfloat * pgradY = ((float *) (gradY.data)) + stepy*cY + cX;\r\n\t\t\tfloat * pmag = ((float *) (mag.data)) + stepmag*cY + cX;\r\n\t\t\tint gradXCellOffset = stepx - cWidth;\r\n\t\t\tint gradYCellOffset = stepy - cWidth;\r\n\t\t\tint magoffset = stepmag - cWidth;\r\n\t\t\tdouble sumX = 0;\r\n\t\t\tdouble sumY = 0;\r\n\t\t\tdouble sumMag = 0;\r\n\t\t\tfor (int b=0; b < cHeight; b++, pmag += magoffset, pgradX += gradXCellOffset, pgradY+= gradYCellOffset){\r\n\t\t\t  for (int a=0; a < cWidth; a++, pmag++, pgradX++, pgradY++){\r\n\t\t\t\t  if (*pmag >= minval) {\r\n\t\t\t\t\t  sumX += *pgradX;\r\n\t\t\t\t\t  sumY += *pgradY;\r\n\t\t\t\t\t  sumMag += *pmag;\r\n\t\t\t\t  }\r\n\t\t\t  }\r\n\t\t\t}\r\n\t\t\tif (sumMag > 0) {\r\n\t\t\t\tsumX /= sumMag;\r\n\t\t\t\tsumY /= sumMag;\r\n\t\t\t}\r\n\t\t\tbool is_significant = ((sumX * sumX + sumY * sumY) > 0.5);\r\n\t\t\tuchar * pmask = mask.data + (mask.step)*cY + cX;\r\n\t\t\tint maskoffset = mask.step - cWidth;\r\n\t\t\tfor (int b=0; b < cHeight; b++, pmask += maskoffset){\r\n\t\t\t  for (int a=0; a < cWidth; a++, pmask++){\r\n\t\t\t\t  if (!is_significant && *pmask > 0) *pmask = 0;\r\n\t\t\t  }\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/** ------------------------------- Center detection ------------------------------- **/\r\n\r\n/**\r\n * Type for a bi-directional ray with originating point and direction\r\n *\r\n * x: x-coordinate of origin\r\n * y: y-coordinate of origin\r\n * fx: x-direction\r\n * fy: y-direction\r\n * mag: ray weight (magnitude)\r\n */\r\nstruct BidRay{\r\n\tfloat x;\r\n\tfloat y;\r\n\tfloat fx;\r\n\tfloat fy;\r\n\tfloat mag;\r\n\tBidRay(float _x, float _y, float _fx, float _fy, float _mag){\r\n\t\tx = _x;\r\n\t\ty = _y;\r\n\t\tfx = _fx;\r\n\t\tfy = _fy;\r\n\t\tmag = _mag;\r\n\t}\r\n};\r\n\r\n/**\r\n * Calculates determinant of vectors (x1, y1) and (x2, y2)\r\n *\r\n * x1: first vector's x-coordinate\r\n * y1: first vector's x-coordinate\r\n * x2: second vector's y-coordinate\r\n * y2: second vector's y-coordinate\r\n *\r\n * returning: determinant\r\n */\r\ninline float det(const float &x1, const float &y1, const float &x2, const float &y2) {\r\n\treturn x1*y2 - y1*x2;\r\n}\r\n\r\n/**\r\n * Intersects two lines (x1, y1) + s*(fx1, fy1) and (x2, y2) + t*(fx2, fy2)\r\n *\r\n * x1: x-coordinate of point on line 1\r\n * y1: y-coordinate of point on line 1\r\n * fx1: direction-vector x-coordinate of line 1\r\n * fy1: direction-vector y-coordinate of line 1\r\n * x2: x-coordinate of point on line 2\r\n * y2: y-coordinate of point on line 2\r\n * fx2: direction-vector x-coordinate of line 2\r\n * fy2: direction-vector y-coordinate of line 2\r\n * sx: intersection point x-coordinate\r\n * sy: intersection point y-coordinate\r\n *\r\n * returning: 1 if they intersect, 0 if they are parallel, -1 is they are equal\r\n */\r\nint intersect(const float &x1, const float &y1, const float &fx1, const float &fy1, const float &x2, const float &y2, const float &fx2, const float &fy2, float &sx, float &sy){\r\n\tif (det(fx1,fy1,fx2,fy2) == 0){\r\n\t\tif (det(fx1,fy1,x2-x1,y2-y1) == 0){\r\n\t\t\tsx = x1;\r\n\t\t\tsy = y1;\r\n\t\t\treturn -1; // equal\r\n\t\t}\r\n\t\tsx = NAN;\r\n\t\tsy = NAN;\r\n\t\treturn 0; // parallel\r\n\t}\r\n\tfloat Ds = det(x2-x1,y2-y1,-fx2,-fy2);\r\n\tfloat D = det(fx1,fy1,-fx2,-fy2);\r\n\tfloat s = Ds / D;\r\n\tsx = x1 + s*fx1;\r\n\tsy = y1 + s*fy1;\r\n\treturn 1;\r\n}\r\n\r\n/**\r\n * Intersects a line (x1, y1) + s*(fx1, fy1) with an axis parallel to the x-axis\r\n *\r\n * x1: x-coordinate of point on line 1\r\n * y1: y-coordinate of point on line 1\r\n * fx1: direction-vector x-coordinate of line 1\r\n * fy1: direction-vector y-coordinate of line 1\r\n * y2: y-coordinate of point on axis parallel to x-axis\r\n * sx: intersection point x-coordinate (sy is always equal y2)\r\n *\r\n * returning:  1 if the line intersects, 0 if it is parallel to the x-axis, -1 if it is the x-axis\r\n */\r\nint intersectX(const float &x1, const float &y1, const float &fx1, const float &fy1, const float &y2, float &sx){\r\n\tif (fy1 == 0){\r\n\t\tif (y2-y1 == 0){\r\n\t\t\tsx = x1;\r\n\t\t\treturn -1; // equal\r\n\t\t}\r\n\t\tsx = NAN;\r\n\t\treturn 0; // parallel\r\n\t}\r\n\tsx = x1 + ((y2-y1)*fx1 / fy1);\r\n\treturn 1;\r\n}\r\n\r\n/**\r\n * Intersects a line (x1, y1) + s*(fx1, fy1) with an axis parallel to the y-axis\r\n *\r\n * x1: x-coordinate of point on line 1\r\n * y1: y-coordinate of point on line 1\r\n * fx1: direction-vector x-coordinate of line 1\r\n * fy1: direction-vector y-coordinate of line 1\r\n * x2: x-coordinate of point on axis parallel to y-axis\r\n * sy: intersection point x-coordinate (sx is always equal x2)\r\n *\r\n * returning:  1 if the line intersects, 0 if it is parallel to the y-axis, -1 if it is the y-axis\r\n */\r\nint intersectY(const float &x1, const float &y1, const float &fx1, const float &fy1, const float &x2, float &sy){\r\n\tif (fx1 == 0){\r\n\t\tif (x2-x1 == 0){\r\n\t\t\tsy = y1;\r\n\t\t\treturn -1; // equal\r\n\t\t}\r\n\t\tsy = NAN;\r\n\t\treturn 0; // parallel\r\n\t}\r\n\tsy = y1 + ((x2-x1)*fy1 / fx1);\r\n\treturn 1;\r\n}\r\n\r\n/**\r\n * intersects a line (x, y) + s*(fx, fy) with an axis parallel rectangle\r\n *\r\n * x: x-coordinate of point on line\r\n * y: y-coordinate of point on line\r\n * fx: direction-vector x-coordinate of line\r\n * fy: direction-vector y-coordinate of line\r\n * left: left coordinate of rectangle\r\n * top: top coordinate of rectangle\r\n * right: right coordinate of rectangle\r\n * bottom: bottom coordinate of rectangle\r\n * px: first intersection point x-coordinate\r\n * py: first intersection point y-coordinate\r\n * qx: first intersection point x-coordinate\r\n * qy: first intersection point y-coordinate\r\n *\r\n * returning:  1 if the line intersects in 2 points, 0 if it does not intersect, -1 if it corresponds to a side of the rectangle\r\n */\r\nint intersectRect(const float &x, const float &y, const float &fx, const float &fy, const float &left, const float &top, const float &right, const float &bottom, float &px, float &py, float &qx, float &qy){\r\n\tfloat leftY, bottomX, rightY, topX;\r\n\tint lefti = intersectY(x,y,fx,fy,left,leftY);\r\n\tbool leftHit = (lefti != 0) && leftY >= top && leftY <= bottom;\r\n\tint topi = intersectX(x,y,fx,fy,top,topX);\r\n\tbool topHit = (topi != 0) && topX >= left && topX <= right;\r\n\tint righti = intersectY(x,y,fx,fy,right,rightY);\r\n\tbool rightHit = (righti != 0) && rightY >= top && rightY <= bottom;\r\n\tint bottomi = intersectX(x,y,fx,fy,bottom,bottomX);\r\n\tbool bottomHit = (bottomi != 0) && bottomX >= left && bottomX <= right;\r\n\tif (leftHit){\r\n\t\tif (bottomHit){\r\n\t\t\tif (rightHit){\r\n\t\t\t\tif (topHit){\r\n\t\t\t\t\t// left, bottom, right, top\r\n\t\t\t\t\tpx = left;\r\n\t\t\t\t\tpy = leftY;\r\n\t\t\t\t\tqx = right;\r\n\t\t\t\t\tqy = rightY;\r\n\t\t\t\t\treturn -1;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t// left, bottom, right\r\n\t\t\t\t\tpx = left;\r\n\t\t\t\t\tpy = leftY;\r\n\t\t\t\t\tqx = right;\r\n\t\t\t\t\tqy = rightY;\r\n\t\t\t\t\treturn -1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tif (topHit){\r\n\t\t\t\t\t// left, bottom, top\r\n\t\t\t\t\tpx = topX;\r\n\t\t\t\t\tpy = top;\r\n\t\t\t\t\tqx = bottomX;\r\n\t\t\t\t\tqy = bottom;\r\n\t\t\t\t\treturn -1;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t// left, bottom\r\n\t\t\t\t\tpx = left;\r\n\t\t\t\t\tpy = leftY;\r\n\t\t\t\t\tqx = bottomX;\r\n\t\t\t\t\tqy = bottom;\r\n\t\t\t\t\treturn 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tif (rightHit){\r\n\t\t\t\tif (topHit){\r\n\t\t\t\t\t// left, right, top\r\n\t\t\t\t\tpx = left;\r\n\t\t\t\t\tpy = leftY;\r\n\t\t\t\t\tqx = right;\r\n\t\t\t\t\tqy = rightY;\r\n\t\t\t\t\treturn -1;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t// left, right\r\n\t\t\t\t\tpx = left;\r\n\t\t\t\t\tpy = leftY;\r\n\t\t\t\t\tqx = right;\r\n\t\t\t\t\tqy = rightY;\r\n\t\t\t\t\treturn 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tif (topHit){\r\n\t\t\t\t\t// left, top\r\n\t\t\t\t\tpx = left;\r\n\t\t\t\t\tpy = leftY;\r\n\t\t\t\t\tqx = topX;\r\n\t\t\t\t\tqy = top;\r\n\t\t\t\t\treturn 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tif (bottomHit){\r\n\t\t\tif (rightHit){\r\n\t\t\t\tif (topHit){\r\n\t\t\t\t\t// bottom, right, top\r\n\t\t\t\t\tpx = topX;\r\n\t\t\t\t\tpy = top;\r\n\t\t\t\t\tqx = bottomX;\r\n\t\t\t\t\tqy = bottom;\r\n\t\t\t\t\treturn -1;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t// bottom, right\r\n\t\t\t\t\tpx = bottomX;\r\n\t\t\t\t\tpy = bottom;\r\n\t\t\t\t\tqx = right;\r\n\t\t\t\t\tqy = rightY;\r\n\t\t\t\t\treturn 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tif (topHit){\r\n\t\t\t\t\t// bottom, top\r\n\t\t\t\t\tpx = topX;\r\n\t\t\t\t\tpy = top;\r\n\t\t\t\t\tqx = bottomX;\r\n\t\t\t\t\tqy = bottom;\r\n\t\t\t\t\treturn 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tif (rightHit){\r\n\t\t\t\tif (topHit){\r\n\t\t\t\t\t// right, top\r\n\t\t\t\t\tpx = topX;\r\n\t\t\t\t\tpy = top;\r\n\t\t\t\t\tqx = right;\r\n\t\t\t\t\tqy = rightY;\r\n\t\t\t\t\treturn 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tpx = NAN;\r\n\tpy = NAN;\r\n\tqx = NAN;\r\n\tqy = NAN;\r\n\treturn 0;\r\n}\r\n\r\n/**\r\n * Draws a line onto accumulator matrix using Bresenham's algorithm:\r\n * Increases a rectangular accumulator by adding a given value to all points on a line\r\n *\r\n * line: line to be drawn\r\n * accu: floating point canvas (accumulator)\r\n * border: outer accu boundary rectangle in user space coordinates\r\n *\r\n * returning: true, if values are added to the accu\r\n */\r\nbool drawLine(const BidRay& line, Mat_<float>& accu, const float borderX, const float borderY, const float borderWidth, const float borderHeight){\r\n\t// intersect line with border\r\n\tfloat cellWidth = borderWidth/accu.cols;\r\n\tfloat cellHeight = borderHeight/accu.rows;\r\n\tfloat lx = borderX, ly = borderY;\r\n\tfloat rx = borderX+borderWidth, ry = borderY+borderHeight;\r\n\tfloat px, py, qx, qy;\r\n\tfloat incValue = line.mag / 1000;\r\n\tint accuLine = (accu.step/sizeof(float));\r\n\r\n\tint res = intersectRect(line.x,line.y,line.fx,line.fy,lx,ly,rx,ry,px,py,qx,qy);\r\n\tif (res != 0){\r\n\t  int x1 = min(max(cvRound((px-lx)/cellWidth),0),accu.cols-1);\r\n\t  int y1 = min(max(cvRound((py-ly)/cellHeight),0),accu.rows-1);\r\n\t  int x2 = min(max(cvRound((qx-lx)/cellWidth),0),accu.cols-1);\r\n\t  int y2 = min(max(cvRound((qy-ly)/cellHeight),0),accu.rows-1);\r\n\t  // line intersects with border, so draw line onto accu\r\n\t  float * p = (float *) (accu.data);\r\n\t  int t, dx, dy, incx, incy, pdx, pdy, ddx, ddy, es, el, err;\r\n\t  dx = x2 - x1;\r\n\t  dy = y2 - y1;\r\n\t  incx = (dx > 0) ? 1 : (dx < 0) ? -1 : 0;\r\n\t  incy = (dy > 0) ? accuLine : (dy < 0) ? -accuLine : 0;\r\n\t  if(dx<0) dx = -dx;\r\n\t  if(dy<0) dy = -dy;\r\n\t  if (dx>dy) {\r\n\t\tpdx=incx; // parallel step\r\n\t\tpdy=0;\r\n\t\tddx=incx; // diagonal step\r\n\t\tddy=incy;\r\n\t\tes=dy; // error step\r\n\t\tel=dx;\r\n\t  } else {\r\n\t\tpdx=0; // parallel step\r\n\t\tpdy=incy;\r\n\t\tddx=incx; // diagonal step\r\n\t\tddy=incy;\r\n\t\tes=dx; // error step\r\n\t\tel=dy;\r\n\t  }\r\n\t  p += x1 + y1*accuLine;\r\n\t  err = el/2;\r\n\t  // setPixel\r\n\t  *p += incValue;\r\n\t  // Calculate pixel\r\n\t  for(t=0; t<el; ++t) {// t counts Pixels, el is also count\r\n\t\t// update error\r\n\t\terr -= es;\r\n\t\tif(err<0) {\r\n\t\t  // make error term positive\r\n\t\t  err += el;\r\n\t\t  // step towards slower direction\r\n\t\t  p += ddx + ddy;\r\n\t\t}\r\n\t\telse  {\r\n\t\t  // step towards faster direction\r\n\t\t  p += pdx + pdy;\r\n\t\t}\r\n\t\t*p += incValue;\r\n\r\n\t  }\r\n\t  return true;\r\n\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n/**\r\n * Returns a gaussian 2D kernel\r\n * kernel: output CV_32FC1 image of specific size\r\n * sigma: gaussian sigma parameter\r\n */\r\nvoid gaussianKernel(cv::Mat& kernel,float sigma = 1.4){\r\n\tCV_Assert(kernel.type() == CV_32FC1);\r\n\tCV_Assert(kernel.cols%2==1 && kernel.rows%2==1);\r\n\tfloat * p = (float *)kernel.data;\r\n\tint width = kernel.cols;\r\n\tint height = kernel.rows;\r\n\tint offset = kernel.step/sizeof(float) - width;\r\n\tint rx = width/2;\r\n\tint ry = height/2;\r\n\tfloat sqrsigma = sigma*sigma;\r\n\tfor (int y=-ry,i=0;i<height;y++,i++,p+=offset){\r\n\t\tfor (int x=-rx,j=0;j<width;x++,j++,p++){\r\n\t\t\t*p = std::exp((x*x+y*y)/(-2*sqrsigma))/(2*M_PI*sqrsigma);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/*\r\n * Calculates circle center in source image.\r\n *\r\n * gradX: CV_32FC1 image, gradient in x direction\r\n * gradY: CV_32FC1 image, gradient in y direction\r\n * mask: CV_8UC1 mask image to exclude wrong points for gradient extraction (same size as gradX, gradY)\r\n * center: center point of main circle in source image\r\n * accuPrecision: stop condition for accuracy of center\r\n * accuSize: size of the accumulator array\r\n */\r\nvoid detectEyeCenter(const Mat& gradX, const Mat& gradY, const Mat& mag, const Mat& mask, float& centerx, float& centery, const float accuPrecision = .5, const int accuSize = 10){\r\n\t// initial declarations\r\n\tint width = mask.cols;\r\n\tint height = mask.rows;\r\n\tint accuScaledSize = (accuSize+1)/2;\r\n\tfloat rectX = -0.5, rectY = -0.5, rectWidth = width, rectHeight = height;\r\n\tMat gauss(accuScaledSize,accuScaledSize,CV_32FC1);\r\n\tgaussianKernel(gauss,accuScaledSize/3);\r\n\tMat_<float> accu(accuSize,accuSize);\r\n\tMat_<float> accuScaled(accuScaledSize,accuScaledSize);\r\n\t// create candidates list\r\n\tlist<BidRay> candidates;\r\n\tfloat * px = (float *)(gradX.data);\r\n\tfloat * py = (float *)(gradY.data);\r\n\tfloat * pmag = (float *)(mag.data);\r\n\tuchar * pmask = (uchar *)(mask.data);\r\n\tint xoffset = gradX.step/sizeof(float) - width;\r\n\tint yoffset = gradY.step/sizeof(float) - width;\r\n\tint magoffset = mag.step/sizeof(float) - width;\r\n\tint maskoffset = mask.step - width;\r\n\r\n\tfor (int y=0; y < height; y++, px += xoffset, py += yoffset,pmask += maskoffset,pmag += magoffset){\r\n\t\tfor (int x=0; x < width; x++, px++, py++, pmask++, pmag++){\r\n\t\t\tif (*pmask > 0){\r\n\t\t\t\tcandidates.push_back(BidRay(x,y,*px,*py,*pmag));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t//int tempi = 0;\r\n\twhile (rectWidth > accuPrecision || rectHeight > accuPrecision){\r\n\t\taccu.setTo(0);\r\n\t\tbool isIn = true;\r\n\t\tif (candidates.size() > 0){\r\n\t\t\tfor (list<BidRay>::iterator it = candidates.begin(); it != candidates.end();(isIn) ? ++it : it = candidates.erase(it)){\r\n\t\t\t\tisIn = drawLine(*it,accu,rectX,rectY,rectWidth,rectHeight);\r\n\t\t\t}\r\n\t\t}\r\n\t\tpyrDown(accu,accuScaled);\r\n\t\tmultiply(accuScaled,gauss,accuScaled,1,CV_32FC1);\r\n\r\n\t\tfloat * p = (float *) (accuScaled.data);\r\n\t\tfloat maxCellValue = 0;\r\n\t\tint maxCellX = accuScaled.cols / 2;\r\n\t\tint maxCellY = accuScaled.rows / 2;\r\n\t\tint accuOffset = accuScaled.step / sizeof(float) - accuScaled.cols;\r\n\t\tfor (int y=0; y < accuScaledSize; y++, p += accuOffset){\r\n\t\t\tfor (int x=0; x < accuScaledSize; x++, p++){\r\n\t\t\t\tif (*p > maxCellValue){\r\n\t\t\t\t\tmaxCellX = x;\r\n\t\t\t\t\tmaxCellY = y;\r\n\t\t\t\t\tmaxCellValue = *p;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\trectX += (((maxCellX + 0.5) * rectWidth) / accuScaledSize) - (rectWidth * 0.25); //std::min( accuRect.width * 0.5,((maxCellX * accuRect.width + 0.5) / accuScaledSize) - (accuRect.width * 0.25));\r\n\t\trectY += (((maxCellY + 0.5) * rectHeight) / accuScaledSize) - (rectHeight * 0.25); //std::min( accuRect.height * 0.5,((maxCellY * accuRect.height + 0.5) / accuScaledSize) - (accuRect.height * 0.25));\r\n\t\trectWidth /= 2;\r\n\t\trectHeight /= 2;\r\n\r\n\t}\r\n\tcenterx = rectX + rectWidth / 2;\r\n\tcentery = rectY + rectHeight / 2;\r\n}\r\n\r\n/** ------------------------------- Rubbersheet transform ------------------------------- **/\r\n\r\n/*\r\n * interpolation mode for rubbersheet repeating the last pixel for a given angle if no values are available\r\n * (otherwise behaves like INTER_LINEAR)\r\n */\r\nstatic const int INTER_LINEAR_REPEAT = 82;\r\n\r\n/*\r\n * Calculates the mapped (polar) image of source using two transformation contours.\r\n *\r\n * src: CV_8U (cartesian) source image (possibly multi-channel)\r\n * dst:\tCV_8U (polar) destination image (possibly multi-channel, 2 times the col size of inner)\r\n * inner: CV_32FC2 inner cartesian coordinates\r\n * outer: CV_32FC2 outer cartesian coordinates\r\n * interpolation: interpolation mode (INTER_NEAREST, INTER_LINEAR or INTER_LINEAR_REPEAT)\r\n * fill: fill value for pixels out of the image\r\n */\r\nvoid rubbersheet(const Mat& src, Mat& dst, const Mat& inner, const Mat& outer, const int interpolation = INTER_LINEAR, const uchar fill = 0) {\r\n\tint nChannels = src.channels();\r\n\tint dstheight = dst.rows;\r\n\tint dstwidth = dst.cols;\r\n\tint srcheight = src.rows;\r\n\tint srcwidth = src.cols;\r\n\tuchar * pdst = dst.data;\r\n\tint dstoffset = dst.step - dstwidth * nChannels;\r\n\tint srcstep = src.step;\r\n\tfloat roffset = 1.f / dstheight;\r\n\tfloat r = 0;\r\n\tif (interpolation == INTER_NEAREST){\r\n\t\tfor (int y=0; y < dstheight; y++, pdst+= dstoffset, r+=roffset){\r\n\t\t\tfloat * pinner = (float *) inner.data;\r\n\t\t\tfloat * pouter = (float *) outer.data;\r\n\t\t\tfor (int x=0; x < dstwidth; x++, pinner++, pouter++){\r\n\t\t\t\tfloat a = *pinner + r * (*pouter - *pinner);\r\n\t\t\t\tpinner++; pouter++;\r\n\t\t\t\tfloat b =  *pinner + r * (*pouter - *pinner);\r\n\t\t\t\tint coordX = cvRound(a);\r\n\t\t\t\tint coordY = cvRound(b);\r\n\t\t\t\tif (coordX < 0 || coordY < 0 || coordX >= srcwidth || coordY >= srcheight){\r\n\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t*pdst = *psrc;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse if (interpolation == INTER_LINEAR){\r\n\t\tfor (int y=0; y < dstheight; y++, pdst+= dstoffset, r+= roffset){\r\n\t\t\tfloat * pinner = (float *) inner.data;\r\n\t\t\tfloat * pouter = (float *) outer.data;\r\n\t\t\tfor (int x=0; x < dstwidth; x++, pinner++, pouter++){\r\n\t\t\t\tfloat a = *pinner + r * (*pouter - *pinner);\r\n\t\t\t\tpinner++; pouter++;\r\n\t\t\t\tfloat b =  *pinner + r * (*pouter - *pinner);\r\n\t\t\t\tint coordX = cvFloor(a);\r\n\t\t\t\tint coordY = cvFloor(b);\r\n\t\t\t\tif (coordX >= 0){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(*psrc)) + dx*(float)(psrc[nChannels]))+ dy*((1-dx)*((float)(psrc[srcstep])) + dx*(float)(psrc[nChannels+srcstep])));\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(*psrc)) + dx*(float)(psrc[nChannels])) + dy * ((float) fill));\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){// right out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dx)*((1-dy)*((float)(*psrc))+ dy*((float)(psrc[srcstep]))) + dx * ((float) fill));\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom right out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(*psrc)) + dx * ((float)fill)) + dy * ((float) fill));\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){// top out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((dy)*((1-dx)*((float)(psrc[srcstep])) + dx*(float)(psrc[nChannels+srcstep])) + (1-dy) * ((float) fill));\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){// top right out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((dy)*((1-dx)*((float)(psrc[srcstep])) + dx * ((float)fill)) + (1-dy) * ((float) fill));\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if (coordX == -1){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordY < srcheight-1){// left out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(dx*((1-dy)*(float)(psrc[nChannels]) + dy*(float)(psrc[nChannels+srcstep])) + (1-dx) * ((float) fill));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordY == srcheight-1){ // left bottom out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((dx)*((float)(psrc[nChannels])) + (1-dx) * ((float) fill)) + dy * ((float) fill));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){ // left top out\r\n\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((dy)*((dx)*((float)(psrc[nChannels+srcstep])) + (1-dx) * ((float) fill)) + (1-dy) * ((float) fill));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse { // INTER_LINEAR_REPEAT (repeats last pixel value)\r\n\t\tuchar * firstLine = pdst + dst.step;\r\n\t\tint step = dst.step;\r\n\t\tfor (int y=0; y < dstheight; y++, pdst+= dstoffset, r+= roffset){\r\n\t\t\tfloat * pinner = (float *) inner.data;\r\n\t\t\tfloat * pouter = (float *) outer.data;\r\n\t\t\tfor (int x=0; x < dstwidth; x++, pinner++, pouter++){\r\n\t\t\t\tfloat a = *pinner + r * (*pouter - *pinner);\r\n\t\t\t\tpinner++; pouter++;\r\n\t\t\t\tfloat b =  *pinner + r * (*pouter - *pinner);\r\n\t\t\t\tint coordX = cvFloor(a);\r\n\t\t\t\tint coordY = cvFloor(b);\r\n\t\t\t\tif (coordX >= 0){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(*psrc)) + dx*(float)(psrc[nChannels]))+ dy*((1-dx)*((float)(psrc[srcstep])) + dx*(float)(psrc[nChannels+srcstep])));\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dx)*((float)(*psrc)) + dx*(float)(psrc[nChannels])));\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t\t*pdst = *(pdst - step); // one row above\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){// right out\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dy)*((float)(*psrc))+ dy*((float)(psrc[srcstep]))));\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom right out\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = *psrc;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t\t*pdst = *(pdst - step); // one row above\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t*pdst = *(pdst - step); // one row above\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){// top out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dx)*((float)(psrc[srcstep])) + dx*(float)(psrc[nChannels+srcstep])));\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){// top right out\r\n\t\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t\t*pdst = psrc[srcstep];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t*pdst = *(pdst - step); // one row above\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t*pdst = *(pdst - step); // one row above\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if (coordX == -1){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordY < srcheight-1){// left out\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dy)*(float)(psrc[nChannels]) + dy*(float)(psrc[nChannels+srcstep])));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom left out\r\n\t\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t\t*pdst = psrc[nChannels];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t*pdst = *(pdst - step); // one row above\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){ // top left out\r\n\t\t\t\t\t\tuchar * psrc = (uchar*) (src.data+coordY*srcstep+coordX*nChannels);\r\n\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++,psrc++){\r\n\t\t\t\t\t\t\t*pdst = psrc[nChannels+srcstep];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t*pdst = *(pdst - step); // one row above\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t*pdst = *(pdst - step); // one row above\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tfor (int i=0; i< nChannels; i++,pdst++){\r\n\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/** ------------------------------- Boundary detection ------------------------------- **/\r\n\r\n/*\r\n * Calculates the mapped (polar) image of source using transformation center (polar origin) and radius.\r\n *\r\n * src: CV_8UC1 (cartesian) source image\r\n * dst: CV_8UC1 (polar) destination image (same size as src)\r\n * ellipse: unit ellipse located in the source image (size equals stretching coefficients)\r\n * radius: radius in pixels of the source image (to map whole image, this should be the maximum of distances between origin and corners)\r\n * interpolation: interpolation mode (INTER_NEAREST, INTER_LINEAR or INTER_LINEAR_REPEAT)\r\n * fill: fill value for pixels out of the image\r\n *\r\n * returning: polar resolution\r\n */\r\nfloat ellipsopolarTransform(const Mat& src, Mat& dst, const RotatedRect& ellipse, const float radius = -1, const int interpolation = INTER_LINEAR, const uchar fill = 0) {\r\n\t// first: translate point to origin\r\n\t// then: rotate points against ellipse angle\r\n\t// then: scale points' axes\r\n\t// finally: polar transform\r\n\tint dstheight = dst.rows;\r\n\tint dstwidth = dst.cols;\r\n\tint srcheight = src.rows;\r\n\tint srcwidth = src.cols;\r\n\tfloat rad = radius;\r\n\tfloat centerX = ellipse.center.x;\r\n\tfloat centerY = ellipse.center.y;\r\n\tfloat ellA = ellipse.size.width/2;\r\n\tfloat ellB = ellipse.size.height/2;\r\n\tdouble alpha = (ellipse.angle)*M_PI/180; // inclination angle of the ellipse\r\n\tif (alpha > M_PI) alpha -= M_PI; // normalize alpha to [0,M_PI]\r\n\tdouble omega = 2 * M_PI - alpha; // angle for reverse transformation\r\n\tconst double cosAlpha = cos(alpha);\r\n\tconst double sinAlpha = sin(alpha);\r\n\tconst double cosOmega = cos(omega);\r\n\tconst double sinOmega = sin(omega);\r\n\tif (rad < 0){\r\n\t\tconst float x1 = cosOmega * (-centerX) - sinOmega * (-centerY); // center x-coordinate in ellipse coords\r\n\t\tconst float y1 = sinOmega * (-centerX) + cosOmega * (-centerY); // center x-coordinate in ellipse coords\r\n\t\tconst float x2 = cosOmega * (srcwidth-centerX) - sinOmega * (-centerY); // center x-coordinate in ellipse coords\r\n\t\tconst float y2 = sinOmega * (srcwidth-centerX) + cosOmega * (-centerY); // center x-coordinate in ellipse coords\r\n\t\tconst float x3 = cosOmega * (srcwidth-centerX) - sinOmega * (srcheight-centerY); // center x-coordinate in ellipse coords\r\n\t\tconst float y3 = sinOmega * (srcwidth-centerX) + cosOmega * (srcheight-centerY); // center x-coordinate in ellipse coords\r\n\t\tconst float x4 = cosOmega * (-centerX) - sinOmega * (srcheight-centerY); // center x-coordinate in ellipse coords\r\n\t\tconst float y4 = sinOmega * (-centerX) + cosOmega * (srcheight-centerY); // center x-coordinate in ellipse coords\r\n\t\tconst float ellASquare = ellA*ellA;\r\n\t\tconst float ellBSquare = ellB*ellB;\r\n\t\trad = max(max(sqrt(x1*x1/ellASquare+y1*y1/ellBSquare),sqrt(x2*x2/ellASquare+y2*y2/ellBSquare)),max(sqrt(x3*x3/ellASquare+y3*y3/ellBSquare),sqrt(x4*x4/ellASquare+y4*y4/ellBSquare)));\r\n\t}\r\n\tuchar * pdst = dst.data;\r\n\tuchar * psrc = src.data;\r\n\tint dstoffset = dst.step - dstwidth;\r\n\tint srcstep = src.step;\r\n\tfloat roffset = rad/(dstheight-1);\r\n\tfloat r = 0;\r\n\tfloat thetaoffset = 2.f * M_PI / dstwidth;\r\n\tif (interpolation == INTER_NEAREST){\r\n\t\tfor (int y=0; y < dstheight; y++, pdst+= dstoffset, r+= roffset){\r\n\t\t\tfloat theta = 0;\r\n\t\t\tfor (int x=0; x < dstwidth; x++, theta += thetaoffset,pdst++){\r\n\t\t\t\tfloat beta = (alpha <= theta) ? theta - alpha : 2 * M_PI + theta - alpha; // angle of polar ray in ellipse coords (alpha + beta = theta)\r\n\t\t\t\tfloat s = r * ellA * cos(beta), t = r * ellB * sin(beta);\r\n\t\t\t\tfloat a = centerX + cosAlpha * s - sinAlpha * t, b = centerY + sinAlpha * s + cosAlpha * t;\r\n\t\t\t\tint coordX = cvRound(a);\r\n\t\t\t\tint coordY = cvRound(b);\r\n\t\t\t\tif (coordX < 0 || coordY < 0 || coordX >= srcwidth || coordY >= srcheight){\r\n\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t*pdst = psrc[coordY*srcstep+coordX];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse if (interpolation == INTER_LINEAR){\r\n\t\tfor (int y=0; y < dstheight; y++, pdst+= dstoffset, r+= roffset){\r\n\t\t\tfloat theta = 0;\r\n\t\t\tfor (int x=0; x < dstwidth; x++, theta += thetaoffset,pdst++){\r\n\t\t\t\tfloat beta = (alpha <= theta) ? theta - alpha : 2 * M_PI + theta - alpha; // angle of polar ray in ellipse coords (alpha + beta = theta)\r\n\t\t\t\tfloat s = r * ellA * cos(beta), t = r * ellB * sin(beta);\r\n\t\t\t\tfloat a = centerX + cosAlpha * s - sinAlpha * t, b = centerY + sinAlpha * s + cosAlpha * t;\r\n\t\t\t\tint coordX = cvFloor(a);\r\n\t\t\t\tint coordY = cvFloor(b);\r\n\t\t\t\tif (coordX >= 0){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(psrc[offset])) + dx*(float)(psrc[offset+1]))+ dy*((1-dx)*((float)(psrc[offset+srcstep])) + dx*(float)(psrc[offset+1+srcstep])));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(psrc[offset])) + dx*(float)(psrc[offset+1])) + dy * ((float)fill));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){// right out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dx)*((1-dy)*((float)(psrc[offset]))+ dy*((float)(psrc[offset+srcstep]))) + dx * ((float)fill));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom right out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(psrc[offset])) + dx * ((float) fill)) + dy * ((float) fill));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){// top out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((dy)*((1-dx)*((float)(psrc[offset+srcstep])) + dx*(float)(psrc[offset+1+srcstep])) + (1-dy) * ((float) fill));\r\n\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){// top right out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((dy)*((1-dx)*((float)(psrc[offset+srcstep])) + dx * ((float)fill)) + (1-dy) * ((float) fill));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if (coordX == -1){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordY < srcheight-1){// left out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(dx*((1-dy)*(float)(psrc[offset+1]) + dy*(float)(psrc[offset+1+srcstep])) + (1-dx) * ((float) fill));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom left out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((dx)*((float)(psrc[offset+1])) + (1-dx) * ((float) fill)) + dy * ((float) fill));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){ // top left out\r\n\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t*pdst = saturate_cast<uchar>((dy)*((dx)*((float)(psrc[offset+1+srcstep])) + (1-dx) * ((float) fill)) + (1-dy) * ((float)fill));\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse { // INTER_LINEAR_REPEAT (repeats last pixel value)\r\n\t\tuchar * firstLine = pdst + dst.step;\r\n\t\tfor (int y=0; y < dstheight; y++, pdst+= dstoffset, r+= roffset){\r\n\t\t\tfloat theta = 0;\r\n\t\t\tfor (int x=0; x < dstwidth; x++, theta += thetaoffset,pdst++){\r\n\t\t\t\tfloat beta = (alpha <= theta) ? theta - alpha : 2 * M_PI + theta - alpha; // angle of polar ray in ellipse coords (alpha + beta = theta)\r\n\t\t\t\tfloat s = r * ellA * cos(beta), t = r * ellB * sin(beta);\r\n\t\t\t\tfloat a = centerX + cosAlpha * s - sinAlpha * t, b = centerY + sinAlpha * s + cosAlpha * t;\r\n\t\t\t\tint coordX = cvFloor(a);\r\n\t\t\t\tint coordY = cvFloor(b);\r\n\t\t\t\tif (coordX >= 0){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(psrc[offset])) + dx*(float)(psrc[offset+1]))+ dy*((1-dx)*((float)(psrc[offset+srcstep])) + dx*(float)(psrc[offset+1+srcstep])));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dx)*((float)(psrc[offset])) + dx*(float)(psrc[offset+1])));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){// right out\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dy)*((float)(psrc[offset]))+ dy*((float)(psrc[offset+srcstep]))));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom right out\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = psrc[offset];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){// top out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dx)*((float)(psrc[offset+srcstep])) + dx*(float)(psrc[offset+1+srcstep])));\r\n\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){// top right out\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = psrc[offset+srcstep];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\t*pdst = *(pdst - dst.step);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = fill; // one row above;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if (coordX == -1){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordY < srcheight-1){// left out\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dy)*(float)(psrc[offset+1]) + dy*(float)(psrc[offset+1+srcstep])));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom left out\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = psrc[offset+1];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){ // top left out\r\n\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t*pdst = psrc[offset+1+srcstep];\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn roffset;\r\n}\r\n\r\n/*\r\n * Calculates the mapped (polar) image of source using transformation center (polar origin) and radius.\r\n *\r\n * src: CV_8UC1 (cartesian) source image\r\n * dst: CV_8UC1 (polar) destination image (same size as src)\r\n * centerX: x-coordinate of polar origin in (floating point) pixels of the source image\r\n * centerY: y-coordinate of polar origin in (floating point) pixels of the source image\r\n * radius: radius in pixels of the source image (to map whole image, this should be the maximum of distances between origin and corners)\r\n * interpolation: interpolation mode (INTER_NEAREST, INTER_LINEAR or INTER_LINEAR_REPEAT)\r\n * fill: fill value for pixels out of the image\r\n *\r\n * returning: polar resolution\r\n */\r\nfloat polarTransform(const Mat& src, Mat& dst, const float centerX = 0, const float centerY = 0, const float radius = -1, const int interpolation = INTER_LINEAR, const uchar fill = 0) {\r\n\tint dstheight = dst.rows;\r\n\tint dstwidth = dst.cols;\r\n\tint srcheight = src.rows;\r\n\tint srcwidth = src.cols;\r\n\tfloat rad = radius;\r\n\tif (rad < 0){\r\n\t\tfloat dist1 = centerX*centerX;\r\n\t\tfloat dist2 = centerY*centerY;\r\n\t\tfloat dist3 = (srcwidth-centerX)*(srcwidth-centerX);\r\n\t\tfloat dist4 = (srcheight-centerY)*(srcheight-centerY);\r\n\t\trad = max(max(sqrt(dist1+dist2),sqrt(dist1+dist4)),max(sqrt(dist3+dist2),sqrt(dist3+dist4)));\r\n\t}\r\n\tuchar * pdst = dst.data;\r\n\tuchar * psrc = src.data;\r\n\tint dstoffset = dst.step - dstwidth;\r\n\tint srcstep = src.step;\r\n\tfloat roffset = rad/(dstheight-1);\r\n\tfloat r = 0;\r\n\tfloat thetaoffset = 2.f * M_PI / dstwidth;\r\n\tif (interpolation == INTER_NEAREST){\r\n\t\tfor (int y=0; y < dstheight; y++, pdst+= dstoffset, r+= roffset){\r\n\t\t\tfloat theta = 0;\r\n\t\t\tfor (int x=0; x < dstwidth; x++, theta += thetaoffset,pdst++){\r\n\t\t\t\tfloat a = centerX + r * cos(theta);//std::cos(theta);\r\n\t\t\t\tfloat b = centerY + r * sin(theta);//std::sin(theta);\r\n\t\t\t\tint coordX = cvRound(a);\r\n\t\t\t\tint coordY = cvRound(b);\r\n\t\t\t\tif (coordX < 0 || coordY < 0 || coordX >= srcwidth || coordY >= srcheight){\r\n\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t*pdst = psrc[coordY*srcstep+coordX];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse if (interpolation == INTER_LINEAR){\r\n\t\tfor (int y=0; y < dstheight; y++, pdst+= dstoffset, r+= roffset){\r\n\t\t\tfloat theta = 0;\r\n\t\t\tfor (int x=0; x < dstwidth; x++, theta += thetaoffset,pdst++){\r\n\t\t\t\tfloat a = centerX + r * cos(theta);//std::cos(theta);\r\n\t\t\t\tfloat b = centerY + r * sin(theta);//std::sin(theta);\r\n\t\t\t\tint coordX = cvFloor(a);\r\n\t\t\t\tint coordY = cvFloor(b);\r\n\t\t\t\tif (coordX >= 0){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(psrc[offset])) + dx*(float)(psrc[offset+1]))+ dy*((1-dx)*((float)(psrc[offset+srcstep])) + dx*(float)(psrc[offset+1+srcstep])));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(psrc[offset])) + dx*(float)(psrc[offset+1])) + dy * ((float)fill));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){// right out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dx)*((1-dy)*((float)(psrc[offset]))+ dy*((float)(psrc[offset+srcstep]))) + dx * ((float)fill));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom right out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(psrc[offset])) + dx * ((float) fill)) + dy * ((float) fill));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){// top out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((dy)*((1-dx)*((float)(psrc[offset+srcstep])) + dx*(float)(psrc[offset+1+srcstep])) + (1-dy) * ((float) fill));\r\n\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){// top right out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((dy)*((1-dx)*((float)(psrc[offset+srcstep])) + dx * ((float)fill)) + (1-dy) * ((float) fill));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if (coordX == -1){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordY < srcheight-1){// left out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(dx*((1-dy)*(float)(psrc[offset+1]) + dy*(float)(psrc[offset+1+srcstep])) + (1-dx) * ((float) fill));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom left out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((dx)*((float)(psrc[offset+1])) + (1-dx) * ((float) fill)) + dy * ((float) fill));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){ // top left out\r\n\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t*pdst = saturate_cast<uchar>((dy)*((dx)*((float)(psrc[offset+1+srcstep])) + (1-dx) * ((float) fill)) + (1-dy) * ((float)fill));\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse { // INTER_LINEAR_REPEAT (repeats last pixel value)\r\n\t\tuchar * firstLine = pdst + dst.step;\r\n\t\tfor (int y=0; y < dstheight; y++, pdst+= dstoffset, r+= roffset){\r\n\t\t\tfloat theta = 0;\r\n\t\t\tfor (int x=0; x < dstwidth; x++, theta += thetaoffset,pdst++){\r\n\t\t\t\tfloat a = centerX + r * cos(theta);//std::cos(theta);\r\n\t\t\t\tfloat b = centerY + r * sin(theta);//std::sin(theta);\r\n\t\t\t\tint coordX = cvFloor(a);\r\n\t\t\t\tint coordY = cvFloor(b);\r\n\t\t\t\tif (coordX >= 0){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>((1-dy)*((1-dx)*((float)(psrc[offset])) + dx*(float)(psrc[offset+1]))+ dy*((1-dx)*((float)(psrc[offset+srcstep])) + dx*(float)(psrc[offset+1+srcstep])));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom out\r\n\t\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dx)*((float)(psrc[offset])) + dx*(float)(psrc[offset+1])));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){\r\n\t\t\t\t\t\t\tif (coordY < srcheight-1){// right out\r\n\t\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dy)*((float)(psrc[offset]))+ dy*((float)(psrc[offset+srcstep]))));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom right out\r\n\t\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t\t*pdst = psrc[offset];\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){\r\n\t\t\t\t\t\tif (coordX < srcwidth-1){// top out\r\n\t\t\t\t\t\t\tfloat dx = a-coordX;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dx)*((float)(psrc[offset+srcstep])) + dx*(float)(psrc[offset+1+srcstep])));\r\n\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordX == srcwidth-1){// top right out\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = psrc[offset+srcstep];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\t*pdst = *(pdst - dst.step);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = fill; // one row above;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if (coordX == -1){\r\n\t\t\t\t\tif (coordY >= 0){\r\n\t\t\t\t\t\tif (coordY < srcheight-1){// left out\r\n\t\t\t\t\t\t\tfloat dy = b-coordY;\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = saturate_cast<uchar>(((1-dy)*(float)(psrc[offset+1]) + dy*(float)(psrc[offset+1+srcstep])));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (coordY == srcheight-1){ // bottom left out\r\n\t\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t\t*pdst = psrc[offset+1];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (coordY == -1){ // top left out\r\n\t\t\t\t\t\tint offset = coordY*srcstep+coordX;\r\n\t\t\t\t\t\t*pdst = psrc[offset+1+srcstep];\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if (pdst >= firstLine){\r\n\t\t\t\t\t*pdst = *(pdst - dst.step); // one row above;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\t*pdst = fill;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn roffset;\r\n}\r\n\r\n/**\r\n * Constructs a gabor 2D kernel\r\n *\r\n * kernel: CV_32FC1 image of specific size (kernel.cols%2 and kernel.rows%2 should be 1)\r\n * lambda: wavelength of cosine factor\r\n * theta: orientation of normal to parallel stripes\r\n * psi: phase offset\r\n * sigma: gaussian sigma parameter\r\n * gamma: spatial aspect ratio\r\n *\r\n * returning: gabor kernel\r\n */\r\nvoid gaborKernel(Mat& kernel,const float lambda,const float theta,const float psi,const float sigma,const float gamma){\r\n\tMatIterator_<float> p = kernel.begin<float>();\r\n\tint width = kernel.cols;\r\n\tint height = kernel.rows;\r\n\tint rx = width/2;\r\n\tint ry = height/2;\r\n\tfloat sigma_x = sigma;\r\n\tfloat sigma_y = sigma/gamma;\r\n\tfor (int y=-ry,i=0;i<height;y++,i++){\r\n\t\tfor (int x=-rx,j=0;j<width;x++,j++,p++){\r\n\t\t\tfloat x_theta = x*std::cos(theta)+y*std::sin(theta);\r\n\t\t\tfloat y_theta =-x*std::sin(theta)+y*std::cos(theta);\r\n\t\t\t*p = 1 / (2*M_PI*sigma_x*sigma_y) * std::exp(-.5f*((x_theta*x_theta)/(sigma_x*sigma_x) + (y_theta*y_theta)/(sigma_y*sigma_y)))*std::cos(2*M_PI/lambda*x_theta+psi);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Normalizes a kernel, such that the area under the kernel is 1\r\n *\r\n * kernel: output CV_32FC1 image of specific size\r\n */\r\nvoid kernelNormArea(Mat& kernel){\r\n\tdouble sum = 0;\r\n\tMatIterator_<float> it;\r\n\tfor (it = kernel.begin<float>(); it < kernel.end<float>(); it++){\r\n\t\tsum += *it;\r\n\t}\r\n\tif (sum != 0){\r\n\t\tfor (it = kernel.begin<float>(); it < kernel.end<float>(); it++){\r\n\t\t\t*it /= sum;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Normalizes a kernel, such that the value of the absolute maximum (peak) of the kernel is 1\r\n *\r\n * kernel: output CV_32FC1 image of specific size\r\n */\r\nvoid kernelNormPeak(Mat& kernel){\r\n\tfloat peak = 0;\r\n\tMatIterator_<float> it;\r\n\tfor (it = kernel.begin<float>(); it < kernel.end<float>(); it++){\r\n\t\tfloat val = std::abs(*it);\r\n\t\tif (val > peak) peak = val;\r\n\t}\r\n\tif (peak != 0){\r\n\t\tfor (it = kernel.begin<float>(); it < kernel.end<float>(); it++){\r\n\t\t\t*it /= peak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Interpolates an array by linearly filling all values less than zero\r\n * arr: CV_32FC1 array to be normalized\r\n */\r\nvoid interpolateArr(Mat& arr){\r\n\tfloat *c = (float *) arr.data;\r\n\tfloat *p = (float *) arr.data;\r\n\tint width = arr.cols;\r\n\tint pos = width-1;\r\n\t// repair beginning, if needed\r\n\tp += pos;\r\n\twhile (pos > 0 && *p < 0) {p--; pos--;} // find previous intact point\r\n\tif (pos == 0) return; // nothing, we can do\r\n\tint startx = pos;\r\n\tfloat starty = c[pos];\r\n\tpos = 0;\r\n\tp = c;\r\n\twhile (pos < width && *p < 0) {p++; pos++;} // find next intact point\r\n\tint endx = pos;\r\n\tfloat endy = c[pos];\r\n\tint diffx1 = width - startx;\r\n\tint diffx = diffx1 + endx;\r\n\tif (diffx > 1){ // repairing needed\r\n\t\tp = (c + startx + 1);\r\n\t\tfloat delta = (endy - starty) / diffx;\r\n\t\tfor (int i=1;i<diffx1;i++,p++){\r\n\t\t\t*p = starty + i * delta;\r\n\t\t}\r\n\t\tp = c;\r\n\t\tfor (int i=diffx1; i<diffx; i++, p++){\r\n\t\t\t*p = starty + i * delta;\r\n\t\t}\r\n\t}\r\n\tstartx = endx;\r\n\tstarty = endy;\r\n\tp = c + startx + 1;\r\n\tpos = startx + 1;\r\n\twhile (pos < width && *p >= 0) {p++; pos++;} // find next damaged point\r\n\tif (pos == width) return; // nothing more, we can do\r\n\telse { // intact point is the point before\r\n\t\tstartx = pos - 1;\r\n\t\tstarty = c[pos-1];\r\n\t}\r\n\tpos++;p++;\r\n\twhile (pos < width){\r\n\t\t// find next intact point and interpolate\r\n\t\twhile (pos < width && *p < 0) {p++; pos++;} // find next intact point\r\n\t\tendx = pos;\r\n\t\tendy = c[pos];\r\n\t\tdiffx = endx-startx;\r\n\t\tfloat delta = (endy - starty) / diffx;\r\n\t\tp = (c + startx + 1);\r\n\t\tfor (int i=1; i<diffx; i++, p++){\r\n\t\t\t*p = starty + i * delta;\r\n\t\t}\r\n\t\tstartx = endx;\r\n\t\tstarty = endy;\r\n\t\tp = c + startx + 1;\r\n\t\tpos = startx + 1;\r\n\t\t// and then look for next non-intact point\r\n\t\twhile (pos < width && *p >= 0) {p++; pos++;} // find next damaged point\r\n\t}\r\n}\r\n\r\n/**\r\n * Filters polar image for edges\r\n *\r\n * src: source image\r\n * filtered: result image (src.rows, src.cols, CV_32FC1)\r\n * fast: if true employs only one filter direction\r\n */\r\nvoid findHorizontalEdges(const Mat& src, const Mat& reflect, Mat& filtered){\r\n\t\tint fsize = 21;\r\n\t\tMat filter(fsize,fsize,CV_32FC1);\r\n\t\tgaborKernel(filter,8*M_PI,-M_PI/2,M_PI/2,6,0.5);\r\n\t\tkernelNormPeak(filter);\r\n\t\tMat src2(src.rows,src.cols+2*fsize,CV_8UC1);\r\n\t\tMat p1(src2,cv::Rect(0,0,fsize,src.rows));\r\n\t\tMat p2(src2,cv::Rect(fsize,0,src.cols,src.rows));\r\n\t\tMat p3(src2,cv::Rect(src.cols+fsize,0,fsize,src.rows));\r\n\t\tMat p4(src,cv::Rect(0,0,fsize,src.rows));\r\n\t\tMat p5(src,cv::Rect(src.cols-fsize,0,fsize,src.rows));\r\n\t\tp5.copyTo(p1);\r\n\t\tsrc.copyTo(p2);\r\n\t\tp4.copyTo(p3);\r\n\r\n\t\t//kernelWrite(filter,\"kernel.png\");\r\n\t\tMat filtered2(filtered.rows,filtered.cols+2*fsize,CV_32FC1);\r\n\t\tMat p6(filtered2,cv::Rect(fsize,0,filtered.cols,filtered.rows));\r\n\t\tfilter2D(src2,filtered2,filtered2.depth(),filter,cvPoint(-1,-1),0,BORDER_CONSTANT);\r\n\t\tmaskValue(p6,filtered,reflect,255,0);\r\n\t\t/*\r\n\t\tMat filter(21,21,CV_32FC1);\r\n\t\tgaborKernel(filter,8*M_PI,-M_PI/2,M_PI/2,6,0.5);\r\n\t\tkernelNormPeak(filter);\r\n\t\t//kernelWrite(filter,\"kernel.png\");\r\n\t\tfilter2D(src,filtered,filtered.depth(),filter,cvPoint(-1,-1),0,BORDER_REPLICATE);\r\n\t\tmask2f(filtered,filtered,reflect,255,0);*/\r\n}\r\n\r\n/**\r\n * Interpolates a contour by linearly filling all values less than zero\r\n * contour: contour to be normalized\r\n */\r\nvoid contInterpolate(Mat& cont){\r\n\tint *c = (int *) cont.data;\r\n\tint *p = (int *) cont.data;\r\n\tint width = cont.cols;\r\n\tint pos = width-1;\r\n\t// repair beginning, if needed\r\n\tp += pos;\r\n\twhile (pos > 0 && *p < 0) {p--; pos--;} // find previous intact point\r\n\tif (pos == 0) return; // nothing, we can do\r\n\tint startx = pos;\r\n\tint starty = c[pos];\r\n\tpos = 0;\r\n\tp = c;\r\n\twhile (pos < width && *p < 0) {p++; pos++;} // find next intact point\r\n\tint endx = pos;\r\n\tint endy = c[pos];\r\n\tint diffx1 = width - startx;\r\n\tint diffx = diffx1 + endx;\r\n\tif (diffx > 1){ // repairing needed\r\n\t\tp = (c + startx + 1);\r\n\t\tfloat delta = ((float)(endy - starty)) / diffx;\r\n\t\tfor (int i=1;i<diffx1;i++,p++){\r\n\t\t\t*p = cvRound(starty + i * delta);\r\n\t\t}\r\n\t\tp = c;\r\n\t\tfor (int i=diffx1; i<diffx; i++, p++){\r\n\t\t\t*p = cvRound(starty + i * delta);\r\n\t\t}\r\n\t}\r\n\tstartx = endx;\r\n\tstarty = endy;\r\n\tp = c + startx + 1;\r\n\tpos = startx + 1;\r\n\twhile (pos < width && *p >= 0) {p++; pos++;} // find next damaged point\r\n\tif (pos == width) return; // nothing more, we can do\r\n\telse { // intact point is the point before\r\n\t\tstartx = pos - 1;\r\n\t\tstarty = c[pos-1];\r\n\t}\r\n\tpos++;p++;\r\n\twhile (pos < width){\r\n\t\t// find next intact point and interpolate\r\n\t\twhile (pos < width && *p < 0) {p++; pos++;} // find next intact point\r\n\t\tendx = pos;\r\n\t\tendy = c[pos];\r\n\t\tdiffx = endx-startx;\r\n\t\tfloat delta = ((float)(endy - starty)) / diffx;\r\n\t\tp = (c + startx + 1);\r\n\t\tfor (int i=1; i<diffx; i++, p++){\r\n\t\t\t*p = cvRound(starty + i * delta);\r\n\t\t}\r\n\t\tstartx = endx;\r\n\t\tstarty = endy;\r\n\t\tp = c + startx + 1;\r\n\t\tpos = startx + 1;\r\n\t\t// and then look for next non-intact point\r\n\t\twhile (pos < width && *p >= 0) {p++; pos++;} // find next damaged point\r\n\t}\r\n}\r\n\r\n/**\r\n * Conducts a gradient fit cont onto gradient image\r\n * cont: contour (1,width,CV_32SC1)\r\n * gradient: edge image (CV_32FC1)\r\n */\r\nvoid gradientFit(Mat& cont, const Mat& gradient, const int maxrange, const int from = 0, const int to = -1){\r\n\tCV_Assert(cont.type() == CV_32FC1);\r\n\tCV_Assert(gradient.type() == CV_32FC1);\r\n\tint width = gradient.cols;\r\n\tint height = gradient.rows;\r\n\tMatIterator_<float> p = cont.begin<float>();\r\n\tfloat * g = (float *)gradient.data;\r\n\tint gstride = gradient.step / sizeof(float);\r\n\tfor (int x=0; x<width; x++, g++, p++){\r\n\t\tint val = min(max(0,cvRound(*p)),height-1);\r\n\t\tif (*(g + val*gstride) > 0){ // not masked\r\n\t\t\tint pvalfrom = max(max(0,from),min(height-1,val - maxrange));\r\n\t\t\tint pvalto = max(0,min((to < 0) ? height-1 : to,val + maxrange));\r\n\t\t\tfloat * row = g + pvalfrom * gstride;\r\n\t\t\tint maxy = pvalfrom;\r\n\t\t\tfloat maxrow = - FLT_MAX;\r\n\t\t\tfor (int y = pvalfrom; y < pvalto; y++, row += gstride) {\r\n\t\t\t\tif (*row > maxrow){\r\n\t\t\t\t\tmaxrow = *row;\r\n\t\t\t\t\tmaxy = y;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t*p = maxy;\r\n\t\t}\r\n\t\telse {\r\n\t\t\t*p = val;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Modifies a contour such that only a certain amount of best edges are kept - other contour points are linearly interpolated.\r\n * cont: contour (1,width,CV_32SC1)\r\n * gradient: edge image (CV_32FC1)\r\n */\r\nvoid contKeepBestEdges(Mat& cont, const Mat& gradient){\r\n\tCV_Assert(cont.type() == CV_32SC1);\r\n\tCV_Assert(gradient.type() == CV_32FC1);\r\n\tint width = cont.cols;\r\n\tint histbins = 100;\r\n\tMat hist(1,histbins,CV_32SC1);\r\n\tMat edges(1,width,CV_32SC1);\r\n\tMatIterator_<int> p = cont.begin<int>();\r\n\tMatIterator_<int> e = cont.end<int>();\r\n\tMatIterator_<float> pg = edges.begin<float>();\r\n\tfloat * g = (float *)gradient.data;\r\n\tint gstride = gradient.step / sizeof(float);\r\n\tfloat min = FLT_MAX;\r\n\tfloat max = -FLT_MAX;\r\n\tfor (; p != e; pg++, g++, p++){\r\n\t\tfloat val = *(g + (*p) * gstride);\r\n\t\t*pg = val;\r\n\t\tif (val > max) max = val;\r\n\t\tif (val < min) min = val;\r\n\t}\r\n\tfloat histmax = max + (max-min)/histbins;\r\n\thist2f(edges,hist,min,histmax);\r\n\tfloat low = histquant2u(hist,width,0.33) * (histmax-min) * 1. / histbins + min;\r\n\t// eliminate outliers\r\n\tp = cont.begin<int>();\r\n\tpg = edges.begin<float>();\r\n\tfor (; p != e; p++, pg++){\r\n\t\tif (*pg < low) *p = -1;\r\n\t}\r\n\tcontInterpolate(cont);\r\n}\r\n\r\n/**\r\n * Calculates the energy of a Boundary\r\n *\r\n * src: CV_32FC1 source image\r\n * cartBoundary: CV_32FC2 contour in cartesian coordinates (x and y coordinates)\r\n * polarBoundary: CV_32FC1 polar values\r\n * my: gaussian mean\r\n * sigma: gaussian sigma\r\n * returning: resulting energy (sum)\r\n */\r\ndouble boundaryEnergyWeighted(const Mat& src, const Mat& cartBoundary, const RotatedRect& ellipse, const float resolution, const float my, const float sigma){\r\n\tdouble sum = 0;\r\n\tint width = src.cols;\r\n\tint height = src.rows;\r\n\tfloat centerX = ellipse.center.x;\r\n\tfloat centerY = ellipse.center.y;\r\n\tfloat ellA = ellipse.size.width/2;\r\n\tfloat ellB = ellipse.size.height/2;\r\n\tfloat corrA = ellA * resolution;\r\n\tfloat corrB = ellB * resolution;\r\n\tdouble alpha = (ellipse.angle)*M_PI/180; // inclination angle of the ellipse\r\n\tif (alpha > M_PI) alpha -= M_PI; // normalize alpha to [0,M_PI]\r\n\tdouble omega = 2 * M_PI - alpha; // angle for reverse transformation\r\n\tconst double cosOmega = cos(omega);\r\n\tconst double sinOmega = sin(omega);\r\n\tfloat * c = (float *)cartBoundary.data;\r\n\tdouble sigma2 = 2 * sigma * sigma;\r\n\tfor (float * e = c + 2*cartBoundary.cols; c != e; c+=2) {\r\n\t\tint x =  std::max(0,std::min(width-1,cvRound(c[0])));\r\n\t\tint y = std::max(0,std::min(height-1,cvRound(c[1])));\r\n\t\tfloat a = c[0] - centerX;\r\n\t\tfloat b = c[1] - centerY;\r\n\t\tfloat s = (cosOmega * a - sinOmega * b) / corrA;\r\n\t\tfloat t = (sinOmega * a + cosOmega * b) / corrB;\r\n\t\tfloat r = sqrt(s*s+t*t);\r\n\t\tdouble z = r - my;\r\n\t\tdouble w = cv::exp(-z*z / sigma2);\r\n\t\tsum += src.at<float>(y,x) * w;\r\n\t}\r\n\treturn sum;\r\n}\r\n\r\n/**\r\n * Calculates the energy of a Boundary\r\n *\r\n * src: CV_32FC1 source image\r\n * cartCont: CV_32FC1 contour in cartesian coordinates (x and y coordinates)\r\n *\r\n * returning: resulting energy (sum)\r\n */\r\ndouble boundaryEnergy(const Mat& src, const Mat& cartBoundary){\r\n\tdouble sum = 0;\r\n\tint width = src.cols;\r\n\tint height = src.rows;\r\n\tfloat* b = (float*)cartBoundary.data;\r\n\tfloat* e = b + 2*cartBoundary.cols;\r\n\twhile (b != e){\r\n\t\tint x = std::max(0, std::min(width - 1, cvRound(*b++)));\r\n\t\tint y = std::max(0, std::min(height - 1, cvRound(*b++)));\r\n\t\tsum += src.at<float>(y, x);\r\n\t}\r\n\treturn sum;\r\n}\r\n\r\n/**\r\n * Computes the maximum sum of a sliding window for a given line range\r\n * src: CV_32FC1 source image\r\n * line: offset, line\r\n * wsize: size of the window\r\n * from: inclusive starting index\r\n * to: exclusive ending index\r\n *\r\n * resulting: energy (line sum)\r\n */\r\ndouble lineSumWindowed(const Mat& src, const int line = 0, const int wsize = -1, const int from = 0, const int to = -1){\r\n\tMatConstIterator_<float> p = src.begin<float>();\r\n\tMatConstIterator_<float> e;\r\n\tMatConstIterator_<float> m;\r\n\tint end = (to < 0) ? src.cols : min(src.cols,to);\r\n\tint start = max(0,min(src.cols-1,from));\r\n\tint y = max(0,min(src.rows-1,line));\r\n\tint windowsize = (wsize < 0) ? ((start <= end) ? end-start : (src.cols + end - start)) : min(wsize,((start <= end) ? end-start : (src.cols + end - start)));\r\n\tdouble sum = 0;\r\n\tp += y * src.cols + start;\r\n\tdouble maxsum = -FLT_MAX;\r\n\tif (start <= end){\r\n\t\tm = p;\r\n\t\t// build up first window\r\n\t\tfor(e = p + windowsize; p != e; p++){\r\n\t\t\tsum += *p;\r\n\t\t}\r\n\t\tmaxsum = sum;\r\n\t\t// now window has energy, lets shift window and compare energy\r\n\t\tfor(e = p + (end - start - windowsize); p != e; p++, m++){\r\n\t\t\tsum = sum + *p - *m;\r\n\t\t\tif (sum > maxsum) maxsum = sum;\r\n\t\t}\r\n\t}\r\n\telse if (windowsize >= src.cols - start){\r\n\t\tm = p;\r\n\t\tint size2 = src.cols - start;\r\n\t\tfor(e = p + size2; p != e; p++){\r\n\t\t\tsum += *p;\r\n\t\t}\r\n\t\tp = src.begin<float>() + (y * src.cols);\r\n\t\tfor(e = p + (windowsize-size2); p != e; p++){\r\n\t\t\tsum += *p;\r\n\t\t}\r\n\t\tmaxsum = sum;\r\n\t\tfor(e = p + min(end-windowsize+size2,size2); p != e; p++, m++){\r\n\t\t\tsum = sum + *p - *m;\r\n\t\t\tif (sum > maxsum) maxsum = sum;\r\n\t\t}\r\n\t\tm = src.begin<float>() + (y * src.cols);\r\n\t\tfor(e = p + max(0,end - windowsize); p != e; p++, m++){\r\n\t\t\tsum = sum + *p - *m;\r\n\t\t\tif (sum > maxsum) maxsum = sum;\r\n\t\t}\r\n\t}\r\n\telse { // (wsize < cont.cols - from){\r\n\t\tm = p;\r\n\t\tint size2 = src.cols - start;\r\n\t\tfor(e = p + windowsize; p != e; p++){\r\n\t\t\tsum += *p;\r\n\t\t}\r\n\t\tmaxsum = sum;\r\n\t\tfor(e = p + (size2 - windowsize); p != e; p++, m++){\r\n\t\t\tsum = sum + *p - *m;\r\n\t\t\tif (sum > maxsum) maxsum = sum;\r\n\t\t}\r\n\t\tp = src.begin<float>() + (y * src.cols);\r\n\t\tfor(e = p + min(end,windowsize); p != e; p++, m++){\r\n\t\t\tsum = sum + *p - *m;\r\n\t\t\tif (sum > maxsum) maxsum = sum;\r\n\t\t}\r\n\t\tm = src.begin<float>() + (y * src.cols);\r\n\t\tfor(e = p + max(0,end-windowsize); p != e; p++, m++){\r\n\t\t\tsum = sum + *p - *m;\r\n\t\t\tif (sum > maxsum) maxsum = sum;\r\n\t\t\tif (sum > maxsum) maxsum = sum;\r\n\t\t}\r\n\t}\r\n\treturn maxsum;\r\n}\r\n\r\n/**\r\n * Samples an ellipse from center point using polar rays\r\n *\r\n * ellipse: rotated rectangle ellipse representation\r\n * cont: CV_32FC1 1 x size sampled contour (360/size is used as sample angle theta)\r\n * centerX: polar center x-coordinate\r\n * centerY: polar center y-coordinate\r\n */\r\nvoid ellipse2polar(const RotatedRect& ellipse, Mat& cont, const float centerX, const float centerY){\r\n\tconst int width = cont.cols;\r\n\tfloat theta = 0; // angle of the polar ray\r\n\tconst float thetaoffset = 2.f * M_PI / width;\r\n\tconst float a = ellipse.size.width/2; // big half axis of the ellipse\r\n\tconst float aSquare = a*a;\r\n\tconst float b = ellipse.size.height/2; // small half axis of the ellipse\r\n\tconst float bSquare = b*b;\r\n\tdouble alpha = (ellipse.angle)*M_PI/180; // inclination angle of the ellipse\r\n\tif (alpha > M_PI) alpha -= M_PI; // normalize alpha to [0,M_PI]\r\n\tdouble omega = 2 * M_PI - alpha; // angle for reverse transformation\r\n\tconst double cosAlpha = cos(alpha);\r\n\tconst double sinAlpha = sin(alpha);\r\n\tconst double cosOmega = cos(omega);\r\n\tconst double sinOmega = sin(omega);\r\n\tconst float cXunrot = centerX - ellipse.center.x;\r\n\tconst float cYunrot = centerY - ellipse.center.y;\r\n\tconst float cX = cosOmega * cXunrot - sinOmega * cYunrot; // center x-coordinate in ellipse coords\r\n\tconst float cY = sinOmega * cXunrot + cosOmega * cYunrot; // center x-coordinate in ellipse coords\r\n\tfloat *p = (float *)cont.data;\r\n\tfor (float *e = p+width; p != e; p++, theta += thetaoffset){\r\n\t\tfloat beta = (alpha <= theta) ? theta - alpha : 2 * M_PI + theta - alpha; // angle of polar ray in ellipse coords (alpha + beta = theta)\r\n\t\t//cout << \"Shooting ray in direction: \" << beta / M_PI * 180 << \" ( alpha is \" << alpha / M_PI * 180 << \" theta is: \" << theta / M_PI * 180 << \")\" << endl;\r\n\t\tfloat x=0, y=0;\r\n\t\tif (abs(beta-M_PI/2) < 0.00001){\r\n\t\t\t// return positive y value of ellipse at cX\r\n\t\t\tx=cX;\r\n\t\t\ty=b*sqrt(aSquare-cX*cX)/a;\r\n\t\t}\r\n\t\telse if(abs(beta-3*M_PI/2) < 0.00001){\r\n\t\t\t// return negative y value of ellipse at cX\r\n\t\t\tx=cX;\r\n\t\t\ty=-b*sqrt(aSquare-cX*cX)/a;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfloat m = tan(beta); // steigung\r\n\t\t\t//cout << \"Steigung: \" << m << endl;\r\n\t\t\tfloat b1 = cY - m*cX; // verschiebung\r\n\t\t\tfloat mSquare = m*m;\r\n\t\t\tfloat D = aSquare*mSquare + bSquare - b1*b1;\r\n\t\t\tif (D <= 0) { // ERROR, entering desperate mode\r\n\t\t\t\t*p = 0; continue;\r\n\t\t\t}\r\n\t\t\telse { // Formula see Bartsch, p. 262\r\n\t\t\t\tD = sqrt(D);\r\n\t\t\t\tfloat N = bSquare + aSquare * mSquare;\r\n\t\t\t\tfloat T1 = -aSquare*m*b1;\r\n\t\t\t\tfloat T2 = a*b*D;\r\n\t\t\t\tfloat U1 = bSquare * b1;\r\n\t\t\t\tfloat U2 = a*b*m*D;\r\n\t\t\t\t// determine quadrant\r\n\t\t\t\tfloat y1 = (U1 + U2)/N;\r\n\t\t\t\tif (beta < M_PI){ // Q1 x: + y: + or Q2 x: - y: + let y decide\r\n\t\t\t\t\tif (y1-cY >= 0){\r\n\t\t\t\t\t\tx = (T1 + T2)/N;\r\n\t\t\t\t\t\ty = y1;\r\n\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tx = (T1 - T2)/N;\r\n\t\t\t\t\t\ty = (U1 - U2)/N;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse { // Q3 x: - y: - or Q4 x: + y: -\r\n\t\t\t\t\tif (y1-cY < 0){\r\n\t\t\t\t\t\tx = (T1 + T2)/N;\r\n\t\t\t\t\t\ty = y1;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tx = (T1 - T2)/N;\r\n\t\t\t\t\t\ty = (U1 - U2)/N;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t\t// rotate back to polar coords\r\n\t\tfloat fX = cosAlpha * x - sinAlpha * y - cXunrot;\r\n\t\tfloat fY = sinAlpha * x + cosAlpha * y - cYunrot;\r\n\t\t*p = sqrt(fX*fX+fY*fY);\r\n\t}\r\n}\r\n\r\n\r\n\r\n/**\r\n * Normalizes a function based on DFT by keeping the first numberCoeffs fourier coefficients only\r\n * f:            original signal, should be Mat (1, size, CV_32FC1);\r\n * norm:         normalized signal, should be Mat (1, size, CV_32FC1);\r\n * energy:\t\t total energy of the first numberCoeffs Fourier coefficients\r\n * numberCoeffs: number of fourrier coefficients to keep\r\n */\r\nvoid fourierNormalize(Mat& cont, Mat& norm, float& energy, const int numberCoeffs = -1){\r\n\tCV_Assert(cont.size() == norm.size());\r\n\tint size = cont.cols;\r\n\tint dftSize = getOptimalDFTSize(size);\r\n\tif (dftSize != size){\r\n\t\tprintf(\"WARNING ERROR\");\r\n\t\tMat g (1,dftSize,CV_32FC1);\r\n\t\tfloat mean = cv::mean(cont)[0];\r\n\t\tint * src = (int *) cont.data;\r\n\t\tMatIterator_<float> dst = g.begin<float>();\r\n\t\tdouble inc = ((double)size) / dftSize;\r\n\t\tdouble idx = 0;\r\n\t\tfor (MatConstIterator_<float> e = g.end<float>(); dst != e; dst++, idx += inc){\r\n\t\t\t*dst = src[min(size-1,cvRound(idx))] - mean;\r\n\t\t}\r\n\t\tMat gFourier (1,dftSize,CV_32FC1);\r\n\t\tdft(g,gFourier,CV_DXT_FORWARD);\r\n\t\tif (numberCoeffs >= 0 && (1 + 2*numberCoeffs) < dftSize){\r\n\t\t\tMat roi(gFourier,Rect(1 + 2*numberCoeffs,0,dftSize - (1 + 2*numberCoeffs),1));\r\n\t\t\troi.setTo(0);\r\n\t\t\troi = Mat(gFourier,Rect(1,0,2*numberCoeffs,1));\r\n\t\t\tenergy = cv::norm(roi);\r\n\t\t}\r\n\t\tdft(gFourier,g,CV_DXT_INV_SCALE);\r\n\t\tfloat * isrc = (float *) g.data;\r\n\t\tMatIterator_<int> idst = norm.begin<int>();\r\n\t\tinc = ((double)dftSize) / size;\r\n\t\tidx = 0;\r\n\t\tfor (MatConstIterator_<int> e = norm.end<int>(); idst != e; idst++, idx += inc){\r\n\t\t\t*idst = saturate_cast<int>(isrc[min(dftSize-1,cvRound(idx))] + mean);\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tMat g (1,dftSize,CV_32FC1);\r\n\t\tfloat mean = cv::mean(cont)[0];\r\n\t\tg = cont - mean;\r\n\t\tMat gFourier (1,dftSize,CV_32FC1);\r\n\t\tdft(g,gFourier,CV_DXT_FORWARD);\r\n\t\tif (numberCoeffs >= 0 && (1 + 2*numberCoeffs) < dftSize){\r\n\t\t\tMat roi(gFourier,Rect(1 + 2*numberCoeffs,0,dftSize - (1 + 2*numberCoeffs),1));\r\n\t\t\troi.setTo(0);\r\n\t\t\troi = Mat(gFourier,Rect(1,0,2*numberCoeffs,1));\r\n\t\t\tenergy = cv::norm(roi);\r\n\t\t}\r\n\t\tdft(gFourier,g,CV_DXT_INV_SCALE);\r\n\t\tnorm = g + mean;\r\n\t}\r\n}\r\n\r\n/**\r\n * Maps an ellipsopolar contour to cartesian coordinates\r\n * polar: CV_32FC1 1 x size array of radius values from center position\r\n * cart CV_32FC2 1 x size array of x- and y-positions from upper left corner\r\n * centerX: x-coordinate of center in cartesian coordinate system (upper-left corner)\r\n * centerY: y-coordinate of center in cartesian coordinate system (upper left corner)\r\n * resolution: polar resolution (i.e. pixels per unit in polar coords before considering axis stretch factors)\r\n * offset: optional offset added to the contour before the conversion\r\n */\r\nvoid ellipsopolar2Cart(const Mat& polar, Mat& cart, const RotatedRect& ellipse, const float resolution = 1, const float offset = 0) {\r\n\tCV_Assert(polar.type() == CV_32FC1);\r\n\tCV_Assert(cart.type() == CV_32FC2);\r\n\tCV_Assert(polar.cols == cart.cols);\r\n\tfloat centerX = ellipse.center.x;\r\n\tfloat centerY = ellipse.center.y;\r\n\tfloat ellA = ellipse.size.width/2;\r\n\tfloat ellB = ellipse.size.height/2;\r\n\tdouble alpha = (ellipse.angle)*M_PI/180; // inclination angle of the ellipse\r\n\tif (alpha > M_PI) alpha -= M_PI; // normalize alpha to [0,M_PI]\r\n\tconst double cosAlpha = cos(alpha);\r\n\tconst double sinAlpha = sin(alpha);\r\n\tfloat * d = (float *)cart.data;\r\n\tint width = polar.cols;\r\n\tconst float thetaoffset = 2 * M_PI / polar.cols;\r\n\tfloat theta = 0;\r\n\tfloat * p = (float *)polar.data;\r\n\tfor (int x=0; x<width; x++,p++,d++, theta += thetaoffset){\r\n\t\tfloat beta = (alpha <= theta) ? theta - alpha : 2 * M_PI + theta - alpha; // angle of polar ray in ellipse coords (alpha + beta = theta)\r\n\t\tfloat s = (*p + offset) * resolution * ellA * cos(beta), t = (*p + offset) * resolution * ellB * sin(beta);\r\n\t\t*d = centerX + cosAlpha * s - sinAlpha * t; // x coordiante\r\n\t\td++;\r\n\t\t*d = centerY + sinAlpha * s + cosAlpha * t; // y coordinate\r\n\t}\r\n}\r\n\r\n/**\r\n * Maps a cartesian contour to ellipsopolar coordinates (more precisely, only radius values are computed)\r\n */\r\nvoid cart2Ellipsopolar(const Mat& cart, Mat& polar, const RotatedRect& ellipse, const float resolution = 1) {\r\n\tCV_Assert(polar.type() == CV_32FC1);\r\n\tCV_Assert(cart.type() == CV_32FC2);\r\n\tCV_Assert(polar.cols == cart.cols);\r\n\tfloat centerX = ellipse.center.x;\r\n\tfloat centerY = ellipse.center.y;\r\n\tfloat ellA = ellipse.size.width/2;\r\n\tfloat ellB = ellipse.size.height/2;\r\n\tfloat corrA = ellA * resolution;\r\n\tfloat corrB = ellB * resolution;\r\n\tdouble alpha = (ellipse.angle)*M_PI/180; // inclination angle of the ellipse\r\n\tif (alpha > M_PI) alpha -= M_PI; // normalize alpha to [0,M_PI]\r\n\tdouble omega = 2 * M_PI - alpha; // angle for reverse transformation\r\n\tconst double cosOmega = cos(omega);\r\n\tconst double sinOmega = sin(omega);\r\n\tfloat * c = (float *)cart.data;\r\n\tint width = cart.cols;\r\n\tfloat * p = (float *)polar.data;\r\n\tfor (int x=0; x<width; x++,p++,c++){\r\n\t\t// rotate to ellipse coords\r\n\t\tfloat a = *c - centerX; c++;\r\n\t\tfloat b = *c - centerY;\r\n\t\tfloat s = (cosOmega * a - sinOmega * b) / corrA;\r\n\t\tfloat t = (sinOmega * a + cosOmega * b) / corrB;\r\n\t\t*p = sqrt(s*s+t*t);\r\n\t}\r\n}\r\n\r\n\r\n\r\n/**\r\n * Samples an ellipse in cartesian coordinates\r\n * cart: CV_32FC2 1 x size cartesian coordinates\r\n * ellipse: ellipse to be sampled\r\n */\r\nvoid ellipse2Cart(Mat& cart, const RotatedRect& ellipse) {\r\n\tCV_Assert(cart.type() == CV_32FC2);\r\n\tfloat centerX = ellipse.center.x;\r\n\tfloat centerY = ellipse.center.y;\r\n\tfloat ellA = ellipse.size.width/2;\r\n\tfloat ellB = ellipse.size.height/2;\r\n\tdouble alpha = (ellipse.angle)*M_PI/180; // inclination angle of the ellipse\r\n\tif (alpha > M_PI) alpha -= M_PI; // normalize alpha to [0,M_PI]\r\n\tconst double cosAlpha = cos(alpha);\r\n\tconst double sinAlpha = sin(alpha);\r\n\tfloat * d = (float *)cart.data;\r\n\tint width = cart.cols;\r\n\tconst float thetaoffset = 2 * M_PI / cart.cols;\r\n\tfloat theta = 0;\r\n\tfor (int x=0; x<width; x++, d++, theta += thetaoffset){\r\n\t\tfloat beta = (alpha <= theta) ? theta - alpha : 2 * M_PI + theta - alpha; // angle of polar ray in ellipse coords (alpha + beta = theta)\r\n\t\tfloat s = ellA * cos(beta), t = ellB * sin(beta);\r\n\t\t*d = centerX + cosAlpha * s - sinAlpha * t; // x coordiante\r\n\t\td++;\r\n\t\t*d = centerY + sinAlpha * s + cosAlpha * t; // y coordinate\r\n\t}\r\n}\r\n\r\n/**\r\n * Maps a polar contour to cartesian coordinates\r\n * polar: CV_32FC1 1 x size array of radius values from center position\r\n * cart CV_32FC2 1 x size array of x- and y-positions from upper left corner\r\n * centerX: x-coordinate of center in cartesian coordinate system (upper-left corner)\r\n * centerY: y-coordinate of center in cartesian coordinate system (upper left corner)\r\n * resolution: polar resolution (i.e. pixels per unit in polar coords, use maxDistToCorner() / (polar.rows-1))\r\n * offset: optional offset added to the contour before the conversion\r\n */\r\nvoid polar2Cart(const Mat& polar, Mat& cart, const float centerX = 0, const float centerY = 0, const float resolution = 1, const float offset = 0) {\r\n\tCV_Assert(polar.type() == CV_32FC1);\r\n\tCV_Assert(cart.type() == CV_32FC2);\r\n\tCV_Assert(polar.cols == cart.cols);\r\n\tfloat * d = (float *)cart.data;\r\n\tint width = polar.cols;\r\n\tconst float thetaoffset = 2 * M_PI / polar.cols;\r\n\tfloat theta = 0;\r\n\tfloat * s = (float *)polar.data;\r\n\tif (offset != 0){\r\n\t\tfor (int x=0; x<width; x++,s++,d++, theta += thetaoffset){\r\n\t\t\t*d = centerX + (*s + offset) * resolution * cos(theta); // x coordiante\r\n\t\t\td++;\r\n\t\t\t*d = centerY + (*s + offset) * resolution * sin(theta);; // y coordinate\r\n\t\t}\r\n\t}\r\n\telse if (centerX == 0 && centerY == 0 && resolution == 1){ // fast version\r\n\t\tfor (int x=0; x<width; x++,s++,d++, theta += thetaoffset){\r\n\t\t\t*d = *s * cos(theta); // x coordiante\r\n\t\t\td++;\r\n\t\t\t*d = *s * sin(theta);; // y coordinate\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tfor (int x=0; x<width; x++,s++,d++, theta += thetaoffset){\r\n\t\t\t*d = centerX + *s * resolution * cos(theta); // x coordiante\r\n\t\t\td++;\r\n\t\t\t*d = centerY + *s * resolution * sin(theta);; // y coordinate\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid ellipseNormalize(Mat& cont, Mat& norm){\r\n\tCV_Assert(cont.size() == norm.size());\r\n\tint width = cont.cols;\r\n\tMat cart (1,width,CV_32FC2);\r\n\tpolar2Cart(cont, cart, 0, 0, 1, 2.f * M_PI / width);\r\n\tRotatedRect ell = fitEllipse(cart);\r\n\tellipse2polar(ell,norm,0,0);\r\n}\r\n\r\n/**\r\n * Initializes a contour in polar or ellipsopolar transformed domain by first looking for the highest horizontal energy window.\r\n *\r\n * src: CV_32FC1 height x width polar or ellipsopolar gradient image\r\n * cont CV_32FC1 1 x width polar or ellipsopolar contour\r\n * min: minimum inclusive index\r\n * max: maximum exclusive index\r\n * useSectors: if true, look in left and right windows, otherwise look in entire range\r\n * sigma: fuzzy gaussian sigma (use < 0 to avoid fuzzy computation, default)\r\n * my: gaussian my\r\n */\r\nvoid initContour(const Mat& src, Mat& cont, const int min = 0, const int max = -1, const bool useSectors = false, const float sigma = -1, const float my = -1){\r\n\tconst int miny = std::max(0,std::min(min,src.rows - 1));\r\n\tconst int maxy = (max < 0) ? src.rows : std::min(src.rows,max);\r\n\tconst int width = cont.cols;\r\n\tint y = miny;\r\n\tint besty = y;\r\n\tdouble energy = -FLT_MAX;\r\n\tdouble sigma2 = 2 * sigma * sigma;\r\n\tdouble z = y - my;\r\n\tif (sigma > 0){ // with fuzzy logic\r\n\t\tif (useSectors){\r\n\t\t\tconst int windowSize = width/8;\r\n\t\t\tconst int windowRightFrom = 15*width / 16;\r\n\t\t\tconst int windowRightTo = 3*width / 16;\r\n\t\t\tconst int windowLeftFrom = 5*width / 16;\r\n\t\t\tconst int windowLeftTo = 9*width / 16;\r\n\t\t\tfor (; y < maxy; y++, z++){\r\n\t\t\t\tdouble w = cv::exp(-z*z / sigma2);\r\n\t\t\t\tdouble eng = (lineSumWindowed(src,y,windowSize,windowRightFrom,windowRightTo) + lineSumWindowed(src,y,windowSize,windowLeftFrom,windowLeftTo)) * w; //cv::exp(-z*z / sigma2);\r\n\t\t\t\tif (eng > energy) {\r\n\t\t\t\t\tenergy = eng;\r\n\t\t\t\t\tbesty = y;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfor (; y < maxy; y++, z++){\r\n\t\t\t\tdouble w = cv::exp(-z*z / sigma2);\r\n\t\t\t\tfloat eng = lineSumWindowed(src,y) * w;\r\n\t\t\t\tif (eng > energy) {\r\n\t\t\t\t\tenergy = eng;\r\n\t\t\t\t\tbesty = y;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse { // without fuzzy logic\r\n\t\tif (useSectors){\r\n\t\t\tconst int windowSize = width/8;\r\n\t\t\tconst int windowRightFrom = 15*width / 16;\r\n\t\t\tconst int windowRightTo = 3*width / 16;\r\n\t\t\tconst int windowLeftFrom = 5*width / 16;\r\n\t\t\tconst int windowLeftTo = 9*width / 16;\r\n\t\t\tfor (; y < maxy; y++, z++){\r\n\t\t\t\tdouble eng = (lineSumWindowed(src,y,windowSize,windowRightFrom,windowRightTo) + lineSumWindowed(src,y,windowSize,windowLeftFrom,windowLeftTo));\r\n\t\t\t\tif (eng > energy) {\r\n\t\t\t\t\tenergy = eng;\r\n\t\t\t\t\tbesty = y;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfor (; y < maxy; y++){\r\n\t\t\t\tfloat eng = lineSumWindowed(src,y);\r\n\t\t\t\tif (eng > energy) {\r\n\t\t\t\t\tenergy = eng;\r\n\t\t\t\t\tbesty = y;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcont.setTo(besty);\r\n}\r\n\r\n/**\r\n * Returns a subwindow of cart\r\n *\r\n * cart: CV_32FC2 1 x size cartesian contour\r\n *\r\n * returning sectorized contour\r\n */\r\nvoid cartSectors(const Mat& cart, Mat& sub){\r\n\tint width = cart.cols;\r\n\tconst int windowRightFrom = 15*width / 16;\r\n\tconst int windowRightTo = 3*width / 16;\r\n\tconst int windowLeftFrom = 5*width / 16;\r\n\tconst int windowLeftTo = 9*width / 16;\r\n\tif (sub.empty() || sub.type() != CV_32FC2 || sub.rows != 1 || sub.cols != width-windowRightFrom+windowRightTo+windowLeftTo-windowLeftFrom)\r\n\t\tsub.create(1,width-windowRightFrom+windowRightTo+windowLeftTo-windowLeftFrom,CV_32FC2);\r\n\tMat s1(cart,Rect(windowRightFrom,0,width-windowRightFrom,1));\r\n\tMat s2(cart,Rect(0,0,windowRightTo,1));\r\n\tMat s3(cart,Rect(windowLeftFrom,0,windowLeftTo-windowLeftFrom,1));\r\n\tMat d1(sub,Rect(0,0,width-windowRightFrom,1));\r\n\tMat d2(sub,Rect(width-windowRightFrom,0,windowRightTo,1));\r\n\tMat d3(sub,Rect(width-windowRightFrom+windowRightTo,0,windowLeftTo-windowLeftFrom,1));\r\n\ts1.copyTo(d1);\r\n\ts2.copyTo(d2);\r\n\ts3.copyTo(d3);\r\n}\r\n\r\n/** ------------------------------- Contour refinement ------------------------------- **/\r\n\r\n\r\n\r\n\r\n/**\r\n * Maps a contour in rubbersheet coordinates back to cartesian coordinates given the two cartesian boundaries\r\n * cartInner: CV_32FC2 1 x size inner cartesian boundary\r\n * cartOuter: CV_32FC2 1 x size outer cartesian boundary\r\n * cont: CV_32FC1 1 x size array of radius values from inner contour\r\n * cartCont: CV_32FC2 1 x size contour in cartesian coordinates\r\n * height: total height of the rubbersheet model\r\n *\r\n */\r\nvoid rubbersheet2Cart(const Mat& cartInner, const Mat& cartOuter, const Mat& cont, Mat& cartCont, const int height, const float pixeloffset = 0) {\r\n\r\n\tfloat * i = (float *)cartInner.data, * o = (float *)cartOuter.data, *c = (float *)cont.data, *dst = (float *)cartCont.data;\r\n\tfor (float *e = c + cont.cols;c != e; c++, i++, o++, dst++){\r\n\t\t*dst = *i + (*c + pixeloffset) * (*o - *i) / height;\r\n\t\ti++; o++; dst++;\r\n\t\t*dst = *i + (*c + pixeloffset) * (*o - *i) / height;\r\n\t}\r\n}\r\n\r\n/**\r\n * Resamples a closed contour from its new nucleus.\r\n * Hint: take care to divide dx and dy by polar resolution resY, if not equals to 1\r\n *\r\n * contOld: CV_32FC1 old polar contour, even spacing of 2 Pi (1,width,CV_32FC1), stretch-normalized (divide by resolution resY)\r\n * dx: center x-coordinate difference to old center (old_cx + dx = new_cx)\r\n * dy: center y-coordinate difference to old center (old_cy + dy = new_cy)\r\n * contourNew: CV_32FC1 new polar contour, even spacing of 2 Pi (1,width,CV_32FC1)\r\n */\r\nvoid resampleContour(const Mat& contOld, const float dx, const float dy, Mat& contNew){\r\n\tCV_Assert(contOld.type() == CV_32FC1);\r\n\tCV_Assert(contNew.type() == CV_32FC1);\r\n\tint width = contOld.cols;\r\n\tMat angles(1,width,CV_32FC1);\r\n\tMat points(1,width,CV_32FC2);\r\n\tMat angleIdx(1,width,CV_32SC1);\r\n\tfloat *p = (float *)contOld.data;\r\n\tfloat *q = (float *)angles.data;\r\n\tfloat *v = (float *)points.data;\r\n\tconst float thetaoffset = 2.f * M_PI / width;\r\n\tfloat theta = 0;\r\n\tfloat thetafactor = M_PI/180.f;\r\n\t// calculate angles with respect to new center\r\n\tfor (float *e = p+width; p != e; p++, q++, v+=2, theta += thetaoffset){\r\n\t\t*v = (*p) * cos(theta) - dx;\r\n\t\tv[1] = (*p) * sin(theta) - dy;\r\n\t\t*q = fastAtan2(v[1], *v) * thetafactor;\r\n\t}\r\n\t// angles are sorted\r\n\tsortIdx(angles,angleIdx,CV_SORT_EVERY_ROW + CV_SORT_ASCENDING);\r\n\tq = (float *)angles.data;\r\n\tv = (float *)points.data;\r\n\tint * idx = (int *) angleIdx.data;\r\n\ttheta = 0;\r\n\tfloat *dst = (float *)contNew.data;\r\n\tint j=0;\r\n\tfor (int i=0; i<width; i++, theta += thetaoffset){\r\n\t\tfor (; j<width && q[idx[j]] < theta; j++);\r\n\t\tint idxPrev, idxSucc; // interesting indices are j-1 und j (wrt. to ring buffer)\r\n\t\tbool desperate = false;\r\n\t\tif (j== width || j == 0){\r\n\t\t\t// jumping over 360 deg\r\n\t\t\tidxPrev = idx[width-1];\r\n\t\t\tidxSucc = idx[0];\r\n\t\t\t// (det(x1,y1,x2,y2) < 0) i.e. negative orientation: new origin is outside\r\n\t\t\tif (q[idxSucc] + M_PI - q[idxPrev] > 0) desperate = true;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tidxPrev = idx[j-1];\r\n\t\t\tidxSucc = idx[j];\r\n\t\t\tif (q[idxSucc] - q[idxPrev] > M_PI) desperate = true;\r\n\t\t}\r\n\t\t// build equation of line\r\n\t\t// y = k*x + m in polar coordinates: r(t) = m / (sin(t) + k*cos(t))\r\n\t\tfloat x1 = v[2*idxPrev], y1 = v[2*idxPrev+1], x2 = v[2*idxSucc], y2 = v[2*idxSucc+1];\r\n\t\tif (!desperate) {\r\n\t\t\t// Calculate intersection points\r\n\t\t\tif  (abs(x2-x1) < 0.00001){\r\n\t\t\t\tdst[i] = x1 / cos(theta);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tfloat k = (y2-y1)/(x2-x1);\r\n\t\t\t\tfloat m = ((y2-k*x2) + (y1-k*x1))/2;\r\n\t\t\t\tdst[i] = m / (sin(theta) - k * cos(theta));\r\n\t\t\t}\r\n\t\t}\r\n\t\telse { // force validity\r\n\t\t\tdst[i] = 0;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Computes the contour center\r\n * warning: multiply coordinates with y-resolution to get correct values!\r\n */\r\nvoid pullAndPush(const Mat& polarCont, Vec2f& offset){\r\n\tint width = polarCont.cols;\r\n\tMat cart(1,width,CV_32FC2);\r\n\tMat polar(1,width,CV_32FC1);\r\n\tpolarCont.convertTo(polar,CV_32FC1);\r\n\t//copy2f(polarCont,polar);\r\n\tfloat fx = 0, fy = 0, dx = 0, dy = 0;\r\n\tint iter = 0;\r\n\tdo {\r\n\t\tfx = 0; fy = 0;\r\n\t\tpolar2Cart(polar,cart,0,0,1,0);\r\n\t\tfor (MatIterator_<float> s = cart.begin<float>(), e = cart.end<float>(); s != e; s++){\r\n\t\t\tfx += (*s);\r\n\t\t\ts++;\r\n\t\t\tfy += (*s);\r\n\t\t}\r\n\t\tfx /= width;\r\n\t\tfy /= width;\r\n\t\tdx += fx;\r\n\t\tdy += fy;\r\n\t\tresampleContour(polarCont,dx,dy,polar);\r\n\t\titer++;\r\n\t}\r\n\twhile ((abs(fx) > 0.1 || abs(fy) > 0.1) && iter < 1000);\r\n\toffset[0] = dx;\r\n\toffset[1] = dy;\r\n}\r\n\r\n/*** Mask lids ****/\r\n\r\n\r\nvoid adjust_luminance(Mat& image, int black, int white)\r\n{\r\n    /*\r\n     * Adjust the luminance of the image in-place so that the result has at least\r\n     * black completely black and white completely white pixels (if possible). */\r\n\tMat hist(1,256,CV_32SC1);\r\n\thist2u(image,hist);\r\n\tint * histogram = (int*)hist.data;\r\n\tint blackpoint, whitepoint;\r\n    int i;\r\n    if (black)\r\n    {\r\n        int bn = 0;\r\n        for (i = 0; i < 256; i++)\r\n        {\r\n            bn += histogram[i];\r\n            if (bn >= black)\r\n            {\r\n                break;\r\n            }\r\n        }\r\n        blackpoint = i;\r\n    }\r\n    else\r\n    {\r\n        blackpoint = 0;\r\n    }\r\n    if (white)\r\n    {\r\n        int wn = 0;\r\n        for (i = 255; i >= 0; i--)\r\n        {\r\n            wn += histogram[i];\r\n            if (wn >= white)\r\n            {\r\n                break;\r\n            }\r\n        }\r\n        whitepoint = i;\r\n    }\r\n    else\r\n    {\r\n        whitepoint = 255;\r\n    }\r\n\tfor (MatIterator_<uchar> it = image.begin<uchar>(); it < image.end<uchar>(); it++){\r\n\t\tint c = *it;\r\n\t\tint c_ = c - blackpoint;\r\n\t\tc_ = c_ * 255 / (whitepoint - blackpoint);\r\n\t\tif (c_ < 0)\r\n\t\t{\r\n\t\t\tc_ = 0;\r\n\t\t}\r\n\t\tif (c_ > 255)\r\n\t\t{\r\n\t\t\tc_ = 255;\r\n\t\t}\r\n\t\t*it = c_;\r\n\t}\r\n}\r\n\r\n/*\r\n * Make light areas lighter\r\n */\r\nvoid cumulate(const Mat& image, Mat& result, int cw, int ch)\r\n{\r\n\tCV_Assert(image.size() == result.size());\r\n\r\n    int w = image.cols;\r\n    int h = image.rows;\r\n    int step = image.step;\r\n    uchar* data = image.data;\r\n    uchar* a = result.data;\r\n    int ox = cw / 2;\r\n    int oy = ch / 2;\r\n    for (int y = 0; y < h; y++)\r\n    {\r\n        int ay, by;\r\n        if (y < oy)\r\n        {\r\n            ay = oy - y;\r\n        }\r\n        else\r\n        {\r\n            ay = 0;\r\n        }\r\n        if (y + ch - oy > h)\r\n        {\r\n            by = h + oy - y;\r\n        }\r\n        else\r\n        {\r\n            by = ch;\r\n        }\r\n        for (int x = 0; x < w; x++)\r\n        {\r\n            int sum = 0;\r\n            int ax, bx;\r\n            if (x < ox)\r\n            {\r\n                ax = ox - x;\r\n            }\r\n            else\r\n            {\r\n                ax = 0;\r\n            }\r\n            if (x + cw - ox > w)\r\n            {\r\n                bx = w + ox - x;\r\n            }\r\n            else\r\n            {\r\n                bx = cw;\r\n            }\r\n            for (int j = ay; j < by; j++)\r\n            {\r\n                for (int i = ax; i < bx; i++)\r\n                {\r\n                    sum += data[(y + j - oy) * step + (x + i - ox)];\r\n                }\r\n            }\r\n            if (sum > 255)\r\n            {\r\n                sum = 255;\r\n            }\r\n            a[y * step + x] = sum;\r\n        }\r\n    }\r\n}\r\n\r\n/*\r\n * Looks for longest horizontal run\r\n */\r\nint longest_horizontal_run(const Mat& image, int border, int threshold)\r\n{\r\n    int w = image.cols;\r\n    int h = image.rows;\r\n    int step = image.step;\r\n    int maxrun = 0;\r\n    uchar * data = image.data;\r\n    for (int j = border; j < h - border; j++)\r\n    {\r\n        int run = 0;\r\n        for (int i = border; i < w - border; i++)\r\n        {\r\n            if (data[i + j * step] <= threshold)\r\n            {\r\n                run++;\r\n                if (run > maxrun)\r\n                {\r\n                    maxrun = run;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                run = 0;\r\n            }\r\n        }\r\n    }\r\n    return maxrun;\r\n}\r\n\r\n/*\r\n * Looks for longest vertical run\r\n */\r\nint longest_vertical_run(const Mat& image, int border, int threshold)\r\n{\r\n    int w = image.cols;\r\n    int h = image.rows;\r\n    int step = image.step;\r\n    int maxrun = 0;\r\n    uchar * data = image.data;\r\n    for (int i = border; i < w - border; i++)\r\n    {\r\n        int run = 0;\r\n        for (int j = border; j < h - border; j++)\r\n        {\r\n            if (data[i + j * step] <= threshold)\r\n            {\r\n                run++;\r\n                if (run > maxrun)\r\n                {\r\n                    maxrun = run;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                run = 0;\r\n            }\r\n        }\r\n    }\r\n    return maxrun;\r\n}\r\n\r\n\r\n\r\n/*\r\n * Returns the result of convoluting image with kernel.\r\n * The border is handled by treating all outside pixels as the nearest picture\r\n * pixel.\r\n */\r\nvoid convolution_brute(const Mat& image, Mat& res, const Mat& kernel)\r\n{\r\n    int w = image.cols;\r\n    int h = image.rows;\r\n    int step = image.step / sizeof (float);\r\n    int kw = kernel.cols;\r\n    int kh = kernel.rows;\r\n    int kstep = kernel.step / sizeof (float);\r\n    float *data = (float*)image.data;\r\n    float *kdata = (float*)kernel.data;\r\n    int ox = -kw / 2;\r\n    int oy = -kh / 2;\r\n    float *result = (float*)res.data;\r\n    int rstep = res.step / sizeof (float);\r\n    for (int y = oy; y < h + oy; y++)\r\n    {\r\n        for (int x = ox; x < w + ox; x++)\r\n        {\r\n            float sum = 0;\r\n            for (int j = 0; j < kh; j++)\r\n            {\r\n                int yj;\r\n                if (y + j >= 0 && y + j < h)\r\n                {\r\n                    yj = y + j;\r\n                }\r\n                else\r\n                {\r\n                    yj = y - oy;\r\n                }\r\n                for (int i = 0; i < kw; i++)\r\n                {\r\n                    int xi;\r\n                    if (x + i >= 0 && x + i < w)\r\n                    {\r\n                        xi = x + i;\r\n                    }\r\n                    else\r\n                    {\r\n                        xi = x - ox;\r\n                    }\r\n                    float v = data[step * yj + xi];\r\n                    float k = kdata[j * kstep + i];\r\n                    sum += v * k;\r\n                }\r\n            }\r\n            result[(y - oy) * rstep + x - ox] = sum;\r\n        }\r\n    }\r\n}\r\n\r\n/*\r\n * Returns a new image of size w times h with the result of a gaussian\r\n * smoothing operation.\r\n * TODO: Should do this in frequency domain, especially for big radius.\r\n */\r\nvoid gaussian_smooth(Mat& image, Mat& res, double sigma, int size)\r\n{\r\n    double sigma2 = sigma * sigma;\r\n    int kw = size;\r\n    int kh = size;\r\n    Mat kernel(kh,kw,CV_32FC1);\r\n    float *pos = (float *) kernel.data;\r\n    int off = (kernel.step / sizeof(float)) - kernel.cols;\r\n    int o = -size / 2;\r\n    for (int j = o; j < kh + o; j++, pos+=off)\r\n    {\r\n        for (int i = o; i < kw + o; i++, pos++)\r\n        /* This is 2D (for 1D, sqrt the factor) */\r\n        {\r\n            *pos = exp(-(i * i + j * j) / (2 * sigma2)) / (2 * M_PI * sigma2);\r\n        }\r\n    }\r\n    convolution_brute(image, res, kernel);\r\n}\r\n\r\n/*\r\n * Generates horizontal Sobel Kernel\r\n */\r\nvoid horizontal_sobel(Mat& image, Mat& res)\r\n{\r\n    float kdata[] = { -1, 0, 1, -2, 0, 2, -1, 0, 1 };\r\n    Mat kernel(3, 3, CV_32FC1, &kdata);\r\n    convolution_brute(image, res, kernel);\r\n}\r\n\r\n/*\r\n * Generates vertical Sobel Kernel\r\n */\r\nvoid vertical_sobel(Mat& image, Mat& res)\r\n{\r\n\tfloat kdata[] = { 1, 2, 1, 0, 0, 0, -1, -2, -1 };\r\n    Mat kernel(3, 3, CV_32FC1, &kdata);\r\n    convolution_brute(image, res, kernel);\r\n}\r\n\r\n/*\r\n * Use vertical and horizontal sobel operators to estimate the gradient, and\r\n * return it as  magnitude an orientation maps.\r\n */\r\nvoid get_gradient(Mat& image, Mat& mag, Mat& orient, float hfactor, float vfactor)\r\n{\r\n    int w = image.cols;\r\n    int h = image.rows;\r\n    Mat imsobelh(h,w,CV_32FC1);\r\n    Mat imsobelv(h,w,CV_32FC1);\r\n    int w_sobelh = imsobelh.step / sizeof(float);\r\n    int w_sobelv = imsobelv.step / sizeof(float);\r\n    int w_mag = mag.step / sizeof(float);\r\n    int w_orient = orient.step / sizeof(float);\r\n    horizontal_sobel(image,imsobelh);\r\n    vertical_sobel(image,imsobelv);\r\n\r\n    float* sobelh = (float*) imsobelh.data;\r\n    float* sobelv = (float*) imsobelv.data;\r\n    float* magnitude = (float*) mag.data;\r\n    float* orientation = (float*) orient.data;\r\n    for (int j = 0; j < h; j++)\r\n    {\r\n        for (int i = 0; i < w; i++)\r\n        {\r\n            float x = sobelh[i + w_sobelh * j];\r\n            float y = sobelv[i + w_sobelv * j];\r\n            float m = sqrt(x * x * hfactor + y * y * vfactor);\r\n            /* if m > 255: m = 255 */\r\n            m /= 4;\r\n            magnitude[i + w_mag * j] = m;\r\n            double a = atan2(y, x);\r\n            orientation[i + w_orient * j] = a;\r\n        }\r\n    }\r\n}\r\n\r\n/*\r\n * Returns gradient neighbors\r\n */\r\nstatic inline void get_gradient_neighbors(float o, int i, int j, int *i_, int *j_, int *i__, int *j__)\r\n{\r\n    if (o == 0)\r\n    {\r\n        *i_ = i + 1;\r\n        *i__ = i - 1;\r\n        *j_ = *j__ = j;\r\n    }\r\n    else if (o == 1)\r\n    {\r\n        *i_ = i + 1;\r\n        *i__ = i - 1;\r\n        *j_ = j - 1;\r\n        *j__ = j + 1;\r\n    }\r\n    else if (o == 2)\r\n    {\r\n        *i_ = *i__ = i;\r\n        *j_ = j - 1;\r\n        *j__ = j + 1;\r\n    }\r\n    else if (o == 3)\r\n    {\r\n        *i_ = i - 1;\r\n        *i__ = i + 1;\r\n        *j_ = j - 1;\r\n        *j__ = j + 1;\r\n    }\r\n    else\r\n    {\r\n        assert(0);\r\n    }\r\n}\r\n\r\n/*\r\n * Performs Border check\r\n */\r\nstatic inline void suppress_gradient_with_border_check(float* gradient, float* orientation, int i, int j, float* result, int gradstep, int orientstep, int resstep, int w, int h)\r\n{\r\n    float g = gradient[i + gradstep * j];\r\n    float o = orientation[i + orientstep * j];\r\n    int i_, j_, i__, j__;\r\n    get_gradient_neighbors(o, i, j, &i_, &j_, &i__, &j__);\r\n    float g1 = g, g2 = g;\r\n    if (i_ >= 0 && i_ < w && j_ >= 0 && j_ < h)\r\n    {\r\n        g1 = gradient[i_ + gradstep * j_];\r\n    }\r\n    if (i__ >= 0 && i__ < w && j__ >= 0 && j__ < h)\r\n    {\r\n        g2 = gradient[i__ + gradstep * j__];\r\n    }\r\n    if (g < g1 || g < g2)\r\n    {\r\n        result[i + resstep * j] = 0;\r\n    }\r\n    else\r\n    {\r\n        result[i + resstep * j] = g;\r\n    }\r\n}\r\n\r\n/*\r\n * For each pixel, if either the left or right neighbor is brighter, set it to\r\n * 0. That way, only thinned areas of maximum brightness are left. Because\r\n * left/right neighbors are used, this is biased to create vertical lines.\r\n */\r\nvoid non_maximum_suppression(Mat& gradient, Mat& orientation, Mat& res)\r\n{\r\n    int w = gradient.cols;\r\n    int h = gradient.rows;\r\n    float* result = (float*) res.data;\r\n    float * gdata = (float*) gradient.data;\r\n    float * odata = (float*) orientation.data;\r\n    int gstep = gradient.step/sizeof(float);\r\n    int ostep = orientation.step/sizeof(float);\r\n    int rstep = res.step/sizeof(float);\r\n\r\n    /* handle border pixels in a special way first */\r\n    for (int j = 0; j < h; j += h - 1)\r\n    {\r\n        for (int i = 0; i < w; i++)\r\n        {\r\n            suppress_gradient_with_border_check(gdata, odata, i, j, result,gstep,ostep,rstep,w,h);\r\n        }\r\n    }\r\n    for (int i = 0; i < w; i += w - 1)\r\n    {\r\n        for (int j = 1; j < h - 1; j++)\r\n        {\r\n            suppress_gradient_with_border_check(gdata, odata, i, j, result,gstep,ostep,rstep,w,h);\r\n            /* now remaining pixels, without check */\r\n        }\r\n    }\r\n    for (int j = 1; j < h - 1; j++)\r\n    {\r\n        for (int i = 1; i < w - 1; i++)\r\n        {\r\n            float g = gdata[i + gstep * j];\r\n            float o = odata[i + ostep * j];\r\n            int i_, j_, i__, j__;\r\n            get_gradient_neighbors(o, i, j, &i_, &j_, &i__, &j__);\r\n            float g1 = gdata[i_ + gstep * j_];\r\n            float g2 = gdata[i__ + gstep * j__];\r\n            if (g < g1 || g < g2)\r\n            {\r\n                result[i + rstep * j] = 0;\r\n            }\r\n            else\r\n            {\r\n                result[i + rstep * j] = g;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n/*\r\n * Quantize the orientations into 4 bins:\r\n * 0 right\r\n * 1 right up\r\n * 2 up\r\n * 3 left up\r\n * Those are all we need for pixel-edge-tracking  */\r\nvoid edge_directions(Mat& orientation, Mat& res)\r\n{\r\n    int w = orientation.cols;\r\n    int h = orientation.rows;\r\n    float *e = (float*)res.data;\r\n    float *o = (float*)orientation.data;\r\n    int estep = res.step / sizeof(float);\r\n    int ostep = orientation.step / sizeof(float);\r\n\r\n    for (int j = 0; j < h; j++)\r\n    {\r\n        for (int i = 0; i < w; i++)\r\n        {\r\n            float a = o[i + ostep * j];\r\n            float c;\r\n            /* not 2*pi, left/right both is horizontal */\r\n            if (a < 0)\r\n            {\r\n                a += M_PI;\r\n            }\r\n            if (a > M_PI * 0.875)\r\n            {\r\n                c = 0;\r\n            }\r\n            else if (a > M_PI * 0.625)\r\n            {\r\n                c = 3;\r\n            }\r\n            else if (a > M_PI * 0.375)\r\n            {\r\n                c = 2;\r\n            }\r\n            else if (a > M_PI * 0.125)\r\n            {\r\n                c = 1;\r\n            }\r\n            else\r\n            {\r\n                c = 0;\r\n            }\r\n            e[i + estep * j] = c;\r\n        }\r\n    }\r\n}\r\n\r\n/*\r\n * Returns a new image of size w times h with the result of a canny edge\r\n * detection. The implementation here uses the following algorithm:\r\n * - Apply gaussian smoothing to the image.\r\n * - Approximate gradient for each pixel (we use H and V Sobel here right now,\r\n *   should compare to e.g. differential gaussian instead)\r\n * - Localize edges.\r\n * - fix edges\r\n */\r\nvoid canny(Mat& raster, Mat& magnitude, Mat& orientation, Mat& res, double gauss_sigma, int gauss_size, double hfactor, double vfactor)\r\n{\r\n\tMat image(raster.rows,raster.cols,CV_32FC1);\r\n\traster.convertTo(image,CV_32FC1);\r\n\tMat smooth(raster.rows,raster.cols,CV_32FC1);\r\n    gaussian_smooth(image, smooth, gauss_sigma, gauss_size);\r\n    //Mat magnitude(raster.rows,raster.cols,CV_32FC1);\r\n    //Mat orientation(raster.rows,raster.cols,CV_32FC1);\r\n    get_gradient(smooth, magnitude, orientation, hfactor, vfactor);\r\n    Mat dirs(raster.rows,raster.cols,CV_32FC1);\r\n    edge_directions(orientation,dirs);\r\n    Mat thinned(raster.rows,raster.cols,CV_32FC1);\r\n    non_maximum_suppression(magnitude, dirs,thinned);\r\n    /* binarize(thinned, w, h, 10) */\r\n    thinned.convertTo(res,CV_8UC1);\r\n}\r\n\r\n/*\r\n * Follows a streak\r\n */\r\nint follow_streak(Mat& image, int x, int y, int *dirs, int *mark, int tag, int kill, int *ax, int *ay, int *bx, int *by)\r\n{\r\n\tvector<Point> stack;\r\n    int w = image.cols;\r\n    int h = image.rows;\r\n    uchar * data = image.data;\r\n    int dx[] = {+1, +1,  0, -1, -1, -1,  0, +1, +1};\r\n    int dy[] = { 0, -1, -1, -1,  0, +1, +1, +1,  0};\r\n    /*  */\r\n    /* xxxxx */\r\n    /* x...x */\r\n    /* x.x.x */\r\n    /* x...x */\r\n    /* xxxxx */\r\n    /*  */\r\n    unsigned int first = 0;\r\n    stack.push_back(Point(x,y));\r\n    if (kill)\r\n    {\r\n        data[x + w * y] = 0;\r\n    }\r\n    else\r\n    {\r\n        mark[x + w * y] = tag;\r\n    }\r\n    *ax = x;\r\n    *ay = y;\r\n    *bx = x;\r\n    *by = y;\r\n    while (first < stack.size())\r\n    {\r\n    \tPoint n = stack[first++];\r\n        for (int i = 0; i < 8; i++)\r\n        {\r\n            int nx = n.x + dx[i];\r\n            int ny = n.y + dy[i];\r\n            if (nx >= 0 && ny >= 0 && nx < w && ny < h)\r\n            {\r\n                int ok;\r\n                if (kill)\r\n                {\r\n                    ok = (mark[nx + w * ny] == tag);\r\n                }\r\n                else\r\n                {\r\n                    ok = (mark[nx + w * ny] == 0);\r\n                }\r\n                if (ok && data[nx + w * ny])\r\n                {\r\n                    if (kill)\r\n                    {\r\n                        data[nx + w * ny] = 0;\r\n                    }\r\n                    else\r\n                    {\r\n                        mark[nx + w * ny] = tag;\r\n                    }\r\n                    dirs[i]++;\r\n                    stack.push_back(Point(nx,ny));\r\n                    if (nx < *ax)\r\n                    {\r\n                        *ax = nx;\r\n                    }\r\n                    if (nx > *bx)\r\n                    {\r\n                        *bx = nx;\r\n                    }\r\n                    if (ny < *ay)\r\n                    {\r\n                        *ay = ny;\r\n                    }\r\n                    if (ny > *by)\r\n                    {\r\n                        *by = ny;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n    return stack.size();\r\n}\r\n\r\n/*\r\n * We trace some edges and remove them if they certainly aren't part of the\r\n * wanted feature, but could confuse the hough transform later.\r\n */\r\nvoid remove_streaks(Mat& image, int minpixels, int min_w_pixels, int min_h_pixels, int max_horizontal, int max_vertical, int max_slash, int max_backslash, int max_bound_w, int max_bound_h)\r\n{\r\n\tint w = image.cols;\r\n    int h = image.rows;\r\n    vector<int> mark(w*h);\r\n    uchar * data = image.data;\r\n    int tag = 1;\r\n    for (int j = 0; j < h; j++)\r\n    {\r\n        for (int i = 0; i < w; i++)\r\n        {\r\n            if (! mark[i + j * w] && data[i + j * w])\r\n            {\r\n                int dirs[8] = {0, 0, 0, 0, 0, 0, 0, 0};\r\n                int ax, ay, bx, by;\r\n                int size = follow_streak(image, i, j, dirs, &mark[0], tag, 0, &ax, &ay, &bx, &by);\r\n                int kill = 0;\r\n                /* Seems, using just the bounding box is enough (so we can get */\r\n                /* rid of all the dirs counting). And using the bounding box, */\r\n                /* instead of just the ratio, we could also already do the test for */\r\n                /* min/max radius. */\r\n                if (size >= minpixels && bx - ax >= min_w_pixels && by - ay >= min_h_pixels)\r\n                /* int ho = dirs[0] + dirs[4] */\r\n                /* int ve = dirs[2] + dirs[6] */\r\n                /* int d1 = dirs[1] + dirs[5] */\r\n                /* int d2 = dirs[3] + dirs[7] */\r\n                /* printf(\"%d/%d: %d %d %d %d\\n\", i, j, ho, ve, d1, d2) */\r\n                /* We don't want to remove the pupil here under no */\r\n                /* circumstances, even if it is degenerated to just a small */\r\n                /* arc - so must be quite conservative. */\r\n                /* if ho > ve * max_horizontal or ve > ho * max_vertical: */\r\n                /* d1 > d2 * max_slash or d2 > d1 * max_backslash or\\ */\r\n                {\r\n                    if ((bx - ax) > max_bound_w * (by - ay) || (by - ay) > max_bound_h * (bx - ax))\r\n                    {\r\n                        kill = 1;\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    kill = 1;\r\n                }\r\n                if (kill)\r\n                {\r\n                    follow_streak(image, i, j, dirs, &mark[0], tag, 1, &ax, &ay, &bx, &by);\r\n                }\r\n                tag++;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n/*\r\n * thresholds\r\n */\r\nint bounds_bigger_than_threshold(Mat& image, int threshold, int *x, int *y, int *x_, int *y_)\r\n{\r\n    int w = image.cols;\r\n    int step = image.step;\r\n    int h = image.rows;\r\n    uchar* data = image.data;\r\n    int n= 0;\r\n    *x = w - 1;\r\n    *y = h - 1;\r\n    *x_ = 0;\r\n    *y_ = 0;\r\n    for (int j = 0; j < h ; j++)\r\n    {\r\n        for (int i = 0; i < w; i++)\r\n        {\r\n            uchar c = data[j * step + i];\r\n            if (c > threshold)\r\n            {\r\n                if (i < *x)\r\n                {\r\n                    *x = i;\r\n                }\r\n                if (i > *x_)\r\n                {\r\n                    *x_ = i;\r\n                }\r\n                if (j < *y)\r\n                {\r\n                    *y = j;\r\n                }\r\n                if (j > *y_)\r\n                {\r\n                    *y_ = j;\r\n                }\r\n                n++;\r\n            }\r\n        }\r\n    }\r\n    return n;\r\n}\r\n\r\n\r\n/*\r\n * Blacks out pupil\r\n */\r\nvoid black_out_circle(Mat& image, int x, int y, int r1, int r2)\r\n{\r\n    int w = image.cols;\r\n    int step = image.step;\r\n    int h = image.rows;\r\n    uchar* data = image.data;\r\n    int sum = 0, n = 0;\r\n    for (int j = 0; j < h; j++)\r\n    {\r\n        for (int i = 0; i < w ; i++)\r\n        {\r\n            int dx = i - x;\r\n            int dy = j - y;\r\n            int d = sqrt(dx * dx + dy * dy);\r\n            if (d <= r2 && d >= r1)\r\n            {\r\n                int c = data[i + j * step];\r\n                sum += c;\r\n                n++;\r\n            }\r\n        }\r\n    }\r\n    sum /= n;\r\n    for (int j = 0; j < h; j++)\r\n    {\r\n        for (int i = 0; i < w ; i++)\r\n        {\r\n            int dx = i - x;\r\n            int dy = j - y;\r\n            int d = sqrt(dx * dx + dy * dy);\r\n            if (d <= r2)\r\n            {\r\n                int alpha = r2 * (d - r1) / (r2 - r1);\r\n                if (alpha < 0)\r\n                {\r\n                    alpha = 0;\r\n                }\r\n                int c = data[i + j * step];\r\n                data[i + j * step] = c * alpha / r2 + sum * (r2 - alpha) / r2;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n/*\r\n * horizon fade out\r\n */\r\nvoid dim_above_horizon(Mat& image, int y, float a)\r\n{\r\n    int w = image.cols;\r\n    int step = image.step;\r\n    uchar* data = image.data;\r\n    for (int j = 0; j < y; j++)\r\n    {\r\n        float val = (j - y) * (j - y) * a;\r\n        val = 255 - val;\r\n        if (val < 0)\r\n        {\r\n            val = 0;\r\n        }\r\n        for (int i = 0; i < w ; i++)\r\n        {\r\n            int c = data[i + j * step];\r\n            data[i + j * step] = c * val / 255;\r\n        }\r\n    }\r\n}\r\n\r\n/*\r\n * Any pixels at or below the threshold are set to the given value.\r\n */\r\nvoid threshold_below(Mat& image, int threshold, int value)\r\n{\r\n    int w = image.cols;\r\n    int step = image.step;\r\n    int h = image.rows;\r\n    uchar* data = image.data;\r\n    for (int j = 0; j < h; j++)\r\n    {\r\n        for (int i = 0; i < w; i++)\r\n        {\r\n            int c = data[i + j * step];\r\n            if (c <= threshold)\r\n            {\r\n                data[i + j * step] = value;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n/*\r\n * Any pixels ar or above the given threshold are set to the given value.\r\n */\r\nvoid threshold_above(Mat& image, int threshold, int value)\r\n{\r\n    int w = image.cols;\r\n    int step = image.step;\r\n    int h = image.rows;\r\n    uchar* data = image.data;\r\n    for (int j = 0; j < h; j++)\r\n    {\r\n        for (int i = 0; i < w; i++)\r\n        {\r\n            int c = data[i + j * step];\r\n            if (c >= threshold)\r\n            {\r\n                data[i + j * step] = value;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n/** ------------------------------- Iris mask ------------------------------- **/\r\n\r\n/*\r\n * Starting at the given location, created a mask from edges.\r\n */\r\nvoid scan_edge(Mat& image, int x, int y, int dx, int dy, int n)\r\n{\r\n\tint step = image.step;\r\n    uchar * data = image.data;\r\n    int tox = (dx > 0) ? min(x+n,image.cols) : max(x-n,-1);\r\n    int toy = (dy > 0) ? image.rows: -1;\r\n    //printf(\"x from %i to %i inc %i, y from %i to %i inc %i\\n\",x,tox,dx,y,toy,dy);\r\n    double avg = 0;\r\n    int count = 0;\r\n    for (int i=x; i != tox; i+=dx)\r\n    {\r\n    \tbool mask = false;\r\n    \tint j=y;\r\n    \tfor (; j != toy; j+= dy){\r\n    \t\tif (mask) {\r\n    \t\t\tdata[i + j * step] = 255;\r\n    \t\t}\r\n    \t\telse {\r\n    \t\t     int c = data[i + j * step];\r\n    \t\t     if (c > 0) {\r\n    \t\t    \t mask = true;\r\n    \t\t    \t avg += j;\r\n    \t\t    \t count++;\r\n    \t\t     }\r\n    \t\t}\r\n    \t}\r\n    }\r\n    if (count > 0){\r\n    \tint y = avg / count;\r\n\t\tfor (int i=x; i != tox; i+=dx)\r\n\t\t{\r\n\t\t\tint j=y;\r\n\t\t\tfor (; j != toy; j+= dy){\r\n\t\t\t\tdata[i + j * step] = 255;\r\n\t\t\t}\r\n\t\t}\r\n    }\r\n}\r\n\r\n/*\r\n * px, py, pr: Pupil position and radius\r\n * ix, iy, ir: Iris position and radius\r\n *\r\n * This creates a black&white image, where black pixels are considered iris\r\n * texture and all other pixels are considered belonging to lids.\r\n *\r\n * Right now, this is a somewhat over-zealous algorithm, often cutting away\r\n * more than needed, especially in the presence of eyelashes.\r\n */\r\nvoid mask_lids(const Mat& orig_image, Mat& mask, int px, int py, int pr, int ix, int iy, int ir)\r\n{\r\n\r\n    int oxl = ix - ir;\r\n    int oyl = iy - ir;\r\n    int oxr = ix+ir;\r\n    int oyr = iy+ir;\r\n    int xl = min(max(0,oxl),orig_image.cols-1);\r\n    int yl = min(max(0,oyl),orig_image.rows-1);\r\n    int xr = min(max(0,oxr),orig_image.cols-1);\r\n    int yr = min(max(0,oyr),orig_image.rows-1);\r\n    Mat image(orig_image,Rect(xl,yl,xr-xl,yr-yl));\r\n    Mat img(yr-yl,xr-xl,CV_8UC1);\r\n    image.copyTo(img);\r\n    Mat mag(yr-yl,xr-xl,CV_32FC1);\r\n    Mat orient(yr-yl,xr-xl,CV_32FC1);\r\n    Mat edges(yr-yl,xr-xl,CV_8UC1);\r\n    int min_r = pr * 1.5;\r\n    /* Blackout the pupil */\r\n    black_out_circle(img, px-xl, py-yl, pr, min_r);\r\n    canny(img,mag,orient,edges, 3, 15, 0, 1);\r\n    threshold_below(edges, 6, 0);\r\n    threshold_above(edges, 7, 255);\r\n    remove_streaks(edges, 30, 30, 0, 1, 1, 1, 1, 100, 1);\r\n    scan_edge(edges, 0, iy-yl, 1, -1, ir);\r\n    scan_edge(edges, edges.cols - 1, iy-yl, -1, -1, ir);\r\n    scan_edge(edges, 0, iy-yl, 1, 1, ir);\r\n    scan_edge(edges, edges.cols - 1, iy-yl, -1, 1, ir);\r\n    mask.setTo(255);\r\n    Mat maskcrop(mask,Rect(xl,yl,xr-xl,yr-yl));\r\n    edges.copyTo(maskcrop);\r\n}\r\n\r\n\r\n/** ------------------------------- commandline functions ------------------------------- **/\r\n\r\n/**\r\n * Parses a command line\r\n * This routine should be called for parsing command lines for executables.\r\n * Note, that all options require '-' as prefix and may contain an arbitrary\r\n * number of optional arguments.\r\n *\r\n * cmd: commandline representation\r\n * argc: number of parameters\r\n * argv: string array of argument values\r\n */\r\nvoid cmdRead(map<string ,vector<string> >& cmd, int argc, char *argv[]){\r\n\tfor (int i=1; i< argc; i++){\r\n\t\tchar * argument = argv[i];\r\n\t\tif (strlen(argument) > 1 && argument[0] == '-' && (argument[1] < '0' || argument[1] > '9')){\r\n\t\t\tcmd[argument]; // insert\r\n\t\t\tchar * argument2;\r\n\t\t\twhile (i + 1 < argc && (strlen(argument2 = argv[i+1]) <= 1 || argument2[0] != '-'  || (argument2[1] >= '0' && argument2[1] <= '9'))){\r\n\t\t\t\tcmd[argument].push_back(argument2);\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tCV_Error(CV_StsBadArg,\"Invalid command line format\");\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Checks, if each command line option is valid, i.e. exists in the options array\r\n *\r\n * cmd: commandline representation\r\n * validOptions: list of valid options separated by pipe (i.e. |) character\r\n */\r\nvoid cmdCheckOpts(map<string ,vector<string> >& cmd, const string validOptions){\r\n\tvector<string> tokens;\r\n\tconst string delimiters = \"|\";\r\n\tstring::size_type lastPos = validOptions.find_first_not_of(delimiters,0); // skip delimiters at beginning\r\n\tstring::size_type pos = validOptions.find_first_of(delimiters, lastPos); // find first non-delimiter\r\n\twhile (string::npos != pos || string::npos != lastPos){\r\n\t\ttokens.push_back(validOptions.substr(lastPos,pos - lastPos)); // add found token to vector\r\n\t\tlastPos = validOptions.find_first_not_of(delimiters,pos); // skip delimiters\r\n\t\tpos = validOptions.find_first_of(delimiters,lastPos); // find next non-delimiter\r\n\t}\r\n\tsort(tokens.begin(), tokens.end());\r\n\tfor (map<string, vector<string> >::iterator it = cmd.begin(); it != cmd.end(); it++){\r\n\t\tif (!binary_search(tokens.begin(),tokens.end(),it->first)){\r\n\t\t\tCV_Error(CV_StsBadArg,\"Command line parameter '\" + it->first + \"' not allowed.\");\r\n\t\t\ttokens.clear();\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\ttokens.clear();\r\n}\r\n\r\n/*\r\n * Checks, if a specific required option exists in the command line\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n */\r\nvoid cmdCheckOptExists(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it == cmd.end()) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' is required, but does not exist.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * size: appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptSize(map<string ,vector<string> >& cmd, const string option, const unsigned int size = 1){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it->second.size() != size) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' has unexpected size.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * min: minimum appropriate number of parameters for the option\r\n * max: maximum appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptRange(map<string ,vector<string> >& cmd, string option, unsigned int min = 0, unsigned int max = 1){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tunsigned int size = it->second.size();\r\n\tif (size < min || size > max) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' is out of range.\");\r\n}\r\n\r\n/*\r\n * Returns the list of parameters for a given option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nvector<string> * cmdGetOpt(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\treturn (it != cmd.end()) ? &(it->second) : 0;\r\n}\r\n\r\n/*\r\n * Returns number of parameters in an option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nunsigned int cmdSizePars(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\treturn (it != cmd.end()) ? it->second.size() : 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (int) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nint cmdGetParInt(map<string ,vector<string> >& cmd, string option, unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn atoi(it->second[param].c_str());\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (float) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nfloat cmdGetParFloat(map<string ,vector<string> >& cmd, const string option, const unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn atof(it->second[param].c_str());\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (string) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nstring cmdGetPar(map<string ,vector<string> >& cmd, const string option, const unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn it->second[param];\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/** ------------------------------- timing functions ------------------------------- **/\r\n\r\n/**\r\n * Class for handling timing progress information\r\n */\r\nclass Timing{\r\npublic:\r\n\t/** integer indicating progress with respect tot total **/\r\n\tint progress;\r\n\t/** total count for progress **/\r\n\tint total;\r\n\r\n\t/*\r\n\t * Default constructor for timing initializing time.\r\n\t * Automatically calls init()\r\n\t *\r\n\t * seconds: update interval in seconds\r\n\t * eraseMode: if true, outputs sends erase characters at each print command\r\n\t */\r\n\tTiming(long seconds, bool eraseMode){\r\n\t\tupdateInterval = seconds;\r\n\t\tprogress = 1;\r\n\t\ttotal = 100;\r\n\t\teraseCount=0;\r\n\t\terase = eraseMode;\r\n\t\tinit();\r\n\t}\r\n\r\n\t/*\r\n\t * Destructor\r\n\t */\r\n\t~Timing(){}\r\n\r\n\t/*\r\n\t * Initializes timing variables\r\n\t */\r\n\tvoid init(void){\r\n\t\tstart = boost::posix_time::microsec_clock::universal_time();\r\n\t\tlastPrint = start - boost::posix_time::seconds(updateInterval);\r\n\t}\r\n\r\n\t/*\r\n\t * Clears printing (for erase option only)\r\n\t */\r\n\tvoid clear(void){\r\n\t\tstring erase(eraseCount,'\\r');\r\n\t\terase.append(eraseCount,' ');\r\n\t\terase.append(eraseCount,'\\r');\r\n\t\tprintf(\"%s\",erase.c_str());\r\n\t\teraseCount = 0;\r\n\t}\r\n\r\n\t/*\r\n\t * Updates current time and returns true, if output should be printed\r\n\t */\r\n\tbool update(void){\r\n\t\tcurrent = boost::posix_time::microsec_clock::universal_time();\r\n\t\treturn ((current - lastPrint > boost::posix_time::seconds(updateInterval)) || (progress == total));\r\n\t}\r\n\r\n\t/*\r\n\t * Prints timing object to STDOUT\r\n\t */\r\n\tvoid print(void){\r\n\t\tlastPrint = current;\r\n\t\tfloat percent = 100.f * progress / total;\r\n\t\tboost::posix_time::time_duration passed = (current - start);\r\n\t\tboost::posix_time::time_duration togo = passed * (total - progress) / max(1,progress);\r\n\t\tif (erase) {\r\n\t\t\tstring erase(eraseCount,'\\r');\r\n\t\t\tprintf(\"%s\",erase.c_str());\r\n\t\t\tint newEraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000),togo.hours(),togo.minutes(),togo.seconds(),(int)(togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000));\r\n\t\t\tif (newEraseCount < eraseCount) {\r\n\t\t\t\tstring erase(newEraseCount-eraseCount,' ');\r\n\t\t\t\terase.append(newEraseCount-eraseCount,'\\r');\r\n\t\t\t\tprintf(\"%s\",erase.c_str());\r\n\t\t\t}\r\n\t\t\teraseCount = newEraseCount;\r\n\t\t}\r\n\t\telse {\r\n\t\t\teraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\\n\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000),togo.hours(),togo.minutes(),togo.seconds(),(int)(togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\\n\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000));\r\n\t\t}\r\n\t}\r\nprivate:\r\n\tlong updateInterval;\r\n\tboost::posix_time::ptime start;\r\n\tboost::posix_time::ptime current;\r\n\tboost::posix_time::ptime lastPrint;\r\n\tint eraseCount;\r\n\tbool erase;\r\n};\r\n\r\n/** ------------------------------- file pattern matching functions ------------------------------- **/\r\n\r\n\r\n/*\r\n * Formats a given string, such that it can be used as a regular expression\r\n * I.e. escapes special characters and uses * and ? as wildcards\r\n *\r\n * pattern: regular expression path pattern\r\n * pos: substring starting index\r\n * n: substring size\r\n *\r\n * returning: escaped substring\r\n */\r\nstring patternSubstrRegex(string& pattern, size_t pos, size_t n){\r\n\tstring result;\r\n\tfor (size_t i=pos, e=pos+n; i < e; i++ ) {\r\n\t\tchar c = pattern[i];\r\n\t\tif ( c == '\\\\' || c == '.' || c == '+' || c == '[' || c == '{' || c == '|' || c == '(' || c == ')' || c == '^' || c == '$' || c == '}' || c == ']') {\r\n\t\t\tresult.append(1,'\\\\');\r\n\t\t\tresult.append(1,c);\r\n\t\t}\r\n\t\telse if (c == '*'){\r\n\t\t\tresult.append(\"([^/\\\\\\\\]*)\");\r\n\t\t}\r\n\t\telse if (c == '?'){\r\n\t\t\tresult.append(\"([^/\\\\\\\\])\");\r\n\t\t}\r\n\t\telse {\r\n\t\t\tresult.append(1,c);\r\n\t\t}\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/*\r\n * Converts a regular expression path pattern into a list of files matching with this pattern by replacing wildcards\r\n * starting in position pos assuming that all prior wildcards have been resolved yielding intermediate directory path.\r\n * I.e. this function appends the files in the specified path according to yet unresolved pattern by recursive calling.\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n * pos: an index such that positions 0...pos-1 of pattern are already considered/matched yielding path\r\n * path: the current directory (or empty)\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files, const size_t& pos, const string& path){\r\n\tsize_t first_unknown = pattern.find_first_of(\"*?\",pos); // find unknown * in pattern\r\n\tif (first_unknown != string::npos){\r\n\t\tsize_t last_dirpath = pattern.find_last_of(\"/\\\\\",first_unknown);\r\n\t\tsize_t next_dirpath = pattern.find_first_of(\"/\\\\\",first_unknown);\r\n\t\tif (next_dirpath != string::npos){\r\n\t\t\tboost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern,last_dirpath+1,next_dirpath-last_dirpath-1) : patternSubstrRegex(pattern,pos,next_dirpath-pos));\r\n\t\t\tboost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n\t\t\ttry {\r\n\t\t\t\tfor ( boost::filesystem::directory_iterator itr( ((path.length() > 0) ? path + pattern[pos-1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) : \"\")); itr != end_itr; ++itr )\r\n\t\t\t\t{\r\n\t\t\t\t\tif (boost::filesystem::is_directory(itr->path())){\r\n\t\t\t\t\t\tboost::filesystem::path p = itr->path().filename();\r\n\t\t\t\t\t\tstring s =  p.string();\r\n\t\t\t\t\t\tif (boost::regex_match(s.c_str(), expr)){\r\n\t\t\t\t\t\t\tpatternToFiles(pattern,files,(int)(next_dirpath+1),((path.length() > 0) ? path + pattern[pos-1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) + pattern[last_dirpath] : \"\") + s);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch (boost::filesystem::filesystem_error &e){}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tboost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern,last_dirpath+1,pattern.length()-last_dirpath-1) : patternSubstrRegex(pattern,pos,pattern.length()-pos));\r\n\t\t\tboost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n\t\t\ttry {\r\n\t\t\t\tfor ( boost::filesystem::directory_iterator itr(((path.length() > 0) ? path +  pattern[pos-1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) : \"\")); itr != end_itr; ++itr )\r\n\t\t\t\t{\r\n\t\t\t\t\tboost::filesystem::path p = itr->path().filename();\r\n\t\t\t\t\tstring s =  p.string();\r\n\t\t\t\t\tif (boost::regex_match(s.c_str(), expr)){\r\n\t\t\t\t\t\tfiles.push_back(((path.length() > 0) ? path + pattern[pos-1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) + pattern[last_dirpath] : \"\") + s);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch (boost::filesystem::filesystem_error &e){}\r\n\t\t}\r\n\t}\r\n\telse { // no unknown symbols\r\n\t\tboost::filesystem::path file(((path.length() > 0) ? path + \"/\" : \"\") + pattern.substr(pos,pattern.length()-pos));\r\n\t\tif (boost::filesystem::exists(file)){\r\n\t\t\tfiles.push_back(file.string());\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Converts a regular expression path pattern into a list of files matching with this pattern\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files){\r\n\tpatternToFiles(pattern,files,0,\"\");\r\n}\r\n\r\n/*\r\n * Renames a given filename corresponding to the actual file pattern using a renaming pattern.\r\n * Wildcards can be referred to as ?1, ?2, ... in the order they appeared in the file pattern.\r\n *\r\n * pattern: regular expression path pattern\r\n * renamePattern: renaming pattern using ?1, ?2, ... as placeholders for wildcards\r\n * infile: path of the file (matching with pattern) to be renamed\r\n * outfile: path of the renamed file\r\n * par: used parameter (default: '?')\r\n */\r\nvoid patternFileRename(string& pattern, const string& renamePattern, const string& infile, string& outfile, const char par = '?'){\r\n\tsize_t first_unknown = renamePattern.find_first_of(par,0); // find unknown ? in renamePattern\r\n\tif (first_unknown != string::npos){\r\n\t\tstring formatOut = \"\";\r\n\t\tfor (size_t i=0, e=renamePattern.length(); i < e; i++ ) {\r\n\t\t\tchar c = renamePattern[i];\r\n\t\t\tif ( c == par && i+1 < e) {\r\n\t\t\t\tc = renamePattern[i+1];\r\n\t\t\t\tif (c > '0' && c <= '9'){\r\n\t\t\t\t\tformatOut.append(1,'$');\r\n\t\t\t\t\tformatOut.append(1,c);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tformatOut.append(1,par);\r\n\t\t\t\t\tformatOut.append(1,c);\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tformatOut.append(1,c);\r\n\t\t\t}\r\n\t\t}\r\n\t\tboost::regex patternOut(patternSubstrRegex(pattern,0,pattern.length()));\r\n\t\toutfile = boost::regex_replace(infile,patternOut,formatOut,boost::match_default | boost::format_perl);\r\n\t} else {\r\n\t\toutfile = renamePattern;\r\n\t}\r\n}\r\n\r\n/** ------------------------------- Program ------------------------------- **/\r\n\r\n/*\r\n * Main program\r\n */\r\nint main(int argc, char *argv[])\r\n{\r\n\tint mode = MODE_HELP;\r\n\tmap<string,vector<string> > cmd;\r\n\ttry {\r\n\t\tcmdRead(cmd,argc,argv);\r\n    \tif (cmd.size() == 0 || cmdGetOpt(cmd,\"-h\") != 0) mode = MODE_HELP;\r\n    \telse mode = MODE_MAIN;\r\n    \tif (mode == MODE_MAIN){\r\n\t\t\t// validate command line\r\n\t\t\tcmdCheckOpts(cmd,\"-i|-o|-s|-e|-q|-t|-m|-rm|-rr|-em|-gr|-ic|-po|-fb|-ep|-ib|-ob|-sr|-bm|-lt|-so|-si|-tr|-l\");\r\n\t\t\tcmdCheckOptExists(cmd,\"-i\");\r\n\t\t\tcmdCheckOptSize(cmd,\"-i\",1);\r\n\t\t\tstring inFiles = cmdGetPar(cmd,\"-i\");\r\n\t\t\tcmdCheckOptExists(cmd,\"-o\");\r\n\t\t\tcmdCheckOptSize(cmd,\"-o\",1);\r\n\t\t\tstring outFiles = cmdGetPar(cmd,\"-o\");\r\n\t\t\tint outWidth = 512, outHeight = 64;\r\n\t\t\tif (cmdGetOpt(cmd,\"-s\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-s\",2);\r\n\t\t\t\toutWidth = cmdGetParInt(cmd,\"-s\",0);\r\n\t\t\t\toutHeight = cmdGetParInt(cmd,\"-s\",1);\r\n\t\t\t}\r\n\t\t\tbool enhance = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-e\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-e\",0);\r\n\t\t\t\tenhance = true;\r\n\t\t\t}\r\n\t\t\tbool quiet = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-q\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-q\",0);\r\n\t\t\t\tquiet = true;\r\n\t\t\t}\r\n\t\t\tbool time = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-t\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-t\",0);\r\n\t\t\t\ttime = true;\r\n\t\t\t}\r\n\t\t\tstring maskFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-m\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-m\",1);\r\n\t\t\t\tmaskFiles = cmdGetPar(cmd,\"-m\");\r\n\t\t\t}\r\n\t\t\tstring rmaskFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-rm\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-rm\",1);\r\n\t\t\t\trmaskFiles = cmdGetPar(cmd,\"-rm\");\r\n\t\t\t}\r\n\t\t\tstring rremovFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-rr\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-rr\",1);\r\n\t\t\t\trremovFiles = cmdGetPar(cmd,\"-rr\");\r\n\t\t\t}\r\n\t\t\tstring emaskFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-em\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-em\",1);\r\n\t\t\t\temaskFiles = cmdGetPar(cmd,\"-em\");\r\n\t\t\t}\r\n\t\t\tstring gradFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-gr\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-gr\",1);\r\n\t\t\t\tgradFiles = cmdGetPar(cmd,\"-gr\");\r\n\t\t\t}\r\n\t\t\tstring icentFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-ic\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-ic\",1);\r\n\t\t\t\ticentFiles = cmdGetPar(cmd,\"-ic\");\r\n\t\t\t}\r\n\t\t\tstring polarFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-po\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-po\",1);\r\n\t\t\t\tpolarFiles = cmdGetPar(cmd,\"-po\");\r\n\t\t\t}\r\n\t\t\tstring fboundFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-fb\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-fb\",1);\r\n\t\t\t\tfboundFiles = cmdGetPar(cmd,\"-fb\");\r\n\t\t\t}\r\n\t\t\tstring ellpolFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-ep\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-ep\",1);\r\n\t\t\t\tellpolFiles = cmdGetPar(cmd,\"-ep\");\r\n\t\t\t}\r\n\t\t\tstring iboundFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-ib\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-ib\",1);\r\n\t\t\t\tiboundFiles = cmdGetPar(cmd,\"-ib\");\r\n\t\t\t}\r\n\t\t\tstring oboundFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-ob\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-ob\",1);\r\n\t\t\t\toboundFiles = cmdGetPar(cmd,\"-ob\");\r\n\t\t\t}\r\n\t\t\tstring segresFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-sr\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-sr\",1);\r\n\t\t\t\tsegresFiles = cmdGetPar(cmd,\"-sr\");\r\n\t\t\t}\r\n\t\t\tstring binmaskFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-bm\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-bm\",1);\r\n\t\t\t\tbinmaskFiles = cmdGetPar(cmd,\"-bm\");\r\n\t\t\t}\r\n\t\t\tint lt = 1;\r\n\t\t\tif (cmdGetOpt(cmd,\"-lt\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-lt\",1);\r\n\t\t\t\tlt = cmdGetParInt(cmd,\"-lt\");\r\n\t\t\t}\r\n            float outer_scale = 1;\r\n            if (cmdGetOpt(cmd,\"-so\") != 0){\r\n                cmdCheckOptSize(cmd, \"-so\", 1);\r\n                outer_scale = cmdGetParFloat(cmd, \"-so\", 0);\r\n                if ( outer_scale <=0){\r\n                    cerr << \"outer_scale factor (-so) <=0, this will result in an error\" << endl;\r\n                }\r\n                outer_scale = sqrt(outer_scale);\r\n            }\r\n            float inner_scale = 1;\r\n            if (cmdGetOpt(cmd,\"-si\") != 0){\r\n                cmdCheckOptSize(cmd, \"-si\", 1);\r\n                inner_scale = cmdGetParFloat(cmd, \"-si\", 0);\r\n                if ( inner_scale <=0){\r\n                    cerr << \"inner_scale factor (-si) <=0, this will result in an error\" << endl;\r\n                }\r\n                inner_scale = sqrt(inner_scale);\r\n            }\r\n            float translate = 0.;\r\n            if (cmdGetOpt(cmd,\"-tr\") != 0){\r\n                cmdCheckOptSize(cmd, \"-tr\", 1);\r\n                translate = cmdGetParFloat(cmd, \"-tr\", 0);\r\n            }\r\n\t\t\tofstream logFile;\r\n\t\t\tif (cmdGetOpt(cmd,\"-l\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-l\",1);\r\n                string logFileName = cmdGetPar(cmd,\"-l\");\r\n\t\t\t\tlogFile.open(logFileName.c_str()); \r\n                if( !logFile) cerr << \"Failed to open logfile (\"<<logFileName<<\") for writing\"<<endl;\r\n\t\t\t}\r\n            if( logFile.is_open()){ \r\n                    logFile << \"# Filename\" << \", \" \r\n                            << \"inner.x\" << \", \" \r\n                            << \"inner.y\" << \", \" \r\n                            << \"inner.width\" << \", \" \r\n                            << \"inner.height\" << \", \" \r\n                            << \"inner.angle\" << \", \" \r\n                            << \"outer.x\" << \", \"\r\n                            << \"outer.y\" << \", \"\r\n                            << \"outer.width\" << \", \"\r\n                            << \"outer.height\" << \", \"\r\n                            << \"outer.angle\" << endl;\r\n            }\r\n\t\t\t// starting routine\r\n\t\t\tTiming timing(1,quiet);\r\n\t\t\tvector<string> files;\r\n\t\t\tpatternToFiles(inFiles,files);\r\n\t\t\tCV_Assert(files.size() > 0);\r\n\t\t\ttiming.total = files.size();\r\n\t\t\tfor (vector<string>::iterator inFile = files.begin(); inFile != files.end(); ++inFile, timing.progress++){\r\n\t\t\t\tif (!quiet) printf(\"Loading image '%s' ...\\n\", (*inFile).c_str());;\r\n\t\t\t\t// MODIFICATION TB, June 3rd, 2014\r\n\t\t\t\t// additional conversion step to enable direct JP2K processing (Bug in CV)\r\n\t\t\t\t// Loading of JP2k in color is supported, loading as grayscale, however, not\r\n\t\t\t\tMat imgCol = imread(*inFile, CV_LOAD_IMAGE_COLOR);\t\t\t\r\n\t\t\t\tMat img;\t\t\t\r\n\t\t\t\tcvtColor(imgCol,img,CV_BGR2GRAY);\r\n\t\t\t\tCV_Assert(img.data != 0);\r\n\t\t\t\tMat orig;\r\n\t\t\t\tif (!segresFiles.empty()) img.copyTo(orig);\r\n\t\t\t\tint width = img.cols;\r\n\t\t\t\tint height = img.rows;\r\n\t\t\t\tint cx1 = 0, cy1 = 0, cr1 = 0;\r\n\t\t\t\tint cx2 = 0, cy2 = 0, cr2 = 0;\r\n\t\t\t\tint cx3 = 0, cy3 = 0, cr3 = 0;\r\n\t\t\t\tif (!quiet) printf(\"Removing reflections ...\\n\");\r\n\t\t\t\tMat mask(height,width,CV_8UC1);\r\n\t\t\t\tcreateReflectionMask(img, mask);\r\n\t\t\t\tif (!rmaskFiles.empty()){\r\n\t\t\t\t\tstring rmaskFile;\r\n\t\t\t\t\tpatternFileRename(inFiles,rmaskFiles,*inFile,rmaskFile);\r\n\t\t\t\t\tif (!quiet) printf(\"Storing reflection mask '%s' ...\\n\",rmaskFile.c_str());\r\n\t\t\t\t\tif (!imwrite(rmaskFile,mask)) CV_Error(CV_StsError,\"Could not save image '\" + rmaskFile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tinpaint(img,mask,img,10,INPAINT_NS);\r\n\t\t\t\tif (!rremovFiles.empty()){\r\n\t\t\t\t\tstring nonreflectFile;\r\n\t\t\t\t\tpatternFileRename(inFiles,rremovFiles,*inFile,nonreflectFile);\r\n\t\t\t\t\tif (!quiet) printf(\"Storing reflection-removed image '%s' ...\\n\",nonreflectFile.c_str());\r\n\t\t\t\t\tif (!imwrite(nonreflectFile,img)) CV_Error(CV_StsError,\"Could not save image '\" + nonreflectFile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tif (!quiet) printf(\"Estimating gradient information ...\\n\");\r\n\t\t\t\tMat gradX(height,width,CV_32FC1);\r\n\t\t\t\tMat gradY(height,width,CV_32FC1);\r\n\t\t\t\tMat mag(height,width,CV_32FC1);\r\n\t\t\t\tSobel(img,gradX,gradX.depth(),1,0,7);\r\n\t\t\t\tSobel(img,gradY,gradY.depth(),0,1,7);\r\n\t\t\t\tmaskValue(gradX,gradX,mask,255,0);\r\n\t\t\t\tmaskValue(gradY,gradY,mask,255,0);\r\n\t\t\t\tmagnitude(gradX,gradY,mag);\r\n\t\t\t\tif (!gradFiles.empty()){\r\n\t\t\t\t\tMat visual;\r\n\t\t\t\t\tMat gradPhase(height,width,CV_32FC1);\r\n\t\t\t\t\tphase(gradX,gradY,gradPhase,true);\r\n\t\t\t\t\tvector<Mat> planes(3);\r\n\t\t\t\t\tfor (int i=0; i<3; i++) planes[i].create(height,width,CV_8UC1);\r\n\t\t\t\t\tplanes[1].setTo(255);\r\n\t\t\t\t\tdouble minVal, maxVal;\r\n\t\t\t\t\tminMaxLoc(mag,&minVal,&maxVal);\r\n\t\t\t\t\tmag.convertTo(planes[2],CV_8UC1,255.f/maxVal);\r\n\t\t\t\t\tgradPhase.convertTo(planes[0],CV_8UC1,0.5f);\r\n\t\t\t\t\tmerge(planes,visual);\r\n\t\t\t\t\tcvtColor(visual,visual,CV_HSV2BGR);\r\n\t\t\t\t\tstring gradFile;\r\n\t\t\t\t\tpatternFileRename(inFiles,gradFiles,*inFile,gradFile);\r\n\t\t\t\t\tif (!quiet) printf(\"Storing gradient image '%s' ...\\n\",gradFile.c_str());\r\n\t\t\t\t\tif (!imwrite(gradFile,visual)) CV_Error(CV_StsError,\"Could not save image '\" + gradFile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tMat boundaryEdges(height,width,CV_8UC1);\r\n\t\t\t\tcreateBoundaryMask(img,boundaryEdges,gradX,gradY,mag);\r\n\t\t\t\tif (!emaskFiles.empty()){\r\n\t\t\t\t\tstring emaskFile;\r\n\t\t\t\t\tpatternFileRename(inFiles,emaskFiles,*inFile,emaskFile);\r\n\t\t\t\t\tif (!quiet) printf(\"Storing edges mask '%s' ...\\n\",emaskFile.c_str());\r\n\t\t\t\t\tif (!imwrite(emaskFile,boundaryEdges)) CV_Error(CV_StsError,\"Could not save image '\" + emaskFile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tif (!quiet) printf(\"Detecting initial center ...\\n\");\r\n\t\t\t\tfloat centerX, centerY;\r\n\t\t\t\tdetectEyeCenter(gradX,gradY,mag,boundaryEdges,centerX, centerY,.5f,101);\r\n\t\t\t\tif (centerX < 0 || centerY < 0 || centerX >= width || centerY >= height){\r\n\t\t\t\t\tif (!quiet) printf(\"Warning: Center not in bounds, correcting to image center.\\n\");\r\n\t\t\t\t\tcenterX = width/2;\r\n\t\t\t\t\tcenterY = height/2;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tif (!quiet) printf(\"Initial center: (x,y) = (%f,%f)\\n\", centerX, centerY);\r\n\t\t\t\t}\r\n\t\t\t\tif (!icentFiles.empty()){\r\n\t\t\t\t\tMat visual;\r\n\t\t\t\t\tcvtColor(img,visual,CV_GRAY2BGR);\r\n\t\t\t\t\tline(visual,Point2f(centerX,0),Point2f(centerX,img.rows),Scalar(0,0,255,0),lt);\r\n\t\t\t\t\tline(visual,Point2f(0,centerY),Point2f(img.cols,centerY),Scalar(0,0,255,0),lt);\r\n\t\t\t\t\tstring icentFile;\r\n\t\t\t\t\tpatternFileRename(inFiles,icentFiles,*inFile,icentFile);\r\n\t\t\t\t\tif (!quiet) printf(\"Storing initial center '%s' ...\\n\", icentFile.c_str());\r\n\t\t\t\t\tif (!imwrite(icentFile,visual)) CV_Error(CV_StsError,\"Could not save image '\" + icentFile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tif (!quiet) printf(\"Detecting first boundary ...\\n\");\r\n\t\t\t\tint polarWidth = outWidth;\r\n\t\t\t\tint polarHeight = cvRound(polarWidth * height / ((float)(width)));\r\n\t\t\t\tMat polar (polarHeight,polarWidth,CV_8UC1);\r\n\t\t\t\tMat polarMask (polarHeight,polarWidth,CV_8UC1);\r\n\t\t\t\tMat polarGrad (polarHeight,polarWidth,CV_32FC1);\r\n\t\t\t\tMat cont(1,polarWidth,CV_32FC1);\r\n\t\t\t\tMat cart (1,polarWidth,CV_32FC2);\r\n\t\t\t\tMat sub;\r\n\t\t\t\tfloat resolution = polarTransform(img,polar,centerX,centerY,-1,INTER_LINEAR_REPEAT);\r\n\t\t\t\tif (!polarFiles.empty()){\r\n\t\t\t\t\tstring polarFile;\r\n\t\t\t\t\tpatternFileRename(inFiles,polarFiles,*inFile,polarFile);\r\n\t\t\t\t\tif (!quiet) printf(\"Storing polar image '%s' ...\\n\", polarFile.c_str());\r\n\t\t\t\t\tif (!imwrite(polarFile,polar)) CV_Error(CV_StsError,\"Could not save image '\" + polarFile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tpolarTransform(mask,polarMask,centerX,centerY,-1,INTER_NEAREST);\r\n\t\t\t\tfindHorizontalEdges(polar,polarMask,polarGrad);\r\n\t\t\t\tinitContour(polarGrad,cont,12,polarHeight); // CHANGED, REMOVE 115 15\r\n\t\t\t\tgradientFit(cont,polarGrad,15);\r\n\t\t\t\tfloat feng = 0;\r\n\t\t\t\tfourierNormalize(cont,cont,feng,1);\r\n\t\t\t\tgradientFit(cont,polarGrad,5);\r\n\t\t\t\tfourierNormalize(cont,cont,feng,3);\r\n\t\t\t\tif (!fboundFiles.empty()){\r\n\t\t\t\t\tMat visual;\r\n\t\t\t\t\tcvtColor(polar,visual,CV_GRAY2BGR);\r\n\t\t\t\t\tMatIterator_<float> it, ite;\r\n\t\t\t\t\tint i=0;\r\n\t\t\t\t\tfor (it = cont.begin<float>(), ite = (cont.end<float>()-1); it < ite; it++, i++){\r\n\t\t\t\t\t\tline(visual,Point2f(i,*it),Point2f(i+1, it[1]),Scalar(0,0,255,0),lt);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tstring fboundFile;\r\n\t\t\t\t\tpatternFileRename(inFiles,fboundFiles,*inFile,fboundFile);\r\n\t\t\t\t\tif (!quiet) printf(\"Storing first boundary image '%s' ...\\n\", fboundFile.c_str());\r\n\t\t\t\t\tif (!imwrite(fboundFile,visual)) CV_Error(CV_StsError,\"Could not save image '\" + fboundFile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tpolar2Cart(cont, cart, 0, 0, resolution);\r\n\t\t\t\t//cartSectors(cart, sub);\r\n\t\t\t\t//RotatedRect boundary = fitEllipse(sub);\r\n\t\t\t\tRotatedRect boundary = fitEllipse(cart);\r\n\t\t\t\tboundary.center.x += centerX;\r\n\t\t\t\tboundary.center.y += centerY;\r\n\t\t\t\tMat cartRefBoundary(1,polarWidth,CV_32FC2);\r\n\t\t\t\tellipse2Cart(cartRefBoundary,boundary);\r\n                \r\n                RotatedRect boundary_cartref_outer_scale = boundary; //scale\r\n                float translate_from_outer_ref = boundary_cartref_outer_scale.size.width * translate; // translate\r\n                boundary_cartref_outer_scale.center.x += translate_from_outer_ref;\r\n                boundary_cartref_outer_scale.size.width *= outer_scale; // scale\r\n                boundary_cartref_outer_scale.size.height *= outer_scale; //scale\r\n                \r\n                RotatedRect boundary_cartref_inner_scale = boundary; //scale\r\n                boundary_cartref_inner_scale.center.x += translate_from_outer_ref;\r\n                boundary_cartref_inner_scale.size.width *= inner_scale; // scale\r\n                boundary_cartref_inner_scale.size.height *= inner_scale; //scale\r\n\r\n\t\t\t\tfloat enRefBoundary = boundaryEnergy(mag,cartRefBoundary);\r\n\t\t\t\tcx1 = centerX;\r\n\t\t\t\tcy1 = centerY;\r\n\t\t\t\tcr1 = (boundary.size.width + boundary.size.height) / 2;\r\n\t\t\t\tif (!quiet) printf(\"Boundary found with energy: %f\\n\", enRefBoundary);\r\n\t\t\t\tif (!quiet) printf(\"Refined center: (x,y) = (%f,%f)\\n\", centerX, centerY);\r\n\t\t\t\tif (abs(boundary.size.width) < 0.0001 || abs(boundary.size.height) < 0.0001){\r\n\t\t\t\t\tboundary.size.width = 1; boundary.size.height = 1;\r\n\t\t\t\t}\r\n\t\t\t\tif (!quiet) printf(\"Ellipsopolar transform and image enhancement ...\\n\");\r\n\t\t\t\tMat ellipsopolar (polarHeight,polarWidth,CV_8UC1);\r\n\t\t\t\tMat ellipsopolarMask (polarHeight,polarWidth,CV_8UC1);\r\n\t\t\t\tfloat ellResolution = ellipsopolarTransform(img,ellipsopolar,boundary,-1,INTER_LINEAR_REPEAT);\r\n\t\t\t\tif (!ellpolFiles.empty()){\r\n\t\t\t\t\tstring ellpolFile;\r\n\t\t\t\t\tpatternFileRename(inFiles,ellpolFiles,*inFile,ellpolFile);\r\n\t\t\t\t\tif (!quiet) printf(\"Storing polar image '%s' ...\\n\", ellpolFile.c_str());\r\n\t\t\t\t\tif (!imwrite(ellpolFile,ellipsopolar)) CV_Error(CV_StsError,\"Could not save image '\" + ellpolFile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tellipsopolarTransform(mask,ellipsopolarMask,boundary,-1,INTER_NEAREST);\r\n\t\t\t\t// enhance images and refer to subimages for inner/outer boundary detection\r\n\t\t\t\tint heightInner = max(1,cvRound(1.f/ellResolution));\r\n\t\t\t\tint heightOuter = polarHeight - heightInner;\r\n\t\t\t\tMat ellipsopolarInner (ellipsopolar,Rect(0,0,polarWidth,heightInner));\r\n\t\t\t\tMat ellipsopolarOuter (ellipsopolar,Rect(0,heightInner,polarWidth,heightOuter));\r\n\t\t\t\tequalizeHist(ellipsopolarInner,ellipsopolarInner);\r\n\t\t\t\tclahe(ellipsopolarOuter,ellipsopolarOuter,polarWidth,min(heightOuter, heightInner * 3));\r\n\t\t\t\t// calculate gradient\r\n\t\t\t\tMat ellipsopolarGrad (polarHeight,polarWidth,CV_32FC1);\r\n\t\t\t\tfindHorizontalEdges(ellipsopolar,ellipsopolarMask,ellipsopolarGrad);\r\n\t\t\t\tRotatedRect innerEll, outerEll;\r\n\t\t\t\tfloat enInner = - FLT_MAX, enOuter = - FLT_MAX;\r\n\t\t\t\tMat cartInner (1,polarWidth,CV_32FC2);\r\n\t\t\t\tMat cartOuter (1,polarWidth,CV_32FC2);\r\n\t\t\t\tif (!quiet) printf(\"Detecting inner boundary candidate ...\\n\");\r\n\t\t\t\t// detect boundary candidates\r\n\t\t\t\tdouble myInner = heightInner * 0.66;//.66\r\n\t\t\t\tdouble sigmaInner = heightInner * 0.4;//.4\r\n\t\t\t\tdouble miny = 21;\r\n\t\t\t\tdouble maxy = heightInner-21;\r\n                RotatedRect fromInner, fromOuter; // keep the source of the inner and outer iris for printout\r\n\t\t\t\tif (miny < maxy){\r\n\t\t\t\t\tinitContour(ellipsopolarGrad,cont,miny,maxy,false,sigmaInner,myInner);// was sigmaouter\r\n\t\t\t\t\tgradientFit(cont,ellipsopolarGrad,15,miny,maxy);\r\n\t\t\t\t\tfourierNormalize(cont,cont,feng,1);\r\n\t\t\t\t\tgradientFit(cont,ellipsopolarGrad,5,miny,maxy);\r\n\t\t\t\t\tfourierNormalize(cont,cont,feng,3);\r\n\t\t\t\t\tif (!iboundFiles.empty()){\r\n\t\t\t\t\t\tMat visual;\r\n\t\t\t\t\t\tcvtColor(ellipsopolar,visual,CV_GRAY2BGR);\r\n\t\t\t\t\t\tMatIterator_<float> it, ite;\r\n\t\t\t\t\t\tint i=0;\r\n\t\t\t\t\t\tfor (it = cont.begin<float>(), ite = (cont.end<float>()-1); it < ite; it++, i++){\r\n\t\t\t\t\t\t\tline(visual,Point2f(i,*it),Point2f(i+1, it[1]),Scalar(0,0,255,0),lt);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tstring iboundFile;\r\n\t\t\t\t\t\tpatternFileRename(inFiles,iboundFiles,*inFile,iboundFile);\r\n\t\t\t\t\t\tif (!quiet) printf(\"Storing i border image '%s' ...\\n\", iboundFile.c_str());\r\n\t\t\t\t\t\tif (!imwrite(iboundFile,visual)) CV_Error(CV_StsError,\"Could not save image '\" + iboundFile + \"'\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tellipsopolar2Cart(cont, cart, boundary, ellResolution);\r\n\t\t\t\t\t//cartSectors(cart,sub); // this usually took a different sector\r\n\t\t\t\t\t//innerEll = fitEllipse(sub);\r\n\t\t\t\t\tinnerEll = fitEllipse(cart);\r\n\t\t\t\t\tellipse2Cart(cartInner,innerEll);\r\n\t\t\t\t\tenInner = boundaryEnergyWeighted(mag,cartInner,boundary,ellResolution,myInner, sigmaInner);//boundaryEnergy(mag,cartInner);//\r\n\t\t\t\t\tif (!quiet) printf(\"Inner boundary candidate found with energy: %f\\n\", enInner);\r\n\t\t\t\t\tRotatedRect innerEll_scale = innerEll;\r\n                    innerEll_scale.center.x += translate_from_outer_ref;\r\n                    innerEll_scale.size.width *= inner_scale;\r\n                    innerEll_scale.size.height *= inner_scale;\r\n\t\t\t\t\tellipse2Cart(cartInner,innerEll_scale);\r\n                    fromInner = innerEll_scale;\r\n\t\t\t\t\tcx2 = innerEll_scale.center.x;\r\n\t\t\t\t\tcy2 = innerEll_scale.center.y;\r\n\t\t\t\t\tcr2 = (innerEll_scale.size.width + innerEll_scale.size.height) / 2;\r\n\t\t\t\t}\r\n\t\t\t\tif (!quiet) printf(\"Detecting outer boundary candidate ...\\n\");\r\n\t\t\t\tdouble myOuter = heightInner * 2.5;//2.5\r\n\t\t\t\tdouble sigmaOuter = heightInner * 1;// 1\r\n\t\t\t\tminy = heightInner+21;\r\n\t\t\t\tmaxy = polarHeight-21;\r\n\t\t\t\tif (miny < maxy){\r\n\t\t\t\t\tinitContour(ellipsopolarGrad,cont,miny,maxy,true,sigmaOuter,myOuter);// was sigmaouter\r\n\t\t\t\t\tgradientFit(cont,ellipsopolarGrad,15,miny,maxy);\r\n\t\t\t\t\tfourierNormalize(cont,cont,feng,1);\r\n\t\t\t\t\tgradientFit(cont,ellipsopolarGrad,5,miny,maxy);\r\n\t\t\t\t\tfourierNormalize(cont,cont,feng,3);\r\n\t\t\t\t\tif (!oboundFiles.empty()){\r\n\t\t\t\t\t\tMat visual;\r\n\t\t\t\t\t\tcvtColor(ellipsopolar,visual,CV_GRAY2BGR);\r\n\t\t\t\t\t\tMatIterator_<float> it, ite;\r\n\t\t\t\t\t\tint i=0;\r\n\t\t\t\t\t\tfor (it = cont.begin<float>(), ite = (cont.end<float>()-1); it < ite; it++, i++){\r\n\t\t\t\t\t\t\tline(visual,Point2f(i,*it),Point2f(i+1, it[1]),Scalar(0,0,255,0),lt);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tstring oboundFile;\r\n\t\t\t\t\t\tpatternFileRename(inFiles,oboundFiles,*inFile,oboundFile);\r\n\t\t\t\t\t\tif (!quiet) printf(\"Storing border image '%s' ...\\n\", oboundFile.c_str());\r\n\t\t\t\t\t\tif (!imwrite(oboundFile,visual)) CV_Error(CV_StsError,\"Could not save image '\" + oboundFile + \"'\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tellipsopolar2Cart(cont, cart, boundary, ellResolution);\r\n\t\t\t\t\t//cartSectors(cart,sub); // this usually took a different sector\r\n\t\t\t\t\t//outerEll = fitEllipse(sub);\r\n\t\t\t\t\touterEll = fitEllipse(cart);\r\n\t\t\t\t\tellipse2Cart(cartOuter,outerEll);\r\n\t\t\t\t\tenOuter = boundaryEnergyWeighted(mag,cartOuter,boundary,ellResolution,myOuter, sigmaOuter);//boundaryEnergy(mag,cartInner);//\r\n\t\t\t\t\tif (!quiet) printf(\"Outer boundary candidate found with energy: %f\\n\", enOuter);\r\n                    //scaling outer boundary\r\n\t\t\t\t\tRotatedRect outerEll_scale = outerEll;\r\n                    outerEll_scale.center.x += translate_from_outer_ref;\r\n                    outerEll_scale.size.width *= outer_scale;\r\n                    outerEll_scale.size.height *= outer_scale;\r\n\t\t\t\t\tellipse2Cart(cartOuter,outerEll_scale);\r\n                    fromOuter = outerEll_scale;\r\n\t\t\t\t\tcx3 = outerEll_scale.center.x;\r\n\t\t\t\t\tcy3 = outerEll_scale.center.y;\r\n\t\t\t\t\tcr3 = (outerEll_scale.size.width + outerEll_scale.size.height) / 2;\r\n\t\t\t\t}\r\n\t\t\t\tif (!quiet) printf(\"Selecting better candidate ...\\n\");\r\n\t\t\t\tint px = 0, py = 0, pr = 0, ix = 0, iy = 0, ir = 0;\r\n\t\t\t\tif (enInner > enOuter){\r\n                    ellipse2Cart(cartRefBoundary,boundary_cartref_outer_scale);\r\n\t\t\t\t\tcartOuter = cartRefBoundary;\r\n                    fromOuter = boundary_cartref_outer_scale;\r\n\t\t\t\t\tpx = cx2;\r\n\t\t\t\t\tpy = cy2;\r\n\t\t\t\t\tpr = cr2;\r\n\t\t\t\t\tix = cx1;\r\n\t\t\t\t\tiy = cy1;\r\n\t\t\t\t\tir = cr1;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n                    ellipse2Cart(cartRefBoundary,boundary_cartref_inner_scale);\r\n\t\t\t\t\tcartInner = cartRefBoundary;\r\n                    fromInner = boundary_cartref_inner_scale;\r\n\t\t\t\t\tpx = cx1;\r\n\t\t\t\t\tpy = cy1;\r\n\t\t\t\t\tpr = cr1;\r\n\t\t\t\t\tix = cx3;\r\n\t\t\t\t\tiy = cy3;\r\n\t\t\t\t\tir = cr3;\r\n\t\t\t\t}\r\n\t\t\t\tMat imask;\r\n\t\t\t\tif (!maskFiles.empty()){\r\n\t\t\t\t\timask.create(height,width,CV_8UC1);\r\n\t\t\t\t\tmask_lids(img, imask, px, py, pr, ix, iy, ir);\r\n\t\t\t\t\tthreshold(imask,imask,1,255,CV_THRESH_BINARY_INV);\r\n\t\t\t\t}\r\n\t\t\t\tif (!segresFiles.empty()){\r\n\t\t\t\t\tMat visual;\r\n\t\t\t\t\tcvtColor(orig,visual,CV_GRAY2BGR);\r\n\t\t\t\t\tfor (float * it = (float *)cartInner.data, * ite = it + (2*polarWidth - 2); it < ite; it+=2){\r\n\t\t\t\t\t\tline(visual,Point2f(*it,it[1]),Point2f(it[2], it[3]),Scalar(0,0,255,0),lt);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfor (float * it = (float *) cartOuter.data, * ite = it + (2*polarWidth - 2); it < ite; it+=2){\r\n\t\t\t\t\t\tline(visual,Point2f(*it,it[1]),Point2f(it[2], it[3]),Scalar(0,255,0,0),lt);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tstring vsegmentfile;\r\n\t\t\t\t\tpatternFileRename(inFiles,segresFiles,*inFile,vsegmentfile);\r\n\t\t\t\t\tif (!quiet) printf(\"Storing segmentation image '%s' ...\\n\", vsegmentfile.c_str());\r\n\t\t\t\t\tif (!imwrite(vsegmentfile,visual)) CV_Error(CV_StsError,\"Could not save image '\" + vsegmentfile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tif (!binmaskFiles.empty()){\r\n\t\t\t\t\tMat bw(height, width, CV_8UC1, Scalar(0));\r\n\t\t\t\t\tvector<Point> iris_points;\r\n\t\t\t\t\tfloat * it = (float *)cartOuter.data;\r\n\t\t\t\t\tfor (int i = 0; i < outWidth; i++){\r\n\t\t\t\t\t\tiris_points.push_back(Point2i(cvRound(*it), cvRound(it[1])));\r\n\t\t\t\t\t\tit += 2;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tconst Point* irisp[1] = { &iris_points[0] };\r\n\t\t\t\t\tvector<Point> pupil_points;\r\n\t\t\t\t\tit = (float *)cartInner.data;\r\n\t\t\t\t\tfor (int i = 0; i < outWidth; i++){\r\n\t\t\t\t\t\tpupil_points.push_back(Point2f(cvRound(*it), cvRound(it[1])));\r\n\t\t\t\t\t\tit += 2;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tconst Point* pupilp[1] = { &pupil_points[0] };\r\n\t\t\t\t\tfillPoly(bw, irisp, &outWidth, 1, Scalar(255, 255, 255));\r\n\t\t\t\t\tfillPoly(bw, pupilp, &outWidth, 1, Scalar(0, 0, 0));\r\n\t\t\t\t\tif (!binmaskFiles.empty()) {\r\n\t\t\t\t\t\tstring binmaskFile;\r\n\t\t\t\t\t\tpatternFileRename(inFiles, binmaskFiles, *inFile, binmaskFile);\r\n\t\t\t\t\t\tif (!quiet) printf(\"Storing binary mask '%s' ...\\n\", binmaskFile.c_str());\r\n\t\t\t\t\t\tif (!imwrite(binmaskFile, bw)) CV_Error(CV_StsError, \"Could not save image '\" + binmaskFile + \"'\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (!quiet) printf(\"Creating final texture ...\\n\");\r\n\t\t\t\tMat out (outHeight,outWidth,CV_8UC1);\r\n                if (!quiet) printf(\"Inner RotatedRect at (%f,%f) size (%f,%f) angle (%f)\\n\", fromInner.center.x, fromInner.center.y, fromInner.size.width, fromInner.size.height, fromInner.angle);\r\n                if (!quiet) printf(\"Outer RotatedRect at (%f,%f) size (%f,%f) angle (%f)\\n\", fromOuter.center.x, fromOuter.center.y, fromOuter.size.width, fromOuter.size.height, fromOuter.angle);\r\n                if( logFile.is_open()){ \r\n                    logFile << inFile->c_str() << \", \" \r\n                            << fromInner.center.x << \", \" \r\n                            << fromInner.center.y << \", \" \r\n                            << fromInner.size.width << \", \" \r\n                            << fromInner.size.height << \", \" \r\n                            << fromInner.angle << \", \" \r\n                            << fromOuter.center.x << \", \"\r\n                            << fromOuter.center.y << \", \"\r\n                            << fromOuter.size.width << \", \"\r\n                            << fromOuter.size.height << \", \"\r\n                            << fromOuter.angle << endl;\r\n                }\r\n\t\t\t\trubbersheet(img, out, cartInner, cartOuter, INTER_LINEAR);\r\n\t\t\t\tif (enhance){\r\n\t\t\t\t\tif (!quiet) printf(\"Enhancing texture ...\\n\");\r\n\t\t\t\t\tclahe(out,out,width/8,height/2);\r\n\t\t\t\t}\r\n\t\t\t\tif (!maskFiles.empty()){\r\n\t\t\t\t\tMat maskout (outHeight,outWidth,CV_8UC1);\r\n\t\t\t\t\trubbersheet(imask, maskout, cartInner, cartOuter, INTER_NEAREST);\r\n\t\t\t\t\tstring maskfile;\r\n\t\t\t\t\tpatternFileRename(inFiles,maskFiles,*inFile,maskfile);\r\n\t\t\t\t\tif (!quiet) printf(\"Storing mask image '%s' ...\\n\", maskfile.c_str());\r\n\t\t\t\t\tif (!imwrite(maskfile,maskout)) CV_Error(CV_StsError,\"Could not save image '\" + maskfile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tstring outfile;\r\n\t\t\t\tpatternFileRename(inFiles,outFiles,*inFile,outfile);\r\n\t\t\t\tif (!quiet) printf(\"Storing image '%s' ...\\n\", outfile.c_str());\r\n\t\t\t\tif (!imwrite(outfile,out)) CV_Error(CV_StsError,\"Could not save image '\" + outfile + \"'\");\r\n\t\t\t\tif (time && timing.update()) timing.print();\r\n\t\t\t}\r\n\t\t\tif (time && quiet) timing.clear();\r\n    \t}\r\n    \telse if (mode == MODE_HELP){\r\n\t\t\t// validate command line\r\n\t\t\tcmdCheckOpts(cmd,\"-h\");\r\n\t\t\tif (cmdGetOpt(cmd,\"-h\") != 0) cmdCheckOptSize(cmd,\"-h\",0);\r\n\t\t\t// starting routine\r\n\t\t\tprintUsage();\r\n    \t}\r\n    }\r\n\tcatch (cv::Exception e){\r\n\t   \tprintf(\"Exit with errors.\\n\");\r\n\t   \texit(EXIT_FAILURE);\r\n\t}\r\n\tcatch (...){\r\n\t   \tprintf(\"Exit with errors.\\n\");\r\n\t   \texit(EXIT_FAILURE);\r\n\t}\r\n    return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "52309e3530575cf7a2d33fc3c278bf935245121f", "size": 175969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wahet.cpp", "max_stars_repo_name": "ngoclamvt123/usit-v2.2.0", "max_stars_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-20T12:40:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T20:04:22.000Z", "max_issues_repo_path": "wahet.cpp", "max_issues_repo_name": "ngoclamvt123/usit-v2.2.0", "max_issues_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "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": "wahet.cpp", "max_forks_repo_name": "ngoclamvt123/usit-v2.2.0", "max_forks_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:51:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T02:49:06.000Z", "avg_line_length": 34.8246586186, "max_line_length": 513, "alphanum_fraction": 0.555910416, "num_tokens": 52353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427860270573, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6368863237610245}}
{"text": "/*\n * Copyright 2019 Denis Yaroshevskiy\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"algo/nth_permutation.h\"\n\n#include <algorithm>\n#include <cstdint>\n#include <numeric>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"algo/factorial.h\"\n\n#include \"test/catch.h\"\n\nnamespace algo {\nnamespace {\n\nusing big_int = boost::multiprecision::cpp_int;\n\nTEST_CASE(\"algorithm.nth_permutation.5ints\", \"[algorithm]\") {\n  std::vector<int> sorted(5);\n  std::iota(sorted.begin(), sorted.end(), 0);\n\n  std::vector<int> actual = sorted;\n\n  for (std::int64_t i = 0;; ++i) {\n    std::vector<int> expected(sorted.size());\n\n    INFO(\"permutation number: \" << i);\n    nth_permutation(sorted.begin(), sorted.end(), expected.begin(), i);\n\n    REQUIRE(expected == actual);\n    if (!std::next_permutation(actual.begin(), actual.end())) break;\n  }\n}\n\nTEST_CASE(\"algorithm.nth_permutation.special_cases\", \"[algorithm]\") {\n  {\n    std::vector<int> v1, v2;\n    nth_permutation(v1.begin(), v1.end(), v2.begin(), 0);\n  }\n  {\n    std::vector<int> v1{1}, v2{1};\n    nth_permutation(v1.begin(), v1.end(), v2.begin(), 0);\n  }\n  {\n    static constexpr size_t size = 1000;\n    std::vector<int> sorted(size), expected(size), actual(size);\n\n    std::iota(sorted.begin(), sorted.end(), 0);\n    std::reverse_copy(sorted.begin(), sorted.end(), expected.begin());\n\n    big_int last_permuation_number =\n        factorial<big_int>(static_cast<int>(size)) - 1;\n\n    nth_permutation(sorted.begin(), sorted.end(), actual.begin(),\n                    std::move(last_permuation_number));\n    REQUIRE(expected == actual);\n  }\n}\n\n}  // namespace\n}  // namespace algo\n", "meta": {"hexsha": "92ffde505db949f6b504ea7c891f613b7a6d64c5", "size": 2163, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/test/algo/nth_permutation.t.cc", "max_stars_repo_name": "maxpev/algorithm_dumpster", "max_stars_repo_head_hexsha": "e68c7da1b1d278fefe2617ce19e4278ac623d286", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/algo/nth_permutation.t.cc", "max_issues_repo_name": "maxpev/algorithm_dumpster", "max_issues_repo_head_hexsha": "e68c7da1b1d278fefe2617ce19e4278ac623d286", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/algo/nth_permutation.t.cc", "max_forks_repo_name": "maxpev/algorithm_dumpster", "max_forks_repo_head_hexsha": "e68c7da1b1d278fefe2617ce19e4278ac623d286", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3797468354, "max_line_length": 75, "alphanum_fraction": 0.6731391586, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6368766735037681}}
{"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#ifndef NDEBUG\n  #define NDEBUG\n#endif\n\n//#define VIENNACL_DEBUG_ALL\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <vector>\n\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/qr-method.hpp\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n\nnamespace ublas = boost::numeric::ublas;\n\ntypedef float ScalarType;\n\n\nvoid initialize(viennacl::matrix<ScalarType>& A, std::vector<ScalarType>& v);\nvoid vector_print(std::vector<ScalarType>& v );\nvoid matrix_print(viennacl::matrix<ScalarType>& A_orig);\n\n\n\n\nvoid qr_method()\n{\n    /*\n     *                      Tutorial for the qr-method\n     *\n     * The eigenvalues and eigenvectors of a symmetric 9 by 9 matrix are calculated\n     * by the QR-method.\n     *\n     */\n\n    std::cout << \"Testing matrix of size \" << 9 << \"-by-\" << 9 << std::endl;\n\n    viennacl::matrix<ScalarType> A_input(9,9);\n    viennacl::matrix<ScalarType> Q(9, 9);\n    std::vector<ScalarType> eigenvalues_ref(9);\n    std::vector<ScalarType> eigenvalues(9);\n\n    initialize(A_input, eigenvalues_ref);  //initialize with data for tutorial\n\n    std::cout << std::endl <<\"Input matrix: \" << std::endl;\n    matrix_print(A_input);\n\n\n    std::cout << std::endl << \"Starting QR-method\" << std::endl;\n    std::cout << \"Calculation...\" << std::endl;\n\n    /*\n     * Call function qr_method_sym to calculate eigenvalues and eigenvectors\n     * Parameters:\n     *       A_input     - input matrix to find eigenvalues and eigenvectors from\n     *       Q           - matrix, where the calculated eigenvectors will be stored in\n     *       eigenvalues - vector, where the calculated eigenvalues will be stored in\n     */\n\n    viennacl::linalg::qr_method_sym(A_input, Q, eigenvalues);\n\n    std::cout << std::endl << \"Eigenvalues:\" << std::endl;\n    vector_print(eigenvalues);\n    std::cout << std::endl << \"Reference eigenvalues:\" << std::endl;\n    vector_print(eigenvalues_ref);\n    std::cout << std::endl << \"Eigenvectors - each column is an eigenvector\" << std::endl;\n\n    matrix_print(Q);\n\n}\n\nint main()\n{\n\n  qr_method();\n\n  std::cout << std::endl;\n  std::cout << \"------- Tutorial completed --------\" << std::endl;\n  std::cout << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n//initialize vector and matrix\nvoid initialize(viennacl::matrix<ScalarType>& A, std::vector<ScalarType>& v)\n{\n    ScalarType M[9][9] = {{4, 1, -2, 2, -7, 3, 9, -6, -2}, {1, -2, 0, 1, -1, 5, 4, 7, 3}, {-2, 0, 3, 2, 0, 3, 6, 1, -1},   {2, 1, 2, 1, 4, 5, 6, 7, 8},\n               {-7, -1, 0, 4, 5, 4, 9, 1, -8},  {3, 5, 3, 5, 4, 9, -3, 3, 3}, {9, 4, 6, 6, 9, -3, 3, 6, -7},   {-6, 7, 1, 7, 1, 3, 6, 2, 6},\n               {-2, 3, -1, 8, -8, 3, -7, 6, 1}};\n\n    for(int i = 0; i < 9; i++)\n        for(int j = 0; j < 9; j++)\n            A(i, j) = M[i][j];\n\n    ScalarType V[9] = {12.6005, 19.5905, 8.06067, 2.95074, 0.223506, 24.3642, -9.62084, -13.8374, -18.3319};\n\n    for(int i = 0; i < 9; i++)\n        v[i] = V[i];\n}\n\nvoid matrix_print(viennacl::matrix<ScalarType>& A_orig)\n{\n    ublas::matrix<ScalarType> A(A_orig.size1(), A_orig.size2());\n    viennacl::copy(A_orig, A);\n    for (unsigned int i = 0; i < A.size1(); i++) {\n        for (unsigned int j = 0; j < A.size2(); j++)\n           std::cout << A(i, j) << \"\\t\";\n        std::cout << std::endl;\n    }\n}\n\nvoid vector_print(std::vector<ScalarType>& v )\n{\n  for (unsigned int i = 0; i < v.size(); i++)\n      std::cout << std::setprecision(6) << std::fixed << v[i] << \"\\t\";\n    std::cout << std::endl;\n}\n", "meta": {"hexsha": "fa41997db8eb84d3f7b753fdb74650b3b3d047dd", "size": 4220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/qr_method.cpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tutorial/qr_method.cpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tutorial/qr_method.cpp", "max_forks_repo_name": "denis14/ViennaCL-1.5.2", "max_forks_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3597122302, "max_line_length": 151, "alphanum_fraction": 0.5471563981, "num_tokens": 1277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6368766671100802}}
{"text": "/*\n * NOTE: this is a \"power set\" problem\n */\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <numeric>\n#include <string>\n#include <vector>\n\n#include <boost/range/counting_range.hpp>\n\ntemplate<typename T>\nauto get_vector_from_file(std::fstream& file) {\n\treturn std::vector<T>{\n\t\tstd::istream_iterator<T>{file},\n\t\tstd::istream_iterator<T>{}\n\t};\n}\n\nint main() {\n\n\tconst auto filename = std::string{\"containers.txt\"};\n\tauto file = std::fstream{filename};\n\n\tif(file.is_open()) {\n\n\t\tconst auto containers = get_vector_from_file<std::uint64_t>(file);\n\n\t\tconst auto target_volume = std::uint64_t{150};\n\n\t\tauto count = std::uint64_t{};\n\n\t\t/*\n\t\t * NOTE: the following algorithm was adapted\n\t\t * from this stackoverflow.com answer:\n\t\t * https://stackoverflow.com/a/19891145/699211\n\t\t */\n\n\t\t/* compute power set */\n\t\tconst auto size = containers.size();\n\n\t\tauto powerset = std::vector<std::vector<std::uint64_t>>(1 << size);\n\n\t\tpowerset[0] = {};\n\n\t\tfor(const auto i : boost::counting_range({}, size)) {\n\n\t\t\tconst auto subsize = (1 << i); // doubling size of subset\n\n\t\t\tfor(const auto j : boost::counting_range({}, subsize)) {\n\n\t\t\t\tconst auto& source = powerset[j];\n\n\t\t\t\tconst auto srcsize = source.size();\n\n\t\t\t\tauto& destination = powerset[subsize+j] = std::vector<std::uint64_t>(srcsize + 1);\n\n\t\t\t\tfor(const auto k : boost::counting_range({}, srcsize)) {\n\t\t\t\t\tdestination[k] = source[k];\n\t\t\t\t}\n\n\t\t\t\tdestination[srcsize] = containers[i];\n\n\t\t\t\tconst auto new_volume = std::accumulate(destination.begin(), destination.end(), std::uint64_t{});\n\n\t\t\t\tif(new_volume == target_volume) {\n\t\t\t\t\t++count;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstd::cout << count << std::endl;\n\n\t} else {\n\t\tstd::cerr << \"Error! Could not open \\\"\" << filename << \"\\\"!\" << std::endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "0b100830d77a2a3ccfd3f6e3b68ddc50c3ac3594", "size": 1759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 17 Part 1/main.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 17 Part 1/main.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 17 Part 1/main.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7160493827, "max_line_length": 101, "alphanum_fraction": 0.644115975, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.7745833789613197, "lm_q1q2_score": 0.63685404836417}}
{"text": "/*\n Copyright (C) 2017 Sascha Meiers\n Distributed under the MIT software license, see the accompanying\n file LICENSE.md or http://www.opensource.org/licenses/mit-license.php.\n */\n\n#ifndef distribution_h\n#define distribution_h\n\n#include <iostream>\n#include <vector>\n#include <cassert>\n#include \"utils.hpp\"\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/negative_binomial.hpp>\n#include <boost/math/distributions/binomial.hpp>\n\n\nnamespace hmm {\n\n\n    static const double MIN_EMISSION_LOG = -1e4;\n    // TODO: check for p=0 or 1 in all pdfs --> take special care for log then!\n\n\n    /**\n     *  NegativeBinomial\n     *  ----------------\n     *  p(k) = {\\Gamma(n + k) \\over \\Gamma(k+1) \\Gamma(n) } p^n (1-p)^k\n     *  Number of failures k before n-th success.\n     *  Mean :=  n * (1-p)/p\n     *  Variance := Mean/p\n     */\n    class NegativeBinomial\n    {\n    public:\n        typedef unsigned TEmission;\n        static const uint8_t dim = 1;\n        boost::math::negative_binomial nb;\n\n\n        NegativeBinomial(double p, double n) : nb(n,p)\n        {}\n\n        inline double calc_log_emission(std::vector<unsigned>::const_iterator iter) const\n        {\n            double pr = log(calc_emission(iter));\n            if (pr < MIN_EMISSION_LOG)\n                pr = MIN_EMISSION_LOG;\n            return pr;\n        }\n\n        inline double calc_emission(std::vector<unsigned>::const_iterator iter) const\n        {\n            return boost::math::pdf(nb, *iter);\n        }\n    };\n\n    std::ostream& operator<<(std::ostream& os, const NegativeBinomial& obj)\n    {\n        os << \"Negative Binomial Distribution:\" << std::endl;\n        os << \"       p = \" << obj.nb.success_fraction() << std::endl;\n        os << \"       r = \" << obj.nb.successes() << std::endl;\n        os << \"    mean = \" << mean(obj.nb) << std::endl;\n        os << \"     var = \" << variance(obj.nb) << std::endl;\n        return os;\n    }\n\n\n\n    /**\n     *  MultiVariate\n     *  ------------\n     *  A quick wrapper to sum up multiple 1-dim distirbutions of the same type into\n     *  one \"multivariate\" one, in which components are independent.\n     */\n    template <typename TDistribution>\n    class MultiVariate\n    {\n    public:\n        uint8_t dim;\n        std::vector<TDistribution> inner;\n        double log_prior;\n\n        MultiVariate(std::vector<TDistribution> const & distributions, double _prior = 1) :\n        inner(distributions), dim(distributions.size()), log_prior(log(_prior))\n        {\n            assert(distributions.size() > 0 && distributions.size() < 256);\n            for (auto dist : distributions)\n                assert(dist.dim == (uint8_t)1);\n        }\n\n        inline double calc_log_emission(typename std::vector<typename TDistribution::TEmission>::const_iterator iter) const\n        {\n            double logp = 0;\n            for (unsigned i=0; i<dim; ++i, ++iter)\n                logp += inner[i].calc_log_emission(iter);\n            logp += log_prior;\n            if (logp < MIN_EMISSION_LOG)\n                logp = MIN_EMISSION_LOG;\n            return logp;\n        }\n\n        inline double calc_emission(std::vector<unsigned>::const_iterator iter) const\n        {\n            return exp(calc_log_emission(iter));\n        }\n    };\n\n    template <typename TDistribution>\n    std::ostream& operator<<(std::ostream& os, const MultiVariate<TDistribution>& obj)\n    {\n        os << \"Multivariate distribution with \" << (int)obj.dim << \" dimensions:\" << std::endl;\n        for (unsigned i=0; i<obj.inner.size(); ++i)\n            os << \">> \" <<  i << \") \" <<  obj.inner[i];\n        os << std::endl;\n        return os;\n    }\n\n\n\n\n    /**\n     *  CombinedNegBinAndBinomial\n     *  ----------------\n     *  Model total coverage (w+c) by Negative Binomial and fraction c/(w+c) by\n     *  a binomial distribution.\n     */\n    class CombinedNegBinAndBinomial\n    {\n    public:\n        typedef unsigned TEmission;\n        static const uint8_t dim = 2;\n        boost::math::negative_binomial nb;\n        double ratio;\n        double prior;\n\n        CombinedNegBinAndBinomial(double nb_p, double nb_r, double strand_ratio, double prior = 1) :\n        nb(nb_r,nb_p), ratio(strand_ratio), prior(prior)\n        {}\n\n        inline double calc_log_emission(std::vector<unsigned>::const_iterator iter) const\n        {\n            double pr = log(calc_emission(iter));\n            if (pr < MIN_EMISSION_LOG)\n                pr = MIN_EMISSION_LOG;\n            return pr;\n        }\n\n        inline double calc_emission(std::vector<unsigned>::const_iterator iter) const\n        {\n            unsigned c = *iter++;\n            unsigned w = *iter++;\n            boost::math::binomial_distribution<> binomial(c+w, ratio);\n            return prior * boost::math::pdf(nb, w+c) * boost::math::pdf(binomial, w);\n        }\n    };\n\n\n    \n}\n#endif /* distribution_h */\n", "meta": {"hexsha": "ed79f01af4d4a4f4fba96509111b64c97c436aec", "size": 4862, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/distribution.hpp", "max_stars_repo_name": "tobiasmarschall/mosaicatcher", "max_stars_repo_head_hexsha": "42b078ec0964f3711f0f4871065be5157e63eb37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-26T01:36:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T00:28:01.000Z", "max_issues_repo_path": "src/distribution.hpp", "max_issues_repo_name": "tobiasmarschall/mosaicatcher", "max_issues_repo_head_hexsha": "42b078ec0964f3711f0f4871065be5157e63eb37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-01-12T11:56:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-29T16:09:34.000Z", "max_forks_repo_path": "src/distribution.hpp", "max_forks_repo_name": "tobiasmarschall/mosaicatcher", "max_forks_repo_head_hexsha": "42b078ec0964f3711f0f4871065be5157e63eb37", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-05-24T09:12:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-02T11:33:28.000Z", "avg_line_length": 29.8282208589, "max_line_length": 123, "alphanum_fraction": 0.57239819, "num_tokens": 1171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6367329394381197}}
{"text": "#include \"correlation.hpp\"\n#include <cmath>\n#include <algorithm>\n#include <iterator>\n#include <stdexcept>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n#include \"global.hpp\"\n#include \"lua.hpp\"\n#include <boost/numeric/ublas/io.hpp>\n\ncorrelation_fn makeGaussianCorrelation( double corrlength )\n{\n\tdouble scale = -1.0 / corrlength / corrlength;\n\tauto f = [scale](const gen_vect& v) -> double\n\t{\n\t\tusing boost::numeric::ublas::inner_prod;\n\t\treturn std::exp(inner_prod(v, v) * scale);\n\t};\n\treturn f;\n}\n\ncorrelation_fn makeAnisotropicGaussianCorrelation( double corrlength, gen_vect ani )\n{\n\t// scale anisotropy factor with global correlation length and precalculate the squares\n\tfor( auto& v : ani )\n\t\tv = v*v/corrlength/corrlength;\n\t\n\tauto f = [ani](const gen_vect& v) -> double\n\t{\n\t\tusing boost::numeric::ublas::inner_prod;\n\t\tdouble sum = 0;\n\t\tfor( unsigned i = 0; i < v.size(); ++i )\n\t\t\tsum -= v[i] * v[i] * ani[i];\n\n\t\treturn std::exp( sum );\n\t};\n\treturn f;\n}\n\ncorrelation_fn makeSechCorrelation( double corrlength )\n{\n\tdouble scale = 1.0 / corrlength;\n\tauto f = [scale](const gen_vect& v) -> double\n\t{\n\t\tusing boost::numeric::ublas::inner_prod;\n\t\tdouble l = std::sqrt(inner_prod(v, v)) * scale;\n\t\t// sech(x) = 1 / cosh(x)\n\t\treturn 1.0 / std::cosh(l);\n\t};\n\treturn f;\n}\n\ncorrelation_fn makePowerCorrelation( double corrlength, double alpha )\n{\n\tdouble scale = 1.0 / corrlength / corrlength;\n\tauto f = [scale, alpha](const gen_vect& v) -> double\n\t{\n\t\tusing boost::numeric::ublas::inner_prod;\n\t\tdouble l = 1 + inner_prod(v, v) * scale;\n\t\treturn std::pow(l, -alpha);\n\t};\n\treturn f;\n}\n\ncorrelation_fn makeLuaCorrelation( double corrlength, std::string scriptfile, const std::vector<std::string>& vars )\n{\n\tauto make_lua = [=]() {\n\t\t// create state, load and compile file\n\t\tlua_State* state = luaL_newstate();\n\t\t// open math library\n\t\tluaL_requiref(state, LUA_MATHLIBNAME, luaopen_math, 1);\n\t\tlua_pop(state, 1);\n\t\t// open file\n\t\tluaL_dofile(state, scriptfile.c_str());\n\n\t\t// set the variables\n\t\tfor (unsigned i = 0; i < vars.size(); i += 2) {\n\t\t\tauto name = vars.at(i);\n\t\t\tauto value = boost::lexical_cast<double>(vars.at(i + 1));\n\t\t\tlua_pushnumber(state, value);\n\t\t\tlua_setglobal(state, name.c_str());\n\t\t}\n\n\n\t\t// check that correlation function is set\n\t\tlua_getglobal(state, \"c\");\n\t\tif (!lua_isfunction(state, -1))\n\t\tTHROW_EXCEPTION(std::runtime_error, \"lua script does not contain a function named c\");\n\t\tlua_pop(state, 1);\n\n\t\treturn state;\n\t};\n\n\t// now the correlation function\n\tauto f = [make_lua, corrlength](const gen_vect& v) -> double\n\t{\n        // ensure that we have a one lua interpreter per thread\n\t\tthread_local lua_State* state = make_lua();\n\t\t// get the lua function reference\n\t\t/// \\todo is it possible to cache this?\n\t\tlua_getglobal(state, \"c\");\n\t\tassert(lua_isfunction(state, -1));\n\n\t\t// push the scaled vector\n\t\tfor(unsigned i = 0; i < v.size(); ++i)\n\t\t\tlua_pushnumber(state, v[i] / corrlength);\n\n\t\t// call the function and handle any errors\n\t\tif(lua_pcall(state, v.size(), 1, 0))\n\t\t{\n\t\t\tconst char* error = lua_tostring(state, -1);\n\t\t\tTHROW_EXCEPTION( std::runtime_error, error );\n\t\t}\n\n\t\t// get the result and clear the stack\n\t\tdouble result = lua_tonumber(state, -1);\n\t\tlua_pop(state, 1);\n\t\treturn result;\n\t};\n\treturn f;\n}\n\ncorrelation_fn makeTransformedCorrelation( correlation_fn original, trafo_matrix_t matrix )\n{\n\tauto f = [original, matrix](const gen_vect& v) -> double\n\t{\n\t\treturn original( boost::numeric::ublas::prod(matrix, v) );\n\t};\n\treturn f;\n}\n\n// make correlation function without any trafo.\ncorrelation_fn makeCorrelation( const std::vector<std::string>& specs, double length )\n{\n\tassert( !specs.empty() );\n\tstd::string corr_type = specs[0];\n\tif(corr_type == \"gauss\" || corr_type == \"gaussian\")\n\t\tif( specs.size() == 1 )\t// no further parameters: use isotropic gaussian\n\t\t\treturn makeGaussianCorrelation( length );\n\t\telse\n\t\t{\n\t\t\tgen_vect ani( specs.size() - 1);\n\t\t\tfor(unsigned i = 1; i < specs.size(); ++i)\n\t\t\t\tani[i-1] = boost::lexical_cast<double>( specs[i] );\n\t\t\treturn makeAnisotropicGaussianCorrelation( length, ani );\n\t\t}\n\telse if(corr_type == \"sech\" )\n\t\treturn makeSechCorrelation( length );\n\telse if(corr_type == \"pow\" || corr_type == \"power\")\n\t\treturn makePowerCorrelation( length, boost::lexical_cast<double>(specs.at(1)));\n\telse if(corr_type == \"lua\")\n\t{\n\t\tif( specs.size() < 2 )\n\t\t\tTHROW_EXCEPTION( std::runtime_error, \"No script file specified for lua correlation\" );\n\n\t\t// load specifications for variables that are set in lua\n\t\tstd::vector<std::string> vars(specs.begin() + 2, specs.end());\n\t\tif( vars.size() % 2 != 0 )\n\t\t\tTHROW_EXCEPTION( std::runtime_error, \"invalid variables for lua script. Use \\\"lua filename var1 value1 var2 value2\\\"\" );\n\t\treturn makeLuaCorrelation( length, specs.at(1), vars);\n\t}\n\telse\n\t\tTHROW_EXCEPTION( std::runtime_error, \"correlation type %1% not valid\", corr_type);\n\n}\n\n// convert a vector of strings to a ublas matrix\ntrafo_matrix_t matrix_from_string_vector(const std::vector<std::string>& source)\n{\n\tstd::size_t dim = 0;\n\tswitch(source.size())\n\t{\n\tcase 1:\n\t\tdim = 1;\n\t\tbreak;\n\tcase 4:\n\t\tdim = 2;\n\t\tbreak;\n\tcase 9:\n\t\tdim = 3;\n\t\tbreak;\n\tdefault:\n\t\tTHROW_EXCEPTION(std::runtime_error, \"transformation matrix is required to be square with dim <= 3. Got %1% elements.\", source.size());\n\t}\n\n\tstd::vector<double> converted;\n\ttrafo_matrix_t matrix(dim, dim);\n\tstd::transform( begin(source), end(source), std::back_inserter(converted), [](const std::string& s){ return boost::lexical_cast<double>(s); } );\n\tfor(unsigned i = 0; i < dim; ++i)\n\t{\n\t\tfor(unsigned j = 0; j < dim; ++j)\n\t\t{\n\t\t\tmatrix(i, j) = converted[dim*i + j];\n\t\t}\n\t}\n\treturn matrix;\n}\n\ncorrelation_fn makeCorrelation( const std::vector<std::string>& specs, double length, std::string trafo )\n{\n\t// easy case: no trafo\n\tif(trafo.empty())\n\t\treturn makeCorrelation(specs, length);\n\t\n\t// otherwise, start out with untrafo'ed\n\t// in case we get quotes from the command line, remove them.\n\tauto base = makeCorrelation(specs, length);\n\tif(boost::starts_with(trafo, \"\\\"\"))\n\t\ttrafo = trafo.substr(1);\n\tif(boost::ends_with(trafo, \"\\\"\"))\n\t\ttrafo = trafo.substr(0, trafo.size() - 1);\n\t\n\t// now split\n\tstd::vector<std::string> split;\n\tboost::split(split, trafo, [](char c){ return std::isspace(c); });\n\ttrafo_matrix_t matrix = matrix_from_string_vector(split);\n\t\n\treturn makeTransformedCorrelation(base, matrix);\n}\n", "meta": {"hexsha": "18fedabf2f348188c255d6fd31b99be6734f04d8", "size": 6413, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/potgen/correlation.cpp", "max_stars_repo_name": "ngc92/branchedflowsim", "max_stars_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/potgen/correlation.cpp", "max_issues_repo_name": "ngc92/branchedflowsim", "max_issues_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/potgen/correlation.cpp", "max_forks_repo_name": "ngc92/branchedflowsim", "max_forks_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8873873874, "max_line_length": 145, "alphanum_fraction": 0.682208015, "num_tokens": 1866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6367329378232701}}
{"text": "/*!\n * \\file QBezierTriangle.hpp\n * \\author Jun Yoshida\n * \\copyright (c) 2019 Jun Yoshida.\n * The project is released under the MIT License.\n * \\date Descember 6, 2019: created\n */\n\n#pragma once\n\n#include <array>\n#include <vector>\n#include <Eigen/Dense>\n\n#include \"../math/Bezier.hpp\"\n#include \"PathFigure3D.hpp\"\n\nclass QBezierTriangle : public PathFigure3D\n{\nprivate:\n    std::array<Eigen::Vector3d,3> m_vert, m_edge;\n    std::vector<Bezier<Eigen::Vector3d,3> > m_ridges;\n    bool m_reliable;\n\npublic:\n    QBezierTriangle(std::array<vertex_type,3> const &vert, std::array<vertex_type,3> const &edge)\n        : m_vert{ Eigen::Vector3d(vert[0][0], vert[0][1], vert[0][2]),\n                  Eigen::Vector3d(vert[1][0], vert[1][1], vert[1][2]),\n                  Eigen::Vector3d(vert[2][0], vert[2][1], vert[2][2]) },\n          m_edge{ Eigen::Vector3d(edge[0][0], edge[0][1], edge[0][2]),\n                  Eigen::Vector3d(edge[1][0], edge[1][1], edge[1][2]),\n                  Eigen::Vector3d(edge[2][0], edge[2][1], edge[2][2]) },\n          m_ridges(),\n          m_reliable(true)\n    {}\n\n    QBezierTriangle(std::array<double,3> const &v0, std::array<double,3> const &v1, std::array<double,3> const &v2, std::array<double,3> const &e0, std::array<double,3> const &e1, std::array<double,3> const &e2)\n        : m_vert{ Eigen::Vector3d(v0[0], v0[1], v0[2]),\n                  Eigen::Vector3d(v1[0], v1[1], v1[2]),\n                  Eigen::Vector3d(v2[0], v2[1], v2[2]) },\n          m_edge{ Eigen::Vector3d(e0[0], e0[1], e0[2]),\n                  Eigen::Vector3d(e1[0], e1[1], e1[2]),\n                  Eigen::Vector3d(e2[0], e2[1], e2[2]) },\n          m_ridges(),\n          m_reliable(true)\n    {}\n    virtual ~QBezierTriangle() = default;\n\n    Eigen::Vector3d eval(double t0, double t1, double t2) {\n        return t0*t0*m_vert[0]\n            + t1*t1*m_vert[1]\n            + t2*t2*m_vert[2]\n            + 2.0*t0*t1*m_edge[2]\n            + 2.0*t1*t2*m_edge[0]\n            + 2.0*t2*t0*m_edge[1];\n    }\n\n    Eigen::Vector3d eval(double s1, double s2) {\n        return eval(1.0-s1-s2, s1, s2);\n    }\n\n    /**!\n     * \\section Member functions derived from PathFigure\n     **/\n    virtual void draw(SchemeType &scheme) const override;\n\n    /**!\n     * \\section Member functions derived from PathFigure3d\n     **/\n    virtual void updateProjector(Eigen::Matrix<double,2,3> const &proj) override;\n};\n\n", "meta": {"hexsha": "2c02cc2b484aa1b3c2e76ebfbb0a7971d73daa1b", "size": 2394, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/figures/QBezierTriangle.hpp", "max_stars_repo_name": "Junology/bord2", "max_stars_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/figures/QBezierTriangle.hpp", "max_issues_repo_name": "Junology/bord2", "max_issues_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/figures/QBezierTriangle.hpp", "max_forks_repo_name": "Junology/bord2", "max_forks_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7945205479, "max_line_length": 211, "alphanum_fraction": 0.5664160401, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6367025401337155}}
{"text": "/*\nThis example shows how to convert to/from transformation matrix (rotation matrix + translation vector).\n\nZivid primarily operate with a (4x4) transformation matrix. This example shows how to use Eigen to\nconvert to and from: AxisAngle, Rotation Vector, Roll-Pitch-Yaw, Quaternion\n\nThe convenience functions from this example can be reused in applicable applications. The YAML files for this sample can\nbe found under the main instructions for Zivid samples.\n*/\n\n#include <Zivid/Zivid.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include <iomanip>\n#include <iostream>\n\nnamespace\n{\n    enum class RotationConvention\n    {\n        zyxIntrinsic,\n        xyzExtrinsic,\n        xyzIntrinsic,\n        zyxExtrinsic,\n        nofROT\n    };\n    constexpr size_t nofRotationConventions = static_cast<size_t>(RotationConvention::nofROT);\n\n    struct RollPitchYaw\n    {\n        RotationConvention convention;\n        Eigen::Array3d rollPitchYaw;\n    };\n\n    std::string toString(RotationConvention convention)\n    {\n        switch(convention)\n        {\n            case RotationConvention::xyzIntrinsic: return \"xyzIntrinsic\";\n            case RotationConvention::xyzExtrinsic: return \"xyzExtrinsic\";\n            case RotationConvention::zyxIntrinsic: return \"zyxIntrinsic\";\n            case RotationConvention::zyxExtrinsic: return \"zyxExtrinsic\";\n            case RotationConvention::nofROT: break;\n        }\n\n        throw std::invalid_argument(\"Invalid RotationConvention\");\n    }\n\n    // The following function converts Roll-Pitch-Yaw angles in radians to Rotation Matrix.\n    // This function takes an array of roll, pitch and yaw angles, and a rotation convention, as input parameters.\n    // For Roll-Pitch-Yaw we define that roll is a rotation about x-axis, pitch is a rotation about y-axis\n    // and yaw is a rotation about z-axis.\n    // Whether the axes are moving (intrinsic) or fixed (extrinsic) is defined by the rotation convention.\n    // The array is ordered by Roll, Pitch and then Yaw.\n    Eigen::Matrix3d rollPitchYawToRotationMatrix(const Eigen::Array3d &rollPitchYaw, const RotationConvention &rotation)\n    {\n        switch(rotation)\n        {\n            case RotationConvention::xyzIntrinsic:\n            case RotationConvention::zyxExtrinsic:\n                return (Eigen::AngleAxisd(rollPitchYaw[0], Eigen::Vector3d::UnitX())\n                        * Eigen::AngleAxisd(rollPitchYaw[1], Eigen::Vector3d::UnitY())\n                        * Eigen::AngleAxisd(rollPitchYaw[2], Eigen::Vector3d::UnitZ()))\n                    .matrix();\n            case RotationConvention::zyxIntrinsic:\n            case RotationConvention::xyzExtrinsic:\n                return (Eigen::AngleAxisd(rollPitchYaw[2], Eigen::Vector3d::UnitZ())\n                        * Eigen::AngleAxisd(rollPitchYaw[1], Eigen::Vector3d::UnitY())\n                        * Eigen::AngleAxisd(rollPitchYaw[0], Eigen::Vector3d::UnitX()))\n                    .matrix();\n            case RotationConvention::nofROT: break;\n        }\n\n        throw std::invalid_argument(\"Invalid orientation\");\n    }\n\n    void rollPitchYawListToRotationMatrix(const std::vector<RollPitchYaw> &rpyList)\n    {\n        Eigen::IOFormat matrixFmt(4, 0, \", \", \"\\n\", \"[\", \"]\", \"[\", \"]\");\n        for(const auto &rotation : rpyList)\n        {\n            std::cout << \"Rotation Matrix from Roll-Pitch-Yaw angles (\" << toString(rotation.convention)\n                      << \"):\" << std::endl;\n            const auto rotationMatrixFromRollPitchYaw =\n                rollPitchYawToRotationMatrix(rotation.rollPitchYaw, rotation.convention);\n            std::cout << rotationMatrixFromRollPitchYaw.format(matrixFmt) << std::endl;\n        }\n    }\n\n    // The following function converts Rotation Matrix to Roll-Pitch-Yaw angles in radians.\n    // The rotation convention we use here is that Roll is a rotation about x-axis,\n    // Pitch is a rotation about y-axis and Yaw is a rotation about z-axis.\n    // Whether the axes are moving (intrinsic) or fixed (extrinsic) is defined by the rotation convention.\n    // The array is ordered by Roll, Pitch and then Yaw.\n    Eigen::Array3d rotationMatrixToRollPitchYaw(const Eigen::Matrix3d &rotationMatrix,\n                                                const RotationConvention &convention)\n    {\n        switch(convention)\n        {\n            case RotationConvention::zyxExtrinsic:\n            case RotationConvention::xyzIntrinsic: return rotationMatrix.eulerAngles(0, 1, 2);\n            case RotationConvention::xyzExtrinsic:\n            case RotationConvention::zyxIntrinsic: return rotationMatrix.eulerAngles(2, 1, 0).reverse();\n            case RotationConvention::nofROT: break;\n        }\n\n        throw std::invalid_argument(\"Invalid rotation\");\n    }\n\n    std::vector<RollPitchYaw> rotationMatrixToRollPitchYawList(const Eigen::Matrix3d &rotationMatrix)\n    {\n        const Eigen::IOFormat vectorFmt(4, 0, \", \", \"\", \"\", \"\", \"[\", \"]\");\n        std::vector<RollPitchYaw> rpyList;\n        for(size_t i = 0; i < nofRotationConventions; i++)\n        {\n            RotationConvention convention{ static_cast<RotationConvention>(i) };\n            std::cout << \"Roll-Pitch-Yaw angles (\" << toString(convention) << \"):\" << std::endl;\n            rpyList.push_back({ convention, rotationMatrixToRollPitchYaw(rotationMatrix, convention) });\n            std::cout << rpyList[i].rollPitchYaw.format(vectorFmt) << std::endl;\n        }\n        return rpyList;\n    }\n\n    Eigen::MatrixXd cvToEigen(const cv::Mat &cvMat)\n    {\n        Eigen::MatrixXd eigenMat(cvMat.rows, cvMat.cols);\n\n        cv::cv2eigen(cvMat, eigenMat);\n\n        return eigenMat;\n    }\n\n    Eigen::Affine3d getTransformationMatrixFromYAML(const std::string &path)\n    {\n        cv::FileStorage fileStorageIn;\n        if(!fileStorageIn.open(path, cv::FileStorage::Mode::READ))\n        {\n            throw std::runtime_error(\"Could not open \" + path + \". Please run this sample from the build directory\");\n        }\n        const auto poseStateNode = fileStorageIn[\"PoseState\"];\n        std::cout << \"Getting PoseState:\" << std::endl;\n        if(poseStateNode.empty())\n        {\n            fileStorageIn.release();\n            throw std::runtime_error(\"PoseState node not found in file\");\n        }\n        auto transformationMatrix = Eigen::Affine3d(static_cast<Eigen::Matrix4d>(cvToEigen(poseStateNode.mat())));\n        fileStorageIn.release();\n\n        return transformationMatrix;\n    }\n\n    cv::Mat eigenToCv(const Eigen::MatrixXd &eigenMat)\n    {\n        // NOLINTNEXTLINE(hicpp-signed-bitwise)\n        cv::Mat cvMat(static_cast<int>(eigenMat.rows()), static_cast<int>(eigenMat.cols()), CV_64FC1, cv::Scalar(0));\n\n        cv::eigen2cv(eigenMat, cvMat);\n\n        return cvMat;\n    }\n\n    void saveTransformationMatrixToYAML(const Eigen::Affine3d &transformationMatrix, const std::string &path)\n    {\n        // Save Transformation Matrix to .YAML file\n        cv::FileStorage fileStorageOut;\n        if(!fileStorageOut.open(path, cv::FileStorage::Mode::WRITE))\n        {\n            throw std::runtime_error(\"Could not open robotTransformOut.yaml for writing\");\n        }\n        fileStorageOut.write(\"TransformationMatrixFromQuaternion\", eigenToCv(transformationMatrix.matrix()));\n        fileStorageOut.release();\n    }\n\n    Eigen::Vector3d rotationMatrixToRotationVector(const Eigen::Matrix3d &rotationMatrix)\n    {\n        const Eigen::AngleAxisd axisAngle(rotationMatrix);\n        return axisAngle.angle() * axisAngle.axis();\n    }\n\n    Eigen::Matrix3d rotationVectorToRotationMatrix(const Eigen::Vector3d &rotationVector)\n    {\n        Eigen::AngleAxisd axisAngle(rotationVector.norm(), rotationVector.normalized());\n        return axisAngle.toRotationMatrix();\n    }\n\n    void printHeader(const std::string &txt)\n    {\n        const std::string asterixLine = \"****************************************************************\";\n        std::cout << asterixLine << \"\\n* \" << txt << std::endl << asterixLine << std::endl;\n    }\n} // namespace\n\nint main()\n{\n    try\n    {\n        Zivid::Application zivid;\n\n        std::cout << std::setprecision(4);\n        Eigen::IOFormat matrixFormatRules(4, 0, \", \", \"\\n\", \"[\", \"]\", \"[\", \"]\");\n        Eigen::IOFormat vectorFormatRules(4, 0, \", \", \"\", \"\", \"\", \"[\", \"]\");\n        printHeader(\"This example shows conversions to/from Transformation Matrix\");\n\n        const auto transformationMatrix =\n            getTransformationMatrixFromYAML(std::string(ZIVID_SAMPLE_DATA_DIR) + \"/RobotTransform.yaml\");\n        std::cout << transformationMatrix.matrix().format(matrixFormatRules) << std::endl;\n\n        // Extract Rotation Matrix and Translation Vector from Transformation Matrix\n        std::cout << \"RotationMatrix:\\n\" << transformationMatrix.linear().format(matrixFormatRules) << std::endl;\n        std::cout << \"TranslationVector:\\n\"\n                  << transformationMatrix.translation().format(vectorFormatRules) << std::endl;\n\n        /*\n         * Convert from Rotation Matrix (Zivid) to other representations of orientation (Robot)\n         */\n        printHeader(\"Convert from Zivid (Rotation Matrix) to Robot\");\n        const Eigen::AngleAxisd axisAngle(transformationMatrix.linear());\n        std::cout << \"AxisAngle:\\n\"\n                  << axisAngle.axis().format(vectorFormatRules) << \", \" << axisAngle.angle() << std::endl;\n        const auto rotationVector = rotationMatrixToRotationVector(transformationMatrix.linear());\n        std::cout << \"Rotation Vector:\\n\" << rotationVector.format(vectorFormatRules) << std::endl;\n        const Eigen::Quaterniond quaternion(transformationMatrix.linear());\n        std::cout << \"Quaternion:\\n\" << quaternion.coeffs().format(vectorFormatRules) << std::endl;\n        const auto rpyList = rotationMatrixToRollPitchYawList(transformationMatrix.linear());\n\n        /*\n         * Convert to Rotation Matrix (Zivid) from other representations of orientation (Robot)\n         */\n        printHeader(\"Convert from Robot to Zivid (Rotation Matrix)\");\n        const auto rotationMatrixFromAxisAngle = axisAngle.toRotationMatrix();\n        std::cout << \"Rotation Matrix from Axis Angle:\\n\"\n                  << rotationMatrixFromAxisAngle.format(matrixFormatRules) << std::endl;\n        const auto rotationMatrixFromRotationVector = rotationVectorToRotationMatrix(rotationVector);\n        std::cout << \"Rotation Matrix from Rotation Vector:\\n\"\n                  << rotationMatrixFromRotationVector.format(matrixFormatRules) << std::endl;\n        const auto rotationMatrixFromQuaternion = quaternion.toRotationMatrix();\n        std::cout << \"Rotation Matrix from Quaternion:\\n\"\n                  << rotationMatrixFromQuaternion.format(matrixFormatRules) << std::endl;\n        rollPitchYawListToRotationMatrix(rpyList);\n\n        // Combine Rotation Matrix with Translation Vector to form Transformation Matrix\n        Eigen::Affine3d transformationMatrixFromQuaternion(rotationMatrixFromQuaternion);\n        transformationMatrixFromQuaternion.translation() = transformationMatrix.translation();\n        saveTransformationMatrixToYAML(transformationMatrixFromQuaternion, \"RobotTransformOut.yaml\");\n    }\n\n    catch(const std::exception &e)\n    {\n        std::cerr << \"Error: \" << e.what() << std::endl;\n        std::cout << \"Press enter to exit.\" << std::endl;\n        std::cin.get();\n        return EXIT_FAILURE;\n    }\n}\n", "meta": {"hexsha": "66f3b7ef9a22d890ed3833a4a1ef8210648a8035", "size": 11466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Applications/Advanced/HandEyeCalibration/PoseConversions/PoseConversions.cpp", "max_stars_repo_name": "marvinx97/zivid-cpp-samples", "max_stars_repo_head_hexsha": "7be83661adeb48d28286458b1e01b3dde28e0a43", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-21T03:04:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-21T03:04:34.000Z", "max_issues_repo_path": "source/Applications/Advanced/HandEyeCalibration/PoseConversions/PoseConversions.cpp", "max_issues_repo_name": "marvinx97/zivid-cpp-samples", "max_issues_repo_head_hexsha": "7be83661adeb48d28286458b1e01b3dde28e0a43", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Applications/Advanced/HandEyeCalibration/PoseConversions/PoseConversions.cpp", "max_forks_repo_name": "marvinx97/zivid-cpp-samples", "max_forks_repo_head_hexsha": "7be83661adeb48d28286458b1e01b3dde28e0a43", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7633587786, "max_line_length": 120, "alphanum_fraction": 0.6498342927, "num_tokens": 2533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6367025392011813}}
{"text": "/*\n * Maximum Likelihood estimator using Google's ceres-solver\n *\n */\n\n#include <iomanip>\n#include <fstream>\n#include <iterator>\n#include <ceres/ceres.h>\n#include <glog/logging.h>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\nusing namespace boost::accumulators;\n\n// Log likelihood of normal distribution\ndouble llfunc(double x, double mu, double sigma) {\n    return -log(1 / (sigma * sqrt(2 * M_PI))) +\n           (x - mu) * (x - mu) / (2 * sigma * sigma);\n}\n\n// Manual derivative with respect to mu\ndouble llfunc_div_mu(double x, double mu, double sigma) {\n    return (mu - x) / (sigma * sigma);\n}\n\n// Manual derivative with respect to sigma\ndouble llfunc_div_sigma(double x, double mu, double sigma) {\n    return -(mu * mu - 2 * mu * x - sigma * sigma + x * x) /\n           (sigma * sigma * sigma);\n}\n\n/*\n * Class representing the log likelihood for a certain dataset\n * OpenMP is used to process parts of the dataset in parallel\n */\nclass LogLikelihood : public ceres::FirstOrderFunction {\npublic:\n    LogLikelihood(std::vector<double> input) : data(input) {}\n\n    virtual ~LogLikelihood() {}\n\n    virtual bool Evaluate(const double* parameters, double* cost,\n                          double* gradient) const {\n        const double mu = parameters[0];\n        const double sigma = parameters[1];\n\n        if (mu < -10 || mu > 10 || sigma <= 0) {\n            return false;\n        }\n\n        // Calculate cost\n        double c = 0;\n        #pragma omp parallel for reduction(+ : c)\n        for (size_t i = 0; i < data.size(); i++) {\n            c += llfunc(data[i], mu, sigma);\n        }\n        cost[0] = c;\n\n        // Calculate gradient\n        if (gradient != NULL) {\n            double g0 = 0;\n            double g1 = 0;\n            #pragma omp parallel for reduction(+ : g0, g1)\n            for (size_t i = 0; i < data.size(); i++) {\n                g0 += llfunc_div_mu(data[i], mu, sigma);\n                g1 += llfunc_div_sigma(data[i], mu, sigma);\n            }\n            gradient[0] = g0;\n            gradient[1] = g1;\n        }\n        return true;\n    }\n\n    virtual int NumParameters() const { return 2; }\n\nprivate:\n    std::vector<double> data;\n};\n\nint main(int argc, char** argv) {\n    google::InitGoogleLogging(argv[0]);\n\n    double parameters[2] = {8, 8.0};\n\n    // Generate data\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::normal_distribution<> dis(0, 1);\n    std::vector<double> input;\n    std::cout << \"Generating data...\" << std::endl;\n    for (int i = 0; i < 100000; i++) {\n        input.push_back(dis(gen));\n    }\n\n    // Perform fit\n    std::cout << \"Running fit...\" << std::endl;\n    ceres::GradientProblemSolver::Options options;\n    options.minimizer_progress_to_stdout = true;\n    options.max_num_iterations = 300;\n    options.function_tolerance = 1e-15;\n\n    ceres::GradientProblemSolver::Summary summary;\n    ceres::GradientProblem problem(new LogLikelihood(input));\n    ceres::Solve(options, problem, parameters, &summary);\n\n    //std::cout << summary.FullReport() << std::endl;\n\n    std::cout << std::setprecision(16)\n              << \"Final    mu: \" << parameters[0] << \" sigma: \" << parameters[1]\n              << std::endl;\n\n    // Compare with analytic estimators (mean and std)\n    accumulator_set<double, features<tag::mean, tag::variance>> acc;\n    for_each(input.begin(), input.end(), [&acc](double x) { acc(x); });\n\n    std::cout << std::setprecision(16)\n              << \"Analytic mu: \" << mean(acc) << \" sigma: \" << sqrt(variance(acc))\n              << std::endl;\n\n    std::ofstream data(\"./data.txt\");\n    std::ostream_iterator<double> output_iterator(data, \"\\n\");\n    std::copy(input.begin(), input.end(), output_iterator);\n\n    std::ofstream params(\"./params.txt\");\n    params << parameters[0] << std::endl;\n    params << parameters[1] << std::endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "8beebd9a35fee4f9669fcd1b72674169904a9ff3", "size": 3887, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mle.cc", "max_stars_repo_name": "ibab/ceres-mle", "max_stars_repo_head_hexsha": "28d4d967c4e05c69d5e998935a2d5c7f8053a411", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-07-31T02:50:25.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-31T02:50:25.000Z", "max_issues_repo_path": "mle.cc", "max_issues_repo_name": "ibab/ceres-mle", "max_issues_repo_head_hexsha": "28d4d967c4e05c69d5e998935a2d5c7f8053a411", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mle.cc", "max_forks_repo_name": "ibab/ceres-mle", "max_forks_repo_head_hexsha": "28d4d967c4e05c69d5e998935a2d5c7f8053a411", "max_forks_repo_licenses": ["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.446969697, "max_line_length": 82, "alphanum_fraction": 0.5873424235, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563823, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6367025258995699}}
{"text": "#include <vector>\n#include \"boost/random.hpp\"\n#include \"boost/generator_iterator.hpp\"\n#include <boost/random/normal_distribution.hpp>\n#include <algorithm>\n\ntypedef boost::mt19937 RNGType; ///< mersenne twister generator\n\nint main() {\n    RNGType rng;\n    boost::normal_distribution<> rdist(1.0,0.5); /**< normal distribution\n                           with mean of 1.0 and standard deviation of 0.5 */\n\n    boost::variate_generator< RNGType, boost::normal_distribution<> >\n                    get_rand(rng, rdist);\n\n    std::vector<double> v(1000);\n    generate(v.begin(),v.end(),get_rand);\n    return 0;\n}\n", "meta": {"hexsha": "70e0a34fdb74a4d018d8f81657d843254b9428a6", "size": 607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/random-numbers-3.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-29T20:08:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:16:05.000Z", "max_issues_repo_path": "lang/C++/random-numbers-3.cpp", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/C++/random-numbers-3.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-13T04:19:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T04:19:31.000Z", "avg_line_length": 28.9047619048, "max_line_length": 76, "alphanum_fraction": 0.6573311367, "num_tokens": 147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6365621116514066}}
{"text": "#pragma once\n\n#include <iostream>\n\n#include <Eigen/Dense>\n\nnamespace dg {\n\nusing Real = double;\n\nusing Matrix2 = Eigen::Matrix<Real,2,2>;\nusing Matrix3 = Eigen::Matrix<Real,3,3>;\nusing Matrix4 = Eigen::Matrix<Real,4,4>;\n\nusing Vector2 = Eigen::Matrix<Real,2,1>;\nusing Vector3 = Eigen::Matrix<Real,3,1>;\nusing Vector4 = Eigen::Matrix<Real,4,1>;\n\nusing Matrix2f = Eigen::Matrix<float,2,2>;\nusing Matrix3f = Eigen::Matrix<float,3,3>;\nusing Matrix4f = Eigen::Matrix<float,4,4>;\n\nusing Vector2f = Eigen::Matrix<float,2,1>;\nusing Vector3f = Eigen::Matrix<float,3,1>;\nusing Vector4f = Eigen::Matrix<float,4,1>;\n\n\n\nusing Quaternion = Eigen::Quaternion<Real>;\nusing AngleAxis  = Eigen::AngleAxis<Real>;\n\nusing Quaternionf = Eigen::Quaternion<float>;\nusing AngleAxisf  = Eigen::AngleAxis<float>;\n\nusing Transform  = Matrix4;\nusing Transformf = Matrix4f;\n\nnamespace math {\n\n\ninline Transform transformFromScaleRotTrans(const Vector3& scale, const Quaternion& q, const Vector3& t)\n{\n    // Ordering:\n    //    1. Scale\n    //    2. Rotate\n    //    3. Translate\n\n    Transform m;\n\n    Matrix3 rot3x3 = q.toRotationMatrix();\n\n    m(0,0) = scale.x() * rot3x3(0,0); m(0,1) = scale.y() * rot3x3(0,1); m(0,2) = scale.z() * rot3x3(0,2); m(0,3) = t.x();\n    m(1,0) = scale.x() * rot3x3(1,0); m(1,1) = scale.y() * rot3x3(1,1); m(1,2) = scale.z() * rot3x3(1,2); m(1,3) = t.y();\n    m(2,0) = scale.x() * rot3x3(2,0); m(2,1) = scale.y() * rot3x3(2,1); m(2,2) = scale.z() * rot3x3(2,2); m(2,3) = t.z();\n    m(3,0) = 0; m(3,1) = 0; m(3,2) = 0; m(3,3) = 1;\n\n    return m;\n}\n\n} }\n\n", "meta": {"hexsha": "e0ebf325f11b088fbfbaf039e58acffcd8e22458", "size": 1554, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dg/core/math.hpp", "max_stars_repo_name": "epicodic/diligent-graph", "max_stars_repo_head_hexsha": "64325a17498fa6b913bffadfc1a43108c81dd7b0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-08-25T07:54:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T20:05:06.000Z", "max_issues_repo_path": "include/dg/core/math.hpp", "max_issues_repo_name": "epicodic/diligent-graph", "max_issues_repo_head_hexsha": "64325a17498fa6b913bffadfc1a43108c81dd7b0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dg/core/math.hpp", "max_forks_repo_name": "epicodic/diligent-graph", "max_forks_repo_head_hexsha": "64325a17498fa6b913bffadfc1a43108c81dd7b0", "max_forks_repo_licenses": ["Apache-2.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.064516129, "max_line_length": 121, "alphanum_fraction": 0.6241956242, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6365621060702822}}
{"text": "#include \"Parameterization.h\"\n\n#include <unordered_set>\n\n#include <Eigen/Eigen>\n\n#include <iostream>\n\nnamespace Chaf\n{\n\tstruct pair_hash {\n\t\ttemplate <class T1, class T2>\n\t\tstd::size_t operator () (const std::pair<T1, T2>& p) const {\n\t\t\tauto h1 = std::hash<T1>{}(p.first);\n\t\t\tauto h2 = std::hash<T2>{}(p.second);\n\t\t\treturn h1 ^ h2;\n\t\t}\n\t};\n\n\tRef<TriMesh> Parameterization::parameterize(const Ref<TriMesh>& mesh, ParameterizationMethod method)\n\t{\n\t\tstd::vector<Vertex> raw_vertices = mesh->m_Vertices;\n\t\tstd::vector<uint32_t> raw_indices = mesh->m_Indices;\n\n\t\tstd::vector<Vertex> vertices;\n\t\tstd::vector<uint32_t> indices;\n\n\t\t//optimize mesh\n\t\tstd::unordered_map<glm::vec3, size_t> vertices_map;\n\t\tfor (auto& v : raw_vertices)\n\t\t{\n\t\t\tvertices_map[v.m_Position] = 0;\n\t\t}\n\n\t\tfor (auto& [key, index] : vertices_map)\n\t\t{\n\t\t\tindex = vertices.size();\n\t\t\tVertex v = {};\n\t\t\tv.m_Position = key;\n\t\t\tvertices.push_back(v);\n\t\t}\n\n\t\tfor (auto& idx : raw_indices)\n\t\t{\n\t\t\tindices.push_back(vertices_map[raw_vertices[idx].m_Position]);\n\t\t}\n\n\t\tstd::vector<std::unordered_set<size_t>> neigborhood(vertices.size());\n\t\tstd::unordered_map<std::pair<size_t, size_t>, size_t, pair_hash> triangle_map;\n\t\tfor (size_t i = 0; i < indices.size(); i += 3)\n\t\t{\n\t\t\tneigborhood[indices[i]].insert(indices[i + 1]);\n\t\t\tneigborhood[indices[i + 1]].insert(indices[i + 2]);\n\t\t\tneigborhood[indices[i + 2]].insert(indices[i]);\n\t\t\ttriangle_map[std::make_pair(indices[i], indices[i + 1])] = i;\n\t\t\ttriangle_map[std::make_pair(indices[i + 1], indices[i + 2])] = i;\n\t\t\ttriangle_map[std::make_pair(indices[i + 2], indices[i])] = i;\n\t\t}\n\n\t\tauto& boundaries = findBoundary(vertices, indices);\n\t\tif (boundaries.empty())\n\t\t{\n\t\t\treturn mesh;\n\t\t}\n\t\tauto& boundary = boundaries[0];\n\n\t\tEigen::SparseMatrix<float> Laplace_matrix(vertices.size(), vertices.size());\n\t\tEigen::MatrixXf b(vertices.size(), 2);\n\n\t\tLaplace_matrix.setZero();\n\t\tb.setZero();\n\n\t\tstd::vector<Eigen::Triplet<float>> Lij;\n\n\t\tfor (size_t i = 0; i < vertices.size(); i++)\n\t\t{\n\t\t\tLij.push_back(Eigen::Triplet<float>(i, i, 1.f));\n\n\t\t\tif (std::find(boundary.begin(), boundary.end(), i) == boundary.end())\n\t\t\t{\n\t\t\t\tstd::unordered_map<size_t, float> wi;\n\t\t\t\tfor (auto& idx : neigborhood[i])\n\t\t\t\t{\n\t\t\t\t\tif (method == ParameterizationMethod::Uniform)\n\t\t\t\t\t{\n\t\t\t\t\t\twi[idx] = 1.f;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tsize_t t1 = triangle_map[std::make_pair(i, idx)];\n\t\t\t\t\t\tsize_t t2 = triangle_map[std::make_pair(idx, i)];\n\n\t\t\t\t\t\tglm::vec3 v = vertices[i].m_Position;\n\t\t\t\t\t\tglm::vec3 vi = vertices[idx].m_Position;\n\n\t\t\t\t\t\tglm::vec3 vi1, vi2;\n\n\t\t\t\t\t\tfor (size_t k = 0; k < 3; k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (vertices[indices[t1 + k]].m_Position != v && vertices[indices[t1 + k]].m_Position != vi)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvi1 = vertices[indices[t1 + k]].m_Position;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (vertices[indices[t2 + k]].m_Position != v && vertices[indices[t2 + k]].m_Position != vi)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvi2 = vertices[indices[t2 + k]].m_Position;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (method == ParameterizationMethod::WP)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat r = glm::length(v - vi);\n\t\t\t\t\t\t\tfloat cos1 = glm::dot(v - vi, vi1 - vi);\n\t\t\t\t\t\t\tfloat cos2 = glm::dot(v - vi, vi2 - vi);\n\n\t\t\t\t\t\t\tfloat cot1 = cos1 / (sqrtf(1 - cos1 * cos1));\n\t\t\t\t\t\t\tfloat cot2 = cos2 / (sqrtf(1 - cos2 * cos2));\n\n\t\t\t\t\t\t\twi[idx] = (cot1 + cot2) / (r * r);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (method == ParameterizationMethod::MV)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat r = glm::length(v - vi);\n\t\t\t\t\t\t\tfloat cos1 = glm::dot(v - vi, v - vi1);\n\t\t\t\t\t\t\tfloat cos2 = glm::dot(v - vi, v - vi2);\n\t\t\t\t\t\t\tfloat alpha1 = acosf(cos1);\n\t\t\t\t\t\t\tfloat alpha2 = acosf(cos2);\n\n\t\t\t\t\t\t\twi[idx] = (tanf(alpha1 / 2.f) + tanf(alpha2 / 2.f)) / r;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (method == ParameterizationMethod::DH)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfloat cos1 = glm::dot(vi1 - v, vi1 - vi);\n\t\t\t\t\t\t\tfloat cos2 = glm::dot(vi2 - v, vi2 - vi);\n\t\t\t\t\t\t\tfloat alpha1 = acosf(cos1);\n\t\t\t\t\t\t\tfloat alpha2 = acosf(cos2);\n\n\t\t\t\t\t\t\twi[idx] = (1.f / tanf(alpha1) + tanf(1.f / alpha2));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfloat wi_sum = 0.f;\n\t\t\t\tfor (auto& [idx, w] : wi)\n\t\t\t\t{\n\t\t\t\t\twi_sum += w;\n\t\t\t\t}\n\t\t\t\tfor (auto& [idx, w] : wi)\n\t\t\t\t{\n\t\t\t\t\tLij.push_back(Eigen::Triplet<float>(i, idx, -w / wi_sum));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (uint32_t i = 0; i < boundary.size(); i++)\n\t\t{\n\t\t\tb(boundary[i], 0) = std::cos((float)i * glm::pi<float>() * 2.f / static_cast<float>(boundary.size()));\n\t\t\tb(boundary[i], 1) = std::sin((float)i * glm::pi<float>() * 2.f / static_cast<float>(boundary.size()));\n\t\t}\n\n\t\tLaplace_matrix.setFromTriplets(Lij.begin(), Lij.end());\n\n\t\tEigen::SparseLU<Eigen::SparseMatrix<float>> solver;\n\n\t\tsolver.compute(Laplace_matrix);\n\n\t\tEigen::MatrixXf result = solver.solve(b);\n\n\t\tstd::vector<Vertex> new_vertices(vertices.size());\n\n\t\tfor (size_t i = 0; i < vertices.size(); i++)\n\t\t{\n\t\t\tnew_vertices[i].m_Position.x = result(i, 0);\n\t\t\tnew_vertices[i].m_Position.y = result(i, 1);\n\t\t\tnew_vertices[i].m_Position.z = 0.f;\n\t\t}\n\n\t\treturn CreateRef<TriMesh>(std::move(new_vertices), std::move(indices));\n\t}\n\n\tstd::vector<std::vector<size_t>> Parameterization::findBoundary(const std::vector<Vertex>& vertices, const std::vector<uint32_t>& indices)\n\t{\n\t\tstd::vector<std::vector<size_t>> mesh_graph(vertices.size(), std::vector<size_t>(vertices.size()));\n\t\tfor (auto& g : mesh_graph)\n\t\t{\n\t\t\tstd::fill(g.begin(), g.end(), 0);\n\t\t}\n\n\t\tfor (size_t i = 0; i < indices.size(); i += 3)\n\t\t{\n\t\t\tmesh_graph[indices[i]][indices[i + 1]]++;\n\t\t\tmesh_graph[indices[i + 1]][indices[i]] ++;\n\t\t\tmesh_graph[indices[i + 1]][indices[i + 2]] ++;\n\t\t\tmesh_graph[indices[i + 2]][indices[i + 1]] ++;\n\t\t\tmesh_graph[indices[i + 2]][indices[i]]++;\n\t\t\tmesh_graph[indices[i]][indices[i + 2]] ++;\n\t\t}\n\n\t\tstd::unordered_set<size_t> found;\n\t\tstd::vector<std::vector<size_t>> boundaries;\n\n\t\tfor (size_t i = 0; i < vertices.size(); i++)\n\t\t{\n\t\t\tsize_t currect_vertex = i;\n\t\t\tstd::vector<size_t> boundary;\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\tbool has = false;\n\t\t\t\tfor (size_t j = 0; j < vertices.size(); j++)\n\t\t\t\t{\n\t\t\t\t\tif (j != currect_vertex && mesh_graph[currect_vertex][j] == 1 && found.find(j) == found.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tfound.insert(j);\n\t\t\t\t\t\tboundary.push_back(j);\n\t\t\t\t\t\tcurrect_vertex = j;\n\t\t\t\t\t\thas = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (currect_vertex == i || !has)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!boundary.empty())\n\t\t\t{\n\t\t\t\tboundaries.push_back(boundary);\n\t\t\t}\n\t\t}\n\n\t\tstd::sort(boundaries.begin(), boundaries.end(), [](const std::vector<size_t>& lhs, const std::vector<size_t>& rhs) {return lhs.size() > rhs.size(); });\n\t\treturn boundaries;\n\t}\n}", "meta": {"hexsha": "2b7647a10c6c3b7d589e5e682bcbf82a8e5efcf7", "size": 6410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homework/Homeworks/Homework11/Parameterization.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/Homework11/Parameterization.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/Homework11/Parameterization.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": 27.6293103448, "max_line_length": 153, "alphanum_fraction": 0.5914196568, "num_tokens": 2032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357632379241, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6365078893573605}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2018 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/distance_functions.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Points_off_io.h>\n\n#include <gudhi/Miniball.hpp>\n\n#include <boost/program_options.hpp>\n\n#include <string>\n#include <vector>\n#include <limits>   // infinity\n#include <utility>  // for pair\n#include <map>\n\n// ----------------------------------------------------------------------------\n// rips_persistence_step_by_step is an example of each step that is required to\n// build a Rips over a Simplex_tree. Please refer to rips_persistence to see\n// how to do the same thing with the Rips_complex wrapper for less detailed\n// steps.\n// ----------------------------------------------------------------------------\n\n// Types definition\nusing Simplex_tree = Gudhi::Simplex_tree<>;\nusing Simplex_handle = Simplex_tree::Simplex_handle;\nusing Filtration_value = Simplex_tree::Filtration_value;\nusing Point = std::vector<double>;\nusing Points_off_reader = Gudhi::Points_off_reader<Point>;\nusing Proximity_graph = Gudhi::Proximity_graph<Simplex_tree>;\n\nclass Cech_blocker {\n private:\n  using Point_cloud = std::vector<Point>;\n  using Point_iterator = Point_cloud::const_iterator;\n  using Coordinate_iterator = Point::const_iterator;\n  using Min_sphere = Gudhi::Miniball::Miniball<Gudhi::Miniball::CoordAccessor<Point_iterator, Coordinate_iterator>>;\n\n public:\n  bool operator()(Simplex_handle sh) {\n    std::vector<Point> points;\n    for (auto vertex : simplex_tree_.simplex_vertex_range(sh)) {\n      points.push_back(point_cloud_[vertex]);\n#ifdef DEBUG_TRACES\n      std::clog << \"#(\" << vertex << \")#\";\n#endif  // DEBUG_TRACES\n    }\n    Filtration_value radius = Gudhi::Minimal_enclosing_ball_radius()(points);\n#ifdef DEBUG_TRACES\n    std::clog << \"radius = \" << radius << \" - \" << (radius > max_radius_) << std::endl;\n#endif  // DEBUG_TRACES\n    simplex_tree_.assign_filtration(sh, radius);\n    return (radius > max_radius_);\n  }\n  Cech_blocker(Simplex_tree& simplex_tree, Filtration_value max_radius, const std::vector<Point>& point_cloud)\n      : simplex_tree_(simplex_tree), max_radius_(max_radius), point_cloud_(point_cloud) {\n    dimension_ = point_cloud_[0].size();\n  }\n\n private:\n  Simplex_tree simplex_tree_;\n  Filtration_value max_radius_;\n  std::vector<Point> point_cloud_;\n  int dimension_;\n};\n\nvoid program_options(int argc, char* argv[], std::string& off_file_points, Filtration_value& max_radius, int& dim_max);\n\nint main(int argc, char* argv[]) {\n  std::string off_file_points;\n  Filtration_value max_radius;\n  int dim_max;\n\n  program_options(argc, argv, off_file_points, max_radius, dim_max);\n\n  // Extract the points from the file filepoints\n  Points_off_reader off_reader(off_file_points);\n\n  // Compute the proximity graph of the points\n  Proximity_graph prox_graph = Gudhi::compute_proximity_graph<Simplex_tree>(off_reader.get_point_cloud(), max_radius,\n                                                                            Gudhi::Minimal_enclosing_ball_radius());\n\n  // Construct the Rips complex in a Simplex Tree\n  Simplex_tree st;\n  // insert the proximity graph in the simplex tree\n  st.insert_graph(prox_graph);\n  // expand the graph until dimension dim_max\n  st.expansion_with_blockers(dim_max, Cech_blocker(st, max_radius, off_reader.get_point_cloud()));\n\n  std::clog << \"The complex contains \" << st.num_simplices() << \" simplices \\n\";\n  std::clog << \"   and has dimension \" << st.dimension() << \" \\n\";\n\n  // Sort the simplices in the order of the filtration\n  st.initialize_filtration();\n\n#if DEBUG_TRACES\n  std::clog << \"********************************************************************\\n\";\n  std::clog << \"* The complex contains \" << st.num_simplices() << \" simplices - dimension=\" << st.dimension() << \"\\n\";\n  std::clog << \"* Iterator on Simplices in the filtration, with [filtration value]:\\n\";\n  for (auto f_simplex : st.filtration_simplex_range()) {\n    std::clog << \"   \"\n              << \"[\" << st.filtration(f_simplex) << \"] \";\n    for (auto vertex : st.simplex_vertex_range(f_simplex)) {\n      std::clog << static_cast<int>(vertex) << \" \";\n    }\n    std::clog << std::endl;\n  }\n#endif  // DEBUG_TRACES\n\n  return 0;\n}\n\nvoid program_options(int argc, char* argv[], std::string& off_file_points, Filtration_value& max_radius, int& dim_max) {\n  namespace po = boost::program_options;\n  po::options_description hidden(\"Hidden options\");\n  hidden.add_options()(\"input-file\", po::value<std::string>(&off_file_points),\n                       \"Name of an OFF file containing a point set.\\n\");\n\n  po::options_description visible(\"Allowed options\", 100);\n  visible.add_options()(\"help,h\", \"produce help message\")(\n      \"max-radius,r\",\n      po::value<Filtration_value>(&max_radius)->default_value(std::numeric_limits<Filtration_value>::infinity()),\n      \"Maximal length of an edge for the Rips complex construction.\")(\n      \"cpx-dimension,d\", po::value<int>(&dim_max)->default_value(1),\n      \"Maximal dimension of the Rips complex we want to compute.\");\n\n  po::positional_options_description pos;\n  pos.add(\"input-file\", 1);\n\n  po::options_description all;\n  all.add(visible).add(hidden);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(all).positional(pos).run(), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") || !vm.count(\"input-file\")) {\n    std::clog << std::endl;\n    std::clog << \"Construct a Cech complex defined on a set of input points.\\n \\n\";\n\n    std::clog << \"Usage: \" << argv[0] << \" [options] input-file\" << std::endl << std::endl;\n    std::clog << visible << std::endl;\n    exit(-1);\n  }\n}\n", "meta": {"hexsha": "f59f02938ecfbb98da2c0fb6c0f8aedb3d9c7f72", "size": 5955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Cech_complex/example/cech_complex_step_by_step.cpp", "max_stars_repo_name": "m0baxter/gudhi-devel", "max_stars_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Cech_complex/example/cech_complex_step_by_step.cpp", "max_issues_repo_name": "m0baxter/gudhi-devel", "max_issues_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Cech_complex/example/cech_complex_step_by_step.cpp", "max_forks_repo_name": "m0baxter/gudhi-devel", "max_forks_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 38.4193548387, "max_line_length": 120, "alphanum_fraction": 0.6678421495, "num_tokens": 1493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7341195210831258, "lm_q1q2_score": 0.6365078817924208}}
{"text": "//#define DEBUG 1\n\n#include <iostream>\n#include <iomanip>\n//#include <cmath>\n#include \"Hubbard2D.hpp\"\n#ifdef USE_SPECTRA\n#include <MatOp/SparseGenMatProd.h>\n#include <SymEigsSolver.h>\n#endif\n\n#include <boost/random.hpp>\n#include <boost/limits.hpp>\n#include <ietl/interface/eigen3.h>\n#include <ietl/vectorspace.h>\n#include <ietl/lanczos.h>\n\nint main(int argc, const char * argv[]) {\n  \n  std::ofstream outfile;\n  outfile.open(\"dope_energies.dat\");\n  outfile << std::setprecision(9);\n  int Lx=4,Ly=4; //dimensions of lattice\n  for(int ne=1;ne<6;ne++){//number of electrons\n    for(int U=1;U<=8;U++){\n      //int ne=2; //# of electrons\n      //int U=4;\n      HubbardModel2D H(ne,ne,1,U);\n      std::cout << \"2D \"<<Lx<<\"x\"<<Ly<<\" Hubbard model with \"\n      << ne <<\" up/down electrons and U/t=\"<<U<<std::endl;\n      H.makeBasis();\n      std::cout <<\"Made Basis: \" << H.getBasis()->size()<< std::endl;\n\n      H.buildHubbard2D();\n      std::cout <<\"Built Matrix\" << std::endl;\n      SpMat Hmat = *(H.getH());\n      std::cout << \"# of non-zero elements:\"<<(H.getH())->nonZeros() << std::endl;\n      H.getH()->makeCompressed();\n\n      //Exact Diag with specrta\n#ifdef USE_SPECTRA\n      // Construct matrix operation object using the wrapper class SparseGenMatProd\n      using wrapper_t =Spectra::SparseGenMatProd<double,Eigen::ColMajor,long>;\n      wrapper_t op(Hmat);\n      \n      // Construct eigen solver object, requesting the largest three eigenvalues\n      Spectra::SymEigsSolver< double, Spectra::SMALLEST_ALGE , wrapper_t > eigs(&op, 1, 6);\n      // Initialize and compute\n      eigs.init();\n      int nconv = eigs.compute();\n      \n#ifdef DEBUG\n      if(eigs.info() != Spectra::SUCCESSFUL)\n          std::cout <<\"Warning something failed \" <<nconv << std::endl;\n#endif\n      \n      std::cout<< \"E0=\"<<eigs.eigenvalues()[0]<<std::endl;\n#else\n      typedef boost::lagged_fibonacci607 Gen;\n      Gen mygen;\n      mygen.seed(0);\n      \n      typedef Eigen::SparseMatrix<double,Eigen::RowMajor,long> Matrix;\n      typedef Eigen::VectorXd Vector;\n      typedef ietl::vectorspace<Vector> Vecspace;\n       \n       \n       \n      // Creation of an iteration object:\n      int max_iter = 10*H.getBasis()->size();\n      double rel_tol = 500*std::numeric_limits<double>::epsilon();\n      double abs_tol = std::pow(std::numeric_limits<double>::epsilon(),2./3);\n      int n_lowest_eigenval = 1;\n      std::vector<double> eigen;\n      std::vector<double> err;\n      std::vector<int> multiplicity;\n\n      //std::vector<double> groundStates;\n\n      Vecspace vec(Hmat.cols());\n      ietl::lanczos<Matrix,Vecspace> lanczos(Hmat,vec);\n      ietl::lanczos_iteration_nlowest<double>\n      iter(max_iter, n_lowest_eigenval, rel_tol, abs_tol);\n      std::cout << \"lanczos\" << std::endl;\n      try{\n        lanczos.calculate_eigenvalues(iter,mygen);\n        eigen = lanczos.eigenvalues();\n        err = lanczos.errors();\n        multiplicity = lanczos.multiplicities();\n        std::cout<<\"number of iterations: \"<<iter.iterations()<<\"\\n\";\n        //groundStates.push_back(eigen[0]);\n        outfile<<ne <<\" \" <<U<<\" \" <<eigen[0]<<std::endl;\n      }\n      catch (std::runtime_error& e) {\n        std::cout << e.what() << \"\\n\";\n      }\n      std::cout << \"#        eigenvalue            error         multiplicity\\n\";\n      for (int i=0;i<10;++i)\n        std::cout << i << \"\\t\" << eigen[i] << \"\\t\" << err[i] << \"\\t\"\n        << multiplicity[i] << \"\\n\";\n\n      /*\n      // call of eigenvectors function follows:\n      std::cout << \"\\nEigen vectors computations for the lowest eigenvalue:\\n\\n\";\n      std::vector<double>::iterator start = eigen.begin();\n      std::vector<double>::iterator end = eigen.begin()+1;\n      std::vector<Vector> eigenvectors; // for storing the eigen vectors.\n      ietl::Info<double> info; // (m1, m2, ma, eigenvalue, residualm, status).\n\n      try {\n        lanczos.eigenvectors(start,end,std::back_inserter(eigenvectors),info,mygen,max_iter);\n      }\n      catch (std::runtime_error& e) {\n        std::cout << e.what() << \"\\n\";\n      }\n\n      for(int i=0;i<10;i++){\n        std::cout << eigenvectors[0](i)<<std::endl;\n      }\n      std::cout << \" Information about the eigenvector computations:\\n\\n\";\n      for(int i = 0; i < info.size(); i++) {\n        std::cout << \" m1(\" << i+1 << \"): \" << info.m1(i) << \", m2(\" << i+1 << \"): \"\n        << info.m2(i) << \", ma(\" << i+1 << \"): \" << info.ma(i) << \" eigenvalue(\"\n        << i+1 << \"): \" << info.eigenvalue(i) << \" residual(\" << i+1 << \"): \"\n        << info.residual(i) << \" error_info(\" << i+1 << \"): \"\n        << info.error_info(i) << \"\\n\\n\";\n      }\n      */\n#endif\n    }//U\n  }//ne\n  outfile.close();\n  return 0;\n}\n", "meta": {"hexsha": "e2c39725b66b8c08f3ad71b7bbe2169f9db4230f", "size": 4669, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main_mult.cpp", "max_stars_repo_name": "qftphys/A-Slow-Exact-Diagonalization-for-the-1D-2D-Hubbard-Model", "max_stars_repo_head_hexsha": "c8352681036e93fb83a56374c639075fea72e3af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-05-26T13:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T06:58:54.000Z", "max_issues_repo_path": "main_mult.cpp", "max_issues_repo_name": "qftphys/A-Slow-Exact-Diagonalization-for-the-1D-2D-Hubbard-Model", "max_issues_repo_head_hexsha": "c8352681036e93fb83a56374c639075fea72e3af", "max_issues_repo_licenses": ["MIT"], "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_mult.cpp", "max_forks_repo_name": "qftphys/A-Slow-Exact-Diagonalization-for-the-1D-2D-Hubbard-Model", "max_forks_repo_head_hexsha": "c8352681036e93fb83a56374c639075fea72e3af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-08-08T04:17:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-13T08:13:10.000Z", "avg_line_length": 34.5851851852, "max_line_length": 93, "alphanum_fraction": 0.5752837867, "num_tokens": 1325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.636507876747003}}
{"text": "#include <igl/directed_edge_orientations.h>\r\n#include <igl/directed_edge_parents.h>\r\n#include <igl/forward_kinematics.h>\r\n#include <igl/PI.h>\r\n#include <igl/lbs_matrix.h>\r\n#include <igl/deform_skeleton.h>\r\n#include <igl/dqs.h>\r\n#include <igl/readDMAT.h>\r\n#include <igl/readOBJ.h>\r\n#include <igl/readTGF.h>\r\n#include <igl/opengl/glfw/Viewer.h>\r\n\r\n#include <Eigen/Geometry>\r\n#include <Eigen/StdVector>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <iostream>\r\n\r\n#include \"tutorial_shared_path.h\"\r\n\r\ntypedef \r\n  std::vector<Eigen::Quaterniond,Eigen::aligned_allocator<Eigen::Quaterniond> >\r\n  RotationList;\r\n\r\nconst Eigen::RowVector3d sea_green(70./255.,252./255.,167./255.);\r\nEigen::MatrixXd V,W,C,U,M;\r\nEigen::MatrixXi F,BE;\r\nEigen::VectorXi P;\r\nstd::vector<RotationList > poses;\r\ndouble anim_t = 0.0;\r\ndouble anim_t_dir = 0.015;\r\nbool use_dqs = false;\r\nbool recompute = true;\r\n\r\nbool pre_draw(igl::opengl::glfw::Viewer & viewer)\r\n{\r\n  using namespace Eigen;\r\n  using namespace std;\r\n  if(recompute)\r\n  {\r\n    // Find pose interval\r\n    const int begin = (int)floor(anim_t)%poses.size();\r\n    const int end = (int)(floor(anim_t)+1)%poses.size();\r\n    const double t = anim_t - floor(anim_t);\r\n\r\n    // Interpolate pose and identity\r\n    RotationList anim_pose(poses[begin].size());\r\n    for(int e = 0;e<poses[begin].size();e++)\r\n    {\r\n      anim_pose[e] = poses[begin][e].slerp(t,poses[end][e]);\r\n    }\r\n    // Propagate relative rotations via FK to retrieve absolute transformations\r\n    RotationList vQ;\r\n    vector<Vector3d> vT;\r\n    igl::forward_kinematics(C,BE,P,anim_pose,vQ,vT);\r\n    const int dim = C.cols();\r\n    MatrixXd T(BE.rows()*(dim+1),dim);\r\n    for(int e = 0;e<BE.rows();e++)\r\n    {\r\n      Affine3d a = Affine3d::Identity();\r\n      a.translate(vT[e]);\r\n      a.rotate(vQ[e]);\r\n      T.block(e*(dim+1),0,dim+1,dim) =\r\n        a.matrix().transpose().block(0,0,dim+1,dim);\r\n    }\r\n    // Compute deformation via LBS as matrix multiplication\r\n    if(use_dqs)\r\n    {\r\n      igl::dqs(V,W,vQ,vT,U);\r\n    }else\r\n    {\r\n      U = M*T;\r\n    }\r\n\r\n    // Also deform skeleton edges\r\n    MatrixXd CT;\r\n    MatrixXi BET;\r\n    igl::deform_skeleton(C,BE,T,CT,BET);\r\n    \r\n    viewer.data().set_vertices(U);\r\n    viewer.data().set_edges(CT,BET,sea_green);\r\n    viewer.data().compute_normals();\r\n    if(viewer.core().is_animating)\r\n    {\r\n      anim_t += anim_t_dir;\r\n    }\r\n    else\r\n    {\r\n      recompute=false;\r\n    }\r\n  }\r\n  return false;\r\n}\r\n\r\nbool key_down(igl::opengl::glfw::Viewer &viewer, unsigned char key, int mods)\r\n{\r\n  recompute = true;\r\n  switch(key)\r\n  {\r\n    case 'D':\r\n    case 'd':\r\n      use_dqs = !use_dqs;\r\n      return true;\r\n    case ' ':\r\n      viewer.core().is_animating = !viewer.core().is_animating;\r\n      return true;\r\n  }\r\n  return false;\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n  using namespace Eigen;\r\n  using namespace std;\r\n  igl::readOBJ(TUTORIAL_SHARED_PATH \"/arm.obj\",V,F);\r\n  U=V;\r\n  igl::readTGF(TUTORIAL_SHARED_PATH \"/arm.tgf\",C,BE);\r\n  // retrieve parents for forward kinematics\r\n  igl::directed_edge_parents(BE,P);\r\n  RotationList rest_pose;\r\n  igl::directed_edge_orientations(C,BE,rest_pose);\r\n  poses.resize(4,RotationList(4,Quaterniond::Identity()));\r\n  // poses[1] // twist\r\n  const Quaterniond twist(AngleAxisd(igl::PI,Vector3d(1,0,0)));\r\n  poses[1][2] = rest_pose[2]*twist*rest_pose[2].conjugate();\r\n  const Quaterniond bend(AngleAxisd(-igl::PI*0.7,Vector3d(0,0,1)));\r\n  poses[3][2] = rest_pose[2]*bend*rest_pose[2].conjugate();\r\n\r\n  igl::readDMAT(TUTORIAL_SHARED_PATH \"/arm-weights.dmat\",W);\r\n  igl::lbs_matrix(V,W,M);\r\n\r\n  // Plot the mesh with pseudocolors\r\n  igl::opengl::glfw::Viewer viewer;\r\n  viewer.data().set_mesh(U, F);\r\n  viewer.data().set_edges(C,BE,sea_green);\r\n  viewer.data().show_lines = false;\r\n  viewer.data().show_overlay_depth = false;\r\n  viewer.data().line_width = 1;\r\n  viewer.core().trackball_angle.normalize();\r\n  viewer.callback_pre_draw = &pre_draw;\r\n  viewer.callback_key_down = &key_down;\r\n  viewer.core().is_animating = false;\r\n  viewer.core().camera_zoom = 2.5;\r\n  viewer.core().animation_max_fps = 30.;\r\n  cout<<\"Press [d] to toggle between LBS and DQS\"<<endl<<\r\n    \"Press [space] to toggle animation\"<<endl;\r\n  viewer.launch();\r\n}\r\n", "meta": {"hexsha": "432ad0ef840207a8eed9922e8c76ccddd80608a9", "size": 4223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdf-net/lib/submodules/libigl/tutorial/404_DualQuaternionSkinning/main.cpp", "max_stars_repo_name": "hardikk13/nglod", "max_stars_repo_head_hexsha": "6c6c66ce1b39c5a3515cafc290ec903ae90b506e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdf-net/lib/submodules/libigl/tutorial/404_DualQuaternionSkinning/main.cpp", "max_issues_repo_name": "hardikk13/nglod", "max_issues_repo_head_hexsha": "6c6c66ce1b39c5a3515cafc290ec903ae90b506e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdf-net/lib/submodules/libigl/tutorial/404_DualQuaternionSkinning/main.cpp", "max_forks_repo_name": "hardikk13/nglod", "max_forks_repo_head_hexsha": "6c6c66ce1b39c5a3515cafc290ec903ae90b506e", "max_forks_repo_licenses": ["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.3422818792, "max_line_length": 80, "alphanum_fraction": 0.6424342884, "num_tokens": 1237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.636507866658899}}
{"text": "//\n// Created by Ujjwal Chadha on 11/2/19.\n//\n\n#include \"Mesh.h\"\n#include <iostream>\n#include <fstream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <vector>\n#include \"Utils.h\"\n#include <unordered_map>\n\nusing namespace std;\nusing namespace Eigen;\n\nMesh::Mesh() {\n\n}\n\nMesh::Mesh(const MatrixXf& vertices, const MatrixXf& faces):\n        Mesh(vertices, faces, Eigen::Vector3f(0.0, 1.1, 2.2), WIREFRAME) {\n}\n\nMesh::Mesh(const MatrixXf &vertices, const MatrixXf &faces, const Vector3f& color, const RenderType& renderType) {\n    this->vertices = vertices;\n    this->faces = faces;\n    this->model = MatrixXf(4, 4);\n    this->model <<  1,    0.,   0.,   0.,\n            0.,   1,    0.,   0.,\n            0.,   0.,   1,    0.,\n            0.,   0.,   0.,   1.;\n\n    this->color = color;\n    this->renderType = renderType;\n\n    this->triangleVertices = calculateTriangleVertices(faces, vertices);\n    this->faceNormals = calculateFaceNormals(faces, vertices, this->triangleVertices);\n    this->vertexNormals = calculateVertexNormals(faces, vertices, this->triangleVertices, this->faceNormals);\n}\n\nMesh Mesh::fromOffFile(const string &filePath) {\n    return fromOffFile(filePath, Eigen::Vector3f(0.0, 1.1, 2.2), WIREFRAME);\n}\n\nMesh Mesh::fromOffFile(const string& filepath, const Vector3f& color, const RenderType& renderType) {\n    ifstream inputFile;\n    inputFile.open(filepath);\n\n    if (!inputFile) {\n        throw std::runtime_error(\"Error opening data file: \" + filepath);\n    } else {\n        string line;\n        getline(inputFile, line);\n        getline(inputFile, line);\n        vector<string> meta = Utils::splitString(line, \" \");\n        int numVertices = stoi(meta.at(0));\n        int numFaces = stoi(meta.at(1));\n\n        MatrixXf vertices = MatrixXf::Zero(3, numVertices);\n        for (int i = 0; i < numVertices; i++) {\n            getline(inputFile, line);\n            vector<string> vertexString = Utils::splitString(line, \" \");\n\n            vertices(0, i) = (stof(vertexString[0]));\n            vertices(1, i) = (stof(vertexString[1]));\n            vertices(2, i) = stof(vertexString[2]);\n        }\n\n        MatrixXf faces = MatrixXf::Zero(3, numFaces);\n        for (int i = 0; i < numFaces; i++) {\n            getline(inputFile, line);\n            vector<string> faceString = Utils::splitString(line, \" \");\n\n            faces(0, i) = stoi(faceString[1]);\n            faces(1, i) = stoi(faceString[2]);\n            faces(2, i) = stoi(faceString[3]);\n        }\n        inputFile.close();\n\n        Vector3f baryCenter = calculateBarycenter(faces, vertices);\n        for (long i = 0; i < vertices.cols(); i++) {\n            vertices.col(i) << vertices.col(i) - baryCenter;\n        }\n        return Mesh(vertices, faces, color, renderType);\n    }\n}\n\nVector3f Mesh::calculateBarycenter(const MatrixXf &faces, const MatrixXf &vertices) {\n    Vector3f centroid(0., 0., 0.);\n    for (long faceNumber = 0; faceNumber < faces.cols(); faceNumber++) {\n        const Vector3f& a = vertices.col(faces(0, faceNumber));\n        const Vector3f& b = vertices.col(faces(1, faceNumber));\n        const Vector3f& c = vertices.col(faces(2, faceNumber));\n\n        const Vector3f& center = (a + b + c) / 3;\n        centroid = centroid + center;\n    }\n    return centroid / faces.cols();\n}\n\nMatrixXf Mesh::calculateTriangleVertices(const MatrixXf &faces, const MatrixXf &vertices) {\n    MatrixXf triangleVertices = MatrixXf::Zero(3, faces.cols() * faces.rows());\n    for (long faceNumber = 0; faceNumber < faces.cols(); faceNumber++) {\n        for (long faceVertexNumber = 0; faceVertexNumber < faces.rows(); faceVertexNumber++) {\n            int vertexNumber = faces(faceVertexNumber, faceNumber);\n            triangleVertices.col((faces.rows()*faceNumber) + faceVertexNumber) << vertices.col(vertexNumber);\n        }\n    }\n    return triangleVertices;\n}\n\nMatrixXf Mesh::calculateFaceNormals(const MatrixXf& faces, const MatrixXf& vertices, MatrixXf triangleVertices) {\n    MatrixXf normals = MatrixXf::Zero(3, triangleVertices.cols());\n    for (long i = 0; i < triangleVertices.cols(); i += 3) {\n        Vector3f a = triangleVertices.col(i);\n        Vector3f b = triangleVertices.col(i + 1);\n        Vector3f c = triangleVertices.col(i + 2);\n\n        Vector3f normal = ((b - a).cross(c - a)).normalized();\n        normals.col(i) << normal;\n        normals.col(i + 1) << normal;\n        normals.col(i + 2) << normal;\n    }\n    return normals;\n}\n\nMatrixXf Mesh::calculateVertexNormals(const MatrixXf& faces, const MatrixXf& vertices, const MatrixXf& triangleVertices,\n        const MatrixXf& faceNormals) {\n\n    unordered_map<int, vector<int>> vertexNumberToFaceNumbersMap;\n    for (long faceNumber = 0; faceNumber < faces.cols(); faceNumber++) {\n        for (long faceVertexNumber = 0; faceVertexNumber < faces.rows(); faceVertexNumber++) {\n            int vertexNumber = faces(faceVertexNumber, faceNumber);\n            if (vertexNumberToFaceNumbersMap.find(vertexNumber) == vertexNumberToFaceNumbersMap.end()) {\n                vertexNumberToFaceNumbersMap[vertexNumber] = std::vector<int>();\n            }\n            vertexNumberToFaceNumbersMap[vertexNumber].push_back(faceNumber);\n        }\n    }\n\n    MatrixXf normals(3, triangleVertices.cols());\n    for (long faceNumber = 0; faceNumber < faces.cols(); faceNumber++) {\n        for (long faceVertexNumber = 0; faceVertexNumber < faces.rows(); faceVertexNumber++) {\n            int vertexNumber = faces(faceVertexNumber, faceNumber);\n            vector<int> facesAdjascentToVertex =  vertexNumberToFaceNumbersMap[vertexNumber];\n            Vector3f vertexNormal(0.0, 0.0, 0.0);\n            for (int face: facesAdjascentToVertex) {\n                Vector3f faceNormal = faceNormals.col(face*3);\n                vertexNormal += faceNormal;\n            }\n            normals.col((3*faceNumber) + faceVertexNumber) = vertexNormal.normalized();\n        }\n    }\n    return normals;\n}\n\nvoid Mesh::scaleToUnitCube() {\n    float xmax = -999999, xmin = 99999;\n    float ymax = -999999, ymin = 99999;\n    float zmax = -999999, zmin = 99999;\n    for (long i = 0; i < getVertices().cols(); i++) {\n        Vector3f vertex = getVertices().col(i);\n        if (vertex(0) < xmin) {\n            xmin = vertex(0);\n        }\n        if (vertex(0) > xmax) {\n            xmax = vertex(0);\n        }\n        if (vertex(1) < ymin) {\n            ymin = vertex(1);\n        }\n        if (vertex(1) > ymax) {\n            ymax = vertex(1);\n        }\n        if (vertex(2) < zmin) {\n            zmin = vertex(2);\n        }\n        if (vertex(2) > zmax) {\n            zmax = vertex(2);\n        }\n    }\n    scale(1 / max(max(xmax-xmin, ymax-ymin), zmax-zmin));\n}\n\nRenderType Mesh::getRenderType() {\n    return renderType;\n}\n\nvoid Mesh::setRenderType(const RenderType& renderType) {\n    this->renderType = renderType;\n}\n\nVector3f Mesh::getColor() {\n    return this->color;\n}\n\nvoid Mesh::setColor(const Vector3f &color) {\n    this->color = color;\n}\n\nvoid Mesh::translate(const Vector3f& translateBy) {\n    this->model << Utils::generateTranslationMatrix(translateBy) * this->model;\n}\n\nvoid Mesh::scale(float factor) {\n    this->model << Utils::generateScaleAboutPointMatrix(getTranslation(), factor) * this->model;\n}\n\nvoid Mesh::rotate(int axis, float radians) {\n    this->model << Utils::generateRotateAboutPointMatrix(axis, radians, getTranslation()) * this->model;\n}\n\nVector3f Mesh::getTranslation() {\n    auto res = Vector3f(this->model.block(0, 3, 3, 1));\n    return res;\n}\n\nMatrixXf Mesh::getVertices() {\n    return this->vertices;\n}\n\nMatrixXf Mesh::getFaces() {\n    return this->faces;\n}\n\nMatrixXf Mesh::getModel() {\n    return this->model;\n}\n\nMatrixXf Mesh::getTriangleVertices() {\n    return this->triangleVertices;\n}\n\nMatrixXf Mesh::getFaceNormals() {\n    return this->faceNormals;\n}\n\nMatrixXf Mesh::getVertexNormals() {\n    return this->vertexNormals;\n}\n\nMesh::~Mesh() {\n\n}\n\n", "meta": {"hexsha": "701203ddc66c53ce108efd7edeba6093a3e7a2e6", "size": 7904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Mesh.cpp", "max_stars_repo_name": "ujjwalchadha8/3D-Editor-using-OpenGL", "max_stars_repo_head_hexsha": "5cf873f74861a527e47908c8f95d6f0e29b9a287", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Mesh.cpp", "max_issues_repo_name": "ujjwalchadha8/3D-Editor-using-OpenGL", "max_issues_repo_head_hexsha": "5cf873f74861a527e47908c8f95d6f0e29b9a287", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Mesh.cpp", "max_forks_repo_name": "ujjwalchadha8/3D-Editor-using-OpenGL", "max_forks_repo_head_hexsha": "5cf873f74861a527e47908c8f95d6f0e29b9a287", "max_forks_repo_licenses": ["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.0, "max_line_length": 120, "alphanum_fraction": 0.6182945344, "num_tokens": 2099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.6364850766540671}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"miMaS/field.h\"\n#include \"miMaS/weno.h\"\n#include \"miMaS/fft.h\"\n#include \"miMaS/array_view.h\"\n#include \"miMaS/poisson.h\"\n\nnamespace math = boost::math::constants;\n\nint main(int,char**)\n{\n  const int Nx = 9;\n  double l=2.*math::pi<double>();\n  double dx = l/Nx, dt = 0.5*dx;\n  ublas::vector<double> v(Nx),kx(Nx);\n  double vk=-0.5;\n\n\tfor ( auto i=0 ; i<Nx/2+1 ; ++i )   { kx[i] = 2.*math::pi<double>()*i/l; }\n\tfor ( auto i=0 ; i<((Nx/2)) ; ++i ) { kx[i+Nx/2+1] = -kx[Nx/2-i]; }\n\n  for ( auto i=0 ; i<Nx ; ++i ) {\n    v[i] = std::cos((double)i*dx);\n  }\n\n  std::ofstream f0(\"init.dat\");\n  for ( auto i=0 ; i<Nx ; ++i ) { f0 << i*dx << \" \" << v[i] << \"\\n\"; }\n  f0 << std::endl;\n  f0.close();\n\n  fft::spectrum s(Nx);\n\nstd::cout << std::endl;\n  int Nb_iter = 100;\n  for ( auto t=0 ; t<Nb_iter ; ++t ) {\n    std::cout << t*dt << \"----\\n\";\n    s.fft(&v[0]);\n    for ( auto i=0 ; i<Nx ; ++i ) {\n      std::cout << kx[i] << \" \" << s[i][fft::re] << \" \" << s[i][fft::im] <<  \"\\n\";\n    }\n    std::cout << \"\\n----\\n\" ; \n\n    for ( auto i=0 ; i<Nx ; ++i ) {\n      double re = s[i][fft::re], im = s[i][fft::im];\n      s[i][fft::re] = std::cos(kx[i]*dt*vk)*re + std::sin(kx[i]*dt*vk)*im;\n      s[i][fft::im] = std::cos(kx[i]*dt*vk)*im - std::sin(kx[i]*dt*vk)*re;\n    }\n    s.ifft(&v[0]);\n  }\nstd::cout << std::endl;\n\n  std::ofstream f1(\"vp.dat\");\n  for ( auto i=0 ; i<Nx ; ++i ) {\n    f1 << i*dx << \" \" << v[i] << \" \" << std::cos(i*dx-vk*(Nb_iter)*dt) << \"\\n\";\n  }\n  f1 << std::endl;\n  f1.close();\n\n  return 0;\n}\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "ce32fa23c966f1f8cb7761551a00f545f52147ba", "size": 1736, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/trp.cc", "max_stars_repo_name": "kivvix/vlasovpp", "max_stars_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-03T22:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-29T06:12:07.000Z", "max_issues_repo_path": "code/trp.cc", "max_issues_repo_name": "kivvix/vlasovpp", "max_issues_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/trp.cc", "max_forks_repo_name": "kivvix/vlasovpp", "max_forks_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-29T06:17:16.000Z", "avg_line_length": 22.5454545455, "max_line_length": 82, "alphanum_fraction": 0.5046082949, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6364831497541833}}
{"text": "/**\n * @file Math.cpp\n * @author Giulio Romualdi\n * @copyright Released under the terms of the MIT License.\n * @date 2021\n */\n\n#include <utility>\n\n#include <Eigen/Cholesky>\n#include <Eigen/Dense>\n\n#include <ScsEigen/Logger.h>\n#include <ScsEigen/Math.h>\n\nstd::pair<bool, Eigen::MatrixXd>\nScsEigen::choleskyDecomposition(const Eigen::Ref<const Eigen::MatrixXd>& A)\n{\n    if (A.rows() != A.cols())\n    {\n        log()->error(\"[ScsEigen::choleskyDecomposition] A is not square.\");\n        assert(false);\n        return std::pair(false, Eigen::MatrixXd());\n    }\n\n    // In most case the cholesky decomposition should be fine.\n    // if eigen is not able to find a feasible solution we try to use a robust cholesky\n    // decomposition\n    Eigen::LLT<Eigen::MatrixXd> lltA(A);\n    if (lltA.info() == Eigen::Success)\n    {\n        return std::pair(true, lltA.matrixU());\n    } else\n    {\n        Eigen::LDLT<Eigen::MatrixXd> ldltA(A);\n        if (ldltA.info() == Eigen::Success)\n        {\n            return std::pair(true, ldltA.matrixU());\n        }\n    }\n\n    log()->error(\"[ScsEigen::choleskyDecomposition] Unable to compute the Cholesky decomposition.\");\n    return std::pair(false, Eigen::MatrixXd());\n}\n", "meta": {"hexsha": "fbb7b22ccf2ce2305d01d45f7939666980736fae", "size": 1204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ScsEigen/src/Math.cpp", "max_stars_repo_name": "GiulioRomualdi/scs-eigen", "max_stars_repo_head_hexsha": "b315dbee88f2a0bdcfe5b538607b858209880086", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-29T07:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T16:36:54.000Z", "max_issues_repo_path": "src/ScsEigen/src/Math.cpp", "max_issues_repo_name": "GiulioRomualdi/scs-eigen", "max_issues_repo_head_hexsha": "b315dbee88f2a0bdcfe5b538607b858209880086", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-03T20:21:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T21:12:24.000Z", "max_forks_repo_path": "src/ScsEigen/src/Math.cpp", "max_forks_repo_name": "GiulioRomualdi/scs-eigen", "max_forks_repo_head_hexsha": "b315dbee88f2a0bdcfe5b538607b858209880086", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-12T16:35:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-12T16:35:06.000Z", "avg_line_length": 26.7555555556, "max_line_length": 100, "alphanum_fraction": 0.627076412, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6364831494519506}}
{"text": "#ifndef __PROBABILITY_DISTRIBUTIONS__DISCRETE_IMPL_HPP__\n#define __PROBABILITY_DISTRIBUTIONS__DISCRETE_IMPL_HPP__\n\n#include \"discrete.hpp\"\n\n#include \"const_slice.hpp\"\n#include \"slice.hpp\"\n\n#include <boost/random/discrete_distribution.hpp>\n#include <cmath>\n\nnamespace ProbabilityDistributions {\n  template <unsigned int K, class D, class W, class T>\n  Discrete<K,D,W,T>::Discrete():\n    p_(K, 1./K) { }\n\n  template <unsigned int K, class D, class W, class T>\n  Discrete<K,D,W,T>::Discrete(std::vector<T> const& p):\n    p_(p) {\n      assert(p.size() == K);\n    }\n\n  template <unsigned int K, class D, class W, class T>\n  template <class RNG>\n  void Discrete<K,D,W,T>::sample(MA::Array<D>& samples, size_t n_samples,\n      RNG& rng) const {\n    MA::Size::SizeType size(2);\n    size[0] = n_samples;\n    size[1] = K;\n    samples.resize(size);\n\n    boost::random::discrete_distribution<unsigned int, T> dist(p_.begin(),\n        p_.end());\n\n    MA::Slice<T> slice(samples, 0);\n    for (size_t j = 0; j < slice.total_left_size(); j++) {\n      MA::Array<T> s = slice.get_element(j);\n\n      unsigned int val = dist(rng);\n      for (unsigned int i = 0; i < K; i++) {\n        if (i == val)\n          s(i) = 1;\n        else\n          s(i) = 0;\n      }\n    }\n  }\n\n  template <unsigned int K, class D, class W, class T>\n  T Discrete<K,D,W,T>::log_likelihood(MA::ConstArray<D> const& data,\n          MA::ConstArray<W> const& weight) const {\n    check_data_and_weight(data, weight);\n\n    T ll = 0;\n    std::vector<T> log_p(p_);\n    for (unsigned int i = 0; i < K; i++)\n      log_p[i] = log(log_p[i]);\n\n    MA::ConstSlice<T> slice(data, 0);\n    for (size_t j = 0; j < slice.total_left_size(); j++) {\n      MA::ConstArray<T> const& sample = slice.get_element(j);\n      T w = weight(j);\n      for (unsigned int i = 0; i < K; i++) {\n        T s = sample(i);\n        if (s != 0)\n          ll += w * s * log_p[i];\n      }\n    }\n\n    return ll;\n  }\n\n  template <unsigned int K, class D, class W, class T>\n  void Discrete<K,D,W,T>::MLE(MA::ConstArray<D> const& data,\n      MA::ConstArray<W> const& weight, std::vector<size_t> const& indexes) {\n    check_data_and_weight(data, weight);\n\n    for (unsigned int i = 0; i < K; i++)\n      p_[i] = 0;\n\n    MA::ConstSlice<T> slice(data, 0);\n    for (size_t j = 0; j < slice.total_left_size(); j++) {\n      MA::ConstArray<T> const& sample = slice.get_element(j);\n      T w = weight(j);\n      for (unsigned int i = 0; i < K; i++)\n        p_[i] += w * sample(i);\n    }\n\n    normalize();\n  }\n\n  template <unsigned int K, class D, class W, class T>\n  void Discrete<K,D,W,T>::sample_to_index(MA::Array<unsigned int>& indexes,\n          MA::ConstArray<D> const& samples) const {\n    assert(samples.size().size() == 2);\n    assert(samples.size()[0] > 0);\n    assert(samples.size()[1] == K);\n\n    MA::Size::SizeType size(1);\n    size[0] = samples.size()[0];\n    indexes.resize(size);\n\n    MA::ConstSlice<T> samples_slice(samples, 0);\n    for (size_t j = 0; j < samples_slice.total_left_size(); j++) {\n      MA::ConstArray<T> const& s = samples_slice.get_element(j);\n      size_t i;\n      for (i = 0; i < K; i++)\n        if (s(i) == 1) {\n          indexes(j) = i;\n          break;\n        }\n      assert(i < K);\n    }\n  }\n\n  template <unsigned int K, class D, class W, class T>\n  void Discrete<K,D,W,T>::index_to_sample(MA::Array<D>& samples,\n          MA::ConstArray<unsigned int> const& indexes) const {\n    assert(indexes.size().size() == 1);\n    assert(indexes.size()[0] > 0);\n\n    MA::Size::SizeType size = indexes.size();\n    size.push_back(K);\n    samples.resize(size);\n\n    MA::Slice<T> samples_slice(samples, 0);\n    for (size_t j = 0; j < samples_slice.total_left_size(); j++) {\n      MA::Array<T>& s = samples_slice.get_element(j);\n      unsigned int index = indexes(j);\n      assert(index < K);\n      for (size_t i = 0; i < K; i++) {\n        if (i == index)\n          s(i) = 1;\n        else\n          s(i) = 0;\n      }\n    }\n  }\n\n  template <unsigned int K, class D, class W, class T>\n  void Discrete<K,D,W,T>::check_data_and_weight(MA::ConstArray<D> const& data,\n          MA::ConstArray<W> const& weight) const {\n    assert(data.size().size() == 2);\n    assert(data.size()[0] > 0);\n    assert(data.size()[1] == K);\n    assert(weight.size().size() == 1);\n    assert(weight.size()[0] == data.size()[0]);\n  }\n\n  template <unsigned int K, class D, class W, class T>\n  void Discrete<K,D,W,T>::normalize() {\n    T sum = 0;\n    for (unsigned int i = 0; i < K; i++)\n      sum += p_[i];\n\n    for (unsigned int i = 0; i < K; i++)\n      p_[i] /= sum;\n  }\n\n  template <unsigned int K, class D, class W, class T>\n  void Discrete<K,D,W,T>::anneal(T temp) {\n    for (unsigned int i = 0; i < K; i++)\n      p_[i] = std::exp(std::log(p_[i])/temp);\n    normalize();\n  }\n};\n\n#endif\n", "meta": {"hexsha": "122ec9bcd4541d84309785bb7fdebbca0e7430e5", "size": 4783, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/discrete_impl.hpp", "max_stars_repo_name": "mirandaconrado/probability-distributions", "max_stars_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/discrete_impl.hpp", "max_issues_repo_name": "mirandaconrado/probability-distributions", "max_issues_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/discrete_impl.hpp", "max_forks_repo_name": "mirandaconrado/probability-distributions", "max_forks_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3017751479, "max_line_length": 78, "alphanum_fraction": 0.5674263015, "num_tokens": 1450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6364576116120391}}
{"text": "#include <Eigen/Dense>\n\n#include \"NumpySaver.hpp\"\n#include \"Timer.hpp\"\n#include \"fft.hpp\"\n#include \"image_fft.hpp\"\n#include \"progressbar.hpp\"\n\nusing namespace Eigen;\nstd::tuple<double, double> measure_fft_time(Index input_size) {\n  VectorXd vec = VectorXd::Random(input_size);\n  VectorXcd dest(input_size);\n\n  return Timer::measure_time(\n      [&]() { fft(vec.data(), dest.data(), input_size); }, .01);\n}\n\nint main(int argc, char const* argv[]) {\n#ifndef NDEBUG\n  FFT::tests();\n  // image_test();\n  compress_test();\n#endif\n\n  VectorXd input_sizes_lin = VectorXd::LinSpaced(1030 - 500 + 1, 500, 1030);\n  VectorXd input_sizes_p2(14);\n  // dont judge me\n  input_sizes_p2 << 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192,\n      16384;\n\n  progressbar bar(input_sizes_lin.size() + input_sizes_p2.size());\n\n  VectorXd mean_lin(input_sizes_lin.size()), std_lin(input_sizes_lin.size());\n  for (Index k = 0; k < input_sizes_lin.size(); k++) {\n    bar.update();\n    auto [mean, std] = measure_fft_time(input_sizes_lin[k] + 1e-5);\n    mean_lin[k] = mean;\n    std_lin[k] = std;\n  }\n\n  VectorXd mean_p2(input_sizes_p2.size()), std_p2(input_sizes_p2.size());\n  for (Index k = 0; k < input_sizes_p2.size(); k++) {\n    bar.update();\n    auto [mean, std] = measure_fft_time(input_sizes_p2[k]);\n    mean_p2[k] = mean;\n    std_p2[k] = std;\n  }\n\n  NumpySaver(\"build/output/times_lin.npy\")\n      << input_sizes_lin << mean_lin << std_lin;\n  NumpySaver(\"build/output/times_p2.npy\")\n      << input_sizes_p2 << mean_p2 << std_p2;\n\n  VectorXd lost(6);\n  VectorXcd lost_fft(lost.size());\n  VectorXd lost_dct(lost.size());\n  lost << 4, 8, 15, 16, 23, 42;\n  fft(lost.data(), lost_fft.data(), lost.size());\n  dct(lost.data(), lost_dct.data(), lost.size());\n  NumpySaver(\"build/output/lost.npy\")\n      << lost << lost_fft.real() << lost_fft.imag() << lost_dct;\n\n  VectorXd plot(1000);\n  VectorXcd plot_fft(plot.size());\n  for (Index k = 0; k < plot.size() / 3; k++) {\n    plot[k] = 0;\n  }\n  for (Index k = plot.size() / 3; k < plot.size() / 3 * 2; k++) {\n    plot[k] = 1;\n  }\n  for (Index k = plot.size() / 3 * 2; k < plot.size(); k++) {\n    plot[k] = 0;\n  }\n  fft(plot.data(), plot_fft.data(), plot.size());\n  NumpySaver(\"build/output/plot.npy\")\n      << plot << plot_fft.real() << plot_fft.imag();\n\n  compress_image(\"images/A.png\", \"build/output/A9.ldw\", 0.9);\n  compress_image(\"images/A.png\", \"build/output/A5.ldw\", 0.5);\n  compress_image(\"images/A.png\", \"build/output/A2.ldw\", 0.2);\n  compress_image(\"images/A.png\", \"build/output/A1.ldw\", 0.1);\n  decompress_image(\"build/output/A9.ldw\", \"build/plots/A9.png\");\n  decompress_image(\"build/output/A5.ldw\", \"build/plots/A5.png\");\n  decompress_image(\"build/output/A2.ldw\", \"build/plots/A2.png\");\n  decompress_image(\"build/output/A1.ldw\", \"build/plots/A1.png\");\n\n  blur(\"images/dune.png\", \"build/output/dune_blur1.png\",\n       \"build/output/dune_blur1_mask.png\", .1);\n  blur(\"images/dune.png\", \"build/output/dune_blur2.png\",\n       \"build/output/dune_blur2_mask.png\", .2);\n  blur(\"images/dune.png\", \"build/output/dune_blur4.png\",\n       \"build/output/dune_blur4_mask.png\", .4);\n  blur(\"images/dune.png\", \"build/output/dune_blur3.png\",\n       \"build/output/dune_blur3_mask.png\", .3);\n\n  blur_smooth(\"images/dune.png\", \"build/output/dune_blur_smooth.png\",\n              \"build/output/dune_blur_smooth_mask.png\", .001);\n\n  rect_filter(\"images/dune.png\", \"build/output/dune_blur_rect.png\",\n              \"build/output/dune_rect_mask.png\", .1, .1);\n\n  sharpen(\"images/blackhole.png\", \"build/output/blackhole_sharp9.png\",\n          \"build/output/blackhole_sharp9_mask.png\", .09);\n  sharpen(\"images/blackhole.png\", \"build/output/blackhole_sharp6.png\",\n          \"build/output/blackhole_sharp6_mask.png\", .06);\n  sharpen(\"images/blackhole.png\", \"build/output/blackhole_sharp3.png\",\n          \"build/output/blackhole_sharp3_mask.png\", .03);\n  sharpen(\"images/blackhole.png\", \"build/output/blackhole_sharp1.png\",\n          \"build/output/blackhole_sharp1_mask.png\", .01);\n\n  sharpen_smooth(\"images/blackhole.png\",\n                 \"build/output/blackhole_sharp_smooth_g.png\",\n                 \"build/output/blackhole_sharp_smooth_mask_g.png\", .01, true);\n  sharpen_smooth(\"images/blackhole.png\",\n                 \"build/output/blackhole_sharp_smooth.png\",\n                 \"build/output/blackhole_sharp_smooth_mask.png\", .01, false);\n\n  // compress_image(\"images/dune.png\", \"build/output/dune8.ldw\", 0.9);\n  // compress_image(\"images/dune.png\", \"build/output/dune5.ldw\", 0.5);\n  // compress_image(\"images/dune.png\", \"build/output/dune1.ldw\", 0.1);\n  // decompress_image(\"build/output/dune5.ldw\", \"build/plots/dune9.png\");\n  // decompress_image(\"build/output/dune5.ldw\", \"build/plots/dune5.png\");\n  // decompress_image(\"build/output/dune1.ldw\", \"build/plots/dune1.png\");\n\n  //   sharpen(\"images/blackhole.png\", \"build/plots/blackhole001_bw.png\",\n  //           \"build/plots/blackhole001_bw_mask.png\", .001, true);\n  //   sharpen(\"images/blackhole.png\", \"build/plots/blackhole05_bw.png\",\n  //           \"build/plots/blackhole01_bw_mask.png\", .01, true);\n  //   sharpen(\"images/blackhole.png\", \"build/plots/blackhole01_bw.png\",\n  //           \"build/plots/blackhole01_bw_mask.png\", .01, true);\n  //   sharpen(\"images/blackhole.png\", \"build/plots/blackhole0_bw.png\",\n  //           \"build/plots/blackhole0_bw_mask.png\", .0, true);\n\n  //   sharpen(\"images/dune.png\", \"build/plots/dune_bw_sharp.png\",\n  //           \"build/plots/dune_bw_sharp_mask.png\", .005, true);\n  //   blur(\"images/dune.png\", \"build/plots/dune_bw_blur.png\",\n  //        \"build/plots/dune_bw_blur_mask.png\", .95, true);\n  //   sharpen(\"images/dune.png\", \"build/plots/dune_bw.png\",\n  //           \"build/plots/dune_bw_mask.png\", 0, true);\n\n  //   rect_filter(\"images/dune.png\", \"build/plots/dune_bw_rect.png\",\n  //               \"build/plots/dune_bw_rect_mask.png\", .5, .5, true);\n  //   anti_rect_filter(\"images/dune.png\", \"build/plots/dune_bw_arect.png\",\n  //                    \"build/plots/dune_bw_arect_mask.png\", .05, .05, true);\n\n  //   blur(\"images/A.png\", \"build/plots/A_blur95.png\",\n  //        \"build/plots/A_blur95_mask.png\", .95);\n  //   blur(\"images/A.png\", \"build/plots/A_blur9.png\",\n  //        \"build/plots/A_blur9_mask.png\", .9);\n  //   blur(\"images/A.png\", \"build/plots/A_blur8.png\",\n  //        \"build/plots/A_blur8_mask.png\", .8);\n  //   blur(\"images/A.png\", \"build/plots/A_blur7.png\",\n  //        \"build/plots/A_blur7_mask.png\", .7);\n  //   blur(\"images/A.png\", \"build/plots/A_blur6.png\",\n  //        \"build/plots/A_blur6_mask.png\", .6);\n  //   blur(\"images/A.png\", \"build/plots/A_blur5.png\",\n  //        \"build/plots/A_blur5_mask.png\", .5);\n  //   blur(\"images/A.png\", \"build/plots/A_blur4.png\",\n  //        \"build/plots/A_blur4_mask.png\", .4);\n  //   blur(\"images/A.png\", \"build/plots/A_blur3.png\",\n  //        \"build/plots/A_blur3_mask.png\", .3);\n  //   blur(\"images/A.png\", \"build/plots/A_blur2.png\",\n  //        \"build/plots/A_blur2_mask.png\", .2);\n  //   blur(\"images/A.png\", \"build/plots/A_blur1.png\",\n  //        \"build/plots/A_blur1_mask.png\", .1);\n\n  sharpen(\"images/A.png\", \"build/output/A_sharpen95.png\",\n          \"build/output/A_sharpen95_mask.png\", .95);\n  //   sharpen(\"images/A.png\", \"build/plots/A_sharpen9.png\",\n  //           \"build/plots/A_sharpen9_mask.png\", .9);\n  //   sharpen(\"images/A.png\", \"build/plots/A_sharpen8.png\",\n  //           \"build/plots/A_sharpen8_mask.png\", .8);\n  //   sharpen(\"images/A.png\", \"build/plots/A_sharpen7.png\",\n  //           \"build/plots/A_sharpen7_mask.png\", .7);\n  //   sharpen(\"images/A.png\", \"build/plots/A_sharpen6.png\",\n  //           \"build/plots/A_sharpen6_mask.png\", .6);\n  //   sharpen(\"images/A.png\", \"build/plots/A_sharpen5.png\",\n  //           \"build/plots/A_sharpen5_mask.png\", .5);\n  //   sharpen(\"images/A.png\", \"build/plots/A_sharpen4.png\",\n  //           \"build/plots/A_sharpen4_mask.png\", .4);\n  //   sharpen(\"images/A.png\", \"build/plots/A_sharpen3.png\",\n  //           \"build/plots/A_sharpen3_mask.png\", .3);\n  //   sharpen(\"images/A.png\", \"build/plots/A_sharpen2.png\",\n  //           \"build/plots/A_sharpen2_mask.png\", .2);\n  sharpen(\"images/A.png\", \"build/output/A_sharpen1.png\",\n          \"build/output/A_sharpen1_mask.png\", .1);\n\n  sharpen_smooth(\"images/A.png\", \"build/output/A_sharp_smooth.png\",\n                 \"build/output/A_sharp_smooth_mask.png\", .001, false);\n\n  //   rect_filter(\"images/A.png\", \"build/plots/A_blur_rect95.png\",\n  //               \"build/plots/A_blur_rect95_mask.png\", .95, .95);\n  //   rect_filter(\"images/A.png\", \"build/plots/A_blur_rect9.png\",\n  //               \"build/plots/A_blur_rect9_mask.png\", .9, .9);\n  //   rect_filter(\"images/A.png\", \"build/plots/A_blur_rect8.png\",\n  //               \"build/plots/A_blur_rect8_mask.png\", .8, .8);\n  //   rect_filter(\"images/A.png\", \"build/plots/A_blur_rect7.png\",\n  //               \"build/plots/A_blur_rect7_mask.png\", .7, .7);\n  //   rect_filter(\"images/A.png\", \"build/plots/A_blur_rect6.png\",\n  //               \"build/plots/A_blur_rect6_mask.png\", .6, .6);\n  //   rect_filter(\"images/A.png\", \"build/plots/A_blur_rect5.png\",\n  //               \"build/plots/A_blur_rect5_mask.png\", .5, .5);\n  //   rect_filter(\"images/A.png\", \"build/plots/A_blur_rect4.png\",\n  //               \"build/plots/A_blur_rect4_mask.png\", .4, .4);\n  //   rect_filter(\"images/A.png\", \"build/plots/A_blur_rect3.png\",\n  //               \"build/plots/A_blur_rect3_mask.png\", .3, .3);\n  //   rect_filter(\"images/A.png\", \"build/plots/A_blur_rect2.png\",\n  //               \"build/plots/A_blur_rect2_mask.png\", .2, .2);\n  //   rect_filter(\"images/A.png\", \"build/plots/A_blur_rect1.png\",\n  //               \"build/plots/A_blur_rect1_mask.png\", .1, .1);\n\n  //   anti_rect_filter(\"images/A.png\", \"build/plots/A_blur_anti_rect95.png\",\n  //                    \"build/plots/A_blur_anti_rect95_mask.png\", .95, .95);\n  //   anti_rect_filter(\"images/A.png\", \"build/plots/A_blur_anti_rect9.png\",\n  //                    \"build/plots/A_blur_anti_rect9_mask.png\", .9, .9);\n  //   anti_rect_filter(\"images/A.png\", \"build/plots/A_blur_anti_rect8.png\",\n  //                    \"build/plots/A_blur_anti_rect8_mask.png\", .8, .8);\n  //   anti_rect_filter(\"images/A.png\", \"build/plots/A_blur_anti_rect7.png\",\n  //                    \"build/plots/A_blur_anti_rect7_mask.png\", .7, .7);\n  //   anti_rect_filter(\"images/A.png\", \"build/plots/A_blur_anti_rect6.png\",\n  //                    \"build/plots/A_blur_anti_rect6_mask.png\", .6, .6);\n  //   anti_rect_filter(\"images/A.png\", \"build/plots/A_blur_anti_rect5.png\",\n  //                    \"build/plots/A_blur_anti_rect5_mask.png\", .5, .5);\n  //   anti_rect_filter(\"images/A.png\", \"build/plots/A_blur_anti_rect4.png\",\n  //                    \"build/plots/A_blur_anti_rect4_mask.png\", .4, .4);\n  //   anti_rect_filter(\"images/A.png\", \"build/plots/A_blur_anti_rect3.png\",\n  //                    \"build/plots/A_blur_anti_rect3_mask.png\", .3, .3);\n  //   anti_rect_filter(\"images/A.png\", \"build/plots/A_blur_anti_rect2.png\",\n  //                    \"build/plots/A_blur_anti_rect2_mask.png\", .2, .2);\n  //   anti_rect_filter(\"images/A.png\", \"build/plots/A_blur_anti_rect1.png\",\n  //                    \"build/plots/A_blur_anti_rect1_mask.png\", .1, .1);\n\n  //   sharpen(\"images/boy.png\", \"build/plots/boy.png\",\n  //           \"build/plots/boy_control.png\", .05);\n\n  //   sharpen_smooth(\"images/boy.png\", \"build/plots/boy_smooth.png\",\n  //                  \"build/plots/boy_control_smooth.png\", .001);\n}\n", "meta": {"hexsha": "29902c998bb9371f062cbe7644acdc12429ce400", "size": 11449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project08-ImageFourierTransform/imagefouriertransform.cpp", "max_stars_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_stars_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project08-ImageFourierTransform/imagefouriertransform.cpp", "max_issues_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_issues_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project08-ImageFourierTransform/imagefouriertransform.cpp", "max_forks_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_forks_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.9037656904, "max_line_length": 79, "alphanum_fraction": 0.6273036946, "num_tokens": 3524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6364561782164239}}
{"text": "\r\n#include <Discregrid/All>\r\n#include <Eigen/Dense>\r\n#include <cxxopts/cxxopts.hpp>\r\n\r\n#include <string>\r\n#include <iostream>\r\n#include <array>\r\n\r\n#include \"sph_kernel.hpp\"\r\n#include \"gauss_quadrature.hpp\"\r\n\r\nusing namespace Eigen;\r\n\r\nstd::istream& operator>>(std::istream& is, std::array<unsigned int, 3>& data)\r\n{\r\n\tis >> data[0] >> data[1] >> data[2];\r\n\treturn is;\r\n}\r\n\r\nstd::istream& operator>>(std::istream& is, AlignedBox3d& data)\r\n{\r\n\tis\t>> data.min()[0] >> data.min()[1] >> data.min()[2]\r\n\t\t>> data.max()[0] >> data.max()[1] >> data.max()[2];\r\n\treturn is;\r\n}\r\n\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\tcxxopts::Options options(argv[0], \"Generates a signed distance field from a closed two-manifold triangle mesh.\");\r\n\toptions.positional_help(\"[input OBJ file]\");\r\n\r\n\toptions.add_options()\r\n\t(\"h,help\", \"Prints this help text\")\r\n\t(\"r,rest_density\", \"Rest density rho0 of the fluid\", cxxopts::value<double>()->default_value(\"1000.0\"))\r\n\t(\"i,invert\", \"Invert field\")\r\n\t(\"s,smoothing_length\", \"Kernel smoothing length\", cxxopts::value<double>()->default_value(\"0.1\"))\r\n\t(\"o,output\", \"Ouput file in cdf format\", cxxopts::value<std::string>()->default_value(\"\"))\r\n\t(\"no-reduction\", \"Disables discarding of cells for sparse layout.\")\r\n\t(\"input\", \"Discrete grid file containing input SDF in field 0\", cxxopts::value<std::vector<std::string>>())\r\n\t;\r\n\r\n\ttry\r\n\t{\r\n\t\toptions.parse_positional(\"input\");\r\n\t\toptions.parse(argc, argv);\r\n\t}\r\n\tcatch (cxxopts::OptionException const& e)\r\n\t{\r\n\t\tstd::cout << \"error parsing options: \" << e.what() << std::endl;\r\n\t\texit(1);\r\n\t}\r\n\tif (options.count(\"help\"))\r\n\t{\r\n\t\tstd::cout << options.help() << std::endl;\r\n\t\tstd::cout << std::endl << std::endl << \"Example: GenerateSDF -r \\\"50 50 50\\\" dragon.obj\" << std::endl;\r\n\t\texit(0);\r\n\t}\r\n\tif (!options.count(\"input\"))\r\n\t{\r\n\t\tstd::cout << \"ERROR: No input SDF given.\" << std::endl;\r\n\t\tstd::cout << options.help() << std::endl;\r\n\t\tstd::cout << std::endl << std::endl << \"Example: GenerateDensityMap -r \\\"50 50 50\\\" field.cdf\" << std::endl;\r\n\t\texit(1);\r\n\t}\r\n\tauto filename = options[\"input\"].as<std::vector<std::string>>().front();\r\n\r\n\tif (!std::ifstream(filename).good())\r\n\t{\r\n\t\tstd::cerr << \"ERROR: Input file does not exist!\" << std::endl;\r\n\t\texit(1);\r\n\t}\r\n\r\n\tauto sdf = std::unique_ptr<Discregrid::DiscreteGrid>{};\r\n\r\n\tauto lastindex = filename.find_last_of(\".\");\r\n\tauto extension = filename.substr(lastindex+1, filename.length() - lastindex);\r\n\r\n\tstd::cout << \"Load SDF...\";\r\n\tif (extension == \"cdf\")\r\n\t{\r\n\t\tsdf = std::make_unique<Discregrid::CubicLagrangeDiscreteGrid>(filename);\r\n\t}\r\n\tstd::cout << \"DONE\" << std::endl;\r\n\r\n\tauto h = options[\"s\"].as<double>();\r\n\tauto sph_kernel = CubicKernel{};\r\n\tsph_kernel.setRadius(h);\r\n\tauto gamma = [&](Vector3d const& x)\r\n\t{\r\n\t\tauto ar = sph_kernel.getRadius();\r\n\t\tauto dist = sdf->interpolate(0u, x);\r\n\t\tif (dist > ar)\r\n\t\t\treturn 0.0;\r\n\t\treturn 1.0 - dist / ar;\r\n\t};\r\n\tauto int_domain = AlignedBox3d(Vector3d::Constant(-h), Vector3d::Constant(h));\r\n\tauto rho0 = options[\"r\"].as<double>();\r\n\tauto density_func = [&](Vector3d const& x)\r\n\t{\r\n\t\tauto dist = sdf->interpolate(0u, x);\r\n\t\tif (dist > 2.0 * sph_kernel.getRadius())\r\n\t\t{\r\n\t\t\treturn 0.0;\r\n\t\t}\r\n\r\n\t\tauto integrand = [&sph_kernel, &gamma, &x](Vector3d const& xi)\r\n\t\t{\r\n\t\t\tauto res = gamma(x + xi) * sph_kernel.W(xi);\r\n\t\t\treturn res;\r\n\t\t};\r\n\r\n\t\tauto res = GaussQuadrature::integrate(integrand, int_domain, 30);\r\n\t\treturn rho0 * res;\r\n\t};\r\n\r\n\tauto no_reduction = options[\"no-reduction\"].count() > 0u;\r\n\r\n\r\n\tauto cell_diag = sdf->cellSize().norm();\r\n\tstd::cout << \"Generate density map...\" << std::endl;\r\n\tsdf->addFunction(density_func, true, [&](Vector3d const& x_)\r\n\t{\r\n\t\tif (no_reduction)\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tauto x = x_.cwiseMax(sdf->domain().min()).cwiseMin(sdf->domain().max());\r\n\t\tauto dist = sdf->interpolate(0u, x);\r\n\t\tif (dist == std::numeric_limits<double>::max())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\treturn -6.0 * h < dist + cell_diag && dist -cell_diag < 2.0 * h;\r\n\t});\r\n\r\n\tif (options[\"no-reduction\"].count() == 0u)\r\n\t{\r\n\t\tstd::cout << \"Reduce discrete fields...\";\r\n\t\tsdf->reduceField(0u, [&](auto const&, double v)\r\n\t\t{\r\n\t\t\treturn -6.0 * h < v + cell_diag && v -cell_diag  < 2.0 * h;\r\n\t\t});\r\n\t\tsdf->reduceField(1u, [&](auto const&, double v)\r\n\t\t{\r\n\t\t\treturn 0.0 <= v && v <= 3.0 * rho0;\r\n\t\t});\r\n\t\tstd::cout << \"DONE\" << std::endl;\r\n\t}\r\n\r\n\tstd::cout << \"Serialize discretization...\";\r\n\tauto output_file = options[\"o\"].as<std::string>();\r\n\tif (output_file == \"\")\r\n\t{\r\n\t\toutput_file = filename;\r\n\t\tif (output_file.find(\".\") != std::string::npos)\r\n\t\t{\r\n\t\t\tauto lastindex = output_file.find_last_of(\".\");\r\n\t\t\toutput_file = output_file.substr(0, lastindex);\r\n\t\t}\r\n\t\toutput_file += \".cdm\";\r\n\t}\r\n\tsdf->save(output_file);\r\n\tstd::cout << \"DONE\" << std::endl;\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "cda836215eef352f3aedbf9a89096f180cbcf875", "size": 4760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmd/generate_density_map/main.cpp", "max_stars_repo_name": "Borges3D/Discregrid", "max_stars_repo_head_hexsha": "f16a29afebf7a7f43139d5832bbfc7124c5d98db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmd/generate_density_map/main.cpp", "max_issues_repo_name": "Borges3D/Discregrid", "max_issues_repo_head_hexsha": "f16a29afebf7a7f43139d5832bbfc7124c5d98db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmd/generate_density_map/main.cpp", "max_forks_repo_name": "Borges3D/Discregrid", "max_forks_repo_head_hexsha": "f16a29afebf7a7f43139d5832bbfc7124c5d98db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:58:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:58:55.000Z", "avg_line_length": 28.0, "max_line_length": 115, "alphanum_fraction": 0.6067226891, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6364561626694015}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nMatrix4d A = Matrix4d::Random(4,4);\ncout << \"Here is a random 4x4 matrix:\" << endl << A << endl;\nHessenbergDecomposition<Matrix4d> hessOfA(A);\nMatrix4d pm = hessOfA.packedMatrix();\ncout << \"The packed matrix M is:\" << endl << pm << endl;\ncout << \"The upper Hessenberg part corresponds to the matrix H, which is:\" \n     << endl << hessOfA.matrixH() << endl;\nVector3d hc = hessOfA.householderCoefficients();\ncout << \"The vector of Householder coefficients is:\" << endl << hc << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "9a67d33c70ff5771b4277861f047d4018485f457", "size": 1015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_HessenbergDecomposition_packedMatrix.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_HessenbergDecomposition_packedMatrix.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_HessenbergDecomposition_packedMatrix.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7575757576, "max_line_length": 224, "alphanum_fraction": 0.6896551724, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6363555617776001}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_CCMATH_ILOGB_HPP\n#define BOOST_MATH_CCMATH_ILOGB_HPP\n\n#include <cmath>\n#include <type_traits>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/math/ccmath/logb.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/abs.hpp>\n\nnamespace boost::math::ccmath {\n\n// If arg is not zero, infinite, or NaN, the value returned is exactly equivalent to static_cast<int>(std::logb(arg))\ntemplate <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>\ninline constexpr int ilogb(Real arg) noexcept\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))\n    {\n        return boost::math::ccmath::abs(arg) == Real(0) ? FP_ILOGB0 :\n               boost::math::ccmath::isinf(arg) ? INT_MAX :\n               boost::math::ccmath::isnan(arg) ? FP_ILOGBNAN :\n               static_cast<int>(boost::math::ccmath::logb(arg));\n    }\n    else\n    {\n        using std::ilogb;\n        return ilogb(arg);\n    }\n}\n\ntemplate <typename Z, std::enable_if_t<std::is_integral_v<Z>, bool> = true>\ninline constexpr int ilogb(Z arg) noexcept\n{\n    return boost::math::ccmath::ilogb(static_cast<double>(arg));\n}\n\ninline constexpr int ilogbf(float arg) noexcept\n{\n    return boost::math::ccmath::ilogb(arg);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr int ilogbl(long double arg) noexcept\n{\n    return boost::math::ccmath::ilogb(arg);\n}\n#endif\n\n} // Namespaces\n\n#endif // BOOST_MATH_CCMATH_ILOGB_HPP\n", "meta": {"hexsha": "a3b55d3b1ac062a506e0804e0e209757a02e941a", "size": 1724, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/ilogb.hpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "include/boost/math/ccmath/ilogb.hpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "include/boost/math/ccmath/ilogb.hpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 29.724137931, "max_line_length": 117, "alphanum_fraction": 0.7082366589, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.636345674070144}}
{"text": "#include \"laplace.hpp\"\n\n#include <gtest/gtest.h>\n\n#include <boost/random/mersenne_twister.hpp>\n\nusing namespace MultidimensionalArray;\nusing namespace ProbabilityDistributions;\n\nTEST(LaplaceTest, Likelihood) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  Laplace<double> dist(0, 1);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n\n  auto indexes = Distribution<double>::sort_data(samples);\n\n  double likelihood1 = dist.log_likelihood(samples);\n\n  dist.MLE(samples, indexes);\n\n  double likelihood2 = dist.log_likelihood(samples);\n\n  EXPECT_GE(likelihood2, likelihood1);\n\n  EXPECT_LT(0, dist.get_lambda());\n}\n\nTEST(LaplaceTest, MLE) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  Laplace<double> dist(0, 1);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n  auto indexes = Distribution<double>::sort_data(samples);\n  dist.MLE(samples, indexes);\n\n  double mu = dist.get_mu(), lambda = dist.get_lambda();\n  double eps = 1e-2;\n  double ll = dist.log_likelihood(samples);\n\n  dist.set_mu(mu + eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_mu(mu - eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_mu(mu);\n\n  dist.set_lambda(lambda + eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_lambda(lambda - eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_lambda(lambda);\n}\n\nTEST(LaplaceTest, Samples) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  Laplace<double> dist(0, 1);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n  for (size_t i = 0; i < n_samples; i++) {\n    EXPECT_LT(-10, samples(i,0));\n    EXPECT_GT(10, samples(i,0));\n  }\n}\n\nTEST(LaplaceTest, ExtremeSamples) {\n  Laplace<double> dist(0, 1);\n  Array<double> samples({3,1});\n  samples(0,0) = -1;\n  samples(1,0) = 0;\n  samples(2,0) = 1;\n\n  double w1[] = {1, 1, 10}, w2[] = {10, 1, 1};\n  auto indexes = Distribution<double>::sort_data(samples);\n\n  {\n    MA::ConstArray<double> weight({3}, w1);\n    dist.MLE(samples, weight, indexes);\n    EXPECT_LT(dist.get_mu(), samples(2,0));\n    EXPECT_GT(dist.get_mu(), samples(1,0));\n  }\n\n  {\n    MA::ConstArray<double> weight({3}, w2);\n    dist.MLE(samples, weight, indexes);\n    EXPECT_LT(dist.get_mu(), samples(1,0));\n    EXPECT_GT(dist.get_mu(), samples(0,0));\n  }\n}\n", "meta": {"hexsha": "0523dbb743935a0ee2fd375b3915a6248561d38e", "size": 2345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/laplace.cpp", "max_stars_repo_name": "mirandaconrado/probability-distributions", "max_stars_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/laplace.cpp", "max_issues_repo_name": "mirandaconrado/probability-distributions", "max_issues_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/laplace.cpp", "max_forks_repo_name": "mirandaconrado/probability-distributions", "max_forks_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4891304348, "max_line_length": 58, "alphanum_fraction": 0.6840085288, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6363456709622437}}
{"text": "#include \"util.hpp\"\n#include <armadillo>\n\n\nnamespace util{\n  /*\n    For a discrete probability distribution Pi = p(i), returns the index\n    of an element randomly selected by sampling the distribution.\n\n    Examples:\n    * sample_discrete({0.5, 0.5}) returns 0 or 1 with probability 0.5\n    * sample_discrete({0.0, 0.0, 1.0}) returns 2 with probability 1.0\n\n    Note:\n    While there does exist std::discrete_distribution, I think that the\n    below implementation is superior in that it does not require\n    instantiating a new distribution for every round.\n  */\n  arma::uword sample_discrete(const arma::vec &p){\n    /*\n      Sanity checks; require:\n      * Pi >= 0 forall i\n      * Sum(Pi) == 1\n      */\n    std::string die = \"\";\n    const double eps = 1e-12;\n    if (p.has_nan()){die = \"P is malformed; it contains NaN!\";}\n    if (arma::any(p < -1 * eps)){die = \"P cannot have negative elements!\";}\n    if (std::abs(arma::sum(p) - 1) > eps){ die = \"P is not normed!\";}\n\n    if (die != \"\"){\n      p.t().print(\"P\");\n      throw std::logic_error(die);\n    }\n\n    const double zeta = arma::randu();\n    return as_scalar(arma::find(arma::cumsum(p) > zeta, 1));\n  }\n\n\n  // return a uvec with filled with the indicies [a,b)\n  arma::uvec range(arma::uword a, arma::uword b){\n    if (a > b){\n      throw std::logic_error(\"cannot compute range with a > b\");\n    }\n\n    arma::uword N = b - a;\n    arma::uvec R(N, arma::fill::zeros);\n    for (arma::uword i = 0; i < N; i++){\n      R(i) = i + a;\n    }\n\n    return R;\n  }\n\n  // variant for [0, n)\n  arma::uvec range(arma::uword n){ return range(0, n); }\n\n\n  /*\n    std::hypot() for complex<double>\n\n    returns sqrt(|a|^2 + |b|^2)\n\n    I'm not sure what is the \"best\" sequence for the real() operations.\n    The present choice---to call real() twice, once after each\n    multiplication---was made because that's the first time the\n    opperands mathematically lie on the real line. Waiting longer seemed\n    to invite the accumulation of small numerical deviations.\n  */\n  double hypot(std::complex<double> a, std::complex<double> b){\n    return std::sqrt(std::real(std::conj(a)*a) + std::real(std::conj(b)*b) );\n  }\n\n\n  arma::vec center_of_mass(const arma::mat &R, const arma::vec &m){\n    // R.B.: sum(A,1) gives the sum of the elements of each row of A\n    return arma::sum(R.each_row() % m.t(), 1) / arma::sum(m);\n  }\n\n  /*\n    For the (3xN) configuration space vectors A, B, compute the sum of\n    the cross products of the vectors in each column: Sum(Ai X Bi)\n  */\n  arma::vec sum_cross(const arma::mat A, const arma::mat B){\n    if ((A.n_cols != B.n_cols) || (3 != A.n_rows) || (3 != B.n_rows)){\n      throw std::logic_error(\"Invalid dimension!\");\n    }\n\n    arma::vec sum(3, arma::fill::zeros);\n\n    for (arma::uword i = 0; i < A.n_cols; i++){\n      sum += arma::cross(A.col(i), B.col(i));\n    }\n\n    return sum;  \n  }\n}\n", "meta": {"hexsha": "5418888e6851459b381037c15514e38725091266", "size": 2870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gifs_src/util.cpp", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-11T19:48:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T19:48:20.000Z", "max_issues_repo_path": "gifs_src/util.cpp", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gifs_src/util.cpp", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 28.9898989899, "max_line_length": 77, "alphanum_fraction": 0.6048780488, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6363456709622436}}
{"text": "//  (C) Copyright John Maddock 2005-2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_TOOLS_STATS_INCLUDED\r\n#define BOOST_MATH_TOOLS_STATS_INCLUDED\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <cmath>\r\n#include <boost/cstdint.hpp>\r\n#include <boost/math/tools/precision.hpp>\r\n\r\nnamespace boost{ namespace math{ namespace tools{\r\n\r\ntemplate <class T>\r\nclass stats\r\n{\r\npublic:\r\n   stats()\r\n      : m_min(tools::max_value<T>()),\r\n        m_max(-tools::max_value<T>()),\r\n        m_total(0),\r\n        m_squared_total(0),\r\n        m_count(0)\r\n   {}\r\n   void add(const T& val)\r\n   {\r\n      if(val < m_min)\r\n         m_min = val;\r\n      if(val > m_max)\r\n         m_max = val;\r\n      m_total += val;\r\n      ++m_count;\r\n      m_squared_total += val*val;\r\n   }\r\n   T min BOOST_PREVENT_MACRO_SUBSTITUTION()const{ return m_min; }\r\n   T max BOOST_PREVENT_MACRO_SUBSTITUTION()const{ return m_max; }\r\n   T total()const{ return m_total; }\r\n   T mean()const{ return m_total / static_cast<T>(m_count); }\r\n   boost::uintmax_t count()const{ return m_count; }\r\n   T variance()const\r\n   {\r\n      BOOST_MATH_STD_USING\r\n\r\n      T t = m_squared_total - m_total * m_total / m_count;\r\n      t /= m_count;\r\n      return t;\r\n   }\r\n   T variance1()const\r\n   {\r\n      BOOST_MATH_STD_USING\r\n\r\n      T t = m_squared_total - m_total * m_total / m_count;\r\n      t /= (m_count-1);\r\n      return t;\r\n   }\r\n   T rms()const\r\n   {\r\n      BOOST_MATH_STD_USING\r\n\r\n      return sqrt(m_squared_total / static_cast<T>(m_count));\r\n   }\r\n   stats& operator+=(const stats& s)\r\n   {\r\n      if(s.m_min < m_min)\r\n         m_min = s.m_min;\r\n      if(s.m_max > m_max)\r\n         m_max = s.m_max;\r\n      m_total += s.m_total;\r\n      m_squared_total += s.m_squared_total;\r\n      m_count += s.m_count;\r\n      return *this;\r\n   }\r\nprivate:\r\n   T m_min, m_max, m_total, m_squared_total;\r\n   boost::uintmax_t m_count;\r\n};\r\n\r\n} // namespace tools\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "5e937e0cb46bd58698cb484d98809125f253f2a4", "size": 2120, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "windows/include/boost/math/tools/stats.hpp", "max_stars_repo_name": "jaredhoberock/gotham", "max_stars_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "windows/include/boost/math/tools/stats.hpp", "max_issues_repo_name": "jaredhoberock/gotham", "max_issues_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "windows/include/boost/math/tools/stats.hpp", "max_forks_repo_name": "jaredhoberock/gotham", "max_forks_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_forks_repo_licenses": ["Apache-2.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.8202247191, "max_line_length": 69, "alphanum_fraction": 0.6066037736, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6363456679913881}}
{"text": "// Copyright (c) 2013, Manuel Blum\n// All rights reserved.\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"nn.h\"\n\nTEST(nn, sigmoid1)\n{\n    matrix_t X(3,3);\n    matrix_t s(3,3);\n    X << -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2;\n    s <<  0.1192, 0.1824, 0.2689, 0.3775, 0.5, 0.6225, 0.7311, 0.8176, 0.8808;\n    matrix_t Y = NeuralNet::sigmoid(X);\n    ASSERT_NEAR((Y.array()-s.array()).maxCoeff(), 0.0, 1e-4);\n}\n\nTEST(nn, sigmoid2)\n{\n    matrix_t X = matrix_t::Random(100,200) * 2;\n    matrix_t Y = NeuralNet::sigmoid(X);\n    ASSERT_EQ(X.rows(), Y.rows());\n    ASSERT_EQ(X.cols(), Y.cols());\n\n    for (int i=0; i<X.rows(); ++i)\n    {\n        for (int j=0; j<X.cols(); ++j)\n        {\n            ASSERT_NEAR(Y(i,j), 1/(1+exp(-X(i,j))), 1e-7);\n        }\n    }\n}\n\nTEST(nn, sigmoid_gradient1)\n{\n    matrix_t X(3,3);\n    matrix_t s(3,3);\n    X << -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2;\n    s <<  0.105, 0.1491, 0.1966, 0.2350, 0.25, 0.2350, 0.1966, 0.1491, 0.1050;\n    matrix_t sig = NeuralNet::sigmoid(X);\n    matrix_t Y = NeuralNet::sigmoid_gradient(sig);\n    ASSERT_NEAR((Y.array()-s.array()).maxCoeff(), 0.0, 1e-4);\n}\n\nTEST(nn, sigmoid_gradient2)\n{\n    matrix_t X = matrix_t::Random(100,200) * 2;\n    matrix_t sig = NeuralNet::sigmoid(X);\n    matrix_t Y = NeuralNet::sigmoid_gradient(sig);\n    ASSERT_EQ(X.rows(), Y.rows());\n    ASSERT_EQ(X.cols(), Y.cols());\n\n    for (int i=0; i<X.rows(); ++i)\n    {\n        for (int j=0; j<X.cols(); ++j)\n        {\n            double sigmoid = 1/(1+exp(-X(i,j)));\n            ASSERT_NEAR(Y(i,j), sigmoid*(1-sigmoid), 1e-9);\n        }\n    }\n}\n\n// compare analytical with numerical gradients\nTEST(nn, gradient)\n{\n    Eigen::VectorXi topo(4);\n    topo << 3, 10, 10, 2;\n    NeuralNet nn(topo);\n    nn.init_weights(0.5);\n    int m = 100;\n    matrix_t X = matrix_t::Random(m,3);\n    matrix_t Y = matrix_t::Random(m,2);\n    Y = Y.array() * 0.4 + 0.5;\n    ASSERT_GE(Y.minCoeff(), 0.1);\n    ASSERT_LE(Y.maxCoeff(), 0.9);\n    double lambda = 0.01;\n    double e = 1e-4;\n    ASSERT_EQ(nn.layer[0].size, topo(0));\n\n    for (int i=1; i<nn.layer.size(); ++i)\n    {\n        ASSERT_EQ(nn.layer[i].W.rows(), nn.layer[i].size);\n        ASSERT_EQ(nn.layer[i].W.cols(), nn.layer[i-1].size);\n        ASSERT_EQ(nn.layer[i].b.rows(), nn.layer[i].size);\n        ASSERT_EQ(nn.layer[i].size, topo(i));\n\n        for (int j=0; j<nn.layer[i].W.rows(); ++j)\n        {\n            for (int k=0; k<nn.layer[i].W.cols(); ++k)\n            {\n                double w = nn.layer[i].W(j,k);\n                nn.layer[i].W(j,k) = w - e;\n                double j1 = nn.loss(X, Y, lambda);\n                nn.layer[i].W(j,k) = w + e;\n                double j2 = nn.loss(X, Y, lambda);\n                nn.layer[i].W(j,k) = w;\n                nn.loss(X, Y, lambda);\n                ASSERT_NEAR((j2-j1)/(2*e), nn.layer[i].dEdW(j,k), 1e-9);\n            }\n        }\n\n        for (int j=0; j<nn.layer[i].b.rows(); ++j)\n        {\n            double b = nn.layer[i].b(j);\n            nn.layer[i].b(j) = b - e;\n            double j1 = nn.loss(X, Y, lambda);\n            nn.layer[i].b(j) = b + e;\n            double j2 = nn.loss(X, Y, lambda);\n            nn.layer[i].b(j) = b;\n            nn.loss(X, Y, lambda);\n            ASSERT_NEAR((j2-j1)/(2*e), nn.layer[i].dEdb(j), 1e-9);\n        }\n    }\n}\n\nTEST(nn, readwrite)\n{\n    Eigen::VectorXi topo(4);\n    topo << 3, 10, 10, 2;\n    NeuralNet nn(topo);\n    nn.init_weights(0.5);\n    nn.write(\"testnet.nn\");\n    NeuralNet nnclone(\"testnet.nn\");\n    ASSERT_EQ(topo.size(), nnclone.layer.size());\n\n    for (int i=0; i<topo.size(); ++i)\n    {\n        ASSERT_EQ(topo(i), nnclone.layer[i].size);\n    }\n\n    for (int i=1; i<nn.layer.size(); ++i)\n    {\n        for (int j=0; j<nn.layer[i].W.rows(); ++j)\n        {\n            for (int k=0; k<nn.layer[i].W.cols(); ++k)\n            {\n                ASSERT_NEAR(nn.layer[i].W(j,k), nnclone.layer[i].W(j,k), 1e-12);\n            }\n        }\n\n        for (int j=0; j<nn.layer[i].b.rows(); ++j)\n        {\n            ASSERT_NEAR(nn.layer[i].b(j), nnclone.layer[i].b(j), 1e-12);\n        }\n    }\n}\n\nTEST(nn, testfunction)\n{\n    srand((unsigned int) time(NULL));\n    Eigen::VectorXi topo(4);\n    topo << 2, 10, 10, 1;\n    NeuralNet nn(topo);\n    matrix_t X = matrix_t::Random(1000,2);\n    matrix_t Y = matrix_t::Random(1000,1);\n\n    for (int i=0; i<X.rows(); ++i)\n    {\n        Y(i,0) = (X(i,0) * X(i,1) + 1.2)*0.4;\n    }\n\n    double lambda = 0.01, err;\n\n    for (int i=0; i<300; ++i)\n    {\n        err = nn.loss(X, Y, lambda);\n        nn.rprop();\n    }\n\n    ASSERT_LE(err, 0.01);\n    nn.write(\"testnet.nn\");\n    NeuralNet nnclone(\"testnet.nn\");\n    ASSERT_NEAR(nn.loss(X, Y, lambda), nnclone.loss(X, Y, lambda), 1e-12);\n}\n", "meta": {"hexsha": "46cdffe3bfb324449b1df0eb9795e8c983afbb24", "size": 4695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nntest.cpp", "max_stars_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_stars_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-05-27T11:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-12T14:57:31.000Z", "max_issues_repo_path": "nntest.cpp", "max_issues_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_issues_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nntest.cpp", "max_forks_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_forks_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-08-25T11:04:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-15T04:36:25.000Z", "avg_line_length": 26.6761363636, "max_line_length": 80, "alphanum_fraction": 0.4949946752, "num_tokens": 1639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6363067648770506}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"test-util.h\"\n\n#include <faiss/IndexFlat.h>\n#include <faiss/utils.h>\nBOOST_AUTO_TEST_SUITE(FlatIndex)\n/**\ntest the correctness of flat index using faiss flat index\n*/\nBOOST_AUTO_TEST_CASE(FP32FlatIndexCPU) {\n\tint64_t nb = 1024;\n\tint d = 64;\n\tstd::vector <float> database(nb * d);\n\tgenerate_float_vector(d, database.data(), nb);\n\tdecorate_float_vector(d, database.data(), nb);\n\tL2norm(d, database.data(), nb);\n\n\tstd::unique_ptr<faiss::Index> index;\n\tindex.reset(new faiss::IndexFlatL2(d));\n\tindex->add(nb, database.data());\n\n\tint64_t nq = 128;\n\tint k = 4;\n\tstd::vector<float> query(nq*d);\n\tgenerate_float_vector(d, query.data(), nq);\n\tdecorate_float_vector(d, query.data(), nq);\n\tL2norm(d, query.data(), nq);\n\n\tstd::vector<int64_t> I(k * nq);\n\tstd::vector<float> D(k * nq);\n\tindex->search(nq, query.data(), k, D.data(), I.data());\n\n\tstd::vector<int64_t> I_GT(k * nq);\n\tstd::vector<float> D_GT(k * nq);\n\tfor (int n1 = 0; n1 < nq; ++n1) {\n\t\tstd::vector<std::pair<float,int64_t>> pResult;\n\t\tfor (int64_t n2 = 0; n2 < nb; ++n2) {\n\t\t\tfloat* qv = query.data() + n1*d;\n\t\t\tfloat* rv = database.data() + n2*d;\n\t\t\tdouble sum=0;\n\t\t\tfor (int d1 = 0; d1 < d; ++d1,++qv,++rv) {\n\t\t\t\tfloat r=(*qv-*rv);\n\t\t\t\tsum += r*r;\n\t\t\t}\n\t\t\tpResult.push_back(std::make_pair((float)sum,n2));\n\t\t}\n\t\tstd::partial_sort(pResult.begin(),pResult.begin()+k,pResult.end(),[](const std::pair<float,long>& p1,\n\t\t\tconst std::pair<float,long>& p2)->bool{return p1.first<p2.first;});\n\t\tfor (int k1 = 0; k1 < k; ++k1) {\n\t\t\tI_GT[n1*k+k1] = pResult[k1].second;\n\t\t\tD_GT[n1*k+k1] = pResult[k1].first;\n\t\t}\n\t}\n\tint nNumOfInterSec=0;\n\tfor (int64_t n = 0; n < nq; ++n) {\n\t\tfor (int k1 = 0; k1 < k; k1++) {\n\t\t\tBOOST_CHECK(I_GT[n*k + k1] == I[n*k + k1]);\n\t\t}\n\t}\n}\n\n\nBOOST_AUTO_TEST_CASE(FP32FlatIndexGPU) {\n\tint64_t nb = 1024;\n\tint d = 64;\n\tstd::vector <float> database(nb * d);\n\tgenerate_float_vector(d, database.data(), nb);\n\tdecorate_float_vector(d, database.data(), nb);\n\tL2norm(d, database.data(), nb);\n\n\tstd::unique_ptr<faiss::Index> index;\n\tindex.reset(new faiss::GPU_IndexFlatL2(d));\n\tindex->add(nb, database.data());\n\n\tint64_t nq = 128;\n\tint k = 4;\n\tstd::vector<float> query(nq*d);\n\tgenerate_float_vector(d, query.data(), nq);\n\tdecorate_float_vector(d, query.data(), nq);\n\tL2norm(d, query.data(), nq);\n\n\tstd::vector<int64_t> I(k * nq);\n\tstd::vector<float> D(k * nq);\n\tindex->search(nq, query.data(), k, D.data(), I.data());\n\n\tstd::vector<int64_t> I_GT(k * nq);\n\tstd::vector<float> D_GT(k * nq);\n\tfor (int n1 = 0; n1 < nq; ++n1) {\n\t\tstd::vector<std::pair<float, int64_t>> pResult;\n\t\tfor (int64_t n2 = 0; n2 < nb; ++n2) {\n\t\t\tfloat* qv = query.data() + n1 * d;\n\t\t\tfloat* rv = database.data() + n2 * d;\n\t\t\tdouble sum = 0;\n\t\t\tfor (int d1 = 0; d1 < d; ++d1, ++qv, ++rv) {\n\t\t\t\tfloat r = (*qv - *rv);\n\t\t\t\tsum += r * r;\n\t\t\t}\n\t\t\tpResult.push_back(std::make_pair((float)sum, n2));\n\t\t}\n\t\tstd::partial_sort(pResult.begin(), pResult.begin() + k, pResult.end(), [](const std::pair<float, long>& p1,\n\t\t\tconst std::pair<float, long>& p2)->bool {return p1.first<p2.first; });\n\t\tfor (int k1 = 0; k1 < k; ++k1) {\n\t\t\tI_GT[n1*k + k1] = pResult[k1].second;\n\t\t\tD_GT[n1*k + k1] = pResult[k1].first;\n\t\t}\n\t}\n\tint nNumOfInterSec = 0;\n\tfor (int64_t n = 0; n < nq; ++n) {\n\t\tfor (int k1 = 0; k1 < k; k1++) {\n\t\t\tBOOST_CHECK(I_GT[n*k + k1] == I[n*k + k1]);\n\t\t}\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(FP16FlatIndexGPU) {\n\tint64_t nb = 1024;\n\tint d = 64;\n\tstd::vector <float> database(nb * d);\n\tgenerate_float_vector(d, database.data(), nb);\n\tdecorate_float_vector(d, database.data(), nb);\n\tL2norm(d, database.data(), nb);\n\n\tstd::unique_ptr<faiss::Index> index;\n\tindex.reset(new faiss::GPU_IndexFlatFP16L2(d));\n\tindex->add(nb, database.data());\n\n\tint64_t nq = 128;\n\tint k = 4;\n\tstd::vector<float> query(nq*d);\n\tgenerate_float_vector(d, query.data(), nq);\n\tdecorate_float_vector(d, query.data(), nq);\n\tL2norm(d, query.data(), nq);\n\n\tstd::vector<int64_t> I(k * nq);\n\tstd::vector<float> D(k * nq);\n\tindex->search(nq, query.data(), k, D.data(), I.data());\n\n\tstd::vector<int64_t> I_GT(k * nq);\n\tstd::vector<float> D_GT(k * nq);\n\tfor (int n1 = 0; n1 < nq; ++n1) {\n\t\tstd::vector<std::pair<float, int64_t>> pResult;\n\t\tfor (int64_t n2 = 0; n2 < nb; ++n2) {\n\t\t\tfloat* qv = query.data() + n1 * d;\n\t\t\tfloat* rv = database.data() + n2 * d;\n\t\t\tdouble sum = 0;\n\t\t\tfor (int d1 = 0; d1 < d; ++d1, ++qv, ++rv) {\n\t\t\t\tfloat r = (*qv - *rv);\n\t\t\t\tsum += r * r;\n\t\t\t}\n\t\t\tpResult.push_back(std::make_pair((float)sum, n2));\n\t\t}\n\t\tstd::partial_sort(pResult.begin(), pResult.begin() + k, pResult.end(), [](const std::pair<float, long>& p1,\n\t\t\tconst std::pair<float, long>& p2)->bool {return p1.first<p2.first; });\n\t\tfor (int k1 = 0; k1 < k; ++k1) {\n\t\t\tI_GT[n1*k + k1] = pResult[k1].second;\n\t\t\tD_GT[n1*k + k1] = pResult[k1].first;\n\t\t}\n\t}\n\tint nNumOfInterSec=0;\n\tfor (int n = 0; n < nq; ++n) {\n\t\t//check intersection\n\t\tstd::vector<int64_t> GT_Labels;\n\t\tstd::vector<int64_t> Labels;\n\t\tfor (int m = 0; m < k; ++m) {\n\t\t\tGT_Labels.push_back(I_GT[n * 4 + m]);\n\t\t\tLabels.push_back(I[n * 4 + m]);\n\t\t}\n\t\tstd::sort(GT_Labels.begin(), GT_Labels.end());\n\t\tstd::sort(Labels.begin(), Labels.end());\n\t\tstd::vector<int> v(2 * k);\n\t\tauto itr = std::set_intersection(GT_Labels.begin(), GT_Labels.end(), Labels.begin(), Labels.end(), v.begin());\n\t\tv.resize(itr - v.begin());\n\t\tnNumOfInterSec += v.size();\n\t}\n\tBOOST_TEST_MESSAGE(\"GPU fp16 flat index search results is \" << nNumOfInterSec*100.0f / (nq * k) << \"% close to that of CPU fp32 flat index \");\n}\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "40b66d0e8f47915defe1b0a2ed520ca9a95bafeb", "size": 5484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test-flatindex.cpp", "max_stars_repo_name": "bitsun/faiss-windows", "max_stars_repo_head_hexsha": "4ecd22981f8473ecd213a740264873ac0dbc083e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2019-01-20T22:14:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T08:08:32.000Z", "max_issues_repo_path": "tests/test-flatindex.cpp", "max_issues_repo_name": "anthonyaue/faiss-windows", "max_issues_repo_head_hexsha": "47486c44cab3badf52be4ed8dd9ec6d692212bcc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-01-16T08:16:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-15T16:30:17.000Z", "max_forks_repo_path": "tests/test-flatindex.cpp", "max_forks_repo_name": "bitsun/faiss-windows", "max_forks_repo_head_hexsha": "4ecd22981f8473ecd213a740264873ac0dbc083e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-05-17T13:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-18T01:18:33.000Z", "avg_line_length": 30.9830508475, "max_line_length": 143, "alphanum_fraction": 0.6143326039, "num_tokens": 1940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6363067553253456}}
{"text": "/*\n * Copyright Nick Thompson, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <random>\n#include <array>\n#include <vector>\n#include <boost/math/interpolators/cubic_hermite.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/circular_buffer.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\n\nusing boost::math::interpolators::cubic_hermite;\nusing boost::math::interpolators::cardinal_cubic_hermite;\nusing boost::math::interpolators::cardinal_cubic_hermite_aos;\n\n\ntemplate<typename Real>\nvoid test_constant()\n{\n    Real x0 = 0;\n    std::vector<Real> x{x0,1,2,3, 9, 22, 81};\n    std::vector<Real> y(x.size());\n    for (auto & t : y)\n    {\n        t = 7;\n    }\n\n    std::vector<Real> dydx(x.size(), Real(0));\n    auto x_copy = x;\n    auto y_copy = y;\n    auto dydx_copy = dydx;\n    auto hermite_spline = cubic_hermite(std::move(x_copy), std::move(y_copy), std::move(dydx_copy));\n\n    // Now check the boundaries:\n    Real tlo = x.front();\n    Real thi = x.back();\n    int samples = 5000;\n    int i = 0;\n    while (i++ < samples)\n    {\n        CHECK_ULP_CLOSE(Real(7), hermite_spline(tlo), 2);\n        CHECK_ULP_CLOSE(Real(7), hermite_spline(thi), 2);\n        CHECK_ULP_CLOSE(Real(0), hermite_spline.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(0), hermite_spline.prime(thi), 2);\n        tlo = boost::math::nextafter(tlo, (std::numeric_limits<Real>::max)());\n        thi = boost::math::nextafter(thi, std::numeric_limits<Real>::lowest());\n    }\n\n    boost::circular_buffer<Real> x_buf(x.size());\n    for (auto & t : x) {\n        x_buf.push_back(t);\n    }\n\n    boost::circular_buffer<Real> y_buf(x.size());\n    for (auto & t : y) {\n        y_buf.push_back(t);\n    }\n\n    boost::circular_buffer<Real> dydx_buf(x.size());\n    for (auto & t : dydx) {\n        dydx_buf.push_back(t);\n    }\n\n    auto circular_hermite_spline = cubic_hermite(std::move(x_buf), std::move(y_buf), std::move(dydx_buf));\n\n    for (Real t = x[0]; t <= x.back(); t += 0.25) {\n        CHECK_ULP_CLOSE(Real(7), circular_hermite_spline(t), 2);\n        CHECK_ULP_CLOSE(Real(0), circular_hermite_spline.prime(t), 2);\n    }\n\n    circular_hermite_spline.push_back(x.back() + 1, 7, 0);\n    CHECK_ULP_CLOSE(Real(0), circular_hermite_spline.prime(x.back()+1), 2);\n\n}\n\ntemplate<typename Real>\nvoid test_linear()\n{\n    std::vector<Real> x{0,1,2,3};\n    std::vector<Real> y{0,1,2,3};\n    std::vector<Real> dydx{1,1,1,1};\n\n    auto x_copy = x;\n    auto y_copy = y;\n    auto dydx_copy = dydx;\n    auto hermite_spline = cubic_hermite(std::move(x_copy), std::move(y_copy), std::move(dydx_copy));\n\n    CHECK_ULP_CLOSE(y[0], hermite_spline(x[0]), 0);\n    CHECK_ULP_CLOSE(Real(1)/Real(2), hermite_spline(Real(1)/Real(2)), 10);\n    CHECK_ULP_CLOSE(y[1], hermite_spline(x[1]), 0);\n    CHECK_ULP_CLOSE(Real(3)/Real(2), hermite_spline(Real(3)/Real(2)), 10);\n    CHECK_ULP_CLOSE(y[2], hermite_spline(x[2]), 0);\n    CHECK_ULP_CLOSE(Real(5)/Real(2), hermite_spline(Real(5)/Real(2)), 10);\n    CHECK_ULP_CLOSE(y[3], hermite_spline(x[3]), 0);\n\n    x.resize(45);\n    y.resize(45);\n    dydx.resize(45);\n    for (size_t i = 0; i < x.size(); ++i) {\n        x[i] = i;\n        y[i] = i;\n        dydx[i] = 1;\n    }\n\n    x_copy = x;\n    y_copy = y;\n    dydx_copy = dydx;\n    hermite_spline = cubic_hermite(std::move(x_copy), std::move(y_copy), std::move(dydx_copy));\n    for (Real t = 0; t < x.back(); t += 0.5) {\n        CHECK_ULP_CLOSE(t, hermite_spline(t), 0);\n        CHECK_ULP_CLOSE(Real(1), hermite_spline.prime(t), 0);\n    }\n\n    boost::circular_buffer<Real> x_buf(x.size());\n    for (auto & t : x) {\n        x_buf.push_back(t);\n    }\n\n    boost::circular_buffer<Real> y_buf(x.size());\n    for (auto & t : y) {\n        y_buf.push_back(t);\n    }\n\n    boost::circular_buffer<Real> dydx_buf(x.size());\n    for (auto & t : dydx) {\n        dydx_buf.push_back(t);\n    }\n\n    auto circular_hermite_spline = cubic_hermite(std::move(x_buf), std::move(y_buf), std::move(dydx_buf));\n\n    for (Real t = x[0]; t <= x.back(); t += 0.25) {\n        CHECK_ULP_CLOSE(t, circular_hermite_spline(t), 2);\n        CHECK_ULP_CLOSE(Real(1), circular_hermite_spline.prime(t), 2);\n    }\n\n    circular_hermite_spline.push_back(x.back() + 1, y.back()+1, 1);\n\n    CHECK_ULP_CLOSE(Real(y.back() + 1), circular_hermite_spline(Real(x.back()+1)), 2);\n    CHECK_ULP_CLOSE(Real(1), circular_hermite_spline.prime(Real(x.back()+1)), 2);\n\n}\n\ntemplate<typename Real>\nvoid test_quadratic()\n{\n    std::vector<Real> x(50);\n    std::default_random_engine rd;\n    std::uniform_real_distribution<Real> dis(0.1,1);\n    Real x0 = dis(rd);\n    x[0] = x0;\n    for (size_t i = 1; i < x.size(); ++i) {\n        x[i] = x[i-1] + dis(rd);\n    }\n    Real xmax = x.back();\n\n    std::vector<Real> y(x.size());\n    std::vector<Real> dydx(x.size());\n    for (size_t i = 0; i < x.size(); ++i) {\n        y[i] = x[i]*x[i]/2;\n        dydx[i] = x[i];\n    }\n\n    auto s = cubic_hermite(std::move(x), std::move(y), std::move(dydx));\n    for (Real t = x0; t <= xmax; t+= 0.0125)\n    {\n        CHECK_ULP_CLOSE(t*t/2, s(t), 5);\n        CHECK_ULP_CLOSE(t, s.prime(t), 138);\n    }\n}\n\ntemplate<typename Real>\nvoid test_interpolation_condition()\n{\n    for (size_t n = 4; n < 50; ++n) {\n        std::vector<Real> x(n);\n        std::vector<Real> y(n);\n        std::vector<Real> dydx(n);\n        std::default_random_engine rd;\n        std::uniform_real_distribution<Real> dis(0,1);\n        Real x0 = dis(rd);\n        x[0] = x0;\n        y[0] = dis(rd);\n        for (size_t i = 1; i < n; ++i) {\n            x[i] = x[i-1] + dis(rd);\n            y[i] = dis(rd);\n            dydx[i] = dis(rd);\n        }\n\n        auto x_copy = x;\n        auto y_copy = y;\n        auto dydx_copy = dydx;\n        auto s = cubic_hermite(std::move(x_copy), std::move(y_copy), std::move(dydx_copy));\n        //std::cout << \"s = \" << s << \"\\n\";\n        for (size_t i = 0; i < x.size(); ++i) {\n            CHECK_ULP_CLOSE(y[i], s(x[i]), 2);\n            CHECK_ULP_CLOSE(dydx[i], s.prime(x[i]), 2);\n        }\n    }\n}\n\ntemplate<typename Real>\nvoid test_cardinal_constant()\n{\n    Real x0 = 0;\n    Real dx = 2;\n    std::vector<Real> y(25);\n    for (auto & t : y) {\n        t = 7;\n    }\n\n    std::vector<Real> dydx(y.size(), Real(0));\n\n    auto hermite_spline = cardinal_cubic_hermite(std::move(y), std::move(dydx), x0, dx);\n\n    for (Real t = x0; t <= x0 + 24*dx; t += 0.25) {\n        CHECK_ULP_CLOSE(Real(7), hermite_spline(t), 2);\n        CHECK_ULP_CLOSE(Real(0), hermite_spline.prime(t), 2);\n    }\n\n    // Array of structs:\n\n    std::vector<std::array<Real, 2>> data(25);\n    for (auto & t : data) {\n        t[0] = 7;\n        t[1] = 0;\n    }\n    auto hermite_spline_aos = cardinal_cubic_hermite_aos(std::move(data), x0, dx);\n\n    for (Real t = x0; t <= x0 + 24*dx; t += 0.25) {\n        if (!CHECK_ULP_CLOSE(Real(7), hermite_spline_aos(t), 2)) {\n            std::cerr << \"  Wrong evaluation at t = \" << t << \"\\n\";\n        }\n        if (!CHECK_ULP_CLOSE(Real(0), hermite_spline_aos.prime(t), 2)) {\n            std::cerr << \"  Wrong evaluation at t = \" << t << \"\\n\";\n        }\n    }\n\n    // Now check the boundaries:\n    Real tlo = x0;\n    Real thi = x0 + (25-1)*dx;\n    int samples = 5000;\n    int i = 0;\n    while (i++ < samples)\n    {\n        CHECK_ULP_CLOSE(Real(7), hermite_spline(tlo), 2);\n        CHECK_ULP_CLOSE(Real(7), hermite_spline(thi), 2);\n        CHECK_ULP_CLOSE(Real(7), hermite_spline_aos(tlo), 2);\n        CHECK_ULP_CLOSE(Real(7), hermite_spline_aos(thi), 2);\n        CHECK_ULP_CLOSE(Real(0), hermite_spline.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(0), hermite_spline.prime(thi), 2);\n        CHECK_ULP_CLOSE(Real(0), hermite_spline_aos.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(0), hermite_spline_aos.prime(thi), 2);\n\n        tlo = boost::math::nextafter(tlo, (std::numeric_limits<Real>::max)());\n        thi = boost::math::nextafter(thi, std::numeric_limits<Real>::lowest());\n    }\n\n}\n\n\ntemplate<typename Real>\nvoid test_cardinal_linear()\n{\n    Real x0 = 0;\n    Real dx = 1;\n    std::vector<Real> y{0,1,2,3};\n    std::vector<Real> dydx{1,1,1,1};\n    auto y_copy = y;\n    auto dydx_copy = dydx;\n    auto hermite_spline = cardinal_cubic_hermite(std::move(y_copy), std::move(dydx_copy), x0, dx);\n\n    CHECK_ULP_CLOSE(y[0], hermite_spline(0), 0);\n    CHECK_ULP_CLOSE(Real(1)/Real(2), hermite_spline(Real(1)/Real(2)), 10);\n    CHECK_ULP_CLOSE(y[1], hermite_spline(1), 0);\n    CHECK_ULP_CLOSE(Real(3)/Real(2), hermite_spline(Real(3)/Real(2)), 10);\n    CHECK_ULP_CLOSE(y[2], hermite_spline(2), 0);\n    CHECK_ULP_CLOSE(Real(5)/Real(2), hermite_spline(Real(5)/Real(2)), 10);\n    CHECK_ULP_CLOSE(y[3], hermite_spline(3), 0);\n\n\n    y.resize(45);\n    dydx.resize(45);\n    for (size_t i = 0; i < y.size(); ++i) {\n        y[i] = i;\n        dydx[i] = 1;\n    }\n\n    hermite_spline = cardinal_cubic_hermite(std::move(y), std::move(dydx), x0, dx);\n    for (Real t = 0; t < 44; t += 0.5) {\n        CHECK_ULP_CLOSE(t, hermite_spline(t), 0);\n        CHECK_ULP_CLOSE(Real(1), hermite_spline.prime(t), 0);\n    }\n\n    std::vector<std::array<Real, 2>> data(45);\n    for (size_t i = 0; i < data.size(); ++i) {\n        data[i][0] = i;\n        data[i][1] = 1;\n    }\n\n    auto hermite_spline_aos = cardinal_cubic_hermite_aos(std::move(data), x0, dx);\n    for (Real t = 0; t < 44; t += 0.5) {\n        CHECK_ULP_CLOSE(t, hermite_spline_aos(t), 0);\n        CHECK_ULP_CLOSE(Real(1), hermite_spline_aos.prime(t), 0);\n    }\n\n    Real tlo = x0;\n    Real thi = x0 + (45-1)*dx;\n    int samples = 5000;\n    int i = 0;\n    while (i++ < samples)\n    {\n        CHECK_ULP_CLOSE(Real(tlo), hermite_spline(tlo), 2);\n        CHECK_ULP_CLOSE(Real(thi), hermite_spline(thi), 2);\n        CHECK_ULP_CLOSE(Real(1), hermite_spline.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(1), hermite_spline.prime(thi), 2);\n        CHECK_ULP_CLOSE(Real(tlo), hermite_spline_aos(tlo), 2);\n        CHECK_ULP_CLOSE(Real(thi), hermite_spline_aos(thi), 2);\n        CHECK_ULP_CLOSE(Real(1), hermite_spline_aos.prime(tlo), 2);\n        CHECK_ULP_CLOSE(Real(1), hermite_spline_aos.prime(thi), 2);\n\n        tlo = boost::math::nextafter(tlo, (std::numeric_limits<Real>::max)());\n        thi = boost::math::nextafter(thi, std::numeric_limits<Real>::lowest());\n    }\n\n\n}\n\n\ntemplate<typename Real>\nvoid test_cardinal_quadratic()\n{\n    Real x0 = -1;\n    Real dx = Real(1)/Real(256);\n\n    std::vector<Real> y(50);\n    std::vector<Real> dydx(y.size());\n    for (size_t i = 0; i < y.size(); ++i) {\n        Real x = x0 + i*dx;\n        y[i] = x*x/2;\n        dydx[i] = x;\n    }\n\n    auto s = cardinal_cubic_hermite(std::move(y), std::move(dydx), x0, dx);\n    for (Real t = x0; t <= x0 + 49*dx; t+= 0.0125)\n    {\n        CHECK_ULP_CLOSE(t*t/2, s(t), 12);\n        CHECK_ULP_CLOSE(t, s.prime(t), 70);\n    }\n\n    std::vector<std::array<Real, 2>> data(50);\n    for (size_t i = 0; i < data.size(); ++i) {\n        Real x = x0 + i*dx;\n        data[i][0] = x*x/2;\n        data[i][1] = x;\n    }\n\n\n    auto saos = cardinal_cubic_hermite_aos(std::move(data), x0, dx);\n    for (Real t = x0; t <= x0 + 49*dx; t+= 0.0125)\n    {\n        CHECK_ULP_CLOSE(t*t/2, saos(t), 12);\n        CHECK_ULP_CLOSE(t, saos.prime(t), 70);\n    }\n\n    auto [tlo, thi] = s.domain();\n    int samples = 5000;\n    int i = 0;\n    while (i++ < samples)\n    {\n        CHECK_ULP_CLOSE(Real(tlo*tlo/2), s(tlo), 3);\n        CHECK_ULP_CLOSE(Real(thi*thi/2), s(thi), 3);\n        CHECK_ULP_CLOSE(Real(tlo), s.prime(tlo), 3);\n        CHECK_ULP_CLOSE(Real(thi), s.prime(thi), 3);\n        CHECK_ULP_CLOSE(Real(tlo*tlo/2), saos(tlo), 3);\n        CHECK_ULP_CLOSE(Real(thi*thi/2), saos(thi), 3);\n        CHECK_ULP_CLOSE(Real(tlo), saos.prime(tlo), 3);\n        CHECK_ULP_CLOSE(Real(thi), saos.prime(thi), 3);\n\n        tlo = boost::math::nextafter(tlo, (std::numeric_limits<Real>::max)());\n        thi = boost::math::nextafter(thi, std::numeric_limits<Real>::lowest());\n    }\n}\n\n\ntemplate<typename Real>\nvoid test_cardinal_interpolation_condition()\n{\n    for (size_t n = 4; n < 50; ++n) {\n        std::vector<Real> y(n);\n        std::vector<Real> dydx(n);\n        std::default_random_engine rd;\n        std::uniform_real_distribution<Real> dis(0.1,1);\n        Real x0 = Real(2);\n        Real dx = Real(1)/Real(128);\n        for (size_t i = 0; i < n; ++i) {\n            y[i] = dis(rd);\n            dydx[i] = dis(rd);\n        }\n\n        auto y_copy = y;\n        auto dydx_copy = dydx;\n        auto s = cardinal_cubic_hermite(std::move(y_copy), std::move(dydx_copy), x0, dx);\n        for (size_t i = 0; i < y.size(); ++i) {\n            CHECK_ULP_CLOSE(y[i], s(x0 + i*dx), 2);\n            CHECK_ULP_CLOSE(dydx[i], s.prime(x0 + i*dx), 2);\n        }\n    }\n}\n\n\n\nint main()\n{\n    test_constant<float>();\n    test_linear<float>();\n    test_quadratic<float>();\n    test_interpolation_condition<float>();\n    test_cardinal_constant<float>();\n    test_cardinal_linear<float>();\n    test_cardinal_quadratic<float>();\n    test_cardinal_interpolation_condition<float>();\n\n    test_constant<double>();\n    test_linear<double>();\n    test_quadratic<double>();\n    test_interpolation_condition<double>();\n    test_cardinal_constant<double>();\n    test_cardinal_linear<double>();\n    test_cardinal_quadratic<double>();\n    test_cardinal_interpolation_condition<double>();\n\n    test_constant<long double>();\n    test_linear<long double>();\n    test_quadratic<long double>();\n    test_interpolation_condition<long double>();\n    test_cardinal_constant<long double>();\n    test_cardinal_linear<long double>();\n    test_cardinal_quadratic<long double>();\n    test_cardinal_interpolation_condition<long double>();\n\n\n#ifdef BOOST_HAS_FLOAT128\n    test_constant<float128>();\n    test_linear<float128>();\n    test_cardinal_constant<float128>();\n    test_cardinal_linear<float128>();\n#endif\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "a8ded3990471e572c8d2dd6e1c57ccd40eed047d", "size": 14036, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cubic_hermite_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/cubic_hermite_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/cubic_hermite_test.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 30.380952381, "max_line_length": 106, "alphanum_fraction": 0.5918352807, "num_tokens": 4550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.6363067525547564}}
{"text": "/*\n * math.hpp\n *\n *  Created on: Apr 26, 2021\n *      Author: jelavice\n */\n#pragma once\n#include <cmath>\n#include <vector>\n\n#include <Eigen/Core>\n\nnamespace icp_loco{\n\n// Clamps 'value' to be in the range ['min', 'max'].\ntemplate <typename T>\nT Clamp(const T value, const T min, const T max) {\n  if (value > max) {\n    return max;\n  }\n  if (value < min) {\n    return min;\n  }\n  return value;\n}\n\n// Calculates 'base'^'exponent'.\ntemplate <typename T>\nconstexpr T Power(T base, int exponent) {\n  return (exponent != 0) ? base * Power(base, exponent - 1) : T(1);\n}\n\n// Calculates a^2.\ntemplate <typename T>\nconstexpr T Pow2(T a) {\n  return Power(a, 2);\n}\n\n// Converts from degrees to radians.\nconstexpr double DegToRad(double deg) { return M_PI * deg / 180.; }\n\n// Converts form radians to degrees.\nconstexpr double RadToDeg(double rad) { return 180. * rad / M_PI; }\n\n// Bring the 'difference' between two angles into [-pi; pi].\ntemplate <typename T>\nT NormalizeAngleDifference(T difference) {\n  const T kPi = T(M_PI);\n  while (difference > kPi) difference -= 2. * kPi;\n  while (difference < -kPi) difference += 2. * kPi;\n  return difference;\n}\n\ntemplate <typename T>\nT atan2(const Eigen::Matrix<T, 2, 1>& vector) {\n  return std::atan2(vector.y(), vector.x());\n}\n\ntemplate <typename T>\ninline void QuaternionProduct(const double* const z, const T* const w,\n                              T* const zw) {\n  zw[0] = z[0] * w[0] - z[1] * w[1] - z[2] * w[2] - z[3] * w[3];\n  zw[1] = z[0] * w[1] + z[1] * w[0] + z[2] * w[3] - z[3] * w[2];\n  zw[2] = z[0] * w[2] - z[1] * w[3] + z[2] * w[0] + z[3] * w[1];\n  zw[3] = z[0] * w[3] + z[1] * w[2] - z[2] * w[1] + z[3] * w[0];\n}\n\n\n} //icp_loco\n", "meta": {"hexsha": "273dc557183798b15a97b5cca8991c58d1f2ae82", "size": 1677, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/icp_localization/transform/math.hpp", "max_stars_repo_name": "ibrahimhroob/icp_localization", "max_stars_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 72.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T09:05:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T08:21:07.000Z", "max_issues_repo_path": "include/icp_localization/transform/math.hpp", "max_issues_repo_name": "ibrahimhroob/icp_localization", "max_issues_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-09T20:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T09:54:42.000Z", "max_forks_repo_path": "include/icp_localization/transform/math.hpp", "max_forks_repo_name": "ibrahimhroob/icp_localization", "max_forks_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T09:18:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T03:14:10.000Z", "avg_line_length": 23.9571428571, "max_line_length": 70, "alphanum_fraction": 0.5891472868, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915616, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6363010787466705}}
{"text": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Molassembler/Temple/Adaptors/Zip.h\"\n#include \"Molassembler/Temple/Functional.h\"\n#include \"Molassembler/Temple/Random.h\"\n#include \"Molassembler/Temple/Stringify.h\"\n#include \"Molassembler/Temple/constexpr/Array.h\"\n#include \"Molassembler/Temple/constexpr/BTree.h\"\n#include \"Molassembler/Temple/constexpr/Jsf.h\"\n\n#include <set>\n#include <iostream>\n\nusing namespace Scine::Molassembler;\n\nextern Temple::Generator<> generator;\n\nnamespace BTreeStaticTests {\n\nconstexpr Temple::BTree<unsigned, 3, 20> generateTree() {\n  Temple::BTree<unsigned, 3, 20> tree;\n\n  tree.insert(9);\n  tree.insert(3);\n  tree.insert(5);\n  tree.insert(20);\n\n  return tree;\n}\n\nconstexpr auto testTree = generateTree();\nstatic_assert(testTree.size() == 4, \"Size of generated tree is wrong!\");\n\nstatic_assert(\n  /* BTree of minimum order 3 has max 5 keys per node and max 6 children per node\n   *\n   * height  nodes       keys\n   * 0       1           5\n   * 1       1 + 6       5 + 6*5\n   * 2       1 + 6 + 36  5 + 6*5 + 36*5\n   *\n   * #nodes(h) = sum_{i = 0}^{h} (2t)^i\n   *\n   *     (2t)^{h + 1} - 1\n   *  N = ----------------\n   *         2t - 1\n   *\n   * -> N * (2t - 1) + 1 = (2t)^{h + 1}\n   *\n   * -> log_2t [N * (2t - 1) + 1] = h + 1\n   *\n   * -> h = log_2t [N * (2t - 1) + 1] - 1\n   *\n   */\n  Temple::BTreeProperties::minHeight(5, 3) == 0\n  && Temple::BTreeProperties::minHeight(35, 3) == 1\n  && Temple::BTreeProperties::minHeight(215, 3) == 2,\n  \"minHeight function is wrong\"\n);\n\nstatic_assert(\n  Temple::BTreeProperties::maxNodesInTree(0, 3) == 1\n  && Temple::BTreeProperties::maxNodesInTree(1, 3) == 7\n  && Temple::BTreeProperties::maxNodesInTree(2, 3) == 43\n  && Temple::BTreeProperties::maxNodesInTree(3, 3) == 259,\n  \"maxNodesInTree is wrong\"\n);\n\n} // namespace BTreeStaticTests\n\ninline unsigned popRandom(std::set<unsigned>& values) {\n  auto it = values.begin();\n\n  std::advance(\n    it,\n    Temple::Random::getSingle<unsigned>(0, values.size() - 1, generator.engine)\n  );\n\n  auto value = *it;\n\n  values.erase(it);\n\n  return value;\n}\n\nBOOST_AUTO_TEST_CASE(ConstexprBTree, *boost::unit_test::label(\"Temple\")) {\n  constexpr unsigned nKeys = 100;\n\n  using namespace std::string_literals;\n\n  std::vector<unsigned> values (nKeys);\n\n  std::iota(\n    values.begin(),\n    values.end(),\n    0\n  );\n\n  std::set<unsigned> notInTree {values.begin(), values.end()};\n  std::set<unsigned> inTree;\n\n  Temple::BTree<unsigned, 3, nKeys> tree;\n\n  std::string lastTreeGraph;\n\n  std::vector<std::string> decisions;\n\n  auto addElement = [&](const std::string& treeGraph) {\n    // Add an element\n    auto toAdd = popRandom(notInTree);\n    decisions.emplace_back(\"i\"s + std::to_string(toAdd));\n\n    BOOST_TEST_CONTEXT(\n      \"Element insertion threw. Operation sequence: \"\n      << Temple::condense(decisions)\n      << \". Prior to last operation: \\n\"\n      << treeGraph << \"\\n\\n After last operation: \\n\"\n      << tree.dumpGraphviz()\n    ) {\n      BOOST_REQUIRE_NO_THROW(tree.insert(toAdd));\n    }\n\n    inTree.insert(toAdd);\n  };\n\n  auto removeElement = [&](const std::string& treeGraph) {\n    // Remove an element\n    auto toRemove = popRandom(inTree);\n    decisions.emplace_back(\"r\"s + std::to_string(toRemove));\n\n    BOOST_TEST_CONTEXT(\n      \"Tree element removal failed. Operation sequence: \"\n        << Temple::condense(decisions)\n        << \". Prior to last operation: \\n\"\n        << treeGraph << \"\\n\\n After last operation: \\n\"\n        << tree.dumpGraphviz()\n    ) {\n      BOOST_REQUIRE_NO_THROW(tree.remove(toRemove));\n    }\n\n    notInTree.insert(toRemove);\n  };\n\n  auto fullValidation = [&](const std::string& treeGraph) {\n    // Validate the tree\n    BOOST_TEST_CONTEXT(\n      \"Tree validation failed. Operation sequence: \"\n        << Temple::condense(decisions)\n        << \". Prior to last operation: \\n\"\n        << treeGraph << \"\\n\\n After last operation: \\n\"\n        << tree.dumpGraphviz()\n    ) {\n      BOOST_REQUIRE_NO_THROW(tree.validate());\n    }\n\n    // Check that elements that weren't inserted aren't falsely contained\n    auto notInsertedButContained = Temple::copy_if(\n      notInTree,\n      [&](const auto& notInTreeValue) -> bool {\n        return tree.contains(notInTreeValue);\n      }\n    );\n\n    // Check that all elements are truly contained or not\n    BOOST_REQUIRE_MESSAGE(\n      notInsertedButContained.empty(),\n      \"Not all elements recorded as not in the tree are recognized as such!\\n\"\n        << \"Found in the tree, but should not be present: \"\n        << Temple::condense(notInsertedButContained)\n        << \"\\nSequence of operations: \"\n        << Temple::condense(decisions)\n        << \". Prior to last operation: \\n\"\n        << treeGraph << \"\\n\\n After last operation: \\n\"\n        << tree.dumpGraphviz()\n    );\n\n    auto insertedNotContained = Temple::copy_if(\n      inTree,\n      [&](const auto& inTreeValue) -> bool {\n        return !tree.contains(inTreeValue);\n      }\n    );\n\n    BOOST_REQUIRE_MESSAGE(\n      insertedNotContained.empty(),\n      \"Not all elements recorded as contained in the tree are recognized as such!\\n\"\n        << \"Not found in the tree: \"\n        << Temple::condense(insertedNotContained)\n        << \"\\nSequence of operations: \"\n        << Temple::condense(decisions)\n        << \". Prior to last operation: \\n\"\n        << treeGraph << \"\\n\\n After last operation: \\n\"\n        << tree.dumpGraphviz()\n    );\n  };\n\n  for(unsigned i = 0; i < 10; ++i) {\n    decisions.clear();\n\n    // Heavy insert-delete workload\n    for(unsigned nSteps = 0; nSteps < 1000; ++nSteps) {\n      lastTreeGraph = tree.dumpGraphviz();\n\n      // Decide whether to insert or remove a random item\n      auto decisionFloat = Temple::Random::getSingle<double>(0.0, 1.0, generator.engine);\n      if(decisionFloat >= static_cast<double>(inTree.size()) / nKeys) {\n        addElement(lastTreeGraph);\n      } else {\n        removeElement(lastTreeGraph);\n      }\n\n      fullValidation(lastTreeGraph);\n    }\n\n    BOOST_REQUIRE_MESSAGE(\n      Temple::all_of(\n        Temple::Adaptors::zip(tree, inTree),\n        [&](const unsigned treeValue, const unsigned testValue) -> bool {\n          if(treeValue != testValue) {\n            std::cout << \"Expected \" << testValue << \", got \" << treeValue << std::endl;\n            return false;\n          }\n\n          return true;\n        }\n      ),\n      \"BTree through-iteration does not yield the same elements as expected!\\n\"\n        << tree.dumpGraphviz()\n    );\n\n    // Fill'er up all the way\n    while(inTree.size() != nKeys) {\n      lastTreeGraph = tree.dumpGraphviz();\n\n      addElement(lastTreeGraph);\n      fullValidation(lastTreeGraph);\n    }\n\n    // Empty the tree\n    while(!inTree.empty()) {\n      lastTreeGraph = tree.dumpGraphviz();\n\n      removeElement(lastTreeGraph);\n      fullValidation(lastTreeGraph);\n    }\n  }\n}\n\nnamespace {\n\n/* Test that if a BTree is instantiated with a specific size, that size\n * definitely fits in the tree\n */\n\ntemplate<size_t minOrder, size_t nElements>\nconstexpr bool BTreeAllocatedSizeSufficient() {\n  Temple::BTree<unsigned, minOrder, nElements> tree;\n\n  for(unsigned i = 0; i < nElements; ++i) {\n    tree.insert(i);\n  }\n\n  return true;\n}\n\ntemplate<size_t minOrder, size_t ... nElements>\nconstexpr bool testAllBTrees(std::index_sequence<nElements...> /* elements */) {\n  Temple::Array<bool, sizeof...(nElements)> results {{\n    BTreeAllocatedSizeSufficient<minOrder, 5 + nElements>()...\n  }};\n\n  for(unsigned i = 0; i < sizeof...(nElements); ++i) {\n    if(!results.at(i)) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\ntemplate<size_t ... minOrders>\nconstexpr bool testAllBTrees(std::index_sequence<minOrders...> /* elements */) {\n  Temple::Array<bool, sizeof...(minOrders)> results {{\n    testAllBTrees<2 + minOrders>(std::make_index_sequence<45>{})... // Test sizes 5->50\n  }};\n\n  for(unsigned i = 0; i < sizeof...(minOrders); ++i) {\n    if(!results.at(i)) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nconstexpr bool testAllBTrees() {\n  return testAllBTrees(std::make_index_sequence<3>{}); // Test min orders 2->5\n}\n\nstatic_assert(\n  testAllBTrees(),\n  \"For some B-Trees, you cannot fit as many elements in as requested at instantiation\"\n);\n\n} // namespace\n", "meta": {"hexsha": "38d91238091898f0903c990c8284eabd8fbc64d9", "size": 8375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Temple/BTree.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "test/Temple/BTree.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Temple/BTree.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 26.8429487179, "max_line_length": 89, "alphanum_fraction": 0.6253134328, "num_tokens": 2262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6363010677064213}}
{"text": "#include \"eigen-la.h\"\n#include <Eigen/Core>\n#include <Eigen/LU>\n//#include <Eigen/LeastSquares>\n#include <Eigen/QR>\n// #include <Eigen/QR>\n#include <Eigen/SVD> // src/SVD/JacobiSVD.h>\n\nusing namespace Eigen;\n\ntemplate <class T>\nRET rank(Decomposition d, int* v, const void* p, int r, int c) {\n    typedef Map< Matrix<T,Dynamic,Dynamic> > MapMatrix;\n    MapMatrix A((T*)p,r,c);\n    switch (d) {\n        case ::FullPivLU:\n            *v = A.fullPivLu().rank();\n            break;\n        case ::ColPivHouseholderQR:\n            *v = A.colPivHouseholderQr().rank();\n            break;\n        case ::FullPivHouseholderQR:\n            *v = A.fullPivHouseholderQr().rank();\n            break;\n        case ::JacobiSVD:\n            *v = A.jacobiSvd(ComputeThinU | ComputeThinV).rank();\n            break;\n        default:\n            return strdup(\"Selected decomposition doesn't support rank revealing.\");\n    }\n    return 0;\n}\nAPI(rank, (int code, Decomposition d, int* v, const void* p, int r, int c), (d,v,p,r,c));\n\ntemplate <class T>\nRET kernel(Decomposition d, void** p0, int* r0, int* c0, const void* p1, int r1, int c1) {\n    typedef Map< Matrix<T,Dynamic,Dynamic> > MapMatrix;\n    if (d != ::FullPivLU)\n        return strdup(\"Selected decomposition doesn't support kernel revealing.\");\n    MapMatrix A((T*)p1,r1,c1);\n    Matrix<T,Dynamic,Dynamic> B = A.fullPivLu().kernel();\n    *r0 = B.rows();\n    *c0 = B.cols();\n    *p0 = malloc(*r0 * *c0 * sizeof(T));\n    MapMatrix((T*)*p0, *r0, *c0) = B;\n    return 0;\n}\nAPI(kernel, (int code, Decomposition d, void** p0, int* r0, int* c0, const void* p1, int r1, int c1), (d,p0,r0,c0,p1,r1,c1));\n\ntemplate <class T>\nRET image(Decomposition d, void** p0, int* r0, int* c0, const void* p1, int r1, int c1) {\n    typedef Map< Matrix<T,Dynamic,Dynamic> > MapMatrix;\n    if (d != ::FullPivLU)\n        return strdup(\"Selected decomposition doesn't support image revealing.\");\n    MapMatrix A((T*)p1,r1,c1);\n    Matrix<T,Dynamic,Dynamic> B = A.fullPivLu().image(A);\n    *r0 = B.rows();\n    *c0 = B.cols();\n    *p0 = malloc(*r0 * *c0 * sizeof(T));\n    MapMatrix((T*)*p0, *r0, *c0) = B;\n    return 0;\n}\nAPI(image, (int code, Decomposition d, void** p0, int* r0, int* c0, const void* p1, int r1, int c1), (d,p0,r0,c0,p1,r1,c1));\n\ntemplate <class T>\nRET solve(Decomposition d,\n    void* px, int rx, int cx,\n    const void* pa, int ra, int ca,\n    const void* pb, int rb, int cb)\n{\n    typedef Map< Matrix<T,Dynamic,Dynamic> > MapMatrix;\n    MapMatrix x((T*)px, rx, cx);\n    MapMatrix A((T*)pa, ra, ca);\n    MapMatrix b((T*)pb, rb, cb);\n    switch (d) {\n        case ::PartialPivLU:\n            x = A.partialPivLu().solve(b);\n            break;\n        case ::FullPivLU:\n            x = A.fullPivLu().solve(b);\n            break;\n        case ::HouseholderQR:\n            x = A.householderQr().solve(b);\n            break;\n        case ::ColPivHouseholderQR:\n            x = A.colPivHouseholderQr().solve(b);\n            break;\n        case ::FullPivHouseholderQR:\n            x = A.fullPivHouseholderQr().solve(b);\n            break;\n        case ::LLT:\n            x = A.llt().solve(b);\n            break;\n        case ::LDLT:\n            x = A.ldlt().solve(b);\n            break;\n        case ::JacobiSVD:\n            x = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b);\n            break;\n    }\n    return 0;\n}\nAPI(solve, (int code, Decomposition d,\n    void* px, int rx, int cx,\n    const void* pa, int ra, int ca,\n    const void* pb, int rb, int cb), (d,px,rx,cx,pa,ra,ca,pb,rb,cb));\n\ntemplate <class T>\nRET relativeError(void* e,\n    const void* px, int rx, int cx,\n    const void* pa, int ra, int ca,\n    const void* pb, int rb, int cb)\n{\n    typedef Map< Matrix<T,Dynamic,Dynamic> > MapMatrix;\n    MapMatrix x((T*)px, rx, cx);\n    MapMatrix A((T*)pa, ra, ca);\n    MapMatrix b((T*)pb, rb, cb);\n    *(T*)e = (A*x - b).norm() / b.norm();\n    return 0;\n}\nAPI(relativeError, (int code, void* e,\n    const void* px, int rx, int cx,\n    const void* pa, int ra, int ca,\n    const void* pb, int rb, int cb), (e,px,rx,cx,pa,ra,ca,pb,rb,cb));\n\n", "meta": {"hexsha": "9056bf030a7e327f6f626fc58d4f9e33067fa744", "size": 4075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cbits/eigen-la.cpp", "max_stars_repo_name": "nilsalex/eigen", "max_stars_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T08:14:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T10:27:07.000Z", "max_issues_repo_path": "cbits/eigen-la.cpp", "max_issues_repo_name": "nilsalex/eigen", "max_issues_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-07-17T14:12:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T11:37:18.000Z", "max_forks_repo_path": "cbits/eigen-la.cpp", "max_forks_repo_name": "nilsalex/eigen", "max_forks_repo_head_hexsha": "2b75b0ad40fa973982ef0f85ba7b79cd149db1df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-11-22T08:11:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T07:40:02.000Z", "avg_line_length": 32.3412698413, "max_line_length": 125, "alphanum_fraction": 0.5666257669, "num_tokens": 1322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6363010623839583}}
{"text": "// -*- mode: c++; indent-tabs-mode: nil; -*-\n//\n// Copyright (c) 2009-2013 Illumina, Inc.\n//\n// This software is provided under the terms and conditions of the\n// Illumina Open Source Software License 1.\n//\n// You should have received a copy of the Illumina Open Source\n// Software License 1 along with this program. If not, see\n// <https://github.com/sequencing/licenses/>\n//\n\n/// \\file\n\n/// \\author Chris Saunders\n///\n#include \"blt_util/binomial_test.hh\"\n#include \"blt_util/stat_util.hh\"\n\n#include <boost/math/distributions/binomial.hpp>\n\nusing boost::math::binomial;\nusing boost::math::cdf;\n\n#include <algorithm>\n\n\n\nbool\nis_reject_binomial_p_exact(const double alpha,\n                           const double p,\n                           const unsigned n_success,\n                           const unsigned n_failure) {\n\n    const unsigned n_trial(n_success+n_failure);\n    const double obs_p((double)n_success/(double)n_trial);\n\n    double exact_prob;\n    if (obs_p <= p) {\n        exact_prob=cdf(binomial(n_trial,p),n_success);\n    } else {\n        exact_prob=cdf(binomial(n_trial,1.-p),n_failure);\n    }\n\n    return ((2.*exact_prob)<alpha);\n}\n\n\n\nbool\nis_reject_binomial_p_chi_sqr(const double alpha,\n                             const double p,\n                             const unsigned n_success,\n                             const unsigned n_failure) {\n\n    assert((p>0.) && (p<1.));\n\n    const unsigned n_trial(n_success+n_failure);\n    const double e_success(p*n_trial);\n    const double e_failure(((double)n_trial)-e_success);\n\n    const double d_success(n_success-e_success);\n    const double d_failure(n_failure-e_failure);\n\n    const double xsq((d_success*d_success)/e_success+(d_failure*d_failure)/e_failure);\n\n    return is_chi_sqr_reject(xsq,1,alpha);\n}\n\n\n\nbool\nis_reject_binomial_p(const double alpha,\n                     const double p,\n                     const unsigned n_success,\n                     const unsigned n_failure) {\n\n    static const unsigned exact_test_threshold(250);\n\n    const unsigned n_trial(n_success+n_failure);\n\n    if (n_trial > exact_test_threshold) {\n        return is_reject_binomial_p_chi_sqr(alpha,p,n_success,n_failure);\n    } else {\n        return is_reject_binomial_p_exact(alpha,p,n_success,n_failure);\n    }\n}\n", "meta": {"hexsha": "298d05a5aecc7d4a64dd8ad456b0e26be5d8174c", "size": 2268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isaac_variant_caller/src/lib/blt_util/binomial_test.cpp", "max_stars_repo_name": "sequencing/isaac_variant_caller", "max_stars_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-01-09T01:11:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-04T03:48:21.000Z", "max_issues_repo_path": "isaac_variant_caller/src/lib/blt_util/binomial_test.cpp", "max_issues_repo_name": "sequencing/isaac_variant_caller", "max_issues_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-07-23T09:38:39.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-01T05:37:26.000Z", "max_forks_repo_path": "isaac_variant_caller/src/lib/blt_util/binomial_test.cpp", "max_forks_repo_name": "sequencing/isaac_variant_caller", "max_forks_repo_head_hexsha": "ed24e20b097ee04629f61014d3b81a6ea902c66b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:41:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T02:42:32.000Z", "avg_line_length": 25.7727272727, "max_line_length": 86, "alphanum_fraction": 0.647707231, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6363010555862374}}
{"text": "#include <permutation.h>\n#include \"problemes.h\"\n\n#include <boost/rational.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\ntypedef boost::rational<nombre> fraction;\n\nENREGISTRER_PROBLEME(121, \"Disc game prize fund\") {\n    // A bag contains one red disc and one blue disc. In a game of chance a player takes a disc at \n    // random and its colour is noted. After each turn the disc is returned to the bag, an extra red\n    // disc is added, and another disc is taken at random.\n    //\n    // The player pays \u00a31 to play and wins if they have taken more blue discs than red discs at the \n    // end of the game.\n    //\n    // If the game is played for four turns, the probability of a player winning is exactly 11/120, \n    // and so the maximum prize fund the banker should allocate for winning in this game would be \u00a310\n    // before they would expect to incur a loss. Note that any payout will be a whole number of pounds\n    // and also includes the original \u00a31 paid to play the game, so in the example given the player \n    // actually wins \u00a39.\n    //\n    // Find the maximum prize fund that should be allocated to a single game in which fifteen turns are\n    // played.\n    nombre limite = 15;\n    std::vector<fraction> probabilites;\n    for (nombre n = 1; n < limite + 1; ++n) {\n        probabilites.emplace_back(1, n + 1);\n    }\n\n    fraction probabilite;\n\n    for (nombre bleu = limite / 2 + 1; bleu < limite + 1; ++bleu) {\n        std::vector<bool> possibilite(limite - bleu, false);\n        possibilite.insert(possibilite.end(), bleu, true);\n        for (auto &permutation: permutation::Permutation<std::vector<bool>>(possibilite)) {\n            fraction p(1);\n            for (size_t n = 0; n < limite; ++n) {\n                if (permutation.at(n))\n                    p *= probabilites.at(n);\n                else\n                    p *= fraction(1) - probabilites.at(n);\n            }\n\n            probabilite += p;\n        }\n    }\n\n    nombre resultat = probabilite.denominator() / probabilite.numerator();\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "a7a5937fecf6b7a62cda585cc28e9a1b920051f8", "size": 2090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme121.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/probleme121.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/probleme121.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.7037037037, "max_line_length": 103, "alphanum_fraction": 0.633492823, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.636243715544339}}
{"text": "#include \"curves.h\"\r\n\r\n#include <algorithm>\r\n#include <array>\r\n#include <cassert>\r\n#include <cstddef>\r\n#include <cstdint>\r\n#include <memory>\r\n\r\n#include <boost/optional.hpp>\r\n\r\n#include \"../shader_core/lerp.h\"\r\n#include \"../shader_core/rect.h\"\r\n\r\nstatic float eval_hermite_interpolation(\r\n\tconst csc::Float2 p0,\r\n\tconst csc::Float2 p1,\r\n\tconst csc::Float2 p2,\r\n\tconst csc::Float2 p3,\r\n\tconst float input_x )\r\n{\r\n\tstd::array<csc::Float2, 32> hermite_curve;\r\n\r\n\tconst auto do_hermite = [](const float p0, const float p1, const float p2, const float p3, const float t) -> float\r\n\t{\r\n\t\tconst float a{ -p0 / 2.0f + (3.0f * p1) / 2.0f - (3.0f * p2) / 2.0f + p3 / 2.0f };\r\n\t\tconst float b{ p0 - (5.0f * p1) / 2.0f + 2.0f * p2 - p3 / 2.0f };\r\n\t\tconst float c{ -p0 / 2.0f + p2 / 2.0f };\r\n\t\tconst float d{ p1 };\r\n\r\n\t\treturn a * t*t*t + b * t*t + c * t + d;\r\n\t};\r\n\r\n\t// Assert that x values are in strictly ascending order\r\n\tassert(p1.x >= p0.x);\r\n\tassert(p2.x >= p1.x);\r\n\tassert(p3.x >= p2.x);\r\n\r\n\t// Populate our whole curve with (x, y) pairs\r\n\tfor (size_t i = 0; i < hermite_curve.size(); i++) {\r\n\t\tconst float t{ static_cast<float>(i) / (hermite_curve.size() - 1) };\r\n\t\tconst float x{ do_hermite(p0.x, p1.x, p2.x, p3.x, t) };\r\n\t\tconst float y{ do_hermite(p0.y, p1.y, p2.y, p3.y, t) };\r\n\t\thermite_curve[i] = csc::Float2{ x, y };\r\n\t}\r\n\r\n\t// Look for the two (x, y) pairs that surround our x value\r\n\t// The curve is already known to be sorted on x\r\n\tsize_t before_index{ SIZE_MAX };\r\n\tfor (size_t i = 0; i < hermite_curve.size(); i++) {\r\n\t\tif (hermite_curve[i].x < input_x) {\r\n\t\t\tbefore_index = i;\r\n\t\t}\r\n\t}\r\n\r\n\t// In the case where our x input is before the first point, just return the value of the first point\r\n\t// This may happen due to floating point oddities\r\n\tif (before_index == SIZE_MAX) {\r\n\t\treturn hermite_curve[0].y;\r\n\t}\r\n\r\n\t// In the case where our x input is beyond the last point, just return the value of the last point\r\n\t// This may happen due to floating point oddities\r\n\tif (before_index == hermite_curve.size() - 1) {\r\n\t\treturn hermite_curve[hermite_curve.size() - 1].y;\r\n\t}\r\n\r\n\tconst float lerp_t{ (input_x - hermite_curve[before_index].x) / (hermite_curve[before_index + 1].x - hermite_curve[before_index].x) };\r\n\treturn csc::lerp(hermite_curve[before_index].y, hermite_curve[before_index + 1].y, lerp_t);\r\n}\r\n\r\nbool csg::CurvePoint::operator==(const CurvePoint& other) const\r\n{\r\n\treturn pos == other.pos && interp == other.interp;\r\n}\r\n\r\ncsg::Curve::Curve(const csc::Float2 min, const csc::Float2 max, const boost::optional<std::vector<CurvePoint>> points) : _min{ min }, _max{ max }\r\n{\r\n\tif (points) {\r\n\t\t// Validate that all points are inside the bounds\r\n\t\tconst csc::FloatRect bounds{ min, max };\r\n\t\tfor (const CurvePoint& this_point : *points) {\r\n\t\t\tassert(bounds.contains(this_point.pos));\r\n\t\t}\r\n\t\tthis->m_points = *points;\r\n\t}\r\n\telse {\r\n\t\t// Default value is always a straight line from min to max\r\n\t\tthis->m_points.push_back(csg::CurvePoint{ min, CurveInterp::CUBIC_HERMITE });\r\n\t\tthis->m_points.push_back(csg::CurvePoint{ max, CurveInterp::CUBIC_HERMITE });\r\n\t}\r\n\tsort_points();\r\n}\r\n\r\nfloat csg::Curve::eval_point(const float input) const\r\n{\r\n\t// For speed, this function assumes the control point vector is sorted already\r\n\tassert(m_points.size() >= 1);\r\n\r\n\t// Variable naming convention for points:\r\n\t// p1 is the point immediately before input\r\n\t// p2 is the point immediately after input\r\n\t// In the case of spline interpolation, we need 2 more\r\n\t// p0 is the point before p1\r\n\t// p3 is the point after p2\r\n\t// Any one of the points might not be real, but at least one of p1 or p2 must be real\r\n\r\n\tboost::optional<size_t> p1_index;\r\n\tboost::optional<size_t> p2_index;\r\n\tfor (size_t i = 0; i < m_points.size(); i++) {\r\n\t\t// Find the point before input\r\n\t\tif (m_points[i].pos.x <= input) {\r\n\t\t\tp1_index = i;\r\n\t\t}\r\n\t}\r\n\tfor (size_t i = m_points.size(); i > 0; i--) {\r\n\t\t// Find the point after input\r\n\t\tif (m_points[i-1].pos.x > input) {\r\n\t\t\tp2_index = i-1;\r\n\t\t}\r\n\t}\r\n\r\n\t// Clamp if input is not between two points\r\n\tif (p1_index.has_value() == false) {\r\n\t\treturn m_points[0].pos.y;\r\n\t}\r\n\tif (p2_index.has_value() == false) {\r\n\t\treturn m_points[m_points.size() - 1].pos.y;\r\n\t}\r\n\r\n\tconst csc::Float2 p1{ m_points[*p1_index].pos };\r\n\tconst csc::Float2 p2{ m_points[*p2_index].pos };\r\n\tconst csg::CurveInterp p1_interp{ m_points[*p1_index].interp };\r\n\tconst csg::CurveInterp p2_interp{ m_points[*p2_index].interp };\r\n\r\n\tconst float delta_x{ p2.x - p1.x };\r\n\tconst float fade{ (input - p1.x) / delta_x };\r\n\r\n\tconst float linear_result{ csc::lerp(p1.y, p2.y, fade) };\r\n\tif (p1_interp == csg::CurveInterp::LINEAR && p2_interp == csg::CurveInterp::LINEAR) {\r\n\t\t// End early if possible to avoid doing unnecessary spline math\r\n\t\treturn linear_result;\r\n\t}\r\n\r\n\t// Lambdas to generate p0 and p3 for our interp\r\n\tconst auto gen_p0_pos = [](const std::vector<CurvePoint>& points, const size_t p1_index, const size_t p2_index) -> csc::Float2\r\n\t{\r\n\t\tif (p1_index == 0) {\r\n\t\t\tconst csc::Float2 p1{ points[p1_index].pos };\r\n\t\t\tconst csc::Float2 p2{ points[p2_index].pos };\r\n\t\t\treturn p1 - (p2 - p1);\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn points[p1_index - 1].pos;\r\n\t\t}\r\n\t};\r\n\tconst auto gen_p3_pos = [](const std::vector<CurvePoint>& points, const size_t p1_index, const size_t p2_index) -> csc::Float2\r\n\t{\r\n\t\tif (p2_index >= points.size() - 1) {\r\n\t\t\tconst csc::Float2 p1{ points[p1_index].pos };\r\n\t\t\tconst csc::Float2 p2{ points[p2_index].pos };\r\n\t\t\treturn p2 + (p2 - p1);\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn points[p2_index + 1].pos;\r\n\t\t}\r\n\t};\r\n\tconst csc::Float2 p0{ gen_p0_pos(m_points, *p1_index, *p2_index) };\r\n\tconst csc::Float2 p3{ gen_p3_pos(m_points, *p1_index, *p2_index) };\r\n\r\n\t// Hermite spline interpolation\r\n\r\n\tconst float hermite_result{ eval_hermite_interpolation(p0, p1, p2, p3, input) };\r\n\r\n\t// 0 means to use fully linear interp, 1 means fully hermite\r\n\tconst auto calc_interp_lerp = [](const csg::CurveInterp p1_interp, const csg::CurveInterp p2_interp, const float t) -> float\r\n\t{\r\n\t\tif (p1_interp == csg::CurveInterp::LINEAR && p2_interp == csg::CurveInterp::LINEAR) {\r\n\t\t\treturn 0.0f;\r\n\t\t}\r\n\t\telse if (p1_interp == csg::CurveInterp::CUBIC_HERMITE && p2_interp == csg::CurveInterp::CUBIC_HERMITE) {\r\n\t\t\treturn 1.0f;\r\n\t\t}\r\n\t\telse if (p1_interp == csg::CurveInterp::CUBIC_HERMITE && p2_interp == csg::CurveInterp::LINEAR) {\r\n\t\t\treturn 1.0f - t;\r\n\t\t}\r\n\t\telse if (p1_interp == csg::CurveInterp::LINEAR && p2_interp == csg::CurveInterp::CUBIC_HERMITE) {\r\n\t\t\treturn t;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tassert(false);\r\n\t\t\t// To suppress a compiler warning\r\n\t\t\treturn 0.0f;\r\n\t\t}\r\n\t};\r\n\r\n\tconst float interp_t{ (input - p1.x) / (p2.x - p1.x) };\r\n\treturn csc::lerp(linear_result, hermite_result, calc_interp_lerp(p1_interp, p2_interp, interp_t));\r\n}\r\n\r\nvoid csg::Curve::delete_point(const size_t index)\r\n{\r\n\tif (m_points.size() < 2) {\r\n\t\t// Curve is in a meaningless state\r\n\t\tassert(false);\r\n\t}\r\n\telse if (m_points.size() == 2) {\r\n\t\treturn;\r\n\t}\r\n\r\n\tm_points.erase(m_points.begin() + index);\r\n\tsort_points();\r\n}\r\n\r\nsize_t csg::Curve::create_point(const float x)\r\n{\r\n\tif (x < _min.x) {\r\n\t\treturn 0;\r\n\t}\r\n\tif (x > _max.x) {\r\n\t\treturn m_points.size() - 1;\r\n\t}\r\n\tconst float y{ eval_point(x) };\r\n\tconst CurvePoint new_point{ csc::Float2{ x, y }, csg::CurveInterp::LINEAR };\r\n\tm_points.push_back(new_point);\r\n\tsort_points();\r\n\t// Use linear interp by default\r\n\t// If either surrounding point is hermite, then use hermite\r\n\tfor (size_t i = 0; i < m_points.size(); i++) {\r\n\t\tif (m_points[i] == new_point) {\r\n\t\t\t// i is the index of the new point\r\n\t\t\tcsg::CurveInterp interp{ csg::CurveInterp::LINEAR };\r\n\t\t\tif (i > 0 && m_points[i - 1].interp == csg::CurveInterp::CUBIC_HERMITE) {\r\n\t\t\t\tinterp = csg::CurveInterp::CUBIC_HERMITE;\r\n\t\t\t}\r\n\t\t\tif (i + 1 < m_points.size() && m_points[i + 1].interp == csg::CurveInterp::CUBIC_HERMITE) {\r\n\t\t\t\tinterp = csg::CurveInterp::CUBIC_HERMITE;\r\n\t\t\t}\r\n\t\t\tm_points[i].interp = interp;\r\n\t\t\treturn i;\r\n\t\t}\r\n\t}\r\n\tassert(false);\r\n\treturn 0;\r\n}\r\n\r\nsize_t csg::Curve::move_point(const size_t index, const csc::Float2 new_pos)\r\n{\r\n\tif (index >= m_points.size()) {\r\n\t\treturn index;\r\n\t}\r\n\r\n\tconst csc::FloatRect valid_pos{ _min, _max };\r\n\tm_points[index].pos = valid_pos.clamp(new_pos);\r\n\tconst CurvePoint changed_point{ m_points[index] };\r\n\tsort_points();\r\n\r\n\t// Find and return the point's new index\r\n\tfor (size_t i = 0; i < m_points.size(); i++) {\r\n\t\tif (changed_point == m_points[i]) {\r\n\t\t\treturn i;\r\n\t\t}\r\n\t}\r\n\tassert(false);\r\n\treturn index;\r\n}\r\n\r\nvoid csg::Curve::set_interp(const size_t index, const CurveInterp new_interp)\r\n{\r\n\tif (index >= m_points.size()) {\r\n\t\treturn;\r\n\t}\r\n\tm_points[index].interp = new_interp;\r\n}\r\n\r\nvoid csg::Curve::set_bounds(const csc::FloatRect bounds_rect)\r\n{\r\n\tif (bounds_valid(bounds_rect) == false) {\r\n\t\treturn;\r\n\t}\r\n\t_min = bounds_rect.begin();\r\n\t_max = bounds_rect.end();\r\n}\r\n\r\nbool csg::Curve::bounds_valid(const csc::FloatRect bounds_rect)\r\n{\r\n\tfor (const CurvePoint& this_point : m_points) {\r\n\t\tif (bounds_rect.contains(this_point.pos) == false) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool csg::Curve::similar(const Curve& other, const float margin) const\r\n{\r\n\tif (_min.similar(other._min, margin) == false) {\r\n\t\treturn false;\r\n\t}\r\n\tif (_max.similar(other._max, margin) == false) {\r\n\t\treturn false;\r\n\t}\r\n\tif (m_points.size() != other.m_points.size()) {\r\n\t\treturn false;\r\n\t}\r\n\tfor (size_t i = 0; i < m_points.size(); i++) {\r\n\t\tif (m_points[i].interp != other.m_points[i].interp) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (m_points[i].pos.similar(other.m_points[i].pos, margin) == false) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nbool csg::Curve::operator==(const Curve& other) const\r\n{\r\n\tif (_min != other._min) {\r\n\t\treturn false;\r\n\t}\r\n\tif (_max != other._max) {\r\n\t\treturn false;\r\n\t}\r\n\tif (m_points.size() != other.m_points.size()) {\r\n\t\treturn false;\r\n\t}\r\n\tfor (size_t i = 0; i < m_points.size(); i++) {\r\n\t\tif (m_points[i] != other.m_points[i]) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid csg::Curve::sort_points()\r\n{\r\n\tconst auto lt_x = [](const CurvePoint a, const CurvePoint b) -> bool {\r\n\t\treturn a.pos.x < b.pos.x;\r\n\t};\r\n\tstd::sort(m_points.begin(), m_points.end(), lt_x);\r\n}\r\n", "meta": {"hexsha": "cd62a41f1f0910a470590b08ef5328ab0b2ee8bc", "size": 10138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vistual-shader-graph/shader_online/shader_graph/curves.cpp", "max_stars_repo_name": "zwluoqi/mobile-visual-shader-editor", "max_stars_repo_head_hexsha": "e02e34e02a826f2f1cda74ca385a65e720883917", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 84.0, "max_stars_repo_stars_event_min_datetime": "2021-10-08T02:39:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T20:07:03.000Z", "max_issues_repo_path": "src/vistual-shader-graph/shader_online/shader_graph/curves.cpp", "max_issues_repo_name": "zwluoqi/mobile-visual-shader-editor", "max_issues_repo_head_hexsha": "e02e34e02a826f2f1cda74ca385a65e720883917", "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/vistual-shader-graph/shader_online/shader_graph/curves.cpp", "max_forks_repo_name": "zwluoqi/mobile-visual-shader-editor", "max_forks_repo_head_hexsha": "e02e34e02a826f2f1cda74ca385a65e720883917", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3855072464, "max_line_length": 146, "alphanum_fraction": 0.6426316828, "num_tokens": 3167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6362437114983032}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <mathtoolbox/acquisition-functions.hpp>\n#include <mathtoolbox/gaussian-process-regression.hpp>\n#include <mathtoolbox/probability-distributions.hpp>\n#include <timer.hpp>\n\nusing Eigen::Matrix2d;\nusing Eigen::MatrixXd;\nusing Eigen::Vector2d;\nusing Eigen::VectorXd;\n\ndouble CalcFunc(const Vector2d& x)\n{\n    return mathtoolbox::GetNormalDist(3.0 * x, Vector2d::Zero(), Matrix2d::Identity(), 1.0);\n}\n\nint main(int argc, char** argv)\n{\n    // Define the scene setting\n    constexpr int    num_samples     = 10;\n    constexpr double noise_intensity = 1e-04;\n\n    // Generate scattered data\n    MatrixXd X(2, num_samples);\n    VectorXd y(num_samples);\n    for (int i = 0; i < num_samples; ++i)\n    {\n        X.col(i) = Vector2d::Random();\n        y(i)     = CalcFunc(X.col(i)) + noise_intensity * (VectorXd::Random(1))(0);\n    }\n\n    // Define the kernel type\n    const auto kernel_type = mathtoolbox::GaussianProcessRegressor::KernelType::ArdMatern52;\n\n    // Instantiate the interpolation object\n    mathtoolbox::GaussianProcessRegressor regressor(X, y, kernel_type);\n\n    // Perform hyperparameter estimation\n    const Eigen::Vector3d default_kernel_hyperparams(0.50, 0.50, 0.50);\n    regressor.PerformMaximumLikelihood(default_kernel_hyperparams, 1e-04);\n\n    // Calculate EI values and their derivatives\n    for (int i = 0; i < 100; ++i)\n    {\n        constexpr int    num_dims = 2;\n        constexpr double epsilon  = 1e-06;\n\n        const VectorXd x_plus = [&]() {\n            int index;\n            y.maxCoeff(&index);\n            return X.col(index);\n        }();\n\n        const VectorXd x = Vector2d::Random();\n\n        const VectorXd acquisition_deriv = mathtoolbox::GetExpectedImprovementDerivative(\n            x,\n            [&](const VectorXd& x) { return regressor.PredictMean(x); },\n            [&](const VectorXd& x) { return regressor.PredictStdev(x); },\n            x_plus,\n            [&](const VectorXd& x) { return regressor.PredictMeanDeriv(x); },\n            [&](const VectorXd& x) { return regressor.PredictStdevDeriv(x); });\n\n        VectorXd acquisition_numerical_deriv(num_dims);\n        for (int d = 0; d < num_dims; ++d)\n        {\n            VectorXd delta = VectorXd::Zero(num_dims);\n            delta(d)       = epsilon;\n\n            const double value_plus = mathtoolbox::GetExpectedImprovement(\n                x + delta,\n                [&](const VectorXd& x) { return regressor.PredictMean(x); },\n                [&](const VectorXd& x) { return regressor.PredictStdev(x); },\n                x_plus);\n\n            const double value_minus = mathtoolbox::GetExpectedImprovement(\n                x - delta,\n                [&](const VectorXd& x) { return regressor.PredictMean(x); },\n                [&](const VectorXd& x) { return regressor.PredictStdev(x); },\n                x_plus);\n\n            acquisition_numerical_deriv(d) = value_plus - value_minus;\n        }\n        acquisition_numerical_deriv /= 2.0 * epsilon;\n\n        const auto scale     = acquisition_deriv.norm();\n        const auto abs_error = (acquisition_deriv - acquisition_numerical_deriv).norm();\n        const auto rel_error = abs_error / scale;\n\n        if (scale > 1e-06 && rel_error > 1e-02)\n        {\n            std::cout << \"point location: \" << x.transpose() << std::endl;\n            std::cout << \"analytic      : \" << acquisition_deriv.transpose() << std::endl;\n            std::cout << \"numerical     : \" << acquisition_numerical_deriv.transpose() << std::endl;\n            std::cout << \"error         : \" << abs_error << std::endl;\n\n            exit(1);\n        }\n    }\n\n    // Calculate GP-UCB values and their derivatives\n    for (int i = 0; i < 100; ++i)\n    {\n        constexpr int    num_dims = 2;\n        constexpr double epsilon  = 1e-06;\n\n        const double hyperparam = 1.0 + (Eigen::VectorXd::Random(1))(0);\n\n        const VectorXd x = Vector2d::Random();\n\n        const VectorXd acquisition_deriv = mathtoolbox::GetGaussianProcessUpperConfidenceBoundDerivative(\n            x,\n            [&](const VectorXd& x) { return regressor.PredictMean(x); },\n            [&](const VectorXd& x) { return regressor.PredictStdev(x); },\n            hyperparam,\n            [&](const VectorXd& x) { return regressor.PredictMeanDeriv(x); },\n            [&](const VectorXd& x) { return regressor.PredictStdevDeriv(x); });\n\n        VectorXd acquisition_numerical_deriv(num_dims);\n        for (int d = 0; d < num_dims; ++d)\n        {\n            VectorXd delta = VectorXd::Zero(num_dims);\n            delta(d)       = epsilon;\n\n            const double value_plus = mathtoolbox::GetGaussianProcessUpperConfidenceBound(\n                x + delta,\n                [&](const VectorXd& x) { return regressor.PredictMean(x); },\n                [&](const VectorXd& x) { return regressor.PredictStdev(x); },\n                hyperparam);\n\n            const double value_minus = mathtoolbox::GetGaussianProcessUpperConfidenceBound(\n                x - delta,\n                [&](const VectorXd& x) { return regressor.PredictMean(x); },\n                [&](const VectorXd& x) { return regressor.PredictStdev(x); },\n                hyperparam);\n\n            acquisition_numerical_deriv(d) = value_plus - value_minus;\n        }\n        acquisition_numerical_deriv /= 2.0 * epsilon;\n\n        const auto scale     = acquisition_deriv.norm();\n        const auto abs_error = (acquisition_deriv - acquisition_numerical_deriv).norm();\n        const auto rel_error = abs_error / scale;\n\n        if (scale > 1e-06 && rel_error > 1e-02)\n        {\n            std::cout << \"point location: \" << x.transpose() << std::endl;\n            std::cout << \"analytic      : \" << acquisition_deriv.transpose() << std::endl;\n            std::cout << \"numerical     : \" << acquisition_numerical_deriv.transpose() << std::endl;\n            std::cout << \"error         : \" << abs_error << std::endl;\n\n            exit(1);\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "4955c8f7cba68df4a986f5266eea944995138760", "size": 5977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/acquisition-function/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/acquisition-function/main.cpp", "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": "examples/acquisition-function/main.cpp", "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": 37.5911949686, "max_line_length": 105, "alphanum_fraction": 0.5860799732, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139577, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6362437019957462}}
{"text": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <utility> // std::pair, std::make_pair\n#include <cmath> // float comparison\n#include <limits>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"persistent_cohomology_multi_field\"\n#include <boost/test/unit_test.hpp>\n\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/reader_utils.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n#include <gudhi/Persistent_cohomology/Multi_field.h>\n\nusing namespace Gudhi;\nusing namespace Gudhi::persistent_cohomology;\nusing namespace boost::unit_test;\n\ntypedef Simplex_tree<> typeST;\n\nstd::string test_rips_persistence(int min_coefficient, int max_coefficient, double min_persistence) {\n  // file is copied in CMakeLists.txt\n  std::ifstream simplex_tree_stream;\n  simplex_tree_stream.open(\"simplex_tree_file_for_multi_field_unit_test.txt\");\n  typeST st;\n  simplex_tree_stream >> st;\n  simplex_tree_stream.close();\n\n  // Display the Simplex_tree\n  std::clog << \"The complex contains \" << st.num_simplices() << \" simplices\" << \" - dimension= \" << st.dimension()\n      << std::endl;\n\n  // Check\n  BOOST_CHECK(st.num_simplices() == 58);\n  BOOST_CHECK(st.dimension() == 3);\n\n  // Sort the simplices in the order of the filtration\n  st.initialize_filtration();\n\n  // Compute the persistence diagram of the complex\n  Persistent_cohomology<Simplex_tree<>, Multi_field> pcoh(st);\n\n  pcoh.init_coefficients(min_coefficient, max_coefficient); // initializes the coefficient field for homology\n  // Check infinite rips\n  pcoh.compute_persistent_cohomology(min_persistence); // Minimal lifetime of homology feature to be recorded.\n\n  std::ostringstream ossRips;\n  pcoh.output_diagram(ossRips);\n\n  std::string strRips = ossRips.str();\n  return strRips;\n}\n\nvoid test_rips_persistence_in_dimension(int min_dimension, int max_dimension) {\n  // there are 2 discontinued ensembles \n  std::string value0(\"  0 0.25 inf\");\n  std::string value1(\"  1 0.4 inf\");\n  // And a big hole - cut in 2 pieces after 0.3\n  std::string value2(\"  0 0.2 0.3\");\n\n  // For dim <= 1 =>\n  std::string value3(\"  1 0.25 inf\");\n  std::string value4(\"  2 0.25 inf\");\n  std::string value5(\"  1 0.3 inf\");\n  std::string value6(\"  2 0.3 inf\");\n  std::string value7(\"  2 0.4 inf\");\n\n  std::clog << \"********************************************************************\" << std::endl;\n  std::clog << \"TEST OF RIPS_PERSISTENT_COHOMOLOGY_MULTI_FIELD MIN_DIM=\" << min_dimension << \" MAX_DIM=\" << max_dimension << \" MIN_PERS=0\" << std::endl;\n\n  std::string str_rips_persistence = test_rips_persistence(min_dimension, max_dimension, 0.0);\n  std::clog << \"str_rips_persistence=\" << str_rips_persistence << std::endl;\n\n  BOOST_CHECK(str_rips_persistence.find(value0) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value1) != std::string::npos); // Check found\n  BOOST_CHECK(str_rips_persistence.find(value2) != std::string::npos); // Check found\n\n  if ((min_dimension < 2) && (max_dimension < 2)) {\n    BOOST_CHECK(str_rips_persistence.find(value3) != std::string::npos); // Check found\n    BOOST_CHECK(str_rips_persistence.find(value4) != std::string::npos); // Check found\n    BOOST_CHECK(str_rips_persistence.find(value5) != std::string::npos); // Check found\n    BOOST_CHECK(str_rips_persistence.find(value6) != std::string::npos); // Check found\n    BOOST_CHECK(str_rips_persistence.find(value7) != std::string::npos); // Check found\n  } else {\n    BOOST_CHECK(str_rips_persistence.find(value3) == std::string::npos); // Check not found\n    BOOST_CHECK(str_rips_persistence.find(value4) == std::string::npos); // Check not found\n    BOOST_CHECK(str_rips_persistence.find(value5) == std::string::npos); // Check not found\n    BOOST_CHECK(str_rips_persistence.find(value6) == std::string::npos); // Check not found\n    BOOST_CHECK(str_rips_persistence.find(value7) == std::string::npos); // Check not found\n  }\n\n}\n\nBOOST_AUTO_TEST_CASE(rips_persistent_cohomology_multi_field_dim_1_2) {\n  test_rips_persistence_in_dimension(0, 1);\n}\n\nBOOST_AUTO_TEST_CASE(rips_persistent_cohomology_multi_field_dim_2_3) {\n  test_rips_persistence_in_dimension(1, 3);\n}\n\nBOOST_AUTO_TEST_CASE(rips_persistent_cohomology_multi_field_dim_1_5) {\n  test_rips_persistence_in_dimension(1, 5);\n}\n\n// TODO(VR): not working from 6\n// std::string str_rips_persistence = test_rips_persistence(6, 0);\n// TODO(VR): division by zero\n// std::string str_rips_persistence = test_rips_persistence(0, 0);\n// TODO(VR): is result OK of :\n// test_rips_persistence_in_dimension(3, 4);\n\n", "meta": {"hexsha": "3602aa09c95b1e59f43a115d4c68afa1cbb1f7f8", "size": 4561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Persistent_cohomology/test/persistent_cohomology_unit_test_multi_field.cpp", "max_stars_repo_name": "m0baxter/gudhi-devel", "max_stars_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Persistent_cohomology/test/persistent_cohomology_unit_test_multi_field.cpp", "max_issues_repo_name": "m0baxter/gudhi-devel", "max_issues_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Persistent_cohomology/test/persistent_cohomology_unit_test_multi_field.cpp", "max_forks_repo_name": "m0baxter/gudhi-devel", "max_forks_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 39.3189655172, "max_line_length": 152, "alphanum_fraction": 0.7261565446, "num_tokens": 1277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6362298135811156}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n\n//Quaternion Exponential\n//implements simple 0th-order integration\n//ref: quaternion kinematics, section 4.6.1 \nusing Eigen::Quaternionf;\nusing Eigen::Vector3f;\nQuaternionf qExponential(float dt, Vector3f w)\n{\n  float wn = w.norm();\n  Vector3f wN = w.normalized();\n  Quaternionf qReturn;\n  qReturn.w() = cos(wn * dt / 2);\n  qReturn.vec() = wN * sin(wn * dt / 2);\n  return qReturn;\n}\n\nint main()\n{\n  using Eigen::Quaternionf;\n  using Eigen::Vector3f;\n  float dt = 0.01;\n  Vector3f w(1.0, 2.0, -3.0);\n  Quaternionf qExp = qExponential(dt, w);\n  std::cout << qExp.w() << std::endl << qExp.vec() << std::endl;\n}\n  \n", "meta": {"hexsha": "f51250e22e83255087849a1366ce5afc5082ef7c", "size": 673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qExponential.cpp", "max_stars_repo_name": "nearlab/rover_visual_od", "max_stars_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "qExponential.cpp", "max_issues_repo_name": "nearlab/rover_visual_od", "max_issues_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qExponential.cpp", "max_forks_repo_name": "nearlab/rover_visual_od", "max_forks_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4333333333, "max_line_length": 64, "alphanum_fraction": 0.661218425, "num_tokens": 219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.6361779722193096}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"test_gauss\"\n\n#include <boost/test/unit_test.hpp>\n#include \"nanocv/math/gauss.hpp\"\n#include <iostream>\n\nBOOST_AUTO_TEST_CASE(test_gauss)\n{\n        using namespace ncv;\n\n        using std::size_t;\n\n        const std::vector<double> sigmas = { 0.2, 0.5, 0.7, 1.0, 1.5, 2.0, 2.5 };\n        const std::vector<double> cutoffs = { 0.001, 0.01, 0.1 };\n\n        const gauss::kernel_normalization normalize = gauss::kernel_normalization::on;\n\n        // test various variances\n        for (double sigma : sigmas)\n        {\n                // test various cutoffs (skip low values in the kernel)\n                for (double cutoff : cutoffs)\n                {\n                        const auto kernel = gauss_kernel_t<double>(sigma, cutoff, normalize);\n\n                        std::cout << \"sigma = \" << sigma << \", cutoff = \" << cutoff << std::endl;\n                        std::cout << \"kernel = {\";\n                        for (size_t k = 0; k < kernel.size(); k ++)\n                        {\n                                std::cout << kernel[k] << (k + 1 == kernel.size() ? \"\" : \", \");\n                        }\n                        std::cout << \"}\" << std::endl << std::endl;\n\n                        /// \\todo more tests!\n\n                        // check kernel sum\n                        const double sum = kernel.sum();\n                        BOOST_CHECK_LE(sum, 1.0 + 1e-8);\n                        BOOST_CHECK_GE(sum, 1.0 - 1e-8);\n                }\n        }\n}\n\n", "meta": {"hexsha": "84e07a20c31897342122bb567b3560aba6f925ba", "size": 1526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_gauss.cpp", "max_stars_repo_name": "0x0all/nanocv", "max_stars_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_gauss.cpp", "max_issues_repo_name": "0x0all/nanocv", "max_issues_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_gauss.cpp", "max_forks_repo_name": "0x0all/nanocv", "max_forks_repo_head_hexsha": "dc58dea6b4eb7be2089b168d39c2b02aa2730741", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T02:41:37.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-02T02:41:37.000Z", "avg_line_length": 33.9111111111, "max_line_length": 97, "alphanum_fraction": 0.4593709043, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.6361593472530859}}
{"text": "#include \"../DynAutoDiff/DynAutoDiff.hpp\"\n#include <algorithm>\n#include <boost/test/tools/old/interface.hpp>\n#include <eigen3/Eigen/Core>\n#include <iostream>\n#include <ostream>\n#include <vector>\n\n#define BOOST_TEST_MODULE Normal_Test\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#define TL 1e-10\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace DynAutoDiff;\n\nBOOST_AUTO_TEST_SUITE(Losses_Test)\n\nBOOST_AUTO_TEST_CASE(bce_test) {\n    vector<TMat<>> v(2);\n    v[0] = TMat<>(2, 2);\n    // cout << v[0] << endl;\n\n    auto p = vec<double>({0.2, 0.3, 0.4, 0.5, 0.8}, true), y = vec<double>({0, 0, 1, 1, 1});\n\n    auto y1 = binary_cross_entropy(p, y);\n    GraphManager gm1(y1);\n    gm1.run();\n\n    BOOST_CHECK_CLOSE(y1->v(), 2.4123999590012524, 1e-5);\n    BOOST_CHECK_CLOSE(p->g(), 5.0 / 4, 1e-5);\n    BOOST_CHECK_CLOSE(p->g(1), 1.4285714382902825, 1e-3);\n    BOOST_CHECK_CLOSE(p->g(3), -2, 1e-10);\n}\nBOOST_AUTO_TEST_CASE(ivecl_test) {}\nBOOST_AUTO_TEST_CASE(times_test) {}\n\nBOOST_AUTO_TEST_CASE(division_test) {}\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4e0a6439e13487fb7f5fa09f29b40e3fb78e3966", "size": 1103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_losses.cpp", "max_stars_repo_name": "kilasuelika/DynAutoDiff", "max_stars_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-26T06:13:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-26T06:13:56.000Z", "max_issues_repo_path": "test/test_losses.cpp", "max_issues_repo_name": "kilasuelika/DynAutoDiff", "max_issues_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_losses.cpp", "max_forks_repo_name": "kilasuelika/DynAutoDiff", "max_forks_repo_head_hexsha": "1da36182e93f4893201389c5841941500586e3ea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9024390244, "max_line_length": 92, "alphanum_fraction": 0.6999093382, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6360412083584027}}
{"text": "#include <blitzml/base/math_util.h>\n\n#include <utility>\n\nusing std::pair;\n\nnamespace BlitzML {\n\n\npair<value_t, value_t> compute_quadratic_roots(value_t a, value_t b, \n                                                    value_t c) {\n  value_t discriminant = b*b - 4*a*c;\n  bool result_exists = (discriminant >= 0);\n  if (a == 0. && b == 0. && c != 0.) {\n    result_exists = false;\n  }\n  if (!result_exists) {\n    value_t nan = std::numeric_limits<value_t>::quiet_NaN();\n    return pair<value_t, value_t>(nan, nan);\n  } \n  if (a == 0.) {\n    value_t result = -c/b;\n    return pair<value_t, value_t>(result, result);\n  }\n\n  value_t sqrt_discriminant = sqrt(discriminant);\n  value_t root1 = (-b - sqrt_discriminant) / (2 * a);\n  value_t root2 = (-b + sqrt_discriminant) / (2 * a);\n  if (a > 0) {\n    return pair<value_t, value_t>(root1, root2);\n  } else {\n    return pair<value_t, value_t>(root2, root1);\n  }\n}\n\n} // namespace BlitzML\n\n", "meta": {"hexsha": "06498ae64f6c160b83b981d427cb042e6dd4dbf0", "size": 932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/base/math_util.cpp", "max_stars_repo_name": "tbjohns/BlitzML", "max_stars_repo_head_hexsha": "0523743e1ae3614bfe3f16aa226d7a27fab2d623", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T05:17:17.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-02T05:50:01.000Z", "max_issues_repo_path": "src/base/math_util.cpp", "max_issues_repo_name": "tbjohns/BlitzML", "max_issues_repo_head_hexsha": "0523743e1ae3614bfe3f16aa226d7a27fab2d623", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T13:53:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-11T14:53:26.000Z", "max_forks_repo_path": "src/base/math_util.cpp", "max_forks_repo_name": "tbjohns/BlitzML", "max_forks_repo_head_hexsha": "0523743e1ae3614bfe3f16aa226d7a27fab2d623", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T05:50:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-21T04:44:15.000Z", "avg_line_length": 24.5263157895, "max_line_length": 69, "alphanum_fraction": 0.5944206009, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604134, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6360411864990886}}
{"text": "#include <cmath>\n#include <boost/numeric/conversion/cast.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include \"kernel.h\"\n\nconst std::map<std::string, double> calculator::WExpression::global_constants\n{\n    {\"pi\", boost::math::constants::pi<double>()},\n    {\"e\", boost::math::constants::e<double>()}\n};\n\ndouble calculator::WExpression::expression()\n{\n    Token t {ts.pop()};\n    bool isNeg {false};\n    if (t.kind == TokenKind::minus)\n        isNeg = true;\n    else if (t.kind == TokenKind::plus)\n        isNeg = false;\n    else\n        ts.push(t);\n\n    double left {term()};\n    if (isNeg) left = -left;\n\n    while (true)\n    {\n        Token t {ts.pop()};\n        switch(t.kind)\n        {\n            case TokenKind::plus:\n                left += term();\n                break;\n            case TokenKind::minus:\n                left -= term();\n                break;\n            default:\n                ts.push(t);\n                return left;\n        }\n    }\n}\n\ndouble calculator::WExpression::term()\n{\n    using boost::numeric_cast;\n    double left {primary()};\n\n    while (true)\n    {\n        Token t {ts.pop()};\n        switch (t.kind) {\n            case TokenKind::multiply:\n                left *= primary();\n                break;\n            case TokenKind::divide:\n            {\n                double d {primary()};\n                if (d == 0.0) throw std::logic_error(\"division by 0\");\n                left /= d;\n                break;\n            }\n            case TokenKind::mod:\n            {\n                double d{primary()};\n                int i1 = numeric_cast<int>(left);\n                double di1 = numeric_cast<double>(i1);\n                if (left - di1 > std::numeric_limits<double>::min())\n                    throw std::logic_error(\"left operand of %(mod) is not integer\");\n                int i2 = numeric_cast<int>(d);\n                double di2 = numeric_cast<double>(i2);\n                if (d - di2 > std::numeric_limits<double>::min())\n                    throw std::logic_error(\"right operand of %(mod) is not integer\");\n                left = i1 % i2;\n                break;\n            }\n            default:\n                ts.push(t);\n                return left;\n        }\n    }\n}\n\ndouble calculator::WExpression::primary()\n{\n    using boost::numeric_cast;\n    double result {0.0};\n    Token t {ts.pop()};\n    auto endBracket = [](TokenKind tk)->TokenKind{\n        switch (tk)\n        {\n            case TokenKind::bracket_left0:\n                return TokenKind::bracket_right0;\n            case TokenKind::bracket_left1:\n                return TokenKind::bracket_right1;\n            default:\n                return tk;\n        }\n    };\n    switch (t.kind) {\n        case TokenKind::number:\n        {\n            result = t.value;\n            break;\n        }\n        case TokenKind::variable:\n        {\n            // first find in constants\n            auto gcit {global_constants.find(t.name)};\n            if (gcit == cend(global_constants))\n            {\n                auto vit = variables.find(t.name);\n                if (vit == cend(variables))\n                {\n                    throw std::logic_error(\"undefined symbolic literal \" + t.name);\n                }\n                result = vit->second;\n                break;\n            }\n            result = gcit->second;\n            break;\n//            auto it {variables.find(t.name)};\n//            if (it == end(variables))\n//                throw std::logic_error(\"undefined variable \"+t.name);\n//            result = it->second;\n//            break;\n        }\n        case TokenKind::function:\n        {\n            result = function(t.name);\n            break;\n        }\n        case TokenKind::bracket_left0:\n        case TokenKind::bracket_left1:\n        {\n            double d {expression()};\n            Token t2 {ts.pop()};\n            if (t2.kind != endBracket(t.kind)/*TokenKind::bracket_right0*/)\n                throw std::logic_error(\"bracket_right expected\");\n            result = d;\n            break;\n        }\n//        case TokenKind::bracket_left1:\n//        {\n//            double d {expression()};\n//            t = ts.pop();\n//            if (t.kind != TokenKind::bracket_right1)\n//                throw std::logic_error(\"bracket_right expected\");\n//            result = d;\n//            break;\n//        }\n        default:\n            throw std::logic_error(\"primary is expected\");\n    }\n    while (true)\n    {\n        Token tp {ts.pop()};\n        switch (tp.kind)\n        {\n            case TokenKind::factorial:\n            {\n                unsigned int f = numeric_cast<unsigned int>(result);\n                double df = numeric_cast<double>(f);\n                if (result-df > std::numeric_limits<double>::min())\n                    throw std::logic_error(\"factorial applied to not integer\");\n                result = boost::math::factorial<double>(f);\n                break;\n            }\n            default:\n            {\n                ts.push(tp);\n                return result;\n            }\n        }\n    }\n//    return result;\n//    switch (tf.kind)\n//    {\n//        case TokenKind::factorial:\n//        {\n//            unsigned int f = numeric_cast<unsigned int>(result);\n//            double df = numeric_cast<double>(f);\n//            if (result-df > std::numeric_limits<double>::min())\n//                throw std::logic_error(\"factorial applied to not integer\");\n//            return boost::math::factorial<double>(f);\n//        }\n//        default:\n//            ts.push(tf);\n//            return result;\n    //    }\n}\n\ndouble calculator::WExpression::function(std::string function_name)\n{\n//    double result {0.0};\n    Token t {ts.pop()};\n    std::vector<double> args;\n    auto endBracket = [](TokenKind tk)->TokenKind{\n        switch (tk)\n        {\n            case TokenKind::bracket_left0:\n                return TokenKind::bracket_right0;\n            case TokenKind::bracket_left1:\n                return TokenKind::bracket_right1;\n            default:\n                return tk;\n        }\n    };\n    switch (t.kind)\n    {\n        case TokenKind::bracket_left0:\n        case TokenKind::bracket_left1:\n        {\n            while (ist)\n            {\n                double d {expression()};\n                args.push_back(d);\n                Token t2 {ts.pop()};\n                if (t2.kind != TokenKind::comma)\n                {\n                    ts.push(t2);\n                    break;\n                }\n            } // args is done\n            Token t3 {ts.pop()};\n            if (t3.kind != endBracket(t.kind))\n                throw std::logic_error(\"correct bracket_right is expected\");\n            break;\n        }\n        default:\n            throw std::logic_error(\"bracket_left is expected\");\n    }\n    if (function_name == \"pow\")\n    {\n        if (args.size() != 2)\n            throw std::logic_error(\"2 args for pow function\");\n        return std::pow(args[0], args[1]);\n    }\n    else if (function_name == \"cos\")\n    {\n        if (args.size() != 1)\n            throw std::logic_error(\"1 args for cos function\");\n        return std::cos(args[0]);\n    }\n    else if (function_name == \"sin\")\n    {\n        if (args.size() != 1)\n            throw std::logic_error(\"1 args for sin function\");\n        return std::sin(args[0]);\n    }\n    else if (function_name == \"tan\")\n    {\n        if (args.size() != 1)\n            throw std::logic_error(\"1 args for tan function\");\n        return std::tan(args[0]);\n    }\n    else if (function_name == \"acos\")\n    {\n        if (args.size() != 1)\n            throw std::logic_error(\"1 args for acos function\");\n        return std::acos(args[0]);\n    }\n    else if (function_name == \"asin\")\n    {\n        if (args.size() != 1)\n            throw std::logic_error(\"1 args for asin function\");\n        return std::asin(args[0]);\n    }\n    else if (function_name == \"atan\")\n    {\n        if (args.size() != 1)\n            throw std::logic_error(\"1 args for atan function\");\n        return std::atan(args[0]);\n    }\n    else if (function_name == \"atan2\")\n    {\n        if (args.size() != 2)\n            throw std::logic_error(\"2 args for atan2 function\");\n        return std::atan2(args[0], args[1]);\n    }\n    else if (function_name == \"exp\")\n    {\n        if (args.size() != 1)\n            throw std::logic_error(\"1 args for exp function\");\n        return std::exp(args[0]);\n    }\n    else if (function_name == \"log\")\n    {\n        if (args.size() != 1)\n            throw std::logic_error(\"1 args for log function\");\n        return std::log(args[0]);\n    }\n    else if (function_name == \"log10\")\n    {\n        if (args.size() != 1)\n            throw std::logic_error(\"1 args for log10 function\");\n        return std::log10(args[0]);\n    }\n    else if (function_name == \"sqrt\")\n    {\n        if (args.size() != 1)\n            throw std::logic_error(\"1 args for sqrt function\");\n        return std::sqrt(args[0]);\n    }\n    else if (function_name == \"abs\")\n    {\n        if (args.size() != 1)\n            throw std::logic_error(\"1 args for abs function\");\n        return std::fabs(args[0]);\n    }\n    else\n    {\n        throw std::logic_error(\"undefined function\"+function_name);\n    }\n\n\n}\n\ncalculator::Token calculator::Token_stream::pop()\n{\n    if (!(data.empty()))\n    {\n        auto res = data.top();\n        data.pop();\n        return res;\n    }\n    Token result;\n    if (!ist) return result;\n    char sym {0};\n    ist >> sym;\n    if (ist.eof()) return result;\n    switch (sym)\n    {\n        case '(':\n            result.kind = TokenKind::bracket_left0;\n            break;\n        case ')':\n            result.kind = TokenKind::bracket_right0;\n            break;\n        case '{':\n            result.kind = TokenKind::bracket_left1;\n            break;\n        case '}':\n            result.kind = TokenKind::bracket_right1;\n            break;\n        case '*':\n            result.kind = TokenKind::multiply;\n            break;\n        case '/':\n            result.kind = TokenKind::divide;\n            break;\n        case '%':\n            result.kind = TokenKind::mod;\n            break;\n        case '+':\n            result.kind = TokenKind::plus;\n            break;\n        case '-':\n            result.kind = TokenKind::minus;\n            break;\n        case '!':\n            result.kind = TokenKind::factorial;\n            break;\n        case ',':\n            result.kind = TokenKind::comma;\n            break;\n        case '.':\n        case '0':\n        case '1':\n        case '2':\n        case '3':\n        case '4':\n        case '5':\n        case '6':\n        case '7':\n        case '8':\n        case '9':\n        {\n            ist.unget();\n            double val {0.0};\n            ist >> val;\n            result.kind = TokenKind::number;\n            result.value = val;\n            break;\n        }\n        default:\n        {\n            if (isalpha(sym)) // function or variable name: func ( | lsldkm239283\n            {\n                std::string s;\n                s += sym;\n                char ch {0};\n                while (ist.get(ch) && (isalpha(ch) || isdigit(ch))) s += ch;\n                ist.putback(ch);\n                ist >> ch;\n                if (ch == '(' || ch == '{')\n                {\n                    ist.putback(ch);\n                    result.kind = TokenKind::function;\n                    result.name = s;\n                    break;\n                }\n                else\n                {\n                    ist.putback(ch);\n                    result.kind = TokenKind::variable;\n                    result.name = s;\n                    break;\n                }\n            }\n            else\n            {\n                throw std::logic_error(\"bad Token\");\n            }\n        }\n    }\n    return result;\n}\n", "meta": {"hexsha": "4cc3361c6f50c20e006e5f120887451fc2e8df35", "size": 11774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel.cpp", "max_stars_repo_name": "vega1986/wcalc_expression_parser", "max_stars_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel.cpp", "max_issues_repo_name": "vega1986/wcalc_expression_parser", "max_issues_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel.cpp", "max_forks_repo_name": "vega1986/wcalc_expression_parser", "max_forks_repo_head_hexsha": "e9645a5fa8086c4108ce4dc1f3ad7da3cead6480", "max_forks_repo_licenses": ["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.1002386635, "max_line_length": 85, "alphanum_fraction": 0.4556650246, "num_tokens": 2618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6358807935268943}}
{"text": "#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <iostream>\n#include <vector>\n#include <map>\n#include <png.h>\n#include <TaskGraph>\n#include <TaskUserFunctions.h>\n#include <boost/ptr_container/ptr_vector.hpp>\n#include \"mandelbrot.hpp\"\n\nusing namespace tg;\n\nconst float gamma_exponent = 3.5;\nconst int max_iterations = 1000;\n\nconst int max_alloc = 1024*176; // Allocate up to 176K\nconst int width = 12800;\nconst int height = 9600;\nconst char* output_filename = \"mandelbrot_set_tu.png\";\n\nstruct TgInfo\n{\n  int startRow;\n  int rowCount;\n  char* data; \n};\n\nint main(int argc, char* argv[])\n{\n  int threads;\n  const Options options = getOptions(\"mandelbrot_tu\", argc, argv);\n\n  if (options.threads < 1 || options.threads > NUM_SPES)\n  {\n    std::cerr << \"Please select a number of threads between 1 and \" << NUM_SPES << \" (inclusive).\" << std::endl;\n    exit(EXIT_FAILURE);\n  }\n  else\n  {\n    threads = options.threads;\n  }\n\n  const int rowSize = width * sizeof(char);\n  const int rowMultiple = max_alloc/rowSize;\n  unsigned int arraySize[2] = {rowMultiple, width};\n\n  std::cout << \"Calculating mandelbrot of size \" << width << \" x \" << height << \".\" << std::endl;\n  std::cout << \"Will transfer data in blocks of \" << rowSize*rowMultiple << \" bytes.\" << std::endl;\n\n  tuTaskGraph mandel;\n  tu_taskgraph(mandel)\n  {\n    tParameter(tVarNamed(int, startRow, \"startRow\"));\n    tParameter(tVarNamed(int, rowCount, \"rowCount\"));\n    tParameter(tArrayFromListNamed(char, imageData, 2, arraySize, \"imageData\"));\n\n    tVar(float, x);\n    tVar(float, y);\n    tVar(float, x0);\n    tVar(float, y0);\n    tVar(float, xtemp);\n    tVar(int, x_pos);\n    tVar(int, y_pos);\n    tVar(int, iteration);\n    tVar(float, pixel);\n  \n    tFor(y_pos, startRow, startRow+rowCount-1)\n    {\n      y0 = (y_pos * (3.0f / height)) - 1.5f;\n      \n      tFor(x_pos, 0, width-1)\n      {\n        // Scale the pixel location to be +- 2 from the origin of the complex plane\n        x0 = (x_pos * (3.5f / width)) - 2.5f;\n        x = x0;\n        y = y0;\n        iteration = 0;\n      \n        // Test if this location is in the set\n        tWhile ((x*x + y*y) < 4.0f && iteration  < max_iterations) {\n          xtemp = (x*x) - (y*y) + x0;\n          y = 2*x*y + y0;\n          x = xtemp;\n          iteration+=1;\n        }\n        \n        // Calculate and set the value of the pixel\n        tIf(iteration == max_iterations)\n          pixel = 0.0f;\n        tElse\n          pixel = 8.0f * (iteration + 1.0f - tLogf(tLogf(tSqrtf(x*x + y*y))) / std::log(2.0f)) / max_iterations;\n\n        imageData[y_pos-startRow][x_pos] = tPowf(pixel, (1.0f / gamma_exponent)) * 255.0f;\n      }\n    }\n  }\n \n  mandel.compile(tg::SPU_GCC, false);\n\n  boost::ptr_vector<tuTaskGraph> taskGraphs; \n  std::map<tuTaskGraph*, TgInfo> tgInfo;\n  TaskFarm farm;\n\n  for(int thread=0; thread<threads; ++thread)\n  {\n    taskGraphs.push_back(new tuTaskGraph(mandel)); \n    farm.add(&taskGraphs.back());\n    tgInfo[&taskGraphs.back()].data = static_cast<char*>(spu_malloc(rowSize*rowMultiple));\n  }\n  \n  FILE *output_file;\n  png_structp png_ptr;\n  png_infop info_ptr;\n  \n  if (!(output_file = fopen(output_filename, \"wb\"))) {\n    std::cerr << \"Unable to open \" << output_filename << \" for writing. Aborting now.\" << std::endl;\n    exit(1);\n  }\n  \n  if (!(png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL))) {\n    std::cerr << \"Failed to create png write struct. Aborting now.\" << std::endl;\n    exit(1);\n  }\n  \n  if (!(info_ptr = png_create_info_struct(png_ptr))) {\n    std::cerr << \"Failed to create png info struct. Aborting now.\" << std::endl;\n    // Clean up\n    png_destroy_write_struct(&png_ptr,static_cast<png_infopp>(NULL));\n    exit(1);\n  }\n  \n  png_init_io(png_ptr, output_file);  \n  png_set_IHDR(png_ptr, info_ptr, width, height, 8,\n               PNG_COLOR_TYPE_PALETTE,\n               PNG_INTERLACE_NONE,\n               PNG_COMPRESSION_TYPE_DEFAULT,\n               PNG_FILTER_TYPE_DEFAULT);\n  png_set_gamma(png_ptr, 0.5, 0.45455);\n\n  std::vector<png_color> palette(generateRedYellowColourMap());\n  png_set_PLTE(png_ptr, info_ptr, &palette[0], palette.size());\n  png_write_info(png_ptr, info_ptr);\n\n  int currentRow = 0;\n\n  while(currentRow < height)\n  {\n    for(int thread=0; thread<threads; ++thread)\n    {\n      tgInfo[&taskGraphs[thread]].startRow = currentRow;\n      tgInfo[&taskGraphs[thread]].rowCount = std::min(rowMultiple, height-currentRow);\n      currentRow+=tgInfo[&taskGraphs[thread]].rowCount;\n    \n      taskGraphs[thread].setParameter(\"startRow\", &tgInfo[&taskGraphs[thread]].startRow);\n      taskGraphs[thread].setParameter(\"rowCount\", &tgInfo[&taskGraphs[thread]].rowCount);\n      taskGraphs[thread].setParameter(\"imageData\", tgInfo[&taskGraphs[thread]].data);\n    }\n\n    farm.execute();\n    \n    for(int thread=0; thread<threads; ++thread)\n    {\n      for (int line = 0; line<tgInfo[&taskGraphs[thread]].rowCount; ++line) \n      {\n        png_bytep png_row_ptr = reinterpret_cast<png_bytep>(tgInfo[&taskGraphs[thread]].data + rowSize*line);\n        png_write_row(png_ptr, png_row_ptr);\n      }\n    }\n  }\n  \n  std::cout << \"Done.\" << std::endl;\n\n  png_write_end(png_ptr, info_ptr);\n  png_destroy_write_struct(&png_ptr, &info_ptr);\n\n  for(int thread=0; thread<threads; ++thread)\n    spu_free(tgInfo[&taskGraphs[thread]].data);\n\n  exit(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "7344a225829ef79aa97a02d271c85d068278fb3d", "size": 5334, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/cell/mandelbrot/mandelbrot_tu.cc", "max_stars_repo_name": "paulhjkelly/taskgraph-metaprogramming", "max_stars_repo_head_hexsha": "54c4e2806a97bec555a90784ab4cf0880660bf89", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-04-11T21:30:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T16:16:09.000Z", "max_issues_repo_path": "examples/cell/mandelbrot/mandelbrot_tu.cc", "max_issues_repo_name": "paulhjkelly/taskgraph-metaprogramming", "max_issues_repo_head_hexsha": "54c4e2806a97bec555a90784ab4cf0880660bf89", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/cell/mandelbrot/mandelbrot_tu.cc", "max_forks_repo_name": "paulhjkelly/taskgraph-metaprogramming", "max_forks_repo_head_hexsha": "54c4e2806a97bec555a90784ab4cf0880660bf89", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1475409836, "max_line_length": 112, "alphanum_fraction": 0.6347956505, "num_tokens": 1563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6358393738972841}}
{"text": "#ifndef YANNQ_GEOMETRY_FISHERMATIRX_HPP\n#define YANNQ_GEOMETRY_FISHERMATIRX_HPP\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"Utilities/Utility.hpp\"\n#include \"Observables/Observable.hpp\"\n\n#include <Eigen/IterativeLinearSolvers>\n#include <unsupported/Eigen/IterativeSolvers>\n\nnamespace yannq\n{\ntemplate<typename Machine>\nclass FisherMatrix;\n} //namespace yannq\n\nnamespace Eigen {\nnamespace internal {\n\ttemplate<typename Machine>\n\tstruct traits<yannq::FisherMatrix<Machine> > :  public Eigen::internal::traits<Eigen::SparseMatrix<typename Machine::Scalar> > {};\n}\n} //namespace Eigen\n\nnamespace yannq\n{\n/** \n * Construct the fisher information metric for quantum states\n * */\ntemplate<class Machine>\nclass FisherMatrix\n\t: public Observable<FisherMatrix<Machine> >, \n\tpublic Eigen::EigenBase<FisherMatrix<Machine> >\n{\npublic:\n\tusing Scalar = typename Machine::Scalar;\n\tusing RealScalar = typename remove_complex<Scalar>::type;\n\n\tusing Matrix = typename Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n\tusing Vector = typename Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\tusing RealMatrix = typename Eigen::Matrix<RealScalar, Eigen::Dynamic, Eigen::Dynamic>;\n\tusing RealVector = typename Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n\nprivate:\n\tuint32_t n_;\n\n\tconst Machine& qs_;\n\tRealScalar shift_;\n\t\n\tMatrix deltas_;\n\tVector deltaMean_;\n\npublic:\n\t// Required typedefs, constants, and method:\n\ttypedef int StorageIndex;\n\n\tenum {\n\t\tColsAtCompileTime = Eigen::Dynamic,\n\t\tMaxColsAtCompileTime = Eigen::Dynamic,\n\t\tIsRowMajor = false\n\t};\n\n\tEigen::Index rows() const { return qs_.getDim(); }\n\tEigen::Index cols() const { return qs_.getDim(); }\n\n\ttemplate<typename Rhs>\n\tEigen::Product<FisherMatrix<Machine>, Rhs, Eigen::AliasFreeProduct> \n\t\t\toperator*(const Eigen::MatrixBase<Rhs>& x) const {\n\t  return Eigen::Product<FisherMatrix<Machine>, Rhs, Eigen::AliasFreeProduct>(*this, x.derived());\n\t}\n\n\tvoid setShift(RealScalar shift)\n\t{\n\t\tshift_ = shift;\n\t}\n\n\tRealScalar getShift() const\n\t{\n\t\treturn shift_;\n\t}\n\n\tvoid initIter(int nsmp)\n\t{\n\t\tdeltas_.setZero(nsmp, qs_.getDim());\n\t}\n\n\ttemplate<class Elt, class State>\n\tinline void eachSample(int n, Elt&& elt, State&& state)\n\t{\n\t\t(void)state;\n\t\tdeltas_.row(n) = qs_.logDeriv(elt);\n\t}\n\n\tvoid finIter()\n\t{\n\t\tdeltaMean_ = deltas_.colwise().mean();\n\t\tdeltas_ = deltas_.rowwise() - deltaMean_.transpose();\n\t}\n\n\t/**\n\t * \\param weights normalized weights for each sigma\n\t * */\n\tvoid finIter(const Eigen::Ref<const RealVector>& weights)\n\t{\n\t\tweights_ = weights;\n\t\tdeltaMean_ = weights.transpose()*deltas_;\n\t\tdeltas_ = deltas_.rowwise() - deltaMean_.transpose();\n\t}\n\n\tinline \n\tconst Matrix& logDervs() const&\n\t{\n\t\treturn deltas_;\n\t}\n\n\tinline \n\tMatrix logDervs() &&\n\t{\n\t\treturn std::move(deltas_);\n\t}\n\n\tinline \n\tconst Vector& oloc() const&\n\t{\n\t\treturn deltaMean_;\n\t}\n\tinline \n\tVector oloc() &&\n\t{\n\t\treturn std::move(deltaMean_);\n\t}\n\n\tMatrix corrMat() const\n\t{\n\t\tint nsmp = deltas_.rows();\n\t\tif(weights_.size() == 0)\n\t\t\treturn (deltas_.adjoint() * deltas_)/nsmp;\n\t\telse\n\t\t\treturn (deltas_.adjoint() * weights_.asDiagonal() * deltas_);\n\t}\n\n\tRealVector diagCorrMat() const\n\t{\n\t\tRealMatrix sqrDeltas = deltas_.cwiseAbs2();\n\t\treturn sqrDeltas.colwise().mean();\n\t}\n\t\n\tFisherMatrix(const Machine& qs)\n\t  : n_{qs.getN()}, qs_(qs), shift_{1e-3}\n\t{\n\t}\n\n\ttemplate<class Rhs>\n\ttypename Machine::Vector apply(const Rhs& rhs) const\n\t{\n\t\tassert(rhs.size() == qs_.getDim());\n\t\tVector r = deltas_*rhs;\n\n\t\tVector res;\n\t\t\n\t\tif(weights_.size() == 0)\n\t\t\tres = deltas_.adjoint()*r/r.rows();\n\t\telse\n\t\t\tres = deltas_.adjoint() * weights_.asDiagonal() * r;\n\n\t\treturn res + Scalar(shift_)*rhs;\n\t}\n};\n}//namespace yannq\n\n// Implementation of yannq::SRMat * Eigen::DenseVector though a specialization of internal::generic_product_impl:\nnamespace Eigen {\nnamespace internal {\n\ttemplate<typename Rhs, typename Machine>\n\tstruct generic_product_impl<yannq::FisherMatrix<Machine>, Rhs, SparseShape, DenseShape, GemvProduct> // GEMV stands for matrix-vector\n\t: generic_product_impl_base<yannq::FisherMatrix<Machine>, Rhs, generic_product_impl<yannq::FisherMatrix<Machine>, Rhs> >\n\t{\n\t\ttypedef typename Product<yannq::FisherMatrix<Machine>, Rhs>::Scalar Scalar;\n\t\ttemplate<typename Dest>\n\t\tstatic void scaleAndAddTo(Dest& dst, const yannq::FisherMatrix<Machine>& lhs, const Rhs& rhs, const Scalar& alpha)\n\t\t{\n\t\t\t// This method should implement \"dst += alpha * lhs * rhs\" inplace,\n\t\t\t// however, for iterative solvers, alpha is always equal to 1, so let's not bother about it.\n\t\t\tassert(alpha==Scalar(1) && \"scaling is not implemented\");\n\t\t\tEIGEN_ONLY_USED_FOR_DEBUG(alpha);\n\n\t\t\tdst += lhs.apply(rhs);\n\t\t}\n\t};\n} //namespace internal\n} //namespace Eigen\n\n#endif//YANNQ_GEOMETRY_FISHERMATIRX_HPP\n", "meta": {"hexsha": "0c93c023613f5c6ab1b448e2668732cae180e3fd", "size": 4698, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Observables/FisherMatrix.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Observables/FisherMatrix.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Observables/FisherMatrix.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2164948454, "max_line_length": 134, "alphanum_fraction": 0.7166879523, "num_tokens": 1286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6358393610041798}}
{"text": "/*\n * Copyright Andrey Semashev 2020\n *\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/*!\n * \\file bit_ceil.hpp\n *\n * This header defines \\c bit_ceil algorithm, which produces a nearest power of 2 integer\n * that is greater or equal to the input integer.\n */\n\n#ifndef BOOST_BIT_OPS_POW2_BIT_CEIL_HPP_INCLUDED_\n#define BOOST_BIT_OPS_POW2_BIT_CEIL_HPP_INCLUDED_\n\n#include <limits>\n#include <boost/bit_ops/detail/config.hpp>\n#include <boost/bit_ops/detail/type_traits/enable_if.hpp>\n#include <boost/bit_ops/detail/type_traits/is_integral.hpp>\n#include <boost/bit_ops/detail/type_traits/is_unsigned.hpp>\n#include <boost/bit_ops/count/countl_zero.hpp>\n\nnamespace boost {\nnamespace bit_ops {\n\n/*!\n * \\brief Returns the nearest power of 2 integer that is greater or equal to \\a value\n *\n * \\pre \\a value must not be zero\n */\ntemplate< typename T >\ninline typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,\n    T\n>::type bit_ceil_nz(T value) BOOST_NOEXCEPT\n{\n    return static_cast< T >(1u) << ((std::numeric_limits< T >::digits - 1u) - bit_ops::countl_zero_nz(value) + ((value & (value - 1u)) != 0u));\n}\n\n//! Returns the nearest power of 2 integer that is greater or equal to \\a value\ntemplate< typename T >\ninline typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,\n    T\n>::type bit_ceil(T value) BOOST_NOEXCEPT\n{\n    // bit_ceil(0) == bit_ceil(1) == 1\n    return value == 0u ? static_cast< T >(1u) : bit_ops::bit_ceil_nz(value);\n}\n\n} // namespace bit_ops\n} // namespace boost\n\n#endif // BOOST_BIT_OPS_POW2_BIT_CEIL_HPP_INCLUDED_\n", "meta": {"hexsha": "250807fab39b0c77e6bdcdfaa593b6f06a08fe64", "size": 1791, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/bit_ops/pow2/bit_ceil.hpp", "max_stars_repo_name": "Lastique/bit_ops", "max_stars_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/pow2/bit_ceil.hpp", "max_issues_repo_name": "Lastique/bit_ops", "max_issues_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "max_issues_repo_licenses": ["BSL-1.0"], "max_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/bit_ops/pow2/bit_ceil.hpp", "max_forks_repo_name": "Lastique/bit_ops", "max_forks_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "max_forks_repo_licenses": ["BSL-1.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.4210526316, "max_line_length": 143, "alphanum_fraction": 0.7252931323, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6358076938143955}}
{"text": "#include <string>\n#include <memory>\n#include <complex>\n#include <vector>\n#include <cmath>\n#include <sndfile.h>\n#include <fftw3.h>\n// #include <boost/format.hpp>\n\nusing std::complex;\nusing std::vector;\nusing std::pair;\n\n// LPC \u4fc2\u6570\u306e\u6b21\u6570\nconst int LPC_ORDER = 64;\n\n// \u89e3\u6790\u306b\u7528\u3044\u308b\u5fae\u5c0f\u533a\u9593 (sec)\nconst double WINDOW_DURATION = 0.04;\n\n// FFT \u3059\u308b\nvector<double> fft(const vector<double>& input);\n\n// LPC \u30b9\u30da\u30af\u30c8\u30eb\u5305\u7d61\u3092\u5f97\u308b\nvector<double> lpc(const vector<double>& input, int order, double df);\n\n// [1 : -1] \u306b\u6b63\u898f\u5316\nvector<double> normalize(const vector<double>& input);\n\n// \u30cf\u30df\u30f3\u30b0\u7a93\u3092\u304b\u3051\u308b\nvector<double> hamming(const vector<double>& input);\n\n// \u30c7\u30b8\u30bf\u30eb\u30d5\u30a3\u30eb\u30bf\nvector<double> freqz(const vector<double>& b, const vector<double>& a, double df, int N);\n\n// \u30d5\u30a9\u30eb\u30de\u30f3\u30c8 f1 / f2 \u3092\u8fd4\u3059\npair<double, double> formant(const vector<double>& input, double df);\n\n// \u30d5\u30a9\u30eb\u30de\u30f3\u30c8\u304b\u3089\u6bcd\u97f3\u3092\u63a8\u5b9a\u3059\u308b\nstd::string vowel(double f1, double f2);\n\n// \u4e0e\u3048\u3089\u308c\u305f\u7bc4\u56f2\u306e\u97f3\u306e\u5e73\u5747\ndouble volume(const vector<double>& input);\n\n\nint main()\n{\n\t// \u97f3\u58f0\u30d5\u30a1\u30a4\u30eb\u8aad\u307f\u8fbc\u307f\n\tSF_INFO sinfo;\n\tstd::shared_ptr<SNDFILE> sf(\n\t\tsf_open(\"aiueo.wav\", SFM_READ, &sinfo), [](SNDFILE* ptr) { sf_close(ptr); });\n\tconst int frame = sinfo.frames;\n\tstd::unique_ptr<short[]> input(new short[frame]);\n\tconst double sample_rate = sinfo.samplerate;\n\tconst double dt = 1.0 / sample_rate;\n\tsf_read_short(sf.get(), input.get(), frame);\n\n\t// \u5fae\u5c0f\u97f3\u58f0\u533a\u9593\u53d6\u308a\u51fa\u3057\n\tconst int window_size = static_cast<int>(WINDOW_DURATION / dt);\n\tconst double df  = 1.0 / (window_size / sample_rate);\n\tfor (int n = 0; n < frame / window_size; ++n) {\n\t\tvector<double> data;\n\t\tfor (int i = window_size * n; i < window_size * (n + 1) && i < frame; ++i) {\n\t\t\tdata.push_back(input[i]);\n\t\t}\n\t\tauto hamming_result = normalize( hamming(data) );\n\n\t\tauto lpc_result = normalize( lpc(hamming_result, LPC_ORDER, df) );\n\t\tauto fft_result = normalize( fft(hamming_result) );\n\n\t\t// \u5f97\u3089\u308c\u305f LPC \u30b9\u30da\u30af\u30c8\u30eb\u5305\u7d61\u7dda\u304b\u3089\u30d5\u30a9\u30eb\u30de\u30f3\u30c8\u3092\u62bd\u51fa\n\t\tauto formant_result = formant(lpc_result, df);\n\t\tdouble f1 = formant_result.first;\n\t\tdouble f2 = formant_result.second;\n\n\t\tif (volume(data) < 1e4) {\n\t\t\tstd::cout << \"-\";\n\t\t} else {\n\t\t\tstd::cout << boost::format(\"%1%  (f1:%2%, f2:%3%)\")\n\t\t\t\t% vowel(f1, f2) % f1 % f2;\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\t// Gnuplot \u3067\u7d50\u679c\u3092\u78ba\u8a8d\n\tstd::shared_ptr<FILE> freq_graph(\n\t\tpopen(\"gnuplot -persist\", \"w\"), [](FILE* ptr) { pclose(ptr); });\n\tfprintf(freq_graph.get(), \"load 'freq.plt'\\n\");\n\n\t// std::shared_ptr<FILE> wav_graph(\n\t// \tpopen(\"gnuplot -persist\", \"w\"), [](FILE* ptr) { pclose(ptr); });\n\t// fprintf(wav_graph.get(), \"load 'wav.plt'\\n\");\n\n\treturn 0;\n}\n\n\n// FFT\nvector<double> fft(const vector<double>& input)\n{\n\tconst int frame = input.size();\n\tvector<complex<double>> in(frame), out(frame);\n\tauto plan = fftw_plan_dft_1d(\n\t\t\tframe,\n\t\t\treinterpret_cast<fftw_complex*>(&in[0]),\n\t\t\treinterpret_cast<fftw_complex*>(&out[0]),\n\t\t\tFFTW_FORWARD, FFTW_ESTIMATE\n\t);\n\tfor (int i = 0; i < frame; ++i) {\n\t\tin[i] = complex<double>(input[i], 0.0);\n\t}\n\tfftw_execute(plan);\n\n\tvector<double> fft_result(frame);\n\tfor (int i = 0; i < frame; ++i) {\n\t\tfft_result[i] = abs(out[i]);\n\t}\n\n\treturn fft_result;\n}\n\n\n// LPC\nvector<double> lpc(const vector<double>& input, int order, double df)\n{\n\tconst int N = input.size();\n\n\t// \u81ea\u5df1\u76f8\u95a2\u95a2\u6570\n\tvector<double> r(N);\n\tconst int lags_num = order + 1;\n\tfor (int l = 0; l < lags_num; ++l) {\n\t\tr[l] = 0.0;\n\t\tfor (int n = 0; n < N - l; ++n) {\n\t\t\tr[l] += input[n] * input[n + l];\n\t\t}\n\t}\n\n\t// Levinson-Durbin \u306e\u30a2\u30eb\u30b4\u30ea\u30ba\u30e0\u3067 LPC \u4fc2\u6570\u3092\u8a08\u7b97\n\tvector<double> a(order + 1, 0.0), e(order + 1, 0.0);\n\ta[0] = e[0] = 1.0;\n\ta[1] = - r[1] / r[0];\n\te[1] = r[0] + r[1] * a[1];\n\tfor (int k = 1; k < order; ++k) {\n\t\tdouble lambda = 0.0;\n\t\tfor (int j = 0; j < k + 1; ++j) {\n\t\t\tlambda -= a[j] * r[k + 1 - j];\n\t\t}\n\t\tlambda /= e[k];\n\n\t\tvector<double> U(k + 2), V(k + 2);\n\t\tU[0] = 1.0; V[0] = 0.0;\n\t\tfor (int i = 1; i < k + 1; ++i) {\n\t\t\tU[i] = a[i];\n\t\t\tV[k + 1 - i] = a[i];\n\t\t}\n\t\tU[k + 1] = 0.0; V[k + 1] = 1.0;\n\n\t\tfor (int i = 0; i < k + 2; ++i) {\n\t\t\ta[i] = U[i] + lambda * V[i];\n\t\t}\n\n\t\te[k + 1] = e[k] * (1.0 - lambda * lambda);\n\t}\n\n\t// LPC \u4fc2\u6570\u304b\u3089\u97f3\u58f0\u4fe1\u53f7\u518d\u73fe\n\t// vector<double> lpc_result(N, 0.0);\n\t// for (int i = 0; i < N; ++i) {\n\t// \tif (i < order) {\n\t// \t\tlpc_result[i] = input[i];\n\t// \t} else {\n\t// \t\tfor (int j = 1; j < order; ++j) {\n\t// \t\t\tlpc_result[i] -= a[j] * input[i + 1 - j];\n\t// \t\t}\n\t// \t}\n\t// }\n\t// return lpc_result;\n\n\treturn freqz(e, a, df, N);\n}\n\n\n// \u6b63\u898f\u5316\nvector<double> normalize(const vector<double>& input)\n{\n\t// \u6700\u5927 / \u6700\u5c0f\u5024\n\tauto max = abs( *std::max_element(input.begin(), input.end()) );\n\tauto min = abs( *std::min_element(input.begin(), input.end()) );\n\tdouble factor = std::max(max, min);\n\tvector<double> result( input.size() );\n\tstd::transform(input.begin(), input.end(), result.begin(), [factor](double x) {\n\t\treturn x / factor;\n\t});\n\treturn result;\n}\n\n\n// \u30cf\u30df\u30f3\u30b0\u7a93\u3092\u304b\u3051\u308b\nvector<double> hamming(const vector<double>& input)\n{\n\tconst double N = input.size();\n\tvector<double> result(N);\n\tfor (int i = 1; i < N - 1; ++i) {\n\t\tconst double h = 0.54 - 0.46 * cos(2 * M_PI * i / (N - 1));\n\t\tresult[i] = input[i] * h;\n\t}\n\tresult[0] = result[N - 1] = 0;\n\treturn result;\n}\n\n\n// \u30c7\u30b8\u30bf\u30eb\u30d5\u30a3\u30eb\u30bf\nvector<double> freqz(const vector<double>& b, const vector<double>& a, double df, int N)\n{\n\tvector<double> H(N);\n\tfor (int n = 0; n < N + 1; ++n) {\n\t\tauto z = std::exp(complex<double>(0.0, -2.0 * M_PI * n / N));\n\t\tcomplex<double> numerator(0.0, 0.0), denominator(0.0, 0.0);\n\t\tfor (int i = 0; i < b.size(); ++i) {\n\t\t\tnumerator += b[b.size() - 1 - i] * pow(z, i);\n\t\t}\n\t\tfor (int i = 0; i < a.size(); ++i) {\n\t\t\tdenominator += a[a.size() - 1 - i] * pow(z, i);\n\t\t}\n\t\tH[n] = abs(numerator / denominator);\n\t}\n\n\treturn H;\n}\n\n\n// \u30d5\u30a9\u30eb\u30de\u30f3\u30c8 f1 / f2 \u3092\u8fd4\u3059\npair<double, double> formant(const vector<double>& input, double df)\n{\n\tpair<double, double> result(0.0, 0.0);\n\tbool is_find_first = false;\n\tfor (int i = 1; i < input.size() - 1; ++i) {\n\t\tif (input[i] > input[i-1] && input[i] > input[i+1]) {\n\t\t\tif (!is_find_first) {\n\t\t\t\tresult.first = df * i;\n\t\t\t\tis_find_first = true;\n\t\t\t} else {\n\t\t\t\tresult.second = df * i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\n\n// \u6bcd\u97f3\u3092\u63a8\u5b9a\n// NOTE: \u6a5f\u68b0\u5b66\u7fd2\u306b\u3059\u308b\u4e88\u5b9a\nstd::string vowel(double f1, double f2)\n{\n\tif (f1 > 600 && f1 < 1400 && f2 > 900  && f2 < 2000) return \"a\";\n\tif (f1 > 100 && f1 < 410  && f2 > 1900 && f2 < 3500) return \"i\";\n\tif (f1 > 100 && f1 < 700  && f2 > 1100 && f2 < 2000) return \"u\";\n\tif (f1 > 400 && f1 < 800  && f2 > 1700 && f2 < 3000) return \"e\";\n\tif (f1 > 300 && f1 < 900  && f2 > 500  && f2 < 1300) return \"o\";\n\treturn \"-\";\n}\n\n\n// \u30dc\u30ea\u30e5\u30fc\u30e0\ndouble volume(const vector<double>& input)\n{\n\tdouble v = 0.0;\n\tstd::for_each(input.begin(), input.end(), [&v](double x) { v += x*x; });\n\tv /= input.size();\n\treturn v;\n}\n", "meta": {"hexsha": "0c3da9e0433a012ecc229dddb286a4b461738ca1", "size": 6522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sample/multitask/Vowel.cpp", "max_stars_repo_name": "meganetaaan/suburi-m5stack", "max_stars_repo_head_hexsha": "199478636a3e88aea87bac27ace293b3618acf36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sample/multitask/Vowel.cpp", "max_issues_repo_name": "meganetaaan/suburi-m5stack", "max_issues_repo_head_hexsha": "199478636a3e88aea87bac27ace293b3618acf36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sample/multitask/Vowel.cpp", "max_forks_repo_name": "meganetaaan/suburi-m5stack", "max_forks_repo_head_hexsha": "199478636a3e88aea87bac27ace293b3618acf36", "max_forks_repo_licenses": ["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.0664206642, "max_line_length": 89, "alphanum_fraction": 0.5855565777, "num_tokens": 2497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6357918379502594}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/blas_wrapper.hpp>\n\n#define BOOST_TEST_MODULE FrovedisTest\n#include <boost/test/unit_test.hpp>\n#include \"../../rmse.hpp\"\n\nusing namespace frovedis;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    // creating a colmajor matrix local from file\n    colmajor_matrix_local<float> cm1 (\n    make_rowmajor_matrix_local_load<float>(\"./sample_3x4\"));\n    auto cm2 = cm1;\n  \n    // slicing row and col\n    auto row1 = make_row_vector<float> (cm1,0); // (4x1)\n    auto col1 = make_col_vector<float> (cm1,0); // (3x1)\n\n    // col1-of-cm1 = cm2*row1-of-cm1\n    gemv<float>(cm2,row1,col1); // (3x4) * (4x1) => (OK)\n\n    bool isError = false;\n    // row1-of-cm1 = cm2*col1-of-cm1\n    try {\n      gemv<float>(cm2,col1,row1); // (3x4) * (3x1) => (Error)\n    }\n    catch (exception& e) {\n      isError = true;\n    }\n    BOOST_CHECK (isError);\n\n    // row1-of-cm1 = trans(cm2)*col1-of-cm1\n    gemv<float>(cm2,col1,row1,'T'); // (4x3) * (3x1) => (OK)\n\n    double tol = 0.01;\n    colmajor_matrix_local<float> ref (\n    make_rowmajor_matrix_local_load<float> (\"./ref_3x4\"));\n    BOOST_CHECK (calc_rms_err<float> (cm1.val, ref.val) < tol);\n}\n\n", "meta": {"hexsha": "e487d4695d32f2089309e8af97a3a94c6fb5c876", "size": 1264, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test6.7-3/test.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "test/matrix/test6.7-3/test.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "test/matrix/test6.7-3/test.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 26.3333333333, "max_line_length": 63, "alphanum_fraction": 0.6321202532, "num_tokens": 421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778823, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6357093071573121}}
{"text": "/*\nTest inner shortened RS code over binary extension field\n*/\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <boost/program_options.hpp>\n#include \"../include/DFT.hpp\"\n#include \"../include/helpers.hpp\"\n#include \"../include/GF2M.hpp\"\n//#include \"../include/encodedecode.hpp\"\n#include \"../include/ReedSolomon.hpp\"\n#include <string>\n#include <fstream>\n#include <streambuf>\n#include <random>\n#include <chrono>\n\n\nusing namespace std;\n\n\n// define static variables \n\n\n\n\nint main(int ac, char* av[])\n{\n\n\n// GF(2^6) with primitive polynomail 91\nconst unsigned m = 6;\nconst unsigned prim_poly = 91;\ntypedef GF2M<m,prim_poly> gf;\n\n// randomness\nrandom_device r;\ndefault_random_engine gen(r());\nuniform_int_distribution<int> randbit(0, 1);\nuniform_int_distribution<int> randint(0, 63);\n\n\n// parameters\nconst unsigned N = 20;\nconst unsigned N_u = 63; // the underlying length of the shortened inner code\nconst unsigned K = 18;\nconst unsigned Qi = 9;\nconst unsigned Pi = 7; //P*Q = 2^6 - 1\n\n\n///// GF2M definitions\n\ngf fa = gf(2,0); // 64 + 2 = 1000010 = x + x^5\n\ncout << \"primitive polynomial: \" << bitset<32>(prim_poly) << endl;\ncout << \"                      \" <<  bitset<32>( (1 << m) ) << endl; \ncout << \"order of a: \" << fa.order() << endl;\n\nDFT_FFT<gf> dftgf(N_u,fa,Pi,Qi); // Fourier transform for the outer code \n//DFT_PRIM<gf> dftgf(N_u,fa);\n\n\n//RScode<gf,DFT_PRIM<gf>> innercode(N,K,fa,dftgf,N_u);\nRScode<gf, DFT_FFT<gf> > innercode(N,K,fa,dftgf,N_u);\n\n///// test the inner code\n\n// generate information\n\nvector<gf> infvec(innercode.k); // information vector; \nfor(gf& el: infvec)\n\tel = gf(randbit(gen),0);\n\n\n\n// encode\n\nvector<gf> c; // outer codeword \ninnercode.RS_shortened_encode(infvec,c);\n\n// disturb\n\nuniform_int_distribution<int> randcoef(0, c.size()-1);\n\n// insert one random error\n// c[randcoef(gen)] = gf(randbit(gen),0);\n\n// insert one random error\nc[randcoef(gen)] = gf();\nc[randcoef(gen)] = gf();\n\n\n// decoding\n\nauto t1 = chrono::high_resolution_clock::now();\nvector<gf> infvecrec;\npair<unsigned,unsigned> erctroc = innercode.RS_shortened_decode(infvecrec,c);\nauto t2 = chrono::high_resolution_clock::now();\ncout << \"decoding took \"\n     << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n     << \" milliseconds\\n\";\n\ncout << \"outer code: \" << erctroc.first << \" errasures, \" << erctroc.second << \" errors corrected\"<< endl;\n\n\nif( infvec ==  infvecrec)\n\tcout << \"I did correct all errors!\" << endl; \nelse\t\n\tcout << \"I couldn't correct all errors!\" << endl; \n\n\n}\n", "meta": {"hexsha": "1e43c8e9eb4acf730018aec9d6528607cda55f87", "size": 2513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testShortRS.cpp", "max_stars_repo_name": "libingzheren/dna_rs_coding", "max_stars_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-12-01T11:55:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T01:57:11.000Z", "max_issues_repo_path": "tests/testShortRS.cpp", "max_issues_repo_name": "libingzheren/dna_rs_coding", "max_issues_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-26T09:13:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-26T15:19:01.000Z", "max_forks_repo_path": "tests/testShortRS.cpp", "max_forks_repo_name": "libingzheren/dna_rs_coding", "max_forks_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-05T06:14:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T09:10:36.000Z", "avg_line_length": 21.852173913, "max_line_length": 106, "alphanum_fraction": 0.6725029845, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6357093003821944}}
{"text": "#include <blitz/array.h>\n\nusing namespace blitz;\n\nint main()\n{\n    Array<int,2> A(6,6), B(3,3);\n  \n    // Set the upper left quadrant of A to 5 \n    A(Range(0,2), Range(0,2)) = 5; \n\n    // Set the upper right quadrant of A to an identity matrix\n    B = 1, 0, 0,\n        0, 1, 0,\n        0, 0, 1;\n    A(Range(0,2), Range(3,5)) = B;\n\n    // Set the fourth row to 1\n    A(3, Range::all()) = 1;\n\n    // Set the last two rows to 0\n    A(Range(4, toEnd), Range::all()) = 0;\n\n    // Set the bottom right element to 8\n    A(5,5) = 8;\n\n    cout << \"A = \" << A << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "115396575dacae8c64d648ed0468a7005b83f6cd", "size": 578, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/doc/examples/slicing.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/slicing.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/slicing.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0625, "max_line_length": 62, "alphanum_fraction": 0.5069204152, "num_tokens": 223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6356752266077291}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <sstream>\n#include <complex>\n#include <tuple>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"miMaS/field.h\"\n#include \"miMaS/complex_field.h\"\n#include \"miMaS/weno.h\"\n#include \"miMaS/fft.h\"\n#include \"miMaS/array_view.h\"\n#include \"miMaS/poisson.h\"\n#include \"miMaS/splitting.h\"\n#include \"miMaS/lagrange5.h\"\n\nnamespace math = boost::math::constants;\nconst std::complex<double> & I = std::complex<double>(0.,1.);\n\n#define SQ(X) ((X)*(X))\n#define Xi(i) (i*fh.step.dx+fh.range.x_min)\n#define Vk(k) (k*fh.step.dv+fh.range.v_min)\n\n#define ping(X) std::cerr << __LINE__ << \" \" << #X << \":\" << X << std::endl\nint debug = 0;\n\nauto\nmaxwellian ( double rho , double u , double T ) {\n  //std::cout << rho << \" \" << u << \" \" << T << std::endl;\n  //std::cout << rho/(std::sqrt(2.*math::pi<double>()*T)) << std::endl;\n  return [=](double x,double v){ return rho/(std::sqrt(2.*math::pi<double>()*T))*std::exp( -0.5*SQ(v-u)/T ); };\n}\n\nint main(int,char**)\n{\n  std::size_t Nx = 135, Nv = 256;\n\n  // $(u_c,E,\\hat{f}_h)$ and $f_h$\n  ublas::vector<double> uc(Nx,0.);\n  ublas::vector<double> E (Nx,0.);\n  field<double,1> fh(boost::extents[Nv][Nx]);\n  complex_field<double,1> hfh(boost::extents[Nv][Nx]);\n\n  const double Kx = 0.5;\n  // phase-space domain\n  fh.range.v_min = -8.; fh.range.v_max = 8.;\n  fh.range.x_min =  0.; fh.range.x_max = 2./Kx*math::pi<double>();\n\n  // compute dx, dv\n  fh.step.dv = (fh.range.v_max-fh.range.v_min)/Nv;\n  fh.step.dx = (fh.range.x_max-fh.range.x_min)/Nx;\n\n  double dt = 0.05;//1.*fh.step.dv;\n  double Tf = 200.;\n  \n  // velocity and frequency\n  ublas::vector<double> v (Nv,0.); for ( std::size_t k=0 ; k<Nv ; ++k ) { v[k] = Vk(k); }\n  const double l = fh.range.x_max-fh.range.x_min;\n  ublas::vector<double> kx(Nx);\n  for ( auto i=0 ; i<Nx/2 ; ++i ) { kx[i]    = 2.*math::pi<double>()*i/l; }\n  for ( int i=-Nx/2 ; i<0 ; ++i ) { kx[Nx+i] = 2.*math::pi<double>()*i/l; }\n\n  // initial condition\n  double ui=2., alpha=0.2;\n  auto tb_M1 = maxwellian(0.5*alpha,ui,1.) , tb_M2 = maxwellian(0.5*alpha,-ui,1.);\n  for (field<double,2>::size_type k=0 ; k<fh.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<fh.size(1) ; ++i ) {\n      //fh[k][i] = ( 0.5*alpha/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)-ui)) + 0.5*alpha/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)+ui)) )*(1.+0.04*std::cos(0.3*Xi(i)));\n      //fh[k][i] = ( 0.5*alpha/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)-ui)) + 0.5*alpha/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)+ui)) )*(1.+0.04*std::cos(Kx*Xi(i)));\n\n      fh[k][i] = ( tb_M1(Xi(i),Vk(k)) + tb_M2(Xi(i),Vk(k)) )*(1. + 0.01*std::cos(Kx*Xi(i)));\n    }\n    fft::fft(&(fh[k][0]),&(fh[k][Nx-1])+1,&(hfh[k][0]));\n  }\n  fh.write(\"vphl/split/init.dat\");\n\n  std::cout << \"Nx: \" << Nx << \"\\n\";\n  std::cout << \"Nv: \" << Nv << \"\\n\";\n  std::cout << \"v_min: \" << fh.range.v_min << \"\\n\";\n  std::cout << \"v_max: \" << fh.range.v_max << \"\\n\";\n  std::cout << \"x_min: \" << fh.range.x_min << \"\\n\";\n  std::cout << \"x_max: \" << fh.range.x_max << \"\\n\";\n  std::cout << \"dt: \" << dt << \"\\n\";\n  std::cout << \"dx: \" << fh.step.dx << \"\\n\";\n  std::cout << \"dv: \" << fh.step.dv << \"\\n\";\n  std::cout << \"Tf: \" << Tf << \"\\n\";\n  std::cout << \"f_0: \" << \"\\\"tb\\\"\" << \"\\n\";\n  std::cout << std::endl;\n\n  const double rho_c = 1.-alpha;\n  // init E (electric field) with Poisson\n  {\n    poisson<double> poisson_solver(Nx,l);\n    ublas::vector<double> rho(Nx,0.);\n    rho = fh.density(); // compute density from init data\n    for ( auto i=0 ; i<Nx ; ++i ) { rho[i] += rho_c; } // add (1-alpha) for cold particules\n    E = poisson_solver(rho);\n  }\n\n  // monitoring data\n  std::vector<double> ee;\n  std::vector<double> Emax;\n  std::vector<double> times;\n\n  times.push_back(0);\n  {\n    double electric_energy = 0.;\n    for ( const auto & ei : E ) { electric_energy += ei*ei*fh.step.dx; }\n    ee.push_back( std::sqrt(electric_energy) );\n  }\n  Emax.push_back( std::abs(*std::max_element( E.begin() , E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n\n  //U_type<double,1> U({uc,E,hfh};\n  splitting<double,1> Lie( fh , l , rho_c );\n\n  std::size_t i_t = 0;\n  double current_time = 0.;\n  while ( current_time < Tf ) {\n    std::cout << \" [\" << std::setw(5) << i_t << \"] \" << i_t*dt << \"\\r\" << std::flush;\n\n    Lie.phi_a(dt,uc,E,hfh);\n    Lie.phi_b(dt,uc,E,hfh);\n    Lie.phi_c(dt,uc,E,hfh);\n    //Lie.phi_b(0.5*dt,uc,E,hfh);\n    //Lie.phi_a(0.5*dt,uc,E,hfh);\n\n    Emax.push_back( std::abs(*std::max_element( E.begin() , E.end() , [](double a,double b){return (std::abs(a) < std::abs(b));} )) );\n\n    double electric_energy = 0.;\n    for ( const auto & ei : E ) { electric_energy += ei*ei*fh.step.dx; }\n    ee.push_back( std::sqrt(electric_energy) );\n\n    current_time += dt;\n    ++i_t;\n    times.push_back( current_time );\n  } // while current_time < Tf\n  std::cout<<\" [\"<<std::setw(5)<<i_t<<\"] \"<<i_t*dt<<std::endl;\n\n  std::ofstream of;\n  std::size_t count = 0;\n  auto dt_y = [&,count=0](auto const& y) mutable { std::stringstream ss; ss<<times[count++]<<\" \"<<y; return ss.str(); };\n\n  of.open(\"vphl/split/ee.dat\");\n  std::transform( ee.begin() , ee.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dt_y );\n  of.close();\n\n  of.open(\"vphl/split/Emax.dat\");\n  std::transform( Emax.begin() , Emax.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dt_y );\n  of.close();\n\n  for ( auto k=0 ; k<hfh.shape()[0] ; ++k ) { fft::ifft(&(hfh[k][0]),&(hfh[k][Nx-1])+1,&(fh[k][0])); }\n  fh.write(\"vphl/split/vp.dat\");\n\n\n  return 0;\n}\n\n", "meta": {"hexsha": "037f1fdf40c6d0c974f0840ec0373e42f1f64219", "size": 5703, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/main_vphl_split.cc", "max_stars_repo_name": "Kivvix/miMaS", "max_stars_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-03T22:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-29T06:12:07.000Z", "max_issues_repo_path": "code/main_vphl_split.cc", "max_issues_repo_name": "Kivvix/miMaS", "max_issues_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/main_vphl_split.cc", "max_forks_repo_name": "Kivvix/miMaS", "max_forks_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-29T06:17:16.000Z", "avg_line_length": 34.5636363636, "max_line_length": 197, "alphanum_fraction": 0.56864808, "num_tokens": 2077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787538, "lm_q2_score": 0.7057850340255387, "lm_q1q2_score": 0.6355804419679436}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n#include <cgi/logger/logger.hpp>\n#include <cgi/mosaic/Mosaic.hpp>\n#include <cgi/mosaic/MosaicUtility.hpp>\n#include <boost/filesystem/convenience.hpp>\n\nstatic const int nBands = 8;\n\nnamespace Eigen {\n  typedef Eigen::Matrix<float, nBands, nBands> Matrix8f;\n  typedef Eigen::Matrix<float, nBands, 1> Vector8f;\n}\n\nEigen::Vector8f v2v(const std::vector<unsigned short>& sVec)\n{\n  Eigen::Vector8f eVec;\n  for(unsigned int i=0; i<sVec.size(); ++i)\n    eVec(i,0) = sVec[i];\n  return eVec;\n}\n\nstd::vector<unsigned short> v2v(const Eigen::VectorXf& eVec)\n{\n  std::vector<unsigned short> sVec(eVec.rows());\n  for(unsigned int i=0; i<sVec.size(); ++i)\n    sVec[0] = eVec(i,0);\n  return sVec;\n}\n\ncgi::Tile<unsigned char> threshold(const cgi::Tile<float>& inTile, const Eigen::VectorXf& thresh)\n{\n  const cgi::core::Size2d<int>& size(inTile.getSize());\n  const int height = size.getHeight();\n  const int width = size.getWidth();\n  const int depth = inTile.getBandCount();\n\n  cgi::Tile<unsigned char> outTile(size, depth, 0);\n\n  for(int r=0; r<height; ++r)\n    {\n      for(int c=0; c<width; ++c)\n\t{\n\t  for(int b=0; b<depth; ++b)\n\t    {\n\t      if(inTile[b](r,c) > thresh(b,0))\n\t\toutTile[b](r,c) = 255;\n\t    }\n\t}\n    }\n\n  return outTile;\n}\n\n////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////\n\nint main(int argc, char** argv)\n{\n  if(argc != 4)\n    {\n      std::cerr << \"USAGE: \" << argv[0] << \" <input filename> <output filename> <number of output levels>\" << std::endl;\n      return 1;\n    }\n\n  cgi::log::MetaLogStream::instance().setTargets(cgi::log::STDOUT);\n  cgi::log::MetaLogStream::instance().setPriorityThreshold(cgi::log::Priority::DEBUG);\n  cgi::log::MetaLogStream& log (cgi::log::MetaLogStream::instance());\n  ////////////////////////////////////////////////////////\n  ////////////////////////////////////////////////////////\n\n  const std::string outputFile(argv[2]);\n  CGI_THROW_IF(true == boost::filesystem::exists(outputFile), std::runtime_error);\n\n  const int l = boost::lexical_cast<int>(argv[3]);\n\n  ////////////////////////////////////////////////////////\n  ////////////////////////////////////////////////////////\n\n  cgi::Mosaic m;\n  CGI_THROW_IF(cgi::NoError != m.open(argv[1]), std::runtime_error);\n\n  CGI_THROW_IF(nBands != m.getBandCount(), std::runtime_error);\n\n  m.setTileSize(cgi::core::Size2d< int >(1000,1000));\n \n  const cgi::core::Size2d< int > &size = m.getTileSize();\n  const int numRows = size.getHeight();\n  const int numCols = size.getWidth();\n\n  //const int everyNthTile = m.getColumnCount()/2 - 1;\n  const int everyNthTile = 100;\n\n  // initialization\n  Eigen::Vector8f mean = Eigen::Vector8f::Zero();\n  int validPixelCount = 0;\n\n  log << cgi::log::Priority::INFO << \"eigen_dmp\" << \"Calculating mean for...\" << cgi::log::flush;\n\n  // Calculate the mean vector across all tiles\n  for(int i=0; i<m.getTileCount(); ++i)\n    {\n      if(0 != (i % everyNthTile))\n\tcontinue;\n\n      log << cgi::log::Priority::INFO << \"eigen_dmp\" << \"Tile \" << i << \" of \" << m.getTileCount() << cgi::log::flush;\n\n      const cgi::Tile<unsigned short> t(m.getTile<unsigned short>(i));\n      const boost::numeric::ublas::matrix< bool > mask (t.getValidMask(cgi::valid_mask::ALL));\n\n      for(int r=0; r<numRows; ++r)\n\t{\n\t  for(int c=0; c<numCols; ++c)\n\t    {\n\t      if(mask(r,c))\n\t\t{\n\t\t  const Eigen::Vector8f eVec(v2v(t(r,c)));\n\t\t  mean += eVec;\n\t\t  ++validPixelCount;\n\t\t}\n\t    }\n\t}\n      \n    }\n\n  mean /= validPixelCount;\n  std::cout << \"mean = \" << std::endl << mean << std::endl;\n\n  ////////////////////////////////////////////////////////\n\n  //\n  // Calculate the covariance matrix\n  //\n  \n  Eigen::Matrix8f cov = Eigen::Matrix8f::Zero();\n\n  log << cgi::log::Priority::INFO << \"eigen_dmp\" << \"Calculating covariance for...\" << cgi::log::flush;\n\n  for(int i=0; i<m.getTileCount(); ++i)\n    {\n      if(0 != (i % everyNthTile))\n\tcontinue;\n\n      log << cgi::log::Priority::INFO << \"eigen_dmp\" << \"Tile \" << i << \" of \" << m.getTileCount() << cgi::log::flush;\n\n      const cgi::Tile<unsigned short> t(m.getTile<unsigned short>(i));\n      const boost::numeric::ublas::matrix< bool > mask (t.getValidMask(cgi::valid_mask::ALL));\n  \n      for(int r=0; r<numRows; ++r)\n\t{\n\t  for(int c=0; c<numCols; ++c)\n\t    {\n\t      if(mask(r,c))\n\t\t{\n\n\t\t  const Eigen::Vector8f eVec(v2v(t(r,c)));\n\t\t  cov += (eVec - mean) * (eVec - mean).transpose();\n\t\t}\n\t    }\n\t}\n    }\n\n  cov /= validPixelCount;\n  //cov -= mean * mean.transpose();\n  std::cout << \"cov = \" << std::endl << cov << std::endl;\n\n  ////////////////////////////////////////////////////////\n\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix8f> eigensolver(cov);\n  \n  if (eigensolver.info() != Eigen::Success) \n    abort();\n\n\n  std::cout << \"The eigenvalues of A are:\" << std::endl << eigensolver.eigenvalues() << std::endl;\n  std::cout << \"Here's a matrix whose columns are eigenvectors of A \" << std::endl\n\t    << \"corresponding to these eigenvalues:\" << std::endl\n\t    << eigensolver.eigenvectors() << std::endl;\n  \n\n  ////////////////////////////////////////////////////////\n\n  Eigen::Vector8f evals = eigensolver.eigenvalues();\n  evals /= evals(evals.rows()-1, 0);\n  std::cout << \"Cummulative energy content for each eigenvector: \" << std::endl\n\t    << evals << std::endl;\n\n  ////////////////////////////////////////////////////////\n\n  //const Eigen::Vector8f z = eigensolver.eigenvectors().col(nBands-1);\n  Eigen::MatrixXf zz(nBands,l);\n  zz = eigensolver.eigenvectors().block(0,nBands-l, nBands,l);\n\n  ////////////////////////////////////////////////////////\n\n  Eigen::VectorXf meanOfEigenImage = zz.transpose() * mean;\n  std::cout << \"meanOfEigneImage = \" << std::endl\n\t    << meanOfEigenImage << std::endl;\n\n  ////////////////////////////////////////////////////////\n\n  const cgi::Tile<unsigned short> t(m.getTile<unsigned short>(m.getTileIndex1D(m.getRowCount()/2, m.getColumnCount()/2)));\n  cgi::Tile<float> tt(t.getSize(), l);\n  \n  for(int r=0; r<numRows; ++r)\n    {\n      for(int c=0; c<numCols; ++c)\n        {\n\t  const Eigen::Vector8f eVec(v2v(t(r,c)));\n\n\t  //const float pp = z.transpose() * (eVec - mean);\n\t  const Eigen::VectorXf ppv (zz.transpose() * (eVec - mean));\n\n\t  for(int b=0; b < ppv.rows(); ++b)\n\t    tt[b](r,c) = ppv(b,0);\n        }\n    }\n  \n  cgi::MosaicUtility::writeImage<unsigned short>(t, \"dmp.tif\");\n  cgi::MosaicUtility::writeImage<float>(tt, \"out.tif\");\n\n  cgi::MosaicUtility::writeImage<unsigned char>(threshold(tt, 3*meanOfEigenImage), \"thresh.tif\");\n\n  ////////////////////////////////////////////////////////\n\n  return 0;\n\n  /*\n  Eigen::Matrix8f A;\n  \n  //srand(time(NULL));\n\n  const int n = nBands;\n  for(int i=0; i<n; ++i)\n    for(int j=i; j<n; ++j)\n      A(i,j) = A(j,i) = (-1 + (2 * (rand()%2))) * (rand() / static_cast<float>(RAND_MAX));\n\n  cout << \"Here is the matrix A:\\n\" << A << endl;\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix8f> eigensolver(A);\n  if (eigensolver.info() != Eigen::Success) abort();\n  cout << \"The eigenvalues of A are:\\n\" << eigensolver.eigenvalues() << endl;\n  cout << \"Here's a matrix whose columns are eigenvectors of A \\n\"\n       << \"corresponding to these eigenvalues:\\n\"\n       << eigensolver.eigenvectors() << endl;\n\n  */\n}\n", "meta": {"hexsha": "c9fb09fde8e561ab2d20e74daac7555b40aa0cbf", "size": 7355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_dmp/eigen_dmp.cpp", "max_stars_repo_name": "klaricmn/snippets", "max_stars_repo_head_hexsha": "a1ae04c13a2209dee013284358d2d987bb0fb4fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigen_dmp/eigen_dmp.cpp", "max_issues_repo_name": "klaricmn/snippets", "max_issues_repo_head_hexsha": "a1ae04c13a2209dee013284358d2d987bb0fb4fc", "max_issues_repo_licenses": ["MIT"], "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_dmp/eigen_dmp.cpp", "max_forks_repo_name": "klaricmn/snippets", "max_forks_repo_head_hexsha": "a1ae04c13a2209dee013284358d2d987bb0fb4fc", "max_forks_repo_licenses": ["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.3027888446, "max_line_length": 122, "alphanum_fraction": 0.5419442556, "num_tokens": 2084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6355804401632749}}
{"text": "//#define BOOST_MATH_ASSERT_UNDEFINED_POLICY false\n//#define BOOST_MATH_OVERFLOW_ERROR_POLICY errno_on_error\n\n#include <boost/math/distributions/bernoulli.hpp>\n#include <boost/math/distributions/beta.hpp>\n#include <boost/math/distributions/binomial.hpp>\n#include <boost/math/distributions/cauchy.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/distributions/exponential.hpp>\n#include <boost/math/distributions/extreme_value.hpp>\n#include <boost/math/distributions/fisher_f.hpp>\n#include <boost/math/distributions/gamma.hpp>\n#include <boost/math/distributions/geometric.hpp>\n#include <boost/math/distributions/laplace.hpp>\n#include <boost/math/distributions/lognormal.hpp>\n#include <boost/math/distributions/negative_binomial.hpp>\n#include <boost/math/distributions/non_central_chi_squared.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/math/distributions/triangular.hpp>\n#include <boost/math/distributions/uniform.hpp>\n#include <boost/math/distributions/weibull.hpp>\n\n#include <boost/log/trivial.hpp>\n#include <boost/log/attributes/scoped_attribute.hpp>\n\n#include \"GenericDistribution.h\"\n\nnamespace Distribution\n{\nnamespace Detail\n{\n    namespace bm = boost::math;\n\n    struct pdf_visitor : boost::static_visitor<>\n    {\n        pdf_visitor(QVector<double> const& x, QVector<double>& y) :\n            _x(x), _y(y) {}\n\n        // Uniform Distributions\n        void operator()(UniformInt const& d) const {\n            auto m = bm::uniform_distribution<>(d.a(), d.b());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(UniformReal const& d) const {\n            auto m = bm::uniform_distribution<>(d.a(), d.b());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(Binomial const& d) const {\n            auto m = bm::binomial_distribution<>(d.t(), d.p());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(Geometric const& d) const {\n            auto m = bm::geometric_distribution<>(d.p());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(NegativeBinomial const& d) const {\n            auto m = bm::negative_binomial_distribution<>(d.k(), d.p());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        // Poisson Distributions\n        void operator()(Poisson const& d) const {\n            auto m = bm::poisson_distribution<>(d.mean());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(Exponential const& d) const {\n            auto m = bm::exponential_distribution<>(d.lambda());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(Gamma const& d) const {\n            auto m = bm::gamma_distribution<>(d.alpha(), d.beta());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(Weibull const& d) const {\n            auto m = bm::weibull_distribution<>(d.a(), d.b());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(ExtremeValue const& d) const {\n            auto m = bm::extreme_value_distribution<>(d.a(), d.b());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(Beta const& d) const {\n            auto m = bm::beta_distribution<>(d.alpha(), d.beta());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(Laplace const& d) const {\n            auto m = bm::laplace_distribution<>(d.mean(), d.beta());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        // Normal Distributions\n        void operator()(Normal const& d) const {\n            auto m = bm::normal_distribution<>(d.mean(), d.sigma());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(Lognormal const& d) const {\n            auto m = bm::lognormal_distribution<>(d.m(), d.s());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(ChiSquared const& d) const {\n            auto m = bm::chi_squared_distribution<>(d.n());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(NCChiSquared const& d) const {\n            auto m = bm::non_central_chi_squared_distribution<>(d.k(), d.lambda());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(Cauchy const& d) const {\n            auto m = bm::cauchy_distribution<>(d.median(), d.sigma());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(FisherF const& d) const {\n            auto m = bm::fisher_f_distribution<>(d.m(), d.n());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        void operator()(StudentT const& d) const {\n            auto m = bm::students_t_distribution<>(d.n());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        // Sampling Distributions\n        void operator()(Discrete const& d) const {\n            _y = QVector<double>::fromStdVector(d.probabilities());\n        }\n        void operator()(PiecewiseConstant const& d) const {\n            _y = QVector<double>::fromStdVector(d.densities());\n        }\n        void operator()(PiecewiseLinear const& d) const {\n            _y = QVector<double>::fromStdVector(d.densities());\n        }\n        // Miscellaneous Distributions\n        void operator()(Triangle const& d) const {\n            auto m = bm::triangular_distribution<>(d.a(), d.b(), d.c());\n            for(const auto &x : _x) _y.push_back(bm::pdf(m, x));\n        }\n        // Placeholder\n        void operator()(Constant const& d) const {\n            for(const auto &x : _x) _y.push_back(d.a());\n        }\n        \n    private:\n        const QVector<double> &_x;\n        QVector<double> &_y;\n    };\n\n} // namespace Distribution\n} // namespace Detail\n\nvoid GenericDistribution::pdf(QVector<double> const& x, QVector<double> &y) const\n{\n    BOOST_LOG_SCOPED_THREAD_TAG(\"Tag\", \"Distribution\");\n\n    y.reserve(x.size());\n    try {\n        boost::apply_visitor(Distribution::Detail::pdf_visitor(x, y), *this);\n    } catch (const std::exception &e) {\n        BOOST_LOG_TRIVIAL(warning) << e.what();\n        return;\n    }\n}\n", "meta": {"hexsha": "8d4b57b484bb58e3cc9a689b2cae26660ab8fdbd", "size": 6545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GenericDistribution.cpp", "max_stars_repo_name": "jbuonagurio/GenericDistribution", "max_stars_repo_head_hexsha": "18333d754ff2f39e8b229b3b20cced69406b4ebb", "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": "GenericDistribution.cpp", "max_issues_repo_name": "jbuonagurio/GenericDistribution", "max_issues_repo_head_hexsha": "18333d754ff2f39e8b229b3b20cced69406b4ebb", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GenericDistribution.cpp", "max_forks_repo_name": "jbuonagurio/GenericDistribution", "max_forks_repo_head_hexsha": "18333d754ff2f39e8b229b3b20cced69406b4ebb", "max_forks_repo_licenses": ["BSL-1.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.90625, "max_line_length": 83, "alphanum_fraction": 0.5920550038, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529786117893, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6355804401632749}}
{"text": "#ifndef MATH_HPP\n#define MATH_HPP\n\n#include <armadillo>\n\nvoid build_psi_tht_phi_TM(const double &psi, const double &tht, const double &phi, arma::mat &AMAT);\narma::mat skew_sym(arma::vec3 const &vec);\nvoid Matrix2Quaternion(arma::mat33 Matrix_in, arma::vec &Quaternion);\nvoid Quaternion2Matrix(arma::vec4 const &Quaternion_in, arma::mat &Matrix_out);\narma::vec3 euler_angle(const arma::mat33 &TBD_in);\nint sign(const double &variable);\n\n#endif\n", "meta": {"hexsha": "a3a4085ab3bb1c91711c08ce2730b8ca21adc356", "size": 444, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Math.hpp", "max_stars_repo_name": "octoberskyTW/Multibody-Dynamics-Solver", "max_stars_repo_head_hexsha": "67b0ea9f6cfbed9e9cf8f048b7e35b620b9aeb4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-17T03:06:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T03:06:47.000Z", "max_issues_repo_path": "include/Math.hpp", "max_issues_repo_name": "octoberskyTW/Multibody-Dynamics-Solver", "max_issues_repo_head_hexsha": "67b0ea9f6cfbed9e9cf8f048b7e35b620b9aeb4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Math.hpp", "max_forks_repo_name": "octoberskyTW/Multibody-Dynamics-Solver", "max_forks_repo_head_hexsha": "67b0ea9f6cfbed9e9cf8f048b7e35b620b9aeb4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-31T13:05:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-31T13:05:36.000Z", "avg_line_length": 31.7142857143, "max_line_length": 100, "alphanum_fraction": 0.7702702703, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6355441979813187}}
{"text": "#include <cmath>\n#include <vector>\n#include <catch2/catch.hpp>\n#include <Eigen/Dense>\n#include \"factory.h\"\n#include \"normal_dist.h\"\n\nTEST_CASE(\"Test different distribution types\", \"[Distributions]\") {\n\n  SECTION(\"Test CDF/ICDF values for normal distribution\") {\n    double mean = 0.0;\n    double std_dev = 1.0;\n    auto test_distribution =\n        Factory<stochastic::Distribution, double, double>::instance()->create(\n            \"NormalDist\", std::move(mean), std::move(std_dev));\n\n    std::vector<double> locations = {0.0};\n\n    auto probabilities = test_distribution->cumulative_dist_func(locations);\n    auto calced_locations = test_distribution->inv_cumulative_dist_func(probabilities);\n    \n    REQUIRE(probabilities[0] == Approx(0.5).epsilon(0.01));\n    REQUIRE(calced_locations[0] == Approx(0.0).epsilon(0.01));    \n  }\n\n  SECTION(\"Test CDF/ICDF values for lognormal distribution\") {\n    double mean = 0.0;\n    double std_dev = 0.25;\n    auto test_distribution =\n        Factory<stochastic::Distribution, double, double>::instance()->create(\n            \"LognormalDist\", std::move(mean), std::move(std_dev));\n\n    std::vector<double> locations = {1.0};\n\n    auto probabilities = test_distribution->cumulative_dist_func(locations);\n    auto calced_locations = test_distribution->inv_cumulative_dist_func(probabilities);\n    \n    REQUIRE(probabilities[0] == Approx(0.5).epsilon(0.01));\n    REQUIRE(calced_locations[0] == Approx(1.0).epsilon(0.01));\n  }\n\n  SECTION(\"Test CDF/ICDF values for Beta distribution\") {\n    double alpha = 0.5;\n    double beta = 0.5;\n    auto test_distribution =\n        Factory<stochastic::Distribution, double, double>::instance()->create(\n            \"BetaDist\", std::move(alpha), std::move(beta));\n\n    std::vector<double> locations = {0.5};\n\n    auto probabilities = test_distribution->cumulative_dist_func(locations);\n    auto calced_locations = test_distribution->inv_cumulative_dist_func(probabilities);\n    \n    REQUIRE(probabilities[0] == Approx(0.5).epsilon(0.01));\n    REQUIRE(calced_locations[0] == Approx(0.5).epsilon(0.01));    \n  }\n\n  SECTION(\"Test CDF/ICDF values for inverse Gaussian distribution\") {\n    double mean = 1.0;\n    double std_dev = 1.0;\n    auto test_distribution =\n        Factory<stochastic::Distribution, double, double>::instance()->create(\n            \"InverseGaussianDist\", std::move(mean), std::move(std_dev));\n\n    std::vector<double> locations = {0.01, 0.675841, 20};\n\n    auto probabilities = test_distribution->cumulative_dist_func(locations);\n    auto calced_locations = test_distribution->inv_cumulative_dist_func(probabilities);\n\n    REQUIRE(probabilities[0] + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(probabilities[1] == Approx(0.5).epsilon(0.01));\n    REQUIRE(probabilities[2] == Approx(1.0).epsilon(0.01));\n    REQUIRE(calced_locations[0] == Approx(locations[0]).epsilon(0.01));\n    REQUIRE(calced_locations[1] == Approx(locations[1]).epsilon(0.01));\n    REQUIRE(calced_locations[2] == Approx(locations[2]).epsilon(0.01));\n  }\n\n  SECTION(\"Test CDF/ICDF values for Student's t distribution\") {\n    double mean = 1.0;\n    double scale = 0.25;\n    double dof = 1.0;\n    auto test_distribution =\n        Factory<stochastic::Distribution, double, double, double>::instance()\n            ->create(\"StudentstDist\", std::move(mean), std::move(scale),\n                     std::move(dof));\n\n    std::vector<double> locations = {1.0};\n\n    auto probabilities = test_distribution->cumulative_dist_func(locations);\n    auto calced_locations = test_distribution->inv_cumulative_dist_func(probabilities);\n\n    REQUIRE(probabilities[0]== Approx(0.5).epsilon(0.01));\n    REQUIRE(calced_locations[0] == Approx(locations[0]).epsilon(0.01));\n  }\n\n  SECTION(\"Test CDF/ICDF values for uniform distribution\") {\n    double lower = 0.0;\n    double upper = 1.0;\n    auto test_distribution =\n        Factory<stochastic::Distribution, double, double>::instance()->create(\n            \"UniformDist\", std::move(lower), std::move(upper));\n\n    std::vector<double> locations = {0.0, 0.5, 1.0};\n\n    auto probabilities = test_distribution->cumulative_dist_func(locations);\n    auto calced_locations =\n        test_distribution->inv_cumulative_dist_func(probabilities);\n\n    REQUIRE(probabilities[0] + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(calced_locations[0] + 1.0 == Approx(1.0).epsilon(0.01));\n    REQUIRE(probabilities[1] == Approx(0.5).epsilon(0.01));\n    REQUIRE(calced_locations[1] == Approx(0.5).epsilon(0.01));\n    REQUIRE(probabilities[2] == Approx(1.0).epsilon(0.01));\n    REQUIRE(calced_locations[2] == Approx(1.0).epsilon(0.01));\n  }\n}\n", "meta": {"hexsha": "a798e91e7a1514a449078fca802f54b581667964", "size": 4611, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/distribution_tests.cc", "max_stars_repo_name": "fmckenna/smelt", "max_stars_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "test/distribution_tests.cc", "max_issues_repo_name": "fmckenna/smelt", "max_issues_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "test/distribution_tests.cc", "max_forks_repo_name": "fmckenna/smelt", "max_forks_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 39.4102564103, "max_line_length": 87, "alphanum_fraction": 0.6796790284, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6355441977649865}}
{"text": "/** @file\n *\n *  Declaration of the LikelihoodFieldTest class.\n */\n\n#include <grid_map_lf/LikelihoodField.h>\n#include <grid_map_core/GridMapMath.hpp>\n#include <grid_map_core/iterators/GridMapIterator.hpp>\n\n#include <gtest/gtest.h>\n\n#include <boost/math/distributions/normal.hpp>\n\n#include <iostream>\n#include <cmath>\n\nusing namespace grid_map;\nusing namespace std;\n\nnamespace {\ndouble g_sigma = 0.1;\n}\n \nTEST(LikelihoodField, EmptyMap)\n{\n  GridMap map({\"layer\"});\n  map.setGeometry(Length(3.0, 3.0), 1.0, Position());\n  map[\"layer\"].setConstant(0);\n\n  SignedDistanceField sdf;\n  sdf.calculateSignedDistanceField(map, \"layer\");\n  map.add(\"distance_field\", sdf.getData());\n\n  LikelihoodField lf;\n  lf.calculateLikelihoodField(map, \"distance_field\", g_sigma);\n  map.add(\"likelihood_field\", lf.getData());\n\n  for (grid_map::GridMapIterator iterator(map); !iterator.isPastEnd(); ++iterator)\n  {\n    EXPECT_EQ(map.at(\"likelihood_field\", (*iterator)), 0);\n  }\n}\n\nTEST(LikelihoodField, FullyOccupiedMap)\n{\n  GridMap map({\"layer\"});\n  map.setGeometry(Length(3.0, 3.0), 1.0, Position());\n  map[\"layer\"].setConstant(1);\n\n  SignedDistanceField sdf;\n  sdf.calculateSignedDistanceField(map, \"layer\");\n  map.add(\"distance_field\", sdf.getData());\n\n  LikelihoodField lf;\n  lf.calculateLikelihoodField(map, \"distance_field\", g_sigma);\n  map.add(\"likelihood_field\", lf.getData());\n\n  for (grid_map::GridMapIterator iterator(map); !iterator.isPastEnd(); ++iterator)\n  {\n    EXPECT_EQ(map.at(\"likelihood_field\", (*iterator)), 1);\n  }\n}\n\nTEST(LikelihoodField, MiddlePoint)\n{\n  GridMap map({\"layer\"});\n  map.setGeometry(Length(3.0, 3.0), 1.0, Position());\n  map[\"layer\"].setConstant(0);\n  map[\"layer\"](1, 1) = 1; // set middle point to obstacle\n\n  SignedDistanceField sdf;\n  sdf.calculateSignedDistanceField(map, \"layer\");\n  map.add(\"distance_field\", sdf.getData());\n\n  LikelihoodField lf;\n  lf.calculateLikelihoodField(map, \"distance_field\", g_sigma);\n  map.add(\"likelihood_field\", lf.getData());\n\n  boost::math::normal_distribution<double> normalDistribution(0, g_sigma);\n  double normalization = pdf(normalDistribution, 0);\n\n  EXPECT_NEAR(map[\"layer\"](0, 0), pdf(normalDistribution, sqrt(2))/ normalization, 1e-5);\n  EXPECT_NEAR(map[\"layer\"](0, 1), pdf(normalDistribution, 1)/ normalization, 1e-5);\n  EXPECT_NEAR(map[\"layer\"](0, 2), pdf(normalDistribution, sqrt(2))/ normalization, 1e-5);\n  EXPECT_NEAR(map[\"layer\"](1, 0), pdf(normalDistribution, 1)/ normalization, 1e-5);\n  EXPECT_NEAR(map[\"layer\"](1, 1), pdf(normalDistribution, 0)/ normalization, 1e-5);\n  EXPECT_NEAR(map[\"layer\"](1, 2), pdf(normalDistribution, 1)/ normalization, 1e-5);\n  EXPECT_NEAR(map[\"layer\"](2, 0), pdf(normalDistribution, sqrt(2))/ normalization, 1e-5);\n  EXPECT_NEAR(map[\"layer\"](2, 1), pdf(normalDistribution, 1)/ normalization, 1e-5);\n  EXPECT_NEAR(map[\"layer\"](2, 2), pdf(normalDistribution, sqrt(2))/ normalization, 1e-5);\n}\n\nTEST(LikelihoodField, getLikelihoodAt)\n{\n  GridMap map({\"layer\"});\n  map.setGeometry(Length(3.0, 3.0), 1.0, Position());\n  map[\"layer\"].setConstant(0);\n  map[\"layer\"](1, 1) = 1; // set middle point to obstacle\n\n  SignedDistanceField sdf;\n  sdf.calculateSignedDistanceField(map, \"layer\");\n  map.add(\"distance_field\", sdf.getData());\n\n  LikelihoodField lf;\n  lf.calculateLikelihoodField(map, \"distance_field\", g_sigma);\n  map.add(\"likelihood_field\", lf.getData());\n\n  boost::math::normal_distribution<double> normalDistribution(0, g_sigma);\n  double normalization = pdf(normalDistribution, 0);\n\n  EXPECT_NEAR(lf.getLikelihoodAt(grid_map::Position(0, 0)),\n          pdf(normalDistribution, sdf.getDistanceAt(grid_map::Position(0, 0))) / normalization, 1e5);\n  EXPECT_NEAR(lf.getLikelihoodAt(grid_map::Position(0, 1)),\n          pdf(normalDistribution, sdf.getDistanceAt(grid_map::Position(0, 1))) / normalization, 1e5);\n  EXPECT_NEAR(lf.getLikelihoodAt(grid_map::Position(0, 2)),\n          pdf(normalDistribution, sdf.getDistanceAt(grid_map::Position(0, 2))) / normalization, 1e5);\n  EXPECT_NEAR(lf.getLikelihoodAt(grid_map::Position(1, 0)),\n          pdf(normalDistribution, sdf.getDistanceAt(grid_map::Position(1, 0))) / normalization, 1e5);\n  EXPECT_NEAR(lf.getLikelihoodAt(grid_map::Position(1, 1)),\n          pdf(normalDistribution, sdf.getDistanceAt(grid_map::Position(1, 1))) / normalization, 1e5);\n  EXPECT_NEAR(lf.getLikelihoodAt(grid_map::Position(1, 2)),\n          pdf(normalDistribution, sdf.getDistanceAt(grid_map::Position(1, 2))) / normalization, 1e5);\n  EXPECT_NEAR(lf.getLikelihoodAt(grid_map::Position(2, 0)),\n          pdf(normalDistribution, sdf.getDistanceAt(grid_map::Position(2, 0))) / normalization, 1e5);\n  EXPECT_NEAR(lf.getLikelihoodAt(grid_map::Position(2, 1)),\n          pdf(normalDistribution, sdf.getDistanceAt(grid_map::Position(2, 1))) / normalization, 1e5);\n  EXPECT_NEAR(lf.getLikelihoodAt(grid_map::Position(2, 2)),\n          pdf(normalDistribution, sdf.getDistanceAt(grid_map::Position(2, 2))) / normalization, 1e5);\n}\n\nTEST(LikelihoodField, unknown_region)\n{\n  GridMap map({\"layer\"});\n  map.setGeometry(Length(1.0, 1.0), 1.0, Position());\n  map[\"layer\"].setConstant(NAN);\n\n  grid_map::LikelihoodField lf;\n  lf.calculateLikelihoodField(map, \"layer\", 1.0);\n\n  EXPECT_EQ(lf.getData()(0, 0), 0.5);\n}\n", "meta": {"hexsha": "94d274896d179ab8ad9910ddc6d424eab9cfe21b", "size": 5219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grid_map_lf/test/LikelihoodFieldTest.cpp", "max_stars_repo_name": "BeatScherrer/grid_map", "max_stars_repo_head_hexsha": "9a6ba1ef494cd3c5bbd9c0f050653bc50f758ecf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grid_map_lf/test/LikelihoodFieldTest.cpp", "max_issues_repo_name": "BeatScherrer/grid_map", "max_issues_repo_head_hexsha": "9a6ba1ef494cd3c5bbd9c0f050653bc50f758ecf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_lf/test/LikelihoodFieldTest.cpp", "max_forks_repo_name": "BeatScherrer/grid_map", "max_forks_repo_head_hexsha": "9a6ba1ef494cd3c5bbd9c0f050653bc50f758ecf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7535211268, "max_line_length": 101, "alphanum_fraction": 0.7135466564, "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595163, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6355441831007751}}
{"text": "/*\nAuthor: Rohan Chetan Thanki\nDate created: 16-Oct-2021\n*/\n\n// This file contains functions which are used in the main file. This ensures that the main file is not cluttered\n\n#include \"Hedging_Portfolio.hpp\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n\n#include <boost/random.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/date_time.hpp>\n\nusing namespace std;\n\nvoid testDelta ()\n{\n\tconst double K = 250;\n\tconst double S = 248;\n\tconst double r = 0.03;\n\tconst double T = 1;\n\tconst double sigma = 0.3;\n\tconst double trueDelta = 0.5882;\n\tHedging_Portfolio hpobj1(K, S, r, T, sigma, 'c');\n\tdouble computedDelta = hpobj1.computeDelta();\n\tif (abs(trueDelta - computedDelta) <= 0.01)\n\t\tcout << \"Delta test case passed\" << endl;\n\telse\n\t\tcout << \"Delta test case failed\" << endl;\n}\n\nvoid testImpliedVol()\n{\n\tconst double K = 250;\n\tconst double S = 248;\n\tconst double r = 0.03;\n\tconst double T = 1;\n\tconst double sigma = 0;\n\n\tconst double marketPrice = 46.41;\n\tdouble maxVol = 100;\n\tconst double trueImpliedVol = 0.45;\n\n\tHedging_Portfolio hpobj1(K, S, r, T, sigma, 'c');\n\thpobj1.setOptionPrice(marketPrice);\n\tdouble computedImpliedVol = hpobj1.computeImpliedVol(maxVol);\n\n\tif (abs(trueImpliedVol - computedImpliedVol) <= 0.01)\n\t\tcout << \"Implied volatility test case passed\" << endl;\n\telse\n\t\tcout << \"Implied volatility test case failed\" << endl;\n}\n\nvoid runAllTests()\n{\n\ttestDelta();\n\ttestImpliedVol();\n}", "meta": {"hexsha": "15a2d0cbf87d2d9353ccbe1ce70962fcd301aa81", "size": 1422, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/test.hpp", "max_stars_repo_name": "rohanthanki/delta_hedging", "max_stars_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "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": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/test.hpp", "max_issues_repo_name": "rohanthanki/delta_hedging", "max_issues_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/test.hpp", "max_forks_repo_name": "rohanthanki/delta_hedging", "max_forks_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "max_forks_repo_licenses": ["Apache-2.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.3114754098, "max_line_length": 113, "alphanum_fraction": 0.7081575246, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888481, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6355111057292259}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2021 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n\n/*! \\file InvertMatrix.hpp\n\nThe following code inverts the matrix input using LU-decomposition with backsubstitution of unit vectors. Reference: Numerical Recipies in C, 2nd ed., by Press, Teukolsky, Vetterling & Flannery.\n\nyou can solve Ax=b using three lines of ublas code:\n\npermutation_matrix<> piv;\nlu_factorize(A, piv);\nlu_substitute(A, piv, x);\n\n*/\n#ifndef INVERT_MATRIX_HPP\n#define INVERT_MATRIX_HPP\n\n// REMEMBER to update \"lu.hpp\" header includes from boost-CVS\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n/** Matrix inversion routine.\n\n    Uses lu_factorize and lu_substitute in uBLAS to invert a matrix \n    \n    \\param input source matrix\n    \\param output inverted matrix.  \n\n*/\ntemplate<class T, class U, class V>\nbool InvertMatrix(const boost::numeric::ublas::matrix<T, U, V>& input,\n                  boost::numeric::ublas::matrix<T, U, V>& inverse)\n{\n  typedef boost::numeric::ublas::permutation_matrix<std::size_t> pmatrix;\n  // create a working copy of the input\n  boost::numeric::ublas::matrix<T, U, V> A(input);\n  // create a permutation matrix for the LU-factorization\n  pmatrix pm(A.size1());\n  \n  // perform LU-factorization\n  int res = lu_factorize(A,pm);\n  if(res != 0) return false;\n  \n  // create identity matrix of \"inverse\"\n  inverse.assign(boost::numeric::ublas::identity_matrix<T>(A.size1()));\n  \n// backsubstitute to get the inverse\n  lu_substitute(A, pm, inverse);\n\n  return true;\n}\n#endif //INVERT_MATRIX_HPP\n\n\n", "meta": {"hexsha": "3a2678e4508ac10828b05743364d5f398c4a2b68", "size": 2349, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/InvertMatrix.hpp", "max_stars_repo_name": "BuildJet/siconos", "max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/InvertMatrix.hpp", "max_issues_repo_name": "BuildJet/siconos", "max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/InvertMatrix.hpp", "max_forks_repo_name": "BuildJet/siconos", "max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 31.32, "max_line_length": 194, "alphanum_fraction": 0.7318007663, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.635511085335284}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/core.hpp>\n#include <eve/module/core.hpp>\n#include <eve/module/math.hpp>\n#include <eve/module/elliptic.hpp>\n#include <boost/math/special_functions/ellint_1.hpp>\n\n//==================================================================================================\n// Types tests\n//==================================================================================================\nEVE_TEST_TYPES( \"Check return types of ellint_1\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n\n  TTS_EXPR_IS( eve::ellint_1(T())  , T);\n  TTS_EXPR_IS( eve::ellint_1(v_t()), v_t);\n  TTS_EXPR_IS( eve::ellint_1(T(), T())  , T);\n  TTS_EXPR_IS( eve::ellint_1(v_t(), v_t()), v_t);\n  TTS_EXPR_IS( eve::ellint_1(T(), v_t()), T);\n  TTS_EXPR_IS( eve::ellint_1(v_t(), T()), T);\n};\n\n//==================================================================================================\n// ellint_1  tests\n//==================================================================================================\nEVE_TEST( \"Check behavior of ellint_1 on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate( eve::test::randoms(0, 1.0)\n                             , eve::test::randoms(0, eve::pio_2))\n        )\n<typename T>(T const& k, T const& phi)\n{\n  using eve::detail::map;\n  using v_t = eve::element_type_t<T>;\n\n  TTS_ULP_EQUAL(eve::ellint_1(k)      , map([](auto e) -> v_t { return boost::math::ellint_1(e); }, k), 16);\n  TTS_ULP_EQUAL(eve::ellint_1(phi, k) , map([](auto e, auto f) -> v_t { return boost::math::ellint_1(e, f); }, k, phi), 16);\n};\n", "meta": {"hexsha": "cd331f3c19177719409d9ad2b7c2090603318354", "size": 1968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/elliptic/ellint_1.cpp", "max_stars_repo_name": "clayne/eve", "max_stars_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/elliptic/ellint_1.cpp", "max_issues_repo_name": "clayne/eve", "max_issues_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/elliptic/ellint_1.cpp", "max_forks_repo_name": "clayne/eve", "max_forks_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1632653061, "max_line_length": 124, "alphanum_fraction": 0.4288617886, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6355068034312613}}
{"text": "#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nvoid setupInitialConditions(Array<float,3>& P1, Array<float,3>& P2,\n    Array<float,3>& P3, Array<float,3>& c, int N);\n\nfloat acoustic3D_BlitzInterlacedCycled(int N, int niters)\n{\n    // Allocate the arrays as a group.  Blitz++ will interlace them in\n    // memory, improving data locality.\n\n    Array<float,3> P1, P2, P3, c;\n    allocateArrays(shape(N,N,N), P1, P2, P3, c);\n    Range I(1,N-2), J(1,N-2), K(1,N-2);\n\n    setupInitialConditions(P1, P2, P3, c, N);\n\n    for (int iter=0; iter < niters; ++iter)\n    {\n        P3(I,J,K) = (2-6*c(I,J,K)) * P2(I,J,K)\n          + c(I,J,K)*(P2(I-1,J,K) + P2(I+1,J,K) + P2(I,J-1,K) + P2(I,J+1,K)\n          + P2(I,J,K-1) + P2(I,J,K+1)) - P1(I,J,K);\n\n        cycleArrays(P1, P2, P3);\n    }\n\n    return P1(N/2,N/2,N/2);\n}\n\n", "meta": {"hexsha": "40c4cb278e9ce77a07ebc769a06d4662ae7e378f", "size": 813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/acou3db2.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/acou3db2.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/acou3db2.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": 26.2258064516, "max_line_length": 75, "alphanum_fraction": 0.5645756458, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148981, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6355067960900458}}
{"text": "//\n// Copyright (c) 2016-2019 CNRS, INRIA\n//\n\n#ifndef __pinocchio_math_quaternion_hpp__\n#define __pinocchio_math_quaternion_hpp__\n\n#include \"pinocchio/math/fwd.hpp\"\n#include \"pinocchio/math/comparison-operators.hpp\"\n#include \"pinocchio/math/sincos.hpp\"\n#include \"pinocchio/utils/static-if.hpp\"\n#include <boost/type_traits.hpp>\n\n#include <Eigen/Geometry>\n\nnamespace pinocchio\n{\n  namespace quaternion\n  {\n    ///\n    /// \\brief Compute the minimal angle between q1 and q2.\n    ///\n    /// \\param[in] q1 input quaternion.\n    /// \\param[in] q2 input quaternion.\n    ///\n    /// \\return angle between the two quaternions\n    ///\n    template<typename D1, typename D2>\n    typename D1::Scalar\n    angleBetweenQuaternions(const Eigen::QuaternionBase<D1> & q1,\n                            const Eigen::QuaternionBase<D2> & q2)\n    {\n      typedef typename D1::Scalar Scalar;\n      const Scalar innerprod = q1.dot(q2);\n      Scalar theta = math::acos(innerprod);\n      static const Scalar PI_value = PI<Scalar>();\n\n      theta = internal::if_then_else(internal::LT, innerprod, Scalar(0),\n                                     PI_value - theta,\n                                     theta);\n      return theta;\n    }\n    \n    ///\n    /// \\brief Check if two quaternions define the same rotations.\n    /// \\note Two quaternions define the same rotation iff q1 == q2 OR q1 == -q2.\n    ///\n    /// \\param[in] q1 input quaternion.\n    /// \\param[in] q2 input quaternion.\n    ///\n    /// \\return Return true if the two input quaternions define the same rotation.\n    ///\n    template<typename D1, typename D2>\n    bool defineSameRotation(const Eigen::QuaternionBase<D1> & q1,\n                            const Eigen::QuaternionBase<D2> & q2,\n                            const typename D1::RealScalar & prec = Eigen::NumTraits<typename D1::Scalar>::dummy_precision())\n    {\n      return (q1.coeffs().isApprox(q2.coeffs(), prec) || q1.coeffs().isApprox(-q2.coeffs(), prec) );\n    }\n    \n    /// Approximately normalize by applying the first order limited development\n    /// of the normalization function.\n    ///\n    /// Only additions and multiplications are required. Neither square root nor\n    /// division are used (except a division by 2). Let \\f$ \\delta = ||q||^2 - 1 \\f$.\n    /// Using the following limited development:\n    /// \\f[ \\frac{1}{||q||} = (1 + \\delta)^{-\\frac{1}{2}} = 1 - \\frac{\\delta}{2} + \\mathcal{O}(\\delta^2) \\f]\n    ///\n    /// The output is\n    /// \\f[ q_{out} = q \\times \\frac{3 - ||q_{in}||^2}{2} \\f]\n    ///\n    /// The output quaternion is guaranted to statisfy the following:\n    /// \\f[ | ||q_{out}|| - 1 | \\le \\frac{M}{2} ||q_{in}|| ( ||q_{in}||^2 - 1 )^2 \\f]\n    /// where \\f$ M = \\frac{3}{4} (1 - \\epsilon)^{-\\frac{5}{2}} \\f$\n    /// and \\f$ \\epsilon \\f$ is the maximum tolerance of \\f$ ||q_{in}||^2 - 1 \\f$.\n    ///\n    /// \\warning \\f$ ||q||^2 - 1 \\f$ should already be close to zero.\n    ///\n    /// \\note See\n    /// http://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html#title3\n    /// to know the reason why the argument is const.\n    template<typename D>\n    void firstOrderNormalize(const Eigen::QuaternionBase<D> & q)\n    {\n      typedef typename D::Scalar Scalar;\n      const Scalar N2 = q.squaredNorm();\n#ifndef NDEBUG\n      const Scalar epsilon = sqrt(sqrt(Eigen::NumTraits<Scalar>::epsilon()));\n      typedef apply_op_if<less_than_or_equal_to_op,boost::is_floating_point<Scalar>::value,true> static_leq;\n      assert(static_leq::op(math::fabs(N2-1.), epsilon));\n#endif\n      const Scalar alpha = ((Scalar)3 - N2) / Scalar(2);\n      PINOCCHIO_EIGEN_CONST_CAST(D,q).coeffs() *= alpha;\n#ifndef NDEBUG\n      const Scalar M = Scalar(3) * math::pow(Scalar(1)-epsilon, ((Scalar)-Scalar(5))/Scalar(2)) / Scalar(4);\n      assert(static_leq::op(math::fabs(q.norm() - Scalar(1)),\n                            math::max(M * sqrt(N2) * (N2 - Scalar(1))*(N2 - Scalar(1)) / Scalar(2), Eigen::NumTraits<Scalar>::dummy_precision())));\n#endif\n    }\n    \n    /// Uniformly random quaternion sphere.\n    template<typename Derived>\n    void uniformRandom(const Eigen::QuaternionBase<Derived> & q)\n    {\n      typedef typename Derived::Scalar Scalar;\n\n      // Rotational part\n      const Scalar u1 = (Scalar)rand() / RAND_MAX;\n      const Scalar u2 = (Scalar)rand() / RAND_MAX;\n      const Scalar u3 = (Scalar)rand() / RAND_MAX;\n      \n      const Scalar mult1 = sqrt(Scalar(1)-u1);\n      const Scalar mult2 = sqrt(u1);\n      \n      static const Scalar PI_value = PI<Scalar>();\n      Scalar s2,c2; SINCOS(Scalar(2)*PI_value*u2,&s2,&c2);\n      Scalar s3,c3; SINCOS(Scalar(2)*PI_value*u3,&s3,&c3);\n      \n      PINOCCHIO_EIGEN_CONST_CAST(Derived,q).w() = mult1 * s2;\n      PINOCCHIO_EIGEN_CONST_CAST(Derived,q).x() = mult1 * c2;\n      PINOCCHIO_EIGEN_CONST_CAST(Derived,q).y() = mult2 * s3;\n      PINOCCHIO_EIGEN_CONST_CAST(Derived,q).z() = mult2 * c3;\n    }\n    \n    namespace internal\n    {\n\n      template<typename Scalar, bool value = boost::is_floating_point<Scalar>::value>\n      struct quaternionbase_assign_impl;\n      \n      template<Eigen::DenseIndex i>\n      struct quaternionbase_assign_impl_if_t_negative\n      {\n        template<typename Scalar, typename Matrix3, typename QuaternionDerived>\n        static inline void run(Scalar t,\n                               Eigen::QuaternionBase<QuaternionDerived> & q,\n                               const Matrix3 & mat)\n        {\n          using pinocchio::math::sqrt;\n          \n          Eigen::DenseIndex j = (i+1)%3;\n          Eigen::DenseIndex k = (j+1)%3;\n          \n          t = sqrt(mat.coeff(i,i)-mat.coeff(j,j)-mat.coeff(k,k) + Scalar(1.0));\n          q.coeffs().coeffRef(i) = Scalar(0.5) * t;\n          t = Scalar(0.5)/t;\n          q.w() = (mat.coeff(k,j)-mat.coeff(j,k))*t;\n          q.coeffs().coeffRef(j) = (mat.coeff(j,i)+mat.coeff(i,j))*t;\n          q.coeffs().coeffRef(k) = (mat.coeff(k,i)+mat.coeff(i,k))*t;\n        }\n      };\n      \n      struct quaternionbase_assign_impl_if_t_positive\n      {\n        template<typename Scalar, typename Matrix3, typename QuaternionDerived>\n        static inline void run(Scalar t, \n                               Eigen::QuaternionBase<QuaternionDerived> & q,\n                               const Matrix3 & mat)\n        {\n          using pinocchio::math::sqrt;\n          \n          t = sqrt(t + Scalar(1.0));\n          q.w() = Scalar(0.5)*t;\n          t = Scalar(0.5)/t;\n          q.x() = (mat.coeff(2,1) - mat.coeff(1,2)) * t;\n          q.y() = (mat.coeff(0,2) - mat.coeff(2,0)) * t;\n          q.z() = (mat.coeff(1,0) - mat.coeff(0,1)) * t;\n        }\n      };\n      \n      template<typename Scalar>\n      struct quaternionbase_assign_impl<Scalar, true>\n      {\n        template<typename Matrix3, typename QuaternionDerived>\n        static inline void run(Eigen::QuaternionBase<QuaternionDerived> & q,\n                               const Matrix3 & mat)\n        {\n          using pinocchio::math::sqrt;\n          \n          Scalar t = mat.trace();\n          if (t > Scalar(0.))\n            quaternionbase_assign_impl_if_t_positive::run(t,q,mat);\n          else\n          {\n            Eigen::DenseIndex i = 0;\n            if (mat.coeff(1,1) > mat.coeff(0,0))\n              i = 1;\n            if (mat.coeff(2,2) > mat.coeff(i,i))\n              i = 2;\n              \n            if(i==0)\n              quaternionbase_assign_impl_if_t_negative<0>::run(t,q,mat);\n            else if(i==1)\n              quaternionbase_assign_impl_if_t_negative<1>::run(t,q,mat);\n            else\n              quaternionbase_assign_impl_if_t_negative<2>::run(t,q,mat);\n          }\n        }\n      };\n      \n    } // namespace internal\n    \n    template<typename D, typename Matrix3>\n    void assignQuaternion(Eigen::QuaternionBase<D> & quat,\n                          const Eigen::MatrixBase<Matrix3> & R)\n    {\n      internal::quaternionbase_assign_impl<typename Matrix3::Scalar>::run(PINOCCHIO_EIGEN_CONST_CAST(D,quat),\n                                                                          R.derived());\n    }\n      \n  } // namespace quaternion\n\n}\n#endif //#ifndef __pinocchio_math_quaternion_hpp__\n", "meta": {"hexsha": "0fcb162d2522512c28ea824cf61a9452f2d82d33", "size": 8114, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/quaternion.hpp", "max_stars_repo_name": "ikalevatykh/pinocchio", "max_stars_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/quaternion.hpp", "max_issues_repo_name": "ikalevatykh/pinocchio", "max_issues_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/quaternion.hpp", "max_forks_repo_name": "ikalevatykh/pinocchio", "max_forks_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7395348837, "max_line_length": 147, "alphanum_fraction": 0.5706186838, "num_tokens": 2156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6355067927979435}}
{"text": "//#include <boost/test/unit_test.hpp>\n//#include <iostream>\n//\n//#include \"ssmkit/filter/kalman.hpp\"\n//\n//using namespace PROJECT_NAME;\n//\n//BOOST_AUTO_TEST_SUITE(kalman_filter_test);\n//\n//BOOST_AUTO_TEST_CASE(one_step_test)\n//{\n//    constexpr double diff_tol = 0.0001;\n//\n//    arma::mat F {{1, 0}, {0, 1}};\n//    arma::mat H (\"1 0\");\n//    arma::mat B (\"1; 1\");\n//\n//    mlpack::distribution::GaussianDistribution w(arma::zeros<arma::vec>(2), arma::eye<arma::mat>(2,2));\n//    mlpack::distribution::GaussianDistribution v(arma::zeros<arma::vec>(1), arma::eye<arma::mat>(1,1));\n//\n//    mlpack::distribution::GaussianDistribution x0(arma::zeros<arma::vec>(2), arma::eye<arma::mat>(2,2));\n//\n//    filter::Kalman kf(F,H,B,w,v); \n//\n//    // whithout control input\n//    kf.initialize(x0);\n//    BOOST_REQUIRE(arma::approx_equal(arma::vec({0,0}),kf.state().Mean(), \"absdiff\", diff_tol));\n//    BOOST_REQUIRE(arma::approx_equal(arma::mat({{1,0},{0,1}}),kf.state().Covariance(), \"absdiff\", diff_tol));\n//    \n//    kf.predict(); \n//    BOOST_REQUIRE(arma::approx_equal(arma::vec({0,0}),kf.predicted().Mean(), \"absdiff\", diff_tol));\n//    BOOST_REQUIRE(arma::approx_equal(arma::mat({{2,0},{0,2}}),kf.predicted().Covariance(), \"absdiff\", diff_tol));\n//\n//    kf.filter(arma::vec({1}));\n//    BOOST_REQUIRE(arma::approx_equal(arma::vec({0.6667,0}),kf.state().Mean(), \"absdiff\", diff_tol));\n//    BOOST_REQUIRE(arma::approx_equal(arma::mat({{0.6667,0},{0,2}}),kf.state().Covariance(), \"absdiff\", diff_tol));\n//\n//    // with control input\n//    kf.initialize(x0);\n//    BOOST_REQUIRE(arma::approx_equal(arma::vec({0,0}),kf.state().Mean(), \"absdiff\", diff_tol));\n//    BOOST_REQUIRE(arma::approx_equal(arma::mat({{1,0},{0,1}}),kf.state().Covariance(), \"absdiff\", diff_tol));\n//    \n//    kf.predict(arma::vec({2})); \n//    BOOST_REQUIRE(arma::approx_equal(arma::vec({2,2}),kf.predicted().Mean(), \"absdiff\", diff_tol));\n//    BOOST_REQUIRE(arma::approx_equal(arma::mat({{2,0},{0,2}}),kf.predicted().Covariance(), \"absdiff\", diff_tol));\n//\n//    kf.filter(arma::vec({3}));\n//    BOOST_REQUIRE(arma::approx_equal(arma::vec({2.6667,2}),kf.state().Mean(), \"absdiff\", diff_tol));\n//    BOOST_REQUIRE(arma::approx_equal(arma::mat({{0.6667,0},{0,2}}),kf.state().Covariance(), \"absdiff\", diff_tol));\n//}\n//\n//BOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "a0340ca7c1c6cb1d5c2113749aaa0f8fef0197f8", "size": 2322, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/filter/kalman.cpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "test/filter/kalman.cpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/filter/kalman.cpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 43.8113207547, "max_line_length": 116, "alphanum_fraction": 0.6287683032, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6355005310630951}}
{"text": "#include<Eigen/Dense>\n#include<Eigen/Geometry>\n#include<cstring>\n#include <boost/iterator/iterator_concepts.hpp>\nusing namespace std;\nnamespace map3d{\n  \ntemplate <typename PoseT>\nstruct edge{\n\n  string Header;\n  int a_ID;\n  int b_ID;\n  PoseT pose_ab;\n  Eigen::Matrix<float,6,6> informationMatrix_ab;  \n};\n\nstruct pose\n{\n    Eigen::Vector3f t;\n    Eigen::Quaternion<float> q;   \n};\ntemplate <typename PoseT>\nstruct vertix{\n  string Header;\n  int pose_ID;\n  PoseT initialPose;\n};\n}\n", "meta": {"hexsha": "ffd1a7aa7c87853e92688b91702e74edf9e76965", "size": 481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "types.hpp", "max_stars_repo_name": "zoumaguanxin/slamEvaluation", "max_stars_repo_head_hexsha": "2ef824291db7c826cb193d31086057cd4d8b07d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-06T09:08:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-06T09:08:05.000Z", "max_issues_repo_path": "types.hpp", "max_issues_repo_name": "zoumaguanxin/slamEvaluation", "max_issues_repo_head_hexsha": "2ef824291db7c826cb193d31086057cd4d8b07d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "types.hpp", "max_forks_repo_name": "zoumaguanxin/slamEvaluation", "max_forks_repo_head_hexsha": "2ef824291db7c826cb193d31086057cd4d8b07d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0333333333, "max_line_length": 50, "alphanum_fraction": 0.7172557173, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6354858989720809}}
{"text": "// Copyright Maarten L. Hekkelman, Radboud University 2008-2011.\n//   Distributed under the Boost Software License, Version 1.0.\n//       (See accompanying file LICENSE_1_0.txt or copy at    \n//             http://www.boost.org/LICENSE_1_0.txt)      \n// \n// 3d routines\n\n#include \"mas.h\"\n\n#include <valarray>\n#include <cmath>\n\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH\n\n#include \"primitives-3d.h\"\n#include \"matrix.h\"\n\nusing namespace std;\n\nconst double\n\tkPI = 4 * std::atan(1.0);\n\n// --------------------------------------------------------------------\n\nMQuaternion Normalize(MQuaternion q)\n{\n\tvalarray<double> t(4);\n\t\n\tt[0] = q.R_component_1();\n\tt[1] = q.R_component_2();\n\tt[2] = q.R_component_3();\n\tt[3] = q.R_component_4();\n\t\n\tt *= t;\n\t\n\tdouble length = sqrt(t.sum());\n\n\tif (length > 0.001)\n\t\tq /= length;\n\telse\n\t\tq = MQuaternion(1, 0, 0, 0);\n\n\treturn q;\n}\n\n// --------------------------------------------------------------------\n\ndouble MPoint::Normalize()\n{\n\tdouble length = mX * mX + mY * mY + mZ * mZ;\n\tif (length > 0)\n\t{\n\t\tlength = sqrt(length);\n\t\tmX /= length;\n\t\tmY /= length;\n\t\tmZ /= length;\n\t}\n\treturn length;\n}\n\nMPoint operator+(const MPoint& lhs, const MPoint& rhs)\n{\n\treturn MPoint(lhs.mX + rhs.mX, lhs.mY + rhs.mY, lhs.mZ + rhs.mZ);\n}\n\nMPoint operator-(const MPoint& lhs, const MPoint& rhs)\n{\n\treturn MPoint(lhs.mX - rhs.mX, lhs.mY - rhs.mY, lhs.mZ - rhs.mZ);\n}\n\nMPoint operator-(const MPoint& pt)\n{\n\treturn MPoint(-pt.mX, -pt.mY, -pt.mZ);\n}\n\nMPoint operator*(const MPoint& pt, double f)\n{\n\tMPoint result(pt);\n\tresult *= f;\n\treturn result;\n}\n\nMPoint operator/(const MPoint& pt, double f)\n{\n\tMPoint result(pt);\n\tresult /= f;\n\treturn result;\n}\n\nostream& operator<<(ostream& os, const MPoint& pt)\n{\n\tos << '(' << pt.mX << ',' << pt.mY << ',' << pt.mZ << ')';\n\treturn os;\n}\n\nostream& operator<<(ostream& os, const vector<MPoint>& pts)\n{\n\tuint32 n = pts.size();\n\tos << '[' << n << ']';\n\t\n\tforeach (const MPoint& pt, pts)\n\t{\n\t\tos << pt;\n\t\tif (n-- > 1)\n\t\t\tos << ',';\n\t}\n\t\n\treturn os;\n}\n\n// --------------------------------------------------------------------\n\ndouble DihedralAngle(const MPoint& p1, const MPoint& p2, const MPoint& p3, const MPoint& p4)\n{\n\tMPoint v12 = p1 - p2;\t// vector from p2 to p1\n\tMPoint v43 = p4 - p3;\t// vector from p3 to p4\n\t\n\tMPoint z = p2 - p3;\t\t// vector from p3 to p2\n\t\n\tMPoint p = CrossProduct(z, v12);\n\tMPoint x = CrossProduct(z, v43);\n\tMPoint y = CrossProduct(z, x);\n\t\n\tdouble u = DotProduct(x, x);\n\tdouble v = DotProduct(y, y);\n\t\n\tdouble result = 360;\n\tif (u > 0 and v > 0)\n\t{\n\t\tu = DotProduct(p, x) / sqrt(u);\n\t\tv = DotProduct(p, y) / sqrt(v);\n\t\tif (u != 0 or v != 0)\n\t\t\tresult = atan2(v, u) * 180 / kPI;\n\t}\n\t\n\treturn result;\n}\n\ndouble CosinusAngle(const MPoint& p1, const MPoint& p2, const MPoint& p3, const MPoint& p4)\n{\n\tMPoint v12 = p1 - p2;\n\tMPoint v34 = p3 - p4;\n\t\n\tdouble result = 0;\n\t\n\tdouble x = DotProduct(v12, v12) * DotProduct(v34, v34);\n\tif (x > 0)\n\t\tresult = DotProduct(v12, v34) / sqrt(x);\n\t\n\treturn result;\n}\n\n// --------------------------------------------------------------------\n\ntuple<double,MPoint> QuaternionToAngleAxis(MQuaternion q)\n{\n\tif (q.R_component_1() > 1)\n\t\tq = Normalize(q);\n\n\t// angle:\n\tdouble angle = 2 * acos(q.R_component_1());\n\tangle = angle * 180 / kPI;\n\n\t// axis:\n\tdouble s = sqrt(1 - q.R_component_1() * q.R_component_1());\n\tif (s < 0.001)\n\t\ts = 1;\n\t\n\tMPoint axis(q.R_component_2() / s, q.R_component_3() / s, q.R_component_4() / s);\n\n\treturn make_tuple(angle, axis);\n}\n\nMPoint CenterPoints(vector<MPoint>& points)\n{\n\tMPoint t;\n\t\n\tforeach (MPoint& pt, points)\n\t{\n\t\tt.mX += pt.mX;\n\t\tt.mY += pt.mY;\n\t\tt.mZ += pt.mZ;\n\t}\n\t\n\tt.mX /= points.size();\n\tt.mY /= points.size();\n\tt.mZ /= points.size();\n\t\n\tforeach (MPoint& pt, points)\n\t{\n\t\tpt.mX -= t.mX;\n\t\tpt.mY -= t.mY;\n\t\tpt.mZ -= t.mZ;\n\t}\n\t\n\treturn t;\n}\n\nMPoint Centroid(vector<MPoint>& points)\n{\n\tMPoint result;\n\t\n\tforeach (MPoint& pt, points)\n\t\tresult += pt;\n\t\n\tresult /= points.size();\n\t\n\treturn result;\n}\n\ndouble RMSd(const vector<MPoint>& a, const vector<MPoint>& b)\n{\n\tdouble sum = 0;\n\tfor (uint32 i = 0; i < a.size(); ++i)\n\t{\n\t\tvalarray<double> d(3);\n\t\t\n\t\td[0] = b[i].mX - a[i].mX;\n\t\td[1] = b[i].mY - a[i].mY;\n\t\td[2] = b[i].mZ - a[i].mZ;\n\n\t\td *= d;\n\t\t\n\t\tsum += d.sum();\n\t}\n\t\n\treturn sqrt(sum / a.size());\n}\n\n// The next function returns the largest solution for a quartic equation\n// based on Ferrari's algorithm.\n// A depressed quartic is of the form:\n//\n//   x^4 + ax^2 + bx + c = 0\n//\n// (since I'm too lazy to find out a better way, I've implemented the\n//  routine using complex values to avoid nan's as a result of taking\n//  sqrt of a negative number)\ndouble LargestDepressedQuarticSolution(double a, double b, double c)\n{\n\tcomplex<double> P = - (a * a) / 12 - c;\n\tcomplex<double> Q = - (a * a * a) / 108 + (a * c) / 3 - (b * b) / 8;\n\tcomplex<double> R = - Q / 2.0 + sqrt((Q * Q) / 4.0 + (P * P * P) / 27.0);\n\t\n\tcomplex<double> U = pow(R, 1 / 3.0);\n\t\n\tcomplex<double> y;\n\tif (U == 0.0)\n\t\ty = -5.0 * a / 6.0 + U - pow(Q, 1.0 / 3.0);\n\telse\n\t\ty = -5.0 * a / 6.0 + U - P / (3.0 * U);\n\n\tcomplex<double> W = sqrt(a + 2.0 * y);\n\t\n\t// And to get the final result:\n\t// result = (\u00b1W + sqrt(-(3 * alpha + 2 * y \u00b1 2 * beta / W))) / 2;\n\t// We want the largest result, so:\n\n\tvalarray<double> t(4);\n\n\tt[0] = (( W + sqrt(-(3.0 * a + 2.0 * y + 2.0 * b / W))) / 2.0).real();\n\tt[1] = (( W + sqrt(-(3.0 * a + 2.0 * y - 2.0 * b / W))) / 2.0).real();\n\tt[2] = ((-W + sqrt(-(3.0 * a + 2.0 * y + 2.0 * b / W))) / 2.0).real();\n\tt[3] = ((-W + sqrt(-(3.0 * a + 2.0 * y - 2.0 * b / W))) / 2.0).real();\n\n\treturn t.max();\n}\n\nMQuaternion AlignPoints(const vector<MPoint>& pa, const vector<MPoint>& pb)\n{\n\t// First calculate M, a 3x3 matrix containing the sums of products of the coordinates of A and B\n\tmatrix<double> M(3, 3, 0);\n\n\tfor (uint32 i = 0; i < pa.size(); ++i)\n\t{\n\t\tconst MPoint& a = pa[i];\n\t\tconst MPoint& b = pb[i];\n\t\t\n\t\tM(0, 0) += a.mX * b.mX;\tM(0, 1) += a.mX * b.mY;\tM(0, 2) += a.mX * b.mZ;\n\t\tM(1, 0) += a.mY * b.mX;\tM(1, 1) += a.mY * b.mY;\tM(1, 2) += a.mY * b.mZ;\n\t\tM(2, 0) += a.mZ * b.mX;\tM(2, 1) += a.mZ * b.mY;\tM(2, 2) += a.mZ * b.mZ;\n\t}\n\t\n\t// Now calculate N, a symmetric 4x4 matrix\n\tsymmetric_matrix<double> N(4);\n\t\n\tN(0, 0) =  M(0, 0) + M(1, 1) + M(2, 2);\n\tN(0, 1) =  M(1, 2) - M(2, 1);\n\tN(0, 2) =  M(2, 0) - M(0, 2);\n\tN(0, 3) =  M(0, 1) - M(1, 0);\n\t\n\tN(1, 1) =  M(0, 0) - M(1, 1) - M(2, 2);\n\tN(1, 2) =  M(0, 1) + M(1, 0);\n\tN(1, 3) =  M(0, 2) + M(2, 0);\n\t\n\tN(2, 2) = -M(0, 0) + M(1, 1) - M(2, 2);\n\tN(2, 3) =  M(1, 2) + M(2, 1);\n\t\n\tN(3, 3) = -M(0, 0) - M(1, 1) + M(2, 2);\n\n\t// det(N - \u03bbI) = 0\n\t// find the largest \u03bb (\u03bbm)\n\t//\n\t// A\u03bb4 + B\u03bb3 + C\u03bb2 + D\u03bb + E = 0\n\t// A = 1\n\t// B = 0\n\t// and so this is a so-called depressed quartic\n\t// solve it using Ferrari's algorithm\n\t\n\tdouble C = -2 * (\n\t\tM(0, 0) * M(0, 0) + M(0, 1) * M(0, 1) + M(0, 2) * M(0, 2) +\n\t\tM(1, 0) * M(1, 0) + M(1, 1) * M(1, 1) + M(1, 2) * M(1, 2) +\n\t\tM(2, 0) * M(2, 0) + M(2, 1) * M(2, 1) + M(2, 2) * M(2, 2));\n\t\n\tdouble D = 8 * (M(0, 0) * M(1, 2) * M(2, 1) +\n\t\t\t\t\tM(1, 1) * M(2, 0) * M(0, 2) +\n\t\t\t\t\tM(2, 2) * M(0, 1) * M(1, 0)) -\n\t\t\t   8 * (M(0, 0) * M(1, 1) * M(2, 2) +\n\t\t\t\t\tM(1, 2) * M(2, 0) * M(0, 1) +\n\t\t\t\t\tM(2, 1) * M(1, 0) * M(0, 2));\n\t\n\tdouble E = \n\t\t(N(0,0) * N(1,1) - N(0,1) * N(0,1)) * (N(2,2) * N(3,3) - N(2,3) * N(2,3)) +\n\t\t(N(0,1) * N(0,2) - N(0,0) * N(2,1)) * (N(2,1) * N(3,3) - N(2,3) * N(1,3)) +\n\t\t(N(0,0) * N(1,3) - N(0,1) * N(0,3)) * (N(2,1) * N(2,3) - N(2,2) * N(1,3)) +\n\t\t(N(0,1) * N(2,1) - N(1,1) * N(0,2)) * (N(0,2) * N(3,3) - N(2,3) * N(0,3)) +\n\t\t(N(1,1) * N(0,3) - N(0,1) * N(1,3)) * (N(0,2) * N(2,3) - N(2,2) * N(0,3)) +\n\t\t(N(0,2) * N(1,3) - N(2,1) * N(0,3)) * (N(0,2) * N(1,3) - N(2,1) * N(0,3));\n\t\n\t// solve quartic\n\tdouble lm = LargestDepressedQuarticSolution(C, D, E);\n\t\n\t// calculate t = (N - \u03bbI)\n\tmatrix<double> li = identity_matrix<double>(4) * lm;\n\tmatrix<double> t = N - li;\n\t\n\t// calculate a matrix of cofactors for t\n\tmatrix<double> cf(4, 4);\n\n\tconst uint32 ixs[4][3] =\n\t{\n\t\t{ 1, 2, 3 },\n\t\t{ 0, 2, 3 },\n\t\t{ 0, 1, 3 },\n\t\t{ 0, 1, 2 }\n\t};\n\n\tuint32 maxR = 0;\n\tfor (uint32 r = 0; r < 4; ++r)\n\t{\n\t\tconst uint32* ir = ixs[r];\n\t\t\n\t\tfor (uint32 c = 0; c < 4; ++c)\n\t\t{\n\t\t\tconst uint32* ic = ixs[c];\n\n\t\t\tcf(r, c) =\n\t\t\t\tt(ir[0], ic[0]) * t(ir[1], ic[1]) * t(ir[2], ic[2]) +\n\t\t\t\tt(ir[0], ic[1]) * t(ir[1], ic[2]) * t(ir[2], ic[0]) +\n\t\t\t\tt(ir[0], ic[2]) * t(ir[1], ic[0]) * t(ir[2], ic[1]) -\n\t\t\t\tt(ir[0], ic[2]) * t(ir[1], ic[1]) * t(ir[2], ic[0]) -\n\t\t\t\tt(ir[0], ic[1]) * t(ir[1], ic[0]) * t(ir[2], ic[2]) -\n\t\t\t\tt(ir[0], ic[0]) * t(ir[1], ic[2]) * t(ir[2], ic[1]);\n\t\t}\n\t\t\n\t\tif (r > maxR and cf(r, 0) > cf(maxR, 0))\n\t\t\tmaxR = r;\n\t}\n\t\n\t// NOTE the negation of the y here, why? Maybe I swapped r/c above?\n\tMQuaternion q(cf(maxR, 0), cf(maxR, 1), -cf(maxR, 2), cf(maxR, 3));\n\tq = Normalize(q);\n\t\n\treturn q;\n}\n", "meta": {"hexsha": "be34987fc54a0ce0d034f101883ada192229aa8c", "size": 8732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/dssp/primitives-3d.cpp", "max_stars_repo_name": "confitarlaburra/pteros2.0", "max_stars_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-19T14:36:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T14:36:10.000Z", "max_issues_repo_path": "thirdparty/dssp/primitives-3d.cpp", "max_issues_repo_name": "confitarlaburra/pteros2.0", "max_issues_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/dssp/primitives-3d.cpp", "max_forks_repo_name": "confitarlaburra/pteros2.0", "max_forks_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1618037135, "max_line_length": 97, "alphanum_fraction": 0.502290426, "num_tokens": 3721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6354593702680912}}
{"text": "#include \"phase_space.hpp\"\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <gsl/gsl_sf_bessel.h>\n\nusing MomentaType = std::array<phase_space::LVector<double>, 4>;\n\n/// Struct holding whatever parameters are needed\nstruct ModelParameters {\n  double mx;\n  std::array<double, 4> fsp_masses;\n};\n\n/// Function computing squared matrix element\nauto msqrd(const MomentaType &momenta, const ModelParameters &params)\n    -> double {\n  return 1.0;\n}\n\n/// Compute zero-temperature cross section\nauto cross_section(double cme, const ModelParameters &params) -> double {\n  auto msqrd_ = [&params](const MomentaType &momenta) {\n    return msqrd(momenta, params);\n  };\n  return phase_space::cross_section(msqrd_, cme, params.mx, params.mx,\n                                    params.fsp_masses)\n      .first;\n}\n\n/// Compute the thermal cross section for X + X -> A + B + C + D\n///\n/// Usual integal is:\n///     <\u03c3v> = (2 \u03c0\u00b2 T) \u222b ds \u03c3[\u221as] (s - 4 m\u00b2) \u221as K\u2081[\u221as/T] / (4\u03c0 m\u00b2 T K\u2082[m/T])\n/// Define: s = z\u00b2 m\u00b2, x = m /T. Then this becomes:\n///     <\u03c3v> = x \u222b dz z\u00b2 (z\u00b2 - 4) \u03c3[m z] K\u2081[x * z] / (4 K\u2082[x]\u00b2)\n/// Next, define scaled bessel functions: K\u2081[x] = exp(-x) k\u2081[x]\n/// and K\u2082[x] = exp(-x) k\u2082[x]. Then:\n///     <\u03c3v> = x / (4 k\u2082[x]\u00b2) \u222b dz z\u00b2 (z\u00b2 - 4) \u03c3[m z] k\u2081[x * z] exp(-x (z-2))\ndouble thermal_cross_section(const double x, const ModelParameters &params) {\n  using boost::math::quadrature::gauss_kronrod;\n\n  const double den = 2.0 * gsl_sf_bessel_Kn_scaled(2, x);\n  const double pre = x / (den * den);\n  const double mx = params.mx;\n\n  auto f = [x, &params, mx](double z) -> double {\n    const double z2 = z * z;\n    const double sig = cross_section(z * mx, params);\n    const double ker =\n        z2 * (z2 - 4.0) * gsl_sf_bessel_K1_scaled(x * z) * exp(-x * (z - 2.0));\n    return sig * ker;\n  };\n\n  const double integral = gauss_kronrod<double, 15>::integrate(\n      f, 4.0, std::numeric_limits<double>::infinity(), 5, 1e-8);\n\n  return pre * integral;\n}\n\nint main() {\n\n  ModelParameters params = {100.0, {1.0, 1.0, 1.0, 1.0}};\n  std::cout << thermal_cross_section(1.0, params);\n  return 0.0;\n}\n", "meta": {"hexsha": "dccddecea79e5bd4d866443b244b6a176cc9fb94", "size": 2089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/thermal_cross_section.cpp", "max_stars_repo_name": "LoganAMorrison/phase_space_integration", "max_stars_repo_head_hexsha": "06de5dc3c8efeae66ebabba468d7b28be6986ff3", "max_stars_repo_licenses": ["MIT"], "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/thermal_cross_section.cpp", "max_issues_repo_name": "LoganAMorrison/phase_space_integration", "max_issues_repo_head_hexsha": "06de5dc3c8efeae66ebabba468d7b28be6986ff3", "max_issues_repo_licenses": ["MIT"], "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/thermal_cross_section.cpp", "max_forks_repo_name": "LoganAMorrison/phase_space_integration", "max_forks_repo_head_hexsha": "06de5dc3c8efeae66ebabba468d7b28be6986ff3", "max_forks_repo_licenses": ["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.1384615385, "max_line_length": 79, "alphanum_fraction": 0.62326472, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6353975477052267}}
{"text": "#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n#include \"../include/ply.h\"\n\n\n\n\n// contruct the stiffness matrix of the ply in the ply coordinates. P\nEigen::Matrix3d build_Q(const Properties& p);\n\ndouble to_radian(double angle_degree);\n\nusing std::cin; using std::cout; using std::endl;\nusing Eigen::Matrix3d;\n\nply::ply(const std::string material_label, \n    const Properties material_properties, \n    const double theta, const double thickness):\n    material_label_(material_label), \n    material_properties_(material_properties), theta_(theta), \n    thickness_(thickness) {\n    \n    double angle_radian = to_radian(theta);\n    double s = sin(angle_radian);\n    double c = cos(angle_radian);\n    Matrix3d T_stress_inv;\n    Matrix3d T_strain;\n\n    T_stress_inv << pow(c,2), pow(s,2), -2*s*c,\n                    pow(s,2), pow(c,2),  2*s*c,\n                    s*c     , -s*c    ,  pow(c,2) - pow(s,2);\n\n    T_strain << pow(c,2), pow(s,2),  s*c,\n                pow(s,2), pow(c,2), -s*c,\n                -2*s*c     , 2*s*c  ,  pow(c,2) - pow(s,2);    \n    \n    Matrix3d Q = build_Q(material_properties_);\n\n    // Transformation from ply coordinates to laminate coordinates.\n    Qbar_ = T_stress_inv * Q * T_strain;\n\n}\n\nMatrix3d build_Q(const Properties& p) {\n    double D = 1 - p.E2 / p.E1 * pow(p.nu12, 2);\n    Matrix3d Q;\n\n    Q << p.E1/D       , p.nu12*p.E2/D, 0,\n         p.nu12*p.E2/D, p.E2/D       , 0,\n         0            , 0            , p.G12;\n\n    return Q;\n}\n\ndouble to_radian(double angle_degree) {\n    return angle_degree * M_PI/180;\n}\n\n", "meta": {"hexsha": "d5624b000f1e89496fec055a53de9c25a9c0f821", "size": 1563, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/ply.cc", "max_stars_repo_name": "quentin-tw/laminate_calc", "max_stars_repo_head_hexsha": "d70718ab1092e502f8e467c57d1284eddf8836f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/ply.cc", "max_issues_repo_name": "quentin-tw/laminate_calc", "max_issues_repo_head_hexsha": "d70718ab1092e502f8e467c57d1284eddf8836f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/ply.cc", "max_forks_repo_name": "quentin-tw/laminate_calc", "max_forks_repo_head_hexsha": "d70718ab1092e502f8e467c57d1284eddf8836f2", "max_forks_repo_licenses": ["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.05, "max_line_length": 69, "alphanum_fraction": 0.5950095969, "num_tokens": 457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6353975298643395}}
{"text": "#include <HElib/FHE.h>\n#include <HElib/FHEContext.h>\n#include <HElib/EncryptedArray.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <iostream>\n#include <fstream>\nvoid generate_poly(std::vector<NTL::ZZX> &polys,\n                   const EncryptedArray *ea,\n                   const long upper) {\n    polys.resize(ea->size());\n    long d = ea->getDegree();\n    for (size_t i = 0; i < polys.size(); i++) {\n        polys[i].SetLength(d);\n        for (long j = 0; j < d; j++)\n            NTL::SetCoeff(polys[i], j, NTL::RandomBnd(upper));\n        // std::cout << NTL::deg(polys[i]) << \"=?\" << d << std::endl;\n    }\n}\n\nlong inner_prod(NTL::ZZX const& v, NTL::ZZX const& u, \n                const long d,\n                const long upper) {\n    NTL::ZZ ip(0);\n    // std::cout << v << \" \" << u << std::endl;\n    for (long i = 0; i < d; i++) {\n        // std::cout << NTL::coeff(v, i)  << \"*\" << NTL::coeff(u, d - i - 1) << std::endl;\n        ip = ip + NTL::coeff(v, i) * NTL::coeff(u, d - i - 1);\n    }\n    return ip % upper;\n}\n\nint main(int argc, char *argv[]) {\n    // long m = 32;\n    // long p = 113;\n    long m = NTL::RandomPrime_long(5, 20);\n    long p = NTL::RandomPrime_long(13, 20);\n    do {\n          p = NTL::RandomPrime_long(13, 20);\n     } while ((m % p) == 0);\n    FHEcontext context(m, p, 1);\n    auto G = context.alMod.getFactorsOverZZ()[0];\n    // EncryptedArray *ea = new EncryptedArray(context, G);\n    auto ea = context.ea;\n    std::cout << m << \" \" << p << std::endl;\n    std::cout << ea->size() << \" \" << ea->getDegree() << std::endl;\n    buildModChain(context, 4);\n    FHESecKey sk(context);\n    sk.GenSecKey(64);\n    \n    std::vector<NTL::ZZX> slots, slots2;\n    generate_poly(slots, ea, p);\n    generate_poly(slots2, ea, p);\n    for (size_t i = 0; i < slots.size(); i++) {\n        std::cout << inner_prod(slots[i], slots2[i], ea->getDegree(), p) << std::endl;\n    }\n    std::cout << \"\\n\";\n    Ctxt ctx(sk), ctx2(sk);\n    ea->skEncrypt(ctx, sk, slots); \n    ea->skEncrypt(ctx2, sk, slots2); \n    ctx *= ctx2;\n    ea->decrypt(ctx, sk, slots);\n    for (auto &ss : slots)\n        std::cout << NTL::coeff(ss, ea->getDegree() - 1) << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "57894a2e4033c454b9d9ad433d5efb24db276e04", "size": 2178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_general_double_packing.cpp", "max_stars_repo_name": "Vampsj/SMP", "max_stars_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_general_double_packing.cpp", "max_issues_repo_name": "Vampsj/SMP", "max_issues_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_general_double_packing.cpp", "max_forks_repo_name": "Vampsj/SMP", "max_forks_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5074626866, "max_line_length": 90, "alphanum_fraction": 0.5220385675, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6353623348361178}}
{"text": "#include <iostream>\n#include <random>\n#include <acado_toolkit.hpp>\n#include <acado_gnuplot.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\n#define pi 3.14159\n\nusing namespace std;\n\nstatic boost::random::mt19937 gen;\n\nint gen_data(float bounds[8], int index, char thread);\nfloat rand_gen(float lim[2]);\n\nfloat rand_gen(float lim[2]){\n  static boost::random::uniform_real_distribution<> dist(0, 1);\n  return lim[0] + dist(gen)*(lim[1] - lim[0]);\n}\n\nint gen_data(float bounds[8], int index, char thread){\n  string states_nm, parameters_nm, control_nm;\n  bool flag = false;\n\n  USING_NAMESPACE_ACADO\n\n  DifferentialState        q1,q2,qd1,qd2;   // the differential states\n  Control                  tau1,tau2;       // the control input u\n  Parameter                T;\n  DifferentialEquation     f( 0.0, 0.5 );\n\n  //  -------------------------------------\n\n  OCP ocp( 0.0, 0.5,5 );  \n  ocp.minimizeLagrangeTerm(1+tau1*tau1 + tau2*tau2);\n  //ocp.minimizeMayerTerm(q1*q1 + q2*q2 + qd1*qd1 + qd2*qd2 );\n\n  f << dot(q1) == qd1;\n  f << dot(q2) == qd2;\n  f << dot(qd1) == -(48*tau1 - 48*tau2 + 24*qd1*qd1*sin(q2) + 24*qd2*qd2*sin(q2) + 18*qd1*qd1*sin(2*q2) - 72*tau2*cos(q2) + 48*qd1*qd2*sin(q2))/(36*cos(q2)*cos(q2) - 64);\n  f << dot(qd2) == (48*tau1 - 240*tau2 + 120*qd1*qd1*sin(q2) + 24*qd2*qd2*sin(q2) + 36*qd1*qd1*sin(2*q2) + 18*qd2*qd2*sin(2*q2) + 72*tau1*cos(q2) - 144*tau2*cos(q2) + 48*qd1*qd2*sin(q2) + 36*qd1*qd2*sin(2*q2))/(18*cos(2*q2) - 46);\n\n  ocp.subjectTo(f);\n  ocp.subjectTo(AT_START, q1 ==  bounds[0] );       \n\n  ocp.subjectTo(AT_START, q2 ==  bounds[1] );       \n\n  ocp.subjectTo(AT_START, qd1 ==  bounds[2] );\n  ocp.subjectTo(AT_START, qd2 ==  bounds[3] );\n\n  ocp.subjectTo(AT_END, q1 == bounds[4]);\n  ocp.subjectTo(AT_END, q2 == bounds[5]);\n  ocp.subjectTo(AT_END, qd1 == bounds[6]);\n  ocp.subjectTo(AT_END, qd2 == bounds[7]);\n\n  // bounds on the control input u\n  ocp.subjectTo(-400 <= tau1 <= 400);  \n  ocp.subjectTo(-400 <= tau2 <= 400);\n\n  //  -------------------------------------\n  \n  // Optimization algorithm\n  OptimizationAlgorithm algorithm(ocp);     \n  algorithm.set( DISCRETIZATION_TYPE , SINGLE_SHOOTING);\n  algorithm.set( INTEGRATOR_TYPE , INT_RK45);\n  algorithm.set( HESSIAN_APPROXIMATION   , BLOCK_BFGS_UPDATE);\n  algorithm.set( KKT_TOLERANCE   , 1e-1); \n  algorithm.set( ABSOLUTE_TOLERANCE, 1e-1);\n  algorithm.set( INTEGRATOR_TOLERANCE, 1e-1);\n  algorithm.set( MAX_NUM_ITERATIONS, 1000);\n  algorithm.set( MAX_NUM_INTEGRATOR_STEPS, 10000);\n\n  algorithm.set(PRINT_COPYRIGHT,BT_FALSE);\n  algorithm.set(PRINTLEVEL,LOW);\n  algorithm.set(PRINT_INTEGRATOR_PROFILE,BT_FALSE);\n  algorithm.set(PRINT_SCP_METHOD_PROFILE,BT_FALSE);\n  bool return_code = algorithm.solve();                        \n\n  // VariablesGrid grid;\n  // algorithm.getDifferentialStates(grid);\n  // DVector final_state(4), diff(4);\n  // final_state = grid.getLastVector(); \n  \n  // diff(0) = final_state[0] - bounds[4];\n  // diff(1) = final_state[1] - bounds[5];\n  // diff(2) = final_state[2] - bounds[6];\n  // diff(3) = final_state[3] - bounds[7];\n\n  // if (diff.getNorm(VN_L2) < 0.001){\n  \n  if (return_code == 0){\n    flag = true;\n    // cout << thread;\n    states_nm = \"states_\" + to_string(index) + \"_\" + thread + \".txt\";\n    parameters_nm = \"parameters_\" + to_string(index) + \"_\" + thread + \".txt\";\n    control_nm = \"control_\" + to_string(index) + \"_\" + thread + \".txt\";\n    algorithm.getDifferentialStates(states_nm.c_str());\n    algorithm.getObjectiveValue(parameters_nm.c_str());\n    algorithm.getControls(control_nm.c_str());\n  }\n\n  clearAllStaticCounters();\n  return flag;\n}\n\nint main(int argc, char const *argv[])\n{  \n  float q_lims[2] = {0.0,2*pi};\n  float qd_lims[2] = {-30.0,30.0};\n    \n  if(argc != 3){\n    cout << \"Incorrect number of arguments.\" << endl;\n  }\n  else{\n    int num_iter = atoi(argv[1]);\n    \n    gen.seed(time(0) + int(*argv[2]));\n    int i = 0;\n    while(i < num_iter){\n      float bounds[8] = {rand_gen(q_lims),rand_gen(q_lims),rand_gen(qd_lims),rand_gen(qd_lims),rand_gen(q_lims),rand_gen(q_lims),rand_gen(qd_lims),rand_gen(qd_lims)};\n      cout << i << endl;\n      cout << bounds[0] << \" \" << bounds[1] << \" \" << bounds[2] << \" \" << bounds[3] << \" \" << bounds[4] << \" \" << bounds[5] << \" \" << bounds[6] << \" \" << bounds[7] << endl;\n      bool success = gen_data(bounds, i, *argv[2]);\n      if(success){\n        i++;\n      }\n    }\n  }\n  return 0;\n}\n\n", "meta": {"hexsha": "2cce6d303cb0d98158efa6927f6d5714f49da74f", "size": 4430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2link_direct/src/2link.cpp", "max_stars_repo_name": "DeepakParamkusam/learning-based-RRT", "max_stars_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-06-13T11:36:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-13T11:36:45.000Z", "max_issues_repo_path": "2link_direct/src/2link.cpp", "max_issues_repo_name": "DeepakParamkusam/learning-based-RRT", "max_issues_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2link_direct/src/2link.cpp", "max_forks_repo_name": "DeepakParamkusam/learning-based-RRT", "max_forks_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3082706767, "max_line_length": 230, "alphanum_fraction": 0.6178329571, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6352656760027481}}
{"text": "#pragma once\n\n#include <boost/multi_array.hpp>\n\nnamespace fuzzy\n{\n  inline int _edit_distance_char_nonempty(const char *s1, int n1, const char *s2, int n2) {\n    boost::multi_array<int, 2> arr(boost::extents[n1+1][n2+1]);\n\n    arr[0][0] = 0;\n    for (int i = 1; i < n1 + 1; i++)\n      arr[i][0] = arr[i-1][0] + 1;\n    for (int j = 1; j < n2 + 1; j++)\n      arr[0][j] = arr[0][j-1] + 1;\n\n    for (int i = 1; i < n1 + 1; i++)\n    {\n      for (int j = 1; j < n2 + 1; j++)\n      {\n        int diff = 0;\n        if (s1[i-1] != s2[j-1])\n          diff = 1;\n        arr[i][j] = std::min(std::min(arr[i - 1][j] + 1,\n                                      arr[i][j - 1] + 1),\n                             arr[i - 1][j - 1] + diff);\n      }\n    }\n    return arr[n1][n2];\n  }\n\n  inline int _edit_distance_char(const char *s1, int n1, const char *s2, int n2) {\n    if (n1==0 || n2==0) return n1+n2;\n    return _edit_distance_char_nonempty(s1, n1, s2, n2);\n  }\n}\n", "meta": {"hexsha": "be2afdc99556370a06ae24f01bbfa22cc2b5964b", "size": 949, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/fuzzy/edit_distance.hxx", "max_stars_repo_name": "guillaumekln/fuzzy-match", "max_stars_repo_head_hexsha": "3cf2d46a8c8d48b6ff697a9c0a68cf9cc24ecb64", "max_stars_repo_licenses": ["MIT"], "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/fuzzy/edit_distance.hxx", "max_issues_repo_name": "guillaumekln/fuzzy-match", "max_issues_repo_head_hexsha": "3cf2d46a8c8d48b6ff697a9c0a68cf9cc24ecb64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/fuzzy/edit_distance.hxx", "max_forks_repo_name": "guillaumekln/fuzzy-match", "max_forks_repo_head_hexsha": "3cf2d46a8c8d48b6ff697a9c0a68cf9cc24ecb64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3611111111, "max_line_length": 91, "alphanum_fraction": 0.4636459431, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6352656750658944}}
{"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/** \\example qr.cpp\n*\n*   This tutorial shows how the QR factorization of matrices from ViennaCL or Boost.uBLAS can be computed.\n*\n**/\n\n// Activate ublas support in ViennaCL\n#define VIENNACL_WITH_UBLAS\n\n//\n// Include necessary system headers\n//\n#include <iostream>\n\n//\n// ViennaCL includes\n//\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/qr.hpp\"\n\n//\n// Boost includes\n//\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n\n/**\n* A helper function comparing two matrices and returning the maximum entry-wise relative error encountered.\n**/\ntemplate<typename MatrixType>\ndouble check(MatrixType const & qr, MatrixType const & ref)\n{\n  bool do_break = false;\n  double max_error = 0;\n  for (std::size_t i=0; i<ref.size1(); ++i)\n  {\n    for (std::size_t j=0; j<ref.size2(); ++j)\n    {\n      if (qr(i,j) != 0.0 && ref(i,j) != 0.0)\n      {\n        double rel_err = fabs(qr(i,j) - ref(i,j)) / fabs(ref(i,j) );\n\n        if (rel_err > max_error)\n          max_error = rel_err;\n      }\n\n\n      /* Uncomment the following if you also want to check for NaNs.\n      if (qr(i,j) != qr(i,j))\n      {\n        std::cout << \"!!!\" << std::endl;\n        std::cout << \"!!! NaN detected at i=\" << i << \" and j=\" << j << std::endl;\n        std::cout << \"!!!\" << std::endl;\n        do_break = true;\n        break;\n      }*/\n    }\n    if (do_break)\n      break;\n  }\n  return max_error;\n}\n\n/**\n*  We set up a random matrix using Boost.uBLAS and use it to initialize a ViennaCL matrix.\n*  Then we compute the QR factorization directly for the uBLAS matrix as well as the ViennaCL matrix.\n**/\nint main (int, const char **)\n{\n  typedef double               ScalarType;     //feel free to change this to 'double' if supported by your hardware\n  typedef boost::numeric::ublas::matrix<ScalarType>              MatrixType;\n  typedef viennacl::matrix<ScalarType, viennacl::column_major>   VCLMatrixType;\n\n  std::size_t rows = 113;   // number of rows in the matrix\n  std::size_t cols = 54;    // number of columns\n\n  /**\n  * Create uBLAS matrices with some random input data.\n  **/\n  MatrixType ublas_A(rows, cols);\n  MatrixType Q(rows, rows);\n  MatrixType R(rows, cols);\n\n  // Some random data with a bit of extra weight on the diagonal\n  for (std::size_t i=0; i<rows; ++i)\n  {\n    for (std::size_t j=0; j<cols; ++j)\n    {\n      ublas_A(i,j) = ScalarType(-1.0) + ScalarType((i+1)*(j+1))\n                     + ScalarType( (rand() % 1000) - 500.0) / ScalarType(1000.0);\n\n      if (i == j)\n        ublas_A(i,j) += ScalarType(10.0);\n\n      R(i,j) = 0.0;\n    }\n\n    for (std::size_t j=0; j<rows; ++j)\n      Q(i,j) = ScalarType(0.0);\n  }\n\n  // keep initial input matrix for comparison\n  MatrixType ublas_A_backup(ublas_A);\n\n\n  /**\n  *   Setup the matrix in ViennaCL and copy the data from the uBLAS matrix:\n  **/\n  VCLMatrixType vcl_A(ublas_A.size1(), ublas_A.size2());\n\n  viennacl::copy(ublas_A, vcl_A);\n\n  /**\n  *  <h2>QR Factorization with Boost.uBLAS Matrices</h2>\n  * Compute QR factorization of A. A is overwritten with Householder vectors. Coefficients are returned and a block size of 3 is used.\n  * Note that at the moment the number of columns of A must be divisible by the block size\n  **/\n\n  std::cout << \"--- Boost.uBLAS ---\" << std::endl;\n  std::vector<ScalarType> ublas_betas = viennacl::linalg::inplace_qr(ublas_A);  //computes the QR factorization\n\n  /**\n  *  Let us check for the correct result:\n  **/\n  viennacl::linalg::recoverQ(ublas_A, ublas_betas, Q, R);\n  MatrixType ublas_QR = prod(Q, R);\n  double ublas_error = check(ublas_QR, ublas_A_backup);\n  std::cout << \"Maximum relative error (ublas): \" << ublas_error << std::endl;\n\n  /**\n  *  <h2>QR Factorization with Boost.uBLAS Matrices</h2>\n  *  We now compute the QR factorization from a ViennaCL matrix. Internally it uses Boost.uBLAS for the panel factorization.\n  **/\n  std::cout << \"--- Hybrid (default) ---\" << std::endl;\n  viennacl::copy(ublas_A_backup, vcl_A);\n  std::vector<ScalarType> hybrid_betas = viennacl::linalg::inplace_qr(vcl_A);\n\n  /**\n  *  Let us check for the correct result:\n  **/\n  viennacl::copy(vcl_A, ublas_A);\n  Q.clear(); R.clear();\n  viennacl::linalg::recoverQ(ublas_A, hybrid_betas, Q, R);\n  double hybrid_error = check(ublas_QR, ublas_A_backup);\n  std::cout << \"Maximum relative error (hybrid): \" << hybrid_error << std::endl;\n\n\n  /**\n  *  That's it. Print a success message and exit.\n  **/\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "13c15468aa263a8313a597f97208749c365b6a14", "size": 5342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/qr.cpp", "max_stars_repo_name": "ddemidov/viennacl-dev", "max_stars_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-08-23T17:05:21.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-23T17:06:24.000Z", "max_issues_repo_path": "examples/tutorial/qr.cpp", "max_issues_repo_name": "ddemidov/viennacl-dev", "max_issues_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tutorial/qr.cpp", "max_forks_repo_name": "ddemidov/viennacl-dev", "max_forks_repo_head_hexsha": "0f7de9cd28e54a5ca8f7c2ab03263bc56bf004ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1807909605, "max_line_length": 134, "alphanum_fraction": 0.6044552602, "num_tokens": 1477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6352105522772172}}
{"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 <random>\n#include <algorithm>\n#include <iterator>\n#include <vector>\n#include <iostream>\n#include <boost/math/special_functions/gamma.hpp>\n\nusing namespace std;\n\nvector<double> linspace( double start, double end, int num ) {\n\tdouble delta = (end - start) / (num - 1);\n\tvector<double> 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<double> vec, bool last = false ) {\n\tcout << \"[\";\n\tfor ( vector<double>::iterator it = vec.begin(); it != vec.end(); ++it ) {\n\t\tif ( vec.end() != it+1 ) {\n\t\t\tcout << setprecision (16) << *it;\n\t\t\tcout << \",\";\n\t\t} else {\n\t\t\tcout << setprecision (16) << *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(\n\tvector<double> x,\n\tvector<double> s,\n\tvector<double> lower_regularized,\n\tvector<double> upper_regularized,\n\tvector<double> lower_unregularized,\n\tvector<double> upper_unregularized\n) {\n\tcout << \"{\" << endl;\n\tcout << \"  \\\"x\\\": \";\n\tprint_vector( x );\n\tcout << \"  \\\"s\\\": \";\n\tprint_vector( s );\n\tcout << \"  \\\"lower_regularized\\\": \";\n\tprint_vector( lower_regularized );\n\tcout << \"  \\\"upper_regularized\\\": \";\n\tprint_vector( upper_regularized );\n\tcout << \"  \\\"lower_unregularized\\\": \";\n\tprint_vector( lower_unregularized );\n\tcout << \"  \\\"upper_unregularized\\\": \";\n\tprint_vector( upper_unregularized, true );\n\tcout << \"}\" << endl;\n\treturn;\n}\n\nint main() {\n\trandom_device rd;\n\tmt19937 g(rd());\n\n\tvector<double> x = linspace( 1.0, 40.0, 100 );\n\tshuffle( x.begin(), x.end(), g );\n\tvector<double> s = linspace( 1.0, 40.0, 100 );\n\tshuffle( s.begin(), s.end(), g );\n\tvector<double> lower_regularized;\n\tvector<double> upper_regularized;\n\tvector<double> lower_unregularized;\n\tvector<double> upper_unregularized;\n\n\tfor ( int i = 0; i < 100; i++  ) {\n\t\tdouble arg1 = s[ i ];\n\t\tdouble arg2 = x[ i ];\n\t\tlower_regularized.push_back( boost::math::gamma_p( arg1, arg2 ) );\n\t\tupper_regularized.push_back( boost::math::gamma_q( arg1, arg2 ) );\n\t\tlower_unregularized.push_back( boost::math::tgamma_lower( arg1, arg2 ) );\n\t\tupper_unregularized.push_back( boost::math::tgamma( arg1, arg2 ) );\n\t}\n\n\tprint_results( x, s, lower_regularized, upper_regularized, lower_unregularized, upper_unregularized );\n\treturn 0;\n}\n", "meta": {"hexsha": "92d5cab338619a45b89d974223d1764bb662083d", "size": 2462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fixtures/runner.cpp", "max_stars_repo_name": "math-io/gammainc", "max_stars_repo_head_hexsha": "00cb2a596f93b5264ffb52b050d03f913d109598", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-01-26T15:45:28.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-26T15:45:28.000Z", "max_issues_repo_path": "test/fixtures/runner.cpp", "max_issues_repo_name": "math-io/gammainc", "max_issues_repo_head_hexsha": "00cb2a596f93b5264ffb52b050d03f913d109598", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-04T05:14:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-04T05:14:45.000Z", "max_forks_repo_path": "test/fixtures/runner.cpp", "max_forks_repo_name": "math-io/gammainc", "max_forks_repo_head_hexsha": "00cb2a596f93b5264ffb52b050d03f913d109598", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6629213483, "max_line_length": 170, "alphanum_fraction": 0.6450040617, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214158, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6352105393239518}}
{"text": "/**\n * @file\n * @brief We build a tensor product mesh on the unit square and use pointwise\n * refinement to refine it.\n * @author Anian Ruoss\n * @date   2018-10-06 16:37:17\n * @copyright MIT License\n */\n\n#include <boost/program_options.hpp>\n#include <functional>\n#include <iostream>\n#include <vector>\n\n#include <lf/refinement/mesh_hierarchy.h>\n#include <lf/refinement/refutils.h>\n#include \"lf/io/io.h\"\n#include \"lf/mesh/utils/utils.h\"\n\nusing CodimMeshDataSet_t =\n    std::shared_ptr<lf::mesh::utils::CodimMeshDataSet<bool>>;\n\nbool PointInTriangle(const Eigen::MatrixXd &tria_coords,\n                     const Eigen::Vector2d &point) {\n  // calculate barycentric coordinates of point using affine transformation\n  // from reference triangle: phi(x_hat) = alpha + beta * x_hat\n  Eigen::Vector2d alpha = tria_coords.col(0);\n  Eigen::Matrix2d beta;\n  beta << tria_coords.col(1) - tria_coords.col(0),\n      tria_coords.col(2) - tria_coords.col(0);\n\n  Eigen::Vector2d loc_coords = beta.inverse() * (point - alpha);\n\n  return (0 <= loc_coords(0) && 0 <= loc_coords(1) && loc_coords.sum() <= 1);\n}\n\nCodimMeshDataSet_t MarkMesh(\n    const std::shared_ptr<const lf::mesh::Mesh> &mesh_ptr,\n    const Eigen::MatrixXd &point) {\n  // we use CodimMeshDataSet to store whether an edge has to be marked or not\n  CodimMeshDataSet_t marked =\n      lf::mesh::utils::make_CodimMeshDataSet<bool>(mesh_ptr, 1, false);\n\n  // loop through all cells to check if it contains the point\n  for (const lf::mesh::Entity &cell : mesh_ptr->Entities(0)) {\n    const lf::geometry::Geometry *geom_ptr = cell.Geometry();\n    lf::base::RefEl ref_el = cell.RefEl();\n    const Eigen::MatrixXd &ref_el_coords(ref_el.NodeCoords());\n    const Eigen::MatrixXd vtx_coords(geom_ptr->Global(ref_el_coords));\n\n    // mark all edges if the point lies inside the cell\n    if (ref_el == lf::base::RefEl::kTria()) {\n      if (PointInTriangle(vtx_coords, point)) {\n        for (const lf::mesh::Entity &edge : cell.SubEntities(1)) {\n          marked->operator()(edge) = true;\n        }\n      }\n    } else if (ref_el == lf::base::RefEl::kQuad()) {\n      // split quadrilateral into two triangles and check each separately\n      Eigen::MatrixXd tria1 = vtx_coords.block(0, 0, 2, 3);\n      Eigen::MatrixXd tria2(2, 3);\n      tria2 << vtx_coords.col(0), vtx_coords.col(2), vtx_coords.col(3);\n\n      if (PointInTriangle(tria1, point) || PointInTriangle(tria2, point)) {\n        for (const lf::mesh::Entity &edge : cell.SubEntities(1)) {\n          marked->operator()(edge) = true;\n        }\n      }\n    } else {\n      std::cerr << \"unknown cell geometry\" << std::endl;\n    }\n  }\n\n  return marked;\n}\n\nint main(int argc, char **argv) {\n  // define allowed command line arguments:\n  namespace po = boost::program_options;\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()(\"help\", \"Produce this help message\")(\n      \"num_steps\", po::value<size_t>()->default_value(5),\n      \"Number of refinement steps\")(\n      \"pointwise\", po::value<bool>()->default_value(true),\n      \"Whether to use pointwise refinement or not\")(\n      \"point\",\n      po::value<std::vector<double>>()->multitoken()->default_value(\n          std::vector<double>{.5, .5}, \".5, .5\"),\n      \"Point coordinates in unit square (ignored if pointwise=false)\");\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") != 0u) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n\n  size_t num_steps = vm[\"num_steps\"].as<size_t>();\n  bool pointwise = vm[\"pointwise\"].as<bool>();\n  std::vector<double> point_coords = vm[\"point\"].as<std::vector<double>>();\n  Eigen::Vector2d point(point_coords.data());\n\n  using size_type = lf::base::size_type;\n  using lf::mesh::utils::TikzOutputCtrl;\n\n  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =\n      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(2);\n\n  // build single-cell tensor product mesh on unit square\n  lf::mesh::hybrid2d::TPQuadMeshBuilder builder(mesh_factory_ptr);\n  builder.setBottomLeftCorner(Eigen::Vector2d{0, 0});\n  builder.setTopRightCorner(Eigen::Vector2d{1, 1});\n  builder.setNoXCells(1);\n  builder.setNoYCells(1);\n  std::shared_ptr<lf::mesh::Mesh> mesh_ptr = builder.Build();\n\n  // output mesh information\n  const lf::mesh::Mesh &mesh = *mesh_ptr;\n  lf::mesh::utils::PrintInfo(mesh, std::cout);\n  std::cout << std::endl;\n\n  // build mesh hierarchy\n  lf::refinement::MeshHierarchy multi_mesh(mesh_ptr, mesh_factory_ptr);\n\n  // mark edges of cells containing point\n  auto marker = [](const lf::mesh::Mesh &mesh, const lf::mesh::Entity &edge,\n                   CodimMeshDataSet_t mesh_data) -> bool {\n    return mesh_data->operator()(edge);\n  };\n\n  for (int step = 0; step < num_steps; ++step) {\n    // obtain pointer to mesh on finest level\n    const size_type n_levels = multi_mesh.NumLevels();\n    std::shared_ptr<const lf::mesh::Mesh> mesh_fine =\n        multi_mesh.getMesh(n_levels - 1);\n\n    // print number of entities of various co-dimensions\n    std::cout << \"Mesh on level \" << n_levels - 1 << \": \" << mesh_fine->Size(2)\n              << \" nodes, \" << mesh_fine->Size(1) << \" edges, \"\n              << mesh_fine->Size(0) << \" cells,\" << std::endl;\n\n    lf::mesh::utils::writeTikZ(\n        *mesh_fine,\n        std::string(\"refinement_mesh\") + std::to_string(step) + \".txt\",\n        TikzOutputCtrl::RenderCells | TikzOutputCtrl::CellNumbering |\n            TikzOutputCtrl::VerticeNumbering | TikzOutputCtrl::NodeNumbering |\n            TikzOutputCtrl::EdgeNumbering);\n\n    lf::io::writeMatplotlib(*mesh_fine, std::string(\"refinement_mesh\") +\n                                            std::to_string(step) + \".csv\");\n\n    if (pointwise) {\n      CodimMeshDataSet_t marked_mesh = MarkMesh(mesh_fine, point);\n      multi_mesh.MarkEdges(std::bind(marker, std::placeholders::_1,\n                                     std::placeholders::_2, marked_mesh));\n      multi_mesh.RefineMarked();\n    } else {\n      multi_mesh.RefineRegular();\n    }\n  }\n\n  // generate MATLAB functions describing all levels of mesh hierarchy\n  lf::refinement::WriteMatlab(multi_mesh, \"pointwise_refinement\");\n\n  return 0;\n}\n", "meta": {"hexsha": "d432f4b091fe4f36f8091870b6e98dbb93f8cd6a", "size": 6176, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/refinement/point_refinement_demo.cc", "max_stars_repo_name": "Cryoris/lehrfempp", "max_stars_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/refinement/point_refinement_demo.cc", "max_issues_repo_name": "Cryoris/lehrfempp", "max_issues_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/refinement/point_refinement_demo.cc", "max_forks_repo_name": "Cryoris/lehrfempp", "max_forks_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5443786982, "max_line_length": 79, "alphanum_fraction": 0.6515544041, "num_tokens": 1677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6352017954345845}}
{"text": "/*\nCopyright 2017 InitialDLab\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n#include <iostream>\n#include <string>\n#include <random>\n\n#include <cstdlib>\n\n#include <boost/timer/timer.hpp>\n#include <boost/random/taus88.hpp>\n#include <boost/random/uniform_smallint.hpp>\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n\nconstexpr int REPEAT = 1000000;\n\ntemplate <typename T>\nvoid test(std::string const& name)\n{\n    T t;\n    boost::timer::auto_cpu_timer _;\n    float s = 0;\n    for(int i = 0; i < REPEAT; ++i)\n    {\n        s += t.run();\n    }\n    std::cerr << name << ' ' << s << std::endl;\n            std::cerr << std::endl;\n}\n\nstruct Rand\n{\n    int run() { rand()%10000; }\n};\n\nstruct Drand48\n{\n    int run() { (size_t)(drand48()*10000); }\n};\n\nstruct GSLReal\n{\n    GSLReal() { _gsl_rng = gsl_rng_alloc (gsl_rng_taus); }\n\n    gsl_rng *_gsl_rng = nullptr;\n    int run() {\n        return gsl_ran_flat(_gsl_rng, 0, 10000);\n    }\n};\n\ntemplate<typename RNG, typename DIST>\nstruct Dist\n{\n    RNG rng;\n    int run() { \n        DIST dist(0, 10000);\n        dist(rng);\n    }\n};\n\ntemplate<typename RNG, typename DIST>\nstruct Dist_1 \n{\n    RNG rng;\n    DIST dist{0, 10000};\n    int run() { \n        dist(rng);\n    }\n};\n\ntemplate<typename RNG, typename DIST>\nstruct Dist_2 \n{\n    int run() { \n        RNG rng;\n        DIST dist{0, 10000};\n        dist(rng);\n    }\n};\n\nvoid test_uni()\n{\n    test<Rand>(\"rand\");\n    test<Drand48>(\"drand48\");\n\n    using std_default = std::default_random_engine;\n    using taus88 = boost::random::taus88;\n\n    using std_uni = std::uniform_int_distribution<int>;\n    using smallint = boost::random::uniform_smallint<int>;\n\n    test<Dist<std_default, std_uni>>(\"uni_default\");\n    test<Dist_1<std_default, std_uni>>(\"uni_default_1\");\n    test<Dist<taus88, std_uni>>(\"uni_taus88\");\n    test<Dist_1<taus88, std_uni>>(\"uni_taus88_1\");\n\n    test<Dist<std_default, smallint>>(\"smallint_default\");\n    test<Dist_1<std_default, smallint>>(\"smallint_default_1\");\n    test<Dist<taus88, smallint>>(\"smallint_taus88\");\n    test<Dist_1<taus88, smallint>>(\"smallint_taus88_1\");\n}\n\ntemplate<typename RNG, typename DIST>\nstruct RealDist\n{\n    RNG rng;\n    float run() { \n        DIST dist(0, 1);\n        return dist(rng);\n    }\n};\n\ntemplate<typename RNG, typename DIST>\nstruct RealDist_1 \n{\n    RNG rng;\n    DIST dist{0, 1};\n    float run() { \n        return dist(rng);\n    }\n};\n\ntemplate<typename RNG, typename DIST>\nstruct RealDist_2 \n{\n    float run() { \n        RNG rng;\n        DIST dist{0, 1};\n        return dist(rng);\n    }\n};\n\nvoid test_real()\n{\n    using std_default = std::default_random_engine;\n    using taus88 = boost::random::taus88;\n\n    using std_real = std::uniform_real_distribution<float>;\n\n    test<Rand>(\"rand\");\n    test<Drand48>(\"drand48\");\n    test<GSLReal>(\"GSL_real\");\n\n    test<RealDist<std_default, std_real>>(\"real_default\");\n    test<RealDist_1<std_default, std_real>>(\"real_default_1\");\n    test<RealDist<taus88, std_real>>(\"real_taus88\");\n    test<RealDist_1<taus88, std_real>>(\"real_taus88_1\");\n}\n\nvoid test_binomial()\n{\n    using taus88 = boost::random::taus88;\n    taus88 rng;\n    for(size_t total = 1; total < 100; total += 10)\n    {\n        //for(double prob = 0.0; prob < 1; prob += 0.2)\n        double prob = 0.001;\n        {\n            size_t s = 0;\n            {\n                boost::timer::auto_cpu_timer _;\n                for(int i = 0; i < REPEAT; ++i)\n                {\n                    s += std::binomial_distribution<size_t>(total, prob)(rng);\n                }\n            }\n            std::cerr << \"binomial \" << total << ' ' << prob << ' ' << s << std::endl;\n            std::cerr << std::endl;\n        }\n        {\n            size_t s = 0;\n            {\n                boost::timer::auto_cpu_timer _;\n                std::uniform_real_distribution<float> coin_dist(0,1);\n                for(int i = 0; i < REPEAT; ++i)\n                {\n                    for(size_t j = 0; j < total; ++j)\n                        if(coin_dist(rng) < prob)\n                            ++s;\n                }\n            }\n            std::cerr << \"coin \" <<  total << ' ' << prob << ' ' << s << std::endl;\n            std::cerr << std::endl;\n        }\n    }\n}\n\nint main()\n{\n//    test_uni();\n    test_real();\n//    test_binomial();\n    return 0;\n}\n", "meta": {"hexsha": "c91160ee2b4fe932c754d12c3b7425ae2b583870", "size": 5279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_random_number.cpp", "max_stars_repo_name": "InitialDLab/SampleIndex", "max_stars_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-09-30T22:34:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-18T21:21:35.000Z", "max_issues_repo_path": "test_random_number.cpp", "max_issues_repo_name": "InitialDLab/SONAR-SamplingIndex", "max_issues_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_issues_repo_licenses": ["MIT"], "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_random_number.cpp", "max_forks_repo_name": "InitialDLab/SONAR-SamplingIndex", "max_forks_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_forks_repo_licenses": ["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.5534883721, "max_line_length": 86, "alphanum_fraction": 0.6004925175, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.635177889131046}}
{"text": "// system includes -----------------------------------------------\n#include <boost/math/constants/constants.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n// own includes --------------------------------------------------\n#include <base/eigen2hdf.hpp>\n#include <base/init.hpp>\n#include <fft/fft2.hpp>\n#include <ridgelet/ridgelet_cell_array.hpp>\n#include <ridgelet/ridgelet_frame.hpp>\n#include <ridgelet/rt.hpp>\n\nusing namespace std;\n\nconst char* fname = \"test_rt.h5\";\n\ntypedef RT<> RT_t;\n\ntypedef RT_t::array_t array_t;\ntypedef RT_t::complex_array_t complex_array_t;\ntypedef RT_t::rt_coeff_t rt_coeff_t;\n\nvoid dump_frc(const std::vector<rt_coeff_t>& f_rc,\n              const RidgeletFrame& rt,\n              string fname = \"f_rc.h5\")\n{\n  hid_t file = H5Fcreate(fname.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  for (unsigned int i = 0; i < f_rc.size(); ++i) {\n    stringstream ss;\n    ss << rt.lambdas()[i];\n    string slam = ss.str();\n    eigen2hdf::save(file, slam, f_rc[i]);\n  }\n  H5Fclose(file);\n  cout << \"\\n\\n ---- Written f(lambda, t) to `\" << fname << \"` ----\\n\\n\";\n}\n\nint main(int argc, char* argv[])\n{\n  SOURCE_INFO();\n\n  namespace po = boost::program_options;\n\n  cout << \"FFTW_BACKWARD: \" << FFTW_BACKWARD << \"\\n\";\n  cout << \"FFTW_FORWARD: \" << FFTW_FORWARD << \"\\n\";\n\n  unsigned int Jx, Jy, rho_x, rho_y;\n\n  po::options_description options(\"options\");\n  options.add_options()(\"help\", \"produce help message\")\n      (\"Jx,i\", po::value<unsigned int>(&Jx)->default_value(2), \"Jx\")\n      (\"Jy,j\", po::value<unsigned int>(&Jy)->default_value(2), \"Jy\")\n      (\"rx,x\", po::value<unsigned int>(&rho_x)->default_value(1), \"rho_x\")\n      (\"ry,y\", po::value<unsigned int>(&rho_y)->default_value(1), \"rho_x\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << options << \"\\n\";\n    return 0;\n  }\n\n  cout << setw(20) << \"Jx\"\n       << \": \" << Jx << \"\\n\"\n       << setw(20) << \"Jy\"\n       << \": \" << Jy << \"\\n\"\n       << setw(20) << \"rho_x\"\n       << \": \" << rho_x << \"\\n\"\n       << setw(20) << \"rho_y\"\n       << \": \" << rho_y << \"\\n\";\n\n  RidgeletFrame frame(Jx, Jy, rho_x, rho_y);\n  const unsigned int ncols = frame.Nx();  // #cols\n  const unsigned int nrows = frame.Ny();  // #rows\n  // FFT fft;\n  RT_t rt(frame);\n  complex_array_t Fh(nrows, ncols);\n  complex_array_t Fh2(nrows, ncols);\n  /* compute ridgelet transform  */\n  std::vector<rt_coeff_t> rt_coeffs(frame.size());\n  std::vector<rt_coeff_t> rt_coeffs2(frame.size());\n  rt.rt(rt_coeffs, Fh);\n\n  for (unsigned int i = 0; i < frame.size(); ++i) {\n    rt_coeffs[i].setZero();\n  }\n  bool failed = false;\n\n  cout << \"Set single lambda rt coeff to random and check invertibility...\"\n       << \"\\n\";\n  for (unsigned int i = 0; i < frame.size(); ++i) {\n    rt_coeffs[i].setRandom();\n    rt.irt(Fh, rt_coeffs);\n    // forward transform\n    rt.rt(rt_coeffs2, Fh);\n    // inverse transform\n    rt.irt(Fh2, rt_coeffs2);\n    // check that is invertible on half size\n    auto Diff = ftcut(Fh2, nrows / 2, ncols / 2) - ftcut(Fh, nrows / 2, ncols / 2);\n    double diff = Diff.abs().sum();\n    if (diff > 1e-11) {\n      cout << \"::check inverse::\" << frame.lambdas()[i] << \": \" << diff << \"\\n\";\n      failed = true;\n    }\n  }\n\n  if (!failed)\n    cout << \"TEST PASSSED\"\n         << \"\\n\";\n  else\n    cout << \"TEST FAILED\"\n         << \"\\n\";\n\n  return 0;\n}\n", "meta": {"hexsha": "1e7feee7cc0b5455a538f7219c0ba08c2177def0", "size": 3414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/main_test_rt_manual.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "test/main_test_rt_manual.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/main_test_rt_manual.cpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 29.1794871795, "max_line_length": 83, "alphanum_fraction": 0.575278266, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6351778840979879}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2010, Sebastian Schlenkrich\n\n*/\n\n/*! \\file auxilliariesT.hpp\n    \\brief provide template functions for required computations with active data types\n*/\n\n\n#ifndef quantlib_templateauxilliaries_hpp\n#define quantlib_templateauxilliaries_hpp\n\n#include <boost/math/special_functions/erf.hpp>\n#include <ql/experimental/templatemodels/auxilliaries/minimADVariable2T.hpp>\n#include <ql/experimental/templatemodels/auxilliaries/integratorsT.hpp>\n\n\n\nnamespace TemplateAuxilliaries {\n\n    inline double erf(const double x)     { return boost::math::erf(x); }\n    inline double erf_inv(const double x) { return boost::math::erf_inv(x); }\n    inline double DBL(const double x)     { return x; }\n//\tinline double DBL(const ADTAGEO::daglad x) { return x.val(); }\n    inline double DBL(const MinimAD::Variable<QuantLib::Real> x) { return x.value(); }\n\n\n    // transformation (-inf, +inf) -> (a, b)\n    template <typename Type> inline Type direct(const Type x, const Type a, const Type b) {\n        Type y = (x<0.0) ? (-1.0/(x-1.0)) : (-1.0/(x+1.0)+2.0);\n        y = 0.5*(b-a)*y + a;\n        return y;\n    }\n\n    // transformation (a, b) -> (-inf, +inf)\n    template <typename Type> inline Type inverse(const Type y, const Type a, const Type b) {\n        Type x = 2.0*(y-a)/(b-a);\n        x = (x<1.0) ? (-1.0/x+1.0) : (-1.0/(x-2.0)-1.0);\n        return x;\n    }\n\n\n    // square of vector elements\n    template <typename Type> inline\n    std::vector<Type> sqr(std::vector<Type> x) {\n        std::vector<Type> x2(x.size());\n        for (size_t i=0; i<x.size(); ++i) x2[i] = x[i]*x[i];\n        return x2;\n    }\n\n\n    // find index in ascending vector\n    // evaluate n s.t. t[n-1] < t <= t[n]\n    template <typename Type> inline\n    size_t idx(const std::vector<Type>& times, const Type t) {\n        if ((t <= times[0]) | (times.size()<2)) return 0;\n        if (t >  times[times.size()-2 ])        return times.size()-1;\n        // bisection search\n        size_t a = 0, b = times.size()-2;\n        while (b-a>1) {\n            size_t s = (a + b) / 2;\n            if (t <= times[s]) b = s;\n            else                a = s;\n        }\n        return b;\n    }\n\n    // union of two vectors\n    template <typename Type> inline\n    std::vector<Type> unionVector(const std::vector<Type>& v1, const std::vector<Type>& v2) {\n        std::vector<Type> res;\n        std::set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(res));\n        return res;\n    }\n\n    //  normal distribution and Black76 functions\n\n    template <typename Type> inline\n    Type Phi( Type x) {\n        return 0.5*(erf(x*M_SQRT1_2)+1.0);\n    }\n\n    template <typename Type> inline\n    Type phi( Type x) {\n        return M_SQRT1_2 * M_1_SQRTPI * exp(-x*x/2.0);\n    }\n\n    template <typename Type> inline\n    Type PhiInv(const Type x) {\n        return M_SQRT2*erf_inv(2*x-1);\n    }\n\n    template <typename Type> inline\n    Type Black76(Type F,        // forward price\n                 Type K,        // strike\n                 Type sigma,    // Black76 volatility\n                 Type T,        // Time to expiry\n                 int  cop       // call (1) or put (-1) option\n                ) {\n        Type d1 = log(F/K)/sigma/sqrt(T) + sigma*sqrt(T)/2.0;\n        Type d2 = d1 - sigma*sqrt(T);\n        return cop * (F*Phi(cop*d1) - K*Phi(cop*d2));\n    }\n\n    template <typename Type> inline\n    Type Black76Vega(Type F,        // forward price\n                    Type K,        // strike\n                    Type sigma,    // Black76 volatility\n                    Type T,        // Time to expiry\n                    int    cop     // call (1) or put (-1) option\n                    ) {\n        Type d1 = log(F/K)/sigma/sqrt(T) + sigma*sqrt(T)/2.0;\n        return F * exp(-d1*d1/2.0) * sqrt( T / 2.0 / M_PI);\n    }\n\n    template <typename Type> inline\n    Type Bachelier(Type F,        // forward price\n                   Type K,        // strike\n                   Type sigma,    // Normal volatility\n                   Type T,        // Time to expiry\n                   int  cop       // call (1) or put (-1) option\n                ) {\n        Type d = cop*(F-K);\n        Type h = d/sigma/sqrt(T);\n        return d*Phi(h) + phi(h)*sigma*sqrt(T);\n    }\n\n    //  cubic interpolation and integration of expectation\n    \n    //  solve A X = Y by LU decomposition where A = tridiag { a, b, c }\n    template <typename DateType, typename ValueType> inline void\n    solveTridiagLinearSystem ( std::vector<DateType>&   a,  // input: a_1 to a_{dim-1}, output: l_1 to l_{dim-1} of L\n                               std::vector<DateType>&   b,  // input: b_0 to b_{dim-1}, output: u_0 to u_{dim-1} of U\n                               std::vector<DateType>&   c,  // input: c_0 to c_{dim-2}, output: v_0 to v_{dim-2} of U\n                               std::vector<ValueType>&  y,  // input: right hand sides y, output: solutions x\n                               std::vector<ValueType>&  z   // intermediates\n                               ) {\n        size_t dim = b.size();\n        // in place LU decomposition; no error handling if LU decomposition does not exist\n        for (size_t i=1; i<dim; ++i) {\n            a[i] /= b[i-1];\n            b[i] -= c[i-1]*a[i];\n        }\n        // forward substitution\n        z[0] = y[0];\n        for (size_t i=1; i<dim; ++i) z[i] = y[i] - a[i]*z[i-1];\n        // backward substitution, eliminate input\n        y[dim-1] = z[dim-1]/b[dim-1];\n        //for (long i=dim-2; i>=0; --i) y[i] = (z[i] - c[i]*y[i+1])/b[i];\n        for (size_t i=dim-1; i>0; --i) y[i-1] = (z[i-1] - c[i-1]*y[i])/b[i-1];\n    }\n\n    //  (Log) Cubic interpolation requires precomputed derivatives g[i] = y'[i]\n    template <typename DateType, typename ValueType> inline\n    void c2splineDerivatives( std::vector<DateType>&  x,  // input parameter, strictly increasing grid point \n                              std::vector<ValueType>& y,  // input parameter, function values at x[i] \n                              std::vector<ValueType>&       g,  // output parameter, derivatives at x[i] \n                              std::vector<ValueType>&       z,  // intermediates\n                              int       logInterpolation  = 0,  // (1) interpolate log(y[i]), (0) standard   \n                              int       boundaryCondition = 1   // (0) g[0] = g[dim-1] = 0,\n                                                                // (1) g[0], g[dim-1] by secants   \n                        ) {\n        ValueType dy1, dy2;\n        size_t i, dim = std::min(x.size(),y.size()); \n        std::vector<DateType> a(dim), b(dim), c(dim);\n        // constant extrapolation\n        if (dim==1) {\n            g[0] = 0.0;\n        }\n        // see Wikipedia 'spline interpolation'\n        for (i=1; i<dim-1; ++i) {\n            a[i] = x[i+1] - x[i];\n            b[i] = 2.0*(x[i+1] - x[i-1]);\n            c[i] = x[i] - x[i-1];\n            dy1  = (logInterpolation) ? log(y[i]/y[i-1]) : y[i] - y[i-1];\n            dy2  = (logInterpolation) ? log(y[i+1]/y[i]) : y[i+1] - y[i];\n            g[i] = 3.0*(a[i]/c[i]*dy1 + c[i]/a[i]*dy2);\n            dy1 = 0.0; dy2 = 0.0; // elimination\n        }\n        // boundary conditions\n        a[0] = 0.0; c[0] = 0.0; g[0] = 0.0; a[dim-1] = 0.0; c[dim-1] = 0.0; g[dim-1] = 0.0;\n        b[0] = 1.0; b[dim-1] = 1.0;\n        if (boundaryCondition && (dim>1)) { // fix boundaries\n            g[0] =  (logInterpolation) ? log(y[1]/y[0]) : (y[1]-y[0]);\n            g[0] /= (x[1]-x[0]);\n            g[dim-1] =  (logInterpolation) ? log(y[dim-1]/y[dim-2]) : (y[dim-1]-y[dim-2]);\n            g[dim-1] /= (x[dim-1]-x[dim-2]);\n        }\n        // solve tridiag [ a, b, c ] x = g and x -> g\n        solveTridiagLinearSystem( a, b, c, g, z );\n    }\n\n    template <typename DateType, typename ValueType> inline\n    ValueType interpolCSpline ( DateType                      xi,\n                                std::vector<DateType>&  x,\n                                std::vector<ValueType>& y,\n                                std::vector<ValueType>& g,\n                                int    logInterpolation = 0) {\n        size_t prevIdx, nextIdx, idx;\n        size_t dim = std::min(x.size(),y.size());\n        dim = std::min(dim,g.size());\n        ValueType h, u, v, p, q, yPrev, yNext, res;\n        // linear extrapolation\n        if (xi<=x[0]) {\n            res = (logInterpolation) ? log(y[0]) : y[0];\n            res += g[0]*(xi-x[0]);\n            res = (logInterpolation) ? exp(res) : res;\n            return res;\n        }\n        if (xi>=x[dim-1]) {\n            res = (logInterpolation) ? log(y[dim-1]) : y[dim-1];\n            res += g[dim-1]*(xi-x[dim-1]);\n            res = (logInterpolation) ? exp(res) : res;\n            return res;\n        }\n        // find prevIdx and nextIdx s.t. x[prevIdx] < xi <= x[nextIdx]\n        prevIdx = 0;\n        nextIdx = dim-1;\n        while (nextIdx>prevIdx+1) {\n            idx = (prevIdx + nextIdx)/2;\n            if (xi<=x[idx]) nextIdx = idx;\n            else            prevIdx = idx;\n        }\n        // auxilliary variables\n        h = x[nextIdx] - x[prevIdx];\n        u = (xi - x[prevIdx])/h;\n        v = 1.0 - u;\n        yPrev = (logInterpolation) ? log(y[prevIdx]) : y[prevIdx];\n        yNext = (logInterpolation) ? log(y[nextIdx]) : y[nextIdx];\n        p = 3.0*yNext - h*g[nextIdx];\n        q = 3.0*yPrev + h*g[prevIdx];\n        // final interpolation\n        res = yNext*u*u*u + p*u*u*v + q*u*v*v + yPrev*v*v*v;\n        res = (logInterpolation) ? exp(res) : res;\n        return res;\n    }\n\n\n    // integration x_0, ..., x_N plus extrapolation via Bachelier formula\n    template <typename PassiveType, typename ActiveType> inline\n    ActiveType normalExpectation(\n                std::vector<PassiveType>&   x,    //  grid points of payoff\n                std::vector<ActiveType>&    v,    //  payoff\n                std::vector<ActiveType>&    g,  //  derivatives of payoff for interpolation\n                ActiveType                  mu,   //  expectation of normal distribution\n                ActiveType                  var,  //  variance sigma^2 of normal distribution\n                std::string                 method=\"\" //  integration method  \n                  ) {\n        ActiveType res=0.0;\n        if (x.size()==0) return res;\n\n        // low rate extrapolation\n        ActiveType Q0 = Phi((x[0]-mu)/sqrt(var));\n        res = v[0]*Q0;\n        if (x.size()==1) return res;  \n        res -= (v[1]-v[0])/(x[1]-x[0])*Bachelier(mu,(ActiveType)x[0],sqrt(var),(ActiveType)(1.0),-1);\n        //res -= g[0]*Bachelier(mu,(ActiveType)x[0],sqrt(var),(ActiveType)(1.0),-1);\n\n        // high rate extrapolation\n        ActiveType QN = Phi((x[x.size()-1]-mu)/sqrt(var));\n        res += v[v.size()-1]*(1.0-QN);\n        res += (v[v.size()-1]-v[v.size()-2])/(x[x.size()-1]-x[x.size()-2])*Bachelier(mu,(ActiveType)x[x.size()-1],sqrt(var),(ActiveType)(1.0),+1);\n        //res += g[x.size()-1]*Bachelier(mu,(ActiveType)x[x.size()-1],sqrt(var),(ActiveType)(1.0),+1);\n\n        // switch methods...\n\n        // default intervall integrations\n        // boundaries\n        res += v[v.size()-1]*QN - v[0]*Q0;\n        // replication via Put-Spreads\n        ActiveType B1, B2 = Bachelier(mu,(ActiveType)x[0],sqrt(var),(ActiveType)(1.0),-1);\n        for (size_t i=0; i<x.size()-1; ++i) {\n            B1  = B2;\n            B2  = Bachelier(mu,(ActiveType)x[i+1],sqrt(var),(ActiveType)(1.0),-1);\n            res -= (v[i+1] - v[i]) / (x[i+1] - x[i]) * (B2 - B1);\n            //res -= 0.5 * (g[i] + g[i+1]) * (B2 - B1);\n        }\n        return res;\n    }\n\n\n    template <typename PassiveType, typename ActiveType> inline\n    ActiveType normalExpectation(\n                std::vector<PassiveType>&   x,  //  grid points of payoff\n                std::vector<ActiveType>&    v,  //  payoff\n                std::vector<ActiveType>&    g,  //  derivatives of payoff for interpolation\n                ActiveType                       mu,  //  expectation of normal distribution\n                ActiveType                      var,  //  variance sigma^2 of normal distribution\n                PassiveType                     tol   //  tolerance for accuracy\n                  ) {\n\n        if ((std::min(x.size(),v.size())<2)||(x.size()!=v.size())) return 0;\n        if ((g.size()<2)||(g.size()!=x.size())) return 0;\n        if (tol<=0) return normalExpectation( x, v, g, mu, var );\n        PassiveType x0, x1, x2, h, err, tmp, lambda, sum1;\n        ActiveType  v0, v1, v2;\n        ActiveType  y0, y1, y2, sum2, res;\n        std::vector<ActiveType> sums(x.size());\n        sums.push_back((ActiveType)0.0);\n        for (int i=0; i<2; ++i) {\n            x0 = DBL(mu);\n            v0 = interpolCSpline(x0,x,v,g);\n            y0 = v0 * exp(-(x0-mu)*(x0-mu)/2.0/var);\n            //h = (1-2*i)*tol; // first stupid guess\n            h = (1-2*i)*x[x.size()-1]/x.size()*2;\n            x2 = x0 + h;\n            v2 = interpolCSpline(x2,x,v,g);\n            y2 = v2 * exp(-(x2-mu)*(x2-mu)/2.0/var);\t\t\t\t      \n            // integrate mu to +infty\n            tmp = Phi(DBL((x0-mu)/sqrt(var)));\n            tmp = (tmp<0.5) ? tmp : (1.0-tmp);\n            while ((tmp>tol*tol)||(fabs(DBL(v0))*tmp>tol*tol)) {\n                x1 = x0 + 0.5*h;\n                v1 = interpolCSpline(x1,x,v,g);\n                y1 = v1 * exp(-(x1-mu)*(x1-mu)/2.0/var);\t\t\t\t      \n                sum1 = DBL(y0 + y2)*h/2.0;           // order-3\n                sum2 = (y0 + 4.0*y1 + y2)*h/6.0;  // order-5\n                err = fabs((sum1-DBL(sum2))/h);\n                if (err>tol) {  // reject the step\n                    h *= 0.5;\n                    x2 = x1;\n                    v2 = v1;\n                    y2 = y1;\n                    continue;  // try again with half the step size\n                }\n                //res += (1-2*i)*sum2;  // use the more accurate estimate\n                sums.push_back(sums.back() + (1-2*i)*sum2);\n                x0 = x2;\n                v0 = v2;\n                y0 = y2;\t\n                lambda = sqrt(tol/(err+1.0e-32));\n                lambda = (lambda>2.0) ? 2.0 : lambda; // cap step size increase\n                lambda = ((lambda>1.0)&(lambda<1.3)) ? 1.0 : lambda; // avoid step size oscillation\n                h *= lambda;\n                x2 = x0 + h;\n                v2 = interpolCSpline(x2,x,v,g);\n                y2 = v2 * exp(-(x2-mu)*(x2-mu)/2.0/var);\t\t\t\t      \n                tmp = Phi(DBL((x0-mu)/sqrt(var)));\n                tmp = (tmp<0.5) ? tmp : (1.0-tmp);\n            }\n        }\n        // don't forget the scaling factor...\n        res = sums.back() / sqrt(2.0 * M_PI * var);\n        // reverse elimination\n        for (size_t i=sums.size(); i>0; --i) sums[i-1] = 0.0;\n        return res;\n    }\n\n}\n\n#endif  /* quantlib_templateauxilliaries_hpp */\n", "meta": {"hexsha": "ec8d1d421ffa146fa51f7a8ee3d0450c72c24648", "size": 14893, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/auxilliaries/auxilliariesT.hpp", "max_stars_repo_name": "urgu00/QuantLib", "max_stars_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/experimental/templatemodels/auxilliaries/auxilliariesT.hpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T07:24:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:29:06.000Z", "max_forks_repo_path": "ql/experimental/templatemodels/auxilliaries/auxilliariesT.hpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-24T08:28:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T08:59:54.000Z", "avg_line_length": 41.9521126761, "max_line_length": 146, "alphanum_fraction": 0.4800241724, "num_tokens": 4459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.63517788402849}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <ipc/utils/eigen_ext.hpp>\n\nnamespace ipc {\n\n/// @brief Compute the distance between a two infinite lines in 3D.\n/// @note The distance is actually squared distance.\n/// @warning If the lines are parallel this function returns a distance of zero.\n/// @param ea0 The first vertex of the edge defining the first line.\n/// @param ea1 The second vertex of the edge defining the first line.\n/// @param ea0 The first vertex of the edge defining the second line.\n/// @param ea1 The second vertex of the edge defining the second line.\n/// @return The distance between the two lines.\ntemplate <\n    typename DerivedEA0,\n    typename DerivedEA1,\n    typename DerivedEB0,\n    typename DerivedEB1>\nauto line_line_distance(\n    const Eigen::MatrixBase<DerivedEA0>& ea0,\n    const Eigen::MatrixBase<DerivedEA1>& ea1,\n    const Eigen::MatrixBase<DerivedEB0>& eb0,\n    const Eigen::MatrixBase<DerivedEB1>& eb1)\n{\n    assert(ea0.size() == 3);\n    assert(ea1.size() == 3);\n    assert(eb0.size() == 3);\n    assert(eb1.size() == 3);\n\n    const auto normal = cross(ea1 - ea0, eb1 - eb0);\n    const auto line_to_line = (eb0 - ea0).dot(normal);\n    return line_to_line * line_to_line / normal.squaredNorm();\n}\n\n// Symbolically generated derivatives;\nnamespace autogen {\n    void line_line_distance_gradient(\n        double v01,\n        double v02,\n        double v03,\n        double v11,\n        double v12,\n        double v13,\n        double v21,\n        double v22,\n        double v23,\n        double v31,\n        double v32,\n        double v33,\n        double g[12]);\n\n    void line_line_distance_hessian(\n        double v01,\n        double v02,\n        double v03,\n        double v11,\n        double v12,\n        double v13,\n        double v21,\n        double v22,\n        double v23,\n        double v31,\n        double v32,\n        double v33,\n        double H[144]);\n} // namespace autogen\n\n/// @brief Compute the gradient of the distance between a two lines in 3D.\n/// @note The distance is actually squared distance.\n/// @warning If the lines are parallel this function returns a distance of zero.\n/// @param[in] ea0 The first vertex of the edge defining the first line.\n/// @param[in] ea1 The second vertex of the edge defining the first line.\n/// @param[in] ea0 The first vertex of the edge defining the second line.\n/// @param[in] ea1 The second vertex of the edge defining the second line.\n/// @param[out] hess The gradient of the distance wrt ea0, ea1, eb0, and eb1.\ntemplate <\n    typename DerivedEA0,\n    typename DerivedEA1,\n    typename DerivedEB0,\n    typename DerivedEB1,\n    typename DerivedGrad>\nvoid line_line_distance_gradient(\n    const Eigen::MatrixBase<DerivedEA0>& ea0,\n    const Eigen::MatrixBase<DerivedEA1>& ea1,\n    const Eigen::MatrixBase<DerivedEB0>& eb0,\n    const Eigen::MatrixBase<DerivedEB1>& eb1,\n    Eigen::PlainObjectBase<DerivedGrad>& grad)\n{\n    assert(ea0.size() == 3);\n    assert(ea1.size() == 3);\n    assert(eb0.size() == 3);\n    assert(eb1.size() == 3);\n\n    grad.resize(ea0.size() + ea1.size() + eb0.size() + eb1.size());\n    autogen::line_line_distance_gradient(\n        ea0[0], ea0[1], ea0[2], ea1[0], ea1[1], ea1[2], eb0[0], eb0[1], eb0[2],\n        eb1[0], eb1[1], eb1[2], grad.data());\n}\n\n/// @brief Compute the hessian of the distance between a two lines in 3D.\n/// @note The distance is actually squared distance.\n/// @warning If the lines are parallel this function returns a distance of zero.\n/// @param[in] ea0 The first vertex of the edge defining the first line.\n/// @param[in] ea1 The second vertex of the edge defining the first line.\n/// @param[in] ea0 The first vertex of the edge defining the second line.\n/// @param[in] ea1 The second vertex of the edge defining the second line.\n/// @param[out] hess The hessian of the distance wrt ea0, ea1, eb0, and eb1.\ntemplate <\n    typename DerivedEA0,\n    typename DerivedEA1,\n    typename DerivedEB0,\n    typename DerivedEB1,\n    typename DerivedHess>\nvoid line_line_distance_hessian(\n    const Eigen::MatrixBase<DerivedEA0>& ea0,\n    const Eigen::MatrixBase<DerivedEA1>& ea1,\n    const Eigen::MatrixBase<DerivedEB0>& eb0,\n    const Eigen::MatrixBase<DerivedEB1>& eb1,\n    Eigen::PlainObjectBase<DerivedHess>& hess)\n{\n    assert(ea0.size() == 3);\n    assert(ea1.size() == 3);\n    assert(eb0.size() == 3);\n    assert(eb1.size() == 3);\n\n    hess.resize(\n        ea0.size() + ea1.size() + eb0.size() + eb1.size(),\n        ea0.size() + ea1.size() + eb0.size() + eb1.size());\n    autogen::line_line_distance_hessian(\n        ea0[0], ea0[1], ea0[2], ea1[0], ea1[1], ea1[2], eb0[0], eb0[1], eb0[2],\n        eb1[0], eb1[1], eb1[2], hess.data());\n}\n\n} // namespace ipc\n", "meta": {"hexsha": "98aaf28dbc2abd5cd63af44fd59de78a71d1e1c0", "size": 4714, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/distance/line_line.hpp", "max_stars_repo_name": "ipc-sim/ipc-toolk", "max_stars_repo_head_hexsha": "81873d0288810e30166d871419da4104329860e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T21:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:24:31.000Z", "max_issues_repo_path": "src/distance/line_line.hpp", "max_issues_repo_name": "dbelgrod/ipc-toolkit", "max_issues_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T18:39:30.000Z", "max_forks_repo_path": "src/distance/line_line.hpp", "max_forks_repo_name": "dbelgrod/ipc-toolkit", "max_forks_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T12:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T04:55:49.000Z", "avg_line_length": 33.9136690647, "max_line_length": 80, "alphanum_fraction": 0.6576156131, "num_tokens": 1306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6351765288206753}}
{"text": "/* Copyright (c) 2018, Skolkovo Institute of Science and Technology (Skoltech)\n * All rights reserved.\n *\n * See LICENSE file in the root of the mrob library.\n *\n *\n * example_SE3.cpp\n *\n *  Created on: Feb 12, 2018\n *      Author: Gonzalo Ferrer\n *              g.ferrer@skoltech.ru\n *              Mobile Robotics Lab, Skoltech\n */\n\n\n#include <iostream>\n#include <Eigen/LU> // for inverse and determinant\n#include <cmath>\n#include \"mrob/SE3.hpp\"\n#include \"mrob/SO3.hpp\"\n\n\nint main()\n{\n\n\n    // TODO please write me as a test unit!!!\n    // SO3 tests\n    // ========================================================\n\n    // Testing the Identity element\n    {\n    mrob::SO3 R;\n    R.print();\n    std::cout << \"Identity element error= \" << R.ln_vee().norm() << std::endl;\n    }\n\n    // Testing the Identity element plus epsilon\n    {\n    Mat31 w;\n    w << 1e-15, 0, 0;\n    mrob::SO3 R = mrob::SO3(w);\n    std::cout << \"Identity element error epsilon = \" << R.ln_vee().norm() << std::endl;\n    }\n\n    // Testing Regular\n    {\n    Mat31 w;\n    w << 1.2, -0.3, 0.2;\n    mrob::SO3 R = mrob::SO3(w);\n    std::cout << \"Exponent and Log test \" << (R.ln_vee() - w).norm() << std::endl;\n    }\n\n    //testing bool function isSO3\n    {\n    Mat31 w;\n    w << 1.2, -0.3, 0.2;\n    mrob::SO3 R(w);\n    std::cout << \"Matris is SO3: \" << mrob::isSO3(R.R()) << std::endl;\n    Mat3 notR = Mat3::Random();\n    std::cout << \"Matris is SO3: \" << mrob::isSO3(notR) << std::endl;\n    }\n\n    // Testing Pi\n    {\n    Mat31 w;\n    w << M_PI, 0.0, 0.0;\n    mrob::SO3 R = mrob::SO3(w);\n    //R.print();\n    std::cout << \"Pi rotation 1 component = \" << (R.ln_vee() - w).norm() << std::endl;\n    }\n\n    {\n    Mat31 w;\n    w << M_PI*std::sqrt(1.0/3), M_PI*std::sqrt(1.0/3), M_PI*std::sqrt(1.0/3);\n    mrob::SO3 R = mrob::SO3(w);\n    std::cout << \"Pi rotation 3 components= \" <<  (R.ln_vee() - w).norm() << std::endl;\n    }\n\n    // testing operators}\n    {\n    std::cout << \"\\ntesting operators\\n\";\n    Mat31 w;\n    w << M_PI, 0.0, 0.0;\n    mrob::SO3 R = mrob::SO3(w);\n    R.print();\n    Mat3 w_hat = R.ln();\n    std::cout << w_hat << std::endl;\n\n    std::cout << \"testing inverse\"  << std::endl;\n    mrob::SO3 Rt = R.inv();\n    std::cout << \"invers = \" << Rt.R()  << std::endl;\n    }\n\n\n    // SE3 tests\n    // ========================================================\n    // testing the constructor\n    std::cout << \"\\n\\nSE3 tests\"  << std::endl;\n    {\n    mrob::SE3 T;\n    //T.print();\n    std::cout << \"Identity element error= \" << T.ln_vee().norm() << std::endl;\n    }\n    {\n    Mat61 xi;\n    xi << 1e-9,0,0, 20, 100, 4;\n    mrob::SE3 T(xi);\n    T.print();\n    std::cout << \"random element plus epsilon= \" << (T.ln_vee() - xi).norm() << std::endl;\n    }\n    {\n    Mat61 xi;\n    xi << 1,0,-0.2, 5, 10, 2;\n    mrob::SE3 T(xi);\n    //T.print();\n    std::cout << \"Some normal element error = \" << (T.ln_vee() - xi).norm() << std::endl;\n    }\n\n    //testing bool function isSE3\n    {\n    Mat61 xi;\n    xi << 1,0,-0.2, 5, 10, 2;\n    mrob::SE3 T(xi);\n    std::cout << \"input SE3 and Matris is SE3?: \" << mrob::isSE3(T.T()) << std::endl;\n    Mat4 notT = Mat4::Random();\n    std::cout << \"Random Matris is SE3: \" << mrob::isSE3(notT) << std::endl;\n    }\n    {\n    Mat61 xi;\n    xi << M_PI,0,0, 5, 100, 2;\n    mrob::SE3 T(xi);\n    T.print_lie();\n    std::cout << \"Pi error plus trans= \" << (T.ln_vee()-xi).norm() << std::endl;\n    }\n    {\n    Mat61 xi;\n    xi << M_PI*std::sqrt(1.0/3)-1e-4, M_PI*std::sqrt(1.0/3), M_PI*std::sqrt(1.0/3), 5, 1000, 200;\n    mrob::SE3 T(xi);\n    T.print_lie();\n    std::cout << \"Pi error 3 comp plus trans= \" << (T.ln_vee()-xi).norm() << std::endl;\n    // The error ind\n    }\n    mrob::SE3 T1;\n    T1.print();\n    T1.print_lie();\n    Mat61 xi;\n    xi << 1,0,-0.2, 5, 10, 2;\n    mrob::SE3 T(xi);\n    T.print();\n    xi << T.ln_vee();\n    mrob::SE3 T2(xi);\n    T2.print();\n    std::cout << \"Matrix distance = \" << (T.T()-T2.T()).norm() << std::endl;\n\n    std::cout << \"testing update\\n\";\n    T2.update_lhs(xi);\n    T2.print();\n    Mat41 v;\n    v << 1.0, 3.2, -1.2, 1.0;\n    std::cout << T2.T()*v << std::endl;\n    v = T2.T()*v;\n    std::cout << v << std::endl;\n\n    std::cout << \"testing inverse\"  << std::endl;\n    mrob::SE3 Tt = T2.inv();\n    std::cout << \"invers = \" << Tt.T()  << std::endl;\n    std::cout << \"Matrix distance = \" << (Tt.T()-T2.T().inverse()).norm() << std::endl;\n    Mat61 xi2 = -T2.ln_vee();\n    mrob::SE3 T22( xi2);\n    std::cout << \"Matrix distance by negating= \" << (T22.T()-T2.T().inverse()).norm() << std::endl;\n\n    std::cout << \"testing adjoint\"  << std::endl;\n    std::cout << \"Adjoint= \" << Tt.adj()  << std::endl;\n\n\n    // testing subblock matrices\n    std::cout << \"Subblock methods an matrix:\"  << std::endl;\n    T.print();\n    std::cout << \"\\nT = \" << T.T()  << std::endl;\n    std::cout << \"\\nR = \" << T.R()  << std::endl;\n    std::cout << \"\\nt = \" << T.t()  << std::endl;\n\n    // Acess inner matrix\n    T.ref2T() << 1, 0, 0, 0,\n             0, 1, 0, 0,\n             0, 0, 5, 0,\n             0, 0, 0 , 1;\n    T.print();\n\n\n    // testing transformation\n    {\n    Mat61 xi;\n    xi << 1,0,-0.2, 5, 10, 2;\n    mrob::SE3 T(xi);\n    Mat31 p,p2;\n    p << 2,3,-1;\n    p2 = p;\n    p = T.transform(p);\n    p = T.inv().transform(p);\n    std::cout << \"Testing transformations = \" << (p-p2).norm() << std::endl;\n    }\n    //testing SE3 multiplications\n\n\n\n}\n", "meta": {"hexsha": "b4edcf8b72155fb158c3c3651933f2386ab98c14", "size": 5363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/examples/example_SE3.cpp", "max_stars_repo_name": "anastasiia-kornilova/mrob", "max_stars_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-10T09:36:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-10T09:36:50.000Z", "max_issues_repo_path": "src/geometry/examples/example_SE3.cpp", "max_issues_repo_name": "anastasiia-kornilova/mrob", "max_issues_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/examples/example_SE3.cpp", "max_forks_repo_name": "anastasiia-kornilova/mrob", "max_forks_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6602870813, "max_line_length": 99, "alphanum_fraction": 0.4866679098, "num_tokens": 1951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6351632656293538}}
{"text": "/*\n\nDefines the functions of the Frame\n\nAuthor  : Subramanian Krishnan\nDate    : 30 Sep 2020\n\nChangelog:\n    subbu - 9/30  - Initial commit\n    subbu - 10/27 - update members+methods\n*/\n\n#include <iostream>\n#include <Eigen/Core>\n#include <opencv2/core/eigen.hpp>\n\n// Custom headers\n#include \"frame.h\"\n#include \"utils.h\"\n#include \"optim.h\"\n\nvoid FramePair::SampleIndices(const Eigen::MatrixXi& lines, std::vector<points2d>& sampled_lines_2d){\n    /*\n    Input: lines matrix expected to be of form nx4 with each entry being [x1,y1,x2,y2] \n           where x_i, y_i denote the end points of the lines\n    \n    Output: Sampled points of the form (2n)x(n_samples) vector.\n    note: different lines have different n_samples based on line length\n    */\n   \n    const int max_samples = 100;\n\n    // Iterating through row elements is possible in eigen 3.4\n    for(int i = 0; i < lines.rows(); i++ ){        \n        Eigen::Vector2i p1(lines(i,0), lines(i,1)), p2(lines(i,2), lines(i,3));\n        float dist = (p1-p2).norm();\n        float n_samples = std::min(max_samples, int(dist));\n        u_int point_index = 0;\n\n        // ref: https://stackoverflow.com/questions/28018147/emgucv-get-coordinates-of-pixels-in-a-line-between-two-points\n        int x0 = lines(i,0), y0 = lines(i,1), x1 = lines(i,2), y1 = lines(i,3);\n        int dx = std::abs(x1- x0), dy = std::abs(y1-y0);\n        int sx = x0 < x1 ? 1 : -1;\n        int sy = y0 < y1 ? 1 : -1;\n        int err = dx - dy;\n\n        // For each line store the index points (need to be 'int')\n        Eigen::Matrix<int, 2, max_samples> line_points;\n\n        if (n_samples < max_samples){\n            // Bresenham's algorithm\n            while(true){\n                line_points(0, point_index) = x0;\n                line_points(1, point_index) = y0;\n                point_index++;\n\n                if(x0 == x1 && y0 == y1) break;\n                int e2 = 2*err;\n                if(e2 > -dy){\n                    err = err - dy;\n                    x0 = x0 + sx;\n                }\n                if(e2 < dx){\n                    err = err + dx;\n                    y0 = y0 + sy;\n                }\n            }\n\n        }\n        else{\n         for (int i=1; i<=max_samples; ++i){\n            line_points(0, point_index) = x0 + (x1 - x0)*(i-1)/(max_samples-1);\n            line_points(1, point_index) = y0 + (y1 - y0)*(i-1)/(max_samples-1);\n            point_index++;\n         }\n        }\n        // Add the x and y indices to class variable\n        sampled_lines_2d.push_back(line_points.leftCols(point_index));\n    }\n}\n\nEigen::Matrix3d FramePair::Cov3D(double u, double v, double depth){\n    // depth noise co-efficients for the kinect [ref: Lu, Song 2015]\n    const double c1 = 0.00273, c2 = 0.00074, c3 = -0.00058;\n    // Our estiamte of how accurate the 2D point sampled on a line is (Not sure if this needs to be changed. May require tuning)\n    const double sigma_g = 1;\n    double sigma_d = c1*depth*depth + c2*depth + c3;\n\n    Eigen::Matrix3d cov2d = (Eigen::Matrix<double,3,3>()<< \n                             sigma_g*sigma_g, 0,               0,\n                             0,               sigma_g*sigma_g, 0,\n                             0,               0,               sigma_d*sigma_d).finished();\n\n    Eigen::Matrix3d J = (Eigen::Matrix<double,3,3>()<< \n                         depth/K(0,0), 0,            (u - K(0,2))/K(0,0),\n                         0,            depth/K(1,1), (v - K(1,2))/K(1,1),\n                         0,            0,            1).finished();\n\n    Eigen::Matrix3d cov3d = J*cov2d*(J.transpose());\n\n    return cov3d;\n}\n\nvoid FramePair::Reproject(){\n    \n    std::size_t num_lines = sampled_lines_2d_im1.size();\n    int l1_num_points, l2_num_points;\n\n    for(int i=0; i < num_lines; ++i){\n        std::vector<Eigen::Matrix3d> l1_cov, l1_eig_vec, l2_cov, l2_eig_vec, l1_inv_cov, l2_inv_cov; \n        std::vector<Eigen::Vector3d> l1_eig_val, l2_eig_val;\n\n        Eigen::Matrix3Xd P1(3, sampled_lines_2d_im1[i].cols()), P2(3, sampled_lines_2d_im2[i].cols());\n        l1_num_points = reprojectSingleLine(depth_image1, sampled_lines_2d_im1[i], P1, l1_cov, l1_eig_val, l1_eig_vec, l1_inv_cov);\n        l2_num_points = reprojectSingleLine(depth_image2, sampled_lines_2d_im2[i], P2, l2_cov, l2_eig_val, l2_eig_vec, l2_inv_cov);\n\n        if(l1_num_points and l2_num_points){\n            // Update line 1 details\n            points_3d_im1.push_back(P1.leftCols(l1_num_points));\n            cov_G_im1.push_back(l1_cov);\n            cov_eig_values_im1.push_back(l1_eig_val);\n            cov_eig_vectors_im1.push_back(l1_eig_vec);\n            im1_data.cov_matrices.push_back(l1_inv_cov);\n            \n            // Update line 2 details\n            points_3d_im2.push_back(P2.leftCols(l2_num_points));\n            cov_G_im2.push_back(l2_cov);\n            cov_eig_values_im2.push_back(l2_eig_val);\n            cov_eig_vectors_im2.push_back(l2_eig_vec);\n            im2_data.cov_matrices.push_back(l2_inv_cov);\n        }\n    }\n}\n\nint FramePair::reprojectSingleLine(const cv::Mat& depth_image, const points2d& current_line, points3d& P, std::vector<Eigen::Matrix3d>& line_covariance,\n                                   std::vector<Eigen::Vector3d>& eigen_values, std::vector<Eigen::Matrix3d>& eigen_vectors,\n                                   std::vector<Eigen::Matrix3d>& inv_cov_one_line){\n    int index = 0;\n    for(int i=0; i<current_line.cols(); ++i){\n        \n        // rerpoject to 3D using depth value\n        int u = current_line(0,i), v = current_line(1,i);\n        float depth = depth_image.at<uint16_t>(v, u)/5000.0;\n        if(depth == 0) continue;\n        P(0,index) = (u - K(0,2))*depth/K(0,0);\n        P(1,index) = (v - K(1,2))*depth/K(1,1);\n        P(2,index) = depth;\n        index++;\n        \n        // Propogate 2D covariance to 3D\n        Eigen::Matrix3d covariance_3d = Cov3D(u, v, depth);\n\n        // Generate Eigen values of cov for ransac later\n        Eigen::SelfAdjointEigenSolver<covariance> eigensolver(covariance_3d);\n        if (eigensolver.info() != Eigen::Success){\n            cout << \"Could not perform eigen decomposition on 3D point's covariance matrix\" << endl;\n            cout << covariance_3d << endl;\n            abort();\n        }\n        \n        Eigen::Matrix3d U = eigensolver.eigenvectors();\n        Eigen::Vector3d D = eigensolver.eigenvalues();\n        Eigen::Matrix3d CovInvRoot = ((D.array().inverse()).sqrt()).matrix().asDiagonal() * U.transpose();\n\n        line_covariance.push_back(covariance_3d);\n        eigen_values.push_back(D);\n        eigen_vectors.push_back(U);\n        inv_cov_one_line.push_back(CovInvRoot);\n    }\n    \n    return index >= 5 ? index : 0;\n}\n\nFramePair::FramePair(const cv::Mat& rgb_image1, cv::Mat& depth_image1, cv::Mat& rgb_image2, cv::Mat& depth_image2) :    rgb_image1(rgb_image1), \n                                                                                                                        depth_image1(depth_image1),\n                                                                                                                        rgb_image2(rgb_image2), \n                                                                                                                        depth_image2(depth_image2) {\n    // Make the intrinsic matrix [Got from dataset information]\n    K = (Eigen::Matrix<double, 3, 3>() << 517.306408, 0.000000, 318.643040, \n                                            0.000000, 516.469215, 255.313989,\n                                            0.000000, 0.000000, 1.000000).finished();\n\n    // populate distortion\n    dist = {0.262383, -0.953104, -0.005358, 0.002628, 1.163314};\n\n    // populate image dimensions\n    im_wd = rgb_image1.cols; im_ht = rgb_image1.rows;\n\n    // Make ransac object for culling outliers later\n    pointRefine = new Ransac(10, 1);\n\n    // Function returing lines in both images and matches between them contained in a structure element\n    pstruct = image_process(rgb_image1, rgb_image2);\n\n    img1_lines.resize(int(pstruct.matches.size()/2),4);\n    img2_lines.resize(int(pstruct.matches.size()/2),4);\n\n    int lineIDLeft;\n    int lineIDRight;\n    for (unsigned int pair = 0; pair < pstruct.matches.size() / 2; pair++)\n    {\n        lineIDLeft = pstruct.matches[2 * pair];\n        lineIDRight = pstruct.matches[2 * pair + 1];\n        Eigen::Vector4i r1(int(pstruct.linesInLeft[lineIDLeft][0].startPointX), int(pstruct.linesInLeft[lineIDLeft][0].startPointY), \n                            int(pstruct.linesInLeft[lineIDLeft][0].endPointX), int(pstruct.linesInLeft[lineIDLeft][0].endPointY));\n        Eigen::Vector4i r2(int(pstruct.linesInRight[lineIDRight][0].startPointX), int(pstruct.linesInRight[lineIDRight][0].startPointY), \n                            int(pstruct.linesInRight[lineIDRight][0].endPointX), int(pstruct.linesInRight[lineIDRight][0].endPointY));\n        img1_lines.row(pair) = r1;\n        img2_lines.row(pair) = r2;\n\n        /*\n        // ---------Following code allows to visualize individual matches between the two images-------------\n        cv::Point startPoint = cv::Point(int(pstruct.linesInLeft[lineIDLeft][0].startPointX), int(pstruct.linesInLeft[lineIDLeft][0].startPointY));\n        cv::Point endPoint = cv::Point(int(pstruct.linesInLeft[lineIDLeft][0].endPointX), int(pstruct.linesInLeft[lineIDLeft][0].endPointY));\n        cv::line(rgb_image1, startPoint, endPoint, CV_RGB(255,0,0), 1, cv::LINE_AA, 0);\n        startPoint = cv::Point(int(pstruct.linesInRight[lineIDRight][0].startPointX), int(pstruct.linesInRight[lineIDRight][0].startPointY));\n        endPoint = cv::Point(int(pstruct.linesInRight[lineIDRight][0].endPointX), int(pstruct.linesInRight[lineIDRight][0].endPointY));\n        cv::line(rgb_image2, startPoint, endPoint, CV_RGB(255,0,0), 1, cv::LINE_AA, 0);\n        utils::DisplayDualImage(rgb_image1, rgb_image2);\n        cv::waitKey(0);\n        */\n\n    }\n    // std::cout << \"Im1 line \" << img1_lines.rows() << \" \" << img1_lines.cols() << std::endl;\n    // std::cout << \"Im2 line \" << img2_lines.rows() << \" \" << img2_lines.cols() << std::endl;\n    // sample lines in image\n    SampleIndices(img1_lines, sampled_lines_2d_im1);\n    SampleIndices(img2_lines, sampled_lines_2d_im2);\n\n    // Reproject left and right image points to 3D\n    Reproject();\n\n    // optim::nonlinOptimize(points_3d_im1[0], im1_data.cov_matrices[0], 0, im1_data.cov_matrices[0].size()-1);\n\n    // TODO: CHECK REPROJECT FUNCTION\n    // TODO: ASSIGN STRUCT ELEMENTS HERE (HAVE TO OBTAIN IDX1 AND IDX2)\n\n    // cull outlier points\n    // std::cout << \"C1\" << std::endl;\n    for(int i=0; i < points_3d_im1.size(); ++i){\n        std::vector<Eigen::Matrix3d> updated_covariance;\n        std::vector<Eigen::Matrix3d> updated_inv_root_covariance;\n        \n        // point update\n        rsac_points_3d_im1.push_back(pointRefine->removeOutlierPoints(points_3d_im1[i], cov_eig_values_im1[i], cov_eig_vectors_im1[i],\n                                     updated_covariance, updated_inv_root_covariance, cov_G_im1[i], im1_data.cov_matrices[i]));\n\n        // cov update\n        cov_G_im1[i] = updated_covariance;\n        im1_data.cov_matrices[i] = updated_inv_root_covariance;\n    }\n\n    for(int i=0; i < points_3d_im2.size(); ++i){\n        std::vector<Eigen::Matrix3d> updated_covariance;\n        std::vector<Eigen::Matrix3d> updated_inv_root_covariance;\n        \n        // point update\n        rsac_points_3d_im2.push_back(pointRefine->removeOutlierPoints(points_3d_im2[i], cov_eig_values_im2[i], cov_eig_vectors_im2[i],\n                                    updated_covariance, updated_inv_root_covariance, cov_G_im2[i], im2_data.cov_matrices[i]));\n\n        // cov update\n        cov_G_im2[i] = updated_covariance;\n        im2_data.cov_matrices[i] = updated_inv_root_covariance;\n    }\n    // std::cout << \"C2\" << std::endl;\n    // std::cout << rsac_points_3d_im1.size() << std::endl;\n    // std::cout << rsac_points_3d_im2.size() << std::endl;\n    // std::cout << im1_data.cov_matrices.size() << std::endl;\n    // std::cout << im2_data.cov_matrices.size() << std::endl;\n\n    std::cout << \"Starting Im1\" << std::endl;\n    int Inp;\n\n    std::vector<Eigen::Matrix3d> line1_endPt_covs, line2_endPt_covs;\n\n    for(int i = 0; i < rsac_points_3d_im1.size(); i++){\n    // std::cout << rsac_points_3d_im1[i].cols() << \" \" << im1_data.cov_matrices[i].size() << std::endl;\n    points3d optimized_line1 = optim::nonlinOptimize(rsac_points_3d_im1[i], im1_data.cov_matrices[i], cov_G_im1[i], line1_endPt_covs, 0, im1_data.cov_matrices[i].size()-1);\n    optimized_lines_im1.push_back(optimized_line1);\n    // std::cin >> Inp;\n    }\n\n    std::cout << \"Starting Im2\" << std::endl;\n    for(int i = 0; i < rsac_points_3d_im2.size(); i++){\n    points3d optimized_line2 = optim::nonlinOptimize(rsac_points_3d_im2[i], im2_data.cov_matrices[i], cov_G_im2[i], line2_endPt_covs, 0, im2_data.cov_matrices[i].size()-1);\n    optimized_lines_im2.push_back(optimized_line2);\n    }\n    std::cout << \"Matrix Size\" << line1_endPt_covs.size() << \" \" << line2_endPt_covs.size() << std::endl;\n\n\n\n}\n\n    // points3d FramePair::OptimizeFrames(){\n        \n    // }\n", "meta": {"hexsha": "57e9394ccf8cad03a41a783a9cbee8bf9e240465", "size": 13157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/frame.cpp", "max_stars_repo_name": "SubramanianKrish/roblineVO", "max_stars_repo_head_hexsha": "9c977c63cc02e8a3a9e42dfa8bae77198f5347f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-09T08:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T08:28:48.000Z", "max_issues_repo_path": "src/frame.cpp", "max_issues_repo_name": "SubramanianKrish/roblineVO", "max_issues_repo_head_hexsha": "9c977c63cc02e8a3a9e42dfa8bae77198f5347f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-11T07:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-11T07:00:50.000Z", "max_forks_repo_path": "src/frame.cpp", "max_forks_repo_name": "SubramanianKrish/roblineVO", "max_forks_repo_head_hexsha": "9c977c63cc02e8a3a9e42dfa8bae77198f5347f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T11:55:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T19:24:46.000Z", "avg_line_length": 44.2996632997, "max_line_length": 172, "alphanum_fraction": 0.5925362925, "num_tokens": 3721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6350474813470778}}
{"text": "/*JULKA - Julka\n#big-numbers\n\nJulka surprised her teacher at preschool by solving the following riddle:\n\nKlaudia and Natalia have 10 apples together, but Klaudia has two apples more than Natalia. How many apples does each of he girls have?\n\nJulka said without thinking: Klaudia has 6 apples and Natalia 4 apples. The teacher tried to check if Julka's answer wasn't accidental and repeated the riddle every time increasing the numbers. Every time Julka answered correctly. The surprised teacher wanted to continue questioning Julka, but with big numbers she could't solve the riddle fast enough herself. Help the teacher and write a program which will give her the right answers.\nTask\n\nWrite a program which\n\n    reads from standard input the number of apples the girls have together and how many more apples Klaudia has,\n    counts the number of apples belonging to Klaudia and the number of apples belonging to Natalia,\n    writes the outcome to standard output\n\nInput\n\nTen test cases (given one under another, you have to process all!). Every test case consists of two lines. The first line says how many apples both girls have together. The second line says how many more apples Klaudia has. Both numbers are positive integers. It is known that both girls have no more than 10100 (1 and 100 zeros) apples together. As you can see apples can be very small.\nOutput\n\nFor every test case your program should output two lines. The first line should contain the number of apples belonging to Klaudia. The second line should contain the number of apples belonging to Natalia.\nExample\n\nInput:\n10\n2\n[and 9 test cases more]\n\nOutput:\n6\n4\n[and 9 test cases more]\n\n*/\n\n#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\n\nint main()\n{\n    using namespace boost::multiprecision;\n    \n    for (int n = 0; n < 10; ++n)\n    {\n        cpp_int a, b, c;\n        \n        if (std::cin >> a >> b)\n        {\n            c = (a - b) / 2;\n            std::cout << c + b << \"\\n\" << c << std::endl;\n        }\n    }\n    \n    return 0;\n}\n", "meta": {"hexsha": "a833b4a5ee3f670843464322cc6d48c0f8d0e885", "size": 2025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SPOJ/JULKA - Julka.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/JULKA - Julka.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/JULKA - Julka.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": 34.9137931034, "max_line_length": 437, "alphanum_fraction": 0.7219753086, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6350474665350136}}
{"text": "/* Boost test/test_float.cpp\n * test arithmetic operations on a range of intervals\n *\n * Copyright 2003 Guillaume Melquiond\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/numeric/interval.hpp>\n#include <boost/test/test_tools.hpp>\n#include <boost/config.hpp>\n#include \"bugs.hpp\"\n\n/* All the following tests should be BOOST_CHECK; however, if a test fails,\n   the probability is high that hundreds of other tests will fail, so it is\n   replaced by BOOST_REQUIRE to avoid flooding the logs. */\n\ntemplate<class T, class F>\nvoid test_unary() {\n  typedef typename F::I I;\n  for(I a(-10., -9.91); a.lower() <= 10.; a += 0.3) {\n    if (!F::validate(a)) continue;\n    I rI = F::f_I(a);\n    T rT1 = F::f_T(a.lower()), rT2 = F::f_T(a.upper()),\n      rT3 = F::f_T(median(a));\n    BOOST_REQUIRE(in(rT1, rI));\n    BOOST_REQUIRE(in(rT2, rI));\n    BOOST_REQUIRE(in(rT3, rI));\n  }\n}\n\ntemplate<class T, class F>\nvoid test_binary() {\n  typedef typename F::I I;\n  for(I a(-10., -9.91); a.lower() <= 10.; a += 0.3) {\n    for(I b(-10., -9.91); b.lower() <= 10.; b += 0.3) {\n      if (!F::validate(a, b)) continue;\n      T al = a.lower(), au = a.upper(), bl = b.lower(), bu = b.upper();\n      I rII = F::f_II(a, b);\n      I rIT1 = F::f_IT(a, bl), rIT2 = F::f_IT(a, bu);\n      I rTI1 = F::f_TI(al, b), rTI2 = F::f_TI(au, b);\n      I rTT1 = F::f_TT(al, bl), rTT2 = F::f_TT(al, bu);\n      I rTT3 = F::f_TT(au, bl), rTT4 = F::f_TT(au, bu);\n      BOOST_REQUIRE(subset(rTT1, rIT1));\n      BOOST_REQUIRE(subset(rTT3, rIT1));\n      BOOST_REQUIRE(subset(rTT2, rIT2));\n      BOOST_REQUIRE(subset(rTT4, rIT2));\n      BOOST_REQUIRE(subset(rTT1, rTI1));\n      BOOST_REQUIRE(subset(rTT2, rTI1));\n      BOOST_REQUIRE(subset(rTT3, rTI2));\n      BOOST_REQUIRE(subset(rTT4, rTI2));\n      BOOST_REQUIRE(subset(rIT1, rII));\n      BOOST_REQUIRE(subset(rIT2, rII));\n      BOOST_REQUIRE(subset(rTI1, rII));\n      BOOST_REQUIRE(subset(rTI2, rII));\n    }\n  }\n}\n\n#define new_unary_bunch(name, op, val) \\\n  template<class T> \\\n  struct name { \\\n    typedef boost::numeric::interval<T> I; \\\n    static I f_I(const I& a) { return op(a); } \\\n    static T f_T(const T& a) { return op(a); } \\\n    static bool validate(const I& a) { return val; } \\\n  }\n\n//#ifndef BOOST_NO_STDC_NAMESPACE\nusing std::abs;\nusing std::sqrt;\n//#endif\n\nnew_unary_bunch(bunch_pos, +, true);\nnew_unary_bunch(bunch_neg, -, true);\nnew_unary_bunch(bunch_sqrt, sqrt, a.lower() >= 0.);\nnew_unary_bunch(bunch_abs, abs, true);\n\ntemplate<class T>\nvoid test_all_unaries() {\n  BOOST_CHECKPOINT(\"pos\");  test_unary<T, bunch_pos<T> >();\n  BOOST_CHECKPOINT(\"neg\");  test_unary<T, bunch_neg<T> >();\n  BOOST_CHECKPOINT(\"sqrt\"); test_unary<T, bunch_sqrt<T> >();\n  BOOST_CHECKPOINT(\"abs\");  test_unary<T, bunch_abs<T> >();\n}\n\n#define new_binary_bunch(name, op, val) \\\n  template<class T> \\\n  struct bunch_##name { \\\n    typedef boost::numeric::interval<T> I; \\\n    static I f_II(const I& a, const I& b) { return a op b; } \\\n    static I f_IT(const I& a, const T& b) { return a op b; } \\\n    static I f_TI(const T& a, const I& b) { return a op b; } \\\n    static I f_TT(const T& a, const T& b) \\\n    { return boost::numeric::interval_lib::name<I>(a,b); } \\\n    static bool validate(const I& a, const I& b) { return val; } \\\n  }\n\nnew_binary_bunch(add, +, true);\nnew_binary_bunch(sub, -, true);\nnew_binary_bunch(mul, *, true);\nnew_binary_bunch(div, /, !zero_in(b));\n\ntemplate<class T>\nvoid test_all_binaries() {\n  BOOST_CHECKPOINT(\"add\"); test_binary<T, bunch_add<T> >();\n  BOOST_CHECKPOINT(\"sub\"); test_binary<T, bunch_sub<T> >();\n  BOOST_CHECKPOINT(\"mul\"); test_binary<T, bunch_mul<T> >();\n  BOOST_CHECKPOINT(\"div\"); test_binary<T, bunch_div<T> >();\n}\n\nint test_main(int, char *[]) {\n  BOOST_CHECKPOINT(\"float tests\");\n  test_all_unaries<float> ();\n  test_all_binaries<float> ();\n  BOOST_CHECKPOINT(\"double tests\");\n  test_all_unaries<double>();\n  test_all_binaries<double>();\n  //BOOST_CHECKPOINT(\"long double tests\");\n  //test_all_unaries<long double>();\n  //test_all_binaries<long double>();\n# ifdef __BORLANDC__\n  ::detail::ignore_warnings();\n# endif\n  return 0;\n}\n", "meta": {"hexsha": "b8c33882317f15db951cfdb37359094567c2842a", "size": 4203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/numeric/interval/test/test_float.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/numeric/interval/test/test_float.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/numeric/interval/test/test_float.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 32.5813953488, "max_line_length": 75, "alphanum_fraction": 0.6393052581, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6350474620195621}}
{"text": "/**\n * $Id$\n *\n * Copyright (C)\n * 2015 - $Date$\n *     Martin Wolf <ndhist@martin-wolf.org>\n *\n * This file is distributed under the BSD 2-Clause Open Source License\n * (See LICENSE file).\n *\n */\n#ifndef NDHIST_STATS_EXCESS_HPP_INCLUDED\n#define DHIST_STATS_EXCESS_HPP_INCLUDED 1\n\n#include <boost/python.hpp>\n\n#include <ndhist/ndhist.hpp>\n#include <ndhist/stats/kurtosis.hpp>\n\nnamespace ndhist {\nnamespace stats {\n\nnamespace detail {\n\ntemplate <typename AxisValueType, typename WeightValueType>\ndouble\ncalc_axis_excess_impl(\n    ndhist const & h\n  , intptr_t const axis\n)\n{\n    return calc_axis_kurtosis_impl<AxisValueType, WeightValueType>(h, axis) - 3;\n}\n\n}// namespace detail\n\nnamespace py {\n\n/**\n * @brief Calculates the excess kurtosis along the given axis of the given\n *     ndhist object. As in statistics, the excess kurtosis is defined as\n *     :math:`Excess[x] = Kurtosis[x] - 3`.\n *     This function generates a projection along the given axis and then\n *     calculates the excess kurtosis.\n *     If None is given as axis, the excess kurtosis for all individual axes\n *     of the ndhist object will be calculated and returned as a tuple.\n *     But if the dimensionality of the ndhist object is 1, a scalar value is\n *     returned.\n *\n * @note This function is only defined for ndhist objects with POD axis values\n *     AND POD weight values.\n */\nboost::python::object\nexcess(\n    ndhist const & h\n  , boost::python::object const & axis = boost::python::object()\n);\n\n}// namespace py\n\n}// namespace stats\n}// namespace ndhist\n\n#endif // !DHIST_STATS_EXCESS_HPP_INCLUDED\n", "meta": {"hexsha": "3561c7bebfb12f665afeac861f16959987d01728", "size": 1589, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ndhist/stats/excess.hpp", "max_stars_repo_name": "martwo/ndhist", "max_stars_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ndhist/stats/excess.hpp", "max_issues_repo_name": "martwo/ndhist", "max_issues_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ndhist/stats/excess.hpp", "max_forks_repo_name": "martwo/ndhist", "max_forks_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4461538462, "max_line_length": 80, "alphanum_fraction": 0.7117684078, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6350474589707675}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n  MatrixXf m(3,3), n(2,2);\n  \n  m << 1,2,3,\n       4,5,6,\n       7,8,9;\n       \n  // assignment through a block operation,\n  //  block as rvalue\n  n = m.block(0,0,2,2);\n  \n  //print n\n  cout << \"n = \" << endl << n << endl << endl;\n  \n  \n  n << 1,1,\n       1,1;\n        \n  // block as lvalue\n  m.block(0,0,2,2) = n;\n  \n  //print m\n  cout << \"m = \" << endl << m << endl;\n}\n", "meta": {"hexsha": "0419a500fd8773ca8c123f66674bc73f2e7f9811", "size": 473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_BlockOperations_block_assignment.cpp", "max_stars_repo_name": "dailysoap/CSMM.104x", "max_stars_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_BlockOperations_block_assignment.cpp", "max_issues_repo_name": "dailysoap/CSMM.104x", "max_issues_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_BlockOperations_block_assignment.cpp", "max_forks_repo_name": "dailysoap/CSMM.104x", "max_forks_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 14.78125, "max_line_length": 46, "alphanum_fraction": 0.4820295983, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.8031738034238807, "lm_q1q2_score": 0.634933242767815}}
{"text": "\ufeff/*! \\file helium_hf.cpp\n    \\brief Hartree-Fock\u6cd5\u3067\u3001\u30d8\u30ea\u30a6\u30e0\u539f\u5b50\u306e\u30a8\u30cd\u30eb\u30ae\u30fc\u3092\u8a08\u7b97\u3059\u308b\n    Copyright \u00a9 2017 @dc1394 All Rights Reserved.\n    (but this is originally adapted by Paolo Giannozzi for helium_hf_gauss.c from http://www.fisica.uniud.it/~giannozz/Corsi/MQ/Software/C/helium_hf_gauss.c )\n    This software is released under the BSD 2-Clause License.\n*/\n\n#include <chrono>                               // for std::chrono\n#include <cmath>                                // for std::pow, std::sqrt\n#include <cstdint>                              // for std::int32_t\n#include <iostream>                             // for std::cerr, std::cin, std::cout\n#include <optional>                             // for std::make_optional, std::optional, std::nullopt\n#include <valarray>                             // for std::valarray\n#include <boost/assert.hpp>                     // for BOOST_ASSERT\n#include <boost/format.hpp>                     // for boost::format\n#include <boost/math/constants/constants.hpp>   // for boost::math::constants::pi\n#include <boost/multi_array.hpp>                // for boost::multi_array\n#include <Eigen/Core>                           // for Eigen::MatrixXd, Eigen::VectorXd\n#include <Eigen/Eigenvalues>                    // for Eigen::GeneralizedSelfAdjointEigenSolver\n\nnamespace {\n    //! A global variable (constant expression).\n    /*!\n        \u30d0\u30c3\u30d5\u30a1\u30b5\u30a4\u30ba\u306e\u4e0a\u9650\n    */\n    static auto constexpr MAXBUFSIZE = 32;\n\n    //! A global variable (constant expression).\n    /*!\n        SCF\u8a08\u7b97\u306e\u30eb\u30fc\u30d7\u306e\u4e0a\u9650\n    */\n\tstatic auto constexpr MAXITER = 1000;\n\n    //! A global variable (constant expression).\n    /*!\n        SCF\u8a08\u7b97\u306e\u30eb\u30fc\u30d7\u304b\u3089\u629c\u3051\u308b\u969b\u306e\u30a8\u30cd\u30eb\u30ae\u30fc\u306e\u5dee\u306e\u95be\u5024\n    */\n\tstatic auto constexpr SCFTHRESHOLD = 1.0E-15;\n\n    //! A global function.\n    /*!\n        SCF\u8a08\u7b97\u3092\u884c\u3046\n        \\return SCF\u8a08\u7b97\u304c\u6b63\u5e38\u306b\u7d42\u4e86\u3057\u305f\u5834\u5408\u306f\u30a8\u30cd\u30eb\u30ae\u30fc\u3092\u3001\u3057\u306a\u304b\u3063\u305f\u5834\u5408\u306fstd::nullopt\u3092\u8fd4\u3059\n    */\n    std::optional<double> do_scfloop();\n\n    //! A global function.\n    /*!\n        nalpha\u500b\u306eGTO\u306b\u3088\u308b\u30d8\u30ea\u30a6\u30e0\u539f\u5b50\u306e\u30a8\u30cd\u30eb\u30ae\u30fc\u3092\u8a08\u7b97\u3059\u308b\n        \\param c \u56fa\u6709\u30d9\u30af\u30c8\u30ebC\n        \\param ep \u4e00\u822c\u5316\u56fa\u6709\u5024\u554f\u984c\u306e\u30a8\u30cd\u30eb\u30ae\u30fc\u56fa\u6709\u5024E'\n        \\param h 1\u96fb\u5b50\u7a4d\u5206\n        \\return \u30d8\u30ea\u30a6\u30e0\u539f\u5b50\u306e\u30a8\u30cd\u30eb\u30ae\u30fc\n    */\n    double getenergy(Eigen::VectorXd const & c, double ep, boost::multi_array<double, 2> const & h);\n\n    //! A global function.\n    /*!\n        \u4f7f\u7528\u3059\u308bGTO\u306e\u6570\u3092\u30e6\u30fc\u30b6\u306b\u5165\u529b\u3055\u305b\u308b\n        \\return \u4f7f\u7528\u3059\u308bGTO\u306e\u6570\n    */\n    std::int32_t input_nalpha();\n\n    //! A global function.\n    /*!\n        GTO\u306e\u80a9\u306e\u4fc2\u6570\u304c\u683c\u7d0d\u3055\u308c\u305f\u914d\u5217\u3092\u751f\u6210\u3059\u308b\n        \\param nalpha \u4f7f\u7528\u3059\u308bGTO\u306e\u500b\u6570\n        \\return GTO\u306e\u80a9\u306e\u4fc2\u6570\u304c\u683c\u7d0d\u3055\u308c\u305fstd::vector\n    */\n    std::valarray<double> make_alpha(std::int32_t nalpha);\n\n    //! A global function.\n    /*!\n        \u5168\u3066\u306e\u8981\u7d20\u304c\u3001\u5f15\u6570\u3067\u6307\u5b9a\u3055\u308c\u305f\u5024\u3067\u57cb\u3081\u3089\u308c\u305fnalpha\u6b21\u5143\u30d9\u30af\u30c8\u30eb\u3092\u751f\u6210\u3059\u308b\n        \\param nalpha \u4f7f\u7528\u3059\u308bGTO\u306e\u500b\u6570\n        \\param val \u8981\u7d20\u3092\u57cb\u3081\u308b\u5024\n        \\return \u5f15\u6570\u3067\u6307\u5b9a\u3055\u308c\u305f\u5024\u3067\u57cb\u3081\u3089\u308c\u305f\u30d9\u30af\u30c8\u30eb (Eigen::VectorXd)\n    */\n    Eigen::VectorXd make_c(std::int32_t nalpha, double val);\n\n    //! A global function.\n    /*!\n        nalpha\u306e\u6570\u3067\u3001\u56fa\u6709\u30d9\u30af\u30c8\u30eb\u30011\u96fb\u5b50\u7a4d\u5206\u304a\u3088\u30732\u96fb\u5b50\u7a4d\u5206\u304b\u3089Fock\u884c\u5217\u3092\u751f\u6210\u3059\u308b\n        \\param c \u56fa\u6709\u30d9\u30af\u30c8\u30ebC\n        \\param h 1\u96fb\u5b50\u7a4d\u5206hpq\n        \\param q 2\u96fb\u5b50\u7a4d\u5206Qprqs\n        \\return Fock\u884c\u5217 (Eigen::MatrixXd)\n    */\n    Eigen::MatrixXd make_fockmatrix(Eigen::VectorXd const & c, boost::multi_array<double, 2> const & h, boost::multi_array<double, 4> const & q);\n\n    //! A global function.\n    /*!\n        1\u96fb\u5b50\u7a4d\u5206\u304c\u683c\u7d0d\u3055\u308c\u305f\u3001nalpha\u00d7nalpha\u306e2\u6b21\u5143\u914d\u5217\u3092\u751f\u6210\u3059\u308b\n        \\param alpha GTO\u306e\u80a9\u306e\u4fc2\u6570\u304c\u683c\u7d0d\u3055\u308c\u305fstd::vector\n        \\return 1\u96fb\u5b50\u7a4d\u5206\u304c\u683c\u7d0d\u3055\u308c\u305f2\u6b21\u5143\u914d\u5217 (boost::multi_array)\n    */\n    boost::multi_array<double, 2> make_oneelectroninteg(std::valarray<double> const & alpha);\n    \n    //! A global function.\n    /*!\n        nalpha\u6b21\u6b63\u65b9\u884c\u5217\u306e\u91cd\u306a\u308a\u884c\u5217\u3092\u751f\u6210\u3059\u308b\n        \\param alpha GTO\u306e\u80a9\u306e\u4fc2\u6570\u304c\u683c\u7d0d\u3055\u308c\u305fstd::vector\n        \\return \u91cd\u306a\u308a\u884c\u5217 (Eigen::MatrixXd)\n    */\n    Eigen::MatrixXd make_overlapmatrix(std::valarray<double> const & alpha);\n    \n    //! A global function.\n    /*!\n        2\u96fb\u5b50\u7a4d\u5206\u304c\u683c\u7d0d\u3055\u308c\u305fnalpha\u00d7nalpha\u00d7nalpha\u00d7nalpha\u306e4\u6b21\u5143\u914d\u5217\u3092\u751f\u6210\u3059\u308b\n        \\param alpha GTO\u306e\u80a9\u306e\u4fc2\u6570\u304c\u683c\u7d0d\u3055\u308c\u305fstd::vector\n        \\return 2\u96fb\u5b50\u7a4d\u5206\u304c\u683c\u7d0d\u3055\u308c\u305f4\u6b21\u5143\u914d\u5217 (boost::multi_array)\n    */\n    boost::multi_array<double, 4> make_twoelectroninteg(std::valarray<double> const & alpha);\n}\n\nint main()\n{\n    using namespace std::chrono;\n\n    auto const start = system_clock::now();\n    \n    if (auto const res(do_scfloop()); res) {\n        std::cout << boost::format(\"SCF\u8a08\u7b97\u304c\u53ce\u675f\u3057\u307e\u3057\u305f: energy = %.14f (Hartree)\") % (*res) << std::endl;\n\n        auto const end = system_clock::now();\n        std::cout << boost::format(\"\u8a08\u7b97\u6642\u9593 = %.14f\uff08\u79d2\uff09\\n\") % duration_cast< duration<double> >(end - start).count();\n\n        return 0;\n    }\n    else {\n        std::cerr << \"SCF\u8a08\u7b97\u304c\u53ce\u675f\u3057\u307e\u305b\u3093\u3067\u3057\u305f\" << std::endl;\n\n        return -1;\n    }\n}\n\nnamespace {\n    std::optional<double> do_scfloop()\n    {\n        // \u4f7f\u7528\u3059\u308bGTO\u306e\u6570\u3092\u5165\u529b\n        //auto const nalpha(input_nalpha());\n        int nalpha = 6;\n\n        // GTO\u306e\u80a9\u306e\u4fc2\u6570\u304c\u683c\u7d0d\u3055\u308c\u305f\u914d\u5217\u3092\u751f\u6210\n        auto alpha = make_alpha(nalpha);\n\n        // 1\u96fb\u5b50\u7a4d\u5206\u304c\u683c\u7d0d\u3055\u308c\u305f2\u6b21\u5143\u914d\u5217\u3092\u751f\u6210\n        auto const h(make_oneelectroninteg(alpha));\n\n        // 2\u96fb\u5b50\u7a4d\u5206\u304c\u683c\u7d0d\u3055\u308c\u305f4\u6b21\u5143\u914d\u5217\u3092\u751f\u6210\n        auto const q(make_twoelectroninteg(alpha));\n\n        // \u91cd\u306a\u308a\u884c\u5217\u3092\u751f\u6210\n        auto const s(make_overlapmatrix(alpha));\n\n        // \u5168\u30660.0\u3067\u521d\u671f\u5316\u3055\u308c\u305f\u56fa\u6709\u30d9\u30af\u30c8\u30eb\u3092\u751f\u6210\n        auto c(make_c(nalpha, 0.0));\n\n        // \u65b0\u3057\u304f\u8a08\u7b97\u3055\u308c\u305f\u30a8\u30cd\u30eb\u30ae\u30fc\n        auto enew = 0.0;\n\n        // SCF\u30eb\u30fc\u30d7\n        for (auto iter = 1; iter < MAXITER; iter++) {\n            // Fock\u884c\u5217\u3092\u751f\u6210\n            auto const f(make_fockmatrix(c, h, q));\n\n            // \u4e00\u822c\u5316\u56fa\u6709\u5024\u554f\u984c\u3092\u89e3\u304f\n            Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> es(f, s);\n            \n            // E'\u3092\u53d6\u5f97\n            auto const ep = es.eigenvalues()[0];\n            \n            // \u56fa\u6709\u30d9\u30af\u30c8\u30eb\u3092\u53d6\u5f97\n            c = es.eigenvectors().col(0);\n\n            // \u524d\u56de\u306eSCF\u8a08\u7b97\u306e\u30a8\u30cd\u30eb\u30ae\u30fc\u3092\u4fdd\u7ba1\n            auto const eold = enew;\n\n            // \u4eca\u56de\u306eSCF\u8a08\u7b97\u306e\u30a8\u30cd\u30eb\u30ae\u30fc\u3092\u8a08\u7b97\u3059\u308b\n            enew = getenergy(c, ep, h);\n\n            std::cout << boost::format(\"Iteration # %2d: HF eigenvalue = %.14f, energy = %.14f\\n\") % iter % ep % enew;\n\n            // SCF\u8a08\u7b97\u304c\u53ce\u675f\u3057\u305f\u304b\u3069\u3046\u304b\n            if (std::fabs(enew - eold) < SCFTHRESHOLD) {\n                // \u53ce\u675f\u3057\u305f\u306e\u3067\u305d\u306e\u30a8\u30cd\u30eb\u30ae\u30fc\u3092\u8fd4\u3059\n                return std::make_optional(enew);\n            }\n        }\n\n        // SCF\u8a08\u7b97\u304c\u53ce\u675f\u3057\u306a\u304b\u3063\u305f\n        return std::nullopt;\n    }\n    \n    double getenergy(Eigen::VectorXd const & c, double ep, boost::multi_array<double, 2> const & h)\n    {\n        auto const nalpha = static_cast<std::int32_t>(c.size());\n        auto e = ep;\n        for (auto p = 0; p < nalpha; p++) {\n            for (auto q = 0; q < nalpha; q++) {\n                // E = E' + Cp * Cq * hpq\n                e += c[p] * c[q] * h[p][q];\n            }\n        }\n\n        return e;\n    }\n    \n    std::int32_t input_nalpha()\n    {\n        std::int32_t nalpha;\n\n        while (true) {\n            std::cout << \"\u4f7f\u7528\u3059\u308bGTO\u306e\u500b\u6570\u3092\u5165\u529b\u3057\u3066\u304f\u3060\u3055\u3044 (3, 4 or 6): \";\n            std::cin >> nalpha;\n\n            if (!std::cin.fail() && (nalpha == 3 || nalpha == 4 || nalpha == 6)) {\n                break;\n            }\n\n            std::cin.clear();\n            std::cin.ignore(MAXBUFSIZE, '\\n');\n        }\n\n        return nalpha;\n    }\n\n    std::valarray<double> make_alpha(std::int32_t nalpha)\n    {\n        switch (nalpha) {\n        case 3:\n            return { 0.31364978999999998, 1.1589229999999999, 6.3624213899999997 };\n\n        case 4:\n            return { 0.297104, 1.236745, 5.749982, 38.2166777 };\n\n        case 6:\n            return { 0.18595935599999999, 0.45151632200000003, 1.1627151630000001, 3.384639924, 12.09819836, 65.984568240000002 };\n\n        default:\n            BOOST_ASSERT(!\"switch\u6587\u306edefault\u306b\u6765\u3066\u3057\u307e\u3063\u305f\uff01\");\n            return std::valarray<double>();\n        }\n    }\n\n    Eigen::VectorXd make_c(std::int32_t nalpha, double val)\n    {\n        Eigen::VectorXd c(nalpha);\n\n        // \u56fa\u6709\u30d9\u30af\u30c8\u30ebC\u306e\u8981\u7d20\u3092\u5168\u3066val\u3067\u521d\u671f\u5316\n        for (auto i = 0; i < nalpha; i++) {\n            c[i] = val;\n        }\n\n        return c;\n    }\n\n    Eigen::MatrixXd make_fockmatrix(Eigen::VectorXd const & c, boost::multi_array<double, 2> const & h, boost::multi_array<double, 4> const & q)\n    {\n        auto const nalpha = static_cast<std::int32_t>(c.size());\n        Eigen::MatrixXd f = Eigen::MatrixXd::Zero(nalpha, nalpha);\n\n        for (auto p = 0; p < nalpha; p++) {\n            for (auto qi = 0; qi < nalpha; qi++) {\n                // Fpq = hpq + \u03a3Cr * Cs * Qprqs\n                f(p, qi) = h[p][qi];\n\n                for (auto r = 0; r < nalpha; r++) {\n                    for (auto s = 0; s < nalpha; s++) {\n                        f(p, qi) += c[r] * c[s] * q[p][r][qi][s];\n                    }\n                }\n            }\n        }\n\n        return f;\n    }\n\n    boost::multi_array<double, 2> make_oneelectroninteg(std::valarray<double> const & alpha)\n    {\n        using namespace boost::math::constants;\n\n        auto const nalpha = static_cast<std::int32_t>(alpha.size());\n        boost::multi_array<double, 2> h(boost::extents[nalpha][nalpha]);\n\n        for (auto p = 0; p < nalpha; p++) {\n            for (auto q = 0; q < nalpha; q++) {\n                // \u03b1p + \u03b1q\n                auto const appaq = alpha[p] + alpha[q];\n\n                // hpq = 3\u03b1p\u03b1q\u03c0^1.5 / (\u03b1p + \u03b1q)^2.5 - 4\u03c0 / (\u03b1p + \u03b1q)\n                h[p][q] = 3.0 * alpha[p] * alpha[q] * std::pow((pi<double>() / appaq), 1.5) / appaq -\n                          4.0 * pi<double>() / appaq;\n            }\n        }\n\n        return h;\n    }\n\n    Eigen::MatrixXd make_overlapmatrix(std::valarray<double> const & alpha)\n    {\n        using namespace boost::math::constants;\n\n        auto const nalpha = static_cast<std::int32_t>(alpha.size());\n        Eigen::MatrixXd s = Eigen::MatrixXd::Zero(nalpha, nalpha);\n\n        for (auto p = 0; p < nalpha; p++) {\n            for (auto q = 0; q < nalpha; q++) {\n                // Spq = (\u03c0 / (\u03b1p + \u03b1q))^1.5\n                s(p, q) = std::pow((pi<double>() / (alpha[p] + alpha[q])), 1.5);\n            }\n        }\n\n        return s;\n    }\n\n    boost::multi_array<double, 4> make_twoelectroninteg(std::valarray<double> const & alpha)\n    {\n        using namespace boost::math::constants;\n\n        auto const nalpha = static_cast<std::int32_t>(alpha.size());\n        boost::multi_array<double, 4> q(boost::extents[nalpha][nalpha][nalpha][nalpha]);\n\n        for (auto p = 0; p < nalpha; p++) {\n            for (auto qi = 0; qi < nalpha; qi++) {\n                for (auto r = 0; r < nalpha; r++) {\n                    for (auto s = 0; s < nalpha; s++) {\n                        // Qprqs = 2\u03c0^2.5 / [(\u03b1p + \u03b1q)(\u03b1r + \u03b1s)\u221a(\u03b1p + \u03b1q + \u03b1r + \u03b1s)]\n                        q[p][r][qi][s] = 2.0 * std::pow(pi<double>(), 2.5) /\n                            ((alpha[p] + alpha[qi]) * (alpha[r] + alpha[s]) *\n                            std::sqrt(alpha[p] + alpha[qi] + alpha[r] + alpha[s]));\n                    }\n                }\n            }\n        }\n\n        return q;\n    }\n}\n", "meta": {"hexsha": "85b2b417bfc270bd545d80a51a7efc4fd805faa5", "size": 10579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/helium_hf.cpp", "max_stars_repo_name": "dc1394/helium_hf", "max_stars_repo_head_hexsha": "89d8821d15a5c29b131e54350a071692f55a9533", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-13T18:48:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-13T18:48:45.000Z", "max_issues_repo_path": "src/helium_hf.cpp", "max_issues_repo_name": "dc1394/helium_hf", "max_issues_repo_head_hexsha": "89d8821d15a5c29b131e54350a071692f55a9533", "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/helium_hf.cpp", "max_forks_repo_name": "dc1394/helium_hf", "max_forks_repo_head_hexsha": "89d8821d15a5c29b131e54350a071692f55a9533", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1147058824, "max_line_length": 158, "alphanum_fraction": 0.5281217506, "num_tokens": 3527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6348979706533909}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <unsupported/Eigen/KroneckerProduct>\n\n#include \"yavque/utils.hpp\"\nEigen::VectorXcd product_state(uint32_t n, const Eigen::VectorXcd& s)\n{\n\tEigen::VectorXcd res(1);\n\tres(0) = 1.0;\n\tfor(uint32_t i = 0; i < n; i++)\n\t{\n\t\tres = Eigen::kroneckerProduct(res, s).eval();\n\t}\n\treturn res;\n}\n\ntemplate<typename T>\nEigen::VectorXcd\napply_kronecker(uint32_t N, const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& m,\n                const Eigen::VectorXcd& vec)\n{\n\tEigen::VectorXcd res = vec;\n\tfor(uint32_t k = 0; k < N; ++k)\n\t{\n\t\tres = yavque::apply_single_qubit(res, m, k);\n\t}\n\treturn res;\n}\n\ntemplate<typename RandomEngine>\nstd::pair<uint32_t, uint32_t> random_connection(const int N, RandomEngine& re)\n{\n\tstd::uniform_int_distribution<uint32_t> uid1(0, N - 1);\n\tstd::uniform_int_distribution<uint32_t> uid2(0, N - 2);\n\n\tauto r1 = uid1(re);\n\tauto r2 = uid2(re);\n\n\tif(r2 < r1)\n\t\treturn std::make_pair(r1, r2);\n\telse\n\t\treturn std::make_pair(r1, r2 + 1);\n}\n\ntemplate<typename RandomEngine>\nEigen::MatrixXcd random_unitary(uint32_t dim, RandomEngine&& re)\n{\n\tconstexpr yavque::cx_double I(0.0, 1.0);\n\tstd::normal_distribution<double> ndist;\n\n\tEigen::MatrixXcd m(dim, dim);\n\tfor(uint32_t i = 0; i < dim; ++i)\n\t{\n\t\tfor(uint32_t j = 0; j < dim; ++j)\n\t\t{\n\t\t\tm(i, j) = ndist(re) + I * ndist(re);\n\t\t}\n\t}\n\tEigen::HouseholderQR<Eigen::MatrixXcd> qr(m);\n\treturn qr.householderQ();\n}\n\ntemplate<typename RandomEngine>\nEigen::VectorXcd random_vector(uint32_t dim, RandomEngine&& re)\n{\n\tconstexpr yavque::cx_double I(0.0, 1.0);\n\tstd::normal_distribution<double> ndist;\n\n\tEigen::VectorXcd res(dim);\n\tfor(uint32_t k = 0; k < dim; ++k)\n\t{\n\t\tres(k) = ndist(re) + I * ndist(re);\n\t}\n\tres.normalize();\n\treturn res;\n}\n", "meta": {"hexsha": "92fd6e1f3cf49332ab3e800a0ee4f0c9fee1f026", "size": 1731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Tests/common.hpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/common.hpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests/common.hpp", "max_forks_repo_name": "chaeyeunpark/Yavque", "max_forks_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4805194805, "max_line_length": 86, "alphanum_fraction": 0.6741767764, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901036, "lm_q2_score": 0.740174350576073, "lm_q1q2_score": 0.6348979500559186}}
{"text": "#include <iostream>\n#include <stdlib.h>\n#include <vector>\n#include <math.h>\n#include <fstream>\n#include <boost/qvm/vec.hpp>\n#include <boost/qvm/vec_operations.hpp>\n#include <boost/qvm/vec_access.hpp>\n#include <boost/qvm/mat.hpp>\n#include \"Body.h\"\n#include \"script_reader.h\"\n\nconst double G = 100.0;\nconst double S = 0.05;\n\nboost::qvm::vec<double, 3> acceleration_gravity(Body& b1, Body& b2)\n{\n    boost::qvm::vec<double, 3> r = b2.r - b1.r;\n    boost::qvm::vec<double, 3> numerator = G * b2.m * r;\n    double denominator = pow((pow(boost::qvm::mag(r), 2) + pow(S, 2)), 1.5);\n    return numerator / denominator;\n}\n\nboost::qvm::vec<double, 3> net_acceleration(Body& b, std::vector<Body>& system)\n{\n    boost::qvm::vec<double, 3> a = { 0, 0, 0 };\n    int i = 0;\n\n    for (std::vector<Body>::const_iterator it = std::begin(system);\n        it != std::end(system); it++, i++)\n    {\n        if (b.r != system[i].r)\n        {\n            a += acceleration_gravity(b, system[i]);\n        }\n    }\n\n    return a;\n}\n\n// velocity verlet integrator - step forward once by dt\nvoid verlet_step(std::vector<Body>& system, const double& dt)\n{\n    int i = 0;\n\n    for (std::vector<Body>::const_iterator it = std::begin(system);\n        it != std::end(system); it++, i++)\n    {\n        boost::qvm::vec<double, 3> a1 = net_acceleration(system[i], system);\n        system[i].r += system[i].v * dt + 0.5 * a1 * pow(dt, 2);\n        boost::qvm::vec<double, 3> a2 = net_acceleration(system[i], system);\n        system[i].v += 0.5 * (a1 + a2) * dt;\n    }\n}\n\nvoid integrate(initial_state& state, char* output_file_path)\n{\n    double t_current = 0;\n    double t_save_current = 0;\n    std::ofstream output_file(output_file_path);\n    output_file << \"t\\tid\\tm\\trx\\try\\trz\\n\";\n    output_file << std::scientific;\n    int i = 0;\n\n    while (t_current < state.t)\n    {\n        verlet_step(state.system, state.dt);\n\n        if (t_save_current >= state.save_interval)\n        {\n            // save to file with format time \\t id \\t mass \\t rx \\t ry \\t rz\n            for (std::vector<Body>::const_iterator it = std::begin(state.system);\n                it != std::end(state.system); it++, i++)\n            {\n                output_file << t_current << \"\\t\"\n                    << i + 1 << \"\\t\"\n                    << state.system[i].m << \"\\t\"\n                    << boost::qvm::A<0>(state.system[i].r) << \"\\t\"\n                    << boost::qvm::A<1>(state.system[i].r) << \"\\t\"\n                    << boost::qvm::A<2>(state.system[i].r) << \"\\n\";\n            }\n\n            i = 0;\n            t_save_current = 0;\n        }\n        else\n        {\n            t_save_current += state.dt;\n        }\n\n        t_current += state.dt;\n    }\n}\n\nint main(int argc, char* argv[])\n{\n    if (argc == 3)\n    {\n        char* input_file_path = argv[1];\n        char* output_file_path = argv[2];\n        initial_state input_state = load_input_data(input_file_path);\n        integrate(input_state, output_file_path);\n    }\n    else\n    {\n        std::cout << \"error: takes two args: arg1 = input_file_path\"\n            << \" arg2 = output_file_path\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    return 0;\n}", "meta": {"hexsha": "5e9a45da45b775741133d4c1cd604d13759c130b", "size": 3159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nbody.cpp", "max_stars_repo_name": "ilovematter/nbody_cpp", "max_stars_repo_head_hexsha": "94b0e26b65a2fdf4534b58e447ae25578513416e", "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/nbody.cpp", "max_issues_repo_name": "ilovematter/nbody_cpp", "max_issues_repo_head_hexsha": "94b0e26b65a2fdf4534b58e447ae25578513416e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nbody.cpp", "max_forks_repo_name": "ilovematter/nbody_cpp", "max_forks_repo_head_hexsha": "94b0e26b65a2fdf4534b58e447ae25578513416e", "max_forks_repo_licenses": ["Apache-2.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.2053571429, "max_line_length": 81, "alphanum_fraction": 0.5438429883, "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463334, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.63489794912354}}
{"text": "/*\nThis file is part of Bohrium and Copyright (c) 2012 the Bohrium team:\nhttp://bohrium.bitbucket.org\n\nBohrium is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as \npublished by the Free Software Foundation, either version 3 \nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the \nGNU Lesser General Public License along with bohrium. \n\nIf not, see <http://www.gnu.org/licenses/>.\n*/\n#include <iostream>\n#include <armadillo>\n#include <bp_util.h>\n\nusing namespace std;\nusing namespace arma;\n\ntemplate <typename T>\nCol<T> cnd(Col<T> x)\n{\n    size_t samples = x.n_elem;\n    Col<T> l(samples), k(samples), w(samples);\n    T a1 = 0.31938153,\n      a2 =-0.356563782,\n      a3 = 1.781477937,\n      a4 =-1.821255978,\n      a5 = 1.330274429,\n      pp = 2.5066282746310002; // sqrt(2.0*PI)\n\n    l = abs(x);\n    k = 1.0 / (1.0 + 0.2316419 * l);\n\n    w = 1.0 - 1.0 / pp * exp(-1.0*l%l/2.0) % \\\n        (a1*k + \\\n         a2*(pow(k,(T)2)) + \\\n         a3*(pow(k,(T)3)) + \\\n         a4*(pow(k,(T)4)) + \\\n         a5*(pow(k,(T)5)));\n\n    uvec mask = x < 0.0;\n\n    return w % (-mask) + (1.0-w) % mask;\n}\n\ntemplate <typename T>\nT* pricing(size_t samples, size_t iterations, char flag, T x, T d_t, T r, T v)\n{\n    T* p    = (T*)malloc(sizeof(T)*samples);    // Intermediate results\n    T t     = d_t;                              // Initial delta\n\n    Col<T> d1(samples), d2(samples), res(samples);\n    Col<T> s = randu<Col<T> >(samples)*4.0 +58.0;      // Model between 58-62\n\n    for(size_t i=0; i<iterations; i++) {\n        d1 = (log(s/x) + (r+v*v/2.0)*t) / (v*sqrt(t));\n        d2 = d1-v*sqrt(t);\n        if (flag == 'c') {\n            res = s % cnd<T>(d1) -x * exp(-r*t) * cnd<T>(d2);\n        } else {\n            res = x * exp(-r*t) * cnd<T>(-1.0*d2) - s*cnd<T>(-1.0*d1);\n        }\n\n        t += d_t;                               // Increment delta\n        p[i] = sum(res) / (T)samples;           // Result from timestep\n    }\n\n    return p;\n}\n\nint main(int argc, char* argv[])\n{\n    bp_util_type bp = bp_util_create(argc, argv, 2);\n    if (bp.args.has_error) {\n        return 1;\n    }\n    const size_t samples    = bp.args.sizes[0];\n    const size_t iterations = bp.args.sizes[1];\n\n    bp.timer_start();\n    double* prices = pricing(\n        samples, iterations,\n        'c', 65.0, 1.0 / 365.0,\n        0.08, 0.3\n    );\n    bp.timer_stop();\n\n    bp.print(\"black_scholes(cpp11_armadillo)\");\n    if (bp.args.verbose) {\n        cout << \", \\\"output\\\": [\";\n        for(size_t i=0; i<iterations; i++) {\n            cout << prices[i];\n            if (iterations-1!=i) {\n                cout << \", \";\n            }\n        }\n        cout << \"]\" << endl;\n    }\n\n    free(prices);\n    return 0;\n}\n\n", "meta": {"hexsha": "7d765149d1773c9b490d1f159bcecdf3eada06e7", "size": 3015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchpress/benchmarks/black_scholes/cpp11_armadillo/src/black_scholes.cpp", "max_stars_repo_name": "bh107/benchpress", "max_stars_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-03-31T15:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T21:30:49.000Z", "max_issues_repo_path": "benchpress/benchmarks/black_scholes/cpp11_armadillo/src/black_scholes.cpp", "max_issues_repo_name": "bh107/benchpress", "max_issues_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-04-13T12:03:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-28T13:31:11.000Z", "max_forks_repo_path": "benchpress/benchmarks/black_scholes/cpp11_armadillo/src/black_scholes.cpp", "max_forks_repo_name": "bh107/benchpress", "max_forks_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-06-28T08:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T17:30:25.000Z", "avg_line_length": 26.9196428571, "max_line_length": 78, "alphanum_fraction": 0.544278607, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6348319684133129}}
{"text": "/*\n * =====================================================================================\n *\n *       Filename:  optimal_transport.cpp\n *\n *    Description:\n *\n *        Version:  1.0\n *        Created:  11/04/19 10:55:59\n *       Revision:  none\n *       Compiler:  gcc\n *\n *         Author:  YOUR NAME (),\n *   Organization:\n *\n * =====================================================================================\n */\n#include <stdlib.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include \"optimal_transport.h\"\n\nusing namespace Eigen;\ntypedef Map<VectorXd> MapT;\n\n// TODO how to do it passable via cffi?\n// const double lambda = 1;\n// const double epsilon = 0.1;\n// const double tol = 1e-05;\n// const double threshold = 1e+02;\n// const double max_iter = 1000;\n\nVectorXd proxdiv_TV(VectorXd s, VectorXd u, VectorXd p, double lambda,\n                    double epsilon) {\n    ArrayXd e_lam = ((lambda - u.array()) / epsilon).exp();\n    ArrayXd e_minus_lam = (-(lambda + u.array()) / epsilon).exp();\n    return e_lam.cwiseMin(e_minus_lam.cwiseMax(p.array() / s.array())).matrix();\n}\n\nVectorXd proxdiv_i(VectorXd s, VectorXd u, VectorXd p, double lambda,\n                   double epsilon) {\n    return (p.array() / s.array()).matrix();\n}\n\nMatrixXd calc_distance_matrix(VectorXd mzs1, VectorXd mzs2) {\n    return (mzs1 * VectorXd::Ones(mzs2.rows()).transpose() -\n                VectorXd::Ones(mzs1.rows()) * mzs2.transpose()).cwiseAbs();\n}\n\nMatrixXd calc_transport_plan(VectorXd ints1, VectorXd ints2, MatrixXd dists,\n                             double lambda, double epsilon, double tol,\n                             double threshold, double max_iter) {\n    int n1 = ints1.rows();\n    int n2 = ints2.rows();\n    MatrixXd K_0 = (-dists / epsilon).array().exp().matrix();\n    MatrixXd K = K_0;\n\n    VectorXd b = VectorXd::Ones(n2);\n    VectorXd a = VectorXd::Zero(n1);\n    VectorXd u = VectorXd::Zero(n1);\n    VectorXd v = VectorXd::Zero(n2);\n\tVectorXd a_new, b_new;\n    double coverging_val;\n\n    int tick = 0;\n    bool coverged = false;\n\n    do {\n        a_new = proxdiv_TV(K * b, u, ints1, lambda, epsilon); // * is matrix-matrix\n        b_new = proxdiv_TV(K.transpose() * a_new, v, ints2, lambda, epsilon);\n\n        if ((((a_new.array().log().abs() - threshold) > 0).any()) or\n            (((b_new.array().log().abs() - threshold) > 0).any())) {\n            // Stabilizing\n            u += epsilon * a_new.array().log().matrix();\n            v += epsilon * b_new.array().log().matrix();\n            // below is exp((u_i + v_j - dists_{ij}) / eps) forall i,j\n            K = (u / epsilon).array().exp().matrix().asDiagonal() * K_0 *\n                (v / epsilon).array().exp().matrix().asDiagonal();\n        }\n\n        coverging_val = std::max((a_new - a).maxCoeff(),\n                                 (b_new - b).maxCoeff());\n        tick++;\n        coverged = coverging_val < tol or tick >= max_iter;\n        a = a_new;\n        b = b_new;\n    } while (not coverged);\n    // below is (a_i * K_{ij} * b_j)_{ij}\n    return a.asDiagonal() * K * b.asDiagonal();\n}\n\ndouble calc_distance_from_plan(MatrixXd transport_plan, MatrixXd distances,\n                               VectorXd ints1, VectorXd ints2, double lambda) {\n    double transport = (transport_plan.array() * distances.array()).sum();\n    // ^^^ coeff-wise multiplication ^^^\n\n    double trash = 0;\n    trash += lambda * ((transport_plan.rowwise().sum() - ints1).cwiseAbs().sum());\n    trash += lambda * ((transport_plan.colwise().sum().transpose() - ints2).cwiseAbs().sum());\n    // ^^ colwise sum is row, not column\n    return transport + trash;\n}\n\ndouble calc_distance_cpp(double* mzs1, double* ints1, int len1, double* mzs2,\n                         double* ints2, int len2, double lambda,\n                         double epsilon, double tol, double threshold,\n                         double max_iter) {\n    /*  TODO description\n     *\n     *  ints1, and ints2 should be normalized */\n    /*\n     * TODO sharing memory causes segfault, so maybe copying to matrix is\n     * better?\n     */\n\n    MapT mzs1_map(mzs1, len1);\n    MapT mzs2_map(mzs2, len2);\n    MapT ints1_map(ints1, len1);\n    MapT ints2_map(ints2, len2);\n    MatrixXd dists = calc_distance_matrix(mzs1_map, mzs2_map);\n    MatrixXd transport_plan = calc_transport_plan(ints1_map, ints2_map, dists,\n            lambda, epsilon, tol, threshold, max_iter);\n    return calc_distance_from_plan(transport_plan, dists, ints1_map, ints2_map,\n                                   lambda);\n}\n\n\ndouble calc_distance_c(double* mzs1, double* ints1, int len1, double* mzs2,\n                       double* ints2, int len2, double lambda, double epsilon,\n                       double tol, double threshold, double max_iter) {\n    return calc_distance_cpp(mzs1, ints1, len1, mzs2, ints2, len2, lambda,\n                             epsilon, tol, threshold, max_iter);\n}\n\n", "meta": {"hexsha": "9a0a9ec7281699ddbc930425c90479d7b368032f", "size": 4884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MasSpOT/optimal_transport.cpp", "max_stars_repo_name": "grzsko/MasSpOT", "max_stars_repo_head_hexsha": "e5b0e259965e7d542c298053cd505b7fbad5b978", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-08T17:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-08T17:12:09.000Z", "max_issues_repo_path": "MasSpOT/optimal_transport.cpp", "max_issues_repo_name": "grzsko/MasSpOT", "max_issues_repo_head_hexsha": "e5b0e259965e7d542c298053cd505b7fbad5b978", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-05T13:59:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-05T13:59:57.000Z", "max_forks_repo_path": "MasSpOT/optimal_transport.cpp", "max_forks_repo_name": "grzsko/MasSpOT", "max_forks_repo_head_hexsha": "e5b0e259965e7d542c298053cd505b7fbad5b978", "max_forks_repo_licenses": ["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.9117647059, "max_line_length": 94, "alphanum_fraction": 0.5653153153, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6348319684133128}}
{"text": "/*\n *  Distributed under the MIT License (See accompanying file /LICENSE )\n */\n#include <doctest/doctest.h>  // for ResultBuilder\n\n#include <array>                             // for operator==\n#include <boost/multiprecision/cpp_int.hpp>  // for cpp_int\n#include <ostream>                           // for operator<<\n#include <tuple>                             // for get, tuple\n#include <type_traits>                       // for move\n\n#include \"projgeom/ck_plane.hpp\"       // for ellck, hyck\n#include \"projgeom/common_concepts.h\"  // for Value_type\n#include \"projgeom/fractions.hpp\"      // for operator*\n#include \"projgeom/pg_common.hpp\"      // for cross\n#include \"projgeom/pg_line.hpp\"        // for pg_line\n#include \"projgeom/pg_object.hpp\"      // for operator*\n#include \"projgeom/pg_point.hpp\"       // for pg_point\n#include \"projgeom/proj_plane.hpp\"     // for tri_dual\n// #include <iostream>\n\nusing namespace fun;\n\nstatic const auto Zero = doctest::Approx(0).epsilon(0.01);\n\n/**\n * @brief\n *\n * @param[in] a\n * @return true\n * @return false\n */\ntemplate <typename T> inline auto ApproxZero(const T& a) -> bool {\n    return a[0] == Zero && a[1] == Zero && a[2] == Zero;\n}\n\n/**\n * @brief\n *\n * @tparam PG\n * @param[in] myck\n */\ntemplate <typename PG> void chk_tri(const PG& myck) {\n    using Point = typename PG::point_t;\n    using K = Value_type<Point>;\n\n    auto a1 = Point{1, 3, 1};\n    auto a2 = Point{4, 2, 1};\n    auto a3 = Point{1, 1, -1};\n    auto a4 = plucker(2, a1, 3, a2);\n\n    const auto triangle = std::tuple{std::move(a1), std::move(a2), std::move(a3)};\n    const auto trilateral = tri_dual(triangle);\n    const auto& [l1, l2, l3] = trilateral;\n\n    const auto Q = myck.tri_quadrance(triangle);\n    const auto S = myck.tri_spread(trilateral);\n\n    if constexpr (Integral<K>) {\n        CHECK(myck.perp(myck.perp(a4)) == a4);\n        CHECK(myck.perp(myck.perp(l1)) == l1);\n        CHECK(myck.perp(myck.perp(l2)) == l2);\n        CHECK(myck.perp(myck.perp(l3)) == l3);\n        // CHECK(check_cross_law(S, std::get<2>(Q)) == K(0));\n        // CHECK(check_cross_law(Q, std::get<2>(S)) == K(0));\n    } else {\n        CHECK(ApproxZero(cross(myck.perp(myck.perp(a4)), a4)));\n        CHECK(ApproxZero(cross(myck.perp(myck.perp(l1)), l1)));\n        CHECK(ApproxZero(cross(myck.perp(myck.perp(l2)), l2)));\n        CHECK(ApproxZero(cross(myck.perp(myck.perp(l3)), l3)));\n        CHECK(check_cross_law(S, std::get<2>(Q)) == Zero);\n        CHECK(check_cross_law(Q, std::get<2>(S)) == Zero);\n    }\n}\n\n/**\n * @brief\n *\n * @tparam PG\n * @param[in] myck\n */\ntemplate <typename PG> void chk_tri2(const PG& myck) {\n    using Point = typename PG::point_t;\n    using K = Value_type<Point>;\n\n    auto a1 = Point{1, 3, 1};\n    auto a2 = Point{4, 2, 1};\n    auto a4 = plucker(2, a1, 3, a2);\n\n    const auto collin = std::tuple{std::move(a1), std::move(a2), std::move(a4)};\n    const auto Q2 = myck.tri_quadrance(collin);\n\n    if constexpr (Integral<K>) {\n        CHECK(check_cross_TQF(Q2) == 0);\n    } else {\n        CHECK(check_cross_TQF(Q2) == Zero);\n    }\n}\n\nTEST_CASE(\"Elliptic/Hyperbolic plane\") {\n    using boost::multiprecision::cpp_int;\n\n    chk_tri(ellck<pg_point<cpp_int>>());\n    chk_tri(ellck<pg_line<cpp_int>>());\n    chk_tri(hyck<pg_point<cpp_int>>());\n    chk_tri(hyck<pg_line<cpp_int>>());\n\n    chk_tri2(ellck<pg_point<cpp_int>>());\n    chk_tri2(ellck<pg_line<cpp_int>>());\n    chk_tri2(hyck<pg_point<cpp_int>>());\n    chk_tri2(hyck<pg_line<cpp_int>>());\n}\n\nTEST_CASE(\"Elliptic/Hyperbolic plane (double)\") {\n    chk_tri(ellck<pg_point<double>>());\n    chk_tri(ellck<pg_line<double>>());\n    chk_tri(hyck<pg_point<double>>());\n    chk_tri(hyck<pg_line<double>>());\n\n    chk_tri2(ellck<pg_point<double>>());\n    chk_tri2(ellck<pg_line<double>>());\n    chk_tri2(hyck<pg_point<double>>());\n    chk_tri2(hyck<pg_line<double>>());\n}\n", "meta": {"hexsha": "d16aef628fa4819ab52ccc59c7ea5398d27d6ca0", "size": 3841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/source/test_ell_plane.cpp", "max_stars_repo_name": "luk036/projgeom-cpp", "max_stars_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/source/test_ell_plane.cpp", "max_issues_repo_name": "luk036/projgeom-cpp", "max_issues_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/source/test_ell_plane.cpp", "max_forks_repo_name": "luk036/projgeom-cpp", "max_forks_repo_head_hexsha": "665f852e17804a251639808c509df0a675f21e1d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.728, "max_line_length": 82, "alphanum_fraction": 0.6040093726, "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6348319585079176}}
{"text": "/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https://github.com/h2ssh/Vulcan\".\n*/\n\n\n/**\n * \\file\n * \\author   Collin Johnson\n *\n * Definition of independent_t_test.\n */\n\n#include \"math/t_test.h\"\n#include <boost/math/distributions/students_t.hpp>\n\nnamespace vulcan\n{\nnamespace math\n{\n\nt_test_results_t independent_t_test(const t_test_sample_t& sampleA, const t_test_sample_t& sampleB, double confidence)\n{\n    // Code closely related to Boost.Math example at:\n    // http://www.boost.org/doc/libs/1_65_1/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/two_sample_students_t.html\n\n    using namespace boost::math;\n\n    assert(sampleA.numSamples > 1);\n    assert(sampleB.numSamples > 1);\n    assert(sampleA.variance > 0.0);\n    assert(sampleB.variance > 0.0);\n\n    int dofA = sampleA.numSamples - 1;\n    int dofB = sampleB.numSamples - 1;\n    int dof = dofA + dofB;\n\n    double pooledVariance = std::sqrt(((dofA * sampleA.variance) + (dofB * sampleB.variance)) / dof);\n    double tDenom = pooledVariance * std::sqrt((1.0 / sampleA.numSamples) + (1.0 / sampleB.numSamples));\n\n    t_test_results_t results;\n    results.tValue = (sampleA.mean - sampleB.mean) / tDenom;\n    results.confidence = confidence;\n\n    students_t dist(dof);\n\n    results.pValueDifferent = cdf(complement(dist, std::abs(results.tValue)));\n    results.areDifferent = results.pValueDifferent < (confidence / 2.0);\n\n    results.pValueGreater = cdf(complement(dist, results.tValue));\n    results.isGreater = results.pValueGreater < confidence;\n\n    results.pValueLess = cdf(dist, results.tValue);\n    results.isLess = results.pValueLess < confidence;\n\n    return results;\n}\n\n}   // namespace math\n}   // namespace vulcan\n", "meta": {"hexsha": "c4b19508a841c82a2ca8c8e5fa62b41c6ff97f99", "size": 1969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/t_test.cpp", "max_stars_repo_name": "anuranbaka/Vulcan", "max_stars_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T23:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T19:06:50.000Z", "max_issues_repo_path": "src/math/t_test.cpp", "max_issues_repo_name": "anuranbaka/Vulcan", "max_issues_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-07T01:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T01:23:47.000Z", "max_forks_repo_path": "src/math/t_test.cpp", "max_forks_repo_name": "anuranbaka/Vulcan", "max_forks_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T07:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T07:54:16.000Z", "avg_line_length": 30.765625, "max_line_length": 121, "alphanum_fraction": 0.7171152869, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6348319433972145}}
{"text": "#include <igl/active_set.h>\n#include <igl/boundary_facets.h>\n#include <igl/cotmatrix.h>\n#include <igl/invert_diag.h>\n#include <igl/jet.h>\n#include <igl/massmatrix.h>\n#include <igl/readOFF.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <Eigen/Sparse>\n#include <iostream>\n#include \"tutorial_shared_path.h\"\n  \nEigen::VectorXi b;\nEigen::VectorXd B,bc,lx,ux,Beq,Bieq,Z;\nEigen::SparseMatrix<double> Q,Aeq,Aieq;\n\nvoid solve(igl::opengl::glfw::Viewer &viewer)\n{\n  using namespace std;\n  igl::active_set_params as;\n  as.max_iter = 8;\n  igl::active_set(Q,B,b,bc,Aeq,Beq,Aieq,Bieq,lx,ux,as,Z);\n  // Pseudo-color based on solution\n  Eigen::MatrixXd C;\n  igl::jet(Z,0,1,C);\n  viewer.data().set_colors(C);\n}\n\nbool key_down(igl::opengl::glfw::Viewer &viewer, unsigned char key, int mod)\n{\n  switch(key)\n  {\n    case '.':\n      Beq(0) *= 2.0;\n      solve(viewer);\n      return true;\n    case ',':\n      Beq(0) /= 2.0;\n      solve(viewer);\n      return true;\n    case ' ':\n      solve(viewer);\n      return true;\n    default:\n      return false;\n  }\n}\n\n\nint main(int argc, char *argv[])\n{\n  using namespace Eigen;\n  using namespace std;\n  MatrixXd V;\n  MatrixXi F;\n  igl::readOFF(TUTORIAL_SHARED_PATH \"/cheburashka.off\",V,F);\n\n  // Plot the mesh\n  igl::opengl::glfw::Viewer viewer;\n  viewer.data().set_mesh(V, F);\n  viewer.data().show_lines = false;\n  viewer.callback_key_down = &key_down;\n\n  // One fixed point\n  b.resize(1,1);\n  // point on belly.\n  b<<2556;\n  bc.resize(1,1);\n  bc<<1;\n\n  // Construct Laplacian and mass matrix\n  SparseMatrix<double> L,M,Minv;\n  igl::cotmatrix(V,F,L);\n  igl::massmatrix(V,F,igl::MASSMATRIX_TYPE_VORONOI,M);\n  //M = (M/M.diagonal().maxCoeff()).eval();\n  igl::invert_diag(M,Minv);\n  // Bi-Laplacian\n  Q = L.transpose() * (Minv * L);\n  // Zero linear term\n  B = VectorXd::Zero(V.rows(),1);\n\n  // Lower and upper bound\n  lx = VectorXd::Zero(V.rows(),1);\n  ux = VectorXd::Ones(V.rows(),1);\n\n  // Equality constraint constrain solution to sum to 1\n  Beq.resize(1,1);\n  Beq(0) = 0.08;\n  Aeq = M.diagonal().sparseView().transpose();\n  // (Empty inequality constraints)\n  solve(viewer);\n  cout<<\n    \"Press '.' to increase scale and resolve.\"<<endl<<\n    \"Press ',' to decrease scale and resolve.\"<<endl;\n\n  viewer.launch();\n}\n", "meta": {"hexsha": "f158f5f9b919d5a9aa28e66df29f58628112dcc4", "size": 2238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/tutorial/305_QuadraticProgramming/main.cpp", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "isometric-deformation/ext/libigl/tutorial/305_QuadraticProgramming/main.cpp", "max_issues_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_issues_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isometric-deformation/ext/libigl/tutorial/305_QuadraticProgramming/main.cpp", "max_forks_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_forks_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8367346939, "max_line_length": 76, "alphanum_fraction": 0.6434316354, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875223, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6347274415966946}}
{"text": "/**\n * @file engquistoshernumericalflux_main.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 <Eigen/Core>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\n#include \"engquistoshernumericalflux.h\"\n\n/* SAM_LISTING_BEGIN_1 */\nconst static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                       Eigen::DontAlignCols, \", \", \"\\n\");\n\ndouble u0(double x) { return (0.0 < x && x <= 1.0) ? 1.0 : -1.0; }\n\nint main() {\n  unsigned int N = 100;\n  double a = -1.2;\n  double b = 2.2;\n  double T = 1.0;\n  double h = (b - a) / N;\n\n  Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(N, a - 0.5 * h, b - 0.5 * h);\n  Eigen::VectorXd uinitial = x.unaryExpr(std::ref(u0));\n  Eigen::VectorXd ufinal =\n      EngquistOsherNumericalFlux::solveCP(a, b, uinitial, T);\n\n  //====================\n  // Your code goes here\n  // Use std::ofstream to write the solution to\n  // the file \"ufinal.csv\". To plot this file\n  // you may uncomment the following line:\n  // std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot_solution.py \"\n  // CURRENT_BINARY_DIR \"/ufinal.csv \" CURRENT_BINARY_DIR \"/ufinal.eps\");\n  //====================\n\n  return 0;\n}\n/* SAM_LISTING_END_1 */\n", "meta": {"hexsha": "e91a2ac113b9193e9526c182073e04972caf8082", "size": 1285, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/EngquistOsherNumericalFlux/templates/engquistoshernumericalflux_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/EngquistOsherNumericalFlux/templates/engquistoshernumericalflux_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/EngquistOsherNumericalFlux/templates/engquistoshernumericalflux_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 27.9347826087, "max_line_length": 78, "alphanum_fraction": 0.6241245136, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.8221891370573388, "lm_q1q2_score": 0.6346013308015641}}
{"text": "#include \"math/Base.h\"\n#include \"operation/field/setup.h\"\n\n#include <boost/test/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(Base)\n\nBOOST_AUTO_TEST_CASE(intlog) {\n  unsigned int p2w = math::intlog(0);\n  BOOST_CHECK_EQUAL(p2w, 0);\n  p2w = math::intlog(1);\n  BOOST_CHECK_EQUAL(p2w, 0);\n  p2w = math::intlog(2);\n  BOOST_CHECK_EQUAL(p2w, 1);\n  for (unsigned int i = 0; i < sizeof(int) * 8; ++i) {\n    p2w = math::intlog(1 << i);\n    BOOST_CHECK_EQUAL(p2w, i);\n  }\n  for (unsigned int i = 1; i < sizeof(int) * 8; ++i) {\n    p2w = math::intlog((1 << i) + 1);\n    BOOST_CHECK_EQUAL(p2w, i + 1);\n  }\n  for (unsigned int i = 2; i < sizeof(int)*8; i++) {\n    p2w = math::intlog((1 << i) - 1);\n    BOOST_CHECK_EQUAL(p2w, i);\n  }\n  // Check when every bit is 1\n  p2w = math::intlog(static_cast<unsigned>(-1));\n  BOOST_CHECK_EQUAL(p2w, sizeof(int) * 8);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n\nbool init_unit_test() {\n  return true;\n}\n", "meta": {"hexsha": "2e9b4cc0a8ac703d89d0d47fcb533b3430a24adc", "size": 908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/Base.t.cpp", "max_stars_repo_name": "cherba29/slp-poly", "max_stars_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/Base.t.cpp", "max_issues_repo_name": "cherba29/slp-poly", "max_issues_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "max_issues_repo_licenses": ["Apache-2.0"], "max_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/Base.t.cpp", "max_forks_repo_name": "cherba29/slp-poly", "max_forks_repo_head_hexsha": "0812e433c19c3ae036610c50ce54bf2d8cb8bf93", "max_forks_repo_licenses": ["Apache-2.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.8947368421, "max_line_length": 54, "alphanum_fraction": 0.6266519824, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6346013190315377}}
{"text": "#include <iostream>\n#include <UnitTest++.h>\n\n#include <Eigen/Dense>\n\n#include \"rbdl/Model.h\"\n#include \"rbdl/Dynamics.h\"\n#include \"rbdl/rbdl_mathutils.h\"\n\n#include \"Fixtures.h\"\n#include \"Human36Fixture.h\"\n#include \"ModelAD.h\"\n#include \"ModelED.h\"\n#include \"DynamicsAD.h\"\n#include \"DynamicsED.h\"\n#include \"DynamicsFD.h\"\n#include \"DynamicsFDC.h\"\n#include \"rbdl_mathutilsAD.h\"\n\n#include \"ModelCheckADvsFD.h\"\n\nusing namespace std;\nusing namespace RigidBodyDynamics;\nusing namespace RigidBodyDynamics::Math;\n\nstatic const double TEST_PREC = 1.0e-8;\nstatic const double EPS = std::sqrt(numeric_limits<double>::epsilon());\n\n// -----------------------------------------------------------------------------\n/*! \\brief We want to compute the derivative of d X(q(t)) / dt\n*/\n\ntemplate <typename T>\nvoid analytic_derivative_of_spatial_transform(\n  T & obj,\n  std::function<SpatialTransform (const double &)> get_transform,\n  const SpatialVector & S,\n  const double TEST_PRECISION=1e-8\n) {\n  const VectorNd Q = VectorNd::Random(1);\n  const VectorNd Qdot = VectorNd::Random(1);\n\n  // nominal evaluation\n  SpatialMatrix X = get_transform(Q(0)).toMatrix();\n\n  // derivative evaluation\n  SpatialMatrix X_fd = get_transform(Q(0) + EPS * Qdot(0)).toMatrix();\n  X_fd = (X_fd - X) / EPS;\n\n  // analytic derivative\n  SpatialMatrix X_ad = -crossm(S*Qdot(0))*X;\n\n  // print results\n  const SpatialMatrix X_err = (X_ad - X_fd).cwiseAbs();\n  const double error = X_err.maxCoeff();\n\n  if (error > 1e-7)\n  {\n    cout << \"S:\" << S.transpose() << endl;\n    // cout << \"w:\" << w.transpose() << endl;\n    // cout << \"v0:\" << v0.transpose() << endl;\n\n    cout << \"X_fd: \" << endl << X_fd << endl;\n    cout << \"X_ad: \" << endl << X_ad << endl;\n    cout << \"error(max): \" << \" (\" << error << \")\" << endl\n      << endl << X_err << endl;\n    cout << endl;\n  }\n\n  // test result\n  CHECK_ARRAY_CLOSE(X_fd.data(), X_ad.data(), X.size(), TEST_PRECISION);\n}\n\nTEST(Xrotx_analytic_derivative_of_spatial_transform){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(0) = 1.0;\n  analytic_derivative_of_spatial_transform(*this, Xrotx, S, 1e-8);\n}\n\nTEST(Xroty_analytic_derivative_of_spatial_transform){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(1) = 1.0;\n  analytic_derivative_of_spatial_transform(*this, Xroty, S, 1e-8);\n}\n\nTEST(Xrotz_analytic_derivative_of_spatial_transform){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(2) = 1.0;\n  analytic_derivative_of_spatial_transform(*this, Xrotz, S, 1e-8);\n}\n\nTEST(Xtransx_analytic_derivative_of_spatial_transform){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(3) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransx\n    = [](const double &q) { return Xtrans(Vector3d(q, 0., 0.)); };\n  analytic_derivative_of_spatial_transform(*this, Xtransx, S, 1e-8);\n}\n\nTEST(Xtransy_analytic_derivative_of_spatial_transform){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(4) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransy\n    = [](const double &q) { return Xtrans(Vector3d(0., q, 0.)); };\n  analytic_derivative_of_spatial_transform(*this, Xtransy, S, 1e-8);\n}\n\nTEST(Xtransz_analytic_derivative_of_spatial_transform){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(5) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransz\n    = [](const double &q) { return Xtrans(Vector3d(0., 0., q)); };\n  analytic_derivative_of_spatial_transform(*this, Xtransz, S, 1e-8);\n}\n\n// -----------------------------------------------------------------------------\n/*! \\brief We want to compute the derivative of d X(q(t)) / dt\n*/\n\nSpatialTransform get_random_spatial_transform()\n{\n  Matrix3d Z = Matrix3d::Random();\n  Eigen::ColPivHouseholderQR<Eigen::Matrix3d> dec(Z);\n  Eigen::Matrix3d Q = dec.householderQ();\n  Eigen::Matrix3d R = dec.matrixQR();\n  Eigen::Vector3d d = R.diagonal();\n  Eigen::Vector3d ph = d.cwiseQuotient(d.cwiseAbs());\n  // std::cout << \"ph = \" << ph.transpose() << std::endl;\n  // std::cout << \"Q = \" << endl << Q << std::endl;\n  Q = Q.array().rowwise() * ph.transpose().array();\n  // std::cout << \"Q = \" << endl << Q << std::endl;\n\n  // std::cout << \"Q = \" << endl << Q << std::endl;\n  const Eigen::Matrix3d Q_err = (Q*Q.transpose() - Eigen::Matrix3d::Identity()).cwiseAbs();\n  const double error = Q_err.maxCoeff();;\n\n  if (error > 1e-14)\n  {\n    std::cerr << \"Not orthogonal Q\" << std::endl;\n    std::cerr << \"Q * Q.transpose() = \" << endl << Q * Q.transpose() << std::endl;\n    abort();\n  }\n\n\n  return SpatialTransform(Q, Vector3d::Random());\n}\n\nEigen::Index get_index_of_one(const SpatialVector& S)\n{\n  for(Eigen::Index i=0; i < S.size(); ++i){\n    if(S(i) != 0.0){\n      return i;\n    }\n  }\n  return S.size();\n}\n\nSpatialMatrix spatialDerivativeToMatrix (\n  SpatialTransform const& X,\n  SpatialTransform const& X_ad\n) {\n  SpatialMatrix ret;\n\n  ret.block<3, 3>(0, 0) = X_ad.E;\n  ret.block<3, 3>(0, 3) = Matrix3d::Zero();\n  ret.block<3, 3>(3, 0)\n    = -(X_ad.E*VectorCrossMatrix(X.r) + X.E * VectorCrossMatrix(X_ad.r));\n  ret.block<3, 3>(3, 3) = ret.block<3, 3>(0, 0);\n\n  return ret;\n}\n\n\ntemplate <typename T>\nvoid analytic_derivative_of_spatial_transform_using_plt(\n  T & obj,\n  std::function<SpatialTransform (const double &)> get_transform,\n  const SpatialVector & S,\n  const double TEST_PRECISION=1e-8\n) {\n  const VectorNd Q = VectorNd::Random(1);\n  // const VectorNd Qdot = VectorNd::Random(1);\n  VectorNd Qdot = VectorNd::Random(1);\n  Qdot << 1.0;\n\n  // nominal evaluation\n  SpatialTransform Y = get_random_spatial_transform();\n  SpatialTransform X = get_transform(Q(0))*Y;\n\n  // derivative evaluation\n  SpatialTransform X_fd = get_transform(Q(0) + EPS * Qdot(0))*Y;\n  X_fd = (X_fd - X) * (1. / EPS);\n\n  SpatialMatrix X_an = -crossm(S*Qdot(0))*X.toMatrix();\n\n  // analytic derivative\n  const Math::Matrix3d wx = VectorCrossMatrix(S.head(3)*Qdot);\n  // const Math::Matrix3d v0x = VectorCrossMatrix(S.tail(3)*Qdot);\n  SpatialTransform X_ad;\n\n  // if (get_index_of_one(S) < 3)\n  // {\n  //   X_ad = SpatialTransform(-wx*X.E, Vector3d::Zero());\n  // }\n  // else if (get_index_of_one(S) < 6)\n  // {\n  //   X_ad = SpatialTransform(Matrix3d::Zero(), Qdot(0) * S.tail(3).transpose() * X.E);\n  // }\n  // else\n  // {\n  //   cout << \"Index out of bounds of S\" << endl;\n  //   abort();\n  // }\n\n  X_ad = SpatialTransform(-wx*X.E, Qdot(0) * S.tail(3).transpose() * X.E);\n\n  // print results\n  SpatialMatrix SD_ad = spatialDerivativeToMatrix(X, X_ad);\n  SpatialMatrix SD_fd = spatialDerivativeToMatrix(X, X_fd);\n\n  const SpatialMatrix X_err = (SD_ad - SD_fd).cwiseAbs();\n  const double error = X_err.maxCoeff();\n\n  if (error > TEST_PRECISION)\n  {\n    cout << \"Q:\" << Q.transpose() << endl;\n    cout << \"Qdot:\" << Qdot.transpose() << endl;\n    cout << \"S:\" << S.transpose() << endl;\n    // cout << \"w:\" << w.transpose() << endl;\n    // cout << \"v0:\" << v0.transpose() << endl;\n    // cout << \"wx:\" << wx << endl;\n    // cout << \"v0x:\" << v0x << endl;\n\n    // cout << \"X: \" << endl << X << endl;\n    // cout << \"X_fd: \" << endl << X_fd << endl;\n    // cout << \"X_ad: \" << endl << X_ad << endl;\n    cout << \"X_fd: \" << endl << SD_fd << endl;\n    cout << \"X_ad: \" << endl << SD_ad << endl;\n    cout << \"X_an: \" << endl << X_an << endl;\n    cout << \"error(max): \" << \" (\" << error << \")\" << endl\n      << endl << X_err << endl;\n  }\n\n  // test result\n  CHECK_ARRAY_CLOSE(\n    X_ad.E.data(),\n    X_fd.E.data(),\n    X.E.size(),\n    TEST_PRECISION\n  );\n\n  CHECK_ARRAY_CLOSE(\n    X_ad.r.data(),\n    X_fd.r.data(),\n    X.r.size(),\n    TEST_PRECISION\n  );\n\n  CHECK_ARRAY_CLOSE(\n    spatialDerivativeToMatrix(X, X_ad).data(),\n    spatialDerivativeToMatrix(X, X_fd).data(),\n    X.toMatrix().size(),\n    TEST_PRECISION\n  );\n}\n\nTEST(Xrotx_analytic_derivative_of_spatial_transform_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(0) = 1.0;\n  analytic_derivative_of_spatial_transform_using_plt(*this, Xrotx, S, 1e-7);\n}\n\nTEST(Xroty_analytic_derivative_of_spatial_transform_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(1) = 1.0;\n  analytic_derivative_of_spatial_transform_using_plt(*this, Xroty, S, 1e-8);\n}\n\nTEST(Xrotz_analytic_derivative_of_spatial_transform_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(2) = 1.0;\n  analytic_derivative_of_spatial_transform_using_plt(*this, Xrotz, S, 1e-8);\n}\n\nTEST(Xtransx_analytic_derivative_of_spatial_transform_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(3) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransx\n    = [](const double &q) { return Xtrans(Vector3d(q, 0., 0.)); };\n  analytic_derivative_of_spatial_transform_using_plt(*this, Xtransx, S, 1e-8);\n}\n\nTEST(Xtransy_analytic_derivative_of_spatial_transform_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(4) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransy\n    = [](const double &q) { return Xtrans(Vector3d(0., q, 0.)); };\n  analytic_derivative_of_spatial_transform_using_plt(*this, Xtransy, S, 1e-8);\n}\n\nTEST(Xtransz_analytic_derivative_of_spatial_transform_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(5) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransz\n    = [](const double &q) { return Xtrans(Vector3d(0., 0., q)); };\n  analytic_derivative_of_spatial_transform_using_plt(*this, Xtransz, S, 1e-8);\n}\n\n// -----------------------------------------------------------------------------\n/*! \\brief We want to compute the derivative of d X(q(t)) / dt * v\n*/\ntemplate <typename T>\nvoid analytic_derivative_of_spatial_transform_times_v(\n  T & obj,\n  std::function<SpatialTransform (const double &)> get_transform,\n  const SpatialVector & S,\n  const double TEST_PRECISION=1e-8\n) {\n  const VectorNd Q = VectorNd::Random(1);\n  const VectorNd Qdot = VectorNd::Random(1);\n\n  // nominal evaluation\n  SpatialTransform X = get_transform(Q(0));\n  SpatialVector v = SpatialVector::Random();\n  SpatialVector res = X.apply(v);\n\n  // derivative evaluation\n  SpatialTransform X_fd = get_transform(Q(0) + EPS * Qdot(0));\n  SpatialVector res_fd = (X_fd.apply(v) - res) / EPS;\n\n  // analytic derivative\n  SpatialVector res_ad = -crossm(S*Qdot(0), res);\n\n  // print results\n  // cout << \"res_fd:      \" << res_fd.transpose() << endl;\n  // cout << \"res_ad:      \" << res_ad.transpose() << endl;\n  // cout << \"error(max):  \" << (res_ad - res_fd).cwiseAbs().transpose()\n  //      << \" (\" << (res_ad - res_fd).cwiseAbs().maxCoeff() << \")\" << endl;\n  // cout << endl;\n\n  // test result\n  CHECK_ARRAY_CLOSE(res_fd.data(), res_ad.data(), res.size(), TEST_PRECISION);\n}\n\nTEST(Xrotx_analytic_derivative_of_spatial_transform_times_v){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(0) = 1.0;\n  analytic_derivative_of_spatial_transform_times_v(*this, Xrotx, S, 1e-8);\n}\n\nTEST(Xroty_analytic_derivative_of_spatial_transform_times_v){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(1) = 1.0;\n  analytic_derivative_of_spatial_transform_times_v(*this, Xroty, S, 1e-7);\n}\n\nTEST(Xrotz_analytic_derivative_of_spatial_transform_times_v){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(2) = 1.0;\n  analytic_derivative_of_spatial_transform_times_v(*this, Xrotz, S, 1e-8);\n}\n\nTEST(Xtransx_analytic_derivative_of_spatial_transform_times_v){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(3) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransx\n    = [](const double &q) { return Xtrans(Vector3d(q, 0., 0.)); };\n  analytic_derivative_of_spatial_transform_times_v(*this, Xtransx, S, 1e-8);\n}\n\nTEST(Xtransy_analytic_derivative_of_spatial_transform_times_v){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(4) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransy\n    = [](const double &q) { return Xtrans(Vector3d(0., q, 0.)); };\n  analytic_derivative_of_spatial_transform_times_v(*this, Xtransy, S, 1e-8);\n}\n\nTEST(Xtransz_analytic_derivative_of_spatial_transform_times_v){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(5) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransz\n    = [](const double &q) { return Xtrans(Vector3d(0., 0., q)); };\n  analytic_derivative_of_spatial_transform_times_v(*this, Xtransz, S, 1e-8);\n}\n\n// -----------------------------------------------------------------------------\n/*! \\brief We want to compute the derivative of d X(q(t)) / dt * v\n*/\ntemplate <typename T>\nvoid analytic_derivative_of_spatial_transform_times_v_using_plt(\n  T & obj,\n  std::function<SpatialTransform (const double &)> get_transform,\n  const SpatialVector & S,\n  const double TEST_PRECISION=1e-8\n) {\n  const VectorNd Q = VectorNd::Random(1);\n  const VectorNd Qdot = VectorNd::Random(1);\n\n  // nominal evaluation\n  SpatialTransform X = get_transform(Q(0));\n  SpatialVector v = SpatialVector::Random();\n  SpatialVector res = X.apply(v);\n\n  // derivative evaluation\n  SpatialTransform X_fd = get_transform(Q(0) + EPS * Qdot(0));\n  SpatialVector res_fd = (X_fd.apply(v) - res) / EPS;\n\n\n  // analytic derivative\n  SpatialVector res_an = -crossm(S*Qdot(0), res);\n\n  // recover derivative from spatial transform derivative\n  const Math::Matrix3d wx = VectorCrossMatrix(S.head(3)*Qdot);\n  SpatialTransform X_ad = SpatialTransform(-wx*X.E, Qdot(0) * S.tail(3).transpose() * X.E);\n\n  SpatialVector res_ad; // =  X_ad.apply(v)\n  res_ad.head(3) = X_ad.E * v.head(3);\n  res_ad.tail(3) = X_ad.E * ( v.tail<3>() + v.head<3>().cross(X.r))\n    - X.E * X_ad.r.cross(v.head<3>()) ;\n\n  // print results\n  const SpatialVector v_err = (res_ad - res_fd).cwiseAbs();\n  const double error = v_err.maxCoeff();\n\n  if (error > TEST_PRECISION)\n  {\n    cout << \"Q:\" << Q.transpose() << endl;\n    cout << \"Qdot:\" << Qdot.transpose() << endl;\n    cout << \"S:\" << S.transpose() << endl;\n    // cout << \"w:\" << w.transpose() << endl;\n    // cout << \"v0:\" << v0.transpose() << endl;\n    // cout << \"wx:\" << wx << endl;\n    // cout << \"v0x:\" << v0x << endl;\n\n    // cout << \"X: \" << endl << X << endl;\n    // cout << \"X_fd: \" << endl << X_fd << endl;\n    // cout << \"X_ad: \" << endl << X_ad << endl;\n    cout << \"v_fd: \" << res_fd.transpose() << endl;\n    cout << \"v_ad: \" << res_ad.transpose() << endl;\n    cout << \"v_an: \" << res_an.transpose() << endl;\n    cout << \"error(max): \" << \" (\" << error << \")\" << endl\n      << endl << v_err.transpose() << endl;\n  }\n\n  // test result\n  CHECK_ARRAY_CLOSE(res_fd.data(), res_ad.data(), res.size(), TEST_PRECISION);\n}\n\nTEST(Xrotx_analytic_derivative_of_spatial_transform_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(0) = 1.0;\n  analytic_derivative_of_spatial_transform_times_v_using_plt(*this, Xrotx, S, 1e-8);\n}\n\nTEST(Xroty_analytic_derivative_of_spatial_transform_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(1) = 1.0;\n  analytic_derivative_of_spatial_transform_times_v_using_plt(*this, Xroty, S, 1e-7);\n}\n\nTEST(Xrotz_analytic_derivative_of_spatial_transform_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(2) = 1.0;\n  analytic_derivative_of_spatial_transform_times_v_using_plt(*this, Xrotz, S, 1e-8);\n}\n\nTEST(Xtransx_analytic_derivative_of_spatial_transform_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(3) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransx\n    = [](const double &q) { return Xtrans(Vector3d(q, 0., 0.)); };\n  analytic_derivative_of_spatial_transform_times_v_using_plt(*this, Xtransx, S, 1e-8);\n}\n\nTEST(Xtransy_analytic_derivative_of_spatial_transform_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(4) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransy\n    = [](const double &q) { return Xtrans(Vector3d(0., q, 0.)); };\n  analytic_derivative_of_spatial_transform_times_v_using_plt(*this, Xtransy, S, 1e-8);\n}\n\nTEST(Xtransz_analytic_derivative_of_spatial_transform_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(5) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransz\n    = [](const double &q) { return Xtrans(Vector3d(0., 0., q)); };\n  analytic_derivative_of_spatial_transform_times_v_using_plt(*this, Xtransz, S, 1e-8);\n}\n\n// -----------------------------------------------------------------------------\n/*! \\brief We want to compute the derivative of d X(q(t))^* / dt * f\n*/\ntemplate <typename T>\nvoid analytic_derivative_of_spatial_transform_transpose_times_f(\n  T & obj,\n  std::function<SpatialTransform (const double &)> get_transform,\n  const SpatialVector & S,\n  const double TEST_PRECISION=1e-8\n) {\n  const VectorNd Q = VectorNd::Random(1);\n  const VectorNd Qdot = VectorNd::Random(1);\n\n  // nominal evaluation\n  SpatialTransform X = get_transform(Q(0));\n  SpatialVector f = SpatialVector::Random();\n  SpatialVector res = X.applyTranspose(f);\n\n  // derivative evaluation\n  SpatialTransform X_fd = get_transform(Q(0) + EPS * Qdot(0));\n  SpatialVector res_fd = (X_fd.applyTranspose(f) - res) / EPS;\n\n  // analytic derivative\n  SpatialVector res_ad = crossf(S*Qdot(0), res);\n\n  // print results\n  // cout << \"res_fd:      \" << res_fd.transpose() << endl;\n  // cout << \"res_ad:      \" << res_ad.transpose() << endl;\n  // cout << \"error(max):  \" << (res_ad - res_fd).cwiseAbs().transpose()\n  //      << \" (\" << (res_ad - res_fd).cwiseAbs().maxCoeff() << \")\" << endl;\n  // cout << endl;\n\n  // test result\n  CHECK_ARRAY_CLOSE(res_fd.data(), res_ad.data(), res.size(), TEST_PRECISION);\n}\n\nTEST(Xrotx_analytic_derivative_of_spatial_transform_transpose_times_f){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(0) = 1.0;\n  analytic_derivative_of_spatial_transform_transpose_times_f(*this, Xrotx, S, 1e-8);\n}\n\nTEST(Xroty_analytic_derivative_of_spatial_transform_transpose_times_f){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(1) = 1.0;\n  analytic_derivative_of_spatial_transform_transpose_times_f(*this, Xroty, S, 1e-7);\n}\n\nTEST(Xrotz_analytic_derivative_of_spatial_transform_transpose_times_f){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(2) = 1.0;\n  analytic_derivative_of_spatial_transform_transpose_times_f(*this, Xrotz, S, 1e-8);\n}\n\nTEST(Xtransx_analytic_derivative_of_spatial_transform_transpose_times_f){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(3) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransx\n    = [](const double &q) { return Xtrans(Vector3d(q, 0., 0.)); };\n  analytic_derivative_of_spatial_transform_transpose_times_f(*this, Xtransx, S, 1e-8);\n}\n\nTEST(Xtransy_analytic_derivative_of_spatial_transform_transpose_times_f){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(4) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransy\n    = [](const double &q) { return Xtrans(Vector3d(0., q, 0.)); };\n  analytic_derivative_of_spatial_transform_transpose_times_f(*this, Xtransy, S, 1e-8);\n}\n\nTEST(Xtransz_analytic_derivative_of_spatial_transform_transpose_times_f){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(5) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransz\n    = [](const double &q) { return Xtrans(Vector3d(0., 0., q)); };\n  analytic_derivative_of_spatial_transform_transpose_times_f(*this, Xtransz, S, 1e-8);\n}\n\n// -----------------------------------------------------------------------------\n/*! \\brief We want to compute the derivative of d X(q(t)) / dt * v\n*/\ntemplate <typename T>\nvoid analytic_derivative_of_spatial_transform_inverse_times_v_using_plt(\n  T & obj,\n  std::function<SpatialTransform (const double &)> get_transform,\n  const SpatialVector & S,\n  const double TEST_PRECISION=1e-8\n) {\n  const VectorNd Q = VectorNd::Random(1);\n  const VectorNd Qdot = VectorNd::Random(1);\n\n  // nominal evaluation\n  SpatialTransform X = get_transform(Q(0));\n  SpatialVector v = SpatialVector::Random();\n  SpatialVector res = X.inverse().apply(v);\n\n  // derivative evaluation\n  SpatialTransform X_fd = get_transform(Q(0) + EPS * Qdot(0));\n  SpatialVector res_fd = (X_fd.inverse().apply(v) - res) / EPS;\n\n\n  // analytic derivative\n  SpatialVector res_an = -crossm(S*Qdot(0), res);\n\n  // recover derivative from spatial transform derivative\n  const Math::Matrix3d wx = VectorCrossMatrix(S.head(3)*Qdot);\n  SpatialTransform X_ad = SpatialTransform(-wx*X.E, Qdot(0) * S.tail(3).transpose() * X.E);\n\n  SpatialVector res_ad; // =  X_ad.apply(v)\n  res_ad.head(3) = X_ad.E.transpose() * v.head(3);\n  res_ad.tail(3) = X_ad.E.transpose() * (\n    v.tail<3>() - v.head<3>().cross(X.E*X.r)\n  ) + X.E.transpose() * (X_ad.E*X.r + X.E*X_ad.r).cross(v.head<3>()) ;\n\n  // print results\n  const SpatialVector v_err = (res_ad - res_fd).cwiseAbs();\n  const double error = v_err.maxCoeff();\n\n  if (error > TEST_PRECISION)\n  {\n    cout << \"Q:\" << Q.transpose() << endl;\n    cout << \"Qdot:\" << Qdot.transpose() << endl;\n    cout << \"S:\" << S.transpose() << endl;\n    // cout << \"w:\" << w.transpose() << endl;\n    // cout << \"v0:\" << v0.transpose() << endl;\n    // cout << \"wx:\" << wx << endl;\n    // cout << \"v0x:\" << v0x << endl;\n\n    // cout << \"X: \" << endl << X << endl;\n    // cout << \"X_fd: \" << endl << X_fd << endl;\n    // cout << \"X_ad: \" << endl << X_ad << endl;\n    cout << \"v_fd: \" << res_fd.transpose() << endl;\n    cout << \"v_ad: \" << res_ad.transpose() << endl;\n    cout << \"v_an: \" << res_an.transpose() << endl;\n    cout << \"error(max): \" << \" (\" << error << \")\" << endl\n      << endl << v_err.transpose() << endl;\n  }\n\n  // test result\n  CHECK_ARRAY_CLOSE(res_fd.data(), res_ad.data(), res.size(), TEST_PRECISION);\n}\n\nTEST(Xrotx_analytic_derivative_of_spatial_transform_inverse_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(0) = 1.0;\n  analytic_derivative_of_spatial_transform_inverse_times_v_using_plt(*this, Xrotx, S, 1e-8);\n}\n\n\nTEST(Xroty_analytic_derivative_of_spatial_transform_inverse_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(1) = 1.0;\n  analytic_derivative_of_spatial_transform_inverse_times_v_using_plt(*this, Xroty, S, 1e-7);\n}\n\nTEST(Xrotz_analytic_derivative_of_spatial_transform_inverse_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(2) = 1.0;\n  analytic_derivative_of_spatial_transform_inverse_times_v_using_plt(*this, Xrotz, S, 1e-8);\n}\n\nTEST(Xtransx_analytic_derivative_of_spatial_transform_inverse_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(3) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransx\n    = [](const double &q) { return Xtrans(Vector3d(q, 0., 0.)); };\n  analytic_derivative_of_spatial_transform_inverse_times_v_using_plt(*this, Xtransx, S, 1e-8);\n}\n\nTEST(Xtransy_analytic_derivative_of_spatial_transform_inverse_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(4) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransy\n    = [](const double &q) { return Xtrans(Vector3d(0., q, 0.)); };\n  analytic_derivative_of_spatial_transform_inverse_times_v_using_plt(*this, Xtransy, S, 1e-8);\n}\n\nTEST(Xtransz_analytic_derivative_of_spatial_transform_inverse_times_v_using_plt){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(5) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransz\n    = [](const double &q) { return Xtrans(Vector3d(0., 0., q)); };\n  analytic_derivative_of_spatial_transform_inverse_times_v_using_plt(*this, Xtransz, S, 1e-8);\n}\n\n\n// -----------------------------------------------------------------------------\n/*! \\brief We want to compute the derivative of d ^B I(q(t)) / dt\n*/\n\ntemplate <typename T>\nvoid analytic_derivative_of_spatial_inertia(\n  T & obj,\n  std::function<SpatialTransform (const double &)> get_transform,\n  const SpatialVector & S,\n  const double TEST_PRECISION=1e-8\n) {\n  const VectorNd Q = VectorNd::Random(1);\n  const VectorNd Qdot = VectorNd::Random(1);\n\n  VectorNd v = VectorNd::Random(1);\n  const double m = v(0);\n  const Vector3d h = Vector3d::Random();\n  const Matrix3d Ic = Matrix3d::Random();\n  const SpatialRigidBodyInertia IC = SpatialRigidBodyInertia(m, h, Ic);\n\n  // nominal evaluation\n  SpatialTransform X = get_transform(Q(0));\n  SpatialMatrix I = X.applyTranspose(IC).toMatrix();\n\n  // derivative evaluation\n  SpatialTransform X_fd = get_transform(Q(0) + EPS * Qdot(0));\n  SpatialMatrix I_fd = (X_fd.applyTranspose(IC).toMatrix() - I) / EPS;\n\n  // analytic derivative\n  SpatialMatrix I_ad = crossf(S*Qdot(0))*I - I*crossm(S*Qdot(0));\n\n  // print results\n  // cout << \"I_fd: \" << endl << I_fd.transpose() << endl;\n  // cout << \"I_ad: \" << endl << I_ad.transpose() << endl;\n  // cout << \"error(max): \" << endl << (I_ad - I_fd).cwiseAbs().transpose()\n  //      << endl << \" (\" << (I_ad - I_fd).cwiseAbs().maxCoeff() << \")\" << endl;\n  // cout << endl;\n\n  // test Iult\n  CHECK_ARRAY_CLOSE(I_fd.data(), I_ad.data(), I_fd.size(), TEST_PRECISION);\n}\n\nTEST(Xrotx_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(0) = 1.0;\n  analytic_derivative_of_spatial_inertia(*this, Xrotx, S, 1e-7);\n}\n\nTEST(Xroty_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(1) = 1.0;\n  analytic_derivative_of_spatial_inertia(*this, Xroty, S, 1e-7);\n}\n\nTEST(Xrotz_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(2) = 1.0;\n  analytic_derivative_of_spatial_inertia(*this, Xrotz, S, 1e-7);\n}\n\nTEST(Xtransx_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(3) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransx\n    = [](const double &q) { return Xtrans(Vector3d(q, 0., 0.)); };\n  analytic_derivative_of_spatial_inertia(*this, Xtransx, S, 1e-8);\n}\n\nTEST(Xtransy_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(4) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransy\n    = [](const double &q) { return Xtrans(Vector3d(0., q, 0.)); };\n  analytic_derivative_of_spatial_inertia(*this, Xtransy, S, 1e-8);\n}\n\nTEST(Xtransz_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(5) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransz\n    = [](const double &q) { return Xtrans(Vector3d(0., 0., q)); };\n  analytic_derivative_of_spatial_transform_times_v(*this, Xtransz, S, 1e-8);\n}\n\n// -----------------------------------------------------------------------------\n/*! \\brief We want to compute the derivative of d ^B I(q(t)) / dt\n*/\n\n// SpatialRigidBodyInertia derivative_of_X_applyTranspose_rbi(\n//   const SpatialRigidBodyInertia& I,\n//   const SpatialVector& S,\n//   const SpatialDirection& Qdirs\n// ) {\n//   return SpatialRigidBodyInertia();\n// }\n\nMatrix3d cross(Vector3d r) {\n  return Matrix3d (\n        0., -r[2],  r[1],\n      r[2],    0., -r[0],\n     -r[1],  r[0],    0.\n  );\n};\n\n\ntemplate <typename T>\nvoid efficient_analytic_derivative_of_spatial_inertia(\n  T & obj,\n  std::function<SpatialTransform (const double &)> get_transform,\n  const SpatialVector & S,\n  const double TEST_PRECISION=1e-8\n) {\n  const VectorNd Q = VectorNd::Random(1);\n  const VectorNd Qdot = VectorNd::Random(1);\n\n  VectorNd v = VectorNd::Random(1);\n  const double m = v(0);\n  const Vector3d h = Vector3d::Random();\n  const Matrix3d Ic = Matrix3d::Random();\n  const SpatialRigidBodyInertia IC = SpatialRigidBodyInertia(m, h, Ic);\n\n  // nominal evaluation\n  SpatialTransform X_T = Xrotx(0.345)*Xtrans(Vector3d(0.3, 0.2, 0.1));\n  SpatialTransform X = get_transform(Q(0))*X_T;\n  SpatialRigidBodyInertia I = X.applyTranspose(IC);\n\n  // derivative evaluation\n  SpatialTransform X_fd = get_transform(Q(0) + EPS * Qdot(0))*X_T;\n  SpatialRigidBodyInertia I_fd = (X_fd.applyTranspose(IC) - I) * (1.0 / EPS);\n\n  // analytic derivative\n  // SpatialMatrix I_ad = crossf(S*Qdot(0))*I - I*crossm(S*Qdot(0));\n  // const Math::SpatialVector imv = S;\n  const Math::SpatialVector imv = X.inverse().apply(S);\n  SpatialMatrix I_an = crossf(imv*Qdot(0))*I.toMatrix() - I.toMatrix()*crossm(imv*Qdot(0));\n\n  // separate vector into 3D components\n  Vector3d w = imv.head(3)*Qdot(0);\n  Vector3d v0 = imv.tail(3)*Qdot(0);\n\n  SpatialRigidBodyInertia I_ad\n    = SpatialRigidBodyInertia (\n        0,\n        w.cross(I.h) + I.m * v0,\n        Matrix3d(\n          -I.Iyx*w[2] + I.Izx*w[1] - I.Iyx*w[2] + I.Izx*w[1] + 2.*(I.h[1]*v0[1] + I.h[2]*v0[2]),\n           I.Ixx*w[2] - I.Izx*w[0] - I.Iyy*w[2] + I.Izy*w[1] -     I.h[0]*v0[1] - I.h[1]*v0[0] ,\n          -I.Ixx*w[1] + I.Iyx*w[0] - I.Izy*w[2] + I.Izz*w[1] -     I.h[0]*v0[2] - I.h[2]*v0[0] ,\n\n           I.Ixx*w[2] - I.Iyy*w[2] + I.Izy*w[1] - I.Izx*w[0] -     I.h[0]*v0[1] - I.h[1]*v0[0] ,\n           I.Iyx*w[2] + I.Iyx*w[2] - I.Izy*w[0] - I.Izy*w[0] + 2.*(I.h[0]*v0[0] + I.h[2]*v0[2]),\n           I.Izx*w[2] - I.Iyx*w[1] + I.Iyy*w[0] - I.Izz*w[0] -     I.h[1]*v0[2] - I.h[2]*v0[1] ,\n\n          -I.Ixx*w[1] + I.Iyx*w[0] - I.Izy*w[2] + I.Izz*w[1] -     I.h[0]*v0[2] - I.h[2]*v0[0] ,\n          -I.Iyx*w[1] + I.Iyy*w[0] + I.Izx*w[2] - I.Izz*w[0] -     I.h[1]*v0[2] - I.h[2]*v0[1] ,\n          -I.Izx*w[1] + I.Izy*w[0] - I.Izx*w[1] + I.Izy*w[0] + 2.*(I.h[0]*v0[0] + I.h[1]*v0[1])\n        )\n    );\n\n\n  const SpatialMatrix I_err = (I_ad.toMatrix() - I_fd.toMatrix()).cwiseAbs();\n  const double error = I_err.maxCoeff();\n\n  if (error > 1e-7) {\n    cout << \"S:\" << S.transpose() << endl;\n    cout << \"imv:\\t\" << imv.transpose() << endl;\n    cout << \"w:\" << w.transpose() << endl;\n    cout << \"v0:\" << v0.transpose() << endl;\n\n    cout << \"I: \" << endl << I.toMatrix() << endl;\n    cout << \"I_fd: \" << endl << I_fd.toMatrix() << endl;\n    cout << \"I_an: \" << endl << I_an << endl << endl;\n    cout << \"I_ad: \" << endl << I_ad.toMatrix() << endl << endl;\n    cout << \"error(max): \" << \" (\" << error << \")\" << endl\n      << endl << I_err << endl;\n  }\n\n  // test result\n  CHECK_ARRAY_CLOSE(\n    I_fd.toMatrix().data(), I_ad.toMatrix().data(),\n    I_fd.toMatrix().size(), TEST_PRECISION\n  );\n}\n\nTEST(Xrotx_efficient_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(0) = 1.0;\n  efficient_analytic_derivative_of_spatial_inertia(*this, Xrotx, S, 1e-7);\n}\n\nTEST(Xroty_efficient_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(1) = 1.0;\n  efficient_analytic_derivative_of_spatial_inertia(*this, Xroty, S, 1e-7);\n}\n\nTEST(Xrotz_efficient_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(2) = 1.0;\n  efficient_analytic_derivative_of_spatial_inertia(*this, Xrotz, S, 1e-7);\n}\n\nTEST(Xtransx_efficient_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(3) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransx\n    = [](const double &q) { return Xtrans(Vector3d(q, 0., 0.)); };\n  efficient_analytic_derivative_of_spatial_inertia(*this, Xtransx, S, 1e-8);\n}\n\nTEST(Xtransy_efficient_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(4) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransy\n    = [](const double &q) { return Xtrans(Vector3d(0., q, 0.)); };\n  efficient_analytic_derivative_of_spatial_inertia(*this, Xtransy, S, 1e-7);\n}\n\nTEST(Xtransz_efficient_analytic_derivative_of_spatial_inertia){\n  srand (421337);\n  SpatialVector S = SpatialVector::Zero();\n  S(5) = 1.0;\n  std::function<SpatialTransform (const double &)> Xtransz\n    = [](const double &q) { return Xtrans(Vector3d(0., 0., q)); };\n  efficient_analytic_derivative_of_spatial_inertia(*this, Xtransz, S, 1e-7);\n}\n\n// -----------------------------------------------------------------------------\n\n", "meta": {"hexsha": "b1bb2a6bd2f5a392bae9b85764940508459f6aa5", "size": 32016, "ext": "cc", "lang": "C++", "max_stars_repo_path": "addons/differentiation/tests/SpatialAlgebraTest.cc", "max_stars_repo_name": "mkudruss/rbdl_derivatives", "max_stars_repo_head_hexsha": "0fec930aad4a6fb3084aa5aa2bb27bcfd7409a1e", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T09:31:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-21T09:31:56.000Z", "max_issues_repo_path": "addons/differentiation/tests/SpatialAlgebraTest.cc", "max_issues_repo_name": "mkudruss/rbdl_derivatives", "max_issues_repo_head_hexsha": "0fec930aad4a6fb3084aa5aa2bb27bcfd7409a1e", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "addons/differentiation/tests/SpatialAlgebraTest.cc", "max_forks_repo_name": "mkudruss/rbdl_derivatives", "max_forks_repo_head_hexsha": "0fec930aad4a6fb3084aa5aa2bb27bcfd7409a1e", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T05:03:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:03:17.000Z", "avg_line_length": 33.5597484277, "max_line_length": 96, "alphanum_fraction": 0.6517678661, "num_tokens": 9896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127641048443, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6346006484285766}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_STIRLING_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_STIRLING_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n /*!\n    @ingroup group-euler\n    This function object computes stirling formula for the gamma function\n\n    @par Semantic:\n    For every parameter of floating type @c T , the following code:\n    @code\n    T r = stirling(x);\n    @endcode\n    computes  \\f$\\sqrt{2 \\pi} x^{x-\\frac12} e^{-x} ( 1 + \\frac1{x} P(\\frac1{x}))\\f$,\n    where \\f$P\\f$ is a polynomial.\n    The formula implementation is usable for x between 33 and 172 to approximate \\f$\\Gamma(x)\\f$.\n\n    @see gamma, gammaln\n\n    @param v0 value of a floating-point\n    @return The aproximation of \\f$\\Gamma(v_0)\\f$ using Striling's formula.\n  **/\n  Value stirling(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/stirling.hpp>\n#include <boost/simd/function/simd/stirling.hpp>\n\n#endif\n", "meta": {"hexsha": "459a6fa928cc57c90b1c70c83ceeabd6b42d1240", "size": 1314, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/stirling.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "include/boost/simd/function/stirling.hpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/stirling.hpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 30.5581395349, "max_line_length": 100, "alphanum_fraction": 0.597412481, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6345913252545928}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include \"measures.hpp\"\n#include <eve/module/complex.hpp>\n#include <complex>\n#include <boost/math/complex/asinh.hpp>\n\ntemplate < typename T >\nauto cv(std::complex < T > sc)\n{\n  return eve::complex<T>(sc.real(), sc.imag());\n}\n\nEVE_TEST( \"Check behavior of asinh on scalar\"\n        , eve::test::scalar::ieee_reals\n        , eve::test::generate( eve::test::randoms(-10, 10)\n                             , eve::test::randoms(-10, 10))\n        )\n  <typename T>(T const& a0, T const& a1 )\n{\n  auto ulp = (spy::stdlib == spy::libcpp_) ? 300.0 : 3.5;\n  using e_t = typename T::value_type;\n  using c_t = std::complex<e_t>;\n  for(auto e : a0)\n  {\n    for(auto f : a1)\n    {\n      TTS_ULP_EQUAL(eve::asinh(eve::complex<e_t>(e, f)),  cv(boost::math::asinh(c_t(e, f))), ulp);\n    }\n  }\n};\n\nEVE_TEST( \"Check behavior of asinh on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(-5, 5)\n                             , eve::test::randoms(-5, 5))\n        )\n  <typename T>(T const& a0, T const&  a1)\n{\n  auto ulp = (spy::stdlib == spy::libcpp_) ? 300.0 : 2.0;\n  using e_t = typename T::value_type;\n  using ce_t = eve::complex<e_t>;\n  using z_t = eve::as_complex_t<T>;\n  using c_t = std::complex<e_t>;\n  auto std_asinh = [](auto x, auto y){return cv(boost::math::asinh(c_t(x, y))); };\n  auto init_with_std = [std_asinh](auto a0,  auto a1){\n    z_t b;\n    for(int i = 0; i !=  eve::cardinal_v<T>; ++i)\n    {\n      ce_t z = std_asinh(a0.get(i), a1.get(i));\n      b.set(i, z);\n    }\n    return b;\n  };\n  TTS_ULP_EQUAL(eve::asinh(z_t{a0,a1}), init_with_std(a0, a1), ulp);\n};\n\nEVE_TEST_TYPES( \"Check return types of eve::asinh\", eve::test::scalar::ieee_reals)\n  <typename T>(eve::as<T>)\n{\n  auto ulp = (spy::stdlib == spy::libcpp_) ? 300.0 : 0.75;\n  using e_t = eve::element_type_t<T>;\n  using c_t = eve::complex<e_t>;\n  using eve::as;\n\n  // specific values tests\n\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::nan  (as<T>()), eve::zero(as<T>()))), c_t(eve::nan (as<T>()), eve::zero(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::one  (as<T>()), eve::inf (as<T>()))), c_t(eve::inf(as<T>()),  eve::pio_2(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::one  (as<T>()), eve::nan (as<T>()))), c_t(eve::nan(as<T>()),  eve::nan(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::inf  (as<T>()), eve::one (as<T>()))), c_t(eve::inf (as<T>()), eve::zero(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::inf  (as<T>()), eve::inf(as<T>()))),  c_t(eve::inf (as<T>()), eve::pi(as<T>())/4), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::inf  (as<T>()), eve::nan(as<T>()))),  c_t(eve::inf (as<T>()), eve::nan(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::nan  (as<T>()), eve::one(as<T>()))),  c_t(eve::nan (as<T>()), eve::nan(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::nan  (as<T>()), eve::inf(as<T>()))),  c_t(eve::inf (as<T>()), eve::nan(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::nan  (as<T>()), eve::nan(as<T>()))),  c_t(eve::nan (as<T>()), eve::nan(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::one  (as<T>()), -eve::inf (as<T>()))), c_t(eve::inf(as<T>()),  -eve::pio_2(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::one  (as<T>()), -eve::nan (as<T>()))), c_t(eve::nan(as<T>()),  -eve::nan(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::inf  (as<T>()), -eve::one (as<T>()))), c_t(eve::inf (as<T>()), -eve::zero(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::inf  (as<T>()), -eve::inf(as<T>()))),  c_t(eve::inf (as<T>()), -eve::pi(as<T>())/4), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::inf  (as<T>()), -eve::nan(as<T>()))),  c_t(eve::inf (as<T>()), -eve::nan(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::nan  (as<T>()), -eve::one(as<T>()))),  c_t(eve::nan (as<T>()), -eve::nan(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::nan  (as<T>()), -eve::inf(as<T>()))),  c_t(eve::inf (as<T>()), -eve::nan(as<T>())), ulp);\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::nan  (as<T>()), -eve::nan(as<T>()))),  c_t(eve::nan (as<T>()), -eve::nan(as<T>())), ulp);\n\n   TTS_ULP_EQUAL(eve::asinh(c_t(eve::zero(as<T>()),  eve::zero(as<T>()))), c_t(eve::zero(as<T>()), eve::zero(as<T>())), ulp);\n};\n", "meta": {"hexsha": "c2aeb726108a3459d83a994ce9070c7f1d7d4d33", "size": 4503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/complex/asinh.cpp", "max_stars_repo_name": "mshojatalab/eve", "max_stars_repo_head_hexsha": "9fc1f46e695b05e2e72f7e2083729621e6bdb57e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/complex/asinh.cpp", "max_issues_repo_name": "mshojatalab/eve", "max_issues_repo_head_hexsha": "9fc1f46e695b05e2e72f7e2083729621e6bdb57e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/complex/asinh.cpp", "max_forks_repo_name": "mshojatalab/eve", "max_forks_repo_head_hexsha": "9fc1f46e695b05e2e72f7e2083729621e6bdb57e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.9042553191, "max_line_length": 128, "alphanum_fraction": 0.5307572729, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6345913141419676}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// skewness.hpp\r\n//\r\n//  Copyright 2006 Olivier Gygi, Daniel Egloff. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_ACCUMULATORS_STATISTICS_SKEWNESS_HPP_EAN_28_10_2005\r\n#define BOOST_ACCUMULATORS_STATISTICS_SKEWNESS_HPP_EAN_28_10_2005\r\n\r\n#include <limits>\r\n#include <boost/mpl/placeholders.hpp>\r\n#include <boost/accumulators/framework/accumulator_base.hpp>\r\n#include <boost/accumulators/framework/extractor.hpp>\r\n#include <boost/accumulators/framework/parameters/sample.hpp>\r\n#include <boost/accumulators/numeric/functional.hpp>\r\n#include <boost/accumulators/framework/depends_on.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/moment.hpp>\r\n#include <boost/accumulators/statistics/mean.hpp>\r\n\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // skewness_impl\r\n    /**\r\n        @brief Skewness estimation\r\n\r\n        The skewness of a sample distribution is defined as the ratio of the 3rd central moment and the \\f$ 3/2 \\f$-th power\r\n        of the 2nd central moment (the variance) of the sampless 3. The skewness can also be expressed by the simple moments:\r\n\r\n        \\f[\r\n            \\hat{g}_1 =\r\n                \\frac\r\n                {\\widehat{m}_n^{(3)}-3\\widehat{m}_n^{(2)}\\hat{\\mu}_n+2\\hat{\\mu}_n^3}\r\n                {\\left(\\widehat{m}_n^{(2)} - \\hat{\\mu}_n^{2}\\right)^{3/2}}\r\n        \\f]\r\n\r\n        where \\f$ \\widehat{m}_n^{(i)} \\f$ are the \\f$ i \\f$-th moment and \\f$ \\hat{\\mu}_n \\f$ the mean (first moment) of the\r\n        \\f$ n \\f$ samples.\r\n    */\r\n    template<typename Sample>\r\n    struct skewness_impl\r\n      : accumulator_base\r\n    {\r\n        // for boost::result_of\r\n        typedef typename numeric::functional::average<Sample, Sample>::result_type result_type;\r\n\r\n        skewness_impl(dont_care)\r\n        {\r\n        }\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            return numeric::average(\r\n                        accumulators::moment<3>(args)\r\n                        - 3. * accumulators::moment<2>(args) * mean(args)\r\n                        + 2. * mean(args) * mean(args) * mean(args)\r\n                      , ( accumulators::moment<2>(args) - mean(args) * mean(args) )\r\n                        * std::sqrt( accumulators::moment<2>(args) - mean(args) * mean(args) )\r\n                   );\r\n        }\r\n    };\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::skewness\r\n//\r\nnamespace tag\r\n{\r\n    struct skewness\r\n      : depends_on<mean, moment<2>, moment<3> >\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::skewness_impl<mpl::_1> impl;\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::skewness\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::skewness> const skewness = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(skewness)\r\n}\r\n\r\nusing extract::skewness;\r\n\r\n// So that skewness can be automatically substituted with\r\n// weighted_skewness when the weight parameter is non-void\r\ntemplate<>\r\nstruct as_weighted_feature<tag::skewness>\r\n{\r\n    typedef tag::weighted_skewness type;\r\n};\r\n\r\ntemplate<>\r\nstruct feature_of<tag::weighted_skewness>\r\n  : feature_of<tag::skewness>\r\n{\r\n};\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#endif\r\n", "meta": {"hexsha": "c811eb0c4522146dd9193df0a9e09b67247954ec", "size": 3635, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/accumulators/statistics/skewness.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "master/core/third/boost/accumulators/statistics/skewness.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/accumulators/statistics/skewness.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 31.6086956522, "max_line_length": 126, "alphanum_fraction": 0.566437414, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213880824789, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.6345864250451191}}
{"text": "\r\n\r\n#include <boost/math/quaternion.hpp>\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <vector>\r\n\r\n\r\n\r\ntypedef float                                 Real;\r\ntypedef boost::numeric::ublas::vector<Real>   Vector3;\r\ntypedef boost::numeric::ublas::matrix<Real>   Matrix44;\r\ntypedef boost::math::quaternion<Real>         Quaternion;\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "7abcceaf296b0603c341ad32d06350aaa448db8d", "size": 406, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/fileRead/PhysicsTypes.hpp", "max_stars_repo_name": "taku-xhift/labo", "max_stars_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/fileRead/PhysicsTypes.hpp", "max_issues_repo_name": "taku-xhift/labo", "max_issues_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/fileRead/PhysicsTypes.hpp", "max_forks_repo_name": "taku-xhift/labo", "max_forks_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.5, "max_line_length": 58, "alphanum_fraction": 0.6083743842, "num_tokens": 87, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6345864212294564}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// cross_validation::error::sqrt_mse.hpp                                    //\n//                                                                          //\n//  (C) Copyright 2009 Erwann Rogard                                        //\n//  Use, modification and distribution are subject to the                   //\n//  Boost Software License, Version 1.0. (See accompanying file             //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)        //\n//////////////////////////////////////////////////////////////////////////////\n#ifndef  BOOST_STATISTICS_DETAIL_CROSS_VALIDATION_ERROR_SQRT_MSE_HPP_ER_2009\n#define  BOOST_STATISTICS_DETAIL_CROSS_VALIDATION_ERROR_SQRT_MSE_HPP_ER_2009\n#include <cmath>\n#include <boost/iterator/iterator_traits.hpp>\n#include <boost/range.hpp>\n#include <boost/vector_space/functional/l2_distance_squared.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace cross_validation{\nnamespace error{\n\n    template<typename It,typename It1>\n    typename iterator_value<It>::type\n    sqrt_mse(\n        It b,\n        It e,\n        It1 b1\n    ){\n\n        typedef iterator_range<It>                          range_;\n        typedef typename iterator_difference<It>::type      diff_;\n        typedef iterator_range<It1>                         range1_;\n        typedef typename iterator_value<It>::type           val_;\n        typedef vector_space::l2_distance_squared<range_>   l2_;\n        \n        diff_ d = std::distance(b,e);\n        \n        l2_ l2(range_(b,e));\n        range1_ range1(\n            b1,\n            boost::next(\n                b1,\n                d\n            )\n        );\n        val_ res = l2(range1);\n        res /= static_cast<val_>(d);\n        res = sqrt( res );\n        return res;\n    };\n\n}// error\n}// cross_validation\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "3d2ea5b92bc98e00b14f3f5515df517d53ef9f2b", "size": 1932, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cross_validation/boost/statistics/detail/cross_validation/error/sqrt_mse.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cross_validation/boost/statistics/detail/cross_validation/error/sqrt_mse.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cross_validation/boost/statistics/detail/cross_validation/error/sqrt_mse.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3103448276, "max_line_length": 78, "alphanum_fraction": 0.5108695652, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6345864156652192}}
{"text": "#ifndef OB_CONFIG_HPP\n#define OB_CONFIG_HPP\n\n#include <Eigen/Dense>\n#include <vector>\n#include <limits>\n#include <memory>\n#include <iostream>\n\n\n\nnamespace OB\n{\n    // We could also use 16 bits to save space?\n    using FeatureId = uint32_t;\n\n    using Real = double;\n    using Point = Eigen::Matrix<Real, 3, 1>;\n    using Vector = Point;\n    using Matrix3 = Eigen::Matrix<Real,3,3>;\n    using DiagonalMatrix3 = Eigen::DiagonalMatrix<Real,3>;\n    using Plane = Eigen::Hyperplane<Real,3>;\n\n    // Affine looks like slow...\n    constexpr enum Eigen::TransformTraits Isometry = Eigen::Isometry;\n    //constexpr enum Eigen::TransformTraits Isometry = Eigen::Affine;\n\n    // can't get it to work with CompactAffine\n    constexpr enum Eigen::TransformTraits DefaultTransformTrait = Eigen::Affine;\n    using Transform = Eigen::Transform<Real,3,DefaultTransformTrait>; //size:128 with double\n\n    using Translation = Eigen::Translation<Real,3>;\n    using Quaternion = Eigen::Quaternion<Real>;\n    using AngleAxis = Eigen::AngleAxis<Real>;\n    using ParametrizedLine = Eigen::ParametrizedLine<Real,3>;\n\n    constexpr Real PI = EIGEN_PI;\n\n    template<typename ScalarType>\n    bool is_zero(ScalarType value, ScalarType prec = std::numeric_limits< float >::epsilon())\n    {\n        return Eigen::internal::isMuchSmallerThan(value,\n                                                  static_cast<ScalarType>(1.0),\n                                                  prec);\n    }\n\n\n}\n\n\n#endif\n", "meta": {"hexsha": "44f39f5fe5c70af0c4fbcd18ecd3cd46d50da71f", "size": 1474, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/obconfig.hpp", "max_stars_repo_name": "javierdelapuente/tfm_ode_bullet", "max_stars_repo_head_hexsha": "cc0d40b9a91e43b5045c10903b5244e680d909ef", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-08T11:22:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T11:22:13.000Z", "max_issues_repo_path": "include/obconfig.hpp", "max_issues_repo_name": "javierdelapuente/tfm_ode_bullet", "max_issues_repo_head_hexsha": "cc0d40b9a91e43b5045c10903b5244e680d909ef", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/obconfig.hpp", "max_forks_repo_name": "javierdelapuente/tfm_ode_bullet", "max_forks_repo_head_hexsha": "cc0d40b9a91e43b5045c10903b5244e680d909ef", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3461538462, "max_line_length": 93, "alphanum_fraction": 0.6567164179, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6345182173122329}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <iterator>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Random.h>\n\n#include <OpenMesh/Core/IO/MeshIO.hh>\n#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>\n\n#include <CGAL/boost/graph/graph_traits_PolyMesh_ArrayKernelT.h>\n#include <CGAL/boost/graph/properties_PolyMesh_ArrayKernelT.h>\n\n#include <CGAL/boost/graph/iterator.h>\n\n#include <CGAL/Surface_mesh_shortest_path/Surface_mesh_shortest_path_traits.h>\n#include <CGAL/Surface_mesh_shortest_path/Surface_mesh_shortest_path.h>\n\n#include <boost/lexical_cast.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\n\ntypedef OpenMesh::PolyMesh_ArrayKernelT<> Triangle_mesh;\n\ntypedef boost::graph_traits<Triangle_mesh> Graph_traits;\ntypedef Graph_traits::vertex_descriptor vertex_descriptor;\ntypedef Graph_traits::vertex_iterator vertex_iterator;\ntypedef Graph_traits::face_descriptor face_descriptor;\ntypedef Graph_traits::face_iterator face_iterator;\n\ntypedef CGAL::Surface_mesh_shortest_path_traits<Kernel, Triangle_mesh> Traits;\ntypedef CGAL::Surface_mesh_shortest_path<Traits> Surface_mesh_shortest_path;\n\nint main(int argc, char** argv)\n{\n  // read the input surface mesh\n  Triangle_mesh tmesh;\n  OpenMesh::IO::read_mesh(tmesh, (argc>1)?argv[1]:\"data/elephant.off\");\n\n  // pick up a random face\n  const unsigned int randSeed = argc > 2 ? boost::lexical_cast<unsigned int>(argv[2]) : 7915421;\n  CGAL::Random rand(randSeed);\n  const int target_face_index = rand.get_int(0, static_cast<int>(num_faces(tmesh)));\n  face_iterator face_it = faces(tmesh).first;\n  std::advance(face_it,target_face_index);\n  // ... and define a barycentric coordinates inside the face\n  Traits::Barycentric_coordinates face_location = {{0.25, 0.5, 0.25}};\n\n  // construct a shortest path query object and add a source point\n  Surface_mesh_shortest_path shortest_paths(tmesh);\n  shortest_paths.add_source_point(*face_it, face_location);\n\n  // For all vertices in the tmesh, compute the points of\n  // the shortest path to the source point and write them\n  // into a file readable using the CGAL Tmesh demo\n  std::ofstream output(\"shortest_paths_OpenMesh.cgal\");\n  vertex_iterator vit, vit_end;\n  for ( boost::tie(vit, vit_end) = vertices(tmesh);\n        vit != vit_end; ++vit)\n  {\n    std::vector<Traits::Point_3> points;\n    shortest_paths.shortest_path_points_to_source_points(*vit, std::back_inserter(points));\n\n    // print the points\n    output << points.size() << \" \";\n    for (std::size_t i = 0; i < points.size(); ++i)\n      output << \" \" << points[i];\n    output << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "aa40d6f07275153d554531e623440a1d38d7f208", "size": 2655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_shortest_path/examples/Surface_mesh_shortest_path/shortest_paths_OpenMesh.cpp", "max_stars_repo_name": "jjcasmar/cgal", "max_stars_repo_head_hexsha": "5a3e50e6b4418a25db7d2c1e2c00650c33c6e8e9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "Surface_mesh_shortest_path/examples/Surface_mesh_shortest_path/shortest_paths_OpenMesh.cpp", "max_issues_repo_name": "guorongtao/cgal", "max_issues_repo_head_hexsha": "a848e52552a9205124b7ae13c7bcd2b860eb4530", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "Surface_mesh_shortest_path/examples/Surface_mesh_shortest_path/shortest_paths_OpenMesh.cpp", "max_forks_repo_name": "guorongtao/cgal", "max_forks_repo_head_hexsha": "a848e52552a9205124b7ae13c7bcd2b860eb4530", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 35.4, "max_line_length": 96, "alphanum_fraction": 0.7649717514, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6345182104561867}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/spatial_sort.h>\n#include <CGAL/Spatial_sort_traits_adapter_3.h>\n#include <vector>\n#include <boost/iterator/counting_iterator.hpp>\n\ntypedef CGAL::Simple_cartesian<double>                  Kernel;\ntypedef Kernel::Point_3                                 Point_3;\n//using a pointer as a special property map type\ntypedef \n  CGAL::Spatial_sort_traits_adapter_3<Kernel,Point_3*>  Search_traits_3;\n\nint main()\n{\n  std::vector<Point_3> points;\n  points.push_back(Point_3(1,3,11));\n  points.push_back(Point_3(14,34,46));\n  points.push_back(Point_3(414,34,4));\n  points.push_back(Point_3(4,2,56));\n  points.push_back(Point_3(744,4154,43));\n  points.push_back(Point_3(74,44,1));\n  \n  std::vector<std::ptrdiff_t> indices;\n  indices.reserve(points.size());\n  \n  std::copy(boost::counting_iterator<std::ptrdiff_t>(0),\n            boost::counting_iterator<std::ptrdiff_t>(points.size()),\n            std::back_inserter(indices));\n  \n  CGAL::spatial_sort( indices.begin(),indices.end(),Search_traits_3(&(points[0])) );\n\n  for (std::vector<std::ptrdiff_t>::iterator it=indices.begin();it!=indices.end();++it)\n    std::cout << points[*it] << \"\\n\";\n\n  std::cout << \"done\" << std::endl;\n  \n  return 0;\n}\n", "meta": {"hexsha": "ab48feafc9fcd4ebfe698f8d67d3fa1ee836c0ef", "size": 1234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Spatial_sorting/examples/Spatial_sorting/sp_sort_using_property_map_3.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Spatial_sorting/examples/Spatial_sorting/sp_sort_using_property_map_3.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Spatial_sorting/examples/Spatial_sorting/sp_sort_using_property_map_3.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.641025641, "max_line_length": 87, "alphanum_fraction": 0.6766612642, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.634422865168605}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// Unit Test\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n#include <geometry_test_common.hpp>\r\n\r\n#include <boost/geometry/arithmetic/dot_product.hpp>\r\n\r\n\r\n#include <boost/geometry/algorithms/assign.hpp>\r\n\r\n#include <boost/geometry/geometries/point.hpp>\r\n#include <boost/geometry/geometries/adapted/c_array.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n#include <test_common/test_point.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\n\r\n\r\ntemplate <typename P>\r\nvoid test_all()\r\n{\r\n    P p1;\r\n    bg::assign_values(p1, 1, 2, 3);\r\n    P p2;\r\n    bg::assign_values(p2, 4, 5, 6);\r\n    BOOST_CHECK(bg::dot_product(p1, p2) == 1*4 + 2*5 + 3*6);\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n    test_all<int[3]>();\r\n    test_all<float[3]>();\r\n    test_all<double[3]>();\r\n    test_all<test::test_point>();\r\n    test_all<bg::model::point<int, 3, bg::cs::cartesian> >();\r\n    test_all<bg::model::point<float, 3, bg::cs::cartesian> >();\r\n    test_all<bg::model::point<double, 3, bg::cs::cartesian> >();\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "f5dc709871b826ce7917d21c135a4d56b7820366", "size": 1644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/test/arithmetic/dot_product.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/test/arithmetic/dot_product.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/test/arithmetic/dot_product.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 30.4444444444, "max_line_length": 80, "alphanum_fraction": 0.6879562044, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6343314307472715}}
{"text": "//#include <boost/iostreams/stream.hpp>\n//#include <boost/iostreams/tee.hpp>\n\n#include <iostream>\n#include <iomanip>\n#include <bitset>\n#include <sstream>\n#include <string>\n#include <fstream>\n#include <stdexcept>\n\nusing unsigned_type = unsigned int;\n\nstatic_assert(sizeof(unsigned_type) > 1, \"If type not greater than one byte, Carry out won't work\");\n\nstd::string get_hex(unsigned_type in)\n{\n\tstd::stringstream buffer;\n\tbuffer << std::hex << unsigned(in & 0xff);\n\treturn buffer.str();\n}\n\nstd::string get_bin(unsigned_type in)\n{\n\treturn std::bitset<8>(in).to_string();\n}\n\n#define DO_OP(op_sign) if (op == #op_sign) { return arg1 op_sign arg2; }\nunsigned_type do_op(unsigned_type arg1, std::string op, unsigned_type arg2)\n{\n\tDO_OP(+)\n\tDO_OP(-)\n\tDO_OP(|)\n\tDO_OP(^)\n\tDO_OP(&)\n\tthrow std::invalid_argument(\"invalid operand: \" + op);\n}\n#undef DO_OP\n\nstd::string intro_message =\nR\"(Enter: <Uint8> <whitespace> <op> <whitespace> <Uint8>\nEnter: 'bin' to switch to binary entry mode\nEnter: 'hex' to switch to hexadecimal mode (default)\nEnter: 'clear' to clear the screen\nEnter: 'help' to display this help message\nEnter: 'q' or press Ctrl-C to quit)\";\n\nint main()\n{\n\t//using Tee = boost::iostreams::tee_device<std::ostream, std::ofstream>;\n\t//using TeeStream = boost::iostreams::stream<Tee>;\n\n\t//std::ofstream file(\"log.txt\");\n\t//Tee tee(std::cout, file);\n\t//TeeStream both(tee);\n\n\tstd::cout << intro_message << std::endl;\n\n\tstd::string mode = \"hex\";\n\tint base = 16;\n\tunsigned_type arg1, arg2, ans;\n\tfor (;;)\n\t{\n\t\tstd::string first, op, second;\n\n\t\tstd::cout << mode << \" >>> \";\n\t\tstd::cin >> first;\n\t\tif (first == \"quit\" || first == \"exit\" || first == \"q\") { break; }\n\t\tif (first == \"clear\" || first == \"clr\")\n\t\t{\n\t\t\tsystem(\"clear\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (first == \"help\")\n\t\t{\n\t\t\tstd::cout << intro_message << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\tif (first == \"bin\")\n\t\t{\n\t\t\tbase = 2;\n\t\t\tstd::cout << \"Switched to binary mode\" << std::endl;\n\t\t\tmode = \"bin\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (first == \"hex\")\n\t\t{\n\t\t\tbase = 16;\n\t\t\tstd::cout << \"Switched to hexadecimal mode\" << std::endl;\n\t\t\tmode = \"hex\";\n\t\t\tcontinue;\n\t\t}\n\t\ttry\n\t\t{\n\t\t\targ1 = static_cast<unsigned_type>(std::stoul(first, 0, base));\n\t\t}\n\t\tcatch (std::invalid_argument & invalid)\n\t\t{\n\t\t\tstd::cout << invalid.what() << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\tstd::cin >> op >> second;\n\t\ttry\n\t\t{\n\t\t\targ2 = static_cast<unsigned_type>(std::stoul(second, 0, base));\n\t\t\tans = do_op(arg1, op, arg2);\n\t\t}\n\t\tcatch (std::invalid_argument & invalid)\n\t\t{\n\t\t\tstd::cout << invalid.what() << std::endl;;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (ans > 0xff) { std::cout << \"Carry-out: 1\" << std::endl; }\n\t\tstd::cout << get_hex(arg1) << \" \" << op << \" \" << get_hex(arg2) << \" = \" << get_hex(ans) << std::endl;\n\t\tstd::cout << get_bin(arg1) << \" \" << op << \"\\n\" << get_bin(arg2) << \" =\\n\" << get_bin(ans) << std::endl;\n\t}\n}\n", "meta": {"hexsha": "18484977024f45bf00644f17234ef2001b8452f8", "size": 2813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Unsigned_Interp/main.cpp", "max_stars_repo_name": "bbkane/Sandbox", "max_stars_repo_head_hexsha": "848030da315045888fd8542ddee49b929fa2e64a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Unsigned_Interp/main.cpp", "max_issues_repo_name": "bbkane/Sandbox", "max_issues_repo_head_hexsha": "848030da315045888fd8542ddee49b929fa2e64a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Unsigned_Interp/main.cpp", "max_forks_repo_name": "bbkane/Sandbox", "max_forks_repo_head_hexsha": "848030da315045888fd8542ddee49b929fa2e64a", "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": 23.6386554622, "max_line_length": 106, "alphanum_fraction": 0.6146462851, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.634331427690318}}
{"text": "#include \"global.h\"\n#include \"distr.h\"\n#include \"utils.h\"\n\n#include <omp.h>\n#include <armadillo>\n#include <cmath>\n#include <limits>\n#include <vector>\n#include <random>\n#include <boost/math/special_functions/erf.hpp> // can I do this?\n#include <iostream>\n\n//defined in global.h\nextern std::vector<std::mt19937_64> rng;\n\nnamespace Distributions{\n\n\tdouble randU01()\n\t{\n\t\tstd::uniform_real_distribution<> distr(0, std::nextafter(1, std::numeric_limits<double>::max())); // init U(0,1)\n\t\tdouble res = distr(rng[omp_get_thread_num()]);\n\t\treturn res;\n\t}\n\n\tdouble randLogU01()\n\t{\n\t\tstd::uniform_real_distribution<> distr(0, std::nextafter(1, std::numeric_limits<double>::max())); // init U(0,1)\n\t\tdouble res = log(distr(rng[omp_get_thread_num()]));\n\t\treturn res;\n\t}\n\n\tint randIntUniform(const int a,const int b)\n\t{\n\t\tstd::uniform_int_distribution<> distr(a, b); // init the discrete uniform\n\t\tdouble res = distr(rng[omp_get_thread_num()]);\n\t\treturn res;\n\t}\n\n\tarma::ivec randIntUniform(const unsigned int n, const int a,const int b)\n\t{\n\t\tarma::ivec res(n);\n\t\tstd::uniform_int_distribution<> distr(a, b); // init the discrete uniform\n\t\tfor(unsigned int i=0; i<n; ++i)\n\t\t{\n\t\t\tres(i) = distr(rng[omp_get_thread_num()]);\n\t\t}\n\t\treturn res;\n\t}\n\n\tdouble randExponential(const double lambda)\n\t{\n\t\tstd::exponential_distribution<> distr(lambda);\n\t\tdouble res = distr(rng[omp_get_thread_num()]);\n\t\treturn res;\n\t}\n\n\tarma::vec randExponential(const unsigned int n, const double lambda)\n\t{\n\t\tarma::vec res(n);\n\t\tstd::exponential_distribution<> distr(lambda);\n\t\tfor(unsigned int i=0; i<n; ++i)\n\t\t{\n\t\t\tres(i) = distr(rng[omp_get_thread_num()]);\n\t\t}\n\t\treturn res;\n\t}\n\n\tunsigned int randBinomial(const unsigned int n, const double p) // slow but safe (CARE, n here is the binomial parameters, return value is always ONE integer)\n\t{\n\t\tstd::binomial_distribution<> d(n, p);\n\t\tdouble res = d(rng[omp_get_thread_num()]);\n\t\treturn res;\n\t}\n\n\tarma::uvec randMultinomial(unsigned int n, const arma::vec prob)\n\t{\n\n\t  unsigned int K = prob.n_elem;\n\t  arma::uvec rN = arma::zeros<arma::uvec>(K);\n\t  double p_tot = sum(prob);\n\t  double pp;\n\n\t  for(unsigned int k = 0 ; k < (K-1) ; ++k)\n\t  {\n\t    if(prob(k)>0) {\n\t    \tpp = prob(k) / p_tot;\n\t    \trN(k) = ((pp < 1.) ? randBinomial(n,  pp) : n);\n\t    \tn -= rN(k);\n\t    }else{\n\t    \trN(k) = 0;\n\t    }\n\n\n\t    if(n <= 0) /* we have all*/ return rN;\n\t    p_tot -= prob(k); /* i.e. = sum(prob[(k+1):K]) */\n\t  }\n\t  rN(K-1) = n - sum(rN);\n\t  return rN;\n\n\t}\n\n\n\tdouble randNormal(const double m=0., const double sigmaSquare=1.) // random normal interface, parameters mean and variance\n\t{\n    \tstd::normal_distribution<> d(m,sqrt(sigmaSquare));\n\t\tdouble res = d(rng[omp_get_thread_num()]);\n\t\treturn res;\n\t}\n\n\tarma::vec randNormal(const unsigned int n, const double m=0., const double sigmaSquare=1.) // n-sample normal, parameters mean and variance\n\t{\n    \tarma::vec res(n);\n    \tstd::normal_distribution<> d(m,sqrt(sigmaSquare));\n    \tfor(unsigned int i=0; i<n; ++i)\n\t\t{\n\t\t\tres(i) = d(rng[omp_get_thread_num()]);\n\t\t}\n\t\treturn res;\n\t}\n\n\tarma::vec randMvNormal(const arma::vec &m, const arma::mat &Sigma) // random normal interface to arma::randn\n\t{\n\t\tunsigned int d = m.n_elem;\n\n\t\t//check\n\t\tif(Sigma.n_rows != d || Sigma.n_cols != d )\n\t\t{\n\t\t\tstd::cout << \" Dimension not matching in the multivariate normal sampler\" << std::flush;\n\t\t\treturn 0;\n\t\t}\n\n\t\t\tarma::mat A;\n\t\t\tarma::vec eigval;\n\t\t\tarma::mat eigvec;\n\t\t\tarma::rowvec res;\n\n\t\t\tif( arma::chol(A,Sigma) )\n\t\t\t{\n\t\t\t\tres = randNormal(d).t() * A ;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t// std::cout << Sigma << std::endl << std::endl;\n\t// std::cin >> d; d = m.n_elem;\n\t\t\t\tif( eig_sym(eigval, eigvec, Sigma) )\n\t\t\t\t{\n\t\t\t\t\tres = (eigvec * arma::diagmat(arma::sqrt(eigval)) * randNormal(d)).t();\n\t\t\t\t}else{\n\t\t\t\t\tstd::cout << \"randMvNorm failing because of singular Sigma matrix\" << std::endl << std::flush;\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t}\n\n\t\treturn res.t() + m;\n\t}\n\n\tdouble randT(const double nu)\n\t{\n    \tstd::student_t_distribution<double> d(nu);\n\t\tdouble res = d(rng[omp_get_thread_num()]);;\n\t\treturn res;\n\t}\n\n\tarma::vec randT(const unsigned int n, const double nu)\n\t{\n    \tarma::vec res(n);\n    \tstd::student_t_distribution<double> d(nu);\n    \tfor(unsigned int i=0; i<n; ++i)\n\t\t{\n\t\t\tres(i) = d(rng[omp_get_thread_num()]);\n\t\t}\n\t\treturn res;\n\t}\n\n\tarma::vec randMvT(const double &nu, const arma::vec &m, const arma::mat &Sigma)\n\t{\n\t\tunsigned int d = m.n_elem;\n\n\t\t//check\n\t\tif(Sigma.n_rows != d || Sigma.n_cols != d )\n\t\t{\n\t\t\tstd::cout << \" Dimension not matching in the multivariate t sampler\" << std::flush;\n\t\t\tthrow; // THROW EXCPTION\n\t\t}\n\n\t\tarma::rowvec res = randT(d,nu).t() * arma::chol(Sigma);\n\n\t\treturn res.t() + m;\n\t}\n\n\n\n\tdouble randGamma(double shape, double scale)   // shape scale parametrisation\n\t{\n\t\t//check\n\t\tif(shape <= 0 || scale <= 0 )\n\t\t{\n\t\t\tstd::cout << \" Negative parameter in the gamma sampler \" << std::flush;\n\t\t\tthrow; // THROW EXCPTION\n\t\t}\n\n\t\tstd::gamma_distribution<> d(shape,scale);\n\t\tdouble res = d(rng[omp_get_thread_num()]);\n\t\treturn res;\n\t}\n\n\n\tdouble randIGamma(double shape, double scale)\n\t{\n\t\t//check\n\t\tif(shape <= 0 || scale <= 0 )\n\t\t{\n\t\t\tstd::cout << \" Negative parameter in the gamma sampler \" << std::flush;\n\t\t\tthrow; // THROW EXCPTION\n\t\t}\n\n\t\tstd::gamma_distribution<> d(shape,1./scale);\n\t\tdouble res =  ( 1./d(rng[omp_get_thread_num()]) );\n\t\treturn res;\n\t}\n\n\n\n\tarma::mat randWishart(double df, const arma::mat& S)   // unsigned int df is obsolete, I see no reason to keep it\n\t{\n\t\t// Dimension of returned wishart\n\t\tunsigned int m = S.n_rows;\n\n\t\t// Z composition:\n\t\t// sqrt chisqs on diagonal (with different parameters, so no need to create the distribution object here)\n\t\t// random normals below diagonal\n\t\tstd::normal_distribution<> normal01(0.,1.);\n\t\t// misc above diagonal\n\t\tarma::mat Z(m,m);\n\n\t\t// Fill the diagonal\n\t\tfor(unsigned int i = 0; i < m; i++){\n\t\t\tZ(i,i) = sqrt( randGamma( (df-i)/2.,2. ) );    // (note it's df-1:m+1)\n\t\t}\n\n\t\t// Fill the lower matrix with random normals\n\t\tfor(unsigned int j = 0; j < m; j++){\n\t\t\tfor(unsigned int i = j+1; i < m; i++){\n\t\t  \t\tZ(i,j) = normal01(rng[omp_get_thread_num()]);\n\t\t\t}\n\t\t}\n\n\t\t// Lower triangle * chol decomp\n\t\tarma::mat C = arma::trimatl(Z).t() * arma::chol(S);\n\n\t\t// Return random wishart\n\t\treturn C.t()*C;\n\t}\n\n\n\tarma::mat randIWishart(double df, const arma::mat& S)\n\t{\n\n  \t\treturn arma::inv_sympd( randWishart(df,S.i()) );   // return the inverse of the correspondent Wishart variate ... is this even fast enough?\n\t}\n\n\n\tarma::mat randMN(const arma::mat &M, const arma::mat &rowCov, const arma::mat &colCov)\n\t{\n\t\tarma::mat C = arma::chol( arma::kron(colCov,rowCov) );\n\t\tarma::mat z = randNormal( (unsigned int)(M.n_cols * M.n_rows) ).t() * C;\n\t\tz.reshape( arma::size(M) );\n\t\treturn (z + M);\n\t}\n\n\n\tdouble randBeta(double a, double b)\n\t{\n\t\tdouble num = randGamma(a,1.);\n\t\tdouble den = randGamma(b,1.) + num;\n\n\t\treturn num/den;\n\t}\n\n\n\tunsigned int randBernoulli(double pi)\n\t{\n\t\tstd::bernoulli_distribution d(pi);\n\t\tdouble res = d(rng[omp_get_thread_num()]);\n\t\treturn res;\n\t}\n\n\tdouble randTruncNorm(double m, double sd,double lower, double upper) // Naive, but it'll do for now -- notice now parameters are mean and standard deviation!\n\t{\n\t\tdouble ret = randNormal(m,sd);\n\n\t\twhile( ret < lower || ret > upper)\n\t\t\tret = randNormal(m,sd);\n\n\t\treturn ret;\n\t}\n\n\tarma::uvec randSampleWithoutReplacement\n\t(\n\t    unsigned int populationSize,    // size of set sampling from\n\t    const arma::uvec& population, // population to draw from\n\t    unsigned int sampleSize        // size of each sample\n\t) // output, sample is a zero-offset indices to selected items, output is the subsampled populaiton.\n\t{\n\t\tarma::uvec samples(sampleSize);\n\n\t    int t = 0; // total input records dealt with\n\t    unsigned int m = 0; // number of items selected so far\n\t    double u;\n\n\t    while (m < sampleSize)\n\t    {\n\t        u = randU01(); // call a uniform(0,1) random number generator\n\n\t        if ( (populationSize - t)*u >= sampleSize - m )\n\t        {\n\t            t++;\n\t        }\n\t        else\n\t        {\n\t            samples(m) = t;\n\t            t++; m++;\n\t        }\n\t    }\n\n\t    return population(samples);\n\t}\n\n\tstd::vector<unsigned int> randSampleWithoutReplacement\n\t(\n\t    unsigned int populationSize,    // size of set sampling from\n\t    const std::vector<unsigned int>& population, // population to draw from\n\t    unsigned int sampleSize        // size of each sample\n\t) // output, sample is a zero-offset indices to selected items, output is the subsampled populaiton.\n\t{\n\t\tstd::vector<unsigned int> samplesIndexes(sampleSize);\n\n\t    int t = 0; // total input records dealt with\n\t    unsigned int m = 0; // number of items selected so far\n\t    double u;\n\n\t    while (m < sampleSize)\n\t    {\n\t        u = randU01(); // call a uniform(0,1) random number generator\n\n\t        if ( (populationSize - t)*u >= sampleSize - m )\n\t        {\n\t            t++;\n\t        }\n\t        else\n\t        {\n\t            samplesIndexes[m] = t;\n\t            t++; m++;\n\t        }\n\t    }\n\n\t\tstd::vector<unsigned int> res(sampleSize);\n\t\tm = 0;\n\t\tfor( auto i : samplesIndexes )\n\t\t{\n\t\t\tres[m++] = population[i];\n\t\t}\n\t\t\n\t    return res;\n\t}\n\n\t// IMPLEMENTATION FROM Efraimidistr and Spirakis 2006\n\t// (probably efficient when n is close to N rather than in our case, but is there a better alternative?)\n\t//  even for n=1, we'd still need to compute the cumulative sum of all the weights if we want to use bisection, or what I use below which is O(N) anyway...\n\tarma::uvec randWeightedSampleWithoutReplacement\n\t(\n\t    unsigned int populationSize,    // size of set sampling from\n\t    const arma::vec& weights,\t   // probability for each element\n\t    unsigned int sampleSize,        // size of each sample\n\t    const arma::uvec& population // population to draw from\n\t) // sample is a zero-offset indices to selected items, output is the subsampled population.\n\t{\n\n\t    arma::vec score = randExponential(populationSize,1.)/weights;\n\t    arma::uvec result = population( (arma::sort_index(weights,\"ascend\")) );\n\n\t    return result.subvec(0,sampleSize-1);\n\t}\n\n\t// overload with sampleSize equal to one\n\tarma::uword randWeightedSampleWithoutReplacement\n\t(\n\t    unsigned int populationSize,    // size of set sampling from\n\t    const arma::vec& weights,\t   // probability for each element\n\t    const arma::uvec& population // population to draw from\n\t) // sample is a zero-offset indices to selected items, output is the subsampled population.\n\t{\n\t    double u = randU01();\n\t    double tmp = weights(0);\n\t    int t = 0;\n\n\t    while(u > tmp)\n\t    {\n\t    \ttmp += weights(++t);\n\t    }\n\n\t    return population( t );\n\t}\n\n\n\t// Versions that return indexes only\n\tarma::uvec randWeightedIndexSampleWithoutReplacement\n\t(\n\t    unsigned int populationSize,    // size of set sampling from\n\t    const arma::vec& weights,\t   // (log) probability for each element\n\t    unsigned int sampleSize         // size of each sample\n\t) // sample is a zero-offset indices to selected items, output is the subsampled population.\n\t{\n\t\t// note I can do everything in the log scale as the ordering won't change!\n\t    arma::vec score = randExponential(populationSize,1.) - weights;\n\t    arma::uvec result = arma::sort_index(score,\"ascend\");\n\n\t    return result.subvec(0,sampleSize-1);\n\t}\n\n\t// Overload with equal weights\n\tarma::uvec randWeightedIndexSampleWithoutReplacement\n\t(\n\t    unsigned int populationSize,    // size of set sampling from\n\t    unsigned int sampleSize         // size of each sample\n\t) // sample is a zero-offset indices to selected items, output is the subsampled population.\n\t{\n\t\t// note I can do everything in the log scale as the ordering won't change!\n\t    arma::vec score = randExponential(populationSize,1.);\n\t    arma::uvec result = arma::sort_index(score,\"ascend\");\n\n\t    return result.subvec(0,sampleSize-1);\n\t}\n\n\t// overload with sampleSize equal to one\n\tarma::uword randWeightedIndexSampleWithoutReplacement\n\t(\n\t    unsigned int populationSize,    // size of set sampling from\n\t    const arma::vec& weights     // probability for each element\n\t) // sample is a zero-offset indices to selected items, output is the subsampled population.\n\t{\n\t\t// note I can do everything in the log scale as the ordering won't change!\n\n\t    double u = randU01();\n\t    double tmp = weights(0);\n\t    unsigned int t = 0;\n\n\t    while(u > tmp)\n\t    {\n\t    \t// tmp = Utils::logspace_add(tmp,logWeights(++t));\n\t    \ttmp += weights(++t);\n\t    }\n\n\t    return t;\n\t}\n\n\n\n\t/// ################### NOW LOG PDFs\n\n\n\t// logPDF rand Weighted Indexes (need to implement the one for the original starting vector?)\n\tdouble logPDFWeightedIndexSampleWithoutReplacement(const arma::vec& weights, const arma::uvec& indexes)\n\t{\n\t\t// arma::vec logP_permutation = arma::zeros<arma::vec>((int)std::tgamma(indexes.n_elem+1));  //too big of a vector\n\t\tdouble logP_permutation = 0.; double tmp;\n\n\t\tstd::vector<unsigned int> v = arma::conv_to<std::vector<unsigned int>>::from(arma::sort(indexes));\n\t\t// vector should be sorted at the beginning.\n\n\t\tarma::uvec current_permutation;\n\t\tarma::vec current_weights;\n\t \tunsigned int i = 0;\n\n\t    do {\n\t        current_permutation = arma::conv_to<arma::uvec>::from(v);\n\t        current_weights = weights;\n\t\t\ttmp = 0.;\n\n\t\t\twhile( current_permutation.n_elem > 0 )\n\t\t\t{\n\t\t\t   tmp += log(current_weights(current_permutation(0)));\n\t\t\t   current_permutation.shed_row(0);\n\t\t\t   current_weights = current_weights/arma::sum(current_weights(current_permutation));   // this will gets array weights that do not sum to 1 in total, but will only use relevant elements\n    \t\t}\n\n\t\t\t++i;\n\t\t\tlogP_permutation = Utils::logspace_add(logP_permutation,tmp);\n\n\t    } while (std::next_permutation(v.begin(), v.end()));\n\n\t\treturn logP_permutation;\n\t}\n\n\n\tdouble logPDFIGamma(double x, double a, double b)\n\t{\n\t\tif( x < 0 || b < 0 || a < 0 )\n\t\t\treturn -std::numeric_limits<double>::infinity();\n\t\telse\n\t\t\treturn a*log(b) -std::lgamma(a) + (-a-1.)*log(x) -b/x;\n\t}\n\n\tdouble logPDFGamma(double x, double a, double b)\n\t{\n\t\tif( x < 0 || b < 0 || a < 0 )\n\t\t\treturn -std::numeric_limits<double>::infinity();\n\t\telse\n\t\t\treturn -a*log(b) -std::lgamma(a) + (a-1.)*log(x) -x/b;\n\t}\n\n\n\tdouble logPDFIWishart(const arma::mat& X, double nu, const arma::mat& Sigma)\n\t{\n\t\tunsigned int p = X.n_rows;\n\t\tdouble ret = -0.5*(double)p*nu*log(2) - lMvGamma(p,nu) - 0.5*arma::trace( Sigma * arma::inv_sympd(X) );\n\t\tdouble sign, tmp;\n\t\tarma::log_det(tmp, sign, X );\n\t\tret += -0.5*( (double)p + nu + 1. )*tmp;\n\n\t\tarma::log_det(tmp, sign, Sigma );\n\t\tret += +0.5*nu*tmp;\n\n\t\treturn ret;\n\t}\n\n\n\tdouble logPDFMN(const arma::mat& X, const arma::mat& rowCov, const arma::mat colCov)\n\t{\n\t\tunsigned int n = X.n_rows;\n\t\tunsigned int m = X.n_cols;\n\n\t\tdouble ret = -0.5*arma::trace( arma::inv_sympd(colCov) * X.t() * arma::inv_sympd(rowCov) * X ) -\n\t\t\t\t\t(double)n*(double)m*0.5*log(2*M_PI);\n\t\tdouble sign, tmp;\n\t\tarma::log_det(tmp, sign, colCov );\n\t\tret += -0.5*(double)n*tmp;\n\n\t\tarma::log_det(tmp, sign, rowCov );\n\t\tret += -0.5*(double)m*tmp;\n\n\t\treturn ret;\n\t}\n\n\n \tdouble logPDFNormal(const double& x, const double& m,const  double& sigmaSquare)\n\t{\n\n\t\treturn -0.5*log(2*M_PI) -0.5*log(sigmaSquare) -(0.5/sigmaSquare)*arma::as_scalar( pow(x-m,2) );\n\n\t}\n\n\n\tdouble logPDFNormal(const arma::vec& x, const  arma::mat& Sigma)  // zeroMean\n\t{\n\t\tunsigned int k = Sigma.n_cols;\n\n\t\tdouble sign, tmp;\n\t\tarma::log_det(tmp, sign, Sigma ); //sign is not importantas det SHOULD be > 0 as for positive definiteness!\n\n\t\treturn -0.5*(double)k*log(2*M_PI) -0.5*tmp -0.5* arma::as_scalar( (x).t() * arma::inv_sympd(Sigma) * (x) );\n\n\t}\n\n\n\tdouble logPDFNormal(const arma::vec& x, const arma::vec& m,const  arma::mat& Sigma)\n\t{\n\t\tunsigned int k = Sigma.n_cols;\n\n\t\tdouble sign, tmp;\n\t\tarma::log_det(tmp, sign, Sigma ); //sign is not importantas det SHOULD be > 0 as for positive definiteness!\n\n\t\treturn -0.5*(double)k*log(2*M_PI) -0.5*tmp -0.5* arma::as_scalar( (x-m).t() * arma::inv_sympd(Sigma) * (x-m) );\n\n\t}\n\n\tdouble logPDFNormal(const arma::vec& x, const arma::vec& m,const  double& Sigma)\n\t{\n\n\t\t//this is more a lok likelihood here, since the input vector is indep realisations with same sigma and (possibly) different means\n\t\tunsigned int n = x.n_elem;\n\n\t\treturn -0.5*(double)n*log(2*M_PI) -0.5*n*log(Sigma) -0.5/Sigma * arma::as_scalar( (x-m).t() * (x-m) );\n\n\t}\n\n\tdouble logPDFNormal(arma::vec& x, arma::vec& m, const arma::mat& rowCov ,const arma::mat& colCov)   // vectorised version of a matrix normal\n\t{\n\t\tunsigned int k = rowCov.n_rows;\n\t\tunsigned int d = colCov.n_rows;\n\n\t\tdouble logP = -0.5*(double)k*log(2*M_PI) - 0.5 * arma::as_scalar( ( (x-m).t() * arma::inv_sympd( arma::kron( colCov , rowCov ) ) * (x-m) ) );\n\n\t\tdouble sign, tmp;\n\t\tarma::log_det(tmp, sign, rowCov );\n\t\tlogP += -0.5*(double)d*tmp;\n\n\t\tarma::log_det(tmp, sign, colCov );\n\t\tlogP += -0.5*(double)k*tmp;\n\n\t\treturn logP;\n\t}\n\n\n\tdouble lBeta(double a,double b){    //log beta function\n\t\treturn std::lgamma(a) + std::lgamma(b) - std::lgamma(a+b);\n\t}\n\n\tdouble logPDFBeta(double x, double a, double b)\n\t{\n\t\tif( x <= 0. || x >= 1. )\n\t\t\treturn -std::numeric_limits<double>::infinity();\n\t\telse\n\t\t\treturn -lBeta(a,b) + (a-1)*log(x) + (b-1)*log(1-x);\n\t}\n\n\tdouble logPDFBernoulli(unsigned int x, double pi)\n\t{\n\t\tif( x > 1 ) // remember x is UNSIGNED int here\n\t\t\treturn -std::numeric_limits<double>::infinity();\n\t\telse\n\t\t\treturn x*log(pi) + (1-x)*log(1.-pi);\n\t}\n\n\tdouble CDFNormal(double x, double m, double sd)\n\t{\n\t\treturn 0.5 * std::erfc(-((x-m)/sd) * M_SQRT1_2); // ... right?\n\t}\n\n\tdouble invCDFNormal(double x, double m, double sd)\n\t{\n\t\treturn sqrt(2.) * boost::math::erf_inv(2.*((x-m)/sd)-1.);; // ... right?\n\t}\n\n\n\tdouble logPDFTruncNorm(double x, double m, double sd, double lower, double upper)\n\t{\n\t\tdouble truncNormConst = log( CDFNormal(upper,m,sd) - CDFNormal(lower,m,sd) );\n\t\treturn -log(sqrt(2*M_PI)) -log(sd) -0.5*(x-m)*(x-m)/(sd*sd) - truncNormConst;\n\t}\n\n\tdouble lMvGamma(unsigned int n, double a)\t\t\t\t\t// Multivariate GAMMA FUNCTION! NOT THE PDF/CDF\n\t{\n\t\tdouble lmvG = 0;\n\t\tfor(unsigned int j=0; j<n ; ++j)\n\t\t{\n\t\t\tlmvG += std::lgamma( a + 0.5*(1.-(double)j+1.) );   //last +1 cause indexes start from 0\n\t\t}\n\n\t\treturn (n*(n-1.)*0.25)*log(M_PI) + lmvG;\n\t}\n\n\n\n}\n", "meta": {"hexsha": "04fd2ae15b31d076eba01ab62e01d88a5e92df4d", "size": 18091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/distr.cpp", "max_stars_repo_name": "alexlewin24/Bayesian_SSUR_old", "max_stars_repo_head_hexsha": "3cf2e39181609b1a4caca91632201d8c3d075c9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distr.cpp", "max_issues_repo_name": "alexlewin24/Bayesian_SSUR_old", "max_issues_repo_head_hexsha": "3cf2e39181609b1a4caca91632201d8c3d075c9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-13T12:57:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-13T12:57:09.000Z", "max_forks_repo_path": "src/distr.cpp", "max_forks_repo_name": "alexlewin24/Bayesian_SSUR_old", "max_forks_repo_head_hexsha": "3cf2e39181609b1a4caca91632201d8c3d075c9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-16T14:43:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-16T14:43:06.000Z", "avg_line_length": 27.5357686454, "max_line_length": 189, "alphanum_fraction": 0.6370571002, "num_tokens": 5429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.634196631439057}}
{"text": "//\n// fibonacci.cpp\n//\n// Created by massimo on 3/16/18.\n//\n\n#include \"fibonacci.h\"\n\n#include <climits>\n#include <iostream>\n#include <boost/program_options.hpp>\n////////////////////////////////////////////////////////////////////////////////\nnamespace po      = boost::program_options;\nnamespace postyle = boost::program_options::command_line_style;\n////////////////////////////////////////////////////////////////////////////////\n\nstatic\nstd::pair<bigint::bigint, bigint::bigint>\nfast_fib_even(ui64 n)\n{\n  if ( 0 == n )\n  {\n    return std::make_pair(1, 0);\n  }\n  else if ( 2 == n )\n  {\n    return std::make_pair(1, 1);\n  }\n  else if ( 4 == n )\n  {\n    return std::make_pair(2, 3);\n  }\n  auto p = fast_fib((n >> 1) - 1);\n  auto c = p.first + p.second;\n  auto d = p.second + c;\n\n  return std::make_pair(p.second * d + p.first * c, c * (d + p.second));\n}\n\nstatic\nstd::pair<bigint::bigint, bigint::bigint>\nfast_fib(ui64 n)\n{\n if (isOdd(n))\n {\n   auto p = fast_fib_even(n - 1);\n   return std::make_pair(p.second, p.first + p.second);\n }\n else\n {\n   return fast_fib_even(n);\n }\n}\n\n\nstatic ui64 a;\nstatic ui64 b;\nstatic ui64 c;\nstatic ui64 d;\n\nstatic\nvoid\nfast_fib(ui64 n, ui64 ans[])\n{\n  if (0 == n)\n  {\n    ans[0] = 0;  // F(0)\n    ans[1] = 1;  // F(1)\n    return;\n  }\n\n  fast_fib((n >> 1), ans);\n\n  a = ans[0];  // F(n)\n  b = ans[1];  // F(n+1)\n  c = 2 * b - a;\n\n  c = (a * c);          // F(2n)\n  d = (a * a + b * b);  // F(2n + 1)\n  if (0 == n % 2)\n  {\n    ans[0] = c;\n    ans[1] = d;\n  }\n  else\n  {\n    ans[0] = d;\n    ans[1] = c + d;\n  }\n}\n\nstatic\nui64\nfastFib(ui64 n)\n{\n  if (n < 94)\n  {\n    ui64 ans[2] = {0};\n\n    fast_fib(n, ans);\n\n    return ans[0];\n  }\n  return 0;\n}\n\nstatic\nbigint::bigint\nfastFib(ui64 n, bool flag)\n{\n  if (n >= 94)\n  {\n    return fast_fib(n).second;\n  }\n  return 0;\n}\n\n////////////////////////////////////////////////////////////////////////////////\nint\nmain(const int argc, const char** argv)\n{\n  po::options_description desc(\"Options\");\n\n  desc.add_options()\n          (\"n,n\",    po::value<ui64>()->implicit_value(1)->default_value(1), \"the fib number we want to compute\")\n          (\"test,t\", po::value<bool>()->implicit_value(true)->default_value(false), \"test fib algorithms; no result is printed or saved on file\")\n          (\"help,h\",   \"Print this help message\")\n          ;\n\n  po::variables_map vm;\n\n  try\n  {\n    po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n\n    po::notify(vm);\n\n    if ( vm.count(\"help\") )\n    {\n      std::clog << \"[\" << __func__ << \"] \"\n                << \"USAGE: \"\n                << argv[0]\n                << \" options\\n\"\n                << desc\n                << '\\n';\n      return 0;\n    }\n  }\n  catch (const std::exception &e)\n  {\n    std::cerr << \"[\" << __func__ << \"] \"\n              << \"Error parsing command line: '\"\n              << e.what()\n              << \"'\"\n              << '\\n';\n\n    std::cerr << desc << '\\n';\n\n    return -1;\n  }\n\n  const ui64 N = vm[\"n\"].as<ui64>();\n  const bool testAlgo = vm[\"test\"].as<bool>();\n////////////////////////////////////////////////////////////////////////////////\n  if ( N < 94 )\n  {\n    ui64 fN = fastFib(N);\n    std::string sfN = std::to_string(fN);\n    std::string fileName{\"fib-\" + std::to_string(N) + \".txt\"};\n    utilities::cfile_helper::cfile_helper fs = utilities::cfile_helper::cfile_helper(fileName,\n                                                                                     utilities::cfile_helper::cfile_helper::fstream_direction::fs_OUTPUT);\n    fs.get_fstream() << sfN;\n\n    std::cout << \"[\" << __func__ << \"] \"\n              << \"fib(\"\n              << N\n              << \") = \"\n              << sfN\n              << \"\\nof length \"\n              << sfN.size()\n              << \" digits written to file \"\n              << fileName\n              << std::endl;\n  }\n  else  // when N >= 94\n  {\n//    [[maybe_unused]]\n//    auto\n//    fib = [&N]() {\n//      bigint::bigint fib_n;\n//      bigint::bigint fib_n_1;\n//      bigint::bigint fib_n_2;\n//      ui64 n{};\n//\n//      fib_n_1 = 1;\n//      fib_n_2 = 0;\n//\n//      for (n = 2; n <= N; ++n) {\n//        fib_n = fib_n_1 + fib_n_2;\n//        fib_n_2 = fib_n_1;\n//        fib_n_1 = fib_n;\n//      }\n//      return fib_n_1;\n//    };\n\n//    [[maybe_unused]]\n//    auto\n//    pfib = [&N]() {\n//      bigint::bigint *pfib_n = new bigint::bigint;\n//      bigint::bigint *pfib_n_1 = new bigint::bigint;\n//      bigint::bigint *pfib_n_2 = new bigint::bigint;\n//      ui64 n{};\n//\n//      *pfib_n_1 = 1;\n//      *pfib_n_2 = 0;\n//\n//      for (n = 2; n <= N; ++n) {\n//        *pfib_n = *pfib_n_1 + *pfib_n_2;\n//        std::swap(pfib_n_2, pfib_n);\n//        std::swap(pfib_n_2, pfib_n_1);\n//      }\n//      return *pfib_n_1;\n//    };\n\n    [[maybe_unused]]\n    auto\n    upfib = [&N]() {\n      std::unique_ptr<bigint::bigint> upfib_n = bigint::createUniquePtr();\n      std::unique_ptr<bigint::bigint> upfib_n_1 = bigint::createUniquePtr();\n      std::unique_ptr<bigint::bigint> upfib_n_2 = bigint::createUniquePtr();\n      ui64 n{};\n\n      *upfib_n_1 = 1;\n      *upfib_n_2 = 0;\n\n      for (n = 2; n <= N; ++n) {\n        *upfib_n = *upfib_n_1 + *upfib_n_2;\n        std::swap(upfib_n_2, upfib_n);\n        std::swap(upfib_n_2, upfib_n_1);\n      }\n      return *upfib_n_1;\n    };\n\n//    bigint::bigint fN;\n\n    if ( bigint::bigint fN; false == testAlgo )\n    {\n      fN = upfib();\n\n      std::string fileName{\"fib-\" + std::to_string(N) + \".txt\"};\n      utilities::cfile_helper::cfile_helper fs = utilities::cfile_helper::cfile_helper(fileName,\n                                                                                       utilities::cfile_helper::cfile_helper::fstream_direction::fs_OUTPUT);\n      fs.get_fstream() << fN;\n\n      std::cout << \"[\" << __func__ << \"] \"\n                << \"fib(\"\n                << N\n                << \") of length \"\n                << bigint::numberOfDigits(fN)\n                << \" digits written to file \"\n                << fileName\n                << std::endl;\n    }\n    else\n    {\n      [[maybe_unused]]\n      auto\n      upfibTest = [](const ui64 &N)\n      {\n        std::unique_ptr<bigint::bigint> upfib_n = bigint::createUniquePtr();\n        std::unique_ptr<bigint::bigint> upfib_n_1 = bigint::createUniquePtr();\n        std::unique_ptr<bigint::bigint> upfib_n_2 = bigint::createUniquePtr();\n        ui64 n{};\n\n        *upfib_n_1 = 1;\n        *upfib_n_2 = 0;\n\n        for (n = 2; n <= N; ++n)\n        {\n          *upfib_n = *upfib_n_1 + *upfib_n_2;\n          std::swap(upfib_n_2, upfib_n);\n          std::swap(upfib_n_2, upfib_n_1);\n        }\n        return *upfib_n_1;\n      };\n\n      bigint::bigint fNnew;\n      for (ui64 n{94}; n <= N; ++n)\n      {\n        fN = upfibTest(n);\n        fNnew = fastFib(n, true);\n\n        if (fN != fNnew)\n        {\n          std::cout << n << \": \" << \"DIFFERENT\" << std::endl;\n\n          std::stringstream olds{};\n          std::stringstream news{};\n          olds << fN;\n          news << fNnew;\n          if (olds.str().size() != news.str().size())\n          {\n            std::cout << n << \": \" << \"LENGTHS DIFFER\" << std::endl;\n          }\n          exit(2);\n\n//          for (size_t i{0}; i < olds.str().size(); ++i)\n//          {\n//            if (olds.str()[i] != news.str()[i]) {\n//              std::cout << \"differ at index \"\n//                        << i\n//                        << \" -> '\"\n//                        << static_cast<char>(olds.str()[i])\n//                        << \"' - '\"\n//                        << static_cast<char>(news.str()[i])\n//                        << \"'\"\n//                        << std::endl;\n//            }\n        }\n//        else\n//        {\n//          std::cout << n << \": \" << \"EQUAL\" << std::endl;\n//        }\n      }\n      std::cout << \"[\" << __func__ << \"] \"\n                << \"fib(\"\n                << N\n                << \") was computed correctly\"\n                << std::endl;\n    }\n  }\n  return 0;\n}\n", "meta": {"hexsha": "8a183e48a81cb13f16678d1e87c47053701280f7", "size": 7931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fibonacci/fibonacci.cpp", "max_stars_repo_name": "massimo-marino/bigint", "max_stars_repo_head_hexsha": "ed1e615145d6b2cdcc743663156985baa95f2a65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-11-06T04:01:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T02:05:29.000Z", "max_issues_repo_path": "src/fibonacci/fibonacci.cpp", "max_issues_repo_name": "massimo-marino/bigint", "max_issues_repo_head_hexsha": "ed1e615145d6b2cdcc743663156985baa95f2a65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fibonacci/fibonacci.cpp", "max_forks_repo_name": "massimo-marino/bigint", "max_forks_repo_head_hexsha": "ed1e615145d6b2cdcc743663156985baa95f2a65", "max_forks_repo_licenses": ["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.745508982, "max_line_length": 156, "alphanum_fraction": 0.4377758164, "num_tokens": 2307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6341966305659156}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  GeneralizedEigenSolver<MatrixXf> ges;\nMatrixXf A = MatrixXf::Random(4,4);\nMatrixXf B = MatrixXf::Random(4,4);\nges.compute(A, B);\ncout << \"The (complex) numerators of the generalzied eigenvalues are: \" << ges.alphas().transpose() << endl;\ncout << \"The (real) denominatore of the generalzied eigenvalues are: \" << ges.betas().transpose() << endl;\ncout << \"The (complex) generalzied eigenvalues are (alphas./beta): \" << ges.eigenvalues().transpose() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "ee3a20394f16af75118269c4483258436abc97b1", "size": 607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_GeneralizedEigenSolver.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_GeneralizedEigenSolver.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_GeneralizedEigenSolver.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.35, "max_line_length": 110, "alphanum_fraction": 0.6985172982, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6341966266409489}}
{"text": "\ufeff#include <iostream>\n#include <string>\n#include <fstream>\n#include <cmath>\n#include <map>\n#include <vector>\n#include <ctime>\n#include <windows.h> \n#include <sstream>\n#include <float.h>\n#include <pcl/point_types.h>\n//#include <pcl/io/pcd_io.h>\n\n#include <Eigen/Dense>  \n#include <vector>\n#include <math.h>\n\nusing namespace Eigen;\nusing namespace Eigen::internal;  \nusing namespace Eigen::Architecture;  \nusing namespace pcl;\nusing namespace std;\n\nconst int ERROR_RANGE = 5;\nconst int COUNT_RANGE = 10;\nint TTTTT = 0;\nint KKKKK = 0;\n\n\ninline  int string2int(std::string s)\n{\n    int n = atoi(s.c_str());\n\treturn n;\n}\n\ninline float string2float(std::string str)\n{\n\tfloat result = atof(str.c_str());\n\treturn result;\n}\n\ninline double string2double(std::string str)\n{\n\tdouble result;\n\tstringstream sstr(str);\n\tsstr >> result;\n\treturn result;\n}\n\ninline long string2long(std::string str)\n{\n   long result = atol(str.c_str());\n   return result;\n}\n\nstd::string double2String(double d) \n{  \n\tstd::ostringstream os;  \n\t if (os << d)\n\t    return os.str();\n\t else\n\t\t return \"double2string error!\";\n}  \n\ninline void cutstring(std::string s ,int a[])\n{ \n\tstd::string flag = \":\";  \n\tstd::string::size_type position=0; \n\tint i=0;  \n\twhile((position=s.find_first_of(flag,position)) != std::string::npos)  \n\t{  \n\t\t//\t  std::cout<< \"position  \" << i << \" : \" << position << std::endl;  \n\t\ta[i] = position;\n\t\tposition++;  \n\t\ti++;  \n\t}  \n}\n\n//Akima\u65b9\u6cd5\nclass  akima\n{\nprivate: \n\tint n, k;\n\tdouble  *x, *y, t, z, s[4];\npublic:\n\takima (int nn)\n\t{\n\t\tn = nn;\n\t\tx = new double[n];    //\u52a8\u6001\u5206\u914d\u5185\u5b58\n\t\ty = new double[n];\n\t}\n\tvoid input(const std::vector<double> &X, const std::vector<double> &Y);          //\u7531\u6587\u4ef6\u8bfb\u5165n\u4e2a\u6570\u636e\u70b9(x, y)\n\tdouble interp(double);  //\u8ba1\u7b97\u63d2\u503c\u70b9t\u6240\u5728\u5b50\u533a\u95f4\u4e0a\u7684\u4e09\u6b21\u591a\u9879\u5f0f\n\t//\u5e76\u8ba1\u7b97t\u70b9\u7684\u8fd1\u4f3c\u503cz\n\tvoid output(); //\u8f93\u51fa\u4e09\u6b21\u591a\u9879\u5f0f\u7cfb\u6570\u4ee5\u53cat\u70b9\u7684\u8fd1\u4f3c\u503cz\u5230\u6587\u4ef6\u5e76\u663e\u793a\n\t~akima()\n\t{\n\t\tdelete []x;  \n\t    delete []y;\n\t}\n};\n\nvoid akima::input(const std::vector<double> &X, const std::vector<double> &Y)\n{\n    for (int i = 0; i < X.size(); i++)\n\t{\n\t x[i] = X[i];\n\t y[i] = Y[i];\n\t}\n}\n\ndouble akima::interp(double tt)    ////\u8ba1\u7b97\u63d2\u503c\u70b9t\u6240\u5728\u5b50\u533a\u95f4\u4e0a\u7684\u4e09\u6b21\u591a\u9879\u5f0f\n{ \n\t//\u5e76\u8ba1\u7b97t\u70b9\u7684\u8fd1\u4f3c\u503cz\n\tint m,kk;\n\tdouble u[5],p,q;\n\tt = tt;\n\tz=0.0; s[0]=0.0; s[1]=0.0; s[2]=0.0; s[3]=0.0;\n\tif (n<1) { k = 0; return z; }\n\tif (n==1) { k = 0; s[0]=y[0]; z=y[0]; return z;}\n\tif (n==2)\n\t{ \n\t\tk = 0;\n\t\ts[0]=y[0]; s[1]=(y[1]-y[0])/(x[1]-x[0]);\n\t\tz=(y[0]*(t-x[1])-y[1]*(t-x[0]))/(x[0]-x[1]);\n\t\treturn z;\n\t}\n\tif (t<=x[1]) k=0;\n\telse if (t>=x[n-1]) k=n-2;\n\telse\n\t{ \n\t\tk=1; m=n;\n\t\twhile (((k-m)!=1)&&((k-m)!=-1))\n\t\t{ \n\t\t\tkk=(k+m)/2;\n\t\t\tif (t<x[kk-1]) m=kk;\n\t\t\telse k=kk;\n\t\t}\n\t\tk=k-1;\n\t}\n\tu[2]=(y[k+1]-y[k])/(x[k+1]-x[k]);\n\tif (n==3)\n\t{ \n\t\tif (k==0)\n\t\t{ \n\t\t\tu[3]=(y[2]-y[1])/(x[2]-x[1]);\n\t\t\tu[4]=2.0*u[3]-u[2];\n\t\t\tu[1]=2.0*u[2]-u[3];\n\t\t\tu[0]=2.0*u[1]-u[2];\n\t\t}\n\t\telse\n\t\t{ \n\t\t\tu[1]=(y[1]-y[0])/(x[1]-x[0]);\n\t\t\tu[0]=2.0*u[1]-u[2];\n\t\t\tu[3]=2.0*u[2]-u[1];\n\t\t\tu[4]=2.0*u[3]-u[2];\n\t\t}\n\t}\n\telse\n\t{ \n\t\tif (k<=1)\n\t\t{ \n\t\t\tu[3]=(y[k+2]-y[k+1])/(x[k+2]-x[k+1]);\n\t\t\tif (k==1)\n\t\t\t{ \n\t\t\t\tu[1]=(y[1]-y[0])/(x[1]-x[0]);\n\t\t\t\tu[0]=2.0*u[1]-u[2];\n\t\t\t\tif (n==4) u[4]=2.0*u[3]-u[2];\n\t\t\t\telse u[4]=(y[4]-y[3])/(x[4]-x[3]);\n\t\t\t}\n\t\t\telse\n\t\t\t{ \n\t\t\t\tu[1]=2.0*u[2]-u[3];\n\t\t\t\tu[0]=2.0*u[1]-u[2];\n\t\t\t\tu[4]=(y[3]-y[2])/(x[3]-x[2]);\n\t\t\t}\n\t\t}\n\t\telse if (k>=(n-3))\n\t\t{ \n\t\t\tu[1]=(y[k]-y[k-1])/(x[k]-x[k-1]);\n\t\t\tif (k==(n-3))\n\t\t\t{ \n\t\t\t\tu[3]=(y[n-1]-y[n-2])/(x[n-1]-x[n-2]);\n\t\t\t\tu[4]=2.0*u[3]-u[2];\n\t\t\t\tif (n==4) u[0]=2.0*u[1]-u[2];\n\t\t\t\telse u[0]=(y[k-1]-y[k-2])/(x[k-1]-x[k-2]);\n\t\t\t}\n\t\t\telse\n\t\t\t{ \n\t\t\t\tu[3]=2.0*u[2]-u[1];\n\t\t\t\tu[4]=2.0*u[3]-u[2];\n\t\t\t\tu[0]=(y[k-1]-y[k-2])/(x[k-1]-x[k-2]);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{ \n\t\t\tu[1]=(y[k]-y[k-1])/(x[k]-x[k-1]);\n\t\t\tu[0]=(y[k-1]-y[k-2])/(x[k-1]-x[k-2]);\n\t\t\tu[3]=(y[k+2]-y[k+1])/(x[k+2]-x[k+1]);\n\t\t\tu[4]=(y[k+3]-y[k+2])/(x[k+3]-x[k+2]);\n\t\t}\n\t}\n\ts[0]=fabs(u[3]-u[2]);\n\ts[1]=fabs(u[0]-u[1]);\n\tif ((s[0]+1.0==1.0)&&(s[1]+1.0==1.0))\n\t\tp=(u[1]+u[2])/2.0;\n\telse p=(s[0]*u[1]+s[1]*u[2])/(s[0]+s[1]);\n\ts[0]=fabs(u[3]-u[4]);\n\ts[1]=fabs(u[2]-u[1]);\n\tif ((s[0]+1.0==1.0)&&(s[1]+1.0==1.0))\n\t\tq=(u[2]+u[3])/2.0;\n\telse q=(s[0]*u[2]+s[1]*u[3])/(s[0]+s[1]);\n\ts[0]=y[k];\n\ts[1]=p;\n\ts[3]=x[k+1]-x[k];\n\ts[2]=(3.0*u[2]-2.0*p-q)/s[3];\n\ts[3]=(q+p-2.0*u[2])/(s[3]*s[3]);\n\tp=t-x[k];\n\tz=s[0]+s[1]*p+s[2]*p*p+s[3]*p*p*p;\n\treturn z;\n}\n\nvoid akima::output ()//\u8f93\u51fa\u4e09\u6b21\u591a\u9879\u5f0f\u7cfb\u6570\u4ee5\u53cat\u70b9\u7684\u8fd1\u4f3c\u503cz\u5230\u6587\u4ef6\u5e76\u663e\u793a\n{\n\tchar str2[20];\n\tcout <<\"\\n\u8f93\u51fa\u6587\u4ef6\u540d:  \";\n\tcin >>str2;\n\tofstream fout (str2, ios::app);\n\tif (!fout)\n\t{ cout <<\"\\n\u4e0d\u80fd\u6253\u5f00\u8fd9\u4e2a\u6587\u4ef6 \" <<str2 <<endl; exit(1); }\n\tfout <<endl;  cout <<endl;\n\tfout <<k <<\":\" <<endl;\n\tfout <<s[0] <<\"   \" <<s[1] <<\"   \" <<s[2] <<\"   \" <<s[3] <<endl;\n\tcout <<k <<\":\" <<endl;\n\tcout <<s[0] <<\"   \" <<s[1] <<\"   \" <<s[2] <<\"   \" <<s[3] <<endl;\n\tfout <<endl <<t <<\"   \" <<z <<endl;\n\tcout <<endl <<t <<\"   \" <<z <<endl;\n\tfout.close ();\n}\n/*\nvoid main ()      //\u4e3b\u51fd\u6570\n{\n\takima  solution(11); \n\tsolution.input ();          //\u7531\u6587\u4ef6\u8bfb\u5165n\u4e2a\u6570\u636e\u70b9(x, y)\n\tsolution.interp (-0.85);         //\u6267\u884cAkima\u65b9\u6cd5\n\tsolution.output ();//\u8f93\u51fa\u4e09\u6b21\u591a\u9879\u5f0f\u7cfb\u6570\u4ee5\u53cat\u70b9\u7684\u8fd1\u4f3c\u503cz\u5230\u6587\u4ef6\u5e76\u663e\u793a\n\tsolution.interp (0.15);         //\u6267\u884cAkima\u65b9\u6cd5\n\tsolution.output ();//\u8f93\u51fa\u4e09\u6b21\u591a\u9879\u5f0f\u7cfb\u6570\u4ee5\u53cat\u70b9\u7684\u8fd1\u4f3c\u503cz\u5230\u6587\u4ef6\u5e76\u663e\u793a\t  \n}\n*/\n\ndouble Assum(vector<double> &vec)\n{\n\tstd::size_t len = vec.size();\n\tdouble sum = 0;\n\tfor (int i = 0; i < len; i++)\n\t{\n\t sum += vec[i];\n\t}\n\n\treturn (static_cast<double>(sum) / len);\n}\n\nvoid Seprate2GetTrans(const string recorder_str, \n\t                     Matrix4d &rotation, \n\t\t\t\t\t     Vector3d &Origanl_XYZ,\n\t\t\t\t    const string previous_time,\n\t\t\t\t    const string current_time)\n{\n\tint a[10] = {0};\n\tcutstring(recorder_str,a);\n\tVector4d q;\n\tVector3d vel;\n/*\n    //////////////////////////////////////////////////////////\t\t \n\t\t 2\ud835\udc5e02+2\ud835\udc5e12\u22121  2\ud835\udc5e1\ud835\udc5e2\u22122\ud835\udc5e0\ud835\udc5e3   2\ud835\udc5e1\ud835\udc5e3+2\ud835\udc5e0\ud835\udc5e2 \n\t\t 2\ud835\udc5e1\ud835\udc5e2+2\ud835\udc5e0\ud835\udc5e3  2\ud835\udc5e02+2\ud835\udc5e22\u22121   2\ud835\udc5e2\ud835\udc5e3\u22122\ud835\udc5e0\ud835\udc5e1\n\t\t 2\ud835\udc5e1\ud835\udc5e3\u22122\ud835\udc5e0\ud835\udc5e2  2\ud835\udc5e2\ud835\udc5e3+2\ud835\udc5e0\ud835\udc5e1   2\ud835\udc5e02+2\ud835\udc5e32\u22121\n*/\n\tq(0) = string2double(recorder_str.substr(a[0]+1, a[1] - a[0] - 1).c_str());\n\tq(1) = string2double(recorder_str.substr(a[1]+1, a[2] - a[1] - 1).c_str());\n\tq(2) = string2double(recorder_str.substr(a[2]+1, a[3] - a[2] - 1).c_str());\n\tq(3) = string2double(recorder_str.substr(a[3]+1, a[4] - a[3] - 1).c_str());\n\n    int delta_time = string2int(current_time.substr(4).c_str()) - string2int(previous_time.substr(4).c_str());\n\n\tvel(0) =  string2double(recorder_str.substr(a[4]+1, a[5] - a[4] - 1).c_str());\n\tvel(1) =  string2double(recorder_str.substr(a[5]+1, a[6] - a[5] - 1).c_str());\n\tvel(2) =  string2double(recorder_str.substr(a[6]+1).c_str());\n\n\tOriganl_XYZ += static_cast<double>(delta_time)*vel / 3 ;\n\tdouble  w = q(0), x = q(1) , y = q(2) , z = q(3);\n\n\trotation(0,0) = 2 * ( pow(q(0),2) + pow(q(1),2) ) - 1;\n\trotation(0,1) = 2 * q(1) * q(2) - 2 * q(0) * q(3);\n\trotation(0,2) = 2 * q(1) * q(3) + 2 * q(0) * q(2);\n\trotation(0,3) = Origanl_XYZ(0);\n\n\trotation(1,0) = 2 * q(1) * q(2) + 2 * q(0) * q(3);\n\trotation(1,1) = 2 * ( pow(q(0),2) + pow(q(2),2) ) - 1;\n\trotation(1,2) = 2 * q(2) * q(3) - 2 * q(0) * q(1);\n\trotation(1,3) = Origanl_XYZ(1);\n\n\trotation(2,0) = 2 * q(1) * q(3) - 2 * q(0) * q(2);\n\trotation(2,1) = 2 * q(2) * q(3) + 2 * q(0) * q(1);\n\trotation(2,2) = 2 * ( pow(q(0),2) + pow(q(3),2) ) - 1;\n\t//rotation(2,3) = Origanl_XYZ(2);\n\trotation(2,3) = 0;\n\t\n\n  /*\n    | 1\u22122(y2+z2)  2(xy+zw)      2(xz\u2212yw)\n\t| 2(xy\u2212zw)    1\u22122(x2+z2)   2(yz+xw)\n\t| 2(xz+yw)     2(yz\u2212xw)    1\u22122(x2+y2)\n   */\n\t/*\n\trotation(0,0) = - 2 * ( pow(q(2),2) + pow(q(3),2) ) + 1;\n\trotation(0,1) = 2 * q(1) * q(2) - 2 * q(0) * q(3);\n\trotation(0,2) = 2 * q(1) * q(3) - 2 * q(0) * q(2);\n\trotation(0,3) = Origanl_XYZ(0);\n\n\trotation(1,0) = 2 * q(1) * q(2) - 2 * q(0) * q(3);\n\trotation(1,1) = - 2 * ( pow(q(1),2) - pow(q(3),2) ) + 1;\n\trotation(1,2) = 2 * q(2) * q(3) + 2 * q(0) * q(1);\n\trotation(1,3) = Origanl_XYZ(1);\n\n\trotation(2,0) = 2 * q(1) * q(3) + 2 * q(0) * q(2);\n\trotation(2,1) = 2 * q(2) * q(3) + 2 * q(0) * q(1);\n\trotation(2,2) = - 2 * ( pow(q(1),2) + pow(q(2),2) ) + 1;\n\trotation(2,3) = Origanl_XYZ(2);\n\t//rotation(2,3) = 0;\n\t*/\n\t////////////////////////////////////\n\t/*\n\tr(1,1)=1-2*y*y-2*z*z;  \n\tr(1,2)=2*x*y+2*w*z;  \n\tr(1,3)=2*x*z-2*w*y;  \n\n\tr(2,1)=2*x*y-2*w*z;  \n\tr(2,2)=1-2*x*x-2*z*z;  \n\tr(2,3)=2*z*y+2*w*x;  \n\n\tr(3,1)=2*x*z+2*w*y;  \n\tr(3,2)=2*y*z-2*w*x;  \n\tr(3,3)=1-2*x*x-2*y*y;  \n\t*/\n\t/*\n\trotation(0,0) = 1 - ( 2*y*y + 2*z*z);  \n\trotation(0,1) = 2*x*y - 2*w*z;  \n\trotation(0,2) = 2*x*z - 2*w*y;  \n\trotation(0,3) = Origanl_XYZ(0);\n\n\trotation(1,0) = 2*x*y - 2*w*z;  \n\trotation(1,1) = 1 + ( 2*x*x - 2*z*z );  \n\trotation(1,2) = 2*z*y + 2*w*x;  \n\trotation(1,3) = Origanl_XYZ(1);\n\n\trotation(2,0) = 2*x*z + 2*w*y;  \n\trotation(2,1) = 2*y*z + 2*w*x;  \n\trotation(2,2) = 1 - ( 2*x*x + 2*y*y );  \n\trotation(2,3) = Origanl_XYZ(2);\n\t//rotation(2,3) = 0;\n\t\n\trotation(3,0) = 0;\n\trotation(3,1) = 0;\n\trotation(3,2) = 0;\n\trotation(3,3) = 1;\n\t*/\n}\n\nvoid Seprate2GetPCvec(const string str, Vector4d &point,const int signal[5],const Vector3d &coor)\n{\n\tpoint(0) = string2double(str.substr(0, signal[0]).c_str());\n\tpoint(1) = string2double(str.substr(signal[0] + 1, signal[1] - signal[0] -1).c_str());\n    point(2) = 0;\n // point(2) = coor(2);\n\tpoint(3) = 1;\n}\n\nvoid Combine2PCL(std::map<std::string, std::string> &mymap,const char *str)\n{\n    if (str == NULL)\n\t{\n\t    std::cout << __FILE__<<\":\"<<__LINE__ <<\"  File ERROR!\"<<std::endl;\n\t    return ;\n\t}\n\n\tstd::ifstream input(str);\n\tint number = -1;\n\tif (input.is_open())\n\t{\n\t\tstd::string str = \"\";\n\t\tstd::string prefix_timestamp = \"\";\n\n\t\tpcl::PointCloud<pcl::PointXYZI> TotalCloud;\n\t\tpcl::PointCloud<pcl::PointXYZI> midcloud;\n\t\t\n\t\tMatrix4d rotation;//\u65cb\u8f6c\u53d8\u6362\u7684\u77e9\u9635\uff0c\u4e3a4*4\u7684\u77e9\u9635\uff0c\u591a\u4e00\u7ef4\u662f\u4e3a\u4e86\u6dfb\u52a0\u8fdb\u5165\u5e73\u79fb\u53d8\u6362\u3002\n\t\tVector4d f; f(3) = 1; //\u6bcf\u4e00\u4e2a\u70b9\u5728\u5c40\u90e8\u5750\u6807\u7cfb\u4e2d\u7684\u4f4d\u7f6e\n\t\tVector3d current_position ;//\u7b2ck\u5e27\u65f6\u523b\u7684\u5750\u6807\u7cfb\u8ddd\u79bb\u539f\u70b9\u7684\u4f4d\u7f6e\n\t\tcurrent_position(0) = current_position(1) = current_position(2) = 0.0;\n\t\tlong int i = 0;\n\n\t\tstring current_timestamp;\n\t\tstring previous_timestamp;\n\n\t\twhile ( getline(input,str) )\n\t\t{\n\t\t\tif (str.find(\"x86isnice\") != std::string::npos)\n\t\t\t{\n\t\t\t\tnumber++;\n\t\t\t\tTotalCloud += midcloud;\n\t\t\t\tstd::size_t count  = string2int(str.substr(0,str.find_first_of(\" \")));\n\t\t\t\n\t\t\t\tmidcloud.clear();\n\t\t\t\tpcl::PointCloud<pcl::PointXYZI>().swap(midcloud);\n\n\t\t\t\ti = 0;\n\t\t\t\tmidcloud.height = 1;\n\t\t\t\tmidcloud.width = count;\n\t\t\t\tmidcloud.is_dense = true;\n\t\t\t\tmidcloud.resize(midcloud.width  *  midcloud.height);\n\n\t\t\t\tgetline(input ,str);\n\t\t\t\n\t\t\t\tint signal[5] = {0};\n\t\t\t\tcutstring(str,signal);\n\t\t\t\tprefix_timestamp = str.substr(signal[1]+1,signal[2] - signal[1] - 1);\n\t\t\t\tstring  recorder_str = mymap[prefix_timestamp];\n\t\t\t\t/*\u5206\u5272\u51fa\u53c2\u6570\uff0c\u83b7\u5f97\u8f6c\u6362\u77e9\u9635\u7684\u66f4\u65b0*///Seprate2GetTrans(string recorder_str, Vector4d transform, Vector3d Origanl_XYZ,string previous_time,string current_time)\n\t\t\t\t                              //Seprate2GetPCvec(string str, Vector4d point,int signal[5])\n\t\t\t\tif ( 0 == number )\n\t\t\t\t{\n\t\t\t\t   current_timestamp = previous_timestamp = prefix_timestamp;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t   previous_timestamp = current_timestamp;\n\t\t\t\t   current_timestamp = prefix_timestamp;\n\t\t\t\t}\n\n\t\t\t\tSeprate2GetTrans(recorder_str,rotation, current_position, previous_timestamp,current_timestamp);\n\t\t\t\t/*\u5206\u5272\u51fa\u53c2\u6570\uff0c\u83b7\u5f97\u8f6c\u6362\u77e9\u9635\u7684\u66f4\u65b0*/\n\t\t\t\t//Seprate2GetPCvec( str, f, signal);//QQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\t\t\t\tSeprate2GetPCvec( str, f, signal,current_position);//QQ\n\n\t\t\t\tf = rotation * f;\n\t\t\t\tmidcloud.points[i].x = f(0);\n\t\t\t\tmidcloud.points[i].y = f(1);\n\t\t\t\tmidcloud.points[i].z = f(2);\n\t\t\t\tmidcloud.points[i].intensity = string2double(str.substr(signal[2] + 1 , signal[3] - signal[2] - 1));\n\t\t\t\ti++;\n\t\t\t}\n\t\t\telse\n\t\t\t{   \n\t\t\t\tint signal[5] = {0}; \n\t\t\t\tcutstring(str,signal);\n\t\t\t\t//Seprate2GetPCvec( str, f, signal);QQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n\t\t\t\tSeprate2GetPCvec( str, f, signal,current_position);//QQ\n\t\t\t\tf = rotation * f;\n\t\t\t\tmidcloud.points[i].x = f(0);\n\t\t\t\tmidcloud.points[i].y = f(1);\n\t\t\t\tmidcloud.points[i].z = f(2);\n\t\t\t\tmidcloud.points[i].intensity = string2double(str.substr(signal[2] + 1 , signal[3] - signal[2] - 1));\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\n\t\tTotalCloud += midcloud;\n\n\t\tofstream outpcd(\"../mypcd.pcd\");\n\n\t\toutpcd << \"# .PCD v.7 - Point Cloud Data file format\"<<std::endl;\n\t\toutpcd << \"VERSION 0.7\" << std::endl;\n\t\toutpcd << \"FIELDS x y z intensity\" << std::endl;\n\t\toutpcd << \"SIZE 4 4 4 4\" <<std::endl;\n\t\toutpcd << \"TYPE F F F F\" <<std::endl;\n\t\toutpcd << \"COUNT 1 1 1 1\" <<std::endl;\n\t\toutpcd << \"WIDTH \" << TotalCloud.size() << std::endl;\n\t\toutpcd << \"HEIGHT 1\" <<std::endl;\n\t\toutpcd << \"VIEWPOINT 0 0 0 1 0 0 0\" <<std::endl;\n\t\toutpcd << \"POINTS \" << TotalCloud.size() << std::endl;\n\t\toutpcd << \"DATA ascii\" << std::endl;\n\n\t\tfor (std::size_t pp = 0; pp < static_cast<std::size_t>(TotalCloud.size()); pp++)\n\t\t{\n\t\t     outpcd << TotalCloud.points[pp].x<<\"  \"<< TotalCloud.points[pp].y << \"  \" << TotalCloud.points[pp].z<< \"  \"<< TotalCloud.points[pp].intensity << std::endl;\n\t\t}\n\t\toutpcd.close();\n\t//\tpcl::io::savePCDFile(\"../pp.pcd\",TotalCloud);\n\n\t\tinput.close();\n\t\tstd::cerr<<\"Research completed!  \"<<TotalCloud.size() << std::endl;\n\t}\n\telse\n\t{\n\t\tstd::cerr << \"One of the file is not Open ,please check!\" << endl; \n\t\texit(EXIT_FAILURE);\n\t}\n}\n\n#if 1\n\nint main()//\u52a8\u6001\u89c4\u5212\u5339\u914d\n{\n\t ifstream xsens;\n\t ifstream laser;\n\t std::map<string , string> recorder;\n\n\t clock_t start , finish;\n\n\t string laserfile = \"E:/binding/1450857349-laser.txt\";\n\t string xsensfile = \"E:/binding/1450857349-Xsnes.txt\";\n\t// xsens.open(\"D:\\\\1448246245-Xsnes.txt\");\n\t// laser.open(\"D:\\\\test.txt\");\n\t laser.open(laserfile);\n\t xsens.open(xsensfile);\n\n\t if (laser.is_open() && xsens.is_open())\n\t {\n\t\t start = clock();\n\t     string str;\n\t\t vector<string> log;\n\n\t\t vector<string> xsens_log; //record th log of xsens to interplot value @ \"ERROR\"\n\n\t\t while ( getline(laser,str) )\n\t\t {\n\t\t    if (str.find(\"x86isnice\") != std::string::npos)\n\t\t\t{\n\t\t\t\tstring xx;\n\t\t\t\tgetline(laser,str);\n\t\t\t\tint laser_signal[5] = {0};\n\t\t\t\tcutstring(str,laser_signal);\n\t\t\t\tint laser_result = string2int(str.substr(laser_signal[1]+5,laser_signal[2] - laser_signal[1] - 5));//@@@@@@@@@@@@@@@@@@@@\n\t\t\t//\tint laser_result = string2int(str.substr(laser_signal[1]+4,laser_signal[2] - laser_signal[1] - 5));\n\t\t\t\tint xsens_signal[10] = {0};\n\t\t\t\tint xsens_result = 0;\n\t\t\t\tint count = 0;\n\n\t\t\t    bool flag = 0;\n\t\t\n\t\t\t\tif ( !log.empty() )\n\t\t\t\t{\n\t\t\t\t  for (vector<string>::iterator it = log.begin(); it != log.end(); it++)\n\t\t\t\t  {  \n\t\t\t\t\t   cutstring(*it ,xsens_signal);\n\t\t\t\t\t   xsens_result = string2int(it->substr( 4, 10));\n\t\t\t\t\t   if ( abs(laser_result - xsens_result) <= ERROR_RANGE)\n\t\t\t\t\t   {\n\t\t\t\t\t    // recorder.insert(pair<string,string>(str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1), it->substr(0,13)));\n\t\t\t\t\t\t   recorder.insert(pair<string,string>(str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1), *it));\n\t\t\t\t\t\t   flag = 1;\n\t\t\t\t\t\t  break;\n\t\t\t\t\t   }\n\t\t\t\t  }\n\t              if ( flag == 1)\n\t\t\t\t  {\n\t\t\t\t//\t  log.clear();\n\t\t\t\t//\t  vector<string>().swap(log);\n\t\t\t\t\t  \n\t\t\t\t\t  vector<string>::iterator it = log.begin();\n\t\t\t\t\t  vector<string>::iterator xl = xsens_log.begin();\n\t\t\t\t\t  //while (it != log.end() && it->compare(xx.substr(0,13)) < 0)\n\t\t\t\t\t // while (it != log.end() && it->compare(str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1)) < 0)\n\t\t\t\t\t  while (it != log.end() && (it->substr(0,13)).compare(str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1)) < 0)\n\t\t\t\t\t  {//(it->substr(0,13)).compare(str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1);\n\t\t\t\t\t\t  it = log.erase(it);\n\t\t\t\t\t\t  xl = xsens_log.erase(xl);\n\t\t\t\t\t  }\n\t\t\t\t\t  //xsens_log to clear-------------------------------------------//\n\t\t\t\t  }\n\t\t\t\t}\n\n\t\t\t\tif ( flag == 0 )\n\t\t\t\t{\t\n\t\t\t\t\tbool tag = 0;\n\t\t\t\t\tdo \n\t\t\t\t\t{\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t  \n\t\t\t\t\t\tgetline( xsens, xx);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ( xx == \"\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttag = 1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcutstring( xx, xsens_signal);\n\t\t\t\t\t\t//log.push_back(xx.substr(0,13));\n\t\t\t\t\t\tlog.push_back(xx);\n\t\t\t\t\t\txsens_log.push_back(xx);//xsens_log\u7684\u8bb0\u5f55\uff0c\u5e76\u67e5\u96c6\u5408//////////////////////////////////////////////\n\n\t\t\t\t\t\txsens_result = string2int(xx.substr( 4, 10));\n\t\t\t\t\t} while (abs(laser_result - xsens_result) > ERROR_RANGE  && !xsens.eof() && count < COUNT_RANGE);\n\n\t\t\t\t\t//\tif (count < COUNT_RANGE )\n\t\t\t\t\tif (count < COUNT_RANGE && tag != 1)\t\t\t\n\t\t\t\t\t{  \n\t\t\t\t\t   //while (it != log.end() && it->compare(xx.substr(0,13)) < 0)\n\t\t\t\t\t    vector<string>::iterator it = log.begin();\t\n\t\t\t\t\t\tvector<string>::iterator xl = xsens_log.begin();\n\t\t\t\t\t\twhile (it != log.end() && it->compare(str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1)) < 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tit = log.erase(it);\n\t\t\t\t\t\t        xl = xsens_log.erase(xl);//////////////////////////////\u5e76\u67e5\u96c6\u5408\u5254\u9664\n\t\t\t\t\t\t}\n\t\t\t\t\t//   @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//\n\t\t\t\t\t//\trecorder.insert(pair<string,string>(str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1), xx.substr(0,13)));\n\t\t\t\t\t//   recorder.insert(pair<string,string>(str, xx));\n\t\t\t\t\t\trecorder.insert(pair<string,string>(str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1), xx));\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tTTTTT++;\n                     #if 0\n\t\t\t\t\t\trecorder.insert(pair<string,string>(str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1),\"ERROR\"));\n                     #else  \n                        /////////////\n\t\t\t\t\t\t\n\t\t\t\t\t   \t for (int cheap = 0 ; cheap <= 3 && !xsens.eof(); cheap++)\n\t\t\t\t\t\t {\n\t\t\t\t\t\t getline( xsens, xx);\n\n\t\t\t\t\t\t\t if ( xx == \"\")\n\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t cutstring( xx, xsens_signal);\n\t\t\t\t\t\t log.push_back(xx);\n\n\t\t\t\t\t\t xsens_log.push_back(xx);//xsens_log\u7684\u8bb0\u5f55\uff0c\u5e76\u67e5\u96c6\u5408//////////////////////////////////////////////\n\t\t\t\t\t\t }\n\t\t\t\t\t\t\n\t\t\t\t\t\t////////////\n\t\t\t\t\t\tvector<vector<double>> YY(7);\n\t\t\t\t\t\tvector<double> XX;\n\n\t\t\t\t\t\tfor (vector<string>::iterator i = xsens_log.begin(); i != xsens_log.end(); i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t  int pp[10] = {0};\n\t\t\t\t\t\t  ::cutstring(*i , pp);\n\n\t\t\t\t\t\t  XX.push_back(static_cast<double>(::string2int(i->substr(4,10).c_str())));\n\t\t\t\t\t\t\n\t\t\t\t\t\t  YY[0].push_back(string2double(i->substr(pp[0]+1, pp[1] - pp[0] - 1).c_str()));\n\t\t\t\t\t\t  YY[1].push_back(string2double(i->substr(pp[1]+1, pp[2] - pp[1] - 1).c_str()));\n\t\t\t\t\t\t  YY[2].push_back(string2double(i->substr(pp[2]+1, pp[3] - pp[2] - 1).c_str()));\n\t\t\t\t\t\t  YY[3].push_back(string2double(i->substr(pp[3]+1, pp[4] - pp[3] - 1).c_str()));\n\t\t\t\t\t\t  YY[4].push_back(string2double(i->substr(pp[4]+1, pp[5] - pp[4] - 1).c_str()));\n\t\t\t\t\t\t  YY[5].push_back(string2double(i->substr(pp[5]+1, pp[6] - pp[5] - 1).c_str()));\n\t\t\t\t\t\t  YY[6].push_back(string2double(i->substr(pp[6]+1).c_str()));\n\t\t\t\t\t\t}//\u904d\u5386\u83b7\u5f97\u6570\u503c\n\n\t\t\t\t\t\tdouble interplot[7] = {0.0};\n\t\t\t\t\t\tint num_of_element = XX.size();\n\t\t\t\t\t\tfor (int i = 0; i < 7; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t  akima computing(num_of_element);\n\n\t\t\t\t\t\t  computing.input(XX,YY[i]);\n\n\t\t\t\t\t\t  double x = string2double(str.substr(laser_signal[1]+5,laser_signal[2] - laser_signal[1] - 5));\n\t\t\t\t\t\t  interplot[i] = computing.interp(x);\n\t\t\t\t\t\t  if (_isnan(interplot[i]))\n\t\t\t\t\t\t  {\n\t\t\t\t\t\t     interplot[i] = Assum(YY[i]);\n\t\t\t\t\t\t  }\n\t\t\t\t\t\t//  computing.~akima();\n\t\t\t\t\t\t}\n\t\t\t\t\t//\tstd::cout << interplot[0]<<\" \"<< interplot[1]<<\" \"<<interplot[2]<<\" \"<< interplot[3]<<\" \" << interplot[4]<<\" \" << interplot[5]<<\" \"<<interplot[6]<<endl;\n\t\t\t\t\t\tstring result = str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1) +\":\"+ \n\t\t\t\t\t\t\t                                               double2String(interplot[0]) +\":\"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   double2String(interplot[1]) +\":\"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   double2String(interplot[2]) +\":\"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   double2String(interplot[3]) +\":\"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   double2String(interplot[4]) +\":\"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   double2String(interplot[5]) +\":\"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   double2String(interplot[6]) ;\n\t\t\t\t\t  //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//\n\t\t\t\t\t  recorder.insert(pair<string,string>(str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1),result));\n\t\t\t\t      //recorder.insert(pair<string,string>(str,result + \" == x86isnice\"));\n\t\t\t\t\t\t////////@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\t\t\t\t\t //   recorder.insert(pair<string,string>(str.substr(laser_signal[1]+1,laser_signal[2] - laser_signal[1] - 1),result + \" == x86isnice\"));\n\n\t\t\t\t\t\t\t\n                     #endif\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tstr.clear();\n\t\t\t}\n\t\t\telse\n\t\t\t{  \n\t\t\t\tstr.clear();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t }\n\n\t }\n\t else\n\t {\n\t\t std::cerr << \"One of the file is not Open ,please check!\" << endl; \n\t\t exit(EXIT_FAILURE);\n\t }\n\n\t laser.close();\n\t xsens.close();\n\t \n\t for (std::map<string,string>::iterator it = recorder.begin(); it != recorder.end(); it++)\n\t {\n\t    std::cout << it->first << \" <--> \" << it->second << endl;\n\t }\n\t \n\t finish = clock();\n\t cout <<\"recorder.size()::\"<< recorder.size()<<\"   \"<<\"NOT HIT:: \" << TTTTT<<\"  OUT_OF_RANGE:\"<<KKKKK/7<<\"  The Cost Of Time is:\"<<finish - start<<\" ms\" <<endl;\n\t \n     Combine2PCL(recorder, laserfile.c_str());\n\n\t std::cout << \"Complete All\" << std::endl;\n\t return 0;\n}\n\n#else \nint main()\n{\n\tifstream laser;\n\tofstream output(\"D:\\\\test.txt\");\n\tlaser.open(\"D:\\\\1448246245-laser.txt\");\n\n\tif (laser.is_open())\n\t{\n\t\tstring str;\n\t\twhile ( getline(laser,str)  && output.good())\n\t\t{\n\t\t\tif (str.find(\"x86isnice\") != std::string::npos)\n\t\t\t{\n\t\t\t\toutput << str <<endl;\n\n\t\t\t\tgetline(laser,str);\n\n\t\t\t\toutput << str<< endl;\n/*\n\t\t\t\tgetline(laser,str);\t\n\t\t\t\toutput << str << endl;\n\n\t\t\t\tgetline(laser,str);\n\t\t\t\toutput << str << endl;\n*/\n\t\t\t}\n\t\t\telse\n\t\t\t\tcontinue;\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::cerr << \"laser is not open!\" <<endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tlaser.close();\n\toutput.close();\n   return 0;\n}\n#endif", "meta": {"hexsha": "ac4ed0ba1095b49e18ee940f0cd0d56a06cf7eb2", "size": 21227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/matchparameters.cpp", "max_stars_repo_name": "x86isnice/Match-Gen-PCL", "max_stars_repo_head_hexsha": "f014bc2e5d9a7755e5684d623b08cb766163d9f7", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-04T12:38:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-04T12:38:09.000Z", "max_issues_repo_path": "src/matchparameters.cpp", "max_issues_repo_name": "x86isnice/Match-Gen-PCL", "max_issues_repo_head_hexsha": "f014bc2e5d9a7755e5684d623b08cb766163d9f7", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matchparameters.cpp", "max_forks_repo_name": "x86isnice/Match-Gen-PCL", "max_forks_repo_head_hexsha": "f014bc2e5d9a7755e5684d623b08cb766163d9f7", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6753585398, "max_line_length": 162, "alphanum_fraction": 0.5297027371, "num_tokens": 8152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6341966257678073}}
{"text": "#include <Eigen/CholmodSupport>\n#include <fstream>\n#include <iomanip>\n#include \"../../include/Optimization/LineSearch.h\"\n#include \"../../include/Optimization/AugmentedLagrangian.h\"\n#include \"../../include/timer.h\"\n#include <iostream>\n\nvoid OptSolver::augmentedLagrangianSolver(\n\tstd::function<double(const Eigen::VectorXd&, Eigen::VectorXd*, Eigen::SparseMatrix<double>*, bool)> objFunc,\n\tstd::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&)> findMaxStep,\n\tstd::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&, Eigen::VectorXd*, Eigen::SparseMatrix<double>*, bool, Eigen::VectorXd*)> constraintsFunc,\n\tstd::function<double(const Eigen::VectorXd&, const double&, Eigen::VectorXd*, Eigen::SparseMatrix<double>*, bool)> penaltyFunc,\n\tEigen::VectorXd& x0, Eigen::VectorXd& lambda, double& mu,\n\tint numIter, double gradTol, double xTol, double cTol, bool displayInfo, std::function<void(const Eigen::VectorXd&, double&, double&)> getNormFunc, std::string* savingFolder, std::function<void(Eigen::VectorXd&)> postProcess)\n{\n\tconst int DIM = x0.rows();\n\tEigen::VectorXd randomVec = x0;\n\trandomVec.setRandom();\n\tx0 += 1e-6 * randomVec;\n\tEigen::VectorXd grad = Eigen::VectorXd::Zero(DIM);\n\tEigen::SparseMatrix<double> hessian;\n\n\tEigen::VectorXd neggrad, delta_x;\n\tdouble maxStepSize = 1.0;\n\tdouble reg = 1e-8;\n\n\tbool isProj = true;\n\tTimer<std::chrono::high_resolution_clock> totalTimer;\n\tdouble totalAssemblingTime = 0;\n\tdouble totalSolvingTime = 0;\n\tdouble totalLineSearchTime = 0;\n\n\ttotalTimer.start();\n\tstd::ofstream optInfo;\n\n\tEigen::VectorXd constVec;\n\tdouble init = constraintsFunc(x0, lambda, NULL, NULL, false, &constVec);\n\tstd::cout << \"constraint violation: \" << constVec.minCoeff() << \", \" << constVec.maxCoeff() << std::endl;\n\n\tint i = 0;\n\tfor (; i < numIter; i++)\n\t{\n\t\tif (displayInfo)\n\t\t\tstd::cout << \"\\niter: \" << i << std::endl;\n\n\t\tauto lagrangian = [&](const Eigen::VectorXd& x, Eigen::VectorXd* grad, Eigen::SparseMatrix<double>* hess, bool isProj) {\n\t\t\tEigen::VectorXd deriv, derivc, derivp;\n\t\t\tEigen::SparseMatrix<double> H, Hc, Hp;\n\t\t\tdouble E = objFunc(x, grad ? &deriv : NULL, hess ? &H : NULL, isProj);\n\t\t\tdouble Ec = constraintsFunc(x, lambda, grad ? &derivc : NULL, hess ? &Hc : NULL, isProj, NULL);\n\t\t\tdouble Ep = penaltyFunc(x, mu, grad ? &derivp : NULL, hess ? &Hp : NULL, isProj);\n\n\t\t\tif (grad)\n\t\t\t{\n\t\t\t\t(*grad) = deriv + derivc + derivp;\n\t\t\t}\n\n\t\t\tif (hess)\n\t\t\t{\n\t\t\t\t(*hess) = H + Hc + Hp;\n\t\t\t}\n\n\t\t\treturn E + Ec + Ep;\n\t\t};\n\n\t\tTimer<std::chrono::high_resolution_clock> localTimer;\n\t\tlocalTimer.start();\n\t\tdouble f = lagrangian(x0, &grad, &hessian, isProj);\n\t\tlocalTimer.stop();\n\t\tdouble localAssTime = localTimer.elapsed<std::chrono::milliseconds>() * 1e-3;\n\t\ttotalAssemblingTime += localAssTime;\n\n\t\tlocalTimer.start();\n\t\tEigen::SparseMatrix<double> H = hessian;\n\t\tEigen::SparseMatrix<double> I(DIM, DIM);\n\t\tI.setIdentity();\n\t\tstd::cout << \"num of nonzeros: \" << H.nonZeros() << \", rows: \" << H.rows() << \", cols: \" << H.cols() << std::endl;\n\t\tEigen::CholmodSupernodalLLT<Eigen::SparseMatrix<double>> solver(H);\n\n\t\t//\t\tEigen::SimplicialLLT<Eigen::SparseMatrix<double> > solver(hessian);\n\n\n\t\twhile (solver.info() != Eigen::Success)\n\t\t{\n\t\t\tif (displayInfo)\n\t\t\t{\n\t\t\t\tif (isProj)\n\t\t\t\t\tstd::cout << \"some small perturb is needed to remove round-off error, current reg = \" << reg << std::endl;\n\t\t\t\telse\n\t\t\t\t\tstd::cout << \"Matrix is not positive definite, current reg = \" << reg << std::endl;\n\t\t\t}\n\n\t\t\tH = hessian + reg * I;\n\t\t\tsolver.compute(H);\n\t\t\treg = std::max(2 * reg, 1e-16);\n\t\t}\n\n\t\tneggrad = -grad;\n\t\tdelta_x = solver.solve(neggrad);\n\n\t\tlocalTimer.stop();\n\t\tdouble localSolvingTime = localTimer.elapsed<std::chrono::milliseconds>() * 1e-3;\n\t\ttotalSolvingTime += localSolvingTime;\n\n\n\t\tmaxStepSize = findMaxStep(x0, delta_x);\n\n\t\tlocalTimer.start();\n\t\tdouble rate = LineSearch::backtrackingArmijo(x0, grad, delta_x, lagrangian, maxStepSize);\n\t\tlocalTimer.stop();\n\t\tdouble localLinesearchTime = localTimer.elapsed<std::chrono::milliseconds>() * 1e-3;\n\t\ttotalLineSearchTime += localLinesearchTime;\n\n\n\t\tif (!isProj)\n\t\t{\n\t\t\treg *= 0.5;\n\t\t\treg = std::max(reg, 1e-16);\n\t\t}\n\n\t\tx0 = x0 + rate * delta_x;\n\n\t\tdouble fnew = lagrangian(x0, &grad, NULL, isProj);\n\n\t\t//Eigen::VectorXd constVec;\n\t\tdouble tmpE = constraintsFunc(x0, lambda, NULL, NULL, false, &constVec);\n\t\tbool iskeepsame = true;\n\n\t\tif (rate * delta_x.lpNorm<Eigen::Infinity>() < std::max(1.0, xTol))\n\t\t{\n\t\t\tif (std::max(std::abs(constVec.minCoeff()), std::abs(constVec.maxCoeff())) > 10 * cTol && mu < 1e4)\n\t\t\t{\n\t\t\t\tiskeepsame = false;\n\t\t\t\tmu *= 2;\n\t\t\t}\n\t\t\tif (iskeepsame)\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < constVec.rows(); j++)\n\t\t\t\t{\n\t\t\t\t\tlambda(j) += mu * constVec(j);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tdouble fnewAfterUpdate = lagrangian(x0, NULL, NULL, isProj);\t// after update lambda and mu\n\t\tdouble Ec = constraintsFunc(x0, lambda, NULL, NULL, isProj, NULL);\n\t\tdouble Ep = penaltyFunc(x0, mu, NULL, NULL, isProj);\n\t\tif (displayInfo)\n\t\t{\n\t\t\tstd::cout << \"line search rate : \" << rate << \", actual hessian : \" << !isProj << \", reg = \" << reg << std::endl;\n\t\t\tstd::cout << \"f_old: \" << f << \", after update x, f_new: \" << fnew << \", after update lambda and mu, f_new: \" << fnewAfterUpdate << \", grad norm: \" << grad.norm() << \", delta x: \" << rate * delta_x.norm() << \", delta_f: \" << f - fnew << std::endl;\n\t\t\tstd::cout << \"constraint violation: \" << constVec.minCoeff() << \", \" << constVec.maxCoeff() << std::endl;\n\t\t\tstd::cout << \"lambda: \" << lambda.minCoeff() << \", \" << lambda.maxCoeff() << \", mu: \" << mu << std::endl;\n\t\t\tstd::cout << \"E const: \" << Ec << \", E penalty: \" << Ep << std::endl;\n\t\t\tif (getNormFunc)\n\t\t\t{\n\t\t\t\tdouble gradz, gradw;\n\t\t\t\tgetNormFunc(grad, gradz, gradw);\n\n\t\t\t\tdouble updatez, updatew;\n\t\t\t\tgetNormFunc(rate * delta_x, updatez, updatew);\n\t\t\t\tstd::cout << \"z grad: \" << gradz << \", w grad: \" << gradw << \", z change: \" << updatez << \", w change: \" << updatew << std::endl;\n\t\t\t}\n\t\t\tstd::cout << \"timing info (in total seconds): \" << std::endl;\n\t\t\tstd::cout << \"assembling took: \" << totalAssemblingTime << \", LLT solver took: \" << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n\t\t}\n\n\t\tif (savingFolder)\n\t\t{\n\t\t\toptInfo << \"line search rate : \" << rate << \", actual hessian : \" << !isProj << \", reg = \" << reg << std::endl;\n\t\t\toptInfo << \"f_old: \" << f << \", f_new: \" << fnew << \", grad norm: \" << grad.norm() << \", delta x: \" << rate * delta_x.norm() << \", delta_f: \" << f - fnew << std::endl;\n\t\t\tif (getNormFunc)\n\t\t\t{\n\t\t\t\tdouble gradz, gradw;\n\t\t\t\tgetNormFunc(grad, gradz, gradw);\n\n\t\t\t\tdouble updatez, updatew;\n\t\t\t\tgetNormFunc(rate * delta_x, updatez, updatew);\n\t\t\t\toptInfo << \"z grad: \" << gradz << \", w grad: \" << gradw << \", z change: \" << updatez << \", w change: \" << updatew << std::endl;\n\t\t\t}\n\t\t\toptInfo << \"timing info (in total seconds): \" << std::endl;\n\t\t\toptInfo << \"assembling took: \" << totalAssemblingTime << \", LLT solver took: \" << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n\n\t\t\tif (i % 100 == 0)\n\t\t\t{\n\t\t\t\tstd::string fileName = (*savingFolder) + \"intermediate.txt\";\n\t\t\t\tstd::ofstream ofs(fileName);\n\t\t\t\tif (ofs)\n\t\t\t\t{\n\t\t\t\t\tofs << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << x0 << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (iskeepsame)\n\t\t{\n\t\t\tif (std::abs(f - fnew) / f < 1e-5 || rate * delta_x.norm() < 1e-5 || grad.norm() < 1e-4)\n\t\t\t{\n\t\t\t\tisProj = false;\n\t\t\t}\n\t\t\tif (reg > 1e3)\n\t\t\t\tisProj = true;\n\t\t}\n\n\n\t\tif (rate < 1e-8)\n\t\t{\n\t\t\tstd::cout << \"terminate with small line search rate (<1e-8): L2-norm = \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (grad.norm() < gradTol && std::max(std::abs(constVec.minCoeff()), std::abs(constVec.maxCoeff())) < cTol)\n\t\t{\n\t\t\tstd::cout << \"terminate with gradient L2-norm = \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (rate * delta_x.norm() < xTol)\n\t\t{\n\t\t\tstd::cout << \"terminate with small variable change, gradient L2-norm = \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (i >= numIter)\n\t\tstd::cout << \"terminate with reaching the maximum iteration, with gradient L2-norm = \" << grad.norm() << std::endl;\n\n\ttotalTimer.stop();\n\tif (displayInfo)\n\t{\n\t\tstd::cout << \"total time costed (s): \" << totalTimer.elapsed<std::chrono::milliseconds>() * 1e-3 << \", within that, assembling took: \" << totalAssemblingTime << \", LLT solver took: \" << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n\t}\n\n\tif (savingFolder)\n\t{\n\t\toptInfo << \"total time costed (s): \" << totalTimer.elapsed<std::chrono::milliseconds>() * 1e-3 << \", within that, assembling took: \" << totalAssemblingTime << \", LLT solver took: \" << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n\n\t\tstd::string fileName = (*savingFolder) + \"final_res.txt\";\n\t\tstd::ofstream ofs(fileName);\n\t\tif (ofs)\n\t\t{\n\t\t\tofs << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << x0 << std::endl;\n\t\t}\n\n\n\t}\n\n}\n\n\n", "meta": {"hexsha": "c28a014b3d7e11e7bc049e557170ddc46401de25", "size": 8887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Optimization/AugmentedLagrangian.cpp", "max_stars_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_stars_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Optimization/AugmentedLagrangian.cpp", "max_issues_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_issues_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Optimization/AugmentedLagrangian.cpp", "max_forks_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_forks_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.406374502, "max_line_length": 267, "alphanum_fraction": 0.6229323731, "num_tokens": 2741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6341077220004318}}
{"text": "/**\n * \\file ButterworthFilter.hxx\n */\n\n#include \"ButterworthFilter.h\"\n#include <ATK/EQ/helpers.h>\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/polynomial.hpp>\n\nnamespace ButterworthUtilities\n{\n  template<typename DataType>\n  void create_butterworth_analog_coefficients(int order, EQUtilities::ZPK<DataType>& zpk)\n  {\n    zpk.k = 1;\n    zpk.z.clear(); // no zeros for this filter type\n    zpk.p.clear();\n    for(gsl::index i = -order+1; i < order; i += 2)\n    {\n      zpk.p.push_back(std::complex<DataType>(-std::cos(boost::math::constants::pi<DataType>() * i / (2 * order)), -std::sin(boost::math::constants::pi<DataType>() * i / (2 * order))));\n    }\n  }\n  \n  template<typename DataType, typename Container>\n  void create_default_coeffs(size_t order, DataType Wn, Container& coefficients_in, Container& coefficients_out)\n  {\n    EQUtilities::ZPK<DataType> zpk;\n\n    int fs = 2;\n    create_butterworth_analog_coefficients(static_cast<int>(order), zpk);\n    EQUtilities::populate_lp_coeffs(Wn, fs, order, zpk, coefficients_in, coefficients_out);\n  }\n\n  template<typename DataType, typename Container>\n  void create_bp_coeffs(size_t order, DataType wc1, DataType wc2, Container& coefficients_in, Container& coefficients_out)\n  {\n    EQUtilities::ZPK<DataType> zpk;\n\n    int fs = 2;\n    create_butterworth_analog_coefficients(static_cast<int>(order/2), zpk);\n    EQUtilities::populate_bp_coeffs(wc1, wc2, fs, order, zpk, coefficients_in, coefficients_out);\n  }\n  \n  template<typename DataType, typename Container>\n  void create_bs_coeffs(size_t order, DataType wc1, DataType wc2, Container& coefficients_in, Container& coefficients_out)\n  {\n    EQUtilities::ZPK<DataType> zpk;\n\n    int fs = 2;\n    create_butterworth_analog_coefficients(static_cast<int>(order/2), zpk);\n    EQUtilities::populate_bs_coeffs(wc1, wc2, fs, order, zpk, coefficients_in, coefficients_out);\n  }\n}\n\nnamespace ATK\n{\n  template <typename DataType>\n  ButterworthLowPassCoefficients<DataType>::ButterworthLowPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n  \n  template <typename DataType_>\n  void ButterworthLowPassCoefficients<DataType_>::set_cut_frequency(CoeffDataType cut_frequency)\n  {\n    if(cut_frequency <= 0)\n    {\n      throw std::out_of_range(\"Frequency can't be negative\");\n    }\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n\n  template <typename DataType_>\n  typename ButterworthLowPassCoefficients<DataType_>::CoeffDataType ButterworthLowPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n\n  template <typename DataType>\n  void ButterworthLowPassCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  unsigned int ButterworthLowPassCoefficients<DataType>::get_order() const\n  {\n    return in_order;\n  }\n\n  template <typename DataType>\n  void ButterworthLowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    ButterworthUtilities::create_default_coeffs(in_order, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n\n  template <typename DataType>\n  ButterworthHighPassCoefficients<DataType>::ButterworthHighPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n  \n  template <typename DataType_>\n  void ButterworthHighPassCoefficients<DataType_>::set_cut_frequency(CoeffDataType cut_frequency)\n  {\n    if(cut_frequency <= 0)\n    {\n      throw std::out_of_range(\"Frequency can't be negative\");\n    }\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n  \n  template <typename DataType_>\n  typename ButterworthHighPassCoefficients<DataType_>::CoeffDataType ButterworthHighPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n  \n  template <typename DataType>\n  void ButterworthHighPassCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  unsigned int ButterworthHighPassCoefficients<DataType>::get_order() const\n  {\n    return in_order;\n  }\n\n  template <typename DataType>\n  void ButterworthHighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    ButterworthUtilities::create_default_coeffs(in_order, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);\n    for(gsl::index i = in_order - 1; i >= 0; i -= 2)\n    {\n      coefficients_in[i] = - coefficients_in[i];\n      coefficients_out[i] = - coefficients_out[i];\n    }\n  }\n\n  template <typename DataType>\n  ButterworthBandPassCoefficients<DataType>::ButterworthBandPassCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n\n  template <typename DataType_>\n  void ButterworthBandPassCoefficients<DataType_>::set_cut_frequencies(std::pair<CoeffDataType, CoeffDataType> cut_frequencies)\n  {\n    if(cut_frequencies.first <= 0 || cut_frequencies.second <= 0)\n    {\n      throw std::out_of_range(\"Frequencies can't be negative\");\n    }\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n\n  template <typename DataType_>\n  void ButterworthBandPassCoefficients<DataType_>::set_cut_frequencies(CoeffDataType f0, CoeffDataType f1)\n  {\n    set_cut_frequencies(std::make_pair(f0, f1));\n  }\n\n  template <typename DataType_>\n  std::pair<typename ButterworthBandPassCoefficients<DataType_>::CoeffDataType, typename ButterworthBandPassCoefficients<DataType_>::CoeffDataType> ButterworthBandPassCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n\n  template <typename DataType>\n  void ButterworthBandPassCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = 2 * order;\n    setup();\n  }\n\n  template <typename DataType>\n  unsigned int ButterworthBandPassCoefficients<DataType>::get_order() const\n  {\n    return in_order / 2;\n  }\n\n  template <typename DataType>\n  void ButterworthBandPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    ButterworthUtilities::create_bp_coeffs(in_order, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n\n  template <typename DataType>\n  ButterworthBandStopCoefficients<DataType>::ButterworthBandStopCoefficients(gsl::index nb_channels)\n  :Parent(nb_channels, nb_channels)\n  {\n  }\n  \n  template <typename DataType_>\n  void ButterworthBandStopCoefficients<DataType_>::set_cut_frequencies(std::pair<CoeffDataType, CoeffDataType> cut_frequencies)\n  {\n    if(cut_frequencies.first <= 0 || cut_frequencies.second <= 0)\n    {\n      throw std::out_of_range(\"Frequencies can't be negative\");\n    }\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n  \n  template <typename DataType_>\n  void ButterworthBandStopCoefficients<DataType_>::set_cut_frequencies(CoeffDataType f0, CoeffDataType f1)\n  {\n    set_cut_frequencies(std::make_pair(f0, f1));\n  }\n  \n  template <typename DataType_>\n  std::pair<typename ButterworthBandStopCoefficients<DataType_>::CoeffDataType, typename ButterworthBandStopCoefficients<DataType_>::CoeffDataType> ButterworthBandStopCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n  \n  template <typename DataType>\n  void ButterworthBandStopCoefficients<DataType>::set_order(unsigned int order)\n  {\n    if(order == 0)\n    {\n      throw std::out_of_range(\"Order can't be null\");\n    }\n    in_order = out_order = 2 * order;\n    setup();\n  }\n  \n  template <typename DataType>\n  unsigned int ButterworthBandStopCoefficients<DataType>::get_order() const\n  {\n    return in_order / 2;\n  }\n\n  template <typename DataType>\n  void ButterworthBandStopCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    ButterworthUtilities::create_bs_coeffs(in_order, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n}\n", "meta": {"hexsha": "fc8826fdc1ddf5d6fbc620e205daf799be99e23f", "size": 8598, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/EQ/ButterworthFilter.hxx", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "ATK/EQ/ButterworthFilter.hxx", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "ATK/EQ/ButterworthFilter.hxx", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 31.2654545455, "max_line_length": 219, "alphanum_fraction": 0.7321470109, "num_tokens": 2143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6340962067243194}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <map>\n#include <set>\n#include <tuple>\n#include <stdbool.h>\n#include <bitset>\n#include <string>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace mp = boost::multiprecision;\nusing namespace std;\n\n\nint main(void) {\n    int n,k;\n    cin >> n;\n    cin >> k;\n    k -= 1;\n\n    vector<mp::cpp_int> trees(n);\n    for(int i = 0 ; i < n ; ++i) {\n        cin >> trees[i];\n    }\n    sort(trees.begin(), trees.end());\n    // \u8ddd\u96e2\u306e\u5dee\u5206\u3067\u4f5c\u308a\u76f4\u3059\n    // \u30bd\u30fc\u30c8\u3057\u3066\u30a2\u30ec\u3070k\u672c\u5206\u96e2\u308c\u305f\u4f4d\u7f6e\u304chmax-hmin\u305d\u306e\u3082\u306e\u306b\u306a\u308a\u305d\u3046\n    mp::cpp_int min = 9999999999999999;\n    for(int i = 0 ; i < n - k ; ++i) {\n        auto d = abs(trees[i] - trees[i + k]);\n        if (d < min) {\n            min = d;\n        }\n    }\n    cout << min << endl;\n    return 0;\n}", "meta": {"hexsha": "dfaad918c57a143ca707b7173dd86fd5317f4a66", "size": 782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc115/c/main.cpp", "max_stars_repo_name": "kamiyaowl/atcoder", "max_stars_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc115/c/main.cpp", "max_issues_repo_name": "kamiyaowl/atcoder", "max_issues_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-20T11:51:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-20T11:51:59.000Z", "max_forks_repo_path": "abc115/c/main.cpp", "max_forks_repo_name": "kamiyaowl/atcoder", "max_forks_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0512820513, "max_line_length": 46, "alphanum_fraction": 0.5549872123, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6340961917017737}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <map>\n#include <algorithm>\n#include <Eigen/Dense>\n#include \"../matplotlibcpp.h\"\n\nusing namespace Eigen;\nnamespace plt = matplotlibcpp;\n\nMatrixXd sigmoid(MatrixXd&);\n// MatrixXd ReLU(MatrixXd&);\n// MatrixXd tanh(MatrixXd&);\n\nint main()\n{\n    using std::cout;\n    using std::endl;\n    using std::map;\n    using std::vector;\n    using std::string;\n\n    int node_num = 100;\n    MatrixXd input_data = MatrixXd::Random(1000, node_num);\n    int hidden_layer_size = 5;\n    map<int, MatrixXd> activations;\n\n    MatrixXd x = input_data;\n    MatrixXd w, a, z;\n\n    for (int i = 0; i < hidden_layer_size; i++)\n    {\n        if (i != 0)\n        {\n            x = activations[i-1];\n        }\n\n        w = MatrixXd::Random(node_num, node_num) * 0.1; // \u3053\u3053\u306e\u91cd\u307f\u3092\u5909\u66f4\u3059\u308b\n        a = x * w;\n        z = sigmoid(a);\n\n        activations[i] = z;\n    }\n\n    // vector\u306bEigen\u3092\u8a70\u3081\u306a\u304a\u3057\u3066\u3001\u30d7\u30ed\u30c3\u30c8\u3092\u4f5c\u6210\u3059\u308b\u3053\u3068\n    // for (auto activation : activations)\n    // {\n    //     cout << activation.first << \":\" << endl;\n    //     cout << activation.second << endl;\n    // }\n\n    vector<double> a_vec(1000*node_num);\n    Map<MatrixXd>(&a_vec[0], 1000, node_num) = activations[0];\n\n    int bins = 30;\n    string title = \"Layer1\";\n\n    plt::hist(a_vec, bins);\n    plt::xlim(0, 1);\n    plt::title(title);\n    plt::save(\"activation_hist_xavier0.png\");\n\n    // vector<double> tmp_a(node_num*node_num);\n    for (auto activation : activations)\n    {\n        if (activation.first != 0)\n        {\n            string save_filename = \"activation_hist_xavier\";\n            save_filename += std::to_string(activation.first);\n            save_filename += \".png\";\n\n            Map<MatrixXd>(&a_vec[0], 1000, node_num) = activation.second;\n\n            title = \"Layer\";\n            title += std::to_string(activation.first + 1);\n            plt::hist(a_vec, bins);\n            plt::xlim(0, 1);\n            plt::title(title);\n            plt::save(save_filename);\n        }\n    }\n\n    return 0;\n}\n\nMatrixXd sigmoid(MatrixXd& X)\n{\n    return X.unaryExpr([](double p){return 1 / (1 + exp(p));});\n}\n\n// MatrixXd ReLU(MatrixXd& X)\n// {\n//     return X.unaryExpr([](double p){return std::max(0, p);});\n// }\n\n// MatrixXd tanh(MatrixXd& X)\n// {\n//     return X.unaryExpr([](double p){return tanh(p);});\n// }", "meta": {"hexsha": "ed3aa5532f64529bf78b11820d046d6f3927bbc3", "size": 2299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/weight_init_activation_histogram.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch6/weight_init_activation_histogram.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch6/weight_init_activation_histogram.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.99, "max_line_length": 73, "alphanum_fraction": 0.5663331883, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6340773826983525}}
{"text": "/**\n * @file advectionfv2d.cc\n * @brief NPDE homework AdvectionFV2D code\n * @author Philipp Egg\n * @date 21.06.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"advectionfv2d.h\"\n\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <algorithm>\n#include <array>\n#include <memory>\n#include <stdexcept>\n#include <vector>\n\nnamespace AdvectionFV2D {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix<double, 2, 3> gradbarycoordinates(\n    const Eigen::Matrix<double, 2, 3> &triangle) {\n  Eigen::Matrix3d X;\n\n  // solve for the coefficients of the barycentric coordinate functions\n  X.block<3, 1>(0, 0) = Eigen::Vector3d::Ones();\n  X.block<3, 2>(0, 1) = triangle.transpose();\n  return X.inverse().block<2, 3>(1, 0);\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nstd::shared_ptr<\n    lf::mesh::utils::CodimMeshDataSet<Eigen::Matrix<double, 2, Eigen::Dynamic>>>\ncomputeCellNormals(std::shared_ptr<const lf::mesh::Mesh> mesh_p) {\n  //====================\n  // Your code goes here\n  //====================\n  return nullptr;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nstd::shared_ptr<\n    lf::mesh::utils::CodimMeshDataSet<std::array<const lf::mesh::Entity *, 4>>>\ngetAdjacentCellPointers(std::shared_ptr<const lf::mesh::Mesh> mesh_p) {\n  //====================\n  // Your code goes here\n  //====================\n  return nullptr;\n}\n/* SAM_LISTING_END_3 */\n\n// Function returning the barycenter of TRIA or QUAD\n/* SAM_LISTING_BEGIN_4 */\nEigen::Vector2d barycenter(const Eigen::MatrixXd corners) {\n  Eigen::Vector2d midpoint;\n  if (corners.cols() == 3) {\n    midpoint = (corners.col(0) + corners.col(1) + corners.col(2)) / 3.0;\n  } else if (corners.cols() == 4) {\n    midpoint =\n        (corners.col(0) + corners.col(1) + corners.col(2) + corners.col(3)) /\n        4.0;\n  } else {\n    throw std::runtime_error(\"Wrong geometrie in barycenter()\");\n  }\n  return midpoint;\n}\n/* SAM_LISTING_END_4 */\n\n/* SAM_LISTING_BEGIN_5 */\ndouble computeHmin(std::shared_ptr<const lf::mesh::Mesh> mesh_p) {\n  //====================\n  // Your code goes here\n  // Replace the dummy return value below:\n  return 0.0;\n  //====================\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace AdvectionFV2D\n", "meta": {"hexsha": "abb9aef4a9656774ac76eace4ef23cb558b72606", "size": 2273, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/AdvectionFV2D/templates/advectionfv2d.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T10:59:19.000Z", "max_issues_repo_path": "homeworks/AdvectionFV2D/templates/advectionfv2d.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/AdvectionFV2D/templates/advectionfv2d.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1264367816, "max_line_length": 80, "alphanum_fraction": 0.6405631324, "num_tokens": 675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.6340773825208535}}
{"text": "#include \"nearest_neighbor_brute_force.h\"\n#include \"point_AABBTree_squared_distance.h\"\n#include \"CloudPoint.h\"\n#include \"Object.h\"\n#include \"AABBTree.h\"\n#include \"warnings.h\"\n#include \"VectorXb.h\"\n#include \"tictoc.h\"\n#include \"visualize_aabbtree.h\"\n#include <igl/read_triangle_mesh.h>\n#include <Eigen/Core>\n#include <iostream>\n#include <string> // std::stoi\n#include <iomanip> // std::setw\n#include <memory> // std::shared_ptr\n\nint main(int argc, char * argv[])\n{\n  /////////////////////////////////////////////////////////////////////////////\n  // POINT CLOUD DISTANCE QUERY\n  /////////////////////////////////////////////////////////////////////////////\n  std::cout<<\"# Point Cloud Distance Queries\"<<std::endl;\n  // Prepare a random list of points in our set and random queries\n  Eigen::MatrixXd points =  \n    Eigen::MatrixXd::Random(argc>1?std::stoi(argv[1]):100000,3);\n  Eigen::MatrixXd queries = \n    Eigen::MatrixXd::Random(argc>2?std::stoi(argv[2]):10000,3);\n\n  std::cout<<\"    |points|: \"<< points.rows()<<std::endl;\n  std::cout<<\"  |querires|: \"<<queries.rows()<<std::endl<<std::endl;\n  // Brute Force\n  tic(); // Start the clock!\n  Eigen::VectorXd bf_sqrD(queries.rows());\n  Eigen::VectorXi bf_I   (queries.rows());\n  // Loop over queries\n  for(int i = 0;i < queries.rows(); i++)\n  {\n    nearest_neighbor_brute_force(points,queries.row(i),bf_I(i),bf_sqrD(i));\n  }\n  std::cout<<\"  | Method      | Time in seconds |\"<<std::endl;\n  std::cout<<\"  |:------------|----------------:|\"<<std::endl;\n  std::cout<<\"  | brute force | \" << FLOAT15 << toc() << \" |\"<<std::endl;\n\n  tic();\n  // Build a tree\n  std::vector<std::shared_ptr<Object> > point_indices;\n  // Put a reference to each point in a boxable object\n  point_indices.reserve(points.rows());\n  for(int i = 0;i<points.rows();i++)\n  {\n    point_indices.emplace_back(std::make_shared<CloudPoint>(points,i));\n  }\n  // Build tree\n  std::shared_ptr<AABBTree> root = std::make_shared<AABBTree>(point_indices);\n  std::cout<<\"  | build tree  | \" << FLOAT15 << toc() << \" |\"<<std::endl;\n\n  tic();\n  Eigen::VectorXd tree_sqrD(queries.rows());\n  Eigen::VectorXi tree_I   (queries.rows());\n  // Loop over queries\n  for(int i = 0;i < queries.rows(); i++)\n  {\n    Eigen::RowVector3d query = queries.row(i);\n    std::shared_ptr<Object> closest_object;\n    const double inf = std::numeric_limits<double>::infinity();\n    point_AABBTree_squared_distance(\n      query,root,0,inf,tree_sqrD(i),closest_object);\n    if(closest_object)\n    {\n      tree_I(i) = std::static_pointer_cast<CloudPoint>(closest_object)->i;\n    }else\n    {\n      tree_I(i) = -1;\n    }\n  }\n  std::cout<<\"  | use tree    | \" << FLOAT15 << toc() << \" |\"<<std::endl;\n \n  // Check that solutions match.\n  for(int i = 0;i < queries.rows(); i++)\n  {\n    WARN_IF_NOT_EQUAL(bf_I,tree_I,i);\n    WARN_IF_NOT_APPROX(bf_sqrD,tree_sqrD,i);\n  }\n  visualize_aabbtree(points,root);\n  \n}\n", "meta": {"hexsha": "743169d9caa55bbf054df64b28a3ae06c39aaf4f", "size": 2885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "distances.cpp", "max_stars_repo_name": "ericpko/computer-graphics-bounding-volume-hierarchy", "max_stars_repo_head_hexsha": "9f4781ab2308ebf57d4ac89e1d37e51c311a17f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distances.cpp", "max_issues_repo_name": "ericpko/computer-graphics-bounding-volume-hierarchy", "max_issues_repo_head_hexsha": "9f4781ab2308ebf57d4ac89e1d37e51c311a17f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distances.cpp", "max_forks_repo_name": "ericpko/computer-graphics-bounding-volume-hierarchy", "max_forks_repo_head_hexsha": "9f4781ab2308ebf57d4ac89e1d37e51c311a17f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1609195402, "max_line_length": 79, "alphanum_fraction": 0.6031195841, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6340773671592037}}
{"text": "// Copyright 2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_custom_accumulators\n\n#include <array>\n#include <boost/format.hpp>\n#include <boost/histogram.hpp>\n#include <boost/histogram/accumulators/mean.hpp>\n#include <iostream>\n\nint main() {\n  using namespace boost::histogram;\n  const auto axis = axis::regular<>(3, 0.0, 1.0);\n\n  // Create a 1D-profile, which computes the mean of samples in each bin. The\n  // factory function `make_profile` is provided by the library as a shorthand.\n  auto h1 = make_histogram_with(dense_storage<accumulators::mean<>>(), axis);\n\n  // Argument of `sample` is passed to accumulator.\n  h1(0.0, sample(2)); // sample 2 goes to first bin\n  h1(0.1, sample(2)); // sample 2 goes to first bin\n  h1(0.4, sample(3)); // sample 3 goes to second bin\n  h1(0.5, sample(4)); // sample 4 goes to second bin\n\n  std::ostringstream os1;\n  for (auto x : indexed(h1)) {\n    // Accumulators usually have methods to access their state. Use the arrow\n    // operator to access them. Here, `count()` gives the number of samples,\n    // `value()` the mean, and `variance()` the variance estimate of the mean.\n    os1 << boost::format(\"%i count %i mean %.1f variance %.1f\\n\") % x.index() %\n               x->count() % x->value() % x->variance();\n  }\n  std::cout << os1.str() << std::flush;\n  assert(os1.str() == \"0 count 2 mean 2.0 variance 0.0\\n\"\n                      \"1 count 2 mean 3.5 variance 0.5\\n\"\n                      \"2 count 0 mean 0.0 variance 0.0\\n\");\n\n  // Let's make a custom accumulator, which tracks the maximum of the samples. It must\n  // have a call operator that accepts the argument of the `sample` function. The return\n  // value of the call operator is ignored.\n  struct max {\n    void operator()(double x) {\n      if (x > value) value = x;\n    }\n    double value = 0;\n  };\n\n  // Create a histogram with the custom accumulator, initialize the accumulators\n  // to 1.\n  auto h2 = make_histogram_with(dense_storage<max>(), axis);\n  h2(0.0, sample(2));   // sample 2 goes to first bin\n  h2(0.1, sample(2.5)); // sample 2.5 goes to first bin\n  h2(0.4, sample(3));   // sample 3 goes to second bin\n  h2(0.5, sample(4));   // sample 4 goes to second bin\n\n  std::ostringstream os2;\n  for (auto x : indexed(h2)) {\n    os2 << boost::format(\"%i value %.1f\\n\") % x.index() % x->value;\n  }\n  std::cout << os2.str() << std::flush;\n  assert(os2.str() == \"0 value 2.5\\n\"\n                      \"1 value 4.0\\n\"\n                      \"2 value 0.0\\n\");\n}\n\n//]\n", "meta": {"hexsha": "a11dc1c38e099a5ef10fc8fec10747cd3653ee80", "size": 2617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/guide_custom_accumulators.cpp", "max_stars_repo_name": "henryiii/histogram", "max_stars_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2020-12-21T05:14:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T11:27:32.000Z", "max_issues_repo_path": "examples/guide_custom_accumulators.cpp", "max_issues_repo_name": "henryiii/histogram", "max_issues_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T13:40:06.000Z", "max_forks_repo_path": "examples/guide_custom_accumulators.cpp", "max_forks_repo_name": "henryiii/histogram", "max_forks_repo_head_hexsha": "d9f000cb86a4b4ac5ebfcb395616fa9aaa28e06c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2020-12-22T09:40:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T18:16:00.000Z", "avg_line_length": 36.8591549296, "max_line_length": 88, "alphanum_fraction": 0.6301108139, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6340307409190693}}
{"text": "// Copyright (c) 2015\n// Author: Chrono Law\n#include <std.hpp>\n//using namespace std;\n\n#include <boost/random.hpp>\nusing namespace boost;\n\n//////////////////////////////////////////\n\nvoid case1()\n{\n    mt19937 rng(time(0));\n\n    std::cout << mt19937::min() << \"<->\"\n        << mt19937::max() << std::endl;\n\n    for (int i = 0;i < 100;++i)\n    {\n        std::cout << rng() << \",\";\n    }\n\n    rng.discard(5);\n    std::vector<int> vec(10);\n    rng.generate(vec.begin(), vec.end());\n\n}\n\n//////////////////////////////////////////\n\nvoid case2()\n{\n    mt19937 rng(time(0));\n    std::cout <<  rng() << std::endl;\n\n    mt19937 rng2(rng);\n\n    for (int i = 0;i < 10;++i)\n    {   assert(rng() == rng2());    }\n}\n\n//////////////////////////////////////////\n\nvoid case3()\n{\n    //using namespace boost::random;\n    mt19937 rng(time(0));\n\n    random::uniform_int_distribution<> ui(0, 255);\n    for (int i = 0;i < 10;++i)\n    {   std::cout << ui(rng) << \",\"; }\n    assert(ui.a() == 0 && ui.b() == 255);\n    std::cout << std::endl;\n\n    uniform_01<> u01;\n    for (int i = 0;i < 10;++i)\n    {   std::cout << u01(rng) << \",\";    }\n    std::cout << std::endl;\n\n    normal_distribution<> nd(1, 2);\n    int count = 0;\n    for (int i = 0;i < 10000;++i)\n    {\n        if (abs(nd(rng) - 1) <= 2.0)\n        {   ++count;    }\n    }\n    std::cout << 1.0 * count / 10000 << std::endl;\n}\n\n//////////////////////////////////////////\n\nvoid case4()\n{\n    mt19937 rng((int32_t)time(0));\n    uniform_smallint<>  us(1,100);\n\n    variate_generator<mt19937&, uniform_smallint<>> gen(rng, us);\n    for (int i = 0; i < 10 ; ++i)\n    {       std::cout << gen() << std::endl;  }\n\n}\n\ntemplate<typename Rng >\nvoid rand_bytes(unsigned char *buf, int buf_len)\n{\n    typedef variate_generator<Rng, uniform_smallint<>> var_gen_t;\n    static var_gen_t\n        gen(Rng((typename Rng::result_type)time(0)),\n                uniform_smallint<>(1,255));\n\n    generate_n(buf, buf_len, std::ref(gen));\n    //for (int i = 0; i < buf_len; ++i)\n    //{   buf[i] = gen();}\n}\n\nvoid case5()\n{\n    unsigned char buf[10];\n\n    rand_bytes<mt19937>(buf, 10);\n    for (int i = 0;i < 10 ;++i)\n    {       std::cout << (short)buf[i] << \",\";   }\n    std::cout << std::endl;\n\n    rand_bytes<rand48>(buf, 10);\n    for (int i = 0;i < 10 ;++i)\n    {       std::cout << (short)buf[i] << \",\";   }\n\n    std::cout << std::endl;\n}\n\n//////////////////////////////////////////\n\n#include <boost/nondet_random.hpp>\n\nclass boost::random_device::impl\n{\n    private:\n        rand48 rng;\n    public:\n        impl():rng(time(0))\n    {   std::cout << \"random_device::impl ctor\\n\";   }\n\n    ~impl() \n    {   std::cout << \"random_device::impl dtor\\n\";   }\n\n    unsigned int operator()()\n    {   return rng();   }\n};\n\nboost::random_device::random_device()\n: pimpl(new impl)\n{}\n\nboost::random_device::~random_device()\n{   delete pimpl;}\n\ndouble boost::random_device::entropy() const\n{   return 10;}\n\nunsigned int boost::random_device::operator()()\n{   return (*pimpl)();}\n\nvoid case6()\n{\n    random_device rng;\n    for (int i = 0 ;i < 10 ; ++i)\n    {   std::cout << rng() << \",\";   }\n    std::cout << std::endl;\n\n    uniform_real<> ur(1.0, 2.0);\n    for (int i = 0 ;i < 10 ; ++i)\n    {   std::cout << ur(rng) << \",\"; }\n    std::cout << std::endl;\n\n    variate_generator<random_device&, uniform_smallint<>> \n        gen(rng, uniform_smallint<>(0,255));\n    for (int i = 0 ;i < 10 ; ++i)\n    {   std::cout << gen() << \",\";   }\n    std::cout << std::endl;\n}\n\n\nint main()\n{\n    case1();\n    case2();\n    case3();\n    case4();\n    case5();\n    case6();\n}\n\n", "meta": {"hexsha": "00a68a6f5a37f32c37aea1198bd23acff378a437", "size": 3560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/random.cpp", "max_stars_repo_name": "xujungp02/boost_guide", "max_stars_repo_head_hexsha": "328516455d334506f824402455a17afc606ca3bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 355.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T12:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T04:15:00.000Z", "max_issues_repo_path": "math/random.cpp", "max_issues_repo_name": "lak123456/boost_guide", "max_issues_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-04T18:14:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-09T02:38:12.000Z", "max_forks_repo_path": "math/random.cpp", "max_forks_repo_name": "lak123456/boost_guide", "max_forks_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 202.0, "max_forks_repo_forks_event_min_datetime": "2015-03-23T16:16:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:55:48.000Z", "avg_line_length": 20.4597701149, "max_line_length": 65, "alphanum_fraction": 0.4851123596, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6340307396767062}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/box/comparison.hpp>\n#include <fcppt/math/box/intersection.hpp>\n#include <fcppt/math/box/null.hpp>\n#include <fcppt/math/box/object_impl.hpp>\n#include <fcppt/math/box/output.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_box_intersection\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef fcppt::math::box::object<\n\t\tint,\n\t\t2\n\t> box_i2;\n\n\tbox_i2 const\n\t\tbox1(\n\t\t\tbox_i2::vector(\n\t\t\t\t1,\n\t\t\t\t1\n\t\t\t),\n\t\t\tbox_i2::dim(\n\t\t\t\t2,\n\t\t\t\t2\n\t\t\t)\n\t\t),\n\t\tbox2(\n\t\t\tbox_i2::vector(\n\t\t\t\t0,\n\t\t\t\t0\n\t\t\t),\n\t\t\tbox_i2::dim(\n\t\t\t\t4,\n\t\t\t\t4\n\t\t\t)\n\t\t),\n\t\tbox3(\n\t\t\tbox_i2::vector(\n\t\t\t\t2,\n\t\t\t\t2\n\t\t\t),\n\t\t\tbox_i2::dim(\n\t\t\t\t2,\n\t\t\t\t2\n\t\t\t)\n\t\t),\n\t\tbox4(\n\t\t\tbox_i2::vector(\n\t\t\t\t5,\n\t\t\t\t5\n\t\t\t),\n\t\t\tbox_i2::dim(\n\t\t\t\t1,\n\t\t\t\t1\n\t\t\t)\n\t\t),\n\t\tintersection1(\n\t\t\tfcppt::math::box::intersection(\n\t\t\t\tbox1,\n\t\t\t\tbox2\n\t\t\t)\n\t\t),\n\t\tintersection2(\n\t\t\tfcppt::math::box::intersection(\n\t\t\t\tbox1,\n\t\t\t\tbox3\n\t\t\t)\n\t\t),\n\t\tintersection3(\n\t\t\tfcppt::math::box::intersection(\n\t\t\t\tbox1,\n\t\t\t\tbox4\n\t\t\t)\n\t\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tintersection1,\n\t\tbox1\n\t);\n\n\tbox_i2 const result2(\n\t\tbox_i2::vector(\n\t\t\t2,\n\t\t\t2\n\t\t),\n\t\tbox_i2::dim(\n\t\t\t1,\n\t\t\t1\n\t\t)\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tintersection2,\n\t\tresult2\n\t);\n\n\tBOOST_CHECK_EQUAL(\n\t\tintersection3,\n\t\tfcppt::math::box::null<\n\t\t\tbox_i2\n\t\t>()\n\t);\n}\n", "meta": {"hexsha": "23b38eb59e46bd14d6d894b2044be43906d42838", "size": 1756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/box/intersection.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/box/intersection.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/box/intersection.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.393442623, "max_line_length": 61, "alphanum_fraction": 0.6258542141, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6340307338471048}}
{"text": "#include <Eigen/Dense>\n#include <igl/readOFF.h>\n#include <igl/writeOFF.h>\n#include <igl/exact_geodesic.h>\n#include <igl/colormap.h>\n\nint main()\n{\n    Eigen::MatrixXd V;\n    Eigen::MatrixXi F;\n    igl::readOFF(\"./data/mesh/bunny.off\", V, F);\n\n    // Compute geodesic distances from all vertices to the source vertex 0.\n    Eigen::VectorXi VS, FS, VT, FT;\n    VS.resize(1);\n    VS << 0;\n    VT.setLinSpaced(V.rows(), 0, V.rows() - 1);\n    Eigen::VectorXd D;\n    igl::exact_geodesic(V, F, VS, FS, VT, FT, D);\n\n    // Visualize the geodesics as colors using a colormap.\n    Eigen::MatrixXd C;\n    igl::colormap(igl::COLOR_MAP_TYPE_JET, D, true, C);\n    igl::writeOFF(\"./bunny_heat_geodesics.off\", V, F, C);\n}\n", "meta": {"hexsha": "1d43e11abeae9f510ff9c906ee919207c1325b69", "size": 705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "use_libigl/main.cpp", "max_stars_repo_name": "unclejimbo/practical-geometry-processing", "max_stars_repo_head_hexsha": "2ff43b0d258765af142d9f880ac64b125d15a33e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "use_libigl/main.cpp", "max_issues_repo_name": "unclejimbo/practical-geometry-processing", "max_issues_repo_head_hexsha": "2ff43b0d258765af142d9f880ac64b125d15a33e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "use_libigl/main.cpp", "max_forks_repo_name": "unclejimbo/practical-geometry-processing", "max_forks_repo_head_hexsha": "2ff43b0d258765af142d9f880ac64b125d15a33e", "max_forks_repo_licenses": ["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.1153846154, "max_line_length": 75, "alphanum_fraction": 0.6397163121, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.6791786991753929, "lm_q1q2_score": 0.6339663214897742}}
{"text": "#include \"StableFluidsSim.h\"\n#include <Eigen/LU>\n\nscalar lerp(scalar a, scalar b, scalar x) {\n    return (1 - x) * a + x * b;\n}\n\nvoid StableFluidsSim::diffuseD(int N, ArrayXs * x, ArrayXs * x0, scalar diff, scalar dt)\n{\n  assert((*x0 == *x0).all());\n  \n  scalar a = diff * dt * N * N;\n  *x = *x0;\n  \n  scalar dD;\n  for (int k = 0; k < 20; k++)\n  {\n    for (int i = 1; i <= N; i++)\n    {\n      for (int j = 1; j <= N; j++) // IMPORTANT: DO NOT MODIFY THE LOOP ORDER\n      {\n        // STUDENTS: You will certainly need code here, do diffuse for ([1, N], [1, N])\n        dD = a * ((*x)(i - 1, j) + (*x)(i + 1, j) + (*x)(i, j - 1) + (*x)(i, j + 1));\n        (*x)(i, j) = ((*x0)(i, j) + dD) / (1 + 4 * a); \n      }\n    }\n  }\n}\n\nvoid StableFluidsSim::diffuseU(int N, ArrayXs * x, ArrayXs * x0, scalar diff, scalar dt)\n{\n    assert((*x0 == *x0).all());\n\n    scalar a = diff * dt * N * N;\n    *x = *x0;\n    scalar du;\n    int nTerms;\n    for (int k = 0; k < 20; k++)\n    {\n        for (int i = 1; i <= N; i++)\n        {\n            for (int j = 0; j <= N; j++) // IMPORTANT: DO NOT MODIFY THE LOOP ORDER\n            {\n                // STUDENTS: You will certainly need code here, do diffuse for ([1, N], [0, N]), note the case when (j == 0) or (j == N) need special treatment\n                if (j == 0) {\n                    du = a * ((*x)(i - 1, j) + (*x)(i + 1, j) + (*x)(i, j + 1));\n                    nTerms = 3;\n                }\n                else if (j == N) {\n                    du = a * ((*x)(i - 1, j) + (*x)(i + 1, j) + (*x)(i, j - 1));\n                    nTerms = 3; \n                }\n                else {\n                    du = a * ((*x)(i - 1, j) + (*x)(i + 1, j) + (*x)(i, j - 1) + (*x)(i, j + 1));\n                    nTerms = 4;\n                }\n                (*x)(i, j) = ((*x0)(i, j) + du) / (1 + nTerms * a); \n            }\n        }\n    }\n}\n\nvoid StableFluidsSim::diffuseV(int N, ArrayXs * x, ArrayXs * x0, scalar diff, scalar dt)\n{\n    assert((*x0 == *x0).all());\n\n    scalar a = diff * dt * N * N;\n    *x = *x0;\n    scalar du;\n    int nTerms;\n    for (int k = 0; k < 20; k++)\n    {\n        for (int i = 0; i <= N; i++)\n        {\n            for (int j = 1; j <= N; j++) // IMPORTANT: DO NOT MODIFY THE LOOP ORDER\n            {\n                if (i == 0) {\n                    du = a * ((*x)(i + 1, j) + (*x)(i, j - 1) + (*x)(i, j + 1));\n                    nTerms = 3;\n                }\n                else if (i == N) {\n                    du = a * ((*x)(i - 1, j) + (*x)(i, j - 1) + (*x)(i, j + 1));\n                    (*x)(i, j)= ((*x0)(i, j) + du) / (1 + 3 * a); \n                    nTerms = 3;\n                }\n                else {\n                    du = a * ((*x)(i - 1, j) + (*x)(i + 1, j) + (*x)(i, j - 1) + (*x)(i, j + 1));\n                    nTerms = 4;\n                }\n                (*x)(i, j) = ((*x0)(i, j) + du) / (1 + nTerms * a); \n            }\n        }\n    }\n}\n\nvoid StableFluidsSim::advectD(int N, ArrayXs * x, ArrayXs * x0, ArrayXs * u, ArrayXs * v, scalar dt)\n{\n    assert((*x0 == *x0).all());\n    assert((*u == *u).all());\n    assert((*v == *v).all());\n    \n    \n    // STUDENTS: You will certainly need code here, advect for ([1, N], [1, N])\n    scalar dt0 = dt * N;\n    \n    for (int i = 1; i <= N; i++)\n    {\n        for (int j = 1; j <= N; j++)\n        {\n            scalar i0 = i - dt0 * interpolateV(v, i, j);\n            scalar j0 = j - dt0 * interpolateU(u, i, j);\n            (*x)(i, j) = interpolateD(x0, i0, j0);\n            \n            \n        }\n    }\n}\n\nscalar StableFluidsSim::interpolateD(ArrayXs * d, scalar i, scalar j)\n{\n    // STUDENTS: You will certainly need code here, note the indices should be CLAMP-ed to [0, m_N], since we have to use (i + 1) and (j + 1)\n    int i1 = CLAMP((int) i, 0, m_N);\n    int i2 = i1 + 1;\n    int j1 = CLAMP((int) j, 0, m_N);\n    int j2 = j1 + 1;\n    scalar s = CLAMP(i - i1, 0, 1);\n    scalar t = CLAMP(j - j1, 0, 1);\n    scalar d1 = lerp((*d)(i1, j1), (*d)(i2, j1), s);\n    scalar d2 = lerp((*d)(i1, j2), (*d)(i2, j2), s);\n    return lerp(d1, d2, t);\n}\n\nscalar StableFluidsSim::interpolateU(ArrayXs * u, scalar i, scalar j)\n{\n    // STUDENTS: You will certainly need code here, note the i index should be CLAMP-ed to [0, m_N], while j index should be CLAMP-ed to [0, m_N-1], since we have to use (i + 1) and (j + 1)\n    int i1 = CLAMP((int) i, 0, m_N);\n    int i2 = i1 + 1;\n    int j1 = CLAMP((int) (j - 0.5), 0, m_N - 1);\n    int j2 = j1 + 1;\n    scalar s = CLAMP(i - i1, 0, 1);\n    scalar t = CLAMP(j - j1 - 0.5, 0, 1);\n    scalar u1 = lerp((*u)(i1, j1), (*u)(i2, j1), s);\n    scalar u2 = lerp((*u)(i1, j2), (*u)(i2, j2), s);\n    return lerp(u1, u2, t);\n}\n\nscalar StableFluidsSim::interpolateV(ArrayXs * v, scalar i, scalar j)\n{\n    // STUDENTS: You will certainly need code here\n    int i1 = CLAMP((int) (i - 0.5), 0, m_N - 1);\n    int i2 = i1 + 1;\n    int j1 = CLAMP((int) j, 0, m_N);\n    int j2 = j1 + 1;\n    scalar s = CLAMP(i - i1 - 0.5, 0, 1);\n    scalar t = CLAMP(j - j1, 0, 1);\n    scalar v1 = lerp((*v)(i1, j1), (*v)(i2, j1), s);\n    scalar v2 = lerp((*v)(i1, j2), (*v)(i2, j2), s);\n    return lerp(v1, v2, t);\n}\n\nvoid StableFluidsSim::advectU(int N, ArrayXs * x, ArrayXs * x0, ArrayXs * u, ArrayXs * v, scalar dt)\n{\n    assert((*x0 == *x0).all());\n    assert((*u == *u).all());\n    assert((*v == *v).all());\n\n    scalar dt0 = dt * N;\n    for (int i = 1; i <= N; i++)\n    {\n        for (int j = 0; j <= N; j++)\n        {\n            // STUDENTS: You will certainly need code here,\n            // add the origin of U grid to the coordinate before sampling, for example, sample at (i + 0, j + 0.5) when you need backtracing the old velocity at (i, j)\n            scalar i0 = i - dt0 * interpolateV(v, i, j + 0.5);\n            scalar j0 = j + 0.5 - dt0 * interpolateU(u, i, j + 0.5);\n            // now you have the backward-traced velocity, minus it from the current position (i + 0, j + 0.5), then sample the velocity again.\n            (*x)(i, j) = interpolateU(x0, i0, j0);\n        }\n    }\n}\n\nvoid StableFluidsSim::advectV(int N, ArrayXs * x, ArrayXs * x0, ArrayXs * u, ArrayXs * v, scalar dt)\n{\n    assert((*x0 == *x0).all());\n    assert((*u == *u).all());\n    assert((*v == *v).all());\n\n    scalar dt0 = dt * N;\n    for (int i = 0; i <= N; i++)\n    {\n        for (int j = 1; j <= N; j++)\n        {\n            // STUDENTS: You will certainly need code here\n            scalar i0 = i + 0.5 - dt0 * interpolateV(v, i + 0.5, j);\n            scalar j0 = j - dt0 * interpolateU(u, i + 0.5, j);\n            (*x)(i, j) = interpolateV(x0, i0, j0);\n        }\n    }\n}\n\nvoid StableFluidsSim::project(int N, ArrayXs * u, ArrayXs * v, ArrayXs * u0, ArrayXs * v0)\n{\n    if (VERBOSE) std::cout << \"u0: \" << std::endl << *u0 << std::endl << std::endl;\n    if (VERBOSE) std::cout << \"v0: \" << std::endl << *v0 << std::endl << std::endl;\n\n    ArrayXs div(N + 2, N + 2);\n    ArrayXs p(N + 2, N + 2);\n    div.setZero();\n    p.setZero();\n    scalar h = 1.0 / N;\n\n    // STUDENTS: You will certainly need code here\n\n    // set solid boundary conditions, 0 the most top and bottom row / left and right column of u0, v0\n    for (int i = 0; i <= N; ++i) {\n        // Top and bottom rows\n        (*u0)(0, i) = 0;\n        (*u0)(N + 1, i) = 0;\n        (*v0)(0, i) = 0;\n        (*v0)(N, i) = 0;\n        \n        // Left and right columns\n        (*u0)(i, 0) = 0;\n        (*u0)(i, N) = 0;\n        (*v0)(i, 0) = 0;\n        (*v0)(i, N + 1) = 0;\n        \n    }\n    // Edge cases\n    (*v0)(0, N + 1) = 0;\n    (*v0)(N, N + 1) = 0;\n    (*u0)(N + 1, 0) = 0;\n    (*u0)(N + 1, N) = 0;\n    \n    for (int i = 1; i <= N; i++)\n    {\n        for (int j = 1; j <= N; j++)\n        {\n          // compute divergence of the velocity field, note the divergence field is available from ([1, N], [1, N])\n          div(i, j) = -h * ((*v0)(i, j) - (*v0)(i - 1, j) + (*u0)(i, j) - (*u0)(i, j - 1));\n        }\n    }\n\n    for (int k = 0; k < 20; k++)\n    {\n        for (int i = 1; i <= N; i++)\n        {\n              for (int j = 1; j <= N; j++) // IMPORTANT: DO NOT MODIFY THE LOOP ORDER\n              {\n                  // solve for pressure inside the region ([1, N], [1, N])\n                  int nTerms = 4;\n                  scalar terms = p(i - 1, j) + p(i + 1, j) + p(i, j - 1) + p(i, j + 1);\n                  \n                  if (i == 1) {\n                      terms -= p(i - 1, j);\n                      --nTerms;\n                  }\n                  else if (i == N) {\n                      terms -= p(i + 1, j);\n                      --nTerms;\n                  }\n                  \n                  if (j == 1) {\n                      terms -= p(i, j - 1);\n                      --nTerms;\n                  }\n                  else if (j == N) {\n                      terms -= p(i, j + 1);\n                      --nTerms;\n                  }\n                  p(i, j) = (div(i, j) + terms) / nTerms;\n              }\n        }\n    }\n\n    (*u) = (*u0);\n    (*v) = (*v0);\n\n    for (int i = 1; i <= N; i++)\n    {\n        for (int j = 1; j < N; j++)\n        {\n            // apply pressure to correct velocities ([1, N], [1, N)) for u, ([1, N), [1, N]) for v\n            (*u)(i, j) -= (p(i, j + 1) - p(i, j)) / h;\n            (*v)(j, i) -= (p(j + 1, i) - p(j, i)) / h;   \n        }\n    }\n}", "meta": {"hexsha": "3e6b76d0287792844340b3deb424e3d0eefe33fe", "size": 9285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t5m1/FOSSSim/StableFluids/StableFluidsSim.cpp", "max_stars_repo_name": "edaaydinea/CSMM104X-Animation-CGI-Motion", "max_stars_repo_head_hexsha": "82c3e85826a1b27e4b4886f1f49877d2b95ab3ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-09-27T10:00:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T11:44:47.000Z", "max_issues_repo_path": "t5m1/FOSSSim/StableFluids/StableFluidsSim.cpp", "max_issues_repo_name": "edaaydinea/CSMM104X-Animation-CGI-Motion", "max_issues_repo_head_hexsha": "82c3e85826a1b27e4b4886f1f49877d2b95ab3ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "t5m1/FOSSSim/StableFluids/StableFluidsSim.cpp", "max_forks_repo_name": "edaaydinea/CSMM104X-Animation-CGI-Motion", "max_forks_repo_head_hexsha": "82c3e85826a1b27e4b4886f1f49877d2b95ab3ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T06:58:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T06:58:26.000Z", "avg_line_length": 32.2395833333, "max_line_length": 189, "alphanum_fraction": 0.4039849219, "num_tokens": 3365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6339277539727012}}
{"text": "//####### Test module for quadrature ####################################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"quadratures\"\n\n//Will automatically define a main for this test\n #define BOOST_TEST_DYN_LINK\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\n //Units choice. Not relevant here, but avoids compile-time warning\n #define PXRMP_USE_SI_UNITS\n\n#include \"quadrature.hpp\"\n\nusing namespace picsar::multi_physics;\n\n// ------------- Tests --------------\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-6;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-3;\n\n//Test quadrature with double precision\nBOOST_AUTO_TEST_CASE( quadrature_finite_interval_double_1 )\n{\n    auto sin2 = [](double x)\n        {return sin(x)*sin(x);};\n\n    const double a = 0.0;\n    const double b = 2.0*pi;\n\n    const double exp_res_sin2 = pi;\n\n    double res_sin2 = quad_a_b<double>(sin2, a, b);\n\n    BOOST_CHECK_SMALL((res_sin2-exp_res_sin2)/exp_res_sin2, double_tolerance);\n}\n\nBOOST_AUTO_TEST_CASE( quadrature_infinite_interval_double_1 )\n{\n    auto expx2 = [](double x)\n        {return exp(-x*x);};\n\n    const double a = 0.0;\n\n    const double exp_expx2 = sqrt(pi)/2.0;\n\n    double res_expx2 = quad_a_inf<double>(expx2, a);\n\n    BOOST_CHECK_SMALL((res_expx2-exp_expx2)/exp_expx2, double_tolerance);\n}\n\nBOOST_AUTO_TEST_CASE( quadrature_infinite_interval_double_2 )\n{\n    auto datan = [](double x)\n        {return 1.0/(1.0+x*x);};\n\n    const double a = 0.0;\n\n    const double exp_datan = pi/2.0;\n\n    double res_datan = quad_a_inf<double>(datan, a);\n\n    BOOST_CHECK_SMALL((res_datan-exp_datan)/exp_datan, double_tolerance);\n}\n\n//Test Bessel functions with single precision\nBOOST_AUTO_TEST_CASE( quadrature_finite_interval_float_1 )\n{\n    auto fsin2 = [](float x)\n        {return sin(x)*sin(x);};\n\n        const float fa = static_cast<float>(0.0);\n        const float fb = static_cast<float>(2.0*pi);\n\n        const float fexp_res_sin2 = static_cast<float>(pi);\n\n        float fres_sin2 = quad_a_b<float>(fsin2, fa, fb);\n\n        BOOST_CHECK_SMALL((fres_sin2-fexp_res_sin2)/fexp_res_sin2,\n            float_tolerance);\n}\n\nBOOST_AUTO_TEST_CASE( quadrature_infinite_interval_float_1 )\n{\n    auto fexpx2 = [](float x)\n        {return exp(-x*x);};\n\n    const float fa = static_cast<float>(0.0);\n\n    const float fexp_expx2 = static_cast<float>(sqrt(pi)/2.0);\n\n    float fres_expx2 = quad_a_inf<float>(fexpx2, fa);\n\n    BOOST_CHECK_SMALL((fres_expx2-fexp_expx2)/fexp_expx2, float_tolerance);\n}\n\nBOOST_AUTO_TEST_CASE( quadrature_infinite_interval_float_2 )\n{\n    auto fdatan = [](float x)\n        {return 1.0f/(1.0f+x*x);};\n\n    const float fa = static_cast<float>(0.0);\n\n    const float fexp_datan = static_cast<float>(pi/2.0);\n\n    float fres_datan = quad_a_inf<float>(fdatan, fa);\n\n    BOOST_CHECK_SMALL((fres_datan-fexp_datan)/fexp_datan, float_tolerance);\n}\n", "meta": {"hexsha": "2218ff0cb0f03b88972a65c7d06e9fa3e9d87665", "size": 3028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_quadrature.cpp", "max_stars_repo_name": "thaisacs/PICSAR", "max_stars_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multi_physics/QED_tests/test_quadrature.cpp", "max_issues_repo_name": "thaisacs/PICSAR", "max_issues_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multi_physics/QED_tests/test_quadrature.cpp", "max_forks_repo_name": "thaisacs/PICSAR", "max_forks_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1034482759, "max_line_length": 78, "alphanum_fraction": 0.6925363276, "num_tokens": 828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.754914975839675, "lm_q1q2_score": 0.633927747917043}}
{"text": "#include \"SHTools.h\"\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <boost/filesystem.hpp>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n#include <math.h>\n#include <random>\n#include <string>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<unsigned, K> Vb;\ntypedef CGAL::Triangulation_data_structure_2<Vb> Tds;\ntypedef CGAL::Delaunay_triangulation_2<K, Tds> Delaunay;\ntypedef Delaunay::Face_circulator Face_circulator;\ntypedef Delaunay::Face_handle Face_handle;\ntypedef Delaunay::Point Point;\ntypedef Eigen::Vector3d Vector3d;\ntypedef Eigen::VectorXd VectorXd;\ntypedef Eigen::Matrix3d Matrix3d;\ntypedef Eigen::Matrix3Xd Matrix3Xd;\ntypedef Eigen::Map<Matrix3Xd> MapM3Xd;\ntypedef Eigen::Ref<Matrix3Xd> RefM3Xd;\n\nint main(int argc, char *argv[]) {\n\n  // We expect three command line arguments:\n  // 1. Path to the data file\n  // 2. Output directory where output files will be created\n  if (argc < 3) {\n    std::cout << \"Usage: ./postProcess <data_file> <output_dir>\" << std::endl;\n    return 0;\n  }\n\n  clock_t t = clock();\n\n  // Open the data file\n  std::ifstream inputfile(argv[1]);\n  if (!inputfile.is_open()) {\n    std::cout << \"Unable to open file \" << argv[1] << std::endl;\n    return 0;\n  }\n\n  //**********************************************************************//\n  // Create directory for storing the output files f.dat, Alm.dat and\n  // spectrum.dat\n  //\n\n  auto outputDir = boost::filesystem::path(std::string(argv[2]));\n  if (!boost::filesystem::create_directory(outputDir)) {\n    std::cout << \"Could not create output directory \" << outputDir << std::endl;\n    return 0;\n  }\n\n  auto f_path = std::string(argv[2]) + \"/f0.dat\";\n  std::ofstream f_file(f_path);\n  auto df2_path = std::string(argv[2]) + \"/df2.dat\";\n  std::ofstream df2_file(df2_path);\n  auto u_path = std::string(argv[2]) + \"/u2.dat\";\n  std::ofstream u_file(u_path);\n  auto Alm_mean_path = std::string(argv[2]) + \"/Alm_mean.dat\";\n  std::ofstream Alm_mean_file(Alm_mean_path);\n  auto Alm_var_path = std::string(argv[2]) + \"/Alm_var.dat\";\n  std::ofstream Alm_var_file(Alm_var_path);\n  auto spec_path = std::string(argv[2]) + \"/spectrum.dat\";\n  std::ofstream spec_file(spec_path);\n\n  if (!f_file) {\n    std::cout << \"Failed to create output file \" << f_path;\n    return 0;\n  }\n  if (!df2_file) {\n    std::cout << \"Failed to create output file \" << df2_path;\n    return 0;\n  }\n  if (!u_file) {\n    std::cout << \"Failed to create output file \" << u_path;\n    return 0;\n  }\n  if (!Alm_mean_file) {\n    std::cout << \"Failed to create output file \" << Alm_mean_path;\n    return 0;\n  }\n  if (!Alm_var_file) {\n    std::cout << \"Failed to create output file \" << Alm_var_path;\n    return 0;\n  }\n  if (!spec_file) {\n    std::cout << \"Failed to create output file \" << spec_path;\n    return 0;\n  }\n\n  //**********************************************************************//\n  // Now read the first( or the header ) line of the data file\n  // The first line contains N, gamma and beta information\n  std::string line, ignore;\n  size_t N;\n  double_t gamma = 0, beta = 0;\n  std::getline(inputfile, line);\n  std::istringstream header(line);\n  header >> ignore >> N >> ignore >> gamma >> ignore >> beta;\n  int lmax = std::floor(std::sqrt(N) - 1);\n\n  // Write column names in the output files\n  f_file << \"f0\" << std::endl;\n  df2_file << \"df2\" << std::endl;\n  u_file << \"mean,variance\" << std::endl;\n  for (auto i = 0; i < lmax; ++i) {\n    Alm_mean_file << \"l\" << i << \",\";\n    Alm_var_file << \"l\" << i << \",\";\n    spec_file << \"l\" << i << \",\";\n  }\n  Alm_mean_file << \"l\" << lmax << std::endl;\n  Alm_var_file << \"l\" << lmax << std::endl;\n  spec_file << \"l\" << lmax << std::endl;\n\n  //**********************************************************************//\n  // Create the Gauss-Lengendre grid\n  //\n  int nlat, nlong;\n  Eigen::VectorXd latglq(lmax + 1);\n  Eigen::VectorXd longlq(2 * lmax + 1);\n  glqgridcoord_wrapper_(latglq.data(), longlq.data(), &lmax, &nlat, &nlong);\n  auto numQ = nlat * nlong;\n\n  Eigen::VectorXd gridglq(numQ);\n  Eigen::VectorXd plx((lmax + 1) * (lmax + 1) * (lmax + 2) / 2);\n  Eigen::VectorXd w(lmax + 1), zero(lmax + 1);\n  Eigen::VectorXd cilm(2 * (lmax + 1) * (lmax + 1));\n  Eigen::VectorXd pspectrum(lmax + 1);\n\n  // Pre-compute all the matrices needed for expansion\n  shglq_wrapper_(&lmax, zero.data(), w.data(), plx.data());\n\n  //**********************************************************************//\n  // Some useful lambda functions\n  //\n\n  // A function to read N rows of a 3xN matrix from a stringstream\n  auto readMatrix3Xd = [](std::istringstream &ss, RefM3Xd X) {\n    auto N = X.cols();\n    size_t valCount = 0;\n    while (valCount < 3 * N && ss.good()) {\n      std::string value;\n      std::getline(ss, value, ',');\n      X(valCount % 3, valCount / 3) = std::stod(value);\n      valCount++;\n    }\n  };\n\n  // Calculate Alm from cilm\n  auto A_lm = [&cilm, &lmax](const size_t l, const int m) {\n    int j = 0, n = m;\n    if (m < 0) {\n      j = 1;\n      n = -m;\n    }\n    return cilm(j + 2 * (l + (lmax + 1) * n));\n  };\n\n  // The first row of data is ALWAYS the zero temperature particle position\n  // and rotation vectors. We will use it to locate the triangles containing\n  // the quadrature points for interpolation and also the zero temperature\n  // radius\n  Matrix3Xd zeroTempX(3, N);\n  std::getline(inputfile, line);\n  std::istringstream zeroTempRow(line);\n  readMatrix3Xd(zeroTempRow, zeroTempX);\n\n  // Calculate the zero temperature radius\n  double_t R0 = zeroTempX.colwise().norm().mean();\n\n  // Now we need to project the zeroTempX to a sphere of radius R0\n  Matrix3Xd X0(3, N);\n  X0 = R0 * zeroTempX.colwise().normalized();\n\n  // The following matrix is unit normals associated with X0\n  Matrix3Xd x0(3, N);\n  x0 = X0.normalized();\n\n  // Quadrature point coordinates in Cartesian on a sphere of radius R0\n  Matrix3Xd Q0(3, numQ);\n  size_t index = 0;\n  for (auto ip = 0; ip < nlong; ++ip) {\n    auto phi = longlq(ip) * M_PI / 180.0;\n    auto sin_p = std::sin(phi);\n    auto cos_p = std::cos(phi);\n    for (auto it = 0; it < nlat; ++it) {\n      auto theta = (90.0 - latglq(it)) * M_PI / 180.0;\n      auto sin_t = std::sin(theta);\n      Q0.col(index++) << R0 * sin_t * cos_p, R0 * sin_t * sin_p,\n          R0 * std::cos(theta);\n    }\n  }\n\n  // Rotate all points of the shell so that the 0th point is along z-axis\n  Vector3d c = X0.col(0);\n  double_t cos_t = c(2) / c.norm();\n  double_t sin_t = std::sin(std::acos(cos_t));\n  Vector3d axis;\n  axis << c(1), -c(0), 0.;\n  axis.normalize();\n  Matrix3d rotMat, axis_cross, outer;\n  axis_cross << 0., -axis(2), axis(1), axis(2), 0., -axis(0), -axis(1), axis(0),\n      0.;\n  outer.noalias() = axis * axis.transpose();\n  rotMat =\n      cos_t * Matrix3d::Identity() + sin_t * axis_cross + (1 - cos_t) * outer;\n  Matrix3Xd rPts(3, N);\n  rPts = rotMat * X0;\n\n  // Calculate the stereographic projections\n  Vector3d p0;\n  p0 << 0, 0, -R0; // Point on the plane of projection\n  c = rPts.col(0); // The point from which we are projecting\n\n  MapM3Xd l0(&(rPts(0, 1)), 3, N - 1);\n  Matrix3Xd l(3, N - 1), proj(3, N - 1);\n  l = (l0.colwise() - c).colwise().normalized(); // dirns of projections\n  for (auto j = 0; j < N - 1; ++j) {\n    proj.col(j) = ((p0(2) - l0(2, j)) / l(2, j)) * l.col(j) + l0.col(j);\n  }\n\n  // Insert the projected points in a CGAL vertex_with_info vector\n  std::vector<std::pair<Point, unsigned>> verts;\n  for (auto j = 0; j < N - 1; ++j) {\n    verts.push_back(std::make_pair(Point(proj(0, j), proj(1, j)), j + 1));\n  }\n\n  // Triangulate\n  Delaunay dt(verts.begin(), verts.end());\n\n  // Rotate the quadrature points\n  Matrix3Xd Qr(3, numQ);\n  Qr = rotMat * Q0;\n\n  // Stereographic projection of quadrature points\n  Eigen::Matrix3Xd lQ(3, numQ), Qsp(3, numQ);\n  lQ = (Qr.colwise() - c).colwise().normalized();\n  for (auto j = 0; j < numQ; ++j) {\n    Qsp.col(j) = ((p0(2) - Qr(2, j)) / lQ(2, j)) * lQ.col(j) + Qr.col(j);\n  }\n  //**********************************************************************//\n\n  //******************** Determine interpolation weights ******************//\n  std::vector<std::vector<std::pair<size_t, double_t>>> interpolData;\n  for (auto q = 0; q < numQ; ++q) {\n    auto query = Point(Qsp(0, q), Qsp(1, q));\n    Delaunay::Locate_type lt;\n    int li;\n    Face_handle face = dt.locate(query, lt, li);\n    std::vector<std::pair<size_t, double_t>> nodesAndWeights;\n    switch (lt) {\n    case Delaunay::FACE: {\n      auto i = face->vertex(0)->info();\n      auto j = face->vertex(1)->info();\n      auto k = face->vertex(2)->info();\n      Eigen::Vector3d v0 = X0.col(i);\n      Eigen::Vector3d v1 = X0.col(j);\n      Eigen::Vector3d v2 = X0.col(k);\n      Eigen::Vector3d qp = Q0.col(q);\n      auto A0 = ((v1 - qp).cross((v2 - qp))).norm();\n      auto A1 = ((v2 - qp).cross((v0 - qp))).norm();\n      auto A2 = ((v0 - qp).cross((v1 - qp))).norm();\n      auto A = A0 + A1 + A2;\n      nodesAndWeights.push_back(std::make_pair(i, A0 / A));\n      nodesAndWeights.push_back(std::make_pair(j, A1 / A));\n      nodesAndWeights.push_back(std::make_pair(k, A2 / A));\n      break;\n    }\n    case Delaunay::OUTSIDE_CONVEX_HULL: {\n      auto i = dt.is_infinite(face->vertex(0)) ? 0 : face->vertex(0)->info();\n      auto j = dt.is_infinite(face->vertex(1)) ? 0 : face->vertex(1)->info();\n      auto k = dt.is_infinite(face->vertex(2)) ? 0 : face->vertex(2)->info();\n      Eigen::Vector3d v0 = X0.col(i);\n      Eigen::Vector3d v1 = X0.col(j);\n      Eigen::Vector3d v2 = X0.col(k);\n      Eigen::Vector3d qp = Q0.col(q);\n      auto A0 = ((v1 - qp).cross((v2 - qp))).norm();\n      auto A1 = ((v2 - qp).cross((v0 - qp))).norm();\n      auto A2 = ((v0 - qp).cross((v1 - qp))).norm();\n      auto A = A0 + A1 + A2;\n      nodesAndWeights.push_back(std::make_pair(i, A0 / A));\n      nodesAndWeights.push_back(std::make_pair(j, A1 / A));\n      nodesAndWeights.push_back(std::make_pair(k, A2 / A));\n      break;\n    }\n    case Delaunay::EDGE: {\n      auto id1 = face->vertex((li + 1) % 3)->info();\n      auto id2 = face->vertex((li + 2) % 3)->info();\n      Eigen::Vector3d v1, v2, qp;\n      v1 = X0.col(id1);\n      v2 = X0.col(id2);\n      qp = Q0.col(q);\n      double_t ratio = (qp - v1).norm() / (qp - v2).norm();\n      nodesAndWeights.push_back(std::make_pair(id1, 1.0 / (1 + ratio)));\n      nodesAndWeights.push_back(std::make_pair(id2, ratio / (1 + ratio)));\n      break;\n    }\n    case Delaunay::VERTEX:\n      nodesAndWeights.push_back(std::make_pair(li, 1.0));\n      break;\n    default:\n      std::cout << \"Quadrature point \" << q << \" not found!\" << std::endl;\n    }\n    interpolData.push_back(nodesAndWeights);\n  }\n  //**********************************************************************//\n\n  //***************************** MAIN LOOP ******************************//\n  // Now iterate over the remaining rows\n  auto f0_mean = 0.0;\n  auto rowCount = 1;\n  while (std::getline(inputfile, line)) {\n\n    std::istringstream rowStream(line);\n\n    // We will extract 3*N doubles representing particle positions\n    // from the stream and ignore the 3*N rotation vector components\n    Matrix3Xd Xt(3, N);\n    readMatrix3Xd(rowStream, Xt);\n\n    // Calculate finput for all particles\n    VectorXd finput(N);\n    // VectorXd u_squared(N);\n    finput = ((Xt - X0).array() * x0.array()).matrix().colwise().sum();\n    auto f0 = finput.mean();\n    f_file << f0 << std::endl;\n    f0_mean += f0;\n\n    // Calculate tangent fluctuations\n    VectorXd u_squared(N);\n    u_squared = ((Xt - X0) - x0 * finput.asDiagonal()).colwise().squaredNorm();\n    u_file << u_squared.mean() << \",\"\n           << (u_squared - u_squared.mean() * VectorXd::Ones(N))\n                  .array()\n                  .square()\n                  .mean()\n           << std::endl;\n\n    // Now calculate f at quadrature points from finput by interpolation\n    gridglq.setZero(numQ);\n    for (auto q = 0; q < numQ; ++q) {\n      auto nodeWeights = interpolData[q];\n      for (const auto &nw : nodeWeights) {\n        gridglq(q) += finput(nw.first) * nw.second;\n      }\n    }\n\n    // Expand using Gauss-Legendre Quadrature\n    shexpandglq_wrapper_(cilm.data(), &lmax, gridglq.data(), w.data(),\n                         plx.data());\n\n    // Calculate Alm coefficients and their mean and variance\n    for (auto l = 0; l < lmax; ++l) {\n      std::vector<double_t> Alm_vec;\n      double_t Alm_mean = 0.0;\n      for (auto m = -l; m <= l; ++m) {\n        auto Alm = A_lm(l, m);\n        Alm_mean += Alm;\n        Alm_vec.push_back(Alm);\n      }\n      auto n = Alm_vec.size();\n      Alm_mean /= n;\n      double_t Alm_var = 0.0;\n      for (const auto &alm : Alm_vec) {\n        Alm_var += (alm - Alm_mean) * (alm - Alm_mean);\n      }\n      Alm_var /= n;\n      // Write the mean and variance to file\n      Alm_mean_file << Alm_mean << \",\";\n      Alm_var_file << Alm_var << \",\";\n    }\n\n    {\n      std::vector<double_t> Alm_vec;\n      double_t Alm_mean = 0.0;\n      for (auto m = -lmax; m <= lmax; ++m) {\n        auto Alm = A_lm(lmax, m);\n        Alm_mean += Alm;\n        Alm_vec.push_back(Alm);\n      }\n      auto n = Alm_vec.size();\n      Alm_mean /= n;\n      double_t Alm_var = 0.0;\n      for (const auto &alm : Alm_vec) {\n        Alm_var += (alm - Alm_mean) * (alm - Alm_mean);\n      }\n      Alm_var /= n;\n      // Write the mean and variance to file\n      Alm_mean_file << Alm_mean << std::endl;\n      Alm_var_file << Alm_var << std::endl;\n    }\n\n    // Get the power spectrum and write it to file\n    shpowerspectrum_wrapper_(cilm.data(), &lmax, pspectrum.data());\n    for (auto l = 0; l < lmax; ++l)\n      spec_file << pspectrum(l) << \",\";\n    spec_file << pspectrum(lmax) << std::endl;\n\n    rowCount++;\n  }\n  // Time average of f0\n  f0_mean /= rowCount;\n\n  // Close all the open files\n  spec_file.close();\n  f_file.close();\n  u_file.close();\n  Alm_mean_file.close();\n  Alm_var_file.close();\n\n  // Now we will read the input data file again to calculate variance of\n  // finput over all time steps\n  inputfile.clear();\n  inputfile.seekg(0, std::ios::beg);\n  std::getline(inputfile, line); // Eat the header line\n  std::getline(inputfile, line); // Eat the zero temperature line\n\n  while (std::getline(inputfile, line)) {\n\n    std::istringstream rowStream(line);\n\n    // We will extract 3*N doubles representing particle positions\n    // from the stream and ignore the 3*N rotation vector components\n    Matrix3Xd Xt(3, N);\n    readMatrix3Xd(rowStream, Xt);\n\n    // Calculate finput for all particles\n    VectorXd finput(N);\n    finput = ((Xt - X0).array() * x0.array()).matrix().colwise().sum();\n    df2_file << (finput - f0_mean * VectorXd::Ones(N)).array().square().mean()\n             << std::endl;\n  }\n\n  df2_file.close();\n\n  std::cout << \"Time elapsed = \" << ((float)(clock() - t)) / CLOCKS_PER_SEC\n            << \" seconds.\" << std::endl;\n\n  return 1;\n}\n", "meta": {"hexsha": "24230011ef7443f2a35f4f47005feeba213530a4", "size": 14993, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/PostProcess/PostProcess.cxx", "max_stars_repo_name": "amit112amit/oriented-particles", "max_stars_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-21T08:01:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T08:01:15.000Z", "max_issues_repo_path": "src/PostProcess/PostProcess.cxx", "max_issues_repo_name": "amit112amit/oriented-particles", "max_issues_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PostProcess/PostProcess.cxx", "max_forks_repo_name": "amit112amit/oriented-particles", "max_forks_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5413870246, "max_line_length": 80, "alphanum_fraction": 0.5813379577, "num_tokens": 4616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.6339145748984624}}
{"text": "// weighted_die.cpp\r\n//\r\n// Copyright (c) 2009\r\n// Steven Watanabe\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[weighted_die\r\n/*`\r\n    For the source of this example see\r\n    [@boost://libs/random/example/weighted_die.cpp weighted_die.cpp].\r\n*/\r\n#include <boost/random/mersenne_twister.hpp>\r\n#include <boost/random/discrete_distribution.hpp>\r\n\r\nboost::mt19937 gen;\r\n\r\n/*`\r\n   This time, instead of a fair die, the probability of\r\n   rolling a 1 is 50% (!).  The other five faces are all\r\n   equally likely.\r\n\r\n   __discrete_distribution works nicely here by allowing\r\n   us to assign weights to each of the possible outcomes.\r\n\r\n   [tip If your compiler supports `std::initializer_list`,\r\n   you can initialize __discrete_distribution directly with\r\n   the weights.]\r\n*/\r\ndouble probabilities[] = {\r\n    0.5, 0.1, 0.1, 0.1, 0.1, 0.1\r\n};\r\nboost::random::discrete_distribution<> dist(probabilities);\r\n\r\n/*`\r\n  Now define a function that simulates rolling this die.\r\n*/\r\nint roll_weighted_die() {\r\n    /*<< Add 1 to make sure that the result is in the range [1,6]\r\n         instead of [0,5].\r\n    >>*/\r\n    return dist(gen) + 1;\r\n}\r\n\r\n//]\r\n\r\n#include <iostream>\r\n\r\nint main() {\r\n    for(int i = 0; i < 10; ++i) {\r\n        std::cout << roll_weighted_die() << std::endl;\r\n    }\r\n}\r\n", "meta": {"hexsha": "f207cfa54ffdd769aa46b4e166b67d6b723e17f4", "size": 1401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/example/weighted_die.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/random/example/weighted_die.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/example/weighted_die.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 25.0178571429, "max_line_length": 70, "alphanum_fraction": 0.6495360457, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.63386890183762}}
{"text": "//==================================================================================================\n//  BiLinearInterpolation.hpp\n//\n//  Created by Zachary Clawson on 7/19/2015\n//  Copyright (c) 2015 Zachary Clawson. All rights reserved.\n//==================================================================================================\n\n#ifndef __BiLinearInterpolation_hpp\n#define __BiLinearInterpolation_hpp\n\n#include <Eigen/Dense>\n#include \"config/GlobalTypes.hpp\"\n\n//------------------------------------------------------------------------------------------------//\n//------------------------------------------------------------------------------------------------//\n\n/** BiLinearInterpolation\n *  * This implementation follows the way it is written on Wikipedia with the exception that we\n *    reverse the meaning of eta and xi (i.e. on Wikipedia eta <- 1-eta and xi <- 1-xi\n *    https://en.wikipedia.org/wiki/Bilinear_interpolation\n */\n\nclass BiLinearInterpolationPrivate;\n\nclass BiLinearInterpolation {\npublic:\n\tBiLinearInterpolation(\n        const ArrayXreal_t & values,\n        const Vector2real_t bounds_min,\n        const Vector2real_t bounds_max\n    );\n\n\t~BiLinearInterpolation();\n    \n    real_t operator()(const Vector2real_t & x) const;\n    \nprivate:\n    std::unique_ptr<BiLinearInterpolationPrivate> p;\n};\n\n\n//------------------------------------------------------------------------------------------------//\n\n\n\n//------------------------------------------------------------------------------------------------//\n//------------------------------------------------------------------------------------------------//\n\n#endif /* BILINEARINTERPOLATION */\n", "meta": {"hexsha": "6bfac4af582304359ecf5408fa065ad51e4a5014", "size": 1671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "BiLinearInterpolation.hpp", "max_stars_repo_name": "skimnc/BiLinearInterpolation", "max_stars_repo_head_hexsha": "78c00980d3e7f3894ba27030e8019b8a9d04468d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-27T22:03:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-27T22:03:35.000Z", "max_issues_repo_path": "BiLinearInterpolation.hpp", "max_issues_repo_name": "skimnc/BiLinearInterpolation", "max_issues_repo_head_hexsha": "78c00980d3e7f3894ba27030e8019b8a9d04468d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BiLinearInterpolation.hpp", "max_forks_repo_name": "skimnc/BiLinearInterpolation", "max_forks_repo_head_hexsha": "78c00980d3e7f3894ba27030e8019b8a9d04468d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-22T08:57:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T08:57:15.000Z", "avg_line_length": 33.42, "max_line_length": 100, "alphanum_fraction": 0.4225014961, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6338688864973834}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 2020 by the deal.II authors\n *\n * This file is part of the deal.II library.\n *\n * The deal.II library is free software; you can use it, redistribute\n * it, and/or modify it under the terms of the GNU Lesser General\n * Public License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * The full text of the license can be found in the file LICENSE.md at\n * the top level directory of deal.II.\n *\n * ---------------------------------------------------------------------\n *\n * Authors: Wolfgang Bangerth, 1999,\n *          Guido Kanschat, 2011\n *          Luca Heltai, 2021\n */\n#include \"step-3.h\"\n\n#include <deal.II/base/function.h>\n#include <deal.II/base/quadrature_lib.h>\n\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/grid/grid_generator.h>\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_cg.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <fstream>\n#include <iostream>\n\nusing namespace dealii;\n\nStep3::Step3()\n  : ParameterAcceptor(\"Step3\")\n  , dof_handler(triangulation)\n{\n  add_parameter(\"Number of global refinements\", n_refinements);\n  add_parameter(\"Output filename\", output_name);\n  add_parameter(\"Finite element degree\", fe_degree);\n  add_parameter(\"Forcing term expression\", forcing_term_expression);\n  add_parameter(\"Boundary condition expression\", boundary_contition_expression);\n  add_parameter(\"Problem constants\", function_constants);\n  add_parameter(\"Grid generator function\", grid_generator_function);\n  add_parameter(\"Grid generator arguments\", grid_generator_arguments);\n}\n\n\n\nvoid\nStep3::make_grid(const std::string &params)\n{\n  ParameterAcceptor::initialize(params);\n  // GridGenerator::hyper_cube(triangulation, -1, 1);\n  // GridGenerator::hyper_L(triangulation);\n  GridGenerator::generate_from_name_and_arguments(triangulation,\n                                                  grid_generator_function,\n                                                  grid_generator_arguments);\n  // triangulation.begin_active()->face(0)->set_boundary_id(1);\n  // // for (auto &face : triangulation.active_face_iterators())\n  // //   if (((std::fabs(face->center()[0]) < 1e-12 &&\n  // //         std::fabs(face->center()[1] - 0.5) < 1e-12) ||\n  // //        (std::fabs(face->center()[1]) < 1e-12 &&\n  // //         std::fabs(face->center()[0] - 0.5) < 1e-12)))\n  //     face->set_boundary_id(1);\n  triangulation.refine_global(n_refinements);\n  std::cout << \"Number of active cells: \" << triangulation.n_active_cells()\n            << std::endl;\n}\n\n\n\nvoid\nStep3::setup_system()\n{\n  FE_Q<2> fe{fe_degree};\n  dof_handler.distribute_dofs(fe);\n  std::cout << \"Number of degrees of freedom: \" << dof_handler.n_dofs()\n            << std::endl;\n  DynamicSparsityPattern dsp(dof_handler.n_dofs());\n  DoFTools::make_sparsity_pattern(dof_handler, dsp);\n  sparsity_pattern.copy_from(dsp);\n  system_matrix.reinit(sparsity_pattern);\n  solution.reinit(dof_handler.n_dofs());\n  system_rhs.reinit(dof_handler.n_dofs());\n\n  forcing_term.initialize(\"x,y\", forcing_term_expression, function_constants);\n  boundary_condition.initialize(\"x,y\",\n                                boundary_contition_expression,\n                                function_constants);\n}\n\n\n\nvoid\nStep3::assemble_system()\n{\n  QGauss<2>          quadrature_formula(fe_degree + 1);\n  FEValues<2>        fe_values(dof_handler.get_fe(),\n                        quadrature_formula,\n                        update_values | update_gradients | update_JxW_values |\n                          update_quadrature_points);\n  const unsigned int dofs_per_cell = dof_handler.get_fe().n_dofs_per_cell();\n  FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell);\n  Vector<double>     cell_rhs(dofs_per_cell);\n  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n  for (const auto &cell : dof_handler.active_cell_iterators())\n    {\n      fe_values.reinit(cell);\n      cell_matrix = 0;\n      cell_rhs    = 0;\n      for (const unsigned int q_index : fe_values.quadrature_point_indices())\n        {\n          for (const unsigned int i : fe_values.dof_indices())\n            for (const unsigned int j : fe_values.dof_indices())\n              cell_matrix(i, j) +=\n                (fe_values.shape_grad(i, q_index) * // grad phi_i(x_q)\n                 fe_values.shape_grad(j, q_index) * // grad phi_j(x_q)\n                 fe_values.JxW(q_index));           // dx\n          for (const unsigned int i : fe_values.dof_indices())\n            cell_rhs(i) += (fe_values.shape_value(i, q_index) * // phi_i(x_q)\n                            forcing_term.value(\n                              fe_values.quadrature_point(q_index)) * // f(x_q)\n                            fe_values.JxW(q_index));                 // dx\n        }\n      cell->get_dof_indices(local_dof_indices);\n      for (const unsigned int i : fe_values.dof_indices())\n        for (const unsigned int j : fe_values.dof_indices())\n          system_matrix.add(local_dof_indices[i],\n                            local_dof_indices[j],\n                            cell_matrix(i, j));\n      for (const unsigned int i : fe_values.dof_indices())\n        system_rhs(local_dof_indices[i]) += cell_rhs(i);\n    }\n  std::map<types::global_dof_index, double> boundary_values;\n  // VectorTools::interpolate_boundary_values(dof_handler,\n  //                                          0,\n  //                                          Functions::ZeroFunction<2>(),\n  //                                          boundary_values);\n  VectorTools::interpolate_boundary_values(dof_handler,\n                                           0,\n                                           boundary_condition,\n                                           boundary_values);\n  MatrixTools::apply_boundary_values(boundary_values,\n                                     system_matrix,\n                                     solution,\n                                     system_rhs);\n}\n\n\n\nvoid\nStep3::solve()\n{\n  SolverControl            solver_control(1000, 1e-12);\n  SolverCG<Vector<double>> solver(solver_control);\n  solver.solve(system_matrix, solution, system_rhs, PreconditionIdentity());\n}\n\n\n\nvoid\nStep3::output_results() const\n{\n  DataOut<2> data_out;\n  data_out.attach_dof_handler(dof_handler);\n  data_out.add_data_vector(solution, \"solution\");\n  data_out.build_patches();\n  std::ofstream output(output_name);\n  data_out.write_vtk(output);\n}\n\n\n\nvoid\nStep3::run(const std::string &params)\n{\n  make_grid(params);\n  setup_system();\n  assemble_system();\n  solve();\n  output_results();\n}\n", "meta": {"hexsha": "a802842e22e51245c1f1cb420d7b82a5c722a5f0", "size": 6875, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/step-3.cc", "max_stars_repo_name": "dealii-courses/sissa-mhpc-lab-03-iprusak", "max_stars_repo_head_hexsha": "15be897b9cc2ee0850f23bb991a5cfd0c4459e74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/step-3.cc", "max_issues_repo_name": "dealii-courses/sissa-mhpc-lab-03-iprusak", "max_issues_repo_head_hexsha": "15be897b9cc2ee0850f23bb991a5cfd0c4459e74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/step-3.cc", "max_forks_repo_name": "dealii-courses/sissa-mhpc-lab-03-iprusak", "max_forks_repo_head_hexsha": "15be897b9cc2ee0850f23bb991a5cfd0c4459e74", "max_forks_repo_licenses": ["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.2564102564, "max_line_length": 80, "alphanum_fraction": 0.6136727273, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357563664174, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6338539378314026}}
{"text": "#pragma once\n\n#include <glad/glad.h>\n#include <bound.hpp>\n#include <Eigen/Dense>\n\nnamespace Config {\n\nnamespace Type {\n    using real = float;\n    using Point = Eigen::Matrix<real, 2, 1>;\n    using Vertex = Point;\n    using Color3f = Eigen::Vector3f;\n    using Color4f = Eigen::Vector4f;\n    using Bound2D = Bounds<real, 2>;\n\n    using SData = Eigen::Matrix3i;\n\n    template<int width, int height>\n    struct Size2D final {\n        static constexpr int width = width;\n        static constexpr int height = height;\n    };\n\n    template<int width, int height, int depth>\n    struct Size3D final {\n        static constexpr int width = width;\n        static constexpr int height = height;\n        static constexpr int depth = depth;\n    };\n\n    struct Offset2D final {\n        int x, y;\n        bool operator!=(Offset2D other) {\n            return x != other.x || y != other.y;\n        }\n    };\n\n} // namespace Type\n\n} // namespace Config\n", "meta": {"hexsha": "5ead8f33b4c9b4ecc8369621587d7b040b6205ae", "size": 935, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/config/type.hpp", "max_stars_repo_name": "Codesire-Deng/gsq", "max_stars_repo_head_hexsha": "841a296cbff700a102fbdc3cb76515fe4158e144", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/config/type.hpp", "max_issues_repo_name": "Codesire-Deng/gsq", "max_issues_repo_head_hexsha": "841a296cbff700a102fbdc3cb76515fe4158e144", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/config/type.hpp", "max_forks_repo_name": "Codesire-Deng/gsq", "max_forks_repo_head_hexsha": "841a296cbff700a102fbdc3cb76515fe4158e144", "max_forks_repo_licenses": ["Apache-2.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.2619047619, "max_line_length": 48, "alphanum_fraction": 0.6117647059, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6338539351489193}}
{"text": "#include \"SVD_pvfmm.hpp\"\n\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <vector>\n\n#include <Eigen/Dense>\n\n// Assume A=(m,n), m>n\n// U = (m,n), S = (n,n), VT = (n,n)\nvoid testSVD(const EMat &U, const EVec &Sdiag, const EMat &VT, const EMat &A, const EVec &x, const EVec &b) {\n    EMat S(U.cols(), VT.rows());\n    S = Sdiag.asDiagonal();\n\n    // step 1, test if USVT==A\n    EMat Arecon = U * (S * VT);\n    EMat Aerror = Arecon - A;\n    printf(\"Aerror max min %g, %g\\n\", Aerror.maxCoeff(), Aerror.minCoeff());\n\n    // step 2, test backward error\n    EVec Sdiaginv = Sdiag;\n    for (int i = 0; i < Sdiaginv.size(); i++) {\n        Sdiaginv[i] = Sdiaginv[i] < Sdiag[0] * eps ? 0 : 1.0 / Sdiaginv[i];\n    }\n\n    EMat V = VT.transpose();\n    for (int i = 0; i < Sdiaginv.size(); i++) {\n        V.col(i) *= Sdiaginv[i];\n    }\n\n    EVec x2 = V * (U.transpose() * b);\n    EVec b2 = A * x2;\n    EVec xerror = x2 - x;\n    EVec berror = b2 - b;\n    printf(\"xerror max min %g, %g\\n\", xerror.maxCoeff(), xerror.minCoeff());\n    printf(\"berror max min %g, %g\\n\", berror.maxCoeff(), berror.minCoeff());\n}\n\ninline double pot(const EVec3 &target, const EVec3 &source) {\n    EVec3 rst = target - source;\n    double rnorm = rst.norm();\n    return rnorm < eps ? 0 : 1 / rnorm;\n}\n\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n\n    const int pEquiv = atoi(argv[1]); // (8-1)^2*6 + 2 points\n    const int pCheck = atoi(argv[1]);\n    const double scaleEquiv = 1.05;\n    const double scaleCheck = 2.95;\n    const double pCenterEquiv[3] = {-(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2};\n    const double pCenterCheck[3] = {-(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2};\n\n    auto pointMEquiv = surface(pEquiv, (double *)&(pCenterEquiv[0]), scaleEquiv, 0);\n    auto pointMCheck = surface(pCheck, (double *)&(pCenterCheck[0]), scaleCheck, 0);\n\n    // Aup for solving MEquiv\n    const int equivN = pointMEquiv.size() / 3;\n    const int checkN = pointMCheck.size() / 3;\n    EMat Aup(checkN, equivN);\n    for (int k = 0; k < checkN; k++) {\n        EVec3 Cpoint(pointMCheck[3 * k], pointMCheck[3 * k + 1], pointMCheck[3 * k + 2]);\n        for (int l = 0; l < equivN; l++) {\n            const EVec3 Lpoint(pointMEquiv[3 * l], pointMEquiv[3 * l + 1], pointMEquiv[3 * l + 2]);\n            Aup(k, l) = pot(Cpoint, Lpoint);\n        }\n    }\n\n    EVec x(Aup.cols());\n    x.setRandom();\n    EVec b = Aup * x;\n\n    // jacobi svd\n    using std::cout;\n    using std::endl;\n\n    {\n        cout << \"JacobiSVD\" << endl;\n        Eigen::JacobiSVD<EMat> svd(Aup, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        EMat U = svd.matrixU();\n        EMat VT = svd.matrixV().transpose();\n        EVec Svec = svd.singularValues();\n        testSVD(U, Svec, VT, Aup, x, b);\n    }\n    // this triggers error #13212make -j: Reference to ebx in function requiring stack alignment\n    // {\n    //     cout << \"BDCSVD\" << endl;\n    //     Eigen::BDCSVD<EMat> svd(Aup, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    //     EMat U = svd.matrixU();\n    //     EMat VT = svd.matrixV().transpose();\n    //     EVec Svec = svd.singularValues();\n    //     testSVD(U, Svec, VT, Aup, x, b);\n    // }\n    {\n        cout << \"HouseholderQR\" << endl;\n        EVec x2 = Aup.colPivHouseholderQr().solve(b);\n        EVec b2 = Aup * x2;\n        EVec xerror = x2 - x;\n        EVec berror = b2 - b;\n        printf(\"xerror max min %g, %g\\n\", xerror.maxCoeff(), xerror.minCoeff());\n        printf(\"berror max min %g, %g\\n\", berror.maxCoeff(), berror.minCoeff());\n    }\n\n    return 0;\n}", "meta": {"hexsha": "c44e08246adc54c5243ab116c9a07e2afa8229a6", "size": 3602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2L/svd_test.cpp", "max_stars_repo_name": "benlandrum/STKFMM", "max_stars_repo_head_hexsha": "e562b7b1d5f8c9b63472ad568a3185e3e4612157", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-10-25T14:52:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T20:05:34.000Z", "max_issues_repo_path": "M2L/svd_test.cpp", "max_issues_repo_name": "benlandrum/STKFMM", "max_issues_repo_head_hexsha": "e562b7b1d5f8c9b63472ad568a3185e3e4612157", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-01-08T00:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T13:38:09.000Z", "max_forks_repo_path": "M2L/svd_test.cpp", "max_forks_repo_name": "benlandrum/STKFMM", "max_forks_repo_head_hexsha": "e562b7b1d5f8c9b63472ad568a3185e3e4612157", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-10-19T18:16:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:07:05.000Z", "avg_line_length": 33.3518518519, "max_line_length": 109, "alphanum_fraction": 0.56191005, "num_tokens": 1241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6338539302392765}}
{"text": "#include <iostream>\n#include <ctime>\n#include <sys/time.h>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <genecis/math/matrix.h>\n\nusing namespace std ;\nusing namespace genecis::math ;\n\nint main() {\n\n//\tmatrix<int> mt(3,3) ;\n//\tmt(0,0) = 1 ; mt(0,1) = 4 ; mt(0,2) = 7 ;\n//\tmt(1,0) = 0 ; mt(1,1) = 1 ; mt(1,2) = 0 ;\n//\tmt(2,0) = 0 ; mt(2,1) = 0 ; mt(2,2) = 1 ;\n//\tcout << \"mt: \" << mt << endl ;\n\n//\tsrand(time(NULL)) ;\n\tmatrix<double> mymatx(5,5) ;\n\tfor(unsigned i=0; i<mymatx.rows(); ++i) {\n\t\tfor(unsigned j=0; j<mymatx.cols(); ++j) {\n\t\t\tmymatx(i,j) = rand() % 15 ;\n\t\t\tmymatx(i,j) = (16+i*8 - j*2) % 7 ;\n\t\t}\n\t}\n//\tcout << \"mymatx: \" << mymatx << endl ;\n//\tmymatx.resize(2,2) ;\n//\tcout << \"resized:\" << mymatx << endl ;\n//\tfor(unsigned i=0; i<mymatx.rows(); ++i) {\n//\t\tmymatx(i,i) = 1 ;\n//\t}\n//\tmatrix<double> omatx(5,1) ;\n//\tfor(unsigned i=0; i<omatx.rows(); ++i) {\n//\t\tfor(unsigned j=0; j<omatx.cols(); ++j) {\n//\t\t\tomatx(i,j) = i+j ;\n//\t\t}\n//\t}\n\n//\tbool result = typeid(double) == typeid(int) ;\n//\tcout << \"double == int: \" ;\n//\tcout << ((result) ? \"true\" : \"false\") << endl ;\n\n//\tmymatx.transpose() ;\n//\tcout << \"transpose: \" << mymatx << endl ;\n//\tcout << \"omatx: \" << omatx << endl ;\n//\tomatx.transpose() ;\n//\tcout << \"transpose: \" << omatx << endl ;\n//\tomatx = mymatx ;\n//\tcout << \"reassign: \" << omatx << endl ;\n\n//\tmatrix<double> mtx ;\n//\tmtx.transpose() ;\n//\tcout << \"mtx: \" << mtx << endl ;\n//\tmtx *= omatx ;\n//\tcout << \"after *= mtx: \" << mtx << endl ;\n//\tomatx *= mymatx ;\n//\tcout << \"new omatx: \" << omatx << endl ;\n//\tmtx = &omatx ;\n\tmatrix<double> mtx(2,2) ;\n\tfor(unsigned i=0; i<mtx.rows(); ++i) {\n\t\tfor(unsigned j=0; j<mtx.cols(); ++j) {\n\t\t\tmtx(i,j) = i*900+j*100 ;\n\t\t}\n\t}\n//\tcout << \"mtx: \" << mtx << endl ;\n//\t(*mtx)(0,0) = 2 ;\n//\t(*mtx)^2 ;\n//\tcout << \"mtx^2: \" << *mtx << endl ;\n//\t\n\tmatrix<double> dmtx(2,2) ;\n\tfor(unsigned i=0; i<dmtx.rows(); ++i) {\n\t\tfor(unsigned j=0; j<dmtx.cols(); ++j) {\n\t\t\tdmtx(i,j) = i+j*0.0234+1 ;\n\t\t}\n\t}\n\tcout << \"dmtx: \" << dmtx << endl ;\n//\tdmtx.swap_row(0,1) ;\n//\tcout << \"dmtx after swap_row: \" << dmtx << endl ;\n//\tdmtx.swap_col(0,1) ;\n//\tcout << \"dmtx after swap_col: \" << dmtx << endl ;\n//\t\n//\tomatx = omatx + omatx ;\n//\tcout << \"+omatx: \" << omatx << endl ;\n//\tdmtx.inverse() ;\n\tdmtx.lu_decomp(mtx,mymatx) ;\n\tcout << \"dmtx decomp:\\nupper\" << mtx << endl ;\n\tcout << \"lower\" << mymatx << endl ;\n\tmatrix<double> lu = matrix_product(mymatx,mtx) ;\n\tcout << \"LU\" << lu << endl ;\n\tmatrix<double> t = mymatx * mtx ;\n\tcout << \"t: \" << t << endl ;\n\n//\tmatrix<double> omatx2 ;\n//\tomatx.transpose(omatx2) ;\n//\tcout << \"omatx2: \" << omatx2 << endl ;\n//\tcout << \"omatx: \" << omatx << endl ;\n\t\n//\tsrand(time(0)) ;\n//\tunsigned N = 10 ;\n//\tmatrix<double> m(N,N) ;\n//\tmatrix<double> m2(N,N) ;\n//\tboost::numeric::ublas::matrix<double> m3(N,N) ;\n//\tfor(unsigned i=0; i<N; ++i) {\n//\t\tfor(unsigned j=0; j<N; ++j) {\n//\t\t\tm(i,j) = rand() % 10 + 1 ;\n//\t\t\tm2(i,j) = rand() % 10 + 1 ;\n//\t\t\tm3(i,j) = rand() % 10 + 1 ;\n//\t\t}\n//\t}\n\t\n//\tcout << \"m: \" << m << endl ;\n//\tcout << \"m2: \" << m2 << endl ;\n//\tmatrix<double> m3 = m * m2 ;\n//\tcout << \"m3: \" << m3 << endl ;\n//\tif (true) {\n//\tmatrix<double> mn = m-m2 ;\n//\tcout << \"m-m2: \" << mn << endl ;\n//\tdelete mn ;\n//\t}\n//\tcout << \"m: \" << m << endl ;\n//\tcout << \"m2: \" << m2 << endl ;\n//\tmatrix<double> temp = 2.0 * m2 ;\n//\tcout << \"m2*2.0: \" << temp << endl ;\n//\tcout << \"Starting matrix multiply\" << endl ;\n//\tstruct timeval time ;\n//    struct timezone zone ;\n//    double start ;\n//    double complete ;\n//    double avg = 0 ;\n//    for(unsigned i=0; i<N; ++i) {\n//\t    gettimeofday( &time, &zone ) ;\n//    \tstart = time.tv_sec + time.tv_usec * 1e-6 ;\n//\t\ttemp = m2 * m2 ;\n//\t\tprod(m3, m3) ;\n//\t\tm2 *= 4.0 ;\n//\t\tgettimeofday( &time, &zone ) ;\n//    \tcomplete = time.tv_sec + time.tv_usec * 1e-6 ;\n//    \tavg += (complete-start) ;\n//    \tcout << \"matrix.h Complete...time: \" << (complete-start) << endl ;\n//    }\n//    cout << \"Average execute time: \" << avg/N << endl ;\n//    cout << \"temp: \" << temp << endl ;\n//    gettimeofday( &time, &zone ) ;\n//    start = time.tv_sec + time.tv_usec * 1e-6 ;\n//\tgettimeofday( &time, &zone ) ;\n//    complete = time.tv_sec + time.tv_usec * 1e-6 ;\n//    cout << \"Ublas Complete...time: \" << (complete-start) << endl ;\n\n}\n", "meta": {"hexsha": "fc4eab4c3c570bc8f9d828b3c4e38136203ac2c6", "size": 4277, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix_test.cc", "max_stars_repo_name": "Tibonium/genecis", "max_stars_repo_head_hexsha": "4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc", "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/matrix_test.cc", "max_issues_repo_name": "Tibonium/genecis", "max_issues_repo_head_hexsha": "4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc", "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/matrix_test.cc", "max_forks_repo_name": "Tibonium/genecis", "max_forks_repo_head_hexsha": "4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3245033113, "max_line_length": 73, "alphanum_fraction": 0.5064297405, "num_tokens": 1614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021706, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6338539301823612}}
{"text": "#include <fstream>\n#include <mlpack/methods/kmeans/kmeans.hpp>\n#include <armadillo>\n\n//g++ k_means.cpp -o kmeans_test -O3 -std=c++11 -larmadillo -lmlpack -lboost_serialization && ./kmeans_test \n\nint main() {\n\n    int k = 2; \n    int dim = 2; \n    int samples = 50;\n    int max_iter = 10;\n     \n    arma::mat data(dim, samples, arma::fill::zeros);\n\n    // create data\n    int i = 0;\n    for(; i < samples / 2; ++i)\n    {\n        data.col(i) = arma::vec({1, 1}) + 0.25*arma::randn<arma::vec>(dim);\n    }\n    for(; i < samples; ++i)\n    {\n        data.col(i) = arma::vec({2, 3}) + 0.25*arma::randn<arma::vec>(dim);\n    }\n\n\n    //cluster the data\n    arma::Row<size_t> clusters;\n    arma::mat centroids;\n\n    mlpack::kmeans::KMeans<> mlpack_kmeans(max_iter);\n\n    mlpack_kmeans.Cluster(data, k, clusters, centroids);\n\n\n    centroids.print(\"Centroids:\");\n\n\n    return 0;\n}", "meta": {"hexsha": "466b24d49070c57207aa90be68fb8f33d8189d26", "size": 867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Section3/k_means.cpp", "max_stars_repo_name": "PacktPublishing/Introduction-to-Machine-Learning-C-Libraries", "max_stars_repo_head_hexsha": "6b0a5978c72ea6d13492bb53d8107c408fda1902", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-03-24T12:08:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:12:12.000Z", "max_issues_repo_path": "Section3/k_means.cpp", "max_issues_repo_name": "PacktPublishing/Introduction-to-Machine-Learning-C-Libraries", "max_issues_repo_head_hexsha": "6b0a5978c72ea6d13492bb53d8107c408fda1902", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Section3/k_means.cpp", "max_forks_repo_name": "PacktPublishing/Introduction-to-Machine-Learning-C-Libraries", "max_forks_repo_head_hexsha": "6b0a5978c72ea6d13492bb53d8107c408fda1902", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-10-27T03:04:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-27T05:05:59.000Z", "avg_line_length": 21.1463414634, "max_line_length": 108, "alphanum_fraction": 0.5790080738, "num_tokens": 285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6338539252158023}}
{"text": "/*  \n*  Copyright August 2015\n*  Author: Olalekan P. Ogunmolu\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n*  you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n*      http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* \n* See the License for the specific language governing permissions and\n* limitations under the License.\n* \n*/\n\n// Include Files\n#include \"savgol.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include <queue>\n\nusing namespace Eigen;\nusing namespace std;\n\n/*Compute the polynomial basis vectors s_0, s_1, s_2 ... s_n using the vandermonde matrix.*/\nMatrixXi vander(const int F)\n{\n  auto v = VectorXi::LinSpaced(F,(-(F-1)/2),((F-1)/2)).transpose().eval();\n\n  MatrixXi A(F, F+1);     //We basically compute an F X F+1 matrix;\n\n  for(auto i = 0; i < F; ++ i)\n  {\n    for(auto j=1; j < F+1; ++j)\n    {\n      A(i,j) = pow(v(i), (j-1) ); \n    }\n  }\n\n  A = A.block(0, 1, F, F );   //and retrieve the right F X F matrix block, excluding the first column block to find the vandermonde matrix.\n\n  return A;\n}\n\n/*brief Compute the S-Golay Matrix of differentiators\n*\n*/\nMatrixXf sgdiff(int k, int F, double Fd)\n{\n  //We set the weighting matrix to an identity matrix if no weighting matrix is supplied\n  auto W = MatrixXf::Identity(Fd, Fd);      \n\n  //Compute Projection Matrix B\n  auto s = vander(F);   \n\n  //Retrieve the rank deficient matrix from the projection matrix\n  auto S = s.block(0, 0, s.rows(), (k+1) ) ; \n\n  //Compute sqrt(W)*S\n  auto Sd = S.cast<float> ();    //cast S to float\n  auto inter = W * Sd;              //W is assumed to be identity. Change this if you have reasons to.\n\n  //Compute the QR Decomposition\n  HouseholderQR<MatrixXf> qr(inter);\n  qr.compute(inter);\n\n  FullPivLU<MatrixXf>lu_decomp(inter);      //retrieve rank of matrix\n  \n  auto Rank = lu_decomp.rank() ;\n   \n  //For rank deficient matrices. The S matrix block will always be rank deficient.        \n  // MatrixXf Q = qr.householderQ();  //unsused\n  MatrixXf R = qr.matrixQR().topLeftCorner(Rank, Rank).template triangularView<Upper>();\n\n  //Compute Matrix of Differentiators\n  auto Rinv = R.inverse();\n  MatrixXf RinvT = Rinv.transpose();\n\n  MatrixXf G = Sd * Rinv * RinvT;           /*G = S(S'S)^(-1)   -- eqn 8.3.90 (matrix of differentiation filters)*/\n \n  MatrixXf SdT = Sd.transpose().eval();\n\n  MatrixXf B = G * SdT * W;   //SG-Smoothing filters of length F and polynomial order k\n\n  return B;\n}\n\ntemplate<typename T>\nRowVectorXf savgolfilt(std::queue<T> const & x, int k, int F)\n{  \n  auto DIM = Matrix4f::Zero();        //initialize DIM as a matrix of zeros if it is not supplied\n  auto siz = x.size();       //Reshape depth values by working along the first non-singleton dimension\n\n  //Find leading singleton dimensions\n  auto Fd = static_cast<double>(F);        //sets the frame size for the savgol differentiation coefficients. This must be odd\n\n  auto B = sgdiff(k, F, Fd);       //retrieve matrix B\n\n  /*Transient On*/\n  auto id_size = (F+1)/2 - 1;\n  auto Bbutt = B.bottomLeftCorner((F-1)/2, B.cols());\n\n  auto n = Bbutt.rows();\n  //flip Bbutt from top all the way down \n  MatrixXf Bbuttflipped(n, Bbutt.cols());\n \n    for(auto j = n - 1; j >= 0;)\n    { \n      for(auto i = 0; i < n ; ++i)\n      {        \n        Bbuttflipped.row(i) = Bbutt.row(j);\n        j--;\n      }\n    }\n    \n  //flip x_on up and down as above\n  VectorXf x_onflipped(x.size(), 1);  //pre-allocate\n  x_onflipped.transpose().eval();     \n\n  auto m = x.size();                          //retrieve total # coefficients\n\n    for(auto j = m -1; j >=0;)\n    {\n      for(auto i = 0; i < m; ++i)\n      {\n        x_onflipped.row(i) = x.row(j);\n        j--;\n      }\n    }\n  \n  VectorXf y_on = Bbuttflipped * x_onflipped;  //Now compute the transient on\n\n /*Compute the steady state output*/\n  size_t idzeroth = floor(B.cols()/2);\n  auto Bzeroth = B.col(idzeroth);\n  auto Bzerothf = Bzeroth.cast<float>();\n\n  auto y_ss = Bzerothf.transpose().eval() * x;     //This is the steady-state smoothed value\n\n  /*Compute the transient off for non-sequential data*/\n  auto Boff = B.topLeftCorner((F-1)/2, B.cols());\n\n  auto p = Boff.rows();                        //flip Boff along the horizontal axis\n\n  MatrixXf Boff_flipped(p, Boff.cols());\n    \n  for(auto j = p - 1; j >= 0;)\n  { \n    for(auto i = 0; i < p ; ++i)\n    {        \n      Boff_flipped.row(i) = Boff.row(j);\n      j--;\n    }\n  }\n\n/*x_off will be the last (F-1) x-values. Note, if you are smoothing in real time, you need to find \n  a way to let your compiler pick the last F-length samples from your data in order to compute your x_off. \n  You could have the program wait for x_milliseconds before you pick \n  the transient off, for example*/\n  auto x_off = VectorXf::LinSpaced(F, x(0), x(F-1)).transpose();  \n  VectorXf x_offflipped(x_off.rows(), x_off.cols());      //pre-allocate    \n  //flip x_off along the horizontal axis\n    auto q = x_off.size();                          //retrieve total # coefficients\n\n    for(auto j = q -1; j >=0;)\n    {\n      for(auto i = 0; i < q; ++i)\n      {\n        x_offflipped.row(i) = x.row(j);\n        j--;\n      }\n    }\n  auto y_off = Boff_flipped * x_offflipped;   //This is the transient off\n\n  /*Make Y into the shape of X and return the smoothed values!*/\n  RowVectorXf y(F);\n  y << y_off.transpose().eval(), y_ss, y_on.transpose().eval();\n\n  return y;\n}\n\n\n", "meta": {"hexsha": "5e014cbbf1638bd4d28ba885bc0dec5f8e75079d", "size": 5660, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "ensenso/src/savgol.cxx", "max_stars_repo_name": "lakehanne/ensenso", "max_stars_repo_head_hexsha": "10d3cbec97441a2eb2c8335be27764e8a82549cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-04-25T20:32:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T09:16:04.000Z", "max_issues_repo_path": "ensenso/src/savgol.cxx", "max_issues_repo_name": "lakehanne/ensenso", "max_issues_repo_head_hexsha": "10d3cbec97441a2eb2c8335be27764e8a82549cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-06-28T21:31:25.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-07T23:44:37.000Z", "max_forks_repo_path": "ensenso/src/savgol.cxx", "max_forks_repo_name": "lakehanne/ensenso", "max_forks_repo_head_hexsha": "10d3cbec97441a2eb2c8335be27764e8a82549cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-04-25T20:32:30.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-19T22:31:36.000Z", "avg_line_length": 29.7894736842, "max_line_length": 139, "alphanum_fraction": 0.6243816254, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6338326504269163}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string> \n#include <Eigen/Dense>\n\n#include \"DataMnist.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nDataMnist::DataMnist(std::string data_path)\n{\n    //Initialize DataMnist loader according to directory passed as argument\n\t_path = data_path;\n    //Initialize default file names\n\tinitFileNames();\n    //Initialize sizes of arrays according to MNIST specifications\n\tinitSizes();\n}\n\n\nDataMnist::~DataMnist(void)\n{\n}\n\nint DataMnist::initSizes()\n{\n\t_xtest.resize(test_size);\n\t_xtrain.resize(train_size);\n\t_ytest.resize(test_size);\n\t_ytrain.resize(train_size);\n\tfor (int i = 0; i<test_size; ++i)\n\t{\n\t\t_xtest[i].resize(flat_image_size);\n\t}\n\tfor (int i = 0; i<train_size; ++i)\n\t{\n\t\t_xtrain[i].resize(flat_image_size);\n\t}\n\treturn 0;\n}\n\n\nint DataMnist::initFileNames()\n{\n\t_images_file_names.push_back(\"train-images.idx3-ubyte\");\n\t_images_file_names.push_back(\"t10k-images.idx3-ubyte\");\n\t_labels_file_names.push_back(\"train-labels.idx1-ubyte\");\n\t_labels_file_names.push_back(\"t10k-labels.idx1-ubyte\");\n\treturn 0;\n}\n\n\n//This method is a bit long, but we did not had a choice : \n//We have to unpack the file in one shot\n//as we cannot have access to a precise point in the file.\n\n//beg = 0 ou 1 \n//if beg = 0, loads xtrain and xtest\n//if beg = 1, loads only xtest\n//Once it is run on an element of the class Data,\n//This element has _xtrain and _xtest as attributes (if beg=0)\n//Else it only has _xtest\nint DataMnist::loadImages(int beg)\n{\n\t//Test to verify if the users has given a right value\n\t//If not, default to 1\n\tif (beg != 0 && beg != 1) \n\t{\n\t\tbeg = 1; \n\t}\n\n\t//If beg == 1, this loop only has one iteration\n\t//As we only load one file (the test one)\n\tfor (int k = beg; k < 2; ++k)\n\t{\n\t\t//The ios::binary parameters is very important here \n\t\t//(without it the data we get is all zeros)\n\n\t\t\n\t\tifstream file ( (_path + _images_file_names[k]).c_str(), ios::binary);\n\n\t\t//test to be sure that the file is open\n\t\tif (!file.is_open())\n\t\t{\n\t\t\tcerr << \"Could not open file\" << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\t\n\t\t//We initialize variables to unload the header variables of the MNIST database\n\t\t//magic_number is useless, but we need to unload it to keep going in the data (cf next commentary) \n\t\tint magic_number = 0;\n\t\tint number_of_images = 0;\n\t\tint number_of_rows = 0;\n\t\tint number_of_cols = 0;\n\n\t\t//The method fstream::read() takes two parameters : \n\t\t//\t\t- a pointer to an array of char where the characters are stored \n\t\t//      (thus we cast &magic_number as a char* for instance)\n\t\t//\t\t- the number of character it should extract\n\t\t//The method fstream::read() works serially : \n\t\t//Once we call it on a file, the next time we will call it on that same file\n\t\t//it will continue unloading the data at the point it stopped the previous time\n\t\t//Thus we unload the first elements of the database even though they won't be useful\n\t\tfile.read((char*)&magic_number,sizeof(magic_number)); \n\t\tfile.read((char*)&number_of_images,sizeof(number_of_images));\n\t\tfile.read((char*)&number_of_rows,sizeof(number_of_rows));\n\t\tfile.read((char*)&number_of_cols,sizeof(number_of_cols));\n\t\t\n\t\t//Storing the data into class attributes for train images\n\t\tif (k == 0 )\n\t\t{\n\t\t\tfor (int i = 0; i < train_size; ++i)\n\t\t\t{\n\t\t\t\tint count = 0;\n\t\t\t\tfor(int r = 0; r < image_size; ++r)\n\t\t\t\t{\n\t\t\t\t\tfor(int c = 0; c < image_size; ++c)\n\t\t\t\t\t{\n\t\t\t\t\t\t//In the structure of the MNIST database,\n\t\t\t\t\t\t//pixels are unsigned bytes which can be interpreted as numbers\n\t\t\t\t\t\t//describing the nuance of black of the pixel.\n\t\t\t\t\t\t//As the file.read method needs a pointer to a character\n\t\t\t\t\t\t//to store the data, we create an unsigned char (value between 0 and 255) \n\t\t\t\t\t\t//instead of a char (value between -127 and 128)\n\t\t\t\t\t\t//It is more practical since we want our pixel coloration to take positive value\n\t\t\t\t\t\tunsigned char pix = 0;\n\t\t\t\t\t\tfile.read((char*)&pix,sizeof(pix));\n\t\t\t\t\t\t_xtrain[i](count)= (double) pix / 255.;\n\t\t\t\t\t\t++ count;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//Storing the data for test images\n\t\telse\n\t\t{\n\t\t\tfor (int i = 0; i < test_size; ++i)\n\t\t\t{\n\t\t\t\tint count = 0;\n\t\t\t\tfor(int r = 0; r < image_size; ++r)\n\t\t\t\t{\n\t\t\t\t\tfor(int c = 0; c < image_size; ++c)\n\t\t\t\t\t{\n\t\t\t\t\t\t//In the structure of the MNIST database,\n\t\t\t\t\t\t//pixels are unsigned bytes which can be interpreted as numbers\n\t\t\t\t\t\t//describing the nuance of black of the pixel.\n\t\t\t\t\t\t//As the file.read method needs a pointer to a character\n\t\t\t\t\t\t//to store the data, we create an unsigned char (value between 0 and 255) \n\t\t\t\t\t\t//instead of a char (value between -127 and 128)\n\t\t\t\t\t\t//it does not matter since they both correspond to a byte memorywise\n\t\t\t\t\t\tunsigned char pix = 0;\n\t\t\t\t\t\tfile.read((char*)&pix,sizeof(pix));\n\t\t\t\t\t\t_xtest[i](count)= (double) pix / 255.;\n\t\t\t\t\t\t++ count;\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << \"Images loaded successfully\" << endl;\n\t}\n\treturn 0;\n}\n\n\n//Same principle as Data::loadImages with labels\nint DataMnist :: loadLabels(int beg)\n{\n\t//Test to verify if the users has given a right value\n\t//If not, default to 1\n\tif (beg !=0 && beg !=1) \n\t{\n\t\tbeg = 1; \n\t}\n\n\t//If beg == 1, this loop only has one iteration\n\t//As we only load one file\n\tfor (int k = beg; k < 2; ++k)\n\t{\n\t\tifstream file ( (_path + _labels_file_names[k]).c_str(), ios::binary);\n\n\t//test to be sure that the file is open\n\t\tif (!file.is_open())\n\t\t{\n\t\t\tcerr << \"Could not open file\" << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\t//We initialize variables to unload the header variables of the MNIST database\n\t\t//magic_number is useless, but we need to unload it to keep going in the data (cf next commentary) \n\t\tint magic_number = 0;\n\t\tint number_of_items = 0;\n\n\t\tfile.read((char*)&magic_number,sizeof(magic_number)); \n\t\tfile.read((char*)&number_of_items,sizeof(number_of_items));\n\n\t\t//Storing the data\n\t\tif (k==0)\n\t\t{\n\t\t\tfor (int i = 0; i < train_size ; ++i)\n\t\t\t{\n\t\t\t\tunsigned char temporary = 0;\n\t\t\t\tfile.read((char*)&temporary,sizeof(temporary));\n\t\t\t\t_ytrain[i]=temporary;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int i = 0; i < test_size ; ++i)\n\t\t\t{\n\t\t\t\tunsigned char temporary = 0;\n\t\t\t\tfile.read((char*)&temporary,sizeof(temporary));\n\t\t\t\t_ytest[i]=temporary;\n\t\t\t}\n\t\t}\n\t\tcout << \"Labels loaded successfully\" << endl;\n\n\t}\n\treturn 0;\n}\n\n//Accessors\nint DataMnist::trainLabel (int i)\n{\n\treturn _ytrain[i];\n}\n\nint DataMnist::testLabel (int i)\n{\n\treturn _ytest[i];\n}\n\n\nEigen::VectorXd DataMnist::trainImage (int i)\n{\n\treturn _xtrain[i];\n}\n\nEigen::VectorXd DataMnist::testImage (int i)\n{\n\treturn _xtest[i];\n}\n\nvector<VectorXd> DataMnist::GetTrainImages()\n{\n    return _xtrain;\n}\n\nvector<int> DataMnist::GetTrainLabels()\n{\n    return _ytrain;\n}\n", "meta": {"hexsha": "9756f8e2e20d32e0f2058148b72b6964b613e3ff", "size": 6575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DataMnist.cpp", "max_stars_repo_name": "pminder/NeuralNetworks", "max_stars_repo_head_hexsha": "586e244f9d234002d811c362a2bd64df11f7aee3", "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": "DataMnist.cpp", "max_issues_repo_name": "pminder/NeuralNetworks", "max_issues_repo_head_hexsha": "586e244f9d234002d811c362a2bd64df11f7aee3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-01-16T21:32:57.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-04T13:05:41.000Z", "max_forks_repo_path": "DataMnist.cpp", "max_forks_repo_name": "pminder/NeuralNetworks", "max_forks_repo_head_hexsha": "586e244f9d234002d811c362a2bd64df11f7aee3", "max_forks_repo_licenses": ["Apache-2.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.5836575875, "max_line_length": 101, "alphanum_fraction": 0.6619011407, "num_tokens": 1936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.633832647846427}}
{"text": "#define BOOST_TEST_MODULE matrix\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/matrix/all.h++>\n#include <mla/matrix/convert.h++>\n\n\ntypedef boost::mpl::list<\n\tmla::matrix::DenseRowMajor<float>,\n\tmla::matrix::DenseRowMajor<double>,\n\tmla::matrix::SparseDOK<float>,\n\tmla::matrix::SparseDOK<double>,\n\tmla::matrix::SparseCOO<float>,\n\tmla::matrix::SparseCOO<double>,\n\tmla::matrix::SparseCRS<float>,\n\tmla::matrix::SparseCRS<double>,\n\tmla::matrix::SparseCCS<float>,\n\tmla::matrix::SparseCCS<double>\n> matrix_type_list;\n\n\nBOOST_AUTO_TEST_SUITE(test_matrix)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( matrix_convert, MatrixTypeTo, matrix_type_list )\n{\n\tsize_t matrix_size = 6;\n\n\tmla::matrix::DenseRowMajor<float> from(matrix_size, matrix_size);\n\n\tfrom(0,0) = (typename MatrixTypeTo::scalar_type)1;\n\tfrom(0,3) = (typename MatrixTypeTo::scalar_type)3;\n\tfrom(3,0) = (typename MatrixTypeTo::scalar_type)3;\n\tfrom(2,3) = (typename MatrixTypeTo::scalar_type)5;\n\n\tMatrixTypeTo to(matrix_size, matrix_size);\n\n\n\tmla::matrix::convert(from, to);\n\n\tBOOST_CHECK_EQUAL(from.rows(), to.rows());\n\tBOOST_CHECK_EQUAL(from.columns(), to.columns());\n\n\tfor(size_t i = 0; i < matrix_size; i++)\n\t{\n\t\tfor(size_t j = 0; i < matrix_size; i++)\n\t\t{\n\t\t\tBOOST_CHECK_CLOSE( from.getValue(i, j), to.getValue(i,j), 0.001f );\n\t\t}\n\t}\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "912dfd18ecf2683df2dc06f1d96eec3cfb77d15e", "size": 1390, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_matrix_convert.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/test_matrix_convert.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/test_matrix_convert.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5593220339, "max_line_length": 79, "alphanum_fraction": 0.7273381295, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6338326452659374}}
{"text": "/*\r\n * gauss_packet.cpp\r\n *\r\n * Schroedinger equation with potential barrier and periodic boundary conditions\r\n * Initial Gauss packet moving to the right\r\n *\r\n * pipe output into gnuplot to see animation\r\n *\r\n * Implementation of Hamilton operator via MTL library\r\n *\r\n * Copyright 2011-2013 Mario Mulansky\r\n * Copyright 2011-2012 Karsten Ahnert\r\n *\r\n * Distributed under the Boost Software License, Version 1.0.\r\n * (See accompanying file LICENSE_1_0.txt or\r\n * copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n\r\n#include <iostream>\r\n#include <complex>\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n#include <boost/numeric/odeint/external/mtl4/mtl4.hpp>\r\n\r\n#include <boost/numeric/mtl/mtl.hpp>\r\n\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\ntypedef mtl::dense_vector< complex< double > > state_type;\r\n\r\nstruct hamiltonian {\r\n\r\n    typedef mtl::compressed2D< complex< double > > matrix_type;\r\n    matrix_type m_H;\r\n\r\n    hamiltonian( const int N ) : m_H( N , N )\r\n    {\r\n        // constructor with zero potential\r\n        m_H = 0.0;\r\n        initialize_kinetic_term();\r\n    }\r\n\r\n    //template< mtl::compressed2D< double > >\r\n    hamiltonian( mtl::compressed2D< double > &V ) : m_H( num_rows( V ) , num_cols( V ) )\r\n    {\r\n        // use potential V in hamiltonian\r\n        m_H = complex<double>( 0.0 , -1.0 ) * V;\r\n        initialize_kinetic_term();\r\n    }\r\n\r\n    void initialize_kinetic_term( )\r\n    {\r\n        const int N = num_rows( m_H );\r\n        mtl::matrix::inserter< matrix_type , mtl::update_plus< complex<double> > > ins( m_H );\r\n        const double z = 1.0;\r\n        // fill diagonal and upper and lower diagonal\r\n        for( int i = 0 ; i<N ; ++i )\r\n        {\r\n            ins[ i ][ (i+1) % N ] << complex< double >( 0.0 , -z );\r\n            ins[ i ][ i ] << complex< double >( 0.0 , z );\r\n            ins[ (i+1) % N ][ i ] << complex< double >( 0.0 , -z );\r\n        }\r\n    }\r\n\r\n    void operator()( const state_type &psi , state_type &dpsidt , const double t )\r\n    {\r\n        dpsidt = m_H * psi;\r\n    }\r\n\r\n};\r\n\r\nstruct write_for_gnuplot\r\n{\r\n    size_t m_every , m_count;\r\n\r\n    write_for_gnuplot( size_t every = 10 )\r\n    : m_every( every ) , m_count( 0 ) { }\r\n\r\n    void operator()( const state_type &x , double t )\r\n    {\r\n        if( ( m_count % m_every ) == 0 )\r\n        {\r\n            //clog << t << endl;\r\n            cout << \"p [0:\" << mtl::size(x) << \"][0:0.02] '-'\" << endl;\r\n            for( size_t i=0 ; i<mtl::size(x) ; ++i )\r\n            {\r\n                cout << i << \"\\t\" << norm(x[i]) << \"\\n\";\r\n            }\r\n            cout << \"e\" << endl;\r\n        }\r\n\r\n        ++m_count;\r\n    }\r\n};\r\n\r\nstatic const int N = 1024;\r\nstatic const int N0 = 256;\r\nstatic const double sigma0 = 20;\r\nstatic const double k0 = -1.0;\r\n\r\nint main( int argc , char** argv )\r\n{\r\n    state_type x( N , 0.0 );\r\n\r\n    // initialize gauss packet with nonzero velocity\r\n    for( int i=0 ; i<N ; ++i )\r\n    {\r\n        x[i] = exp( -(i-N0)*(i-N0) / ( 4.0*sigma0*sigma0 ) ) * exp( complex< double >( 0.0 , k0*i ) );\r\n        //x[i] += 2.0*exp( -(i+N0-N)*(i+N0-N) / ( 4.0*sigma0*sigma0 ) ) * exp( complex< double >( 0.0 , -k0*i ) );\r\n    }\r\n    x /= mtl::two_norm( x );\r\n\r\n    typedef runge_kutta4< state_type > stepper;\r\n\r\n    // create potential barrier\r\n    mtl::compressed2D< double > V( N , N );\r\n    V = 0.0;\r\n    {\r\n        mtl::matrix::inserter< mtl::compressed2D< double > > ins( V );\r\n        for( int i=0 ; i<N ; ++i )\r\n        {\r\n            //ins[i][i] << 1E-4*(i-N/2)*(i-N/2);\r\n\r\n            if( i < N/2 )\r\n                ins[ i ][ i ] << 0.0 ;\r\n            else\r\n                ins[ i ][ i ] << 1.0 ;\r\n\r\n        }\r\n    }\r\n\r\n    // perform integration, output can be piped to gnuplot\r\n    integrate_const( stepper() , hamiltonian( V ) , x , 0.0 , 1000.0 , 0.1 , write_for_gnuplot( 10 ) );\r\n\r\n    clog << \"Norm: \" << mtl::two_norm( x ) << endl;\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "6ac46f93b27e3598c85f75cad2fb0528556a1a4b", "size": 3903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/mtl/gauss_packet.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/mtl/gauss_packet.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/mtl/gauss_packet.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 27.485915493, "max_line_length": 115, "alphanum_fraction": 0.5211375865, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6338326401049585}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdLogFallingFactorial, Fvar) {\n  using boost::math::digamma;\n  using stan::math::fvar;\n  using stan::math::log_falling_factorial;\n\n  fvar<double> a(4.0, 1.0);\n  fvar<double> x = log_falling_factorial(a, 2);\n  EXPECT_FLOAT_EQ(std::log(12.0), x.val_);\n  EXPECT_FLOAT_EQ((boost::math::digamma(5) - boost::math::digamma(3)), x.d_);\n\n  // finite diff\n  double eps = 1e-6;\n  EXPECT_FLOAT_EQ((stan::math::log_falling_factorial(4.0 + eps, 2.0)\n                   - stan::math::log_falling_factorial(4.0 - eps, 2.0))\n                      / (2 * eps),\n                  x.d_);\n\n  fvar<double> c(-3.0, 2.0);\n\n  EXPECT_THROW(log_falling_factorial(c, 2), std::domain_error);\n  EXPECT_THROW(log_falling_factorial(c, c), std::domain_error);\n\n  x = log_falling_factorial(a, a);\n  EXPECT_FLOAT_EQ(std::log(24.0), x.val_);\n  EXPECT_FLOAT_EQ(boost::math::digamma(5), x.d_);\n\n  x = log_falling_factorial(5, a);\n  EXPECT_FLOAT_EQ(std::log(120.0), x.val_);\n  EXPECT_FLOAT_EQ(digamma(2.0), x.d_);\n\n  // finite diff\n  EXPECT_FLOAT_EQ((stan::math::log_falling_factorial(5.0, 4.0 + eps)\n                   - stan::math::log_falling_factorial(5.0, 4.0 - eps))\n                      / (2 * eps),\n                  x.d_);\n}\n\nTEST(AgradFwdLogFallingFactorial, FvarFvarDouble) {\n  using stan::math::fvar;\n  using stan::math::log_falling_factorial;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 4.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 3.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = log_falling_factorial(x, y);\n\n  EXPECT_FLOAT_EQ(3.1780539, a.val_.val_);\n  EXPECT_FLOAT_EQ(1.0833334, a.val_.d_);\n  EXPECT_FLOAT_EQ(0.42278433, a.d_.val_);\n  EXPECT_FLOAT_EQ(0.64493406, a.d_.d_);\n}\n\nstruct log_falling_factorial_fun {\n  template <typename T0, typename T1>\n  inline typename boost::math::tools::promote_args<T0, T1>::type operator()(\n      const T0 arg1, const T1 arg2) const {\n    return log_falling_factorial(arg1, arg2);\n  }\n};\n\nTEST(AgradFwdLogFallingFactorial, nan_0) {\n  log_falling_factorial_fun log_falling_factorial_;\n  test_nan_fwd(log_falling_factorial_, 3.0, 5.0, false);\n}\n", "meta": {"hexsha": "37111ab0795a55cdd44afc4bca0c057fd539f9dd", "size": 2243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/fwd/scal/fun/log_falling_factorial_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/fwd/scal/fun/log_falling_factorial_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/fwd/scal/fun/log_falling_factorial_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9066666667, "max_line_length": 77, "alphanum_fraction": 0.6633972358, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6338326401049585}}
{"text": "/*\n * poisson test.\n *\n * Takaaki MINOMO.\n */\n\n#include <iostream>\n#include <cmath>\n#include <array>\n#include <Eigen/Sparse>\n\nconstexpr int N = 10;\n/*\nnamespace rittai3d{\n\tnamespace utility{\n\t\t// [ minimum, maximum ) \u306e\u7bc4\u56f2\u3067\u30e9\u30c3\u30d7\u30a2\u30e9\u30a6\u30f3\u30c9\n\t\ttemplate <typename T>\n\t\tconstexpr T wrap_around(T value, T minimum, T maximum){\n\t\t\tconst T n = (value - minimum) % (maximum - minimum);\n\t\t\treturn n >= 0 ? (n + minimum) : (n + maximum); \n\t\t}\n\t}\n}\n\nnamespace sksat {\n\ttemplate<std::size_t Num, typename T = double>\n\tclass array_wrapper{\n\tprivate:\n\t\tstd::array<T, Num> arr;\n\tpublic:\n\t\tconstexpr array_wrapper() : arr() {}\n\t\t~array_wrapper() = default;\n\n\t\tT& operator[](int i){\n\t\t\ti = rittai3d::utility::wrap_around(i, 0, static_cast<int>(Num));\n\t\t\treturn arr[i];\n\t\t}\n\t};\n}\n\nusing extendedArray = sksat::array_wrapper<N + 1, sksat::array_wrapper<N + 1>>;\n*/\nint main(){\n\n    Eigen::SparseMatrix<double> A(N, N);\n    Eigen::VectorXd b(N), x(N);\n    \n    for(int i=0; i<N; ++i){\n        b(i) = 0.0;\n    }\n\n    b(0)   = 0.0;\n    b(N-1) = - 1.0;\n\n    for(int i=0; i<N; ++i){\n        for(int j=0; j<N; ++j){\n            if(i == j){\n                A.insert(i,j) = - 2.0;\n            }else if(i == (j+1) || i == (j-1)){\n                A.insert(i,j) = 1.0;\n            }else{\n                A.insert(i,j) = 0.0;\n            }\n        }\n    }\n    \n    std::cout << A << std::endl;\n    std::cout << std::endl;\n    std::cout << b << std::endl;\n    std::cout << std::endl;\n    Eigen::ConjugateGradient<Eigen::SparseMatrix<double> > cg;\n    cg.compute(A);\n    x = cg.solve(b);\n\n    std::cout << x << std::endl;\n\n}\n", "meta": {"hexsha": "af8389484d1725112d7cd8ec775b76962e91d11a", "size": 1582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kazakami003/test/poisson.cpp", "max_stars_repo_name": "mino2357/2dimPDE", "max_stars_repo_head_hexsha": "448287de056ccbf630503e8949627827d2c81d41", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-11-07T03:15:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T11:50:51.000Z", "max_issues_repo_path": "kazakami003/test/poisson.cpp", "max_issues_repo_name": "mino2357/2dimPDE", "max_issues_repo_head_hexsha": "448287de056ccbf630503e8949627827d2c81d41", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kazakami003/test/poisson.cpp", "max_forks_repo_name": "mino2357/2dimPDE", "max_forks_repo_head_hexsha": "448287de056ccbf630503e8949627827d2c81d41", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-07T03:15:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-07T03:15:36.000Z", "avg_line_length": 20.2820512821, "max_line_length": 79, "alphanum_fraction": 0.5227560051, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6338326376630498}}
{"text": "#pragma once\n// kalman.hpp\n//\n// Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.\n//\n// This file is part of the HPR-BLAS project, which is released under an MIT Open Source license.\n#include <boost/numeric/mtl/mtl.hpp>\n\ntemplate<typename Ty>\nclass KalmanFilter {\npublic:\n\n\t/**\n\t* Create a Kalman filter with the specified matrices.\n\t*   A - System dynamics 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\tdouble dt,\n\t\tconst mtl::dense2D<Ty>& A,\n\t\tconst mtl::dense2D<Ty>& C,\n\t\tconst mtl::dense2D<Ty>& Q,\n\t\tconst mtl::dense2D<Ty>& R,\n\t\tconst mtl::dense2D<Ty>& P\n\t) : A(A), C(C), Q(Q), R(R), P0(P),\n\t\tm(num_rows(C)), n(num_rows(A)), dt(dt), initialized(false),\n\t\tI(n, n), x_hat(n), t(0), t0(0)\n\t{\n\t\tI = mtl::mat::identity2D(m,n); // I.setIdentity();\n\t}\n\tKalmanFilter() {}\n\n\t/**\n\t* Initialize the filter with initial states as zero.\n\t*/\n\tvoid init() {\n\t\tx_hat.setToZero();\n\t\tP = P0;\n\t\tt0 = 0;\n\t\tt = t0;\n\t}\n\n\t/**\n\t* Initialize the filter with a guess for initial states.\n\t*/\n\tvoid init(double _t0, const mtl::dense_vector<Ty>& _x0) {\n\t\tx_hat = _x0;\n\t\tP = P0;\n\t\tt0 = _t0;\n\t\tt = t0;\n\t}\n\n\t/**\n\t* Update the estimated state based on measured values. The\n\t* time step is assumed to remain constant.\n\t*/\n\tvoid update(const mtl::dense_vector<Ty>& y) {\n\t\tmtl::dense_vector<Ty> x_hat_new(n);\n\t\tx_hat_new = A * x_hat;\n//\t\tP = A * P * trans(A) + Q;\n//\t\tK = P * trans(C) * (C * P * trans(C) + R).inverse();\n//\t\tx_hat_new += K * (y - C * x_hat_new);\n//\t\tP = (I - K * C) * P;\n\t\tx_hat = x_hat_new;\n\t}\n\n\t/**\n\t* Update the estimated state based on measured values,\n\t* using the given time step and dynamics matrix.\n\t*/\n\tvoid update(const mtl::dense_vector<Ty>& _y, double _dt, const mtl::dense2D<Ty> _A) {\n\t\tA = _A;\n\t\tdt = _dt;\n\t\tupdate(_y);\n\t}\n\n\t/**\n\t* Return the current state and time.\n\t*/\n\tmtl::dense_vector<Ty> state() { return x_hat; };\n\tdouble time() { return t; };\n\nprivate:\n\tbool initialized;\n\n\t// Matrices for computation\n\tmtl::dense2D<Ty> A, C, Q, R, P, K, P0;\n\n\t// System dimensions\n\tsize_t m, n;\n\n\t// Initial and current time\n\tdouble t0, t;\n\n\t// Discrete time step\n\tdouble dt;\n\n\t// n-size identity\n\tmtl::dense2D<Ty> I;\n\n\t// Estimated states\n\tmtl::dense_vector<Ty> x_hat;\n};\n", "meta": {"hexsha": "4a2ef64345d1bf6dc5cf8448ce14462f6cb0922a", "size": 2283, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/estimation/kalman.hpp", "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/estimation/kalman.hpp", "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/estimation/kalman.hpp", "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": 21.3364485981, "max_line_length": 97, "alphanum_fraction": 0.6254927727, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6338326349439793}}
{"text": "//\n//  cal_Bmat.hpp\n//  hybrid_fem_bie\n//\n//  Created by Max on 3/21/18.\n//\n//\n\n#ifndef cal_Bmat_hpp\n#define cal_Bmat_hpp\n\n#include <stdio.h>\n#include <Eigen/Eigen>\n\nusing namespace Eigen;\n\nvoid cal_Bmat(MatrixXd coord ,double E, double nu, std::vector<Eigen::MatrixXd> &B_mat, double &detJ);\n\n\n#endif /* cal_Bmat_hpp */\n", "meta": {"hexsha": "f2bcab67ffd207b4caa130c8e6e5f20e5e23c04e", "size": 321, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fem/cal_Bmat.hpp", "max_stars_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_stars_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "src/fem/cal_Bmat.hpp", "max_issues_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_issues_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fem/cal_Bmat.hpp", "max_forks_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_forks_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 15.2857142857, "max_line_length": 102, "alphanum_fraction": 0.6947040498, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6338326250377636}}
{"text": "#pragma once\n\n#include <Eigen/Geometry>\n\n#include <autodiff/autodiff.h>\n#include <interval/interval.hpp>\n#include <utils/eigen_ext.hpp>\n\nnamespace ipc::rigid {\n\ndouble sinc(const double& x);\n\nInterval sinc(const Interval& x);\n\n/// Compute the L2 norm (\u2211|x\u1d62|\u00b2)\ntemplate <typename T> T norm(const VectorMax3<T>& x)\n{\n    // Do an explicit abs to avoid possible problems with intervals\n    VectorMax3<T> absx(x.size());\n    for (int i = 0; i < x.size(); i++) {\n        absx(i) = abs(x(i));\n    }\n    return sqrt(absx.dot(absx));\n}\n\n/// Compute sinc(||x||) for x \u2208 R\u207f\ntemplate <typename T> T sinc_normx(const VectorMax3<T>& x)\n{\n    static_assert(\n        !std::is_base_of<DiffScalarBase, T>::value,\n        \"This version does not work with autodiff!\");\n    return sinc(norm(x));\n}\n\n/// Compute \u2207sinc(||x||) for x \u2208 R\u207f\nVectorMax3d sinc_normx_grad(const VectorMax3d& x);\n\n/// Compute \u2207\u00b2sinc(||x||) for x \u2208 R\u207f\nMatrixMax3d sinc_normx_hess(const VectorMax3d& x);\n\ntemplate <typename Scalar, typename Gradient>\nDScalar1<Scalar, Gradient>\nsinc_normx(const VectorMax3<DScalar1<Scalar, Gradient>>& x)\n{\n    const int m = DiffScalarBase::getVariableCount(), n = x.size();\n\n    // Extract the vector of values\n    VectorMax3<Scalar> x_vals(n);\n    for (int i = 0; i < n; i++) {\n        x_vals(i) = x(i).getValue();\n    }\n\n    // Compute the value and gradient (without chain-rule)\n    Scalar value = sinc_normx(x_vals);\n    VectorMax3d grad = sinc_normx_grad(x_vals);\n\n    // Apply chain-rule\n    Gradient full_grad = Gradient::Zero(m);\n    for (int j = 0; j < n; j++) {\n        full_grad += grad(j) * x(j).getGradient();\n    }\n\n    return DScalar1<Scalar, Gradient>(value, full_grad);\n}\n\ntemplate <typename Scalar, typename Gradient, typename Hessian>\nDScalar2<Scalar, Gradient, Hessian>\nsinc_normx(const VectorMax3<DScalar2<Scalar, Gradient, Hessian>>& x)\n{\n    const int m = DiffScalarBase::getVariableCount(), n = x.size();\n\n    // Extract the vector of values\n    VectorMax3<Scalar> x_vals(n);\n    for (int i = 0; i < n; i++) {\n        x_vals(i) = x(i).getValue();\n    }\n\n    // Compute the value, gradient, and hessian (without chain-rule)\n    Scalar value = sinc_normx(x_vals);\n    VectorMax3d grad = sinc_normx_grad(x_vals);\n    MatrixMax3d hess = sinc_normx_hess(x_vals);\n\n    // Apply chain-rule\n    Gradient full_grad = Gradient::Zero(m);\n    for (int k = 0; k < n; k++) {\n        full_grad += grad(k) * x(k).getGradient();\n    }\n\n    Hessian full_hess = Hessian::Zero(m, m);\n    for (int k = 0; k < n; k++) {\n        for (int l = 0; l < n; l++) {\n            full_hess += hess(k, l) * x(l).getGradient()\n                * x(k).getGradient().transpose();\n        }\n        full_hess += grad(k) * x(k).getHessian();\n    }\n\n    return DScalar2<Scalar, Gradient, Hessian>(value, full_grad, full_hess);\n}\n\n} // namespace ipc::rigid\n", "meta": {"hexsha": "15e2db018a756e42a3ef3929c3cc61bcdedd62b8", "size": 2825, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/sinc.hpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "src/utils/sinc.hpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "src/utils/sinc.hpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 27.6960784314, "max_line_length": 76, "alphanum_fraction": 0.6269026549, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.633773452450147}}
{"text": "#ifndef TVMTL_MANIFOLD_SON_HPP\n#define TVMTL_MANIFOLD_SON_HPP\n\n#include <cmath>\n#include <complex>\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/SVD>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <unsupported/Eigen/KroneckerProduct>\n\n#include \"enumerators.hpp\"\n#include \"matrix_utils.hpp\"\n\nnamespace tvmtl {\n\n// Specialization SO(N)\ntemplate <int N>\nstruct Manifold< SO, N> {\n    \n    public:\n\tstatic const MANIFOLD_TYPE MyType;\n\tstatic const int manifold_dim ;\n\tstatic const int value_dim; // TODO: maybe rename to embedding_dim \n\n\tstatic const bool non_isometric_embedding;\n\n\t// Scalar type of manifold\n\t//typedef double scalar_type;\n\ttypedef double scalar_type;\n\ttypedef double dist_type;\n\ttypedef std::complex<double> complex_type;\n\ttypedef std::vector<double> weight_list; \n\n\t// Value Typedef\n\ttypedef Eigen::Matrix< scalar_type, N, N>\t\t\t\tvalue_type;\n\ttypedef value_type&\t\t\t\t\t\t\tref_type;\n\ttypedef const value_type&\t\t\t\t\t\tcref_type;\n\ttypedef std::vector<value_type, Eigen::aligned_allocator<value_type> >\tvalue_list; \n\n\t\n\t// Tangent space typedefs\n\ttypedef Eigen::Matrix <scalar_type, N * N, N * (N - 1) / 2> tm_base_type;\n\ttypedef tm_base_type& tm_base_ref_type;\n\n\t// Derivative Typedefs\n\ttypedef value_type\t\t\t     deriv1_type;\n\ttypedef deriv1_type&\t\t\t     deriv1_ref_type;\n\t\n\ttypedef Eigen::Matrix<scalar_type, N*N, N*N>\t\t\t\tderiv2_type;\n\ttypedef deriv2_type&\t\t\t\t\t\t\tderiv2_ref_type;\n\ttypedef\tEigen::Matrix<scalar_type, N * (N - 1) / 2, N * (N - 1) / 2>\trestricted_deriv2_type;\n\n\t// Helper Types\n\ttypedef Eigen::PermutationMatrix<N*N, N*N, int> perm_type;\n\n\tinline static perm_type ConstructPermutationMatrix();\n\n\t// Manifold distance functions (for IRLS)\n\tinline static dist_type dist_squared(cref_type x, cref_type y);\n\tinline static void deriv1x_dist_squared(cref_type x, cref_type y, deriv1_ref_type result);\n\tinline static void deriv1y_dist_squared(cref_type x, cref_type y, deriv1_ref_type result);\n\n\tinline static void deriv2xx_dist_squared(cref_type x, cref_type y, deriv2_ref_type result);\n\tinline static void deriv2xy_dist_squared(cref_type x, cref_type y, deriv2_ref_type result);\n\tinline static void deriv2yy_dist_squared(cref_type x, cref_type y, deriv2_ref_type result);\n\tstatic const perm_type permutation_matrix;\n\n\n\t// Manifold exponentials und logarithms ( for Proximal point)\n\ttemplate <typename DerivedX, typename DerivedY>\n\tinline static void exp(const Eigen::MatrixBase<DerivedX>& x, const Eigen::MatrixBase<DerivedY>& y, Eigen::MatrixBase<DerivedX>& result);\n\tinline static void log(cref_type x, cref_type y, ref_type result);\n\t\n\tinline static void convex_combination(cref_type x, cref_type y, double t, ref_type result);\n\n\t// Implementations of the Karcher mean\n\t// Slow list version\n\tinline static void karcher_mean(ref_type x, const value_list& v, double tol=1e-10, int maxit=15);\n\tinline static void weighted_karcher_mean(ref_type x, const weight_list& w, const value_list& v, double tol=1e-10, int maxit=15);\n\t// Variadic templated version\n\ttemplate <typename V, class... Args>\n\tinline static void karcher_mean(V& x, const Args&... args);\n\ttemplate <typename V>\n\tinline static void variadic_karcher_mean_gradient(V& x, const V& y);\n\ttemplate <typename V, class... Args>\n\tinline static void variadic_karcher_mean_gradient(V& x, const V& y1, const Args&... args);\n\n\t// Basis transformation for restriction to tangent space\n\tinline static void tangent_plane_base(cref_type x, tm_base_ref_type result);\n\n\t// Projection\n\tinline static void projector(ref_type x);\n\n\t// Interpolation pre- and postprocessing\n\tinline static void interpolation_preprocessing(ref_type x) {};\n\tinline static void interpolation_postprocessing(ref_type x) {};\n\n\n};\n\n\n/*-----IMPLEMENTATION SO----------*/\n\n// Static constants, Outside definition to avoid linker error\n\ntemplate <int N>\nconst MANIFOLD_TYPE Manifold < SO, N>::MyType = SO; \n\ntemplate <int N>\nconst int Manifold < SO, N>::manifold_dim = N * (N - 1) / 2; \n\ntemplate <int N>\nconst int Manifold < SO, N>::value_dim = N * N; \n\ntemplate <int N>\nconst bool Manifold < SO, N>::non_isometric_embedding = false; \n\n// PermutationMatrix\ntemplate <int N>\ntypename Manifold < SO, N>::perm_type Manifold<SO, N>::ConstructPermutationMatrix(){\n    perm_type P;\n    P.setIdentity();\n    for(int i=0; i<N; i++)\n\tfor(int j=0; j<i; j++)\n\t    P.applyTranspositionOnTheRight(j*N + i, i*N + j);\n    return P;\n}\n\ntemplate <int N>\nconst typename Manifold < SO, N>::perm_type Manifold<SO, N>::permutation_matrix = ConstructPermutationMatrix(); \n\n\n\n\n// Squared SO distance function\ntemplate <int N>\ninline typename Manifold < SO, N>::dist_type Manifold < SO, N>::dist_squared( cref_type x, cref_type y ){\n    #ifdef TV_SON_DEBUG\n\tstd::cout << \"\\nDist2 function with x=\\n\" << x << \"\\nand y=\\n\" << y << std::endl;\n    #endif \n    return (x.transpose() * y).log().squaredNorm();\n}\n\n\n// Derivative of Squared SO distance w.r.t. first argument\ntemplate <int N>\ninline void Manifold < SO, N>::deriv1x_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){\n    result = -2.0 * x * (x.transpose() * y).log();\n}\n// Derivative of Squared SO distance w.r.t. second argument\ntemplate <int N>\ninline void Manifold < SO, N>::deriv1y_dist_squared( cref_type x, cref_type y, deriv1_ref_type result){\n    result =  -2.0 * y * (y.transpose() * x).log();\n}\n\n\n\n\n// Second Derivative of Squared SO distance w.r.t first argument\ntemplate <int N>\ninline void Manifold < SO, N>::deriv2xx_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    value_type XtY = x.transpose()*y;\n\n    deriv2_type logXtY_kron_I ,I_kron_x, Yt_kron_I, dlog; \n    logXtY_kron_I = Eigen::kroneckerProduct(XtY.log().eval(),value_type::Identity());\n    I_kron_x = Eigen::kroneckerProduct(value_type::Identity(),x);\n    Yt_kron_I = Eigen::kroneckerProduct(y.transpose(),value_type::Identity());\n    KroneckerDLog(XtY, dlog);\n\n    result = -2.0 * (logXtY_kron_I.transpose() + I_kron_x * dlog * Yt_kron_I * permutation_matrix );\n}\n// Second Derivative of Squared SO distance w.r.t first and second argument\ntemplate <int N>\ninline void Manifold < SO, N>::deriv2xy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    value_type XtY = x.transpose()*y;\n\n    deriv2_type I_kron_x, dlog; \n    I_kron_x = Eigen::kroneckerProduct(value_type::Identity(),x);\n    KroneckerDLog(XtY, dlog);\n\n    result = -2.0 * I_kron_x * dlog * I_kron_x.transpose();\n}\n// Second Derivative of Squared SO distance w.r.t second argument\ntemplate <int N>\ninline void Manifold < SO, N>::deriv2yy_dist_squared( cref_type x, cref_type y, deriv2_ref_type result){\n    deriv2xx_dist_squared(y, x, result);\n}\n\n\n\n// Exponential and Logarithm Map\ntemplate <int N>\ntemplate <typename DerivedX, typename DerivedY>\ninline void Manifold <SO, N>::exp(const Eigen::MatrixBase<DerivedX>& x, const Eigen::MatrixBase<DerivedY>& y, Eigen::MatrixBase<DerivedX>& result){\n    result = x * (x.transpose() * y).exp();\n}\n\ntemplate <int N>\ninline void Manifold <SO, N>::log(cref_type x, cref_type y, ref_type result){\n    result = x * (x.transpose() * y).log();\n}\n\n// Tangent Plane restriction\ntemplate <int N>\ninline void Manifold <SO, N>::tangent_plane_base(cref_type x, tm_base_ref_type result){\n    int d = value_type::RowsAtCompileTime;\n    int k = 0;\n    \n    value_type T;\n\n    for(int i=0; i<d-1; i++)\n\tfor(int j=i+1; j<d; j++){\n\t    T.setZero();\n\t    scalar_type sqrt = 1.0/std::sqrt(2);\n\t    T.col(i) = -sqrt * x.col(j);\n\t    T.col(j) =  sqrt * x.col(i);\n\n\t    result.col(k) = Eigen::Map<Eigen::VectorXd>(T.data(), T.size());\n\t    k++;\n\t}\n}\n\n// Convex geodesic combinations\ntemplate <int N>\ninline void Manifold <SO, N>::convex_combination(cref_type x, cref_type y, double t, ref_type result){\n    value_type l;\n    if (t == 0.5){\n\tresult = x + y;\n\tprojector(result);\n    }\n    else{\n    log(x, y, l);\n    exp(x, l * t, result);\n    }\n}\n\n// Karcher mean implementations\ntemplate <int N>\ninline void Manifold<SO, N>::karcher_mean(ref_type x, const value_list& v, double tol, int maxit){\n    value_type L, temp;\n   \n    int k = 0;\n    double error = 0.0;\n    do{\n\tscalar_type m1 = x.sum();\n\tL = value_type::Zero();\n\tfor(int i = 0; i < v.size(); ++i){\n\t    log(x, v[i], temp);\n\t    L += temp;\n\t}\n\texp(x, 1.0 / v.size() * L , temp);\n\tx = temp;\n\terror = std::abs(x.sum() - m1);\n\t++k;\n    } while(error > tol && k < maxit);\n\n}\n\ntemplate <int N>\ninline void Manifold<SO, N>::weighted_karcher_mean(ref_type x, const weight_list& w, const value_list& v, double tol, int maxit){\n    value_type L, temp;\n   \n    int k = 0;\n    double error = 0.0;\n    do{\n\tscalar_type m1 = x.sum();\n\tL = value_type::Zero();\n\tfor(int i = 0; i < v.size(); ++i){\n\t    log(x, v[i], temp);\n\t    L += w[i] * temp;\n\t}\n\texp(x, 1.0 / v.size() * L , temp);\n\tx = temp;\n\tprojector(x);\n\terror = std::abs(x.sum() - m1);\n\t++k;\n    } while(error > tol && k < maxit);\n\n}\n\ntemplate <int N>\ntemplate <typename V, class... Args>\ninline void Manifold<SO, N>::karcher_mean(V& x, const Args&... args){\n    V temp, sum;\n    \n    int numArgs = sizeof...(args);\n    int k = 0;\n    double error = 0.0;    \n    double tol = 1e-10;\n    int maxit = 15;\n    do{\n\tscalar_type m1 = x.sum();\n\tsum = x;\n\tvariadic_karcher_mean_gradient(sum, args...);\n\texp(x, 1.0 / numArgs * sum, temp);\n\tx = temp;\n\tprojector(x);\n\terror = std::abs(x.sum() - m1);\n\t++k;\n    } while(error > tol && k < maxit);\n}\n\ntemplate <int N>\ntemplate <typename V>\ninline void Manifold<SO, N>::variadic_karcher_mean_gradient(V& x, const V& y){\n    V temp;\n    log(x, y, temp);\n    x = temp;\n}\n\ntemplate <int N>\ntemplate <typename V, class... Args>\ninline void Manifold<SO, N>::variadic_karcher_mean_gradient(V& x, const V& y1, const Args& ... args){\n    V temp1, temp2;\n    temp2 = x;\n    \n    log(x, y1, temp1);\n\n    variadic_karcher_mean_gradient(temp2, args...);\n    temp1 += temp2;\n    x = temp1;\n}\n\ntemplate <int N>\ninline void Manifold <SO, N>::projector(ref_type x){\n    \n    #ifdef TV_SON_DEBUG\n\tstd::cout << \"\\n\\nProjector with initial x=\\n\" << x << std::endl;\n    #endif     \n    \n    Eigen::JacobiSVD<value_type> svd(x, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    x = svd.matrixU() * svd.matrixV().transpose();\n    //if(x.determinant() < 0)\n    //\tx.row(1)*=-1.0;\n\n    #ifdef TV_SON_DEBUG\n\tstd::cout << \"\\nProjector with final x=\\n\" << x << std::endl;\n    #endif\n}\n\n\n\n} // end namespace tvmtl\n\n\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "feaca7bff903db2d241ee807bad271d5e520fca5", "size": 10353, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mtvmtl/core/manifold_son.hpp", "max_stars_repo_name": "pdebus/MTVMTL", "max_stars_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-08T12:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-02T05:11:01.000Z", "max_issues_repo_path": "mtvmtl/core/manifold_son.hpp", "max_issues_repo_name": "pdebus/MTVMTL", "max_issues_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mtvmtl/core/manifold_son.hpp", "max_forks_repo_name": "pdebus/MTVMTL", "max_forks_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0814606742, "max_line_length": 147, "alphanum_fraction": 0.6842461122, "num_tokens": 3019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359806, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6337734196774926}}
{"text": "/*****************************************************************************\n*\n* Copyright (C) 2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include <iomanip>\n#include <iostream>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n\nint main() {\n  using std::abs; using std::sqrt;\n  typedef double real_t;\n\n  auto f = [](real_t x) { return sqrt(1 - x * x); };\n  real_t r = boost::math::constants::pi<real_t>() / 2;\n  \n  boost::math::quadrature::tanh_sinh<real_t> integrator;\n  real_t termination = sqrt(std::numeric_limits<real_t>::epsilon());\n  real_t error, L1;\n  size_t levels;\n  real_t q = integrator.integrate(f, -1, 1, termination, &error, &L1, &levels);\n\n  std::cout << std::scientific << std::setprecision(std::numeric_limits<real_t>::digits10)\n            << \"result: \" << q << std::endl\n            << \"estimated error: \" << error << std::endl\n            << \"real error: \" << abs(q - r) << std::endl\n            << \"L1 * error: \" << L1 * error << std::endl\n            << \"levels: \" << levels << std::endl;\n}\n", "meta": {"hexsha": "90baa5e7d0aca25f35aaf3e9d276a4e134824cfc", "size": 1320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tanh_sinh/example4.cpp", "max_stars_repo_name": "wistaria/boost-examples", "max_stars_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tanh_sinh/example4.cpp", "max_issues_repo_name": "wistaria/boost-examples", "max_issues_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tanh_sinh/example4.cpp", "max_forks_repo_name": "wistaria/boost-examples", "max_forks_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6666666667, "max_line_length": 90, "alphanum_fraction": 0.553030303, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6337081514778712}}
{"text": "#include <boost/program_options.hpp>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cassert>\n#include <cmath>\n#include <stdlib.h>\n#include <stdint.h>\n#include <random>\n#include <algorithm>    // std::min_element, std::max_element\n\n#include \"structures.h\"\n#include \"clear_ciffers.h\"\n\n// Questions 2 and 3\n// Display the linear approximation matrix.\nvoid linearApproximationMatrix(int nbElt=16) {\n    std::vector<std::pair<int,int>> goodKeys ;\n    std::cout << \"\\\\[\\n\\\\bordermatrix{\\n& \" ;\n    for(int b = 0 ; b < nbElt-1 ; b++) {\n        std::cout << b << \" & \" ;\n    }\n    std::cout << nbElt-1 << \"\\\\cr\\n\" ;\n    for(int a = 0 ; a < nbElt ; a++) {\n        std::cout << a << \" & \" ;\n        for(int b = 0 ; b < nbElt ; b++) {\n            int nbKey = 0 ;\n            for(int c = 0 ; c < nbElt ; c++) {\n                Block blockA(a) ;\n                Block blockB(b) ;\n                Block key(c) ;\n                blockA.product(key) ;\n                key.substitution() ;\n                blockB.product(key) ;\n                if(blockA.bitsXor() == blockB.bitsXor()) {\n                    nbKey ++ ;\n                }\n            }\n            std::cout << nbKey ;\n            double proba = ((double)nbKey)/16 ;\n            if(std::abs(proba - 0.5) > 0.3) {\n                // std::cout << nbKey ;\n                goodKeys.push_back(std::pair<int,int>(a, b)) ;\n            }\n            if(b < nbElt-1)\n                std::cout << \" & \" ;\n        }\n        std::cout << \"\\\\cr\\n\" ;\n    }\n    std::cout << \"}\\n\\\\]\\n\";\n    std::cout << \"Couples (a, b) with the highest probability:\\n\\\\[\" ;\n    if(goodKeys.size() > 0)\n        std::cout << \"(\" << goodKeys[0].first << \", \" << goodKeys[0].second << \")\" ;\n    for(unsigned i = 1 ; i < goodKeys.size() ; i++) {\n        std::cout << \", (\" << goodKeys[i].first << \", \" << goodKeys[i].second << \")\" ;\n    }\n    std::cout << \"\\\\]\\n\" ;\n}\n\n// Question 4\n// Check experimentaly that Prob(a.m = P(b).c) is in {1/2-1/8, 1/2+1/8}\nvoid experimentalCheck(uint32_t a=1, uint32_t b=5) {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    std::uniform_int_distribution<unsigned int> dis(0, UINT32_MAX);\n    Block A(a<<28);\n    Block B(b<<28);\n    B.permutation() ;\n    // int nbMess = 1000000 ;\n    int nbMess = 100000 ;\n    for(int i = 0 ; i < 10 ; i++) {\n        Block K0(dis(gen)) ;\n        Block K1(dis(gen)) ;\n        int nbEqual = 0 ;\n        for(int j = 0 ; j < nbMess ; j++) {\n            Block m(dis(gen)) ;\n            Block x(m) ;\n            x.addition(K0) ;\n            x.turn(K1) ;\n            m.product(A) ;\n            x.product(B) ;\n            if(m.bitsXor() == x.bitsXor())\n                nbEqual ++ ;\n        }\n        std::cout << \"& $\" << (double)nbEqual/(double)nbMess << \"$ \";//std::endl ;\n    }\n    std::cout << \"\\\\\\\\\" << std::endl ;\n}\n\n// Questions 7-8\n// Guess the block of given index of the key K2.\nint guessKeyBox(int blockIndex, uint32_t a=4, uint32_t b=8) {\n    std::vector<int> keyCount(16, 0) ;\n    Block A(a<<(blockIndex*4)) ;\n    Block B(b<<(blockIndex*4)) ;\n    B.permutation(2) ;\n    // Compute the distribution of each key over all the couples plaintext/ciphertext\n    for(unsigned int i = 0 ; i < Plaintext.size() ; i++) {\n        Block M(Plaintext[i]) ;\n        Block C(Ciphertext[i]) ;\n        C.permutation(-2) ;\n        for(uint32_t k = 0 ; k < 16 ; k++) {\n            Block K(k<<(blockIndex*4)) ;\n            K.addition(C) ;\n            K.substitution(REVERSE_DEFAULT_SUBST) ;\n            Block Mcopy(M) ;\n            Mcopy.product(A) ;\n            K.product(B) ;\n            if(Mcopy.bitsXor() == K.bitsXor())\n                keyCount[k] ++ ;\n        }\n    }\n    // The key with the distribution the farthest from 1/2 is probably the key that we are looking for.\n    int kmin = std::min_element(keyCount.begin(), keyCount.end()) - keyCount.begin();\n    int kmax = std::max_element(keyCount.begin(), keyCount.end()) - keyCount.begin();\n    if(std::abs((double)Plaintext.size()/2 - keyCount[kmin]) > std::abs((double)Plaintext.size()/2 - keyCount[kmax]))\n        return kmin ;\n    else\n        return kmax ;\n}\n\n// Questions 7-8\n// Guess the key K2 block by block.\nBlock guessK2() {\n    Block K(0) ;\n    for(int i = 0 ; i < 8 ; i++) {\n        K.setBox(i, guessKeyBox(i)) ;\n    }\n    K.permutation() ;\n    return K ;\n}\n\n// Check if the given keys are the keys which crypted the table Plaintext.\nbool checkSolution(Block K0, Block K1, Block K2) {\n    unsigned int i ;\n    for(i = 0 ; i < Plaintext.size() ; i++) {\n        Block m(Plaintext[i]) ;\n        Block c(Ciphertext[i]) ;\n        m.encrypt(K0, K1, K2) ;\n        if(m.getBits() != c.getBits())\n            break ;\n    }\n    return i == Plaintext.size() ;\n}\n\n// Not in the subject\n// Retrieve the keys with a brute force attack.\n// Too long, not fully tested.\nvoid bruteForce() { // too long\n    uint32_t k = 0 ;\n    Block K0, K1, K2 ;\n    while(1) {\n        if(k%10000 == 0)\n            std::cout << k << \"/\" << UINT32_MAX << std::endl ;\n        Block K(k) ;\n        K.generateSubKeys(&K0, &K1, &K2) ;\n        if(checkSolution(K0, K1, K2))\n            break ;\n        k++ ;\n    }\n    std::cout << \"Found keys by brute force:\" << std::endl ;\n    std::cout << \"K  = \" << k << std::endl ;\n    std::cout << \"K0 = \" << K0.getBits() << std::endl ;\n    std::cout << \"K1 = \" << K1.getBits() << std::endl ;\n    std::cout << \"K2 = \" << K2.getBits() << std::endl ;\n}\n\n// Question 9\n// Find the keys with the method of the actives boxes.\nBlock guessKey() {\n    int bit ;\n    std::vector<int> K2Subst = DEFAULT_K2_SUBST ;\n    Block K2 = guessK2() ;\n    Block K ;\n    std::vector<bool> knownBit(32, false) ;\n    // Build the key K with the key K2\n    for(int i = 0 ; i < 32 ; i++) {\n        K.setBox(K2Subst[i], K2.getBox(i, 1), 1) ;\n        knownBit[K2Subst[i]] = true ;\n    }\n    // Bits of K that we do not know\n    std::vector<int> unknownPositions ;\n    for(int i = 0 ; i < 32 ; i++) {\n        if(!knownBit[i])\n            unknownPositions.push_back(i) ;\n    }\n    std::vector<int> bitsToGuess(unknownPositions.size(), 0) ;\n    Block K0, K1, K2bis ;\n    // Brute force attack on the unknown bits\n    K.generateSubKeys(&K0, &K1, &K2bis) ;\n    assert(K2bis.getBits() == K2.getBits()) ;\n    while(!checkSolution(K0, K1, K2)) {\n        int i = bitsToGuess.size() - 1 ;\n        while(bitsToGuess[i] == 1) {\n            bitsToGuess[i] = 0 ;\n            K.setBox(unknownPositions[i], 0, 1) ;\n            i-- ;\n        }\n        bitsToGuess[i] = 1 ;\n        K.setBox(unknownPositions[i], 1, 1) ;\n        K.generateSubKeys(&K0, &K1, &K2bis) ;\n        assert(K2bis.getBits() == K2.getBits()) ;\n    }\n    return K ;\n}\n\nnamespace po = boost::program_options;\n\nint main(int argc, char *argv[]) {\n    po::options_description description(\"Usage\");\n\n    description.add_options()\n        (\"help,h\", \"produce help message\")\n        (\"linearApproximationMatrix\", \"display the linear approximation matrix\")\n        (\"experimentalCheck\", \"display the experimental results\")\n        (\"bruteForce\", \"retrieve the keys by a brute force attack (very long)\")\n        (\"activeBox\", \"retrieve the keys by active boxes attack\") ;\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(description).run(), vm);\n    po::notify(vm);\n\n    if(vm.count(\"help\")){\n        std::cout << description;\n        return 0 ;\n    }\n\n    if(vm.count(\"linearApproximationMatrix\")) {\n        linearApproximationMatrix() ;\n    }\n\n    if(vm.count(\"experimentalCheck\")) {\n        std::vector<std::pair<int, int>> couples = {std::pair<int, int>(1, 5),\\\n            std::pair<int, int>(3, 15), std::pair<int, int>(4, 8), std::pair<int, int>(7, 7),\\\n            std::pair<int, int>(9, 4), std::pair<int, int>(10, 11), std::pair<int, int>(13, 12)} ;\n        for(unsigned i = 0 ; i < couples.size() ; i++) {\n            std::cout << \"$(\" << couples[i].first << \", \" << couples[i].second << \")$ \" ;\n            experimentalCheck(couples[i].first, couples[i].second) ;\n        }\n    }\n\n    if(vm.count(\"bruteForce\")) {\n        bruteForce() ;\n    }\n\n    if(vm.count(\"activeBox\")) {\n        Block K = guessKey() ;\n        Block K0, K1, K2 ;\n        K.generateSubKeys(&K0, &K1, &K2) ;\n        std::cout << \"K  = \" << K.getBits() << std::endl ;\n        std::cout << \"K0 = \" << K0.getBits() << std::endl ;\n        std::cout << \"K1 = \" << K1.getBits() << std::endl ;\n        std::cout << \"K2 = \" << K2.getBits() << std::endl ;\n    }\n\n    return 0 ;\n}\n", "meta": {"hexsha": "ac513fdb199055d60e9eeca5e5a8d7c534a35684", "size": 8465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Ezibenroc/crypto-B32", "max_stars_repo_head_hexsha": "5bf3876175345735e1034e9e78f0e417709f7442", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-11-04T20:03:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T07:26:30.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "Ezibenroc/crypto-B32", "max_issues_repo_head_hexsha": "5bf3876175345735e1034e9e78f0e417709f7442", "max_issues_repo_licenses": ["MIT"], "max_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": "Ezibenroc/crypto-B32", "max_forks_repo_head_hexsha": "5bf3876175345735e1034e9e78f0e417709f7442", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-03-23T10:41:32.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-04T14:39:03.000Z", "avg_line_length": 32.9377431907, "max_line_length": 117, "alphanum_fraction": 0.5170702894, "num_tokens": 2508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6337081511411224}}
{"text": "/*\n * MultivariateNormalDistribution.hpp\n *\n *  Created on: Oct 6, 2012\n *      Author: bing\n */\n\n#ifndef MULTIVARIATENORMALDISTRIBUTION_HPP_\n#define MULTIVARIATENORMALDISTRIBUTION_HPP_\n\n#include <boost/random.hpp>\n#include <Eigen/Cholesky>\n\ntemplate<class T, size_t N>\nclass MultivariateNormalDistribution {\npublic:\n\tMultivariateNormalDistribution(unsigned int seed = time(0));\n\n\tMultivariateNormalDistribution(const Eigen::Matrix<T, N, N>& covarianceMatrix, unsigned int seed = time(0));\n\n\tvirtual ~MultivariateNormalDistribution();\n\n\tvoid setCovarianceMatrix(const Eigen::Matrix<T, N, N>& covarianceMatrix);\n\n\tEigen::Matrix<T, N, 1> draw();\n\n\tEigen::Matrix<T, N, 1> draw(const Eigen::Matrix<T, N, N>& covarianceMatrix);\n\nprivate:\n\tEigen::Matrix<T, N, 1> draw(const Eigen::LLT<Eigen::Matrix<T, N, N> >& llt);\n\nprivate:\n\tEigen::Matrix<T, N, N> covarianceMatrix_;\n\tEigen::LLT<Eigen::Matrix<T, N, N> > llt_;\n\tboost::mt19937 rng_;\n};\n\ntemplate<class T, size_t N>\nMultivariateNormalDistribution<T, N>::MultivariateNormalDistribution(unsigned int seed) :\n\t\tcovarianceMatrix_(Eigen::Matrix<T, N, N>::Identity()), llt_(Eigen::Matrix<T, N, N>::Identity()), rng_(seed) {\n\n}\n\ntemplate<class T, size_t N>\nMultivariateNormalDistribution<T, N>::MultivariateNormalDistribution(const Eigen::Matrix<T, N, N>& covarianceMatrix, unsigned int seed) :\n\t\tcovarianceMatrix_(covarianceMatrix), llt_(covarianceMatrix), rng_(seed) {\n\n}\n\ntemplate<class T, size_t N>\nMultivariateNormalDistribution<T, N>::~MultivariateNormalDistribution() {\n\n}\n\ntemplate<class T, size_t N>\nvoid MultivariateNormalDistribution<T, N>::setCovarianceMatrix(const Eigen::Matrix<T, N, N>& covarianceMatrix) {\n\tcovarianceMatrix_ = covarianceMatrix;\n\tllt_ = Eigen::LLT<Eigen::Matrix<T, N, N> >(covarianceMatrix);\n}\n\ntemplate<class T, size_t N>\nEigen::Matrix<T, N, 1> MultivariateNormalDistribution<T, N>::draw() {\n\treturn draw(llt_);\n}\n\ntemplate<class T, size_t N>\nEigen::Matrix<T, N, 1> MultivariateNormalDistribution<T, N>::draw(const Eigen::Matrix<T, N, N>& covarianceMatrix) {\n\treturn draw(Eigen::LLT<Eigen::Matrix<T, N, N> >(covarianceMatrix));\n}\n\ntemplate<class T, size_t N>\nEigen::Matrix<T, N, 1> MultivariateNormalDistribution<T, N>::draw(const Eigen::LLT<Eigen::Matrix<T, N, N> >& llt) {\n\t// Draw N independent random numbers from standard normal distribution.\n\tboost::normal_distribution<double> normalDistribution(0.0, 1.0);\n\tboost::variate_generator<boost::mt19937&, boost::normal_distribution<> > variateGenerator(rng_, normalDistribution);\n\tEigen::Matrix<T, N, 1> r(N);\n\tfor (unsigned int i = 0; i < N; i++) {\n\t\tr(i) = variateGenerator();\n\t}\n\n\t// Transform numbers to multivariate normal distribution.\n\tEigen::Matrix<T, N, 1> z = llt.matrixL() * r;\n\n\treturn z;\n}\n\n#endif /* MULTIVARIATENORMALDISTRIBUTION_HPP_ */\n", "meta": {"hexsha": "e89755d33d4589065173d4a68d491dd1edc3199a", "size": 2776, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/tools/calibration/MultivariateNormalDistribution.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/tools/calibration/MultivariateNormalDistribution.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/tools/calibration/MultivariateNormalDistribution.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5454545455, "max_line_length": 137, "alphanum_fraction": 0.7334293948, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.633708150804373}}
{"text": "\r\n/*\r\n\t\r\n\tstest01.cpp\r\n\r\n\tkoli\u306e\u3046\u3061\u7d71\u8a08\u95a2\u4fc2\u90e8\u5206\u306e\u30c6\u30b9\u30c8\r\n\t\r\n\tWritten by Koji Yamamoto\r\n\tCopyright (C) 2019-2020 Koji Yamamoto\r\n\t\r\n\tTODO:\u3000\r\n\r\n\tksvggraph.cpp\u306e\u30c6\u30b9\u30c8\u3092\u66f8\u304f\u3002\r\n\r\n\t-std:c++17\u3067\u30b3\u30f3\u30d1\u30a4\u30eb\u304c\u901a\u308b\u304b\u3084\u3063\u3066\u307f\u308b\u3002\r\n\tgcc\u3067\u3082\u3002\r\n\r\n\tkstat.cpp\u306e\u30c6\u30b9\u30c8\u3092\u66f8\u304f\u3002\r\n\r\n\tkdataset\u306b\u623b\u308b\u3002\r\n\r\n\tNelder-Mead\u3092\u5b9f\u88c5\u3002\r\n\r\n\r\n\r\n\r\n\t\u2193\u4ee5\u4e0b\u306f\u524d\u304b\u3089\u66f8\u3044\u3066\u3042\u308b\u3082\u306e\u3002\r\n\t\u5ea6\u6570\u5206\u5e03\u8868\u3092\u3064\u304f\u308b\u3002kstat\u3092\u898b\u3066\u3002\r\n\t\u3000\u5225\u306b\u3001\u9023\u7d9a\u5909\u6570\u7528\u306e\u6a5f\u80fd\u3092\u3064\u3051\u308b\u3002\r\n\t\u3000\u3000start/end, width, bin \u3092\u6307\u5b9a\u3059\u308b\u65b9\u5f0f\u3002\r\n\t\u3000\u3000\u81ea\u52d5\u3067\u3001\u30b9\u30bf\u30fc\u30b8\u30a7\u30b9\u306e\u516c\u5f0f\u3092\u4f7f\u3046\u65b9\u5f0f\u3002\r\n\t\u3000\u3000\u968e\u7d1a\u306e\u7aef\u70b9\u306e\u8868\u3092\u4e0e\u3048\u308b\u65b9\u5f0f\u3002\r\n\t\r\n*/\r\n\r\n\r\n/* ********** Preprocessor Directives ********** */\r\n\r\n#include <k09/kdataset01.cpp>\r\n#include <k09/kstat02.cpp>\r\n#include <k09/koutputfile00.cpp>\r\n#include <k09/ksvggraph00.cpp>\r\n#include <k09/krand00.cpp>\r\n#include <iostream> \r\n#include <iomanip>\r\n#include <algorithm>\r\n\r\n#include <boost/algorithm/string.hpp>\r\n\r\n\r\n/* ********** Namespace Declarations/Directives ********** */\r\n\r\nusing namespace std;\r\n\r\n\r\n/* ********** Class Declarations ********** */\r\n\r\n\r\n/* ********** Enum Definitions ********** */\r\n\r\n\r\n/* ********** Function Declarations ********** */\r\n\r\nint main( int, char *[]);\r\n\r\nSvgGraph calculatePi( double);\r\n\r\nSvgGraph createScatterAndCircle(\r\n\tconst std::vector <double> &xvec,\r\n\tconst std::vector <double> &yvec\r\n);\r\n\r\n\r\n/* ********** Class Definitions ********** */\r\n\r\n\r\n/* ********** Global Variables ********** */\r\n\r\n\r\n/* ********** Definitions of Static Member Variables ********** */\r\n\r\n\r\n/* ********** Function Definitions ********** */\r\n\r\nint main( int, char *[])\r\n{\r\n\t\r\n\tvector <double> dvec;\r\n\tvector <double> dvecclean;\r\n\r\n\t{\r\n\t\tDataset ds;\r\n\t\tbool b;\r\n\r\n\t\tcout << \"Reading data...\";\r\n\t\tb = ds.readCsvFile( \"jhpsmerged_191029_v403.csv\");\r\n\t\tif ( b == false){\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tcout << \"Done.\" << endl;\r\n\r\n\t\tcout << \"Fixing variable types...\";\r\n\t\tint nnum, nmis;\r\n\t\tds.fixVariableType( nnum, nmis);\t\r\n\t\tcout << \"Done.\" << endl;\r\n\t\t\r\n\t\tcout << \"Getting numeric vector before specifying missing...\";\r\n\t\tb = ds.getNumericVectorWithoutMissing( dvec, \"v403\");\r\n\t\tif ( b == false){\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tcout << \"Done.\" << endl;\r\n\t\t\r\n\t\tcout << \"Specifying missing cases and excluding very big values...\";\r\n\t\tds.specifyValid( \r\n\t\t\t\"v403\",\r\n\t\t\t[]( double v)->bool{ return ( v < 99999.0 && v < 2500.0);}\r\n\t\t);\r\n\t\tcout << \"Done.\" << endl;\r\n\r\n\t\tcout << \"Getting numeric vector excl. missing...\";\r\n\t\tb = ds.getNumericVectorWithoutMissing( dvecclean, \"v403\");\r\n\t\tif ( b == false){\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tcout << \"Done.\" << endl;\r\n\t\t\r\n\t}\r\n\r\n\tcout << endl;\r\n\tcout << \"***************************************************\" << endl;\r\n\tcout << \"JHPS 2009 Household Income incl. Tax\" << endl;\r\n\tcout << \"Calculated by mean() and median()\" << endl;\r\n\tcout << \"Mean:   \" << setprecision( 15) << mean( dvecclean)   << \" (Ten Thousand Yen)\" << endl;\r\n\tcout << \"Median: \" << median( dvecclean) << \" (Ten Thousand Yen)\" << endl;\r\n\tcout << \"***************************************************\" << endl;\r\n\tcout << \"FYI: Mean from \\\"dirty\\\" data: \" << setprecision( 15) << mean( dvec) << endl;\r\n\r\n\r\n\t// \u5ea6\u6570\u5206\u5e03\u8868\r\n\r\n\tcout << endl;\r\n\tcout << \"Number of unique values: \" << countUniqueValues( dvecclean) << endl;\r\n\tcout << \"FYI Number of unique values in \\\"dirty\\\" vector: \" << countUniqueValues( dvec) << endl << endl;\r\n\r\n\r\n\tRecodeTable <double, int> rt;\r\n\trt.setAutoTableFromContVar( dvecclean); \r\n\r\n\tcout << \"RecodeTable:\" << endl;\r\n\trt.print( cout, \",\"); \r\n\tcout << endl;\r\n\r\n\tFreqType <int, int> ft;\r\n\tft.setFreqFromRecodeTable( dvecclean, rt);\r\n\r\n\tft.printPadding( cout);\r\n\r\n\r\n\t// \u30d2\u30b9\u30c8\u30b0\u30e9\u30e0\u3092\u3064\u304f\u308b\u3002\r\n\r\n\t{\r\n//\t\tSvgHistogramMaker histm( leftvec, rightvec, counts);\r\n\t\tSvgHistogramMaker histm( dvecclean);\r\n\t\thistm.setGraphTitle( \"Frequency - restricted to v less than 2500\");\r\n\t\thistm.setXAxisTitle( \"Household Income\");\r\n\t\thistm.setYAxisTitle( \"#Cases\");\r\n\t\tSvgGraph svgg = histm.createGraph();\r\n\t\tsvgg.writeFile( \"stest01out01.svg\");\r\n\t}\r\n\r\n\t// animation version\r\n\t{\r\n//\t\tSvgHistogramMaker histm( leftvec, rightvec, counts, true); // \u30a2\u30cb\u30e1\u30d0\u30fc\u30b8\u30e7\u30f3\r\n\t\tSvgHistogramMaker histm( dvecclean, true); \r\n\t\thistm.setGraphTitle( \"Frequency - restricted to v less than 2500\");\r\n\t\thistm.setXAxisTitle( \"Household Income\");\r\n\t\thistm.setYAxisTitle( \"#Cases\");\r\n\t\tSvgGraph svgg = histm.createGraph();\r\n\t\tsvgg.writeFile( \"stest01out02.svg\");\r\n\t}\r\n\r\n\t{\r\n\t\tSvgGraph svgg = calculatePi( 4000);\r\n\t\tsvgg.writeFile( \"stest01out03.svg\");\r\n\t}\r\n\t\r\n\treturn 0;\r\n\r\n\r\n\r\n\t// \u4eca\u306eRecodeTable\u306b\u306f\u3001\u5de6\u7aef\u30fb\u53f3\u7aef\u304c\u306a\u3044\uff08\u7121\u9650\u5927\uff09\u3068\u3044\u3046\u6307\u5b9a\u304c\u3067\u304d\u306a\u3044\u3002\r\n\r\n\t// FreqType\u306b\u306f\u3059\u3054\u304f\u5c0f\u3055\u3044\u6a5f\u80fd\u3060\u3051\u3092\u6301\u305f\u305b\u308b\u3053\u3068\u306b\u3057\u3066\u3001\r\n\t// \u5225\u306bFreqTableType\u304b\u4f55\u304b\u3092\u3064\u304f\u3063\u3066\u3001\u305d\u3053\u306b\u3001RecodeTable\u3092\u6301\u305f\u305b\u305f\u308a\u3001\r\n\t// \u305d\u308c\u3092\u3082\u3068\u306b\u3057\u305fFreq\u3092\u4f5c\u3089\u305b\u305f\u308a\u3057\u3066\u3082\u3088\u3044\u304b\u3082\u3002\r\n\r\n\t/*\r\n\t\u5ea6\u6570\u5206\u5e03\u8868\u3092\u3064\u304f\u308b\u3002kstat\u3092\u898b\u3066\u3002\r\n\t\u3000\u5225\u306b\u3001\u9023\u7d9a\u5909\u6570\u7528\u306e\u6a5f\u80fd\u3092\u3064\u3051\u308b\u3002\r\n\t\u3000\u3000start/end, width, bin \u3092\u6307\u5b9a\u3059\u308b\u65b9\u5f0f\u3002\r\n\t\u3000\u3000\u81ea\u52d5\u3067\u3001\u30b9\u30bf\u30fc\u30b8\u30a7\u30b9\u306e\u516c\u5f0f\u3092\u4f7f\u3046\u65b9\u5f0f\uff1f\r\n\t\u3000\u3000\u203bStata\u3067\u306f\u3001min{ sqrt(N), 10*ln(N)/ln(10)}\u3089\u3057\u3044\u306e\u3067\u3001\u305d\u308c\u3067\u3044\u304f\u3002\r\n\t\u3000\u3000\u968e\u7d1a\u306e\u7aef\u70b9\u306e\u8868\u3092\u4e0e\u3048\u308b\u65b9\u5f0f\u3002\r\n\t*/\r\n\r\n}\r\n\r\nSvgGraph calculatePi( double n)\r\n{\r\n\r\n\tstd::vector <double> xvec;\r\n\tstd::vector <double> yvec;\r\n\txvec.reserve( n);\r\n\tyvec.reserve( n);\r\n\r\n\tfor ( int i = 0; i < n; i++) {\r\n    \txvec.push_back( randomUniform( -1.0, 1.0));\r\n    \tyvec.push_back( randomUniform( -1.0, 1.0));\r\n\t}\t\r\n\r\n\tint ninside = 0;\r\n\tfor ( int i = 0; i < n; i++){\r\n\t\tif ( xvec[ i] * xvec[ i] + yvec[ i] * yvec[ i] < 1.0){\r\n\t\t\tninside++;\r\n\t\t}\r\n\t}\r\n\tstd::cout << \"N of Draws: \" << n << std::endl;\r\n\tstd::cout << \"Estimated PI: \" << ( ( double)ninside / n ) * 4.0 << std::endl << std::endl;\t\r\n\r\n\tSvgGraph svgg = createScatterAndCircle( xvec, yvec);\r\n\t\r\n\treturn svgg;\r\n\t\r\n}\r\n\r\nSvgGraph createScatterAndCircle(\r\n\tconst std::vector <double> &xvec,\r\n\tconst std::vector <double> &yvec\r\n)\r\n{\r\n\r\n\tstd::string graph_title = \"Random Numbers and Circle\";\r\n\tstd::string xaxis_title = \"x\";\r\n\tstd::string yaxis_title = \"y\";\r\n\r\n\tSvgScatterMaker maker( xvec, yvec);\r\n\tmaker.setGraphTitle( graph_title);\r\n\tmaker.setXAxisTitle( xaxis_title); \t\r\n\tmaker.setYAxisTitle( yaxis_title); \r\n\r\n\tauto svgg = maker.createGraph(); \r\n\r\n\tGraphEllipse el( 0, 0, 1, 1);\r\n\tel.setFill( \"none\");\r\n\tel.setStroke( \"red\");\r\n\tel.setStrokewidth( 3);\r\n\tsvgg.addElement( el);\r\n\r\n\treturn svgg; \r\n\r\n}\r\n\r\n\r\n/* ********** Definitions of Member Functions ********** */\r\n\r\n\r\n", "meta": {"hexsha": "b4bf8b033afe564c681e293ac5cdfbb2230342c7", "size": 5890, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "k09/stest/stest01.cpp", "max_stars_repo_name": "kojiynet/koli", "max_stars_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "k09/stest/stest01.cpp", "max_issues_repo_name": "kojiynet/koli", "max_issues_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "k09/stest/stest01.cpp", "max_forks_repo_name": "kojiynet/koli", "max_forks_repo_head_hexsha": "681f9c1b1a291a36e1f0eee43c45b37567d2661e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9776119403, "max_line_length": 106, "alphanum_fraction": 0.5853989813, "num_tokens": 1966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.737158174177441, "lm_q1q2_score": 0.6337081501308734}}
{"text": "#include <Eigen/Dense>\n\n#include <iostream>\n#include <iomanip>\n\n#include <cmath>\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 <class Func, class DFunc, class StateType>\nstd::vector<StateType> 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    // TODO: implement rosenbrock method\n}\n\n\nint main() {\n    // Final time\n    const double T = 10;\n    // All mesh sizes\n    const std::vector<int> 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\n    // Function and his Jacobian\n    // TODO: implement r.h.s. and Jacobian\n        \n    // TODO: compute reference solutions, solution, error and output approximate order of convergence\n    }\n}\n                                    \n", "meta": {"hexsha": "e504cdcbe4739ffcc7971348474f76d7bb1800b1", "size": 1493, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS14/templates_ps14/rosenbrock_template.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS14/templates_ps14/rosenbrock_template.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS14/templates_ps14/rosenbrock_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": 31.7659574468, "max_line_length": 101, "alphanum_fraction": 0.6222371065, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6336801077771275}}
{"text": "#include <boost/python.hpp>\n#include <boost/math/special_functions/ellint_1.hpp>\n#include <boost/math/special_functions/ellint_2.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <cmath>\n\n\n#define MU_0 M_PI*4e-7\n\n\n/* Functional code because making it into a class that is interfaceable with python is a massive\n   sweffort.  It will instead be used and wrapped into a python class for ease of use.\n */\n\ndouble ellipk(double _arg){\n  return boost::math::ellint_1(_arg);\n}\n\ndouble ellipe(double _arg){\n  return boost::math::ellint_2(_arg);\n}\n\n\nstd::tuple<double, double> field_from_loop(double current, double radius, double R, double Z){\n  double rho = sqrt(R*R + Z*Z);\n  double alpha = sqrt(radius*radius + rho*rho - 2*radius*R);\n  double beta = sqrt(radius*radius + rho*rho + 2*radius*R);\n  double k = sqrt(1 - (alpha*alpha)/(beta*beta));\n\n  double C = (MU_0*current)/M_PI;\n  double a = 1.0/(2*(alpha*alpha)*beta);\n  double b = Z/(2*(alpha*alpha)*beta*R);\n\n  double Bz = C*a*((radius*radius - rho*rho)*ellipe(k) + (alpha*alpha)*ellipk(k));\n  double Br = C*b*((radius*radius + rho*rho)*ellipe(k) - (alpha*alpha)*ellipk(k));\n\n  if (std::isnan(Bz) == true || std::isinf(Bz) == true){\n    Bz = 0;\n  }\n  if (std::isnan(Br) == true || std::isinf(Br) == true){\n    Br = 0;\n  }\n  \n  return std::make_tuple(Br, Bz);\n}\n\n\n\nstd::tuple<double, double> make_current_layer(int nTurns, double separation, double startPos, double current, double radius, double R, double Z){\n\n  double offset = startPos - separation;\n  double newZ = 0;\n  std::tuple<double, double> newBrBz (0, 0);\n  double totalBr = 0;\n  double totalBz = 0;\n\n  for (int i = 0; i < nTurns; i++){\n    offset += separation;\n    newZ = Z - offset;\n    newBrBz = field_from_loop(current, radius, R, newZ);\n    totalBr += std::get<0>(newBrBz);\n    totalBz += std::get<1>(newBrBz);\n  }\n  return std::make_tuple(totalBr, totalBz);\n\n}\n\n\nstd::tuple<double, double> make_coil_from_layers(int nLayers, int nTurns, double layerSep, double loopSep, double startPos, double current, double minR, double R, double Z){\n  double totalBr = 0;\n  double totalBz = 0;\n\n  std::tuple<double, double> newBrBz (0, 0);\n\n  double radius = minR - layerSep;\n\n  for (int i = 0; i < nLayers; i++){\n    radius += layerSep;\n    newBrBz = make_current_layer(nTurns, loopSep, startPos, current, radius, R, Z);\n    totalBr += std::get<0>(newBrBz);\n    totalBz += std::get<1>(newBrBz);\n  }\n  return std::make_tuple(totalBr, totalBz);\n}\n\n\nstd::tuple<double, double> make_coil(double currentDensity, double centrePos, double length, double rInner, double rOuter, int nLayers, int nTurns, double R, double Z){\n  double z1 = centrePos - 0.5*length;\n  double z2 = centrePos + 0.5*length;\n  double height = rOuter - rInner;\n\n  double loopSep = length/double(nTurns);\n  double layerSep = height/double(nLayers);\n\n  double firstLoopZ = z1 + 0.5*loopSep;\n  double firstLoopR = rInner + 0.5*layerSep;\n\n  int totalLoops = nLayers*nTurns;\n  double totalCurrent = length*height*currentDensity*1.0e6; //convert from A/mm^2 to A/m^2\n  double currentPerLoop = totalCurrent/double(totalLoops);\n\n  std::tuple<double, double> newBrBz = make_coil_from_layers(nLayers, nTurns, layerSep, loopSep, firstLoopZ, currentPerLoop, firstLoopR, R, Z);\n\n  return newBrBz;\n}\n\ndouble current_to_density(double current, double rInner, double rOuter, double length, int nLayers, int nTurns){\n  return (current*double(nLayers)*double(nTurns))/(length*(rOuter - rInner)*1e6); //in A/mm^2\n}\n\nstd::tuple<double, double, double, double, double, double> convert_to_cartesian(double r, double phi, double z, double Br, double Bphi, double Bz){\n  using namespace boost::numeric::ublas;\n  double x = r*cos(phi);\n  double y = r*sin(phi);\n  \n  //form vector of (Br, Bphi)\n  vector<double> B(2);\n  B(0) = Br; B(1) = Bphi;\n  \n  //form matrix that converts B_r/phi to B_x/y\n  matrix<double> xy_rphi(2, 2);\n  xy_rphi(0,0) = cos(phi); xy_rphi(0,1) = -1.0*sin(phi);\n  xy_rphi(1,0) = sin(phi); xy_rphi(1,1) = cos(phi);\n  \n  vector<double> Bxy = prod(xy_rphi, B);\n  \n  return std::make_tuple(x, y, z, Bxy(0), Bxy(1), Bz);\n}\n\n\nstd::tuple<double, double, double, double, double, double> convert_to_polar(double x, double y, double z, double Bx, double By, double Bz){\n  using namespace boost::numeric::ublas;\n  double r = sqrt(x*x + y*y);\n  double phi = atan2(y, x);\n\n  //form vector of (Bx, By)\n  vector<double> B(2);\n  B(0) = Bx; B(1) = By;\n\n  //form matrix that converts B_x/y to B_r/phi\n  matrix<double> rphi_xy(2, 2);\n  rphi_xy(0, 0) = cos(phi); rphi_xy(0, 1) = sin(phi);\n  rphi_xy(1, 0) = -1.0*sin(phi) ; rphi_xy(1, 1) = cos(phi);\n\n  vector<double> Brphi = prod(rphi_xy, B);\n\n  return std::make_tuple(r, phi, z, Brphi(0), Brphi(1), Bz);\n}\n\nstd::tuple<double, double, double, double, double, double> rotate(double x, double y, double z, double Bx, double By, double Bz, double thetaX, double thetaY, double px, double py, bool transpose){\n  using namespace boost::numeric::ublas;\n\n  //set up vectors for x,y,z and Bxyz to manipulate on\n  vector<double> X(3);\n  X(0) = x; X(1) = y; X(2) = z;\n\n  vector<double> B(3);\n  B(0) = Bx; B(1) = By; B(2) = Bz;\n\n  //set up offset vector\n  vector<double> offset(3);\n  offset(0) = px; offset(1) = py; offset(2) = 0;\n  \n  //set up rotation matrix\n  matrix<double> R(3, 3);\n  R(0, 0) = cos(thetaY); R(0, 1) = 0; R(0, 2) = sin(thetaY);\n  R(1, 0) = sin(thetaX)*sin(thetaY); R(1, 1) = cos(thetaX); R(1, 2) = -1.0*cos(thetaY)*sin(thetaX);\n  R(2, 0) = -1.0*sin(thetaY)*cos(thetaX); R(2, 1) = sin(thetaX); R(2, 2) = cos(thetaY)*cos(thetaX);\n\n  if (transpose == false){\n    vector<double> newX = prod(R, X) + offset;\n    vector<double> newB = prod(R, B);\n    return std::make_tuple(newX(0), newX(1), newX(2), newB(0), newB(1), newB(2));\n    \n  } else{\n    vector<double> newX = prod(trans(R), X) - offset;\n    vector<double> newB = prod(trans(R), B);\n    return std::make_tuple(newX(0), newX(1), newX(2), newB(0), newB(1), newB(2));\n  }\n}\n\n\nboost::python::tuple get_field_at_point(double current, double centrePos, double length, double rInner, double rOuter, int nLayers, int nTurns, double thetaX, double thetaY, double px, double py, double R, double PHI, double Z){\n  double currentDensity = current_to_density(current, rInner, rOuter, length, nLayers, nTurns);\n\n  //convert coords to cartesian\n  auto tmp = convert_to_cartesian(R, PHI, Z, 0, 0, 0);\n  \n  //rotate with R\n  tmp = rotate(std::get<0>(tmp), std::get<1>(tmp), std::get<2>(tmp), 0, 0, 0, thetaX, thetaY, px, py, false);\n  \n  //convert back to polar\n  tmp = convert_to_polar(std::get<0>(tmp), std::get<1>(tmp), std::get<2>(tmp), std::get<3>(tmp), std::get<4>(tmp), std::get<5>(tmp));\n  \n  //now calculate the field\n  std::tuple<double, double> newBrBz = make_coil(currentDensity, centrePos, length, rInner, rOuter, nLayers, nTurns, std::get<0>(tmp), std::get<2>(tmp));\n  \n  //convert to cartesian again INCLUDING B FIELD!!\n  auto tmp_2 = convert_to_cartesian(std::get<0>(tmp), std::get<1>(tmp), std::get<2>(tmp), std::get<0>(newBrBz), 0, std::get<1>(newBrBz));\n  \n  //Rotate with R_t\n  tmp_2 = rotate(std::get<0>(tmp_2), std::get<1>(tmp_2), std::get<2>(tmp_2), std::get<3>(tmp_2), std::get<4>(tmp_2), std::get<5>(tmp_2), thetaX, thetaY, px, py, true);\n  \n  //convert back to polars\n  tmp_2 = convert_to_polar(std::get<0>(tmp_2), std::get<1>(tmp_2), std::get<2>(tmp_2), std::get<3>(tmp_2), std::get<4>(tmp_2), std::get<5>(tmp_2));\n\n  //Should check whether the coords are the same as R, PHI, Z\n  \n  return  boost::python::make_tuple(std::get<3>(tmp_2), std::get<4>(tmp_2), std::get<5>(tmp_2));\n}\n\n//This func is like above but takes (x,y,z) as args and returns Bx, By, Bz for g4blgrid field\nboost::python::tuple get_field_at_point_xyz(double current, double centrePos, double length, double rInner, double rOuter, int nLayers, int nTurns, double thetaX, double thetaY, double px, double py, double X, double Y, double Z){\n  double currentDensity = current_to_density(current, rInner, rOuter, length, nLayers, nTurns);\n\n  auto tmp = rotate(X, Y, Z, 0, 0, 0, thetaX, thetaY, px, py, false);\n\n  tmp = convert_to_polar(std::get<0>(tmp), std::get<1>(tmp), std::get<2>(tmp), std::get<3>(tmp), std::get<4>(tmp), std::get<5>(tmp));\n\n  std::tuple<double, double> newBrBz =  make_coil(currentDensity, centrePos, length, rInner, rOuter, nLayers, nTurns, std::get<0>(tmp), std::get<2>(tmp));\n\n  auto tmp_2 = convert_to_cartesian(std::get<0>(tmp), std::get<1>(tmp), std::get<2>(tmp), std::get<0>(newBrBz), 0, std::get<1>(newBrBz));\n\n  tmp_2 = rotate(std::get<0>(tmp_2), std::get<1>(tmp_2), std::get<2>(tmp_2), std::get<3>(tmp_2), std::get<4>(tmp_2), std::get<5>(tmp_2), thetaX, thetaY, px, py, true);\n\n  return boost::python::make_tuple(std::get<3>(tmp_2), std::get<4>(tmp_2), std::get<5>(tmp_2));\n\n}\n\n\nBOOST_PYTHON_MODULE(makefield_cpp){\n  using namespace boost::python;\n  def (\"get_field_at_point\", get_field_at_point);\n  def (\"get_field_at_point_xyz\", get_field_at_point_xyz);\n}\n", "meta": {"hexsha": "2982d4d78bc90d00291c56e1973c707c181fec7c", "size": 9009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "micemag/makefields/makefield_cpp.cpp", "max_stars_repo_name": "JoeLanglands/MICE-MagneticFieldMapping", "max_stars_repo_head_hexsha": "e8d58614e8d341bffe3691574885c4148620e0f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "micemag/makefields/makefield_cpp.cpp", "max_issues_repo_name": "JoeLanglands/MICE-MagneticFieldMapping", "max_issues_repo_head_hexsha": "e8d58614e8d341bffe3691574885c4148620e0f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "micemag/makefields/makefield_cpp.cpp", "max_forks_repo_name": "JoeLanglands/MICE-MagneticFieldMapping", "max_forks_repo_head_hexsha": "e8d58614e8d341bffe3691574885c4148620e0f4", "max_forks_repo_licenses": ["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.6945606695, "max_line_length": 230, "alphanum_fraction": 0.6648906649, "num_tokens": 3107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6336263921175896}}
{"text": "#pragma once\n#include <boost/multiprecision/cpp_int.hpp>\n#include <tuple>\n#include \"utils.hpp\"\n\nnamespace mp = boost::multiprecision;\n\nnamespace rsa {\n\n    template<unsigned int N>\n    class keys {\n\n    public:\n\n        using number = typename num_utils<N>::number;\n\n        keys() {\n            std::tie(_n, _e, _d, _phi) = generate_keys();\n        }\n\n        keys(const number& n , const number& e, const number& d, const number& phi) :\n            _n(n), _e(e), _d(d), _phi(phi) {\n\n        }\n\n        static auto generate_keys() {\n            const auto p = static_cast<number>(num_utils<N / 2>::generate_random_prime());\n            const auto q = static_cast<number>(num_utils<N / 2>::generate_random_prime());\n            const auto n = p * q;\n            const auto phi = (p - 1) * (q - 1);\n            const auto rand = num_utils<N>::get_int_random(2, phi - 1);\n            auto e = rand();\n            while (mp::gcd(phi, e) != 1)\n                e = rand();\n            const auto d = num_utils<N>::bezout_identity(e, phi).first % phi;\n            return std::make_tuple(n, e, static_cast<number>(d > 0 ? d : phi + d), phi);\n        }\n\n        const auto& get_n() const {\n            return _n;\n        }\n\n        const auto& get_e() const {\n            return _e;\n        }\n        const auto& get_d() const {\n            return _d;\n        }\n        const auto& get_phi() const {\n            return _phi;\n        }\n\n    private:\n\n        number _n, _e, _d, _phi;\n\n    };\n\n}// namespace rsa\n", "meta": {"hexsha": "28f001213ff624ee9b47bc771bd580025a1fe627", "size": 1502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "keys.hpp", "max_stars_repo_name": "GoldFeniks/RSA", "max_stars_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "keys.hpp", "max_issues_repo_name": "GoldFeniks/RSA", "max_issues_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "keys.hpp", "max_forks_repo_name": "GoldFeniks/RSA", "max_forks_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_forks_repo_licenses": ["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.0333333333, "max_line_length": 90, "alphanum_fraction": 0.5126498003, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.6336263772398812}}
{"text": "#include <Eigen/Eigen>\n#include <cfloat>\n#include <iostream>\n#include \"GQ_Characterize.hpp\"\n\nGQ_Characterize::GQ_Characterize(double A, double B, double C,\n                                 double D, double E, double F,\n                                 double G, double H, double J,\n                                 double K):\n    A_(A),B_(B),C_(C),D_(D),E_(E),F_(F),G_(G),H_(H),J_(J),K_(K) {\n    //determine canonical form of GQ and determine transformation\n    make_canonical();\n}\n\n// The GQ Characterization method used here is based on work from\n// Skip Thompson at Radford university\n// https://www.radford.edu/~thompson/RP/quadrics.pdf\nvoid GQ_Characterize::make_canonical()\n{\n  // create coefficient matrix\n  Eigen::Matrix3f Aa;\n  Aa << A_, D_/2, F_/2,\n        D_/2, B_, E_/2,\n        F_/2, E_/2, C_;\n\n  // create hessian matrix\n  Eigen::Matrix4f Ac;\n  Ac << A_, D_/2, F_/2, G_/2,\n        D_/2, B_, E_/2, H_/2,\n        F_/2, E_/2, C_, J_/2,\n        G_/2,  H_/2, J_/2, K_;\n\n  // characterization values\n  int rnkAa, rnkAc, delta, S, D;\n  Eigen::FullPivLU<Eigen::Matrix3f> lu_decomp_Aa(Aa);\n  Eigen::FullPivLU<Eigen::Matrix4f> lu_decomp_Ac(Ac);\n  rnkAa = lu_decomp_Aa.rank();\n  rnkAc = lu_decomp_Ac.rank();\n\n  double determinant = Ac.determinant();\n  if (fabs(determinant) < gq_tol)\n    delta = 0;\n  else\n    delta = (determinant < 0) ? -1 : 1;\n\n  Eigen::Vector3f eigenvals;\n  Eigen::Matrix3f eigenvects;\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> AaEigs;\n  // completes Eiegen value computation, stored in AaEigs\n  AaEigs.compute(Aa, Eigen::ComputeEigenvectors);\n  eigenvals = AaEigs.eigenvalues();\n  eigenvects = AaEigs.eigenvectors();\n  Eigen::Vector3f signs;\n\n  // determine signs of the eigenvalues\n  for(unsigned int i = 0; i < 3; i++) {\n    if (eigenvals[i] > -1 * gq_tol)\n      signs[i] = 1;  //Sign counted as + if above -tolerance\n    else\n      signs[i] = -1; //Sign counted as - if less than -tolerance\n  }\n\n  // set S parameter based on agreement of eigenvalue signs\n  S = (fabs(signs.sum()) == 3) ? 1 : -1;\n\n  // may need to adjust delta for speical cases using the new scaling factor, K_\n  // so we'll calculate that now\n  Eigen::Vector3f b;\n  b << -G_/2, -H_/2, -J_/2;\n\n  // Use a Moore-Penrose pseudoinverse to ensure minimal norm least squares solution\n  // this particular inverse ensures we get the \"minimal\" translation of the GQ\n  // surface. A standard inverse may get the correct new basis set (rotation)\n  // for the GQ, but with arbitrary scaling and in turn an arbitrarily scaled\n  // translation vector\n  Eigen::Matrix3f Aai = Aa.completeOrthogonalDecomposition().pseudoInverse();\n\n  // Compute the translation from the inverse\n  Eigen::Vector3f c = Aai * b;\n  double dx = c[0], dy = c[1], dz = c[2];\n\n  // Update the constant using the resulting translation\n  K_ += (G_/2) * dx + (H_/2) * dy + (J_/2) * dz;\n\n  // For the special case of the elliptic cylinder, delta will be needed.\n  // Delta is set based on whether the sign of the equation constant, K, and the\n  // signs of the eigenvalues are the same.\n  if (rnkAa == 2 && rnkAc == 3 && S == 1) {\n    delta = (K_ * signs[0]) ? -1 : 1;\n  }\n\n  D = (K_*signs[0]) ? -1:1;\n\n  // characterize this GQ equation using the parameter values calculated above\n  type = find_type(rnkAa, rnkAc, delta, S, D);\n  // set the translation\n  translation = Vector3d(dx,dy,dz);\n  // set the rotaion matrix. LINE BELOW MAY BE UNNECESSARY but is saved in case\n  // it is needed\n  std::copy(eigenvects.data(),eigenvects.data()+9,rotation_mat);\n\n  // update equation coefficients\n  for(unsigned int i = 0; i < 3; i ++ ) if (fabs(eigenvals[i]) < gq_tol) eigenvals[i] = 0;\n  A_ = eigenvals[0]; B_ = eigenvals[1]; C_ = eigenvals[2];\n  D_ = 0; E_ = 0; F_ = 0;\n  G_ = 0; H_ = 0; J_ = 0;\n  // K is set above\n\n  // simplify the GQ if possible\n  reduce_type();\n}\n\n// this method reduces a complex GQ to a geometrically equivalent\n// and more CAD-friendly form if appropriate\nvoid GQ_Characterize::reduce_type() {\n\n  if( ONE_SHEET_HYPERBOLOID == type ) {\n    // if the K value is near-zero, reduce to Elliptic Cone\n    if ( fabs(K_) < equivalence_tol ) {\n      K_ = 0;\n      type = ELLIPTIC_CONE;\n      return;\n    }\n  }\n\n  if ( TWO_SHEET_HYPERBOLOID == type ) {\n    // if the K value is near-zero, reduce to Elliptic Cone\n    if ( fabs(K_) < equivalence_tol ) {\n      K_ = 0;\n      type = ELLIPTIC_CONE;\n      return;\n    }\n  }\n\n  if ( ELLIPSOID == type ) {\n    //if any of the 2nd order terms are near-zero, reduce to Elliptic Cylinder\n    if ( fabs(A_) < equivalence_tol ) {\n      A_ = 0;\n      type = ELLIPTIC_CYL;\n      return;\n    }\n    else if ( fabs(B_) < equivalence_tol ) {\n      B_ = 0;\n      type = ELLIPTIC_CYL;\n      return;\n    }\n    else if ( fabs(C_) < equivalence_tol ) {\n      C_ = 0;\n      type = ELLIPTIC_CYL;\n      return;\n    }\n  }\n\n};\n\nGQ_TYPE GQ_Characterize::find_type(int rt, int rf, int del, int s, int d) {\n\n  GQ_TYPE t;\n  if( 3 == rt && 4 == rf && -1 == del && 1 == s){\n    t = ELLIPSOID;\n  }\n  else if( 3 == rt && 4 == rf && 1 == del && -1 == s){\n    t = ONE_SHEET_HYPERBOLOID;\n  }\n  else if( 3 == rt && 4 == rf && -1 == del && -1 == s){\n    t = TWO_SHEET_HYPERBOLOID;\n  }\n  else if( 3 == rt && 3 == rf && 0 == del && -1 == s){\n    t = ELLIPTIC_CONE;\n  }\n  else if( 2 == rt && 4 == rf && -1 == del && 1 == s){\n    t = ELLIPTIC_PARABOLOID;\n  }\n  else if( 2 == rt && 4 == rf && 1 == del && -1 == s){\n    t = HYPERBOLIC_PARABOLOID;\n  }\n  else if( 2 == rt && 3 == rf && -1 == del && 1 == s){\n    t = ELLIPTIC_CYL;\n  }\n  else if( 2 == rt && 3 == rf && 0 == del && -1 == s){\n    t = HYPERBOLIC_CYL;\n  }\n  else if( 1 == rt && 3 == rf && 0 == del && 1 == s){\n    t = PARABOLIC_CYL;\n  }\n  else{\n    t = UNKNOWN;\n  }\n\n  //special case, replace delta with D\n  if(2 == rt && 3 == rf && 1 == s && d != 0) {\n    t = find_type(rt, rf, d, s, 0);\n  }\n\n  return t;\n}\n", "meta": {"hexsha": "0f5ba0e08dd733034eb6335b182f96610a334a1a", "size": 5838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GQ_Characterize.cpp", "max_stars_repo_name": "gonuke/mcnp2cad", "max_stars_repo_head_hexsha": "18bd8b6f70ed02cb8bb8cb5e34f8e5eef6af494a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-09-11T08:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:10:01.000Z", "max_issues_repo_path": "GQ_Characterize.cpp", "max_issues_repo_name": "gonuke/mcnp2cad", "max_issues_repo_head_hexsha": "18bd8b6f70ed02cb8bb8cb5e34f8e5eef6af494a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-01-24T18:21:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-25T11:30:23.000Z", "max_forks_repo_path": "GQ_Characterize.cpp", "max_forks_repo_name": "gonuke/mcnp2cad", "max_forks_repo_head_hexsha": "18bd8b6f70ed02cb8bb8cb5e34f8e5eef6af494a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2015-01-31T19:25:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-29T13:58:29.000Z", "avg_line_length": 29.6345177665, "max_line_length": 90, "alphanum_fraction": 0.5957519699, "num_tokens": 1998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6336263771788505}}
{"text": "// Petter Strandmark 2012\u20132013.\n#include <array>\n#include <limits>\n\n#include <Eigen/Dense>\n\n#include <spii/solver.h>\n\nnamespace spii {\n\nnamespace\n{\n\t// constexpr when supported.\n\tconst double nan = std::numeric_limits<double>::quiet_NaN();\n}\n\ndouble\npolynomial_interpolation(std::array<double, 2> x,\n                         std::array<double, 2> f,\n                         std::array<double, 2> df,\n                         double xmin = nan, double xmax = nan)\n{\n\tint minpos = 0;\n\tif (x[1] < x[0]) {\n\t\tminpos = 1;\n\t}\n\tint maxpos = 1 - minpos;\n\n\tif (xmin != xmin) {\n\t\txmin = x[minpos];\n\t}\n\tif (xmax != xmax) {\n\t\txmax = x[maxpos];\n\t}\n\n\tauto d1 = df[minpos] + df[maxpos] - 3*(f[minpos] - f[maxpos]) / (x[minpos] - x[maxpos]);\n\tauto inside_sqrt = d1*d1 - df[0]*df[1];\n\tif (inside_sqrt >= 0) {\n\t\tauto d2 = std::sqrt(inside_sqrt);\n\t\tauto t = x[maxpos] - (x[maxpos] - x[minpos])*((df[maxpos] + d2 - d1)/(df[maxpos] - df[minpos] + 2*d2));\n\t\treturn std::min(std::max(t, xmin), xmax);\n\t}\n\telse {\n\t\treturn (xmin + xmax) / 2;\n\t}\n}\n\ndouble perform_Wolfe_linesearch(const Solver& solver,\n                                const Function& function,\n                                const Eigen::VectorXd& x,\n                                const double fval,\n                                const Eigen::VectorXd& g,\n                                const Eigen::VectorXd& p,\n                                Eigen::VectorXd* scratch,\n                                const double start_alpha)\n{\n\tEigen::VectorXd g_prev = g;\n\tauto f = function.evaluate(x);\n\tauto f_prev = f;\n\tdouble gtp = g.dot(p);\n\tauto gtp_prev = gtp;\n\n\tauto n = x.size();\n\tEigen::VectorXd g_new(n);  // TODO: Somehow use scratch space.\n\n\tdouble alpha = start_alpha;\n\tdouble alpha_prev = 0;\n\n\t*scratch = x + alpha * p;\n\tdouble f_new = function.evaluate(*scratch, &g_new);\n\tdouble gtp_new  = g_new.dot(p);\n\n\t//\n\tauto c1 = solver.line_search_c;\n\tauto c2 = solver.line_search_c2;\n\t//\n\n\tstd::array<double, 2> bracket;\n\tstd::array<double, 2> bracket_fval;\n\tstd::array<double, 2> bracket_gTpval;\n\tbool done = false;\n\n\t//\n\t// Bracketing phase.\n\t//\n\tint iterations = 0;\n\tconst int max_iterations = 30;\n\twhile (iterations <= max_iterations) {\n\n\t\tif (f_new > f + c1 * alpha * gtp || (iterations > 1 && f_new >= f_prev)) {\n\t\t\t// Double braces for GCC 4.7 compatibility. Remove later.\n\t\t\tbracket        = {{alpha_prev, alpha}};\n\t\t\tbracket_fval   = {{f_prev, f_new}};\n\t\t\tbracket_gTpval = {{ g_prev.dot(p), g_new.dot(p)}};\n\t\t\tbreak;\n\t\t}\n\t\telse if (std::abs(gtp_new) <= -c2 * gtp) {\n\t\t\t// We are done.\n\t\t\treturn alpha;\n\t\t}\n\t\telse if (gtp_new >= 0) {\n\t\t\t// Double braces for GCC 4.7 compatibility. Remove later.\n\t\t\tbracket        = {{alpha_prev, alpha}};\n\t\t\tbracket_fval   = {{f_prev, f_new}};\n\t\t\tbracket_gTpval = {{g_prev.dot(p), g_new.dot(p)}};\n\t\t\tbreak;\n\t\t}\n\n\t\tdouble temp = alpha_prev;\n\t\talpha_prev = alpha;\n\t\tdouble minStep = alpha + 0.01*(alpha - temp);\n\t\tdouble maxStep = 10 * alpha;\n\n\t\tif (solver.wolfe_interpolation_strategy == Solver::BISECTION) {\n\t\t\talpha = maxStep;\n\t\t}\n\t\telse {\n\t\t\t// Double braces for GCC 4.7 compatibility. Remove later.\n\t\t\talpha = polynomial_interpolation({{temp, alpha}},\n\t\t\t                                 {{f_prev, f_new}},\n\t\t\t                                 {{gtp_prev, gtp_new}},\n\t\t\t                                 minStep, maxStep);\n\t\t}\n\n\t\tf_prev = f_new;\n\t\tg_prev = g_new;\n\t\tgtp_prev = gtp_new;\n\n\t\t*scratch = x + alpha * p;\n\t\tf_new = function.evaluate(*scratch, &g_new);\n\t\tgtp_new  = g_new.dot(p);\n\n\t\titerations++;\n\t}\n\n\t//\n\t// Zoom phase.\n\t//\n\tbool insufficient_progress = false;\n\twhile (!done && iterations <= max_iterations) {\n\n\t\t// Compute new trial value.\n\t\tif (solver.wolfe_interpolation_strategy == Solver::BISECTION) {\n\t\t\talpha = (bracket[0] + bracket[1]) / 2.0;\n\t\t}\n\t\telse {\n\t\t\talpha = polynomial_interpolation(bracket,\n\t\t\t                                 bracket_fval,\n\t\t\t                                 bracket_gTpval);\n\t\t}\t \n\n\t\tauto max_bracket = std::max({bracket[0], bracket[1]});\n\t\tauto min_bracket = std::min({bracket[0], bracket[1]});\n\n\t\tif (std::min({max_bracket-alpha, alpha-min_bracket}) / (max_bracket - min_bracket) < 0.1) {\n\t\t\tif (insufficient_progress || alpha >= max_bracket || alpha <= min_bracket) {\n\t\t\t\tif (std::abs(alpha - max_bracket) < std::abs(alpha - min_bracket)) {\n\t\t\t\t\talpha = max_bracket - 0.1*(max_bracket - min_bracket);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\talpha = min_bracket + 0.1*(max_bracket - min_bracket);\n\t\t\t\t}\n\t\t\t\tinsufficient_progress = false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tinsufficient_progress = true;\n\t\t\t}\n\t\t}\n\n\t\t*scratch = x + alpha * p;\n\t\tf_new = function.evaluate(*scratch, &g_new);\n\t\tgtp_new  = g_new.dot(p);\n\n\t\tint lo_pos, hi_pos;\n\t\tdouble f_low;\n\t\tif (bracket_fval[0] < bracket_fval[1]) {\n\t\t\tf_low = bracket_fval[0];\n\t\t\tlo_pos = 0;\n\t\t\thi_pos = 1;\n\t\t}\n\t\telse {\n\t\t\tf_low = bracket_fval[1];\n\t\t\tlo_pos = 1;\n\t\t\thi_pos = 0;\n\t\t}\n\n\t\tbool armijo = f_new < f + c1 * alpha * gtp;\n\n\t\tif (!armijo || f_new >= f_low) {\n\t\t\t// Armijo condition not satisfied or not lower than lowest\n\t\t\t// point\n\t\t\tbracket[hi_pos]        = alpha;\n\t\t\tbracket_fval[hi_pos]   = f_new;\n\t\t\tbracket_gTpval[hi_pos] = g_new.dot(p);\n\t\t}\n\t\telse {\n\t\t\tif (std::abs(gtp_new) <= - c2*gtp) {\n\t\t\t\t// Wolfe conditions satisfied\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t\telse if (gtp_new * (bracket[hi_pos] - bracket[lo_pos]) >= 0) {\n\t\t\t\t// Old HI becomes new LO\n\t\t\t\tbracket[hi_pos]        = bracket[lo_pos];\n\t\t\t\tbracket_fval[hi_pos]   = bracket_fval[lo_pos];\n\t\t\t\tbracket_gTpval[hi_pos] = bracket_gTpval[lo_pos];\n\t\t\t}\n\n\t\t\t// New point becomes new LO\n\t\t\tbracket[lo_pos]        = alpha;\n\t\t\tbracket_fval[lo_pos]   = f_new;\n\t\t\tbracket_gTpval[lo_pos] = g_new.dot(p);\n\t\t}\n\n\t\titerations++;\n\t}\n\t\n\tif (!done) {\n\t\tif (solver.log_function) {\n\t\t\tsolver.log_function(\"Wolfe line search maximum iterations exceeded.\");\n\t\t}\n\t\treturn 0.0;\n\t}\n\n\tif (bracket_fval[0] < bracket_fval[1]) {\n\t\talpha = bracket[0];\n\t}\n\telse {\n\t\talpha = bracket[1];\n\t}\n\n\treturn alpha;\n}\n\ndouble perform_Armijo_linesearch(const Solver& solver,\n                                 const Function& function,\n                                 const Eigen::VectorXd& x,\n                                 const double fval,\n                                 const Eigen::VectorXd& g,\n                                 const Eigen::VectorXd& p,\n                                 Eigen::VectorXd* scratch,\n                                 const double start_alpha)\n{\n\t//\n\t// Perform back-tracking line search.\n\t//\n\n\t// Starting value for alpha during line search. Newton and\n\t// quasi-Newton methods should choose 1.0.\n\tdouble alpha = start_alpha;\n\tdouble rho = solver.line_search_rho;\n\tdouble c = solver.line_search_c;\n\tdouble gTp = g.dot(p);\n\tif (gTp != gTp) {\n\t\tif (solver.log_function) {\n\t\t\tsolver.log_function(\"Backtracking encountered NaN, returning zero step.\");\n\t\t}\n\t\treturn 0.0;\n\t}\n\n\tint backtracking_attempts = 0;\n\twhile (true) {\n\t\t*scratch = x + alpha * p;\n\t\tdouble lhs = function.evaluate(*scratch);\n\t\tdouble rhs = fval + c * alpha * gTp;\n\t\tif (lhs <= rhs) {\n\t\t\tbreak;\n\t\t}\n\t\talpha *= rho;\n\n\t\tbacktracking_attempts++;\n\t\tif (backtracking_attempts > 1000) {\n\t\t\tif (solver.log_function) {\n\t\t\t\tsolver.log_function(\"Backtracking failed, returning zero step.\");\n\t\t\t}\n\t\t\treturn 0.0;\n\t\t}\n\t}\n\n\treturn alpha;\n}\n\ndouble Solver::perform_linesearch(const Function& function,\n                                  const Eigen::VectorXd& x,\n                                  const double fval,\n                                  const Eigen::VectorXd& g,\n                                  const Eigen::VectorXd& p,\n                                  Eigen::VectorXd* scratch,\n                                  const double start_alpha) const\n{\n\tif (this->line_search_type == ARMIJO) {\n\t\treturn perform_Armijo_linesearch(*this, function, x, fval, g, p, scratch, start_alpha);\n\t}\n\telse {\n\t\treturn perform_Wolfe_linesearch(*this, function, x, fval, g, p, scratch, start_alpha);\n\t}\n}\n\n}  // namespace spii\n", "meta": {"hexsha": "ebd06428c7641d0b76c0a3873324ac5926664a32", "size": 7875, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/solver_line_search.cpp", "max_stars_repo_name": "PetterS/spii", "max_stars_repo_head_hexsha": "98c5847223d7c3febea5a1aac6f4978dfef207ec", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T16:21:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T08:02:12.000Z", "max_issues_repo_path": "source/solver_line_search.cpp", "max_issues_repo_name": "nashdingsheng/spii", "max_issues_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-07-16T14:41:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-09T19:27:22.000Z", "max_forks_repo_path": "source/solver_line_search.cpp", "max_forks_repo_name": "nashdingsheng/spii", "max_forks_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-09-21T23:09:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T20:20:30.000Z", "avg_line_length": 26.3377926421, "max_line_length": 105, "alphanum_fraction": 0.5713015873, "num_tokens": 2219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.63360200025742}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nusing namespace std; \nnamespace ublas = boost::numeric::ublas;\n\nint main() {\n    ublas::vector<double> v1(3), v2(3);\n    for (unsigned i = 0; i < 3; ++i)\n        v1 (i) = i, v2 (i) = i*10;\n\n    cout << v1 << endl\n        << v2 << endl\n        << outer_prod(v1, v2) << endl;\n}\n", "meta": {"hexsha": "3fc1a5c9327da64b8a5f11bd76b2adc6ecef80c0", "size": 357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "practice/matrix2.cpp", "max_stars_repo_name": "ShiZhan/graph-study", "max_stars_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-14T07:27:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-15T03:11:31.000Z", "max_issues_repo_path": "practice/matrix2.cpp", "max_issues_repo_name": "Zhan2012/graph-study", "max_issues_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practice/matrix2.cpp", "max_forks_repo_name": "Zhan2012/graph-study", "max_forks_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3125, "max_line_length": 41, "alphanum_fraction": 0.5602240896, "num_tokens": 125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6335926163647947}}
{"text": "#include \"Mesh3D.hpp\"\n\n#include <Eigen/Geometry>\n\nfloat noob::mesh_3d::get_volume()\n{\n\tif (!volume_calculated)\n\t{\n\t\t// Proudly gleaned from U of R website!\n\t\t// http://mathcentral.uregina.ca/QQ/database/QQ.09.09/h/ozen1.html\n\t\t// The volume of the tetrahedron with vertices (0 ,0 ,0), (a1 ,a2 ,a3), (b1, b2, b3) and (c1, c2, c3) is [a1b2c3 + a2b3c1 + a3b1c2 - a1b3c2 - a2b1c3 - a3b2c1] / 6.\n\t\tdouble accum = 0.0;\n\t\tfor (uint32_t i = 0; i < indices.size(); i += 3)\n\t\t{\n\t\t\tconst noob::vec3f first = vertices[i].position;\n\t\t\tconst noob::vec3f second = vertices[i+1].position;\n\t\t\tconst noob::vec3f third = vertices[i+2].position;\n\n\t\t\taccum += ((first[0] * second[1] * third[2]) + (first[1] * second[2] * third[0]) + (first[2] * second[0] * third.v[1]) - (first[0] * second.v[2] * third.v[1]) - (first.v[1] * second[0] * third.v[2]) - (first[2] * second[1] * third.v[0])) / 6.0;\n\n\t\t}\n\n\t\tvolume_calculated = true;\n\t\tvolume = static_cast<float>(accum);\n\t}\n\n\treturn volume;\n}\n\n\nvoid noob::mesh_3d::calculate_dims() noexcept(true)\n{\n\tif (vertices.size() > 0)\n\t{\n\t\tbbox.min = bbox.max = vertices[0].position;\n\t\tfor (noob::mesh_3d::vert v : vertices)\n\t\t{\n\t\t\tbbox.min[0] = std::min(bbox.min[0], v.position[0]);\n\t\t\tbbox.min[1] = std::min(bbox.min[1], v.position[1]);\n\t\t\tbbox.min[2] = std::min(bbox.min[2], v.position[2]);\n\t\t\tbbox.max[0] = std::max(bbox.max[0], v.position[0]);\n\t\t\tbbox.max[1] = std::max(bbox.max[1], v.position[1]);\n\t\t\tbbox.max[2] = std::max(bbox.max[2], v.position[2]);\n\t\t}\n\t}\n}\n\n\n\n\n\n/*\n   void noob::mesh_3d::to_origin()\n   {\n   noob::vec3f dims = bbox.get_dims();\n   for (size_t i = 0; i < vertices.size(); ++i)\n   {\n   vertices[i] = (vertices[i] + dims);\n   }\n   }\n\n   std::string noob::mesh_3d::save() const\n   {\n   fmt::MemoryWriter w;\n   w << \"OFF\" << \"\\n\" << vertices.size() << \" \" << indices.size() / 3 << \" \" << 0 <<  \"\\n\";\n   for (auto v : vertices)\n   {\n   w << v.v[0] << \" \" << v.v[1] << \" \" << v.v[2] <<  \"\\n\";\n   }\n   for (size_t i = 0; i < indices.size(); i = i + 3)\n   {\n   w << 3 << \" \" << indices[i] << \" \" << indices[i+1] << \" \" << indices[i+2] << \"\\n\";\n   }\n\n   return w.str();\n   }\n\n   void noob::mesh_3d::save(const std::string& filename) const\n   {\n\n   }\n   */\n\n\n", "meta": {"hexsha": "3197bda77f71a989d2a536ec7d037573f7419128", "size": 2190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "engine/common/Mesh3D.cpp", "max_stars_repo_name": "ColinGilbert/noobwerkz-engine", "max_stars_repo_head_hexsha": "f5670e98ca0dada8865be9ab82d25d3acf549ebe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-03-02T10:56:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T03:32:49.000Z", "max_issues_repo_path": "engine/common/Mesh3D.cpp", "max_issues_repo_name": "ColinGilbert/noobwerkz-engine-borked", "max_issues_repo_head_hexsha": "f5670e98ca0dada8865be9ab82d25d3acf549ebe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 73.0, "max_issues_repo_issues_event_min_datetime": "2015-04-14T09:39:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-11T21:49:10.000Z", "max_forks_repo_path": "engine/common/Mesh3D.cpp", "max_forks_repo_name": "ColinGilbert/noobwerkz-engine-borked", "max_forks_repo_head_hexsha": "f5670e98ca0dada8865be9ab82d25d3acf549ebe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-02-22T01:29:32.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-02T06:07:12.000Z", "avg_line_length": 25.7647058824, "max_line_length": 246, "alphanum_fraction": 0.5543378995, "num_tokens": 846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6335173944370995}}
{"text": "#include <iostream>\n#include <cstdio>\n#include <armadillo>\n#include <random>\n\n#include \"histograms.hh\"\n\nusing namespace std;\nusing namespace arma;\n\n/**\n * Save histogram data to file.\n *\n * Will save file with four data points for each histogram bin:\n *  bin_start     Low edge of bin\n *  bin_end       High edge of bin\n *  count         Absolute count of values in bin\n *  relcount      Relative count (i.e., divided by total number of values)\n *\n * Arguments:\n *  v           - Vector containing all values\n *  dm          - Bin width\n *  filename    - Name of file to save to\n**/\nvoid save_histogram(const vector<double> &v, double dm, const char *filename) {\n  // create armadillo vector from std::vector\n  vec m(v);\n\n  double mmin = 0, mmax = m.max();\n  size_t nbins = ceil((mmax - mmin) / dm);\n  size_t total = m.n_elem;\n\n  vec bin_edges(nbins + 1);\n  for(size_t i = 0; i <= nbins; i++)\n    bin_edges[i] = mmin + dm * i;\n\n  uvec bins = histc(m, bin_edges);\n\n  // save histogram bins to file\n  FILE *fp = fopen(filename, \"w\");\n  fprintf(fp, \"m_start\\tm_end\\tcount\\trelcount\\n\");\n  for(size_t i = 0; i < nbins; i++) {\n    int count = bins(i);\n    fprintf(fp, \"%.3E\\t%.3E\\t%d\\t%.3E\\n\", bin_edges(i), bin_edges(i + 1), count, (double)count / total);\n  }\n  fprintf(fp, \"%.3E\\t%.3E\\t%d\\t%.3E\\n\", bin_edges(nbins), bin_edges(nbins), 0, 0.0);\n}\n", "meta": {"hexsha": "540017c472b72e8ec061ec9bf37793ff09e7cd93", "size": 1343, "ext": "cc", "lang": "C++", "max_stars_repo_path": "project5/code/histograms.cc", "max_stars_repo_name": "frxstrem/fys3150", "max_stars_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project5/code/histograms.cc", "max_issues_repo_name": "frxstrem/fys3150", "max_issues_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project5/code/histograms.cc", "max_forks_repo_name": "frxstrem/fys3150", "max_forks_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9791666667, "max_line_length": 104, "alphanum_fraction": 0.625465376, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6335040011348443}}
{"text": "// https://www.codechef.com/problems/FCTRL2/\n#include<iostream>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\n\nusing namespace std;\nint main()\n{\n    int t,i,a;\n    cin>>t;\n    for(i=0;i<t;i++){\n        cin>>a;\n        cpp_int fact;\n        fact=1;\n        for(int j=1;j<=a;j++){\n            fact*=j;\n        }\n        cout<<fact<<endl;\n\n    }\n    return 0;\n}", "meta": {"hexsha": "a3fc0901f73f5dcecc2dbc3a05712a635a1f72c3", "size": 395, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CodeChef/FCTRL2.cpp", "max_stars_repo_name": "Srimanta11/DSA_Practice_Questions", "max_stars_repo_head_hexsha": "c01cee6f6fbffa1e8c5edd7199079181fce0bbdc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-10-11T04:38:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-16T04:42:46.000Z", "max_issues_repo_path": "CodeChef/FCTRL2.cpp", "max_issues_repo_name": "Sayan3990/DSA_Practice_Questions", "max_issues_repo_head_hexsha": "c01cee6f6fbffa1e8c5edd7199079181fce0bbdc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-12T01:42:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-22T03:31:25.000Z", "max_forks_repo_path": "CodeChef/FCTRL2.cpp", "max_forks_repo_name": "Sayan3990/DSA_Practice_Questions", "max_forks_repo_head_hexsha": "c01cee6f6fbffa1e8c5edd7199079181fce0bbdc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-10-11T04:57:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-22T03:40:12.000Z", "avg_line_length": 17.9545454545, "max_line_length": 44, "alphanum_fraction": 0.5417721519, "num_tokens": 108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095992, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6335039945915202}}
{"text": "#pragma once\n\n#include <vector>\n#include <algorithm>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include <unsupported/Eigen/MatrixFunctions>\n\nusing std::vector;\nusing Eigen::MatrixXf;\n\nclass MultiwayMatcher{\n\npublic:\n\tMultiwayMatcher();\n\t~MultiwayMatcher();\n\tvoid initialize(Eigen::MatrixXf A, vector<unsigned> numSmp);\n\tvoid set_verbose(bool verbose);\n\n\tvoid estimate_universe_size();\n\tvoid CLEAR();\n\tvoid get_X(Eigen::MatrixXf& X);\n\tvoid get_Y(Eigen::MatrixXf& Y);\n\tvoid get_assignments(vector<int>& assignments);\n\tvoid get_fused_counts(vector<unsigned>& fused_counts);\n\tvoid save_data();\n\nprivate:\n\tvoid construct_D();\n\tvoid construct_L();\n\tvoid construct_Lnrm();\n\n\tvector<unsigned> numSmp_;\n\tvector<unsigned> cumSum_;\n\n\tEigen::SparseMatrix<float> A_sp;\n\tEigen::SparseMatrix<float> D_sp;\n\tEigen::SparseMatrix<float> L_sp;\n\tEigen::SparseMatrix<float> Lnrm_sp;\n\n\n\t// MatrixXf A_;\n\t// MatrixXf D_;\n\t// MatrixXf L_;\n\tMatrixXf Lnrm_; // Normalized Laplacian\n\tMatrixXf sl_; // vector of singular values of Lnrm_ (decreasing order)\n\tMatrixXf Vl_; // right singular vectors of Lnrm_\n\tMatrixXf N_; // embedding matrix (CLEAR)\n\tMatrixXf C_; // cluster centers (CLEAR)\n\tMatrixXf Y_; // lifting permutation (CLEAR)\n\tMatrixXf X_; // optimized pairwise permutations (CLEAR)\n\n\tunsigned m_; // estimated size of the universe\n\tvector<int> assignments_; // assignment of each local observation to the universe \n\tvector<unsigned> fused_counts_; // observation count of each global object\n\n\t// threshold for estimating universe size\n\tdouble thresh_ = 0.50;\n\n\tbool verbose_ = true;\n\n\n};", "meta": {"hexsha": "80dc1dab22ed9f78d486d87fd8049e11767d43aa", "size": 1598, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/clear/MultiwayMatcher.hpp", "max_stars_repo_name": "NamDinhRobotics/clear-fusion", "max_stars_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:53.000Z", "max_issues_repo_path": "include/clear/MultiwayMatcher.hpp", "max_issues_repo_name": "NamDinhRobotics/clear-fusion", "max_issues_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/clear/MultiwayMatcher.hpp", "max_forks_repo_name": "NamDinhRobotics/clear-fusion", "max_forks_repo_head_hexsha": "bde1af066db655f2c308f7afdf143287e634dca5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.96875, "max_line_length": 83, "alphanum_fraction": 0.7490613267, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.633479087054953}}
{"text": "/* \n * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <votca/tools/cubicspline.h>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <votca/tools/linalg.h>\n#include <iostream>\n#include <cmath>\n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\nvoid CubicSpline::Interpolate(ub::vector<double> &x, ub::vector<double> &y)\n{    \n    if(x.size() != y.size())\n        throw std::invalid_argument(\"error in CubicSpline::Interpolate : sizes of vectors x and y do not match\");\n    \n    if(x.size()<3)\n        throw std::invalid_argument(\"error in CubicSpline::Interpolate : vectors x and y have to contain at least 3 points\");\n\n    const int N = x.size();\n    \n    // adjust the grid\n    _r.resize(N);\n    _f.resize(N);\n    _f2.resize(N);\n    \n    // create vector proxies to individually access f and f''\n\n    // copy the grid points into f\n    _r = x;\n    _f = y;\n    _f2 = ub::zero_vector<double>(N);\n    \n    // not calculate the f''\n    ub::matrix<double> A(N, N);\n    A = ub::zero_matrix<double>(N,N);\n    \n    for(int i=0; i<N - 2; ++i) {\n            _f2(i+1) = -( A_prime_l(i)*_f(i)\n            + (B_prime_l(i) - A_prime_r(i)) * _f(i+1)\n            -B_prime_r(i) * _f(i+2));\n\n            A(i+1, i) = C_prime_l(i);\n            A(i+1, i+1) = D_prime_l(i) - C_prime_r(i);\n            A(i+1, i+2) = -D_prime_r(i);\n    }\n    \n    switch(_boundaries) {\n        case splineNormal:\n            A(0, 0) = 1;\n            A(N - 1, N-1) = 1;\n            break;\n        case splinePeriodic:\n            A(0,0) = 1; A(0,N-1) = -1;\n            A(N-1,0) = 1; A(N-1,N-1) = -1;\n            break;\n        case splineDerivativeZero:\n\t    throw std::runtime_error(\"erro in CubicSpline::Interpolate: case splineDerivativeZero not implemented yet\");\n\t    break;\n    }\n\n    votca::tools::linalg_qrsolve(_f2, A, _f2);\n}\n\nvoid CubicSpline::Fit(ub::vector<double> &x, ub::vector<double> &y)\n{\n    if(x.size() != y.size())\n        throw std::invalid_argument(\"error in CubicSpline::Fit : sizes of vectors x and y do not match\");\n    \n    const int N = x.size();\n    const int ngrid = _r.size();\n    \n    // construct the equation\n    // A*u = b\n    // where u = { {f[i]}, {f''[i]} }\n    // and b[i] = y[i] for 0<=i<N\n    // and b[i]=0 for i>=N (for smoothing condition)\n    // A[i,j] contains the data fitting + the spline smoothing conditions\n    \n    ub::matrix<double> A(N, 2*ngrid);\n    ub::vector<double> b(N);    \n    ub::matrix<double> B_constr(ngrid, 2*ngrid);  // Matrix with smoothing conditions\n\n    A = ub::zero_matrix<double>(N, 2*ngrid);\n    b  = ub::zero_vector<double>(N);\n    B_constr = ub::zero_matrix<double>(ngrid, 2*ngrid);\n    \n    // Construct smoothing matrix\n    AddBCToFitMatrix(B_constr, 0);\n\n    // construct the matrix to fit the points and the vector b\n    AddToFitMatrix(A, x, 0);\n    b = -y; // why is it -y?\n\n    // now do a constrained qr solve\n    ub::vector<double> sol(2*ngrid);\n    votca::tools::linalg_constrained_qrsolve(sol, A, b, B_constr);\n\n    // check vector \"sol\" for nan's\n    for(int i=0; i<2*ngrid; i++) {\n        if( (isinf(sol(i))) || (isnan(sol(i))) ) {\n            throw std::runtime_error(\"error in CubicSpline::Fit : value nan occurred due to wrong fitgrid boundaries\");\n        }\n    }\n\n    _f = ub::vector_range<ub::vector<double> >(sol, ub::range (0, ngrid));\n    _f2 = ub::vector_range<ub::vector<double> >(sol, ub::range (ngrid, 2*ngrid));\n}\n\n}}\n", "meta": {"hexsha": "b0641dd72111833320f9b7876a16932a49146a20", "size": 4076, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/cubicspline.cc", "max_stars_repo_name": "vaidyanathanms/votca.tools", "max_stars_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libtools/cubicspline.cc", "max_issues_repo_name": "vaidyanathanms/votca.tools", "max_issues_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libtools/cubicspline.cc", "max_forks_repo_name": "vaidyanathanms/votca.tools", "max_forks_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5968992248, "max_line_length": 125, "alphanum_fraction": 0.6035328754, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6333129153007327}}
{"text": "// Boost.Geometry\n// QuickBook Example\n\n// Copyright (c) 2021, 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//[azimuth_strategy\n//` Shows how to calculate azimuth in geographic coordinate system\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n\nint main()\n{\n    namespace bg = boost::geometry;\n    typedef bg::model::point<double, 2, bg::cs::geographic<bg::degree> > point_type;\n\n    point_type p1(0, 0);\n    point_type p2(1, 1);\n\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\n    bg::strategies::azimuth::geographic<> strategy(spheroid);\n\n    auto azimuth = boost::geometry::azimuth(p1, p2, strategy);\n\n    std::cout << \"azimuth: \" << azimuth << std::endl;\n\n    return 0;\n}\n\n//]\n\n//[azimuth_strategy_output\n/*`\nOutput:\n[pre\nazimuth: 0.788674\n]\n*/\n//]\n", "meta": {"hexsha": "2a8ef5178f3fc261ee04683752d7e496b4aebd2a", "size": 1071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "console/src/boost_1_78_0/libs/geometry/doc/src/examples/algorithms/azimuth_strategy.cpp", "max_stars_repo_name": "vany152/FilesHash", "max_stars_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "console/src/boost_1_78_0/libs/geometry/doc/src/examples/algorithms/azimuth_strategy.cpp", "max_issues_repo_name": "vany152/FilesHash", "max_issues_repo_head_hexsha": "39f282807b7f1abc56dac389e8259ee3bb557a8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/geometry/doc/src/examples/algorithms/azimuth_strategy.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": 22.7872340426, "max_line_length": 84, "alphanum_fraction": 0.700280112, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6333129047969865}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Andres Hernandez\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file levyflightdistribution.hpp\n    \\brief Levy Flight, aka Pareto Type I, distribution as needed by Boost Random\n*/\n\n#ifndef quantlib_levy_flight_distribution_hpp\n#define quantlib_levy_flight_distribution_hpp\n\n#include <ql/types.hpp>\n#include <ql/errors.hpp>\n#include <boost/config/no_tr1/cmath.hpp>\n#include <boost/random/detail/config.hpp>\n#include <boost/random/detail/operators.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <iosfwd>\n\nnamespace QuantLib {\n\n    //! Levy Flight distribution as needed by Boost Random\n    /*! The levy flight distribution is a random distribution with \n        the following form:\n        \\f[\n        p(x) = \\frac{\\alpha x_m^{\\alpha}}{x^{\\alpha+1}}\n        \\f]\n        with support over \\f$ x \\in [x_m, \\infty) \\f$\n        and the parameter \\f$ \\alpha > 0 \\f$.\n\n        Levy Flight is normally defined as \\f$ x_m = 1 \\f$ and \\f$ 0 <\n        \\alpha < 2 \\f$, which is where \\f$ p(x) \\f$ has an infinite\n        variance. However, the more general version, known as Pareto\n        Type I, is well defined for \\f$ \\alpha > 2 \\f$, so the current\n        implementation does not restrict \\f$ \\alpha \\f$ to be smaller\n        than 2.\n    */\n    class LevyFlightDistribution\n    {\n      public:\n        typedef Real input_type;\n        typedef Real result_type;\n\n        class param_type\n        {\n          public:\n\n            typedef LevyFlightDistribution distribution_type;\n\n            /*!    Constructs parameters with a given xm and alpha\n                Requires: alpha > 0\n            */\n            param_type(Real xm = 1.0, Real alpha = 1.0)\n              : xm_(xm), alpha_(alpha) { QL_REQUIRE(alpha_ > 0.0, \"alpha must be larger than 0\"); }\n\n            //! Returns the xm parameter of the distribution\n            Real xm() const { return xm_; }\n            \n            //! Returns the alpha parameter of the distribution\n            Real alpha() const { return alpha_; }\n\n            //! Writes the parameters to a @c std::ostream\n            BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\n            {\n                os << parm.xm_ << \" \" << parm.alpha_;\n                return os;\n            }\n            \n            //! Reads the parameters from a @c std::istream\n            BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\n            {\n                is >> parm.xm_ >> std::ws >> parm.alpha_;\n                return is;\n            }\n\n            //! Returns true if the two sets of parameters are equal\n            BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\n            { return lhs.xm_ == rhs.xm_ && lhs.alpha_ == rhs.alpha_; }\n\n            //! Returns true if the two sets of parameters are different\n            BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\n\n        private:\n            Real xm_;\n            Real alpha_;\n        };\n\n        //! \\name Constructors\n        //@{\n        /*! Constructs a LevyFlightDistribution with a given xm and alpha\n            Requires: alpha > 0\n        */\n        explicit LevyFlightDistribution(Real xm = 1.0, Real alpha = 1.0)\n          : xm_(xm), alpha_(alpha) { QL_REQUIRE(alpha_ > 0.0, \"alpha must be larger than 0\"); }\n\n        //!Constructs a LevyFlightDistribution from its parameters\n        explicit LevyFlightDistribution(const param_type& parm)\n          : xm_(parm.xm()), alpha_(parm.alpha()) {}\n\n        // compiler-generated copy ctor and assignment operator are fine\n        //@}\n\n        //! \\name Inspectors\n        //@{\n        //! Returns the xm parameter of the distribution\n        Real xm() const { return xm_; }\n            \n        //! Returns the alpha parameter of the distribution\n        Real alpha() const { return alpha_; }\n\n        //! Returns the smallest value that the distribution can produce\n        Real min BOOST_PREVENT_MACRO_SUBSTITUTION () const\n        { return xm_; }\n        //! Returns the largest value that the distribution can produce\n        Real max BOOST_PREVENT_MACRO_SUBSTITUTION () const\n        { return QL_MAX_REAL; }\n\n        //! Returns the parameters of the distribution\n        param_type param() const { return {xm_, alpha_}; }\n        //@}\n        \n        //! Sets the parameters of the distribution\n        void param(const param_type& parm) { \n            xm_ = parm.xm();\n            alpha_ = parm.alpha();\n        }\n\n        /*! Effects: Subsequent uses of the distribution do not depend\n            on values produced by any engine prior to invoking reset.\n        */\n        void reset() { }\n        \n        //! Returns the value of the pdf for x\n        Real operator()(Real x) const{\n            using std::pow;\n            if(x < xm_) return 0.0;\n            return alpha_*pow(xm_/x, alpha_)/x;\n        }\n        \n        /*!    Returns a random variate distributed according to the\n            levy flight distribution.\n        */\n        template<class Engine>\n        result_type operator()(Engine& eng) const{\n            using std::pow;\n            return xm_*pow(boost::random::uniform_01<Real>()(eng), -1.0/alpha_);\n        }\n\n        /*!    Returns a random variate distributed according to the\n            levy flight with parameters specified by parm\n        */\n        template<class Engine>\n        result_type operator()(Engine& eng, const param_type& parm) const{\n            return LevyFlightDistribution (parm)(eng);\n        }\n\n        //! Writes the distribution to a std::ostream\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, LevyFlightDistribution, ed)\n        {\n            os << ed.xm_ << \" \" << ed.alpha_;\n            return os;\n        }\n\n        //! Reads the distribution from a std::istream\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, LevyFlightDistribution, ed)\n        {\n            is >> ed.xm_ >> std::ws >> ed.alpha_;\n            return is;\n        }\n\n        /*! Returns true iff the two distributions will produce identical\n            sequences of values given equal generators.\n        */\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(LevyFlightDistribution, lhs, rhs)\n        { return lhs.xm_ == rhs.xm_ && lhs.alpha_ == rhs.alpha_; }\n        \n        /*!    Returns true iff the two distributions will produce different\n            sequences of values given equal generators.\n        */\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(LevyFlightDistribution)\n\n    private:\n        result_type xm_;\n        result_type alpha_;\n    };\n\n}\n\n#endif\n", "meta": {"hexsha": "be5395f9c3f5607cf153829ca99753f80335b0f5", "size": 7222, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/math/levyflightdistribution.hpp", "max_stars_repo_name": "igitur/quantlib", "max_stars_repo_head_hexsha": "3f6b7271a68004cdb6db90f0e87346e8208234a2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-16T16:41:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T16:41:39.000Z", "max_issues_repo_path": "ql/experimental/math/levyflightdistribution.hpp", "max_issues_repo_name": "igitur/quantlib", "max_issues_repo_head_hexsha": "3f6b7271a68004cdb6db90f0e87346e8208234a2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T06:07:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T12:23:40.000Z", "max_forks_repo_path": "ql/experimental/math/levyflightdistribution.hpp", "max_forks_repo_name": "westonsteimel/QuantLib", "max_forks_repo_head_hexsha": "739ea894961dc6da5e8aa0b61c392d40637d39c1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2292682927, "max_line_length": 99, "alphanum_fraction": 0.6031570202, "num_tokens": 1590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6333128949200592}}
{"text": "\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include <manifold/SO3.h>\n#include <manifold/gradientDescentSE3.h>\n\nclass GDSE3gmm : public GDSE3<double> {\n public:\n  GDSE3gmm(const Eigen::Vector3d& muA, const\n      Eigen::Matrix3d& covA, const Eigen::Vector3d& muB, const\n      Eigen::Matrix3d& covB) \n    : piA_(1.), piB_(1.), muA_(muA), muB_(muB), covA_(covA), covB_(covB)\n  {\n    std::cout << \"-A-\"\n      << muA.transpose() << std::endl\n      << covA << std::endl;\n    std::cout << \"-B-\"\n      << muB.transpose() << std::endl\n      << covB << std::endl;\n  };\n\n  virtual void ComputeJacobian(const SE3d& theta, Eigen::Matrix<double,6,1>* J, double* f) {\n    SE3d T = theta;\n    Eigen::Matrix3d R = T.matrix().topLeftCorner(3,3);\n    Eigen::Vector3d t = T.matrix().topRightCorner(3,1);\n    // TODO: maybe this has to be negated?\n    Eigen::Vector3d m = (R*muB_ - muA_);\n    Eigen::Matrix3d SB = R*covB_*R.transpose();\n    Eigen::Matrix3d S = covA_+SB;\n    double logCA = -0.5*log(2.*M_PI)*3-0.5*covA_.determinant(); \n    double logCB = -0.5*log(2.*M_PI)*3-0.5*SB.determinant();\n    double logD = log(piA_) + log(piB_) + logCA +logCB;\n    double z = -0.5*(t-m).dot(S.ldlt().solve(t-m));\n//    std::cout << \"logCA=\" << logCA << \" logCB=\" << logCB << std::endl;\n//    std::cout << \"logD=\" << logD << \" z=\" << z \n//      << \" exp(logD+z)=\" << exp(logD + z) << std::endl;\n    if (J) {\n      J->fill(exp(logD + z));\n      J->topRows(3) = J->topRows(3).array()*(-S.ldlt().solve(t-m)).array();\n      for (uint32_t j=0; j<3; ++j) {\n        Eigen::Matrix3d G = SO3d::G(j);\n        Eigen::Matrix3d C = G*SB+SB*G.transpose();\n        Eigen::Matrix3d SinvC = S.ldlt().solve(C);\n        Eigen::Matrix3d SinvG = S.ldlt().solve(G);\n        Eigen::Matrix3d Sinv = S.inverse();\n\n//        std::cout << \"G = \"<<G<<std::endl\n//         << \"C = \"         <<C<<std::endl\n//         << \"SinvC =\"<<  SinvC<<std::endl\n//         << \"SinvG =\"<<  SinvG<<std::endl\n//         << \"Sinv = \"<<  Sinv<<std::endl;\n//         std::cout << G.transpose()*Sinv << std::endl\n//           << SinvC*Sinv << std::endl\n//           << SinvG << std::endl;\n//            << (G.transpose()*Sinv-SinvC*Sinv+SinvG) << std::endl;\n//           << C << std::endl;\n\n        std::cout << \"@G\" << j \n           << \"\\t\" << SinvC.trace()\n           << \"\\t\" << - t.dot(SinvC*S.ldlt().solve(t))\n           << \"\\t\" << -2.*t.dot(SinvC*S.ldlt().solve(muA_))\n           << \"\\t\" << -2.*t.dot((-SinvC*S.ldlt().solve(R)+SinvG*R)*muB_)\n           << \"\\t\" << (R*muB_).dot((G.transpose()*Sinv-SinvC*Sinv+SinvG)*R*muB_)\n           << \"\\t\" << +2.*(R*muB_).dot((SinvG*(Eigen::Matrix3d::Identity()-SB*Sinv))*R*muB_)\n           << std::endl;\n\n        (*J)(3+j) *= -0.5*(\n            SinvC.trace()\n            - t.dot(SinvC*S.ldlt().solve(t))\n            -2.*t.dot(SinvC*S.ldlt().solve(muA_))\n            -2.*t.dot((-SinvC*S.ldlt().solve(R)+SinvG*R)*muB_)\n            +(R*muB_).dot((G.transpose()*Sinv-SinvC*Sinv+SinvG)*R*muB_));\n      }\n      (*J) *= -1.;\n//      J->bottomRows(3).fill(0.);\n    }\n    if (f) {\n      *f = -exp(logD + z);\n    }\n  };\n protected:\n  SO3d Rmu_;\n  double piA_;\n  double piB_;\n  Eigen::Vector3d muA_;\n  Eigen::Vector3d muB_;\n  Eigen::Matrix3d covA_;\n  Eigen::Matrix3d covB_;\n};\n\nint main (int argc, char** argv) {\n  \n  double theta = 15.*M_PI/180.;\n  Eigen::Matrix3d R;\n  R << 1, 0, 0,\n         0, cos(theta), sin(theta),\n         0, -sin(theta), cos(theta);\n//  R = Eigen::Matrix3d::Identity();\n  Eigen::Vector3d t = Eigen::Vector3d::Ones();\n  Eigen::Matrix3d covA =   Eigen::Vector3d(1.,.1,1.).asDiagonal();\n  Eigen::Matrix3d covB = R*covA*R.transpose();\n  Eigen::Vector3d muA = Eigen::Vector3d::Zero();\n  Eigen::Vector3d muB = R*muA+t;\n\n  SE3d T;\n\n  GDSE3gmm gd(muA, covA, muB, covB);\n  gd.Compute(T, 1e-6, 200);\n//  gd.Compute(T, 0, 200);\n  T = gd.GetMinimum();\n  Eigen::Vector3d tEst = T.matrix().topRightCorner(3,1);\n  Eigen::Matrix3d REst = T.matrix().topLeftCorner(3,3);\n  std::cout << T << std::endl;\n  std::cout << R << std::endl;\n  std::cout << REst.transpose() << std::endl;\n  std::cout << (-REst.transpose()*tEst).transpose() << std::endl;\n  std::cout << t.transpose() << std::endl;\n  \n}\n", "meta": {"hexsha": "d79a4d7e7813a5a61c1d36bbb36a8995a89c0c87", "size": 4179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/SE3GD.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "test/SE3GD.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "test/SE3GD.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 34.5371900826, "max_line_length": 92, "alphanum_fraction": 0.5273988993, "num_tokens": 1520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070035949656, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6332573598961985}}
{"text": "#include <cstdio>\n#include <cstdlib>\n#include <MNIST.h>\n#include <Matrix.h>\n#include <Function.h>\n#include <Eigen/Dense>\n\nint main() {\n    MNIST mnist;\n    if (mnist.load(\"./../dataset/t10k-images-idx3-ubyte\", \"./../dataset/t10k-labels-idx1-ubyte\") != 0) {\n        fprintf(stderr, \"Failed to load MNIST.\\n\");\n        return -1;\n    }\n\n    MatrixXd W1(784, 50);\n    if (initMatrix(W1, \"./data/W1.csv\") != 0) {\n        fprintf(stderr, \"Failed to init W1\\n\");\n        return -1;\n    }\n\n    MatrixXd W2(50, 100);\n    if (initMatrix(W2, \"./data/W2.csv\") != 0) {\n        fprintf(stderr, \"Failed to init W2\\n\");\n        return -1;\n    }\n\n    MatrixXd W3(100, 10);\n    if (initMatrix(W3, \"./data/W3.csv\") != 0) {\n        fprintf(stderr, \"Failed to init W3\\n\");\n        return -1;\n    }\n\n    RowVectorXd b1(50);\n    if (initRowVector(b1, \"./data/b1.csv\") != 0) {\n        fprintf(stderr, \"Failed to init b1\\n\");\n        return -1;\n    }\n\n    RowVectorXd b2(100);\n    if (initRowVector(b2, \"./data/b2.csv\") != 0) { \n        fprintf(stderr, \"Failed to init b2\\n\");\n        return -1;\n    }\n\n    RowVectorXd b3(10);\n    if (initRowVector(b3, \"./data/b3.csv\") != 0) {\n        fprintf(stderr, \"Failed to init b3\\n\");\n        return -1;\n    }\n\n    int accuracyCnt = 0;\n    const MatrixXd& images = mnist.getImages();\n    const VectorXi& labels = mnist.getLabels();\n    for (int i = 0; i < images.rows(); ++i) {\n        const MatrixXd& M = mnist.getImages();\n        const RowVectorXd& x = M.row(i);\n        const RowVectorXd a1 = x * W1 + b1;\n        const RowVectorXd z1 = sigmoid(a1);\n        const RowVectorXd a2 = z1 * W2 + b2;\n        const RowVectorXd z2 = sigmoid(a2);\n        const RowVectorXd a3 = z2 * W3 + b3;\n        const RowVectorXd y = softmax(a3);\n\n        const int p = argmax(y);\n        if (p == labels(i)) {\n            ++accuracyCnt;\n        }\n    }\n\n    std::printf(\"Accuracy:%lf\\n\", (double)(accuracyCnt) / images.rows());\n\n    return 0;\n}\n", "meta": {"hexsha": "2ccda4903ae5fee9d43289277c2c8d1a8616b3d7", "size": 1947, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch03/NeuralnetMNISTBatch.cpp", "max_stars_repo_name": "chgzm/deep-learning-from-scratch-cpp", "max_stars_repo_head_hexsha": "72d2ab03e548147e7e26d38f69d56da8a919ec56", "max_stars_repo_licenses": ["MIT"], "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/NeuralnetMNISTBatch.cpp", "max_issues_repo_name": "chgzm/deep-learning-from-scratch-cpp", "max_issues_repo_head_hexsha": "72d2ab03e548147e7e26d38f69d56da8a919ec56", "max_issues_repo_licenses": ["MIT"], "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/NeuralnetMNISTBatch.cpp", "max_forks_repo_name": "chgzm/deep-learning-from-scratch-cpp", "max_forks_repo_head_hexsha": "72d2ab03e548147e7e26d38f69d56da8a919ec56", "max_forks_repo_licenses": ["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.3108108108, "max_line_length": 104, "alphanum_fraction": 0.5408320493, "num_tokens": 588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391558356, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6331581940446449}}
{"text": "#include \"VPD.h\"\n#include <opencv2/imgproc.hpp>\n#include <opencv2/highgui.hpp>\n\n#include <lsd.h>\n#include <iostream>\n#include <cmath>\n#include <boost/numeric/ublas/lu.hpp>\n\n\n#include \"VPCluster.h\"\n#include \"VPSample.h\"\n\n\nstd::vector< std::pair<float, float> > \textractVP \t\t(image_double &image, const cv::Mat &img);\ncv::Mat \t\t\t\t\t\t\t\tmakeFeatureMap\t(std::vector< std::pair<float, float> > &vp, const cv::Mat &img, double *reliability = NULL);\n\n\n\ntemplate<typename T>\nstd::vector<T> polyfit( const std::vector<T>& oX, const std::vector<T>& oY, int nDegree ) {\n\tusing namespace boost::numeric::ublas;\n \n\tif ( oX.size() != oY.size() )\n\t\tthrow std::invalid_argument( \"X and Y vector sizes do not match\" );\n \n\t// more intuative this way\n\tnDegree++;\n\t\n\tsize_t nCount =  oX.size();\n\tmatrix<T> oXMatrix( nCount, nDegree );\n\tmatrix<T> oYMatrix( nCount, 1 );\n\t\n\t// copy y matrix\n\tfor ( size_t i = 0; i < nCount; i++ )\n\t{\n\t\toYMatrix(i, 0) = oY[i];\n\t}\n \n\t// create the X matrix\n\tfor ( size_t nRow = 0; nRow < nCount; nRow++ )\n\t{\n\t\tT nVal = 1.0f;\n\t\tfor ( int nCol = 0; nCol < nDegree; nCol++ )\n\t\t{\n\t\t\toXMatrix(nRow, nCol) = nVal;\n\t\t\tnVal *= oX[nRow];\n\t\t}\n\t}\n \n\t// transpose X matrix\n\tmatrix<T> oXtMatrix( trans(oXMatrix) );\n\t// multiply transposed X matrix with X matrix\n\tmatrix<T> oXtXMatrix( prec_prod(oXtMatrix, oXMatrix) );\n\t// multiply transposed X matrix with Y matrix\n\tmatrix<T> oXtYMatrix( prec_prod(oXtMatrix, oYMatrix) );\n \n\t// lu decomposition\n\tpermutation_matrix<T> pert(oXtXMatrix.size1());\n\tconst std::size_t singular = lu_factorize(oXtXMatrix, pert);\n\t// must be singular\n\tif( singular != 0 ) {\n\t\t// then the regression cannot be done... return an empty vector\n\t\treturn std::vector<T>();\n\t}\n \n\t// backsubstitution\n\tlu_substitute(oXtXMatrix, pert, oXtYMatrix);\n \n\t// copy the result to coeff\n\treturn std::vector<T>( oXtYMatrix.data().begin(), oXtYMatrix.data().end() );\n}\n\ntemplate<typename T>\nstd::vector<T> polyval( const std::vector<T>& oCoeff,  const std::vector<T>& oX ) {\n\tsize_t nCount =  oX.size();\n\tsize_t nDegree = oCoeff.size();\n\tstd::vector<T>\toY( nCount );\n \n\tfor ( size_t i = 0; i < nCount; i++ )\n\t{\n\t\tT nY = 0;\n\t\tT nXT = 1;\n\t\tT nX = oX[i];\n\t\tfor ( size_t j = 0; j < nDegree; j++ )\n\t\t{\n\t\t\t// multiply current x by a coefficient\n\t\t\tnY += oCoeff[j] * nXT;\n\t\t\t// power up the X\n\t\t\tnXT *= nX;\n\t\t}\n\t\toY[i] = nY;\n\t}\n \n\treturn oY;\n}\n\n\n\n\n\nstruct Segment {\n\tfloat x;\n\tfloat y;\n\tfloat xend;\n\tfloat yend;\n\tfloat angle;\n};\n\nfloat  horizonLine(cv::Mat &image) {\n\tif(image.empty()) return 0;\n\n\n\tstd::vector<float> x, y;\n\n\tcv::Mat gray;\n\tcv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);\n\n\tcv::Mat edges;\n\tcv::Canny(gray, edges, 110, 220);\n\n\tstd::vector<cv::Vec4i> lines;\n    cv::HoughLinesP( edges, lines, 1, CV_PI/2, 0, 30, 1 );\n    float meanY = 0; int nbLines = 0;\n    float meanY2 = 0;\n    for( size_t i = 0; i < lines.size(); i++ )\n    {\n    \tif(lines[i][0] == lines[i][2]) continue;\n\n\t\tif(lines[i][1] > (.7 * image.rows)) continue;\n\t\tif(lines[i][1] < (.3 * image.rows)) continue;\n\n        cv::line( image, cv::Point(lines[i][0], lines[i][1]),\n            cv::Point(lines[i][2], lines[i][3]), cv::Scalar(0,0,255), 3, 8 );\n\n        x.push_back(lines[i][0]);\n\t\tx.push_back(lines[i][2]);\n\t\ty.push_back(lines[i][1]);\n\t\ty.push_back(lines[i][3]);\n\n\t\tmeanY += lines[i][1]; ++nbLines;\n\t\tmeanY += lines[i][3]; ++nbLines;\n\n\t\tmeanY2 += lines[i][1] * lines[i][1];\n\t\tmeanY2 += lines[i][3] * lines[i][3];\n\n    }\n    meanY /= nbLines;\n    meanY2 /= nbLines;\n\n    float stdev = std::sqrt(meanY2 - meanY*meanY);\n    float meanValue = meanY;\n    \n    meanY = 0; nbLines = 0;\n    for( size_t i = 0; i < lines.size(); i++ )\n    {\n    \tif(lines[i][0] == lines[i][2]) continue;\n\n\t\tif(lines[i][1] > (.7 * image.rows)) continue;\n\t\tif(lines[i][1] < (.3 * image.rows)) continue;\n\n        if(std::abs(lines[i][1] - meanValue) > 1.3 * stdev) continue;\n\n\t\tmeanY += lines[i][1]; ++nbLines;\n\t\tmeanY += lines[i][3]; ++nbLines;\n\n    }\n    meanY /= nbLines;\n\n\n\n    if(nbLines == 0) {\n    \tmeanY = image.rows/2;\n    } else {\n    \tstd::vector<float> model = polyfit<float>(x, y, 1);\n\n\t    if(std::abs(model[0]- image.rows/2) < std::abs(meanY - image.rows/2))\n\t    \tmeanY = model[0];\n    }\n\n\n\tcv::line(image, cv::Point_<int>(0, meanY), cv::Point_<int>(image.cols, meanY), cv::Scalar( 0, 255, 0 ), 2);\n\n\n\nreturn meanY;\n\n\n}\n\n\nstd::vector< std::pair<float, float> >  extractVP(const cv::Mat &image) {\n\n\n\t// ------------------------------------------------------------------------------------\n\t// convert image input\n\n\tif(image.empty()) return std::vector< std::pair<float, float> >();\n\n\tcv::Mat gray;\n\tcv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);\n\tcv::Mat grayF;\n\tgray.convertTo(grayF, CV_32FC1);\n\n\n\timage_double image_d = new_image_double(gray.cols, gray.rows);\n\tfor(int i = 0 ; i < gray.cols*gray.rows ; ++i) {\n\t\timage_d->data[i] = reinterpret_cast<float*>(grayF.data)[i];\n\t}\n\n\n\n\treturn extractVP(image_d, image);\n\n}\n\nstd::vector< std::pair<float, float> > extractVP(image_double &image_d, const cv::Mat &) {\n\n\n\t// cv::Mat colorImg = image.clone();\n\n\n\t// ------------------------------------------------------------------------------------\n\t// Run LSD line segment detector\n\t\n\n\tntuple_list ntuple = LineSegmentDetection( image_d, 0.7,\n                                  0.6, 2.6,\n                                  22.5, 0.0, 0.6,\n                                  1024, 1.0,\n                                  NULL );\n\n\t// ntuple_list ntuple = LineSegmentDetection( image_d, 0.7,\n    //                               0.6, 2.6,\n    //                               22.5, 0.0, 0.6,\n    //                               1024, 1.0,\n    //                               NULL );\n\n\tstd::vector< std::vector<float> *> pts;\n\n\tstd::vector<float> stroke_length(ntuple->size);\n\tfor(size_t i = 0 ; i < ntuple->size ; ++i) {\n\t\tstroke_length[i] = static_cast<float>( (ntuple->values[ i * ntuple->dim + 0 ] - ntuple->values[ i * ntuple->dim + 2 ])*(ntuple->values[ i * ntuple->dim + 0 ] - ntuple->values[ i * ntuple->dim + 2 ]) + (ntuple->values[ i * ntuple->dim + 1 ] - ntuple->values[ i * ntuple->dim + 3 ])*(ntuple->values[ i * ntuple->dim + 1 ] - ntuple->values[ i * ntuple->dim + 3 ]));\n\t}\n\n\tstd::sort(stroke_length.begin(), stroke_length.end());\n\n\n\tif(stroke_length.empty()) {\n\t\tfree_image_double(image_d);\n\t\tfree_ntuple_list(ntuple);\n\t\treturn std::vector< std::pair<float, float> >();\n\t}\n\n\t// std::cout << stroke_length[static_cast<int>(stroke_length.size()*.7)] << std::endl;\n\n\t // std::cout << ntuple->size << \"line segments found:\\n\";\n\tfor(size_t i = 0 ; i < ntuple->size ; ++i) {\n\t\tfloat len = static_cast<float>( (ntuple->values[ i * ntuple->dim + 0 ] - ntuple->values[ i * ntuple->dim + 2 ])*(ntuple->values[ i * ntuple->dim + 0 ] - ntuple->values[ i * ntuple->dim + 2 ]) + (ntuple->values[ i * ntuple->dim + 1 ] - ntuple->values[ i * ntuple->dim + 3 ])*(ntuple->values[ i * ntuple->dim + 1 ] - ntuple->values[ i * ntuple->dim + 3 ]) );\n\t\tif(len < stroke_length[static_cast<int>(stroke_length.size()*.7)]) continue;\n\t\tif(len < 827.748f) continue; \n\n\t\tstd::vector<float>* p = new std::vector<float>(4);\n\t\tpts.push_back(p);\n\t\tfor(size_t j = 0 ; j < ntuple->dim ; ++j) {\n\t\t\tif(j < 4) (*p)[j] = static_cast<float>(ntuple->values[ i * ntuple->dim + j ]);\n\t\t\t// std::cout << ntuple->values[ i * ntuple->dim + j ] << \" \";\n\t\t}\n\t\t // std::cout << \"\\n\";\n\t}\n\n\tfree_image_double(image_d);\n\tfree_ntuple_list(ntuple);\n\n\n\t// for(size_t i = 0 ; i < pts.size() ; ++i) {\n\t// \tcv::line(colorImg, cv::Point((*pts[i])[0], (*pts[i])[1]),  cv::Point((*pts[i])[2], (*pts[i])[3]), cv::Scalar(255,0,0),2);\n\t// }\n\n\n\t// ------------------------------------------------------------------------------------\n\t// JLinkage for cluster detection\n\n\n\n\n\tstd::vector<unsigned int> Lables;\n\tstd::vector<unsigned int> LableCount;\n\n\tif(pts.size() < 20) {\n\t\tfor(size_t i = 0 ; i < pts.size() ; ++i) {\n\t\t\tdelete pts[i];\n\t\t}\n\n\t\treturn std::vector< std::pair<float, float> >();\n\t}\n\n\tstd::vector<std::vector<float> *> *mModels = \n\t\tVPSample::run(&pts, 5000, 2, 0, 3); // VPSample::run(&pts, 5000, 2, 0, 3);\n\tint classNum = VPCluster::run(Lables, LableCount, &pts, mModels, 2, 2);\n\t// std::cout<<\"vpdetection found \"<<classNum<<\" classes!\"<<std::endl;\n\n\t//2.1. release other resource\n\tfor(unsigned int i=0; i < mModels->size(); ++i)\n\t\tdelete (*mModels)[i];\n\tdelete mModels;\n\n\n\n\t// ------------------------------------------------------------------------------------\n\t// Compute the vanishing point positions\n\n\n\n\tstd::vector< std::vector<float> > lengths(Lables.size());\n\tstd::vector<float> dydx(pts.size());\n\tstd::vector<float> b(pts.size());\n\tstd::vector<bool>  disabled(pts.size(), false);\n\n\n\tfor(size_t i = 0 ; i < pts.size() ; ++i) {\n\t\tlengths[Lables[i]].push_back(std::sqrt(((*pts[i])[1]-(*pts[i])[3])*((*pts[i])[1]-(*pts[i])[3]) +  ((*pts[i])[0]-(*pts[i])[2])*((*pts[i])[0]-(*pts[i])[2])));\n\t\tif(std::abs(((*pts[i])[0] - (*pts[i])[2])) < 0.00001) {\n\t\t\tdisabled[i] = true;\n\t\t\tcontinue;\n\t\t}\n\n\n\t\tdydx[i] = ((*pts[i])[1] - (*pts[i])[3]) / ((*pts[i])[0] - (*pts[i])[2]);\n\t\tb[i] =  (*pts[i])[1] - dydx[i] * (*pts[i])[0];\n\n\t\tif(atan(std::abs(dydx[i])) < (20*3.141592653/180)) {\n\t\t\tdisabled[i] = true;\n\t\t}\n\n\n\t}\n\n\tfor(int i = 0 ; i < classNum ; ++i) {\n\t\tstd::sort(lengths[i].begin(), lengths[i].end());\n\t}\n\n\tstd::vector<float> numPoints(classNum, 0);\n\tstd::vector<float> vp_x(classNum, 0);\n\tstd::vector<float> vp_y(classNum, 0);\n\n\tfor(size_t ii = 0 ; ii < pts.size() ; ++ii) {\n\t\tfor(size_t jj = ii+1 ; jj < pts.size() ; ++jj) {\n\n\t\t\tfloat l1 = std::sqrt(((*pts[ii])[1]-(*pts[ii])[3])*((*pts[ii])[1]-(*pts[ii])[3]) +  ((*pts[ii])[0]-(*pts[ii])[2])*((*pts[ii])[0]-(*pts[ii])[2]));\n\t\t\tfloat l2 = std::sqrt(((*pts[jj])[1]-(*pts[jj])[3])*((*pts[jj])[1]-(*pts[jj])[3]) +  ((*pts[jj])[0]-(*pts[jj])[2])*((*pts[jj])[0]-(*pts[jj])[2]));\n\n\t\t\tif(Lables[ii] != Lables[jj]) continue;\n\t\t\tif(disabled[ii] || disabled[jj]) continue;\n\t\t\tif(lengths[Lables[ii]].size() == 0) continue;\n\t\t\tif(lengths[Lables[jj]].size() == 0) continue;\n\n\n\t\t\tif(l1 < lengths[Lables[ii]][static_cast<int>(lengths[Lables[ii]].size()*.7)]) continue;\n\t\t\tif(l2 < lengths[Lables[jj]][static_cast<int>(lengths[Lables[jj]].size()*.7)]) continue;\n\n\t\t\tif(std::abs((dydx[jj] - dydx[ii])) < 0.000001) continue;\n\n\t\t\tfloat x = (b[ii] - b[jj]) / (dydx[jj] - dydx[ii]);\n\t\t\tfloat y = dydx[ii] * x + b[ii];\n\n\t\n\t\t\t// cv::line(colorImg, cv::Point((*pts[ii])[0], (*pts[ii])[1]),  cv::Point((*pts[ii])[2], (*pts[ii])[3]), cv::Scalar(0,255,0),2);\n\t\t\t// cv::line(colorImg, cv::Point((*pts[jj])[0], (*pts[jj])[1]),  cv::Point((*pts[jj])[2], (*pts[jj])[3]), cv::Scalar(0,0,255),2);\n\n\t\t\tvp_x[Lables[ii]] += x;\n\t\t\tvp_y[Lables[ii]] += y;\n\t\t\t++numPoints[Lables[ii]];\n\t\t}\n\t}\n\n\tstd::vector< std::pair<float, float> > vp;\n\tint considered_idx = 0;\n\tfor(int i = 0 ; i < classNum ; ++i) {\n\t\tif(numPoints[i] == 0) \n\t\t\tcontinue;\n\n\t\tvp_x[i] /= numPoints[i];\n\t\tvp_y[i] /= numPoints[i];\n\n\t\t// if(numPoints[i] < 1)\n\t\t// \tcontinue;\n\n\t\tconsidered_idx = i;\n\t\tvp.push_back(std::make_pair(vp_x[i], vp_y[i]));\n\n\t\t// cv::circle(colorImg, cv::Point(vp_x[i], vp_y[i]), 3, cv::Scalar(0,0,255),2);\n\t}\n\n\t//cv::imshow(\"colorImg\", colorImg);\n\t// cv::waitKey();\n\n\t// ------------------------------------------------------------------------------------\n\t// Done. free memory\n\n\n\tfor(size_t i = 0 ; i < pts.size() ; ++i) {\n\t\tdelete pts[i];\n\t}\n\n\n\treturn vp;\n\n}\n\n\ncv::Mat makeFeatureMap\t(std::vector< std::pair<float, float> > &vp, const cv::Mat &img, double *reliability) {\n\tcv::Mat featureMap(img.rows, img.cols, CV_64FC1, cv::Scalar(0.f));\n\n\tif(reliability != NULL)  *reliability = 0.f;\n\n\tstd::vector<float> dists;\n\tfor(size_t i = 0 ; i < vp.size() ; ++i) {\n        float normx = vp[i].first/img.cols;\n        float normy = vp[i].second/img.rows;\n\n\t\tif(normx > 1.f || normx < 0.f) continue;\n\t\tif(normy > 1.f || normy < 0.f) continue;\n\n        // std::cout << normx << \" \" << normy << std::endl;\n\n        float d = (normx-.5f)*(normx-.5f) + (normy-.5f)*(normy-.5f);\n\n\t\tdists.push_back(d);\n\t}\n\n\tstd::sort(dists.begin(), dists.end());\n\n    for(size_t i = 0 ; i < vp.size() ; ++i) {\n        float normx = vp[i].first/img.cols;\n        float normy = vp[i].second/img.rows;\n\n\t\tif(normx > 1.f || normx < 0.f) continue;\n\t\tif(normy > 1.f || normy < 0.f) continue;\n\n        // std::cout << normx << \" \" << normy << std::endl;\n\n        float d = (normx-.5f)*(normx-.5f) + (normy-.5f)*(normy-.5f);\n\n\t\tif(dists.size() > 7 && dists[dists.size()-7] > d) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(std::abs(normy-.5f) > 0.25) continue;\n\n\t\td =  (normy-.5f)*(normy-.5f);\n\n        float sigma = 0.00005f / (d + 0.01f);\n\t\tif(reliability != NULL) {\n\t\t\t*reliability = std::max(static_cast<float>(*reliability), sigma);\n\t\t}\n        \n        for(int i = 0 ; i < img.rows ; ++i) {\n            for(int j = 0 ; j < img.cols ; ++j) {\n                float fi = static_cast<float>(i) / img.rows;\n                float fj = static_cast<float>(j) / img.cols;\n                featureMap.at<double>(i,j) = std::max(featureMap.at<double>(i,j), static_cast<double>(std::exp(-((fj-normx)*(fj-normx)*2 + (fi-normy)*(fi-normy))/sigma)));\n\n            }\n        }\n    }\n\n    return featureMap;\n}\n\n\ncv::Mat vanishingLineFeatureMapF64\t(const cv::Mat &img, double *reliability) {\n\n\n\timage_double image_d = new_image_double(img.cols, img.rows);\n\tfor(int i = 0 ; i < img.cols*img.rows ; ++i) {\n\t\timage_d->data[i] = reinterpret_cast<double*>(img.data)[i];\n\t}\n\n\tstd::vector< std::pair<float, float> > vp = extractVP(image_d, img);\n\n    return makeFeatureMap(vp, img, reliability);\n}\n\ncv::Mat vanishingLineFeatureMapF64C3(const cv::Mat &img, double *reliability) {\n\n\tcv::Mat imgu(img.rows, img.cols, CV_8UC3, cv::Scalar(0.f, 0.f, 0.f));\n    for(int i = 0 ; i < img.rows ; ++i) {\n        for(int j = 0 ; j < img.cols ; ++j) {\n            cv::Point3_<unsigned char> &o = imgu.at< cv::Point3_<unsigned char> >(i,j);\n            const cv::Point3_<double> &in = img.at< cv::Point3_<double> >(i,j);\n\n            o.x = static_cast<unsigned char>(in.x*255);\n            o.y = static_cast<unsigned char>(in.y*255);\n            o.z = static_cast<unsigned char>(in.z*255);\n        }\n    }\n\n\tstd::vector< std::pair<float, float> > vp = extractVP(imgu);\n\n    return makeFeatureMap(vp, img, reliability);\n}\n\n\ncv::Mat vanishingLineFeatureMap (const cv::Mat &img, double *reliability) {\n\n\tif(img.empty()) return cv::Mat();\n\n    std::vector< std::pair<float, float> > vp = extractVP(img);\n\n    return makeFeatureMap(vp, img, reliability);\n}\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "68ddbb2d6200c0233e610497a0c4b3daaaf61b25", "size": 14378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/liblinper/src/VPD.cpp", "max_stars_repo_name": "Telecommunication-Telemedia-Assessment/GBVS360-BMS360-ProSal", "max_stars_repo_head_hexsha": "d0312f54a28e1ef2cf1e1581241571d9612bb36c", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-01-23T14:37:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T13:53:41.000Z", "max_issues_repo_path": "lib/liblinper/src/VPD.cpp", "max_issues_repo_name": "Telecommunication-Telemedia-Assessment/GBVS360-BMS360-ProSal", "max_issues_repo_head_hexsha": "d0312f54a28e1ef2cf1e1581241571d9612bb36c", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2018-09-05T23:38:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T18:52:18.000Z", "max_forks_repo_path": "lib/liblinper/src/VPD.cpp", "max_forks_repo_name": "Telecommunication-Telemedia-Assessment/GBVS360-BMS360-ProSal", "max_forks_repo_head_hexsha": "d0312f54a28e1ef2cf1e1581241571d9612bb36c", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T00:35:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T16:55:07.000Z", "avg_line_length": 27.5969289827, "max_line_length": 364, "alphanum_fraction": 0.5513284184, "num_tokens": 4746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6331440777038713}}
{"text": "#include <iostream>\n#include <vector>\n#include <random>\n#include <chrono>\n#include <cstdint>\n#include <boost/math/special_functions/prime.hpp>\n\nstatic const std::size_t kNbItems( 1000000 );\n\nnamespace method1\n{\n\nvoid removeDuplicates( std::vector<uint32_t> & items )\n{\n    using namespace boost::math;\n    uint64_t checker = 1u; // Be careful of integer overflow here\n\n    std::size_t n = 0;\n    for( const uint32_t x : items )\n    {\n        const uint32_t p = prime( x );\n        if ( checker % p )\n        {\n            checker *= p;\n            items[n++] = x;\n        }\n    }\n\n    items.resize( n );\n}\n\n}\n\nnamespace method2\n{\n\nvoid removeDuplicates( std::vector<uint32_t> & items )\n{\n    std::sort( items.begin(), items.end() );\n    items.erase( std::unique( items.begin(), items.end() ), items.end() );\n}\n\n}\n\n/**\n * @brief main goes here\n */\nint main( int argc, char **argv )\n{\n    std::mt19937 rng;\n    rng.seed( time( 0 ) );\n\n    std::uniform_int_distribution<uint32_t> rand( 0, 10 );\n    std::vector<uint32_t> v;\n    v.reserve( kNbItems );\n    for( std::size_t i = 0; i < kNbItems; ++i )\n    {\n        v.push_back( rand( rng ) );\n    }\n\n    // Benchmark\n    typedef std::chrono::high_resolution_clock Clock;\n    using std::chrono::microseconds;\n    using std::chrono::duration_cast;\n\n    std::vector<uint32_t> uniqueItems1( v );\n    {\n        auto t1 = Clock::now();\n        method1::removeDuplicates( uniqueItems1 );\n        auto t2 = Clock::now();\n        std::cout << \"Method1 took : \" << duration_cast<microseconds>(t2-t1).count() << std::endl;\n    }\n\n    std::vector<uint32_t> uniqueItems2( v );\n    {\n        auto t1 = Clock::now();\n        method2::removeDuplicates( uniqueItems2 );\n        auto t2 = Clock::now();\n        std::cout << \"Method2 took : \" << duration_cast<microseconds>(t2-t1).count() << std::endl;\n    }\n    \n    std::sort( uniqueItems1.begin(), uniqueItems1.end() );\n    std::sort( uniqueItems2.begin(), uniqueItems2.end() );\n    if ( uniqueItems1 == uniqueItems2 )\n    {\n        std::cout << \"RESULTS ARE CONFORM\" << std::endl;\n    }\n    else\n    {\n        std::cerr << \"OUPS... Algorithm outputs different resutls!\" << std::endl;\n    }\n    std::cout << \"uniqueItems1.size(): \" << uniqueItems1.size() << std::endl;\n    std::cout << \"uniqueItems2.size(): \" << uniqueItems2.size() << std::endl;\n}\n", "meta": {"hexsha": "7d4866b2ca742b3dee1b1ee3449b326556692ad8", "size": 2328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "edubois/magicUnique", "max_stars_repo_head_hexsha": "0e0174f588781beb06317a9b55e39af0e3b490f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-10T18:50:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-10T18:50:03.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "edubois/magicUnique", "max_issues_repo_head_hexsha": "0e0174f588781beb06317a9b55e39af0e3b490f3", "max_issues_repo_licenses": ["MIT"], "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": "edubois/magicUnique", "max_forks_repo_head_hexsha": "0e0174f588781beb06317a9b55e39af0e3b490f3", "max_forks_repo_licenses": ["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.5052631579, "max_line_length": 98, "alphanum_fraction": 0.5841924399, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.633144070804988}}
{"text": "#include \"conex/jordan_matrix_algebra.h\"\n\n#include \"gtest/gtest.h\"\n#include <Eigen/Dense>\n\n#include \"conex/debug_macros.h\"\n#include \"conex/test/test_util.h\"\n\nnamespace conex {\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nusing JordanTypes = testing::Types<Real, Complex, Quaternions, Octonions>;\n\nVectorXd sort(const VectorXd& x) {\n  auto y = x;\n  std::sort(y.data(), y.data() + x.rows());\n  return y;\n}\n\ntemplate <typename T>\nclass TestCases : public testing::Test {\n public:\n  void DoMultiplyByIdentity() {\n    auto X = T::Random(3, 3);\n    auto I = T::Identity(3);\n    EXPECT_TRUE(T::IsEqual(X, T::Multiply(X, I)));\n  }\n  void VerifyJordanIdentity(int n) {\n    using Matrix = typename T::Matrix;\n    Matrix A = T::Random(n, n);\n    A = T::Add(A, T::ConjugateTranspose(A));\n    Matrix B = T::Random(n, n);\n    B = T::Add(B, T::ConjugateTranspose(B));\n    auto W = T::JordanMultiply(A, B);\n\n    EXPECT_TRUE(T::IsHermitian(B));\n    EXPECT_TRUE(T::IsHermitian(A));\n    EXPECT_TRUE(T::IsHermitian(W));\n\n    // Test Jordan identity.\n    auto Asqr = T::JordanMultiply(A, A);\n    auto BA = T::JordanMultiply(A, B);\n    auto P1 = T::JordanMultiply(Asqr, BA);\n\n    auto BAsqr = T::JordanMultiply(B, Asqr);\n    auto P2 = T::JordanMultiply(A, BAsqr);\n\n    EXPECT_TRUE(T::IsEqual(P1, P2));\n  }\n\n  void DoQuadraticRepresentationAssociativeTest(int d) {\n    using Matrix = typename T::Matrix;\n    Matrix A = T::Random(d, d);\n    A = T::Add(A, T::ConjugateTranspose(A));\n    Matrix B = T::Random(d, d);\n    B = T::Add(B, T::ConjugateTranspose(B));\n    Matrix Yref = T::QuadraticRepresentation(B, A);\n\n    Matrix Y1 = T::Multiply(T::Multiply(B, A), B);\n    Matrix Y2 = T::Multiply(B, T::Multiply(A, B));\n    Y1 = T::ScalarMultiply(Y1, .5);\n    Y2 = T::ScalarMultiply(Y2, .5);\n    Y1 = T::Add(Y1, Y2);\n\n    if (std::is_same<T, Octonions>::value) {\n      EXPECT_FALSE(T::IsEqual(Y1, Yref));\n    } else {\n      EXPECT_TRUE(T::IsEqual(Y1, Yref));\n    }\n  }\n\n  void DoEigenvalueTests() {\n    double eps = 1e-9;\n    using Matrix = typename T::Matrix;\n    int n = 3;\n    Matrix Q = T::Random(n, n);\n    Q = T::Add(Q, T::ConjugateTranspose(Q));\n    Q = T::JordanMultiply(Q, Q);\n\n    auto I = T::Identity(n);\n    double normsqr = T::TraceInnerProduct(Q, Q);\n    double trace = T::TraceInnerProduct(I, Q);\n    auto eigvals = T::Eigenvalues(Q);\n\n    EXPECT_TRUE(eigvals.minCoeff() > eps);\n    EXPECT_NEAR(eigvals.squaredNorm(), normsqr, eps);\n    EXPECT_NEAR(eigvals.sum(), trace, eps);\n\n    // eigvals = T::Eigenvalues(I);\n    // for (int i = 0; i < eigvals.rows(); i++) {\n    //   EXPECT_NEAR(eigvals(i), 1, 1e-8);\n    // }\n  }\n\n  void DoTestOrthogonal(int d) {\n    if (std::is_same<T, Octonions>::value) {\n      return;\n    }\n    double eps = 1e-8;\n    auto Q = T::Random(d, d);\n\n    Q = T::Orthogonalize(Q);\n\n    auto I = T::ScalarMultiply(T::Identity(d), -1);\n    auto res = T::Add(I, T::Multiply(Q, T::ConjugateTranspose(Q)));\n    EXPECT_TRUE(T::TraceInnerProduct(res, res) < eps);\n  }\n\n  void DoEigenvaluesFromSpectralDecomp(int d) {\n    if (std::is_same<T, Octonions>::value) {\n      return;\n    }\n    double eps = 1e-8;\n    auto Q = T::Random(d, d);\n\n    Q = T::Orthogonalize(Q);\n    HyperComplexMatrix D = T::Zero(d, d);\n    for (int i = 0; i < d; i++) {\n      D.at(0)(i, i) = -d / 2 + i;\n    }\n    auto X = T::Multiply(T::Multiply(Q, D), T::ConjugateTranspose(Q));\n\n    VectorXd calc = sort(T::Eigenvalues(X));\n    for (int i = 0; i < d; i++) {\n      EXPECT_NEAR(calc(i), D.at(0)(i, i), eps);\n    }\n\n    auto r = T::Random(d, 1);\n    calc = sort(T::ApproximateEigenvalues(X, r, d));\n    for (int i = 0; i < d; i++) {\n      EXPECT_NEAR(calc(i), D.at(0)(i, i), eps);\n    }\n  }\n\n  void DoAsymmetricEigenvaluesTest(int d) {\n    if (std::is_same<T, Octonions>::value) {\n      return;\n    }\n    double eps = 1e-8;\n    auto Wsqrt = T::Random(d, d);\n    Wsqrt = T::Add(Wsqrt, T::ConjugateTranspose(Wsqrt));\n    auto S = T::Random(d, d);\n    S = T::Add(S, T::ConjugateTranspose(S));\n\n    auto W = T::Multiply(Wsqrt, T::ConjugateTranspose(Wsqrt));\n\n    VectorXd ref = sort(T::Eigenvalues(T::QuadraticRepresentation(Wsqrt, S)));\n\n    VectorXd calc;\n    calc = sort(T::EigenvaluesOfJacobiMatrix(T::Multiply(W, S), W, d));\n    auto calc2 = sort(\n        T::ApproximateEigenvalues(T::Multiply(W, S), W, T::Random(d, 1), d));\n    for (int i = 0; i < d; i++) {\n      EXPECT_NEAR(calc(i), calc2(i), eps);\n    }\n\n    for (int i = 0; i < d; i++) {\n      EXPECT_NEAR(calc(i), ref(i), eps);\n    }\n  }\n\n  void RankOneTest(int d) {\n    assert(d == 3);\n    double eps = 1e-5;\n    auto Wsqrt = T::Random(d, 1);\n\n    if (std::is_same<T, Octonions>::value) {\n      // Lemma 14.90 Spinors and Calibrations By F. Reese Harvey shows\n      // that primitive idempotents of the Albert algebra\n      // are of the form w w^*, with associator [w_1 w_2 w_3] = 0.\n      // This implies w_i are contained in a quaternion subalgebra.\n      auto WsqrtQ = Quaternions::Random(d, 1);\n      Wsqrt = T::Zero(d, 1);\n      for (int i = 0; i < 4; i++) {\n        Wsqrt.at(i) = WsqrtQ.at(i);\n      }\n    }\n\n    Wsqrt = T::ScalarMultiply(Wsqrt, 1.0 / Wsqrt.norm());\n    auto W = T::Multiply(Wsqrt, T::ConjugateTranspose(Wsqrt));\n\n    // Add noise to make eigenvalues distinct.\n    W.at(0)(0, 0) += 0.00003 * eps;\n    W.at(0)(1, 1) += 0.00001 * eps;\n    W.at(0)(2, 2) += 0.00002 * eps;\n\n    VectorXd ref(d);\n    ref.setZero();\n    ref(0) = 1;\n    ref = sort(ref);\n    VectorXd calc = sort(T::Eigenvalues(W));\n    for (int i = 0; i < d; i++) {\n      EXPECT_NEAR(calc(i), ref(i), eps);\n    }\n  }\n};\n\nTYPED_TEST_CASE(TestCases, JordanTypes);\nTYPED_TEST(TestCases, MultiplyByIdentity) {\n  TestFixture::DoMultiplyByIdentity();\n}\n\nTYPED_TEST(TestCases, JordanIdentity) { TestFixture::VerifyJordanIdentity(3); }\n\nTYPED_TEST(TestCases, QuadraticRepresentationAssociativeTest) {\n  TestFixture::DoQuadraticRepresentationAssociativeTest(3);\n}\n\nTYPED_TEST(TestCases, EigenvalueTests) { TestFixture::DoEigenvalueTests(); }\n\nTYPED_TEST(TestCases, DoTestOrthogonal) { TestFixture::DoTestOrthogonal(3); }\n\nTYPED_TEST(TestCases, DoAsymmetricEigenvaluesTest) {\n  TestFixture::DoAsymmetricEigenvaluesTest(3);\n}\n\nTYPED_TEST(TestCases, DoEigenvaluesFromSpectralDecomp) {\n  TestFixture::DoEigenvaluesFromSpectralDecomp(3);\n}\n\nTYPED_TEST(TestCases, RankOneTest) { TestFixture::RankOneTest(3); }\n\nTEST(JordanMatrixAlgebra, HermitianRealMatchesEigen) {\n  using T = Real;\n  int n = 3;\n  auto Q = T::Random(n, n);\n  Q = T::JordanMultiply(Q, Q);\n\n  EXPECT_TRUE(\n      (sort(T::Eigenvalues(Q)) - sort(eig(Q.at(0)).eigenvalues)).norm() < 1e-8);\n}\n\n}  // namespace conex\n", "meta": {"hexsha": "d65c9f8195aaf4621bcf83ef4dc90000a487d855", "size": 6579, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/test/jordan_matrix_algebra_test.cc", "max_stars_repo_name": "ToyotaResearchInstitute/conex", "max_stars_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T08:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T21:53:22.000Z", "max_issues_repo_path": "conex/test/jordan_matrix_algebra_test.cc", "max_issues_repo_name": "ToyotaResearchInstitute/conex", "max_issues_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/test/jordan_matrix_algebra_test.cc", "max_forks_repo_name": "ToyotaResearchInstitute/conex", "max_forks_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T16:02:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T11:25:46.000Z", "avg_line_length": 27.8771186441, "max_line_length": 80, "alphanum_fraction": 0.6108831129, "num_tokens": 2112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.633144066529764}}
{"text": "\ufeff#include <iostream>\r\n#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n\r\nnamespace mp = boost::multiprecision;\r\n\r\nint main( int argc, char **argv )\r\n{\r\n    if ( argc < 2 ){\r\n        std::cout << argv[ 0 ] << \" number\" << std::endl;\r\n\r\n    }else{\r\n        mp::cpp_int number( argv[ 1 ] );\r\n\r\n        mp::cpp_int prev_00(1);\r\n        mp::cpp_int prev_01(0);\r\n        mp::cpp_int current(1);\r\n        mp::cpp_int result(0);\r\n        mp::cpp_int i(0);\r\n\r\n        while( i < number )\r\n        {\r\n            result = current;\r\n            current = prev_00 + prev_01;\r\n            prev_01 = prev_00;\r\n            prev_00 = current;\r\n            i += 1;\r\n        }\r\n        std::cout << result << std::endl;\r\n    }\r\n}\r\n", "meta": {"hexsha": "517e8434e8ae1416771a06d8fd99c0d9922a4b8c", "size": 750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fib/fib.cpp", "max_stars_repo_name": "Matsuyanagi/fibonacci_cpp", "max_stars_repo_head_hexsha": "9bc94184cf6a9ac33a602cb5b35247c5db57a91d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fib/fib.cpp", "max_issues_repo_name": "Matsuyanagi/fibonacci_cpp", "max_issues_repo_head_hexsha": "9bc94184cf6a9ac33a602cb5b35247c5db57a91d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fib/fib.cpp", "max_forks_repo_name": "Matsuyanagi/fibonacci_cpp", "max_forks_repo_head_hexsha": "9bc94184cf6a9ac33a602cb5b35247c5db57a91d", "max_forks_repo_licenses": ["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.7272727273, "max_line_length": 58, "alphanum_fraction": 0.48, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.633144062424408}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n#include \"./include/prints.hpp\"\n\nstd::vector<int> baseIndex;\n\nvoid triangularize(Eigen::MatrixXd& B){\n    int _m = B.rows();\n    int _n = B.cols();\n    int start_row = 0;                                  // \u6bcf\u6b21\u4ecestart_row\u5f00\u59cb\u5224\u5b9a\n    for (int col = 0; col < _n; col ++){\n        int row = start_row;\n        bool push_flag = false;\n        if (B(row, col) == 0.0){\n            for (; row < _m; row ++){\n                if (B(row, col) != 0.0){\n                    B.row(col).swap(B.row(row));        // \u4e3a0\u548c\u4e0d\u4e3a0\u884c\u8fdb\u884c\u4ea4\u6362\n                    push_flag = true;\n                    row ++;\n                    break;\n                }\n            }\n        }\n        else{\n            row ++;\n            push_flag = true;\n        }\n        for (; row < _m; row ++){\n            double head = B(row, col);\n            if (head != 0.0){\n                B.row(row) -= head / B(col, col) * B.row(col);  // \u6d88\u9664\u5934\u90e80\n            }\n        }\n        if (push_flag == true){\n            baseIndex.emplace_back(col);\n            start_row ++;\n            if (start_row >= _m){\n                return;\n            }\n        }\n    }\n}\n\nint main(){\n    std::cout << \"==================== test ladderize ==================\\n\";\n    int row = 3, col = 6;\n    Eigen::MatrixXd mat(row, col);\n    mat << 1, -2, 1, 0, 0, 2,\n        0, 1, -3, 1, 0, 1,\n        0, 1, -1, 0, 1, 2;\n    std::cout << \"Before ladderize:\\n\";\n    printMat(mat); \n    triangularize(mat);\n    std::cout << \"After ladderize:\\n\";\n    printMat(mat);\n    std::cout << \"Base index:\\n\";\n    for (int ind: baseIndex){\n        std::cout << ind << \", \";\n    }\n    std::cout << std::endl;\n    Eigen::MatrixXd B(row, row);\n    for (int i = 0; i < row; i++){\n        B.col(i) = mat.col(baseIndex[i]);\n    }\n    std::cout << \"B:\\n\";\n    printMat(B);\n    Eigen::MatrixXd Binv = B.colPivHouseholderQr().solve(Eigen::MatrixXd::Identity(row, row));\n    std::cout << \"Binv:\\n\";\n    printMat(Binv);\n    Eigen::MatrixXd res = Binv * mat;\n    std::cout << \"Result:\\n\";\n    printMat(res);\n    return 0;\n}", "meta": {"hexsha": "cff52575488346d7548b3acdcfc407e98a1051d4", "size": 2102, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/testConcat.cc", "max_stars_repo_name": "Enigmatisms/Operation", "max_stars_repo_head_hexsha": "c68f6246a448ba1be18597b2145eee882cb6478e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T12:04:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T03:15:44.000Z", "max_issues_repo_path": "cpp/testConcat.cc", "max_issues_repo_name": "Enigmatisms/Operation", "max_issues_repo_head_hexsha": "c68f6246a448ba1be18597b2145eee882cb6478e", "max_issues_repo_licenses": ["MIT"], "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/testConcat.cc", "max_forks_repo_name": "Enigmatisms/Operation", "max_forks_repo_head_hexsha": "c68f6246a448ba1be18597b2145eee882cb6478e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-13T01:30:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-13T01:30:18.000Z", "avg_line_length": 27.6578947368, "max_line_length": 94, "alphanum_fraction": 0.435775452, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6331440568373543}}
{"text": "//\n// Copyright 2020 Debabrata Mandal <mandaldebabrata123@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n#ifndef BOOST_GIL_IMAGE_PROCESSING_HISTOGRAM_EQUALIZATION_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_HISTOGRAM_EQUALIZATION_HPP\n\n#include <boost/gil/histogram.hpp>\n#include <boost/gil/image.hpp>\n\n#include <cmath>\n#include <map>\n#include <vector>\n\nnamespace boost { namespace gil {\n\n\n/////////////////////////////////////////\n/// Histogram Equalization(HE)\n/////////////////////////////////////////\n/// \\defgroup HE HE\n/// \\brief Contains implementation and description of the algorithm used to compute\n///        global histogram equalization of input images.\n///\n///        Algorithm :-\n///        1. If histogram A is to be equalized compute the cumulative histogram of A.\n///        2. Let CFD(A) refer to the cumulative histogram of A\n///        3. For a uniform histogram A', CDF(A') = A'\n///        4. We need to transfrom A to A' such that\n///        5. CDF(A') = CDF(A) => A' = CDF(A)\n///        6. Hence the pixel transform , px => histogram_of_ith_channel[px].\n///\n\n/// \\fn histogram_equalization\n/// \\ingroup HE\n/// \\tparam SrcKeyType Key Type of input histogram\n/// @param src_hist INPUT Input source histogram\n/// \\brief Overload for histogram equalization algorithm, takes in a single source histogram \n///        and returns the color map used for histogram equalization.\n///\ntemplate <typename SrcKeyType>\nstd::map<SrcKeyType, SrcKeyType> histogram_equalization(histogram<SrcKeyType> const& src_hist)\n{\n    histogram<SrcKeyType> dst_hist;\n    return histogram_equalization(src_hist, dst_hist);\n}\n\n/// \\overload histogram_equalization\n/// \\ingroup HE\n/// \\tparam SrcKeyType Key Type of input histogram\n/// \\tparam DstKeyType Key Type of output histogram\n/// @param src_hist INPUT source histogram\n/// @param dst_hist OUTPUT Output histogram\n/// \\brief Overload for histogram equalization algorithm, takes in both source histogram &\n///        destination histogram and returns the color map used for histogram equalization\n///        as well as transforming the destination histogram.\n///\ntemplate <typename SrcKeyType, typename DstKeyType>\nstd::map<SrcKeyType, DstKeyType>\n    histogram_equalization(histogram<SrcKeyType> const& src_hist, histogram<DstKeyType>& dst_hist)\n{\n    static_assert(\n        std::is_integral<SrcKeyType>::value &&\n        std::is_integral<DstKeyType>::value,\n        \"Source and destination histogram types are not appropriate\");\n\n    using value_t = typename histogram<SrcKeyType>::value_type;\n    dst_hist.clear();\n    double sum          = src_hist.sum();\n    SrcKeyType min_key  = std::numeric_limits<DstKeyType>::min();\n    SrcKeyType max_key  = std::numeric_limits<DstKeyType>::max();\n    auto cumltv_srchist = cumulative_histogram(src_hist);\n    std::map<SrcKeyType, DstKeyType> color_map;\n    std::for_each(cumltv_srchist.begin(), cumltv_srchist.end(), [&](value_t const& v) {\n        DstKeyType trnsfrmd_key =\n            static_cast<DstKeyType>((v.second * (max_key - min_key)) / sum + min_key);\n        color_map[std::get<0>(v.first)] = trnsfrmd_key;\n    });\n    std::for_each(src_hist.begin(), src_hist.end(), [&](value_t const& v) {\n        dst_hist[color_map[std::get<0>(v.first)]] += v.second;\n    });\n    return color_map;\n}\n\n/// \\overload histogram_equalization\n/// \\ingroup HE\n/// @param src_view  INPUT source image view\n/// @param dst_view  OUTPUT Output image view\n/// @param bin_width INPUT Histogram bin width\n/// @param mask      INPUT Specify is mask is to be used\n/// @param src_mask  INPUT Mask vector over input image\n/// \\brief Overload for histogram equalization algorithm, takes in both source & destination\n///        image views and histogram equalizes the input image.\n///\ntemplate <typename SrcView, typename DstView>\nvoid histogram_equalization(\n    SrcView const& src_view,\n    DstView const& dst_view,\n    std::size_t bin_width = 1,\n    bool mask = false,\n    std::vector<std::vector<bool>> src_mask = {})\n{\n    gil_function_requires<ImageViewConcept<SrcView>>();\n    gil_function_requires<MutableImageViewConcept<DstView>>();\n\n    static_assert(\n        color_spaces_are_compatible<\n            typename color_space_type<SrcView>::type,\n            typename color_space_type<DstView>::type>::value,\n        \"Source and destination views must have same color space\");\n    \n    // Defining channel type\n    using source_channel_t = typename channel_type<SrcView>::type;\n    using dst_channel_t    = typename channel_type<DstView>::type;\n    using coord_t          = typename SrcView::x_coord_t;\n\n    std::size_t const channels = num_channels<SrcView>::value;\n    coord_t const width        = src_view.width();\n    coord_t const height       = src_view.height();\n    std::size_t pixel_max      = std::numeric_limits<dst_channel_t>::max();\n    std::size_t pixel_min      = std::numeric_limits<dst_channel_t>::min();\n\n    for (std::size_t i = 0; i < channels; i++)\n    {\n        histogram<source_channel_t> h;\n        fill_histogram(nth_channel_view(src_view, i), h, bin_width, false, false, mask, src_mask);\n        h.normalize();\n        auto h2 = cumulative_histogram(h);\n        for (std::ptrdiff_t src_y = 0; src_y < height; ++src_y)\n        {\n            auto src_it = nth_channel_view(src_view, i).row_begin(src_y);\n            auto dst_it = nth_channel_view(dst_view, i).row_begin(src_y);\n            for (std::ptrdiff_t src_x = 0; src_x < width; ++src_x)\n            {\n                if (mask && !src_mask[src_y][src_x])\n                    dst_it[src_x][0] = channel_convert<dst_channel_t>(src_it[src_x][0]);\n                else\n                    dst_it[src_x][0] = static_cast<dst_channel_t>(\n                        h2[src_it[src_x][0]] * (pixel_max - pixel_min) + pixel_min);\n            }\n        }\n    }\n}\n\n}}  //namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "d33c6f46633d369908f504a564af9255b8a33117", "size": 5996, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/histogram_equalization.hpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "include/boost/gil/image_processing/histogram_equalization.hpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "include/boost/gil/image_processing/histogram_equalization.hpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 39.7086092715, "max_line_length": 98, "alphanum_fraction": 0.6696130754, "num_tokens": 1438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6331247171395337}}
{"text": "// https://www.boost.org/doc/libs/1_71_0/more/getting_started/windows.html\r\n\r\n#include <boost/lambda/lambda.hpp>\r\n#include <iostream>\r\n#include <iterator>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\nusing namespace boost::lambda;\r\n\r\nint main()\r\n{\r\n\ttypedef istream_iterator<int> in;\r\n\r\n\tcout << \"Usage: Enter some numbers in the console with space between and press enter\" << endl;\r\n\r\n\tfor_each(\r\n\t\tin(cin), in(), cout << (_1 * 3) << \" \");\r\n}\r\n", "meta": {"hexsha": "49161645fd4eb8a91e9d4aa73eba34f1dc48af08", "size": 447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vs-tutorials/boost-lambda/boost-lambda.cpp", "max_stars_repo_name": "haraldhoff/vcpkg", "max_stars_repo_head_hexsha": "48281bb4d8eb6d07362b638fd73004a99dd239df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vs-tutorials/boost-lambda/boost-lambda.cpp", "max_issues_repo_name": "haraldhoff/vcpkg", "max_issues_repo_head_hexsha": "48281bb4d8eb6d07362b638fd73004a99dd239df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vs-tutorials/boost-lambda/boost-lambda.cpp", "max_forks_repo_name": "haraldhoff/vcpkg", "max_forks_repo_head_hexsha": "48281bb4d8eb6d07362b638fd73004a99dd239df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.35, "max_line_length": 96, "alphanum_fraction": 0.6733780761, "num_tokens": 107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.6331247125694556}}
{"text": "#include \"layer.h\"\n\n#include <random>\n#include <cmath>\n#include <boost/range/algorithm/fill.hpp>\n#include <boost/range/algorithm/for_each.hpp>\n\nnamespace ann {\n\nLayer::Layer(size_t inputRowCount, size_t outputRowCount, layerFx forwardFunc, layerFx derivateFunc)\n    : mForwardFunc(forwardFunc)\n    , mDerivateFunc(derivateFunc)\n{\n    mWeights = math::make_matrix<float>(outputRowCount, inputRowCount);\n    mBias = math::make_matrix<float>(outputRowCount, 1);\n\n    std::random_device rd{};\n    std::mt19937 generator{rd()};\n    std::normal_distribution<float> distribution{0.0f, 1.0f};\n\n    const auto div = std::sqrtf(static_cast<float>(inputRowCount / 2));\n    boost::for_each(mWeights, [&generator, &distribution, &div](float &value) {\n        value = distribution(generator) / div;\n    });\n    boost::fill(mBias, 0.01f);\n}\n\nmath::MatrixF Layer::feedForward(const math::MatrixF &inputData)\n{\n    mInput = inputData;\n    mZ = (mWeights * mInput).addColumnVector(mBias);\n    mActivation = mForwardFunc(mZ);\n    return mActivation;\n}\n\nmath::MatrixF Layer::beginBackPropagation(const math::MatrixF &expectedOutput)\n{\n    const auto m = static_cast<float>(mInput.getColumnCount());\n\n    auto lossd = mActivation - expectedOutput;\n    mWeightDelta = (1.0f / m) * (lossd * mInput.transpose());\n    mBiasDelta =  (1.0f / m) * math::rowSum(lossd);\n\n    return mWeights.transpose() * lossd;\n}\n\nmath::MatrixF Layer::calculateGradients(const math::MatrixF& prevDz)\n{\n    const auto m = static_cast<float>(mInput.getColumnCount());\n\n    const auto dz = prevDz.hadamardProduct(mDerivateFunc(mActivation));\n    mWeightDelta = (1.0f / m) * (dz * mInput.transpose());\n    mBiasDelta = (1.0f / m) * math::rowSum(dz);\n\n    return mWeights.transpose() * dz;\n}\n\nvoid Layer::applyGradients(float learnSpeed)\n{\n    mWeights = mWeights - (learnSpeed * mWeightDelta);\n    mBias = mBias - (learnSpeed * mBiasDelta);\n}\n\n}", "meta": {"hexsha": "083125e162baede3ad2da497a55279548cc200db", "size": 1896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/ann_lib/src/layer.cpp", "max_stars_repo_name": "elnoir/ge_test", "max_stars_repo_head_hexsha": "a85a6ea95452005c4c6428faa80b1a8b3d4fd6a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libs/ann_lib/src/layer.cpp", "max_issues_repo_name": "elnoir/ge_test", "max_issues_repo_head_hexsha": "a85a6ea95452005c4c6428faa80b1a8b3d4fd6a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libs/ann_lib/src/layer.cpp", "max_forks_repo_name": "elnoir/ge_test", "max_forks_repo_head_hexsha": "a85a6ea95452005c4c6428faa80b1a8b3d4fd6a4", "max_forks_repo_licenses": ["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.625, "max_line_length": 100, "alphanum_fraction": 0.6946202532, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.6331135957274999}}
{"text": "#include <Eigen/StdVector>\n#include <unsupported/Eigen/BVH>\n#include <iostream>\n\nusing namespace Eigen;\ntypedef AlignedBox<double, 2> Box2d;\n\nBox2d ei_bounding_box(const Vector2d &v) { return Box2d(v, v); } //compute the bounding box of a single point\n\nstruct PointPointMinimizer //how to compute squared distances between points and rectangles\n{\n  PointPointMinimizer() : calls(0) {}\n  typedef double Scalar;\n\n  double minimumOnVolumeVolume(const Box2d &r1, const Box2d &r2) { ++calls; return r1.squaredExteriorDistance(r2); }\n  double minimumOnVolumeObject(const Box2d &r, const Vector2d &v) { ++calls; return r.squaredExteriorDistance(v); }\n  double minimumOnObjectVolume(const Vector2d &v, const Box2d &r) { ++calls; return r.squaredExteriorDistance(v); }\n  double minimumOnObjectObject(const Vector2d &v1, const Vector2d &v2) { ++calls; return (v1 - v2).squaredNorm(); }\n\n  int calls;\n};\n\nint main()\n{\n  typedef std::vector<Vector2d, aligned_allocator<Vector2d> > StdVectorOfVector2d;\n  StdVectorOfVector2d redPoints, bluePoints;\n  for(int i = 0; i < 100; ++i) { //initialize random set of red points and blue points\n    redPoints.push_back(Vector2d::Random());\n    bluePoints.push_back(Vector2d::Random());\n  }\n\n  PointPointMinimizer minimizer;\n  double minDistSq = std::numeric_limits<double>::max();\n\n  //brute force to find closest red-blue pair\n  for(int i = 0; i < (int)redPoints.size(); ++i)\n    for(int j = 0; j < (int)bluePoints.size(); ++j)\n      minDistSq = std::min(minDistSq, minimizer.minimumOnObjectObject(redPoints[i], bluePoints[j]));\n  std::cout << \"Brute force distance = \" << sqrt(minDistSq) << \", calls = \" << minimizer.calls << std::endl;\n\n  //using BVH to find closest red-blue pair\n  minimizer.calls = 0;\n  KdBVH<double, 2, Vector2d> redTree(redPoints.begin(), redPoints.end()), blueTree(bluePoints.begin(), bluePoints.end()); //construct the trees\n  minDistSq = BVMinimize(redTree, blueTree, minimizer); //actual BVH minimization call\n  std::cout << \"BVH distance         = \" << sqrt(minDistSq) << \", calls = \" << minimizer.calls << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "d135fd99062531c72bc4ad4dac291eafd4485d95", "size": 2089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/unsupported/doc/examples/BVH_Example.cpp", "max_stars_repo_name": "dailysoap/CSMM.104x", "max_stars_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "t1m1/include/eigen/unsupported/doc/examples/BVH_Example.cpp", "max_issues_repo_name": "dailysoap/CSMM.104x", "max_issues_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "t1m1/include/eigen/unsupported/doc/examples/BVH_Example.cpp", "max_forks_repo_name": "dailysoap/CSMM.104x", "max_forks_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 42.6326530612, "max_line_length": 143, "alphanum_fraction": 0.7108664433, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6330634609994636}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Boost Graph Library along with the software; see the file LICENSE.\r\n// If not, contact Office of Research, Indiana University,\r\n// Bloomington, IN 47405.\r\n//\r\n// Permission to modify the code and to distribute the code is\r\n// granted, provided the text of this NOTICE is retained, a notice if\r\n// the code was modified is included with the above COPYRIGHT NOTICE\r\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\r\n// LICENSE file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n#include <iostream>\r\n#include <boost/graph/edge_list.hpp>\r\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  // ID numbers for the routers (vertices).\r\n  enum\r\n  { A, B, C, D, E, F, G, H, n_vertices };\r\n  const int n_edges = 11;\r\n  typedef std::pair < int, int >Edge;\r\n\r\n  // The list of connections between routers stored in an array.\r\n  Edge edges[] = {\r\n  Edge(A, B), Edge(A, C),\r\n        Edge(B, D), Edge(B, E), Edge(C, E), Edge(C, F), Edge(D, H),\r\n        Edge(D, E), Edge(E, H), Edge(F, G), Edge(G, H)\r\n  };\r\n\r\n  // Specify the graph type and declare a graph object\r\n  typedef edge_list < Edge*, Edge, std::ptrdiff_t, std::random_access_iterator_tag> Graph;\r\n  Graph g(edges, edges + n_edges);\r\n\r\n  // The transmission delay values for each edge.  \r\n  float delay[] =\r\n    {5.0, 1.0, 1.3, 3.0, 10.0, 2.0, 6.3, 0.4, 1.3, 1.2, 0.5};\r\n\r\n  // Declare some storage for some \"external\" vertex properties.\r\n  char name[] = \"ABCDEFGH\";\r\n  int parent[n_vertices];\r\n  for (int i = 0; i < n_vertices; ++i)\r\n    parent[i] = i;\r\n  float distance[n_vertices];\r\n  std::fill(distance, distance + n_vertices, std::numeric_limits < float >::max());\r\n  // Specify A as the source vertex\r\n  distance[A] = 0;\r\n\r\n  bool r = bellman_ford_shortest_paths(g, int (n_vertices),\r\n                                       weight_map(make_iterator_property_map\r\n                                                  (&delay[0],\r\n                                                   get(edge_index, g),\r\n                                                   delay[0])).\r\n                                       distance_map(&distance[0]).\r\n                                       predecessor_map(&parent[0]));\r\n\r\n  if (r)\r\n    for (int i = 0; i < n_vertices; ++i)\r\n      std::cout << name[i] << \": \" << distance[i]\r\n        << \" \" << name[parent[i]] << std::endl;\r\n  else\r\n    std::cout << \"negative cycle\" << std::endl;\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "c7202b1c88bb7750d99d719e06bec8d3aecd22f6", "size": 3181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/bellman-ford-internet.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/bellman-ford-internet.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/graph/example/bellman-ford-internet.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7625, "max_line_length": 91, "alphanum_fraction": 0.5749764225, "num_tokens": 764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059707450325, "lm_q2_score": 0.7981867825403176, "lm_q1q2_score": 0.6330467030024928}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n\r\n//! \\file\r\n//!\\brief Perform tests of frexp and ldexp for fixed_point.\r\n\r\n#define BOOST_TEST_MODULE test_negatable_func_frexp_ldexp\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <cmath>\r\n#include <iomanip>\r\n#include <iostream>\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nnamespace local\r\n{\r\n  template<typename FixedPointType>\r\n  const FixedPointType& tolerance_maker(const int fuzzy_bits)\r\n  {\r\n    static const FixedPointType the_tolerance = ldexp(FixedPointType(1), FixedPointType::resolution + fuzzy_bits);\r\n\r\n    return the_tolerance;\r\n  }\r\n\r\n  template<typename FixedPointType,\r\n           typename FloatPointType = typename FixedPointType::float_type>\r\n  void test_frexp_ldexp(const int fuzzy_bits)\r\n  {\r\n    // Use at least 17 resolution bits.\r\n    // Use at least  6 range bits.\r\n\r\n    BOOST_STATIC_ASSERT(-FixedPointType::resolution >= 17);\r\n    BOOST_STATIC_ASSERT( FixedPointType::range      >=  6);\r\n\r\n    using std::ldexp;\r\n    using std::frexp;\r\n\r\n    const FixedPointType a1(boost::math::constants::pi        <FixedPointType>());      const FloatPointType b1(boost::math::constants::pi        <FloatPointType>());\r\n    const FixedPointType a2(boost::math::constants::e         <FixedPointType>());      const FloatPointType b2(boost::math::constants::e         <FloatPointType>());\r\n    const FixedPointType a3(boost::math::constants::ln_two    <FixedPointType>());      const FloatPointType b3(boost::math::constants::ln_two    <FloatPointType>());\r\n    const FixedPointType a4(boost::math::constants::zeta_three<FixedPointType>());      const FloatPointType b4(boost::math::constants::zeta_three<FloatPointType>());\r\n    const FixedPointType a5(boost::math::constants::pi        <FixedPointType>() * 11); const FloatPointType b5(boost::math::constants::pi        <FloatPointType>() * 11);\r\n    const FixedPointType a6(boost::math::constants::pi        <FixedPointType>() / 11); const FloatPointType b6(boost::math::constants::pi        <FloatPointType>() / 11);\r\n    const FixedPointType a7(boost::math::constants::ln_two    <FixedPointType>() /  5); const FloatPointType b7(boost::math::constants::ln_two    <FloatPointType>() /  5);\r\n    const FixedPointType a8(boost::math::constants::phi       <FixedPointType>() / 11); const FloatPointType b8(boost::math::constants::phi       <FloatPointType>() / 11);\r\n\r\n    FixedPointType c1; FixedPointType c2; FixedPointType c3; FixedPointType c4;\r\n    FixedPointType c5; FixedPointType c6; FixedPointType c7; FixedPointType c8;\r\n\r\n    int exp2a1; int exp2a2; int exp2a3; int exp2a4;\r\n    int exp2a5; int exp2a6; int exp2a7; int exp2a8;\r\n\r\n    int exp2b1; int exp2b2; int exp2b3; int exp2b4;\r\n    int exp2b5; int exp2b6; int exp2b7; int exp2b8;\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(c1 = frexp(a1, &exp2a1), FixedPointType(frexp(b1, &exp2b1)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(c2 = frexp(a2, &exp2a2), FixedPointType(frexp(b2, &exp2b2)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(c3 = frexp(a3, &exp2a3), FixedPointType(frexp(b3, &exp2b3)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(c4 = frexp(a4, &exp2a4), FixedPointType(frexp(b4, &exp2b4)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(c5 = frexp(a5, &exp2a5), FixedPointType(frexp(b5, &exp2b5)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(c6 = frexp(a6, &exp2a6), FixedPointType(frexp(b6, &exp2b6)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(c7 = frexp(a7, &exp2a7), FixedPointType(frexp(b7, &exp2b7)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(c8 = frexp(a8, &exp2a8), FixedPointType(frexp(b8, &exp2b8)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n\r\n    BOOST_CHECK_EQUAL(exp2a1, exp2b1);\r\n    BOOST_CHECK_EQUAL(exp2a2, exp2b2);\r\n    BOOST_CHECK_EQUAL(exp2a3, exp2b3);\r\n    BOOST_CHECK_EQUAL(exp2a4, exp2b4);\r\n    BOOST_CHECK_EQUAL(exp2a5, exp2b5);\r\n    BOOST_CHECK_EQUAL(exp2a6, exp2b6);\r\n    BOOST_CHECK_EQUAL(exp2a7, exp2b7);\r\n    BOOST_CHECK_EQUAL(exp2a8, exp2b8);\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c1, exp2a1), a1, tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c2, exp2a2), a2, tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c3, exp2a3), a3, tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c4, exp2a4), a4, tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c5, exp2a5), a5, tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c6, exp2a6), a6, tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c7, exp2a7), a7, tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c8, exp2a8), a8, tolerance_maker<FixedPointType>(fuzzy_bits));\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c1, exp2a1), FixedPointType(b1), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c2, exp2a2), FixedPointType(b2), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c3, exp2a3), FixedPointType(b3), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c4, exp2a4), FixedPointType(b4), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c5, exp2a5), FixedPointType(b5), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c6, exp2a6), FixedPointType(b6), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c7, exp2a7), FixedPointType(b7), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(ldexp(c8, exp2a8), FixedPointType(b8), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_func_frexp_ldexp)\r\n{\r\n  { typedef boost::fixed_point::negatable<  6,  -17> fixed_point_type; static_cast<void>(local::test_frexp_ldexp<fixed_point_type>(5)); }\r\n  { typedef boost::fixed_point::negatable<  6,  -25> fixed_point_type; static_cast<void>(local::test_frexp_ldexp<fixed_point_type>(5)); }\r\n  { typedef boost::fixed_point::negatable<  6,  -46> fixed_point_type; static_cast<void>(local::test_frexp_ldexp<fixed_point_type>(5)); }\r\n  { typedef boost::fixed_point::negatable<  6,  -57> fixed_point_type; static_cast<void>(local::test_frexp_ldexp<fixed_point_type>(5)); }\r\n  { typedef boost::fixed_point::negatable<  6, -121> fixed_point_type; static_cast<void>(local::test_frexp_ldexp<fixed_point_type>(5)); }\r\n  { typedef boost::fixed_point::negatable<  6, -233> fixed_point_type; static_cast<void>(local::test_frexp_ldexp<fixed_point_type>(5)); }\r\n  { typedef boost::fixed_point::negatable< 39, -200> fixed_point_type; static_cast<void>(local::test_frexp_ldexp<fixed_point_type>(5)); }\r\n  { typedef boost::fixed_point::negatable<100, -139> fixed_point_type; static_cast<void>(local::test_frexp_ldexp<fixed_point_type>(5)); }\r\n}\r\n", "meta": {"hexsha": "d596f38230b5f56ce147593dffef9ad20574a9be", "size": 7532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_frexp_ldexp.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_func_frexp_ldexp.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_func_frexp_ldexp.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": 66.0701754386, "max_line_length": 172, "alphanum_fraction": 0.7348645778, "num_tokens": 2192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7981867777396212, "lm_q1q2_score": 0.6330466835817636}}
{"text": "// Copyright (c) 2018 Graphcore Ltd. All rights reserved.\n// Simple tests for popsolver.\n//\n#include <popsolver/Model.hpp>\n#define BOOST_TEST_MODULE Div\n#include \"poplibs_support/Algorithm.hpp\"\n#include <boost/test/unit_test.hpp>\n\nusing namespace popsolver;\n\nBOOST_AUTO_TEST_CASE(CeilDiv) {\n  Model m;\n  auto a = m.addConstant(10);\n  auto b = m.addConstant(4);\n  auto c = m.ceildiv(a, b);\n  auto s = m.minimize(c);\n  BOOST_CHECK_EQUAL(s[c], DataType{3});\n}\n\nBOOST_AUTO_TEST_CASE(CeilDiv2) {\n  Model m;\n  auto a = m.addVariable();\n  auto b = m.addConstant(4);\n  auto c = m.ceildiv(a, b);\n  m.lessOrEqual(DataType{3}, c);\n  auto s = m.minimize(a);\n  BOOST_CHECK_EQUAL(s[a], DataType{9});\n  BOOST_CHECK_EQUAL(s[c], DataType{3});\n}\n\nBOOST_AUTO_TEST_CASE(FloorDiv) {\n  Model m;\n  auto a = m.addVariable();\n  auto b = m.addConstant(4);\n  auto c = m.floordiv(a, b);\n  m.lessOrEqual(DataType{3}, c);\n  auto s = m.minimize(a);\n  BOOST_CHECK_EQUAL(s[a], DataType{12});\n  BOOST_CHECK_EQUAL(s[c], DataType{3});\n}\n\nBOOST_AUTO_TEST_CASE(CeilDivZero) {\n  Model m;\n  auto a = m.addVariable();\n  auto b = m.addConstant(0);\n  auto c = m.ceildiv(a, b);\n  BOOST_CHECK_EQUAL(m.minimize(c).validSolution(), false);\n}\n\nBOOST_AUTO_TEST_CASE(CeilDivConstrainDivisor) {\n  using poplibs_support::ceildiv;\n  const unsigned maxDivisor = 20;\n  for (unsigned divisor = 1; divisor != maxDivisor; ++divisor) {\n    Model m;\n    const unsigned dividend = 49;\n    auto a = m.addConstant(dividend, \"a\");\n    auto b = m.addConstant(divisor, \"b\");\n    auto c = m.ceildivConstrainDivisor(a, b, \"c\");\n\n    auto s = m.minimize(c);\n    // The constrained div result is only valid when a smaller divisor would\n    // give a different result\n    auto expectSolution = divisor < 2 || ceildiv(dividend, divisor) !=\n                                             ceildiv(dividend, divisor - 1);\n    BOOST_CHECK_EQUAL(s.validSolution(), expectSolution);\n    // division correct?\n    if (expectSolution && s.validSolution()) {\n      BOOST_CHECK_EQUAL(s[c], DataType{poplibs_support::ceildiv(\n                                  dividend, s[b].getAs<unsigned>())});\n    }\n  }\n}\n", "meta": {"hexsha": "33ce0183fb1fe640575c50813b0cfcfd42996a36", "size": 2123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/popsolver/Div.cpp", "max_stars_repo_name": "graphcore/poplibs", "max_stars_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:28.000Z", "max_issues_repo_path": "tests/popsolver/Div.cpp", "max_issues_repo_name": "giantchen2012/poplibs", "max_issues_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/popsolver/Div.cpp", "max_forks_repo_name": "giantchen2012/poplibs", "max_forks_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:32:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T14:58:45.000Z", "avg_line_length": 29.0821917808, "max_line_length": 76, "alphanum_fraction": 0.6561469618, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.7122321903471562, "lm_q1q2_score": 0.633002624277988}}
{"text": "#ifndef MLA_SOLVERS_CONJUGATE_GRADIENT_HPP\n#define MLA_SOLVERS_CONJUGATE_GRADIENT_HPP\n\n#include <string>\n\n#include <boost/lexical_cast.hpp>\n\n#include <mla/matrix/all.h++>\n#include <mla/vector/all.h++>\n\n#include <mla/operations/level1/dot.h++>\n#include <mla/operations/level1/axpy.h++>\n#include <mla/operations/level1/scale.h++>\n#include <mla/operations/level2/gemv.h++>\n\n#include <mla/solvers/SolverReturnCodes.h++>\n\n#include <mla/output.h++>\n\nnamespace mla\n{\n\n\n/**\n * Conjugate gradient method algorithm\n *\n *@param A\tMatrix\n *@param x\tunknown vector\n *@param b\tvector\n *@param delta\terror tolerance\n *@param max_iterations\tmaximum number of iterations allowed\n *\n *@return \n */\ntemplate<typename Scalar, template<typename> class MatrixStoragePolicy, template<typename> class VectorStoragePolicyX, template<typename> class VectorStoragePolicyB >\nReturnCode \ncg(MatrixStoragePolicy<Scalar> &A, VectorStoragePolicyX<Scalar> &x, VectorStoragePolicyB<Scalar> &b, const double delta, int max_iterations) \n{\n\tif( !A.isSquare() )\n\t{\n\t\tthrow LAException(\"cg: A must be a square matrix\");\n\t}\n\n\tif(A.columns() != b.size())\n\t{\n\t\tthrow LAException(\"cg: A.columns() != b.size()\");\n\t}\n\n\tx.resize( b.size() );\n\n\tVectorStoragePolicyB<Scalar> r, p(A.columns());\n\tVectorStoragePolicyB<Scalar> Ap(A.columns());\n\tScalar dotrr, dotrrnew, alpha;\n\n\t//r = b - A*x;\n\tr = b;\n\tmla::gemv( (Scalar)(-1.0f), A, x, (Scalar)(1.0f), r );\n\tp = r;\n\n\tdotrr = dot(r,r);\n\n\tfor (int iter = 0; iter < max_iterations; iter++)\n\t{\n\t\t//Ap = A*p;\n\t\tmla::gemv( (Scalar)1.0f, A, p, (Scalar)1.0f, Ap);\n\n\t\talpha = dotrr/dot(p,Ap);\n\t\t//x = x + alpha*p;\n\t\tmla::axpy(alpha, p, x);\n\t\t\n\t\t// r_{k+1] = r_{k} - a*A*p\n\t\tmla::axpy( (Scalar)-1.0f*alpha, Ap, r);\n\n\t\tdotrrnew = dot(r,r);\n\n\t\tif(dotrrnew < delta)\n\t\t{\n\t\t\treturn OK;\n\t\t}\n\n\t\t//p = r + (dotrrnew/dotrr)*p;\n\t\tmla::scale( dotrrnew/dotrr, p);\n\t\tmla::axpy( (Scalar)1.0f, r, p);\n\n\t\tdotrr = dotrrnew;\n\t}\n\n\treturn ERR_EXCESSIVE_ITERATIONS;\n}\n\n\n}\n\n#endif\n", "meta": {"hexsha": "1e23910da8bbf7b7ef7f5ed7177b33741e7b1e94", "size": 1948, "ext": "h++", "lang": "C++", "max_stars_repo_path": "mla/solvers/CG.h++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mla/solvers/CG.h++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mla/solvers/CG.h++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5052631579, "max_line_length": 166, "alphanum_fraction": 0.6673511294, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.633002620080869}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE cubicspline_test\n\n// Standard includes\n#include <iostream>\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/tools/cubicspline.h\"\n\nusing namespace votca::tools;\n\nBOOST_AUTO_TEST_SUITE(cubicspline_test)\n\nBOOST_AUTO_TEST_CASE(spline_grid_high) {\n  CubicSpline cspline;\n  cspline.setBCInt(0);\n  cspline.GenerateGrid(0, 9, 2);\n  Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(5);\n  values_ref << 0, 2, 4, 6, 9;\n\n  bool equal_val = values_ref.isApprox(cspline.getX(), 1e-5);\n  BOOST_CHECK_EQUAL(equal_val, true);\n  if (!equal_val) {\n    std::cout << \"result value\" << std::endl;\n    std::cout << cspline.getX().transpose() << std::endl;\n    std::cout << \"ref value\" << std::endl;\n    std::cout << values_ref.transpose() << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(spline_grid_low) {\n  CubicSpline cspline;\n  cspline.setBCInt(0);\n  cspline.GenerateGrid(0, 7, 2);\n  Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(4);\n  values_ref << 0, 2, 4, 7;\n\n  bool equal_val = values_ref.isApprox(cspline.getX(), 1e-5);\n  BOOST_CHECK_EQUAL(equal_val, true);\n  if (!equal_val) {\n    std::cout << \"result value\" << std::endl;\n    std::cout << cspline.getX().transpose() << std::endl;\n    std::cout << \"ref value\" << std::endl;\n    std::cout << values_ref.transpose() << std::endl;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(cubicspline_fit_test) {\n\n  votca::Index size = 80;\n  Eigen::VectorXd x = Eigen::VectorXd::Zero(size);\n  Eigen::VectorXd y = Eigen::VectorXd::Zero(size);\n  for (votca::Index i = 0; i < size; ++i) {\n    x(i) = 0.25 * double(i);\n    y(i) = std::sin(x(i));\n  }\n  CubicSpline cspline;\n  cspline.setBCInt(0);\n  cspline.GenerateGrid(0.4, 0.6, 0.1);\n  Eigen::VectorXd gridpoints_ref = Eigen::VectorXd::Zero(3);\n  gridpoints_ref << 0.4, 0.5, 0.6;\n  bool grid_check = cspline.getX().isApprox(gridpoints_ref, 1e-5);\n  BOOST_CHECK_EQUAL(grid_check, true);\n  if (!grid_check) {\n    std::cout << \"result value\" << std::endl;\n    std::cout << cspline.getX().transpose() << std::endl;\n    std::cout << \"ref value\" << std::endl;\n    std::cout << gridpoints_ref.transpose() << std::endl;\n  }\n  cspline.Fit(x, y);\n\n  Eigen::VectorXd rs = Eigen::VectorXd::Zero(10);\n  rs << 0.45, 0.47, 0.8, 0.75, 0.6, 0.4, 0.9, 0.55, 0, 0;\n  Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(10);\n  values_ref << 0.311213, 0.310352, 0.296153, 0.298304, 0.304759, 0.313364,\n      0.291851, 0.30691, 0.33058, 0.33058;\n  Eigen::VectorXd derivatives_ref = Eigen::VectorXd::Zero(10);\n  derivatives_ref << -0.0430277, -0.0430282, -0.0430231, -0.0430267, -0.0430313,\n      -0.0430272, -0.0430128, -0.0430308, -0.04306, -0.04306;\n  Eigen::VectorXd values = cspline.Calculate(rs);\n  Eigen::VectorXd derivatives = cspline.CalculateDerivative(rs);\n\n  bool equal_val = values_ref.isApprox(values, 1e-5);\n\n  if (!equal_val) {\n    std::cout << \"result value\" << std::endl;\n    std::cout << values.transpose() << std::endl;\n    std::cout << \"ref value\" << std::endl;\n    std::cout << values_ref.transpose() << std::endl;\n  }\n  BOOST_CHECK_EQUAL(equal_val, true);\n\n  bool equal_derivative = derivatives_ref.isApprox(derivatives, 1e-5);\n\n  if (!equal_derivative) {\n    std::cout << \"result value\" << std::endl;\n    std::cout << derivatives.transpose() << std::endl;\n    std::cout << \"ref value\" << std::endl;\n    std::cout << derivatives_ref.transpose() << std::endl;\n  }\n  BOOST_CHECK_EQUAL(equal_derivative, true);\n}\n\nBOOST_AUTO_TEST_CASE(cubicspline_interpolate_test) {\n\n  int size = 80;\n  Eigen::VectorXd x = Eigen::VectorXd::Zero(size);\n  Eigen::VectorXd y = Eigen::VectorXd::Zero(size);\n  for (int i = 0; i < size; ++i) {\n    x(i) = 0.25 * i;\n    y(i) = std::sin(x(i));\n  }\n  CubicSpline cspline;\n  cspline.setBCInt(0);\n  cspline.Interpolate(x, y);\n\n  Eigen::VectorXd rs = Eigen::VectorXd::Zero(10);\n  rs << 0.45, 0.47, 0.8, 0.75, 0.6, 0.4, 0.9, 0.55, 0, 0;\n  Eigen::VectorXd values_ref = Eigen::VectorXd::Zero(10);\n  values_ref << 0.434964, 0.452886, 0.717353, 0.681639, 0.564637, 0.389415,\n      0.78332, 0.522684, 0, 0;\n  Eigen::VectorXd derivatives_ref = Eigen::VectorXd::Zero(10);\n  derivatives_ref << 0.900494, 0.891601, 0.69661, 0.731673, 0.825305, 0.921091,\n      0.621663, 0.852451, 0.999978, 0.999978;\n  Eigen::VectorXd values = cspline.Calculate(rs);\n  Eigen::VectorXd derivatives = cspline.CalculateDerivative(rs);\n\n  bool equal_val = values_ref.isApprox(values, 1e-5);\n\n  if (!equal_val) {\n    std::cout << \"result value\" << std::endl;\n    std::cout << values.transpose() << std::endl;\n    std::cout << \"ref value\" << std::endl;\n    std::cout << values_ref.transpose() << std::endl;\n  }\n  BOOST_CHECK_EQUAL(equal_val, true);\n\n  bool equal_derivative = derivatives_ref.isApprox(derivatives, 1e-5);\n\n  if (!equal_derivative) {\n    std::cout << \"result value\" << std::endl;\n    std::cout << derivatives.transpose() << std::endl;\n    std::cout << \"ref value\" << std::endl;\n    std::cout << derivatives_ref.transpose() << std::endl;\n  }\n  BOOST_CHECK_EQUAL(equal_derivative, true);\n}\n\nBOOST_AUTO_TEST_CASE(cubicspline_matrix_test) {\n\n  CubicSpline cspline;\n  cspline.setBCInt(0);\n  cspline.GenerateGrid(0.4, 0.6, 0.1);\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(1, 6);\n  Eigen::MatrixXd Aref = Eigen::MatrixXd::Zero(1, 6);\n\n  Aref << 0.0, -9.0, 10.0, 0.0, -0.03333333, -0.01666667;\n\n  cspline.AddToFitMatrix(A, 0.5, 0, 0, 1.0, 1.0);\n\n  bool equalMatrix = Aref.isApprox(A, 1e-5);\n  if (!equalMatrix) {\n    std::cout << \"result A\" << std::endl;\n    std::cout << A << std::endl;\n    std::cout << \"ref A\" << std::endl;\n    std::cout << Aref << std::endl;\n  }\n  BOOST_CHECK_EQUAL(equalMatrix, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "cc114244a88c47ce03e87e4a5ecb076fea5b6b1a", "size": 6328, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_cubicspline.cc", "max_stars_repo_name": "MrTheodor/tools", "max_stars_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/test_cubicspline.cc", "max_issues_repo_name": "MrTheodor/tools", "max_issues_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_cubicspline.cc", "max_forks_repo_name": "MrTheodor/tools", "max_forks_repo_head_hexsha": "9bb95454a188e827bdf25a6de8302cde70355ecb", "max_forks_repo_licenses": ["Apache-2.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.7875647668, "max_line_length": 80, "alphanum_fraction": 0.6597661188, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.63293585022178}}
{"text": "/*\n * Copyright Evan Miller, 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"mp_t.hpp\"\n#include <boost/math/tools/test_data.hpp>\n#include <boost/test/included/prg_exec_monitor.hpp>\n#include <boost/math/special_functions/jacobi_theta.hpp>\n#include <fstream>\n#include <boost/math/tools/test_data.hpp>\n\nusing namespace boost::math::tools;\nusing namespace boost::math;\nusing namespace std;\n\nstruct jacobi_theta_data_generator\n{\n   boost::math::tuple<mp_t, mp_t, mp_t, mp_t> operator()(mp_t z, mp_t tau)\n   {\n      return boost::math::make_tuple(\n              jacobi_theta1tau(z, tau),\n              jacobi_theta2tau(z, tau),\n              jacobi_theta3tau(z, tau),\n              jacobi_theta4tau(z, tau));\n   }\n};\n\nint cpp_main(int argc, char*argv [])\n{\n   parameter_info<mp_t> arg1, arg2;\n   test_data<mp_t> data;\n\n   bool cont;\n   std::string line;\n\n   if(argc < 1)\n      return 1;\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for the Jacobi Theta functions.\\n\"\n      ;\n\n   do{\n      if(0 == get_user_parameter_info(arg1, \"z\"))\n         return 1;\n      if(0 == get_user_parameter_info(arg2, \"tau\"))\n         return 1;\n\n      data.insert(jacobi_theta_data_generator(), arg1, arg2);\n\n      std::cout << \"Any more data [y/n]?\";\n      std::getline(std::cin, line);\n      boost::algorithm::trim(line);\n      cont = (line == \"y\");\n   } while(cont);\n\n   std::cout << \"Generating \" << data.size() << \" test points.\";\n\n   std::cout << \"Enter name of test data file [default=jacobi_theta.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"jacobi_theta.ipp\";\n   std::ofstream ofs(line.c_str());\n   ofs << std::scientific << std::setprecision(40);\n   write_code(ofs, data, \"jacobi_theta_data\");\n\n   return 0;\n}\n", "meta": {"hexsha": "16c4f7fd8159f29bd66338f37fdf5d9fdd92d053", "size": 1942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/jacobi_theta_data.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "tools/jacobi_theta_data.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "tools/jacobi_theta_data.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 26.602739726, "max_line_length": 79, "alphanum_fraction": 0.6395468589, "num_tokens": 525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6328813122114214}}
{"text": "#include <memory>\n#include <algorithm>\n#include <vector>\n#include \"lib.h\"\n#include \"expression.h\"\n#include \"phase_expression.h\"\n#include \"phase_solver.h\"\n#include <thread>\n#include <iterator>\n#include \"exprtk.hpp\"\n\n#include <boost/numeric/odeint.hpp>\n#include <cmath>\n\nusing Variables = exprtk::symbol_table<double>;\nusing Formula = exprtk::expression<double>;\nusing Parser = exprtk::parser<double>;\n\nusing state_type = std::vector<double>;\n\nclass CauchyProblem {\n\npublic:\n    CauchyProblem(double init_x, double init_y):\n        _init_x(init_x), _init_y(init_y) { };\n\n    void operator()(const state_type & x, state_type & dxdt, double t) {\n        dxdt[0] = 2 * std::exp(pow(t, 2)) - x[0] / t;\n    };\n\nprivate:\n    double _init_x;\n    double _init_y;\n};\n\ndouble ode(double x, double t) {\n    return 2 * std::exp(pow(t, 2)) - x / t;;\n}\n\ndouble runge_kutta_step(double x, double t, double step) {\n    auto k1 = ode(x, t);\n    auto k2 = ode(x + step / 2 * k1, t + step / 2);\n    auto k3 = ode(x + step / 2 * k2, t + step / 2);\n    auto k4 = ode(x + step * k3, t + step);\n    return x + step / 6 * (k1 + 2 * k2 + 2 * k3 + k4);\n}\n\nauto expression = std::make_shared<PhaseExpression>(\n        1, \n        \"2*exp(t^2)-x/t\", \n        std::make_pair(0.0, 0.0));\n\ndouble runge_kutta_step_expr(double x, double t, double step) {\n \n    auto k1 = expression->evaluate(x, t);\n    auto k2 = expression->evaluate(x + step / 2 * k1, t + step / 2);\n    auto k3 = expression->evaluate(x + step / 2 * k2, t + step / 2);\n    auto k4 = expression->evaluate(x + step * k3, t + step);\n    return x + step / 6 * (k1 + 2 * k2 + 2 * k3 + k4);\n}\n\nvoid cauchy_problem(const state_type & x, state_type & dxdt, double t) {\n    dxdt[0] = 2 * std::exp(pow(t, 2)) - x[0] / t;\n};\n\nint main (int argc, char * argv[])\n{\n    const double t = 1;\n    const double m_x = std::exp(1);\n    const double step = 0.0000001;\n\n    // auto system = CauchyProblem(1, std::exp(1));\n    // auto stepper = boost::numeric::odeint::runge_kutta4<state_type>();\n\n    // state_type x { std::exp(1) };\n    //     // state_type x { 27.2991 };\n\n    // boost::numeric::odeint::integrate_const(stepper, system, x, 1.0, 2.0, step);\n\n    // std::cout<< \"The solution at 2.0 is \" << x[x.size() - 1] << std::endl;\n\n    // auto expression = std::make_shared<PhaseExpression>(\n    //     1, \n    //     \"2*exp(t^2)-x/t\", \n    //     std::make_pair(m_x, t));\n    // auto solver = PhaseSolver(expression, std::make_pair(m_x, t));\n    // auto result = solver.solve(2.0, step);\n    // std::cout<< \"The solution with CustomSolver at 2.0 is \" << result << std::endl;\n\n    auto correctColution = std::exp(pow(2, 2)) / 2;\n\n\n\n\n    auto cur_x = m_x;\n    for (double cur_t = t; cur_t <= 2; cur_t += step) {\n        cur_x = runge_kutta_step(cur_x, cur_t, step);\n    }\n\n    std::cout << \"Manual Runge-Kutta at point 2 is \" << cur_x << std::endl;\n    std::cout << \"The right solution is \" << correctColution << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "7404ba6feb452de0d38b61875bc9428b03cb569d", "size": 2957, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SCConsole/source/main.cpp", "max_stars_repo_name": "ghostbuster73/SmartControl", "max_stars_repo_head_hexsha": "05ef18287ba904124e1fc91b8e46d47c58f69491", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SCConsole/source/main.cpp", "max_issues_repo_name": "ghostbuster73/SmartControl", "max_issues_repo_head_hexsha": "05ef18287ba904124e1fc91b8e46d47c58f69491", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SCConsole/source/main.cpp", "max_forks_repo_name": "ghostbuster73/SmartControl", "max_forks_repo_head_hexsha": "05ef18287ba904124e1fc91b8e46d47c58f69491", "max_forks_repo_licenses": ["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.4326923077, "max_line_length": 86, "alphanum_fraction": 0.5928305715, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6328813037666641}}
{"text": "//  (C) Copyright Raffi Enficiaud 2014.\n//  Distributed under the Boost Software License, Version 1.0.\n//  (See accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n\n//  See http://www.boost.org/libs/test for the library home page.\n\n//[example_code\n#define BOOST_TEST_MODULE example67\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n#include <sstream>\n\nnamespace bdata = boost::unit_test::data;\n\n// Generates a Fibonacci sequence\nstd::vector<float> fibonacci() {\n  std::vector<float> ret(8);\n  ret[0] = 0;\n  ret[1] = 1;\n  \n  for(std::size_t s(2); s < ret.size(); s++)\n  {\n    ret[s] = ret[s-1] + ret[s-2];\n  }\n  return ret;\n}\n\nBOOST_DATA_TEST_CASE( \n  test1, \n  bdata::make(fibonacci()),\n  array_element)\n{\n  std::cout << \"test 1: \" \n    << array_element \n    << std::endl;\n  BOOST_TEST(array_element <= 13);\n}\n\n\n// Generates a map from a vector\nstd::map<std::string, float> vect_2_str(std::vector<float> v) \n{\n  std::map<std::string, float> out;\n  for(std::size_t s(0); s < v.size(); s++)\n  {\n    std::ostringstream o;\n    o << v[s];\n    out[o.str()] = v[s];\n  }\n  return out;\n}\n\ntypedef std::pair<const std::string, float> pair_map_t;\nBOOST_TEST_DONT_PRINT_LOG_VALUE( pair_map_t )\n\nBOOST_DATA_TEST_CASE( \n  test2, \n  bdata::make(vect_2_str(fibonacci())),\n  array_element)\n{\n  std::cout << \"test 2: \\\"\" \n    << array_element.first << \"\\\", \"\n    << array_element.second\n    << std::endl;\n  BOOST_TEST(array_element.second <= 13);\n}\n//]\n", "meta": {"hexsha": "ce5038f3b3436c208f3c723837b9d4085da2664a", "size": 1551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/boost_1_71_0/libs/test/doc/examples/dataset_example67.run.cpp", "max_stars_repo_name": "anonymouscode1/djxperf", "max_stars_repo_head_hexsha": "b6073a761753aa7a6247f2618977ca3a2633e78a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "thirdparty/boost_1_71_0/libs/test/doc/examples/dataset_example67.run.cpp", "max_issues_repo_name": "anonymouscode1/djxperf", "max_issues_repo_head_hexsha": "b6073a761753aa7a6247f2618977ca3a2633e78a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T01:39:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:18:40.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/test/doc/examples/dataset_example67.run.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 22.1571428571, "max_line_length": 65, "alphanum_fraction": 0.6511927789, "num_tokens": 467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.8031737987125612, "lm_q1q2_score": 0.6328456995279842}}
{"text": "//\n// Copyright (c) 2009, Markus Rickert\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n//   this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright notice,\n//   this list of conditions and the following disclaimer in the documentation\n//   and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n\n#include <fstream>\n#include <iostream>\n#include <Eigen/Eigenvalues>\n#include <rl/math/Matrix.h>\n#include <rl/math/Vector.h>\n\nint\nmain(int argc, char** argv)\n{\n\tif (argc < 2)\n\t{\n\t\tstd::cout << \"Usage: rlPcaDemo FILE\" << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n\tstd::ifstream data;\n\tdata.open(argv[1]);\n\t\n\tstd::size_t rows;\n\tdata >> rows;\n\tstd::size_t cols;\n\tdata >> cols;\n\t\n\trl::math::Matrix src(rows, cols);\n\t\n\tfor (std::size_t i = 0; i < rows; ++i)\n\t{\n\t\tfor (std::size_t j = 0; j < cols; ++j)\n\t\t{\n\t\t\tdata >> src(i, j);\n\t\t}\n\t}\n\t\n\tdata.close();\n\t\n\tstd::cout << \"src = \" << std::endl << src << std::endl;\n\t\n\trl::math::Vector mean(cols);\n\tmean.setZero();\n\t\n\tfor (std::size_t i = 0; i < rows; ++i)\n\t{\n\t\tmean += src.row(i);\n\t}\n\t\n\tmean /= static_cast<rl::math::Real>(rows);\n\t\n\tstd::cout << \"mean = \" << mean.transpose() << std::endl;\n\t\n\trl::math::Matrix covariance(cols, cols);\n\tcovariance.setZero();\n\t\n\tfor (std::size_t i = 0; i < rows; ++i)\n\t{\n\t\trl::math::Vector delta = src.row(i).transpose() - mean;\n\t\tcovariance += delta * delta.transpose();\n\t}\n\t\n\tcovariance /= static_cast<rl::math::Real>(rows) - 1;\n\t\n\tstd::cout << \"covariance = \" << std::endl << covariance << std::endl;\n\t\n\tEigen::EigenSolver<rl::math::Matrix> eigen(covariance);\n\t\n\tstd::cout << \"eigenvectors = \" << std::endl << eigen.eigenvectors() << std::endl;\n\tstd::cout << \"eigenvalues = \" << std::endl << eigen.eigenvalues() << std::endl;\n\t\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "cceab5013351527050ce45e9b59199b67187cd4b", "size": 2792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/rlPcaDemo/rlPcaDemo.cpp", "max_stars_repo_name": "Broekman/rl", "max_stars_repo_head_hexsha": "285a7adab0bca3aa4ce4382bf5385f5b0626f10e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 568.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T03:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:12:56.000Z", "max_issues_repo_path": "demos/rlPcaDemo/rlPcaDemo.cpp", "max_issues_repo_name": "jencureboy/rl", "max_issues_repo_head_hexsha": "658cdd8387397261ebf0f52d3bde74aae0379e24", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-03-23T13:16:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T05:58:06.000Z", "max_forks_repo_path": "demos/rlPcaDemo/rlPcaDemo.cpp", "max_forks_repo_name": "jencureboy/rl", "max_forks_repo_head_hexsha": "658cdd8387397261ebf0f52d3bde74aae0379e24", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 169.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T12:59:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:44:54.000Z", "avg_line_length": 29.0833333333, "max_line_length": 82, "alphanum_fraction": 0.6783667622, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6328293470399965}}
{"text": "// SPDX-License-Identifier: MIT\n// Copyright (c) 2019-2021 Thomas Vanderbruggen <th.vanderbruggen@gmail.com>\n\n#ifndef SCICPP_CORE_STATS\n#define SCICPP_CORE_STATS\n\n#include \"scicpp/core/functional.hpp\"\n#include \"scicpp/core/numeric.hpp\"\n#include \"scicpp/core/units/quantity.hpp\"\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <numeric>\n#include <tuple>\n\nnamespace scicpp::stats {\n\nnamespace detail {\n\ntemplate <class Array>\nauto quiet_nan() {\n    return std::numeric_limits<typename Array::value_type>::quiet_NaN();\n}\n\n} // namespace detail\n\n//---------------------------------------------------------------------------------\n// amax\n//---------------------------------------------------------------------------------\n\ntemplate <class Array>\nconstexpr auto amax(const Array &f) {\n    if (f.empty()) {\n        return detail::quiet_nan<Array>();\n    }\n\n    return *std::max_element(f.cbegin(), f.cend());\n}\n\n//---------------------------------------------------------------------------------\n// amin\n//---------------------------------------------------------------------------------\n\ntemplate <class Array>\nconstexpr auto amin(const Array &f) {\n    if (f.empty()) {\n        return detail::quiet_nan<Array>();\n    }\n\n    return *std::min_element(f.cbegin(), f.cend());\n}\n\n//---------------------------------------------------------------------------------\n// ptp\n//---------------------------------------------------------------------------------\n\ntemplate <class Array>\nconstexpr auto ptp(const Array &f) {\n    if (f.empty()) {\n        return detail::quiet_nan<Array>();\n    }\n\n    const auto [it_min, it_max] = std::minmax_element(f.cbegin(), f.cend());\n    return *it_max - *it_min;\n}\n\n//---------------------------------------------------------------------------------\n// average\n//---------------------------------------------------------------------------------\n\ntemplate <class Array1, class Array2>\nconstexpr auto average(const Array1 &f, const Array2 &weights) {\n    if (f.empty() || (f.size() != weights.size())) {\n        return detail::quiet_nan<Array1>();\n    }\n\n    return inner(f, weights) / sum(weights);\n}\n\n//---------------------------------------------------------------------------------\n// median\n//---------------------------------------------------------------------------------\n\nnamespace detail {\n\n// https://stackoverflow.com/questions/1719070/what-is-the-right-approach-when-using-stl-container-for-median-calculation\ntemplate <class InputIt>\nauto median_inplace(InputIt first, InputIt last) {\n    using T = typename std::iterator_traits<InputIt>::value_type;\n    using raw_t = units::representation_t<T>;\n    const auto size = std::distance(first, last);\n\n    if (size == 0) {\n        return std::numeric_limits<T>::quiet_NaN();\n    }\n\n    const signed_size_t half = size / 2;\n    const auto target = first + half;\n    std::nth_element(first, target, last);\n\n    if (size % 2 != 0) { // vector size is odd\n        return *target;\n    } else {\n        const auto max_it = std::max_element(first, first + half);\n        return (*max_it + *target) / raw_t{2}; // cf. std::midpoint (C++20)\n    }\n}\n\n} // namespace detail\n\ntemplate <class InputIt, class Predicate>\nauto median(InputIt first, InputIt last, Predicate p) {\n    auto v = filter(std::vector(first, last), p);\n    return detail::median_inplace(v.begin(), v.end());\n}\n\ntemplate <class Array, class Predicate>\nauto median(const Array &f, Predicate filter) {\n    return median(f.cbegin(), f.cend(), filter);\n}\n\ntemplate <class Array>\nauto median(Array &&f) {\n    if constexpr (std::is_lvalue_reference_v<Array>) {\n        auto tmp = f;\n        return detail::median_inplace(tmp.begin(), tmp.end());\n    } else {\n        return detail::median_inplace(f.begin(), f.end());\n    }\n}\n\ntemplate <class Array>\nauto nanmedian(const Array &f) {\n    return median(f, filters::not_nan);\n}\n\n//---------------------------------------------------------------------------------\n// mean\n//---------------------------------------------------------------------------------\n\ntemplate <class InputIt, class Predicate>\nconstexpr auto mean(InputIt first, InputIt last, Predicate filter) {\n    using T = typename std::iterator_traits<InputIt>::value_type;\n\n    if (std::distance(first, last) == 0) {\n        return std::numeric_limits<T>::quiet_NaN();\n    }\n\n    const auto [res, cnt] = sum(first, last, filter);\n    return res / units::representation_t<T>(cnt);\n}\n\ntemplate <class Array, class Predicate>\nconstexpr auto mean(const Array &f, Predicate filter) {\n    return mean(f.cbegin(), f.cend(), filter);\n}\n\ntemplate <class Array>\nconstexpr auto mean(const Array &f) {\n    return mean(f, filters::all);\n}\n\ntemplate <class Array>\nauto nanmean(const Array &f) {\n    return mean(f, filters::not_nan);\n}\n\ntemplate <class Array, typename T = typename Array::value_type>\nconstexpr auto tmean(const Array &f,\n                     const std::array<T, 2> &limits,\n                     const std::array<bool, 2> &inclusive = {true, true}) {\n    return mean(f, filters::Trim<T>(limits, inclusive));\n}\n\n//---------------------------------------------------------------------------------\n// gmean\n//---------------------------------------------------------------------------------\n\ntemplate <class Array>\nauto gmean(Array &&f) {\n    using T = typename std::decay_t<Array>::value_type;\n\n    if (f.empty()) {\n        return std::numeric_limits<T>::quiet_NaN();\n    }\n\n    if constexpr (units::is_quantity_v<T>) {\n        using namespace operators;\n        return T(std::exp(mean(log(std::forward<Array>(f) / T(1)))));\n    } else {\n        return std::exp(mean(log(std::forward<Array>(f))));\n    }\n}\n\ntemplate <class Array, class Predicate>\nauto gmean(Array &&f, Predicate p) {\n    return gmean(filter(std::forward<Array>(f), p));\n}\n\ntemplate <class Array>\nauto nangmean(Array &&f) {\n    return gmean(std::forward<Array>(f), filters::not_nan);\n}\n\n//---------------------------------------------------------------------------------\n// covariance\n//---------------------------------------------------------------------------------\n\ntemplate <int ddof = 0, class InputIt1, class InputIt2, class Predicate>\nconstexpr auto covariance(InputIt1 first1,\n                          InputIt1 last1,\n                          InputIt2 first2,\n                          InputIt2 last2,\n                          Predicate filter) {\n    using T1 = typename std::iterator_traits<InputIt1>::value_type;\n    using T2 = typename std::iterator_traits<InputIt2>::value_type;\n    using raw_t1 = units::representation_t<T1>;\n    using raw_t2 = units::representation_t<T2>;\n    using raw_t = std::common_type_t<raw_t1, raw_t2>;\n    using prod_t = decltype(std::declval<T1>() * std::declval<T2>());\n\n    static_assert(meta::is_predicate<Predicate, T1>);\n    static_assert(meta::is_predicate<Predicate, T2>);\n\n    scicpp_require(std::distance(first1, last1) ==\n                   std::distance(first2, last2));\n\n    if (std::distance(first1, last1) == 0) {\n        return std::make_tuple(std::numeric_limits<prod_t>::quiet_NaN(),\n                               signed_size_t(0));\n    }\n\n    // Pairwise recursive implementation of covariance summation\n    const auto [m1_, m2_, cov_, c_] = pairwise_accumulate<64>(\n        first1,\n        last1,\n        first2,\n        last2,\n        [&](auto f1, auto l1, auto f2, auto l2) {\n            const auto m1 = mean(f1, l1, filter);\n            const auto m2 = mean(f2, l2, filter);\n\n            auto res = utils::set_zero<prod_t>();\n            signed_size_t cnt = 0;\n\n            for (; f1 != l1; ++f1, ++f2) {\n                if (filter(*f1) && filter(*f2)) {\n                    if constexpr (meta::is_complex_v<T2>) {\n                        res += (*f1 - m1) * std::conj(*f2 - m2);\n                    } else {\n                        res += (*f1 - m1) * (*f2 - m2);\n                    }\n                    cnt++;\n                }\n            }\n\n            return std::make_tuple(m1, m2, res, cnt);\n        },\n        [&](const auto res1, const auto res2) {\n            // Combine covariances\n            // https://stackoverflow.com/questions/45773857/merging-covariance-from-two-sets-to-create-new-covariance\n            const auto [m11, m12, covar1, n1] = res1;\n            const auto [m21, m22, covar2, n2] = res2;\n\n            const auto n_c = n1 + n2;\n            const auto m1_c = (raw_t1{1} / raw_t1(n_c)) *\n                              (raw_t1(n1) * m11 + raw_t1(n2) * m21);\n            const auto m2_c = (raw_t2{1} / raw_t2(n_c)) *\n                              (raw_t2(n1) * m12 + raw_t2(n2) * m22);\n            const auto covar_c = covar1 + covar2 +\n                                 (raw_t(n1) * raw_t(n2) / raw_t(n_c)) *\n                                     conj(m12 - m22) * (m11 - m21);\n            return std::make_tuple(m1_c, m2_c, covar_c, n_c);\n        });\n\n    if (unlikely(c_ - ddof <= 0)) {\n        return std::make_tuple(std::numeric_limits<decltype(cov_)>::infinity(),\n                               c_);\n    } else {\n        return std::make_tuple(cov_ / raw_t(c_ - ddof), c_);\n    }\n}\n\ntemplate <int ddof = 0, class Array1, class Array2, class Predicate>\nconstexpr auto\ncovariance(const Array1 &f1, const Array2 &f2, Predicate filter) {\n    return std::get<0>(covariance<ddof>(\n        f1.cbegin(), f1.cend(), f2.cbegin(), f2.cend(), filter));\n}\n\ntemplate <int ddof = 0, class Array1, class Array2>\nconstexpr auto covariance(const Array1 &f1, const Array2 &f2) {\n    return covariance<ddof>(f1, f2, filters::all);\n}\n\ntemplate <int ddof = 0, class Array1, class Array2>\nauto nancovariance(const Array1 &f1, const Array2 &f2) {\n    return covariance<ddof>(f1, f2, filters::not_nan);\n}\n\n//---------------------------------------------------------------------------------\n// var\n//---------------------------------------------------------------------------------\n\ntemplate <int ddof = 0, class InputIt, class Predicate>\nconstexpr auto var(InputIt first, InputIt last, Predicate filter) {\n    const auto [v, n] = covariance<ddof>(first, last, first, last, filter);\n    using T = std::decay_t<decltype(v)>;\n\n    if constexpr (meta::is_complex_v<T>) {\n        // The variance is always a nonnegative real number\n        return std::make_tuple(std::real(v), n);\n    } else {\n        return std::make_tuple(v, n);\n    }\n}\n\ntemplate <int ddof = 0, class Array, class Predicate>\nconstexpr auto var(const Array &f, Predicate filter) {\n    return std::get<0>(var<ddof>(f.cbegin(), f.cend(), filter));\n}\n\ntemplate <int ddof = 0, class Array>\nconstexpr auto var(const Array &f) {\n    return var<ddof>(f, filters::all);\n}\n\ntemplate <int ddof = 0, class Array>\nauto nanvar(const Array &f) {\n    return var<ddof>(f, filters::not_nan);\n}\n\ntemplate <int ddof = 1, class Array, typename T = typename Array::value_type>\nconstexpr auto tvar(const Array &f,\n                    const std::array<T, 2> &limits,\n                    const std::array<bool, 2> &inclusive = {true, true}) {\n    return var<ddof>(f, filters::Trim<T>(limits, inclusive));\n}\n\n//---------------------------------------------------------------------------------\n// std\n//---------------------------------------------------------------------------------\n\ntemplate <int ddof = 0, class Array, class Predicate>\nauto std(const Array &a, Predicate filter) {\n    return units::sqrt(var<ddof>(a, filter));\n}\n\ntemplate <int ddof = 0, class Array>\nauto std(const Array &a) {\n    return units::sqrt(var<ddof>(a));\n}\n\ntemplate <int ddof = 0, class Array>\nauto nanstd(const Array &a) {\n    return units::sqrt(nanvar<ddof>(a));\n}\n\ntemplate <int ddof = 1, class Array, typename T = typename Array::value_type>\nauto tstd(const Array &a,\n          const std::array<T, 2> &limits,\n          const std::array<bool, 2> &inclusive = {true, true}) {\n    return units::sqrt(tvar<ddof>(a, limits, inclusive));\n}\n\n//---------------------------------------------------------------------------------\n// sem\n//---------------------------------------------------------------------------------\n\ntemplate <int ddof = 1, class Array, class Predicate>\nauto sem(const Array &a, Predicate filter) {\n    const auto [v, n] = var<ddof>(a.cbegin(), a.cend(), filter);\n    using T = std::decay_t<decltype(v)>;\n    using raw_t = units::representation_t<T>;\n    return units::sqrt(v / raw_t(n));\n}\n\ntemplate <int ddof = 1, class Array>\nauto sem(const Array &a) {\n    const auto v = var<ddof>(a);\n    using T = std::decay_t<decltype(v)>;\n    using raw_t = units::representation_t<T>;\n    return units::sqrt(v / raw_t(a.size()));\n}\n\ntemplate <int ddof = 1, class Array>\nauto nansem(const Array &a) {\n    return sem<ddof>(a, filters::not_nan);\n}\n\ntemplate <int ddof = 1, class Array, typename T = typename Array::value_type>\nconstexpr auto tsem(const Array &f,\n                    const std::array<T, 2> &limits,\n                    const std::array<bool, 2> &inclusive = {true, true}) {\n    return sem<ddof>(f, filters::Trim<T>(limits, inclusive));\n}\n\n//---------------------------------------------------------------------------------\n// moment\n//---------------------------------------------------------------------------------\n\ntemplate <intmax_t n, class Array, class Predicate>\nauto moment(const Array &f, [[maybe_unused]] Predicate filter) {\n    using namespace operators;\n    using T = typename Array::value_type;\n\n    if constexpr (n == 0) {\n        return T{1};\n    } else if constexpr (n == 1) {\n        return T{0};\n    } else if constexpr (n == 2) {\n        return var(f, filter);\n    } else {\n        // This allocates an extra array,\n        // but preserves pairwise recursion precision\n        return mean(pow<n>(f - mean(f, filter)), filter);\n        // Combination of moments\n        // http://prod.sandia.gov/techlib/access-control.cgi/2008/086212.pdf\n    }\n}\n\ntemplate <intmax_t n, class Array>\nauto moment(const Array &f) {\n    return moment<n>(f, filters::all);\n}\n\ntemplate <intmax_t n, class Array>\nauto nanmoment(const Array &f) {\n    return moment<n>(f, filters::not_nan);\n}\n\n//---------------------------------------------------------------------------------\n// kurtosis\n//---------------------------------------------------------------------------------\n\nenum KurtosisDef { Fisher = 0, Pearson = 1 };\n\ntemplate <KurtosisDef def = KurtosisDef::Fisher, class Array, class Predicate>\nauto kurtosis(const Array &f, Predicate filter) {\n    const auto m2 = moment<2>(f, filter);\n    const auto m4 = moment<4>(f, filter);\n    const auto k = m4 / (m2 * m2);\n\n    if constexpr (def == KurtosisDef::Fisher) {\n        using T = decltype(k);\n        return k - T(3);\n    } else {\n        return k;\n    }\n}\n\ntemplate <KurtosisDef def = KurtosisDef::Fisher, class Array>\nauto kurtosis(const Array &f) {\n    return kurtosis<def>(f, filters::all);\n}\n\ntemplate <KurtosisDef def = KurtosisDef::Fisher, class Array>\nauto nankurtosis(const Array &f) {\n    return kurtosis<def>(f, filters::not_nan);\n}\n\n//---------------------------------------------------------------------------------\n// skew\n//---------------------------------------------------------------------------------\n\ntemplate <class Array, class Predicate>\nauto skew(const Array &f, Predicate filter) {\n    const auto m2 = moment<2>(f, filter);\n    const auto m3 = moment<3>(f, filter);\n    return m3 / units::sqrt(m2 * m2 * m2);\n}\n\ntemplate <class Array>\nauto skew(const Array &f) {\n    return skew(f, filters::all);\n}\n\ntemplate <class Array>\nauto nanskew(const Array &f) {\n    return skew(f, filters::not_nan);\n}\n\n//---------------------------------------------------------------------------------\n// covariance matrix\n//---------------------------------------------------------------------------------\n\ntemplate <int ddof = 1, class Array1, class Array2, class Predicate>\nauto cov(const Array1 &f1, const Array2 &f2, Predicate filter) {\n    const auto covar = covariance<ddof>(f1, f2, filter);\n    using T = std::decay_t<decltype(covar)>;\n\n    Eigen::Matrix<T, 2, 2> res;\n    res(0, 0) = T(var<ddof>(f1, filter));\n    res(0, 1) = covar;\n    res(1, 0) = conj(covar);\n    res(1, 1) = T(var<ddof>(f2, filter));\n    return res;\n}\n\ntemplate <int ddof = 1, class Array1, class Array2>\nauto cov(const Array1 &f1, const Array2 &f2) {\n    return cov<ddof>(f1, f2, filters::all);\n}\n\ntemplate <int ddof = 1, class Array1, class Array2>\nauto nancov(const Array1 &f1, const Array2 &f2) {\n    return cov<ddof>(f1, f2, filters::not_nan);\n}\n\n} // namespace scicpp::stats\n\n#endif // SCICPP_CORE_STATS\n", "meta": {"hexsha": "0d3ec2b35cd1ae19fd1295346d66082da50be968", "size": 16502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "scicpp/core/stats.hpp", "max_stars_repo_name": "tvanderbruggen/SciCpp", "max_stars_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-02T09:03:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T11:58:05.000Z", "max_issues_repo_path": "scicpp/core/stats.hpp", "max_issues_repo_name": "tvanderbruggen/SciCpp", "max_issues_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scicpp/core/stats.hpp", "max_forks_repo_name": "tvanderbruggen/SciCpp", "max_forks_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0427184466, "max_line_length": 121, "alphanum_fraction": 0.5216337414, "num_tokens": 3912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6328293420588699}}
{"text": "#include <chrono>\n#include <random>\n#include <boost/program_options.hpp>\n#include \"myDist.hpp\"\n#include \"matGen_lapack.hpp\"\n\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[]){\n\n  po::options_description desc(\"Artificial Matrices MT: Options\");\n  desc.add_options()\n       (\"help,h\",\"show the help\")\n       (\"N\", po::value<std::size_t>()->default_value(10), \"number of row and column of matrices to be generated.\")\n       (\"dmax\", po::value<double>()->default_value(21), \"A scalar which scales the generated eigenvalues, this makes\"\n\t\t\t\t\t\t\t \" the maximum absolute eigenvalue is abs(dmax).\" )\n       (\"epsilon\", po::value<double>()->default_value(0.1), \"This value is epsilon.\" ) \n\n       (\"myDist\", po::value<std::size_t>()->default_value(0), \"Specifies my externel setup distribution for generating eigenvalues:\\n \"\n\t\t\t\t\t\t\t      \"0: Uniform eigenspectrum lambda_k = dmax * (epsilon + k * (1 - epsilon) / n for k = 0, ..., n-1)\\n \"\n                                                              \"1: Geometric eigenspectrum lambda_k =lambda_k = epsilon^[(n - k) / n] for k = 0, ..., n-1) \\n\"\n\t\t\t\t\t\t\t      \"2: 1-2-1 matrix\\n\"\n\t\t\t\t\t\t\t      \"3: Wilkinson matrix\\n\")\n       (\"mean\", po::value<double>()->default_value(0.5), \"Mean value of Normal distribution for the randomness.\" )\n       (\"stddev\", po::value<double>()->default_value(1.0), \"Standard deviation value of Normal distribution for the randomness.\" );\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << desc << std::endl;\n    return 1;\n  }\n  \n  //number of row and column of matrix to be generated\n  std::size_t n = vm[\"N\"].as<std::size_t>();\n  double dmax = vm[\"dmax\"].as<double>();\n  double eps = vm[\"epsilon\"].as<double>();\n  std::size_t myDist = vm[\"myDist\"].as<std::size_t>();\n  //for the randomness with normal distribution\n  double mean = vm[\"mean\"].as<double>();\n  double stddev = vm[\"stddev\"].as<double>();\n\n  //generating ...\n  std::cout << \"]> start generating ...\" << std::endl;\n\n  std::chrono::high_resolution_clock::time_point start, end;\n  std::chrono::duration<double> elapsed;\n  \n  start = std::chrono::high_resolution_clock::now();\n\n  double *A;\n  \n  //myDist = 0: Uniform eigenspectrum\n  //myDist = 1: Geometric eigenspectrum\n  //myDist = 2: 1-2-1 tridiagonal matrix\n  //myDist = 3: Wilkinson tridiagonal matrix\n  std::string mode;\n\n  if(myDist == 0){\n    mode= \"Uniform\";\n  }else if(myDist == 1){\n    mode = \"Geometric\";\n  }else if(myDist == 2){\n    mode = \"1-2-1\";\n  }else if(myDist == 3){\n    mode = \"Wilkinson\";\n  }else{\n    mode = \"myLambda\";\n  }\n\n  if(myDist == 0){\n      A = matGen_lapack<double>(n, mean, stddev, myUniformDist<double>, n, eps, dmax);\n  }else if(myDist == 1){\n      A = matGen_lapack<double>(n, mean, stddev, myGeometricDist<double>, n, eps, dmax);\n  }else if(myDist == 2){\n      A = matGen_121<double>(n);\n  }else if(myDist == 3){\n      A = matGen_WilkinsonPlus<double>(n); \n  }else{\n    A = matGen_lapack<double>(n, mean, stddev, [](std::size_t n, int x){\n                double *eigenv = new double[n];\n                for(auto k = 0; k < n; k++){\n                    eigenv[k] = k * (x + 1);\n                }\n                return eigenv;\n            }, n, 1);\n  }\n\n  end = std::chrono::high_resolution_clock::now();\n\n  elapsed = std::chrono::duration_cast<std::chrono::duration<double>>(end - start);\n  \n  std::cout << \"]> matrix generated in \" << elapsed.count() << \" seconds\" << std::endl;\n\n  std::ostringstream out_str;\n\n  if(myDist == 0 || myDist == 1){\n    out_str << std::scientific << \"matgen_m_\" << n << \"_\" << mode << \"_eps_\"<< eps\n            << \"_dmax_\" << dmax << \".bin\";\n  }else{\n    out_str << std::scientific << \"matgen_m_\" << n << \"_\"<< mode << \".bin\";\n  }\n\n  //save matrix into binary file\n  wrtMatIntoBinary<double>(A, out_str.str(), n * n);\n \n  delete [] A; \n  return 0;\n}\n\n", "meta": {"hexsha": "ed029eb1d9ebb40f3ff2f7a10d7ebb4659c38df8", "size": 3898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/driver_lapack.cpp", "max_stars_repo_name": "SMG2S/DEMAGIS", "max_stars_repo_head_hexsha": "9332fb687129d15024d49eb0a7027b552c1c91c7", "max_stars_repo_licenses": ["MIT"], "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/driver_lapack.cpp", "max_issues_repo_name": "SMG2S/DEMAGIS", "max_issues_repo_head_hexsha": "9332fb687129d15024d49eb0a7027b552c1c91c7", "max_issues_repo_licenses": ["MIT"], "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/driver_lapack.cpp", "max_forks_repo_name": "SMG2S/DEMAGIS", "max_forks_repo_head_hexsha": "9332fb687129d15024d49eb0a7027b552c1c91c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T18:31:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-09T18:33:05.000Z", "avg_line_length": 34.8035714286, "max_line_length": 157, "alphanum_fraction": 0.5890200103, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6326698750943812}}
{"text": "//  (C) Copyright 2006 Eric Niebler, Olivier Gygi.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Test case for kurtosis.hpp\r\n\r\n#include <boost/random.hpp>\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/accumulators/numeric/functional/vector.hpp>\r\n#include <boost/accumulators/numeric/functional/complex.hpp>\r\n#include <boost/accumulators/numeric/functional/valarray.hpp>\r\n#include <boost/accumulators/accumulators.hpp>\r\n#include <boost/accumulators/statistics/stats.hpp>\r\n#include <boost/accumulators/statistics/kurtosis.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace unit_test;\r\nusing namespace boost::accumulators;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// test_stat\r\n//\r\nvoid test_stat()\r\n{\r\n    // tolerance in %\r\n    // double epsilon = 1;\r\n\r\n    accumulator_set<double, stats<tag::kurtosis > > acc1;\r\n    accumulator_set<int, stats<tag::kurtosis > > acc2;\r\n\r\n    // two random number generators\r\n    boost::lagged_fibonacci607 rng;\r\n    boost::normal_distribution<> mean_sigma(0,1);\r\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal(rng, mean_sigma);\r\n\r\n    for (std::size_t i=0; i<100000; ++i)\r\n    {\r\n        acc1(normal());\r\n    }\r\n\r\n    // This check fails because epsilon is relative and not absolute\r\n    // BOOST_CHECK_CLOSE( kurtosis(acc1), 0., epsilon );\r\n\r\n    acc2(2);\r\n    acc2(7);\r\n    acc2(4);\r\n    acc2(9);\r\n    acc2(3);\r\n\r\n    BOOST_CHECK_EQUAL( mean(acc2), 5 );\r\n    BOOST_CHECK_EQUAL( accumulators::moment<2>(acc2), 159./5. );\r\n    BOOST_CHECK_EQUAL( accumulators::moment<3>(acc2), 1171./5. );\r\n    BOOST_CHECK_EQUAL( accumulators::moment<4>(acc2), 1863 );\r\n    BOOST_CHECK_CLOSE( kurtosis(acc2), -1.39965397924, 1e-6 );\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// init_unit_test_suite\r\n//\r\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\r\n{\r\n    test_suite *test = BOOST_TEST_SUITE(\"kurtosis test\");\r\n\r\n    test->add(BOOST_TEST_CASE(&test_stat));\r\n\r\n    return test;\r\n}\r\n\r\n", "meta": {"hexsha": "334068ac19ac640363acef900e11e0343d66975e", "size": 2262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/accumulators/test/kurtosis.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/accumulators/test/kurtosis.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/accumulators/test/kurtosis.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 31.8591549296, "max_line_length": 114, "alphanum_fraction": 0.6396993811, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.6326698629503407}}
{"text": "#include <iostream>\n#include <stdio.h>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/Core>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char * argv[])\n{\n  if (argc != 3 || strcmp(argv[1], \"-h\") == 0)\n  {\n    cout << \"Usage: ./eigDeterm N_MATRIX(<=1000) ITERATIONS(~1000)\"\n      << endl;\n    return 1;\n  }\n\n  srand(time(NULL));\n  int MAT_DIM = 6;\n  int N_MATRIX = atoi(argv[1]);\n  int ITERATIONS = atoi(argv[2]);\n  int i, j, k, count;\n  double start, end, t_time = 0.0;\n\n\n  printf(\"N_MATRIX: %d, ITERATIONS: %d\\n\", N_MATRIX, ITERATIONS);\n\n\n//  MatrixXd *m_list(6,6);\n\n  MatrixXd m = MatrixXd::Random(MAT_DIM, MAT_DIM);\n  \n  cout << \"Here is the matrix m:\" << endl << m << endl;\n  double determinant;\n  cout << \"Determinant is: \" << m.determinant() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "15766f426ecae43b5d4e5bfe86b252ca0e331132", "size": 804, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/matrix_library_tests/eigDeterm.cpp", "max_stars_repo_name": "tcrundall/chronostar", "max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-28T11:05:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T01:13:11.000Z", "max_issues_repo_path": "benchmarks/matrix_library_tests/eigDeterm.cpp", "max_issues_repo_name": "tcrundall/chronostar", "max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2019-08-14T07:30:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T23:44:29.000Z", "max_forks_repo_path": "benchmarks/matrix_library_tests/eigDeterm.cpp", "max_forks_repo_name": "tcrundall/chronostar", "max_forks_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-21T08:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T06:53:52.000Z", "avg_line_length": 20.1, "max_line_length": 67, "alphanum_fraction": 0.6106965174, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.6326492535447396}}
{"text": "#include <bits/stdc++.h>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\nusing mpi = boost::multiprecision::int128_t;\nusing namespace boost::numeric;\nusing imatrix = ublas::matrix<mpi>;\n\nusing namespace std;\ntypedef long long int ll;\ntypedef pair<int, int> P;\n//typedef pair<ll, ll> Pll;\ntypedef vector<int> Vi;\n//typedef tuple<int, int, int> T;\n#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)\n#define REP(i,x) FOR(i,0,x)\n#define ALL(c) c.begin(), c.end()\n#define DUMP( x ) cerr << #x << \" = \" << ( x ) << endl\n#define UNIQUE(c) sort(ALL(c)), c.erase(unique(ALL(c)), c.end())\n\nconst int dr[4] = {-1, 0, 1, 0};\nconst int dc[4] = {0, 1, 0, -1};\nconst ll mod = (int)1e9 + 7;\n\n\nvoid modulo(imatrix &mat, mpi mod) {\n  for (size_t i = 0; i < mat.size1(); i++) {\n    for (size_t j = 0; j < mat.size2(); j++) {\n      mat(i, j) %= mod;\n    }\n  }\n}\n\nint main() {\n  // use scanf in CodeForces!\n\n  cin.tie(0);\n  ios_base::sync_with_stdio(false);\n  int N; ll K; cin >> N >> K;\n  imatrix mat(N, N);\n  REP(i, N) REP(j, N) cin >> mat(i, j);\n\n  imatrix pow2 = mat, ans(N, N);\n  REP(i, N) REP(j, N) ans(i, j) = (ll)(i == j);\n  while (K) {\n    if (K & 1LL) {\n      ans = ublas::prod(ans, pow2);\n      modulo(ans, mod);\n    }\n    pow2 = ublas::prod(pow2, pow2);\n    modulo(pow2, mod);\n    K >>= 1;\n  }\n\n  mpi count = 0;\n  REP(i, N) REP(j, N) count = (count + ans(i, j)) % mod;\n  cout << count << endl;\n  return 0;\n}\n", "meta": {"hexsha": "778e5311a9daa2aa141939c88915cd2b8dffc483", "size": 1471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "atcoder/dp/dp_r.cpp", "max_stars_repo_name": "knuu/competitive-programming", "max_stars_repo_head_hexsha": "16bc68fdaedd6f96ae24310d697585ca8836ab6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-12T15:18:55.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-12T15:18:55.000Z", "max_issues_repo_path": "atcoder/dp/dp_r.cpp", "max_issues_repo_name": "knuu/competitive-programming", "max_issues_repo_head_hexsha": "16bc68fdaedd6f96ae24310d697585ca8836ab6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "atcoder/dp/dp_r.cpp", "max_forks_repo_name": "knuu/competitive-programming", "max_forks_repo_head_hexsha": "16bc68fdaedd6f96ae24310d697585ca8836ab6e", "max_forks_repo_licenses": ["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.5166666667, "max_line_length": 64, "alphanum_fraction": 0.5710401088, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6326492367188731}}
{"text": "/**\n * @file\n * @brief Implementations from make_quad_rule.h\n * @author Raffael Casagrande\n * @date   2018-08-19 06:35:16\n * @copyright MIT License\n */\n\n#include \"make_quad_rule.h\"\n#include <Eigen/KroneckerProduct>\n#include \"gauss_quadrature.h\"\n\nnamespace lf::quad {\nnamespace detail {\ntemplate <base::RefElType REF_EL, int Order>\nQuadRule HardcodedQuadRule();\n}\n\nQuadRule make_QuadRule(base::RefEl ref_el, unsigned char order) {\n  if (ref_el == base::RefEl::kSegment()) {\n    quadOrder_t n = order / 2 + 1;\n    auto [points, weights] = GaussLegendre(n);\n    return QuadRule(base::RefEl::kSegment(), points.transpose(),\n                    std::move(weights), 2 * n - 1);\n  }\n  if (ref_el == base::RefEl::kQuad()) {\n    quadOrder_t n = order / 2 + 1;\n    auto [points1d, weights1d] = GaussLegendre(n);\n    Eigen::MatrixXd points2d(2, n * n);\n    points2d.row(0) = Eigen::kroneckerProduct(points1d.transpose(),\n                                              Eigen::MatrixXd::Ones(1, n));\n    points2d.row(1) = points1d.transpose().replicate(1, n);\n    return QuadRule(base::RefEl::kQuad(), std::move(points2d),\n                    Eigen::kroneckerProduct(weights1d, weights1d), 2 * n - 1);\n  }\n  if (ref_el == base::RefEl::kTria()) {\n    switch (order) {\n      case 1:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 1>();\n      case 2:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 2>();\n      case 3:  // user order 4 rule instead\n      case 4:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 4>();\n      case 5:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 5>();\n      case 6:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 6>();\n      case 7:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 7>();\n      case 8:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 8>();\n      case 9:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 9>();\n      case 10:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 10>();\n      case 11:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 11>();\n      case 12:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 12>();\n      case 13:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 13>();\n      case 14:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 14>();\n      case 15:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 15>();\n      case 16:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 16>();\n      case 17:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 17>();\n      case 18:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 18>();\n      case 19:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 19>();\n      case 20:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 20>();\n      case 21:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 21>();\n      case 22:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 22>();\n      case 23:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 23>();\n      case 24:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 24>();\n      case 25:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 25>();\n      case 26:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 26>();\n      case 27:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 27>();\n      case 28:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 28>();\n      case 29:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 29>();\n      case 30:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 30>();\n      case 31:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 31>();\n      case 32:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 32>();\n      case 33:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 33>();\n      case 34:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 34>();\n      case 35:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 35>();\n      case 36:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 36>();\n      case 37:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 37>();\n      case 38:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 38>();\n      case 39:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 39>();\n      case 40:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 40>();\n      case 41:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 41>();\n      case 42:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 42>();\n      case 43:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 43>();\n      case 44:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 44>();\n      case 45:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 45>();\n      case 46:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 46>();\n      case 47:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 47>();\n      case 48:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 48>();\n      case 49:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 49>();\n      case 50:\n        return detail::HardcodedQuadRule<base::RefEl::kTria(), 50>();\n      default:\n        // Create a quadrule using tensor product quadrature rule + duffy\n        // transform\n        quadOrder_t n = order / 2 + 1;\n        auto [leg_p, leg_w] = GaussLegendre(n);\n        auto [jac_p, jac_w] = GaussJacobi(n, 1, 0);\n        jac_p.array() = (jac_p.array() + 1) / 2.;  // rescale to [0,1]\n        jac_w.array() *= 0.25;\n        Eigen::MatrixXd points2d(2, n * n);\n        points2d.row(0) = Eigen::kroneckerProduct(\n            leg_p.transpose(), (1 - jac_p.transpose().array()).matrix());\n        points2d.row(1) = jac_p.transpose().replicate(1, n);\n        return QuadRule(base::RefEl::kTria(), std::move(points2d),\n                        Eigen::kroneckerProduct(leg_w, jac_w), 2 * n - 1);\n    }\n  }\n  LF_VERIFY_MSG(\n      false, \"No Quadrature rules implemented for this reference element yet.\");\n}\n}  // namespace lf::quad\n", "meta": {"hexsha": "a5b991609864ac81d99e6c29924d0c122616b589", "size": 6304, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/lf/quad/make_quad_rule.cc", "max_stars_repo_name": "Cryoris/lehrfempp", "max_stars_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/lf/quad/make_quad_rule.cc", "max_issues_repo_name": "Cryoris/lehrfempp", "max_issues_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/lf/quad/make_quad_rule.cc", "max_forks_repo_name": "Cryoris/lehrfempp", "max_forks_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.152866242, "max_line_length": 80, "alphanum_fraction": 0.5997779188, "num_tokens": 1917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6325808769175707}}
{"text": "#define BOOST_TEST_MODULE example\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n#include <iostream>\n\nBOOST_DATA_TEST_CASE(\n    test1,\n    boost::unit_test::data::random(1, 17) ^ boost::unit_test::data::xrange(7),\n    random_sample,\n    index)\n{\n    std::cout << \"test 1: \" << random_sample << \", \" << index << std::endl;\n    BOOST_TEST((random_sample <= 17 && random_sample >= 1));\n}\n\nBOOST_DATA_TEST_CASE(\n    test,\n    boost::unit_test::data::random(\n        (boost::unit_test::data::distribution = \n            std::uniform_real_distribution<float>{ 1, 2 }))\n    ^  \n    boost::unit_test::data::xrange(7),\n    random_sample,\n    index)\n{\n    std::cout << \"test 2: \" << random_sample << \", \" << index << std::endl;\n    BOOST_TEST(random_sample < 2.0);\n}\n        \n", "meta": {"hexsha": "e7694bd4c066bae4160b62ff37b983748b24b7c2", "size": 848, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/13-test_with_a_random_sequence/main.cpp", "max_stars_repo_name": "ordinary-developer/education", "max_stars_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/13-test_with_a_random_sequence/main.cpp", "max_issues_repo_name": "ordinary-developer/education", "max_issues_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "books/tech/cpp/boost/official_doc/11-correctness_and_testing/04-test/13-test_with_a_random_sequence/main.cpp", "max_forks_repo_name": "ordinary-developer/education", "max_forks_repo_head_hexsha": "1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3548387097, "max_line_length": 78, "alphanum_fraction": 0.6320754717, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6325294956156372}}
{"text": "//  (C) Copyright Nick Thompson 2020.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#include <iostream>\n#include <boost/math/tools/ulps_plot.hpp>\n#include <boost/core/demangle.hpp>\n#include <boost/math/tools/agm.hpp>\n#include <boost/multiprecision/float128.hpp>\n\nusing boost::math::tools::ulps_plot;\nusing boost::math::tools::agm;\n\nint main() {\n    using PreciseReal = boost::multiprecision::float128;\n    using CoarseReal = float;\n\n    auto agm_coarse = [](CoarseReal x) {\n        return agm<CoarseReal>(x, CoarseReal(1));\n    };\n    auto agm_precise = [](PreciseReal x) {\n        return agm<PreciseReal>(x, PreciseReal(1));\n    };\n\n    std::string filename = \"agm_\" + boost::core::demangle(typeid(CoarseReal).name()) + \".svg\";\n    int samples = 2500;\n    int width = 1100;\n    PreciseReal clip = 100;\n    auto plot = ulps_plot<decltype(agm_precise), PreciseReal, CoarseReal>(agm_precise, CoarseReal(0), CoarseReal(10000), samples);\n    plot.clip(clip).width(width);\n    std::string title = \"AGM ULP plot at \" + boost::core::demangle(typeid(CoarseReal).name()) + \" precision\";\n    //plot.title(title);\n    plot.vertical_lines(10);\n    plot.add_fn(agm_coarse);\n    plot.write(filename);\n}\n", "meta": {"hexsha": "ca28feabad3f8ba6c11daa04fc06d2dc93fa08bc", "size": 1334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reporting/accuracy/test_agm.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "reporting/accuracy/test_agm.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/reporting/accuracy/test_agm.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 36.0540540541, "max_line_length": 130, "alphanum_fraction": 0.6866566717, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.632529493074997}}
{"text": "/*\n * Copyright 2018-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n#include <Eigen/Core>\n#include <eigen-osqp/CSCMatrix.h>\n#include <eigen-osqp/OSQP.h>\n#include <iostream>\n\nint main()\n{\n    int nrVar = 6;\n    int nrConstr = 5;\n    auto inf = std::numeric_limits<double>::infinity();\n\n    Eigen::MatrixXd Q = Eigen::MatrixXd::Identity(nrVar, nrVar);\n    Eigen::MatrixXd A(nrConstr, nrVar);\n    A << 1., -1., 1., 0., 3., 1.,\n        -1., 0., -3., -4., 5., 6.,\n        2., 5., 3., 0., 1., 0.,\n        0., 1., 0., 1., 2., -1.,\n        -1., 0., 2., 1., 1., 0.;\n\n    Eigen::VectorXd c(nrVar);\n    Eigen::VectorXd AL(nrConstr);\n    Eigen::VectorXd AU(nrConstr);\n    Eigen::VectorXd XL(nrVar);\n    Eigen::VectorXd XU(nrVar);\n    c << 1., 2., 3., 4., 5., 6.;\n    AL << 1., 2., 3., -inf, -inf;\n    AU << 1., 2., 3., -1., 2.5;\n    XL << -1000., -10000., 0., -1000., -1000., -1000.;\n    XU << 10000., 100., 1.5, 100., 100., 1000.;\n\n    Eigen::OSQP qp;\n\n    qp.problem(nrVar, nrConstr);\n    bool success = qp.solve(Q, c, A, AL, AU, XL, XU);\n\n    Eigen::VectorXd result = qp.result();\n\n    std::cout << \"Problem:\"\n              << \"\\n\\tminimize 0.5*x'*Q*x + c'*x\"\n              << \"\\n\\twith     AL <= A <= AU\"\n              << \"\\n\\t         XL <= x <= XU\"\n              << \"\\n\\nQ:\\n\"\n              << Q\n              << \"\\nc:\\n\"\n              << c.transpose()\n              << \"\\nA:\\n\"\n              << A\n              << \"\\nAL:\\n\"\n              << AL.transpose()\n              << \"\\nAU:\\n\"\n              << AU.transpose()\n              << \"\\nXL:\\n\"\n              << XL.transpose()\n              << \"\\nXU:\\n\"\n              << XU.transpose()\n              << \"\\n\\n\\nSolution:\\n\"\n              << result.transpose() << std::endl;\n\n    std::cout << \"Press enter to quit\" << std::endl;\n    std::cin.get();\n}\n", "meta": {"hexsha": "bfc8a17dc1a9314ababe9c92f39637209880870a", "size": 1783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dense_matrix_qp.cpp", "max_stars_repo_name": "jrl-umi3218/eigen-osqp", "max_stars_repo_head_hexsha": "6b21a48e4c15f977bd9a5bc0b2863653f0a9cd10", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-19T02:46:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T15:21:29.000Z", "max_issues_repo_path": "examples/dense_matrix_qp.cpp", "max_issues_repo_name": "jrl-umi3218/eigen-osqp", "max_issues_repo_head_hexsha": "6b21a48e4c15f977bd9a5bc0b2863653f0a9cd10", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-04-24T12:04:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T00:24:17.000Z", "max_forks_repo_path": "examples/dense_matrix_qp.cpp", "max_forks_repo_name": "jrl-umi3218/eigen-osqp", "max_forks_repo_head_hexsha": "6b21a48e4c15f977bd9a5bc0b2863653f0a9cd10", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-19T02:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-07T04:15:32.000Z", "avg_line_length": 27.0151515152, "max_line_length": 64, "alphanum_fraction": 0.4240044868, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.6325294930634898}}
{"text": "// Copyright (c) 2021 FRC Team 3512. All Rights Reserved.\n\n#pragma once\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <drake/math/discrete_algebraic_riccati_equation.h>\n\nnamespace frc3512 {\n\n/**\n * Returns solution to the DARE.\n *\n * @param A System matrix.\n * @param B Input matrix.\n * @param Q State cost matrix.\n * @param R Input cost matrix.\n * @param N State-input cross-term cost matrix.\n */\ntemplate <int States, int Inputs>\nEigen::Matrix<double, States, States> DARE(\n    const Eigen::Matrix<double, States, States>& A,\n    const Eigen::Matrix<double, States, Inputs>& B,\n    const Eigen::Matrix<double, States, States>& Q,\n    const Eigen::Matrix<double, Inputs, Inputs>& R,\n    const Eigen::Matrix<double, States, Inputs>& N) {\n    Eigen::Matrix<double, States, States> scrA =\n        A - B * R.llt().solve(N.transpose());\n    Eigen::Matrix<double, States, States> scrQ =\n        Q - N * R.llt().solve(N.transpose());\n\n    return drake::math::DiscreteAlgebraicRiccatiEquation(scrA, B, scrQ, R);\n}\n\n}  // namespace frc3512\n", "meta": {"hexsha": "70dd0bc8002ecc840d7b84e38977a740f41320d7", "size": 1044, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/controllers/DARE.hpp", "max_stars_repo_name": "frc3512/Robot-2020", "max_stars_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T04:13:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T00:13:39.000Z", "max_issues_repo_path": "src/main/include/controllers/DARE.hpp", "max_issues_repo_name": "frc3512/Robot-2020", "max_issues_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2020-02-12T03:05:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T02:14:38.000Z", "max_forks_repo_path": "src/main/include/controllers/DARE.hpp", "max_forks_repo_name": "frc3512/Robot-2020", "max_forks_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T16:24:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:10:01.000Z", "avg_line_length": 29.0, "max_line_length": 75, "alphanum_fraction": 0.6772030651, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897459384731, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.6325227622805029}}
{"text": "#include <Eigen/Dense>\n#include <tuple>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include \"NARMAL2Network.h\"\n#include \"util.h\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::ArrayXd;\nusing narmal2::NARMAL2Network;\nusing narmal2::writeCSV;\n\n/**\n * Generate data for the example system\n * @param n number of samples to be produced\n * @return X and y\n */\nstd::tuple<MatrixXd, VectorXd> generateData(const VectorXd& u)\n{\n\tint n = u.size();\n\tdouble y0 = 0.3, y_1 = 0, u_1 = 0; // intial values\n\tMatrixXd X{ n, 3 };\n\tVectorXd y{ n + 1 };\n\t// compute y(1) manually: [y(k), y(k-1), u(k-1)] -> y(k+1)\n\ty(0) = y0;\n\tX.row(0) << y0, y_1, u_1;\n\ty(1) = 1.5 * y0 * y_1 / (1 + y0 * y_1 + y_1*y_1)\n\t\t+ std::sin(y0 + y_1) + 0.8 * u_1 + u(0) * std::cos(y0 - u_1);\n\n\tfor (int k = 1; k < n; k++)\n\t{\n\t\tX.row(k) << y(k), y(k - 1), u(k - 1);\n\t\ty(k + 1) = 1.5 * y(k) * y(k - 1) / (1 + y(k) * y(k) + y(k - 1)*y(k - 1))\n\t\t\t+ std::sin(y(k) + y(k - 1)) + 0.8 * u(k - 1) + std::cos(y(k) - u(k-1)) * u(k);\n\t}\n\treturn { X, y.bottomRows(n) };\n}\n\n/**\n * Generate the training or test dataset.\n * @param which \"train\" or \"test\"\n * @return X, u, and y\n */\nstd::tuple<MatrixXd, VectorXd, VectorXd> generateDataSet(const std::string& which)\n{\n\tassert(which == \"train\" || which == \"test\");\n\tif (which == \"train\")\n\t{\n\t\t// generate data for training set\n\t\tArrayXd k;\n\t\tint n = 5000;\n\t\tMatrixXd X;\n\t\tVectorXd y;\n\t\tk.setLinSpaced(n, 1, n);\n\t\tEigen::VectorXd u = (1 * 3.14 / 3 * k).sin() + (2 * 3.14 / 24 * k).sin()\n\t\t\t+ ArrayXd::Random(n) * 0.2;\n\t\tstd::tie(X, y) = generateData(u);\n\t\treturn { X, u, y };\n\t}\n\telse\n\t{\n\t\t// generate data for test set\n\t\tint ntest = 200;\n\t\tArrayXd k;\n\t\tk.setLinSpaced(ntest, 1, ntest); // [1, 2, ..., ntest]\n\t\tVectorXd utest = (1 * 3.14 / 5 * k).cos() + (2 * 3.14 / 25 * k).sin() \n\t\t\t+ ArrayXd::Random(ntest) * 0.1;\n\t\tMatrixXd Xtest;\n\t\tVectorXd ytest;\n\t\tstd::tie(Xtest, ytest) = generateData(utest);\n\t\treturn { Xtest, utest, ytest };\n\t}\n}\n\n\nint main()\n{\n\t// get training set\n\tMatrixXd X;\n\tVectorXd u, y;\n\tstd::tie(X, u, y) = generateDataSet(\"train\");\n\n\t// train a network: 3 inputs, \n\t// the upper subnet has 30 hidden neurons and the lower 20 hidden neurons.\n\tNARMAL2Network net{ 3, {40}, {30}, \"ReLU\" };\n\tint batchSize = 500;\n\tint nIterations = 3000;\n\tauto stats = net.trainBatch(X, u, y, 1e-5, batchSize, nIterations, \"momentum\", \n\t\t{ {\"learningRate\", 1e-2}, {\"gamma\", 0.9}, {\"decayRate\", 0.98} });\n\tauto yp = net.predict(X, y);\n\n\t// get the test set and make predictions\n\tMatrixXd Xtest;\n\tVectorXd utest, ytest;\n\tstd::tie(Xtest, utest, ytest) = generateDataSet(\"test\");\n\tauto ytestp = net.predict(Xtest, utest);\n\t\n\t// write results CSV files for further analysis using for example MATLAB\n\twriteCSV(\"trainingLoss.csv\", stats.trainLossHistory);\n\tEigen::MatrixXd testResults{ytest.rows(), 2 };\n\ttestResults.col(0) = ytest;\n\ttestResults.col(1) = ytestp;\n\twriteCSV(\"testResults.csv\", testResults);\n\tEigen::MatrixXd trainingResults{ yp.rows(), 2 };\n\ttrainingResults.col(0) = y;\n\ttrainingResults.col(1) = yp;\n\twriteCSV(\"trainingResults.csv\", trainingResults);\n\n\tstd::getchar();\n}", "meta": {"hexsha": "7501d8cd80b32429457cec2342cc38568d6f526c", "size": 3091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NARMA-L2/core/main.cpp", "max_stars_repo_name": "ShuhuaGao/NARMA-L2", "max_stars_repo_head_hexsha": "9b2fdab87ca7b4f81b99fe74e9937a13f7a3e75f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T06:57:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T09:28:32.000Z", "max_issues_repo_path": "NARMA-L2/core/main.cpp", "max_issues_repo_name": "ShuhuaGao/NARMA-L2", "max_issues_repo_head_hexsha": "9b2fdab87ca7b4f81b99fe74e9937a13f7a3e75f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NARMA-L2/core/main.cpp", "max_forks_repo_name": "ShuhuaGao/NARMA-L2", "max_forks_repo_head_hexsha": "9b2fdab87ca7b4f81b99fe74e9937a13f7a3e75f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T15:03:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:28:35.000Z", "avg_line_length": 27.5982142857, "max_line_length": 82, "alphanum_fraction": 0.612423164, "num_tokens": 1126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346598, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6324845751811344}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include \"toplevelfixture.hpp\"\n#include <boost/test/unit_test.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yield/discountcurve.hpp>\n#include <ql/termstructures/yield/zerocurve.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <qle/termstructures/interpolateddiscountcurve2.hpp>\n#include <qle/termstructures/interpolateddiscountcurvelinearzero.hpp>\n\nusing namespace boost::unit_test_framework;\nusing namespace QuantLib;\nusing std::vector;\n\nBOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)\n\nBOOST_AUTO_TEST_SUITE(DiscountCurveTest)\n\nBOOST_AUTO_TEST_CASE(testDiscountCurve) {\n\n    // FIXME: test curve1 or 2 or both\n    BOOST_TEST_MESSAGE(\"Testing QuantExt::InteroplatedDiscountCurve2...\");\n\n    SavedSettings backup;\n    Settings::instance().evaluationDate() = Date(1, Dec, 2015);\n    Date today = Settings::instance().evaluationDate();\n\n    vector<Date> dates;\n    vector<Real> times;\n    vector<DiscountFactor> dfs;\n    vector<Rate> zeros;\n    vector<Handle<Quote> > quotes;\n\n    Size numYears = 30;\n    int startYear = 2015;\n    DayCounter dc = ActualActual();\n    Calendar cal = NullCalendar();\n\n    for (Size i = 0; i < numYears; i++) {\n\n        // rate\n        Real rate = 0.01 + i * 0.001;\n        // 1 year apart\n        dates.push_back(Date(1, Dec, startYear + i));\n        Time t = dc.yearFraction(today, dates.back());\n        times.push_back(t);\n\n        // set up Quote of DiscountFactors\n        DiscountFactor df = ::exp(-rate * t);\n        Handle<Quote> q(boost::make_shared<SimpleQuote>(df));\n        quotes.push_back(q);\n        dfs.push_back(df);\n        zeros.push_back(rate);\n    }\n\n    // Test against the QL curve\n    boost::shared_ptr<YieldTermStructure> ytsBase;\n    ytsBase =\n        boost::shared_ptr<YieldTermStructure>(new QuantLib::InterpolatedDiscountCurve<LogLinear>(dates, dfs, dc, cal));\n    ytsBase->enableExtrapolation();\n\n    boost::shared_ptr<YieldTermStructure> ytsTest(new QuantExt::InterpolatedDiscountCurve2(times, quotes, dc));\n\n    // now check that they give the same discount factors (including extrapolation)\n    for (Time t = 0.1; t < numYears + 10.0; t += 0.1) {\n        BOOST_CHECK_CLOSE(ytsBase->discount(t), ytsTest->discount(t), 1e-12);\n    }\n\n\n\tBOOST_TEST_MESSAGE(\"Testing QuantExt::InterpolatedDiscountCurveLinearZero...\");\n\t// Test linear interpolation in the zero rate against the QL curve\n\t// flat in the zero rate between t=0 and the first point\n    zeros.at(0) = zeros.at(1);\n    ytsBase = boost::make_shared<InterpolatedZeroCurve<Linear> >(dates, zeros, dc, cal);\n    ytsBase->enableExtrapolation();\n\n\tytsTest = boost::make_shared<QuantExt::InterpolatedDiscountCurveLinearZero>(times, quotes, dc);\n    \n    // now check that they give the same discount factors (including extrapolation)\n    for (Time t = 0.1; t < numYears + 10.0; t += 0.1) {        \n        BOOST_CHECK_CLOSE(ytsBase->discount(t), ytsTest->discount(t), 1e-12);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c0d37b0f2e5fa9ff152135368871b93a1d28f7d4", "size": 3810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/test/discountcurve.cpp", "max_stars_repo_name": "stevenvanharen/Engine", "max_stars_repo_head_hexsha": "d23a0ec07d31e587916672a5d56e41299acaf388", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantExt/test/discountcurve.cpp", "max_issues_repo_name": "stevenvanharen/Engine", "max_issues_repo_head_hexsha": "d23a0ec07d31e587916672a5d56e41299acaf388", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/test/discountcurve.cpp", "max_forks_repo_name": "stevenvanharen/Engine", "max_forks_repo_head_hexsha": "d23a0ec07d31e587916672a5d56e41299acaf388", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9433962264, "max_line_length": 119, "alphanum_fraction": 0.7186351706, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6324845624535254}}
{"text": "#include \"power.h\"\n#include <stopwatch.h>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <iostream>\n#include <cmath>\n\nusing namespace boost::multiprecision;\nusing uint2048_t = number<cpp_int_backend<2048, 2048, unsigned_magnitude, unchecked, void>>;\n\nauto mul = [](auto a, auto b) { return a * b; };\n\ntemplate<typename I>\nI power_1(I a, I b)\n{\n    I r = 1;\n    for (I i = 0; i < b; ++i) {\n        r *= a;\n    }\n    return r;\n}\n\ntemplate<typename I>\nI power_2(I a, I b)\n{\n    return power(a, b, mul);\n}\n\nint main(int, char**)\n{\n    stop_watch_t t;\n\n    t.start();\n    uint64_t a = 12;\n    uint64_t b = 27;\n    auto r = std::pow(a, b);\n    auto elapsed = t.stop();\n    std::cout << \"std::pow = \" << static_cast<uint2048_t>(r) << \" : \" << elapsed << \" \" << t.period() << \"\\n\";\n\n    uint2048_t x = 12;\n    uint2048_t y = 27;\n    t.start();\n    auto ra = power_1(x, y); // 429981696\n    elapsed = t.stop();\n    std::cout << \"power_1  = \" << ra << \" : \" << elapsed << \" \" << t.period() << \"\\n\";\n\n    t.start();\n    ra = power_2(x, y);\n    elapsed = t.stop();\n    std::cout << \"power_2  = \" << ra << \" : \" << elapsed << \" \" << t.period() << \"\\n\";\n    return 0;\n}\n", "meta": {"hexsha": "ac73ad5b35841da2ff1e6ca58c0da42f70ade1dc", "size": 1162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lesson_03/power_compare.cpp", "max_stars_repo_name": "andreyc2018/otus_algorithms", "max_stars_repo_head_hexsha": "d7fc3e683c6c47caed787176a2c1580701bf2044", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lesson_03/power_compare.cpp", "max_issues_repo_name": "andreyc2018/otus_algorithms", "max_issues_repo_head_hexsha": "d7fc3e683c6c47caed787176a2c1580701bf2044", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lesson_03/power_compare.cpp", "max_forks_repo_name": "andreyc2018/otus_algorithms", "max_forks_repo_head_hexsha": "d7fc3e683c6c47caed787176a2c1580701bf2044", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.3461538462, "max_line_length": 110, "alphanum_fraction": 0.5344234079, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6324845575084236}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace std;\nint main(int, char**)\n{\n    typedef double value_type;\n    typedef int    size_type;\n    const int nb_elements= 6, nb_nodes= 12;\n    \n    value_type array[][4]= {{2, 3,   4,   5}, \n\t\t\t    {4, 10, 13,  16},\n\t\t\t    {6, 25, 38,  46},\n\t\t\t    {8, 32, 77, 100}};\n    mtl::dense2D<value_type>   E_mat(array);\n    \n    std::cout<<\"E_mat=\\n\"<< E_mat <<\"\\n\";\n\n    mtl::mat::element_structure<value_type> A;\n    \n    typedef mtl::mat::element<value_type>\telement_type;\n    element_type* elements = new element_type[nb_elements];\n    \n    mtl::dense_vector<size_type>  index_a(4, 0), \n\t\t\t\t   index_b(4, 0), \n\t\t\t\t   index_c(4, 0), \n\t\t\t\t   index_d(4, 0), \n\t\t\t\t   index_e(4, 0), \n\t\t\t\t   index_f(4, 0);\n\t\n    // construct nodes for every element\n    index_a[0]= 0; index_a[1]= 1; index_a[2]= 4; index_a[3]= 5;\n    index_b= index_a + 1;\n    index_c= index_a + 2;\n    index_d= index_a + 4;\n    index_e= index_a + 5;\n    index_f= index_a + 6;\n   \n    //construct the 6 elements from the example grid\n    element_type a(0, index_a, E_mat);\n    element_type b(1, index_b, E_mat);\n    element_type c(2, index_c, E_mat);\n    element_type d(3, index_d, E_mat);\n    element_type e(4, index_e, E_mat);\n    element_type f(5, index_f, E_mat);\n    \n    //construct neighborhood information for each element\n    a.add_neighbors(&b, &d, &e);\n    b.add_neighbors(&a, &c, &d, &e, &f);\n    c.add_neighbors(&a, &b, &e);\n    d.add_neighbors(&a, &b, &e);\n    e.add_neighbors(&a, &b, &c, &d, &f);\n    f.add_neighbors(&b, &c, &e);\n\n    std::cout<< \"a=\" << a << \"\\n\";\n    \n    //construct array of elements\n    elements[0]=a;\n    elements[1]=b;\n    elements[2]=c;\n    elements[3]=d;\n    elements[4]=e;\n    elements[5]=f;\n    \n    //construct element_structure from the 6 single elements\n    A.consume(nb_elements, nb_nodes, elements);\n    mtl::dense_vector<value_type> x(nb_nodes, 1.0), test(A * x);\n    \n    std::cout<< \"test=\"<< test << \"\\n\";\n    \n    return 0;\n}\n", "meta": {"hexsha": "c36e5778273d626c6b749fae01f70bc21c1b965d", "size": 2005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/element_structure_example.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/element_structure_example.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/element_structure_example.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 27.4657534247, "max_line_length": 64, "alphanum_fraction": 0.5815461347, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6324720379569465}}
{"text": "#ifndef JOINT_HPP\n#define JOINT_HPP\n#include <armadillo>\n#include \"Math.hpp\"\n#include \"Body.hpp\"\n\nclass Joint\n{\npublic:\n    Joint(unsigned int TypeIn, arma::vec piIn, arma::vec pjIn, arma::vec qiIn,\n            arma::vec qjIn, Body *i_In, Body *j_In);\n    ~Joint() {};\n    void Build_C();\n    void Build_Cq();\n    void Build_GAMMA();\n    void update();\n\n    arma::mat get_Cq();\n    arma::vec get_GAMMA();\n\nprivate:\n    unsigned int Type;  \n    arma::vec pi;\n    arma::vec pj;\n    arma::vec qi;\n    arma::vec qj;\n    arma::mat Cq;\n    arma::vec GAMMA;\n    arma::vec CONSTRAINT;\n    arma::mat TBI_i;\n    arma::mat TBI_j;\n    arma::vec Pi;\n    arma::vec Pj;\n    arma::vec Qi;\n    arma::vec Qj;\n    arma::vec wi;\n    arma::vec wj;\n    arma::vec Si;\n    arma::vec Sj;\n    Body *body_i_ptr;\n    Body *body_j_ptr;\n};\n\n#endif  //JOINT_HPP", "meta": {"hexsha": "74ed8cdcb6c98a3284e448b84f299cd1cbb3dfcd", "size": 830, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Joint.hpp", "max_stars_repo_name": "j8xixo12/Multibody-Dynamics-Solver", "max_stars_repo_head_hexsha": "6102a97b00e3ce59db7fb95acc25be5bd8711984", "max_stars_repo_licenses": ["MIT"], "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/Joint.hpp", "max_issues_repo_name": "j8xixo12/Multibody-Dynamics-Solver", "max_issues_repo_head_hexsha": "6102a97b00e3ce59db7fb95acc25be5bd8711984", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Joint.hpp", "max_forks_repo_name": "j8xixo12/Multibody-Dynamics-Solver", "max_forks_repo_head_hexsha": "6102a97b00e3ce59db7fb95acc25be5bd8711984", "max_forks_repo_licenses": ["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.8636363636, "max_line_length": 78, "alphanum_fraction": 0.5879518072, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6324720281418652}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include \"math/Bezier.hpp\"\n#include \"math/Bezier2D.hpp\"\n\nTEST(Bezier, Linear2D)\n{\n    using VT = Eigen::Vector2d;\n\n    auto bez = Bezier<VT,1>(VT(0.0, 0.0), VT(1.0, 2.0));\n    EXPECT_TRUE(bez.get<0>() == VT(0.0, 0.0));\n    EXPECT_TRUE(bez.get<1>() == VT(1.0, 2.0));\n    EXPECT_LT( (bez.eval(0.2) - VT(0.2, 0.4)).norm(), 10e-14 );\n    EXPECT_LT( (bez.eval(0.5) - VT(0.5, 1.0)).norm(), 10e-14 );\n    EXPECT_LT( (bez.eval(0.7) - VT(0.7, 1.4)).norm(), 10e-14 );\n}\n\nTEST(Bezier, LinearDiv)\n{\n    using VT = Eigen::Vector2d;\n\n    auto bez = Bezier<VT,1>(VT(0.0, 0.0), VT(1.0, 2.0));\n    auto bezdiv = bez.divide();\n\n    EXPECT_LT( (bezdiv.first.get<0>()-bez.eval(0.0)).norm(), 10e-14 );\n    EXPECT_LT( (bezdiv.first.get<1>()-bez.eval(0.5)).norm(), 10e-14 );\n    EXPECT_LT( (bezdiv.second.get<0>()-bez.eval(0.5)).norm(), 10e-14 )\n        << bezdiv.second.get<0>() << std::endl;\n    EXPECT_LT( (bezdiv.second.get<1>()-bez.eval(1.0)).norm(), 10e-14 )\n        << bezdiv.second.get<1>() << std::endl;\n}\n\nTEST(Bezier, LinearClip)\n{\n    Bezier<Eigen::Vector2d,1> bez(\n        Eigen::Vector2d(0.0, 0.0),\n        Eigen::Vector2d(1.0, 2.0) );\n\n    constexpr size_t smp = 10;\n    constexpr double dur = 1.0/smp;\n    for(size_t i = 0; i < smp; ++i) {\n        for(size_t j = i+1; j < smp; ++j) {\n            auto bezclip = bez.clip(i*dur, j*dur);\n            EXPECT_LT( (bezclip.get<0>()-bez.eval(i*dur)).norm(), 10e-10);\n            EXPECT_LT( (bezclip.get<1>()-bez.eval(j*dur)).norm(), 10e-10);        }\n    }\n}\n\nTEST(Bezier, Quad2D)\n{\n    using VT = Eigen::Vector2d;\n\n    auto bez = Bezier<VT,2>(VT(2.0, 0.0), VT(0.0, 0.0), VT(0.0, 2.0));\n\n    EXPECT_TRUE(bez.get<0>() == VT(2.0, 0.0));\n    EXPECT_TRUE(bez.get<1>() == VT(0.0, 0.0));\n    EXPECT_TRUE(bez.get<2>() == VT(0.0, 2.0));\n    EXPECT_LT( (bez.eval(0.2) - VT(1.28, 0.08)).norm(), 10e-14 );\n    EXPECT_LT( (bez.eval(0.5) - VT(0.5, 0.5)).norm(), 10e-14 );\n    EXPECT_LT( (bez.eval(0.8) - VT(0.08, 1.28)).norm(), 10e-14 );\n}\n\nTEST(Bezier, QuadDiv)\n{\n    using VT = Eigen::Vector2d;\n\n    auto bez = Bezier<VT,2>(VT(2.0, 0.0), VT(0.0, 0.0), VT(0.0, 2.0));\n    auto bezdiv = bez.divide();\n\n    EXPECT_LT( (bezdiv.first.get<0>() - bez.eval(0.0)).norm(), 10e-14 );\n    EXPECT_LT( (bezdiv.first.get<1>() - VT(1.0,0.0)).norm(), 10e-14 );\n    EXPECT_LT( (bezdiv.first.get<2>() - bez.eval(0.5)).norm(), 10e-14 );\n    EXPECT_LT( (bezdiv.second.get<0>() - bez.eval(0.5)).norm(), 10e-14 );\n    EXPECT_LT( (bezdiv.second.get<1>() - VT(0.0,1.0)).norm(), 10e-14 );\n    EXPECT_LT( (bezdiv.second.get<2>() - bez.eval(1.0)).norm(), 10e-14 );\n\n    for(double t = 0.0; t < 1.0; t += 0.1) {\n        EXPECT_LT( (bezdiv.first.eval(t) - bez.eval(t/2.0)).norm(), 10e-14 )\n            << \"different at \" << t << std::endl\n            << \"bez(t/2) =\" << bez.eval(t/2.0).adjoint() << std::endl\n            << \"bezdiv(t)=\" << bezdiv.first.eval(t).adjoint() << std::endl;\n        EXPECT_LT( (bezdiv.second.eval(t) - bez.eval(0.5+t/2.0)).norm(), 10e-14 )\n            << \"different at \" << t << std::endl\n            << \"bez(t/2+0.5)=\" << bez.eval(0.5+t/2.0).adjoint() << std::endl\n            << \"bezdiv2(t)  =\" << bezdiv.second.eval(t).adjoint() << std::endl;\n    }\n}\n\nTEST(Bezier, QuadClip)\n{\n    Bezier<Eigen::Vector2d,2> bez(\n        Eigen::Vector2d(2.0, 0.0),\n        Eigen::Vector2d(0.0, 0.0),\n        Eigen::Vector2d(0.0, 2.0));\n\n    constexpr size_t smp = 10;\n    constexpr double dur = 1.0/smp;\n    for(size_t i = 0; i < smp; ++i) {\n        for(size_t j = i+1; j < smp; ++j) {\n            auto bezclip = bez.clip(i*dur, j*dur);\n            EXPECT_LT( (bezclip.get<0>()-bez.eval(i*dur)).norm(), 10e-10);\n            EXPECT_LT( (bezclip.eval(0.5)-bez.eval(i*dur/2 + j*dur/2)).norm(), 10e-10);\n            EXPECT_LT( (bezclip.get<2>()-bez.eval(j*dur)).norm(), 10e-10);        }\n    }\n}\n\nTEST(Bezier, Range)\n{\n    Bezier<Eigen::Vector2d,3> bez = {\n        Eigen::Vector2d(0.0, 0.0),\n        Eigen::Vector2d(1.0, 0.0),\n        Eigen::Vector2d(0.0, 1.0),\n        Eigen::Vector2d(1.0, 1.0)\n    };\n\n    std::vector<Eigen::Vector2d> vec;\n\n    for(auto& pt : bez) {\n        vec.push_back(pt);\n    }\n\n    ASSERT_EQ(vec.size(), 4);\n    EXPECT_EQ(vec[0], Eigen::Vector2d(0.0, 0.0));\n    EXPECT_EQ(vec[1], Eigen::Vector2d(1.0, 0.0));\n    EXPECT_EQ(vec[2], Eigen::Vector2d(0.0, 1.0));\n    EXPECT_EQ(vec[3], Eigen::Vector2d(1.0, 1.0));\n\n    Bezier<Eigen::Vector2d, 3> const cbez = bez;\n\n    vec.clear();\n\n    for(auto& pt : cbez) {\n        vec.push_back(pt);\n    }\n\n    ASSERT_EQ(vec.size(), 4);\n    EXPECT_EQ(vec[0], Eigen::Vector2d(0.0, 0.0));\n    EXPECT_EQ(vec[1], Eigen::Vector2d(1.0, 0.0));\n    EXPECT_EQ(vec[2], Eigen::Vector2d(0.0, 1.0));\n    EXPECT_EQ(vec[3], Eigen::Vector2d(1.0, 1.0));\n}\n\n// Test class\nstruct TestVec2 {\n    double arr[2];\n    double norm() const noexcept {\n        return std::sqrt(arr[0]*arr[0] + arr[1]*arr[1]);\n    }\n    constexpr double& operator[](size_t i) noexcept{ return arr[i]; }\n    constexpr double const& operator[](size_t i) const noexcept { return arr[i]; }\n    constexpr TestVec2& operator+=(TestVec2 const& rhs) {\n        arr[0] += rhs.arr[0];\n        arr[1] += rhs.arr[1];\n        return *this;\n    }\n    constexpr TestVec2& operator-=(TestVec2 const& rhs) {\n        arr[0] -= rhs.arr[0];\n        arr[1] -= rhs.arr[1];\n        return *this;\n    }\n};\n\nconstexpr TestVec2 operator+(TestVec2 lhs, TestVec2 const& rhs)\n{\n    lhs += rhs;\n    return lhs;\n}\n\nconstexpr TestVec2 operator-(TestVec2 lhs, TestVec2 const& rhs)\n{\n    lhs -= rhs;\n    return lhs;\n}\n\nconstexpr TestVec2 operator*(double a, TestVec2 const& rhs)\n{\n    return {rhs[0]*a, rhs[1]*a};\n}\n\nbool operator==(TestVec2 const& lhs, TestVec2 const& rhs)\n{\n    return (lhs-rhs).norm() <= (lhs.norm() + rhs.norm())*10e-10;\n}\n\nbool operator!=(TestVec2 const& lhs, TestVec2 const& rhs)\n{\n    return !(lhs==rhs);\n}\n\nTEST(Bezier, CubicWithMyVector)\n{\n    constexpr auto bez = Bezier<TestVec2,3>(\n        TestVec2{0.0, 0.0},\n        TestVec2{0.0, 1.0},\n        TestVec2{1.0, 1.0},\n        TestVec2{1.0, 0.0} );\n\n    constexpr auto v = bez.eval(0.5);\n    constexpr auto vshouldbe = TestVec2{1.0/8.0 + 3.0/8.0, 3.0/8.0 + 3.0/8.0};\n    EXPECT_EQ(v, vshouldbe);\n\n    constexpr auto bezdiv = bez.divide();\n    constexpr size_t smp = 10;\n    constexpr double dur = 1.0/smp;\n    for(size_t i = 0; i < smp; ++i) {\n        double t = i*dur;\n        EXPECT_EQ(bezdiv.first.eval(t), bez.eval(t/2.0))\n            << \"different at \" << t << std::endl;\n        EXPECT_EQ(bezdiv.second.eval(t), bez.eval(0.5+t/2.0))\n            << \"different at \" << t << std::endl;\n    }\n\n    constexpr auto bezclip = bez.clip(0.3, 0.7);\n    for(size_t i = 0; i < smp; ++i) {\n        double t = i*dur;\n        EXPECT_EQ(bezclip.eval(t), bez.eval(0.3+t*0.4));\n    }\n}\n\nTEST(Bezier, ArbitraryDivision)\n{\n    constexpr auto bez = Bezier<TestVec2,3>(\n        TestVec2{0.0, 0.0},\n        TestVec2{0.0, 1.0},\n        TestVec2{1.0, 1.0},\n        TestVec2{1.0, 0.0} );\n\n    for(double t0 = 0.1; t0 < 1.0; t0 += 0.1) {\n        auto bezdiv = bez.divide(t0);\n        for(double t = 0.0; t < 1.0; t += 0.1) {\n            EXPECT_EQ(bezdiv.first.eval(t), bez.eval(t*t0))\n                << \"different at \" << t << std::endl;\n            EXPECT_EQ(bezdiv.second.eval(t), bez.eval(t0+t*(1.0-t0)))\n                << \"different at \" << t << std::endl;\n        }\n    }\n}\n\nTEST(Bezier, Convert)\n{\n    struct Rotate90 {\n        constexpr TestVec2 operator()(TestVec2 src) const noexcept {\n            return TestVec2{-src.arr[1], src.arr[0]};\n        }\n    };\n\n    constexpr auto bez = Bezier<TestVec2,3>(\n        TestVec2{0.0, 0.0},\n        TestVec2{0.0, 1.0},\n        TestVec2{1.0, 1.0},\n        TestVec2{1.0, 0.0} );\n    constexpr auto bez90 = bez.convert(Rotate90());\n    constexpr size_t smp = 10;\n    constexpr double dur = 1.0/smp;\n    for(size_t i = 0; i < smp; ++i) {\n        double t = i*dur;\n        auto pt = bez.eval(t);\n        auto pt90 = bez90.eval(t);\n        auto pt90shouldbe = TestVec2{-pt.arr[1], pt.arr[0]};\n        EXPECT_EQ(pt90, pt90shouldbe);\n        if(i > 0)\n            EXPECT_NE(pt90, pt);\n    }\n};\n\nTEST(Bezier, Variant)\n{\n    constexpr Bezier<TestVec2,2> bez2(\n        TestVec2{0.0, 0.0},\n        TestVec2{1.0, 0.0},\n        TestVec2{1.0, 1.0});\n    constexpr BezierVariant<TestVec2,0,1,2,3> bezvar(std::integral_constant<size_t,2>(), bez2);\n\n    std::vector<TestVec2> vs;\n    for(auto pt : bezvar) {\n        vs.push_back(pt);\n    }\n    ASSERT_EQ(vs.size(), 3);\n    EXPECT_EQ(vs[0], (TestVec2{0.0, 0.0}));\n    EXPECT_EQ(vs[1], (TestVec2{1.0, 0.0}));\n    EXPECT_EQ(vs[2], (TestVec2{1.0, 1.0}));\n\n    constexpr size_t smp = 10;\n    constexpr double dur = 1.0/smp;\n\n    // Evaluation test\n    for(size_t i = 0; i <= smp; ++i) {\n        double t = i*dur;\n        EXPECT_EQ(bez2.eval(t),\n                  bezvar.eval(t));\n    }\n\n    // Division test\n    constexpr auto bez2div = bez2.divide();\n    constexpr auto bezvardiv = bezvar.divide();\n    for(size_t i = 0; i <= smp; ++i) {\n        double t = i*dur;\n        EXPECT_EQ(bez2div.first.eval(t),\n                  bezvardiv.first.eval(t));\n        EXPECT_EQ(bez2div.second.eval(t),\n                  bezvardiv.second.eval(t));\n    }\n\n    // Clip test\n    for(size_t i = 0; i < smp; ++i) {\n        for(size_t j = i+1; j <= smp; ++j) {\n            auto bez2clip = bez2.clip(i*dur, j*dur);\n            auto bezvarclip = bezvar.clip(i*dur, j*dur);\n            for(size_t k = 0; k <= smp; ++k) {\n                double t = k*dur;\n                EXPECT_EQ(bez2clip.eval(t), bezvarclip.eval(t));\n            }\n        }\n    }\n\n    // Convert test\n    struct Rotate90 {\n        constexpr TestVec2 operator()(TestVec2 src) const noexcept {\n            return TestVec2{-src.arr[1], src.arr[0]};\n        }\n    };\n    constexpr auto bez2_90 = bez2.convert(Rotate90());\n    constexpr auto bezvar_90 = bezvar.convert(Rotate90());\n    for(size_t i = 0; i <= smp; ++i) {\n        double t = i*dur;\n        EXPECT_EQ(bez2_90.eval(t), bezvar_90.eval(t));\n    }\n\n    // Assignment\n    constexpr Bezier<TestVec2,3> bez3(\n        TestVec2{0.0, 0.0},\n        TestVec2{1.0, 0.0},\n        TestVec2{0.0, 1.0},\n        TestVec2{1.0, 1.0});\n    auto bezvar3 = bezvar;\n    bezvar3.assign(std::integral_constant<size_t,3>(), bez3);\n    vs.clear();\n    for(auto pt : bezvar3) {\n        vs.push_back(pt);\n    }\n    ASSERT_EQ(vs.size(), 4);\n    EXPECT_EQ(vs[0], (TestVec2{0.0, 0.0}));\n    EXPECT_EQ(vs[1], (TestVec2{1.0, 0.0}));\n    EXPECT_EQ(vs[2], (TestVec2{0.0, 1.0}));\n    EXPECT_EQ(vs[3], (TestVec2{1.0, 1.0}));\n}\n\nTEST(Bezier2D, IntersectionLinLin)\n{\n    constexpr size_t max_smp = 20;\n    for(size_t i = 0; i < max_smp; ++i) {\n        double t = 2*i*M_PI/max_smp;\n        Eigen::Matrix2d mat;\n        mat << cos(t), -sin(t), sin(t), cos(t);\n\n        auto bez1 = Bezier<Eigen::Vector2d,1>(\n            mat*Eigen::Vector2d(-1.0, 0.0),\n            mat*Eigen::Vector2d(1.0, 0.0) );\n        auto bez2 = Bezier<Eigen::Vector2d,1>(\n            mat*Eigen::Vector2d(0.8, 0.6),\n            mat*Eigen::Vector2d(0.8, -0.6) );\n\n        auto params = intersect<12,3>(bez1, bez2);\n        ASSERT_GE(params.size(), 1) << \"t=\" << t;\n        EXPECT_LT(std::abs(params[0].first - 0.9), 10e-10);\n        EXPECT_LT(std::abs(params[0].second - 0.5), 10e-10);\n        if (params.size() > 1) {\n            ADD_FAILURE()\n                << \"i=\" << i << \", t=\" << t << std::endl\n                << \"(\" << params[0].first << \", \" << params[0].second << \")\"\n                << std::endl\n                << \"(\" << params[1].first << \", \" << params[1].second << \")\"\n                << std::endl;\n        }\n    }\n}\n\nTEST(Bezier2D, IntersectionLinLinTerminated)\n{\n    constexpr size_t max_smp = 20;\n    for(size_t i = 0; i < max_smp; ++i) {\n        double t = 2*i*M_PI/max_smp;\n        Eigen::Matrix2d mat;\n        mat << cos(t), -sin(t), sin(t), cos(t);\n\n        auto bez1 = Bezier<Eigen::Vector2d,1>(\n            mat*Eigen::Vector2d(-1.0, 0.0),\n            mat*Eigen::Vector2d(1.0, 0.0) );\n        auto bez2 = Bezier<Eigen::Vector2d,1>(\n            mat*Eigen::Vector2d(0.8, 0.6),\n            mat*Eigen::Vector2d(0.8, -0.6) );\n\n        auto params = intersect<12,3>(bez1, bez2, std::false_type{});\n        EXPECT_TRUE(params.empty());\n    }\n}\n\nTEST(Bezier2D, IntersectionQQ)\n{\n    constexpr size_t max_smp = 20;\n    for(size_t i = 0; i < max_smp; ++i) {\n        double t = 2*i*M_PI/max_smp;\n        Eigen::Matrix2d mat;\n        mat << cos(t), -sin(t), sin(t), cos(t);\n\n        auto bez1 = Bezier<Eigen::Vector2d,2>(\n            mat*Eigen::Vector2d(-0.5, -1.0),\n            mat*Eigen::Vector2d(1.0, 0.0),\n            mat*Eigen::Vector2d(-0.5, 1.0) );\n        auto bez2 = Bezier<Eigen::Vector2d,2>(\n            mat*Eigen::Vector2d(0.5, -1.0),\n            mat*Eigen::Vector2d(-1.0, 0.0),\n            mat*Eigen::Vector2d(0.5, 1.0) );\n\n        auto params = intersect<12,3>(bez1, bez2);\n        ASSERT_GE(params.size(), 2) << \"t=\" << t;\n        EXPECT_LT(\n            std::abs((mat.adjoint()*bez1.eval(params[0].first))(0)),\n            10e-10);\n        EXPECT_LT(\n            std::abs((mat.adjoint()*bez2.eval(params[1].first))(0)),\n            10e-10);\n        if (params.size() > 2) {\n            ADD_FAILURE()\n                << \"i=\" << i << \", t=\" << t << std::endl\n                << \"(\" << params[0].first << \", \" << params[0].second << \")\"\n                << std::endl\n                << \"(\" << params[1].first << \", \" << params[1].second << \")\"\n                << std::endl;\n        }\n    }\n}\n\nTEST(Bezier2D, IntersectionVarQL)\n{\n    constexpr size_t max_smp = 20;\n    for(size_t i = 0; i < max_smp; ++i) {\n        double t = 2*i*M_PI/max_smp;\n        Eigen::Matrix2d mat;\n        mat << cos(t), -sin(t), sin(t), cos(t);\n\n        auto bez1 = BezierVariant<Eigen::Vector2d,0,1,2>(\n            std::integral_constant<size_t,2>(),\n            mat*Eigen::Vector2d(-0.5, -1.0),\n            mat*Eigen::Vector2d(1.0, 0.0),\n            mat*Eigen::Vector2d(-0.5, 1.0) );\n        auto bez2 = Bezier<Eigen::Vector2d,2>(\n            mat*Eigen::Vector2d(0.5, -1.0),\n            mat*Eigen::Vector2d(-1.0, 0.0),\n            mat*Eigen::Vector2d(0.5, 1.0) );\n\n        auto params = intersect<12,3>(bez1, bez2);\n        ASSERT_GE(params.size(), 2) << \"t=\" << t;\n        EXPECT_LT(\n            std::abs((mat.adjoint()*bez1.eval(params[0].first))(0)),\n            10e-10);\n        EXPECT_LT(\n            std::abs((mat.adjoint()*bez2.eval(params[1].first))(0)),\n            10e-10);\n        if (params.size() > 2) {\n            ADD_FAILURE()\n                << \"i=\" << i << \", t=\" << t << std::endl\n                << \"(\" << params[0].first << \", \" << params[0].second << \")\"\n                << std::endl\n                << \"(\" << params[1].first << \", \" << params[1].second << \")\"\n                << std::endl;\n        }\n    }\n}\n", "meta": {"hexsha": "b281027235ab3c870ee54acc1dfcf76766f82100", "size": 14829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_bezier.cpp", "max_stars_repo_name": "Junology/bord2", "max_stars_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_bezier.cpp", "max_issues_repo_name": "Junology/bord2", "max_issues_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_bezier.cpp", "max_forks_repo_name": "Junology/bord2", "max_forks_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4840764331, "max_line_length": 95, "alphanum_fraction": 0.5166228336, "num_tokens": 5264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759128, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6324720251156745}}
{"text": " /*\n * functions.cpp\n *\n */\n#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <numeric>\n\n#include <boost/assert.hpp>\n\n#include \"core/utils.h\"\n#include \"core/types.h\"\n#include \"core/functions.h\"\n\nusing namespace std;\nusing namespace yann;\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// Activation functions implementation\n//\n\n// identity function:\n//  f(x) = x\n//  d f(x<i>) / d(x<j>) = 1 if i == j and 0 if i != j\nstring yann::IdentityFunction::get_info() const\n{\n  return \"Identity\";\n}\nvoid yann::IdentityFunction::f(const RefConstVectorBatch & input, RefVectorBatch output, enum OperationMode mode)\n{\n  YANN_SLOW_CHECK(is_same_size(input, output));\n  switch(mode) {\n  case Operation_Assign:\n    output.noalias() = input;\n    break;\n  case Operation_PlusEqual:\n    output.noalias() += input;\n    break;\n  }\n}\nvoid yann::IdentityFunction::derivative(const RefConstVectorBatch & input, RefVectorBatch output)\n{\n  YANN_SLOW_CHECK(is_same_size(input, output));\n  output.setOnes();\n}\nunique_ptr<ActivationFunction> yann::IdentityFunction::copy() const\n{\n  return make_unique<IdentityFunction>();\n}\n\n// rectified linear unit function or leaky ReLU if a != 0:\n//  f(x) = x for x > 0 ; a*x for x < 0\n//  d f(x<i>) / d(x<j>) = 1 if x > 0; a if x < 0\nstring yann::ReluFunction::get_info() const\n{\n  return \"Relu\";\n}\nvoid yann::ReluFunction::f(const RefConstVectorBatch & input, RefVectorBatch output, enum OperationMode mode)\n{\n  YANN_SLOW_CHECK(is_same_size(input, output));\n\n  switch(mode) {\n  case Operation_Assign:\n    output.setZero();\n    break;\n  case Operation_PlusEqual:\n    // do nothing\n    break;\n  }\n\n  const auto batch_size = get_batch_size(output);\n  const auto batch_item_size = get_batch_item_size(output);\n  for(MatrixSize ii = 0 ; ii < batch_size; ++ii) {\n    for(MatrixSize jj = 0 ; jj < batch_item_size; ++jj) {\n      if(get_batch(input, ii)(jj) >= 0) {\n        get_batch(output, ii)(jj) += get_batch(input, ii)(jj);\n      } else {\n        get_batch(output, ii)(jj) += _a * get_batch(input, ii)(jj);\n      }\n    }\n  }\n}\nvoid yann::ReluFunction::derivative(const RefConstVectorBatch & input, RefVectorBatch output)\n{\n  YANN_SLOW_CHECK(is_same_size(input, output));\n\n  const auto batch_size = get_batch_size(output);\n  const auto batch_item_size = get_batch_item_size(output);\n  for(MatrixSize ii = 0 ; ii < batch_size; ++ii) {\n    for(MatrixSize jj = 0 ; jj < batch_item_size; ++jj) {\n      if(get_batch(input, ii)(jj) >= 0) {\n        get_batch(output, ii)(jj) = 1;\n      } else {\n        get_batch(output, ii)(jj) = _a;\n      }\n    }\n  }\n}\nunique_ptr<ActivationFunction> yann::ReluFunction::copy() const\n{\n  return make_unique<ReluFunction>(_a);\n}\n\n// sigmoid function:\n//  f(x) = 1 / (1 + exp(-x))\nstring yann::SigmoidFunction::get_info() const\n{\n  return \"Sigmoid\";\n}\nValue yann::SigmoidFunction::sigmoid_scalar(const Value & x)\n{\n  return 1 / (1 + exp(-x));\n}\n\nValue yann::SigmoidFunction::sigmoid_derivative_scalar(const Value & x)\n{\n  Value s = sigmoid_scalar(x);\n  return s * (1 - s);\n}\n\nvoid yann::SigmoidFunction::f(const RefConstVectorBatch & input, RefVectorBatch output, enum OperationMode mode)\n{\n  YANN_SLOW_CHECK(is_same_size(input, output));\n\n  switch(mode) {\n  case Operation_Assign:\n    output.array() = 1 / (1 + exp(-input.array()));\n    break;\n  case Operation_PlusEqual:\n    output.array() += 1 / (1 + exp(-input.array()));\n    break;\n  }\n}\n\nvoid yann::SigmoidFunction::derivative(const RefConstVectorBatch & input, RefVectorBatch output)\n{\n  YANN_SLOW_CHECK(is_same_size(input, output));\n  this->f(input, output);\n  output.array() =  output.array() * (1 -  output.array());\n}\nunique_ptr<ActivationFunction> yann::SigmoidFunction::copy() const\n{\n  return make_unique<SigmoidFunction>();\n}\n\n\n// Fast sigmoid function:\n//  f(x) = 1 / (1 + exp(-x))\nyann::FastSigmoidFunction::FastSigmoidFunction(const size_t & table_size, const Value & max_value) :\n    _table(table_size + 1),\n    _max_value(max_value)\n{\n  // populates _table with sigmoid(x) values for x in (-max_value, max_value)\n  for(size_t ii = 0; ii <= table_size; ++ii) {\n    _table[ii] = SigmoidFunction::sigmoid_scalar((2 * ii / (Value)table_size - 1) * max_value);\n  }\n}\n\nyann::FastSigmoidFunction::FastSigmoidFunction(const SigmoidTable & table, const Value & max_value) :\n    _table(table),\n    _max_value(max_value)\n{\n}\n\nstring yann::FastSigmoidFunction::get_info() const\n{\n  ostringstream oss;\n  oss << \"FastSigmoidFunction[\"\n      << \"max_value=\" << _max_value\n      << \", table_size=\" << _table.size()\n      << \"]\"\n      ;\n  return oss.str();\n}\n\nvoid yann::FastSigmoidFunction::f(const RefConstVectorBatch & input, RefVectorBatch output, enum OperationMode mode)\n{\n  YANN_SLOW_CHECK(is_same_size(input, output));\n\n  auto sigmoid = [&](const Value & xx) -> Value {\n    if(xx <= -_max_value) {\n      return 0;\n    } else if(xx >= _max_value) {\n      return 1;\n    }\n    auto index = (size_t)((xx + _max_value) * (_table.size() - 1) / (2 * _max_value));\n    YANN_SLOW_CHECK_GE(index, 0);\n    YANN_SLOW_CHECK_LT(index, _table.size());\n    return _table[index];\n  };\n\n  switch(mode) {\n  case Operation_Assign:\n    for(MatrixSize ii = 0; ii < input.rows(); ++ii) {\n      for(MatrixSize jj = 0; jj < input.cols(); ++jj) {\n        output(ii, jj) = sigmoid(input(ii, jj));\n      }\n    }\n    break;\n  case Operation_PlusEqual:\n    for(MatrixSize ii = 0; ii < input.rows(); ++ii) {\n      for(MatrixSize jj = 0; jj < input.cols(); ++jj) {\n        output(ii, jj) += sigmoid(input(ii, jj));\n      }\n    }\n    break;\n  }\n}\n\nvoid yann::FastSigmoidFunction::derivative(const RefConstVectorBatch & input, RefVectorBatch output)\n{\n  YANN_SLOW_CHECK(is_same_size(input, output));\n  this->f(input, output);\n  output.array() =  output.array() * (1 -  output.array());\n}\nunique_ptr<ActivationFunction> yann::FastSigmoidFunction::copy() const\n{\n  // can't use make_unique<> because this constructor is private\n  auto res = new FastSigmoidFunction(_table, _max_value);\n  return unique_ptr<ActivationFunction>(res);\n}\n\n// tanh function:\n//  f(x) = A * tanh(S*x)\n//  df/dx = A * S * (1\u2212(tanh(S*x))^2)\nstring yann::TanhFunction::get_info() const\n{\n  ostringstream oss;\n  oss << \"Tanh[\"\n      << \"A=\" << _AA\n      << \", S=\" << _SS\n      << \"]\"\n      ;\n  return oss.str();\n}\n\nvoid yann::TanhFunction::f(const RefConstVectorBatch & input, RefVectorBatch output, enum OperationMode mode)\n{\n  YANN_SLOW_CHECK(is_same_size(input, output));\n\n  switch(mode) {\n  case Operation_Assign:\n    output.array() = _AA * tanh(input.array() * _SS);\n    break;\n  case Operation_PlusEqual:\n    output.array() += _AA * tanh(input.array()* _SS);\n    break;\n  }\n}\n\nvoid yann::TanhFunction::derivative(const RefConstVectorBatch & input, RefVectorBatch output)\n{\n  YANN_SLOW_CHECK(is_same_size(input, output));\n  this->f(input, output);\n  output.array() = (1 - tanh(input.array()* _SS).square()) * (_AA * _SS);\n}\nunique_ptr<ActivationFunction> yann::TanhFunction::copy() const\n{\n  return make_unique<TanhFunction>(_AA, _SS);\n}\n\n// quadratic cost function:\n//  f(actual, expected) = sum((actual<i> - expected<i>)^2)\n//  d f(actual, expected) / d (actual) = (actual<i> - expected<i>)\nstring yann::QuadraticCost::get_info() const\n{\n  return \"Quadratic\";\n}\nValue yann::QuadraticCost::f(const RefConstVectorBatch & actual, const RefConstVectorBatch & expected)\n{\n  YANN_SLOW_CHECK(is_same_size(actual, expected));\n  return ((actual.array() - expected.array()).square()).sum();\n}\nvoid yann::QuadraticCost::derivative(const RefConstVectorBatch & actual, const RefConstVectorBatch & expected, RefVectorBatch output)\n{\n  YANN_SLOW_CHECK(is_same_size(actual, expected));\n  YANN_SLOW_CHECK(is_same_size(actual, output));\n  output.noalias() = 2 * (actual - expected);\n}\nunique_ptr<CostFunction> yann::QuadraticCost::copy() const\n{\n  return make_unique<QuadraticCost>();\n}\n\n// Exponential cost:\n//  f(actual, expected) = tau * exp(sum((actual<i> - expected<i>)^2) / tau)\n//  d f(actual, expected) / d (actual) = 2 * f(actual, expected) * (actual<i> - expected<i>)\nstring yann::ExponentialCost::get_info() const\n{\n  ostringstream oss;\n  oss << \"Exponential[\"\n      << \"tau=\" << _tau\n      << \"]\"\n      ;\n  return oss.str();\n}\nValue yann::ExponentialCost::f(const RefConstVectorBatch & actual, const RefConstVectorBatch & expected)\n{\n  YANN_SLOW_CHECK(is_same_size(actual, expected));\n  const auto val = (actual.array() - expected.array()).square().sum();\n  return _tau * exp(val / _tau);\n}\nvoid yann::ExponentialCost::derivative(const RefConstVectorBatch & actual, const RefConstVectorBatch & expected, RefVectorBatch output)\n{\n  YANN_SLOW_CHECK(is_same_size(actual, expected));\n  YANN_SLOW_CHECK(is_same_size(actual, output));\n  output.noalias() = (2 * f(actual, expected)) * (actual - expected);\n}\nunique_ptr<CostFunction> yann::ExponentialCost::copy() const\n{\n  return make_unique<ExponentialCost>(_tau);\n}\n\n// cross entropy function:\n//  f(actual, expected) = sum(-(expected * ln(actual) + (1 - expected) * ln(1 - actual)))\n//  d f(actual, expected) / d (actual) = (actual - expected) / ((1 - actual) * actual)\nstring yann::CrossEntropyCost::get_info() const\n{\n  ostringstream oss;\n  oss << \"CrossEntropy[\"\n      << \"epsilon=\" << _epsilon\n      << \"]\"\n      ;\n  return oss.str();\n}\n\nValue yann::CrossEntropyCost::f(const RefConstVectorBatch & actual, const RefConstVectorBatch & expected)\n{\n  YANN_SLOW_CHECK(is_same_size(actual, expected));\n\n  // iterate over elements manually and use small _epsilon to avoid hitting nan\n  Value res = 0;\n  for(MatrixSize ii = 0; ii < actual.rows(); ++ii) {\n    for(MatrixSize jj = 0; jj < actual.cols(); ++jj) {\n      auto aa = actual(ii, jj);\n      auto ee = expected(ii, jj);\n      if(aa <= 0) {\n        aa = _epsilon;\n      } else if(aa >= 1) {\n        aa = 1 - _epsilon;\n      }\n      res += (ee * log(aa) + (1 - ee) * log(1 - aa));\n    }\n  }\n  return -(res);\n}\n\nvoid yann::CrossEntropyCost::derivative(const RefConstVectorBatch & actual, const RefConstVectorBatch & expected, RefVectorBatch output)\n{\n  YANN_SLOW_CHECK(is_same_size(actual, expected));\n  YANN_SLOW_CHECK(is_same_size(actual, output));\n\n  // iterate over elements manually and use small _epsilon to avoid hitting nan\n  for(MatrixSize ii = 0; ii < actual.rows(); ++ii) {\n    for(MatrixSize jj = 0; jj < actual.cols(); ++jj) {\n      auto aa = actual(ii, jj);\n      auto ee = expected(ii, jj);\n      if(fabs(aa - ee) > _epsilon) {\n        if(aa <= 0) {\n          aa = _epsilon;\n        } else if(aa >= 1) {\n          aa = 1 - _epsilon;\n        }\n        output(ii, jj) = (aa - ee) / ((1 - aa) * aa);\n      } else {\n        output(ii, jj) = 0;\n      }\n    }\n  }\n}\n\nunique_ptr<CostFunction> yann::CrossEntropyCost::copy() const\n{\n  return make_unique<CrossEntropyCost>(_epsilon);\n}\n\n// Hellinger distance cost:\n//  f(actual, expected) = sum(sqrt(actual) - sqrt(expected))^2\n//  d f(actual, expected) / d (actual) =  (1 -  sqrt(expected) /  sqrt(actual))\nstring yann::HellingerDistanceCost::get_info() const\n{\n  ostringstream oss;\n  oss << \"HellingerDistance[\"\n      << \"epsilon=\" << _epsilon\n      << \"]\"\n      ;\n  return oss.str();\n}\n\nValue yann::HellingerDistanceCost::f(const RefConstVectorBatch & actual, const RefConstVectorBatch & expected)\n{\n  YANN_SLOW_CHECK(is_same_size(actual, expected));\n  return (((actual.array() + _epsilon).sqrt() - expected.array().sqrt()).square()).sum();\n}\n\nvoid yann::HellingerDistanceCost::derivative(const RefConstVectorBatch & actual, const RefConstVectorBatch & expected, RefVectorBatch output)\n{\n  YANN_SLOW_CHECK(is_same_size(actual, expected));\n  YANN_SLOW_CHECK(is_same_size(actual, output));\n  output.array() = (1 - expected.array().sqrt() / (actual.array() + _epsilon).sqrt());\n}\nunique_ptr<CostFunction> yann::HellingerDistanceCost::copy() const\n{\n  return make_unique<HellingerDistanceCost>(_epsilon);\n}\n\n// Squared Hinge Loss:\n//  f(actual, expected) = (max(0, 1 - actual * expected))^2\n//  d f(actual, expected) / d (actual(i)) =  if (actual * expected) > 1 then 0; otherwise -2 * (1 - actual * expected) * expected(i)\nstring yann::SquaredHingeLoss::get_info() const\n{\n  return \"SquaredHingeLoss\";\n}\nValue yann::SquaredHingeLoss::f(const RefConstVectorBatch & actual, const RefConstVectorBatch & expected)\n{\n  YANN_SLOW_CHECK(is_same_size(actual, expected));\n\n  Value res = 0;\n  for(MatrixSize ii = 0; ii < get_batch_size(actual); ++ii) {\n    const auto aa = get_batch(actual, ii);\n    const auto ee = get_batch(expected, ii);\n\n    const Value vv = (aa.array() * ee.array()).sum();\n    if(vv < 1.0) {\n      res += (1.0 - vv) * (1.0 - vv);\n    }\n  }\n  return res;\n}\n\nvoid yann::SquaredHingeLoss::derivative(const RefConstVectorBatch & actual, const RefConstVectorBatch & expected, RefVectorBatch output)\n{\n  YANN_SLOW_CHECK(is_same_size(actual, expected));\n  YANN_SLOW_CHECK(is_same_size(actual, output));\n\n  for(MatrixSize ii = 0; ii < get_batch_size(actual); ++ii) {\n    const auto aa = get_batch(actual, ii);\n    const auto ee = get_batch(expected, ii);\n    auto oo = get_batch(output, ii);\n\n    const Value vv = (aa.array() * ee.array()).sum();\n    if(vv < 1) {\n      oo = - 2 * (1.0 - vv) * ee;\n    } else {\n      oo.setZero();\n    }\n  }\n}\n\nunique_ptr<CostFunction> yann::SquaredHingeLoss::copy() const\n{\n  return make_unique<SquaredHingeLoss>();\n}\n\n", "meta": {"hexsha": "386709bde7caed1537c202c0a362c789ccf7ef0f", "size": 13329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/functions.cpp", "max_stars_repo_name": "lsh123/yann", "max_stars_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T10:25:07.000Z", "max_issues_repo_path": "src/core/functions.cpp", "max_issues_repo_name": "lsh123/yann", "max_issues_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/functions.cpp", "max_forks_repo_name": "lsh123/yann", "max_forks_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1026200873, "max_line_length": 141, "alphanum_fraction": 0.6557131068, "num_tokens": 3756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6324720174941726}}
{"text": "#include <iostream>\n\n#include \"KokkosCore/kokkosConfigCommon.h\"\n#include \"KokkosCore/kokkosConfig.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n#include \"../test_common.h\"\n\nusing namespace Eigen;\n\nusing Matrix5d = Matrix<double, 5, 5>;\n\ntemplate <class C>\nKOKKOS_INLINE_FUNCTION void printIt(C* m) {\n#ifdef TEST_DEBUG\n  printf(\"\\nMatrix %dx%d\\n\", (int)m->rows(), (int)m->cols());\n  for (u_int r = 0; r < m->rows(); ++r) {\n    for (u_int c = 0; c < m->cols(); ++c) {\n      printf(\"Matrix(%d,%d) = %f\\n\", r, c, (*m)(r, c));\n    }\n  }\n#endif\n}\n\nKOKKOS_INLINE_FUNCTION void eigenValues(Matrix3d* m, Eigen::SelfAdjointEigenSolver<Matrix3d>::RealVectorType* ret) {\n#if TEST_DEBUG\n  printf(\"Matrix(0,0): %f\\n\", (*m)(0, 0));\n  printf(\"Matrix(1,1): %f\\n\", (*m)(1, 1));\n  printf(\"Matrix(2,2): %f\\n\", (*m)(2, 2));\n#endif\n  SelfAdjointEigenSolver<Matrix3d> es;\n  es.computeDirect(*m);\n  (*ret) = es.eigenvalues();\n  return;\n}\n\nKOKKOS_INLINE_FUNCTION void kernel(\n    Kokkos::View<Matrix3d, KokkosExecSpace> vm,\n    Kokkos::View<Eigen::SelfAdjointEigenSolver<Matrix3d>::RealVectorType, KokkosExecSpace> vret) {\n  eigenValues(vm.data(), vret.data());\n}\n\nKOKKOS_INLINE_FUNCTION void kernelInverse3x3(Kokkos::View<Matrix3d, KokkosExecSpace> vm,\n                                             Kokkos::View<Matrix3d, KokkosExecSpace> vmret) {\n  vmret() = vm().inverse();\n}\n\nKOKKOS_INLINE_FUNCTION void kernelInverse4x4(Kokkos::View<Matrix4d, KokkosExecSpace> vm,\n                                             Kokkos::View<Matrix4d, KokkosExecSpace> vmret) {\n  vmret() = vm().inverse();\n}\n\nKOKKOS_INLINE_FUNCTION void kernelInverse5x5(Kokkos::View<Matrix5d, KokkosExecSpace> vm,\n                                             Kokkos::View<Matrix5d, KokkosExecSpace> vmret) {\n  vmret() = vm().inverse();\n}\n\ntemplate <typename M1, typename M2, typename M3>\nKOKKOS_INLINE_FUNCTION void kernelMultiply(Kokkos::View<M1, KokkosExecSpace> d_j,\n                                           Kokkos::View<M2, KokkosExecSpace> d_c,\n                                           Kokkos::View<M3, KokkosExecSpace> d_result) {\n//  Map<M3> res(result->data());\n#if TEST_DEBUG\n  printf(\"*** GPU IN ***\\n\");\n#endif\n  printIt(d_j.data());\n  printIt(d_c.data());\n  //  res.noalias() = (*J) * (*C);\n  //  printIt(&res);\n  d_result() = d_j() * d_c();\n#if TEST_DEBUG\n  printf(\"*** GPU OUT ***\\n\");\n#endif\n  return;\n}\n\ntemplate <int row1, int col1, int row2, int col2>\nvoid testMultiply() {\n  std::cout << \"TEST MULTIPLY\" << std::endl;\n  std::cout << \"Product of type \" << row1 << \"x\" << col1 << \" * \" << row2 << \"x\" << col2 << std::endl;\n\n  Kokkos::View<Matrix<double, row1, col1>, KokkosExecSpace> d_j(\"d_j\");\n  Kokkos::View<Matrix<double, row2, col2>, KokkosExecSpace> d_c(\"d_c\");\n  Kokkos::View<Matrix<double, row1, col2>, KokkosExecSpace> d_multiply_result(\"d_multiply_result\");\n\n  auto h_j = Kokkos::create_mirror_view(d_j);\n  auto h_c = Kokkos::create_mirror_view(d_c);\n  auto h_multiply_result = Kokkos::create_mirror_view(d_multiply_result);\n\n  fillMatrix(h_j());\n  fillMatrix(h_c());\n  h_multiply_result() = h_j() * h_c();\n  auto multiply_result = h_multiply_result();\n\n#if TEST_DEBUG\n  std::cout << \"Input J:\" << std::endl;\n  printIt(h_j.data());\n  std::cout << \"Input C:\" << std::endl;\n  printIt(h_c.data());\n  std::cout << \"Output:\" << std::endl;\n  printIt(&multiply_result);\n#endif\n  // GPU\n  Eigen::Matrix<double, row1, col2>* multiply_resultGPUret = new Eigen::Matrix<double, row1, col2>();\n\n  Kokkos::deep_copy(KokkosExecSpace(), d_j, h_j);\n  Kokkos::deep_copy(KokkosExecSpace(), d_c, h_c);\n  Kokkos::deep_copy(KokkosExecSpace(), d_multiply_result, h_multiply_result);\n\n  auto policy = Kokkos::RangePolicy<KokkosExecSpace>(KokkosExecSpace(), 0, 1);\n  Kokkos::parallel_for(\n      \"kernelMultiply\", policy, KOKKOS_LAMBDA(const int& i) { kernelMultiply(d_j, d_c, d_multiply_result); });\n  KokkosExecSpace().fence();\n\n  Kokkos::deep_copy(KokkosExecSpace(), h_multiply_result, d_multiply_result);\n  printIt(h_multiply_result.data());\n  assert(isEqualFuzzy(multiply_result, h_multiply_result()));\n}\n\nvoid testInverse3x3() {\n  std::cout << \"TEST INVERSE 3x3\" << std::endl;\n\n  Kokkos::View<Matrix3d, KokkosExecSpace> d_m(\"d_m\");\n  Kokkos::View<Matrix3d, KokkosExecSpace> d_mret(\"d_mret\");\n\n  auto h_m = Kokkos::create_mirror_view(d_m);\n  auto h_mret = Kokkos::create_mirror_view(d_mret);\n\n  fillMatrix(h_m());\n  h_m() += h_m().transpose().eval();\n\n  Matrix3d m_inv = h_m().inverse();\n\n#if TEST_DEBUG\n  std::cout << \"Here is the matrix m:\" << std::endl << h_m() << std::endl;\n  std::cout << \"Its inverse is:\" << std::endl << m_inv << std::endl;\n#endif\n  Kokkos::deep_copy(KokkosExecSpace(), d_m, h_m);\n\n  auto policy = Kokkos::RangePolicy<KokkosExecSpace>(KokkosExecSpace(), 0, 1);\n  Kokkos::parallel_for(\n      \"kernelInverse3x3\", policy, KOKKOS_LAMBDA(const int& i) { kernelInverse3x3(d_m, d_mret); });\n  Kokkos::deep_copy(KokkosExecSpace(), h_mret, d_mret);\n  KokkosExecSpace().fence();\n\n#if TEST_DEBUG\n  std::cout << \"Its GPU inverse is:\" << std::endl << h_mret() << std::endl;\n#endif\n  assert(isEqualFuzzy(m_inv, h_mret()));\n}\n\nvoid testInverse4x4() {\n  std::cout << \"TEST INVERSE 4x4\" << std::endl;\n\n  Kokkos::View<Matrix4d, KokkosExecSpace> d_m(\"d_m\");\n  Kokkos::View<Matrix4d, KokkosExecSpace> d_mret(\"d_mret\");\n\n  auto h_m = Kokkos::create_mirror_view(d_m);\n  auto h_mret = Kokkos::create_mirror_view(d_mret);\n\n  fillMatrix(h_m());\n  h_m() += h_m().transpose().eval();\n\n  Matrix4d m_inv = h_m().inverse();\n\n#if TEST_DEBUG\n  std::cout << \"Here is the matrix m:\" << std::endl << h_m() << std::endl;\n  std::cout << \"Its inverse is:\" << std::endl << m_inv << std::endl;\n#endif\n  Kokkos::deep_copy(KokkosExecSpace(), d_m, h_m);\n\n  auto policy = Kokkos::RangePolicy<KokkosExecSpace>(KokkosExecSpace(), 0, 1);\n  Kokkos::parallel_for(\n      \"kernelInverse4x4\", policy, KOKKOS_LAMBDA(const int& i) { kernelInverse4x4(d_m, d_mret); });\n  Kokkos::deep_copy(KokkosExecSpace(), h_mret, d_mret);\n  KokkosExecSpace().fence();\n#if TEST_DEBUG\n  std::cout << \"Its GPU inverse is:\" << std::endl << h_mret() << std::endl;\n#endif\n  assert(isEqualFuzzy(m_inv, h_mret()));\n}\n\nvoid testInverse5x5() {\n  std::cout << \"TEST INVERSE 5x5\" << std::endl;\n\n  Kokkos::View<Matrix5d, KokkosExecSpace> d_m(\"d_m\");\n  Kokkos::View<Matrix5d, KokkosExecSpace> d_mret(\"d_mret\");\n\n  auto h_m = Kokkos::create_mirror_view(d_m);\n  auto h_mret = Kokkos::create_mirror_view(d_mret);\n\n  fillMatrix(h_m());\n  h_m() += h_m().transpose().eval();\n\n  Matrix5d m_inv = h_m().inverse();\n\n#if TEST_DEBUG\n  std::cout << \"Here is the matrix m:\" << std::endl << h_m() << std::endl;\n  std::cout << \"Its inverse is:\" << std::endl << m_inv << std::endl;\n#endif\n  Kokkos::deep_copy(KokkosExecSpace(), d_m, h_m);\n\n  auto policy = Kokkos::RangePolicy<KokkosExecSpace>(KokkosExecSpace(), 0, 1);\n  Kokkos::parallel_for(\n      \"kernelInverse5x5\", policy, KOKKOS_LAMBDA(const int& i) { kernelInverse5x5(d_m, d_mret); });\n  Kokkos::deep_copy(KokkosExecSpace(), h_mret, d_mret);\n  KokkosExecSpace().fence();\n#if TEST_DEBUG\n  std::cout << \"Its GPU inverse is:\" << std::endl << h_mret() << std::endl;\n#endif\n  assert(isEqualFuzzy(m_inv, h_mret()));\n}\n\nvoid testEigenvalues() {\n  std::cout << \"TEST EIGENVALUES\" << std::endl;\n\n  Kokkos::View<Matrix3d, KokkosExecSpace> d_m(\"d_m\");\n  Kokkos::View<Eigen::SelfAdjointEigenSolver<Matrix3d>::RealVectorType, KokkosExecSpace> d_ret(\"d_ret\");\n\n  auto h_m = Kokkos::create_mirror_view(d_m);\n  auto h_ret = Kokkos::create_mirror_view(d_ret);\n\n  fillMatrix(h_m());\n  h_m() += h_m().transpose().eval();\n\n  Eigen::SelfAdjointEigenSolver<Matrix3d>::RealVectorType* ret =\n      new Eigen::SelfAdjointEigenSolver<Matrix3d>::RealVectorType;\n  eigenValues(h_m.data(), ret);\n#if TEST_DEBUG\n  std::cout << \"Generated Matrix M 3x3:\\n\" << h_m() << std::endl;\n  std::cout << \"The eigenvalues of M are:\" << std::endl << (*ret) << std::endl;\n  std::cout << \"*************************\\n\\n\" << std::endl;\n#endif\n  Kokkos::deep_copy(KokkosExecSpace(), d_m, h_m);\n\n  auto policy = Kokkos::RangePolicy<KokkosExecSpace>(KokkosExecSpace(), 0, 1);\n  Kokkos::parallel_for(\n      \"kernel\", policy, KOKKOS_LAMBDA(const int& i) { kernel(d_m, d_ret); });\n  Kokkos::deep_copy(KokkosExecSpace(), h_m, d_m);\n  Kokkos::deep_copy(KokkosExecSpace(), h_ret, d_ret);\n  KokkosExecSpace().fence();\n\n#if TEST_DEBUG\n  std::cout << \"GPU Generated Matrix M 3x3:\\n\" << (h_m()) << std::endl;\n  std::cout << \"GPU The eigenvalues of M are:\" << std::endl << (h_ret()) << std::endl;\n  std::cout << \"*************************\\n\\n\" << std::endl;\n#endif\n  assert(isEqualFuzzy(*ret, h_ret()));\n}\n\nint main(int argc, char* argv[]) {\n  kokkos_common::InitializeScopeGuard kokkosGuard({KokkosBackend<KokkosExecSpace>::value});\n  testEigenvalues();\n  testInverse3x3();\n  testInverse4x4();\n  // disable testInverse5x5 since it will result in runtime error: what():  cudaMemcpyAsync(dst, src, n, cudaMemcpyDefault, instance.cuda_stream()) error( cudaErrorLaunchFailure): unspecified launch failure\n  // testInverse5x5();\n\n  testMultiply<1, 2, 2, 1>();\n  testMultiply<1, 2, 2, 2>();\n  testMultiply<1, 2, 2, 3>();\n  testMultiply<1, 2, 2, 4>();\n  testMultiply<1, 2, 2, 5>();\n  testMultiply<2, 1, 1, 2>();\n  testMultiply<2, 1, 1, 3>();\n  testMultiply<2, 1, 1, 4>();\n  testMultiply<2, 1, 1, 5>();\n  testMultiply<2, 2, 2, 2>();\n  testMultiply<2, 3, 3, 1>();\n  testMultiply<2, 3, 3, 2>();\n  testMultiply<2, 3, 3, 4>();\n  testMultiply<2, 3, 3, 5>();\n  testMultiply<3, 2, 2, 3>();\n  testMultiply<2, 3, 3, 3>();  // DOES NOT COMPILE W/O PATCHING EIGEN\n  testMultiply<3, 3, 3, 3>();\n  testMultiply<8, 8, 8, 8>();\n  testMultiply<3, 4, 4, 3>();\n  testMultiply<2, 4, 4, 2>();\n  testMultiply<3, 4, 4, 2>();  // DOES NOT COMPILE W/O PATCHING EIGEN\n\n  return 0;\n}\n", "meta": {"hexsha": "ca8625fb4e5358e0525cbe1da86bb4a5edc055bf", "size": 9734, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/kokkos/test/kokkos/testEigenGPUNoFit.cc", "max_stars_repo_name": "lauracappelli/pixeltrack-standalone", "max_stars_repo_head_hexsha": "1a8286f1712e8693796503328e300d52c0c73e61", "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/kokkos/test/kokkos/testEigenGPUNoFit.cc", "max_issues_repo_name": "lauracappelli/pixeltrack-standalone", "max_issues_repo_head_hexsha": "1a8286f1712e8693796503328e300d52c0c73e61", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kokkos/test/kokkos/testEigenGPUNoFit.cc", "max_forks_repo_name": "lauracappelli/pixeltrack-standalone", "max_forks_repo_head_hexsha": "1a8286f1712e8693796503328e300d52c0c73e61", "max_forks_repo_licenses": ["Apache-2.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.1543859649, "max_line_length": 206, "alphanum_fraction": 0.6510170536, "num_tokens": 3187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7154239957834734, "lm_q1q2_score": 0.6324629197477543}}
{"text": "#include <Eigen/Dense>\r\n#include <string.h>\r\n#include <fstream>\r\n#include <iostream>\r\nusing namespace std;\r\n\r\n#define MODEL_PATH_DISTANCE 100\r\n#define POLYFIT_DEGREE 4\r\n\r\nEigen::Matrix<float, MODEL_PATH_DISTANCE, POLYFIT_DEGREE> vander;\r\n\r\nvoid poly_fit(float *in_pts, float *in_stds, float *out) {\r\n  // References to inputs\r\n  Eigen::Map<Eigen::Matrix<float, MODEL_PATH_DISTANCE, 1> > pts(in_pts, MODEL_PATH_DISTANCE);\r\n  Eigen::Map<Eigen::Matrix<float, MODEL_PATH_DISTANCE, 1> > std(in_stds, MODEL_PATH_DISTANCE);\r\n  Eigen::Map<Eigen::Matrix<float, POLYFIT_DEGREE, 1> > p(out, POLYFIT_DEGREE);\r\n\r\n  // Build Least Squares equations\r\n  Eigen::Matrix<float, MODEL_PATH_DISTANCE, POLYFIT_DEGREE> lhs = vander.array().colwise() / std.array();\r\n  Eigen::Matrix<float, MODEL_PATH_DISTANCE, 1> rhs = pts.array() / std.array();\r\n\r\n  // Improve numerical stability\r\n  Eigen::Matrix<float, POLYFIT_DEGREE, 1> scale = 1. / (lhs.array()*lhs.array()).sqrt().colwise().sum();\r\n  lhs = lhs * scale.asDiagonal();\r\n\r\n  // Solve inplace\r\n  Eigen::ColPivHouseholderQR<Eigen::Ref<Eigen::MatrixXf> > qr(lhs);\r\n  p = qr.solve(rhs);\r\n\r\n  // Apply scale to output\r\n  p = p.transpose() * scale.asDiagonal();\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{\r\n\tfor(int i = 0; i < MODEL_PATH_DISTANCE; i++) {\r\n    for(int j = 0; j < POLYFIT_DEGREE; j++) {\r\n      vander(i, j) = pow(i, POLYFIT_DEGREE-j-1);\r\n    }\r\n  }\r\n  float* points = new float[MODEL_PATH_DISTANCE]();\r\n  float* stds = new float[MODEL_PATH_DISTANCE]();\r\n  float* poly = new float[POLYFIT_DEGREE]();\r\n  string filename = argv[1];\r\n  string name = filename + \"_pts\";\r\n  fstream file(name.c_str());\r\n  float tp;\r\n  int idx=0;\r\n  while(file >> tp)\r\n  {\r\n    // cout << tp << \" \";\r\n    points[idx] = tp;\r\n    idx++;\r\n  }\r\n  cout << endl;\r\n  file.close();\r\n  name = filename+\"_stds\";\r\n  fstream file2(name.c_str());\r\n  idx=0;\r\n  while(file2 >> tp)\r\n  {\r\n    // cout << tp << \" \";\r\n    stds[idx] = tp;\r\n    idx++;\r\n  }\r\n\r\n  poly_fit(points, stds, poly);\r\n  cout << poly[0];\r\n  for (int i=1;i<POLYFIT_DEGREE;i++)\r\n  {\r\n    cout << \" \" << poly[i]; \r\n  }\r\n  cout << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "04efe91854c3a4dbf7637d640a18346224c0a12c", "size": 2112, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/qr.cpp", "max_stars_repo_name": "CodingSheep1229/openpilot-lane-detection", "max_stars_repo_head_hexsha": "4a0065b32b293f7fe9f409c177a830e1bf55e9b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T02:40:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-05T04:52:49.000Z", "max_issues_repo_path": "src/utils/qr.cpp", "max_issues_repo_name": "CodingSheep1229/openpilot-lane-detection", "max_issues_repo_head_hexsha": "4a0065b32b293f7fe9f409c177a830e1bf55e9b2", "max_issues_repo_licenses": ["MIT"], "max_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/qr.cpp", "max_forks_repo_name": "CodingSheep1229/openpilot-lane-detection", "max_forks_repo_head_hexsha": "4a0065b32b293f7fe9f409c177a830e1bf55e9b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-10-30T00:21:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T07:16:34.000Z", "avg_line_length": 28.16, "max_line_length": 106, "alphanum_fraction": 0.6226325758, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6324629100123645}}
{"text": "/*\n * Author: Mario L\u00fcder\n * Date: Nov. 2018\n */\n\n#ifndef MOTIONUKF_HPP\n#define MOTIONUKF_HPP\n\n#include \"Ukf.hpp\"\n#include \"tools.h\"\n\n#include <Eigen/Dense>\n#include <sstream>\n\nclass ProcessModel\n{\npublic:\n   struct MotionParams\n   {\n      double p_x;\n      double p_y;\n      double v;\n      double yaw;\n      double yaw_dot;\n      double std_a;\n      double std_yaw_dot_dot;\n   };\n\n   static inline void normalize(const long colIdx, Eigen::MatrixXd &XSigmaPointsDiff)\n   {\n      double & yaw = XSigmaPointsDiff.col(colIdx)(3);\n\n      // normalize phi to -/+ pi\n      Tools::normalizeAngle(yaw);\n   }\n\n   static void predictSigmaPoints(const Eigen::MatrixXd & XSigmaPoints, const double d_t_s, Eigen::MatrixXd & XSigmaPointsPred);\n   static inline void processModel(const MotionParams & x, const double d_t_s, MotionParams & x_pred);\n\n   //set state dimension\n   static constexpr long m_n_x = 5;\n\n   //set augumented state dimension\n   static constexpr long m_n_x_aug = 7;\n\n   // constant 2 * PI\n   static constexpr double TWO_PI = 2 * M_PI;\n\n   static constexpr long m_nSigmaPoints = 1 + 2 * m_n_x_aug;\n\n   // Process noise standard deviation longitudinal acceleration in m/s^2\n   // static constexpr double m_std_a = 0.2;\n   static constexpr double m_std_a = 1.5;\n\n   // Process noise standard deviation yaw acceleration in rad/s^2\n   // static constexpr double m_std_yawdd = 0.2;\n   static constexpr double m_std_yawdd = 1;\n};\n\n\nclass MotionUkf : public Ukf<ProcessModel>\n{\npublic:\n   MotionUkf()\n      : Ukf<ProcessModel>()\n   {}\n\n   virtual ~MotionUkf();\n\n   struct Measurement\n   {\n      Measurement(int32_t dim) : value(dim) {}\n      Eigen::VectorXd value;\n   };\n\n\n   struct RadarMeasurement : public Measurement\n   {\n      RadarMeasurement() : Measurement(3) {}\n      RadarMeasurement(std::istringstream & iss)  : Measurement(3)\n      {\n         double rho;\n         double phi;\n         double rho_dot;\n         iss >> rho;\n         iss >> phi;\n         iss >> rho_dot;\n\n         value << rho, phi, rho_dot;\n      }\n\n      RadarMeasurement & operator=(std::istringstream & iss)\n      {\n         double rho;\n         double phi;\n         double rho_dot;\n         iss >> rho;\n         iss >> phi;\n         iss >> rho_dot;\n\n         value << rho, phi, rho_dot;\n         return  *this;\n      }\n\n      double & rho() {return value(0);}\n      double & phi() {return value(1);}\n      double & rho_dot() {return value(2);}\n\n      struct Definition\n      {\n         double rho;\n         double phi;\n         double rho_dot;\n      };\n\n      static Definition * cast(void * data)\n      {\n         return reinterpret_cast<Definition*>(data);\n      }\n   };\n\n   struct RadarMeasurementModel\n   {\n      using MEASUREMENT_T = RadarMeasurement;\n\n      RadarMeasurementModel();\n\n      static inline void normalize(const long colIdx, Eigen::MatrixXd &ZSigmaPointsDiff)\n      {\n         //double & phi = reinterpret_cast<RadarMeasurement*>(ZSigmaPointsDiff.col(colIdx).data())->phi;\n         double & phi = RadarMeasurement::cast(ZSigmaPointsDiff.col(colIdx).data())->phi;\n\n         // normalize phi to -/+ pi\n         Tools::normalizeAngle(phi);\n      }\n\n      static inline void normalize(Eigen::MatrixXd &matrix)\n      {\n         const int cols = matrix.cols();\n\n         for (int colIdx = 0; colIdx < cols; ++colIdx)\n         {\n            normalize(colIdx, matrix);\n         }\n      }\n\n      static inline void normalize(Eigen::VectorXd &vector)\n      {\n         double & phi = RadarMeasurement::cast(vector.data())->phi;\n\n         // normalize phi to -/+ pi\n         Tools::normalizeAngle(phi);\n      }\n\n\n      void predictCovar(const Ukf<ProcessModel> & ukf, const Eigen::MatrixXd & XSigmaPoints, const Eigen::VectorXd & x_pred, Eigen::MatrixXd & P_pred) const;\n      void predictMeasurement(const Eigen::MatrixXd & XSigmaPointPred, Eigen::MatrixXd & ZSigmaPointsRadarPred) const;\n\n      static constexpr long nRadarValues = 3;\n\n      //radar measurement noise standard deviation radius in m\n      const double m_std_radr = 0.3;\n\n      //radar measurement noise standard deviation angle in rad\n      const double m_std_radphi = 0.03;\n\n      //radar measurement noise standard deviation radius change in m/s\n      const double m_std_radrd = 0.3;\n\n      MEASUREMENT_T measurement;\n\n      // NIS\n      double m_nis = 0.0;\n\n   private:\n      Eigen::MatrixXd m_R;\n   };\n\n   struct LaserMeasurement : public Measurement\n   {\n      LaserMeasurement() : Measurement(2) {}\n      LaserMeasurement(std::istringstream & iss) : Measurement(2)\n      {\n         double px;\n         double py;\n         iss >> px;\n         iss >> py;\n         value << px , py;\n      }\n\n      LaserMeasurement & operator=(std::istringstream & iss)\n      {\n         double px;\n         double py;\n         iss >> px;\n         iss >> py;\n         value << px, py;\n         return *this;\n      }\n\n      double & px() {return value(0);}\n      double & py() {return value(1);}\n\n      struct Definition\n      {\n         double px;\n         double py;\n      };\n\n      static Definition * cast(void * data)\n      {\n         return reinterpret_cast<Definition*>(data);\n      }\n   };\n\n   struct LaserMeasurementModel\n   {\n      using MEASUREMENT_T = LaserMeasurement;\n\n      LaserMeasurementModel();\n\n      static inline void normalize(const long colIdx, Eigen::MatrixXd &ZSigmaPointsDiff)\n      {\n         (void)colIdx;\n         (void)ZSigmaPointsDiff;\n         // nothing to normalize\n      }\n\n      static inline void normalize(Eigen::MatrixXd &matrix)\n      {\n         (void)matrix;\n      }\n\n      static inline void normalize(Eigen::VectorXd &vector)\n      {\n         (void)vector;\n      }\n\n      void predictCovar(const Ukf<ProcessModel> & ukf, const Eigen::MatrixXd & XSigmaPoints, const Eigen::VectorXd & x_pred, Eigen::MatrixXd & P_pred) const;\n      void predictMeasurement(const Eigen::MatrixXd & XSigmaPointPred, Eigen::MatrixXd & ZSigmaPointsLaserPred) const;\n\n      // Process noise standard deviation longitudinal acceleration in m/s^2\n      double m_std_a = 30;\n\n      //laser measurement noise standard deviation (position) in m\n      const double m_std_laser_pos = 0.15;\n\n      static constexpr long nLaserValues = 2;\n\n      MEASUREMENT_T measurement;\n\n      // NIS\n      double m_nis = 0.0;\n   private:\n\n      // Laser Measurement Covariance Matrix\n      Eigen::MatrixXd m_L;\n   };\n\n   template<typename MEASUREMENTMODEL_T>\n   void processMeasurement(MEASUREMENTMODEL_T & measurementModel, int64_t timestamp_us)\n   {\n      Ukf<ProcessModel>::processMeasurement<typename MEASUREMENTMODEL_T::MEASUREMENT_T, MEASUREMENTMODEL_T>(measurementModel.measurement, measurementModel, timestamp_us);\n   }\n\n   void init(const LaserMeasurementModel & laserMeasurementModel, int64_t timestamp_us)\n   {\n      Ukf<ProcessModel>::setNewTime(timestamp_us);\n      m_x.setZero(ProcessModel::m_n_x);\n\n      // set initial x pos\n      m_x(0) = laserMeasurementModel.measurement.value(0);\n\n      // set initial y pos\n      m_x(1) = laserMeasurementModel.measurement.value(1);\n\n      // initialize process noise\n      m_std.setZero(2);\n      m_std(0) = ProcessModel::m_std_a;\n      m_std(1) = ProcessModel::m_std_yawdd;\n   }\n\n   RadarMeasurementModel radarMeasurementModel;\n   LaserMeasurementModel laserMeasurementModel;\n};\n\n#endif // MOTIONUKF_HPP\n", "meta": {"hexsha": "c9949f1f3fbc216497c61e7a661ca08ca6878c9d", "size": 7297, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/MotionUkf.hpp", "max_stars_repo_name": "monsieurmona/CarND-Unscented-Kalman-Filter-Project", "max_stars_repo_head_hexsha": "6ac3f2248e03fb363292b90f62a03dc453ac73cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-18T12:23:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-18T12:23:59.000Z", "max_issues_repo_path": "src/MotionUkf.hpp", "max_issues_repo_name": "monsieurmona/CarND-Unscented-Kalman-Filter-Project", "max_issues_repo_head_hexsha": "6ac3f2248e03fb363292b90f62a03dc453ac73cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MotionUkf.hpp", "max_forks_repo_name": "monsieurmona/CarND-Unscented-Kalman-Filter-Project", "max_forks_repo_head_hexsha": "6ac3f2248e03fb363292b90f62a03dc453ac73cd", "max_forks_repo_licenses": ["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.3368055556, "max_line_length": 170, "alphanum_fraction": 0.6269699877, "num_tokens": 1749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6323386868427944}}
{"text": "#include <triumf/nmr/dipole_dipole.hpp>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n\ndouble dipole_dipole(const double *x, const double *par) {\n  double omega_d = std::abs(par[2] * par[3] * par[0] * par[0]);\n  double factor = par[1] * (3.0 / 10.0);\n  double normalization = factor / omega_d;\n  return normalization * triumf::nmr::dipole_dipole::slr_rate<double>(\n                             *x, par[0], par[1], par[2], par[3]);\n}\n\ndouble generic(const double *x, const double *par) {\n  double B_d = par[0];\n  double nu_c = par[1];\n  double gamma_I = par[2];\n  double omega = gamma_I * x[0];\n  double omega_d = gamma_I * gamma_I * B_d * B_d;\n  return triumf::nmr::dipole_dipole::j<double>(omega, nu_c) * par[1];\n}\n\nvoid plot_dipole_dipole() {\n\n  const double B_min = 2e-5;\n  const double B_max = 2e-1;\n\n  const auto n_points = 200;\n\n  const double B_d = 1e-5;\n  const double nu_c = 1.0 / 23.8e-6;\n  const double gamma_8Li = boost::math::constants::two_pi<double>() * 6.30221e6;\n  const double gamma_93Nb =\n      boost::math::constants::two_pi<double>() * 10.30221e6;\n\n  TCanvas *canvas = new TCanvas();\n\n  TF1 *f_dipole = new TF1(\"f_dipole\", dipole_dipole, B_min, B_max, 4);\n  f_dipole->SetTitle(\"\");\n  f_dipole->SetNpx(n_points);\n  f_dipole->SetLineColor(kRed);\n  f_dipole->SetParameter(0, B_d);\n  f_dipole->SetParameter(1, nu_c);\n  f_dipole->SetParameter(2, gamma_8Li);\n  f_dipole->SetParameter(3, gamma_93Nb);\n\n  f_dipole->GetHistogram()->GetXaxis()->SetTitle(\"B_{0} (T)\");\n  f_dipole->GetHistogram()->GetYaxis()->SetTitle(\n      \"[1/T_{1}(B_{0})] / [1/T_{1}(0)]\");\n\n  f_dipole->Draw();\n\n  TF1 *f_generic = new TF1(\"f_generic\", generic, B_min, B_max, 3);\n  f_generic->SetTitle(\"\");\n  f_generic->SetLineColor(kBlue);\n  f_generic->SetNpx(n_points);\n  f_generic->SetParameter(0, B_d);\n  f_generic->SetParameter(1, nu_c);\n  f_generic->SetParameter(2, gamma_8Li);\n\n  f_generic->GetHistogram()->GetXaxis()->SetTitle(\"B_{0} (T)\");\n  f_generic->GetHistogram()->GetYaxis()->SetTitle(\n      \"[1/T_{1}(B_{0})] / [1/T_{1}(0)]\");\n\n  f_generic->Draw(\"same\");\n\n  auto legend = new TLegend(0.15, 0.15, 0.60, 0.45);\n  // option \"C\" allows to center the header\n  legend->SetHeader(\"Models for dipole-dipole SLR 1/T_{1}\", \"C\");\n  legend->AddEntry(f_dipole, \"Eq. (8.21) in Mehring (1983)\", \"l\");\n  legend->AddEntry(f_generic, \"Generic BPP expression\", \"l\");\n  legend->Draw();\n\n  // logarithmic scale\n  gPad->SetLogx();\n  gPad->SetLogy();\n\n  // tick marks on all sides of the plot\n  gPad->SetTickx();\n  gPad->SetTicky();\n\n  // grid lines\n  gPad->SetGridx();\n  gPad->SetGridy();\n\n  canvas->Print(\"dipole-dipole.pdf\", \"EmbedFonts\");\n}\n", "meta": {"hexsha": "d221a8c58d529b90bf365b2a66b9753caf9fc305", "size": 2636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/plot_dipole_dipole.cpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/plot_dipole_dipole.cpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/plot_dipole_dipole.cpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6179775281, "max_line_length": 80, "alphanum_fraction": 0.6490895296, "num_tokens": 917, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6323386824051216}}
{"text": "#include \"geometrycentral/numerical/linear_solvers.h\"\n#include \"geometrycentral/surface/manifold_surface_mesh.h\"\n#include \"geometrycentral/surface/meshio.h\"\n#include \"geometrycentral/surface/simple_polygon_mesh.h\"\n#include \"geometrycentral/surface/vertex_position_geometry.h\"\n\n#include <emscripten/bind.h>\n#include <emscripten/val.h>\n\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n\n#include \"geometrycentral/surface/manifold_surface_mesh.h\"\n#include \"geometrycentral/surface/simple_polygon_mesh.h\"\n\n#include \"interpolate_vectors.h\"\n\nusing namespace emscripten;\nusing namespace geometrycentral;\nusing namespace geometrycentral::surface;\n\nstruct GeoMesh {\n    std::unique_ptr<ManifoldSurfaceMesh> mesh;\n    std::unique_ptr<VertexPositionGeometry> geom;\n};\n\nstd::vector<Vector3> toList(ManifoldSurfaceMesh& mesh,\n                            const VertexData<Vector3>& data) {\n    std::vector<Vector3> vectorList;\n    for (Vertex v : mesh.vertices()) {\n        vectorList.push_back(data[v]);\n    }\n    return vectorList;\n}\n\nVertexData<Vector3> toData(ManifoldSurfaceMesh& mesh,\n                           const std::vector<Vector3>& list) {\n    VertexData<Vector3> data(mesh);\n    for (size_t iV = 0; iV < mesh.nVertices(); iV++) {\n        data[iV] = list[iV];\n    }\n    return data;\n}\n\nstd::vector<Vector3> generateSmoothBoundaryField(GeoMesh& geo) {\n    VertexData<Vector3> bField =\n        generateSmoothBoundaryVectorField(*geo.mesh, *geo.geom);\n    return toList(*geo.mesh, bField);\n}\n\nstd::vector<Vector3> generateWavyBoundaryField(GeoMesh& geo, size_t frequency) {\n    VertexData<Vector3> bField =\n        generateWavyBoundaryVectorField(*geo.mesh, *geo.geom, frequency);\n    return toList(*geo.mesh, bField);\n}\n\nstd::vector<Vector3>\ninterpolateHarmonicFunction(GeoMesh& geo,\n                            const std::vector<Vector3>& boundaryData) {\n    return toList(*geo.mesh,\n                  interpolateByHarmonicFunction(\n                      *geo.mesh, *geo.geom, toData(*geo.mesh, boundaryData)));\n}\n\nstd::vector<Vector3>\ninterpolateConnectionLaplacian(GeoMesh& geo,\n                               const std::vector<Vector3>& boundaryData,\n                               bool estimateNormalDirection) {\n    return toList(*geo.mesh,\n                  interpolateByConnectionLaplacian(\n                      *geo.mesh, *geo.geom, toData(*geo.mesh, boundaryData),\n                      estimateNormalDirection));\n}\n\nstd::vector<Vector3>\ninterpolateStereographicProjection(GeoMesh& geo,\n                                   const std::vector<Vector3>& boundaryData) {\n    return toList(*geo.mesh,\n                  interpolateByStereographicProjection(\n                      *geo.mesh, *geo.geom, toData(*geo.mesh, boundaryData)));\n}\n\nstd::vector<Vector3>\ninterpolateHarmonicMapToSphere(GeoMesh& geo,\n                               const std::vector<Vector3>& boundaryData) {\n    return toList(*geo.mesh,\n                  interpolateByHarmonicMapToSphere(\n                      *geo.mesh, *geo.geom, toData(*geo.mesh, boundaryData)));\n}\n\n// Stolen from Ricky Reusser https://observablehq.com/d/d0df0c04ce5c94FCC\ntemplate <typename T>\nvoid copyToVector(const val& typedArray, std::vector<T>& vec) {\n    unsigned int length = typedArray[\"length\"].as<unsigned int>();\n    val memory          = val::module_property(\"buffer\");\n    vec.reserve(length);\n    val memoryView = typedArray[\"constructor\"].new_(\n        memory, reinterpret_cast<uintptr_t>(vec.data()), length);\n    memoryView.call<void>(\"set\", typedArray);\n}\n\n// Mostly stolen from Ricky Reusser https://observablehq.com/d/d0df0c04ce5c94fc\nEMSCRIPTEN_BINDINGS(my_module) {\n    value_array<Vector3>(\"Vector3\")\n        .element(&Vector3::x)\n        .element(&Vector3::y)\n        .element(&Vector3::z);\n    value_array<Vector2>(\"Vector2\").element(&Vector2::x).element(&Vector2::y);\n\n    register_vector<Vector3>(\"VectorVector3\");\n    register_vector<size_t>(\"VectorSizeT\");\n    register_vector<std::vector<size_t>>(\"VectorVectorSizeT\");\n\n    class_<GeoMesh>(\"GCMesh\")\n        .function(\"polygons\", optional_override([](GeoMesh& self) {\n                      return self.mesh->getFaceVertexList();\n                  }))\n        .function(\"vertexCoordinates\",\n                  optional_override([](const GeoMesh& self) {\n                      std::vector<Vector3> vCoords;\n                      for (Vertex v : self.mesh->vertices())\n                          vCoords.push_back(self.geom->inputVertexPositions[v]);\n                      return vCoords;\n                  }));\n\n    function(\"readMesh\",\n             optional_override([](std::string str, std::string type = \"\") {\n                 std::stringstream in;\n                 in << str;\n\n                 GeoMesh gMesh;\n                 std::tie(gMesh.mesh, gMesh.geom) =\n                     readManifoldSurfaceMesh(in, type);\n                 return gMesh;\n             }));\n\n    function(\"generateSmoothBoundaryField\", &generateSmoothBoundaryField);\n    function(\"generateWavyBoundaryField\", &generateWavyBoundaryField);\n\n    function(\"interpolateHarmonicFunction\", &interpolateHarmonicFunction);\n    function(\"interpolateConnectionLaplacian\", &interpolateConnectionLaplacian);\n    function(\"interpolateStereographicProjection\",\n             &interpolateStereographicProjection);\n    function(\"interpolateHarmonicMapToSphere\", &interpolateHarmonicMapToSphere);\n}\n", "meta": {"hexsha": "655b45393809d19f532a4ee6c38a1029c867ec5d", "size": 5386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/embind.cpp", "max_stars_repo_name": "MarkGillespie/VectorInterpolation", "max_stars_repo_head_hexsha": "4825e9c0956937fe5b2775747c5f3f6e9441e1d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/embind.cpp", "max_issues_repo_name": "MarkGillespie/VectorInterpolation", "max_issues_repo_head_hexsha": "4825e9c0956937fe5b2775747c5f3f6e9441e1d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/embind.cpp", "max_forks_repo_name": "MarkGillespie/VectorInterpolation", "max_forks_repo_head_hexsha": "4825e9c0956937fe5b2775747c5f3f6e9441e1d7", "max_forks_repo_licenses": ["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.8904109589, "max_line_length": 80, "alphanum_fraction": 0.647047902, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6323318743585199}}
{"text": "#pragma once\n\n#include \"../linesegment.hh\"\n#include \"../../../util/Maybe.hh\"\n\n#include <Eigen/Core>\n\nnamespace bold\n{\n  template<typename T>\n  class LineSegment2 : public LineSegment<T, 2>\n  {\n  public:\n    typedef Eigen::Matrix<T,2,1> Point;\n\n    LineSegment2(Point const& p1, Point const& p2)\n    : LineSegment<T, 2>::LineSegment(p1, p2)\n    {}\n\n    LineSegment2(T x1, T y1, T x2, T y2)\n    : LineSegment<T, 2>::LineSegment(Point(x1, y1), Point(x2, y2))\n    {}\n\n    using LineSegment<T, 2>::LineSegment;\n    using LineSegment<T, 2>::operator=;\n\n    Maybe<Point> tryIntersect(LineSegment2<T> const& other) const\n    {\n      double t;\n      double u;\n      return tryIntersect(other, t, u);\n    }\n\n    /**\n    * Attempt to intersect two line segments.\n    * Note that even if the line segments do not intersect, the t and u values will be set.\n    * @param other the line to attempt intersection of this line with\n    * @param t (output) the distance along this line at which intersection would occur, or NaN if lines are collinear/parallel\n    * @param u (output) the distance along the other line at which intersection would occur, or NaN if lines are collinear/parallel\n    * @return The point of intersection if within the line segments, or empty.\n    */\n    Maybe<Point> tryIntersect(LineSegment2<T> const& other, double& t, double& u) const\n    {\n      // http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect\n\n      Eigen::Vector2d pos1 = this->p1().template cast<double>();    // p\n      Eigen::Vector2d pos2 = other.p1().template cast<double>();    // q\n      Eigen::Vector2d dir1 = this->delta().template cast<double>(); // r\n      Eigen::Vector2d dir2 = other.delta().template cast<double>(); // s\n\n      // t = (q \u2212 p) \u00d7 s / (r \u00d7 s)\n      // u = (q \u2212 p) \u00d7 r / (r \u00d7 s)\n\n      double denom = fake2dCross(dir1, dir2);\n\n      if (denom == 0)\n      {\n        // lines are collinear or parallel\n        t = std::numeric_limits<double>::quiet_NaN();\n        u = std::numeric_limits<double>::quiet_NaN();\n        return Maybe<Point>::empty();\n      }\n\n      double t_numer = fake2dCross(pos2 - pos1, dir2);\n      double u_numer = fake2dCross(pos2 - pos1, dir1);\n\n      t = t_numer / denom;\n      u = u_numer / denom;\n\n      if (t < 0 || t > 1 || u < 0 || u > 1)\n      {\n        // line segments do not intersect within their ranges\n        return Maybe<Point>::empty();\n      }\n\n      Eigen::Vector2d intersectionPoint = pos1 + dir1 * t;\n\n      // If we are using integers, be sure to round the result before casting\n      if (std::is_same<T,int>())\n      {\n        Eigen::Vector2d rounded = intersectionPoint.unaryExpr([](double v) { return round(v); });\n        return Maybe<Point>(rounded.cast<T>());\n      }\n\n      return Maybe<Point>(intersectionPoint.cast<T>());\n    }\n\n  private:\n    /**\n     * Returns the magnitude of the vector that would result from a regular\n     * 3D cross product of the input vectors, taking their Z values implicitly\n     * as 0 (i.e. treating the 2D space as a plane in the 3D space)\n     */\n    inline static double fake2dCross(Eigen::Vector2d const& a, Eigen::Vector2d const& b)\n    {\n      return a.x()*b.y() - a.y()*b.x();\n    }\n  };\n\n  typedef LineSegment2<double> LineSegment2d;\n  typedef LineSegment2<float> LineSegment2f;\n}\n", "meta": {"hexsha": "5b928cfe51a2aa9815e290e1c63cc6fba174a0d2", "size": 3310, "ext": "hh", "lang": "C++", "max_stars_repo_path": "geometry/LineSegment/LineSegment2/linesegment2.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geometry/LineSegment/LineSegment2/linesegment2.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/LineSegment/LineSegment2/linesegment2.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1359223301, "max_line_length": 131, "alphanum_fraction": 0.6223564955, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6323318712413758}}
{"text": "#define BOOST_TEST_MODULE TestQR\n#include <boost/test/unit_test.hpp>\n\n#include <vector>\n#include <random>\n#include <boost/multi_array.hpp>\n\n#include <amgcl/detail/qr.hpp>\n#include <amgcl/value_type/interface.hpp>\n#include <amgcl/value_type/complex.hpp>\n#include <amgcl/value_type/static_matrix.hpp>\n\ntemplate <class T>\nstruct make_random {\n    static T get() {\n        static std::mt19937 gen;\n        static std::uniform_real_distribution<T> rnd;\n\n        return rnd(gen);\n    }\n};\n\ntemplate <class T>\nT random() {\n    return make_random<T>::get();\n}\n\ntemplate <class T>\nstruct make_random< std::complex<T> > {\n    static std::complex<T> get() {\n        return std::complex<T>( random<T>(), random<T>() );\n    }\n};\n\ntemplate <class T, int N, int M>\nstruct make_random< amgcl::static_matrix<T,N,M> > {\n    typedef amgcl::static_matrix<T,N,M> matrix;\n    static matrix get() {\n        matrix A = amgcl::math::zero<matrix>();\n        for(int i = 0; i < N; ++i)\n            for(int j = 0; j < M; ++j)\n                A(i,j) = make_random<T>::get();\n        return A;\n    }\n};\n\ntemplate <class value_type, amgcl::detail::storage_order order>\nvoid qr_factorize(int n, int m) {\n    std::cout << \"factorize \" << n << \" \" << m << std::endl;\n    typedef typename std::conditional<order == amgcl::detail::row_major,\n            boost::c_storage_order,\n            boost::fortran_storage_order\n            >::type ma_storage_order;\n\n    boost::multi_array<value_type, 2> A0(boost::extents[n][m], ma_storage_order());\n\n    for(int i = 0; i < n; ++i)\n        for(int j = 0; j < m; ++j)\n            A0[i][j] = random<value_type>();\n\n    boost::multi_array<value_type, 2> A = A0;\n\n    amgcl::detail::QR<value_type> qr;\n\n    qr.factorize(n, m, A.data(), order);\n\n    // Check that A = QR\n    int p = std::min(n, m);\n    for(int i = 0; i < n; ++i) {\n        for(int j = 0; j < m; ++j) {\n            value_type sum = amgcl::math::zero<value_type>();\n\n            for(int k = 0; k < p; ++k)\n                sum += qr.Q(i,k) * qr.R(k,j);\n\n            sum -= A0[i][j];\n\n            BOOST_CHECK_SMALL(amgcl::math::norm(sum), 1e-8);\n        }\n    }\n}\n\ntemplate <class value_type, amgcl::detail::storage_order order>\nvoid qr_solve(int n, int m) {\n    std::cout << \"solve \" << n << \" \" << m << std::endl;\n    typedef typename std::conditional<order == amgcl::detail::row_major,\n            boost::c_storage_order,\n            boost::fortran_storage_order\n            >::type ma_storage_order;\n\n    typedef typename amgcl::math::rhs_of<value_type>::type rhs_type;\n\n    boost::multi_array<value_type, 2> A0(boost::extents[n][m], ma_storage_order());\n\n    for(int i = 0; i < n; ++i)\n        for(int j = 0; j < m; ++j)\n            A0[i][j] = random<value_type>();\n\n    boost::multi_array<value_type, 2> A = A0;\n\n    amgcl::detail::QR<value_type> qr;\n\n    std::vector<rhs_type> f0(n, amgcl::math::constant<rhs_type>(1));\n    std::vector<rhs_type> f = f0;\n\n    std::vector<rhs_type> x(m);\n\n    qr.solve(n, m, A.data(), f.data(), x.data(), order);\n\n    std::vector<rhs_type> Ax(n);\n    for(int i = 0; i < n; ++i) {\n        rhs_type sum = amgcl::math::zero<rhs_type>();\n        for(int j = 0; j < m; ++j)\n            sum += A0[i][j] * x[j];\n\n        Ax[i] = sum;\n\n        if (n < m) {\n            BOOST_CHECK_SMALL(amgcl::math::norm(sum - f0[i]), 1e-8);\n        }\n    }\n\n    if (n >= m) {\n        for(int i = 0; i < m; ++i) {\n            rhs_type sumx = amgcl::math::zero<rhs_type>();\n            rhs_type sumf = amgcl::math::zero<rhs_type>();\n\n            for(int j = 0; j < n; ++j) {\n                sumx += amgcl::math::adjoint(A0[j][i]) * Ax[j];\n                sumf += amgcl::math::adjoint(A0[j][i]) * f0[j];\n            }\n\n            rhs_type delta = sumx - sumf;\n\n            BOOST_CHECK_SMALL(amgcl::math::norm(delta), 1e-8);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE( test_qr )\n\nBOOST_AUTO_TEST_CASE( test_qr_factorize ) {\n    const int shape[][2] = {\n        {3, 3},\n        {3, 5},\n        {5, 3},\n        {5, 5}\n    };\n\n    const int n = sizeof(shape) / sizeof(shape[0]);\n\n    for(int i = 0; i < n; ++i) {\n        qr_factorize<double,                             amgcl::detail::row_major>(shape[i][0], shape[i][1]);\n        qr_factorize<double,                             amgcl::detail::col_major>(shape[i][0], shape[i][1]);\n        qr_factorize<std::complex<double>,               amgcl::detail::row_major>(shape[i][0], shape[i][1]);\n        qr_factorize<std::complex<double>,               amgcl::detail::col_major>(shape[i][0], shape[i][1]);\n        qr_factorize<amgcl::static_matrix<double, 2, 2>, amgcl::detail::row_major>(shape[i][0], shape[i][1]);\n        qr_factorize<amgcl::static_matrix<double, 2, 2>, amgcl::detail::col_major>(shape[i][0], shape[i][1]);\n    }\n}\n\nBOOST_AUTO_TEST_CASE( test_qr_solve ) {\n    const int shape[][2] = {\n        {3, 3},\n        {3, 5},\n        {5, 3},\n        {5, 5}\n    };\n\n    const int n = sizeof(shape) / sizeof(shape[0]);\n\n    for(int i = 0; i < n; ++i) {\n        qr_solve<double,                             amgcl::detail::row_major>(shape[i][0], shape[i][1]);\n        qr_solve<double,                             amgcl::detail::col_major>(shape[i][0], shape[i][1]);\n        qr_solve<std::complex<double>,               amgcl::detail::row_major>(shape[i][0], shape[i][1]);\n        qr_solve<std::complex<double>,               amgcl::detail::col_major>(shape[i][0], shape[i][1]);\n        qr_solve<amgcl::static_matrix<double, 2, 2>, amgcl::detail::row_major>(shape[i][0], shape[i][1]);\n        qr_solve<amgcl::static_matrix<double, 2, 2>, amgcl::detail::col_major>(shape[i][0], shape[i][1]);\n    }\n}\n\nBOOST_AUTO_TEST_CASE( qr_issue_39 ) {\n    boost::multi_array<double, 2> A0(boost::extents[2][2]);\n    A0[0][0] = 1e+0;\n    A0[0][1] = 1e+0;\n    A0[1][0] = 1e-8;\n    A0[1][1] = 1e+0;\n\n    boost::multi_array<double, 2> A = A0;\n\n    amgcl::detail::QR<double> qr;\n\n    qr.factorize(2, 2, A.data());\n\n    // Check that A = QR\n    for(int i = 0; i < 2; ++i) {\n        for(int j = 0; j < 2; ++j) {\n            double sum = 0;\n            for(int k = 0; k < 2; ++k)\n                sum += qr.Q(i,k) * qr.R(k,j);\n\n            sum -= A0[i][j];\n\n            BOOST_CHECK_SMALL(sum, 1e-8);\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "4a27e120b723a43007165af897f9b6a07c2190c9", "size": 6249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_qr.cpp", "max_stars_repo_name": "tenglongcong/amgcl", "max_stars_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 504.0, "max_stars_repo_stars_event_min_datetime": "2015-03-11T13:50:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:08:55.000Z", "max_issues_repo_path": "tests/test_qr.cpp", "max_issues_repo_name": "tenglongcong/amgcl", "max_issues_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 209.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T19:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:44:12.000Z", "max_forks_repo_path": "tests/test_qr.cpp", "max_forks_repo_name": "tenglongcong/amgcl", "max_forks_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92.0, "max_forks_repo_forks_event_min_datetime": "2015-01-04T06:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:49:12.000Z", "avg_line_length": 29.7571428571, "max_line_length": 109, "alphanum_fraction": 0.5309649544, "num_tokens": 1943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.754914997895581, "lm_q1q2_score": 0.6323318667369565}}
{"text": "/*****************************************************************************\n * random.cpp        Blitz++ random numbers example\n */\n\n#include <random/uniform.h>\n#include <blitz/numinquire.h>\n#include <time.h>\n#include <iostream>\n#include <iomanip>\n\nusing namespace ranlib;\nusing namespace blitz;\n\n// workaround for broken streams in Compaq cxx, can't handle long double\n#if defined(__DECCXX)\n#define LD_HACK(x) static_cast<double>(x)\n#else\n#define LD_HACK(x) x\n#endif\n\ntemplate<typename T>\nvoid printRandoms()\n{\n  Uniform<T> x;\n  //x.seed((unsigned int)time(0));\n  x.seed(5);\n  int N=5;\n  for (int i = 0; i < N; ++i) \n    cout << setprecision(digits10(T())) << LD_HACK(x.random()) << endl;\n\n  cout << endl;\n}\n\nint main()\n{\n// test get/set state interface\n  Uniform<double> x;\n  Uniform<double>::T_state S = x.getState();\n  x.setState(S);\n  std::string str = x.getStateString();\n  x.setState(str);\n\n  cout << \"Some random float: \" << endl;\n  printRandoms<float>();\n\n  cout << \"Some random doubles: \" << endl;\n  printRandoms<double>();\n\n  cout << \"Some random long doubles: \" << endl;\n  printRandoms<long double>();\n\n  return 0;\n}\n\n", "meta": {"hexsha": "3c3f6af8c4b56b6402edc84de5049fdb87ae2dd3", "size": 1133, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/random.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/random.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/random.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": 20.6, "max_line_length": 78, "alphanum_fraction": 0.6081200353, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6323318528811064}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n  Eigen::Matrix4f m;\n  m << 1, 2, 3, 4,\n       5, 6, 7, 8,\n       9, 10,11,12,\n       13,14,15,16;\n  cout << \"m.leftCols(2) =\" << endl << m.leftCols(2) << endl << endl;\n  cout << \"m.bottomRows<2>() =\" << endl << m.bottomRows<2>() << endl << endl;\n  m.topLeftCorner(1,3) = m.bottomRightCorner(3,1).transpose();\n  cout << \"After assignment, m = \" << endl << m << endl;\n}\n", "meta": {"hexsha": "3a31507aa63e01f69d312b3733a338106be5f9b5", "size": 448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_BlockOperations_corner.cpp", "max_stars_repo_name": "shareq2005/CarND-MPC-Project", "max_stars_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3457.0, "max_stars_repo_stars_event_min_datetime": "2018-06-09T15:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-01T22:09:25.000Z", "max_issues_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_BlockOperations_corner.cpp", "max_issues_repo_name": "shareq2005/CarND-MPC-Project", "max_issues_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "src/Eigen-3.3/doc/examples/Tutorial_BlockOperations_corner.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 24.8888888889, "max_line_length": 77, "alphanum_fraction": 0.5446428571, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358014, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6323294181204481}}
{"text": "/* Daniel R. Reynolds\n   SMU Mathematics\n   7 August 2020 */\n\n// Inclusions\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <armadillo>\nusing namespace std;\n\n\n// Gram-Schmidt process for orthonormalizing a set of vectors\nint GramSchmidt(arma::mat& X) {\n\n  // check that there is work to do\n  if (X.n_cols < 1)  return 0;\n\n  // get entry magnitude (for linear dependence check)\n  double Xmax = arma::norm(X,\"inf\");\n\n  // normalize first column\n  double colnorm = arma::norm(X.col(0));\n  if (colnorm < 1.e-13*Xmax) {\n    cerr << \"GramSchmidt error: vectors are linearly-dependent!\\n\";\n    return 1;\n  }\n  X.col(0) *= (1.0/colnorm);\n\n  // iterate over remaining vectors, performing Gram-Schmidt process\n  for (int i=1; i<X.n_cols; i++) {\n\n    // subtract off portions in directions of existing basis vectors\n    for (int j=0; j<i; j++)\n      X.col(i) -= (arma::dot(X.col(i), X.col(j)) * X.col(j));\n\n    // normalize vector, checking for linear dependence\n    colnorm = arma::norm(X.col(i));\n    if (colnorm < 1.e-13*Xmax) {\n      cerr << \"GramSchmidt error: vectors are linearly-dependent!\\n\";\n      return 1;\n    }\n    X.col(i) *= (1.0/colnorm);\n  }\n\n  // return success\n  return 0;\n}\n", "meta": {"hexsha": "627df00f71d00a34b3a102c7fdc1b89b23e2d314", "size": 1203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "armadillo/GramSchmidt.cpp", "max_stars_repo_name": "drreynolds/Math6321-codes", "max_stars_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "armadillo/GramSchmidt.cpp", "max_issues_repo_name": "drreynolds/Math6321-codes", "max_issues_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "armadillo/GramSchmidt.cpp", "max_forks_repo_name": "drreynolds/Math6321-codes", "max_forks_repo_head_hexsha": "3cce53bbe70bdd00220b5d8888b00b20b4fd521b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-31T18:04:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-31T18:04:07.000Z", "avg_line_length": 24.5510204082, "max_line_length": 69, "alphanum_fraction": 0.6350789692, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6323294137687917}}
{"text": "/*\nCopyright (c) 2020 Inverse Palindrome\nProceduralX - ECS/Utility/AngleConversions.hpp\nhttps://inversepalindrome.com/\n*/\n\n\n#pragma once\n\n\n#include <boost/math/constants/constants.hpp>\n\n\nnamespace ECS::Utility\n{\n    template<typename T>\n    T degreesToRadians(T degrees)\n    {\n        return degrees * boost::math::constants::pi<T>() / (T)180;\n    }\n\n    template<typename T>\n    T radiansToDegrees(T radians)\n    {\n        return radians * (T)180 / boost::math::constants::pi<T>();\n    }\n}\n", "meta": {"hexsha": "e65df7d5f40bcbdc7707d42a681ec23ac2f2e30b", "size": 491, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ECS/Utility/AngleConversions.hpp", "max_stars_repo_name": "InversePalindrome/ProceduralX", "max_stars_repo_head_hexsha": "f53d734970be4300f06db295d25e1a012b1a8fd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-06T14:39:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T08:27:54.000Z", "max_issues_repo_path": "include/ECS/Utility/AngleConversions.hpp", "max_issues_repo_name": "InversePalindrome/ProceduralX", "max_issues_repo_head_hexsha": "f53d734970be4300f06db295d25e1a012b1a8fd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ECS/Utility/AngleConversions.hpp", "max_forks_repo_name": "InversePalindrome/ProceduralX", "max_forks_repo_head_hexsha": "f53d734970be4300f06db295d25e1a012b1a8fd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5357142857, "max_line_length": 66, "alphanum_fraction": 0.6558044807, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6323294134204592}}
{"text": "/*\n * Copyright 2017-2020 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// Define our Module name (prints at testing)\n#define BOOST_TEST_MODULE MyTest\n\n#include <boost/test/unit_test.hpp>\n#include \"gram_savitzky_golay/gram_savitzky_golay.h\"\n#include <chrono>\n#include <cmath>\n#include <iostream>\n\nusing namespace gram_sg;\n\nBOOST_AUTO_TEST_CASE(TestGorryTables)\n{\n  // Compare with tables in the paper from Gorry.\n  // Convolution weights for quadratic initial-point smoothing:\n  // polynomial order = 2, derivative = 0\n  std::vector<double> sg7_gram{32, 15, 3, -4, -6, -3, 5};\n\n  SavitzkyGolayFilter filter(3, -3, 2, 0);\n\n  const auto & filter_weights = filter.weights();\n  for(unsigned int i = 0; i < sg7_gram.size(); i++)\n  {\n    std::cout << \"ref: \" << sg7_gram[i] << \", computed: \" << filter_weights[i] * 42 << std::endl;\n    BOOST_REQUIRE_CLOSE(sg7_gram[i], filter_weights[i] * 42, 10e-6);\n  }\n\n  // BOOST_CHECK( test_object.is_valid() );\n}\n\nBOOST_AUTO_TEST_CASE(TestGorryDerivative)\n{\n  // Compare with tables in the paper from Gorry.\n  // Convolution weights for quadratic initial-point first derivative:\n  // polynomial order = 2, derivative = 1\n  std::vector<double> sg7_deriv_gram{-13, -2, 5, 8, 7, 2, -7};\n\n  SavitzkyGolayFilter filter(3, -3, 2, 1);\n\n  const auto & filter_weights = filter.weights();\n  for(unsigned int i = 0; i < sg7_deriv_gram.size(); i++)\n  {\n    std::cout << \"ref: \" << sg7_deriv_gram[i] << \", computed: \" << filter_weights[i] * 28 << std::endl;\n    BOOST_REQUIRE_CLOSE(sg7_deriv_gram[i], filter_weights[i] * 28, 10e-6);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(TestIdentity)\n{\n  SavitzkyGolayFilter filter(3, 0, 2, 0);\n  std::vector<double> data = {1, 1, 1, 1, 1, 1, 1};\n  double res = filter.filter(data);\n  BOOST_REQUIRE_CLOSE(res, 1, 10e-6);\n}\n\nBOOST_AUTO_TEST_CASE(TestRealTimeFilter)\n{\n  // Window size is 2*m+1\n  const unsigned m = 3;\n  // Polynomial Order\n  const unsigned n = 2;\n  // Initial Point Smoothing (ie evaluate polynomial at first point in the window)\n  // Points are defined in range [-m;m]\n  const int t = m;\n  // Derivate? 0: no derivation, 1: first derivative...\n  SavitzkyGolayFilter filter(m, t, n, 0);\n\n  // Filter some data\n  std::vector<double> data = {.1, .7, .9, .7, .8, .5, -.3};\n  double result = filter.filter(data);\n  double result_ref = -0.22619047619047616;\n  BOOST_REQUIRE_CLOSE(result, result_ref, 10e-6);\n}\n\nBOOST_AUTO_TEST_CASE(TestRealTimeDerivative)\n{\n  // Window size is 2*m+1\n  const unsigned m = 3;\n  // Polynomial Order\n  const unsigned n = 2;\n  // Initial Point Smoothing (ie evaluate polynomial at first point in the window)\n  // Points are defined in range [-m;m]\n  const int t = m;\n\n  // Test First Order Derivative\n  SavitzkyGolayFilter filter(m, t, n, 1);\n  SavitzkyGolayFilter filter_dt(m, t, n, 1, 0.005);\n  BOOST_REQUIRE(filter_dt.config().time_step() == 0.005);\n\n  // Filter some data\n  std::vector<double> data = {.1, .2, .3, .4, .5, .6, .7};\n  double result = filter.filter(data);\n  double result_ref = 0.1;\n  BOOST_REQUIRE_CLOSE(result, result_ref, 10e-6);\n\n  // Test filtering with timestep=0.005\n  data = {.1, .2, .3, .4, .5, .6, .7};\n  result = filter_dt.filter(data);\n  result_ref = 0.1 / filter_dt.config().time_step();\n  BOOST_REQUIRE_CLOSE(result, result_ref, 10e-6);\n\n  // Filter some data\n  data = {-1, -2, -3, -4, -5, -6, -7};\n  result = filter.filter(data);\n  result_ref = -1;\n  BOOST_REQUIRE_CLOSE(result, result_ref, 10e-6);\n  // Test filtering with timestep=0.005\n  result = filter_dt.filter(data);\n  result_ref = -1. / filter_dt.config().time_step();\n  BOOST_REQUIRE_CLOSE(result, result_ref, 10e-6);\n\n  // Test Second Order Derivative\n  SavitzkyGolayFilter second_order_filter(m, t, n, 2);\n\n  // Filter some data\n  data = {.1, .2, .3, .4, .5, .6, .7};\n  result = second_order_filter.filter(data);\n  BOOST_CHECK_SMALL(result, 10e-6);\n\n  // Filter some data\n  data = {-1, -2, -3, -4, -5, -6, -7};\n  result = second_order_filter.filter(data);\n  BOOST_CHECK_SMALL(result, 10e-6);\n}\n\n// Test derivation on a known polynomial function\nBOOST_AUTO_TEST_CASE(TestPolynomialDerivative)\n{\n  // Polynomial is a*x^3 + bx^2 + c*x^1 + d\n  double a = 10;\n  double b = 2;\n  double c = -3;\n  double d = -4;\n  double timeStep = 0.42;\n\n  // Window size is 2*m+1\n  const unsigned m = 50;\n  // Polynomial Order\n  const unsigned n = 3;\n  // Points are defined in range [-m;m]\n  // Eval at central point\n  const int t = 0;\n\n  SavitzkyGolayFilter filter_order1(m, t, n, 1, timeStep);\n  SavitzkyGolayFilter filter_order2(m, t, n, 2, timeStep);\n  std::vector<double> data;\n  std::vector<double> derivative_order1, derivative_order2;\n  data.resize(2 * m + 1);\n  derivative_order1.resize(2 * m + 1);\n  derivative_order2.resize(2 * m + 1);\n  // Generate some data points\n  for(unsigned x = 0; x < data.size(); ++x)\n  {\n    data[x] = a * std::pow(x, 3) + b * std::pow(x, 2) + c * std::pow(x, 1) + d;\n    derivative_order1[x] = (3 * a * std::pow(x, 2) + 2 * b * std::pow(x, 1) + c) / timeStep;\n    derivative_order2[x] = (6 * a * std::pow(x, 1) + 2 * b) / std::pow(timeStep, 2);\n  }\n  const auto result_order1 = filter_order1.filter(data);\n  const auto expected_result_order1 = derivative_order1[m];\n  const auto result_order2 = filter_order2.filter(data);\n  const auto expected_result_order2 = derivative_order2[m];\n\n  BOOST_REQUIRE_CLOSE(result_order1, expected_result_order1, 10e-8);\n  BOOST_REQUIRE_CLOSE(result_order2, expected_result_order2, 10e-8);\n}\n", "meta": {"hexsha": "eb5ae0a16d1cfd8708dd941e37ee962328f2b3d1", "size": 5408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_gram_savitzky_golay.cpp", "max_stars_repo_name": "hedgepigdaniel/gram_savitzky_golay", "max_stars_repo_head_hexsha": "ad18bf4ee1648dc80144681565a324f9f4ad7914", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 51.0, "max_stars_repo_stars_event_min_datetime": "2018-02-16T16:12:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:09:04.000Z", "max_issues_repo_path": "tests/test_gram_savitzky_golay.cpp", "max_issues_repo_name": "hedgepigdaniel/gram_savitzky_golay", "max_issues_repo_head_hexsha": "ad18bf4ee1648dc80144681565a324f9f4ad7914", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-03-22T13:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T15:23:42.000Z", "max_forks_repo_path": "tests/test_gram_savitzky_golay.cpp", "max_forks_repo_name": "hedgepigdaniel/gram_savitzky_golay", "max_forks_repo_head_hexsha": "ad18bf4ee1648dc80144681565a324f9f4ad7914", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-07-18T08:51:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T02:57:25.000Z", "avg_line_length": 31.8117647059, "max_line_length": 103, "alphanum_fraction": 0.6697485207, "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219505, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6323294070671411}}
{"text": "#include \"fastkpm.h\"\n\n#include <cassert>\n#include <algorithm>\n#include <boost/math/tools/roots.hpp>\n\n#ifdef WITH_FFTW\n#include <fftw3.h>\n#endif\n\nnamespace fkpm {\n    \n    Vec<double> jackson_kernel(int M) {\n        auto ret = Vec<double>(M);\n        double Mp = M+1.0;\n        for (int m = 0; m < M; m++) {\n            ret[m] = (1.0/Mp)*((Mp-m)*cos(Pi*m/Mp) + sin(Pi*m/Mp)/tan(Pi/Mp));\n        }\n        return ret;\n    }\n    \n    Vec<double> lorentz_kernel(int M, double lambda) {\n        auto ret = Vec<double>(M);\n        for (int m = 0; m < M; m++) {\n            ret[m] = sinh(lambda * (1.0 - ((double) m)/ M)) / sinh(lambda);\n        }\n        return ret;\n    }\n    \n    void chebyshev_fill_array(double x, Vec<double>& ret, int kind) {\n        assert(kind == 1 || kind == 2);\n        if (ret.size() > 0)\n            ret[0] = 1.0;\n        if (ret.size() > 1)\n            ret[1] = kind * x;\n        for (int m = 2; m < ret.size(); m++) {\n            ret[m] = 2*x*ret[m-1] - ret[m-2];\n        }\n    }\n    \n    Vec<double> expansion_coefficients(int M, int Mq, std::function<double(double)> f, EnergyScale es) {\n        assert(Mq >= M);\n        auto kernel = jackson_kernel(M);\n        auto ret = Vec<double>(M, 0.0);\n#ifdef WITH_FFTW\n        double *xc, *yc;\n        xc = (double*) fftw_malloc(sizeof(double) * Mq);\n        yc = (double*) fftw_malloc(sizeof(double) * Mq);\n        for (int i = 0; i < Mq; i++) {\n            double x_i = cos(Pi * (i+0.5) / Mq);\n            xc[i] = f(es.unscale(x_i));\n        }\n        fftw_plan p;\n        p = fftw_plan_r2r_1d(Mq, xc, yc, FFTW_REDFT10, FFTW_ESTIMATE);  // DCT-II\n        fftw_execute(p);\n        fftw_destroy_plan(p);\n        for (int m = 0; m < M; m++) {\n            ret[m] = (m == 0 ? 0.5 : 1.0) * kernel[m] * yc[m] / Mq;\n        }\n        fftw_free(xc);\n        fftw_free(yc);\n#else\n        auto fp = Vec<double>(M, 0.0);\n        auto T = Vec<double>(M);\n        for (int i = 0; i < Mq; i++) {\n            double x_i = cos(Pi * (i+0.5) / Mq);\n            double f_i = f(es.unscale(x_i));\n            chebyshev_fill_array(x_i, T);\n            for (int m = 0; m < M; m++) {\n                fp[m] += f_i * T[m];\n            }\n        }\n        for (int m = 0; m < M; m++) {\n            ret[m] = (m == 0 ? 1.0 : 2.0) * kernel[m] * fp[m] / Mq;\n        }\n#endif\n        return ret;\n    }\n    \n    Vec<Vec<cx_double>> electrical_conductivity_coefficients(int M, int Mq, double kT, double mu,\n                                                             double omega, EnergyScale es, Vec<double> const& kernel) {\n        assert(kernel.size() == M);\n        assert(Mq >= 2*M);                                                      // To simplify usage of Y_{m_1+m_2} (see notes on fft)\n        assert(omega >= 0.0);\n        double cutoff = 1e-4;                                                   // neglect points near the boundary\n        double omega_scaled = omega / es.mag();                                 // rescale omega\n        Vec<Vec<cx_double>> ret(M);\n        for (int i = 0; i < M; i++) {                                           // initialize cmn to 0\n            ret[i].resize(M, 0.0);\n        }\n        if (omega_scaled >= 2.0 ) return ret;\n        \n        if (omega_scaled < 1e-10) {                                             // static conductivity\n#ifdef WITH_FFTW\n            double *x1, *x2, *yc1, *yc2, *ys1, *ys2;\n            fftw_plan p1, p2, p3, p4;\n            x1  = (double*) fftw_malloc(sizeof(double) * Mq);\n            x2  = (double*) fftw_malloc(sizeof(double) * Mq);\n            yc1 = (double*) fftw_malloc(sizeof(double) * Mq);\n            yc2 = (double*) fftw_malloc(sizeof(double) * Mq);\n            ys1 = (double*) fftw_malloc(sizeof(double) * Mq);\n            ys2 = (double*) fftw_malloc(sizeof(double) * Mq);\n            for (int i = 0; i < Mq; i++) {\n                double x_i = cos(Pi * (i+0.5) / Mq);\n                if (1.0-x_i*x_i < cutoff) {                                     // neglect points near boundary\n                    x1[i] = 0.0;\n                    x2[i] = 0.0;\n                } else {\n                    double f_i = fermi_density(es.unscale(x_i), kT, mu);\n                    x1[i] = f_i * x_i / std::pow(1.0-x_i*x_i, 1.5);\n                    x2[i] = f_i / (1.0-x_i*x_i);\n                }\n            }\n            p1  = fftw_plan_r2r_1d(Mq, x1, yc1, FFTW_REDFT10, FFTW_ESTIMATE);   // DCT-II\n            fftw_execute(p1);\n            p2  = fftw_plan_r2r_1d(Mq, x2, yc2, FFTW_REDFT10, FFTW_ESTIMATE);   // DCT-II\n            fftw_execute(p2);\n            p3  = fftw_plan_r2r_1d(Mq, x1, ys1, FFTW_RODFT10, FFTW_ESTIMATE);   // DST-II\n            fftw_execute(p3);\n            p4  = fftw_plan_r2r_1d(Mq, x2, ys2, FFTW_RODFT10, FFTW_ESTIMATE);   // DST-II\n            fftw_execute(p4);\n            fftw_destroy_plan(p1);\n            fftw_destroy_plan(p2);\n            fftw_destroy_plan(p3);\n            fftw_destroy_plan(p4);\n            fftw_free(x1);\n            fftw_free(x2);\n            for (int m1 = 0; m1 < M; m1++) {\n                double temp_m1 = Pi * (m1 == 0 ? 1.0 : 2.0) * kernel[m1] / (2.0 * Mq * es.mag() * es.mag());\n                for (int m2 = 0; m2 < M; m2++) {\n                    double temp_m2 = temp_m1 * (m2 == 0 ? 1.0 : 2.0) * kernel[m2];\n                    int m_sum   = m1 + m2;\n                    int m_dif   = m1 - m2;\n                    double y_re =  2.0 * yc1[m_sum]\n                                 + 2.0 * (m_dif >= 0 ? yc1[m_dif] : yc1[-m_dif])\n                                 + m_sum * (m_sum > 0 ? ys2[m_sum-1] : 0.0)\n                                 + m_dif * (m_dif > 0 ? ys2[m_dif-1] : (m_dif < 0 ? -ys2[-m_dif-1] : 0.0));\n                    double y_im =  2.0 * (m_dif > 0 ? ys1[m_dif-1] : (m_dif < 0 ? -ys1[-m_dif-1] : 0.0))\n                                 - m_dif * (yc2[m_sum] + (m_dif >=0 ? yc2[m_dif] : yc2[-m_dif]));\n                    ret[m1][m2] = cx_double(temp_m2 * y_re, temp_m2 * y_im);\n                }\n            }\n            fftw_free(yc1);\n            fftw_free(yc2);\n            fftw_free(ys1);\n            fftw_free(ys2);\n#else\n            std::cout << \"Warning: Not using FFTW (electrical_conductivity_coefficients).\" << std::endl;\n            auto T_i = Vec<double>(M);\n            auto T_j = Vec<double>(M);\n            for (int i = 0; i < Mq; i++) {\n                double x_i = cos(Pi * (i+0.5) / Mq);\n                if (1.0-x_i*x_i < cutoff) continue;                             // neglect points near boundary\n                double temp_squareroot1 = std::sqrt(1.0-x_i*x_i);\n                double f_i;\n                chebyshev_fill_array(x_i, T_i);\n                chebyshev_fill_array(x_i, T_j, 2);                              // fill T_j with sin[m * arccos(x)]\n                for (int m = M-1; m > 0; m--) {\n                    T_j[m] = T_j[m-1] * temp_squareroot1;\n                }\n                T_j[0] = 0.0;\n                f_i = fermi_density(es.unscale(x_i), kT, mu) / std::pow(1.0-x_i*x_i, 1.5);\n                for (int m1 = 0; m1 < M; m1++) {\n                    for (int m2 = 0; m2 < M; m2++) {\n                        ret[m1][m2] += ( T_i[m1] * cx_double(T_i[m2],-T_j[m2])\n                                        * cx_double(x_i, m2 * temp_squareroot1)\n                                        +T_i[m2] * cx_double(T_i[m1], T_j[m1])\n                                        * cx_double(x_i,-m1 * temp_squareroot1) ) * f_i;\n                    }\n                }\n            }\n            for (int m1 = 0; m1 < M; m1++) {\n                double temp_m1 = 2.0 * Pi * (m1 == 0 ? 1.0 : 2.0) * kernel[m1] / (Mq * es.mag() * es.mag());\n                for (int m2 = 0; m2 < M; m2++) {\n                    double temp_m2 = temp_m1 * (m2 == 0 ? 1.0 : 2.0) * kernel[m2];\n                    ret[m1][m2] *= cx_double(temp_m2, 0.0);\n                }\n            }\n#endif\n        } else {                                                                // optical conductivity\n            std::cout << \"Warning: FFTW not implemented yet (electrical_conductivity_coefficients).\" << std::endl;\n            int i_start = std::ceil(acos(1.0 - omega_scaled) / Pi * Mq - 0.5);\n            assert(M - i_start >= 20);                                          // at least 20 points to do integration\n            auto T_i = Vec<double>(M);\n            auto T_j = Vec<double>(M);\n            for (int i = i_start; i < Mq; i++) {\n                double x_i = cos(Pi * (i+0.5) / Mq);\n                if (1.0-x_i*x_i < cutoff) continue;                             // neglect points near boundary\n                double temp_squareroot2 = std::sqrt(1.0 - (x_i + omega_scaled) * (x_i + omega_scaled));\n                double f_i;\n                chebyshev_fill_array(x_i + omega_scaled, T_i);\n                chebyshev_fill_array(x_i, T_j);           // fill T_j with cos[m * arccos(x)]\n                f_i = (fermi_density(es.unscale(x_i), kT, mu) - fermi_density(es.unscale(x_i) + omega, kT, mu))\n                     / (omega * temp_squareroot2);\n                for (int m1 = 0; m1 < M; m1++) {\n                    for (int m2 = 0; m2 < M; m2++) {\n                        ret[m1][m2] += T_i[m1] * T_j[m2] * f_i;\n                    }\n                }\n            }\n            for (int m1 = 0; m1 < M; m1++) {\n                double temp_m1 = 2.0 * Pi * (m1 == 0 ? 1.0 : 2.0) * kernel[m1] / (Mq * es.mag() * es.mag());\n                for (int m2 = 0; m2 < M; m2++) {\n                    double temp_m2 = temp_m1 * (m2 == 0 ? 1.0 : 2.0) * kernel[m2];\n                    ret[m1][m2] *= cx_double(temp_m2, 0.0);\n                }\n            }\n            \n        }\n        return ret;\n    }\n\n    \n    Vec<double> moment_transform(Vec<double> const& moments, int Mq) {\n        int M = moments.size();\n        auto T = Vec<double>(M);\n        auto mup = Vec<double>(M);\n        auto gamma = Vec<double>(Mq);\n        \n        auto kernel = jackson_kernel(M);\n        for (int m = 0; m < M; m++)\n            mup[m] = moments[m] * kernel[m];\n        \n        // TODO: replace with DCT-III, mup -> gamma (caution, double check FFTW docs)\n        for (int i = 0; i < Mq; i++) {\n            gamma[i] = 0.0;\n            double x_i = cos(Pi * (i+0.5) / Mq);\n            chebyshev_fill_array(x_i, T); // T_m(x_i) = cos(m pi (i+1/2) / Mq)\n            for (int m = 0; m < M; m++) {\n                gamma[i] += (m == 0 ? 1 : 2) * mup[m] * T[m];\n            }\n        }\n        return gamma;\n    }\n    \n    Vec<Vec<cx_double>> moment_transform(Vec<Vec<cx_double>> const& moments, int Mq, Vec<double> const& kernel) {\n        int M = moments.size();\n        auto T_i = Vec<double>(M);\n        auto T_j = Vec<double>(M);\n        Vec<Vec<cx_double>> mup(M);\n        Vec<Vec<cx_double>> gamma(Mq);\n        for (int i = 0; i < M; i++)  mup[i].resize(M, cx_double(0.0,0.0));\n        for (int i = 0; i < Mq; i++) gamma[i].resize(Mq, cx_double(0.0,0.0));\n        \n        for (int m1 = 0; m1 < M; m1++) {\n            for (int m2 = 0; m2 < M; m2++) {\n                mup[m1][m2] = cx_double((m1 == 0 ? 1.0 : 2.0) * (m2 == 0 ? 1.0 : 2.0)\n                                        * kernel[m1] * kernel[m2], 0.0) * moments[m1][m2];\n            }\n        }\n        \n        // TODO replace with fftw\n        for (int i = 0; i < Mq; i++) {\n            double x_i = cos(Pi * (i+0.5) / Mq);\n            chebyshev_fill_array(x_i, T_i);\n            for (int j = 0; j < Mq; j++) {\n                double x_j = cos(Pi * (j+0.5) / Mq);\n                chebyshev_fill_array(x_j, T_j);\n                for (int m1 = 0; m1 < M; m1++) {\n                    for (int m2 = 0; m2 < M; m2++) {\n                        gamma[i][j] += (T_i[m1] * T_j[m2]) * mup[m1][m2];\n                    }\n                }\n            }\n        }\n        return gamma;\n    }\n    \n    double moment_product(Vec<double> const& c, Vec<double> const& mu) {\n        int M = c.size();\n        double ret = 0;\n        for (int i = 0; i < M; i++) {\n            ret += c[i]*mu[i];\n        }\n        return ret;\n    }\n\n    cx_double moment_product(Vec<Vec<cx_double>> const& c, Vec<Vec<cx_double>> const& mu) {\n        int M1 = c.size();\n        int M2 = c[0].size();\n        assert(mu.size() == M1);\n        assert(mu[0].size() == M2);\n        cx_double ret(0.0, 0.0);\n        for (int m1 = 0; m1 < M1; m1++) {\n            for (int m2 = 0; m2 < M2; m2++) {\n                ret += c[m1][m2] * mu[m1][m2];\n            }\n        }\n        return ret;\n    }\n    \n    double density_product(Vec<double> const& gamma, std::function<double(double)> f, EnergyScale es) {\n        int Mq = gamma.size();\n        double ret = 0.0;\n        for (int i = 0; i < Mq; i++) {\n            double x_i = cos(Pi * (i+0.5) / Mq);\n            ret += gamma[i] * f(es.unscale(x_i));\n        }\n        return ret / Mq;\n    }\n    \n    void density_function(Vec<double> const& gamma, EnergyScale es, Vec<double>& x, Vec<double>& rho) {\n        int Mq = gamma.size();\n        x.resize(Mq);\n        rho.resize(Mq);\n        for (int i = Mq-1; i >= 0; i--) {\n            double x_i = cos(Pi * (i+0.5) / Mq);\n            x[Mq-1-i] = es.unscale(x_i);\n            rho[Mq-1-i] = gamma[i] / (Pi * sqrt(1-x_i*x_i) * es.mag());\n        }\n    }\n    \n    void density_function(Vec<Vec<cx_double>> const& gamma, EnergyScale es, Vec<double>& x, Vec<double>& y, Vec<Vec<cx_double>>& rho) {\n        int Mq1 = gamma.size();\n        int Mq2 = gamma[0].size();\n        x.resize(Mq1);\n        y.resize(Mq2);\n        rho.resize(Mq1);\n        for (int i = 0; i < Mq1; i++) {\n            rho[i].resize(Mq2);\n            for (int j = 0; j < Mq2; j++) {\n                rho[i][j] = 0.0;\n            }\n        }\n        for (int i2 = Mq2-1; i2 >= 0; i2--) {\n            double x2   = cos(Pi * (i2+0.5) / Mq2);\n            y[Mq2-1-i2] = es.unscale(x2);\n        }\n        for (int i1 = Mq1-1; i1 >= 0; i1--) {\n            double x1   = cos(Pi * (i1+0.5) / Mq1);\n            x[Mq1-1-i1] = es.unscale(x1);\n            for (int i2 = Mq2-1; i2 >= 0; i2--) {\n                double x2 = cos(Pi * (i2+0.5) / Mq2);\n                rho[Mq1-1-i1][Mq2-1-i2] = gamma[i1][i2] / (Pi * sqrt(1.0 - x1*x1)\n                                                          * Pi * sqrt(1.0 - x2*x2) * es.mag() * es.mag());\n            }\n        }\n    }\n    \n    void integrated_density_function(Vec<double> const& gamma, EnergyScale es, Vec<double>& x, Vec<double>& irho) {\n        int Mq = gamma.size();\n        x.resize(Mq);\n        irho.resize(Mq);\n        double acc = 0.0;\n        for (int i = Mq-1; i >= 0; i--) {\n            double x_i = cos(Pi * (i+0.5) / Mq);\n            x[Mq-1-i] = es.unscale(x_i);\n            irho[Mq-1-i] = (acc+0.5*gamma[i]) / Mq;\n            acc += gamma[i];\n        }\n    }\n    \n    double fermi_energy(double x, double kT, double mu) {\n        double alpha = (x-mu)/std::abs(kT);\n        if (kT < 1e-15 || std::abs(alpha) > 20) {\n            return (x < mu) ? (x-mu) : 0.0;\n        }\n        else {\n            return -kT*log(1 + exp(-alpha));\n        }\n    }\n    \n    double fermi_density(double x, double kT, double mu) {\n        double alpha = (x-mu)/std::abs(kT);\n        if (kT < 1e-15 || std::abs(alpha) > 20) {\n            return (x < mu) ? 1.0 : 0.0;\n        }\n        else {\n            return 1.0/(exp(alpha)+1.0);\n        }\n    }\n    \n    double mu_to_filling(Vec<double> const& gamma, EnergyScale const& es, double kT, double mu) {\n        using std::placeholders::_1;\n        double n_occ = density_product(gamma, std::bind(fermi_density, _1, kT, mu), es);\n        double n_tot = density_product(gamma, [](double x){return 1;}, es);\n        return n_occ/n_tot;\n    }\n    double mu_to_filling(arma::vec const& evals, double kT, double mu) {\n        double n_occ = 0;\n        double n_tot = evals.size();\n        for (double const& x : evals) {\n            n_occ += fermi_density(x, kT, mu);\n        }\n        return n_occ/n_tot;\n    }\n    \n    static double root_solver(std::function<double(double)> f, double lo, double hi) {\n        int precision_bits = 30;\n        boost::math::tools::eps_tolerance<double> tol(precision_bits);\n        boost::uintmax_t max_iter=50;\n        auto bds = boost::math::tools::toms748_solve(f, lo, hi, tol, max_iter);\n        return 0.5 * (bds.first + bds.second);\n    }\n    \n    double filling_to_mu(Vec<double> const& gamma, EnergyScale const& es, double kT, double filling, double delta_filling) {\n        // thermal smearing for faster convergence\n        kT = std::max(kT, 0.1*es.mag()/gamma.size());\n        double c = kT * std::log(1.0/filling - 1.0);\n\n        auto f1 = [&](double x) { return mu_to_filling(gamma, es, kT, x) - (filling+delta_filling); };\n        auto f2 = [&](double x) { return mu_to_filling(gamma, es, kT, x) - (filling-delta_filling); };\n        if (delta_filling == 0) {\n            return root_solver(f1, es.lo - std::max(c,0.0), es.hi + std::max(-c,0.0));\n        }\n        else {\n            return 0.5 * (root_solver(f1, es.lo - std::max(c,0.0), es.hi + std::max(-c,0.0))\n                        + root_solver(f2, es.lo - std::max(c,0.0), es.hi + std::max(-c,0.0)));\n        }\n    }\n    double filling_to_mu(arma::vec const& evals, double kT, double filling) {\n        assert(kT > 0 && \"filling_to_mu() requires thermal smearing!\");\n        auto f = [&](double x) { return mu_to_filling(evals, kT, x) - filling; };\n        auto minmax = std::minmax_element(evals.begin(), evals.end());\n        return root_solver(f, *minmax.first, *minmax.second);\n    }\n    \n    double electronic_grand_energy(Vec<double> const& gamma, EnergyScale const& es, double kT, double mu) {\n        using std::placeholders::_1;\n        return density_product(gamma, std::bind(fermi_energy, _1, kT, mu), es);\n    }\n    double electronic_grand_energy(arma::vec const& evals, double kT, double mu) {\n        double acc = 0;\n        for (double const& x : evals) {\n            acc += fermi_energy(x, kT, mu);\n        }\n        return acc;\n    }\n    \n    double electronic_energy(Vec<double> const& gamma, EnergyScale const& es, double kT, double filling, double mu) {\n        double n_tot = density_product(gamma, [](double x){return 1;}, es);\n        double n_occ = filling*n_tot;\n        return electronic_grand_energy(gamma, es, kT, mu) + mu*n_occ;\n    }\n    double electronic_energy(arma::vec const& evals, double kT, double filling) {\n        // at zero temperature, need special logic to correctly count degenerate eigenvalues\n        if (kT == 0) {\n            auto evals_sorted = evals;\n            std::sort(evals_sorted.begin(), evals_sorted.end());\n            int n_occ = int(filling*evals.size() + 0.5);\n            assert(n_occ >= 0 && n_occ <= evals.size());\n            double acc = 0;\n            for (int i = 0; i < n_occ; i++) {\n                acc += evals_sorted[i];\n            }\n            return acc;\n        }\n        else {\n            double n_tot = evals.size();\n            double n_occ = filling*n_tot;\n            double mu = filling_to_mu(evals, kT, filling);\n            return electronic_grand_energy(evals, kT, mu) + mu*n_occ;\n        }\n    }\n    \n}\n", "meta": {"hexsha": "3287f39ace062c410e7d91ebb95ff59d4ea0c266", "size": 19108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fastkpm.cpp", "max_stars_repo_name": "wztzjhn/FastKPM", "max_stars_repo_head_hexsha": "ce5fee32f466bb58546e8d42f96aa280fecf58d3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T01:17:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-25T20:13:51.000Z", "max_issues_repo_path": "src/fastkpm.cpp", "max_issues_repo_name": "wztzjhn/FastKPM", "max_issues_repo_head_hexsha": "ce5fee32f466bb58546e8d42f96aa280fecf58d3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fastkpm.cpp", "max_forks_repo_name": "wztzjhn/FastKPM", "max_forks_repo_head_hexsha": "ce5fee32f466bb58546e8d42f96aa280fecf58d3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T01:21:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T02:46:42.000Z", "avg_line_length": 41.8118161926, "max_line_length": 135, "alphanum_fraction": 0.452794641, "num_tokens": 5921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6323111044972201}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/complex.h>\n#include <pybind11/numpy.h>\n#include <boost/lexical_cast.hpp>\n\n#include <assert.h>\n#include <vector>\n\n#include <CGAL/Kernel/global_functions.h>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Triangulation_vertex_base_with_info_3.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel            Kernel;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<unsigned int, Kernel> Vb;\ntypedef CGAL::Triangulation_data_structure_2<Vb>                       Tds;\ntypedef CGAL::Delaunay_triangulation_2<Kernel, Tds>                    Delaunay;\ntypedef Kernel::Point_2 Point;\n\ntypedef CGAL::Triangulation_vertex_base_with_info_3<unsigned int, Kernel> Vb3;\ntypedef CGAL::Triangulation_data_structure_3<Vb3>                       Tds3;\ntypedef CGAL::Delaunay_triangulation_3<Kernel, Tds3>                    Delaunay3;\ntypedef Kernel::Point_3 Point3;\n\n\n\nstd::vector<double> c_circumballs2(std::vector<double> &vertices)\n{\n    int num_faces = vertices.size()/6;\n    std::vector<double> circumcenters;\n    for(std::size_t i=0; i < num_faces; ++i)\n    {\n        Point tmp_cc =\n                CGAL::circumcenter(\n                Point(vertices[i*6],vertices[i*6+1]),\n                Point(vertices[i*6+2],vertices[i*6+3]),\n                Point(vertices[i*6+4],vertices[i*6+5])\n                );\n        circumcenters.push_back(tmp_cc.x());\n        circumcenters.push_back(tmp_cc.y());\n        circumcenters.push_back(\n                CGAL::squared_radius(\n                    Point(vertices[i*6],vertices[i*6+1]),\n                    Point(vertices[i*6+2],vertices[i*6+3]),\n                    Point(vertices[i*6+4],vertices[i*6+5])\n                    )\n                );\n    }\n    return circumcenters;\n}\n\nstd::vector<double> c_circumballs3(std::vector<double> &vertices)\n{\n    int num_cells = vertices.size()/12;\n    std::vector<double> circumcenters;\n    for(std::size_t i=0; i < num_cells; ++i)\n    {\n        Point3 tmp_cc =\n                CGAL::circumcenter(\n                Point3(vertices[i*12],vertices[i*12+1],vertices[i*12+2]),\n                Point3(vertices[i*12+3],vertices[i*12+4],vertices[i*12+5]),\n                Point3(vertices[i*12+6],vertices[i*12+7],vertices[i*12+8]),\n                Point3(vertices[i*12+9], vertices[i*12+10],vertices[i*12+11])\n                );\n        circumcenters.push_back(tmp_cc.x());\n        circumcenters.push_back(tmp_cc.y());\n        circumcenters.push_back(tmp_cc.z());\n        circumcenters.push_back(\n                CGAL::squared_radius(\n                Point3(vertices[i*12],vertices[i*12+1],vertices[i*12+2]),\n                Point3(vertices[i*12+3],vertices[i*12+4],vertices[i*12+5]),\n                Point3(vertices[i*12+6],vertices[i*12+7],vertices[i*12+8]),\n                Point3(vertices[i*12+9], vertices[i*12+10],vertices[i*12+11]))\n                );\n    }\n    return circumcenters;\n}\n\nstd::vector<int> c_delaunay2(std::vector<double> &x, std::vector<double> &y)\n{\n  int num_points = x.size();\n  assert(y.size()!=num_points);\n  std::vector< std::pair<Point,unsigned> > points;\n  // add index information to form face table later\n  for(std::size_t i = 0; i < num_points; ++i)\n  {\n     points.push_back( std::make_pair( Point(x[i],y[i]), i ) );\n  }\n\n  Delaunay triangulation;\n  triangulation.insert(points.begin(),points.end());\n\n  // save the face table\n  int num_faces = triangulation.number_of_faces();\n  std::vector<int> faces;\n  faces.resize(num_faces*3);\n\n  int i=0;\n  for(Delaunay::Finite_faces_iterator fit = triangulation.finite_faces_begin();\n    fit != triangulation.finite_faces_end(); ++fit) {\n\n    Delaunay::Face_handle face = fit;\n    faces[i*3]=face->vertex(0)->info();\n    faces[i*3+1]=face->vertex(1)->info();\n    faces[i*3+2]=face->vertex(2)->info();\n    i+=1;\n  }\n  return faces;\n}\n\n\n\n\nstd::vector<int> c_delaunay3(std::vector<double> &x, std::vector<double> &y, std::vector<double> &z)\n{\n  int num_points = x.size();\n  assert(y.size()!=num_points);\n  assert(z.size()!=num_points);\n  std::vector< std::pair<Point3,unsigned> > points;\n  // add index information to form face table later\n  for(std::size_t i = 0; i < num_points; ++i)\n  {\n     points.push_back( std::make_pair( Point3(x[i],y[i],z[i]), i ) );\n  }\n  Delaunay3 triangulation;\n  triangulation.insert(points.begin(),points.end());\n  // save the indices of all cells\n  int num_cells = triangulation.number_of_finite_cells();\n  std::vector<int> cells;\n  cells.resize(num_cells*4);\n\n  int i=0;\n  for(Delaunay3::Finite_cells_iterator cit = triangulation.finite_cells_begin();\n    cit != triangulation.finite_cells_end(); ++cit) {\n\n    Delaunay3::Cell_handle cell = cit;\n    cells[i*4]=cell->vertex(0)->info();\n    cells[i*4+1]=cell->vertex(1)->info();\n    cells[i*4+2]=cell->vertex(2)->info();\n    cells[i*4+3]=cell->vertex(3)->info();\n    i+=1;\n  }\n  return cells;\n}\n\n\n// ----------------\n// Python interface\n// ----------------\n// (from https://github.com/tdegeus/pybind11_examples/blob/master/04_numpy-2D_cpp-vector/example.cpp)\n\nnamespace py = pybind11;\npy::array circumballs2(py::array_t<double, py::array::c_style | py::array::forcecast> vertices)\n{\n    // each triangle has 3 vertices with 2 coordinates each\n    int sz = vertices.shape()[0];\n    std::vector<double> cppvertices(sz);\n    std::memcpy(cppvertices.data(),vertices.data(),sz*sizeof(double));\n    std::vector<double> circumcenters = c_circumballs2(cppvertices);\n    ssize_t              soreal      = sizeof(double);\n    ssize_t              num_points = circumcenters.size()/3;\n    ssize_t              ndim      = 2;\n    std::vector<ssize_t> shape     = {num_points, 3};\n    std::vector<ssize_t> strides   = {soreal*3, soreal};\n    // return 2-D NumPy array\n    return py::array(py::buffer_info(\n        circumcenters.data(),                    /* data as contiguous array  */\n        sizeof(double),                          /* size of one scalar        */\n        py::format_descriptor<double>::format(), /* data type                 */\n        2,                                       /* number of dimensions      */\n        shape,                                   /* shape of the matrix       */\n        strides                                  /* strides for each axis     */\n  ));\n}\n\npy::array circumballs3(py::array_t<double, py::array::c_style | py::array::forcecast> vertices)\n{\n    // each triangle has 4 vertices with 3 coordinates each\n    int sz = vertices.size();\n    std::vector<double> cppvertices(sz);\n    std::memcpy(cppvertices.data(),vertices.data(),sz*sizeof(double));\n    std::vector<double> circumcenters = c_circumballs3(cppvertices);\n    ssize_t              soreal      = sizeof(double);\n    ssize_t              num_points = circumcenters.size()/4;\n    ssize_t              ndim      = 2;\n    std::vector<ssize_t> shape     = {num_points, 4};\n    std::vector<ssize_t> strides   = {soreal*4, soreal};\n    // return 2-D NumPy array\n    return py::array(py::buffer_info(\n        circumcenters.data(),                    /* data as contiguous array  */\n        sizeof(double),                          /* size of one scalar        */\n        py::format_descriptor<double>::format(), /* data type                 */\n        2,                                       /* number of dimensions      */\n        shape,                                   /* shape of the matrix       */\n        strides                                  /* strides for each axis     */\n  ));\n}\n\n\npy::array delaunay2(py::array_t<double, py::array::c_style | py::array::forcecast> x,\n                    py::array_t<double, py::array::c_style | py::array::forcecast> y)\n{\n\n  // check input dimensions\n  if ( x.ndim() != 1 )\n    throw std::runtime_error(\"Input should be 2 1D NumPy arrays\");\n  if ( y.ndim() != 1 )\n    throw std::runtime_error(\"Input should be 2 1D NumPy arrays\");\n\n  int num_points = x.shape()[0];\n\n  // allocate std::vector (to pass to the C++ function)\n  std::vector<double> cppx(num_points);\n  std::vector<double> cppy(num_points);\n\n  // copy py::array -> std::vector\n  std::memcpy(cppx.data(),x.data(),num_points*sizeof(double));\n  std::memcpy(cppy.data(),y.data(),num_points*sizeof(double));\n  std::vector<int> faces = c_delaunay2(cppx, cppy);\n\n  ssize_t              soint      = sizeof(int);\n  ssize_t              num_faces = faces.size()/3;\n  ssize_t              ndim      = 2;\n  std::vector<ssize_t> shape     = {num_faces, 3};\n  std::vector<ssize_t> strides   = {soint*3, soint};\n\n  // return 2-D NumPy array\n  return py::array(py::buffer_info(\n    faces.data(),                           /* data as contiguous array  */\n    sizeof(int),                          /* size of one scalar        */\n    py::format_descriptor<int>::format(), /* data type                 */\n    2,                                    /* number of dimensions      */\n    shape,                                   /* shape of the matrix       */\n    strides                                  /* strides for each axis     */\n  ));\n}\n\n\npy::array delaunay3(py::array_t<double, py::array::c_style | py::array::forcecast> x,\n                    py::array_t<double, py::array::c_style | py::array::forcecast> y,\n                    py::array_t<double, py::array::c_style | py::array::forcecast> z)\n{\n\n  // check input dimensions\n  if ( x.ndim() != 1 )\n    throw std::runtime_error(\"Input should be three 1D NumPy arrays\");\n  if ( y.ndim() != 1 )\n    throw std::runtime_error(\"Input should be three 1D NumPy arrays\");\n  if ( z.ndim() != 1 )\n    throw std::runtime_error(\"Input should be three 1D NumPy arrays\");\n\n  int num_points = x.shape()[0];\n\n  // allocate std::vector (to pass to the C++ function)\n  std::vector<double> cppx(num_points);\n  std::vector<double> cppy(num_points);\n  std::vector<double> cppz(num_points);\n\n  // copy py::array -> std::vector\n  std::memcpy(cppx.data(),x.data(),num_points*sizeof(double));\n  std::memcpy(cppy.data(),y.data(),num_points*sizeof(double));\n  std::memcpy(cppz.data(),z.data(),num_points*sizeof(double));\n  std::vector<int> cells = c_delaunay3(cppx, cppy, cppz);\n\n  ssize_t              num_cells = cells.size()/4;\n  ssize_t              ndim      = 2;\n  ssize_t              soint      = sizeof(int);\n  std::vector<ssize_t> shape     = {num_cells, 4};\n  std::vector<ssize_t> strides   = {soint*4, soint};\n\n  // return 2-D NumPy array\n  return py::array(py::buffer_info(\n    cells.data(),                           /* data as contiguous array  */\n    sizeof(int),                          /* size of one scalar        */\n    py::format_descriptor<int>::format(), /* data type                 */\n    2,                                    /* number of dimensions      */\n    shape,                                   /* shape of the matrix       */\n    strides                                  /* strides for each axis     */\n  ));\n}\n\n\n\nPYBIND11_MODULE(c_cgal, m) {\n    m.def(\"circumballs3\", &circumballs3);\n    m.def(\"circumballs2\", &circumballs2);\n    m.def(\"delaunay2\", &delaunay2);\n    m.def(\"delaunay3\", &delaunay3);\n}\n", "meta": {"hexsha": "7e330558cb8a5669a40540229ecad7b4b9475769", "size": 11229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SeismicMesh/generation/cpp/delaunay.cpp", "max_stars_repo_name": "WPringle/SeismicMesh", "max_stars_repo_head_hexsha": "9e73aac63ecc4411163dc4093941af946cffae37", "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": "SeismicMesh/generation/cpp/delaunay.cpp", "max_issues_repo_name": "WPringle/SeismicMesh", "max_issues_repo_head_hexsha": "9e73aac63ecc4411163dc4093941af946cffae37", "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": "SeismicMesh/generation/cpp/delaunay.cpp", "max_forks_repo_name": "WPringle/SeismicMesh", "max_forks_repo_head_hexsha": "9e73aac63ecc4411163dc4093941af946cffae37", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9358108108, "max_line_length": 101, "alphanum_fraction": 0.580105085, "num_tokens": 2937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6323110798921961}}
{"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <array>\n//#include <boost/multiprecision/cpp_int.hpp>\n// using namespace boost::multiprecision;\nconst int mx = 1e6 + 5;\nusing ll = int64_t;\n\nstd::array<ll, mx> parent;\nll node, edge;\nstd::vector<std::pair<ll, std::pair<ll, ll>>> edges;\nvoid initial() {\n    for (int i = 0; i < node + edge; ++i) {\n      parent[i] = i;\n    }\n}\n\nint root(int i) {\n    while (parent[i] != i) {\n        parent[i] = parent[parent[i]];\n        i = parent[i];\n    }\n    return i;\n}\n\nvoid join(int x, int y) {\n    int root_x = root(x);  // Disjoint set union by rank\n    int root_y = root(y);\n    parent[root_x] = root_y;\n}\n\nll kruskal() {\n    ll mincost = 0;\n    for (int i = 0; i < edge; ++i) {\n        ll x = edges[i].second.first;\n        ll y = edges[i].second.second;\n        if (root(x) != root(y)) {\n            mincost += edges[i].first;\n            join(x, y);\n        }\n    }\n    return mincost;\n}\n\nint main() {\n    while (true) {\n        int from = 0, to = 0, cost = 0, totalcost = 0;\n        std::cin >> node >> edge;  // Enter the nodes and edges\n        if (node == 0 && edge == 0) {\n            break;  // Enter 0 0 to break out\n        }\n        initial();  // Initialise the parent array\n        for (int i = 0; i < edge; ++i) {\n            std::cin >> from >> to >> cost;\n            edges.emplace_back(make_pair(cost, std::make_pair(from, to)));\n            totalcost += cost;\n        }\n        sort(edges.begin(), edges.end());\n        std::cout << kruskal() << std::endl;\n        edges.clear();\n    }\n    return 0;\n}\n", "meta": {"hexsha": "e179131a1b36ac1db7ba7367256c0c440a084051", "size": 1582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graph/kruskal.cpp", "max_stars_repo_name": "Krishnapal4050/C-Plus-Plus", "max_stars_repo_head_hexsha": "9fc628d358a971a04e249392386549c448ae627a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-04T11:25:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T11:25:46.000Z", "max_issues_repo_path": "graph/kruskal.cpp", "max_issues_repo_name": "Krishnapal4050/C-Plus-Plus", "max_issues_repo_head_hexsha": "9fc628d358a971a04e249392386549c448ae627a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graph/kruskal.cpp", "max_forks_repo_name": "Krishnapal4050/C-Plus-Plus", "max_forks_repo_head_hexsha": "9fc628d358a971a04e249392386549c448ae627a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-13T08:47:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-13T08:47:49.000Z", "avg_line_length": 24.3384615385, "max_line_length": 74, "alphanum_fraction": 0.512642225, "num_tokens": 463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6323107705495996}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2002, 2003 Ferdinando Ametrano\n Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl\n Copyright (C) 2010 Kakhkhor Abdijalilov\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file normaldistribution.hpp\n    \\brief normal, cumulative and inverse cumulative distributions\n*/\n\n#ifndef quantlib_normal_distribution_hpp\n#define quantlib_normal_distribution_hpp\n\n#include <ql/math/errorfunction.hpp>\n#include <ql/errors.hpp>\n#include <ql/math/comparison.hpp>\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n\n#include <boost/math/distributions/normal.hpp>\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\nnamespace QuantLib {\n\n    //! Normal distribution function\n    /*! Given x, it returns its probability in a Gaussian normal distribution.\n        It provides the first derivative too.\n\n        \\test the correctness of the returned value is tested by\n              checking it against numerical calculations. Cross-checks\n              are also performed against the\n              CumulativeNormalDistribution and InverseCumulativeNormal\n              classes.\n    */\n    class NormalDistribution : public std::unary_function<Real,Real> {\n      public:\n        NormalDistribution(Real average = 0.0,\n                           Real sigma = 1.0);\n        // function\n        Real operator()(Real x) const;\n        Real derivative(Real x) const;\n      private:\n        Real average_, sigma_, normalizationFactor_, denominator_,\n            derNormalizationFactor_;\n    };\n\n    typedef NormalDistribution GaussianDistribution;\n\n\n    //! Cumulative normal distribution function\n    /*! Given x it provides an approximation to the\n        integral of the gaussian normal distribution:\n        formula here ...\n\n        For this implementation see M. Abramowitz and I. Stegun,\n        Handbook of Mathematical Functions,\n        Dover Publications, New York (1972)\n    */\n    class CumulativeNormalDistribution\n    : public std::unary_function<Real,Real> {\n      public:\n        CumulativeNormalDistribution(Real average = 0.0,\n                                     Real sigma   = 1.0);\n        // function\n        Real operator()(Real x) const;\n        Real derivative(Real x) const;\n      private:\n        Real average_, sigma_;\n        NormalDistribution gaussian_;\n        ErrorFunction errorFunction_;\n    };\n\n\n    //! Inverse cumulative normal distribution function\n    /*! Given x between zero and one as\n      the integral value of a gaussian normal distribution\n      this class provides the value y such that\n      formula here ...\n\n      It use Acklam's approximation:\n      by Peter J. Acklam, University of Oslo, Statistics Division.\n      URL: http://home.online.no/~pjacklam/notes/invnorm/index.html\n\n      This class can also be used to generate a gaussian normal\n      distribution from a uniform distribution.\n      This is especially useful when a gaussian normal distribution\n      is generated from a low discrepancy uniform distribution:\n      in this case the traditional Box-Muller approach and its\n      variants would not preserve the sequence's low-discrepancy.\n\n    */\n    class InverseCumulativeNormal\n        : public std::unary_function<Real,Real> {\n      public:\n        InverseCumulativeNormal(Real average = 0.0,\n                                Real sigma   = 1.0);\n        // function\n        Real operator()(Real x) const {\n            return average_ + sigma_*standard_value(x);\n        }\n        // value for average=0, sigma=1\n        /* Compared to operator(), this method avoids 2 floating point\n           operations (we use average=0 and sigma=1 most of the\n           time). The speed difference is noticeable.\n        */\n        static Real standard_value(Real x) {\n            Real z;\n            if (x < x_low_() || x_high_() < x) {\n                z = tail_value(x);\n            } else {\n                z = x - 0.5;\n                Real r = z*z;\n                z = (((((a1_()*r+a2_())*r+a3_())*r+a4_())*r+a5_())*r+a6_())*z /\n                    (((((b1_()*r+b2_())*r+b3_())*r+b4_())*r+b5_())*r+1.0);\n            }\n\n            // The relative error of the approximation has absolute value less\n            // than 1.15e-9.  One iteration of Halley's rational method (third\n            // order) gives full machine precision.\n            // #define REFINE_TO_FULL_MACHINE_PRECISION_USING_HALLEYS_METHOD\n            #ifdef REFINE_TO_FULL_MACHINE_PRECISION_USING_HALLEYS_METHOD\n            // error (f_(z) - x) divided by the cumulative's derivative\n            const Real r = (f_(z) - x) * M_SQRT2 * M_SQRTPI * exp(0.5 * z*z);\n            //  Halley's method\n            z -= r/(1+0.5*z*r);\n            #endif\n\n            return z;\n        }\n      private:\n        /* Handling tails moved into a separate method, which should\n           make the inlining of operator() and standard_value method\n           easier. tail_value is called rarely and doesn't need to be\n           inlined.\n        */\n        static Real tail_value(Real x);\n        #if defined(QL_PATCH_SOLARIS)\n        CumulativeNormalDistribution f_;\n        #else\n        static const CumulativeNormalDistribution f_;\n        #endif\n        Real average_, sigma_;\n        // Coefficients for the rational approximation.\n        static Real a1_() { return -3.969683028665376e+01; }\n        static Real a2_() { return 2.209460984245205e+02; }\n        static Real a3_() { return -2.759285104469687e+02; }\n        static Real a4_() { return 1.383577518672690e+02; }\n        static Real a5_() { return -3.066479806614716e+01; }\n        static Real a6_() { return 2.506628277459239e+00; }\n\n        static Real b1_() { return -5.447609879822406e+01; }\n        static Real b2_() { return 1.615858368580409e+02; }\n        static Real b3_() { return -1.556989798598866e+02; }\n        static Real b4_() { return 6.680131188771972e+01; }\n        static Real b5_() { return -1.328068155288572e+01; }\n\n        static Real c1_() { return -7.784894002430293e-03; }\n        static Real c2_() { return -3.223964580411365e-01; }\n        static Real c3_() { return -2.400758277161838e+00; }\n        static Real c4_() { return -2.549732539343734e+00; }\n        static Real c5_() { return 4.374664141464968e+00; }\n        static Real c6_() { return 2.938163982698783e+00; }\n\n        static Real d1_() { return 7.784695709041462e-03; }\n        static Real d2_() { return 3.224671290700398e-01; }\n        static Real d3_() { return 2.445134137142996e+00; }\n        static Real d4_() { return 3.754408661907416e+00; }\n\n        // Limits of the approximation regions\n        static Real x_low_() { return 0.02425; }\n        static Real x_high_() { return 1.0 - x_low_(); }\n    };\n\n    // backward compatibility\n    typedef InverseCumulativeNormal InvCumulativeNormalDistribution;\n\n    //! Moro Inverse cumulative normal distribution class\n    /*! Given x between zero and one as\n        the integral value of a gaussian normal distribution\n        this class provides the value y such that\n        formula here ...\n\n        It uses Beasly and Springer approximation, with an improved\n        approximation for the tails. See Boris Moro,\n        \"The Full Monte\", 1995, Risk Magazine.\n\n        This class can also be used to generate a gaussian normal\n        distribution from a uniform distribution.\n        This is especially useful when a gaussian normal distribution\n        is generated from a low discrepancy uniform distribution:\n        in this case the traditional Box-Muller approach and its\n        variants would not preserve the sequence's low-discrepancy.\n\n        Peter J. Acklam's approximation is better and is available\n        as QuantLib::InverseCumulativeNormal\n    */\n    class MoroInverseCumulativeNormal\n    : public std::unary_function<Real,Real> {\n      public:\n        MoroInverseCumulativeNormal(Real average = 0.0,\n                                    Real sigma   = 1.0);\n        // function\n        Real operator()(Real x) const;\n      private:\n        Real average_, sigma_;\n        static Real a0_() { return 2.50662823884; }\n        static Real a1_() { return -18.61500062529; }\n        static Real a2_() { return 41.39119773534; }\n        static Real a3_() { return -25.44106049637; }\n\n        static Real b0_() { return -8.47351093090; }\n        static Real b1_() { return 23.08336743743; }\n        static Real b2_() { return -21.06224101826; }\n        static Real b3_() { return 3.13082909833; }\n\n        static Real c0_() { return 0.3374754822726147; }\n        static Real c1_() { return 0.9761690190917186; }\n        static Real c2_() { return 0.1607979714918209; }\n        static Real c3_() { return 0.0276438810333863; }\n        static Real c4_() { return 0.0038405729373609; }\n        static Real c5_() { return 0.0003951896511919; }\n        static Real c6_() { return 0.0000321767881768; }\n        static Real c7_() { return 0.0000002888167364; }\n        static Real c8_() { return 0.0000003960315187; }\n    };\n\n    //! Maddock's Inverse cumulative normal distribution class\n    /*! Given x between zero and one as\n        the integral value of a gaussian normal distribution\n        this class provides the value y such that\n        formula here ...\n\n        From the boost documentation:\n         These functions use a rational approximation devised by\n         John Maddock to calculate an initial approximation to the\n         result that is accurate to ~10^-19, then only if that has\n         insufficient accuracy compared to the epsilon for type double,\n         do we clean up the result using Halley iteration.\n    */\n    class MaddockInverseCumulativeNormal\n    : public std::unary_function<Real,Real> {\n      public:\n        MaddockInverseCumulativeNormal(Real average = 0.0,\n                                       Real sigma   = 1.0);\n        Real operator()(Real x) const;\n\n      private:\n        const Real average_, sigma_;\n    };\n\n    //! Maddock's cumulative normal distribution class\n    class MaddockCumulativeNormal : public std::unary_function<Real,Real> {\n      public:\n        MaddockCumulativeNormal(Real average = 0.0,\n                                       Real sigma   = 1.0);\n        Real operator()(Real x) const;\n\n      private:\n        const Real average_, sigma_;\n    };\n\n\n    // inline definitions\n\n    inline NormalDistribution::NormalDistribution(Real average,\n                                                  Real sigma)\n    : average_(average), sigma_(sigma) {\n\n        QL_REQUIRE(sigma_>0.0,\n                   \"sigma must be greater than 0.0 (\"\n                   << sigma_ << \" not allowed)\");\n\n        normalizationFactor_ = M_SQRT_2*M_1_SQRTPI/sigma_;\n        derNormalizationFactor_ = sigma_*sigma_;\n        denominator_ = 2.0*derNormalizationFactor_;\n    }\n\n    inline Real NormalDistribution::operator()(Real x) const {\n        Real deltax = x-average_;\n        Real exponent = -(deltax*deltax)/denominator_;\n        // debian alpha had some strange problem in the very-low range\n        return exponent <= -690.0 ? 0.0 :  // exp(x) < 1.0e-300 anyway\n            normalizationFactor_*std::exp(exponent);\n    }\n\n    inline Real NormalDistribution::derivative(Real x) const {\n        return ((*this)(x) * (average_ - x)) / derNormalizationFactor_;\n    }\n\n    inline CumulativeNormalDistribution::CumulativeNormalDistribution(\n                                                 Real average, Real sigma)\n    : average_(average), sigma_(sigma) {\n\n        QL_REQUIRE(sigma_>0.0,\n                   \"sigma must be greater than 0.0 (\"\n                   << sigma_ << \" not allowed)\");\n    }\n\n    inline Real CumulativeNormalDistribution::derivative(Real x) const {\n        Real xn = (x - average_) / sigma_;\n        return gaussian_(xn) / sigma_;\n    }\n\n    inline InverseCumulativeNormal::InverseCumulativeNormal(\n                                                 Real average, Real sigma)\n    : average_(average), sigma_(sigma) {\n\n        QL_REQUIRE(sigma_>0.0,\n                   \"sigma must be greater than 0.0 (\"\n                   << sigma_ << \" not allowed)\");\n    }\n\n    inline MoroInverseCumulativeNormal::MoroInverseCumulativeNormal(\n                                                 Real average, Real sigma)\n    : average_(average), sigma_(sigma) {\n\n        QL_REQUIRE(sigma_>0.0,\n                   \"sigma must be greater than 0.0 (\"\n                   << sigma_ << \" not allowed)\");\n    }\n\n    // implementation\n\n    inline Real CumulativeNormalDistribution::operator()(Real z) const {\n        //QL_REQUIRE(!(z >= average_ && 2.0*average_-z > average_),\n        //           \"not a real number. \");\n        z = (z - average_) / sigma_;\n\n        Real result = 0.5 * ( 1.0 + errorFunction_( z*M_SQRT_2 ) );\n        if (result<=1e-8) { //todo: investigate the threshold level\n            // Asymptotic expansion for very negative z following (26.2.12)\n            // on page 408 in M. Abramowitz and A. Stegun,\n            // Pocketbook of Mathematical Functions, ISBN 3-87144818-4.\n            Real sum=1.0, zsqr=z*z, i=1.0, g=1.0, x, y,\n                 a=QL_MAX_REAL, lasta;\n            do {\n                lasta=a;\n                x = (4.0*i-3.0)/zsqr;\n                y = x*((4.0*i-1)/zsqr);\n                a = g*(x-y);\n                sum -= a;\n                g *= y;\n                ++i;\n                a = std::fabs(a);\n            } while (lasta>a && a>=std::fabs(sum*QL_EPSILON));\n            result = -gaussian_(z)/z*sum;\n        }\n        return result;\n    }\n\n    // #if !defined(QL_PATCH_SOLARIS)\n    // const CumulativeNormalDistribution InverseCumulativeNormal::f_;\n    // #endif\n\n    inline Real InverseCumulativeNormal::tail_value(Real x) {\n        if (x <= 0.0 || x >= 1.0) {\n            // try to recover if due to numerical error\n            if (close_enough(x, 1.0)) {\n                return QL_MAX_REAL; // largest value available\n            } else if (std::fabs(x) < QL_EPSILON) {\n                return QL_MIN_REAL; // largest negative value available\n            } else {\n                QL_FAIL(\"InverseCumulativeNormal(\" << x\n                        << \") undefined: must be 0 < x < 1\");\n            }\n        }\n\n        Real z;\n        if (x < x_low_()) {\n            // Rational approximation for the lower region 0<x<u_low\n            z = std::sqrt(-2.0*std::log(x));\n            z = (((((c1_()*z+c2_())*z+c3_())*z+c4_())*z+c5_())*z+c6_()) /\n                ((((d1_()*z+d2_())*z+d3_())*z+d4_())*z+1.0);\n        } else {\n            // Rational approximation for the upper region u_high<x<1\n            z = std::sqrt(-2.0*std::log(1.0-x));\n            z = -(((((c1_()*z+c2_())*z+c3_())*z+c4_())*z+c5_())*z+c6_()) /\n                ((((d1_()*z+d2_())*z+d3_())*z+d4_())*z+1.0);\n        }\n\n        return z;\n    }\n\n    inline Real MoroInverseCumulativeNormal::operator()(Real x) const {\n        QL_REQUIRE(x > 0.0 && x < 1.0,\n                   \"MoroInverseCumulativeNormal(\" << x\n                   << \") undefined: must be 0<x<1\");\n\n        Real result;\n        Real temp=x-0.5;\n\n        if (std::fabs(temp) < 0.42) {\n            // Beasley and Springer, 1977\n            result=temp*temp;\n            result=temp*\n                (((a3_()*result+a2_())*result+a1_())*result+a0_()) /\n                ((((b3_()*result+b2_())*result+b1_())*result+b0_())*result+1.0);\n        } else {\n            // improved approximation for the tail (Moro 1995)\n            if (x<0.5)\n                result = x;\n            else\n                result=1.0-x;\n            result = std::log(-std::log(result));\n            result = c0_()+result*(c1_()+result*(c2_()+result*(c3_()+result*\n                                   (c4_()+result*(c5_()+result*(c6_()+result*\n                                                       (c7_()+result*c8_())))))));\n            if (x<0.5)\n                result=-result;\n        }\n\n        return average_ + result*sigma_;\n    }\n\n    inline MaddockInverseCumulativeNormal::MaddockInverseCumulativeNormal(\n        Real average, Real sigma)\n    : average_(average), sigma_(sigma) {}\n\n    inline Real MaddockInverseCumulativeNormal::operator()(Real x) const {\n        return boost::math::quantile(\n            boost::math::normal_distribution<Real>(average_, sigma_), x);\n    }\n\n    inline MaddockCumulativeNormal::MaddockCumulativeNormal(\n        Real average, Real sigma)\n    : average_(average), sigma_(sigma) {}\n\n    inline Real MaddockCumulativeNormal::operator()(Real x) const {\n        return boost::math::cdf(\n            boost::math::normal_distribution<Real>(average_, sigma_), x);\n    }\n    \n\n}\n\n\n#endif\n", "meta": {"hexsha": "25338bea37664afc2c02d480017fe191f3ec50ce", "size": 17468, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/distributions/normaldistribution.hpp", "max_stars_repo_name": "markxio/Quantuccia", "max_stars_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T14:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:00:52.000Z", "max_issues_repo_path": "ql/math/distributions/normaldistribution.hpp", "max_issues_repo_name": "markxio/Quantuccia", "max_issues_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-04-02T14:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T05:31:12.000Z", "max_forks_repo_path": "ql/math/distributions/normaldistribution.hpp", "max_forks_repo_name": "markxio/Quantuccia", "max_forks_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T05:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:30:20.000Z", "avg_line_length": 38.0566448802, "max_line_length": 87, "alphanum_fraction": 0.5901076254, "num_tokens": 4412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6323107660039723}}
{"text": "// Copyright 2010 Gunter Winkler <guwi17@gmx.de>\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <complex>\n\n#include \"libs/numeric/ublas/test/utils.hpp\"\n\nusing namespace boost::numeric::ublas;\n\nstatic const double TOL(1.0e-5); ///< Used for comparing two real numbers.\n\nBOOST_UBLAS_TEST_DEF ( test_double_complex_norm_inf ) {\n    typedef std::complex<double> dComplex;\n    vector<dComplex> v(4);\n    for (unsigned int i = 0; i < v.size(); ++i)\n        v[i] = dComplex(i, i + 1);\n\n    const double expected = abs(v[3]);\n\n    BOOST_UBLAS_DEBUG_TRACE( \"norm is \" << norm_inf(v) );\n    BOOST_UBLAS_TEST_CHECK(std::abs(norm_inf(v) - expected) < TOL);\n    v *= 3.;\n    BOOST_UBLAS_TEST_CHECK(std::abs(norm_inf(v) - (3.0*expected)) < TOL);\n}\n\nBOOST_UBLAS_TEST_DEF ( test_double_complex_norm_2 ) {\n    typedef std::complex<double> dComplex;\n    vector<dComplex> v(4);\n    for (unsigned int i = 0; i < v.size(); ++i)\n        v[i] = dComplex(i, i + 1);\n\n    const double expected = sqrt(44.0);\n\n    BOOST_UBLAS_DEBUG_TRACE( \"norm is \" << norm_2(v) );\n    BOOST_UBLAS_TEST_CHECK(std::abs(norm_2(v) - expected) < TOL);\n    v *= 3.;\n    BOOST_UBLAS_TEST_CHECK(std::abs(norm_2(v) - (3.0*expected)) < TOL);\n}\n\nBOOST_UBLAS_TEST_DEF ( test_float_complex_norm_inf ) {\n    typedef std::complex<float> dComplex;\n    vector<dComplex> v(4);\n    for (unsigned int i = 0; i < v.size(); ++i)\n        v[i] = dComplex(i, i + 1);\n\n    const float expected = abs(v[3]);\n\n    BOOST_UBLAS_DEBUG_TRACE( \"norm is \" << norm_inf(v) );\n    BOOST_UBLAS_TEST_CHECK(std::abs(norm_inf(v) - expected) < TOL);\n    v *= 3.;\n    BOOST_UBLAS_TEST_CHECK(std::abs(norm_inf(v) - (3.0*expected)) < TOL);\n}\n\nBOOST_UBLAS_TEST_DEF ( test_float_complex_norm_2 ) {\n    typedef std::complex<float> dComplex;\n    vector<dComplex> v(4);\n    for (unsigned int i = 0; i < v.size(); ++i)\n        v[i] = dComplex(i, i + 1);\n\n    const double expected = sqrt(44.0);\n\n    BOOST_UBLAS_DEBUG_TRACE( \"norm is \" << norm_2(v) );\n    BOOST_UBLAS_TEST_CHECK(std::abs(norm_2(v) - expected) < TOL);\n    v *= 3.;\n    BOOST_UBLAS_TEST_CHECK(std::abs(norm_2(v) - (3.0*expected)) < TOL);\n}\n\nint main() {\n    BOOST_UBLAS_TEST_BEGIN();\n\n    BOOST_UBLAS_TEST_DO( test_double_complex_norm_inf );\n    BOOST_UBLAS_TEST_DO( test_float_complex_norm_inf );\n    BOOST_UBLAS_TEST_DO( test_double_complex_norm_2 );\n    BOOST_UBLAS_TEST_DO( test_float_complex_norm_2 );\n\n    BOOST_UBLAS_TEST_END();\n}\n", "meta": {"hexsha": "dcd37e58d8b0830a335348069c9dbe5f859c58eb", "size": 2652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/test/test_complex_norms.cpp", "max_stars_repo_name": "cdaniels/boost_1_57_0", "max_stars_repo_head_hexsha": "94d381dbcc731b9c69aababcfe89adc6a4ba20f0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-11-02T07:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T19:56:59.000Z", "max_issues_repo_path": "libs/numeric/ublas/test/test_complex_norms.cpp", "max_issues_repo_name": "cdaniels/boost_1_57_0", "max_issues_repo_head_hexsha": "94d381dbcc731b9c69aababcfe89adc6a4ba20f0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-18T21:24:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-11T12:39:57.000Z", "max_forks_repo_path": "libs/numeric/ublas/test/test_complex_norms.cpp", "max_forks_repo_name": "cdaniels/boost_1_57_0", "max_forks_repo_head_hexsha": "94d381dbcc731b9c69aababcfe89adc6a4ba20f0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-02T14:11:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-20T13:42:13.000Z", "avg_line_length": 31.9518072289, "max_line_length": 74, "alphanum_fraction": 0.6674208145, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6323107606434433}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <gtest/gtest.h>\n\n#ifdef STAN_OPENCL\n#include <stan/math/opencl/opencl.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#endif\n\n#define EXPECT_MATRIX_NEAR(A, B, DELTA) \\\n  for (int i = 0; i < A.size(); i++)    \\\n    EXPECT_NEAR(A(i), B(i), DELTA);\n\nTEST(MathMatrix, mdivide_right_tri_val) {\n  using stan::math::mdivide_right_tri;\n  stan::math::matrix_d Ad(2, 2);\n  stan::math::matrix_d I;\n\n  Ad << 2.0, 0.0, 5.0, 7.0;\n\n  I = mdivide_right_tri<Eigen::Lower>(Ad, Ad);\n  EXPECT_NEAR(1.0, I(0, 0), 1.0E-12);\n  EXPECT_NEAR(0.0, I(0, 1), 1.0E-12);\n  EXPECT_NEAR(0.0, I(1, 0), 1.0E-12);\n  EXPECT_NEAR(1.0, I(1, 1), 1.0e-12);\n\n  Ad << 2.0, 3.0, 0.0, 7.0;\n\n  I = mdivide_right_tri<Eigen::Upper>(Ad, Ad);\n  EXPECT_NEAR(1.0, I(0, 0), 1.0E-12);\n  EXPECT_NEAR(0.0, I(0, 1), 1.0E-12);\n  EXPECT_NEAR(0.0, I(1, 0), 1.0E-12);\n  EXPECT_NEAR(1.0, I(1, 1), 1.0e-12);\n}\n\n#ifdef STAN_OPENCL\n\nvoid mdivide_right_tri_cl_test(int size) {\n  boost::random::mt19937 rng;\n  stan::math::matrix_d m1(size, size);\n  for (int i = 0; i < size; i++) {\n    for (int j = 0; j < i; j++) {\n      m1(i, j) = stan::math::uniform_rng(-5, 5, rng);\n    }\n    m1(i, i) = 20.0;\n    for (int j = i + 1; j < size; j++) {\n      m1(i, j) = 0.0;\n    }\n  }\n\n  stan::math::opencl_context.tuning_opts().tri_inverse_size_worth_transfer\n      = size * 2;\n\n  stan::math::matrix_d m1_cpu\n      = stan::math::mdivide_right_tri<Eigen::Lower>(m1, m1);\n\n  stan::math::opencl_context.tuning_opts().tri_inverse_size_worth_transfer = 0;\n\n  stan::math::matrix_d m1_cl\n      = stan::math::mdivide_right_tri<Eigen::Lower>(m1, m1);\n\n  EXPECT_MATRIX_NEAR(m1_cpu, m1_cl, 1E-8);\n}\nTEST(MathMatrixCL, mdivide_right_tri_cl_small) { mdivide_right_tri_cl_test(3); }\nTEST(MathMatrixCL, mdivide_right_tri_cl_mid) { mdivide_right_tri_cl_test(100); }\nTEST(MathMatrixCL, mdivide_right_tri_cl_big) { mdivide_right_tri_cl_test(500); }\n#endif\n", "meta": {"hexsha": "6190c5522570ca596467fabb123e7bd39ea1c654", "size": 1902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/mat/fun/mdivide_right_tri_test.cpp", "max_stars_repo_name": "PhilClemson/math", "max_stars_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/prim/mat/fun/mdivide_right_tri_test.cpp", "max_issues_repo_name": "PhilClemson/math", "max_issues_repo_head_hexsha": "fffe604a7ead4525be2551eb81578c5f351e5c87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "archive/math/test/unit/math/prim/mat/fun/mdivide_right_tri_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3880597015, "max_line_length": 80, "alphanum_fraction": 0.6451104101, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6323107602359924}}
{"text": "/*\n * PolynomialSpline.hpp\n *\n *  Created on: Mar 7, 2017\n *      Author: Dario Bellicoso\n */\n\n#pragma once\n\n// eigen\n#include <Eigen/Core>\n\n// curves\n#include \"curves/polynomial_splines_traits.hpp\"\n\n// stl\n#include <numeric>\n\nnamespace curves {\n\n/*!\n *  This class is the implementation of a scalar polynomial spline s(t) function of a scalar t.\n *  The spline is define as\n *    s(t) = an*t^n + ... + a1*t + a0 = sum(ai*t^i)\n *\n *  The spline coefficients are stored in a standard container as\n *    alpha = [an ... a1 a0]^T\n *\n *  The spline can also be evaluated as:\n *    s(t) = tau^T * alpha\n *\n *  where the vector tau (referred to as time vector in the comments) is define as\n *    tau = [t^n ... t^2 t 1]^T\n */\ntemplate <int splineOrder_>\nclass PolynomialSpline {\n public:\n\n  static constexpr unsigned int splineOrder = splineOrder_;\n  static constexpr unsigned int coefficientCount = splineOrder + 1;\n\n  using SplineImplementation = spline_traits::spline_rep<double, splineOrder>;\n  using SplineCoefficients = typename SplineImplementation::SplineCoefficients;\n  using EigenTimeVectorType = Eigen::Matrix<double, 1, coefficientCount>;\n  using EigenCoefficientVectorType = Eigen::Matrix<double, coefficientCount, 1>;\n\n  PolynomialSpline() :\n    duration_(0.0),\n    didEvaluateCoeffs_(false),\n    coefficients_()\n  {\n\n  }\n\n  template<typename SplineCoeff_>\n  PolynomialSpline(SplineCoeff_&& coefficients, double duration) :\n    duration_(duration),\n    didEvaluateCoeffs_(true),\n    coefficients_(std::forward<SplineCoeff_>(coefficients))\n  {\n\n  }\n\n  explicit PolynomialSpline(const SplineOptions& options) : duration_(options.tf_) {\n    computeCoefficients(options);\n  }\n\n  explicit PolynomialSpline(SplineOptions&& options) : duration_(options.tf_) {\n    computeCoefficients(std::move(options));\n  }\n\n  virtual ~PolynomialSpline() = default;\n\n  PolynomialSpline(PolynomialSpline &&) = default;\n  PolynomialSpline& operator=(PolynomialSpline &&) = default;\n\n  PolynomialSpline(const PolynomialSpline&) = default;\n  PolynomialSpline& operator=(const PolynomialSpline&) = default;\n\n  //! Get the coefficients of the spline.\n  const SplineCoefficients& getCoefficients() const {\n    return coefficients_;\n  }\n\n  //! Get the coefficients of the spline.\n  SplineCoefficients* getCoefficientsPtr() {\n    return &coefficients_;\n  }\n\n  //! Compute the coefficients of the spline.\n  template<typename SplineOptionsType_>\n  bool computeCoefficients(SplineOptionsType_&& options) {\n    duration_ = options.tf_;\n    return SplineImplementation::compute(std::forward<SplineOptionsType_>(options), coefficients_);\n  }\n\n  //! Set the coefficients and the duration of the spline.\n  void setCoefficientsAndDuration(const SplineCoefficients& coefficients, double duration) {\n    coefficients_ = coefficients;\n    duration_ = duration;\n  }\n\n  //! Get the spline evaluated at time tk.\n  constexpr double getPositionAtTime(double tk) const {\n    return std::inner_product(coefficients_.begin(), coefficients_.end(),\n                              SplineImplementation::tau(tk).begin(), 0.0);\n  }\n\n  //! Get the first derivative of the spline evaluated at time tk.\n  constexpr double getVelocityAtTime(double tk) const {\n    return std::inner_product(coefficients_.begin(), coefficients_.end(),\n                              SplineImplementation::dtau(tk).begin(), 0.0);\n  }\n\n  //! Get the second derivative of the spline evaluated at time tk.\n  constexpr double getAccelerationAtTime(double tk) const {\n    return std::inner_product(coefficients_.begin(), coefficients_.end(),\n                              SplineImplementation::ddtau(tk).begin(), 0.0);\n  }\n\n\n\n\n  //! Get the time vector evaluated at time tk.\n  static inline void getTimeVector(Eigen::Ref<EigenTimeVectorType> timeVec, const double tk) {\n    timeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::tau(tk).data());\n  }\n\n  //! Get the time vector evaluated at time tk.\n  template<typename Derived>\n  static inline void getTimeVector(Eigen::MatrixBase<Derived> const & timeVec, const double tk) {\n    assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(timeVec) =\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tau(tk)).data());\n  }\n\n  //! Get the time vector evaluated at time tk and add it to the input vector.\n  template<typename Derived>\n  static inline void addTimeVector(Eigen::MatrixBase<Derived> const & timeVec, const double tk) {\n    assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(timeVec) +=\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tau(tk)).data());\n  }\n\n\n\n\n  //! Get the first derivative of the time vector evaluated at time tk.\n  static inline void getDTimeVector(Eigen::Ref<EigenTimeVectorType> dtimeVec, const double tk) {\n    dtimeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::dtau(tk).data());\n  }\n\n  //! Get the first derivative of the time vector evaluated at time tk.\n  template<typename Derived>\n  static inline void getDiffTimeVector(Eigen::MatrixBase<Derived> const & dtimeVec, const double tk) {\n    assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) =\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtau(tk)).data());\n  }\n\n  //! Get the first derivative of the time vector evaluated at time tk and add it to the input vector.\n  template<typename Derived>\n  static inline void addDiffTimeVector(Eigen::MatrixBase<Derived> const & dtimeVec, const double tk) {\n    assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) +=\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtau(tk)).data());\n  }\n\n\n\n  //! Get the second derivative of the time vector evaluated at time tk.\n  static inline void getDDTimeVector(Eigen::Ref<EigenTimeVectorType> ddtimeVec, const double tk) {\n    ddtimeVec = Eigen::Map<EigenTimeVectorType>(SplineImplementation::ddtau(tk).data());\n  }\n\n  //! Get the second derivative of the time vector evaluated at time tk.\n  template<typename Derived>\n  static inline void getDDiffTimeVector(Eigen::MatrixBase<Derived> const & ddtimeVec, const double tk) {\n    assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) =\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtau(tk)).data());\n  }\n\n  //! Get the second derivative of the time vector evaluated at time tk and add it to the input vector.\n  template<typename Derived>\n  static inline void addDDiffTimeVector(Eigen::MatrixBase<Derived> const & ddtimeVec, const double tk) {\n    assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) +=\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtau(tk)).data());\n  }\n\n\n\n  //! Get the time vector evaluated at zero.\n  static inline void getTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> timeVec) {\n    timeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tauZero).data());\n  }\n\n  //! Get the time vector evaluated at zero.\n  template<typename Derived>\n  static inline void getTimeVectorAtZero(\n      Eigen::MatrixBase<Derived> const & timeVec) {\n    assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(timeVec) =\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tauZero).data());\n  }\n\n  //! Get the time vector evaluated at zero.\n  template<typename Derived>\n  static inline void addTimeVectorAtZero(\n      Eigen::MatrixBase<Derived> const & timeVec) {\n    assert(timeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           timeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(timeVec) +=\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::tauZero).data());\n  }\n\n\n\n\n  //! Get the first derivative of the time vector evaluated at zero.\n  static inline void getDTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> dtimeVec) {\n    dtimeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtauZero).data());\n  }\n\n  //! Get the time vector evaluated at zero.\n  template<typename Derived>\n  static inline void getDiffTimeVectorAtZero(\n      Eigen::MatrixBase<Derived> const & dtimeVec) {\n    assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) =\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtauZero).data());\n  }\n\n  //! Get the time vector evaluated at zero.\n  template<typename Derived>\n  static inline void addDiffTimeVectorAtZero(\n      Eigen::MatrixBase<Derived> const & dtimeVec) {\n    assert(dtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           dtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(dtimeVec) +=\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::dtauZero).data());\n  }\n\n\n  //! Get the second derivative of the time vector evaluated at zero.\n  static inline void getDDTimeVectorAtZero(Eigen::Ref<EigenTimeVectorType> ddtimeVec) {\n    ddtimeVec = Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtauZero).data());\n  }\n\n  //! Get the time vector evaluated at zero.\n  template<typename Derived>\n  static inline void getDDiffTimeVectorAtZero(\n      Eigen::MatrixBase<Derived> const & ddtimeVec) {\n    assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) =\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtauZero).data());\n  }\n\n  //! Get the time vector evaluated at zero.\n  template<typename Derived>\n  static inline void addDDiffTimeVectorAtZero(\n      Eigen::MatrixBase<Derived> const & ddtimeVec) {\n    assert(ddtimeVec.rows() == EigenTimeVectorType::RowsAtCompileTime &&\n           ddtimeVec.cols() == EigenTimeVectorType::ColsAtCompileTime);\n    // https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html\n    const_cast<Eigen::MatrixBase<Derived>&>(ddtimeVec) +=\n        Eigen::Map<const EigenTimeVectorType>((SplineImplementation::ddtauZero).data());\n  }\n\n  //! Get the duration of the spline in seconds.\n  double getSplineDuration() const {\n    return duration_;\n  }\n\n protected:\n  //! The duration of the spline in seconds.\n  double duration_;\n\n  //! True if the coefficents were computed at least once.\n  bool didEvaluateCoeffs_;\n\n  /*\n   * s(t) = an*t^n + ... + a1*t + a0\n   * splineCoeff_ = [an ... a1 a0]\n   */\n  SplineCoefficients coefficients_;\n};\n\n} /* namespace */\n", "meta": {"hexsha": "4160ee93f13537e6dbb82ddacbabcbd9a5fe6a02", "size": 12275, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "curves/include/curves/PolynomialSpline.hpp", "max_stars_repo_name": "leggedrobotics/curves", "max_stars_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "curves/include/curves/PolynomialSpline.hpp", "max_issues_repo_name": "leggedrobotics/curves", "max_issues_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "curves/include/curves/PolynomialSpline.hpp", "max_forks_repo_name": "leggedrobotics/curves", "max_forks_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_forks_repo_licenses": ["BSD-3-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.4694533762, "max_line_length": 104, "alphanum_fraction": 0.7224439919, "num_tokens": 3002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587159, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6321510517517224}}
{"text": "#pragma once\n#include <Eigen/Core>\n\n//! The gradient of the shape function (on the reference element)\n//!\n//! We have three shape functions\n//!\n//! @param i integer between 0 and 2 (inclusive). Decides which shape function to return.\n//! @param x x coordinate in the reference element.\n//! @param y y coordinate in the reference element.\ninline Eigen::Vector2d gradientLambda(const int i, double x, double y) {\n\t// (write your solution here)\n\treturn Eigen::Vector2d(0, 0); //remove when implemented\n}\n", "meta": {"hexsha": "06822f8fa3dcbe5234f5ce3e28e5c7b8981469ab", "size": 501, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_warmup/2d-poissonlFEM/grad_shape.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series2_warmup/2d-poissonlFEM/grad_shape.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series2_warmup/2d-poissonlFEM/grad_shape.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4, "max_line_length": 89, "alphanum_fraction": 0.7245508982, "num_tokens": 119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6321510316885586}}
{"text": "#include <Rcpp.h>\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <igl/volume.h>\n#include <Eigen/Core>\nusing namespace Rcpp;\n\n  \n  // [[Rcpp::export]]\ndouble mesh_volume(NumericMatrix Vi, NumericMatrix Fi) {\n  \n\n  int V_nrow = Vi.nrow(), F_nrow = Fi.nrow();\n  int V_ncol = Vi.ncol(), F_ncol = Fi.ncol();\n  \n  // std::cout << VA_nrow << \"\\t\" << VA_ncol << \"\\t\" << VB_nrow << \"\\t\" << VB_ncol << \"\\t\" << FA_nrow << \"\\t\" << FA_ncol << \"\\t\" << FB_nrow << \"\\t\" << FB_ncol << \"\\n\" ; \n \n\n  Eigen::MatrixXd V(V_nrow,V_ncol);\n  Eigen::MatrixXi F(F_nrow,F_ncol);\n\n  for(int i=0; i < V_nrow; i++){\n    for(int j=0; j< V_ncol; j++){\n      V(i,j) = Vi(i,j);\n    }\n  }\n\n  \n  for(int i=0; i < F_nrow; i++){\n    for(int j=0; j< F_ncol; j++){\n      F(i,j) = Fi(i,j);\n    }\n  }\n\n  Eigen::MatrixXd V2(V.rows() + 1, V.cols());\n  V2.topRows(V.rows()) = V;\n  V2.bottomRows(1).setZero();\n  Eigen::MatrixXi T(F.rows(), 4);\n  T.leftCols(3) = F;\n  T.rightCols(1).setConstant(V.rows());\n  Eigen::VectorXd vol;\n  igl::volume(V2, T, vol);\n\n  return std::abs( vol.sum());\n  }", "meta": {"hexsha": "c10c1e07f893244c988bac639b6929fe4ef261f2", "size": 1061, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mesh_volume_R.cpp", "max_stars_repo_name": "pkm304/density_moving_window", "max_stars_repo_head_hexsha": "70712164a9269bc3aa6fc7db0021edf1809dbe33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mesh_volume_R.cpp", "max_issues_repo_name": "pkm304/density_moving_window", "max_issues_repo_head_hexsha": "70712164a9269bc3aa6fc7db0021edf1809dbe33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mesh_volume_R.cpp", "max_forks_repo_name": "pkm304/density_moving_window", "max_forks_repo_head_hexsha": "70712164a9269bc3aa6fc7db0021edf1809dbe33", "max_forks_repo_licenses": ["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.0652173913, "max_line_length": 169, "alphanum_fraction": 0.5504241282, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392797, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6320740598197232}}
{"text": "/**\n * @file systemode_main.cc\n * @brief NPDE homework SystemODE\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n\n#include \"../../../lecturecodes/helperfiles/polyfit.h\"\n#include \"systemode.h\"\n\n/* SAM_LISTING_BEGIN_0 */\nint main() {\n  // PARAMETERS\n  double T = 1;\n  int n = 5;\n\n  // INITIAL VALUE\n  Eigen::VectorXd y0(2 * n);\n  for (int i = 0; i < n; ++i) {\n    y0(i) = (i + 1.) / n;\n    y0(i + n) = -1;\n  }\n\n  // SETUP\n  double conv_rate = 0;\n  std::cout << std::setw(8) << \"M\" << std::setw(20) << \"Error\" << std::endl;\n\n  //====================\n  // Your code goes here\n  // apply the classical Runge-Kutta method of order 4 to solve a particular initial value problem \n  // for the ODE derivide in problem a. \n\n\n  // build the tridiagonal C matrix \n  Eigen::SparseMatrix<double> C(n,n); \n  C.reserve(Eigen::VectorXi::Contant(n,3)); \n  C.insert(0,0)=2; \n  for (int i=1; i<n; i++){\n    C.insert(i,i)=2; \n    C.insert(i-1,i)=-1;\n    C.insert(i,i-1)=-1; \n  }\n  C.compress();\n\n\n  // compute the right-hand side f \n  auto f [n,C] (Eigen::VectorXi y) {\n\n    Eigen::VectorXd fy(2*n); \n    fy.head(n) = y.tail(n); \n    //compute r\n    Eigen::VectorXd r(n); \n    r.insert(0) = y(0) *(y(0)+y(1)); \n    r.insert(n-1) = y(n-1)*(y(n-1)+y(n-1)); \n    for (int i=1; i<n-1; i++){\n      r.insert(i) = y(i)*(y(i-1)+y(i+1)); \n    }\n    Eigen::SparseLU <Eigen::SparseMatrix <double>>csolver; \n    csolver.compute(C); \n    fy.tail(n) = csolver.solve(C); \n    return fy; \n  }\n\n  // compute the exact solution \n  //use N = 2^12 steps to calculate an approximate exact solution \n  int stepNum = std::pow(2,12); \n  double h = T/stepNum; \n  Eigen::VectorXd y_init; \n  Eigen::VectorXd y_exact; \n  y_init=y0; \n\n  for (int i= 1; i<stepNum; i++){\n    y_exact = SystemODE::rk4step(f, h, y_init); \n    y_init = y_exact; \n  }\n\n  // calculate solution using N = 2, 2^2, 2^3, ....., 2^10 timesteps \n  kmax = 10; \n  Eigen::VectorXd Error(kmax); \n  for (int k=1;k< kmax+1; k++){\n    int stepNum2 = std::pow(2,k); \n    doubel h_2 = T/stepNum2; \n    Eigen::VectorXd Y_init; \n    Eigen::VectorXd Y_exact; \n    Y_init=y0; \n\n    for (int i=1; i<stepNum2; i++){\n      Y_exact = SystemODE::rk4step(f,h_2, Y_init); \n      Y_init = Y_exact; \n    }\n\n    Error(k) = (Y_exact-y_exact).norm();\n  }\n\n  // \n  //====================\n\n  std::cout << \"Convergence rate: \" << std::round(std::abs(conv_rate))\n            << std::endl;\n\n  return 0;\n}\n/* SAM_LISTING_END_0 */\n", "meta": {"hexsha": "95f2c299e9e5358a5a52a9efd34cef688f1919f7", "size": 2546, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/SystemODE/mysolution/systemode_main.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/SystemODE/mysolution/systemode_main.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/SystemODE/mysolution/systemode_main.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1454545455, "max_line_length": 99, "alphanum_fraction": 0.5659858602, "num_tokens": 875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7401743735019594, "lm_q1q2_score": 0.6320443424448735}}
{"text": "#pragma once\n\n#include \"../PolynomialBasisGen.hh\"\n#include \"RBFKernel.hh\"\n#include \"FiniteDifferentiator.hh\"\n#include <Eigen/Dense>\n#include <boost/tuple/tuple.hpp>\n#include <boost/static_assert.hpp>\n#include <vector>\n\nnamespace kt84 {\n\ntemplate <int _DimIn, int _DimOut, class _RBFKernel_Core, int _DegreePolynomial>\nstruct HermiteRBF\n    : public FiniteDifferentiator<HermiteRBF<_DimIn, _DimOut, _RBFKernel_Core, _DegreePolynomial>, _DimIn, _DimOut>\n{\n    enum {\n        DimIn  = _DimIn,\n        DimOut = _DimOut,\n        DegreePolynomial = _DegreePolynomial,\n    };\n    \n    typedef Eigen::Matrix<double, DimIn , 1> Point;\n    typedef Eigen::Matrix<double, DimOut, 1> Value;\n    typedef Eigen::Matrix<double, DimOut, DimIn> Gradient;\n    typedef PolynomialBasisGen<DimIn, DegreePolynomial> PolynomialBasisGen;\n    typedef RBFKernel_Bivariate<DimIn, _RBFKernel_Core> Kernel;\n    typedef boost::tuple<Point, Value, Gradient> Constraint;\n    \n    BOOST_STATIC_ASSERT(Kernel::GradientAlwaysDefined);\n    \n    std::vector<Constraint> constraints;\n    Kernel kernel;\n    Eigen::Matrix<double, -1, DimOut> weights;\n    Eigen::MatrixXd A_matrix;\n    Eigen::ColPivHouseholderQR<Eigen::MatrixXd> A_factorized;\n    \n    void clear_constraints() {\n        constraints.clear();\n    }\n    void add_constraint(const Point& point, const Value& value, const Gradient& gradient) {\n        constraints.push_back(Constraint(point, value, gradient));\n    }\n    void factorize() {\n        const int P = PolynomialBasisGen::DimOut;\n        const int D = 1 + DimIn;\n        const size_t n = constraints.size();\n        const int m = D * n + P;\n        A_matrix = Eigen::MatrixXd::Zero(m, m);\n        for (size_t i = 0; i < n; ++i) {\n            const Point& point_i = constraints[i].get<0>();\n            // rbf part\n            for (size_t j = 0; j < n; ++j) {       // note that A is not symmetric\n                const Point& point_j = constraints[j].get<0>();\n                // make submatrix\n                Eigen::Matrix<double, D, D> A_sub;\n                A_sub.setZero();\n                A_sub(0, 0) = kernel(point_i, point_j);\n                A_sub.block<1, DimIn>(0, 1) = kernel.gradient(point_i, point_j);\n                A_sub.block<DimIn, 1>(1, 0) = A_sub.block<1, DimIn>(0, 1).transpose();\n                A_sub.block<DimIn, DimIn>(1, 1) = kernel.hessian(point_i, point_j);\n                // insert submatrix\n                A_matrix.block<D, D>(D * i, D * j) = A_sub;\n            }\n            // polynomial part\n            A_matrix.block<P, D>(D * n, D * i) <<\n                PolynomialBasisGen::basis(point_i),\n                PolynomialBasisGen::gradient(point_i);\n            A_matrix.block<D, P>(D * i, D * n) = A_matrix.block<P, D>(D * n, D * i).transpose();\n        }\n        A_factorized.compute(A_matrix);         // factorize\n    }\n    void solve() {\n        const int P = PolynomialBasisGen::DimOut;\n        const int D = 1 + DimIn;\n        const size_t n = constraints.size();\n        const int m = D * n + P;\n        Eigen::Matrix<double, -1, DimOut> b;\n        b.setZero(m, DimOut);\n        // constraint part\n        for (size_t i = 0; i < n; ++i) {\n            const Value& value_i = constraints[i].get<1>();\n            const Gradient& gradient_i = constraints[i].get<2>();\n            b.block<D, DimOut>(D * i, 0).transpose() << value_i, gradient_i;\n        }\n        // polynomial part is just 0\n        weights = A_factorized.solve(b);        // solve\n    }\n    void factorize_and_solve() {\n        factorize();\n        solve();\n    }\n    Value operator()(const Point& point) const {\n        const int P = PolynomialBasisGen::DimOut;\n        const int D = 1 + DimIn;\n        Value result = Value::Zero();\n        for (size_t i = 0; i < constraints.size(); ++i) {\n            const Point& point_i = constraints[i].get<0>();\n            // first (value) rbf part\n            result += kernel(point, point_i) * weights.row(D * i).transpose();\n            // second (gradient) rbf part\n            result += (kernel.gradient(point, point_i) * weights.block<DimIn, DimOut>(D * i + 1, 0)).transpose();\n        }\n        // polynomial part\n        PolynomialBasisGen::Basis basis = PolynomialBasisGen::basis(point);\n        result += (basis.transpose() * weights.bottomRows(P)).transpose();\n        return result;\n    }\n    Gradient gradient(const Point& point) const {\n        const int P = PolynomialBasisGen::DimOut;\n        Gradient result = Gradient::Zero();\n        // rbf part\n        for (size_t i = 0; i < constraints.size(); ++i) {\n            const Point& point_i = constraints[i].get<0>();\n            const int D = 1 + DimIn;\n            // first (value) rbf part\n            result += weights.row(D * i).transpose() * kernel.gradient(point, point_i);\n            // second (gradient) rbf part\n            result += weights.block<DimIn, DimOut>(D * i + 1, 0).transpose() * kernel.hessian(point, point_i);\n        }\n        // polynomial part\n        PolynomialBasisGen::Gradient b_gradient = PolynomialBasisGen::gradient(point);\n        result += weights.bottomRows(P).transpose() * b_gradient;\n        return result;\n    }\n};\n\n}\n\n", "meta": {"hexsha": "f1f585cf95f8ce41664b12e590ff5cf34a5f8328", "size": 5156, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/math/HermiteRBF.hh", "max_stars_repo_name": "honoriocassiano/skbar", "max_stars_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kt84/math/HermiteRBF.hh", "max_issues_repo_name": "honoriocassiano/skbar", "max_issues_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T12:16:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T12:21:41.000Z", "max_forks_repo_path": "src/kt84/math/HermiteRBF.hh", "max_forks_repo_name": "honoriocassiano/skbar", "max_forks_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6615384615, "max_line_length": 115, "alphanum_fraction": 0.5820403413, "num_tokens": 1338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958426, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.6319915784492799}}
{"text": "#include \"complexErf.hpp\"\n\n#include <ql/math/comparison.hpp>\n\n#include <boost/math/special_functions/erf.hpp>\n\nnamespace QuantLib {\nstd::complex<double> erf(const std::complex<double>& z, const std::size_t order) {\n    const double x = z.real();\n    const double y = z.imag();\n    double erfr = boost::math::erf(x);\n    double erfi = 0.0;\n    const double emxs = std::exp(-x * x);\n    if (!close_enough(x, 0.0)) {\n        erfr += emxs / (2.0 * M_PI * x) * (1.0 - cos(2.0 * x * y));\n        erfi += emxs / (2.0 * M_PI * x) * sin(2.0 * x * y);\n    } else {\n        erfi += y / (M_PI);\n    }\n    double rr = 0.0, ri = 0.0;\n    for (int n = 1; n <= order; ++n) {\n        double nd = static_cast<double>(n);\n        rr += exp(-0.25 * nd * nd) / (nd * nd + 4.0 * x * x) *\n              (2.0 * x - 2.0 * x * cosh(nd * y) * cos(2.0 * x * y) + nd * sinh(n * y) * sin(2.0 * x * y));\n        ri += exp(-0.25 * nd * nd) / (nd * nd + 4.0 * x * x) *\n              (2.0 * x * cosh(nd * y) * sin(2.0 * x * y) + nd * sinh(nd * y) * cos(2.0 * x * y));\n    }\n    rr *= 2.0 / M_PI * emxs;\n    ri *= 2.0 / M_PI * emxs;\n    return std::complex<double>(erfr + rr, erfi + ri);\n}\n} // namespace QuantLib\n", "meta": {"hexsha": "1f4dc67750d4160f9876add59ca1697c8a0923b6", "size": 1179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/preexperimental/complexErf.cpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/experimental/preexperimental/complexErf.cpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/experimental/preexperimental/complexErf.cpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 35.7272727273, "max_line_length": 106, "alphanum_fraction": 0.481764207, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.6319474181385893}}
{"text": "/*\r\n This program is free software; you can redistribute it and/or modify it under\r\n the terms of the European Union Public Licence - EUPL v.1.1 as published by\r\n the European Commission.\r\n\r\n This program is distributed in the hope that it will be useful, but WITHOUT\r\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r\n FOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1\r\n for more details.\r\n\r\n You should have received a copy of the European Union Public Licence - EUPL v.1.1\r\n along with this program.\r\n\r\n Further information about the European Union Public Licence - EUPL v.1.1 can\r\n also be found on the world wide web at http://ec.europa.eu/idabc/eupl\r\n\r\n*/\r\n\r\n/*\r\n ------ Copyright (C) 2011 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\r\n*/\r\n\r\n//------------------ Author: Catarina Silva  -------------------------------------------------\r\n// ------------------ E-mail: (catsilva20@gmail.com) ------------------------------------------\r\n// Patched by Guillermo to correct errors, July 2011\r\n// Patched by Guillermo to allow compilation in Linux, August 2011\r\n\r\n#include \"attitudetransformations.h\"\r\n\r\n#include \"Astro-Core/RotationState.h\"\r\n#include \"Astro-Core/stamath.h\"\r\n#include \"Astro-Core/stamath.h\"\r\n#include <Eigen/Core>\r\n#include <Eigen/Geometry>\r\n\r\n#include <QDebug>\r\n#include <QMessageBox>\r\n\r\n\r\n// Sets all the transformations between quaternions, Euler angles and Direction cosine matrix\r\n// The following Euler sequences will be implemented: 123, 321, 313\r\n\r\n//----------------------------------------------------------------------------------------------------------------------\r\n// The quaternions are considered to have\r\n// the following form: q = w + xi + yj + zk = q4 + q1i + q2j + q3k, with q4 being the real part, and q1, q2 and q3\r\n// the imaginary part.\r\n// Throughout the code, PHI is considered to be the first rotation angle, THETA the second rotation angle and PSI the\r\n// third rotation angle.\r\n//-----------------------------------------------------------------------------------------------------------------------\r\n//Euler to Quaternions\r\n/**\r\n  * Converts the input Euler angles and sequence to a DCM\r\n  *\r\n  * @param EulerAngles  the input Euler angles (radians)\r\n  * @param seq1         first entry of the Euler sequence\r\n  * @param seq2         second entry of the Euler sequence\r\n  * @param seq3         third entry of the Euler sequence\r\n  *\r\n  * @return the Quaternions\r\n  */\r\nQuaterniond ToQuaternions(const Vector3d EulerAngles,\r\n                          int seq1,\r\n                          int seq2,\r\n                          int seq3)\r\n{\r\n    //Euler angles (phi, theta, psi)\r\n    double phi= sta::degToRad(EulerAngles[0]);\r\n    double theta = sta::degToRad(EulerAngles[1]);\r\n    double psi = sta::degToRad(EulerAngles[2]);\r\n\r\n    // SEQUENCE 321\r\n    if (seq1 == 3 && seq2 == 2 && seq3 == 1)\r\n    {\r\n        Quaterniond quaternion = Quaterniond(AngleAxis<double> (phi,   Vector3d::UnitZ())*\r\n                                             Quaterniond(AngleAxis<double> (theta, Vector3d::UnitY()))*\r\n                                             Quaterniond(AngleAxis<double> (psi,   Vector3d::UnitX())));\r\n\r\n        return quaternion;\r\n    }\r\n\r\n    // SEQUENCE 123\r\n    if (seq1 == 1 && seq2 == 2 && seq3 == 3)\r\n    {\r\n\r\n        Quaterniond quaternion = Quaterniond(AngleAxis<double> (phi,   Vector3d::UnitX())*\r\n                                             Quaterniond(AngleAxis<double> (theta, Vector3d::UnitY()))*\r\n                                             Quaterniond(AngleAxis<double> (psi,   Vector3d::UnitZ())));\r\n\r\n        return quaternion;\r\n    }\r\n\r\n    // SEQUENCE 313\r\n    if(seq1 == 3 && seq2 == 1 && seq3 == 3)\r\n    {\r\n\r\n        Quaterniond quaternion = Quaterniond(AngleAxis<double> (phi,   Vector3d::UnitZ())*\r\n                                             Quaterniond(AngleAxis<double> (theta, Vector3d::UnitX()))*\r\n                                             Quaterniond(AngleAxis<double> (psi,   Vector3d::UnitZ())));\r\n        return quaternion;\r\n\r\n    }\r\n\r\n}\r\n\r\n\r\n//Quaternions to Euler angles\r\n/**\r\n  * Converts the input quaternions to a set of Euler angles, using the Euler sequence provided\r\n  *\r\n  * @param quaternion   the input quaternions\r\n  * @param seq1         first entry of the Euler sequence\r\n  * @param seq2         second entry of the Euler sequence\r\n  * @param seq3         third entry of the Euler sequence\r\n  *\r\n  * @return the Euler angles (radians)\r\n  */\r\nVector3d ToEulerAngles(Quaterniond quaternion,\r\n                       int seq1,\r\n                       int seq2,\r\n                       int seq3)\r\n{\r\n    double theta1, theta2, theta3, a, b, c;\r\n    Vector3d finalEulerAngles;\r\n\r\n    //Transform the initial quaternions in the direction cosine matrix, using Eigen::Geometry capabilities.\r\n//     Matrix3d R = quaternion.toRotationMatrix();\r\n\r\n        double q1 = quaternion.coeffs().coeffRef(0);\r\n        double q2 = quaternion.coeffs().coeffRef(1);\r\n        double q3 = quaternion.coeffs().coeffRef(2);\r\n        double q4 = quaternion.coeffs().coeffRef(3);\r\n\r\n        double rotationMatrix_coeff[9]=\r\n        {\r\n            (1-2*(q2*q2+q3*q3)),   2*(q1*q2-q3*q4),    2*(q1*q3+q2*q4),\r\n            2*(q2*q1+q3*q4),      1-2*(q1*q1+q3*q3),   2*(q2*q3-q1*q4),\r\n            2*(q3*q1-q2*q4),        2*(q3*q2+q1*q4),   (1-2*(q1*q1+q2*q2))\r\n        };\r\n\r\n       Matrix3d R(rotationMatrix_coeff);\r\n\r\n    //Transform the direction cosine matrix in the Euler angles for the three sequences.\r\n    // SEQUENCE 321\r\n    if (seq1 == 3 && seq2 == 2 && seq3 == 1)\r\n    {\r\n        a = R(0,1)/R(0,0);\r\n        theta1 = atan(a);\r\n        theta2 = asin(-R(0,2));\r\n        b = R(2,0)*sin(theta1) - R(2,1)*cos(theta1);\r\n        c = -R(1,0)*sin(theta1) + R(1,1)*cos(theta1);\r\n        theta3 = atan(b/c);\r\n    }\r\n    // SEQUENCE 123\r\n    else if (seq1 == 1 && seq2 == 2 && seq3 == 3)\r\n    {\r\n        a = -R(2,1)/R(2,2);\r\n        theta1 = atan(a);\r\n        theta2 = asin(R(2,0));\r\n        b = R(0,2)*sin(theta1) + R(0,1)*cos(theta1);\r\n        c = R(1,2)*sin(theta1) + R(1,1)*cos(theta1);\r\n        theta3 = atan(b/c);\r\n    }\r\n    // SEQUENCE 313\r\n    else if (seq1 == 3 && seq2 == 1 && seq3 == 3)\r\n    {\r\n        a = R(2,0)/(-R(2,1));\r\n        theta1 = atan(a);\r\n        theta2 = acos(R(2,2));\r\n        b = -R(1,1)*sin(theta1) - R(1,0)*cos(theta1);\r\n        c = R(0,1)*sin(theta1) + R(0,0)*cos(theta1);\r\n        theta3 = atan(b/c);\r\n    }\r\n    else\r\n    {\r\n        theta1= 0.0;\r\n        theta2 = 0.0;\r\n        theta3 = 0.0;\r\n    }\r\n\r\n    finalEulerAngles(0) = theta1;\r\n    finalEulerAngles(1) = theta2;\r\n    finalEulerAngles(2) = theta3;\r\n\r\n    return finalEulerAngles;\r\n}\r\n\r\n\r\n//Body rates to Euler angle rates\r\n/**\r\n  * Converts the input angular velocity to a set of Euler angles rates, using the Euler sequence provided\r\n  *\r\n  * @param angVel       the input angular velocity (radians/seconds)\r\n  * @param EulerAngles  the input Euler angles (radians)\r\n  * @param seq1         first entry of the Euler sequence\r\n  * @param seq2         second entry of the Euler sequence\r\n  * @param seq3         third entry of the Euler sequence\r\n  *\r\n  * @return             the Euler angle rates representation (radians/second)\r\n  */\r\nVector3d ToEulerAngleRates(const Vector3d angVel,\r\n                           const Vector3d EulerAngles,\r\n                           int seq1,\r\n                           int seq2,\r\n                           int seq3)\r\n{\r\n    //Convert the Euler angles from degress to radians\r\n    //double phi = sta::degToRad(EulerAngles[0]); // Guillermo\r\n    double theta = sta::degToRad(EulerAngles[1]);\r\n    double psi = sta::degToRad(EulerAngles[2]);\r\n\r\n    // we need to check the singularities. theta = pi/2 there's a singularity\r\n    bool singularity = false;\r\n\r\n    Vector3d finalEulerRates; // Guillermo\r\n    finalEulerRates.setZero();\r\n\r\n    // SEQUENCE 321\r\n    if (seq1 == 3 && seq2 == 2 && seq3 == 1)\r\n    {\r\n        if(cos(theta)==0)\r\n            singularity = true;\r\n        else\r\n        {\r\n            static double MatrixCoeffs[9] = {\r\n                0.0,    sin(psi)/cos(theta),              cos(psi)/cos(theta),\r\n                0.0,    cos(psi),                         -sin(psi),\r\n                1.0,   (sin(psi)*sin(theta))/cos(theta),  (cos(psi)*sin(theta))/cos(theta)\r\n            };\r\n            static const Matrix3d Matrix(MatrixCoeffs);\r\n            finalEulerRates = Matrix*angVel;\r\n        }\r\n    }\r\n\r\n    // SEQUENCE 123\r\n    if (seq1 == 1 && seq2 == 2 && seq3 == 3)\r\n    {\r\n        if(cos(theta)==0)\r\n            singularity = true;\r\n        else\r\n        {\r\n            static double MatrixCoeffs[9] = {\r\n                cos(psi)/cos(theta),                    -sin(psi)/cos(theta),               0.0,\r\n                sin(psi),                               cos(psi),                           0.0,\r\n                (-cos(psi)*sin(theta))/cos(theta),      (sin(psi)*sin(theta))/cos(theta),   1.0\r\n            };\r\n            static const Matrix3d Matrix(MatrixCoeffs);\r\n            finalEulerRates = Matrix*angVel;\r\n        }\r\n    }\r\n\r\n    // SEQUENCE 313\r\n    if (seq1 == 3 && seq2 == 1 && seq3 == 3)\r\n    {\r\n        if(sin(theta)==0)\r\n            singularity = true;\r\n        else\r\n        {\r\n            static double MatrixCoeffs[9] = {\r\n                sin(psi)/sin(theta),                  cos(psi)/sin(theta),                0.0,\r\n                cos(psi),                             -sin(psi),                          0.0,\r\n                -(sin(psi)*cos(theta))/sin(theta),    -(cos(psi)*cos(theta))/sin(theta),    1.0\r\n            };\r\n            static const Matrix3d Matrix(MatrixCoeffs);\r\n            finalEulerRates = Matrix*angVel;\r\n        }\r\n    }\r\n\r\n    if (singularity)\r\n    {\r\n        //throw an exception to user\r\n        QMessageBox EulerSingularity;\r\n        //EulerSingularity.setIcon();\r\n        EulerSingularity.setText(\"A singularity in the Euler angles has occurred. Value of angle rates set to (0,0,0). Do you want to continue?\");\r\n        EulerSingularity.setStandardButtons(QMessageBox::Ignore | QMessageBox::Abort);\r\n        EulerSingularity.setDefaultButton(QMessageBox::Abort);\r\n        EulerSingularity.exec();\r\n        finalEulerRates << 0, 0, 0;  // Guillermo\r\n    }\r\n\r\n    return finalEulerRates;\r\n}\r\n\r\n\r\n\r\n//Euler angle rates to Body rates\r\n/**\r\n  * Converts the input Euler angle rates to an angular velocity, using the Euler sequence provided\r\n  *\r\n  * @param EulerRates   the input Euler rates (radians/seconds)\r\n  * @param EulerAngles  the input Euler angles (radians)\r\n  * @param seq1         first entry of the Euler sequence\r\n  * @param seq2         second entry of the Euler sequence\r\n  * @param seq3         third entry of the Euler sequence\r\n  *\r\n  * @return             the angular velocity (radians/second)\r\n  */\r\nVector3d ToAngularVelocity(const Vector3d EulerRates,\r\n                           const Vector3d EulerAngles,\r\n                           int seq1,\r\n                           int seq2,\r\n                           int seq3)\r\n{\r\n    //Convert the Euler angles from degress to radians\r\n    //double phi = sta::degToRad(EulerAngles[0]);\r\n    double theta = sta::degToRad(EulerAngles[1]);\r\n    double psi = sta::degToRad(EulerAngles[2]);\r\n    Vector3d finalAngVel;\r\n\r\n    // SEQUENCE 321\r\n    if(seq1 == 3 && seq2 == 2 && seq3 == 1)\r\n    {\r\n        static double MatrixCoeffs[9] = {\r\n            -sin(theta),                  0,          1,\r\n            sin(psi)*cos(theta),          cos(psi),   0,\r\n            cos(psi)*cos(theta),         -sin(psi),   0\r\n        };\r\n        static const Matrix3d Matrix(MatrixCoeffs);\r\n        finalAngVel = Matrix * EulerRates;\r\n    }\r\n\r\n    // SEQUENCE 123\r\n    if(seq1 == 1 && seq2 == 2 && seq3 == 3)\r\n    {\r\n        static double MatrixCoeffs[9] = {\r\n            cos(psi)*cos(theta),      sin(psi),   0.0,\r\n            -sin(psi)*cos(theta),     cos(psi),   0.0,\r\n            sin(theta),               0.0,        1.0\r\n        };\r\n        static const Matrix3d Matrix(MatrixCoeffs);\r\n        finalAngVel = Matrix * EulerRates;\r\n    }\r\n\r\n    // SEQUENCE 313\r\n    if(seq1 == 3 && seq2 == 1 && seq3 == 3)\r\n    {\r\n        static double MatrixCoeffs[9] = {\r\n            sin(psi)*sin(theta),        cos(psi),       0.0,\r\n            cos(psi)*sin(theta),        -sin(psi),      0.0,\r\n            cos(theta),                 0.0,            1.0\r\n        };\r\n        static const Matrix3d Matrix(MatrixCoeffs);\r\n        finalAngVel = Matrix * EulerRates;\r\n    }\r\n\r\n    return finalAngVel;\r\n}\r\n\r\n\r\n\r\n//------------------------------------------------------------------------------------------------------------\r\n// These transformations were taken from: \"Space vehicles dynamics and control\", Bong Wie, AIAA Education Series\r\n//------------------------------------------------------------------------------------------------------------\r\n\r\n//Quaternion rates to body rates\r\nVector3d ToAngularVelocity(Eigen::Quaterniond quaternion,\r\n                           Eigen::Quaterniond initQuatRates)\r\n{\r\n    // q = q4 + q1i + q2j + q3k\r\n    double q1 = quaternion.coeffs().coeffRef(0);\r\n    double q2 = quaternion.coeffs().coeffRef(1);\r\n    double q3 = quaternion.coeffs().coeffRef(2);\r\n    double q4 = quaternion.coeffs().coeffRef(3);\r\n\r\n    double q1_Dot = initQuatRates.coeffs().coeffRef(0);\r\n    double q2_Dot = initQuatRates.coeffs().coeffRef(1);\r\n    double q3_Dot = initQuatRates.coeffs().coeffRef(2);\r\n    double q4_Dot = initQuatRates.coeffs().coeffRef(3);\r\n\r\n    //    static const Vector qDot(q1_Dot,q2_Dot,q3_Dot, q4_Dot );\r\n\r\n    //    static const Vector3d angularRates = 2*W_q*qDot;\r\n    double angRate_p = 2*(q4*q1_Dot + q3*q2_Dot - q2*q3_Dot - q1*q4_Dot);\r\n    double angRate_q = 2*(-q3*q1_Dot + q4*q2_Dot + q1*q3_Dot - q2*q4_Dot);\r\n    double angRate_r = 2*(q2*q1_Dot - q1*q2_Dot + q4*q3_Dot - q3*q4_Dot);\r\n\r\n    Vector3d angularRates(angRate_p,angRate_q,angRate_r);\r\n    return angularRates;\r\n\r\n}\r\n\r\n//Body rates to quaternion rates\r\nQuaterniond ToQuaternionRates(Eigen::Quaterniond quaternion,\r\n                              Vector3d bodyRates)\r\n{\r\n\r\n    double q1 = quaternion.coeffs().coeffRef(0);\r\n    double q2 = quaternion.coeffs().coeffRef(1);\r\n    double q3 = quaternion.coeffs().coeffRef(2);\r\n    double q4 = quaternion.coeffs().coeffRef(3);\r\n\r\n    double p = bodyRates[0];\r\n    double q = bodyRates[1];\r\n    double r = bodyRates[2];\r\n\r\n    double q1_Dot = 0.5*(q4*p - q3*q + q2*r);\r\n    double q2_Dot = 0.5*(q3*p + q4*q - q1*r);\r\n    double q3_Dot = 0.5*(-q2*p + q1*q + q4*r);\r\n    double q4_Dot = 0.5*(-q1*p - q2*q - q3*r);\r\n\r\n    Quaterniond quatRates(q1_Dot, q2_Dot, q3_Dot, q4_Dot);\r\n    return quatRates;\r\n}\r\n", "meta": {"hexsha": "8154a8524d577dfbf12d7190883b04065055ff6c", "size": 14729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Astro-Core/attitudetransformations.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Astro-Core/attitudetransformations.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Astro-Core/attitudetransformations.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 36.5483870968, "max_line_length": 147, "alphanum_fraction": 0.5284133342, "num_tokens": 3849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995028, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6318956623548893}}
{"text": "#pragma once\n#include <future>\n#include <iostream>\n#include <Eigen/Dense>\n#include <limits.h>\n#include \"Data.hpp\"\n#include \"tsne/tsne.h\"\n\n//Single class for data projection, differnet methods can be set in the constructor\n//When created the data is projected in a separate thread\n//On completion the \"projected\" member is set to true\n//Call wait on the future object to sync\nclass DataProjector{\npublic:\n    enum Method{\n        PCA,\n        TSNE\n    };\n\n    struct ProjectionSettings{\n        //settings for PCA\n\n        //settings for TSNE\n        double perplexity, theta;\n        int randSeed, maxIter, stopLyingIter, momSwitchIter;\n        bool skipRandomInit;\n    };\n\n    DataProjector(const Data& data, int reducedDimensionSize, Method projectionMethod, const ProjectionSettings& settings, std::vector<uint32_t>& indices, std::vector<uint32_t> attributeIndices = {}):data(data), reducedDimensionSize(reducedDimensionSize), projectionMethod(projectionMethod), indices(indices){\n        if(attributeIndices.empty()){\n            this->attributeIndices.resize(data.columns.size());\n            for(uint32_t i = 0; i < indices.size(); ++i) this->attributeIndices[i] = i;\n        }\n        else this->attributeIndices = attributeIndices;\n        this->settings = settings;\n        future = std::async(runAsync, this);\n    }\n\n    static void runAsync(DataProjector* p){\n        p->run();\n    }\n\n    void run(){\n        switch(projectionMethod){\n        case Method::PCA:{\n            execPCA();\n        } break;\n        case Method::TSNE:{\n            execTSNE();\n        }break;\n        }\n    }\n\n    Eigen::MatrixXf projectedPoints;\n    bool projected = false;\n    bool interrupted = false;\n    float progress = .0f;\n    int reducedDimensionSize;\n    std::future<void> future;\n\nprotected:\n    const Data& data;\n    std::vector<uint32_t> attributeIndices, &indices;\n    ProjectionSettings settings;\n    const float eps = 1e-6;\n    Method projectionMethod;\n    Eigen::MatrixXf getDataMatrix(){\n        //data to eigen matrix\n        Eigen::MatrixXf d(indices.size(), attributeIndices.size());\n        for(int i = 0; i < indices.size(); ++i){\n            for(int  c = 0; c < attributeIndices.size(); ++c){\n                d(i,c) = data(indices[i],attributeIndices[c]);\n            }\n        }\n        //zero center and normalize\n        Eigen::RowVectorXf meanCols = d.colwise().mean();\n        d = d.rowwise() - meanCols;\n        Eigen::RowVectorXf mins = d.colwise().minCoeff(), diff = d.colwise().maxCoeff() - mins;\n        diff.array() += eps;\n        d.array().rowwise() /= diff.array();\n        progress = .33f;\n        return d;\n    }\n\n    void normalizeProjectedPoints(){\n        Eigen::RowVectorXf min = projectedPoints.colwise().minCoeff();\n        Eigen::RowVectorXf diff = projectedPoints.colwise().maxCoeff() - min;\n        projectedPoints.rowwise() -= min;\n        projectedPoints.array().rowwise() /= diff.array(); \n    }\n\n    void execPCA(){\n        Eigen::MatrixXf d = getDataMatrix();\n        Eigen::BDCSVD<Eigen::MatrixXf> svd(d, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        progress = .66f;\n        //convert points to pc scores\n        auto u = svd.matrixU().real();\n        projectedPoints = u * svd.singularValues().real().asDiagonal();\n        //drop unused scores and normalizing the points\n        projectedPoints.conservativeResize(Eigen::NoChange, reducedDimensionSize);\n        normalizeProjectedPoints();\n        progress = 1;\n        projected = true;\n    }\n\n    void execTSNE(){\n        // usage of exact algorithm\n        if(data.size() - 1 < 3 * settings.perplexity){\n            std::cout << \"Perplexity too large for the number of data points!\" << std::endl;\n            return;\n        }\n        bool exact = settings.theta == .0f;\n        if(exact && data.size() * data.size() > INT_MAX){\n            std::cout << \"Too large dataset for exact computation, use a theta > 0 for approximation\" << std::endl;\n            progress = 1;\n            interrupted = true;\n            return;\n        }\n\n        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> d = getDataMatrix().cast<double>();\n        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> y(d.rows(), reducedDimensionSize);\n\n        //checking rowmajorness of d\n        //assert(d(0,0) == d.data()[0]);\n        //assert(d(0,1) == d.data()[1]);\n        //assert(d(0,2) == d.data()[2]);\n        //assert(d(1,0) == d.data()[3]);\n        //std::cout << d(0,0) << \" \" << d.data()[0] << std::endl;\n        //std::cout << d(0,1) << \" \" << d.data()[1] << std::endl;\n        //std::cout << d(0,2) << \" \" << d.data()[2] << std::endl;\n        //std::cout << d(1,0) << \" \" << d.data()[3] << std::endl;\n        //std::cout << d(2,0) << \" \" << d.data()[6] << std::endl;\n\n\n        TSNE::run(d.data(), d.rows(), d.cols(), y.data(), reducedDimensionSize, settings.perplexity, settings.theta, settings.randSeed, settings.skipRandomInit, settings.maxIter, settings.stopLyingIter, settings.momSwitchIter, &progress);\n        if(progress == -1){\n            interrupted = true;\n            return;\n        }\n        projectedPoints = y.cast<float>();\n        normalizeProjectedPoints();\n        progress = 1;\n        projected = true;\n    }\n};", "meta": {"hexsha": "aa6e780be41352c86c0b899919ac0da7439ac309", "size": 5265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PCViewer/DataProjector.hpp", "max_stars_repo_name": "wavestoweather/PCViewer", "max_stars_repo_head_hexsha": "27dc8dc156f49281810b2ade42dfab60c480589c", "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": "PCViewer/DataProjector.hpp", "max_issues_repo_name": "wavestoweather/PCViewer", "max_issues_repo_head_hexsha": "27dc8dc156f49281810b2ade42dfab60c480589c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PCViewer/DataProjector.hpp", "max_forks_repo_name": "wavestoweather/PCViewer", "max_forks_repo_head_hexsha": "27dc8dc156f49281810b2ade42dfab60c480589c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-16T12:57:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T12:57:45.000Z", "avg_line_length": 36.3103448276, "max_line_length": 309, "alphanum_fraction": 0.5891737892, "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.631895651734097}}
{"text": "// 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 <iostream>\r\n#include <limits>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <iomanip>\r\n#include <exception>\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//[bessel_errors_example_1\r\n\r\n/*`[h5 Error messages from 'bad' input]\r\n\r\nAnother example demonstrates calculating zeros of the Bessel functions\r\nshowing the error messages from 'bad' input is handled by throwing exceptions.\r\n\r\nTo use the functions for finding zeros of the functions we need:\r\n*/\r\n  #include <boost/math/special_functions/bessel.hpp>\r\n  #include <boost/math/special_functions/airy.hpp>\r\n\r\n//] [/bessel_errors_example_1]\r\n\r\nint main()\r\n{\r\n//[bessel_errors_example_2\r\n\r\n/*`[tip It is always wise to place all code using Boost.Math inside try'n'catch blocks;\r\nthis will ensure that helpful error messages can be shown when exceptional conditions arise.]\r\n\r\nExamples below show messages from several 'bad' arguments that throw a `domain_error` exception.\r\n*/\r\n  try\r\n  { // Try a zero order v.\r\n    float dodgy_root = boost::math::cyl_bessel_j_zero(0.F, 0);\r\n    std::cout << \"boost::math::cyl_bessel_j_zero(0.F, 0) \" << dodgy_root << std::endl;\r\n    // Thrown exception Error in function boost::math::cyl_bessel_j_zero<double>(double, int):\r\n    // Requested the 0'th zero of J0, but the rank must be > 0 !\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/*`[note The type shown in the error message is the type [*after promotion],\r\nusing __precision_policy and __promotion_policy, from `float` to `double` in this case.]\r\n\r\nIn this example the promotion goes:\r\n\r\n# Arguments are `float` and `int`.\r\n# Treat `int` \"as if\" it were a `double`, so arguments are `float` and `double`.\r\n# Common type is `double` - so that's the precision we want (and the type that will be returned).\r\n# Evaluate internally as `double` for full `float` precision.\r\n\r\nSee full code for other examples that promote from `double` to `long double`.\r\n\r\nOther examples of 'bad' inputs like infinity and NaN are below.\r\nSome compiler warnings indicate that 'bad' values are detected at compile time.\r\n*/\r\n\r\n  try\r\n  { // order v = inf\r\n     std::cout << \"boost::math::cyl_bessel_j_zero(inf, 1) \" << std::endl;\r\n     double inf = std::numeric_limits<double>::infinity();\r\n     double inf_root = boost::math::cyl_bessel_j_zero(inf, 1);\r\n     std::cout << \"boost::math::cyl_bessel_j_zero(inf, 1) \" << inf_root << std::endl;\r\n     // Throw exception Error in function boost::math::cyl_bessel_j_zero<long double>(long double, unsigned):\r\n     // Order argument is 1.#INF, but must be finite >= 0 !\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  try\r\n  { // order v = NaN, rank m = 1\r\n     std::cout << \"boost::math::cyl_bessel_j_zero(nan, 1) \" << std::endl;\r\n     double nan = std::numeric_limits<double>::quiet_NaN();\r\n     double nan_root = boost::math::cyl_bessel_j_zero(nan, 1);\r\n     std::cout << \"boost::math::cyl_bessel_j_zero(nan, 1) \" << nan_root << std::endl;\r\n     // Throw exception Error in function boost::math::cyl_bessel_j_zero<long double>(long double, unsigned):\r\n     // Order argument is 1.#QNAN, but must be finite >= 0 !\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/*`The output from other examples are shown appended to the full code listing.\r\n*/\r\n//] [/bessel_errors_example_2]\r\n  try\r\n  {   // Try a zero rank m.\r\n    std::cout << \"boost::math::cyl_neumann_zero(0.0, 0) \" << std::endl;\r\n    double dodgy_root = boost::math::cyl_bessel_j_zero(0.0, 0);\r\n    //  warning C4146: unary minus operator applied to unsigned type, result still unsigned.\r\n    std::cout << \"boost::math::cyl_neumann_zero(0.0, -1) \" << dodgy_root << std::endl;\r\n    //  boost::math::cyl_neumann_zero(0.0, -1) 6.74652e+009\r\n    // This *should* fail because m is unreasonably large.\r\n\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  try\r\n  { // m = inf\r\n   std::cout << \"boost::math::cyl_bessel_j_zero(0.0, inf) \" << std::endl;\r\n   double inf = std::numeric_limits<double>::infinity();\r\n     double inf_root = boost::math::cyl_bessel_j_zero(0.0, inf);\r\n     // warning C4244: 'argument' : conversion from 'double' to 'int', possible loss of data.\r\n     std::cout << \"boost::math::cyl_bessel_j_zero(0.0, inf) \" << inf_root << std::endl;\r\n     // Throw exception Error in function boost::math::cyl_bessel_j_zero<long double>(long double, int):\r\n     // Requested the 0'th zero, but must be > 0 !\r\n\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  try\r\n  { // m = NaN\r\n     double nan = std::numeric_limits<double>::quiet_NaN();\r\n     double nan_root = boost::math::airy_ai_zero<double>(nan);\r\n     // warning C4244: 'argument' : conversion from 'double' to 'int', possible loss of data.\r\n     std::cout << \"boost::math::airy_ai_zero<double>(nan) \" << nan_root << std::endl;\r\n     // Thrown exception Error in function boost::math::airy_ai_zero<double>(double,double):\r\n     // The requested rank of the zero is 0, but must be 1 or more !\r\n  }\r\n  catch (std::exception& ex)\r\n  {\r\n    std::cout << \"Thrown exception \" << ex.what() << std::endl;\r\n  }\r\n } // int main()\r\n\r\n/*\r\nOutput:\r\n\r\n  Description: Autorun \"J:\\Cpp\\big_number\\Debug\\bessel_errors_example.exe\"\r\n  Thrown exception Error in function boost::math::cyl_bessel_j_zero<double>(double, int): Requested the 0'th zero of J0, but the rank must be > 0 !\r\n  boost::math::cyl_bessel_j_zero(inf, 1) \r\n  Thrown exception Error in function boost::math::cyl_bessel_j_zero<long double>(long double, int): Order argument is 1.#INF, but must be finite >= 0 !\r\n  boost::math::cyl_bessel_j_zero(nan, 1) \r\n  Thrown exception Error in function boost::math::cyl_bessel_j_zero<long double>(long double, int): Order argument is 1.#QNAN, but must be finite >= 0 !\r\n  boost::math::cyl_neumann_zero(0.0, 0) \r\n  Thrown exception Error in function boost::math::cyl_bessel_j_zero<long double>(long double, int): Requested the 0'th zero of J0, but the rank must be > 0 !\r\n  boost::math::cyl_bessel_j_zero(0.0, inf) \r\n  Thrown exception Error in function boost::math::cyl_bessel_j_zero<long double>(long double, int): Requested the -2147483648'th zero, but the rank must be positive !\r\n  Thrown exception Error in function boost::math::airy_ai_zero<double>(double,double): The requested rank of the zero is 0, but must be 1 or more !\r\n\r\n \r\n*/\r\n\r\n", "meta": {"hexsha": "6180b8e49f8344add33f4af26c47cbd04619b441", "size": 7239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/bessel_errors_example.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/math/example/bessel_errors_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/bessel_errors_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": 42.0872093023, "max_line_length": 167, "alphanum_fraction": 0.6732974168, "num_tokens": 2034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998663336158, "lm_q2_score": 0.8128673269042767, "lm_q1q2_score": 0.6318416645496578}}
{"text": "/* test_uniform_on_sphere.cpp\n *\n * Copyright Steven Watanabe 2011\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id$\n *\n */\n\n#include <boost/random/uniform_on_sphere.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/math/distributions/uniform.hpp>\n#include <cmath>\n\nclass uniform_on_sphere_test {\npublic:\n    typedef double result_type;\n    uniform_on_sphere_test(int dims, int x, int y)\n        : impl(dims), idx1(x), idx2(y) {}\n    template<class Engine>\n    result_type operator()(Engine& rng) {\n        const boost::random::uniform_on_sphere<>::result_type& tmp = impl(rng);\n        // This should be uniformly distributed in [-pi,pi)\n        return std::atan2(tmp[idx1], tmp[idx2]);\n    }\nprivate:\n    boost::random::uniform_on_sphere<> impl;\n    int idx1, idx2;\n};\n\nstatic const double pi = 3.14159265358979323846;\n\n#define BOOST_RANDOM_DISTRIBUTION uniform_on_sphere_test\n#define BOOST_RANDOM_DISTRIBUTION_NAME uniform_on_sphere\n#define BOOST_MATH_DISTRIBUTION boost::math::uniform\n#define BOOST_RANDOM_ARG1_TYPE double\n#define BOOST_RANDOM_ARG1_NAME n\n#define BOOST_RANDOM_ARG1_DEFAULT 6\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_int<>(2, n)\n#define BOOST_RANDOM_DISTRIBUTION_INIT (n, 0, n-1)\n#define BOOST_MATH_DISTRIBUTION_INIT (-pi, pi)\n\n#include \"test_real_distribution.ipp\"\n", "meta": {"hexsha": "4da940f5a74833601d3c874a8bcb7bb5f56d13a3", "size": 1430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/random/test/test_uniform_on_sphere.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/test/test_uniform_on_sphere.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/test/test_uniform_on_sphere.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 31.0869565217, "max_line_length": 79, "alphanum_fraction": 0.7503496503, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6318416575021106}}
{"text": "/* @copyright The code is licensed under the MIT License\n *            <https://opensource.org/licenses/MIT>,\n *            Copyright (c) 2020 Christian Eskil Vaugelade Berg\n * @author Christian Eskil Vaugelade Berg\n*/\n#pragma once\n\n#include <utility>\n\n#include <Eigen/Dense>\n\nnamespace orient {\n\n// \\brief Calculate quaternion from angle axis\n//        Quaternion is expressed as a 4D-vector [w,a,b,c] such that\n//        q = w + a*i + b*j + c*k\n// \\param aa Source angle axis\n// \\return The quaternion\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, 4, 1> quaternionFromAngleAxis(Eigen::Matrix<Scalar, 3, 1> const& aa);\n\n// \\brief Calculate quaternion and partial derivatives from angle axis \n//        See above for more detail\n// \\param aa Source angle axis\n// \\return A pair containg first the quaternion then secondly the Jacobian matrix \ntemplate<typename Scalar>\nstd::pair<Eigen::Matrix<Scalar, 4, 1>, Eigen::Matrix<Scalar, 4, 3>> quaternionFromAngleAxisWD(Eigen::Matrix<Scalar,3, 1> const& aa);\n\n// \\brief Calculate rotation matrix from angle axis\n// \\param aa Source angle axis\n// \\return Rotation matrix\ntemplate<typename Scalar>\nEigen::Matrix<Scalar, 3, 3> rotationMatrixFromAngleAxis(Eigen::Matrix<Scalar,3, 1> const& aa);\n\n// \\brief Calculate rotation matrix and partial derivatives from angle axis\n// \\param aa Source angle axis\n// \\return A pair containg first the rotation matrix then secondly the Jacobian matrix \ntemplate<typename Scalar>\nstd::pair<Eigen::Matrix<Scalar, 3, 3>, Eigen::Matrix<Scalar, 9, 3>> rotationMatrixFromAngleAxisWD(Eigen::Matrix<Scalar, 3, 1> const& aa);\n\n}\n\n#include <orient/impl/from_angle_axis.hpp>\n", "meta": {"hexsha": "daee778fb891354870e5e0fb9087cd983430b047", "size": 1643, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orient/from_angle_axis.hpp", "max_stars_repo_name": "Eskilade/orient", "max_stars_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T07:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T09:23:29.000Z", "max_issues_repo_path": "include/orient/from_angle_axis.hpp", "max_issues_repo_name": "Eskilade/orient", "max_issues_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T02:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T01:42:47.000Z", "max_forks_repo_path": "include/orient/from_angle_axis.hpp", "max_forks_repo_name": "Eskilade/orient", "max_forks_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T04:26:22.000Z", "avg_line_length": 37.3409090909, "max_line_length": 137, "alphanum_fraction": 0.7279367012, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.631779946369251}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[transform_with_strategy\n//` Shows how points can be scaled, translated or rotated\n\n#include <iostream>\n#include <boost/geometry.hpp>\n\n\nint main()\n{\n    namespace trans = boost::geometry::strategy::transform;\n    using boost::geometry::dsv;\n    \n    typedef boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> point_type;\n\n    point_type p1(1.0, 1.0);\n\n    // Translate over (1.5, 1.5)\n    point_type p2;\n    trans::translate_transformer<double, 2, 2> translate(1.5, 1.5);\n    boost::geometry::transform(p1, p2, translate);\n\n    // Scale with factor 3.0\n    point_type p3;\n    trans::scale_transformer<double, 2, 2> scale(3.0);\n    boost::geometry::transform(p1, p3, scale);\n\n    // Rotate with respect to the origin (0,0) over 90 degrees (clockwise)\n    point_type p4;\n    trans::rotate_transformer<boost::geometry::degree, double, 2, 2> rotate(90.0);\n    boost::geometry::transform(p1, p4, rotate);\n    \n    std::cout \n        << \"p1: \" << dsv(p1) << std::endl\n        << \"p2: \" << dsv(p2) << std::endl\n        << \"p3: \" << dsv(p3) << std::endl\n        << \"p4: \" << dsv(p4) << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[transform_with_strategy_output\n/*`\nOutput:\n[pre\np1: (1, 1)\np2: (2.5, 2.5)\np3: (3, 3)\np4: (1, -1)\n]\n*/\n//]\n", "meta": {"hexsha": "d55e5e2d16c2d212f184bdd8bea3159b060eedab", "size": 1582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/transform_with_strategy.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/transform_with_strategy.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/transform_with_strategy.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-17T15:37:11.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-10T14:06:31.000Z", "avg_line_length": 24.71875, "max_line_length": 96, "alphanum_fraction": 0.6371681416, "num_tokens": 501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.6317799331487707}}
{"text": "\n// solving A * X = B\n// using driver function gesv()\n// with c_vector<> & c_matrix<> \n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n//#define BOOST_NUMERIC_BINDINGS_NO_SANITY_CHECK\n//#define BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK\n\n#include <cstddef>\n#include <iostream>\n#include <boost/numeric/bindings/atlas/cblas.hpp>\n#include <boost/numeric/bindings/atlas/clapack.hpp>\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n#  include <boost/numeric/bindings/traits/ublas_vector2.hpp>\n#endif \n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp> \n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef ublas::c_matrix<double, 4, 4> m4x4_t;\ntypedef ublas::c_matrix<double, 3, 3> m3x3_t;\ntypedef ublas::c_matrix<double, 1, 3> mrhs_t;\ntypedef ublas::c_vector<double, 5> v5_t; \n\nint main() {\n\n  cout << endl; \n  size_t n = 3;\n\n  m4x4_t a (n, n);   // system matrix \n  a(0,0) = 1.; a(0,1) = 1.; a(0,2) = 1.;\n  a(1,0) = 2.; a(1,1) = 3.; a(1,2) = 1.;\n  a(2,0) = 1.; a(2,1) = -1.; a(2,2) = -1.;\n\n  mrhs_t b (1, n);  // right-hand side vector\n  b(0,0) = 4.; b(0,1) = 9.; b(0,2) = -2.; \n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n  m3x3_t a2; // for part 2\n  a2 = project (a, ublas::range (0,3), ublas::range (0,3)); \n  v5_t b2 (n); \n  b2 = row (b, 0); \n#endif \n\n  // part 1:\n  cout << \"A: \" << a << endl; \n  cout << \"B: \" << b << endl; \n\n  atlas::lu_solve (a, b);  \n  cout << \"X: \" << b << endl; \n\n  cout << endl; \n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n  // part 2:\n  cout << \"A: \" << a2 << endl; \n  cout << \"B: \" << b2 << endl; \n\n  atlas::lu_solve (a2, b2);  \n  cout << \"X: \" << b2 << endl; \n\n  cout << endl; \n#endif\n}\n\n", "meta": {"hexsha": "a8dee6f2bbecb34448a3bdce9525c3aed34ca5d2", "size": 1877, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv5.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv5.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv5.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 24.6973684211, "max_line_length": 60, "alphanum_fraction": 0.6403835908, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6317799265385301}}
{"text": "#ifndef STAN_MATH_FWD_SCAL_FUN_FALLING_FACTORIAL_HPP\n#define STAN_MATH_FWD_SCAL_FUN_FALLING_FACTORIAL_HPP\n\n#include <stan/math/fwd/core.hpp>\n\n#include <stan/math/prim/scal/fun/falling_factorial.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template<typename T>\n    inline fvar<T>\n    falling_factorial(const fvar<T>& x, const fvar<T>& n) {\n      using boost::math::digamma;\n\n      T falling_fact(falling_factorial(x.val_, n.val_));\n      return fvar<T>(falling_fact,\n                     falling_fact\n                     * (digamma(x.val_ + 1) - digamma(x.val_ - n.val_ + 1))\n                     * x.d_\n                     + falling_fact\n                     * digamma(x.val_ - n.val_ + 1) * n.d_);\n    }\n\n    template<typename T>\n    inline fvar<T>\n    falling_factorial(const fvar<T>& x, double n) {\n      using boost::math::digamma;\n\n      T falling_fact(falling_factorial(x.val_, n));\n      return fvar<T>(falling_fact,\n                     falling_fact\n                     * (digamma(x.val_ + 1) - digamma(x.val_ - n + 1))\n                     * x.d_);\n    }\n\n    template<typename T>\n    inline fvar<T>\n    falling_factorial(double x, const fvar<T>& n) {\n      using boost::math::digamma;\n\n      T falling_fact(falling_factorial(x, n.val_));\n      return fvar<T>(falling_fact,\n                     falling_fact\n                     * digamma(x - n.val_ + 1) * n.d_);\n    }\n  }\n}\n#endif\n", "meta": {"hexsha": "cb1623db3157b0ae4203b0e21e227fe1952b1b38", "size": 1449, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/fwd/scal/fun/falling_factorial.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/fwd/scal/fun/falling_factorial.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/fwd/scal/fun/falling_factorial.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4117647059, "max_line_length": 75, "alphanum_fraction": 0.5741890959, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.631749937379142}}
{"text": "#include <numeric> // for accumulate\n#include <vector>\n#include <algorithm>\n\n#include <assert.h> // for assert? need C++ library?\n\n#include <boost/filesystem.hpp>\n\n#include \"../include/Climate.h\"\n\n#include \"inc/errorcode.h\"\n#include \"inc/timeconst.h\"\n\n#include \"TEMUtilityFunctions.h\"\n#include \"TEMLogger.h\"\n\nextern src::severity_logger< severity_level > glg;\n\n// Should really put these in temutil and then write some test\n// routines that exercise the funcitons over a wide range of values\n\n/** Find \"Vapor Pressure Density\"??? as a funciton of svp and vp ?? \n*/\nfloat calculate_vpd (const float svp, const float vp) {\n  float vpd = svp - vp;\n\n  if (vpd < 0) {\n    vpd = 0;\n  }\n\n  return vpd; // unit Pa\n}\n\n/** Find saturated vapor pressure as a function of temperature.\n\nGuide to Meteorological Instruments and Methods of Observation (CIMO Guide)\n  %      (WMO, 2008), for saturation vapor pressure\n  %      (1) ew = 6.112 e(17.62 t/(243.12 + t))                [2]\n  %      with t in [deg C] and ew in [hPa, mbar]\n\n  %      (2) ei = 6.112 e(22.46 t/(272.62 + t))                [14]\n  %      with t in [deg C] and ei in [hPa]\n*/\nfloat calculate_saturated_vapor_pressure(const float tair) {\n\n  float svp; // saturated vapor pressure (Pa)\n\n  if( tair > 0 ) {\n    svp = 6.112 * exp(17.63 * tair / (243.12 + tair) ) * 100.0;\n  } else {\n    svp = 6.112 * exp(17.27 * tair / (272.62 + tair) ) * 100.0;\n  }\n\n  return svp;\n}\n\n/** Cloudiness as a function of girr and nirr */\nfloat calculate_clouds(const float girr, const float nirr) {\n  assert (nirr >= 0.0 && \"Invalid nirr in Climate::calculate_clouds(..)!\");\n  assert (girr >= 0.0 && \"Invalid girr in Climate::calculate_clouds(..)!\");\n\n  float clouds;\n\n  if ( nirr >= (0.76 * girr) ) {\n    clouds = 0.0;\n  } else {\n    clouds = 1.0 - (((nirr/girr) - 0.251)/0.509);\n    clouds *= 100.0;\n  }\n\n  if ( clouds > 100.0 ) {\n    clouds = 100.0;\n  }\n\n  return clouds;\n}\n\n/** PAR (watts per meter squared) as a function of cloudiness and nirr. */\nfloat calculate_par(const float clds, const float nirr) {\n\n  float par;  //  W/m2\n\n  if ( clds >= 0.0 ) {\n    par = nirr * ((0.2 * clds / 100.0) + 0.45);\n  } else {\n    par = MISSING_D;\n  }\n\n  return par;\n}\n\n/** The rain/snow split as a function of temperatore and precip.\n\nWillmott's assumption. Returns a pair: (rain, snow).\n*/\nstd::pair<float, float> willmot_split(const float t, const float p) {\n  float r, s = 0.0;\n  if ( t > 0.0 ) {\n    r = p;\n    s = 0.0;\n  } else  {\n    r = 0.0;\n    s = p;\n  }\n  return std::make_pair(r,s);\n}\n\n/** GIRR (W/m^2) as a function of latitude and month.\n*\n*  More information and formulas can be found here:\n*  http://www.fao.org/docrep/X0490E/x0490e07.htm\n*  (section \"Extraterrestrial radiation for daily periods\")\n* \n*  And a table of expected values here:\n*  http://www.fao.org/docrep/X0490E/x0490e0j.htm#annex%202.%20meteorological%20tables\n* \n*  NOTE: To convert from MJ/m^2/day to W/m^2:\n*        multiply by (1,000,000)/(60*60*24) or ~11.57\n*/\nfloat calculate_girr(const float lat, const int im) {\n  const float pi = 3.141592654;                // Greek \"pi\" TODO: fix this to use constant from math library?\n  const float sp = 1368.0 * 3600.0 / 41860.0;  // solar constant\n  float lambda;\n  float sumd;\n  float sig;\n  float eta;\n  float sinbeta;\n  float sb;\n  float sotd;\n  int hour;\n  lambda = lat * pi / 180.0;\n  float gross = 0.0;\n\n  for ( int day = 0; day < DINM[im]; ++day ) {\n\n    // find julian day\n    // http://www.fao.org/docrep/X0490E/x0490e0j.htm#annex%202.%20meteorological%20tables\n    float jd = 0.0;\n    jd = (275 * (im+1)/9) - 30 + (day+1);\n    if( (im+1) < 3 ) {\n      jd = jd + 2;\n    }\n    int julianday = int(jd);\n\n    sumd = 0;\n    sig = -23.4856*cos(2 * pi * (julianday + 10.0)/365.25);\n    sig *= pi / 180.0;\n\n    for ( hour = 0; hour < 24; hour++ ) {\n      eta = (float) ((hour+1) - 12) * pi / 12.0;\n      sinbeta = sin(lambda)*sin(sig) + cos(lambda)*cos(sig)*cos(eta);\n      sotd = 1 - (0.016729 * cos(0.9856 * (julianday - 4.0)\n                                 * pi / 180.0));\n      sb = sp * sinbeta / pow((double)sotd,2.0);\n\n      if (sb >= 0.0) {\n        sumd += sb;\n      }\n    }\n\n    gross += sumd;\n  }\n\n  gross /= (float)DINM[im];\n  gross *= 0.484; // convert from cal/cm2day to W/m^2\n  return gross;\n}\n\nstd::vector<float> calculate_daily_prec(const int midx, const float mta, const float mprec) {\n                                  \n  // input are monthly precipitation, monthly temperature\n  // output are daily precpitation\n  // this function is based on the code provided Qianlai on Feb. 19, 2007\n  \n  float RT, RS, R ;\n  RT=1.778;\n  RS=0.635;\n  R=0.5;\n  float TEMP, PREC, DURT, DURS;\n  PREC = mprec/10.0/2.54; //comvert mm to cm, then to in.\n  DURT=RT/R;\n  DURS=RS/R;\n  float B=1.0, T=0.0, S=1.0, RB, DURB;\n\n  float RAINDUR[DINM[midx]];\n  float RAININTE[DINM[midx]];\n  for(int id = 0; id < DINM[midx]; id++) {\n    RAININTE[id] =0.;\n    RAINDUR[id] = 0.;\n  }\n\n  TEMP = mta;\n  \n  //  Case 1, TEMP<0.\n  if (TEMP <= 0.0) {\n    if (PREC <= 1.0) {\n      B=1.0;\n      T=0.0;\n      S=1.0;\n    } else {\n      B=1.0;\n      T=1.0;\n      S=1.0;\n    }\n  }\n  //   Case 2, PREC<1.0 inch.\n  else if (PREC <= 1.0) {\n    B=1.0;\n    T=0.0;\n    S=1.0;\n  }\n  //   Case 3, 1.0<PREC<2.5 inches.\n  else if ((2.5 >= PREC) && (PREC > 1.0)) {\n    B=1.0;\n    T=1.0;\n    S=1.0;\n  }\n  //   Case 4, 2.5<PREC<4.0 inches.\n  else if ((4.0 >= PREC) && (PREC > 2.5)) {\n    B=1.0;\n    S=4.0;\n\n    if (PREC < 3.7) {\n      T=1.0;\n    } else {\n      T=2.0;\n    }\n  }\n  //   Case 5, 4.0<PREC<5.0 inches.\n  else if ((5.0 >= PREC) && (PREC > 4.0)) {\n    B=1.0;\n    S=4.0;\n\n    if (PREC < 4.43) {\n      T=1.0;\n    } else {\n      T=2.0;\n    }\n  }\n  //   Case 6, 5.0<PREC<7.0 inches.\n  else if ((7.0 >= PREC) && (PREC > 5.0)) {\n    B=2.0;\n    S=4.0;\n\n    if (PREC < 5.65) {\n      T=1.0;\n    } else {\n      T=2.0;\n    }\n  }\n  //   Case 7, 7.0<PREC<9.0 inches.\n  else if ((9.0 >= PREC) && (PREC > 7.0)) {\n    B=2.0;\n    S=6.0;\n\n    if (PREC < 8.21) {\n      T=3.0;\n    } else {\n      T=4.0;\n    }\n  }\n  //   Case 8, 9.0<PREC<11.0 inches.\n  else if ((11.0 >= PREC) && (PREC > 9.0)) {\n    B=3.0;\n    S=6.0;\n\n    if (PREC < 10.0) {\n      T=4.0;\n    } else {\n      T=5.0;\n    }\n  }\n  //   Case 9, PREC>11.0 inches.\n  else if (PREC > 11.0) {\n    B=4.0;\n    S=7.0;\n\n    if (PREC < 13.0) {\n      T=4.0;\n    } else {\n      T=5.0;\n    }\n  }\n  \n  RB = ( PREC*2.54 - RS*S - RT*T ) / B;   // Yuan\n  DURB = RB / R;    // Yuan\n\n  if (DURB <= 0.01) {\n    DURB = 0.01;  // !added //changed from zero to 0.01 by shuhua\n  }\n\n  PREC = PREC * 2.54 * 10.0;  // convert back to cm, and then to mm\n  float BB, TT;\n  int KTT, KDD, KTD, KKTD;\n  int NN, DT;\n  DT = DINM[midx];\n  KTT = (int)(B+T);\n  KTD = DT / KTT;\n  KDD = DT - KTT * KTD;\n  BB = B;\n  TT = T;\n  NN = 0;\n  \n  for (int JJ=1; JJ<=KTT; JJ++) {\n    if (BB > 0.0) {\n      BB = BB - 1.0;\n\n      for (int L=1; L<=KTD; L++) {\n        NN = NN+1;\n        RAININTE[NN] = 0.0;\n        RAINDUR[NN] = 0.0;\n\n        if (L == KTD) {\n          RAININTE[NN] = 5.0; // unit with mm /hr\n          RAINDUR[NN] = DURB;\n        }\n      }\n    }\n\n    if (TT > 0.0) {\n      TT = TT - 1.0;\n\n      if (JJ == 1) {\n        KKTD = KTD+KDD;\n      } else {\n        KKTD = KTD;\n      }\n\n      for (int L=1; L <= KKTD; L++) {\n        NN = NN+1;\n        RAININTE[NN] = 0.0;\n        RAINDUR[NN] = 0.0;\n\n        if (L == KKTD) {\n          RAININTE[NN] = 5.0; //unit mm/hr\n          RAINDUR[NN] = DURT;\n        }\n      }\n    }\n  }  // end of for J\n  \n  // in winter season, DURT was always zero, so put the precipitation\n  //   on the day with RAININTE>0;\n  int numprec = 0;\n  double tothour = 0.;\n\n  for (int id = 0; id < DINM[midx]; id++) {\n    if (RAINDUR[id+1] > 0) {\n      numprec++;\n      tothour += RAINDUR[id+1];\n    }\n  }\n  \n  float sumprec = 0.;\n\n\n  std::vector<float> precip_daily (DINM[midx], 0);\n  if(numprec > 0) {\n    double rainrate = mprec / tothour;\n\n    for (int id = 0; id < DINM[midx]; id++) {\n      precip_daily[id] = RAINDUR[id+1] * rainrate;\n      sumprec += precip_daily[id];\n    }\n  }\n  \n  return precip_daily;\n}\n\n\n\nClimate::Climate() {\n  BOOST_LOG_SEV(glg, note) << \"--> CLIMATE --> empty ctor\";\n}\n\n\nClimate::Climate(const std::string& fname, const std::string& co2fname, int y, int x) {\n  BOOST_LOG_SEV(glg, note) << \"--> CLIMATE --> BETTER CTOR\";\n  this->load_from_file(fname, y, x);\n\n  // co2 is not spatially explicit\n  #pragma omp critical(load_input)\n  {\n    this->co2 = temutil::get_timeseries(co2fname, \"co2\");\n  }\n}\n\nvoid Climate::load_from_file(const std::string& fname, int y, int x) {\n\n  if(!boost::filesystem::exists(fname)){\n    BOOST_LOG_SEV(glg, fatal) << \"Input file \"<<fname<<\" does not exist\";\n  }\n\n  #pragma omp critical(load_input)\n  {\n    BOOST_LOG_SEV(glg, info) << \"Loading climate from file: \" << fname;\n    BOOST_LOG_SEV(glg, info) << \"Loading climate for (y, x) point: \"\n                             << \"(\" << y <<\",\"<< x <<\"), all timesteps.\";\n\n    BOOST_LOG_SEV(glg, info) << \"Read in the base climate data timeseries ...\";\n\n    tair = temutil::get_timeseries<float>(fname, \"tair\", y, x);\n    vapo = temutil::get_timeseries<float>(fname, \"vapor_press\", y, x);\n    prec = temutil::get_timeseries<float>(fname, \"precip\", y, x);\n    nirr = temutil::get_timeseries<float>(fname, \"nirr\", y, x);\n  }//End critical(load_climate)\n\n  // Report on sizes...\n  BOOST_LOG_SEV(glg, info) << \"  -->sizes (tair, vapor_press, precip, nirr): (\"\n                           << tair.size() << \", \" << vapo.size() << \", \"\n                           << prec.size() << \", \" << nirr.size() << \")\";\n\n  // assert all sizes are the same?\n  if ( !(tair.size() == prec.size() &&\n         tair.size() == vapo.size() &&\n         tair.size() == nirr.size()) ) {\n    BOOST_LOG_SEV(glg, err) << \"ERROR - your base climate datasets are not \"\n                            << \"the same size! Very little bounds checking \"\n                            << \"done, not sure what will happen.\";\n\n  }\n\n  // make some space for the derived variables\n  girr = std::vector<float>(12, 0); // <-- !! wow, no need for year dimension??\n  par = std::vector<float>(prec.size(), 0);\n  cld = std::vector<float>(prec.size(), 0);\n\n  BOOST_LOG_SEV(glg, debug) << \"tair = [\" << temutil::vec2csv(tair) << \"]\";\n  BOOST_LOG_SEV(glg, debug) << \"prec = [\" << temutil::vec2csv(prec) << \"]\";\n\n  // find girr as a function of month and latitude\n  std::pair<float, float> latlon = temutil::get_latlon(fname, y, x);\n  for (int im = 0; im < 12; ++im) {\n    float g = calculate_girr(latlon.first, im);\n    girr[im] = g;\n  }\n  BOOST_LOG_SEV(glg, debug) << \"nirr = [\" << temutil::vec2csv(nirr) << \"]\";\n  BOOST_LOG_SEV(glg, debug) << \"girr = [\" << temutil::vec2csv(girr) << \"]\";\n\n  // determine \"cloudiness\" based on ratio of girr and nirr\n  for (int i = 0; i < nirr.size(); ++i) {\n    int midx = i % 12;\n    cld[i] = calculate_clouds(girr[midx], nirr[i]);\n  }\n  BOOST_LOG_SEV(glg, debug) << \"cld = [\" << temutil::vec2csv(cld) << \"]\";\n\n  // find par based on cloudiness and nirr\n  for (int i = 0; i < cld.size(); ++i) {\n    par[i] = calculate_par(cld[i], nirr[i]);\n  }\n  BOOST_LOG_SEV(glg, debug) << \"par = [\" << temutil::vec2csv(par) << \"]\";\n\n  // create the simplified climate by averaging the first X years of data\n  avgX_tair = avg_over(tair, 30);\n  avgX_prec = avg_over(prec, 30);\n  avgX_nirr = avg_over(nirr, 30);\n  avgX_vapo = avg_over(vapo, 30);\n \n  // Do we need simplified 'avgX_' values for par, and cld??\n  // ===> YES: the derived variables should probably be based off the avgX\n  //      containers...\n\n\n  // Finally, need to create the daily dataset(s) by interpolating the monthly\n  // --> actually looking like these should not be calculated upon construction.\n  //     instead, they should get calculated each year...\n\n}\n\n/** This loads data from a projected climate data file, overwriting any old climate data*/\nvoid Climate::load_proj_climate(const std::string& fname, int y, int x){\n  BOOST_LOG_SEV(glg, note) << \"Climate, loading projected data\";\n\n  this->load_from_file(fname, y, x);\n}\n\nstd::vector<float> Climate::avg_over(const std::vector<float> & var, const int window) {\n\n  assert(var.size() % 12 == 0 && \"The data vector is the wrong size! var.size() should be an even multiple of 12.\");\n  assert(var.size() >= 12*window && \"The data vector is too short to average over the window!\");\n\n  // make space for the result - one number for each month\n  std::vector<float> result(12, 0);\n\n  for (int im = 0; im < 12; ++im) {\n    // make space for a month's data over the averaging window\n    std::vector<float> mdata(window, 0);\n\n    // gather up the data for this month over the averaging window\n    for (int iy = 0; iy < window; ++iy) {\n      mdata[iy] = var[iy*12 + im];\n    }\n\n    // average the data for the month\n    float sum = std::accumulate(mdata.begin(), mdata.end(), 0.0);\n\n    // put the value in the result vector for this month\n    result[im] = sum / window; // ?? should window be a float??\n\n    //BOOST_LOG_SEV(glg, debug) << \"result = [\" << temutil::vec2csv(result) << \"]\";\n\n  }\n\n  BOOST_LOG_SEV(glg, debug) << \"result = [\" << temutil::vec2csv(result) << \"]\";\n\n  return result;\n\n}\n\n\n// Interpolate from monthly values to daily. Does NOT account for leap years!\nstd::vector<float> Climate::monthly2daily(const std::vector<float>& mly_vals) {\n\n  // setup a container for the daily data\n  std::vector<float> daily_container;\n\n  // set up the \"month midpoint to relative days\" vector\n  static const float arr[] = { -15.5, 15.5, 45.0, 74.5, 105.0,\n                                135.5, 166, 196.5, 227.5, 258, 288.5,\n                                319, 349.5, 380.5 };\n  std::vector<float> rel_days;\n  rel_days.assign( arr, arr + sizeof(arr) / sizeof(arr[0]) );\n\n  assert(mly_vals.size() == 14 && \"Monthly values must be size 14 (D J F M A M J J A S O N D J)\");\n  assert(rel_days.size() == 14 && \"Relative days vector must be size 14: (D J F M A M J J A S O N D J)\");\n\n  for (std::vector<float>::iterator it = rel_days.begin()+1; it != rel_days.end(); ++it) {\n    int idx = it - rel_days.begin();\n\n    // find our range to work over\n    float x0 = *(it-1);\n    float x1 = *it;\n\n    std::vector<float> psd = temutil::resample(\n        std::make_pair( x0, mly_vals.at(idx-1) ),   // first point on line\n        std::make_pair( x1, mly_vals.at(idx) ),                // second point on line\n        int(floor(x0)),     // begining of interval to interpolate\n        int(floor(x1)),     // end of iterval to interpolate\n        1                   // step size\n    );\n\n    // Add this month's interpolated values to the back of the\n    // temporary storage...\n    daily_container.insert(daily_container.end(), psd.begin(), psd.end());\n  }\n\n  // TODO: Probably need to fix this? mostly works, but returns a container\n  // that has 366 elements, even on non-leap years. Also when plotting, there\n  // appears to be a slight discontinutiy in the interpolation from month to month\n  std::vector<float> cal_yr_daily(daily_container.begin()+16, daily_container.end()-14);\n\n  return cal_yr_daily;\n}\n\n// rough draft method to get \"prev\" Dec, this year, and \"next\" Jan that are\n// needed for monthly2daily interpolation...\nstd::vector<float> Climate::eq_range(const std::vector<float>& data) {\n  std::vector<float> foo;\n\n  // recycle Dec as the \"previous\" Dec\n  foo.push_back(data.at(11));\n\n  // get Jan - Dec values\n  foo.insert(foo.end(), data.begin(), data.begin()+12);\n\n  // use this Jan as \"next\" Jan\n  foo.push_back(data.at(0));\n\n  return foo;\n}\n\n/** Method to build a vector of 14 monthly data points for interpolation.\n* In order to interpolate out to the ends of the year, you need the 12 months\n* of data, plus the preceeding Dec and following Jan.\n*/\nstd::vector<float> Climate::interpolation_range(const std::vector<float>& data, int year){\n  //BOOST_LOG_SEV(glg, fatal) << \"interpolation_range, year: \"<<year;\n\n  std::vector<float> foo;\n\n  int curr_jan = year*12;\n\n  // Copy in previous Dec, unless in year 0\n  if(year==0){\n    foo.push_back(data.at(11));\n  }\n  else{\n    foo.push_back(data.at(curr_jan-1));\n  }\n\n  // Get Jan - Dec values\n  foo.insert(foo.end(), &data[curr_jan], &data[curr_jan+12]);\n\n  // Copy in next Jan, unless it is the last year's worth of data\n  if(year == data.size()/12-1){\n    foo.push_back(data.at(curr_jan));\n  }\n  else{\n    foo.push_back(data.at(curr_jan+13));\n  }\n\n  return foo;\n}\n\n\n/** Prepares a single year of daily driving data */ \nvoid Climate::prepare_daily_driving_data(int iy, const std::string& stage) {\n  //FIX rename iy to avoid confusion, since it isn't always the same\n  //as the iy in Runner (SP passes in a modded value).\n\n  if( (stage.find(\"pre\") != std::string::npos)\n      || (stage.find(\"eq\") != std::string::npos) ){\n    //Uses the same value of CO2 every day of the year.\n    //Pre-Run and EQ also use constant CO2 value for all years.\n    co2_d = co2.at(0);\n\n    //Create daily data by interpolating\n    tair_d = monthly2daily(eq_range(avgX_tair));\n    vapo_d = monthly2daily(eq_range(avgX_vapo));\n    nirr_d = monthly2daily(eq_range(avgX_nirr));\n\n    //Not totally sure if this is right to interpolate (girr and par) \n    par_d = monthly2daily(eq_range(par));\n  }\n  else{//Spin-up, Transient, Scenario\n    //Uses the same value of CO2 every day of the year\n    co2_d = co2.at(iy);\n\n    //Create daily data by interpolating\n    // straight up interpolated....\n    tair_d = monthly2daily(interpolation_range(tair, iy));\n    vapo_d = monthly2daily(interpolation_range(vapo, iy));\n    nirr_d = monthly2daily(interpolation_range(nirr, iy));\n\n    //Not totally sure if this is right to interpolate (girr and par) \n    par_d = monthly2daily(interpolation_range(par, iy));\n  }\n\n  //BOOST_LOG_SEV(glg, debug) << stage << \" tair_d = [\" << temutil::vec2csv(tair_d) << \"]\";\n\n  //Not totally sure if this is right to interpolate (girr and par)\n  //GIRR is passed to eq_range for all stages as it has only twelve values.\n  girr_d = monthly2daily(eq_range(girr));\n\n  // The interpolation is slightly broken, so it 'overshoots' when the\n  // slope is negative, and can result in negative values.\n  BOOST_LOG_SEV(glg, info) << \"Forcing negative values to zero in girr and nirr daily containers...\";\n  std::for_each(nirr_d.begin(), nirr_d.end(), temutil::force_negative2zero);\n  std::for_each(girr_d.begin(), girr_d.end(), temutil::force_negative2zero);\n\n  // much more complicated than straight interpolation...\n  prec_d.clear();\n  for (int i=0; i < 12; ++i) {\n    std::vector<float> v;\n    if( (stage.find(\"pre\") != std::string::npos)\n        || (stage.find(\"eq\") != std::string::npos) ){\n      v = calculate_daily_prec(i, avgX_tair.at(i), avgX_prec.at(i));\n    }\n    else{//Spin-Up, Transient, Scenario\n      v = calculate_daily_prec(i, tair.at(i), prec.at(i));\n    }\n\n    prec_d.insert( prec_d.end(), v.begin(), v.end() );\n  }\n\n  // derive rain and snow from precip...\n  // Look into boost::zip_iterator\n  rain_d.clear();\n  snow_d.clear();\n  for (int i = 0; i < prec_d.size(); ++i) {\n    std::pair<float, float> rs = willmot_split(tair_d[i], prec_d[i]);\n    rain_d.push_back(rs.first);\n    snow_d.push_back(rs.second);\n  }\n\n  svp_d.resize(tair_d.size());\n  std::transform( tair_d.begin(), tair_d.end(), svp_d.begin(), calculate_saturated_vapor_pressure );\n\n  vpd_d.resize(tair_d.size());\n  std::transform( svp_d.begin(), svp_d.end(), vapo_d.begin(), vpd_d.begin(), calculate_vpd );\n\n  cld_d.resize(tair_d.size());\n  std::transform( girr_d.begin(), girr_d.end(), nirr_d.begin(), cld_d.begin(), calculate_clouds );\n\n  // THESE MAY NEVER BE USED??\n  // rhoa_d;\n  // dersvp_d;\n  // abshd_d;\n\n  // Dump data to log stream for debugging analysis \n  //this->dailycontainers2log();\n}\n\n/** Print the contents of the monthly containers to the log stream.\n* Format is intendend to be copy/pastable into python.\n*/\nvoid Climate::monthlycontainers2log() {\n  BOOST_LOG_SEV(glg, debug) << \"co2 = [\" << temutil::vec2csv(co2) << \"]\";\n  BOOST_LOG_SEV(glg, debug) << \"tair = [\" << temutil::vec2csv(tair) << \"]\";\n  BOOST_LOG_SEV(glg, debug) << \"prec = [\" << temutil::vec2csv(prec) << \"]\";\n  BOOST_LOG_SEV(glg, debug) << \"nirr = [\" << temutil::vec2csv(nirr) << \"]\";\n  BOOST_LOG_SEV(glg, debug) << \"vapo = [\" << temutil::vec2csv(vapo) << \"]\";\n  BOOST_LOG_SEV(glg, debug) << \"girr = [\" << temutil::vec2csv(girr) << \"]\";\n  BOOST_LOG_SEV(glg, debug) << \"cld = [\" << temutil::vec2csv(cld) << \"]\";\n  BOOST_LOG_SEV(glg, debug) << \"par = [\" << temutil::vec2csv(par) << \"]\";\n}\n\n/** Print the contents of the daily containers to the log stream. \n* Format is intendend to be copy/pastable into python.\n*/\nvoid Climate::dailycontainers2log() {\n\n    BOOST_LOG_SEV(glg, debug) << \"tair_d = [\" << temutil::vec2csv(tair_d) << \"]\";\n    BOOST_LOG_SEV(glg, debug) << \"nirr_d = [\" << temutil::vec2csv(nirr_d) << \"]\";\n    BOOST_LOG_SEV(glg, debug) << \"vapo_d = [\" << temutil::vec2csv(vapo_d) << \"]\";\n    BOOST_LOG_SEV(glg, debug) << \"prec_d = [\" << temutil::vec2csv(prec_d) << \"]\";\n    BOOST_LOG_SEV(glg, debug) << \"rain_d = [\" << temutil::vec2csv(rain_d) << \"]\";\n    BOOST_LOG_SEV(glg, debug) << \"snow_d = [\" << temutil::vec2csv(snow_d) << \"]\";\n    BOOST_LOG_SEV(glg, debug) << \"svp_d = [\" << temutil::vec2csv(svp_d) << \"]\";\n    BOOST_LOG_SEV(glg, debug) << \"vpd_d = [\" << temutil::vec2csv(vpd_d) << \"]\";\n    BOOST_LOG_SEV(glg, debug) << \"girr_d = [\" << temutil::vec2csv(girr_d) << \"]\";\n    BOOST_LOG_SEV(glg, debug) << \"cld_d = [\" << temutil::vec2csv(cld_d) << \"]\";\n    BOOST_LOG_SEV(glg, debug) << \"par_d = [\" << temutil::vec2csv(par_d) << \"]\";\n\n    BOOST_LOG_SEV(glg, debug) << \"tair_d.size() = \" << tair_d.size();\n    BOOST_LOG_SEV(glg, debug) << \"nirr_d.size() = \" << nirr_d.size();\n    BOOST_LOG_SEV(glg, debug) << \"vapo_d.size() = \" << vapo_d.size();\n    BOOST_LOG_SEV(glg, debug) << \"prec_d.size() = \" << prec_d.size();\n    BOOST_LOG_SEV(glg, debug) << \"rain_d.size() = \" << rain_d.size();\n    BOOST_LOG_SEV(glg, debug) << \"snow_d.size() = \" << snow_d.size();\n    BOOST_LOG_SEV(glg, debug) << \"vpd_d.size() = \" << vpd_d.size();\n    BOOST_LOG_SEV(glg, debug) << \"svp_d.size() = \" << svp_d.size();\n    BOOST_LOG_SEV(glg, debug) << \"girr_d.size() = \" << girr_d.size();\n    BOOST_LOG_SEV(glg, debug) << \"cld_d.size() = \" << cld_d.size();\n    BOOST_LOG_SEV(glg, debug) << \"par_d.size() = \" << par_d.size();\n\n}\n", "meta": {"hexsha": "405a4bcab396d395eb81d416b8473b430e061bae", "size": 22248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Climate.cpp", "max_stars_repo_name": "rarutter/dvm-dos-tem", "max_stars_repo_head_hexsha": "8e776005c3883aae67b83bb71c5e1e25c94fc842", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Climate.cpp", "max_issues_repo_name": "rarutter/dvm-dos-tem", "max_issues_repo_head_hexsha": "8e776005c3883aae67b83bb71c5e1e25c94fc842", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Climate.cpp", "max_forks_repo_name": "rarutter/dvm-dos-tem", "max_forks_repo_head_hexsha": "8e776005c3883aae67b83bb71c5e1e25c94fc842", "max_forks_repo_licenses": ["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.1463414634, "max_line_length": 116, "alphanum_fraction": 0.58697411, "num_tokens": 7379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6317499358842609}}
{"text": "/*\n    mvee.hpp\n    Desc: Computes minimum volume ellipsoid\n    @author Chris Larson, Cornell University\n    @date (2017)\n    @version 1.0\n*/\n\n#ifndef MVEE_HPP_\n#define MVEE_HPP_\n\n#include <string>\n#include <vector>\n#include <Eigen/Dense>\n\n\nnamespace mvee {\n\nclass Mvee {\n\nprivate:\n\n\tstd::vector<double> _centroid;\n\n\tstd::vector<double> _radii;\n\n\tstd::vector<std::vector<double>> _pose;\n\t\n\tvoid decompose(Eigen::MatrixXd&,\n\t\t\t \t   Eigen::VectorXd&, \n\t\t\t \t   Eigen::MatrixXd&, \n\t\t\t \t   Eigen::MatrixXd&);\n\n\tvoid khachiyan(Eigen::MatrixXd&, double, double);\n\npublic:\n\t\n\tMvee();\n\n\tdouble time;\n\n\tlong int iters;\n\n\tstd::vector<double> centroid();\n\n\tstd::vector<double> radii();\n\n\tstd::vector<std::vector<double>> pose();\n\n\tvoid compute(std::vector<std::vector<double>>&, double, double);\n\n\tvoid compute(Eigen::MatrixXd&, double, double);\n\n\tvoid compute(std::string, char, double, double);\n\n\t~Mvee();\n\n};\n\n}\n\n\n#endif /* MVEE_HPP_ */", "meta": {"hexsha": "ce408c6b1cb240a3136eeb6a7806afc5fc11ea09", "size": 927, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mvee.hpp", "max_stars_repo_name": "chrislarson1/MVEE", "max_stars_repo_head_hexsha": "4a6aa32f05527dcb01c89a72803f0dcfd078d082", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-09T02:16:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T12:15:23.000Z", "max_issues_repo_path": "include/mvee.hpp", "max_issues_repo_name": "chrislarson1/MVEE", "max_issues_repo_head_hexsha": "4a6aa32f05527dcb01c89a72803f0dcfd078d082", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mvee.hpp", "max_forks_repo_name": "chrislarson1/MVEE", "max_forks_repo_head_hexsha": "4a6aa32f05527dcb01c89a72803f0dcfd078d082", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.7142857143, "max_line_length": 65, "alphanum_fraction": 0.6591154261, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6316713795290465}}
{"text": "#include <string>\n#include <map>\n#include <functional>\n#include <Eigen/Dense>\n#include \"two_layer_net.h\"\n#include \"simple_activation.h\"\n#include \"simple_loss.h\"\n\n#include <iostream>\n\nnamespace MyDL\n{\n\n    using namespace Eigen;\n    using std::cout;\n    using std::endl;\n\n    // \u30c7\u30d5\u30a9\u30eb\u30c8\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf(\u521d\u671f\u5024\u306f\u9069\u5f53)\n    TwoLayerNet::TwoLayerNet() : _input_size(3), _hidden_size(3), _output_size(2), _weight_init_std(0.01)\n    {\n        // params\u306b\u683c\u7d0d\u3059\u308b\u5909\u6570\u306e\u521d\u671f\u5316\n        MatrixXd W1 = _weight_init_std * MatrixXd::Random(_input_size, _hidden_size);\n        VectorXd b1 = VectorXd::Zero(_hidden_size);\n        MatrixXd W2 = _weight_init_std * MatrixXd::Random(_hidden_size, _output_size);\n        VectorXd b2 = VectorXd::Zero(_output_size);\n\n        params[\"W1\"] = W1;\n        params[\"W2\"] = W2;\n        params[\"b1\"] = b1;\n        params[\"b2\"] = b2;\n    }\n\n    // \u521d\u671f\u5024\u3042\u308a\u306e\u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\n    TwoLayerNet::TwoLayerNet(int input_size, int hidden_size, int output_size, double weight_init_std) : _input_size(input_size), _hidden_size(hidden_size), _output_size(output_size), _weight_init_std(weight_init_std)\n    {\n        // params\u306b\u683c\u7d0d\u3059\u308b\u5909\u6570\u306e\u521d\u671f\u5316\n        MatrixXd W1 = _weight_init_std * MatrixXd::Random(_input_size, _hidden_size);\n        VectorXd b1 = VectorXd::Zero(_hidden_size);\n        MatrixXd W2 = _weight_init_std * MatrixXd::Random(_hidden_size, _output_size);\n        VectorXd b2 = VectorXd::Zero(_output_size);\n\n        params[\"W1\"] = W1;\n        params[\"W2\"] = W2;\n        params[\"b1\"] = b1;\n        params[\"b2\"] = b2;\n    }\n\n    MatrixXd TwoLayerNet::predict(MatrixXd &X)\n    {\n        MatrixXd a1, a2, z1, y, W1, W2;\n        VectorXd b1, b2;\n        W1 = params[\"W1\"];\n        W2 = params[\"W2\"];\n        b1 = params[\"b1\"];\n        b2 = params[\"b2\"];\n\n        // \u30d6\u30ed\u30fc\u30c9\u30ad\u30e3\u30b9\u30c8\u6f14\u7b97\u3092\u3059\u308b\u3088\u3046\u306b\u5b9f\u88c5(numpy\u3068\u306f\u4ed5\u69d8\u304c\u9055\u3046\u3053\u3068\u306b\u6ce8\u610f)\n        a1 = (X * W1).rowwise() + b1.transpose();\n        z1 = sigmoid(a1);\n        a2 = (z1 * W2).rowwise() + b2.transpose();\n        y = softmax(a2);\n\n        _cache[\"a1\"] = a1;\n        _cache[\"z1\"] = z1;\n        _cache[\"a2\"] = a2;\n        _cache[\"y\"] = y;\n\n        return y;\n    }\n\n    double TwoLayerNet::loss(MatrixXd &x, MatrixXd &t)\n    {\n        MatrixXd y;\n        y = this->predict(x);\n\n        double loss;\n        loss = MyDL::cross_entropy_error(y, t);\n        return loss;\n    }\n\n    double TwoLayerNet::accuracy(MatrixXd& x, MatrixXd& t){\n        MatrixXd y;\n        MatrixXd::Index y_row, y_col, t_row, t_col;\n\n        double accuracy = 0;\n        int batch_size = t.rows();\n        // double max_y, max_t;\n\n        y = this->predict(x);\n\n        // \u5404\u884c\u3054\u3068\u306b\u3001\u6700\u5927\u8981\u7d20\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3092\u53d6\u5f97 \u2192 \u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u304c\u7b49\u3057\u3051\u308c\u3070\u3001accuracy\u306b\u52a0\u7b97\n        for (int i=0; i < batch_size; i++){\n            y.row(i).maxCoeff(&y_row, &y_col);\n            t.row(i).maxCoeff(&t_row, &t_col);\n\n            accuracy += (double)(y_col == t_col); // \u30ab\u30e9\u30e0\u306e\u30a4\u30f3\u30c7\u30c3\u30af\u30b9\u3060\u3051\u898b\u308c\u3070OK\n        }\n\n        return accuracy / batch_size;\n    }\n\n    // \u6570\u5024\u5fae\u5206\u3067\u306f\u9045\u3059\u304e\u308b\u306e\u3067\u3001\u8aa4\u5dee\u9006\u4f1d\u64ad\u6cd5\u3092\u5b9f\u88c5\n    std::map<std::string, MatrixXd> TwoLayerNet::gradient(MatrixXd& X, MatrixXd& t){\n        using std::map;\n        using std::string;\n\n        map<string, MatrixXd> grads;\n        MatrixXd dW1, dW2;\n        VectorXd db1, db2;\n\n        MatrixXd da2, da1, dz1;\n        MatrixXd y, z1, a1, a2, W1, W2, b1, b2;\n        int batch_size = t.rows();\n\n        y  = this->predict(X); // \u3053\u308c\u3092\u30b3\u30fc\u30eb\u3057\u3066\u304a\u304b\u306a\u3044\u3068\u3001_cache\u306e\u5404\u7a2e\u5909\u6570\u304c\u4fdd\u5b58\u3055\u308c\u306a\u3044\n        a1 = _cache[\"a1\"];\n        a2 = _cache[\"a2\"];\n        z1 = _cache[\"z1\"];\n        W1 = params[\"W1\"];\n        W2 = params[\"W2\"];\n        b1 = params[\"b1\"];\n        b2 = params[\"b2\"];\n\n        // \u9006\u4f1d\u64ad\u8a08\u7b97\n        // softmax with loss layer\n        da2 = (y - t) / batch_size;\n        // affine layer 2\n        dz1 = da2 * W2.transpose();\n        dW2 = z1.transpose() * da2; // \u7e26\u30d9\u30af\u30c8\u30eb \u00d7 \u6a2a\u30d9\u30af\u30c8\u30eb \u306e\u69cb\u56f3(\u30d0\u30c3\u30c1\u65b9\u5411\u306b\u7e2e\u7d04)\n        db2 = da2.colwise().sum();\n        // sigmoid layer: da1 = z1(1-z1) * dz1\n        da1 = z1.array() * (MatrixXd::Ones(z1.rows(), z1.cols()) - z1).array() * dz1.array();\n        // affine layer 1\n        dW1 = X.transpose() * da1;\n        db1 = da1.colwise().sum();\n        // dx = da1 * W2.transpose() // \u2192 \u4eca\u56de\u306f\u5fc5\u8981\u306a\u3044\u306e\u3067\u30b9\u30eb\u30fc\n\n        grads[\"W1\"] = dW1;\n        grads[\"W2\"] = dW2;\n        grads[\"b1\"] = db1;\n        grads[\"b2\"] = db2;\n\n        return grads;\n    }\n\n}", "meta": {"hexsha": "e0dfe676a73465bf4855fe8e8a67b67704dd60e5", "size": 4172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/two_layer_net.cpp", "max_stars_repo_name": "potedo/MNIST_loader_sample", "max_stars_repo_head_hexsha": "6c6723c8c20e05ecc093a04fa045d20a73dd04f8", "max_stars_repo_licenses": ["MIT"], "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/two_layer_net.cpp", "max_issues_repo_name": "potedo/MNIST_loader_sample", "max_issues_repo_head_hexsha": "6c6723c8c20e05ecc093a04fa045d20a73dd04f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/two_layer_net.cpp", "max_forks_repo_name": "potedo/MNIST_loader_sample", "max_forks_repo_head_hexsha": "6c6723c8c20e05ecc093a04fa045d20a73dd04f8", "max_forks_repo_licenses": ["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.5753424658, "max_line_length": 217, "alphanum_fraction": 0.5558485139, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.631659796479527}}
{"text": "#define NUM_BITS_REAL_MANTISSA 128\n#include <cstdint>\n#include <cmath>\n#include <NTL/ZZ.h>\n\n#include \"binomials.hpp\"\n\nint main(int argc, char* argv[]){\n if(argc != 3){\n     std::cout << \"Calculator to derive the length of the encodable bit string via CW-enc\" << std::endl << \" Usage \" \n               << argv[0] << \" <codeword_size> <number_of_errors> \" << std::endl;\n    return -1;\n }\n\n InitBinomials();\n NTL::RR::SetPrecision(NUM_BITS_REAL_MANTISSA);\n pi = NTL::ComputePi_RR();\n uint32_t n = atoi(argv[1]);\n uint32_t t = atoi(argv[2]);\n /* reduce by a factor matching the QC block size */\n NTL::RR encodable_length;\n encodable_length = lnBinom(NTL::to_RR(n), NTL::to_RR(t))/NTL::log(NTL::RR(2));\n\n NTL::RR d = NTL::to_RR( 0.69315 * ((double)n - ( (double)t - 1.0)/2.0) /((double) t) );\n\n std::cout << \"Maximum safely encoded: \" << t*NTL::conv<unsigned long int>(NTL::floor(NTL::log(d)/NTL::log(NTL::RR(2))+1)) << std::endl;\n std::cout << \"#define MAX_ENCODABLE_BIT_SIZE_CW_ENCODING (\" << NTL::conv<unsigned long int>(encodable_length) << \")\" ;\n  std::cout << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "b0d80dd57d91b475c1f7bc3f859737bb1cce6b11", "size": 1086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "constant_weight_encodable_bits.cpp", "max_stars_repo_name": "alexrow/LEDAtools", "max_stars_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "constant_weight_encodable_bits.cpp", "max_issues_repo_name": "alexrow/LEDAtools", "max_issues_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "constant_weight_encodable_bits.cpp", "max_forks_repo_name": "alexrow/LEDAtools", "max_forks_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-12T09:12:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T09:12:30.000Z", "avg_line_length": 35.0322580645, "max_line_length": 136, "alphanum_fraction": 0.6399631676, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6316324752361874}}
{"text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n/* \n * File:   polynomial_selection.cpp\n * Author: pankaj\n *\n * Created on 20 February, 2016, 11:40 AM\n */\n\n#include <cstdlib>\n\n\n#include <iostream>\n#include<string>\n#include<NTL/tools.h>\n#include<NTL/vector.h>\n#include<NTL/matrix.h>\n#include<NTL/ZZX.h>\n#include<NTL/mat_ZZ.h>\n#include<NTL/GF2X.h>\n#include <NTL/pair_GF2X_long.h>\n#include<NTL/GF2XFactoring.h>\n#include<NTL/GF2E.h>\n#include<NTL/mat_GF2E.h>\n#include<math.h>\n#include\"ffspol.h\"\n#include\"ffstools.h\"\n#include<string>\n\n\n//Resultant by sylvester's matrix method\nvoid resultant(GF2X& r,const ffs_poly& f,const ffs_poly& g)\n{\n  GF2X p=BuildSparseIrred_GF2X(1000); //set some large bound of degree for sparse irreducible polynomial which will not affect the computation  \n  GF2E::init(p);\n\n  Mat<GF2E> M;\t\n long d=f.deg+g.deg;\n \n M.SetDims(d,d);\n long n=f.deg;\n long m=g.deg; \n int i,j;\n\n//Initialize the matrix with zero's\n for(i=0;i<d;i++)\n for(j=0;j<d;j++)\n  M[i][j]=conv<GF2E>(0);\n\nfor(i=0;i<m;i++)\n for(j=0;j<d;j++)\n{\n   if(i>=0 && m>i)\n  {\n   M[i][j]=conv<GF2E>(f.coeffs[n+i-j]);\n   \n  } \n} \n\n for(;i<d;i++)\n for(j=0;j<d;j++)\n{\n   if((i-j)>=0 && (i-j)<2)\n   {\n     M[i][j]=conv<GF2E>(g.coeffs[i-j]);\n   }\n}\nr=conv<GF2X>(determinant(M)); \n}\n\nffs_poly polynomial_selection(const ffs_poly& f,const long n)\n{\n   ffs_poly g;\n   long t=2;\n   Vec< Pair< GF2X,long > > factors;\n   // vec_GF2X factors;\n   factors.SetLength(100);\n   long d=ceil(n/f.deg);\n   g.deg=1;\n  g.coeffs.SetLength(t);\n \n   GF2X g0,g1;\n   GF2X res;\n    \t\n  while(1)\n  {\n     g0=random_GF2X(d+1);\n     g1=random_GF2X(d+1);\n\n     cout<<\"g0=\"<<g0<<endl;\n     cout<<\"g0=\"<<g0<<endl;\n\n     g.coeffs[0]=g0;\n     g.coeffs[1]=g1;          \n     resultant(res,f,g);  \n\n    cout<<\"\\n\\nResulant=\"<<res<<endl;\n\n    CanZass(factors,res,(long)0); //defined in GF2XFactoring.h\n\n    cout<<\"Factors=\"<<factors<<endl;\n \n    for(int i=0;i<factors.length();i++)\n    {\n     if(IterIrredTest(factors[i].a) && (deg(factors[i].a)==n)) \n     {\n       cout<<\"Irreducible factor of degree n:-\"<<factors[i].a<<endl;\n       return g;\n     }\n   }\n  \n }\n\n}\n\n\nint main()\n{\n  ffs_poly f,g;\n  long n=607;\n  string pol_f=\"4,0,3,0,0,1\";\n  cout<<\"\\n polynomial f:\\n\";\n  read_ffs_poly(f,pol_f);\n  print_ffs_poly(f); \n  cout<<\"\\nPolynomial g:\\n\";  \n  g=polynomial_selection(f,n); \n  print_ffs_poly(g);\n  return 0;\n}\n\n\n", "meta": {"hexsha": "006704524caba0d14918c0c2f17741305d8d65a4", "size": 2493, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "polynomial_selection.cpp", "max_stars_repo_name": "pankajcharpe/FunctionFieldSeieve", "max_stars_repo_head_hexsha": "b4df784ba7e52c13ba8324b81b4b6f8216dbef19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "polynomial_selection.cpp", "max_issues_repo_name": "pankajcharpe/FunctionFieldSeieve", "max_issues_repo_head_hexsha": "b4df784ba7e52c13ba8324b81b4b6f8216dbef19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "polynomial_selection.cpp", "max_forks_repo_name": "pankajcharpe/FunctionFieldSeieve", "max_forks_repo_head_hexsha": "b4df784ba7e52c13ba8324b81b4b6f8216dbef19", "max_forks_repo_licenses": ["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.3308823529, "max_line_length": 144, "alphanum_fraction": 0.6109105495, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.631632469174785}}
{"text": "#include <iostream>\n#include <cmath>\n#include <cassert>\n#include <arprec/mp_real.h>\n#include \"Polynomklasse_templ.hpp\"\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace std;\n\nclass mp_starter\n{\n  public:\n    mp_starter() { mp::mp_init(40); }\n    ~mp_starter() { mp::mp_finalize(); }\n};\n\nconst mp_starter dummy;\n\nint const gp=10; //=N+1\nmp_real gitter[gp];\nmp_real e(\"1.0\");\n\n\npolynom<mp_real> phi(int i, mp_real eins, mp_real zwei){\n\tpolynom<mp_real> c(1);\n\tif(i==0||i==gp-1){\n\t\tc.data[0]=0.0;\n\t\tc.data[1]=0.0;\n\t\treturn c;\n\t}\n\tif(eins==gitter[i] && zwei==gitter[i+1]){\n\t\tc.data[0]=-gitter[i+1]/(gitter[i]-gitter[i+1]);\n\t\tc.data[1]=1/(gitter[i]-gitter[i+1]);\n\t}else if(eins==gitter[i-1] && zwei==gitter[i]){\n\t\tc.data[0]=-gitter[i-1]/(gitter[i]-gitter[i-1]);\n\t\tc.data[1]=1/(gitter[i]-gitter[i-1]);\n\t}else{\n\t\tc.data[0]=0.0;\n\t\tc.data[1]=0.0;\n\t}\n\treturn c;\n}\n\nmp_real func_c(mp_real x){\n\treturn 1.0;\n}\n\nmp_real f(mp_real x){\n\treturn 1.0;\n}\n\npolynom<mp_real> inter_c(int i, mp_real eins, mp_real zwei){\n\tpolynom<mp_real> c(1);\n\tif(i==0||i==gp-1){\n\t\tc.data[0]=0.0;\n\t\tc.data[1]=0.0;\n\t\treturn c;\n\t} \n\tif(eins==gitter[i] && zwei==gitter[i+1]){\n\t\tc.data[0]=func_c(gitter[i])*(-1.0)*(gitter[i+1])/(gitter[i]-gitter[i+1]);\n\t\tc.data[1]=func_c(gitter[i])/(gitter[i]-gitter[i+1]);\n\t}else if(eins==gitter[i-1] && zwei==gitter[i]){\n\t\tc.data[0]=func_c(gitter[i])*(-1.0)*(gitter[i-1])/(gitter[i]-gitter[i-1]);\n\t\tc.data[1]=func_c(gitter[i])/(gitter[i]-gitter[i-1]);\n\t}else{\n\t\tc.data[0]=0.0;\n\t\tc.data[1]=0.0;\n\t}\n\treturn c;\n}\npolynom<mp_real> inter_f(mp_real eins, mp_real zwei){\n\tpolynom<mp_real> c(1);\n\tc.data[0]=f(eins)-(f(zwei)-f(eins))/(zwei-eins)*eins;\n\tc.data[1]=(f(zwei)-f(eins))/(zwei-eins);\n\treturn c;\n\n}\n\n\n\nmp_real eintrag(int i, int j){\n\tmp_real tmp=0.0;\n\tfor(int k=0;k<gp-1;k++){\n\t\tpolynom<mp_real> da=phi(i,gitter[k],gitter[k+1]).diff();\n\t\tpolynom<mp_real> db=phi(j,gitter[k],gitter[k+1]).diff();\n\t\tpolynom<mp_real> b=phi(j,gitter[k],gitter[k+1]);\n\t\tpolynom<mp_real> I_ca=inter_c(i,gitter[k],gitter[k+1]);\n\t\ttmp+=(e*e)*(da*db).integral(gitter[k],gitter[k+1])+(I_ca*b).integral(gitter[k],gitter[k+1]);\n\t}\n\treturn tmp;\t\n\t\n}\n\nmp_real vektoreintrag(int j){\n\tmp_real tmp=0.0;\n\tfor(int k=0;k<gp-1;k++){\n\t\tpolynom<mp_real> b=phi(j,gitter[k],gitter[k+1]);\n\t\tpolynom<mp_real> I_f=inter_f(gitter[k],gitter[k+1]);\n\t\ttmp+=(I_f*b).integral(gitter[k],gitter[k+1]);\n\t}\n\treturn tmp;\n}\n\nint main(){\n\tcout<<\"test\";\n\t// mp::mp_init(40);\n\tcout<<\"test1\";\n\tfor (int i=0;i<gp;i++){\n\t\tcout<<\"test2\";\n\t\tgitter[i]=1.0*i/(gp-1);\n\t\tcout<<\"test3\";\n\t\tcout<<\"gitter[\"<<i<<\"]=\"<<gitter[i]<<\" \\n\";\n\t\n\t}\n\n\tcout.precision(3);\t\n\t\n\t\n\tmtl::dense2D<mp_real> matrix(gp-2,gp-2);\n\n\tfor(int i=1;i<gp-1;i++){\n\t\tfor(int j=1;j<gp-1;j++){\n\t\t\tmatrix[i-1][j-1]=eintrag(i,j);\n\t\t\t\n\t\t}\n\t}\n\t\n\tcout<<matrix;\n\t\n\tmtl::dense_vector<mp_real> vector(gp-2),p(gp-2);\n\t\n\tfor(int i=1;i<gp-1;i++){\n\t\tvector[i-1]=vektoreintrag(i);\n\t}\n\tcout<<vector<<\"\\n\";\n\t\n\tp=lu_solve(matrix,vector);\n\t\n\tcout<<p<<\"\\n\";\n\n\t\n\treturn 0;\n\n\t\n}\n", "meta": {"hexsha": "dd07a3cfe705b08e989e0779b55d09903ad48cf7", "size": 2952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/linFEM_mp_real.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/experimental/linFEM_mp_real.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/experimental/linFEM_mp_real.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 20.2191780822, "max_line_length": 94, "alphanum_fraction": 0.6029810298, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.631632460272847}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008-2012 Gael Guennebaud <gael.guennebaud@inria.fr>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"main.h\"\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\n\ntemplate<typename Scalar>\nvoid verify_euler(const Matrix<Scalar,3,1>& ea, int i, int j, int k)\n{\n  typedef Matrix<Scalar,3,3> Matrix3;\n  typedef Matrix<Scalar,3,1> Vector3;\n  typedef AngleAxis<Scalar> AngleAxisx;\n  using std::abs;\n  Matrix3 m(AngleAxisx(ea[0], Vector3::Unit(i)) * AngleAxisx(ea[1], Vector3::Unit(j)) * AngleAxisx(ea[2], Vector3::Unit(k)));\n  Vector3 eabis = m.eulerAngles(i, j, k);\n  Matrix3 mbis(AngleAxisx(eabis[0], Vector3::Unit(i)) * AngleAxisx(eabis[1], Vector3::Unit(j)) * AngleAxisx(eabis[2], Vector3::Unit(k))); \n  VERIFY_IS_APPROX(m,  mbis); \n  /* If I==K, and ea[1]==0, then there no unique solution. */ \n  /* The remark apply in the case where I!=K, and |ea[1]| is close to pi/2. */ \n  if( (i!=k || ea[1]!=0) && (i==k || !internal::isApprox(abs(ea[1]),Scalar(M_PI/2),test_precision<Scalar>())) ) \n    VERIFY((ea-eabis).norm() <= test_precision<Scalar>());\n  \n  // approx_or_less_than does not work for 0\n  VERIFY(0 < eabis[0] || test_isMuchSmallerThan(eabis[0], Scalar(1)));\n  VERIFY_IS_APPROX_OR_LESS_THAN(eabis[0], Scalar(M_PI));\n  VERIFY_IS_APPROX_OR_LESS_THAN(-Scalar(M_PI), eabis[1]);\n  VERIFY_IS_APPROX_OR_LESS_THAN(eabis[1], Scalar(M_PI));\n  VERIFY_IS_APPROX_OR_LESS_THAN(-Scalar(M_PI), eabis[2]);\n  VERIFY_IS_APPROX_OR_LESS_THAN(eabis[2], Scalar(M_PI));\n}\n\ntemplate<typename Scalar> void check_all_var(const Matrix<Scalar,3,1>& ea)\n{\n  verify_euler(ea, 0,1,2);\n  verify_euler(ea, 0,1,0);\n  verify_euler(ea, 0,2,1);\n  verify_euler(ea, 0,2,0);\n\n  verify_euler(ea, 1,2,0);\n  verify_euler(ea, 1,2,1);\n  verify_euler(ea, 1,0,2);\n  verify_euler(ea, 1,0,1);\n\n  verify_euler(ea, 2,0,1);\n  verify_euler(ea, 2,0,2);\n  verify_euler(ea, 2,1,0);\n  verify_euler(ea, 2,1,2);\n}\n\ntemplate<typename Scalar> void eulerangles()\n{\n  typedef Matrix<Scalar,3,3> Matrix3;\n  typedef Matrix<Scalar,3,1> Vector3;\n  typedef Array<Scalar,3,1> Array3;\n  typedef Quaternion<Scalar> Quaternionx;\n  typedef AngleAxis<Scalar> AngleAxisx;\n\n  Scalar a = internal::random<Scalar>(-Scalar(M_PI), Scalar(M_PI));\n  Quaternionx q1;\n  q1 = AngleAxisx(a, Vector3::Random().normalized());\n  Matrix3 m;\n  m = q1;\n  \n  Vector3 ea = m.eulerAngles(0,1,2);\n  check_all_var(ea);\n  ea = m.eulerAngles(0,1,0);\n  check_all_var(ea);\n  \n  // Check with purely random Quaternion:\n  q1.coeffs() = Quaternionx::Coefficients::Random().normalized();\n  m = q1;\n  ea = m.eulerAngles(0,1,2);\n  check_all_var(ea);\n  ea = m.eulerAngles(0,1,0);\n  check_all_var(ea);\n  \n  // Check with random angles in range [0:pi]x[-pi:pi]x[-pi:pi].\n  ea = (Array3::Random() + Array3(1,0,0))*Scalar(M_PI)*Array3(0.5,1,1);\n  check_all_var(ea);\n  \n  ea[2] = ea[0] = internal::random<Scalar>(0,Scalar(M_PI));\n  check_all_var(ea);\n  \n  ea[0] = ea[1] = internal::random<Scalar>(0,Scalar(M_PI));\n  check_all_var(ea);\n  \n  ea[1] = 0;\n  check_all_var(ea);\n  \n  ea.head(2).setZero();\n  check_all_var(ea);\n  \n  ea.setZero();\n  check_all_var(ea);\n}\n\nvoid test_geo_eulerangles()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( eulerangles<float>() );\n    CALL_SUBTEST_2( eulerangles<double>() );\n  }\n}\n", "meta": {"hexsha": "b4830bd41f22e689191ef2d415e810c279866680", "size": 3510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/eigen/test/geo_eulerangles.cpp", "max_stars_repo_name": "MelvinG24/dust3d", "max_stars_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/eigen/test/geo_eulerangles.cpp", "max_issues_repo_name": "MelvinG24/dust3d", "max_issues_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T20:31:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T15:29:20.000Z", "max_forks_repo_path": "thirdparty/instant-meshes/instant-meshes-dust3d/ext/nanogui/ext/eigen/test/geo_eulerangles.cpp", "max_forks_repo_name": "MelvinG24/dust3d", "max_forks_repo_head_hexsha": "c4936fd900a9a48220ebb811dfeaea0effbae3ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 31.0619469027, "max_line_length": 138, "alphanum_fraction": 0.6726495726, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6314886986040429}}
{"text": "#include \"stdafx.h\"\n\n#include <iostream>\n#include <stdio.h>\n\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <Math.h>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n\n#include \"utils.h\"\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace cv;\n\nconst float LIMBUS_R_MM = 6;\n\n// ThinkpadHelix Params\nconst double FOCAL_LEN_X_PX = 957.648052597;\nconst double FOCAL_LEN_Y_PX = 960.154605354;\nconst double FOCAL_LEN_Z_PX = (FOCAL_LEN_X_PX + FOCAL_LEN_Y_PX) / 2;\nconst cv::Point2d PRIN_POINT(634.799023712, 367.91715841);\n\nvector<Vector3d> ellipse_to_limbus(cv::RotatedRect ellipse, bool limbus_switch=true){\n\n\tvector<Vector3d> limbus_to_return;\n\n\tdouble maj_axis_px = ellipse.size.width, min_axis_px = ellipse.size.height;\n\n\t// Using iris_r_px / focal_len_px = iris_r_mm / distance_to_iris_mm\n\tdouble iris_z_mm = (LIMBUS_R_MM * 2 * FOCAL_LEN_Z_PX) / maj_axis_px;\n    \n    // Using (x_screen_px - prin_point) / focal_len_px = x_world / z_world\n\tdouble iris_x_mm = -iris_z_mm * (ellipse.center.x - PRIN_POINT.x) / FOCAL_LEN_X_PX;\n    double iris_y_mm = iris_z_mm * (ellipse.center.y - PRIN_POINT.y) / FOCAL_LEN_Y_PX;\n\n\tVector3d limbus_center(iris_x_mm, iris_y_mm, iris_z_mm);\n\n\tdouble psi = CV_PI / 180.0 * (ellipse.angle+90);    // z-axis rotation (radians)\n    double tht = acos(min_axis_px / maj_axis_px);       // y-axis rotation (radians)\n\n\tif (limbus_switch) tht = -tht;                      // ambiguous acos, so sometimes switch limbus\n\n    // Get limbus normal for chosen theta\n    Vector3d limb_normal(sin(tht) * cos(psi), -sin(tht) * sin(psi), -cos(tht));\n\n\t// Now correct for weak perspective by modifying angle by offset between camera axis and limbus\n    double x_correction = -atan2(iris_y_mm, iris_z_mm);\n    double y_correction = -atan2(iris_x_mm, iris_z_mm);\n\tAngleAxisd rot1(y_correction, Vector3d(0,-1,0));\n\tAngleAxisd rot2(x_correction, Vector3d(1,0,0));\n\tlimb_normal = rot1 * limb_normal;\n\tlimb_normal = rot2 * limb_normal;\n\n\tlimbus_to_return.push_back(limbus_center);\n\tlimbus_to_return.push_back(limb_normal);\n\treturn limbus_to_return;\n}\n\n// returns intersection with z-plane of optical axis vector (mm)\nPoint2d get_gaze_point_mm(Vector3d limb_center, Vector3d limb_normal){\n    \n    // ray/plane intersection\n    double t = -limb_center.z() / limb_normal.z();\n    return Point2d(limb_center.x() + limb_normal.x() * t, limb_center.y() + limb_normal.y() * t);\n}\n\n\nPoint2d get_gaze_pt_mm(RotatedRect& ellipse){\n\n\t// get two possible limbus centres and normals because of ambiguous trig\n\tvector<Vector3d> limbus_a = ellipse_to_limbus(ellipse, true);\n\tvector<Vector3d> limbus_b = ellipse_to_limbus(ellipse, false);\n\n\t// calculate gaze points for each possible limbus\n\tPoint2d gp_mm_a = get_gaze_point_mm(limbus_a[0], limbus_a[1]);\n\tPoint2d gp_mm_b = get_gaze_point_mm(limbus_b[0], limbus_b[1]);\n\n\t// calculate distance from centre of screen for each possible gaze point\n\tint dist_a = std::abs(gp_mm_a.x) + std::abs(gp_mm_a.y);\n\tint dist_b = std::abs(gp_mm_b.x) + std::abs(gp_mm_b.y);\n\n\t// return gaze point closest to screen centre\n\treturn (dist_a < dist_b) ? gp_mm_a : gp_mm_b;\n}\n\n\nconst Size SCREEN_SIZE_MM(236, 134);\nconst Size SCREEN_SIZE_PX(1920, 1080);\t\t// screen size in pixels\nconst Point2i CAMERA_OFFSET_MM(120, 140);\t// vector from top left of screen to camera\n\n\nPoint2i convert_gaze_pt_mm_to_px(Point2d gaze_pt_mm){\n\n\tint gp_px_x = (gaze_pt_mm.x + CAMERA_OFFSET_MM.x) / SCREEN_SIZE_MM.width * SCREEN_SIZE_PX.width;\n    int gp_px_y = (gaze_pt_mm.y + CAMERA_OFFSET_MM.y) / SCREEN_SIZE_MM.height * SCREEN_SIZE_PX.height;\n    \n    return Point2i(gp_px_x, gp_px_y);\n}\n\n\nfloat scale = 720 / float(SCREEN_SIZE_PX.height);\n\n// draws the gaze-points on-screen as circles and crosses\nvoid show_gaze(Mat& img, vector<Point2i> gaze_pt_raw_s, vector<Scalar> colors_raw, Point2i gaze_pt_smoothed, Scalar color_smoothed){\n\n\tMat screen(SCREEN_SIZE_PX.height, SCREEN_SIZE_PX.width, CV_8UC3);\n\tscreen.setTo(YELLOW);\n\n\t// draw ra\n\tfor (int i=0; i<gaze_pt_raw_s.size(); i++)\n\t\tcircle(img, gaze_pt_raw_s[i] * scale, 10, colors_raw[i], -1);\n\n\tcircle(img, gaze_pt_smoothed * scale, 20, color_smoothed, -1);\n}", "meta": {"hexsha": "1b54d4c09bc7ae40ecd22850e94a4c9b5d136335", "size": 4161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EyeTab/gaze_geometry.cpp", "max_stars_repo_name": "errollw/EyeTab", "max_stars_repo_head_hexsha": "4aa63fdd23c3a9eadcfa30a356cd6d48f55a9055", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 96.0, "max_stars_repo_stars_event_min_datetime": "2015-03-16T06:00:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:22:35.000Z", "max_issues_repo_path": "EyeTab_SP2/gaze_geometry.cpp", "max_issues_repo_name": "Amal-Vincent/EyeTab", "max_issues_repo_head_hexsha": "4aa63fdd23c3a9eadcfa30a356cd6d48f55a9055", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-11-01T06:49:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-12T08:43:36.000Z", "max_forks_repo_path": "EyeTab_SP2/gaze_geometry.cpp", "max_forks_repo_name": "Amal-Vincent/EyeTab", "max_forks_repo_head_hexsha": "4aa63fdd23c3a9eadcfa30a356cd6d48f55a9055", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-02-18T21:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T10:56:01.000Z", "avg_line_length": 35.2627118644, "max_line_length": 132, "alphanum_fraction": 0.7406873348, "num_tokens": 1228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.6314795022383319}}
{"text": "/* @file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Molassembler/Shapes/Diophantine.h\"\n\nusing namespace Scine::Molassembler::Shapes;\n\nBOOST_AUTO_TEST_CASE(DiophantineExample, *boost::unit_test::label(\"Shapes\")) {\n  std::vector<unsigned> x;\n  const std::vector<unsigned> a {4, 3, 2};\n  const int b = 12;\n\n  const std::vector<\n    std::vector<unsigned>\n  > expectedX {\n    {0, 0, 6},\n    {0, 2, 3},\n    {0, 4, 0},\n    {1, 0, 4},\n    {1, 2, 1},\n    {2, 0, 2},\n    {3, 0, 0}\n  };\n\n  BOOST_REQUIRE(Diophantine::first_solution(x, a, b));\n  unsigned i = 0;\n  do {\n    BOOST_CHECK(x == expectedX.at(i));\n    ++i;\n  } while(Diophantine::next_solution(x, a, b));\n  BOOST_REQUIRE_EQUAL(i, expectedX.size());\n  BOOST_REQUIRE(x == std::vector<unsigned> (3, 0));\n}\n", "meta": {"hexsha": "0e13d57e8681a2ece0c119613844de71cc82acab", "size": 937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Shapes/Diophantine.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "test/Shapes/Diophantine.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Shapes/Diophantine.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 24.0256410256, "max_line_length": 78, "alphanum_fraction": 0.6339381003, "num_tokens": 302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.631451493860521}}
{"text": "#include \"distribution.h\"\n#include \"reference.h\"\nusing namespace std;\nusing namespace Rcpp ;\n#include <boost/algorithm/string.hpp>\n\n// [[Rcpp::depends(RcppEigen)]]\nReferenceF::ReferenceF(void) {\n  distribution dist;\n}\n\nEigen::VectorXd ReferenceF::inverse_logistic(const Eigen::VectorXd& eta) const\n{\n  Eigen::VectorXd pi( eta.size() );\n  double norm1 = 1.;\n  for(size_t j=0; j<eta.size(); ++j)\n  {\n    pi[j] = cdf_logit( eta(j) ) / ( 1-\n      std::max(1e-10, std::min(1-1e-6,cdf_logit( eta(j) )))\n    );\n\n\n    norm1 += pi[j];\n  }\n  return (pi/norm1);\n}\n\nEigen::VectorXd ReferenceF::inverse_normal(const Eigen::VectorXd& eta) const\n{\n  Eigen::VectorXd pi( eta.size() );\n  double norm1 = 1.;\n  for(size_t j=0; j<eta.size(); ++j)\n  {\n    pi[j] = cdf_normal( eta(j) ) / ( 1-\n      std::max(1e-10, std::min(1-1e-6,cdf_normal( eta(j) )))\n    );\n    norm1 += pi[j];\n\n  }\n  return (pi/norm1);\n}\n\nEigen::MatrixXd ReferenceF::inverse_derivative_logistic(const Eigen::VectorXd& eta2 ) const\n{\n  Eigen::VectorXd pi1 = ReferenceF::inverse_logistic(eta2);\n  Eigen::MatrixXd D1 = Eigen::MatrixXd::Zero(pi1.rows(),pi1.rows());\n  for(int j=0; j<eta2.rows(); ++j)\n    // { D1(j,j) = pdf_logit( eta2(j) ) /\n    //   (Logistic::cdf_logit(eta2(j)) * (1-Logistic::cdf_logit(eta2(j))));\n    // }\n\n  { D1(j,j) = pdf_logit( eta2(j) ) /\n    ( std::max(1e-10, std::min(1-1e-6,cdf_logit(eta2(j)))) *\n      std::max(1e-10, std::min(1-1e-6, 1-cdf_logit(eta2(j)))) ); }\n\n  return D1 * ( Eigen::MatrixXd(pi1.asDiagonal()) - pi1 * pi1.transpose().eval() );\n}\n\nEigen::MatrixXd ReferenceF::inverse_derivative_normal(const Eigen::VectorXd& eta) const\n{\n  Eigen::VectorXd pi = ReferenceF::inverse_normal(eta);\n  Eigen::MatrixXd D = Eigen::MatrixXd::Zero(pi.rows(),pi.rows());\n  for(size_t j=0; j<pi.rows(); ++j)\n  { D(j,j) = pdf_normal( eta(j) ) /\n    ( std::max(1e-10, std::min(1-1e-6,cdf_normal(eta(j)))) *\n      std::max(1e-10, std::min(1-1e-6, 1-cdf_normal(eta(j)))) ); }\n  return D * ( Eigen::MatrixXd(pi.asDiagonal()) - pi * pi.transpose().eval() );\n}\n\nEigen::VectorXd ReferenceF::inverse_cauchit(const Eigen::VectorXd& eta) const\n{\n  Eigen::VectorXd pi( eta.size() );\n  double norm1 = 1.;\n  for(size_t j=0; j<eta.size(); ++j)\n  {\n    pi[j] = Cauchit::cdf_cauchit( eta(j) ) / ( 1-Cauchit::cdf_cauchit( eta(j) ) );\n    norm1 += pi[j];\n  }\n  return (pi/norm1);\n}\n\nEigen::MatrixXd ReferenceF::inverse_derivative_cauchit(const Eigen::VectorXd& eta2) const\n{\n  Eigen::VectorXd pi1 = ReferenceF::inverse_cauchit(eta2);\n  Eigen::MatrixXd D1 = Eigen::MatrixXd::Zero(pi1.rows(),pi1.rows());\n  for(int j=0; j<eta2.rows(); ++j)\n  { D1(j,j) = pdf_cauchit( eta2(j) ) /\n    (Cauchit::cdf_cauchit(eta2(j)) * (1-Cauchit::cdf_cauchit(eta2(j))));\n  }\n  return D1 * ( Eigen::MatrixXd(pi1.asDiagonal()) - pi1 * pi1.transpose().eval() );\n}\n\nEigen::VectorXd ReferenceF::inverse_student(const Eigen::VectorXd& eta, const double& freedom_degrees) const\n{\n  Eigen::VectorXd pi( eta.size() );\n  double norm1 = 1.;\n  for(size_t j=0; j<eta.size(); ++j)\n  {\n    double num = Student::cdf_student(eta(j),freedom_degrees);\n    double den = std::max(1e-10, std::min(1-1e-6, 1 - Student::cdf_student(eta(j),freedom_degrees)));\n    pi[j] = (num / den);\n    norm1 += pi[j];\n  }\n  return (pi/norm1);\n}\n\n\nEigen::MatrixXd ReferenceF::inverse_derivative_student(const Eigen::VectorXd& eta2, const double& freedom_degrees) const\n{\n  Eigen::VectorXd pi1 = ReferenceF::inverse_student(eta2, freedom_degrees);\n  Eigen::MatrixXd D1 = Eigen::MatrixXd::Zero(pi1.rows(),pi1.rows());\n  for(int j=0; j<eta2.rows(); ++j)\n  {\n    double num = Student::pdf_student( eta2(j) , freedom_degrees);\n    double den1 = Student::cdf_student(eta2(j), freedom_degrees) ;\n    double den2 = 1-Student::cdf_student(eta2(j),freedom_degrees) ;\n    D1(j,j) = (num / std::max(1e-10, std::min(1-1e-6, (den1 * den2)) ));\n  }\n  Eigen::MatrixXd D3 = pi1 * (pi1.transpose());\n  Eigen::MatrixXd D2 = Eigen::MatrixXd(pi1.asDiagonal());\n  Eigen::MatrixXd FINAL = D1 * ( D2 - D3 );\n  return FINAL;\n}\n\ndistribution dist1;\n\n// [[Rcpp::export(\".GLMref\")]]\nList GLMref(Formula formula,\n            CharacterVector categories_order,\n            CharacterVector proportional_effects,\n            DataFrame data,\n            std::string distribution,\n            double freedom_degrees){\n\n  const int N = data.nrows() ; // Number of observations\n\n  List Full_M = dist1.All_pre_data_or(formula, data,\n                                      categories_order, proportional_effects);\n\n  Eigen::MatrixXd Y_init = Full_M[\"Response_EXT\"];\n  Eigen::MatrixXd X_EXT = Full_M[\"Design_Matrix\"];\n  CharacterVector levs1 = Full_M[\"Levels\"];\n  CharacterVector explanatory_complete = Full_M[\"Complete_effects\"];\n  int N_cats = Full_M[\"N_cats\"];\n\n  int P_c = explanatory_complete.length();\n  int P_p = 0;\n  if(proportional_effects[0] != \"NA\"){P_p = proportional_effects.length();}\n  int P =  P_c +  P_p ; // Number of explanatory variables without intercept\n\n  int Q = Y_init.cols();\n  int K = Q + 1;\n  // // // Beta initialization with zeros\n  Eigen::MatrixXd BETA;\n  BETA = Eigen::MatrixXd::Zero(X_EXT.cols(),1);\n  //\n  int iteration = 0;\n  // double check_tutz = 1.0;\n  double Stop_criteria = 1.0;\n  Eigen::MatrixXd X_M_i ;\n  Eigen::VectorXd Y_M_i ;\n  Eigen::VectorXd eta ;\n  Eigen::VectorXd pi ;\n  Eigen::MatrixXd D ;\n  Eigen::MatrixXd Cov_i ;\n  Eigen::MatrixXd W_in ;\n  Eigen::MatrixXd Score_i_2 ;\n  Eigen::MatrixXd F_i_2 ;\n  Eigen::VectorXd LogLikIter;\n  LogLikIter = Eigen::MatrixXd::Zero(1,1) ;\n  Eigen::MatrixXd var_beta;\n  Eigen::VectorXd Std_Error;\n  double LogLik;\n  Eigen::MatrixXd pi_ma(N, K);\n  Eigen::MatrixXd F_i_final = Eigen::MatrixXd::Zero(BETA.rows(), BETA.rows());\n\n  // for (int iteration=1; iteration < 18; iteration++){\n  // while (check_tutz > 0.0001){\n  double epsilon = 0.0001 ;\n  while (Stop_criteria >( epsilon / N) & iteration < 26){\n\n    Eigen::MatrixXd Score_i = Eigen::MatrixXd::Zero(BETA.rows(),1);\n    Eigen::MatrixXd F_i = Eigen::MatrixXd::Zero(BETA.rows(), BETA.rows());\n    LogLik = 0.;\n\n    // Loop by subject\n    for (int i=0; i < N; i++){\n      // Block of size (p,q), starting at (i,j): matrix.block(i,j,p,q);\n      X_M_i = X_EXT.block(i*Q , 0 , Q , X_EXT.cols());\n      Y_M_i = Y_init.row(i);\n      eta = X_M_i * BETA;\n\n      ReferenceF ref;\n\n      // Vector pi depends on selected distribution\n      if(distribution == \"logistic\"){\n        pi = ref.inverse_logistic(eta);\n        D = ref.inverse_derivative_logistic(eta);\n      }else if(distribution == \"normal\"){\n        pi = ref.inverse_normal(eta);\n        D = ref.inverse_derivative_normal(eta);\n      }else if(distribution == \"cauchit\"){\n        pi = ref.inverse_cauchit(eta);\n        D = ref.inverse_derivative_cauchit(eta);\n      }else if(distribution == \"student\"){\n        pi = ref.inverse_student(eta, freedom_degrees);\n        D = ref.inverse_derivative_student(eta, freedom_degrees);\n      }\n\n      Cov_i = Eigen::MatrixXd(pi.asDiagonal()) - (pi*pi.transpose());\n      // Rcout << Cov_i.determinant() << std::endl;\n      W_in = D * Cov_i.inverse();\n      Score_i_2 = X_M_i.transpose() * W_in * (Y_M_i - pi);\n      Score_i = Score_i + Score_i_2;\n      F_i_2 = X_M_i.transpose() * (W_in) * (D.transpose() * X_M_i);\n      F_i = F_i + F_i_2;\n      LogLik = LogLik + (Y_M_i.transpose().eval()*Eigen::VectorXd(pi.array().log())) + ( (1 - Y_M_i.sum()) * std::log(1 - pi.sum()) );\n\n      pi_ma.row(i) = pi.transpose();\n\n    }\n\n    Eigen::VectorXd Ones1 = Eigen::VectorXd::Ones(pi_ma.rows());\n    pi_ma.col(Q) = Ones1 - pi_ma.rowwise().sum() ;\n\n    // To stop when LogLik is smaller than the previous\n    if(iteration>1){\n      if (LogLikIter[iteration] > LogLik)\n        break;\n      // iteration = 25;\n    }\n\n    // To stop when LogLik is smaller than the previous\n    // if(iteration>1){\n    // if (iteration == 25) {  break; }\n\n    // }\n\n    LogLikIter.conservativeResize(iteration+2, 1);\n    LogLikIter(iteration+1) = LogLik;\n    Stop_criteria = (abs(LogLikIter(iteration+1) - LogLikIter(iteration))) / (epsilon + (abs(LogLikIter(iteration+1)))) ;\n    Eigen::VectorXd beta_old = BETA;\n\n    if (F_i.determinant() < 0.000000000000000000001) {\n      cout << \"F_i.determinant() = 0\" << endl;\n      Rcpp::stop(\"F_i.determinant() = 0 \\n Memory allocation failed!\\n\");\n    }\n\n    BETA = BETA + (F_i.inverse() * Score_i);\n    // check_tutz = ((BETA - beta_old).norm())/(beta_old.norm()+check_tutz);\n    iteration = iteration + 1;\n\n\n\n    // if (iteration == 30) {\n    //   cout << \"Max iter\" << endl;\n    //   Rcpp::stop(\"Max iter\");\n    // }\n\n    F_i_final = F_i;\n    // Rcout << \"BETA\" << std::endl;\n    // Rcout << BETA << std::endl;\n    // Rcout << \"LogLik\" << std::endl;\n    // Rcout << LogLik << std::endl;\n  }\n\n  // var_beta = (((X_EXT.transpose() * F_i_final) * X_EXT).inverse());\n  var_beta = F_i_final.inverse();\n  Std_Error = var_beta.diagonal();\n  Std_Error = Std_Error.array().sqrt() ;\n\n  std::vector<std::string> text=as<std::vector<std::string>>(explanatory_complete);\n  std::vector<std::string> level_text=as<std::vector<std::string>>(levs1);\n  StringVector names(Q*P_c + P_p);\n\n\n  if(P_c > 0){\n    for(int var = 0 ; var < explanatory_complete.size() ; var++){\n      for(int cat = 0 ; cat < Q ; cat++){\n        names[(Q*var) + cat] = dist1.concatenate(text[var], level_text[cat]);\n      }\n    }\n  }\n  if(P_p > 0){\n    for(int var_p = 0 ; var_p < proportional_effects.size() ; var_p++){\n      names[(Q*P_c) + var_p] = proportional_effects[var_p];\n    }\n  }\n\n  // TO NAMED THE RESULT BETAS\n  NumericMatrix coef = wrap(BETA);\n  rownames(coef) = names;\n\n\n\n  // AIC\n  double AIC = (-2*LogLik) + (2 *coef.length());\n\n  // AIC\n  double BIC = (-2*LogLik) + (coef.length() * log(N) );\n\n  int df = (N*Q) - coef.length();\n\n  Eigen::MatrixXd predicted = X_EXT * BETA;\n\n  Eigen::VectorXd Ones2 = Eigen::VectorXd::Ones(Y_init.rows());\n  Eigen::VectorXd vex1 = (Y_init.rowwise().sum()) ;\n  Y_init.conservativeResize( Y_init.rows(), K);\n  Y_init.col(Q) = (vex1 - Ones2).array().abs() ;\n  Eigen::MatrixXd residuals = Y_init - pi_ma;\n  Eigen::VectorXd pi_ma_vec(Eigen::Map<Eigen::VectorXd>(pi_ma.data(), pi_ma.cols()*pi_ma.rows()));\n  Eigen::VectorXd Y_init_vec(Eigen::Map<Eigen::VectorXd>(Y_init.data(), Y_init.cols()*Y_init.rows()));\n  Eigen::VectorXd div_arr = Y_init_vec.array() / pi_ma_vec.array();\n  Eigen::VectorXd dev_r(Y_init.rows());\n  int el_1 = 0;\n  for (int element = 0 ; element < div_arr.size() ;  element++){\n    if (div_arr[element] != 0){\n      dev_r[el_1] = div_arr[element];\n      el_1 = el_1 +1 ;\n    }\n  }\n  Eigen::ArrayXd dev_log = dev_r.array().log();\n  double deviance = dev_log.sum();\n  deviance = -2*deviance;\n\n  return List::create(\n    Named(\"coefficients\") = coef,\n    Named(\"iteration\") = iteration,\n    // Named(\"AIC\") = AIC,\n    // Named(\"BIC\") = BIC,\n    Named(\"freedom_degrees\") = freedom_degrees,\n    Named(\"levs1\") = levs1,\n    Named(\"stderr\") = Std_Error,\n    Rcpp::Named(\"df\") = df,\n    Rcpp::Named(\"predicted\") = predicted,\n    Rcpp::Named(\"fitted\") = pi_ma,\n    Rcpp::Named(\"pi_ma_vec\") = pi_ma_vec,\n    Rcpp::Named(\"Y_init_vec\") = Y_init_vec,\n    Rcpp::Named(\"dev_log\") = dev_log,\n    Rcpp::Named(\"deviance\") = deviance,\n    Rcpp::Named(\"residuals\") = residuals,\n    Named(\"Log-likelihood\") = LogLik,\n    // Named(\"freedom_degrees\") = freedom_degrees,\n    // Named(\"Y_init\") = Y_init,\n    Named(\"LogLikIter\") = LogLikIter,\n    Named(\"formula\") = formula,\n    Named(\"categories_order\") = categories_order,\n    Named(\"proportional_effects\") = proportional_effects,\n    Named(\"N_cats\") = N_cats,\n    Named(\"distribution\") = distribution\n  );\n}\n\n// [[Rcpp::export(\".Predict_Response\")]]\nList Predict_Response(List model_object,\n                      DataFrame NEWDATA){\n  Environment base_env(\"package:base\");\n  Function my_rowSums = base_env[\"rowSums\"];\n\n  int N_cats = model_object[\"N_cats\"];\n  Eigen::MatrixXd coef = model_object[\"coefficients\"];\n\n  List NewDataList = dist1.All_pre_data_NEWDATA(model_object[\"formula\"],\n                                                NEWDATA,\n                                                model_object[\"categories_order\"],\n                                                            model_object[\"proportional_effects\"],\n                                                                        N_cats\n\n  );\n\n  Eigen::MatrixXd Design_Matrix = NewDataList[\"Design_Matrix\"];\n  Eigen::MatrixXd predicted_eta;\n\n  String distribution = model_object[\"distribution\"];\n  double freedom_degrees = model_object[\"freedom_degrees\"];\n\n  ReferenceF ref;\n  Eigen::VectorXd pi;\n  int N = NEWDATA.rows();\n  Eigen::MatrixXd X_M_i;\n\n  Eigen::MatrixXd pi_total = Eigen::MatrixXd::Zero(N,N_cats-1);\n\n\n  for (int i=0; i < N; i++){\n\n    X_M_i = Design_Matrix.block(i*(N_cats-1) , 0 , N_cats-1 , Design_Matrix.cols());\n\n    predicted_eta = X_M_i * coef;\n\n    if(distribution == \"logistic\"){\n      pi = ref.inverse_logistic(predicted_eta);\n    }else if(distribution == \"normal\"){\n      pi = ref.inverse_normal(predicted_eta);\n    }else if(distribution == \"cauchit\"){\n      pi = ref.inverse_cauchit(predicted_eta);\n    }else if(distribution == \"student\"){\n      pi = ref.inverse_student(predicted_eta, freedom_degrees);\n    }\n    pi_total.row(i) = pi;\n\n  }\n\n  NumericVector cum_prob = my_rowSums(pi_total);\n  Eigen::Map<Eigen::VectorXd> cum_prob1 = as<Eigen::Map<Eigen::VectorXd> >(cum_prob);\n  Eigen::VectorXd Ones1 = Eigen::VectorXd::Ones(pi_total.rows());\n\n  pi_total.conservativeResize(pi_total.rows() , N_cats);\n  pi_total.col(N_cats-1) = Ones1 - cum_prob1;\n\n  return List::create(\n    Named(\"Design_Matrix\") = Design_Matrix,\n    Named(\"Eta\") = predicted_eta,\n    // Named(\"cum_prob\") = cum_prob,\n    Named(\"pi_total\") = pi_total\n  );\n\n}\n\n\n// [[Rcpp::export(\".Discrete_CM\")]]\nList Discrete_CM(Formula formula,\n                 String case_id,\n                 String alternatives,\n                 SEXP reference,\n                 CharacterVector alternative_specific,\n                 DataFrame data,\n                 std::string distribution,\n                 double freedom_degrees\n){\n\n  List Full_M = dist1.select_data_nested(formula,\n                                         case_id,\n                                         alternatives,\n                                         reference,\n                                         alternative_specific,\n                                         data\n  );\n\n  Eigen::MatrixXd Y_init = Full_M[\"Response_M\"];\n  Eigen::MatrixXd X_EXT = Full_M[\"Design_Matrix\"];\n\n  int Q = Y_init.cols();\n  int K = Q + 1;\n  int N = K * Y_init.rows();\n\n  Eigen::MatrixXd BETA;\n  BETA = Eigen::MatrixXd::Zero(X_EXT.cols(),1); // Beta initialization with zeros\n  int iteration = 0;\n  double Stop_criteria = 1.0;\n  Eigen::MatrixXd X_M_i ;\n  Eigen::VectorXd Y_M_i ;\n  Eigen::VectorXd eta ;\n  Eigen::VectorXd pi ;\n  Eigen::MatrixXd D ;\n  Eigen::MatrixXd Cov_i ;\n  Eigen::MatrixXd W_in ;\n  Eigen::MatrixXd Score_i_2 ;\n  Eigen::MatrixXd F_i_2 ;\n  Eigen::VectorXd LogLikIter;\n  LogLikIter = Eigen::MatrixXd::Zero(1,1) ;\n  double LogLik;\n\n  Eigen::MatrixXd F_i_final = Eigen::MatrixXd::Zero(BETA.rows(), BETA.rows());\n  Eigen::MatrixXd var_beta;\n  Eigen::VectorXd Std_Error;\n\n  double epsilon = 0.0001 ;\n  // for (int iteration=1; iteration < 18; iteration++){\n  while (Stop_criteria >( epsilon / N)){\n    Eigen::MatrixXd Score_i = Eigen::MatrixXd::Zero(BETA.rows(),1);\n    Eigen::MatrixXd F_i = Eigen::MatrixXd::Zero(BETA.rows(), BETA.rows());\n    LogLik = 0.;\n    ReferenceF ref;\n\n    for (int i=0; i < N/K; i++){\n      X_M_i = X_EXT.block(i*Q , 0 , Q , X_EXT.cols());\n      Y_M_i = Y_init.row(i);\n      eta = X_M_i * BETA;\n\n      if(distribution == \"logistic\"){\n        pi = ref.inverse_logistic(eta);\n        D = ref.inverse_derivative_logistic(eta);\n      }else if(distribution == \"normal\"){\n        pi = ref.inverse_normal(eta);\n        D = ref.inverse_derivative_normal(eta);\n      }else if(distribution == \"cauchit\"){\n        pi = ref.inverse_cauchit(eta);\n        D = ref.inverse_derivative_cauchit(eta);\n      }else if(distribution == \"student\"){\n        pi = ref.inverse_student(eta, freedom_degrees);\n        D = ref.inverse_derivative_student(eta, freedom_degrees);\n      }\n      Cov_i = Eigen::MatrixXd(pi.asDiagonal()) - (pi*pi.transpose());\n      W_in = D * Cov_i.inverse();\n      Score_i_2 = X_M_i.transpose() * W_in * (Y_M_i - pi);\n      Score_i = Score_i + Score_i_2;\n      F_i_2 = X_M_i.transpose() * (W_in) * (D.transpose() * X_M_i);\n      F_i = F_i + F_i_2;\n      LogLik = LogLik + (Y_M_i.transpose().eval()*Eigen::VectorXd(pi.array().log())) + ( (1 - Y_M_i.sum()) * std::log(1 - pi.sum()) );\n    }\n\n\n\n    // To stop when LogLik is smaller than the previous\n    if(iteration>1){\n      if (LogLikIter[iteration] > LogLik)\n        break;\n    }\n\n    LogLikIter.conservativeResize( LogLikIter.rows() +1 , 1);\n    LogLikIter(LogLikIter.rows() - 1) = LogLik;\n    Stop_criteria = (abs(LogLikIter(iteration+1) - LogLikIter(iteration))) / (epsilon + (abs(LogLikIter(iteration+1)))) ;\n    Eigen::VectorXd beta_old = BETA;\n    BETA = BETA + (F_i.inverse() * Score_i);\n\n    iteration = iteration + 1;\n    // Rcout << \"BETA\" << std::endl;\n    // Rcout << BETA << std::endl;\n\n    // Rcout << \"iteration\" << std::endl;\n    // Rcout << iteration << std::endl;\n    // Rcout << \"LogLik\" << std::endl;\n    // Rcout << LogLik << std::endl;\n    F_i_final = F_i;\n\n    // Rcout << \"LogLikIter\" << std::endl;\n    // Rcout << LogLikIter << std::endl;\n\n  }\n\n  var_beta = F_i_final.inverse();\n  Std_Error = var_beta.diagonal();\n  Std_Error = Std_Error.array().sqrt() ;\n\n  // Eigen::MatrixXd X_M_i_1 = X_EXT.block(0*Q , 0 , Q , X_EXT.cols());\n  // Eigen::VectorXd Y_M_i_1 = Y_init.row(0);\n\n  NumericMatrix BETA_2 = wrap(BETA);\n\n  return List::create(\n    Named(\"Nb. iterations\") = iteration-1 ,\n    Named(\"coefficients\") = BETA_2,\n    Named(\"Log-likelihood\") = LogLikIter(LogLikIter.rows() - 1),\n    Named(\"LogLikIter\") =  LogLikIter,\n    Named(\"stderr\") =  Std_Error\n  );\n\n\n}\n\nRCPP_MODULE(referencemodule){\n  Rcpp::function(\"GLMref\", &GLMref,\n                 List::create(_[\"formula\"] = R_NaN,\n                              _[\"categories_order\"] = CharacterVector::create( \"A\", NA_STRING),\n                              _[\"proportional_effects\"] = CharacterVector::create(NA_STRING),\n                              _[\"data\"] = NumericVector::create( 1, NA_REAL, R_NaN, R_PosInf, R_NegInf),\n                              _[\"distribution\"] = \"a\",\n                              _[\"freedom_degrees\"] = 1.0),\n                              \"Reference model\");\n\n  Rcpp::function(\"Discrete_CM\", &Discrete_CM,\n                 List::create(_[\"formula\"] = R_NaN,\n                              _[\"case_id\"] = \"a\",\n                              _[\"alternatives\"] = \"a\",\n                              _[\"reference\"] = R_NaN,\n                              _[\"alternative_specific\"] = CharacterVector::create( NA_STRING),\n                              _[\"data\"] = NumericVector::create( 1, NA_REAL, R_NaN, R_PosInf, R_NegInf),\n                              _[\"distribution\"] = \"a\",\n                              _[\"freedom_degrees\"] = 1.0),\n                              \"Discrete Choice Model\");\n\n  Rcpp::function(\"Predict_Response\", &Predict_Response,\n                 List::create(_[\"model_object\"] = R_NaN,\n                              _[\"data\"] = NumericVector::create( 1, NA_REAL, R_NaN, R_PosInf, R_NegInf)\n                 ),\n                 \"Predict_Response Choice Model\");\n\n  Rcpp::class_<ReferenceF>(\"ReferenceF\")\n    .constructor()\n    .method( \"inverse_logistic\", &ReferenceF::inverse_logistic )\n  ;\n}\n", "meta": {"hexsha": "ae188a9483010d531082c431ae5f0b9d1492939f", "size": 19533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/reference.cpp", "max_stars_repo_name": "ylleonv/pack", "max_stars_repo_head_hexsha": "cb3416a8e230cfbee5a95273c9c6a15184d2458b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/reference.cpp", "max_issues_repo_name": "ylleonv/pack", "max_issues_repo_head_hexsha": "cb3416a8e230cfbee5a95273c9c6a15184d2458b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reference.cpp", "max_forks_repo_name": "ylleonv/pack", "max_forks_repo_head_hexsha": "cb3416a8e230cfbee5a95273c9c6a15184d2458b", "max_forks_repo_licenses": ["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.4469178082, "max_line_length": 134, "alphanum_fraction": 0.5997030666, "num_tokens": 5570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6314514859057007}}
{"text": "// Author: Daisuke Kanaizumi\n// Affiliation: Department of Applied Mathematics, Waseda University\n\n// verification program for q-Bessel functions\n// April 12th, 2018\n\n#ifndef QBESSEL_HPP\n#define QBESSEL_HPP\n\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/constants.hpp>\n#include <kv/complex.hpp>\n#include <kv/convert.hpp>\n#include <kv/defint.hpp>\n#include <kv/Heine.hpp>\n#include <kv/Pochhammer.hpp>\n#include <kv/QHypergeometric.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <limits>\nnamespace ub = boost::numeric::ublas;\nnamespace kv{\ntemplate <class T> interval<T>Jackson1(const interval<T>& z,const interval<T>& nu,const interval<T>& q){\n// verification program for Jackson`s 1st q-Bessel function\ninterval<T>res,a,b,c,series;\nint j,K;\nT rad;\nif(abs(z)>=2){\nthrow std::domain_error(\"Jackson`s 1st q-Bessel function is not defined\");\n}\nif(abs(q)>=1){\nthrow std::domain_error(\"absolute value of q must be under 1\");\n}\n if(z<0){\n   throw std::domain_error(\"z must be positive\");\n }\n if (pow(q,nu)<1){\nj=1;\nK=500;\na=1.;\nb=1.;\nc=1.;\n// Leibniz criterion\n for (int k=1; k<=K; k++){\n    j = -1*j;\n    b=b*(1-pow(q,k));\n    c=c*(1-pow(q,k+nu));\n    a = a+j*pow(z/2,2*k)/(b*c);\n  }\nb=b*(1-pow(q,K+1));\nc=c*(1-pow(q,K+nu+1));\n\nrad=abs(pow(z/2,2*K+2)/(b*c)).upper();\nseries=a+rad*interval<T>(-1.,1.);\nres=pow(z/2,nu)*series/Karpelevich(interval<T>(pow(q,nu+1)),interval<T>(q));\n}\n else{\nres=pow(z/2,nu)*infinite_qPochhammer(interval<T>(pow(q,nu+1)),interval<T>(q))*\n  Heine(interval<T>(0),interval<T>(0),interval<T>(pow(q,nu+1)),interval<T>(q),interval<T>(-z*z/4))/Euler(interval<T>(q));\n}\n\n return res;\n}\ntemplate <class T> complex<interval<T> >Jackson1(const complex<interval<T> >& z,const complex<interval<T> >& nu,const interval<T>& q){\n  complex<interval<T> >res,i;\n\n\nif(abs(q)>=1){\nthrow std::domain_error(\"absolute value of q must be under 1\");\n}\n if(abs(z).upper()>=2){\nthrow std::domain_error(\"Jackson`s 1st q-Bessel function is not defined\");\n}\n\nres=pow(z/2,nu)*infinite_qPochhammer(complex<interval<T> >(pow(q,nu+1)),interval<T>(q))*\n  Heine(complex<interval<T> >(0),complex<interval<T> >(0),complex<interval<T> >(pow(q,nu+1)),interval<T>(q),complex<interval<T> >(-z*z/4))/Euler(interval<T>(q));\n \n return res;       \n}\n\ntemplate <class T> complex<interval<T> >modified_qBesselI1(const complex<interval<T> >& z,const complex<interval<T> >& nu,const interval<T>& q){\n  // verification program for 1st modified q-Bessel I1\n  complex<interval<T> >res,i;\n  if(abs(q)>=1){\n    throw std::domain_error(\"absolute value of q must be under 1\");\n  }\n  if(abs(z).upper()>=2){\n    throw std::domain_error(\"1st modified q-Bessel function is not defined\");\n  }\n  interval<T>pi;\n  i=complex<interval<T> >::i();\n  pi=constants<interval<T> >::pi();\n  res=exp(-i*nu*pi/2)*Jackson1(complex<interval<T> >(i*z),complex<interval<T> >(nu),interval<T> (q));\n  return res;       \n}\n  \n  template <class T> complex<interval<T> >modified_qBesselK1(const complex<interval<T> >& z,const complex<interval<T> >& nu,const interval<T>& q){\n    // verification program for 1st modified q-Bessel K1, nu should not be an integer\n    complex<interval<T> >res;\n    if(abs(q)>=1){\n      throw std::domain_error(\"absolute value of q must be under 1\");\n    }\n    if(abs(z).upper()>=2){\n      throw std::domain_error(\"1st modified q-Bessel function is not defined\");\n    }\n    interval<T>pi;\n    pi=constants<interval<T> >::pi();\n    res=pi*0.5/sin(pi*nu)*\n      (modified_qBesselI1(complex<interval<T> > (z), complex<interval<T> > (-nu), interval<T> (q))-modified_qBesselI1(complex<interval<T> > (z), complex<interval<T> > (nu), interval<T> (q)));\n    return res;  \n  }\n  template <class T> interval<T>Jackson2(const interval<T>& z,const interval<T>& nu,const interval<T>& q){\n    // verification program for Jackson`s 2nd q-Bessel function\n  interval<T>res,a,b,c,series,pq;\nint j,K;\nT rad;\nif(abs(q)>=1){\nthrow std::domain_error(\"absolute value of q must be under 1\");\n}\n\n// if (pow(q,nu)<1 && z*z<4*q){\n/*j=1;\nK=500;\na=1.;\nb=1.;\nc=1.;\n// Leibniz criterion\n for (int k=1; k<=K; k++){\n    j = -1*j;\n    b=b*(1-pow(q,k));\n    c=c*(1-pow(q,k+nu));\n    a = a+j*pow(q,k*(k-1))*pow(pow(q,nu+1)*z*z/4,k)/(b*c);\n  }\n  b=b*(1-pow(q,K+1));\n  c=c*(1-pow(q,K+nu+1));\n \n rad=abs(pow(q,K*(K+1))*pow(pow(q,nu+1)*z*z/4,K+1)/(b*c)).upper();\n series=a+rad*interval<T>(-1.,1.);\n res=pow(z/2,nu)*series/Karpelevich(interval<T>(pow(q,nu+1)),interval<T>(q));\n*/ //}\n// else{\n   /* implementation by original definition*/\n// res=pow(z*0.5,nu)*infinite_qPochhammer(interval<T>(pow(q,nu+1)),interval<T>(q))*\n//  _0phi_1(interval<T>(pow(q,nu+1)),interval<T>(q),interval<T>(-z*z*pow(q,nu+1)/4))/Euler(interval<T>(q));\n   \n // alternative implementaion\n // reference\n // H. T Koelink, Hansen-Lommel orthogonality Relations for Jackson`s q-Bessel functions, formula 3.2\n // Journal of Mathematical Analysis and Applications 175, 425-437 (1993)\n pq=pow(q,nu+1);\n res=pow(z/2,nu)*_1phi_1(interval<T> (-z*z/4),interval<T> (0),interval<T>(q), interval<T> (pq))/Euler(interval<T>(q));\n // }\n\n  return res;\n}\ntemplate <class T> complex<interval<T> >Jackson2(const complex<interval<T> >& z,const complex<interval<T> >& nu,const interval<T>& q){\n  complex<interval<T> >res,pq,i;\n  i=complex<interval<T> >::i();\n  if(abs(q)>=1){\n    throw std::domain_error(\"absolute value of q must be under 1\");\n  }\n  pq=pow(q,nu+1);\n  /* implementation by original definition*/\n     \n  //  res=pow(z/2,nu)*infinite_qPochhammer(complex<interval<T> >(pq),interval<T>(q))*\n  //  _0phi_1(complex<interval<T> >(pq),interval<T>(q),complex<interval<T> >(-z*z*pq/4))/Euler(interval<T>(q));\n  \n  // alternative implementaion\n  // reference\n  // H. T Koelink, Hansen-Lommel Orthogonality Relations for Jackson`s q-Bessel functions, formula 3.2\n  // Journal of Mathematical Analysis and Applications 175, 425-437 (1993)\n   try{\n  res=pow(z/2,nu)*_1phi_1(complex<interval<T> >(-z*z/4),complex<interval<T> >(0),interval<T>(q), complex<interval<T> >(pq))/Euler(interval<T>(q));\n  }\n  // alternative implementaion\n  // reference\n  // Y. Chen , M. E. Ismail, K. A. Muttalib. Asymptotics of basic Bessel functions and q-Laguerre polynomials, Lemma 2\n  // Journal of Computational and Applied Mathematics, 54(3), 263-272 (1994).\n  catch(std::domain_error){\n    ub::vector< complex<interval<T> > > a(3);\n    ub::vector< complex<interval<T> > > b(2);\n    ub::vector< complex<interval<T> > > c(2);\n    a(0)=pow(q,(nu+0.5)*0.5);\n    a(1)=-pow(q,(nu+0.5)*0.5);\n    a(2)=0.;\n    b(0)=-sqrt(q);\n    b(1)=i*a(0)*z*0.5;\n    c(0)=-sqrt(q);\n    c(1)=-b(1);\n\n    res=pow(z*0.5,nu)*infinite_qPochhammer(interval<T>(sqrt(q)),interval<T>(q))/Euler(interval<T>(q))*0.5\n      *(infinite_qPochhammer(complex<interval<T> >(b(1)),interval<T>(sqrt(q)))\n\t*QHypergeom(ub::vector<complex<interval<T> > >(a),ub::vector<complex<interval<T> > >(b),interval<T>(sqrt(q)),complex<interval<T> >(sqrt(q),0))+\n\tinfinite_qPochhammer(complex<interval<T> >(c(1)),interval<T>(sqrt(q)))\n\t*QHypergeom(ub::vector<complex<interval<T> > >(a),ub::vector<complex<interval<T> > >(c),interval<T>(sqrt(q)),complex<interval<T> >(sqrt(q),0)));\n    \t} \n  \n    if((abs(res)).upper()==std::numeric_limits<T>::infinity()){  \n    ub::vector< complex<interval<T> > > a(3);\n    ub::vector< complex<interval<T> > > b(2);\n    ub::vector< complex<interval<T> > > c(2);\n    a(0)=pow(q,(nu+0.5)*0.5);\n    a(1)=-pow(q,(nu+0.5)*0.5);\n    a(2)=0.;\n    b(0)=-sqrt(q);\n    b(1)=i*a(0)*z*0.5;\n    c(0)=-sqrt(q);\n    c(1)=-b(1);\n\n    res=pow(z*0.5,nu)*infinite_qPochhammer(interval<T>(sqrt(q)),interval<T>(q))/Euler(interval<T>(q))*0.5\n      *(infinite_qPochhammer(complex<interval<T> >(b(1)),interval<T>(sqrt(q)))\n\t*QHypergeom(ub::vector<complex<interval<T> > >(a),ub::vector<complex<interval<T> > >(b),interval<T>(sqrt(q)),complex<interval<T> >(sqrt(q),0))+\n\tinfinite_qPochhammer(complex<interval<T> >(c(1)),interval<T>(sqrt(q)))\n\t*QHypergeom(ub::vector<complex<interval<T> > >(a),ub::vector<complex<interval<T> > >(c),interval<T>(sqrt(q)),complex<interval<T> >(sqrt(q),0)));\n     }\n    //std::cout<<qPochhammer(complex<interval<T> >(pow(q,(nu+0.5)*0.5)),interval<T>(q),int(1000))\n    //*qPochhammer(complex<interval<T> >(-pow(q,(nu+0.5)*0.5)),interval<T>(q),int(1000))<<std::endl;\n\n    return res;       \n}\n  template <class TT> struct qBesselintegral_nu_int_real {\n    TT x, q;\n    int nu,n; // Setting parameters\n    qBesselintegral_nu_int_real(TT x, TT q, int nu,int n) : x(x),q(q),nu(nu),n(n) {}\n    \n    template <class T> T operator() (const T& t) {\n      complex<T>  pro;\n      T proreal;\n      complex<T> i;\n      pro=1.;\n      i=complex<T>::i();\n      for(int k=0;k<=nu-1;k++){\n\tpro=pro*(1-pow(T(q),k)*exp(2*i*t))*(1-pow(T(q),k)*exp(-2*i*t));\n      }\n      for(int j=0;j<=n-1;j++){\n\tpro=pro*(1+i*T(x)*pow(T(q),T(nu)/2+0.5+j)*exp(i*t)/2)*(1+i*T(x)*pow(T(q),T(nu)/2+0.5+j)*exp(-i*t)/2);\n      }\n      \n      proreal=pro.real();\n      return proreal;\t  \n    }\n  };\n  template <class TT> struct qBesselintegral_nu_int_imag {\n    TT x, q;\n    int nu,n; // Setting parameters\n    qBesselintegral_nu_int_imag(TT x, TT q, int nu,int n) : x(x),q(q),nu(nu),n(n) {}\n    \n    template <class T> T operator() (const T& t) {\n      complex<T>  pro;\n      T proimag;\n      complex<T> i;\n      pro=1.;\n      i=complex<T>::i();\n      for(int k=0;k<=nu-1;k++){\n\tpro=pro*(1-pow(T(q),k)*exp(2*i*t))*(1-pow(T(q),k)*exp(-2*i*t));\n      }\n      for(int j=0;j<=n-1;j++){\n\tpro=pro*(1+i*T(x)*pow(T(q),T(nu)/2+0.5+j)*exp(i*t)/2)*(1+i*T(x)*pow(T(q),T(nu)/2+0.5+j)*exp(-i*t)/2);\n      }\n      \n      proimag=pro.imag();\n      return proimag;\t  \n    }\n  };\n  template <class T> complex<interval<T> >Jackson2_integral(const interval<T>& z,const int & nu,const interval<T>& q){\n      // verification program for Jackson`s 2nd q-Bessel function\n      // Integral representation is used\n    \n      // References\n      // Rahman(1987), An Integral Representation and Some Transformation Properties of q-Bessel Functions, Journal of Mathematical Analysis and Applications 125\n      // Zhang(2008), Plancherel-Rotach asymptotics for certain basic hypergeometric series, Advances in Mathematics 217, Lemma 1.1\n    int n;    \n    n=100;\n    if(nu<=0){\n      throw std::domain_error(\"nu must be positive\");\n    }\n    if(abs(z)*pow(q,nu/2+n+0.5)/2/(1-q)>=0.5){\n      n=n+10;\n    }\n    complex<interval<T> >res,integral;\n    interval<T>num,realint,imagint,pi;\n    T numrad;\n    numrad=(abs(z)*pow(q,nu/2+n+0.5)*2/(1-q)).upper();\n    num=pow((1+numrad*interval<T>(-1.,1.)),2);\n    pi=constants<interval<T> >::pi();\n    realint=defint(qBesselintegral_nu_int_real<interval<T> >(z,q,nu,n),interval<T>(0.),interval<T>(pi),10,10);\n    imagint=defint(qBesselintegral_nu_int_imag<interval<T> >(z,q,nu,n),interval<T>(0.),interval<T>(pi),10,10);\n    integral=complex<interval<T> >(realint,imagint);\n    \n    res=num*integral*pow(z/2,nu)*infinite_qPochhammer(interval<T>(pow(q,2*nu)),interval<T>(q))/infinite_qPochhammer(interval<T>(pow(q,nu)),interval<T>(q))/(2*pi);\n    \n    \n    return res;\n  }\n    template <class TT> struct qBesselintegral_nu_double_real {\n      TT x,q,nu;\n      int n; // Setting parameters\n      qBesselintegral_nu_double_real(TT x, TT q, TT nu,int n) : x(x),q(q),nu(nu),n(n) {}\n      \n      template <class T> T operator() (const T& t) {\n      complex<T>  pro;\n      T proreal;\n      complex<T> i;\n      pro=1.;\n      i=complex<T>::i();\n      for(int k=0;k<=n-1;k++){\n\tpro=pro*(1-pow(T(q),k)*exp(2*i*t))*(1-pow(T(q),k)*exp(-2*i*t));\n      }\n      for(int j=0;j<=n-1;j++){\n\tpro=pro*(1+i*T(x)*pow(T(q),T(nu)/2+0.5+j)*exp(i*t)/2)*(1+i*T(x)*pow(T(q),T(nu)/2+0.5+j)*exp(-i*t)/2);\n      }\n      for(int l=0;l<=n-1;l++){\n\tpro=pro/(1-pow(T(q),l+nu)*exp(2*i*t))/(1-pow(T(q),l+nu)*exp(-2*i*t));\n      }      \n      proreal=pro.real();\n      return proreal;\t  \n      }\n  };\n  template <class TT> struct qBesselintegral_nu_double_imag {\n    TT x,q,nu;\n    int n; // Setting parameters\n    qBesselintegral_nu_double_imag(TT x, TT q, TT nu,int n) : x(x),q(q),nu(nu),n(n) {}\n    \n    template <class T> T operator() (const T& t) {\n      complex<T>  pro;\n      T proimag;\n      complex<T> i;\n      pro=1.;\n      i=complex<T>::i();\n      for(int k=0;k<=n-1;k++){\n\tpro=pro*(1-pow(T(q),k)*exp(2*i*t))*(1-pow(T(q),k)*exp(-2*i*t));\n      }\n      for(int j=0;j<=n-1;j++){\n\tpro=pro*(1+i*T(x)*pow(T(q),T(nu)/2+0.5+j)*exp(i*t)/2)*(1+i*T(x)*pow(T(q),T(nu)/2+0.5+j)*exp(-i*t)/2);\n      }\n      for(int l=0;l<=n-1;l++){\n\tpro=pro/(1-pow(T(q),l+nu)*exp(2*i*t))/(1-pow(T(q),l+nu)*exp(-2*i*t));\n      }      \n      \n      proimag=pro.imag();\n      return proimag;\t  \n    }\n  };\n  template <class T> complex<interval<T> >Jackson2_integral(const interval<T>& z,const interval<T> & nu,const interval<T>& q){\n      // verification program for Jackson`s 2nd q-Bessel function\n      // Integral representation is used\n    \n      // References\n      // Rahman(1987), An Integral Representation and Some Transformation Properties of q-Bessel Functions, Journal of Mathematical Analysis and Applications 125\n      // Zhang(2008), Plancherel-Rotach asymptotics for certain basic hypergeometric series, Advances in Mathematics 217, Lemma 1.1\n    int n;    \n    n=100;\n    if(nu<=0){\n      throw std::domain_error(\"nu must be positive\");\n    }\n    if(abs(z)*pow(q,nu/2+n+0.5)/2/(1-q)>=0.5){\n      n=n+10;\n    }\n    if(pow(q,nu+n)/2/(1-q)>=0.5){\n      n=n+10;\n    }\n\n    complex<interval<T> >res,integral;\n    interval<T>num1,num2,denom,realint,imagint,pi;\n    T numrad1,numrad2,denomrad;\n    numrad1=(abs(z)*pow(q,nu/2+n+0.5)*2/(1-q)).upper();\n    num1=pow((1+numrad1*interval<T>(-1.,1.)),2);\n    numrad2=(pow(q,n)*2/(1-q)).upper();\n    num2=pow((1+numrad2*interval<T>(-1.,1.)),2);\n    denomrad=(pow(q,nu+n)*2/(1-q)).upper();\n    denom=pow((1+denomrad*interval<T>(-1.,1.)),2);\n    pi=constants<interval<T> >::pi();\n    realint=defint(qBesselintegral_nu_double_real<interval<T> >(z,q,nu,n),interval<T>(0.),interval<T>(pi),10,10);\n    imagint=defint(qBesselintegral_nu_double_imag<interval<T> >(z,q,nu,n),interval<T>(0.),interval<T>(pi),10,10);\n    integral=complex<interval<T> >(realint,imagint);\n    \n    res=num1*num2*denom*integral*pow(z/2,nu)*infinite_qPochhammer(interval<T>(pow(q,2*nu)),interval<T>(q))/infinite_qPochhammer(interval<T>(pow(q,nu)),interval<T>(q))/(2*pi);\n    \n    \n    return res;\n  }\n    template <class TT> struct qBesselintegral_z_complex_real {\n      TT q,nu;\n      complex<TT> x;\n      int n; // Setting parameters\n      qBesselintegral_z_complex_real(complex<TT> x, TT q, TT nu,int n) : x(x),q(q),nu(nu),n(n) {}\n      \n      template <class T> T operator() (const T& t) {\n      complex<T>  pro;\n      T proreal;\n      complex<T> i;\n      pro=1.;\n      i=complex<T>::i();\n      for(int k=0;k<=n-1;k++){\n\tpro=pro*(1-pow(T(q),k)*exp(2*i*t))*(1-pow(T(q),k)*exp(-2*i*t));\n      }\n      for(int j=0;j<=n-1;j++){\n\tpro=pro*(1+i*complex<T>(x)*pow(T(q),T(nu)/2+0.5+j)*exp(i*t)/2)*(1+i*complex<T>(x)*pow(T(q),T(nu)/2+0.5+j)*exp(-i*t)/2);\n      }\n      for(int l=0;l<=n-1;l++){\n\tpro=pro/(1-pow(T(q),l+T(nu))*exp(2*i*t))/(1-pow(T(q),l+T(nu))*exp(-2*i*t));\n      }      \n      proreal=pro.real();\n      return proreal;\t  \n      }\n  };\n  template <class TT> struct qBesselintegral_z_complex_imag {\n    TT q,nu;\n    complex<TT> x;\n    int n; // Setting parameters\n    qBesselintegral_z_complex_imag(complex<TT> x, TT q, TT nu,int n) : x(x),q(q),nu(nu),n(n) {}\n    \n    template <class T> T operator() (const T& t) {\n      complex<T>  pro;\n      T proimag;\n      complex<T> i;\n      pro=1.;\n      i=complex<T>::i();\n      for(int k=0;k<=n-1;k++){\n\tpro=pro*(1-pow(T(q),k)*exp(2*i*t))*(1-pow(T(q),k)*exp(-2*i*t));\n      }\n      for(int j=0;j<=n-1;j++){\n\tpro=pro*(1+i*complex<T>(x)*pow(T(q),T(nu)/2+0.5+j)*exp(i*t)/2)*(1+i*complex<T>(x)*pow(T(q),T(nu)/2+0.5+j)*exp(-i*t)/2);\n      }\n      for(int l=0;l<=n-1;l++){\n\tpro=pro/(1-pow(T(q),l+T(nu))*exp(2*i*t))/(1-pow(T(q),l+T(nu))*exp(-2*i*t));\n      }      \n      \n      proimag=pro.imag();\n      return proimag;\t  \n    }\n  };\n  template <class T> complex<interval<T> >Jackson2_integral(const complex<interval<T> >& z,const interval<T> & nu,const interval<T>& q){\n      // verification program for Jackson`s 2nd q-Bessel function\n      // Integral representation is used\n    \n      // References\n      // Rahman(1987), An Integral Representation and Some Transformation Properties of q-Bessel Functions, Journal of Mathematical Analysis and Applications 125\n      // Zhang(2008), Plancherel-Rotach asymptotics for certain basic hypergeometric series, Advances in Mathematics 217, Lemma 1.1\n    int n;    \n    n=100;\n    if(nu<=0){\n      throw std::domain_error(\"nu must be positive\");\n    }\n    if(abs(z*pow(q,nu/2+n+0.5))/2/(1-q)>=0.5){\n      n=n+10;\n    }\n    if(abs(pow(q,nu+n))/2/(1-q)>=0.5){\n      n=n+10;\n    }\n\n    complex<interval<T> >res,integral,num1,denom;\n\n    interval<T> num2;\n    interval<T> pi,realint,imagint;\n    T numrad1,numrad2,denomrad;\n    numrad1=(abs(z*pow(q,nu/2+n+0.5))*2/(1-q)).upper();\n    num1=pow(complex_nbd(complex<interval<T> >(1,0),numrad1),2);\n    numrad2=(pow(q,n)*2/(1-q)).upper();\n    num2=pow((1+numrad2*interval<T>(-1.,1.)),2);\n    denomrad=(abs(pow(q,nu+n))*2/(1-q)).upper();\n    denom=pow(complex_nbd(complex<interval<T> >(1,0),denomrad),2);\n    pi=constants<interval<T> >::pi();\n    realint=defint(qBesselintegral_z_complex_real<interval<T> >(z,q,nu,n),interval<T>(0.),interval<T>(pi),10,10);\n    imagint=defint(qBesselintegral_z_complex_imag<interval<T> >(z,q,nu,n),interval<T>(0.),interval<T>(pi),10,10);\n    integral=complex<interval<T> >(realint,imagint);\n    \n    res=num1*num2*denom*integral*pow(z/2,nu)*infinite_qPochhammer(complex<interval<T> >(pow(q,2*nu)),interval<T>(q))/infinite_qPochhammer(complex<interval<T> >(pow(q,nu)),interval<T>(q))/(2*pi);\n    \n    return res;\n  }\n  template <class T> interval<T> J2ratio(const interval<T> & z,const interval<T> & nu,const interval<T>& q){\n    interval<T>res;\n    res=Jackson2(interval<T>(z),interval<T>(nu),interval<T>(q))/Jackson2(interval<T>(z),interval<T>(nu-1),interval<T>(q));\n    return res;\n  }\n  template <class T> complex<interval<T> >modified_qBesselI2(const complex<interval<T> >& z,const complex<interval<T> >& nu,const interval<T>& q){\n    //verification program for 2nd modified q-Bessel function I2\n    complex<interval<T> >res,i;\n    if(abs(q)>=1){\n      throw std::domain_error(\"absolute value of q must be under 1\");\n    }\n    /*implementation by original definition\n      interval<T>pi;\n      i=complex<interval<T> >::i();\n      pi=constants<interval<T> >::pi();\n      res=exp(-i*nu*pi/2)*Jackson2(complex<interval<T> >(i*z),complex<interval<T> >(nu),interval<T> (q));\n    */\n    // alternative implementation\n    // reference\n    // Ismail, M. E., & Zhang, R. (2015). $ q $-Bessel Functions and Rogers-Ramanujan Type Identities.\n    // arXiv preprint arXiv:1508.06861.\n    res=pow(z/2,nu)/Euler(interval<T>(q))\n      *_1phi_1(complex<interval<T> >(z*z/4),complex<interval<T> >(0.),interval<T>(q),complex<interval<T> >(pow(q,nu+1)));\n    return res;       \n  }\n template <class T> interval<T> modified_qBesselI2(const interval<T> & z,const interval<T> & nu,const interval<T>& q){\n    //verification program for 2nd modified q-Bessel function I2\n    interval<T> res;\n    if(abs(q)>=1){\n      throw std::domain_error(\"absolute value of q must be under 1\");\n    }\n    /*implementation by original definition\n      interval<T>pi;\n      i=complex<interval<T> >::i();\n      pi=constants<interval<T> >::pi();\n      res=exp(-i*nu*pi/2)*Jackson2(complex<interval<T> >(i*z),complex<interval<T> >(nu),interval<T> (q));\n    */\n    // alternative implementation\n    // reference\n    // Ismail, M. E., & Zhang, R. (2015). $ q $-Bessel Functions and Rogers-Ramanujan Type Identities.\n    // arXiv preprint arXiv:1508.06861.\n    res=pow(z/2,nu)/Euler(interval<T>(q))\n      *_1phi_1(interval<T> (z*z/4),interval<T> (0.),interval<T>(q),interval<T> (pow(q,nu+1)));\n    return res;       \n  }\n  /*template <class T> interval<T> modified_qBesselI2_ae(const interval<T> & z,const interval<T> & nu,const interval<T>& q){\n    //verification program for 2nd modified q-Bessel function I2, z>0\n    // reference\n    // Ismail, M. E., & Zhang, R. (2015). $ q $-Bessel Functions and Rogers-Ramanujan Type Identities.\n    // arXiv preprint arXiv:1508.06861.\n    interval<T> res;\n    if(abs(q)>=1){\n      throw std::domain_error(\"absolute value of q must be under 1\");\n    }\n    res=pow(z/2.,nu)*infinite_qPochhammer(interval<T>(sqrt(q)),interval<T>(q))*0.5/Euler(interval<T>(q))\n      *(infinite_qPochhammer(interval<T>(z*0.5*pow(q,(nu+0.5)*0.5)),interval<T>(sqrt(q)))+infinite_qPochhammer(interval<T>(-z*0.5*pow(q,(nu+0.5)*0.5)),interval<T>(sqrt(q))));\n    return res;\n    }*/\n  template <class T> interval<T> Hahn_Exton(const interval<T> & z,const interval<T> & nu,const interval<T>& q){\n    // verification program for Hahn-Exton q-Bessel function\n    interval<T> res,pq;\n    if(abs(q)>=1){\n      throw std::domain_error(\"absolute value of q must be under 1\");\n    }\n    pq=pow(q,nu+1);\n    /* implementation by original definition*/\n    /*    res=pow(z,nu)*infinite_qPochhammer(interval<T> (pq),interval<T>(q))*\n\t  _1phi_1(interval<T> (0),interval<T> (pq),interval<T>(q),interval<T> (z*z*q))/Euler(interval<T>(q));*/\n       // alternative implementation\n       // A. B. Olde Daalhuis, Asymptotic Expansions for q-Gamma, q-Exponential and q-Bessel Functions, formula 4.6\n       // Journal of Mathematical Analysis and Applications 186, 896-913 (1994)\n       \n    \t res=pow(z,nu)*infinite_qPochhammer(interval<T> (z*z*q),interval<T>(q))*_1phi_1(interval<T> (0),interval<T> (z*z*q),interval<T>(q),interval<T> (pq))/Euler(interval<T> (q));\n       return res;       \n  }\n  template <class T> complex<interval<T> >Hahn_Exton(const complex<interval<T> >& z,const complex<interval<T> >& nu,const interval<T>& q){\n    // verification program for Hahn-Exton q-Bessel function\n    complex<interval<T> >res,pq;\n    if(abs(q)>=1){\n      throw std::domain_error(\"absolute value of q must be under 1\");\n    }\n    pq=pow(q,nu+1);\n    /* implementation by original definition*/\n    /*  res=pow(z,nu)*infinite_qPochhammer(complex<interval<T> >(pq),interval<T>(q))*\n       _1phi_1(complex<interval<T> >(0),complex<interval<T> >(pq),interval<T>(q),complex<interval<T> >(z*z*q))/Euler(interval<T>(q));\n    */\n    // alternative implementation\n    // A. B. Olde Daalhuis, Asymptotic Expansions for q-Gamma, q-Exponential and q-Bessel Functions, formula 4.6\n    // Journal of Mathematical Analysis and Applications 186, 896-913 (1994)\n    res=pow(z,nu)*infinite_qPochhammer(complex<interval<T> >(z*z*q),interval<T>(q))*_1phi_1(complex<interval<T> >(0),complex<interval<T> >(z*z*q),interval<T>(q), complex<interval<T> >(pq))/Euler(interval<T> (q));\n     return res;       \n  }\n   template <class T> interval<T> HEratio(const interval<T> & z,const interval<T> & nu,const interval<T>& q){\n    interval<T>res;\n    res=Hahn_Exton(interval<T>(z),interval<T>(nu),interval<T>(q))/Hahn_Exton(interval<T>(z),interval<T>(nu-1),interval<T>(q));\n    return res;\n  }\n\n\n  template <class T> complex<interval<T> >little(const complex<interval<T> >& z,const complex<interval<T> >& nu,const interval<T>& q){\n    // verification program for little q-Bessel function\n    // reference\n    // Koornwinder and Swarttouw, On q-analogues of the Fourier and Hankel transforms, 1992\n    // Bouzeffour, New Addition Formula for the Little q-Bessel Functions, arXiv, 2013\n    complex<interval<T> >res,pq;\n    if(abs(q)>=1){\n      throw std::domain_error(\"absolute value of q must be under 1\");\n    }\n    pq=pow(q,nu+1);\n    res=pow(z,nu)*infinite_qPochhammer(complex<interval<T> >(pq),interval<T>(q))*\n      _1phi_1(complex<interval<T> >(0),complex<interval<T> >(pq),interval<T>(q),complex<interval<T> >(z))/Euler(interval<T>(q));\n    return res;       \n  }\n\n\n}\n  \n#endif\n", "meta": {"hexsha": "b894c6bf02411338f49deb033f737b4d37fbb3f6", "size": 23897, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qBessel.hpp", "max_stars_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_stars_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T20:55:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T12:26:00.000Z", "max_issues_repo_path": "qBessel.hpp", "max_issues_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_issues_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-03-07T04:32:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-05T01:48:57.000Z", "max_forks_repo_path": "qBessel.hpp", "max_forks_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_forks_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.434856176, "max_line_length": 212, "alphanum_fraction": 0.6171485961, "num_tokens": 8024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6313100799878374}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/blas_wrapper.hpp>\n\n#define BOOST_TEST_MODULE FrovedisTest\n#include <boost/test/unit_test.hpp>\n\nusing namespace frovedis;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    // norm of a std::vector\n    std::vector<float> x = {0,0,3,4};\n    auto d = nrm2<float> (x);\n    BOOST_CHECK (d == 5);\n\n    // creating a colmajor matrix local from file\n    colmajor_matrix_local<float> cm (\n           make_rowmajor_matrix_local_load<float>(\"./sample_4x4\"));\n  \n    // checking norm() operation  \n    auto row1 = make_row_vector<float> (cm,1);\n    \n    // checking whether the norm operation successfully taken place\n    float expected = 6; \n    float res = nrm2<float>(row1);\n    BOOST_CHECK (res == expected);\n}\n\n", "meta": {"hexsha": "cf2681c7848812b23677fc3da254eb02ce1c6263", "size": 846, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test6.6/test.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "test/matrix/test6.6/test.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "test/matrix/test6.6/test.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 24.8823529412, "max_line_length": 67, "alphanum_fraction": 0.670212766, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6313100560071534}}
{"text": "#include <iostream>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/algorithm/minmax.hpp>\n#include <vector>\n\n#include \"dbscan.h\"\n\nnamespace clustering\n{\n\tDBSCAN::ClusterData DBSCAN::gen_cluster_data( size_t features_num, size_t elements_num )\n\t{\n\t\tDBSCAN::ClusterData cl_d( elements_num, features_num );\n\n\t\tfor (size_t i = 0; i < elements_num; ++i)\n\t\t{\n\t\t\tfor (size_t j = 0; j < features_num; ++j)\t\n\t\t\t{\n\t\t\t\tcl_d(i, j) = (-1.0 + rand() * (2.0) / RAND_MAX);\n\t\t\t}\n\t\t}\n\n\t\treturn cl_d;\n\t}\n\n\tDBSCAN::FeaturesWeights DBSCAN::std_weights( size_t s )\n\t{\n\t\t// num cols\n\t\tDBSCAN::FeaturesWeights ws( s );\n\n\t\tfor (size_t i = 0; i < s; ++i)\n\t\t{\n\t\t\tws(i) = 1.0;\n\t\t}\n\n\t\treturn ws;\n\t}\n\n\tDBSCAN::DBSCAN()\n\t{\n\n\t}\n\n\tvoid DBSCAN::init(double eps, size_t min_elems/*, int num_threads*/)\n\t{\n\t\tm_eps = eps;\n\t\tm_min_elems = min_elems;\n\t}\n\n\tDBSCAN::DBSCAN(double eps, size_t min_elems/*, int num_threads*/)\n\t: m_eps( eps )\n\t, m_min_elems( min_elems )\n\t, m_dmin(0.0)\n\t, m_dmax(0.0)\n\t{\n\t\treset();\n\t}\n\n\tDBSCAN::~DBSCAN()\n\t{\n\n\t}\n\n\tvoid DBSCAN::reset()\n\t{\n\t\tm_labels.clear();\n\t}\n\n\tvoid DBSCAN::prepare_labels( size_t s )\n\t{\n\t\tm_labels.resize(s);\n\n\t\tfor( auto & l : m_labels)\n\t\t{\n\t\t\tl = -1;\n\t\t}\n\t}\n\n\tconst DBSCAN::DistanceMatrix DBSCAN::calc_dist_matrix( const DBSCAN::ClusterData & C, const DBSCAN::FeaturesWeights & W )\n\t{\n\t\tDBSCAN::ClusterData cl_d = C;\n\n\t\tfor (size_t i = 0; i < cl_d.size2(); ++i)\n\t\t{\n\t\t\tublas::matrix_column<DBSCAN::ClusterData>col(cl_d, i);\n\n\t\t\tconst auto r = minmax_element( col.begin(), col.end() );\n\n\t\t\tdouble data_min = *r.first;\n\t\t\tdouble data_range = *r.second - *r.first;\n\n\t\t\tif (data_range == 0.0) { data_range = 1.0; }\n\n\t\t\tconst double scale = 1/data_range;\n\t\t\tconst double min = -1.0*data_min*scale;\n\n\t\t\tcol *= scale;\n\t\t\tcol.plus_assign( ublas::scalar_vector< typename ublas::matrix_column<DBSCAN::ClusterData>::value_type >(col.size(), min) );\n\t\t}\n\n\t\t// rows x rows\n\t\tDBSCAN::DistanceMatrix d_m( cl_d.size1(), cl_d.size1() );\n\t\tublas::vector<double> d_max( cl_d.size1() );\n\t\tublas::vector<double> d_min( cl_d.size1() );\n\n\t\tfor (size_t i = 0; i < cl_d.size1(); ++i)\n\t\t{\n\t\t\tfor (size_t j = i; j < cl_d.size1(); ++j)\t\n\t\t\t{\n\t\t\t\td_m(i, j) = 0.0;\n\n\t\t\t\tif (i != j)\n\t\t\t\t{\n\t\t\t\t\tublas::matrix_row<DBSCAN::ClusterData> U (cl_d, i);\n\t\t\t\t\tublas::matrix_row<DBSCAN::ClusterData> V (cl_d, j);\n\n\t\t\t\t\tint k = 0;\n\t\t\t\t\tfor (const auto e : ( U-V ) )\n\t\t\t\t\t{\n\t\t\t\t\t\td_m(i, j) += fabs(e)*W[k++];\n\t\t\t\t\t}\n\n\t\t\t\t\td_m(j, i) = d_m(i, j);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst auto cur_row = ublas::matrix_row<DBSCAN::DistanceMatrix>(d_m, i);\n\t\t\tconst auto mm = minmax_element( cur_row.begin(), cur_row.end() );\n\n\t\t\td_max(i) = *mm.second;\n\t\t\td_min(i) = *mm.first;\n\t\t}\n\n\t\tm_dmin = *(min_element( d_min.begin(), d_min.end() ));\n\t\tm_dmax = *(max_element( d_max.begin(), d_max.end() ));\n\n\t\tm_eps = (m_dmax - m_dmin) * m_eps + m_dmin;\n\n\t\treturn d_m;\n\t}\n\n\tDBSCAN::Neighbors DBSCAN::find_neighbors(const DBSCAN::DistanceMatrix & D, uint32_t pid)\n\t{\n\t\tNeighbors ne;\n\n\t\tfor (uint32_t j = 0; j < D.size1(); ++j)\n\t\t{\n\t\t\tif \t( D(pid, j) <= m_eps )\n\t\t\t{\n\t\t\t\tne.push_back(j);\n\t\t\t}\n\t\t}\n\t\treturn ne;\n\t}\n\n\tvoid DBSCAN::dbscan( const DBSCAN::DistanceMatrix & dm )\n\t{\n\t\tstd::vector<uint8_t> visited( dm.size1() );\n\n\t\tuint32_t cluster_id = 0;\n\n\t\tfor (uint32_t pid = 0; pid < dm.size1(); ++pid)\n\t\t{\n\t\t\tif ( !visited[pid] )\n\t\t\t{  \n\t\t\t\tvisited[pid] = 1;\n\n\t\t\t\tNeighbors ne = find_neighbors(dm, pid );\n\n\t\t\t\tif (ne.size() >= m_min_elems)\n\t\t\t\t{\n\t\t\t\t\tm_labels[pid] = cluster_id;\n\n\t\t\t\t\tfor (uint32_t i = 0; i < ne.size(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tuint32_t nPid = ne[i];\n\n\t\t\t\t\t\tif ( !visited[nPid] )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvisited[nPid] = 1;\n\n\t\t\t\t\t\t\tNeighbors ne1 = find_neighbors(dm, nPid);\n\n\t\t\t\t\t\t\tif ( ne1.size() >= m_min_elems )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfor (const auto & n1 : ne1)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tne.push_back(n1);\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\n\t\t\t\t\t\tif ( m_labels[nPid] == -1 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_labels[nPid] = cluster_id;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t++cluster_id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid DBSCAN::fit( const DBSCAN::ClusterData & C ) \n\t{\n\t\tconst DBSCAN::FeaturesWeights W = DBSCAN::std_weights( C.size2() );\n\t\twfit( C, W );\n\t}\n\tvoid DBSCAN::fit_precomputed( const DBSCAN::DistanceMatrix & D ) \n\t{\n\t\tprepare_labels( D.size1() );\n\t\tdbscan( D );\n\t}\n\n\tvoid DBSCAN::wfit( const DBSCAN::ClusterData & C, const DBSCAN::FeaturesWeights & W )\n\t{\n\t\tprepare_labels( C.size1() );\n\t\tconst DBSCAN::DistanceMatrix D = calc_dist_matrix( C, W );\n\t\tdbscan( D );\n\t}\n\n\tconst DBSCAN::Labels & DBSCAN::get_labels() const\n\t{\n\t\treturn m_labels;\n\t}\n\n\tstd::ostream& operator<<(std::ostream& o, DBSCAN & d)\n\t{\n\t\to << \"[ \";\n\t\tfor ( const auto & l : d.get_labels() )\n\t\t{\n\t\t\to << \" \" << l;\n\t\t}\n\t\to << \" ] \" << std::endl;\n\n\t\treturn o;\n\t}\n}\n", "meta": {"hexsha": "62f86002cb4ba0504a8a071cb3c5fb0757181ea7", "size": 4708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "clients/deprecated/ios/plugins/com.dmsl.anyplace.magloc/src/ios/Localization/DBSCAN/dbscan.cpp", "max_stars_repo_name": "Paschalis/anyplace", "max_stars_repo_head_hexsha": "e752f1e865d2a044eee7bb817dceff034c243976", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 684.0, "max_stars_repo_stars_event_min_datetime": "2015-08-28T11:03:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T03:56:10.000Z", "max_issues_repo_path": "ios/plugins/com.dmsl.anyplace.magloc/src/ios/Localization/DBSCAN/dbscan.cpp", "max_issues_repo_name": "Signage-Org/anyplace", "max_issues_repo_head_hexsha": "6b6d41efff808403321752f63dadf2e9e2910538", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": 355.0, "max_issues_repo_issues_event_min_datetime": "2015-11-03T09:30:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T11:02:05.000Z", "max_forks_repo_path": "ios/plugins/com.dmsl.anyplace.magloc/src/ios/Localization/DBSCAN/dbscan.cpp", "max_forks_repo_name": "Signage-Org/anyplace", "max_forks_repo_head_hexsha": "6b6d41efff808403321752f63dadf2e9e2910538", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": 345.0, "max_forks_repo_forks_event_min_datetime": "2015-09-19T03:01:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T11:54:43.000Z", "avg_line_length": 19.5352697095, "max_line_length": 126, "alphanum_fraction": 0.5826253186, "num_tokens": 1620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6312356423652936}}
{"text": "// souece: http://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html\n// Compile: g++ -I /usr/include/eigen3/ eigen_ex1.cpp -o eigen_ex1\n#include <iostream>\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\n\nint main(void)\n{\n    Eigen::Matrix3f m3;\n    // Comma-initialization\n    m3 << 1, 2, 3,\n          4, 5, 6,\n          7, 8, 9;\n    std::cout << m3 << std::endl;\n    \n    // Resize\n    MatrixXd m(2,5);\n    m.resize(4,3);\n    std::cout << \"The matrix m is of size \" \n              << m.rows() << \"X\" << m.cols() << std::endl;\n    std::cout << \"It has \" << m.size() << \" coefficients\"\n        << std::endl;\n    Eigen::VectorXd v(2);\n    v.resize(5);\n    std::cout << \"The vector v is of size \" << v.size()\n        << std::endl;\n    std::cout << \"As a matrix, v is of size \"\n              << v.rows() << \"x\" << v.cols() << std::endl;\n\n    // Assignment (operator=) and resizing\n    Eigen::MatrixXf a(2,2);\n    std::cout << \"a is of size \" << a.rows() << \"x\" << a.cols() \n        << std::endl;\n    Eigen::MatrixXf b(3,3);\n    a = b;  // using operator=, will resize the matrix on the left-hand.\n    std::cout << \"a is now of size \" << a.rows() << \"x\" << a.cols() \n        << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "48b814c1de4cff7e4ba2a6d5f54df5f1b78c1424", "size": 1205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen_practice/eigen_ex3.cpp", "max_stars_repo_name": "RobinCPC/ros_tutorials", "max_stars_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Eigen_practice/eigen_ex3.cpp", "max_issues_repo_name": "RobinCPC/ros_tutorials", "max_issues_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Eigen_practice/eigen_ex3.cpp", "max_forks_repo_name": "RobinCPC/ros_tutorials", "max_forks_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T06:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-29T06:32:54.000Z", "avg_line_length": 29.3902439024, "max_line_length": 73, "alphanum_fraction": 0.5170124481, "num_tokens": 394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6311906547025943}}
{"text": "#include <algorithm>\n#include <cassert>\n#include <vector>\n\n#include <gtest/gtest.h>\n#include <boost/math/distributions/binomial.hpp>\n\n#include <hypergirgs/Hyperbolic.h>\n#include <hypergirgs/HyperbolicTree.h>\n\n\nclass EdgeProbabilities_test: public ::testing::TestWithParam< std::tuple<unsigned, unsigned, double, double> > {\nprotected:\n    const int sampleSeed = 12456;\n    const int edgesSeed = 1400;\n\n    static size_t edge2idx(unsigned u, unsigned v, size_t n) {\n        const auto mm = std::minmax(u, v);\n        return mm.first * n + mm.second;\n    }\n\n    static std::vector<uint64_t>\n    count_edges(const std::vector<double> &radii, const std::vector<double> &angles, double T, double R, int seed,\n                const unsigned num_graphs) {\n        const auto n = radii.size();\n        assert(radii.size() == angles.size());\n        assert(n > 0);\n\n        std::vector<uint64_t> counts(n * n, 0);\n        if (!num_graphs)\n            return counts;\n\n        auto count_callback = [&counts, n](int u, int v, int /*tid*/) { counts[edge2idx(u, v, n)]++; };\n        auto generator = hypergirgs::makeHyperbolicTree(radii, angles, T, R, count_callback, false);\n\n        for (unsigned i = 0; i < num_graphs; ++i)\n            generator.generate(i * 1234567 + 123);\n\n        return counts;\n    }\n\n    static uint64_t count_violations(const std::vector<double> &radii, const std::vector<double> &angles, double T, double R,\n                                     const std::vector<uint64_t> &counts, const unsigned num_graphs, const double confidence) {\n        using namespace boost::math;\n\n        const auto n = radii.size();\n        assert(radii.size() == angles.size());\n        assert(n > 0);\n\n        uint64_t violations = 0;\n        #pragma omp parallel for schedule(dynamic) reduction(+:violations)\n        for (int u = 0; u < n; ++u) {\n            for (int v = u + 1; v < n; ++v) {\n                const auto idx = edge2idx(u, v, n);\n                const auto dist = hypergirgs::hyperbolicDistance(radii[u], angles[u], radii[v], angles[v]);\n                const auto prob = 1.0 / (1.0 + std::exp(0.5 / T * (dist - R)));\n                const auto count = counts[idx];\n                const auto mean = prob * num_graphs;\n\n                const double pvalue = 2.0 * ((count < mean) ? cdf(binomial(num_graphs, prob), count) : cdf(\n                    complement(binomial(num_graphs, prob), count - 1)));\n\n                EXPECT_GT(pvalue, confidence)\n                                << \"Edge (\" << u << \", \" << v << \") with r1=\" << radii[u] << \", phi1\" << angles[u] << \", r2=\" << radii[v]\n                                << \", phi2\" << angles[v] << \", dist=\" << dist << \", prob=\" << prob << \", count=\" << count << \", p-value=\"\n                                << pvalue;\n\n                violations += pvalue < confidence;\n            }\n        }\n\n        return violations;\n    }\n};\n\n/*\n * For positive temperatures we carry out statistical tests for each edge. Our null hypothesis is that our generator works\n * correct. Then we compute numGraphs many graph instances for the same set of points and count for each possible edge (u,v) the\n * number N(u,v) of times it is generated. Given that (u,v) has a probability of p(u,v) we expect N(u,v) to be distributed as\n * Bernoulli(numGraphs, p(u,v)). We compute its p-value and reject with a significance level of sig (corrected for the fact,\n * the we carry out (n over 2) trials -- one for each possible edge).\n */\nTEST_P(EdgeProbabilities_test, StatTestCorrectProbs) {\n    unsigned n, deg;\n    double alpha, T;\n    std::tie(n, deg, alpha, T) = GetParam();\n    ASSERT_GT(T, 0.0);\n\n    const auto sig = 0.05; // Reject H0 (generator is correct) with a significance level of 5%\n    const auto numGraphs = 100; // Compute 100 graphs\n    const auto corrected_sig = sig / n / (n - 1) * 2.0; // Bonferroni correction as we carry out (n over 2) independent trails\n\n    auto R = hypergirgs::calculateRadius(n, alpha, T, deg);\n    std::vector<double> radii, angles;\n    std::tie(radii, angles) = hypergirgs::sampleRadiiAndAngles(n, alpha, R, sampleSeed + n);\n\n    const auto counts = count_edges(radii, angles, T, R, edgesSeed + n, numGraphs);\n    const auto violations = count_violations(radii, angles, T, R, counts, numGraphs, corrected_sig);\n    ASSERT_EQ(violations, 0);\n}\n\nstatic std::vector< std::tuple<unsigned, unsigned, double, double> > params({\n    {1000, 10, 0.75, 0.5}, {900, 100, 0.75, 0.5}, {800, 10, 0.6, 0.5}, {700, 10, 0.75, 0.9}\n});\nINSTANTIATE_TEST_SUITE_P(Params, EdgeProbabilities_test,\n                         ::testing::ValuesIn(params.begin(), params.end()));", "meta": {"hexsha": "2419599af6646ec5e5cc87f940fbbfcdd1aeb7f0", "size": 4632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/tests/hypergirgs-test/EdgeProbabilities_test.cpp", "max_stars_repo_name": "PFischbeck/pygirgs", "max_stars_repo_head_hexsha": "e2a9bb4d514ebfd13ecd3dec1c862dd4c83118c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/tests/hypergirgs-test/EdgeProbabilities_test.cpp", "max_issues_repo_name": "PFischbeck/pygirgs", "max_issues_repo_head_hexsha": "e2a9bb4d514ebfd13ecd3dec1c862dd4c83118c3", "max_issues_repo_licenses": ["MIT"], "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/tests/hypergirgs-test/EdgeProbabilities_test.cpp", "max_forks_repo_name": "PFischbeck/pygirgs", "max_forks_repo_head_hexsha": "e2a9bb4d514ebfd13ecd3dec1c862dd4c83118c3", "max_forks_repo_licenses": ["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.6981132075, "max_line_length": 137, "alphanum_fraction": 0.5986614853, "num_tokens": 1262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.63119064702926}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Siddharth Pritam, Vincent Rouvreau\n *\n *    Copyright (C) 2020 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <gudhi/Flag_complex_edge_collapser.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n#include <gudhi/reader_utils.h>\n#include <gudhi/graph_simplicial_complex.h>\n\n#include <boost/program_options.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n\nusing Simplex_tree = Gudhi::Simplex_tree<Gudhi::Simplex_tree_options_fast_persistence>;\nusing Filtration_value = Simplex_tree::Filtration_value;\nusing Vertex_handle = Simplex_tree::Vertex_handle;\n\nusing Filtered_edge = std::tuple<Vertex_handle, Vertex_handle, Filtration_value>;\nusing Proximity_graph = Gudhi::Proximity_graph<Simplex_tree>;\n\nusing Field_Zp = Gudhi::persistent_cohomology::Field_Zp;\nusing Persistent_cohomology = Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Field_Zp>;\nusing Distance_matrix = std::vector<std::vector<Filtration_value>>;\n\nvoid program_options(int argc, char* argv[], std::string& csv_matrix_file, std::string& filediag,\n                     Filtration_value& threshold, int& dim_max, int& p, int& edge_collapse_iter_nb,\n                     Filtration_value& min_persistence);\n\nint main(int argc, char* argv[]) {\n  std::string csv_matrix_file;\n  std::string filediag;\n  Filtration_value threshold;\n  int dim_max = 2;\n  int p;\n  int edge_collapse_iter_nb;\n  Filtration_value min_persistence;\n\n  program_options(argc, argv, csv_matrix_file, filediag, threshold, dim_max, p, edge_collapse_iter_nb,\n                  min_persistence);\n\n  Distance_matrix distances = Gudhi::read_lower_triangular_matrix_from_csv_file<Filtration_value>(csv_matrix_file);\n  std::cout << \"Read the distance matrix succesfully, of size: \" << distances.size() << std::endl;\n\n  Proximity_graph proximity_graph = Gudhi::compute_proximity_graph<Simplex_tree>(boost::irange((size_t)0,\n                                                                                               distances.size()),\n                                                                                 threshold,\n                                                                                 [&distances](size_t i, size_t j) {\n                                                                                   return distances[j][i];\n                                                                                 });\n\n  auto edges_from_graph = boost::adaptors::transform(edges(proximity_graph), [&](auto&&edge){\n        return std::make_tuple(source(edge, proximity_graph),\n                               target(edge, proximity_graph),\n                               get(Gudhi::edge_filtration_t(), proximity_graph, edge));\n      });\n  std::vector<Filtered_edge> edges_list(edges_from_graph.begin(), edges_from_graph.end());\n  std::vector<Filtered_edge> remaining_edges;\n  for (int iter = 0; iter < edge_collapse_iter_nb; iter++) {\n    auto remaining_edges = Gudhi::collapse::flag_complex_collapse_edges(edges_list);\n    edges_list = std::move(remaining_edges);\n    remaining_edges.clear();\n  }\n\n  Simplex_tree stree;\n  for (Vertex_handle vertex = 0; static_cast<std::size_t>(vertex) < distances.size(); vertex++) {\n    // insert the vertex with a 0. filtration value just like a Rips\n    stree.insert_simplex({vertex}, 0.);\n  }\n  for (auto filtered_edge : edges_list) {\n    stree.insert_simplex({std::get<0>(filtered_edge), std::get<1>(filtered_edge)}, std::get<2>(filtered_edge));\n  }\n\n  stree.expansion(dim_max);\n\n  std::cout << \"The complex contains \" << stree.num_simplices() << \" simplices  after collapse. \\n\";\n  std::cout << \"   and has dimension \" << stree.dimension() << \" \\n\";\n\n  // Sort the simplices in the order of the filtration\n  stree.initialize_filtration();\n  // Compute the persistence diagram of the complex\n  Persistent_cohomology pcoh(stree);\n  // initializes the coefficient field for homology\n  pcoh.init_coefficients(3);\n\n  pcoh.compute_persistent_cohomology(min_persistence);\n  if (filediag.empty()) {\n    pcoh.output_diagram();\n  } else {\n    std::ofstream out(filediag);\n    pcoh.output_diagram(out);\n    out.close();\n  }\n  return 0;\n}\n\nvoid program_options(int argc, char* argv[], std::string& csv_matrix_file, std::string& filediag,\n                     Filtration_value& threshold, int& dim_max, int& p, int& edge_collapse_iter_nb,\n                     Filtration_value& min_persistence) {\n  namespace po = boost::program_options;\n  po::options_description hidden(\"Hidden options\");\n  hidden.add_options()(\n      \"input-file\", po::value<std::string>(&csv_matrix_file),\n      \"Name of file containing a distance matrix. Can be square or lower triangular matrix. Separator is ';'.\");\n\n  po::options_description visible(\"Allowed options\", 100);\n  visible.add_options()(\"help,h\", \"produce help message\")(\n      \"output-file,o\", po::value<std::string>(&filediag)->default_value(std::string()),\n      \"Name of file in which the persistence diagram is written. Default print in std::cout\")(\n      \"max-edge-length,r\",\n      po::value<Filtration_value>(&threshold)->default_value(std::numeric_limits<Filtration_value>::infinity()),\n      \"Maximal length of an edge for the Rips complex construction.\")(\n      \"cpx-dimension,d\", po::value<int>(&dim_max)->default_value(1),\n      \"Maximal dimension of the Rips complex we want to compute.\")(\n      \"field-charac,p\", po::value<int>(&p)->default_value(11),\n      \"Characteristic p of the coefficient field Z/pZ for computing homology.\")(\n      \"edge-collapse-iterations,i\", po::value<int>(&edge_collapse_iter_nb)->default_value(1),\n      \"Number of iterations edge collapse is performed.\")(\n      \"min-persistence,m\", po::value<Filtration_value>(&min_persistence),\n      \"Minimal lifetime of homology feature to be recorded. Default is 0. Enter a negative value to see zero length \"\n      \"intervals\");\n\n  po::positional_options_description pos;\n  pos.add(\"input-file\", 1);\n\n  po::options_description all;\n  all.add(visible).add(hidden);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(all).positional(pos).run(), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") || !vm.count(\"input-file\")) {\n    std::cout << std::endl;\n    std::cout << \"Compute the persistent homology with coefficient field Z/pZ \\n\";\n    std::cout << \"of a Rips complex after edge collapse defined on a set of distance matrix.\\n \\n\";\n    std::cout << \"The output diagram contains one bar per line, written with the convention: \\n\";\n    std::cout << \"   p   dim b d \\n\";\n    std::cout << \"where dim is the dimension of the homological feature,\\n\";\n    std::cout << \"b and d are respectively the birth and death of the feature and \\n\";\n    std::cout << \"p is the characteristic of the field Z/pZ used for homology coefficients.\" << std::endl << std::endl;\n\n    std::cout << \"Usage: \" << argv[0] << \" [options] input-file\" << std::endl << std::endl;\n    std::cout << visible << std::endl;\n    exit(-1);\n  }\n}\n", "meta": {"hexsha": "11ee5871155863864e78b6288da72bcb674d9eb1", "size": 7238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Collapse/utilities/distance_matrix_edge_collapse_rips_persistence.cpp", "max_stars_repo_name": "m0baxter/gudhi-devel", "max_stars_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Collapse/utilities/distance_matrix_edge_collapse_rips_persistence.cpp", "max_issues_repo_name": "m0baxter/gudhi-devel", "max_issues_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Collapse/utilities/distance_matrix_edge_collapse_rips_persistence.cpp", "max_forks_repo_name": "m0baxter/gudhi-devel", "max_forks_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 47.3071895425, "max_line_length": 119, "alphanum_fraction": 0.6608179055, "num_tokens": 1747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6311906393559255}}
{"text": "#ifndef MATHTOOLBOX_GAUSSIAN_PROCESS_REGRESSION_HPP\n#define MATHTOOLBOX_GAUSSIAN_PROCESS_REGRESSION_HPP\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <mathtoolbox/kernel-functions.hpp>\n\nnamespace mathtoolbox\n{\n    class GaussianProcessRegressor\n    {\n    public:\n        enum class KernelType\n        {\n            ArdSquaredExp,\n            ArdMatern52\n        };\n\n        /// \\brief Construct an instance with input data\n        GaussianProcessRegressor(const Eigen::MatrixXd& X,\n                                 const Eigen::VectorXd& y,\n                                 const KernelType       kernel_type            = KernelType::ArdMatern52,\n                                 const bool             use_data_normalization = true);\n\n        /// \\brief Calculate the mean of the predicted distribution\n        double PredictMean(const Eigen::VectorXd& x) const;\n\n        /// \\brief Calculate the standard deviation of the predicted distribution\n        double PredictStdev(const Eigen::VectorXd& x) const;\n\n        /// \\brief Calculate the derivative of the mean of the predicted distribution\n        Eigen::VectorXd PredictMeanDeriv(const Eigen::VectorXd& x) const;\n\n        /// \\brief Calculate the derivative of the standard deviation of the predicted distribution\n        Eigen::VectorXd PredictStdevDeriv(const Eigen::VectorXd& x) const;\n\n        /// \\brief Set hyperparameters directly\n        ///\n        /// \\details Covariance matrix calculation will run within this method.\n        void SetHyperparams(const Eigen::VectorXd& kernel_hyperparams, const double noise_hyperparam);\n\n        /// \\brief Perform maximum likelihood estimation of the hyperparameters\n        void PerformMaximumLikelihood(const Eigen::VectorXd& kernel_hyperparams_initial,\n                                      const double           noise_hyperparam_initial);\n\n        /// \\brief Get the input data points\n        const Eigen::MatrixXd& GetDataPoints() const { return m_X; }\n\n        /// \\brief Get the input data values\n        const Eigen::VectorXd& GetDataValues() const { return m_y; }\n\n    private:\n        // Data points\n        Eigen::MatrixXd m_X;\n        Eigen::VectorXd m_y;\n\n        // Derivative data\n        Eigen::MatrixXd             m_K_y;\n        Eigen::LLT<Eigen::MatrixXd> m_K_y_llt;\n        Eigen::VectorXd             m_K_y_inv_y;\n\n        // Normalization parameters\n        double m_data_mu;\n        double m_data_sigma;\n        double m_data_scale;\n\n        // Hyperparameters\n        Eigen::VectorXd m_kernel_hyperparams;\n        double          m_noise_hyperparam;\n\n        // Kernel functions\n        Kernel                   m_kernel;\n        KernelThetaIDerivative   m_kernel_deriv_theta_i;\n        KernelFirstArgDerivative m_kernel_deriv_first_arg;\n    };\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_GAUSSIAN_PROCESS_REGRESSION_HPP\n", "meta": {"hexsha": "17e5c6cae10b2dfb42882548c369a58bf4a27b90", "size": 2867, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/gaussian-process-regression.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/gaussian-process-regression.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/gaussian-process-regression.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": 36.2911392405, "max_line_length": 105, "alphanum_fraction": 0.6382978723, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6311898483279633}}
{"text": "#include <cstdlib>\n#include <cstdio>\n\n//#include <boost/random.hpp>\n#include <boost/random/random_device.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\n//Test::Test(boost::random::mt19937_64, boost::random::uniform_real_distribution<>);\n//Test::~Test();\n//Test::double GetRNG01();\n\nstruct Test\n{\n    boost::random::mt19937_64 rng;\n    boost::random::uniform_real_distribution<double> dist01;\n\n    Test(boost::random::mt19937_64 engine, boost::random::uniform_real_distribution<double> dist) : rng(engine), dist01(dist) {};\n    ~Test() {};\n\n    double GetRNG01()\n    {\n        return dist01(rng);\n    }\n};\n\nint main()\n{\n    boost::random::random_device rd;\n    boost::random::mt19937_64 engine(rd);\n    boost::random::uniform_real_distribution<double> dist(0,1);\n\n    Test testStruct(engine, dist);\n    printf(\"Result: %f\\n\", testStruct.GetRNG01());\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "a8336c32d5e3df997d84c1d23bcfed2e7feee6bf", "size": 936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/CPP/use_boost_mt.cpp", "max_stars_repo_name": "CaryRock/Phys642_Final_Project", "max_stars_repo_head_hexsha": "fb1e49b84efb0585857bb16379fbc6ac39074c5c", "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": "testing/CPP/use_boost_mt.cpp", "max_issues_repo_name": "CaryRock/Phys642_Final_Project", "max_issues_repo_head_hexsha": "fb1e49b84efb0585857bb16379fbc6ac39074c5c", "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": "testing/CPP/use_boost_mt.cpp", "max_forks_repo_name": "CaryRock/Phys642_Final_Project", "max_forks_repo_head_hexsha": "fb1e49b84efb0585857bb16379fbc6ac39074c5c", "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.0, "max_line_length": 129, "alphanum_fraction": 0.6955128205, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6311898380490437}}
{"text": "#include \"QuadraticMinimization.hpp\"\n#include \"gtest/gtest.h\"\n#include <vector>\n#include <Eigen/Core>\n\n\n//--------------------------------------------------------------------------------\nclass Wrapper_QuadraticMinimization : public QuadraticMinimization {\n  public:\n    Wrapper_QuadraticMinimization ( int dim_input ) :\n       QuadraticMinimization ( dim_input ) { };\n\n    int quadratic_minimization_test1 ( ) {\n      std::vector<double> y(2);\n      std::vector<double> g(2);\n      std::vector< std::vector<double> > H(2);\n      H[0].resize(2);\n      H[1].resize(2);\n      g[0] = 1.0; g[1] = 2.0;\n      H[0][0] = -4.0; H[0][1] = 1.0;   //XX check second\n      H[1][0] =  1.0; H[1][1] = 5.0;   //XX check second\n      QuadraticMinimization::minimize( y, g, H );\n      if ( fabs(y[0] + 0.994835624149) > 1e-6 ) return 0;\n      if ( fabs(y[1] + 0.101499306351) > 1e-6 ) return 0;\n      return 1;\n    }\n    int quadratic_minimization_test2 ( ) {\n      std::vector<double> y(2);\n      std::vector<double> g(2);\n      std::vector< std::vector<double> > H(2);\n      H[0].resize(2);\n      H[1].resize(2);\n      g[0] = 1.0; g[1] = 0.0;\n      H[0][0] = -1.0; H[0][1] = 0.0;\n      H[1][0] =  0.0; H[1][1] = 1.0; \n      QuadraticMinimization::minimize( y, g, H );\n      if ( fabs(y[0] + 1.0 ) > 1e-6 ) return 0;\n      if ( fabs(y[1] + 0.0 ) > 1e-6 ) return 0;\n      return 1;\n    }\n    int quadratic_minimization_test3 ( ) {\n      std::vector<double> y(2);\n      std::vector<double> g(2);\n      std::vector< std::vector<double> > H(2);\n      H[0].resize(2);\n      H[1].resize(2);\n      g[0] = 0.0; g[1] = 2.0;\n      H[0][0] = -4.0; H[0][1] = 0.0;\n      H[1][0] =  0.0; H[1][1] = 4.0; \n      QuadraticMinimization::minimize( y, g, H );\n      if ( fabs(y[0] - 0.968252226024 ) > 1e-6 && \n           fabs(y[0] - 0.968252226024 ) > 1e-6 ) return 0;\n      if ( fabs(y[1] + 0.249975252374 ) > 1e-6 ) return 0;\n      return 1;\n    }\n\n};\n//--------------------------------------------------------------------------------\n\n\n//--------------------------------------------------------------------------------\nTEST ( QuadraticMinimizationTest, minimize_test1 ) \n{\n  Wrapper_QuadraticMinimization W ( 2 );\n  EXPECT_EQ( 1, W.quadratic_minimization_test1() );\n}\n//--------------------------------------------------------------------------------\n\n//--------------------------------------------------------------------------------\nTEST ( QuadraticMinimizationTest, minimize_test2 ) \n{\n  Wrapper_QuadraticMinimization W ( 2 );\n  EXPECT_EQ( 1, W.quadratic_minimization_test2() );\n}\n//--------------------------------------------------------------------------------\n\n//--------------------------------------------------------------------------------\nTEST ( QuadraticMinimizationTest, minimize_test3 ) \n{\n  Wrapper_QuadraticMinimization W ( 2 );\n  EXPECT_EQ( 1, W.quadratic_minimization_test3() );\n}\n//--------------------------------------------------------------------------------\n\n", "meta": {"hexsha": "cbabc64afcf19de7560d493465cf924e0ee437a2", "size": 2951, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/include/gtest_quadraticminimization.hpp", "max_stars_repo_name": "snowpac/snowpac", "max_stars_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-04T20:18:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T23:50:27.000Z", "max_issues_repo_path": "test/include/gtest_quadraticminimization.hpp", "max_issues_repo_name": "snowpac/snowpac", "max_issues_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/include/gtest_quadraticminimization.hpp", "max_forks_repo_name": "snowpac/snowpac", "max_forks_repo_head_hexsha": "ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7176470588, "max_line_length": 82, "alphanum_fraction": 0.4388342935, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6311810360524073}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_NBMANTISSABITS_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_NBMANTISSABITS_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Nbmantissabits Nbmantissabits (function template)\n\n  Generates a constant representing the number of mantissa bits of a floating point type.\n\n  @headerref{<boost/simd/constant/nbexponentbits.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> as_integer_t<T> Nbmantissabits();\n      @endcode\n\n  2.  @code\n      template<typename T> as_integer_t<T> Nbmantissabits( boost::simd::as_<T> const& target );\n      @endcode\n\n    Generates a value of type `as_integer_t<T>` that evaluates to the number of bits used to\n    represents the mantissa of an IEEE value.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c as_integer_t<T> that evaluates to:\n\n  | Type         | double      | float         |\n  |:-------------|:------------|---------------|\n  | **Values**   |   52        |     23        |\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/nbmantissabits.hpp>\n#include <boost/simd/constant/simd/nbmantissabits.hpp>\n\n#endif\n", "meta": {"hexsha": "9157f17ed4458ebc79f9a1e6a773e58e669fd741", "size": 1832, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/nbmantissabits.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/nbmantissabits.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/nbmantissabits.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 32.7142857143, "max_line_length": 100, "alphanum_fraction": 0.5403930131, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117812622843, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6311810221328017}}
{"text": "#include <boost/units/cmath.hpp>\n#include <boost/units/io.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/systems/si.hpp>\n#include <iostream>\n#include <tuple>\n\nusing Length_unit = boost::units::si::length;\nusing Length = boost::units::quantity<Length_unit>;\nusing Time_unit = boost::units::si::time;\nusing Time = boost::units::quantity<Time_unit>;\nusing Velocity_unit = boost::units::si::velocity;\nusing Velocity = boost::units::quantity<Velocity_unit>;\n\nVelocity compute_velocity(const Length dx, const Time dt) {\n    return dx/dt;\n}\n\nusing Point = std::tuple<Length, Length>;\n\nLength distance(const Point& p1, const Point& p2) {\n    Length x1 {std::get<0>(p1)};\n    Length x2 {std::get<0>(p2)};\n    Length y1 {std::get<1>(p1)};\n    Length y2 {std::get<1>(p2)};\n    return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));\n}\n\nint main() {\n    // define units to make formulas easier to read\n    Length_unit m {boost::units::si::meter};\n    Time_unit s {boost::units::si::seconds};\n\n    Length dx {3.5*m};\n    Time dt {2.0*s};\n    Velocity velocity = compute_velocity(dx, dt);\n    std::cout << velocity << std::endl;\n    std::cout << velocity.value() << std::endl;\n\n    Point p1 {std::make_tuple(3.0*m, 4.0*m)};\n    Point p2 {std::make_tuple(5.0*m, 2.0*m)};\n    std::cout << distance(p1, p2) << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "a6c1fd8612c4454cc6b9cd22d7f9bf2c25b7daca", "size": 1337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Boost/Units/units_okay.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Boost/Units/units_okay.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Boost/Units/units_okay.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 29.0652173913, "max_line_length": 59, "alphanum_fraction": 0.6469708302, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6311807516911505}}
{"text": "// STL includes\n#include <iostream>\n#include <vector>\n\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n  boost::no_property, boost::property<boost::edge_weight_t, int> >      weighted_graph;\ntypedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map;\ntypedef boost::graph_traits<weighted_graph>::edge_descriptor            edge_desc;\ntypedef boost::graph_traits<weighted_graph>::vertex_descriptor          vertex_desc;\n\nusing namespace std;\n\nint dijkstra(const weighted_graph &G, int s, int t) {\n  int n = boost::num_vertices(G);\n  std::vector<int> dist_map(n);\n\n  boost::dijkstra_shortest_paths(G, s,\n    boost::distance_map(boost::make_iterator_property_map(\n      dist_map.begin(), boost::get(boost::vertex_index, G))));\n\n  return dist_map[t];\n}\n\nvoid kruskal(const weighted_graph &G, vector<edge_desc> &mst) {\n  boost::kruskal_minimum_spanning_tree(G, std::back_inserter(mst));\n}\n\n\nvoid testcase() {\n  int n; cin >> n;\n  int m; cin >> m;\n  int s; cin >> s;\n  int a, b; cin >> a; cin >> b;\n  vector<weighted_graph> Gs(s, weighted_graph(n));\n  weighted_graph G(n);\n  vector<weight_map> weights(s);\n\n  for(int i = 0; i < s; i++)\n    weights[i] = boost::get(boost::edge_weight, Gs[i]);\n  \n  weight_map weights_g = boost::get(boost::edge_weight, G);\n  edge_desc e;\n  for(int i = 0; i < m; i++) {\n    int u,v; cin >> u; cin >> v;\n    for(int j = 0; j < s; j++) {\n      int w; cin >> w;\n      e = boost::add_edge(u, v, Gs[j]).first; weights[j][e] = w;\n    }\n  }\n  \n  int hive; // disregard hives\n  for(int i = 0; i < s; i++) {\n    cin >> hive;\n  }\n  for(int i = 0; i < s; i++) {\n    vector<edge_desc> mst;\n    kruskal(Gs[i], mst);\n    for (std::vector<edge_desc>::iterator it = mst.begin(); it != mst.end(); ++it) {\n        int u = boost::source(*it, Gs[i]);\n        int v = boost::target(*it, Gs[i]);\n        if(!edge(u,v,G).second) { // edge not yet in G\n          e = boost::add_edge(u, v, G).first;\n          weights_g[e] = weights[i][*it];\n        } else {\n          e = edge(u,v,G).first;\n          weights_g[e] = min(weights_g[e], weights[i][*it]);\n        }\n    }\n  }\n  \n  cout << dijkstra(G, a, b) << endl;\n  \n}\nint main()\n{\n  std::ios_base::sync_with_stdio(false); // Always!\n  int t; cin >> t;\n  for(int i = 0; i < t; i++)\n    testcase();\n  return 0;\n}\n", "meta": {"hexsha": "bcf26f55f01a69025f545ae0e93694c44dbe1ffd", "size": 2476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week04-ant_challenge/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/week04-ant_challenge/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/week04-ant_challenge/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4597701149, "max_line_length": 87, "alphanum_fraction": 0.6134894992, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021706, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6311807413425611}}
{"text": "//  (C) Copyright Nick Thompson 2020.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n\n\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <map>\n#include <cmath>\n#include <vector>\n#include <iomanip>\n#include <boost/algorithm/string.hpp>\n#include <boost/math/statistics/linear_regression.hpp>\n#include <boost/assert.hpp>\n\n\nint main(int argc, char** argv)\n{\n    if (argc != 2)\n    {\n        std::cout << \"Usage: ./regress_accuracy.x foo.csv\\n\";\n        return 1;\n    }\n    std::string filename = std::string(argv[1]);\n    std::ifstream ifs(filename.c_str());\n    if (!ifs.good())\n    {\n        std::cerr << \"Couldn't find file \" << filename << \"\\n\";\n        return 1;\n    }\n    std::map<std::string, std::vector<double>> m;\n\n    std::string header_line;\n    std::getline(ifs, header_line);\n    std::cout << \"Header line = \" << header_line << \"\\n\";\n    std::vector<std::string> header_strs;\n    boost::split(header_strs, header_line, boost::is_any_of(\",\"));\n    for (auto & s : header_strs) {\n        boost::algorithm::trim(s);\n    }\n\n    std::string line;\n    std::vector<double> r;\n    std::vector<double> matched_holder;\n    std::vector<double> linear;\n    std::vector<double> quadratic_b_spline;\n    std::vector<double> cubic_b_spline;\n    std::vector<double> quintic_b_spline;\n    std::vector<double> cubic_hermite;\n    std::vector<double> pchip;\n    std::vector<double> makima;\n    std::vector<double> fotaylor;\n    std::vector<double> quintic_hermite;\n    std::vector<double> sotaylor;\n    std::vector<double> totaylor;\n    std::vector<double> septic_hermite;\n    while(std::getline(ifs, line))\n    {\n        std::vector<std::string> strs;\n        boost::split(strs, line, boost::is_any_of(\",\"));\n        for (auto & s : strs)\n        {\n            boost::algorithm::trim(s);\n        }\n        std::vector<double> v(strs.size(), std::numeric_limits<double>::quiet_NaN());\n        for (size_t i = 0; i < v.size(); ++i)\n        {\n            v[i] = std::stod(strs[i]);\n        }\n        r.push_back(v[0]);\n        matched_holder.push_back(std::log2(v[1]));\n        linear.push_back(std::log2(v[2]));\n        quadratic_b_spline.push_back(std::log2(v[3]));\n        cubic_b_spline.push_back(std::log2(v[4]));\n        quintic_b_spline.push_back(std::log2(v[5]));\n        cubic_hermite.push_back(std::log2(v[6]));\n        pchip.push_back(std::log2(v[7]));\n        makima.push_back(std::log2(v[8]));\n        fotaylor.push_back(std::log2(v[9]));\n        if (v.size() > 10) {\n            quintic_hermite.push_back(std::log2(v[10]));\n            sotaylor.push_back(std::log2(v[11]));\n        }\n        if (v.size() > 12) {\n            totaylor.push_back(std::log2(v[12]));\n            septic_hermite.push_back(std::log2(v[13]));\n        }\n    }\n\n    std::cout << std::fixed << std::setprecision(16);\n    auto q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, matched_holder);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"Matched Holder    : \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, linear);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"Linear            : \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, quadratic_b_spline);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"Quadratic B-spline: \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, cubic_b_spline);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"Cubic B-spline    : \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, quintic_b_spline);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"Quintic B-spline  : \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, cubic_hermite);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"Cubic Hermite     : \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, pchip);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"PCHIP             : \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, makima);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"Makima            : \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, fotaylor);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"First-order Taylor: \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    if (sotaylor.size() > 0)\n    {\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, quintic_hermite);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"Quintic Hermite   : \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, sotaylor);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"2nd order Taylor  : \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    }\n\n    if (totaylor.size() > 0)\n    {\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, totaylor);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"3rd order Taylor  : \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    q  = boost::math::statistics::simple_ordinary_least_squares_with_R_squared(r, septic_hermite);\n    BOOST_ASSERT(std::get<1>(q) < 0);\n    std::cout << \"Septic Hermite    : \" << std::get<0>(q) << \" - \" << std::abs(std::get<1>(q)) << \"r, R^2 = \" << std::get<2>(q) << \"\\n\";\n\n    }\n\n}\n", "meta": {"hexsha": "a033f8170814b4402845bed8b4b5481a00b31365", "size": 6583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/daubechies_wavelets/regress_daubechies_accuracy.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/regress_daubechies_accuracy.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "example/daubechies_wavelets/regress_daubechies_accuracy.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 42.4709677419, "max_line_length": 136, "alphanum_fraction": 0.5690414705, "num_tokens": 2144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6311807364549437}}
{"text": "/**\r\ncnt.cpp\r\nStores all relevant information for a carbon nanotube\r\n*/\r\n\r\n#include <iostream>\r\n#include <numeric>\r\n#include <armadillo>\r\n#include <complex>\r\n#include <stdexcept>\r\n\r\n#include \"constants.h\"\r\n#include \"cnt.h\"\r\n#include \"../helper/progress.hpp\"\r\n\r\nvoid cnt::get_parameters()\r\n{\r\n  // graphen unit vectors and reciprocal lattice vectors\r\n  _a1 = arma::vec({_a_l*std::sqrt(3.0)/2.0, +_a_l/2.0});\r\n  _a2 = arma::vec({_a_l*std::sqrt(3.0)/2.0, -_a_l/2.0});\r\n  _b1 = arma::vec({1.0/sqrt(3.0)*2.0*constants::pi/_a_l, +2.0*constants::pi/_a_l});\r\n  _b2 = arma::vec({1.0/sqrt(3.0)*2.0*constants::pi/_a_l, -2.0*constants::pi/_a_l});\r\n\r\n  // carbon-carbon translation vector\r\n  _aCC_vec = 1.0/3.0*(_a1+_a2);\r\n\r\n  // cnt chirality vector and its length\r\n\t_ch_vec = double(_n) * _a1 + double(_m) * _a2;\r\n\t_ch_len = arma::norm(_ch_vec,2);\r\n\r\n  // cnt radius\r\n  _radius = _ch_len/2.0/constants::pi;\r\n\r\n  // calculate cnt t_vector\r\n  int dR = std::gcd(2*_n+_m,_n+2*_m);\r\n\t_t1 = +(2*_m+_n)/dR;\r\n\t_t2 = -(2*_n+_m)/dR;\r\n  _t_vec = double(_t1)*_a1 + double(_t2)*_a2;\r\n\r\n  // number of hexagons in cnt unit cells which is equal to number of carbon atoms divided by half\r\n  _Nu = 2*(std::pow(_n,2)+std::pow(_m,2)+_n*_m)/dR;\r\n\r\n\r\n  // rotate basis vectors so that ch_vec is along the x_axis and t_vec is along y_axis\r\n\tdouble cos_theta = _ch_vec(0)/arma::norm(_ch_vec);\r\n\tdouble sin_theta = _ch_vec(1)/arma::norm(_ch_vec);\r\n\tarma::mat rot = {{+cos_theta, +sin_theta},\r\n                   {-sin_theta, +cos_theta}}; // rotation matrix\r\n\r\n\t_ch_vec = rot*_ch_vec;\r\n\t_t_vec = rot*_t_vec;\r\n\t_a1 = rot*_a1;\r\n\t_a2 = rot*_a2;\r\n\t_b1 = rot*_b1;\r\n\t_b2 = rot*_b2;\r\n\t_aCC_vec = rot*_aCC_vec;\r\n\r\n  \t//make 3d t_vec where the cnt axis is parallel to y-axis\r\n\t_t_vec_3d = arma::vec(3,arma::fill::zeros);\r\n\t_t_vec_3d(1) = _t_vec(1);\r\n\r\n\r\n  std::cout << \"\\n...graphene unit cell vectors:\\n\";\r\n  _a1.print(\"a1:\");\r\n  _a2.print(\"a2:\");\r\n\r\n  std::cout << \"\\n...graphene reciprocal lattice vectors:\\n\";\r\n  _b1.print(\"b1:\");\r\n  _b2.print(\"b2:\");\r\n\r\n  std::cout << \"\\n...vector connecting basis carbon atoms:\\n\";\r\n  _aCC_vec.print(\"aCC vector:\");\r\n\r\n  _ch_vec.print(\"chirality vector:\");\r\n  std::cout << \"ch_vec length:\\n   \" << _ch_len << std::endl;\r\n\r\n  _t_vec.print(\"t_vec:\");\r\n  _t_vec_3d.print(\"3d t_vec:\");\r\n\r\n\r\n\t// calculate reciprocal lattice of CNT\r\n\t_K1 = (-double(_t2)*_b1 + double(_t1)*_b2)/(double(_Nu));\r\n\t_K2 = (double(_m)*_b1-double(_n)*_b2)/(double(_Nu));\r\n  _K2_normed = arma::normalise(_K2);\r\n  _nk_K1 = _number_of_cnt_unit_cells;\r\n\t_dk_l = _K2/(double(_nk_K1));\r\n\r\n  std::cout << \"\\n...cnt reciprocal lattice vectors:\\n\";\r\n  _K1.print(\"K1:\");\r\n  _K2.print(\"K2:\");\r\n\r\n\t// calculate K2-extended representation parameters\r\n  {\r\n    double p_min = (1./double(_t1)+1./double(_n))/(double(_m)/double(_n)-double(_t2)/double(_t1));\r\n    double p_max = (1./double(_t1)+double(_Nu)/double(_n))/(double(_m)/double(_n)-double(_t2)/double(_t1));\r\n\r\n    bool found = false;\r\n\r\n    for (int p=std::ceil(p_min); p<std::ceil(p_max); p++)\r\n    {\r\n      if (((1+_t2*p) % _t1) == 0)\r\n      {\r\n        int q = (1+_t2*p)/_t1;\r\n        _M = _m*p - _n*q;\r\n        _Q = std::gcd(_Nu,_M);\r\n        std::cout << \"\\n...K2-extended representation parameters:\\n M: \" << _M << \" ,Q: \" << _Q << \"\\n\";\r\n        found = true;\r\n        break;\r\n      }\r\n    }\r\n    if (not found)\r\n    {\r\n      std::cout << \"Failed to calculate p and q for K2-extended representation .... investigate! .... aborting the simulation!!!\\n\";\r\n    }\r\n  }\r\n\r\n}\r\n\r\n// calculates position of atoms and reciprocal lattice vectors\r\nvoid cnt::get_atom_coordinates()\r\n{\r\n\r\n\t// calculate positions of atoms in the cnt unit cell\r\n\t_pos_a = arma::mat(_Nu,2,arma::fill::zeros);\r\n\t_pos_b = arma::mat(_Nu,2,arma::fill::zeros);\r\n\r\n\tint k = 0;\r\n\r\n\tfor (int i=0; i<=_t1+_n; i++)\r\n\t{\r\n\t\tfor (int j=_t2; j<=_m; j++)\r\n\t\t{\r\n\t\t\tbool flag1 = double(_t2*i)/(double)_t1 <= double(j);\r\n\t\t\tbool flag2 = double(_m*i)/(double)_n >= double(j);\r\n\t\t\tbool flag3 = double(_t2*(i-_n))/double(_t1) > double(j-_m);\r\n\t\t\tbool flag4 = double(_m*(i-_t1))/double(_n) < double(j-_t2);\r\n\r\n\t\t\tif(flag1 && flag2 && flag3 && flag4)\r\n\t\t\t{\r\n        _pos_a.row(k) = double(i)*_a1.t() + double(j)*_a2.t();\r\n        _pos_b.row(k) = _pos_a.row(k) + _aCC_vec.t();\r\n\r\n\t\t\t\tif(_pos_a(k,0) > _ch_vec(0))\r\n          _pos_a(k,0) -= _ch_vec(0);\r\n\t\t\t\tif(_pos_a(k,0) < 0.0)\r\n          _pos_a(k,0) += _ch_vec(0);\r\n\t\t\t\tif(_pos_a(k,1) > _ch_vec(1))\r\n          _pos_a(k,1) -= _ch_vec(1);\r\n\t\t\t\tif(_pos_a(k,1) < 0.0)\r\n          _pos_a(k,1) += _ch_vec(1);\r\n\r\n\t\t\t\tif(_pos_b(k,0) > _ch_vec(0))\r\n          _pos_b(k,0) -= _ch_vec(0);\r\n\t\t\t\tif(_pos_b(k,0) < 0.0)\r\n          _pos_b(k,0) += _ch_vec(0);\r\n\t\t\t\tif(_pos_b(k,1) > _ch_vec(1))\r\n          _pos_b(k,1) -= _ch_vec(1);\r\n\t\t\t\tif(_pos_b(k,1) < 0.0)\r\n          _pos_b(k,1) += _ch_vec(1);\r\n\r\n\t\t\t\tk++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n  std::cout << \"\\n...atom coordinates:\\n\";\r\n  _pos_a.print(\"pos_a:\");\r\n  _pos_b.print(\"pos_b:\");\r\n\r\n\tif (k != _Nu)\r\n\t{\r\n\t\tstd::cout << \"error in finding position of atoms in cnt unit cell!!!\" << std::endl;\r\n\t\tstd::cout << \"Nu = \" << _Nu << \"  ,  k = \" << k << std::endl;\r\n\t\texit(1);\r\n\t}\r\n\r\n\t// put position of all atoms in a single variable in 2d space(unrolled graphene sheet)\r\n\t_pos_2d = arma::mat(2*_Nu,2,arma::fill::zeros);\r\n  _pos_2d.rows(0,_Nu-1) = _pos_a;\r\n  _pos_2d.rows(_Nu,2*_Nu-1) = _pos_b;\r\n\r\n\t// calculate position of all atoms in the 3d space (rolled graphene sheet)\r\n\t_pos_3d = arma::mat(2*_Nu,3,arma::fill::zeros);\r\n\tfor (unsigned int i=0; i<_pos_3d.n_rows; i++)\r\n\t{\r\n\t\t_pos_3d(i,0) = _radius*cos(_pos_2d(i,0)/_radius);\r\n\t\t_pos_3d(i,1) = _pos_2d(i,1);\r\n\t\t_pos_3d(i,2) = _radius*sin(_pos_2d(i,0)/_radius);\r\n\t}\r\n\r\n\t// save coordinates of atoms in 2d space\r\n  std::string filename = _directory.path() / \"pos_2d.dat\";\r\n  _pos_2d.save(filename, arma::arma_ascii);\r\n\r\n  // save coordinates of atoms in 3d space\r\n  filename = _directory.path() / \"pos_3d.dat\";\r\n  _pos_3d.save(filename, arma::arma_ascii);\r\n\r\n  // put position of all graphene unit cells in 2d (unrolled graphene sheet) and 3d space (rolled graphene sheet)\r\n\t_pos_u_2d = _pos_a;\r\n\t_pos_u_3d = arma::mat(_Nu,3,arma::fill::zeros);\r\n\tfor (unsigned int i=0; i<_pos_u_3d.n_rows; i++)\r\n\t{\r\n\t\t_pos_u_3d(i,0) = _radius*cos(_pos_u_2d(i,0)/_radius);\r\n\t\t_pos_u_3d(i,1) = _pos_u_2d(i,1);\r\n\t\t_pos_u_3d(i,2) = _radius*sin(_pos_u_2d(i,0)/_radius);\r\n\t}\r\n\r\n}\r\n\r\n// calculate electron energy dispersions in the K1-extended representation using full unit cell (2*Nu atoms)\r\nvoid cnt::electron_full_unit_cell()\r\n{\r\n\r\n\t// make the list of 1st nearest neighbor atoms\r\n\tarma::umat nn_list(2*_Nu,3,arma::fill::zeros); // contains index of the nearest neighbor atom\r\n\tarma::imat nn_tvec_index(2*_Nu,3,arma::fill::zeros); // contains the index of the cnt unit cell that the nearest neigbor atom is in.\r\n\tfor (unsigned int i=0; i<_pos_3d.n_rows; i++)\r\n\t{\r\n\t\tint k=0;\r\n\t\tfor (unsigned int j=0; j<_pos_3d.n_rows; j++)\r\n\t\t{\r\n\t\t\tfor (int l=-1; l<=1; l++)\r\n\t\t\t{\r\n        double dR = arma::norm(_pos_3d.row(i)-_pos_3d.row(j)+double(l)*_t_vec_3d.t());\r\n\t\t\t\tif ( (i!=j) && (dR<(1.4*_a_cc)) )\r\n\t\t\t\t{\r\n\t\t\t\t\tnn_list(i,k) = j;\r\n\t\t\t\t\tnn_tvec_index(i,k) = l;\r\n\t\t\t\t\tk++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n    if (k != 3)\r\n    {\r\n      std::cout << \"error: nearest neighbors partially found!!!\\n\";\r\n      std::exit(1);\r\n    }\r\n\t}\r\n\r\n\tarma::cx_mat H(2*_Nu, 2*_Nu, arma::fill::zeros);\r\n\tarma::cx_mat S(2*_Nu, 2*_Nu, arma::fill::zeros);\r\n  arma::vec E;\r\n  arma::cx_mat C;\r\n\r\n\tint NK = _nk_K1;\r\n\r\n\tarma::mat el_energy_full(2*_Nu, NK, arma::fill::zeros);\r\n\tarma::cx_cube el_psi_full(2*_Nu, 2*_Nu, NK, arma::fill::zeros);\r\n\r\n\tdouble t_len = arma::norm(_t_vec_3d);\r\n\r\n\tfor (int n=0; n<NK; n++)\r\n\t{\r\n\t\tdouble wave_vec = double(n-_nk_K1/2)*arma::norm(_dk_l);\r\n\r\n\t\tH.zeros();\r\n\t\tS.zeros();\r\n\r\n\t\tfor (int i=0; i<2*_Nu; i++)\r\n\t\t{\r\n\t\t\tH(i,i) = std::complex<double>(_e2p,0.e0);\r\n\t\t\tfor (int k=0; k<3; k++)\r\n\t\t\t{\r\n\t\t\t\tint j = nn_list(i,k);\r\n\t\t\t\tint l = nn_tvec_index(i,k);\r\n\r\n\t\t\t\tH(i,j) += arma::cx_double(_t0,0.e0)*exp(arma::cx_double(0.0,wave_vec*double(l)*t_len));\r\n\t\t\t\tS(i,j) += arma::cx_double(_s0,0.e0)*exp(arma::cx_double(0.0,wave_vec*double(l)*t_len));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tarma::eig_sym(E, C, H);\r\n\r\n\t\t// fix the phase of the eigen vectors\r\n\t\tfor (unsigned int i=0; i<C.n_cols; i++)\r\n\t\t{\r\n\t\t\tarma::cx_double phi = std::conj(C(0,i))/std::abs(C(0,i));\r\n\t\t\tfor (unsigned int j=0; j<C.n_rows; j++)\r\n\t\t\t{\r\n\t\t\t\tC(j,i) *= phi;\r\n\t\t\t}\r\n\t\t}\r\n\r\n    el_energy_full.col(n) = E;\r\n    el_psi_full.slice(n) = C;\r\n\r\n\t}\r\n\r\n  // save electron energy bands using full Brillouine zone\r\n  std::cout << \"saved electron energy dispersion in K1-extended representation\\n\";\r\n  std::string filename = _directory.path() / \"el_energy_full.dat\";\r\n  el_energy_full.save(filename, arma::arma_ascii);\r\n\r\n  // // save electron wavefunctions using full Brillouine zone\r\n  // filename = _directory.path()/\"el_psi_full.dat\";\r\n  // el_psi_full.save(filename, arma::arma_ascii);\r\n\r\n}\r\n\r\n// calculate electron dispersion energies for an input range of ik and mu\r\ncnt::el_energy_struct cnt::electron_energy(const std::array<int,2>& ik_range, const std::array<int,2>& mu_range, const std::string& name)\r\n{\r\n  int number_of_bands = 2;\r\n  int number_of_atoms_in_graphene_unit_cell = number_of_bands;\r\n\r\n  int nk = ik_range[1] - ik_range[0];\r\n  int n_mu = mu_range[1] - mu_range[0];\r\n\r\n\r\n  arma::cube energy(number_of_bands, nk, n_mu, arma::fill::zeros);\r\n  arma::field<arma::cx_cube> wavefunc(n_mu); // this pretty weird order is chosen so than we can select each cutting line easier and more efficiently\r\n  wavefunc.for_each([&](arma::cx_cube& c){c.zeros(number_of_atoms_in_graphene_unit_cell, number_of_bands, nk);}); // this pretty weird order is chosen so than we can select each cutting line easier and more efficiently\r\n\r\n  const std::complex<double> i1(0,1);\r\n  \r\n  const int ic = 1;\r\n  const int iv = 0;\r\n  \r\n  const int iA = 0;\r\n  const int iB = 1;\r\n\r\n  for (int mu=mu_range[0]; mu<mu_range[1]; mu++)\r\n  {\r\n    for (int ik=ik_range[0]; ik<ik_range[1]; ik++)\r\n    {\r\n      arma::vec k_vec = double(mu)*_K1 + double(ik)*_dk_l;\r\n      std::complex<double> fk = std::exp(std::complex<double>(0,arma::dot(k_vec,(_a1+_a2)/3.))) + \\\r\n                                std::exp(std::complex<double>(0,arma::dot(k_vec,(_a1-2.*_a2)/3.))) + \\\r\n                                std::exp(std::complex<double>(0,arma::dot(k_vec,(_a2-2.*_a1)/3.)));\r\n      \r\n      energy(ic,ik-ik_range[0],mu-mu_range[0]) = +_t0*std::abs(fk);\r\n      energy(iv,ik-ik_range[0],mu-mu_range[0]) = -_t0*std::abs(fk);\r\n\r\n      (wavefunc(mu-mu_range[0]))(iA,ic,ik-ik_range[0]) = +1./std::sqrt(2.); // this pretty weird order is chosen so than we can select each cutting line easier and more efficiently\r\n      (wavefunc(mu-mu_range[0]))(iA,iv,ik-ik_range[0]) = +1./std::sqrt(2.); // this pretty weird order is chosen so than we can select each cutting line easier and more efficiently\r\n      (wavefunc(mu-mu_range[0]))(iB,ic,ik-ik_range[0]) = -1./std::sqrt(2.)*std::conj(fk)/std::abs(fk); // this pretty weird order is chosen so than we can select each cutting line easier and more efficiently\r\n      (wavefunc(mu-mu_range[0]))(iB,iv,ik-ik_range[0]) = +1./std::sqrt(2.)*std::conj(fk)/std::abs(fk); // this pretty weird order is chosen so than we can select each cutting line easier and more efficiently\r\n    }\r\n  }\r\n\r\n  // save electron energy bands using full Brillouine zone\r\n  std::string filename = _directory.path() / (name +\".el_energy.dat\");\r\n  energy.save(filename,arma::arma_ascii);\r\n\r\n  std::cout << \"\\n...calculated \" + name + \" electron dispersion\\n\";\r\n\r\n  el_energy_struct energy_s;\r\n  energy_s.name = name;\r\n  energy_s.energy = energy;\r\n  energy_s.wavefunc = wavefunc;\r\n  energy_s.ik_range = ik_range;\r\n  energy_s.mu_range = mu_range;\r\n  energy_s.nk = nk;\r\n  energy_s.n_mu = n_mu;\r\n  energy_s.no_of_atoms = number_of_atoms_in_graphene_unit_cell;\r\n  energy_s.no_of_bands = number_of_bands;\r\n\r\n  return energy_s;\r\n}\r\n\r\nvoid cnt::find_valleys(const cnt::el_energy_struct& elec_struct)\r\n{\r\n\r\n\r\n  // get the indicies of valleys\r\n  std::vector<std::array<unsigned int,2>> ik_valley_idx;\r\n\r\n  int iC = 1;\r\n  for (int ik_idx=0; ik_idx<elec_struct.nk; ik_idx++)\r\n  {\r\n    for (int i_mu_idx=0; i_mu_idx<elec_struct.n_mu; i_mu_idx++)\r\n    {\r\n      int ik_idx_p1 = ik_idx + 1;\r\n      int ik_idx_m1 = ik_idx - 1;\r\n      while(ik_idx_p1 >= elec_struct.nk)\r\n      {\r\n        ik_idx_p1 -= elec_struct.nk;\r\n      }\r\n      while(ik_idx_m1 < 0)\r\n      {\r\n        ik_idx_m1 += elec_struct.nk;\r\n      }\r\n\r\n      if ((elec_struct.energy(iC,ik_idx,i_mu_idx) < elec_struct.energy(iC,ik_idx_m1,i_mu_idx)) \\\r\n            and (elec_struct.energy(iC,ik_idx,i_mu_idx) < elec_struct.energy(iC,ik_idx_p1,i_mu_idx)))\r\n      {\r\n        ik_valley_idx.push_back({(unsigned int)ik_idx, (unsigned int)i_mu_idx});\r\n      }\r\n\r\n    }\r\n  }\r\n\r\n  // sort valleys in order of their\r\n  std::sort(ik_valley_idx.begin(),ik_valley_idx.end(), [&](const auto& s1, const auto& s2) {\r\n                                    return elec_struct.energy(1,s1[0],s1[1]) < elec_struct.energy(1,s2[0],s2[1]);\r\n                                  });\r\n\r\n  // put them in a vector with each element containing the two equivalent valleys\r\n  for (unsigned int i=0; i<ik_valley_idx.size()/2; i++)\r\n  {\r\n    std::array<std::array<unsigned int, 2>, 2> valley = {ik_valley_idx.at(2*i), ik_valley_idx.at(2*i+1)};\r\n    _valleys_K2.push_back(valley);\r\n  }\r\n\r\n  std::cout << \"\\n...found and sorted indices of valleys:\\n\";\r\n  for (const auto& valleys: _valleys_K2)\r\n  {\r\n    auto v1 = valleys.at(0);\r\n    auto v2 = valleys.at(1);\r\n    std::cout << \"[\" << v1[0] << \",\" << v1[1] << \"] , [\" << v2[0] << \",\" << v2[1] << \"]\\n\";\r\n  }\r\n\r\n  std::cout << \"number of valleys: \" << _valleys_K2.size() << std::endl;\r\n\r\n}\r\n\r\n// find ik values that are energetically relevant around the bottom of the valley\r\nvoid cnt::find_relev_ik_range(double delta_energy, const cnt::el_energy_struct& elec_struct)\r\n{\r\n  std::vector<std::vector<std::array<int,2>>> relev_ik_range(2);\r\n\r\n  // first get ik for relevant states in the first valley\r\n  int i_valley = 0;\r\n  int ik_bottom = _valleys_K2[_i_sub][i_valley][0]+elec_struct.ik_range[0];\r\n  int mu_bottom = _valleys_K2[_i_sub][i_valley][1]+elec_struct.mu_range[0];\r\n  int iC = 1;\r\n  double max_energy = elec_struct.energy(iC, ik_bottom-elec_struct.ik_range[0], mu_bottom-elec_struct.mu_range[0]) + delta_energy;\r\n\r\n  relev_ik_range.at(i_valley).push_back({ik_bottom,mu_bottom});\r\n  bool in_range = true;\r\n  int count = 0;\r\n  while (in_range)\r\n  {\r\n    in_range = false;\r\n    count ++;\r\n    int ik = ik_bottom + count;\r\n    while(ik >= elec_struct.ik_range[1])\r\n    {\r\n      ik -= elec_struct.nk;\r\n    }\r\n    if (elec_struct.energy(iC, ik-elec_struct.ik_range[0], mu_bottom-elec_struct.mu_range[0]) < max_energy)\r\n    {\r\n      relev_ik_range.at(i_valley).push_back({ik,mu_bottom});\r\n      in_range = true;\r\n    }\r\n\r\n    ik = ik_bottom - count;\r\n    while(ik < elec_struct.ik_range[0])\r\n    {\r\n      ik += elec_struct.nk;\r\n    }\r\n    if (elec_struct.energy(iC, ik-elec_struct.ik_range[0], mu_bottom-elec_struct.mu_range[0]) < max_energy)\r\n    {\r\n      // std::array<int,2> relev_state = {ik,mu_bottom};\r\n      relev_ik_range.at(i_valley).insert(relev_ik_range.at(i_valley).begin(), {ik,mu_bottom});\r\n      in_range = true;\r\n    }\r\n  }\r\n\r\n  // do the same thing for the second valley\r\n  i_valley = 1;\r\n  ik_bottom = _valleys_K2[_i_sub][i_valley][0]+elec_struct.ik_range[0];\r\n  mu_bottom = _valleys_K2[_i_sub][i_valley][1]+elec_struct.mu_range[0];\r\n  max_energy = elec_struct.energy(iC, ik_bottom-elec_struct.ik_range[0], mu_bottom-elec_struct.mu_range[0]) + delta_energy;\r\n\r\n  relev_ik_range.at(i_valley).push_back({ik_bottom,mu_bottom});\r\n  in_range = true;\r\n  count = 0;\r\n  while (in_range)\r\n  {\r\n    in_range = false;\r\n    count ++;\r\n    int ik = ik_bottom + count;\r\n    while(ik >= elec_struct.ik_range[1])\r\n    {\r\n      ik -= elec_struct.nk;\r\n    }\r\n    if (elec_struct.energy(iC, ik-elec_struct.ik_range[0], mu_bottom-elec_struct.mu_range[0]) < max_energy)\r\n    {\r\n      relev_ik_range.at(i_valley).push_back({ik,mu_bottom});\r\n      in_range = true;\r\n    }\r\n\r\n    ik = ik_bottom - count;\r\n    while(ik < elec_struct.ik_range[0])\r\n    {\r\n      ik += elec_struct.nk;\r\n    }\r\n    if (elec_struct.energy(iC, ik-elec_struct.ik_range[0], mu_bottom-elec_struct.mu_range[0]) < max_energy)\r\n    {\r\n      relev_ik_range.at(i_valley).insert(relev_ik_range.at(i_valley).begin(), {ik,mu_bottom});\r\n      in_range = true;\r\n    }\r\n  }\r\n\r\n\r\n  std::cout << \"\\n...ik for relevant states calculated:\\n\";\r\n  std::cout << \"relev_ik_range has length of \" << relev_ik_range[0].size() << std::endl;\r\n\r\n  // i_valley = 0;\r\n  // std::cout << \"valley: \" << i_valley << \"\\n\";\r\n  // for (const auto& state: relev_ik_range.at(i_valley))\r\n  // {\r\n  //   std::cout << \"   [\" << state.at(0) << \",\" << state.at(1) << \"]\\n\";\r\n  // }\r\n\r\n  // i_valley = 1;\r\n  // std::cout << \"\\nvalley: \" << i_valley << \"\\n\";\r\n  // for (const auto& state: relev_ik_range.at(i_valley))\r\n  // {\r\n  //   std::cout << \"   [\" << state.at(0) << \",\" << state.at(1) << \"]\\n\";\r\n  // }\r\n\r\n  _relev_ik_range = relev_ik_range;\r\n\r\n}\r\n\r\n// fourier transformation of the coulomb interaction a.k.a v(q)\r\ncnt::vq_struct cnt::calculate_vq(const std::array<int,2> iq_range, const std::array<int,2> mu_range, unsigned int no_of_cnt_unit_cells)\r\n{\r\n  // primary checks for function input\r\n  int nq = iq_range.at(1) - iq_range.at(0);\r\n  if (nq <= 0) {\r\n    throw \"Incorrect range for iq!\";\r\n  }\r\n  int n_mu = mu_range.at(1) - mu_range.at(0);\r\n  if (n_mu <= 0) {\r\n    throw \"Incorrect range for mu_q!\";\r\n  }\r\n  if (no_of_cnt_unit_cells % 2 == 0)  no_of_cnt_unit_cells ++;\r\n\r\n  // calculate distances between atoms in a warped cnt unit cell.\r\n\tarma::mat pos_aa = arma::mat(_Nu,2,arma::fill::zeros);\r\n\tarma::mat pos_ab = arma::mat(_Nu,2,arma::fill::zeros);\r\n\tarma::mat pos_ba = arma::mat(_Nu,2,arma::fill::zeros);\r\n  arma::mat pos_bb = arma::mat(_Nu,2,arma::fill::zeros);\r\n\r\n\tfor (int i=0; i<_Nu; i++)\r\n\t{\r\n    pos_aa.row(i) = _pos_a.row(i)-_pos_a.row(0);\r\n    pos_ab.row(i) = _pos_a.row(i)-_pos_b.row(0);\r\n    pos_ba.row(i) = _pos_b.row(i)-_pos_a.row(0);\r\n    pos_bb.row(i) = _pos_b.row(i)-_pos_b.row(0);\r\n\r\n\t\tif(pos_aa(i,0) > _ch_vec(0)/2)\r\n      pos_aa(i,0) -= _ch_vec(0);\r\n\t\tif(pos_ab(i,0) > _ch_vec(0)/2)\r\n      pos_ab(i,0) -= _ch_vec(0);\r\n\t\tif(pos_ba(i,0) > _ch_vec(0)/2)\r\n      pos_ba(i,0) -= _ch_vec(0);\r\n\t\tif(pos_bb(i,0) > _ch_vec(0)/2)\r\n      pos_bb(i,0) -= _ch_vec(0);\r\n\t}\r\n\r\n  arma::cube rel_pos(_Nu*no_of_cnt_unit_cells,2,4,arma::fill::zeros);\r\n  for (int i=-std::floor(double(no_of_cnt_unit_cells)/2.); i<=std::floor(double(no_of_cnt_unit_cells)/2.); i++)\r\n  {\r\n    int idx = (i+std::floor(double(no_of_cnt_unit_cells)/2.))*_Nu;\r\n    for (int j=0; j<_Nu; j++)\r\n    {\r\n      rel_pos.slice(0).row(idx+j) = pos_aa.row(j)+(i*_t_vec.t());\r\n      rel_pos.slice(1).row(idx+j) = pos_ab.row(j)+(i*_t_vec.t());\r\n      rel_pos.slice(2).row(idx+j) = pos_ba.row(j)+(i*_t_vec.t());\r\n      rel_pos.slice(3).row(idx+j) = pos_bb.row(j)+(i*_t_vec.t());\r\n    }\r\n  }\r\n\r\n  // calculate vq\r\n  arma::cx_cube vq(nq,n_mu,4,arma::fill::zeros);\r\n  arma::vec q_vec(nq,arma::fill::zeros);\r\n\r\n  arma::vec q(2,arma::fill::zeros);\r\n  const double coeff = std::pow(4.*constants::pi*constants::eps0*_Upp/constants::q0/constants::q0,2);\r\n  const std::complex<double> i1(0.,1.);\r\n  auto Uhno = [&](const arma::mat& R){\r\n    return std::exp(i1*arma::dot(q,R))*_Upp/std::sqrt(coeff*(std::pow(R(0),2)+std::pow(R(1),2))+1);\r\n  };\r\n\r\n  progress_bar prog(nq, \"vq\");\r\n\r\n  for (int iq=iq_range[0]; iq<iq_range[1]; iq++)\r\n  {\r\n    int iq_idx = iq-iq_range[0];\r\n\r\n    prog.step();\r\n\r\n    q_vec(iq_idx) = iq*arma::norm(_dk_l,2);\r\n    for (int mu=mu_range[0]; mu<mu_range[1]; mu++)\r\n    {\r\n      int mu_idx = mu - mu_range[0];\r\n      q = iq*_dk_l + mu*_K1;\r\n      // std::cout << \"after addition!\\n\";\r\n      for (int i=0; i<4; i++)\r\n      {\r\n        for (unsigned int k=0; k<_Nu*no_of_cnt_unit_cells; k++)\r\n        {\r\n          vq(iq_idx,mu_idx,i) += Uhno(rel_pos.slice(i).row(k));\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  vq = vq/(2*_Nu*no_of_cnt_unit_cells);\r\n\r\n  std::cout << \"\\n...calculated vq\\n\";\r\n\r\n  std::cout << \"saved real part of vq\\n\";\r\n  arma::cube vq_real = arma::real(vq);\r\n  std::string filename = _directory.path()/\"vq_real.dat\";\r\n  vq_real.save(filename, arma::arma_ascii);\r\n\r\n  std::cout << \"saved imaginary part of vq\\n\";\r\n  arma::cube vq_imag = arma::imag(vq);\r\n  filename = _directory.path()/\"vq_imag.dat\";\r\n  vq_imag.save(filename, arma::arma_ascii);\r\n\r\n  std::cout << \"saved q_vector for vq\\n\";\r\n  filename = _directory.path()/\"vq_q_vec.dat\";\r\n  q_vec.save(filename, arma::arma_ascii);\r\n\r\n  // make the vq_struct that is to be returned\r\n  vq_struct vq_s;\r\n  vq_s.data = vq;\r\n  vq_s.iq_range = iq_range;\r\n  vq_s.mu_range = mu_range;\r\n  vq_s.nq = nq;\r\n  vq_s.n_mu = n_mu;\r\n\r\n  return vq_s;\r\n}\r\n\r\n// polarization of electronic states a.k.a PI(q)\r\ncnt::PI_struct cnt::calculate_polarization(const std::array<int,2> iq_range, const std::array<int,2> mu_range, const cnt::el_energy_struct& elec_struct)\r\n{\r\n  // primary checks for function input\r\n  int nq = iq_range.at(1) - iq_range.at(0);\r\n  if (nq <= 0) {\r\n    throw \"Incorrect range for iq in calculate_polarization!\";\r\n  }\r\n  int n_mu = mu_range.at(1) - mu_range.at(0);\r\n  if (n_mu <= 0) {\r\n    throw \"Incorrect range for mu_q in calculate_polarization!\";\r\n  }\r\n\r\n  int ikq, mu_kq;\r\n  int ik, mu_k;\r\n  int iq, mu_q;\r\n  // lambda function to wrap iq+ik and mu_k+mu_q inside the K2-extended brillouine zone\r\n  auto get_kq = [&](){\r\n    mu_kq = mu_k+mu_q;\r\n    ikq = ik+iq;\r\n    while (mu_kq >= elec_struct.mu_range[1]) {\r\n      mu_kq -= elec_struct.n_mu;\r\n      ikq += _nk_K1*_M;\r\n    }\r\n    while (mu_kq < elec_struct.mu_range[0]) {\r\n      mu_kq += elec_struct.n_mu;\r\n      ikq -= _nk_K1*_M;\r\n    }\r\n    while (ikq >= elec_struct.ik_range[1]){\r\n      ikq -= elec_struct.nk;\r\n    }\r\n    while (ikq < elec_struct.ik_range[0]){\r\n      ikq += elec_struct.nk;\r\n    }\r\n  };\r\n\r\n  arma::mat PI(nq,n_mu,arma::fill::zeros);\r\n  arma::vec q_vec(nq,arma::fill::zeros);\r\n\r\n  const int iv = 0;\r\n  const int ic = 1;\r\n\r\n  progress_bar prog(nq, \"calculate polarization\");\r\n\r\n  int iq_idx, mu_q_idx;\r\n  int ik_idx, mu_k_idx;\r\n  int i_kq_idx, mu_kq_idx;\r\n  for (iq=iq_range[0]; iq<iq_range[1]; iq++)\r\n  {\r\n    iq_idx = iq - iq_range[0];\r\n    q_vec(iq_idx) = iq*arma::norm(_dk_l);\r\n\r\n    prog.step(iq_idx);\r\n\r\n    for (mu_q=mu_range[0]; mu_q<mu_range[1]; mu_q++)\r\n    {\r\n      mu_q_idx = mu_q - mu_range[0];\r\n      for (ik=elec_struct.ik_range[0]; ik<elec_struct.ik_range[1]; ik++)\r\n      {\r\n        ik_idx = ik - elec_struct.ik_range[0];\r\n        for (mu_k=elec_struct.mu_range[0]; mu_k<elec_struct.mu_range[1]; mu_k++)\r\n        {\r\n          mu_k_idx = mu_k - elec_struct.mu_range[0];\r\n          get_kq();\r\n          mu_kq_idx = mu_kq - elec_struct.mu_range[0];\r\n          i_kq_idx = ikq - elec_struct.ik_range[0];\r\n\r\n          PI(iq_idx,mu_q_idx) += std::pow(std::abs(arma::dot(arma::conj(elec_struct.wavefunc(mu_k_idx).slice(ik_idx).col(iv)),\\\r\n                                                             elec_struct.wavefunc(mu_kq_idx).slice(i_kq_idx).col(ic))),2)/ \\\r\n                                          (elec_struct.energy(ic,i_kq_idx,mu_kq_idx)-elec_struct.energy(iv,ik_idx,mu_k_idx)) + \\\r\n                                 std::pow(std::abs(arma::dot(arma::conj(elec_struct.wavefunc(mu_k_idx).slice(ik_idx).col(ic)), \\\r\n                                                             elec_struct.wavefunc(mu_kq_idx).slice(i_kq_idx).col(iv))),2)/ \\\r\n                                          (elec_struct.energy(ic,ik_idx,mu_k_idx)-elec_struct.energy(iv,i_kq_idx,mu_kq_idx));\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  PI = 2*PI;\r\n\r\n  std::cout << \"\\n...calculated polarization: PI(q)\\n\";\r\n\r\n  std::cout << \"saved PI\\n\";\r\n  std::string filename = _directory.path()/\"PI.dat\";\r\n  PI.save(filename, arma::arma_ascii);\r\n\r\n  std::cout << \"saved q_vector for PI\\n\";\r\n  filename = _directory.path()/\"PI_q_vec.dat\";\r\n  q_vec.save(filename, arma::arma_ascii);\r\n\r\n  // make the vq_struct that is to be returned\r\n  PI_struct PI_s;\r\n  PI_s.data = PI;\r\n  PI_s.iq_range = iq_range;\r\n  PI_s.mu_range = mu_range;\r\n  PI_s.nq = nq;\r\n  PI_s.n_mu = n_mu;\r\n\r\n  return PI_s;\r\n}\r\n\r\n// dielectric function a.k.a eps(q)\r\ncnt::epsilon_struct cnt::calculate_dielectric(const std::array<int,2> iq_range, const std::array<int,2> mu_range)\r\n{\r\n  // check if vq has been calculated properly before\r\n  if (not (in_range(iq_range,_vq.iq_range) and in_range(mu_range,_vq.mu_range))){\r\n    throw std::logic_error(\"You need to calculate vq with correct range before \\\r\n                            trying to calculate dielectric function\");\r\n  }\r\n  // check if PI has been calculated properly before\r\n  if (not (in_range(iq_range,_PI.iq_range) and in_range(mu_range,_PI.mu_range))){\r\n    throw std::logic_error(\"You need to calculate PI with correct range before \\\r\n                            trying to calculate dielectric function\");\r\n  }\r\n\r\n  int nq = iq_range[1] - iq_range[0];\r\n  int n_mu = mu_range[1] - mu_range[0];\r\n  arma::mat eps = arma::real(arma::mean(_vq.data,2));\r\n  eps = eps.submat(iq_range[0]-_vq.iq_range[0],mu_range[0]-_vq.mu_range[0],arma::size(nq,n_mu));\r\n  eps %= _PI.data.submat(iq_range[0]-_PI.iq_range[0],mu_range[0]-_PI.mu_range[0],arma::size(nq,n_mu));\r\n  std::cout << \"size of dielectric function matrix: \" << arma::size(eps) << std::endl;\r\n  eps += 1.;\r\n\r\n  arma::vec q_vec(nq);\r\n  for (int iq=iq_range[0]; iq<iq_range[1]; iq++)\r\n  {\r\n    int iq_idx = iq - iq_range[0];\r\n    q_vec(iq_idx) = iq*arma::norm(_dk_l);\r\n  }\r\n\r\n  std::cout << \"\\n...calculated dielectric function: epsilon(q)\\n\";\r\n\r\n  std::cout << \"saved epsilon\\n\";\r\n  std::string filename = _directory.path()/\"eps.dat\";\r\n  eps.save(filename, arma::arma_ascii);\r\n\r\n  std::cout << \"saved q_vector for epsilon\\n\";\r\n  filename = _directory.path()/\"eps_q_vec.dat\";\r\n  q_vec.save(filename, arma::arma_ascii);\r\n\r\n  epsilon_struct eps_s;\r\n  eps_s.data = eps;\r\n  eps_s.iq_range = iq_range;\r\n  eps_s.mu_range = mu_range;\r\n  eps_s.nq = nq;\r\n  eps_s.n_mu = n_mu;\r\n  return eps_s;\r\n}\r\n\r\n// calculate exciton dispersion\r\nstd::vector<cnt::exciton_struct> cnt::calculate_A_excitons(const std::array<int,2> ik_cm_range, const cnt::el_energy_struct& elec_struct) {\r\n  // some utility variables that are going to be used over and over again\r\n  int ik_c, mu_c;\r\n  int ik_v, mu_v;\r\n  int ik_cp, mu_cp;\r\n  int ik_vp, mu_vp;\r\n  int ik_c_diff, mu_c_diff;\r\n  int ik_cm, mu_cm;\r\n\r\n  std::complex<double> dir_interaction;\r\n  std::complex<double> xch_interaction;\r\n\r\n  const int iv = 0;\r\n  const int ic = 1;\r\n\r\n  const int i_valley_1 = 0;\r\n  const int i_valley_2 = 1;\r\n\r\n  // lambda function to calculate direct interaction\r\n  auto get_direct_interaction = [&](){\r\n    ik_c_diff = ik_c-ik_cp;\r\n    mu_c_diff = mu_c-mu_cp;\r\n    while(ik_c_diff < elec_struct.ik_range[0]){\r\n      ik_c_diff += elec_struct.nk;\r\n    }\r\n    while(ik_c_diff >= elec_struct.ik_range[1]){\r\n      ik_c_diff -= elec_struct.nk;\r\n    }\r\n\r\n    dir_interaction = 0;\r\n    for (int i=0; i<2; i++)\r\n    {\r\n      for (int j=0; j<2; j++)\r\n      {\r\n        dir_interaction += std::conj(elec_struct.wavefunc(mu_c -elec_struct.mu_range[0])(i,ic,ik_c -elec_struct.ik_range[0]))* \\\r\n                                     elec_struct.wavefunc(mu_v -elec_struct.mu_range[0])(j,iv,ik_v -elec_struct.ik_range[0]) * \\\r\n                                     elec_struct.wavefunc(mu_cp-elec_struct.mu_range[0])(i,ic,ik_cp-elec_struct.ik_range[0]) * \\\r\n                           std::conj(elec_struct.wavefunc(mu_vp-elec_struct.mu_range[0])(j,iv,ik_vp-elec_struct.ik_range[0]))* \\\r\n                                                          _vq.data(ik_c_diff-_vq.iq_range[0],mu_c_diff-_vq.mu_range[0],2*i+j)/ \\\r\n                                                             _eps.data(ik_c_diff-_eps.iq_range[0],mu_c_diff-_eps.mu_range[0]);\r\n      }\r\n    }\r\n    return dir_interaction;\r\n  };\r\n\r\n  // lambda function to calculate exchange interaction\r\n  auto get_exchange_interaction = [&](){\r\n    xch_interaction = 0;\r\n    for (int i=0; i<2; i++)\r\n    {\r\n      for (int j=0; j<2; j++)\r\n      {\r\n        xch_interaction += std::conj(elec_struct.wavefunc(mu_c -elec_struct.mu_range[0])(i,ic,ik_c -elec_struct.ik_range[0]))* \\\r\n                                     elec_struct.wavefunc(mu_v -elec_struct.mu_range[0])(i,iv,ik_v -elec_struct.ik_range[0]) * \\\r\n                                     elec_struct.wavefunc(mu_cp-elec_struct.mu_range[0])(j,ic,ik_cp-elec_struct.ik_range[0]) * \\\r\n                           std::conj(elec_struct.wavefunc(mu_vp-elec_struct.mu_range[0])(j,iv,ik_vp-elec_struct.ik_range[0]))* \\\r\n                                                                  _vq.data(ik_cm-_vq.iq_range[0],mu_cm-_vq.mu_range[0],2*i+j);\r\n      }\r\n    }\r\n    return xch_interaction;\r\n  };\r\n\r\n  // get ik of valence band state by taking care of wrapping around K2-extended zone\r\n  auto get_ikv = [&elec_struct](const int& ik_c, const int& ik_cm){\r\n    int ik_v = ik_c - ik_cm;\r\n    while (ik_v >= elec_struct.ik_range[1]){\r\n      ik_v -= elec_struct.nk;\r\n    }\r\n    while (ik_v < elec_struct.ik_range[0]){\r\n      ik_v += elec_struct.nk;\r\n    }\r\n    return ik_v;\r\n  };\r\n  \r\n  // get ik of conduction band state by taking care of wrapping around K2-extended zone\r\n  auto get_ikc = [&elec_struct](const int& ik_v, const int& ik_cm){\r\n    int ik_c = ik_v + ik_cm;\r\n    while (ik_c >= elec_struct.ik_range[1]){\r\n      ik_c -= elec_struct.nk;\r\n    }\r\n    while (ik_c < elec_struct.ik_range[0]){\r\n      ik_c += elec_struct.nk;\r\n    }\r\n    return ik_c;\r\n  };\r\n\r\n\r\n  int nk_cm = ik_cm_range[1] - ik_cm_range[0];\r\n  int nk_relev = int(_relev_ik_range[0].size());\r\n  int nk_c = 2*nk_relev;\r\n\r\n  arma::mat ex_energy_A1(nk_cm,nk_relev,arma::fill::zeros);\r\n  arma::mat ex_energy_A2_singlet(nk_cm,nk_relev,arma::fill::zeros);\r\n  arma::mat ex_energy_A2_triplet(nk_cm,nk_relev,arma::fill::zeros);\r\n  \r\n  arma::cx_cube ex_psi_A1(nk_c,nk_relev,nk_cm, arma::fill::zeros);\r\n  arma::cx_cube ex_psi_A2_singlet(nk_c,nk_relev,nk_cm, arma::fill::zeros);\r\n  arma::cx_cube ex_psi_A2_triplet(nk_c,nk_relev,nk_cm, arma::fill::zeros);\r\n\r\n  arma::ucube ik_idx(4, nk_c, nk_cm);\r\n\r\n  arma::cx_mat kernel_11(nk_relev,nk_relev,arma::fill::zeros);\r\n  arma::cx_mat kernel_12(nk_relev,nk_relev,arma::fill::zeros);\r\n  arma::cx_mat kernel_exchange(nk_relev,nk_relev,arma::fill::zeros);\r\n  arma::vec energy;\r\n  arma::cx_mat psi;\r\n  arma::vec k_cm_vec(nk_cm,arma::fill::zeros);\r\n\r\n  progress_bar prog(nk_cm, \"calculate ex_energy\");\r\n\r\n  // loop to calculate exciton dispersion\r\n  for (ik_cm=ik_cm_range[0]; ik_cm<ik_cm_range[1]; ik_cm++)\r\n  {\r\n    kernel_11.zeros();\r\n    kernel_12.zeros();\r\n    kernel_exchange.zeros();\r\n    mu_cm = 0;\r\n    int ik_cm_idx = ik_cm - ik_cm_range[0];\r\n    k_cm_vec(ik_cm_idx) = ik_cm*arma::norm(_dk_l);\r\n\r\n    prog.step(ik_cm_idx);\r\n\r\n\r\n    for (int ik_c_idx=0; ik_c_idx<nk_relev; ik_c_idx++)\r\n    {\r\n      ik_c = _relev_ik_range[i_valley_1][ik_c_idx][0];\r\n      mu_c = _relev_ik_range[i_valley_1][ik_c_idx][1];\r\n      ik_v = get_ikv(ik_c,ik_cm);\r\n      mu_v = mu_c;\r\n\r\n      kernel_11(ik_c_idx, ik_c_idx) += elec_struct.energy(ic,ik_c-elec_struct.ik_range[0],mu_c-elec_struct.mu_range[0]) - \\\r\n                                       elec_struct.energy(iv,ik_v-elec_struct.ik_range[0],mu_c-elec_struct.mu_range[0]);\r\n\r\n      // interaction  between valley_1 and valley_1\r\n      for (int ik_cp_idx=0; ik_cp_idx<=ik_c_idx; ik_cp_idx++)\r\n      {\r\n        ik_cp = _relev_ik_range[i_valley_1][ik_cp_idx][0];\r\n        mu_cp = _relev_ik_range[i_valley_1][ik_cp_idx][1];\r\n        ik_vp = get_ikv(ik_cp,ik_cm);\r\n        mu_vp = mu_cp;\r\n\r\n        kernel_11(ik_c_idx,ik_cp_idx) -= get_direct_interaction();\r\n        kernel_exchange(ik_c_idx,ik_cp_idx) += std::complex<double>(2,0)*get_exchange_interaction();\r\n      }\r\n\r\n      // interaction  between valley_1 and valley_2\r\n      for (int ik_vp_idx=ik_c_idx; ik_vp_idx<nk_relev; ik_vp_idx++)\r\n      {\r\n        ik_vp = _relev_ik_range[i_valley_2][ik_vp_idx][0];\r\n        mu_vp = _relev_ik_range[i_valley_2][ik_vp_idx][1];\r\n        ik_cp = get_ikc(ik_vp,ik_cm);\r\n        mu_cp = mu_vp;\r\n\r\n        kernel_12(ik_c_idx,nk_relev-1-ik_vp_idx) -= get_direct_interaction();\r\n      }\r\n    }\r\n\r\n    kernel_11 += kernel_11.t();\r\n    kernel_12 += kernel_12.t();\r\n    kernel_exchange += kernel_exchange.t();\r\n    for (int ik_c_idx=0; ik_c_idx<nk_relev; ik_c_idx++)\r\n    {\r\n      kernel_11(ik_c_idx,ik_c_idx) /= std::complex<double>(2,0);\r\n      kernel_12(ik_c_idx,ik_c_idx) /= std::complex<double>(2,0);\r\n      kernel_exchange(ik_c_idx,ik_c_idx) /= std::complex<double>(2,0);\r\n    }\r\n\r\n    arma::eig_sym(energy,psi,kernel_11-kernel_12);\r\n    ex_energy_A1.row(ik_cm_idx) = energy.t();\r\n    ex_psi_A1.slice(ik_cm_idx).head_rows(nk_relev) = (+1/std::sqrt(2.))*psi;\r\n    ex_psi_A1.slice(ik_cm_idx).tail_rows(nk_relev) = (-1/std::sqrt(2.))*psi;\r\n\r\n    // energy = arma::eig_sym(kernel_11+kernel_12);\r\n    arma::eig_sym(energy,psi,kernel_11+kernel_12);\r\n    ex_energy_A2_triplet.row(ik_cm_idx) = energy.t();\r\n    ex_psi_A2_triplet.slice(ik_cm_idx).head_rows(nk_relev) = (+1/std::sqrt(2.))*psi;\r\n    ex_psi_A2_triplet.slice(ik_cm_idx).tail_rows(nk_relev) = (+1/std::sqrt(2.))*psi;\r\n\r\n    // energy = arma::eig_sym(kernel_11+kernel_12+std::complex<double>(2,0)*kernel_exchange);\r\n    arma::eig_sym(energy,psi,kernel_11+kernel_12+std::complex<double>(2,0)*kernel_exchange);\r\n    ex_energy_A2_singlet.row(ik_cm_idx) = energy.t();\r\n    ex_psi_A2_singlet.slice(ik_cm_idx).head_rows(nk_relev) = (+1/std::sqrt(2.))*psi;\r\n    ex_psi_A2_singlet.slice(ik_cm_idx).tail_rows(nk_relev) = (+1/std::sqrt(2.))*psi;\r\n\r\n\r\n    // save the index of kc and kv states from i_valley_1\r\n    for (int ik_c_idx=0; ik_c_idx<nk_relev; ik_c_idx++)\r\n    {\r\n      ik_c = _relev_ik_range[i_valley_1][ik_c_idx][0];\r\n      mu_c = _relev_ik_range[i_valley_1][ik_c_idx][1];\r\n      ik_v = get_ikv(ik_c,ik_cm);\r\n      mu_v = mu_c;\r\n\r\n      ik_idx(0,ik_c_idx,ik_cm_idx) = ik_c-elec_struct.ik_range[0];\r\n      ik_idx(1,ik_c_idx,ik_cm_idx) = mu_c-elec_struct.mu_range[0];\r\n      ik_idx(2,ik_c_idx,ik_cm_idx) = ik_v-elec_struct.ik_range[0];\r\n      ik_idx(3,ik_c_idx,ik_cm_idx) = mu_v-elec_struct.mu_range[0];\r\n    }\r\n\r\n    // save the index of kc and kv states from i_valley_2\r\n    for (int ik_v_idx=0; ik_v_idx<nk_relev; ik_v_idx++)\r\n    {\r\n      ik_v = _relev_ik_range[i_valley_2][ik_v_idx][0];\r\n      mu_v = _relev_ik_range[i_valley_2][ik_v_idx][1];\r\n      ik_c = get_ikc(ik_v,ik_cm);\r\n      mu_c = mu_v;\r\n\r\n      ik_idx(0,nk_c-1-ik_v_idx,ik_cm_idx) = ik_c-elec_struct.ik_range[0];\r\n      ik_idx(1,nk_c-1-ik_v_idx,ik_cm_idx) = mu_c-elec_struct.mu_range[0];\r\n      ik_idx(2,nk_c-1-ik_v_idx,ik_cm_idx) = ik_v-elec_struct.ik_range[0];\r\n      ik_idx(3,nk_c-1-ik_v_idx,ik_cm_idx) = mu_v-elec_struct.mu_range[0];\r\n    }\r\n\r\n  }\r\n\r\n  std::cout << \"\\n...calculated exciton dispersion\\n\";\r\n\r\n  std::cout << \"saved exciton dispersion: A2 singlet\\n\";\r\n  std::string filename = _directory.path()/\"ex_energy_A2_singlet.dat\";\r\n  ex_energy_A2_singlet.save(filename, arma::arma_ascii);\r\n\r\n  std::cout << \"saved exciton dispersion: A2 triplet\\n\";\r\n  filename = _directory.path()/\"ex_energy_A2_triplet.dat\";\r\n  ex_energy_A2_triplet.save(filename, arma::arma_ascii);\r\n\r\n  std::cout << \"saved exciton dispersion: A1\\n\";\r\n  filename = _directory.path()/\"ex_energy_A1.dat\";\r\n  ex_energy_A1.save(filename, arma::arma_ascii);\r\n\r\n  std::cout << \"saved k_vector for center of mass\\n\";\r\n  filename = _directory.path()/\"exciton_k_cm_vec.dat\";\r\n  k_cm_vec.save(filename, arma::arma_ascii);\r\n\r\n  // prepare the values that are to be returned\r\n  std::vector<exciton_struct> excitons(3,exciton_struct(this));\r\n\r\n  excitons[0].name = \"A1 exciton\";\r\n  excitons[0].energy = ex_energy_A1;\r\n  excitons[0].spin = 0;\r\n  excitons[0].mu_cm = 0;\r\n  excitons[0].n_principal = nk_relev;\r\n  excitons[0].nk_c = nk_c;\r\n  excitons[0].nk_cm = nk_cm;\r\n  excitons[0].psi = ex_psi_A1;\r\n  excitons[0].ik_idx = ik_idx;\r\n  excitons[0].ik_cm_range = ik_cm_range;\r\n\r\n  excitons[1].name = \"A2 triplet exciton\";\r\n  excitons[1].energy = ex_energy_A2_triplet;\r\n  excitons[1].spin = 1;\r\n  excitons[1].mu_cm = 0;\r\n  excitons[1].n_principal = nk_relev;\r\n  excitons[1].nk_c = nk_c;\r\n  excitons[1].nk_cm = nk_cm;\r\n  excitons[1].psi = ex_psi_A2_triplet;\r\n  excitons[1].ik_idx = ik_idx;\r\n  excitons[1].ik_cm_range = ik_cm_range;\r\n\r\n  excitons[2].name = \"A2 singlet exciton\";\r\n  excitons[2].energy = ex_energy_A2_singlet;\r\n  excitons[2].spin = 0;\r\n  excitons[2].mu_cm = 0;\r\n  excitons[2].n_principal = nk_relev;\r\n  excitons[2].nk_c = nk_c;\r\n  excitons[2].nk_cm = nk_cm;\r\n  excitons[2].psi = ex_psi_A2_singlet;\r\n  excitons[2].ik_idx = ik_idx;\r\n  excitons[2].ik_cm_range = ik_cm_range;\r\n\r\n  return excitons;\r\n}\r\n\r\n// call this to do all the calculations at once\r\nvoid cnt::calculate_exciton_dispersion()\r\n{\r\n  get_parameters();\r\n  get_atom_coordinates();\r\n\r\n  // calculate K2-extended representation of electron energy\r\n  std::array<int,2> ik_range_K2 = {0,_Nu/_Q*_nk_K1};\r\n  std::array<int,2> mu_range_K2 = {0,_Q};\r\n  _elec_K2 = electron_energy(ik_range_K2, mu_range_K2, \"K2_extended\");\r\n\r\n  // find valleys and select a range of relevant iks in the focus valleys\r\n  find_valleys(_elec_K2);\r\n  find_relev_ik_range(1.*constants::eV, _elec_K2);\r\n\r\n  // calculate vq, and dielectric function for a sufficiently large range of mu and ik.\r\n  std::array<int,2> iq_range = {-(_elec_K2.ik_range[1]-1),_elec_K2.ik_range[1]};\r\n  std::array<int,2> mu_range = {-(_elec_K2.mu_range[1]-1),_elec_K2.mu_range[1]};\r\n  _vq = calculate_vq(iq_range, mu_range, _number_of_cnt_unit_cells);\r\n  _PI = calculate_polarization(iq_range, mu_range, _elec_K2);\r\n  _eps = calculate_dielectric(iq_range, mu_range);\r\n\r\n  // calculate exciton dispersions using the information calculated above\r\n  std::array<int,2> ik_cm_range = {-int(_relev_ik_range[0].size()), int(_relev_ik_range[0].size())};\r\n  _excitons = calculate_A_excitons(ik_cm_range, _elec_K2);\r\n\r\n}", "meta": {"hexsha": "eaee243b24947d445f6683d1bf56bbc408f5c052", "size": 37954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "montecarlo/src/exciton_transfer/cnt.cpp", "max_stars_repo_name": "li779/DECaNT", "max_stars_repo_head_hexsha": "8fe0faedd372a8214f1bd475eb7451d2eee1ca56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T19:21:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T16:41:21.000Z", "max_issues_repo_path": "montecarlo/src/exciton_transfer/cnt.cpp", "max_issues_repo_name": "li779/DECaNT", "max_issues_repo_head_hexsha": "8fe0faedd372a8214f1bd475eb7451d2eee1ca56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "montecarlo/src/exciton_transfer/cnt.cpp", "max_forks_repo_name": "li779/DECaNT", "max_forks_repo_head_hexsha": "8fe0faedd372a8214f1bd475eb7451d2eee1ca56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-22T15:02:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T15:02:52.000Z", "avg_line_length": 35.1100832562, "max_line_length": 219, "alphanum_fraction": 0.6194867471, "num_tokens": 12406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6311807363402729}}
{"text": "// Created by A. Aichert on Tue Aug 12th 2014\n#ifndef __model_similarity3D\n#define __model_similarity3D\n\n#include <LibOpterix/ParameterModel.hxx>\n\n#include <LibProjectiveGeometry/ProjectiveGeometry.hxx>\n\n#include <Eigen/Geometry>\n\nnamespace Geometry {\n\t// Parametrization for a similarity transformation of 3-space\n\tstruct ModelSimilarity3D : public LibOpterix::ParameterModel<Geometry::RP3Homography>\n\t{\n\t\t/// Human readable names of all parameters.\n\t\tstatic const std::vector<std::string>& ParameterNames()\n\t\t{\n\t\t\tstatic std::vector<std::string> names;\n\t\t\tif (names.empty())\n\t\t\t{\n\t\t\t\tnames.resize(7);\n\t\t\t\tnames[ 0]=\"Translation X\";\n\t\t\t\tnames[ 1]=\"Translation Y\";\n\t\t\t\tnames[ 2]=\"Translation Z\";\n\t\t\t\tnames[ 3]=\"Rotation X\";\n\t\t\t\tnames[ 4]=\"Rotation Y\";\n\t\t\t\tnames[ 5]=\"Rotation Z\";\n\t\t\t\tnames[ 6]=\"3D Scale\";\n\t\t\t}\n\t\t\treturn names;\n\t\t}\n\n\t\t/// Frequent sets of active parameters\n\t\tstatic const LibOpterix::ParameterSets& ParameterSets()\n\t\t{\n\t\t\tstatic LibOpterix::ParameterSets sets;\n\t\t\tif (sets.empty())\n\t\t\t{\n\t\t\t\tsets[\"3D Translation\"].insert(0);\n\t\t\t\tsets[\"3D Translation\"].insert(1);\n\t\t\t\tsets[\"3D Translation\"].insert(2);\n\t\t\t\tsets[\"3D Rigid\"].insert(0);\n\t\t\t\tsets[\"3D Rigid\"].insert(1);\n\t\t\t\tsets[\"3D Rigid\"].insert(2);\n\t\t\t\tsets[\"3D Rigid\"].insert(3);\n\t\t\t\tsets[\"3D Rigid\"].insert(4);\n\t\t\t\tsets[\"3D Rigid\"].insert(5);\n\t\t\t\tsets[\"3D Similarity\"].insert(0);\n\t\t\t\tsets[\"3D Similarity\"].insert(1);\n\t\t\t\tsets[\"3D Similarity\"].insert(2);\n\t\t\t\tsets[\"3D Similarity\"].insert(3);\n\t\t\t\tsets[\"3D Similarity\"].insert(4);\n\t\t\t\tsets[\"3D Similarity\"].insert(5);\n\t\t\t\tsets[\"3D Similarity\"].insert(6);\n\t\t\t}\n\t\t\treturn sets;\n\t\t}\n\t\t\n\t\tModelSimilarity3D(std::set<int> _active=std::set<int>())\n\t\t\t: LibOpterix::ParameterModel<Geometry::RP3Homography>(ParameterNames(),_active)\n\t\t{}\n\n\t\t// Compose a 3D homography from parametrization\n\t\tvirtual Geometry::RP3Homography getInstance() const\n\t\t{\n\t\t\tusing namespace Eigen;\n\t\t\t// Slicker naming of the parameter vector.\n\t\t\tconst std::vector<double>& x(current_values);\n\t\t\t// We begin with an identity\n\t\t\tMatrix4d T=Matrix4d::Identity();\n\t\t\t// Rotation about X Y and Z\n\t\t\tif (x[3]!=0||x[4]!=0||x[5]!=0)\n\t\t\t{\n\t\t\t\tauto R=( AngleAxisd(x[3], Vector3d::UnitX())\n\t\t\t\t\t\t*AngleAxisd(x[4], Vector3d::UnitY())\n\t\t\t\t\t\t*AngleAxisd(x[5], Vector3d::UnitZ()));\n\t\t\t\tT.block<3,3>(0,0)=(Matrix3d)R;\n\t\t\t}\n\t\t\t// Center of rotation and translation\n\t\t\tT(0,3)=x[0];\n\t\t\tT(1,3)=x[1];\n\t\t\tT(2,3)=x[2];\n\t\t\t// Apply scaling\n\t\t\tif (x[6]!=0) T.block<3,3>(0,0)*=(1.0+x[6]);\n\t\t\t// Return result\n\t\t\treturn T;\n\t\t}\n\t\t\n\t};\n\n} // namespace Geometry \n\n#endif // __model_similarity3D\n", "meta": {"hexsha": "5794a25fede066bf0402e0d21c817deb0615e1e3", "size": 2547, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "code/LibProjectiveGeometry/Models/ModelSimilarity3D.hxx", "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/Models/ModelSimilarity3D.hxx", "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/Models/ModelSimilarity3D.hxx", "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": 27.0957446809, "max_line_length": 86, "alphanum_fraction": 0.6454652532, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356994, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6311213304570026}}
{"text": "//\n// Created by krab1k on 31/10/18.\n//\n\n#include <vector>\n#include <functional>\n#include <Eigen/LU>\n\n#include \"eem.h\"\n#include \"../parameters.h\"\n#include \"../geometry.h\"\n\nCHARGEFW2_METHOD(EEM)\n\n\nEigen::VectorXd EEM::EE_system(const std::vector<const Atom *> &atoms, double total_charge) const {\n\n    size_t n = atoms.size();\n\n    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(n + 1, n + 1);\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(n + 1);\n\n    for (size_t i = 0; i < n; i++) {\n        const auto &atom_i = *atoms[i];\n        A(i, i) = parameters_->atom()->parameter(atom::B)(atom_i);\n        b(i) = -parameters_->atom()->parameter(atom::A)(atom_i);\n        for (size_t j = i + 1; j < n; j++) {\n            const auto &atom_j = *atoms[j];\n            auto x = parameters_->common()->parameter(common::kappa) / distance(atom_i, atom_j);\n            A(i, j) = x;\n            A(j, i) = x;\n        }\n    }\n    A.row(n) = Eigen::VectorXd::Constant(n + 1, 1);\n    A.col(n) = Eigen::VectorXd::Constant(n + 1, 1);\n    A(n, n) = 0;\n    b(n) = total_charge;\n\n    return A.partialPivLu().solve(b).head(n);\n}\n\n\nstd::vector<double> EEM::calculate_charges(const Molecule &molecule) const {\n    auto f = [this](const std::vector<const Atom *> &atoms, double total_charge) -> Eigen::VectorXd {\n        return EE_system(atoms, total_charge);\n    };\n\n    Eigen::VectorXd q = solve_EE(molecule, f);\n    return std::vector<double>(q.data(), q.data() + q.size());\n}\n", "meta": {"hexsha": "bc74b623081dc7047e62793789d6e0538bd7dc14", "size": 1447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/eem.cpp", "max_stars_repo_name": "danny305/ChargeFW2", "max_stars_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T15:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:38:09.000Z", "max_issues_repo_path": "src/methods/eem.cpp", "max_issues_repo_name": "danny305/ChargeFW2", "max_issues_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-03-04T21:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T07:11:19.000Z", "max_forks_repo_path": "src/methods/eem.cpp", "max_forks_repo_name": "danny305/ChargeFW2", "max_forks_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T00:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T05:47:39.000Z", "avg_line_length": 28.3725490196, "max_line_length": 101, "alphanum_fraction": 0.5812024879, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.63112130476077}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>, Randi Cabezas <rcabezas@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/distributions/inverse_gamma.hpp>\n\n#include <boost/random/chi_squared_distribution.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n#include <dpMM/distribution.hpp>\n#include <dpMM/normal.hpp>\n\nusing namespace Eigen;\nusing std::endl;\nusing std::cout;\nusing std::vector;\n\ntemplate<typename T>\nclass NIW : public Distribution<T>\n{\npublic:\n  Matrix<T,Dynamic,Dynamic> Delta_;\n  Matrix<T,Dynamic,1> theta_;\n  T nu_,kappa_;\n  uint32_t D_;\n\n  NIW(const Matrix<T,Dynamic,Dynamic>& Delta, \n    const Matrix<T,Dynamic,Dynamic>& theta, T nu,  T kappa, \n    boost::mt19937 *pRndGen);\n  NIW(const NIW& niw);\n  ~NIW();\n\n  NIW<T>* copy();\n\n  NIW<T> posterior(const Matrix<T,Dynamic,Dynamic>& x, const VectorXu& z, \n    uint32_t k);\n  NIW<T> posterior(const vector<Matrix<T,Dynamic,Dynamic> >&x, const\n      VectorXu& z, uint32_t k);\n  // assumes vector [N, sum(x), flatten(sum(outer(x,x)))]\n  NIW<T> posteriorFromSS(const Matrix<T,Dynamic,1>& x);\n  NIW<T> posteriorFromSS(const vector<Matrix<T,Dynamic,1> >&x, const\n      VectorXu& z, uint32_t k);\n\n  NIW<T> posterior() const;\n  void resetSufficientStatistics();\n  void getSufficientStatistics(const Matrix<T,Dynamic,Dynamic> &x, \n    const VectorXu& z, uint32_t k);\n  void getSufficientStatistics(const vector<Matrix<T,Dynamic,Dynamic> > &x, \n    const VectorXu& z, uint32_t k);\n  T logProb(const Matrix<T,Dynamic,Dynamic>& x_i) const;\n  T logPosteriorProb(const Matrix<T,Dynamic,Dynamic>& x, VectorXu& z, uint32_t k, \n    uint32_t i);\n\n  Normal<T> sample();\n  Normal<T> sampleFromPosterior();\n\n  T logPdf(const Normal<T>& normal) const;\n  T logPdfMarginalized() const; // log pdf of SS under NIW prior\n  T logPdfUnderPriorMarginalizedMerged(const NIW<T>& other) const;\n\n  T logLikelihoodMarginalized(const Matrix<T,Dynamic,Dynamic>& Scatter, \n      const Matrix<T,Dynamic,1>& mean, T count) const;\n  void print() const;\n\n  virtual NIW<T>* merge(const NIW<T>& other);\n  void fromMerge(const NIW<T>& niwA, const NIW<T>& niwB);\n\n  const Matrix<T,Dynamic,Dynamic>& scatter() const {return scatter_;};\n  Matrix<T,Dynamic,Dynamic>& scatter() {return scatter_;};\n  const Matrix<T,Dynamic,1>& mean() const {return mean_;};\n  Matrix<T,Dynamic,1>& mean() {return mean_;};\n  T count() const {return count_;};\n  T& count() {return count_;};\n\n  void computeMergedSS( const NIW<T>& niwA, \n    const NIW<T>& niwB, Matrix<T,Dynamic,Dynamic>& scatterM, \n    Matrix<T,Dynamic,1>& muM, T& countM) const;\n\nprivate:\n  boost::random::normal_distribution<> gauss_;\n\n  // sufficient statistics\n  Matrix<T,Dynamic,Dynamic> scatter_;\n  Matrix<T,Dynamic,1> mean_;\n  T count_;\n\n};\n\ntypedef NIW<double> NIWd;\ntypedef NIW<float> NIWf;\n\n", "meta": {"hexsha": "c425e0cdc3d092bb398177c35bd75b8d2389dd90", "size": 2963, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/niw.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/dpMM/niw.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dpMM/niw.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 30.5463917526, "max_line_length": 120, "alphanum_fraction": 0.6992912589, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6310959508182902}}
{"text": "//  Copyright John Maddock 2012.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// Basic sanity check that header <boost/math/special_functions/bessel.hpp>\n// #includes all the files that it needs to.\n//\n#include <boost/math/special_functions/jacobi_elliptic.hpp>\n//\n// Note this header includes no other headers, this is\n// important if this test is to be meaningful:\n//\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n   check_result<float>(boost::math::jacobi_elliptic<float>(f, f, static_cast<float*>(0), static_cast<float*>(0)));\n   check_result<double>(boost::math::jacobi_elliptic<double>(d, d, static_cast<double*>(0), static_cast<double*>(0)));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_elliptic<long double>(l, l, static_cast<long double*>(0), static_cast<long double*>(0)));\n#endif\n\n   check_result<float>(boost::math::jacobi_sn<float>(f, f));\n   check_result<double>(boost::math::jacobi_sn<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_sn<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_cn<float>(f, f));\n   check_result<double>(boost::math::jacobi_cn<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_cn<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_dn<float>(f, f));\n   check_result<double>(boost::math::jacobi_dn<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_dn<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_cd<float>(f, f));\n   check_result<double>(boost::math::jacobi_cd<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_cd<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_dc<float>(f, f));\n   check_result<double>(boost::math::jacobi_dc<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_dc<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_ns<float>(f, f));\n   check_result<double>(boost::math::jacobi_ns<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_ns<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_sd<float>(f, f));\n   check_result<double>(boost::math::jacobi_sd<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_sd<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_ds<float>(f, f));\n   check_result<double>(boost::math::jacobi_ds<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_ds<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_nc<float>(f, f));\n   check_result<double>(boost::math::jacobi_nc<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_nc<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_nd<float>(f, f));\n   check_result<double>(boost::math::jacobi_nd<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_nd<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_sc<float>(f, f));\n   check_result<double>(boost::math::jacobi_sc<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_sc<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_cs<float>(f, f));\n   check_result<double>(boost::math::jacobi_cs<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_cs<long double>(l, l));\n#endif\n\n}\n", "meta": {"hexsha": "a1fc66b0c43387bcd346df660b9c88edc80389cc", "size": 4066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/test/compile_test/sf_jacobi_incl_test.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/test/compile_test/sf_jacobi_incl_test.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/test/compile_test/sf_jacobi_incl_test.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 41.9175257732, "max_line_length": 138, "alphanum_fraction": 0.7456960157, "num_tokens": 1064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6310959252583037}}
{"text": "#ifndef PHYSICS_HPP\n#define PHYSICS_HPP\n\n#define _USE_MATH_DEFINES\n#include <vector>\n#include <random>\n#include <cstdint>\n#include <Eigen/Core>\n\nclass physics\n{\npublic:\n\tphysics();\n\tvirtual ~physics();\n\n\tvoid init(uint16_t obj_count);\n\tvoid deinit();\n\tvoid step(double delta_t);\n\tuint16_t get_obj_count(){return obj_count;}\n\tstd::vector<Eigen::Vector3d>& get_pos(){return x[current];}\n\tstd::vector<double> get_radii(){return r;}\n\nprivate:\n\t/**\n\t * @brief Finds acceleration due to gravity\n\t * @param x_i Position\n\t * @param skip_index The index of the object that acceleration is calc\n\t * @return The acceleration vector\n\t */\n\tEigen::Vector3d accel(Eigen::Vector3d x_i, uint16_t skip_index);\n\n\t/**\n\t * @brief Current and next indicies\n\t */\n\tuint16_t current, next;\n\tuint16_t obj_count;\n\tdouble total_time;\n\tdouble mass_range[2];\n\tdouble radius_range[2];\n\tdouble distance_range[2];\n\t/**\n\t * @brief Position (x1, x2, x3), two vectors for new and old\n\t */\n\tstd::vector<Eigen::Vector3d> x[2];\n\t/**\n\t * @brief Velocity, two vectors for new and old\n\t */\n\tstd::vector<Eigen::Vector3d> v[2];\n\t/**\n\t * @brief Acceleration, two vectors for new and old\n\t */\n\tstd::vector<Eigen::Vector3d> a[2];\n\t/**\n\t * @brief Ocject radii\n\t */\n\tstd::vector<double> r;\n\t/**\n\t * @brief Object mass\n\t */\n\tstd::vector<double> m;\n\t/**\n\t * @brief A random generator that is initialized in the constructor\n\t */\n\tstd::mt19937_64 generator;\n\n\tdouble G = 6.67408e-11;\n};\n\n#endif\n", "meta": {"hexsha": "63c46878a819eebb77f45f1101006078658afcb2", "size": 1442, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "phy/physics.hpp", "max_stars_repo_name": "foxfire256/grav_sim", "max_stars_repo_head_hexsha": "bc5d4ca1250203a6b7654c04914bb3fe13cef67e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phy/physics.hpp", "max_issues_repo_name": "foxfire256/grav_sim", "max_issues_repo_head_hexsha": "bc5d4ca1250203a6b7654c04914bb3fe13cef67e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phy/physics.hpp", "max_forks_repo_name": "foxfire256/grav_sim", "max_forks_repo_head_hexsha": "bc5d4ca1250203a6b7654c04914bb3fe13cef67e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6, "max_line_length": 71, "alphanum_fraction": 0.6886269071, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6310700878714357}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n   //[cpp_dec_float_eg\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <iostream>\n\nint main()\n{\n   using namespace boost::multiprecision;\n\n   // Operations at fixed precision and full numeric_limits support:\n   cpp_dec_float_100 b = 2;\n   std::cout << std::numeric_limits<cpp_dec_float_100>::digits << std::endl;\n   // Note that digits10 is the same as digits, since we're base 10! :\n   std::cout << std::numeric_limits<cpp_dec_float_100>::digits10 << std::endl;\n   // We can use any C++ std lib function, lets print all the digits as well:\n   std::cout << std::setprecision(std::numeric_limits<cpp_dec_float_100>::max_digits10)\n      << log(b) << std::endl; // print log(2)\n   // We can also use any function from Boost.Math:\n   std::cout << boost::math::tgamma(b) << std::endl;\n   // These even work when the argument is an expression template:\n   std::cout << boost::math::tgamma(b * b) << std::endl;\n   // And since we have an extended exponent range we can generate some really large\n   // numbers here (4.0238726007709377354370243e+2564):\n   std::cout << boost::math::tgamma(cpp_dec_float_100(1000)) << std::endl;\n   return 0;\n}\n//]\n", "meta": {"hexsha": "a779b2d3b007233a3b9739754abbc9266a95a0e9", "size": 1447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/multiprecision/example/cpp_dec_float_snips.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/multiprecision/example/cpp_dec_float_snips.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/multiprecision/example/cpp_dec_float_snips.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": 43.8484848485, "max_line_length": 87, "alphanum_fraction": 0.6738078784, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.63107008756442}}
{"text": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @files zelikovsky_11_per_6_long_test.cpp\n * @brief\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2013-02-04\n */\n\n#include <boost/test/unit_test.hpp>\n\n// this include must be here! //hack for clang\n#include \"paal/steiner_tree/zelikovsky_11_per_6.hpp\"\n\n#include \"test_utils/logger.hpp\"\n#include \"test_utils/read_steinlib.hpp\"\n#include \"test_utils/test_result_check.hpp\"\n\n#include \"paal/utils/irange.hpp\"\n#include \"paal/data_structures/bimap.hpp\"\n\n#include <vector>\n\nBOOST_AUTO_TEST_CASE(zelikovsky_11_per_6_test) {\n    std::vector<paal::steiner_tree_test_with_metric> data;\n    LOGLN(\"READING INPUT...\");\n    read_steinlib_tests(data);\n    for (auto const &test : data) {\n        LOGLN(\"TEST \" << test.test_name);\n        LOGLN(\"OPT \" << test.optimal);\n\n        using Metric = decltype(test.metric);\n        using voronoiT = paal::data_structures::voronoi<Metric>;\n        using FSet = typename voronoiT::GeneratorsSet;\n        voronoiT voronoi(\n            FSet(test.terminals.begin(), test.terminals.end()),\n            FSet(test.steiner_points.begin(), test.steiner_points.end()),\n            test.metric);\n        std::vector<int> selected_steiner_points;\n        paal::steiner_tree_zelikovsky11per6approximation(\n            test.metric, voronoi, std::back_inserter(selected_steiner_points));\n\n        auto res_range = boost::join(test.terminals, selected_steiner_points);\n        LOG_COPY_RANGE_DEL(res_range, \",\");\n        paal::data_structures::bimap<int> idx;\n        auto g = paal::data_structures::metric_to_bgl_with_index(\n            test.metric, res_range, idx);\n        std::vector<int> pm(res_range.size());\n        boost::prim_minimum_spanning_tree(g, &pm[0]);\n        auto idx_m = paal::data_structures::make_metric_on_idx(test.metric, idx);\n        int res(0);\n        for (int i : paal::irange(pm.size())) {\n            if (pm[i] != i) {\n                res += idx_m(i, pm[i]);\n            }\n        }\n        check_result(res, test.optimal, 11. / 6);\n    }\n}\n", "meta": {"hexsha": "353efa8f2812225a93bd83a4d8b07b10daffdcad", "size": 2313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/steiner_tree/zelikovsky_11_per_6_long_test.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/steiner_tree/zelikovsky_11_per_6_long_test.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/steiner_tree/zelikovsky_11_per_6_long_test.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 35.0454545455, "max_line_length": 81, "alphanum_fraction": 0.6126242974, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.6310700823899579}}
{"text": "//  Copyright (c) 2019 AUTHORS\n//\n//  Distributed under the Boost Software License, Version 1.0. (See accompanying\n//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Original Fortran source: http://cococubed.asu.edu/research_pages/sedov.shtml\n\n\n\n/* sedov3.f -- translated by f2c (version 20160102).\n You must link the resulting object file with libf2c:\n on Microsoft Windows system, link with libf2c.lib;\n on Linux or Unix systems, link with .../path/to/libf2c.a -lm\n or, if you install libf2c.a in a standard place, with -lf2c -lm\n -- in that order, at the end of the command line, as ina\n cc *.o -lf2c -lm\n Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,\n\n http://www.netlib.org/f2c/libf2c.zip\n */\n\n#include <cmath>\n#include <vector>\n#include <unordered_map>\n#include <memory>\n//#include \"f2c.h\"\n#include <memory>\n#include <assert.h>\n#if !defined(OCTOTIGER_HAVE_BOOST_MULTIPRECISION)\n#include <quadmath.h>\nusing sed_real = __float128;\n\nsed_real _exp(sed_real a) {\n    return expq(a);\n}\n\nsed_real pow_dd(sed_real *a, sed_real *b) {\n    return powq(*a, *b);\n}\n\n\nsed_real d_sign(sed_real *a, sed_real * b) {\n    return copysignq(*a, *b);\n}\n#else\n#include <boost/multiprecision/cpp_bin_float.hpp>\nusing sed_real = boost::multiprecision::cpp_bin_float_quad;\n\nsed_real _exp(sed_real a) {\n    return boost::multiprecision::exp(a);\n}\n\nsed_real pow_dd(sed_real *a, sed_real *b) {\n    return boost::multiprecision::pow(*a, *b);\n}\n\n\nsed_real d_sign(sed_real *a, sed_real * b) {\n    if ((*a > static_cast<sed_real>(0.) && (*b > static_cast<sed_real>(0.))) ||\n        (*a < static_cast<sed_real>(0.) && (*b < static_cast<sed_real>(0.))))\n    {\n        return *a;\n    }\n    return *b;\n}\n#endif\n\n/* Subroutine */int sed_1d__(sed_real *time, int *nstep,\n        sed_real * xpos, sed_real *eblast, sed_real *omega_in__,\n        sed_real * xgeom_in__, sed_real *rho0, sed_real *vel0,\n        sed_real *ener0, sed_real *pres0, sed_real *cs0, sed_real *gam0,\n        sed_real *den, sed_real *ener, sed_real *pres, sed_real *vel,\n        sed_real *cs);\n/* Common Block Declarations */\n\nstruct {\n    sed_real gamma, gamm1, gamp1, gpogm, xgeom, xg2, rwant, r2, a0, a1, a2, a3,\n            a4, a5, a_val__, b_val__, c_val__, d_val__, e_val__, omega, vv,\n            xlam_want__, vwant, rvv;\n    bool lsingular, lstandard, lvacuum, lomega2, lomega3;\n} slap_;\n\n#define slap_1 slap_\n\nstruct {\n    sed_real gam_int__;\n} cmidp_;\n\n#define cmidp_1 cmidp_\n\n/* Table of constant values */\n\nusing D_fp = sed_real (*)(sed_real*);\nusing S_fp = int (*)(\n    D_fp, sed_real*, sed_real*, sed_real*, int*);    //Subroutine\nusing U_fp = int (*)();                              // Unknown procedure type\n\nstatic sed_real c_b52 = 2.;\nstatic sed_real c_b53 = 1e-10;\nstatic sed_real c_b79 = 0.f;\nstatic sed_real c_b80 = 1e-30;\nstatic int c__3 = 3;\nstatic int c__5 = 5;\nstatic sed_real efun01_(sed_real *v);\nstatic sed_real efun02_(sed_real *v);\nstatic sed_real sed_v_find__(sed_real *v);\nstatic sed_real sed_r_find__(sed_real *r__);\n/* Subroutine */int sedov_funcs__(sed_real *v, sed_real *l_fun__, sed_real *dlamdv,\n        sed_real *f_fun__, sed_real *g_fun__, sed_real *h_fun__);\n/* Subroutine */static int midpnt_(D_fp func, sed_real *a, sed_real *b, sed_real *s,\n        int *n);\n/* Subroutine */static int midpowl_(D_fp funk, sed_real *aa, sed_real *bb,\n        sed_real *s, int *n);\n/* Subroutine */static int midpowl2_(D_fp funk, sed_real *aa, sed_real *bb,\n        sed_real *s, int *n);\n/* Subroutine */static int qromo_(D_fp func, sed_real *a, sed_real *b, sed_real *eps,\n        sed_real *ss, S_fp choose);\n/* Subroutine */static int polint_(sed_real *xa, sed_real *ya, int *n,\n        sed_real *x, sed_real *y, sed_real *dy);\nstatic sed_real zeroin_(sed_real *ax, sed_real *bx, D_fp f, sed_real *tol);\n\n\nint pow_ii(int * a, int * b) {\n    return std::pow(*a, *b);\n}\n\n\n/* Subroutine */int sed_1d__(sed_real *time, int *nstep, sed_real * xpos,\n        sed_real *eblast, sed_real *omega_in__, sed_real * xgeom_in__, sed_real *rho0,\n        sed_real *vel0, sed_real *ener0, sed_real *pres0, sed_real *cs0, sed_real *gam0,\n        sed_real *den, sed_real *ener, sed_real *pres, sed_real *vel, sed_real *cs) {\n\n    /* System generated locals */\n    int i__1;\n    sed_real d__1, d__2, d__3;\n\n    /* Builtin functions */\n\n    /* Local variables */\n    static int i__;\n    static sed_real p2, v0, u2, v2, us;\n    static sed_real vat, rho1, rho2;\n    static sed_real vmin, eval1, eval2, alpha, f_fun__;\n    static sed_real g_fun__, h_fun__, l_fun__;\n    static sed_real vstar, denom2, denom3, dlamdv;\n    sed_real zeroin_(sed_real *ax, sed_real *bx, D_fp f, sed_real *tol);\n\n    /* ..this routine produces 1d solutions for a sedov blast wave propagating */\n    /* ..through a density gradient rho = rho**(-omega) */\n    /* ..in planar, cylindrical or spherical geometry */\n    /* ..for the standard, singular and vaccum cases. */\n    /* ..standard case: a nonzero solution extends from the shock to the origin, */\n    /* ..               where the pressure is finite. */\n    /* ..singular case: a nonzero solution extends from the shock to the origin, */\n    /* ..               where the pressure vanishes. */\n    /* ..vacuum case  : a nonzero solution extends from the shock to a boundary point, */\n    /* ..               where the density vanishes making the pressure meaningless. */\n    /* ..input: */\n    /* ..time     = temporal point where solution is desired seconds */\n    /* ..xpos(i)  = spatial points where solution is desired cm */\n    /* ..eblast   = energy of blast erg */\n    /* ..rho0     = ambient density g/cm**3    rho = rho0 * r**(-omega_in) */\n    /* ..omegain  = density power law _exponent rho = rho0 * r**(-omega_in) */\n    /* ..vel0     = ambient material speed cm/s */\n    /* ..pres0    = ambient pressure erg/cm**3 */\n    /* ..cs0      = ambient sound speed cm/s */\n    /* ..gam0   = gamma law equation of state */\n    /* ..xgeom_in = geometry factor, 3=spherical, 2=cylindircal, 1=planar */\n    /* ..for efficiency reasons (doing the energy integrals only once), */\n    /* ..this routine returns the solution for an array of spatial points */\n    /* ..at the desired time point. */\n    /* ..output: */\n    /* ..den(i)  = density  g/cm**3 */\n    /* ..ener(i) = specific internal energy erg/g */\n    /* ..pres(i) = presssure erg/cm**3 */\n    /* ..vel(i)  = velocity cm/s */\n    /* ..cs(i)   = sound speed cm/s */\n    /* ..this routine is based upon two papers: */\n    /* ..\"evaluation of the sedov-von neumann-taylor blast wave solution\" */\n    /* ..jim kamm, la-ur-00-6055 */\n    /* ..\"the sedov self-similiar point blast solutions in nonuniform media\" */\n    /* ..david book, shock waves, 4, 1, 1994 */\n    /* ..although the ordinary differential equations are analytic, */\n    /* ..the sedov _expressions appear to become singular for various */\n    /* ..combinations of parameters and at the lower limits of the integration */\n    /* ..range. all these singularies are removable and done so by this routine. */\n    /* ..these routines are written in sed_real*8 precision because the */\n    /* ..sed_real*8 implementations simply run out of precision \"near\" the origin */\n    /* ..in the standard case or the transition region in the vacuum case. */\n    /* ..declare the pass */\n    /* ..local variables */\n    /* ..eps controls the integration accuracy, don't get too greedy or the number */\n    /* ..of function evaluations required kills. */\n    /* ..eps2 controls the root find accuracy */\n    /* ..osmall controls the size of transition regions */\n    /* ..common block communication */\n    /* ..common block communication with the integration stepper */\n    /* ..popular formats */\n    /* ..initialize the solution */\n    /* Parameter adjustments */\n    --cs;\n    --vel;\n    --pres;\n    --ener;\n    --den;\n    --xpos;\n\n    /* Function Body */\n    /* L87: */\n    /* L88: */\n    i__1 = *nstep;\n    for (i__ = 1; i__ <= i__1; ++i__) {\n        den[i__] = 0.f;\n        vel[i__] = 0.f;\n        pres[i__] = 0.f;\n        ener[i__] = 0.f;\n        cs[i__] = 0.f;\n    }\n    /* ..return on unphysical cases */\n    /* ..infinite mass */\n    if (*omega_in__ >= *xgeom_in__) {\n        return 0;\n    }\n    /* ..transfer the pass to common block and create some frequent combinations */\n    slap_1.gamma = *gam0;\n    slap_1.gamm1 = slap_1.gamma - 1.f;\n    slap_1.gamp1 = slap_1.gamma + 1.f;\n    slap_1.gpogm = slap_1.gamp1 / slap_1.gamm1;\n    slap_1.xgeom = *xgeom_in__;\n    slap_1.omega = *omega_in__;\n    slap_1.xg2 = slap_1.xgeom + 2.f - slap_1.omega;\n    denom2 = slap_1.gamm1 * 2.f + slap_1.xgeom - slap_1.gamma * slap_1.omega;\n    denom3 = slap_1.xgeom * (2.f - slap_1.gamma) - slap_1.omega;\n    /* ..post shock location v2 and location of singular point vstar */\n    /* ..kamm equation 18 and 19 */\n    v2 = 4.f / (slap_1.xg2 * slap_1.gamp1);\n    vstar = 2.f / (slap_1.gamm1 * slap_1.xgeom + 2.f);\n    /* ..set two bools that determines the type of solution */\n    slap_1.lstandard = false;\n    slap_1.lsingular = false;\n    slap_1.lvacuum = false;\n    if ((d__1 = v2 - vstar, fabs(static_cast<double>(d__1))) <= 1e-4) {\n        slap_1.lsingular = true;\n    } else if (v2 < vstar - 1e-4) {\n        slap_1.lstandard = true;\n    } else if (v2 > vstar + 1e-4) {\n        slap_1.lvacuum = true;\n    }\n    /* ..two apparent singularies, book's notation for omega2 and omega3 */\n    slap_1.lomega2 = false;\n    slap_1.lomega3 = false;\n    if (fabs(static_cast<double>(denom2)) <= 1e-4) {\n        slap_1.lomega2 = true;\n        denom2 = 1e-8f;\n    } else if (fabs(static_cast<double>(denom3)) <= 1e-4) {\n        slap_1.lomega3 = true;\n        denom3 = 1e-8f;\n    }\n    /* ..various _exponents, kamm equations 42-47 */\n    /* ..in terms of book's notation: */\n    /* ..a0=beta6 a1=beta1  a2=-beta2 a3=beta3 a4=beta4 a5=-beta5 */\n    slap_1.a0 = 2.f / slap_1.xg2;\n    slap_1.a2 = -slap_1.gamm1 / denom2;\n    slap_1.a1 = slap_1.xg2 * slap_1.gamma / (slap_1.xgeom * slap_1.gamm1 + 2.f)\n            * ((slap_1.xgeom * (2.f - slap_1.gamma) - slap_1.omega) * 2.f\n                    / (slap_1.gamma * slap_1.xg2 * slap_1.xg2) - slap_1.a2);\n    slap_1.a3 = (slap_1.xgeom - slap_1.omega) / denom2;\n    slap_1.a4 = slap_1.xg2 * (slap_1.xgeom - slap_1.omega) * slap_1.a1 / denom3;\n    slap_1.a5 = (slap_1.omega * slap_1.gamp1 - slap_1.xgeom * 2.f) / denom3;\n    /* ..frequent combinations, kamm equations 33-37 */\n    slap_1.a_val__ = slap_1.xg2 * .25f * slap_1.gamp1;\n    slap_1.b_val__ = slap_1.gpogm;\n    slap_1.c_val__ = slap_1.xg2 * .5f * slap_1.gamma;\n    slap_1.d_val__ = slap_1.xg2 * slap_1.gamp1\n            / (slap_1.xg2 * slap_1.gamp1\n                    - (slap_1.xgeom * slap_1.gamm1 + 2.f) * 2.f);\n    slap_1.e_val__ = (slap_1.xgeom * slap_1.gamm1 + 2.f) * .5f;\n    /* ..evaluate the energy integrals */\n    /* ..the singular case can be done by hand; save some cpu cycles */\n    /* ..kamm equations 80, 81, and 85 */\n    if (slap_1.lsingular) {\n        /* Computing 2nd power */\n        d__1 = slap_1.gamm1 * slap_1.xgeom + 2.f;\n        eval2 = slap_1.gamp1 / (slap_1.xgeom * (d__1 * d__1));\n        eval1 = 2.f / slap_1.gamm1 * eval2;\n        /* Computing 2nd power */\n        d__1 = slap_1.gamm1 * slap_1.xgeom + 2.f;\n        alpha = slap_1.gpogm * pow_dd(&c_b52, &slap_1.xgeom)\n                / (slap_1.xgeom * (d__1 * d__1));\n        if (static_cast<int>(slap_1.xgeom) != 1) {\n            alpha *= 3.1415926535897932384626433832795029;\n        }\n        /* ..for the standard or vacuum cases */\n        /* ..v0 = post-shock origin v0 and vv = vacuum boundary vv */\n        /* ..set the radius corespondin to vv to zero for now */\n        /* ..kamm equations 18, and 28. */\n    } else {\n        v0 = 2.f / (slap_1.xg2 * slap_1.gamma);\n        slap_1.vv = 2.f / slap_1.xg2;\n        slap_1.rvv = 0.;\n        if (slap_1.lstandard) {\n            vmin = v0;\n        }\n        if (slap_1.lvacuum) {\n            vmin = slap_1.vv;\n        }\n        /* ..the first energy integral */\n        /* ..in the standard case the term (c_val*v - 1) might be singular at v=vmin */\n        if (slap_1.lstandard) {\n            cmidp_1.gam_int__ = slap_1.a3 - slap_1.a2 * slap_1.xg2 - 1.f;\n            if (cmidp_1.gam_int__ >= 0.) {\n                qromo_(static_cast<D_fp>(efun01_), &vmin, &v2, &c_b53, &eval1,\n                        static_cast<S_fp>(midpnt_));\n            } else {\n                cmidp_1.gam_int__ = fabs(static_cast<double>(cmidp_1.gam_int__));\n                qromo_(static_cast<D_fp>(efun01_), &vmin, &v2, &c_b53, &eval1,\n                        static_cast<S_fp>(midpowl_));\n            }\n            /* ..in the vacuum case the term (1 - c_val/gamma*v) might be singular at v=vmin */\n        } else if (slap_1.lvacuum) {\n            cmidp_1.gam_int__ = slap_1.a5;\n            if (cmidp_1.gam_int__ >= 0.) {\n                qromo_(static_cast<D_fp>(efun01_), &vmin, &v2, &c_b53, &eval1,\n                        static_cast<S_fp>(midpnt_));\n            } else {\n                cmidp_1.gam_int__ = fabs(static_cast<double>(cmidp_1.gam_int__));\n                qromo_(static_cast<D_fp>(efun01_), &vmin, &v2, &c_b53, &eval1,\n                        static_cast<S_fp>(midpowl2_));\n            }\n        }\n        /* ..the second energy integral */\n        /* ..in the standard case the term (c_val*v - 1) might be singular at v=vmin */\n        if (slap_1.lstandard) {\n            cmidp_1.gam_int__ = slap_1.a3 - slap_1.a2 * slap_1.xg2 - 2.f;\n            if (cmidp_1.gam_int__ >= 0.) {\n                qromo_(static_cast<D_fp>(efun02_), &vmin, &v2, &c_b53, &eval2,\n                        static_cast<S_fp>(midpnt_));\n            } else {\n                cmidp_1.gam_int__ = fabs(static_cast<double>(cmidp_1.gam_int__));\n                qromo_(static_cast<D_fp>(efun02_), &vmin, &v2, &c_b53, &eval2,\n                        static_cast<S_fp>(midpowl_));\n            }\n            /* ..in the vacuum case the term (1 - c_val/gamma*v) might be singular at v=vmin */\n        } else if (slap_1.lvacuum) {\n            cmidp_1.gam_int__ = slap_1.a5;\n            if (cmidp_1.gam_int__ >= 0.) {\n                qromo_(static_cast<D_fp>(efun02_), &vmin, &v2, &c_b53, &eval2,\n                        static_cast<S_fp>(midpnt_));\n            } else {\n                cmidp_1.gam_int__ = fabs(static_cast<double>(cmidp_1.gam_int__));\n                qromo_(static_cast<D_fp>(efun02_), &vmin, &v2, &c_b53, &eval2,\n                        static_cast<S_fp>(midpowl2_));\n            }\n        }\n        /* ..kamm equations 57 and 58 for alpha, in a slightly different form. */\n        if (static_cast<int>(slap_1.xgeom) == 1) {\n            alpha = eval1 * .5f + eval2 / slap_1.gamm1;\n        } else {\n            alpha = (slap_1.xgeom - 1.f) * 3.1415926535897932384626433832795029\n                    * (eval1 + eval2 * 2.f / slap_1.gamm1);\n        }\n    }\n    /* ..write what we have for the energy integrals */\n    if (true) {\n//\t\ts_wsfe(&io___42);\n//\t\tdo_fio(&c__1, \"xgeom =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &slap_1.xgeom, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"eblast=\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &(*eblast), (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"omega =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &slap_1.omega, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"alpha =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &alpha, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"j1    =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &eval1, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"j2    =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &eval2, (ftnlen) sizeof(sed_real));\n//\t\te_wsfe();\n    }\n    /*      write(6,87) omega,alpha */\n    /* ..immediate post-shock values */\n    /* ..kamm page 14 or equations 14, 16, 5, 13 */\n    /* ..r2 = shock position, u2 = shock speed, rho1 = pre-shock density, */\n    /* ..u2 = post-shock material speed, rho2 = post-shock density, */\n    /* ..p2 = post-shock pressure, e2 = post-shoock specific internal energy, */\n    /* ..and cs2 = post-shock sound speed */\n    d__1 = *eblast / (alpha * *rho0);\n    d__2 = 1.f / slap_1.xg2;\n    d__3 = 2.f / slap_1.xg2;\n    slap_1.r2 = pow_dd(&d__1, &d__2) * pow_dd(time, &d__3);\n    us = 2.f / slap_1.xg2 * slap_1.r2 / *time;\n    d__1 = -slap_1.omega;\n    rho1 = *rho0 * pow_dd(&slap_1.r2, &d__1);\n    u2 = us * 2.f / slap_1.gamp1;\n    rho2 = slap_1.gpogm * rho1;\n    /* Computing 2nd power */\n    d__1 = us;\n    p2 = rho1 * 2.f * (d__1 * d__1) / slap_1.gamp1;\n//\te2 = p2 / (slap_1.gamm1 * rho2);\n//\tcs2 = sqrt(slap_1.gamma * p2 / rho2);\n    /* ..find the radius corresponding to vv */\n    if (slap_1.lvacuum) {\n        slap_1.vwant = slap_1.vv;\n        slap_1.rvv = zeroin_(&c_b79, &slap_1.r2, static_cast<D_fp>(sed_r_find__), &c_b80);\n    }\n//\tif (slap_1.lstandard) {\n//\t\ts_wsfe(&io___50);\n//\t\tdo_fio(&c__1, \"r2    =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &slap_1.r2, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"rho2  =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &rho2, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"u2    =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &u2, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"e2    =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &e2, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"p2    =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &p2, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"cs2   =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &cs2, (ftnlen) sizeof(sed_real));\n//\t\te_wsfe();\n//\t}\n//\tif (slap_1.lvacuum) {\n//\t\ts_wsfe(&io___51);\n//\t\tdo_fio(&c__1, \"rv    =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &slap_1.rvv, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"r2    =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &slap_1.r2, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"rho2  =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &rho2, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"u2    =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &u2, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"e2    =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &e2, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"p2    =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &p2, (ftnlen) sizeof(sed_real));\n//\t\tdo_fio(&c__1, \"cs2   =\", (ftnlen) 7);\n//\t\tdo_fio(&c__1, (char *) &cs2, (ftnlen) sizeof(sed_real));\n//\t\te_wsfe();\n//\t}\n    /* ..now start the loop over spatial positions */\n    i__1 = *nstep;\n    for (i__ = 1; i__ <= i__1; ++i__) {\n        slap_1.rwant = xpos[i__];\n        /* ..if we are upstream from the shock front */\n        if (slap_1.rwant > slap_1.r2) {\n            d__1 = -slap_1.omega;\n            den[i__] = *rho0 * pow_dd(&slap_1.rwant, &d__1);\n            vel[i__] = *vel0;\n            pres[i__] = *pres0;\n            ener[i__] = *ener0;\n            cs[i__] = *cs0;\n            /* ..if we are between the origin and the shock front */\n            /* ..find the correct similarity value for this radius in the standard or vacuum cases */\n        } else {\n            if (slap_1.lstandard) {\n                d__1 = v0 * .9f;\n                vat = zeroin_(&d__1, &v2, static_cast<D_fp>(sed_v_find__), &c_b80);\n            } else if (slap_1.lvacuum) {\n                d__1 = slap_1.vv * 1.2f;\n                vat = zeroin_(&v2, &d__1, static_cast<D_fp>(sed_v_find__), &c_b80);\n            }\n            /* ..the physical solution */\n            sedov_funcs__(&vat, &l_fun__, &dlamdv, &f_fun__, &g_fun__,\n                    &h_fun__);\n            den[i__] = rho2 * g_fun__;\n            vel[i__] = u2 * f_fun__;\n            pres[i__] = p2 * h_fun__;\n            ener[i__] = 0.f;\n            cs[i__] = 0.f;\n            if (den[i__] != 0.f) {\n                ener[i__] = pres[i__] / (slap_1.gamm1 * den[i__]);\n                cs[i__] = sqrt(static_cast<double>(slap_1.gamma * pres[i__] / den[i__]));\n            }\n        }\n        /* ..end of loop over positions */\n    }\n    return 0;\n} /* sed_1d__ */\n\nsed_real efun01_(sed_real *v) {\n    /* System generated locals */\n    sed_real ret_val, d__1, d__2;\n    ret_val = 0;\n\n    /* Builtin functions */\n    sed_real pow_dd(sed_real *, sed_real *);\n\n    /* Local variables */\n    static sed_real f_fun__, g_fun__, h_fun__, l_fun__, dlamdv;\n\n    /* ..evaluates the first energy integrand, kamm equations 67 and 10. */\n    /* ..the (c_val*v - 1) term might be singular at v=vmin in the standard case. */\n    /* ..the (1 - c_val/gamma * v) term might be singular at v=vmin in the vacuum case. */\n    /* ..due care should be taken for these removable singularities by the integrator. */\n    /* ..declare the pass */\n    /* ..common block communication */\n    /* ..local variables */\n    /* ..go */\n    sedov_funcs__(v, &l_fun__, &dlamdv, &f_fun__, &g_fun__, &h_fun__);\n    d__1 = slap_1.xgeom + 1.f;\n    /* Computing 2nd power */\n    d__2 = *v;\n    ret_val = dlamdv * pow_dd(&l_fun__, &d__1) * slap_1.gpogm * g_fun__\n            * (d__2 * d__2);\n    return ret_val;\n} /* efun01_ */\n\nsed_real efun02_(sed_real *v) {\n    /* System generated locals */\n    sed_real ret_val, d__1;\n    ret_val = 0;\n\n    /* Builtin functions */\n    sed_real pow_dd(sed_real *, sed_real *);\n\n    /* Local variables */\n    static sed_real z__;\n    static sed_real f_fun__, g_fun__, h_fun__, l_fun__, dlamdv;\n\n    /* ..evaluates the second energy integrand, kamm equations 68 and 11. */\n    /* ..the (c_val*v - 1) term might be singular at v=vmin in the standard case. */\n    /* ..the (1 - c_val/gamma * v) term might be singular at v=vmin in the vacuum case. */\n    /* ..due care should be taken for these removable singularities by the integrator. */\n    /* ..declare the pass */\n    /* ..common block communication */\n    /* ..local variables */\n    /* ..go */\n    sedov_funcs__(v, &l_fun__, &dlamdv, &f_fun__, &g_fun__, &h_fun__);\n    /* Computing 2nd power */\n    d__1 = slap_1.xgeom + 2.f - slap_1.omega;\n    z__ = 8.f / (d__1 * d__1 * slap_1.gamp1);\n    d__1 = slap_1.xgeom - 1.f;\n    ret_val = dlamdv * pow_dd(&l_fun__, &d__1) * h_fun__ * z__;\n    return ret_val;\n} /* efun02_ */\n\nsed_real sed_v_find__(sed_real *v) {\n    /* System generated locals */\n    sed_real ret_val;\n    ret_val = 0;\n\n    /* Local variables */\n    static sed_real f_fun__, g_fun__, h_fun__, l_fun__, dlamdv;\n\n    /* ..given corresponding physical distances, find the similarity variable v */\n    /* ..kamm equation 38 as a root find */\n    /* ..declare the pass */\n    /* ..common block communication */\n    /* ..local variables */\n    sedov_funcs__(v, &l_fun__, &dlamdv, &f_fun__, &g_fun__, &h_fun__);\n    ret_val = slap_1.r2 * l_fun__ - slap_1.rwant;\n    return ret_val;\n} /* sed_v_find__ */\n\nsed_real sed_r_find__(sed_real *r__) {\n    /* System generated locals */\n    sed_real ret_val;\n    ret_val = 0;\n\n    /* Local variables */\n    static sed_real f_fun__, g_fun__, h_fun__, l_fun__, dlamdv;\n\n    /* ..given the similarity variable v, find the corresponding physical distance */\n    /* ..kamm equation 38 as a root find */\n    /* ..declare the pass */\n    /* ..common block communication */\n    /* ..local variables */\n    sedov_funcs__(&slap_1.vwant, &l_fun__, &dlamdv, &f_fun__, &g_fun__,\n            &h_fun__);\n    ret_val = slap_1.r2 * l_fun__ - *r__;\n    return ret_val;\n} /* sed_r_find__ */\n\n/* Subroutine */int sedov_funcs__(sed_real *v, sed_real *l_fun__, sed_real *dlamdv,\n        sed_real *f_fun__, sed_real *g_fun__, sed_real *h_fun__) {\n    /* System generated locals */\n    sed_real d__1, d__2, d__3;\n\n    /* Builtin functions */\n//\tsed_real pow_dd(sed_real *, sed_real *), _exp(sed_real);\n\n    /* Local variables */\n    static sed_real y, z__, c2, c6, x1, x2, x3, x4, pp1, pp2, pp3, pp4, cbag,\n            ebag, beta0, dx1dv, dx2dv, dx3dv, dx4dv, dpp2dv;\n\n    /* ..given the similarity variable v, returns functions */\n    /* ..lambda, f, g, and h and the derivative of lambda with v dlamdv */\n    /* ..although the ordinary differential equations are analytic, */\n    /* ..the sedov _expressions appear to become singular for various */\n    /* ..combinations of parameters and at the lower limits of the integration */\n    /* ..range. all these singularies are removable and done so by this routine. */\n    /* ..declare the pass */\n    /* ..common block communication */\n    /* ..local variables */\n    /* ..frequent combinations and their derivative with v */\n    /* ..kamm equation 29-32, x4 a bit different to save a divide */\n    /* ..x1 is book's F */\n    x1 = slap_1.a_val__ * *v;\n    dx1dv = slap_1.a_val__;\n    /* Computing MAX */\n    d__1 = 1e-30, d__2 = slap_1.c_val__ * *v - 1.f;\n    cbag = fmax(static_cast<double>(d__1), static_cast<double>(d__2));\n    x2 = slap_1.b_val__ * cbag;\n    dx2dv = slap_1.b_val__ * slap_1.c_val__;\n    ebag = 1.f - slap_1.e_val__ * *v;\n    x3 = slap_1.d_val__ * ebag;\n    dx3dv = -slap_1.d_val__ * slap_1.e_val__;\n    x4 = slap_1.b_val__ * (1.f - slap_1.xg2 * .5f * *v);\n    dx4dv = -slap_1.b_val__ * .5f * slap_1.xg2;\n    /* ..transition region between standard and vacuum cases */\n    /* ..kamm page 15 or equations 88-92 */\n    /* ..lambda = l_fun is book's zeta */\n    /* ..f_fun is books V, g_fun is book's D, h_fun is book's P */\n    if (slap_1.lsingular) {\n        *l_fun__ = slap_1.rwant / slap_1.r2;\n        *dlamdv = 0.f;\n        *f_fun__ = *l_fun__;\n        d__1 = slap_1.xgeom - 2.f;\n        *g_fun__ = pow_dd(l_fun__, &d__1);\n        *h_fun__ = pow_dd(l_fun__, &slap_1.xgeom);\n        /* ..for the vacuum case in the hole */\n    } else if (slap_1.lvacuum && slap_1.rwant < slap_1.rvv) {\n        *l_fun__ = 0.f;\n        *dlamdv = 0.f;\n        *f_fun__ = 0.f;\n        *g_fun__ = 0.f;\n        *h_fun__ = 0.f;\n        /* ..omega = omega2 = (2*(gamma -1) + xgeom)/gamma case, denom2 = 0 */\n        /* ..book _expressions 20-22 */\n    } else if (slap_1.lomega2) {\n        beta0 = 1.f / (slap_1.e_val__ * 2.f);\n        pp1 = slap_1.gamm1 * beta0;\n        c6 = slap_1.gamp1 * .5f;\n        c2 = c6 / slap_1.gamma;\n        y = 1.f / (x1 - c2);\n        z__ = (1.f - x1) * y;\n        pp2 = slap_1.gamp1 * beta0 * z__;\n        dpp2dv = -slap_1.gamp1 * beta0 * dx1dv * y * (z__ + 1.f);\n        pp3 = (4.f - slap_1.xgeom - slap_1.gamma * 2.f) * beta0;\n        pp4 = -slap_1.xgeom * slap_1.gamma * beta0;\n        d__1 = -slap_1.a0;\n        *l_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &pp1) * _exp(pp2);\n        *dlamdv = (-slap_1.a0 * dx1dv / x1 + pp1 * dx2dv / x2 + dpp2dv)\n                * *l_fun__;\n        *f_fun__ = x1 * *l_fun__;\n        d__1 = slap_1.a0 * slap_1.omega;\n        *g_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &pp3) * pow_dd(&x4, &\n        slap_1.a5) * _exp(pp2 * -2.f);\n        d__1 = slap_1.a0 * slap_1.xgeom;\n        d__2 = slap_1.a5 + 1.f;\n        *h_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &pp4) * pow_dd(&x4, &d__2);\n        /* ..omega = omega3 = xgeom*(2 - gamma) case, denom3 = 0 */\n        /* ..book _expressions 23-25 */\n    } else if (slap_1.lomega3) {\n        beta0 = 1.f / (slap_1.e_val__ * 2.f);\n        pp1 = slap_1.a3 + slap_1.omega * slap_1.a2;\n        pp2 = 1.f - beta0 * 4.f;\n        c6 = slap_1.gamp1 * .5f;\n        pp3 = -slap_1.xgeom * slap_1.gamma * slap_1.gamp1 * beta0 * (1.f - x1)\n                / (c6 - x1);\n        pp4 = (slap_1.xgeom * slap_1.gamm1 - slap_1.gamma) * 2.f * beta0;\n        d__1 = -slap_1.a0;\n        d__2 = -slap_1.a2;\n        d__3 = -slap_1.a1;\n        *l_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &d__2) * pow_dd(&x4, &d__3);\n        *dlamdv = -(slap_1.a0 * dx1dv / x1 + slap_1.a2 * dx2dv / x2 +\n        slap_1.a1 * dx4dv / x4) * *l_fun__;\n        *f_fun__ = x1 * *l_fun__;\n        d__1 = slap_1.a0 * slap_1.omega;\n        *g_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &pp1) * pow_dd(&x4, &pp2)\n                * _exp(pp3);\n        d__1 = slap_1.a0 * slap_1.xgeom;\n        *h_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x4, &pp4) * _exp(pp3);\n        /* ..for the standard or vacuum case not in the hole */\n        /* ..kamm equations 38-41 */\n    } else {\n        d__1 = -slap_1.a0;\n        d__2 = -slap_1.a2;\n        d__3 = -slap_1.a1;\n        *l_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &d__2) * pow_dd(&x3, &d__3);\n        *dlamdv = -(slap_1.a0 * dx1dv / x1 + slap_1.a2 * dx2dv / x2 +\n        slap_1.a1 * dx3dv / x3) * *l_fun__;\n        *f_fun__ = x1 * *l_fun__;\n        d__1 = slap_1.a0 * slap_1.omega;\n        d__2 = slap_1.a3 + slap_1.a2 * slap_1.omega;\n        d__3 = slap_1.a4 + slap_1.a1 * slap_1.omega;\n        *g_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &d__2) * pow_dd(&x3, &d__3)\n                * pow_dd(&x4, &slap_1.a5);\n        d__1 = slap_1.a0 * slap_1.xgeom;\n        d__2 = slap_1.a4 + slap_1.a1 * (slap_1.omega - 2.f);\n        d__3 = slap_1.a5 + 1.f;\n        *h_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x3, &d__2) * pow_dd(&x4, &d__3);\n    }\n    return 0;\n} /* sedov_funcs__ */\n\n/* Subroutine */int midpnt_(D_fp func, sed_real *a, sed_real *b, sed_real *s,\n        int *n) {\n    /* System generated locals */\n    int i__1;\n    sed_real d__1;\n\n    /* Builtin functions */\n    int pow_ii(int *, int *);\n\n    /* Local variables */\n    static int j;\n    static sed_real x;\n    static int it;\n    static sed_real del, tnm, sum, ddel;\n\n    /* ..this routine computes the n'th stage of refinement of an extended midpoint */\n    /* ..rule. func is input as the name of the function to be integrated between */\n    /* ..limits a and b. when called with n=1, the routine returns as s the crudest */\n    /* ..estimate of the integralof func from a to b. subsequent calls with n=2,3... */\n    /* ..improve the accuracy of s by adding 2/3*3**(n-1) addtional interior points. */\n    /* ..declare */\n    if (*n == 1) {\n        d__1 = (*a + *b) * .5f;\n        *s = (*b - *a) * (*func)(&d__1);\n    } else {\n        i__1 = *n - 2;\n        it = pow_ii(&c__3, &i__1);\n        tnm = static_cast<sed_real>(it);\n        del = (*b - *a) / (tnm * 3.f);\n        ddel = del + del;\n        x = *a + del * .5f;\n        sum = 0.f;\n        i__1 = it;\n        for (j = 1; j <= i__1; ++j) {\n            sum += (*func)(&x);\n            x += ddel;\n            sum += (*func)(&x);\n            x += del;\n        }\n        *s = (*s + (*b - *a) * sum / tnm) / 3.f;\n    }\n    return 0;\n} /* midpnt_ */\n\n/* Subroutine */int midpowl_(D_fp funk, sed_real *aa, sed_real *bb, sed_real *s,\n        int *n) {\n    /* System generated locals */\n    int i__1;\n    sed_real d__1, d__2, d__3, d__4;\n\n    /* Builtin functions */\n    sed_real pow_dd(sed_real *, sed_real *);\n    int pow_ii(int *, int *);\n\n    /* Local variables */\n    static sed_real a, b;\n    static int j;\n    static sed_real x;\n    static int it;\n    static sed_real del, tnm, sum, ddel;\n\n    /* ..this routine is an exact replacement for midpnt, except that it allows for */\n    /* ..an integrable power-law singularity of the form (x - a)**(-gam_int) */\n    /* ..at the lower limit aa for 0 < gam_int < 1. */\n    /* ..declare */\n    /* ..common block communication */\n    /* ..a little conversion, recipe equation 4.4.3 */\n    d__1 = *bb - *aa;\n    d__2 = 1.f - cmidp_1.gam_int__;\n    b = pow_dd(&d__1, &d__2);\n    a = 0.f;\n    /* ..now exactly as midpnt */\n    if (*n == 1) {\n        d__1 = (a + b) * .5f;\n        d__2 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__);\n        d__4 = 1.f / (1.f - cmidp_1.gam_int__);\n        d__3 = pow_dd(&d__1, &d__4) + *aa;\n        *s = (b - a)\n                * (1.f / (1.f - cmidp_1.gam_int__) * pow_dd(&d__1, &d__2)\n                        * (*funk)(&d__3));\n    } else {\n        i__1 = *n - 2;\n        it = pow_ii(&c__3, &i__1);\n        tnm = static_cast<sed_real>(it);\n        del = (b - a) / (tnm * 3.f);\n        ddel = del + del;\n        x = a + del * .5f;\n        sum = 0.f;\n        i__1 = it;\n        for (j = 1; j <= i__1; ++j) {\n            d__1 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__);\n            d__3 = 1.f / (1.f - cmidp_1.gam_int__);\n            d__2 = pow_dd(&x, &d__3) + *aa;\n            sum += 1.f / (1.f - cmidp_1.gam_int__) * pow_dd(&x, &d__1)\n                    * (*funk)(&d__2);\n            x += ddel;\n            d__1 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__);\n            d__3 = 1.f / (1.f - cmidp_1.gam_int__);\n            d__2 = pow_dd(&x, &d__3) + *aa;\n            sum += 1.f / (1.f - cmidp_1.gam_int__) * pow_dd(&x, &d__1)\n                    * (*funk)(&d__2);\n            x += del;\n        }\n        *s = (*s + (b - a) * sum / tnm) / 3.f;\n    }\n    return 0;\n} /* midpowl_ */\n\n/* Subroutine */int midpowl2_(D_fp funk, sed_real *aa, sed_real *bb, sed_real *s,\n        int *n) {\n    /* System generated locals */\n    int i__1;\n    sed_real d__1, d__2, d__3, d__4;\n\n    /* Builtin functions */\n\n    /* Local variables */\n    static sed_real a, b;\n    static int j;\n    static sed_real x;\n    static int it;\n    static sed_real del, tnm, sum, ddel;\n\n    /* ..this routine is an exact replacement for midpnt, except that it allows for */\n    /* ..an integrable power-law singularity of the form (a - x)**(-gam_int) */\n    /* ..at the lower limit aa for 0 < gam_int < 1. */\n    /* ..declare */\n    /* ..common block communication */\n    /* ..a little conversion, modulo recipe equation 4.4.3 */\n    d__1 = *aa - *bb;\n    d__2 = 1.f - cmidp_1.gam_int__;\n    b = pow_dd(&d__1, &d__2);\n    a = 0.f;\n    /* ..now exactly as midpnt */\n    if (*n == 1) {\n        d__1 = (a + b) * .5f;\n        d__2 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__);\n        d__4 = 1.f / (1.f - cmidp_1.gam_int__);\n        d__3 = *aa - pow_dd(&d__1, &d__4);\n        *s = (b - a)\n                * (1.f / (cmidp_1.gam_int__ - 1.f) * pow_dd(&d__1, &d__2)\n                        * (*funk)(&d__3));\n    } else {\n        i__1 = *n - 2;\n        it = pow_ii(&c__3, &i__1);\n        tnm = static_cast<sed_real>(it);\n        del = (b - a) / (tnm * 3.f);\n        ddel = del + del;\n        x = a + del * .5f;\n        sum = 0.f;\n        i__1 = it;\n        for (j = 1; j <= i__1; ++j) {\n            d__1 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__);\n            d__3 = 1.f / (1.f - cmidp_1.gam_int__);\n            d__2 = *aa - pow_dd(&x, &d__3);\n            sum += 1.f / (cmidp_1.gam_int__ - 1.f) * pow_dd(&x, &d__1)\n                    * (*funk)(&d__2);\n            x += ddel;\n            d__1 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__);\n            d__3 = 1.f / (1.f - cmidp_1.gam_int__);\n            d__2 = *aa - pow_dd(&x, &d__3);\n            sum += 1.f / (cmidp_1.gam_int__ - 1.f) * pow_dd(&x, &d__1)\n                    * (*funk)(&d__2);\n            x += del;\n        }\n        *s = (*s + (b - a) * sum / tnm) / 3.f;\n    }\n    return 0;\n} /* midpowl2_ */\n\n/* Subroutine */int qromo_(D_fp func, sed_real *a, sed_real *b, sed_real *eps,\n        sed_real *ss, S_fp choose) {\n    /* Builtin functions */\n\n    /* Local variables */\n    static sed_real h__[15];\n    static int j;\n    static sed_real s[15], dss;\n\n    /* Fortran I/O blocks */\n\n    /* ..this routine returns as s the integral of the function func from a to b */\n    /* ..with fractional accuracy eps. *//* ..jmax limits the number of steps; nsteps = 3**(jmax-1) */\n    /* ..integration is done via romberg algorithm. */\n    /* ..it is assumed the call to choose triples the number of steps on each call */\n    /* ..and that its error series contains only even powers of the number of steps. */\n    /* ..the external choose may be any of the above drivers, i.e midpnt,midinf... */\n    /* ..declare */\n    h__[0] = 1.f;\n    for (j = 1; j <= 14; ++j) {\n        (*choose)(static_cast<D_fp>(func), a, b, &s[j - 1], &j);\n        if (j >= 5) {\n            polint_(&h__[j - 5], &s[j - 5], &c__5, &c_b79, ss, &dss);\n            if (fabs(static_cast<double>(dss)) <= *eps * fabs(static_cast<double>(*ss))) {\n                return 0;\n            }\n        }\n        s[j] = s[j - 1];\n        h__[j] = h__[j - 1] / 9.f;\n    }\n    return 0;\n} /* qromo_ */\n\n/* Subroutine */int polint_(sed_real *xa, sed_real *ya, int *n, sed_real *x,\n        sed_real *y, sed_real *dy) {\n    /* System generated locals */\n    int i__1, i__2;\n    sed_real d__1;\n\n\n    /* Local variables */\n    static sed_real c__[20], d__[20];\n    static int i__, m;\n    static sed_real w, ho, hp;\n    static int ns;\n    static sed_real dif, den, dift;\n\n    /* ..given arrays xa and ya of length n and a value x, this routine returns a */\n    /* ..value y and an error estimate dy. if p(x) is the polynomial of degree n-1 */\n    /* ..such that ya = p(xa) ya then the returned value is y = p(x) */\n    /* ..declare */\n    /* ..find the index ns of the closest table entry; initialize the c and d tables */\n    /* Parameter adjustments */\n    --ya;\n    --xa;\n\n    /* Function Body */\n    ns = 1;\n    dif = (d__1 = *x - xa[1], fabs(static_cast<double>(d__1)));\n    i__1 = *n;\n    for (i__ = 1; i__ <= i__1; ++i__) {\n        dift = (d__1 = *x - xa[i__], fabs(static_cast<double>(d__1)));\n        if (dift < dif) {\n            ns = i__;\n            dif = dift;\n        }\n        c__[i__ - 1] = ya[i__];\n        d__[i__ - 1] = ya[i__];\n    }\n    /* ..first guess for y */\n    *y = ya[ns];\n    /* ..for each column of the table, loop over the c's and d's and update them */\n    --ns;\n    i__1 = *n - 1;\n    for (m = 1; m <= i__1; ++m) {\n        i__2 = *n - m;\n        for (i__ = 1; i__ <= i__2; ++i__) {\n            ho = xa[i__] - *x;\n            hp = xa[i__ + m] - *x;\n            w = c__[i__] - d__[i__ - 1];\n            den = ho - hp;\n            if (den == 0.f) {\n    //\t\t\ts_stop(\" 2 xa entries are the same in polint\", (ftnlen) 36);\n            }\n            den = w / den;\n            d__[i__ - 1] = hp * den;\n            c__[i__ - 1] = ho * den;\n        }\n        /* ..after each column is completed, decide which correction c or d, to add */\n        /* ..to the accumulating value of y, that is, which path to take in the table */\n        /* ..by forking up or down. ns is updated as we go to keep track of where we */\n        /* ..are. the last dy added is the error indicator. */\n        if (ns << 1 < *n - m) {\n            *dy = c__[ns];\n        } else {\n            *dy = d__[ns - 1];\n            --ns;\n        }\n        *y += *dy;\n    }\n    return 0;\n} /* polint_ */\n\nsed_real zeroin_(sed_real *ax, sed_real *bx, D_fp f, sed_real *tol) {\n    /* System generated locals */\n    sed_real ret_val, d__1;\n    ret_val = 0;\n\n    /* Local variables */\n    static sed_real a, b, c__, d__, e, p, q, r__, s, fa, fb, fc, xm, eps, tol1;\n\n    /* ----------------------------------------------------------------------- */\n\n    /* This subroutine solves for a zero of the function  f(x)  in the */\n    /* interval ax,bx. */\n\n    /*  input.. */\n\n    /*  ax     left endpoint of initial interval */\n    /*  bx     right endpoint of initial interval */\n    /*  f      function subprogram which evaluates f(x) for any x in */\n    /*         the interval  ax,bx */\n    /*  tol    desired length of the interval of uncertainty of the */\n    /*         final result ( .ge. 0.0) */\n\n    /*  output.. */\n\n    /*  zeroin abcissa approximating a zero of  f  in the interval ax,bx */\n\n    /*      it is assumed  that   f(ax)   and   f(bx)   have  opposite  signs */\n    /*  without  a  check.  zeroin  returns a zero  x  in the given interval */\n    /*  ax,bx  to within a tolerance  4*macheps*fabs(x) + tol, where macheps */\n    /*  is the relative machine precision. */\n    /*      this function subprogram is a slightly  modified  translation  of */\n    /*  the algol 60 procedure  zero  given in  richard brent, algorithms for */\n    /*  minimization without derivatives, prentice - hall, inc. (1973). */\n\n    /* ----------------------------------------------------------------------- */\n    /* .... call list variables */\n\n    /* ---------------------------------------------------------------------- */\n\n    /*  compute eps, the relative machine precision */\n\n    eps = 1.f;\n    L10: eps /= 2.f;\n    tol1 = eps + 1.f;\n    if (tol1 > 1.f) {\n        goto L10;\n    }\n\n    /* initialization */\n\n    a = *ax;\n    b = *bx;\n    fa = (*f)(&a);\n    fb = (*f)(&b);\n\n    /* begin step */\n\n    L20: c__ = a;\n    fc = fa;\n    d__ = b - a;\n    e = d__;\n    L30: if (fabs(static_cast<double>(fc)) >= fabs(static_cast<double>(fb))) {\n        goto L40;\n    }\n    a = b;\n    b = c__;\n    c__ = a;\n    fa = fb;\n    fb = fc;\n    fc = fa;\n\n    /* convergence test */\n\n    L40: tol1 = eps * 2.f * fabs(static_cast<double>(b)) + *tol * .5f;\n    xm = (c__ - b) * .5f;\n    if (fabs(static_cast<double>(xm)) <= tol1) {\n        goto L90;\n    }\n    if (fb == 0.f) {\n        goto L90;\n    }\n\n    /* is bisection necessary? */\n\n    if (fabs(static_cast<double>(e)) < tol1) {\n        goto L70;\n    }\n    if (fabs(static_cast<double>(fa)) <= fabs(static_cast<double>(fb))) {\n        goto L70;\n    }\n\n    /* is quadratic interpolation possible? */\n\n    if (a != c__) {\n        goto L50;\n    }\n\n    /* linear interpolation */\n\n    s = fb / fa;\n    p = xm * 2.f * s;\n    q = 1.f - s;\n    goto L60;\n\n    /* inverse quadratic interpolation */\n\n    L50: q = fa / fc;\n    r__ = fb / fc;\n    s = fb / fa;\n    p = s * (xm * 2.f * q * (q - r__) - (b - a) * (r__ - 1.f));\n    q = (q - 1.f) * (r__ - 1.f) * (s - 1.f);\n\n    /* adjust signs */\n\n    L60: if (p > 0.f) {\n        q = -q;\n    }\n    p = fabs(static_cast<double>(p));\n\n    /* is interpolation acceptable? */\n\n    if (p * 2.f >= xm * 3.f * q - (d__1 = tol1 * q, fabs(static_cast<double>(d__1)))) {\n        goto L70;\n    }\n    if (p >= (d__1 = e * .5f * q, fabs(static_cast<double>(d__1)))) {\n        goto L70;\n    }\n    e = d__;\n    d__ = p / q;\n    goto L80;\n\n    /* bisection */\n\n    L70: d__ = xm;\n    e = d__;\n\n    /* complete step */\n\n    L80: a = b;\n    fa = fb;\n    if (fabs(static_cast<double>(d__)) > tol1) {\n        b += d__;\n    }\n    if (fabs(static_cast<double>(d__)) <= tol1) {\n        b += d_sign(&tol1, &xm);\n    }\n    fb = (*f)(&b);\n    if (fb * (fc / fabs(static_cast<double>(fc))) > 0.f) {\n        goto L20;\n    }\n    goto L30;\n\n    /* done */\n\n    L90: ret_val = b;\n    return ret_val;\n} /* zeroin_ */\n\n\n\n#include <functional>\n#include <mutex>\n\n#ifndef NO_HPX\n#include <hpx/synchronization/spinlock.hpp>\nusing mutex_type = hpx::lcos::local::spinlock;\n#else\n#include <unordered_map>\n#include <memory>\n#include <cassert>\nusing mutex_type = std::mutex;\n#endif\n\nnamespace sedov {\n\nvoid solution(double time, double r, double rmax, double& d, double& v, double& p, int ndim) {\n\tint nstep = 10000;\n\tconstexpr int bw = 2;\n\tusing function_type = std::function<void(double,double&,double&,double&)>;\n\tusing map_type = std::unordered_map<double,std::shared_ptr<function_type>>;\n\n\tstatic map_type map;\n\tstatic mutex_type mutex;\n\n\n\tsed_real rho0 = 1.0;\n\tsed_real vel0 = 0.0;\n\tsed_real ener0 = 0.0;\n\tsed_real pres0 = 0.0;\n\tsed_real cs0 = 0.0;\n\tsed_real gamma = 7.0/5.0;\n\tsed_real omega = 0.0;\n\tsed_real eblast = 1.0;\n\tsed_real xgeom = sed_real(ndim);\n\n\tstd::vector<sed_real> xpos(nstep+2*bw);\n\tstd::vector<sed_real> den(nstep+2*bw);\n\tstd::vector<sed_real> ener(nstep+2*bw);\n\tstd::vector<sed_real> pres(nstep+2*bw);\n\tstd::vector<sed_real> vel(nstep+2*bw);\n\tstd::vector<sed_real> cs(nstep+2*bw);\n\n\tstd::vector<double> den1(nstep+2*bw);\n\tstd::vector<double> pres1(nstep+2*bw);\n\tstd::vector<double> vel1(nstep+2*bw);\n\n\tstd::shared_ptr<function_type> ptr;\n\n\tfor( int i = 0; i < nstep + 2*bw; i++) {\n\t\txpos[i] = (i - bw + 0.5)*rmax/(nstep);\n\t}\n\tnstep += bw;\n\n\tstd::unique_lock<mutex_type> lock(mutex);\n\tauto iter = map.find(time);\n\tif (iter == map.end()) {\n\t\tsed_real sed_time = time;\n\t\tprintf( \"Computing sedov solution\\n\");\n\t\tsed_1d__(&sed_time, &nstep, xpos.data() + bw, &eblast, &omega, &xgeom, &rho0,\n\t\t\t\t&vel0, &ener0, &pres0, &cs0, &gamma, den.data() + bw, ener.data() + bw,\n\t\t\t\tpres.data() + bw, vel.data() + bw, cs.data() + bw);\n\n\t\txpos[0] = -xpos[3];\n\t\tden[0] = den[3];\n\t\tener[0] = ener[3];\n\t\tpres[0] = pres[3];\n\t\tvel[0] = -vel[3];\n\t\tcs[0] = cs[3];\n\n\t\txpos[1] = -xpos[2];\n\t\tden[1] = den[2];\n\t\tener[1] = ener[2];\n\t\tpres[1] = pres[2];\n\t\tvel[1] = -vel[2];\n\t\tcs[1] = cs[2];\n\n#if defined(OCTOTIGER_HAVE_BOOST_MULTIPRECISION)\n\t\tstd::transform(den.begin(), den.end(), den1.begin(),\n\t\t\t[](sed_real v) { return v.convert_to<double>(); });\n\t\tstd::transform(vel.begin(), vel.end(), vel1.begin(),\n\t\t\t[](sed_real v) { return v.convert_to<double>(); });\n\t\tstd::transform(pres.begin(), pres.end(), pres1.begin(),\n\t\t\t[](sed_real v) { return v.convert_to<double>(); });\n#else\n\t\tstd::copy(den.begin(), den.end(), den1.begin());\n\t\tstd::copy(vel.begin(), vel.end(), vel1.begin());\n\t\tstd::copy(pres.begin(), pres.end(), pres1.begin());\n#endif\n\n\t\tfunction_type func = [nstep,rmax,den1,pres1,vel1,bw](double r, double& d, double& v, double & p) {\n\t\t\tdouble dr = rmax / (nstep);\n\t\t\tstd::array<int,4> i;\n\t\t\ti[1] = (r + (bw - 0.5)*dr) / dr;\n\t\t\ti[0] = i[1] - 1;\n\t\t\ti[2] = i[1] + 1;\n\t\t\ti[3] = i[1] + 2;\n\t\t\tdouble r0 = (r - (i[1]-bw + 0.5)*dr)/dr;\n\t//\t\tprintf( \"%i %e\\n\", i[0], r, dr );\n\t\t\tassert( i[0] >= 0 );\n\t\t\tassert( i[3] < int(vel1.size()));\n\t\t\tconst auto interp = [r0,i](const std::vector<double>& data) {\n\t\t\t\tdouble sum = 0.0;\n\t\t\t\tsum += (-0.5 * data[i[0]] + 1.5 * data[i[1]] - 1.5 * data[i[2]] + 0.5 * data[i[3]]) * r0 * r0 * r0;\n\t\t\t\tsum += (+1.0 * data[i[0]] - 2.5 * data[i[1]] + 2.0 * data[i[2]] - 0.5 * data[i[3]]) * r0 * r0;\n\t\t\t\tsum += (-0.5 * data[i[0]]                   +  0.5 * data[i[2]]) * r0;\n\t\t\t\tsum += data[i[1]];\n\t\t\t\treturn sum;\n\t\t\t};\n\n\t\t\td = interp(den1);\n\t\t\tv = interp(vel1);\n\t\t\tp = interp(pres1);\n\n\t\t};\n\n\t\tptr = std::make_shared<function_type>(std::move(func));\n\t\tmap[time] = ptr;\n\t\tlock.unlock();\n\t} else {\n\t\tlock.unlock();\n\t\tptr = iter->second;\n\t}\n\n\tconst auto& func = *(ptr);\n\n\tfunc(r, d, v, p);\n}\n\n}\n", "meta": {"hexsha": "6a666f6742a6b28797f8e46a16caf6fd5acf5b52", "size": 45347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_problems/blast/sedovf_c.cpp", "max_stars_repo_name": "cclauss/octotiger", "max_stars_repo_head_hexsha": "73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test_problems/blast/sedovf_c.cpp", "max_issues_repo_name": "cclauss/octotiger", "max_issues_repo_head_hexsha": "73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_problems/blast/sedovf_c.cpp", "max_forks_repo_name": "cclauss/octotiger", "max_forks_repo_head_hexsha": "73c3f2e5366e2c0b2d46a1f252b13f3b2f9b9171", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.018268467, "max_line_length": 103, "alphanum_fraction": 0.5516792732, "num_tokens": 15510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6310700799562348}}
{"text": "#ifndef InitCondLV_CC_\n#define InitCondLV_CC_\n/**\n * @file initcondlv.cc\n * @brief NPDE homework InitCondLV code\n * @author lfilippo, tille, jgacon, dcasati\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <iostream>\n#include <utility>\n\n#include \"../../../lecturecodes/Ode45/ode45.h\"\n\nnamespace InitCondLV {\n\n/* Compute the maps Phi(t,y0) and W(t,y0) at final time T.\n * Use initial data given by u0 and v0. */\n/* SAM_LISTING_BEGIN_1 */\nstd::pair<Eigen::Vector2d, Eigen::Matrix2d> PhiAndW(double u0, double v0,\n                                                    double T) {\n  // Save the values of Phi and W at time T in PaW.first and PaW.second resp.\n  std::pair<Eigen::Vector2d, Eigen::Matrix2d> PaW;\n\n  //====================\n  // Your code goes here\n  //====================\n  return PaW;\n}\n/* SAM_LISTING_END_1 */\n\n}  // namespace InitCondLV\n\n#endif  // #define InitCondLV_CC_\n", "meta": {"hexsha": "6bac13f0484782d6c218c12751c1af4777660c1f", "size": 908, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/InitCondLV/templates/initcondlv.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/InitCondLV/templates/initcondlv.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/InitCondLV/templates/initcondlv.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 25.2222222222, "max_line_length": 77, "alphanum_fraction": 0.6255506608, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7956581024858786, "lm_q1q2_score": 0.631041183971311}}
{"text": "///\n/// @author  Thomas Lehmann\n/// @file    factorial.cxx\n/// @brief   factorial function\n///\n/// Copyright (c) 2015 Thomas Lehmann\n///\n/// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n/// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\n/// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,\n/// and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in all copies\n/// or substantial portions of the Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n/// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n/// DAMAGES OR OTHER LIABILITY,\n/// 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 SOFTWARE.\n#include <generator/select.h>\n#include <math/big_integer.h>\n#include <math/big_integer_configurator.h>\n#include <performance/measurement.h>\n\n#include <boost/program_options.hpp>\n#include <vector>\n#include <cstdint>\n\n/// @struct options\n/// @brief parsed command line options\nstruct Options {\n    uint64_t max_n; ///! factorial: n!\n    bool all;       ///! when true showing each factorial\n};\n\n/// @param argc number of parameters\n/// @param argv array of parameters\n/// @param options where to store the parsed command line options\n/// @return true when all is fine and application can use the option(s).\nstatic bool parse(int argc, char** argv, Options& options) {\n    namespace po = boost::program_options;\n    po::options_description description(\"Allowed options for tool 'factorial'\");\n    description.add_options()\n        (\"help\", \"print this help\")\n        (\"n\", po::value<uint64_t>(&options.max_n)->default_value(100),\n         \"Calculating factorial: n! (default: 100)\")\n        (\"all\", po::value<bool>(&options.all)->default_value(true),\n         \"showing each factorials until 'n!' (default: true)\")\n        ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, description), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << description << std::endl;\n        return false;\n    }\n\n    return true;\n}\n\n/// Simple example demonstrating how to generate factorials.\n///\n/// @param argc number of parameters\n/// @param argv array of parameters\n/// @return 0 when succeeded, 1 when failed or when used the help\nint main(int argc, char** argv) {\n    std::cout << \"factorial tool (version \" << VERSION << \")\" << std::endl;\n\n    Options options;\n    // parsing command line options\n    if (!parse(argc, argv, options)) {\n        return 1;\n    }\n\n    // registering implementations\n    math::big_integer_configurator bic;\n    bic.configure();\n\n    math::big_integer bi = 1;\n    std::cout << options.max_n << \"!\" << std::endl << std::endl;\n\n    std::vector<math::big_integer> results;\n\n    const auto duration = performance::measure<std::milli>([&options, &bi, &results]() {\n        for (auto n = static_cast<uint64_t>(2); n <= options.max_n; ++n) {\n            bi *= math::big_integer(n);\n            if (options.all) {\n                results.push_back(bi);\n            }\n        }\n    });\n\n    if (!options.all) {\n        results.push_back(bi);\n    }\n\n    for (const auto& result: results) {\n        std::cout << result.to_string() << std::endl;\n    }\n\n    std::cout << std::endl;\n    std::cout << \" ... \" << bi.size() << \" digits.\" << std::endl;\n    std::cout << \" ... Calculation only took \" << duration << \"ms.\" << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "111decd2a3e15a82626a90e066300f8f3b17652d", "size": 3915, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "examples/factorial.cxx", "max_stars_repo_name": "Nachtfeuer/demo-cpp", "max_stars_repo_head_hexsha": "6449c99dd43ec862b02d6431fd59f443ba400f62", "max_stars_repo_licenses": ["MIT"], "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/factorial.cxx", "max_issues_repo_name": "Nachtfeuer/demo-cpp", "max_issues_repo_head_hexsha": "6449c99dd43ec862b02d6431fd59f443ba400f62", "max_issues_repo_licenses": ["MIT"], "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/factorial.cxx", "max_forks_repo_name": "Nachtfeuer/demo-cpp", "max_forks_repo_head_hexsha": "6449c99dd43ec862b02d6431fd59f443ba400f62", "max_forks_repo_licenses": ["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.2702702703, "max_line_length": 115, "alphanum_fraction": 0.6559386973, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6310411742679312}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file libs/numeric/ublasx/test/eps.cpp.\n *\n * \\brief Test suite for the \\c eps operation.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/numeric/ublasx/detail/debug.hpp>\n#include <boost/numeric/ublasx/operation/eps.hpp>\n#include <cmath>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n#include <limits>\n\n\nnamespace ublasx = boost::numeric::ublasx;\n\n\nconst float float_tol = ::std::numeric_limits<float>::epsilon()*2.0;\nconst double double_tol = ::std::numeric_limits<double>::epsilon()*2.0;\n\n\nBOOST_UBLASX_TEST_DEF( float_no_arg )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Float type - No arg\");\n\n    typedef float value_type;\n\n    value_type eps = ublasx::eps<value_type>();\n    value_type expect_eps = ::std::numeric_limits<value_type>::epsilon();\n\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK_CLOSE(eps, expect_eps, float_tol);\n}\n\n\nBOOST_UBLASX_TEST_DEF( float_scalar_arg )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Float type - Scalar arg\");\n\n    typedef float value_type;\n\n    value_type val;\n    value_type eps;\n    value_type expect_eps;\n\n\n    val = 0;\n    eps = ublasx::eps<value_type>(val);\n    expect_eps = ::std::numeric_limits<value_type>::denorm_min();\n    BOOST_UBLASX_DEBUG_TRACE(\"val = \" << val);\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK_CLOSE(eps, expect_eps, float_tol);\n\n    val = ::std::numeric_limits<value_type>::min();\n    eps = ublasx::eps<value_type>(val);\n    expect_eps = ::std::numeric_limits<value_type>::denorm_min();\n    BOOST_UBLASX_DEBUG_TRACE(\"val = \" << val);\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK_CLOSE(eps, expect_eps, float_tol);\n\n    val = ::std::numeric_limits<value_type>::min()/static_cast<value_type>(2);\n    eps = ublasx::eps<value_type>(val);\n    expect_eps = ::std::numeric_limits<value_type>::denorm_min();\n    BOOST_UBLASX_DEBUG_TRACE(\"val = \" << val);\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK_CLOSE(eps, expect_eps, float_tol);\n\n    val = ::std::numeric_limits<value_type>::infinity();\n    eps = ublasx::eps<value_type>(val);\n    BOOST_UBLASX_DEBUG_TRACE(\"val = \" << val);\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK(std::isnan(eps));\n\n    val = ::std::numeric_limits<value_type>::quiet_NaN();\n    eps = ublasx::eps<value_type>(val);\n    BOOST_UBLASX_DEBUG_TRACE(\"val = \" << val);\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK(std::isnan(eps));\n}\n\n\nBOOST_UBLASX_TEST_DEF( double_no_arg )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Double type - No arg\");\n\n    typedef double value_type;\n\n    value_type eps = ublasx::eps<value_type>();\n    value_type expect_eps = ::std::numeric_limits<value_type>::epsilon();\n\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK_CLOSE(eps, expect_eps, double_tol);\n}\n\n\nBOOST_UBLASX_TEST_DEF( double_scalar_arg )\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Case: Double type - Scalar arg\");\n\n    typedef double value_type;\n\n    value_type val;\n    value_type eps;\n    value_type expect_eps;\n\n\n    val = 0;\n    eps = ublasx::eps<value_type>(val);\n    expect_eps = ::std::numeric_limits<value_type>::denorm_min();\n    BOOST_UBLASX_DEBUG_TRACE(\"val = \" << val);\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK_CLOSE(eps, expect_eps, double_tol);\n\n    val = ::std::numeric_limits<value_type>::min();\n    eps = ublasx::eps<value_type>(val);\n    expect_eps = ::std::numeric_limits<value_type>::denorm_min();\n    BOOST_UBLASX_DEBUG_TRACE(\"val = \" << val);\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK_CLOSE(eps, expect_eps, double_tol);\n\n    val = ::std::numeric_limits<value_type>::min()/static_cast<value_type>(2);\n    eps = ublasx::eps<value_type>(val);\n    expect_eps = ::std::numeric_limits<value_type>::denorm_min();\n    BOOST_UBLASX_DEBUG_TRACE(\"val = \" << val);\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK_CLOSE(eps, expect_eps, double_tol);\n\n    val = ::std::numeric_limits<value_type>::infinity();\n    eps = ublasx::eps<value_type>(val);\n    BOOST_UBLASX_DEBUG_TRACE(\"val = \" << val);\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK(std::isnan(eps));\n\n    val = ::std::numeric_limits<value_type>::quiet_NaN();\n    eps = ublasx::eps<value_type>(val);\n    BOOST_UBLASX_DEBUG_TRACE(\"val = \" << val);\n    BOOST_UBLASX_DEBUG_TRACE(\"eps = \" << eps);\n    BOOST_UBLASX_TEST_CHECK(std::isnan(eps));\n}\n\n\nint main()\n{\n    BOOST_UBLASX_DEBUG_TRACE(\"Test Suite: 'eps' operations\");\n\n    BOOST_UBLASX_TEST_BEGIN();\n\n    BOOST_UBLASX_TEST_DO( float_no_arg )\n    BOOST_UBLASX_TEST_DO( float_scalar_arg )\n    BOOST_UBLASX_TEST_DO( double_no_arg )\n    BOOST_UBLASX_TEST_DO( double_scalar_arg )\n\n    BOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "0dd9259b20a0c088b0f9754cf92f99b9d216b455", "size": 5132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/eps.cpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "libs/numeric/ublasx/test/eps.cpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "libs/numeric/ublasx/test/eps.cpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 30.9156626506, "max_line_length": 78, "alphanum_fraction": 0.6968043648, "num_tokens": 1485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6310395254353367}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Dense>\n#include <conio.h>\n#include<vector>\nusing namespace std;\nusing namespace Eigen;\n\nMatrixXd Data(string fileToOpen)\n{\n\n    vector<double> 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<Matrix<double, Dynamic, Dynamic, RowMajor>>(matrixEntries.data(), matrixRowNumber, matrixEntries.size() / matrixRowNumber);\n\n}\n\nvoid InvertirGaussJordan()\n{\n    MatrixXd m = Data(\"Texto.txt\"), I(m.rows(),m.rows());\n    int c = m.rows();\n    //Se crea la matriz identidad\n    for (int x = 0; x < c; x++)\n    {\n        for (int y = 0; y < c; y++)\n        {\n            I(x, y) = 0;\n            if (x == y)\n            {\n                I(x, y) = 1;\n\n            }\n        }\n    }\n    cout << \"Matriz inicial:\\n \" << m << endl;\n    cout << \"Matriz identidad:\\n \" << I << endl;\n    cout << m.cols()<<endl;  \n    /*Para lograr que la diagonal de la matriz sea 1, se divide cada elemento de la diagonal por el mismo y por su\n    fila correspondiente, igual con la matriz identidad.*/\n    for (int x = 0; x < c; x++)\n    {\n        float v = m(x, x);\n\n        for (int y = 0; y < c; y++)\n        {\n\n            m(x, y) = m(x, y)*(1/v);\n            I(x, y) = I(x, y)*(1/v);\n        }\n\n\n        for (int j = 0; j < c; j++)\n        {\n            //verifico no estar en diagonal y empiezo a hacer GJ:\n            if (x != j)\n            {\n                float  s = m(j, x);\n                for (int k = 0; k < c; k++)\n                {\n                    m(j, k) = m(j, k) - (s * m(x, k));\n                    I(j, k) = I(j, k) - (s * I(x, k));\n                }\n\n\n            }\n\n\n\n\n        }\n    }\n    cout << \"Inversa:\\n \" << I << endl;\n    fstream archivo;\n    archivo.open(\"Texto.txt\", ios::app);\n    if (archivo.is_open())\n    {\n        archivo <<\"La inversa es: \\n\"<< I;\n        archivo.close();\n    }\n}\n   \nint determinantecofactor(Matrix2d x)\n{\n    int resultado;\n    resultado = x(0, 0) * x(1, 1) - x(0, 1) * (1, 0);\n    return resultado;\n}\n    \nvoid determinante(MatrixXd m)\n{\n    //intento de una funcion recursiva que calcula el determinante por cofactores.\n     if (m.rows() == 2)\n     {\n         return determinantecofactor(m);\n     }\n    vector<int> f;\n   \n        for (int i = 0; i < m.rows(); i++)\n        {\n            for (int j = 0; j < m.rows(); j++)\n            {\n                for (int k = 0; k < m.rows(); k++)\n                {\n                    if ((j == i) && (k == 0))\n                    {\n                        continue;\n                        \n                    }\n                    MatrixXd m_l(m.rows() - 1, m.rows() - 1);\n                    m_l(l,i) = m(j, k);\n                    f.push_back(m(j, k));\n                }\n\n            }\n        }\n    \n        cout << int(f.size()) << endl;\n}\nint main() \n{\n\n   \n    InvertirGaussJordan();\n    determinante(Data(\"Texto.txt\"));\n    return 0;\n\n}", "meta": {"hexsha": "dc0a2c913af7e4f76f16a3f2182be19bc398e77f", "size": 3293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "soluciones/ja.tavera/tarea2/solucion.cpp", "max_stars_repo_name": "japeinado/FISI2028-202120", "max_stars_repo_head_hexsha": "6b16a779f3e34bcbf35d8b5e0ea345cf50ffdadd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T19:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:26:41.000Z", "max_issues_repo_path": "soluciones/ja.tavera/tarea2/solucion.cpp", "max_issues_repo_name": "japeinado/FISI2028-202120", "max_issues_repo_head_hexsha": "6b16a779f3e34bcbf35d8b5e0ea345cf50ffdadd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-09-18T01:33:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T00:11:45.000Z", "max_forks_repo_path": "soluciones/ja.tavera/tarea2/solucion.cpp", "max_forks_repo_name": "japeinado/FISI2028-202120", "max_forks_repo_head_hexsha": "6b16a779f3e34bcbf35d8b5e0ea345cf50ffdadd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-09-17T22:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T19:59:49.000Z", "avg_line_length": 22.7103448276, "max_line_length": 138, "alphanum_fraction": 0.4564227148, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475683211324, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.6309865733456589}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <iostream>\n\nvoid gradient_descent_test(const std::function<double(const double)> f, const std::function<double(const double)> gf, const double x0, double & fx, double & x, std::vector<double> & intervals, std::vector<double> & values, std::vector<double> & minima){\n//    for (int i = 0; i<intervals.size(); i++) {\n//        std::cout << \" \" << intervals[i];\n//    }\n    //std::cout << std::endl;\n    int max_iter = 100;\n    //double alpha = 0.02;\n    double alpha = 0.02; // CHANGE THIS BACK\n    double tau,g;\n    double min = 0.0;\n    double max = 1.0;\n    double tol = 1e-6;\n    double xmin = x0;\n    double xmax = x0;\n    x = x0;\n    \n    double prev_x = 10000000.0;\n    int iter = 0;\n    bool stop = false;\n    double x_candidate,fx_candidate;\n    g = 100.0;\n    //std::cout << \"run\" << std::endl;\n    int in_existing_interval = -1;\n    assert(iter<max_iter && !stop && abs(x-prev_x)>tol);\n    while (iter<max_iter && !stop && abs(x-prev_x)>tol) {\n        xmin = std::min(xmin,x);\n        xmax = std::max(xmax,x);\n        \n        for (int mm = 0; mm < (intervals.size()/2); mm++) {\n            if ((x >= (intervals[2*mm]-1e-6)) && (x <= (intervals[2*mm+1]+1e-6)) ){\n                fx = values[mm];\n                x = minima[mm];\n                in_existing_interval = mm;\n                break;\n             //   in_existing_interval = true;\n            }\n        }\n        if (in_existing_interval>-1) {\n            break;\n        }\n        if (iter==0) {\n            fx = f(x);\n        }\n//        if (fx<-0.1) {\n//            break;\n//        }\n        \n        \n        \n        g = gf(x);\n        //std::cout << g << std::endl;\n        tau = alpha;\n        prev_x = x;\n        for (int div = 1; div<10; div++) {\n            iter = iter + 1;\n            assert(iter<max_iter);\n            x_candidate = x - tau* ( (double) (g > 0) - (g < 0));\n            x_candidate = std::max(std::min(x_candidate,1.0),0.0);\n            fx_candidate = f(x_candidate);\n            if ((fx_candidate-fx)<(0.5*(x_candidate - x)*g)) {\n                x = x_candidate;\n                fx = fx_candidate;\n                //std::cout << div << std::endl;\n                break;\n            }\n            tau = 0.5*tau;\n            if (div==9) {\n                //std::cout << div << std::endl;\n                stop = true;\n            }\n        }\n    }\n    \n    \n    if (in_existing_interval==-1) {\n        // we have discovered a new interval\n        intervals.push_back(xmin);\n        intervals.push_back(xmax);\n        values.push_back(fx);\n        minima.push_back(x);\n    }else{\n        // grow interval\n        intervals[2*in_existing_interval] = std::min(intervals[2*in_existing_interval],xmin);\n        intervals[2*in_existing_interval+1] = std::max(intervals[2*in_existing_interval+1],xmax);\n    }\n    \n  //  std::cout << iter << std::endl;\n    \n    \n//    for (int i = 0; i<intervals.size(); i++) {\n//        std::cout << \" \" << intervals[i];\n//    }\n//    std::cout << std::endl;\n    \n}\n", "meta": {"hexsha": "bda857d7562a11e1ab44386fd8410df6a573ab61", "size": 3043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/gradient_descent_test.cpp", "max_stars_repo_name": "sgsellan/swept-volumes", "max_stars_repo_head_hexsha": "12d1ec636e1f64dfd9cd0c13639e15ab9de67284", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2021-06-19T16:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T23:56:15.000Z", "max_issues_repo_path": "include/gradient_descent_test.cpp", "max_issues_repo_name": "sgsellan/swept-volumes", "max_issues_repo_head_hexsha": "12d1ec636e1f64dfd9cd0c13639e15ab9de67284", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gradient_descent_test.cpp", "max_forks_repo_name": "sgsellan/swept-volumes", "max_forks_repo_head_hexsha": "12d1ec636e1f64dfd9cd0c13639e15ab9de67284", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-19T15:27:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-30T13:01:28.000Z", "avg_line_length": 30.43, "max_line_length": 253, "alphanum_fraction": 0.4791324351, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.7371581684030624, "lm_q1q2_score": 0.6308976747653159}}
{"text": "/**\n * @file loss_functions_test.cpp\n * @author Dakshit Agrawal\n * @author Sourabh Varshney\n * @author Atharva Khandait\n * @author Saksham Rastogi\n *\n * Tests for loss functions in mlpack::methods::ann:loss_functions.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/loss_functions/kl_divergence.hpp>\n#include <mlpack/methods/ann/loss_functions/earth_mover_distance.hpp>\n#include <mlpack/methods/ann/loss_functions/mean_squared_error.hpp>\n#include <mlpack/methods/ann/loss_functions/sigmoid_cross_entropy_error.hpp>\n#include <mlpack/methods/ann/loss_functions/cross_entropy_error.hpp>\n#include <mlpack/methods/ann/loss_functions/reconstruction_loss.hpp>\n#include <mlpack/methods/ann/loss_functions/mean_squared_logarithmic_error.hpp>\n#include <mlpack/methods/ann/loss_functions/mean_bias_error.hpp>\n#include <mlpack/methods/ann/loss_functions/dice_loss.hpp>\n#include <mlpack/methods/ann/loss_functions/log_cosh_loss.hpp>\n#include <mlpack/methods/ann/init_rules/nguyen_widrow_init.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n#include \"ann_test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(LossFunctionsTest);\n\n/**\n * Simple KL Divergence test.  The loss should be zero if input = target.\n */\nBOOST_AUTO_TEST_CASE(SimpleKLDivergenceTest)\n{\n  arma::mat input, target, output;\n  double loss;\n  KLDivergence<> module(true);\n\n  // Test the Forward function.  Loss should be 0 if input = target.\n  input = arma::ones(10, 1);\n  target = arma::ones(10, 1);\n  loss = module.Forward(std::move(input), std::move(target));\n  BOOST_REQUIRE_SMALL(loss, 0.00001);\n}\n\n/*\n * Simple test for the mean squared logarithmic error function.\n */\nBOOST_AUTO_TEST_CASE(SimpleMeanSquaredLogarithmicErrorTest)\n{\n  arma::mat input, output, target;\n  MeanSquaredLogarithmicError<> module;\n\n  // Test the Forward function on a user generator input and compare it against\n  // the manually calculated result.\n  input = arma::zeros(1, 8);\n  target = arma::zeros(1, 8);\n  double error = module.Forward(std::move(input), std::move(target));\n  BOOST_REQUIRE_SMALL(error, 0.00001);\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(target), std::move(output));\n  // The output should be equal to 0.\n  CheckMatrices(input, output);\n  BOOST_REQUIRE_EQUAL(output.n_rows, input.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input.n_cols);\n\n  // Test the error function on a single input.\n  input = arma::mat(\"2\");\n  target = arma::mat(\"3\");\n  error = module.Forward(std::move(input), std::move(target));\n  BOOST_REQUIRE_CLOSE(error, 0.082760974810151655, 0.001);\n\n  // Test the Backward function on a single input.\n  module.Backward(std::move(input), std::move(target), std::move(output));\n  BOOST_REQUIRE_CLOSE(arma::accu(output), -0.1917880483011872, 0.001);\n  BOOST_REQUIRE_EQUAL(output.n_elem, 1);\n}\n\n/**\n * Test to check KL Divergence loss function when we take mean.\n */\nBOOST_AUTO_TEST_CASE(KLDivergenceMeanTest)\n{\n  arma::mat input, target, output;\n  double loss;\n  KLDivergence<> module(true);\n\n  // Test the Forward function.\n  input = arma::mat(\"1 1 1 1 1 1 1 1 1 1\");\n  target = arma::exp(arma::mat(\"2 1 1 1 1 1 1 1 1 1\"));\n\n  loss = module.Forward(std::move(input), std::move(target));\n  BOOST_REQUIRE_CLOSE_FRACTION(loss, -1.1 , 0.00001);\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(target), std::move(output));\n  BOOST_REQUIRE_CLOSE_FRACTION(arma::as_scalar(output), -0.1, 0.00001);\n}\n\n/**\n * Test to check KL Divergence loss function when we do not take mean.\n */\nBOOST_AUTO_TEST_CASE(KLDivergenceNoMeanTest)\n{\n  arma::mat input, target, output;\n  double loss;\n  KLDivergence<> module(false);\n\n  // Test the Forward function.\n  input = arma::mat(\"1 1 1 1 1 1 1 1 1 1\");\n  target = arma::exp(arma::mat(\"2 1 1 1 1 1 1 1 1 1\"));\n\n  loss = module.Forward(std::move(input), std::move(target));\n  BOOST_REQUIRE_CLOSE_FRACTION(loss, -11, 0.00001);\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(target), std::move(output));\n  BOOST_REQUIRE_CLOSE_FRACTION(arma::as_scalar(output), -1, 0.00001);\n}\n\n/*\n * Simple test for the mean squared error performance function.\n */\nBOOST_AUTO_TEST_CASE(SimpleMeanSquaredErrorTest)\n{\n  arma::mat input, output, target;\n  MeanSquaredError<> module;\n\n  // Test the Forward function on a user generator input and compare it against\n  // the manually calculated result.\n  input = arma::mat(\"1.0 0.0 1.0 0.0 -1.0 0.0 -1.0 0.0\");\n  target = arma::zeros(1, 8);\n  double error = module.Forward(std::move(input), std::move(target));\n  BOOST_REQUIRE_EQUAL(error, 0.5);\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(target), std::move(output));\n  // We subtract a zero vector, so according to the used backward formula:\n  // output = 2 * (input - target) / target.n_cols,\n  // output * nofColumns / 2 should be equal to input.\n  CheckMatrices(input, output * output.n_cols / 2);\n  BOOST_REQUIRE_EQUAL(output.n_rows, input.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input.n_cols);\n\n  // Test the error function on a single input.\n  input = arma::mat(\"2\");\n  target = arma::mat(\"3\");\n  error = module.Forward(std::move(input), std::move(target));\n  BOOST_REQUIRE_EQUAL(error, 1.0);\n\n  // Test the Backward function on a single input.\n  module.Backward(std::move(input), std::move(target), std::move(output));\n  // Test whether the output is negative.\n  BOOST_REQUIRE_EQUAL(arma::accu(output), -2);\n  BOOST_REQUIRE_EQUAL(output.n_elem, 1);\n}\n\n/*\n * Simple test for the cross-entropy error performance function.\n */\nBOOST_AUTO_TEST_CASE(SimpleCrossEntropyErrorTest)\n{\n  arma::mat input1, input2, output, target1, target2;\n  CrossEntropyError<> module(1e-6);\n\n  // Test the Forward function on a user generator input and compare it against\n  // the manually calculated result.\n  input1 = arma::mat(\"0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5\");\n  target1 = arma::zeros(1, 8);\n  double error1 = module.Forward(std::move(input1), std::move(target1));\n  BOOST_REQUIRE_SMALL(error1 - 8 * std::log(2), 2e-5);\n\n  input2 = arma::mat(\"0 1 1 0 1 0 0 1\");\n  target2 = arma::mat(\"0 1 1 0 1 0 0 1\");\n  double error2 = module.Forward(std::move(input2), std::move(target2));\n  BOOST_REQUIRE_SMALL(error2, 1e-5);\n\n  // Test the Backward function.\n  module.Backward(std::move(input1), std::move(target1), std::move(output));\n  for (double el : output)\n  {\n    // For the 0.5 constant vector we should get 1 / (1 - 0.5) = 2 everywhere.\n    BOOST_REQUIRE_SMALL(el - 2, 5e-6);\n  }\n  BOOST_REQUIRE_EQUAL(output.n_rows, input1.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input1.n_cols);\n\n  module.Backward(std::move(input2), std::move(target2), std::move(output));\n  for (size_t i = 0; i < 8; ++i)\n  {\n    double el = output.at(0, i);\n    if (input2.at(i) == 0)\n      BOOST_REQUIRE_SMALL(el - 1, 2e-6);\n    else\n      BOOST_REQUIRE_SMALL(el + 1, 2e-6);\n  }\n  BOOST_REQUIRE_EQUAL(output.n_rows, input2.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input2.n_cols);\n}\n\n/**\n * Simple test for the Sigmoid Cross Entropy performance function.\n */\nBOOST_AUTO_TEST_CASE(SimpleSigmoidCrossEntropyErrorTest)\n{\n  arma::mat input1, input2, input3, output, target1,\n            target2, target3, expectedOutput;\n  SigmoidCrossEntropyError<> module;\n\n  // Test the Forward function on a user generator input and compare it against\n  // the calculated result.\n  input1 = arma::mat(\"0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5\");\n  target1 = arma::zeros(1, 8);\n  double error1 = module.Forward(std::move(input1), std::move(target1));\n  double expected = 0.97407699;\n  // Value computed using tensorflow.\n  BOOST_REQUIRE_SMALL(error1 / input1.n_elem - expected, 1e-7);\n\n  input2 = arma::mat(\"1 2 3 4 5\");\n  target2 = arma::mat(\"0 0 1 0 1\");\n  double error2 = module.Forward(std::move(input2), std::move(target2));\n  expected = 1.5027283;\n  BOOST_REQUIRE_SMALL(error2 / input2.n_elem - expected, 1e-6);\n\n  input3 = arma::mat(\"0 -1 -1 0 -1 0 0 -1\");\n  target3 = arma::mat(\"0 -1 -1 0 -1 0 0 -1\");\n  double error3 = module.Forward(std::move(input3), std::move(target3));\n  expected = 0.00320443;\n  BOOST_REQUIRE_SMALL(error3 / input3.n_elem - expected, 1e-6);\n\n  // Test the Backward function.\n  module.Backward(std::move(input1), std::move(target1), std::move(output));\n  expected = 0.62245929;\n  for (size_t i = 0; i < output.n_elem; i++)\n    BOOST_REQUIRE_SMALL(output(i) - expected, 1e-5);\n  BOOST_REQUIRE_EQUAL(output.n_rows, input1.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input1.n_cols);\n\n  expectedOutput = arma::mat(\n      \"0.7310586 0.88079709 -0.04742587 0.98201376 -0.00669285\");\n  module.Backward(std::move(input2), std::move(target2), std::move(output));\n  for (size_t i = 0; i < output.n_elem; i++)\n    BOOST_REQUIRE_SMALL(output(i) - expectedOutput(i), 1e-5);\n  BOOST_REQUIRE_EQUAL(output.n_rows, input2.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input2.n_cols);\n\n  module.Backward(std::move(input3), std::move(target3), std::move(output));\n  expectedOutput = arma::mat(\"0.5 1.2689414\");\n  for (size_t i = 0; i < 8; ++i)\n  {\n    double el = output.at(0, i);\n    if (std::abs(input3.at(i) - 0.0) < 1e-5)\n      BOOST_REQUIRE_SMALL(el - expectedOutput[0], 2e-6);\n    else\n      BOOST_REQUIRE_SMALL(el - expectedOutput[1], 2e-6);\n  }\n  BOOST_REQUIRE_EQUAL(output.n_rows, input3.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input3.n_cols);\n}\n\n/**\n * Simple test for the Earth Mover Distance Layer.\n */\nBOOST_AUTO_TEST_CASE(SimpleEarthMoverDistanceLayerTest)\n{\n  arma::mat input1, input2, output, target1, target2, expectedOutput;\n  EarthMoverDistance<> module;\n\n  // Test the Forward function on a user generator input and compare it against\n  // the manually calculated result.\n  input1 = arma::mat(\"0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5\");\n  target1 = arma::zeros(1, 8);\n  double error1 = module.Forward(std::move(input1), std::move(target1));\n  double expected = 0.0;\n  BOOST_REQUIRE_SMALL(error1 / input1.n_elem - expected, 1e-7);\n\n  input2 = arma::mat(\"1 2 3 4 5\");\n  target2 = arma::mat(\"1 0 1 0 1\");\n  double error2 = module.Forward(std::move(input2), std::move(target2));\n  expected = -1.8;\n  BOOST_REQUIRE_SMALL(error2 / input2.n_elem - expected, 1e-6);\n\n  // Test the Backward function.\n  module.Backward(std::move(input1), std::move(target1), std::move(output));\n  expected = 0.0;\n  for (size_t i = 0; i < output.n_elem; i++)\n    BOOST_REQUIRE_SMALL(output(i) - expected, 1e-5);\n  BOOST_REQUIRE_EQUAL(output.n_rows, input1.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input1.n_cols);\n\n  expectedOutput = arma::mat(\"-1 0 -1 0 -1\");\n  module.Backward(std::move(input2), std::move(target2), std::move(output));\n  for (size_t i = 0; i < output.n_elem; i++)\n    BOOST_REQUIRE_SMALL(output(i) - expectedOutput(i), 1e-5);\n  BOOST_REQUIRE_EQUAL(output.n_rows, input2.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input2.n_cols);\n}\n\n/*\n * Mean Squared Error numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientMeanSquaredErrorTest)\n{\n  // Linear function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(10, 1);\n      target = arma::randu(2, 1);\n\n      model = new FFN<MeanSquaredError<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<Linear<> >(10, 2);\n      model->Add<SigmoidLayer<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      arma::mat output;\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<MeanSquaredError<>, NguyenWidrowInitialization>* model;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/*\n * Reconstruction Loss numerical gradient test.\n */\nBOOST_AUTO_TEST_CASE(GradientReconstructionLossTest)\n{\n  // Linear function gradient instantiation.\n  struct GradientFunction\n  {\n    GradientFunction()\n    {\n      input = arma::randu(10, 1);\n      target = arma::randu(2, 1);\n\n      model = new FFN<ReconstructionLoss<>, NguyenWidrowInitialization>();\n      model->Predictors() = input;\n      model->Responses() = target;\n      model->Add<IdentityLayer<> >();\n      model->Add<Linear<> >(10, 2);\n      model->Add<SigmoidLayer<> >();\n    }\n\n    ~GradientFunction()\n    {\n      delete model;\n    }\n\n    double Gradient(arma::mat& gradient) const\n    {\n      arma::mat output;\n      double error = model->Evaluate(model->Parameters(), 0, 1);\n      model->Gradient(model->Parameters(), 0, gradient, 1);\n      return error;\n    }\n\n    arma::mat& Parameters() { return model->Parameters(); }\n\n    FFN<ReconstructionLoss<>, NguyenWidrowInitialization>* model;\n    arma::mat input, target;\n  } function;\n\n  BOOST_REQUIRE_LE(CheckGradient(function), 1e-4);\n}\n\n/*\n * Simple test for the dice loss function.\n */\nBOOST_AUTO_TEST_CASE(DiceLossTest)\n{\n  arma::mat input1, input2, target, output;\n  double loss;\n  DiceLoss<> module;\n\n  // Test the Forward function. Loss should be 0 if input = target.\n  input1 = arma::ones(10, 1);\n  target = arma::ones(10, 1);\n  loss = module.Forward(std::move(input1), std::move(target));\n  BOOST_REQUIRE_SMALL(loss, 0.00001);\n\n  // Test the Forward function. Loss should be 0.185185185.\n  input2 = arma::ones(10, 1) * 0.5;\n  loss = module.Forward(std::move(input2), std::move(target));\n  BOOST_REQUIRE_CLOSE(loss, 0.185185185, 0.00001);\n\n  // Test the Backward function for input = target.\n  module.Backward(std::move(input1), std::move(target), std::move(output));\n  for (double el : output)\n  {\n    // For input = target we should get 0.0 everywhere.\n    BOOST_REQUIRE_CLOSE(el, 0.0, 0.00001);\n  }\n  BOOST_REQUIRE_EQUAL(output.n_rows, input1.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input1.n_cols);\n\n  // Test the Backward function.\n  module.Backward(std::move(input2), std::move(target), std::move(output));\n  for (double el : output)\n  {\n    // For the 0.5 constant vector we should get -0.0877914951989026 everywhere.\n    BOOST_REQUIRE_CLOSE(el, -0.0877914951989026, 0.00001);\n  }\n  BOOST_REQUIRE_EQUAL(output.n_rows, input2.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input2.n_cols);\n}\n\n/*\n * Simple test for the mean bias error performance function.\n */\nBOOST_AUTO_TEST_CASE(SimpleMeanBiasErrorTest)\n{\n  arma::mat input, output, target;\n  MeanBiasError<> module;\n\n  // Test the Forward function on a user generator input and compare it against\n  // the manually calculated result.\n  input = arma::mat(\"1.0 0.0 1.0 -1.0 -1.0 0.0 -1.0 0.0\");\n  target = arma::zeros(1, 8);\n  double error = module.Forward(std::move(input), std::move(target));\n  BOOST_REQUIRE_EQUAL(error, 0.125);\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(target), std::move(output));\n  // We should get a vector with -1 everywhere.\n  for (double el : output)\n  {\n    BOOST_REQUIRE_EQUAL(el, -1);\n  }\n  BOOST_REQUIRE_EQUAL(output.n_rows, input.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input.n_cols);\n\n  // Test the error function on a single input.\n  input = arma::mat(\"2\");\n  target = arma::mat(\"3\");\n  error = module.Forward(std::move(input), std::move(target));\n  BOOST_REQUIRE_EQUAL(error, 1.0);\n\n  // Test the Backward function on a single input.\n  module.Backward(std::move(input), std::move(target), std::move(output));\n  // Test whether the output is negative.\n  BOOST_REQUIRE_EQUAL(arma::accu(output), -1);\n  BOOST_REQUIRE_EQUAL(output.n_elem, 1);\n}\n\n/**\n * Simple test for the Log-Hyperbolic-Cosine loss function.\n */\nBOOST_AUTO_TEST_CASE(LogCoshLossTest)\n{\n  arma::mat input, target, output;\n  double loss;\n  LogCoshLoss<> module(2);\n\n  // Test the Forward function. Loss should be 0 if input = target.\n  input = arma::ones(10, 1);\n  target = arma::ones(10, 1);\n  loss = module.Forward(std::move(input), std::move(target));\n  BOOST_REQUIRE_EQUAL(loss, 0);\n\n  // Test the Backward function for input = target.\n  module.Backward(std::move(input), std::move(target), std::move(output));\n  for (double el : output)\n  {\n    // For input = target we should get 0.0 everywhere.\n    BOOST_REQUIRE_CLOSE(el, 0.0, 1e-5);\n  }\n\n  BOOST_REQUIRE_EQUAL(output.n_rows, input.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input.n_cols);\n\n  // Test the Forward function. Loss should be 0.546621.\n  input = arma::mat(\"1 2 3 4 5\");\n  target = arma::mat(\"1 2.4 3.4 4.2 5.5\");\n  loss = module.Forward(std::move(input), std::move(target));\n  BOOST_REQUIRE_CLOSE(loss, 0.546621, 1e-3);\n\n  // Test the Backward function.\n  module.Backward(std::move(input), std::move(target), std::move(output));\n  BOOST_REQUIRE_CLOSE(arma::accu(output), 2.46962, 1e-3);\n  BOOST_REQUIRE_EQUAL(output.n_rows, input.n_rows);\n  BOOST_REQUIRE_EQUAL(output.n_cols, input.n_cols);\n}\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "cdcb4661702c2ba9d3b18a93cd547fb4cbb88a20", "size": 17335, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/loss_functions_test.cpp", "max_stars_repo_name": "mhmohona/mlpack", "max_stars_repo_head_hexsha": "e2ba6cf75bcacb47d6f3ca9fb31d5cb1e48d095a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/loss_functions_test.cpp", "max_issues_repo_name": "mhmohona/mlpack", "max_issues_repo_head_hexsha": "e2ba6cf75bcacb47d6f3ca9fb31d5cb1e48d095a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/loss_functions_test.cpp", "max_forks_repo_name": "mhmohona/mlpack", "max_forks_repo_head_hexsha": "e2ba6cf75bcacb47d6f3ca9fb31d5cb1e48d095a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7256809339, "max_line_length": 80, "alphanum_fraction": 0.6959907701, "num_tokens": 5060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6308976688660538}}
{"text": "#include <mass.h>\n#include <cmath>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n\nBOOST_AUTO_TEST_SUITE(mass);\n\nBOOST_AUTO_TEST_CASE(cone_bounding_test)\n{\n  // Values for outer bounding cylinder -- given by bottom radius\n  mass::Properties<float> O;\n\n  // Values for inner bounding cylinder -- given by bottom radius\n  ;\n\n  // Values for conical solid\n  ;\n  \n  float const rho = 1.0f;  // density\n  float       a   = 2.0f;  // bottom radius\n  float const b   = 1.0f;  // top radius\n  float const h   = 1.0f;  // height\n  \n  // Compute inner bounding cylinder -- Never changes!!! \n\tmass::Properties<float> I = compute_cylinder(rho, b, h/2.0f);\n  I = translate_to_model_frame(0.0f, h/2.0f, 0.0f, I);\n  \n  float old_Cy = 0.0f;\n  \n  for ( int i = 0 ; i < 9 ;++i)\n  {\n    a -= 0.1f;  // We are schrinking bottom radius of conical solid\n    \n    // Compute outer bounding cylinder \n    mass::Properties<float> O = compute_cylinder(rho, a, h/2.0f);\n    O = translate_to_model_frame(0.0f, h/2.0f, 0.0f, O);\n        \n    mass::Properties<float> C = compute_conical_solid(rho, a, b, h );\n        \n    \n    BOOST_CHECK( !C.is_body_space() );  \n    BOOST_CHECK(  C.is_model_space() );  \n\n    // Verify that the mass are bounded by the cylinders\n    BOOST_CHECK( I.m_m < C.m_m  );\n    BOOST_CHECK( C.m_m < O.m_m  );\n\n    // Verify that the xx inertia products are bounded\n    BOOST_CHECK( I.m_Ixx < C.m_Ixx );\n    BOOST_CHECK( C.m_Ixx < O.m_Ixx );\n    \n    // Verify that the yy inertia products are bounded\n    BOOST_CHECK( I.m_Iyy < C.m_Iyy );\n    BOOST_CHECK( C.m_Iyy < O.m_Iyy );\n\n    // Verify that the zz inertia products are the same as teh xx values\n    BOOST_CHECK_CLOSE(C.m_Ixx, C.m_Izz, 0.01f);\n    \n    // Test if center of mass in x-z plane are correct\n    BOOST_CHECK_CLOSE(C.m_x, 0.0f, 0.01f);\n    BOOST_CHECK_CLOSE(C.m_z, 0.0f, 0.01f);\n\n    // Test if center of mass of conical is lower than the cylinders\n    BOOST_CHECK(C.m_y < O.m_y);\n\n    // As bottom radius is increas center of mass should rise up moving closer and closer towards center of mass of the boudning cylinders.\n    BOOST_CHECK(C.m_y > old_Cy);\n    old_Cy = C.m_y;\n  }\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "337c9acacfa9b8e55601cf13755d3e89f2882155", "size": 2331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_conical/mass_conical.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_conical/mass_conical.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/SIMULATION/MASS/unit_tests/mass_conical/mass_conical.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5063291139, "max_line_length": 139, "alphanum_fraction": 0.6602316602, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6308976540400273}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_LOG_DIFF_EXP_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_LOG_DIFF_EXP_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/scal/fun/log1m_exp.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <boost/math/tools/promotion.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * The natural logarithm of the difference of the natural exponentiation\n * of x and the natural exponentiation of y\n *\n * This function is only defined for x >= y\n *\n *\n   \\f[\n   \\mbox{log\\_diff\\_exp}(x, y) =\n   \\begin{cases}\n     \\textrm{NaN} & \\mbox{if } x < y\\\\\n     \\ln(\\exp(x)-\\exp(y)) & \\mbox{if } x \\geq y \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{log\\_diff\\_exp}(x, y)}{\\partial x} =\n   \\begin{cases}\n     \\textrm{NaN} & \\mbox{if } x \\leq y\\\\\n     \\frac{\\exp(x)}{\\exp(x)-\\exp(y)} & \\mbox{if } x > y \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{log\\_diff\\_exp}(x, y)}{\\partial y} =\n   \\begin{cases}\n     \\textrm{NaN} & \\mbox{if } x \\leq y\\\\\n     -\\frac{\\exp(y)}{\\exp(x)-\\exp(y)} & \\mbox{if } x > y \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n *\n */\ntemplate <typename T1, typename T2>\ninline return_type_t<T1, T2> log_diff_exp(const T1 x, const T2 y) {\n  if (x <= y)\n    return (x < INFTY && x == y) ? NEGATIVE_INFTY : NOT_A_NUMBER;\n  return x + log1m_exp(y - x);\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "3e7b35dc82407d254a3f919869dec72bef89ee0d", "size": 1573, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/math/prim/scal/fun/log_diff_exp.hpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "src/stan/math/prim/scal/fun/log_diff_exp.hpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "src/stan/math/prim/scal/fun/log_diff_exp.hpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1206896552, "max_line_length": 72, "alphanum_fraction": 0.6013986014, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6308593167226832}}
{"text": "/**********************************************************************************************************************\nThis file is part of the Control Toolbox (https://adrlab.bitbucket.io/ct), copyright by ETH Zurich, Google Inc.\nLicensed under Apache2 license (see LICENSE file in main directory)\n**********************************************************************************************************************/\n\n#pragma once\n\n#include <Eigen/Dense>\n\nnamespace ct {\nnamespace models {\nnamespace quadrotor {\n\nconst double pi = 3.14159265;\n\n// mass / inertia\nconst double mQ = 0.546;         // mass of quadcopter [ kg ]\nconst double Thxxyy = 2.32e-3;   // moment of inertia around x,y [ kg*m^2 ]\nconst double Thzz = 3e-4;        // moment of inertia around z [ kg*m^2 ]\nconst double arm_len = 0.175;    // length of quadcopter arm [ m ]\nconst double grav_const = 9.81;  // gravitational constant [ m/s^2 ]\n\nconst double f_hover = mQ * grav_const;\n\n// Thrust parameters\nconst double kF = 6.17092e-8 * 3600 / (2 * pi * 2 * pi);  // rotor thrust coefficient [ N/rad^2 ]\nconst double kM = 1.3167e-9 * 3600 / (2 * pi * 2 * pi);   // rotor moment coefficient [ Nm/rad^2]\nconst double wmax = 7800.0 * 2 * pi / 60;                 // maximum rotor speed [ rad/s ]\nconst double wmin = 1200.0 * 2 * pi / 60;                 // minimum rotor speed [ rad/s ]\nconst double Fsat_min = kF * wmin * wmin;\nconst double Fsat_max = kF * wmax * wmax;\n\nconst Eigen::Vector4d kFs(kF, kF, kF, kF);\nconst Eigen::Vector4d kMs(kM, kM, kM, kM);\n\n}  // namespace quadrotor\n}  // namespace models\n}  // namespace ct\n", "meta": {"hexsha": "d97ac709e202bac607e966b6bb9959db423a3839", "size": 1594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ct_models/include/ct/models/Quadrotor/quadrotor_definitions/quadModelParameters.hpp", "max_stars_repo_name": "vbargsten/ct", "max_stars_repo_head_hexsha": "774ad978c032fda0ef3c2eed0dc3f25f829df7f8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T07:41:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-03T07:41:30.000Z", "max_issues_repo_path": "ct_models/include/ct/models/Quadrotor/quadrotor_definitions/quadModelParameters.hpp", "max_issues_repo_name": "ADVRHumanoids/ct", "max_issues_repo_head_hexsha": "774ad978c032fda0ef3c2eed0dc3f25f829df7f8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ct_models/include/ct/models/Quadrotor/quadrotor_definitions/quadModelParameters.hpp", "max_forks_repo_name": "ADVRHumanoids/ct", "max_forks_repo_head_hexsha": "774ad978c032fda0ef3c2eed0dc3f25f829df7f8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-27T17:13:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-27T17:13:13.000Z", "avg_line_length": 40.8717948718, "max_line_length": 119, "alphanum_fraction": 0.5520702635, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6308593157295628}}
{"text": "//multiprecision long factorials handling\n#include <boost/multiprecision/cpp_int.hpp>\n#include <iostream>\nnamespace mp = boost::multiprecision;\nusing namespace std;\n\nmp :: cpp_int factorial(int n){\n    mp :: cpp_int u = 1;\n     for(int i = 2; i <= n; i++){\n          u *= i;\n      }\n    return u;\n}\nint main(){\n    \n    int T;\n\t\tcin>>T;\n\t\t// cin.ignore(); must be there when using getline(cin, s)\n\t\twhile(T--){\n\t\t    int n, r;\n\t\t    cin >> n >> r;\n\t\t    mp :: cpp_int a = factorial(n);\n\t\t    mp :: cpp_int b = factorial(n - r);\n\t\t    mp :: cpp_int c = factorial(r);\n\t\t    cout << (a / (b * c)) % 1000000007 << '\\n';\n\t\t    \n\t\t}\n     \n    return 0;\n}", "meta": {"hexsha": "2f33a23ae9f8ac79378c1724cabb0eae7584d4e1", "size": 648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GeeksForGeeks/ncr.cpp", "max_stars_repo_name": "theexplorist/Competitve-Programming", "max_stars_repo_head_hexsha": "854afd38313d45a8c89e805a54612e56d6714949", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GeeksForGeeks/ncr.cpp", "max_issues_repo_name": "theexplorist/Competitve-Programming", "max_issues_repo_head_hexsha": "854afd38313d45a8c89e805a54612e56d6714949", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GeeksForGeeks/ncr.cpp", "max_forks_repo_name": "theexplorist/Competitve-Programming", "max_forks_repo_head_hexsha": "854afd38313d45a8c89e805a54612e56d6714949", "max_forks_repo_licenses": ["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.6, "max_line_length": 59, "alphanum_fraction": 0.5308641975, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055544, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6308593081305536}}
{"text": "//This code is an implementation of the Parallel ILU algorithm described in Chow and Patel (2015)\n//\"Fine-Grained Parallel Incomplete LU Factorization,\" SIAM J. Sci Comput., Vol. 37, No.2, C169-C193\n\n//C++ and the Eigen library are used for sparse linear algebra, OpenMP is used for parallelization\n//This implementation assumes the input of a square, symmetric, positive definite matrix\n//Terminology used from paper: \"ILU residual norm\", \"nonlinear residual norm\"\n\n//Developed by Marcos Botto Tornielli, May 2021\n\n//####################################################################################################//\n//######################## Parallel Incomplete LU Factorization ######################################//\n//####################################################################################################//\n#include <iostream>\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/SparseExtra>\n#include <iomanip>\n\nint main()\n{\n    //dummy parallel region to use up the overhead from starting first region\n#pragma omp parallel\n    {\n#pragma omp single\n        std::cout << \"This is thread #\" << omp_get_thread_num() << std::endl;  \n    }\n    \n    //################################################################################################//\n    //##################################### Matrix I/O ###############################################//\n    //################################################################################################//\n\n    //Define common Eigen objects to be used throughout the code\n    typedef Eigen::SparseMatrix<double> SpMat;\n    typedef Eigen::SparseMatrix<double,Eigen::RowMajor> SpMatRow;\n    typedef Eigen::Triplet<double> T;\n\n    //Define timing variables\n    double t1,t2;\n\n    //Load input matrix\n    SpMat A;\n    Eigen::loadMarket(A, \"../input/Pres_Poisson/Pres_Poisson.mtx\");\n\n    //Matrix information as read from MatrixMarket file\n    //Unknown loadMarket bug causes only lower triangular part of symmetric matrix to be read\n    int rows = A.rows();\n    int cols = A.cols();\n    int nonzs = A.nonZeros();\n    double norm = A.norm();\n    bool compr = A.isCompressed();\n    std::cout << \"Matrix is compressed: \" << compr << std::endl;\n    std::cout << \"Number of rows    : \" << rows << std::endl;\n    std::cout << \"Number of columns : \" << cols << std::endl;\n    std::cout << \"Number of nonzeros: \" << nonzs << std::endl;\n    std::cout << \"Frobenius norm    : \" << norm << std::endl << std::endl;\n    \n    //Workaround for loadMarket symmetry issue\n    //Add A to its transpose; diagonal will be divided by 2 to compensate later\n    SpMat A_t = A.transpose();\n    A = A + A_t;\n    //Matrix information for true A matrix\n    rows = A.rows();\n    cols = A.cols();\n    nonzs = A.nonZeros();\n    norm = A.norm();\n    compr = A.isCompressed();\n    std::cout << \"Matrix is compressed: \" << compr << std::endl;\n    std::cout << \"Number of rows    : \" << rows << std::endl;\n    std::cout << \"Number of columns : \" << cols << std::endl;\n    std::cout << \"Number of nonzeros: \" << nonzs << std::endl;\n    std::cout << \"Frobenius norm    : \" << norm << std::endl << std::endl;\n\n    //################################################################################################//\n    //################################ Diagonal Scaling of A #########################################//\n    //################################################################################################//\n\n    //Scale the diagonal down by 2 for loadMarket issue workaround\n    //Compute values for diagonal scaling matrix D\n    //Chow and Patel assume that the matrix used in the algorithm has been scaled to have unit diagonal\n\n    std::vector<T> dTriplets;\n    dTriplets.reserve(rows);\n    for (int i=0; i<A.outerSize(); ++i)\n    {\n        for (Eigen::SparseMatrix<double>::InnerIterator it(A,i); it; ++it)\n        {\n            if (it.row() == it.col())\n            {\n                it.valueRef() = it.value()/2.0;\n                double diag_entry = it.value();\n                double scale_diag_entry = 1.0/sqrt(diag_entry);\n                dTriplets.push_back(T(it.row(),it.row(),scale_diag_entry));\n            }\n\n        }\n    }\n\n    SpMat D(A.rows(),A.cols());\n    D.setFromTriplets(dTriplets.begin(),dTriplets.end());\n\n    //Scale A matrix for unit diagonal\n    A = D*A*D;\n\n    //################################################################################################//\n    //##################### Define Sparsity Structure (not supported) ################################//\n    //################################################################################################//\n\n    //This section is included for potential future development\n    //But the higher ILU Levels are not currently supported by the code (5/8/21)\n    //Unless this support is added, the rest of the code assumes ILU(0) sparsity structure\n    \n    int ilu_level = 0;\n    SpMat A_sparsity = A;\n\n    for (int i=0; i<ilu_level; i++)\n    {\n        A_sparsity = A_sparsity*A;\n    }\n\n    //################################################################################################//\n    //################### Construct Initial Guesses for L and U ######################################//\n    //################################################################################################//\n\n    //\"Standard\" initial guess used:\n    //L guess is the strictly lower triangular part of A with an enforced unit diagonal\n    //U guess is the upper triangular part of A (also has a unit diagonal because A does)\n\n    std::vector<T> lTriplets;\n    std::vector<T> uTriplets;\n\n    lTriplets.reserve(((A.nonZeros() - A.rows())/2.0)+A.rows());\n    uTriplets.reserve(((A.nonZeros() - A.rows())/2.0)+A.rows());\n\n\n    for (int i=0; i<A.outerSize(); ++i)\n    {\n        for (Eigen::SparseMatrix<double>::InnerIterator it(A,i); it; ++it)\n        {\n            if (it.row() == it.col())\n            {\n                lTriplets.push_back(T(it.row(),it.col(),1.0));\n            }\n\n            if (it.row() > it.col())\n            {\n                lTriplets.push_back(T(it.row(),it.col(),it.value()));\n            }else{\n                uTriplets.push_back(T(it.row(),it.col(),it.value()));\n            }\n\n        }\n    }\n\n    SpMatRow L(A.rows(),A.cols());\n    SpMat U(A.rows(),A.cols());\n    L.setFromTriplets(lTriplets.begin(),lTriplets.end());\n    U.setFromTriplets(uTriplets.begin(),uTriplets.end());\n\n    //Calculate ILU residual norm for 0 sweeps\n    SpMat resM = A - L*U;\n    double ilu_res_norm = resM.norm();\n    std::cout << \"ILU residual norm,       0 sweeps: \" << ilu_res_norm << std::endl;\n\n    //Calculate nonlinear residual norm for 0 sweeps\n\n    double nonl_res_norm = 0.0;\n\n    t1 = omp_get_wtime();\n\n#pragma omp parallel for reduction(+:nonl_res_norm) schedule(dynamic,8)\n    for (int i=0; i<A.outerSize(); ++i)\n    {\n        for (Eigen::SparseMatrix<double>::InnerIterator it(A,i); it; ++it)\n        {\n            if (it.row() > it.col())\n            {\n                SpMat in_prod_mat = L.block(it.row(),0,1,it.col()+1) * U.block(0,it.col(),it.col()+1,1);\n                double in_prod = in_prod_mat.coeffRef(0,0);\n                nonl_res_norm = nonl_res_norm + abs(it.value() - in_prod);\n            }else{\n                SpMat in_prod_mat = L.block(it.row(),0,1,it.row()+1) * U.block(0,it.col(),it.row()+1,1);\n                double in_prod = in_prod_mat.coeffRef(0,0);\n                nonl_res_norm = nonl_res_norm + abs(it.value() - in_prod); \n            }\n\n        }\n    }\n\n    t2 = omp_get_wtime();\n\n    std::cout << \"Nonlinear residual norm, 0 sweeps: \" << nonl_res_norm << std::endl;\n    std::cout << \"Time to compute (s)              : \" << t2-t1 << std::endl << std::endl;\n\n    //################################################################################################//\n    //################################# MAIN ALGORITHM LOOP ##########################################//\n    //################################################################################################//\n\n    int n_sweeps = 5;\n\n    for (int sweep=0; sweep<n_sweeps; sweep++)\n    {\n        t1 = omp_get_wtime();\n\n#pragma omp parallel for schedule(dynamic,8)\n        for (int i=0; i<A.outerSize(); ++i)\n        {\n            for (Eigen::SparseMatrix<double>::InnerIterator it(A,i); it; ++it)\n            {\n                if (it.row() > it.col())\n                {\n                    double div = 1.0/U.coeffRef(it.col(),it.col());\n                    SpMat in_prod_mat = L.block(it.row(),0,1,it.col()) * U.block(0,it.col(),it.col(),1);\n                    double in_prod = in_prod_mat.coeffRef(0,0);\n                    L.coeffRef(it.row(),it.col()) = (it.value() - in_prod) * div;\n                }else{\n                    SpMat in_prod_mat = L.block(it.row(),0,1,it.row()) * U.block(0,it.col(),it.row(),1);\n                    double in_prod = in_prod_mat.coeffRef(0,0);\n                    U.coeffRef(it.row(),it.col()) = it.value() - in_prod; \n                }\n\n            }\n        }\n\n        t2 = omp_get_wtime();\n        std::cout << \"Time to compute sweep \" << sweep+1 << \" (s)      : \" << t2-t1 << std::endl << std::endl;\n\n\n        //Calculate ILU residual norm for current number of sweeps\n        resM = A - L*U;\n        ilu_res_norm = resM.norm();\n        std::cout << \"ILU residual norm,       \" << sweep+1 << \" sweeps: \" << ilu_res_norm << std::endl;\n\n        //Calculate nonlinear residual norm for current number of sweeps\n        nonl_res_norm = 0.0;\n    \n        t1 = omp_get_wtime();\n\n#pragma omp parallel for reduction(+:nonl_res_norm) schedule(dynamic,8)\n        for (int i=0; i<A.outerSize(); ++i)\n        {\n            for (Eigen::SparseMatrix<double>::InnerIterator it(A,i); it; ++it)\n            {\n                if (it.row() > it.col())\n                {\n                    SpMat in_prod_mat = L.block(it.row(),0,1,it.col()+1) * U.block(0,it.col(),it.col()+1,1);\n                    double in_prod = in_prod_mat.coeffRef(0,0);\n                    nonl_res_norm = nonl_res_norm + abs(it.value() - in_prod);\n                }else{\n                    SpMat in_prod_mat = L.block(it.row(),0,1,it.row()+1) * U.block(0,it.col(),it.row()+1,1);\n                    double in_prod = in_prod_mat.coeffRef(0,0);\n                    nonl_res_norm = nonl_res_norm + abs(it.value() - in_prod); \n                }\n\n            }\n        }\n\n        t2 = omp_get_wtime();\n\n        std::cout << \"Nonlinear residual norm, \" << sweep+1 << \" sweeps: \" << nonl_res_norm << std::endl;\n        std::cout << \"Time to compute (s)              : \" << t2-t1 << std::endl << std::endl <<std::endl;\n\n\n    }\n\n    return 0;\n}\n//####################################################################################################//\n//####################################################################################################//\n//####################################################################################################//\n\n", "meta": {"hexsha": "ef7567bf3c2a78c3c40fb42651fcc66e94210cc0", "size": 10996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pilu.cpp", "max_stars_repo_name": "mbotto123/parallel-ilu-demo", "max_stars_repo_head_hexsha": "9f82d9f0b55fbbedc74420e56dabde13159ca441", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pilu.cpp", "max_issues_repo_name": "mbotto123/parallel-ilu-demo", "max_issues_repo_head_hexsha": "9f82d9f0b55fbbedc74420e56dabde13159ca441", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pilu.cpp", "max_forks_repo_name": "mbotto123/parallel-ilu-demo", "max_forks_repo_head_hexsha": "9f82d9f0b55fbbedc74420e56dabde13159ca441", "max_forks_repo_licenses": ["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.7259259259, "max_line_length": 110, "alphanum_fraction": 0.4611676973, "num_tokens": 2501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648678, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6308593062596312}}
{"text": "#include <Engine/MeshEdit/AXAP.h>\n\n#include <Engine/Primitive/TriMesh.h>\n\n#include <Eigen/Sparse>\n#include <Eigen/LU>\n#include <Eigen/SVD> \n\nusing namespace Ubpa;\n\nusing namespace std;\nusing namespace Eigen;\n\nAXAP::AXAP(Ptr<TriMesh> triMesh)\n\t: heMesh(make_shared<HEMesh<V>>())\n{\n\tInit(triMesh);\n}\n\nvoid AXAP::Clear() {\n\theMesh->Clear();\n\ttriMesh = nullptr;\n}\n\nbool AXAP::Init(Ptr<TriMesh> triMesh) {\n\tClear();\n\n\tif (triMesh == nullptr)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID)\n\t{\n\t\tprintf(\"ERRIR::Minsurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is invalid\\n\");\n\t\treturn false;\n\t}\n\n\t// init half-edge structure\n\tnV = triMesh->GetPositions().size();\n\tnT = triMesh->GetTriangles().size();\n\tvector<vector<size_t>> triangles;\n\ttriangles.reserve(nT);\n\tfor (auto triangle : triMesh->GetTriangles())\n\t{\n\t\ttriangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });\n\t}\n\theMesh->Reserve(nV);\n\theMesh->Init(triangles);\n\n\tif (!heMesh->IsTriMesh() || !heMesh->HaveBoundary())\n\t{\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is not a triangle mesh or hasn't a boundary\\n\");\n\t\theMesh->Clear();\n\t\treturn false;\n\t}\n\n\t// positions of triangle mesh -> positions of half-edge structure\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\tauto v = heMesh->Vertices().at(i);\n\t\tv->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t}\n\n\tthis->triMesh = triMesh;\n\treturn true;\n}\n\nbool AXAP::Run() {\n\tif (heMesh->IsEmpty() || !triMesh)\n\t{\n\t\tprintf(\"ERROR::Minsurf::Run\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\n\tInitPara();\n\tInitFlatTri();\n\tInitParaSolver();\n\titer_count_ = 0;\n\n\tUpdateTriMesh();\n\treturn true;\n}\n\nvoid AXAP::UpdateTriMesh()\n{\n\t// half-edge structure -> triangle mesh\n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tvector<normalf> normals = vector<normalf>();\n\tvector<pointf2> texcoords;\n\tpositions.reserve(nV);\n\tindice.reserve(3 * nT);\n\tnormals.reserve(nV);\n\ttexcoords.reserve(nV);\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\t//positions.push_back(heMesh->Vertices().at(i)->pos.cast_to<pointf3>());\n\t\tpositions.push_back({ para_solution_(i, 0), para_solution_(i, 1), 0 });\n\t\ttexcoords.push_back({ para_solution_(i, 0), para_solution_(i, 1) });\n\t}\n\tfor (auto f : heMesh->Polygons())\n\t{\n\t\tfor (auto v : f->BoundaryVertice())\n\t\t{\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t\t}\n\t}\n\n\ttriMesh->Init(indice, positions, normals, texcoords);\n}\n\nvoid AXAP::InitPara()\n{\n\tSparseMatrix<float> A(nV, nV);\n\tMatrixXf B(nV, 2);\n\t// construct matrix A, B\n\n\t// Initialize\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\tA.insert(i, i) = 0;\n\t\tB.row(i) = RowVector2f::Zero();\n\t\tauto vi = heMesh->Vertices().at(i);\n\t\tfor (auto vj : vi->AdjVertices())\n\t\t{\n\t\t\tA.insert(i, heMesh->Index(vj)) = 0;\n\t\t}\n\t}\n\n\t// add cotangent weight\n\tfor (size_t t = 0; t < nT; t++)\n\t{\n\t\tauto triangle = heMesh->Polygons().at(t);\n\t\tauto edge = triangle->HalfEdge();\n\t\tfor (int k = 0; k < 3; k++, edge = edge->Next())\n\t\t{\n\t\t\tauto vi = edge->Origin();\n\t\t\tauto vj = edge->End();\n\t\t\tauto vk = edge->Next()->End();\n\t\t\tint i = heMesh->Index(vi);\n\t\t\tint j = heMesh->Index(vj);\n\t\t\tvecf3 eki = vi->pos - vk->pos;\n\t\t\tvecf3 ekj = vj->pos - vk->pos;\n\t\t\tfloat cot_theta = eki.cos_theta(ekj) / eki.sin_theta(ekj);\n\t\t\tA.coeffRef(i, i) += cot_theta;\n\t\t\tA.coeffRef(i, j) -= cot_theta;\n\t\t\tA.coeffRef(j, i) -= cot_theta;\n\t\t\tA.coeffRef(j, j) += cot_theta;\n\t\t}\n\t}\n\n\t// set boundary to given value\n\tsize_t nB = heMesh->Boundaries()[0].size();\n\tfloat length_count = 0;\n\tfor (size_t k = 0; k < nB; k++)\n\t{\n\t\tauto edge = heMesh->Boundaries()[0][k];\n\t\tdouble length = (edge->End()->pos - edge->Origin()->pos).norm();\n\t\tlength_count += length;\n\t}\n\n\tbool flag = false;\n\tfloat length_pos = 0;\n\tfor (size_t k = 0; k < nB; k++)\n\t{\n\t\tauto edge = heMesh->Boundaries()[0][k];\n\t\tauto vi = edge->Origin();\n\t\tsize_t i = heMesh->Index(vi);\n\t\tfloat ratio = length_pos / length_count;\n\t\tif (k == 0)\n\t\t{\n\t\t\tstart = i;\n\t\t}\n\t\telse if ((ratio >= 0.5) && !flag)\n\t\t{\n\t\t\tend = i;\n\t\t\tflag = true;\n\t\t}\n\n\t\tfor (auto vj : vi->AdjVertices())\n\t\t{\n\t\t\tA.coeffRef(i, heMesh->Index(vj)) = 0;\n\t\t}\n\t\tA.coeffRef(i, i) = 1;\n\t\tif (ratio < 0.25)\n\t\t{\n\t\t\tB(i, 0) = ratio * 4;\n\t\t\tB(i, 1) = 0;\n\t\t}\n\t\telse if (ratio >= 0.25 && ratio < 0.5)\n\t\t{\n\t\t\tB(i, 0) = 1;\n\t\t\tB(i, 1) = (ratio - 0.25) * 4;\n\t\t}\n\t\telse if (ratio >= 0.5 && ratio < 0.75)\n\t\t{\n\t\t\tB(i, 0) = 1 - (ratio - 0.5) * 4;\n\t\t\tB(i, 1) = 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tB(i, 0) = 0;\n\t\t\tB(i, 1) = 1 - (ratio - 0.75) * 4;\n\t\t}\n\t\tdouble length = (edge->End()->pos - edge->Origin()->pos).norm();\n\t\tlength_pos += length;\n\t}\n\n\t// solve sparse linear equations\n\tSparseLU<SparseMatrix<float>> solver;\n\tsolver.compute(A);\n\tpara_solution_ = solver.solve(B);\n\n\tcout << \"Success::Parametrize::Parametrize:\" << endl\n\t\t<< \"\\t\" << \"parametrization successfully constructed\" << endl;\n}\n\nvoid AXAP::InitFlatTri()\n{\n\tflat_tri_ = (Matrix<float, 3, 2>*)malloc(nT * sizeof(Matrix<float, 3, 2>));\n\tif (flat_tri_ == nullptr)\n\t{\n\t\tcout << \"No enough memory!\" << endl;\n\t}\n\n\tfor (size_t i = 0; i < nT; i++)\n\t{\n\t\tauto ti = heMesh->Polygons().at(i);\n\t\tauto vi0 = ti->HalfEdge()->Origin();\n\t\tauto vi1 = ti->HalfEdge()->End();\n\t\tauto vi2 = ti->HalfEdge()->Next()->End();\n\t\tvecf3 ei1 = vi1->pos - vi0->pos;\n\t\tvecf3 ei2 = vi2->pos - vi0->pos;\n\t\tdouble cos_theta = ei1.cos_theta(ei2);\n\t\tflat_tri_[i] = Matrix<float, 3, 2>();\n\t\tflat_tri_[i].row(0) = RowVector2f::Zero();\n\t\tflat_tri_[i].row(1) = RowVector2f(ei1.norm(), 0);\n\t\tflat_tri_[i].row(2) = RowVector2f(ei2.norm() * cos_theta, ei2.norm() * sqrt(1 - pow(cos_theta, 2)));\n\t}\n}\n\nvoid AXAP::InitParaSolver()\n{\n\tSparseMatrix<float> A(nV, nV);\n\tfor (size_t i = 0; i < nV; i++)\n\t{\n\t\tif (i == start || i == end)\n\t\t{\n\t\t\tA.insert(i, i) = 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto vi = heMesh->Vertices().at(i);\n\t\t\tA.insert(i, i) = 0;\n\t\t\tfor (auto vj : vi->AdjVertices())\n\t\t\t{\n\t\t\t\tA.insert(i, heMesh->Index(vj)) = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\t// add cotangent weight\n\tfor (size_t t = 0; t < nT; t++)\n\t{\n\t\tauto triangle = heMesh->Polygons().at(t);\n\t\tauto edge = triangle->HalfEdge();\n\t\tfor (int k = 0; k < 3; k++, edge = edge->Next())\n\t\t{\n\t\t\tauto vi = edge->Origin();\n\t\t\tauto vj = edge->End();\n\t\t\tauto vk = edge->Next()->End();\n\t\t\tint i = heMesh->Index(vi);\n\t\t\tint j = heMesh->Index(vj);\n\t\t\tvecf3 eki = vi->pos - vk->pos;\n\t\t\tvecf3 ekj = vj->pos - vk->pos;\n\t\t\tfloat cot_theta = eki.cos_theta(ekj) / eki.sin_theta(ekj);\n\t\t\tif (i != start && i != end)\n\t\t\t{\n\t\t\t\tA.coeffRef(i, i) += cot_theta;\n\t\t\t\tA.coeffRef(i, j) -= cot_theta;\n\t\t\t}\n\t\t\tif (j != start && j != end)\n\t\t\t{\n\t\t\t\tA.coeffRef(j, i) -= cot_theta;\n\t\t\t\tA.coeffRef(j, j) += cot_theta;\n\t\t\t}\n\t\t}\n\t}\n\tpara_solver_.compute(A);\n}\n\nMatrix2f AXAP::Jacobian(Matrix<float, 3, 2>& x, Matrix<float, 3, 2>& u)\n{\n\tMatrix2f A = Matrix2f();\n\tMatrix2f B = Matrix2f();\n\tA.row(0) = x.row(1) - x.row(0);\n\tA.row(1) = x.row(2) - x.row(0);\n\tB.row(0) = u.row(1) - u.row(0);\n\tB.row(1) = u.row(2) - u.row(0);\n\tMatrix2f J =  A.lu().solve(B);\n\treturn J;\n}\n\nbool AXAP::Iterate()\n{\n\treturn true;\n}\n\nvoid AXAP::UpdatePara()\n{\n\n}", "meta": {"hexsha": "437dd6d9c0015894227127eaca0e02ea034cd2a4", "size": 6903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/AXAP.cpp", "max_stars_repo_name": "danielchyustc/USTC_CG-1", "max_stars_repo_head_hexsha": "97f87c06dc67b2f34dc52a31bd23f8185653ef18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/AXAP.cpp", "max_issues_repo_name": "danielchyustc/USTC_CG-1", "max_issues_repo_head_hexsha": "97f87c06dc67b2f34dc52a31bd23f8185653ef18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/AXAP.cpp", "max_forks_repo_name": "danielchyustc/USTC_CG-1", "max_forks_repo_head_hexsha": "97f87c06dc67b2f34dc52a31bd23f8185653ef18", "max_forks_repo_licenses": ["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.9840764331, "max_line_length": 102, "alphanum_fraction": 0.5900333188, "num_tokens": 2490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6308592981640616}}
{"text": "#include <boost/numeric/ublas/vector.hpp> \n#include <boost/numeric/ublas/matrix.hpp> \n#include <boost/math/tools/solve.hpp> \n#include <iostream>\n#include <iomanip>\n#include <regex>\n#include <omp.h>\n#include \"../lib/prim2d.h\"\n#include \"../lib/de2d.h\"\n\n#define ub  boost::numeric::ublas\n\n#define DEBUG 2\n\nint main(int argc, char* argv[]){\n\n    if( !argv[1] ) \n    {\n        std::cout << \"set the input file name\\n\";\n        exit(1);\n    }\n    std::string fileName0(argv[1]);\n\n    std::vector<Segm2D> sigma_t;\n    sigma_t.reserve(1000);\n\n    load_border(sigma_t, fileName0);\n    size_t n = sigma_t.size();\n    #if DEBUG > 1\n       std::cout << \"\\033[31;1mn = \" << n << \"\\033[0m\\n\";\n    #endif\n\n    bool isMove = true;\n    int cycle = 0;\n    double t = 0.0;\n    double dt = 0.01;\n    const double T = 5.;\n    const double lambda = 0.5;\n    const double alpha = 0.2;\n    const Vector2D rM1 = Vector2D(2.5,0.0);\n    const double q1 = -M_PI;\n    const double T0 = 1.0;\n    const double VEps = 0.1;\n    const size_t max_cycle = 20;\n\n    ub::matrix<double> A(n,n);\n    ub::vector<double> f(n);\n    ub::vector<double> g(n);\n\n    for(;cycle<max_cycle&&isMove;++cycle)\n    { \n\n        // ***********   stage 1 *****************// \n\n\n        double ts1 = omp_get_wtime();\n        #pragma omp parallel for\n        for(size_t i=0; i<n; ++i)\n        {\n            Vector2D rM = (sigma_t[i].A + sigma_t[i].B)/2.0;\n            for(size_t j=0; j<n; ++j)\n            {\n                if(i!=j)\n                {\n                    Vector2D rN = 0.5*(sigma_t[j].A + sigma_t[j].B );\n                    Vector2D nN = normal(sigma_t[j]);\n                    A(i,j)=-2.0*lambda*Omega(rM,rN,nN)*dl(sigma_t[j]);\n                }\n                else A(i,j)=1.0;\n            }\n            f(i)=2.0*lambda*phi0(rM,q1,rM1)+2.0*alpha*rM.y; \n        }\n        double te1 = omp_get_wtime();\n        std::cout << \"\\t\\033[33mstage 1: \"\n                  << std::fixed << std::showpoint<< std::setprecision(10)\n                  << te1-ts1 << \" sec.\\033[0m\";\n\n        // ***********   stage 2 *****************// \n\n        double ts2 = omp_get_wtime();\n        g = boost::math::tools::solve(A,f);\n        double te2 = omp_get_wtime();\n        std::cout << \"\\t\\033[34mstage 2: \" \n                  << std::fixed << std::showpoint<< std::setprecision(5)\n                  << te2-ts2 << \" sec.\\033[0m\";\n\n\n        // ***********   stage 3 *****************// \n\n        std::vector<Vector2D> vA(n), vB(n);\n\n        double ts3 = omp_get_wtime();\n        #pragma omp parallel for\n        for(size_t i=0; i<n; ++i){\n            Vector2D rMA = sigma_t[i].A;\n            vA[i] = v0(rMA,q1,rM1);\n            for(size_t j=0; j<n; ++j)\n                vA[i] += g(j)*vSegmTheta(rMA,sigma_t[j],VEps);\n        }// for_i\n\n        #pragma omp parallel for\n        for(size_t i=0; i<n; ++i){\n            sigma_t[i].A += vA[i]*dt;\n            sigma_t[(i+1)%n].B = sigma_t[i].A;\n \n        }// for_i\n\n        double te3 = omp_get_wtime();\n        std::cout << \"\\t\\033[35mstage 3: \" \n                  << std::fixed << std::showpoint<< std::setprecision(10)\n                  << te3-ts3 << \" sec. \\033[0m\\n\";\n\n        t+=dt/T0;\n\n        #if DEBUG > 1 \n        for( size_t k=1; k<5; ++k)\n            if(cycle==(k*(max_cycle-1)/5)) \n            {\n                std::stringstream ss;\n                ss << k;\n                std::string suffix;\n                ss >> suffix; \n\n                std::string outFileName = std::regex_replace(\n                    fileName0, \n                    std::regex(\"0\"), \n                    suffix\n                );\n                std::cout << \"\\033[31;1mcycle=\" << std::setw(4) << cycle \n                          << \"\\tsave \" << outFileName \n                          << \"\\t\\tt = \" << t \n                          << \"\\033[0m\\n\"; \n                save_border(sigma_t, outFileName); \n            }\n        #endif \n\n        // set your conditions for the variable isMove here:\n        // if ( u cond. )  isMove = false;\n   \n    } // cycle\n\n    std::cout <<  \"\\033[32;1msimulation time T = \" << T << \"\\033[0m\\n\";\n    std::string outFileName = std::regex_replace(\n        fileName0, \n        std::regex(\"0\"), \n        \"_end\"\n    );\n    save_border(sigma_t, outFileName); \n\n}//main\n", "meta": {"hexsha": "111ab094f5bc525c99fa20dae7ed594f1148b05e", "size": 4262, "ext": "cc", "lang": "C++", "max_stars_repo_path": "evolution2d/cpp/uniform_media/modelling/one_boundary_diff_dens_and_visc.cc", "max_stars_repo_name": "nikolskydn/discrete_vortex_method", "max_stars_repo_head_hexsha": "68c6672d3744706f4c51a184470bb027ce377f4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "evolution2d/cpp/uniform_media/modelling/one_boundary_diff_dens_and_visc.cc", "max_issues_repo_name": "nikolskydn/discrete_vortex_method", "max_issues_repo_head_hexsha": "68c6672d3744706f4c51a184470bb027ce377f4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "evolution2d/cpp/uniform_media/modelling/one_boundary_diff_dens_and_visc.cc", "max_forks_repo_name": "nikolskydn/discrete_vortex_method", "max_forks_repo_head_hexsha": "68c6672d3744706f4c51a184470bb027ce377f4b", "max_forks_repo_licenses": ["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.2251655629, "max_line_length": 73, "alphanum_fraction": 0.4519005162, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6308592915581726}}
{"text": "#define _USE_MATH_DEFINES\n\n#include <Eigen/Core>\n#include \"../matplotlibcpp.h\"\n\nnamespace plt = matplotlibcpp;\n\nEigen::ArrayXd fun(const Eigen::ArrayXd& t)\n{\n    using Eigen::cos;\n    using Eigen::exp;\n    using Eigen::sin;\n    return 0.0981 * cos(0.1 * t - 0.007845) - exp(-0.3999 * t) * (0.0981 * cos(3.169 * t) + 0.0124 * sin(3.169 * t));\n}\n\nint main()\n{\n    Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(100, 0, 10);\n    Eigen::VectorXd y = fun(x.array());\n    plt::stl::plot(x.data(), x.data() + x.size(), y.data(),\n                   {{\"label\", \"Eigen VectorXd\"}, {\"marker\", \"o\"}, {\"markersize\", \"5\"}, {\"markerfacecolor\", \"#3efab0\"}});\n    plt::legend();\n    plt::show();\n}", "meta": {"hexsha": "129c69d1f946f62f2903707b104f891719893e4a", "size": 680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/eigen_objects.cpp", "max_stars_repo_name": "Hs293Go/matplotlib-cpp", "max_stars_repo_head_hexsha": "da596676b216e5e07563dfa8a8bc9844f664decc", "max_stars_repo_licenses": ["MIT"], "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_objects.cpp", "max_issues_repo_name": "Hs293Go/matplotlib-cpp", "max_issues_repo_head_hexsha": "da596676b216e5e07563dfa8a8bc9844f664decc", "max_issues_repo_licenses": ["MIT"], "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_objects.cpp", "max_forks_repo_name": "Hs293Go/matplotlib-cpp", "max_forks_repo_head_hexsha": "da596676b216e5e07563dfa8a8bc9844f664decc", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 120, "alphanum_fraction": 0.575, "num_tokens": 221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.630775236878321}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <array>\n#include <string>\n#include <ros/ros.h>\n#include <swerve_math/Swerve.h>\n#include <swerve_point_generator/profiler.h>\n#include <swerve_point_generator/FullGenCoefs.h>\n#include <swerve_point_generator/GenerateSwerveProfile.h>\n#include <talon_swerve_drive_controller/MotionProfile.h> //Only needed for visualization\n#include <talon_swerve_drive_controller/MotionProfilePoints.h> //Only needed for visualization\n#include <talon_swerve_drive_controller/WheelPos.h>\n\n//Get swerve info here:\n\nstd::shared_ptr<swerve> swerve_math;\nstd::shared_ptr<swerve_profile::swerve_profiler> profile_gen;\n\nros::ServiceClient graph_prof;\nros::ServiceClient get_pos;\nros::ServiceClient graph_swerve_prof;\ndouble defined_dt;\n\ndouble f_v;\ndouble f_s;\ndouble f_a;\ndouble f_s_s;\ndouble f_s_v;\n\nswerveVar::driveModel model;\n\nbool full_gen(swerve_point_generator::FullGenCoefs::Request &req, swerve_point_generator::FullGenCoefs::Response &res)\n{\n\t//ROS_ERROR(\"running point gen\");\n\n\tstd::array<double, WHEELCOUNT> curPos;\n\ttalon_swerve_drive_controller::WheelPos pos_msg;\n\tif (!get_pos.call(pos_msg))\n\t{\n\t\tROS_ERROR(\"failed to get wheel pos in point gen, maybe asked swerve drive controller before it was started up?\");\n\t\treturn false;\n\t}\n\tfor (int i = 0; i < WHEELCOUNT; i++)\n\t\tcurPos[i] = pos_msg.response.positions[i]; //TODO: FILL THIS OUT SOMEHOW\n\tconst int k_p = 1;\n\tres.points.resize(155 / defined_dt);\n\tint prev_point_count = 0;\n\ttalon_swerve_drive_controller::MotionProfile graph_msg;\n\tfor (size_t s = 0; s < req.spline_groups.size(); s++)\n\t{\n\t\tint priv_num = 0;\n\t\tif (s > 0)\n\t\t{\n\t\t\tpriv_num = req.spline_groups[s - 1];\n\t\t}\n\t\tconst int n = round(req.wait_before_group[s] / defined_dt);\n\t\tstd::vector<swerve_profile::spline_coefs> x_splines;\n\t\tstd::vector<swerve_profile::spline_coefs> y_splines;\n\t\tstd::vector<swerve_profile::spline_coefs> orient_splines;\n\n\t\tconst int neg_x = req.x_invert[s] ? -1 : 1;\n\t\tstd::vector<double> end_points_holder;\n\t\tdouble shift_by = 0;\n\t\tif (s != 0)\n\t\t{\n\t\t\tshift_by = req.end_points[priv_num - 1];\n\t\t}\n\n\t\tfor (int i = priv_num; i < req.spline_groups[s]; i++)\n\t\t{\n\t\t\tROS_INFO_STREAM(\"orient_coefs[\" << i << \"].spline=\" << req.orient_coefs[i].spline[0] << \" \" <<\n\t\t\t\t\t\t\treq.orient_coefs[i].spline[1] << \" \" <<\n\t\t\t\t\t\t\treq.orient_coefs[i].spline[2] << \" \" <<\n\t\t\t\t\t\t\treq.orient_coefs[i].spline[3] << \" \" <<\n\t\t\t\t\t\t\treq.orient_coefs[i].spline[4] << \" \" <<\n\t\t\t\t\t\t\treq.orient_coefs[i].spline[5]);\n\n\t\t\torient_splines.push_back(swerve_profile::spline_coefs(\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[0] * neg_x,\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[1] * neg_x,\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[2] * neg_x,\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[3] * neg_x,\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[4] * neg_x,\n\t\t\t\t\t\t\t\t\t\t req.orient_coefs[i].spline[5] * neg_x));\n\t\t\tROS_INFO_STREAM(\"orient_coefs[\" << i << \"].spline=\" << orient_splines.back());\n\n\t\t\tROS_INFO_STREAM(\"x_coefs[\" << i << \"].spline=\" << req.x_coefs[i].spline[0] << \" \" <<\n\t\t\t\t\t\t\treq.x_coefs[i].spline[1] << \" \" <<\n\t\t\t\t\t\t\treq.x_coefs[i].spline[2] << \" \" <<\n\t\t\t\t\t\t\treq.x_coefs[i].spline[3] << \" \" <<\n\t\t\t\t\t\t\treq.x_coefs[i].spline[4] << \" \" <<\n\t\t\t\t\t\t\treq.x_coefs[i].spline[5]);\n\n\t\t\tx_splines.push_back(swerve_profile::spline_coefs(\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[0] * neg_x,\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[1] * neg_x,\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[2] * neg_x,\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[3] * neg_x,\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[4] * neg_x,\n\t\t\t\t\t\t\t\t\treq.x_coefs[i].spline[5] * neg_x));\n\t\t\tROS_INFO_STREAM(\"x_coefs[\" << i << \"].spline=\" << x_splines.back());\n\n\t\t\tROS_INFO_STREAM(\"y_coefs[\" << i << \"].spline=\" << req.y_coefs[i].spline[0] << \" \" <<\n\t\t\t\t\t\t\treq.y_coefs[i].spline[1] << \" \" <<\n\t\t\t\t\t\t\treq.y_coefs[i].spline[2] << \" \" <<\n\t\t\t\t\t\t\treq.y_coefs[i].spline[3] << \" \" <<\n\t\t\t\t\t\t\treq.y_coefs[i].spline[4] << \" \" <<\n\t\t\t\t\t\t\treq.y_coefs[i].spline[5]);\n\n\t\t\ty_splines.push_back(swerve_profile::spline_coefs(\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[0],\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[1],\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[2],\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[3],\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[4],\n\t\t\t\t\t\t\t\t\treq.y_coefs[i].spline[5]));\n\t\t\tROS_INFO_STREAM(\"y_coefs[\" << i << \"].spline=\" << y_splines.back());\n\n\t\t\tROS_INFO_STREAM(\"hrer: \" << req.end_points[i] - shift_by << \" r_s: \" <<  req.spline_groups[s] <<  \" s: \" << s);\n\t\t\tend_points_holder.push_back(req.end_points[i] - shift_by);\n\t\t}\n\n\t\tconst double t_shift = req.t_shift[s];\n\t\tconst bool flip_dirc = req.flip[s];\n\n\t\tswerve_point_generator::GenerateSwerveProfile::Response srv_msg; //TODO FIX THIS, HACK\n\t\t//srv_msg.points.resize(0);\n\t\tROS_INFO_STREAM(\"req.initial_v: \" << req.initial_v << \" req.final_v: \" << req.final_v << \" t_shift: \" << t_shift);\n\t\tprofile_gen->generate_profile(x_splines, y_splines, orient_splines, req.initial_v, req.final_v, srv_msg, end_points_holder, t_shift, flip_dirc);\n\t\tconst int point_count = srv_msg.points.size();\n\t\t//ROS_WARN(\"TEST2\");\n\n\t\tgraph_msg.request.joint_trajectory.header = srv_msg.header;\n\n\t\tres.dt = defined_dt;\n\n\t\t//ROS_INFO_STREAM(\"dt: \" << res.dt);\n\n\t\t//ROS_WARN(\"BUFFERING\");\n\t\t//TODO: optimize code?\n\n\t\tstd::array<bool, WHEELCOUNT> holder;\n\n\t\t//Do first point and initialize stuff\n\n\t\t/*\n\t\tTODO: IMPLEMENT BELOW\n\t\tif(motion_profile_mode == steering_joints_[0].getMode())\n\t\t{\n\t\t\tfor(size_t i = 0; i < WHEELCOUNT; i++)\n\t\t\t{\n\t\t\t\tspeed_joints_[i].setCommand(0);\n\t\t\t\tsteering_joints_[i].setCommand(0);\n\t\t\t}\n\t\t}\n\t\t*/\n\t\t//ROS_INFO_STREAM(\"pos_0:\" << srv_msg.points[0].positions[0] << \"pos_1:\" << srv_msg.points[0].positions[1] <<\"pos_2:\" <<  srv_msg.points[0].positions[2]);\n\n\t\t// Bounds checking - not safe to proceed with setting up angle\n\t\t// positions and velocities if data is not as expected.\n\t\tif (srv_msg.points.size() < 2)\n\t\t{\n\t\t\tROS_ERROR(\"Need at least 2 points\");\n\t\t\treturn false;\n\t\t}\n\t\tfor (const auto point : srv_msg.points)\n\t\t{\n\t\t\tif (point.positions.size() < 3)\n\t\t\t{\n\t\t\t\tROS_ERROR(\"Not enough positions in point\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tconst std::array<Eigen::Vector2d, WHEELCOUNT> angles_positions  = swerve_math->motorOutputs({srv_msg.points[1].positions[0] - srv_msg.points[0].positions[0], srv_msg.points[1].positions[1] - srv_msg.points[0].positions[1]}, srv_msg.points[1].positions[2] - srv_msg.points[0].positions[2], srv_msg.points[1].positions[2], false, holder, false, curPos, false);\n\t\t//TODO: angles on the velocity array below are superfluous, could remove\n\t\t//std::array<Eigen::Vector2d, WHEELCOUNT> angles_velocities  = swerve_math->motorOutputs({srv_msg.points[1].velocities[0], srv_msg.points[1].velocities[1]}, -srv_msg.points[1].velocities[2], /*srv_msg.points[1].positions[2]*/ M_PI / 2.0, false, holder, false, curPos, false);\n\t\tfor (size_t k = 0; k < WHEELCOUNT; k++)\n\t\t\tcurPos[k] = angles_positions[k][1];\n\n\t\t//ROS_INFO_STREAM(\"pos_0:\" << srv_msg.points[i+1].positions[0] << \"pos_1:\" << srv_msg.points[i+1].positions[1] <<\"pos_2:\" <<  srv_msg.points[i+1].positions[2] << \" counts: \" << point_count << \" i: \"<< i << \" wheels: \" << WHEELCOUNT);\n\t\tstd::array<double, WHEELCOUNT> vel_sum;\n\t\tfor (int i = prev_point_count; i < n + prev_point_count; i++)\n\t\t{\n\t\t\tgraph_msg.request.joint_trajectory.points.push_back(srv_msg.points[0]);\n\n\t\t\tfor (size_t k = 0; k < WHEELCOUNT; k++)\n\t\t\t{\n\t\t\t\tres.points[i].hold.push_back(true);\n\n\t\t\t\tif (s == 0)\n\t\t\t\t{\n\t\t\t\t\tres.points[i].drive_pos.push_back(angles_positions[k][0]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tres.points[i].drive_pos.push_back(res.points[i - 1].drive_pos[k]);\n\n\t\t\t\t}\n\t\t\t\t//ROS_WARN(\"re\");\n\n\t\t\t\tres.points[i].drive_f.push_back(0);\n\t\t\t\tvel_sum[k] = 0;\n\n\t\t\t\tres.points[i].steer_pos.push_back(angles_positions[k][1]);\n\t\t\t\tres.points[i].steer_f.push_back(0);\n\t\t\t\t//ROS_INFO_STREAM(\"drive_pos: \" << res.points[i+1].drive_pos[k] << \"drive_f: \" << res.points[i+1].drive_vel[k] << \"steer_pos: \" << res.points[i+1].steer_pos[i]);\n\t\t\t}\n\t\t}\n\n\t\tgraph_msg.request.joint_trajectory.points.insert(graph_msg.request.joint_trajectory.points.end(), srv_msg.points.begin(), srv_msg.points.end());\n\n\t\tstd::array<double, WHEELCOUNT> prev_vels;\n\t\tstd::array<double, WHEELCOUNT> prev_steer_pos;\n\t\tfor (size_t k = 0; k < WHEELCOUNT; k++)\n\t\t{\n\t\t\tprev_vels[k] = 0;\n\t\t\tprev_steer_pos[k] = angles_positions[k][1];\n\t\t}\n\t\tfor (int i = 0; i < point_count - k_p; i++)\n\t\t{\n\t\t\tconst std::array<Eigen::Vector2d, WHEELCOUNT> angles_positions  = swerve_math->motorOutputs({srv_msg.points[i + 1].positions[0] - srv_msg.points[i].positions[0], srv_msg.points[i + 1].positions[1] - srv_msg.points[i].positions[1]}, srv_msg.points[i + 1].positions[2] - srv_msg.points[i].positions[2], srv_msg.points[i + 1].positions[2], false, holder, false, curPos, false);\n\t\t\t//TODO: angles on the velocity array below are superfluous, could remove\n\t\t\tstd::array<Eigen::Vector2d, WHEELCOUNT> angles_velocities  = swerve_math->motorOutputs({srv_msg.points[i + 1].velocities[0], srv_msg.points[i + 1].velocities[1]}, srv_msg.points[i + 1].velocities[2], srv_msg.points[i + 1].positions[2], false, holder, false, curPos, false);\n\t\t\tfor (size_t k = 0; k < WHEELCOUNT; k++)\n\t\t\t\tcurPos[k] = angles_positions[k][1];\n\n\t\t\t//ROS_INFO_STREAM(\"pos_0:\" << srv_msg.points[i+1].positions[0] << \"pos_1:\" << srv_msg.points[i+1].positions[1] <<\"pos_2:\" <<  srv_msg.points[i+1].positions[2] << \" counts: \" << point_count << \" i: \"<< i << \" wheels: \" << WHEELCOUNT);\n\t\t\tfor (size_t k = 0; k < WHEELCOUNT; k++)\n\t\t\t{\n\t\t\t\tres.points[i + n + prev_point_count].hold.push_back(false);\n\n\t\t\t\t//ROS_WARN(\"hhhhere\");\n\t\t\t\tif (i != 0 || n != 0 || s != 0)\n\t\t\t\t{\n\t\t\t\t\tres.points[i + n + prev_point_count].drive_pos.push_back(angles_positions[k][0] + res.points[i + n - 1 + prev_point_count].drive_pos[k]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tres.points[i + n + prev_point_count ].drive_pos.push_back(angles_positions[k][0]);\n\t\t\t\t}\n\n\t\t\t\tif (i > point_count - k_p - 2)\n\t\t\t\t{\n\t\t\t\t\t//ROS_INFO_STREAM(\"final pos\" << angles_positions[k][0] + res.points[i + n - 1 + prev_point_count].drive_pos[k]);\n\t\t\t\t\t//ROS_INFO_STREAM(\"vel sum\" << vel_sum[k]);\n\t\t\t\t\tres.points[i + n + prev_point_count].drive_f.push_back(0);\n\t\t\t\t\tres.points[i + n + prev_point_count].steer_f.push_back(0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tint sign_v = angles_velocities[k][0] < 0 ? -1 : angles_velocities[k][0] > 0 ? 1 : 0;\n\t\t\t\t\tres.points[i + n + prev_point_count].drive_f.push_back(angles_velocities[k][0] * f_v + sign_v * f_s + f_a /* / ( -fabs(angles_velocities[k][0]) / (model.maxSpeed * 1.2) + 1.05 ) */ * (angles_velocities[k][0] - prev_vels[k]) / defined_dt);\n\t\t\t\t\tprev_vels[k] = angles_velocities[k][0];\n\t\t\t\t\tvel_sum[k] += angles_velocities[k][0];\n\n\t\t\t\t\tconst double steer_v = (angles_positions[k][1] - prev_steer_pos[k]) / defined_dt;\n\t\t\t\t\tconst int sign_steer_v = steer_v < 0 ? -1 : steer_v > 0 ? 1 : 0;\n\t\t\t\t\tres.points[i + n + prev_point_count].steer_f.push_back(steer_v * f_s_v + sign_steer_v * f_s_s);\n\t\t\t\t}\n\n\t\t\t\tres.points[i + n + prev_point_count].steer_pos.push_back(angles_positions[k][1]);\n\n\t\t\t\tprev_steer_pos[k] = angles_positions[k][1];\n\n\t\t\t\t//ROS_INFO_STREAM(\"drive_pos: \" << res.points[i+n+prev_point_count].drive_pos[k] << \"drive_f: \" << res.points[i+n+prev_point_count].drive_f[k] << \"steer_pos: \" << res.points[i+n+prev_point_count].steer_pos[k]);\n\t\t\t}\n\t\t}\n\t\tprev_point_count += point_count + n - k_p;\n\t\t//ROS_ERROR_STREAM(\"l: \" <<  prev_point_count << \" P: \" << point_count);\n\t}\n\n\tgraph_prof.call(graph_msg);\n\tres.points.erase(res.points.begin() + prev_point_count, res.points.end());\n\tROS_INFO_STREAM(\"profile time: \" << res.points.size() * defined_dt);\n\n\tres.joint_trajectory = graph_msg.request.joint_trajectory;\n\n\t//talon_swerve_drive_controller::MotionProfilePoints graph_swerve_msg;\n\t//graph_swerve_msg.request.points = res.points;\n\t//graph_swerve_prof.call(graph_swerve_msg);\n\t//ROS_WARN(\"FIN\");\n\treturn true;\n}\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"point_gen\");\n\tros::NodeHandle nh;\n\n\tros::NodeHandle controller_nh(nh, \"swerve_drive_controller\");\n\n\t//double wheel_radius;\n\tbool invert_wheel_angle;\n\tswerveVar::ratios drive_ratios;\n\tswerveVar::encoderUnits units;\n\tdouble max_accel;\n\tdouble max_brake_accel;\n\tdouble ang_accel_conv;\n\n\tif (!controller_nh.getParam(\"f_s\", f_s))\n\t\tROS_ERROR(\"Could not read f_s in point gen\");\n\tif (!controller_nh.getParam(\"f_a\", f_a))\n\t\tROS_ERROR(\"Could not read f_a in point gen\");\n\tif (!controller_nh.getParam(\"f_v\", f_v))\n\t\tROS_ERROR(\"Could not read f_v in point gen\");\n\tif (!controller_nh.getParam(\"f_s_v\", f_s_v))\n\t\tROS_ERROR(\"Could not read f_s_v in point gen\");\n\tif (!controller_nh.getParam(\"f_s_s\", f_s_s))\n\t\tROS_ERROR(\"Could not read f_s_s in point gen\");\n\n\tif (!controller_nh.getParam(\"wheel_radius\", model.wheelRadius))\n\t\tROS_ERROR(\"Could not read wheel_radius in point_gen\");\n\tif (!controller_nh.getParam(\"max_accel\", max_accel))\n\t\tROS_ERROR(\"Could not read max_accel in point_gen\");\n\tif (!controller_nh.getParam(\"max_brake_accel\", max_brake_accel))\n\t\tROS_ERROR(\"Could not read max_brake_accel in point_gen\");\n\tif (!controller_nh.getParam(\"ang_accel_conv\", ang_accel_conv))\n\t\tROS_ERROR(\"Could not read ang_accel_conv in point_gen\");\n\tif (!controller_nh.getParam(\"max_speed\", model.maxSpeed))\n\t\tROS_ERROR(\"Could not read max_speed in point_gen\");\n\tif (!controller_nh.getParam(\"mass\", model.mass))\n\t\tROS_ERROR(\"Could not read mass in point_gen\");\n\tif (!controller_nh.getParam(\"motor_free_speed\", model.motorFreeSpeed))\n\t\tROS_ERROR(\"Could not read motor_free_speed in point_gen\");\n\tif (!controller_nh.getParam(\"motor_stall_torque\", model.motorStallTorque))\n\t\tROS_ERROR(\"Could not read motor_stall_torque in point_gen\");\n\t// TODO : why not just use the number of wheels read from yaml?\n\tif (!controller_nh.getParam(\"motor_quantity\", model.motorQuantity))\n\t\tROS_ERROR(\"Could not read motor_quantity in point_gen\");\n\tif (!controller_nh.getParam(\"invert_wheel_angle\", invert_wheel_angle))\n\t\tROS_ERROR(\"Could not read invert_wheel_angle in point_gen\");\n\tif (!controller_nh.getParam(\"ratio_encoder_to_rotations\", drive_ratios.encodertoRotations))\n\t\tROS_ERROR(\"Could not read ratio_encoder_to_rotations in point_gen\");\n\tif (!controller_nh.getParam(\"ratio_motor_to_rotations\", drive_ratios.motortoRotations))\n\t\tROS_ERROR(\"Could not read ratio_motor_to_rotations in point_gen\");\n\tif (!controller_nh.getParam(\"ratio_motor_to_steering\", drive_ratios.motortoSteering))\n\t\tROS_ERROR(\"Could not read ratio_motor_to_steering in point_gen\");\n\tif (!controller_nh.getParam(\"encoder_drive_get_V_units\", units.rotationGetV))\n\t\tROS_ERROR(\"Could not read encoder_drive_get_V_units in point_gen\");\n\tif (!controller_nh.getParam(\"encoder_drive_get_P_units\", units.rotationGetP))\n\t\tROS_ERROR(\"Could not read encoder_drive_get_P_units in point_gen\");\n\tif (!controller_nh.getParam(\"encoder_drive_set_V_units\", units.rotationSetV))\n\t\tROS_ERROR(\"Could not read encoder_drive_set_V_units in point_gen\");\n\tif (!controller_nh.getParam(\"encoder_drive_set_P_units\", units.rotationSetP))\n\t\tROS_ERROR(\"Could not read encoder_drive_set_P_units in point_gen\");\n\tif (!controller_nh.getParam(\"encoder_steering_get_units\", units.steeringGet))\n\t\tROS_ERROR(\"Could not read encoder_steering_get_units in point_gen\");\n\tif (!controller_nh.getParam(\"encoder_steering_set_units\", units.steeringSet))\n\t\tROS_ERROR(\"Could not read encoder_steering_set_units in point_gen\");\n\tstd::array<Eigen::Vector2d, WHEELCOUNT> wheel_coords;\n\tif (!controller_nh.getParam(\"wheel_coords1x\", wheel_coords[0][0]))\n\t\tROS_ERROR(\"Could not read wheel_coords1x in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords2x\", wheel_coords[1][0]))\n\t\tROS_ERROR(\"Could not read wheel_coords2x in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords3x\", wheel_coords[2][0]))\n\t\tROS_ERROR(\"Could not read wheel_coords3x in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords4x\", wheel_coords[3][0]))\n\t\tROS_ERROR(\"Could not read wheel_coords4x in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords1y\", wheel_coords[0][1]))\n\t\tROS_ERROR(\"Could not read wheel_coords1y in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords2y\", wheel_coords[1][1]))\n\t\tROS_ERROR(\"Could not read wheel_coords2y in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords3y\", wheel_coords[2][1]))\n\t\tROS_ERROR(\"Could not read wheel_coords3y in point_gen\");\n\tif (!controller_nh.getParam(\"wheel_coords4y\", wheel_coords[3][1]))\n\t\tROS_ERROR(\"Could not read wheel_coords4y in point_gen\");\n\n\t//ROS_WARN(\"point_init\");\n\t//ROS_INFO_STREAM(\"model max speed: \" << model.maxSpeed << \" radius: \" << model.wheelRadius);\n\n\tXmlRpc::XmlRpcValue wheel_list;\n\tcontroller_nh.getParam(\"steering\", wheel_list);\n\n\tstd::vector<std::string> wheel_names;\n\twheel_names.resize(wheel_list.size());\n\tfor (int i = 0; i < wheel_list.size(); ++i)\n\t{\n\t\twheel_names[i] = static_cast<std::string>(wheel_list[i]);\n\t}\n\tstd::vector<double> offsets;\n\tfor (auto it = wheel_names.cbegin(); it != wheel_names.cend(); ++it)\n\t{\n\t\tros::NodeHandle nh(controller_nh, *it);\n\t\tdouble dbl_val = 0;\n\t\tif (!nh.getParam(\"offset\", dbl_val))\n\t\t\tROS_ERROR_STREAM(\"Can not read offset for \" << *it);\n\t\toffsets.push_back(dbl_val);\n\t}\n\n\tswerve_math = std::make_shared<swerve>(wheel_coords, offsets, invert_wheel_angle, drive_ratios, units, model);\n\tdefined_dt = .02;\n\tprofile_gen = std::make_shared<swerve_profile::swerve_profiler>(hypot(wheel_coords[0][0], wheel_coords[0][1]), max_accel, model.maxSpeed, 1, 1, defined_dt, ang_accel_conv, max_brake_accel); //Fix last val\n\t//Something to get intial wheel position\n\n\tstd::map<std::string, std::string> service_connection_header;\n\tservice_connection_header[\"tcp_nodelay\"] = \"1\";\n\tgraph_prof = nh.serviceClient<talon_swerve_drive_controller::MotionProfile>(\"/visualize_profile\", false, service_connection_header);\n\tgraph_swerve_prof = nh.serviceClient<talon_swerve_drive_controller::MotionProfilePoints>(\"/visualize_swerve_profile\", false, service_connection_header);\n\n\tros::service::waitForService(\"swerve_drive_controller/wheel_pos\");\n\tROS_ERROR(\"DONE WAITING FOR wheel_pos\");\n\tget_pos = nh.serviceClient<talon_swerve_drive_controller::WheelPos>(\"swerve_drive_controller/wheel_pos\", false, service_connection_header);\n\n\t// Once everything this node needs is available, open\n\t// it up to connections from the outside\n        //ROS_ERROR(\"BEFORE advertiseService\");\n\tros::ServiceServer service = nh.advertiseService(\"/point_gen/command\", full_gen);\n\t//ROS_ERROR(\"AFTER advertiseService\");\n\n\tros::spin();\n}\n", "meta": {"hexsha": "8181e99bb731ee8c374484bc57878ccbe4d581a8", "size": 18233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "zebROS_ws/src/swerve_point_generator/src/point_gen.cpp", "max_stars_repo_name": "FRC900/2018Offseason", "max_stars_repo_head_hexsha": "9940869e9c126c6b0beaa5517d1e719ed5063a35", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T20:54:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-24T20:54:20.000Z", "max_issues_repo_path": "zebROS_ws/src/swerve_point_generator/src/point_gen.cpp", "max_issues_repo_name": "FRC900/2018Offseason", "max_issues_repo_head_hexsha": "9940869e9c126c6b0beaa5517d1e719ed5063a35", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zebROS_ws/src/swerve_point_generator/src/point_gen.cpp", "max_forks_repo_name": "FRC900/2018Offseason", "max_forks_repo_head_hexsha": "9940869e9c126c6b0beaa5517d1e719ed5063a35", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-19T00:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-19T00:40:39.000Z", "avg_line_length": 44.3625304136, "max_line_length": 377, "alphanum_fraction": 0.6999945154, "num_tokens": 5360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6306720260379342}}
{"text": "#include <qpOASES.hpp>\n#include <iostream>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n//#include <OptimalControl/ControlsLibrary.hpp>\n\nusing namespace qpOASES;\n\n\nusing Eigen::MatrixXd;\n\n\nint main()\n{\n    /*\n    MatrixXd A(2,2);\n    MatrixXd B(2,1);\n    A(0,0) = 1;\n    A(0,1) = 1;\n    A(1,1) = 1;\n    A(1,0) = 1;\n    B(0,0) = 10;\n    B(1,0) = 10;\n\n    MatrixXd A_d, B_d;\n    \n    ControlsLibrary::ContinuousToDiscrete(A, B, 0.1, A_d, B_d);\n    \n    cout <<A_d << endl << B_d << endl; */\n\n\n    // QProblem qp(2,1);\n\n    // MatrixXd H(2,2);\n    // MatrixXd A(1,2);\n    // MatrixXd g(2,1);\n    // MatrixXd lbA(1,1);\n\n    // H = 2*MatrixXd::Identity(2,2);\n    // A = MatrixXd::Ones(1,2);\n    // g = MatrixXd::Zero(2,1);\n\n    // lbA << 10;\n    // /*\n\n    // H << 0.4, 0,\n    //      0, 1;\n    // H = 2 * H;\n    // cout << H << endl;\n    // A << 1, -1,\n    //      -0.3, -1;\n    // ubA << -2, -8;\n    // g << -5, -6;\n    // lb << 0, 0;\n    // ub << 10, 10; */\n\n\n    // cout << H << endl;\n    // cout << A << endl;\n    // cout << lbA << endl;\n    // cout << g << endl;\n\n    // int nWSR = 10;\n    // qp.setPrintLevel(qpOASES::PL_MEDIUM);\n    // qp.init(H.data(), g.data(), A.data(), NULL, NULL, lbA.data(), NULL, nWSR);\n    // MatrixXd x_out(2,1);\n\n    // qp.getPrimalSolution(x_out.data());\n\n    // cout << x_out << endl;\n    //cout << qp.getObjVal() << endl;\n\n\n     qpOASES::int_t vars = 2;\n     qpOASES::int_t cons = 2;\n\n    QProblem qp(vars,cons);\n\n     Eigen::Matrix<double, 2, 2, Eigen::RowMajor> H;\n     Eigen::Matrix<double, 2, 2, Eigen::RowMajor> A;\n\n   // MatrixXd H(2,2);\n   // MatrixXd A(2,2);\n    MatrixXd g(2,1);\n    MatrixXd ubA(2,1);\n    //MatrixXd lbX(2,1);\n    //MatrixXd ubX(2,1);\n\n    H << 0.4, 0.0,\n         0.0, 1.0;\n\n    H = 2 * H;\n\n    A << 1.0, -1.0,\n         -0.3, -1.0;\n\n    ubA << -2, -8;\n\n    g << -5, -6;\n    //lbX << 0, 0;\n    //ubX << 10, 10;\n\n    std::cout << H << std::endl;\n    std::cout << H.data()[0] << std::endl;\n    std::cout << H.data()[1] << std::endl;\n    std::cout << H.data()[2] << std::endl;\n    std::cout << H.data()[3] << std::endl;\n    std::cout << A << std::endl;\n\n    std::cout << A.data()[0] << std::endl;\n    std::cout << A.data()[1] << std::endl;\n    std::cout << A.data()[2] << std::endl;\n    std::cout << A.data()[3] << std::endl;\n\n    std::cout << g << std::endl;\n //   cout << ubA << endl;\n    std::cout << ubA << std::endl;\n    //cout << lbX << endl;\n    //cout << ubX << endl;\n\n     qpOASES::Options myOptions;\n     //myOptions.enableRamping = BT_FALSE;\n     //myOptions.maxPrimalJump = 1;\n     //myOptions.setToMPC();\n    qpOASES::int_t nWSR = 10;\n    qp.setPrintLevel(qpOASES::PL_HIGH);\n    qp.setOptions(myOptions);\n    qp.init(H.data(), g.data(), A.data(), NULL, NULL, NULL, ubA.data(), nWSR);\n    MatrixXd x_out(2,1);\n\n    qp.getPrimalSolution(x_out.data());\n    // qp.printOptions();\n    std::cout << x_out << std::endl;\n}   ", "meta": {"hexsha": "ec5e6c7274794122fcfee6e9dac3cd74b0069d86", "size": 2908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Software/Core/Controllers/test/qp_solver_test.cpp", "max_stars_repo_name": "implementedrobotics/Nomad", "max_stars_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T18:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T01:22:55.000Z", "max_issues_repo_path": "Software/Core/Controllers/test/qp_solver_test.cpp", "max_issues_repo_name": "implementedrobotics/Nomad", "max_issues_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2019-05-29T12:57:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-29T02:26:06.000Z", "max_forks_repo_path": "Software/Core/Controllers/test/qp_solver_test.cpp", "max_forks_repo_name": "implementedrobotics/Nomad", "max_forks_repo_head_hexsha": "de8c27ed79cdcde59b1fd6e9a0865d29b84b7d58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T03:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T05:34:16.000Z", "avg_line_length": 21.7014925373, "max_line_length": 81, "alphanum_fraction": 0.4869325997, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6306579383698453}}
{"text": "#include \"stdafx.h\"\n\n#include \"problem.hpp\"\n\n#include <fstream>\n#include <functional>\n#include <vector>\n\n#include <boost/algorithm/string.hpp>\n\nstruct advent_2015_2 : problem\n{\n\tadvent_2015_2() noexcept : problem(2015, 2) {\n\t}\n\n\tstruct box\n\t{\n\t\tstd::size_t l, w, h;\n\t};\n\nprotected:\n\tstd::vector<box> boxes;\n\t\n\tvoid prepare_input(std::ifstream& fin) override {\n\t\tfor(std::string line; std::getline(fin, line); ) {\n\t\t\tstd::vector<std::string> fragments;\n\t\t\tboost::split(fragments, line, [](char ch) { return ch == 'x'; });\n\t\t\tboxes.push_back(box{ std::stoull(fragments[0]), std::stoull(fragments[1]), std::stoull(fragments[2]) });\n\t\t}\n\t}\n\n\tstd::size_t get_paper_area(box b) {\n\t\tconst std::size_t areas[] = { b.l * b.w, b.w * b.h, b.h * b.l };\n\t\tconst std::size_t smallest = *std::min_element(std::begin(areas), std::end(areas));\n\t\treturn 2 * std::accumulate(std::begin(areas), std::end(areas), 0ui64) + smallest;\n\t}\n\n\tstd::size_t get_ribbon_length(box b) noexcept {\n\t\tconst std::size_t semiperimeters[] = { b.l + b.w, b.w + b.h, b.h + b.l };\n\t\tconst std::size_t smallest = *std::min_element(std::begin(semiperimeters), std::end(semiperimeters));\n\t\treturn (2 * smallest) + (b.l * b.w * b.h);\n\t}\n\n\tstd::string part_1() override {\n\t\tstd::size_t paper_required = 0;\n\t\tfor(const box b : boxes) {\n\t\t\tpaper_required += get_paper_area(b);\n\t\t}\n\t\treturn std::to_string(paper_required);\n\t}\n\n\tstd::string part_2() override {\n\t\tstd::size_t ribbon_required = 0;\n\t\tfor(const box b : boxes) {\n\t\t\tribbon_required += get_ribbon_length(b);\n\t\t}\n\t\treturn std::to_string(ribbon_required);\n\t}\n};\n\nREGISTER_SOLVER(2015, 2);\n", "meta": {"hexsha": "1db2feface31e0bb30360f393ac73450b2716301", "size": 1598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc/src/2015/day-2.cpp", "max_stars_repo_name": "DrPizza/advent-of-code-2017", "max_stars_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-09T06:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-18T12:15:08.000Z", "max_issues_repo_path": "aoc/src/2015/day-2.cpp", "max_issues_repo_name": "DrPizza/advent-of-code-2017", "max_issues_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-03T17:46:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-03T17:46:56.000Z", "max_forks_repo_path": "aoc/src/2015/day-2.cpp", "max_forks_repo_name": "DrPizza/advent-of-code", "max_forks_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7741935484, "max_line_length": 107, "alphanum_fraction": 0.6570713392, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6306008386889336}}
{"text": "#include <math.h>\r\n#include <float.h>\r\n\r\n#include <Eigen/Sparse>\r\n\r\n#include \"HarmonicMap.h\"\r\n\r\n#ifndef M_PI\r\n#define M_PI 3.141592653589793238462643383279\r\n#endif\r\n\r\nvoid MeshLib::CHarmonicMap::set_mesh(CHarmonicMapMesh* pMesh)\r\n{\r\n    m_pMesh = pMesh;\r\n    \r\n    // 1. compute the weights of edges\r\n    _calculate_edge_weight();\r\n\r\n    // 2. map the boundary to unit circle\r\n    _set_boundary();\r\n\r\n    // 3. initialize the map of interior vertices to (0, 0)\r\n    using M = CHarmonicMapMesh;\r\n    for (M::MeshVertexIterator viter(m_pMesh); !viter.end(); ++viter)\r\n    {\r\n        M::CVertex* pV = *viter;\r\n        if (pV->boundary())\r\n            continue;\r\n\t\t//insert your code here\r\n        pV->uv() = CPoint2(0, 0);\r\n    }\r\n}\r\n\r\ndouble MeshLib::CHarmonicMap::step_one() \r\n{\r\n    if (!m_pMesh)\r\n    {\r\n        std::cerr << \"Should set mesh first!\" << std::endl;\r\n        return DBL_MAX;\r\n    }\r\n\r\n    using M = CHarmonicMapMesh;\r\n\r\n    // move each interior vertex to its weighted center of neighbors\r\n    double max_error = -DBL_MAX;\r\n    for (M::MeshVertexIterator viter(m_pMesh); !viter.end(); ++viter)\r\n    {\r\n        M::CVertex* pV = *viter;\r\n        if (pV->boundary())\r\n            continue;\r\n\r\n        double sw = 0;\r\n        CPoint2 suv(0, 0);\r\n        for (M::VertexVertexIterator vviter(pV); !vviter.end(); vviter++)\r\n        {\r\n            M::CVertex* pW = *vviter;\r\n            M::CEdge* pE = m_pMesh->vertexEdge(pV, pW);\r\n\t\t\t//insert your code here\r\n            suv += pW->uv() * pE->weight();\r\n            sw += pE->weight();\r\n        }\r\n        suv /= sw;\r\n\r\n        double error = (pV->uv() - suv).norm();\r\n        max_error = (error > max_error) ? error : max_error;\r\n        pV->uv() = suv;\r\n    }\r\n\r\n    printf(\"Current max error is %g\\n\", max_error);\r\n    return max_error;\r\n}\r\n\r\nvoid MeshLib::CHarmonicMap::iterative_map(double epsilon)\r\n{\r\n    if (!m_pMesh)\r\n    {\r\n        std::cerr << \"Should set mesh first!\" << std::endl;\r\n        return;\r\n    }\r\n\r\n    using M = CHarmonicMapMesh;\r\n\r\n    // take steps until it converges.\r\n    while (true)\r\n    {\r\n        double error = this->step_one();\r\n        if (error < epsilon)\r\n            break;\r\n    }\r\n}\r\n\r\nvoid MeshLib::CHarmonicMap::map() \r\n{\r\n    if (!m_pMesh)\r\n    {\r\n        std::cerr << \"Should set mesh first!\" << std::endl;\r\n        return;\r\n    }\r\n\r\n    using M = CHarmonicMapMesh;\r\n\r\n    // 1. Initialize\r\n    int vid = 0;  // interior vertex id\r\n    int bid = 0;  // boundary vertex id\r\n    for (M::MeshVertexIterator viter(m_pMesh); !viter.end(); ++viter)\r\n    {\r\n        M::CVertex* pV = *viter;\r\n\r\n        if (pV->boundary())\r\n            pV->idx() = bid++;\r\n        else\r\n            pV->idx() = vid++;\r\n    }\r\n\r\n    int interior_vertices = vid;\r\n    int boundary_vertices = bid;\r\n\r\n    // 2. Set the matrix A and B\r\n    std::vector<Eigen::Triplet<double>> A_coefficients;\r\n    std::vector<Eigen::Triplet<double>> B_coefficients;\r\n\r\n    for (M::MeshVertexIterator viter(m_pMesh); !viter.end(); ++viter)\r\n    {\r\n        M::CVertex* pV = *viter;\r\n        if (pV->boundary())\r\n            continue;\r\n        int vid = pV->idx();\r\n\r\n        double sw = 0;\r\n        for (M::VertexVertexIterator witer(pV); !witer.end(); ++witer)\r\n        {\r\n            M::CVertex* pW = *witer;\r\n            int wid = pW->idx();\r\n\r\n            M::CEdge* e = m_pMesh->vertexEdge(pV, pW);\r\n            double w = e->weight();\r\n\r\n\t\t\t//insert your code here\r\n\t\t\t//construct one element of the matrix A and B, using             \r\n            sw += w;\r\n\t\t\t//there push_back the triplet to A or B coefficients\r\n            if (pW->boundary())\r\n            {\r\n                B_coefficients.push_back(Eigen::Triplet<double>(vid, wid, w));\r\n            }\r\n            else\r\n            {\r\n                A_coefficients.push_back(Eigen::Triplet<double>(vid, wid, -1 * w));\r\n            }\r\n        }\r\n\t\t//insert the diagonal element\r\n        A_coefficients.push_back(Eigen::Triplet<double>(vid, vid, sw));\r\n\r\n    }\r\n\r\n    Eigen::SparseMatrix<double> A(interior_vertices, interior_vertices);\r\n    A.setZero();\r\n    Eigen::SparseMatrix<double> B(interior_vertices, boundary_vertices);\r\n    B.setZero();\r\n    A.setFromTriplets(A_coefficients.begin(), A_coefficients.end());\r\n    B.setFromTriplets(B_coefficients.begin(), B_coefficients.end());\r\n\r\n    // 3. Solve the equations\r\n    Eigen::ConjugateGradient<Eigen::SparseMatrix<double>> solver;\r\n    std::cerr << \"Eigen Decomposition\" << std::endl;\r\n    solver.compute(A);\r\n    std::cerr << \"Eigen Decomposition Finished\" << std::endl;\r\n\r\n    if (solver.info() != Eigen::Success)\r\n    {\r\n        std::cerr << \"Waring: Eigen decomposition failed\" << std::endl;\r\n    }\r\n\r\n    for (int k = 0; k < 2; k++)\r\n    {\r\n        Eigen::VectorXd b(boundary_vertices);\r\n        // set boundary constraints vector b\r\n        for (M::MeshVertexIterator viter(m_pMesh); !viter.end(); ++viter)\r\n        {\r\n            M::CVertex* pV = *viter;\r\n            if (!pV->boundary())\r\n                continue;\r\n            int id = pV->idx();\r\n            b(id) = pV->uv()[k];\r\n        }\r\n\r\n        Eigen::VectorXd c(interior_vertices);\r\n        c = B * b;\r\n\r\n        Eigen::VectorXd x = solver.solve(c); // Ax=c\r\n        if (solver.info() != Eigen::Success)\r\n        {\r\n            std::cerr << \"Waring: Eigen decomposition failed\" << std::endl;\r\n        }\r\n\r\n        // set the images of the harmonic map to interior vertices\r\n        for (M::MeshVertexIterator viter(m_pMesh); !viter.end(); ++viter)\r\n        {\r\n            M::CVertex* pV = *viter;\r\n            if (pV->boundary())\r\n                continue;\r\n            int id = pV->idx();\r\n            pV->uv()[k] = x(id);\r\n        }\r\n    }\r\n}\r\n\r\nvoid MeshLib::CHarmonicMap::_calculate_edge_weight() \r\n{\r\n    using M = CHarmonicMapMesh;\r\n\r\n    // 1. compute edge length\r\n    for (M::MeshEdgeIterator eiter(m_pMesh); !eiter.end(); ++eiter)\r\n    {\r\n        M::CEdge* pE = *eiter;\r\n        M::CVertex* v1 = m_pMesh->edgeVertex1(pE);\r\n        M::CVertex* v2 = m_pMesh->edgeVertex2(pE);\r\n        pE->length() = (v1->point() - v2->point()).norm();\r\n    }\r\n\r\n    // 2. compute corner angle\r\n    for (M::MeshFaceIterator fiter(m_pMesh); !fiter.end(); ++fiter)\r\n    {\r\n        M::CFace* pF = *fiter;\r\n        M::CHalfEdge* pH[3];\r\n\t\t//insert your code here\r\n        int i = 0;\r\n        for (M::FaceHalfedgeIterator fhiter(pF); !fhiter.end(); ++fhiter)\r\n        {\r\n            pH[i] = *fhiter;\r\n            i++;\r\n            assert(i < 4);\r\n        }\r\n        assert(i == 3);\r\n        assert(pH[0]->target() == pH[1]->source());\r\n        assert(pH[1]->target() == pH[2]->source());\r\n        assert(pH[2]->target() == pH[0]->source());\r\n\t\t//use inverse cosine law to compute the corner angles\r\n        pH[0]->angle() = _inverse_cosine_law(static_cast<CHarmonicMapEdge *>(pH[1]->edge())->length(), static_cast<CHarmonicMapEdge*>(pH[2]->edge())->length(), static_cast<CHarmonicMapEdge*>(pH[0]->edge())->length());\r\n        pH[1]->angle() = _inverse_cosine_law(static_cast<CHarmonicMapEdge*>(pH[0]->edge())->length(), static_cast<CHarmonicMapEdge*>(pH[2]->edge())->length(), static_cast<CHarmonicMapEdge*>(pH[1]->edge())->length());\r\n        pH[2]->angle() = _inverse_cosine_law(static_cast<CHarmonicMapEdge*>(pH[1]->edge())->length(), static_cast<CHarmonicMapEdge*>(pH[0]->edge())->length(), static_cast<CHarmonicMapEdge*>(pH[2]->edge())->length());\r\n    }\r\n\r\n    // 3. compute edge weight\r\n    for (M::MeshEdgeIterator eiter(m_pMesh); !eiter.end(); ++eiter)\r\n    {\r\n        M::CEdge* pE = *eiter;\r\n\t\t//insert your code here\r\n        if (pE->halfedge(0) != NULL)\r\n        {\r\n            pE->weight() += std::tan(M_PI / 2 - static_cast<CHarmonicMapHalfEdge*>(pE->halfedge(0))->angle());\r\n        }\r\n        if (pE->halfedge(1) != NULL)\r\n        {\r\n            pE->weight() += std::tan(M_PI / 2 - static_cast<CHarmonicMapHalfEdge*>(pE->halfedge(1))->angle());\r\n        }        \r\n\t\t//set cotangent edge weight\r\n    }\r\n}\r\n\r\nvoid MeshLib::CHarmonicMap::_set_boundary() \r\n{\r\n    using M = CHarmonicMapMesh;\r\n\r\n    // 1. get the boundary half edge loop\r\n    M::CBoundary boundary(m_pMesh);\r\n    std::vector<M::CLoop*>& pLs = boundary.loops();\r\n    if (pLs.size() != 1)\r\n    {\r\n        std::cerr << \"Only topological disk accepted!\" << std::endl;\r\n        exit(EXIT_FAILURE);\r\n    }\r\n    M::CLoop* pL = pLs[0];\r\n    std::list<M::CHalfEdge*>& pHs = pL->halfedges();\r\n    \r\n    // 2. compute the total length of the boundary\r\n    double sum = 0.0;\r\n    std::list<M::CHalfEdge*>::iterator it;\r\n    for (it = pHs.begin(); it != pHs.end(); ++it)\r\n    {\r\n        M::CHalfEdge* pH = *it;\r\n        sum += m_pMesh->halfedgeEdge(pH)->length();\r\n    }\r\n\r\n    // 3. parameterize the boundary using arc length parameter\r\n    double len = 0.0;\r\n    for (it = pHs.begin(); it != pHs.end(); ++it)\r\n    {\r\n        M::CHalfEdge* pH = *it;\r\n        M::CVertex* pV = m_pMesh->halfedgeVertex(pH);\r\n\r\n        len += m_pMesh->halfedgeEdge(pH)->length();\r\n        double angle = len / sum * 2.0 * M_PI;\r\n        pV->uv() = CPoint2(cos(angle), sin(angle)); \r\n    }\r\n}\r\n\r\ndouble MeshLib::CHarmonicMap::_inverse_cosine_law(double a, double b, double c) \r\n{ \r\n    double cs = (a * a + b * b - c * c) / (2.0 * a * b);\r\n    assert(cs <= 1.0 && cs >= -1.0);\r\n    return std::acos(cs);\r\n}\r\n", "meta": {"hexsha": "eeec0390a67238bba2d06be756831f718952900a", "size": 9275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HarmonicMap.cpp", "max_stars_repo_name": "zhangchuangnankai/2020-Computational-Conformal-Geometry-homework", "max_stars_repo_head_hexsha": "6454a2b800ac768163506b6e723d2376b396da8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-10T02:46:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T02:46:41.000Z", "max_issues_repo_path": "HarmonicMap.cpp", "max_issues_repo_name": "zhangchuangnankai/2020-Computational-Conformal-Geometry-homework", "max_issues_repo_head_hexsha": "6454a2b800ac768163506b6e723d2376b396da8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HarmonicMap.cpp", "max_forks_repo_name": "zhangchuangnankai/2020-Computational-Conformal-Geometry-homework", "max_forks_repo_head_hexsha": "6454a2b800ac768163506b6e723d2376b396da8b", "max_forks_repo_licenses": ["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.5098684211, "max_line_length": 218, "alphanum_fraction": 0.5330458221, "num_tokens": 2648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6305936321317377}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2010 Sebastian Schlenkrich\n\n*/\n\n\n\n#ifndef quantlib_gausslobatto_hpp\n#define quantlib_gausslobatto_hpp\n\n#include <ql/types.hpp>\n#include <boost/function.hpp>\n\n\nnamespace TemplateAuxilliaries {\n\n    //! Template for Gauss-Lobatto integration, see gausslobattointegral.hpp/.cpp\n    template <class Type>\n    class GaussLobatto {\n    private:\n        //! local types\n        typedef double Real;\n        //! attributes\n        mutable size_t maxEvaluations_;\n        mutable Type absAccuracy_;\n        mutable Type relAccuracy_;\n        mutable Type absError_;\n        mutable size_t evaluations_;\n        const bool useConvergenceEstimate_;\n        //! constants\n        const static double alpha_, beta_, x1_, x2_, x3_;\n        //! specific integration routines\n        Type calculateAbsTolerance(const boost::function<Type (Type)>& f, Type a, Type b) const;\n        Type adaptivGaussLobattoStep(const boost::function<Type (Type)>& f, Type a, Type b, Type fa, Type fb, Type acc) const;\n    public:\n        //! constructor\n        GaussLobatto( size_t maxEvaluations,\n                      Type absAccuracy,\n                      Type relAccuracy = 0,\n                      bool useConvergenceEstimate = true )\n            : maxEvaluations_(maxEvaluations), absAccuracy_(absAccuracy), relAccuracy_(relAccuracy),\n              absError_(0), evaluations_(0), useConvergenceEstimate_(useConvergenceEstimate) {}\n        //! inspectors\n        Type absoluteAccuracy() const { return absAccuracy_;      }\n        Type absoluteError()    const { return absError_;         }\n        size_t maxEvaluations()   const { return maxEvaluations_;   }\n        size_t evaluations()      const { return evaluations_;      }\n        //! modifiers\n        void setNumberOfEvaluations(size_t number)         const { evaluations_ = number; }\n        void increaseNumberOfEvaluations(size_t increase)  const { evaluations_ += increase; }\n        //! integrate function interface\n        Type integrate(const boost::function<Type (Type)>& f, Type a, Type b) const {\n            //setNumberOfEvaluations(0);\n            const Type calcAbsTolerance = calculateAbsTolerance(f, a, b);\n            //increaseNumberOfEvaluations(2);\n            return adaptivGaussLobattoStep(f, a, b, f(a), f(b), calcAbsTolerance);\n        }\n    };\n\n    template <class Type> const double GaussLobatto<Type>::alpha_ = std::sqrt(2.0/3.0); \n    template <class Type> const double GaussLobatto<Type>::beta_  = 1.0/std::sqrt(5.0);\n    template <class Type> const double GaussLobatto<Type>::x1_    = 0.94288241569547971906; \n    template <class Type> const double GaussLobatto<Type>::x2_    = 0.64185334234578130578;\n    template <class Type> const double GaussLobatto<Type>::x3_    = 0.23638319966214988028;\n\n    template <class Type> Type\n    GaussLobatto<Type>::calculateAbsTolerance( const boost::function<Type (Type)>& f, Type a, Type b) const {\n        Type relTol = (relAccuracy_ > QL_EPSILON) ? relAccuracy_ : QL_EPSILON;\n        \n        const Type m = (a+b)/2; \n        const Type h = (b-a)/2;\n        const Type y1 = f(a);\n        const Type y3 = f(m-alpha_*h);\n        const Type y5 = f(m-beta_*h);\n        const Type y7 = f(m);\n        const Type y9 = f(m+beta_*h);\n        const Type y11= f(m+alpha_*h);\n        const Type y13= f(b);\n\n        Type acc=h*(0.0158271919734801831*(y1+y13)\n                  +0.0942738402188500455*(f(m-x1_*h)+f(m+x1_*h))\n                  +0.1550719873365853963*(y3+y11)\n                  +0.1888215739601824544*(f(m-x2_*h)+ f(m+x2_*h))\n                  +0.1997734052268585268*(y5+y9) \n                  +0.2249264653333395270*(f(m-x3_*h)+f(m+x3_*h))\n                  +0.2426110719014077338*y7);  \n        \n        increaseNumberOfEvaluations(13);\n        QL_REQUIRE(acc != 0.0, \"can not calculate absolute accuracy from \"\n                               \"relative accuracy\");\n\n        Type r = 1.0;\n        if (useConvergenceEstimate_) {\n            const Type integral2 = (h/6)*(y1+y13+5*(y5+y9));\n            const Type integral1 = (h/1470)*(77*(y1+y13)+432*(y3+y11)+\n                                             625*(y5+y9)+672*y7);\n        \n            if (fabs(integral2-acc) != 0.0) \n                r = fabs(integral1-acc)/fabs(integral2-acc);\n            if (r == 0.0 || r > 1.0)\n                r = 1.0;\n        }\n\n        if (relAccuracy_ != 0)\n            return  ((absoluteAccuracy() < acc*relTol) ? absoluteAccuracy() : acc*relTol)/(r*QL_EPSILON);\n                    //min(absoluteAccuracy(), acc*relTol)/(r*QL_EPSILON);\n        else {\n            return absoluteAccuracy()/(r*QL_EPSILON);\n        }\n    }\n\n    template <class Type> Type\n    GaussLobatto<Type>::adaptivGaussLobattoStep(const boost::function<Type (Type)>& f, Type a, Type b, Type fa, Type fb, Type acc) const {\n        QL_REQUIRE(evaluations() < maxEvaluations(),\n                   \"max number of iterations reached\");\n        \n        const Type h=(b-a)/2; \n        const Type m=(a+b)/2;\n        \n        const Type mll=m-alpha_*h; \n        const Type ml =m-beta_*h; \n        const Type mr =m+beta_*h; \n        const Type mrr=m+alpha_*h;\n        \n        const Type fmll= f(mll);\n        const Type fml = f(ml);\n        const Type fm  = f(m);\n        const Type fmr = f(mr);\n        const Type fmrr= f(mrr);\n        increaseNumberOfEvaluations(5);\n        \n        const Type integral2=(h/6)*(fa+fb+5*(fml+fmr));\n        const Type integral1=(h/1470)*(77*(fa+fb)\n                                       +432*(fmll+fmrr)+625*(fml+fmr)+672*fm);\n        \n        // avoid 80 bit logic on x86 cpu\n        Type dist = acc + (integral1-integral2);\n        if(dist==acc || mll<=a || b<=mrr) {\n            QL_REQUIRE(m>a && b>m,\"Interval contains no more machine number\");\n            return integral1;\n        }\n        else {\n            return  adaptivGaussLobattoStep(f,a,mll,fa,fmll,acc)  \n                  + adaptivGaussLobattoStep(f,mll,ml,fmll,fml,acc)\n                  + adaptivGaussLobattoStep(f,ml,m,fml,fm,acc)\n                  + adaptivGaussLobattoStep(f,m,mr,fm,fmr,acc)\n                  + adaptivGaussLobattoStep(f,mr,mrr,fmr,fmrr,acc)\n                  + adaptivGaussLobattoStep(f,mrr,b,fmrr,fb,acc);\n        }\n    }\n    \n}\n\n#endif  /* ifndef quantlib_gausslobatto_hpp */\n", "meta": {"hexsha": "faec5c1b0374dc85490cfcbc8e2d4b6826ad43aa", "size": 6357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/auxilliaries/gausslobattoT.hpp", "max_stars_repo_name": "sschlenkrich/quantlib", "max_stars_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/experimental/templatemodels/auxilliaries/gausslobattoT.hpp", "max_issues_repo_name": "sschlenkrich/quantlib", "max_issues_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/templatemodels/auxilliaries/gausslobattoT.hpp", "max_forks_repo_name": "sschlenkrich/quantlib", "max_forks_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4904458599, "max_line_length": 138, "alphanum_fraction": 0.575900582, "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6305936314501333}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <unistd.h>\n#include <pangolin/pangolin.h>\n#include \"Draw.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(){\n    string traj_file = \"/home/leodu/learn_slambook/ch3/examples/trajectory.txt\";\n    vector<Isometry3d, Eigen::aligned_allocator<Isometry3d>> poses;\n    ifstream fin(traj_file);\n    if(!fin){\n        cout << \"File not found.\" << endl;\n        return 1;\n    }\n    while(!fin.eof()){\n        double time, tx, ty, tz, qw, qx, qy, qz;\n        fin >> time >> tx >> ty >> tz >> qx >> qy >> qz >> qw;\n        Isometry3d Twr(Quaterniond(qw,qx,qy,qz));\n        Twr.pretranslate(Vector3d(tx,ty,tz));\n        poses.push_back(Twr);\n//        cout << \"Twr = \\n\" << Twr.matrix() << endl;\n    }\n    Draw draw(poses);\n    draw.drawTraj();\n\n}", "meta": {"hexsha": "6739587f2bcf32b9f4fc30642dc494d20bf4d1f1", "size": 839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/examples/plotCamera.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": "ch3/examples/plotCamera.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": "ch3/examples/plotCamera.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": 27.064516129, "max_line_length": 80, "alphanum_fraction": 0.6019070322, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6305936265671899}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <math.h>\n#include <cassert>\n#include <vector>\n#include <algorithm>\n#include <Eigen/Core>\n#include \"metro/log_sum_exp.hpp\"\n\nnamespace metro {\n\ttemplate<>\n\tdouble log_sum_exp( std::vector< double > const& data ) {\n\t\tif( data.size() == 0 ) {\n\t\t\treturn -std::numeric_limits< double >::infinity() ;\n\t\t}\n\t\tstd::vector< double >::const_iterator max_i = std::max_element( data.begin(), data.end() ) ;\n\t\tdouble const max_value = *max_i ;\n\t\tif( max_value == -std::numeric_limits< double >::infinity() ) {\n\t\t\treturn max_value ;\n\t\t}\n\t\t// exponentiate\n\t\tdouble result = max_value ;\n\t\tfor( std::size_t i = 0; i < data.size(); ++i ) {\n\t\t\tresult += std::exp(data[i] - max_value) ;\n\t\t}\n\t\treturn max_value + std::log( result ) ;\n\t}\n\t\n\tvoid rowwise_log_sum_exp( Eigen::MatrixXd const& data, Eigen::VectorXd* result ) {\n\t\tassert( result ) ;\n\t\tassert( result->size() == data.rows() ) ;\n\n\t\tfor( int i = 0; i < result->size(); ++i ) {\n\t\t\t(*result)(i) = log_sum_exp( data.row(i) ) ;\n\t\t}\n\t}\n\tvoid rowwise_log_sum_exp( Eigen::MatrixXd const& data, Eigen::MatrixXd const& nonmissingness, Eigen::VectorXd* result ) {\n\t\tassert( result ) ;\n\t\tassert( result->size() == data.rows() ) ;\n\t\tassert( data.rows() == nonmissingness.rows() ) ;\n\t\tassert( data.cols() == nonmissingness.cols() ) ;\n\n\t\tfor( int i = 0; i < result->size(); ++i ) {\n\t\t\t(*result)(i) = log_sum_exp( data.row(i), nonmissingness.row(i) ) ;\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "cacab81388337c5b64970cebebbc018c9ae08a6c", "size": 1607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metro/src/log_sum_exp.cpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "metro/src/log_sum_exp.cpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "metro/src/log_sum_exp.cpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9038461538, "max_line_length": 122, "alphanum_fraction": 0.6309894213, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6305936265671899}}
{"text": "\n#define _LIE_ALGEBRA_\n\n\n#include <iostream>\n#include <vector>\n#include <armadillo>\n#include <cmath>\n#include <algorithm>\n\n#ifdef _WEIGHTED_MAT_\n#else\n#include \"weightedMat.hpp\"\n#endif\n\nusing arma::cx_mat;\nusing arma::kron;\n\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\n\nclass LieAlgebra\n{\n\n  public:\n\n    LieAlgebra(int n, double penalty)\n    {\n      basisGenerator(n, penalty, lieBasis);\n    }\n\n    ~LieAlgebra();\n\n    vector<weightedMat> lieBasis;\n\n    struct byCost\n    {\n        bool operator()(weightedMat const &a, weightedMat const &b)\n        {\n          \t\treturn a.cost < b.cost;\n        }\n    };\n\n  private:\n\n    cx_double imagI = cx_double(0.0, 1.0);\n\n    void generatorLoop(int depth,\n              vector<int> & indices,\n              vector<int> & maxIndex,\n              vector<cx_mat>& Paulis,\n              vector<weightedMat>& lieBasis,\n              double penalty\n              )\n    {\n      if (depth>0){\n         for(int i = 0; i < maxIndex[depth-1]; ++i){\n            indices[depth-1] = i;\n            generatorLoop(depth-1, indices, maxIndex, Paulis, lieBasis, penalty);\n         }\n      }\n      else\n      {\n          // indices of tensor product\n          //cout << \"indices : \";\n          int numNonZeros = 0;\n          weightedMat temp;\n          temp.lieMat = Paulis[indices[0]];\n\n          for(int r = 0; r < indices.size(); ++r)\n          {\n            if(indices[r] != 0)\n            {\n              ++numNonZeros;\n            }\n            //cout << indices[r] <<\" \";\n          }\n\n          if(numNonZeros < 3 )\n          {\n            temp.cost = 1;\n          }\n          else\n          {\n            temp.cost = penalty;\n          }\n\n          //make kronecker products\n          for(int r = 1; r < indices.size(); ++r)\n          {\n            temp.lieMat = kron(temp.lieMat, Paulis[indices[r]]);\n          }\n\n          temp.lieMat *= imagI;\n\n\n          //sub riemannian case\n          lieBasis.push_back(temp);\n\n       }\n    }\n\n    //n is 2^n in SU(2^n)\n    void basisGenerator(int n, double penalty, vector<weightedMat>& lieBasis)\n    {\n\n      vector<cx_mat> Paulis;\n      Paulis.reserve(4);\n\n      Paulis[0] = eye<cx_mat>(2,2);\n      Paulis[1] = { {0.0,0.0}, {1.0,0.0}, {1.0,0.0}, {0.0,0.0} };\n      Paulis[2] = { {0.0,0.0}, {0.0,1.0}, {0.0,-1.0}, {0.0,0.0} };\n      Paulis[3] = { {1.0,0.0}, {0.0,0.0}, {0.0,0.0}, {-1.0,0.0} };\n\n      for(int s = 1; s < 4; ++s)\n      {\n        Paulis[s].reshape(2,2);\n      }\n\n      vector<int> indices(n,0);\n      vector<int> maxIndex;\n\n      for(int i=0; i<n; ++i)\n      {\n        maxIndex.push_back(4);\n      }\n\n      generatorLoop(indices.size(),indices, maxIndex, Paulis, lieBasis, penalty);\n\n      //for SU remove the identity product I otimes I .... otimes I\n      lieBasis.erase(lieBasis.begin());\n      std::sort(lieBasis.begin(), lieBasis.end(), byCost());\n\n      cout << \"number of basis elements : \" << lieBasis.size() << endl;\n      for(int i=0; i< lieBasis.size(); ++i)\n      {\n        cout << \"basis element :\" << i << \" with cost :\" << lieBasis[i].cost << endl << lieBasis[i].lieMat << endl;\n      }\n    }\n};\n", "meta": {"hexsha": "ba6b93480642675d3a29fe77b2364ca95f245190", "size": 3107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/lieAlgebra.cpp", "max_stars_repo_name": "Swaddle/qGeod", "max_stars_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/lieAlgebra.cpp", "max_issues_repo_name": "Swaddle/qGeod", "max_issues_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/lieAlgebra.cpp", "max_forks_repo_name": "Swaddle/qGeod", "max_forks_repo_head_hexsha": "8108fe44c09c0c89b23cf5f14efa098b09d6bcf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7272727273, "max_line_length": 115, "alphanum_fraction": 0.4940457033, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6305936216842467}}
{"text": "// number_systems.cpp: performance comparison between different number systems\n//\n// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.\n//\n// This file is part of the HPRBLAS project, which is released under an MIT Open Source license.\n#include <boost/multiprecision/cpp_bin_float.hpp>\n//#define POSIT_FAST_SPECIALIZATION 1\n#define POSIT_FAST_POSIT_16_1 1\n#define POSIT_FAST_POSIT_32_2 1\n#include <universal/number/posit/posit.hpp>\n#include <universal/performance/number_system.hpp>\n\n// define a true 256-bit IEEE floating point type\nconstexpr size_t bits_in_octand = 113 + 128;\nusing cpp_bin_float_octand = boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<bits_in_octand, boost::multiprecision::backends::digit_base_2, void, boost::int16_t, -16382, 16383>, boost::multiprecision::expression_template_option::et_off>;\n// define the floating point types (single, double, quad, octand)\nusing sp = boost::multiprecision::cpp_bin_float_single;\nusing dp = boost::multiprecision::cpp_bin_float_double;\nusing qp = boost::multiprecision::cpp_bin_float_quad;\nusing op = cpp_bin_float_octand;\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace sw::universal;\n\n\tcout << \"Arithmetic performance comparison\" << endl;\n\n\tposit<16,1> p16;\n\tfloat f;\n\tsp boostsp;\n\tposit<32, 2> p32;\n\n\tOperatorPerformance report;\n\tGeneratePerformanceReport(f, report);\n\tcout << ReportPerformance(f, report) << endl;\n//\tGeneratePerformanceReport(boostsp, report);\n//\tcout << ReportPerformance(boostsp, report) << endl;\n\tGeneratePerformanceReport(p16, report);\n\tcout << ReportPerformance(p16, report) << endl;\n\tGeneratePerformanceReport(p32, report);\n\tcout << ReportPerformance(p32, report) << 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": "5daba832c8b221eb920ffe66c9522533b4ae8372", "size": 2501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/benchmark/number_systems.cpp", "max_stars_repo_name": "stillwater-sc/hpr-blas", "max_stars_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-13T10:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T20:30:58.000Z", "max_issues_repo_path": "tools/benchmark/number_systems.cpp", "max_issues_repo_name": "stillwater-sc/hpr-blas", "max_issues_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T11:19:32.000Z", "max_forks_repo_path": "tools/benchmark/number_systems.cpp", "max_forks_repo_name": "stillwater-sc/hpr-blas", "max_forks_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:35:35.000Z", "avg_line_length": 35.7285714286, "max_line_length": 266, "alphanum_fraction": 0.7493002799, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6305936161196989}}
{"text": "#include \"config.hpp\"\n#include \"include/common.hpp\"\n#include \"include/pi.hpp\"\n#include <boost/mpi.hpp>\n#include <boost/program_options.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nnamespace mpi = boost::mpi;\nnamespace po = boost::program_options;\nnamespace mp = boost::multiprecision;\n\nusing number = mp::number<mp::cpp_dec_float<10000>>;\nconstexpr int ROOT = 0;\n\nnamespace mpi_pi {\n\nint main(int argc, char **argv) {\n  mpi::environment env(argc, argv, false);\n  mpi::communicator world;\n\n  config::Configuration config;\n  po::options_description description(\"options\");\n  if (world.rank() == ROOT) {\n    description.add_options()(\"help,h\", \"print help message\");\n    description.add_options()(\n        \"method,m\", po::value<std::string>()->default_value(\"area_integral\"),\n        \"method to calculate pi\");\n    description.add_options()(\"terms,t\",\n                              po::value<std::size_t>()->default_value(1000),\n                              \"terms number to calculate\");\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, description), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\"))\n      config.show_help = true;\n    if (vm.count(\"method\"))\n      config.method = vm[\"method\"].as<std::string>();\n    if (vm.count(\"terms\"))\n      config.terms = vm[\"terms\"].as<std::size_t>();\n  }\n\n  mpi::broadcast(world, config, ROOT);\n\n  if (config.show_help) {\n    if (world.rank() == ROOT) {\n      std::cout << description << std::endl;\n    }\n    return 0; // all processes exit\n  }\n\n  number result;\n  if (config.method == \"area_integral\") {\n    result = area_integral::pi<number>(world, ROOT, config.terms);\n  } else if (config.method == \"power_series\") {\n    result = power_series::pi<number>(world, ROOT, config.terms);\n  } else if (config.method == \"improved_power_series\") {\n    result = improved_power_series::pi<number>(world, ROOT, config.terms);\n  } else if (config.method == \"monte_carlo\") {\n    result = monte_carlo::pi<number>(world, ROOT, config.terms);\n  } else if (config.method == \"monte_carlo_integral\") {\n    result = monte_carlo_integral::pi<number>(world, ROOT, config.terms);\n  } else if (config.method == \"random_integral\") {\n    result = random_integral::pi<number>(world, ROOT, config.terms);\n  } else if (config.method == \"borwein1987\") {\n    result = borwein1987::pi<number>(world, ROOT, config.terms);\n  } else if (config.method == \"yasumasa2002\") {\n    result = yasumasa2002::pi<number>(world, ROOT, config.terms);\n  } else if (config.method == \"chudnovsky\") {\n    result = chudnovsky::pi<number>(world, ROOT, config.terms);\n  } else if (config.method == \"bbp\") {\n    result = bbp::pi<number>(world, ROOT, config.terms);\n  } else {\n    std::cout << \"invalid method \\\"\" << config.method << \"\\\"\" << std::endl;\n  }\n  if (world.rank() == ROOT) {\n    std::cout << std::setprecision(std::numeric_limits<number>::max_digits10)\n              << result << std::endl;\n  }\n}\n\n} // namespace mpi_pi\n\nint main(int argc, char **argv) { return mpi_pi::main(argc, argv); }", "meta": {"hexsha": "72cbc7129cf0667305a04141e3311dfdebe1c17e", "size": 3084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "linyinfeng/mpi-pi", "max_stars_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "linyinfeng/mpi-pi", "max_issues_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "linyinfeng/mpi-pi", "max_forks_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0454545455, "max_line_length": 77, "alphanum_fraction": 0.6436446174, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6305936007892641}}
{"text": "//\n//  multivector_AWT.cpp\n//\n//  Created by r. on 18/05/14\n//\n\n// Disables checks in boost\n#ifndef NDEBUG\n#define NDEBUG\n#endif\n\n//\n#include \"../include/reporter.hpp\"\n\n#include <iostream>\n#include \"../include/stopwatch.hpp\"\n#include \"../include/multivector.hpp\"\n#include \"../include/multivector_AWT.hpp\"\n#include \"../include/tFEM.hpp\"\n#include \"../include/AWT.hpp\"\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n\nnamespace mypara\n{\n\tusing namespace std;\n\tnamespace mpi = boost::mpi;\n\tnamespace ublas = boost::numeric::ublas;\n\t\n\tvoid test_multivector_AWT_basic()\n\t{\n\t\tcout << \"Enter: mypara::test_multivector_AWT_basic()\" << endl;\n\t\tstopwatch::Time time(stopwatch::watches, \"mypara::test_multivector_AWT_basic()\");\n\t\t\n\t\tmpi::communicator world;\n\t\t\n\t\ttypedef ublas::matrix<double> matrix;\n\t\t\n\t\tusing namespace mypara;\n\t\t\n\t\tunsigned int size1 = 3; // Number of rows\n\t\tunsigned int size2 = 9; // Number of columns\n\t\t\n\t\t\n\t\t// Create AWT\n\t\tdouble T = 4;\n\t\tspacetime::tmesh te;\n\t\tte.makeuniform(0, T, size2);\n\t\t\n\t\tspacetime::tFEM tfem(te);\n\t\t\n\t\tunsigned int nu = 2;\n\t\tmypara::AWT awt(tfem.AtE, tfem.MtE, nu);\n\t\t\n\t\t// Check generalized \"eigenvalues\" of awt\n\t\t{\n\t\t\tspacetime::AWT awt2(tfem.AtE, tfem.MtE, nu);\n\t\t\tbool ok = true;\n\t\t\tfor (auto i = 0; i != awt.gamma.size(); ++i) {\n\t\t\t\tok = ok && (fabs(awt.gamma[i] - awt2.gamma[i]) <= 1e-8);\n\t\t\t}\n\t\t\tcout << \"Eigenvalues OK? \" << (ok ? \"YES\" : \"NO\") << endl;\n\t\t\tassert(ok);\n\t\t}\n\t\t\n\t\tmatrix v_ref(size1, size2); v_ref.clear();\n\t\t// Create matrix to be distributed\n\t\t{\n\t\t\tfor (unsigned int j = 0; j != size2; ++j)\n\t\t\t{\n\t\t\t\tv_ref(j % size1, j) = 1;\n//\t\t\t\tv_ref(j, j) = 1;\n\t\t\t}\n\t\t}\n\t\t\n\t\tmultivector v(size1, size2, world);\n\t\t// Distributed matrix\n\t\t{\n\t\t\tfor (unsigned int j = v.getja(); j < v.getjb(); ++j) {\n\t\t\t\tv.colio_local(j) = ublas::column(v_ref, j);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Check multivector::get_whole()\n\t\t{\n\t\t\tmatrix z = (v_ref - v.getwhole());\n\t\t\tbool ok = (ublas::norm_frobenius(z) == 0);\n\t\t\tcout << \"Get whole OK? \" << (ok ? \"YES\" : \"NO\") << endl;\n\t\t\tassert(ok);\n\t\t\tworld.barrier();\n\t\t}\n\t\t\n\t\t// Print info\n\t\t{\n\t\t\tfor (unsigned int j = v.getja(); j < v.getjb(); ++j) {\n\t\t\t\tcout << \"Proc \" << world.rank() << \": \" << \"column #\" << j << \" is \" << v.colio_local(j) << endl;\n\t\t\t}\n\t\t\tcout.flush(); world.barrier();\n\t\t}\n\t\t\n\t\t// Multiplication 1\n\t\t{\n\t\t\t// Print info\n\t\t\t{\n\t\t\t\tif (!world.rank()) cout << \"Testing right multiplication by T\" << endl;\n\t\t\t\tcout.flush(); world.barrier();\n\t\t\t}\n\t\t\t\n\t\t\tmultivector w = awt.uT(v);\n\t\t\t\n\t\t\tmatrix w_ref;\n\t\t\t{\n\t\t\t\tspacetime::AWT awt(tfem.AtE, tfem.MtE, nu);\n\t\t\t\tw_ref = ublas::prod(v_ref, awt.V);\n\t\t\t}\n\t\t\t\n\t\t\t// Print info\n\t\t\t{\n\t\t\t\tfor (unsigned int j = w.getja(); j < w.getjb(); ++j) {\n\t\t\t\t\tcout << \"Proc \" << world.rank() << \": \" << \"column #\" << j << \" is \" << w.colio_local(j) << endl;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmultivector::dense_matrix w_whole = w.getwhole();\n\t\t\t\tif (!world.rank()) cout << \"w_whole: \" << w_whole << endl;\n\t\t\t\t\n\t\t\t\tcout.flush(); world.barrier();\n\t\t\t}\n\t\t\t\n\t\t\t// Check multiplication result\n\t\t\t{\n\t\t\t\tif (!world.rank()) cout << \"w_ref: \" << w_ref << endl;\n\t\t\t\tmatrix z = (w_ref - w.getwhole());\n\t\t\t\tbool ok = (ublas::norm_frobenius(z) <= 1e-10);\n\t\t\t\tcout << \"Multiplication 1 OK? \" << (ok ? \"YES\" : \"NO\") << endl;\n\t\t\t\tassert(ok);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Multiplication 2\n\t\t{\n\t\t\t// Print info\n\t\t\t{\n\t\t\t\tif (!world.rank()) cout << \"Testing right multiplication by Tt\" << endl;\n\t\t\t\tcout.flush(); world.barrier();\n\t\t\t}\n\t\t\t\n\t\t\tmultivector w = awt.uTt(v);\n\t\t\t\n\t\t\tmatrix w_ref;\n\t\t\t{\n\t\t\t\tspacetime::AWT awt(tfem.AtE, tfem.MtE, nu);\n\t\t\t\tw_ref = ublas::prod(v_ref, ublas::trans(awt.V));\n\t\t\t}\n\t\t\t\n\t\t\t// Print info\n\t\t\t{\n\t\t\t\tfor (unsigned int j = w.getja(); j < w.getjb(); ++j) {\n\t\t\t\t\tcout << \"Proc \" << world.rank() << \": \" << \"column #\" << j << \" is \" << w.colio_local(j) << endl;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmultivector::dense_matrix w_whole = w.getwhole();\n\t\t\t\tif (!world.rank()) cout << \"w_whole: \" << w_whole << endl;\n\t\t\t\t\n\t\t\t\tcout.flush(); world.barrier();\n\t\t\t}\n\t\t\t\n\t\t\t// Check multiplication result\n\t\t\t{\n\t\t\t\tif (!world.rank()) cout << \"w_ref: \" << w_ref << endl;\n\t\t\t\tmatrix z = (w_ref - w.getwhole());\n\t\t\t\tbool ok = (ublas::norm_frobenius(z) <= 1e-10);\n\t\t\t\tcout << \"Multiplication 2 OK? \" << (ok ? \"YES\" : \"NO\") << endl;\n\t\t\t\tassert(ok);\n\t\t\t}\n\t\t}\n\t\t\n\t\t//\n\t\t{\n\t\t\tmultivector::dense_matrix v_whole = v.getwhole();\n\t\t\t\n\t\t\t// Print info\n\t\t\t{\n\t\t\t\tif (!world.rank()) cout << \"v_whole: \" << v_whole << endl;\n\t\t\t\tcout.flush(); world.barrier();\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tcout << \"Exit: mypara::test_multivector_AWT_basic()\" << endl;\n\t}\n\t\n//\tvoid test_multivector_AWT_large()\n//\t{\n//\t\tcout << \"Enter: mypara::test_multivector_AWT_large()\" << endl;\n//\t\tstopwatch::Time time(stopwatch::watches, \"mypara::test_multivector_AWT_large()\");\n//\t\t\n//\t\tmpi::communicator world;\n//\t\t\n//\t\tunsigned int size1 = 100000;\n//\t\tunsigned int size2 = (1 << 12);\n//\t\t\n//\t\tmultivector v(size1, size2, world);\n//\t\t\n//\t\t{\n//\t\t\ttypedef ublas::compressed_matrix<double> sparse_matrix;\n//\t\t\t\n//\t\t\tsparse_matrix m(size2, size2, 3*size2); m.clear();\n//\t\t\tm = ublas::identity_matrix<>(size2);\n//\t\t\t\n//\t\t\tstopwatch::StopWatch w;\n//\t\t\tw.tic();\n//\t\t\tv * m;\n//\t\t\tw.add();\n//\t\t\t\n//\t\t\t// Print timings\n//\t\t\t{\n//\t\t\t\tcout.flush(); world.barrier();\n//\t\t\t\tif (!world.rank())\n//\t\t\t\t{\n//\t\t\t\t\tcout << \"@iden: \";\n//\t\t\t\t\tcout << \"size2: \" << size2 << \" \";\n//\t\t\t\t\tcout << \"time(ms): \" << w.ms().count() << \" \";\n//\t\t\t\t\tcout << endl;\n//\t\t\t\t}\n//\t\t\t\tworld.barrier();\n//\t\t\t}\n//\t\t}\n//\t\t\n//\t\tcout << \"Exit: mypara::test_multivector_AWT_large()\" << endl;\n//\t}\n\t\n\tvoid test_multivector_AWT_scale()\n\t{\n\t\tcout << \"Enter: mypara::test_multivector_AWT_scale()\" << endl;\n\t\tstopwatch::Time time(stopwatch::watches, \"mypara::test_multivector_AWT_scale()\");\n\t\t\n\t\treporter::note(\"Parallel AWT scalability test\");\n\t\treporter::note(\"Timings are in milliseconds\");\n\t\t\n\t\ttypedef ublas::matrix<double> matrix;\n\t\ttypedef ublas::compressed_matrix<double> sparse_matrix;\n\t\t\n\t\tmpi::communicator world;\n\t\t\n\t\t//unsigned int n1 = 12; // size1 = dimV increases up to (2 ^ n1)\n\t\tunsigned int n2 = 14; // size2 = dimE increases up to (2 ^ n2)\n\t\t\n\t\t//for (unsigned int size1 = (1 << n1); size1 <= (1 << n1); size1 *= 2)\n\t\tunsigned size1 = 1953;\n\t\treporter::note[\"dimV\"] = size1;\n\t\treporter::note(\"Number of temporal elements\")[\"N = []\"];\n\t\treporter::note(\"Multiplication by T [ms]\")[\"T = []\"];\n\t\treporter::note(\"Multiplication by V [ms]\")[\"V = []\"];\n\t\t{\n\t\t\tfor (unsigned int size2 = 1; size2 <= (1 << n2); size2 *= 2)\n\t\t\t{\n\t\t\t\treporter::note[\"\"];\n\t\t\t\treporter::note[\"n\"] = size2;\n\t\t\t\t\n\t\t\t\tmultivector v(size1, 1 + size2, world);\n\t\t\t\t\n\t\t\t\t// Create AWT\n\t\t\t\tdouble T = 2;\n\t\t\t\tspacetime::tmesh te;\n\t\t\t\tte.makeuniform(0, T, v.getot());\n\t\t\t\t\n\t\t\t\tspacetime::tFEM tfem(te);\n\t\t\t\t\n\t\t\t\tunsigned int nu = 2;\n\t\t\t\tAWT awt(tfem.AtE, tfem.MtE, nu);\n\t\t\t\t\n\t\t\t\tdouble t_max = 0;\n\t\t\t\t\n\t\t\t\t// Multiply by T\n\t\t\t\t{\n\t\t\t\t\tstopwatch::StopWatch w;\n\t\t\t\t\t//awt.uT(v); // compute jplan\n\t\t\t\t\tw.tic();\n\t\t\t\t\tawt.uT(v);\n\t\t\t\t\tw.add();\n\t\t\t\t\tdouble t = w.ms().count();\n\t\t\t\t\tt_max = max(t, t_max);\n\t\t\t\t\t\n\t\t\t\t\t// Print timings\n\t\t\t\t\t{\n\t\t\t\t\t\tcout.flush(); world.barrier();\n\t\t\t\t\t\tif (!world.rank())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcout << \"@T: \";\n\t\t\t\t\t\t\tcout << \"size1: \" << size1 << \" \";\n\t\t\t\t\t\t\tcout << \"size2: \" << size2 << \" \";\n\t\t\t\t\t\t\tcout << \"time(ms): \" << t << \" \";\n\t\t\t\t\t\t\tcout << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tworld.barrier();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\treporter::note[\"t\"] = t;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Multiply by Tt\n\t\t\t\t{\n\t\t\t\t\tstopwatch::StopWatch w;\n\t\t\t\t\t//awt.uTt(v); // compute jplan\n\t\t\t\t\tw.tic();\n\t\t\t\t\tawt.uTt(v);\n\t\t\t\t\tw.add();\n\t\t\t\t\tdouble v = w.ms().count();\n\t\t\t\t\tt_max = max(v, t_max);\n\t\t\t\t\t\n\t\t\t\t\t// Print timings\n\t\t\t\t\t{\n\t\t\t\t\t\tcout.flush(); world.barrier();\n\t\t\t\t\t\tif (!world.rank())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcout << \"@V: \";\n\t\t\t\t\t\t\tcout << \"size1: \" << size1 << \" \";\n\t\t\t\t\t\t\tcout << \"size2: \" << size2 << \" \";\n\t\t\t\t\t\t\tcout << \"time(ms): \" << v << \" \";\n\t\t\t\t\t\t\tcout << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tworld.barrier();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\treporter::note[\"v\"] = v;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t\treporter::note[\"N.append(n);\"];\n\t\t\t\treporter::note[\"T.append(t);\"];\n\t\t\t\treporter::note[\"V.append(v);\"];\n\t\t\t\t\n\t\t\t\t// Abort loop if the trafo is taking too long\n\t\t\t\tdouble t_max_ok = 4 * 60e3; // seconds\n\t\t\t\tif (t_max >= t_max_ok) break;\n\t\t\t} // for size2\n\t\t} // for size1\n\t\t\n\t\tcout << \"Exit: mypara::test_multivector_AWT_scale()\" << endl;\n\t}\n}\n\n\nvoid test()\n{\n\treporter::note.is_quiet = (boost::mpi::communicator().rank() != 0);\n\t\n\tmypara::test_multivector_AWT_basic();\n//    mypara::test_multivector_AWT_large();\n    mypara::test_multivector_AWT_scale();\n}\n", "meta": {"hexsha": "83e75138282b9a6780d7285047cca5e50b9c4751", "size": 8439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "parawt/c++/test/multivector_AWT.cpp", "max_stars_repo_name": "numpde/parabolic", "max_stars_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "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": "parawt/c++/test/multivector_AWT.cpp", "max_issues_repo_name": "numpde/parabolic", "max_issues_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "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": "parawt/c++/test/multivector_AWT.cpp", "max_forks_repo_name": "numpde/parabolic", "max_forks_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "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": 23.9065155807, "max_line_length": 102, "alphanum_fraction": 0.5449697831, "num_tokens": 2814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6305637611570925}}
{"text": "/* SPDX-License-Identifier: BSD-3-Clause */\n/* Copyright \u00a9 2020 Fragcolor Pte. Ltd. */\n\n#ifndef CB_NO_BIGINT_BLOCKS\n\n#include \"math.h\"\n#include \"shared.hpp\"\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\n\nnamespace chainblocks {\nnamespace BigInt {\ninline Var to_var(const cpp_int &bi, std::vector<uint8_t> &buffer) {\n  buffer.clear();\n  buffer.emplace_back(uint8_t(bi < 0));\n  export_bits(bi, std::back_inserter(buffer), 8);\n  return Var(&buffer.front(), buffer.size());\n}\n\ninline cpp_int from_var(const CBVar &op) {\n  cpp_int bib;\n  import_bits(bib, op.payload.bytesValue + 1,\n              op.payload.bytesValue + op.payload.bytesSize);\n  auto negative = bool(op.payload.bytesValue[0]);\n  if (negative)\n    bib *= -1;\n  return bib;\n}\n\nstruct ToBigInt {\n  std::vector<uint8_t> _buffer;\n\n  static inline Types InputTypes{CoreInfo::IntType, CoreInfo::FloatType,\n                                 CoreInfo::StringType, CoreInfo::BytesType};\n  static CBTypesInfo inputTypes() { return InputTypes; }\n  static CBTypesInfo outputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString outputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n\n  CBVar activate(CBContext *context, const CBVar &input) {\n    cpp_int bi;\n    switch (input.valueType) {\n    case Int: {\n      bi = input.payload.intValue;\n    } break;\n    case Float: {\n      bi = cpp_int(input.payload.floatValue);\n    } break;\n    case String: {\n      bi = cpp_int(input.payload.stringValue);\n    } break;\n    case Bytes: {\n      import_bits(bi, input.payload.bytesValue,\n                  input.payload.bytesValue + input.payload.bytesSize);\n    } break;\n    default: {\n      throw ActivationError(\"Invalid input type\");\n    }\n    }\n    return to_var(bi, _buffer);\n  }\n};\n\ntemplate <typename T>\nstruct BigIntBinaryOp : public ::chainblocks::Math::BinaryOperation<T> {\n  std::deque<std::vector<uint8_t>> _buffers;\n  size_t _offset{0};\n\n  static inline Types BigIntInputTypes{\n      {CoreInfo::BytesType, CoreInfo::BytesSeqType}};\n\n  static CBTypesInfo inputTypes() { return BigIntInputTypes; }\n  static CBOptionalString inputHelp() {\n    return CBCCSTR(\"Any valid big integer(s) represented as bytes supported by \"\n                   \"this operation.\");\n  }\n  static CBTypesInfo outputTypes() { return BigIntInputTypes; }\n\n  CBParametersInfo parameters() {\n    static Parameters params{\n        {\"Operand\",\n         CBCCSTR(\"The bytes variable representing the operand\"),\n         {CoreInfo::BytesVarType, CoreInfo::BytesVarSeqType}}};\n    return params;\n  }\n\n  CBVar activate(CBContext *context, const CBVar &input) {\n    _offset = 0;\n    return ::chainblocks::Math::BinaryOperation<T>::activate(context, input);\n  }\n};\n\n#define BIGINT_MATH_OP(__NAME__, __OP__)                                       \\\n  struct __NAME__ : public BigIntBinaryOp<__NAME__> {                          \\\n    void operator()(CBVar &output, const CBVar &input, const CBVar &operand,   \\\n                    void *pself) {                                             \\\n      auto self = reinterpret_cast<__NAME__ *>(pself);                         \\\n      std::vector<uint8_t> *buffer = nullptr;                                  \\\n      if (self->_buffers.size() <= _offset) {                                  \\\n        buffer = &self->_buffers.emplace_back();                               \\\n      } else {                                                                 \\\n        buffer = &self->_buffers[_offset];                                     \\\n      }                                                                        \\\n      cpp_int bia = from_var(input);                                           \\\n      cpp_int bib = from_var(operand);                                         \\\n      cpp_int bres = bia __OP__ bib;                                           \\\n      output = to_var(bres, *buffer);                                          \\\n      _offset++;                                                               \\\n    }                                                                          \\\n  };\n\nstruct BigOperandBase {\n  std::vector<uint8_t> _buffer;\n\n  static CBTypesInfo inputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString inputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n  static CBTypesInfo outputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString outputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n\n  CBParametersInfo parameters() {\n    static Parameters params{\n        {\"Operand\",\n         CBCCSTR(\"The bytes variable representing the operand\"),\n         {CoreInfo::BytesVarType}}};\n    return params;\n  }\n\n  ParamVar _op{};\n\n  void setParam(int index, const CBVar &value) { _op = value; }\n\n  CBVar getParam(int index) { return _op; }\n\n  void cleanup() { _op.cleanup(); }\n\n  void warmup(CBContext *context) { _op.warmup(context); }\n\n  const CBVar &getOperand() {\n    CBVar &op = _op.get();\n    if (op.valueType == None) {\n      throw ActivationError(\"Operand is None, should be valid bigint bytes\");\n    }\n    return op;\n  }\n};\n\nstruct RegOperandBase {\n  std::vector<uint8_t> _buffer;\n\n  static CBTypesInfo inputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString inputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n  static CBTypesInfo outputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString outputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n\n  CBParametersInfo parameters() {\n    static Parameters params{{\"Operand\",\n                              CBCCSTR(\"The integer operand, can be a variable\"),\n                              {CoreInfo::IntType, CoreInfo::IntVarType}}};\n    return params;\n  }\n\n  ParamVar _op{};\n\n  void setParam(int index, const CBVar &value) { _op = value; }\n\n  CBVar getParam(int index) { return _op; }\n\n  void cleanup() { _op.cleanup(); }\n\n  void warmup(CBContext *context) { _op.warmup(context); }\n\n  const CBVar &getOperand() {\n    CBVar &op = _op.get();\n    if (op.valueType == None) {\n      throw ActivationError(\"Operand is None, should be an integer\");\n    }\n    return op;\n  }\n};\n\nBIGINT_MATH_OP(Add, +);\nBIGINT_MATH_OP(Subtract, -);\nBIGINT_MATH_OP(Multiply, *);\nBIGINT_MATH_OP(Divide, /);\nBIGINT_MATH_OP(Xor, ^);\nBIGINT_MATH_OP(And, &);\nBIGINT_MATH_OP(Or, |);\nBIGINT_MATH_OP(Mod, %);\n\n#define BIGINT_LOGIC_OP(__NAME__, __OP__)                                      \\\n  struct __NAME__ : public BigOperandBase {                                    \\\n    static CBTypesInfo outputTypes() { return CoreInfo::BoolType; }            \\\n    static CBOptionalString outputHelp() {                                     \\\n      return CBCCSTR(                                                          \\\n          \"A boolean value repesenting the result of the logic operation.\");   \\\n    }                                                                          \\\n                                                                               \\\n    CBVar activate(CBContext *context, const CBVar &input) {                   \\\n      cpp_int bia = from_var(input);                                           \\\n      auto op = getOperand();                                                  \\\n      cpp_int bib = from_var(op);                                              \\\n      bool res = bia __OP__ bib;                                               \\\n      return Var(res);                                                         \\\n    }                                                                          \\\n  }\n\nBIGINT_LOGIC_OP(Is, ==);\nBIGINT_LOGIC_OP(IsNot, !=);\nBIGINT_LOGIC_OP(IsMore, >);\nBIGINT_LOGIC_OP(IsLess, <);\nBIGINT_LOGIC_OP(IsMoreEqual, >=);\nBIGINT_LOGIC_OP(IsLessEqual, <=);\n\n#define BIGINT_BINARY_OP(__NAME__, __OP__)                                     \\\n  struct __NAME__ : public BigIntBinaryOp<__NAME__> {                          \\\n    void operator()(CBVar &output, const CBVar &input, const CBVar &operand,   \\\n                    void *pself) {                                             \\\n      auto self = reinterpret_cast<__NAME__ *>(pself);                         \\\n      std::vector<uint8_t> *buffer = nullptr;                                  \\\n      if (self->_buffers.size() <= _offset) {                                  \\\n        buffer = &self->_buffers.emplace_back();                               \\\n      } else {                                                                 \\\n        buffer = &self->_buffers[_offset];                                     \\\n      }                                                                        \\\n      cpp_int bia = from_var(input);                                           \\\n      cpp_int bib = from_var(operand);                                         \\\n      cpp_int bres = __OP__(bia, bib);                                         \\\n      output = to_var(bres, *buffer);                                          \\\n      _offset++;                                                               \\\n    }                                                                          \\\n  };\n\nBIGINT_BINARY_OP(Min, std::min);\nBIGINT_BINARY_OP(Max, std::max);\n\n#define BIGINT_REG_BINARY_OP(__NAME__, __OP__)                                 \\\n  struct __NAME__ : public RegOperandBase {                                    \\\n    CBVar activate(CBContext *context, const CBVar &input) {                   \\\n      cpp_int bia = from_var(input);                                           \\\n      auto op = getOperand();                                                  \\\n      if (op.valueType != Int)                                                 \\\n        throw ActivationError(\"Pow operand should be an Int\");                 \\\n      cpp_int bres = __OP__(bia, op.payload.intValue);                         \\\n      return to_var(bres, _buffer);                                            \\\n    }                                                                          \\\n  }\n\nBIGINT_REG_BINARY_OP(Pow, pow);\n\n#define BIGINT_UNARY_OP(__NAME__, __OP__)                                      \\\n  struct __NAME__ : public RegOperandBase {                                    \\\n    CBParametersInfo parameters() { return {}; }                               \\\n    CBVar activate(CBContext *context, const CBVar &input) {                   \\\n      cpp_int bia = from_var(input);                                           \\\n      cpp_int bres = __OP__(bia);                                              \\\n      return to_var(bres, _buffer);                                            \\\n    }                                                                          \\\n  }\n\nBIGINT_UNARY_OP(Sqrt, sqrt);\n\nstruct ShiftBase {\n  ParamVar _shift{Var(0)};\n\n  void setParam(int index, const CBVar &value) { _shift = value; }\n\n  CBVar getParam(int index) { return _shift; }\n\n  void cleanup() { _shift.cleanup(); }\n\n  void warmup(CBContext *context) { _shift.warmup(context); }\n};\n\nstruct Shift : public ShiftBase {\n  std::vector<uint8_t> _buffer;\n\n  static CBTypesInfo inputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString inputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n  static CBTypesInfo outputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString outputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n\n  CBParametersInfo parameters() {\n    static Parameters params{\n        {\"By\",\n         CBCCSTR(\n             \"The shift is of the decimal point, i.e. of powers of ten, and is \"\n             \"to the left if n is negative or to the right if n is positive.\"),\n         {CoreInfo::IntType, CoreInfo::IntVarType}}};\n    return params;\n  }\n\n  CBVar activate(CBContext *context, const CBVar &input) {\n    cpp_int bi = from_var(input);\n    cpp_dec_float_100 bf(bi);\n\n    cpp_dec_float_100 bshift(_shift.get().payload.intValue);\n    bshift = pow(cpp_dec_float_100(10), bshift);\n\n    auto bres = cpp_int(bf * bshift);\n\n    return to_var(bres, _buffer);\n  }\n};\n\nstruct ToFloat : public ShiftBase {\n  static CBOptionalString help() {\n    return CBCCSTR(\"Converts a big integer value to a floating point number.\");\n  }\n\n  static CBTypesInfo inputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString inputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n\n  static CBTypesInfo outputTypes() { return CoreInfo::FloatType; }\n  static CBOptionalString outputHelp() {\n    return CBCCSTR(\n        \"Floating point number representation of the big integer value.\");\n  }\n\n  CBParametersInfo parameters() {\n    static Parameters params{\n        {\"ShiftedBy\",\n         CBCCSTR(\n             \"The shift is of the decimal point, i.e. of powers of ten, and is \"\n             \"to the left if n is negative or to the right if n is positive.\"),\n         {CoreInfo::IntType}}};\n    return params;\n  }\n\n  CBVar activate(CBContext *context, const CBVar &input) {\n    cpp_int bi = from_var(input);\n    cpp_dec_float_100 bf(bi);\n\n    cpp_dec_float_100 bshift(_shift.get().payload.intValue);\n    bshift = pow(cpp_dec_float_100(10), bshift);\n\n    auto bres = bf * bshift;\n\n    return Var(bres.convert_to<double>());\n  }\n};\n\nstruct ToInt {\n  static CBOptionalString help() {\n    return CBCCSTR(\"Converts a big integer value to an integer.\");\n  }\n\n  static CBTypesInfo inputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString inputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n\n  static CBTypesInfo outputTypes() { return CoreInfo::IntType; }\n  static CBOptionalString outputHelp() {\n    return CBCCSTR(\"Integer representation of the big integer value.\");\n  }\n\n  CBVar activate(CBContext *context, const CBVar &input) {\n    cpp_int bi = from_var(input);\n    return Var(bi.convert_to<int64_t>());\n  }\n};\n\nstruct FromFloat : public ShiftBase {\n  static CBOptionalString help() {\n    return CBCCSTR(\"Converts a floating point number to a big integer.\");\n  }\n\n  static CBTypesInfo inputTypes() { return CoreInfo::FloatType; }\n  static CBOptionalString inputHelp() {\n    return CBCCSTR(\"Floating point number.\");\n  }\n\n  static CBTypesInfo outputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString outputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n\n  CBParametersInfo parameters() {\n    static Parameters params{\n        {\"ShiftedBy\",\n         CBCCSTR(\n             \"The shift is of the decimal point, i.e. of powers of ten, and is \"\n             \"to the left if n is negative or to the right if n is positive.\"),\n         {CoreInfo::IntType}}};\n    return params;\n  }\n\n  CBVar activate(CBContext *context, const CBVar &input) {\n    cpp_dec_float_100 bi(input.payload.floatValue);\n\n    cpp_dec_float_100 bshift(_shift.get().payload.intValue);\n    bshift = pow(cpp_dec_float_100(10), bshift);\n\n    auto bres = bi * bshift;\n    cpp_int bo(bres);\n\n    return to_var(bo, _buffer);\n  }\n\nprivate:\n  std::vector<uint8_t> _buffer;\n};\n\nstruct ToString {\n  static CBOptionalString help() {\n    return CBCCSTR(\"Converts the value to a string representation.\");\n  }\n\n  static CBTypesInfo inputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString inputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n  static CBTypesInfo outputTypes() { return CoreInfo::StringType; }\n  static CBOptionalString outputHelp() {\n    return CBCCSTR(\"String representation of the big integer value.\");\n  }\n\n  CBVar activate(CBContext *context, const CBVar &input) {\n    cpp_int bi = from_var(input);\n    _buffer = bi.str();\n    return Var(_buffer);\n  }\n\nprivate:\n  std::string _buffer;\n};\n\nstruct ToBytes {\n  std::vector<uint8_t> _buffer;\n\n  static CBTypesInfo inputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString inputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n  static CBTypesInfo outputTypes() { return CoreInfo::BytesType; }\n\n  CBParametersInfo parameters() {\n    static Parameters params{{\"Bits\",\n                              CBCCSTR(\"The desired amount of bits for the \"\n                                      \"output or 0 for automatic packing.\"),\n                              {CoreInfo::IntType}}};\n    return params;\n  }\n\n  ParamVar _bits{Var(0)};\n\n  void setParam(int index, const CBVar &value) { _bits = value; }\n\n  CBVar getParam(int index) { return _bits; }\n\n  void warmup(CBContext *context) { _bits.warmup(context); }\n  void cleanup() { _bits.cleanup(); }\n\n  CBVar activate(CBContext *context, const CBVar &input) {\n    const auto bits = _bits.get().payload.intValue;\n    if (bits <= 0) {\n      CBVar fixedInput = input;\n      fixedInput.payload.bytesValue++;\n      fixedInput.payload.bytesSize--;\n      return fixedInput;\n    } else {\n      cpp_int bi = from_var(input);\n      const auto usedBits = msb(bi) + 1;\n      if (usedBits > bits) {\n        throw ActivationError(\n            \"The number of used bits is higher than the requested bits\");\n      }\n      const auto padding = bits - usedBits;\n      _buffer.clear();\n      export_bits(bi, std::back_inserter(_buffer), 8);\n      // this is because we are using little endianess\n      _buffer.insert(_buffer.begin(), padding / 8, 0);\n      return Var(_buffer);\n    }\n  }\n};\n\nstruct ToHex {\n  static CBOptionalString help() {\n    return CBCCSTR(\"Converts the value to a hexadecimal representation.\");\n  }\n\n  static inline Types toHexTypes{CoreInfo::IntType, CoreInfo::BytesType,\n                                 CoreInfo::StringType};\n  static CBTypesInfo inputTypes() { return toHexTypes; }\n\n  static CBTypesInfo outputTypes() { return CoreInfo::StringType; }\n  static CBOptionalString outputHelp() {\n    return CBCCSTR(\"Hexadecimal representation of the integer value.\");\n  }\n\n  CBVar activate(CBContext *context, const CBVar &input) {\n    CBVar fixedInput = input;\n    fixedInput.payload.bytesValue++;\n    fixedInput.payload.bytesSize--;\n    _stream.tryWriteHex(fixedInput);\n    return Var(_stream.str());\n  }\n\nprivate:\n  VarStringStream _stream;\n};\n\nstruct Abs {\n  static CBOptionalString help() {\n    return CBCCSTR(\"Computes the absolute value of a big integer.\");\n  }\n\n  static CBTypesInfo inputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString inputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n\n  static CBTypesInfo outputTypes() { return CoreInfo::BytesType; }\n  static CBOptionalString outputHelp() {\n    return CBCCSTR(\"Big integer represented as bytes.\");\n  }\n\n  CBVar activate(CBContext *context, const CBVar &input) {\n    cpp_int bi = from_var(input);\n    cpp_int abi = abs(bi);\n    return to_var(abi, _buffer);\n  }\n\nprivate:\n  std::vector<uint8_t> _buffer;\n};\n\nvoid registerBlocks() {\n  REGISTER_CBLOCK(\"BigInt\", ToBigInt);\n  REGISTER_CBLOCK(\"BigInt.Add\", Add);\n  REGISTER_CBLOCK(\"BigInt.Subtract\", Subtract);\n  REGISTER_CBLOCK(\"BigInt.Multiply\", Multiply);\n  REGISTER_CBLOCK(\"BigInt.Divide\", Divide);\n  REGISTER_CBLOCK(\"BigInt.Xor\", Xor);\n  REGISTER_CBLOCK(\"BigInt.And\", And);\n  REGISTER_CBLOCK(\"BigInt.Or\", Or);\n  REGISTER_CBLOCK(\"BigInt.Mod\", Mod);\n  REGISTER_CBLOCK(\"BigInt.Shift\", Shift);\n  REGISTER_CBLOCK(\"BigInt.ToFloat\", ToFloat);\n  REGISTER_CBLOCK(\"BigInt.ToInt\", ToInt);\n  REGISTER_CBLOCK(\"BigInt.FromFloat\", FromFloat);\n  REGISTER_CBLOCK(\"BigInt.ToString\", ToString);\n  REGISTER_CBLOCK(\"BigInt.ToBytes\", ToBytes);\n  REGISTER_CBLOCK(\"BigInt.ToHex\", ToHex);\n  REGISTER_CBLOCK(\"BigInt.Is\", Is);\n  REGISTER_CBLOCK(\"BigInt.IsNot\", IsNot);\n  REGISTER_CBLOCK(\"BigInt.IsMore\", IsMore);\n  REGISTER_CBLOCK(\"BigInt.IsLess\", IsLess);\n  REGISTER_CBLOCK(\"BigInt.IsMoreEqual\", IsMoreEqual);\n  REGISTER_CBLOCK(\"BigInt.IsLessEqual\", IsLessEqual);\n  REGISTER_CBLOCK(\"BigInt.Min\", Min);\n  REGISTER_CBLOCK(\"BigInt.Max\", Max);\n  REGISTER_CBLOCK(\"BigInt.Pow\", Pow);\n  REGISTER_CBLOCK(\"BigInt.Abs\", Abs);\n  REGISTER_CBLOCK(\"BigInt.Sqrt\", Sqrt);\n}\n} // namespace BigInt\n} // namespace chainblocks\n\n#else\nnamespace chainblocks {\nnamespace BigInt {\nvoid registerBlocks() {}\n} // namespace BigInt\n} // namespace chainblocks\n#endif", "meta": {"hexsha": "1024b6e4fa6920ce41bfb3ac4c375cbf4586c499", "size": 20175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/blocks/bigint.cpp", "max_stars_repo_name": "Kryptos-FR/chainblocks", "max_stars_repo_head_hexsha": "67160c535237a90cfe8a059db487d054d2714a3c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-10-30T18:21:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T06:06:15.000Z", "max_issues_repo_path": "src/core/blocks/bigint.cpp", "max_issues_repo_name": "Kryptos-FR/chainblocks", "max_issues_repo_head_hexsha": "67160c535237a90cfe8a059db487d054d2714a3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2019-10-28T15:56:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-19T11:27:03.000Z", "max_forks_repo_path": "src/core/blocks/bigint.cpp", "max_forks_repo_name": "Kryptos-FR/chainblocks", "max_forks_repo_head_hexsha": "67160c535237a90cfe8a059db487d054d2714a3c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-05T19:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T06:30:42.000Z", "avg_line_length": 34.4871794872, "max_line_length": 80, "alphanum_fraction": 0.5752664188, "num_tokens": 4582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.679178686187839, "lm_q1q2_score": 0.630555465370447}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/ellint_rd.hpp>\n#include <boost/math/special_functions/ellint_rd.hpp>\n#include <eve/wide.hpp>\n\n\nTTS_CASE_TPL(\"Check eve::ellint_rd behavior\", EVE_TYPE)\n{\n  using elt_t = eve::element_type_t<T>;\n  TTS_ULP_EQUAL(eve::ellint_rd(T(0.2), T(0.4), T(0.1)),  T(boost::math::ellint_rd(elt_t(0.2), elt_t(0.4), elt_t(0.1))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rd(T(1.5), T(1), T(1.7)),T(boost::math::ellint_rd(elt_t(1.5), elt_t(1), elt_t(1.7))), 1.0);\n  TTS_ULP_EQUAL(eve::ellint_rd(T(2), T(0), T(7)),  T(boost::math::ellint_rd(elt_t(2), elt_t(0), elt_t(7))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rd(T(0), T(5), T(3.4)),  T(boost::math::ellint_rd(elt_t(0), elt_t(5), elt_t(3.4))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rd(T(2), T(5), T(0.5)),  T(boost::math::ellint_rd(elt_t(2), elt_t(5), elt_t(0.5))),   1.0);\n                                                                        }\n", "meta": {"hexsha": "20eba518630822e92c4dfb77c135b30e1853d84a", "size": 1213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/elliptic/ellint_rd/regular/ellint_rd.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/elliptic/ellint_rd/regular/ellint_rd.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/elliptic/ellint_rd/regular/ellint_rd.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.1363636364, "max_line_length": 127, "alphanum_fraction": 0.505358615, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6305498997787958}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_DEGINRAD_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_DEGINRAD_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Deginrad Deginrad (function template)\n\n  Generates the constant \\f$\\frac\\pi{180}\\f$.\n\n  @headerref{<boost/simd/constant/deginrad.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Deginrad();\n      @endcode\n\n  2.  @code\n      template<typename T> T Deginrad( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates the constant \\f$\\frac\\pi{180}\\f$ usable to convert degrees to radians.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c T that evaluates to `Pi<T>()/180`.\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/deginrad.hpp>\n#include <boost/simd/constant/simd/deginrad.hpp>\n\n#endif\n", "meta": {"hexsha": "e603f4879cd5ea2e01b71f7a74325ba8a427e85a", "size": 1502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/deginrad.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/deginrad.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/deginrad.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 29.4509803922, "max_line_length": 100, "alphanum_fraction": 0.5306258322, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6305498921882253}}
{"text": "\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//! \\file\r\n//!\\brief Tests for computing the value of a Bessel function using a trapezoid integration of (fixed_point).\r\n\r\n#include <cmath>\r\n\r\n#define BOOST_TEST_MODULE test_negatable_math_trapezoid_integral\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <boost/cstdint.hpp>\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nnamespace local\r\n{\r\n  template<typename NumericType, typename RealFunctionType>\r\n  NumericType integral(const NumericType& a,\r\n                       const NumericType& b,\r\n                       const NumericType& tol,\r\n                       RealFunctionType real_function)\r\n  {\r\n    boost::uint_fast32_t n2(1);\r\n\r\n    NumericType step = ((b - a) / 2U);\r\n\r\n    NumericType result = (real_function(a) + real_function(b)) * step;\r\n\r\n    const boost::uint_fast8_t k_max = UINT8_C(16);\r\n\r\n    for(boost::uint_fast8_t k = UINT8_C(0); k < k_max; ++k)\r\n    {\r\n      NumericType sum(0);\r\n\r\n      for(boost::uint_fast32_t j(0U); j < n2; ++j)\r\n      {\r\n        const boost::uint_fast32_t two_j_plus_one = (j * UINT32_C(2)) + UINT32_C(1);\r\n\r\n        sum += real_function(a + (step * two_j_plus_one));\r\n      }\r\n\r\n      const NumericType tmp = result;\r\n\r\n      result = (result / 2U) + (step * sum);\r\n\r\n      using std::fabs;\r\n      const NumericType ratio = fabs(tmp / result);\r\n      const NumericType delta = fabs(ratio - 1U);\r\n\r\n      if((k > UINT8_C(1)) && (delta < tol))\r\n      {\r\n        break;\r\n      }\r\n\r\n      n2 *= 2U;\r\n\r\n      step /= 2U;\r\n    }\r\n\r\n    return result;\r\n  }\r\n\r\n  template<typename NumericType>\r\n  NumericType cyl_bessel_j(const boost::uint_fast8_t n, const NumericType& x)\r\n  {\r\n    using std::sqrt;\r\n    const NumericType tol = sqrt(std::numeric_limits<NumericType>::epsilon());\r\n\r\n    const NumericType jn =\r\n      local::integral(NumericType(0),\r\n                      boost::math::constants::pi<NumericType>(),\r\n                      tol,\r\n                      [&x, &n](const NumericType& t) -> NumericType\r\n                      {\r\n                        using std::cos;\r\n                        using std::sin;\r\n\r\n                        return cos(x * sin(t) - (t * n));\r\n                      }) / boost::math::constants::pi<NumericType>();\r\n\r\n    return jn;\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_math_trapezoid_integral)\r\n{\r\n  typedef boost::fixed_point::negatable<15, -240> fixed_point_type;\r\n\r\n  typedef fixed_point_type::float_type float_point_type;\r\n\r\n  const fixed_point_type tol = ldexp(fixed_point_type(1), fixed_point_type::resolution + 6);\r\n\r\n  // Compute y = cyl_bessel_j(2, 123 / 100).\r\n  const fixed_point_type j2   = local::cyl_bessel_j(UINT8_C(2), fixed_point_type(123) / 100);\r\n\r\n  // Assign the known reference value of the Bessel function.\r\n  const float_point_type reference = float_point_type(\"0.166369383786814073512678524315131594371033482453328555149562207827319927054822411949870923\");\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(j2, reference, tol);\r\n}\r\n", "meta": {"hexsha": "c87e9e8e0d08158fdc7bb92477e7244b77889da5", "size": 3410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_math_trapezoid_integral.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_math_trapezoid_integral.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_math_trapezoid_integral.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.0, "max_line_length": 151, "alphanum_fraction": 0.6093841642, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6305380861523509}}
{"text": "// geometric_examples.cpp\n\n// Copyright Paul A. Bristow 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// This file is written to be included from a Quickbook .qbk document.\n// It can still be compiled by the C++ compiler, and run. \n// Any output can also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n// Examples of using the geometric distribution.\n\n//[geometric_eg1_1\n/*`\nFor this example, we will opt to #define two macros to control \nthe error and discrete handling policies.\nFor this simple example, we want to avoid throwing\nan exception (the default policy) and just return infinity.\nWe want to treat the distribution as if it was continuous,\nso we choose a discrete_quantile policy of real,\nrather than the default policy integer_round_outwards.\n*/\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n#define BOOST_MATH_DISCRETE_QUANTILE_POLICY real\n/*`\n[caution It is vital to #include distributions etc *after* the above #defines]\nAfter that we need some includes to provide easy access to the negative binomial distribution,\nand we need some std library iostream, of course.\n*/\n#include <boost/math/distributions/geometric.hpp>\n  // for geometric_distribution\n  using ::boost::math::geometric_distribution; // \n  using ::boost::math::geometric; // typedef provides default type is double.\n  using  ::boost::math::pdf; // Probability mass function.\n  using  ::boost::math::cdf; // Cumulative density function.\n  using  ::boost::math::quantile;\n\n#include <boost/math/distributions/negative_binomial.hpp>\n  // for negative_binomial_distribution\n  using boost::math::negative_binomial; // typedef provides default type is double.\n\n#include <boost/math/distributions/normal.hpp>\n  // for negative_binomial_distribution\n  using boost::math::normal; // typedef provides default type is double.\n\n#include <iostream>\n  using std::cout; using std::endl;\n  using std::noshowpoint; using std::fixed; using std::right; using std::left;\n#include <iomanip>\n  using std::setprecision; using std::setw; \n\n#include <limits>\n  using std::numeric_limits;\n//] [geometric_eg1_1]\n\nint main()\n{\n  cout <<\"Geometric distribution example\" << endl;\n  cout << endl;\n\n  cout.precision(4); // But only show a few for this example.\n  try\n  {\n//[geometric_eg1_2\n/*`\nIt is always sensible to use try and catch blocks because defaults policies are to\nthrow an exception if anything goes wrong.\n\nSimple try'n'catch blocks (see below) will ensure that you get a\nhelpful error message instead of an abrupt (and silent) program abort.\n\n[h6 Throwing a dice]\nThe Geometric distribution describes the probability (/p/) of a number of failures\nto get the first success in /k/ Bernoulli trials.\n(A [@http://en.wikipedia.org/wiki/Bernoulli_distribution Bernoulli trial]\nis one with only two possible outcomes, success of failure,\nand /p/ is the probability of success).\n\nSuppose an 'fair' 6-face dice is thrown repeatedly: \n*/\n    double success_fraction = 1./6; // success_fraction (p) = 0.1666\n    // (so failure_fraction is 1 - success_fraction = 5./6 = 1- 0.1666 = 0.8333)\n\n/*`If the dice is thrown repeatedly until the *first* time a /three/ appears.\nThe probablility distribution of the number of times it is thrown *not* getting a /three/\n (/not-a-threes/ number of failures to get a /three/)\nis a geometric distribution with the success_fraction = 1/6 = 0.1666[recur].\n\nWe therefore start by constructing a geometric distribution\nwith the one parameter success_fraction, the probability of success.\n*/\n    geometric g6(success_fraction); // type double by default.\n/*`\nTo confirm, we can echo the success_fraction parameter of the distribution.\n*/\n    cout << \"success fraction of a six-sided dice is \" << g6.success_fraction() << endl;\n/*`So the probability of getting a three at the first throw (zero failures) is\n*/\n    cout << pdf(g6, 0) << endl; // 0.1667\n    cout << cdf(g6, 0) << endl; // 0.1667\n/*`Note that the cdf and pdf are identical because the is only one throw.\nIf we want the probability of getting the first /three/ on the 2nd throw:\n*/\n    cout << pdf(g6, 1) << endl; // 0.1389\n\n/*`If we want the probability of getting the first /three/ on the 1st or 2nd throw\n(allowing one failure):\n*/\n    cout << \"pdf(g6, 0) + pdf(g6, 1) = \" << pdf(g6, 0) + pdf(g6, 1) << endl;\n/*`Or more conveniently, and more generally,\nwe can use the Cumulative Distribution Function CDF.*/\n\n    cout << \"cdf(g6, 1) = \" << cdf(g6, 1) << endl; // 0.3056\n\n/*`If we allow many more (12) throws, the probability of getting our /three/ gets very high:*/\n    cout << \"cdf(g6, 12) = \" << cdf(g6, 12) << endl; // 0.9065 or 90% probability.\n/*`If we want to be much more confident, say 99%, \nwe can estimate the number of throws to be this sure\nusing the inverse or quantile.\n*/\n    cout << \"quantile(g6, 0.99) = \" << quantile(g6, 0.99) << endl; // 24.26\n/*`Note that the value returned is not an integer:\nif you want an integer result you should use either floor, round or ceil functions,\nor use the policies mechanism.\nSee [link math_toolkit.policy.pol_tutorial.understand_dis_quant\nUnderstanding Quantiles of Discrete Distributions] \n\nThe geometric distribution is related to the negative binomial\n__spaces `negative_binomial_distribution(RealType r, RealType p);` with parameter /r/ = 1.\nSo we could get the same result using the negative binomial,\nbut using the geometric the results will be faster, and may be more accurate.\n*/\n    negative_binomial nb(1, success_fraction);\n    cout << pdf(nb, 1) << endl; // 0.1389\n    cout << cdf(nb, 1) << endl; // 0.3056\n/*`We could also the complement to express the required probability\nas 1 - 0.99 = 0.01 (and get the same result):\n*/\n    cout << \"quantile(complement(g6, 1 - p))  \" << quantile(complement(g6, 0.01)) << endl; // 24.26\n/*`\nNote too that Boost.Math geometric distribution is implemented as a continuous function.\nUnlike other implementations (for example R) it *uses* the number of failures as a *real* parameter,\nnot as an integer. If you want this integer behaviour, you may need to enforce this by\nrounding the parameter you pass, probably rounding down, to the nearest integer.\nFor example, R returns the success fraction probability for all values of failures\nfrom 0 to 0.999999 thus:\n[pre\n__spaces R> formatC(pgeom(0.0001,0.5, FALSE), digits=17) \"               0.5\"\n] [/pre]\nSo in Boost.Math the equivalent is\n*/\n    geometric g05(0.5);  // Probability of success = 0.5 or 50%\n    // Output all potentially significant digits for the type, here double.\n\n#ifdef BOOST_NO_CXX11_NUMERIC_LIMITS\n  int max_digits10 = 2 + (boost::math::policies::digits<double, boost::math::policies::policy<> >() * 30103UL) / 100000UL;\n  cout << \"BOOST_NO_CXX11_NUMERIC_LIMITS is defined\" << endl; \n#else \n  int max_digits10 = std::numeric_limits<double>::max_digits10;\n#endif\n  cout << \"Show all potentially significant decimal digits std::numeric_limits<double>::max_digits10 = \"\n    << max_digits10 << endl; \n  cout.precision(max_digits10); // \n\n    cout << cdf(g05, 0.0001) << endl; // returns 0.5000346561579232, not exact 0.5.\n/*`To get the R discrete behaviour, you simply need to round with,\nfor example, the `floor` function.\n*/\n    cout << cdf(g05, floor(0.0001)) << endl; // returns exactly 0.5\n/*`\n[pre\n`> formatC(pgeom(0.9999999,0.5, FALSE), digits=17) [1] \"              0.25\"`\n`> formatC(pgeom(1.999999,0.5, FALSE), digits=17)[1] \"              0.25\" k = 1`\n`> formatC(pgeom(1.9999999,0.5, FALSE), digits=17)[1] \"0.12500000000000003\" k = 2`\n] [/pre]\nshows that R makes an arbitrary round-up decision at about 1e7 from the next integer above.\nThis may be convenient in practice, and could be replicated in C++ if desired.\n\n[h6 Surveying customers to find one with a faulty product]\nA company knows from warranty claims that 2% of their products will be faulty,\nso the 'success_fraction' of finding a fault is 0.02.\nIt wants to interview a purchaser of faulty products to assess their 'user experience'.\n\nTo estimate how many customers they will probably need to contact \nin order to find one who has suffered from the fault,\nwe first construct a geometric distribution with probability 0.02,\nand then chose a confidence, say 80%, 95%, or 99% to finding a customer with a fault.\nFinally, we probably want to round up the result to the integer above using the `ceil` function.\n(We could also use a policy, but that is hardly worthwhile for this simple application.)\n\n(This also assumes that each customer only buys one product:\nif customers bought more than one item,\nthe probability of finding a customer with a fault obviously improves.)\n*/\n    cout.precision(5);\n    geometric g(0.02); // On average, 2 in 100 products are faulty.\n    double c = 0.95; // 95% confidence.\n    cout << \" quantile(g, \" << c << \") = \" << quantile(g, c) << endl;\n\n    cout << \"To be \" << c * 100 \n      << \"% confident of finding we customer with a fault, need to survey \"\n      <<  ceil(quantile(g, c)) << \" customers.\" << endl; // 148\n    c = 0.99; // Very confident.\n    cout << \"To be \" << c * 100 \n      << \"% confident of finding we customer with a fault, need to survey \"\n      <<  ceil(quantile(g, c)) << \" customers.\" << endl; // 227\n    c = 0.80; // Only reasonably confident.\n    cout << \"To be \" << c * 100 \n      << \"% confident of finding we customer with a fault, need to survey \"\n      <<  ceil(quantile(g, c)) << \" customers.\" << endl; // 79\n\n/*`[h6 Basket Ball Shooters]\nAccording to Wikipedia, average pro basket ball players get \n[@http://en.wikipedia.org/wiki/Free_throw free throws]\nin the baskets 70 to 80 % of the time,\nbut some get as high as 95%, and others as low as 50%.\nSuppose we want to compare the probabilities\nof failing to get a score only on the first or on the fifth shot?\nTo start we will consider the average shooter, say 75%.\nSo we construct a geometric distribution\nwith success_fraction parameter 75/100 = 0.75.\n*/ \n    cout.precision(2);\n    geometric gav(0.75); // Shooter averages 7.5 out of 10 in the basket.\n/*`What is probability of getting 1st try in the basket, that is with no failures? */\n    cout << \"Probability of score on 1st try = \" << pdf(gav, 0) << endl; // 0.75\n/*`This is, of course, the success_fraction probability 75%.\nWhat is the probability that the shooter only scores on the fifth shot?\nSo there are 5-1 = 4 failures before the first success.*/\n    cout << \"Probability of score on 5th try = \" << pdf(gav, 4) << endl; // 0.0029\n/*`Now compare this with the poor and the best players success fraction.\nWe need to constructing new distributions with the different success fractions,\nand then get the corresponding probability density functions values:\n*/\n    geometric gbest(0.95);\n    cout << \"Probability of score on 5th try = \" << pdf(gbest, 4) << endl; // 5.9e-6\n    geometric gmediocre(0.50);\n    cout << \"Probability of score on 5th try = \" << pdf(gmediocre, 4) << endl; // 0.031\n/*`So we can see the very much smaller chance (0.000006) of 4 failures by the best shooters,\ncompared to the 0.03 of the mediocre.*/\n\n/*`[h6 Estimating failures]\nOf course one man's failure is an other man's success.\nSo a fault can be defined as a 'success'.\n\nIf a fault occurs once after 100 flights, then one might naively say\nthat the risk of fault is obviously 1 in 100 = 1/100, a probability of 0.01.\n\nThis is the best estimate we can make, but while it is the truth,\nit is not the whole truth,\nfor it hides the big uncertainty when estimating from a single event.\n\"One swallow doesn't make a summer.\"\nTo show the magnitude of the uncertainty, the geometric \n(or the negative binomial) distribution can be used. \n\nIf we chose the popular 95% confidence in the limits, corresponding to an alpha of 0.05,\nbecause we are calculating a two-sided interval, we must divide alpha by two.\n*/\n    double alpha = 0.05;\n    double k = 100; // So frequency of occurence is 1/100.\n    cout << \"Probability is failure is \" << 1/k << endl;\n    double t = geometric::find_lower_bound_on_p(k, alpha/2);\n    cout << \"geometric::find_lower_bound_on_p(\" << int(k) << \", \" << alpha/2 << \") = \" \n      << t << endl; // 0.00025\n    t = geometric::find_upper_bound_on_p(k, alpha/2);\n    cout << \"geometric::find_upper_bound_on_p(\" << int(k) << \", \" << alpha/2 << \") = \"\n      << t << endl; // 0.037\n/*`So while we estimate the probability is 0.01, it might lie between 0.0003 and 0.04.\nEven if we relax our confidence to alpha = 90%, the bounds only contract to 0.0005 and 0.03.\nAnd if we require a high confidence, they widen to 0.00005 to 0.05.\n*/\n    alpha = 0.1; // 90% confidence.\n    t = geometric::find_lower_bound_on_p(k, alpha/2);\n    cout << \"geometric::find_lower_bound_on_p(\" << int(k) << \", \" << alpha/2 << \") = \"\n      << t << endl; // 0.0005\n    t = geometric::find_upper_bound_on_p(k, alpha/2);\n    cout << \"geometric::find_upper_bound_on_p(\" << int(k) << \", \" << alpha/2 << \") = \"\n      << t << endl; // 0.03\n\n    alpha = 0.01; // 99% confidence.\n    t = geometric::find_lower_bound_on_p(k, alpha/2);\n    cout << \"geometric::find_lower_bound_on_p(\" << int(k) << \", \" << alpha/2 << \") = \"\n      << t << endl; // 5e-005\n    t = geometric::find_upper_bound_on_p(k, alpha/2);\n    cout << \"geometric::find_upper_bound_on_p(\" << int(k) << \", \" << alpha/2 << \") = \"\n        << t << endl; // 0.052\n/*`In real life, there will usually be more than one event (fault or success),\nwhen the negative binomial, which has the neccessary extra parameter, will be needed.\n*/\n\n/*`As noted above, using a catch block is always a good idea,\neven if you hope not to use it!\n*/\n  }\n  catch(const std::exception& e)\n  { // Since we have set an overflow policy of ignore_error,\n    // an overflow exception should never be thrown.\n     std::cout << \"\\nMessage from thrown exception was:\\n \" << e.what() << std::endl;\n/*`\nFor example, without a ignore domain error policy, \nif we asked for ``pdf(g, -1)`` for example, \nwe would get an unhelpful abort, but with a catch:\n[pre\nMessage from thrown exception was:\n Error in function boost::math::pdf(const exponential_distribution<double>&, double):\n Number of failures argument is -1, but must be >= 0 !\n] [/pre]\n*/\n//] [/ geometric_eg1_2]\n  }\n  return 0;\n}  // int main()\n\n\n/*\nOutput is:\n\n  Geometric distribution example\n  \n  success fraction of a six-sided dice is 0.1667\n  0.1667\n  0.1667\n  0.1389\n  pdf(g6, 0) + pdf(g6, 1) = 0.3056\n  cdf(g6, 1) = 0.3056\n  cdf(g6, 12) = 0.9065\n  quantile(g6, 0.99) = 24.26\n  0.1389\n  0.3056\n  quantile(complement(g6, 1 - p))  24.26\n  0.5000346561579232\n  0.5\n   quantile(g, 0.95) = 147.28\n  To be 95% confident of finding we customer with a fault, need to survey 148 customers.\n  To be 99% confident of finding we customer with a fault, need to survey 227 customers.\n  To be 80% confident of finding we customer with a fault, need to survey 79 customers.\n  Probability of score on 1st try = 0.75\n  Probability of score on 5th try = 0.0029\n  Probability of score on 5th try = 5.9e-006\n  Probability of score on 5th try = 0.031\n  Probability is failure is 0.01\n  geometric::find_lower_bound_on_p(100, 0.025) = 0.00025\n  geometric::find_upper_bound_on_p(100, 0.025) = 0.037\n  geometric::find_lower_bound_on_p(100, 0.05) = 0.00051\n  geometric::find_upper_bound_on_p(100, 0.05) = 0.03\n  geometric::find_lower_bound_on_p(100, 0.005) = 5e-005\n  geometric::find_upper_bound_on_p(100, 0.005) = 0.052\n  \n*/\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "b10ff1f7bd89e1673380a67ef0db7bfa385628ff", "size": 15617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/geometric_examples.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "libs/math/example/geometric_examples.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "libs/math/example/geometric_examples.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 42.7863013699, "max_line_length": 122, "alphanum_fraction": 0.7000064033, "num_tokens": 4414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6305380816366174}}
{"text": "/*\n    This file is part of control-lib.\n\n    Copyright (c) 2020, 2021, 2022 Bernardo Fichera <bernardo.fichera@gmail.com>\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n*/\n\n#ifndef CONTROLLIB_SPATIAL_SE3_HPP\n#define CONTROLLIB_SPATIAL_SE3_HPP\n\n#include <Eigen/Geometry>\n\nnamespace control_lib {\n    namespace spatial {\n        struct SE3 {\n            /* Init via translation and orientation */\n            SE3(const Eigen::Matrix3d& rot, const Eigen::Vector3d& trans) : _rot(rot), _trans(trans) {}\n\n            /* Init via vector representation */\n            SE3(const Eigen::Matrix<double, 6, 1>& x) : _trans(x.head(3)), _rot(Eigen::AngleAxisd(x.tail(3).norm(), x.tail(3).normalized())) {}\n\n            /* Default constructor */\n            SE3() = default;\n\n            /* Space elements difference */\n            Eigen::Matrix<double, 6, 1> operator-(SE3 const& obj) const { return obj.actionInverse(*this).log(); }\n\n            /* Space dimension */\n            constexpr static size_t dimension() { return 6; }\n\n            /* Translation & rotation */\n            Eigen::Vector3d _trans;\n            Eigen::Matrix3d _rot;\n\n            /* Tangent and contagent plane elements (optionals) */\n            Eigen::Matrix<double, 6, 1> _vel, _acc, _eff;\n\n        protected:\n            SE3 action(const SE3& pose) const { return SE3(_rot * pose._rot, _trans + _rot * pose._trans); }\n\n            SE3 actionInverse(const SE3& pose) const { return SE3(_rot.transpose() * pose._rot, _rot.transpose() * (pose._trans - _trans)); }\n\n            Eigen::Matrix<double, 6, 1> log(const SE3& pose) const\n            {\n                Eigen::AngleAxisd aa(pose._rot);\n\n                Eigen::Vector3d omega = aa.angle() * aa.axis();\n\n                Eigen::Matrix3d omega_skew;\n                omega_skew << 0, -omega(2), omega(1),\n                    omega(2), 0, -omega(0),\n                    -omega(1), omega(0), 0;\n\n                double theta = omega.norm(), A = std::sin(theta) / theta, B = (1 - std::cos(theta)) / std::pow(theta, 2);\n\n                return (Eigen::Matrix<double, 6, 1>() << (Eigen::Matrix3d::Identity() - 0.5 * omega_skew + (1 - 0.5 * A / B) / std::pow(theta, 2) * omega_skew * omega_skew) * pose._trans, omega).finished();\n            }\n\n            Eigen::Matrix<double, 6, 1> log() { return log(*this); }\n        };\n    } // namespace spatial\n\n} // namespace control_lib\n\n#endif // CONTROLLIB_SPATIAL_SE3_HPP", "meta": {"hexsha": "848e4d23af1596d51a2b0d1527c9590ee045f813", "size": 3467, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/control_lib/spatial/SE3.hpp", "max_stars_repo_name": "nash169/control-lib", "max_stars_repo_head_hexsha": "102d14dcc7e3d77c28ed89ff3b8f703dd0a0c504", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/control_lib/spatial/SE3.hpp", "max_issues_repo_name": "nash169/control-lib", "max_issues_repo_head_hexsha": "102d14dcc7e3d77c28ed89ff3b8f703dd0a0c504", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/control_lib/spatial/SE3.hpp", "max_forks_repo_name": "nash169/control-lib", "max_forks_repo_head_hexsha": "102d14dcc7e3d77c28ed89ff3b8f703dd0a0c504", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2804878049, "max_line_length": 206, "alphanum_fraction": 0.625324488, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6304843969720039}}
{"text": "/*!\n\\brief\nDemonstrates plotting various types (including user-defined like multiprecision that can be converted to double.\n*/\n\n//  convertible_to_double.cpp\n\n// Copyright Paul A. Bristow 2018, 2021\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n//   or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\n// using namespace boost::svg;\n// Very convenient to allow easy access to colors and other items.\n\n#include <map>\n// using std::map;\n#include <cmath>\n//using std::sin;\n//using std::cos;\n//using std::tan;\n\n#include <boost/math/constants/constants.hpp> // For pi\n\n// Example of a Boost.Multiprecision type.\n#include <boost/multiprecision/cpp_bin_float.hpp>\n// using boost::multiprecision:: cpp_bin_float_quad;\n// not is_convertible to double, but is_constructible to double.\n\n// Example of a User Defined Type - a fixed point type can also be plotted OK.\n//#include <boost/fixed_point/fixed_point_negatable.hpp>\n//#include <boost/fixed_point/fixed_point_negatable_cmath.hpp>\n// for typedef boost::fixed_point::negatable<15, -16> fixed_point_type;\n\n// Some functions to generate some trig functions.\n// template of floating-point type to allow testing of any type.\ntemplate <typename T>\nT f(T x)\n{\n  return sin(x);\n}\n\ntemplate <typename T>\nT g(T x)\n{\n  return cos(x);\n}\n\ntemplate <typename T>\nT h(T x)\n{\n  return tan(x);\n}\n\ntemplate <typename T = double>\nvoid trig_plots()\n{\n  using namespace boost::svg; // Very convenient to allow easy access to colors and other items.\n\n  std::map<T, T> sin_data, cos_data, tan_data, sincos_data;\n\n  T step = boost::math::constants::pi<T>() / 8;  // Interval between function data points.\n\n   // Generate some trigonometric data to plot.\n  for (T i = static_cast<T>(0); i <= static_cast<T>(10); i += step)\n  {\n    sin_data[i] = f(i); // sin\n    cos_data[i] = g(i); // cos\n    tan_data[i] = h(i); // tan\n    sincos_data[i] = sin(g(i)); // sincos\n  } // for i\n\n  svg_2d_plot my_plot; // Data structure to hold the plot.\n\n                       // Size/scale settings.\n  my_plot.size(700, 500) // SVG image size (pixel).\n    .x_range(-0.5, 10.5) // Range of x and y axes,\n    .y_range(-1.1, 1.1); // chosen to ensure that the maxima and minimax\n                         // are not just on the edge of the plot window.\n\n                         // Text settings.\n  my_plot.title(\"Plot of sin, cos, tan &#x26;  sincos functions\")\n  // Note: for ampersand must use Unicode &#x26; because it is a reserved symbol in SVG XML.\n  // Search engines will provide Unicodes by querying \"UNicode ampersand\"\n  // at sites like https://unicode.org/,\n  // http://www.fileformat.info/info/unicode/char/0026/index.htm and others.\n    .title_font_size(28)\n    .x_label(\"x Axis Units\")\n    .y_major_labels_side(left)\n    .y_major_grid_on(true);\n\n    // Layout options:\n  my_plot.legend_on(true) // Want a legend box.\n    .plot_window_on(true) // want a plot window with axis labels etc outside.\n    .x_label_on(true) // Label X-axis ticks with their values.\n                      //.y_label_on(false)  // false is default.\n    ;\n\n  // Plot color settings.\n  // (Note use of chaining to add settings).\n  my_plot\n    .background_color(darkgreen)\n    .legend_background_color(lightgray)\n    .legend_border_color(black)\n    .plot_background_color(lightgoldenrodyellow)\n    .title_color(white)\n    .y_major_grid_color(black);\n\n    // X axis settings.\n  my_plot.x_major_interval(2)\n    .x_major_tick_length(14)\n    .x_major_tick_width(1)\n    .x_minor_tick_length(7)\n    .x_minor_tick_width(1)\n    .x_num_minor_ticks(3)\n\n    // Y axis settings.\n    .y_major_interval(25)\n    .y_num_minor_ticks(5);\n\n    // Legend settings.\n  my_plot.legend_title_font_size(15)\n    .legend_title(\"Legend\");\n\n  my_plot.plot(sin_data, \"sin(x)\")\n    .line_on(true) // Line joining data points, using default color black.\n    .shape(circlet) // and circle marker showing data points.\n    .size(10) // Size (diameter pixels) of circlet data point marker.\n    .fill_color(yellow) // Outline is default black and centre yellow.\n                        // Default is no bezier.  Note angularity at the minima and maxima.\n    ;\n\n  my_plot.plot(cos_data, \"cos(x)\")\n    .line_color(blue) // Defaults to showing line, but not in legend.\n    .line_on(true) // Needed to show in the legend.\n    .line_width(1) // thinner line.\n    .shape(square) // Center of square has the data point coordinate.\n    .size(5)\n    .fill_color(red)  // Center of square.\n    ;\n\n  my_plot.plot(tan_data, \"tan(x)\")\n    .line_on(false)  // No line joining points.\n    .shape(cone) // bottom point of cone has the coordinate of the data point.\n    .size(5).fill_color(blue); // Just show data point markers.\n\n  my_plot.plot(sincos_data, \"sincos(x)\")\n    .line_on(true)  // Just line joining points.\n    .line_color(purple)\n    .line_width(0.5)\n    .bezier_on(true) // Note plot curve is smoother at the minima and maxima.\n    .shape(none); // NO data point markers (and only shows a line in the legend).\n\n  my_plot.write(\"./demo_convertible_to_double.svg\"); // Final plot.\n\n} // void trig_plots()\n\nint main()\n{\n  // Plot test trig data using several floating-point fundamental or builtin or user-defined (and perhaps fixed-point) types.\n\n  trig_plots<float>(); // OK\n  trig_plots<>(); // default double OK\n  trig_plots<double>(); // OK\n // trig_plots<long double>(); // not OK error C2440: 'static_cast': cannot convert from 'const _Ty2' to 'boost::quan::uncun'\n  // and for higher-than-double precision types, the range from\n  // (std::numeric_limits<long double>::max)() to min() is greater than for double.\n  // so overflow or underflow on conversion to double is possible.\n\n  //using boost::multiprecision::cpp_bin_float_quad;\n  //trig_plots<cpp_bin_float_quad>();  // Not OK error C2440: 'static_cast': cannot convert from 'const _Ty2' to 'boost::quan::uncun'\n\n  // As an example of a User-defined Type a fixed-point is also possible:\n  ///typedef boost::fixed_point::negatable<15, -16> fixed_point_type;\n  //trig_plots<fixed_point_type>(); // OK\n  // But some fixed_point types might fail this example because\n  // the range from max to min might not be great enough for the data to plot chosen.\n\n  // Probably ill-advised, but works, with a warning from use of constant pi which will be 3. not 3.1459...\n  //trig_plots<int>(); //  warning C4244: '=': conversion from 'double' to 'int', possible loss of data\n\n  // Hopeless case - but does not provide a very helpful error message.\n  // trig_plots<std::string>();\n\n  return 0;\n} // int main()\n", "meta": {"hexsha": "41b4d559496dc06f1f4d542c87d401fcb190f664", "size": 6635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/convertible_to_double.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/convertible_to_double.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/convertible_to_double.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 34.9210526316, "max_line_length": 133, "alphanum_fraction": 0.684853052, "num_tokens": 1746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.8080672066194946, "lm_q1q2_score": 0.6302866840913742}}
{"text": "/**\n * $Id$\n *\n * Copyright (C)\n * 2015 - $Date$\n *     Martin Wolf <ndhist@martin-wolf.org>\n *\n * This file is distributed under the BSD 2-Clause Open Source License\n * (See LICENSE file).\n *\n */\n#ifndef NDHIST_STATS_KURTOSIS_HPP_INCLUDED\n#define NDHIST_STATS_KURTOSIS_HPP_INCLUDED 1\n\n#include <boost/python.hpp>\n\n#include <ndhist/ndhist.hpp>\n#include <ndhist/stats/expectation.hpp>\n#include <ndhist/stats/var.hpp>\n\nnamespace ndhist {\nnamespace stats {\n\nnamespace detail {\n\ntemplate <typename AxisValueType, typename WeightValueType>\ndouble\ncalc_axis_kurtosis_impl(\n    ndhist const & h\n  , intptr_t const axis\n)\n{\n    // Do the projection here, so it won't be done twice.\n    ndhist const proj = (h.get_nd() == 1 ? h : h.project(bp::object(axis)));\n\n    double const expact1 = calc_axis_expectation_impl<AxisValueType, WeightValueType>(proj, 1, axis);\n    double const expact2 = calc_axis_expectation_impl<AxisValueType, WeightValueType>(proj, 2, axis);\n    double const expact3 = calc_axis_expectation_impl<AxisValueType, WeightValueType>(proj, 3, axis);\n    double const expact4 = calc_axis_expectation_impl<AxisValueType, WeightValueType>(proj, 4, axis);\n    double const var = calc_axis_var_impl<AxisValueType, WeightValueType>(proj, axis);\n\n    // Kurtosis[x] = (E[x^4] - 4 E[x] E[x^3] + 6 E[x]^2 E[x^2] - 3 E[x]^4) / V[x]^2\n    return (expact4 - 4*expact1*expact3 + 6*expact1*expact1*expact2 - 3*expact1*expact1*expact1*expact1) / (var*var);\n}\n\n}// namespace detail\n\nnamespace py {\n\n/**\n * @brief Calculates the kurtosis along the given axis of the given\n *     ndhist object. As in statistics, the kurtosis is defined as\n *     :math:`Kurtosis[x] = (E[x^4] - 4 E[x] E[x^3] + 6 E[x]^2 E[x^2] - 3 E[x]^4) / V[x]^2`.\n *     This function generates a projection along the given axis and then\n *     calculates the kurtosis.\n *     If None is given as axis, the kurtosis for all individual axes of the\n *     ndhist object will be calculated and returned as a tuple. But if the\n *     dimensionality of the ndhist object is 1, a scalar value is returned.\n *\n * @note This function is only defined for ndhist objects with POD axis values\n *     AND POD weight values.\n */\nboost::python::object\nkurtosis(\n    ndhist const & h\n  , boost::python::object const & axis = boost::python::object()\n);\n\n}// namespace py\n\n}// namespace stats\n}// namespace ndhist\n\n#endif // NDHIST_STATS_KURTOSIS_HPP_INCLUDED\n", "meta": {"hexsha": "dbaf09a1f447be9ada0444a37ed2b0db16ecb5f8", "size": 2402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ndhist/stats/kurtosis.hpp", "max_stars_repo_name": "martwo/ndhist", "max_stars_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ndhist/stats/kurtosis.hpp", "max_issues_repo_name": "martwo/ndhist", "max_issues_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ndhist/stats/kurtosis.hpp", "max_forks_repo_name": "martwo/ndhist", "max_forks_repo_head_hexsha": "193cef3585b5d0277f0721bb9c3a1e78cc67cf1f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0266666667, "max_line_length": 117, "alphanum_fraction": 0.70316403, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6301825237506827}}
{"text": "\r\n#include <iostream>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\ntypedef boost::numeric::ublas::matrix<float> Matrix44;\r\n//typedef boost::numeric::ublas\r\n\r\nint main()\r\n{\r\n\tMatrix44 matrix = boost::numeric::ublas::identity_matrix<float> (4);\r\n\r\n\tstd::cout << matrix << std::endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "76f3e28053c83243c6b69490e187ea90db86854f", "size": 343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/IOTest/IOTest.cpp", "max_stars_repo_name": "taku-xhift/labo", "max_stars_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/IOTest/IOTest.cpp", "max_issues_repo_name": "taku-xhift/labo", "max_issues_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/IOTest/IOTest.cpp", "max_forks_repo_name": "taku-xhift/labo", "max_forks_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0526315789, "max_line_length": 70, "alphanum_fraction": 0.6705539359, "num_tokens": 88, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6301825142977059}}
{"text": "#include <metaSMT/support/default_visitation_unrolling_limit.hpp>\n#include <metaSMT/frontend/QF_BV.hpp>\n#include <metaSMT/DirectSolver_Context.hpp>\n#include <metaSMT/GraphSolver_Context.hpp>\n#include <metaSMT/backend/Boolector.hpp>\n#include <metaSMT/backend/MiniSAT.hpp>\n#include <metaSMT/backend/PicoSAT.hpp>\n#include <metaSMT/backend/CUDD_Context.hpp>\n#include <metaSMT/backend/SAT_Aiger.hpp>\n \n#include <metaSMT/BitBlast.hpp>\n#include <metaSMT/support/run_algorithm.hpp>\n\n#include <boost/mpl/vector.hpp>\n#include <boost/format.hpp>\n#include <boost/foreach.hpp>\n\nusing namespace metaSMT;\nusing namespace metaSMT::logic;\nusing namespace metaSMT::logic::QF_BV;\nusing namespace metaSMT::solver;\nusing namespace std; \n\n#define foreach BOOST_FOREACH \n\ntemplate<typename Solver>\nstruct sudoku\n{\n  typedef bool result_type;\n  \n  sudoku ( string problem ) \n  {\n    field_size = 16; \n    bit_width = int(ceil ( log ( field_size ) / log ( 2 ) )); \n    block_width = bit_width; \n    \n    init_field (); \n    parse ( problem ); \n    field_constraints();\n  }\n\n  void parse ( string problem )\n  {\n    unsigned x = 0, y = 0;\n\n    foreach ( char c, problem )\n    {\n      if ( c != '_') \n      {\n        assertion ( ctx, \n            equal ( field[x][y], bvuint ( c - 'a', bit_width ) ) ); \n      }\n\n      ++x;\n      if ( x == field_size )\n      {\n        y++;\n        x = 0; \n      }\n    }\n  }\n  \n  bool operator() ()\n  {\n    std::cout << \"Solving\" << std::endl; \n    bool sat = solve(ctx);\n    if(sat) print_solution();\n    return sat; \n  }\n\n  void init_field () \n  {\n    field.resize ( field_size ); \n\n    foreach ( vector<bitvector>& row, field )\n    {\n      row.clear ();\n      for ( unsigned i = 0; i < field_size; i++ )\n      {\n        row.push_back ( new_bitvector ( bit_width ) ); \n      }\n    }\n  }\n\n  void field_constraints() \n  {\n    for ( unsigned i = 0; i < field_size; ++i )\n    {\n      row ( i );\n      column ( i ); \n    }\n\n    for ( unsigned i = 0; i < block_width; i++ )\n    {\n      for ( unsigned j = 0; j < block_width; j++ )\n      {\n        block ( i*block_width, j*block_width ); \n      }\n    }\n\n\n  }\n  \n  void row ( unsigned row )\n  {\n    for ( unsigned i = 0; i < field_size; i++ )\n    {\n      for ( unsigned j = i + 1; j < field_size; ++j )\n      {\n        assertion ( ctx, \n            nequal ( field[row][i], field[row][j] ) ); \n      }\n    }\n  }\n\n  void column ( unsigned col )\n  {\n    for ( unsigned i = 0; i < field_size; i++ )\n    {\n      for ( unsigned j = i + 1; j < field_size; ++j )\n      {\n        assertion ( ctx, \n            nequal ( field[i][col], field[j][col] ) ); \n      }\n    }\n  }\n\n  // gets the i-th element of block at pos (col, row)\n  bitvector& index (unsigned row, unsigned col, unsigned i)\n  {\n    return field[row + i/block_width][col + i%block_width];  \n  }\n\n  void block ( unsigned col, unsigned row )  \n  {\n    for ( unsigned i = 0; i < field_size; i++ )\n    {\n      for ( unsigned j = i + 1; j < field_size; ++j )\n      {\n        assertion ( ctx, \n            nequal ( index(row, col, i), index(row, col, j) ) ); \n      }\n    }\n         \n  }\n\n  void print_solution()\n  {\n    for (unsigned i = 0; i < field_size; ++i) {\n      if( i % block_width == 0) printf(\"\\n\");\n      for (unsigned k = 0; k < field_size; ++k) {\n        if( k % block_width == 0 ) printf(\" \");\n        unsigned val = read_value(ctx, field[i][k]);\n        printf(\"%c\", 'a'+val);\n      }\n      printf(\"\\n\");\n    }\n    printf(\"\\n\");\n  }\n\n  Solver ctx; \n  unsigned field_size; \n  unsigned bit_width; \n  unsigned block_width; \n  vector < vector < bitvector > > field; \n\n\n};\n\nint\nmain(int argc, const char *argv[])\n{\n  typedef mpl::vector < \n      DirectSolver_Context < Boolector >\n    , DirectSolver_Context < BitBlast < SAT_Aiger < MiniSAT > > >\n    , DirectSolver_Context < BitBlast < SAT_Aiger < PicoSAT > > >\n    , DirectSolver_Context < BitBlast < CUDD_Context > >\n \n    , GraphSolver_Context < Boolector >\n    , GraphSolver_Context < BitBlast < SAT_Aiger < MiniSAT > > >\n    , GraphSolver_Context < BitBlast < SAT_Aiger < PicoSAT > > >\n    , GraphSolver_Context < BitBlast < CUDD_Context > >\n     \n      > SolverVec;\n\n  if( argc < 2) {\n    cout << \"usage: \"<< argv[0] << \"  solver sudoku\\nsolver:\\n\\t0 - Boolector (SMT)\\n\\t1 - MiniSAT (SAT)\\n\\t2 - PicoSAT (SAT)\\n\\t3 - CUDD (BDD)\" << endl;\n    exit(1);\n  }\n\n  unsigned solver = atoi ( argv[1] ); \n\n  bool val = run_algorithm<SolverVec, sudoku> ( solver, argv[2] ); \n\n  std::cout << \"Sudoku valid? \" << (val ? \"yes\" : \"no\") << std::endl;\n\n  return val? 0 : 1;\n}\n\n", "meta": {"hexsha": "45603a2d375e00f24b033247a6d3eee1adea1318", "size": 4525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox/sudoku/sudoku.cpp", "max_stars_repo_name": "finnhaedicke/metaSMT", "max_stars_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-04-09T14:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:55:58.000Z", "max_issues_repo_path": "toolbox/sudoku/sudoku.cpp", "max_issues_repo_name": "finnhaedicke/metaSMT", "max_issues_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2015-03-13T14:21:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-02T07:59:34.000Z", "max_forks_repo_path": "toolbox/sudoku/sudoku.cpp", "max_forks_repo_name": "finnhaedicke/metaSMT", "max_forks_repo_head_hexsha": "949245da0bf0f3c042cb589aaea5d015e2ed9e9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-04-22T18:10:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T12:44:12.000Z", "avg_line_length": 22.625, "max_line_length": 153, "alphanum_fraction": 0.5593370166, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6301825112483069}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#define NT2_UNIT_MODULE \"nt2 optimize toolbox - nedlermead\"\n\n#include <iostream>\n#include <nt2/include/functions/neldermead.hpp>\n\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/bind.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/rowvect.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/globalsum.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/ones.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/oneo_10.hpp>\n#include <nt2/table.hpp>\nstruct ffp\n{\n  template < class Tab > inline\n  typename Tab::value_type operator()(const Tab & x ) const\n  {\n    typedef typename Tab::value_type value_type;\n    return nt2::globalsum((nt2::sqr((nt2::rowvect(x)-nt2::_(value_type(1), value_type(numel(x)))))));\n    //   NT2_DISPLAY(r)\n  }\n};\n\ntemplate<class Tab > typename Tab::value_type f1(const Tab & x )\n{\n    typedef typename Tab::value_type value_type;\n    return nt2::globalsum((nt2::sqr((nt2::rowvect(x)-nt2::_(value_type(1), value_type(numel(x)))))));\n}\n\n\n// NT2_TEST_CASE_TPL( nedlermead_function_ptr, NT2_REAL_TYPES )\n// {\n//   using nt2::nedlermead;\n//   using nt2::optimization::output;\n//   typedef nt2::table<T> tab_t;\n//   typedef typename nt2::meta::as_logical<T>::type lT;\n//   typedef nt2::table<T> ltab_t;\n//   tab_t x0 = nt2::zeros(nt2::of_size(1, 3), nt2::meta::as_<T>());\n//   ltab_t h = nt2::is_nez(nt2::ones (nt2::of_size(1, 3), nt2::meta::as_<T>())*nt2::Half<T>());\n//   tab_t r = nt2::ones (nt2::of_size(1, 3), nt2::meta::as_<T>());\n//   output<tab_t,T> res = nedlermead(&f1<tab_t, tab_t>, x0, h);\n\n//   std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n//             << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n//   NT2_TEST(res.successful);\n//   NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::abs(res.minimum()-r)), nt2::Sqrteps<T>());\n// }\n\nNT2_TEST_CASE_TPL( nedlermead_functor, NT2_REAL_TYPES )\n{\n  using nt2::neldermead;\n  using nt2::options;\n  using nt2::optimization::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  tab_t x0 = nt2::zeros(nt2::of_size(1, 2), nt2::meta::as_<T>());\n  tab_t h = nt2::ones (nt2::of_size(1, 2), nt2::meta::as_<T>())*nt2::Oneo_10<T>();\n  tab_t r = nt2::_(T(1), T(2));\n  NT2_DISPLAY(x0);\n  NT2_DISPLAY(h);\n  output<tab_t,T> res = neldermead(ffp(), x0, h,\n                                  options [ nt2::iterations_ = 100,\n                                            nt2::tolerance::absolute_ = T(0.001)\n                                    ]);\n\n  std::cout << \"Minimum : f(\" << res.minimum << \") = \" << res.value\n            << \" after \" << res.iterations_count <<  \" iterations\\n\";\n\n  NT2_TEST(res.successful);\n  NT2_DISPLAY(res.minimum());\n  NT2_DISPLAY(r);\n  NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::abs(res.minimum()-r)), T(0.001));\n\n}\n\n", "meta": {"hexsha": "73b62847f6ae88b5fce37f8a0e2c34982b39a767", "size": 3587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/optimization/unit/scalar/neldermead.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/optimization/unit/scalar/neldermead.cpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/optimization/unit/scalar/neldermead.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1595744681, "max_line_length": 101, "alphanum_fraction": 0.6091441316, "num_tokens": 1054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6301825055377018}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n \n This simple example shows how to call dlib's optimal linear assignment problem solver.\n It is an implementation of the famous Hungarian algorithm and is quite fast, operating in\n O(N^3) time.\n\n*/\n\n#include <dlib/optimization/max_cost_assignment.h>\n#include <iostream>\n\nusing namespace std;\nusing namespace dlib;\n\nint main ()\n{\n    // Let's imagine you need to assign N people to N jobs.  Additionally, each person will make\n    // your company a certain amount of money at each job, but each person has different skills\n    // so they are better at some jobs and worse at others.  You would like to find the best way\n    // to assign people to these jobs.  In particular, you would like to maximize the amount of\n    // money the group makes as a whole.  This is an example of an assignment problem and is\n    // what is solved by the max_cost_assignment() routine.\n    // \n    // So in this example, let's imagine we have 3 people and 3 jobs.  We represent the amount of\n    // money each person will produce at each job with a cost matrix.  Each row corresponds to a\n    // person and each column corresponds to a job.  So for example, below we are saying that\n    // person 0 will make $1 at job 0, $2 at job 1, and $6 at job 2.  \n    matrix<int> cost(3,3);\n    cost = 1, 2, 6,\n           5, 3, 6,\n           4, 5, 0;\n\n    // To find out the best assignment of people to jobs we just need to call this function.\n    std::vector<long> assignment = max_cost_assignment(cost);\n\n    // This prints optimal assignments:  [2, 0, 1] which indicates that we should assign\n    // the person from the first row of the cost matrix to job 2, the middle row person to\n    // job 0, and the bottom row person to job 1.\n    for (unsigned int i = 0; i < assignment.size(); i++)\n        cout << assignment[i] << std::endl;\n\n    // This prints optimal cost:  16.0\n    // which is correct since our optimal assignment is 6+5+5.\n    cout << \"optimal cost: \" << assignment_cost(cost, assignment) << endl;\n}\n\n", "meta": {"hexsha": "f6985a9e3c9869ead1bf655981bd01b9cb3f4bf8", "size": 2088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/examples/max_cost_assignment_ex.cpp", "max_stars_repo_name": "maxmert/nlp-mitie", "max_stars_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "examples/max_cost_assignment_ex.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "examples/max_cost_assignment_ex.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 43.5, "max_line_length": 97, "alphanum_fraction": 0.6882183908, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6301824950035597}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\n\n//Cross Product Equivalent\nusing Eigen::Matrix3f;\nusing Eigen::Vector3f;\nMatrix3f crossProductEquivalent(Vector3f v)\n{\n  std::cout << v <<std::endl;\n  std::cout << v(2) <<std::endl;\n  Matrix3f c;\n  c << 0, -v(2), v(1),\n       v(2), 0, -v(0),\n       -v(1), v(0), 0;\n  std::cout << c << std::endl;\n  return c;\n}\n\nint main()\n{\n  Vector3f v;\n  v << 1,\n       2,\n       3;\n  crossProductEquivalent(v);\n}\n", "meta": {"hexsha": "07a21472400238d2b4633ddd3128b6a30e94ec8c", "size": 444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crossProductEquivalent.cpp", "max_stars_repo_name": "nearlab/rover_visual_od", "max_stars_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "crossProductEquivalent.cpp", "max_issues_repo_name": "nearlab/rover_visual_od", "max_issues_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "crossProductEquivalent.cpp", "max_forks_repo_name": "nearlab/rover_visual_od", "max_forks_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.8571428571, "max_line_length": 43, "alphanum_fraction": 0.5630630631, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.6301433770614041}}
{"text": "#include \"sfm/filter_view_pairs_from_orientation.h\"\n\n#include <glog/logging.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <unordered_map>\n#include <unordered_set>\n\n#include \"math/rotation.h\"\n#include \"math/util.h\"\n#include \"rotation_estimation/rotation_estimator.h\"\n#include \"sfm/twoview_info.h\"\n#include \"util/hash.h\"\n#include \"util/map_util.h\"\n#include \"util/types.h\"\n\nnamespace DAGSfM {\n\nnamespace {\n\nbool AngularDifferenceIsAcceptable(\n    const Eigen::Vector3d& orientation1, const Eigen::Vector3d& orientation2,\n    const Eigen::Vector3d& relative_orientation,\n    const double sq_max_relative_rotation_difference_radians) {\n  const Eigen::Vector3d composed_relative_rotation =\n      MultiplyRotations(orientation2, -orientation1);\n  const Eigen::Vector3d loop_rotation =\n      MultiplyRotations(-relative_orientation, composed_relative_rotation);\n  const double sq_rotation_angular_difference_radians =\n      loop_rotation.squaredNorm();\n  return sq_rotation_angular_difference_radians <=\n         sq_max_relative_rotation_difference_radians;\n}\n\n}  // namespace\n\nvoid FilterViewPairsFromOrientation(\n    const std::unordered_map<image_t, Eigen::Vector3d>& orientations,\n    const double max_relative_rotation_difference_degrees,\n    std::unordered_map<ImagePair, TwoViewInfo>& view_pairs,\n    Database& database) {\n  CHECK_GE(max_relative_rotation_difference_degrees, 0.0);\n\n  // Precompute the squared threshold in radians.\n  const double max_relative_rotation_difference_radians =\n      DegToRad(max_relative_rotation_difference_degrees);\n  const double sq_max_relative_rotation_difference_radians =\n      max_relative_rotation_difference_radians *\n      max_relative_rotation_difference_radians;\n\n  std::unordered_set<ImagePair> view_pairs_to_remove;\n\n  for (auto& view_pair : view_pairs) {\n    const Eigen::Vector3d* orientation1 =\n        FindOrNull(orientations, view_pair.first.first);\n    const Eigen::Vector3d* orientation2 =\n        FindOrNull(orientations, view_pair.first.second);\n\n    // If the view pair contains a view that does not have an orientation then\n    // remove it.\n    if (orientation1 == nullptr || orientation2 == nullptr) {\n      LOG(WARNING)\n          << \"View pair (\" << view_pair.first.first << \", \"\n          << view_pair.first.second\n          << \") contains a view that does not exist! Removing the view pair.\";\n      view_pairs_to_remove.insert(view_pair.first);\n      continue;\n    }\n\n    // Remove the view pair if the relative rotation estimate is not within the\n    // tolerance.\n    if (!AngularDifferenceIsAcceptable(\n            *orientation1, *orientation2, view_pair.second.rotation_2,\n            sq_max_relative_rotation_difference_radians)) {\n      view_pairs_to_remove.insert(view_pair.first);\n    } else {\n      // Update relative rotations.\n      view_pair.second.rotation_2 = geometry::RelativeRotationFromTwoRotations(\n          *orientation1, *orientation2);\n    }\n  }\n\n  // Remove all the \"bad\" relative poses.\n  for (const ImagePair view_id_pair : view_pairs_to_remove) {\n    view_pairs.erase(view_id_pair);\n    database.DeleteMatches(view_id_pair.first, view_id_pair.second);\n    database.DeleteInlierMatches(view_id_pair.first, view_id_pair.second);\n  }\n  VLOG(1) << \"Removed \" << view_pairs_to_remove.size()\n          << \" view pairs by rotation filtering.\";\n}\n\n}  // namespace DAGSfM", "meta": {"hexsha": "f00783a3322e5ccd333cb93cc2578fb9ae1f16e2", "size": 3365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sfm/filter_view_pairs_from_orientation.cpp", "max_stars_repo_name": "Yzhbuaa/DAGSfM", "max_stars_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 255.0, "max_stars_repo_stars_event_min_datetime": "2018-12-14T05:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-04T12:15:32.000Z", "max_issues_repo_path": "src/sfm/filter_view_pairs_from_orientation.cpp", "max_issues_repo_name": "Yzhbuaa/DAGSfM", "max_issues_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2018-12-25T03:02:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T03:33:25.000Z", "max_forks_repo_path": "src/sfm/filter_view_pairs_from_orientation.cpp", "max_forks_repo_name": "Yzhbuaa/DAGSfM", "max_forks_repo_head_hexsha": "321f9bf24456f2e68aa4ea3d7a59c39040fe1f1f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2018-12-14T06:09:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T08:29:31.000Z", "avg_line_length": 35.7978723404, "max_line_length": 79, "alphanum_fraction": 0.7420505201, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.630143374822805}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"../simple_lib/include/simple_activation.h\"\n#include <map>\n#include <string>\n\nusing namespace Eigen;\n\n// prototype declaration\nstd::map<std::string, MatrixXd> init_network(void);\nMatrixXd forward(std::map<std::string, MatrixXd> network, MatrixXd x);\n\n// main function\nint main(){\n    using std::cout;\n    using std::endl;\n    using std::map;\n    using std::string;\n\n    MatrixXd X  = MatrixXd::Zero(1, 2);\n    MatrixXd W1 = MatrixXd::Zero(2, 3);\n    MatrixXd B1 = MatrixXd::Zero(1, 3);\n    MatrixXd A1 = MatrixXd::Zero(1, 3);\n    MatrixXd Z1 = MatrixXd::Zero(1, 3);\n    MatrixXd W2 = MatrixXd::Zero(3, 2);\n    MatrixXd B2 = MatrixXd::Zero(1, 2);\n    MatrixXd A2 = MatrixXd::Zero(1, 2);\n    MatrixXd Z2 = MatrixXd::Zero(1, 2);\n    MatrixXd W3 = MatrixXd::Zero(2, 2);\n    MatrixXd B3 = MatrixXd::Zero(1, 2);\n    MatrixXd A3 = MatrixXd::Zero(1, 2);\n    MatrixXd Y  = MatrixXd::Zero(1, 2);\n\n    X << 1.0, 0.5;\n    W1 << 0.1, 0.3, 0.5,  0.2, 0.4, 0.6;\n    B1 << 0.1, 0.2, 0.3;\n\n    W2 << 0.1, 0.4,  0.2, 0.5,  0.3, 0.6;\n    B2 << 0.1, 0.2;\n\n    W3 << 0.1, 0.3,  0.2, 0.4;\n    B3 << 0.1, 0.2;\n\n    A1 = X * W1 + B1;\n\n    cout << \"A1 = \" << A1 << endl;\n\n    Z1 = A1.unaryExpr([](double p){return MyDL::sigmoid<double>(p);});\n\n    cout << \"Z1 = \" << Z1 << endl;\n\n    A2 = Z1 * W2 + B2;\n    Z2 = A2.unaryExpr([] (double p){return MyDL::sigmoid<double>(p);});\n\n    cout << \"A2 = \" << A2 << endl;\n    cout << \"Z2 = \" << Z2 << endl;\n\n    A3 = Z2 * W3 + B3;\n    Y = A3.unaryExpr([] (double p){return MyDL::identity_function<double>(p);});\n\n    cout << \"A3 = \" << A3 << endl;\n    cout << \"Y = \" << Y << endl;\n\n    // call network function -> last activation is Softmax function\n    map <string, MatrixXd> network;\n    network = init_network();\n    Y = forward(network, X);\n\n    cout << \"Function ver: Y = \" << Y << endl;\n\n    return 0;\n}\n\n\n// Implementation\nstd::map<std::string, MatrixXd> init_network(void)\n{\n\n    using std::map;\n    using std::string;\n\n    map<string, MatrixXd> network;\n\n    MatrixXd W1 = MatrixXd::Zero(2, 3);\n    MatrixXd b1 = MatrixXd::Zero(1, 3);\n    MatrixXd W2 = MatrixXd::Zero(3, 2);\n    MatrixXd b2 = MatrixXd::Zero(1, 2);\n    MatrixXd W3 = MatrixXd::Zero(2, 2);\n    MatrixXd b3 = MatrixXd::Zero(1, 2);\n\n    W1 << 0.1, 0.3, 0.5, 0.2, 0.4, 0.6;\n    b1 << 0.1, 0.2, 0.3;\n    W2 << 0.1, 0.4, 0.2, 0.5, 0.3, 0.6;\n    b2 << 0.1, 0.2;\n    W3 << 0.1, 0.3, 0.2, 0.4;\n    b3 << 0.1, 0.2;\n\n    network[\"W1\"] = W1;\n    network[\"b1\"] = b1;\n    network[\"W2\"] = W2;\n    network[\"b2\"] = b2;\n    network[\"W3\"] = W3;\n    network[\"b3\"] = b3;\n\n    return network;\n}\n\nMatrixXd forward(std::map<std::string, MatrixXd> network, MatrixXd x)\n{\n    using std::map;\n    using std::string;\n\n    MatrixXd W1 = MatrixXd::Zero(2, 3);\n    MatrixXd b1 = MatrixXd::Zero(1, 3);\n    MatrixXd W2 = MatrixXd::Zero(3, 2);\n    MatrixXd b2 = MatrixXd::Zero(1, 2);\n    MatrixXd W3 = MatrixXd::Zero(2, 2);\n    MatrixXd b3 = MatrixXd::Zero(1, 2);\n\n    MatrixXd a1 = MatrixXd::Zero(1, 3);\n    MatrixXd z1 = MatrixXd::Zero(1, 3);\n    MatrixXd a2 = MatrixXd::Zero(1, 2);\n    MatrixXd z2 = MatrixXd::Zero(1, 2);\n    MatrixXd a3 = MatrixXd::Zero(1, 2);\n    MatrixXd y = MatrixXd::Zero(1, 2);\n\n    W1 = network[\"W1\"];\n    b1 = network[\"b1\"];\n    W2 = network[\"W2\"];\n    b2 = network[\"b2\"];\n    W3 = network[\"W3\"];\n    b3 = network[\"b3\"];\n\n    a1 = x * W1 + b1;\n    z1 = a1.unaryExpr([] (double p){return MyDL::sigmoid<double>(p);});\n    a2 = z1 * W2 + b2;\n    z2 = a2.unaryExpr([] (double p){return MyDL::sigmoid<double>(p);});\n    a3 = z2 * W3 + b3;\n    y  = MyDL::softmax(a3);\n\n    return y;\n}", "meta": {"hexsha": "96897a6d8843a03a8186565edfc2366506978b48", "size": 3613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/MLP_3layers.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/MLP_3layers.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/MLP_3layers.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": 25.4436619718, "max_line_length": 80, "alphanum_fraction": 0.5502352616, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391685381606, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.630042292277939}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n/// class DigitalFilter\nclass DigitalFilter {\npublic:\n  /// \\{ \\name Constructor and Destructor\n  DigitalFilter();\n\n  virtual ~DigitalFilter();\n  /// \\}\n\n  /// Input to this filter\n  virtual void Input(double input_value) = 0;\n\n  /// Output of this filter\n  virtual double Output() = 0;\n\n  /// Reset data history in this filter\n  virtual void Clear() = 0;\n};\n\n/// class ButterWorthFilter\nclass ButterWorthFilter : public DigitalFilter {\npublic:\n  ButterWorthFilter(int num_sample, double dt, double cutoff_frequency);\n  virtual ~ButterWorthFilter();\n  virtual void Input(double input_value);\n  virtual double Output();\n  virtual void Clear();\n\nprivate:\n  double *mpBuffer;\n  int mCurIdx;\n  int mNumSample;\n  double mDt;\n  double mCutoffFreq;\n  double mValue;\n};\n\n/// class LowPassFilter\nclass LowPassFilter : public DigitalFilter {\npublic:\n  LowPassFilter(double w_c, double t_s);\n  virtual ~LowPassFilter();\n  virtual void Input(double input_value);\n  virtual double Output();\n  virtual void Clear();\n\nprivate:\n  double Lpf_in_prev[2];\n  double Lpf_out_prev[2];\n  double Lpf_in1, Lpf_in2, Lpf_in3, Lpf_out1, Lpf_out2;\n  double lpf_out;\n};\n\n/// class SimpleMovingAverage\nclass SimpleMovingAverage : public DigitalFilter {\npublic:\n  SimpleMovingAverage(int num_data);\n  virtual ~SimpleMovingAverage();\n  virtual void Input(double input_value);\n  virtual double Output();\n  virtual void Clear();\n\nprivate:\n  Eigen::VectorXd buffer_;\n  int num_data_;\n  int idx_;\n  double sum_;\n};\n\n/// class DerivativeLowPassFilter\nclass DerivativeLowPassFilter : public DigitalFilter {\npublic:\n  DerivativeLowPassFilter(double w_c, double t_s);\n  virtual ~DerivativeLowPassFilter();\n  virtual void Input(double input_value);\n  virtual double Output();\n  virtual void Clear();\n\nprivate:\n  double Lpf_in_prev[2];\n  double Lpf_out_prev[2];\n  double Lpf_in1, Lpf_in2, Lpf_in3, Lpf_out1, Lpf_out2;\n  double lpf_out;\n};\n", "meta": {"hexsha": "114c1242c638d1a091f99a90cb5114943081b6d2", "size": 1934, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pnc/filters/digital_filters.hpp", "max_stars_repo_name": "junhyeokahn/PnC", "max_stars_repo_head_hexsha": "388440f7db7b2aedf1e397d0130d806090865c35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-01-31T13:51:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T13:19:01.000Z", "max_issues_repo_path": "pnc/filters/digital_filters.hpp", "max_issues_repo_name": "junhyeokahn/PnC", "max_issues_repo_head_hexsha": "388440f7db7b2aedf1e397d0130d806090865c35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T20:48:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T11:42:02.000Z", "max_forks_repo_path": "pnc/filters/digital_filters.hpp", "max_forks_repo_name": "junhyeokahn/PnC", "max_forks_repo_head_hexsha": "388440f7db7b2aedf1e397d0130d806090865c35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-11-20T22:37:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T17:17:27.000Z", "avg_line_length": 21.7303370787, "max_line_length": 72, "alphanum_fraction": 0.734229576, "num_tokens": 494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6300383108107117}}
{"text": "// Copyright John Maddock 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#include <boost/math/tools/test_data.hpp>\n#include <boost/test/included/prg_exec_monitor.hpp>\n#include <boost/math/special_functions/ellint_1.hpp>\n#include <boost/math/special_functions/jacobi_zeta.hpp>\n#include <fstream>\n#include <boost/math/tools/test_data.hpp>\n#include \"mp_t.hpp\"\n\nusing namespace boost::math::tools;\nusing namespace boost::math;\nusing namespace std;\n\nmp_t heuman_lambda(mp_t phi, mp_t k)\n{\n   mp_t kp = sqrt(1 - k *k);\n   if((k * k < tools::epsilon<float>()) && (fabs(phi) >= constants::half_pi<mp_t>()))\n      throw std::domain_error(\"\");\n   return ellint_1(kp, phi) / ellint_1(kp) + ellint_1(k) * jacobi_zeta(kp, phi) / constants::half_pi<mp_t>();\n}\n\nint cpp_main(int argc, char*argv [])\n{\n   using namespace boost::math::tools;\n\n   parameter_info<mp_t> arg1, arg2;\n   test_data<mp_t> data;\n\n   bool cont;\n   std::string line;\n\n   if(argc < 1)\n      return 1;\n\n   do{\n      if(0 == get_user_parameter_info(arg1, \"phi\"))\n         return 1;\n      if(0 == get_user_parameter_info(arg2, \"k\"))\n         return 1;\n\n      mp_t(*fp)(mp_t, mp_t) = &heuman_lambda;\n      data.insert(fp, arg1, arg2);\n\n      std::cout << \"Any more data [y/n]?\";\n      std::getline(std::cin, line);\n      boost::algorithm::trim(line);\n      cont = (line == \"y\");\n   }while(cont);\n\n   std::cout << \"Enter name of test data file [default=heuman_lambda_data.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"heuman_lambda_data.ipp\";\n   std::ofstream ofs(line.c_str());\n   line.erase(line.find('.'));\n   ofs << std::scientific << std::setprecision(40);\n   write_code(ofs, data, line.c_str());\n\n   return 0;\n}\n\n\n", "meta": {"hexsha": "44aa3803b689e14827cf74b8bc0afa24e5c8b6c1", "size": 1879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/heuman_lambda_data.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/math/tools/heuman_lambda_data.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/math/tools/heuman_lambda_data.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 27.6323529412, "max_line_length": 109, "alphanum_fraction": 0.6514103246, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6299851247802073}}
{"text": "// Copyright Louis Dionne 2013-2017\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n\n#include <boost/hana/functional/fix.hpp>\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/eval_if.hpp>\n#include <boost/hana/functional/always.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/minus.hpp>\n#include <boost/hana/mult.hpp>\nnamespace hana = boost::hana;\n\n\nBOOST_HANA_CONSTEXPR_LAMBDA auto fact = hana::fix([](auto fact, auto n) {\n    return hana::eval_if(hana::equal(n, hana::ullong_c<0>),\n        hana::always(hana::ullong_c<1>),\n        [=](auto _) { return hana::mult(n, fact(_(n) - hana::ullong_c<1>)); }\n    );\n});\n\nconstexpr unsigned long long reference(unsigned long long n)\n{ return n == 0 ? 1 : n * reference(n - 1); }\n\ntemplate <int n>\nvoid test() {\n    BOOST_HANA_CONSTANT_CHECK(hana::equal(\n        fact(hana::ullong_c<n>),\n        hana::ullong_c<reference(n)>\n    ));\n    test<n - 1>();\n}\n\ntemplate <> void test<-1>() { }\n\nint main() {\n    test<15>();\n}\n", "meta": {"hexsha": "79041b4a9840dc2f17d1ff8ec8aa3bace204172e", "size": 1149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/hana/test/functional/fix.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/hana/test/functional/fix.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/hana/test/functional/fix.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": 27.3571428571, "max_line_length": 81, "alphanum_fraction": 0.6684073107, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332893, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.629900753769544}}
{"text": "#include <cstdio> \n#include <cstdlib> \n#include <iostream>\n#include <fstream> \n#include <vector> \n#include <chrono>\n\n#include <getopt.h>\n\n#include \"Alpert_Transform.hpp\"\n#include \"Utils.hpp\"\n\n#include <boost/numeric/bindings/blas/blas.h>\n\nusing namespace std;\n\nint main(int argc, char** argv) {\n    \n  if(argc == 1 ){\n    cout << argv[0] << \" usage is:\" << endl;\n    cout << argv[0] << \" --reduction 'reduction_value' [mesh input_file] [data input_file]\" << endl;\n    cout << \"If the data input file is provided it should have the same number of points as the mesh, if not a default data field will be assigned\" << endl;\n    cout << \"Please refer to README.txt in this folder for more info\" << endl;\n    exit (0);\n  }\n\n    chrono::duration <double> duration;\n    chrono::system_clock::time_point t1, t2;\n    \n    int d, N;\n    double R=10.0e0;\n    int c;\n    \n    {\n          static struct option long_options[] =\n        {\n          /* These options set a flag. */\n          /* These options don\u2019t set a flag.\n             We distinguish them by their indices. */\n          {\"reduction\",  required_argument, 0, 'r'},\n          {0, 0, 0}\n        };\n      /* getopt_long stores the option index here. */\n      int option_index = 0;\n\n      while (c = getopt_long (argc, argv, \"r\",\n\t\t\t      long_options, &option_index) != -1){\n\n\tif(option_index == 0 && optarg){\n\t  R  = atof(optarg); \n\t  cout << \"Reduction set to \" << R << endl;\n\t}\n      }\n\n    }\n\n\n    if(optind >= argc ) {\n      cout << \"Expected an input file name \" << endl;\n      exit(0);\n    }       \n    \n    cout << \"Reading mesh input file\" << argv[optind] << endl;\n    ifstream f(argv[optind]);\n    f >> N >> d;\n\n    cout << \"Number of Points \" << N << endl;\n    cout << \"Number of dimensions \" << d << endl;\n    cout << \"R \" << R << endl;\n        \n    int M=ceil(double(N)/R);\n    int NR=N-M;\n   // meshpoints \n    vector<vector<double> >meshPoints(N, vector<double>(d));\n    \n    // Read mesh into array\n    for (int i = 0; i < N; i++)\n        for (int j = 0; j < d; j++)\n            f >> meshPoints[i][j];\n    \n    f.close();\n    \n    // Setting Wavelet orders\n    vector<int> ki(d);\n    for (int j = 0; j < d; j++)\n      ki[j] = 5;\n    \n    boost::numeric::ublas::vector<double> x(N);\n    boost::numeric::ublas::vector<double> w(N);\n    boost::numeric::ublas::vector<double> xw(N);\n    boost::numeric::ublas::vector<double> ys(N);\n    \n    // Setting data, this step can be replaced by some commands to read an external data file\n    double pi=4.0e0*atan(1.0e0);\n    if (argc>4) {\n      cout << \"Reading data input file\" << argv[optind+1] << endl;\n      f.open(argv[optind+1]);\n      for (int i = 0; i < N; i++)\n\tf >> x(i);\n    }\n    else\n      for (int i = 0; i < N; i++) x(i)=(4.0e0*sin(8.0e0*pi*meshPoints[i][0]))*(4.0e0*sin(7.0e0*pi*meshPoints[i][1]) )*3.0e0*sin(6.0e0*pi*meshPoints[i][0]);\n//     for (int i = 0; i < N; i++) x[i]=(4.0*sin(2.0*pi*p[i][0]) - 4.0*sin(2.0*pi*p[i][1]))*3.0*sin(2.0*pi*p[i][0]);\n    \n    int J=-1;\n    std::list<std::list<boost::numeric::ublas::matrix<double,boost::numeric::ublas::column_major> > > Uj;\n    std::list<std::vector<int> > part;\n    std::vector<int> G;\n    //void Compute_Uj(std::vector<std::vector<double> >meshPoints, std::vector<int> ki, int &J, std::list<std::list<boost::numeric::ublas::matrix<double,boost::numeric::ublas::column_major> > > &Uj, std::list<std::vector<int> > &part, std::vector<int> &G) \n    \n    // Forward wavelet transform\n    t1 = chrono::system_clock::now();\n    Compute_Uj(meshPoints,ki,J,Uj, part, G);\n    Perform_Alpert_transform(x, ki, J,1, w, Uj, part, G);\n    \n    // Sorting, wavelet compression and inverse wavelet transform\n    vector<double> yv(N);\n    vector<size_t> iyv(N);\n    for (int i = 0; i < N; i++) {yv[i]=fabs(w(i));iyv[i]=i;}\n    sortandindices(yv, iyv);\n    t2 = chrono::system_clock::now();\n    duration=t2-t1;\n    cout << \"Total wavelet compression time \" << duration.count() << endl;\n    \n//     for (int i = 0; i < N; i++)\n//       std::cout << w(i) << std::endl;\n    \n    t1 = chrono::system_clock::now();\n    for (int i = NR; i < N; i++) ys(iyv[i])=w(iyv[i]);\n    \n    // xw is the reconstruction by wavelets\n    Perform_Alpert_transform(ys,  ki, J,-1, xw, Uj, part, G);\n    \n    // Computing NRMSE\n    double ew=0.0e0;\n    for (int i = 0; i < N; i++) \n      ew+=pow(x(i)-xw(i),2.0e0);\n    \n    t2 = chrono::system_clock::now();\n    duration=t2-t1;\n    cout << \"Total wavelet decompression time \" << duration.count() << endl;\n    \n    // Computing min and max values in the data x\n    double mx=x(0);\n    double mn=x(0);\n    for (int i = 0; i < N; i++) {\n      if (x(i)>mx)\n\tmx=x(i);\n      if (x(i)<mn)\n\tmn=x(i);\n    }\n    \n    ew=sqrt(ew/double(N))/(mx-mn);\n    \n    cout << \"Alpert Wavelets Compression NRMSE = \" << ew << endl;\n}\n", "meta": {"hexsha": "4eb8ef5dbf8c148e3c1ef1cc759ff928e227bac9", "size": 4797, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "swinzip-v2.0/examples/compress_wavelets/main.cpp", "max_stars_repo_name": "msalloum80/SWinzip", "max_stars_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-17T07:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T07:58:23.000Z", "max_issues_repo_path": "swinzip-v2.5/examples/compress_wavelets/main.cpp", "max_issues_repo_name": "msalloum80/SWinzip", "max_issues_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swinzip-v2.5/examples/compress_wavelets/main.cpp", "max_forks_repo_name": "msalloum80/SWinzip", "max_forks_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-05T20:18:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T20:18:25.000Z", "avg_line_length": 30.5541401274, "max_line_length": 256, "alphanum_fraction": 0.5559724828, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.7520125682019723, "lm_q1q2_score": 0.6299007519966282}}
{"text": "/* Copyright (c) 2018, Skolkovo Institute of Science and Technology (Skoltech)\n * All rights reserved.\n *\n * See LICENSE file in the root of the mrob library.\n *\n *\n * create_points.hpp\n *\n *  Created on: Feb 6, 2018\n *      Author: Gonzalo Ferrer\n *              g.ferrer@skoltech.ru\n *              Mobile Robotics Lab, Skoltech \n */\n\n#ifndef CREATE_POINTS_HPP_\n#define CREATE_POINTS_HPP_\n\n#include \"mrob/SE3.hpp\"\n#include \"mrob/plane.hpp\"\n#include \"mrob/plane_registration.hpp\"\n#include <random>\n#include <memory>\n#include <utility>\n#include <Eigen/StdVector> // for fixed size SE3 objects\n\n\n\nusing namespace Eigen;\n\nnamespace mrob{\n\n/**\n * Class samples a random configuration on SE3 using a\n * uniform distribution U(-R_range, R_range)\n * or any implemented distribution\n */\nclass SampleUniformSE3{\n  public:\n    SampleUniformSE3(double R_range, double t_range);\n    SampleUniformSE3(double R_min, double R_max, double t_min, double t_max);\n    ~SampleUniformSE3();\n    SE3 samplePose();\n    Mat31 samplePosition();\n    SO3 sampleOrientation();\n  protected:\n    std::default_random_engine generator_;\n    std::uniform_real_distribution<double> rotationUniform_;\n    std::uniform_real_distribution<double> tUniform_;\n};\n\n/**\n * Class samples a point on a surface over the plane XY\n * according to a fixed noise on height\n */\nclass SamplePlanarSurface{\n  public:\n    SamplePlanarSurface(double zStd, double bias = 0.0);\n    ~SamplePlanarSurface();\n    /**\n     * samples a point with noise and biases as specified in class\n     */\n    Mat31 samplePoint();\n    void sampleBias();\n\n  protected:\n    std::default_random_engine generator_;\n    std::uniform_real_distribution<double> x_, y_;\n    std::normal_distribution<double> z_, bias_;\n    double xBias_, yBias_;\n};\n\n/**\n * Class generating a sequence of pointClouds given some specifications.\n */\nclass CreatePoints{\npublic:\n    /**\n     * Creates a class\n     */\n    CreatePoints(uint_t N = 10, uint_t numberPlanes = 4, uint_t numberPoses = 2, double noisePerPoint = 0.01, double noiseBias = 0.1);\n    ~CreatePoints();\n\n    /**\n     * Fill the PlaneRegistration class with planes calculated here (reset)\n     * and a new initial trajectory set to I's\n     */\n    void create_plane_registration(PlaneRegistration& planeReg);\n\n    std::vector<Mat31>& get_point_cloud(uint_t t);\n    std::vector<uint_t>& get_point_plane_ids(uint_t t);\n\n    uint_t get_number_planes() const {return numberPlanes_;};\n    uint_t get_number_poses() const {return numberPoses_;};\n\n    std::vector<SE3>& get_ground_truth_trajectory() {return goundTruthTrajectory_;};\n\n    std::vector<SE3>& get_plane_poses() {return planePoses_;};\n    std::vector<std::pair<uint_t, std::shared_ptr<Plane> >>& get_all_planes() {return planes_;}\n\n    void print() const;\n\n\nprotected:\n    // generation parameters\n    uint_t numberPoints_; // Number of points\n    uint_t numberPlanes_; // Number of planes in the virtual environment\n    double noisePerPoint_, noiseBias_;\n    double rotationRange_;\n    double transRange_;\n    double lamdaOutlier_;\n    SampleUniformSE3 samplePoses_,samplePlanes_;\n    SamplePlanarSurface samplePoints_;\n\n    // Point cloud data generated\n    std::vector< std::vector<Mat31> > X_;\n    // IDs for facilitating the task of DA and normal computation\n    std::vector< std::vector<uint_t>> pointId_;\n\n    // Trajectory parameters\n    double xRange_, yRange_; // dimension of the workspace\n    SE3 initialPose_, finalPose_;\n    std::vector<SE3> goundTruthTrajectory_;// ground truth trajectory\n    uint_t numberPoses_;\n\n    // Generation of planes\n    std::vector<SE3> planePoses_;\n    std::vector<std::pair<uint_t, std::shared_ptr<Plane> >> planes_;\n\n};\n\n}\n#endif /* CREATE_POINTS_HPP_ */\n", "meta": {"hexsha": "4ac567ed07f3eb6daf13c9bcad1b4789e1dc5974", "size": 3725, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/PCRegistration/mrob/create_points.hpp", "max_stars_repo_name": "anastasiia-kornilova/mrob", "max_stars_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-10T09:36:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-10T09:36:50.000Z", "max_issues_repo_path": "src/PCRegistration/mrob/create_points.hpp", "max_issues_repo_name": "anastasiia-kornilova/mrob", "max_issues_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PCRegistration/mrob/create_points.hpp", "max_forks_repo_name": "anastasiia-kornilova/mrob", "max_forks_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_forks_repo_licenses": ["BSD-3-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.007518797, "max_line_length": 134, "alphanum_fraction": 0.7087248322, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6299007369210782}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n\nusing namespace std;\n\nint main()\n{\n    Eigen::Matrix<float,7,9>mat0;\n    mat0=Eigen::MatrixXf::Random(7,9);\n    cout<<\"mat0:\"<<endl<<mat0<<endl;\n\n    Eigen::Matrix<float,3,3>mat1=mat0.block(0,0,3,3);\n    cout<<\"mat1:\"<<endl<<mat1<<endl;\n    \n    mat1=Eigen::MatrixXf::Identity(3,3);\n    cout<<\"mat1:\"<<endl<<mat1<<endl;\n    return 0;\n}\n", "meta": {"hexsha": "d582c2ed2480337de19b98e282b64df6e020ec59", "size": 379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/assignment/ex3_5/ex3_5.cpp", "max_stars_repo_name": "linmeeka/slambook", "max_stars_repo_head_hexsha": "554a9fdd33fc50b2b7d375cdbf4a1a5f8b46e7b8", "max_stars_repo_licenses": ["MIT"], "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/assignment/ex3_5/ex3_5.cpp", "max_issues_repo_name": "linmeeka/slambook", "max_issues_repo_head_hexsha": "554a9fdd33fc50b2b7d375cdbf4a1a5f8b46e7b8", "max_issues_repo_licenses": ["MIT"], "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/assignment/ex3_5/ex3_5.cpp", "max_forks_repo_name": "linmeeka/slambook", "max_forks_repo_head_hexsha": "554a9fdd33fc50b2b7d375cdbf4a1a5f8b46e7b8", "max_forks_repo_licenses": ["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.9473684211, "max_line_length": 53, "alphanum_fraction": 0.6094986807, "num_tokens": 133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.62986190013082}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE gaussian_quadratures_test\n\n// Standard includes\n#include <fstream>\n\n// Third party includes\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/xtp/quadrature_factory.h\"\n\n// VOTCA includes\n#include <votca/tools/eigenio_matrixmarket.h>\n\nusing namespace votca::xtp;\nusing namespace votca;\n\n// defines a Gaussian as integration test\n// result should by ~sqrt(pi)\nclass FunctionEvaluation {\n public:\n  FunctionEvaluation(){};\n\n  double operator()(Index j, double point, bool symmetry) const {\n    double factor = 0.0;\n    // this is only here to staisfy the unused variable warning\n    if (j < 100) {\n      if (symmetry) {\n        factor = 2.0;\n      } else {\n        factor = 1.0;\n      }\n    }\n\n    return factor * exp(-std::pow(point, 2));\n  }\n};\n\nBOOST_AUTO_TEST_SUITE(gaussian_quadratures_test)\n\nBOOST_AUTO_TEST_CASE(gauss_legendre) {\n\n  QuadratureFactory::RegisterAll();\n  std::unique_ptr<GaussianQuadratureBase> gq_ =\n      Quadratures().Create(\"legendre\");\n\n  std::vector<int> orders{8, 10, 12, 14, 16, 18, 20, 40, 100};\n  FunctionEvaluation f = FunctionEvaluation();\n\n  Eigen::VectorXd integrals(9);\n  for (Index i = 0; i < 9; i++) {\n    gq_->configure(orders[i]);\n    integrals(i) = gq_->Integrate(f);\n  }\n\n  Eigen::VectorXd integrals_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadVector(\n          std::string(XTP_TEST_DATA_FOLDER) +\n          \"/gaussian_quadratures/gauss_legendre.mm\");\n\n  bool check_integral = integrals.isApprox(integrals_ref, 1e-10);\n  if (!check_integral) {\n    std::cout << \"Gauss-Legendre\" << std::endl;\n    std::cout << integrals << std::endl;\n    std::cout << \"Gauss-Legendre ref\" << std::endl;\n    std::cout << integrals_ref << std::endl;\n  }\n  BOOST_CHECK_EQUAL(check_integral, true);\n}\n\nBOOST_AUTO_TEST_CASE(modified_gauss_legendre) {\n\n  QuadratureFactory::RegisterAll();\n  std::unique_ptr<GaussianQuadratureBase> gq_ =\n      std::unique_ptr<GaussianQuadratureBase>(\n          Quadratures().Create(\"modified_legendre\"));\n\n  std::vector<int> orders{8, 10, 12, 14, 16, 18, 20, 40, 100};\n  FunctionEvaluation f = FunctionEvaluation();\n\n  Eigen::VectorXd integrals(9);\n  for (Index i = 0; i < 9; i++) {\n    gq_->configure(orders[i]);\n    integrals(i) = gq_->Integrate(f);\n  }\n\n  Eigen::VectorXd integrals_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadVector(\n          std::string(XTP_TEST_DATA_FOLDER) +\n          \"/gaussian_quadratures/modified_gauss_legendre.mm\");\n\n  bool check_integral = integrals.isApprox(integrals_ref, 1e-10);\n  if (!check_integral) {\n    std::cout << \"modified Gauss-Legendre\" << std::endl;\n    std::cout << integrals << std::endl;\n    std::cout << \"modified Gauss-Legendre ref\" << std::endl;\n    std::cout << integrals_ref << std::endl;\n  }\n  BOOST_CHECK_EQUAL(check_integral, true);\n}\n\nBOOST_AUTO_TEST_CASE(gauss_laguerre) {\n\n  QuadratureFactory::RegisterAll();\n  std::unique_ptr<GaussianQuadratureBase> gq_ =\n      std::unique_ptr<GaussianQuadratureBase>(Quadratures().Create(\"laguerre\"));\n  std::vector<int> orders{8, 10, 12, 14, 16, 18, 20, 40, 100};\n  FunctionEvaluation f = FunctionEvaluation();\n\n  Eigen::VectorXd integrals(9);\n  for (Index i = 0; i < 9; i++) {\n    gq_->configure(orders[i]);\n    integrals(i) = gq_->Integrate(f);\n  }\n\n  Eigen::VectorXd integrals_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadVector(\n          std::string(XTP_TEST_DATA_FOLDER) +\n          \"/gaussian_quadratures/gauss_laguerre.mm\");\n\n  bool check_integral = integrals.isApprox(integrals_ref, 1e-10);\n  if (!check_integral) {\n    std::cout << \"Gauss-Laguerre\" << std::endl;\n    std::cout << integrals << std::endl;\n    std::cout << \"Gauss-Laguerre ref\" << std::endl;\n    std::cout << integrals_ref << std::endl;\n  }\n  BOOST_CHECK_EQUAL(check_integral, true);\n}\n\nBOOST_AUTO_TEST_CASE(gauss_hermite) {\n\n  QuadratureFactory::RegisterAll();\n  std::unique_ptr<GaussianQuadratureBase> gq_ =\n      std::unique_ptr<GaussianQuadratureBase>(Quadratures().Create(\"hermite\"));\n  std::vector<int> orders{8, 10, 12, 14, 16, 18, 20, 40, 100};\n  FunctionEvaluation f = FunctionEvaluation();\n\n  Eigen::VectorXd integrals(9);\n  for (Index i = 0; i < 9; i++) {\n    gq_->configure(orders[i]);\n    integrals(i) = gq_->Integrate(f);\n  }\n\n  Eigen::VectorXd integrals_ref =\n      votca::tools::EigenIO_MatrixMarket::ReadVector(\n          std::string(XTP_TEST_DATA_FOLDER) +\n          \"/gaussian_quadratures/gauss_hermite.mm\");\n\n  bool check_integral = integrals.isApprox(integrals_ref, 1e-10);\n  if (!check_integral) {\n    std::cout << \"Gauss-Hermite\" << std::endl;\n    std::cout << integrals << std::endl;\n    std::cout << \"Gauss-Hermite ref\" << std::endl;\n    std::cout << integrals_ref << std::endl;\n  }\n  BOOST_CHECK_EQUAL(check_integral, true);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a134475b98f26975a32764c86b18b157398ee716", "size": 5399, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_gaussian_quadratures.cc", "max_stars_repo_name": "rubengerritsen/xtp", "max_stars_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/test_gaussian_quadratures.cc", "max_issues_repo_name": "rubengerritsen/xtp", "max_issues_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_gaussian_quadratures.cc", "max_forks_repo_name": "rubengerritsen/xtp", "max_forks_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_forks_repo_licenses": ["Apache-2.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.3314606742, "max_line_length": 80, "alphanum_fraction": 0.6821633636, "num_tokens": 1533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6298618849048501}}
{"text": "#include <Rcpp.h>\n#include <Eigen/Eigenvalues>\n\nusing namespace Rcpp;\nusing namespace Eigen;\n\n// This is a simple example of exporting a C++ function to R. You can\n// source this function into an R session using the Rcpp::sourceCpp\n// function (or via the Source button on the editor toolbar). Learn\n// more about Rcpp at:\n//\n//   http://www.rcpp.org/\n//   http://adv-r.had.co.nz/Rcpp.html\n//   http://gallery.rcpp.org/\n//\n\n\n// [[Rcpp::export]]\nEigen::MatrixXd rcppeigen_sqrt(const Eigen::Map<Eigen::MatrixXd> & A){\n  SelfAdjointEigenSolver<MatrixXd> es(A);\n  MatrixXd sqrtA = es.operatorSqrt();\n  return sqrtA;\n}\n\n// [[Rcpp::export]]\nEigen::MatrixXd rcppeigen_invsqrt(const Eigen::Map<Eigen::MatrixXd> & A){\n  SelfAdjointEigenSolver<MatrixXd> es(A);\n  MatrixXd invsqrtA = es.operatorInverseSqrt();\n  return invsqrtA;\n}\n\n\n\n\n\n// [[Rcpp::export]]\nNumericVector timesTwo(NumericVector x) {\n  return x * 2;\n}\n\n\n// You can include R code blocks in C++ files processed with sourceCpp\n// (useful for testing and development). The R code will be automatically\n// run after the compilation.\n//\n\n/*** R\ntimesTwo(42)\nrcppeigen_sqrt(diag(c(2, 2)))\n*/\n", "meta": {"hexsha": "8fe26718406921621735ed8f4b82019329574595", "size": 1139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen_sqrt.cpp", "max_stars_repo_name": "cran/qtl2pleio", "max_stars_repo_head_hexsha": "f20276022e209695b3c4954c461db9f956b8bede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-02-16T01:30:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T17:38:57.000Z", "max_issues_repo_path": "src/eigen_sqrt.cpp", "max_issues_repo_name": "cran/qtl2pleio", "max_issues_repo_head_hexsha": "f20276022e209695b3c4954c461db9f956b8bede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2018-02-22T20:21:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-13T20:27:30.000Z", "max_forks_repo_path": "src/eigen_sqrt.cpp", "max_forks_repo_name": "cran/qtl2pleio", "max_forks_repo_head_hexsha": "f20276022e209695b3c4954c461db9f956b8bede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-28T16:05:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-29T18:18:13.000Z", "avg_line_length": 22.3333333333, "max_line_length": 73, "alphanum_fraction": 0.7023705004, "num_tokens": 315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276222, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6298618847656017}}
{"text": "#include \"../geometry.hpp\"\n#include \"../static_graph.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n\n#include <algorithm>\n\nnamespace boost {\n    namespace test_tools {\n        template<>\n        struct print_log_value<coordinate>\n        {\n            void operator()(std::ostream& os,const coordinate& coord)\n            {\n                ::operator<<(os, coord);\n            }\n        };\n    }\n}\n\nnamespace geometry {\ninline std::ostream& operator<<(std::ostream& lhs, const geometry::point_position& rhs)\n{\n    switch (rhs)\n    {\n    case geometry::point_position::LEFT_OF_LINE:\n        lhs << \"LEFT_OF_LINE\";\n        break;\n    case geometry::point_position::RIGHT_OF_LINE:\n        lhs << \"RIGHT_OF_LINE\";\n        break;\n    case geometry::point_position::ON_LINE:\n        lhs << \"ON_LINE\";\n        break;\n    }\n    return lhs;\n}\n}\n\nBOOST_AUTO_TEST_SUITE(geometry_tests)\n\nBOOST_AUTO_TEST_CASE(cross_product_test)\n{\n    BOOST_CHECK_EQUAL(geometry::cross(coordinate {0, 0}, coordinate {1, 1}), 0);\n    BOOST_CHECK_EQUAL(geometry::cross(coordinate {1, 0}, coordinate {1, 0}), 0);\n    BOOST_CHECK_EQUAL(geometry::cross(coordinate {-1, 0}, coordinate {1, 0}), 0);\n    BOOST_CHECK_EQUAL(geometry::cross(coordinate {-1, 0}, coordinate {-1, 0}), 0);\n}\n\nBOOST_AUTO_TEST_CASE(segments_intersect)\n{\n    BOOST_CHECK(geometry::segments_intersect(coordinate {0, 0}, coordinate {1, 1}, coordinate {0, 0.5}, coordinate {1, 0.5}));\n    BOOST_CHECK(!geometry::segments_intersect(coordinate {0, 0}, coordinate {-1, -1}, coordinate {0, 0.5}, coordinate {1, 0.5}));\n}\n\nBOOST_AUTO_TEST_CASE(segment_intersection)\n{\n    // 0    1     2     3\n    // 4    5     6     7\n    // 8    9     10    11\n    std::vector<coordinate> coords {\n        coordinate {0, 1}, coordinate {1, 1}, coordinate {2, 1}, coordinate {3, 1},\n        coordinate {0, 0}, coordinate {1, 0}, coordinate {2, 0}, coordinate {3, 0},\n        coordinate {0, -1}, coordinate {1, -1}, coordinate {2, -1}, coordinate {3, -1},\n    };\n\n    {\n        auto params = geometry::segment_intersection(coords[4], coords[7], coords[0], coords[9]);\n        BOOST_CHECK_EQUAL(params.first_param, 1/6.0);\n        BOOST_CHECK_EQUAL(params.second_param, 0.5);\n    }\n\n    {\n        auto params = geometry::segment_intersection(coords[4], coords[7], coords[9], coords[0]);\n        BOOST_CHECK_EQUAL(params.first_param, 1/6.0);\n        BOOST_CHECK_EQUAL(params.second_param, 0.5);\n    }\n\n    {\n        auto params = geometry::segment_intersection(coords[4], coords[5], coords[2], coords[11]);\n        BOOST_CHECK_EQUAL(params.first_param, 2.5);\n        BOOST_CHECK_EQUAL(params.second_param, 0.5);\n    }\n\n    {\n        auto params = geometry::segment_intersection(coords[2], coords[9], coords[3], coords[10]);\n        BOOST_CHECK(params.colinear);\n    }\n\n    {\n        auto params = geometry::segment_intersection(coords[1], coords[10], coords[2], coords[9]);\n        BOOST_CHECK_EQUAL(params.first_param, 0.5);\n        BOOST_CHECK_EQUAL(params.second_param, 0.5);\n    }\n}\n\nBOOST_AUTO_TEST_CASE(intersection_regression)\n{\n    auto params = geometry::segment_intersection(coordinate {0, 0}, coordinate {2, 2}, coordinate {1, 1}, coordinate {2, 1});\n    BOOST_CHECK_EQUAL(params.first_param, 0.5);\n    BOOST_CHECK_EQUAL(params.second_param, 0);\n}\n\nBOOST_AUTO_TEST_CASE(normal_test)\n{\n    BOOST_CHECK_EQUAL(geometry::line_normal(coordinate {0, 0}, coordinate {1, 1}), (coordinate{-1, 1}));\n    BOOST_CHECK_EQUAL(geometry::line_normal(coordinate {0, 0}, coordinate {-1, -1}), (coordinate{1, -1}));\n    BOOST_CHECK_EQUAL(geometry::line_normal(coordinate {-1, -1}, coordinate {-2, -2}), (coordinate{1, -1}));\n    BOOST_CHECK_EQUAL(geometry::line_normal(coordinate {1, 1}, coordinate {3, 0.5}), (coordinate{0.5, 2}));\n}\n\nBOOST_AUTO_TEST_CASE(position_to_line_test)\n{\n    BOOST_CHECK_EQUAL(geometry::position_to_line(coordinate {1, 1}, coordinate {3, 0.5}, coordinate {2, 0}), geometry::point_position::RIGHT_OF_LINE);\n    BOOST_CHECK_EQUAL(geometry::position_to_line(coordinate {0, 0}, coordinate {1, 1}, coordinate {0.5, 1}), geometry::point_position::LEFT_OF_LINE);\n    BOOST_CHECK_EQUAL(geometry::position_to_line(coordinate {0, 0}, coordinate {1, 1}, coordinate {0.5, -1}), geometry::point_position::RIGHT_OF_LINE);\n    BOOST_CHECK_EQUAL(geometry::position_to_line(coordinate {0, 0}, coordinate {1, 1}, coordinate {2, 2}), geometry::point_position::ON_LINE);\n    BOOST_CHECK_EQUAL(geometry::position_to_line(coordinate {0, 0}, coordinate {-1, -1}, coordinate {-0.5, -1}), geometry::point_position::LEFT_OF_LINE);\n    BOOST_CHECK_EQUAL(geometry::position_to_line(coordinate {0, 0}, coordinate {-1, -1}, coordinate {-0.5, 1}), geometry::point_position::RIGHT_OF_LINE);\n    BOOST_CHECK_EQUAL(geometry::position_to_line(coordinate {0, 0}, coordinate {-1, -1}, coordinate {-2, -2}), geometry::point_position::ON_LINE);\n}\n\nBOOST_AUTO_TEST_CASE(normalized_angle)\n{\n    const float epsilon = 0.001f;\n    BOOST_CHECK(std::abs(geometry::normalize_angle(-M_PI) - M_PI) < epsilon);\n    BOOST_CHECK(std::abs(geometry::normalize_angle(M_PI) - M_PI) < epsilon);\n}\n\nBOOST_AUTO_TEST_CASE(angle_diff_test)\n{\n    const float epsilon = 0.001f;\n    BOOST_CHECK(geometry::angle_diff(-M_PI, M_PI) < epsilon);\n    BOOST_CHECK(geometry::angle_diff(M_PI, -M_PI) < epsilon);\n    BOOST_CHECK(geometry::angle_diff(-M_PI_2, 3*M_PI_2) < epsilon);\n    BOOST_CHECK(geometry::angle_diff(3*M_PI_2, -M_PI_2) < epsilon);\n    BOOST_CHECK(std::abs(geometry::angle_diff(M_PI/4, -M_PI/4) - M_PI_2) < epsilon);\n    BOOST_CHECK(std::abs(geometry::angle_diff(-M_PI/4, M_PI/4) - M_PI_2) < epsilon);\n}\n\nBOOST_AUTO_TEST_CASE(slope_compare_test)\n{\n    // 0\n    //    1\n    // x    2\n    //    3\n    // 4\n    std::vector<coordinate> coordinates {\n        coordinate {0, 1},\n        coordinate {0.5, 0.5},\n        coordinate {1.0, 0.0},\n        coordinate {0.5, -0.5},\n        coordinate {0, -1},\n    };\n\n    coordinate origin {0, 0};\n\n    for (auto i = 0u; i < coordinates.size(); ++i)\n    {\n        for (auto j = i+1; j < coordinates.size(); ++j)\n        {\n            BOOST_CHECK(geometry::slope_compare(origin, coordinates[i], coordinates[j]));\n        }\n    }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e370ced9843a83ec43d50c072270bdca9ee9eaa4", "size": 6209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/geometry_tests.cpp", "max_stars_repo_name": "TheMarex/deberg", "max_stars_repo_head_hexsha": "050f9ae8930801cc03d216eddc515e9929f7b916", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-06-23T14:01:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-12T23:08:06.000Z", "max_issues_repo_path": "tests/geometry_tests.cpp", "max_issues_repo_name": "TheMarex/deberg", "max_issues_repo_head_hexsha": "050f9ae8930801cc03d216eddc515e9929f7b916", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/geometry_tests.cpp", "max_forks_repo_name": "TheMarex/deberg", "max_forks_repo_head_hexsha": "050f9ae8930801cc03d216eddc515e9929f7b916", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5235294118, "max_line_length": 153, "alphanum_fraction": 0.6545337413, "num_tokens": 1708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6298618695860485}}
{"text": "#include \"bond.h\"\n#include <Eigen/Dense>\n#include <iostream>\n\nconstexpr bool DO_PROJECTION = true;\n\nBond::Bond(double force_constant, double equilibrium_distance, int first_atom, int second_atom,\n           Eigen::VectorXd rail)\n    : force_constant(force_constant)\n    , equilibrium_distance(equilibrium_distance)\n    , atoms { first_atom, second_atom }\n    , rail {rail.normalized()} {}\n\nEigen::VectorXd Bond::project_onto_rail(const Eigen::VectorXd& input) const {\n    //! Project a given vector onto this bond rail\n    /*!\n     *! \\param input the vector to do the projection of\n     *! \\return projected the component of the vector in the direction of the rail\n     */\n    if constexpr (DO_PROJECTION) {\n        return input.dot(rail) * rail;\n    }\n    return input;\n}\n\ndouble Bond::get_excitement_factor(const Eigen::MatrixXd& positions) const {\n    Eigen::VectorXd separation = positions.row(atoms[0]) - positions.row(atoms[1]);\n    separation = project_onto_rail(separation);\n    double distance = separation.dot(rail);\n    return distance / equilibrium_distance;\n\n}\n\nHarmonicBond::HarmonicBond(double force_constant, double equilibrium_distance, int first_atom,\n                           int second_atom, Eigen::VectorXd rail)\n    : Bond(force_constant, equilibrium_distance, first_atom, second_atom, rail) {}\n\nEigen::VectorXd HarmonicBond::force(const Eigen::MatrixXd& positions) const {\n    const Eigen::VectorXd separation = positions.row(atoms[0]) - positions.row(atoms[1]);\n    auto magnitude = separation.norm();\n    const Eigen::VectorXd direction = separation / magnitude;\n    double extension = magnitude - equilibrium_distance;\n    \n    const Eigen::VectorXd force_direction = force_constant * extension * direction;\n    \n    return project_onto_rail(force_direction);\n}\n\ndouble HarmonicBond::frequency(const Eigen::VectorXd& masses) const {\n    const auto reduced_mass = masses[atoms[0]] * masses[atoms[1]] / (masses[atoms[0]] + masses[atoms[1]]);\n    return std::sqrt(force_constant / reduced_mass);\n}\n\ndouble HarmonicBond::period(const Eigen::VectorXd& masses) const {\n    return 2 * M_PI / frequency(masses);\n}\n\ndouble HarmonicBond::energy(const Eigen::MatrixXd& positions) const {\n    const auto stretch_ratio = get_excitement_factor(positions) - 1.0;\n    return  stretch_ratio * stretch_ratio * force_constant * equilibrium_distance * equilibrium_distance / 2.0;\n}\n", "meta": {"hexsha": "bcb98b85924a1476f0b613918abae129f977e902", "size": 2391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bond.cpp", "max_stars_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_stars_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bond.cpp", "max_issues_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_issues_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bond.cpp", "max_forks_repo_name": "Matt-HJ-Bailey/Constrained-MD", "max_forks_repo_head_hexsha": "3897a5f97272772ea03f953414df779aed844216", "max_forks_repo_licenses": ["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.564516129, "max_line_length": 111, "alphanum_fraction": 0.721455458, "num_tokens": 530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6298355251838255}}
{"text": "#pragma once\n\n#include <vector>\n#include <Eigen/Core>\n\nclass Polygon {\n    Eigen::MatrixX2d _points;\n    int _n_points;\n    int _orientation;\n\npublic:\n    Polygon(Eigen::MatrixX2d points);\n\n    Eigen::Vector2d operator[](int i) const {\n        // Wrap indices to the number of vertices in the polygon\n        int j = (_n_points + (i % _n_points)) % _n_points;\n        return _points.row(j);\n    }\n\n    Eigen::MatrixX2d points() const {\n        return _points;\n    }\n\n    int n_points() const {\n        return _n_points;\n    }\n\n    /*  Orientation of the polygon\n        Returns: \n            >0 if orientation is counter-clockwise\n            <0 if orientation is clockwise\n    */\n    int orientation() const {\n        return _orientation;\n    }\n\n    bool is_solid() const {\n        return _orientation > 0;\n    }\n\n    bool is_hollow() const {\n        return _orientation < 0;\n    }\n};\n\nbool inside_polygon(const Eigen::Vector2d& point, const Polygon& polygon);\nbool inside_any_polygon(const Eigen::Vector2d& point, const std::vector<Polygon>& polygons);\n\nint segments_intersect(const std::pair<Eigen::Vector2d, Eigen::Vector2d>& ab, const std::pair<Eigen::Vector2d, Eigen::Vector2d>& cd);\nint segment_intersects_polygon(const std::pair<Eigen::Vector2d, Eigen::Vector2d>& segment, const Polygon& polygon);\n", "meta": {"hexsha": "f5e80848f26fdae09525ae36020882ac549c8f9a", "size": 1306, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/headers/geometry.hpp", "max_stars_repo_name": "will-bell/navitools", "max_stars_repo_head_hexsha": "1760799097c5f8aefbc7a3e87e60a2a99649724d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-26T18:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T18:41:00.000Z", "max_issues_repo_path": "src/headers/geometry.hpp", "max_issues_repo_name": "will-bell/navitools", "max_issues_repo_head_hexsha": "1760799097c5f8aefbc7a3e87e60a2a99649724d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/headers/geometry.hpp", "max_forks_repo_name": "will-bell/navitools", "max_forks_repo_head_hexsha": "1760799097c5f8aefbc7a3e87e60a2a99649724d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6078431373, "max_line_length": 133, "alphanum_fraction": 0.6500765697, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.629834914116451}}
{"text": "#pragma once\n\n#include <cmath>\n#include <limits>\n#include <Eigen/Core>\n\nnamespace kt84 {\n\n// the definition of functions alpha(r) and beta(r) implemented in each kernel |\n//-----------------------------------------------------------------------------+\n/*\n\ninner product of vectors x and y:\n    x * y := x^T y (scalar)\nouter product of vectors x and y: \n    x % y := x y^T (matrix)\n\nnotations:\n    x := (x_1, ..., x_N)\n    r := |x| = sqrt(x * x)\n\nunivariate RBF kernel:\n    phi(r): R+ --> R;\n\nfirst & second derivatives of phi:\n    phi'(r) : R+ --> R\n    phi\"(r) : R+ --> R\n\nexamples of phi:\n    phi(r) := |r|^3                             // cubic\n    phi(r) := exp(-r^2/(2 * sigma^2))           // Gaussian\n\nmultivariate RBF kernel:\n    f(x): R^N --> R\n    f(x) := phi(r)\n          = phi(|x|)\n\ngradient:\n    g(x): R^N --> R^N\n    g(x) := df/dx(x)\n          = phi'(r) / r * x\n\ndefinition of alpha:\n    alpha(r) := phi'(r) / r\n    g(x) = alpha(r) * x\n\nHessian:\n    H(x): R^N --> R^(NxN)\n    H(x) := d^2f/dx^2\n          = dg/dx\n          = {(r * phi\"(r) - phi'(r)) / r^3} * (x % x) + {phi'(r) / r} * I\n\ndefinition of beta:\n    beta(r) := (r * phi\"(r) - phi'(r)) / r^3\n    H(x) = alpha(r) * I + beta(r) * (x % x);\n\n*/\n\n// Gradient is always defined even for singular (r=0) cases --> can be used with Hermite RBF |\n//-------------------------------------------------------------------------------------------+\nstruct RBFKernel_Gaussian {\n    struct Param {\n        double sigma;\n        Param(double sigma = 1) : sigma(sigma) {}\n    } param;\n    double operator()       (double r) const { return std::exp(-r * r / (2 * param.sigma * param.sigma)); }\n    double derivative_first (double r) const { return operator()(r) * r / (-param.sigma * param.sigma); }\n    double derivative_second(double r) const { return operator()(r) * (r * r - param.sigma * param.sigma) / (param.sigma * param.sigma * param.sigma * param.sigma); }\n    double alpha_singular() const { return -1 / (param.sigma * param.sigma); }\n    static const bool AlphaAlwaysDefined = true;\n    static const bool Decaying = true;\n};\n\nstruct RBFKernel_SquaredInverse {\n    struct Param {\n        double epsilon;\n        Param(double epsilon = 0) : epsilon(epsilon) {}\n    } param;\n    double operator()(double r) const {\n        if (r == 0 && param.epsilon == 0)\n            return std::numeric_limits<double>::infinity();         // indication of hard constraint (for MLS)\n        return 1 / (r * r + param.epsilon * param.epsilon);\n    }\n    double derivative_first(double r) const {\n        double t = operator()(r);\n        return -2 * r * t * t;\n    }\n    double derivative_second(double r) const {\n        double t = operator()(r);\n        return (6 * r * r - 2 * param.epsilon * param.epsilon) * t * t * t;\n    }\n    double alpha_singular() const {\n        return -2 / (param.epsilon * param.epsilon * param.epsilon * param.epsilon);\n    }\n    static const bool AlphaAlwaysDefined = true;\n    static const bool Decaying = true;\n};\n\nstruct RBFKernel_Wendland {\n    // Wendland, H. \n    // Piecewise polynomial, positive definite and compactly supported radial basis functions of minimal degree. \n    // Advances in Computational Mathematics 4, 389--396, 1995.\n    struct Param {\n        double support;\n        Param(double support = 1) : support(support) {}\n    } param;\n    double operator()(double r) const {\n        double t = r / param.support;\n        if (t > 1)\n            return 0;\n        return (1 - t) * (1 - t) * (1 - t) * (1 - t) * (4 * t + 1);\n    }\n    double derivative_first(double r) const {\n        double t = r / param.support;\n        if (t > 1)\n            return 0;\n        return -20 * t * (1 - t) * (1 - t) * (1 - t) / param.support;\n    }\n    double derivative_second(double r) const {\n        double t = r / param.support;\n        if (t > 1)\n            return 0;\n        return 20 * (1 - t) * (1 - t) * (4 * t - 1) / (param.support * param.support);\n    }\n    double alpha_singular() const { return -20 / (param.support * param.support); }\n    static const bool AlphaAlwaysDefined = true;\n    static const bool Decaying = true;\n};\n\nstruct RBFKernel_Cubed {\n    struct Param {} param;\n    double operator()       (double r) const { return r * r * r; }\n    double derivative_first (double r) const { return 3 * r * r; }\n    double derivative_second(double r) const { return 6 * r; }\n    double alpha_singular() const { return 0; }\n    static const bool AlphaAlwaysDefined = true;\n    static const bool Decaying = false;\n};\n\n// gradient is undefined for singular (r=0) cases --> cannot be used with HermiteRBF |\n//-----------------------------------------------------------------------------------+\nstruct RBFKernel_Identity {\n    struct Param {} param;\n    double operator()       (double r) const { return r; }\n    double derivative_first (double r) const { return 1; }\n    double derivative_second(double r) const { return 0; }\n    double alpha_singular() const { throw std::logic_error(\"undefined!\"); }\n    static const bool AlphaAlwaysDefined = false;\n    static const bool Decaying = false;\n};\n\nstruct RBFKernel_SquaredLog {\n    struct Param {} param;\n    double operator()(double r) const {\n        if (r == 0)\n            return 0;\n        return r * r * std::log(r);\n    }\n    double derivative_first(double r) const {\n        if (r == 0)\n            return 0;\n        return 2 * r * std::log(r) + r;\n    }\n    double derivative_second(double r) const {\n        if (r == 0)\n            return -std::numeric_limits<double>::infinity();        // not sure if this treatment is correct...\n        return 2 * std::log(r) + 3;\n    }\n    double alpha_singular() const { throw std::logic_error(\"undefined!\"); }\n    static const bool AlphaAlwaysDefined = false;\n    static const bool Decaying = false;\n};\n\n// general template classes |\n//--------------------------+\n\ntemplate <class _RBFKernel_Core>\nstruct RBFKernel_Univariate {\n    typedef _RBFKernel_Core Core;\n    \n    Core core;\n    \n    double operator()(double r) const { return core(r); }\n    double derivative_first(double r) const { return core.derivative_first(r); }\n    double derivative_second(double r) const { return core.derivative_second(r); }\n    double alpha(double r) const { return core.derivative_first(r) / r; }\n    double beta(double r) const { return (r * core.derivative_second(r) - core.derivative_first(r)) / (r * r * r); }\n};\n\ntemplate <int _Dim, class _RBFKernel_Core>\nstruct RBFKernel_Bivariate {\n    enum { Dim  = _Dim };\n    \n    typedef Eigen::Matrix<double, Dim, 1> Point;\n    typedef Eigen::Matrix<double, 1, Dim> Gradient;\n    typedef Eigen::Matrix<double, Dim, Dim> Hessian;\n    typedef RBFKernel_Univariate<_RBFKernel_Core> Univariate;\n    \n    static const bool GradientAlwaysDefined = Univariate::Core::AlphaAlwaysDefined;\n    static const bool Decaying              = Univariate::Core::Decaying;\n    \n    Univariate univariate;\n    \n    double operator()(const Point& p0, const Point& p1) const { return univariate((p1 - p0).norm()); }\n    Gradient gradient(const Point& p_variable, const Point& p_fixed) const {\n        Point p_diff = p_variable - p_fixed;\n        double r = p_diff.norm();\n        if (r == 0)\n            return Gradient::Zero();\n        return univariate.alpha(r) * p_diff.transpose();\n    }\n    Hessian hessian(const Point& p_variable, const Point& p_fixed) const {\n        Point p_diff = p_variable - p_fixed;\n        double r = p_diff.norm();\n        if (r == 0)\n            return univariate.core.alpha_singular() * Hessian::Identity();\n        return univariate.alpha(r) * Hessian::Identity() + univariate.beta(r) * p_diff * p_diff.transpose();\n    }\n    \n    // easy access to kernel parameters\n    typename Univariate::Core::Param& param() { return univariate.core.param; }\n    const typename Univariate::Core::Param& param() const { return univariate.core.param; }\n};\n\n}\n\n", "meta": {"hexsha": "8f13650493686d9a932749f1a67ffbf7c1f15131", "size": 7880, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/math/RBFKernel.hh", "max_stars_repo_name": "honoriocassiano/skbar", "max_stars_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kt84/math/RBFKernel.hh", "max_issues_repo_name": "honoriocassiano/skbar", "max_issues_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T12:16:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T12:21:41.000Z", "max_forks_repo_path": "src/kt84/math/RBFKernel.hh", "max_forks_repo_name": "honoriocassiano/skbar", "max_forks_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7136563877, "max_line_length": 166, "alphanum_fraction": 0.5763959391, "num_tokens": 2029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676514011486, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.6298023530330635}}
{"text": "#include \"mtf/SSM//AffineEstimator.h\"\n#include \"mtf/Utilities/warpUtils.h\"\n#include \"mtf/Utilities/miscUtils.h\"\n#include \"opencv2/core/core_c.h\"\n#include \"opencv2/calib3d/calib3d.hpp\"\n#include <boost/random/uniform_int_distribution.hpp>\n\n\n_MTF_BEGIN_NAMESPACE\n\nAffineEstimator::AffineEstimator(int _modelPoints, bool _use_boost_rng)\n\t: SSMEstimator(_modelPoints, cvSize(3, 2), 1, _use_boost_rng) {\n\tassert(_modelPoints >= 3);\n\tcheckPartialSubsets = false;\n}\n\nint AffineEstimator::runKernel(const CvMat* m1, const CvMat* m2, CvMat* H) {\n\tint n_pts = m1->rows * m1->cols;\n\n\t//if(n_pts != 3) {\n\t//    throw invalid_argument(cv::format(\"Invalid no. of points: %d provided\", n_pts));\n\t//}\n\tconst CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;\n\tconst CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;\n\n\tMatrix2Xd in_pts, out_pts;\n\tin_pts.resize(Eigen::NoChange, n_pts);\n\tout_pts.resize(Eigen::NoChange, n_pts);\n\tfor(int pt_id = 0; pt_id < n_pts; pt_id++) {\n\t\tin_pts(0, pt_id) = M[pt_id].x;\n\t\tin_pts(1, pt_id) = M[pt_id].y;\n\n\t\tout_pts(0, pt_id) = m[pt_id].x;\n\t\tout_pts(1, pt_id) = m[pt_id].y;\n\t}\n\tMatrix3d affine_mat = utils::computeAffineDLT(in_pts, out_pts);\n\n\tdouble *H_ptr = H->data.db;\n\tH_ptr[0] = affine_mat(0, 0);\n\tH_ptr[1] = affine_mat(0, 1);\n\tH_ptr[2] = affine_mat(0, 2);\n\tH_ptr[3] = affine_mat(1, 0);\n\tH_ptr[4] = affine_mat(1, 1);\n\tH_ptr[5] = affine_mat(1, 2);\n\treturn 1;\n}\n\n\nvoid AffineEstimator::computeReprojError(const CvMat* m1, const CvMat* m2,\n\tconst CvMat* model, CvMat* _err) {\n\tint n_pts = m1->rows * m1->cols;\n\tconst CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;\n\tconst CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;\n\tconst double* H = model->data.db;\n\tfloat* err = _err->data.fl;\n\n\tfor(int pt_id = 0; pt_id < n_pts; pt_id++) {\n\t\tdouble dx = (H[0] * M[pt_id].x + H[1] * M[pt_id].y + H[2]) - m[pt_id].x;\n\t\tdouble dy = (H[3] * M[pt_id].x + H[4] * M[pt_id].y + H[5]) - m[pt_id].y;\n\t\terr[pt_id] = (float)(dx * dx + dy * dy);\n\t}\n}\n\nbool AffineEstimator::refine(const CvMat* m1, const CvMat* m2,\n\tCvMat* model, int maxIters) {\n\tLevMarq solver(6, 0, cvTermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS, maxIters, DBL_EPSILON));\n\tint n_pts = m1->rows * m1->cols;\n\tconst CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;\n\tconst CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;\n\tCvMat modelPart = cvMat(solver.param->rows, solver.param->cols, model->type, model->data.ptr);\n\tcvCopy(&modelPart, solver.param);\n\n\tfor(;;)\t{\n\t\tconst CvMat* _param = 0;\n\t\tCvMat *_JtJ = 0, *_JtErr = 0;\n\t\tdouble* _errNorm = 0;\n\n\t\tif(!solver.updateAlt(_param, _JtJ, _JtErr, _errNorm))\n\t\t\tbreak;\n\n\t\tfor(int pt_id = 0; pt_id < n_pts; pt_id++)\t{\n\t\t\tconst double* h = _param->data.db;\n\t\t\tdouble Mx = M[pt_id].x, My = M[pt_id].y;\n\t\t\tdouble _xi = (h[0] * Mx + h[1] * My + h[2]);\n\t\t\tdouble _yi = (h[3] * Mx + h[4] * My + h[5]);\n\t\t\tdouble err[] = { _xi - m[pt_id].x, _yi - m[pt_id].y };\n\t\t\tif(_JtJ || _JtErr) {\n\t\t\t\tdouble J[][6] = {\n\t\t\t\t\t{ Mx, My, 1, 0, 0, 0 },\n\t\t\t\t\t{ 0, 0, 0, Mx, My, 1 }\n\t\t\t\t};\n\t\t\t\tfor(int j = 0; j < 6; j++) {\n\t\t\t\t\tfor(int k = j; k < 6; k++)\n\t\t\t\t\t\t_JtJ->data.db[j * 6 + k] += J[0][j] * J[0][k] + J[1][j] * J[1][k];\n\t\t\t\t\t_JtErr->data.db[j] += J[0][j] * err[0] + J[1][j] * err[1];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(_errNorm)\n\t\t\t\t*_errNorm += err[0] * err[0] + err[1] * err[1];\n\t\t}\n\t}\n\n\tcvCopy(solver.param, &modelPart);\n\treturn true;\n}\n\ncv::Mat estimateAffine(cv::InputArray _points1, cv::InputArray _points2,\n\tcv::OutputArray _mask, const SSMEstimatorParams &params){\n\tcv::Mat points1 = _points1.getMat(), points2 = _points2.getMat();\n\tint npoints = points1.checkVector(2);\n\tCV_Assert(npoints >= 0 && points2.checkVector(2) == npoints &&\n\t\tpoints1.type() == points2.type());\n\n\tcv::Mat H(2, 3, CV_64F);\n\tCvMat _pt1 = points1, _pt2 = points2;\n\tCvMat matH = H, c_mask, *p_mask = 0;\n\tif(_mask.needed()){\n\t\t_mask.create(npoints, 1, CV_8U, -1, true);\n\t\tp_mask = &(c_mask = _mask.getMat());\n\t}\n\tbool ok = estimateAffine(&_pt1, &_pt2, &matH, p_mask, params) > 0;\n\tif(!ok)\n\t\tH = cv::Scalar(0);\n\treturn H;\n}\n\nint\testimateAffine(const CvMat* in_pts, const CvMat* out_pts,\n\tCvMat* __H, CvMat* mask, const SSMEstimatorParams &params) {\n\tbool result = false;\n\tcv::Ptr<CvMat> out_pts_hm, in_pts_hm, tempMask;\n\n\tdouble H[6];\n\tCvMat matH = cvMat(2, 3, CV_64FC1, H);\n\n\tCV_Assert(CV_IS_MAT(out_pts) && CV_IS_MAT(in_pts));\n\n\tint n_pts = MAX(out_pts->cols, out_pts->rows);\n\tCV_Assert(n_pts >= params.n_model_pts);\n\n\tout_pts_hm = cvCreateMat(1, n_pts, CV_64FC2);\n\tcvConvertPointsHomogeneous(out_pts, out_pts_hm);\n\n\tin_pts_hm = cvCreateMat(1, n_pts, CV_64FC2);\n\tcvConvertPointsHomogeneous(in_pts, in_pts_hm);\n\n\tif(mask) {\n\t\tCV_Assert(CV_IS_MASK_ARR(mask) && CV_IS_MAT_CONT(mask->type) &&\n\t\t\t(mask->rows == 1 || mask->cols == 1) &&\n\t\t\tmask->rows * mask->cols == n_pts);\n\t}\n\tif(mask || n_pts > params.n_model_pts)\n\t\ttempMask = cvCreateMat(1, n_pts, CV_8U);\n\tif(!tempMask.empty())\n\t\tcvSet(tempMask, cvScalarAll(1.));\n\n\tAffineEstimator estimator(params.n_model_pts, params.use_boost_rng);\n\n\tint method = n_pts == params.n_model_pts ? 0 : params.method_cv;\n\tif(method == CV_LMEDS)\n\t\tresult = estimator.runLMeDS(in_pts_hm, out_pts_hm, &matH, tempMask, params.confidence, \n\t\tparams.max_iters, params.max_subset_attempts);\n\telse if(method == CV_RANSAC)\n\t\tresult = estimator.runRANSAC(in_pts_hm, out_pts_hm, &matH, tempMask, params.ransac_reproj_thresh,\n\t\tparams.confidence, params.max_iters, params.max_subset_attempts);\n\telse\n\t\tresult = estimator.runKernel(in_pts_hm, out_pts_hm, &matH) > 0;\n\n\tif(result && n_pts > params.n_model_pts) {\n\t\tutils::icvCompressPoints((CvPoint2D64f*)in_pts_hm->data.ptr, tempMask->data.ptr, 1, n_pts);\n\t\tn_pts = utils::icvCompressPoints((CvPoint2D64f*)out_pts_hm->data.ptr, tempMask->data.ptr, 1, n_pts);\n\t\tin_pts_hm->cols = out_pts_hm->cols = n_pts;\n\t\tif(method == CV_RANSAC)\n\t\t\testimator.runKernel(in_pts_hm, out_pts_hm, &matH);\n\t\tif(params.refine){\n\t\t\testimator.refine(in_pts_hm, out_pts_hm, &matH, params.lm_max_iters);\n\t\t}\n\t}\n\n\tif(result)\n\t\tcvConvert(&matH, __H);\n\n\tif(mask && tempMask) {\n\t\tif(CV_ARE_SIZES_EQ(mask, tempMask))\n\t\t\tcvCopy(tempMask, mask);\n\t\telse\n\t\t\tcvTranspose(tempMask, mask);\n\t}\n\n\treturn (int)result;\n}\n\n//AffineEstimator::AffineEstimator(int _modelPoints)\n//\t: SSMEstimator(_modelPoints, cvSize(3, 3), 1)\n//{\n//\tassert(_modelPoints == 4 || _modelPoints == 5);\n//\tcheckPartialSubsets = false;\n//}\n\n//int AffineEstimator::runKernel(const CvMat* m1, const CvMat* m2, CvMat* H)\n//{\n//\tint i, count = m1->rows*m1->cols;\n//\tconst CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;\n//\tconst CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;\n\n//\tdouble LtL[9][9], W[9][1], V[9][9];\n//\tCvMat _LtL = cvMat(9, 9, CV_64F, LtL);\n//\tCvMat matW = cvMat(9, 1, CV_64F, W);\n//\tCvMat matV = cvMat(9, 9, CV_64F, V);\n//\tCvMat _H0 = cvMat(3, 3, CV_64F, V[8]);\n//\tCvMat _Htemp = cvMat(3, 3, CV_64F, V[7]);\n//\tCvPoint2D64f cM = { 0, 0 }, cm = { 0, 0 }, sM = { 0, 0 }, sm = { 0, 0 };\n\n//\tfor(i = 0; i < count; i++)\n//\t{\n//\t\tcm.x += m[i].x; cm.y += m[i].y;\n//\t\tcM.x += M[i].x; cM.y += M[i].y;\n//\t}\n\n//\tcm.x /= count; cm.y /= count;\n//\tcM.x /= count; cM.y /= count;\n\n//\tfor(i = 0; i < count; i++)\n//\t{\n//\t\tsm.x += fabs(m[i].x - cm.x);\n//\t\tsm.y += fabs(m[i].y - cm.y);\n//\t\tsM.x += fabs(M[i].x - cM.x);\n//\t\tsM.y += fabs(M[i].y - cM.y);\n//\t}\n\n//\tif(fabs(sm.x) < DBL_EPSILON || fabs(sm.y) < DBL_EPSILON ||\n//\t\tfabs(sM.x) < DBL_EPSILON || fabs(sM.y) < DBL_EPSILON)\n//\t\treturn 0;\n//\tsm.x = count / sm.x; sm.y = count / sm.y;\n//\tsM.x = count / sM.x; sM.y = count / sM.y;\n\n//\tdouble invHnorm[9] = { 1. / sm.x, 0, cm.x, 0, 1. / sm.y, cm.y, 0, 0, 1 };\n//\tdouble Hnorm2[9] = { sM.x, 0, -cM.x*sM.x, 0, sM.y, -cM.y*sM.y, 0, 0, 1 };\n//\tCvMat _invHnorm = cvMat(3, 3, CV_64FC1, invHnorm);\n//\tCvMat _Hnorm2 = cvMat(3, 3, CV_64FC1, Hnorm2);\n\n//\tcvZero(&_LtL);\n//\tfor(i = 0; i < count; i++)\n//\t{\n//\t\tdouble x = (m[i].x - cm.x)*sm.x, y = (m[i].y - cm.y)*sm.y;\n//\t\tdouble X = (M[i].x - cM.x)*sM.x, Y = (M[i].y - cM.y)*sM.y;\n//\t\tdouble Lx[] = { X, Y, 1, 0, 0, 0, -x*X, -x*Y, -x };\n//\t\tdouble Ly[] = { 0, 0, 0, X, Y, 1, -y*X, -y*Y, -y };\n//\t\tint j, k;\n//\t\tfor(j = 0; j < 9; j++)\n//\t\t\tfor(k = j; k < 9; k++)\n//\t\t\t\tLtL[j][k] += Lx[j] * Lx[k] + Ly[j] * Ly[k];\n//\t}\n//\tcvCompleteSymm(&_LtL);\n\n//\t//cvSVD( &_LtL, &matW, 0, &matV, CV_SVD_MODIFY_A + CV_SVD_V_T );\n//\tcvEigenVV(&_LtL, &matV, &matW);\n//\tcvMatMul(&_invHnorm, &_H0, &_Htemp);\n//\tcvMatMul(&_Htemp, &_Hnorm2, &_H0);\n//\tcvConvertScale(&_H0, H, 1. / _H0.data.db[8]);\n\n//\treturn 1;\n//}\n\n\n//void AffineEstimator::computeReprojError(const CvMat* m1, const CvMat* m2,\n//\tconst CvMat* model, CvMat* _err)\n//{\n//\tint i, count = m1->rows*m1->cols;\n//\tconst CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;\n//\tconst CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;\n//\tconst double* H = model->data.db;\n//\tfloat* err = _err->data.fl;\n\n//\tfor(i = 0; i < count; i++)\n//\t{\n//\t\tdouble ww = 1. / (H[6] * M[i].x + H[7] * M[i].y + 1.);\n//\t\tdouble dx = (H[0] * M[i].x + H[1] * M[i].y + H[2])*ww - m[i].x;\n//\t\tdouble dy = (H[3] * M[i].x + H[4] * M[i].y + H[5])*ww - m[i].y;\n//\t\terr[i] = (float)(dx*dx + dy*dy);\n//\t}\n//}\n\n//bool AffineEstimator::refine(const CvMat* m1, const CvMat* m2, CvMat* model, int maxIters)\n//{\n//\tCvLevMarq solver(8, 0, cvTermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS, maxIters, DBL_EPSILON));\n//\tint i, j, k, count = m1->rows*m1->cols;\n//\tconst CvPoint2D64f* M = (const CvPoint2D64f*)m1->data.ptr;\n//\tconst CvPoint2D64f* m = (const CvPoint2D64f*)m2->data.ptr;\n//\tCvMat modelPart = cvMat(solver.param->rows, solver.param->cols, model->type, model->data.ptr);\n//\tcvCopy(&modelPart, solver.param);\n\n//\tfor(;;)\n//\t{\n//\t\tconst CvMat* _param = 0;\n//\t\tCvMat *_JtJ = 0, *_JtErr = 0;\n//\t\tdouble* _errNorm = 0;\n\n//\t\tif(!solver.updateAlt(_param, _JtJ, _JtErr, _errNorm))\n//\t\t\tbreak;\n\n//\t\tfor(i = 0; i < count; i++)\n//\t\t{\n//\t\t\tconst double* h = _param->data.db;\n//\t\t\tdouble Mx = M[i].x, My = M[i].y;\n//\t\t\tdouble ww = h[6] * Mx + h[7] * My + 1.;\n//\t\t\tww = fabs(ww) > DBL_EPSILON ? 1. / ww : 0;\n//\t\t\tdouble _xi = (h[0] * Mx + h[1] * My + h[2])*ww;\n//\t\t\tdouble _yi = (h[3] * Mx + h[4] * My + h[5])*ww;\n//\t\t\tdouble err[] = { _xi - m[i].x, _yi - m[i].y };\n//\t\t\tif(_JtJ || _JtErr)\n//\t\t\t{\n//\t\t\t\tdouble J[][8] =\n//\t\t\t\t{\n//\t\t\t\t\t{ Mx*ww, My*ww, ww, 0, 0, 0, -Mx*ww*_xi, -My*ww*_xi },\n//\t\t\t\t\t{ 0, 0, 0, Mx*ww, My*ww, ww, -Mx*ww*_yi, -My*ww*_yi }\n//\t\t\t\t};\n\n//\t\t\t\tfor(j = 0; j < 8; j++)\n//\t\t\t\t{\n//\t\t\t\t\tfor(k = j; k < 8; k++)\n//\t\t\t\t\t\t_JtJ->data.db[j * 8 + k] += J[0][j] * J[0][k] + J[1][j] * J[1][k];\n//\t\t\t\t\t_JtErr->data.db[j] += J[0][j] * err[0] + J[1][j] * err[1];\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\tif(_errNorm)\n//\t\t\t\t*_errNorm += err[0] * err[0] + err[1] * err[1];\n//\t\t}\n//\t}\n\n//\tcvCopy(solver.param, &modelPart);\n//\treturn true;\n//}\n\n_MTF_END_NAMESPACE\n", "meta": {"hexsha": "36cf5e1939d3477606902933afc49097d4635660", "size": 10664, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SSM/src/AffineEstimator.cc", "max_stars_repo_name": "abhineet123/MTF", "max_stars_repo_head_hexsha": "6cb45c88d924fb2659696c3375bd25c683802621", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2016-12-11T00:34:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T23:03:40.000Z", "max_issues_repo_path": "SSM/src/AffineEstimator.cc", "max_issues_repo_name": "siqiyan/MTF", "max_issues_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-09-04T06:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T19:07:23.000Z", "max_forks_repo_path": "SSM/src/AffineEstimator.cc", "max_forks_repo_name": "siqiyan/MTF", "max_forks_repo_head_hexsha": "9a76388c907755448bb7223420fe74349130f636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2017-02-19T02:12:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T03:47:55.000Z", "avg_line_length": 31.8328358209, "max_line_length": 102, "alphanum_fraction": 0.6026819205, "num_tokens": 4382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6297867153295403}}
{"text": "/** @file\n * @brief NPDE OutputImpedanceBVP\n * @author Erick Schulz\n * @date 12/07/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"outputimpedancebvp.h\"\n\n#include <lf/assemble/assemble.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <cassert>\n\nnamespace OutputImpedanceBVP {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::VectorXd solveImpedanceBVP(\n    const std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> &fe_space_p,\n    Eigen::Vector2d g) {\n  // Related implementations:\n  // Homework problem ErrorEstimatesForTraces:\n  // https://gitlab.math.ethz.ch/ralfh/npdecodes/tree/master/homeworks/ErrorEstimatesForTraces\n\n  // Pointer to current mesh\n  std::shared_ptr<const lf::mesh::Mesh> mesh_p = fe_space_p->Mesh();\n  // Obtain local->global index mapping for current finite element space\n  const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n  // Dimension of finite element space\n  const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n  // Obtain specification for shape functions on edges\n  std::shared_ptr<const lf::uscalfe::ScalarReferenceFiniteElement<double>>\n      rsf_edge_p = fe_space_p->ShapeFunctionLayout(lf::base::RefEl::kSegment());\n\n  Eigen::VectorXd discrete_solution(N_dofs);\n\n  // I : ASSEMBLY\n  // Matrix in triplet format holding Galerkin matrix, zero initially.\n  lf::assemble::COOMatrix<double> A(N_dofs, N_dofs);\n  // Right hand side vector, must be initialized with 0!\n  Eigen::Matrix<double, Eigen::Dynamic, 1> phi(N_dofs);\n  phi.setZero();\n\n  // I.i : Computing volume matrix for negative Laplace operator\n  //====================\n  // Your code goes here\n  //====================\n  /* SAM_LISTING_END_1 */\n\n  /* SAM_LISTING_BEGIN_2 */\n  // I.ii : Computing mass edge matrix resulting from Robin B.C.\n  // Obtain an array of boolean flags for the edges of the mesh, 'true'\n  // indicates that the edge lies on the boundary\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 1)};\n  //====================\n  // Your code goes here\n  //====================\n  /* SAM_LISTING_END_2 */\n\n  /* SAM_LISTING_BEGIN_9 */\n  // I.iii : Computing right-hand side vector\n  // Right-hand side source function f\n  auto mf_f = lf::mesh::utils::MeshFunctionGlobal(\n      [](Eigen::Vector2d x) -> double { return 0.0; });\n  lf::uscalfe::ScalarLoadElementVectorProvider<double, decltype(mf_f)>\n      elvec_builder(fe_space_p, mf_f);\n  // Invoke assembly on cells (codim == 0)\n  AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n  // I.iv : Imposing essential boundary conditions\n  // Dirichlet data\n  auto mf_g = lf::mesh::utils::MeshFunctionGlobal(\n      [&g](Eigen::Vector2d x) -> double { return g.dot(x); });\n  //====================\n  // Your code goes here\n  //====================\n\n  // Assembly completed! Convert COO matrix A into CRS format using Eigen's\n  // internal conversion routines.\n  Eigen::SparseMatrix<double> A_sparse = A.makeSparse();\n\n// II : SOLVING  THE LINEAR SYSTEM\n//====================\n// Your code goes here\n//====================\n\n  discrete_solution.setZero();\n  return discrete_solution;\n};\n/* SAM_LISTING_END_9 */\n\n/* SAM_LISTING_BEGIN_3 */\ndouble computeBoundaryOutputFunctional(\n    const Eigen::VectorXd eta,\n    const std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> &fe_space_p,\n    Eigen::Vector2d d) {\n  double func_val = 0.0;\n  // Pointer to current mesh\n  std::shared_ptr<const lf::mesh::Mesh> mesh_p = fe_space_p->Mesh();\n  // Obtain local->global index mapping for current finite element space\n  const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n\n  // Obtain an array of boolean flags for the edges of the mesh, 'true'\n  // indicates that the edge lies on the boundary\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 1)};\n\n  //====================\n  // Your code goes here\n  //====================\n\n  // Computing value of the functional\n  for (const lf::mesh::Entity *edge : mesh_p->Entities(1)) {\n    //====================\n    // Your code goes here\n    //====================\n  }\n  return func_val;\n};\n/* SAM_LISTING_END_3 */\n\n}  // namespace OutputImpedanceBVP\n", "meta": {"hexsha": "6499ff277cbcf71ed9e11d2b33d29e04dc11e86d", "size": 4199, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/OutputImpedanceBVP/templates/outputimpedancebvp.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/OutputImpedanceBVP/templates/outputimpedancebvp.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/OutputImpedanceBVP/templates/outputimpedancebvp.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3253968254, "max_line_length": 94, "alphanum_fraction": 0.6684924982, "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6297867126276053}}
{"text": "//####### Test module for special functions ####################################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"special functions\"\n\n//Will automatically define a main for this test\n #define BOOST_TEST_DYN_LINK\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\n//Units choice. Not relevant here, but avoids compile-time warning\n#define PXRMP_USE_SI_UNITS\n\n#include \"special_functions.hpp\"\n\nusing namespace picsar::multi_physics;\n\n// ------------- Tests --------------\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-10;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-4;\n\n//Templated tolerance\ntemplate <typename T>\nT tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\n//Test Bessel functions generic\ntemplate<typename T, typename WHATEVER>\nvoid bessel_functions_test(WHATEVER _v, WHATEVER _x, WHATEVER _exp)\n{\n    const T v = static_cast<T>(_v);\n    const T x = static_cast<T>(_x);\n    const T exp = static_cast<T>(_exp);\n\n    T res = k_v(v,x);\n    BOOST_CHECK_SMALL((res-exp)/exp, tolerance<T>());\n}\n\n\n//Test Bessel functions with double precision\nBOOST_AUTO_TEST_CASE( bessel_functions_double_1 )\n{\n    bessel_functions_test<double>(1.0/3.0, 0.5, 0.989031074246724);\n}\n\n//Test Bessel functions with single precision\nBOOST_AUTO_TEST_CASE( bessel_functions_single_1 )\n{\n    bessel_functions_test<float>(1.0/3.0, 0.5, 0.989031074246724);\n}\n\n//Test Bessel functions with double precision\nBOOST_AUTO_TEST_CASE( bessel_functions_double_2 )\n{\n    bessel_functions_test<double>(1.0/3.0, 1.0, 0.438430633441534);\n}\n\n//Test Bessel functions with single precision\nBOOST_AUTO_TEST_CASE( bessel_functions_single_2 )\n{\n    bessel_functions_test<float>(1.0/3.0, 1.0, 0.438430633441534);\n}\n\n//Test Bessel functions with double precision\nBOOST_AUTO_TEST_CASE( bessel_functions_double_3 )\n{\n    bessel_functions_test<double>(1.0/3.0, 2.0, 0.116544961296165);\n}\n\n//Test Bessel functions with single precision\nBOOST_AUTO_TEST_CASE( bessel_functions_single_3 )\n{\n    bessel_functions_test<float>(1.0/3.0, 2.0, 0.116544961296165);\n}\n\n//Test Bessel functions with double precision\nBOOST_AUTO_TEST_CASE( bessel_functions_double_4 )\n{\n    bessel_functions_test<double>(2.0/3.0, 0.5, 1.205930464720336);\n}\n\n//Test Bessel functions with single precision\nBOOST_AUTO_TEST_CASE( bessel_functions_float_4 )\n{\n    bessel_functions_test<float>(2.0/3.0, 0.5, 1.205930464720336);\n}\n\n//Test Bessel functions with double precision\nBOOST_AUTO_TEST_CASE( bessel_functions_double_5 )\n{\n    bessel_functions_test<double>(2.0/3.0, 1.0, 0.494475062104208);\n}\n\n//Test Bessel functions with single precision\nBOOST_AUTO_TEST_CASE( bessel_functions_float_5 )\n{\n    bessel_functions_test<float>(2.0/3.0, 1.0, 0.494475062104208);\n}\n\n//Test Bessel functions with double precision\nBOOST_AUTO_TEST_CASE( bessel_functions_double_6 )\n{\n    bessel_functions_test<double>(2.0/3.0, 2.0, 0.124838927488128);\n}\n\n//Test Bessel functions with single precision\nBOOST_AUTO_TEST_CASE( bessel_functions_float_6 )\n{\n    bessel_functions_test<float>(2.0/3.0, 2.0, 0.124838927488128);\n}\n", "meta": {"hexsha": "1a1893f0e6c207850d44078a2efbc688a2f4284a", "size": 3302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/multi_physics/QED_tests/test_special_functions.cpp", "max_stars_repo_name": "thaisacs/PICSAR", "max_stars_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multi_physics/QED_tests/test_special_functions.cpp", "max_issues_repo_name": "thaisacs/PICSAR", "max_issues_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multi_physics/QED_tests/test_special_functions.cpp", "max_forks_repo_name": "thaisacs/PICSAR", "max_forks_repo_head_hexsha": "1e3840779f478a70417975feecd35814ef92bf9d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0655737705, "max_line_length": 80, "alphanum_fraction": 0.7510599637, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6297867104055321}}
{"text": "//\n//  Copyright Markus Rickert 2008\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include <algorithm>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/bindings/blas/blas.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector2.hpp>\n\nint\nmain(int argc, char** argv)\n{\n\t// a * b' = C ; a' * b = d\n\t{\n\t\tboost::numeric::ublas::vector<double> a(3);\n\t\tfor (std::size_t i = 0; i < a.size(); ++i) a(i) = i;\n\t\tstd::cout << \"a=\" << a << std::endl;\n\t\t\n\t\tboost::numeric::ublas::vector<double> b(3);\n\t\tfor (std::size_t i = 0; i < b.size(); ++i) b(i) = i;\n\t\tstd::cout << \"b=\" << b << std::endl;\n\t\t\n\t\tboost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> c(3, 3);\n\t\tboost::numeric::bindings::blas::gemm(\n\t\t\tboost::numeric::bindings::traits::NO_TRANSPOSE,\n\t\t\tboost::numeric::bindings::traits::TRANSPOSE,\n\t\t\t1.0, a, b, 0.0, c\n\t\t);\n\t\tstd::cout << \"C=\" << c << std::endl;\n\t\t\n\t\tboost::numeric::ublas::vector<double> d(1);\n\t\tboost::numeric::bindings::blas::gemm(\n\t\t\tboost::numeric::bindings::traits::TRANSPOSE,\n\t\t\tboost::numeric::bindings::traits::NO_TRANSPOSE,\n\t\t\t1.0, a, b, 0.0, d\n\t\t);\n\t\tstd::cout << \"d=\" << d << std::endl;\n\t}\n\t\n\tstd::cout << std::endl;\n\t\n\t// a * b' = C ; a' * b = d\n\t{\n\t\tboost::numeric::ublas::bounded_vector<double, 3> a;\n\t\tfor (std::size_t i = 0; i < a.size(); ++i) a(i) = i;\n\t\tstd::cout << \"a=\" << a << std::endl;\n\t\t\n\t\tboost::numeric::ublas::bounded_vector<double, 3> b;\n\t\tfor (std::size_t i = 0; i < b.size(); ++i) b(i) = i;\n\t\tstd::cout << \"b=\" << b << std::endl;\n\t\t\n\t\tboost::numeric::ublas::bounded_matrix<double, 3, 3, boost::numeric::ublas::column_major> c;\n\t\tboost::numeric::bindings::blas::gemm(\n\t\t\tboost::numeric::bindings::traits::NO_TRANSPOSE,\n\t\t\tboost::numeric::bindings::traits::TRANSPOSE,\n\t\t\t1.0, a, b, 0.0, c\n\t\t);\n\t\tstd::cout << \"C=\" << c << std::endl;\n\t\t\n\t\tboost::numeric::ublas::bounded_vector<double, 1> d;\n\t\tboost::numeric::bindings::blas::gemm(\n\t\t\tboost::numeric::bindings::traits::TRANSPOSE,\n\t\t\tboost::numeric::bindings::traits::NO_TRANSPOSE,\n\t\t\t1.0, a, b, 0.0, d\n\t\t);\n\t\tstd::cout << \"d=\" << d << std::endl;\n\t}\n\t\n\tstd::cout << std::endl;\n\t\n\t// A * B = C\n\t{\n\t\tboost::numeric::ublas::bounded_matrix<double, 4, 3, boost::numeric::ublas::column_major> a;\n\t\tfor (std::size_t i = 0; i < a.size1(); ++i) for (std::size_t j = 0; j < a.size2(); ++j) a(i, j) = i * a.size2() + j;\n\t\tstd::cout << \"A=\" << a << std::endl;\n\t\t\n\t\tboost::numeric::ublas::bounded_matrix<double, 3, 4, boost::numeric::ublas::column_major> b;\n\t\tfor (std::size_t i = 0; i < b.size1(); ++i) for (std::size_t j = 0; j < b.size2(); ++j) b(i, j) = i * b.size2() + j;\n\t\tstd::cout << \"B=\" << b << std::endl;\n\t\t\n\t\tboost::numeric::ublas::bounded_matrix<double, 4, 4, boost::numeric::ublas::column_major> c;\n\t\tboost::numeric::bindings::blas::gemm(a, b, c);\n\t\tstd::cout << \"C=\" << c << std::endl;\n\t}\n\t\n\tstd::cout << std::endl;\n\t\n\t// A[0:3;0:2] * B[0:2;0:3] = C\n\t{\n\t\tboost::numeric::ublas::bounded_matrix<double, 4, 3, boost::numeric::ublas::column_major> a;\n\t\tfor (std::size_t i = 0; i < a.size1(); ++i) for (std::size_t j = 0; j < a.size2(); ++j) a(i, j) = i * a.size2() + j;\n\t\tstd::cout << \"A=\" << a << std::endl;\n\t\t\n\t\tboost::numeric::ublas::matrix_range<\n\t\t\tboost::numeric::ublas::bounded_matrix<double, 4, 3, boost::numeric::ublas::column_major>\n\t\t> a2 = boost::numeric::ublas::subrange(a, 0, 3, 0, 2);\n\t\tstd::cout << \"A2=\" << a2 << std::endl;\n\t\t\n\t\tboost::numeric::ublas::bounded_matrix<double, 3, 4, boost::numeric::ublas::column_major> b;\n\t\tfor (std::size_t i = 0; i < b.size1(); ++i) for (std::size_t j = 0; j < b.size2(); ++j) b(i, j) = i * b.size2() + j;\n\t\tstd::cout << \"B=\" << b << std::endl;\n\t\t\n\t\tboost::numeric::ublas::matrix_range<\n\t\t\tboost::numeric::ublas::bounded_matrix<double, 3, 4, boost::numeric::ublas::column_major>\n\t\t> b2 = boost::numeric::ublas::subrange(b, 0, 2, 0, 3);\n\t\tstd::cout << \"B2=\" << b2 << std::endl;\n\t\t\n\t\tboost::numeric::ublas::bounded_matrix<double, 4, 4, boost::numeric::ublas::column_major> c;\n\t\tstd::fill(c.data().begin(), c.data().end(), 0.0);\n\t\tboost::numeric::ublas::matrix_range<\n\t\t\tboost::numeric::ublas::bounded_matrix<double, 4, 4, boost::numeric::ublas::column_major>\n\t\t> c2 = boost::numeric::ublas::subrange(c, 0, 3, 0, 3);\n\t\tboost::numeric::bindings::blas::gemm(a2, b2, c2);\n\t\tstd::cout << \"C2=\" << c2 << std::endl;\n\t\tstd::cout << \"C=\" << c << std::endl;\n\t}\n\t\n\tstd::cout << std::endl;\n\t\n\t// a + b = b ; b - a = b\n\t{\n\t\tboost::numeric::ublas::bounded_vector<double, 3> a;\n\t\tfor (std::size_t i = 0; i < a.size(); ++i) a(i) = i;\n\t\tstd::cout << \"a=\" << a << std::endl;\n\t\t\n\t\tboost::numeric::ublas::bounded_vector<double, 3> b;\n\t\tfor (std::size_t i = 0; i < b.size(); ++i) b(i) = i;\n\t\tstd::cout << \"b=\" << b << std::endl;\n\t\t\n\t\tboost::numeric::bindings::blas::axpy(1.0, a, b);\n\t\tstd::cout << \"b=\" << b << std::endl;\n\t\t\n\t\tboost::numeric::bindings::blas::axpy(-1.0, a, b);\n\t\tstd::cout << \"b=\" << b << std::endl;\n\t}\n\t\n\tstd::cout << std::endl;\n\t\n\t// b + c = c ; c - b = c\n\t{\n\t\tboost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> a(5, 5);\n\t\tfor (std::size_t i = 0; i < a.size1(); ++i) for (std::size_t j = 0; j < a.size2(); ++j) a(i, j) = i * a.size2() + j;\n\t\tstd::cout << \"A=\" << a << std::endl;\n\t\t\n\t\tboost::numeric::ublas::matrix_vector_range<\n\t\t\tboost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major>\n\t\t> b(a, boost::numeric::ublas::range(1, 4), boost::numeric::ublas::range(0, 3));\n\t\tstd::cout << \"b=\" << b << std::endl;\n\t\t\n\t\tboost::numeric::ublas::matrix_vector_slice<\n\t\t\tboost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major>\n\t\t> c(a, boost::numeric::ublas::slice(0, 1, 3), boost::numeric::ublas::slice(3, 0, 3));\n\t\tstd::cout << \"c=\" << c << std::endl;\n\t\t\n\t\tboost::numeric::bindings::blas::axpy(1.0, b, c);\n\t\tstd::cout << \"c=\" << c << std::endl;\n\t\t\n\t\tboost::numeric::bindings::blas::axpy(-1.0, b, c);\n\t\tstd::cout << \"c=\" << c << std::endl;\n\t}\n\t\n\tstd::cout << std::endl;\n\t\n\t// b + c = c ; c - b = c\n\t{\n\t\tboost::numeric::ublas::bounded_matrix<double, 5, 5, boost::numeric::ublas::column_major> a;\n\t\tfor (std::size_t i = 0; i < a.size1(); ++i) for (std::size_t j = 0; j < a.size2(); ++j) a(i, j) = i * a.size2() + j;\n\t\tstd::cout << \"A=\" << a << std::endl;\n\t\t\n\t\tboost::numeric::ublas::matrix_vector_range<\n\t\t\tboost::numeric::ublas::bounded_matrix<double, 5, 5, boost::numeric::ublas::column_major>\n\t\t> b(a, boost::numeric::ublas::range(1, 4), boost::numeric::ublas::range(0, 3));\n\t\tstd::cout << \"b=\" << b << std::endl;\n\t\t\n\t\tboost::numeric::ublas::matrix_vector_slice<\n\t\t\tboost::numeric::ublas::bounded_matrix<double, 5, 5, boost::numeric::ublas::column_major>\n\t\t> c(a, boost::numeric::ublas::slice(0, 1, 3), boost::numeric::ublas::slice(3, 0, 3));\n\t\tstd::cout << \"c=\" << c << std::endl;\n\t\t\n\t\tboost::numeric::bindings::blas::axpy(1.0, b, c);\n\t\tstd::cout << \"c=\" << c << std::endl;\n\t\t\n\t\tboost::numeric::bindings::blas::axpy(-1.0, b, c);\n\t\tstd::cout << \"c=\" << c << std::endl;\n\t}\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "eb356f7c2557ff40b06cc9bfe16532a14a8571fd", "size": 7270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/blas/test/ublas_slice.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/blas/test/ublas_slice.cpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/blas/test/ublas_slice.cpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 36.7171717172, "max_line_length": 118, "alphanum_fraction": 0.5880330124, "num_tokens": 2692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311353, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6297867101656012}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2020, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"poses-precomp.h\"  // Precompiled headers\n\n#include <mrpt/math/TPose2D.h>\n#include <mrpt/math/TPose3D.h>\n#include <mrpt/poses/SO_SE_average.h>\n#include <Eigen/Dense>\n\nusing namespace mrpt;\nusing namespace mrpt::math;\nusing namespace mrpt::poses;\n\n// -----------   SO_average<2> --------------------\nSO_average<2>::SO_average() = default;\n\nvoid SO_average<2>::clear()\n{\n\tm_count = .0;\n\tm_accum_x = m_accum_y = .0;\n}\nvoid SO_average<2>::append(const double orientation_rad)\n{\n\tappend(orientation_rad, 1.0);\n}\nvoid SO_average<2>::append(const double orientation_rad, const double weight)\n{\n\tm_count += weight;\n\tm_accum_x += cos(orientation_rad) * weight;\n\tm_accum_y += sin(orientation_rad) * weight;\n}\ndouble SO_average<2>::get_average() const\n{\n\tASSERT_ABOVE_(m_count, 0);\n\tconst double x = m_accum_x / m_count;\n\tconst double y = m_accum_y / m_count;\n\terrno = 0;\n\tdouble ang = atan2(y, x);\n\tif (errno == EDOM)\n\t{\n\t\tif (enable_exception_on_undeterminate)\n\t\t\tthrow std::runtime_error(\n\t\t\t\t\"[SO_average<2>::get_average()] Undetermined average value\");\n\t\telse\n\t\t\tang = 0;\n\t}\n\treturn ang;\n}\n\n// -----------   SO_average<3> --------------------\nSO_average<3>::SO_average() : m_accum_rot() { clear(); }\nvoid SO_average<3>::clear()\n{\n\tm_count = .0;\n\tm_accum_rot.setZero();\n}\nvoid SO_average<3>::append(const mrpt::math::CMatrixDouble33& M)\n{\n\tappend(M, 1.0);\n}\nvoid SO_average<3>::append(\n\tconst mrpt::math::CMatrixDouble33& M, const double weight)\n{\n\tm_count += weight;\n\tm_accum_rot.asEigen() += weight * M.asEigen();\n}\n// See: eq. (3.7) in \"MEANS AND AVERAGING IN THE GROUP OF ROTATIONS\", MAHER\n// MOAKHER, 2002.\nmrpt::math::CMatrixDouble33 SO_average<3>::get_average() const\n{\n\tASSERT_ABOVE_(m_count, 0);\n\tconst Eigen::Matrix3d MtM = m_accum_rot.transpose() * m_accum_rot.asEigen();\n\n\tEigen::JacobiSVD<Eigen::Matrix3d> svd(MtM, Eigen::ComputeFullU);\n\tconst Eigen::Vector3d vs = svd.singularValues();\n\n\terrno = 0;\n\tconst double d1 = 1.0 / sqrt(vs[0]);\n\tconst double d2 = 1.0 / sqrt(vs[1]);\n\tconst double d3 = mrpt::sign(m_accum_rot.det()) / sqrt(vs[2]);\n\tif (errno != 0)\n\t{\n\t\tif (enable_exception_on_undeterminate)\n\t\t\tthrow std::runtime_error(\n\t\t\t\t\"[SO_average<3>::get_average()] Undetermined average value\");\n\t\telse\n\t\t\treturn mrpt::math::CMatrixDouble33::Identity();\n\t}\n\n\tmrpt::math::CMatrixDouble33 D = mrpt::math::CMatrixDouble33::Zero();\n\tD(0, 0) = d1;\n\tD(1, 1) = d2;\n\tD(2, 2) = d3;\n\treturn mrpt::math::CMatrixDouble33(\n\t\tm_accum_rot.asEigen() * svd.matrixU() * D.asEigen() *\n\t\tsvd.matrixU().transpose());\n}\n\n// -----------   SE_average<2> --------------------\nSE_average<2>::SE_average() : m_rot_part() { clear(); }\nvoid SE_average<2>::clear()\n{\n\tm_count = .0;\n\tm_accum_x = m_accum_y = .0;\n\tm_rot_part.clear();\n}\nvoid SE_average<2>::append(const mrpt::poses::CPose2D& p) { append(p, 1.0); }\nvoid SE_average<2>::append(const mrpt::poses::CPose2D& p, const double weight)\n{\n\tm_count += weight;\n\tm_accum_x += weight * p.x();\n\tm_accum_y += weight * p.y();\n\tm_rot_part.append(p.phi(), weight);\n}\nvoid SE_average<2>::append(const mrpt::math::TPose2D& p, const double weight)\n{\n\tm_count += weight;\n\tm_accum_x += weight * p.x;\n\tm_accum_y += weight * p.y;\n\tm_rot_part.append(p.phi, weight);\n}\nvoid SE_average<2>::get_average(mrpt::poses::CPose2D& ret_mean) const\n{\n\tASSERT_ABOVE_(m_count, 0);\n\tret_mean.x(m_accum_x / m_count);\n\tret_mean.y(m_accum_y / m_count);\n\tconst_cast<SO_average<2>*>(&m_rot_part)->enable_exception_on_undeterminate =\n\t\tthis->enable_exception_on_undeterminate;\n\tret_mean.phi(m_rot_part.get_average());\n}\n\n// -----------   SE_average<3> --------------------\nSE_average<3>::SE_average() : m_rot_part() { clear(); }\nvoid SE_average<3>::clear()\n{\n\tm_count = .0;\n\tm_accum_x = m_accum_y = m_accum_z = .0;\n\tm_rot_part.clear();\n}\nvoid SE_average<3>::append(const mrpt::poses::CPose3D& p) { append(p, 1.0); }\nvoid SE_average<3>::append(const mrpt::poses::CPose3D& p, const double weight)\n{\n\tm_count += weight;\n\tm_accum_x += weight * p.x();\n\tm_accum_y += weight * p.y();\n\tm_accum_z += weight * p.z();\n\tm_rot_part.append(p.getRotationMatrix(), weight);\n}\nvoid SE_average<3>::append(const mrpt::math::TPose3D& p, const double weight)\n{\n\tappend(CPose3D(p), weight);\n}\nvoid SE_average<3>::get_average(mrpt::poses::CPose3D& ret_mean) const\n{\n\tASSERT_ABOVE_(m_count, 0);\n\tret_mean.x(m_accum_x / m_count);\n\tret_mean.y(m_accum_y / m_count);\n\tret_mean.z(m_accum_z / m_count);\n\tconst_cast<SO_average<3>*>(&m_rot_part)->enable_exception_on_undeterminate =\n\t\tthis->enable_exception_on_undeterminate;\n\tret_mean.setRotationMatrix(m_rot_part.get_average());\n}\n", "meta": {"hexsha": "f6b0539b96816cc07448469d56464854fabcd57f", "size": 5181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/poses/src/SO_SE_average.cpp", "max_stars_repo_name": "swt2c/mrpt", "max_stars_repo_head_hexsha": "9b4fd246530ff94bb93f5703e61844c6f67aa0b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/poses/src/SO_SE_average.cpp", "max_issues_repo_name": "swt2c/mrpt", "max_issues_repo_head_hexsha": "9b4fd246530ff94bb93f5703e61844c6f67aa0b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/poses/src/SO_SE_average.cpp", "max_forks_repo_name": "swt2c/mrpt", "max_forks_repo_head_hexsha": "9b4fd246530ff94bb93f5703e61844c6f67aa0b9", "max_forks_repo_licenses": ["BSD-3-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.4764705882, "max_line_length": 80, "alphanum_fraction": 0.6332754295, "num_tokens": 1480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6297867027795888}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_THIRDROOTEPS_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_THIRDROOTEPS_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Thirdrooteps Thirdrooteps (function template)\n\n  Generates the constant \\f$\\sqrt[3]{\\epsilon}\\f$\n\n  @headerref{<boost/simd/constant/thirdrooteps.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Thirdrooteps();\n      @endcode\n\n  2.  @code\n      template<typename T> T Thirdrooteps( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T that evaluates to \\f$\\sqrt[3]{\\epsilon}\\f$.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c T that evaluates to:\n\n  | Type       | double                     | float             |    Integral     |\n  |:-----------|:---------------------------|-------------------|-----------------|\n  | **Values** |   6.055454452393343e-06    |  4.9215667e-03f   |   1             |\n\n  @par Requirements\n  - **T** models Value\n**/\n\n#include <boost/simd/constant/scalar/thirdrooteps.hpp>\n#include <boost/simd/constant/simd/thirdrooteps.hpp>\n\n#endif\n", "meta": {"hexsha": "abef4e5043298a76cf17dcc6f78ac3d764654d67", "size": 1771, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/thirdrooteps.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/thirdrooteps.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/thirdrooteps.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 32.2, "max_line_length": 100, "alphanum_fraction": 0.4952004517, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6297867003175845}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of full_gen_tikhonov class.\n */\n#include \"num_collect/regularization/full_gen_tikhonov.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n#include \"eigen_approx.h\"\n#include \"num_prob_collect/regularization/blur_sine.h\"\n#include \"num_prob_collect/regularization/dense_diff_matrix.h\"\n\nTEST_CASE(\"num_collect::regularization::full_gen_tikhonov\") {\n    using coeff_type = Eigen::MatrixXd;\n    using data_type = Eigen::VectorXd;\n\n    SECTION(\"solve\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 30;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n        const coeff_type reg_mat =\n            num_prob_collect::regularization::dense_diff_matrix<coeff_type>(\n                solution_size);\n\n        num_collect::regularization::full_gen_tikhonov<coeff_type, data_type>\n            full_gen_tikhonov;\n        full_gen_tikhonov.compute(prob.coeff(), prob.data(), reg_mat);\n        Eigen::VectorXd solution;\n        full_gen_tikhonov.solve(0.0, solution);\n\n        REQUIRE_THAT(solution, eigen_approx(prob.solution()));\n    }\n\n    SECTION(\"solve with different parameters\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 30;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n        const coeff_type reg_mat =\n            num_prob_collect::regularization::dense_diff_matrix<coeff_type>(\n                solution_size);\n\n        num_collect::regularization::full_gen_tikhonov<coeff_type, data_type>\n            full_gen_tikhonov;\n        full_gen_tikhonov.compute(prob.coeff(), prob.data(), reg_mat);\n\n        constexpr double param_small = 1e-2;\n        Eigen::VectorXd solution_small;\n        full_gen_tikhonov.solve(param_small, solution_small);\n\n        constexpr double param_large = 1e+2;\n        Eigen::VectorXd solution_large;\n        full_gen_tikhonov.solve(param_large, solution_large);\n\n        REQUIRE((reg_mat * solution_large).squaredNorm() <\n            (reg_mat * solution_small).squaredNorm());\n    }\n\n    SECTION(\"check functions of the internal solver\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 30;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n        const coeff_type reg_mat =\n            num_prob_collect::regularization::dense_diff_matrix<coeff_type>(\n                solution_size);\n\n        num_collect::regularization::full_gen_tikhonov<coeff_type, data_type>\n            full_gen_tikhonov;\n        full_gen_tikhonov.compute(prob.coeff(), prob.data(), reg_mat);\n\n        constexpr double param = 1e-2;\n\n        REQUIRE_THAT(full_gen_tikhonov.singular_values(),\n            eigen_approx(\n                full_gen_tikhonov.internal_solver().singular_values()));\n\n        REQUIRE_THAT(full_gen_tikhonov.residual_norm(param),\n            Catch::Matchers::WithinRel(\n                full_gen_tikhonov.internal_solver().residual_norm(param)));\n        REQUIRE_THAT(full_gen_tikhonov.regularization_term(param),\n            Catch::Matchers::WithinRel(\n                full_gen_tikhonov.internal_solver().regularization_term(\n                    param)));\n\n        REQUIRE_THAT(full_gen_tikhonov.first_derivative_of_residual_norm(param),\n            Catch::Matchers::WithinRel(\n                full_gen_tikhonov.internal_solver()\n                    .first_derivative_of_residual_norm(param)));\n        REQUIRE_THAT(\n            full_gen_tikhonov.first_derivative_of_regularization_term(param),\n            Catch::Matchers::WithinRel(\n                full_gen_tikhonov.internal_solver()\n                    .first_derivative_of_regularization_term(param)));\n\n        REQUIRE_THAT(\n            full_gen_tikhonov.second_derivative_of_residual_norm(param),\n            Catch::Matchers::WithinRel(\n                full_gen_tikhonov.internal_solver()\n                    .second_derivative_of_residual_norm(param)));\n        REQUIRE_THAT(\n            full_gen_tikhonov.second_derivative_of_regularization_term(param),\n            Catch::Matchers::WithinRel(\n                full_gen_tikhonov.internal_solver()\n                    .second_derivative_of_regularization_term(param)));\n\n        REQUIRE_THAT(full_gen_tikhonov.sum_of_filter_factor(param),\n            Catch::Matchers::WithinRel(\n                full_gen_tikhonov.internal_solver().sum_of_filter_factor(\n                    param)));\n\n        REQUIRE(full_gen_tikhonov.data_size() ==\n            full_gen_tikhonov.internal_solver().data_size());\n\n        REQUIRE(full_gen_tikhonov.param_search_region() ==\n            full_gen_tikhonov.internal_solver().param_search_region());\n    }\n\n    SECTION(\"try to solve using reg_coeff without full row rank\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 30;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n        coeff_type reg_mat =\n            num_prob_collect::regularization::dense_diff_matrix<coeff_type>(\n                solution_size);\n        reg_mat.bottomRows(1).setZero();\n\n        num_collect::regularization::full_gen_tikhonov<coeff_type, data_type>\n            full_gen_tikhonov;\n        REQUIRE_THROWS(\n            full_gen_tikhonov.compute(prob.coeff(), prob.data(), reg_mat));\n    }\n\n    SECTION(\"try to solve using same matrices for coeff and reg_coeff\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 3;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n        const auto& reg_mat = prob.coeff();\n\n        num_collect::regularization::full_gen_tikhonov<coeff_type, data_type>\n            full_gen_tikhonov;\n        REQUIRE_THROWS(\n            full_gen_tikhonov.compute(prob.coeff(), prob.data(), reg_mat));\n    }\n}\n", "meta": {"hexsha": "c58ebb2ce807e15dc7db79a541052fd298a56f9c", "size": 6834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/regularization/full_gen_tikhonov_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units/regularization/full_gen_tikhonov_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units/regularization/full_gen_tikhonov_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1686746988, "max_line_length": 80, "alphanum_fraction": 0.679397132, "num_tokens": 1459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.629786699837723}}
{"text": "/**\n * @file\n * @brief NPDE homework TestQuadratureRules\n * @author Erick Schulz, Liaowang Huang (refactoring)\n * @date 08/03/2019, 22/02/2020 (refactoring)\n * @copyright Developed at ETH Zurich\n */\n\n#include \"testquadraturerules.h\"\n\n#include <lf/base/base.h>\n#include <lf/quad/quad.h>\n\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace TestQuadratureRules {\n\ndouble factorial(int i) { return std::tgamma(i + 1); }\n\n/* SAM_LISTING_BEGIN_1 */\nbool testQuadOrderTria(const lf::quad::QuadRule &quad_rule,\n                       unsigned int order) {\n  bool order_isExact = true;  // return variable\n  //====================\n  // Your code goes here\n\n  // STEP 0: Exception handling\n  // mesh shape must match\n  if (quad_rule.RefEl()!= lf::base::RefEl::kTria()){\n    throw \"The quadrature rule must be defined on simplicial cells!\";\n  }\n\n  // STEP 1: obtain the weights and nodes of the quadrature rule\n  Eigen::VectorXd weights_ = quad_rule.Weights();\n  Eigen::MatrixXd nodes_ = quad_rule.Points();    // 2 by # nodes matrix\n\n  // std::cout << \"It is a \" << nodes_.rows() << \" by \" << nodes_.cols() << \" matrix!\" << std::endl;\n\n  Eigen::VectorXd x_coords = nodes_.row(0);   // x-coords of nodes stored in a vec\n  Eigen::VectorXd y_coords = nodes_.row(1);   // y-coords\n\n\n  // STEP 2: compute the weights using the analytic formula\n  // double volume = 0.5; // area of the reference triangle => not required because gets cancelled out in the formula\n\n  double epsilon = 1e-12; // epsilon used as tolerance\n  double exact;     // stores result of the exact integral\n  double approx;    // stores result of the approximated integral using quadrature rule\n\n\n  // helper function for the quadrature rule\n  auto F = [&](int i, int j)-> Eigen::VectorXd { return x_coords.array().pow(i) * y_coords.array().pow(j);};\n\n  for(int i = 0; i < order; ++i){\n    for(int j = 0; j < order - i; ++j){\n\n      // STEP 3: compute the integrals\n\n      exact = (factorial(i) * factorial(j)) / (factorial(i + j + 2));// analytic: exact integral\n      approx = F(i,j).dot(weights_);// numeric:  from quadrature rule\n                                 //           dot product of the 2 vectors as sum\n\n      // STEP 4: test difference\n      // test failed for \"big error\" relative to the value tested\n      if(std::fabs(exact - approx) > std::fabs(exact) * epsilon){\n          return false; // the order is not exact, fails for one test\n      }\n\n    }\n  }\n\n  //====================\n  return order_isExact;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nbool testQuadOrderQuad(const lf::quad::QuadRule &quad_rule,\n                       unsigned int order) {\n  bool order_isExact = true;  // return variable\n\n  //====================\n  // Your code goes here\n\n  // STEP 0: exception handling\n  if(quad_rule.RefEl() != lf::base::RefEl::kQuad()){\n    throw \"Only quadraterial cells are allowed!\";\n  }\n\n  // STEP 1: obtain weights and nodes of the quadrature rule\n  Eigen::VectorXd weights_ = quad_rule.Weights();\n  Eigen::MatrixXd nodes_   = quad_rule.Points();   // 2 by # nodes matrix\n\n  // obtain x_coords and y_coords from nodes_\n  Eigen::VectorXd x_coords = nodes_.row(0);\n  Eigen::VectorXd y_coords = nodes_.row(1);\n\n  // helper function for the numeric formula\n  auto F = [&](int i, int j)-> Eigen::VectorXd { return x_coords.array().pow(i) * y_coords.array().pow(j);};\n\n  double exact, approx;\n  double epsilon = 1e-12;  // define the epsilon for tolerance\n\n  // STEP 2: loop over the possible combis of basis functions\n  for(int i = 0; i < order; ++i){\n      for(int j = 0; j < order; ++j){\n\n        exact = 1. / ((i + 1.)* (j + 1.)); // using the exact formula\n        approx = F(i, j).dot(weights_); // compute using the quad rule\n\n        // STEP 3: Check the equality with tolerance allowed\n        if(std::fabs(exact - approx) >= exact * epsilon){\n            return false;\n        }\n      }\n  }\n\n  //====================\n  return order_isExact;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nunsigned int calcQuadOrder(const lf::quad::QuadRule &quad_rule) {\n  unsigned int maximal_order = quad_rule.Order();\n\n  //====================\n  // Your code goes here\n\n  // case distinction\n  // based on reference element of the quadrature rule\n  const lf::base::RefEl reference  = quad_rule.RefEl();\n\n\n  // CASE 1: on simplicial cells\n  if(reference == lf::base::RefEl::kTria()){\n\n    while(testQuadOrderTria(quad_rule, maximal_order + 1)){\n        // change the condition\n        ++maximal_order;\n    }\n\n  }\n  // CASE 2: on tensor product cells\n  else if (reference == lf::base::RefEl::kQuad()){\n\n    while(testQuadOrderQuad(quad_rule, maximal_order + 1)){\n        // change the condition\n        ++maximal_order;\n    }\n\n  }\n  // default: error handling for exception\n  else{\n    throw \"Only possible tests for mesh with reference elements being simplex or tensor product\";\n  }\n\n\n  //====================\n  return maximal_order;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace TestQuadratureRules\n", "meta": {"hexsha": "18dec58a4059e7cdca759a18c883c112806aeb65", "size": 4998, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/TestQuadratureRules/mysolution/testquadraturerules.cc", "max_stars_repo_name": "youwuyou/NPDECODES", "max_stars_repo_head_hexsha": "c6db4e50476eab37464744797d3b932ab4cdfb44", "max_stars_repo_licenses": ["MIT"], "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/TestQuadratureRules/mysolution/testquadraturerules.cc", "max_issues_repo_name": "youwuyou/NPDECODES", "max_issues_repo_head_hexsha": "c6db4e50476eab37464744797d3b932ab4cdfb44", "max_issues_repo_licenses": ["MIT"], "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/TestQuadratureRules/mysolution/testquadraturerules.cc", "max_forks_repo_name": "youwuyou/NPDECODES", "max_forks_repo_head_hexsha": "c6db4e50476eab37464744797d3b932ab4cdfb44", "max_forks_repo_licenses": ["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.9281437126, "max_line_length": 117, "alphanum_fraction": 0.6262505002, "num_tokens": 1332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6297043257535202}}
{"text": "#include <iostream>\n#include <stdio.h>\n\n#include <Eigen/Dense>\n\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n\nusing namespace boost::numeric;\n\nusing std::cout;\nusing std::endl;\n\n#include \"KalmanFilter.h\"\n\nnamespace openmht {\n\n     KalmanFilter::KalmanFilter()\n     {\n     }\n\n     KalmanFilter::KalmanFilter(const Eigen::MatrixXf &F, \n\t\t\t\tconst Eigen::MatrixXf &B, \n\t\t\t\tconst Eigen::MatrixXf &H, \n\t\t\t\tconst Eigen::MatrixXf &Q, \n\t\t\t\tconst Eigen::MatrixXf &R)\n     {\n\t  setModel(F, B, H, Q, R);\n     }\n\n     int KalmanFilter::setModel(const Eigen::MatrixXf &F, \n\t\t\t\tconst Eigen::MatrixXf &B, \n\t\t\t\tconst Eigen::MatrixXf &H, \n\t\t\t\tconst Eigen::MatrixXf &Q, \n\t\t\t\tconst Eigen::MatrixXf &R)\n     {\n\t  F_ = F;\n\t  B_ = B;\n\t  H_ = H;\n          Q_ = Q;\n          R_ = R;\n\t  eye_ = Eigen::MatrixXf::Identity(F.rows(), F.cols());\n\n\t  return 0;\n     }\n\n     int KalmanFilter::init(const Eigen::MatrixXf &x0, \n\t\t\t    const Eigen::MatrixXf &P0)\n     {\n\t  x_ = x0;\n\t  P_ = P0;\n\t  return 0;\n     }\n\n     int KalmanFilter::predict(const Eigen::MatrixXf &u)\n     {\n          x_ = F_*x_ + B_*u;\n          P_ = F_*P_*F_.transpose() + Q_;              \n          \n\t  return 0;\n     }\n     \n     int KalmanFilter::update(const Eigen::MatrixXf &z)\n     {                    \n\t  K_ = P_*H_.transpose()*(H_*P_*H_.transpose() + R_).inverse();\n\t  x_ = x_ + K_*(z - H_*x_);\n          P_ = (eye_ - K_*H_)*P_;\n\t  return 0;\n     }\n     \n     Eigen::MatrixXf KalmanFilter::state() const\n     {\n\t  return x_;\n     }\n\n     void KalmanFilter::set_state(const Eigen::MatrixXf &x)\n     {\n          x_ = x;\n     }\n     \n     Eigen::MatrixXf KalmanFilter::covariance() const\n     {\n\t  return P_;\n     }\n\n     Ellipse KalmanFilter::error_ellipse(double confidence)\n     {\n          if (confidence < 0) {\n               confidence = 0;\n          } else if (confidence > 1) {\n               confidence = 1;\n          }\n          \n          // Compute the eigenvectors and eigenvalues of the measurement\n          // covariance matrix\n          Eigen::MatrixXf B = this->meas_covariance();          \n          Eigen::EigenSolver<Eigen::MatrixXf> es(B);\n          Eigen::EigenSolver< Eigen::MatrixXf >::EigenvectorsType evecs = es.eigenvectors();\n          Eigen::EigenSolver< Eigen::MatrixXf >::EigenvectorsType evalues = es.eigenvalues();\n          \n          // Find the larger (1st) eigenvalue / eigenvector\n          double eig0 = evalues(0).real();\n          double eig1 = evalues(1).real();\n\n          double lambda0, lambda1;\n          int eig_1st_index;\n          if (eig0 >= eig1) {\n               eig_1st_index = 0;\n               lambda0 = eig0;\n               lambda1 = eig1;\n          } else {\n               eig_1st_index = 1;\n               lambda0 = eig1;\n               lambda1 = eig0;\n          }\n          \n          // Determine the angle of the ellipse\n          double q0x = evecs.col(eig_1st_index)(0).real();\n          double q0y = evecs.col(eig_1st_index)(1).real();\n          double angle = 180.0/3.14159265359 * atan2(q0y,q0x);                 \n          \n          double p = confidence; // 0.0 - 1.0\n\n          // The major and minor axes of the ellipse are stored as \"half\" of\n          // the major axes because cv::ellipse accepts half sizes for input\n          double r0 = sqrt(-2.0*log(1.0-p/1.00)*lambda0) / 2.0;\n          double r1 = sqrt(-2.0*log(1.0-p/1.00)*lambda1) / 2.0;\n          \n          Eigen::Vector2d center(x_(0,0),x_(1,0));\n          //cv::Point2d center(160,120);\n          return Ellipse(center, Eigen::Vector2d(r0,r1), angle);\n     }\n\n     bool KalmanFilter::is_within_region(Eigen::MatrixXf Zm, double std) \n     {\n          Eigen::MatrixXf B = this->meas_covariance();\n          Eigen::MatrixXf diff = Zm - H_*x_;\n          Eigen::MatrixXf dist_mat = diff.transpose()*B.inverse()*diff;          \n          double dist = dist_mat(0,0);\n          //if (dist <= pow(nsigma,2)) {\n          if (dist <= std) {\n               return true;\n          } else {\n               return false;\n          }\n     }\n\n     Eigen::MatrixXf KalmanFilter::meas_covariance()\n     {          \n          return H_ * P_ * H_.transpose() + R_;\n     }\n\n     void KalmanFilter::print()\n     {\n          cout << \"State: \" << endl << x_ << endl;\n          cout << \"Covar: \" << endl << P_ << endl;\n          cout << \"R: \" << endl << R_ << endl;\n     }\n}\n\n", "meta": {"hexsha": "ab0a045026685ce3678f7442c5574a5818fd4a2b", "size": 4351, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filter/KalmanFilter.cpp", "max_stars_repo_name": "SyllogismRXS/openmht", "max_stars_repo_head_hexsha": "a29ae04907f88618a938a5eb58a950b0efcde849", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2017-01-09T12:21:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-12T16:50:02.000Z", "max_issues_repo_path": "src/filter/KalmanFilter.cpp", "max_issues_repo_name": "SyllogismRXS/openmht", "max_issues_repo_head_hexsha": "a29ae04907f88618a938a5eb58a950b0efcde849", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-05-27T14:55:44.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-27T14:55:44.000Z", "max_forks_repo_path": "src/filter/KalmanFilter.cpp", "max_forks_repo_name": "SyllogismRXS/openmht", "max_forks_repo_head_hexsha": "a29ae04907f88618a938a5eb58a950b0efcde849", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-12-09T15:52:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T14:02:06.000Z", "avg_line_length": 27.0248447205, "max_line_length": 93, "alphanum_fraction": 0.5168926684, "num_tokens": 1259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6297043050972827}}
{"text": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_REFINE_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_REFINE_RSQRT_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/detail/traits.hpp>\n#include <boost/simd/function/fnms.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/three.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD_IF( refine_rsqrt_\n                            , (typename T, typename X)\n                            , (detail::is_native<X>)\n                            , bd::cpu_\n                            , bs::pack_<bd::floating_<T>,X>\n                            , bs::pack_<bd::floating_<T>,X>\n                            )\n  {\n    BOOST_FORCEINLINE T operator()(T const& a0, T const& x) const BOOST_NOEXCEPT\n    {\n      // Newton-Raphson\n      //      return fma( fnms(a0, sqr(x), One<T>()), x*Half<T>(), x);\n      return x * Half<T>() * fnms(a0, sqr(x), Three<T>());\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "5726fd6c9ba61847ae90327efac798c50a17749b", "size": 1574, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/refine_rsqrt.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/simd/function/refine_rsqrt.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/simd/function/refine_rsqrt.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 35.7727272727, "max_line_length": 100, "alphanum_fraction": 0.5438373571, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.6296994361485617}}
{"text": "// A program to read xyz point set (position) and write off file with CGAL\n// Visualization with Open3D in python\n// Source: https://doc.cgal.org/latest/Advancing_front_surface_reconstruction/index.html#Chapter_Advancing_Front_Surface_Reconstruction\n\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Advancing_front_surface_reconstruction.h>\n#include <CGAL/tuple.h>\n#include <boost/lexical_cast.hpp>\ntypedef CGAL::Simple_cartesian<double> K;\ntypedef K::Point_3  Point_3;\ntypedef std::array<std::size_t,3> Facet;\nnamespace std {\n  std::ostream&\n  operator<<(std::ostream& os, const Facet& f)\n  {\n    os << \"3 \" << f[0] << \" \" << f[1] << \" \" << f[2];\n    return os;\n  }\n}\n\nstruct Perimeter {\n  double bound;\n  Perimeter(double bound)\n    : bound(bound)\n  {}\n  template <typename AdvancingFront, typename Cell_handle>\n  double operator() (const AdvancingFront& adv, Cell_handle& c,\n                     const int& index) const\n  {\n    // bound == 0 is better than bound < infinity\n    // as it avoids the distance computations\n    if(bound == 0){\n      return adv.smallest_radius_delaunay_sphere (c, index);\n    }\n    // If perimeter > bound, return infinity so that facet is not used\n    double d  = 0;\n    d = sqrt(squared_distance(c->vertex((index+1)%4)->point(),\n                              c->vertex((index+2)%4)->point()));\n    if(d>bound) return adv.infinity();\n    d += sqrt(squared_distance(c->vertex((index+2)%4)->point(),\n                               c->vertex((index+3)%4)->point()));\n    if(d>bound) return adv.infinity();\n    d += sqrt(squared_distance(c->vertex((index+1)%4)->point(),\n                               c->vertex((index+3)%4)->point()));\n    if(d>bound) return adv.infinity();\n    // Otherwise, return usual priority value: smallest radius of\n    // delaunay sphere\n    return adv.smallest_radius_delaunay_sphere (c, index);\n  }\n};\n\nint main(int argc, char* argv[])\n{\n  std::ifstream in((argc>1)?argv[1]:\"data/atoms.xyz\");\n  double per = (argc>2)?boost::lexical_cast<double>(argv[2]):0;\n  std::vector<Point_3> points;\n  std::vector<Facet> facets;\n  std::string header;\n  in >> header;\n  std::istream_iterator<Point_3> in_points_begin(in);\n  std::istream_iterator<Point_3> in_points_end;\n  std::copy(in_points_begin, in_points_end, std::back_inserter(points));\n  Perimeter perimeter(per);\n  CGAL::advancing_front_surface_reconstruction(points.begin(),\n                                               points.end(),\n                                               std::back_inserter(facets),\n                                               perimeter);\n  std::ofstream outoff;\n  outoff.open (\"data/atoms_CGAL.off\");\n  outoff << \"OFF\\n\" << points.size() << \" \" << facets.size() << \" 0\\n\";\n  std::copy(points.begin(),\n            points.end(),\n            std::ostream_iterator<Point_3>(outoff, \"\\n\"));\n  std::copy(facets.begin(),\n            facets.end(),\n            std::ostream_iterator<Facet>(outoff, \"\\n\"));\n  return 0;\n}\n", "meta": {"hexsha": "032bfa91049cad8a33cd1706796fd3a9ee09ae87", "size": 3009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CGAL-5.0.3/surface_reconstruction/src/main.cpp", "max_stars_repo_name": "pranjal-s/cpp17", "max_stars_repo_head_hexsha": "04b5278ff4d754d6e62f955d49bddf6509f86e73", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CGAL-5.0.3/surface_reconstruction/src/main.cpp", "max_issues_repo_name": "pranjal-s/cpp17", "max_issues_repo_head_hexsha": "04b5278ff4d754d6e62f955d49bddf6509f86e73", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CGAL-5.0.3/surface_reconstruction/src/main.cpp", "max_forks_repo_name": "pranjal-s/cpp17", "max_forks_repo_head_hexsha": "04b5278ff4d754d6e62f955d49bddf6509f86e73", "max_forks_repo_licenses": ["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.6951219512, "max_line_length": 135, "alphanum_fraction": 0.6171485543, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6296994267712012}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file    CameraResectioning.cpp\n * @brief   An example of gtsam for solving the camera resectioning problem\n * @author  Duy-Nguyen Ta\n * @date    Aug 23, 2011\n */\n\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/geometry/PinholeCamera.h>\n#include <gtsam/geometry/Cal3_S2.h>\n#include <boost/make_shared.hpp>\n\nusing namespace gtsam;\nusing namespace gtsam::noiseModel;\nusing symbol_shorthand::X;\n\n/**\n * Unary factor on the unknown pose, resulting from meauring the projection of\n * a known 3D point in the image\n */\nclass ResectioningFactor: public NoiseModelFactor1<Pose3> {\n  typedef NoiseModelFactor1<Pose3> Base;\n\n  Cal3_S2::shared_ptr K_; ///< camera's intrinsic parameters\n  Point3 P_;              ///< 3D point on the calibration rig\n  Point2 p_;              ///< 2D measurement of the 3D point\n\npublic:\n\n  /// Construct factor given known point P and its projection p\n  ResectioningFactor(const SharedNoiseModel& model, const Key& key,\n      const Cal3_S2::shared_ptr& calib, const Point2& p, const Point3& P) :\n      Base(model, key), K_(calib), P_(P), p_(p) {\n  }\n\n  /// evaluate the error\n  virtual Vector evaluateError(const Pose3& pose, boost::optional<Matrix&> H =\n      boost::none) const {\n    PinholeCamera<Cal3_S2> camera(pose, *K_);\n    return camera.project(P_, H, boost::none, boost::none) - p_;\n  }\n};\n\n/*******************************************************************************\n * Camera: f = 1, Image: 100x100, center: 50, 50.0\n * Pose (ground truth): (Xw, -Yw, -Zw, [0,0,2.0]')\n * Known landmarks:\n *    3D Points: (10,10,0) (-10,10,0) (-10,-10,0) (10,-10,0)\n * Perfect measurements:\n *    2D Point:  (55,45)   (45,45)    (45,55)     (55,55)\n *******************************************************************************/\nint main(int argc, char* argv[]) {\n  /* read camera intrinsic parameters */\n  Cal3_S2::shared_ptr calib(new Cal3_S2(1, 1, 0, 50, 50));\n\n  /* 1. create graph */\n  NonlinearFactorGraph graph;\n\n  /* 2. add factors to the graph */\n  // add measurement factors\n  SharedDiagonal measurementNoise = Diagonal::Sigmas(Vector2(0.5, 0.5));\n  boost::shared_ptr<ResectioningFactor> factor;\n  graph.emplace_shared<ResectioningFactor>(measurementNoise, X(1), calib,\n          Point2(55, 45), Point3(10, 10, 0));\n  graph.emplace_shared<ResectioningFactor>(measurementNoise, X(1), calib,\n          Point2(45, 45), Point3(-10, 10, 0));\n  graph.emplace_shared<ResectioningFactor>(measurementNoise, X(1), calib,\n          Point2(45, 55), Point3(-10, -10, 0));\n  graph.emplace_shared<ResectioningFactor>(measurementNoise, X(1), calib,\n          Point2(55, 55), Point3(10, -10, 0));\n\n  /* 3. Create an initial estimate for the camera pose */\n  Values initial;\n  initial.insert(X(1),\n      Pose3(Rot3(1, 0, 0, 0, -1, 0, 0, 0, -1), Point3(0, 0, 2)));\n\n  /* 4. Optimize the graph using Levenberg-Marquardt*/\n  Values result = LevenbergMarquardtOptimizer(graph, initial).optimize();\n  result.print(\"Final result:\\n\");\n\n  return 0;\n}\n", "meta": {"hexsha": "b124180983249ff977db8615473d210c8d431548", "size": 3424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/CameraResectioning.cpp", "max_stars_repo_name": "kvmanohar22/gtsam", "max_stars_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-08-13T20:25:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T22:24:43.000Z", "max_issues_repo_path": "examples/CameraResectioning.cpp", "max_issues_repo_name": "kvmanohar22/gtsam", "max_issues_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-21T09:54:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-21T09:54:08.000Z", "max_forks_repo_path": "examples/CameraResectioning.cpp", "max_forks_repo_name": "kvmanohar22/gtsam", "max_forks_repo_head_hexsha": "8194b931fe07fb1bd346cdcf116a35f9c4e208ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T20:46:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T20:46:15.000Z", "avg_line_length": 36.0421052632, "max_line_length": 81, "alphanum_fraction": 0.6150700935, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6296630603593683}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2020 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <gudhi/Flag_complex_edge_collapser.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n#include <gudhi/distance_functions.h>\n#include <gudhi/Points_off_io.h>\n#include <gudhi/graph_simplicial_complex.h>\n\n#include <boost/range/adaptor/transformed.hpp>\n\n#include<utility>  // for std::pair\n#include<vector>\n#include<tuple>\n\n// Types definition\n\nusing Simplex_tree = Gudhi::Simplex_tree<>;\nusing Filtration_value = Simplex_tree::Filtration_value;\nusing Vertex_handle = Simplex_tree::Vertex_handle;\nusing Point = std::vector<Filtration_value>;\nusing Vector_of_points = std::vector<Point>;\n\nusing Proximity_graph = Gudhi::Proximity_graph<Simplex_tree>;\n\nusing Field_Zp = Gudhi::persistent_cohomology::Field_Zp;\nusing Persistent_cohomology = Gudhi::persistent_cohomology::Persistent_cohomology<Simplex_tree, Field_Zp>;\n\nusing Persistence_interval = std::tuple<int, Filtration_value, Filtration_value>;\n/*\n * Compare two intervals by dimension, then by length.\n */\nstruct cmp_intervals_by_length {\n  explicit cmp_intervals_by_length(Simplex_tree * sc)\n      : sc_(sc) { }\n\n  template<typename Persistent_interval>\n  bool operator()(const Persistent_interval & p1, const Persistent_interval & p2) {\n    return (sc_->filtration(get < 1 > (p1)) - sc_->filtration(get < 0 > (p1))\n            > sc_->filtration(get < 1 > (p2)) - sc_->filtration(get < 0 > (p2)));\n  }\n  Simplex_tree* sc_;\n};\n\nstd::vector<Persistence_interval> get_persistence_intervals(Simplex_tree& st, int ambient_dim) {\n  std::vector<Persistence_interval> persistence_intervals;\n  st.expansion(ambient_dim);\n  \n  // Sort the simplices in the order of the filtration\n  st.initialize_filtration();\n  // Compute the persistence diagram of the complex\n  Persistent_cohomology pcoh(st);\n  // initializes the coefficient field for homology - must be a prime number\n  int p = 11;\n  pcoh.init_coefficients(p);\n\n  // Default min_interval_length = 0.\n  pcoh.compute_persistent_cohomology();\n  // Custom sort and output persistence\n  cmp_intervals_by_length cmp(&st);\n  auto persistent_pairs = pcoh.get_persistent_pairs();\n  std::sort(std::begin(persistent_pairs), std::end(persistent_pairs), cmp);\n  for (auto pair : persistent_pairs) {\n    persistence_intervals.emplace_back(st.dimension(get<0>(pair)),\n                                       st.filtration(get<0>(pair)),\n                                       st.filtration(get<1>(pair)));\n  }\n  return persistence_intervals;\n}\n\nint main(int argc, char* argv[]) {\n  if (argc != 3) {\n    std::cerr << \"This program requires an OFF file and minimal threshold value as parameter\\n\";\n    std::cerr << \"For instance: ./Edge_collapse_conserve_persistence ../../data/points/tore3D_300.off 1.\\n\";\n    exit(-1);  // ----- >>\n  }\n\n  std::string off_file_points {argv[1]};\n  double threshold {atof(argv[2])};\n\n  Gudhi::Points_off_reader<Point> off_reader(off_file_points);\n  if (!off_reader.is_valid()) {\n    std::cerr << \"Unable to read file \" << off_file_points << \"\\n\";\n    exit(-1);  // ----- >>\n  }\n\n  Vector_of_points point_vector = off_reader.get_point_cloud();\n  if (point_vector.size() <= 0) {\n    std::cerr << \"Empty point cloud.\" << std::endl;\n    exit(-1);  // ----- >>\n  }\n\n  Proximity_graph proximity_graph = Gudhi::compute_proximity_graph<Simplex_tree>(off_reader.get_point_cloud(),\n                                                                                 threshold,\n                                                                                 Gudhi::Euclidean_distance());\n\n  if (num_edges(proximity_graph) <= 0) {\n    std::cerr << \"Total number of egdes are zero.\" << std::endl;\n    exit(-1);\n  }\n\n  int ambient_dim = point_vector[0].size();\n\n  // ***** Simplex tree from a flag complex built after collapse *****\n  auto remaining_edges = Gudhi::collapse::flag_complex_collapse_edges(\n    boost::adaptors::transform(edges(proximity_graph), [&](auto&&edge){\n      return std::make_tuple(static_cast<Vertex_handle>(source(edge, proximity_graph)),\n                             static_cast<Vertex_handle>(target(edge, proximity_graph)),\n                             get(Gudhi::edge_filtration_t(), proximity_graph, edge));\n      })\n  );\n\n  Simplex_tree stree_from_collapse;\n  for (Vertex_handle vertex = 0; static_cast<std::size_t>(vertex) < point_vector.size(); vertex++) {\n    // insert the vertex with a 0. filtration value just like a Rips\n    stree_from_collapse.insert_simplex({vertex}, 0.);\n  }\n  for (auto remaining_edge : remaining_edges) {\n    stree_from_collapse.insert_simplex({std::get<0>(remaining_edge), std::get<1>(remaining_edge)},\n                                       std::get<2>(remaining_edge));\n  }\n\n  std::vector<Persistence_interval> persistence_intervals_from_collapse = get_persistence_intervals(stree_from_collapse, ambient_dim);\n\n  // ***** Simplex tree from the complete flag complex *****\n  Simplex_tree stree_wo_collapse;\n  stree_wo_collapse.insert_graph(proximity_graph);\n\n  std::vector<Persistence_interval> persistence_intervals_wo_collapse = get_persistence_intervals(stree_wo_collapse, ambient_dim);\n\n  // ***** Comparison *****\n  if (persistence_intervals_wo_collapse.size() != persistence_intervals_from_collapse.size()) {\n    std::cerr << \"Number of persistence pairs with    collapse is \" << persistence_intervals_from_collapse.size() << std::endl;\n    std::cerr << \"Number of persistence pairs without collapse is \" << persistence_intervals_wo_collapse.size()   << std::endl;\n    exit(-1);\n  }\n\n  int return_value = 0;\n  auto ppwoc_ptr = persistence_intervals_wo_collapse.begin();\n  for (auto ppfc: persistence_intervals_from_collapse) {\n    if (ppfc != *ppwoc_ptr) {\n      return_value++;\n      std::cerr << \"Without collapse: \"\n                << std::get<0>(*ppwoc_ptr) << \" \" << std::get<1>(*ppwoc_ptr) << \" \" << std::get<2>(*ppwoc_ptr)\n                << \" - With collapse: \"\n                << std::get<0>(ppfc) << \" \" << std::get<1>(ppfc) << \" \" << std::get<2>(ppfc) << std::endl;\n    }\n    ppwoc_ptr++;\n  }\n  return return_value;\n}\n", "meta": {"hexsha": "b2c55e7af939cb6eab0b1e61f0e02fa3639e8b0c", "size": 6383, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Collapse/example/edge_collapse_conserve_persistence.cpp", "max_stars_repo_name": "m0baxter/gudhi-devel", "max_stars_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Collapse/example/edge_collapse_conserve_persistence.cpp", "max_issues_repo_name": "m0baxter/gudhi-devel", "max_issues_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Collapse/example/edge_collapse_conserve_persistence.cpp", "max_forks_repo_name": "m0baxter/gudhi-devel", "max_forks_repo_head_hexsha": "6e14ef1f31e09f3875316440303450ff870d9881", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 39.89375, "max_line_length": 134, "alphanum_fraction": 0.6688077706, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.629663051571246}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include \"gtest/gtest.h\"\n#include \"solvers/bfgs.hpp\"\n\nnamespace bfgs_test {\n\ntemplate <typename Mat>\nbool is_posdef(Mat H)\n{\n    Eigen::EigenSolver<Mat> eigensolver(H);\n    for (int i = 0; i < eigensolver.eigenvalues().rows(); i++) {\n        double v = eigensolver.eigenvalues()(i).real();\n        if (v <= 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\nTEST(BFGSTestCase, Test2D_posdef) {\n    using Scalar = double;\n    using Mat = Eigen::Matrix<Scalar, 2, 2>;\n    using Vec = Eigen::Matrix<Scalar, 2, 1>;\n\n    Vec step, delta_grad;\n    Mat H; // true constant hessian;\n    H << 2, 0,\n         0, 1;\n    Mat B = Mat::Identity();\n\n    for (int i = 0; i < 10; i++) {\n        // do some random steps\n        step = {sin(i), cos(i)};\n\n        delta_grad = H*step;\n        BFGS_update(B, step, delta_grad);\n\n        EXPECT_TRUE(is_posdef(B));\n    }\n\n    EXPECT_TRUE(B.isApprox(H, 1e-3));\n}\n\nTEST(BFGSTestCase, Test2D_indefinite) {\n    using Scalar = double;\n    using Mat = Eigen::Matrix<Scalar, 2, 2>;\n    using Vec = Eigen::Matrix<Scalar, 2, 1>;\n\n    Vec step, delta_grad;\n    Mat H; // true constant hessian;\n    H << 2, 0,\n         0, -1;\n    Mat B = Mat::Identity();\n\n    for (int i = 0; i < 10; i++) {\n        // do some random steps\n        step = {sin(i), cos(i)};\n\n        delta_grad = H*step;\n        BFGS_update(B, step, delta_grad);\n\n        EXPECT_TRUE(is_posdef(B));\n    }\n}\n\n#if 0 // suspended for now, see issue #13\nTEST(BFGSTestCase, TestSmallStep) {\n    using Scalar = float;\n    using Mat = Eigen::Matrix<Scalar, 2, 2>;\n    using Vec = Eigen::Matrix<Scalar, 2, 1>;\n\n    Vec step, y;\n    Mat B;\n\n    B << 418.112, 1213, 1213, 3522.27;\n    EXPECT_TRUE(is_posdef(B));\n    step << -1.2659e-06, 1.25816e-06;\n    y << -0.00963563, -0.00957048;\n    BFGS_update(B, step, y);\n    EXPECT_TRUE(is_posdef(B));\n}\n#endif\n\n} // namespace bfgs_test\n", "meta": {"hexsha": "3bb964da032ab9a96b1c43f39e76975dbeaedf41", "size": 1920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/bfgs_test.cpp", "max_stars_repo_name": "nuft/sqp_solver", "max_stars_repo_head_hexsha": "7d059a717bb649d63ab27e4d3ec967b42a8b071c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2019-10-16T08:05:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T04:51:20.000Z", "max_issues_repo_path": "tests/bfgs_test.cpp", "max_issues_repo_name": "likping/sqp_solver", "max_issues_repo_head_hexsha": "7d059a717bb649d63ab27e4d3ec967b42a8b071c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-19T19:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-16T09:18:04.000Z", "max_forks_repo_path": "tests/bfgs_test.cpp", "max_forks_repo_name": "likping/sqp_solver", "max_forks_repo_head_hexsha": "7d059a717bb649d63ab27e4d3ec967b42a8b071c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-10-18T17:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:07:22.000Z", "avg_line_length": 22.3255813953, "max_line_length": 64, "alphanum_fraction": 0.5703125, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545425, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6296630468074373}}
{"text": "#include <blitz/array.h>\n\nusing namespace blitz;\n\nint main()\n{\n    Array<int,2> A(4,5,FortranArray<2>());\n    firstIndex i;\n    secondIndex j;\n    A = 10*i + j;\n\n    cout << \"A = \" << A << endl;\n\n    Array<float,1> B(20);\n    B = exp(-i/100.);\n    \n    cout << \"B = \" << endl << B << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "3423fbbd2901b74db433528b5e91a1582f53a432", "size": 308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/doc/examples/output.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/output.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/output.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": 14.0, "max_line_length": 42, "alphanum_fraction": 0.487012987, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6296630457124976}}
{"text": "/**\n * @file GPlotDesignerTest.cpp\n */\n\n/********************************************************************************\n *\n * This file is part of the Geneva library collection. The following license\n * applies to this file:\n *\n * ------------------------------------------------------------------------------\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ------------------------------------------------------------------------------\n *\n * Note that other files in the Geneva library collection may use a different\n * license. Please see the licensing information in each file.\n *\n ********************************************************************************\n *\n * Geneva was started by Dr. R\u00fcdiger Berlich and was later maintained together\n * with Dr. Ariel Garcia under the auspices of Gemfony scientific. For further\n * information on Gemfony scientific, see http://www.gemfomy.eu .\n *\n * The majority of files in Geneva was released under the Apache license v2.0\n * in February 2020.\n *\n * See the NOTICE file in the top-level directory of the Geneva library\n * collection for a list of contributors and copyright information.\n *\n ********************************************************************************/\n\n// Standard headers go here\n#include <cmath>\n#include <iostream>\n\n// Boost headers go here\n#include <boost/math/constants/constants.hpp>\n\n// Geneva headers go here\n#include \"common/GPlotDesigner.hpp\"\n\nusing namespace Gem::Common;\n\nint main(int argc, char** argv) {\n\tstd::tuple<double,double> minMaxX(-boost::math::constants::pi<double>(),boost::math::constants::pi<double>());\n\tstd::tuple<double,double> minMaxY(-boost::math::constants::pi<double>(),boost::math::constants::pi<double>());\n\n\tstd::shared_ptr<GGraph2D> gsin_ptr(new GGraph2D());\n\tgsin_ptr->setPlotMode(Gem::Common::graphPlotMode::SCATTER);\n\tgsin_ptr->setPlotLabel(\"Sine and cosine functions, plotted through TGraph\");\n\tgsin_ptr->setXAxisLabel(\"x\");\n\tgsin_ptr->setYAxisLabel(\"sin(x) vs. cos(x)\");\n\n\tstd::shared_ptr<GGraph2D> gcos_ptr(new GGraph2D());\n\tgcos_ptr->setPlotMode(Gem::Common::graphPlotMode::SCATTER);\n\tgcos_ptr->setPlotLabel(\"A cosine function, plotted through TGraph\");\n\tgcos_ptr->setXAxisLabel(\"x\");\n\tgcos_ptr->setYAxisLabel(\"cos(x)\");\n\n\tstd::shared_ptr<GGraph2D> gcos_ptr_2(new GGraph2D());\n\tgcos_ptr_2->setPlotMode(Gem::Common::graphPlotMode::SCATTER);\n\tgsin_ptr->registerSecondaryPlotter(gcos_ptr_2);\n\n\tfor(std::size_t i=0; i<1000; i++) {\n\t\tdouble x = 2*boost::math::constants::pi<double>()*double(i)/1000. - boost::math::constants::pi<double>();\n\n\t\t(*gsin_ptr) & std::tuple<double, double>(x, sin(x));\n\t\t(*gcos_ptr) & std::tuple<double, double>(x, cos(x));\n\t\t(*gcos_ptr_2) & std::tuple<double, double>(x, cos(x));\n\t}\n\n\tstd::shared_ptr<GFunctionPlotter1D> gsin_plotter_1D_ptr(new GFunctionPlotter1D(\"sin(x)\", minMaxX));\n\tgsin_plotter_1D_ptr->setPlotLabel(\"A sine function, plotted through TF1\");\n\tgsin_plotter_1D_ptr->setXAxisLabel(\"x\");\n\tgsin_plotter_1D_ptr->setYAxisLabel(\"sin(x)\");\n\n\tstd::shared_ptr<GFunctionPlotter1D> gcos_plotter_1D_ptr(new GFunctionPlotter1D(\"cos(x)\", minMaxX));\n\tgcos_plotter_1D_ptr->setPlotLabel(\"A cosine function, plotted through TF1\");\n\tgcos_plotter_1D_ptr->setXAxisLabel(\"x\");\n\tgcos_plotter_1D_ptr->setYAxisLabel(\"cos(x)\");\n\n\tstd::shared_ptr<GFunctionPlotter2D> schwefel_plotter_2D_ptr(new GFunctionPlotter2D(\"-0.5*(x*sin(sqrt(abs(x))) + y*sin(sqrt(abs(y))))\", minMaxX, minMaxY));\n\tschwefel_plotter_2D_ptr->setPlotLabel(\"The Schwefel function\");\n\tschwefel_plotter_2D_ptr->setXAxisLabel(\"x\");\n\tschwefel_plotter_2D_ptr->setYAxisLabel(\"y\");\n\tschwefel_plotter_2D_ptr->setYAxisLabel(\"Schwefel function\");\n\tschwefel_plotter_2D_ptr->setDrawingArguments(\"surf1\");\n\n\tstd::shared_ptr<GFunctionPlotter2D> noisyParabola_plotter_2D_ptr(new GFunctionPlotter2D(\"(cos(x^2+y^2) + 2)*(x^2+y^2)\", minMaxX, minMaxY));\n\tnoisyParabola_plotter_2D_ptr->setPlotLabel(\"The noisy parabola\");\n\tnoisyParabola_plotter_2D_ptr->setXAxisLabel(\"x\");\n\tnoisyParabola_plotter_2D_ptr->setYAxisLabel(\"y\");\n\tnoisyParabola_plotter_2D_ptr->setYAxisLabel(\"Noisy parabola\");\n\tnoisyParabola_plotter_2D_ptr->setDrawingArguments(\"surf1\");\n\n\tGPlotDesigner gpd(\"Sine and cosine and 2D-functions\", 2,3);\n\n\tgpd.setCanvasDimensions(1200,1400);\n\tgpd.registerPlotter(gsin_ptr);\n\tgpd.registerPlotter(gcos_ptr);\n\tgpd.registerPlotter(gsin_plotter_1D_ptr);\n\tgpd.registerPlotter(gcos_plotter_1D_ptr);\n\tgpd.registerPlotter(schwefel_plotter_2D_ptr);\n\tgpd.registerPlotter(noisyParabola_plotter_2D_ptr);\n\n\tgpd.writeToFile(\"result.C\");\n}\n", "meta": {"hexsha": "41a277d6733a883b7a203b4ca70cd0e6df60ba02", "size": 5019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/common/ManualTests/GPlotDesignerTest/GPlotDesignerTest.cpp", "max_stars_repo_name": "denisbertini/geneva", "max_stars_repo_head_hexsha": "eff76fc489001512022d1a20c5561623d73efc32", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-05-20T07:23:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T23:12:21.000Z", "max_issues_repo_path": "tests/common/ManualTests/GPlotDesignerTest/GPlotDesignerTest.cpp", "max_issues_repo_name": "denisbertini/geneva", "max_issues_repo_head_hexsha": "eff76fc489001512022d1a20c5561623d73efc32", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-05-05T13:24:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-27T13:23:17.000Z", "max_forks_repo_path": "tests/common/ManualTests/GPlotDesignerTest/GPlotDesignerTest.cpp", "max_forks_repo_name": "denisbertini/geneva", "max_forks_repo_head_hexsha": "eff76fc489001512022d1a20c5561623d73efc32", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T10:33:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T12:24:55.000Z", "avg_line_length": 42.8974358974, "max_line_length": 155, "alphanum_fraction": 0.6955568838, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6296630372798201}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>\n//\n// Eigen is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 3 of the License, or (at your option) any later version.\n//\n// Alternatively, you can redistribute it and/or\n// modify it under the terms of the GNU General Public License as\n// published by the Free Software Foundation; either version 2 of\n// the License, or (at your option) any later version.\n//\n// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public\n// License and a copy of the GNU General Public License along with\n// Eigen. If not, see <http://www.gnu.org/licenses/>.\n\n#include \"main.h\"\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\ntemplate<typename Scalar> void eulerangles(void)\n{\n  typedef Matrix<Scalar,3,3> Matrix3;\n  typedef Matrix<Scalar,3,1> Vector3;\n  typedef Quaternion<Scalar> Quaternionx;\n  typedef AngleAxis<Scalar> AngleAxisx;\n\n  Scalar a = internal::random<Scalar>(-Scalar(M_PI), Scalar(M_PI));\n  Quaternionx q1;\n  q1 = AngleAxisx(a, Vector3::Random().normalized());\n  Matrix3 m;\n  m = q1;\n\n  #define VERIFY_EULER(I,J,K, X,Y,Z) { \\\n    Vector3 ea = m.eulerAngles(I,J,K); \\\n    Matrix3 m1 = Matrix3(AngleAxisx(ea[0], Vector3::Unit##X()) * AngleAxisx(ea[1], Vector3::Unit##Y()) * AngleAxisx(ea[2], Vector3::Unit##Z())); \\\n    VERIFY_IS_APPROX(m,  Matrix3(AngleAxisx(ea[0], Vector3::Unit##X()) * AngleAxisx(ea[1], Vector3::Unit##Y()) * AngleAxisx(ea[2], Vector3::Unit##Z()))); \\\n  }\n  VERIFY_EULER(0,1,2, X,Y,Z);\n  VERIFY_EULER(0,1,0, X,Y,X);\n  VERIFY_EULER(0,2,1, X,Z,Y);\n  VERIFY_EULER(0,2,0, X,Z,X);\n\n  VERIFY_EULER(1,2,0, Y,Z,X);\n  VERIFY_EULER(1,2,1, Y,Z,Y);\n  VERIFY_EULER(1,0,2, Y,X,Z);\n  VERIFY_EULER(1,0,1, Y,X,Y);\n\n  VERIFY_EULER(2,0,1, Z,X,Y);\n  VERIFY_EULER(2,0,2, Z,X,Z);\n  VERIFY_EULER(2,1,0, Z,Y,X);\n  VERIFY_EULER(2,1,2, Z,Y,Z);\n}\n\nvoid test_geo_eulerangles()\n{\n  for(int i = 0; i < g_repeat; i++) {\n    CALL_SUBTEST_1( eulerangles<float>() );\n    CALL_SUBTEST_2( eulerangles<double>() );\n  }\n}\n", "meta": {"hexsha": "f82cb8fbef4312769a9a0cb9e3d34bf3c45a5edd", "size": 2508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/geo_eulerangles.cpp", "max_stars_repo_name": "mathstuf/ParaView", "max_stars_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-03-12T00:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T08:56:31.000Z", "max_issues_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/geo_eulerangles.cpp", "max_issues_repo_name": "mathstuf/ParaView", "max_issues_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T19:02:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T14:15:04.000Z", "max_forks_repo_path": "Plugins/SciberQuestToolKit/eigen-3.0.3/eigen-eigen-3.0.3/test/geo_eulerangles.cpp", "max_forks_repo_name": "mathstuf/ParaView", "max_forks_repo_head_hexsha": "e867e280545ada10c4ed137f6a966d9d2f3db4cb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-04T12:54:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:04:38.000Z", "avg_line_length": 35.323943662, "max_line_length": 155, "alphanum_fraction": 0.692185008, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6296630361848805}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include <Spectra/SymEigsSolver.h>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass SpectralEmbedding\n{\npublic:\n  using MatrixXd = Eigen::MatrixXd;\n  using ArrayXXd = Eigen::ArrayXXd;\n  using SparseMatrixXd = Eigen::SparseMatrix<double>;\n\n  ArrayXXd process(SparseMatrixXd graph, index dims)\n  {\n    using namespace Eigen;\n    using namespace Spectra;\n    using namespace std;\n    VectorXd diagData = graph * VectorXd::Ones(graph.cols());\n    diagData = (1 / diagData.array().sqrt());\n    SparseMatrixXd D = SparseMatrixXd(graph.rows(), graph.cols());\n    D.reserve(graph.rows());\n    for (index i = 0; i < D.rows(); i++) { D.insert(i, i) = diagData(i); }\n    SparseMatrixXd I = SparseMatrixXd(D.rows(), D.cols());\n    I.setIdentity();\n    SparseMatrixXd           L = I - (D * (graph * D));\n    int                      k = static_cast<int>(dims + 1);\n    index                    ncv = max(2 * k + 1, int(round(sqrt(L.rows()))));\n    VectorXd                 initV = VectorXd::Ones(L.rows());\n    SparseSymMatProd<double> op(L);\n    SymEigsSolver<double, SMALLEST_MAGN, SparseSymMatProd<double>> eigs(&op, k,\n                                                                        ncv);\n    eigs.init(initV.data());\n    auto nConverged = eigs.compute(\n        D.cols(), 1e-4, SMALLEST_MAGN); // TODO: failback if not converging\n    MatrixXd U = eigs.eigenvectors();\n    ArrayXXd Y = U.block(0, 1, U.rows(), dims).array();\n    return Y;\n  }\n};\n}; // namespace algorithm\n}; // namespace fluid\n", "meta": {"hexsha": "ce6af5b955d6f2fbdd109af77b17b557422f34a0", "size": 2004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/SpectralEmbedding.hpp", "max_stars_repo_name": "elgiano/flucoma-core", "max_stars_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/algorithms/util/SpectralEmbedding.hpp", "max_issues_repo_name": "elgiano/flucoma-core", "max_issues_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/algorithms/util/SpectralEmbedding.hpp", "max_forks_repo_name": "elgiano/flucoma-core", "max_forks_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7857142857, "max_line_length": 79, "alphanum_fraction": 0.6432135729, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6296435341900695}}
{"text": "#ifndef CAMERA_UTILS_INCLUDE_GUARD_HPP\n#define CAMERA_UTILS_INCLUDE_GUARD_HPP\n/// \\file\n/// \\brief Camera model and camera lidar fusion\n///\n\n/*! Definition of extrinsics\n *  map -> ... -> base_link -> velodyne -> camera_link -> camera_color_optical_frame\n *      (obtained from slam)         (extrinsic)    (given by camera)\n *   \n *                    z  x                          / z         \n *                    | /                          /_ _ x                  \n *               y _ _|/                          |                       \n *                                                | y                       \n *               camera_link              camera_color_optical_frame                 \n *  \n*/\n\n// ROS\n#include \"ros/ros.h\"\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n\nnamespace disinfection_robot\n{\n\nEigen::Affine3d create_rotation_matrix(double ax, double ay, double az)\n{\n    Eigen::Affine3d rx =\n        Eigen::Affine3d(Eigen::AngleAxisd(ax, Eigen::Vector3d(1, 0, 0)));\n    Eigen::Affine3d ry =\n        Eigen::Affine3d(Eigen::AngleAxisd(ay, Eigen::Vector3d(0, 1, 0)));\n    Eigen::Affine3d rz =\n        Eigen::Affine3d(Eigen::AngleAxisd(az, Eigen::Vector3d(0, 0, 1)));\n    return rz * ry * rx;\n}\n\nclass Camera\n{\npublic:\n    float color_cx_;\n    float color_cy_;\n    float color_fx_;\n    float color_fy_; // Camera intrinsics\n\n    Eigen::Matrix4d Tco2l_; // extrinsic, from camera optical to lidar frame transformation\n\n    int image_height_ = 480;\n    int image_width_ = 640;\n\n    Camera();\n\n    /*! \\brief construct camera object with instrinsics\n    */\n    Camera(ros::NodeHandle &nh)\n    {\n        nh.getParam(\"/color_cx\", color_cx_);\n        nh.getParam(\"/color_cy\", color_cy_);\n        nh.getParam(\"/color_fx\", color_fx_);\n        nh.getParam(\"/color_fy\", color_fy_);\n\n        nh.getParam(\"/image_height\", image_height_);\n        nh.getParam(\"/image_width\", image_width_);\n\n        std::vector<double> rpy_lc;\n        std::vector<double> t_lc;\n        nh.getParam(\"/rpy_lc\", rpy_lc);\n        nh.getParam(\"/t_lc\", t_lc);\n        Eigen::Affine3d Rot_lc = create_rotation_matrix(rpy_lc[0], rpy_lc[1], rpy_lc[2]);\n        Eigen::Affine3d Trans_lc(Eigen::Translation3d(Eigen::Vector3d(t_lc[0], t_lc[1], t_lc[2])));\n        // transformation from camera link to lidar\n        Eigen::Affine3d T_cl = (Trans_lc * Rot_lc).inverse();\n\n        std::vector<double> rpy_c2co;\n        std::vector<double> t_c2co;\n        nh.getParam(\"/rpy_c2co\", rpy_c2co);\n        nh.getParam(\"/t_c2co\", t_c2co);\n        Eigen::Affine3d Rot_c2co = create_rotation_matrix(rpy_c2co[0], rpy_c2co[1], rpy_c2co[2]);\n        Eigen::Affine3d Trans_c2co(Eigen::Translation3d(Eigen::Vector3d(t_c2co[0], t_c2co[1], t_c2co[2])));\n        // transformation from camera optical frame to camera link\n        Eigen::Affine3d T_co2c = (Trans_c2co * Rot_c2co).inverse();\n\n        Tco2l_ = (T_co2c * T_cl).matrix();\n\n        // validated by comparing to ros tf\n        // std::cout << Tco2l_ << std::endl;\n    }\n\n    /*! \\brief return 3 by 3 intrinsic matrix\n    */\n    Eigen::Matrix<double, 3, 3> K() const\n    {\n        Eigen::Matrix<double, 3, 3> k;\n        k << color_fx_, 0, color_cx_, 0, color_fy_, color_cy_, 0, 0, 1;\n        return k;\n    }\n\n    /*! \\brief transform a point from lidar coordinate to camera coordinate\n    */\n    Eigen::Matrix<double, 3, 1> lidar2camera(const Eigen::Matrix<double, 3, 1> &p_l)\n    {\n        return (Tco2l_ * p_l.colwise().homogeneous()).colwise().hnormalized();\n    }\n\n    /*! \\brief transform a point from camera coordinate to sensor coordinate\n    */\n    Eigen::Matrix<int, 2, 1> camera2pixel(const Eigen::Matrix<double, 3, 1> &p_c)\n    {\n        return Eigen::Matrix<int, 2, 1>(\n            color_fx_ * p_c(0, 0) / p_c(2, 0) + color_cx_,\n            color_fy_ * p_c(1, 0) / p_c(2, 0) + color_cy_);\n    }\n\n    /*! \\brief transform a point in the lidar coordinate to pixel position (sensor coordinate)\n    */\n    Eigen::Matrix<int, 2, 1> lidar2pixel(const Eigen::Matrix<double, 3, 1> &p_l)\n    {\n        return camera2pixel(lidar2camera(p_l));\n    }\n\n    /*! \\brief transform a point from lidar coordinate to map coordinate\n    *           Given map to lidar transform and 3D point\n    */\n    Eigen::Matrix<double, 3, 1> lidar2map(const Eigen::Matrix<double, 3, 1> &p_l, const Eigen::Matrix<double, 4, 4> &Tml)\n    {\n        return (Tml * p_l.colwise().homogeneous()).colwise().hnormalized();\n    }\n\n    /*! \\brief given a pixel position and a depth, transfer it into a 3D point in camere frame (all in color camera frame)\n    */\n    Eigen::Matrix<float, 3, 1> depth2camera(const Eigen::Matrix<int, 2, 1> &p_s, unsigned int depth)\n    {\n        float z = float(depth);\n        float x = (p_s[0] - color_cx_) * z / color_fx_;\n        float y = (p_s[1] - color_cy_) * z / color_fy_;\n\n        return Eigen::Matrix<float, 3, 1>(x, y, z);\n    }\n};\n\n} // namespace disinfection_robot\n#endif\n", "meta": {"hexsha": "556c8999bb4869c71fa575d02076a8afdc9a95fc", "size": 4946, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rgbd_object_detection/include/rgbd_object_detection/camera_utils.hpp", "max_stars_repo_name": "shangzhouye/disinfection-robot-ros", "max_stars_repo_head_hexsha": "736ec6495511e0f9fe458c45cac80a99962ce9c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T20:34:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T23:06:37.000Z", "max_issues_repo_path": "rgbd_object_detection/include/rgbd_object_detection/camera_utils.hpp", "max_issues_repo_name": "shangzhouye/disinfection-robot-ros", "max_issues_repo_head_hexsha": "736ec6495511e0f9fe458c45cac80a99962ce9c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-25T07:06:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-25T07:06:54.000Z", "max_forks_repo_path": "rgbd_object_detection/include/rgbd_object_detection/camera_utils.hpp", "max_forks_repo_name": "shangzhouye/disinfection-robot-ros", "max_forks_repo_head_hexsha": "736ec6495511e0f9fe458c45cac80a99962ce9c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T07:21:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T16:10:34.000Z", "avg_line_length": 34.1103448276, "max_line_length": 122, "alphanum_fraction": 0.586736757, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6296435230261181}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file    SFMExample_bal.cpp\n * @brief   Solve a structure-from-motion problem from a \"Bundle Adjustment in the Large\" file\n * @author  Frank Dellaert\n */\n\n// For an explanation of headers, see SFMExample.cpp\n#include <gtsam/sfm/SfmData.h> // for loading BAL datasets !\n#include <gtsam/slam/GeneralSFMFactor.h>\n#include <gtsam/slam/dataset.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/inference/Symbol.h>\n\n#include <boost/format.hpp>\n#include <vector>\n\nusing namespace std;\nusing namespace gtsam;\nusing symbol_shorthand::C;\nusing symbol_shorthand::P;\n\n// We will be using a projection factor that ties a SFM_Camera to a 3D point.\n// An SFM_Camera is defined in datase.h as a camera with unknown Cal3Bundler calibration\n// and has a total of 9 free parameters\ntypedef GeneralSFMFactor<SfmCamera,Point3> MyFactor;\n\n/* ************************************************************************* */\nint main (int argc, char* argv[]) {\n\n  // Find default file, but if an argument is given, try loading a file\n  string filename = findExampleDataFile(\"dubrovnik-3-7-pre\");\n  if (argc>1) filename = string(argv[1]);\n\n  // Load the SfM data from file\n  SfmData mydata = SfmData::FromBalFile(filename);\n  cout << boost::format(\"read %1% tracks on %2% cameras\\n\") % mydata.numberTracks() % mydata.numberCameras();\n\n  // Create a factor graph\n  NonlinearFactorGraph graph;\n\n  // We share *one* noiseModel between all projection factors\n  auto noise =\n      noiseModel::Isotropic::Sigma(2, 1.0); // one pixel in u and v\n\n  // Add measurements to the factor graph\n  size_t j = 0;\n  for(const SfmTrack& track: mydata.tracks) {\n    for(const SfmMeasurement& m: track.measurements) {\n      size_t i = m.first;\n      Point2 uv = m.second;\n      graph.emplace_shared<MyFactor>(uv, noise, C(i), P(j)); // note use of shorthand symbols C and P\n    }\n    j += 1;\n  }\n\n  // Add a prior on pose x1. This indirectly specifies where the origin is.\n  // and a prior on the position of the first landmark to fix the scale\n  graph.addPrior(C(0), mydata.cameras[0],  noiseModel::Isotropic::Sigma(9, 0.1));\n  graph.addPrior(P(0), mydata.tracks[0].p, noiseModel::Isotropic::Sigma(3, 0.1));\n\n  // Create initial estimate\n  Values initial;\n  size_t i = 0; j = 0;\n  for(const SfmCamera& camera: mydata.cameras) initial.insert(C(i++), camera);\n  for(const SfmTrack& track: mydata.tracks)    initial.insert(P(j++), track.p);\n\n  /* Optimize the graph and print results */\n  Values result;\n  try {\n    LevenbergMarquardtParams params;\n    params.setVerbosity(\"ERROR\");\n    LevenbergMarquardtOptimizer lm(graph, initial, params);\n    result = lm.optimize();\n  } catch (exception& e) {\n    cout << e.what();\n  }\n  cout << \"final error: \" << graph.error(result) << endl;\n\n  return 0;\n}\n/* ************************************************************************* */\n\n", "meta": {"hexsha": "10563760d26fe83896d6a429fba356267b90289a", "size": 3305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/SFMExample_bal.cpp", "max_stars_repo_name": "h-rover/gtsam", "max_stars_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T07:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T07:01:48.000Z", "max_issues_repo_path": "examples/SFMExample_bal.cpp", "max_issues_repo_name": "h-rover/gtsam", "max_issues_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/SFMExample_bal.cpp", "max_forks_repo_name": "h-rover/gtsam", "max_forks_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-21T06:58:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T06:58:34.000Z", "avg_line_length": 34.7894736842, "max_line_length": 109, "alphanum_fraction": 0.6366111952, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6296412307669833}}
{"text": "//\n// Created by aoool on 15.11.18.\n//\n\n#include \"trajectory_layer.hpp\"\n\n#include <typeinfo>\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\n\nstd::vector<double>\nTrajectoryLayer::GetJerkMinimizingTrajectory(std::vector<double> start, std::vector<double> end, double t) const\n{\n  /*\n  Calculate the Jerk Minimizing Trajectory that connects the initial state\n  to the final state in time t.\n\n  INPUTS\n\n  start - the vehicles start location given as a length three array\n      corresponding to initial values of [s, s_dot, s_double_dot]\n\n  end   - the desired end state for vehicle. Like \"start\" this is a\n      length three array.\n\n  t     - The duration, in seconds, over which this maneuver should occur.\n\n  OUTPUT\n  an array of length 6, each value corresponding to a coefficent in the polynomial\n  s(t) = a_0 + a_1 * t + a_2 * t**2 + a_3 * t**3 + a_4 * t**4 + a_5 * t**5\n\n  EXAMPLE\n\n  > JMT( [0, 10, 0], [10, 10, 0], 1)\n  [0.0, 10.0, 0.0, 0.0, 0.0, 0.0]\n  */\n\n  MatrixXd A = MatrixXd(3, 3);\n  A << t*t*t, t*t*t*t, t*t*t*t*t,\n       3*t*t, 4*t*t*t, 5*t*t*t*t,\n         6*t,  12*t*t,  20*t*t*t;\n\n  MatrixXd B = MatrixXd(3,1);\n  B << end[0]-(start[0]+start[1]*t+.5*start[2]*t*t),\n       end[1]-(start[1]+start[2]*t),\n       end[2]-start[2];\n\n  MatrixXd Ai = A.inverse();\n\n  MatrixXd C = Ai*B;\n\n  std::vector<double> result = {start[0], start[1], 0.5*start[2]};\n  for(int i = 0; i < C.size(); i++)\n  {\n    result.push_back(C.data()[i]);\n  }\n\n  return result;\n\n}\n\n\nTrajectoryLayer::TrajectoryLayer(const PathPlannerConfig& config, LocalizationLayer& localization_layer,\n                                 PredictionLayer& prediction_layer, BehaviorLayer& behavior_layer):\n  pp_config_{config},\n  localization_layer_{localization_layer},\n  prediction_layer_{prediction_layer},\n  behavior_layer_{behavior_layer},\n  initialized_{false},\n  ego_car_{},\n  next_cars_{}\n{\n\n}\n\n\nstd::vector<Car>\nTrajectoryLayer::GetTrajectory(size_t num_points)\n{\n  if (!initialized_) {\n    throw std::logic_error(\"TrajectoryLayer::Initialize should be invoked before TrajectoryLayer::GetTrajectory\");\n  }\n\n  auto&& predictions = prediction_layer_.GetPredictions(num_points * pp_config_.frequency_s, ego_car_.T());\n\n  auto&& cur_other_cars_current_lane = ego_car_.CarsInCurrentLane(map_keys(predictions));\n  std::optional<Car> cur_other_car_ahead_current_lane_opt = ego_car_.NearestCarAhead(cur_other_cars_current_lane);\n\n  if (cur_other_car_ahead_current_lane_opt.has_value()) {\n    auto cur_other_car_ahead = cur_other_car_ahead_current_lane_opt.value();\n\n    if (ego_car_.IsFrontBufferViolatedBy(cur_other_car_ahead, 0.5)) {\n      std::cout << __PRETTY_FUNCTION__ << \" identified the front buffer violation of ego car\\n\"\n                << ego_car_ << \"\\n by other car\\n\" << cur_other_car_ahead << std::endl;\n      next_cars_.resize(0);\n    }\n  }\n\n\n  if (next_cars_.size() >= pp_config_.path_len) {\n    std::vector<Car> to_return{next_cars_.rbegin(), next_cars_.rbegin() + num_points};\n    ego_car_ = to_return[to_return.size() - 1];\n    next_cars_.resize(next_cars_.size() - num_points);\n\n    return to_return;\n  }\n\n  if (!next_cars_.empty()) {\n    ego_car_ = next_cars_[0];\n  }\n\n  Car planned_ego_car = behavior_layer_.Plan(ego_car_)[0];\n\n  auto ego_car_s = static_cast<double>(ego_car_.S());\n  auto planned_ego_car_s = static_cast<double>(planned_ego_car.S());\n  if (planned_ego_car_s < ego_car_s) {\n    planned_ego_car_s += pp_config_.max_s_m;\n  }\n\n  double planning_time_horizon = planned_ego_car.T() - ego_car_.T();\n\n  std::vector<double> s_coeffs = GetJerkMinimizingTrajectory(\n      {ego_car_s, ego_car_.Vs(), ego_car_.As(), },\n      {planned_ego_car_s, planned_ego_car.Vs(), planned_ego_car.As(), },\n      planning_time_horizon\n  );\n\n  std::vector<double> d_coeffs = GetJerkMinimizingTrajectory(\n      { ego_car_.D(), ego_car_.Vd(), ego_car_.Ad(), },\n      { planned_ego_car.D(), planned_ego_car.Vd(), planned_ego_car.Ad(), },\n      planning_time_horizon\n  );\n\n  double t = pp_config_.frequency_s;\n  const double t_diff = pp_config_.frequency_s;\n  double s_prev = static_cast<double>(ego_car_.S());\n  double d_prev = ego_car_.D();\n  double vs_prev = ego_car_.Vs();\n  double vd_prev = ego_car_.Vd();\n\n\n  for (int i = 0; i < pp_config_.trajectory_layer_queue_len - next_cars_.size(); ++i) {\n    double s = CalcPolynomial(s_coeffs, t);\n    double d = CalcPolynomial(d_coeffs, t);\n    double vs = Calc1DVelocity(s_prev, s, t_diff);\n    double vd = Calc1DVelocity(d_prev, d, t_diff);\n\n    next_cars_.push_front(\n      Car::Builder(planned_ego_car)\n        .SetTime(ego_car_.T() + t)\n        .SetCoordinateS(s)\n        .SetCoordinateD(d)\n        .SetVelocityS(vs)\n        .SetVelocityD(vd)\n        .SetAccelerationS(Calc1DAcc(vs_prev, vs, t_diff))\n        .SetAccelerationD(Calc1DAcc(vd_prev, vd, t_diff))\n      .Build()\n    );\n    s_prev = s;\n    d_prev = d;\n    vs_prev = vs;\n    vd_prev = vd;\n\n    t += t_diff;\n  }\n\n\n  std::vector<Car> to_return{next_cars_.rbegin(), next_cars_.rbegin() + num_points};\n  ego_car_ = to_return[to_return.size() - 1];\n  next_cars_.resize(next_cars_.size() - num_points);\n\n  return to_return;\n}\n\n\nvoid TrajectoryLayer::Initialize(const Car& car)\n{\n  ego_car_ = car;\n  initialized_ = true;\n}\n\n\nTrajectoryLayer::~TrajectoryLayer() = default;\n", "meta": {"hexsha": "a0a6ff781526fd29cc09dc880ce007584e07f37a", "size": 5271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trajectory_layer.cpp", "max_stars_repo_name": "RobertDae/Udacity_PathPlannerProject", "max_stars_repo_head_hexsha": "b65fbfc19c3d7bd971cd9d61256f47326a051683", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-05-05T02:35:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-08T18:28:33.000Z", "max_issues_repo_path": "src/trajectory_layer.cpp", "max_issues_repo_name": "RobertDae/Udacity_PathPlannerProject", "max_issues_repo_head_hexsha": "b65fbfc19c3d7bd971cd9d61256f47326a051683", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/trajectory_layer.cpp", "max_forks_repo_name": "RobertDae/Udacity_PathPlannerProject", "max_forks_repo_head_hexsha": "b65fbfc19c3d7bd971cd9d61256f47326a051683", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-05T15:57:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-15T15:20:17.000Z", "avg_line_length": 28.1871657754, "max_line_length": 114, "alphanum_fraction": 0.6761525327, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6296412144872043}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of mathemttical functions for variable class.\n */\n#include \"num_collect/auto_diff/backward/variable_math.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_template_test_macros.hpp>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n#include \"num_collect/auto_diff/backward/differentiate.h\"\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\"num_collect::auto_diff::backward::exp\", \"\", float, double) {\n    using scalar_type = TestType;\n    using variable_type =\n        num_collect::auto_diff::backward::variable<scalar_type>;\n    using num_collect::auto_diff::backward::constant_tag;\n    using num_collect::auto_diff::backward::differentiate;\n    using num_collect::auto_diff::backward::variable_tag;\n\n    SECTION(\"process an argument with node\") {\n        const auto var = variable_type(1.234, variable_tag());\n\n        const variable_type res = exp(var);\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(std::exp(var.value())));\n        REQUIRE(res.node());\n\n        const scalar_type coeff = differentiate(res, var);\n        REQUIRE_THAT(coeff, Catch::Matchers::WithinRel(std::exp(var.value())));\n    }\n\n    SECTION(\"process an argument without node\") {\n        const auto var = variable_type(1.234, constant_tag());\n\n        const variable_type res = exp(var);\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(std::exp(var.value())));\n        REQUIRE_FALSE(res.node());\n    }\n}\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\"num_collect::auto_diff::backward::log\", \"\", float, double) {\n    using scalar_type = TestType;\n    using variable_type =\n        num_collect::auto_diff::backward::variable<scalar_type>;\n    using num_collect::auto_diff::backward::constant_tag;\n    using num_collect::auto_diff::backward::differentiate;\n    using num_collect::auto_diff::backward::variable_tag;\n\n    SECTION(\"process an argument with node\") {\n        const auto var = variable_type(1.234, variable_tag());\n\n        const variable_type res = log(var);\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(std::log(var.value())));\n        REQUIRE(res.node());\n\n        const scalar_type coeff = differentiate(res, var);\n        REQUIRE_THAT(coeff, Catch::Matchers::WithinRel(1 / var.value()));\n    }\n\n    SECTION(\"process an argument without node\") {\n        const auto var = variable_type(1.234, constant_tag());\n\n        const variable_type res = log(var);\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(std::log(var.value())));\n        REQUIRE_FALSE(res.node());\n    }\n}\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\n    \"num_collect::auto_diff::backward::sqrt\", \"\", float, double) {\n    using scalar_type = TestType;\n    using variable_type =\n        num_collect::auto_diff::backward::variable<scalar_type>;\n    using num_collect::auto_diff::backward::constant_tag;\n    using num_collect::auto_diff::backward::differentiate;\n    using num_collect::auto_diff::backward::variable_tag;\n\n    SECTION(\"process an argument with node\") {\n        const auto var = variable_type(1.234, variable_tag());\n\n        const variable_type res = sqrt(var);\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(std::sqrt(var.value())));\n        REQUIRE(res.node());\n\n        const scalar_type coeff = differentiate(res, var);\n        REQUIRE_THAT(coeff,\n            Catch::Matchers::WithinRel(\n                1 / static_cast<scalar_type>(2) / std::sqrt(var.value())));\n    }\n\n    SECTION(\"process an argument without node\") {\n        const auto var = variable_type(1.234, constant_tag());\n\n        const variable_type res = log(var);\n        REQUIRE_THAT(\n            res.value(), Catch::Matchers::WithinRel(std::log(var.value())));\n        REQUIRE_FALSE(res.node());\n    }\n}\n", "meta": {"hexsha": "5c91c51e07b2962ecc73b2f808ba6d8673bdcb8d", "size": 4437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/auto_diff/backward/variable_math_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units/auto_diff/backward/variable_math_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units/auto_diff/backward/variable_math_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7822580645, "max_line_length": 80, "alphanum_fraction": 0.6741041244, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6296412144872043}}
{"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Sch\u00fcttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearfeelementmatrix.h\"\n\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/mesh/mesh.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix<double, 4, 4> MyLinearFEElementMatrix::Eval(\n    const lf::mesh::Entity &cell) {\n  // Topological type of the cell\n  const lf::base::RefEl ref_el{cell.RefEl()};\n\n  // Obtain the vertex coordinates of the cell, which completely\n  // describe its shape.\n  const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n  // Matrix storing corner coordinates in its columns\n  auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n  // Matrix for returning element matrix\n  Eigen::Matrix<double, 4, 4> elem_mat;\n\n  //====================\n  // Your code goes here\n  //====================\n  Eigen::Matrix<double,4,4> laplace_elem_mat;\n  Eigen::Matrix<double,4,4> mass_elem_mat;\n\n  lf::uscalfe::LinearFELaplaceElementMatrix laplace_elmat_builder;\n  laplace_elem_mat = laplace_elmat_builder.Eval(cell);\n\n  switch (ref_el) {\n      case (lf::base::RefEl::kTria()): {\n          double area = \n              0.5*\n              ( (vertices(0,1)-vertices(0,0))*(vertices(1,2)-vertices(1,0))-\n                (vertices(1,1)-vertices(1,0))*(vertices(0,2)-vertices(0,0)))\n          mass_elem_mat <<\n          2.0,1.0,1.0,0.0,\n          1.0,2.0,1.0.0.0,\n          1.0,1.0,2.0,0.0,\n          0.0,0.0,0.0,0.0;\n\n          mass_elem_mat *= area/12.0;\n          break;\n      }\n      case (lf::base::RefEL::kQuad()): {\n          double area = \n              (vertices(0,1)-vertices(0,0))*(vertices(1,3)-vertices(1,0));\n          mass_elem_mat <<\n          4.0,2.0,1.0,2.0,\n          2.0,4.0,2.0,1.0,\n          1.0,2.0,4.0,2.0,\n          2.0,1.0,2.0,4.0;\n\n          mass_elem_mat *= area/36.0;\n          break;\n      }\n  }\n  elem_mat = laplace_elem_mat + mass_elem_mat;\n  return elem_mat;\n}\n/* SAM_LISTING_END_1 */\n}  // namespace ElementMatrixComputation\n", "meta": {"hexsha": "974cd9b135dd09e4c1243b895afdf686727d9de3", "size": 2168, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_stars_repo_name": "hanyao8/NPDECODES", "max_stars_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_issues_repo_name": "hanyao8/NPDECODES", "max_issues_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_forks_repo_name": "hanyao8/NPDECODES", "max_forks_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5263157895, "max_line_length": 76, "alphanum_fraction": 0.6037822878, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6296334996520165}}
{"text": "#include <ros/ros.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n\n#include <tf/transform_datatypes.h>\n#include <tf/transform_listener.h>\n#include <tf2/LinearMath/Quaternion.h>\n#include <tf2_ros/transform_broadcaster.h>\n#include \"kalman.hpp\"\n\n//#include <people_msgs/PositionMeasurement.h>\n#include <geometry_msgs/PoseStamped.h>\n\n#include <visualization_msgs/Marker.h>\n\ntemplate <typename T> std::string tostr(const T& t)\n{\n    std::ostringstream os; os<<t; return os.str();\n}\n\n//static std::string fixed_frame = \"base_link\";\nstatic std::string fixed_frame = \"map\";\n\n\nclass KalmanTracker{\nprivate:\n    ros::Rate r;\n    ros::Subscriber person_pos_sub;\n    ros::Publisher markers_pub,text_pub,estimate_pos_pub,estimate_arrow_pub;\n    ros::NodeHandle nh1;\n    ros::Time start,now;\n    Eigen::VectorXd x,y;\n    Eigen::MatrixXd A; // System dynamics matrix\n    Eigen::MatrixXd C; // Output matrix\n    Eigen::MatrixXd Q; // Process noise covariance\n    Eigen::MatrixXd R; // Measurement noise covariance\n    Eigen::MatrixXd P; // Estimate error covariance\n    KalmanFilter estimate_X,estimate_Y;\n    int n; // Number of states\n    int m; // Number of measurements\n    int init_f,update_f;\n    double dt; // Time step\n    double t; // Time\n    double sigma_obs;\npublic:\n    KalmanTracker(ros::NodeHandle nh):\n    nh1(nh),r(10),n(6),m(2),dt(1.0/10),sigma_obs(0.002),init_f(0)\n    {\n        x = Eigen::VectorXd(n);\n        A = Eigen::MatrixXd(n,n);\n        C = Eigen::MatrixXd(m,n);\n        Q = Eigen::MatrixXd(n,n);\n        R = Eigen::MatrixXd(m,m);\n        P = Eigen::MatrixXd(n,n);\n        // Discrete LTI projectile motion, measuring position only\n        const double dt2 = 0.5 * dt * dt;\n        A << 1, 0, dt,  0, dt2,   0,\n                 0, 1,  0, dt,   0, dt2,\n                 0, 0,  1,  0,  dt,   0,\n                 0, 0,  0,  1,   0,  dt,\n                 0, 0,  0,  0,   1,   0,\n                 0, 0,  0,  0,   0,   1;\n        C << 1, 0, 0, 0, 0, 0,\n                  0, 1, 0, 0, 0, 0;\n        // Reasonable covariance matrices\n        Q = Eigen::MatrixXd::Identity(n, n) * 1.0e-6;;\n        R = Eigen::MatrixXd::Identity(m, m) * pow(sigma_obs, 2);\n        P = Eigen::MatrixXd::Identity(n, n) * 1.0e-6;\n        estimate_X=KalmanFilter(dt,A, C, Q, R, P);\n        estimate_X.init(0,x);\n        //start = now = ros::Time::now();\n        \n        person_pos_sub = nh1.subscribe(\"filter_measurement\",1,&KalmanTracker::msgCallback_PeopleTracker, this);\n        \n        markers_pub = nh1.advertise<visualization_msgs::Marker>(\"/visualization_estimate_marker\", 20);//Output of KF\n        estimate_pos_pub = nh1.advertise<geometry_msgs::PoseStamped>(\"estimate_pos\", 1);\n        estimate_arrow_pub = nh1.advertise<visualization_msgs::Marker>(\"/visualization_estimate_arrow\", 1);\n        //text_pub = nh1.advertise<visualization_msgs::Marker>(\"tracking_text\", 20);\n        //estimate_pos_pub = nh1.advertise<geometry_msgs::PoseStamped>(\"human_pose\", 20);\n\n        /*\n        std::cout << \"A: \\n\" << A << std::endl;\n        std::cout << \"C: \\n\" << C << std::endl;\n        std::cout << \"Q: \\n\" << Q << std::endl;\n        std::cout << \"R: \\n\" << R << std::endl;\n        std::cout << \"P: \\n\" << P << std::endl;\n        */\n    }\n\n    void msgCallback_PeopleTracker(const geometry_msgs::PoseStamped::ConstPtr& msg)\n    {\n        \n        if(msg->pose.position.z == 1)\n        {\n        // Best guess of initial states\n            //std::cout<<\"---Initialization---\"<<std::endl;\n            //start = now = ros::Time::now();\n            x <<msg->pose.position.x, msg->pose.position.y,0.0,0.0,0.0, 0.0;\n           \n            std::cout<<\"init_measurement: \"<<msg->pose.position.x<<\", \"<<msg->pose.position.y<<std::endl;\n            estimate_X.init(t,x);\n            std::cout<<\"init_estimate        : \"<<estimate_X.state()[0]<<\", \"<<estimate_X.state()[1]<<std::endl;\n     \n            //init_f=1;\n        }\n        else\n        {\n            //now = ros::Time::now();\n            //std::cout<<\"---Update---\"<<std::endl;\n            Eigen::VectorXd z(m);\n            z << msg->pose.position.x,msg->pose.position.y;\n            //std::cout<<\"update_measurement: \"<<msg->pose.position.x<<\", \"<<msg->pose.position.y<<std::endl;\n            estimate_X.update(z);\n            //std::cout<<\"update_estimate        : \"<<estimate_X.state()[0]<<\", \"<<estimate_X.state()[1]<<std::endl;\n        }\n        double estimate_x = estimate_X.state()[0];\n        double estimate_y = estimate_X.state()[1];\n        \n        \n        //std::cout <<\"x_hat=\" << estimate_X.state().transpose()<<std::endl;\n        //std::cout <<\"y_hat=\" << estimate_Y.state().transpose()<<std::endl;\n\n        //std::cout<<\"\"<<std::endl;\n        \n        visualization_msgs::Marker m;\n        m.header.stamp = ros::Time::now();\n        m.header.frame_id = fixed_frame;\n        m.scale.x = 0.2;\n        m.scale.y = 0.2;\n        m.scale.z = 0.05;\n        m.color.a = 1.0f;\n        m.color.r = 0.0f;\n        m.color.g = 1.0f;\n        m.color.b = 0.0f;\n        \n        m.type = m.SPHERE;    \n        m.lifetime = ros::Duration(0.5);\n        m.pose.position.x = estimate_x;\n        m.pose.position.y = estimate_y;\n\n        geometry_msgs::PoseStamped estimate_pos;\n        estimate_pos.pose.position.x = estimate_x;\n        estimate_pos.pose.position.y = estimate_y;\n        estimate_pos.pose.position.z = 0;\n\n        visualization_msgs::Marker estimateposearrow;\n        double yaw = atan2(estimate_y,estimate_x);\n        //std::cout<<\"yaw: \"<<yaw<<std::endl;\n        \n        estimateposearrow.header.frame_id = fixed_frame;;\n        estimateposearrow.header.stamp = ros::Time::now();\n        estimateposearrow.ns = \"basic_shapes\";\n        estimateposearrow.type = visualization_msgs::Marker::ARROW;\n        estimateposearrow.action = visualization_msgs::Marker::ADD;\n        estimateposearrow.pose.position.x = estimate_x;\n        estimateposearrow.pose.position.y = estimate_y;\n        estimateposearrow.pose.orientation=tf::createQuaternionMsgFromYaw(yaw);\n\n        // Set the scale of the marker -- 1x1x1 here means 1m on a side\n        estimateposearrow.scale.x = 0.3;\n        estimateposearrow.scale.y = 0.1;\n        estimateposearrow.scale.z = 0.1;\n        // Set the color -- be sure to set alpha to something non-zero!\n        estimateposearrow.color.r = 0.0f;\n        estimateposearrow.color.g = 1.0f;\n        estimateposearrow.color.b = 0.0f;\n        estimateposearrow.color.a = 1.0f;\n\n        estimateposearrow.lifetime = ros::Duration();\n\n        estimate_arrow_pub.publish(estimateposearrow);\n        markers_pub.publish(m);\n        estimate_pos_pub.publish(estimate_pos);        \n        \n        //estimate_pos.header.stamp = ros::Time::now();\n        //estimate_pos.header.frame_id = fixed_frame;\n        //estimate_pos.name = \"tracking\";\n        \n        //std::cout<<estimate_X.cov()<<std::endl;\n        /*estimate_pos.covariance[0] = (estimate_X.cov()(0,0)+estimate_Y.cov()(0,0))/2;\n        estimate_pos.covariance[1] = 0.0;\n        estimate_pos.covariance[2] = 0.0;\n        estimate_pos.covariance[3] = 0.0;\n        estimate_pos.covariance[4] = (estimate_X.cov()(1,1)+estimate_Y.cov()(1,1))/2;\n        estimate_pos.covariance[5] = 0.0;\n        estimate_pos.covariance[6] = 0.0;\n        estimate_pos.covariance[7] = 0.0;\n        estimate_pos.covariance[8] = (estimate_X.cov()(2,2)+estimate_Y.cov()(2,2))/2;\n        */\n        /*\n        if(init_f==1)\n        {\n            markers_pub.publish(m);\n            estimate_pos_pub.publish(estimate_pos);\n        }\n        */\n\n    //r.sleep();\n    }\n};\n\n// \u8cfc\u8aad\u8005\u30ce\u30fc\u30c9\u306e\u30e1\u30a4\u30f3\u95a2\u6570\nint main(int argc, char **argv)\n{\n    // \u30ce\u30fc\u30c9\u540d\u306e\u521d\u671f\u5316\n    ros::init(argc, argv, \"person_tracking_kalman\");\n    // ROS\u30b7\u30b9\u30c6\u30e0\u3068\u306e\u901a\u4fe1\u306e\u305f\u3081\u306e\u30ce\u30fc\u30c9\u306e\u30cf\u30f3\u30c9\u30eb\u3092\u5ba3\u8a00\n    ros::NodeHandle nh;\n    KalmanTracker kt(nh);\n    ros::spin();\n    return 0;\n}\n", "meta": {"hexsha": "529c340680001f5b77a2e82de979187967c07b0e", "size": 7815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/person_tracking_kalman/src/person_tracking_kalman_node.cpp", "max_stars_repo_name": "ayuguchi/gazed_object_identification_robot", "max_stars_repo_head_hexsha": "c06a49e405fa7c8a05ea6c4540b2a34b4aeca243", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/person_tracking_kalman/src/person_tracking_kalman_node.cpp", "max_issues_repo_name": "ayuguchi/gazed_object_identification_robot", "max_issues_repo_head_hexsha": "c06a49e405fa7c8a05ea6c4540b2a34b4aeca243", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/person_tracking_kalman/src/person_tracking_kalman_node.cpp", "max_forks_repo_name": "ayuguchi/gazed_object_identification_robot", "max_forks_repo_head_hexsha": "c06a49e405fa7c8a05ea6c4540b2a34b4aeca243", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T15:47:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T15:47:50.000Z", "avg_line_length": 36.5186915888, "max_line_length": 116, "alphanum_fraction": 0.5773512476, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6296107964267154}}
{"text": "#ifndef MATHEVAL_IMPLEMENTATION\n#error \"Do not include parser_def.hpp directly!\"\n#endif\n\n#pragma once\n\n#include \"ast.hpp\"\n#include \"ast_adapted.hpp\"\n#include \"../math.hpp\"\n#include \"parser.hpp\"\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/spirit/home/x3.hpp>\n\n#include <cmath>\n#include <iostream>\n#include <limits>\n#include <string>\n\nnamespace matheval {\n\nnamespace x3 = boost::spirit::x3;\n\nnamespace parser {\n\n// LOOKUP\n\nstruct constant_ : x3::symbols<double> {\n    constant_() {\n        // clang-format off\n        add\n            (\"e\"      , boost::math::constants::e<double>())\n            (\"epsilon\", std::numeric_limits<double>::epsilon())\n            (\"phi\"    , boost::math::constants::phi<double>())\n            (\"pi\"     , boost::math::constants::pi<double>())\n            ;\n        // clang-format on\n    }\n} constant;\n\nstruct ufunc_ : x3::symbols<double (*)(double)> {\n    ufunc_() {\n        // clang-format off\n        add\n            (\"abs\"   , static_cast<double (*)(double)>(&std::abs))\n            (\"acos\"  , static_cast<double (*)(double)>(&math::acos))\n            (\"acosh\" , static_cast<double (*)(double)>(&math::acosh))\n            (\"asin\"  , static_cast<double (*)(double)>(&math::asin))\n            (\"asinh\" , static_cast<double (*)(double)>(&std::asinh))\n            (\"atan\"  , static_cast<double (*)(double)>(&std::atan))\n            (\"atanh\" , static_cast<double (*)(double)>(&math::atanh))\n            (\"cbrt\"  , static_cast<double (*)(double)>(&std::cbrt))\n            (\"ceil\"  , static_cast<double (*)(double)>(&std::ceil))\n            (\"cos\"   , static_cast<double (*)(double)>(&math::cos))\n            (\"cosh\"  , static_cast<double (*)(double)>(&std::cosh))\n            (\"deg\"   , static_cast<double (*)(double)>(&math::deg))\n            (\"erf\"   , static_cast<double (*)(double)>(&std::erf))\n            (\"erfc\"  , static_cast<double (*)(double)>(&std::erfc))\n            (\"exp\"   , static_cast<double (*)(double)>(&std::exp))\n            (\"exp2\"  , static_cast<double (*)(double)>(&std::exp2))\n            (\"floor\" , static_cast<double (*)(double)>(&std::floor))\n            (\"isinf\" , static_cast<double (*)(double)>(&math::isinf))\n            (\"isnan\" , static_cast<double (*)(double)>(&math::isnan))\n            (\"log\"   , static_cast<double (*)(double)>(&math::log))\n            (\"log2\"  , static_cast<double (*)(double)>(&math::log2))\n            (\"log10\" , static_cast<double (*)(double)>(&math::log10))\n            (\"rad\"   , static_cast<double (*)(double)>(&math::rad))\n            (\"round\" , static_cast<double (*)(double)>(&std::round))\n            (\"sgn\"   , static_cast<double (*)(double)>(&math::sgn))\n            (\"sin\"   , static_cast<double (*)(double)>(&math::sin))\n            (\"sinh\"  , static_cast<double (*)(double)>(&std::sinh))\n            (\"sqrt\"  , static_cast<double (*)(double)>(&math::sqrt))\n            (\"tan\"   , static_cast<double (*)(double)>(&math::tan))\n            (\"tanh\"  , static_cast<double (*)(double)>(&std::tanh))\n            (\"tgamma\", static_cast<double (*)(double)>(&math::tgamma))\n            ;\n        // clang-format on\n    }\n} ufunc;\n\nstruct tfunc_ : x3::symbols<double (*)(double, double, double)> {\n    tfunc_() {\n        // clang-format off\n        add\n\t  (\"ifelse\", static_cast<double (*)(double, double, double)>(&math::ifelse))\n            ;\n        // clang-format on\n    }\n} tfunc;\n\nstruct bfunc_ : x3::symbols<double (*)(double, double)> {\n    bfunc_() {\n        // clang-format off\n        add\n            (\"atan2\", static_cast<double (*)(double, double)>(&std::atan2))\n            (\"max\"  , static_cast<double (*)(double, double)>(&std::fmax))\n            (\"min\"  , static_cast<double (*)(double, double)>(&std::fmin))\n            (\"pow\"  , static_cast<double (*)(double, double)>(&math::pow))\n            ;\n        // clang-format on\n    }\n} bfunc;\n\nstruct unary_op_ : x3::symbols<double (*)(double)> {\n    unary_op_() {\n        // clang-format off\n        add\n            (\"+\", static_cast<double (*)(double)>(&math::plus))\n            (\"-\", static_cast<double (*)(double)>(&math::minus))\n            (\"!\", static_cast<double (*)(double)>(&math::unary_not))\n            ;\n        // clang-format on\n    }\n} unary_op;\n\nstruct additive_op_ : x3::symbols<double (*)(double, double)> {\n    additive_op_() {\n        // clang-format off\n        add\n            (\"+\", static_cast<double (*)(double, double)>(&math::plus))\n            (\"-\", static_cast<double (*)(double, double)>(&math::minus))\n            ;\n        // clang-format on\n    }\n} additive_op;\n\nstruct multiplicative_op_ : x3::symbols<double (*)(double, double)> {\n    multiplicative_op_() {\n        // clang-format off\n        add\n            (\"*\", static_cast<double (*)(double, double)>(&math::multiplies))\n            (\"/\", static_cast<double (*)(double, double)>(&math::divides))\n            (\"%\", static_cast<double (*)(double, double)>(&math::fmod))\n            ;\n        // clang-format on\n    }\n} multiplicative_op;\n\nstruct logical_op_ : x3::symbols<double (*)(double, double)> {\n    logical_op_() {\n        // clang-format off\n        add\n            (\"&&\", static_cast<double (*)(double, double)>(&math::logical_and))\n            (\"||\", static_cast<double (*)(double, double)>(&math::logical_or))\n            ;\n        // clang-format on\n    }\n} logical_op;\n\nstruct relational_op_ : x3::symbols<double (*)(double, double)> {\n    relational_op_() {\n        // clang-format off\n        add\n            (\"<\" , static_cast<double (*)(double, double)>(&math::less))\n            (\"<=\", static_cast<double (*)(double, double)>(&math::less_equals))\n            (\">\" , static_cast<double (*)(double, double)>(&math::greater))\n            (\">=\", static_cast<double (*)(double, double)>(&math::greater_equals))\n            ;\n        // clang-format on\n    }\n} relational_op;\n\nstruct equality_op_ : x3::symbols<double (*)(double, double)> {\n    equality_op_() {\n        // clang-format off\n        add\n            (\"==\", static_cast<double (*)(double, double)>(&math::equals))\n            (\"!=\", static_cast<double (*)(double, double)>(&math::not_equals))\n            ;\n        // clang-format on\n    }\n} equality_op;\n\nstruct power_ : x3::symbols<double (*)(double, double)> {\n    power_() {\n        // clang-format off\n        add\n            (\"**\", static_cast<double (*)(double, double)>(&math::pow))\n            ;\n        // clang-format on\n    }\n} power;\n\n// ADL markers\n\nstruct expression_class;\nstruct logical_class;\nstruct equality_class;\nstruct relational_class;\nstruct additive_class;\nstruct multiplicative_class;\nstruct factor_class;\nstruct primary_class;\nstruct unary_class;\nstruct binary_class;\nstruct ternary_class;\nstruct variable_class;\n\n// clang-format off\n\n// Rule declarations\n\nauto const expression     = x3::rule<expression_class    , ast::expression>{\"expression\"};\nauto const logical        = x3::rule<logical_class       , ast::expression>{\"logical\"};\nauto const equality       = x3::rule<equality_class      , ast::expression>{\"equality\"};\nauto const relational     = x3::rule<relational_class    , ast::expression>{\"relational\"};\nauto const additive       = x3::rule<additive_class      , ast::expression>{\"additive\"};\nauto const multiplicative = x3::rule<multiplicative_class, ast::expression>{\"multiplicative\"};\nauto const factor         = x3::rule<factor_class        , ast::expression>{\"factor\"};\nauto const primary        = x3::rule<primary_class       , ast::operand   >{\"primary\"};\nauto const unary          = x3::rule<unary_class         , ast::unary_op  >{\"unary\"};\nauto const binary         = x3::rule<binary_class        , ast::binary_op >{\"binary\"};\nauto const ternary        = x3::rule<ternary_class       , ast::ternary_op>{\"ternary\"};\nauto const variable       = x3::rule<variable_class      , std::string    >{\"variable\"};\n\n// Rule defintions\n\nauto const expression_def =\n    logical\n    ;\n\nauto const logical_def =\n    equality >> *(logical_op > equality)\n    ;\n\nauto const equality_def =\n    relational >> *(equality_op > relational)\n    ;\n\nauto const relational_def =\n    additive >> *(relational_op > additive)\n    ;\n\nauto const additive_def =\n    multiplicative >> *(additive_op > multiplicative)\n    ;\n\nauto const multiplicative_def =\n    factor >> *(multiplicative_op > factor)\n    ;\n\nauto const factor_def =\n    primary >> *( power > factor )\n    ;\n\nauto const unary_def =\n    ufunc > '(' > expression > ')'\n    ;\n\nauto const binary_def =\n    bfunc > '(' > expression > ',' > expression > ')'\n    ;\n\nauto const ternary_def =\n    tfunc > '(' > expression > ',' > expression > ',' > expression > ')'\n    ;\n\nauto const variable_def =\n    x3::raw[x3::lexeme[x3::alpha >> *(x3::alnum | '_')]]\n    ;\n\nauto const primary_def =\n      x3::double_\n    | ('(' > expression > ')')\n    | (unary_op > primary)\n    | ternary\n    | binary\n    | unary\n    | constant\n    | variable\n    ;\n\nBOOST_SPIRIT_DEFINE(\n    expression,\n    logical,\n    equality,\n    relational,\n    additive,\n    multiplicative,\n    factor,\n    primary,\n    unary,\n    binary,\n    ternary,\n    variable\n)\n\n// clang-format on\n\nstruct expression_class {\n    template <typename Iterator, typename Exception, typename Context>\n    x3::error_handler_result on_error(Iterator &, Iterator const &last,\n                                      Exception const &x, Context const &) {\n        std::cout << \"Expected \" << x.which() << \" at \\\"\"\n                  << std::string{x.where(), last} << \"\\\"\" << std::endl;\n        return x3::error_handler_result::fail;\n    }\n};\n\n} // namespace parser\n\nparser::expression_type grammar() { return parser::expression; }\n\n} // namespace matheval\n", "meta": {"hexsha": "036c333f6065aa6197148fdc38163288b53a320d", "size": 9648, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/x3/parser_def.hpp", "max_stars_repo_name": "doj/boost_matheval", "max_stars_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/x3/parser_def.hpp", "max_issues_repo_name": "doj/boost_matheval", "max_issues_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/x3/parser_def.hpp", "max_forks_repo_name": "doj/boost_matheval", "max_forks_repo_head_hexsha": "61c6b3cb450127612e4f531ded37f3dca54a1419", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6327868852, "max_line_length": 94, "alphanum_fraction": 0.5615671642, "num_tokens": 2334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530491, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6296107955653956}}
{"text": "#include <random>\n#include <Eigen/Dense>\n#include \"HODLR_Tree.hpp\"\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <squaredeMat.hpp> //squared exponential kernel\n#include <squaredeP1Mat.hpp>\n\nusing std::normal_distribution;\nnamespace py = pybind11;\n\n// AZ: draw random samples from fstar\nEigen::MatrixXd predict(Eigen::MatrixXd X, Eigen::MatrixXd Y, Eigen::MatrixXd Xtest, Eigen::VectorXd sig_samps, Eigen::VectorXd rho_samps, Eigen::VectorXd tau_samps, double multiplier, int M, double tol, int nsamps) {\n    /*\n    Temporarily assumes regression = True\n    */ \n\n  //////////// PASS THE GENERATOR //////////\n\n    std::cout << \"hullo there\" << std::endl;\n\n    // Create the standard normal generator\n    normal_distribution<double> norm(0, 1);\n    std::mt19937 rng;\n    auto r_std_normal = bind(norm, rng);\n    \n    ////Number of observations in train and test\n    int Ntest =  Xtest.rows();  \n    int N =  X.rows();\n    int D =  X.cols();\n   \n\n    int n_levels = log(N / M) / log(2);\n    bool is_sym = true;\n    bool is_pd  = true;\n\n    double tau;\n    double rho; \n    double sig; \n    \n    // Sigma square and SSR\n    double sigsq; // = pow(sig, 2.0);\n    double tmpSSR;\n    \n    // Allocate fstarsamp\n    Eigen::MatrixXd fstarsamp(nsamps, Ntest);\n    Eigen::VectorXd KobsNew(N);\n    \n    for (int s = 0; s < nsamps; s++) {\n\n      sig = sig_samps(s);\n      tau = tau_samps(s);\n      rho = rho_samps(s);\n\n      if (s % 100 == 0) {\n        // printf(\"PREDICT: Sig, Tau, Rho: s = %d, %.2f \\t%.2f \\t%.2f\\n\", s, sig, tau, rho);\n      }\n\n      sigsq = pow(sig, 2.0);\n\n      SQRExponentialP1_Kernel* L  = new SQRExponentialP1_Kernel(X, N, sig, rho, tau);\n      HODLR_Tree* T = new HODLR_Tree(n_levels, tol, L); // With noise (i.e. Sigma + I/tau)\n      T->assembleTree(is_sym, is_pd);\n      T->factorize();\n\n      // VO: Should be able to do this through matrix operations\n      // AZ: cycle through the observations in the test set\n      for (int i = 0; i < Ntest; i++) {\n        ////// Sample a draw of the GP function f*|f,sig,rho,tau,x*.\n        ////// Assume a squared exponential Gaussian Process with params sigf and rho, \n        ////// based on observed function f at new test points x*.\n        Eigen::RowVectorXd Xtest_i = Xtest.row(i);\n        // Get covariance between X and Xtest\n        for (int j = 0; j < N; j++) {\n          Eigen::RowVectorXd tmp = X.row(j) - Xtest_i;\n          tmpSSR = 0.0;\n          for (int d = 0; d < D; d++) {\n            tmpSSR = tmpSSR + pow(tmp(d), 2.0);\n          }\n          KobsNew(j) = sigsq * exp(- tmpSSR * rho);\n        }\n        // Get variance at Xtest\n        double kNewNew = sigsq + 1e-8;\n        // Get posterior mean and variance of f* at point xtest(i)\n        double sdstar = pow(kNewNew - (multiplier * KobsNew.transpose() * T->solve(tau * KobsNew))(0,0), 0.5);\n        double mustar = (multiplier * KobsNew.transpose() * T->solve(tau * Y))(0,0);\n\n        auto normal_samp = r_std_normal();\n\n        fstarsamp(s, i) =  sdstar * normal_samp + mustar;\n        //std::normal_distribution<double> distribution(mustar, sdstar);\n        //fstarsamp(i) = distribution(generator);\n      }\n    }    \n    return fstarsamp;\n}\n\nvoid predict_module(py::module &m) {\n    m.def(\"predict_f\", &predict, \"predicted samples of f at new X\");\n}", "meta": {"hexsha": "a11dd5aa22e3a1519ec932d31103f8794151aed2", "size": 3299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fifa_gp/mwe_predict.cpp", "max_stars_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_stars_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fifa_gp/mwe_predict.cpp", "max_issues_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_issues_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fifa_gp/mwe_predict.cpp", "max_forks_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_forks_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.99, "max_line_length": 217, "alphanum_fraction": 0.5913913307, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6296107859843701}}
{"text": "#include <Eigen/Dense>\r\n#include <Eigen/Core>\r\n#include <Eigen/src/Core/ArithmeticSequence.h>\r\n\r\n#include <opencv2/core.hpp>\r\n#include <opencv2/opencv.hpp>\r\n\r\n#include <string.h>\r\n#include <iostream> \r\n\r\n#include \"Data.h\"\r\n#include \"ConvLayer.h\"\r\n#include \"FilterGenerator.h\"\r\n#include \"Nonlinearity.h\"\r\n#include \"MaxPool.h\"\r\n#include \"FullyConnected.h\"\r\n#include \"SoftMax.h\"\r\n\r\n\r\n\r\nvoid train(std::vector<Eigen::MatrixXd>& TRAINING_DATA, int learning_rate)\r\n{\r\n\t// create filters for convolutional layer \r\n\tint num_filters = 2;\r\n\tint filter_dim_x = 10; \r\n\tint filter_dim_y = 10; \r\n\r\n\tFilterGenerator filters(num_filters,filter_dim_x,filter_dim_y);\r\n\tfilters.create_filters(); \r\n\tstd::vector<Eigen::MatrixXd> conv_filters; \r\n\tconv_filters = filters.output_filters; \r\n\t\r\n\t// get input image dimensions\r\n\tint input_dim_x = TRAINING_DATA[0].cols(); \r\n\tint input_dim_y = TRAINING_DATA[0].rows();\r\n\tint input_dim_c = 1; \r\n\tint stride_x = 1;\r\n\tint stride_y = 1; \r\n\r\n\r\n\tConvLayer convlayer_1(input_dim_x, input_dim_y, input_dim_c, filter_dim_x, filter_dim_y, stride_x, stride_y, num_filters);\r\n\r\n\t// max pool dimensions setup \r\n\tint conv_output_dim_x = convlayer_1.GetOutputDimX();\r\n\tint conv_output_dim_y = convlayer_1.GetOutputDimY();\r\n\tint m_filter_dim_x = 2;\r\n\tint m_filter_dim_y = 2; \r\n\tint m_stride_x = 1; \r\n\tint m_stride_y = 1; \r\n\tMaxPool maxpool_1(conv_output_dim_x, conv_output_dim_y, input_dim_c, m_filter_dim_x, m_filter_dim_y, m_stride_x, m_stride_y);\r\n\r\n\t// nonlinearity \r\n\tNonlinearity sigmoid_1;\r\n\r\n\t// fully connected layer \r\n\tFullyConnected fullyconnected_1; \r\n\tint num_weight_matrices = num_filters; \r\n\tint fc_filter_dim_x = 2;\r\n\tint fc_filter_dim_y = maxpool_1.GetOutputDimX() * maxpool_1.GetOutputDimY(); \r\n\r\n\tFilterGenerator fc_weights_init(num_filters, fc_filter_dim_x, fc_filter_dim_y);\r\n\tfc_weights_init.create_filters(); \r\n\tstd::vector<Eigen::MatrixXd> fc_weights; \r\n\tfc_weights = fc_weights_init.output_filters; \r\n\t\r\n\t// soft max layer \r\n\tSoftMax softmax; \r\n\r\n\tstd::vector<int> actual_class;\r\n\tfor (int i = 0; i < 72; i++)\r\n\t{\r\n\t\tactual_class.push_back(1); \r\n\t}\r\n\r\n\tint epoch_total = 1;\r\n\tint SIZE_OF_DATASET = TRAINING_DATA.size();\r\n\r\n\tfor (int epoch = 0; epoch < epoch_total; epoch++)\r\n\t{\r\n\t\tfor (int i = 0; i < TRAINING_DATA.size(); i++)\r\n\t\t{\r\n\t\t\tprintf(\"\\nFOR IMAGE %i: \\n\", i + 1);\r\n\r\n\t\t\t// FORWARD PROP\r\n\r\n\t\t\tconvlayer_1.Forward(TRAINING_DATA[i], conv_filters);\r\n\t\t\tmaxpool_1.Forward(convlayer_1.output);\r\n\t\t\tsigmoid_1.sigmoid(maxpool_1.output);\r\n\t\t\tfullyconnected_1.Forward(sigmoid_1.sigmoid_output, fc_weights);\r\n\t\t\tsoftmax.SoftMaxLoss(fullyconnected_1.output, actual_class[i]);\r\n\t\t\t\r\n\t\t\t// BACKPROP\r\n\t\t\tsoftmax.Backprop(fullyconnected_1.output, actual_class[i]);\r\n\t\t\tfullyconnected_1.Backprop(softmax.delta_softmax, fc_weights, sigmoid_1.sigmoid_output);\r\n\t\t\tsigmoid_1.Backprop_sigmoid(fullyconnected_1.delta_FC, maxpool_1.output); \r\n\t\t\tmaxpool_1.Backprop(sigmoid_1.delta_sigmas, convlayer_1.output); \r\n\t\t\tconvlayer_1.Backprop(maxpool_1.delta_matrices, TRAINING_DATA[i]);\r\n\r\n\t\t\tfor (int i = 0; i < num_filters; i++)\r\n\t\t\t{\r\n\t\t\t\tfc_weights[i] = fc_weights[i] - learning_rate * fullyconnected_1.delta_weights[i];\r\n\t\t\t\tconv_filters[i] = conv_filters[i] - learning_rate * convlayer_1.delta_filters[i];\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\tsoftmax.SoftMaxLossTotal();\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// just calculates the loss\r\n\t\tstd::cout << \"\\nThe loss for the dataset is: \" << softmax.loss_for_dataset << std::endl; \r\n\r\n\t\t/*\r\n\t\tif (epoch_total % epoch == 10)\r\n\t\t{\r\n\t\t\tprintf(\"EPOCH:\\t %i \\tLOSS: %i\", epoch, softmax.loss_for_dataset);\r\n\t\t}\r\n\t\t*/\r\n\t\tsoftmax.accumulated_loss_values.clear();\t\t\t\t\t\t\t\t\t\t// clear values for next epoch \r\n\t\tsoftmax.SoftMaxLossTotal();\r\n\t\tsoftmax.accumulated_loss_values = { 1, 2, 3 }; \r\n\t\tstd::cout << \"\\nThe loss for the dataset is: \" << softmax.loss_for_dataset << std::endl;\r\n\r\n\t\t\r\n\t}\r\n\r\n\r\n\r\n}\r\n\r\nint main(int argv, char** argc)\r\n{\r\n\t// TEST MATRICES FOR FEEDFORWARD: \r\n\r\n\tEigen::MatrixXd matrix_1;\r\n\tmatrix_1.resize(6, 6);\r\n\tmatrix_1 << 0.1, 0.2, 0.9, 0.4, 0.3, 0.4,\r\n\t\t\t\t0.8, 0.1, 0.4, 0.9, 0.6, 0.7,\r\n\t\t\t\t0.1, 0.4, 0.2, 0.6, 0.7, 0.8,\r\n\t\t\t\t0.3, 0.2, 0.2, 0.1, 0.3, 0.5,\r\n\t\t\t\t0.7, 0.9, 0.2, 0.4, 0.7, 0.1,\r\n\t\t\t\t0.8, 0.6, 0.5, 0.2, 0.3, 0.1;\r\n\tEigen::MatrixXd matrix_2;\r\n\tmatrix_2.resize(6, 6);\r\n\tmatrix_2 << 0.1, 0.7, 0.9, 0.7, 0.3, 0.1,\r\n\t\t\t\t0.7, 0.9, 0.2, 0.4, 0.7, 0.1,\r\n\t\t\t\t0.1, 0.4, 0.2, 0.3, 0.7, 0.1,\r\n\t\t\t\t0.1, 0.1, 0.2, 0.2, 0.7, 0.1,\r\n\t\t\t\t0.8, 0.2, 0.4, 0.1, 0.1, 0.1,\r\n\t\t\t\t0.1, 0.8, 0.2, 0.1, 0.1, 0.1;\r\n\tEigen::MatrixXd matrix_3;\r\n\tmatrix_3.resize(6, 6);\r\n\tmatrix_3 << 0.1, 0.2, 0.9, 0.4, 0.3, 0.1,\r\n\t\t\t\t0.5, 0.5, 0.5, 0.5, 0.5, 0.5,\r\n\t\t\t\t0.1, 0.4, 0.3, 0.6, 0.7, 0.8,\r\n\t\t\t\t0.1, 0.3, 0.2, 0.6, 0.7, 0.3,\r\n\t\t\t\t0.8, 0.2, 0.4, 0.7, 0.3, 0.6,\r\n\t\t\t\t0.5, 0.2, 0.9, 0.4, 0.3, 0.4;\r\n\r\n\tstd::vector<Eigen::MatrixXd> input_matrices;\r\n\tinput_matrices.push_back(matrix_1);\r\n\tinput_matrices.push_back(matrix_2);\r\n\tinput_matrices.push_back(matrix_3);\r\n\t\r\n\tstd::cout << \"THE RESULTS OF TRAIN: \" << std::endl; \r\n\r\n\t\r\n\r\n\t// CALLING DATA HANDLER: \r\n\tData train_images_yes;\r\n\r\n\ttrain_images_yes.load_images(\"Cellphones/training/training/test/cracked/\");\r\n\ttrain_images_yes.set_label();\r\n\ttrain_images_yes.convert_images();\r\n\r\n\r\n\tData train_images_no;\r\n\ttrain_images_no.load_images(\"Cellphones/training/training/test/intact\");\r\n\ttrain_images_no.set_label();\r\n\t\r\n\ttrain(train_images_yes.image_matrices, 0.5);\r\n\r\n\r\n\treturn 0; \r\n}", "meta": {"hexsha": "23bf7b01f70165e31f5b6b15f011a99aeedd9882", "size": 5342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source.cpp", "max_stars_repo_name": "civdex/CNN_First_Attempt", "max_stars_repo_head_hexsha": "d443eb243b4647bc7dc2d64109973c9cecba0935", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source.cpp", "max_issues_repo_name": "civdex/CNN_First_Attempt", "max_issues_repo_head_hexsha": "d443eb243b4647bc7dc2d64109973c9cecba0935", "max_issues_repo_licenses": ["MIT"], "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.cpp", "max_forks_repo_name": "civdex/CNN_First_Attempt", "max_forks_repo_head_hexsha": "d443eb243b4647bc7dc2d64109973c9cecba0935", "max_forks_repo_licenses": ["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.5138121547, "max_line_length": 127, "alphanum_fraction": 0.6639835268, "num_tokens": 1864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422241476944, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.6295828090369037}}
{"text": "/*\nCopyright 2014, 2015 Rogier van Dalen.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** \\file\nDefine a Cartesian product of magmas.\n*/\n\n#ifndef MATH_PRODUCT_HPP_INCLUDED\n#define MATH_PRODUCT_HPP_INCLUDED\n\n#include <boost/mpl/and.hpp>\n#include <boost/mpl/not.hpp>\n\n#include <boost/utility/enable_if.hpp>\n#include <boost/functional/hash_fwd.hpp>\n\n#include \"meta/vector.hpp\"\n#include \"meta/all_of_c.hpp\"\n\n#include \"utility/returns.hpp\"\n#include \"utility/type_sequence_traits.hpp\"\n\n#include \"rime/core.hpp\"\n\n#include \"range/core.hpp\"\n#include \"range/tuple.hpp\"\n#include \"range/call_unpack.hpp\"\n#include \"range/equal.hpp\"\n#include \"range/less_lexicographical.hpp\"\n#include \"range/transform.hpp\"\n#include \"range/any_of.hpp\"\n#include \"range/all_of.hpp\"\n#include \"range/hash_range.hpp\"\n\n#include \"magma.hpp\"\n#include \"detail/tuple_helper.hpp\"\n\nnamespace math {\n\ntemplate <class Operation = void> struct with_inverse;\n\n/**\nMagma that is the Cartesian product of a number of magmas.\n\nIf \\a Inverse is with_inverse with an operation, then the inverse of this\noperation is implemented.\nIn that case, the inverse cannot be defined on that component, and therefore\nthe inverse cannot be defined for the whole product.\nIf any component of this product is an annihilator for that operation, the whole\nproduct must therefore be an annihilator.\nTherefore, with <c>with_inverse \\<Operation></c>, is_annihilator returns \\c true\nif any component returns \\c true for is_annihilator.\nSince any annihilator should be equal, \\c equal returns \\c true for two products\nthat have any annihilator for that operation.\n\nTo produce (as opposed to detect) an annihilator, each of the components must\nhave an annihilator for that operation.\n\n\\c order is not defined for the product: even if an operation implements a\nstrict weak ordering on each component, that does not implement any ordering on\nthe product.\n\nOperations on this product are associative, commutative, idempotent,\ndistributive, and the product is a semiring, if and only if each of the\ncomponents is.\n\nProducts supports Boost.Hash, if \\c boost/functional/hash.hpp is included.\nIf the hash values of the components of two products are the same, then the hash\nvalue of the two products will be the same.\n\n\\todo This is a heterogeneous tuple. Is that good enough? I think so.\nOpenFst has Power<W,n> and SparsePower<W>, which hold n or a variable number\nof components.\nThis may be useful for unknown file formats, but we'd need an any_magma, and\nthe ability to live with a performance hit.\n\n\\tparam Components\n    The list of components, given as math::over.\n\\tparam Inverse\n    (optional)\n    An inverse operation that is allowed, given as math::with_inverse.\n*/\ntemplate <class Components, class Inverse = with_inverse<>> class product;\n\ntemplate <class ComponentTags, class Inverse> struct product_tag;\n\ntemplate <class ... Components, class Inverses>\n    struct decayed_magma_tag <product <over <Components ...>, Inverses>>\n{\n    typedef product_tag <\n            over <typename decayed_magma_tag <Components>::type ...>, Inverses>\n        type;\n};\n\ntemplate <class ... Components, class Inverse>\n    class product <over <Components ...>, Inverse>\n{\npublic:\n    typedef meta::vector <Components ...> component_types;\n    typedef range::tuple <Components ...> components_type;\n    typedef Inverse inverse_specification;\n\n    static_assert (meta::all_of_c <is_magma <Components>::value ...>::value,\n        \"Not all components passed to math::product are magmas.\");\n\nprivate:\n    components_type components_;\n\n    // Private type so that it cannot be constructed exept inside this class.\n    struct dummy_type {};\n\npublic:\n    // All elements explicitly convertible: implicit constructor.\n    template <class ... Arguments, class Enable = typename boost::enable_if <\n        utility::are_constructible <\n            meta::vector <Components ...>, meta::vector <Arguments ...>>>::type>\n    explicit product (Arguments && ... arguments)\n    : components_ (std::forward <Arguments> (arguments) ...) {}\n\n    product (product const &) = default;\n    product (product &&) = default;\n\n    /**\n    Construct from a product with different component types, all of which are\n    implicitly convertible to the component types of this.\n    This constructor is implicit.\n    \\param other The product to copy.\n    */\n    template <class ... OtherComponents, class Enable = typename\n        boost::enable_if <utility::are_convertible <\n            meta::vector <OtherComponents const & ...>,\n            meta::vector <Components ...>>\n        >::type>\n    product (product <over <OtherComponents ...>, Inverse> const & other)\n    : components_ (other.components()) {}\n\n    /**\n    Construct from a product with different component types, at least one of\n    which is explicitly convertible and not implicitly convertible.\n    This constructor is explicit.\n    \\param other The product to copy.\n    \\internal \\param dummy\n        A dummy argument to distinguish this constructor from the implicit one.\n    */\n    template <class ... OtherComponents>\n    explicit product (\n        product <over <OtherComponents ...>, Inverse> const & other, typename\n        boost::enable_if <\n            tuple_helper::components_constructible_only <\n                meta::vector <Components ...>,\n                meta::vector <OtherComponents const & ...>>,\n            dummy_type>::type = dummy_type())\n    : components_ (other.components()) {}\n\n    product & operator = (product const &) = default;\n    product & operator = (product &&) = default;\n\n    components_type & components() { return components_; }\n    components_type const & components() const { return components_; }\n};\n\nnamespace callable {\n\n    template <class Inverses> struct make_product {\n        template <class ... Components>\n            product <over <Components ...>, Inverses>\n            operator() (Components const & ... components) const\n        { return product <over <Components ...>, Inverses> (components ...); }\n    };\n\n    template <class Inverses> struct make_product_over {\n        template <class Components>\n            auto operator() (Components && components) const\n        RETURNS (range::call_unpack (\n            make_product <Inverses>(), std::forward <Components> (components)));\n    };\n\n} // namespace callable\n\ntemplate <class Inverses, class ... Components>\n    inline auto make_product (Components const & ... components)\nRETURNS (callable::make_product <Inverses>() (components ...));\n\ntemplate <class Inverses, class Components>\n    inline auto make_product_over (Components && components)\nRETURNS (callable::make_product_over <Inverses>() (\n    std::forward <Components> (components)));\n\nnamespace product_detail {\n\n    template <class Type> struct is_product_tag : std::false_type {};\n    template <class ComponentTags, class Inverses>\n        struct is_product_tag <product_tag <ComponentTags, Inverses>>\n    : std::true_type {};\n\n} // namespace product_detail\n\nMATH_MAGMA_GENERATE_OPERATORS (product_detail::is_product_tag)\n\nnamespace operation {\n\n    /* Queries. */\n\n    template <class Tags, class Inverses>\n        struct is_member <product_tag <Tags, Inverses>>\n    {\n        template <class Product> auto operator() (Product const & product) const\n        RETURNS (range::all_of (\n            range::transform (product.components(), math::is_member)));\n    };\n\n    // is_annihilator.\n    /*\n    If the operation has an inverse: any component being an annihilator makes\n    the whole product an annihilator.\n    If not, then the default implementation (compare component-per-component\n    with the result of annihilator()) works.\n    */\n    template <class ComponentTags, class Operation>\n        struct is_annihilator <\n            product_tag <ComponentTags, with_inverse <Operation>>, Operation>\n    {\n        template <class Product> auto operator() (Product const & product) const\n        RETURNS (range::any_of (range::transform (\n            product.components(), callable::is_annihilator <Operation>())));\n    };\n\n    // equal.\n    // With no inverse: just compare components.\n    template <class ComponentTags>\n        struct equal <product_tag <ComponentTags, with_inverse<>>>\n    : tuple_helper::equal_components <math::callable::equal> {};\n\n    // With inverse: compare annihilators equal, otherwise compare components.\n    template <class ComponentTags, class Operation>\n        struct equal <product_tag <ComponentTags, with_inverse <Operation>>>\n    : tuple_helper::equal_if_annihilator <Operation,\n        tuple_helper::equal_components <math::callable::equal>> {};\n\n    // approximately_equal.\n    template <class ComponentTags>\n        struct approximately_equal <product_tag <ComponentTags, with_inverse<>>>\n    : tuple_helper::equal_components <math::callable::approximately_equal> {};\n\n    template <class ComponentTags, class Operation>\n        struct approximately_equal <\n            product_tag <ComponentTags, with_inverse <Operation>>>\n    : tuple_helper::equal_if_annihilator <Operation,\n        tuple_helper::equal_components <math::callable::approximately_equal>>\n    {};\n\n    // compare.\n    template <class ... ComponentTags>\n        struct compare <product_tag <over <ComponentTags ...>, with_inverse<>>,\n            typename boost::enable_if <meta::all_of_c <\n                is_implemented <compare <ComponentTags>>::value ...>>::type>\n    : tuple_helper::compare_components <math::callable::compare> {};\n\n    // With inverse: annihilators go at the end.\n    template <class ... ComponentTags, class Operation>\n        struct compare <product_tag <over <ComponentTags ...>,\n            with_inverse <Operation>>,\n            typename boost::enable_if <boost::mpl::and_ <\n                meta::all_of_c <\n                    is_implemented <compare <ComponentTags>>::value ...>,\n                // Only instantiate this if the Operation is not void.\n                // GCC 4.6 requires this, or it won't realise the the\n                // specialisation above is better.\n                boost::mpl::not_ <std::is_same <Operation, void>>\n            >>::type>\n    : tuple_helper::compare_if_annihilator <Operation,\n        tuple_helper::compare_components <math::callable::compare>> {};\n\n    namespace tuple_helper {\n\n        template <class ComponentTags, class Inverses>\n            struct get_components <product_tag <ComponentTags, Inverses>>\n        {\n            template <class Product> auto operator() (Product const & p) const\n            RETURNS (p.components());\n        };\n\n    } // namespace tuple_helper\n\n    /* Produce. */\n\n    // non_member could be implemented if all components implement it.\n    // Otherwise, what value to pick for the other components?\n\n    template <class ... Tags, class Inverses, class Operation>\n        struct identity <product_tag <over <Tags ...>, Inverses>, Operation>\n    : tuple_helper::nullary_operation <callable::make_product <Inverses>,\n        meta::vector <identity <Tags, Operation> ...>> {};\n\n    // annihilator: implemented if all components have an annihilator...\n    // (otherwise, what value to pick for the other components?)\n    template <class ... Tags, class Inverses, class Operation>\n        struct annihilator <product_tag <over <Tags ...>, Inverses>, Operation,\n        typename boost::enable_if <meta::all_of_c <\n            is_implemented <annihilator <Tags, Operation>>::value ...\n        >>::type>\n    : tuple_helper::nullary_operation <callable::make_product <Inverses>,\n        meta::vector <annihilator <Tags, Operation> ...>> {};\n\n    // ... and there is at least one component.\n    template <class Inverses, class Operation>\n        struct annihilator <product_tag <over<>, Inverses>, Operation>\n    : unimplemented {};\n\n    /* Binary operations. */\n\n    template <class ... Tags, class Inverses>\n        struct times <product_tag <over <Tags ...>, Inverses>>\n    : tuple_helper::binary_operation <callable::make_product <Inverses>,\n        meta::vector <times <Tags> ...>> {};\n\n    template <class ... Tags, class Inverses>\n        struct plus <product_tag <over <Tags ...>, Inverses>>\n    : tuple_helper::binary_operation <callable::make_product <Inverses>,\n        meta::vector <plus <Tags> ...>> {};\n\n    // is_semiring iff all components are semirings...\n    template <class ... Tags, class Inverses,\n            class Direction, class Operation1, class Operation2>\n        struct is_semiring <product_tag <over <Tags ...>, Inverses>, Direction,\n            Operation1, Operation2>\n    : meta::all_of_c <\n        is_semiring <Tags, Direction, Operation1, Operation2>::value ...> {};\n\n    // ... except when the product is empty.\n    template <class Inverses, class Direction,\n        class Operation1, class Operation2>\n    struct is_semiring <product_tag <over<>, Inverses>, Direction,\n        Operation1, Operation2>\n    : rime::false_type {};\n\n    template <class ... Tags, class Inverses,\n            class Direction, class Operation1, class Operation2>\n        struct is_distributive <product_tag <over <Tags ...>, Inverses>,\n            Direction, Operation1, Operation2>\n    : meta::all_of_c <\n        is_distributive <Tags, Direction, Operation1, Operation2>::value ...>\n    {};\n\n    template <class ... Tags,\n            class ... Components1, class ... Components2, class Inverses>\n        struct unify_type <product_tag <over <Tags ...>, Inverses>,\n            product <over <Components1 ...>, Inverses>,\n            product <over <Components2 ...>, Inverses>>\n    {\n        // Unify both underlying types separately.\n        typedef product <over <\n            typename unify_type <Tags, Components1, Components2>::type ...>,\n            Inverses> type;\n    };\n\n    // divide: only if the template parameter Inverses is with_inverse <times>.\n    template <class ... Tags, class Direction>\n        struct divide <product_tag <over <Tags ...>,\n            with_inverse <callable::times>>, Direction>\n    : tuple_helper::binary_operation <\n        callable::make_product <with_inverse <callable::times>>,\n        meta::vector <divide <Tags, Direction> ...>> {};\n\n    // minus: only if the template parameter Inverses is with_inverse <plus>.\n    template <class ... Tags, class Direction>\n        struct minus <product_tag <over <Tags ...>,\n            with_inverse <callable::plus>>, Direction>\n    : tuple_helper::binary_operation <\n        callable::make_product <with_inverse <callable::plus>>,\n        meta::vector <minus <Tags, Direction> ...>> {};\n\n    template <class ... Tags, class Direction, class Operation>\n        struct invert <product_tag <over <Tags ...>, with_inverse <Operation>>,\n            Direction, Operation>\n    : tuple_helper::unary_operation <\n        callable::make_product <with_inverse <Operation>>,\n        meta::vector <invert <Tags, Direction, Operation> ...>> {};\n\n    template <class ... Tags, class Inverse, class Operation>\n        struct reverse <product_tag <over <Tags ...>, Inverse>, Operation>\n    : tuple_helper::unary_operation <\n        callable::make_product <Inverse>,\n        meta::vector <reverse <Tags, Operation> ...>> {};\n\n    template <class ... Tags, class Inverses>\n        struct print <product_tag <over <Tags ...>, Inverses>>\n    : tuple_helper::print_components <meta::vector <Tags ...>> {};\n\n} // namespace operation\n\n// Boost.Hash support.\n\nnamespace product_detail {\n\n    // Products with inverses need to treat annihilators specially.\n    static std::size_t constexpr annihilator_hash =\n        std::size_t (0xcba51c150183b7f1 & std::size_t (-1));\n\n} // namespace product_detail\n\n// Without an inverse: just combine the hash values of the components.\ntemplate <class Components>\n    inline std::size_t hash_value (\n        product <Components, with_inverse<>> const & p)\n{ return range::hash_range (p.components()); }\n\n// With an inverse: if p is an annihilator, then return a special hash value.\ntemplate <class Components, class Operation>\n    inline std::size_t hash_value (\n        product <Components, with_inverse <Operation>> const & p)\n{\n    if (is_annihilator <Operation> (p))\n        return product_detail::annihilator_hash;\n    return range::hash_range (p.components());\n}\n\n} // namespace math\n\n#endif // MATH_PRODUCT_HPP_INCLUDED\n", "meta": {"hexsha": "e97d1a7928ef0d1324b838a2036ea1e0cd646daa", "size": 16726, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/product.hpp", "max_stars_repo_name": "rogiervd/math", "max_stars_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/product.hpp", "max_issues_repo_name": "rogiervd/math", "max_issues_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/product.hpp", "max_forks_repo_name": "rogiervd/math", "max_forks_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5391705069, "max_line_length": 80, "alphanum_fraction": 0.6807963649, "num_tokens": 3661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127566694178, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6294687538208061}}
{"text": "/*\n\tCopyright (C) 2003-2013 by David White <davewx7@gmail.com>\n\t\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"graphics.hpp\"\n#include \"rectangle_rotator.hpp\"\n#include <math.h>\n#include <cmath>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n#include \"unit_test.hpp\"\n\n#if defined(_MSC_VER)\n#include <boost/math/special_functions/round.hpp>\n#define bmround\tboost::math::round\n#else\n#define bmround\tstd::round\n#endif\n\nvoid rotate_rect(GLshort center_x, GLshort center_y, float rotation, GLshort* rect_vertexes){\n\n\tpoint p;\n\t\n\tfloat rotate_radians = (rotation * M_PI)/180;\n\t\n\t//rect r(rect_vertexes[0],rect_vertexes[1],rect_vertexes[4]-rect_vertexes[0],rect_vertexes[5]-rect_vertexes[1]);\n\t\n\tp = rotate_point_around_origin_with_offset( rect_vertexes[0], rect_vertexes[1], rotate_radians, center_x, center_y );\n\trect_vertexes[0] = p.x;\n\trect_vertexes[1] = p.y;\n\t\n\tp = rotate_point_around_origin_with_offset( rect_vertexes[2], rect_vertexes[3], rotate_radians, center_x, center_y );\n\trect_vertexes[2] = p.x;\n\trect_vertexes[3] = p.y;\n\t\n\tp = rotate_point_around_origin_with_offset( rect_vertexes[4], rect_vertexes[5], rotate_radians, center_x, center_y );\n\trect_vertexes[4] = p.x;\n\trect_vertexes[5] = p.y;\n\t\n\tp = rotate_point_around_origin_with_offset( rect_vertexes[6], rect_vertexes[7], rotate_radians, center_x, center_y );\n\trect_vertexes[6] = p.x;\n\trect_vertexes[7] = p.y;\n\t\n}\n\n\nvoid rotate_rect(const rect& r, GLfloat angle, GLshort* output){\n\t\n\tpoint offset;\n\toffset.x = r.x() + r.w()/2;\n\toffset.y = r.y() + r.h()/2;\n\n\tpoint p;\n\n\tp = rotate_point_around_origin_with_offset( r.x(), r.y(), angle, offset.x, offset.y );\n\toutput[0] = p.x;\n\toutput[1] = p.y;\n\n\tp = rotate_point_around_origin_with_offset( r.x2(), r.y(), angle, offset.x, offset.y );\n\toutput[2] = p.x;\n\toutput[3] = p.y;\n\n\tp = rotate_point_around_origin_with_offset( r.x2(), r.y2(), angle, offset.x, offset.y );\n\toutput[4] = p.x;\n\toutput[5] = p.y;\n\n\tp = rotate_point_around_origin_with_offset( r.x(), r.y2(), angle, offset.x, offset.y );\n\toutput[6] = p.x;\n\toutput[7] = p.y;\n\n}\n\npoint rotate_point_around_origin_with_offset(int x1, int y1, float alpha, int u1, int v1){\n\t\n\tpoint beta = rotate_point_around_origin(x1 - u1, y1 - v1, alpha);\n\t\n\tbeta.x += u1;\n\tbeta.y += v1;\n\t\n\treturn beta;\n}\n\npoint rotate_point_around_origin(int x1, int y1, float alpha){\n\n\tpoint beta;\n\t\n\t/*   //we actually don't need the initial theta and radius.  This is why:\n\tx2 = R * (cos(theta) * cos(alpha) + sin(theta) * sin(alpha))\n\ty2 = R * (sin(theta) * cos(alpha) + cos(theta) * sin(alpha));\n\tbut\n\tR * (cos(theta)) = x1\n\tR * (sin(theta)) = x2\n\tthis collapses the above to:  */\n\n\tbeta.x = bmround(x1 * cos(alpha)) - bmround(y1 * sin(alpha));\n\tbeta.y = bmround(y1 * cos(alpha)) + bmround(x1 * sin(alpha));\n\n\treturn beta;\n}\n\n/*UNIT_TEST(rotate_test) {\n\tstd::cerr << \"rotating_a_point \\n\";\n\tstd::cerr << rotate_point_around_origin( 1000, 1000, (M_PI/2)).to_string() << \"\\n\";  //Should be -1000,1000 \n\tstd::cerr << rotate_point_around_origin_with_offset( 11000, 1000, (M_PI/2), 10000,0).to_string() << \"\\n\"; //Should be 9000,1000 \n\t\n\tGLshort myOutputData[8];\n\trect r(10, 10, 20, 30);\n\trotate_rect(r, (M_PI*2), myOutputData);\n\t\n\tstd::cerr << \"Outputting point list \\n\";\n\tfor(int i=0;i<8;++i){\n\t\tstd::cerr << myOutputData[i] << \" \";\n\t\tif(i%2){ std::cerr << \"\\n\";}\n\t}\n}*/\n\n\nBENCHMARK(rect_rotation) {\n\trect r(10, 10, 20, 30);\n\tGLshort output[8];\n\tBENCHMARK_LOOP {\n\t\trotate_rect(r, 75, output);\n\t}\n}\n", "meta": {"hexsha": "7c050d9bfdedc83ee1a83577e10ee5c534650625", "size": 4050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rectangle_rotator.cpp", "max_stars_repo_name": "sweetkristas/anura", "max_stars_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rectangle_rotator.cpp", "max_issues_repo_name": "sweetkristas/anura", "max_issues_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rectangle_rotator.cpp", "max_forks_repo_name": "sweetkristas/anura", "max_forks_repo_head_hexsha": "5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.347826087, "max_line_length": 129, "alphanum_fraction": 0.6918518519, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6294687450489075}}
{"text": "\n#include <iostream>\n#include <Eigen/Geometry>\n#include <bench/BenchTimer.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n#ifndef SCALAR\n#define SCALAR float\n#endif\n\n#ifndef SIZE\n#define SIZE 8\n#endif\n\ntypedef SCALAR Scalar;\ntypedef NumTraits<Scalar>::Real RealScalar;\ntypedef Matrix<RealScalar,Dynamic,Dynamic> A;\ntypedef Matrix</*Real*/Scalar,Dynamic,Dynamic> B;\ntypedef Matrix<Scalar,Dynamic,Dynamic> C;\ntypedef Matrix<RealScalar,Dynamic,Dynamic> M;\n\ntemplate<typename Transformation, typename Data>\nEIGEN_DONT_INLINE void transform(const Transformation& t, Data& data)\n{\n  EIGEN_ASM_COMMENT(\"begin\");\n  data = t * data;\n  EIGEN_ASM_COMMENT(\"end\");\n}\n\ntemplate<typename Scalar, typename Data>\nEIGEN_DONT_INLINE void transform(const Quaternion<Scalar>& t, Data& data)\n{\n  EIGEN_ASM_COMMENT(\"begin quat\");\n  for(int i=0;i<data.cols();++i)\n    data.col(i) = t * data.col(i);\n  EIGEN_ASM_COMMENT(\"end quat\");\n}\n\ntemplate<typename T> struct ToRotationMatrixWrapper\n{\n  enum {Dim = T::Dim};\n  typedef typename T::Scalar Scalar;\n  ToRotationMatrixWrapper(const T& o) : object(o) {}\n  T object;\n};\n\ntemplate<typename QType, typename Data>\nEIGEN_DONT_INLINE void transform(const ToRotationMatrixWrapper<QType>& t, Data& data)\n{\n  EIGEN_ASM_COMMENT(\"begin quat via mat\");\n  data = t.object.toRotationMatrix() * data;\n  EIGEN_ASM_COMMENT(\"end quat via mat\");\n}\n\ntemplate<typename Scalar, int Dim, typename Data>\nEIGEN_DONT_INLINE void transform(const Transform<Scalar,Dim,Projective>& t, Data& data)\n{\n  data = (t * data.colwise().homogeneous()).template block<Dim,Data::ColsAtCompileTime>(0,0);\n}\n\ntemplate<typename T> struct get_dim { enum { Dim = T::Dim }; };\ntemplate<typename S, int R, int C, int O, int MR, int MC>\nstruct get_dim<Matrix<S,R,C,O,MR,MC> > { enum { Dim = R }; };\n\ntemplate<typename Transformation, int N>\nstruct bench_impl\n{\n  static EIGEN_DONT_INLINE void run(const Transformation& t)\n  {\n    Matrix<typename Transformation::Scalar,get_dim<Transformation>::Dim,N> data;\n    data.setRandom();\n    bench_impl<Transformation,N-1>::run(t);\n    BenchTimer timer;\n    BENCH(timer,10,100000,transform(t,data));\n    cout.width(9);\n    cout << timer.best() << \" \";\n  }\n};\n\n\ntemplate<typename Transformation>\nstruct bench_impl<Transformation,0>\n{\n  static EIGEN_DONT_INLINE void run(const Transformation&) {}\n};\n\ntemplate<typename Transformation>\nEIGEN_DONT_INLINE void bench(const std::string& msg, const Transformation& t)\n{\n  cout << msg << \" \";\n  bench_impl<Transformation,SIZE>::run(t);\n  std::cout << \"\\n\";\n}\n\nint main(int argc, char ** argv)\n{\n  Matrix<Scalar,3,4> mat34; mat34.setRandom();\n  Transform<Scalar,3,Isometry> iso3(mat34);\n  Transform<Scalar,3,Affine> aff3(mat34);\n  Transform<Scalar,3,AffineCompact> caff3(mat34);\n  Transform<Scalar,3,Projective> proj3(mat34);\n  Quaternion<Scalar> quat;quat.setIdentity();\n  ToRotationMatrixWrapper<Quaternion<Scalar> > quatmat(quat);\n  Matrix<Scalar,3,3> mat33; mat33.setRandom();\n\n  cout.precision(4);\n  std::cout\n     << \"N          \";\n  for(int i=0;i<SIZE;++i)\n  {\n    cout.width(9);\n    cout << i+1 << \" \";\n  }\n  cout << \"\\n\";\n\n  bench(\"matrix 3x3\", mat33);\n  bench(\"quaternion\", quat);\n  bench(\"quat-mat  \", quatmat);\n  bench(\"isometry3 \", iso3);\n  bench(\"affine3   \", aff3);\n  bench(\"c affine3 \", caff3);\n  bench(\"proj3     \", proj3);\n}\n", "meta": {"hexsha": "a7c8c2a51cb66b2a58388e7f310f3e02501ae3f7", "size": 3302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/geometry.cpp", "max_stars_repo_name": "eundersander/bps-nav", "max_stars_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:17:14.000Z", "max_issues_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/geometry.cpp", "max_issues_repo_name": "eundersander/bps-nav", "max_issues_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T21:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:46:40.000Z", "max_forks_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/geometry.cpp", "max_forks_repo_name": "eundersander/bps-nav", "max_forks_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-27T17:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:00:06.000Z", "avg_line_length": 26.2063492063, "max_line_length": 93, "alphanum_fraction": 0.7044215627, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6294687406683618}}
{"text": "#include \"CurveFitting.hpp\"\n#include <boost/algorithm/string.hpp>\n#include <fstream>\n#include <iostream>\n#include <string>\n\nint main(int argc, char** argv)\n{\n    try{\n        if(argc!=2){ throw std::string(\"too few args.\"); }\n        std::string filename(argv[1]);\n        std::ifstream ifs(filename);\n        if(!ifs.is_open()){ throw std::string(\"cannot open file\")+filename; }\n\n        std::vector<double> x;\n        std::vector<double> y;\n        std::string line;\n\n        for(int i=0; std::getline(ifs,line); i++){\n            std::vector<std::string> elements;\n            boost::split(elements, line, boost::is_any_of(\",\"));\n            if(elements.size()==1){\n                x.push_back(i);\n                y.push_back(std::stod(elements[0]));\n            }else if(elements.size()==2){\n                x.push_back(std::stod(elements[0]));\n                y.push_back(std::stod(elements[1]));\n            }else{\n                throw std::string(\"bad file format.\");\n            }\n        }\n\n        {\n            std::cout << \"---Line Fitting---\" << std::endl;\n            LineFitting line_fit(x,y);\n\n            Eigen::VectorXd x_val(line_fit.num_param());\n            x_val.setOnes();\n            line_fit.solve(x_val);\n            std::cout << x_val << std::endl;\n\n            std::vector<double> vec_x(x_val.data(),x_val.data()+line_fit.num_param());\n            std::cout << \"residual(vec_x)=\" << line_fit.residual(vec_x) << std::endl;\n        }\n\n        {\n            std::cout << \"---Polynomial Fitting---\" << std::endl;\n            PolynomialFitting poly_fit(x,y,3);\n\n            std::vector<double> x_val(poly_fit.num_param(),1.0);\n            poly_fit.solve(x_val);\n            std::cout << Eigen::Map<Eigen::VectorXd>(x_val.data(),x_val.size()) << std::endl;\n\n            std::cout << \"residual(x_val)=\" << poly_fit.residual(x_val) << std::endl;\n        }\n\n        {\n            std::cout << \"---Catenary Fitting---\" << std::endl;\n            CatenaryFitting catenary_fit(x,y);\n\n            std::vector<double> x_val{3.5, 9.5, -20.0};\n            catenary_fit.solve(x_val);\n            std::cout << Eigen::Map<Eigen::VectorXd>(x_val.data(),x_val.size()) << std::endl;\n\n            std::cout << \"residual(x_val)=\" << catenary_fit.residual(x_val) << std::endl;\n        }\n        {\n            std::cout << \"---Exponential Fitting---\" << std::endl;\n            ExponentialFitting exponential_fit(x,y);\n\n            Eigen::VectorXd x_val(exponential_fit.num_param());\n            x_val << 10.0, 2.0, 0.0, 0.0;\n            exponential_fit.solve(x_val);\n            std::cout << x_val << std::endl;\n\n            std::vector<double> vec_x(x_val.data(),x_val.data()+exponential_fit.num_param());\n            std::cout << \"residual(vec_x)=\" << exponential_fit.residual(vec_x) << std::endl;\n        }\n        {\n            std::cout << \"---InvCycloid Fitting---\" << std::endl;\n            InvCycloidFitting invCycloid_fit(y,x); /// Inv -> x y exchanging!\n\n            Eigen::VectorXd x_val(invCycloid_fit.num_param());\n            x_val << 3.0, 0.0, 0.0;\n            invCycloid_fit.solve(x_val);\n            std::cout << x_val << std::endl;\n\n            std::vector<double> vec_x(x_val.data(),x_val.data()+invCycloid_fit.num_param());\n            std::cout << \"residual(vec_x)=\" << invCycloid_fit.residual(vec_x) << std::endl;\n        }\n    }catch(std::string message){\n        std::cout << message << std::endl;\n        std::cout << \"Usage: CurveFitting data_file.csv\" << std::endl;\n    }\n\n}\n", "meta": {"hexsha": "15bd4dff69a58dc14ea30c3af2c0fda3d6ec7bae", "size": 3504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CurveFittingMain.cpp", "max_stars_repo_name": "Hiroshi-Nakamura/CurveFitting", "max_stars_repo_head_hexsha": "f170441ad7e400d5d51607a04021916c75d05d47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-02T17:09:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-02T17:09:17.000Z", "max_issues_repo_path": "CurveFittingMain.cpp", "max_issues_repo_name": "Hiroshi-Nakamura/CurveFitting", "max_issues_repo_head_hexsha": "f170441ad7e400d5d51607a04021916c75d05d47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CurveFittingMain.cpp", "max_forks_repo_name": "Hiroshi-Nakamura/CurveFitting", "max_forks_repo_head_hexsha": "f170441ad7e400d5d51607a04021916c75d05d47", "max_forks_repo_licenses": ["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.1237113402, "max_line_length": 93, "alphanum_fraction": 0.5276826484, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6294687401180917}}
{"text": "/**\n * Exercise 8 : Read in a gph-file, interpretes it as a Steiner-problem and solves it.\n *\n * @author FirstSanny\n */\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <utility>\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include \"Steiner.h\"\n#include \"GraphChecker.h\"\n\n// Constants\nnamespace {\n\n\tconst char* FILEEND = \".gph\";\n\n}\n\n// declaring print\nusing std::cout;\nusing std::endl;\nusing std::flush;\nusing std::cerr;\nusing std::string;\n\n// declaring types\nnamespace po = boost::program_options;\n\n/** Parsing the arguments given via command line */\npo::variables_map parseCommandLine(po::options_description desc, int argn,\n\t\tchar* argv[]) {\n\tdesc.add_options()//\n\t\t\t(\"help,h\", \"produce help message\")//\n\t\t\t(\"start_node,sn\", po::value<std::vector<int >>(),\"node, where to start\")//\n\t\t\t(\"input-file\", po::value<string>(), \"input file\");\n\tpo::positional_options_description p;\n\tp.add(\"input-file\", 1);\n\tp.add(\"start_node\", -1);\n\tpo::variables_map vm;\n\tpo::store(\n\t\t\tpo::command_line_parser(argn, argv).options(desc).positional(p).run(),\n\t\t\tvm);\n\tpo::notify(vm);\n\treturn vm;\n}\n\n/** Reading in a Graphfile, computes the Steiner */\nint main(int argn, char *argv[]) {\n\tboost::timer::auto_cpu_timer t;\n\tif (argn <= 1) {\n\t\tcerr << \"ERROR : There was no filename\" << endl;\n\t\treturn 1;\n\t}\n\n\tpo::options_description desc(\"Allowed options\");\n\tpo::variables_map vm = parseCommandLine(desc, argn, argv);\n\n\tif (vm.count(\"help\")) {\n\t    cout << desc << \"\\n\";\n\t    return 1;\n\t}\n\n\tstd::ifstream fileStream;\n\tif(vm.count(\"input-file\") == 0){\n\t\tcerr << \"No input-file was given!\" << endl;\n\t\treturn 1;\n\t}\n\n\tstd::vector<int > startnodes;\n\tif(vm.count(\"start_node\") == 0){\n\t\tcout << \"using default startnode 2\" << endl;\n\t\tstartnodes = std::vector<int >();\n\t\tstartnodes.push_back(2);\n\t} else {\n\t\tstartnodes = vm[\"start_node\"].as<std::vector<int >>();\n\t}\n\n\n\tstring filename = vm[\"input-file\"].as<string >();\n\tif(filename.find(FILEEND) == std::string::npos){\n\t\tfilename += FILEEND;\n\t}\n\tcout << \"Going to parse the file \" << filename << endl;\n\tfileStream.open(filename.c_str(), std::ios::in);\n\n\tif ( (fileStream.rdstate()) != 0 ){\n\t\tstd::perror(\"ERROR : Encoutered Problem opening file\");\n\t\treturn 1;\n\t}\n\n\tstring line;\n\n\tunsigned int edgeCount;\n\tunsigned int vertexCount;\n\n\tif(std::getline(fileStream, line)){\n\t\tsscanf(line.c_str(), \"%d %d\", &vertexCount, &edgeCount);\n\t\tcout << \"Vertexcount: \" << vertexCount << endl;\n\t\tcout << \"Edgecount: \" << edgeCount << endl;\n\t\tline.clear();\n\t\tvertexCount++;\n\t} else {\n\t\tcerr << \"ERROR : File was empty\" << endl;\n\t\treturn 1;\n\t}\n\n\tEdges* edges = new Edges(edgeCount);\n\tWeights* weights = new Weights(edgeCount);\n\n\tcout << \"Reading edges...\" << flush;\n\tint i = 0;\n\twhile (getline(fileStream, line)) {\n\t\tint start;\n\t\tint end;\n\t\tdouble weight;\n\t\tint count = sscanf(line.c_str(), \"%d %d %lf\", &start, &end, &weight);\n\t\tif (count != 3) {\n\t\t\tline.clear();\n\t\t\tcontinue;\n\t\t}\n\t\tedges->at(i) = std::make_pair(start, end);\n\t\tweights->at(i) = weight;\n\t\ti++;\n\t\tline.clear();\n\t}\n\tcout << \"done\" << endl << endl;\n\n\tSteiner** steiners = new Steiner*[startnodes.size()];\n\tcout << \"Solves Steiner problem for startnodes \";\n\tfor(unsigned int i = 0; i < startnodes.size(); i++){\n\t\tcout << startnodes[i];\n\t\tif(i != startnodes.size() - 1){\n\t\t\tcout << \", \";\n\t\t} else {\n\t\t\tcout << endl;\n\t\t}\n\t}\n\t#pragma omp parallel for\n\tfor(unsigned int i = 0; i < startnodes.size(); i++){\n\t\tsteiners[i] = new Steiner();\n\t\tsteiners[i]->steiner(vertexCount, edges, *weights, startnodes[i]);\n\t\tcout << \"Objective value of Steiner-tree for startnode \" << startnodes[i] << \": \" << steiners[i]->getWeight() << endl;\n\t}\n\n\tSteiner* s = steiners[0];\n\tint node = startnodes[0];\n\tint weight = s->getWeight();\n\tcout << \"Searching the one with least weight...\" << flush;\n\tfor(unsigned int i = 0; i < startnodes.size(); i++){\n\t\tif(weight > steiners[i]->getWeight()){\n\t\t\ts = steiners[i];\n\t\t\tnode = startnodes[i];\n\t\t\tweight = steiners[i]->getWeight();\n\t\t}\n\t}\n\tcout << \"done\" << endl;\n\tcout << \"It's the one with startnode \" << node << endl << endl;\n\n\n\tcout << \"Checking for cycle...\" << flush;\n\tEdges steinerEdges = s->getEdges();\n\tGraphChecker* checker = new GraphChecker(steinerEdges, s->getNodes());\n\tif(checker->hasCycle()){\n\t\tcout << \"failed\" << endl;\n\t\treturn 1;\n\t}\n\tcout << \"passed\" << endl;\n\n\tcout << \"Checking if graph is connected...\" << flush;\n\tif(!checker->isConnected()){\n\t\tcout << \"failed\" << endl;\n\t\treturn 1;\n\t}\n\tcout << \"passed\" << endl << endl;\n\n\tcout << \"Edges:\" << endl;\n\tfor(unsigned int i = 0; i < steinerEdges.size(); i++){\n\t\tEdge edge = steinerEdges[i];\n\t\tcout << edge.first << \" \" << edge.second << endl;\n\t}\n\n\tdelete edges;\n\tdelete weights;\n\tdelete checker;\n\tfor(unsigned int i = 0; i < startnodes.size(); i++){\n\t\tdelete steiners[i];\n\t}\n\tdelete [] steiners;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "cd2dae304bae4f2eb314fb16720bf70816305d3b", "size": 4800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sanny/ex8/src/c/ex8.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Sanny/ex8/src/c/ex8.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Sanny/ex8/src/c/ex8.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 24.4897959184, "max_line_length": 120, "alphanum_fraction": 0.6289583333, "num_tokens": 1364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6294632900202872}}
{"text": "#include <catch/catch2.hpp>\n\n#include <orient/from_quaternion.hpp>\n\n#include <Eigen/Geometry>\n#include <gtsam/base/numericalDerivative.h>\n#include <gtsam/geometry/Rot3.h>\n\nTEST_CASE(\"rotationMatrixFromQuaternion\"){\n  Eigen::Quaterniond eq;\n  SECTION(\"zero_angle\"){\n    Eigen::Vector3d u = Eigen::Vector3d::Random();\n    u *= u.squaredNorm();\n    eq = Eigen::AngleAxisd{0.f, u};\n  }\n  SECTION(\"almost_zero_angle\"){\n    Eigen::Vector3d u = Eigen::Vector3d::Random();\n    u *= u.squaredNorm();\n    eq = Eigen::AngleAxisd{1e-10, u};\n  }\n  SECTION(\"random\"){\n    eq = Eigen::Quaterniond::UnitRandom();\n  }\n  Eigen::Vector4d q;\n  q << eq.w(), eq.x(), eq.y(), eq.z();\n  Eigen::Matrix3d expected = eq.toRotationMatrix();\n  Eigen::Matrix3d actual = orient::rotationMatrixFromQuaternion(q);\n  CHECK( actual.isApprox( expected ) );\n}\n\nTEST_CASE(\"rotationMatrixFromQuaternion_derivative\")\n{\n  Eigen::Quaterniond eq;\n  SECTION(\"zero_angle\"){\n    Eigen::Vector3d u = Eigen::Vector3d::Random();\n    u *= u.squaredNorm();\n    eq = Eigen::AngleAxisd{0.f, u};\n  }\n  SECTION(\"almost_zero_angle\"){\n    Eigen::Vector3d u = Eigen::Vector3d::Random();\n    u *= u.squaredNorm();\n    eq = Eigen::AngleAxisd{1e-10, u};\n  }\n  SECTION(\"random\"){\n    eq = Eigen::Quaterniond::UnitRandom();\n  }\n\n  Eigen::Vector4d q;\n  q << eq.w(), eq.x(), eq.y(), eq.z();\n\n  auto num = gtsam::numericalDerivative11(orient::rotationMatrixFromQuaternion<double>, q);\n  const auto [v, J] = orient::rotationMatrixFromQuaternionWD(q);\n  CHECK( v.isApprox(orient::rotationMatrixFromQuaternion(q)) );\n  CHECK( J.isApprox( num, 1e-9) );\n}\n\nTEST_CASE(\"angleAxisFromQuaternion\")\n{\n  Eigen::Quaterniond eq;\n  SECTION(\"zero_angle\"){\n    Eigen::Vector3d u = Eigen::Vector3d::Random();\n    u *= u.squaredNorm();\n    eq = Eigen::AngleAxisd{0.f, u};\n  }\n  SECTION(\"almost_zero_angle\"){\n    Eigen::Vector3d u = Eigen::Vector3d::Random();\n    u *= u.squaredNorm();\n    eq = Eigen::AngleAxisd{1e-11, u};\n  }\n  SECTION(\"almost_zero_angle\"){\n    Eigen::Vector3d u = Eigen::Vector3d::Random();\n    u *= u.squaredNorm();\n    eq = Eigen::AngleAxisd{M_PI/4, u};\n  }\n  SECTION(\"random\"){\n    eq = Eigen::Quaterniond::UnitRandom();\n  }\n  Eigen::Vector4d q;\n  q << eq.w(), eq.x(), eq.y(), eq.z();\n\n  Eigen::AngleAxisd eaa{eq}; \n  Eigen::Vector3d expected = eaa.angle() * eaa.axis();\n  Eigen::Vector3d actual = orient::angleAxisFromQuaternion(q);\n\n  Eigen::Matrix3d eR = gtsam::Rot3::Rodrigues(expected).matrix();\n  Eigen::Matrix3d aR = gtsam::Rot3::Rodrigues(actual).matrix();\n  CHECK( aR.isApprox(eR, 1e-9) );\n}\n\nTEST_CASE(\"angleAxisFromQuaternion_derivative\")\n{\n  Eigen::Quaterniond eq;\n  SECTION(\"almost_zero_angle\"){\n    Eigen::Vector3d u = Eigen::Vector3d::Random();\n    u *= u.squaredNorm();\n    eq = Eigen::AngleAxisd{1e-10, u};\n  }\n  SECTION(\"random\"){\n    eq = Eigen::Quaterniond::UnitRandom();\n  }\n  Eigen::Vector4d q;\n  q << eq.w(), eq.x(), eq.y(), eq.z();\n\n  auto num = gtsam::numericalDerivative11(orient::angleAxisFromQuaternion<double>, q);\n  const auto [v, J] = orient::angleAxisFromQuaternionWD(q);\n  CHECK( v.isApprox( orient::angleAxisFromQuaternion(q)) );\n  CHECK( J.isApprox( num, 1e-9) );\n}\n", "meta": {"hexsha": "76fd1e71e8d3a0480b439d80649375ecceaf3677", "size": 3139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/from_quaternion_test.cpp", "max_stars_repo_name": "Eskilade/orient", "max_stars_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T07:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T09:23:29.000Z", "max_issues_repo_path": "test/from_quaternion_test.cpp", "max_issues_repo_name": "Eskilade/orient", "max_issues_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T02:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T01:42:47.000Z", "max_forks_repo_path": "test/from_quaternion_test.cpp", "max_forks_repo_name": "Eskilade/orient", "max_forks_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T04:26:22.000Z", "avg_line_length": 28.7981651376, "max_line_length": 91, "alphanum_fraction": 0.6533928003, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6294632724113646}}
{"text": "#include <mylib.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nnamespace mylib\n{\n    float calculate()\n    {\n        using Eigen::Vector3f;\n        return Vector3f{1,0,0}.cross(Vector3f{0,1,0}).dot(Vector3f{0,0,2});\n    }\n}", "meta": {"hexsha": "69c3932916518f5371573d26c87efab5b5a42486", "size": 228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/lib-and-exe/mylib/src/mylib.cpp", "max_stars_repo_name": "thautwarm/clang-build", "max_stars_repo_head_hexsha": "79cc6bd8e17a328d9e6a0fbdada2ba88600423aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-03-09T20:02:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-21T21:38:13.000Z", "max_issues_repo_path": "test/lib-and-exe/mylib/src/mylib.cpp", "max_issues_repo_name": "thautwarm/clang-build", "max_issues_repo_head_hexsha": "79cc6bd8e17a328d9e6a0fbdada2ba88600423aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 131.0, "max_issues_repo_issues_event_min_datetime": "2018-03-09T20:40:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T23:20:59.000Z", "max_forks_repo_path": "test/lib-and-exe/mylib/src/mylib.cpp", "max_forks_repo_name": "thautwarm/clang-build", "max_forks_repo_head_hexsha": "79cc6bd8e17a328d9e6a0fbdada2ba88600423aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-15T12:55:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T00:23:55.000Z", "avg_line_length": 17.5384615385, "max_line_length": 75, "alphanum_fraction": 0.6184210526, "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625088705931, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.6294493785064387}}
{"text": "#ifndef GRAPHCLASS\n#define GRAPHCLASS\n\n#include \"graph_node.hpp\"\n\n#include <Eigen/Dense>\n#include <memory>\n#include <stddef.h>\n#include <vector>\n\nclass UndirectedGraph {\npublic:\n  // constructors\n  UndirectedGraph() = delete;\n  UndirectedGraph(const size_t num_nodes, const double lower_weight,\n                  const double upper_weight, const double vertex_prob,\n                  const int max_trials); // random initialization\n  UndirectedGraph(\n      const size_t num_nodes, const double lower_weight,\n      const double upper_weight, const double vertex_prob,\n      const std::string path_to_weights_file); // vertex initialization based on\n                                               // given weights file\n\n  // destructors\n  ~UndirectedGraph() = default;\n\n  // methods\n  double get_shortest_path_costs() const;\n  double get_avg_vertex_costs() const;\n  std::vector<size_t> get_shortest_path_idxs() const;\n  void print_shortest_path_idxs() const;\n  void print_weight_matrix() const;\n  bool is_connected() const;\n  void find_path(const int &start_idx, const int &finish_idx);\n\nprivate:\n  void create_random_graph();\n  void create_graph_based_on_file();\n  void calculate_avg_vertex_weights();\n  bool valid_start_end_nodes(const int &start_node_idx,\n                             const int &end_node_idx);\n\n  double lower_vertex_weight_;\n  double upper_vertex_weight_;\n  double vertex_prob_;\n  double avg_vertex_cost_;\n  double shortest_path_cost_;\n  size_t num_nodes_;\n  size_t num_edges_;\n  bool dijkstra_run_;\n  Eigen::MatrixXd\n      vertex_weights_; // every row and column describes a node, the values\n                       // within the matrix are the vertex weights\n  Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic> connection_matrix_;\n  std::vector<std::shared_ptr<GraphNode>> graph_nodes_;\n  std::vector<std::shared_ptr<GraphNode>> shortest_path_nodes_;\n  std::vector<int> shortest_path_idxs_;\n};\n\n#endif /* GRAPHCLASS */", "meta": {"hexsha": "9a67827514109914706659c064585d9c2a471304", "size": 1941, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/graph_utils/graph_class.hpp", "max_stars_repo_name": "jweber94/dijkstras_shortest_path", "max_stars_repo_head_hexsha": "ec175081895b5bca924c7c98d403fa61db59b992", "max_stars_repo_licenses": ["MIT"], "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/graph_utils/graph_class.hpp", "max_issues_repo_name": "jweber94/dijkstras_shortest_path", "max_issues_repo_head_hexsha": "ec175081895b5bca924c7c98d403fa61db59b992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/graph_utils/graph_class.hpp", "max_forks_repo_name": "jweber94/dijkstras_shortest_path", "max_forks_repo_head_hexsha": "ec175081895b5bca924c7c98d403fa61db59b992", "max_forks_repo_licenses": ["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.35, "max_line_length": 80, "alphanum_fraction": 0.7161257084, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6294268875886628}}
{"text": "#pragma once \n#include \"binomials.hpp\"\n#include <NTL/ZZ.h>\n#include <NTL/RR.h>\n#include <iomanip>\n\n/***************************Classic ISDs***************************************/\n\ndouble isd_log_cost_classic_BJMM_approx(const uint32_t n, \n                                        const uint32_t k,\n                                        const uint32_t t) {\n    return ((double)t) * - log((1.0 - (double) k / (double) n)) / log(2);\n}\n\n// computes the probability of a random k * k being invertible\nconst NTL::RR log_probability_k_by_k_is_inv(const NTL::RR &k) {\n    NTL::RR log_pinv = NTL::RR(0.5);\n    for(long i = 2 ; i <=k ; i++){\n        log_pinv = log_pinv * (NTL::RR(1) - NTL::power2_RR(-i));\n    }\n    return NTL::log(log_pinv);\n}\n\nconst NTL::RR probability_k_by_k_is_inv(const NTL::RR &k) {\n    NTL::RR log_pinv = NTL::RR(0.5);\n    for(long i = 2 ; i <=k ; i++){\n        log_pinv = log_pinv * (NTL::RR(1) - NTL::power2_RR(-i));\n    }\n    return log_pinv;\n}\n\nconst NTL::RR classic_rref_red_cost(const NTL::RR &n, const NTL::RR & r){\n    /* simple reduced row echelon form transform, as it is not likely to be the \n     * bottleneck */\n    NTL::RR k = n-r;\n    return r*r*n/NTL::RR(2) + \n           (n*r)/NTL::RR(2) - \n           r*r*r / NTL::RR(6) +\n           r*r +\n           r / NTL::RR(6) - NTL::RR(1);\n}\n\nconst NTL::RR classic_IS_candidate_cost(const NTL::RR &n, const NTL::RR & r){\n    return classic_rref_red_cost(n,r)/probability_k_by_k_is_inv(r) + r*r;\n}\n\nconst NTL::RR Fin_Send_rref_red_cost(const NTL::RR &n,\n                                     const NTL::RR &r,\n                                     const NTL::RR l){\n    /* reduced size reduced row echelon form transformation, only yields an\n     * (r-l) sized identity matrix */\n    NTL::RR k = n-r;\n    return  - l*l*l / NTL::RR(3) \n            - l*l*n / NTL::RR(2) \n            + l*l*r / NTL::RR(2) \n            - 3*l*l / NTL::RR(2) \n            - 3*l*n / NTL::RR(2) \n            +   l*r / NTL::RR(2) \n            -  13*l / NTL::RR(6) \n            + n*r*r / NTL::RR(2) \n            +   n*r / NTL::RR(2) \n            - r*r*r / NTL::RR(6) \n            +   r*r \n            +     r / NTL::RR(6) \n            - NTL::RR(1);\n}\n\nconst NTL::RR Fin_Send_IS_candidate_cost(const NTL::RR &n,\n                                         const NTL::RR &r,\n                                         const NTL::RR &l){\n    return  Fin_Send_rref_red_cost(n,r,l)/probability_k_by_k_is_inv(r-l) + r*r;\n}\n\ndouble isd_log_cost_classic_Prange(const uint32_t n, \n                                   const uint32_t k,\n                                   const uint32_t t) {\n   NTL::RR n_real = NTL::RR(n);\n   NTL::RR k_real = NTL::RR(k);\n   NTL::RR t_real = NTL::RR(t);\n\n   NTL::RR cost_iter = classic_IS_candidate_cost(n_real,n_real-k_real);\n   NTL::RR num_iter  = NTL::to_RR(binomial_wrapper(n,t)) /\n                       NTL::to_RR(binomial_wrapper(n-k,t));\n\n   NTL::RR log_cost = log2_RR(num_iter)+ log2_RR(cost_iter);\n   return NTL::conv<double>( log_cost );\n}\n\n#define P_MAX_LB 20\ndouble isd_log_cost_classic_LB(const uint32_t n, \n                               const uint32_t k,\n                               const uint32_t t) {\n    NTL::RR n_real = NTL::RR(n);\n    NTL::RR k_real = NTL::RR(k);\n    NTL::RR t_real = NTL::RR(t);\n    NTL::RR min_log_cost = n_real; // unreachable upper bound\n    NTL::RR log_cost;\n    uint32_t best_p = 1;\n    uint32_t constrained_max_p = P_MAX_LB > t ? t : P_MAX_LB;\n    NTL::RR IS_candidate_cost;\n    IS_candidate_cost = classic_IS_candidate_cost(n_real,n_real-k_real);\n    for(uint32_t p = 1 ;p < constrained_max_p; p++ ){\n       NTL::RR p_real = NTL::RR(p);\n       NTL::RR cost_iter = IS_candidate_cost +\n                           NTL::to_RR(binomial_wrapper(k,p)*p*(n-k));\n       NTL::RR num_iter  = NTL::to_RR(binomial_wrapper(n,t)) /\n                           NTL::to_RR( binomial_wrapper(k,p) * \n                                       binomial_wrapper(n-k,t-p) );\n       log_cost = (NTL::log(num_iter)+NTL::log(cost_iter)) / NTL::log(NTL::RR(2));\n       if(min_log_cost > log_cost){\n           min_log_cost = log_cost;\n           best_p=p;\n       }\n    }\n    std::cerr << std::endl << \"Lee-Brickell best p: \" << best_p << std::endl;\n    return NTL::conv<double>( min_log_cost );\n}\n\n#define P_MAX_Leon P_MAX_LB\n#define L_MAX_Leon 200\ndouble isd_log_cost_classic_Leon(const uint32_t n, \n                                 const uint32_t k,\n                                 const uint32_t t) {\n    NTL::RR n_real = NTL::RR(n);\n    NTL::RR k_real = NTL::RR(k);\n    NTL::RR t_real = NTL::RR(t);\n    NTL::RR min_log_cost = n_real; // unreachable upper bound\n    NTL::RR log_cost;\n    uint32_t best_l=0,best_p=1, constrained_max_l, constrained_max_p;\n\n    NTL::RR IS_candidate_cost;\n    IS_candidate_cost = classic_IS_candidate_cost(n_real,n_real-k_real);\n    constrained_max_p = P_MAX_Leon > t ? t : P_MAX_Leon;\n    for(uint32_t p = 1; p < constrained_max_p; p++ ){\n      constrained_max_l = ( L_MAX_Leon > (n-k-(t-p)) ? (n-k-(t-p)) : L_MAX_Leon);\n      NTL::RR p_real = NTL::RR(p);\n      for(uint32_t l = 0; l < constrained_max_l; l++){\n          NTL::RR KChooseP = NTL::to_RR( binomial_wrapper(k,p) );\n          NTL::RR cost_iter = IS_candidate_cost +\n                   KChooseP * p_real * NTL::to_RR(l) +\n                   ( KChooseP / NTL::power2_RR(l))* NTL::RR(p * (n-k - l));\n          NTL::RR num_iter  = NTL::to_RR(binomial_wrapper(n,t)) /\n                              NTL::to_RR( binomial_wrapper(k,p) *\n                                          binomial_wrapper(n-k-l,t-p) );\n          log_cost = ( NTL::log(num_iter) + NTL::log(cost_iter) ) / NTL::log(NTL::RR(2));\n          if(min_log_cost > log_cost){\n              min_log_cost = log_cost;\n              best_l = l;\n              best_p = p;\n          }\n       }\n    }\n    std::cerr << std::endl << \"Leon Best l: \" << best_l << \" best p: \" << best_p << std::endl;\n    return NTL::conv<double>( min_log_cost );\n}\n\n\n#define P_MAX_Stern P_MAX_Leon\n#define L_MAX_Stern L_MAX_Leon\ndouble isd_log_cost_classic_Stern(const uint32_t n, \n                                 const uint32_t k,\n                                 const uint32_t t) {\n    NTL::RR n_real = NTL::RR(n);\n    NTL::RR k_real = NTL::RR(k);\n    NTL::RR t_real = NTL::RR(t);\n    NTL::RR min_log_cost = n_real; // unreachable upper bound\n    NTL::RR log_cost;\n    uint32_t best_l = 0,best_p = 2, constrained_max_l, constrained_max_p;\n\n    NTL::RR IS_candidate_cost;\n    IS_candidate_cost = classic_IS_candidate_cost(n_real,n_real-k_real); \n\n    constrained_max_p = P_MAX_Stern > t ? t : P_MAX_Stern;\n    for(uint32_t p = 2; p < constrained_max_p; p = p+2 ){\n      constrained_max_l = ( L_MAX_Stern > (n-k-(t-p)) ? (n-k-(t-p)) : L_MAX_Stern);\n      NTL::ZZ kHalfChoosePHalf;\n      for(uint32_t  l = 0; l < constrained_max_l; l++){\n          NTL::RR p_real = NTL::RR(p);\n          kHalfChoosePHalf = binomial_wrapper(k/2,p/2);\n          NTL::RR kHalfChoosePHalf_real = NTL::to_RR(kHalfChoosePHalf);\n\n          NTL::RR cost_iter = IS_candidate_cost +\n                  kHalfChoosePHalf_real * \n                              ( NTL::to_RR(l)*p_real + \n                                (kHalfChoosePHalf_real / NTL::power2_RR(l))  * NTL::RR(p * (n-k - l)) \n                              );\n// #if LOG_COST_CRITERION == 1\n          NTL::RR log_stern_list_size = kHalfChoosePHalf_real * \n                                   ( p_real/NTL::RR(2) * NTL::log( k_real/NTL::RR(2))/NTL::log(NTL::RR(2) ) +NTL::to_RR(l)); \n                  log_stern_list_size = NTL::log(log_stern_list_size) / NTL::log(NTL::RR(2));\n                  cost_iter = cost_iter*log_stern_list_size;\n// #endif\n          NTL::RR num_iter  = NTL::to_RR(binomial_wrapper(n,t)) /\n                              NTL::to_RR( kHalfChoosePHalf*kHalfChoosePHalf *    \n                                          binomial_wrapper(n-k-l,t-p) );\n          log_cost = log2_RR(num_iter) + log2_RR(cost_iter);\n          if(min_log_cost > log_cost){\n              min_log_cost = log_cost;\n              best_l = l;\n              best_p = p;\n          }\n       }\n    }\n\n    std::cerr << std::endl << \"Stern Best l: \" << best_l << \" best p: \" << best_p << std::endl;\n    return NTL::conv<double>( min_log_cost );\n}\n\n#define P_MAX_FS P_MAX_Stern \n#define L_MAX_FS L_MAX_Stern \ndouble isd_log_cost_classic_FS(const uint32_t n, \n                                 const uint32_t k,\n                                 const uint32_t t) {\n    NTL::RR n_real = NTL::RR(n);\n    NTL::RR k_real = NTL::RR(k);\n    NTL::RR t_real = NTL::RR(t);\n    NTL::RR min_log_cost = n_real; // unreachable upper bound\n    NTL::RR log_cost;\n    uint32_t best_l = 0, best_p = 2,constrained_max_l, constrained_max_p;\n\n    NTL::RR IS_candidate_cost;\n    constrained_max_p = P_MAX_Stern > t ? t : P_MAX_Stern;\n    for(uint32_t p = 2; p < constrained_max_p; p = p+2 ){\n      constrained_max_l = ( L_MAX_Stern > (n-k-(t-p)) ? (n-k-(t-p)) : L_MAX_Stern);\n      NTL::RR p_real = NTL::RR(p);\n      NTL::ZZ kPlusLHalfChoosePHalf;\n      for(uint32_t  l = 0; l < constrained_max_l; l++){\n       IS_candidate_cost = Fin_Send_IS_candidate_cost(n_real,n_real-k_real,NTL::RR(l));\n          kPlusLHalfChoosePHalf = binomial_wrapper((k+l)/2,p/2);\n          NTL::RR kPlusLHalfChoosePHalf_real = NTL::to_RR(kPlusLHalfChoosePHalf);\n          NTL::RR cost_iter = IS_candidate_cost +\n                  kPlusLHalfChoosePHalf_real * \n                              ( NTL::to_RR(l)*p_real + \n                                ( kPlusLHalfChoosePHalf_real / NTL::power2_RR(l)) * \n                                  NTL::RR(p * (n-k - l)) \n                              );\n// #if LOG_COST_CRITERION == 1\n          NTL::RR l_real = NTL::to_RR(l);\n          NTL::RR log_FS_list_size = kPlusLHalfChoosePHalf_real * \n                                   ( p_real/NTL::RR(2) * NTL::log( (k_real+l_real)/NTL::RR(2))/NTL::log(NTL::RR(2) ) +l_real); \n                  log_FS_list_size = log2_RR(log_FS_list_size);\n                  cost_iter = cost_iter*log_FS_list_size;\n// #endif\n          NTL::RR num_iter  = NTL::to_RR(binomial_wrapper(n,t)) /\n                              NTL::to_RR( kPlusLHalfChoosePHalf * kPlusLHalfChoosePHalf *\n                                          binomial_wrapper(n-k-l,t-p) );\n                              \n          log_cost = log2_RR(num_iter) + log2_RR(cost_iter);\n          if(min_log_cost > log_cost){\n              min_log_cost = log_cost;\n              best_l = l;\n              best_p = p;\n          }\n       }\n    }\n    std::cerr << std::endl << \"FS Best l: \" << best_l << \" best p: \" << best_p << std::endl;\n    return NTL::conv<double>( min_log_cost );\n}\n\n#define P_MAX_MMT (P_MAX_FS+25) // P_MAX_MMT\n#define L_MAX_MMT 350 //L_MAX_MMT\n#define L_MIN_MMT 2\ndouble isd_log_cost_classic_MMT(const uint32_t  n,\n                                 const uint32_t k,\n                                 const uint32_t t) {\n    uint32_t r = n-k;\n    NTL::RR n_real = NTL::RR(n);\n    NTL::RR r_real = NTL::RR(r);\n    NTL::RR k_real = n_real-r_real;\n\n\n    NTL::RR min_log_cost = n_real; // unreachable upper bound\n    NTL::RR log_cost, log_mem_cost;\n    uint32_t best_l= L_MIN_MMT, best_l1, best_p = 4,\n             constrained_max_l = 0, constrained_max_p;\n\n    NTL::RR FS_IS_candidate_cost;\n    constrained_max_p = P_MAX_MMT > t ? t : P_MAX_MMT;\n    /* p should be divisible by 4 in MMT */\n    for(uint32_t p = 4; p <= constrained_max_p; p = p+4 ){\n      constrained_max_l = ( L_MAX_MMT > (n-k-(t-p)) ? (n-k-(t-p)) : L_MAX_MMT );\n             for(uint32_t l = L_MIN_MMT; l <= constrained_max_l; l++){\n                NTL::RR l_real = NTL::to_RR(l);\n                NTL::ZZ kPlusLHalfChoosePHalf = binomial_wrapper((k+l)/2,p/2);\n                NTL::RR num_iter  = NTL::to_RR(binomial_wrapper(n,t)) /\n                              NTL::to_RR( kPlusLHalfChoosePHalf * kPlusLHalfChoosePHalf *\n                                          binomial_wrapper(n-k-l,t-p) );\n                FS_IS_candidate_cost = Fin_Send_IS_candidate_cost(n_real,r_real,l_real);\n                NTL::ZZ  kPlusLHalfChoosePFourths = binomial_wrapper((k+l)/2,p/4);\n                NTL::RR  kPlusLHalfChoosePFourths_real = NTL::to_RR(kPlusLHalfChoosePFourths);\n                NTL::RR  minOperandRight, min;\n                NTL::RR  PChoosePHalf = NTL::to_RR(binomial_wrapper(p,p/2));\n                NTL::RR  kPlusLChoosePHalf = NTL::to_RR(binomial_wrapper((k+l),p/2));\n                minOperandRight = NTL::to_RR(binomial_wrapper((k+l)/2,p/2)) / PChoosePHalf;\n                min =  kPlusLHalfChoosePFourths_real > minOperandRight ? minOperandRight : kPlusLHalfChoosePFourths_real;\n\n               /* hoist out anything not depending on l_1/l_2 split*/\n#if defined(EXPLORE_REPRS)\n               for(uint32_t l_1 = 1 ; l_1 <= l ; l_1++){\n                  uint32_t l_2= l-l_1;\n#else\n                  uint32_t l_2 = NTL::conv<unsigned int>(log2_RR(kPlusLHalfChoosePFourths_real / NTL::to_RR(binomial_wrapper(p,p/2))));\n                  /*clamp l_2 to a safe value , 0 < l_2 < l*/\n                  l_2 = l_2 <= 0 ? 1 : l_2;\n                  l_2 = l_2 >= l ? l-1 : l_2;\n\n                  uint32_t l_1= l - l_2;\n#endif\n                  NTL::RR interm = kPlusLHalfChoosePFourths_real / NTL::power2_RR(l_2) *\n                                         NTL::to_RR(p/2*l_1);\n\n                  NTL::RR otherFactor = ( NTL::to_RR(p/4*l_2) + interm );\n                  NTL::RR cost_iter = FS_IS_candidate_cost +\n                                      min*otherFactor +\n                                      kPlusLHalfChoosePFourths_real * NTL::to_RR(p/2*l_2);\n\n                  NTL::RR lastAddend = otherFactor +\n                                        kPlusLHalfChoosePFourths_real * \n                                         kPlusLChoosePHalf * PChoosePHalf /\n                                         NTL::power2_RR(l)   *  \n                                       NTL::to_RR( p*(r-l) );\n                  lastAddend = lastAddend * kPlusLHalfChoosePFourths_real;\n                  cost_iter += lastAddend;\n// #if 0\n\n          NTL::RR log_MMT_space = r_real*n_real +\n                                  kPlusLHalfChoosePFourths_real *\n                                       (NTL::to_RR(p/4)* log2_RR(NTL::to_RR(k+l/2))+ NTL::to_RR(l_2) )+\n                                  NTL::to_RR(min) * (NTL::to_RR(p/2)* log2_RR(NTL::to_RR(k+l))+ NTL::to_RR(l) );\n                  log_MMT_space = log2_RR(log_MMT_space);\n                  cost_iter = cost_iter*log_MMT_space;\n// #endif\n                  log_cost = log2_RR(num_iter) + log2_RR(cost_iter);\n                  if(min_log_cost > log_cost){\n                      min_log_cost = log_cost;\n                      best_l = l;\n                      best_l1 = l_1;\n                      best_p = p;\n                      log_mem_cost = log_MMT_space;\n                  }\n#if defined(EXPLORE_REPRS)\n               }\n#endif\n            }\n    }\n    std::cerr << std::endl << \"MMT Best l: \" << best_l\n                           << \" best p: \"   << best_p\n                           << \" best l1: \"  << best_l1\n                           << std::endl;\n   if(best_p == constrained_max_p){\n          std::cerr << std::endl << \"Warning: p on exploration edge! \" << std::endl;\n   }\n   if(best_l == constrained_max_l){\n          std::cerr << std::endl << \"Warning: l on exploration edge! \" << std::endl;\n   }\n   //std::cerr << log_mem_cost << \" \";\n   return NTL::conv<double>( min_log_cost );\n}\n\n\n#define P_MAX_BJMM 20 // P_MAX_MMT\n#define L_MAX_BJMM 90 //L_MAX_MMT\n#define Eps1_MAX_BJMM 4\n#define Eps2_MAX_BJMM 4\ndouble isd_log_cost_classic_BJMM(const uint32_t n, \n                                 const uint32_t k,\n                                 const uint32_t t) {\n    NTL::RR n_real = NTL::RR(n);\n    NTL::RR k_real = NTL::RR(k);\n    NTL::RR t_real = NTL::RR(t);\n    uint32_t r = n-k;\n    NTL::RR r_real = NTL::RR(r);\n\n    NTL::RR min_log_cost = n_real; // unreachable upper bound\n    NTL::RR log_cost;\n    uint32_t best_l, best_p, \n             best_eps_1, best_eps_2, \n             constrained_max_l, constrained_max_p;\n\n    NTL::RR FS_IS_candidate_cost;\n    constrained_max_p = P_MAX_BJMM > t ? t : P_MAX_BJMM;\n    /*p should be divisible by 2 in BJMM */\n    for(uint32_t p = 2; p < constrained_max_p; p = p+2 ){\n        /* sweep over all the valid eps1 knowing that p/2 + eps1 should be a \n         * multiple of 4*/ \n        constrained_max_l = ( L_MAX_BJMM > (n-k-(t-p)) ? (n-k-(t-p)) : L_MAX_BJMM );\n        for(uint32_t  l = 0; l < constrained_max_l; l++){\n            for(uint32_t eps1 = 2+(p%2) ; eps1 < Eps1_MAX_BJMM; eps1 = eps1 + 2) {\n                uint32_t p_1 = p/2 + eps1;\n            /* sweep over all the valid eps2 knowing that p_1/2 + eps2 should \n             * be even */ \n                for(uint32_t eps2 = (p_1%2) ; eps2 < Eps2_MAX_BJMM; eps2 = eps2 + 2){\n                    uint32_t p_2 = p_1/2 + eps2;\n\n                \n                    /* Available parameters p, p_1,p_2,p_3, l */\n                    NTL::RR l_real = NTL::RR(l);\n                    FS_IS_candidate_cost = Fin_Send_IS_candidate_cost(n_real,n_real-k_real,l_real); \n                    uint32_t p_3 = p_2/2;\n\n                    NTL::ZZ L3_list_len = binomial_wrapper((k+l)/2,p_3);\n                    NTL::RR L3_list_len_real = NTL::to_RR(L3_list_len);\n                    /* the BJMM number of iterations depends only on L3 parameters\n                    * precompute it */\n                    NTL::RR num_iter  = NTL::to_RR( binomial_wrapper(n,t) ) /\n                                        NTL::to_RR( binomial_wrapper((k+l),p) *\n                                                    binomial_wrapper(r-l,t-p) \n                                                );\n                    NTL::RR P_invalid_splits = NTL::power(L3_list_len_real,2) /\n                                            NTL::to_RR( binomial_wrapper(k+l,p_2));\n                    num_iter = num_iter / NTL::power(P_invalid_splits,4);\n\n                    /* lengths of lists 2 to 0 have to be divided by the number of repr.s*/\n                    NTL::RR L2_list_len = NTL::to_RR(binomial_wrapper(k+l,p_2)) * \n                                        NTL::power(P_invalid_splits,1);\n                    NTL::RR L1_list_len = NTL::to_RR(binomial_wrapper(k+l,p_1)) * \n                                        NTL::power(P_invalid_splits,2);\n                    /* estimating the range for r_1 and r_2 requires to compute the\n                    * number of representations rho_1 and rho_2 */\n\n                    NTL::ZZ rho_2 = binomial_wrapper(p_1,p_1/2) * \n                                    binomial_wrapper(k+l-p_1,eps2);\n                    NTL::ZZ rho_1 = binomial_wrapper(p,p/2) * \n                                    binomial_wrapper(k+l-p,eps1);\n                    int min_r2 = NTL::conv<int>(NTL::log(NTL::to_RR(rho_2)) / \n                                NTL::log(NTL::RR(2)));\n                    int max_r1 = NTL::conv<int>(NTL::log(NTL::to_RR(rho_1)) / \n                                NTL::log(NTL::RR(2)));\n\n                    /*enumerate r_1 and r_2 over the suggested range \n                    * log(rho_2) < r2 < r_1 < log(rho_1)*/\n                    /* clamp to safe values */\n                    min_r2 = min_r2 > 0 ? min_r2 : 1;\n                    max_r1 = max_r1 < (int)l ? max_r1 : l-1;\n\n                    NTL::RR p_real = NTL::RR(p);\n                    for(int r_2 = min_r2 ; r_2 < max_r1 - 1; r_2++){\n                        for(int r_1 = r_2+1; r_1 < max_r1 ; r_1++){\n\n                            /*add the cost of building Layer 3 to cost_iter */\n                            NTL::RR cost_iter = NTL::to_RR(4) *\n                                                (k + l + 2*L3_list_len_real +\n                                                r_2 + \n                                                NTL::power(L3_list_len_real,2)*\n                                                NTL::to_RR(2*p_3*r_2));\n\n                             /* add the cost of building Layer 2 */\n                            cost_iter +=    2 * (NTL::power((NTL::to_RR(rho_2) / \n                                            (NTL::power2_RR(r_2)))*\n                                            NTL::power(L3_list_len_real,2),2) \n                                            * 2 * p_2 * (r_1-r_2));\n\n                            /* add the cost of building Layer 1 */\n                            cost_iter +=    NTL::power((NTL::to_RR(rho_1) / \n                                            NTL::power2_RR(r_1)) * \n                                            (NTL::to_RR(rho_2) / \n                                            NTL::power2_RR(r_2))*\n                                            NTL::power(L3_list_len_real,2),4) * 2 * p_1 * l;\n\n                             /* add the cost of building L0 */\n                            cost_iter +=    p * (r - l) * \n                                            NTL::power((NTL::to_RR(rho_1) / NTL::power2_RR(r_1)) * \n                                            (NTL::to_RR(rho_2) / \n                                            NTL::power2_RR(r_2))*\n                                            NTL::power(L3_list_len_real,2),4)\n                                            / NTL::to_RR(l);\n\n                            log_cost = log2_RR(num_iter) + log2_RR(cost_iter);\n\n                            if(min_log_cost >  log_cost){\n                                min_log_cost = log_cost;\n                                best_l = l;\n                                best_p = p;\n                                best_eps_1 = eps1;\n                                best_eps_2 = eps2;\n                            }\n                        }\n                    }\n\n                } /*end of iteration over l */\n            /* to review up to to here */  \n            } /* end for over eps2 */     \n         } /* end for over eps1 */\n    } /* end for over p*/\n    std::cerr << std::endl << \"BJMM Best l: \" << best_l \n                            << \" best p: \"   << best_p \n                            << \" best eps1: \"  << best_eps_1\n                            << \" best eps2: \"  << best_eps_2\n                            << std::endl;\n   return NTL::conv<double>( min_log_cost );\n}\n\n/***************************Quantum ISDs***************************************/\n\n\nconst NTL::RR quantum_gauss_red_cost(const NTL::RR &n, \n                                     const NTL::RR & k) {\n    return 0.5* NTL::power(n-k,3) + k*NTL::power((n-k),2);\n}\n\n\ndouble isd_log_cost_quantum_LB(const uint32_t n, \n                               const uint32_t k,\n                               const uint32_t t) {\n    NTL::RR n_real = NTL::RR(n);\n    NTL::RR k_real = NTL::RR(k);\n    NTL::RR t_real = NTL::RR(t);\n    NTL::RR log_pi_fourths = NTL::log(pi*0.25);\n    NTL::RR log_pinv = log_probability_k_by_k_is_inv(k_real);\n    NTL::RR iteration_cost = quantum_gauss_red_cost(n_real,k_real) +\n                             NTL::to_RR(binomial_wrapper(k,2) * 2 * (n-k));\n    NTL::RR log_cost = (lnBinom(n_real,t_real) - \n                        (lnBinom(k_real,NTL::RR(2)) + \n                         lnBinom(n_real-k_real,t-NTL::RR(2))) \n                       )*0.5 + \n                       log_pi_fourths; \n    log_cost += NTL::log(iteration_cost);\n    log_cost = log_cost / NTL::log(NTL::RR(2));\n    return NTL::conv<double>( log_cost );\n}\n\n\n#define MAX_M (t/2)\n\ndouble isd_log_cost_quantum_stern(const uint32_t n,\n                                  const uint32_t k,\n                                  const uint32_t t) {\n    NTL::RR n_real = NTL::RR(n);\n    NTL::RR k_real = NTL::RR(k);\n    NTL::RR t_real = NTL::RR(t);\n    NTL::RR current_complexity, log_p_success, c_it, c_dec;\n\n    // Start computing Stern's parameter invariant portions of complexity\n    NTL::RR log_pi_fourths = NTL::log(pi*0.25);\n    // compute the probability of a random k * k being invertible\n    NTL::RR log_pinv = log_probability_k_by_k_is_inv(k_real);\n    // compute the cost of inverting the matrix, in a quantum execution env.\n    NTL::RR c_inv = quantum_gauss_red_cost(n_real,k_real);\n\n    // optimize Stern's parameters :\n    // m : the # of errors in half of the chosen dimensions\n    // l : the length of the run of zeroes in the not chosen dimensions\n    // done via exhaustive parameter space search, minimizing the total \n    // complexity. \n    // Initial value set to codeword bruteforce to ensure the minimum is found.\n    NTL::RR min_stern_complexity = NTL::RR(n)*NTL::log(NTL::RR(2));\n\n    for(long m = 1; m <= MAX_M; m++){\n        NTL::RR m_real = NTL::RR(m);\n        /* previous best complexity as a function of l alone. \n         * initialize to bruteforce-equivalent,  break optimization loop as soon\n         * as a minimum is found */\n        NTL::RR prev_best_complexity = NTL::RR(t);\n        for(long l = 0; l < (n-k-(t-2*m)); l++ ){\n\n          NTL::RR  l_real = NTL::RR(l);\n          log_p_success = lnBinom(t_real, 2*m_real) + \n                   lnBinom(n_real-t_real, k_real-2*m_real) + \n                   lnBinom(2*m_real,m_real) +\n                   lnBinom(n_real-k_real-t_real+2*m_real,l_real);\n          log_p_success = log_p_success - ( m_real*NTL::log(NTL::RR(4)) + \n                              lnBinom(n_real,k_real) +\n                              lnBinom(n_real -k_real, l_real));\n         current_complexity = -(log_p_success+log_pinv)*0.5 + log_pi_fourths;\n         /* to match specifications , the term should be \n          * (n_real-k_real), as per in deVries, although\n          * David Hobach thesis mentions it to be \n          * (n_real-k_real-l_real), and it seems to match.\n          * amend specs for the typo. */\n         c_it = l_real + \n            (n_real-k_real-l_real)* NTL::to_RR(binomial_wrapper(k/2,m)) / \n            NTL::power2_RR(-l);\n\n         c_it = c_it * 2*m_real * NTL::to_RR(binomial_wrapper(k/2,m));\n#if IGNORE_DECODING_COST == 1\n        c_dec = 0.0;\n#elif IGNORE_DECODING_COST == 0\n        /*cost of decoding estimated as per Golomb CWDEC \n         * decoding an n-bit vector with weight k is \n         * CWDEC_cost(k,n)=O(n^2 log_2(n))  and following deVries, where\n         * c_dec = CWDEC_cost(n-k, n) + k + CWDEC_cost(l,n-k)*/\n        c_dec = n_real*n_real*NTL::log(n_real) + k_real +\n                (n_real-k_real)*(n_real-k_real)*NTL::log((n_real-k_real));\n#endif\n         current_complexity = current_complexity + NTL::log(c_it+c_inv+c_dec);\n          if(current_complexity < prev_best_complexity){\n             prev_best_complexity = current_complexity;\n          } else{\n             break;\n          }\n        }\n       if(current_complexity < min_stern_complexity){\n           min_stern_complexity = current_complexity;\n       }\n    }\n    return NTL::conv<double>( min_stern_complexity / NTL::log(NTL::RR(2.0)) );\n}\n\n\n/***************************Aggregation ***************************************/\n\n\ndouble c_isd_log_cost(const uint32_t n, \n                      const uint32_t k,\n                      const uint32_t t,\n                      const uint32_t qc_order, \n                      const uint32_t is_kra) {\n    double min_cost = n, current_cost;\n    /* for key recovery attacks the advantage from quasi-cyclicity is p, \n     * for an ISD, the DOOM advantage is just sqrt(p) */\n    double qc_red_factor= is_kra ? logl(qc_order) : logl(qc_order)/2.0;\n    qc_red_factor = qc_red_factor/logl(2);\n\n    std::cout << \"Classic \";\n    current_cost = isd_log_cost_classic_Prange(n,k,t) - qc_red_factor;\n    std::cerr << \"Classic Prange: \" << std::setprecision(5) << current_cost << std::endl;\n    std::cout << current_cost << \" \";\n    min_cost = current_cost;\n\n    current_cost = isd_log_cost_classic_LB(n,k,t)- qc_red_factor;\n    std::cerr << \"Classic Lee-Brickell ISD: \" << std::setprecision(5) << current_cost << std::endl;\n    std::cout << current_cost << \" \";\n    min_cost = min_cost > current_cost ? current_cost : min_cost;\n\n    current_cost = isd_log_cost_classic_Leon(n,k,t)- qc_red_factor;\n     std::cerr << \"Classic Leon ISD: \" << std::setprecision(5) << current_cost << std::endl;\n    std::cout << current_cost << \" \";\n    min_cost = min_cost > current_cost ? current_cost : min_cost;\n\n    current_cost = isd_log_cost_classic_Stern(n,k,t)- qc_red_factor;\n    std::cerr << \"Classic Stern ISD: \" << std::setprecision(5) << current_cost << std::endl;\n    std::cout << current_cost << \" \";\n    min_cost = min_cost > current_cost ? current_cost : min_cost;\n\n    current_cost = isd_log_cost_classic_FS(n,k,t)- qc_red_factor;\n    std::cerr << \"Classic Fin-Send ISD: \" << std::setprecision(5) << current_cost << std::endl;\n    std::cout << current_cost << \" \";\n    min_cost = min_cost > current_cost ? current_cost : min_cost;\n\n    current_cost = isd_log_cost_classic_MMT(n,k,t)- qc_red_factor;\n    std::cerr << \"Classic MMT ISD: \" << std::setprecision(5) << current_cost << std::endl;\n    std::cout << current_cost << \" \";\n    min_cost = min_cost > current_cost ? current_cost : min_cost;\n\n#if SKIP_BJMM == 0\n    current_cost = isd_log_cost_classic_BJMM(n,k,t)- qc_red_factor;\n    std::cerr << \"Classic BJMM ISD: \" << std::setprecision(5) << current_cost << std::endl;\n    std::cout << current_cost << \" \";\n    min_cost = min_cost > current_cost ? current_cost : min_cost;\n#endif\n    std::cout << std::endl;\n\n    return min_cost;\n}\n\ndouble q_isd_log_cost(const uint32_t n, \n                      const uint32_t k, \n                      const uint32_t t,\n                      const uint32_t qc_order, \n                      const uint32_t is_kra) {\n    double min_cost = n, current_cost;\n    /* for key recovery attacks the advantage from quasi-cyclicity is p, \n     * for an ISD, the DOOM advantage is just sqrt(p) */\n    double qc_red_factor= is_kra ? logl(qc_order) : logl(qc_order)/2.0;\n    qc_red_factor = qc_red_factor/logl(2);\n    std::cout << \"Quantum \";\n\n    current_cost = isd_log_cost_quantum_LB(n,k,t)- qc_red_factor;\n    std::cout << current_cost << \" \";\n//     std::cout << \" Q-Lee-Brickell ISD: \" << /**/current_cost << std::endl;\n    min_cost = current_cost;\n\n    current_cost = isd_log_cost_quantum_stern(n, k, t)- qc_red_factor;\n    std::cout << current_cost << \" \";\n//     std::cout << \", Q-Stern ISD: \" << current_cost << std::endl;\n    min_cost = min_cost > current_cost ? current_cost : min_cost;\n    std::cout << std::endl;\n\n    return min_cost;\n}", "meta": {"hexsha": "33718f278026e8d559e83509a91c5ccef7bf8f12", "size": 30430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "isd_cost_estimate.hpp", "max_stars_repo_name": "alexrow/LEDAtools", "max_stars_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "isd_cost_estimate.hpp", "max_issues_repo_name": "alexrow/LEDAtools", "max_issues_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isd_cost_estimate.hpp", "max_forks_repo_name": "alexrow/LEDAtools", "max_forks_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "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": 44.75, "max_line_length": 135, "alphanum_fraction": 0.5162339796, "num_tokens": 8552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.629426886128565}}
{"text": "#include \"bend_quadratic_forces.h\"\n\n#include <igl/sparse_cached.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <igl/edges.h>\n#include \"../adjacency.h\"\n#include \"../timer.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Eigen::Triplet<double> Tri;\n\n// reference code for Discrete Quadratic Curvature Energies is here\n// http://www.cs.columbia.edu/cg/quadratic/\n// I took the functions cotTheta and Compute LocalStiffness and made them works with Eigen\n\n//         x2\n//         /\\\n//        /  \\\n//     e1/    \\e3\n//      /  t0  \\\n//     /        \\\n//    /    e0    \\\n//  x0------------x1\n//    \\          /\n//     \\   t1   /\n//      \\      /\n//     e2\\    /e4\n//        \\  /\n//         \\/\n//         x3\n//\n// Edge orientation: e0,e1,e2 point away from x0\n//                      e3,e4 point away from x1\n\nBend::Bend() {}\n\ndouble Bend::cotTheta(const Vector3d v, const Vector3d w)\n{\n\t//assert(finite(v.length()));\n\t//assert(finite(w.length()));\n\t//assert(v.length() > 0);\n\t//assert(w.length() > 0);\n\tconst double cosTheta = v.dot(w);\n\tconst double sinTheta = v.cross(w).norm();\n\treturn (cosTheta / sinTheta);\n}\n\n// compute 4 by 4 local stiffness matrix Q(e0)\nvoid Bend::ComputeLocalStiffness(\n\tconst vector< Vector3d>& x,\n\tMatrix4d& Q)\n{\n\tconst Vector3d e0 = x[1] - x[0];\n\tconst Vector3d e1 = x[2] - x[0];\n\tconst Vector3d e2 = x[3] - x[0];\n\tconst Vector3d e3 = x[2] - x[1];\n\tconst Vector3d e4 = x[3] - x[1];\n\n\tconst double c01 = cotTheta(e0, e1);\n\tconst double c02 = cotTheta(e0, e2);\n\tconst double c03 = cotTheta(-e0, e3);\n\tconst double c04 = cotTheta(-e0, e4);\n\n\tconst Vector4d K0 = Vector4d(c03 + c04, c01 + c02, -c01 - c03, -c02 - c04);\n\n\tconst double A0 = e0.cross(e1).norm();\n\tconst double A1 = e0.cross(e2).norm();\n\n\tconst double coef = -3. / (A0 + A1);\n\n\tassert(finite(coef));\n\tassert(finite(c01));\n\tassert(finite(c02));\n\tassert(finite(c03));\n\tassert(finite(c04));\n\n\t// compute Q = coef times outer product of K0 and K0\n\tfor (int i = 0; i < 4; ++i) {\n\t\tfor (int j = 0; j < i; ++j) {\n\t\t\tQ(i, j) = Q(j, i) = coef * K0[i] * K0[j];\n\t\t}\n\t\tQ(i, i) = coef * K0[i] * K0[i];\n\t}\n}\n\nvoid Bend::init(\n\tconst double k_bend,\n\tconst double k_damping,\n\tconst MatrixXd& X,\t\t\t// in: vertex positions\n\tconst MatrixXi& T\t\t\t// in: mesh triangles\n) {\n\tthis->k_bend = k_bend;\n\tthis->k_damping = k_damping;\n\tthis->n = X.rows();\n\n\t// create list of 4 vertices for each face pair (each internal edge)\n\tcreateFacePairEdgeListWith4VerticeIDs(T, E4);\n\n\t// precompute the matrices Q, K and D\n\tK.resize(3 * n, 3 * n);\n\tD.resize(n * 3, n * 3);\n\tQ.resize(E4.rows());\n\n    F_local.resize(E4.rows() * 4);\n    \n\tthis->precompute_rest_shape(X);\n}\n\nvoid Bend::precompute_rest_shape(const MatrixXd& X){\n\n    \n    if(!tripletsInitialized)\n    {\n        std::vector<Eigen::Triplet<double>> tri;\n        \n        for (int e = 0; e < E4.rows(); e++)\n        {\n            // add stiffness matrix\n            for (int dim = 0; dim < 3; dim++) {\n                for (int v1 = 0; v1 < 4; v1++) {\n                    for (int v2 = 0; v2 < v1; v2++) {\n                        tri.push_back(Tri(E4(e, v1) + dim * n, E4(e, v2) + dim * n, 0));\n                        tri.push_back(Tri(E4(e, v2) + dim * n, E4(e, v1) + dim * n, 0));\n                    }\n                    \n                    tri.push_back(Tri(E4(e, v1) + dim * n, E4(e, v1) + dim * n, 0));\n                }\n            }\n        }\n        \n        K = SparseMatrix<double>(3 * n, 3 * n);\n        igl::sparse_cached_precompute(tri, K_data, K);\n        D = K;\n        \n        triK.resize(tri.size());\n        triD.resize(tri.size());\n        \n        tripletsInitialized = true;\n    }\n    \n#pragma omp parallel for\n    for (int e = 0; e < E4.rows(); e++) {\n        vector< Vector3d > x(4);\n        for (int i = 0; i < 4; i++)\n            x[i] = X.row(E4(e, i));\n\n        ComputeLocalStiffness(x, Q[e]);\n\n        // --- second order derivatives ---\n        // stiffness and damping matrix\n        Matrix4d K_local = k_bend * Q[e];\n        Matrix4d D_local = k_damping * Q[e];\n\n        int offset = e * 48;\n        \n        // add stiffness matrix\n        for (int dim = 0; dim < 3; dim++) {\n            for (int v1 = 0; v1 < 4; v1++) {\n                for (int v2 = 0; v2 < v1; v2++) {\n                    \n                    triK[offset] = Tri(0, 0, K_local(v1, v2));\n                    triK[offset+1] = Tri(0, 0, K_local(v2, v1));\n                    \n                    triD[offset] = Tri(0, 0, D_local(v1, v2));\n                    triD[offset+1] = Tri(0, 0, D_local(v2, v1));\n                    \n                    offset += 2;\n                }\n                \n                \n                triK[offset] = Tri(0, 0,  K_local(v1, v1));\n                triD[offset] = Tri(0, 0,  D_local(v1, v1));\n                \n                offset++;\n            }\n        }\n    }\n    \n    igl::sparse_cached(triK, K_data, this->K);\n    igl::sparse_cached(triD, K_data, this->D);\n}\n\n\nconst Eigen::SparseMatrix<double>& Bend::getK() const\n{\n    return K;\n}\n\nconst Eigen::SparseMatrix<double>& Bend::getD() const\n{\n    return D;\n}\n  \n\nvoid Bend::compute_forces(\n\tconst MatrixXd& X,\t\t\t// in: vertex positions\n\tconst VectorXd& V,\t\t\t// in: velocities\n\tVectorXd& F)\t\t\t\t// out: forces\n{\n    //#pragma omp parallel for\n\tfor (int e = 0; e < E4.rows(); e++) {\n\t\t\n        // get necessary positions and velocities for this edge\n\t\tvector< Vector4d > x(3);\t\t\t\t// position: 3 vectors: x_coords, y_coords and z_coords - each with 4 entries for 4 vertices\n\t\tvector< Vector4d > v(3);\t\t\t\t// velocity\n\t\t\n        for (int i = 0; i < 4; i++) {\n\t\t\tint vertex = E4(e, i);\n            for (int j = 0; j < 3; j++) {\n\t\t\t\tx[j](i) = X(vertex, j);\n\t\t\t\tv[j](i) = V(vertex + j * n);\n\t\t\t}\n\t\t}\n\n        const auto qe = Q[e];\n        \n        F_local[3 * e + 0] = qe * (k_bend * x[0] + k_damping * v[0]);\n        F_local[3 * e + 1] = qe * (k_bend * x[1] + k_damping * v[1]);\n        F_local[3 * e + 2] = qe * (k_bend * x[2] + k_damping * v[2]);\n\t}\n            \n    for (int e = 0; e < E4.rows(); e++) {\n        for (int i = 0; i < 4; i++) {            // force on vertex i\n            const int vertex = E4(e, i);\n            for (int j = 0; j < 3; j++) {        // put each force dimension into the right place of the total F\n                F(vertex + j * n) += F_local[3 * e + j](i);\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "28f12db9e4d61e91459ae492768f8eb464db526d", "size": 6329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox/clothsimulation/bend_quadratic_forces.cpp", "max_stars_repo_name": "katjawolff/custom_fit_garments", "max_stars_repo_head_hexsha": "1d6f9dcba612010bb5552201f39595f7b288b8d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-08-15T09:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T10:19:09.000Z", "max_issues_repo_path": "toolbox/clothsimulation/bend_quadratic_forces.cpp", "max_issues_repo_name": "katjawolff/custom_fit_garments", "max_issues_repo_head_hexsha": "1d6f9dcba612010bb5552201f39595f7b288b8d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-24T07:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-24T07:16:34.000Z", "max_forks_repo_path": "toolbox/clothsimulation/bend_quadratic_forces.cpp", "max_forks_repo_name": "katjawolff/custom_fit_garments", "max_forks_repo_head_hexsha": "1d6f9dcba612010bb5552201f39595f7b288b8d5", "max_forks_repo_licenses": ["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.047008547, "max_line_length": 122, "alphanum_fraction": 0.4970769474, "num_tokens": 2025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6294268855592131}}
{"text": "#include \"eigen-runtime.h\"\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/Sparse>\n#include <Spectra/GenEigsSolver.h>\n#include <Spectra/GenEigsRealShiftSolver.h>\n#include <Spectra/SymEigsSolver.h>\n#include <Spectra/SymEigsShiftSolver.h>\n#include <Spectra/SymGEigsSolver.h>\n#include <Spectra/MatOp/DenseSymMatProd.h>\n#include <Spectra/MatOp/SparseGenRealShiftSolve.h>\n#include <Spectra/MatOp/SparseSymShiftSolve.h>\n#include <Spectra/MatOp/SparseCholesky.h>\n#include <Spectra/MatOp/SparseGenMatProd.h>\n#include <Spectra/Util/GEigsMode.h>\n\nusing namespace Spectra;\nusing namespace Eigen;\n\nextern \"C\" RET eigen_eig( \n    void* d, void* v, \n    const void* p, int n)\n{\n    typedef Map< Matrix<T1,Dynamic,Dynamic> > MapMatrix;\n    typedef Map< Matrix<T3,Dynamic,Dynamic> > MapComplexMatrix;\n    MapMatrix M((T1*)p, n, n);\n    MapComplexMatrix D((T3*)d, n, 1);\n    MapComplexMatrix V((T3*)v, n, n);\n    EigenSolver<MatrixXd> es(M);\n    D = es.eigenvalues();\n    V = es.eigenvectors();\n}\n\nextern \"C\" const int spectral_eigs( \n    const int k,   // number of eigenvectors to return\n    void* d, void* v,  // pointer to the results\n    const void* p, const int n,  // pointer to the input and dimensionality\n    const int ncv, int maxit, double tol,\n    const int mode, const double sigma,\n    const int select)\n{\n    typedef Map< Matrix<T1,Dynamic,Dynamic> > MapMatrix;\n    typedef Map< Matrix<T3,Dynamic,Dynamic> > MapComplexMatrix;\n    MapMatrix M((T1*)p, n, n);\n    MapComplexMatrix D((T3*)d, k, 1);\n    MapComplexMatrix V((T3*)v, n, k);\n\n    if(mode == 0) {\n        DenseGenMatProd<double> op(M);\n        GenEigsSolver<DenseGenMatProd<double>> eigs(op, k, ncv);\n        eigs.init();\n        int nconv = eigs.compute(static_cast<SortRule>(select), maxit, tol);\n        if(eigs.info() == CompInfo::Successful) {\n            D = eigs.eigenvalues();\n            V = eigs.eigenvectors();\n        } \n        return static_cast<int>(eigs.info());\n    } else {\n        DenseGenRealShiftSolve<double> op(M);\n        GenEigsRealShiftSolver<DenseGenRealShiftSolve<double>> eigs(op, k, ncv, sigma);\n        eigs.init();\n        int nconv = eigs.compute(static_cast<SortRule>(select), maxit, tol);\n        if(eigs.info() == CompInfo::Successful) {\n            D = eigs.eigenvalues();\n            V = eigs.eigenvectors();\n        } \n        return static_cast<int>(eigs.info());\n    }\n}\n\nextern \"C\" const int spectral_eigsh( \n    int k,\n    void* d, void* v, \n    const void* p, int n,\n    const int ncv, int maxit, double tol,\n    const int mode, const double sigma,\n    const int select)\n{\n    typedef Map< Matrix<T1,Dynamic,Dynamic> > MapMatrix;\n    MapMatrix M((T1*)p, n, n);\n    MapMatrix D((T1*)d, k, 1);\n    MapMatrix V((T1*)v, n, k);\n\n    if(mode == 0) {\n        DenseGenMatProd<double> op(M);\n        SymEigsSolver<DenseGenMatProd<double>> eigsh(op, k, ncv);\n        eigsh.init();\n        int nconv = eigsh.compute(static_cast<SortRule>(select), maxit, tol);\n        if(eigsh.info() == CompInfo::Successful) {\n            D = eigsh.eigenvalues();\n            V = eigsh.eigenvectors();\n        }\n        return static_cast<int>(eigsh.info());\n    } else {\n        DenseSymShiftSolve<double> op(M);\n        SymEigsShiftSolver<DenseSymShiftSolve<double>> eigsh(op, k, ncv, sigma);\n        eigsh.init();\n        int nconv = eigsh.compute(static_cast<SortRule>(select), maxit, tol);\n        if(eigsh.info() == CompInfo::Successful) {\n            D = eigsh.eigenvalues();\n            V = eigsh.eigenvectors();\n        } \n        return static_cast<int>(eigsh.info());\n    }\n}\n\nextern \"C\" const int spectral_seigs( \n    int k,\n    void* d, void* v,\n    const void* values, const void* outerIndexPtr, const void* innerIndices, int n, int s,\n    const int ncv, int maxit, double tol,\n    const int mode, const double sigma,\n    const int select)\n{\n    typedef Map< Matrix<T3,Dynamic,Dynamic> > MapComplexMatrix;\n    typedef Map<const SparseMatrix<T1> > MapSparseMatrix;\n    MapSparseMatrix M(n, n, s, (int*)outerIndexPtr, (int*)innerIndices, (T1*)values);\n    MapComplexMatrix D((T3*)d, k, 1);\n    MapComplexMatrix V((T3*)v, n, k);\n\n    if(mode == 0) {\n        SparseGenMatProd<double> op(M);\n        GenEigsSolver<SparseGenMatProd<double>> eigs(op, k, ncv);\n        eigs.init();\n        int nconv = eigs.compute(static_cast<SortRule>(select), maxit, tol);\n        if(eigs.info() == CompInfo::Successful) {\n            D = eigs.eigenvalues();\n            V = eigs.eigenvectors();\n        }\n        return static_cast<int>(eigs.info());\n    } else {\n        SparseGenRealShiftSolve<double> op(M);\n        GenEigsRealShiftSolver<SparseGenRealShiftSolve<double>> eigs(op, k, ncv, sigma);\n        eigs.init();\n        int nconv = eigs.compute(static_cast<SortRule>(select), maxit, tol);\n        if(eigs.info() == CompInfo::Successful) {\n            D = eigs.eigenvalues();\n            V = eigs.eigenvectors();\n        }\n        return static_cast<int>(eigs.info());\n    }\n}\n\nextern \"C\" const int spectral_seigsh( \n    int k,\n    void* d, void* v,\n    const void* values, const void* outerIndexPtr, const void* innerIndices, int n, int s,\n    const int ncv, int maxit, double tol,\n    const int mode, const double sigma,\n    const int select)\n{\n    typedef Map< Matrix<T1,Dynamic,Dynamic> > MapMatrix;\n    typedef Map<const SparseMatrix<T1> > MapSparseMatrix;\n    MapSparseMatrix M(n, n, s, (int*)outerIndexPtr, (int*)innerIndices, (T1*)values);\n    MapMatrix D((T1*)d, k, 1);\n    MapMatrix V((T1*)v, n, k);\n\n    if(mode == 0) {\n        SparseGenMatProd<double> op(M);\n        SymEigsSolver<SparseGenMatProd<double>> eigsh(op, k, ncv);\n        eigsh.init();\n        int nconv = eigsh.compute(static_cast<SortRule>(select), maxit, tol);\n        if(eigsh.info() == CompInfo::Successful) {\n            D = eigsh.eigenvalues();\n            V = eigsh.eigenvectors();\n        }\n        return static_cast<int>(eigsh.info());\n    } else {\n        SparseSymShiftSolve<double> op(M);\n        SymEigsShiftSolver<SparseSymShiftSolve<double>> eigsh(op, k, ncv, 0);\n        eigsh.init();\n        int nconv = eigsh.compute(static_cast<SortRule>(select), maxit, tol);\n        if(eigsh.info() == CompInfo::Successful) {\n            D = eigsh.eigenvalues();\n            V = eigsh.eigenvectors();\n        }\n        return static_cast<int>(eigsh.info());\n    }\n}\n\n// Generalized eigen solver for real symmetric matrices\nextern \"C\" const int spectral_geigsh( \n    int k,\n    void* d, void* v, \n    const void* a, int n,\n    const void* values, const void* outerIndexPtr, const void* innerIndices, int s,\n    const int ncv, int maxit, double tol,\n    const int select)\n{\n    typedef Map< Matrix<T1,Dynamic,Dynamic> > MapMatrix;\n    typedef Map<const SparseMatrix<T1> > MapSparseMatrix;\n    MapMatrix A((T1*)a, n, n);\n    MapSparseMatrix B(n, n, s, (int*)outerIndexPtr, (int*)innerIndices, (T1*)values);\n    MapMatrix D((T1*)d, k, 1);\n    MapMatrix V((T1*)v, n, k);\n\n    DenseSymMatProd<double> op(A);\n    SparseCholesky<double> Bop(B);\n\n    SymGEigsSolver<DenseSymMatProd<double>, SparseCholesky<double>, GEigsMode::Cholesky> geigs(op, Bop, k, ncv);\n\n    geigs.init();\n    int nconv = geigs.compute(static_cast<SortRule>(select), maxit, tol);\n    if(geigs.info() == CompInfo::Successful) {\n        D = geigs.eigenvalues();\n        V = geigs.eigenvectors();\n    }\n    return static_cast<int>(geigs.info());\n}\n\n\ntemplate <class T>\nRET cholesky(void* px, const void* pa, int n)\n{\n    typedef Map< Matrix<T,Dynamic,Dynamic> > MapMatrix;\n    MapMatrix x((T*)px, n, n);\n    MapMatrix A((T*)pa, n, n);\n    x = A.llt().matrixL();\n    return 0;\n}\nAPI(cholesky, (int code,\n    void* px, const void* pa, int n), (px,pa,n));\n\n\ntemplate <class T, class TT>\nRET bdcsvd(\n    void* pu, void* ps, void* pv, \n    const void* px, int r, int c)\n{\n    int m = r < c ? r : c;\n    typedef Map< Matrix<T,Dynamic,Dynamic> > MapMatrix;\n    typedef Map< Matrix<TT,Dynamic,Dynamic> > MapMatrix2;\n    MapMatrix A((T*)px, r, c);\n    MapMatrix U((T*)pu, r, m);\n    MapMatrix2 s((TT*)ps, m, 1);\n    MapMatrix V((T*)pv, c, m);\n    BDCSVD< Matrix<T,Dynamic,Dynamic>> svd(A, ComputeThinU|ComputeThinV);\n    U = svd.matrixU();\n    V = svd.matrixV();\n    s = svd.singularValues();\n    return 0;\n}\nAPI2(bdcsvd, (int code,\n    void* pu, void* ps, void* pv, const void* px, int r, int c), (pu,ps,pv,px,r,c));", "meta": {"hexsha": "10a4287a5c6e6fba31c6a34ad4fa0d75fe5ebfcf", "size": 8341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cbits/eigen-solver.cpp", "max_stars_repo_name": "kaizhang/matrix-sized", "max_stars_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cbits/eigen-solver.cpp", "max_issues_repo_name": "kaizhang/matrix-sized", "max_issues_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cbits/eigen-solver.cpp", "max_forks_repo_name": "kaizhang/matrix-sized", "max_forks_repo_head_hexsha": "aed69651b2da5ca4c9076c8c4d981b876932e5b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1844262295, "max_line_length": 112, "alphanum_fraction": 0.6211485433, "num_tokens": 2524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6293469078080746}}
{"text": "/**\n * @file    gaussNewton.hpp\n * @brief   This provides the Gauss-Newton algorithm for Non-Linear Least Squares\n * @author  Shubham Shrivastava\n */\n\n#ifndef GAUSS_NEWTON_H_\n#define GAUSS_NEWTON_H_\n\n#include <Eigen/Dense>\n#include \"tapl/common/common.hpp\"\n\nnamespace tapl {\n    namespace optim {\n\n        /**< Gauss-Newton Optimizer */\n        class GaussNewtonOptimizer {\n        public:\n            /**\n             * @brief Compute reprojection error of an estimated 3d point in multiple cameras\n             *\n             * @param[in] point3d estimated 3d point\n             * @param[in] points2d projection of the same 3d point in 'n' cameras\n             * @param[in] projectionMatrices projection matrices of 'n' cameras (n x 3 x 4)\n             * @param[out] errors reprojection error in 'n' cameras (n x 2)\n             */\n            Eigen::MatrixXd reprojectionError( \n                                    const Eigen::MatrixXd &point3d,\n                                    const std::vector<tapl::Point2d> &points2d,\n                                    const std::vector<Eigen::MatrixXd> &projectionMatrices) {\n                \n                // build homogeneous point\n                Eigen::MatrixXd point3d_homogeneous(4,1);\n                point3d_homogeneous.block<3,1>(0,0) << point3d;\n                point3d_homogeneous.block<1,1>(3,0) << 1.0;\n                \n                // reprojection errors\n                Eigen::MatrixXd errors(projectionMatrices.size()*2,1);\n                // go through each camera\n                for (auto it=projectionMatrices.begin();\n                          it!=projectionMatrices.end();\n                          ++it) {\n                    // project to camera plane\n                    Eigen::MatrixXd point2d_homogeneous(1,3); \n                    point2d_homogeneous = (*it) * point3d_homogeneous;\n                    Eigen::MatrixXd point2d_euclidean(2,1); \n                    point2d_euclidean << (point2d_homogeneous(0,0) / point2d_homogeneous(2,0)),\n                                         (point2d_homogeneous(1,0) / point2d_homogeneous(2,0));\n                    // compute reprojection error\n                    auto cam_idx = std::distance(projectionMatrices.begin(), it);\n                    Eigen::MatrixXd reprojection_err(2,1);\n                    Eigen::MatrixXd points2d_eigen(2,1);\n                    points2d_eigen << points2d[cam_idx].x, points2d[cam_idx].y;\n                    reprojection_err << (point2d_euclidean - points2d_eigen);\n                    errors.block<2,1>(2*cam_idx,0) = reprojection_err;\n                }\n                // return reprojection errors\n                return errors;\n            }\n\n            /**\n             * @brief Given a 3D point and its corresponding points in the image \n             *         planes, compute the associated Jacobian\n             *\n             * @param[in] point3d estimated 3d point\n             * @param[in] projectionMatrices projection matrices of 'n' cameras (n x 3 x 4)\n             *\n             * @return J Jacobian Matrix\n             */\n            const Eigen::MatrixXd jacobian( \n                            const Eigen::MatrixXd &point3d,\n                            const std::vector<Eigen::MatrixXd> &projectionMatrices) {\n\n                // build homogeneous point\n                Eigen::MatrixXd point3d_homogeneous(4,1);\n                point3d_homogeneous.block<3,1>(0,0) << point3d;\n                point3d_homogeneous.block<1,1>(3,0) << 1.0;\n\n                // jacobian matrix\n                Eigen::MatrixXd J(projectionMatrices.size()*2,3);\n                // go through each camera\n                for (auto it=projectionMatrices.begin();\n                          it!=projectionMatrices.end();\n                          ++it) {\n                    double m1P_hat = ((*it).block<1,4>(0,0) * point3d_homogeneous)(0,0);\n                    double m2P_hat = ((*it).block<1,4>(1,0) * point3d_homogeneous)(0,0);\n                    double m3P_hat = ((*it).block<1,4>(2,0) * point3d_homogeneous)(0,0);\n\n                    // build Jacobian\n                    auto cam_idx = std::distance(projectionMatrices.begin(), it);\n                    J.block<1,3>(2*cam_idx,0) << (((*it)(0,0)*m3P_hat - (*it)(2,0)*m1P_hat) / (m3P_hat*m3P_hat)),\n                                                 (((*it)(0,1)*m3P_hat - (*it)(2,1)*m1P_hat) / (m3P_hat*m3P_hat)),\n                                                 (((*it)(0,2)*m3P_hat - (*it)(2,2)*m1P_hat) / (m3P_hat*m3P_hat));\n                    J.block<1,3>((2*cam_idx)+1,0) << (((*it)(1,0)*m3P_hat - (*it)(2,0)*m2P_hat) / (m3P_hat*m3P_hat)),\n                                                     (((*it)(1,1)*m3P_hat - (*it)(2,1)*m2P_hat) / (m3P_hat*m3P_hat)),\n                                                     (((*it)(1,2)*m3P_hat - (*it)(2,2)*m2P_hat) / (m3P_hat*m3P_hat));\n                }\n\n                // return the Jacobian Matrix\n                return J;\n            }\n\n            /**\n             * @brief Compute L2 reprojection error of an estimated 3d point in multiple cameras\n             *\n             * @param[in] point3d estimated 3d point\n             * @param[in] points2d projection of the same 3d point in 'n' cameras\n             * @param[in] projectionMatrices projection matrices of 'n' cameras (n x 3 x 4)\n             * @param[out] errors reprojection error in 'n' cameras (n x 2)\n             */\n            Eigen::MatrixXd reprojectionErrorL2( \n                                    const Eigen::MatrixXd &point3d,\n                                    const std::vector<tapl::Point2d> &points2d,\n                                    const std::vector<Eigen::MatrixXd> &projectionMatrices) {\n                \n                // build homogeneous point\n                Eigen::MatrixXd point3d_homogeneous(4,1);\n                point3d_homogeneous.block<3,1>(0,0) << point3d;\n                point3d_homogeneous.block<1,1>(3,0) << 1.0;\n                \n                // reprojection errors\n                Eigen::MatrixXd errors(projectionMatrices.size()*2,1);\n                // go through each camera\n                for (auto it=projectionMatrices.begin();\n                          it!=projectionMatrices.end();\n                          ++it) {\n                    // project to camera plane\n                    Eigen::MatrixXd point2d_homogeneous(1,3); \n                    point2d_homogeneous = (*it) * point3d_homogeneous;\n                    Eigen::MatrixXd point2d_euclidean(2,1); \n                    point2d_euclidean << (point2d_homogeneous(0,0) / point2d_homogeneous(2,0)),\n                                         (point2d_homogeneous(1,0) / point2d_homogeneous(2,0));\n                    // compute reprojection error\n                    auto cam_idx = std::distance(projectionMatrices.begin(), it);\n                    Eigen::MatrixXd reprojection_err(2,1);\n                    Eigen::MatrixXd points2d_eigen(2,1);\n                    points2d_eigen << points2d[cam_idx].x, points2d[cam_idx].y;\n                    reprojection_err << (point2d_euclidean - points2d_eigen)*(point2d_euclidean - points2d_eigen);\n                    errors.block<2,1>(2*cam_idx,0) = reprojection_err;\n                }\n                // return reprojection errors\n                return errors;\n            }\n\n            /**\n             * @brief Given a 3D point and its corresponding points in the image \n             *         planes, compute the associated Jacobian for L2 reprojection errors\n             *\n             * @param[in] point3d estimated 3d point\n             * @param[in] projectionMatrices projection matrices of 'n' cameras (n x 3 x 4)\n             *\n             * @return J Jacobian Matrix\n             */\n            const Eigen::MatrixXd jacobianL2( \n                            const Eigen::MatrixXd &point3d,\n                            const std::vector<tapl::Point2d> &points2d,\n                            const std::vector<Eigen::MatrixXd> &projectionMatrices) {\n\n                // build homogeneous point\n                Eigen::MatrixXd point3d_homogeneous(4,1);\n                point3d_homogeneous.block<3,1>(0,0) << point3d;\n                point3d_homogeneous.block<1,1>(3,0) << 1.0;\n\n                // jacobian matrix\n                Eigen::MatrixXd J(projectionMatrices.size()*2,3);\n                // compute L1 reprojection error\n                Eigen::MatrixXd reprErr = reprojectionError(point3d, points2d, projectionMatrices);\n                // go through each camera\n                for (auto it=projectionMatrices.begin();\n                          it!=projectionMatrices.end();\n                          ++it) {\n                    double m1P_hat = ((*it).block<1,4>(0,0) * point3d_homogeneous)(0,0);\n                    double m2P_hat = ((*it).block<1,4>(1,0) * point3d_homogeneous)(0,0);\n                    double m3P_hat = ((*it).block<1,4>(2,0) * point3d_homogeneous)(0,0);\n\n                    // build Jacobian\n                    auto cam_idx = std::distance(projectionMatrices.begin(), it);\n                    J.block<1,3>(2*cam_idx,0) << 2*reprErr(2*cam_idx,0)*(((*it)(0,0)*m3P_hat - (*it)(2,0)*m1P_hat) / (m3P_hat*m3P_hat)),\n                                                 2*reprErr(2*cam_idx,0)*(((*it)(0,1)*m3P_hat - (*it)(2,1)*m1P_hat) / (m3P_hat*m3P_hat)),\n                                                 2*reprErr(2*cam_idx,0)*(((*it)(0,2)*m3P_hat - (*it)(2,2)*m1P_hat) / (m3P_hat*m3P_hat));\n                    J.block<1,3>((2*cam_idx)+1,0) << 2*reprErr(2*cam_idx+1,0)*(((*it)(1,0)*m3P_hat - (*it)(2,0)*m2P_hat) / (m3P_hat*m3P_hat)),\n                                                     2*reprErr(2*cam_idx+1,0)*(((*it)(1,1)*m3P_hat - (*it)(2,1)*m2P_hat) / (m3P_hat*m3P_hat)),\n                                                     2*reprErr(2*cam_idx+1,0)*(((*it)(1,2)*m3P_hat - (*it)(2,2)*m2P_hat) / (m3P_hat*m3P_hat));\n                }\n\n                // return the Jacobian Matrix\n                return J;\n            }\n\n            /**\n             * @brief Given a 3D point and its corresponding points in the image \n             *         planes, compute the associated Jacobian\n             *\n             * @param[in] point3d initial estimate of the 3d point\n             * @param[in] points2d projection of the same 3d point in 'n' cameras\n             * @param[in] projectionMatrices projection matrices of 'n' cameras (n x 3 x 4)\n             * @param[in] nIterations projection matrices of 'n' cameras (n x 3 x 4)\n             * @param[out] optimPoint3d optimized point 3d\n             * \n             * @return pair of pre-optimization and post-optimization reprojection error norms\n             */\n             std::pair<std::vector<float>,std::vector<float>> optimize( \n                        const tapl::Point3d &point3d,\n                        const std::vector<tapl::Point2d> &points2d,\n                        const std::vector<Eigen::MatrixXd> &projectionMatrices,\n                        const uint16_t nIterations,\n                        const float reprErrorThresh,\n                        tapl::Point3d &optimPoint3d) {\n\n                Eigen::MatrixXd point3d_eigen(3,1);\n                point3d_eigen << point3d.x, point3d.y, point3d.z;\n                std::vector<float> preOptimReprErrNorm(points2d.size());\n                std::vector<float> postOptimReprErrNorm(points2d.size());\n                // log reprojection errors\n                Eigen::MatrixXd errPreOptim = reprojectionErrorL2(point3d_eigen, points2d, projectionMatrices);\n                for (auto i=0; i<points2d.size(); ++i) {\n                    preOptimReprErrNorm.at(i) = sqrt( errPreOptim(2*i,0)*errPreOptim(2*i,0) + \n                                                      errPreOptim(2*i+1,0)*errPreOptim(2*i+1,0));\n                }\n                // start optimization\n                for (auto n=0; n<nIterations; ++n) {\n                    errPreOptim = \n                        reprojectionErrorL2(point3d_eigen, points2d, projectionMatrices);\n                    auto errPreOptimNorm = sqrt( errPreOptim(0,0)*errPreOptim(0,0) + \n                                                 errPreOptim(1,0)*errPreOptim(1,0));\n                    if (errPreOptimNorm < reprErrorThresh) {break;}\n                    auto J = jacobianL2(point3d_eigen, points2d, projectionMatrices);\n                    point3d_eigen = point3d_eigen - (((J.transpose() * J).inverse()) * J.transpose() * errPreOptim);\n                }\n                Eigen::MatrixXd errPostOptim = reprojectionErrorL2(point3d_eigen, points2d, projectionMatrices);\n                for (auto i=0; i<points2d.size(); ++i) {\n                    postOptimReprErrNorm.at(i) = sqrt( errPostOptim(2*i,0)*errPostOptim(2*i,0) + \n                                                       errPostOptim(2*i+1,0)*errPostOptim(2*i+1,0));\n                }\n\n                // optimized point\n                optimPoint3d = *(new tapl::Point3d(point3d_eigen(0), point3d_eigen(1), point3d_eigen(2)));\n\n                // return optimization errors\n                return std::make_pair(preOptimReprErrNorm, postOptimReprErrNorm);\n            }\n        };\n    } \n} \n\n#endif /* GAUSS_NEWTON_H_ */", "meta": {"hexsha": "6ba2e8478bade69f45a82f200debcdeb4f549d37", "size": 13245, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tapl/optim/gaussNewton.hpp", "max_stars_repo_name": "towardsautonomy/TAPL", "max_stars_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T12:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T12:53:17.000Z", "max_issues_repo_path": "tapl/optim/gaussNewton.hpp", "max_issues_repo_name": "towardsautonomy/TAPL", "max_issues_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tapl/optim/gaussNewton.hpp", "max_forks_repo_name": "towardsautonomy/TAPL", "max_forks_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.8414634146, "max_line_length": 142, "alphanum_fraction": 0.4993582484, "num_tokens": 3342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.6293356153882105}}
{"text": "// simple feed-forward neural network\n#pragma once\n#include <Eigen/Core>\n\nusing Eigen::Matrix;\n\n// MatrixXd Sigmoid(MatrixXd const& x) {\n//   return 1.0 / (1.0 + (-x).array().exp());\n// }\n\ninline float relu(float x) {\n  return (x > 0) ? x : 0;\n}\n\n// measured 2x overall slowdown when using MatrixXf instead of template\ntemplate <int n_inputs, int n_hidden, int n_outputs>\nclass SmallNN {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  Matrix<float, n_hidden, n_inputs> w0;\n  Matrix<float, n_hidden, 1> b0;\n  Matrix<float, n_outputs, n_hidden> w1;\n  Matrix<float, n_outputs, 1> b1;\n\n  Matrix<float, n_outputs, 1> predict(Matrix<float, n_inputs, 1> inputs) {\n    Matrix<float, n_hidden, 1> a1 = w0 * inputs + b0;\n    for (int i=0; i<n_hidden; i++) a1(i) = relu(a1(i));  // faster than unaryExpr\n    Matrix<float, n_outputs, 1> a2 = w1 * a1 + b1;\n\n    // somewhat hacky residual connection, but it measurably helps\n    a2 *= 0.1;\n    static_assert(n_outputs <= n_hidden, \"n_hidden must be >= n_outputs\");\n    for (int i=0; i<n_outputs; i++) {\n      a2(i) += a1(i);\n    }\n    a2 *= 1.0 / (1.0 + 0.1);\n\n    return a2;\n  }\n};\n", "meta": {"hexsha": "a804d3161efa2dada5c0b4215f2eca97f32c9e62", "size": 1118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "world/nn.hpp", "max_stars_repo_name": "martinxyz/pixelcrawl", "max_stars_repo_head_hexsha": "e1218be20ec2fb65ab577b366f54546b59db5854", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-24T13:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-26T08:50:21.000Z", "max_issues_repo_path": "world/nn.hpp", "max_issues_repo_name": "martinxyz/pixelcrawl", "max_issues_repo_head_hexsha": "e1218be20ec2fb65ab577b366f54546b59db5854", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T02:21:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T02:21:46.000Z", "max_forks_repo_path": "world/nn.hpp", "max_forks_repo_name": "martinxyz/pixelcrawl", "max_forks_repo_head_hexsha": "e1218be20ec2fb65ab577b366f54546b59db5854", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T13:32:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T13:32:10.000Z", "avg_line_length": 27.2682926829, "max_line_length": 81, "alphanum_fraction": 0.6404293381, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6292796326777281}}
{"text": "#ifndef CANNON_ML_WOLFE_CONDITIONS_H\n#define CANNON_ML_WOLFE_CONDITIONS_H \n\n/*!\n * \\file cannon/ml/wolfe_conditions.hpp\n * \\brief File containing utility functions relating to line search and\n * sufficient decrease conditions.\n */\n\n#include <functional>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nusing RealFunc = std::function<double(const VectorXd&)>;\nusing MultiFunc = std::function<VectorXd(const VectorXd&)>;\n\nnamespace cannon {\n  namespace ml {\n\n    /*!\n     * \\brief Compute whether the input step along the input direction\n     * satisfies the Armijo sufficient decrease condition with respect to the\n     * function under consideration.\n     *\n     * \\param f The function being optimized\n     * \\param f_grad Gradient of the function being optimized\n     * \\param x Current state from which to compute sufficient decrease\n     * \\param step Step along direction from x\n     * \\param direction Optimization direction\n     * \\param c_1 Sufficient decrease parameter\n     *\n     * \\returns Whether the sufficient decrease condition is satisfied.\n     */\n    bool sufficient_decrease_condition(RealFunc f, MultiFunc f_grad, const\n        VectorXd& x, double step, const VectorXd& direction, double c_1);\n\n    /*!\n     * \\brief Compute whether the input step along the input direction\n     * satisfies the curvature condition.\n     *\n     * \\param f The function being optimized\n     * \\param f_grad Gradient of the function being optimized\n     * \\param x Current state from which to compute sufficient decrease\n     * \\param step Step along direction from x\n     * \\param direction Optimization direction\n     * \\param c_2 Curvature parameter\n     */\n    bool curvature_condition(RealFunc f, MultiFunc f_grad, const\n        VectorXd& x, double step, const VectorXd& direction, double c_2);\n\n    /*!\n     * \\brief Compute whether both Wolfe conditions are satisfied by the input\n     * step along the input direction.\n     *\n     * \\param f The function being optimized\n     * \\param f_grad Gradient of the function being optimized\n     * \\param x Current state from which to compute sufficient decrease\n     * \\param step Step along direction from x\n     * \\param direction Optimization direction\n     * \\param c_1 Sufficient decrease parameter\n     * \\param c_2 Curvature parameter\n     */\n    bool wolfe_conditions(RealFunc f, MultiFunc f_grad, const\n        VectorXd& x, double step, const VectorXd& direction, double c_1, \n        double c_2);\n\n    /*!\n     * \\brief Compute the optimal line search step between the input minimum\n     * and maximum along the input direction.  Note that this is the minimizing\n     * step.\n     *\n     * \\param f The function to be minimized.\n     * \\param f_grad Gradient function for the function to be minimized.\n     * \\param x State to conduct line search from\n     * \\param direction Direction for line search\n     * \\param start_low Initial minimal step\n     * \\param start_high Initial maximal step\n     * \\param c_1 Sufficient decrease parameter\n     * \\param c_2 Curvature parameter\n     * \\param iterations Maximum number of iterations.\n     */\n    double line_search_zoom(RealFunc f, MultiFunc f_grad, const VectorXd& x,\n        const VectorXd& direction, double start_low, double start_high,\n        double c_1, double c_2, unsigned int iterations=100);\n\n    /*!\n     * \\brief Compute the optimal line search step along the input direction,\n     * moving as far as possible while satisfying the Wolfe conditions.  Note\n     * that this is the minimizing step.\n     *\n     * \\param f The function to be minimized.\n     * \\param f_grad Gradient function for the function to be minimized.\n     * \\param x State to conduct line search from\n     * \\param direction Direction for line search\n     * \\param step_1 Initial step to consider\n     * \\param c_1 Sufficient decrease parameter\n     * \\param c_2 Curvature parameter\n     * \\param iterations Maximum number of iterations.\n     */\n    // Returns optimal step. Note that this is the minimizing step, not the maximizing.\n    double wolfe_condition_line_search(RealFunc f, MultiFunc f_grad, const\n        VectorXd& x, const VectorXd& direction, double step_1 = 1.0, double c_1 = 1e-4, \n        double c_2 = 0.5, unsigned int iterations=100);\n\n  } // namespace ml\n} // namespace cannon\n\n#endif /* ifndef CANNON_ML_WOLFE_CONDITIONS_H */\n", "meta": {"hexsha": "96e273c6efa69d8fca0d57a182f55b4883529632", "size": 4345, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/ml/wolfe_conditions.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/ml/wolfe_conditions.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/ml/wolfe_conditions.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": 39.1441441441, "max_line_length": 88, "alphanum_fraction": 0.7054085155, "num_tokens": 997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.629231907341757}}
{"text": "/*******************************************************************************\n * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.\n * \n * Licensed under the MIT License (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://opensource.org/licenses/MIT\n * \n * Developers:\n *   Sebastian Niemann - Lead developer\n *   Daniel Kiechle - Unit testing\n ******************************************************************************/\n#include <Expected.hpp>\nusing armadilloJava::Expected;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <utility>\nusing std::pair;\n\n#include <armadillo>\nusing arma::Mat;\nusing arma::det;\nusing arma::log_det;\nusing arma::trace;\nusing arma::diagmat;\nusing arma::symmatu;\nusing arma::symmatl;\nusing arma::trimatu;\nusing arma::trimatl;\n\n#include <InputClass.hpp>\nusing armadilloJava::InputClass;\n\n#include <Input.hpp>\nusing armadilloJava::Input;\n\nnamespace armadilloJava {\n  class ExpectedSquMat : public Expected {\n    public:\n      ExpectedSquMat() {\n        cout << \"Compute ExpectedSquMat(): \" << endl;\n\n          vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({\n            InputClass::SquMat\n          });\n\n          for (vector<pair<string, void*>> input : inputs) {\n            _fileSuffix = \"\";\n\n            int n = 0;\n            for (pair<string, void*> value : input) {\n              switch (n) {\n                case 0:\n                  _fileSuffix += value.first;\n                  _squMat = *static_cast<Mat<double>*>(value.second);\n                  break;\n              }\n              ++n;\n            }\n\n            cout << \"Using input: \" << _fileSuffix << endl;\n\n            expectedArmaDet();\n            expectedArmaLog_det();\n            expectedArmaTrace();\n            expectedArmaDiagmat();\n            expectedArmaSymmatu();\n            expectedArmaSymmatl();\n            expectedArmaTrimatu();\n            expectedArmaTrimatl();\n          }\n\n          cout << \"done.\" << endl;\n        }\n\n    protected:\n      Mat<double> _squMat;\n\n      void expectedArmaDet() {\n        cout << \"- Compute expectedArmaDet() ... \";\n        save<double>(\"Arma.det\", Mat<double>({det(_squMat)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaLog_det() {\n        cout << \"- Compute expectedArmaLog_det() ... \";\n\n        double val, sign;\n\n        log_det(val, sign, _squMat);\n\n        save<double>(\"Arma.log_detVal\", Mat<double>({val}));\n        save<double>(\"Arma.log_detSign\", Mat<double>({sign}));\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrace() {\n        cout << \"- Compute expectedArmaTrace() ... \";\n        save<double>(\"Arma.trace\", Mat<double>({trace(_squMat)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaDiagmat() {\n        cout << \"- Compute expectedArmaDiagmat() ... \";\n        save<double>(\"Arma.diagmat\", diagmat(_squMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSymmatu() {\n        cout << \"- Compute expectedArmaSymmatu() ... \";\n        save<double>(\"Arma.symmatu\", symmatu(_squMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSymmatl() {\n        cout << \"- Compute expectedArmaSymmatl() ... \";\n        save<double>(\"Arma.symmatl\", symmatl(_squMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrimatu() {\n        cout << \"- Compute expectedArmaTrimatu() ... \";\n        save<double>(\"Arma.trimatu\", trimatu(_squMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrimatl() {\n        cout << \"- Compute expectedArmaTrimatl() ... \";\n        save<double>(\"Arma.trimatl\", trimatl(_squMat));\n        cout << \"done.\" << endl;\n      }\n  };\n}\n", "meta": {"hexsha": "374d00b23b10aed6500ed502e10f7c846fa6937d", "size": 3791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/src/ExpectedSquMat.cpp", "max_stars_repo_name": "SebastianNiemann/ArmadilloJava", "max_stars_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T02:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-15T07:43:53.000Z", "max_issues_repo_path": "src/test/cpp/src/ExpectedSquMat.cpp", "max_issues_repo_name": "sebiniemann/ArmadilloJava", "max_issues_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-10-20T21:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T21:53:47.000Z", "max_forks_repo_path": "src/test/cpp/src/ExpectedSquMat.cpp", "max_forks_repo_name": "sebiniemann/ArmadilloJava", "max_forks_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T17:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:45:14.000Z", "avg_line_length": 27.273381295, "max_line_length": 81, "alphanum_fraction": 0.5323133738, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6292318961335038}}
{"text": "#include \"RBGL.hpp\"\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n\nextern \"C\"\n{\n\n    SEXP BGL_KMST_D( SEXP num_verts_in, SEXP num_edges_in,\n                     SEXP R_edges_in, SEXP R_weights_in)\n    {\n        using namespace boost;\n\n        typedef graph_traits < Graph_dd >::edge_descriptor Edge;\n        typedef graph_traits < Graph_dd >::vertex_descriptor Vertex;\n        Graph_dd g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n        property_map < Graph_dd, edge_weight_t >::type weight = get(edge_weight, g);\n\n        std::vector < Edge > spanning_tree;\n\n        kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n        SEXP ansList, ans, answt;\n        PROTECT(ansList = allocVector(VECSXP,2));\n        PROTECT(ans = allocMatrix(INTSXP,2,spanning_tree.size()));\n        PROTECT(answt = allocMatrix(REALSXP,1,spanning_tree.size()));\n        int k = 0, j = 0;\n\n        for (std::vector < Edge >::iterator ei = spanning_tree.begin();\n                ei != spanning_tree.end(); ++ei)\n        {\n            INTEGER(ans)[k++] = source(*ei,g);\n            INTEGER(ans)[k++] = target(*ei,g);\n            REAL(answt)[j++] = weight[*ei];\n        }\n\n        SET_VECTOR_ELT(ansList,0,ans);\n        SET_VECTOR_ELT(ansList,1,answt);\n        UNPROTECT(3);\n        return(ansList);\n    } \n\n    SEXP BGL_KMST_U( SEXP num_verts_in, SEXP num_edges_in,\n                     SEXP R_edges_in, SEXP R_weights_in)\n    {\n        using namespace boost;\n\n        typedef graph_traits < Graph_ud >::edge_descriptor Edge;\n        typedef graph_traits < Graph_ud >::vertex_descriptor Vertex;\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n        property_map < Graph_ud, edge_weight_t >::type weight = get(edge_weight, g);\n\n        std::vector < Edge > spanning_tree;\n\n        kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n        SEXP ansList, ans, answt;\n        PROTECT(ansList = allocVector(VECSXP,2));\n        PROTECT(ans = allocMatrix(INTSXP,2,spanning_tree.size()));\n        PROTECT(answt = allocMatrix(REALSXP,1,spanning_tree.size()));\n\n        int k = 0, j = 0;\n        for (std::vector < Edge >::iterator ei = spanning_tree.begin();\n                ei != spanning_tree.end(); ++ei)\n        {\n            INTEGER(ans)[k++] = source(*ei,g);\n            INTEGER(ans)[k++] = target(*ei,g);\n            REAL(answt)[j++] = weight[*ei];\n        }\n\n        SET_VECTOR_ELT(ansList,0,ans);\n        SET_VECTOR_ELT(ansList,1,answt);\n        UNPROTECT(3);\n        return(ansList);\n    } \n\n    SEXP BGL_PRIM_U( SEXP num_verts_in, SEXP num_edges_in,\n                     SEXP R_edges_in, SEXP R_weights_in)\n    {\n        using namespace boost;\n\n        typedef graph_traits < Graph_ud >::edge_descriptor Edge;\n        typedef graph_traits < Graph_ud >::vertex_descriptor Vertex;\n\n        Graph_ud g(num_verts_in, num_edges_in, R_edges_in, R_weights_in);\n\n\tint NV = asInteger(num_verts_in);\n        std::vector <Vertex> parent(NV);\n\n        prim_minimum_spanning_tree(g, &parent[0]);\n\n        property_map<Graph_ud, edge_weight_t>::type weight = get(edge_weight, g);\n\n        SEXP ansList, ans, answt;\n        PROTECT(ansList = allocVector(VECSXP,2));\n        PROTECT(ans = allocMatrix(INTSXP,2,NV));\n        PROTECT(answt = allocMatrix(REALSXP,1,NV));\n\n        int k = 0, j = 0;\n        for (unsigned int v = 0; v < num_vertices(g); ++v)\n\t{\n            INTEGER(ans)[k++] = parent[v];\n            INTEGER(ans)[k++] = v;\n            REAL(answt)[j++] = ( parent[v] == v) ? \n\t\t\t 0 : get(weight, edge(parent[v], v, g).first);\n\t}\n\n        SET_VECTOR_ELT(ansList,0,ans);\n        SET_VECTOR_ELT(ansList,1,answt);\n        UNPROTECT(3);\n        return(ansList);\n    }\n\n}\n\n", "meta": {"hexsha": "61d240a87cea0360314af53911a224020fc8d3af", "size": 3781, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/minST.cpp", "max_stars_repo_name": "cran/RBGL", "max_stars_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-29T11:20:31.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-29T11:20:31.000Z", "max_issues_repo_path": "src/minST.cpp", "max_issues_repo_name": "cran/RBGL", "max_issues_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/minST.cpp", "max_forks_repo_name": "cran/RBGL", "max_forks_repo_head_hexsha": "e5d1a5109bf1dfbd6882bf50b6650ddc9da5ffb8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8782608696, "max_line_length": 84, "alphanum_fraction": 0.6019571542, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6292318822740393}}
{"text": "#include <gtest/gtest.h>\n#include <stdexcept>\n#include <cmath>\n#include <Eigen/Dense>\n\n// testing following API\n#include \"probability/sampling.h\"\n\nusing namespace Eigen;\nusing namespace probability;\n\nnamespace SamplingTest \n{\n  void sampleNormalAndApproximate(VectorXd mean, MatrixXd covariance)\n  {\n    int N = 10000;\n    \n    // sum up for approximating the mean and variance\n    VectorXd meanApprox = VectorXd::Zero(mean.size());\n    MatrixXd covarianceApprox = MatrixXd::Zero(covariance.rows(), covariance.cols());\n\n    // create N samples\n    for (int i = 0; i < N; i++)\n    {\n      VectorXd sample = sampleNormalDistribution(mean, covariance);\n\n      // accumulate for mean\n      meanApprox = meanApprox + sample;\n\n      // accumulate for variance (take true mean for calculation\n      // otherwise we would have to save the samples)\n      covarianceApprox = covarianceApprox + (sample - mean)*((sample - mean).transpose());\n    }\n\n    meanApprox = meanApprox / N;\n    covarianceApprox = covarianceApprox / N;\n\n    for (int i = 0; i < mean.size(); i++)\n    {\n      EXPECT_NEAR(mean[i], meanApprox[i], 0.1);\n      for (int j = 0; j < covariance.cols(); j++)\n    \tEXPECT_NEAR(covariance(i,j), covarianceApprox(i,j), 0.2);\n    }\n  }\n\n  VectorXd meanOfUniform(VectorXd a, VectorXd b)\n  {\n    int N = 1000;\n    \n    // sum up for approximating the mean and variance\n    VectorXd meanApprox = VectorXd::Zero(a.size());\n\n    // create N samples\n    for (int i = 0; i < N; i++)\n    {\n      VectorXd sample = sampleUniformDistribution(a, b);\n      meanApprox = meanApprox + sample;\t// accumulate for mean\n    }\n\n    meanApprox = meanApprox / N;\n\n    return meanApprox;\n  }\n\n  // -----------------------------------------\n  // tests\n  // -----------------------------------------\n  TEST(SamplingTest, sampleNormalDistribution)\n  {\n    // random vector: size = 1 (like a random variable) ---------------\n    VectorXd mean1(1); \n    mean1 << 0;\n    MatrixXd variance1(1,1); \n    variance1 << 1;\n    EXPECT_NO_THROW(sampleNormalAndApproximate(mean1, variance1));\n\n    // random vector: size = 3 ----------------------------------------\n    VectorXd mean2(3); \n    mean2 << -1, 0, 1;\n    MatrixXd covariance2(3,3);\n    covariance2 << \n      0.5, 0, 0, \n        0, 1, 0,\n        0, 0, 2;\n    EXPECT_NO_THROW(sampleNormalAndApproximate(mean2, covariance2));\n\n    // random vector: size = 3, non-diagonal --------------------------\n    VectorXd mean3(3); \n    mean3 << -5, 1, 100;\n    MatrixXd covariance3(3,3);\n    covariance3 << \n        3, 0.1, 0.1, \n      0.1,   1, 0.9,\n      0.1, 0.9,   2;\n    EXPECT_NO_THROW(sampleNormalAndApproximate(mean3, covariance3));\n\n    // random vector: size = 3, non-diagonal, NOT positive definite! --\n    VectorXd mean4(2); \n    mean4 << -1000, 0;\n    MatrixXd covariance4(2,2);\n    covariance4 << \n      1, 2,\n      2, 1;\n    // throws error (cholesky decomposition failed)\n    EXPECT_ANY_THROW(sampleNormalAndApproximate(mean4, covariance4));\t\n  }\n\n  TEST(SamplingTest, sampleUniformDistribution)\n  {\n    // random vector: size = 1 (like a random variable) ---------------\n    VectorXd a1(1); \n    a1 << 0;\n    VectorXd b1(1); \n    b1 << 1;\n    VectorXd meanApprox;\n    EXPECT_NO_THROW(meanApprox = meanOfUniform(a1,b1));\n    for (int i = 0; i < meanApprox.size(); i++)\n      EXPECT_NEAR((a1[i]+b1[i])/2, meanApprox[i], 0.2);\n\n    // random vector: size = 2 ----------------------------------------\n    VectorXd a2(2); \n    a2 << -3, 0;\n    VectorXd b2(2);\n    b2 << 3, 2;\n    EXPECT_NO_THROW(meanApprox = meanOfUniform(a2, b2));\n    for (int i = 0; i < meanApprox.size(); i++)\n      EXPECT_NEAR((a2[i]+b2[i])/2, meanApprox[i], 0.2);\n\n    // check if really random!\n    VectorXd meanApprox1 = meanOfUniform(a2, b2);\n    VectorXd meanApprox2 = meanOfUniform(a2, b2);\n    EXPECT_GT(fabs(meanApprox1[0] - meanApprox2[0]), 0.000001);\n  }\n}\n", "meta": {"hexsha": "2ce9279b6f21f9429f72e335963220b0d3d0f34a", "size": 3864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sf_estimation/tests/utest_sampling.cpp", "max_stars_repo_name": "tuw-cpsg/sf-pkg", "max_stars_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T09:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T16:01:11.000Z", "max_issues_repo_path": "sf_estimation/tests/utest_sampling.cpp", "max_issues_repo_name": "ros-agriculture/sf-pkg", "max_issues_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T04:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-13T14:39:24.000Z", "max_forks_repo_path": "sf_estimation/tests/utest_sampling.cpp", "max_forks_repo_name": "tuw-cpsg/sf-pkg", "max_forks_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-17T21:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T17:00:28.000Z", "avg_line_length": 28.6222222222, "max_line_length": 90, "alphanum_fraction": 0.5859213251, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6291268888173104}}
{"text": "\n//==================================================\n// newton\n//==================================================\n#include <iostream>\n#include <valarray>\n#include <boost/function.hpp>\n/*\n \u25c6\u958b\u767a\u74b0\u5883\n [OS]: macOS 10.14~\n [c++] gcc version 9.2.0\n [boost] 1.71.0\n \n */\n// \u30c6\u30b9\u30c8\u7528\u30d1\u30e9\u30e1\u30fc\u30bf\u30fc\u30af\u30e9\u30b9\nclass Param\n{\n    public:\n        double t=0;\n        double x=0;\n        double y=0;\n};\n\n\nclass Newton\n{\n    private:\n        double f( double t, double ox, boost::function<double(double, Param)> method, Param _param )\n        {\n            double x;\n            double _dif;\n            x = method(t, _param);\n            _dif = ox - x;\n            return _dif;\n        }\n        \n        double df( double t, double ox, boost::function<double(double, Param)> method, Param _param )\n        {\n            double x;\n            double h;\n            double dx;\n            h = 0.00001;\n            x = this->f(t, ox, method, _param);\n            dx = this->f(t+h, ox, method, _param);\n            return (dx-x)/h;\n        }\n    \n    public:\n        double newton( double initval, double ox, boost::function<double(double, Param)> method, Param _param , int count=1000000000, double ep=0.0001)\n        {\n            /*\n             ox\u306b\u6700\u3082\u8fd1\u3065\u304ft\u5024\u3092\u8fd1\u4f3c\u3059\u308b\u3002ep\u306f\u53ce\u675f\u6642\u306e\u8a31\u5bb9\u8aa4\u5dee\n             */\n            double t2;\n            double rf;\n            double rdf;\n            double t=initval;\n            for (int i=0; i<count; i++)\n                {\n                    rf = this->f(t, ox, method, _param);\n                    rdf = this->df(t, ox, method, _param);\n                    std::cout<<\"t:  \" << t <<\",   ox: \"<< ox << \",  rf: \" << rf << \",    rdf: \" << rdf << std::endl;\n                    if (rf ==0.0 || rdf==0.0)\n                        {\n                            return 0;\n                        }\n                    t2 = t - rf / rdf;\n                    if (std::abs(t2-t) < ep)\n                        {\n                            t=t2;\n                            break;\n                        }else{\n                            t=t2;\n                            continue;\n                        }\n                        return t2;\n                }\n         return t2;\n        }\n};\n\n\n// \u52d5\u4f5c\u30c6\u30b9\u30c8\u7528\ndouble testMethod(double t, Param _param)\n{\n    double result;\n    result = (_param.x*_param.x*t / (_param.y/2)) *(t*t);\n    return result;\n};\n\nint main()\n{\n    double t;\n    Param test_param;\n    test_param.t = 0.0;\n    test_param.x = 3.0;\n    test_param.y = 4.0;\n    Newton nt;\n    t = nt.newton(0.001, 200.34, testMethod, test_param, 1000000000, 0.0001);\n    std::cout<<\"result:  \" <<testMethod(t, test_param)<< std::endl;\n    std::cout<<\"t:  \" <<t<< std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "f215661f1d2c93e3a4e5f0f0905f56cdc73378b2", "size": 2671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "newton/src/newton.cpp", "max_stars_repo_name": "hiroshi-nagai/newton", "max_stars_repo_head_hexsha": "a2652d02bde0e403eeb033aadeb37255f71649e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newton/src/newton.cpp", "max_issues_repo_name": "hiroshi-nagai/newton", "max_issues_repo_head_hexsha": "a2652d02bde0e403eeb033aadeb37255f71649e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "newton/src/newton.cpp", "max_forks_repo_name": "hiroshi-nagai/newton", "max_forks_repo_head_hexsha": "a2652d02bde0e403eeb033aadeb37255f71649e1", "max_forks_repo_licenses": ["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.6826923077, "max_line_length": 151, "alphanum_fraction": 0.4032197679, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6291268831913971}}
{"text": "#include <iostream>\n#include <numeric>\n#include <type.hpp>\n\n#include <Eigen/Eigen>\n\n#include \"FEM/FEM.hpp\"\n#include \"imgui/implot.h\"\n#include \"Visualization/Visualizer.h\"\n\nstatic Float LinearInnerProduct(Float xmin, Float x_mid, Float xmax)\n{\n\treturn ((-2 + x_mid * x_mid + xmax - x_mid * (1 + xmax)) * cos(x_mid) + 2 * cos(xmax) + (1 - 2 * x_mid + xmax) * sin(x_mid) + (-1 + xmax) * sin(xmax))\n\t\t/ (x_mid - xmax) + 1 / (x_mid - xmin) * ((2 + x_mid - x_mid * x_mid + (-1 + x_mid) * xmin) * cos(x_mid) - 2 * cos(xmin) - (1 - 2 * x_mid + xmin) * sin(x_mid) + sin(xmin) - xmin * sin(xmin));\n}\n\nstatic Float LinearFunc(Float x, Float x0, Float x_left, Float x_right)\n{\n\tif (x<x_left || x>x_right)\n\t{\n\t\treturn 0;\n\t}\n\tif (x < x0)\n\t{\n\t\treturn (x - x_left) / (x0 - x_left);\n\t}\n\telse return (x - x_right) / (x0 - x_right);\n}\n\nclass LinearBaseFEM1D :public StaticFEM1D\n{\npublic:\n\tLinearBaseFEM1D(size_t size) : StaticFEM1D(), size(size)\n\t{\n\t\tmesh.resize(size);\n\t\t//A default devision is provided\n\t\tFloat h = 1.0 / (size + 1);\n\t\tfor (int i = 0; i < size; ++i)\n\t\t{\n\t\t\tmesh[i] = (i + 1) * h;\n\t\t}\n\t}\n\n\tstd::vector<Float> mesh;\n\n\tFloat Value(Float x) override\n\t{\n\t\tFloat ret = 0;\n\t\tfor (int i = 0; i < mat_size; ++i)\n\t\t{\n\t\t\tret += LinearFunc(x, MeshValue(i), MeshValue(i - 1), MeshValue(i + 1)) * coeff_()(i);\n\t\t}\n\t\treturn ret;\n\t}\n\nprivate:\n\n\t//return the indices of the functions related to the current function\n\tstd::vector<int> RelatedFuncIdx(int idx) override\n\t{\n\t\tstd::vector<int> ret;\n\t\tret.push_back(idx);\n\t\tint left = idx - 1, right = idx + 1;\n\t\tif (0 <= left && left < mat_size)\n\t\t{\n\t\t\tret.push_back(left);\n\t\t}\n\t\tif (0 <= right && right < mat_size)\n\t\t{\n\t\t\tret.push_back(right);\n\t\t}\n\t\treturn ret;\n\t}\n\n\tFloat MeshValue(int index)\n\t{\n\t\tif (index < 0)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\tif (index >= mat_size)\n\t\t{\n\t\t\treturn  1.0;\n\t\t}\n\t\treturn mesh[index];\n\t}\n\n\tFloat GradientInnerProduct(int i, int j) override\n\t{\n\t\tif (i == j)\n\t\t{\n\t\t\treturn 1.0 / (MeshValue(i) - MeshValue(i - 1)) + 1.0 / (MeshValue(i + 1) - MeshValue(i));\n\t\t}\n\t\telse if (abs(i - j) == 1)\n\t\t{\n\t\t\treturn -1.0 / abs(MeshValue(i) - MeshValue(j));\n\t\t}\n\t\telse return 0;//For robustness\n\t}\n\n\tFloat RHSInnerProduct(int i) override\n\t{\n\t\treturn LinearInnerProduct(MeshValue(i - 1), MeshValue(i), MeshValue(i + 1));\n\t}\n\nprotected:\n\n\tint size;\n\n\tFloat SelfInnerProduct(int i, int j) override\n\t{\n\t\treturn 0;\n\t}\n\n\tFloat GradientSelfInnerProduct(int i, int j) override\n\t{\n\t\treturn 0;\n\t}\n\n\tvoid SetMatSize() override\n\t{\n\t\tmat_size = size;\n\t}\n};\n\nstatic Float Quadratic(Float x, Float x_left, Float x_middle, Float x_right)\n{\n\tif (x <= x_left || x >= x_right)\n\t{\n\t\treturn 0.0;\n\t}\n\n\treturn   (x - x_left) * (x - x_right) / (x_middle - x_left) / (x_middle - x_right);\n}\n\nstatic Float QuadraticInnerProduct(Float xmin, Float xmid, Float xmax)\n{\n\t//return (2. * (1. - 2. * xmax + xmin) * cos(xmax) - 2. * (1. + xmax - 2. * xmin) * cos(xmin) + 6. * (sin(xmax) - sin(xmin)) - (xmax - xmin) * (xmax*sin(xmax) - sin(xmax) + xmin*sin(xmin) - sin(xmin))) / (xmax - xmid) / (xmid - xmin);\n\treturn  (2 * cos(xmax) - 4 * xmax * cos(xmax) + 2 * xmin * cos(xmax) - 2 * cos(xmin) - 2 * xmax * cos(xmin) +\n\t\t4 * xmin * cos(xmin) + 6 * sin(xmax) + xmax * sin(xmax) - (xmax * xmax) * sin(xmax) -\n\t\txmin * sin(xmax) + xmax * xmin * sin(xmax) - 6 * sin(xmin) + xmax * sin(xmin) -\n\t\txmin * sin(xmin) - xmax * xmin * sin(xmin) + (xmin * xmin) * sin(xmin)) /\n\t\t((xmax - xmid) * (xmid - xmin));\n}\n\nstatic Float QuadraticGradientInnerProduct(Float xmin, Float xmid, Float xmax, Float xmin2, Float xmid2, Float xmax2)\n{\n\tauto left = std::max(xmin, xmin2);\n\tauto right = std::min(xmax, xmax2);\n\n\tif (left > right)\n\t{\n\t\treturn  0;\n\t}\n\tFloat ret = -((left - right) * (4 * (left * left) + 4 * left * right + 4 * (right * right) - 3 * left * xmax -\n\t\t3 * right * xmax - 3 * left * xmax2 - 3 * right * xmax2 + 3 * xmax * xmax2 - 3 * left * xmin -\n\t\t3 * right * xmin + 3 * xmax2 * xmin - 3 * left * xmin2 - 3 * right * xmin2 + 3 * xmax * xmin2 +\n\t\t3 * xmin * xmin2)) / 3. / (xmax - xmid) / (xmax2 - xmid2) / (xmid - xmin) / (xmid2 - xmin2);\n\n\treturn ret;\n}\n\nclass QuadraticBaseFEM1D :public StaticFEM1D\n{\npublic:\n\tQuadraticBaseFEM1D(size_t size) : StaticFEM1D(), mesh_size(size), mat_size_(2 * size + 1)\n\t{\n\t\tmesh.resize(size);\n\t\t//A default division is provided\n\t\tFloat h = 1.0 / (size + 1);\n\t\tfor (int i = 0; i < size; ++i)\n\t\t{\n\t\t\tmesh[i] = (i + 1) * h;\n\t\t}\n\t}\n\n\tstd::vector<Float> mesh;\n\tsize_t mesh_size;\n\tsize_t mat_size_;\n\n\tFloat Value(Float x) override\n\t{\n\t\tFloat ret = 0;\n\t\tfor (int i = 0; i < mat_size; ++i)\n\t\t{\n\t\t\tFloat xmin, xmid, xmax;\n\t\t\tidx_to_mesh(i, xmin, xmid, xmax);\n\n\t\t\tret += Quadratic(x, xmin, xmid, xmax) * coeff_()(i);\n\t\t}\n\t\treturn ret;\n\t}\n\nprivate:\n\n\t//return the indices of the functions related to the current function\n\tstd::vector<int> RelatedFuncIdx(int idx) override\n\t{\n\t\tstd::vector<int> ret;\n\t\tif (idx < mesh_size)\n\t\t{\n\t\t\tret.push_back(idx);\n\t\t\tint left = idx - 1, right = idx + 1;\n\t\t\tif (0 <= left && left < mesh_size)\n\t\t\t{\n\t\t\t\tret.push_back(left);\n\t\t\t}\n\t\t\tif (0 <= right && right < mesh_size)\n\t\t\t{\n\t\t\t\tret.push_back(right);\n\t\t\t}\n\t\t\tret.push_back(idx + mesh_size);\n\n\t\t\tret.push_back(idx + mesh_size + 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tret.push_back(idx);\n\t\t\tint left = idx - mesh_size - 1, right = idx - mesh_size;\n\n\t\t\tif (0 <= left && left < mesh_size)\n\t\t\t{\n\t\t\t\tret.push_back(left);\n\t\t\t}\n\t\t\tif (0 <= right && right < mesh_size)\n\t\t\t{\n\t\t\t\tret.push_back(right);\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n\n\tFloat MeshValue(int index)\n\t{\n\t\tif (index < 0)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\tif (index >= mesh_size)\n\t\t{\n\t\t\treturn  1.0;\n\t\t}\n\t\treturn mesh[index];\n\t}\n\n\tvoid idx_to_mesh(int idx, Float& xmin, Float& xmid, Float& xmax)\n\t{\n\t\tif (idx < mesh_size)\n\t\t{\n\t\t\txmin = MeshValue(idx - 1);\txmid = MeshValue(idx);\txmax = MeshValue(idx + 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\txmin = MeshValue(idx - 1 - mesh_size);\n\t\t\txmid = (MeshValue(idx - mesh_size) + MeshValue(idx - 1 - mesh_size)) / 2.0;\n\t\t\txmax = MeshValue(idx - mesh_size);\n\t\t}\n\t}\n\n\tFloat GradientInnerProduct(int i, int j) override\n\t{\n\t\tFloat xmin, xmid, xmax;\n\t\tFloat xmin2, xmid2, xmax2;\n\n\t\tidx_to_mesh(i, xmin, xmid, xmax);\n\t\tidx_to_mesh(j, xmin2, xmid2, xmax2);\n\n\t\treturn QuadraticGradientInnerProduct(xmin, xmid, xmax, xmin2, xmid2, xmax2);\n\t}\n\n\tFloat RHSInnerProduct(int i) override\n\t{\n\t\tFloat xmin, xmid, xmax;\n\n\t\tidx_to_mesh(i, xmin, xmid, xmax);\n\t\treturn QuadraticInnerProduct(xmin, xmid, xmax);\n\t}\n\nprotected:\n\tFloat SelfInnerProduct(int i, int j) override\n\t{\n\t\treturn 0;\n\t}\n\n\tFloat GradientSelfInnerProduct(int i, int j) override\n\t{\n\t\treturn 0;\n\t}\n\n\tvoid SetMatSize() override\n\t{\n\t\tmat_size = mat_size_;\n\t}\n};\n\nclass FEM1DVisualizer :public Visualizer\n{\nprotected:\n\n\tvoid evaluate()\n\t{\n\t\tint segement_ = segemnt;\n\t\tLinearBaseFEM1D linear(segement_);\n\t\tQuadraticBaseFEM1D quadratic(segement_ / 2);\n\t\tlinear.evaluate();\n\t\tquadratic.evaluate();\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\tquadratic_val[i] = quadratic.Value(1.0 / (Length - 1) * i);\n\t\t\tlinear_val[i] = linear.Value(1.0 / (Length - 1) * i);\n\n\t\t\tquadratic_diff[i] = quadratic_val[i] - precise_val[i];\n\t\t\tlinear_diff[i] = linear_val[i] - precise_val[i];\n\t\t}\n\t}\n\n\tvoid AddPoint();\n\tvoid DragPoint();\n\tvoid draw(bool* p_open) override;\n\n\tstd::vector<Point2d> points;\n\tbool updated = true;\n\tint segemnt = 1;\n\n\tvoid error(std::vector<Float>& ref, std::vector<Float>& eval, Float& L_1, Float& L_2, Float& L_inf)\n\t{\n\t\tassert(ref.size() == eval.size());\n\n\t\tstd::vector<Float> minus(ref.size());\n\n\t\tfor (int i = 0; i < ref.size(); ++i)\n\t\t{\n\t\t\tminus[i] = abs(ref[i] - eval[i]);\n\t\t}\n\n\t\tL_inf = *std::max_element(minus.begin(), minus.end(), [](Float a, Float b) {return a < b; });\n\t\tL_2 = sqrt(std::accumulate(minus.begin(), minus.end(), static_cast<Float>(0), [](Float r, Float a) {return r + a * a; }) / Float(ref.size()));\n\t\tL_1 = std::accumulate(minus.begin(), minus.end(), static_cast<Float>(0), [](Float r, Float a) {return r + a; }) / Float(ref.size());\n\t}\n\npublic:\n\tFEM1DVisualizer() {\n\t\tFloat h = 1.0 / (Length - 1);\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\txs[i] = i * h;\n\t\t\trhs_f[i] = (xs[i] - 1) * sin(xs[i]);\n\t\t\tprecise_val[i] = -(2 - 2 * xs[i] + 2 * xs[i] * cos(1) - 2 * cos(xs[i]) + sin(xs[i]) - xs[i] * sin(xs[i]));\n\t\t}\n\t\tevaluate();\n\n\t\tFloat L1, L2, L_inf;\n\n\t\tsegemnt = 1;\n\t\tdo\n\t\t{\n\t\t\tevaluate();\n\n\t\t\terror(precise_val, linear_val, L1, L2, L_inf);\n\n\t\t\tpointcount.push_back(segemnt);\n\t\t\tlinear_vec_L_1.push_back(L1);\n\t\t\tlinear_vec_L_2.push_back(L2);\n\t\t\tlinear_vec_L_inf.push_back(L_inf);\n\t\t\terror(precise_val, quadratic_val, L1, L2, L_inf);\n\n\t\t\tquadratic_vec_L_1.push_back(L1);\n\t\t\tquadratic_vec_L_2.push_back(L2);\n\t\t\tquadratic_vec_L_inf.push_back(L_inf);\n\n\t\t\tsegemnt *= 2;\n\t\t} while (segemnt != 1024);\n\t\tsegemnt = 1;\n\t}\n\tconst size_t Length = 2001;\n\n\tstd::vector<Float> xs = std::vector<Float>(Length);\n\tstd::vector<Float> rhs_f = std::vector<Float>(Length);\n\tstd::vector<Float> precise_val = std::vector<Float>(Length);\n\tstd::vector<Float> quadratic_val = std::vector<Float>(Length);\n\tstd::vector<Float> linear_val = std::vector<Float>(Length);\n\tstd::vector<Float> quadratic_diff = std::vector<Float>(Length);\n\tstd::vector<Float> linear_diff = std::vector<Float>(Length);\n\n\tstd::vector<Float> pointcount;\n\tstd::vector<Float> linear_vec_L_1;\n\tstd::vector<Float> linear_vec_L_2;\n\tstd::vector<Float> linear_vec_L_inf;\n\n\tstd::vector<Float> quadratic_vec_L_1;\n\tstd::vector<Float> quadratic_vec_L_2;\n\tstd::vector<Float> quadratic_vec_L_inf;\n};\n\nvoid FEM1DVisualizer::AddPoint()\n{\n\tif (ImGui::IsMouseClicked(ImGuiMouseButton_Right))\n\t{\n\t\tauto pos = ImPlot::GetPlotMousePos();\n\t\tpoints.emplace_back(pos.x, pos.y);\n\t\tupdated = true;\n\t}\n}\n\nvoid FEM1DVisualizer::DragPoint()\n{\n\tfor (int i = 0; i < points.size(); ++i)\n\t{\n\t\tauto& point = points[i];\n\t\tupdated |= ImPlot::DragPoint((\"Point \" + std::to_string(i)).c_str(), &point.x(), &point.y());\n\t}\n}\nstatic inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); }\nvoid FEM1DVisualizer::draw(bool* p_open)\n{\n\tif (ImGui::BeginTabBar(\"Homework 1\")) {\n\t\tif (ImGui::BeginTabItem(\"FEM1D\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail() - ImVec2(0, 100), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus)) {\n\t\t\t\t//ImPlot::PlotLine(\"u\", &xs[0], &ys1[0], Length);\n\t\t\t\tImPlot::PlotLine(\"Precise solution\", &xs[0], &precise_val[0], Length);\n\t\t\t\t//ImPlot::PlotLine(\"FEM Result\", &xs[0], &ys3[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM Quadratic\", &xs[0], &quadratic_val[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM Linear\", &xs[0], &linear_val[0], Length);\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\t\t\tif (ImGui::SliderInt(\"Number of segments\", &segemnt, 1, 512))\n\t\t\t{\n\t\t\t\tevaluate();\n\t\t\t}\n\t\t\tImGui::EndTabItem();\n\t\t}\n\t\tif (ImGui::BeginTabItem(\"FEM1D difference\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail() - ImVec2(0, 100), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus)) {\n\t\t\t\t//ImPlot::PlotLine(\"u\", &xs[0], &ys1[0], Length);\n\t\t\t\t//ImPlot::PlotLine(\"FEM Result\", &xs[0], &ys3[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM diff Linear\", &xs[0], &linear_diff[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM diff Quadratic\", &xs[0], &quadratic_diff[0], Length);\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\t\t\tif (ImGui::SliderInt(\"Number of segments\", &segemnt, 1, 512))\n\t\t\t{\n\t\t\t\tsegemnt = segemnt < 1 ? 1 : segemnt;\n\t\t\t\tevaluate();\n\t\t\t}\n\t\t\tImGui::EndTabItem();\n\t\t}\n\n\t\tif (ImGui::BeginTabItem(\"Error Plot\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail() - ImVec2(0, 100), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus, ImPlotAxisFlags_LogScale, ImPlotAxisFlags_LogScale)) {\n\t\t\t\t//ImPlot::PlotLine(\"u\", &xs[0], &ys1[0], Length);\n\t\t\t\t//ImPlot::PlotLine(\"FEM Result\", &xs[0], &ys3[0], Length);\n\t\t\t\tImPlot::PlotLine(\"Linear L1    Error\", &pointcount[0], &linear_vec_L_1[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Linear L2    Error\", &pointcount[0], &linear_vec_L_2[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Linear L_inf Error\", &pointcount[0], &linear_vec_L_inf[0], pointcount.size());\n\n\t\t\t\tImPlot::PlotLine(\"Quadratic L1    Error\", &pointcount[0], &quadratic_vec_L_1[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Quadratic L2    Error\", &pointcount[0], &quadratic_vec_L_2[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Quadratic L_inf Error\", &pointcount[0], &quadratic_vec_L_inf[0], pointcount.size());\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\t\t\tif (ImGui::SliderInt(\"Number of segments\", &segemnt, 1, 100))\n\t\t\t{\n\t\t\t\tevaluate();\n\t\t\t}\n\t\t\tImGui::EndTabItem();\n\t\t}\n\t\tImGui::EndTabBar();\n\t}\n\n\tImGui::End();\n}\n\nint main()\n{\n\tFEM1DVisualizer visualizer;\n\tvisualizer.RenderLoop();\n}", "meta": {"hexsha": "d8ecc84e416fb6035b91f3d9832456b3889b73e9", "size": 12517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/FEM/FEM1D/test.cpp", "max_stars_repo_name": "Jerry-Shen0527/Numerical", "max_stars_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/FEM/FEM1D/test.cpp", "max_issues_repo_name": "Jerry-Shen0527/Numerical", "max_issues_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/FEM/FEM1D/test.cpp", "max_forks_repo_name": "Jerry-Shen0527/Numerical", "max_forks_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9151138716, "max_line_length": 235, "alphanum_fraction": 0.621874251, "num_tokens": 4361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6291268726938982}}
{"text": "#include <iostream>\n#include <list>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <kv/lp.hpp>\n\n#ifdef TEST_DD\n#include <kv/dd.hpp>\n#include <kv/rdd.hpp>\ntypedef kv::dd fl;\n#else\ntypedef double fl;\n#endif\n\n\nnamespace ub = boost::numeric::ublas;\n\nint main()\n{\n\tfl r;\n\tkv::interval<fl> ri;\n\t\n\tub::vector<fl> objfunc;\n\tstd::list< ub::vector<fl> > constraints;\n\tub::vector<fl> tmp;\n\n#ifdef TEST_DD\n\tstd::cout.precision(33);\n#else\n\tstd::cout.precision(17);\n#endif\n\n\t// simple problem\n\n\tobjfunc.resize(3);\n\ttmp.resize(3);\n\n\tobjfunc(0) = 0.;\n\tobjfunc(1) = -2.;\n\tobjfunc(2) = -1.;\n\n\ttmp(0) = -5.;\n\ttmp(1) = 1.;\n\ttmp(2) = -1.;\n\tconstraints.push_back(tmp);\n\n\ttmp(0) = -10.;\n\ttmp(1) = 1.;\n\ttmp(2) = 2.;\n\tconstraints.push_back(tmp);\n\n\tr = kv::lp_minimize(objfunc, constraints);\n\tstd::cout << r << \"\\n\";\n\n\tri.lower() = kv::lp_minimize_verified(objfunc, constraints, -1);\n\tri.upper() = kv::lp_minimize_verified(objfunc, constraints, 1);\n\tstd::cout << ri << \"\\n\";\n\n\t// simple problem by akky\n\n\tconstraints.clear();\n\tobjfunc.resize(4);\n\ttmp.resize(4);\n\n\tobjfunc(0) = 0.;\n\tobjfunc(1) = 1.;\n\tobjfunc(2) = 0.;\n\tobjfunc(3) = -1.;\n\n\ttmp(0) = -2.;\n\ttmp(1) = 1.;\n\ttmp(2) = 0.;\n\ttmp(3) = 0.;\n\tconstraints.push_back(tmp);\n\n\ttmp(0) = 0.;\n\ttmp(1) = -2.;\n\ttmp(2) = 1.;\n\ttmp(3) = 0.;\n\tconstraints.push_back(tmp);\n\n\ttmp(0) = -4.;\n\ttmp(1) = 4.;\n\ttmp(2) = -1.;\n\ttmp(3) = 0.;\n\tconstraints.push_back(tmp);\n\n\ttmp(0) = 0.;\n\ttmp(1) = -2.;\n\ttmp(2) = 0.;\n\ttmp(3) = 1.;\n\tconstraints.push_back(tmp);\n\n\ttmp(0) = 0.;\n\ttmp(1) = -4.;\n\ttmp(2) = 2.;\n\ttmp(3) = 1.;\n\tconstraints.push_back(tmp);\n\n\ttmp(0) = -4.;\n\ttmp(1) = 6.;\n\ttmp(2) = -2.;\n\ttmp(3) = -1.;\n\tconstraints.push_back(tmp);\n\n\tr = kv::lp_minimize(objfunc, constraints);\n\tstd::cout << r << \"\\n\";\n\n\tri.lower() = kv::lp_minimize_verified(objfunc, constraints, -1);\n\tri.upper() = kv::lp_minimize_verified(objfunc, constraints, 1);\n\tstd::cout << ri << \"\\n\";\n}\n", "meta": {"hexsha": "cb13369dbd5932961da088df946dff00cdb4fcb5", "size": 1912, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test-lp.cc", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "test/test-lp.cc", "max_issues_repo_name": "soonho-tri/kv", "max_issues_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "test/test-lp.cc", "max_forks_repo_name": "soonho-tri/kv", "max_forks_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 16.7719298246, "max_line_length": 65, "alphanum_fraction": 0.5957112971, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.62904503163875}}
{"text": "#include \"BSpline.h\"\n\n__pragma(warning(push, 0))\n#include <Eigen/Eigen>\n__pragma(warning(pop))\n\n#include <iostream>\n\n#include <omp.h>\n\nnamespace Chaf\n{\n\tBSpline::BSpline()\n\t{\n\t\tm_T = { 0, 0, 0 };\n\t}\n\n\tdouble BSpline::genBasis(const std::vector<double>& T, double t, size_t i, size_t k)\n\t{\n\t\tif (k == 1)\n\t\t{\n\t\t\tif ((t >= T[i] && t < T[i + 1]) || (t >= T[i] && t <= T[i + 1] && T[i + 1] == T.back()))\n\t\t\t{\n\t\t\t\treturn 1.0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 0.0;\n\t\t\t}\n\t\t}\n\t\tdouble left = 0.0;\n\t\tleft = T[i + k - 1] - T[i] == 0.0 ? 0.0 : (t - T[i]) / (T[i + k - 1] - T[i]) * genBasis(T, t, i, k - 1);\n\n\t\tdouble right = 0.0;\n\t\tright = T[i + k] - T[i + 1] == 0.0 ? 0.0 : (T[i + k] - t) / (T[i + k] - T[i + 1]) * genBasis(T, t, i + 1, k - 1);\n\n\t\treturn  left + right;\n\t}\n\n\tvoid BSpline::addPoint(const ImPlotPoint& p, PointType type)\n\t{\n\t\tTypes.push_back(type);\n\t\tControl_Points_X.push_back(p.x);\n\t\tControl_Points_Y.push_back(p.y);\n\t}\n\n\tvoid BSpline::genDeBoorPoints(std::vector<double>& x, std::vector<double>& y)\n\t{\n\t\tstd::vector<size_t> indices = { 1 };\n\t\tstd::vector<double> s;\n\t\tfor (size_t i = 0; i < Types.size(); i++)\n\t\t{\n\t\t\tindices.push_back(Types[i] + indices.back());\n\t\t\ts.push_back(static_cast<double>(i));\n\t\t}\n\n\t\tm_T.clear();\n\t\tm_T.push_back(0);\n\t\tm_T.push_back(0);\n\t\tm_T.push_back(0);\n\t\tfor (size_t i = 0; i < Types.size(); i++)\n\t\t{\n\t\t\tfor (size_t k = 0; k < Types[i]; k++)\n\t\t\t{\n\t\t\t\tm_T.push_back(static_cast<double>(i));\n\t\t\t}\n\t\t}\n\t\tm_T.push_back(static_cast<double>(Types.size() - 1));\n\t\tm_T.push_back(static_cast<double>(Types.size() - 1));\n\t\tm_T.push_back(static_cast<double>(Types.size() - 1));\n\n\t\tsize_t n = m_T.size() - 4;\n\n\t\tx.resize(n);\n\t\ty.resize(n);\n\t\tEigen::MatrixXd A(n, n);\n\t\tEigen::MatrixXd b(n, 2);\n\n\n\t\tA.setZero();\n\t\tb.setZero();\n\n\t\t// Begin\n\t\tswitch (Types[0])\n\t\t{\n\t\tcase PointType::C2:\n\t\t\tA(0, 0) = 1;\n\n\t\t\tA(1, 0) = 2;\n\t\t\tA(1, 1) = -3;\n\t\t\tA(1, 2) = 1;\n\n\t\t\tb(0, 0) = Control_Points_X[0];\n\t\t\tb(0, 1) = Control_Points_Y[0];\n\t\t\tbreak;\n\t\tcase PointType::Line:\n\t\t\tA(0, 0) = 1;\n\n\t\t\tA(1, 0) = 2;\n\t\t\tA(1, 1) = -3;\n\t\t\tA(1, 2) = 1;\n\n\t\t\tA(2, 2) = 1;\n\n\t\t\tb(0, 0) = Control_Points_X[0];\n\t\t\tb(0, 1) = Control_Points_Y[0];\n\n\t\t\tb(2, 0) = Control_Points_X[0];\n\t\t\tb(2, 1) = Control_Points_Y[0];\n\t\t\tbreak;\n\t\tcase PointType::Sharp:\n\t\t\tA(0, 0) = 1;\n\n\t\t\tA(1, 0) = 2;\n\t\t\tA(1, 1) = -3;\n\t\t\tA(1, 2) = 1;\n\n\t\t\tA(2, 2) = 1;\n\n\t\t\tA(3, 3) = 1;\n\n\t\t\tb(0, 0) = Control_Points_X[0];\n\t\t\tb(0, 1) = Control_Points_Y[0];\n\n\t\t\tb(2, 0) = Control_Points_X[0];\n\t\t\tb(2, 1) = Control_Points_Y[0];\n\n\t\t\tb(3, 0) = Control_Points_X[0];\n\t\t\tb(3, 1) = Control_Points_Y[0];\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\t// Inner\n#pragma omp parallel for\n\t\tfor (int i = 1; i < Types.size() - 1; i++)\n\t\t{\n\t\t\tsize_t index = indices[i];\n\n\t\t\tif (Types[i] == PointType::C2)\n\t\t\t{\n\t\t\t\tA(index, index - 1) = genBasis(m_T, s[i], index - 1, 4);\n\t\t\t\tA(index, index) = genBasis(m_T, s[i], index, 4);\n\t\t\t\tA(index, index + 1) = genBasis(m_T, s[i], index + 1, 4);\n\t\t\t\tb(index, 0) = Control_Points_X[i];\n\t\t\t\tb(index, 1) = Control_Points_Y[i];\n\t\t\t}\n\t\t\telse if (Types[i] == PointType::Line)\n\t\t\t{\n\t\t\t\tif (Types[i - 1] != PointType::Line)\n\t\t\t\t{\n\t\t\t\t\tA(index, index) = 2;\n\t\t\t\t\tA(index, index + 1) = -3;\n\t\t\t\t\tA(index, index + 2) = 1;\n\n\t\t\t\t\tA(index + 1, index + 1) = 1;\n\n\t\t\t\t\tb(index + 1, 0) = Control_Points_X[i];\n\t\t\t\t\tb(index + 1, 1) = Control_Points_Y[i];\n\t\t\t\t}\n\t\t\t\telse if (Types[i + 1] != PointType::Line)\n\t\t\t\t{\n\t\t\t\t\tA(index, index) = 1;\n\n\t\t\t\t\tA(index + 1, index - 1) = 1;\n\t\t\t\t\tA(index + 1, index) = -3;\n\t\t\t\t\tA(index + 1, index + 1) = 2;\n\n\t\t\t\t\tb(index, 0) = Control_Points_X[i];\n\t\t\t\t\tb(index, 1) = Control_Points_Y[i];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tA(index, index) = 1;\n\n\t\t\t\t\tA(index + 1, index + 1) = 1;\n\n\t\t\t\t\tb(index, 0) = Control_Points_X[i];\n\t\t\t\t\tb(index, 1) = Control_Points_Y[i];\n\n\t\t\t\t\tb(index + 1, 0) = Control_Points_X[i];\n\t\t\t\t\tb(index + 1, 1) = Control_Points_Y[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (Types[i] == PointType::Sharp)\n\t\t\t{\n\t\t\t\tA(index, index - 1) = 2;\n\t\t\t\tA(index, index) = -3;\n\t\t\t\tA(index, index + 1) = 1;\n\n\t\t\t\tA(index + 1, index + 1) = 1;\n\n\t\t\t\tA(index + 2, index + 1) = 1;\n\t\t\t\tA(index + 2, index + 2) = -3;\n\t\t\t\tA(index + 2, index + 3) = 2;\n\n\t\t\t\tb(index + 1, 0) = Control_Points_X[i];\n\t\t\t\tb(index + 1, 1) = Control_Points_Y[i];\n\t\t\t}\n\t\t}\n\n\n\t\t// End\n\t\tswitch (Types.back())\n\t\t{\n\t\tcase PointType::C2:\n\t\t\tA(n - 2, n - 3) = 1;\n\t\t\tA(n - 2, n - 2) = -3;\n\t\t\tA(n - 2, n - 1) = 2;\n\n\t\t\tA(n - 1, n - 1) = 1;\n\n\t\t\tb(n - 1, 0) = Control_Points_X.back();\n\t\t\tb(n - 1, 1) = Control_Points_Y.back();\n\t\t\tbreak;\n\t\tcase PointType::Line:\n\t\t\tA(n - 3, n - 3) = 1;\n\n\t\t\tA(n - 2, n - 3) = 1;\n\t\t\tA(n - 2, n - 2) = -3;\n\t\t\tA(n - 2, n - 1) = 2;\n\n\t\t\tA(n - 1, n - 1) = 1;\n\n\t\t\tb(n - 3, 0) = Control_Points_X.back();\n\t\t\tb(n - 3, 1) = Control_Points_Y.back();\n\n\t\t\tb(n - 1, 0) = Control_Points_X.back();\n\t\t\tb(n - 1, 1) = Control_Points_Y.back();\n\t\t\tbreak;\n\t\tcase PointType::Sharp:\n\t\t\tA(n - 4, n - 4) = 1;\n\n\t\t\tA(n - 3, n - 3) = 1;\n\n\t\t\tA(n - 2, n - 1) = 2;\n\t\t\tA(n - 2, n - 2) = -3;\n\t\t\tA(n - 2, n - 3) = 1;\n\n\t\t\tA(n - 1, n - 1) = 1;\n\n\t\t\tb(n - 4, 0) = Control_Points_X.back();\n\t\t\tb(n - 4, 1) = Control_Points_Y.back();\n\n\t\t\tb(n - 3, 0) = Control_Points_X.back();\n\t\t\tb(n - 3, 1) = Control_Points_Y.back();\n\n\t\t\tb(n - 1, 0) = Control_Points_X.back();\n\t\t\tb(n - 1, 1) = Control_Points_Y.back();\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\tstd::cout << A << std::endl\n\t\t\t<< \"===========\" << std::endl;\n\n\t\tEigen::MatrixXd res = A.colPivHouseholderQr().solve(b);\n\n\t\tfor (size_t i = 0; i < x.size(); i++)\n\t\t{\n\t\t\tx[i] = res(i, 0);\n\t\t\ty[i] = res(i, 1);\n\t\t}\n\t}\n\n\tvoid BSpline::genBSpline(const std::vector<double>& px, const std::vector<double>& py, std::vector<double>& x, std::vector<double>& y, size_t sample)\n\t{\n\t\tx.resize(sample+1);\n\t\ty.resize(sample+1);\n\n#pragma omp parallel for\n\t\tfor (int i = 0; i <= sample; i++)\n\t\t{\n\t\t\tdouble t = m_T.back() / static_cast<double>(sample) * static_cast<double>(i);\n\t\t\tauto p = genBSpline(px, py, t);\n\t\t\tx[i] = p.x;\n\t\t\ty[i] = p.y;\n\t\t}\n\t}\n\n\tvoid BSpline::clear()\n\t{\n\t\tm_T.clear();\n\t\tControl_Points_X.clear();\n\t\tControl_Points_Y.clear();\n\t\tTypes.clear();\n\t}\n\n\tImPlotPoint BSpline::genBSpline(const std::vector<double>& px, const std::vector<double>& py, double t)\n\t{\n\t\tImPlotPoint result = { 0.0, 0.0 };\n\t\tfor (size_t i = 0; i < px.size(); i++)\n\t\t{\n\t\t\tauto basis = genBasis(m_T, t, i, 4);\n\t\t\tresult.x += basis * px[i];\n\t\t\tresult.y += basis * py[i];\n\t\t}\n\n\t\treturn result;\n\t}\n\n\n\n}", "meta": {"hexsha": "9983cd61ed0e922562e506e5def4464c81c63dec", "size": 6288, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homework/Homeworks/Homework6/BSpline.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/Homework6/BSpline.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/Homework6/BSpline.cpp", "max_forks_repo_name": "Chaphlagical/CAGD", "max_forks_repo_head_hexsha": "55b79364a13fe062f6f7b8d061fb7bed236aa61d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-01T14:47:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T14:47:48.000Z", "avg_line_length": 20.6163934426, "max_line_length": 150, "alphanum_fraction": 0.5157442748, "num_tokens": 2609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6290450240691551}}
{"text": "#ifndef HYPSYS1D_POLYNOMIAL_BASIS_HPP\n#define HYPSYS1D_POLYNOMIAL_BASIS_HPP\n\n#include <Eigen/Dense>\n\n/// Legendre polynomial basis\nclass PolynomialBasis {\n  public:\n\n    PolynomialBasis(int q) : p(q) {\n        set_scaling_factor(1.0);\n    }\n\n    PolynomialBasis(int q, double scaling_factor_) : p(q) {\n        set_scaling_factor(scaling_factor_);\n    }\n\n    void set_scaling_factor(double scaling_factor_) const {\n        scaling_factor = scaling_factor_;\n    }\n\n    /// Computes the Legendre polynomial basis\n    /// at a given reference point xi \\in [0,1]\n    Eigen::VectorXd operator() (double xi) const;\n    \n    /// Computes the derivative of Legendre polynomial basis\n    /// at a given reference point xi \\in [0,1]\n    Eigen::VectorXd deriv (double xi) const;\n\n    int get_degree() const {\n        return p;\n    }\n\n  private:\n\n    int p;\n    mutable double scaling_factor;\n};\n\n#endif // HYPSYS1D_POLYNOMIAL_BASIS_HPP\n", "meta": {"hexsha": "09ef367267c0e70989205deecb6d90bbadb71a33", "size": 924, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_workbench/hyp_sys_1d/include/ancse/polynomial_basis.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_handout/hyp_sys_1d/include/ancse/polynomial_basis.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_handout/hyp_sys_1d/include/ancse/polynomial_basis.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 22.5365853659, "max_line_length": 60, "alphanum_fraction": 0.6785714286, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505964, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6290339762962404}}
{"text": "/* KMeansRexCore.cpp\nA fast, easy-to-read implementation of the K-Means clustering algorithm.\n  allowing customized initialization (random samples or plus plus)\n  and vectorized execution via the Eigen matrix template library.\n\nIntended to be compiled as a shared library libkmeansrex.so\n which can then be utilized from high-level interactive environments,\n  such as Matlab or Python.\n\nContains:\n  Utility Fcns: \n    discrete_rand : sampling discrete r.v.\n    select_without_replacement : sample discrete w/out replacement\n\n\n  Cluster Location Mu Initialization:\n    sampleRowsRandom : sample at random (w/out replacement)\n    sampleRowsPlusPlus : sample via K-Means++ (Arthur et al)\n              see http://en.wikipedia.org/wiki/K-means%2B%2B\n\n  K-Means Algorithm (aka Lloyd's Algorithm)\n    run_lloyd : executes lloyd for spec'd number of iterations\n\n  External \"C\" function interfaces (for calling from Python)\n    NOTE: These take only pointers to float arrays, not Eigen array types\n\n    RunKMeans          : compute cluster centers and assignments via lloyd\n    SampleRowsPlusPlus : get just a plusplus initialization\n\nDependencies:\n  mersenneTwister2002.c : random number generator\n\nAuthor: Mike Hughes (www.michaelchughes.com)\nDate:   2 April 2015\n*/\n/*\nextern \"C\" {\n  void RunKMeans(double *X_IN,  int N,  int D, int K, int Niter, int seed, char* initname, double *Mu_OUT, double *Z_OUT);\n  void SampleRowsPlusPlus(double *X_IN,  int N,  int D, int K, int seed, double *Mu_OUT);\n}\n*/\n#include <iostream>\n#include \"mersenneTwister2002.c\"\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\n/*  DEFINE Custom Type Names to make code more readable\n    ExtMat :  2-dim matrix/array externally defined (e.g. in Matlab or Python)\n*/\ntypedef Map<ArrayXXd> ExtMat;\ntypedef ArrayXXd Mat;\ntypedef ArrayXd Vec;\n\n\n// ====================================================== Utility Functions\nvoid set_seed( int seed ) {\n  init_genrand( seed );\n}\n\nint discrete_rand( Vec &p ) {\n    double total = p.sum();\n    int K = (int) p.size();\n    \n    double r = total*genrand_double();\n    double cursum = p(0);\n    int newk = 0;\n    while ( r >= cursum && newk < K-1) {\n        newk++;\n        cursum += p[newk];\n    }\n    if ( newk < 0 || newk >= K ) {\n        cerr << \"Badness. Chose illegal discrete value.\" << endl;\n        return -1;\n    }\n    return newk;\n}\n\nvoid select_without_replacement( int N, int K, Vec &chosenIDs) {\n    Vec p = Vec::Ones(N);\n    for (int kk =0; kk<K; kk++) {\n      int choice;\n      int doKeep = false;\n      while ( doKeep==false) {\n      \n        doKeep=true;\n        choice = discrete_rand( p );\n      \n        for (int previd=0; previd<kk; previd++) {\n          if (chosenIDs[previd] == choice ) {\n            doKeep = false;\n            break;\n          }\n        }      \n      }      \n      chosenIDs[kk] = choice;     \n    }\n}\n\n// ======================================================= Init Cluster Locs Mu\n\nvoid sampleRowsRandom( ExtMat &X, ExtMat &Mu ) {\n    int N = X.rows();\n    int K = Mu.rows();\n    Vec ChosenIDs = Vec::Zero(K);\n    select_without_replacement( N, K, ChosenIDs );\n\t\tfor (int kk=0; kk<K; kk++) {\n\t\t  Mu.row( kk ) = X.row( ChosenIDs[kk] );\n\t\t}\n}\n\nvoid sampleRowsPlusPlus( ExtMat &X, ExtMat &Mu ) {\n    int N = X.rows();\n    int K = Mu.rows();\n    Vec ChosenIDs = Vec::Ones(K);\n    int choice = discrete_rand( ChosenIDs );\n    Mu.row(0) = X.row( choice );\n    ChosenIDs[0] = choice;\n    Vec minDist(N);\n    Vec curDist(N);\n    for (int kk=1; kk<K; kk++) {\n      curDist = ( X.rowwise() - Mu.row(kk-1) ).square().rowwise().sum().sqrt();\n      if (kk==1) {\n        minDist = curDist;\n      } else {\n        minDist = curDist.min( minDist );\n      }      \n      choice = discrete_rand( minDist );\n      ChosenIDs[kk] = choice;\n      Mu.row(kk) = X.row( choice );\n    }       \n}\n\nvoid init_Mu( ExtMat &X, ExtMat &Mu, const char* initname ) {\t\t  \n\t  if ( string( initname ) == \"random\" ) {\n    \t\tsampleRowsRandom( X, Mu );\n\t  } else if ( string( initname ) == \"plusplus\" ) {\n  \t\t\tsampleRowsPlusPlus( X, Mu );\n\t  }\n}\n\n// ======================================================= Update Cluster Assignments Z\nvoid pairwise_distance( ExtMat &X, ExtMat &Mu, Mat &Dist ) {\n\n  int N = X.rows();\n  int D = X.cols();\n  int K = Mu.rows();\n\n  // For small dims D, for loop is noticeably faster than fully vectorized.\n  // Odd but true.  So we do fastest thing \n  if ( D <= 16 ) \n  {\n    for (int kk=0; kk<K; kk++) {\n      Dist.col(kk) = ( X.rowwise() - Mu.row(kk) ).square().rowwise().sum();\n    }\n  } \n  else \n  {\n\tDist.matrix() = -2*( X.matrix() * Mu.transpose().matrix() );\n    Dist.rowwise() += Mu.square().rowwise().sum().transpose().row(0);\n  }\n}\n\ndouble assignClosest( ExtMat &X, ExtMat &Mu, ExtMat &Z, Mat &Dist) {\n  double totalDist = 0;\n  int minRowID;\n\n  pairwise_distance( X, Mu, Dist );\n\n  for (int nn=0; nn<X.rows(); nn++) {\n    totalDist += Dist.row(nn).minCoeff( &minRowID );\n    Z(nn,0) = minRowID;\n  }\n  return totalDist;\n}\n\n// ======================================================= Update Cluster Locations Mu\nvoid calc_Mu( ExtMat &X, ExtMat &Mu, ExtMat &Z) {\n  Mu = Mat::Zero( Mu.rows(), Mu.cols() );\n  Vec NperCluster = Vec::Zero( Mu.rows() );\n  \n  for (int nn=0; nn<X.rows(); nn++) {\n    Mu.row( (int) Z(nn,0) ) += X.row( nn );\n    NperCluster[ (int) Z(nn,0)] += 1;\n  }  \n  Mu.colwise() /= NperCluster;\n}\n\n// ======================================================= Overall Lloyd Algorithm\nvoid run_lloyd( ExtMat &X, ExtMat &Mu, ExtMat &Z, int Niter )  {\n  double prevDist=INT_MAX,totalDist = 0;\n\n  Mat Dist = Mat::Zero( X.rows(), Mu.rows() );  \n\n  for (int iter=0; iter<Niter; iter++) {\n    \n    totalDist = assignClosest( X, Mu, Z, Dist );\n    calc_Mu( X, Mu, Z );\n    if ( prevDist == totalDist ) {\n      break;\n    }\n    prevDist = totalDist;\n  }\n}\n\n// =================================================================================\n// =================================================================================\n// ===========================  EXTERNALLY CALLABLE FUNCTIONS ======================\n// =================================================================================\n// =================================================================================\n\n\nvoid RunKMeans(double *X_IN,  int N,  int D, int K, int Niter,\n               int seed, const char* initname, double *Mu_OUT, double *Z_OUT) {\n  set_seed( seed );\n\n  ExtMat X  ( X_IN, N, D);\n  ExtMat Mu ( Mu_OUT, K, D);\n  ExtMat Z  ( Z_OUT, N, 1);\n\n  init_Mu( X, Mu, initname);\n  run_lloyd( X, Mu, Z, Niter );\n}\n\n\nvoid SampleRowsPlusPlus(double *X_IN,  int N,  int D, int K, int seed, double *Mu_OUT) {\n  set_seed( seed );\n\n  ExtMat X  ( X_IN, N, D);\n  ExtMat Mu ( Mu_OUT, K, D);\n\n  sampleRowsPlusPlus( X, Mu);\n}\n", "meta": {"hexsha": "64257d86923ccceb41a4fdc1915fc025f8d01db0", "size": 6764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "KMeansRexCore.cpp", "max_stars_repo_name": "edouda/linkedboxdraw", "max_stars_repo_head_hexsha": "efd6e570bce133d41cab73effa3870c93914ed0c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-09-10T21:39:56.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-10T21:39:56.000Z", "max_issues_repo_path": "KMeansRexCore.cpp", "max_issues_repo_name": "edouda/linkedboxdraw", "max_issues_repo_head_hexsha": "efd6e570bce133d41cab73effa3870c93914ed0c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 133.0, "max_issues_repo_issues_event_min_datetime": "2018-05-17T13:42:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T14:00:15.000Z", "max_forks_repo_path": "KMeansRexCore.cpp", "max_forks_repo_name": "edouda/linkedboxdraw", "max_forks_repo_head_hexsha": "efd6e570bce133d41cab73effa3870c93914ed0c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-20T12:59:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T22:05:13.000Z", "avg_line_length": 28.7829787234, "max_line_length": 122, "alphanum_fraction": 0.5473092844, "num_tokens": 1860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6290339681938102}}
{"text": "// 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// Copyright Paul A. Bristow 2015 - 2016.\n// Copyright Christopher Kormanyos 2015 - 2016.\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n// This file also includes Doxygen-style documentation about the function of the code.\n// See http://www.doxygen.org for details.\n\n//! \\file\n\n//! \\brief Example program showing use of math constants.\n\n// Below are snippets of code that are included into Quickbook file fixed_point.qbk.\n\n#include <cmath>\n#include <limits>\n#include <iomanip>\n#include <iostream>\n\n#include <boost/fixed_point/fixed_point.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n// http://www.boost.org/doc/libs/release/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/cpp_bin_float.html\n\nint main()\n{\n//[bin_float_50_pi\n  // Construct a 50 decimal digit multiprecision floating-point version of pi for reference.\n  using boost::multiprecision::cpp_bin_float_50;  // 50 decimal digits precision.\n\n  std::cout << std::setprecision(std::numeric_limits<cpp_bin_float_50>::digits10)\n    << std::fixed\n    << boost::math::constants::pi<cpp_bin_float_50>()\n    // 3.14159265358979323846264338327950288419716939937510\n    << std::endl;\n//] //[/bin_float_50_pi]\n\n  // Use a rather precice fixed_point type that uses a 64-bit integer as its underlying representation.\n//[fixed_point__constant\n  typedef boost::fixed_point::negatable<3, -60> fixed_point_type;\n\n  std::cout << std::setprecision(std::numeric_limits<fixed_point_type>::digits10)\n    << std::fixed\n    << boost::math::constants::pi<fixed_point_type>()\n    // 3.141592653589793238\n    << std::endl;\n//] [/fixed_point__constant]\n\n  // Use a small (and so very imprecise) fixed_point type that will fit into a single byte.\n//[fixed_point_imprecise_constant\n  typedef boost::fixed_point::negatable<2, -5> tiny_fixed_point_type;\n\n  std::cout << std::setprecision(std::numeric_limits<tiny_fixed_point_type>::digits10)\n    << std::fixed\n    << boost::math::constants::pi<tiny_fixed_point_type>()\n    // 3.1\n    << std::endl;\n//] [/fixed_point_imprecise_constant]\n\n  // Use a precise fixed_point type that will fit into a 128-bit 16 byte item.\n//[fixed_point_precise_constant\n\n  typedef boost::fixed_point::negatable<2, -125> precise_fixed_point_type;\n\n  std::cout << std::setprecision(std::numeric_limits<precise_fixed_point_type>::digits10)\n    << std::fixed\n    << boost::math::constants::pi<precise_fixed_point_type>()\n    // 3.1415926535897932384626433832795028842\n    << std::endl;\n//] [/fixed_point_precise_constant]\n\n} // int main()\n", "meta": {"hexsha": "91e4f09c052119cd534dec67fe3a28aeed0a35ff", "size": 3043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_constants.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_constants.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_constants.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": 37.1097560976, "max_line_length": 120, "alphanum_fraction": 0.7413736444, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.6290170575605963}}
{"text": "#include <armadillo>\n#include <gnuplot-iostream.h>\n\nusing namespace arma;\n\nint main()\n{\n    vec x = linspace(0, 2 * M_PI, 50);\n    vec y = sin(x);\n    mat puntos = join_horiz(x, y);\n\n    Gnuplot gp;\n\n    // Ejemplo b\u00e1sico\n    gp << \"plot \" << gp.file1d(y) << \"with lines\" << endl;\n\n    cout << \"Presionar Enter para continuar\\n\";\n    getchar();\n\n    // \"plot\" de Matlab\n    gp << \"set title '\\\"Plot\\\" de Matlab' font ',13'\\n\"\n       << \"set xlabel 'Tiempo (segundos)'\\n\"\n       << \"set ylabel 'Magnitud'\\n\"\n       << \"set xrange [0 : 2*pi]\\n\"\n       << \"set grid\\n\"\n       << \"unset key\\n\" // Ocultar la leyenda\n       << \"plot \" << gp.file1d(puntos) << \"with lines\" << endl;\n\n    cout << \"Presionar Enter para continuar\\n\";\n    getchar();\n\n    // \"stem\" de Matlab\n    gp << \"set title '\\\"Stem\\\" de Matlab' font ',13'\\n\"\n       << \"plot \" << gp.file1d(puntos) << \"with impulses, \"\n       << gp.file1d(puntos) << \"with points pt 7 lt 1\" << endl;\n\n    cout << \"Presionar Enter para continuar\\n\";\n    getchar();\n\n    // \"subplot\" de Matlab\n    gp << \"set terminal qt size 600,650\\n\"\n       << \"set multiplot layout 2, 1 title '\\\"Subplot\\\" de Matlab' font ',14'\\n\"\n       << \"set title '\\\"Plot\\\" de Matlab' font ',13'\\n\"\n       << \"plot \" << gp.file1d(puntos) << \"with lines\\n\"\n       << \"set title '\\\"Stem\\\" de Matlab' font ',13'\\n\"\n       << \"plot \" << gp.file1d(puntos) << \"with impulses, \"\n       << gp.file1d(puntos) << \"with points pt 7 lt 1\\n\"\n       << \"unset multiplot\" << endl;\n\n    cout << \"Presionar Enter para continuar\\n\";\n    getchar();\n\n    return 0;\n}\n", "meta": {"hexsha": "9d3f7ccdae5b4c15c4b449db03e82a56ba2557cb", "size": 1565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ejemplos/graficos.cpp", "max_stars_repo_name": "junrrein/ic2017", "max_stars_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-11T14:24:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-03T00:56:18.000Z", "max_issues_repo_path": "ejemplos/graficos.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": "ejemplos/graficos.cpp", "max_forks_repo_name": "junrrein/ic2017", "max_forks_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-18T12:32:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T12:32:49.000Z", "avg_line_length": 28.4545454545, "max_line_length": 80, "alphanum_fraction": 0.5373801917, "num_tokens": 488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.6289918669091751}}
{"text": "//  Copyright John Maddock 2007.\n//  Copyright Paul A. Bristow 2010\n\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// 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#include <iostream>\nusing std::cout; using std::endl;\n\n//[policy_ref_snip9\n\n#include <boost/math/special_functions/gamma.hpp>\nusing boost::math::tgamma;\nusing boost::math::policies::policy;\nusing boost::math::policies::digits10;\n\ntypedef policy<digits10<5> > my_pol_5; // Define a new, non-default, policy\n// to calculate tgamma to accuracy of approximately 5 decimal digits.\n//]\n\nint main()\n{\n  cout.precision(5); // To only show 5 (hopefully) accurate decimal digits.\n  double t = tgamma(12, my_pol_5()); // Apply the 5 decimal digits accuracy policy to use of tgamma.\n  cout << \"tgamma(12, my_pol_5() = \" << t << endl;\n}\n\n/*\n\nOutput:\n     tgamma(12, my_pol_5() = 3.9917e+007\n*/\n", "meta": {"hexsha": "ed38d46010318e36277b1759ff8e3c701f871f35", "size": 1076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/example/policy_ref_snip9.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/policy_ref_snip9.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/policy_ref_snip9.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 29.0810810811, "max_line_length": 100, "alphanum_fraction": 0.7156133829, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6289626895646826}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>  \n#include <iostream>\n#include <fstream>\n#include <istream> \n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <complex>\n\n#include \"codegen_helper.hpp\"\n\n#define PI 3.14159265\n\n// Read a CSV file and dump it to an Eigen Matrix\nEigen::Matrix<double, Eigen::Dynamic, 1> readCSV(std::istream &input, int matSize)\n{\n    int a = 0;\n    int b = 0;\n\n    std::string csvLine;\n    Eigen::Matrix<double, Eigen::Dynamic, 1> out;\n    out.resize(matSize*matSize);\n    // read every line from the stream\n    while( std::getline(input, csvLine) )\n    {\n\n        std::istringstream csvStream(csvLine);\n        std::vector<std::string> csvColumn;\n        std::string csvElement;\n        // read every element from the line that is seperated by commas\n        // and put it into the vector or strings\n        while( getline(csvStream, csvElement, ',') )\n        {\n            csvColumn.push_back(csvElement);\n            out[b] = std::stod(csvElement);\n            b++;\n        }       \n        a++;\n    }\n    std::cout << \"a : \" << a << \" b : \" << b << std::endl;  \n    return out;\n}\n\n// Build a complex Eigen::Matrix representing the 2D FFT coeffs from 2 files representing the real and imaginary 2D FFT matrices\ntemplate <typename Scalar>\nEigen::Matrix<std::complex<Scalar>, Eigen::Dynamic, 1> CSVtoFTcoeff(std::istream &inputReal, std::istream &inputImag, int matSize)\n{\n    std::complex<Scalar> consti;\n    consti = std::complex<double>{0,1};\n\n    Eigen::Matrix<Scalar, Eigen::Dynamic, 1> outReal;\n    Eigen::Matrix<Scalar, Eigen::Dynamic, 1> outImag;\n    Eigen::Matrix<std::complex<Scalar>, Eigen::Dynamic, 1> out;\n\n    outReal = readCSV(inputReal, matSize);\n    outImag = readCSV(inputImag, matSize);\n\n    out = outReal + consti*outImag;\n\n    return out;\n}\n\n// Evaluate a 2D function from its FT coefficients \ntemplate <typename Scalar>\nScalar evaluateFromFT(Eigen::Matrix<std::complex<Scalar>, Eigen::Dynamic, Eigen::Dynamic> FTcoeffs, Scalar x, Scalar y)\n{\n    Scalar zero;\n    zero = 0;\n    \n    std::complex<Scalar> eval;\n    eval = std::complex<double>{0,0};\n    \n    std::complex<Scalar> consti;\n    consti = std::complex<double>{0,1};\n\n    int m = (int)FTcoeffs.rows();\n    int n = (int)FTcoeffs.cols();\n\n    Scalar coeffThreshold;\n    coeffThreshold = 1e-6;\n\n    for(int i=0; i<n; i++)\n    {\n        for(int j=0; j<m; j++)\n        {   \n            Scalar coeffReal;\n            Scalar coeffImag;\n\n            coeffReal = CppAD::CondExpLt(std::abs(FTcoeffs(i,j)), coeffThreshold, zero, FTcoeffs(i,j).real());\n            coeffImag = CppAD::CondExpLt(std::abs(FTcoeffs(i,j)), coeffThreshold, zero, FTcoeffs(i,j).imag());\n            std::complex<Scalar> coeff(coeffReal, coeffImag);\n\n            eval += coeff*(cos(2*PI*(y*(i-n/2)/n + x*(j-m/2)/m)) + consti*sin(2*PI*(y*(i-n/2)/n + x*(j-m/2)/m)));\n        }\n    }\n    std::complex<Scalar> scale;\n    scale = std::complex<double>{(double)n*m,0};\n    eval/=scale;\n    return CppAD::sqrt(eval.real()*eval.real() - eval.imag()*eval.imag());\n}\n\n// Generates the model for the function f(q, pair) = dist. between frames of given pair\nADFun tapeADShoulderDistanceCheck(Eigen::Matrix<std::complex<ADScalar>, Eigen::Dynamic, Eigen::Dynamic> FTcoeffs)\n{   \n    // Initnialize AD input and output\n    Eigen::Matrix<ADScalar, Eigen::Dynamic, 1> ad_X;\n    Eigen::Matrix<ADScalar, Eigen::Dynamic, 1> ad_Y;\n    ad_X.resize(2);\n    ad_Y.resize(1);\n    CppAD::Independent(ad_X);\n    // Initialize AD function\n    ADFun ad_fun;\n\n    // Tape the function\n    ADScalar d = evaluateFromFT<ADScalar>(FTcoeffs, ad_X[0], ad_X[1]);\n    ad_Y[0] = d;\n    ad_fun.Dependent(ad_X, ad_Y);\n\n    return ad_fun;\n}\n\n\n", "meta": {"hexsha": "90140617ec5c6ba84ff1e745791356c2462b5f4d", "size": 3705, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/autocollision-shoulders-code-generation.hpp", "max_stars_repo_name": "thibnoel/solo-collisions", "max_stars_repo_head_hexsha": "87bf492266578b7bfd04a6657675b1477d27b314", "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/autocollision-shoulders-code-generation.hpp", "max_issues_repo_name": "thibnoel/solo-collisions", "max_issues_repo_head_hexsha": "87bf492266578b7bfd04a6657675b1477d27b314", "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/autocollision-shoulders-code-generation.hpp", "max_forks_repo_name": "thibnoel/solo-collisions", "max_forks_repo_head_hexsha": "87bf492266578b7bfd04a6657675b1477d27b314", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-04T07:49:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T07:49:28.000Z", "avg_line_length": 29.64, "max_line_length": 130, "alphanum_fraction": 0.6259109312, "num_tokens": 1056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.6289473694751317}}
{"text": "//\n// Copyright 2019 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n#ifndef BOOST_GIL_IMAGE_PROCESSING_NUMERIC_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_NUMERIC_HPP\n\n#include <boost/gil/detail/math.hpp>\n#include <cmath>\n#include <boost/gil/image_view.hpp>\n#include <boost/gil/typedefs.hpp>\n\nnamespace boost { namespace gil {\n\n/// \\defgroup ImageProcessingMath\n/// \\brief Math operations for IP algorithms\n///\n/// This is mostly handful of mathemtical 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)\n///\ninline double 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)\ninline double lanczos(double x, std::ptrdiff_t a)\n{\n    // means == but <= avoids compiler warning\n    if (0 <= x && x <= 0)\n        return 1;\n\n    if (-a < x && x < a)\n        return normalized_sinc(x) / normalized_sinc(x / static_cast<double>(a));\n\n    return 0;\n}\n\ninline void compute_tensor_entries(\n    boost::gil::gray16_view_t dx,\n    boost::gil::gray16_view_t dy,\n    boost::gil::gray32f_view_t m11,\n    boost::gil::gray32f_view_t m12_21,\n    boost::gil::gray32f_view_t m22)\n{\n    for (std::ptrdiff_t y = 0; y < dx.height(); ++y) {\n        for (std::ptrdiff_t x = 0; x < dx.width(); ++x) {\n            auto dx_value = dx(x, y);\n            auto dy_value = dy(x, y);\n            m11(x, y) = dx_value * dx_value;\n            m12_21(x, y) = dx_value * dy_value;\n            m22(x, y) = dy_value * dy_value;\n        }\n    }\n}\n\n/// \\brief Compute xy gradient, and second order x and y gradients\n/// \\ingroup ImageProcessingMath\n///\n/// Hessian matrix is defined as a matrix of partial derivates\n/// for 2d case, it is [[ddxx, dxdy], [dxdy, ddyy].\n/// d stands for derivative, and x or y stand for direction.\n/// For example, dx stands for derivative (gradient) in horizontal\n/// direction, and ddxx means second order derivative in horizon direction\n/// https://en.wikipedia.org/wiki/Hessian_matrix\ntemplate <typename GradientView, typename OutputView>\ninline void compute_hessian_entries(\n    GradientView dx,\n    GradientView dy,\n    OutputView ddxx,\n    OutputView dxdy,\n    OutputView ddyy)\n{\n    using x_coord_t = typename OutputView::x_coord_t;\n    using y_coord_t = typename OutputView::y_coord_t;\n    using pixel_t = typename std::remove_reference<decltype(ddxx(0, 0))>::type;\n    using channel_t = typename std::remove_reference<\n                        decltype(\n                            std::declval<pixel_t>().at(\n                                std::integral_constant<int, 0>{}\n                            )\n                        )\n                       >::type;\n\n    constexpr double x_kernel[3][3] =\n    {\n        {1, 0, -1},\n        {2, 0, -2},\n        {1, 0, -1}\n    };\n    constexpr double y_kernel[3][3] =\n    {\n        {1, 2, 1},\n        {0, 0, 0},\n        {-1, -2, -1}\n    };\n    constexpr auto chosen_channel = std::integral_constant<int, 0>{};\n    for (y_coord_t y = 1; y < ddxx.height() - 1; ++y)\n    {\n        for (x_coord_t x = 1; x < ddxx.width() - 1; ++x)\n        {\n            pixel_t ddxx_i;\n            static_transform(ddxx_i, ddxx_i,\n                [](channel_t) { return static_cast<channel_t>(0); });\n            pixel_t dxdy_i;\n            static_transform(dxdy_i, dxdy_i,\n                [](channel_t) { return static_cast<channel_t>(0); });\n            pixel_t ddyy_i;\n            static_transform(ddyy_i, ddyy_i,\n                [](channel_t) { return static_cast<channel_t>(0); });\n            for (y_coord_t y_filter = 0; y_filter < 2; ++y_filter)\n            {\n                for (x_coord_t x_filter = 0; x_filter < 2; ++x_filter)\n                {\n                    auto adjusted_y = y + y_filter - 1;\n                    auto adjusted_x = x + x_filter - 1;\n                    ddxx_i.at(std::integral_constant<int, 0>{}) +=\n                        dx(adjusted_x, adjusted_y).at(chosen_channel)\n                        * x_kernel[y_filter][x_filter];\n                    dxdy_i.at(std::integral_constant<int, 0>{}) +=\n                        dx(adjusted_x, adjusted_y).at(chosen_channel)\n                        * y_kernel[y_filter][x_filter];\n                    ddyy_i.at(std::integral_constant<int, 0>{}) +=\n                        dy(adjusted_x, adjusted_y).at(chosen_channel)\n                        * y_kernel[y_filter][x_filter];\n                }\n            }\n            ddxx(x, y) = ddxx_i;\n            dxdy(x, y) = dxdy_i;\n            ddyy(x, y) = ddyy_i;\n        }\n    }\n}\n\n/// \\brief Generate mean kernel\n/// \\ingroup ImageProcessingMath\n///\n/// Fills supplied view with normalized mean\n/// in which all entries will be equal to\n/// \\code 1 / (dst.size()) \\endcode\ninline void generate_normalized_mean(boost::gil::gray32f_view_t dst)\n{\n    if (dst.width() != dst.height() || dst.width() % 2 != 1)\n        throw std::invalid_argument(\"kernel dimensions should be odd and equal\");\n    const float entry = 1.0f / static_cast<float>(dst.size());\n\n    for (auto& pixel: dst) {\n        pixel.at(std::integral_constant<int, 0>{}) = entry;\n    }\n}\n\n/// \\brief Generate kernel with all 1s\n/// \\ingroup ImageProcessingMath\n///\n/// Fills supplied view with 1s (ones)\ninline void generate_unnormalized_mean(boost::gil::gray32f_view_t dst)\n{\n    if (dst.width() != dst.height() || dst.width() % 2 != 1)\n        throw std::invalid_argument(\"kernel dimensions should be odd and equal\");\n\n    for (auto& pixel: dst) {\n        pixel.at(std::integral_constant<int, 0>{}) = 1.0f;\n    }\n}\n\n/// \\brief Generate Gaussian kernel\n/// \\ingroup ImageProcessingMath\n///\n/// Fills supplied view with values taken from Gaussian distribution. See\n/// https://en.wikipedia.org/wiki/Gaussian_blur\ninline void generate_gaussian_kernel(boost::gil::gray32f_view_t dst, double sigma)\n{\n    if (dst.width() != dst.height() || dst.width() % 2 != 1)\n        throw std::invalid_argument(\"kernel dimensions should be odd and equal\");\n\n    const double denominator = 2 * boost::gil::pi * sigma * sigma;\n    const auto middle = boost::gil::point_t(dst.width() / 2, dst.height() / 2);\n    for (boost::gil::gray32f_view_t::coord_t y = 0; y < dst.height(); ++y)\n    {\n        for (boost::gil::gray32f_view_t::coord_t x = 0; x < dst.width(); ++x)\n        {\n            const auto delta_x = std::abs(middle.x - x);\n            const auto delta_y = std::abs(middle.y - y);\n            const double power = (delta_x * delta_x +  delta_y * delta_y) / (2 * sigma * sigma);\n            const double nominator = std::exp(-power);\n            const float value = nominator / denominator;\n            dst(x, y).at(std::integral_constant<int, 0>{}) = value;\n        }\n    }\n}\n\n}} // namespace boost::gil\n\n#endif\n", "meta": {"hexsha": "d0ae0ac02092c6cd367044a0b9afaa8078b2b16f", "size": 7189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/numeric.hpp", "max_stars_repo_name": "Sricharan16/gil", "max_stars_repo_head_hexsha": "fbec8a3aa4b87245f840829cebfe722270e91f6e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-15T09:09:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T09:09:08.000Z", "max_issues_repo_path": "include/boost/gil/image_processing/numeric.hpp", "max_issues_repo_name": "Sricharan16/gil", "max_issues_repo_head_hexsha": "fbec8a3aa4b87245f840829cebfe722270e91f6e", "max_issues_repo_licenses": ["BSL-1.0"], "max_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": "Sricharan16/gil", "max_forks_repo_head_hexsha": "fbec8a3aa4b87245f840829cebfe722270e91f6e", "max_forks_repo_licenses": ["BSL-1.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.3971291866, "max_line_length": 96, "alphanum_fraction": 0.5903463625, "num_tokens": 1899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465098415278, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6288631144241912}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This is an example illustrating the use of the structural SVM solver from the dlib C++\n    Library.  Therefore, this example teaches you the central ideas needed to setup a\n    structural SVM model for your machine learning problems.  To illustrate the process, we\n    use dlib's structural SVM solver to learn the parameters of a simple multi-class\n    classifier.  We first discuss the multi-class classifier model and then walk through\n    using the structural SVM tools to find the parameters of this classification model.   \n\n*/\n\n\n#include <iostream>\n#include <dlib/svm_threaded.h>\n\nusing namespace std;\nusing namespace dlib;\n\n\n// Before we start, we define three typedefs we will use throughout this program.  The\n// first is used to represent the parameter vector the structural SVM is learning, the\n// second is used to represent the \"sample type\".  In this example program it is just a\n// vector but in general when using a structural SVM your sample type can be anything you\n// want (e.g. a string or an image).  The last typedef is the type used to represent the\n// PSI vector which is part of the structural SVM model which we will explain in detail\n// later on.  But the important thing to note here is that you can use either a dense\n// representation (i.e. a dlib::matrix object) or a sparse representation for the PSI\n// vector.  See svm_sparse_ex.cpp for an introduction to sparse vectors in dlib.  Here we\n// use the same type for each of these three things to keep the example program simple.\ntypedef matrix<double,0,1> column_vector;       // Must be a dlib::matrix type.\ntypedef matrix<double,0,1> sample_type;         // Can be anything you want.\ntypedef matrix<double,0,1> feature_vector_type; // Must be dlib::matrix or some kind of sparse vector.\n\n// ----------------------------------------------------------------------------------------\n\nint           predict_label                (const column_vector& weights, const sample_type& sample);\ncolumn_vector train_three_class_classifier (const std::vector<sample_type>& samples, const std::vector<int>& labels);\n\n// ----------------------------------------------------------------------------------------\n\n\n\n#if defined(BUILD_MONOLITHIC)\n#define main(cnt, arr)      dlib_svm_struct_ex_main(cnt, arr)\n#endif\n\nint main(int argc, const char** argv)\n{\n    // In this example, we have three types of samples: class 0, 1, or 2.  That is, each of\n    // our sample vectors falls into one of three classes.  To keep this example very\n    // simple, each sample vector is zero everywhere except at one place.  The non-zero\n    // dimension of each vector determines the class of the vector.  So for example, the\n    // first element of samples has a class of 1 because samples[0](1) is the only non-zero\n    // element of samples[0].   \n    sample_type samp(3);\n    std::vector<sample_type> samples;\n    samp = 0,2,0; samples.push_back(samp);\n    samp = 1,0,0; samples.push_back(samp);\n    samp = 0,4,0; samples.push_back(samp);\n    samp = 0,0,3; samples.push_back(samp);\n    // Since we want to use a machine learning method to learn a 3-class classifier we need\n    // to record the labels of our samples.  Here samples[i] has a class label of labels[i].\n    std::vector<int> labels;\n    labels.push_back(1);\n    labels.push_back(0);\n    labels.push_back(1);\n    labels.push_back(2);\n\n\n    // Now that we have some training data we can tell the structural SVM to learn the\n    // parameters of our 3-class classifier model.  The details of this will be explained\n    // later.  For now, just note that it finds the weights (i.e. a vector of real valued\n    // parameters) such that predict_label(weights, sample) always returns the correct\n    // label for a sample vector. \n    column_vector weights = train_three_class_classifier(samples, labels);\n\n    // Print the weights and then evaluate predict_label() on each of our training samples.\n    // Note that the correct label is predicted for each sample.\n    cout << weights << endl;\n    for (unsigned long i = 0; i < samples.size(); ++i)\n        cout << \"predicted label for sample[\"<<i<<\"]: \" << predict_label(weights, samples[i]) << endl;\n}\n\n// ----------------------------------------------------------------------------------------\n\nint predict_label (\n    const column_vector& weights,\n    const sample_type& sample\n)\n/*!\n    requires\n        - weights.size() == 9\n        - sample.size() == 3\n    ensures\n        - Given the 9-dimensional weight vector which defines a 3 class classifier, this\n          function predicts the class of the given 3-dimensional sample vector.\n          Therefore, the output of this function is either 0, 1, or 2 (i.e. one of the\n          three possible labels).\n!*/\n{\n    // Our 3-class classifier model can be thought of as containing 3 separate linear\n    // classifiers.  So to predict the class of a sample vector we evaluate each of these\n    // three classifiers and then whatever classifier has the largest output \"wins\" and\n    // predicts the label of the sample.  This is the popular one-vs-all multi-class\n    // classifier model.  \n    //\n    // Keeping this in mind, the code below simply pulls the three separate weight vectors\n    // out of weights and then evaluates each against sample.  The individual classifier\n    // scores are stored in scores and the highest scoring index is returned as the label.\n    column_vector w0, w1, w2;\n    w0 = rowm(weights, range(0,2));\n    w1 = rowm(weights, range(3,5));\n    w2 = rowm(weights, range(6,8));\n\n    column_vector scores(3);\n    scores = dot(w0, sample), dot(w1, sample), dot(w2, sample);\n\n    return index_of_max(scores);\n}\n\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n// ----------------------------------------------------------------------------------------\n\nclass three_class_classifier_problem : public structural_svm_problem_threaded<column_vector, feature_vector_type>\n{\n    /*!\n        Now we arrive at the meat of this example program.  To use dlib's structural SVM\n        solver you need to define an object which tells the structural SVM solver what to\n        do for your problem.  In this example, this is done by defining the three_class_classifier_problem \n        object which inherits from structural_svm_problem_threaded.  Before we get into the\n        details, we first discuss some background information on structural SVMs.  \n        \n        A structural SVM is a supervised machine learning method for learning to predict\n        complex outputs.  This is contrasted with a binary classifier which makes only simple\n        yes/no predictions.  A structural SVM, on the other hand, can learn to predict\n        complex outputs such as entire parse trees or DNA sequence alignments.  To do this,\n        it learns a function F(x,y) which measures how well a particular data sample x\n        matches a label y, where a label is potentially a complex thing like a parse tree.\n        However, to keep this example program simple we use only a 3 category label output. \n       \n        At test time, the best label for a new x is given by the y which maximizes F(x,y).\n        To put this into the context of the current example, F(x,y) computes the score for\n        a given sample and class label.  The predicted class label is therefore whatever\n        value of y which makes F(x,y) the biggest.  This is exactly what predict_label()\n        does.  That is, it computes F(x,0), F(x,1), and F(x,2) and then reports which label\n        has the biggest value.\n       \n        At a high level, a structural SVM can be thought of as searching the parameter space\n        of F(x,y) for the set of parameters that make the following inequality true as often\n        as possible:\n            F(x_i,y_i) > max{over all incorrect labels of x_i} F(x_i, y_incorrect)\n        That is, it seeks to find the parameter vector such that F(x,y) always gives the\n        highest score to the correct output.  To define the structural SVM optimization\n        problem precisely, we first introduce some notation:\n            - let PSI(x,y)    == the joint feature vector for input x and a label y.\n            - let F(x,y|w)    == dot(w,PSI(x,y)).  \n              (we use the | notation to emphasize that F() has the parameter vector of\n              weights called w)\n            - let LOSS(idx,y) == the loss incurred for predicting that the idx-th training \n              sample has a label of y.  Note that LOSS() should always be >= 0 and should\n              become exactly 0 when y is the correct label for the idx-th sample.  Moreover,\n              it should notionally indicate how bad it is to predict y for the idx'th sample.\n            - let x_i == the i-th training sample.\n            - let y_i == the correct label for the i-th training sample.\n            - The number of data samples is N.\n       \n        Then the optimization problem solved by dlib's structural SVM solver is the following:\n            Minimize: h(w) == 0.5*dot(w,w) + C*R(w)\n       \n            Where R(w) == sum from i=1 to N: 1/N * sample_risk(i,w)\n            and sample_risk(i,w) == max over all Y: LOSS(i,Y) + F(x_i,Y|w) - F(x_i,y_i|w)\n            and C > 0\n       \n        You can think of the sample_risk(i,w) as measuring the degree of error you would make\n        when predicting the label of the i-th sample using parameters w.  That is, it is zero\n        only when the correct label would be predicted and grows larger the more \"wrong\" the\n        predicted output becomes.  Therefore, the objective function is minimizing a balance\n        between making the weights small (typically this reduces overfitting) and fitting the\n        training data.  The degree to which you try to fit the data is controlled by the C\n        parameter.\n       \n        For a more detailed introduction to structured support vector machines you should\n        consult the following paper: \n            Predicting Structured Objects with Support Vector Machines by \n            Thorsten Joachims, Thomas Hofmann, Yisong Yue, and Chun-nam Yu\n       \n    !*/\n\npublic:\n\n    // Finally, we come back to the code.  To use dlib's structural SVM solver you need to\n    // provide the things discussed above.  This is the number of training samples, the\n    // dimensionality of PSI(), as well as methods for calculating the loss values and\n    // PSI() vectors.  You will also need to write code that can compute: max over all Y:\n    // LOSS(i,Y) + F(x_i,Y|w).  In particular, the three_class_classifier_problem class is\n    // required to implement the following four virtual functions:\n    //   - get_num_dimensions()\n    //   - get_num_samples() \n    //   - get_truth_joint_feature_vector()\n    //   - separation_oracle()\n\n\n    // But first, we declare a constructor so we can populate our three_class_classifier_problem\n    // object with the data we need to define our machine learning problem.  All we do here\n    // is take in the training samples and their labels as well as a number indicating how\n    // many threads the structural SVM solver will use.  You can declare this constructor\n    // any way you like since it is not used by any of the dlib tools.\n    three_class_classifier_problem (\n        const std::vector<sample_type>& samples_,\n        const std::vector<int>& labels_,\n        const unsigned long num_threads\n    ) : \n        structural_svm_problem_threaded<column_vector, feature_vector_type>(num_threads),\n        samples(samples_),\n        labels(labels_)\n    {}\n\n    feature_vector_type make_psi (\n        const sample_type& x,\n        const int label\n    ) const\n    /*!\n        ensures\n            - returns the vector PSI(x,label)\n    !*/\n    {\n        // All we are doing here is taking x, which is a 3 dimensional sample vector in this\n        // example program, and putting it into one of 3 places in a 9 dimensional PSI\n        // vector, which we then return.  So this function returns PSI(x,label).  To see why\n        // we setup PSI like this, recall how predict_label() works.  It takes in a 9\n        // dimensional weight vector and breaks the vector into 3 pieces.  Each piece then\n        // defines a different classifier and we use them in a one-vs-all manner to predict\n        // the label.  So now that we are in the structural SVM code we have to define the\n        // PSI vector to correspond to this usage.  That is, we need to setup PSI so that\n        // argmax_y dot(weights,PSI(x,y)) == predict_label(weights,x).  This is how we tell\n        // the structural SVM solver what kind of problem we are trying to solve.\n        //\n        // It's worth emphasizing that the single biggest step in using a structural SVM is\n        // deciding how you want to represent PSI(x,label).  It is always a vector, but\n        // deciding what to put into it to solve your problem is often not a trivial task.\n        // Part of the difficulty is that you need an efficient method for finding the label\n        // that makes dot(w,PSI(x,label)) the biggest.  Sometimes this is easy, but often\n        // finding the max scoring label turns into a difficult combinatorial optimization\n        // problem.  So you need to pick a PSI that doesn't make the label maximization step\n        // intractable but also still well models your problem.  \n        //\n        // Finally, note that make_psi() is a helper routine we define in this example.  In\n        // general, you are not required to implement it.  That is, all you must implement\n        // are the four virtual functions defined below.\n\n\n        // So let's make an empty 9-dimensional PSI vector\n        feature_vector_type psi(get_num_dimensions());\n        psi = 0; // zero initialize it\n\n        // Now put a copy of x into the right place in PSI according to its label.  So for\n        // example, if label is 1 then psi would be:  [0 0 0 x(0) x(1) x(2) 0 0 0]\n        if (label == 0)\n            set_rowm(psi,range(0,2)) = x;\n        else if (label == 1)\n            set_rowm(psi,range(3,5)) = x;\n        else // the label must be 2 \n            set_rowm(psi,range(6,8)) = x;\n\n        return psi;\n    }\n\n    // We need to declare the dimensionality of the PSI vector (this is also the\n    // dimensionality of the weight vector we are learning).  Similarly, we need to declare\n    // the number of training samples.  We do this by defining the following virtual\n    // functions.\n    virtual long get_num_dimensions () const { return samples[0].size() * 3; }\n    virtual long get_num_samples ()    const { return samples.size(); }\n\n    // In get_truth_joint_feature_vector(), all you have to do is output the PSI() vector\n    // for the idx-th training sample when it has its true label.  So here it outputs\n    // PSI(samples[idx], labels[idx]).\n    virtual void get_truth_joint_feature_vector (\n        long idx,\n        feature_vector_type& psi \n    ) const \n    {\n        psi = make_psi(samples[idx], labels[idx]);\n    }\n\n    // separation_oracle() is more interesting.  dlib's structural SVM solver will call\n    // separation_oracle() many times during the optimization.  Each time it will give it\n    // the current value of the parameter weights and separation_oracle() is supposed to\n    // find the label that most violates the structural SVM objective function for the\n    // idx-th sample.  Then the separation oracle reports the corresponding PSI vector and\n    // loss value.  To state this more precisely, the separation_oracle() member function\n    // has the following contract:\n    //   requires\n    //       - 0 <= idx < get_num_samples()\n    //       - current_solution.size() == get_num_dimensions()\n    //   ensures\n    //       - runs the separation oracle on the idx-th sample.  We define this as follows: \n    //           - let X           == the idx-th training sample.\n    //           - let PSI(X,y)    == the joint feature vector for input X and an arbitrary label y.\n    //           - let F(X,y)      == dot(current_solution,PSI(X,y)).  \n    //           - let LOSS(idx,y) == the loss incurred for predicting that the idx-th sample\n    //             has a label of y.  Note that LOSS() should always be >= 0 and should\n    //             become exactly 0 when y is the correct label for the idx-th sample.\n    //\n    //               Then the separation oracle finds a Y such that: \n    //                   Y = argmax over all y: LOSS(idx,y) + F(X,y) \n    //                   (i.e. It finds the label which maximizes the above expression.)\n    //\n    //               Finally, we can define the outputs of this function as:\n    //               - #loss == LOSS(idx,Y) \n    //               - #psi == PSI(X,Y) \n    virtual void separation_oracle (\n        const long idx,\n        const column_vector& current_solution,\n        scalar_type& loss,\n        feature_vector_type& psi\n    ) const \n    {\n        // Note that the solver will use multiple threads to make concurrent calls to\n        // separation_oracle(), therefore, you must implement it in a thread safe manner\n        // (or disable threading by inheriting from structural_svm_problem instead of\n        // structural_svm_problem_threaded).  However, if your separation oracle is not\n        // very fast to execute you can get a very significant speed boost by using the\n        // threaded solver.  In general, all you need to do to make your separation oracle\n        // thread safe is to make sure it does not modify any global variables or members\n        // of three_class_classifier_problem.  So it is usually easy to make thread safe.\n\n        column_vector scores(3);\n\n        // compute scores for each of the three classifiers\n        scores = dot(rowm(current_solution, range(0,2)),  samples[idx]),\n                 dot(rowm(current_solution, range(3,5)),  samples[idx]),\n                 dot(rowm(current_solution, range(6,8)),  samples[idx]);\n\n        // Add in the loss-augmentation.  Recall that we maximize LOSS(idx,y) + F(X,y) in\n        // the separate oracle, not just F(X,y) as we normally would in predict_label().\n        // Therefore, we must add in this extra amount to account for the loss-augmentation.\n        // For our simple multi-class classifier, we incur a loss of 1 if we don't predict\n        // the correct label and a loss of 0 if we get the right label.\n        if (labels[idx] != 0)\n            scores(0) += 1;\n        if (labels[idx] != 1)\n            scores(1) += 1;\n        if (labels[idx] != 2)\n            scores(2) += 1;\n\n        // Now figure out which classifier has the largest loss-augmented score.\n        const int max_scoring_label = index_of_max(scores);\n        // And finally record the loss that was associated with that predicted label.\n        // Again, the loss is 1 if the label is incorrect and 0 otherwise.\n        if (max_scoring_label == labels[idx])\n            loss = 0;\n        else\n            loss = 1;\n\n        // Finally, compute the PSI vector corresponding to the label we just found and\n        // store it into psi for output.\n        psi = make_psi(samples[idx], max_scoring_label);\n    }\n\nprivate:\n\n    // Here we hold onto the training data by reference.  You can hold it by value or by\n    // any other method you like.\n    const std::vector<sample_type>& samples;\n    const std::vector<int>& labels;\n};\n    \n// ----------------------------------------------------------------------------------------\n\n// This function puts it all together.  In here we use the three_class_classifier_problem\n// along with dlib's oca cutting plane solver to find the optimal weights given our\n// training data.\ncolumn_vector train_three_class_classifier (\n    const std::vector<sample_type>& samples,\n    const std::vector<int>& labels\n)\n{\n    const unsigned long num_threads = 4;\n    three_class_classifier_problem problem(samples, labels, num_threads);\n\n    // Before we run the solver we set up some general parameters.  First,\n    // you can set the C parameter of the structural SVM by calling set_c().\n    problem.set_c(1);\n\n    // The epsilon parameter controls the stopping tolerance.  The optimizer will run until\n    // R(w) is within epsilon of its optimal value. If you don't set this then it defaults\n    // to 0.001.\n    problem.set_epsilon(0.0001);\n\n    // Uncomment this and the optimizer will print its progress to standard out.  You will\n    // be able to see things like the current risk gap.  The optimizer continues until the\n    // risk gap is below epsilon.\n    //problem.be_verbose();\n\n    // The optimizer uses an internal cache to avoid unnecessary calls to your\n    // separation_oracle() routine.  This parameter controls the size of that cache.\n    // Bigger values use more RAM and might make the optimizer run faster.  You can also\n    // disable it by setting it to 0 which is good to do when your separation_oracle is\n    // very fast.  If you don't call this function it defaults to a value of 5.\n    //problem.set_max_cache_size(20);\n\n    \n    column_vector weights;\n    // Finally, we create the solver and then run it.\n    oca solver;\n    solver(problem, weights);\n\n    // Alternatively, if you wanted to require that the learned weights are all\n    // non-negative then you can call the solver as follows and it will put a constraint on\n    // the optimization problem which causes all elements of weights to be >= 0.  \n    //solver(problem, weights, problem.get_num_dimensions());\n\n    return weights;\n}\n\n// ----------------------------------------------------------------------------------------\n\n", "meta": {"hexsha": "6f4b5056f4f6e3f2592b4b4bb2efd54c1e2d2ebf", "size": 21756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/svm_struct_ex.cpp", "max_stars_repo_name": "GerHobbelt/dlib", "max_stars_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/svm_struct_ex.cpp", "max_issues_repo_name": "GerHobbelt/dlib", "max_issues_repo_head_hexsha": "d26e917abc626fb81f0b57ecf1f3be555bddf8de", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/svm_struct_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": 51.67695962, "max_line_length": 117, "alphanum_fraction": 0.6485107557, "num_tokens": 4900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8267118068790619, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6288388754785788}}
{"text": "#include <sparse.h>\n#include <sparse_fill.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(SPARSE);\n\nBOOST_AUTO_TEST_CASE(product_crm_crm_test)\n{    \n  // scalar case\n  sparse::CompressedRowMatrix<sparse::Block<1,1,float> > sA(1,1,1);\n  sparse::CompressedRowMatrix<sparse::Block<1,1,float> > sB(1,1,1);\n  sparse::CompressedRowMatrix<sparse::Block<1,1,float> > sC(1,1,1);\n  \n  sA(0,0)[0] = 5;\n  sB(0,0)[0] = 2;\n  sparse::prod(sA,sB,sC);\n  BOOST_CHECK(sC(0,0)[0] == 5*2);\n  \n  sA.clear();\n  sB.clear();\n  sC.clear();\n  \n  sA.resize(4,3,5);\n  sB.resize(3,4,3);\n  sparse::fill(sA(0,0),1);\n  sparse::fill(sA(0,2),2);\n  sparse::fill(sA(2,1),3);\n  sparse::fill(sA(3,0),4);\n  sparse::fill(sA(3,1),5);\n  sparse::fill(sB(0,0),6);\n  sparse::fill(sB(1,1),7);\n  sparse::fill(sB(2,3),8);\n  sparse::prod(sA, sB, sC);\n  BOOST_CHECK( sC(0,0)[0] == 6  );\n  BOOST_CHECK( sC(0,3)[0] == 16 );\n  BOOST_CHECK( sC(2,1)[0] == 21 );\n  BOOST_CHECK( sC(3,0)[0] == 24 );\n  BOOST_CHECK( sC(3,1)[0] == 35 );\n  \n  // Observe we do not need to test block case - it has been verified by product_block_test()\n  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "639e9bb2dad0672732acaa9b2e54e37ba8140ff7", "size": 1288, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_product_crm_crm/sparse_product_crm_crm.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_product_crm_crm/sparse_product_crm_crm.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/SPARSE/unit_tests/sparse_product_crm_crm/sparse_product_crm_crm.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.76, "max_line_length": 93, "alphanum_fraction": 0.6436335404, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6287903039173425}}
{"text": "\n#include <iostream>\n#include <string>\n#include <utility>\n#include <stdexcept>\n#include <cmath>\n#include <cstdlib>\n#include <boost/program_options.hpp>\n#include \"logical_expr.hpp\"\n#include \"quine_mccluskey.hpp\"\n\nusing namespace std;\n\ntemplate<typename Property>\nvoid print_term_expr(const logical_expr::logical_term<Property> &term, \n            char first_char = 'A', char inverter = '~')\n{\n    for( int i = 0; i < term.size(); ++i ) {\n        if( term[i] == false )  cout << inverter;\n        if( term[i] != logical_expr::dont_care )\n            cout << static_cast<char>(first_char + i);\n    }\n}\n\ntemplate<typename TermType>\nvoid print_func_expr(\n        const logical_expr::logical_function<TermType> &func,\n        char first_char = 'A', const string &funcname = \"f\", char inverter = '~')\n{\n    cout << funcname << \" = \";\n    for( auto it = func.begin(); it != func.end(); ++it ) {\n        print_term_expr(*it, first_char, inverter);\n        if( it + 1 != func.end() )\n            cout << \" + \";\n    }\n    cout << endl;\n}\n\ntemplate<typename TermType>\nvoid print_truth_table(\n        const logical_expr::logical_function<TermType> &f, \n        char first_char = 'A', const string &funcname =\"f\" \n    )\n{\n    cout << \"Truth Table: \";\n    print_func_expr(f, first_char, funcname);\n    for( char c = first_char; c != first_char + f.term_size(); ++c )\n        cout << c;\n    cout << \" | \" << funcname << \"()\" << endl;\n    for( int i = 0; i < f.term_size() + 6; ++i )\n        cout << ((i == f.term_size() + 1) ? '|' : '-');\n    cout << endl;\n    logical_expr::arg_generator<> generator(0, std::pow(2, f.term_size()), f.term_size());\n    for( auto arg : generator )\n        cout << arg << \" |  \" << f(arg) << endl;\n}\n\nint main(int argc, char **argv)\n{\n    int exit_code = EXIT_SUCCESS;\n    try {\n        bool print_process = true;\n        char first_char = 'A';\n        constexpr char inverter = '~';\n\n        //\n        // Parse command line options\n        //\n        using namespace boost::program_options;\n        options_description opt(\"Options\");\n        opt.add_options()\n            (\"quiet,q\", \"never print the information of the process of simplifying\")\n            (\"first-char,c\", value<char>(), \"specify a character of the first variable used for input expression\")\n            (\"help,h\", \"display this help and exit\");\n        variables_map argmap;\n        store(parse_command_line(argc, argv, opt), argmap);\n        notify(argmap);\n        if( argmap.count(\"help\") ) {\n            std::cout << opt << endl;\n            return EXIT_SUCCESS;\n        }\n        if( argmap.count(\"quiet\") )\n            print_process = false;\n        if( argmap.count(\"first-char\") )\n            first_char = argmap[\"first-char\"].as<char>();\n\n        // Input a target logical function to be simplfied from stdin\n        if( print_process )\n            cout << \"Logical Function Simplifier (Quine-McCluskey)\"   << endl\n                 << \"[*] Enter a logical function to be simplified\"   << endl\n                 << \"    (ex. \\\"f(A, B, C) = A + BC + ~A~B + ABC\\\" )\" << endl\n                 << \"[*] Input: \" << flush;\n        string line;\n        getline(cin, line);\n\n        // Parse input logical expression and return tokenized\n        logical_expr::function_parser<inverter, true> parser(line, first_char);\n        auto token = parser.parse();\n        // Create a logical function with logical_term<term_mark>\n        typedef quine_mccluskey::simplifier::property_type PropertyType;\n        typedef quine_mccluskey::simplifier::term_type TermType;\n        logical_expr::logical_function<TermType> function;\n        for( string term : token.second )\n            function += logical_expr::parse_logical_term<PropertyType, inverter>(term, token.first.size(), first_char);\n\n        // Create a simplifier using Quine-McCluskey algorithm\n        quine_mccluskey::simplifier qm(function);\n        if( print_process ) {\n            cout << endl << \"Sum of products form:\" << endl;\n            print_truth_table(qm.get_std_spf(), first_char);    // Print the function in sum of products form\n            cout << endl << \"Compressing ...\" << endl;\n            qm.compress_table(true);                            // Compress the compression table\n            cout << endl << \"Prime implicants: \" << endl;\n            for( const auto &term : qm.get_prime_implicants() ) {      // Print the prime implicants\n                print_term_expr(term, first_char);\n                cout << \"  \";\n            }\n            cout << endl << endl << \"Result of simplifying:\" << endl;\n        }\n        else\n            qm.compress_table(false);\n\n        for( const auto &func : qm.simplify() )        // Simplify and print its results\n            print_func_expr(func, first_char, parser.function_name() + \"\\'\");\n    }\n    catch( std::exception &e ) {\n        cerr << endl << \"[-] Exception: \" << e.what() << endl;\n        exit_code = EXIT_FAILURE;\n    }\n    return exit_code;\n}\n\n", "meta": {"hexsha": "666e04a55459bf06bcd0d4807e3b128ab5f09706", "size": 4954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "luyiming/Quine-McCluskey", "max_stars_repo_head_hexsha": "9ecff90368c34e98d1aa16aca9a238066f85ef99", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "luyiming/Quine-McCluskey", "max_issues_repo_head_hexsha": "9ecff90368c34e98d1aa16aca9a238066f85ef99", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "luyiming/Quine-McCluskey", "max_forks_repo_head_hexsha": "9ecff90368c34e98d1aa16aca9a238066f85ef99", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2481203008, "max_line_length": 119, "alphanum_fraction": 0.5716592652, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6287902961592371}}
{"text": "/*\nA class to represent the extension field GF(2^M) \n*/\n\n#ifndef EXTENSION_FIELD2\n#define EXTENSION_FIELD2\n\n#include <boost/operators.hpp>\n#include <iostream>\n#include <ostream>\n#include <vector>\n#include <utility>\n#include \"./helpers.hpp\"\n\nusing namespace std;\n\n\n\n// divide a by b; computer a/b and remainder(a/b)\n// return pair with fist: quotient, second: remainder\ntemplate<class uint>\npair<uint,uint> divide(const uint a, const uint b){\n\n\tuint quot = 0; // quotient\n\tuint rem = a; // remainder \n\t\n\tif(b > a){ // then a is not divisible by b, and quot = 0\n\t\treturn pair<uint,uint>(quot,rem);\n\t}\n\t\n\twhile((rem >= b) && (rem != 0)){\n\t\tunsigned exp = degree(rem) - degree(b);\n\t\tquot |= (1 << exp);\n\t\tuint btmp = (b << exp);\n\t\trem ^= btmp;\n\t}\n\treturn pair<uint,uint>(quot,rem);\n};\n\n/* \nGF(2^m)\nParameters are:\n- m: the degree of the extension\n- prim_poly: primitive polynomial defining the extension field\n*/\ntemplate<class uint_, uint_ m_, uint_ prim_poly_>\nclass GF2M:\n\tboost::field_operators< GF2M<uint_,m_,prim_poly_>,\n\tboost::equality_comparable< GF2M<uint_,m_,prim_poly_>\n\t> >\n{\npublic: \n\t//! an element of the extension field is a polynomial, represented by an unsigned integer\n\ttypedef uint_ uint;\n\tstatic const unsigned m = m_;\n\tstatic const uint prim_poly = prim_poly_;\n\tuint el; \n\tbool empty;\n\t//! constructors\n\tGF2M(uint x){el = x % 2;empty = false;};\n\t//GF2M(unsigned x){el = x ;empty = false;};\n\tGF2M(uint x,unsigned v){el = x ;empty = false;}; // generates instance with el = x\n\t\n\tGF2M(){ el = 0; empty = true;}; // -1 marks empty \n\n\n\tGF2M& operator += (const GF2M& x){\n\t\tel = el ^ x.el;\n\t\treturn *this;\n\t}\n\t\n\tGF2M& operator -= (const GF2M& x){\n\t\tel = el ^ x.el;\n\t\treturn *this;\n\t}\n\n\tGF2M& operator *= (const GF2M& x){\n\t\tuint a = el;\n\t\tuint b = x.el;\n\t\tel = 0; // product of this and x\n\t\twhile (a && b) {\n\t\t\t\tif (b & 1) // if b is odd, add the corresponding a to p \n\t\t\t\t\tel ^= a;\n\n\t\t\t\tif (a &  ( ((uint)1) << ( (unsigned) m - 1 )) ) // GF modulo: if a >= 2^m, it overflows when shifted left, so reduce \n\t\t\t\t\ta = (a << 1) ^ prim_poly; // XOR with the primitive polynomial\n\t\t\t\telse\n\t\t\t\t\ta <<= 1; // a*2 /* equivalent to a*2 \n\t\t\t\tb >>= 1; // b / 2\t\n\t\t}\n\t\treturn *this;\n\t}\n\t\t\n\tGF2M& operator /= (const GF2M& x){\n\t\t*this = (x.inverse() * (*this)); \n\t\treturn *this;\n\t}\n\t\n\t//! compute the multiplicative inverse via the extended Euclidean algorithm \n\tGF2M inverse() const {\n\t\t\n\t\tuint rem1 = prim_poly;\n\t\tuint rem2 = el;\n\t\tuint aux1 = 0;\n\t\tuint aux2 = 1;\n\n\t\twhile( rem2 != 0 ){\n\t\t\t// res.first = quotient(rem1/rem2)\n\t\t\t// res.second = remainder(rem1/rem2)\n\t\t\t\n\t\t\tpair< uint, uint > res = divide(rem1,rem2);\n\t\t\t\n\t\t\tGF2M aux_new = GF2M(res.first,0)*GF2M(aux2,0) + GF2M(aux1,0);\n\n\t\t\t// prepare for the next step\n\t\t\trem1 = rem2;\n\t\t\trem2 = res.second;\n\t\t\taux1 = aux2;\n\t\t\taux2 = aux_new.el;\n\t\t\t\n\t\t}\n\t\t//aux1.multiply_monomial(pow(rem1.poly[0],-1), 0);\n\t\treturn GF2M(aux1,0);\n\t}\n\n\n\tunsigned order() const {\n\t\t// multiplicative neutral element = 1\n\t\t//PFE one = PFE(1);\n\t\tGF2M one = GF2M(1); \n\t\tGF2M tmp = *this;  //EFE(el);\t\t\n\t\tunsigned ord = 1;\n\t\twhile(!(tmp == one)){\n\t\t\tord++;\n\t\t\ttmp *= *this;\n\t\t}\n\t\treturn ord;\n\t}\n\n\tbool iszero() const {\n\t\treturn (el == 0);\n\t}\n\t\n\tbool isempty() const {\n\t\treturn empty;\n\t}\n\n\tbool operator ==(const GF2M& x) const {\n\t\treturn (el == x.el);\n\t}\n\t\n\tbool operator < (const GF2M& x) const {\n\t\treturn (el < x.el);\t\n\t}\n\n\n};\t\n\ntemplate<class uint, uint m, uint prim_poly> \nostream &operator<<(ostream& stream, const GF2M<uint,m,prim_poly>& x)\n    {\n\t  \tstream << bitset<32>(x.el);\n      \treturn stream; // must return stream\n\t};\n\n\n\ntemplate<class uint, uint m, uint prim_poly> \nGF2M<uint,m,prim_poly> pow(const GF2M<uint,m,prim_poly>& a, int exp){\n\t\n\tif(a.iszero()) return a;\n\tif(exp == 0) {return GF2M<uint,m,prim_poly>(1);}\n\t\n\tGF2M<uint,m,prim_poly> tmp;\n\t\n\tif(exp < 0){\n\t\tGF2M<uint,m,prim_poly> am = a.inverse(); \n\t\ttmp = am;\n\t\tfor(unsigned i =1; i < abs(exp); ++i) tmp *= am;\n\t} else { // exp > 0\n\t\ttmp = a;\n\t\tfor(unsigned i =1; i < abs(exp); ++i) tmp *= a;\n\t}\n\n\treturn tmp;\n};\n\n\n\n#endif\n", "meta": {"hexsha": "e06c059971b80ce0facbc68b1d7051383edb6241", "size": 4019, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/GF2M.hpp", "max_stars_repo_name": "libingzheren/dna_rs_coding", "max_stars_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-12-01T11:55:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T01:57:11.000Z", "max_issues_repo_path": "include/GF2M.hpp", "max_issues_repo_name": "libingzheren/dna_rs_coding", "max_issues_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-26T09:13:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-26T15:19:01.000Z", "max_forks_repo_path": "include/GF2M.hpp", "max_forks_repo_name": "libingzheren/dna_rs_coding", "max_forks_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-05T06:14:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T09:10:36.000Z", "avg_line_length": 21.0418848168, "max_line_length": 121, "alphanum_fraction": 0.6073650162, "num_tokens": 1332, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6287146169553943}}
{"text": "#include \"pcaauto.h\"\n\n#include <Eigen/Eigenvalues>\n\nvoid PcaAuto::setupInertia( Eigen::Matrix3f const& inertia )\n{\n    inertia_ = inertia;\n\n    auto solver = Eigen::EigenSolver<Eigen::Matrix3f>{inertia_, true};\n\n    eigenVectors_ = solver.eigenvectors();\n    eigenValues_  = solver.eigenvalues();\n}\n", "meta": {"hexsha": "db26c5184ff1627c466b6ff4e8cccc9600c776b4", "size": 299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/pcaauto.cpp", "max_stars_repo_name": "fossabot/datura", "max_stars_repo_head_hexsha": "d8a09c4d5ae13a6984a5a8e89c69ecb8a6023037", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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/pcaauto.cpp", "max_issues_repo_name": "fossabot/datura", "max_issues_repo_head_hexsha": "d8a09c4d5ae13a6984a5a8e89c69ecb8a6023037", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-12T13:12:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-12T13:12:00.000Z", "max_forks_repo_path": "src/core/pcaauto.cpp", "max_forks_repo_name": "fossabot/datura", "max_forks_repo_head_hexsha": "d8a09c4d5ae13a6984a5a8e89c69ecb8a6023037", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T13:10:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-12T13:10:06.000Z", "avg_line_length": 21.3571428571, "max_line_length": 70, "alphanum_fraction": 0.7090301003, "num_tokens": 82, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6287145962696881}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2016-2017 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_FORMULAS_THOMAS_DIRECT_HPP\n#define BOOST_GEOMETRY_FORMULAS_THOMAS_DIRECT_HPP\n\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/core/radius.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/formulas/differential_quantities.hpp>\n#include <boost/geometry/formulas/flattening.hpp>\n#include <boost/geometry/formulas/result_direct.hpp>\n\n\nnamespace boost { namespace geometry { namespace formula\n{\n\n\n/*!\n\\brief The solution of the direct problem of geodesics on latlong coordinates,\n       Forsyth-Andoyer-Lambert type approximation with second order terms.\n\\author See\n    - Technical Report: PAUL D. THOMAS, MATHEMATICAL MODELS FOR NAVIGATION SYSTEMS, 1965\n      http://www.dtic.mil/docs/citations/AD0627893\n    - Technical Report: PAUL D. THOMAS, SPHEROIDAL GEODESICS, REFERENCE SYSTEMS, AND LOCAL GEOMETRY, 1970\n      http://www.dtic.mil/docs/citations/AD0703541\n\n*/\ntemplate <\n    typename CT,\n    bool EnableCoordinates = true,\n    bool EnableReverseAzimuth = false,\n    bool EnableReducedLength = false,\n    bool EnableGeodesicScale = false\n>\nclass thomas_direct\n{\n    static const bool CalcQuantities = EnableReducedLength || EnableGeodesicScale;\n    static const bool CalcCoordinates = EnableCoordinates || CalcQuantities;\n    static const bool CalcRevAzimuth = EnableReverseAzimuth || CalcCoordinates || CalcQuantities;\n\npublic:\n    typedef result_direct<CT> result_type;\n\n    template <typename T, typename Dist, typename Azi, typename Spheroid>\n    static inline result_type apply(T const& lo1,\n                                    T const& la1,\n                                    Dist const& distance,\n                                    Azi const& azimuth12,\n                                    Spheroid const& spheroid)\n    {\n        result_type result;\n\n        CT const lon1 = lo1;\n        CT const lat1 = la1;\n\n        if ( math::equals(distance, Dist(0)) || distance < Dist(0) )\n        {\n            result.lon2 = lon1;\n            result.lat2 = lat1;\n            return result;\n        }\n\n        CT const c0 = 0;\n        CT const c1 = 1;\n        CT const c2 = 2;\n        CT const c4 = 4;\n\n        CT const a = CT(get_radius<0>(spheroid));\n        CT const b = CT(get_radius<2>(spheroid));\n        CT const f = formula::flattening<CT>(spheroid);\n        CT const one_minus_f = c1 - f;\n\n        CT const pi = math::pi<CT>();\n        CT const pi_half = pi / c2;\n\n        // keep azimuth small - experiments show low accuracy\n        // if the azimuth is closer to (+-)180 deg.\n        CT azi12_alt = azimuth12;\n        CT lat1_alt = lat1;\n        bool alter_result = vflip_if_south(lat1, azimuth12, lat1_alt, azi12_alt);\n        \n        CT const theta1 = math::equals(lat1_alt, pi_half) ? lat1_alt :\n                          math::equals(lat1_alt, -pi_half) ? lat1_alt :\n                          atan(one_minus_f * tan(lat1_alt));\n        CT const sin_theta1 = sin(theta1);\n        CT const cos_theta1 = cos(theta1);\n\n        CT const sin_a12 = sin(azi12_alt);\n        CT const cos_a12 = cos(azi12_alt);\n\n        CT const M = cos_theta1 * sin_a12; // cos_theta0\n        CT const theta0 = acos(M);\n        CT const sin_theta0 = sin(theta0);\n\n        CT const N = cos_theta1 * cos_a12;\n        CT const C1 = f * M; // lower-case c1 in the technical report\n        CT const C2 = f * (c1 - math::sqr(M)) / c4; // lower-case c2 in the technical report\n        CT const D = (c1 - C2) * (c1 - C2 - C1 * M);\n        CT const P = C2 * (c1 + C1 * M / c2) / D;\n\n        // special case for equator:\n        // sin_theta0 = 0 <=> lat1 = 0 ^ |azimuth12| = pi/2\n        // NOTE: in this case it doesn't matter what's the value of cos_sigma1 because\n        //       theta1=0, theta0=0, M=1|-1, C2=0 so X=0 and Y=0 so d_sigma=d\n        //       cos_a12=0 so N=0, therefore\n        //       lat2=0, azi21=pi/2|-pi/2\n        //       d_eta = atan2(sin_d_sigma, cos_d_sigma)\n        //       H = C1 * d_sigma\n        CT const cos_sigma1 = math::equals(sin_theta0, c0)\n                                ? c1\n                                : normalized1_1(sin_theta1 / sin_theta0);\n        CT const sigma1 = acos(cos_sigma1);\n        CT const d = distance / (a * D);\n        CT const u = 2 * (sigma1 - d);\n        CT const cos_d = cos(d);\n        CT const sin_d = sin(d);\n        CT const cos_u = cos(u);\n        CT const sin_u = sin(u);\n\n        CT const W = c1 - c2 * P * cos_u;\n        CT const V = cos_u * cos_d - sin_u * sin_d;\n        CT const X = math::sqr(C2) * sin_d * cos_d * (2 * math::sqr(V) - c1);\n        CT const Y = c2 * P * V * W * sin_d;\n        CT const d_sigma = d + X - Y;\n        CT const sin_d_sigma = sin(d_sigma);\n        CT const cos_d_sigma = cos(d_sigma);\n\n        if (BOOST_GEOMETRY_CONDITION(CalcRevAzimuth))\n        {\n            result.reverse_azimuth = atan2(M, N * cos_d_sigma - sin_theta1 * sin_d_sigma);\n\n            if (alter_result)\n            {\n                vflip_rev_azi(result.reverse_azimuth, azimuth12);\n            }\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(CalcCoordinates))\n        {\n            CT const S_sigma = c2 * sigma1 - d_sigma;\n            CT const cos_S_sigma = cos(S_sigma);\n            CT const d_eta = atan2(sin_d_sigma * sin_a12, cos_theta1 * cos_d_sigma - sin_theta1 * sin_d_sigma * cos_a12);\n            CT const H = C1 * (c1 - C2) * d_sigma - C1 * C2 * sin_d_sigma * cos_S_sigma;\n            CT const d_lambda = d_eta - H;\n            \n            result.lon2 = lon1 + d_lambda;\n\n            if (! math::equals(M, c0))\n            {\n                CT const sin_a21 = sin(result.reverse_azimuth);\n                CT const tan_theta2 = (sin_theta1 * cos_d_sigma + N * sin_d_sigma) * sin_a21 / M;\n                result.lat2 = atan(tan_theta2 / one_minus_f);\n            }\n            else\n            {\n                CT const sigma2 = S_sigma - sigma1;\n                //theta2 = asin(cos(sigma2)) <=> sin_theta0 = 1\n                // NOTE: cos(sigma2) defines the sign of tan_theta2\n                CT const tan_theta2 = cos(sigma2) / math::abs(sin(sigma2));\n                result.lat2 = atan(tan_theta2 / one_minus_f);\n            }\n\n            if (alter_result)\n            {\n                result.lat2 = -result.lat2;\n            }\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(CalcQuantities))\n        {\n            typedef differential_quantities<CT, EnableReducedLength, EnableGeodesicScale, 2> quantities;\n            quantities::apply(lon1, lat1, result.lon2, result.lat2,\n                              azimuth12, result.reverse_azimuth,\n                              b, f,\n                              result.reduced_length, result.geodesic_scale);\n        }\n\n        return result;\n    }\n\nprivate:\n    static inline bool vflip_if_south(CT const& lat1, CT const& azi12, CT & lat1_alt, CT & azi12_alt)\n    {\n        CT const c2 = 2;\n        CT const pi = math::pi<CT>();\n        CT const pi_half = pi / c2;\n\n        if (azi12 > pi_half)\n        {\n            azi12_alt = pi - azi12;\n            lat1_alt = -lat1;\n            return true;\n        }\n        else if (azi12 < -pi_half)\n        {\n            azi12_alt = -pi - azi12;\n            lat1_alt = -lat1;\n            return true;\n        }\n\n        return false;\n    }\n\n    static inline void vflip_rev_azi(CT & rev_azi, CT const& azimuth12)\n    {\n        CT const c0 = 0;\n        CT const pi = math::pi<CT>();\n\n        if (rev_azi == c0)\n        {\n            rev_azi = azimuth12 >= 0 ? pi : -pi;\n        }\n        else if (rev_azi > c0)\n        {\n            rev_azi = pi - rev_azi;\n        }\n        else\n        {\n            rev_azi = -pi - rev_azi;\n        }\n    }\n\n    static inline CT normalized1_1(CT const& value)\n    {\n        CT const c1 = 1;\n        return value > c1 ? c1 :\n               value < -c1 ? -c1 :\n               value;\n    }\n};\n\n}}} // namespace boost::geometry::formula\n\n\n#endif // BOOST_GEOMETRY_FORMULAS_THOMAS_DIRECT_HPP\n", "meta": {"hexsha": "6a7ac3e41455a749067dcd321cdc5f8d2074af9b", "size": 8343, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/formulas/thomas_direct.hpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 354.0, "max_stars_repo_stars_event_min_datetime": "2018-08-13T18:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T10:37:20.000Z", "max_issues_repo_path": "include/boost/geometry/formulas/thomas_direct.hpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T13:40:06.000Z", "max_forks_repo_path": "include/boost/geometry/formulas/thomas_direct.hpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2018-11-15T12:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:39.000Z", "avg_line_length": 33.5060240964, "max_line_length": 121, "alphanum_fraction": 0.5620280475, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6287145887089745}}
{"text": "// main is provided in tests-main.cpp\n#include <catch2/catch.hpp>\n#include <mitama/dimensional/quantity.hpp>\n#include <mitama/dimensional/systems/si/all.hpp>\n#include <mitama/dimensional/systems/nonsi/degree_angle.hpp>\n#include <mitama/dimensional/systems/si/prefix.hpp>\n#include <random>\n#include <test_util.hpp>\n#include <mitama/dimensional/arithmetic.hpp>\n\nusing namespace mitama;\nnamespace si = mitama::systems::si;\nnamespace nsi = mitama::systems::nonsi;\nTEST_CASE(\"degree angle and radian\",\n          \"[quantity][systems/nonsi][degree_angle]\")\n{\n    using namespace Catch::literals;\n    quantity_t<nsi::degree_angle_t> s1 = 90;\n    quantity_t<si::radian_t> c = s1;\n    REQUIRE(c.value() == 1.570796_a);\n    quantity_t<nsi::degree_angle_t> s2 = c;\n    REQUIRE(s2.value() == 90._a);\n}\n\nTEST_CASE(\"degree amgle and radian generate tests\",\n          \"[quantity][systems/nonsi][degree_angle]\")\n{\n    using namespace Catch::literals;\n\n    REQUIRE(\n        test_util::RandomGenerator<double>::uniform( -360, 360 )\n            .take(1000)\n            .required([](auto value){\n                quantity_t<nsi::degree_angle_t> c = value;\n                quantity_t<si::radian_t> s = c;\n                return c.value() / s.value() == 57.295779_a;\n            }));\n    REQUIRE(\n        test_util::RandomGenerator<double>::uniform( -6.283185, 6.283185)\n            .take(1)\n            .required([](auto value){\n                quantity_t<si::radian_t> s = value;\n                quantity_t<nsi::degree_angle_t> c = s;\n                return c.value() / s.value() == 57.295779_a;\n            }));\n}\n\n#include <mitama/dimensional/systems/information/byte.hpp>\n#include <mitama/dimensional/systems/information/prefix.hpp>\n#include <mitama/dimensional/systems/information/shannon.hpp>\n#include <mitama/dimensional/systems/information/nat.hpp>\n#include <mitama/dimensional/systems/information/hartley.hpp>\n#include <mitama/dimensional/systems/information/conversions.hpp>\n#include <boost/format.hpp>\n\nTEST_CASE(\"information format\", \"[info]\") {\n    using namespace mitama::systems::information;\n    auto fmt = [](auto x){ return (boost::format(\"%1%\") % x).str(); };\n    REQUIRE( fmt(1|bits) == \"1 [b]\" );\n    REQUIRE( fmt(1|bytes) == \"1 [B]\" );\n    REQUIRE( fmt(1|shannon) == \"1 [Sh]\" );\n    REQUIRE( fmt(1|nat) == \"1 [nat]\" );\n    REQUIRE( fmt(1|hartley) == \"1 [Hart]\" );\n}\n\nTEST_CASE(\"information prefix format\", \"[info]\")\n{\n    using namespace mitama::systems::information;\n    auto fmt = [](auto x){ return (boost::format(\"%1%\") % x).str(); };\n    REQUIRE( fmt(1| kibi * bytes) == \"1 [KiB]\" );\n    REQUIRE( fmt(1| mebi * bytes) == \"1 [MiB]\" );\n    REQUIRE( fmt(1| gibi * bytes) == \"1 [GiB]\" );\n    REQUIRE( fmt(1| tebi * bytes) == \"1 [TiB]\" );\n    REQUIRE( fmt(1| pebi * bytes) == \"1 [PiB]\" );\n}\n", "meta": {"hexsha": "c1e5941d42fbaf9d8ff7d2dba79a1b91c5f99507", "size": 2790, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/nonsi-unit-tests/nonsi-unit-tests.cpp", "max_stars_repo_name": "LoliGothick/mitama-dimensional", "max_stars_repo_head_hexsha": "46b9ae3764bd472da9ed5372afd82e6b5d542543", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2019-01-18T11:51:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T02:46:43.000Z", "max_issues_repo_path": "tests/nonsi-unit-tests/nonsi-unit-tests.cpp", "max_issues_repo_name": "LoliGothick/mitama-dimensional", "max_issues_repo_head_hexsha": "46b9ae3764bd472da9ed5372afd82e6b5d542543", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-02-10T23:12:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-06T21:05:09.000Z", "max_forks_repo_path": "tests/nonsi-unit-tests/nonsi-unit-tests.cpp", "max_forks_repo_name": "LoliGothick/mitama-dimensional", "max_forks_repo_head_hexsha": "46b9ae3764bd472da9ed5372afd82e6b5d542543", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-02-27T11:53:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-20T21:59:59.000Z", "avg_line_length": 36.7105263158, "max_line_length": 73, "alphanum_fraction": 0.6275985663, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6286773623082162}}
{"text": "#define BOOST_TEST_MODULE \"Test Sorensen class\"\n\n#include <boost/test/unit_test.hpp>\n\n#include \"distance/Sorensen.hpp\"\n\nusing namespace genex;\n\n#define TOLERANCE 1e-9\n\nstruct MockData\n{\n  data_t dat_1[5] = {3, 1, 2, 5, 4};\n  data_t dat_2[5] = {3.4, 4, 1.2, 2, 3};\n};\n\nBOOST_AUTO_TEST_CASE( sorensen_test, *boost::unit_test::tolerance(TOLERANCE)  )\n{\n  MockData data;\n  TimeSeries ts_1(data.dat_1, 5);\n  TimeSeries ts_2(data.dat_2, 5);\n  Sorensen dist;\n\n  data_t* total = dist.init();\n\n  for (int i = 0; i < ts_1.getLength(); i++) {\n    total = dist.reduce(total, total, ts_1[i], ts_2[i]);\n  }\n\n  BOOST_TEST( dist.norm(total, ts_1, ts_2), 0.3216 );\n\n  delete total;\n}", "meta": {"hexsha": "b7f244a6f08241a5605cd9f893b2972a03ac7fce", "size": 666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distance/SorensenTest.cpp", "max_stars_repo_name": "mihinsumaria/genex", "max_stars_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-28T07:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T07:49:24.000Z", "max_issues_repo_path": "test/distance/SorensenTest.cpp", "max_issues_repo_name": "mihinsumaria/genex", "max_issues_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/distance/SorensenTest.cpp", "max_forks_repo_name": "mihinsumaria/genex", "max_forks_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T20:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T20:25:42.000Z", "avg_line_length": 20.1818181818, "max_line_length": 79, "alphanum_fraction": 0.6636636637, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6286773459504826}}
{"text": "\n#include <tiny_math_types.h>\n#include <tiny_eigen3x3.h>\n#include <tiny_polar_decomposition3x3.h>\n#include <tiny_matrix_functions.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\n#include <cmath>\n\nBOOST_AUTO_TEST_SUITE(tiny_polar_decomposition);\n\n  BOOST_AUTO_TEST_CASE(eigen_method)\n  {\n    typedef tiny::MathTypes<double>                   math_types;\n    typedef math_types::matrix3x3_type                matrix3x3_type;\n    typedef math_types::real_type                     real_type;\n    typedef math_types::value_traits                  value_traits;\n\n    real_type epsilon = 10e-7;\n    matrix3x3_type A,R,S,D;\n\n    for(size_t i=0;i<10;++i)\n    {\n      S = matrix3x3_type::random();      \n      S = tiny::trans(S)*S;\n      A = matrix3x3_type::random();\n      R = tiny::ortonormalize( A );\n      A = R*S;\n      R = matrix3x3_type::make_diag(1.0);\n      S = matrix3x3_type::make_diag(1.0);\n      bool success = tiny::polar_decomposition_eigen(A,R,S);\n      if(success)\n      {\n        bool right_handed = tiny::det(R) > value_traits::zero();\n        BOOST_CHECK( right_handed );\n        \n        D = A - R*S;\n        real_type maximum_deviation =  tiny::max(  abs(D) );\n\n        //BOOST_CHECK_CLOSE( maximum_deviation, value_traits::zero(), tol);\n        BOOST_CHECK( maximum_deviation<epsilon );\n      }\n    }\n  }\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "c4a7b5dfd6f0e9a8e22acce11ddaad682ccd7e91", "size": 1506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_polar_decomposition/tiny_polar_decomposition.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_polar_decomposition/tiny_polar_decomposition.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/TINY/unit_tests/tiny_polar_decomposition/tiny_polar_decomposition.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9615384615, "max_line_length": 75, "alphanum_fraction": 0.6440903054, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6286551288063895}}
{"text": "#ifndef _FM_HPP\n#define _FM_HPP\n#include <map>\n#include <cmath>\n#include <boost/math/special_functions/bessel.hpp>\n\nusing namespace std;\nusing namespace boost::math;\n\nstatic const int SAMPLE_RATE {44100};\n\nclass Param\n{\nprivate:\n    const float ratio {0.99};\n    float target_value;\n    float intermediate_value;\npublic:\n    Param(float v) : target_value{v}, intermediate_value{v}\n    {\n    }\n\n    void set(float v)\n    {\n        target_value = v;\n    }\n\n    float get()\n    {\n        if ( intermediate_value != target_value )\n            intermediate_value = ratio*intermediate_value + (1.0-ratio)*target_value;\n        return intermediate_value;\n    }\n\n    float abs()\n    {\n        return target_value;\n    }\n};\n\nclass FMSynth\n{\nprivate:\n  float carrier_phase {0.0};\n  float modulating_phase {0.0};\npublic:\n  float carrier_frequency {200.0};\n  float modulating_frequency {100.0};\n  Param modulation_index {0.0};\n\n  struct Band\n  {\n    float amplitude {0.0};\n    enum {NEGATIVE, CENTER, POSITIVE, MIXED} type;\n  };\n\n  float process()\n  {\n    const float value {sin(carrier_phase + modulation_index.get()*sin(modulating_phase))};\n\n    carrier_phase += carrier_frequency * 2.0 * M_PI / SAMPLE_RATE;\n    if ( carrier_phase > 2*M_PI )\n        carrier_phase -= 2*M_PI;\n    modulating_phase += modulating_frequency * 2.0 * M_PI / SAMPLE_RATE;\n    if ( modulating_phase > 2*M_PI )\n        modulating_phase -= 2*M_PI;\n\n    return value;\n  }\n\n  float peak_deviation()\n  {\n      return modulation_index.abs() * modulating_frequency;\n  }\n\n  map<float, Band> spectra()\n  {\n    const float bandwidth {2.0f * (peak_deviation() + modulating_frequency)};\n    const int n {static_cast<int>(ceil(bandwidth / modulating_frequency / 2.0)) + 1};\n    map<float, Band> bands;\n\n    // initial band\n    bands[carrier_frequency].amplitude += cyl_bessel_j(0, modulation_index.abs());\n    bands[carrier_frequency].type = Band::CENTER;\n\n    // side bands\n    for (int i = 1; i <= n; i ++)\n    {\n      const double amplitude_pos {cyl_bessel_j(i, modulation_index.abs())};\n      double amplitude_neg {amplitude_pos * pow(-1.0, i)};\n      const float frequency_pos {carrier_frequency + modulating_frequency*i};\n      float frequency_neg {carrier_frequency - modulating_frequency*i};\n\n      // reflect\n      if (frequency_neg < 0)\n      {\n        frequency_neg *= -1;\n        amplitude_neg *= -1;\n      }\n\n      if ( bands.count(frequency_pos) )\n          bands[frequency_pos].type = Band::MIXED;\n      else\n          bands[frequency_pos].type = Band::POSITIVE;\n      bands[frequency_pos].amplitude += amplitude_pos;\n\n      if ( bands.count(frequency_neg) )\n          bands[frequency_neg].type = Band::MIXED;\n      else\n          bands[frequency_neg].type = Band::NEGATIVE;\n      bands[frequency_neg].amplitude += amplitude_neg;\n    }\n\n    return bands;\n  }\n};\n\n#endif\n", "meta": {"hexsha": "842ecfaf2a410c84799c6e90f9ae27eea5685317", "size": 2838, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fm.hpp", "max_stars_repo_name": "analoq/fmLab", "max_stars_repo_head_hexsha": "af87ff03a2a382e9c736c864cee2438b1f8d308f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fm.hpp", "max_issues_repo_name": "analoq/fmLab", "max_issues_repo_head_hexsha": "af87ff03a2a382e9c736c864cee2438b1f8d308f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fm.hpp", "max_forks_repo_name": "analoq/fmLab", "max_forks_repo_head_hexsha": "af87ff03a2a382e9c736c864cee2438b1f8d308f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8487394958, "max_line_length": 90, "alphanum_fraction": 0.6455250176, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938414, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6286551119782551}}
{"text": "\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <unordered_map>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nconst float fx = 2892.843;\nconst float fy = 2882.249;\nconst int w = 1600;\nconst int h = 1200;\nconst float cx = 824.4251;\nconst float cy = 605.18715;\n\nvoid dtu_to_cameras_txt(const std:: string & out_folder) {\n\n  std::cout<<\"Creating DTU intrinsics file: \"<<out_folder<<\"/cameras.txt \"<<std::flush;\n  std::ofstream cameras_txt (out_folder+\"/cameras.txt\");\n  //intrinsics calibration fixed\n\n  cameras_txt << \"0 PINHOLE \" << w << \" \" << h << \" \" << fx << \" \" << fy << \" \" << cx << \" \" << cy<<std::endl;\n  cameras_txt.close();\n  std::cout<<\"   --->DONE\"<<std::endl;\n} \n\nvoid dtu_to_images_txt(const std::string & pathImages,const std:: string & pathCalib, const std:: string & out_folder) {\n\n\n  std::cout<<\"Creating DTU images file: \"<<out_folder<<\"/images.txt \"<<std::endl;\n  std::cout<<\"pathImages : \"<<pathImages<<\" \"<<std::endl;\n  std::cout<<\"pathCalib : \"<<pathCalib<<\" \"<<std::endl;\n\n  std::ofstream images_txt (out_folder+\"/images.txt\");\n\n  //Path Prefixes/postfixes\n  const std::string image_prefix = \"rect_\";\n  const std::string image_postfix = \"_3_r5000.png\";\n  const std::string pose_prefix = \"pos_\";\n  const std::string pose_postfix = \".txt\";\n  const int n_zeros = 3;\n\n  Eigen::Matrix3f K = Eigen::Matrix3f::Zero();\n  K(0,0) = fx;\n  K(1,1) = fy;\n  K(0,2) = cx;\n  K(1,2) = cy;\n  K(2,2) = 1.0;\n\n  Eigen::Matrix3f K_inv = K.inverse(); //TODO check\n\n  for (int i = 1; i <= 64; ++i){\n    std::string number = std::string(n_zeros - std::to_string(i).length(), '0') + std::to_string(i);\n\n    std::ifstream camFile(pathCalib  + \"/\" + pose_prefix  + number + pose_postfix);\n    std::ifstream imgFile(pathImages + \"/\" + image_prefix + number + image_postfix);\n    \n    Eigen::Matrix<float,3,4> cameraMatrix;\n    if(camFile.is_open() && imgFile.is_open()){\n    //Reading the transpose rotation  since the file stores the inverse of the Hartley Zisserman convention\n      camFile >> cameraMatrix(0,0) >> cameraMatrix(0,1) >> cameraMatrix(0,2) >> cameraMatrix(0,3);\n      camFile >> cameraMatrix(1,0) >> cameraMatrix(1,1) >> cameraMatrix(1,2) >> cameraMatrix(1,3);\n      camFile >> cameraMatrix(2,0) >> cameraMatrix(2,1) >> cameraMatrix(2,2) >> cameraMatrix(2,3);\n\n      Eigen::Matrix<float,3,4> extrinsics;\n      extrinsics = K_inv * cameraMatrix;\n      \n      Eigen::Matrix3f rotation;\n      Eigen::Vector3f traslation;\n      for (int curR = 0; curR < 3; ++curR) {\n        for (int curC = 0; curC < 3; ++curC) {\n          rotation(curR,curC) = extrinsics(curR,curC);\n        }\n      }\n      for (int curR = 0; curR < 3; ++curR) {\n        traslation(curR) = extrinsics(curR,3);\n      }\n\n      Eigen::Quaternionf q(rotation);\n\n\n      images_txt << i << \" \" << q.w() << \" \" << q.x() << \" \" << q.y() << \" \" << q.z ()\n          << \" \" << traslation(0) << \" \" << traslation(1) << \" \" << traslation(2)\n          << \" 0 \" << image_prefix + number + image_postfix << std::endl;\n      images_txt << std::endl;\n    }\n  }\n\n  images_txt.close();\n  std::cout<<\"   --->DONE\"<<std::endl;\n}\n\n\nvoid dtu_to_points_txt(const std:: string & out_folder){\n\n  std::cout<<\"Creating DTU 3D Points file: \"<<out_folder<<\"/points3D.txt \"<<std::flush;\n\n  std::ofstream points_txt (out_folder+\"/points3D.txt\");\n  points_txt.close();\n  std::cout<<\"   --->DONE\"<<std::endl;\n}\n\n\nint main(int argc, char const *argv[])\n{\n  \n  if(argc==4){\n    dtu_to_cameras_txt(std::string(argv[3]));\n    dtu_to_images_txt(std::string(argv[1]), std::string(argv[2]), std::string(argv[3]));\n    dtu_to_points_txt(std::string(argv[3]));\n\n  }else{\n    std::cout<< \"Wrong Arguments\" << std::endl;\n    std::cout<< \"Usage:\" << std::endl;\n    std::cout<< \"dtu_to_colmap pathImages pathcalib outputfolder\" << std::endl;\n  }\n\n\n  return 0;\n}\n", "meta": {"hexsha": "d6fb89722d5f615c965fe3a394be7649bdbfb527", "size": 3811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dtu_to_colmap.cpp", "max_stars_repo_name": "andresax/cam_file_converter_", "max_stars_repo_head_hexsha": "f6a0289167c1e8f9cdbd0f1911696d7ebcaa9dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-19T05:08:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-19T05:08:08.000Z", "max_issues_repo_path": "dtu_to_colmap.cpp", "max_issues_repo_name": "andresax/cam_file_converter_", "max_issues_repo_head_hexsha": "f6a0289167c1e8f9cdbd0f1911696d7ebcaa9dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dtu_to_colmap.cpp", "max_forks_repo_name": "andresax/cam_file_converter_", "max_forks_repo_head_hexsha": "f6a0289167c1e8f9cdbd0f1911696d7ebcaa9dcd", "max_forks_repo_licenses": ["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.4958677686, "max_line_length": 120, "alphanum_fraction": 0.6082393073, "num_tokens": 1183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6285279152787924}}
{"text": "//\n//  cal_T_abc.hpp\n//  hybrid_fem_bie\n//\n//  Created by Max on 2/7/18.\n//\n//\n\n#ifndef cal_T_abc_hpp\n#define cal_T_abc_hpp\n\n#include <stdio.h>\n#include <Eigen/Eigen>\n\nusing namespace Eigen;\n\nvoid cal_T_abc(MatrixXd coord ,double density, MatrixXd &T_abc, double v_p, double v_s);\n\n#endif /* cal_T_abc_hpp */\n", "meta": {"hexsha": "d7a941ad72823bfa6b3ee17bf22e7363b70a9d01", "size": 309, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/fem/cal_T_abc.hpp", "max_stars_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_stars_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "src/fem/cal_T_abc.hpp", "max_issues_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_issues_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fem/cal_T_abc.hpp", "max_forks_repo_name": "XiaoMaResearch/hybrid_tsunamic_plane_stress", "max_forks_repo_head_hexsha": "574988edfcd4839f680b85cde2bf818936e86b78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 15.45, "max_line_length": 88, "alphanum_fraction": 0.7087378641, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6285279050655551}}
{"text": "// Copyright University of Warwick 2014\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Authors:\n// John Back\n\n/*! \\file LpcFunctions.hh\n    \\brief File containing the declaration of the LpcFunctions class\n*/\n\n/*! \\class LpcFunctions\n    \\brief Class containing various functions used by other classes\n*/\n\n#ifndef LPC_FUNCTIONS_HH\n#define LPC_FUNCTIONS_HH\n\n#include <Eigen/Dense>\n\nclass LpcFunctions {\n\npublic:\n\n    //! Default constructor\n    LpcFunctions();\n\n    //! Destructor\n    virtual ~LpcFunctions();\n    \n    //! Weighted mean (centroid) of the hits using Eigen matrices\n    /*!\n      \\param [in] Xi The matrix of hit positions (row = hit, col = x,y,z)\n      \\param [in] weights The vector of the energy or charge weights of the hits\n      \\returns The weighted mean (centroid) of the hits as an Eigen vector.\n    */\n    Eigen::VectorXd getWeightedMean(const Eigen::MatrixXd& Xi, \n\t\t\t\t    const Eigen::VectorXd& weights) const;\n\n    //! Non-weighted centroid of the hits using Eigen matrices\n    /*!\n      \\param [in] Xi The matrix of hit positions (row = hit, col = x,y,z)\n      \\returns The non-weighted centroid of the hits as an Eigen vector.\n    */\n    Eigen::VectorXd getMean(const Eigen::MatrixXd& Xi) const;\n\n\n    //! Subtract the Eigen matrix of hit positions with a constant vector offset\n    /*!\n      \\param [in] Xi The matrix of hit positions (row = hit, col = x,y,z)\n      \\param [in] offset The constant vector position offset\n      \\returns The updated offset hit positions (row = hit, col = x,y,z)\n    */\n    Eigen::MatrixXd offsetPositions(const Eigen::MatrixXd& Xi,\n\t\t\t\t    const Eigen::VectorXd& offset) const;\n\n    //! The kernel function for each hit point\n    /*!\n      \\param [in] hitPoint the data hit point\n      \\param [in] localPoint the local neighbourhood point u\n      \\param [in] factor the kernel denominator factor\n      \\returns the kernel function value\n    */\n    double kernelFunction(const Eigen::VectorXd& hitPoint,\n\t\t\t  const Eigen::VectorXd& localPoint, \n\t\t\t  double factor) const;\n\n    //! The kernel part used by the kernel function\n    /*!\n      \\param [in] x The 1D hit co-ordinate variable\n      \\param [in] u The 1D co-ordinate of the local neighbourhood point\n      \\param [in] factor the kernel denominator factor\n    */\n    double kernelPart(double x, double u, double factor) const;\n\n    //! A function used by the LpcBranchAlgorithm\n    /*!\n      \\param [in] data the matrix of zero mean data (row = hit, col = x,y,z)\n      \\param [in] u the local neighbourhood point\n      \\param [in] factor the kernel denominator factor\n    */\n    double kdex(const Eigen::MatrixXd& data, \n\t\tconst Eigen::VectorXd& u, double factor) const;\n\n    //! Covariance matrix from zero mean matrix data and vector of weights\n    /*!\n      \\param [in] meanData the matrix of zero mean data (row = hit, col = x,y,z)\n      \\param [in] weights the vector of hit weights\n      \\returns the symmetric convariance matrix of the data\n    */\n    Eigen::MatrixXd formCovarianceMatrix(const Eigen::MatrixXd& meanData,\n\t\t\t\t\t const Eigen::VectorXd& weights) const;\n\n    //! Unweighted ovariance matrix from zero mean matrix data\n    /*!\n      \\param [in] meanData the matrix of zero mean data (row = hit, col = x,y,z)\n      \\returns the symmetric convariance matrix of the unweighted data\n    */\n    Eigen::MatrixXd formCovarianceMatrix(const Eigen::MatrixXd& meanData) const;\n\n    //! Covariance matrix from a matrix of data points and vector of weights\n    /*!\n      \\param [in] data the matrix of the data (row = hit, col = x,y,z)\n      \\param [in] weights the vector of hit weights\n      \\returns the symmetric convariance matrix of the data\n    */\n    Eigen::MatrixXd getCovarianceMatrix(const Eigen::MatrixXd& data,\n\t\t\t\t\tconst Eigen::VectorXd& weights) const;\n\n    //! Covariance matrix from a matrix of data points\n    /*!\n      \\param [in] data the matrix of the data (row = hit, col = x,y,z)\n      \\returns the symmetric convariance matrix of the data\n    */\n    Eigen::MatrixXd getCovarianceMatrix(const Eigen::MatrixXd& data) const;\n\n\n    //! Find the eigenvalues and normalised eigenvectors of the covariance matrix\n    /*!\n      \\param [in] covMatrix The covariance matrix\n      \\returns a pair of the descending eigenvalues with the normalised eigenvectors (rows)\n    */\n    std::pair<Eigen::VectorXd, Eigen::MatrixXd>\n    findNormEigenVectors(const Eigen::MatrixXd& covMatrix) const;\n\n    //! Calculate the mean and rms of the set of data recursively\n    /*!\n      \\param [in] data The Eigen VectorXd of data points\n      \\returns the (mean, rms) pair for the set of data\n    */\n    std::pair<double, double> getMeanAndRms(const Eigen::VectorXd& data) const;\n\n    //! Calculate the perpendicular distance of a point from a line\n    /*!\n      \\param [in] point The point that we want to find the distance for\n      \\param [in] centroid A point on the line, defined as the centroid\n      \\param [in] direction The unit direction vector of the line\n    */\n    double getPerpLineDist(const Eigen::VectorXd& point,\n\t\t\t   const Eigen::VectorXd& centroid,\n\t\t\t   const Eigen::VectorXd& direction) const;\n\n    //! Calculate the perpendicular distance of a point from a line\n    //! for points that lie towards the end-point of the line V\n    /*!\n      \\param [in] point The point that we want to find the distance for\n      \\param [in] centroid A point on the line, defined as the centroid\n      \\param [in] direction The unit direction vector of the line\n      \\param [in] dL The distance along the line between the centroid and end-point\n    */\n    double getPerpLineDist(const Eigen::VectorXd& point,\n\t\t\t   const Eigen::VectorXd& centroid,\n\t\t\t   const Eigen::VectorXd& direction,\n\t\t\t   double dL) const;\n\n\nprotected:\n    \nprivate:\n\n};\n\n#endif\n", "meta": {"hexsha": "63dd25d5e1f0781679ca2881429236bfc459007c", "size": 5887, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/LACE/LpcFunctions.hh", "max_stars_repo_name": "petrmanek/LACE", "max_stars_repo_head_hexsha": "5e189bb871a47972490fe2888a60df876cb6b120", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T13:13:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-14T13:13:34.000Z", "max_issues_repo_path": "include/LACE/LpcFunctions.hh", "max_issues_repo_name": "petrmanek/LACE", "max_issues_repo_head_hexsha": "5e189bb871a47972490fe2888a60df876cb6b120", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/LACE/LpcFunctions.hh", "max_forks_repo_name": "petrmanek/LACE", "max_forks_repo_head_hexsha": "5e189bb871a47972490fe2888a60df876cb6b120", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-19T21:29:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-14T13:37:26.000Z", "avg_line_length": 35.8963414634, "max_line_length": 91, "alphanum_fraction": 0.6784440292, "num_tokens": 1411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6285278999701025}}
{"text": "/*\nSimulate outbreak of infectious disease.\n\nInfected individuals infect others from an infinite pool. The model keeps track of\nwho infected whom and when. Infected individuals are initially in a latent phase i.e.\nthey show no symptoms nor can infect others. The illness then progresses according to\nstochastic processes.\n\nFollows the model description in:\n\nTom Britton and Gianpaolo Scalia Tomba (2018)\nEstimation in emerging epidemics: biases and remedies, arXiv:1803.01688v1.\n*/\n\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n#include <random>\n#include <vector>\n#include <cstdlib>\n#include <cmath>\n#include <chrono>\n#include <Eigen/Core>\n\n#include \"infectee.hpp\"\n\nclass Outbreak\n{\n  public:\n    std::vector<Infectee *> infected; // infected individuals (present and past)\n    Eigen::MatrixXi counters;         // counts of each infection state per output interval\n    std::mt19937_64 prng;             // pseudo random-number generator\n    params_struct params;             // user-given parameters (defaults in infectee.hpp)\n\n    Outbreak(std::mt19937_64 &prng, const params_struct &params = params_struct()) : prng(prng), params(params)\n\n    {\n        uint n_output = lrint(1. * params.max_time / params.output_interval);\n        this->counters = Eigen::MatrixXi::Zero(n_output, N_STATES);\n\n        std::vector<Infectee *> new_infected, new_infected1;\n        this->infected.push_back(new Infectee(NULL, 0, prng, params));\n        uint output_counter = 0;\n\n        double time = params.timestep;\n        while (time <= params.max_time)\n        {\n            bool is_output_step = std::fmod(time + 1e-9, params.output_interval) < params.timestep;\n            \n            // iterate over all infected individuals\n            for (std::vector<Infectee *>::iterator it = this->infected.begin(); it != this->infected.end(); ++it)\n            {\n                new_infected1 = (*it)->update(time, prng, params);\n\n                if (!new_infected1.empty()) // append new infectees by single infector\n                {\n                    new_infected.reserve(new_infected.size() + new_infected1.size());\n                    new_infected.insert(new_infected.end(), new_infected1.begin(), new_infected1.end());\n                }\n\n                if (is_output_step)\n                    this->counters(output_counter, (*it)->istatus())++;\n            }\n\n            if (!new_infected.empty()) // append all new infectees from time step\n            {\n                this->infected.reserve(this->infected.size() + new_infected.size());\n                this->infected.insert(this->infected.end(), new_infected.begin(), new_infected.end());\n                // std::cout << \"t=\" << time << \": New infected \" << new_infected.size() << \", total \" << infected.size() << std::endl;\n                new_infected.clear();\n            }\n\n            if (is_output_step)\n            {\n                if (params.verbose)\n                    std::cout << \"t=\" << time << \": \" << this->counters.row(output_counter) << std::endl;\n                output_counter++;\n            }\n\n            if (this->infected.size() > params.max_infected)\n            {\n                if (params.verbose)\n                    std::cout << \"Max number of infected individuals reached. Stopping.\" << std::endl;\n                break;\n            }\n            time += params.timestep;\n        }\n    }\n\n    ~Outbreak()\n    {\n        for (std::vector<Infectee *>::iterator it = this->infected.begin(); it != this->infected.end(); ++it)\n            delete *it;  // need to release these manually as allocated dynamically\n    }\n\n    Eigen::MatrixXi getCounters()\n    {\n        return this->counters;\n    }\n\n    std::vector<Infectee*> getInfected()\n    {\n        return this->infected;\n    }\n\n    float getR0()\n    {\n        // Estimate the basic reproduction number (R0) by considering\n        // reported cases due to infectors now past the infectious period.\n        int n_infected = 0;\n        int n_infectors = 0;\n\n        for (std::vector<Infectee *>::iterator it = this->infected.begin(); it != this->infected.end(); ++it)\n        {\n            if ((*it)->istatus() > 3)\n            {\n                n_infectors++;\n                for (std::vector<Infectee *>::iterator it2 = (*it)->infected.begin(); it2 != (*it)->infected.end(); ++it2)\n                {\n                    if ((*it2)->is_reported())\n                        n_infected++;\n                }\n            }\n        }\n        // std::cout << \"N_infected: \" << n_infected << \" n_infectors: \" << n_infectors << std::endl;\n\n        return (float) n_infected / n_infectors;\n    }\n\n    // Print various statistics for debugging.\n    void printStats()\n    {\n        const uint N_GROUPS = 4;\n        Eigen::ArrayXd end_time_sums = Eigen::ArrayXd::Zero(N_GROUPS);\n        Eigen::ArrayXi status_sums = Eigen::ArrayXi::Zero(N_GROUPS);\n        double offset;\n\n        for (std::vector<Infectee *>::iterator it = this->infected.begin(); it != this->infected.end(); ++it)\n        {\n            // handle latent period\n            if ((*it)->status_trajectory[1] == 1)\n                offset = (*it)->end_times[0];\n            else\n                offset = (*it)->end_times[2];\n            end_time_sums[0] += offset - (*it)->infection_time;\n            status_sums[0]++;\n\n            // infectious period\n            end_time_sums[1] += (*it)->end_times[3] - offset;\n            offset = (*it)->end_times[3];\n            status_sums[1]++;\n\n            // recovering period\n            if ((*it)->status_trajectory[3] == 4)\n            {\n                end_time_sums[2] += (*it)->end_times[4] - offset;\n                status_sums[2]++;\n            }\n            else // dying period\n            {\n                end_time_sums[3] += (*it)->end_times[5] - offset;\n                status_sums[3]++;\n            }\n        }\n\n        std::cout.precision(5);\n        std::cout << std::setw(20) << \"Means:\" << std::setw(20) << \"Latent period\" \n                  << std::setw(20) << \"Infectious period\" << std::setw(20) << \"Recovering period\" \n                  << std::setw(20) << \"Dying period\" << std::endl;\n        std::cout << std::setw(20) << (end_time_sums / status_sums.cast<double>()).transpose() << std::endl;\n        std::cout << std::setw(20) << \"Expected:\" << std::setw(20) << params.latent_period_scale * params.latent_period_shape \n                  << std::setw(20) << params.infect_period_scale * params.infect_period_shape\n                  << std::setw(20) << params.recover_period_scale * params.recover_period_shape\n                  << std::setw(20) << params.dying_period_scale * params.dying_period_shape << std::endl;\n        std::cout << \"Pr(recovery): \" << (1. * status_sums[2]) / (status_sums[2] + status_sums[3]) \n                  << \" Expected \" << params.p_recovery << std::endl;\n    }\n};\n\nint main(int argc, char *argv[])\n{\n    params_struct params;\n    params.verbose = true;\n    uint seed;\n    double R0;\n\n    if (argc > 1)\n    {\n        R0 = std::atof(argv[1]);\n    }\n    else\n    {\n        R0 = 1.7;\n    }\n    if (argc > 2)\n    {\n        seed = std::atoi(argv[2]);\n    }\n    else\n    {\n        seed = static_cast<uint>(std::chrono::system_clock::now().time_since_epoch().count());\n        std::cout << \"Using seed = \" << seed << std::endl;\n    }\n    std::mt19937_64 prng(seed);\n    params.infect_delta = params.infect_period_shape * params.infect_period_scale / R0;\n\n    Outbreak ob(prng, params);\n\n    std::cout << \"Estimated R0: \" << ob.getR0() << std::endl;\n\n    // Eigen::MatrixXi c = ob.getCounters();\n    // std::cout << c << std::endl;\n\n    std::vector<Infectee*> inf = ob.getInfected();\n    if (inf.size() > 3)\n    {\n        std::cout << *(inf[0]) << std::endl;\n        std::cout << *(inf[1]) << std::endl;\n        std::cout << *(inf[2]) << std::endl;\n        std::cout << *(inf[(int) (inf.size()/4)]) << std::endl;\n    }\n\n    ob.printStats();\n    return 0;\n}\n", "meta": {"hexsha": "8e7b9765074f27cb3afd40b457cd98b9e13ccec0", "size": 7929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "outbreak.cpp", "max_stars_repo_name": "vuolleko/outbreak", "max_stars_repo_head_hexsha": "182f687a05bf6086194684dd9d2b4bfaafba2c1f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "outbreak.cpp", "max_issues_repo_name": "vuolleko/outbreak", "max_issues_repo_head_hexsha": "182f687a05bf6086194684dd9d2b4bfaafba2c1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "outbreak.cpp", "max_forks_repo_name": "vuolleko/outbreak", "max_forks_repo_head_hexsha": "182f687a05bf6086194684dd9d2b4bfaafba2c1f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0840707965, "max_line_length": 135, "alphanum_fraction": 0.5458443688, "num_tokens": 1982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6285278999477703}}
{"text": "/* Boost test/mul.cpp\r\n * test multiplication, division, square and square root on some intervals\r\n *\r\n * Copyright Guillaume Melquiond 2002-2003\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation.\r\n *\r\n * None of the above authors nor Polytechnic University make any\r\n * representation about the suitability of this software for any\r\n * purpose. It is provided \"as is\" without express or implied warranty.\r\n *\r\n * $Id: mul.cpp,v 1.3 2003/02/05 17:34:36 gmelquio Exp $\r\n */\r\n\r\n#include <boost/numeric/interval.hpp>\r\n#include <boost/numeric/interval/io.hpp>\r\n#include <boost/test/minimal.hpp>\r\n\r\ntypedef boost::numeric::interval<double> I;\r\n\r\nstatic double min(double a, double b, double c, double d) {\r\n  return std::min(std::min(a, b), std::min(c, d));\r\n}\r\n\r\nstatic double max(double a, double b, double c, double d) {\r\n  return std::max(std::max(a, b), std::max(c, d));\r\n}\r\n\r\nstatic bool test_mul(double al, double au, double bl, double bu) {\r\n  I a(al, au), b(bl, bu);\r\n  I c = a * b;\r\n  return c.lower() == min(al*bl, al*bu, au*bl, au*bu)\r\n      && c.upper() == max(al*bl, al*bu, au*bl, au*bu);\r\n}\r\n\r\nstatic bool test_mul1(double ac, double bl, double bu) {\r\n  I a(ac), b(bl, bu);\r\n  I c = ac * b;\r\n  I d = b * ac;\r\n  I e = a * b;\r\n  return equal(c, d) && equal(d, e);\r\n}\r\n\r\nstatic bool test_div(double al, double au, double bl, double bu) {\r\n  I a(al, au), b(bl, bu);\r\n  I c = a / b;\r\n  return c.lower() == min(al/bl, al/bu, au/bl, au/bu)\r\n      && c.upper() == max(al/bl, al/bu, au/bl, au/bu);\r\n}\r\n\r\nstatic bool test_div1(double al, double au, double bc) {\r\n  I a(al, au), b(bc);\r\n  I c = a / bc;\r\n  I d = a / b;\r\n  return equal(c, d);\r\n}\r\n\r\nstatic bool test_div2(double ac, double bl, double bu) {\r\n  I a(ac), b(bl, bu);\r\n  I c = ac / b;\r\n  I d = a / b;\r\n  return equal(c, d);\r\n}\r\n\r\nstatic bool test_square(double al, double au) {\r\n  I a(al, au);\r\n  I b = square(a);\r\n  I c = a * a;\r\n  return b.upper() == c.upper() &&\r\n         (b.lower() == c.lower() || (c.lower() <= 0 && b.lower() == 0));\r\n}\r\n\r\nstatic bool test_sqrt(double al, double au) {\r\n  I a(al, au);\r\n  I b = square(sqrt(a));\r\n  return subset(abs(a), b);\r\n}\r\n\r\nint test_main(int, char*[]) {\r\n  BOOST_CHECK(test_mul(2, 3, 5, 7));\r\n  BOOST_CHECK(test_mul(2, 3, -5, 7));\r\n  BOOST_CHECK(test_mul(2, 3, -7, -5));\r\n  BOOST_CHECK(test_mul(-2, 3, 5, 7));\r\n  BOOST_CHECK(test_mul(-2, 3, -5, 7));\r\n  BOOST_CHECK(test_mul(-2, 3, -7, -5));\r\n  BOOST_CHECK(test_mul(-3, -2, 5, 7));\r\n  BOOST_CHECK(test_mul(-3, -2, -5, 7));\r\n  BOOST_CHECK(test_mul(-3, -2, -7, -5));\r\n\r\n  BOOST_CHECK(test_mul1(3, 5, 7));\r\n  BOOST_CHECK(test_mul1(3, -5, 7));\r\n  BOOST_CHECK(test_mul1(3, -7, -5));\r\n  BOOST_CHECK(test_mul1(-3, 5, 7));\r\n  BOOST_CHECK(test_mul1(-3, -5, 7));\r\n  BOOST_CHECK(test_mul1(-3, -7, -5));\r\n\r\n  BOOST_CHECK(test_div(30, 42, 2, 3));\r\n  BOOST_CHECK(test_div(30, 42, -3, -2));\r\n  BOOST_CHECK(test_div(-30, 42, 2, 3));\r\n  BOOST_CHECK(test_div(-30, 42, -3, -2));\r\n  BOOST_CHECK(test_div(-42, -30, 2, 3));\r\n  BOOST_CHECK(test_div(-42, -30, -3, -2));\r\n\r\n  BOOST_CHECK(test_div1(30, 42, 3));\r\n  BOOST_CHECK(test_div1(30, 42, -3));\r\n  BOOST_CHECK(test_div1(-30, 42, 3));\r\n  BOOST_CHECK(test_div1(-30, 42, -3));\r\n  BOOST_CHECK(test_div1(-42, -30, 3));\r\n  BOOST_CHECK(test_div1(-42, -30, -3));\r\n\r\n  BOOST_CHECK(test_div2(30, 2, 3));\r\n  BOOST_CHECK(test_div2(30, -3, -2));\r\n  BOOST_CHECK(test_div2(-30, 2, 3));\r\n  BOOST_CHECK(test_div2(-30, -3, -2));\r\n\r\n  BOOST_CHECK(test_square(2, 3));\r\n  BOOST_CHECK(test_square(-2, 3));\r\n  BOOST_CHECK(test_square(-3, 2));\r\n\r\n  BOOST_CHECK(test_sqrt(2, 3));\r\n  BOOST_CHECK(test_sqrt(5, 7));\r\n  BOOST_CHECK(test_sqrt(-1, 2));\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "bf05022a9ebb7f724ddc27b291e436c84185333c", "size": 3849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/test/mul.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/test/mul.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/test/mul.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0703125, "max_line_length": 75, "alphanum_fraction": 0.6071706937, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6285278846167472}}
{"text": "/** @file debug_bvn.cpp\n * @author Mark J. Olah (mjo\\@cs.unm DOT edu)\n * @date 2017-2018\n * @brief NormalDist class defintion\n * \n */\n#include \"PriorHessian/mvn_cdf.h\"\n\n#include <cmath>\n#include <limits>\n\n#include <armadillo>\n\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/math/constants/constants.hpp>\n\nusing namespace prior_hessian;\n\nvoid test_bvn()\n{\n    const int Nsample=100;\n    double ak = 0;\n    double ah = 0;\n    double r=0.2;\n    for(int n=0; n<Nsample; n++) {\n        ak += 0.1;\n        ah += 0.1;\n        double b = bvn_integral(ak,ah,r);\n        std::cout<<\"ak:\"<<ak<<\" ah:\"<<ah<<\" r:\"<<r<<\" b:\"<<b<<\"\\n\";\n    }\n}\n\nint main()\n{\n    test_bvn();\n    \n}\n", "meta": {"hexsha": "efb5aa3159c806508fa9b86b5dfd02f206e5450a", "size": 683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/debug_bvn.cpp", "max_stars_repo_name": "markjolah/PriorHessianLib", "max_stars_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-20T07:40:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T07:40:29.000Z", "max_issues_repo_path": "test/debug_bvn.cpp", "max_issues_repo_name": "markjolah/PriorHessianLib", "max_issues_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_issues_repo_licenses": ["Apache-2.0"], "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/debug_bvn.cpp", "max_forks_repo_name": "markjolah/PriorHessianLib", "max_forks_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.9736842105, "max_line_length": 67, "alphanum_fraction": 0.5827232796, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.88242786954645, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6284935343504429}}
{"text": "#include <iostream>\n#include <string>\n#include <acado_toolkit.hpp>\n#include <acado_gnuplot.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\n#define pi 3.14159\n\nusing namespace std;\n\nstatic boost::random::mt19937 gen;\n\nint gen_data(float bounds[8],int index, char cost_func, int thread);\nfloat rand_gen(float lim[2]);\n\nint gen_data(float bounds[8], int index, char cost_func, int thread)\n{\n  std::string states_nm, parameters_nm, control_nm;\n  bool flag = false;\n\n  USING_NAMESPACE_ACADO\n\n  DifferentialState        q1,q2,qd1,qd2;   // the differential states\n  Control                  tau1,tau2;       // the control input u\n  Parameter                T;\n  DifferentialEquation     f(0.0,0.5);\n\n  //  -------------------------------------\n  OCP ocp( 0.0, 0.5 );\n  \n  switch(cost_func){\n    case 'a': ocp.minimizeMayerTerm(T*T + tau1*qd1*tau1*qd1 + tau2*qd2*tau2*qd2);\n              cout << \"cost function = sq_power\" << endl;\n              break;\n\n    default:  //ocp.minimizeMayerTerm(T*T + tau1*tau1 + tau2*tau2);\n              ocp.minimizeLagrangeTerm(tau1*tau1);\n              ocp.minimizeLagrangeTerm(tau2*tau2);\n              cout << \"cost function = sq_torque\" << endl;\n  }\n\n  f << dot(q1) == qd1;\n  f << dot(q2) == qd2;\n  f << dot(qd1) == -(48*tau1 - 48*tau2 + 24*qd1*qd1*sin(q2) + 24*qd2*qd2*sin(q2) + 18*qd1*qd1*sin(2*q2) - 72*tau2*cos(q2) + 48*qd1*qd2*sin(q2))/(36*cos(q2)*cos(q2) - 64);\n  f << dot(qd2) == (48*tau1 - 240*tau2 + 120*qd1*qd1*sin(q2) + 24*qd2*qd2*sin(q2) + 36*qd1*qd1*sin(2*q2) + 18*qd2*qd2*sin(2*q2) + 72*tau1*cos(q2) - 144*tau2*cos(q2) + 48*qd1*qd2*sin(q2) + 36*qd1*qd2*sin(2*q2))/(18*cos(2*q2) - 46);\n\n  ocp.subjectTo(f);\n  ocp.subjectTo(AT_START, q1 == bounds[0] );\n  ocp.subjectTo(AT_START, q2 == bounds[1]);\n  ocp.subjectTo(AT_START, qd1 == bounds[2]);\n  ocp.subjectTo(AT_START, qd2 == bounds[3]);\n\n  ocp.subjectTo(AT_END, q1 == bounds[4]);\n  ocp.subjectTo(AT_END, q2 == bounds[5]);\n  ocp.subjectTo(AT_END, qd1 == bounds[6]);\n  ocp.subjectTo(AT_END, qd2 == bounds[7]);\n\n  // ocp.subjectTo(0.0 <= q1 <= 2*pi);\n  // ocp.subjectTo(0.0 <= q2 <= 2*pi);\n  ocp.subjectTo(-400 <= tau1 <= 400);  // bounds on the control input u,\n  ocp.subjectTo(-400 <= tau2 <= 400);\n\n  //  -------------------------------------\n\n  OptimizationAlgorithm algorithm(ocp);     // the optimization algorithm\n  algorithm.set( DISCRETIZATION_TYPE , MULTIPLE_SHOOTING);\n  algorithm.set( INTEGRATOR_TYPE , INT_BDF);\n  algorithm.set( HESSIAN_APPROXIMATION   , BLOCK_BFGS_UPDATE);\n  algorithm.set( KKT_TOLERANCE   , 1e-4); \n  algorithm.set( ABSOLUTE_TOLERANCE, 1e-4);\n  algorithm.set( INTEGRATOR_TOLERANCE, 1e-4);\n  algorithm.set( MAX_NUM_ITERATIONS, 1000);\n  algorithm.set( MAX_NUM_INTEGRATOR_STEPS, 10000);\n\n  algorithm.set(PRINT_COPYRIGHT,BT_FALSE);\n  algorithm.set(PRINTLEVEL,LOW);\n  algorithm.set(PRINT_INTEGRATOR_PROFILE,BT_FALSE);\n  algorithm.set(PRINT_SCP_METHOD_PROFILE,BT_FALSE);\n\n  algorithm.solve();                        // solves the problem.\n\n  VariablesGrid grid;\n  algorithm.getDifferentialStates(grid);\n  DVector final_state(4), req_state(4), diff(4);\n  final_state = grid.getLastVector();\n  req_state(0)=bounds[4];\n  req_state(1)=bounds[5];\n  req_state(2)=bounds[6];\n  req_state(3)=bounds[7];\n  diff = final_state - req_state;\n\n  if (diff.getNorm(VN_L2) < 0.001){\n    flag = true;\n    states_nm = \"states_\"+to_string(index)+\"_\"+to_string(thread)+\".txt\";\n    parameters_nm = \"parameters_\"+to_string(index)+\"_\"+to_string(thread)+\".txt\";\n    control_nm = \"control_\"+to_string(index)+\"_\"+to_string(thread)+\".txt\";\n    algorithm.getDifferentialStates(states_nm.c_str());\n    algorithm.getObjectiveValue(parameters_nm.c_str());\n    algorithm.getControls(control_nm.c_str());\n  }\n  clearAllStaticCounters();\n  return flag;\n}\n\nfloat rand_gen(float lim[2]) {\n    static boost::random::uniform_real_distribution<> dist(0, 1);\n    return lim[0] + dist(gen)*(lim[1] - lim[0]);\n}\n\nint main(int argc, const char * argv[]){\n  // srand (time(NULL));\n  int i;\n  float q_lims[2] = {0.0,2*pi};\n  float qd_lims[2] = {-30.0,30.0};\n\n  if(argc!=4){\n    cout << \"Incorrect number of arguments.\" << endl;\n  }\n  else{\n    int num_iter = atoi(argv[2]);\n    gen.seed(time(0) + atoi(argv[3]));\n    i = 0;\n    while(i<num_iter){\n      float bounds[8] = {rand_gen(q_lims),rand_gen(q_lims),rand_gen(qd_lims),rand_gen(qd_lims),rand_gen(q_lims),rand_gen(q_lims),rand_gen(qd_lims),rand_gen(qd_lims)};\n      cout << i << endl;\n      cout << bounds[0] << \" \" << bounds[1] << \" \" << bounds[2] << \" \" << bounds[3] << \" \" << bounds[4] << \" \" << bounds[5] << \" \" << bounds[6] << \" \" << bounds[7] << endl;\n      bool success = gen_data(bounds,i,*argv[1],atoi(argv[3]));\n      if(success){\n        i++;\n      }\n    }\n  }\n  return 0;\n}\n", "meta": {"hexsha": "3e0730b80e2264bfb1c6a1df0ec65527eeddec49", "size": 4766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2link_direct/src/old/2link_gendata.cpp", "max_stars_repo_name": "DeepakParamkusam/learning-based-RRT", "max_stars_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-06-13T11:36:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-13T11:36:45.000Z", "max_issues_repo_path": "2link_direct/src/old/2link_gendata.cpp", "max_issues_repo_name": "DeepakParamkusam/learning-based-RRT", "max_issues_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2link_direct/src/old/2link_gendata.cpp", "max_forks_repo_name": "DeepakParamkusam/learning-based-RRT", "max_forks_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0441176471, "max_line_length": 230, "alphanum_fraction": 0.6290390264, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278571786139, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6284935147615635}}
{"text": "// test_maximum.cpp\n// (c) Tivole\n\n#include <boost/test/unit_test.hpp>\n#include \"../src/numerary.hpp\"\n\nnamespace numerary\n{\n    \n    BOOST_AUTO_TEST_SUITE(TestMaximum)\n    \n    BOOST_AUTO_TEST_CASE(test_maximum_bisection)\n    {\n        const double eps = 1.e-9;\n        double answer;\n        double expected_answer;\n        short int result;\n        short int expected_result;\n\n        // Testing sin function\n        expected_result = 1;\n        expected_answer = M_PI_2;\n        result = Numerary::maximum(sin, -3, 3, &answer, \"bisection\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);\n\n\t    // Testing log function\n        expected_result = 1;\n        expected_answer = 4.0;\n        result = Numerary::maximum(log, 0.5, 4, &answer, \"bisection\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);\n    }\n\n\n    BOOST_AUTO_TEST_CASE(test_maximum_golden_ratio)\n    {\n        const double eps = 1.e-9;\n        double answer;\n        double expected_answer;\n        short int result;\n        short int expected_result;\n\n        // Testing sin function\n        expected_result = 1;\n        expected_answer = M_PI_2;\n        result = Numerary::maximum(sin, -3, 3, &answer, \"golden_ratio\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);\n\n\t    // Testing cos function\n        expected_result = 1;\n        expected_answer = 4.0;\n        result = Numerary::maximum(log, 0.5, 4, &answer, \"golden_ratio\", eps);\n        BOOST_CHECK_EQUAL(result, expected_result);\n        BOOST_CHECK(fabs(answer - expected_answer) < 1.e-7);\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n}\n\n", "meta": {"hexsha": "19f135d0b9ad36992b6c7e026ea5b9e9ac9fd815", "size": 1768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_maximum.cpp", "max_stars_repo_name": "tivole/Numerary", "max_stars_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-02-21T06:09:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T10:00:06.000Z", "max_issues_repo_path": "test/test_maximum.cpp", "max_issues_repo_name": "tivole/Ti_Numerary", "max_issues_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_maximum.cpp", "max_forks_repo_name": "tivole/Ti_Numerary", "max_forks_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T11:12:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T11:12:27.000Z", "avg_line_length": 28.5161290323, "max_line_length": 78, "alphanum_fraction": 0.6278280543, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6284884556439334}}
{"text": "// -----------------------------------------------------------------------\r\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\r\n//\r\n// Copyright (c) German Cancer Research Center (DKFZ),\r\n// Software development for Integrated Diagnostics and Therapy (SIDT).\r\n// ALL RIGHTS RESERVED.\r\n// See rttbCopyright.txt or\r\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html [^]\r\n//\r\n// This software is distributed WITHOUT ANY WARRANTY; without even\r\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n// PURPOSE. See the above copyright notices for more information.\r\n//\r\n//------------------------------------------------------------------------\r\n\r\n// this file defines the rttbCoreTests for the test driver\r\n// and all it expects is that you have a function called RegisterTests\r\n\r\n#include <boost/shared_ptr.hpp>\r\n\r\n#include \"litCheckMacros.h\"\r\n#include \"rttbBioModel.h\"\r\n#include \"rttbDVH.h\"\r\n#include \"rttbTCPLQModel.h\"\r\n#include \"rttbNTCPLKBModel.h\"\r\n#include \"rttbNTCPRSModel.h\"\r\n#include \"rttbBioModelScatterPlots.h\"\r\n#include \"rttbBioModelCurve.h\"\r\n#include \"rttbDvhBasedModels.h\"\r\n#include \"rttbDoseIteratorInterface.h\"\r\n#include \"rttbDVHXMLFileReader.h\"\r\n\r\nnamespace rttb\r\n{\r\n\tnamespace testing\r\n\t{\r\n\r\n\r\n\t\t/*! @brief RTBioModelTest.\r\n\t\tTCP calculated using a DVH PTV and LQ Model.\r\n\t\tNTCP tested using 3 Normal Tissue DVHs and LKB/RS Model.\r\n\r\n\t\tTest if calculation in new architecture returns similar results to the\r\n\t\toriginal implementation.\r\n\r\n\t\tWARNING: The values for comparison need to be adjusted if the input files are changed!\r\n\t\t*/\r\n\t\tint RTBioModelExampleTest(int argc, char* argv[])\r\n\t\t{\r\n\t\t\tPREPARE_DEFAULT_TEST_REPORTING;\r\n\r\n\t\t\ttypedef rttb::models::CurveDataType CurveDataType;\r\n\t\t\ttypedef std::multimap<double , std::pair<double, double> > ScatterPlotType;\r\n\t\t\ttypedef core::DVH::Pointer DVHPointer;\r\n\r\n\t\t\t//increased accuracy requires double values in the calculation (rttbBaseType.h)\r\n\t\t\tdouble toleranceEUD = 1e-5;\r\n\t\t\tdouble tolerance = 1e-7;\r\n\r\n\t\t\t//ARGUMENTS: 1: ptv dvh file name\r\n\t\t\t//           2: normal tissue 1 dvh file name\r\n\t\t\t//           3: normal tissue 2 dvh file name\r\n\t\t\t//           4: normal tissue 3 dvh file name\r\n\t\t\t//...........5: Virtuos MPM_LR_ah dvh lung file name\r\n\t\t\t//...........6: Virtuos MPM_LR_ah dvh target file name\r\n\r\n\t\t\tstd::string DVH_FILENAME_PTV;\r\n\t\t\tstd::string DVH_FILENAME_NT1;\r\n\t\t\tstd::string DVH_FILENAME_NT2;\r\n\t\t\tstd::string DVH_FILENAME_NT3;\r\n\t\t\tstd::string DVH_FILENAME_TV_TEST;\r\n\t\t\tstd::string DVH_Virtuos_Target;\r\n\t\t\tstd::string DVH_Virtuos_Lung;\r\n\r\n\t\t\tif (argc > 1)\r\n\t\t\t{\r\n\t\t\t\tDVH_FILENAME_PTV = argv[1];\r\n\t\t\t}\r\n\r\n\t\t\tif (argc > 2)\r\n\t\t\t{\r\n\t\t\t\tDVH_FILENAME_NT1 = argv[2];\r\n\t\t\t}\r\n\r\n\t\t\tif (argc > 3)\r\n\t\t\t{\r\n\t\t\t\tDVH_FILENAME_NT2 = argv[3];\r\n\t\t\t}\r\n\r\n\t\t\tif (argc > 4)\r\n\t\t\t{\r\n\t\t\t\tDVH_FILENAME_NT3 = argv[4];\r\n\t\t\t}\r\n\r\n\t\t\tif (argc > 5)\r\n\t\t\t{\r\n\t\t\t\tDVH_FILENAME_TV_TEST = argv[5];\r\n\t\t\t}\r\n\r\n\t\t\tif (argc > 6)\r\n\t\t\t{\r\n\t\t\t\tDVH_Virtuos_Lung = argv[6];\r\n\t\t\t}\r\n\r\n\t\t\tif (argc > 7)\r\n\t\t\t{\r\n\t\t\t\tDVH_Virtuos_Target = argv[7];\r\n\t\t\t}\r\n\r\n\r\n\t\t\t//DVH PTV\r\n\t\t\trttb::io::other::DVHXMLFileReader dvhReader = rttb::io::other::DVHXMLFileReader(DVH_FILENAME_PTV);\r\n\t\t\tDVHPointer dvhPtr = dvhReader.generateDVH();\r\n\r\n\t\t\tCHECK_CLOSE(6.04759613161786830000e+001, models::getEUD(dvhPtr, 10), toleranceEUD);\r\n\r\n\t\t\trttb::io::other::DVHXMLFileReader dvhReader_test_tv = rttb::io::other::DVHXMLFileReader(\r\n\t\t\t            DVH_FILENAME_TV_TEST);\r\n\t\t\tDVHPointer dvh_test_tv = dvhReader_test_tv.generateDVH();\r\n\r\n\r\n\t\t\t//test TCP LQ Model\r\n\t\t\tmodels::BioModelParamType alpha = 0.35;\r\n\t\t\tmodels::BioModelParamType beta = 0.023333333333333;\r\n\t\t\tmodels::BioModelParamType roh = 10000000;\r\n\t\t\tint numFractions = 2;\r\n\r\n\t\t\tDoseTypeGy normalizationDose = 68;\r\n\r\n\t\t\trttb::models::TCPLQModel tcplq = rttb::models::TCPLQModel(dvhPtr, alpha, beta, roh, numFractions);\r\n\t\t\tCHECK_EQUAL(alpha, tcplq.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(alpha / beta, tcplq.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(roh, tcplq.getRho());\r\n\r\n\t\t\tCHECK_NO_THROW(tcplq.init());\r\n\r\n\t\t\tif (tcplq.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(1.00497232941856940000e-127, tcplq.getValue(), tolerance);\r\n\t\t\t}\r\n\r\n\t\t\tCurveDataType curve = models::getCurveDoseVSBioModel(tcplq, normalizationDose);\r\n\t\t\tCurveDataType::iterator it;\r\n\r\n\t\t\tfor (it = curve.begin(); it != curve.end(); ++it)\r\n\t\t\t{\r\n\t\t\t\tif ((*it).first < 72)\r\n\t\t\t\t{\r\n\t\t\t\t\tCHECK_EQUAL(0, (*it).second);\r\n\t\t\t\t}\r\n\t\t\t\telse if ((*it).first > 150)\r\n\t\t\t\t{\r\n\t\t\t\t\tCHECK((*it).second > 0.9);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tmodels::BioModelParamType alphaBeta = 10;\r\n\t\t\ttcplq.setParameters(alpha, alphaBeta, roh, 0.08);\r\n\t\t\tCHECK_EQUAL(alpha, tcplq.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(alphaBeta, tcplq.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(roh, tcplq.getRho());\r\n\r\n\t\t\tif (tcplq.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(1.84e-005, tcplq.getValue(), tolerance);\r\n\t\t\t}\r\n\r\n\t\t\tnormalizationDose = 40;\r\n\t\t\tcurve = models::getCurveDoseVSBioModel(tcplq, normalizationDose);\r\n\r\n\t\t\talpha = 1;\r\n\t\t\talphaBeta = 14.5;\r\n\t\t\ttcplq.setAlpha(alpha);\r\n\t\t\ttcplq.setAlphaBeta(alphaBeta);\r\n\t\t\ttcplq.setRho(roh);\r\n\t\t\tCHECK_EQUAL(alpha, tcplq.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(alphaBeta, tcplq.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(roh, tcplq.getRho());\r\n\r\n\t\t\tif (tcplq.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(0.954885, tcplq.getValue(), toleranceEUD);\r\n\t\t\t}\r\n\r\n\t\t\talpha = 0.9;\r\n\t\t\talphaBeta = 1;\r\n\t\t\ttcplq.setAlpha(alpha);\r\n\t\t\ttcplq.setAlphaBeta(alphaBeta);\r\n\t\t\ttcplq.setRho(roh);\r\n\t\t\tCHECK_EQUAL(alpha, tcplq.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(alphaBeta, tcplq.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(roh, tcplq.getRho());\r\n\r\n\t\t\tif (tcplq.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_EQUAL(1, tcplq.getValue());\r\n\t\t\t}\r\n\r\n\r\n\t\t\t//TCP LQ Test\r\n\t\t\talpha = 0.3;\r\n\t\t\tbeta = 0.03;\r\n\t\t\troh = 10000000;\r\n\t\t\tnumFractions = 20;\r\n\t\t\trttb::models::TCPLQModel tcplq_test = rttb::models::TCPLQModel(dvh_test_tv, alpha, beta, roh,\r\n\t\t\t                                      numFractions);\r\n\t\t\tCHECK_EQUAL(alpha, tcplq_test.getAlphaMean());\r\n\t\t\tCHECK_EQUAL(alpha / beta, tcplq_test.getAlphaBeta());\r\n\t\t\tCHECK_EQUAL(roh, tcplq_test.getRho());\r\n\t\t\tCHECK_NO_THROW(tcplq_test.init());\r\n\r\n\t\t\tif (tcplq_test.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(9.79050278878883180000e-001, tcplq_test.getValue(), tolerance);\r\n\t\t\t}\r\n\r\n\t\t\tnormalizationDose = 60;\r\n\t\t\tcurve = models::getCurveDoseVSBioModel(tcplq_test, normalizationDose);\r\n\r\n\t\t\t//DVH HT 1\r\n\t\t\trttb::io::other::DVHXMLFileReader dvhReader2 = rttb::io::other::DVHXMLFileReader(DVH_FILENAME_NT1);\r\n\t\t\tDVHPointer dvhPtr2 = dvhReader2.generateDVH();\r\n\r\n\t\t\tCHECK_CLOSE(1.07920836034015810000e+001, models::getEUD(dvhPtr2, 10), toleranceEUD);\r\n\r\n\t\t\t//test RTNTCPLKBModel\r\n\t\t\trttb::models::NTCPLKBModel lkb = rttb::models::NTCPLKBModel();\r\n\t\t\tmodels::BioModelParamType aVal = 10;\r\n\t\t\tmodels::BioModelParamType mVal = 0.16;\r\n\t\t\tmodels::BioModelParamType d50Val = 55;\r\n\t\t\tCHECK_EQUAL(0, lkb.getA());\r\n\t\t\tCHECK_EQUAL(0, lkb.getM());\r\n\t\t\tCHECK_EQUAL(0, lkb.getD50());\r\n\t\t\tlkb.setDVH(dvhPtr2);\r\n\t\t\tCHECK_EQUAL(dvhPtr2, lkb.getDVH());\r\n\t\t\tlkb.setA(aVal);\r\n\t\t\tCHECK_EQUAL(aVal, lkb.getA());\r\n\t\t\tlkb.setM(mVal);\r\n\t\t\tCHECK_EQUAL(mVal, lkb.getM());\r\n\t\t\tlkb.setD50(d50Val);\r\n\t\t\tCHECK_EQUAL(d50Val, lkb.getD50());\r\n\t\t\tCHECK_NO_THROW(lkb.init());\r\n\r\n\t\t\tif (lkb.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(2.53523522831366570000e-007, lkb.getValue(), tolerance);\r\n\t\t\t}\r\n\r\n\t\t\t//test RTNTCPRSModel\r\n\t\t\trttb::models::NTCPRSModel rs = rttb::models::NTCPRSModel();\r\n\t\t\tmodels::BioModelParamType gammaVal = 1.7;\r\n\t\t\tmodels::BioModelParamType sVal = 1;\r\n\t\t\tCHECK_EQUAL(0, rs.getGamma());\r\n\t\t\tCHECK_EQUAL(0, rs.getS());\r\n\t\t\tCHECK_EQUAL(0, rs.getD50());\r\n\t\t\trs.setDVH(dvhPtr2);\r\n\t\t\tCHECK_EQUAL(dvhPtr2, rs.getDVH());\r\n\t\t\trs.setD50(d50Val);\r\n\t\t\tCHECK_EQUAL(d50Val, rs.getD50());\r\n\t\t\trs.setGamma(gammaVal);\r\n\t\t\tCHECK_EQUAL(gammaVal, rs.getGamma());\r\n\t\t\trs.setS(sVal);\r\n\t\t\tCHECK_EQUAL(sVal, rs.getS());\r\n\t\t\tCHECK_NO_THROW(rs.init());\r\n\r\n\t\t\tif (rs.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(3.70385888626145740000e-009, rs.getValue(), tolerance);\r\n\t\t\t}\r\n\r\n\t\t\t//DVH HT 2\r\n\t\t\trttb::io::other::DVHXMLFileReader dvhReader3 = rttb::io::other::DVHXMLFileReader(DVH_FILENAME_NT2);\r\n\t\t\tDVHPointer dvhPtr3 = dvhReader3.generateDVH();\r\n\t\t\tCHECK_CLOSE(1.26287047025885110000e+001, models::getEUD(dvhPtr3, 10), toleranceEUD);\r\n\r\n\t\t\t//test RTNTCPLKBModel\r\n\t\t\taVal = 10;\r\n\t\t\tmVal = 0.16;\r\n\t\t\td50Val = 55;\r\n\r\n\t\t\tlkb.setDVH(dvhPtr3);\r\n\t\t\tCHECK_EQUAL(dvhPtr3, lkb.getDVH());\r\n\t\t\tlkb.setA(aVal);\r\n\t\t\tCHECK_EQUAL(aVal, lkb.getA());\r\n\t\t\tlkb.setM(mVal);\r\n\t\t\tCHECK_EQUAL(mVal, lkb.getM());\r\n\t\t\tlkb.setD50(d50Val);\r\n\t\t\tCHECK_EQUAL(d50Val, lkb.getD50());\r\n\r\n\t\t\tif (lkb.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(7.36294657754956700000e-007, lkb.getValue(), tolerance);\r\n\t\t\t}\r\n\r\n\t\t\t//test RTNTCPRSModel\r\n\t\t\trs = rttb::models::NTCPRSModel();\r\n\t\t\tgammaVal = 1.7;\r\n\t\t\tsVal = 1;\r\n\t\t\tCHECK_EQUAL(0, rs.getGamma());\r\n\t\t\tCHECK_EQUAL(0, rs.getS());\r\n\t\t\tCHECK_EQUAL(0, rs.getD50());\r\n\t\t\trs.setDVH(dvhPtr3);\r\n\t\t\tCHECK_EQUAL(dvhPtr3, rs.getDVH());\r\n\t\t\trs.setD50(d50Val);\r\n\t\t\tCHECK_EQUAL(d50Val, rs.getD50());\r\n\t\t\trs.setGamma(gammaVal);\r\n\t\t\tCHECK_EQUAL(gammaVal, rs.getGamma());\r\n\t\t\trs.setS(sVal);\r\n\t\t\tCHECK_EQUAL(sVal, rs.getS());\r\n\r\n\t\t\tif (rs.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(1.76778795490939440000e-007, rs.getValue(), tolerance);\r\n\t\t\t}\r\n\r\n\r\n\t\t\t//DVH HT 3\r\n\t\t\trttb::io::other::DVHXMLFileReader dvhReader4 = rttb::io::other::DVHXMLFileReader(DVH_FILENAME_NT3);\r\n\t\t\tDVHPointer dvhPtr4 = dvhReader4.generateDVH();\r\n\t\t\tCHECK_CLOSE(2.18212982041056310000e+001, models::getEUD(dvhPtr4, 10), toleranceEUD);\r\n\r\n\t\t\t//test RTNTCPLKBModel\r\n\t\t\taVal = 10;\r\n\t\t\tmVal = 0.16;\r\n\t\t\td50Val = 55;\r\n\t\t\tlkb.setDVH(dvhPtr4);\r\n\t\t\tCHECK_EQUAL(dvhPtr4, lkb.getDVH());\r\n\t\t\tlkb.setA(aVal);\r\n\t\t\tCHECK_EQUAL(aVal, lkb.getA());\r\n\t\t\tlkb.setM(mVal);\r\n\t\t\tCHECK_EQUAL(mVal, lkb.getM());\r\n\t\t\tlkb.setD50(d50Val);\r\n\t\t\tCHECK_EQUAL(d50Val, lkb.getD50());\r\n\r\n\t\t\tif (lkb.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(8.15234192641929420000e-005, lkb.getValue(), tolerance);\r\n\t\t\t}\r\n\r\n\t\t\t//test RTNTCPRSModel\r\n\t\t\trs = rttb::models::NTCPRSModel();\r\n\t\t\tgammaVal = 1.7;\r\n\t\t\tsVal = 1;\r\n\t\t\tCHECK_EQUAL(0, rs.getGamma());\r\n\t\t\tCHECK_EQUAL(0, rs.getS());\r\n\t\t\tCHECK_EQUAL(0, rs.getD50());\r\n\t\t\trs.setDVH(dvhPtr4);\r\n\t\t\tCHECK_EQUAL(dvhPtr4, rs.getDVH());\r\n\t\t\trs.setD50(d50Val);\r\n\t\t\tCHECK_EQUAL(d50Val, rs.getD50());\r\n\t\t\trs.setGamma(gammaVal);\r\n\t\t\tCHECK_EQUAL(gammaVal, rs.getGamma());\r\n\t\t\trs.setS(sVal);\r\n\t\t\tCHECK_EQUAL(sVal, rs.getS());\r\n\r\n\t\t\tif (rs.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(2.02607985020919480000e-004, rs.getValue(), tolerance);\r\n\t\t\t}\r\n\r\n\r\n\t\t\t//test using Virtuos Pleuramesotheliom MPM_LR_ah\r\n\t\t\t//DVH PTV\r\n\r\n\r\n\t\t\trttb::io::other::DVHXMLFileReader dR_Target = rttb::io::other::DVHXMLFileReader(DVH_Virtuos_Target);\r\n\t\t\tDVHPointer dvhPtrTarget = dR_Target.generateDVH();\r\n\r\n\t\t\trttb::io::other::DVHXMLFileReader dR_Lung = rttb::io::other::DVHXMLFileReader(DVH_Virtuos_Lung);\r\n\t\t\tDVHPointer dvhPtrLung = dR_Lung.generateDVH();\r\n\r\n\r\n\t\t\t//test TCP LQ Model\r\n\t\t\tmodels::BioModelParamType alphaMean = 0.34;\r\n\t\t\tmodels::BioModelParamType alphaVarianz = 0.02;\r\n\t\t\tmodels::BioModelParamType alpha_beta = 28;\r\n\t\t\tmodels::BioModelParamType rho = 1200;\r\n\r\n\t\t\tint numFractionsVirtuos = 27;\r\n\r\n\t\t\trttb::models::TCPLQModel tcplqVirtuos = rttb::models::TCPLQModel(dvhPtrTarget, rho,\r\n\t\t\t                                        numFractionsVirtuos, alpha_beta,\r\n\t\t\t                                        alphaMean, alphaVarianz);\r\n\r\n\t\t\tif (tcplqVirtuos.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(0.8894, tcplqVirtuos.getValue(), 1e-4);\r\n\t\t\t}\r\n\r\n\t\t\tmodels::BioModelParamType d50Mean = 20;\r\n\t\t\tmodels::BioModelParamType m = 0.36;\r\n\t\t\tmodels::BioModelParamType a = 1.06;\r\n\r\n\t\t\trttb::models::NTCPLKBModel lkbVirtuos = rttb::models::NTCPLKBModel(dvhPtrLung, d50Mean, m, a);\r\n\r\n\t\t\tif (lkbVirtuos.init())\r\n\t\t\t{\r\n\t\t\t\tCHECK_CLOSE(0.0397, lkbVirtuos.getValue(), 1e-4);\r\n\t\t\t}\r\n\r\n\r\n\r\n\r\n\t\t\tRETURN_AND_REPORT_TEST_SUCCESS;\r\n\r\n\t\t}\r\n\r\n\t}//testing\r\n}//rttb\r\n", "meta": {"hexsha": "9a99dc79cb1d0ad5baaf7418e53335065f4d6f81", "size": 11710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/examples/RTBioModelExampleTest.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "testing/examples/RTBioModelExampleTest.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/examples/RTBioModelExampleTest.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 28.5609756098, "max_line_length": 104, "alphanum_fraction": 0.6438941076, "num_tokens": 3762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021708, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6284884506629826}}
{"text": "#include \"ExplicitEuler.h\"\n#include <Eigen/LU>\n#include <Eigen/Core>\n\nbool ExplicitEuler::stepScene( TwoDScene& scene, scalar dt )\n{\n    // Your code goes here!\n    \n    // Some tips on getting data from TwoDScene:\n    // A vector containing all of the system's position DoFs. x0, y0, x1, y1, ...\n    //VectorXs& x = scene.getX();\n    // A vector containing all of the system's velocity DoFs. v0, v0, v1, v1, ...\n    //VectorXs& v = scene.getV();\n    // A vector containing the masses associated to each DoF. m0, m0, m1, m1, ...\n    //const VectorXs& m = scene.getM();\n    // Determine if the ith particle is fixed\n    // if( scene.isFixed(i) )\n    \n    VectorXs& qn = scene.getX();\n    VectorXs& qn1 = qn;\n    VectorXs& qdotn = scene.getV();\n    VectorXs& qdotn1 = qdotn;\n    \n    const VectorXs& m = scene.getM();\n    MatrixXs M = m.asDiagonal();\n    MatrixXs MMinus1 = M.inverse();\n    \n    VectorXs f(qn.size());\n    scene.accumulateGradU(f);\n    \n    //(n,1) = (n,n)*(n,1)\n    VectorXs Pn =  M*qdotn;\n    //(n,1) = (n,1) + (1,1)*(n,n)*(n,1)\n    qn1 = qn + dt*MMinus1*Pn;\n    qdotn1 = qdotn + dt*f;\n    \n    for(int i = 0; i < scene.getNumParticles(); ++i)\n    {\n        if(scene.isFixed(i))\n        {\n            scene.setVelocity(i, {0,0});\n        }\n    }\n    \n    return true;\n}\n", "meta": {"hexsha": "f999e4f568275f08e239d3e4d07324a7a1b5a756", "size": 1287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "courses/columbia-cg-animation/week01/FOSSSim/ExplicitEuler.cpp", "max_stars_repo_name": "xunilrj/sandbox", "max_stars_repo_head_hexsha": "f92c12f83433cac01a885585e41c02bb5826a01f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "courses/columbia-cg-animation/week01/FOSSSim/ExplicitEuler.cpp", "max_issues_repo_name": "xunilrj/sandbox", "max_issues_repo_head_hexsha": "f92c12f83433cac01a885585e41c02bb5826a01f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "courses/columbia-cg-animation/week01/FOSSSim/ExplicitEuler.cpp", "max_forks_repo_name": "xunilrj/sandbox", "max_forks_repo_head_hexsha": "f92c12f83433cac01a885585e41c02bb5826a01f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 27.3829787234, "max_line_length": 81, "alphanum_fraction": 0.5617715618, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.628464564584712}}
{"text": "#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl; using namespace mtl::mat;\n    \n    const unsigned                xd= 2, yd= 5, n= xd * yd;\n    dense2D<double>               A(n, n);\n    laplacian_setup(A, xd, yd); \n    dense_vector<double>          v(n), w(n, 7.0);\n\n    // Scale A with 4 and multiply the scaled view with w\n    v= 4 * A * w;\n    std::cout << \"v is \" << v << \"\\n\";\n\n    // Scale w with 4 and multiply the scaled view with A\n    v= A * (4 * w);\n    std::cout << \"v is \" << v << \"\\n\";\n\n    // Scale both with 2 before multiplying\n    v= 2 * A * (2 * w);\n    std::cout << \"v is \" << v << \"\\n\";\n\n    // Scale v after the MVP\n    v= A * w;\n    v*= 4;\n    std::cout << \"v is \" << v << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "eb2d4e08963744aa23e38a48d5816d8f64b94e26", "size": 758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/scaled_matrix_vector_mult.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/scaled_matrix_vector_mult.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/scaled_matrix_vector_mult.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 24.4516129032, "max_line_length": 59, "alphanum_fraction": 0.4802110818, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6284645645847119}}
{"text": "//\n// Created by Alex Beccaro on 09/01/18.\n//\n\n#include \"problem56.hpp\"\n#include <boost/multiprecision/cpp_int.hpp>\n#include <generics.hpp>\n\nusing boost::multiprecision::uint1024_t;\nusing generics::digits;\n\nnamespace problems {\n    uint32_t problem56::solve(uint32_t base_ub, uint32_t exp_ub) {\n        uint32_t result = 0;\n\n        for (uint32_t a = 1; a < base_ub; a++) {\n            uint1024_t n = 1;\n            for (uint32_t b = 1; b < exp_ub; b++) {\n                n *= a;\n                auto digs = digits(n);\n\n                uint32_t sum = 0;\n                for (const auto &d : digs)\n                    sum += d;\n\n                if (sum > result)\n                    result = sum;\n            }\n        }\n\n        return result;\n    }\n}", "meta": {"hexsha": "ed0722cfa6e16ed215ea6c43c4c4386cd013cbe3", "size": 751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/problems/51-100/56/problem56.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "src/problems/51-100/56/problem56.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/51-100/56/problem56.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7575757576, "max_line_length": 66, "alphanum_fraction": 0.4980026631, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6284425397975127}}
{"text": "// ===========================================================================\n// Imagine++ Libraries\n// Copyright (C) Imagine\n// For detailed information: http://imagine.enpc.fr/software\n// ===========================================================================\n\n#include \"Imagine/LinAlg/MyEigen.h\"\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n//N'existe pas dans Eigen Blas\n//corriger\n//info=0 si succes, -i si ieme parametre illegal, i si bdsdc ne converge pas\n//info important car utilise dans Matrix.h\n// Singular values decomposition\n/* jobz est non usite... et est dans la liste des arguments de Imagine::svd */\ntemplate <typename T>\nvoid subSingularValuesDecomposition(const char *jobz,int *m,int *n, T *a, T *s, T *u, T *vt, int *info)\n{\n    assert((*jobz == 'A') || (*jobz == 'S')); // ?\n    Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > AMap (a, *m, *n, OuterStride<>(*m));\n    Eigen::JacobiSVD<Matrix<T, Dynamic, Dynamic> > svd (AMap, ComputeFullU | ComputeFullV);\n    Matrix<T, Dynamic, Dynamic> u1 = svd.matrixU();\n    Matrix<T, Dynamic, Dynamic> v1 = svd.matrixV();\n    Matrix<T, Dynamic, Dynamic> sv = svd.singularValues();\n    Map<Matrix<T, Dynamic, 1> > sMap (s, sv.rows());\n    sMap = sv;\n    Map<Matrix<T, Dynamic, Dynamic> > uMap (u, u1.rows(), u1.cols());\n    uMap = u1;\n    Map<Matrix<T, Dynamic, Dynamic> > vtMap (vt, v1.rows(), v1.cols());\n    vtMap = v1.transpose();\n    Matrix<T, Dynamic, Dynamic> sigma = Matrix<T, Dynamic, Dynamic>::Zero(*m,*n);\n    for (int i = 0 ; i < sMap.rows() ; i++){\n        sigma(i, i) = sMap(i);\n    };\n    *info = 1 - AMap.isApprox(uMap * sigma * vtMap);\n}\n\nvoid singularValuesDecomposition(const char *jobz,int *m,int *n, double *a, double *s, double *u, double *vt, int *info) { subSingularValuesDecomposition<double>(jobz, m, n, a, s, u, vt, info); }\nvoid singularValuesDecomposition(const char *jobz,int *m,int *n, float *a, float *s, float *u, float *vt, int *info) { subSingularValuesDecomposition<float>(jobz, m, n, a, s, u, vt, info); }\n\n// Returns Eigen values (replaces xgeev_)\ntemplate <typename T>\nvoid subEigenValues(int *n, T *a, T *wr, T *wi, T *vr, int *info) \n{\n    Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > AMap (a, *n, *n, OuterStride<>(*n));\n\n    EigenSolver<Matrix<T, Dynamic, Dynamic> > ces(AMap);\n    *info = 1 - int(ces.info());\n    Matrix<std::complex<T>, Dynamic, 1> w1 = ces.eigenvalues();\n    Map<Matrix<T, Dynamic, 1> > wrMap (wr, w1.rows());\n    Map<Matrix<T, Dynamic, 1> > wiMap (wi, w1.rows());\n    Matrix<std::complex<T>, Dynamic, Dynamic> Vr = ces.eigenvectors();\n    Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > VrMap (vr, *n, Vr.cols(), OuterStride<>(1));\n    wrMap = w1.real();\n    wiMap = w1.imag();\n    int j = 0;\n    while (j < Vr.cols()) \n    {\n        Matrix<T, Dynamic, 1> Xr = Vr.col(j).real();\n        Matrix<T, Dynamic, 1> Xc = Vr.col(j).imag();\n        if (Xc.isZero())\n        {\n            VrMap.col(j) = Xr;\n            j++;\n        }\n        else\n        {\n            VrMap.col(j) = Xr;\n            VrMap.col(j + 1) = Xc;\n            j += 2;\n        };\n    }\n}\n\nvoid eigenValues(int *n, double *a, double *wr, double *wi, double *vr, int *info) { subEigenValues<double>(n, a, wr, wi, vr, info); }\nvoid eigenValues(int *n, float *a, float *wr, float *wi, float *vr, int *info) { subEigenValues<float>(n, a, wr, wi, vr, info); }\n", "meta": {"hexsha": "471eb27555960eb40715ac69d6276ef6a4086adf", "size": 3365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Imagine/LinAlg/src/MyEigen2.cpp", "max_stars_repo_name": "Ethiy/imagine-pp", "max_stars_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Imagine/LinAlg/src/MyEigen2.cpp", "max_issues_repo_name": "Ethiy/imagine-pp", "max_issues_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Imagine/LinAlg/src/MyEigen2.cpp", "max_forks_repo_name": "Ethiy/imagine-pp", "max_forks_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "max_forks_repo_licenses": ["BSD-3-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.5949367089, "max_line_length": 195, "alphanum_fraction": 0.5750371471, "num_tokens": 1058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6284425270971749}}
{"text": "#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <tf/transform_datatypes.h>\n\ntf::Quaternion getAverageQuaternion(\n  const std::vector<tf::Quaternion>& quaternions, \n  const std::vector<double>& weights)\n{\n  Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(4, quaternions.size());\n  Eigen::Vector3d vec;\n  for (size_t i = 0; i < quaternions.size(); ++i)\n  {\n    // Weigh the quaternions according to their associated weight\n    tf::Quaternion quat = quaternions[i] * weights[i];\n    // Append the weighted Quaternion to a matrix Q.\n    Q(0,i) = quat.x();\n    Q(1,i) = quat.y();\n    Q(2,i) = quat.z();\n    Q(3,i) = quat.w();\n  }\n\n  // Creat a solver for finding the eigenvectors and eigenvalues\n  Eigen::EigenSolver<Eigen::MatrixXd> es(Q * Q.transpose());\n\n  // Find index of maximum (real) Eigenvalue.\n  auto eigenvalues = es.eigenvalues();\n  size_t max_idx = 0;\n  double max_value = eigenvalues[max_idx].real();\n  for (size_t i = 1; i < 4; ++i)\n  {\n    double real = eigenvalues[i].real();\n    if (real > max_value)\n    {\n      max_value = real;\n      max_idx = i;\n    }\n  }\n\n  // Get corresponding Eigenvector, normalize it and return it as the average quat\n  auto eigenvector = es.eigenvectors().col(max_idx).normalized();\n\n  tf::Quaternion mean_orientation(\n    eigenvector[0].real(),\n    eigenvector[1].real(),\n    eigenvector[2].real(),\n    eigenvector[3].real()\n  );\n\n  return mean_orientation;\n}", "meta": {"hexsha": "ce8dcbff2b628477beb356502fde8b0b1e4d614d", "size": 1424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "averaging_quaternions.cpp", "max_stars_repo_name": "BobMcFry/averaging_weighted_quaternions", "max_stars_repo_head_hexsha": "b16b6182751d26dcfa3e778b66066268fafe5642", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-01-26T12:01:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T05:44:58.000Z", "max_issues_repo_path": "averaging_quaternions.cpp", "max_issues_repo_name": "BobMcFry/averaging_weighted_quaternions", "max_issues_repo_head_hexsha": "b16b6182751d26dcfa3e778b66066268fafe5642", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-06T20:31:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-09T12:10:04.000Z", "max_forks_repo_path": "averaging_quaternions.cpp", "max_forks_repo_name": "BobMcFry/averaging_weighted_quaternions", "max_forks_repo_head_hexsha": "b16b6182751d26dcfa3e778b66066268fafe5642", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T02:30:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T20:52:38.000Z", "avg_line_length": 27.9215686275, "max_line_length": 82, "alphanum_fraction": 0.654494382, "num_tokens": 405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798115, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6284048976220364}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <vector>\n#include <numeric>\n#include <boost/algorithm/string/find.hpp>\n\nclass Calculator\n{\n    public:\n        Calculator() = default;\n\n        Calculator(std::string file_name)\n        {\n            std::ifstream file(file_name);\n            std::string expression;\n            if(file.is_open())\n            {\n                while(std::getline(file, expression))\n                {\n                    expressions.push_back(expression);\n                }\n            }\n        }\n\n        std::vector<std::string> expressions;\n\n        long long calculate(bool addition_over_multiplication = false)\n        {\n            long long result = std::accumulate(std::begin(expressions), std::end(expressions), \n            0LL, [&](const long long previous, std::string expression)\n            { \n                expression.erase(std::remove_if(expression.begin(), expression.end(), isspace), expression.end());\n                return previous + (addition_over_multiplication == true ? calculate(expression, true) : calculate(expression));\n            });\n            return result;\n        }\n\n    private:\n        std::string extract(const std::string expression, int start) const\n        {\n            std::string part = expression.substr(start + 1);\n            int opened_parts = 1;\n            int end = 0;\n            while(opened_parts != 0 && end < part.size())\n            {\n                if(part[end] == '(') opened_parts++;\n                else if(part[end] == ')') opened_parts--;\n                end++;\n            }\n            return part.substr(0, end - 1);\n        }\n\n        enum class Mode\n        {\n            sum = 1, multiply = 2\n        };\n\n        long long do_operation(long long first, long long second, Mode mode) const\n        {\n            return ((mode == Mode::sum) ? first + second : first * second);\n        }\n\n        long long calculate(const std::string expression, bool addition_over_multiplication = false) const\n        {\n            long long first_element = -1LL;\n            long long second_element = -1LL;\n            Mode mode = Mode::sum;\n            for(int i = 0; i < expression.size(); i++)\n            {\n                if(expression[i] == ')') continue;\n                if(expression[i] == '(')\n                {\n                    std::string part = extract(expression, i);\n                    second_element = first_element == -1LL ? second_element : calculate(part, addition_over_multiplication);\n                    first_element = first_element == -1LL ? calculate(part, addition_over_multiplication) : first_element;\n                    i += part.size();\n                }\n                else if(expression[i] == '*' || expression[i] == '+')\n                {\n                    mode = expression[i] == '*' ? Mode::multiply : Mode::sum;\n                    if(addition_over_multiplication && mode == Mode::multiply)\n                    {\n                        second_element = calculate(expression.substr(i + 1), addition_over_multiplication);\n                        first_element *= second_element;\n                        break;\n                    }\n                }\n                else // number\n                {\n                    long long num = (long long)(expression[i] - '0');\n                    second_element = first_element == -1LL ? second_element : num;\n                    first_element = first_element == -1LL ? num : first_element;\n                }\n                if(first_element != -1LL && second_element != -1LL)\n                {\n                    first_element = do_operation(first_element, second_element, mode);\n                    second_element = -1LL;\n                }\n            }\n            return first_element;\n        }\n};\n\nvoid part1(const std::string& file_name)\n{\n    std::cout << \"======\\nPart 1\\n======\\n\";\n    Calculator calculator(file_name);\n    std::cout << \"Sum of the resulting values = \" << calculator.calculate() << '\\n';\n}\n\nvoid part2(const std::string& file_name)\n{\n    std::cout << \"======\\nPart 2\\n======\\n\";\n    Calculator calculator(file_name);\n    std::cout << \"Sum of the resulting values = \" << calculator.calculate(true) << '\\n';\n}\n\nint main()\n{\n    const std::string file_name = \"/home/daria/Documents/AoC2020/input/day18.txt\";\n    part1(file_name);\n    std::cout << '\\n';\n    part2(file_name);\n    std::cout << '\\n';\n}", "meta": {"hexsha": "30bc8857ab10be970db08b2870893309686a56cf", "size": 4417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/day18.cpp", "max_stars_repo_name": "Daria2002/AoC2020", "max_stars_repo_head_hexsha": "29f7e098867934172a2c4460b13caff12f668e94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/day18.cpp", "max_issues_repo_name": "Daria2002/AoC2020", "max_issues_repo_head_hexsha": "29f7e098867934172a2c4460b13caff12f668e94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/day18.cpp", "max_forks_repo_name": "Daria2002/AoC2020", "max_forks_repo_head_hexsha": "29f7e098867934172a2c4460b13caff12f668e94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0555555556, "max_line_length": 127, "alphanum_fraction": 0.5078107313, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.6284048901694287}}
{"text": "//\n//  cross_product.cpp\n//  BGV-Adder\n//\n//  Created by Hindrik Stegenga on 26/10/2020.\n//  Copyright \u00a9 2020 RUG. All rights reserved.\n//\n\n#include \"cross_product.hpp\"\n#include <helib/FHE.h>\n#include <NTL/ZZX.h>\n#include <NTL/tools.h>\n\nusing helib::Ctxt;\n\narray<long, CV_SIZE> compute_cross_product(array<i16, CV_SIZE> lhs, array<i16, CV_SIZE> rhs) {\n    long k = 128; // Security parameter\n    long L = 16; // Number of levels in the modulus default is 16\n    long c = 3; // Nr of columns in key switch matrix.\n    long w = 64; // secret key hamming weight\n    \n    // Change to 65537 for noise warning. (Always fun times)\n    // Compensate for that by setting L = 128. (Increase modchain basically)\n    // Set P to 65537 and L to 32 to showcase decryption failures.\n    \n    long p = 1021; // plaintext base default = 1021\n    long d = 0; // Degree of field extension\n    long r = 1; // hensel lifting\n    \n    // Determine a value for m\n    auto m = helib::FindM(k, L, c, p, d, 0, 0);\n    // Setup context\n    auto context = helib::Context(m, p, r);\n    // Build mod chain\n    helib::buildModChain(context, L, c);\n    \n    \n    // Generating secret key and public key\n    NTL::ZZX encryption_polynomial = context.alMod.getFactorsOverZZ()[0];\n    auto secretKey = helib::SecKey(context);\n    secretKey.GenSecKey();\n    const helib::PubKey& publicKey = secretKey;\n       \n    // Initialize ciphertexts\n    array<Ctxt, CV_SIZE> lhs_ciphertext {\n        Ctxt(publicKey),\n        Ctxt(publicKey),\n        Ctxt(publicKey)\n    }, rhs_ciphertext {\n        Ctxt(publicKey),\n        Ctxt(publicKey),\n        Ctxt(publicKey)\n    };\n    \n    // Plaintext must be encrypted as a polynomial using zzx api.\n    for (size_t i = 0; i < CV_SIZE; ++i) {\n        publicKey.Encrypt(lhs_ciphertext[i], NTL::ZZX(lhs[i]));\n        publicKey.Encrypt(rhs_ciphertext[i], NTL::ZZX(rhs[i]));\n    }\n    \n    // Apply operations on the ciphertexts.\n    // Cross product is vec a x b.\n    // 0 => ay * bz - az * by\n    // 1 => az * bx - ax * bz\n    // 2 => ax * by - ay * bx\n    \n    // Left hand side of equations\n    array<Ctxt, CV_SIZE> lhs_a = {\n        lhs_ciphertext[1], //ay\n        lhs_ciphertext[2], //az\n        lhs_ciphertext[0], //ax\n    };\n    array<Ctxt, CV_SIZE> lhs_b = {\n        rhs_ciphertext[2], //bz\n        rhs_ciphertext[0], //bx\n        rhs_ciphertext[1], //by\n    };\n    \n    // Compute first set of products\n    for (size_t i = 0; i < CV_SIZE; ++i) {\n        lhs_a[i] *= lhs_b[i];\n    }\n    \n    // Right hand side of equations\n    array<Ctxt, CV_SIZE> rhs_a = {\n        lhs_ciphertext[2], //az\n        lhs_ciphertext[0], //ax\n        lhs_ciphertext[1], //ay\n    };\n    array<Ctxt, CV_SIZE> rhs_b = {\n        rhs_ciphertext[1], //by\n        rhs_ciphertext[2], //bz\n        rhs_ciphertext[0], //bx\n    };\n    \n    // Compute second set of products\n    for (size_t i = 0; i < CV_SIZE; ++i) {\n        rhs_a[i] *= rhs_b[i];\n    }\n    \n    // Compute negation of products\n    for (size_t i = 0; i < CV_SIZE; ++i) {\n        lhs_a[i] -= rhs_a[i];\n    }\n    \n    array<Ctxt, CV_SIZE> cipher_results = lhs_a;\n    \n    // Decrypt the results using secret key and convert back from\n    // polynomial representation to numeric.\n    array<long, CV_SIZE> return_values = {0,0,0};\n    array<NTL::ZZX, CV_SIZE> plaintext_results;\n    for (size_t i = 0; i < 3; ++i) {\n        NTL::ZZX zzx;\n        secretKey.Decrypt(zzx, cipher_results[i]);\n        conv(return_values[i], zzx[0]);\n        // Compensate for negative numbers by checking if it's larger than p/2,\n        // In such case it wrapped around due to negative numbers\n        if (return_values[i] > p / 2) {\n            return_values[i] += (-1 * p);\n        }\n    }\n\n    return return_values;\n}\n\n", "meta": {"hexsha": "9d637a7757d0bda4cbf74604d6c08e652c50482c", "size": 3735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGV-Adder/Algorithms/CrossProduct/cross_product.cpp", "max_stars_repo_name": "HindrikStegenga/fhe-toolkit-macos", "max_stars_repo_head_hexsha": "6b65ac00c2a3cb64c487eadfc504eb17108ffd80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BGV-Adder/Algorithms/CrossProduct/cross_product.cpp", "max_issues_repo_name": "HindrikStegenga/fhe-toolkit-macos", "max_issues_repo_head_hexsha": "6b65ac00c2a3cb64c487eadfc504eb17108ffd80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BGV-Adder/Algorithms/CrossProduct/cross_product.cpp", "max_forks_repo_name": "HindrikStegenga/fhe-toolkit-macos", "max_forks_repo_head_hexsha": "6b65ac00c2a3cb64c487eadfc504eb17108ffd80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6428571429, "max_line_length": 94, "alphanum_fraction": 0.5852744311, "num_tokens": 1098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.628356340676277}}
{"text": "#include \"ShapeEvaluation.h\"\n#include \"EvaluationUtil.h\"\n\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMajorMatrix;\n\nnamespace shapeworks {\n\n  //---------------------------------------------------------------------------\ndouble ShapeEvaluation::ComputeCompactness(const ParticleSystem &particleSystem, const int nModes,\n                                                       const std::string &saveTo)\n{\n  const int N = particleSystem.N();\n  if (nModes > N-1){\n    throw std::invalid_argument(\"Invalid mode of variation specified\");\n  }\n  Eigen::VectorXd cumsum = ShapeEvaluation::ComputeFullCompactness(particleSystem);\n\n  if (!saveTo.empty()) {\n    std::ofstream of(saveTo);\n    of << cumsum;\n    of.close();\n  }\n\n  return cumsum(nModes - 1);\n}\n\n//---------------------------------------------------------------------------\nEigen::VectorXd ShapeEvaluation::ComputeFullCompactness(const ParticleSystem &particleSystem, std::function<void(float)> progress_callback)\n{\n  const int N = particleSystem.N();\n  const int D = particleSystem.D();\n  const int num_modes = N-1; // the number of modes is one less than the number of samples\n\n  if (num_modes < 1) {\n    return Eigen::VectorXd();\n  }\n  Eigen::MatrixXd Y = particleSystem.Particles();\n  const Eigen::VectorXd mu = Y.rowwise().mean();\n  Y.colwise() -= mu;\n\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(Y);\n  const auto S = svd.singularValues().array().pow(2) / (N * D);\n\n  // Compute cumulative sum\n  Eigen::VectorXd cumsum(num_modes);\n  cumsum(0) = S(0);\n  for (int i = 1; i < num_modes; i++) {\n    if (progress_callback) {\n      progress_callback(static_cast<float>(i) / static_cast<float>(N));\n    }\n    cumsum(i) = cumsum(i-1) + S(i);\n  }\n  cumsum /= S.sum();\n  return cumsum;\n}\n\n//---------------------------------------------------------------------------\ndouble ShapeEvaluation::ComputeGeneralization(const ParticleSystem &particleSystem, const int nModes,\n                                                          const std::string &saveTo)\n{\n  const int N = particleSystem.N();\n  const int D = particleSystem.D();\n  const Eigen::MatrixXd &P = particleSystem.Particles();\n\n  if (nModes > N-1){\n    throw std::invalid_argument(\"Invalid mode of variation specified\");\n  }\n  // Keep track of the reconstructions so we can visualize them later\n  std::vector<Reconstruction> reconstructions;\n\n  double totalDist = 0.0;\n  for (int leave = 0; leave < N; leave++) {\n\n    Eigen::MatrixXd Y(D, N - 1);\n    Y.leftCols(leave) = P.leftCols(leave);\n    Y.rightCols(N - leave - 1) = P.rightCols(N - leave - 1);\n\n    const Eigen::VectorXd mu = Y.rowwise().mean();\n    Y.colwise() -= mu;\n    const Eigen::VectorXd Ytest = P.col(leave);\n\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(Y, Eigen::ComputeFullU);\n    const auto epsi = svd.matrixU().block(0, 0, D, nModes);\n    const auto betas = epsi.transpose() * (Ytest - mu);\n    const Eigen::VectorXd rec = epsi * betas + mu;\n\n    const int numParticles = D / VDimension;\n    const Eigen::Map<const RowMajorMatrix> Ytest_reshaped(Ytest.data(), numParticles, VDimension);\n    const Eigen::Map<const RowMajorMatrix> rec_reshaped(rec.data(), numParticles, VDimension);\n    const double dist = (rec_reshaped - Ytest_reshaped).rowwise().norm().sum() / numParticles;\n    totalDist += dist;\n\n    reconstructions.push_back({dist, leave, rec_reshaped});\n  }\n  const double generalization = totalDist / N;\n\n  // Save the reconstructions if needed. Generates XML files that can be opened in\n  // ShapeWorksView2\n  if (!saveTo.empty()) {\n    SaveReconstructions(reconstructions, particleSystem.Paths(), saveTo);\n  }\n\n  return generalization;\n}\n\nEigen::VectorXd ShapeEvaluation::ComputeFullGeneralization(const ParticleSystem &particleSystem, std::function<void(float)> progress_callback)\n{\n  const int N = particleSystem.N();\n  const int D = particleSystem.D();\n  const Eigen::MatrixXd &P = particleSystem.Particles();\n\n  if (N <= 1) {\n    return Eigen::VectorXd();\n  }\n\n  Eigen::VectorXd generalizations(N-1);\n\n  Eigen::VectorXd totalDists = Eigen::VectorXd::Zero(N-1);\n\n  for (int leave = 0; leave < N; leave++) {\n    if (progress_callback) {\n      progress_callback(static_cast<float>(leave) / static_cast<float>(N));\n    }\n    Eigen::MatrixXd Y(D, N - 1);\n    Y.leftCols(leave) = P.leftCols(leave);\n    Y.rightCols(N - leave - 1) = P.rightCols(N - leave - 1);\n\n    const Eigen::VectorXd mu = Y.rowwise().mean();\n    Y.colwise() -= mu;\n    const Eigen::VectorXd Ytest = P.col(leave);\n\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(Y, Eigen::ComputeFullU);\n\n    for (int mode = 1; mode < N; mode++) {\n\n      const auto epsi = svd.matrixU().block(0, 0, D, mode);\n      const auto betas = epsi.transpose() * (Ytest - mu);\n      const Eigen::VectorXd rec = epsi * betas + mu;\n\n      const int numParticles = D / VDimension;\n      const Eigen::Map<const RowMajorMatrix> Ytest_reshaped(Ytest.data(), numParticles, VDimension);\n      const Eigen::Map<const RowMajorMatrix> rec_reshaped(rec.data(), numParticles, VDimension);\n      const double dist = (rec_reshaped - Ytest_reshaped).rowwise().norm().sum() / numParticles;\n      totalDists(mode-1) += dist;\n    }\n  }\n\n  generalizations = totalDists / N;\n\n  return generalizations;\n}\n\n//---------------------------------------------------------------------------\ndouble ShapeEvaluation::ComputeSpecificity(const ParticleSystem &particleSystem, const int nModes,\n                                                       const std::string &saveTo)\n{\n\n  const int N = particleSystem.N();\n  const int D = particleSystem.D();\n\n  if (nModes > N-1){\n    throw std::invalid_argument(\"Invalid mode of variation specified\");\n  }\n  const int nSamples = 1000;\n\n  // Keep track of the reconstructions so we can visualize them later\n  std::vector<Reconstruction> reconstructions;\n\n  Eigen::VectorXd meanSpecificity(nModes);\n  Eigen::VectorXd stdSpecificity(nModes);\n  Eigen::MatrixXd spec_store(nModes, 4);\n\n  // PCA calculations\n  const Eigen::MatrixXd &ptsModels = particleSystem.Particles();\n  const Eigen::VectorXd mu = ptsModels.rowwise().mean();\n  Eigen::MatrixXd Y = ptsModels;\n\n  Y.colwise() -= mu;\n\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(Y, Eigen::ComputeFullU);\n  const auto epsi = svd.matrixU().block(0, 0, D, nModes);\n  const auto allEigenValues = svd.singularValues();\n  const auto eigenValues = allEigenValues.head(nModes);\n\n  Eigen::MatrixXd samplingBetas(nModes, nSamples);\n  MultiVariateNormalRandom sampling{eigenValues.asDiagonal()};\n  for (int modeNumber = 0; modeNumber < nModes; modeNumber++) {\n    for (int i = 0; i < nSamples; i++) {\n      samplingBetas.col(i) = sampling();\n    }\n\n    Eigen::MatrixXd samplingPoints = (epsi * samplingBetas).colwise() + mu;\n\n    const int numParticles = D / VDimension;\n    const int nTrain = ptsModels.cols();\n\n    Eigen::VectorXd distanceToClosestTrainingSample(nSamples);\n\n    for (int i = 0; i < nSamples; i++) {\n\n      Eigen::VectorXd pts_m = samplingPoints.col(i);\n      Eigen::MatrixXd ptsDistance_vec = ptsModels.colwise() - pts_m;\n      Eigen::MatrixXd ptsDistance(Eigen::MatrixXd::Constant(1, nTrain, 0.0));\n\n      for (int j = 0; j < nTrain; j++) {\n        Eigen::Map<const RowMajorMatrix> ptsDistance_vec_reshaped(ptsDistance_vec.col(j).data(), numParticles,\n                                                                  VDimension);\n        ptsDistance(j) = (ptsDistance_vec_reshaped).rowwise().norm().sum();\n      }\n\n      int closestIdx, _r;\n      distanceToClosestTrainingSample(i) = ptsDistance.minCoeff(&_r, &closestIdx);\n\n      Eigen::Map<const RowMajorMatrix> pts_m_reshaped(pts_m.data(), numParticles, VDimension);\n      reconstructions.push_back(Reconstruction{\n              distanceToClosestTrainingSample(i),\n              (int) closestIdx,\n              pts_m_reshaped,\n      });\n    }\n\n    meanSpecificity(modeNumber) = distanceToClosestTrainingSample.mean();\n  }\n\n  if (!saveTo.empty()) {\n    SaveReconstructions(reconstructions, particleSystem.Paths(), saveTo);\n  }\n\n  const int numParticles = D / VDimension;\n  const double specificity = meanSpecificity(nModes - 1) / numParticles;\n\n  return specificity;\n}\n\n//---------------------------------------------------------------------------\nEigen::VectorXd ShapeEvaluation::ComputeFullSpecificity(const ParticleSystem &particleSystem, std::function<void(float)> progress_callback)\n{\n  const int N = particleSystem.N();\n  const int D = particleSystem.D();\n  const int numParticles = D / VDimension;\n\n  Eigen::VectorXd specificities(N-1);\n\n  // PCA calculations\n  const Eigen::MatrixXd &ptsModels = particleSystem.Particles();\n  const int nTrain = ptsModels.cols();\n\n  const Eigen::VectorXd mu = ptsModels.rowwise().mean();\n  Eigen::MatrixXd Y = ptsModels;\n  Y.colwise() -= mu;\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(Y, Eigen::ComputeFullU);\n  const auto allEigenValues = svd.singularValues();\n\n  for (int nModes=1;nModes<N;nModes++) {\n    if (progress_callback) {\n      progress_callback(static_cast<float>(nModes) / static_cast<float>(N));\n    }\n\n    const int nSamples = 1000;\n\n    Eigen::VectorXd stdSpecificity(nModes);\n    Eigen::MatrixXd spec_store(nModes, 4);\n    const auto eigenValues = allEigenValues.head(nModes);\n    const auto epsi = svd.matrixU().block(0, 0, D, nModes);\n\n\n    Eigen::MatrixXd samplingBetas(nModes, nSamples);\n    MultiVariateNormalRandom sampling{eigenValues.asDiagonal()};\n    for (int i = 0; i < nSamples; i++) {\n      samplingBetas.col(i) = sampling();\n    }\n\n    Eigen::MatrixXd samplingPoints = (epsi * samplingBetas).colwise() + mu;\n    Eigen::VectorXd distanceToClosestTrainingSample(nSamples);\n\n    for (int i = 0; i < nSamples; i++) {\n\n      Eigen::VectorXd pts_m = samplingPoints.col(i);\n      Eigen::MatrixXd ptsDistance_vec = ptsModels.colwise() - pts_m;\n      Eigen::MatrixXd ptsDistance(Eigen::MatrixXd::Constant(1, nTrain, 0.0));\n\n      for (int j = 0; j < nTrain; j++) {\n        Eigen::Map<const RowMajorMatrix> ptsDistance_vec_reshaped(ptsDistance_vec.col(j).data(), numParticles,\n                                                                  VDimension);\n        ptsDistance(j) = (ptsDistance_vec_reshaped).rowwise().norm().sum();\n      }\n\n      int closestIdx, _r;\n      distanceToClosestTrainingSample(i) = ptsDistance.minCoeff(&_r, &closestIdx);\n    }\n\n    double meanSpecificity = distanceToClosestTrainingSample.mean();\n    const double specificity = meanSpecificity / numParticles;\n    specificities(nModes-1) = specificity;\n  }\n  return specificities;\n}\n\n} // shapeworks\n\n", "meta": {"hexsha": "e4e138aa06e03f5134ef248a2711bba1344a2c75", "size": 10567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Libs/Particles/ShapeEvaluation.cpp", "max_stars_repo_name": "SCIInstitute/shapeworks", "max_stars_repo_head_hexsha": "cbd44fdeb83270179c2331f2ba8431cf7330a4ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T15:29:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-05T18:39:12.000Z", "max_issues_repo_path": "Libs/Particles/ShapeEvaluation.cpp", "max_issues_repo_name": "ben2k/ShapeWorks", "max_issues_repo_head_hexsha": "a61d2710c5592db1dc00b4fe11990e512220161f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2015-05-22T18:26:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-03T18:09:40.000Z", "max_forks_repo_path": "Libs/Particles/ShapeEvaluation.cpp", "max_forks_repo_name": "ben2k/ShapeWorks", "max_forks_repo_head_hexsha": "a61d2710c5592db1dc00b4fe11990e512220161f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-06-18T18:56:12.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-17T19:15:06.000Z", "avg_line_length": 34.6459016393, "max_line_length": 142, "alphanum_fraction": 0.6429450175, "num_tokens": 2631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6283563365674713}}
{"text": "#ifndef CANNON_ML_PIECEWISE_LSTD_H\n#define CANNON_ML_PIECEWISE_LSTD_H \n\n/*!\n * \\file cannon/ml/piecewise_lstd.hpp\n * \\brief File containing PiecewiseLSTDFilter class definition.\n */\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace ml {\n\n    /*!\n     * \\brief Class representing a Least-Squares Temporal Difference (LSTD)\n     * approximator using a feature set that produces a piecewise-affine value\n     * function approximation. This is for use in reinforcement learning algorithms.\n     */\n    class PiecewiseLSTDFilter {\n      public:\n        PiecewiseLSTDFilter() = delete;\n\n        /*!\n         * \\brief Constructor taking state space dimension, number of affine\n         * regions, and discount factor.\n         */\n        PiecewiseLSTDFilter(unsigned int in_dim, unsigned int num_refs,\n                            double discount_factor, double alpha = 1.0)\n            : in_dim_(in_dim + 1), param_dim_(in_dim_ * num_refs),\n              num_refs_(num_refs), discount_factor_(discount_factor),\n              alpha_(alpha),\n              a_inv_(MatrixXd::Identity(param_dim_, param_dim_) * alpha_),\n              b_(VectorXd::Zero(param_dim_)),\n              theta_(VectorXd::Zero(param_dim_)) {}\n\n        /*!\n         * \\brief Update this approximation in light of a single data point,\n         * which is a transition from one state to another with associated\n         * reward.\n         *\n         * \\param in_vec Feature vector for first state.\n         * \\param next_in_vec Feature vector for next state.\n         * \\param idx Region index for first state.\n         * \\param next_idx Region index for next state.\n         * \\param reward Reward associated with this state transition.\n         */\n        void process_datum(const VectorXd &in_vec, const VectorXd &next_in_vec,\n                           unsigned int idx, unsigned int next_idx,\n                           double reward);\n\n        /*!\n         * \\brief Get the matrix representing the linear portion of the local,\n         * affine approximation in the region with for the input index.\n         *\n         * \\param idx Region index\n         *\n         * \\returns Estimated local linear approximation parameter matrix.\n         */\n        VectorXd get_mat(unsigned int idx);\n\n        /*!\n         * \\brief Predict the value of the input state using the estimated\n         * piecewise-affine value function.\n         *\n         * \\param in_vec Feature vector for the state.\n         * \\param idx Region index of the state.\n         *\n         * \\returns Value function prediction.\n         */\n        double predict(const VectorXd& in_vec, unsigned int idx);\n\n        /*!\n         * \\brief Reset this value function approximation.\n         */\n        void reset();\n\n      private:\n        /*!\n         * \\brief Make internal feature vector for the input state in the\n         * region with the input index.\n         *\n         * \\param in_vec Input features for state.\n         * \\param idx Region index for the state.\n         *\n         * \\returns Internal feature representation leading to piecewise-affine\n         * function.\n         */\n        RowVectorXd make_feature_vec_(VectorXd in_vec, unsigned int idx) const;\n\n        /*!\n         * \\brief Update approximation of the linear portion of the LSTD filter\n         * given a particular state transition.\n         *\n         * \\param feat Internal feature vector of the first state.\n         * \\param next_feat Internal feature vector of the next state.\n         */\n        void update_a_inv_(const RowVectorXd& feat, const RowVectorXd& next_feat);\n\n        /*!\n         * \\brief Update approximation of the vector portion of the LSTD filter.\n         *\n         * \\param feat Internal feature vector of the first state.\n         * \\param next_feat Internal feature vector of the next state.\n         */\n        void update_b_(const RowVectorXd& feat, double reward);\n\n        /*!\n         * \\brief Update parameter vector theta, if necessary. This lazy\n         * evaluation can save time if multiple value function updates occur\n         * between predictions.\n         */\n        void check_theta_();\n\n        // Parameters\n        unsigned int in_dim_; //!< Dimension of input\n        unsigned int param_dim_; //!< Dimension of internal feature space\n        unsigned int num_refs_; //!< Number of linear regions\n        double discount_factor_; //!< Discount factor for value function\n        double alpha_; //!< L2 regularization parameter\n\n        // Matrices\n        MatrixXd a_inv_; //!< Linear portion of LSTD filter\n        VectorXd b_; //!< Vector portion of LSTD filter\n        VectorXd theta_; //!< Parameters of value function approximation\n        bool theta_updated_ = false; //!< Whether theta has been updated since last A, b update\n    };\n    \n  } // namespace ml\n} // namespace cannon\n#endif /* ifndef CANNON_ML_PIECEWISE_LSTD_H */\n", "meta": {"hexsha": "2aa45eb5782d7f52fe663b4119150edaa5203635", "size": 4918, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/ml/piecewise_lstd.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/ml/piecewise_lstd.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/ml/piecewise_lstd.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.977443609, "max_line_length": 95, "alphanum_fraction": 0.6187474583, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6283563351666668}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <cmath>\n#include <limits>\n#include <type_traits>\n#include <boost/math/ccmath/sqrt.hpp>\n#include <boost/core/lightweight_test.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n\ntemplate <typename Real>\nvoid test_mp_sqrt()\n{\n    constexpr Real tol = 2*std::numeric_limits<Real>::epsilon();\n\n    // Sqrt(2)\n    constexpr Real test_val = boost::math::ccmath::sqrt(Real(2));\n    constexpr Real sqrt2 = Real(1.4142135623730950488016887242096980785696718753769480731766797379Q);\n    constexpr Real abs_test_error = (test_val - sqrt2) > 0 ? (test_val - sqrt2) : (sqrt2 - test_val);\n    static_assert(abs_test_error < tol, \"Out of tolerance\");\n\n    // inf\n    constexpr Real test_inf = boost::math::ccmath::sqrt(std::numeric_limits<Real>::infinity());\n    static_assert(test_inf == std::numeric_limits<Real>::infinity(), \"Not infinity\");\n\n    // NAN\n    constexpr Real test_nan = boost::math::ccmath::sqrt(std::numeric_limits<Real>::quiet_NaN());\n    static_assert(test_nan, \"Not a NAN\");\n\n    // 100'000'000\n    constexpr Real test_100m = boost::math::ccmath::sqrt(100000000);\n    static_assert(test_100m == 10000, \"Incorrect\");\n}\n\n#endif\n\ntemplate <typename Real>\nvoid test_float_sqrt()\n{\n    using std::abs;\n    \n    constexpr Real tol = 2*std::numeric_limits<Real>::epsilon();\n    \n    constexpr Real test_val = boost::math::ccmath::sqrt(Real(2));\n    constexpr Real sqrt2 = Real(1.4142135623730950488016887l);\n    constexpr Real abs_test_error = (test_val - sqrt2) > 0 ? (test_val - sqrt2) : (sqrt2 - test_val);\n    static_assert(abs_test_error < tol, \"Out of tolerance\");\n\n    Real known_val = std::sqrt(Real(2));\n    BOOST_TEST(abs(test_val - known_val) < tol);\n\n    // 1000 eps\n    constexpr Real test_1000 = boost::math::ccmath::sqrt(1000*std::numeric_limits<Real>::epsilon());\n    Real known_1000 = std::sqrt(1000*std::numeric_limits<Real>::epsilon());\n    BOOST_TEST(abs(test_1000 - known_1000) < tol);\n\n    // inf\n    constexpr Real test_inf = boost::math::ccmath::sqrt(std::numeric_limits<Real>::infinity());\n    static_assert(test_inf == std::numeric_limits<Real>::infinity(), \"Not infinity\");\n\n    // NAN\n    constexpr Real test_nan = boost::math::ccmath::sqrt(std::numeric_limits<Real>::quiet_NaN());\n    static_assert(test_nan, \"Not a NAN\");\n\n    // 100'000'000\n    constexpr Real test_100m = boost::math::ccmath::sqrt(100000000);\n    static_assert(test_100m == 10000, \"Incorrect\");\n\n    // MAX / 2\n    // Only tests float since double and long double will exceed maximum template depth\n    if constexpr (std::is_same_v<float, Real>)\n    {\n        constexpr Real test_max = boost::math::ccmath::sqrt((std::numeric_limits<Real>::max)() / 2);\n        Real known_max = std::sqrt((std::numeric_limits<Real>::max)() / 2);\n        BOOST_TEST(abs(test_max - known_max) < tol);\n    }\n}\n\ntemplate <typename Z>\nvoid test_int_sqrt()\n{\n    using std::abs;\n\n    constexpr double tol = 2*std::numeric_limits<double>::epsilon();\n\n    constexpr double test_val = boost::math::ccmath::sqrt(Z(2));\n    constexpr double dummy = 1;\n    static_assert(test_val > dummy, \"Not constexpr\");\n\n    double known_val = std::sqrt(2.0);\n\n    BOOST_TEST(abs(test_val - known_val) < tol);\n}\n\n// Only test on platforms that provide BOOST_MATH_IS_CONSTANT_EVALUATED\n#ifndef BOOST_MATH_NO_CONSTEXPR_DETECTION\nint main()\n{\n    test_float_sqrt<float>();\n    test_float_sqrt<double>();\n    \n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test_float_sqrt<long double>();\n    #endif\n\n    #if defined(BOOST_HAS_FLOAT128) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\n    test_mp_sqrt<boost::multiprecision::float128>();\n    #endif\n\n    test_int_sqrt<int>();\n    test_int_sqrt<unsigned>();\n    test_int_sqrt<long>();\n    test_int_sqrt<std::int32_t>();\n    test_int_sqrt<std::int64_t>();\n    test_int_sqrt<std::uint32_t>();\n\n    return boost::report_errors();\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "47cba50463a3e46bd3ce56d524dcf391125870c8", "size": 4146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_sqrt_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/ccmath_sqrt_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/ccmath_sqrt_test.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 32.1395348837, "max_line_length": 101, "alphanum_fraction": 0.6910274964, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6283563282562515}}
{"text": "/*! \\file mesh_generator.hpp\n  \\brief Set of functions to generate points.\n  \\author Elad Steinberg\n*/\n#ifndef MESHGENERATOR_HPP\n#define MESHGENERATOR_HPP 1\n\n#ifdef _MSC_VER\n#define _USE_MATH_DEFINES\n#endif // _MSC_VER\n#include <vector>\n#include <cmath>\n#include \"../tessellation/geometry.hpp\"\n#include <algorithm>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n\n/*! \\brief Generates a cartesian mesh\n  \\param nx Number of points along the x axis\n  \\param ny Number of points along the y axis\n  \\param lower_left Lower left point\n  \\param upper_right Upper right point\n  \\return Set of two dimensional points\n*/\nstd::vector<Vector2D> cartesian_mesh(int nx, int ny,\n\t\t\t\tVector2D const& lower_left,\n\t\t\t\tVector2D const& upper_right);\n\n/*!\n  \\brief Generates a round grid with constant point density\n  \\param PointNum The number of points.\n  \\param Rmin The min radius\n  \\param Rmax The max radius\n  \\param xc X of circle center\n  \\param yc Y of circle center\n  \\param xmin Left edge of confining rectangle\n  \\param xmax Right edge of confining rectangle\n  \\param ymax Upper edge of confining rectangle\n  \\param ymin Lower edge of confining rectangle\n  \\return List of two dimensional points\n*/\nstd::vector<Vector2D> CirclePointsRmax(int PointNum,double Rmin,double Rmax,\n\tdouble xmax, double ymax, double xmin, double ymin, double xc = 0, double yc = 0);\n\n/*!\n  \\brief Generates a round grid with 1/r^2 point density confined to a rectangle given by xmin,xmax,ymin and ymax.\n  \\param PointNum The number of points.\n  \\param Rmin The min radius\n  \\param Rmax The max radius\n  \\param xc X of circle center\n  \\param yc Y of circle center\n  \\param xmin Left edge of confining rectangle\n  \\param xmax Right edge of confining rectangle\n  \\param ymax Upper edge of confining rectangle\n  \\param ymin Lower edge of confining rectangle\n  \\return List of two dimensional points\n*/\nstd::vector<Vector2D> CirclePointsRmax_2(int PointNum,double Rmin,double Rmax,\n\t\t\t\t    double xc=0,double yc=0,double xmax=1,double ymax=1,double xmin=-1,\n\t\t\t\t    double ymin=1);\n/*!\n  \\brief Generates a round grid with 1/r point density confined to a rectangle given by xmin,xmax,ymin and ymax.\n  \\param PointNum The number of points.\n  \\param Rmin The min radius\n  \\param Rmax The max radius\n  \\param xc X of circle center\n  \\param yc Y of circle center\n  \\param xmin Left edge of confining rectangle\n  \\param xmax Right edge of confining rectangle\n  \\param ymax Upper edge of confining rectangle\n  \\param ymin Lower edge of confining rectangle\n  \\return List of two dimensional points\n*/\nstd::vector<Vector2D> CirclePointsRmax_1(int PointNum,double Rmin,double Rmax,\n\t\t\t\t    double xc=0,double yc=0,double xmax=1,double ymax=1,double xmin=-1,double ymin=-1);\n\n/*!\n  \\brief Creates a circle of evenly spaced points\n  \\param point_number Number of points along the circumference\n  \\param radius Radius of the circle\n  \\param center Position of the center of the circle\n  \\return List of two dimensional points\n*/\nstd::vector<Vector2D> circle_circumference(size_t point_number,\n\t\t\t\t\t   double radius,\n\t\t\t\t\t   Vector2D const& center);\n\n/*!\n  \\brief Creates a line of evenly spaced points y=slope*x+b\n  \\param PointNum The number of points\n  \\param xmin The minimum x of the line\n  \\param xmax The maximum x of the line\n  \\param ymin The minimum y of the line\n  \\param ymax The maximum y of the line\n  \\return List of two dimensional points\n*/\nstd::vector<Vector2D> Line(int PointNum,double xmin,double xmax,double ymin,double ymax);\n\n/*!\n  \\brief Generates a round grid with r^alpha point density confined to a rectangle given by xmin,xmax,ymin and ymax.\n  \\param PointNum The number of points.\n  \\param Rmin The min radius\n  \\param Rmax The max radius\n  \\param xc X of circle center\n  \\param yc Y of circle center\n  \\param xmin Left edge of confining rectangle\n  \\param xmax Right edge of confining rectangle\n  \\param ymax Upper edge of confining rectangle\n  \\param ymin Lower edge of confining rectangle\n  \\param alpha The point density, should not be -1 or -2\n  \\return List of two dimensional points\n*/\nstd::vector<Vector2D> CirclePointsRmax_a(int PointNum,double Rmin,double Rmax,\n\t\t\t\t    double xc,double yc,double xmax,double ymax,double xmin,double ymin,\n\t\t\t\t    double alpha);\n\n/*!\n  \\brief Generates a rectangular grid with random 1/r point density\n  \\param PointNum The number of points.\n  \\param xl The left boundary\n  \\param xr The right boundary\n  \\param yd The lower boundary\n  \\param yu The upper boundary\n  \\param minR The inner radius in which there are no points\n  \\param xc The X of center of the circle\n  \\param yc The Y of center of the circle\n  \\return List of two dimensional points\n*/\nstd::vector<Vector2D> RandPointsR(int PointNum,double xl=-0.5,double xr=0.5,\n\t\t\t     double yd=-0.5,double yu=0.5,double minR=0,double xc=0,\n\t\t\t\t double yc=0);\n\n/*!\n  \\brief Generates a random rectangular grid with uniform point density and a constant seed\n  \\param PointNum The number of points.\n  \\param lowerleft The lower left point of the domain\n  \\param upperright The upper right point of the domain\n  \\return List of two dimensional points\n*/\nstd::vector<Vector2D> RandSquare(int PointNum,Vector2D const& lowerleft, Vector2D const& upperright);\n\n\n/*!\n\\brief Generates a random rectangular grid with uniform point density and a constant seed\n\\param PointNum The number of points.\n\\param xl The left boundary\n\\param xr The right boundary\n\\param yd The lower boundary\n\\param yu The upper boundary\n\\return List of two dimensional points\n*/\nstd::vector<Vector2D> RandSquare(int PointNum, double xl = -0.5, double xr = 0.5,\n\tdouble yd = -0.5, double yu = 0.5);\n\n/*!\n  \\brief Generates a random rectangular grid with uniform point density. This is when reseting the seed between calls isn't wanted\n  \\param PointNum The number of points.\n  \\param eng The random number generator\n  \\param xl The left boundary\n  \\param xr The right boundary\n  \\param yd The lower boundary\n  \\param yu The upper boundary\n  \\return List of two dimensional points\n*/\n\nstd::vector<Vector2D> RandSquare(int PointNum,boost::random::mt19937 &eng,\n\tdouble xl=-0.5,double xr=0.5,double yd=-0.5,double yu=0.5);\n\n/*!\n  \\brief Generates a random round grid with r^(1-a) point density\n  \\param PointNum The number of points.\n  \\param Rmin The min radius\n  \\param Rmax The max radius\n  \\param alpha The radial density of the points, shouldn't be 1\n  \\param lowerleft The lowerleft corner of the domain\n  \\param upperright The upperright corner of the domain\n  \\param center The center of the coordinates system\n  \\return List of two dimensional points\n*/\n\nstd::vector<Vector2D> RandPointsRa(int PointNum,double Rmin,double Rmax,double alpha,\n\tVector2D const& lowerleft,Vector2D const& upperright,Vector2D const& center=Vector2D(0,0));\n\n/*!\n  \\brief Generates a random round grid with 1/r point density\n  \\param PointNum The number of points.\n  \\param Rmin The min radius\n  \\param Rmax The max radius\n  \\param xc X of circle center\n  \\param yc Y of circle center\n  \\return List of two dimensional points\n*/\nstd::vector<Vector2D> RandPointsRmax(int PointNum,double Rmin,double Rmax,\n\t\t\t\tdouble xc=0,double yc=0);\n\n/*!\n\\brief Generates a random round grid with 1/y point density where y is the cylindrical r coordinate\n\\param PointNum The number of points.\n\\param ll The lower left point of the domain. Should be ll.y>0\n\\param ur The upper right point of the domain\n\\return List of two dimensional points\n*/\nstd::vector<Vector2D> RandPointsCylinder(int PointNum, Vector2D const& ll,Vector2D const& ur);\n\n#endif //MESHGENERATOR_HPP\n", "meta": {"hexsha": "38b24d3286eb8fb5faa00c3c5826e9efd801288e", "size": 7625, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/misc/mesh_generator.hpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/misc/mesh_generator.hpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/misc/mesh_generator.hpp", "max_forks_repo_name": "GalaxyHunters/Vivid", "max_forks_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-29T09:39:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-25T19:17:49.000Z", "avg_line_length": 37.0145631068, "max_line_length": 130, "alphanum_fraction": 0.7522622951, "num_tokens": 1959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6283476635307308}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2016, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** \\example iterative-mtl4.cpp\n*\n*   The following tutorial shows how to use the iterative solvers in ViennaCL with objects from the <a href=\"http://www.mtl4.org/\">MTL4 Library</a> directly.\n*\n*   \\note MTL4 provides iterative solvers through the ITK library. You might also want to check these.\n*\n*   We begin with including the necessary headers:\n**/\n\n// include necessary system headers\n#include <iostream>\n\n// MTL4 headers\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\n// Must be set prior to any ViennaCL includes if you want to use ViennaCL algorithms on Eigen objects\n#define VIENNACL_WITH_MTL4 1\n\n// ViennaCL includes\n#include \"viennacl/linalg/ilu.hpp\"\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/bicgstab.hpp\"\n#include \"viennacl/linalg/gmres.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n\n\n// Some helper functions for this tutorial:\n#include \"vector-io.hpp\"\n\n/**\n*  In the following we run the CG method, the BiCGStab method, and the GMRES method with MTL4 types directly.\n*  First, the matrices are set up, then the respective solvers are called.\n**/\nint main(int, char *[])\n{\n  typedef double    ScalarType;\n\n  mtl::compressed2D<ScalarType> mtl4_matrix;\n  mtl4_matrix.change_dim(65025, 65025);\n  set_to_zero(mtl4_matrix);\n\n  mtl::dense_vector<ScalarType> mtl4_rhs(65025, 1.0);\n  mtl::dense_vector<ScalarType> mtl4_result(65025, 0.0);\n  mtl::dense_vector<ScalarType> mtl4_residual(65025, 0.0);\n\n  /**\n  * Read system from file\n  **/\n\n  mtl::io::matrix_market_istream(\"../examples/testdata/mat65k.mtx\") >> mtl4_matrix;\n\n  /**\n  *  Conjugate Gradient (CG) solver:\n  **/\n  std::cout << \"----- Running CG -----\" << std::endl;\n  mtl4_result = viennacl::linalg::solve(mtl4_matrix, mtl4_rhs, viennacl::linalg::cg_tag());\n\n  mtl4_residual = mtl4_matrix * mtl4_result - mtl4_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(mtl4_residual) / viennacl::linalg::norm_2(mtl4_rhs) << std::endl;\n\n  /**\n  *  Stabilized Bi-Conjugate Gradient (BiCGStab) solver:\n  **/\n  std::cout << \"----- Running BiCGStab -----\" << std::endl;\n  mtl4_result = viennacl::linalg::solve(mtl4_matrix, mtl4_rhs, viennacl::linalg::bicgstab_tag());\n\n  mtl4_residual = mtl4_matrix * mtl4_result - mtl4_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(mtl4_residual) / viennacl::linalg::norm_2(mtl4_rhs) << std::endl;\n\n  /**\n  *  Generalized Minimum Residual (GMRES) solver:\n  **/\n  std::cout << \"----- Running GMRES -----\" << std::endl;\n  mtl4_result = viennacl::linalg::solve(mtl4_matrix, mtl4_rhs, viennacl::linalg::gmres_tag());\n\n  mtl4_residual = mtl4_matrix * mtl4_result - mtl4_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(mtl4_residual) / viennacl::linalg::norm_2(mtl4_rhs) << std::endl;\n\n  /**\n  *   That's it. Print a success message and exit.\n  **/\n  std::cout << std::endl;\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n  std::cout << std::endl;\n}\n\n", "meta": {"hexsha": "98a97059baea900aaaf6c20bbf915a4278a77ce0", "size": 3737, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/iterative-mtl4.cpp", "max_stars_repo_name": "yuchengs/viennacl-dev", "max_stars_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 224.0, "max_stars_repo_stars_event_min_datetime": "2015-02-15T21:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:27:03.000Z", "max_issues_repo_path": "examples/tutorial/iterative-mtl4.cpp", "max_issues_repo_name": "yuchengs/viennacl-dev", "max_issues_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 189.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T17:08:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T06:23:22.000Z", "max_forks_repo_path": "examples/tutorial/iterative-mtl4.cpp", "max_forks_repo_name": "yuchengs/viennacl-dev", "max_forks_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 84.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T14:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T14:51:17.000Z", "avg_line_length": 35.5904761905, "max_line_length": 157, "alphanum_fraction": 0.6395504415, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6282970445068745}}
{"text": "#define BOOST_TEST_MODULE \"test_potential_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/forcefield/local/CosinePotential.hpp>\n#include <mjolnir/math/constants.hpp>\n\nBOOST_AUTO_TEST_CASE(CosinePotential_double)\n{\n    using real_type = double;\n    constexpr std::size_t N = 1000;\n    constexpr real_type   h = 1e-6;\n    constexpr real_type   pi = mjolnir::math::constants<real_type>::pi();\n    const real_type    k = 2.0;\n    const std::int32_t n = 2;\n    const real_type   v0 = 3.0;\n\n    mjolnir::CosinePotential<real_type> potential(k, n, v0);\n\n    const real_type x_min = -pi;\n    const real_type x_max =  pi;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + dx * i;\n        const real_type pot1 = potential.potential(x + h);\n        const real_type pot2 = potential.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = potential.derivative(x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(CosinePotential_float)\n{\n    using real_type = float;\n    constexpr std::size_t N = 100;\n    constexpr real_type   h = 1e-3;\n    constexpr real_type   pi = mjolnir::math::constants<real_type>::pi();\n    const real_type    k = 2.0;\n    const std::int32_t n = 2;\n    const real_type   v0 = 3.0;\n\n    mjolnir::CosinePotential<real_type> potential(k, n, v0);\n\n    const real_type x_min = -2 * pi;\n    const real_type x_max =  2 * pi;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + dx * i;\n        const real_type pot1 = potential.potential(x + h);\n        const real_type pot2 = potential.potential(x - h);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = potential.derivative(x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n    }\n}\n", "meta": {"hexsha": "398693c1531d6727328fc605a5e10524ce7d549d", "size": 2051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_cosine_potential.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/core/test_cosine_potential.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_cosine_potential.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6119402985, "max_line_length": 73, "alphanum_fraction": 0.6416382253, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6282970440871185}}
{"text": "#include <iostream>\n#include <sstream>\n#include <assert.h>\n#include <math.h>\n#include <cmath>\n#include <iomanip>\n#include \"../flt.hpp\"\n#include <boost/algorithm/string.hpp>\n\nusing namespace epilog::pow;\n\nstatic void header( const std::string &str )\n{\n    std::cout << \"\\n\";\n    std::cout << \"--- [\" + str + \"] \" + std::string(60 - str.length(), '-') << \"\\n\";\n    std::cout << \"\\n\";\n}\n\nstatic bool tol_check(double d, flt1648 v, double tol=0.00001)\n{\n    double vd = v.to_double();\n    assert((d < 0) == (vd < 0));\n    if (vd == d) {\n\treturn true;\n    }\n    double rel = fabs(0.5 - fabs(vd) / (fabs(d)+fabs(vd)));\n    assert(rel < tol);\n    return true;\n}\n\nconst size_t N = 10;\nconst double db[N] = { 2.3e-7, 2.134e+10, -5.91352e+5, 2.12345e-3, 2e+256,\n\t\t       123.456e-127, 42e-42, -99e+42, -5e-17, -4.321e+19 };\nflt1648 fl[N];\n\nclass next_count {\npublic:\n    friend std::ostream & operator << (std::ostream &out, const next_count &nc);\n};\n\nstatic int cnt = 0;\n\ninline std::ostream & operator << (std::ostream &out, const next_count &nc) {\n    cnt++;\n    out << \"[\" << cnt << \"]: \";\n    return out;\n}\n\nstatic void test_flt_init()\n{\n    std::cout.precision(17);\n\n    for (size_t i = 0; i < N; i++) {\n\tint exp = 0;\n\tdouble frac = frexp(db[i], &exp);\n\tfl[i] = flt1648( exp, fxp1648(frac));\n\tstd::cout << next_count() << \"db[\" << i << \"]=\" << db[i] << std::endl;\n\tstd::cout << next_count() << \"fl[\" << i << \"]=\" << fl[i] << std::endl;\n\ttol_check(db[i], fl[i]);\n    }\n}\n\nstatic void test_flt_add()\n{\n    header(\"test_flt_add\");\n\n    for (size_t i = 0; i < N; i++) {\n\tfor (size_t j = 0; j < N; j++) {\n\t    double ad = db[i], bd = db[j];\n\t    flt1648 af = fl[i], bf = fl[j];\n\t    std::cout << next_count() << ad << \"+\" << bd << \"=\" << (ad+bd) << std::endl;\n\t    std::cout << next_count() << af << \"+\" << bf << \"=\" << (af+bf) << std::endl;\n\t    tol_check((ad+bd), (af+bf));\n\t}\n    }\n}\n\n\nstatic void test_flt_sub()\n{\n    header(\"test_flt_sub\");\n\n    for (size_t i = 0; i < N; i++) {\n\tfor (size_t j = 0; j < N; j++) {\n\t    double ad = db[i], bd = db[j];\n\t    flt1648 af = fl[i], bf = fl[j];\n\t    std::cout << next_count() << ad << \"-\" << bd << \"=\" << (ad-bd) << std::endl;\n\t    std::cout << next_count() << af << \"-\" << bf << \"=\" << (af-bf) << std::endl;\n\t    tol_check((ad-bd), (af-bf));\n\t}\n    }\n}\n\nstatic void test_flt_mul()\n{\n    header(\"test_flt_mul\");\n\n    for (size_t i = 0; i < N; i++) {\n\tfor (size_t j = 0; j < N; j++) {\n\t    double ad = db[i], bd = db[j];\n\t    flt1648 af = fl[i], bf = fl[j];\n\t    std::cout << next_count() << ad << \"*\" << bd << \"=\" << (ad*bd) << std::endl;\n\t    std::cout << next_count() << af << \"*\" << bf << \"=\" << (af*bf) << std::endl;\n\t    tol_check((ad*bd), (af*bf));\n\t}\n    }\n}\n\nstatic void test_flt_div()\n{\n    header(\"test_flt_div\");\n\n    for (size_t i = 0; i < N; i++) {\n\tfor (size_t j = 0; j < N; j++) {\n\t    double ad = db[i], bd = db[j];\n\t    flt1648 af = fl[i], bf = fl[j];\n\t    std::cout << next_count() << ad << \"/\" << bd << \"=\" << (ad/bd) << std::endl;\n\t    std::cout << next_count() << af << \"/\" << bf << \"=\" << (af/bf) << std::endl;\n\t    tol_check((ad/bd), (af/bf));\n\t}\n    }\n}\n\nstatic void test_flt_reciprocal()\n{\n    header(\"test_flt_reciprocal\");\n\n    for (size_t i = 0; i < N; i++) {\n\tdouble ad = db[i];\n\tflt1648 af = fl[i];\n\tdouble ad_reciprocal = 1.0 / ad;\n\tflt1648 af_reciprocal = af.reciprocal();\n\tstd::cout << next_count() << ad << \" reciprocal=\" << ad_reciprocal << std::endl;\n\tstd::cout << next_count() << af << \" reciprocal=\" << af_reciprocal << std::endl;\n\ttol_check(ad_reciprocal, af_reciprocal);\n    }\n}\n\nstatic void test_flt_values()\n{\n    header(\"test_flt_values\");\n\n    auto v = flt1648::from(12, 1234567);\n\n    std::cout << \"VALUE: \" << v.to_double() << std::endl;\n\n    tol_check(12.1234567, v);\n}\n\nstatic void test_bitcoin_difficulty()\n{\n    header(\"test_bitcoin_difficulty\");\n\n    auto base_value = flt1648(0x0404cb);\n    auto mult_value = flt1648(1) << (8*(0x1b - 3));\n    auto target_value = base_value * mult_value;\n    std::string expect = \"0x00000000000404CB000000000000000000000000000000000000000000000000\";\n    auto target = \"0x\" + boost::to_upper_copy(target_value.to_integer_string(32));\n    std::cout << \"TARGET: \" << target << std::endl;\n    std::cout << \"EXPECT: \" << expect << std::endl;\n    assert( expect == target );\n\n    auto max_value = flt1648(0x00ffff) * (flt1648(1) << (8*(0x1d - 3)));\n    auto difficulty = max_value / target_value;\n    std::cout << \"Difficulty: \" << difficulty.to_double() << std::endl;\n    std::cout << \"Expect    : 16307.42...\" << std::endl;\n\n    assert(abs(difficulty.to_double() - 16307.42) < 0.01);\n}\n\nstatic void test_our_difficulty()\n{\n    header(\"test_out_difficulty\");\n\n    auto base_value = flt1648(16307) << 32;\n    auto target_value = flt1648(1) / base_value;\n    auto difficulty = flt1648(1) - target_value;\n\n    std::cout << \"DIFFICULTY: \" << difficulty.to_double() << std::endl;\n\n    auto rel_target = flt1648(1) - difficulty;\n\n    std::cout << \"REL TARGET: \" << rel_target.to_double() << std::endl;\n    \n    auto max_target = flt1648(1) << 256;\n    auto target = rel_target * max_target;\n\n    std::cout << \"TARGET    : \" << target.to_double() << std::endl;\n\n    std::cout << \"TARGET INT: 0x\" << target.to_integer_string(32) << std::endl;\n}\n\nint main(int argc, char *argv[])\n{\n    test_flt_init();\n    test_flt_add();\n    test_flt_sub();\n    test_flt_mul();\n    test_flt_div();\n    test_flt_reciprocal();\n    test_flt_values();\n    test_bitcoin_difficulty();\n    test_our_difficulty();\n\n    return 0;\n}\n\n", "meta": {"hexsha": "590d5424482802b9406eec4d520ac34b1337a634", "size": 5517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pow/test/test_flt.cpp", "max_stars_repo_name": "datavetaren/epilog", "max_stars_repo_head_hexsha": "7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pow/test/test_flt.cpp", "max_issues_repo_name": "datavetaren/epilog", "max_issues_repo_head_hexsha": "7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pow/test/test_flt.cpp", "max_forks_repo_name": "datavetaren/epilog", "max_forks_repo_head_hexsha": "7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820", "max_forks_repo_licenses": ["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.5240384615, "max_line_length": 94, "alphanum_fraction": 0.5560993293, "num_tokens": 1833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6282970440871184}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Array3d v(M_PI, M_PI/2, M_PI/3);\ncout << v.cos() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "fa85f41e2ae4743981cd7fc1544d0f462f61513a", "size": 209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Cwise_cos.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_Cwise_cos.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_Cwise_cos.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.9333333333, "max_line_length": 34, "alphanum_fraction": 0.6555023923, "num_tokens": 64, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6282970391085836}}
{"text": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/utility.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/mtl/operation/svd.hpp>\n\nusing namespace std;\nint main(int, char**)\n{\n    using namespace mtl;\n    unsigned size=3, row= size, col=size+1;\n\n    double normA(0), tol(0.0000001);\n    dense_vector<double>                    vec(size), vec1(size);\n    dense2D<double>                         A(row, col), A_t(row, col), S(row, row), V(row, col), D(col,col), norm(row, col),\n\t\t\t\t\t    AT(col,row), A_tT(col,row), ST(col, col), VT(col,row), DT(row,row), normT(col, row);\n    A= 0;\n\n    A[0][0]=1;    A[0][1]=1;    A[0][2]=1; \n    A[1][0]=1;    A[1][1]=2;    A[1][2]=2;\n    A[2][0]=9;    A[2][1]=3;    A[2][2]=2;\n    A[2][3]=4;    A[0][3]=4;    A[1][3]=3;\n    std::cout<<\"A=\\n\"<< A <<\"\\n\";\n    AT= trans(A);\n    std::cout<<\"START--------------\\n\";\n\n    boost::tie(S, V, D)= svd(A, tol);\n    std::cout<<\"MAtrix  S=\\n\"<< S <<\"\\n\";\n    std::cout<<\"MAtrix  V=\\n\"<< V <<\"\\n\";\n    std::cout<<\"MAtrix  D=\\n\"<< D <<\"\\n\";\n    A_t= S*V*trans(D);\n    std::cout<<\"MAtrix  A=S*V*D'=\\n\"<< A_t <<\"\\n\";\n    std::cout<<\"Original A==\\n\"<< A <<\"\\n\";\n    norm= A_t - A;\n    normA= one_norm(norm);\n    std::cout<< \"norm(SVD-A)=\" << normA << \"\\n\";\n//     if (normA > size*size*tol) throw mtl::logic_error(\"wrong SVD decomposition of matrix A\");\n    std::cout<<\"START--------------\\n\";\n#if 1\n    boost::tie(ST, VT, DT)= svd(AT, tol);\n    std::cout<<\"MAtrix  ST=\\n\"<< ST <<\"\\n\";\n    std::cout<<\"MAtrix  VT=\\n\"<< VT <<\"\\n\";\n    std::cout<<\"MAtrix  DT=\\n\"<< DT <<\"\\n\";\n    A_tT= ST*VT*trans(DT);\n    std::cout<<\"MAtrix  AT=S*V*D'=\\n\"<< A_tT <<\"\\n\";\n    std::cout<<\"Original A==\\n\"<< AT <<\"\\n\";\n    normT= A_tT - AT;\n    normA= one_norm(normT);\n    std::cout<< \"norm(SVD-A)=\" << normA << \"\\n\";\n#endif\n    return 0;\n}\n\n", "meta": {"hexsha": "a48da216898135594ec41591341b9e5bbcb01ef6", "size": 2233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/svd_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/svd_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/svd_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 34.3538461538, "max_line_length": 125, "alphanum_fraction": 0.5333631885, "num_tokens": 780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6282941297145659}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace std;\n    \n    double aa[2][2]= {{1., 2.},\n\t\t      {3., 4.}};\n    mtl::dense2D<double> A(aa), B(2,2);\n    B = A*A;\n    \n    cout << (A*A) << endl << B << endl;\n    \n    MTL_THROW_IF(B(0, 1) != (A*A)(0,1), mtl::runtime_error(\"Wrong value in matrix product expression!\\n\"));\n\n    return 0;\n}\n", "meta": {"hexsha": "eee025bd351f8376a0ed7168c87cc9f1a48dc01b", "size": 835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/print_matrix_product_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/print_matrix_product_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/print_matrix_product_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 26.935483871, "max_line_length": 107, "alphanum_fraction": 0.6203592814, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6282941142666053}}
{"text": "/* Boost test/pi.cpp\r\n * test if the pi constant is correctly defined\r\n *\r\n * Copyright Guillaume Melquiond, Sylvain Pion 2002-2003\r\n * Permission to use, copy, modify, sell, and distribute this software\r\n * is hereby granted without fee provided that the above copyright notice\r\n * appears in all copies and that both that copyright notice and this\r\n * permission notice appear in supporting documentation.\r\n *\r\n * None of the above authors nor Polytechnic University make any\r\n * representation about the suitability of this software for any\r\n * purpose. It is provided \"as is\" without express or implied warranty.\r\n *\r\n * $Id: pi.cpp,v 1.3 2003/02/05 17:34:36 gmelquio Exp $\r\n */\r\n\r\n#include <boost/numeric/interval.hpp>\r\n#include <boost/limits.hpp>\r\n#include <boost/test/minimal.hpp>\r\n\r\n#define PI 3.14159265358979323846\r\n\r\ntypedef boost::numeric::interval<int>         I_i;\r\ntypedef boost::numeric::interval<float>       I_f;\r\ntypedef boost::numeric::interval<double>      I_d;\r\ntypedef boost::numeric::interval<long double> I_ld;\r\n\r\nusing boost::numeric::interval_lib::pi;\r\nusing boost::numeric::interval_lib::pi_half;\r\nusing boost::numeric::interval_lib::pi_twice;\r\n\r\nint test_main(int, char *[]) {\r\n  I_i  pi_i  = pi<I_i>();\r\n  I_f  pi_f  = pi<I_f>();\r\n  I_d  pi_d  = pi<I_d>();\r\n  I_ld pi_ld = pi<I_ld>();\r\n\r\n  BOOST_TEST(in((int)   PI, pi_i));\r\n  BOOST_TEST(in((float) PI, pi_f));\r\n  BOOST_TEST(in((double)PI, pi_d));\r\n  BOOST_TEST(subset(pi_i, widen(I_i((int)   PI), 1)));\r\n  BOOST_TEST(subset(pi_f, widen(I_f((float) PI), std::numeric_limits<float> ::min())));\r\n  BOOST_TEST(subset(pi_d, widen(I_d((double)PI), std::numeric_limits<double>::min())));\r\n\r\n  // We can't test the following equalities for interval<int>.\r\n  I_f pi_f_half = pi_half<I_f>();\r\n  I_f pi_f_twice = pi_twice<I_f>();\r\n\r\n  I_d pi_d_half = pi_half<I_d>();\r\n  I_d pi_d_twice = pi_twice<I_d>();\r\n\r\n  I_ld pi_ld_half = pi_half<I_ld>();\r\n  I_ld pi_ld_twice = pi_twice<I_ld>();\r\n\r\n  BOOST_TEST(equal(2.0f * pi_f_half, pi_f));\r\n  BOOST_TEST(equal(2.0  * pi_d_half, pi_d));\r\n  BOOST_TEST(equal(2.0l * pi_ld_half, pi_ld));\r\n\r\n  BOOST_TEST(equal(2.0f * pi_f, pi_f_twice));\r\n  BOOST_TEST(equal(2.0  * pi_d, pi_d_twice));\r\n  BOOST_TEST(equal(2.0l * pi_ld, pi_ld_twice));\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "6a6f013b48fcff8dd4598a76d97e7bcf0349aad9", "size": 2260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/test/pi.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/test/pi.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/numeric/interval/test/pi.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7692307692, "max_line_length": 88, "alphanum_fraction": 0.6831858407, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6282790604325195}}
{"text": "//---------------------------------------------------------------------------//\r\n// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>\r\n//\r\n// Distributed under the Boost Software License, Version 1.0\r\n// See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt\r\n//\r\n// See http://boostorg.github.com/compute for more information.\r\n//---------------------------------------------------------------------------//\r\n\r\n#define _USE_MATH_DEFINES\r\n#include <algorithm>\r\n#include <iostream>\r\n#include <vector>\r\n\r\n#include <boost/compute/system.hpp>\r\n#include <boost/compute/algorithm/copy.hpp>\r\n#include <boost/compute/algorithm/copy_n.hpp>\r\n#include <boost/compute/algorithm/transform.hpp>\r\n#include <boost/compute/container/vector.hpp>\r\n\r\n#include \"perf.hpp\"\r\n\r\nnamespace compute = boost::compute;\r\n\r\nusing compute::float2_;\r\n\r\nfloat rand_float()\r\n{\r\n    return (float(rand()) / float(RAND_MAX)) * 1000.f;\r\n}\r\n\r\nvoid serial_cartesian_to_polar(const float *input, size_t n, float *output)\r\n{\r\n    for(size_t i = 0; i < n; i++){\r\n        float x = input[i*2+0];\r\n        float y = input[i*2+1];\r\n\r\n        float magnitude = std::sqrt(x*x + y*y);\r\n        float angle = std::atan2(y, x) * 180.f / M_PI;\r\n\r\n        output[i*2+0] = magnitude;\r\n        output[i*2+1] = angle;\r\n    }\r\n}\r\n\r\nvoid serial_polar_to_cartesian(const float *input, size_t n, float *output)\r\n{\r\n    for(size_t i = 0; i < n; i++){\r\n        float magnitude = input[i*2+0];\r\n        float angle = input[i*2+1];\r\n\r\n        float x = magnitude * cos(angle);\r\n        float y = magnitude * sin(angle);\r\n\r\n        output[i*2+0] = x;\r\n        output[i*2+1] = y;\r\n    }\r\n}\r\n\r\n// converts from cartesian coordinates (x, y) to polar coordinates (magnitude, angle)\r\nBOOST_COMPUTE_FUNCTION(float2_, cartesian_to_polar, (float2_ p),\r\n{\r\n    float x = p.x;\r\n    float y = p.y;\r\n\r\n    float magnitude = sqrt(x*x + y*y);\r\n    float angle = atan2(y, x) * 180.f / M_PI;\r\n\r\n    return (float2)(magnitude, angle);\r\n});\r\n\r\n// converts from polar coordinates (magnitude, angle) to cartesian coordinates (x, y)\r\nBOOST_COMPUTE_FUNCTION(float2_, polar_to_cartesian, (float2_ p),\r\n{\r\n    float magnitude = p.x;\r\n    float angle = p.y;\r\n\r\n    float x = magnitude * cos(angle);\r\n    float y = magnitude * sin(angle);\r\n\r\n    return (float2)(x, y)\r\n});\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n    perf_parse_args(argc, argv);\r\n\r\n    std::cout << \"size: \" << PERF_N << std::endl;\r\n\r\n    // setup context and queue for the default device\r\n    compute::device device = compute::system::default_device();\r\n    compute::context context(device);\r\n    compute::command_queue queue(context, device);\r\n    std::cout << \"device: \" << device.name() << std::endl;\r\n\r\n    // create vector of random numbers on the host\r\n    std::vector<float> host_vector(PERF_N*2);\r\n    std::generate(host_vector.begin(), host_vector.end(), rand_float);\r\n\r\n    // create vector on the device and copy the data\r\n    compute::vector<float2_> device_vector(PERF_N, context);\r\n    compute::copy_n(\r\n        reinterpret_cast<float2_ *>(&host_vector[0]),\r\n        PERF_N,\r\n        device_vector.begin(),\r\n        queue\r\n    );\r\n\r\n    perf_timer t;\r\n    for(size_t trial = 0; trial < PERF_TRIALS; trial++){\r\n        t.start();\r\n        compute::transform(\r\n            device_vector.begin(),\r\n            device_vector.end(),\r\n            device_vector.begin(),\r\n            cartesian_to_polar,\r\n            queue\r\n        );\r\n        queue.finish();\r\n        t.stop();\r\n    }\r\n    std::cout << \"time: \" << t.min_time() / 1e6 << \" ms\" << std::endl;\r\n\r\n    // perform saxpy on host\r\n    t.clear();\r\n    for(size_t trial = 0; trial < PERF_TRIALS; trial++){\r\n        t.start();\r\n        serial_cartesian_to_polar(&host_vector[0], PERF_N, &host_vector[0]);\r\n        t.stop();\r\n    }\r\n    std::cout << \"host time: \" << t.min_time() / 1e6 << \" ms\" << std::endl;\r\n\r\n    std::vector<float> device_data(PERF_N*2);\r\n    compute::copy(\r\n        device_vector.begin(),\r\n        device_vector.end(),\r\n        reinterpret_cast<float2_ *>(&device_data[0]),\r\n        queue\r\n    );\r\n\r\n    for(size_t i = 0; i < PERF_N; i++){\r\n        float host_value = host_vector[i];\r\n        float device_value = device_data[i];\r\n\r\n        if(std::abs(device_value - host_value) > 1e-3){\r\n            std::cout << \"ERROR: \"\r\n                      << \"value at \" << i << \" \"\r\n                      << \"device_value (\" << device_value << \") \"\r\n                      << \"!= \"\r\n                      << \"host_value (\" << host_value << \")\"\r\n                      << std::endl;\r\n            return -1;\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "2d36bda809d9928b11bfc6a1529f420c73d11368", "size": 4640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/perf/perf_cart_to_polar.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/perf/perf_cart_to_polar.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/compute/perf/perf_cart_to_polar.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 29.1823899371, "max_line_length": 86, "alphanum_fraction": 0.5484913793, "num_tokens": 1140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6281070098452647}}
{"text": "#include <map>\n#include <string>\n#include <vector>\n#include <iostream>\n#include <Eigen/Dense>\n#include \"../include/two_layer_net.h\"\n#include \"../datasets/include/mnist.h\"\n#include \"../matplotlibcpp.h\"\n\nusing namespace Eigen;\nnamespace plt = matplotlibcpp;\n\nint main()\n{\n    using std::cout;\n    using std::endl;\n    using std::map;\n    using std::vector;\n    using std::string;\n    using namespace MyDL;\n\n    // \u30cf\u30a4\u30d1\u30fc\u30d1\u30e9\u30e1\u30fc\u30bf\n    int num_iters = 3000;\n    double learning_rate = 0.05;\n    int batch_size = 100;\n    int input_size = 28 * 28;\n    int hidden_size = 100;\n    int output_size = 10;\n\n    // MNIST\u30c7\u30fc\u30bf\u30ed\u30fc\u30c0\n    MnistEigenDataset mnist(batch_size);\n\n    // \u5404\u7a2e\u5909\u6570\u521d\u671f\u5316\n    MatrixXd train_X = MatrixXd::Zero(batch_size, input_size);\n    MatrixXd train_y = MatrixXd::Zero(batch_size, output_size);\n    MatrixXd test_X = MatrixXd::Zero(batch_size, input_size);\n    MatrixXd test_y = MatrixXd::Zero(batch_size, output_size);\n    bool one_hot_label = true;\n\n    // \u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u751f\u6210\n    TwoLayerNet net(input_size, hidden_size, output_size, 0.01);\n\n    // \u6700\u9069\u5316\u7528\n    map<string, MatrixXd> grads;\n    double loss;\n    double accuracy;\n\n    // \u5b66\u7fd2\u7d4c\u904e\u30d7\u30ed\u30c3\u30c8\u7528\n    vector<double> loss_history(num_iters);\n    vector<int> plot_counter(num_iters);\n    vector<double> accuracy_history(num_iters / 10);\n    vector<int> accuracy_counter(num_iters / 10);\n\n    // \u6700\u9069\u5316\u5b9f\u884c\n    for (int i = 0; i < num_iters; i++){\n        // \u6b21\u306e\u30df\u30cb\u30d0\u30c3\u30c1\u53d6\u5f97\n        mnist.next_train(train_X, train_y, one_hot_label);\n        \n        // \u52fe\u914d\u8a08\u7b97\n        grads = net.gradient(train_X, train_y); // \u5185\u90e8\u3067\n        \n        // \u52fe\u914d\u66f4\u65b0\n        for (auto i = grads.begin(); i != grads.end(); i++){\n            net.params[i->first] -= learning_rate * grads[i->first];\n        }\n\n        // \u640d\u5931\u30d7\u30ed\u30c3\u30c8\u7528\n        loss = net.loss(train_X, train_y);\n        loss_history[i] = loss;\n        plot_counter[i] = i;\n\n        cout << \"iteration\" << i << \" loss: \" << loss << endl;\n\n        // 10step\u6bce\u306baccuracy\u8a08\u6e2c\n        if (i % 10 == 0){\n            mnist.next_test(test_X, test_y, one_hot_label);\n            accuracy = net.accuracy(test_X, test_y);\n\n            cout << \"accuracy: \" << accuracy << endl;\n\n            accuracy_history[i/10] = accuracy;\n            accuracy_counter[i/10] = i / 10;\n        }\n    }\n\n    // visualize\n    plt::title(\"Loss History\");\n    plt::plot(plot_counter, loss_history, \"b\");\n    plt::grid(true);\n    plt::save(\"mnist_learning_curve.png\");\n\n    plt::cla();\n    plt::title(\"Accuracy History\");\n    plt::plot(accuracy_counter, accuracy_history, \"r\");\n    plt::grid(true);\n    plt::save(\"mnist_accuracy_plot.png\");\n\n    return 0;\n}", "meta": {"hexsha": "3658130935a241aeb1ab8c2254b677d14bc75292", "size": 2574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main/train_mnist_two_layer_net.cpp", "max_stars_repo_name": "potedo/MNIST_loader_sample", "max_stars_repo_head_hexsha": "6c6723c8c20e05ecc093a04fa045d20a73dd04f8", "max_stars_repo_licenses": ["MIT"], "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/train_mnist_two_layer_net.cpp", "max_issues_repo_name": "potedo/MNIST_loader_sample", "max_issues_repo_head_hexsha": "6c6723c8c20e05ecc093a04fa045d20a73dd04f8", "max_issues_repo_licenses": ["MIT"], "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/train_mnist_two_layer_net.cpp", "max_forks_repo_name": "potedo/MNIST_loader_sample", "max_forks_repo_head_hexsha": "6c6723c8c20e05ecc093a04fa045d20a73dd04f8", "max_forks_repo_licenses": ["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": 68, "alphanum_fraction": 0.6056721057, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6281070092919278}}
{"text": "#include \"drake/math/autodiff.h\"\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"drake/common/autodiff.h\"\n#include \"drake/common/eigen_types.h\"\n#include \"drake/common/test_utilities/eigen_matrix_compare.h\"\n#include \"drake/common/test_utilities/expect_no_throw.h\"\n#include \"drake/math/autodiff_gradient.h\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\nusing Eigen::AutoDiffScalar;\n\nnamespace drake {\nnamespace math {\nnamespace {\n\nclass AutodiffTest : public ::testing::Test {\n protected:\n  typedef Eigen::AutoDiffScalar<VectorXd> Scalar;\n\n  void SetUp() override {\n    vec_.resize(2);\n\n    // Set up to evaluate the derivatives at the values v0 and v1.\n    vec_[0].value() = v0_;\n    vec_[1].value() = v1_;\n\n    // Provide enough room for differentiation with respect to both variables.\n    vec_[0].derivatives().resize(2);\n    vec_[1].derivatives().resize(2);\n\n    // Herein, the shorthand notation is used: v0 = vec_[0] and v1 = vec_[1].\n    // Set partial of v0 with respect to v0 (itself) to 1 (\u2202v0/\u2202v0 = 1).\n    // Set partial of v0 with respect to v1 to 0 (\u2202v0/\u2202v1 = 0).\n    vec_[0].derivatives()(0) = 1.0;\n    vec_[0].derivatives()(1) = 0.0;\n\n    // Set partial of v1 with respect to v0 to 0 (\u2202v1/\u2202v0 = 0).\n    // Set partial of v1 with respect to v1 (itself) to 1 (\u2202v1/\u2202v1 = 1).\n    vec_[1].derivatives()(0) = 0.0;\n    vec_[1].derivatives()(1) = 1.0;\n\n    // Do a calculation that is a function of variables v0 and v1.\n    output_calculation_ = DoMath(vec_);\n  }\n\n  // Do a calculation involving real functions of two real variables. These\n  // functions were chosen due to ease of differentiation.\n  static VectorX<Scalar> DoMath(const VectorX<Scalar>& v) {\n    VectorX<Scalar> output(3);\n    // Shorthand notation: Denote v0 = v[0], v1 = v[1].\n    // Function 0: y0 = cos(v0) + sin(v0) * cos(v0) / v1\n    // Function 1: y1 = sin(v0) + v1.\n    // Function 2: y2 = v0^2 + v1^3.\n    output[0] = cos(v[0]) + sin(v[0]) * cos(v[0]) / v[1];\n    output[1] = sin(v[0]) + v[1];\n    output[2] = v[0] * v[0] + v[1] * v[1] * v[1];\n    return output;\n  }\n\n  VectorX<Scalar> vec_;                 // Array of variables.\n  VectorX<Scalar> output_calculation_;  // Functions that depend on variables.\n\n  // Arbitrary values 7 and 9 will be used as test data.\n  const double v0_ = 7.0;\n  const double v1_ = 9.0;\n};\n\n// Tests that ToValueMatrix extracts the values from the autodiff.\nTEST_F(AutodiffTest, ToValueMatrix) {\n  const VectorXd values = autoDiffToValueMatrix(output_calculation_);\n  VectorXd expected(3);\n  expected[0] = cos(v0_) + sin(v0_) * cos(v0_) / v1_;\n  expected[1] = sin(v0_) + v1_;\n  expected[2] = v0_ * v0_ + v1_ * v1_ * v1_;\n  EXPECT_TRUE(\n      CompareMatrices(expected, values, 1e-10, MatrixCompareType::absolute))\n      << values;\n}\n\n// Tests that ToGradientMatrix extracts the gradients from the autodiff.\nTEST_F(AutodiffTest, ToGradientMatrix) {\n  MatrixXd gradients = autoDiffToGradientMatrix(output_calculation_);\n\n  MatrixXd expected(3, 2);\n  // Shorthand notation: Denote v0 = vec_[0], v1 = vec_[1].\n  // Function 0: y0 = cos(v0) + sin(v0) * cos(v0) / v1\n  // Function 1: y1 = sin(v0) + v1.\n  // Function 2: y2 = v0^2 + v1^3.\n  // Calculate partial derivatives of y0, y1, y2 with respect to v0, v1.\n  // \u2202y0/\u2202v0 = -sin(v0) + (cos(v0)^2 - sin(v0)^2) / v1\n  expected(0, 0) =\n      -sin(v0_) + (cos(v0_) * cos(v0_) - sin(v0_) * sin(v0_)) / v1_;\n  // \u2202y0/\u2202v1 = -sin(v0) * cos(v0) / v1^2\n  expected(0, 1) = -sin(v0_) * cos(v0_) / (v1_ * v1_);\n  // \u2202y1/\u2202v0 = cos(v0).\n  expected(1, 0) = cos(v0_);\n  // \u2202y1/\u2202v1 = 1.\n  expected(1, 1) = 1.0;\n  // \u2202y2/\u2202v0 = 2 * v0.\n  expected(2, 0) = 2 * v0_;\n  // \u2202y2/\u2202v1 = 3 * v1^2.\n  expected(2, 1) = 3 * v1_ * v1_;\n\n  EXPECT_TRUE(\n      CompareMatrices(expected, gradients, 1e-10, MatrixCompareType::absolute))\n      << gradients;\n}\n\nGTEST_TEST(AdditionalAutodiffTest, DiscardGradient) {\n  // Test the double case:\n  Eigen::Matrix2d test = Eigen::Matrix2d::Identity();\n  EXPECT_TRUE(CompareMatrices(DiscardGradient(test), test));\n\n  Eigen::MatrixXd test2 = Eigen::Vector3d{1., 2., 3.};\n  EXPECT_TRUE(CompareMatrices(DiscardGradient(test2), test2));\n\n  // Test the AutoDiff case\n  Vector3<AutoDiffXd> test3 = test2;\n  // Note:  Neither of these would compile:\n  //   Eigen::Vector3d test3out = test3;\n  //   Eigen::Vector3d test3out = test3.cast<double>();\n  // (so even compiling is a success).\n  Eigen::Vector3d test3out = DiscardGradient(test3);\n  EXPECT_TRUE(CompareMatrices(test3out, test2));\n\n  Eigen::Isometry3d test5 = Eigen::Isometry3d::Identity();\n  EXPECT_TRUE(CompareMatrices(DiscardGradient(test5).linear(), test5.linear()));\n  EXPECT_TRUE(CompareMatrices(DiscardGradient(test5).translation(),\n                              test5.translation()));\n\n  Isometry3<AutoDiffXd> test6 = Isometry3<AutoDiffXd>::Identity();\n  test6.translate(Vector3<AutoDiffXd>{3., 2., 1.});\n  Eigen::Isometry3d test6b = DiscardGradient(test6);\n  EXPECT_TRUE(CompareMatrices(test6b.linear(), Eigen::Matrix3d::Identity()));\n  EXPECT_TRUE(\n      CompareMatrices(test6b.translation(), Eigen::Vector3d{3., 2., 1.}));\n}\n\nGTEST_TEST(AdditionalAutodiffTest, DiscardZeroGradient) {\n  // Test the double case:\n  Eigen::Matrix2d test = Eigen::Matrix2d::Identity();\n  DRAKE_EXPECT_NO_THROW(DiscardZeroGradient(test));\n  EXPECT_TRUE(CompareMatrices(DiscardZeroGradient(test), test));\n\n  Eigen::MatrixXd test2 = Eigen::Vector3d{1., 2., 3.};\n  DRAKE_EXPECT_NO_THROW(DiscardZeroGradient(test2));\n  EXPECT_TRUE(CompareMatrices(DiscardZeroGradient(test2), test2));\n  // Check that the returned value is a reference to the original data.\n  EXPECT_EQ(&DiscardZeroGradient(test2), &test2);\n\n  // Test the AutoDiff case\n  Eigen::Matrix<AutoDiffXd, 3, 1> test3 = test2;\n  DRAKE_EXPECT_NO_THROW(DiscardZeroGradient(test3));\n  // Note:  Neither of these would compile:\n  //   Eigen::Vector3d test3out = test3;\n  //   Eigen::Vector3d test3out = test3.cast<double>();\n  // (so even compiling is a success).\n  Eigen::Vector3d test3out = DiscardZeroGradient(test3);\n  EXPECT_TRUE(CompareMatrices(test3out, test2));\n  test3 =\n      initializeAutoDiffGivenGradientMatrix(test2, Eigen::MatrixXd::Zero(3, 2));\n  EXPECT_TRUE(CompareMatrices(DiscardZeroGradient(test3), test2));\n  test3 =\n      initializeAutoDiffGivenGradientMatrix(test2, Eigen::MatrixXd::Ones(3, 2));\n  EXPECT_THROW(DiscardZeroGradient(test3), std::runtime_error);\n  DRAKE_EXPECT_NO_THROW(DiscardZeroGradient(test3, 2.));\n\n  Eigen::Isometry3d test5 = Eigen::Isometry3d::Identity();\n  DRAKE_EXPECT_NO_THROW(DiscardZeroGradient(test5));\n  EXPECT_TRUE(\n      CompareMatrices(DiscardZeroGradient(test5).linear(), test5.linear()));\n  EXPECT_TRUE(CompareMatrices(DiscardZeroGradient(test5).translation(),\n                              test5.translation()));\n  // Check that the returned value is a reference to the original data.\n  EXPECT_EQ(&DiscardZeroGradient(test5), &test5);\n\n  Isometry3<AutoDiffXd> test6 = Isometry3<AutoDiffXd>::Identity();\n  test6.translate(Vector3<AutoDiffXd>{3., 2., 1.});\n  DRAKE_EXPECT_NO_THROW(DiscardZeroGradient(test5));\n  Eigen::Isometry3d test6b = DiscardZeroGradient(test6);\n  EXPECT_TRUE(CompareMatrices(test6b.linear(), Eigen::Matrix3d::Identity()));\n  EXPECT_TRUE(\n      CompareMatrices(test6b.translation(), Eigen::Vector3d{3., 2., 1.}));\n  test6.linear()(0, 0).derivatives() = Vector3d{1., 2., 3.};\n\n  EXPECT_THROW(DiscardZeroGradient(test6), std::runtime_error);\n}\n\n// Make sure that casting to autodiff always results in zero gradients.\nGTEST_TEST(AdditionalAutodiffTest, CastToAutoDiff) {\n  Vector2<AutoDiffXd> dynamic = Vector2d::Ones().cast<AutoDiffXd>();\n  const auto dynamic_gradients = autoDiffToGradientMatrix(dynamic);\n  EXPECT_EQ(dynamic_gradients.rows(), 2);\n  EXPECT_EQ(dynamic_gradients.cols(), 0);\n\n  using VectorUpTo16d = Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 16, 1>;\n  using AutoDiffUpTo16d = Eigen::AutoDiffScalar<VectorUpTo16d>;\n  Vector2<AutoDiffUpTo16d> dynamic_max =\n      Vector2d::Ones().cast<AutoDiffUpTo16d>();\n  const auto dynamic_max_gradients = autoDiffToGradientMatrix(dynamic_max);\n  EXPECT_EQ(dynamic_max_gradients.rows(), 2);\n  EXPECT_EQ(dynamic_max_gradients.cols(), 0);\n\n  Vector2<AutoDiffScalar<Vector3d>> fixed =\n      Vector2d::Ones().cast<AutoDiffScalar<Vector3d>>();\n  const auto fixed_gradients = autoDiffToGradientMatrix(fixed);\n  EXPECT_EQ(fixed_gradients.rows(), 2);\n  EXPECT_EQ(fixed_gradients.cols(), 3);\n  EXPECT_TRUE(fixed_gradients.isZero(0.));\n}\n\n}  // namespace\n}  // namespace math\n}  // namespace drake\n", "meta": {"hexsha": "730fb579cf6d03a298cbf803257c407a0594674e", "size": 8526, "ext": "cc", "lang": "C++", "max_stars_repo_path": "math/test/autodiff_test.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "math/test/autodiff_test.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/test/autodiff_test.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 38.5791855204, "max_line_length": 80, "alphanum_fraction": 0.6907107671, "num_tokens": 2666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6281070074881104}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n\ntemplate <typename Matrix>\nvoid setup(Matrix& A)\n{\n    const int n= int(num_rows(A));\n    A= 1.0;\n    mtl::mat::inserter<Matrix, mtl::update_plus<double> > ins(A);\n\n    for (int i= 0; i < 2 * n; i++) {\n\tint r= rand()%n, c= rand()%n;\n\tins[r][c] << -1;\n\tins[r][r] << 1;\n    }\n}\n\n\ntemplate <typename At, typename Lt, typename Ut>\nvoid dense_ilu_0(const At& As, const Lt& Ls, const Ut& Us)\n{\n    mtl::dense2D<double> LU(As);\n     \n    const int n= int(num_rows(LU));\n    for (int i= 1; i < n; i++) \n\tfor (int k= 0; k < i; k++) {\n\t    LU[i][k]/= LU[k][k];\n\t    for (int j= k + 1; j < n; j++)\n\t\tif (LU[i][j] != 0)\n\t\t    LU[i][j]-= LU[i][k] * LU[k][j];\n\t}\n    std::cout << \"Factorizing A = \\n\" << As << \"-> LU = \\n\" << LU;\n    // std::cout << \"L = \\n\" << Ls << \"\\nU = \\n\" << Us;\n\n    MTL_THROW_IF(std::abs(LU[2][1] - Ls[2][1]) > 0.001, mtl::runtime_error(\"Wrong value in L for sparse ILU(0) factorization\"));\n\n    MTL_THROW_IF(std::abs(LU[2][2] - 1. / Us[2][2]) > 0.001, mtl::runtime_error(\"Wrong value in U for sparse ILU(0) factorization\"));\n}\n\n\nint main(int, char**)\n{\n    // For a more realistic example set sz to 1000 or larger\n    const int N = 3;\n\n    typedef mtl::compressed2D<double>  matrix_type;\n    typedef mtl::dense_vector<double>  vector_type;\n    mtl::compressed2D<double>          A(N, N);\n    setup(A);\n       \n    itl::pc::ilu_0<matrix_type>        P(A);\n    \n    if(N < 11)\n\tdense_ilu_0(A, P.get_L(), P.get_U());\n\n    mtl::dense_vector<double> x(N, 3.0), x2(N), Px(N), x3(N), x4(N), x5(N);\n\n    matrix_type L(P.get_L()), U(P.get_U()), UT(trans(U));\n\n    std::cout << \"L is\\n\" << L << \"U is \\n\" << U;\n\n    x2= strict_upper(U) * x;\n    for (int i= 0; i < N; i++)\n\tx2[i]+= 1. / U[i][i] * x[i];\n    std::cout << \"U*x = \" << x2 << \"\\n\";\n\n    Px= L * x2 + x2;\n    std::cout << \"P*x = (L+I)*U*x = \" << Px << \"\\n\";\n\n    x4= unit_lower_trisolve(L, Px);\n    std::cout << \"L^{-1} * Px = \" << x4 << \"\\n\";\n\n    MTL_THROW_IF(two_norm(vector_type(x4 - x2)) > 0.01, mtl::runtime_error(\"Error in unit_lower_trisolve.\"));\n\n    x5= inverse_upper_trisolve(U, x4);\n    std::cout << \"U^{-1} * L^{-1} * Px = \" << x5 << \"\\n\";\n\n    MTL_THROW_IF(two_norm(vector_type(x5 - x)) > 0.01, mtl::runtime_error(\"Error in inverse_upper_trisolve.\"));\n\n    x3= solve(P, Px);\n    std::cout << \"solve(P, Px) = \" << x3 << \"\\n\";\n    MTL_THROW_IF(two_norm(vector_type(x3 - x)) > 0.01, mtl::runtime_error(\"Error in solve.\"));\n\n\n    // Now test adjoint solve\n    x2= trans(L) * x + x;\n    std::cout << \"\\n\\nNow test adjoint solve\\n(L+I)^T*x = \" << x2 << \"\\n\";\n\n    //Px= trans(strict_upper(U)) * x2;\n    Px= strict_lower(UT) * x2;\n    for (int i= 0; i < N; i++)\n\tPx[i]+= 1. / U[i][i] * x2[i];\n    std::cout << \"P^T*x = ((L+I)*U)^T*x = \" << Px << \"\\n\";\n\n    x4= inverse_lower_trisolve(adjoint(U), Px);\n    std::cout << \"U^{-T} * Px = \" << x4 << \"\\n\";\n\n    MTL_THROW_IF(two_norm(vector_type(x4 - x2)) > 0.01, mtl::runtime_error(\"Error in inverse_lower_trisolve.\"));\n\n    x5= unit_upper_trisolve(adjoint(L), x4);\n    std::cout << \"L^{-T} * U^{-T} * Px = \" << x5 << \"\\n\";\n    MTL_THROW_IF(two_norm(vector_type(x5 - x)) > 0.01, mtl::runtime_error(\"Error in unit_upper_trisolve.\"));\n\n    x3= adjoint_solve(P, Px);\n    std::cout << \"adjoint_solve(P, Px) = \" << x3 << \"\\n\";\n    MTL_THROW_IF(two_norm(vector_type(x3 - x)) > 0.01, mtl::runtime_error(\"Error in adjoint_solve.\"));\n\n#if 0\n    mtl::compressed2D<double>          A2;\n    laplacian_setup(A2, 3, 3);\n       \n    itl::pc::ilu_0<matrix_type, float>  P2(A2);\n    vector_type  xiota(9), y, yc(9);\n    iota(xiota);\n\n    std::cout << \"Halloooooo\" << xiota << '\\n';\n    y= solve(P, xiota);\n    std::cout << y << '\\n';\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "b16e17e7dbd9fa13b6424fdd487f6950bdecda92", "size": 4173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/itl/test/ilu_0_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/itl/test/ilu_0_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/itl/test/ilu_0_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 30.9111111111, "max_line_length": 133, "alphanum_fraction": 0.5542774982, "num_tokens": 1514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857831, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6281070040242828}}
{"text": "#include <iterator>\n#include <string>\n#include <ctime>\n#include <vector>\n#include <iostream>\n#include <fstream>\n#include <boost/assign/std/vector.hpp> \n#include <boost/random.hpp>\n#include <boost/assert.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include<iostream>\n#include \"expm.hpp\"\nusing namespace boost::numeric::ublas;\nusing namespace std;\nint main(void)\n{\n\tmatrix<complex<double> > mat(3,3);\n\tmatrix<complex<double> > gen(3,3);  // Generator of rotaion around z aix in group theory\n\tcomplex<double> img = std::complex<double>(0,1);\n\tgen(0,0) = 0  ; gen(0,1) = -img; gen(0,2) = 0;\n\tgen(1,0) = img; gen(1,1) = 0   ; gen(1,2) = 0;\n\tgen(2,0) = 0  ; gen(2,1) = 0   ; gen(2,2) = 0;\n\n\tdouble theta = 1.5;\n\tmat = img * theta * gen;\n\tcout<< \"Rotation Matrix : \"<< expm_pad(gen) <<\"\\n\\n\";\n\treturn 0;\n}\n\n", "meta": {"hexsha": "a5e7162e878b62bcef6f74af676c0b6275c4f58d", "size": 799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/expm.cpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/numeric/ublasx/test/expm.cpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/ublasx/test/expm.cpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6333333333, "max_line_length": 89, "alphanum_fraction": 0.6470588235, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6281069998633114}}
{"text": "#include <Eigen/SparseCore>\n#include <mathtoolbox/data-normalization.hpp>\n#include <mathtoolbox/som.hpp>\n\nnamespace\n{\n    int GetNumNodes(const int resolution, const int latent_num_dims)\n    {\n        assert(latent_num_dims == 1 || latent_num_dims == 2);\n\n        if (latent_num_dims == 1)\n        {\n            return resolution;\n        }\n        else\n        {\n            return resolution * resolution;\n        }\n    }\n\n    /// \\details The computational complexity is O(#data * #nodes)\n    Eigen::VectorXi FindBestMatchingUnits(const Eigen::MatrixXd& X, const Eigen::MatrixXd& Y)\n    {\n        assert(X.rows() == Y.rows());\n\n        const int num_data  = X.cols();\n        const int num_nodes = Y.cols();\n\n        Eigen::VectorXi node_indices(num_data);\n\n        for (int i = 0; i < num_data; ++i)\n        {\n            Eigen::VectorXd squared_norms(num_nodes);\n\n            for (int j = 0; j < num_nodes; ++j)\n            {\n                squared_norms(j) = (X.col(i) - Y.col(j)).squaredNorm();\n            }\n\n            squared_norms.minCoeff(&(node_indices(i)));\n        }\n\n        return node_indices;\n    }\n\n    Eigen::SparseMatrix<double> ConvertBestMatchingUnitsIntoMat(const Eigen::VectorXi& best_matching_units,\n                                                                const int              num_nodes)\n    {\n        const int num_data = best_matching_units.size();\n\n        Eigen::SparseMatrix<double> B(num_nodes, num_data);\n\n        for (int data_index = 0; data_index < num_data; ++data_index)\n        {\n            B.insert(best_matching_units(data_index), data_index) = 1.0;\n        }\n\n        return B;\n    }\n\n    /// \\return Posititons in the latent space [0, 1]^{#dims x #nodes}\n    Eigen::MatrixXd GetLatentSpacePositions(const int resolution, const int latent_num_dims)\n    {\n        assert(latent_num_dims == 1 || latent_num_dims == 2);\n        assert(resolution >= 2);\n\n        const int num_nodes = GetNumNodes(resolution, latent_num_dims);\n\n        Eigen::MatrixXd positions(latent_num_dims, num_nodes);\n\n        if (latent_num_dims == 1)\n        {\n            for (int x_index = 0; x_index < num_nodes; ++x_index)\n            {\n                positions(0, x_index) = static_cast<double>(x_index) / static_cast<double>(resolution - 1);\n            }\n        }\n        else\n        {\n            for (int y_index = 0; y_index < resolution; ++y_index)\n            {\n                for (int x_index = 0; x_index < resolution; ++x_index)\n                {\n                    const int index = y_index * resolution + x_index;\n\n                    const double x_offset = static_cast<double>(x_index) / static_cast<double>(resolution - 1);\n                    const double y_offset = static_cast<double>(y_index) / static_cast<double>(resolution - 1);\n\n                    positions.col(index) = Eigen::Vector2d(x_offset, y_offset);\n                }\n            }\n        }\n\n        return positions;\n    }\n\n    Eigen::MatrixXd CalcNeighborhoodMat(const Eigen::MatrixXd& latent_node_positions,\n                                        const int              iter_count,\n                                        const double           init_var,\n                                        const double           min_var,\n                                        const double           var_decreasing_speed)\n    {\n        const int    num_nodes = latent_node_positions.cols();\n        const double var       = std::max(init_var * std::exp(-iter_count / var_decreasing_speed), min_var);\n\n        Eigen::MatrixXd H(num_nodes, num_nodes);\n\n        for (int i = 0; i < num_nodes; ++i)\n        {\n            for (int j = i; j < num_nodes; ++j)\n            {\n                const double squared_dist = (latent_node_positions.col(i) - latent_node_positions.col(j)).squaredNorm();\n                const double value        = std::exp(-(1.0 / (2.0 * var)) * squared_dist);\n\n                H(i, j) = value;\n                H(j, i) = value;\n            }\n        }\n\n        return H;\n    }\n} // namespace\n\nmathtoolbox::Som::Som(const Eigen::MatrixXd& data,\n                      const int              latent_num_dims,\n                      const int              resolution,\n                      const double           init_var,\n                      const double           min_var,\n                      const double           var_decreasing_speed,\n                      const bool             normalize_data)\n    : m_latent_num_dims(latent_num_dims),\n      m_resolution(resolution),\n      m_init_var(init_var),\n      m_min_var(min_var),\n      m_var_decreasing_speed(var_decreasing_speed),\n      m_normalize_data(normalize_data),\n      m_latent_node_positions(GetLatentSpacePositions(resolution, latent_num_dims)),\n      m_iter_count(0),\n      m_X(data),\n      m_data_normalizer(nullptr)\n{\n    if (m_normalize_data)\n    {\n        this->NormalizeData();\n    }\n\n    this->PerformInitialization();\n}\n\nEigen::MatrixXd mathtoolbox::Som::GetDataSpaceNodePositions() const\n{\n    return m_normalize_data ? m_data_normalizer->Denormalize(m_Y) : m_Y;\n}\n\nvoid mathtoolbox::Som::Step()\n{\n    const int             num_nodes           = GetNumNodes(m_resolution, m_latent_num_dims);\n    const int             num_data            = m_X.cols();\n    const Eigen::VectorXi best_matching_units = FindBestMatchingUnits(m_X, m_Y);\n\n    // #nodes * #data\n    const Eigen::SparseMatrix<double> B = ConvertBestMatchingUnitsIntoMat(best_matching_units, num_nodes);\n\n    // #nodes * #nodes\n    const Eigen::MatrixXd H =\n        CalcNeighborhoodMat(m_latent_node_positions, m_iter_count, m_init_var, m_min_var, m_var_decreasing_speed);\n\n    // #nodes * #data\n    const Eigen::MatrixXd R = H * B;\n\n    // #nodes * #nodes\n    Eigen::VectorXd G_inv_diag(num_nodes);\n    for (int i = 0; i < num_nodes; ++i)\n    {\n        G_inv_diag(i) = 1.0 / R.row(i).sum();\n    }\n    const auto G_inv = Eigen::DiagonalMatrix<double, Eigen::Dynamic>(G_inv_diag);\n\n    // Update Y (the positions of the grid nodes in the data space)\n    m_Y = (G_inv * H * (B * m_X.transpose())).transpose();\n\n    // Update Z (the positions of the data points in the latent space)\n    for (int i = 0; i < num_data; ++i)\n    {\n        m_Z.col(i) = m_Y.col(best_matching_units(i));\n    }\n\n    // Update the iteration count\n    ++m_iter_count;\n}\n\nvoid mathtoolbox::Som::NormalizeData()\n{\n    // Instantiate a data normalizer object\n    m_data_normalizer = std::make_shared<const DataNormalizer>(m_X);\n\n    // Replace X with its normalized version\n    m_X = m_data_normalizer->GetNormalizedDataPoints();\n}\n\nvoid mathtoolbox::Som::PerformInitialization()\n{\n    const int num_data_dims = m_X.rows();\n    const int num_data      = m_X.cols();\n    const int num_nodes     = GetNumNodes(m_resolution, m_latent_num_dims);\n\n    m_Y = Eigen::MatrixXd::Random(num_data_dims, num_nodes);\n    m_Z = Eigen::MatrixXd::Random(num_data_dims, num_data);\n}\n", "meta": {"hexsha": "1478308d6e557cf4ed635aaf4ad20058a39fc41e", "size": 6894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/som.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": "src/som.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": "src/som.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": 32.8285714286, "max_line_length": 120, "alphanum_fraction": 0.5715114592, "num_tokens": 1585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6281069993099748}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include <stdio.h>\n#include <cmath>\n#include \"pressiodemoapps/impl/swe_rusanov_flux_jacobian_function.hpp\"\n#include \"pressiodemoapps/impl/swe_rusanov_flux_values_function.hpp\"\n#include <complex>\n\nint main()\n{\n  auto passedString = \"PASS\";\n  const double tol = 1e-12;\n  const double eps = 1e-15;\n\n  const int nVars = 3;\n  using scalar_t = std::complex<double>;\n\n  const scalar_t g = 9.8;\n  const scalar_t hL = 0.4;\n  const scalar_t uL = 8.;\n  const scalar_t vL = 3.;\n\n  Eigen::Matrix<scalar_t,1,-1> UL(nVars);\n  UL(0) = hL;\n  UL(1) = hL*uL;\n  UL(2) = hL*vL;\n\n  scalar_t hR = 0.125;\n  scalar_t uR = -0.8;\n  scalar_t vR = -0.3;\n  Eigen::Matrix<scalar_t,1,-1> UR(nVars);\n  UR(0) = hR;\n  UR(1) = hR*uR;\n  UR(2) = hR*vR;\n  scalar_t normals[2];\n  normals[0] = 1;\n  normals[1] = 0;\n\n  Eigen::Matrix<scalar_t,1,-1> flux(nVars);\n  Eigen::Matrix<scalar_t,1,-1> fluxBase(nVars);\n  Eigen::Matrix<scalar_t,-1,-1> JL(nVars,nVars);\n  Eigen::Matrix<scalar_t,-1,-1> JR(nVars,nVars);\n  Eigen::Matrix<scalar_t,-1,-1> JL_FD(nVars,nVars);\n  Eigen::Matrix<scalar_t,-1,-1> JR_FD(nVars,nVars);\n  pressiodemoapps::implswe::swe_rusanov_flux_jacobian_three_dof(JL,JR,UL,UR,normals,g);\n  pressiodemoapps::implswe::swe_rusanov_flux_three_dof(fluxBase,UL,UR,normals,g);\n\n  const scalar_t oneJ(0.0,eps);\n  for (int i = 0;i < nVars; i++){\n    UL(i) += oneJ;\n    pressiodemoapps::implswe::swe_rusanov_flux_three_dof(flux,UL,UR,normals,g);\n    for (int j = 0 ; j < nVars;j++){\n      JL_FD(j,i) = 1./eps*(std::imag(flux(j)));\n      if (std::abs( JL_FD(j,i) - JL(j,i) ) > tol) passedString = \"FAILED\";\n    }\n    UL(i) -= oneJ;\n\n    UR(i) += oneJ;\n    pressiodemoapps::implswe::swe_rusanov_flux_three_dof(flux,UL,UR,normals,g);\n    for (int j = 0 ; j < nVars;j++){\n      JR_FD(j,i) = 1./eps*std::imag(flux(j) );\n      if (std::abs( JR_FD(j,i) - JR(j,i) ) > tol) passedString = \"FAILED\";\n    }\n    UR(i) -= oneJ;\n  }\n\n  normals[0] = 0;\n  normals[1] = 1;\n  pressiodemoapps::implswe::swe_rusanov_flux_jacobian_three_dof(JL,JR,UL,UR,normals,g);\n  pressiodemoapps::implswe::swe_rusanov_flux_three_dof(fluxBase,UL,UR,normals,g);\n  for (int i = 0;i < nVars; i++){\n    UL(i) += oneJ;\n    pressiodemoapps::implswe::swe_rusanov_flux_three_dof(flux,UL,UR,normals,g);\n    for (int j = 0 ; j < nVars;j++){\n      JL_FD(j,i) = 1./eps*std::imag(flux(j) );\n      if (std::abs( JL_FD(j,i) - JL(j,i) ) > tol) passedString = \"FAILED\";\n    }\n    UL(i) -= oneJ;\n\n    UR(i) += oneJ;\n    pressiodemoapps::implswe::swe_rusanov_flux_three_dof(flux,UL,UR,normals,g);\n    for (int j = 0 ; j < nVars;j++){\n      JR_FD(j,i) = 1./eps*std::imag(flux(j));\n      if (std::abs( JR_FD(j,i) - JR(j,i) ) > tol) passedString = \"FAILED\";\n    }\n    UR(i) -= oneJ;\n  }\n\n\n  std::cout << passedString << std::endl;\n\n}\n", "meta": {"hexsha": "2a84317046f5e557ed105aa45ece517fb03cfa59", "size": 2779, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tests_cpp/eigen_rusanov_flux_jacobians_swe/main2d.cc", "max_stars_repo_name": "fnrizzi/pressio-demoapps", "max_stars_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-17T18:20:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T09:23:02.000Z", "max_issues_repo_path": "tests_cpp/eigen_rusanov_flux_jacobians_swe/main2d.cc", "max_issues_repo_name": "fnrizzi/pressio-demoapps", "max_issues_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 70.0, "max_issues_repo_issues_event_min_datetime": "2021-05-13T08:27:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:39:29.000Z", "max_forks_repo_path": "tests_cpp/eigen_rusanov_flux_jacobians_swe/main2d.cc", "max_forks_repo_name": "fnrizzi/pressio-demoapps", "max_forks_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-27T13:39:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T13:39:03.000Z", "avg_line_length": 29.8817204301, "max_line_length": 87, "alphanum_fraction": 0.6246851385, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772318846386, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6281069975061572}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <dlib/clustering.h>\n#include <dlib/rand.h>\n\nusing namespace std;\nusing namespace dlib;\n\nint main()\n{\n\n\n    std::vector<matrix<double,2,1>> samples;\n    std::vector<matrix<double,2,1>> initial_centers = {{1,1},{2,3}};\n\n    matrix<double,2,1> sample;\n\n    const int num = 10;\n\n    for (int i = 0; i < num; ++i)\n    {\n        sample(0) = 1.0 + (((double) std::rand() / RAND_MAX) - 0.5);\n        sample(1) = 1.0 + (((double) std::rand() / RAND_MAX) - 0.5);\n        samples.push_back(sample);\n    }\n\n    for (int i = 0; i < num; ++i)\n    {\n        sample(0) = 2 + (((double) std::rand() / RAND_MAX) - 0.5);\n        sample(1) = 3 + (((double) std::rand() / RAND_MAX) - 0.5);\n        samples.push_back(sample);\n    }\n\n\n    pick_initial_centers(2, initial_centers, samples);\n\n    find_clusters_using_kmeans(samples,initial_centers, 10);\n\n    for (const auto & it : initial_centers) {\n        std::cout << \"cluster x: \" << it(0) << \" , y: \" << it(1) << std::endl;\n    }\n\n\n}\n\n\n\n", "meta": {"hexsha": "0c0d0ecc4954862bd31fec08a6e47b2135b89a8d", "size": 1016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Section4/k_means.cpp", "max_stars_repo_name": "PacktPublishing/Introduction-to-Machine-Learning-C-Libraries", "max_stars_repo_head_hexsha": "6b0a5978c72ea6d13492bb53d8107c408fda1902", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-03-24T12:08:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T13:12:12.000Z", "max_issues_repo_path": "Section4/k_means.cpp", "max_issues_repo_name": "PacktPublishing/Introduction-to-Machine-Learning-C-Libraries", "max_issues_repo_head_hexsha": "6b0a5978c72ea6d13492bb53d8107c408fda1902", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Section4/k_means.cpp", "max_forks_repo_name": "PacktPublishing/Introduction-to-Machine-Learning-C-Libraries", "max_forks_repo_head_hexsha": "6b0a5978c72ea6d13492bb53d8107c408fda1902", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-10-27T03:04:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-27T05:05:59.000Z", "avg_line_length": 20.7346938776, "max_line_length": 78, "alphanum_fraction": 0.5511811024, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6281069851670494}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/pblas_wrapper.hpp>\n\n#define BOOST_TEST_MODULE FrovedisTest\n#include <boost/test/unit_test.hpp>\n\nusing namespace frovedis;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    // norm of a distributed std::vector\n    std::vector<float> x = {0,0,3,4}; \n    auto xbm = vec_to_bcm<float> (x); // distributed vector x\n    auto d = nrm2<float> (xbm); \n    BOOST_CHECK (d == 5);\n\n    auto bm = make_blockcyclic_matrix_load<float> (\"./sample_4x4\");\n  \n    // checking norm operation  \n    auto row1 = make_row_vector<float> (bm,1);\n    \n    // checking whether the norm operation successfully taken place\n    float expected = 6; \n    float res = nrm2<float>(row1);\n    BOOST_CHECK (res == expected);\n}\n\n", "meta": {"hexsha": "c4f0c67ee55e462c4476cab8070f361ecd330bca", "size": 835, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test8.6/test.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "test/matrix/test8.6/test.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "test/matrix/test8.6/test.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 25.303030303, "max_line_length": 67, "alphanum_fraction": 0.6718562874, "num_tokens": 237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.7185943865443349, "lm_q1q2_score": 0.6281069851670494}}
{"text": "/************************************\n * ClassName: RSAUser\n * Function: \u5b9e\u73b0 RSA \u52a0\u5bc6\u4f7f\u7528\u8005\u7684\u7c7b\u5bf9\u8c61\n * *********************************/\n#include \"RSA.h\"\n#include \"Random.h\"\n#include \"AES.h\"\n#include <iostream>\n#include <fstream>\n#include <ctime>\n#include <cstring>\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n#include <algorithm>\n\nusing namespace std;\nusing namespace NTL;\n\n// _getch() \u51fd\u6570\u7684\u7cfb\u7edf\u79fb\u690d\u95ee\u9898\u89e3\u51b3\n#ifdef _WIN32\n#include <conio.h>\n#elif __linux__\nchar _getch();\n#endif\n\nvoid printChoose() {\n    cout << \"Please choose the length of random prime: \\n\";\n    cout << \"1. 512  bits\\n\";\n    cout << \"2. 1024 bits\\n\";\n}\n\nRSAUser::RSAUser() {\n    cout << \"Create RSA user...\" << endl;\n\n}\n\nvoid RSAUser::GenerateKey() {\n    // \u9009\u62e9 RSA \u7d20\u6570\u7684\u6bd4\u7279\u957f\u5ea6\n    int m = 0;\n    \n    printChoose();\n    do {\n        char ch = _getch();\n        switch(ch) {\n            case '1': m = 8; break;\n            case '2': m = 16; break;\n            default: m = 0;\n        }\n    } while (m == 0);\n\n    PrimeGen G(m);\n    cout << \"public key and private key are generating...\\n\";\n\n    // \u751f\u6210\u79c1\u94a5\u7684\u968f\u673a\u7d20\u6570 p, q\n    do {\n        sk.p = G.GeneratePrime();\n        sk.q = G.GeneratePrime();\n    } while (sk.p == sk.q);\n\n    // \u751f\u6210\u516c\u94a5 n\n    pk.n = sk.p * sk.q;\n    ZZ Euler = (sk.p - 1) * (sk.q - 1);    // \u6b27\u62c9\u51fd\u6570\u6570\u503c\n\n    do {\n        pk.b = G.GenerateRandom() % Euler;\n    } while(GCD(pk.b, Euler) != 1);\n\n    // \u4f7f\u7528 NTL \u5e93\u4e2d\u7684\u6c42\u9006\u51fd\u6570 InvModStatus()\n    InvModStatus(sk.a, pk.b, Euler);\n    cout << \"All keys have been generated !\\n\";\n    // \u94a5\u5319\u67e5\u770b\n    viewKey(m * 64);\n}\n\n// \u53d1\u9001 RSA \u516c\u94a5\nvoid RSAUser::SendPublicKey(RSAUser &B) {\n    B.pk = this->pk;\n}\n\n// \u521b\u5efa\u4e34\u65f6\u5bc6\u94a5\nvoid RSAUser::createTempKey() {\n    PRNG G(2);\n    k = G.GenerateRandom();\n    cout << \"Temp key has been created.\\n\";\n    cout << \"Do you want to view temp key, y/n ?\\n\";\n    char ch = _getch();\n    switch (ch) {\n        case 'Y':\n        case 'y':\n            cout << \"temp key\\n\";\n            printKey(k, 128);\n            break;\n        default:\n            break;\n    }\n}\n\n// \u52a0\u5bc6\u4fe1\u606f\uff0c\u4f7f\u7528 CBC \u6a21\u5f0f\nvoid RSAUser::EncryptMessage() {\n    // \u751f\u6210\u4e34\u65f6\u5bc6\u94a5\n    createTempKey();\n    // \u5229\u7528\u516c\u94a5\u52a0\u5bc6 k \u5f97\u5230 c1\uff0c\u6b64\u5904\u4f7f\u7528 ZZ_p \u7c7b\u8ba1\u7b97\n    ZZ_p::init(pk.n);\n    ZZ_p k_p = to_ZZ_p(k);\n    M.c1 = rep(power(k_p, pk.b));\n\n    // \u5c06\u4e34\u65f6\u5bc6\u94a5 k \u8f6c\u5316\u4e3a 128 \u6bd4\u7279\u5f62\u5f0f\n    bitset<128> key(to_ulong(k));\n    // \u4ee5\u6b64\u521b\u5efa AES \u52a0\u5bc6\u7cfb\u7edf\n    AES E(key);\n\n    // \u9700\u8981\u52a0\u5bc6\u7684\u6587\u4ef6\u8def\u5f84\u8f93\u5165\n    string fileName, newfileName;\n    cout << \"Please input the file path: \\n\";\n    cin >> fileName;\n    _getch();   // \u63a5\u6536\u56de\u8f66\u7b26\n\n    // \u5bc6\u6587\u5b58\u50a8\u4e3a \u6e90\u6587\u4ef6\u540d + \".cipher\"\n    newfileName = fileName + \".cipher\";\n    // \u6587\u4ef6\u540d\u4f5c\u4e3a\u4fe1\u606f\u4f20\u8f93\n    M.fileName = fileName;\n\n    // \u6253\u5f00\u6587\u4ef6\n    ifstream fin(fileName, ios::binary);\n    if (!fin) {\n        cerr << \"open file error.\\n\";\n        exit(-1);\n    }\n    ofstream fout(newfileName, ios::binary);\n    if (!fout) {\n        cerr << \"open file error.\\n\";\n        exit(-1);\n    }\n\n    // \u56e0\u4e3a\u9010\u5b57\u7b26\u8bfb\u53d6\u6587\u4ef6\u6bd4\u8f83\u6162\uff0c\u4f7f\u7528\u7f13\u5b58\u533a\u7684\u65b9\u5f0f\u4e00\u6b21\u6027\u8bfb\u53d6 16*1024 \u5b57\u8282\n    bitset<128> buffer[512];\n    // CBC \u6a21\u5f0f\n    // former \u8bb0\u5f55\u5bc6\u6587 y(i-1) \uff0c\u521d\u59cb\u5316\u4e3a\u4e00\u4e2a\u968f\u673a\u6570\n    PRNG G(2);\n    M.IV = G.GenerateRandom();\n    bitset<128> former(to_ulong(M.IV));\n    // \u5c06 IV \u901a\u8fc7 RSA \u52a0\u5bc6\u53d1\u9001\n    ZZ_p IV_p = to_ZZ_p(M.IV);\n    M.IV = rep(power(IV_p, pk.b));\n\n    bitset<128> cipher;     // \u5bc6\u6587\n\n    // \u5f00\u59cb\u8bfb\u53d6\u9700\u8981\u52a0\u5bc6\u7684\u6587\u4ef6\n    while (fin && !fin.eof()) {\n        // \u4e00\u6b21\u6027\u8bfb\u53d6\u6700\u591a 16*1024 \u5b57\u8282\u7684\u5185\u5bb9\n        fin.read((char*)&buffer, 16*512);\n        streamsize readNum = fin.gcount();\n        streamsize i;\n        for (i = 0; i < readNum / 16; i++) {\n            cipher = E.AESEncrypt(former ^ buffer[i]);\n            former = cipher;\n            // \u5199\u5165\u5bc6\u6587\u81f3\u6587\u4ef6\u4e2d\n            fout.write((char*)&cipher, 16);\n        }\n        streamsize end = readNum % 16;\n        // \u6587\u4ef6\u8bfb\u53d6\u7ed3\u675f\u64cd\u4f5c\uff0c\u4f7f\u7528 PKCS7Padding \u5904\u7406\u672b\u5c3e\n        if (fin.eof()) {\n            // \u672b\u5c3e\u586b\u5145\u7684\u6570\u5b57\n            bitset<128> pkcs(16 - end);\n            pkcs = pkcs << 120;\n            for (streamsize j = 16; j > end; j--) {\n                streamsize k = j - end - 1;\n                buffer[i] = ((buffer[i] << k*8) ^ pkcs) >> k*8; \n            }\n            cipher = E.AESEncrypt(former ^ buffer[i]);\n            fout.write((char*)&cipher, 16);\n        }\n    }\n\n    cout << \"File encryption finished.\\n\";\n    cout << \"Encrypted file is located at \" << newfileName << endl;\n    // \u5173\u95ed\u6587\u4ef6\n    fin.close();\n    fout.close();\n}\n\n// \u89e3\u5bc6\u4fe1\u606f\nvoid RSAUser::DecryptMessage() {\n    // \u5229\u7528\u5bc6\u94a5\u6765\u89e3\u5bc6 c1\uff0c\u5f97\u5230\u4e34\u65f6\u5bc6\u94a5 k\n    ZZ_p::init(pk.n);\n    ZZ_p c1_p = to_ZZ_p(M.c1);\n    k = rep(power(c1_p, sk.a));\n    // \u89e3\u5bc6\u5f97\u5230 IV\n    ZZ_p IV_p = to_ZZ_p(M.IV);\n    M.IV = rep(power(IV_p, sk.a));\n\n    // \u67e5\u770b\u4e34\u65f6\u5bc6\u94a5\n    cout << \"Temp key has been decrypted.\\n\";\n    cout << \"Do you want to view temp key, y/n ?\\n\";\n    char ch = _getch();\n    switch (ch) {\n        case 'Y':\n        case 'y':\n            cout << \"temp key\\n\";\n            printKey(k, 128);\n            break;\n        default:\n            break;\n    }\n\n    // \u4f7f\u7528\u5bc6\u94a5 k \u89e3\u5bc6\n    bitset<128> key(to_ulong(k));\n    // \u521b\u5efa AES \u52a0\u5bc6\u89e3\u5bc6\u7cfb\u7edf\n    AES D(key);\n\n    // \u5bc6\u6587\u6587\u4ef6\n    string fileName = M.fileName + \".cipher\";\n    \n    // \u67e5\u627e\u6587\u4ef6\u7684\u540d\u79f0\u4e2d\u7684 '\\' \u6216\u8005 '/' \u6700\u540e\u51fa\u73b0\u4f4d\u7f6e\n    int pos = M.fileName.length() - 1;\n    for (; pos >= 0; pos--) {\n        if (M.fileName[pos] == '/' || M.fileName[pos] == '\\\\')\n            break;\n    }\n    // \u89e3\u5bc6\u6587\u4ef6\u4f4d\u7f6e\n    string newfileName = M.fileName.insert(pos + 1, \"new_\");\n\n    // \u6253\u5f00\u6587\u4ef6\n    ifstream fin(fileName, ios::binary);\n    if (!fin) {\n        cerr << \"open file error.\\n\";\n        exit(-1);\n    }\n    ofstream fout(newfileName, ios::binary);\n    if (!fout) {\n        cerr << \"open file error.\\n\";\n        exit(-1);\n    }\n\n    // buffer \u7f13\u51b2\u533a\u8bfb\u53d6\n    bitset<128> buffer[512];\n    // former \u8bb0\u5f55\u5bc6\u6587 C(i-1)\uff0c\u521d\u59cb\u5316\u4e3a M.IV\n    bitset<128> former(to_ulong(M.IV));\n    bitset<128> plain;      // \u660e\u6587\n\n    // \u5f00\u59cb\u8bfb\u53d6\u89e3\u5bc6\u6587\u4ef6\n    while (fin && !fin.eof()) {\n        fin.read((char*)&buffer, 16*512);\n        streamsize readNum = fin.gcount();\n\n        bool flag = false;  // \u5224\u65ad\u662f\u5426\u7ed3\u675f\u7684\u6807\u5fd7\n        if (fin.eof() || fin.peek() == EOF) {\n            flag = true;\n        }\n        streamsize i, bufferMax = readNum / 16;\n        // \u4f7f\u7528 end \u8bb0\u5f55\u9700\u8981\u89e3\u5bc6\u7684\u7f13\u51b2\u533a\u6700\u5927\u7f16\u53f7\n        if (flag) bufferMax--;\n\n        for (i = 0; i < bufferMax; i++) {\n            plain = D.AESDecrypt(buffer[i]) ^ former;\n            former = buffer[i];\n            // \u5199\u5165\u89e3\u5bc6\u6587\u4ef6\n            fout.write((char*)&plain, 16);\n        }\n        // \u5904\u7406 PKCS7Padding \u7ed3\u5c3e\n        if (flag) {\n            // end \u8868\u793a\u989d\u5916\u586b\u5145\u7684\u5b57\u8282\u6570\n            // \u6700\u540e\u4e00\u6b21\u89e3\u5bc6\n            plain = D.AESDecrypt(buffer[i]) ^ former;\n            streamsize end = (plain >> 120).to_ulong();\n            for (streamsize j = 16; j > end; j--) {\n                // \u6700\u540e\u7684\u5b57\u8282\u5904\u7406\n                bitset<8> text((plain << (j-1)*8 >> 120).to_ulong());\n                fout.write((char*)&text, 1);\n            }\n        }\n    }\n\n    cout << \"File decryption finished.\\n\";\n    cout << \"Decrypted file is located at \" << newfileName << endl;\n    fin.close();\n    fout.close();\n}\n\n// \u53d1\u9001\u4fe1\u606f\nvoid RSAUser::SendMessage(RSAUser& A) {\n    A.M = this->M;\n}\n\n// PEM \u683c\u5f0f\u6253\u5370\u8f93\u51fa\nvoid RSAUser::PrintInPEM(const string s) {\n\tstring res = \"\";\n\tsize_t len = s.length() / 8;\t// \u6bd4\u7279\u4e32\u8f6c\u5316\u4e3a\u5b57\u8282\u7684\u957f\u5ea6\n\tsize_t i;\n\tunsigned char triBytes[3];\t\t// \u5b58\u50a8\u4e09\u4e2a\u5b57\u8282\n\n\tfor (i = 0; i+3 <= len; i += 3) {\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tbitset<8> tmp(s.substr(8*i + 8*j, 8));\n\t\t\ttriBytes[j] = tmp.to_ulong();\n\t\t}\n\t\tres += Base64Map[triBytes[0] >> 2];\n\t\tres += Base64Map[((triBytes[0]<<4) & 0x30) | (triBytes[1] >> 4)];\n\t\tres += Base64Map[((triBytes[1]<<2) & 0x3c) | (triBytes[2] >> 6)];\n\t\tres += Base64Map[triBytes[2] & 0x3f];\n\t}\n\n\tif (i < len) {\n\t\tif (len - i == 1) {\n\t\t\tbitset<8> tmp(s.substr(8*i, 8));\n\t\t\ttriBytes[0] = tmp.to_ulong();\n\t\t\tres += Base64Map[triBytes[0] >> 2];\n\t\t\tres += Base64Map[(triBytes[0]<<4) & 0x30];\n\t\t\tres += \"==\";\n\t\t} else {\n\t\t\tfor (int j = 0; j < 2; j++) {\n\t\t\t\tbitset<8> tmp(s.substr(8*i + 8*j, 8));\n\t\t\t\ttriBytes[j] = tmp.to_ulong();\n\t\t\t}\n\t\t\tres += Base64Map[triBytes[0] >> 2];\n\t\t\tres += Base64Map[((triBytes[0]<<4) & 0x30) | (triBytes[1] >> 4)];\n\t\t\tres += Base64Map[(triBytes[1]<<2) & 0x3c];\n\t\t\tres += \"=\";\n\t\t}\n\t}\n\n\tcout << res << endl;\n}\n\n// DER(\u5341\u516d\u8fdb\u5236)\u683c\u5f0f\u6253\u5370\nvoid RSAUser::PrintInDER(const string s) {\n    cout << \"modulus:\";\n    string pairstr = \"\";\n    for (size_t i = 0; i < s.length(); i += 4) {\n        int index = 0;\n        \n        for (size_t j = i; j < i + 4; j++) {\n            index = index << 1;\n            if (s[j] == '1') {\n                index += 1;\n            }\n        }\n        pairstr += HexTable[index];\n        if (pairstr.length() == 2) {\n            cout << pairstr;\n            if (i + 4 < s.length()) {\n                cout << \":\";\n            }\n            pairstr = \"\";\n        }\n        if (i % 120 == 0) {\n            cout << endl << '\\t';\n        }\n    }\n    cout << endl;\n}\n\n// ZZ \u7c7b\u578b\u8f6c\u5316\u4e3a Bits\nstring RSAUser::ZZToBits(ZZ num, const size_t n) {\n\tstring s = \"\";\n\tZZ last;\n\n\twhile (num != 0) {\n\t\tlast = num % 2;\n\t\tif (last == 1) {\n\t\t\ts += '1';\n\t\t} else {\n\t\t\ts += '0';\n\t\t}\n\t\tnum /= 2;\n\t}\n\tfor (size_t i = s.length(); i < n; i++) {\n\t\ts += '0';\n\t}\n\treverse(s.begin(), s.end());\n\treturn s;\n}\n\n// \u9009\u62e9\u8f93\u51fa\u683c\u5f0f\u6253\u5370\nvoid printFormat() {\n    cout << \"Please choose the format to print key :\\n\";\n    cout << \"1. DER (hexadecimal)\\n\";\n    cout << \"2. PEM\\n\";\n}\n\n// \u67e5\u770b\u94a5\u5319\uff0cn \u4e3a p,q \u7684\u6bd4\u7279\u4f4d\u6570\nvoid RSAUser::viewKey(const size_t n) {\n    // \u67e5\u770b\u516c\u94a5\n    cout << \"Do you want to view public key, y/n ?\\n\";\n    char ch = _getch();\n\n    switch(ch) {\n        case 'Y':\n        case 'y': {\n            cout << \"Public key\\n\";\n            cout << \"Print n in public key :\\n\";\n            printKey(pk.n, n*2);\n            cout << \"Print b in public key :\\n\";\n            printKey(pk.b, n*2);\n            break;\n        }\n        default: break;\n    }\n    // \u67e5\u770b\u79c1\u94a5\n    cout << \"Do you want to view private key, y/n ?\\n\";\n    ch = _getch();\n\n    if (ch == 'y' || ch == 'Y') {\n        cout << \"Attention, please not reveal this information !!!\\n\";\n        cout << \"Read the warning, continue, y/n ?\\n\";\n        ch = _getch();\n\n        switch(ch) {\n            case 'Y':\n            case 'y': {\n                cout << \"Private key\\n\";\n                cout << \"Print p in private key :\\n\";\n                printKey(sk.p, n);\n                cout << \"Print q in private key :\\n\";\n                printKey(sk.q, n);\n                cout << \"Print a in private key :\\n\";\n                printKey(sk.a, n*2);\n                break;\n            }\n            default: break;\n        }\n    }\n\n}\n\n// \u6253\u5370\u6bcf\u4e00\u4e2a\u94a5\u5319\nvoid RSAUser::printKey(ZZ num, const size_t n) {\n    string s = ZZToBits(num, n);\n    printFormat();\n    bool flag = false;\n    while (!flag) {\n        char ch = _getch();\n        switch(ch) {\n            case '1': {\n                PrintInDER(s);\n                flag = true;\n                break;\n            }\n            case '2': {\n                PrintInPEM(s);\n                flag = true;\n                break;\n            }\n            default: break;\n        }\n    }\n}", "meta": {"hexsha": "17b812ad41866762388a290b329b5dc5ddec1ce8", "size": 10693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RSA.cpp", "max_stars_repo_name": "yuanyangwangTJ/RSA", "max_stars_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RSA.cpp", "max_issues_repo_name": "yuanyangwangTJ/RSA", "max_issues_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RSA.cpp", "max_forks_repo_name": "yuanyangwangTJ/RSA", "max_forks_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9217002237, "max_line_length": 70, "alphanum_fraction": 0.474890115, "num_tokens": 3599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.628081275393063}}
{"text": "/*!\n * \\file AffHypPlane.hpp\n * \\author Jun Yoshida\n * \\copyright (c) 2019 Jun Yoshida.\n * The project is released under the MIT License.\n * \\date Descember 9, 2019: created\n */\n\n#pragma once\n\n// #include <iostream> // only for Debug\n#include <utility>\n#include <tuple>\n#include <array>\n#include <Eigen/Dense>\n\n#include \"../utils.hpp\"\n\ntemplate<size_t n>\nclass AffHypPlane\n{\npublic:\n    /*static constexpr size_t*/ enum : size_t { dim = n };\n    static constexpr double threshold = 1e-14;\n    using VecT = typename Eigen::Matrix<double,dim,1>;\n\nprivate:\n    //! The defining function of the line is\n    //!   <m_normal|x> + m_c = 0;\n    VecT m_normal;\n    double m_c;\n\npublic:\n    AffHypPlane(std::array<double,dim> const & normal, double c)\n        : m_normal(Eigen::Map<const VecT>(&normal[0], dim)), m_c(c)\n    {}\n\n    AffHypPlane(VecT const &normal, VecT const &refpt)\n        : m_normal(normal), m_c(-normal.dot(refpt))\n    {}\n\n    AffHypPlane(AffHypPlane<n> const &) = default;\n    AffHypPlane(AffHypPlane<n> &&) = default;\n\n    //! Compute an intersection with another hyper plane.\n    //! The function is specialized in case of dimension 2.\n    template <size_t m= dim>\n    auto intersect(AffHypPlane<m> const &another) const\n        -> std::pair<bool,VecT>\n    {\n        Eigen::Matrix<double,2,dim> A;\n        A.row(0) = m_normal;\n        A.row(1) = another.m_normal;\n        Eigen::Vector2d b{-m_c, -another.m_c};\n\n        Eigen::Matrix<double,dim,1> x = A.colPivHouseholderQr().solve(b);\n\n        return {(A*x-b).norm()/(b.norm()+m_normal.norm()) < threshold, x};\n    }\n\n    //! Compute the height of a given point from the hyperplane.\n    //! \\warning: The value is not normalized; or with respect to the normal vector of the hyperplane.\n    double height(VecT const &v) const\n    {\n        return m_normal.dot(v) + m_c;\n    }\n\n    template <class... Ts>\n    double height(double x, Ts... xs) const\n    {\n        static_assert(1+sizeof...(Ts)==dim, \"Wrong number of arguments.\");\n        static_assert(\n            bord2::allTrue({std::is_convertible<Ts,double>::value...}),\n            \"The arguments must be convertible to double.\" );\n        return height(VecT(x, xs...));\n    }\n};\n\ntemplate<size_t n>\nconstexpr double AffHypPlane<n>::threshold;\n", "meta": {"hexsha": "af009504acb507d0fd1486b88f21a7c6de3cd1a9", "size": 2261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/AffHypPlane.hpp", "max_stars_repo_name": "Junology/bord2", "max_stars_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/AffHypPlane.hpp", "max_issues_repo_name": "Junology/bord2", "max_issues_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/AffHypPlane.hpp", "max_forks_repo_name": "Junology/bord2", "max_forks_repo_head_hexsha": "0068885144032d4a8e30c6f2c5898918d00b1d8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9135802469, "max_line_length": 102, "alphanum_fraction": 0.62804069, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6280239726066887}}
{"text": "#include <boost/safe_float.hpp>\n#include <iostream>\n#include <limits>\n\nusing namespace boost::safe_float;\nusing namespace std;\n\nint main(){\n    double large = numeric_limits<double>::max();\n    double small = numeric_limits<double>::min();\n    //when dividing a small number by a large number, float can underflow to zero\n    double uf = small / large;\n    //this is done silently, even when this number is reused as a divisor\n    double r = 5/uf;\n    //producing an unexpected \"infinity result\"\n    cout << \"Without safe_float, 5 / (small/large) = \" << r << endl;\n\n    //safe float can be used for catching these unexpected behaviors and others\n    safe_float<double> sf_large = numeric_limits<double>::max();\n    safe_float<double> sf_small = numeric_limits<double>::min();\n    try {\n        safe_float<double> sf_uf = sf_small / sf_large;\n    } catch (const std::exception& e) {\n        cout << \"sf_small / sf_large produced an exception because of the underflow to zero\" << endl;\n    }\n    //setting sf_uf to zero\n    safe_float<double> sf_uf = 0.0f;\n    try {\n        safe_float<double> sf_r = safe_float<double>(5.0f) / sf_uf;\n    } catch (const std::exception& e) {\n        cout << \"5 / 0 produced an exception because of division by zero\" << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "e29169dd42525b98000739ca787ea95f11cd2d24", "size": 1279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/example-safezero.cpp", "max_stars_repo_name": "aTom3333/safefloat", "max_stars_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-08T01:24:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-08T01:24:16.000Z", "max_issues_repo_path": "example/example-safezero.cpp", "max_issues_repo_name": "aTom3333/safefloat", "max_issues_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/example-safezero.cpp", "max_forks_repo_name": "aTom3333/safefloat", "max_forks_repo_head_hexsha": "760a1fa243672d49271836e8c431f002a615eca5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-28T11:31:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-12T21:55:25.000Z", "avg_line_length": 35.5277777778, "max_line_length": 101, "alphanum_fraction": 0.6637998436, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6280239676871905}}
{"text": "#ifndef BOOST_UBLAS_INVERT_MATRIX_HPP\n#define BOOST_UBLAS_INVERT_MATRIX_HPP\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n/* Matrix inversion routine.\nUses lu_factorize and lu_substitute in uBLAS to invert a matrix */\nnamespace boost {\n    namespace numeric {\n        namespace ublas {\n\n            template<class T>\n            bool InvertMatrix(const matrix<T>& input, matrix<T>& inverse)\n            {\n                typedef permutation_matrix<std::size_t> pmatrix;\n\n                // create a working copy of the input\n                matrix<T> 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<T>(A.size1(), A.size1()));\n\n                // backsubstitute to get the inverse\n                lu_substitute(A, pm, inverse);\n\n                return true;\n            }\n        } /* namespace ublas */\n    } /* namespace numeric */\n} /* namespace boost */\n\n#endif", "meta": {"hexsha": "5f152f0e208a1a6ec62dba41bf011f2f52bfa8ad", "size": 1233, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublas/invert_matrix.hpp", "max_stars_repo_name": "ATetiukhin/Davidon_Fletcher_Powell", "max_stars_repo_head_hexsha": "92f96b5e8552b86613fc5a5ac7f29bd653dbee1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-07-08T03:35:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-26T19:19:38.000Z", "max_issues_repo_path": "boost/numeric/ublas/invert_matrix.hpp", "max_issues_repo_name": "ATetiukhin/Davidon_Fletcher_Powell", "max_issues_repo_head_hexsha": "92f96b5e8552b86613fc5a5ac7f29bd653dbee1f", "max_issues_repo_licenses": ["MIT"], "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/ublas/invert_matrix.hpp", "max_forks_repo_name": "ATetiukhin/Davidon_Fletcher_Powell", "max_forks_repo_head_hexsha": "92f96b5e8552b86613fc5a5ac7f29bd653dbee1f", "max_forks_repo_licenses": ["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.0731707317, "max_line_length": 73, "alphanum_fraction": 0.5644768856, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6280239559810715}}
{"text": "#include \"bits//stdc++.h\"\r\n#include <boost/math/common_factor_rt.hpp>\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\nint main() {\r\n\tint x, y; cin >> x >> y;\r\n\tint answer = gcd(x, y); cout << answer << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "695d4882bd7476e45308103d106a740f50f91923", "size": 229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AIZU ONLINE JUDGE/ALDS1_1_B.cpp", "max_stars_repo_name": "vow256/codes", "max_stars_repo_head_hexsha": "8ae972132b77ad9813328df7801df685ea87f9f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AIZU ONLINE JUDGE/ALDS1_1_B.cpp", "max_issues_repo_name": "vow256/codes", "max_issues_repo_head_hexsha": "8ae972132b77ad9813328df7801df685ea87f9f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AIZU ONLINE JUDGE/ALDS1_1_B.cpp", "max_forks_repo_name": "vow256/codes", "max_forks_repo_head_hexsha": "8ae972132b77ad9813328df7801df685ea87f9f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9, "max_line_length": 49, "alphanum_fraction": 0.6244541485, "num_tokens": 62, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6279296744257947}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <chrono>\n#include <vector>\n\nclass Kalman\n{\npublic:\n    struct Inputs\n    {\n        double eastAcc;\n        double northAcc;\n    };\n\n    struct Measurements\n    {\n        double x;\n        double y;\n    };\n\n    typedef Measurements Estimates;\n\nprivate:\n    typedef std::chrono::time_point<std::chrono::high_resolution_clock> timeVar;\n\n    timeVar previousUpdateTime = std::chrono::high_resolution_clock::now();\n\n    const std::vector<double> processVariance;\n    const std::vector<double> measurementVariance;\n\n    bool fstScan = true;\n    Eigen::Vector2d aPosteriori_xHat;\n    Eigen::Matrix2d aPosteriori_P;\n\npublic:\n    Kalman(const std::vector<double> &_processVariance, const std::vector<double> &_measurementVariance);\n    Estimates update(const Inputs &inputs, const Measurements &measurements);\n    Estimates getEstimates() const;\n};", "meta": {"hexsha": "862d59320115a2d01eac20ba6a35da3e44c493f5", "size": 884, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/statek_map/include/gps_to_tf/kalman.hpp", "max_stars_repo_name": "Tai-Min/Statek-UAV", "max_stars_repo_head_hexsha": "932219cde0707cd2cf288e467226a21b8c24d19e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/statek_map/include/gps_to_tf/kalman.hpp", "max_issues_repo_name": "Tai-Min/Statek-UAV", "max_issues_repo_head_hexsha": "932219cde0707cd2cf288e467226a21b8c24d19e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/statek_map/include/gps_to_tf/kalman.hpp", "max_forks_repo_name": "Tai-Min/Statek-UAV", "max_forks_repo_head_hexsha": "932219cde0707cd2cf288e467226a21b8c24d19e", "max_forks_repo_licenses": ["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.6666666667, "max_line_length": 105, "alphanum_fraction": 0.6968325792, "num_tokens": 204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6279296495286931}}
{"text": "//  Boost common_factor_ct.hpp header file  ----------------------------------//\r\n\r\n//  (C) Copyright John Maddock 2017.\r\n//  Distributed under the Boost Software License, Version 1.0. (See\r\n//  accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  See http://www.boost.org for updates, documentation, and revision history. \r\n\r\n#ifndef BOOST_MATH_COMMON_FACTOR_CT_HPP\r\n#define BOOST_MATH_COMMON_FACTOR_CT_HPP\r\n\r\n#include <boost/integer/common_factor_ct.hpp>\r\n\r\nnamespace boost\r\n{\r\nnamespace math\r\n{\r\n\r\n   using boost::integer::static_gcd;\r\n   using boost::integer::static_lcm;\r\n   using boost::integer::static_gcd_type;\r\n\r\n}  // namespace math\r\n}  // namespace boost\r\n\r\n\r\n#endif  // BOOST_MATH_COMMON_FACTOR_CT_HPP\r\n", "meta": {"hexsha": "b1eead09d5400e71cc25de4a69ad49aebbe4e9aa", "size": 757, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Service/jni/boost/x86_64/include/boost-1_65_1/boost/math/common_factor_ct.hpp", "max_stars_repo_name": "Mattlk13/innoextract-android", "max_stars_repo_head_hexsha": "5a69382ac9104d47383c1af0aaa0bc8a336c9744", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2017-11-12T08:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T03:16:06.000Z", "max_issues_repo_path": "Service/jni/boost/x86_64/include/boost-1_65_1/boost/math/common_factor_ct.hpp", "max_issues_repo_name": "Mattlk13/innoextract-android", "max_issues_repo_head_hexsha": "5a69382ac9104d47383c1af0aaa0bc8a336c9744", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-12T02:43:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-14T06:08:53.000Z", "max_forks_repo_path": "Service/jni/boost/x86_64/include/boost-1_65_1/boost/math/common_factor_ct.hpp", "max_forks_repo_name": "Mattlk13/innoextract-android", "max_forks_repo_head_hexsha": "5a69382ac9104d47383c1af0aaa0bc8a336c9744", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2017-12-18T12:42:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T08:19:53.000Z", "avg_line_length": 26.1034482759, "max_line_length": 81, "alphanum_fraction": 0.6922060766, "num_tokens": 177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6279296452481624}}
{"text": "#pragma once\n\n#include <Eigen/Eigen>\n#include <unsupported/Eigen/KroneckerProduct>\n#include <array>\n#include <memory>\n#include <tuple>\n\ntemplate<typename Scalar, int Order>\nclass Tensor\n{\npublic:\n\tusing SizeVector = std::array<int, Order>;\n\n\tTensor() noexcept : m_size{}, m_offsets{}, m_numElements(0), m_capacity(0), m_data(nullptr) {}\n\n\texplicit Tensor(const SizeVector& _size)\n\t\t: m_size(_size)\n\t{\n\t\tcomputeOffsets();\n\t\tm_numElements = static_cast<size_t>(m_offsets.back()) \n\t\t\t* static_cast<size_t>(m_size.back());\n\t\tm_capacity = m_numElements;\n\n\t\tm_data = std::make_unique<Scalar[]>(m_numElements);\n\t}\n\n\tTensor(const SizeVector& _size, const Scalar* _data)\n\t\t: Tensor(_size)\n\t{\n\t\tif (_data)\n\t\t\tstd::copy(_data, _data + m_numElements, m_data.get());\n\t}\n\n\tTensor(const Tensor& _oth)\n\t\t: m_size(_oth.m_size), \n\t\tm_offsets(_oth.m_offsets),\n\t\tm_numElements(_oth.m_numElements),\n\t\tm_capacity(_oth.m_numElements),\n\t\tm_data(std::make_unique<Scalar[]>(m_numElements))\n\t{\n\t\tstd::copy(_oth.m_data.get(), _oth.m_data.get() + m_numElements, m_data.get());\n\t}\n\n\tTensor(Tensor&& _oth) noexcept\n\t\t: m_size(_oth.m_size),\n\t\tm_offsets(_oth.m_offsets),\n\t\tm_numElements(_oth.m_numElements),\n\t\tm_capacity(_oth.m_capacity),\n\t\tm_data(std::move(_oth.m_data))\n\t{}\n\n\ttemplate<typename StreamT>\n\texplicit Tensor(StreamT& _stream)\n\t{\n\t\t_stream.read(reinterpret_cast<char*>(m_size.data()), m_size.size() * sizeof(int));\n\n\t\tcomputeOffsets();\n\t\tm_numElements = static_cast<size_t>(m_offsets.back())\n\t\t\t* static_cast<size_t>(m_size.back());\n\t\tm_capacity = m_numElements;\n\n\t\tm_data = std::make_unique<Scalar[]>(m_numElements);\n\n\t\t_stream.read(reinterpret_cast<char*>(m_data.get()), m_numElements * sizeof(Scalar));\n\t}\n\n\tTensor& operator=(const Tensor& _oth)\n\t{\n\t\tm_size = _oth.m_size;\n\t\tm_offsets = _oth.m_offsets;\n\t\tm_numElements = _oth.m_numElements;\n\t\tm_capacity = m_numElements;\n\t\tm_data = std::make_unique<Scalar[]>(m_numElements);\n\t\tstd::copy(_oth.m_data.get(), _oth.m_data.get() + m_numElements, m_data.get());\n\n\t\treturn *this;\n\t}\n\n\tTensor& operator=(Tensor&& _oth) noexcept\n\t{\n\t\tm_size = _oth.m_size;\n\t\tm_offsets = _oth.m_offsets;\n\t\tm_numElements = _oth.m_numElements;\n\t\tm_capacity = _oth.m_capacity;\n\t\tm_data = std::move(_oth.m_data);\n\n\t\treturn *this;\n\t}\n\n\t// set from a k-flattening\n\tvoid set(const Eigen::MatrixX<Scalar>& _flatTensor, int _k)\n\t{\n\t\tassert(_flatTensor.rows() == m_size[_k]);\n\t\tassert(_flatTensor.rows() * _flatTensor.cols() == m_numElements);\n\n\t\tfor (size_t i = 0; i < m_numElements; ++i)\n\t\t{\n\t\t\tconst auto& [indK, indOth] = decomposeFlatIndex(i, _k);\n\t\t\tm_data[i] = _flatTensor(indK, indOth);\n\t\t}\n\t}\n\n\t//set from a k-flattening with K known at compile time\n\ttemplate<int K>\n\tvoid set(const Eigen::MatrixX<Scalar>& _flatTensor) noexcept\n\t{\n\t\tstatic_assert(K < Order);\n\t\tassert(_flatTensor.rows() == m_size[K]);\n\t\tassert(_flatTensor.rows() * _flatTensor.cols() == m_numElements);\n\n\t\tif constexpr (K == 0)\n\t\t{\n\t\t\tstd::copy(_flatTensor.data(), _flatTensor.data() + m_numElements, m_data.get());\n\t\t\treturn;\n\t\t}\n\n\t\tfor (size_t i = 0; i < m_numElements; ++i)\n\t\t{\n\t\t\tconst auto& [indK, indOth] = decomposeFlatIndex<K>(i);\n\t\t\tm_data[i] = _flatTensor(indK, indOth);\n\t\t}\n\t}\n\n\n\n\ttemplate<typename Gen>\n\tvoid set(Gen _generator)\n\t{\n\t\tfor(size_t i = 0; i < m_numElements; ++i)\n\t\t\tm_data[i] = _generator(index(i));\n\t}\n\n\tvoid append(const Tensor<Scalar, Order>& _tensor)\n\t{\n\t\tfor (int i = 0; i < Order - 1; ++i)\n\t\t\tif (m_size[i] != _tensor.size()[i])\n\t\t\t\tthrow std::string(\"Incompatible tensor sizes.\");\n\n\t\treserve(m_numElements + _tensor.numElements());\n\t\tstd::copy(_tensor.data(), _tensor.data() + _tensor.numElements(), m_data.get() + m_numElements);\n\t\tm_size.back() += _tensor.size().back();\n\t\tm_numElements += _tensor.numElements();\n\t}\n\n\tEigen::MatrixX<Scalar> flatten(int _k) const\n\t{\n\t\tconst size_t othDim = m_numElements / m_size[_k];\n\t\tEigen::MatrixX<Scalar> m(m_size[_k], othDim);\n\n\t\tfor (size_t i = 0; i < m_numElements; ++i)\n\t\t{\n\t\t\tconst auto& [indK, indOth] = decomposeFlatIndex(i, _k);\n\t\t\tm(indK, indOth) = m_data[i];\n\t\t}\n\n\t\treturn m;\n\t}\n\n\t// If K is known at compile time use this.\n\ttemplate<int K>\n\tEigen::MatrixX<Scalar> flatten() const\n\t{\n\t\tconst size_t othDim = m_numElements / m_size[K];\n\t\tEigen::MatrixX<Scalar> m(m_size[K], othDim);\n\n\t\tif constexpr (K == 0)\n\t\t{\n\t\t\tstd::copy(m_data.get(), m_data.get() + m_numElements, m.data());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (size_t i = 0; i < m_numElements; ++i)\n\t\t\t{\n\t\t\t\tconst auto& [indK, indOth] = decomposeFlatIndex<K>(i);\n\t\t\t\tm(indK, indOth) = m_data[i];\n\t\t\t}\n\t\t}\n\n\t\treturn m;\n\t}\n\n\t// Change the size of this tensor to _newSize.\n\t// The data is unspecified afterwards.\n\t// @param _shrink Shrink the buffer if the new size is smaller.\n\tvoid resize(const SizeVector& _newSize, bool _shrink = false)\n\t{\n\t\tm_size = _newSize;\n\t\tconst std::size_t oldNum = m_numElements;\n\n\t\tcomputeOffsets();\n\t\tm_numElements = static_cast<size_t>(m_offsets.back()) \n\t\t\t* static_cast<size_t>(m_size.back());\n\n\t\tif (m_capacity < m_numElements || (_shrink && oldNum > m_numElements))\n\t\t{\n\t\t\tm_data = std::make_unique<Scalar[]>(m_numElements);\n\t\t\tm_capacity = m_numElements;\n\t\t}\n\t}\n\n\t// Ensures that the reserved memory can hold atleast _capacity elements.\n\t// If the buffer is already larger no allocations take place.\n\tvoid reserve(std::size_t _capacity)\n\t{\n\t\tif (_capacity <= m_capacity) return;\n\n\t\tScalar* newData = new float[_capacity];\n\t\tstd::copy(m_data.get(), m_data.get() + m_numElements, newData);\n\t\tm_data.reset(newData);\n\t\tm_capacity = _capacity;\n\t}\n\n\t// ACCESS OPERATIONS\n\n\t// vectorization\n\tEigen::Map<const Eigen::VectorX<Scalar>> vec() const noexcept\n\t{\n\t\treturn { m_data.get(), static_cast<Eigen::Index>(m_numElements) };\n\t}\n\n\t// view which is equivalent to the 0-flattening\n\tEigen::Map<const Eigen::MatrixX<Scalar>> mat() const noexcept\n\t{\n\t\treturn { m_data.get(),\n\t\t\tstatic_cast<Eigen::Index>(m_size[0]),\n\t\t\tstatic_cast<Eigen::Index>(m_numElements / m_size[0]) };\n\t}\n\n\t// index access\n\tScalar& operator[](const SizeVector& _index) noexcept { return m_data[flatIndex(_index)]; }\n\tScalar operator[](const SizeVector& _index) const noexcept { return m_data[flatIndex(_index)]; }\n\n\t// raw access to the underlying memory\n\tScalar* data() noexcept { return m_data.get(); }\n\tconst Scalar* data() const noexcept { return m_data.get(); }\n\n\tconstexpr int order() const noexcept { return Order; }\n\tconst SizeVector& size() const noexcept { return m_size; }\n\tconst std::size_t numElements() const noexcept { return m_numElements; }\n\n\ttemplate<int OthOrder>\n\tbool isSameSize(const Tensor<Scalar, OthOrder>& _oth) const noexcept\n\t{\n\t\tif constexpr(OthOrder != Order) return false;\n\n\t\tfor (int i = 0; i < Order; ++i)\n\t\t\tif (m_size[i] != _oth.m_size[i]) return false;\n\n\t\treturn true;\n\t}\n\n\tbool operator==(const Tensor& _oth) const noexcept\n\t{\n\t\tif (!isSameSize(_oth)) return false;\n\n\t\treturn std::memcmp(m_data.get(), _oth.m_data.get(), m_numElements * sizeof(Scalar)) == 0;\n\t}\n\n\t// ARITHMETIC OPERATORS\n\tTensor<Scalar, Order> operator+(const Tensor<Scalar, Order>& _oth) const\n\t{\n\t\tassert(isSameSize(_oth));\n\n\t\tTensor<Scalar, Order> tensor(m_size);\n\t\tfor (size_t i = 0; i < m_numElements; ++i)\n\t\t{\n\t\t\ttensor.m_data[i] = m_data[i] + _oth.m_data[i];\n\t\t}\n\n\t\treturn tensor;\n\t}\n\n\tTensor<Scalar, Order> operator-(const Tensor<Scalar, Order>& _oth) const\n\t{\n\t\tassert(isSameSize(_oth));\n\n\t\tTensor<Scalar, Order> tensor(m_size);\n\t\tfor (size_t i = 0; i < m_numElements; ++i)\n\t\t{\n\t\t\ttensor.m_data[i] = m_data[i] - _oth.m_data[i];\n\t\t}\n\n\t\treturn tensor;\n\t}\n\n\t// Frobenius Norm\n\tScalar norm() const noexcept\n\t{\n\t\tScalar s = 0;\n\t\tfor (size_t i = 0; i < m_numElements; ++i)\n\t\t\ts += m_data[i] * m_data[i];\n\n\t\treturn std::sqrt(s);\n\t}\n\n\tsize_t flatIndex(const SizeVector& _index) const noexcept\n\t{\n\t\tstd::size_t flatInd = _index[0];\n\t\tstd::size_t dimSize = m_size[0];\n\t\tfor (std::size_t i = 1; i < _index.size(); ++i)\n\t\t{\n\t\t\tflatInd += dimSize * _index[i];\n\t\t\tdimSize *= m_size[i];\n\t\t}\n\n\t\treturn flatInd;\n\t}\n\n\tSizeVector index(size_t _flatIndex) const noexcept\n\t{\n\t\tSizeVector ind{};\n\t\tsize_t reminder = _flatIndex;\n\n\t\tfor (std::size_t i = 0; i < m_size.size(); ++i)\n\t\t{\n\t\t\tind[i] = reminder % m_size[i];\n\t\t\treminder /= m_size[i];\n\t\t}\n\n\t\treturn ind;\n\t}\n\n\t// SERIALIZATION\n\ttemplate<typename StreamT>\n\tvoid save(StreamT& _stream) const\n\t{\n\t\t_stream.write(reinterpret_cast<const char*>(m_size.data()), m_size.size() * sizeof(int));\n\t\t_stream.write(reinterpret_cast<const char*>(m_data.get()), \n\t\t\tm_numElements * sizeof(Scalar));\n\t}\nprivate:\n\n\tvoid computeOffsets() noexcept\n\t{\n\t\tm_offsets[0] = 1;\n\t\tfor (std::size_t i = 1; i < m_size.size(); ++i)\n\t\t{\n\t\t\tm_offsets[i] = m_offsets[i-1] * m_size[i-1];\n\t\t}\n\t}\n\n\t// Compute new indices for a k-flattening from a flatIndex.\n\tstd::pair<size_t, size_t> decomposeFlatIndex(size_t flatIndex, int _k) const noexcept\n\t{\n\t\tSizeVector ind{};\n\t\tsize_t reminder = flatIndex;\n\n\t\tstd::size_t flatInd = 0;\n\t\tstd::size_t dimSize = 1;\n\t\tfor (int j = 0; j < _k; ++j)\n\t\t{\n\t\t\tind[j] = reminder % m_size[j];\n\t\t\treminder /= m_size[j];\n\n\t\t\tflatInd += dimSize * ind[j];\n\t\t\tdimSize *= m_size[j];\n\t\t}\n\n\t\tind[_k] = reminder % m_size[_k];\n\t\treminder /= m_size[_k];\n\n\t\tflatInd += reminder * dimSize;\n\n\t\treturn { ind[_k], flatInd };\n\t}\n\n\t// variant for compile time K\n\ttemplate<int K>\n\tstd::pair<size_t, size_t> decomposeFlatIndex(size_t flatIndex) const noexcept\n\t{\n\t\tstatic_assert(K < Order);\n\n\t\tSizeVector ind{};\n\t\tsize_t reminder = flatIndex;\n\n\t\tstd::size_t flatInd = 0;\n\t\tstd::size_t dimSize = 1;\n\t\tfor (int j = 0; j < K; ++j)\n\t\t{\n\t\t\tind[j] = reminder % m_size[j];\n\t\t\treminder /= m_size[j];\n\n\t\t\tflatInd += dimSize * ind[j];\n\t\t\tdimSize *= m_size[j];\n\t\t}\n\n\t\tind[K] = reminder % m_size[K];\n\t\treminder /= m_size[K];\n\n\t\tflatInd += reminder * dimSize;\n\n\t\treturn { ind[K], flatInd };\n\t}\n\n\tSizeVector m_size;\n\tSizeVector m_offsets; // cumulative sizes\n\tstd::size_t m_numElements;\n\tstd::size_t m_capacity;\n\tstd::unique_ptr<Scalar[]> m_data;\n};\n\nnamespace details {\n\ttemplate<int K, typename Scalar, int Order, std::size_t OrderA>\n\tvoid multilinearProductImpl(const std::array<Eigen::MatrixX<Scalar>, OrderA>& _matrices,\n\t\tTensor<Scalar, Order>& _tensor,\n\t\tbool _transpose)\n\t{\n\t\tstatic_assert(Order == OrderA);\n\t\t{\n\t\t\tEigen::MatrixX<Scalar> flat = _tensor.template flatten<K>();\n\t\t\tif (_transpose)\n\t\t\t\tflat = _matrices[K].transpose() * flat;\n\t\t\telse\n\t\t\t\tflat = _matrices[K] * flat;\n\n\t\t\tauto sizeVec = _tensor.size();\n\t\t\tsizeVec[K] = static_cast<int>(flat.rows());\n\t\t\t_tensor.resize(sizeVec);\n\t\t\t_tensor.template set<K>(flat);\n\t\t}\n\t\tif constexpr (K < Order - 1)\n\t\t\tdetails::multilinearProductImpl<K + 1>(_matrices, _tensor, _transpose);\n\t}\n}\n\n// Multilinear product via k-flattening\n// @param _transpose If true, the matrices are multiplied transposed with the tensor.\ntemplate<typename Scalar, int Order, std::size_t OrderS>\nauto multilinearProduct(const std::array<Eigen::MatrixX<Scalar>, OrderS>& _matrices,\n\tconst Tensor<Scalar, Order>& _tensor,\n\tbool _transpose = false)\n\t-> Tensor<Scalar, Order>\n{\n\tstatic_assert(OrderS == Order);\n\n\tauto result = _tensor;\n\n\tdetails::multilinearProductImpl<0>(_matrices, result, _transpose);\n\n\treturn result;\n}\n\n// Multilinear product via Kronecker product\n// This method requires massive amounts of memory and should not be used.\ntemplate<typename Scalar>\nauto multilinearProductKronecker(const std::array<Eigen::MatrixX<Scalar>, 3>& _matrices, \n\tconst Tensor<Scalar, 3>& _tensor, \n\tbool _transpose = false)\n\t-> Tensor<Scalar, 3>\n{\n\tconst Eigen::VectorX<Scalar> core = _transpose ? (kroneckerProduct(_matrices[2].transpose(), kroneckerProduct(_matrices[1].transpose(), _matrices[0].transpose())) * _tensor.vec()).eval()\n\t\t: (kroneckerProduct(_matrices[2], kroneckerProduct(_matrices[1], _matrices[0])) * _tensor.vec()).eval();\n\n\ttypename Tensor<Scalar, 3>::SizeVector sizeVec;\n\tfor (size_t i = 0; i < sizeVec.size(); ++i)\n\t\tsizeVec[i] = static_cast<int>(_matrices[i].rows());\n\n\treturn Tensor<Scalar, 3>(sizeVec, core.data());\n}", "meta": {"hexsha": "2919a5fc84da9a255c4055487e91448cf922a05d", "size": 11870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/tensor.hpp", "max_stars_repo_name": "Thanduriel/tensorCompress", "max_stars_repo_head_hexsha": "5b571ed91064fb7ac1f2987f97340466f4487f44", "max_stars_repo_licenses": ["MIT"], "max_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/tensor.hpp", "max_issues_repo_name": "Thanduriel/tensorCompress", "max_issues_repo_head_hexsha": "5b571ed91064fb7ac1f2987f97340466f4487f44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/tensor.hpp", "max_forks_repo_name": "Thanduriel/tensorCompress", "max_forks_repo_head_hexsha": "5b571ed91064fb7ac1f2987f97340466f4487f44", "max_forks_repo_licenses": ["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.8043478261, "max_line_length": 187, "alphanum_fraction": 0.6787700084, "num_tokens": 3553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080989, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6277280406467584}}
{"text": "#include <cmath>\n#include <cstddef>\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/QR>\n\nint main(int argc, char **argv) {\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> m_(8, 3);\n  m_ <<\n      1, 0, -1,\n      0, 1,  1,\n      1, 0,  1,\n      0, 1,  1,\n      1, 0,  1,\n      0, 1, -1,\n      1, 0, -1,\n      0, 1, -1;\n  auto qr_ = m_.householderQr();\n\n  for (std::size_t i = 0; i < 100; ++i) {\n    Eigen::Vector<double, Eigen::Dynamic> v_(8);\n    v_.setRandom();\n    auto err_ = v_ - m_ * qr_.solve(v_);\n    assert(fabs(err_.dot(v_ - err_)) < 1e-15);\n  }\n\n  return 0;\n}", "meta": {"hexsha": "607f3ca820556858161574c8b58939300b87cab7", "size": 587, "ext": "cc", "lang": "C++", "max_stars_repo_path": "assets/attachments/2021-08-21-swerve-drive-1a/test.cc", "max_stars_repo_name": "Shimushushushu/shimushushushu.github.io", "max_stars_repo_head_hexsha": "2facdf3a1f06e5f982510f57233c09cc20a9ca04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assets/attachments/2021-08-21-swerve-drive-1a/test.cc", "max_issues_repo_name": "Shimushushushu/shimushushushu.github.io", "max_issues_repo_head_hexsha": "2facdf3a1f06e5f982510f57233c09cc20a9ca04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assets/attachments/2021-08-21-swerve-drive-1a/test.cc", "max_forks_repo_name": "Shimushushushu/shimushushushu.github.io", "max_forks_repo_head_hexsha": "2facdf3a1f06e5f982510f57233c09cc20a9ca04", "max_forks_repo_licenses": ["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.2413793103, "max_line_length": 65, "alphanum_fraction": 0.5178875639, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6277238428436187}}
{"text": "#include <filter/KalmanFilter.h>\n\n#include <Eigen/QR>\n#include <cmath>\n\nKalmanFilter::KalmanFilter(ParamsManager* params) {\n  params_ = params;\n\n  // Init State vector\n  state_t_.setZero();\n  state_t_1_.setZero();\n\n  // Set constant velocity\n  // TODO(alericcardi): create const variable\n  state_t_(3, 0) = params_->init_acceleration[0];\n  state_t_(4, 0) = params_->init_acceleration[1];\n  state_t_(5, 0) = params_->init_acceleration[2];\n\n  // Init Covariance noise\n  P_.setZero();\n\n  // Set Covariance process noise\n  D_.setZero();\n  // TODO(alericcardi): create const variable\n  D_(0, 0) = std::pow(params_->noise_process[0], 2);\n  D_(1, 1) = std::pow(params_->noise_process[1], 2);\n  D_(2, 2) = std::pow(params_->noise_process[2], 2);\n\n  // Set Covariance GPS observation noise\n  R_gps_.setZero();\n  R_gps_(0, 0) = std::pow(params_->noise_gps[0], 2);\n  R_gps_(1, 1) = std::pow(params_->noise_gps[1], 2);\n  R_gps_(2, 2) = std::pow(params_->noise_gps[2], 2);\n\n  // Set Covariance Radar observation noise\n  R_radar_.setZero();\n  R_radar_(0, 0) = std::pow(params_->noise_radar[0], 2);\n  R_radar_(1, 1) = std::pow(params_->noise_radar[1], 2);\n  R_radar_(2, 2) = std::pow(params_->noise_radar[2], 2);\n}\n\nvoid KalmanFilter::initialization_step(const GPS_DATA& gps1) {\n  // Save the current timestamp\n  cur_time_ = gps1.timestamp;\n\n  // Set the state as the initial GPS position\n  state_t_.block<3, 1>(0, 0) << gps1.pose;\n}\n\nvoid KalmanFilter::propagation_step(double timestamp) {\n  // ---------------------------------------------------------------------------\n  // Compute the Velocity\n\n  if (dt_ > 0.1) {\n    state_t_.tail(3) =\n        (state_t_.head(3) - state_t_1_.head(3)) / (dt_ + 0.00001);\n    state_t_1_ = state_t_;\n  }\n\n  // ---------------------------------------------------------------------------\n  // Update the time offset (dt)\n\n  dt_ = timestamp - cur_time_;\n  cur_time_ = timestamp;\n\n  // ---------------------------------------------------------------------------\n  // Update the State-transition matrix\n  update_F();\n\n  // ---------------------------------------------------------------------------\n  // Propagate the state and coovariance\n\n  state_t_ = F_ * state_t_;\n  P_ = F_ * P_ * F_.transpose() + D_;\n}\n\nvoid KalmanFilter::correction_gps(GPS_DATA& gps_m) {\n  Eigen::Matrix<double, 6, 6> H_t = compute_H_gps();\n  Eigen::Matrix<double, 6, 1> Y_t = Eigen::Matrix<double, 6, 1>::Zero();\n\n  // Compute the residual between GPS and State\n  Y_t.topLeftCorner(3, 1) = gps_m.pose - state_t_.head(3);\n\n  correction_step(Y_t, H_t, R_gps_);\n}\n\nvoid KalmanFilter::correction_radar(RADAR_DATA& radar_m) {\n  Eigen::Matrix<double, 6, 6> H_t = compute_H_radar();\n  Eigen::Matrix<double, 6, 1> Y_t = Eigen::Matrix<double, 6, 1>::Zero();\n\n  // Compute the residual between Radar and State\n  Y_t.head(3) = radar_m.beam - h_radar();\n\n  correction_step(Y_t, H_t, R_radar_);\n}\n\nEigen::Vector3d KalmanFilter::get_state() { return state_t_.head(3); }\n\nvoid KalmanFilter::correction_step(Eigen::Matrix<double, 6, 1> Y_t,\n                                   Eigen::Matrix<double, 6, 6> H_t,\n                                   Eigen::Matrix<double, 6, 6> R_t) {\n  Eigen::Matrix<double, 6, 6> S_t;\n  Eigen::Matrix<double, 6, 6> S_t_inv;\n  Eigen::Matrix<double, 6, 6> K_t;\n\n  // ---------------------------------------------------------------------------\n  S_t = H_t * P_ * H_t.transpose() + R_t;\n  S_t_inv = S_t.completeOrthogonalDecomposition().pseudoInverse();\n  K_t = P_ * H_t.transpose() * S_t_inv;\n\n  // ---------------------------------------------------------------------------\n  // Correct state and coovariance\n  state_t_ = state_t_ + K_t * Y_t;\n  P_ = (Eigen::Matrix<double, 6, 6>::Identity() - K_t * H_t) * P_;\n  // P_ = P_ - K_t * S_t * K_t.transpose();\n}\n\nvoid KalmanFilter::update_F() {\n  // Init of the State-transistion matrix\n  F_.block<1, 6>(0, 0) << 1, 0, 0, dt_, 0, 0;\n  F_.block<1, 6>(1, 0) << 0, 1, 0, 0, dt_, 0;\n  F_.block<1, 6>(2, 0) << 0, 0, 1, 0, 0, dt_;\n  F_.block<1, 6>(3, 0) << 0, 0, 0, 1, 0, 0;\n  F_.block<1, 6>(4, 0) << 0, 0, 0, 0, 1, 0;\n  F_.block<1, 6>(5, 0) << 0, 0, 0, 0, 0, 1;\n}\n\nEigen::Matrix<double, 6, 6> KalmanFilter::compute_H_gps() {\n  Eigen::Matrix<double, 6, 6> H_t = Eigen::Matrix<double, 6, 6>::Zero();\n\n  H_t.block<3, 3>(0, 0) << Eigen::Matrix3d::Identity();\n\n  return H_t;\n}\n\nEigen::Matrix<double, 6, 6> KalmanFilter::compute_H_radar() {\n  Eigen::Matrix<double, 6, 6> H_t = Eigen::Matrix<double, 6, 6>::Zero();\n  double x = state_t_(0, 0) - params_->init_pose_radar(0, 0);\n  double y = state_t_(1, 0) - params_->init_pose_radar(1, 0);\n  double z = state_t_(2, 0) - params_->init_pose_radar(2, 0);\n  double x_2 = std::pow(x, 2);\n  double y_2 = std::pow(y, 2);\n  double z_2 = std::pow(z, 2);\n  double ro = std::pow(x_2 + y_2 + z_2, 0.5);\n  double ro_2 = std::pow(ro, 2);\n  double sqrt_x_2_y_2 = std::pow(x_2 + y_2, 0.5);\n\n  H_t.block<1, 3>(0, 0) << x / ro, y / ro, z / ro;\n  H_t.block<1, 3>(1, 0) << (x * z) / (ro_2 * sqrt_x_2_y_2),\n      (y * z) / (ro_2 * sqrt_x_2_y_2), (-sqrt_x_2_y_2 / ro_2);\n  H_t.block<1, 3>(2, 0) << (-y / (x_2 + y_2)), (x / (x_2 + y_2)), 0;\n\n  return H_t;\n}\n\nEigen::Vector3d KalmanFilter::h_radar() {\n  Eigen::Vector3d z_radar;\n  // From global to local coordinates\n  double x = state_t_(0, 0) - params_->init_pose_radar(0, 0);\n  double y = state_t_(1, 0) - params_->init_pose_radar(1, 0);\n  double z = state_t_(2, 0) - params_->init_pose_radar(2, 0);\n\n  // From local cartesian coordinates to local spherical coordinates\n  z_radar(0, 0) =\n      std::pow(std::pow(x, 2) + std::pow(y, 2) + std::pow(z, 2), 0.5);\n  z_radar(1, 0) = std::acos(z / z_radar(0, 0));\n  z_radar(2, 0) = std::atan(y / (x + 0.0001));\n\n  return z_radar;\n}\n", "meta": {"hexsha": "6a197105f4fb666b30e8edad32d8d448e6a6fae4", "size": 5688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filter/KalmanFilter.cpp", "max_stars_repo_name": "AleRiccardi/kalman_filter_applied", "max_stars_repo_head_hexsha": "d2741728d60ffabce531ba72d192bfc34890d6cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/filter/KalmanFilter.cpp", "max_issues_repo_name": "AleRiccardi/kalman_filter_applied", "max_issues_repo_head_hexsha": "d2741728d60ffabce531ba72d192bfc34890d6cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/filter/KalmanFilter.cpp", "max_forks_repo_name": "AleRiccardi/kalman_filter_applied", "max_forks_repo_head_hexsha": "d2741728d60ffabce531ba72d192bfc34890d6cf", "max_forks_repo_licenses": ["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.2631578947, "max_line_length": 80, "alphanum_fraction": 0.5733122363, "num_tokens": 2014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952921073469, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6277174017696959}}
{"text": "#include \"gps_ba_helper.h\"\n#include <GeographicLib/Geocentric.hpp>\n#include <GeographicLib/LocalCartesian.hpp>\n#include \"pointstoply.h\"\n#include <json/json.h>\n#include <spdlog/spdlog.h>\n#include <ceres/ceres.h>\n#include <Eigen/Dense>\n#include <openvslam/camera/perspective.h>\n#include <openvslam/data/frame.h>\n#include <openvslam/data/keyframe.h>\n#include <openvslam/data/landmark.h>\n\nclass PoseGraph3dPoseErrorTerm {\npublic:\n    PoseGraph3dPoseErrorTerm(const Eigen::Vector3d& measured)\n        : P_measured_(measured) {}\n\n    template<typename T>\n    bool operator()(const T* const p_ptr, const T* const q_a_ptr, T* residuals_ptr) const {\n        Eigen::Map<Eigen::Matrix<T, 3, 1>> residuals(residuals_ptr);\n        Eigen::Map<const Eigen::Matrix<T, 3, 1>> P(p_ptr);\n        Eigen::Map<const Eigen::Quaternion<T>> q_a(q_a_ptr);\n        Eigen::Matrix<T, 3, 1> P_glob = -(q_a.conjugate() * P);\n        residuals = P_glob - P_measured_.template cast<T>();\n\n        return true;\n    }\n\n    static ceres::CostFunction* Create(const Eigen::Vector3d& P_measured) {\n        return new ceres::AutoDiffCostFunction<PoseGraph3dPoseErrorTerm, 3, 3, 4>(\n            new PoseGraph3dPoseErrorTerm(P_measured));\n    }\n\nprivate:\n    // The measurement for the position of B relative to A in the A frame.\n    const Eigen::Vector3d P_measured_;\n};\n\nstruct SnavelyReprojectionError {\n    SnavelyReprojectionError(double observed_x, double observed_y,\n                             double fx, double fy, double cx, double cy)\n        : observed_x(observed_x), observed_y(observed_y), fx(fx), fy(fy), cx(cx), cy(cy) {}\n\n    template<typename T>\n    bool operator()(const T* const q_curr_glob,\n                    const T* const p_curr_glob,\n                    const T* const point,\n                    T* residuals) const {\n        // camera[0,1,2] are the angle-axis rotation.\n        Eigen::Map<const Eigen::Matrix<T, 3, 1>> t(p_curr_glob);\n        Eigen::Map<const Eigen::Quaternion<T>> q_a(q_curr_glob);\n        Eigen::Map<const Eigen::Matrix<T, 3, 1>> P(point);\n\n        Eigen::Matrix<T, 3, 1> p = q_a * P + t;\n\n        // Compute the center of distortion. The sign change comes from\n        // the camera model that Noah Snavely's Bundler assumes, whereby\n        // the camera coordinate system has a negative z axis.\n        T xp = p[0] / p[2];\n        T yp = p[1] / p[2];\n\n        T predicted_x = fx * xp + cx;\n        T predicted_y = fy * yp + cy;\n\n        // The error is the difference between the predicted and observed position.\n        residuals[0] = predicted_x - T(observed_x);\n        residuals[1] = predicted_y - T(observed_y);\n        return true;\n    }\n\n    // Factory to hide the construction of the CostFunction object from\n    // the client code.\n    static ceres::CostFunction* Create(const double observed_x,\n                                       const double observed_y,\n                                       const double fx, const double fy, const double cx, const double cy) {\n        return (new ceres::AutoDiffCostFunction<SnavelyReprojectionError, 2, 4, 3, 3>(\n            new SnavelyReprojectionError(observed_x, observed_y, fx, fy, cx, cy)));\n    }\n\n    double observed_x;\n    double observed_y;\n    double fx;\n    double fy;\n    double cx;\n    double cy;\n};\n\nclass PoseGraph3dErrorTerm {\npublic:\n    PoseGraph3dErrorTerm(const Eigen::Quaterniond& q_ab_measured,\n                         const Eigen::Vector3d& t_ab_measured,\n                         const Eigen::Matrix<double, 6, 6>& sqrt_information)\n        : q_ab_measured_(q_ab_measured), t_ab_measured_(t_ab_measured), sqrt_information_(sqrt_information) {}\n\n    template<typename T>\n    bool operator()(const T* const p_a_ptr,\n                    const T* const q_a_ptr,\n                    const T* const p_b_ptr,\n                    const T* const q_b_ptr,\n                    T* residuals_ptr) const {\n        Eigen::Map<const Eigen::Matrix<T, 3, 1>> p_a(p_a_ptr);\n        Eigen::Map<const Eigen::Quaternion<T>> q_a(q_a_ptr);\n\n        Eigen::Map<const Eigen::Matrix<T, 3, 1>> p_b(p_b_ptr);\n        Eigen::Map<const Eigen::Quaternion<T>> q_b(q_b_ptr);\n\n        // Compute the relative transformation between the two frames.\n        Eigen::Quaternion<T> q_a_inverse = q_a.conjugate();\n        Eigen::Quaternion<T> q_ab_estimated = q_b * q_a_inverse;\n\n        // Represent the displacement between the two frames in the A frame.\n        Eigen::Matrix<T, 3, 1> p_ab_estimated = -(q_b * q_a_inverse * p_a) + p_b;\n\n        // Compute the error between the two orientation estimates.\n        Eigen::Quaternion<T> delta_q = q_ab_measured_.template cast<T>() * q_ab_estimated.conjugate();\n\n        // Compute the residuals.\n        // [ position         ]   [ delta_p          ]\n        // [ orientation (3x1)] = [ 2 * delta_q(0:2) ]\n        Eigen::Map<Eigen::Matrix<T, 6, 1>> residuals(residuals_ptr);\n        residuals.template block<3, 1>(0, 0) = p_ab_estimated - t_ab_measured_.template cast<T>();\n        residuals.template block<3, 1>(3, 0) = T(2.0) * delta_q.vec();\n\n        // Scale the residuals by the measurement uncertainty.\n        residuals.applyOnTheLeft(sqrt_information_.template cast<T>());\n\n        return true;\n    }\n\n    static ceres::CostFunction* Create(\n        const Eigen::Quaterniond& q_ab_measured,\n        const Eigen::Vector3d& t_ab_measured,\n        const Eigen::Matrix<double, 6, 6>& sqrt_information) {\n        return new ceres::AutoDiffCostFunction<PoseGraph3dErrorTerm, 6, 3, 4, 3, 4>(\n            new PoseGraph3dErrorTerm(q_ab_measured, t_ab_measured, sqrt_information));\n    }\n\nprivate:\n    // The measurement for the position of B relative to A in the A frame.\n    const Eigen::Quaterniond q_ab_measured_;\n    const Eigen::Vector3d t_ab_measured_;\n    // The square root of the measurement information matrix.\n    const Eigen::Matrix<double, 6, 6> sqrt_information_;\n};\n\nclass PoseGraph3dErrorTermWSq {\npublic:\n    PoseGraph3dErrorTermWSq(const Eigen::Quaterniond& q_ab_measured,\n                            const Eigen::Vector3d& t_ab_measured)\n        : q_ab_measured_(q_ab_measured), t_ab_measured_(t_ab_measured) {}\n\n    template<typename T>\n    bool operator()(const T* const p_a_ptr,\n                    const T* const q_a_ptr,\n                    const T* const p_b_ptr,\n                    const T* const q_b_ptr,\n                    T* residuals_ptr) const {\n        Eigen::Map<const Eigen::Matrix<T, 3, 1>> p_a(p_a_ptr);\n        Eigen::Map<const Eigen::Quaternion<T>> q_a(q_a_ptr);\n\n        Eigen::Map<const Eigen::Matrix<T, 3, 1>> p_b(p_b_ptr);\n        Eigen::Map<const Eigen::Quaternion<T>> q_b(q_b_ptr);\n\n        // Compute the relative transformation between the two frames.\n        Eigen::Quaternion<T> q_a_inverse = q_a.conjugate();\n        Eigen::Quaternion<T> q_ab_estimated = q_b * q_a_inverse;\n\n        // Represent the displacement between the two frames in the A frame.\n        Eigen::Matrix<T, 3, 1> p_ab_estimated = -(q_b * q_a_inverse * p_a) + p_b;\n\n        // Compute the error between the two orientation estimates.\n        Eigen::Quaternion<T> delta_q = q_ab_measured_.template cast<T>() * q_ab_estimated.conjugate();\n\n        // Compute the residuals.\n        // [ position         ]   [ delta_p          ]\n        // [ orientation (3x1)] = [ 2 * delta_q(0:2) ]\n        Eigen::Map<Eigen::Matrix<T, 6, 1>> residuals(residuals_ptr);\n        residuals.template block<3, 1>(0, 0) = p_ab_estimated - t_ab_measured_.template cast<T>();\n        residuals.template block<3, 1>(3, 0) = T(2.0) * delta_q.vec();\n\n        return true;\n    }\n\n    static ceres::CostFunction* Create(\n        const Eigen::Quaterniond& q_ab_measured,\n        const Eigen::Vector3d& t_ab_measured) {\n        return new ceres::AutoDiffCostFunction<PoseGraph3dErrorTermWSq, 6, 3, 4, 3, 4>(\n            new PoseGraph3dErrorTermWSq(q_ab_measured, t_ab_measured));\n    }\n\nprivate:\n    // The measurement for the position of B relative to A in the A frame.\n    const Eigen::Quaterniond q_ab_measured_;\n    const Eigen::Vector3d t_ab_measured_;\n};\n\ninline Eigen::Matrix4d odomToMat(const Eigen::Quaterniond& q, const Eigen::Vector3d& t) {\n    Eigen::Matrix4d T_glob_curr = Eigen::Matrix4d::Identity();\n    T_glob_curr.block<3, 3>(0, 0) = q.toRotationMatrix();\n    T_glob_curr.topRightCorner<3, 1>() = t;\n    return T_glob_curr;\n}\n\ninline std::tuple<Eigen::Quaterniond, Eigen::Vector3d> matToQuat(const Eigen::Matrix4d& T) {\n    Eigen::Quaterniond q(T.topLeftCorner<3, 3>());\n    return std::make_tuple(q, T.topRightCorner<3, 1>());\n}\n\n\ntemplate<typename Iterable>\nJson::Value iterable2json(Iterable const& cont) {\n    Json::Value v;\n    for (auto&& element : cont) {\n        v.append(element);\n    }\n    return v;\n}\n\n\nbool gps_ba::staticGPS_SLAM_Calibration(const openvslam::data::map_database* map_db, Eigen::Vector3d& gps_origin_lon_lat_alt) {\n    GeographicLib::Geocentric earth(GeographicLib::Constants::WGS84_a(),\n                                    GeographicLib::Constants::WGS84_f());\n\n    GeographicLib::LocalCartesian proj(gps_origin_lon_lat_alt.y(),\n                                       gps_origin_lon_lat_alt.x(),\n                                       gps_origin_lon_lat_alt.z(),\n                                       earth);\n    double alti = gps_origin_lon_lat_alt.z();\n\n    auto kfs = map_db->get_all_keyframes();\n\n    std::vector<Eigen::Vector3d> points_odom;\n    points_odom.reserve(kfs.size());\n    std::vector<Eigen::Vector3d> points_gps;\n    points_gps.reserve(kfs.size());\n\n    for (auto kf : kfs) {\n        if (kf->gps_fix_.ts > 0) {\n            if (gps_origin_lon_lat_alt.hasNaN()) {\n                gps_origin_lon_lat_alt = kf->gps_fix_.lat_lon_alt;\n                // convert from lat lon to lon lat\n                std::swap(gps_origin_lon_lat_alt.x(), gps_origin_lon_lat_alt.y());\n                // TODO ?? use zero or is it good ???\n                alti = gps_origin_lon_lat_alt.z();\n                proj.Reset(gps_origin_lon_lat_alt.y(),\n                           gps_origin_lon_lat_alt.x(),\n                           gps_origin_lon_lat_alt.z());\n            }\n            Eigen::Matrix4d T_curr_glob = kf->get_cam_pose();\n            Eigen::Quaterniond q;\n            Eigen::Vector3d t;\n            std::tie(q, t) = matToQuat(T_curr_glob);\n            points_odom.push_back(-(q.conjugate() * t));\n            Eigen::Vector3d cart;\n            proj.Forward(kf->gps_fix_.lat_lon_alt.x(), kf->gps_fix_.lat_lon_alt.y(), alti,\n                         cart.x(), cart.y(), cart.z());\n            points_gps.push_back(cart);\n        }\n    }\n\n    if (points_gps.size() < 10)\n        return false;\n\n    // calculate transformation\n    Eigen::Vector3d centroidA = Eigen::Vector3d::Zero();\n    Eigen::Vector3d centroidB = Eigen::Vector3d::Zero();\n    for (size_t i = 0; i < points_odom.size(); ++i) {\n        centroidA += points_gps[i];\n        centroidB += points_odom[i];\n    }\n    centroidA /= static_cast<double>(points_odom.size());\n    centroidB /= static_cast<double>(points_odom.size());\n\n    Eigen::Matrix3d H = Eigen::Matrix3d::Zero();\n    double sum_gps = 0;\n    double sum_odom = 0;\n    for (size_t i = 0; i < points_odom.size(); ++i) {\n        Eigen::Vector3d P_gps_ = (points_gps[i] - centroidA);\n        Eigen::Vector3d P_odom_ = (points_odom[i] - centroidB);\n        sum_gps += P_gps_.squaredNorm();\n        sum_odom += P_odom_.squaredNorm();\n        H += P_gps_ * P_odom_.transpose();\n    }\n\n    double scale = std::sqrt(sum_odom / sum_gps);\n    //double scale = 1.0;// std::sqrt(sum_odom / sum_gps);\n    {\n        std::ofstream depth_scale_file(\"depht_scale_factor.txt\");\n        depth_scale_file << std::setprecision(10);\n        depth_scale_file << \"Depth scale factor from depth to local ENU: \" << 1.0 / scale << std::endl;\n    }\n    spdlog::info(\"Depth scale factor from depth to local ENU: {:03.2f}\", 1.0 / scale);\n\n    Eigen::JacobiSVD<Eigen::Matrix3d> svd(H, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    svd.compute(H);\n\n    Eigen::Matrix3d R = svd.matrixV() * svd.matrixU().transpose();\n\n    // handling special case, reflection\n    if (R.determinant() < 0) {\n        Eigen::Matrix3d V = svd.matrixV();\n        V.col(2) *= -1;\n        R = V * svd.matrixU().transpose();\n    }\n\n    Eigen::Vector3d t = centroidB - scale * R * centroidA;\n\n    Eigen::Matrix4d T_odom_gps = Eigen::Matrix4d::Identity();\n    T_odom_gps.topLeftCorner<3, 3>() = R * scale;\n    T_odom_gps.topRightCorner<3, 1>() = t;\n\n    if (T_odom_gps.hasNaN() || !(R * R.transpose()).isIdentity(1e-4)) {\n        return false;\n    }\n\n    Eigen::Matrix4d T_gps_odom = T_odom_gps.inverse();\n\n    std::vector<Eigen::Matrix4d> T_curr_glob_old(kfs.size());\n    size_t max_kf_num = map_db->get_max_keyframe_id() + 1;\n    std::vector<size_t> kf_idxs(max_kf_num);\n    size_t i = 0;\n    for (auto kf : kfs) {\n        kf_idxs[kf->id_] = i;\n        T_curr_glob_old[i] = kf->get_cam_pose();\n        Eigen::Matrix4d T_glob_curr = kf->get_cam_pose_inv();\n        T_glob_curr.col(3) = T_gps_odom * T_glob_curr.col(3);\n        T_glob_curr.block<3, 3>(0, 0) = R.transpose() * T_glob_curr.block<3, 3>(0, 0);\n        // set new camera matrix\n        kf->set_cam_pose(T_glob_curr.inverse());\n        ++i;\n    }\n\n    // correct landmarks\n    const auto lms = map_db->get_all_landmarks();\n    std::vector<Eigen::Vector3d> landmarks_orig(lms.size());\n    std::vector<Eigen::Vector3d> landmarks_transformed(lms.size());\n    for (size_t i = 0; i < lms.size(); ++i) {\n        landmarks_orig[i] = lms[i]->get_pos_in_world();\n        if (landmarks_orig[i].norm() > 300)\n            landmarks_orig[i] = Eigen::Vector3d::Zero();\n        Eigen::Vector3d P = (T_gps_odom * lms[i]->get_pos_in_world().homogeneous()).head<3>();\n        lms[i]->set_pos_in_world(P);\n        landmarks_transformed[i] = lms[i]->get_pos_in_world();\n        if (landmarks_transformed[i].norm() > 300)\n            landmarks_transformed[i] = Eigen::Vector3d::Zero();\n    }\n\n    pointsToPly(\"landmarks_before.ply\", landmarks_orig, 0, 255, 0);\n    pointsToPly(\"landmarks_transformed.ply\", landmarks_transformed, 0, 255, 0);\n    // transformed gps\n    std::vector<Eigen::Vector3d> transformed_gps;\n    std::vector<Eigen::Vector3d> transformed_odom;\n    transformed_gps.reserve(points_gps.size());\n    transformed_odom.reserve(points_gps.size());\n    for (size_t i = 0; i < points_odom.size(); ++i) {\n        Eigen::Vector3d P = (T_odom_gps * points_gps[i].homogeneous()).head<3>();\n        transformed_gps.push_back(P);\n        P = (T_gps_odom * points_odom[i].homogeneous()).head<3>();\n        transformed_odom.push_back(P);\n    }\n\n    pointsToPly(\"odom.ply\", points_odom, 255, 0, 0);\n    pointsToPly(\"gps.ply\", points_gps, 0, 255, 0);\n    pointsToPly(\"transformed_gps.ply\", transformed_gps, 0, 0, 255);\n    pointsToPly(\"transformed_odom.ply\", transformed_odom, 0, 0, 255);\n    return true;\n}\n\nvoid gps_ba::GPS_SLAM_loop_closure(const openvslam::data::map_database* map_db, Eigen::Vector3d& gps_origin_lon_lat_alt, double gps_p3d_loss) {\n    GeographicLib::Geocentric earth(GeographicLib::Constants::WGS84_a(),\n                                    GeographicLib::Constants::WGS84_f());\n\n    GeographicLib::LocalCartesian proj(gps_origin_lon_lat_alt.y(),\n                                       gps_origin_lon_lat_alt.x(),\n                                       gps_origin_lon_lat_alt.z(),\n                                       earth);\n    double alti = gps_origin_lon_lat_alt.z();\n\n    auto kfs = map_db->get_all_keyframes();\n\n    std::vector<Eigen::Vector3d> kf_poses(kfs.size());\n    std::vector<Eigen::Quaterniond> kf_quats(kfs.size());\n    size_t max_kf_idx = map_db->get_max_keyframe_id() + 1;\n    std::vector<size_t> kf_ids(max_kf_idx);\n    std::vector<Eigen::Vector3d> kf_poses_3d(kfs.size());\n    std::vector<Eigen::Vector3d> gps_pts_tmp;\n    std::vector<Eigen::Vector3d> odom_pts_tmp;\n    std::vector<Eigen::Vector3i> color_tmp;\n\n    ceres::Problem problem_odom_enu;\n    for (size_t i = 0; i < kfs.size(); ++i) {\n        kf_ids[kfs[i]->id_] = i;\n        Eigen::Matrix4d T_curr_glob = kfs[i]->get_cam_pose();\n        std::tie(kf_quats[i], kf_poses[i]) = matToQuat(T_curr_glob);\n        kf_poses_3d[i] = -(kf_quats[i].conjugate() * kf_poses[i]);\n\n        if (kfs[i]->gps_fix_.ts > 0) {\n            Eigen::Vector3d P_gps;\n            proj.Forward(kfs[i]->gps_fix_.lat_lon_alt.x(), kfs[i]->gps_fix_.lat_lon_alt.y(), /*kfs[i]->gps_fix_.lat_lon_alt.z()*/ alti,\n                         //                         P_gps.z(), P_gps.x(), P_gps.y());\n                         P_gps.x(), P_gps.y(), P_gps.z());\n            //P_gps.y() *= -1;\n            //P_gps.x() *= -1;\n            //ceres::LossFunction* loss_function = nullptr;\n            ceres::LossFunction* loss_function = new ceres::CauchyLoss(gps_p3d_loss);\n            ceres::CostFunction* cost_function = PoseGraph3dPoseErrorTerm::Create(P_gps);\n            problem_odom_enu.AddResidualBlock(cost_function,\n                                              loss_function,\n                                              kf_poses[i].data(),\n                                              kf_quats[i].coeffs().data());\n            gps_pts_tmp.push_back(P_gps);\n            odom_pts_tmp.push_back(kf_poses_3d[i]);\n            Eigen::Vector3i color = Eigen::Vector3i::Random();\n            color.x() = color.x() % 255;\n            color.y() = color.y() % 255;\n            color.z() = color.z() % 255;\n            color_tmp.push_back(color);\n        }\n    }\n    pointsToPly(\"gps_pts_tmp.ply\", gps_pts_tmp, color_tmp);\n    pointsToPly(\"odom_pts_tmp.ply\", odom_pts_tmp, color_tmp);\n    pointsToPly(\"kf_poses_3d_before_gps_slam_loop_close.ply\", kf_poses_3d, 0, 0, 255);\n\n    Eigen::Matrix<double, 6, 6> sq = Eigen::Matrix<double, 6, 6>::Identity();\n    for (size_t i = 0; i < kfs.size(); ++i) {\n        auto childrens = kfs[i]->graph_node_->get_spanning_children();\n        Eigen::Matrix4d T_prev_glob = kfs[i]->get_cam_pose();\n        for (auto& c : childrens) {\n            size_t child_idx = kf_ids[c->id_];\n            Eigen::Matrix4d T_curr_glob = c->get_cam_pose();\n\n            Eigen::Matrix4d T_curr_prev = T_curr_glob * T_prev_glob.inverse();\n            Eigen::Quaterniond q;\n            Eigen::Vector3d p;\n            std::tie(q, p) = matToQuat(T_curr_prev);\n\n            ceres::LossFunction* loss_function = nullptr;\n            //ceres::LossFunction* loss_function = new ceres::CauchyLoss(gps_p_loss);\n            ceres::CostFunction* cost_function = PoseGraph3dErrorTerm::Create(q, p, sq);\n\n            problem_odom_enu.AddResidualBlock(cost_function,\n                                              loss_function,\n                                              kf_poses[i].data(),\n                                              kf_quats[i].coeffs().data(),\n                                              kf_poses[child_idx].data(),\n                                              kf_quats[child_idx].coeffs().data());\n        }\n    }\n\n    ceres::LocalParameterization* quaternion_local_parameterization = new ceres::EigenQuaternionParameterization();\n\n    for (size_t i = 0; i < kfs.size(); ++i) {\n        if (problem_odom_enu.HasParameterBlock(kf_quats[i].coeffs().data())) {\n            problem_odom_enu.SetParameterization(kf_quats[i].coeffs().data(),\n                                                 quaternion_local_parameterization);\n        }\n    }\n\n    //std::vector<Eigen::Vector3d> kf_poses_o = kf_poses;\n    //std::vector<Eigen::Quaterniond> kf_quats_o = kf_quats;\n\n    // solve problem once\n    {\n        ceres::Solver::Options options;\n        options.max_num_iterations = 100;\n        options.num_threads = 12;\n        options.linear_solver_type = ceres::SPARSE_SCHUR;\n        ceres::Solver::Summary summary;\n        ceres::Solve(options, &problem_odom_enu, &summary);\n        spdlog::info(summary.FullReport());\n    }\n\n\n //std::vector<Eigen::Vector3d> kf_poses_3d(kf_poses.size());\n    for (size_t i = 0; i < kf_poses.size(); ++i) {\n        if (kfs[i] != nullptr) {\n            Eigen::Matrix4d T_curr_glob_new = odomToMat(kf_quats[i], kf_poses[i]);\n            Eigen::Matrix4d T_glob_curr_new = T_curr_glob_new.inverse();\n            Eigen::Matrix4d T_curr_glob = kfs[i]->get_cam_pose();\n            // correct landmark positions and kf pose\n            auto landmarks = kfs[i]->get_landmarks();\n            for (auto& l : landmarks) {\n                if (l != nullptr && l->get_ref_keyframe()->id_ == kfs[i]->id_) {\n                    Eigen::Vector3d P = l->get_pos_in_world();\n                    P = (T_glob_curr_new * T_curr_glob * P.homogeneous()).head<3>();\n                    l->set_pos_in_world(P);\n                }\n            }\n            kfs[i]->set_cam_pose(T_curr_glob_new);\n        }\n        kf_poses_3d[i] = -(kf_quats[i].conjugate() * kf_poses[i]);\n    }\n\n    //for (size_t i = 0; i < kfs.size(); ++i) {\n    //    kfs[i]->set_cam_pose(odomToMat(kf_quats[i], kf_poses[i]));\n    //    kf_poses_3d[i] = -(kf_quats[i].conjugate() * kf_poses[i]);\n    //}\n    pointsToPly(\"kf_poses_3d_after_gps_slam_loop_close.ply\", kf_poses_3d, 0, 0, 255);\n}\n\nbool gps_ba::relocalization_correct_map_poses(openvslam::data::frame& curr_frm, const Eigen::Matrix4d T_curr_glob_old, uint32_t corrected_map_kf_max_id, uint32_t num_localized_landmark_thrs) {\n    auto kf_parent = curr_frm.ref_keyfrm_->graph_node_->get_spanning_parent();\n    auto cfid = curr_frm.id_;\n    Eigen::Matrix4d T_curr_glob = T_curr_glob_old;\n    std::vector<Eigen::Vector3d> kf_poses;\n    kf_poses.reserve(1000);\n    std::vector<Eigen::Quaterniond> kf_quats;\n    kf_quats.reserve(1000);\n    Eigen::Quaterniond q;\n    Eigen::Vector3d p;\n    std::tie(q, p) = matToQuat(curr_frm.cam_pose_cw_);\n    kf_poses.push_back(p);\n    kf_quats.push_back(q);\n    ceres::Problem problem_lc;\n    std::vector<openvslam::data::keyframe*> kfs;\n    kfs.reserve(1000);\n    kfs.push_back(nullptr);\n    size_t f_num = 0;\n    while (kf_parent != nullptr) {\n        if (kf_parent->id_ >= corrected_map_kf_max_id && kf_parent->num_localized_landmark_ < num_localized_landmark_thrs\n            && f_num < 980) {\n            kfs.push_back(kf_parent);\n            cfid = kf_parent->id_;\n\n            Eigen::Matrix4d T_prev_glob = kf_parent->get_cam_pose();\n            std::tie(q, p) = matToQuat(T_prev_glob);\n            kf_poses.push_back(p);\n            kf_quats.push_back(q);\n            Eigen::Matrix4d T_curr_prev = T_curr_glob * T_prev_glob.inverse();\n            std::tie(q, p) = matToQuat(T_curr_prev);\n\n            ceres::LossFunction* loss_function = nullptr;\n            //ceres::LossFunction* loss_function = new ceres::CauchyLoss(gps_p_loss);\n            ceres::CostFunction* cost_function = PoseGraph3dErrorTermWSq::Create(q, p);\n\n            problem_lc.AddResidualBlock(cost_function,\n                                        loss_function,\n                                        kf_poses[f_num + 1].data(),\n                                        kf_quats[f_num + 1].coeffs().data(),\n                                        kf_poses[f_num].data(),\n                                        kf_quats[f_num].coeffs().data());\n            T_curr_glob = T_prev_glob;\n            kf_parent = kf_parent->graph_node_->get_spanning_parent();\n            // increment keyframe counter\n            ++f_num;\n        }\n        else {\n            //++i;\n            break;\n        }\n    }\n\n    if (kf_parent != nullptr) {\n        Eigen::Matrix4d T_prev_glob = kf_parent->get_cam_pose();\n        std::tie(q, p) = matToQuat(T_prev_glob);\n        kf_poses.push_back(p);\n        kf_quats.push_back(q);\n        kfs.push_back(kf_parent);\n        Eigen::Matrix4d T_curr_prev = T_curr_glob * T_prev_glob.inverse();\n        std::tie(q, p) = matToQuat(T_curr_prev);\n\n        ceres::LossFunction* loss_function = nullptr;\n        //ceres::LossFunction* loss_function = new ceres::CauchyLoss(gps_p_loss);\n        ceres::CostFunction* cost_function = PoseGraph3dErrorTermWSq::Create(q, p);\n\n        problem_lc.AddResidualBlock(cost_function,\n                                    loss_function,\n                                    kf_poses[f_num + 1].data(),\n                                    kf_quats[f_num + 1].coeffs().data(),\n                                    kf_poses[f_num].data(),\n                                    kf_quats[f_num].coeffs().data());\n    }\n\n    if (kf_poses.size() > 2) {\n        ceres::LocalParameterization* quaternion_local_parameterization = new ceres::EigenQuaternionParameterization();\n\n        for (size_t i = 0; i < kf_quats.size(); ++i) {\n            //if (problem_lc.HasParameterBlock(kf_quats[i].coeffs().data())) {\n            problem_lc.SetParameterization(kf_quats[i].coeffs().data(),\n                                           quaternion_local_parameterization);\n            //}\n        }\n        problem_lc.SetParameterBlockConstant(kf_poses.front().data());\n        problem_lc.SetParameterBlockConstant(kf_poses.back().data());\n        problem_lc.SetParameterBlockConstant(kf_quats.front().coeffs().data());\n        problem_lc.SetParameterBlockConstant(kf_quats.back().coeffs().data());\n\n        // solve problem once\n        {\n            ceres::Solver::Options options;\n            options.max_num_iterations = 100;\n            options.num_threads = 12;\n            options.linear_solver_type = ceres::SPARSE_SCHUR;\n            ceres::Solver::Summary summary;\n            ceres::Solve(options, &problem_lc, &summary);\n            spdlog::info(\"Relocalization keyframe correction done {}\", summary.BriefReport());\n        }\n        //std::vector<Eigen::Vector3d> kf_poses_3d(kf_poses.size());\n        for (size_t i = 0; i < kf_poses.size(); ++i) {\n            if (kfs[i] != nullptr) {\n                Eigen::Matrix4d T_curr_glob_new = odomToMat(kf_quats[i], kf_poses[i]);\n                Eigen::Matrix4d T_glob_curr_new = T_curr_glob_new.inverse();\n                Eigen::Matrix4d T_curr_glob = kfs[i]->get_cam_pose();\n                // correct landmark positions and kf pose\n                auto landmarks = kfs[i]->get_landmarks();\n                for (auto& l : landmarks) {\n                    if (l != nullptr && l->get_ref_keyframe()->id_ == kfs[i]->id_) {\n                        Eigen::Vector3d P = l->get_pos_in_world();\n                        P = (T_glob_curr_new * T_curr_glob * P.homogeneous()).head<3>();\n                        l->set_pos_in_world(P);\n                    }\n                }\n                kfs[i]->set_cam_pose(T_curr_glob_new);\n            }\n            //kf_poses_3d[i] = -(kf_quats[i].conjugate() * kf_poses[i]);\n        }\n        //pointsToPly(\"corrected_localization_ptr.ply\", kf_poses_3d, 0, 0, 255);\n    }\n    else {\n        return false;\n    }\n    return true;\n}\n\nvoid gps_ba::global_BA_GPS_SLAM(const openvslam::data::map_database* map_db, const openvslam::camera::base* camera, const Eigen::Vector3d& gps_origin_lon_lat_alt, double gps_p3d_loss_ba, double landmark_reproj_loss) {\n    GeographicLib::Geocentric earth(GeographicLib::Constants::WGS84_a(),\n                                    GeographicLib::Constants::WGS84_f());\n\n    GeographicLib::LocalCartesian proj(gps_origin_lon_lat_alt.y(),\n                                       gps_origin_lon_lat_alt.x(),\n                                       gps_origin_lon_lat_alt.z(),\n                                       earth);\n    double alti = gps_origin_lon_lat_alt.z();\n\n    auto kfs = map_db->get_all_keyframes();\n    // bundle adjustment after odom enum calibration\n    // ---------------------------------------------\n    // ---------------------------------------------\n    //----------------------------------------------\n    ceres::Problem problem_ba;\n    std::vector<Eigen::Vector3d> kf_poses(kfs.size());\n    std::vector<Eigen::Quaterniond> kf_quats(kfs.size());\n    size_t max_kf_idx = map_db->get_max_keyframe_id() + 1;\n    std::vector<size_t> kf_ids(max_kf_idx);\n\n    std::vector<Eigen::Vector3d> kf_poses_3d(kfs.size());\n\n    for (size_t i = 0; i < kfs.size(); ++i) {\n        kf_ids[kfs[i]->id_] = i;\n        Eigen::Matrix4d T_curr_glob = kfs[i]->get_cam_pose();\n        std::tie(kf_quats[i], kf_poses[i]) = matToQuat(T_curr_glob);\n        kf_poses_3d[i] = -(kf_quats[i].conjugate() * kf_poses[i]);\n        if (kfs[i]->gps_fix_.ts > 0) {\n            Eigen::Vector3d P_gps;\n            proj.Forward(kfs[i]->gps_fix_.lat_lon_alt.x(), kfs[i]->gps_fix_.lat_lon_alt.y(), /*kfs[i]->gps_fix_.lat_lon_alt.z()*/ alti,\n                         //                         P_gps.z(), P_gps.x(), P_gps.y());\n                         P_gps.x(), P_gps.y(), P_gps.z());\n            //P_gps.y() *= -1;\n            //P_gps.x() *= -1;\n            //ceres::LossFunction* loss_function = nullptr;\n            ceres::LossFunction* loss_function = new ceres::CauchyLoss(gps_p3d_loss_ba);\n            ceres::CostFunction* cost_function = PoseGraph3dPoseErrorTerm::Create(P_gps);\n            problem_ba.AddResidualBlock(cost_function,\n                                        loss_function,\n                                        kf_poses[i].data(),\n                                        kf_quats[i].coeffs().data());\n        }\n    }\n    pointsToPly(\"odom_before_ba.ply\", kf_poses_3d, 255, 0, 0);\n\n    // add point correspondences constraint to bundle adjustment\n    const auto lms = map_db->get_all_landmarks();\n    std::vector<Eigen::Vector3d> l_ps(lms.size());\n    size_t num_g_lm = 0;\n    const openvslam::camera::perspective* p_cam = dynamic_cast<const openvslam::camera::perspective*>(camera);\n    double fx = p_cam->fx_;\n    double fy = p_cam->fy_;\n    double cx = p_cam->cx_;\n    double cy = p_cam->cy_;\n    for (size_t i = 0; i < lms.size(); ++i) {\n        size_t ref_kf_id = kf_ids[lms[i]->get_ref_keyframe()->id_];\n        l_ps[i] = lms[i]->get_pos_in_world();\n        auto obs = lms[i]->get_observations();\n        for (auto& o : obs) {\n            auto kp = o.first->keypts_[o.second];\n            auto kf_idx = kf_ids[o.first->id_];\n            Eigen::Vector3d P_cam = kf_quats[kf_idx] * l_ps[i] + kf_poses[kf_idx];\n            P_cam /= P_cam.z();\n            double u = P_cam.x() * fx + cx - kp.pt.x;\n            double v = P_cam.y() * fy + cy - kp.pt.y;\n            double err = u * u + v * v;\n            //if (err < 2.0f * 2.0f)\n            {\n                ++num_g_lm;\n                //ceres::LossFunction* loss_function = nullptr;\n                ceres::LossFunction* loss_function = new ceres::CauchyLoss(landmark_reproj_loss);\n                ceres::CostFunction* cost_function = SnavelyReprojectionError::Create(kp.pt.x, kp.pt.y,\n                                                                                      fx, fy, cx, cy);\n                problem_ba.AddResidualBlock(cost_function,\n                                            loss_function,\n                                            kf_quats[kf_idx].coeffs().data(),\n                                            kf_poses[kf_idx].data(),\n                                            l_ps[i].data());\n            }\n        }\n    }\n\n    ceres::LocalParameterization* quaternion_local_parameterization2 = new ceres::EigenQuaternionParameterization();\n\n    size_t min_kfs_id = 210000000;\n    size_t max_kfs_id = 0;\n    for (size_t i = 0; i < kfs.size(); ++i) {\n        if (problem_ba.HasParameterBlock(kf_quats[i].coeffs().data())) {\n            problem_ba.SetParameterization(kf_quats[i].coeffs().data(),\n                                           quaternion_local_parameterization2);\n        }\n        if (min_kfs_id > kfs[i]->id_) {\n            min_kfs_id = kfs[i]->id_;\n        }\n        if (max_kfs_id < kfs[i]->id_) {\n            max_kfs_id = kfs[i]->id_;\n        }\n    }\n\n    //problem_ba.SetParameterBlockConstant(kf_poses[kf_ids[min_kfs_id]].data());\n    //problem_ba.SetParameterBlockConstant(kf_poses[kf_ids[max_kfs_id]].data());\n\n    ceres::Solver::Options options;\n    options.max_num_iterations = 20;\n    options.linear_solver_type = ceres::SPARSE_SCHUR;\n    options.num_threads = 12;\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem_ba, &summary);\n    spdlog::info(summary.FullReport());\n\n    for (size_t i = 0; i < lms.size(); ++i) {\n        lms[i]->set_pos_in_world(l_ps[i]);\n        if (l_ps[i].norm() > 300)\n            l_ps[i] = Eigen::Vector3d::Zero();\n    }\n    for (size_t i = 0; i < kfs.size(); ++i) {\n        kfs[i]->set_cam_pose(odomToMat(kf_quats[i], kf_poses[i]));\n        kf_poses_3d[i] = -(kf_quats[i].conjugate() * kf_poses[i]);\n    }\n\n    pointsToPly(\"odom_after_ba.ply\", kf_poses_3d, 0, 255, 0);\n    pointsToPly(\"landmarks_after_ba.ply\", l_ps, 0, 255, 0);\n}\n\nvoid gps_ba::saveGeoJson(const openvslam::data::map_database* map_db, const openvslam::camera::base* camera, const Eigen::Vector3d& gps_origin_lon_lat_alt) {\n    GeographicLib::Geocentric earth(GeographicLib::Constants::WGS84_a(),\n                                    GeographicLib::Constants::WGS84_f());\n\n    GeographicLib::LocalCartesian proj(gps_origin_lon_lat_alt.y(),\n                                       gps_origin_lon_lat_alt.x(),\n                                       gps_origin_lon_lat_alt.z(),\n                                       earth);\n    Json::Value root;\n    root[\"type\"] = \"FeatureCollection\";\n    Json::Value features;\n    Json::Value origin;\n    origin[\"type\"] = \"Feature\";\n    Json::Value geometry;\n    geometry[\"type\"] = \"Point\";\n    std::vector<double> g_orig = {gps_origin_lon_lat_alt.x(), gps_origin_lon_lat_alt.y()};\n    geometry[\"coordinates\"] = iterable2json(g_orig);\n    origin[\"geometry\"] = geometry;\n    origin[\"properties\"][\"object_type\"] = \"origin\";\n    features.append(origin);\n    //{\n    Json::Value trajectory;\n    trajectory[\"type\"] = \"Feature\";\n    trajectory[\"properties\"][\"traffic_info\"][\"backward\"] = \"forbidden\";\n    Json::Value geometry2;\n    geometry2[\"type\"] = \"LineString\";\n\n    const auto kfs = map_db->get_all_keyframes();\n    size_t max_kf_idx = map_db->get_max_keyframe_id() + 1;\n    std::vector<size_t> kf_ids(max_kf_idx, size_t(-1));\n\n    double p3d_loss = 0.01;\n    double lm_loss = 1.0;\n    std::vector<Eigen::Vector3d> kf_poses_3d(kfs.size());\n\n    for (size_t i = 0; i < kfs.size(); ++i) {\n        kf_ids[kfs[i]->id_] = i;\n    }\n    Json::Value coordinates;\n    for (size_t i = 0; i < kf_ids.size(); ++i) {\n        if (kf_ids[i] != size_t(-1)) {\n            std::vector<double> lon_lat(2);\n            double alt;\n            Eigen::Vector3d P = kfs[kf_ids[i]]->get_cam_pose_inv().col(3).head<3>();\n            proj.Reverse(P.x(), P.y(), P.z(), lon_lat[1], lon_lat[0], alt);\n            coordinates.append(iterable2json(lon_lat));\n        }\n    }\n    geometry2[\"coordinates\"] = coordinates;\n    trajectory[\"geometry\"] = geometry2;\n    features.append(trajectory);\n    //}\n    root[\"features\"] = features;\n    std::ofstream file_id(\"geojson.json\");\n    Json::StyledStreamWriter writer;\n    writer.write(file_id, root);\n}\n\n", "meta": {"hexsha": "fe9208a6c489f564d1f8438bb10d24e4306da311", "size": 34853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openvslam/gps_ba_helper.cpp", "max_stars_repo_name": "faulhornlabs/openvslam", "max_stars_repo_head_hexsha": "2bd2f0c0e6cf5c675aa338d0764d3fba34bec8ea", "max_stars_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-03T00:20:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T00:20:14.000Z", "max_issues_repo_path": "src/openvslam/gps_ba_helper.cpp", "max_issues_repo_name": "faulhornlabs/openvslam", "max_issues_repo_head_hexsha": "2bd2f0c0e6cf5c675aa338d0764d3fba34bec8ea", "max_issues_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openvslam/gps_ba_helper.cpp", "max_forks_repo_name": "faulhornlabs/openvslam", "max_forks_repo_head_hexsha": "2bd2f0c0e6cf5c675aa338d0764d3fba34bec8ea", "max_forks_repo_licenses": ["Apache-2.0", "BSD-2-Clause", "MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T00:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T19:50:49.000Z", "avg_line_length": 43.0815822002, "max_line_length": 217, "alphanum_fraction": 0.5855450033, "num_tokens": 9228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.627717401654298}}
{"text": "#include <SOperations.h>\n\n#include <algorithm>                 // for min\n#include <boost/core/enable_if.hpp>  // for enable_if_c<>::type\n#include <cassert>                   // for assert\n#include <stdexcept>                 // for out_of_range\n\nusing namespace boost;\n\n// https://stackoverflow.com/questions/35971827/c-boost-rational-class-floor-function\nnamespace boost {\ntemplate <typename IntType>\nconstexpr IntType floor(rational<IntType> const &num) {\n  return static_cast<IntType>(num.numerator() / num.denominator());\n}\ntemplate <typename IntType>\nconstexpr IntType ceil(rational<IntType> const &num) {\n  auto inum = static_cast<IntType>(num.numerator() / num.denominator());\n  return (num == inum) ? inum : ((num.numerator() > 0) ? ++inum : --inum);\n}\n}  // namespace boost\n\n/*\nfor i in range(0,10):\n     if floor(i*delta)==floor((i+1)*delta):\n         print B[i-int(floor((i+1)*delta))],\n     else:\n         print A[int(floor(i*delta))],\n\ndeltaC = (deltaA*deltaB)/(deltaA+deltaB)\n*/\n\nrational<int> deltaHash(const rational<int> &arg1, const rational<int> &arg2) {\n  assert(arg1 + arg2 != 0);\n  return (arg1 * arg2) / (arg1 + arg2);\n}\n\nbool Hash(const rational<int> &deltaA, const rational<int> &deltaB, const int i,\n          int &retPos) {\n  assert(deltaA > 0);\n  assert(deltaB > 0);\n  const rational<int> delta = deltaB / (deltaA + deltaB);\n  bool ret = floor(delta * i) == floor(delta * (i + 1));\n  if (ret) {\n    retPos = i - (floor((i + 1) * delta));  // B\n  } else {\n    retPos = floor(i * delta);  // A\n  }\n  return ret;\n}\n\n/*\n#hash - begin\ndelta=deltaB/(deltaA+deltaB)\n\nfor i in range(0,24):\n    if int(i*delta)==int((i+1)*delta):\n        C.append( B[i-int((i+1)*delta)] )\n    else:\n        C.append( A[int(i*delta)] )\n#hash - end\n\n#div - begin\ndeltaC=(deltaA*deltaB)/(deltaA+deltaB)\n\ndeltaA_ = deltaB*deltaC/(deltaB-deltaC)\nassert(deltaA_ == deltaA)\nfrom math import ceil\nfor i in range(0,5) :\n    print C[i+int(ceil((i+1)*deltaA/deltaB))],    <--- tu jest to div\n#Output: 1 2 3 4 5\n\n#div- end\n*/\n\nint Div(const boost::rational<int> &deltaA, const boost::rational<int> &deltaB,\n        const int i) {\n  return i + ceil((i + 1) * deltaA / deltaB);\n}\n\n/*\n#hash - begin\ndelta=deltaB/(deltaA+deltaB)\n\nfor i in range(0,24):\n    if int(i*delta)==int((i+1)*delta):\n        C.append( B[i-int((i+1)*delta)] )\n    else:\n        C.append( A[int(i*delta)] )\n\n#hash - end\n\n#mod - begin\ndeltaC=(deltaA*deltaB)/(deltaA+deltaB)\n\ndeltaB_ = deltaA*deltaC/(deltaA-deltaC)\nassert(deltaB_ == deltaB)\nfor i in range(0,10) :\n    print C[i+int(i*deltaB/deltaA)],                <--- tu jest mod\n#Output: a b c d e f g h i j#\n\n#mod - end\n*/\n\nint Mod(const boost::rational<int> &deltaA, const boost::rational<int> &deltaB,\n        const int i) {\n  return i + floor(i * deltaB / deltaA);\n}\n\n/* Ta funkcja jest taka sama dla obu operacji */\n\nrational<int> deltaDivMod(const rational<int> &arg1,\n                          const rational<int> &arg2) {\n  assert(arg1 != arg2);\n  if (arg1 == arg2)\n    throw std::out_of_range(\"Delta are equal in DehashDiv - undefinied.\");\n  return (arg1 * arg2) / abs(arg1 - arg2);\n}\n\n/*\nfrom math import ceil\nfor i in range(0,10):\n    if deltaA > deltaB :\n        print C[int(ceil(i*deltaA/deltaB))][0],\n    else:\n        print C[i][0],\n*/\n\nrational<int> deltaSubstract(const rational<int> &arg1) { return arg1; }\n// todo\nint Substract(const rational<int> &deltaA, const rational<int> &deltaB,\n              const int i) {\n  return ceil(i * deltaA / deltaB);\n}\n\nrational<int> deltaAdd(const rational<int> &arg1, const rational<int> &arg2) {\n  return std::min(arg1, arg2);\n}\n\n/*\ndeltaC = min( deltaA,deltaB )\nfor i in range(0,10):\n     if deltaC == deltaA:\n         print str(A[i])+B[int(i*deltaA/deltaB)],\n     else:\n         print str(A[int(i*deltaB/deltaA)])+B[i],\n*/\n\nrational<int> deltaTimemove(const rational<int> &arg1,\n                            const rational<int> &arg2) {\n  return arg1;\n}\n\nint agse(int offset, int step) {\n  return floor(boost::rational<int>(offset) / boost::rational<int>(step));\n}\n", "meta": {"hexsha": "909823a6a9c29b94600c37d8d817b4a906f0eb7b", "size": 4034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/share/SOperations.cpp", "max_stars_repo_name": "michalwidera/abracadabradb", "max_stars_repo_head_hexsha": "13d4f66454b3b6af7e8353bd10186409230634e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-12-04T16:51:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T15:13:13.000Z", "max_issues_repo_path": "src/share/SOperations.cpp", "max_issues_repo_name": "michalwidera/abracadabradb", "max_issues_repo_head_hexsha": "13d4f66454b3b6af7e8353bd10186409230634e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-12-07T21:21:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-17T16:44:36.000Z", "max_forks_repo_path": "src/share/SOperations.cpp", "max_forks_repo_name": "michalwidera/abracadabradb", "max_forks_repo_head_hexsha": "13d4f66454b3b6af7e8353bd10186409230634e2", "max_forks_repo_licenses": ["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.6942675159, "max_line_length": 85, "alphanum_fraction": 0.6145265245, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6277173999712347}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n/*\n  boost::math::fft test for non-complex types\n  Use of DFT for Number Theoretical Transform.\n*/\n#include <boost/math/fft/bsl_backend.hpp>\nnamespace fft = boost::math::fft;\n\n#include <iostream>\n#include <vector>\n#include \"math_unit_test.hpp\"\n#include \"fft_test_helpers.hpp\"\n\nclass Z337\n{\npublic:\n  typedef int integer;\n  static constexpr integer mod{337};\n};\n\nvoid test_inverse()\n{\n  using M_int = fft::my_modulo_lib::mint<Z337>;\n  const M_int w{85};\n  const M_int inv_8{M_int{8}.inverse()};\n\n  std::vector<M_int> A{4, 3, 2, 1, 0, 0, 0, 0};\n  std::vector<M_int> FT_A,FT_FT_A;\n\n  fft::bsl_algebraic_transform::forward(A.cbegin(),A.cend(),std::back_inserter(FT_A),w);\n\n  fft::bsl_algebraic_transform::backward(FT_A.cbegin(),FT_A.cend(),std::back_inserter(FT_FT_A),w);\n\n  std::transform(FT_FT_A.begin(), FT_FT_A.end(), FT_FT_A.begin(),\n                 [&inv_8](M_int x) { return x * inv_8; });\n\n  int diff = 0;\n  for (size_t i = 0; i < A.size(); ++i)\n      diff += A[i] == FT_FT_A[i] ? 0 : 1;\n  CHECK_EQUAL(0,diff);\n}\nvoid test_convolution()\n/*\n  product of two integer by means of the NTT,\n  using the convolution theorem\n*/\n{\n  typedef fft::my_modulo_lib::field_modulo<int, 337> local_Z337;\n  using M_int = fft::my_modulo_lib::mint<local_Z337>;\n  const M_int w{85};\n  const M_int inv_8{M_int{8}.inverse()};\n\n  // Multiplying 1234 times 5678 = 7006652\n  std::vector<M_int> A{4, 3, 2, 1, 0, 0, 0, 0};\n  std::vector<M_int> B{8, 7, 6, 5, 0, 0, 0, 0};\n\n  // forward FFT\n  fft::bsl_algebraic_transform::forward(A.cbegin(),A.cend(),A.begin(), w);\n  fft::bsl_algebraic_transform::forward(B.cbegin(),B.cend(),B.begin(), w);\n\n  // convolution in Fourier space\n  std::vector<M_int> AB;\n  std::transform(A.begin(), A.end(), B.begin(),\n                 std::back_inserter(AB),\n                 [](M_int x, M_int y) { return x * y; });\n\n  // backwards FFT\n  fft::bsl_algebraic_transform::backward(AB.cbegin(),AB.cend(),AB.begin(),w);\n  std::transform(AB.begin(), AB.end(), AB.begin(),\n                 [&inv_8](M_int x) { return x * inv_8; });\n\n  // carry the remainders in base 10\n  std::vector<int> C;\n  M_int r{0};\n  for (auto x : AB)\n  {\n    auto y = x + r;\n    C.emplace_back(int(y) % 10);\n    r = M_int(int(y) / 10);\n  }\n  // yields 7006652\n  CHECK_EQUAL(8,static_cast<int>(C.size()));\n  CHECK_EQUAL(2,C[0]);\n  CHECK_EQUAL(5,C[1]);\n  CHECK_EQUAL(6,C[2]);\n  CHECK_EQUAL(6,C[3]);\n  CHECK_EQUAL(0,C[4]);\n  CHECK_EQUAL(0,C[5]);\n  CHECK_EQUAL(7,C[6]);\n  CHECK_EQUAL(0,C[7]);\n}\nint main()\n{\n  test_inverse();\n  test_convolution();\n  return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "60d6ac680db12031b122aa04af3e48c07c255457", "size": 2903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/fft_non-complex.cpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/fft_non-complex.cpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "test/fft_non-complex.cpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 27.9134615385, "max_line_length": 98, "alphanum_fraction": 0.6293489494, "num_tokens": 949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6276992053686932}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main()\n{\n  Matrix2d a;\n  a << 1, 2,\n       3, 4;\n  Vector3d v(1,2,3);\n  std::cout << \"a * 2.5 =\\n\" << a * 2.5 << std::endl;\n  std::cout << \"0.1 * v =\\n\" << 0.1 * v << std::endl;\n  std::cout << \"Doing v *= 2;\" << std::endl;\n  v *= 2;\n  std::cout << \"Now v =\\n\" << v << std::endl;\n}\n", "meta": {"hexsha": "d5f65b53e454951dc8ea0984b39ef46e800967e3", "size": 353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen-3.3/doc/examples/tut_arithmetic_scalar_mul_div.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/tut_arithmetic_scalar_mul_div.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/tut_arithmetic_scalar_mul_div.cpp", "max_forks_repo_name": "shareq2005/CarND-MPC-Project", "max_forks_repo_head_hexsha": "f4094e8b446d2fac2ca0a4c5054d5058621595b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1380.0, "max_forks_repo_forks_event_min_datetime": "2017-06-12T23:58:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:52:48.000Z", "avg_line_length": 19.6111111111, "max_line_length": 53, "alphanum_fraction": 0.4787535411, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6276439905543569}}
{"text": "#include <boost/property_tree/ini_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <complex>\n#include <cstddef>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <istream>\n#include <vector>\n\nusing std::complex;\nusing std::cout;\nusing std::int8_t;\nusing std::vector;\n\nnamespace pt = boost::property_tree;\nstruct Config {\n  double cxmin;\n  double cxmax;\n  double cymin;\n  double cymax;\n  size_t max_iterations;\n  size_t ixsize;\n  size_t iysize;\n  friend std::ostream &operator<<(std::ostream &stream, const Config &config) {\n    return stream << \"Config \\n\"\n                  << \"{ cxmin: \" << config.cxmin << \" ,cxmax: \" << config.cxmax\n                  << \"}\\n\"\n                  << \"{ cymin: \" << config.cymin << \" ,cymax: \" << config.cymax\n                  << \"}\\n\"\n                  << \" Number of iterations: \" << config.max_iterations << \"\\n\"\n                  << \"{ ixsize: \" << config.iysize\n                  << \" ,iysize: \" << config.ixsize << \"}\\n\";\n  }\n};\n\nclass Mandelbrot {\n  Config config;\n  vector<vector<int8_t>> image;\n\npublic:\n  Mandelbrot(Config config)\n      : config(config), image(config.iysize, vector<int8_t>(config.ixsize, 0)) {\n#ifdef DEBUG\n    cout << config;\n#endif\n  }\n\n  void compute() {\n    double cxmin = config.cxmin;\n    double cymin = config.cymin;\n    double cxmax = config.cxmax;\n    double cymax = config.cymax;\n\n    const int width = config.iysize;\n    const int height = config.ixsize;\n    const int num_pixels = width * height;\n\n    // const complex<double> center((cxmax - cxmin) / 2.0, (cymax - cymin) / 2.0);\n    const complex<double> begin = complex<double>(cxmin, cymin);\n    double xinc = (cxmax - cxmin) / width;\n    double yinc = (cymax - cymin) / height;\n\n#pragma omp parallel for schedule(dynamic)\n    for (int pix = 0; pix < num_pixels; ++pix) {\n      const int x = pix % width, y = pix / width;\n\n      complex<double> c = begin + complex<double>(y*yinc, x * xinc);\n      // cout <<  c << \" \" << x << \" \" << y << \"\\n\" ;\n\n      complex<double> z = c;\n      size_t iteration = 0;\n      for (; iteration < config.max_iterations; ++iteration) {\n        if (std::abs(z) >= 2)\n          break;\n        z = z * z + c;\n      }\n      // cout << x << \" \" << y << \" \" << iteration << \"\\n\";\n      if (iteration == config.max_iterations)\n        iteration = 4;\n\n      {\n        // TODO: Fix coloring\n        if (iteration != 4) {\n          image[x][y] = iteration % 4;\n        }\n      }\n    }\n  }\n\n  void serialize() {\n    for (auto row : image) {\n      for (auto pixel : row) {\n        cout << (pixel ? \"*\" : \" \");\n      }\n      cout << \"\\n\";\n    }\n  }\n\n  // Loosely based on https://github.com/skeeto/mandel-simd/blob/master/mandel.c\n  // TODO: Fix coloring\n  void write_image() {\n    uint8_t imgbuf[3 * config.iysize * config.ixsize];\n    const uint32_t color[] = {0xf53d3d, 0xf53d3d, 0xf53d93, 0xf53d93, 0xffffff};\n    const size_t width = config.iysize;\n    const int height = config.ixsize;\n    const int num_pixels = width * height;\n    for (int pix = 0; pix < num_pixels; ++pix) {\n      const int x = pix % width, y = pix / width;\n        // printf(\"%zu %zu %d\\n\", x, y, image[x][y]);\n        uint8_t pxlclr = color[image[x][y]];\n        // cout << y * 3 * config.ixsize + 3 * x << \"\\n\";\n        imgbuf[x * 3 * config.ixsize + 3 * y + 0] = pxlclr >> 16;\n        imgbuf[x * 3 * config.ixsize + 3 * y + 1] = pxlclr >> 8;\n        imgbuf[x * 3 * config.ixsize + 3 * y + 2] = pxlclr >> 0;\n    }\n    fprintf(stdout, \"P6\\n%zu %zu\\n%d\\n\", config.ixsize, config.iysize, 255);\n    fwrite(imgbuf, sizeof(imgbuf), 1, stdout);\n  }\n};\n\nint main(int argc, char **argv) {\n  pt::ptree tree;\n  pt::read_ini(\"./config.ini\", tree);\n\n  Mandelbrot mandel({\n      .cxmin = tree.get<double>(\"xmin\", -2.5),\n      .cxmax = tree.get<double>(\"xmax\", 1.5),\n\n      .cymin = tree.get<double>(\"ymin\", -2.5),\n      .cymax = tree.get<double>(\"ymax\", 1.5),\n\n      .max_iterations = tree.get<size_t>(\"max_iterations\", 256),\n\n      .ixsize = tree.get<size_t>(\"ixsize\", 1000),\n      .iysize = tree.get<size_t>(\"iysize\", 1000),\n  });\n  mandel.compute();\n#ifdef DEBUG\n  mandel.serialize();\n#endif\n  mandel.write_image();\n\n  return 0;\n}\n", "meta": {"hexsha": "49a6fe1ea0cf8c10393e2ccd302e43be23345774", "size": 4193, "ext": "cc", "lang": "C++", "max_stars_repo_path": "chapter-5/5.2/main.cc", "max_stars_repo_name": "Mark1626/road-to-plus-plus", "max_stars_repo_head_hexsha": "500db757051e32e6ccd144b70171c826527610d4", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-04T12:41:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-04T12:41:16.000Z", "max_issues_repo_path": "chapter-5/5.2/main.cc", "max_issues_repo_name": "Mark1626/road-to-plus-plus", "max_issues_repo_head_hexsha": "500db757051e32e6ccd144b70171c826527610d4", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter-5/5.2/main.cc", "max_forks_repo_name": "Mark1626/road-to-plus-plus", "max_forks_repo_head_hexsha": "500db757051e32e6ccd144b70171c826527610d4", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5238095238, "max_line_length": 82, "alphanum_fraction": 0.5602194133, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6275767043161181}}
{"text": "#include <math.h>\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"geometry.hpp\"\n\nnamespace cuauv {\nnamespace fishbowl {\n\nconst double singularity_cutoff = M_PI/2 * 0.985;\n\n// Sphere-sphere Sweep implementation from:\n// http://www.gamasutra.com/view/feature/131790/simple_intersection_tests_for_games.php?page=2\n\nbool quadratic(double a, double b, double c, double& r1, double& r2)\n{\n    double q = b * b - 4 * a * c;\n    if (q < 0) {\n        return false;\n    } else {\n        double sq = sqrt(q);\n        double d = 1 / (2 * a);\n        r1 = (-b + sq) * d;\n        r2 = (-b - sq) * d;\n        return true;\n    }\n}\n\nbool sphere_sphere_sweep(double ar, const Eigen::Vector3d& ax0, const Eigen::Vector3d& ax1,\n                         double br, const Eigen::Vector3d& bx0, const Eigen::Vector3d& bx1,\n                         double& t0, double& t1)\n{\n    Eigen::Vector3d av = ax1 - ax0;\n    Eigen::Vector3d bv = bx1 - bx0;\n    Eigen::Vector3d ab = bx0 - ax0;\n    Eigen::Vector3d abv = bv - av;\n    double abr = ar + br;\n    double a = abv.dot(abv);\n    double b = 2 * abv.dot(ab);\n    double c = ab.dot(ab) - abr * abr;\n\n    if (ab.dot(ab) <= abr * abr) {\n        t0 = 0;\n        t1 = 0;\n        return true;\n    }\n\n    if (quadratic(a, b, c, t0, t1)) {\n        if (t0 > t1) {\n            double x = t0;\n            t0 = t1;\n            t1 = x;\n        }\n        // t0 <= t1\n        return (0 <= t0 && t0 <= 1) || (t0 <= 0 && t1 >= 0);\n    }\n\n    return false;\n}\n\ndouble line_distance(const Eigen::Vector3d& x0, const Eigen::Vector3d& x1, const Eigen::Vector3d& x)\n{\n    const Eigen::Vector3d p = x1 - x0;\n    const Eigen::Vector3d y = x - x0;\n    const Eigen::Vector3d o = (y.dot(p) / p.dot(p)) * p;\n    const Eigen::Vector3d r = y - o;\n\n    return r.dot(r);\n}\n\nvoid swing_twist(const Eigen::Quaterniond& q, const Eigen::Vector3d& vt,\n                 Eigen::Quaterniond& swing, Eigen::Quaterniond& twist) {\n    Eigen::Vector3d p = vt * (q.x() * vt[0] + q.y() * vt[1] + q.z() * vt[2]);\n    twist = Eigen::Quaterniond(q.w(), p[0], p[1], p[2]);\n    twist.normalize();\n    swing = q * twist.conjugate();\n}\n\n\n// Behavior is undefined if q is not a unit quaternion.\n// uses body 3-2-1 convention (z, y, x; heading, pitch, roll)\n// see: NASA Mission Planning and Analysis Division. \"Euler Angles, quaternions, and transformation matrices\".\n// also see: http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/\n// their definitions of 'heading, attitude, and bank' are different from ours, but the equations still work\n// because their coordinate axes are just our coordinate axes rotated a bit, i.e., the relationships between\n// the axes are the same. Their heading = our pitch [y], attitude = heading [z], bank = roll [x].\n// euler[0] is the angle of rotation in radians around the x-axis, in the range [-pi, pi].\n// euler[1] \" y-axis, in the range [-pi/2, pi/2]\n// euler[2] \" z-axis, in the range [-pi, pi]\nEigen::Vector3d quat_to_euler(Eigen::Quaterniond q)\n{\n    Eigen::Vector3d euler;\n\n    // [q0 q1 q2 q3] is in w, x, y, z order\n    const double q0 = q.w();\n    const double q1 = q.x();\n    const double q2 = q.y();\n    const double q3 = q.z();\n\n    euler[0] = atan2(2*(q0*q1 + q2*q3), 1-2*(q1*q1 + q2*q2));\n    euler[1] = asin(2*(q0*q2 - q3*q1));\n    euler[2] = atan2(2*(q0*q3 + q1*q2), 1-2*(q2*q2 + q3*q3));\n\n    // Tentatively handle singularities.\n    if (euler[1] > singularity_cutoff || euler[1] < -singularity_cutoff) {\n        euler[0] = atan2(q3, q0);\n        euler[2] = 0;\n    }\n\n    // XX this makes the controller angry\n    //euler[0] = fmod(euler[0] + 2*M_PI, 2*M_PI);\n    //euler[1] = fmod(euler[1] + 2*M_PI, 2*M_PI);\n    //euler[2] = fmod(euler[2] + 2*M_PI, 2*M_PI);\n\n    return euler;\n}\n\n// body 3-2-1\nEigen::Quaterniond euler_to_quat(double h, double p, double r)\n{\n    return Eigen::Quaterniond(Eigen::AngleAxisd(h, Eigen::Vector3d::UnitZ())\n                            * Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY())\n                            * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()));\n}\n\n} // namespace fishbowl\n} // namespace cuauv\n", "meta": {"hexsha": "2221b3548c961355a67bf93e4709d899fdac6c37", "size": 4127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fishbowl/geometry.cpp", "max_stars_repo_name": "cuauv/software", "max_stars_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T18:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T09:04:02.000Z", "max_issues_repo_path": "fishbowl/geometry.cpp", "max_issues_repo_name": "cuauv/software", "max_issues_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-03T05:13:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-03T06:19:39.000Z", "max_forks_repo_path": "fishbowl/geometry.cpp", "max_forks_repo_name": "cuauv/software", "max_forks_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T17:29:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T14:15:12.000Z", "avg_line_length": 31.7461538462, "max_line_length": 110, "alphanum_fraction": 0.5842015992, "num_tokens": 1342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6275766931888125}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"Tools/Tools.h\"\n#include \"ICP.h\"\n\n\nusing namespace std;\nusing namespace Eigen;\n\n// Matrix4d SVDsolve(const MatrixXd &pts1, const MatrixXd &pts2)\nMatrix4d SVDsolve(const MatrixXd &pts1, const MatrixXd &pts2)\n{\n  Matrix4d T = MatrixXd::Identity(4,4);\n  Vector3d p1(0,0,0);\n  Vector3d p2(0,0,0);\n  int N = pts1.rows();\n  int m = pts1.cols();\n  // cout<<\"N:\" << N << \"   m:\"<< m << endl;\n  // cout<<\"pts1:\"<<pts1<< endl << \"pts2:\"<<pts2<<endl;\n  MatrixXd q1(N, m);\n  MatrixXd q2(N, m);\n\n  for (int i=0; i<N; i++){\n      p1 = p1 + pts1.block<1,3>(i,0).transpose();\n      p2 = p2 + pts2.block<1,3>(i,0).transpose();\n  };\n  p1 = p1/N;\n  p2 = p2/N;\n  // cout<<\"p1:\"<< p1 <<endl<< \"p2:\"<< p2 << endl;\n\n  for (int i=0; i<N; i++){\n      q1.block<1, 3>(i, 0) = pts1.block<1, 3>(i, 0) - p1.transpose();  //(starting at)  <block of size>\n      q2.block<1, 3>(i, 0) = pts2.block<1, 3>(i, 0) - p2.transpose();\n  };\n  // cout<<\"q1:\"<< q1 <<endl<< \"q2:\"<< q2 << endl;\n\n  MatrixXd W = q1.transpose() * q2;\n  // cout<<\"W:\"<<W<<endl;\n\n  JacobiSVD<MatrixXd> svd(W, ComputeThinU | ComputeThinV);\n    MatrixXd U = svd.matrixU();\n    MatrixXd V = svd.matrixV();\n    MatrixXd Vt = V.transpose();\n  // cout<<\"U:\"<<U<<endl<<\"V:\"<<V<<endl<<\"Vt:\"<<Vt<<endl;\n\n  MatrixXd R = Vt.transpose() * U.transpose();\n  // cout<<\"R:\"<<R<<endl;\n\n//   Matrix3d xx(3,3);\n//   xx<<1,1,1,\n//       1,1,1,\n//       1,1,1 ;\n//   xx.block<1,3>(2,0)*= -1;\n//   cout<<xx<<endl;\n\n  if(R.determinant() < 0){\n //R\u884c\u5217\u5f0f<0\n    Vt.block<1, 3>(2, 0) *= -1;       //\u7b2c\u4e09\u884c\u4e58\u4ee5-1\n    R = Vt.transpose() * U.transpose();\n    // cout<<\"Vt:\"<<Vt<<endl;\n  };\n  // cout<<\"R:\"<<R<<endl;\n  Vector3d t = p2 - R*p1;      //(3,1) - (3,3)(3,1) = (3,1)\n  // cout<<\"t:\"<<t<<endl;\n\n  T.block<3,3>(0,0) = R ;\n  T.block<3,1>(0,3) = t ;\n  // cout<<\"T\"<<T<<endl;\n  return T;\n};\n\n\nMatrixXd ICP(const MatrixXd pts1, const MatrixXd pts2, int max_iteration, float tolerance, float k ){\n  int m = pts1.cols();\n  int N1 = pts1.rows();\n  int N2 = pts2.rows();\n  MatrixXd src = MatrixXd::Ones(m+1, N1);    //(4, 12)\n  MatrixXd dst = MatrixXd::Ones(m+1, N2);    //(4, 12)\n  // cout<<\"src:\"<<src<<endl<<\"dst:\"<<dst<<endl;\n  src.block(0,0,m,N1) = pts1.transpose();       \n  dst.block(0,0,m,N2) = pts2.transpose();\n  // cout<<\"src:\"<<src<<endl<<\"dst:\"<<dst<<endl;\n\n  float prev_error = 0;\n  \n  for(int i =0; i<max_iteration; i++){\n    //   NEIGHBOR nearest_neighbot(src.block(0,0,m,N1), dst.block(0,0,m,N2));\n    //   NEIGHBOR nighbor = nearest_neighbot(src.block(0,0,m,N1).transpose(), dst.block(0,0,m,N2).transpose());\n      NEIGHBOR nighbor = nearest_neighbot(src.block(0,0,m,N1).transpose(), dst.block(0,0,m,N2).transpose());\n      std::vector<float> distance = nighbor.distances;\n      std::vector<int> indices = nighbor.indices;\n      float mean_error=0;\n      for(int i = 0; i<distance.size(); i++){\n          mean_error = mean_error + distance[i];\n          // cout<<\"distance:\"<<distance[i]<<endl;\n      };\n      mean_error = mean_error/distance.size();\n      cout<<\"mean_error:\"<<mean_error<<endl;\n      // for(int i = 0; i<indices.size(); i++){\n      // cout<<\"indices:\"<<indices[i]<<endl;};\n\n      int j = 0 ;\n      for (int i = 0; i<N1 ; i++){\n         if(distance[i]<=mean_error*k){\n             j = j+1;\n         };\n      };\n      cout<<\"\u6210\u529f\u5339\u914d:\"<<j<<\"\u5bf9\u70b9\"<<endl;\n\n\n      MatrixXd pts11 = MatrixXd::Ones(j, 3);\n      MatrixXd pts22 = MatrixXd::Ones(j, 3);\n      // cout<<\"pts11:\"<<pts11<<endl<<\"pts22:\"<<pts22<<endl;\n\n      // pts11.block<1,3>(0,0) = src.block<3,1>(0, 0);\n      // pts11.block<1,3>(1,0) = src.block<3,1>(0, 1);\n\n      int jj = 0;\n      for (int i =0; i<N1; i++){\n          if(distance[i]<= mean_error*k){\n              pts11.block<1,3>(jj,0) = src.block<3,1>(0, i);\n              pts22.block<1,3>(jj,0) = dst.block<3,1>(0, indices[i]);\n              jj = jj +1;\n                 }\n          }\n      cout<<\"pts11:\"<<pts11<<endl<<\"pts22:\"<<pts22<<endl;\n\n      MatrixXd T = SVDsolve(pts11, pts22);\n      cout << \"T:\" << T << endl;\n      src = T*src;\n\n      if (fabs(prev_error - mean_error) < tolerance){\n        break;\n      }\n      prev_error = mean_error;\n\n      }\n  MatrixXd T = SVDsolve(pts1, src.block(0,0,m,N1).transpose());\n\n  return T;\n\n};\n\n\n\n\n\n\n", "meta": {"hexsha": "111724fa24c15502f5f2c0a3606960162ba35a14", "size": 4235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ICP/ICPv3/ICP/ICP.cpp", "max_stars_repo_name": "Yihua-Ni/Tools", "max_stars_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ICP/ICPv3/ICP/ICP.cpp", "max_issues_repo_name": "Yihua-Ni/Tools", "max_issues_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICP/ICPv3/ICP/ICP.cpp", "max_forks_repo_name": "Yihua-Ni/Tools", "max_forks_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4228187919, "max_line_length": 111, "alphanum_fraction": 0.5246753247, "num_tokens": 1524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6275751306192627}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          http://www.mrpt.org/                          |\n   |                                                                        |\n   | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file     |\n   | See: http://www.mrpt.org/Authors - All rights reserved.                |\n   | Released under BSD License. See details in http://www.mrpt.org/License |\n   +------------------------------------------------------------------------+ */\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\nusing namespace Eigen;\nusing namespace std;\n\n/** A macro for obtaining the name of the current function:  */\n#if defined(_MSC_VER) && (_MSC_VER >= 1300)\n#define __CURRENT_FUNCTION_NAME__ __FUNCTION__\n#elif defined(_MSC_VER) && (_MSC_VER < 1300)\n// Visual C++ 6 HAS NOT A __FUNCTION__ equivalent.\n#define __CURRENT_FUNCTION_NAME__ ::system::extractFileName(__FILE__).c_str()\n#else\n#define __CURRENT_FUNCTION_NAME__ __PRETTY_FUNCTION__\n#endif\n\n#if 0\n\ntemplate <int ColRowOrder>\nvoid do_test_EigenVal4x4_sym_vs_generic_eigen()\n{\n\tusing Mat44 = Matrix<double,4,4,ColRowOrder>;\n\n\tconst double   dat_C1[] = {\n\t\t13.737245,10.248641,-5.839599,11.108320,\n\t\t10.248641,14.966139,-5.259922,11.662222,\n\t\t-5.839599,-5.259922,9.608822,-4.342505,\n\t\t11.108320,11.662222,-4.342505,12.121940 };\n\tconst Mat44 C1(dat_C1);  // It doesn't mind the row/col major order since data are symetric\n\n\t// Symetric --------------------\n\t// This solver returns the eigenvectors already sorted.\n\tEigen::SelfAdjointEigenSolver<Mat44> eigensolver(C1);\n//\tMatrixXd eVecs_s = eigensolver.eigenvectors();\n//\tMatrixXd eVals_s = eigensolver.eigenvalues();\n\n\tcout << endl << __CURRENT_FUNCTION_NAME__ << endl\n\t\t<< \"SelfAdjointEigenSolver:\\n\"\n\t\t<< \"eigvecs: \" << endl << eigensolver.eigenvectors() << endl\n\t\t<< \"eigvals: \" << endl << eigensolver.eigenvalues() << endl;\n\n\t// Generic ---------------------\n\tEigen::EigenSolver<Mat44> es(C1, true);\n//\tMatrixXd eVecs_g = es.eigenvectors().real();\n//\tMatrixXd eVals_g = es.eigenvalues().real();\n\n\tcout << endl\n\t\t<< \"EigenSolver:\\n\"\n\t\t<< \"eigvecs: \" << endl << es.eigenvectors() << endl\n\t\t<< \"eigvals: \" << endl << es.eigenvalues() << endl;\n}\n\n// Compare the two ways of computing matrix eigenvectors: generic & for symmetric matrices:\nTEST(MatricesEigen,EigenVal4x4_sym_vs_generic)\n{\n\tdo_test_EigenVal4x4_sym_vs_generic_eigen<Eigen::ColMajor>();\n\tdo_test_EigenVal4x4_sym_vs_generic_eigen<Eigen::RowMajor>();\n}\n\n#endif\n", "meta": {"hexsha": "8db121f46419dc075797991386e72ce70d4f5477", "size": 2597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/src/matrix_eigen_unittest.cpp", "max_stars_repo_name": "skair39/mrpt", "max_stars_repo_head_hexsha": "88238f8ac1abdcf15401e14dc3a9faa5c59ba559", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-02-20T02:36:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-20T02:46:51.000Z", "max_issues_repo_path": "libs/math/src/matrix_eigen_unittest.cpp", "max_issues_repo_name": "skair39/mrpt", "max_issues_repo_head_hexsha": "88238f8ac1abdcf15401e14dc3a9faa5c59ba559", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/src/matrix_eigen_unittest.cpp", "max_forks_repo_name": "skair39/mrpt", "max_forks_repo_head_hexsha": "88238f8ac1abdcf15401e14dc3a9faa5c59ba559", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1, "max_line_length": 92, "alphanum_fraction": 0.6168656142, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6274504012207814}}
{"text": "#pragma once\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <Eigen/Dense>\n\n#include \"numerical.hpp\"\n\nusing namespace std;\n\n/**\n * @brief \u66f2\u7ebf\u57fa\u7c7b\uff0c\u5b9a\u4e49\u4e86\u5fc5\u8981\u7684\u63a5\u53e3\n * @tparam N \u66f2\u7ebf\u9636\u6570\n * @tparam PointDim \u6570\u636e\u70b9\u6240\u5728\u7684\u7ef4\u5ea6\n */\ntemplate <int N = 3, int PointDim = 2>\nclass Curve\n{\nprotected:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    typedef Eigen::Matrix<double, PointDim, N+1> PointsType;\n\n    double length_ {-1};\n\n    /**\n     * @brief \u8be5\u65b9\u6cd5\u8ba1\u7b97 length_\n     */\n    virtual void computeLength()\n    {\n        auto df = [&](double t) -> double\n        {\n            return this->at(t,1).norm();\n        };\n        this->length_ = NumericalQuadrature::adaptive_simpson_3_8(df, 0, 1);\n    }\n\n    constexpr static const double EPS = 0.000001;\n\npublic:\n\n    typedef Eigen::Matrix<double, PointDim, 1>  PointType;\n\n    /**\n     * @brief \u8fd4\u56de\u8be5\u66f2\u7ebf\u7684\u957f\u5ea6\uff0c\u800c\u957f\u5ea6\u7684\u4fe1\u606f\u5e94\u5728 computeLength() \u4e2d\u8ba1\u7b97\u5b8c\u6210\n     * @return \u6d3e\u751f\u7c7b\u4e2d\u66f2\u7ebf\u7684\u957f\u5ea6\n     */\n    virtual const double& length() const {return length_;}\n\n    /**\n     * @brief \u8fd4\u56de\u53c2\u6570 $t$ \u4f4d\u7f6e\u66f2\u7ebf\u4e0a\u5bf9\u5e94\u7684\u70b9\u7684\u4f4d\u7f6e\uff0c\u6216$N$\u9636\u5bfc\u6570\n     * @param t \u53c2\u6570\u4f4d\u7f6e\uff0c\u5b9a\u4e49\u57df\u4e3a $[0,1]$\n     * @param derivative_order \u6c42\u89e3\u7684\u5bfc\u6570\u9636\u6b21\uff0c\u9ed8\u8ba4\u4e3a$0$\u9636\uff0c\u5373\u539f\u51fd\u6570\u503c\n     * @return $t$\u53c2\u6570\u4f4d\u7f6e\uff0c$N$\u9636\u5bfc\u6570\u7684\u503c\n     */\n    virtual PointType at(const double& t, const int& derivative_order = 0) const = 0;\n\n    /**\n    * @brief \u8fd4\u56de\u53c2\u6570 $t$ \u4f4d\u7f6e\u66f2\u7ebf\u4e0a\u5bf9\u5e94\u7684\u70b9\u7684\u4f4d\u7f6e\uff0c\u6216$N$\u9636\u5bfc\u6570\n    * @param t \u53c2\u6570\u4f4d\u7f6e\uff0c\u5b9a\u4e49\u57df\u4e3a $[0,1]$\n    * @param derivative_order \u6c42\u89e3\u7684\u5bfc\u6570\u9636\u6b21\uff0c\u9ed8\u8ba4\u4e3a$0$\u9636\uff0c\u5373\u539f\u51fd\u6570\u503c\n    * @return $t$\u53c2\u6570\u4f4d\u7f6e\uff0c$N$\u9636\u5bfc\u6570\u7684\u503c\n    */\n    virtual double findClosestParameter(const PointType& point, double init_param, const int& max_iter = 20) const\n    {\n        /**\n         * \u627e\u5230\u53c2\u6570u\u4f7f\u5f97\u79bb\u70b9p\u662f\u6700\u8fd1\u7684\uff0c\u5373\u6c42\u89e3\n         * f = (C(u)-p)*C'(u) = 0\n         * f'= C'(u)*C'(u) + (C(u)-p)*C''(u)\n         * \u5f53\u7ed9\u5b9au_{n+1} = u_{n} - f/f'\n         */\n        assert(max_iter>0);\n        double numerator, denominator;\n        for (int iter = 0; iter<max_iter; ++iter)\n        {\n            auto d = this->at(init_param) - point;\n            auto first_order  = this->at(init_param, 1);\n            auto second_order = this->at(init_param, 2);\n\n            numerator   = d.dot(first_order);\n            denominator = first_order.dot(first_order) + d.dot(second_order) + std::numeric_limits<double>::min();\n            init_param = init_param - numerator/denominator;\n        }\n\n        return init_param;\n    }\n\n    /**\n     * @brief \u5c06\u66f2\u7ebf\u7684\u53c2\u6570\u5185\u5bb9\u4f20\u9001\u5230\u8f93\u51fa\u6d41\u5bf9\u8c61\u4e2d\uff0c\u9ed8\u8ba4\u5fc5\u987b\u672b\u5c3e\u643a\u5e26 `\\n`\n     * @param out \u6d41\u5bf9\u8c61\uff0c\u4f8b\u5982std::cout, std::stringsteam\n     * @param s \u8bbe\u5b9a\u7684\u524d\u7f00\n     */\n    virtual void print(std::ostream& out, const std::string& s = \"\") const = 0;\n\n    /**\n     * @brief \u8fd1\u4f3c\u5730\u4ee5$delta$\u95f4\u8ddd\u5747\u5300\u91c7\u96c6\u70b9\n     * @param delta \u53c2\u6570\u95f4\u8ddd\u6216\u8005\u8ddd\u79bb\u95f4\u8ddd\uff0c\u7531$for_arc_length$\u6307\u5b9a\n     * @param arc_length_t \u8fd4\u56de\u6700\u7ec8\u5f97\u5230\u7684\u53c2\u6570\u4f4d\u7f6e\n     * @param for_arc_length \u5982\u679c\u4e3a`true`\uff0c\u5219$delta$\u4ee5\u957f\u5ea6\u4e3a\u5355\u4f4d\uff0c\u5426\u5219\u4ee5$t\\in [0,1]$\u53c2\u6570\u4e3a\u5355\u4f4d\n     * @param max_iter_time \u6700\u5927\u8fed\u4ee3\u6b21\u6570\n     * @return \u53c2\u6570\u5316\u91c7\u6837\u70b9\u6570\u636e\n     */\n    virtual vector<PointType> sampleWithArcLengthParameterized(const double& delta, vector<double>& arc_length_t, bool arc_length_base = true,\n                                                       const int& max_iter_time = 4)\n    {\n        const double avg_distance = arc_length_base? delta : this->length_ * delta;\n\n        const double avg_t = arc_length_base? avg_distance/this->length_  : delta;\n\n        assert( avg_distance >= 0 && avg_distance <= this->length_/2.0);\n\n        const int n (this->length_ / avg_distance);\n\n        vector<double> t_array(n, 0);\n        vector<double>   dists(n, 0);\n        vector<PointType> ret(n+1);       // \u5b9e\u9645\u4e0a\u603b\u5171\u6709 n+1 \u4e2a\u70b9\n        ret.front() = this->at(0.0);\n        ret.back() = this->at(1.0);\n\n        // \u7b2c\u4e00\u4e2a\u70b9\u4e0e\u6700\u540e\u4e00\u4e2a\u70b9\u4fdd\u6301\u5728\u5f00\u59cb\u4e0e\u7ed3\u5c3e\u5904\n        for(int i = 1; i < n; ++i)\n        {\n            t_array[i] = i * avg_t;\n            ret[i] = this->at(t_array[i]);\n        }\n        t_array.emplace_back(1.0);\n\n        double prev_offset = -1;\n\n        for(int iter = 0; iter < max_iter_time; ++iter)\n        {\n            // 1. \u8ba1\u7b97\u4e0a\u4e00\u6b21\u8fed\u4ee3\u786e\u5b9a\u7684 t \u53c2\u6570\u4e0b\uff0c\u6bcf\u4e00\u4e2a\u5206\u6bb5\u7684\u8fd1\u4f3c\u957f\u5ea6\n            for (int j = 1; j < n; j++) dists[j] = (ret[j]-ret[j-1]).norm();\n\n            double offset = 0;\n            for (int j = 1; j < n; j++)\n            {\n                // 2. \u7d2f\u8ba1\u8fd1\u4f3c\u5f27\u957f\u5e76\u8ba1\u7b97\u8bef\u5dee\n                offset += dists[j] - avg_distance;\n\n                // 3. Newton's method\n                double first_order  = this->at(t_array[j], 1).norm();\n                double second_order = this->at(t_array[j], 2).norm();\n                double numerator    = offset * first_order;\n                double denominator  = offset * second_order + first_order * first_order;\n\n                t_array[j] = t_array[j] - numerator / denominator;\n\n                ret[j] = this->at(t_array[j]);\n            }\n\n            if ( offset < EPS || abs(offset-prev_offset) < EPS)\n            {\n                break;\n            }\n            prev_offset = offset;\n        }\n\n        arc_length_t.swap(t_array);\n\n        return ret;\n    }\n\n    /**\n     * @brief \u5728\u53c2\u6570$t\\in[0, 1]$\u53d6\u4e0e\u5f27\u957f\u7ebf\u6027\u76f8\u5173\u70b9\n     * @param t \u5f27\u957f\u53c2\u6570\u5316\u4e0b\u7684\u53c2\u6570\u503c\uff0c$t\\in [0, 1]$\n     * @param arc_length_t \u8fd4\u56de\u6700\u7ec8\u8ba1\u7b97\u5f97\u5230\u7684\u53c2\u6570\u4f4d\u7f6e\n     * @param derivative_order \u7ed9\u5b9a\u7684\u9636\u6b21, \u9ed8\u8ba4\u4e3a0\u9636\n     * @param max_iter_time \u6700\u5927\u8fed\u4ee3\u6b21\u6570\n     * @return \u53c2\u6570\u5316\u70b9\u4f4d\u7f6e\n     */\n    virtual PointType atWithArcLengthParameterized(const double& t, double& arc_length_t, \n        const int& derivative_order = 0, const int& max_iter_time = 4)  const\n    {\n        assert(t >= 0.0 && t <= 1.0);\n\n        double approx_t = t, target_length = t * this->length_;\n        double prev_approx_t = approx_t;\n\n        const auto df = [&](double t) -> double{ return this->at(t, 1).norm(); };\n\n        for(int iter = 0; iter < max_iter_time; ++iter)\n        {\n            double approx_length = NumericalQuadrature::adaptive_simpson_3_8(df, 0, approx_t);\n            double d = approx_length - target_length;\n            if (abs(d) < EPS) break;\n\n            // Newton's method\n            double first_order  = this->at(approx_t, 1).norm();\n            double second_order = this->at(approx_t, 2).norm();\n            double numerator    = d * first_order;\n            double denominator  = d * second_order + first_order * first_order;\n\n            approx_t = approx_t - numerator / denominator;\n\n            if ( abs(approx_t-prev_approx_t) < EPS) break;\n            else prev_approx_t = approx_t;\n        }\n        arc_length_t = approx_t;\n        return this->at(approx_t, derivative_order);\n    }\n\n};", "meta": {"hexsha": "a5bf5dc59eb21517ad1e2c83b2c407d8d105cc12", "size": 6206, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/curve.hpp", "max_stars_repo_name": "tanzby/ParametricCurve", "max_stars_repo_head_hexsha": "52d0bba6da64f24ca4e345b9affb6801edb9e507", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-07-11T03:34:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T02:35:10.000Z", "max_issues_repo_path": "include/curve.hpp", "max_issues_repo_name": "gaows123/ParametricCurve", "max_issues_repo_head_hexsha": "52d0bba6da64f24ca4e345b9affb6801edb9e507", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/curve.hpp", "max_forks_repo_name": "gaows123/ParametricCurve", "max_forks_repo_head_hexsha": "52d0bba6da64f24ca4e345b9affb6801edb9e507", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T14:51:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T01:16:47.000Z", "avg_line_length": 30.4215686275, "max_line_length": 142, "alphanum_fraction": 0.5578472446, "num_tokens": 1984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6274504009461715}}
{"text": "/*******************************************************************************\nCopyright (c) 2011, Dr. D. Studios\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and/or other\nmaterials provided with the distribution.\nNeither the name of the Dr. D. Studios nor the names of its contributors may be\nused to endorse or promote products derived from this software without specific\nprior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\nOF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************/\n\n#ifndef _PIMATH_LINEALGO__H_\n#define _PIMATH_LINEALGO__H_\n\n#include <boost/python.hpp>\n#include <ImathVecAlgo.h>\n#include <ImathVec.h>\n#include \"util.h\"\n\nnamespace pimath\n{\n\tnamespace bp = boost::python;\n\n\n\ttemplate<typename T>\n\tstruct VecAlgoBind\n\t{\n\t\tVecAlgoBind()\n\t\t{\n\t\t\tbp::def(\"project\", Imath::project<T>);\n\t\t\tbp::def(\"orthogonal\", Imath::orthogonal<T>);\n\t\t\tbp::def(\"reflect\", Imath::reflect<T> );\n\t\t\tbp::def(\"closestVertex\", Imath::closestVertex<T> );\n\t\t}\n\t};\n}\n\n#endif\n\n", "meta": {"hexsha": "441519cd8d403d73b934dc9df980deaf8642db68", "size": 2113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/VecAlgo.hpp", "max_stars_repo_name": "madpianist/pimath", "max_stars_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-22T21:32:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T21:32:34.000Z", "max_issues_repo_path": "src/VecAlgo.hpp", "max_issues_repo_name": "madpianist/pimath", "max_issues_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/VecAlgo.hpp", "max_forks_repo_name": "madpianist/pimath", "max_forks_repo_head_hexsha": "d79c56d492887d52e1e6f7ec0ffa1966a4717b0a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0701754386, "max_line_length": 82, "alphanum_fraction": 0.7236157123, "num_tokens": 443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.627442347641985}}
{"text": "//  Copyright (c) 2000-2011 Joerg Walter, Mathias Koch, David Bellot\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  GeNeSys mbH & Co. KG in producing this work.\n\n#ifndef _BOOST_UBLAS_BLAS_\n#define _BOOST_UBLAS_BLAS_\n\n#include <boost/numeric/ublas/traits.hpp>\n\nnamespace boost { namespace numeric { namespace ublas {\n\n\n    /** Interface and implementation of BLAS level 1\n     * This includes functions which perform \\b vector-vector operations.\n     * More information about BLAS can be found at\n     * <a href=\"http://en.wikipedia.org/wiki/BLAS\">http://en.wikipedia.org/wiki/BLAS</a>\n     */\n    namespace blas_1 {\n\n        /** 1-Norm: \\f$\\sum_i |x_i|\\f$ (also called \\f$\\mathcal{L}_1\\f$ or Manhattan norm)\n     *\n     * \\param v a vector or vector expression\n     * \\return the 1-Norm with type of the vector's type\n     *\n     * \\tparam V type of the vector (not needed by default)\n     */\n        template<class V>\n        typename type_traits<typename V::value_type>::real_type\n        asum (const V &v) {\n            return norm_1 (v);\n        }\n\n        /** 2-Norm: \\f$\\sum_i |x_i|^2\\f$ (also called \\f$\\mathcal{L}_2\\f$ or Euclidean norm)\n     *\n     * \\param v a vector or vector expression\n     * \\return the 2-Norm with type of the vector's type\n     *\n     * \\tparam V type of the vector (not needed by default)\n     */\n        template<class V>\n        typename type_traits<typename V::value_type>::real_type\n        nrm2 (const V &v) {\n            return norm_2 (v);\n        }\n\n        /** Infinite-norm: \\f$\\max_i |x_i|\\f$ (also called \\f$\\mathcal{L}_\\infty\\f$ norm)\n     *\n     * \\param v a vector or vector expression\n     * \\return the Infinite-Norm with type of the vector's type\n     *\n     * \\tparam V type of the vector (not needed by default)\n     */\n        template<class V>\n        typename type_traits<typename V::value_type>::real_type\n        amax (const V &v) {\n            return norm_inf (v);\n        }\n\n        /** Inner product of vectors \\f$v_1\\f$ and \\f$v_2\\f$\n     *\n     * \\param v1 first vector of the inner product\n     * \\param v2 second vector of the inner product\n     * \\return the inner product of the type of the most generic type of the 2 vectors\n     *\n     * \\tparam V1 type of first vector (not needed by default)\n     * \\tparam V2 type of second vector (not needed by default)\n     */\n        template<class V1, class V2>\n        typename promote_traits<typename V1::value_type, typename V2::value_type>::promote_type\n        dot (const V1 &v1, const V2 &v2) {\n            return inner_prod (v1, v2);\n        }\n\n        /** Copy vector \\f$v_2\\f$ to \\f$v_1\\f$\n     *\n     * \\param v1 target vector\n     * \\param v2 source vector\n     * \\return a reference to the target vector\n     *\n     * \\tparam V1 type of first vector (not needed by default)\n     * \\tparam V2 type of second vector (not needed by default)\n     */\n        template<class V1, class V2>\n        V1 & copy (V1 &v1, const V2 &v2)\n    {\n            return v1.assign (v2);\n        }\n\n        /** Swap vectors \\f$v_1\\f$ and \\f$v_2\\f$\n     *\n     * \\param v1 first vector\n     * \\param v2 second vector\n     *\n         * \\tparam V1 type of first vector (not needed by default)\n     * \\tparam V2 type of second vector (not needed by default)\n     */\n    template<class V1, class V2>\n        void swap (V1 &v1, V2 &v2)\n    {\n            v1.swap (v2);\n        }\n\n        /** scale vector \\f$v\\f$ with scalar \\f$t\\f$\n     *\n     * \\param v vector to be scaled\n     * \\param t the scalar\n     * \\return \\c t*v\n     *\n     * \\tparam V type of the vector (not needed by default)\n     * \\tparam T type of the scalar (not needed by default)\n     */\n        template<class V, class T>\n        V & scal (V &v, const T &t)\n    {\n            return v *= t;\n        }\n\n        /** Compute \\f$v_1= v_1 +  t.v_2\\f$\n     *\n     * \\param v1 target and first vector\n     * \\param t the scalar\n     * \\param v2 second vector\n     * \\return a reference to the first and target vector\n     *\n     * \\tparam V1 type of the first vector (not needed by default)\n     * \\tparam T type of the scalar (not needed by default)\n     * \\tparam V2 type of the second vector (not needed by default)\n     */\n        template<class V1, class T, class V2>\n        V1 & axpy (V1 &v1, const T &t, const V2 &v2)\n    {\n            return v1.plus_assign (t * v2);\n        }\n\n    /** Performs rotation of points in the plane and assign the result to the first vector\n     *\n     * Each point is defined as a pair \\c v1(i) and \\c v2(i), being respectively\n     * the \\f$x\\f$ and \\f$y\\f$ coordinates. The parameters \\c t1 and \\t2 are respectively\n     * the cosine and sine of the angle of the rotation.\n     * Results are not returned but directly written into \\c v1.\n     *\n     * \\param t1 cosine of the rotation\n     * \\param v1 vector of \\f$x\\f$ values\n     * \\param t2 sine of the rotation\n     * \\param v2 vector of \\f$y\\f$ values\n     *\n     * \\tparam T1 type of the cosine value (not needed by default)\n     * \\tparam V1 type of the \\f$x\\f$ vector (not needed by default)\n     * \\tparam T2 type of the sine value (not needed by default)\n     * \\tparam V2 type of the \\f$y\\f$ vector (not needed by default)\n     */\n        template<class T1, class V1, class T2, class V2>\n        void rot (const T1 &t1, V1 &v1, const T2 &t2, V2 &v2)\n    {\n            typedef typename promote_traits<typename V1::value_type, typename V2::value_type>::promote_type promote_type;\n            vector<promote_type> vt (t1 * v1 + t2 * v2);\n            v2.assign (- t2 * v1 + t1 * v2);\n            v1.assign (vt);\n        }\n\n    }\n\n    /** \\brief Interface and implementation of BLAS level 2\n     * This includes functions which perform \\b matrix-vector operations.\n     * More information about BLAS can be found at\n     * <a href=\"http://en.wikipedia.org/wiki/BLAS\">http://en.wikipedia.org/wiki/BLAS</a>\n     */\n    namespace blas_2 {\n\n       /** \\brief multiply vector \\c v with triangular matrix \\c m\n    *\n    * \\param v a vector\n    * \\param m a triangular matrix\n    * \\return the result of the product\n    *\n    * \\tparam V type of the vector (not needed by default)\n    * \\tparam M type of the matrix (not needed by default)\n        */\n        template<class V, class M>\n        V & tmv (V &v, const M &m)\n    {\n            return v = prod (m, v);\n        }\n\n        /** \\brief solve \\f$m.x = v\\f$ in place, where \\c m is a triangular matrix\n     *\n     * \\param v a vector\n     * \\param m a matrix\n     * \\param C (this parameter is not needed)\n     * \\return a result vector from the above operation\n     *\n     * \\tparam V type of the vector (not needed by default)\n     * \\tparam M type of the matrix (not needed by default)\n     * \\tparam C n/a\n         */\n        template<class V, class M, class C>\n        V & tsv (V &v, const M &m, C)\n    {\n            return v = solve (m, v, C ());\n        }\n\n        /** \\brief compute \\f$ v_1 = t_1.v_1 + t_2.(m.v_2)\\f$, a general matrix-vector product\n     *\n     * \\param v1 a vector\n     * \\param t1 a scalar\n     * \\param t2 another scalar\n     * \\param m a matrix\n     * \\param v2 another vector\n     * \\return the vector \\c v1 with the result from the above operation\n     *\n     * \\tparam V1 type of first vector (not needed by default)\n     * \\tparam T1 type of first scalar (not needed by default)\n     * \\tparam T2 type of second scalar (not needed by default)\n     * \\tparam M type of matrix (not needed by default)\n     * \\tparam V2 type of second vector (not needed by default)\n         */\n        template<class V1, class T1, class T2, class M, class V2>\n        V1 & gmv (V1 &v1, const T1 &t1, const T2 &t2, const M &m, const V2 &v2)\n    {\n            return v1 = t1 * v1 + t2 * prod (m, v2);\n        }\n\n        /** \\brief Rank 1 update: \\f$ m = m + t.(v_1.v_2^T)\\f$\n     *\n     * \\param m a matrix\n     * \\param t a scalar\n     * \\param v1 a vector\n     * \\param v2 another vector\n     * \\return a matrix with the result from the above operation\n     *\n     * \\tparam M type of matrix (not needed by default)\n     * \\tparam T type of scalar (not needed by default)\n     * \\tparam V1 type of first vector (not needed by default)\n     * \\tparam V2type of second vector (not needed by default)\n     */\n        template<class M, class T, class V1, class V2>\n        M & gr (M &m, const T &t, const V1 &v1, const V2 &v2)\n    {\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n            return m += t * outer_prod (v1, v2);\n#else\n            return m = m + t * outer_prod (v1, v2);\n#endif\n        }\n\n        /** \\brief symmetric rank 1 update: \\f$m = m + t.(v.v^T)\\f$\n     *\n     * \\param m a matrix\n     * \\param t a scalar\n     * \\param v a vector\n     * \\return a matrix with the result from the above operation\n     *\n     * \\tparam M type of matrix (not needed by default)\n     * \\tparam T type of scalar (not needed by default)\n     * \\tparam V type of vector (not needed by default)\n     */\n        template<class M, class T, class V>\n        M & sr (M &m, const T &t, const V &v)\n    {\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n            return m += t * outer_prod (v, v);\n#else\n            return m = m + t * outer_prod (v, v);\n#endif\n        }\n\n        /** \\brief hermitian rank 1 update: \\f$m = m + t.(v.v^H)\\f$\n     *\n     * \\param m a matrix\n     * \\param t a scalar\n     * \\param v a vector\n     * \\return a matrix with the result from the above operation\n     *\n     * \\tparam M type of matrix (not needed by default)\n     * \\tparam T type of scalar (not needed by default)\n     * \\tparam V type of vector (not needed by default)\n     */\n        template<class M, class T, class V>\n        M & hr (M &m, const T &t, const V &v)\n    {\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n            return m += t * outer_prod (v, conj (v));\n#else\n            return m = m + t * outer_prod (v, conj (v));\n#endif\n        }\n\n         /** \\brief symmetric rank 2 update: \\f$ m=m+ t.(v_1.v_2^T + v_2.v_1^T)\\f$\n      *\n      * \\param m a matrix\n      * \\param t a scalar\n      * \\param v1 a vector\n      * \\param v2 another vector\n      * \\return a matrix with the result from the above operation\n      *\n      * \\tparam M type of matrix (not needed by default)\n      * \\tparam T type of scalar (not needed by default)\n      * \\tparam V1 type of first vector (not needed by default)\n      * \\tparam V2type of second vector (not needed by default)\n          */\n        template<class M, class T, class V1, class V2>\n        M & sr2 (M &m, const T &t, const V1 &v1, const V2 &v2)\n    {\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n            return m += t * (outer_prod (v1, v2) + outer_prod (v2, v1));\n#else\n            return m = m + t * (outer_prod (v1, v2) + outer_prod (v2, v1));\n#endif\n        }\n\n        /** \\brief hermitian rank 2 update: \\f$m=m+t.(v_1.v_2^H) + v_2.(t.v_1)^H)\\f$\n     *\n     * \\param m a matrix\n     * \\param t a scalar\n     * \\param v1 a vector\n     * \\param v2 another vector\n     * \\return a matrix with the result from the above operation\n     *\n     * \\tparam M type of matrix (not needed by default)\n     * \\tparam T type of scalar (not needed by default)\n     * \\tparam V1 type of first vector (not needed by default)\n     * \\tparam V2type of second vector (not needed by default)\n         */\n        template<class M, class T, class V1, class V2>\n        M & hr2 (M &m, const T &t, const V1 &v1, const V2 &v2)\n    {\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n            return m += t * outer_prod (v1, conj (v2)) + type_traits<T>::conj (t) * outer_prod (v2, conj (v1));\n#else\n            return m = m + t * outer_prod (v1, conj (v2)) + type_traits<T>::conj (t) * outer_prod (v2, conj (v1));\n#endif\n        }\n\n    }\n\n    /** \\brief Interface and implementation of BLAS level 3\n     * This includes functions which perform \\b matrix-matrix operations.\n     * More information about BLAS can be found at\n     * <a href=\"http://en.wikipedia.org/wiki/BLAS\">http://en.wikipedia.org/wiki/BLAS</a>\n     */\n    namespace blas_3 {\n\n        /** \\brief triangular matrix multiplication \\f$m_1=t.m_2.m_3\\f$ where \\f$m_2\\f$ and \\f$m_3\\f$ are triangular\n     *\n     * \\param m1 a matrix for storing result\n     * \\param t a scalar\n     * \\param m2 a triangular matrix\n     * \\param m3 a triangular matrix\n     * \\return the matrix \\c m1\n     *\n     * \\tparam M1 type of the result matrix (not needed by default)\n     * \\tparam T type of the scalar (not needed by default)\n     * \\tparam M2 type of the first triangular matrix (not needed by default)\n     * \\tparam M3 type of the second triangular matrix (not needed by default)\n     *\n        */\n        template<class M1, class T, class M2, class M3>\n        M1 & tmm (M1 &m1, const T &t, const M2 &m2, const M3 &m3)\n    {\n            return m1 = t * prod (m2, m3);\n        }\n\n        /** \\brief triangular solve \\f$ m_2.x = t.m_1\\f$ in place, \\f$m_2\\f$ is a triangular matrix\n     *\n     * \\param m1 a matrix\n     * \\param t a scalar\n     * \\param m2 a triangular matrix\n     * \\param C (not used)\n     * \\return the \\f$m_1\\f$ matrix\n     *\n     * \\tparam M1 type of the first matrix (not needed by default)\n     * \\tparam T type of the scalar (not needed by default)\n     * \\tparam M2 type of the triangular matrix (not needed by default)\n     * \\tparam C (n/a)\n         */\n        template<class M1, class T, class M2, class C>\n        M1 & tsm (M1 &m1, const T &t, const M2 &m2, C)\n    {\n            return m1 = solve (m2, t * m1, C ());\n        }\n\n        /** \\brief general matrix multiplication \\f$m_1=t_1.m_1 + t_2.m_2.m_3\\f$\n     *\n     * \\param m1 first matrix\n     * \\param t1 first scalar\n     * \\param t2 second scalar\n     * \\param m2 second matrix\n     * \\param m3 third matrix\n     * \\return the matrix \\c m1\n     *\n     * \\tparam M1 type of the first matrix (not needed by default)\n     * \\tparam T1 type of the first scalar (not needed by default)\n     * \\tparam T2 type of the second scalar (not needed by default)\n     * \\tparam M2 type of the second matrix (not needed by default)\n     * \\tparam M3 type of the third matrix (not needed by default)\n         */\n        template<class M1, class T1, class T2, class M2, class M3>\n        M1 & gmm (M1 &m1, const T1 &t1, const T2 &t2, const M2 &m2, const M3 &m3)\n    {\n            return m1 = t1 * m1 + t2 * prod (m2, m3);\n        }\n\n        /** \\brief symmetric rank \\a k update: \\f$m_1=t.m_1+t_2.(m_2.m_2^T)\\f$\n     *\n     * \\param m1 first matrix\n     * \\param t1 first scalar\n     * \\param t2 second scalar\n     * \\param m2 second matrix\n     * \\return matrix \\c m1\n     *\n     * \\tparam M1 type of the first matrix (not needed by default)\n     * \\tparam T1 type of the first scalar (not needed by default)\n     * \\tparam T2 type of the second scalar (not needed by default)\n     * \\tparam M2 type of the second matrix (not needed by default)\n     * \\todo use opb_prod()\n         */\n        template<class M1, class T1, class T2, class M2>\n        M1 & srk (M1 &m1, const T1 &t1, const T2 &t2, const M2 &m2)\n    {\n            return m1 = t1 * m1 + t2 * prod (m2, trans (m2));\n        }\n\n        /** \\brief hermitian rank \\a k update: \\f$m_1=t.m_1+t_2.(m_2.m2^H)\\f$\n     *\n     * \\param m1 first matrix\n     * \\param t1 first scalar\n     * \\param t2 second scalar\n     * \\param m2 second matrix\n     * \\return matrix \\c m1\n     *\n     * \\tparam M1 type of the first matrix (not needed by default)\n     * \\tparam T1 type of the first scalar (not needed by default)\n     * \\tparam T2 type of the second scalar (not needed by default)\n     * \\tparam M2 type of the second matrix (not needed by default)\n     * \\todo use opb_prod()\n         */\n        template<class M1, class T1, class T2, class M2>\n        M1 & hrk (M1 &m1, const T1 &t1, const T2 &t2, const M2 &m2)\n    {\n            return m1 = t1 * m1 + t2 * prod (m2, herm (m2));\n        }\n\n        /** \\brief generalized symmetric rank \\a k update: \\f$m_1=t_1.m_1+t_2.(m_2.m3^T)+t_2.(m_3.m2^T)\\f$\n     *\n     * \\param m1 first matrix\n     * \\param t1 first scalar\n     * \\param t2 second scalar\n     * \\param m2 second matrix\n     * \\param m3 third matrix\n     * \\return matrix \\c m1\n     *\n     * \\tparam M1 type of the first matrix (not needed by default)\n     * \\tparam T1 type of the first scalar (not needed by default)\n     * \\tparam T2 type of the second scalar (not needed by default)\n     * \\tparam M2 type of the second matrix (not needed by default)\n     * \\tparam M3 type of the third matrix (not needed by default)\n     * \\todo use opb_prod()\n         */\n        template<class M1, class T1, class T2, class M2, class M3>\n        M1 & sr2k (M1 &m1, const T1 &t1, const T2 &t2, const M2 &m2, const M3 &m3)\n    {\n            return m1 = t1 * m1 + t2 * (prod (m2, trans (m3)) + prod (m3, trans (m2)));\n        }\n\n        /** \\brief generalized hermitian rank \\a k update: * \\f$m_1=t_1.m_1+t_2.(m_2.m_3^H)+(m_3.(t_2.m_2)^H)\\f$\n     *\n     * \\param m1 first matrix\n     * \\param t1 first scalar\n     * \\param t2 second scalar\n     * \\param m2 second matrix\n     * \\param m3 third matrix\n     * \\return matrix \\c m1\n     *\n     * \\tparam M1 type of the first matrix (not needed by default)\n     * \\tparam T1 type of the first scalar (not needed by default)\n     * \\tparam T2 type of the second scalar (not needed by default)\n     * \\tparam M2 type of the second matrix (not needed by default)\n     * \\tparam M3 type of the third matrix (not needed by default)\n     * \\todo use opb_prod()\n         */\n        template<class M1, class T1, class T2, class M2, class M3>\n        M1 & hr2k (M1 &m1, const T1 &t1, const T2 &t2, const M2 &m2, const M3 &m3)\n    {\n            return m1 =\n              t1 * m1\n            + t2 * prod (m2, herm (m3))\n            + type_traits<T2>::conj (t2) * prod (m3, herm (m2));\n        }\n\n    }\n\n}}}\n\n#endif\n", "meta": {"hexsha": "934543376322e27af15666dd20358c9a095d0d62", "size": 17892, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/numeric/ublas/blas.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/numeric/ublas/blas.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/numeric/ublas/blas.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 35.784, "max_line_length": 121, "alphanum_fraction": 0.581824279, "num_tokens": 5348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6274423335865921}}
{"text": "\n//\n// Copyright (c) 2012 Ronaldo Carpio\n//\n// Permission to use, copy, modify, distribute and sell this software\n// and its documentation for any purpose is hereby granted without fee,\n// provided that the above copyright notice appear in all copies and\n// that both that copyright notice and this permission notice appear\n// in supporting documentation.  The authors make no representations\n// about the suitability of this software for any purpose.\n// It is provided \"as is\" without express or implied warranty.\n//\n\n/*\nThis is a C++ header-only library for N-dimensional linear interpolation on a\nrectangular grid. Implements two methods:\n* Multilinear: Interpolate using the N-dimensional hypercube containing the\npoint. Interpolation step is O(2^N)\n* Simplicial: Interpolate using the N-dimensional simplex containing the point.\nInterpolation step is O(N log N), but less accurate. Requires boost/multi_array\nlibrary.\n\nFor a description of the algorithms, see:\n* Weiser & Zarantonello (1988), \"A Note on Piecewise Linear and Multilinear\nTable Interpolation in Many Dimensions\", _Mathematics of Computation_ 50 (181),\np. 189-196\n* Davies (1996), \"Multidimensional Triangulation and Interpolation for\nReinforcement Learning\", _Proceedings of Neural Information Processing Systems\n1996_\n*/\n\n#ifndef _linterp_h\n#define _linterp_h\n\n#include <array>\n#include <assert.h>\n#include <cstdarg>\n#include <float.h>\n#include <functional>\n#include <math.h>\n#include <stdarg.h>\n#include <string>\n#include <vector>\n\n#include <boost/multi_array.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/storage.hpp>\n\nusing std::array;\nusing std::vector;\ntypedef unsigned int uint;\ntypedef vector<int> iVec;\ntypedef vector<double> dVec;\n\n// TODO:\n//  - specify behavior past grid boundaries.\n//    1) clamp\n//    2) return a pre-determined value (e.g. NaN)\n\n// compile-time params:\n//   1) number of dimensions\n//   2) scalar type T\n//   3) copy data or not (default: false). The grids will always be copied\n//   4) ref count class (default: none)\n//   5) continuous or not\n\n// run-time constructor params:\n//   1) f\n//   2) grids\n//   3) behavior outside grid: default=clamp\n//   4) value to return outside grid, defaut=nan\n\nstruct EmptyClass {};\n\ntemplate <int N, class T, bool CopyData = true, bool Continuous = true,\n          class ArrayRefCountT = EmptyClass, class GridRefCountT = EmptyClass>\nclass NDInterpolator {\npublic:\n  typedef T value_type;\n  typedef ArrayRefCountT array_ref_count_type;\n  typedef GridRefCountT grid_ref_count_type;\n\n  static const int m_N = N;\n  static const bool m_bCopyData = CopyData;\n  static const bool m_bContinuous = Continuous;\n\n  typedef boost::numeric::ublas::array_adaptor<T> grid_type;\n  typedef boost::const_multi_array_ref<T, N> array_type;\n  typedef std::unique_ptr<array_type> array_type_ptr;\n\n  array_type_ptr m_pF;\n  ArrayRefCountT m_ref_F; // reference count for m_pF\n  vector<T> m_F_copy;     // if CopyData == true, this holds the copy of F\n\n  vector<grid_type> m_grid_list;\n  vector<GridRefCountT> m_grid_ref_list; // reference counts for grids\n  vector<vector<T>> m_grid_copy_list;    // if CopyData == true, this holds the\n                                         // copies of the grids\n\n  // constructors assume that [f_begin, f_end) is a contiguous array in C-order\n  // non ref-counted constructor.\n  template <class IterT1, class IterT2, class IterT3>\n  NDInterpolator(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin,\n                 IterT3 f_end) {\n    init(grids_begin, grids_len_begin, f_begin, f_end);\n  }\n\n  // ref-counted constructor\n  template <class IterT1, class IterT2, class IterT3, class RefCountIterT>\n  NDInterpolator(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin,\n                 IterT3 f_end, ArrayRefCountT &refF,\n                 RefCountIterT grid_refs_begin) {\n    init_refcount(grids_begin, grids_len_begin, f_begin, f_end, refF,\n                  grid_refs_begin);\n  }\n\n  template <class IterT1, class IterT2, class IterT3>\n  void init(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin,\n            IterT3 f_end) {\n    set_grids(grids_begin, grids_len_begin, m_bCopyData);\n    set_f_array(f_begin, f_end, m_bCopyData);\n  }\n  template <class IterT1, class IterT2, class IterT3, class RefCountIterT>\n  void init_refcount(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin,\n                     IterT3 f_end, ArrayRefCountT &refF,\n                     RefCountIterT grid_refs_begin) {\n    set_grids(grids_begin, grids_len_begin, m_bCopyData);\n    set_grids_refcount(grid_refs_begin, grid_refs_begin + N);\n    set_f_array(f_begin, f_end, m_bCopyData);\n    set_f_refcount(refF);\n  }\n\n  template <class IterT1, class IterT2>\n  void set_grids(IterT1 grids_begin, IterT2 grids_len_begin, bool bCopy) {\n    m_grid_list.clear();\n    m_grid_ref_list.clear();\n    m_grid_copy_list.clear();\n    for (int i = 0; i < N; i++) {\n      int gridLength = grids_len_begin[i];\n      if (bCopy == false) {\n        T const *grid_ptr = &(*grids_begin[i]);\n        m_grid_list.push_back(\n            grid_type(gridLength, (T *)grid_ptr)); // use the given pointer\n      } else {\n        m_grid_copy_list.push_back(\n            vector<T>(grids_begin[i],\n                      grids_begin[i] +\n                          grids_len_begin[i])); // make our own copy of the grid\n        T *begin = &(m_grid_copy_list[i][0]);\n        m_grid_list.push_back(grid_type(gridLength, begin)); // use our copy\n      }\n    }\n  }\n  template <class IterT1, class RefCountIterT>\n  void set_grids_refcount(RefCountIterT refs_begin, RefCountIterT refs_end) {\n    assert(refs_end - refs_begin == N);\n    m_grid_ref_list.assign(refs_begin, refs_begin + N);\n  }\n\n  // assumes that [f_begin, f_end) is a contiguous array in C-order\n  template <class IterT>\n  void set_f_array(IterT f_begin, IterT f_end, bool bCopy) {\n    unsigned int nGridPoints = 1;\n    array<int, N> sizes;\n    for (unsigned int i = 0; i < m_grid_list.size(); i++) {\n      sizes[i] = m_grid_list[i].size();\n      nGridPoints *= sizes[i];\n    }\n\n    int f_len = f_end - f_begin;\n    if ((m_bContinuous && f_len != nGridPoints) ||\n        (!m_bContinuous && f_len != 2 * nGridPoints)) {\n      throw std::invalid_argument(\"f has wrong size\");\n    }\n    for (unsigned int i = 0; i < m_grid_list.size(); i++) {\n      if (!m_bContinuous) {\n        sizes[i] *= 2;\n      }\n    }\n\n    m_F_copy.clear();\n    if (bCopy == false) {\n      m_pF.reset(new array_type(f_begin, sizes));\n    } else {\n      m_F_copy = vector<T>(f_begin, f_end);\n      m_pF.reset(new array_type(&m_F_copy[0], sizes));\n    }\n  }\n  void set_f_refcount(ArrayRefCountT &refF) { m_ref_F = refF; }\n\n  // -1 is before the first grid point\n  // N-1 (where grid.size() == N) is after the last grid point\n  int find_cell(int dim, T x) const {\n    grid_type const &grid(m_grid_list[dim]);\n    if (x < *(grid.begin()))\n      return -1;\n    else if (x >= *(grid.end() - 1))\n      return grid.size() - 1;\n    else {\n      auto i_upper = std::upper_bound(grid.begin(), grid.end(), x);\n      return i_upper - grid.begin() - 1;\n    }\n  }\n\n  // return the value of f at the given cell and vertex\n  T get_f_val(array<int, N> const &cell_index,\n              array<int, N> const &v_index) const {\n    array<int, N> f_index;\n\n    if (m_bContinuous) {\n      for (int i = 0; i < N; i++) {\n        if (cell_index[i] < 0) {\n          f_index[i] = 0;\n        } else if (cell_index[i] >= m_grid_list[i].size() - 1) {\n          f_index[i] = m_grid_list[i].size() - 1;\n        } else {\n          f_index[i] = cell_index[i] + v_index[i];\n        }\n      }\n    } else {\n      for (int i = 0; i < N; i++) {\n        if (cell_index[i] < 0) {\n          f_index[i] = 0;\n        } else if (cell_index[i] >= m_grid_list[i].size() - 1) {\n          f_index[i] = (2 * m_grid_list[i].size()) - 1;\n        } else {\n          f_index[i] = 1 + (2 * cell_index[i]) + v_index[i];\n        }\n      }\n    }\n    return (*m_pF)(f_index);\n  }\n\n  T get_f_val(array<int, N> const &cell_index, int v) const {\n    array<int, N> v_index;\n    for (int dim = 0; dim < N; dim++) {\n      v_index[dim] = (v >> (N - dim - 1)) & 1; // test if the i-th bit is set\n    }\n    return get_f_val(cell_index, v_index);\n  }\n};\n\ntemplate <int N, class T, bool CopyData = true, bool Continuous = true,\n          class ArrayRefCountT = EmptyClass, class GridRefCountT = EmptyClass>\nclass InterpSimplex : public NDInterpolator<N, T, CopyData, Continuous,\n                                            ArrayRefCountT, GridRefCountT> {\npublic:\n  typedef NDInterpolator<N, T, CopyData, Continuous, ArrayRefCountT,\n                         GridRefCountT>\n      super;\n\n  template <class IterT1, class IterT2, class IterT3>\n  InterpSimplex(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin,\n                IterT3 f_end)\n      : super(grids_begin, grids_len_begin, f_begin, f_end) {}\n  template <class IterT1, class IterT2, class IterT3, class RefCountIterT>\n  InterpSimplex(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin,\n                IterT3 f_end, ArrayRefCountT &refF, RefCountIterT ref_begins)\n      : super(grids_begin, grids_len_begin, f_begin, f_end, refF, ref_begins) {}\n\n  template <class IterT> T interp(IterT x_begin) const {\n    array<T, 1> result;\n    array<array<T, 1>, N> coord_iter;\n    for (int i = 0; i < N; i++) {\n      coord_iter[i][0] = x_begin[i];\n    }\n    interp_vec(1, coord_iter.begin(), coord_iter.end(), result.begin());\n    return result[0];\n  }\n\n  template <class IterT1, class IterT2>\n  void interp_vec(int n, IterT1 coord_iter_begin, IterT1 coord_iter_end,\n                  IterT2 i_result) const {\n    assert(N == coord_iter_end - coord_iter_begin);\n\n    array<int, N> cell_index, v_index;\n    array<std::pair<T, int>, N> xipair;\n    int c;\n    T y, v0, v1;\n    // mexPrintf(\"%d\\n\", n);\n    for (int i = 0; i < n; i++) { // for each point\n      for (int dim = 0; dim < N; dim++) {\n        typename super::grid_type const &grid(super::m_grid_list[dim]);\n        c = this->find_cell(dim, coord_iter_begin[dim][i]);\n        // mexPrintf(\"%d\\n\", c);\n        if (c == -1) { // before first grid point\n          y = 1.0;\n        } else if (c == grid.size() - 1) { // after last grid point\n          y = 0.0;\n        } else {\n          // mexPrintf(\"%f %f\\n\", grid[c], grid[c+1]);\n          y = (coord_iter_begin[dim][i] - grid[c]) / (grid[c + 1] - grid[c]);\n          if (y < 0.0)\n            y = 0.0;\n          else if (y > 1.0)\n            y = 1.0;\n        }\n        xipair[dim].first = y;\n        xipair[dim].second = dim;\n        cell_index[dim] = c;\n      }\n      // sort xi's and get the permutation\n      std::sort(xipair.begin(), xipair.end(),\n                [](std::pair<T, int> const &a, std::pair<T, int> const &b) {\n                  return (a.first < b.first);\n                });\n      // walk the vertices of the simplex determined by the permutation\n      for (int j = 0; j < N; j++) {\n        v_index[j] = 1;\n      }\n      v0 = this->get_f_val(cell_index, v_index);\n      y = v0;\n      for (int j = 0; j < N; j++) {\n        v_index[xipair[j].second]--;\n        v1 = this->get_f_val(cell_index, v_index);\n        y += (1.0 - xipair[j].first) * (v1 - v0); // interpolate\n        v0 = v1;\n      }\n      *i_result++ = y;\n    }\n  }\n};\n\ntemplate <int N, class T, bool CopyData = true, bool Continuous = true,\n          class ArrayRefCountT = EmptyClass, class GridRefCountT = EmptyClass>\nclass InterpMultilinear : public NDInterpolator<N, T, CopyData, Continuous,\n                                                ArrayRefCountT, GridRefCountT> {\npublic:\n  typedef NDInterpolator<N, T, CopyData, Continuous, ArrayRefCountT,\n                         GridRefCountT>\n      super;\n\n  template <class IterT1, class IterT2, class IterT3>\n  InterpMultilinear(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin,\n                    IterT3 f_end)\n      : super(grids_begin, grids_len_begin, f_begin, f_end) {}\n  template <class IterT1, class IterT2, class IterT3, class RefCountIterT>\n  InterpMultilinear(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin,\n                    IterT3 f_end, ArrayRefCountT &refF,\n                    RefCountIterT ref_begins)\n      : super(grids_begin, grids_len_begin, f_begin, f_end, refF, ref_begins) {}\n\n  template <class IterT1, class IterT2>\n  static T linterp_nd_unitcube(IterT1 f_begin, IterT1 f_end, IterT2 xi_begin,\n                               IterT2 xi_end) {\n    int n = xi_end - xi_begin;\n    int f_len = f_end - f_begin;\n    assert(1 << n == f_len);\n    T sub_lower, sub_upper;\n    if (n == 1) {\n      sub_lower = f_begin[0];\n      sub_upper = f_begin[1];\n    } else {\n      sub_lower = linterp_nd_unitcube(f_begin, f_begin + (f_len / 2),\n                                      xi_begin + 1, xi_end);\n      sub_upper = linterp_nd_unitcube(f_begin + (f_len / 2), f_end,\n                                      xi_begin + 1, xi_end);\n    }\n    T result = sub_lower + (*xi_begin) * (sub_upper - sub_lower);\n    return result;\n  }\n\n  template <class IterT> T interp(IterT x_begin) const {\n    array<T, 1> result;\n    array<array<T, 1>, N> coord_iter;\n    for (int i = 0; i < N; i++) {\n      coord_iter[i][0] = x_begin[i];\n    }\n    interp_vec(1, coord_iter.begin(), coord_iter.end(), result.begin());\n    return result[0];\n  }\n\n  template <class IterT1, class IterT2>\n  void interp_vec(int n, IterT1 coord_iter_begin, IterT1 coord_iter_end,\n                  IterT2 i_result) const {\n    assert(N == coord_iter_end - coord_iter_begin);\n    array<int, N> index;\n    int c;\n    T y, xi;\n    vector<T> f(1 << N);\n    array<T, N> x;\n\n    for (int i = 0; i < n; i++) {         // loop over each point\n      for (int dim = 0; dim < N; dim++) { // loop over each dimension\n        auto const &grid(super::m_grid_list[dim]);\n        xi = coord_iter_begin[dim][i];\n        c = this->find_cell(dim, coord_iter_begin[dim][i]);\n        if (c == -1) { // before first grid point\n          y = 1.0;\n        } else if (c == grid.size() - 1) { // after last grid point\n          y = 0.0;\n        } else {\n          y = (coord_iter_begin[dim][i] - grid[c]) / (grid[c + 1] - grid[c]);\n          if (y < 0.0)\n            y = 0.0;\n          else if (y > 1.0)\n            y = 1.0;\n        }\n        index[dim] = c;\n        x[dim] = y;\n      }\n      // copy f values at vertices\n      for (int v = 0; v < (1 << N); v++) { // loop over each vertex of hypercube\n        f[v] = this->get_f_val(index, v);\n      }\n      *i_result++ = linterp_nd_unitcube(f.begin(), f.end(), x.begin(), x.end());\n    }\n  }\n};\n\ntypedef InterpSimplex<1, double> NDInterpolator_1_S;\ntypedef InterpSimplex<2, double> NDInterpolator_2_S;\ntypedef InterpSimplex<3, double> NDInterpolator_3_S;\ntypedef InterpSimplex<4, double> NDInterpolator_4_S;\ntypedef InterpSimplex<5, double> NDInterpolator_5_S;\ntypedef InterpMultilinear<1, double> NDInterpolator_1_ML;\ntypedef InterpMultilinear<2, double> NDInterpolator_2_ML;\ntypedef InterpMultilinear<3, double> NDInterpolator_3_ML;\ntypedef InterpMultilinear<4, double> NDInterpolator_4_ML;\ntypedef InterpMultilinear<5, double> NDInterpolator_5_ML;\n\n// C interface\nextern \"C\" {\nvoid linterp_simplex_1(double **grids_begin, int *grid_len_begin, double *pF,\n                       int xi_len, double **xi_begin, double *pResult);\nvoid linterp_simplex_2(double **grids_begin, int *grid_len_begin, double *pF,\n                       int xi_len, double **xi_begin, double *pResult);\nvoid linterp_simplex_3(double **grids_begin, int *grid_len_begin, double *pF,\n                       int xi_len, double **xi_begin, double *pResult);\n}\n\nvoid linterp_simplex_1(double **grids_begin, int *grid_len_begin, double *pF,\n                       int xi_len, double **xi_begin, double *pResult) {\n  const int N = 1;\n  size_t total_size = 1;\n  for (int i = 0; i < N; i++) {\n    total_size *= grid_len_begin[i];\n  }\n  InterpSimplex<N, double, false> interp_obj(grids_begin, grid_len_begin, pF,\n                                             pF + total_size);\n  interp_obj.interp_vec(xi_len, xi_begin, xi_begin + N, pResult);\n}\n\nvoid linterp_simplex_2(double **grids_begin, int *grid_len_begin, double *pF,\n                       int xi_len, double **xi_begin, double *pResult) {\n  const int N = 2;\n  size_t total_size = 1;\n  for (int i = 0; i < N; i++) {\n    total_size *= grid_len_begin[i];\n  }\n  InterpSimplex<N, double, false> interp_obj(grids_begin, grid_len_begin, pF,\n                                             pF + total_size);\n  interp_obj.interp_vec(xi_len, xi_begin, xi_begin + N, pResult);\n}\n\nvoid linterp_simplex_3(double **grids_begin, int *grid_len_begin, double *pF,\n                       int xi_len, double **xi_begin, double *pResult) {\n  const int N = 3;\n  size_t total_size = 1;\n  for (int i = 0; i < N; i++) {\n    total_size *= grid_len_begin[i];\n  }\n  InterpSimplex<N, double, false> interp_obj(grids_begin, grid_len_begin, pF,\n                                             pF + total_size);\n  interp_obj.interp_vec(xi_len, xi_begin, xi_begin + N, pResult);\n}\n\n#endif //_linterp_h\n", "meta": {"hexsha": "2340647ecf26ede41b9a1c97db4e03e07b3fbe2f", "size": 17164, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/bounded_rand_walkers/cpp/linterp.hpp", "max_stars_repo_name": "akuhnregnier/bounded-rand-walkers", "max_stars_repo_head_hexsha": "8d241f16327a9ff086e6111a2c4edca6eef6ac21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bounded_rand_walkers/cpp/linterp.hpp", "max_issues_repo_name": "akuhnregnier/bounded-rand-walkers", "max_issues_repo_head_hexsha": "8d241f16327a9ff086e6111a2c4edca6eef6ac21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-22T10:30:17.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T10:30:17.000Z", "max_forks_repo_path": "src/bounded_rand_walkers/cpp/linterp.hpp", "max_forks_repo_name": "akuhnregnier/bounded-rand-walkers", "max_forks_repo_head_hexsha": "8d241f16327a9ff086e6111a2c4edca6eef6ac21", "max_forks_repo_licenses": ["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.5191489362, "max_line_length": 80, "alphanum_fraction": 0.6234560708, "num_tokens": 4878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6274063538788195}}
{"text": "#include \"testsuite.h\"\n#include <blitz/array.h>\n\nusing namespace blitz;\n\ntypedef TinyVector<int,3> tv3;\n\nint main()\n{\n  tv3 A, B;\n    A = 1, 2, 3;\n    B = 0, 1, 2;\n\n    BZTEST(A[0]==1);\n    BZTEST(A[1]==2);\n    BZTEST(A[2]==3);\n    BZTEST(B[0]==0);\n    BZTEST(B[1]==1);\n    BZTEST(B[2]==2);\n\n    A += B*B;\n    BZTEST(all(A==tv3(1,3,7)));\n\n    //cout << A << endl;\n\n    A *= 10;\n    BZTEST(all(A==tv3(10,30,70)));\n\n    //cout << A << endl;\n\n    tv3::iterator it=B.begin(), end=B.end();\n    cout << \"(\" << *it;\n    for (it++; it != end; ++it) \n        cout << \",\" << *it;\n    cout << \")\" << endl;\n\n// test tinyvector dot(), product(), and sum() functions\n\n    int dotAB = dot(A,B); \n    BZTEST(dotAB==170);\n    int dotAB2 = dot(A,B+B);\n    BZTEST(dotAB2==2*dotAB);\n    int dotA2B = dot(A+A,B);\n    BZTEST(dotA2B==2*dotAB);\n    int dotA2B2 = dot(A+A,B+B);\n    BZTEST(dotA2B2==4*dotAB);\n    int prod1 = product(A);\n    BZTEST(prod1==21000);\n    int prod2 = product(A+B);\n    BZTEST(prod2==22320);\n    int sum1 = sum(A);\n    BZTEST(sum1==110);\n    int sum2 = sum(A-B);\n    BZTEST(sum2==sum1-sum(B));\n\n    // (cross product is tested in levicivita.cpp)\n\n    // test funcs\n    B=-1,-2,-3;\n    A=abs(B);\n    BZTEST(A[0]==1);\n    BZTEST(A[1]==2);\n    BZTEST(A[2]==3);\n\n    TinyVector<double,3> C,D;\n    D=1,4,9;\n    C=sqrt(D);\n    BZTEST(C[0]==1);\n    BZTEST(C[1]==2);\n    BZTEST(C[2]==3);\n\n    // test expr constructor\n    tv3 E(A+B*B);\n    BZTEST(all(E==tv3(2,6,12)));\n\n    return 0;\n}\n\n", "meta": {"hexsha": "a30800296145a56a47a02d7ee6dd0fe17eaa36a7", "size": 1480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/testsuite/tinyvec.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/testsuite/tinyvec.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/testsuite/tinyvec.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7341772152, "max_line_length": 56, "alphanum_fraction": 0.5013513514, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6274063523446787}}
{"text": "//  (C) Copyright Nick Thompson 2019.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_STATISTICS_T_TEST_HPP\n#define BOOST_MATH_STATISTICS_T_TEST_HPP\n\n#include <cmath>\n#include <iterator>\n#include <utility>\n#include <boost/math/distributions/students_t.hpp>\n#include <boost/math/statistics/univariate_statistics.hpp>\n\nnamespace boost::math::statistics {\n\ntemplate<typename Real>\nstd::pair<Real, Real> one_sample_t_test(Real sample_mean, Real sample_variance, Real num_samples, Real assumed_mean) {\n    using std::sqrt;\n    typedef boost::math::policies::policy<\n          boost::math::policies::promote_float<false>,\n          boost::math::policies::promote_double<false> >\n          no_promote_policy;\n\n    Real test_statistic = (sample_mean - assumed_mean)/sqrt(sample_variance/num_samples);\n    auto student = boost::math::students_t_distribution<Real, no_promote_policy>(num_samples - 1);\n    Real pvalue;\n    if (test_statistic > 0) {\n        pvalue = 2*boost::math::cdf<Real>(student, -test_statistic);;\n    }\n    else {\n        pvalue = 2*boost::math::cdf<Real>(student, test_statistic);\n    }\n    return std::make_pair(test_statistic, pvalue);\n}\n\ntemplate<class ForwardIterator>\nauto one_sample_t_test(ForwardIterator begin, ForwardIterator end, typename std::iterator_traits<ForwardIterator>::value_type assumed_mean) {\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\n    auto [mu, s_sq] = mean_and_sample_variance(begin, end);\n    return one_sample_t_test(mu, s_sq, Real(std::distance(begin, end)), assumed_mean);\n}\n\ntemplate<class Container>\nauto one_sample_t_test(Container const & v, typename Container::value_type assumed_mean) {\n    return one_sample_t_test(v.begin(), v.end(), assumed_mean);\n}\n\n}\n#endif\n", "meta": {"hexsha": "b1e787ecbae02d09b5150ba9b14944a02809e749", "size": 1911, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/statistics/t_test.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 597.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T10:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:59:36.000Z", "max_issues_repo_path": "boost/math/statistics/t_test.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "boost/math/statistics/t_test.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 112.0, "max_forks_repo_forks_event_min_datetime": "2018-07-26T04:36:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:29:34.000Z", "avg_line_length": 37.4705882353, "max_line_length": 141, "alphanum_fraction": 0.7435897436, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.6273320248737306}}
{"text": "#include \"game/vsr/vsr.h\"\n#include <Eigen/Core>\n#include <adept.h>\n#include <hep/ga.hpp>\n#include <iostream>\n\nusing vsr::cga::Vector;\nusing vsr::cga::Point;\nusing vsr::cga::Rotor;\nusing vsr::cga::Translator;\n\nconst double kPi = 3.141592653589793238462643383279;\n\ntemplate <typename T> using Matrix4 = Eigen::Matrix<T, 4, 4>;\n\ntemplate <typename T> inline static Matrix4<T> s() {\n  Matrix4<T> m;\n  m << T(1), T(0), T(0), T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(1), T(0),\n      T(0), T(0), T(0), T(1);\n  return m;\n}\n\ntemplate <typename T> inline static Matrix4<T> e1() {\n  Matrix4<T> m;\n  m << T(0), T(0), T(0), T(1), T(0), T(0), T(1), T(0), T(0), T(1), T(0), T(0),\n      T(1), T(0), T(0), T(0);\n  return m;\n}\n\ntemplate <typename T> inline static Matrix4<T> e2() {\n  Matrix4<T> m;\n  m << T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(-1), T(1), T(0), T(0), T(0),\n      T(0), T(-1), T(0), T(0);\n  return m;\n}\n\ntemplate <typename T> inline static Matrix4<T> e3() {\n  Matrix4<T> m;\n  m << T(1), T(0), T(0), T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(-1), T(0),\n      T(0), T(0), T(0), T(-1);\n  return m;\n}\n\ntemplate <typename T> inline static Matrix4<T> e23() {\n  return e2<T>() * e3<T>();\n}\n\ntemplate <typename T> inline static Matrix4<T> e31() {\n  return e3<T>() * e1<T>();\n}\n\ntemplate <typename T> inline static Matrix4<T> e12() {\n  return e1<T>() * e2<T>();\n}\n\ntemplate <typename T> inline static Matrix4<T> e123() {\n  return e1<T>() * e2<T>() * e3<T>();\n}\n\ntemplate <typename T> void Diff4(const T th, const T *a, T *b) {\n  Matrix4<T> rotor =\n      cos(T(0.5) * th) * s<T>() - sin(T(0.5) * th) * e1<T>() * e2<T>();\n  Matrix4<T> rotor_inv =\n      cos(T(0.5) * th) * s<T>() + sin(T(0.5) * th) * e1<T>() * e2<T>();\n  Matrix4<T> vec_a = a[0] * e1<T>() + a[1] * e2<T>() + a[2] * e3<T>();\n  Matrix4<T> vec_b = rotor * vec_a * rotor_inv;\n  b[0] = vec_b(0, 3);\n  b[1] = vec_b(2, 0);\n  b[2] = vec_b(0, 0);\n}\n\ntemplate <typename T> void Diff5(const T th, const T *a, T *b) {\n  using Algebra = hep::algebra<T, 3, 0>;\n  using Rotor = hep::multi_vector<Algebra, hep::list<0, 3, 5, 6>>;\n  using Vector = hep::multi_vector<Algebra, hep::list<1, 2, 4>>;\n  Rotor rotor{cos(T(0.5) * th), -sin(T(0.5) * th), T(0.0), T(0.0)};\n  Vector pnt_a{a[0], a[1], a[2]};\n  Vector pnt_b = hep::grade<1>(rotor * pnt_a * ~rotor);\n  for (int i = 0; i < 3; ++i)\n    b[i] = pnt_b[i];\n}\n\ntemplate <typename T> void Diff(const T th, const T *a, T *b) {\n  Rotor<T> rotor{cos(T(0.5) * th), -sin(T(0.5) * th), T(0.0), T(0.0)};\n  Vector<T> vec_a{a[0], a[1], a[2]};\n  Vector<T> vec_b = vec_a.spin(rotor);\n  for (int i = 0; i < 3; ++i)\n    b[i] = vec_b[i];\n}\n\ntemplate <typename T> void Diff2(const T th, const T *a, T *b) {\n  Rotor<T> rotor{cos(T(0.5) * th), -sin(T(0.5) * th), T(0.0), T(0.0)};\n  Point<T> pnt_a = Vector<T>{a[0], a[1], a[2]}.null();\n  Point<T> pnt_b = pnt_a.spin(rotor);\n  for (int i = 0; i < 5; ++i)\n    b[i] = pnt_b[i];\n}\n\ntemplate <typename T> void Diff3(const T t, const T *a, T *b) {\n  Translator<T> trs{T(1.0), -T(0.5) * t, T(0.0), T(0.0)};\n  Point<T> pnt_a = Vector<T>{a[0], a[1], a[2]}.null();\n  Point<T> pnt_b = pnt_a.spin(trs);\n  for (int i = 0; i < 5; ++i)\n    b[i] = pnt_b[i];\n}\n\nint main() {\n  adept::Stack stack;\n  const double theta = kPi / 3;\n\n  double jac[5];\n  adept::adouble at = 3.0;\n  adept::adouble atheta = theta;\n  adept::adouble a[3] = {1.0, 0.0, 0.0}; // e1\n  stack.new_recording();\n  adept::adouble b[5] = {0.0, 0.0, 0.0, 0.0, 0.0};\n\n  // Diff(atheta, a, b);\n  Diff4(atheta, a, b);\n  // Diff5(atheta, a, b);\n  // Diff2(at, a, b);\n  // Diff3(at, a, b);\n\n  // stack.independent(&at, 1);\n  stack.independent(&atheta, 1);\n  stack.dependent(b, 3);\n  stack.jacobian_reverse(jac);\n  // stack.jacobian_forward(jac);\n\n  for (int i = 0; i < 3; ++i)\n    std::cout << b[i] << \" \" << std::endl;\n\n  for (int i = 0; i < 3; ++i)\n    std::cout << jac[i] << \" \" << std::endl;\n\n  stack.print_status();\n  // stack.print_statements();\n  // stack.print_gradients();\n\n  return 0;\n}\n", "meta": {"hexsha": "634fe0848781e8c48299e5222d62b6cdd8788244", "size": 3962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adept_rotor_diff_example.cpp", "max_stars_repo_name": "tingelst/game", "max_stars_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2017-07-25T08:15:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T23:05:46.000Z", "max_issues_repo_path": "src/adept_rotor_diff_example.cpp", "max_issues_repo_name": "tingelst/game", "max_issues_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T09:32:26.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T09:41:47.000Z", "max_forks_repo_path": "src/adept_rotor_diff_example.cpp", "max_forks_repo_name": "tingelst/game", "max_forks_repo_head_hexsha": "2e9acc1d3052e4135605211a622aa8613ee56949", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T04:42:33.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-12T12:56:45.000Z", "avg_line_length": 27.9014084507, "max_line_length": 79, "alphanum_fraction": 0.5365976779, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6271786698447246}}
{"text": "#include <Eigen/Core>\n#include <iostream>\n#include <mathtoolbox/rbf-interpolation.hpp>\n#include <random>\n#include <timer.hpp>\n#include <vector>\n\nusing Eigen::MatrixXd;\nusing Eigen::Vector2d;\nusing Eigen::VectorXd;\n\nnamespace\n{\n    std::random_device                     seed;\n    std::default_random_engine             engine(seed());\n    std::uniform_real_distribution<double> uniform_dist(-1.0, 1.0);\n\n    double CalcFunction(const Vector2d& x) { return std::sin(10.0 * x(0)) + std::sin(10.0 * x(1)); }\n\n    std::shared_ptr<timer::Timer> timer_object;\n} // namespace\n\nvoid PerformTest()\n{\n    constexpr int    number_of_samples      = 500;\n    constexpr int    number_of_test_samples = 100;\n    constexpr double noise_intensity        = 0.1;\n\n    // Generate scattered data (in this case, 500 data points in a 2-dimensional space)\n    Eigen::MatrixXd X = Eigen::MatrixXd::Random(2, number_of_samples);\n    Eigen::VectorXd y(number_of_samples);\n    for (int i = 0; i < number_of_samples; ++i)\n    {\n        y(i) = CalcFunction(X.col(i)) + noise_intensity * uniform_dist(engine);\n    }\n\n    // Define interpolation settings\n    const auto     kernel             = mathtoolbox::ThinPlateSplineRbfKernel();\n    constexpr bool use_regularization = true;\n\n    // Instantiate an interpolator\n    mathtoolbox::RbfInterpolator rbf_interpolator(kernel);\n\n    // Set data\n    rbf_interpolator.SetData(X, y);\n\n    // Calculate internal weights with or without regularization\n    timer_object = std::make_shared<timer::Timer>(\"CalcWeights()\");\n    rbf_interpolator.CalcWeights(use_regularization);\n    timer_object = nullptr;\n\n    // Calculate interpolated values on randomly sampled points\n    Eigen::MatrixXd X_test = Eigen::MatrixXd::Random(2, number_of_test_samples);\n    Eigen::VectorXd y_test(number_of_test_samples);\n    timer_object = std::make_shared<timer::Timer>(\"CalcValue() * \" + std::to_string(number_of_test_samples));\n    for (int i = 0; i < number_of_test_samples; ++i)\n    {\n        y_test(i) = rbf_interpolator.CalcValue(X_test.col(i));\n    }\n    timer_object = nullptr;\n\n    // Display the results in the CSV format\n    std::cout << \"x(0),x(1),y\" << std::endl;\n    for (int i = 0; i < number_of_test_samples; ++i)\n    {\n        std::cout << X_test(0, i) << \",\" << X_test(1, i) << \",\" << y_test(i) << std::endl;\n    }\n}\n\nint main()\n{\n    PerformTest();\n\n    return 0;\n}\n", "meta": {"hexsha": "fac048ecdd8ada130c726cb6460948611b478245", "size": 2378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/rbf-interpolation/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/rbf-interpolation/main.cpp", "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": "examples/rbf-interpolation/main.cpp", "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": 31.2894736842, "max_line_length": 109, "alphanum_fraction": 0.6593776283, "num_tokens": 614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6271786697531546}}
{"text": "// -------------------------------------------------------------------------------------------------\n//                              Copyright 2016 - NumScale SAS\n//\n//                   Distributed under the Boost Software License, Version 1.0.\n//                        See accompanying file LICENSE.txt or copy at\n//                            http://www.boost.org/LICENSE_1_0.txt\n// -------------------------------------------------------------------------------------------------\n\n#include <simd_bench.hpp>\n#include <boost/simd/function/simd/significants.hpp>\n#include <boost/simd/function/simd/enumerate.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\nnamespace nsb = ns::bench;\nnamespace bs =  boost::simd;\nnamespace bd =  boost::dispatch;\ntemplate < int N >\nstruct signif\n{\n  template<class T> T operator()(const T & a) const\n  {\n    using i_t = bd::as_integer_t<T>;\n    return bs::significants(a, bs::enumerate<i_t>(0, N));\n  }\n};\n\nDEFINE_SIMD_BENCH(simd_significantsp, signif< 1>());\nDEFINE_SIMD_BENCH(simd_significantsn, signif<-1>());\n\nDEFINE_BENCH_MAIN() {\n  nsb::for_each<simd_significantsn, NS_BENCH_IEEE_TYPES>(-10, 10);\n  nsb::for_each<simd_significantsp, NS_BENCH_IEEE_TYPES>(-10, 10);\n}\n", "meta": {"hexsha": "6e6fb6a415f601bdd16ac67fed0355cc56d3d6e7", "size": 1253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/function/simd/significants.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "bench/function/simd/significants.cpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/function/simd/significants.cpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 35.8, "max_line_length": 100, "alphanum_fraction": 0.5570630487, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6271786649433487}}
{"text": "#include \"sphere.h\"\n\n\n#include <boost\\math\\constants\\constants.hpp>\n\nvoid make_sphere(std::vector<glm::vec3> &vertices, std::vector<glm::vec3> &normals, std::vector<glm::vec2> &stCoordinates, std::vector<GLushort> &elements, int rings, int sectors)\n{\n\tint radius = 1;\n\n\tfloat const R = 1. / (float) (rings - 1);\n\tfloat const S = 1. / (float) (sectors - 1);\n\tint r, s;\n\n\tvertices.resize(rings * sectors);\n\tnormals.resize(rings * sectors);\n\tstCoordinates.resize(rings * sectors);\n\tstd::vector<glm::vec3>::iterator v = vertices.begin();\n\tstd::vector<glm::vec3>::iterator n = normals.begin();\n\tstd::vector<glm::vec2>::iterator t = stCoordinates.begin();\n\tfor (r = 0; r < rings; r++) for (s = 0; s < sectors; s++) {\n\t\tfloat const y = sin(-boost::math::float_constants::half_pi + boost::math::float_constants::pi * r * R);\n\t\tfloat const x = cos(2 * boost::math::float_constants::pi * s * S) * sin(boost::math::float_constants::pi * r * R);\n\t\tfloat const z = sin(2 * boost::math::float_constants::pi * s * S) * sin(boost::math::float_constants::pi * r * R);\n\n\t\t*t++ = glm::vec2(s*S, r*R);\n\n\t\t*v++ = glm::vec3(x * radius, y * radius, z * radius);\n\n\t\t*n++ = glm::vec3(x, y, z);\n\t}\n\n\telements.resize(rings * sectors * 6);\n\tstd::vector<GLushort>::iterator i = elements.begin();\n\tfor (r = 0; r < rings - 1; r++) for (s = 0; s < sectors - 1; s++) {\n\t\t*i++ = r * sectors + s; //0\t\t\n\t\t*i++ = (r + 1) * sectors + (s + 1); //2\n\t\t*i++ = r * sectors + (s + 1); //1\n\t\t*i++ = r * sectors + s; //0\n\t\t*i++ = (r + 1) * sectors + s; //3\n\t\t*i++ = (r + 1) * sectors + (s + 1); //2\n\t}\n}", "meta": {"hexsha": "7089d8cffc5eebfcf006c25e4609357796ab72b9", "size": 1558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AnimaRender/primitives/sphere.cpp", "max_stars_repo_name": "anima-render/Anima-Render", "max_stars_repo_head_hexsha": "ab6078cf9ffe95ac5514ae2f2178da92d73e8cc1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-04-24T00:28:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-30T15:29:26.000Z", "max_issues_repo_path": "AnimaRender/primitives/sphere.cpp", "max_issues_repo_name": "anima-render/Anima-Render", "max_issues_repo_head_hexsha": "ab6078cf9ffe95ac5514ae2f2178da92d73e8cc1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AnimaRender/primitives/sphere.cpp", "max_forks_repo_name": "anima-render/Anima-Render", "max_forks_repo_head_hexsha": "ab6078cf9ffe95ac5514ae2f2178da92d73e8cc1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0952380952, "max_line_length": 179, "alphanum_fraction": 0.5860077022, "num_tokens": 546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6271786596756955}}
{"text": "/*! \\file 2d_limit.cpp\n  \\brief Simple 2D plot show 1/x function values at limit.\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 2009, 2021\n// Distributed under the Boost Software License, Version 1.0.\n// For more information, see http://www.boost.org\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\n// boost::svg::svg_2d_plot\n#include <limits>\n// infinity\n#include <map>\n//using std::map;\n\ndouble f(double x)\n{ // Function to plot.\n  return 1. / x;\n}\n\nint main()\n{\n  using namespace boost::svg; // For SVG named colors.\n  std::map<double, double> data1;\n\n  const double interval = 0.5;\n  for(double i = -10; i <= 10.; i += interval)\n  {\n    data1[i] = f(i);\n  }\n\n  svg_2d_plot my_plot;\n\n  // Image size & ranges settings.\n  my_plot.size(500, 350) // SVG image in pixels.\n         .x_range(-10.5, 10.5) // Offset by 0.5 so that +10 and -10 markers are visible.\n         .y_range(-1.1, 1.1); // Offset by 1 so that +10 and -10 markers are visible.\n\n  // Text settings.\n  my_plot.title(\"Plot of 1 / x\")\n    .x_label(\"X Axis Units\")\n    .y_label(\"F(x)\")\n    .y_major_labels_side(-1) // Left.\n    .plot_window_on(true);\n\n  // X-axis settings.\n  my_plot.x_major_interval(2)\n    .x_major_tick_length(14)\n    .x_major_tick_width(1)\n    .x_minor_tick_length(7)\n    .x_minor_tick_width(1)\n    .x_num_minor_ticks(1)\n    .x_major_labels_side(1) // Top of X-axis line (but zero collides with vertical x == 0 line).\n\n  // Y-axis settings.\n         .y_major_interval(1)\n         .y_num_minor_ticks(4);\n\n  // Legend-box settings.\n  my_plot.legend_title_font_size(15);\n\n  // Limit value at x = 0 when 1/x == +infinity shown by a pointing-down cone a the top of the plot.\n  //my_plot.minus_inf_limit_color(red).plus_inf_limit_color(green); \n  // TODO - the 'at-limit' infinity point cone pointing-down shows as default color pink, not the changed color(s).\n\n  my_plot.plot(data1, \"1 / x\").shape(square).size (5).line_on(false);\n\n  my_plot.write(\"./2d_limit.svg\");\n\n  // Sets and gets colors correctly, but not used? A fix would be good, but does display.\n  // std::cout << \"\" << my_plot.plus_inf_limit_color() << std::endl; // RGB(0,128,0)\n   //std::cout << \"\" << my_plot.minus_inf_limit_color() << std::endl; // RGB(255,0,0)\n\n  return 0;\n} // int main()\n\n", "meta": {"hexsha": "d6824599ae45f09f84406a8688640ef92abac1e8", "size": 2251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/2d_limit.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/2d_limit.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/2d_limit.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 28.858974359, "max_line_length": 115, "alphanum_fraction": 0.657041315, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.6271786595841259}}
{"text": "\ufeff//\n//  Polygone.cpp\n//  \n//\n//  Created by Victoire Chapelle on 14/01/2016.\n//\n//\n\n#include \"Polygon.h\"\n\n#include <math.h>\n#include <string>\n\n#include <boost/serialization/vector.hpp>\n\n#include \"Utils.h\"\n#include \"optional.h\"\n#include \"Segment.h\"\n\nnamespace TP4\n{\n\tstd::experimental::optional<Polygon> make_polygon(const std::vector<Point> vertices)\n\t{\n\t\tif (vertices.size() > 2)\n\t\t{\n\t\t\tPoint p1, p2;\n\n\t\t\tp1.first = vertices[0].first - vertices[vertices.size() - 1].first;\n\t\t\tp1.second = vertices[0].second - vertices[vertices.size() - 1].second;\n\t\t\tp2.first = vertices[1].first - vertices[0].first;\n\t\t\tp2.second = vertices[1].second - vertices[0].second;\n\n\t\t\tdouble det_value;\n\t\t\tdouble current_det_value;\n\n\t\t\tdet_value = p1.first * p2.second - p1.second * p2.first;\n\n\t\t\tfor (size_t i = 0; i < vertices.size(); ++i)\n\t\t\t{\n\t\t\t\tp1.first = vertices[mod(i + 1, vertices.size())].first - vertices[i].first;\n\t\t\t\tp1.second = vertices[mod(i + 1, vertices.size())].second - vertices[i].second;\n\t\t\t\tp2.first = vertices[mod(i + 2, vertices.size())].first - vertices[mod(i + 1, vertices.size())].first;\n\t\t\t\tp2.second = vertices[mod(i + 2, vertices.size())].second - vertices[mod(i + 1, vertices.size())].second;\n\n\t\t\t\tcurrent_det_value = p1.first * p2.second - p1.second * p2.first;\n\n\t\t\t\tif (det_value*current_det_value < 0 - 0.00001)\n\t\t\t\t\treturn std::experimental::nullopt;\n\t\t\t}\n\n\t\t\treturn std::experimental::optional<Polygon>(Polygon(std::move(vertices)));\n\t\t}\n\n\t\treturn std::experimental::nullopt;\n\t}\n\n\tPolygon Move(const Polygon& shape, coord_t dx, coord_t dy)\n\t{\n\t\tstd::vector<Point> new_vertices;\n\t\tnew_vertices.reserve(new_vertices.size());\n\n\t\tfor (const Point& p : shape.vertices)\n\t\t\tnew_vertices.emplace_back(p.first + dx, p.second + dy);\n\n\t\treturn Polygon(std::move(new_vertices));\n\t}\n\n\tinline double squared_distance(Point a, Point b)\n\t{\n\t\treturn (a.first - b.first) * (a.first - b.first) \n\t\t\t+ (a.second - b.second) * (a.second - b.second);\n\t}\n\n\tbool Is_contained(const Polygon& shape, Point point)\n\t{\n\t\tdouble sum = 0.0;\n\n\t\t// Calcul de la somme des cosinus que font les angles entre les sommets cons\u00e9cutifs et le point\n\t\tfor (size_t i = 0; i < shape.vertices.size(); ++i)\n\t\t{\n\t\t\tauto next_point = shape.vertices[mod(i + 1, shape.vertices.size())];\n\n\t\t\tdouble a2 = squared_distance(shape.vertices[i], point);\n\t\t\tdouble c2 = squared_distance(shape.vertices[i], next_point);\n\t\t\tdouble b2 = squared_distance(next_point, point);\n\n\t\t\tif (abs(a2) < 0.001 || abs(b2) < 0.001)\n\t\t\t\treturn true; // Le point est confondu avec un sommet\n\n\t\t\tauto seg = make_segment(shape.vertices[i], next_point);\n\t\t\tif(seg)\n\t\t\t\tif (Is_contained(*seg, point))\n\t\t\t\t\treturn true;\n\n\t\t\t// Formule d'al-kashi : cos(angle) = (a\u00b2 + b\u00b2 - c\u00b2) / (2*a*b)\n\t\t\tdouble cos = (a2 + b2 - c2) / (2.0*sqrt(a2)*sqrt(b2)); \n\t\t//\tdouble cos = c2 / (length_1 + length_3 - 2.0*sqrt(length_3)*sqrt(length_1));\n\n\t\t\tsum += acos(cos);\n\t\t}\n\n\t\t// Si la somme est 1 le point est \u00e0 l'int\u00e9rieur (somme des angles = 360\u00b0)\n\t\t// TODO: faire mieux?\n\t\tif (abs(mod(sum, 2.0*3.14159) < 0.001))\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\tPolygon::Polygon(const std::vector<Point>&& vertices)\n\t\t: vertices(std::move(vertices))\n\t{ }\n\n\tstd::ostream& operator<<(std::ostream& flux, const Polygon& polygone)\n\t{\n\t\tflux << \"{ \";\n\t\tfor (size_t i = 0; i < polygone.vertices.size(); ++i)\n\t\t\tflux << \"(\" << polygone.vertices[i].first << \", \" << polygone.vertices[i].second << (i == polygone.vertices.size() - 1 ? \") \" : \"); \");\n\t\tflux << \"}\";\n\n\t\treturn flux;\n\t}\n}\n", "meta": {"hexsha": "2f0d132567f8b8d185c89b0ec7ad8f71806be6e6", "size": 3479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TP4_cpp/src/Polygon.cpp", "max_stars_repo_name": "PaulEmmanuelSotir/TPs_3IF", "max_stars_repo_head_hexsha": "51e1b82837bd2e9e01fe84721f127c469f1f24a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TP4_cpp/src/Polygon.cpp", "max_issues_repo_name": "PaulEmmanuelSotir/TPs_3IF", "max_issues_repo_head_hexsha": "51e1b82837bd2e9e01fe84721f127c469f1f24a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TP4_cpp/src/Polygon.cpp", "max_forks_repo_name": "PaulEmmanuelSotir/TPs_3IF", "max_forks_repo_head_hexsha": "51e1b82837bd2e9e01fe84721f127c469f1f24a7", "max_forks_repo_licenses": ["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.2845528455, "max_line_length": 138, "alphanum_fraction": 0.6421385456, "num_tokens": 1059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.627178654591181}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n#include <OpenTissue/core/containers/mesh/polymesh/polymesh.h>\n#include <OpenTissue/core/containers/mesh/polymesh/util/polymesh_is_point_inside.h>\n#include <OpenTissue/core/containers/mesh/common/util/mesh_make_box.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\n#include <cmath>\n\nBOOST_AUTO_TEST_SUITE(opentissue_polymesh_is_point_inside);\n\nBOOST_AUTO_TEST_CASE(box_test)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  typedef math_types::matrix3x3_type                       matrix3x3_type;\n  typedef math_types::real_type                            real_type;\n\n  OpenTissue::polymesh::PolyMesh<math_types> mesh;\n\n  OpenTissue::mesh::make_box(1.0,1.0,1.0,mesh);\n\n\n  //std::vector<vector3_type> profile;\n  //profile.push_back(vector3_type(0.0,0.0,0.0));\n  //profile.push_back(vector3_type(5.0,0.0,5.0));\n  //profile.push_back(vector3_type(5.0,0.0,10.0));\n  //profile.push_back(vector3_type(0.0,0.0,15.0));\n  //OpenTissue::mesh::profile_sweep(profile.begin(),profile.end(),2*OpenTissue::math::detail::pi<real_type>(),32,m_mesh);\n\n  bool inside = false;\n  vector3_type p;\n  real_type val = 0.0;\n\n  p = vector3_type(0.0,0.0,0.0);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( inside );\n\n  val = 0.45;\n  p = vector3_type(val,val,val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( inside );\n  p = vector3_type(val,val,-val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( inside );\n  p = vector3_type(val,-val,val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( inside );\n  p = vector3_type(val,-val,-val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( inside );\n  p = vector3_type(-val,val,val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( inside );\n  p = vector3_type(-val,val,-val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( inside );\n  p = vector3_type(-val,-val,val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( inside );\n  p = vector3_type(-val,-val,-val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( inside );\n\n  val = 0.8;\n  p = vector3_type(val,val,val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( !inside );\n  p = vector3_type(val,val,-val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( !inside );\n  p = vector3_type(val,-val,val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( !inside );\n  p = vector3_type(val,-val,-val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( !inside );\n  p = vector3_type(-val,val,val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( !inside );\n  p = vector3_type(-val,val,-val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( !inside );\n  p = vector3_type(-val,-val,val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( !inside );\n  p = vector3_type(-val,-val,-val);\n  inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  BOOST_CHECK( !inside );\n\n}\n\nBOOST_AUTO_TEST_CASE(advanced_test)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n  typedef math_types::vector3_type                         vector3_type;\n  typedef math_types::matrix3x3_type                       matrix3x3_type;\n  typedef math_types::real_type                            real_type;\n\n  OpenTissue::polymesh::PolyMesh<math_types> mesh;\n\n  //std::vector<vector3_type> profile;\n  //profile.push_back(vector3_type(0.0,0.0,0.0));\n  //profile.push_back(vector3_type(5.0,0.0,5.0));\n  //profile.push_back(vector3_type(5.0,0.0,10.0));\n  //profile.push_back(vector3_type(0.0,0.0,15.0));\n  //OpenTissue::mesh::profile_sweep(profile.begin(),profile.end(),2*OpenTissue::math::detail::pi<real_type>(),32,m_mesh);\n\n  //bool inside = false;\n  vector3_type p;\n\n  //p = vector3_type(0.0,0.0,0.0);\n  //inside = OpenTissue::polymesh::is_point_inside( mesh, p );  \n  //BOOST_CHECK( inside );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "627a50cc74c451824624952f8cc1f22a6972aed0", "size": 4783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/containers/polymesh_is_point_inside/src/unit_polymesh_is_point_inside.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/containers/polymesh_is_point_inside/src/unit_polymesh_is_point_inside.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/containers/polymesh_is_point_inside/src/unit_polymesh_is_point_inside.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 36.7923076923, "max_line_length": 121, "alphanum_fraction": 0.698515576, "num_tokens": 1412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.7248702880639792, "lm_q1q2_score": 0.6271752299775135}}
{"text": "/* test_extreme_value.cpp\n *\n * Copyright Steven Watanabe 2010\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id: test_extreme_value.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\n *\n */\n\n#include <boost/random/extreme_value_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/math/distributions/extreme_value.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::extreme_value_distribution<>\n#define BOOST_RANDOM_DISTRIBUTION_NAME extreme_value\n#define BOOST_MATH_DISTRIBUTION boost::math::extreme_value\n#define BOOST_RANDOM_ARG1_TYPE double\n#define BOOST_RANDOM_ARG1_NAME a\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\n#define BOOST_RANDOM_ARG2_TYPE double\n#define BOOST_RANDOM_ARG2_NAME b\n#define BOOST_RANDOM_ARG2_DEFAULT 1000.0\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\n\n#include \"test_real_distribution.ipp\"\n", "meta": {"hexsha": "ca0b8172570ce376382103eee908496a9286e2a1", "size": 1062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_extreme_value.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "libs/random/test/test_extreme_value.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "libs/random/test/test_extreme_value.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 36.6206896552, "max_line_length": 77, "alphanum_fraction": 0.81826742, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6271752247307293}}
{"text": "#include \"ols.h\"\n\n#include <carma>\n#include <armadillo>\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <pybind11/pytypes.h>\n\npy::tuple ols(arma::colvec& y, arma::mat& X) {\n    int n = X.n_rows, k = X.n_cols;\n\n    arma::colvec coeffs = arma::solve(X, y);\n    arma::colvec resid = y - X * coeffs;\n\n    double sig2 = arma::as_scalar(arma::trans(resid) * resid / (n-k));\n    arma::colvec std_errs = arma::sqrt(sig2 * arma::diagvec( arma::inv(arma::trans(X)*X)) );\n\n    return py::make_tuple(\n        carma::col_to_arr(coeffs),\n        carma::col_to_arr(std_errs)\n    );\n}\n\nvoid bind_ols(py::module &m) {\n    m.def(\n        \"ols\",\n        &ols,\n        R\"pbdoc(\n            Example function performing OLS.\n\n            Parameters\n            ----------\n            arr : np.array\n                input array\n\n            Returns\n            -------\n            coeffs: np.ndarray\n                coefficients\n            std_err : np.ndarray\n                standard error on the coefficients\n        )pbdoc\",\n        py::arg(\"y\"),\n        py::arg(\"x\")\n    );\n}\n", "meta": {"hexsha": "3179472bddd49041433939a2be5b70d2ffddd570", "size": 1079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ols.cpp", "max_stars_repo_name": "libKriging/carma", "max_stars_repo_head_hexsha": "f38fb8743dbd7a7525da274428195046b8e22c6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2020-04-09T13:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:03:43.000Z", "max_issues_repo_path": "examples/ols.cpp", "max_issues_repo_name": "libKriging/carma", "max_issues_repo_head_hexsha": "f38fb8743dbd7a7525da274428195046b8e22c6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2020-05-02T21:55:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T13:54:17.000Z", "max_forks_repo_path": "examples/ols.cpp", "max_forks_repo_name": "libKriging/carma", "max_forks_repo_head_hexsha": "f38fb8743dbd7a7525da274428195046b8e22c6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-05-18T13:39:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T08:23:35.000Z", "avg_line_length": 22.9574468085, "max_line_length": 92, "alphanum_fraction": 0.5208526413, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.627175204473398}}
{"text": "/**\n\n\\file\n\\author Datta Ramadasan\n//==============================================================================\n//         Copyright 2015 INSTITUT PASCAL UMR 6602 CNRS/Univ. Clermont II\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n\n*/\n\n#ifndef __OPTIMISATION2_BUNDLE_COST_HPP__\n#define __OPTIMISATION2_BUNDLE_COST_HPP__\n\n#include <cmath>\n#include \"../function/function.hpp\"\n#include <libv/lma/ttt/traits/wrap.hpp>\n#include <boost/mpl/for_each.hpp>\n#include \"../ba/nan_error.hpp\"\n#include \"../ba/mat.hpp\"\n#include \"../omp/omp.hpp\"\n\nnamespace lma\n{\n  template<class Obs, class Bundle> double cost(const Bundle& bundle)\n  {\n    const auto nb_obs = bundle.template at_obs<Obs>().size();\n    if (nb_obs==0) return 0;\n\n//     std::cout << \" cost without save \" << std::endl;\n    \n    double total = 0;\n\n//     #pragma omp parallel for reduction(+:total) if(use_omp())\n    for(auto iobs = bundle.template at_obs<Obs>().first() ; iobs < nb_obs ; ++iobs)\n    {\n      //total += (make_function(bundle.obs(iobs))(bundle.map(iobs))).squaredNorm() / 2;\n      auto pair_residu = make_function(bundle.obs(iobs))(bundle.map(iobs));\n      if (pair_residu.second)\n        total += ( pair_residu ).first.squaredNorm();\n    }\n\n    if (std::isnan(total))\n      throw NAN_ERROR(\" NAN : cost_and_save\");\n    return total/2.0;\n  }\n\n  template<class Bundle> struct Coster\n  {\n    const Bundle& bundle;\n    double sum;\n    Coster(const Bundle& bundle_):bundle(bundle_),sum(0){}\n\n    template<class T> void operator()(ttt::wrap<T>)\n    {\n      sum += cost<T,Bundle>(bundle);\n    }\n  };\n\n  // total square error\n  template<class Bundle> double cost(const Bundle& bundle)\n  {\n    Coster<Bundle> coster(bundle);\n    mpl::for_each<typename Bundle::ListeToObs, ttt::wrap<mpl::placeholders::_1>>(boost::ref(coster));\n    return coster.sum;\n  }\n\n  template<class ListeObs, class Bundle> double costs(const Bundle& bundle)\n  {\n    Coster<Bundle> coster(bundle);\n    mpl::for_each<ListeObs, ttt::wrap<mpl::placeholders::_1>>(boost::ref(coster));\n    return coster.sum;\n  }\n  \n  // root mean square\n  template<class Bundle> double rms(const Bundle& bundle)\n  {\n    if (bundle.nb_obs()==0) return 0;\n    return  sqrt( cost(bundle) / (double)(bundle.nb_obs()));\n  }\n\n  // mean square error\n  template<class Bundle> double mse(const Bundle& bundle)\n  {\n    if (bundle.nb_obs()==0) return 0;\n    return   cost(bundle) * 2.0 / (double)(bundle.nb_obs());\n  }\n\n}//eon\n\n#endif\n\n", "meta": {"hexsha": "b45a0ff6b724240f8093a45ce8daca6419eb2f63", "size": 2671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libv/lma/lm/bundle/cost.hpp", "max_stars_repo_name": "bezout/LMA", "max_stars_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-12-08T12:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T21:23:01.000Z", "max_issues_repo_path": "src/libv/lma/lm/bundle/cost.hpp", "max_issues_repo_name": "ayumizll/LMA", "max_issues_repo_head_hexsha": "e945452e12a8b05bd17400b46a20a5322aeda01d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-07-11T16:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T13:33:00.000Z", "max_forks_repo_path": "src/libv/lma/lm/bundle/cost.hpp", "max_forks_repo_name": "bezout/LMA", "max_forks_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-12-21T01:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-26T02:26:55.000Z", "avg_line_length": 27.8229166667, "max_line_length": 101, "alphanum_fraction": 0.6068888057, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6271558534790747}}
{"text": "#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_binary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/core/robust_kernel_impl.h>\n#include <iostream>\n\n#include \"common.h\"\n#include <sophus/se3.hpp>\n#include <sophus/so3.hpp>\n\n#include <Eigen/Dense>\n\nusing namespace Sophus;\nusing namespace Eigen;\nusing namespace std;\n\nstruct Camera\n{\n    Camera() {}\n\n    Camera(double* data)\n    {\n        R = Sophus::SO3d::exp(Eigen::Vector3d(data[0], data[1], data[2]));\n        t = Eigen::Vector3d(data[3], data[4], data[5]);\n        f = data[6];\n        k1 = data[7];\n        k2 = data[8];\n    }\n\n    void set_to(double* data) const\n    {\n        Eigen::Vector3d r = R.log();\n        for (int i = 0; i < 3; ++i)\n        {\n            data[i] = r[i];\n            data[i+3] = t[i];\n        }\n        data[6] = f;\n        data[7] = k1;\n        data[8] = k2;\n    }\n\n    Sophus::SO3d R;\n    Eigen::Vector3d t = Eigen::Vector3d::Zero();\n    double f = 0.0, k1 = 0.0, k2 = 0.0;\n};\n\nclass VertexCamera: public g2o::BaseVertex<9, Camera>\n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    virtual void setToOriginImpl() override {\n        _estimate = Camera();\n    }\n\n    virtual void oplusImpl(const double *update) override {\n        _estimate.R = Sophus::SO3d::exp(Eigen::Vector3d(update[0], update[1], update[2])) * _estimate.R;\n        _estimate.t += Eigen::Map<const Eigen::Vector3d>(update+3);\n        _estimate.f += update[6];\n        _estimate.k1 += update[7];\n        _estimate.k2 += update[8];\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n};\n\nclass VertexLandmark: public g2o::BaseVertex<3, Eigen::Vector3d>\n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    virtual void setToOriginImpl() override {\n        _estimate = Eigen::Vector3d::Zero();       \n    }\n\n    virtual void oplusImpl(const double *update) override {\n        _estimate += Eigen::Map<const Eigen::Vector3d>(update);\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n};\n\n\nclass EdgeReprojection: public g2o::BaseBinaryEdge<2, Eigen::Vector2d, VertexCamera, VertexLandmark>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    EdgeReprojection() { }\n\n    virtual void computeError() override {\n        const VertexCamera* v_cam = static_cast<VertexCamera*>(_vertices[0]);\n        const VertexLandmark* v_point = static_cast<VertexLandmark*>(_vertices[1]);\n        auto cam = v_cam->estimate();\n        Eigen::Vector3d X = v_point->estimate();\n        Eigen::Vector3d X_cam = (cam.R * X) + cam.t;\n        X_cam /= -X_cam.z(); // minus because of dataset\n        auto p2 = X_cam.x() * X_cam.x() + X_cam.y() * X_cam.y();\n        auto r = 1.0 + p2 * (cam.k1 + (p2 * cam.k2));\n\n        Eigen::Vector2d uv = X_cam.head<2>() * r * cam.f;\n        _error = _measurement - uv;\n    }\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n\n};\n\n\nint main(int argc, char **argv) {\n\n    if (argc != 2) {\n        cout << \"usage: bundle_adjustment_g2o bal_data.txt\" << endl;\n        return 1;\n    }\n\n    BALProblem dataset(argv[1]);\n    dataset.Normalize();\n    dataset.Perturb(0.1, 0.5, 0.5);\n    dataset.WriteToPLYFile(\"initial_pc.ply\");\n\n    std::cout << \"\\n\";\n    std::cout << \"nb cameras: \" << dataset.num_cameras() << std::endl;\n    std::cout << \"nb landmarks: \" << dataset.num_points() << std::endl;\n    std::cout << \"nb observations: \" << dataset.num_observations() << std::endl;\n    std::cout << \"nb parameters: \" << dataset.num_parameters() << std::endl;\n    std::cout << \"check: \" << dataset.num_cameras() * 9 + dataset.num_points()*3 << std::endl;\n\n\n    // pose dimension 9, landmark is 3\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<9, 3>> BlockSolverType;\n    typedef g2o::LinearSolverCSparse<BlockSolverType::PoseMatrixType> LinearSolverType;\n\n    auto solver = new g2o::OptimizationAlgorithmLevenberg(\n        g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>())\n    );\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    optimizer.setVerbose(true);\n\n\n    auto* cameras = dataset.mutable_cameras();\n    std::vector<VertexCamera*> camera_vertices;\n    for (int i = 0; i < dataset.num_cameras(); ++i)\n    {\n        auto *c = new VertexCamera();\n        c->setId(i);\n        c->setEstimate(Camera(cameras + (i*dataset.camera_block_size())));\n        optimizer.addVertex(c);\n        camera_vertices.push_back(c);\n    }\n    \n    auto* landmarks = dataset.mutable_points();\n    std::vector<VertexLandmark*> landmark_vertices;\n    for (int i = 0; i < dataset.num_points(); ++i)\n    {\n        auto* l = new VertexLandmark();\n        l->setId(dataset.num_cameras() + i);\n        l->setEstimate(Eigen::Map<Eigen::Vector3d>(landmarks + i*dataset.point_block_size()));\n        l->setMarginalized(true);\n        optimizer.addVertex(l);\n        landmark_vertices.push_back(l);\n    }\n\n    auto* observations = dataset.observations();\n    auto* cam_indices = dataset.camera_index();\n    auto* landmark_indices = dataset.point_index();\n    for (int i = 0; i < dataset.num_observations(); ++i)\n    {\n        auto* e = new EdgeReprojection();\n        e->setVertex(0, camera_vertices[cam_indices[i]]);\n        e->setVertex(1, landmark_vertices[landmark_indices[i]]);\n        e->setMeasurement(Eigen::Map<const Eigen::Vector2d>(observations + i*2));\n        e->setInformation(Eigen::Matrix2d::Identity());\n        optimizer.addEdge(e);\n    }\n\n    optimizer.initializeOptimization();\n    optimizer.optimize(40);\n\n\n    for (int i = 0; i < dataset.num_cameras(); ++i)\n    {\n        camera_vertices[i]->estimate().set_to(cameras + (i * dataset.camera_block_size()));\n    }\n    for (int i = 0; i < dataset.num_points(); ++i)\n    {\n        Eigen::Vector3d X = landmark_vertices[i]->estimate();\n        landmarks[i*3] = X.x();\n        landmarks[i*3+1] = X.y();\n        landmarks[i*3+2] = X.z();\n    }\n\n    dataset.WriteToPLYFile(\"after_ba_g2o.ply\");\n\n    return 0;\n}\n", "meta": {"hexsha": "328a8dce0cb9dd3dae9d1c78afda312219648e09", "size": 6164, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch9/bundle_adjustment_g2o_custom.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch9/bundle_adjustment_g2o_custom.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch9/bundle_adjustment_g2o_custom.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2156862745, "max_line_length": 104, "alphanum_fraction": 0.617293965, "num_tokens": 1702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503682, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6271558359728147}}
{"text": "// Copyright Jim Bosch 2010-2012.\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//    (See accompanying file LICENSE_1_0.txt or copy at\r\n//          http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/python/numpy.hpp>\r\n\r\n#include <cmath>\r\n#include <memory>\r\n\r\n#ifndef M_PI\r\n#include <boost/math/constants/constants.hpp>\r\nconst double M_PI = boost::math::constants::pi<double>();\r\n#endif\r\n\r\nnamespace bp = boost::python;\r\nnamespace bn = boost::python::numpy;\r\n\r\n/**\r\n *  A 2x2 matrix class, purely for demonstration purposes.\r\n *\r\n *  Instead of wrapping this class with Boost.Python, we'll convert it to/from numpy.ndarray.\r\n */\r\nclass matrix2 {\r\npublic:\r\n\r\n    double & operator()(int i, int j) {\r\n        return _data[i*2 + j];\r\n    }\r\n\r\n    double const & operator()(int i, int j) const {\r\n        return _data[i*2 + j];\r\n    }\r\n    \r\n    double const * data() const { return _data; }\r\n\r\nprivate:\r\n    double _data[4];\r\n};\r\n\r\n/**\r\n *  A 2-element vector class, purely for demonstration purposes.\r\n *\r\n *  Instead of wrapping this class with Boost.Python, we'll convert it to/from numpy.ndarray.\r\n */\r\nclass vector2 {\r\npublic:\r\n\r\n    double & operator[](int i) {\r\n        return _data[i];\r\n    }\r\n\r\n    double const & operator[](int i) const {\r\n        return _data[i];\r\n    }\r\n    \r\n    double const * data() const { return _data; }\r\n\r\n    vector2 operator+(vector2 const & other) const {\r\n        vector2 r;\r\n        r[0] = _data[0] + other[0];\r\n        r[1] = _data[1] + other[1];\r\n        return  r;\r\n    }\r\n\r\n    vector2 operator-(vector2 const & other) const {\r\n        vector2 r;\r\n        r[0] = _data[0] - other[0];\r\n        r[1] = _data[1] - other[1];\r\n        return  r;\r\n    }\r\n\r\nprivate:\r\n    double _data[2];\r\n};\r\n\r\n/**\r\n *  Matrix-vector multiplication.\r\n */\r\nvector2 operator*(matrix2 const & m, vector2 const & v) {\r\n    vector2 r;\r\n    r[0] = m(0, 0) * v[0] + m(0, 1) * v[1];\r\n    r[1] = m(1, 0) * v[0] + m(1, 1) * v[1];\r\n    return r;\r\n}\r\n\r\n/**\r\n *  Vector inner product.\r\n */\r\ndouble dot(vector2 const & v1, vector2 const & v2) {\r\n    return v1[0] * v2[0] + v1[1] * v2[1];\r\n}\r\n\r\n/**\r\n *  This class represents a simple 2-d Gaussian (Normal) distribution, defined by a\r\n *  mean vector 'mu' and a covariance matrix 'sigma'.\r\n */\r\nclass bivariate_gaussian {\r\npublic:\r\n\r\n    vector2 const & get_mu() const { return _mu; }\r\n\r\n    matrix2 const & get_sigma() const { return _sigma; }\r\n\r\n    /**\r\n     *  Evaluate the density of the distribution at a point defined by a two-element vector.\r\n     */\r\n    double operator()(vector2 const & p) const {\r\n        vector2 u = _cholesky * (p - _mu);\r\n        return 0.5 * _cholesky(0, 0) * _cholesky(1, 1) * std::exp(-0.5 * dot(u, u)) / M_PI;\r\n    }\r\n\r\n    /**\r\n     *  Evaluate the density of the distribution at an (x, y) point.\r\n     */\r\n    double operator()(double x, double y) const {\r\n        vector2 p;\r\n        p[0] = x;\r\n        p[1] = y;\r\n        return operator()(p);\r\n    }\r\n\r\n    /**\r\n     *  Construct from a mean vector and covariance matrix.\r\n     */\r\n    bivariate_gaussian(vector2 const & mu, matrix2 const & sigma)\r\n        : _mu(mu), _sigma(sigma), _cholesky(compute_inverse_cholesky(sigma))\r\n    {}\r\n    \r\nprivate:\r\n\r\n    /**\r\n     *  This evaluates the inverse of the Cholesky factorization of a 2x2 matrix;\r\n     *  it's just a shortcut in evaluating the density.\r\n     */\r\n    static matrix2 compute_inverse_cholesky(matrix2 const & m) {\r\n        matrix2 l;\r\n        // First do cholesky factorization: l l^t = m\r\n        l(0, 0) = std::sqrt(m(0, 0));\r\n        l(0, 1) = m(0, 1) / l(0, 0);\r\n        l(1, 1) = std::sqrt(m(1, 1) - l(0,1) * l(0,1));\r\n        // Now do forward-substitution (in-place) to invert:\r\n        l(0, 0) = 1.0 / l(0, 0);\r\n        l(1, 0) = l(0, 1) = -l(0, 1) / l(1, 1);\r\n        l(1, 1) = 1.0 / l(1, 1);\r\n        return l;\r\n    }\r\n\r\n    vector2 _mu;\r\n    matrix2 _sigma;\r\n    matrix2 _cholesky;\r\n                        \r\n};\r\n\r\n/*\r\n *  We have a two options for wrapping get_mu and get_sigma into NumPy-returning Python methods:\r\n *   - we could deep-copy the data, making totally new NumPy arrays;\r\n *   - we could make NumPy arrays that point into the existing memory.\r\n *  The latter is often preferable, especially if the arrays are large, but it's dangerous unless\r\n *  the reference counting is correct: the returned NumPy array needs to hold a reference that\r\n *  keeps the memory it points to from being deallocated as long as it is alive.  This is what the\r\n *  \"owner\" argument to from_data does - the NumPy array holds a reference to the owner, keeping it\r\n *  from being destroyed.\r\n *\r\n *  Note that this mechanism isn't completely safe for data members that can have their internal\r\n *  storage reallocated.  A std::vector, for instance, can be invalidated when it is resized,\r\n *  so holding a Python reference to a C++ class that holds a std::vector may not be a guarantee\r\n *  that the memory in the std::vector will remain valid.\r\n */\r\n\r\n/**\r\n *  These two functions are custom wrappers for get_mu and get_sigma, providing the shallow-copy\r\n *  conversion with reference counting described above.\r\n *\r\n *  It's also worth noting that these return NumPy arrays that cannot be modified in Python;\r\n *  the const overloads of vector::data() and matrix::data() return const references, \r\n *  and passing a const pointer to from_data causes NumPy's 'writeable' flag to be set to false.\r\n */\r\nstatic bn::ndarray py_get_mu(bp::object const & self) {\r\n    vector2 const & mu = bp::extract<bivariate_gaussian const &>(self)().get_mu();\r\n    return bn::from_data(\r\n        mu.data(),\r\n        bn::dtype::get_builtin<double>(),\r\n        bp::make_tuple(2),\r\n        bp::make_tuple(sizeof(double)),\r\n        self\r\n    );  \r\n}\r\nstatic bn::ndarray py_get_sigma(bp::object const & self) {\r\n    matrix2 const & sigma = bp::extract<bivariate_gaussian const &>(self)().get_sigma();\r\n    return bn::from_data(\r\n        sigma.data(),\r\n        bn::dtype::get_builtin<double>(),\r\n        bp::make_tuple(2, 2),\r\n        bp::make_tuple(2 * sizeof(double), sizeof(double)),\r\n        self\r\n    );\r\n}\r\n\r\n/**\r\n *  To allow the constructor to work, we need to define some from-Python converters from NumPy arrays\r\n *  to the matrix/vector types.  The rvalue-from-python functionality is not well-documented in Boost.Python\r\n *  itself; you can learn more from boost/python/converter/rvalue_from_python_data.hpp.\r\n */\r\n\r\n/**\r\n *  We start with two functions that just copy a NumPy array into matrix/vector objects.  These will be used\r\n *  in the templated converted below.  The first just uses the operator[] overloads provided by\r\n *  bp::object.\r\n */\r\nstatic void copy_ndarray_to_mv2(bn::ndarray const & array, vector2 & vec) {\r\n    vec[0] = bp::extract<double>(array[0]);\r\n    vec[1] = bp::extract<double>(array[1]);\r\n}\r\n\r\n/**\r\n *  Here, we'll take the alternate approach of using the strides to access the array's memory directly.\r\n *  This can be much faster for large arrays.\r\n */\r\nstatic void copy_ndarray_to_mv2(bn::ndarray const & array, matrix2 & mat) {\r\n    // Unfortunately, get_strides() can't be inlined, so it's best to call it once up-front.\r\n    Py_intptr_t const * strides = array.get_strides();\r\n    for (int i = 0; i < 2; ++i) {\r\n        for (int j = 0; j < 2; ++j) {\r\n            mat(i, j) = *reinterpret_cast<double const *>(array.get_data() + i * strides[0] + j * strides[1]);\r\n        }\r\n    }\r\n}\r\n\r\n/**\r\n *  Here's the actual converter.  Because we've separated the differences into the above functions,\r\n *  we can write a single template class that works for both matrix2 and vector2.\r\n */\r\ntemplate <typename T, int N>\r\nstruct mv2_from_python {\r\n    \r\n    /**\r\n     *  Register the converter.\r\n     */\r\n    mv2_from_python() {\r\n        bp::converter::registry::push_back(\r\n            &convertible,\r\n            &construct,\r\n            bp::type_id< T >()\r\n        );\r\n    }\r\n\r\n    /**\r\n     *  Test to see if we can convert this to the desired type; if not return zero.\r\n     *  If we can convert, returned pointer can be used by construct().\r\n     */\r\n    static void * convertible(PyObject * p) {\r\n        try {\r\n            bp::object obj(bp::handle<>(bp::borrowed(p)));\r\n            std::auto_ptr<bn::ndarray> array(\r\n                new bn::ndarray(\r\n                    bn::from_object(obj, bn::dtype::get_builtin<double>(), N, N, bn::ndarray::V_CONTIGUOUS)\r\n                )\r\n            );\r\n            if (array->shape(0) != 2) return 0;\r\n            if (N == 2 && array->shape(1) != 2) return 0;\r\n            return array.release();\r\n        } catch (bp::error_already_set & err) {\r\n            bp::handle_exception();\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    /**\r\n     *  Finish the conversion by initializing the C++ object into memory prepared by Boost.Python.\r\n     */\r\n    static void construct(PyObject * obj, bp::converter::rvalue_from_python_stage1_data * data) {\r\n        // Extract the array we passed out of the convertible() member function.\r\n        std::auto_ptr<bn::ndarray> array(reinterpret_cast<bn::ndarray*>(data->convertible));\r\n        // Find the memory block Boost.Python has prepared for the result.\r\n        typedef bp::converter::rvalue_from_python_storage<T> storage_t;\r\n        storage_t * storage = reinterpret_cast<storage_t*>(data);\r\n        // Use placement new to initialize the result.\r\n        T * m_or_v = new (storage->storage.bytes) T();\r\n        // Fill the result with the values from the NumPy array.\r\n        copy_ndarray_to_mv2(*array, *m_or_v);\r\n        // Finish up.\r\n        data->convertible = storage->storage.bytes;\r\n    }\r\n\r\n};\r\n\r\n\r\nBOOST_PYTHON_MODULE(gaussian) {\r\n    bn::initialize();\r\n\r\n    // Register the from-python converters\r\n    mv2_from_python< vector2, 1 >();\r\n    mv2_from_python< matrix2, 2 >();\r\n\r\n    typedef double (bivariate_gaussian::*call_vector)(vector2 const &) const;\r\n\r\n    bp::class_<bivariate_gaussian>(\"bivariate_gaussian\", bp::init<bivariate_gaussian const &>())\r\n\r\n        // Declare the constructor (wouldn't work without the from-python converters).\r\n        .def(bp::init< vector2 const &, matrix2 const & >())\r\n\r\n        // Use our custom reference-counting getters\r\n        .add_property(\"mu\", &py_get_mu)\r\n        .add_property(\"sigma\", &py_get_sigma)\r\n\r\n        // First overload accepts a two-element array argument\r\n        .def(\"__call__\", (call_vector)&bivariate_gaussian::operator())\r\n\r\n        // This overload works like a binary NumPy universal function: you can pass\r\n        // in scalars or arrays, and the C++ function will automatically be called\r\n        // on each element of an array argument.\r\n        .def(\"__call__\", bn::binary_ufunc<bivariate_gaussian,double,double,double>::make())\r\n        ;\r\n}\r\n", "meta": {"hexsha": "17e8f88bbfb2baacc93be2d2ada30efaafb0a9a6", "size": 10768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/python/example/numpy/gaussian.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/python/example/numpy/gaussian.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/python/example/numpy/gaussian.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 34.0759493671, "max_line_length": 111, "alphanum_fraction": 0.6060549777, "num_tokens": 2790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6271275155290378}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <thread>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\n#include <boost/timer.hpp>\n\n// for sophus\n#include <sophus/se3.hpp>\n\nusing Sophus::SE3d;\n\n// for eigen\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace Eigen;\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgcodecs/imgcodecs.hpp>\n\n\n#include \"constants.h\"\n#include \"cuda_wrapper.h\"\n#include \"kernels.cuh\"\n#include \"plot.h\"\n\nusing namespace cv;\n\n\n/**\n * Dataset from:\n * \n *   http://rpg.ifi.uzh.ch/datasets/remode_test_data.zip\n * \n * */\n\n\ninline double getBilinearInterpolatedValue_no_eigen(const unsigned char *img, double pt[2]) {\n    const unsigned char* d = &img[(int)pt[1] * width + (int)pt[0]];\n    double xx = pt[0] - floor(pt[0]);\n    double yy = pt[1] - floor(pt[1]);\n    return ((1 - xx) * (1 - yy) * double(d[0]) +\n            xx * (1 - yy) * double(d[1]) +\n            (1 - xx) * yy * double(d[width]) +\n            xx * yy * double(d[width + 1])) / 255.0;\n}\n\n\ninline void pix2cam_no_eigen(const double in[2], double out[3]) {\n    out[0] = (in[0] - cx) / fx;\n    out[1] =  (in[1] - cy) / fy;\n    out[2] = 1.0;\n}\n\n\ninline void cam2pix_no_eigen(const double in[3], double out[2]) {\n    out[0] = in[0] * fx / in[2] + cx;\n    out[1] = in[1] * fy / in[2] + cy;\n}\n\n\ninline double norm3_no_eigen(const double in[3])\n{\n    return sqrt(in[0]*in[0] + in[1]*in[1] + in[2]*in[2]);\n}\n\n\ninline double norm2_no_eigen(const double in[2])\n{\n    return sqrt(in[0]*in[0] + in[1]*in[1]);\n}\n\n\n// inplace normalization vec 3\n\ninline void normalize3_no_eigen(double in_out[3]) {\n    double d = sqrt(in_out[0]*in_out[0] \n                    + in_out[1]*in_out[1]\n                    + in_out[2]*in_out[2]);\n    in_out[0] /= d;\n    in_out[1] /= d;\n    in_out[2] /= d;\n}\n\n// inplace normalization vec 2\n\ninline void normalize2_no_eigen(double in_out[2]) {\n    double d = sqrt(in_out[0]*in_out[0] + in_out[1]*in_out[1]);\n    in_out[0] /= d;\n    in_out[1] /= d;\n}\n\n\ninline void transform_no_eigen(double x[3], const double T[12], double out[3])\n{\n    for (int i = 0; i < 3; ++i)\n    {\n        out[i] = x[0] * T[i*4] + x[1] * T[i*4+1] + x[2] * T[i*4+2] +  T[i*4+3];\n    }\n}\n\n\n\ndouble ZNCC_no_eigen(const unsigned char *im1, const double pt1[2], const unsigned char *im2, const double pt2[2])\n{\n    // no need to consider block partly outside because of boarder\n    double v1[ncc_area], v2[ncc_area];\n    double s1 = 0.0, s2 = 0.0;\n    int idx = 0;\n    for (int i = -ncc_window_size; i <= ncc_window_size; ++i)\n    {\n        for (int j = -ncc_window_size; j <= ncc_window_size; ++j)\n        {\n            double val_1 = ((double) im1[((int)pt1[1] + i) * width + (int)pt1[0] + j]) / 255;\n            double temp_p2[2] = {pt2[0] + j, pt2[1] + i};\n            double val_2 = getBilinearInterpolatedValue_no_eigen(im2, temp_p2);\n            s1 += val_1;\n            s2 += val_2;\n            v1[idx] = val_1;\n            v2[idx] = val_2;\n            ++idx;\n        }\n    }\n\n    double mean_1 = s1 / ncc_area;\n    double mean_2 = s2 / ncc_area;\n\n    double numerator = 0.0;\n    double den1 = 0.0, den2 = 0.0;\n    for (int i = 0; i < ncc_area; ++i)\n    {\n        double zv1 = v1[i] - mean_1;\n        double zv2 = v2[i] - mean_2;\n        numerator += zv1*zv2;\n        den1 += zv1 * zv1;\n        den2 += zv2 * zv2;\n    }\n    auto zncc =  numerator / (sqrt(den1 * den2 + epsilon));\n    // std::cout << \"zncc = \" << zncc << \"\\n\";\n    return zncc;\n}\n\n\nbool epipolar_search_no_eigen(const unsigned char* ref, const unsigned char* cur, \n                          const double Tcr[12], const double pt[2],\n                          double depth_mu, double depth_sigma2, \n                          double best_pc[2], double epipolar_dir[2])\n{\n\n    double depth_sigma = sqrt(depth_sigma2);\n    double dmax = depth_mu + 3 * depth_sigma;\n    double dmin = depth_mu - 3 * depth_sigma;\n    dmin = max(0.1, dmin);\n\n    double pn[3];\n    pix2cam_no_eigen(pt, pn);\n    normalize3_no_eigen(pn);\n    double P_max[3] = {pn[0] * dmax, pn[1] * dmax, pn[2] * dmax};\n    double P_min[3] = {pn[0] * dmin, pn[1] * dmin, pn[2] * dmin};\n    double P_mu[3] = {pn[0] * depth_mu, pn[1] * depth_mu, pn[2] * depth_mu};\n\n    double P_max_cur[3], P_min_cur[3], P_mu_cur[3];\n    transform_no_eigen(P_max, Tcr, P_max_cur);\n    transform_no_eigen(P_min, Tcr, P_min_cur);\n    transform_no_eigen(P_mu, Tcr, P_mu_cur);\n\n\n    double pc_max[2], pc_min[2], pc_mu[2];\n    cam2pix_no_eigen(P_max_cur, pc_max);\n    cam2pix_no_eigen(P_min_cur, pc_min);\n    cam2pix_no_eigen(P_mu_cur, pc_mu);\n\n\n    double epipolar_line[2] = {pc_max[0] - pc_min[0], pc_max[1] - pc_min[1]};\n    epipolar_dir[0] = epipolar_line[0];\n    epipolar_dir[1] = epipolar_line[1];\n    normalize2_no_eigen(epipolar_dir);\n    double epipolar_line_norm = norm2_no_eigen(epipolar_line);\n\n    // double step = 0.7;\n    // int nb_samples = std::ceil(epipolar_line.norm() / step);\n\n    double half_range = 0.5 * epipolar_line_norm;\n    if (half_range > 100) half_range = 100;\n\n    double best_zncc = -1.0;\n    for (double l = -half_range; l<= half_range; l+= 0.7)\n    {\n        double p[2] = {pc_mu[0] + l * epipolar_dir[0], pc_mu[1] + l * epipolar_dir[1]};\n\n        if (p[0] < boarder || p[0] >= width-boarder || p[1] < boarder || p[1] >= height-boarder)\n            continue; // p is outside the cur image\n\n        double zncc = ZNCC_no_eigen(ref, pt, cur, p);\n        if (zncc > best_zncc)\n        {\n            best_zncc = zncc;\n            best_pc[0] = p[0];\n            best_pc[1] = p[1];\n        }\n    }\n    if (best_zncc < 0.85)\n        return false;\n    else\n        return true;\n}\n\n\ndouble dot3_no_eigen(const double a[3], const double b[3])\n{\n    return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];\n}\n\n\ndouble det2_no_eigen(const double A[2][2])\n{\n    return A[0][0] * A[1][1] - A[1][0] * A[0][1];\n}\n\n\nvoid solve_Axb2_no_eigen(const double A[2][2], const double b[2], double res[2])\n{\n    double det_inv = 1.0 / det2_no_eigen(A);\n    double A_inv[2][2];\n    A_inv[0][0] = det_inv * A[1][1];\n    A_inv[0][1] = -det_inv * A[0][1];\n    A_inv[1][0] = -det_inv * A[1][0];\n    A_inv[1][1] = det_inv * A[0][0];\n\n    res[0] = A_inv[0][0] * b[0] + A_inv[0][1] * b[1];\n    res[1] = A_inv[1][0] * b[0] + A_inv[1][1] * b[1];\n}\n\n\nvoid update_depth_filter_no_eigen(const double pr[2], const double pc[2], const double Trc[12], const double epipolar_dir[2], double *depth, double *cov2)\n{\n    double fr[3];\n    pix2cam_no_eigen(pr, fr);\n    normalize3_no_eigen(fr);\n\n    double fc[3];\n    pix2cam_no_eigen(pc, fc);\n    normalize3_no_eigen(fc);\n    \n    double f2[3] = {dot3_no_eigen(Trc, fc),\n                    dot3_no_eigen(Trc+4, fc),\n                    dot3_no_eigen(Trc+8, fc)};\n\n    double trc[3] = {Trc[3], Trc[7], Trc[11]};\n    double A[2][2];\n    double b[2];\n\n    A[0][0] = dot3_no_eigen(fr, fr);\n    A[0][1] = dot3_no_eigen(fr, f2);\n    A[1][0] = dot3_no_eigen(f2, fr);\n    A[1][1] = dot3_no_eigen(f2, f2);\n    A[0][1] *= -1;\n    A[1][1] *= -1;\n    \n    b[0] = dot3_no_eigen(fr, trc);\n    b[1] = dot3_no_eigen(f2, trc);\n\n    if (abs(det2_no_eigen(A)) < 1e-20) // not invertible\n        return;\n\n    double res[2];\n    solve_Axb2_no_eigen(A, b, res);\n    double P1[3] = {fr[0] * res[0], fr[1] * res[0], fr[2] * res[0]};\n    double P2[3] = {trc[0] + fc[0] * res[1], trc[1] + fc[1] * res[1], trc[2] + fc[2] * res[1]};\n    double P_est[3] = {(P1[0] + P2[0]) * 0.5, \n                       (P1[1] + P2[1]) * 0.5, \n                       (P1[2] + P2[2]) * 0.5};\n    double depth_obs = norm3_no_eigen(P_est);\n\n    double P[3] = {fr[0] * depth_obs, fr[1] * depth_obs, fr[2] * depth_obs};\n    double a[3] = {P[0] - trc[0], P[1] - trc[1], P[2] - trc[2]};\n\n    double t[3] = {trc[0], trc[1], trc[2]};\n    normalize3_no_eigen(t);\n\n    double alpha = acos(dot3_no_eigen(fr, t));\n    double beta = acos(-dot3_no_eigen(a, t) / norm3_no_eigen(a));\n\n    double pc2[2] = {pc[0] + epipolar_dir[0], pc[1] + epipolar_dir[1]};\n    double fc2[3];\n    pix2cam_no_eigen(pc2, fc2);\n    normalize3_no_eigen(fc2);\n    double beta_2 = acos(-dot3_no_eigen(fc2, t));\n\n    double gamma = M_PI - alpha - beta_2;\n    double d_noise = norm3_no_eigen(trc) * sin(beta_2) / sin(gamma); // sinus law\n    double sigma_obs = depth_obs - d_noise;\n    double sigma2_obs = sigma_obs * sigma_obs;\n\n\n    // Depth fusion\n    double d = depth[(int)pr[1] * width + (int)pr[0]];\n    double sigma2 = cov2[(int)pr[1] * width + (int)pr[0]];\n\n    double d_fused = (sigma2_obs * d + sigma2 * depth_obs) / (sigma2 + sigma2_obs);\n    double sigma2_fused = (sigma2 * sigma2_obs) / (sigma2 + sigma2_obs);\n\n    depth[(int)pr[1] * width + (int)pr[0]] = d_fused;\n    cov2[(int)pr[1] * width + (int)pr[0]] = sigma2_fused;\n\n}\n\n\n\nvoid update_no_eigen(cv::Mat ref, cv::Mat cur, const Sophus::SE3d& Tcr, cv::Mat depth, cv::Mat cov2)\n{\n    Eigen::Vector2d pc;\n    Eigen::Vector2d epipolar_dir;\n    double pc_out[3];\n    double epipolar_dir_out[2];\n\n    Sophus::SE3d Trc = Tcr.inverse();\n    double Tcr_data[12];\n    double Trc_data[12];\n\n    Eigen::Matrix<double, 3, 4, Eigen::RowMajor> Tcr_matrix = Tcr.matrix3x4();\n    Eigen::Matrix<double, 3, 4, Eigen::RowMajor> Trc_matrix = Trc.matrix3x4();\n   \n    int total=0;\n    for (int j = boarder; j < width-boarder; ++j)\n    {\n        for (int i = boarder; i < height-boarder; ++i)\n        {\n            double depth_mu = depth.at<double>(i, j);\n            double depth_sigma2 = cov2.at<double>(i, j);\n            if (depth_sigma2 < min_cov || depth_sigma2 > max_cov)\n                continue;\n            Eigen::Vector2d pr(j, i);\n            bool found = epipolar_search_no_eigen(ref.ptr<unsigned char>(0), cur.ptr<unsigned char>(0),\n                                                  Tcr_matrix.data(), pr.data(),\n                                                  depth_mu, depth_sigma2,\n                                                  pc.data(), epipolar_dir.data());\n            total += found;\n            if (!found)\n                continue;\n            // showEpipolarMatch(ref, cur, pr, pc);\n\n            update_depth_filter_no_eigen(pr.data(), pc.data(), Trc_matrix.data(), epipolar_dir.data(), depth.ptr<double>(0), cov2.ptr<double>(0));\n        }\n    }\n    std::cout << \"total found \" << total << \" / \" << width*height << \"\\n\";\n}\n\n\n\nbool readDatasetFiles(\n    const string &path,\n    vector<string> &color_image_files,\n    vector<SE3d> &poses,\n    cv::Mat &ref_depth\n);\nvoid evaludateDepth(const Mat &depth_truth, const Mat &depth_estimate);\n\n\n\nint main(int argc, char **argv) {\n    if (argc != 2) {\n        cout << \"Usage: dense_mapping path_to_test_dataset\" << endl;\n        return -1;\n    }\n\n    // Read dataset\n    vector<string> color_image_files;\n    vector<SE3d> poses_TWC;\n    Mat ref_depth;\n    bool ret = readDatasetFiles(argv[1], color_image_files, poses_TWC, ref_depth);\n    if (ret == false) {\n        cout << \"Reading image files failed!\" << endl;\n        return -1;\n    }\n    cout << \"read total \" << color_image_files.size() << \" files.\" << endl;\n\n    // Initial depth image\n    Mat ref = imread(color_image_files[0], 0); // gray-scale image\n    SE3d pose_ref_TWC = poses_TWC[0];\n    double init_depth = 3.0;\n    double init_cov2 = 3.0;\n    Mat depth(height, width, CV_64F, init_depth);\n    Mat depth_cov2(height, width, CV_64F, init_cov2);\n\n    for (int index = 1; index < color_image_files.size(); index++) {\n        cout << \"*** loop \" << index << \" ***\" << endl;\n        Mat curr = imread(color_image_files[index], 0);\n        if (curr.data == nullptr) continue;\n        SE3d pose_curr_TWC = poses_TWC[index];\n        SE3d pose_T_C_R = pose_curr_TWC.inverse() * pose_ref_TWC;   // T_C_W * T_W_R = T_C_R\n        chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n        update_no_eigen(ref, curr, pose_T_C_R, depth, depth_cov2);\n        chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n\n        auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n        std::cout << \"Time used: \" << time_used.count() << \"s\\n\";\n\n        evaludateDepth(ref_depth, depth);\n        plotDepth(ref_depth, depth);\n        plotCur(curr);\n        // imshow(\"image\", curr);\n        // waitKey(1);\n    }\n\n    cout << \"estimation returns, saving depth map ...\" << endl;\n    imwrite(\"depth.png\", depth);\n    cout << \"done.\" << endl;\n\n    return 0;\n}\n\nbool readDatasetFiles(\n    const string &path,\n    vector<string> &color_image_files,\n    std::vector<SE3d> &poses,\n    cv::Mat &ref_depth) {\n    ifstream fin(path + \"/first_200_frames_traj_over_table_input_sequence.txt\");\n    if (!fin) return false;\n\n    while (!fin.eof()) {\n        // \u6570\u636e\u683c\u5f0f\uff1a\u56fe\u50cf\u6587\u4ef6\u540d tx, ty, tz, qx, qy, qz, qw \uff0c\u6ce8\u610f\u662f TWC \u800c\u975e TCW\n        string image;\n        fin >> image;\n        double data[7];\n        for (double &d:data) fin >> d;\n\n        color_image_files.push_back(path + string(\"/images/\") + image);\n        poses.push_back(\n            SE3d(Quaterniond(data[6], data[3], data[4], data[5]),\n                 Vector3d(data[0], data[1], data[2]))\n        );\n        if (!fin.good()) break;\n    }\n    fin.close();\n\n    // load reference depth\n    fin.open(path + \"/depthmaps/scene_000.depth\");\n    ref_depth = cv::Mat(height, width, CV_64F);\n    if (!fin) return false;\n    for (int y = 0; y < height; y++)\n        for (int x = 0; x < width; x++) {\n            double depth = 0;\n            fin >> depth;\n            ref_depth.ptr<double>(y)[x] = depth / 100.0;\n        }\n\n    return true;\n}\n\n\n\nvoid evaludateDepth(const Mat &depth_truth, const Mat &depth_estimate) {\n    double ave_depth_error = 0;\n    double ave_depth_error_sq = 0;\n    int cnt_depth_data = 0;\n    for (int y = boarder; y < depth_truth.rows - boarder; y++)\n        for (int x = boarder; x < depth_truth.cols - boarder; x++) {\n            double error = depth_truth.ptr<double>(y)[x] - depth_estimate.ptr<double>(y)[x];\n            ave_depth_error += error;\n            ave_depth_error_sq += error * error;\n            cnt_depth_data++;\n        }\n    ave_depth_error /= cnt_depth_data;\n    ave_depth_error_sq /= cnt_depth_data;\n\n    cout << \"Average squared error = \" << ave_depth_error_sq << \", average error: \" << ave_depth_error << endl;\n}\n", "meta": {"hexsha": "ec61ad560003fffeee6d99a2833ebdf823230e15", "size": 14169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch12/dense_mono/dense_mapping_custom_no_eigen.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch12/dense_mono/dense_mapping_custom_no_eigen.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch12/dense_mono/dense_mapping_custom_no_eigen.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": 29.8924050633, "max_line_length": 154, "alphanum_fraction": 0.5694826734, "num_tokens": 4675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6271275110556327}}
{"text": "/*\n // solvers for Algebraic Riccati equation\n // - Iteration (continuous)\n // - Iteration (discrete)\n // - Arimoto-Potter\n //\n // author: Horibe Takamasa\n */\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <time.h>\n#include <vector>\n#include \"riccati_solver.h\"\n\n#define PRINT_MAT(X) std::cout << #X << \":\\n\" << X << std::endl << std::endl\n\nint\nmain ()\n{\n  const uint dim_x = 4;\n  const uint dim_u = 1;\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(dim_x, dim_x);\n  Eigen::MatrixXd B = Eigen::MatrixXd::Zero(dim_x, dim_u);\n  Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(dim_x, dim_x);\n  Eigen::MatrixXd R = Eigen::MatrixXd::Zero(dim_u, dim_u);\n  Eigen::MatrixXd P = Eigen::MatrixXd::Zero(dim_x, dim_x);\n\n  A(0, 1) = 1.0;\n  A(1, 1) = -15.0;\n  A(1, 2) = 10.0;\n  A(2, 3) = 1.0;\n  A(3, 3) = -15.0;\n  B(1, 0) = 10.0;\n  B(3, 0) = 1.0;\n\n  Q(0, 0) = 1.0;\n  Q(2, 2) = 1.0;\n  Q(3, 3) = 2.0;\n\n  R(0, 0) = 1.0;\n\n  PRINT_MAT(A);\n  PRINT_MAT(B);\n  PRINT_MAT(Q);\n  PRINT_MAT(R);\n\n  /* == iteration based Riccati solution (continuous) == */\n  std::cout << \"-- Iteration based method (continuous) --\" << std::endl;\n  clock_t start = clock();\n  solveRiccatiIterationC(A, B, Q, R, P);\n  clock_t end = clock();\n  std::cout << \"computation time = \" << (double) (end - start) / CLOCKS_PER_SEC << \"sec.\" << std::endl;\n  PRINT_MAT(P);\n\n  /* == iteration based Riccati solution (discrete) == */\n  // discretization\n  const double dt = 0.001;\n  Eigen::MatrixXd I = Eigen::MatrixXd::Identity(dim_x, dim_x);\n  Eigen::MatrixXd Ad = Eigen::MatrixXd::Zero(dim_x, dim_x);\n  Ad = (I + 0.5 * dt * A) * (I - 0.5 * dt * A).inverse();\n  Eigen::MatrixXd Bd;\n  Bd = B * dt;\n\n  std::cout << \"-- Iteration based method (discrete)--\" << std::endl;\n  start = clock();\n  solveRiccatiIterationD(Ad, Bd, Q, R, P);\n  end = clock();\n  std::cout << \"computation time = \" << (double) (end - start) / CLOCKS_PER_SEC << \"sec.\" << std::endl;\n  PRINT_MAT(P);\n\n  /* == eigen decomposition method (Arimoto-Potter algorithm) == */\n  std::cout << \"-- Eigen decomposition mathod --\" << std::endl;\n  start = clock();\n  solveRiccatiArimotoPotter(A, B, Q, R, P);\n  end = clock();\n  std::cout << \"computation time = \" << (double) (end - start) / CLOCKS_PER_SEC << \"sec.\" << std::endl;\n  PRINT_MAT(P);\n\n  return 0;\n}\n", "meta": {"hexsha": "1fd70ef639beb0528cbfbcc7698abd312e8b384b", "size": 2253, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "crowlogic/Riccati_Solver", "max_stars_repo_head_hexsha": "612ee96263533e9a93da960fc20248314e0121d7", "max_stars_repo_licenses": ["MIT"], "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": "crowlogic/Riccati_Solver", "max_issues_repo_head_hexsha": "612ee96263533e9a93da960fc20248314e0121d7", "max_issues_repo_licenses": ["MIT"], "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": "crowlogic/Riccati_Solver", "max_forks_repo_head_hexsha": "612ee96263533e9a93da960fc20248314e0121d7", "max_forks_repo_licenses": ["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.4756097561, "max_line_length": 103, "alphanum_fraction": 0.5943186862, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6271274958443501}}
{"text": "/*\n* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n* its licensors.\n*\n* For complete copyright and license terms please see the LICENSE at the root of this\n* distribution (the \"License\"). All use of this software is governed by the License,\n* or, if provided, by the license below or the license accompanying this file. Do not\n* remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n*\n*/\n\n#include <NumericalMethods_precompiled.h>\n\n#include <cmath>\n\n#include <AzCore/std/algorithm.h>\n\n#include <LinearAlgebra.h>\n#include <Eigenanalysis/Utilities.h>\n\nnamespace NumericalMethods::Eigenanalysis\n{\n    VectorVariable CrossProduct(const VectorVariable& lhs, const VectorVariable& rhs)\n    {\n        AZ_Assert(\n            lhs.GetDimension() == 3 && rhs.GetDimension() == 3, \"VectorVariable dimensions invalid for cross product.\"\n        );\n\n        return VectorVariable::CreateFromVector({\n            lhs[1] * rhs[2] - lhs[2] * rhs[1],\n            lhs[2] * rhs[0] - lhs[0] * rhs[2],\n            lhs[0] * rhs[1] - lhs[1] * rhs[0]\n        });\n    }\n\n    void ComputeOrthogonalComplement(\n        const VectorVariable& vecW, VectorVariable& vecU, VectorVariable& vecV\n    )\n    {\n        // Robustly computes a right-handed orthogonal basis {vecU, vecV, vecW}.\n        double invLength = 1.0;\n\n        if (fabs(vecW[0]) > fabs(vecW[1]))\n        {\n            // The component of maximum absolute value is either vecW[0] or vecW[2].\n            invLength /= sqrt(vecW[0] * vecW[0] + vecW[2] * vecW[2]);\n            vecU = VectorVariable::CreateFromVector({ -vecW[2] * invLength, 0.0, vecW[0] * invLength });\n        }\n        else\n        {\n            // The component of maximum absolute value is either vecW[1] or vecW[2].\n            invLength /= sqrt(vecW[1] * vecW[1] + vecW[2] * vecW[2]);\n            vecU = VectorVariable::CreateFromVector({ 0.0, vecW[2] * invLength, -vecW[1] * invLength });\n        }\n\n        vecV = CrossProduct(vecW, vecU);\n    }\n\n    VectorVariable ComputeEigenvector0(\n        double a00, double a01, double a02, double a11, double a12, double a22, double val\n    )\n    {\n        // By definition, (A\u2212e\u2217I)v = 0, where e is the eigenvalue and v is the corresponding eigenvector to be found.\n        // This condition implies that the rows (A\u2212e\u2217I) must be perpendicular to v. This matrix must have rank 2, so two\n        // rows will be linearly dependent. For those two rows, the cross product will be (nearly) zero. So to find v,\n        // we can simply take the cross product of the two rows that maximize its magnitude.\n        VectorVariable row0 = VectorVariable::CreateFromVector({ a00 - val, a01, a02 });\n        VectorVariable row1 = VectorVariable::CreateFromVector({ a01, a11 - val, a12 });\n        VectorVariable row2 = VectorVariable::CreateFromVector({ a02, a12, a22 - val });\n\n        VectorVariable r0xr1 = CrossProduct(row0, row1);\n        VectorVariable r0xr2 = CrossProduct(row0, row2);\n        VectorVariable r1xr2 = CrossProduct(row1, row2);\n\n        double d0 = r0xr1.Dot(r0xr1);\n        double d1 = r0xr2.Dot(r0xr2);\n        double d2 = r1xr2.Dot(r1xr2);\n\n        return d0 >= d1 && d0 >= d2 ? r0xr1 * (1.0 / sqrt(d0)) :\n               d1 >= d0 && d1 >= d2 ? r0xr2 * (1.0 / sqrt(d1)) :\n                                      r1xr2 * (1.0 / sqrt(d2)) ;\n    }\n\n    VectorVariable ComputeEigenvector1(\n        double a00,\n        double a01,\n        double a02,\n        double a11,\n        double a12,\n        double a22,\n        double val,\n        const VectorVariable& vec\n    )\n    {\n        // Real symmetric matrices must have orthogonal eigenvectors. Thus, if we generate two vectors vecU and vecV\n        // orthogonal to the eigenvector vec already found, the remaining eigenvectors must be a circular combination\n        // of vecU and vecW. This reduces the problem to a 2D system. For details see Eberly.\n        VectorVariable vecU(3);\n        VectorVariable vecV(3);\n        ComputeOrthogonalComplement(vec, vecU, vecV);\n\n        MatrixVariable matA(3, 3);\n\n        matA.Element(0, 0) = a00;\n        matA.Element(0, 1) = a01;\n        matA.Element(0, 2) = a02;\n\n        matA.Element(1, 0) = a01;\n        matA.Element(1, 1) = a11;\n        matA.Element(1, 2) = a12;\n\n        matA.Element(2, 0) = a02;\n        matA.Element(2, 1) = a12;\n        matA.Element(2, 2) = a22;\n\n        double m00 = vecU.Dot(matA * vecU) - val;\n        double absM00 = fabs(m00);\n\n        double m01 = vecU.Dot(matA * vecV);\n        double absM01 = fabs(m01);\n\n        double m11 = vecV.Dot(matA * vecV) - val;\n        double absM11 = fabs(m11);\n\n        auto discardComponentAndNormalize = [](double& factor, double& other) {\n            other /= factor;\n            factor = 1.0 / sqrt(1.0 + other * other);\n            other *= factor;\n        };\n\n        if (absM00 > absM11)\n        {\n            if (AZStd::max(absM00, absM01) > 0.0)\n            {\n                if (absM00 >= absM01)\n                {\n                    discardComponentAndNormalize(m00, m01);\n                }\n                else\n                {\n                    discardComponentAndNormalize(m01, m00);\n                }\n                return vecU * m01 - vecV * m00;\n            }\n            else\n            {\n                return vecU;\n            }\n        }\n        else\n        {\n            if (AZStd::max(absM11, absM01) > 0.0)\n            {\n                if (absM11 >= absM01)\n                {\n                    discardComponentAndNormalize(m11, m01);\n                }\n                else\n                {\n                    discardComponentAndNormalize(m01, m11);\n                }\n                return vecU * m11 - vecV * m01;\n            }\n            else\n            {\n                return vecU;\n            }\n        }\n    }\n\n    VectorVariable ComputeEigenvector2(const VectorVariable& vec0, const VectorVariable& vec1)\n    {\n        return CrossProduct(vec0, vec1);\n    }\n} // namespace NumericalMethods::Eigenanalysis\n", "meta": {"hexsha": "5c77293f7a6bffb979ed6c19b2f8ed81da8ea9b6", "size": 6105, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dev/Gems/PhysX/Code/NumericalMethods/Source/Eigenanalysis/Utilities.cpp", "max_stars_repo_name": "BadDevCode/lumberyard", "max_stars_repo_head_hexsha": "3d688932f919dbf5821f0cb8a210ce24abe39e9e", "max_stars_repo_licenses": ["AML"], "max_stars_count": 1738.0, "max_stars_repo_stars_event_min_datetime": "2017-09-21T10:59:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:05:46.000Z", "max_issues_repo_path": "dev/Gems/PhysX/Code/NumericalMethods/Source/Eigenanalysis/Utilities.cpp", "max_issues_repo_name": "olivier-be/lumberyard", "max_issues_repo_head_hexsha": "3d688932f919dbf5821f0cb8a210ce24abe39e9e", "max_issues_repo_licenses": ["AML"], "max_issues_count": 427.0, "max_issues_repo_issues_event_min_datetime": "2017-09-29T22:54:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T19:26:50.000Z", "max_forks_repo_path": "dev/Gems/PhysX/Code/NumericalMethods/Source/Eigenanalysis/Utilities.cpp", "max_forks_repo_name": "olivier-be/lumberyard", "max_forks_repo_head_hexsha": "3d688932f919dbf5821f0cb8a210ce24abe39e9e", "max_forks_repo_licenses": ["AML"], "max_forks_count": 671.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T08:04:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T14:30:07.000Z", "avg_line_length": 34.4915254237, "max_line_length": 120, "alphanum_fraction": 0.5616707617, "num_tokens": 1642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6271274892827872}}
{"text": "/** @file NormalDist.cpp\n * @author Mark J. Olah (mjo\\@cs.unm DOT edu)\n * @date 2017-2019\n * @brief NormalDist class definition\n * \n */\n#include \"PriorHessian/NormalDist.h\"\n#include \"PriorHessian/PriorHessianError.h\"\n\n#include <sstream>\n#include <cmath>\n#include <limits>\n\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/math/constants/constants.hpp>\n\nnamespace prior_hessian {\n\n/* Static member variables */\nconst StringVecT NormalDist::_param_names = { \"mu\", \"sigma\" };\nconst NormalDist::NparamsVecT NormalDist::_param_lbound = {-INFINITY, 0}; //Lower bound on valid parameter values \nconst NormalDist::NparamsVecT NormalDist::_param_ubound = {INFINITY, INFINITY}; //Upper bound on valid parameter values\n\n\n\n/* Constructors */\nNormalDist::NormalDist(double mu, double sigma) \n    : UnivariateDist()\n{ \n    set_params(mu,sigma);\n}\n\n/* Non-static member functions */\n\nvoid NormalDist::set_sigma(double val) \n{ \n    _sigma = checked_sigma(val); \n    _sigma_inv = 1./_sigma;\n    llh_const_initialized = false;\n}\n\ndouble NormalDist::cdf(double x) const\n{\n    return .5*(1 + boost::math::erf((x - _mu)*_sigma_inv*constants::sqrt2_inv));\n}\n\ndouble NormalDist::icdf(double u) const\n{\n    return mu() + sigma()*constants::sqrt2*boost::math::erf_inv(2*u-1);\n}\n\ndouble NormalDist::checked_mu(double val)\n{\n    if(!std::isfinite(val)) {\n        std::ostringstream msg;\n        msg<<\"NormalDist: got bad mu value:\"<<val;\n        throw ParameterValueError(msg.str());\n    }\n    return val;\n}\n\ndouble NormalDist::checked_sigma(double val)\n{\n    if(val<=0 || !std::isfinite(val)) {\n        std::ostringstream msg;\n        msg<<\"NormalDist: got bad sigma value:\"<<val;\n        throw ParameterValueError(msg.str());\n    }\n    return val;\n}\n\ndouble NormalDist::llh(double x) const \n{ \n    if(!llh_const_initialized) initialize_llh_const(); //Lazy computation of llh_const.\n    return rllh(x) + llh_const;\n}\n\nvoid NormalDist::initialize_llh_const() const\n{\n    llh_const = compute_llh_const(sigma());\n    llh_const_initialized = true;\n}\n\ndouble NormalDist::compute_llh_const(double sigma)\n{\n    return -log(sigma) - .5*constants::log2pi;\n}\n\n} /* namespace prior_hessian */\n", "meta": {"hexsha": "de86a1eea4fa36d4d884c3ba653312a0bc359c34", "size": 2171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NormalDist.cpp", "max_stars_repo_name": "markjolah/PriorHessianLib", "max_stars_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-20T07:40:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T07:40:29.000Z", "max_issues_repo_path": "src/NormalDist.cpp", "max_issues_repo_name": "markjolah/PriorHessianLib", "max_issues_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NormalDist.cpp", "max_forks_repo_name": "markjolah/PriorHessianLib", "max_forks_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_forks_repo_licenses": ["Apache-2.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.1222222222, "max_line_length": 119, "alphanum_fraction": 0.6932289268, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503206, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.6271274868975405}}
{"text": "#include <iostream>\n#include <g2o/core/g2o_core_api.h>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_dogleg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n#include <cmath>\n#include <chrono>\n\nusing namespace std;\n\n// Vertex of curve model, template parameters: optimize variable dimension and data type\nclass CurveFittingVertex : public g2o::BaseVertex<3, Eigen::Vector3d> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  // Reset\n  virtual void setToOriginImpl() override {\n    _estimate << 0, 0, 0;\n  }\n\n  // update\n  virtual void oplusImpl(const double *update) override {\n    _estimate += Eigen::Vector3d(update);\n  }\n\n  // Save and read: leave blank\n  virtual bool read(istream &in) {}\n\n  virtual bool write(ostream &out) const {}\n};\n\n// Error model Template parameters: observation dimension, type, connected vertex type\nclass CurveFittingEdge : public g2o::BaseUnaryEdge<1, double, CurveFittingVertex> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  CurveFittingEdge(double x) : BaseUnaryEdge(), _x(x) {}\n\n  // Calculation curve model error\n  virtual void computeError() override {\n    const CurveFittingVertex *v = static_cast<const CurveFittingVertex *> (_vertices[0]);\n    const Eigen::Vector3d abc = v->estimate();\n    _error(0, 0) = _measurement - std::exp(abc(0, 0) * _x * _x + abc(1, 0) * _x + abc(2, 0));\n  }\n\n  // Calculate the Jacobian matrix\n  virtual void linearizeOplus() override {\n    const CurveFittingVertex *v = static_cast<const CurveFittingVertex *> (_vertices[0]);\n    const Eigen::Vector3d abc = v->estimate();\n    double y = exp(abc[0] * _x * _x + abc[1] * _x + abc[2]);\n    _jacobianOplusXi[0] = -_x * _x * y;\n    _jacobianOplusXi[1] = -_x * y;\n    _jacobianOplusXi[2] = -y;\n  }\n\n  virtual bool read(istream &in) {}\n\n  virtual bool write(ostream &out) const {}\n\npublic:\n  double _x;  // x value, y value is _measurement\n};\n\nint main(int argc, char **argv) {\n  double ar = 1.0, br = 2.0, cr = 1.0;         // True parameter value\n  double ae = 2.0, be = -1.0, ce = 5.0;        // Estimate parameter values\n  int N = 100;                                 // data point\n  double w_sigma = 1.0;                        // noise Sigma value\n  double inv_sigma = 1.0 / w_sigma;\n  cv::RNG rng;                                 // OpenCV random number generator\n\n  vector<double> x_data, y_data;      // data\n  for (int i = 0; i < N; i++) {\n    double x = i / 100.0;\n    x_data.push_back(x);\n    y_data.push_back(exp(ar * x * x + br * x + cr) + rng.gaussian(w_sigma * w_sigma));\n  }\n\n  //Build graph optimization, first set g2o\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<3, 1>> BlockSolverType;  // The optimization variable dimension of each error term is 3, and the error value dimension is 1\n  typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType; // Linear solver type\n\n  // Gradient descent method, choose from GN, LM, DogLe\n  auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n    g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n  g2o::SparseOptimizer optimizer;     // graph model\n  optimizer.setAlgorithm(solver);   // Set the solver\n  optimizer.setVerbose(true);       // Turn on debug output\n\n  // \u5f80\u56fe\u4e2d\u589e\u52a0\u9876\u70b9\n  CurveFittingVertex *v = new CurveFittingVertex();\n  v->setEstimate(Eigen::Vector3d(ae, be, ce));\n  v->setId(0);\n  optimizer.addVertex(v);\n\n  // Add a side to the picture\n  for (int i = 0; i < N; i++) {\n    CurveFittingEdge *edge = new CurveFittingEdge(x_data[i]);\n    edge->setId(i);\n    edge->setVertex(0, v);                //  Set the vertices of the connection\n    edge->setMeasurement(y_data[i]);      // Observe the value\n    edge->setInformation(Eigen::Matrix<double, 1, 1>::Identity() * 1 / (w_sigma * w_sigma)); //Information matrix: the inverse of the covariance matrix\n    optimizer.addEdge(edge);\n  }\n\n  // Perform optimization\n  cout << \"start optimization\" << endl;\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n  optimizer.initializeOptimization();\n  optimizer.optimize(20);\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n\n  // output optimized value\n  Eigen::Vector3d abc_estimate = v->estimate();\n  cout << \"estimated model: \" << abc_estimate.transpose() << endl;\n\n  return 0;\n}", "meta": {"hexsha": "b41d11aa844b219067741eb97c3ee3b438e6ec06", "size": 4693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/g2oCurveFitting.cpp", "max_stars_repo_name": "salahkhan94/slambook2", "max_stars_repo_head_hexsha": "9a2f1694268d5dfd3dbabfbcfb1ada858e62ed33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-28T18:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-28T18:05:53.000Z", "max_issues_repo_path": "ch6/g2oCurveFitting.cpp", "max_issues_repo_name": "salahkhan94/slambook2", "max_issues_repo_head_hexsha": "9a2f1694268d5dfd3dbabfbcfb1ada858e62ed33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch6/g2oCurveFitting.cpp", "max_forks_repo_name": "salahkhan94/slambook2", "max_forks_repo_head_hexsha": "9a2f1694268d5dfd3dbabfbcfb1ada858e62ed33", "max_forks_repo_licenses": ["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.246031746, "max_line_length": 173, "alphanum_fraction": 0.6773918602, "num_tokens": 1346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338727, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6270787472866506}}
{"text": "#include <math_lib/vec_base.h>\n\n#include <math_lib/orthogonal.h>\n\n#include <boost/qvm/vec_operations.hpp>\n\n#include <gtest/gtest.h>\n\nusing namespace pagoda;\n\nTEST(Orthogonal, when_calculating_the_orthogonal_vector_of_a_2d_vector_should_have_zero_as_dot_product)\n{\n\tVec2F v{1, 2};\n\tASSERT_EQ(boost::qvm::dot(v, orthogonal(v)), 0);\n}\n\nTEST(Orthogonal, when_calculating_the_orthogonal_vector_of_a_3d_vector_should_have_zero_as_dot_product)\n{\n\tVec3F v{1, 2, 3};\n\tASSERT_EQ(boost::qvm::dot(v, orthogonal(v)), 0);\n}\n\nTEST(Orthogonal, when_calculating_the_orthogonal_of_a_vector_parallel_with_an_axis_should_have_zero_as_dot_product)\n{\n\tfor (auto v : {Vec3F{1, 0, 0}, Vec3F{0, 1, 0}, Vec3F{0, 0, 1}})\n\t{\n\t\tEXPECT_EQ(boost::qvm::dot(v, orthogonal(v)), 0);\n\t}\n}\n", "meta": {"hexsha": "1e17c140f354fc60b6c9aa02613da0ab6013e776", "size": 753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_tests/math_lib/orthogonal.cpp", "max_stars_repo_name": "diegoarjz/selector", "max_stars_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T17:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-12T14:37:27.000Z", "max_issues_repo_path": "tests/unit_tests/math_lib/orthogonal.cpp", "max_issues_repo_name": "diegoarjz/selector", "max_issues_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47.0, "max_issues_repo_issues_event_min_datetime": "2019-05-27T15:24:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T17:54:54.000Z", "max_forks_repo_path": "tests/unit_tests/math_lib/orthogonal.cpp", "max_forks_repo_name": "diegoarjz/selector", "max_forks_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1, "max_line_length": 115, "alphanum_fraction": 0.7662682603, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6270787366543036}}
{"text": "// adapted from lassopack, see:\n// https://github.com/statalasso/lassopack/blob/master/lassoutils.ado\n\n#include \"../eigen-3.4.0/Eigen/Eigen\"\n#include <iostream>\n#include <math.h>\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <Eigen/Eigen>\n\nnamespace py = pybind11;\nusing namespace Eigen;\nusing namespace std;\n// using MatrixXdRef = Eigen::Ref<Eigen::MatrixXd>;\n// using VectorXdRef = Eigen::Ref<Eigen::VectorXd>;\nusing MatrixXdRef = Eigen::MatrixXd;\nusing VectorXdRef = Eigen::VectorXd;\n\n\nVectorXd coordinateDescent(MatrixXdRef X, VectorXdRef y, MatrixXdRef XX, VectorXdRef Xy,\n                       double lambd, VectorXdRef psi, VectorXdRef startingValues,\n                       bool sqrtLasso = false, bool fitIntercept = true,\n                       double optTol = 1e-10, int maxIter = 1000,\n                       double zeroTol = 1e-4) {\n\n  int n = X.rows(), p = X.cols();\n \n  VectorXd beta = startingValues;\n  \n  VectorXd sdVec = X.colwise().norm();\n  double ySd = y.norm();\n  // normal lasso shooting\n  if (!sqrtLasso) {\n\n    XX *= 2, Xy *= 2;\n    // loop over max iter\n    for (int iter = 0; iter < maxIter; iter++) {\n      // copy beta to beta_old\n      VectorXd betaOld = beta;\n      // loop over p\n      for (int j = 0; j < p; j++) {\n        // calculate s0 and do shooting\n        double S0 = (XX.row(j) * beta).sum() - XX(j, j) * beta(j) - Xy(j);\n\n        if (S0 > lambd * psi(j)) {\n          beta(j) = (lambd * psi(j) - S0) / XX(j, j);\n\n        } else if (S0 < -lambd * psi(j)) {\n          beta(j) = (-lambd * psi(j) - S0) / XX(j, j);\n\n        } else {\n          beta(j) = 0;\n        }\n      }\n      // check for convergence\n      double diff = ((beta - betaOld).cwiseAbs() * sdVec / ySd).sum();\n      // double diff = (beta - betaOld).cwiseAbs().sum();\n      if (diff < optTol) {\n        break;\n      }\n    }\n    // sqrt-lasso shooting algorithm\n  } else {\n    // rescale XX and Xy\n    XX /= n;\n    Xy /= n;\n    double MaxErrorNorm = 1.0e-10;\n\n    // demean X and y\n    // if (fitIntercept) {\n    //   MatrixXd meanX = X.colwise().mean().replicate(n, 1);\n    //   VectorXd meanY = VectorXd::Ones(n) * y.mean();\n    //   X = X - meanX;\n    //   y = y - meanY;\n    // }\n\n    // get error\n    VectorXd error = y - X * beta;\n    double qhat = error.squaredNorm() / n;\n\n    \n    for (int iter = 0; iter < maxIter; iter++) {\n      VectorXd betaOld = beta;\n\n      for (int j = 0; j < p; j++) {\n\n        if (fabs(beta(j)) > 0) {\n          error += X.col(j) * beta(j);\n          qhat = error.squaredNorm() / n;\n        }\n\n        double S0 = XX.row(j).dot(beta) - XX(j, j) * beta(j) - Xy(j);\n        double qqhat = max(qhat - (pow(S0, 2) / XX(j, j)), 0.0);\n\n        if (pow(n, 2) < pow(lambd * psi(j), 2) / XX(j, j)) {\n          beta(j) = 0;\n        }\n\n        else if (S0 > lambd / n * psi(j) * sqrt(qhat)) {\n          beta[j] = ((lambd * psi(j) /\n                      sqrt(pow(n, 2) - pow(lambd * psi(j), 2) / XX(j, j))) *\n                         sqrt(qqhat) -\n                     S0) /\n                    XX(j, j);\n          error -= X.col(j) * beta[j];\n        }\n\n        else if (S0 < -lambd / n * psi(j) * sqrt(qhat)) { // Optimal beta(j) > 0\n          beta[j] = (-(lambd * psi(j) /\n                       sqrt(pow(n, 2) - pow(lambd * psi(j), 2) / XX(j, j))) *\n                         sqrt(qqhat) -\n                     S0) /\n                    XX(j, j);\n          error -= X.col(j) * beta(j);\n        }\n\n        else {\n          beta(j) = 0;\n        }\n      } // end loop beta^(i)_j\n\n      // Update primal and dual value\n      double errorNorm = (y - X * beta).norm();\n      double fobj =\n          errorNorm / sqrt(n) + (lambd / n) * (psi * beta.cwiseAbs()).sum();\n\n      double dual;\n      if (errorNorm > MaxErrorNorm) {\n        VectorXd aaa = sqrt(n) * (error / errorNorm);\n        double bbb = ((lambd / n) * psi - (X.transpose() * aaa / n).cwiseAbs()).cwiseAbs().transpose() * beta.cwiseAbs();\n        dual = aaa.transpose() * (y / n) - bbb;\n      } else {\n        dual = (lambd / n) * (psi * beta.cwiseAbs()).sum();\n      }\n      \n      // check for convergence\n      double diff = (beta - betaOld).cwiseAbs().sum();\n      // double diff = ((beta - betaOld).cwiseAbs() * (sdVec / ySd)).sum();\n      if (diff < optTol) {\n        if ((fobj - dual)  < 1e-6) {\n        // if ((fobj - dual) / ySd < optTol) {\n          break;\n        }\n      }\n    }\n  }\n  // set beta to zero below threshold\n  for (int j = 0; j < p; j++) {\n    if (abs(beta(j)) < zeroTol) {\n      beta(j) = 0;\n    }\n  }\n  return beta;\n}\n\n// docstring\nstring docstring = R\"mydelimiter(\n    \"Lasso Shooting algorithm for and sqrt lasso.\"\n\n    Parameters\n    ----------\n    X : numpy array\n        design matrix\n    y : numpy array\n        response vector\n    XX : ndarray\n      cross product matrix of X\n    Xy : ndarray\n      cross product vector of X and y\n    lambd : float\n        Regularization parameter.\n    psi : float\n        Penalty loadings.\n    starting_values : ndarray, optional, default: None\n        Initial beta estimate.\n    sqrt : bool, optional, default False\n        If True, use sqrt lasso.\n        beta = min ||(y - X @ beta)||_2^2 + lambd ||psi @ beta||_1\n    fit_intercept : bool, optional, default true\n        If True, fit intercept. Only relevant for sqrt lasso.\n    max_iter : int, optional, default: 1000\n        Maximum number of iterations.\n    opt_tol : float, optional, default: 1e-10\n        Optimality tolerance.\n    zero_tol : float, optional, default: 1e-4\n        Zero tolerance. If beta(j) is smaller than zero_tol, \n        set beta(j) = 0.\n\n    Returns\n    -------\n    beta : ndarray\n        Estimated beta.\n)mydelimiter\";\n\nPYBIND11_MODULE(_solver_fast, m) {\n  py::options options;\n  options.disable_function_signatures();\n  m.doc() = \"Coordinate descent solver for lasso and sqrt-lasso\";\n  m.def(\"_cd_solver\", &coordinateDescent, docstring.c_str(),\n        py::arg(\"X\").noconvert() = NULL, \n        py::arg(\"y\").noconvert() = NULL,\n        py::arg(\"XX\").noconvert() = NULL, \n        py::arg(\"Xy\").noconvert() = NULL,\n        py::arg(\"lambd\").noconvert() = NULL, \n        py::arg(\"psi\").noconvert() = NULL,\n        py::arg(\"starting_values\").noconvert() = NULL, \n        py::arg(\"sqrt\") = false,\n        py::arg(\"fit_intercept\") = true, \n        py::arg(\"opt_tol\") = 1e-10,\n        py::arg(\"max_iter\") = 1000, \n        py::arg(\"zero_tol\") = 1e-4);\n};\n", "meta": {"hexsha": "11acaa91930f634ff416f5071c7d3a4a2ba1ab99", "size": 6406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rlassomodels/_solver_fast.cpp", "max_stars_repo_name": "MatPiq/rlassopy", "max_stars_repo_head_hexsha": "ade5daf156c7678215f1cf896e105fc464fa53fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rlassomodels/_solver_fast.cpp", "max_issues_repo_name": "MatPiq/rlassopy", "max_issues_repo_head_hexsha": "ade5daf156c7678215f1cf896e105fc464fa53fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rlassomodels/_solver_fast.cpp", "max_forks_repo_name": "MatPiq/rlassopy", "max_forks_repo_head_hexsha": "ade5daf156c7678215f1cf896e105fc464fa53fe", "max_forks_repo_licenses": ["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.0751173709, "max_line_length": 121, "alphanum_fraction": 0.5156103653, "num_tokens": 1946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.627078731628218}}
{"text": "<<<<<<< HEAD\r\n/*    Copyright (c) 2010-2018, Delft University of Technology\r\n=======\r\n/*    Copyright (c) 2010-2019, Delft University of Technology\r\n>>>>>>> origin/master\r\n *    All rigths reserved\r\n *\r\n *    This file is part of the Tudat. Redistribution and use in source and\r\n *    binary forms, with or without modification, are permitted exclusively\r\n *    under the terms of the Modified BSD license. You should have received\r\n *    a copy of the license with this file. If not, please or visit:\r\n *    http://tudat.tudelft.nl/LICENSE.\r\n */\r\n\r\n#include <Eigen/Geometry>\r\n\r\n#include \"Tudat/Astrodynamics/Relativity/relativisticAccelerationCorrection.h\"\r\n\r\nnamespace tudat\r\n{\r\n\r\nnamespace relativity\r\n{\r\n\r\n//! Function to compute a term common to several relativistic acceleration terms\r\ndouble calculateRelativisticAccelerationCorrectionsCommonterm(\r\n        const double centralBodyGravitationalParameter,\r\n        const double relativeDistance )\r\n{\r\n    return centralBodyGravitationalParameter /\r\n            ( physical_constants::SPEED_OF_LIGHT * physical_constants::SPEED_OF_LIGHT *\r\n              relativeDistance * relativeDistance * relativeDistance );\r\n}\r\n\r\n//! Function to compute the Schwarzschild term of the relativistic acceleration correction.\r\nEigen::Vector3d calculateScharzschildGravitationalAccelerationCorrection(\r\n        const double centralBodyGravitationalParameter,\r\n        const Eigen::Vector3d& relativePosition,\r\n        const Eigen::Vector3d& relativeVelocity,\r\n        const double relativeDistance,\r\n        const double commonCorrectionTerm,\r\n        const double ppnParameterGamma,\r\n        const double ppnParameterBeta )\r\n{\r\n    Eigen::Vector3d acceleration = ( 2.0 * ( ppnParameterGamma + ppnParameterBeta ) *\r\n                      centralBodyGravitationalParameter / relativeDistance - ppnParameterGamma *\r\n                      relativeVelocity.dot( relativeVelocity ) ) * relativePosition +\r\n            2.0 * ( 1.0 + ppnParameterGamma ) * ( relativePosition.dot( relativeVelocity ) ) * relativeVelocity;\r\n    return commonCorrectionTerm * acceleration;\r\n}\r\n\r\n//! Function to compute the Schwarzschild term of the relativistic acceleration correction.\r\nEigen::Vector3d calculateScharzschildGravitationalAccelerationCorrection(\r\n        double centralBodyGravitationalParameter,\r\n        const Eigen::Vector6d& relativeState,\r\n        double ppnParameterGamma,\r\n        double ppnParameterBeta )\r\n{\r\n    return calculateScharzschildGravitationalAccelerationCorrection(\r\n                centralBodyGravitationalParameter, relativeState.segment( 0, 3 ),\r\n                relativeState.segment( 3, 3 ), relativeState.segment( 0, 3 ).norm( ),\r\n                calculateRelativisticAccelerationCorrectionsCommonterm(\r\n                    centralBodyGravitationalParameter, relativeState.segment( 0, 3 ).norm( ) ),\r\n                ppnParameterGamma, ppnParameterBeta );\r\n}\r\n\r\n//! Function to compute the Lense-Thirring term of the relativistic acceleration correction.\r\nEigen::Vector3d calculateLenseThirringCorrectionAcceleration(\r\n        const Eigen::Vector3d& relativePosition,\r\n        const Eigen::Vector3d& relativeVelocity,\r\n        const double relativeDistance,\r\n        const double commonCorrectionTerm,\r\n        const Eigen::Vector3d& centralBodyAngularMomentum,\r\n        const double ppnParameterGamma )\r\n{\r\n    Eigen::Vector3d acceleration = 3.0 / (\r\n                relativeDistance * relativeDistance ) *\r\n            relativePosition.cross( relativeVelocity ) *\r\n            ( relativePosition.dot( centralBodyAngularMomentum ) ) +\r\n            relativeVelocity.cross( centralBodyAngularMomentum );\r\n    return acceleration * ( 1.0 + ppnParameterGamma ) * commonCorrectionTerm;\r\n}\r\n\r\n//! Function to compute the Lense-Thirring term of the relativistic acceleration correction.\r\nEigen::Vector3d calculateLenseThirringCorrectionAcceleration(\r\n        const double centralBodyGravitationalParameter,\r\n        const Eigen::Vector6d& relativeState,\r\n        const Eigen::Vector3d& centralBodyAngularMomentum,\r\n        const double ppnParameterGamma )\r\n{\r\n    return calculateLenseThirringCorrectionAcceleration(\r\n                relativeState.segment( 0, 3 ), relativeState.segment( 3, 3 ), relativeState.segment( 0, 3 ).norm( ),\r\n                calculateRelativisticAccelerationCorrectionsCommonterm(\r\n                    centralBodyGravitationalParameter, relativeState.segment( 0, 3 ).norm( ) ),\r\n                centralBodyAngularMomentum, ppnParameterGamma );\r\n\r\n}\r\n\r\n//! Function to compute the de Sitter term of the relativistic acceleration correction.\r\nEigen::Vector3d calculateDeSitterCorrectionAcceleration(\r\n        const Eigen::Vector3d& orbiterRelativeVelocity,\r\n        const Eigen::Vector3d& orbitedBodyPositionWrtLargerBody,\r\n        const Eigen::Vector3d& orbitedBodyVelocityWrtLargerBody,\r\n        const double commonCorrectionTermOfLargerBody,\r\n        const double ppnParameterGamma )\r\n{\r\n    return - commonCorrectionTermOfLargerBody * ( 1.0 + 2.0 * ppnParameterGamma ) *\r\n            ( orbitedBodyVelocityWrtLargerBody.cross( orbitedBodyPositionWrtLargerBody ) ).cross( orbiterRelativeVelocity );\r\n}\r\n\r\n//! Function to compute the de Sitter term of the relativistic acceleration correction.\r\nEigen::Vector3d calculateDeSitterCorrectionAcceleration(\r\n        const double largerBodyGravitationalParameter,\r\n        const Eigen::Vector6d& orbiterRelativeState,\r\n        const Eigen::Vector6d&orbitedBodyStateWrtLargerBody,\r\n        const double ppnParameterGamma )\r\n{\r\n    return calculateDeSitterCorrectionAcceleration(\r\n                orbiterRelativeState.segment( 3, 3 ),\r\n                orbitedBodyStateWrtLargerBody.segment( 0, 3 ),\r\n                orbitedBodyStateWrtLargerBody.segment( 3, 3 ),\r\n                calculateRelativisticAccelerationCorrectionsCommonterm(\r\n                    largerBodyGravitationalParameter,\r\n                    orbitedBodyStateWrtLargerBody.segment( 0, 3 ).norm( ) ),\r\n                ppnParameterGamma );\r\n}\r\n\r\n}\r\n\r\n}\r\n", "meta": {"hexsha": "43578eaae64b6084f8ef63bc43419038f0a1c022", "size": 6037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Relativity/relativisticAccelerationCorrection.cpp", "max_stars_repo_name": "ViktorJordanov/tudat", "max_stars_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Relativity/relativisticAccelerationCorrection.cpp", "max_issues_repo_name": "ViktorJordanov/tudat", "max_issues_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Relativity/relativisticAccelerationCorrection.cpp", "max_forks_repo_name": "ViktorJordanov/tudat", "max_forks_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.0839694656, "max_line_length": 125, "alphanum_fraction": 0.7059797913, "num_tokens": 1288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.627078723653957}}
{"text": "// The MIT License (MIT)\n//\n// Copyright (c) 2014 Julian Gehring\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <boost/math/distributions/hypergeometric.hpp>\n#include <algorithm>\n\ndouble fisher_test(int a, int b, int c, int d) {\n  unsigned N = a + b + c + d;\n  unsigned r = a + c;\n  unsigned n = c + d;\n  unsigned max_for_k = std::min(r, n);\n  unsigned min_for_k = (unsigned)std::max(0, int(r + n - N));\n  boost::math::hypergeometric_distribution<> hgd(r, n, N);\n  double cutoff = pdf(hgd, c);\n  double tmp_p = 0.0;\n  for(int k = min_for_k;k < max_for_k + 1;k++) {\n    double p = pdf(hgd, k);\n    if(p <= cutoff) tmp_p += p;\n  }\n  return tmp_p;\n}\n", "meta": {"hexsha": "f176c08e64bf3598d2cd4a6bc0ddf5aa7e55855f", "size": 1685, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fisher_test.cpp", "max_stars_repo_name": "SimonLarsen/convaq", "max_stars_repo_head_hexsha": "285d472327696c1404fd9a0772229dc674408f3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-03T00:41:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-18T15:18:35.000Z", "max_issues_repo_path": "src/fisher_test.cpp", "max_issues_repo_name": "SimonLarsen/convaq", "max_issues_repo_head_hexsha": "285d472327696c1404fd9a0772229dc674408f3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-12T21:08:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T21:08:59.000Z", "max_forks_repo_path": "src/fisher_test.cpp", "max_forks_repo_name": "SimonLarsen/convaq", "max_forks_repo_head_hexsha": "285d472327696c1404fd9a0772229dc674408f3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-16T05:55:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-16T05:55:06.000Z", "avg_line_length": 41.0975609756, "max_line_length": 81, "alphanum_fraction": 0.7145400593, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6270698179992517}}
{"text": "/**\n * @file stableevaluationatapoint_main.cc\n * @brief NPDE homework StableEvaluationAtAPoint\n * @author Am\u00e9lie Loher, Erick Schulz & Philippe Peter\n * @date 29.11.2021\n * @copyright Developed at SAM, ETH Zurich\n */\n\n#include <lf/assemble/assemble.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <utility>\n\n#include \"stableevaluationatapoint.h\"\n\nint main(int /*argc*/, const char ** /*argv*/) {\n  // exact solution\n  auto uExact = [](Eigen::Vector2d x) -> double {\n    Eigen::Vector2d one(1.0, 0.0);\n    return std::log((x + one).norm());\n  };\n  // Fixed evaluation point\n  Eigen::Vector2d x(0.3, 0.4);\n  std::cout << \"Exact evaluation at (0.3,0.4) : \" << uExact(x) << std::endl;\n\n  // Number of meshes used in the error analysis:\n  int N_meshes = 6;\n\n  // Error analysis vectors:\n  Eigen::VectorXd mesh_sizes(N_meshes);\n  mesh_sizes.setZero();\n  Eigen::VectorXd dofs(N_meshes);\n  dofs.setZero();\n\n  // Error vector used for the error analysis in exercise b)\n  Eigen::VectorXd errors_potential(N_meshes);\n  errors_potential.setZero();\n\n  // Error vectors used for the error analysis in exercise h\n  Eigen::VectorXd errors_direct(N_meshes);\n  errors_direct.setZero();\n  Eigen::VectorXd errors_stable(N_meshes);\n  errors_stable.setZero();\n\n  // iterate over meshes:\n  for (int k = 0; k < N_meshes; k++) {\n    // read mesh::\n    std::string idx = std::to_string(k + 1);\n    auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n    lf::io::GmshReader reader(std::move(mesh_factory), CURRENT_SOURCE_DIR\n                                                           \"/../meshes/square\" +\n                                                           idx + \".msh\");\n    auto mesh_p = reader.mesh();\n\n    // Initialize fe-space and dofh\n    auto fe_space =\n        std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n    const lf::assemble::DofHandler &dofh = fe_space->LocGlobMap();\n    dofs(k) = dofh.NumDofs();\n\n    // Printing mesh statistics\n    mesh_sizes(k) = StableEvaluationAtAPoint::MeshSize(mesh_p);\n    std::cout << \"square\" + idx + \".msh: \"\n              << \"N_dofs = \" << dofs(k) << \", h=\" << mesh_sizes(k) << std::endl;\n\n    // Error anlysis part b) (Potentials)\n    errors_potential(k) = StableEvaluationAtAPoint::PointEval(mesh_p);\n\n    // error analysis part g/h: Compare direct vs stable point evaluation:\n    auto [direct_eval, stable_eval] =\n        StableEvaluationAtAPoint::ComparePointEval(fe_space, uExact, x);\n    errors_direct(k) = std::abs(uExact(x) - direct_eval);\n    errors_stable(k) = std::abs(uExact(x) - stable_eval);\n  }\n\n  // Compute rates of convergence:\n  Eigen::VectorXd rates_potential(N_meshes - 1);\n  Eigen::VectorXd rates_direct(N_meshes - 1);\n  Eigen::VectorXd rates_stable(N_meshes - 1);\n\n#if SOLUTION\n  for (int k = 0; k < N_meshes - 1; ++k) {\n    double log_denum = std::log(mesh_sizes(k) / mesh_sizes(k + 1));\n    rates_potential(k) =\n        std::log(errors_potential(k) / errors_potential(k + 1)) / log_denum;\n    rates_direct(k) =\n        std::log(errors_direct(k) / errors_direct(k + 1)) / log_denum;\n    rates_stable(k) =\n        std::log(errors_stable(k) / errors_stable(k + 1)) / log_denum;\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n\n  // Report computed errors and rates:\n  std::cout << \"Subtask b) Evaluation based on Potentials \\n\";\n  std::cout << \"Errors: \\n\" << errors_potential << \"\\n\";\n  std::cout << \"Rates: \\n\" << rates_potential << \"\\n\";\n  std::cout << \"Subtask h) Comparison of direct and stable evaluation: \\n\";\n  std::cout << \"Errors direct: \\n\" << errors_direct << \"\\n\";\n  std::cout << \"Rates direct: \\n\" << rates_direct << \"\\n\";\n  std::cout << \"Errors stable: \\n\" << errors_stable << \"\\n\";\n  std::cout << \"Rates stable: \\n\" << rates_stable << \"\\n\";\n\n  // Output\n  const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision,\n                                         Eigen::DontAlignCols, \", \", \"\\n\");\n\n  Eigen::MatrixXd convergence_potential(N_meshes, 2);\n  convergence_potential << mesh_sizes, errors_potential;\n\n  Eigen::MatrixXd convergence_stable(N_meshes, 3);\n  convergence_stable << mesh_sizes, errors_direct, errors_stable;\n\n  std::ofstream file;\n  file.open(\"convergence_potential.csv\");\n  file << \"h, Error u(x) (Potential) \\n\";\n  file << convergence_potential.format(CSVFormat);\n  file.close();\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/convergence_potential.csv\"\n            << std::endl;\n\n  file.open(\"convergence_stable.csv\");\n  file << \"h, Error u(x) (Direct), Error u(x) (Stable) \\n\";\n  file << convergence_stable.format(CSVFormat);\n  file.close();\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/convergence_stable.csv\"\n            << std::endl;\n\n  // Plot\n  std::system(\"python3 \" CURRENT_SOURCE_DIR\n              \"/plot_convergence_potential.py \" CURRENT_BINARY_DIR);\n  std::system(\"python3 \" CURRENT_SOURCE_DIR\n              \"/plot_convergence_stable.py \" CURRENT_BINARY_DIR);\n\n  return 0;\n}\n", "meta": {"hexsha": "a0d47ccf648861898252462f759d26609d78f111", "size": 5180, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/StableEvaluationAtAPoint/mastersolution/stableevaluationatapoint_main.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T10:59:19.000Z", "max_issues_repo_path": "developers/StableEvaluationAtAPoint/mastersolution/stableevaluationatapoint_main.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "developers/StableEvaluationAtAPoint/mastersolution/stableevaluationatapoint_main.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5333333333, "max_line_length": 80, "alphanum_fraction": 0.6388030888, "num_tokens": 1425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7905303285397349, "lm_q1q2_score": 0.626974308156395}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <numeric>\n#include <vector>\n#include <memory>\n#include <map>\n#include <tuple>\n#include <exception>\n#include <iostream>\n#include <functional>\n#include <mutex>          // std::mutex\n#include \"ThreadPool.h\"\n#include \"cubature.h\"\n#if !defined(NO_CUBA)\n#include \"cuba.h\"\n#endif\n#include \"MultiComplex/MultiComplex.hpp\"\n\n#include \"nlohmann/json.hpp\"\n\ndouble factorial(double n) {\n    return std::tgamma(n + 1);\n}\n\nstd::mutex mtx;  // mutex for cout\n\n#if !defined(M_PI)\nconstexpr auto M_PI = 3.14159265358979323846;\n#endif\n\nauto geomspace(double xmin, double xmax, int N) {\n    std::vector<double> vec;\n    double dT = (log(xmax) - log(xmin)) / (N - 1);\n    for (auto i = 0; i < N; ++i) {\n        vec.push_back(exp(log(xmin) + dT * i));\n    }\n    return vec;\n}\n\ndouble gr = (sqrt(5) + 1) / 2;\n\nauto gss(std::function<double(double)> f, double a, double b, const double tol = 1e-5) {\n    /*\n    Golden section search\n    C++ translation of https://en.wikipedia.org/wiki/Golden-section_search#Algorithm\n    Text is available under the Creative Commons Attribution-ShareAlike License\n    */\n    auto c = b - (b - a) / gr;\n    auto d = a + (b - a) / gr;\n    while (abs(c - d) > tol) {\n        if (f(c) < f(d)) {\n            b = d;\n        }\n        else {\n            a = c;\n        }\n        // We recompute both c and d here to avoid loss of precision which may lead to incorrect results or infinite loop\n        c = b - (b - a) / gr;\n        d = a + (b - a) / gr;\n    }\n    return std::make_tuple((b + a) / 2, f((b + a) / 2));\n}\n\n/* \nTrapezoidal integration -- the workhorse numerical integration routine\n*/\ntemplate<typename TYPEX, typename TYPEY>\nTYPEY trapz(const Eigen::Array<TYPEX, Eigen::Dynamic, 1>& x, \n           const Eigen::Array<TYPEY, Eigen::Dynamic, 1>& y) {\n    TYPEY out = 0;\n    for (auto i = 0; i < x.size()-1; ++i) {\n        auto ymean = (y[i+1]+y[i])/2.0;\n        out = out + ymean*(x[i+1] - x[i]);\n    }\n    return out;\n}\n/*\nSimpson's integration rule\n*/\ntemplate<typename TYPEX, typename TYPEY>\nTYPEY simps(const Eigen::Array<TYPEX, Eigen::Dynamic, 1>& x, \n           const Eigen::Array<TYPEY, Eigen::Dynamic, 1>& f) {\n    // C++ translation of https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule_for_irregularly_spaced_data\n    auto N = x.size() - 1;\n    auto h = x.tail(N) - x.head(N);\n    auto cube = [](TYPEX x) { return x * x * x; };\n    auto sq = [](TYPEX x) { return x * x; };\n    TYPEY result = 0.0;\n    for (auto i = 1; i < N; i += 2) {\n        auto hph = h[i] + h[i - 1];\n        result += f[i] * (cube(h[i]) + cube(h[i - 1]) + 3.0 * h[i] * h[i - 1] * hph) / (6 * h[i] * h[i - 1]);\n        result += f[i - 1] * (2.0 * cube(h[i - 1.0]) - cube(h[i]) + 3.0 * h[i] * sq(h[i - 1])) / (6 * h[i - 1] * hph);\n        result += f[i + 1] * (2.0 * cube(h[i]) - cube(h[i - 1]) + 3.0 * h[i - 1] * sq(h[i])) / (6 * h[i] * hph);\n    }\n    if ((N + 1) % 2 == 0) {\n        result += f[N] * (2 * sq(h[N - 1]) + 3.0 * h[N - 2] * h[N - 1]) / (6 * (h[N - 2] + h[N - 1]));\n        result += f[N - 1] * (sq(h[N - 1]) + 3.0 * h[N - 1] * h[N - 2]) / (6 * h[N - 2]);\n        result -= f[N - 2] * cube(h[N - 1]) / (6 * h[N - 2] * (h[N - 2] + h[N - 1]));\n    }\n    return result;\n}\n\ntemplate <typename TYPE>\nclass Molecule {\n\npublic:\n    using EColArray = Eigen::Array<TYPE, Eigen::Dynamic, 1>;\n    using CoordMatrix = Eigen::Array<TYPE, 3, Eigen::Dynamic>;\n    CoordMatrix coords, coords_initial;\n\n    Molecule(const std::vector<std::vector<TYPE>>& pts) {\n        coords.resize(3, pts.size());\n        for (auto i = 0; i < pts.size(); ++i) {\n            auto &pt = pts[i];\n            for (auto j = 0; j < pt.size(); ++j) {\n                coords(j, i) = pt[j];\n            }\n        }\n        coords_initial = coords;\n    };\n    void reset() {\n        coords = coords_initial;\n    };\n    CoordMatrix rotZ3(TYPE theta) const {\n        // Rotation matrix for rotation around the z axis in 3D\n        // See https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations\n        return (Eigen::ArrayXXd(3,3) <<\n            cos(theta), -sin(theta), 0,\n            sin(theta), cos(theta),  0,\n                0,           0,      1 ).finished();\n    };\n    CoordMatrix rotY3(const TYPE theta) const {\n        // Rotation matrix for rotation around the y axis in 3D\n        // See https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations\n        const TYPE c = cos(theta), s = sin(theta);\n        return (Eigen::ArrayXXd(3,3) <<\n            c,  0, s,\n            0,  1, 0,\n            -s, 0, c).finished();\n    }\n    CoordMatrix rotX3(TYPE theta) const {\n        // Rotation matrix for rotation around the x axis in 3D\n        // See https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations\n        return (Eigen::ArrayXXd(3,3) <<\n            1,      0,          0,\n            0, cos(theta), -sin(theta),\n            0, sin(theta), cos(theta)).finished();\n    }\n    void rotate_plusx(TYPE angle) {\n        Eigen::Transform<double, 3, Eigen::Affine> rot(Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitX()));\n        coords = rot.linear() * coords.matrix();\n        //coords = rotX3(angle).matrix() * coords.matrix(); // Old method\n    }\n    void rotate_negativex(TYPE angle) {\n        rotate_plusx(-angle);\n    }\n    void rotate_plusy(TYPE angle) {\n        Eigen::Transform<double, 3, Eigen::Affine> rot(Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitY()));\n        coords = rot.linear() * coords.matrix();\n        //coords = rotY3(angle).matrix() * coords.matrix(); // Old method\n    }\n    void rotate_negativey(TYPE angle) {\n        rotate_plusy(-angle);\n    }\n    void rotate_plusz(TYPE angle) {\n        Eigen::Transform<double, 3, Eigen::Affine> rot(Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ()));\n        coords = rot.linear()*coords.matrix();\n    }\n    void rotate_negativez(TYPE angle) {\n        rotate_plusz(-angle);\n    }\n    void translatex(TYPE dx) {\n        coords.row(0) += dx;\n    }\n    void translatey(TYPE dy) {\n        coords.row(1) += dy;\n    }\n    template<typename ArrayType>\n    TYPE get_dist(const ArrayType&rA, const ArrayType&rB) const{\n        return sqrt((rA - rB).square().sum());\n    }\n    Eigen::Index get_Natoms() const {\n        return coords.cols();\n    }\n    auto get_xyz_atom(const Eigen::Index i) const {\n        if (i > coords.cols()) {\n            throw std::invalid_argument(\"Bad atom index\");\n        }\n        return coords.col(i);\n    }\n};\n\ntemplate<typename TYPE>\nclass PotentialEvaluator {\npublic:\n    std::map<std::tuple<std::size_t, std::size_t>, std::function<double(double)> > potential_map;\n\n    ///< Additional contributions, handled in a very generic way via a callback\n    std::vector<std::function<double(const Molecule<TYPE> &, const Molecule<TYPE>&)>> generic_contributions;\n\n    TYPE eval_pot(const Molecule<TYPE>& molA, const Molecule<TYPE>& molB) const {\n        TYPE u = 0.0;\n        // Sum up site-site contributions to total potential energy\n        for (auto iatom = 0; iatom < molA.get_Natoms(); ++iatom) {\n            auto xyzA = molA.get_xyz_atom(iatom);\n            for (auto jatom = 0; jatom < molB.get_Natoms(); ++jatom) {\n                auto xyzB = molB.get_xyz_atom(jatom);\n                TYPE distij = molA.get_dist(xyzA, xyzB);\n                auto f_potential = get_potential(iatom, jatom);\n                u += f_potential(distij);\n            }\n        }\n        // Add also contributions for other kinds of interactions (e.g., dipole, quadrupole, etc.)\n        for (auto contrib : generic_contributions) {\n            u += contrib(molA, molB);\n        }\n        return u;\n    }\n    /*\n    Connect up all the site-site potentials, all molecules have the same number of sites\n    */\n    void connect_potentials(std::function<double(double)>& f,std::size_t Natoms) {\n        for (auto iatom = 0; iatom < Natoms; ++iatom) {\n            for (auto jatom = 0; jatom < Natoms; ++jatom) {\n                potential_map[std::make_tuple(iatom, jatom)] = f;\n            }\n        }\n    }\n    /*\n    Add a potential for a particular site-site interaction\n\n    @param iatom The index of site on molecule A\n    @param jatom The index of site on molecule B\n    */\n    void add_potential(std::size_t iatom, std::size_t jatom, std::function<double(double)>& f) {\n        potential_map[std::make_tuple(iatom, jatom)] = f;\n    }\n    /*\n    Add a generalized contribution to the overall potential energy.  Callback function takes two molecules\n    */\n    void add_generic_contribution(const std::function<double(const Molecule<TYPE>&, const Molecule<TYPE>&)>& f) {\n        generic_contributions.push_back(f);\n    }\n    /*\n    Get a reference to the potential function for a particular site-site interaction\n    \n    @param i The index of site on molecule A\n    @param j The index of site on molecule B\n\n    */\n    auto& get_potential(std::size_t i, std::size_t j) const {\n        auto itf = potential_map.find(std::make_tuple(i, j));\n        if (itf != potential_map.end()) {\n            return itf->second;\n        }\n        else {\n            throw std::invalid_argument(\"Bad potential\");\n        }\n    }\n};\n/// A helper class\ntemplate<typename TYPE, typename TEMPTYPE>\nclass SharedDataBase {\npublic:\n    TEMPTYPE Tstar;\n    TYPE rstar;\n    Molecule<TYPE> molA, molB;\n    std::valarray<TYPE> xmin, xmax;\n    const PotentialEvaluator<TYPE>& evaltr;\n    SharedDataBase(TEMPTYPE Tstar, TYPE rstar,\n        Molecule<TYPE> molA, Molecule<TYPE> molB, \n        const PotentialEvaluator<TYPE>& evaltr, \n        const std::valarray<TYPE>& xmin = {},\n        const std::valarray<TYPE>& xmax = {}\n    )\n        : Tstar(Tstar), rstar(rstar), molA(molA), molB(molB), evaltr(evaltr), xmin(xmin), xmax(xmax) {};\n\n    TYPE eval_pot(const Molecule<TYPE>& molA, const Molecule<TYPE>& molB) {\n        return evaltr.eval_pot(molA, molB);\n    };\n\n    /* \n    Given the orientational angles, calculate the integrand\n    */\n    void orient_integrand(double theta1, double theta2, double phi, double *fval)\n    {\n        // Rotate molecule #1\n        molA.reset(); // Back to COM at origin\n        molA.rotate_negativey(theta1); // First rotate around -y axis\n\n        // Rotate and move molecule #2\n        molB.reset(); // Back to COM at origin\n        molB.rotate_negativey(theta2); // First rotate around -y axis\n        molB.rotate_negativex(phi); // Then rotate around +x\n        molB.translatex(rstar); // Then translate\n\n        auto V = eval_pot(molA, molB); // And finally evaluate the potential\n        auto a = (exp(-V/Tstar)-1.0)*sin(theta1)*sin(theta2)*pow(rstar, 2);\n        \n        if constexpr (std::is_same<decltype(Tstar), double>::value) {\n            // If T is double (real)\n            fval[0] = a;\n        }\n        else if constexpr (std::is_same<decltype(Tstar), std::complex<double>>::value) {\n            // If T is a complex number (perhaps for complex step derivatives)\n            fval[0] = a.real();\n            fval[1] = a.imag();\n        }\n        else if constexpr (std::is_same<decltype(Tstar), MultiComplex<double>>::value) {\n            // If T is a multicomplex number\n            auto &c = a.get_coef();\n            for (auto i = 0; i < c.size(); ++i) {\n                fval[i] = c[i];\n            }\n        }\n    }\n    /*\n    Given the separations and angle, calculate the integrand for B_3 for a spherically-symmetric potential\n    for an atomic fluid\n    */\n    void atomic_B3_integrand(const double r12, const double r13, const double eta_angle, double* fval)\n    {\n        // Get the potential function V(r) that we should use\n        auto &pot = this->evaltr.get_potential(0, 0);\n        TEMPTYPE Tstar = this->Tstar; // Local reference just for sharing with the lambda function f\n        auto f = [pot, Tstar](double r) -> TEMPTYPE { return 1.0 - exp(-pot(r)/Tstar); };\n        auto SQUARE = [](double x) { return x*x; };\n        auto rangle = sqrt(SQUARE(r12) + SQUARE(r13) - 2*r12*r13*eta_angle);\n        auto a = SQUARE(r12)*f(r12)*SQUARE(r13)*f(r13)*f(rangle);\n\n        if constexpr (std::is_same<decltype(Tstar), double>::value) {\n            // If T is double (real)\n            fval[0] = a;\n        }\n        else if constexpr (std::is_same<decltype(Tstar), std::complex<double>>::value) {\n            // If T is a complex number (perhaps for complex step derivatives)\n            fval[0] = a.real();\n            fval[1] = a.imag();\n        }\n        else if constexpr (std::is_same<decltype(Tstar), MultiComplex<double>>::value) {\n            // If T is a multicomplex number\n            auto& c = a.get_coef();\n            for (auto i = 0; i < c.size(); ++i) {\n                fval[i] = c[i];\n            }\n        }\n    }\n\n\n\t/*\n\tGiven the separations and angles, calculate the integrand for B4_1 for a spherically-symmetric potential\n\tfor an atomic fluid\n\t*/\n\tvoid atomic_B4_1_integrand(const double r14, const double r13, const double gamma_angle, const double r12, const double eta_angle, double* fval)\n\t{\n\t\t// Get the potential function V(r) that we should use\n\t\tauto &pot = this->evaltr.get_potential(0, 0);\n\t\tTEMPTYPE Tstar = this->Tstar; // Local reference just for sharing with the lambda function f\n\t\tauto f = [pot, Tstar](double r) -> TEMPTYPE { return 1.0 - exp(-pot(r) / Tstar); };\n\t\tauto SQUARE = [](double x) { return x * x; };\n\t\tauto sq_r12 = SQUARE(r12);\n\t\tauto sq_r13 = SQUARE(r13);\n\t\tauto sq_r14 = SQUARE(r14);\n\t\tauto rangle_12_13 = sqrt(sq_r12 + sq_r13 - 2 * r12*r13*eta_angle);\n\t\tauto rangle_13_14 = sqrt(sq_r14 + sq_r13 - 2 * r14*r13*gamma_angle);\n\n\t\tauto a = sq_r12 * f(r12)*sq_r13*sq_r14*f(r14)*f(rangle_12_13)*f(rangle_13_14);\n\n\t\tif constexpr (std::is_same<decltype(Tstar), double>::value) {\n\t\t\t// If T is double (real)\n\t\t\tfval[0] = a;\n\t\t}\n\t\telse if constexpr (std::is_same<decltype(Tstar), std::complex<double>>::value) {\n\t\t\t// If T is a complex number (perhaps for complex step derivatives)\n\t\t\tfval[0] = a.real();\n\t\t\tfval[1] = a.imag();\n\t\t}\n\t\telse if constexpr (std::is_same<decltype(Tstar), MultiComplex<double>>::value) {\n\t\t\t// If T is a multicomplex number\n\t\t\tauto& c = a.get_coef();\n\t\t\tfor (auto i = 0; i < c.size(); ++i) {\n\t\t\t\tfval[i] = c[i];\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\nGiven the separations and angles, calculate the integrand for B4_2 for a spherically-symmetric potential\nfor an atomic fluid\n*/\n\tvoid atomic_B4_2_integrand(const double eta_angle, const double r12, const double r13, const double gamma_angle, const double r14, double* fval)\n\t{\n\t\t// Get the potential function V(r) that we should use\n\t\tauto &pot = this->evaltr.get_potential(0, 0);\n\t\tTEMPTYPE Tstar = this->Tstar; // Local reference just for sharing with the lambda function f\n\t\tauto f = [pot, Tstar](double r) -> TEMPTYPE { return 1.0 - exp(-pot(r) / Tstar); };\n\t\tauto SQUARE = [](double x) { return x * x; };\n\t\tauto sq_r12 = SQUARE(r12);\n\t\tauto sq_r13 = SQUARE(r13);\n\t\tauto sq_r14 = SQUARE(r14);\n\t\tauto rangle_12_13 = sqrt(sq_r12 + sq_r13 - 2 * r12*r13*eta_angle);\n\t\tauto rangle_13_14 = sqrt(sq_r14 + sq_r13 - 2 * r14*r13*gamma_angle);\n\n\t\tauto a = sq_r12 * f(r12)*sq_r13*f(r13)*sq_r14*f(r14)*f(rangle_12_13)*f(rangle_13_14);\n\n\t\tif constexpr (std::is_same<decltype(Tstar), double>::value) {\n\t\t\t// If T is double (real)\n\t\t\tfval[0] = a;\n\t\t}\n\t\telse if constexpr (std::is_same<decltype(Tstar), std::complex<double>>::value) {\n\t\t\t// If T is a complex number (perhaps for complex step derivatives)\n\t\t\tfval[0] = a.real();\n\t\t\tfval[1] = a.imag();\n\t\t}\n\t\telse if constexpr (std::is_same<decltype(Tstar), MultiComplex<double>>::value) {\n\t\t\t// If T is a multicomplex number\n\t\t\tauto& c = a.get_coef();\n\t\t\tfor (auto i = 0; i < c.size(); ++i) {\n\t\t\t\tfval[i] = c[i];\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\nGiven the separations and angles, calculate the integrand for B4_3 for a spherically-symmetric potential\nfor an atomic fluid\n*/\n\tvoid atomic_B4_3_integrand(const double eta_angle, const double zeta_angle, const double gamma_angle, const double r12, const double r13, const double r14, double* fval)\n\t{\n\t\t// Get the potential function V(r) that we should use\n\t\tauto &pot = this->evaltr.get_potential(0, 0);\n\t\tTEMPTYPE Tstar = this->Tstar; // Local reference just for sharing with the lambda function f\n\t\tauto f = [pot, Tstar](double r) -> TEMPTYPE { return 1.0 - exp(-pot(r) / Tstar); };\n\t\tauto SQUARE = [](double x) { return x * x; };\n\t\tauto sq_r12 = SQUARE(r12);\n\t\tauto sq_r13 = SQUARE(r13);\n\t\tauto sq_r14 = SQUARE(r14);\n\t\tauto rangle_12_13 = sqrt(sq_r12 + sq_r14 - 2 * r12*r14*eta_angle);\n\t\tauto rangle_13_14 = sqrt(sq_r13 + sq_r14 - 2 * r13*r14*gamma_angle);\n\t\tauto rangle_12_14 = sqrt(sq_r12 + sq_r13 - 2 * r12*r13*(eta_angle * gamma_angle + sqrt(1.0 - SQUARE(eta_angle))*sqrt(1.0 - SQUARE(gamma_angle))*cos(zeta_angle)));\n\t\tauto a = sq_r12 * f(r12)*sq_r13*f(r13)*sq_r14*f(r14)*f(rangle_12_13)*f(rangle_13_14)*f(rangle_12_14);\n\n\t\tif constexpr (std::is_same<decltype(Tstar), double>::value) {\n\t\t\t// If T is double (real)\n\t\t\tfval[0] = a;\n\t\t}\n\t\telse if constexpr (std::is_same<decltype(Tstar), std::complex<double>>::value) {\n\t\t\t// If T is a complex number (perhaps for complex step derivatives)\n\t\t\tfval[0] = a.real();\n\t\t\tfval[1] = a.imag();\n\t\t}\n\t\telse if constexpr (std::is_same<decltype(Tstar), MultiComplex<double>>::value) {\n\t\t\t// If T is a multicomplex number\n\t\t\tauto& c = a.get_coef();\n\t\t\tfor (auto i = 0; i < c.size(); ++i) {\n\t\t\t\tfval[i] = c[i];\n\t\t\t}\n\t\t}\n\t}\n};\n\ntemplate<typename TYPE>\nclass Integrator {\nprivate:\n    std::unique_ptr<ThreadPool> m_pool;\n    nlohmann::json m_conf;\n\npublic:\n    using EColArray = Eigen::Array<TYPE, Eigen::Dynamic, 1>;\n    const Molecule<TYPE> mol1, mol2;\n    PotentialEvaluator<TYPE> potcls;\n\n    Integrator(const Molecule<TYPE>& mol1, const Molecule<TYPE>& mol2) : mol1(mol1), mol2(mol2) {};\n\n    auto& get_conf_view() {\n        return m_conf;\n    }\n\n    /* For a one-dimensional integration for B_2, use trapezoidal integration to calculate B_2 */\n    template <typename TEMPTYPE>\n    TEMPTYPE radial_integrate_B2(TEMPTYPE Tstar, TYPE rstart, TYPE rend, int N) {\n        using arr = Eigen::Array<TYPE, Eigen::Dynamic, 1>;\n        using arrT = Eigen::Array<TEMPTYPE, Eigen::Dynamic, 1>;\n        arr rv = exp(arr::LinSpaced(N, log(rstart), log(rend)));\n        arrT integrand;\n        integrand.resize(rv.size());\n        Molecule<TYPE> mol1 = this->mol1, mol2 = this->mol2;\n        for (auto ir = 0; ir < rv.size(); ++ir) {\n            auto r = rv[ir];\n            mol2.reset();\n            mol2.translatex(r);\n            auto V = potcls.eval_pot(mol1, mol2);\n            integrand[ir] = (exp(-V/Tstar)-1.0)*r*r;\n        }\n        return -2*M_PI*trapz(rv, integrand);\n    };\n    /* \n    Get a reference to the evaluator class, giving access to matrix of site-site potential functions, for instance\n    */\n    auto &get_evaluator() {\n        return potcls;\n    }\n\n    void init_thread_pool(short Nthreads) {\n        if (!m_pool || m_pool->GetThreads().size() != Nthreads) {\n            // Make a thread pool for the workers\n            m_pool = std::unique_ptr<ThreadPool>(new ThreadPool(Nthreads));\n        }\n    }\n    /* \n    A helper function to evaluate the potential given COM separation r and the orientation angles\n    */\n    double potential(double r, double theta1, double theta2, double phi){\n        Molecule<TYPE> molA = mol1, molB = mol2;\n        // Rotate molecule #1\n        molA.reset(); // Back to COM at origin\n        molA.rotate_negativey(theta1); // First rotate around -y axis\n\n        // Rotate and move molecule #2\n        molB.reset(); // Back to COM at origin\n        molB.rotate_negativey(theta2); // First rotate around -y axis\n        molB.rotate_negativex(phi); // Then rotate around +x\n        molB.translatex(r); // Then translate\n\n        auto V = potcls.eval_pot(molA, molB); // And finally evaluate the potential in the form V/epsilon\n        return V;\n    }\n    /*\n    Calculate the orientationally-averaged potential\n    */\n    TYPE orient_averaged_potential(TYPE rstar, Molecule<TYPE> mol1, Molecule<TYPE> mol2) const {\n        using SharedData = SharedDataBase<TYPE, double>;\n        SharedData shared(0.0, 0.0, mol1, mol2, potcls, {0,0,0}, { M_PI, M_PI, 2 * M_PI });\n        //typedef int (*integrand) (unsigned ndim, const double *x, void *, unsigned fdim, double* fval);\n        auto f_integrand = [](unsigned ndim, const double* x, void* p_shared_data, unsigned fdim, double* fval) {\n            auto& shared = *((class SharedDataBase<double, double>*)(p_shared_data));\n            auto& molA = shared.molA;\n            auto& molB = shared.molB;\n            double theta1 = x[0], theta2 = x[1], phi = x[2];\n            shared.orient_integrand(theta1, theta2, phi, fval);\n            return 0; // success\n        };\n        shared.rstar = rstar;\n        int ndim = 1;\n        std::valarray<double> val(0.0, 4), err(0.0, 4);\n        hcubature(ndim, f_integrand, &shared, 3, &(shared.xmin[0]), &(shared.xmax[0]), 100000, 0, 1e-13, ERROR_INDIVIDUAL, &(val[0]), &(err[0]));\n        return val[0]/(8*M_PI);\n    }\n\n    /**\n    Do the calculations for one temperature\n\n    @param order The order of the virial coefficient (2=B_2, 3=B_3, etc.)\n    @param Tstar The temperature\n    @param rstart The initial value of r to be considered in integration\n    @param rend The final value of r to be considered in integration\n    @param mol1 The first molecule\n    @param mol2 The second molecule\n    @returns Tuple of (value, estimated error in value)\n    @note The return numerical type maybe be one of double, std::complex<double> or MultiComplex<double>\n    */\n    template <typename TEMPTYPE>\n    std::tuple<TEMPTYPE,TEMPTYPE> one_temperature(int order, TEMPTYPE Tstar, TYPE rstart, TYPE rend, Molecule<TYPE> mol1, Molecule<TYPE> mol2) const \n    {\n        \n        // Some local typedefs to avoid typing\n        using SharedData = SharedDataBase<TYPE, TEMPTYPE>;\n\n        std::vector<std::valarray<double>> xmins, xmaxs;\n        switch (order)\n        {\n        case 2:\n            xmins = {{ 0, 0, 0, rstart }}, xmaxs = {{ M_PI, M_PI, 2 * M_PI, rend }}; // Limits on theta1, theta2, phi, r\n            break;\n        case 3:{\n            double rbreak = 1.3;\n            xmins = {{ rstart, rstart, -1 },{ rbreak, rstart, -1 } }, xmaxs = {{ rbreak, rend, 1 },{ rend, rend, 1 } }; // Limits on r12, r13, eta\n            break;\n            }\n        case 4: {\n            // Limits on r14, r13, gamma, r12, eta\n            // Limits on eta, r12, r13, eta, r14\n            // Limits on eta,zeta,gamma, r12, r13, r14\t\n            xmins = { {rstart, rstart, -1 , rstart, -1 }, { -1, rstart, rstart, -1 , rstart }, { -1,  rstart, -1 , rstart, rstart , rstart } };\n            xmaxs = { { rend, rend, 1 , rend, 1 }, { 1, rend, rend, 1 , rend }, { 1, 2 * M_PI, 1, rend, rend , rend } };\n            break; \n        }\n        default:\n            break;\n        }\n        SharedData shared(Tstar, 0.0, mol1, mol2, potcls);\n        \n        int ndim = 1; // If T is a floating point number (default)\n        std::valarray<double> outval, outerr;\n        std::vector<std::valarray<double >> vals(10), errs(10);\n        if constexpr (std::is_same<decltype(shared.Tstar), std::complex<double>>::value) {\n            ndim = 2;\n        }\n        else if constexpr (std::is_same<decltype(shared.Tstar), MultiComplex<double>>::value) {\n            ndim = static_cast<int>(shared.Tstar.get_coef().size());\n        }\n        // Fill with zero\n        for (auto& val : vals) {\n            val = std::valarray<double>(0.0, ndim);\n        }\n        for (auto& err : errs) {\n            err = std::valarray<double>(0.0, ndim);\n        }\n        outval = std::valarray<double>(0.0, ndim);\n        outerr = std::valarray<double>(0.0, ndim);\n\n        int feval_max = 0;\n        if (m_conf.contains(\"feval_max\")) {\n            feval_max = static_cast<int>(m_conf[\"feval_max\"]);\n        }\n        else {\n            throw std::invalid_argument(\"Key \\\"feval_max\\\" must be specified in the configuration JSON\");\n        }\n\n#if !defined(NO_CUBA)\n        auto Cuba_integrand = [](const int *pndim, const cubareal x[], const int *pncomp, cubareal fval[], void *p_shared_data) {\n            auto& shared = *((class SharedDataBase<double, TEMPTYPE>*)(p_shared_data));\n            \n            double theta1, theta2, phi, r;\n            double jacobian = 1.0;\n            for (auto i  = 0; i < *pndim; ++i){\n                auto range = shared.xmax[i] - shared.xmin[i];\n                jacobian *= range;\n            }\n            theta1 = shared.xmin[0] + x[0]*(shared.xmax[0]-shared.xmin[0]);\n            theta2 = shared.xmin[1] + x[1]*(shared.xmax[1]-shared.xmin[1]);\n            phi =    shared.xmin[2] + x[2]*(shared.xmax[2]-shared.xmin[2]);\n            r   =    shared.xmin[3] + x[3]*(shared.xmax[3]-shared.xmin[3]);\n            shared.rstar = r;\n            shared.orient_integrand(theta1, theta2, phi, fval);\n            for (auto i = 0; i < *pncomp; ++i){\n                fval[i] *= jacobian;\n            }\n            return 0; // success\n        };\n        \n        int NVEC = 1;\n        int EPSREL = 1e-8;\n        int EPSABS = 1e-12;\n        int VERBOSE = 0;\n        int LAST = 4;\n        int MINEVAL = 0;\n        int MAXEVAL = feval_max;\n        int NSTART = 1000;\n        int NINCREASE = 500;\n        int NBATCH = 1000;\n        int GRIDNO = 0;\n        const char *STATEFILE = nullptr;\n        void *SPIN = nullptr;\n        int neval, fail;\n        cubareal integral[ndim], error[ndim], prob[ndim];\n\n        int nregions;\n        int KEY = 0;\n        auto startTimeC = std::chrono::high_resolution_clock::now();\n        Cuhre(4, ndim, Cuba_integrand, &shared, NVEC,\n        EPSREL, EPSABS, VERBOSE | LAST,\n        MINEVAL, MAXEVAL, KEY,\n        STATEFILE, SPIN,\n        &nregions, &neval, &fail, integral, error, prob);\n        auto endTimeC = std::chrono::high_resolution_clock::now();\n        auto timeC = std::chrono::duration<double>(endTimeC - startTimeC).count(); \n\n        // The quadruple integral needs to be divided by 8*pi, but the leading term in the\n        // expression for B_2 is -2\\pi, so factor becomes -1/4, or -0.25\n        for (auto i = 0; i < outval.size(); ++i) {\n            outval[i] = -0.25 * integral[i];\n            outerr[i] = -0.25 * error[i];\n        }\n#else\n        // Use cubature to do the integration...\n\n        switch (order) {\n        case 2:\n        {\n            // The integrand function\n            //typedef int (*integrand) (unsigned ndim, const double *x, void *, unsigned fdim, double* fval);\n            auto cubature_integrand = [](unsigned ndim, const double* x, void* p_shared_data, unsigned fdim, double* fval) {\n                auto& shared = *((class SharedDataBase<double, TEMPTYPE>*)(p_shared_data));\n                double theta1 = x[0], theta2 = x[1], phi = x[2], r = x[3];\n                shared.rstar = r;\n                shared.orient_integrand(theta1, theta2, phi, fval);\n                return 0; // success\n            };\n\n            int naxes = 4; // How many dimensions the integral is taken over (theta, phi1, phi2, r)\n            hcubature(ndim, cubature_integrand, &shared, naxes, &(xmins[0][0]), &(xmaxs[0][0]), feval_max, 0, 1e-13, ERROR_INDIVIDUAL, &(vals[0][0]), &(errs[0][0]));\n\n            // Copy into output\n            // ....\n            // The quadruple integral needs to be divided by 8*pi, but the leading term in the\n            // expression for B_2 is -2\\pi, so factor becomes -1/4, or -0.25\n            outval = -0.25*vals[0]; outerr = -0.25*errs[0];\n            break;\n        }\n        case 3:\n        {\n            // The integrand function\n            //typedef int (*integrand) (unsigned ndim, const double *x, void *, unsigned fdim, double* fval);\n            auto cubature_integrand = [](unsigned ndim, const double* x, void* p_shared_data, unsigned fdim, double* fval) {\n                auto& shared = *((class SharedDataBase<double, TEMPTYPE>*)(p_shared_data));\n                shared.atomic_B3_integrand(x[0], x[1], x[2], fval);\n                return 0; // success\n            };\n\n            int naxes = 3; // How many dimensions the integral is taken over (r12, r13, eta)\n            for (auto i = 0; i < xmins.size(); ++i){\n                \n                hcubature(ndim, cubature_integrand, &shared, naxes, &(xmins[i][0]), &(xmaxs[i][0]), feval_max, 0, 1e-13, ERROR_INDIVIDUAL, &(vals[i][0]), &(errs[i][0]));\n\n                // Copy into output\n                outval += vals[i]; outerr += std::abs(errs[i]);\n            }\n            // Rescale with the leading factor\n            outval *= 8*M_PI*M_PI/3; outerr *= 8*M_PI*M_PI/3;\n            \n            break;\n        }\n\t\tcase 4:\n\t\t{\n\t\t\t// Fourth virial coefficient: three parts B_4_1,B_4_2,B_4_3\n\t\t\t// The integrand functions\n\t\t\t//typedef int (*integrand) (unsigned ndim, const double *x, void *, unsigned fdim, double* fval);\n\t\t\tauto cubature_integrand_1 = [](unsigned ndim, const double* x, void* p_shared_data, unsigned fdim, double* fval) {\n\t\t\t\tauto& shared = *((class SharedDataBase<double, TEMPTYPE>*)(p_shared_data));\n\t\t\t\tshared.atomic_B4_1_integrand(x[0], x[1], x[2], x[3], x[4], fval);\n\t\t\t\treturn 0; // success\n\t\t\t};\n\n\t\t\tauto cubature_integrand_2 = [](unsigned ndim, const double* x, void* p_shared_data, unsigned fdim, double* fval) {\n\t\t\t\tauto& shared = *((class SharedDataBase<double, TEMPTYPE>*)(p_shared_data));\n\t\t\t\tshared.atomic_B4_2_integrand(x[0], x[1], x[2], x[3], x[4], fval);\n\t\t\t\treturn 0; // success\n\t\t\t};\n\n\t\t\tauto cubature_integrand_3 = [](unsigned ndim, const double* x, void* p_shared_data, unsigned fdim, double* fval) {\n\t\t\t\tauto& shared = *((class SharedDataBase<double, TEMPTYPE>*)(p_shared_data));\n\t\t\t\tshared.atomic_B4_3_integrand(x[0], x[1], x[2], x[3], x[4], x[5], fval);\n\t\t\t\treturn 0; // success\n\t\t\t};\n\n\t\t\t// prefactors for each contribution \n\t\t\tstd::valarray<double> pre_factors = {-3.0*(27.0/4.0), 3.0*(27.0/2.0), -27.0/(8.0*M_PI)};\n\n\t\t\tint naxes = 5; // How many dimensions the integral is taken over (r14, r13, gamma, r12, eta)\n\t\t\thcubature(ndim, cubature_integrand_1, &shared, naxes, &(xmins[0][0]), &(xmaxs[0][0]), feval_max, 0, 1e-4, ERROR_INDIVIDUAL, &(vals[0][0]), &(errs[0][0]));\n\t\t\thcubature(ndim, cubature_integrand_2, &shared, naxes, &(xmins[1][0]), &(xmaxs[1][0]), feval_max, 0, 1e-4, ERROR_INDIVIDUAL, &(vals[1][0]), &(errs[1][0]));\n\n\t\t\tnaxes = 6;\n\t\t\thcubature(ndim, cubature_integrand_3, &shared, naxes, &(xmins[2][0]), &(xmaxs[2][0]), feval_max, 0, 1e-4, ERROR_INDIVIDUAL, &(vals[2][0]), &(errs[2][0]));\n\n\t\t\tfor (auto i = 0; i < pre_factors.size(); ++i) {\n                vals[i] *= pre_factors[i];\n                errs[i] *= pre_factors[i];\n\t\t\t}\n\n            // Copy into output\n\t\t\toutval = vals[0] + vals[1] + vals[2];\n\t\t\touterr = std::abs(errs[0]) + std::abs(errs[1]) + std::abs(errs[2]);\n\n\t\t\tbreak;\n\t\t}\n        default:\n            throw -1;\n        }\n#endif\n        if constexpr (std::is_same<decltype(Tstar), double>::value) {\n            // If T is double (real)\n            return std::make_tuple(outval[0],outerr[0]);\n        }\n        else if constexpr (std::is_same<decltype(Tstar), std::complex<double>>::value) {\n            // If T is a complex number (perhaps for complex step derivatives)\n            return std::make_tuple(decltype(Tstar)(outval[0], outval[1]), decltype(Tstar)(outerr[0], outerr[1]));\n        }\n        else if constexpr (std::is_same<decltype(Tstar), MultiComplex<double>>::value) {\n            // If T is a multicomplex number\n            return std::make_tuple(decltype(Tstar)(outval), decltype(Tstar)(outerr));\n        }\n    }\n    \n    std::map<std::string, double> B_and_derivs(int order, int Nderivs, double T, double rstart, double rend, Molecule<TYPE> mol1, Molecule<TYPE> mol2){\n        \n        if (Nderivs == 0) {\n            auto [val,esterr] = this->one_temperature(order, T, rstart, rend, mol1, mol2);\n            return {\n                {\"T\", T},\n                {\"B\", val},\n                {\"error(B)\", esterr}\n            };\n        }\n        if (Nderivs == 1) {\n            double h = 1e-100;\n            auto [val,esterr] = this->one_temperature(order, std::complex<double>(T,h), rstart, rend, mol1, mol2);\n            return {\n                {\"T\", T},\n                {\"B\", val.real()},\n                {\"error(B)\", esterr.real()},\n                {\"dBdT\", val.imag()/h},\n                {\"error(dBdT)\", esterr.imag()/h},\n            };\n        }\n        else {\n            std::function<std::tuple<MultiComplex<double>,MultiComplex<double>>(const MultiComplex<double>&)> f(\n                [this, order, rstart, rend, mol1, mol2](const MultiComplex<double>& T) {\n                    return this->one_temperature(order, T, rstart, rend, mol1, mol2);\n                });\n            bool and_val = true;\n            auto [val,esterr] = diff_mcx1(f, T, Nderivs, and_val);\n            std::map<std::string, double> o = { {\"T\", T} };\n            for (auto i = 0; i <= Nderivs; ++i) {\n                switch (i) {\n                case 0:\n                    o[\"B\"] = val[0];\n                    o[\"error(B)\"] = esterr[0];\n                    break;\n                case 1:\n                    o[\"dBdT\"] = val[1];\n                    o[\"error(dBdT)\"] = esterr[1];\n                    break;\n                default:\n                    auto n = std::to_string(i);\n                    o[\"d\" + n + \"BdT\" + n] = val[i];\n                    o[\"error(d\" + n + \"BdT\" + n + \")\"] = esterr[i];\n                }\n            }\n            return o;\n        }\n    }\n    auto parallel_B_and_derivs(int order, int Nthreads, int Nderivs, std::vector<double> Tvec, double rstart, double rend, Molecule<TYPE> mol1, Molecule<TYPE> mol2)\n    {\n        init_thread_pool(Nthreads);\n        std::vector<double> times(Tvec.size());\n        std::vector<std::map<std::string, double>> outputs(Tvec.size());\n        std::size_t i = 0;\n        for (auto T : Tvec) {\n            auto& result = outputs[i];\n            auto& time = times[i];\n            std::function<void(void)> one_Temp = [this, order, Nderivs, T, rstart, rend, mol1, mol2, &result, &time]() {\n                auto startTime = std::chrono::high_resolution_clock::now();\n                result = this->B_and_derivs(order, Nderivs, T, rstart, rend, mol1, mol2);\n                auto endTime = std::chrono::high_resolution_clock::now();\n                time = std::chrono::duration<double>(endTime - startTime).count(); \n                {\n                    mtx.lock();\n                    std::cout << \"Done \" << T << \" in \" << time << \" seconds\\n\" ;\n                    mtx.unlock();\n                }\n                result[\"elapsed / s\"] = time;\n            };\n            m_pool->AddJob(one_Temp);\n            i++;\n        }\n        // Wait until all the threads finish...\n        m_pool->WaitAll();\n        return outputs;\n    }\n    TYPE orientation_averaged_integrate(const TYPE Tstar, const TYPE rstart, const TYPE rend) {\n        using arr = Eigen::Array<TYPE, Eigen::Dynamic, 1>;\n        bool parallel = false;\n        if (parallel){\n            // Parallel\n            TYPE result, time;\n            Molecule<TYPE> mol1 = this->mol1, mol2 = this->mol2;\n            auto one_temperature_job = [this, Tstar, rstart, rend, mol1, mol2, &result, &time]() {\n                auto startTime = std::chrono::high_resolution_clock::now();\n                result = one_temperature<double>(Tstar, rstart, rend, mol1, mol2);\n                auto endTime = std::chrono::high_resolution_clock::now();\n                time = std::chrono::duration<double>(endTime - startTime).count();\n            };\n            m_pool->AddJob(one_temperature_job);\n            // Wait until all the threads finish...\n            m_pool->WaitAll();\n            return result;\n        }\n        else {\n            // Serial\n            return one_temperature(Tstar, rstart, rend, mol1, mol2);\n        }\n    }\n};\n", "meta": {"hexsha": "f89bc68e15d2d67b08fdb5a55ee7262fa002bbbe", "size": 35779, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/potter/potter.hpp", "max_stars_repo_name": "usnistgov/potter", "max_stars_repo_head_hexsha": "8d8e396fb37caee6d9be37396c5a3b783d7ed0b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-09T02:36:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T00:46:54.000Z", "max_issues_repo_path": "include/potter/potter.hpp", "max_issues_repo_name": "usnistgov/potter", "max_issues_repo_head_hexsha": "8d8e396fb37caee6d9be37396c5a3b783d7ed0b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/potter/potter.hpp", "max_forks_repo_name": "usnistgov/potter", "max_forks_repo_head_hexsha": "8d8e396fb37caee6d9be37396c5a3b783d7ed0b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-03-24T17:17:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T17:43:39.000Z", "avg_line_length": 40.2916666667, "max_line_length": 170, "alphanum_fraction": 0.5707817435, "num_tokens": 10411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7956581000631541, "lm_q1q2_score": 0.626923838105715}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2015 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   License for the specific language governing rights and limitations under\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n#include <Testing/Utils/SCIRunUnitTests.h>\n#include <fstream>\n#include <boost/filesystem.hpp>\n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Algorithms/Math/SolveLinearSystemWithEigen.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/DenseColumnMatrix.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n#include <Core/Datatypes/MatrixComparison.h>\n#include <Core/Datatypes/MatrixTypeConversions.h>\n#include <Core/Datatypes/MatrixIO.h>\n#define register\n#include <Eigen/Sparse>\n#undef register\n#include <Testing/Utils/MatrixTestUtilities.h>\n#include <Core/Algorithms/DataIO/EigenMatrixFromScirunAsciiFormatConverter.h>\n\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms::Math;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::DataIO::internal;\nusing namespace SCIRun::Core;\nusing namespace SCIRun::TestUtils;\nusing namespace SCIRun;\nusing namespace ::testing;\n\n/// @todo: remove these Eigen tests if they are duplicates of existing SLS tests. Other tests below need to live in separate files.\n\n#if 0\nTEST(SolveLinearSystemWithEigenAlgorithmTests, CanSolveBasicSmallDenseSystemWithEigenClasses)\n{\n  int n = 3;\n  DenseMatrix m1(n,n);\n  m1 << 2,-1,0,\n    -1,2,-1,\n    0,-1,2;\n\n  using namespace Eigen;\n  VectorXd v(n);\n  v << 1,2,3;\n  std::cout << \"expected solution = \\n\" << v << std::endl;\n\n  auto rhs = m1*v;\n  std::cout << \"rhs = \\n\" << rhs << std::endl;\n\n  VectorXd x(n);\n  x.setZero();\n\n  std::cout << \"matrix to solve: \\n\" << m1 << std::endl;\n\n  ConjugateGradient<DenseMatrix::EigenBase> cg;\n  cg.compute(m1);\n\n  ASSERT_TRUE(cg.info() == Success);\n\n  cg.setTolerance(1e-15);\n  x = cg.solve(rhs);\n\n#if 0\n  cg.setMaxIterations(1);\n  int i = 0;\n  do {\n    x = cg.solveWithGuess(rhs, x);\n\n    std::cout << i << \" : \" << cg.error() << std::endl;\n    ++i;\n  } while (cg.info() != Success && i < 2000);\n#endif\n\n  std::cout << \"#iterations:     \" << cg.iterations() << std::endl;\n  std::cout << \"estimated error: \" << cg.error()      << std::endl;\n\n  std::cout << x << std::endl;\n\n  EXPECT_EQ(v, x);\n}\n\nTEST(SolveLinearSystemWithEigenAlgorithmTests, CanSolveBasicSmallDenseSystem)\n{\n  int n = 3;\n  DenseMatrixHandle A(new DenseMatrix(n,n));\n  *A << 2,-1,0,\n    -1,2,-1,\n    0,-1,2;\n\n  DenseColumnMatrix v(n);\n  v << 1,2,3;\n  std::cout << \"expected solution = \\n\" << v << std::endl;\n\n  DenseColumnMatrixHandle rhs(new DenseColumnMatrix(*A * v));\n  std::cout << \"rhs = \\n\" << *rhs << std::endl;\n\n  SolveLinearSystemAlgorithm algo;\n\n  auto x = algo.run(boost::make_tuple(A, rhs), boost::make_tuple(1e-15, 10));\n  DenseColumnMatrixHandle solution = x.get<0>();\n\n  ASSERT_TRUE(solution.get() != nullptr);\n  EXPECT_EQ(v, *solution);\n}\n\nTEST(SolveLinearSystemWithEigenAlgorithmTests, CanSolveBasicSmallSparseSystem)\n{\n  int n = 3;\n  DenseMatrix Adense(n,n);\n  Adense << 2,-1,0,\n    -1,2,-1,\n    0,-1,2;\n\n  SparseRowMatrixHandle A(new SparseRowMatrix(n,n));\n  copyDenseToSparse(Adense, *A);\n\n  DenseColumnMatrix v(n);\n  v << 1,2,3;\n  std::cout << \"expected solution = \\n\" << v << std::endl;\n\n  DenseColumnMatrixHandle rhs(new DenseColumnMatrix(*A * v));\n  std::cout << \"rhs = \\n\" << *rhs << std::endl;\n\n  SolveLinearSystemAlgorithm algo;\n\n  auto x = algo.run(boost::make_tuple(A, rhs), boost::make_tuple(1e-15, 10));\n  DenseColumnMatrixHandle solution = x.get<0>();\n\n  ASSERT_TRUE(solution.get() != nullptr);\n  EXPECT_EQ(v, *solution);\n}\n\nTEST(SolveLinearSystemWithEigenAlgorithmTests, ThrowsOnNullMatrix)\n{\n  DenseMatrixHandle A;\n\n  DenseColumnMatrixHandle rhs(new DenseColumnMatrix(3));\n\n  SolveLinearSystemAlgorithm algo;\n\n  EXPECT_THROW(algo.run(boost::make_tuple(A, rhs), boost::make_tuple(1e-15, 10)), AlgorithmInputException);\n}\n\nTEST(SolveLinearSystemWithEigenAlgorithmTests, ThrowsOnNullRHS)\n{\n  int n = 3;\n  DenseMatrixHandle A(new DenseMatrix(n,n));\n  *A << 2,-1,0,\n    -1,2,-1,\n    0,-1,2;\n\n  DenseColumnMatrixHandle rhs;\n\n  SolveLinearSystemAlgorithm algo;\n\n  EXPECT_THROW(algo.run(boost::make_tuple(A, rhs), boost::make_tuple(1e-15, 10)), AlgorithmInputException);\n}\n\nTEST(SolveLinearSystemWithEigenAlgorithmTests, ThrowsOnNegativeTolerance)\n{\n  int n = 3;\n  DenseMatrixHandle A(new DenseMatrix(n,n));\n  *A << 2,-1,0,\n    -1,2,-1,\n    0,-1,2;\n\n  DenseColumnMatrix v(n);\n  v << 1,2,3;\n\n  DenseColumnMatrixHandle rhs(new DenseColumnMatrix(*A * v));\n\n  SolveLinearSystemAlgorithm algo;\n\n  EXPECT_THROW(algo.run(boost::make_tuple(A, rhs), boost::make_tuple(-4, 10)), AlgorithmInputException);\n}\n\nTEST(SolveLinearSystemWithEigenAlgorithmTests, ThrowsOnNegativeMaxIterations)\n{\n  int n = 3;\n  DenseMatrixHandle A(new DenseMatrix(n,n));\n  *A << 2,-1,0,\n    -1,2,-1,\n    0,-1,2;\n\n  DenseColumnMatrix v(n);\n  v << 1,2,3;\n\n  DenseColumnMatrixHandle rhs(new DenseColumnMatrix(*A * v));\n\n  SolveLinearSystemAlgorithm algo;\n\n  EXPECT_THROW(algo.run(boost::make_tuple(A, rhs), boost::make_tuple(1e-15, -1)), AlgorithmInputException);\n}\n#endif\n//todo: remove unused code\nTEST(SparseMatrixReadTest, DISABLED_RegexOfScirun4Format)\n{\n  EigenMatrixFromScirunAsciiFormatConverter converter;\n\n  auto file = TestResources::rootDir() / \"sp2.mat\";\n\n  if (!boost::filesystem::exists(file))\n  {\n    FAIL() << \"TODO: Issue #142 will standardize these file locations other than being on Dan's hard drive.\" << std::endl\n        << \"Once that issue is done however, this will be a user setup error.\" << std::endl;\n    return;\n  }\n\n  std::string matStr = converter.readFile(file.string());\n\n  //2 3 4 {8 0 2 4 }{8 0 2 0 1 }{1 3.5 -1 2 }}\n\n  std::string contents = converter.getMatrixContentsLine(matStr).get_value_or(\"\");\n\n  std::string newline;\n#ifndef WIN32\n  newline += \"\\r\";\n#endif\n\n  EXPECT_EQ(\"2 3 4 {8 0 2 4 }{8 0 2 0 1 }{1 3.5 -1 2 }}\" + newline, contents);\n\n  auto rawOpt = converter.parseSparseMatrixString(contents);\n  ASSERT_TRUE(static_cast<bool>(rawOpt));\n  auto raw = rawOpt.get();\n\n  EXPECT_EQ(\"2\", raw.get<0>());\n  EXPECT_EQ(\"3\", raw.get<1>());\n  EXPECT_EQ(\"4\", raw.get<2>());\n  EXPECT_EQ(\"0 2 4 \", raw.get<3>());\n  EXPECT_EQ(\"0 2 0 1 \", raw.get<4>());\n  EXPECT_EQ(\"1 3.5 -1 2 \", raw.get<5>());\n\n  auto data = converter.convertRaw(raw);\n  EXPECT_EQ(2, data.get<0>());\n  EXPECT_EQ(3, data.get<1>());\n  EXPECT_EQ(4, data.get<2>());\n  EXPECT_THAT(data.get<3>(), ElementsAre(0, 2, 4));\n  EXPECT_THAT(data.get<4>(), ElementsAre(0, 2, 0, 1));\n  EXPECT_THAT(data.get<5>(), ElementsAre(1.0, 3.5, -1.0, 2.0));\n\n  auto mat = converter.makeSparse(file.string());\n  ASSERT_TRUE(mat.get() != nullptr);\n  EXPECT_EQ(2, mat->rows());\n  EXPECT_EQ(3, mat->cols());\n\n  DenseMatrix a(2, 3);\n  a << 1, 0, 3.5,\n    -1, 2, 0;\n\n  EXPECT_EQ(a, *convertMatrix::toDense(mat));\n#if !DEBUG\n  EXPECT_EQ(to_string(a), to_string(mat->castForPrinting()));\n#endif\n}\n\nTEST(EigenSparseSolverTest, CanSolveTinySystem)\n{\n  typedef Eigen::Triplet<double> T;\n  std::vector<T> tripletList;\n  int estimation_of_entries = 10;\n  tripletList.reserve(estimation_of_entries);\n  for(int i = 0; i < estimation_of_entries; ++i)\n  {\n    tripletList.push_back(T(i,i, i *3 + 1));\n  }\n  int n = 10;\n  Eigen::SparseMatrix<double> mat(n,n);\n  mat.setFromTriplets(tripletList.begin(), tripletList.end());\n\n  Eigen::VectorXd x(n), b(n);\n  // fill A and b\n  b.setZero();\n  b(1) = 1;\n\n  Eigen::ConjugateGradient<Eigen::SparseMatrix<double> > cg;\n  cg.compute(mat);\n  x = cg.solve(b);\n  std::cout << \"#iterations:     \" << cg.iterations() << std::endl;\n  std::cout << \"estimated error: \" << cg.error()      << std::endl;\n}\n\nTEST(SparseMatrixReadTest, DISABLED_CanReadInBigMatrix)\n{\n  auto file = TestResources::rootDir() / \"CGDarrell\" / \"A_txt.mat \";\n  EigenMatrixFromScirunAsciiFormatConverter converter;\n  auto mat = converter.makeSparse(file.string());\n  ASSERT_TRUE(mat.get() != nullptr);\n  EXPECT_EQ(428931, mat->rows());\n  EXPECT_EQ(428931, mat->cols());\n}\n\nTEST(SparseMatrixReadTest, DISABLED_CanReadInBigVector)\n{\n  //428931 1 {0 0.005436646179877679 -0.002975964005526226\n  auto file = TestResources::rootDir() / \"CGDarrell\" / \"RHS_text.txt\";\n  EigenMatrixFromScirunAsciiFormatConverter converter;\n  auto mat = converter.makeDense(file.string());\n  ASSERT_TRUE(mat.get() != nullptr);\n  EXPECT_EQ(428931, mat->rows());\n  EXPECT_EQ(1, mat->cols());\n}\n\nTEST(EigenSparseSolverTest, DISABLED_CanSolveBigSystem)\n{\n  auto AFile = TestResources::rootDir() / \"CGDarrell\" / \"A_txt.mat\";\n  auto rhsFile = TestResources::rootDir() / \"CGDarrell\" / \"RHS_text.txt\";\n  EigenMatrixFromScirunAsciiFormatConverter converter;\n  auto A = converter.make(AFile.string());\n  ASSERT_TRUE(A.get() != nullptr);\n\n  std::cout << A->nrows() << \" x \" << A->ncols() << std::endl;\n\n  auto b = converter.make(rhsFile.string());\n  ASSERT_TRUE(b.get() != nullptr);\n  std::cout << b->nrows() << \" x \" << b->ncols() << std::endl;\n  auto bCol = convertMatrix::toColumn(b);\n\n  SolveLinearSystemAlgorithm::Outputs x;\n  {\n    ScopedTimer t(\"using algorithm object\");\n    SolveLinearSystemAlgorithm algo;\n\n    x = algo.run(std::make_tuple(A, bCol), std::make_tuple(1e-20, 4000, \"cg\"));\n    MatrixHandle solution = std::get<0>(x);\n\n    ASSERT_TRUE(solution.get() != nullptr);\n    std::cout << \"error: \" << std::get<1>(x) << std::endl;\n    std::cout << \"iterations: \" << std::get<2>(x) << std::endl;\n  }\n\n  {\n    ScopedTimer t(\"comparing solutions.\");\n    auto xFileEigen = TestResources::rootDir() / \"CGDarrell\" / \"xEigenNEW.txt\";\n    std::ofstream output(xFileEigen.string());\n    auto solution = *std::get<0>(x);\n    output << std::setprecision(15) << solution << std::endl;\n\n    auto xFileScirun = TestResources::rootDir() / \"CGDarrell\" / \"xScirunColumn.mat\";\n    auto xExpected = converter.makeColumn(xFileScirun.string());\n    ASSERT_TRUE(xExpected.get() != nullptr);\n    EXPECT_EQ(428931, xExpected->nrows());\n    EXPECT_EQ(1, xExpected->ncols());\n\n    EXPECT_COLUMN_MATRIX_EQ_BY_TWO_NORM(*xExpected, solution , .1);\n    EXPECT_COLUMN_MATRIX_EQ_BY_TWO_NORM(*xExpected, solution , .01);\n    EXPECT_COLUMN_MATRIX_EQ_BY_TWO_NORM(*xExpected, solution , .001);\n    EXPECT_COLUMN_MATRIX_EQ_BY_TWO_NORM(*xExpected, solution , .0001);\n  }\n}\n", "meta": {"hexsha": "cd7fcd3d362e19d106765ad7f953f7b73dcecde0", "size": 11363, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Math/Tests/SolveLinearSystemWithEigenTests.cc", "max_stars_repo_name": "Nahusa/SCIRun", "max_stars_repo_head_hexsha": "c54e714d4c7e956d053597cf194e07616e28a498", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T06:00:15.000Z", "max_issues_repo_path": "src/Core/Algorithms/Math/Tests/SolveLinearSystemWithEigenTests.cc", "max_issues_repo_name": "manual123/SCIRun", "max_issues_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Algorithms/Math/Tests/SolveLinearSystemWithEigenTests.cc", "max_forks_repo_name": "manual123/SCIRun", "max_forks_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "max_forks_repo_licenses": ["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.3823529412, "max_line_length": 131, "alphanum_fraction": 0.6896946229, "num_tokens": 3320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6268740185144328}}
{"text": "// (C) 2014 Arek Olek\n\n#pragma once\n\n#include <chrono>\n#include <random>\n#include <tuple>\n\n#include <boost/graph/graphml.hpp>\n\n#include \"algorithm.hpp\"\n#include \"graph.hpp\"\n\ntemplate <class Iterator>\nvoid generate_seeds(Iterator begin, Iterator end, std::string seed) {\n  std::seed_seq seq(seed.begin(), seed.end());\n  seq.generate(begin, end);\n}\n\ndouble pr_within(double x) {\n  return x <= 1\n    ?  .5*x*x*x*x - 8./3*x*x*x + M_PI*x*x\n    : -.5*x*x*x*x - 4*x*x*atan(sqrt(x*x-1)) + 4./3*(2*x*x+1)*sqrt(x*x-1) + (M_PI-2)*x*x + 1./3;\n};\n\ntemplate <class Graph>\nclass test_suite {\npublic:\n  unsigned size() const { return seeds.size() * degrees.size() * sizes.size(); }\n\n  std::string type() const { return t; }\n\n  std::tuple<Graph, unsigned, double, double> get(unsigned i) const {\n    auto run = i % seeds.size();\n    std::default_random_engine generator(seeds[run]);\n    auto expected_degree = degrees[(i / seeds.size()) % degrees.size()];\n    auto n = sizes[i / seeds.size() / degrees.size()];\n    auto d = expected_degree;\n    auto tree_degree = 2.*(n-1)/n;\n    bool mst = found(\"mst\", t);\n    bool unite = !found(\"++\", t);\n    bool vanilla = !found(\"+\", t);\n    Graph G(n), G_shuffled(n);\n    double parameter;\n\n    // use d in [0,1] to mean density (since connected graphs have d > 1 anyway)\n    if(unite && d <= 1) d *= n-1;\n\n    do {\n      G = Graph(n);\n\n      if(found(\"path\", t)) {\n        add_spider(G, 1);\n        // the overlap satisfies    y     = a    x     + b\n        // full graph satisfies:    0     = a  (n-1)   + b\n        // tree graph satisfies: 2(n-1)/n = a 2(n-1)/n + b\n        // so we must subtract this:\n        if(unite) d -= 2./(2.-n) * d + 1. + n/(n-2.);\n      }\n\n      if(found(\"rgg\", t)) {\n        if(mst && unite) d -= d<2 ? tree_degree : 1/sinh(d-sqrt(2.)); // approximate fit\n        parameter = find_argument(d/(n-1), pr_within, 0, sqrt(2.));\n        Geometric points(n, generator);\n        points.add_random_geometric(G, parameter);\n        if(mst) points.add_mst(G);\n      }\n      else if(found(\"gnp\", t)) {\n        if(mst && unite) d -= d<2 ? tree_degree : 1/(2*M_PI*sinh(d-M_PI/sqrt(3.))); // approximate fit\n        parameter = d<0 ? 0 : d/(n-1);\n        add_edges_uniform(G, parameter, generator, mst);\n      }\n    } while(vanilla && !is_connected(G));\n\n    copy_edges_shuffled(G, G_shuffled, generator);\n    return std::make_tuple(G_shuffled, run, expected_degree, parameter);\n  }\n\n  unsigned get_seed(unsigned i) {\n    return seeds[i % seeds.size()];\n  }\n\n  template<class Sizes, class Degrees>\n  test_suite(std::string t, unsigned z, Sizes ns, Degrees ds, std::string seed)\n      : t(t), sizes(ns), degrees(ds) {\n    seeds.resize(z);\n    generate_seeds(seeds.begin(), seeds.end(), seed);\n  }\nprivate:\n  std::string t;\n  std::vector<unsigned> sizes;\n  std::vector<double> degrees;\n  std::vector<unsigned> seeds;\n};\n\ntemplate <class Graph>\nclass file_suite {\npublic:\n  std::tuple<Graph, unsigned, double, double> get(unsigned i) const {\n    auto run = i % seeds.size();\n    i /= seeds.size();\n    std::default_random_engine generator(seeds[run]);\n    Graph g(num_vertices(graphs[i]));\n    copy_edges_shuffled(graphs[i], g, generator);\n    return std::make_tuple(g, run, 0, 0);\n  }\n\n  unsigned get_seed(unsigned i) const {\n    return seeds[i % seeds.size()];\n  }\n\n  unsigned size() const { return graphs.size() * seeds.size(); }\n\n  file_suite(std::string f, unsigned size, std::string seed)\n      : t(f.substr(f.rfind('/')+1, f.rfind('.')-f.rfind('/')-1)),\n        seeds(size)  {\n    std::ifstream file(f);\n    if(!file.good()) {\n      throw std::invalid_argument(\"File does not exist: \" + f);\n    }\n    int z, n, m, s, t;\n    file >> z;\n    while(z--) {\n      file >> n >> m;\n      Graph G(n);\n      for(int i = 0; i < m; ++i) {\n        file >> s >> t;\n        add_edge(s, t, G);\n      }\n      graphs.push_back(G);\n    }\n    file.close();\n    generate_seeds(seeds.begin(), seeds.end(), seed);\n  }\n  std::string type() const {\n    return t;\n  }\nprivate:\n  std::string t;\n  std::vector<Graph> graphs;\n  std::vector<unsigned> seeds;\n};\n\ntemplate <class Graph>\nclass real_suite {\npublic:\n  unsigned size() const { return seeds.size(); }\n\n  std::tuple<Graph, unsigned, double, double> get(unsigned i) const {\n    std::default_random_engine generator(seeds[i]);\n    Graph g(num_vertices(G));\n    copy_edges_shuffled(G, g, generator);\n    return std::make_tuple(g, i, 0, 0);\n  }\n\n  unsigned get_seed(unsigned i) const {\n    return seeds[i];\n  }\n\n  real_suite(std::string f, unsigned size, std::string seed)\n      : G(0),\n        t(f.substr(f.rfind('/')+1, f.rfind('.')-f.rfind('/')-1)),\n        seeds(size) {\n    std::ifstream file(f);\n    if (!file.good()) {\n      throw std::invalid_argument(\"File does not exist: \" + f);\n    }\n    boost::dynamic_properties dp;\n    read_graphml(file, G, dp);\n    generate_seeds(seeds.begin(), seeds.end(), seed);\n  }\n  std::string type() const {\n    return t;\n  }\nprivate:\n  Graph G;\n  std::string t;\n  std::vector<unsigned> seeds;\n};\n", "meta": {"hexsha": "433049659e73b91abc356524818c4ffbeeec0028", "size": 5005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/test_suite.hpp", "max_stars_repo_name": "arekolek/MaxIST", "max_stars_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_suite.hpp", "max_issues_repo_name": "arekolek/MaxIST", "max_issues_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_suite.hpp", "max_forks_repo_name": "arekolek/MaxIST", "max_forks_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8055555556, "max_line_length": 102, "alphanum_fraction": 0.5872127872, "num_tokens": 1453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6268639213032291}}
{"text": "/*! \\file\tut_rpn_evaluator.cpp\n\t\\brief\tRPN evaluator unit test.\n\t\\author\tGarth Santor\n\t\\date\t2021-10-29\n\t\\copyright\tGarth Santor, Trinh Han\n\n=============================================================\nReverse-Polish Evaluator unit test for Expression Evaluator Project.\n\n=============================================================\nRevision History\n-------------------------------------------------------------\n\nVersion 2021.11.01\n\tC++ 20 validated\n\nVersion 2019.11.05\n\tC++ 17 cleanup\n\nVersion 2015.11.05\n\tVisual Studio 2015\n\tTEST_xxxx macros\n\nVersion 2014.11.21\n\tImproved round() - reduced float point conversion errors.\n\nVersion 2014.10.31\n\tVisual Studio 2013\n\tRemoved bit operations\n\tAdded multiprecision.\n\nVersion 2012.11.16\n\tAdded BitAnd, BitNot, BitOr, BitXor, BitShiftLeft, BitShiftRight\n\nVersion 2012.11.15\n\tAdded BinaryInteger, Binary <function>\n\nVersion 2012.11.13\n\tC++ 11 cleanup\n\nVersion 2009.12.01\n\tAlpha release.\n\n=============================================================\n\nCopyright Garth Santor / Trinh Han\n\nThe copyright to the computer program(s) herein\nis the property of Garth Santor / Trinh Han, Canada.\nThe program(s) may be used and /or copied only with\nthe written permission of Garth Santor / Trinh Han\nor in accordance with the terms and conditions\nstipulated in the agreement / contract under which\nthe program(s) have been supplied.\n============================================================= */\n\n// unit test library\n#include <gats/TestApp.hpp>\n\n#include <ee/RPNEvaluator.hpp>\n#include <ee/boolean.hpp>\n#include <ee/integer.hpp>\n#include <ee/function.hpp>\n#include <ee/operator.hpp>\n#include <ee/real.hpp>\n#include <ee/variable.hpp>\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"ut_test_phases.hpp\"\n\n\n#if TEST_REAL\nReal::value_type round(Real::value_type x) {\n\tauto exp = pow(Real::value_type(\"10.0\"), Real::value_type(\"990\"));\n\tx *= exp;\n\tx += 0.5;\n\tx = floor(x);\n\tx /= exp;\n\treturn x;\n}\n\nReal::value_type round(Token::pointer_type const& v) {\n\treturn round(value_of<Real>(v));\n}\n#endif\n\n\nGATS_TEST_CASE(no_operand) {\n\ttry {\n\t\tauto t = RPNEvaluator().evaluate(TokenList());\n\t\tGATS_FAIL(\"Failed to throw exception\");\n\t}\n\tcatch( std::exception& e ) {\n\t\tGATS_CHECK( strcmp( e.what(), \"Error: insufficient operands\" ) == 0 );\n\t}\n}\n\n\n#if TEST_INTEGER\n\tGATS_TEST_CASE(too_many_operand) {\n\t\ttry {\n\t\t\tTokenList tl = { make<Integer>(3), make<Integer>(4) };\n\t\t\tauto t = RPNEvaluator().evaluate(tl);\n\t\t\tGATS_FAIL(\"Failed to throw exception\");\n\t\t}\n\t\tcatch( std::exception& e ) {\n\t\t\tGATS_CHECK( strcmp( e.what(), \"Error: too many operands\" ) == 0 );\n\t\t}\n\t}\n#endif\n\n\n\n#if TEST_VARIABLE\n\tGATS_TEST_CASE(unitialized_single_variable) {\n\t\tauto result = RPNEvaluator().evaluate({ make<Variable>() });\n\n\t\tGATS_CHECK(is<Variable>(result));\n\t\tVariable::pointer_type v = convert<Variable>(result);\n\t\tGATS_CHECK(v->value() == nullptr);\n\t}\n\tGATS_TEST_CASE(unitialized_variable_expression) {\n\t\ttry {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Variable>(), make<Negation>() });\n\t\t\tGATS_FAIL(\"Failed to throw exception\");\n\t\t}\n\t\tcatch (std::exception& e) {\n\t\t\tGATS_CHECK(strcmp(e.what(), \"Error: variable not initialized\") == 0);\n\t\t}\n\t}\n#endif\n\n\n// literals\n#if TEST_INTEGER\n\tGATS_TEST_CASE(Integer_3){\n\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(3) });\n\t\tGATS_CHECK(value_of<Integer>(result) == Integer::value_type(3));\n\t}\n#endif\n#if TEST_REAL\n\tGATS_TEST_CASE(Real_3_14){\n\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"3.14\")) });\n\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"3.14\"));\n\t}\n#endif\n\n\n\n// Constants\n#if TEST_BOOLEAN\n\tGATS_TEST_CASE(constant_true) {\n\t\tauto result = RPNEvaluator().evaluate({ make<True>() });\n\t\tGATS_CHECK(value_of<True>(result) == true);\n\t}\n\tGATS_TEST_CASE(constant_false) {\n\t\tauto result = RPNEvaluator().evaluate({ make<False>() });\n\t\tGATS_CHECK(value_of<False>(result) == false);\n\t}\n#endif\n#if TEST_REAL\n\tGATS_TEST_CASE(constant_Pi) {\n\t\tauto result = RPNEvaluator().evaluate({ make<Pi>() });\n\t\tGATS_CHECK(value_of<Real>(result) == boost::math::constants::pi<Real::value_type>());\n\t}\n\tGATS_TEST_CASE(constant_E) {\n\t\tauto result = RPNEvaluator().evaluate({ make<E>() });\n\t\tGATS_CHECK(value_of<Real>(result) == boost::math::constants::e<Real::value_type>());\n\t}\n#endif\n\n// Identity\n#if TEST_UNARY_OPERATOR\n\t#if TEST_INTEGER\n\t\tGATS_TEST_CASE(identity_test_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(3), make<Identity>() });\n\t\t\tGATS_CHECK(value_of<Integer>(result) == Integer::value_type(3));\n\t\t}\n\t#endif\n\t#if TEST_REAL\n\t\tGATS_TEST_CASE(identity_test_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"3\")), make<Identity>() });\n\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"3.0\"));\n\t\t}\n\t#endif\n\n\n\t// Negation\n\t#if TEST_INTEGER\n\t\tGATS_TEST_CASE(negation_test_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(3), make<Negation>() });\n\t\t\tGATS_CHECK(value_of<Integer>(result) == Integer::value_type(-3));\n\t\t}\n\t#endif\n\t#if TEST_REAL\n\t\tGATS_TEST_CASE(negation_test_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(3), make<Negation>() });\n\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"-3.0\"));\n\t\t}\n\t#endif\n\n\n\t// Factorial\n\t#if TEST_INTEGER\n\t\tGATS_TEST_CASE(factorial_test_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(5), make<Factorial>() });\n\t\t\tGATS_CHECK(value_of<Integer>(result) == Integer::value_type(120));\n\t\t}\n\t#endif\n\n\n\t// Logical not\n\t#if TEST_BOOLEAN\n\t\tGATS_TEST_CASE(not_test_Boolean) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Boolean>(true), make<Not>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\tresult = RPNEvaluator().evaluate({ make<Boolean>(false), make<Not>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t}\n\t#endif\n#endif // TEST_UNARY_OPERATOR\n\n\n#if TEST_BINARY_OPERATOR\n\t#if TEST_INTEGER\n\t\tGATS_TEST_CASE(test_multiply_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(3), make<Integer>(4), make<Multiplication>() });\n\t\t\tGATS_CHECK(value_of<Integer>(result) == Integer::value_type(12));\n\t\t}\n\t\tGATS_TEST_CASE(test_divide_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(45), make<Integer>(3), make<Division>() });\n\t\t\tGATS_CHECK(value_of<Integer>(result) == Integer::value_type(15));\n\t\t}\n\t\tGATS_TEST_CASE(test_addition_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(3), make<Integer>(4), make<Addition>() });\n\t\t\tGATS_CHECK(value_of<Integer>(result) == Integer::value_type(7));\n\t\t}\n\t\tGATS_TEST_CASE(test_subtraction_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(3), make<Integer>(4), make<Subtraction>() });\n\t\t\tGATS_CHECK(value_of<Integer>(result) == Integer::value_type(-1));\n\t\t}\n\t\tGATS_TEST_CASE(test_modulus_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(12), make<Integer>(5), make<Modulus>() });\n\t\t\tGATS_CHECK(value_of<Integer>(result) == Integer::value_type(2));\n\t\t}\n\t\tGATS_TEST_CASE(test_power_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(3), make<Integer>(4), make<Power>() });\n\t\t\tGATS_CHECK(value_of<Integer>(result) == Integer::value_type(81));\n\t\t}\n\t\t#if TEST_VARIABLE\n\t\t\tGATS_TEST_CASE( assignment_test ) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Variable>(), make<Integer>(4), make<Assignment>() });\n\n\t\t\t\tGATS_CHECK(is<Variable>(result));\n\t\t\t\tVariable::pointer_type v = convert<Variable>(result);\n\t\t\t\tGATS_CHECK( is<Integer>( v->value() ) );\n\t\t\t\tInteger::pointer_type i = convert<Integer>( v->value() );\n\t\t\t\tGATS_CHECK( i->value() == 4 );\n\t\t\t}\n\t\t#endif\n\t#endif  // TEST_INTEGER\n\n\t#if TEST_REAL\n\t\tGATS_TEST_CASE(test_multiply_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(3.0), make<Real>(4.0), make<Multiplication>() });\n\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"12.0\"));\n\t\t}\n\t\tGATS_TEST_CASE(test_divide_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"45.0\")), make<Real>(Real::value_type(\"3.0\")), make<Division>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"15.0\")));\n\t\t}\n\t\tGATS_TEST_CASE(test_addition_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"3.0\")), make<Real>(Real::value_type(\"4.0\")), make<Addition>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"7.0\")));\n\t\t}\n\t\tGATS_TEST_CASE(test_subtraction_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"3.0\")), make<Real>(Real::value_type(\"4.0\")), make<Subtraction>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"-1.0\")));\n\t\t}\n\t\tGATS_TEST_CASE(test_power_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"3.0\")), make<Real>(Real::value_type(\"4.0\")), make<Power>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"81\")));\n\t\t}\n\t#endif\t// TEST_REAL\n\n\t#if TEST_MIXED\n\t\tGATS_TEST_CASE(test_multiply_Integer_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(3), make<Real>(4.0), make<Multiplication>() });\n\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"12.0\"));\n\t\t}\n\t\tGATS_TEST_CASE(test_multiply_Real_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(3.0), make<Integer>(4), make<Multiplication>() });\n\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"12.0\"));\n\t\t}\n\t\tGATS_TEST_CASE(test_divide_Integer_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(3), make<Real>(6.0), make<Division>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"0.5\")));\n\t\t}\n\t\tGATS_TEST_CASE(test_divide_Real_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(3.0), make<Integer>(6), make<Division>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"0.5\")));\n\t\t}\n\t\tGATS_TEST_CASE(test_addition_Integer_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(3), make<Real>(Real::value_type(\"4.2\")), make<Addition>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"7.2\")));\n\t\t}\n\t\tGATS_TEST_CASE(test_addition_Real_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"3.3\")), make<Integer>(4), make<Addition>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"7.3\")));\n\t\t}\n\t\tGATS_TEST_CASE(test_subtraction_Integer_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(3), make<Real>(Real::value_type(\"0.5\")), make<Subtraction>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"2.5\")));\n\t\t}\n\t\tGATS_TEST_CASE(test_subtraction_Real_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"4.25\")), make<Integer>(4), make<Subtraction>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"0.25\")));\n\t\t}\n\t\tGATS_TEST_CASE(test_neg_power_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(2), make<Integer>(-4), make<Power>() });\n\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"1.0\") / Real::value_type(\"16.0\"));\n\t\t}\n\t\tGATS_TEST_CASE(test_power_Integer_Real) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(2), make<Real>(Real::value_type(\"3.0\")), make<Power>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"8.0\")));\n\t\t}\n\t\tGATS_TEST_CASE(test_power_Real_Integer) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"2.0\")), make<Integer>(3), make<Power>() });\n\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"8.0\")));\n\t\t}\n\n\t\t#if TEST_VARIABLE\n\t\t\tGATS_TEST_CASE( assignment_to_constant_fail ) {\n\t\t\t\ttry {\n\t\t\t\t\tauto t = RPNEvaluator().evaluate({ make<Pi>(), make<Integer>(4), make<Assignment>() });\n\t\t\t\t\tGATS_FAIL( \"Failed to throw an 'assignment to a non-variable' exception.\" );\n\t\t\t\t}\n\t\t\t\tcatch( std::exception const& ex ) {\n\t\t\t\t\tGATS_CHECK( std::string( ex.what() ) == std::string(\"Error: assignment to a non-variable.\") );\n\t\t\t\t}\n\t\t\t}\n\t\t#endif // TEST_VARIABLE\n\t#endif\t// TEST_MIXED\n\n\t#if TEST_BOOLEAN\n\t\tGATS_TEST_CASE(test_and) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<True>(), make<True>(), make<And>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<True>(), make<False>(), make<And>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<True>(), make<And>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<False>(), make<And>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t}\n\t\tGATS_TEST_CASE(test_nand) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<True>(), make<True>(), make<Nand>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\tresult = RPNEvaluator().evaluate({ make<True>(), make<False>(), make<Nand>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<True>(), make<Nand>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<False>(), make<Nand>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t}\n\t\tGATS_TEST_CASE(test_nor) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<True>(), make<True>(), make<Nor>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\tresult = RPNEvaluator().evaluate({ make<True>(), make<False>(), make<Nor>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<True>(), make<Nor>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<False>(), make<Nor>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t}\n\t\tGATS_TEST_CASE(test_or) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<True>(), make<True>(), make<Or>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<True>(), make<False>(), make<Or>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<True>(), make<Or>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<False>(), make<Or>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t}\n\t\tGATS_TEST_CASE(test_xor) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<True>(), make<True>(), make<Xor>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\tresult = RPNEvaluator().evaluate({ make<True>(), make<False>(), make<Xor>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<True>(), make<Xor>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<False>(), make<Xor>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t}\n\t\tGATS_TEST_CASE(test_equality_boolean) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<True>(), make<True>(), make<Equality>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<True>(), make<Equality>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t}\n\t\tGATS_TEST_CASE(test_inequality_boolean) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<True>(), make<True>(), make<Inequality>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) != true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<True>(), make<Inequality>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) != false);\n\t\t}\n\t\tGATS_TEST_CASE(test_greater_boolean) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<True>(), make<True>(), make<Greater>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) != true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<True>(), make<Greater>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t}\n\t\tGATS_TEST_CASE(test_greater_equal_boolean) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<True>(), make<True>(), make<GreaterEqual>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<True>(), make<GreaterEqual>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\tresult = RPNEvaluator().evaluate({ make<True>(), make<False>(), make<GreaterEqual>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t}\n\t\tGATS_TEST_CASE(test_less_boolean) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<True>(), make<True>(), make<Less>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<True>(), make<Less>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<True>(), make<False>(), make<Less>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t}\n\t\tGATS_TEST_CASE(test_less_equal_boolean) {\n\t\t\tauto result = RPNEvaluator().evaluate({ make<True>(), make<True>(), make<LessEqual>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<False>(), make<True>(), make<LessEqual>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\tresult = RPNEvaluator().evaluate({ make<True>(), make<False>(), make<LessEqual>() });\n\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t}\n\t\t#if TEST_INTEGER\n\t\t\t// Equality\n\t\t\tGATS_TEST_CASE(test_equality_integer) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Integer>(1), make<Equality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(0), make<Integer>(1), make<Equality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_inequality_integer) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Integer>(1), make<Inequality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) != true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(0), make<Integer>(1), make<Inequality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) != false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_greater_integer) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Integer>(1), make<Greater>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) != true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(0), make<Integer>(1), make<Greater>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_greater_equal_integer) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Integer>(1), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(0), make<Integer>(1), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(1), make<Integer>(0), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_less_integer) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Integer>(1), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(0), make<Integer>(1), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(1), make<Integer>(0), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_less_equal_integer) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Integer>(1), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(0), make<Integer>(1), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(1), make<Integer>(0), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t}\n\t\t#endif\n\t\t#if TEST_REAL\n\t\t\tGATS_TEST_CASE(test_equality_real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Real>(Real::value_type(\"1.0\")), make<Equality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.1\")), make<Real>(Real::value_type(\"1.0\")), make<Equality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_inequality_real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Real>(Real::value_type(\"1.0\")), make<Inequality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) != true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.1\")), make<Real>(Real::value_type(\"1.0\")), make<Inequality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) != false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_greater_real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Real>(Real::value_type(\"1.0\")), make<Greater>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) != true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.1\")), make<Real>(Real::value_type(\"1.0\")), make<Greater>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) != false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_greater_equal_real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Real>(Real::value_type(\"1.0\")), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"2.0\")), make<Real>(Real::value_type(\"1.0\")), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Real>(Real::value_type(\"2.0\")), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_less_real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Real>(Real::value_type(\"1.0\")), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.1\")), make<Real>(Real::value_type(\"1.0\")), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"0.1\")), make<Real>(Real::value_type(\"1.0\")), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_less_equal_real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Real>(Real::value_type(\"1.0\")), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"2.0\")), make<Real>(Real::value_type(\"1.0\")), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Real>(Real::value_type(\"2.0\")), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t}\n\t\t#endif\n\n\t\t#if TEST_MIXED\n\t\t\tGATS_TEST_CASE(test_equality_mixed) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Real>(Real::value_type(\"1.0\")), make<Equality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.1\")), make<Integer>(1), make<Equality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_inequality_mixed) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Real>(Real::value_type(\"1.0\")), make<Inequality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) != true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.1\")), make<Integer>(1), make<Inequality>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) != false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_greater_mixed) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Real>(Real::value_type(\"1.0\")), make<Greater>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) != true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.1\")), make<Integer>(1), make<Greater>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) != false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_greater_equal_mixed) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Integer>(1), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.1\")), make<Integer>(1), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Integer>(2), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(1), make<Real>(Real::value_type(\"1.0\")), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(2), make<Real>(Real::value_type(\"1.0\")), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(1), make<Real>(Real::value_type(\"2.0\")), make<GreaterEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_less_mixed) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Real>(Real::value_type(\"1.0\")), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(0), make<Real>(Real::value_type(\"1.0\")), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(2), make<Real>(Real::value_type(\"1.0\")), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Integer>(1), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.1\")), make<Integer>(1), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"0.1\")), make<Integer>(1), make<Less>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_less_equal_mixed) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Integer>(1), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.1\")), make<Integer>(1), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Integer>(2), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(1), make<Real>(Real::value_type(\"1.0\")), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(2), make<Real>(Real::value_type(\"1.0\")), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == false);\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Integer>(1), make<Real>(Real::value_type(\"2.0\")), make<LessEqual>() });\n\t\t\t\tGATS_CHECK(value_of<Boolean>(result) == true);\n\t\t\t}\n\t\t#endif\n\t#endif // TEST_BOOLEAN\n#endif // TEST_BINARY_OPERATOR\n\n\n#if TEST_FUNCTION\n\t#if TEST_SINGLE_ARG\n\t\t#if TEST_INTEGER\n\t\t\tGATS_TEST_CASE(test_abs_Integer) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(4), make<Abs>() });\n\t\t\t\tGATS_CHECK(value_of<Integer>(result) == 4);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_abs_Integer_neg) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(-4), make<Abs>() });\n\t\t\t\tGATS_CHECK(value_of<Integer>(result) == 4);\n\t\t\t}\n\t\t#endif\n\t\t#if TEST_REAL\n\t\t\tGATS_TEST_CASE(test_abs_Real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"4.0\")), make<Abs>() });\n\t\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"4.0\")));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_abs_Real_neg) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"-4.0\")), make<Abs>() });\n\t\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"4.0\")));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_acos_Real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Arccos>() });\n\t\t\t\tGATS_CHECK(round(result) == Real::value_type(\"0.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_asin_Real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Arcsin>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == boost::math::constants::half_pi<Real::value_type>());\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_atan_Real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"0.0\")), make<Arctan>() });\n\t\t\t\tGATS_CHECK(round(result) == Real::value_type(\"0.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_ceil_high_Real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"4.3\")), make<Ceil>() });\n\t\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"5.0\")));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_ceil_low_Real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"-4.3\")), make<Ceil>() });\n\t\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"-4.0\")));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_cos_Real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"0.0\")), make<Cos>() });\n\t\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"1.0\")));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_exp) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Exp>() });\n\t\t\t\tGATS_CHECK(round(result) == round(boost::math::constants::e<Real::value_type>()));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_floor_positive_Real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"4.3\")), make<Floor>() });\n\t\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"4.0\")));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_floor__negative_Real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"-4.3\")), make<Floor>() });\n\t\t\t\tGATS_CHECK(round(result) == round(Real::value_type(\"-5.0\")));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_lb) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"8.0\")), make<Lb>() });\n\t\t\t\tGATS_CHECK(round(value_of<Real>(result)) == round(Real::value_type(\"3.0\")));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_ln) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Ln>() });\n\t\t\t\tGATS_CHECK(round(value_of<Real>(result)) == boost::multiprecision::log(Real::value_type(\"1.0\")));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_sin) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"0.0\")), make<Sin>() });\n\t\t\t\tGATS_CHECK(round(value_of<Real>(result)) == Real::value_type(\"0.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_sqrt) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"16.0\")), make<Sqrt>() });\n\t\t\t\tGATS_CHECK(round(value_of<Real>(result)) == round(Real::value_type(\"4.0\")));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_tan) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Tan>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == tan(Real::value_type(\"1.0\")));\n\t\t\t}\n\t\t#endif\n\t#endif //TEST_SINGLE_ARG\n\t#if TEST_MULTI_ARG\n\t\t#if TEST_INTEGER\n\t\t\tGATS_TEST_CASE(test_max_int_int_rhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Integer>(2), make<Max>() });\n\t\t\t\tGATS_CHECK(value_of<Integer>(result) == 2);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_max_int_int_lhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(2), make<Integer>(1), make<Max>() });\n\t\t\t\tGATS_CHECK(value_of<Integer>(result) == 2);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_max_int_int_same) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(2), make<Integer>(2), make<Max>() });\n\t\t\t\tGATS_CHECK(value_of<Integer>(result) == 2);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_min_int_int_rhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(1), make<Integer>(2), make<Min>() });\n\t\t\t\tGATS_CHECK(value_of<Integer>(result) == 1);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_min_int_int_lhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(2), make<Integer>(1), make<Min>() });\n\t\t\t\tGATS_CHECK(value_of<Integer>(result) == 1);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_min_int_int_same) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(2), make<Integer>(2), make<Min>() });\n\t\t\t\tGATS_CHECK(value_of<Integer>(result) == 2);\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_pow_integer) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(2), make<Integer>(3), make<Pow>() });\n\t\t\t\tGATS_CHECK(value_of<Integer>(result) == Integer::value_type(8));\n\t\t\t}\n\t\t#endif // TEST_INTEGER\n\t\t#if TEST_REAL\n\t\t\tGATS_TEST_CASE(test_arctan2) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Real>(Real::value_type(\"2.0\")), make<Arctan2>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == atan2(Real::value_type(\"1.0\"), Real::value_type(\"2.0\")));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_max_real_real_rhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Real>(Real::value_type(\"2.0\")), make<Max>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"2.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_max_real_real_lhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"2.0\")), make<Real>(Real::value_type(\"1.0\")), make<Max>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"2.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_max_real_real_same) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"2.0\")), make<Real>(Real::value_type(\"2.0\")), make<Max>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"2.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_min_real_real_rhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Real>(Real::value_type(\"2.0\")), make<Min>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"1.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_min_real_real_lhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"2.0\")), make<Real>(Real::value_type(\"1.0\")), make<Min>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"1.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_min_real_real_same) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"2.0\")), make<Real>(Real::value_type(\"2.0\")), make<Min>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"2.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_pow_real) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"2.0\")), make<Real>(Real::value_type(\"3.0\")), make<Pow>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"8.0\"));\n\t\t\t}\n\t\t#endif // TEST_REAL\n\t\t#if TEST_MIXED\n\t\t\tGATS_TEST_CASE(test_max_real_int_rhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Integer>(2), make<Max>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"2.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_max_int_real_lhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(2), make<Real>(Real::value_type(\"1.0\")), make<Max>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"2.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_max_int_real_same) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"2.0\")), make<Integer>(2), make<Max>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"2.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_min_real_int_rhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"1.0\")), make<Integer>(2), make<Min>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"1.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_min_int_real_lhs) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(2), make<Real>(Real::value_type(\"1.0\")), make<Min>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"1.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_min_int_real_same) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"2.0\")), make<Integer>(2), make<Min>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"2.0\"));\n\t\t\t}\n\t\t\tGATS_TEST_CASE(test_pow_mixed) {\n\t\t\t\tauto result = RPNEvaluator().evaluate({ make<Integer>(2), make<Real>(Real::value_type(\"3.0\")), make<Pow>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"8.0\"));\n\t\t\t\tresult = RPNEvaluator().evaluate({ make<Real>(Real::value_type(\"2.0\")), make<Integer>(3), make<Pow>() });\n\t\t\t\tGATS_CHECK(value_of<Real>(result) == Real::value_type(\"8.0\"));\n\t\t\t}\n\t\t#endif // TEST_MIXED\n\t#endif // TEST_MULTI_ARG\n#endif // TEST_FUNCTION", "meta": {"hexsha": "8bf3f19092d5061a2a052e55a42b1a0e2994fa0e", "size": 36381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ee21/5. ut_rpn_evaluator/ut_rpn_evaluator.cpp", "max_stars_repo_name": "ygor-rezende/Expression-Evaluator", "max_stars_repo_head_hexsha": "52868ff11ce72a4ae6fa9a4052005c02f8485b3c", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ee21/5. ut_rpn_evaluator/ut_rpn_evaluator.cpp", "max_issues_repo_name": "ygor-rezende/Expression-Evaluator", "max_issues_repo_head_hexsha": "52868ff11ce72a4ae6fa9a4052005c02f8485b3c", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ee21/5. ut_rpn_evaluator/ut_rpn_evaluator.cpp", "max_forks_repo_name": "ygor-rezende/Expression-Evaluator", "max_forks_repo_head_hexsha": "52868ff11ce72a4ae6fa9a4052005c02f8485b3c", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1256476684, "max_line_length": 142, "alphanum_fraction": 0.6647150985, "num_tokens": 10043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.798186787341014, "lm_q1q2_score": 0.6268229332501304}}
{"text": "// math functions\n\n//local headers\n#include \"math.h\"\n\n//third party headers\n#include <boost/math/special_functions/binomial.hpp>\n\n//standard headers\n#include <cmath>\n#include <cstdint>\n\n\nstd::size_t bin_coeff_get_max_k(std::size_t size)\n{\n    // what is the largest value of (n/2) such that\n    // n choose (n/2) will fit in an integral T{} without overflow?\n\n    // note: results found by incrementing 'n' until failure\n    switch (size)\n    {\n        case 1:\n            return 10/2;\n        case 2:\n            return 18/2;\n        case 4:\n            return 34/2;\n        case 8:\n            return 67/2;\n        case 16:\n            return 131/2;\n        case 32:\n            return 260/2;\n        case 64:\n            return 516/2;\n        case 128:\n            return 1029/2;\n        break;\n    };\n\n    // unknown size, approximate the answer\n    return (10 * size);\n}\n\nstd::vector<std::uint16_t> get_primes_up_to(const std::uint16_t n)\n{\n    // Eratosthenes sieve\n    // get all primes in range [2, n]\n    // '1' and '0' not considered primes\n    std::vector<bool> sieve;\n    std::vector<std::uint16_t> result;\n    sieve.resize(n + 1, false);\n    result.reserve(n/2);\n \n    for (std::size_t i{2}; i <= n; ++i)\n    {\n        // If false, then it's a prime.\n        if (sieve[i] == false)\n        {\n            // Set all multiples of 'i' to true (i.e. non-prime)\n            if (i * i <= n)\n            {\n                for (std::size_t m{i * i}; m <= n; m += i)\n                    sieve[m] = true;\n            }\n\n            // save result\n            result.push_back(i);\n        }\n    }\n\n    return result;\n}\n\nstd::int32_t n_choose_k_bwrap(const std::uint32_t n, const std::uint32_t k)\n{\n    if (k > n)\n        return 0;\n\n    // note: result is 'double::max()' aka 'infinity' if any error occurs\n    using namespace boost::math::policies;\n    double fp_result = boost::math::binomial_coefficient<double>(n, k,\n      make_policy(overflow_error<ignore_error>(),\n        evaluation_error<ignore_error>(),\n        domain_error<ignore_error>(),\n        pole_error<ignore_error>()));\n\n    if (fp_result < 0 || fp_result == std::numeric_limits<double>::infinity())\n        return 0;\n\n    if (fp_result > std::numeric_limits<std::int32_t>::max())\n        return 0;\n\n    return std::round(fp_result);\n}\n\n", "meta": {"hexsha": "06ecda9274e0829d336a3db26adc51fe9349b27f", "size": 2307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sources/math.cpp", "max_stars_repo_name": "UkoeHB/bin-coeff-integral", "max_stars_repo_head_hexsha": "603683f60e22ac8f796df0e549b9fb96fe6d5d0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sources/math.cpp", "max_issues_repo_name": "UkoeHB/bin-coeff-integral", "max_issues_repo_head_hexsha": "603683f60e22ac8f796df0e549b9fb96fe6d5d0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/math.cpp", "max_forks_repo_name": "UkoeHB/bin-coeff-integral", "max_forks_repo_head_hexsha": "603683f60e22ac8f796df0e549b9fb96fe6d5d0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7835051546, "max_line_length": 78, "alphanum_fraction": 0.5509319463, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6268007766466825}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern uncertainty normal distribution\n#include <boost/test/unit_test.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include \"fern/language/uncertainty/normal_distribution.h\"\n\n\nBOOST_AUTO_TEST_CASE(constructor)\n{\n    fern::NormalDistribution<double> distribution(5.0, 2.5);\n\n    BOOST_CHECK_CLOSE(distribution.mean(), 5.0, 0.001);\n    BOOST_CHECK_CLOSE(distribution.standard_deviation(), 2.5, 0.001);\n\n    // boost::random::mt19937 random_number_generator;\n\n    // for(size_t i = 0; i < 1000; ++i) {\n    //     std::cout << i << \" \" << distribution(random_number_generator) << std::endl;\n    // }\n\n    // BOOST_CHECK(false);\n}\n", "meta": {"hexsha": "2c018f07a2a97be51edc863989c72a572e8bfbf9", "size": 1116, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/language/uncertainty/test/normal_distribution_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/language/uncertainty/test/normal_distribution_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/language/uncertainty/test/normal_distribution_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2, "max_line_length": 87, "alphanum_fraction": 0.6093189964, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6268007744402079}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2015 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_THOMAS_INVERSE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_THOMAS_INVERSE_HPP\n\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/core/radius.hpp>\n#include <boost/geometry/core/srs.hpp>\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/algorithms/detail/flattening.hpp>\n\n\nnamespace boost { namespace geometry { namespace detail\n{\n\n/*!\n\\brief The solution of the inverse problem of geodesics on latlong coordinates,\n       Forsyth-Andoyer-Lambert type approximation with second order terms.\n\\author See\n    - Technical Report: PAUL D. THOMAS, MATHEMATICAL MODELS FOR NAVIGATION SYSTEMS, 1965\n      http://www.dtic.mil/docs/citations/AD0627893\n    - Technical Report: PAUL D. THOMAS, SPHEROIDAL GEODESICS, REFERENCE SYSTEMS, AND LOCAL GEOMETRY, 1970\n      http://www.dtic.mil/docs/citations/AD703541\n*/\ntemplate <typename CT>\nclass thomas_inverse\n{\npublic:\n    template <typename T1, typename T2, typename Spheroid>\n    thomas_inverse(T1 const& lon1,\n                   T1 const& lat1,\n                   T2 const& lon2,\n                   T2 const& lat2,\n                   Spheroid const& spheroid)\n        : m_a(get_radius<0>(spheroid))\n        , m_f(detail::flattening<CT>(spheroid))\n        , m_is_result_zero(false)\n    {\n        // coordinates in radians\n\n        if ( math::equals(lon1, lon2)\n          && math::equals(lat1, lat2) )\n        {\n            m_is_result_zero = true;\n            return;\n        }\n\n        CT const one_minus_f = CT(1) - m_f;\n\n//        CT const tan_theta1 = one_minus_f * tan(lat1);\n//        CT const tan_theta2 = one_minus_f * tan(lat2);\n//        CT const theta1 = atan(tan_theta1);\n//        CT const theta2 = atan(tan_theta2);\n\n        CT const pi_half = math::pi<CT>() / CT(2);\n        CT const theta1 = math::equals(lat1, pi_half) ? lat1 :\n                          math::equals(lat1, -pi_half) ? lat1 :\n                          atan(one_minus_f * tan(lat1));\n        CT const theta2 = math::equals(lat2, pi_half) ? lat2 :\n                          math::equals(lat2, -pi_half) ? lat2 :\n                          atan(one_minus_f * tan(lat2));\n\n        CT const theta_m = (theta1 + theta2) / CT(2);\n        CT const d_theta_m = (theta2 - theta1) / CT(2);\n        m_d_lambda = lon2 - lon1;\n        CT const d_lambda_m = m_d_lambda / CT(2);\n\n        m_sin_theta_m = sin(theta_m);\n        m_cos_theta_m = cos(theta_m);\n        m_sin_d_theta_m = sin(d_theta_m);\n        m_cos_d_theta_m = cos(d_theta_m);\n        CT const sin2_theta_m = math::sqr(m_sin_theta_m);\n        CT const cos2_theta_m = math::sqr(m_cos_theta_m);\n        CT const sin2_d_theta_m = math::sqr(m_sin_d_theta_m);\n        CT const cos2_d_theta_m = math::sqr(m_cos_d_theta_m);\n        CT const sin_d_lambda_m = sin(d_lambda_m);\n        CT const sin2_d_lambda_m = math::sqr(sin_d_lambda_m);\n\n        CT const H = cos2_theta_m - sin2_d_theta_m;\n        CT const L = sin2_d_theta_m + H * sin2_d_lambda_m;\n        m_cos_d = CT(1) - CT(2) * L;\n        CT const d = acos(m_cos_d);\n        m_sin_d = sin(d);\n\n        CT const one_minus_L = CT(1) - L;\n\n        if ( math::equals(m_sin_d, CT(0))\n          || math::equals(L, CT(0))\n          || math::equals(one_minus_L, CT(0)) )\n        {\n            m_is_result_zero = true;\n            return;\n        }\n\n        CT const U = CT(2) * sin2_theta_m * cos2_d_theta_m / one_minus_L;\n        CT const V = CT(2) * sin2_d_theta_m * cos2_theta_m / L;\n        m_X = U + V;\n        m_Y = U - V;\n        m_T = d / m_sin_d;\n        //CT const D = CT(4) * math::sqr(T);\n        //CT const E = CT(2) * cos_d;\n        //CT const A = D * E;\n        //CT const B = CT(2) * D;\n        //CT const C = T - (A - E) / CT(2);\n    }\n\n    inline CT distance() const\n    {\n        if ( m_is_result_zero )\n        {\n            // TODO return some approximated value\n            return CT(0);\n        }\n\n        //CT const n1 = X * (A + C*X);\n        //CT const n2 = Y * (B + E*Y);\n        //CT const n3 = D*X*Y;\n\n        //CT const f_sqr = math::sqr(f);\n        //CT const f_sqr_per_64 = f_sqr / CT(64);\n\n        CT const delta1d = m_f * (m_T*m_X-m_Y) / CT(4);\n        //CT const delta2d = f_sqr_per_64 * (n1 - n2 + n3);\n\n        return m_a * m_sin_d * (m_T - delta1d);\n        //double S2 = a * sin_d * (T - delta1d + delta2d);\n    }\n\n    inline CT azimuth() const\n    {\n        // NOTE: if both cos_latX == 0 then below we'd have 0 * INF\n        // it's a situation when the endpoints are on the poles +-90 deg\n        // in this case the azimuth could either be 0 or +-pi\n        if ( m_is_result_zero )\n        {\n            return CT(0);\n        }\n\n        // may also be used to calculate distance21\n        //CT const D = CT(4) * math::sqr(T);\n        CT const E = CT(2) * m_cos_d;\n        //CT const A = D * E;\n        //CT const B = CT(2) * D;\n        // may also be used to calculate distance21\n        CT const f_sqr = math::sqr(m_f);\n        CT const f_sqr_per_64 = f_sqr / CT(64);\n\n        CT const F = CT(2)*m_Y-E*(CT(4)-m_X);\n        //CT const M = CT(32)*T-(CT(20)*T-A)*X-(B+CT(4))*Y;\n        CT const G = m_f*m_T/CT(2) + f_sqr_per_64;\n        CT const tan_d_lambda = tan(m_d_lambda);\n        CT const Q = -(F*G*tan_d_lambda) / CT(4);\n\n        CT const d_lambda_p = (m_d_lambda + Q) / CT(2);\n        CT const tan_d_lambda_p = tan(d_lambda_p);\n\n        CT const v = atan2(m_cos_d_theta_m, m_sin_theta_m * tan_d_lambda_p);\n        CT const u = atan2(-m_sin_d_theta_m, m_cos_theta_m * tan_d_lambda_p);\n\n        CT const pi = math::pi<CT>();\n        CT alpha1 = v + u;\n        if ( alpha1 > pi )\n        {\n            alpha1 -= CT(2) * pi;\n        }\n\n        return alpha1;\n    }\n\nprivate:\n    CT const m_a;\n    CT const m_f;\n\n    CT m_d_lambda;\n    CT m_cos_d;\n    CT m_sin_d;\n    CT m_X;\n    CT m_Y;\n    CT m_T;\n    CT m_sin_theta_m;\n    CT m_cos_theta_m;\n    CT m_sin_d_theta_m;\n    CT m_cos_d_theta_m;\n\n    bool m_is_result_zero;\n};\n\n}}} // namespace boost::geometry::detail\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_THOMAS_INVERSE_HPP\n", "meta": {"hexsha": "1027cd065c8cc831563f3e3ae46a4d2971cecf9c", "size": 6393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/algorithms/detail/thomas_inverse.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T05:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T05:02:05.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/algorithms/detail/thomas_inverse.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3party/boost/boost/geometry/algorithms/detail/thomas_inverse.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-09T21:21:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-09T21:21:09.000Z", "avg_line_length": 31.3382352941, "max_line_length": 105, "alphanum_fraction": 0.5779759112, "num_tokens": 1874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6268007668788055}}
{"text": "//<%\n//cfg['compiler_args'] = ['-std=c++11']\n//cfg['include_dirs'] = ['../eigen']\n//setup_pybind11(cfg)\n//%>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <Eigen/Dense>\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <numeric>\n\nconstexpr auto pi = 3.141592653589793;\n\ndouble log_marginal_probability_cpp(Eigen::VectorXd m, Eigen::MatrixXd S,\n    double r, double v, Eigen::MatrixXd X) {\n    \n    int N = X.rows();\n    int p = X.cols();\n    Eigen::VectorXd xsum = X.colwise().sum().transpose();\n\n    Eigen::MatrixXd Sprime = S + X.transpose() * X + r * N / (N + r) * (m * m.transpose()) - 1 / (N + r) \n    * (xsum * xsum.transpose()) - r / (N + r) * (m * xsum.transpose() + xsum * m.transpose());\n\n    double vprime = v + N;\n\n    std::vector<double> gamma1(p, 0);\n    std::vector<double> gamma2(p, 0);\n    for (int i = 0; i < p; ++i) {\n        gamma1[i] = lgamma((v - i) / 2);\n        gamma2[i] = lgamma((vprime - i) / 2);\n    }\n    double gamma3 = std::accumulate(gamma1.begin(), gamma1.end(), 0.0);\n\tdouble gamma4 = std::accumulate(gamma2.begin(), gamma2.end(), 0.0);\n\t\n\tdouble log_prob = -N * p / 2 * log(2 * pi) + p / 2 * log(r / (N + r)) + v / 2 * log(S.determinant()) - vprime / 2\n\t\t* log(Sprime.determinant()) + vprime * p / 2 * log(2) + gamma4 - v * p / 2 * log(2) - gamma3;\n\t\n\treturn log_prob;\n}\n\nPYBIND11_PLUGIN(log_marginal_prob) {\n    pybind11::module m(\"log_marginal_prob\", \"auto-compiled c++ extension\");\n    m.def(\"log_marginal_probability_cpp\", &log_marginal_probability_cpp);\n    return m.ptr();\n}", "meta": {"hexsha": "b21886ce2b64481fa109a9d16aa1e44505487f77", "size": 1552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bhclust/log_marginal_prob.cpp", "max_stars_repo_name": "ulandddda/Bayesian-Hierarchical-Clustering", "max_stars_repo_head_hexsha": "64a87340e63818fed9647fde53e898bb8f9192a1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bhclust/log_marginal_prob.cpp", "max_issues_repo_name": "ulandddda/Bayesian-Hierarchical-Clustering", "max_issues_repo_head_hexsha": "64a87340e63818fed9647fde53e898bb8f9192a1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bhclust/log_marginal_prob.cpp", "max_forks_repo_name": "ulandddda/Bayesian-Hierarchical-Clustering", "max_forks_repo_head_hexsha": "64a87340e63818fed9647fde53e898bb8f9192a1", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 114, "alphanum_fraction": 0.5966494845, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6268007560076914}}
{"text": "#include \"FKDerivative.h\"\n#include <Eigen/Dense>\n#include <totalmodel.h>\n#include <cmath>\n#include <cassert>\n#include <chrono>\n\nusing namespace Eigen;\n\nvoid AngleAxisToRotationMatrix_Derivative(const double* pose, double* dR_data, const int idj, const int numberColumns)\n{\n    Eigen::Map< Eigen::Matrix<double, 9, Eigen::Dynamic, Eigen::RowMajor> > dR(dR_data, 9, numberColumns);\n    std::fill(dR_data, dR_data + 9 * numberColumns, 0.0);\n    const double theta2 = pose[0] * pose[0] + pose[1] * pose[1] + pose[2] * pose[2];\n    if (theta2 > std::numeric_limits<double>::epsilon())\n    {\n        const double theta = sqrt(theta2);\n        const double s = sin(theta);\n        const double c = cos(theta);\n        const Eigen::Map< const Eigen::Matrix<double, 3, 1> > u(pose);\n        Eigen::VectorXd e(3);\n        e[0] = pose[0] / theta; e[1] = pose[1] / theta; e[2] = pose[2] / theta;\n\n        // dR / dtheta\n        Eigen::Matrix<double, 9, 1> dRdth(9, 1);\n        Eigen::Map< Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > dRdth_(dRdth.data());\n        // skew symmetric\n        dRdth_ << 0.0, -e[2], e[1],\n                  e[2], 0.0, -e[0],\n                  -e[1], e[0], 0.0;\n        // dRdth_ = dRdth_ * c - Matrix<double, 3, 3>::Identity() * s + s * e * e.transpose();\n        dRdth_ = - dRdth_ * c - Matrix<double, 3, 3>::Identity() * s + s * e * e.transpose();\n\n        // dR / de\n        Eigen::Matrix<double, 9, 3, RowMajor> dRde(9, 3);\n        // d(ee^T) / de\n        dRde <<\n            2 * e[0], 0., 0.,\n            e[1], e[0], 0.,\n            e[2], 0., e[0],\n            e[1], e[0], 0.,\n            0., 2 * e[1], 0.,\n            0., e[2], e[1],\n            e[2], 0., e[0],\n            0., e[2], e[1],\n            0., 0., 2 * e[2];\n        Eigen::Matrix<double, 9, 3, RowMajor> dexde(9, 3);\n        dexde <<\n            0, 0, 0,\n            0, 0, -1,\n            0, 1, 0,\n            0, 0, 1,\n            0, 0, 0,\n            -1, 0, 0,\n            0, -1, 0,\n            1, 0, 0,\n            0, 0, 0;\n        // dRde = dRde * (1. - c) + c * dexde;\n        dRde = dRde * (1. - c) - s * dexde;\n        Eigen::Matrix<double, Dynamic, Dynamic, RowMajor> dedu = Matrix<double, 3, 3>::Identity() / theta - u * u.transpose() / theta2 / theta;\n\n        dR.block(0, 3 * idj, 9, 3) = dRdth * e.transpose() + dRde * dedu;\n    }\n    else\n    {\n        dR(1, 3 * idj + 2) = 1;\n        dR(2, 3 * idj + 1) = -1;\n        dR(3, 3 * idj + 2) = -1;\n        dR(5, 3 * idj) = 1;\n        dR(6, 3 * idj + 1) = 1;\n        dR(7, 3 * idj) = -1;\n    }\n}\n\nvoid EulerAnglesToRotationMatrix_Derivative(const double* pose, double* dR_data, const int idj, const int numberColumns)\n{\n    const double degrees_to_radians = 3.14159265358979323846 / 180.0;\n    const double pitch(pose[0] * degrees_to_radians);\n    const double roll(pose[1] * degrees_to_radians);\n    const double yaw(pose[2] * degrees_to_radians);\n\n    const double c1 = cos(yaw);\n    const double s1 = sin(yaw);\n    const double c2 = cos(roll);\n    const double s2 = sin(roll);\n    const double c3 = cos(pitch);\n    const double s3 = sin(pitch);\n\n    Eigen::Matrix<double, 9, 3, Eigen::RowMajor> dRdp(9, 3);\n    // dRdp <<\n    //  -s1 * c2, -s2 * c1, 0.,\n    //  -c1 * c3 - s1 * s2 * s3, c1 * c2 * s3, s1 * s3 + c1 * s2 * c3,\n    //  c1 * s3 - s1 * s2 * c3, c1 * c2 * c3, s1 * c3 - c1 * s2 * s3,\n    //  c1 * c2, -s1 * s2, 0.,\n    //  -s1 * c3 + c1 * s2 * s3, s1 * c2 * s3, -c1 * s3 + s1 * s2 * c3,\n    //  s1 * s3 + c1 * s2 * c3, s1 * c2 * c3, -c1 * c3 - s1 * s2 * s3,\n    //  0, -c2, 0,\n    //  0, -s2 * s3, c2 * c3,\n    //  0, -s2 * c3, -c2 * s3;\n\n    dRdp <<\n        0.,                       -s2 * c1,      -s1 * c2,\n        s1 * s3 + c1 * s2 * c3,    c1 * c2 * s3, -c1 * c3 - s1 * s2 * s3,\n        s1 * c3 - c1 * s2 * s3,    c1 * c2 * c3, c1 * s3 - s1 * s2 * c3,\n        0.,                       -s1 * s2,      c1 * c2,\n        -c1 * s3 + s1 * s2 * c3,   s1 * c2 * s3, -s1 * c3 + c1 * s2 * s3,\n        -c1 * c3 - s1 * s2 * s3,   s1 * c2 * c3, s1 * s3 + c1 * s2 * c3,\n        0,                        -c2,           0,\n        c2 * c3,                  -s2 * s3,      0,\n        -c2 * s3,                 -s2 * c3,      0;\n\n    Eigen::Map< Eigen::Matrix<double, 9, Eigen::Dynamic, Eigen::RowMajor> > dR(dR_data, 9, numberColumns);\n    std::fill(dR_data, dR_data + 9 * numberColumns, 0.0);\n    dR.block(0, 3 * idj, 9, 3) = degrees_to_radians * dRdp;\n}\n\nvoid Product_Derivative(const double* const A_data, const double* const dA_data, const double* const B_data,\n                        const double* const dB_data, double* dAB_data, const int B_col)\n{\n    assert(dA_data != NULL || dB_data != NULL);\n    assert(B_col == 3 || B_col == 1);  // matrix multiplication or matrix-vector multiplication\n    if (dA_data != NULL && dB_data != NULL)\n    {\n        const Eigen::Map<const Eigen::Matrix<double, 9, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dA(dA_data);\n        if (B_col == 1)\n        {\n            // B_col == 1\n            // d(AB) = AdB + (dA)B\n            const Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > A(A_data);\n            const Eigen::Map<const Eigen::Matrix<double, 3, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dB(dB_data);\n            Eigen::Map< Eigen::Matrix<double, 3, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dAB(dAB_data);\n            for (int r = 0; r < 3; r++)\n            {\n                const int baseIndex = 3*r;\n                dAB.row(r) = A(r, 0) * dB.row(0) + A(r, 1) * dB.row(1) + A(r, 2) * dB.row(2) +\n                    B_data[0] * dA.row(baseIndex) + B_data[1] * dA.row(baseIndex + 1) + B_data[2] * dA.row(baseIndex + 2);\n            }\n        }\n        else\n        {\n            // B_col == 3\n            // d(AB) = AdB + (dA)B\n            const Eigen::Map<const Eigen::Matrix<double, 9, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dB(dB_data);\n            Eigen::Map< Eigen::Matrix<double, 9, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dAB(dAB_data);\n            for (int r = 0; r < 3; r++)\n            {\n                const int baseIndex = 3*r;\n                for (int c = 0; c < 3; c++)\n                {\n                    dAB.row(baseIndex + c) = A_data[baseIndex] * dB.row(c) + A_data[baseIndex+1] * dB.row(3 + c) + A_data[baseIndex+2] * dB.row(6 + c) +\n                        B_data[c] * dA.row(baseIndex) + B_data[3 + c] * dA.row(baseIndex + 1) + B_data[6 + c] * dA.row(baseIndex + 2);\n                }\n            }\n        }\n    }\n    else if (dA_data != NULL && dB_data == NULL)  // B is a constant matrix / vector, no derivative\n    {\n        const Eigen::Map<const Eigen::Matrix<double, 9, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dA(dA_data);\n        if (B_col == 1)\n        {\n            // d(AB) = AdB + (dA)B\n            Eigen::Map< Eigen::Matrix<double, 3, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dAB(dAB_data);\n            // // Matrix form (slower)\n            // for (int r = 0; r < 3; r++)\n            //     dABAux.row(r) = B * dA.block<3, TotalModel::NUM_JOINTS * 3>(r, 0);\n            // For loop form\n            for (int r = 0; r < 3; r++)\n            {\n                const int baseIndex = 3*r;\n                dAB.row(r) = B_data[0] * dA.row(baseIndex) + B_data[1] * dA.row(baseIndex + 1) + B_data[2] * dA.row(baseIndex + 2);\n            }\n        }\n        else\n        {\n            // B_col == 3\n            Eigen::Map< Eigen::Matrix<double, 9, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dAB(dAB_data);\n            for (int r = 0; r < 3; r++)\n                for (int c = 0; c < 3; c++)\n                    dAB.row(3 * r + c) = B_data[c] * dA.row(3 * r) + B_data[3 + c] * dA.row(3 * r + 1) + B_data[6 + c] * dA.row(3 * r + 2);  // d(AB) = AdB + (dA)B\n        }\n    }\n    else // A is a constant matrix, no derivative\n    {\n        const Eigen::Map<const Eigen::Matrix<double, 3, 3, Eigen::RowMajor> > A(A_data);\n        // dA_data == NULL && dB_data != NULL\n        if (B_col == 1)\n        {\n            const Eigen::Map<const Eigen::Matrix<double, 3, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dB(dB_data);\n            Eigen::Map< Eigen::Matrix<double, 3, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dAB(dAB_data);\n            dAB.setZero();\n            for (int r = 0; r < 3; r++)\n                dAB.row(r) = A(r, 0) * dB.row(0) + A(r, 1) * dB.row(1) + A(r, 2) * dB.row(2);\n        }\n        else\n        {\n            // B_col == 3\n            const Eigen::Map<const Eigen::Matrix<double, 9, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dB(dB_data);\n            Eigen::Map< Eigen::Matrix<double, 9, TotalModel::NUM_JOINTS * 3, Eigen::RowMajor> > dAB(dAB_data);\n            dAB.setZero();\n            for (int r = 0; r < 3; r++)\n                for (int c = 0; c < 3; c++)\n                    dAB.row(3 * r + c) = A(r, 0) * dB.row(0 + c) + A(r, 1) * dB.row(3 + c) + A(r, 2) * dB.row(6 + c);\n        }\n    }\n}\n\nvoid SparseProductDerivative(const double* const A_data, const double* const dA_data, const double* const B_data,\n                             const double* const dB_data, const int colIndex, const std::vector<int>& parentIndexes, double* dAB_data, const int numberColumns)\n{\n    // d(AB) = AdB + (dA)B\n    Eigen::Map< Eigen::Matrix<double, 9, Eigen::Dynamic, Eigen::RowMajor> > dAB(dAB_data, 9, numberColumns);\n\n    std::fill(dAB_data, dAB_data + 9 * numberColumns, 0.0);\n    // // Dense dAB (sparse dB) version\n    // const Eigen::Map<const Eigen::Matrix<double, 9, numberColumns, Eigen::RowMajor> > dA(dA_data);\n    // const Eigen::Map<const Eigen::Matrix<double, 9, numberColumns, Eigen::RowMajor> > dB(dB_data);\n    // dAB.row(baseIndex + c) = B_data[c] * dA.row(baseIndex) + B_data[3 + c] * dA.row(baseIndex + 1) + B_data[6 + c] * dA.row(baseIndex + 2);\n    // dAB.block<1,3>(baseIndex + c, 3*colIndex) += A_data[baseIndex] * dB.block<1,3>(c, 3*colIndex)\n    //                                            + A_data[baseIndex+1] * dB.block<1,3>(3+c, 3*colIndex)\n    //                                            + A_data[baseIndex+2] * dB.block<1,3>(6+c, 3*colIndex);\n    // Sparse sped up equivalent\n    const auto colOffset = 3*colIndex;\n    for (int r = 0; r < 3; r++)\n    {\n        const int baseIndex = 3*r;\n        for (int c = 0; c < 3; c++)\n        {\n            // AdB\n            for (int subIndex = 0; subIndex < 3; subIndex++)\n            {\n                const auto finalOffset = colOffset + subIndex;\n                dAB_data[numberColumns*(baseIndex + c) + finalOffset] +=\n                    A_data[baseIndex] * dB_data[numberColumns*c + finalOffset]\n                    + A_data[baseIndex+1] * dB_data[numberColumns*(3+c) + finalOffset]\n                    + A_data[baseIndex+2] * dB_data[numberColumns*(6+c) + finalOffset];\n            }\n            // // AdB - Slower equivalent\n            // dAB.block<1,3>(baseIndex + c, colOffset) += A_data[baseIndex] * dB.block<1,3>(c, colOffset)\n            //                                            + A_data[baseIndex+1] * dB.block<1,3>(3+c, colOffset)\n            //                                            + A_data[baseIndex+2] * dB.block<1,3>(6+c, colOffset);\n            // (dA)B\n            for (const auto& parentIndex : parentIndexes)\n            {\n                const auto parentOffset = 3*parentIndex;\n                for (int subIndex = 0; subIndex < 3; subIndex++)\n                {\n                    const auto finalOffset = parentOffset + subIndex;\n                    dAB_data[numberColumns*(baseIndex + c) + finalOffset] +=\n                        B_data[c] * dA_data[numberColumns*baseIndex + finalOffset]\n                        + B_data[3 + c] * dA_data[numberColumns*(baseIndex+1) + finalOffset]\n                        + B_data[6 + c] * dA_data[numberColumns*(baseIndex+2) + finalOffset];\n                }\n            }\n            // // (dA)B - Slower equivalent\n            // for (const auto& parentIndex : parentIndexes)\n            // {\n            //     const auto parentOffset = 3*parentIndex;\n            //     dAB.block<1,3>(baseIndex + c, parentOffset) += B_data[c] * dA.block<1,3>(baseIndex, parentOffset)\n            //                                                  + B_data[3 + c] * dA.block<1,3>(baseIndex+1, parentOffset)\n            //                                                  + B_data[6 + c] * dA.block<1,3>(baseIndex+2, parentOffset);\n            // }\n        }\n    }\n}\n\nvoid SparseProductDerivative(const double* const dA_data, const double* const B_data,\n                             const std::vector<int>& parentIndexes, double* dAB_data, const int numberColumns)\n{\n    // d(AB) = AdB + (dA)B\n    // Sparse for loop form\n    std::fill(dAB_data, dAB_data + 3 * numberColumns, 0.0);\n    for (int r = 0; r < 3; r++)\n    {\n        const int baseIndex = 3*r;\n        for (const auto& parentIndex : parentIndexes)\n        {\n            const auto parentOffset = 3*parentIndex;\n            for (int subIndex = 0; subIndex < 3; subIndex++)\n            {\n                const auto finalOffset = parentOffset + subIndex;\n                dAB_data[numberColumns*r + finalOffset] +=\n                    B_data[0] * dA_data[numberColumns*baseIndex + finalOffset]\n                    + B_data[1] * dA_data[numberColumns*(baseIndex+1) + finalOffset]\n                    + B_data[2] * dA_data[numberColumns*(baseIndex+2) + finalOffset];\n            }\n        }\n    }\n    // // Dense Matrix form (slower)\n    // Eigen::Map< Eigen::Matrix<double, 3, numberColumns, Eigen::RowMajor> > dAB(dAB_data);\n    // const Eigen::Map<const Eigen::Matrix<double, 9, numberColumns, Eigen::RowMajor> > dA(dA_data);\n    // for (int r = 0; r < 3; r++)\n    //     dABAux.row(r) = B * dA.block<3, numberColumns>(r, 0);\n    // // Dense for loop form\n    // for (int r = 0; r < 3; r++)\n    // {\n    //     const int baseIndex = 3*r;\n    //     dAB.row(r) = B_data[0] * dA.row(baseIndex) + B_data[1] * dA.row(baseIndex + 1) + B_data[2] * dA.row(baseIndex + 2);\n    // }\n}\n\nvoid SparseProductDerivativeConstA(const double* const A_data, const double* const dB_data,\n                             const std::vector<int>& parentIndexes, double* dAB_data, const int numberColumns)\n{\n\t// d(AB) = AdB (A is a constant.)\n    // Sparse for loop form\n    std::fill(dAB_data, dAB_data + 3 * numberColumns, 0.0);\n    for (int r = 0; r < 3; r++)\n    {\n\t\tfor (const auto& parentIndex : parentIndexes)\n\t    {\n\t    \tconst auto parentOffset = 3*parentIndex;\n\t    \tfor (int subIndex = 0; subIndex < 3; subIndex++)\n            {\n            \tconst auto finalOffset = parentOffset + subIndex;\n            \tdAB_data[numberColumns * r + finalOffset] = A_data[3 * r + 0] * dB_data[finalOffset] + A_data[3 * r + 1] * dB_data[finalOffset + numberColumns] +\n            \t\tA_data[3 * r + 2] * dB_data[finalOffset + numberColumns + numberColumns];\n            }\n\t\t}\n\t}\n}\n\nvoid SparseAdd(const double* const B_data, const std::vector<int>& parentIndexes, double* A_data, const int numberColumns)\n{\n    // d(AB) += d(AB)_parent\n    Eigen::Map< Eigen::Matrix<double, 3, Eigen::Dynamic, Eigen::RowMajor>> A(A_data, 3, numberColumns);\n    const Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic, Eigen::RowMajor>> B(B_data, 3, numberColumns);\n    // Sparse for loop\n    for (int r = 0; r < 3; r++)\n    {\n        for (const auto& parentIndex : parentIndexes)\n        {\n            const auto parentOffset = 3*parentIndex;\n            for (int subIndex = 0; subIndex < 3; subIndex++)\n            {\n                const auto finalOffset = parentOffset + subIndex;\n                A_data[numberColumns*r + finalOffset] += B_data[numberColumns*r + finalOffset];\n            }\n        }\n    }\n    // // Dense equivalent\n    // dMtdPIdj += dJdP.block<3, numberColumns>(3 * ipar, 0);\n    // A += B;\n}\n\nvoid SparseSubtract(const double* const B_data, const std::vector<int>& parentIndexes, double* A_data, const int numberColumns)\n{\n    // d(AB) += d(AB)_parent\n    Eigen::Map< Eigen::Matrix<double, 3, Eigen::Dynamic, Eigen::RowMajor>> A(A_data, 3, numberColumns);\n    const Eigen::Map<const Eigen::Matrix<double, 3, Eigen::Dynamic, Eigen::RowMajor>> B(B_data, 3, numberColumns);\n    // Sparse for loop\n    for (int r = 0; r < 3; r++)\n    {\n        for (const auto& parentIndex : parentIndexes)\n        {\n            const auto parentOffset = 3*parentIndex;\n            for (int subIndex = 0; subIndex < 3; subIndex++)\n            {\n                const auto finalOffset = parentOffset + subIndex;\n                A_data[numberColumns*r + finalOffset] -= B_data[numberColumns*r + finalOffset];\n            }\n        }\n    }\n    // // Dense equivalent\n    // dMtdPIdj -= dJdP.block<3, numberColumns>(3 * ipar, 0);\n    // A -= B;\n}\n\nvoid projection_Derivative(double* dPdI_data, const double* dJdI_data, const int ncol, double* XYZ, const double* pK_, int offsetP, int offsetJ, float weight)\n{\n\t// Dx/Dt = dx/dX * dX/dt + dx/dY * dY/dt + dx/dZ * dZ/dt\n\tconst double X = XYZ[0], Y = XYZ[1], Z = XYZ[2];\n\tdouble* P_row0 = dPdI_data + offsetP * ncol;\n\tdouble* P_row1 = dPdI_data + (offsetP + 1) * ncol;\n\tconst double* J_row0 = dJdI_data + offsetJ * ncol;\n\tconst double* J_row1 = dJdI_data + (offsetJ + 1) * ncol;\n\tconst double* J_row2 = dJdI_data + (offsetJ + 2) * ncol;\n\tfor (int i = 0; i < ncol; i++)\n\t\tP_row0[i] = weight * ( pK_[0] * J_row0[i] + pK_[1] * J_row1[i] - (pK_[0] * X + pK_[1] * Y) * J_row2[i] / Z ) / Z;\n\tfor (int i = 0; i < ncol; i++)\n\t\tP_row1[i] = weight * pK_[4] * ( J_row1[i] - Y / Z * J_row2[i] ) / Z;\n\t// equivalent to\n\t// dPdI.row(offsetP + 0) = weight * (pK_[0] / Z * dJdI.row(offsetJ + 0)\n\t// \t\t\t\t\t + pK_[1] / Z * dJdI.row(offsetJ + 1)\n\t// \t\t\t\t\t - (pK_[0] * X + pK_[1] * Y) / Z / Z * dJdI.row(offsetJ + 2));\n\t// dPdI.row(offsetP + 1) = weight * (pK_[4] / Z * dJdI.row(offsetJ + 1)\n\t// \t\t\t\t\t - pK_[4] * Y / Z / Z * dJdI.row(offsetJ + 2));\n}", "meta": {"hexsha": "21b49a633412a01954f55c670da047969c2baa92", "size": 17831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "visualization/FitAdam/src/FKDerivative.cpp", "max_stars_repo_name": "alvaro-budria/body2hands", "max_stars_repo_head_hexsha": "0eba438b4343604548120bdb03c7e1cb2b08bcd6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2021-05-14T02:55:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T01:51:12.000Z", "max_issues_repo_path": "visualization/FitAdam/src/FKDerivative.cpp", "max_issues_repo_name": "human2b/body2hands", "max_issues_repo_head_hexsha": "8ab4b206dc397c3b326f2b4ec9448c84ee8801fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-06-24T09:59:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-31T08:15:20.000Z", "max_forks_repo_path": "visualization/FitAdam/src/FKDerivative.cpp", "max_forks_repo_name": "human2b/body2hands", "max_forks_repo_head_hexsha": "8ab4b206dc397c3b326f2b4ec9448c84ee8801fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-05-17T03:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T02:30:44.000Z", "avg_line_length": 46.0749354005, "max_line_length": 163, "alphanum_fraction": 0.5117492008, "num_tokens": 5960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.6267359250212167}}
{"text": "// ===========================================================================\n// Imagine++ Libraries\n// Copyright (C) Imagine\n// For detailed information: http://imagine.enpc.fr/software\n// ===========================================================================\n\n#include \"Imagine/LinAlg/MyEigen.h\"\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n//Existe dans Eigen Blas\n//Experimental et pas de decomposition uplow='U' dans eigen et seulement pour les matrices def pos\n//info important car utilise dans Matrix.h\n\n// Cholesky decomposition (replaces xpotf2_)\ntemplate <typename T>\nvoid subCholeskyDecomposition(const char* job, int *n, T* a, int *info)\n{ \n    Map<Matrix<T, Dynamic, Dynamic> > AMap (a,*n,*n);\n    Eigen::LLT<Matrix<T, Dynamic, Dynamic> > llt (AMap);\n    AMap = (*job == 'L') ? llt.matrixLLT() : llt.matrixU();\n    *info = int(llt.info());\n};\n\nvoid choleskyDecomposition(const char* job, int *n, double* a, int *info) { subCholeskyDecomposition<double>(job, n, a, info); }\nvoid choleskyDecomposition(const char* job, int *n, float* a, int *info) { subCholeskyDecomposition<float>(job, n, a, info); }\n\n// Norms\ntemplate <typename T>\nT subMatrixNorm(char* norm, int *m, int *n, T *a, int *lda)\n{\n    Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > AMap (a,*m,*n,OuterStride<>(*lda)); \n\n    T to_return = 0;\n    switch (*norm)\n    {\n        case 'M':\n            to_return = AMap.template lpNorm<Infinity>();\n            break;\n        case ('1'):\n            to_return = (AMap.colwise().sum()).maxCoeff();\n            break;\n        case ('I'):\n            to_return = (AMap.rowwise().sum()).maxCoeff();\n            break;\n        case ('F'):\n            to_return = AMap.norm();\n            break;\n        default: assert(false);\n    }\n\n    return to_return;\n}\n\ndouble matrixNorm(char* norm, int *m, int *n, double *a, int *lda) { return subMatrixNorm<double>(norm, m, n, a, lda); }\nfloat matrixNorm(char* norm, int *m, int *n, float *a, int *lda) { return subMatrixNorm<float>(norm, m, n, a, lda); }\n\n// System solving by LU decomposition (replaces xgetrs_)\ntemplate <typename T>\nvoid subLUSystemSolve(int *n,T *a,int *ipiv, T *b,int *info) \n{\n  Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > AMap (a,*n,*n,OuterStride<>(*n));\n  Map<Matrix<T, Dynamic, 1>, 0, InnerStride<1> > BMap (b,*n);\n  Matrix<T, Dynamic, Dynamic> B = BMap;\n  T nb = B.norm();\n  // Eigen::FullPivLU<Matrix<T, Dynamic, Dynamic> > lu(AMap);\n\n  // BMap = lu.solve(B);\n  //  BMap = AMap.fullPivLu().solve(B);\n  BMap = AMap.colPivHouseholderQr().solve(B);\n\n  /* // test\n  std::cout << \"-- LU system solve : ||AX - B||_2 = \" << (AMap * BMap - B).norm() << std::endl;\n  std::cout << \"A \" << std::endl;\n  printM(a, *n, *n);\n  std::cout << \"solution\" << std::endl;\n  printV(b, *n);\n  std::cout << \"AB \" << std::endl;\n  T* c = new T[*n];\n  affinity(*n, *n, 1, a, b, 0, c, 'N');\n  printV(c, *n);\n  std::cout << \"-- LU system solve : ||AX - B||_2 = \" << (AMap * BMap - B).norm() << std::endl;\n  delete[] c;\n  */\n\n  *info = ((AMap * BMap - B).norm() <= nb * 1.0e-3f) ? 0 : 1;\n\n}\n\nvoid LUSystemSolve(int *n,double *a,int *ipiv,double *b,int *info) { subLUSystemSolve<double>(n, a, ipiv, b, info); }\nvoid LUSystemSolve(int *n,float *a,int *ipiv,float *b,int *info) { subLUSystemSolve<float>(n, a, ipiv, b, info); }\n\n// System solving by QR decomposition (replaces xgels_)\ntemplate <typename T>\nvoid subQRSystemSolve(int *m,int *n,T *a,T *b,int *info) \n{\n    Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > AMap (a, *m, *n, OuterStride<>(*m));\n    Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > BMap (b, std::max(*m,*n), 1, OuterStride<>(std::max(*m, *n)));\n    *info = 0;\n    Eigen::HouseholderQR<Matrix<T, Dynamic, Dynamic> > qr(AMap);\n    Matrix<T, Dynamic, Dynamic> x = qr.solve(BMap.block(0, 0, *m, 1));\n    if(*m <= *n) *info = 1 - (AMap * x).isApprox(BMap.block(0, 0, *m, 1));\n    BMap.block(0, 0, *n, 1) = x;\n}\n\nvoid QRSystemSolve(int *m, int *n, double *a, double *b, int *info) { subQRSystemSolve<double>(m, n, a, b, info); }\nvoid QRSystemSolve(int *m, int *n, float *a, float *b, int *info) { subQRSystemSolve<float>(m, n, a, b, info); }\n\n// QR factorization\ntemplate <typename T>\nvoid subQRFactorization(int *m,int *n,int *k,T *a,T *r,int *info)\n{\n    Map<Matrix<T, Dynamic, Dynamic> > AMap (a, *m, *k);\n    Map<Matrix<T, Dynamic, Dynamic> > RMap (r, *n, *k);\n    Eigen::HouseholderQR<Matrix<T, Dynamic, Dynamic> > qr(AMap);\n    Matrix<T, Dynamic, Dynamic> R1 = Matrix<T, Dynamic, Dynamic>::Zero(*m, *k);\n    R1= qr.matrixQR().template triangularView<Upper>();\n#ifdef _WIN32\n    for(int i=0; i<*n; i++)\n        for(int j=0; j<*k; j++)\n            RMap(i,j) = R1(i,j);\n#else\n    RMap= R1.block(0, 0, *n, *k);\n#endif\n    Matrix<T, Dynamic, Dynamic> q = qr.householderQ();\n    Matrix<T, Dynamic, Dynamic> original = q.block(0, 0, *m, *n) * RMap;\n    *info=AMap.isApprox(original);\n    if (*n == *k)\n#ifdef _WIN32\n    for(int i=0; i<*m; i++)\n        for(int j=0; j<*k; j++)\n            AMap(i,j) = q(i,j);\n#else\n        AMap=q.block(0, 0, *m, *k);\n#endif\n    else\n    {\n        Map<Matrix<T, Dynamic, Dynamic> > QMap (a, *m, *m);\n        QMap = q;\n    }\n}\n\nvoid QRFactorization(int *m, int *n, int *k, double *a, double *r, int *info) { subQRFactorization<double>(m, n, k, a, r, info); }\nvoid QRFactorization(int *m, int *n, int *k, float *a, float *r, int *info) { subQRFactorization<float>(m, n, k, a, r, info); }\n\n// Reciprocal condition number of triangular matrix\ntemplate <typename T>\nvoid subConditionNumber(int *n,T *a,int *lda,T *rcond,int *info)\n{\n    char x = '1';\n    T l = (matrixNorm(&x, n, n, a, lda)); \n    if (l != 0)\n    {\n        *rcond = 1 / l;\n        *info = 0;\n    }\n    else *info = 1;\n}\n\nvoid conditionNumber(int *n, double *a, int *lda, double *rcond, int *info) { subConditionNumber<double>(n, a, lda, rcond, info); }\nvoid conditionNumber(int *n, float *a, int *lda, float *rcond, int *info) { subConditionNumber<float>(n, a, lda, rcond, info); }\n", "meta": {"hexsha": "1316350daea08ec736d815e6a584337bfb7c76d4", "size": 5977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Imagine/LinAlg/src/MyEigen4.cpp", "max_stars_repo_name": "Ethiy/imagine-pp", "max_stars_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Imagine/LinAlg/src/MyEigen4.cpp", "max_issues_repo_name": "Ethiy/imagine-pp", "max_issues_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Imagine/LinAlg/src/MyEigen4.cpp", "max_forks_repo_name": "Ethiy/imagine-pp", "max_forks_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "max_forks_repo_licenses": ["BSD-3-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.6687116564, "max_line_length": 131, "alphanum_fraction": 0.5788857286, "num_tokens": 2018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182775, "lm_q2_score": 0.6992544335934765, "lm_q1q2_score": 0.626707754028921}}
{"text": "/*\r\n * sharpqballthread.cpp\r\n *\r\n * Created on: 27.12.2012\r\n * @author Ralph Schurade\r\n */\r\n\r\n#include \"sharpqballthread.h\"\r\n\r\n#include \"fmath.h\"\r\n#include \"../data/datasets/datasetdwi.h\"\r\n\r\n#include \"../gui/gl/glfunctions.h\"\r\n\r\n#include <qmath.h>\r\n\r\n#include <boost/math/special_functions/spherical_harmonic.hpp>\r\n\r\n#include \"math.h\"\r\n\r\nSharpQBallThread::SharpQBallThread( DatasetDWI* ds, int order, int id ) :\r\n    m_ds( ds ),\r\n    m_order( order ),\r\n    m_id( id )\r\n{\r\n}\r\n\r\nSharpQBallThread::~SharpQBallThread()\r\n{\r\n    m_qBallVector.clear();\r\n}\r\n\r\nQVector<ColumnVector> SharpQBallThread::getQBallVector()\r\n{\r\n    return m_qBallVector;\r\n}\r\n\r\nvoid SharpQBallThread::run()\r\n{\r\n    QVector<QVector3D> bvecs = m_ds->getBvecs();\r\n\r\n    Matrix gradients( bvecs.size(), 3 );\r\n    for ( int i = 0; i < bvecs.size(); ++i )\r\n    {\r\n        gradients( i + 1, 1 ) = bvecs.at( i ).x();\r\n        gradients( i + 1, 2 ) = bvecs.at( i ).y();\r\n        gradients( i + 1, 3 ) = bvecs.at( i ).z();\r\n    }\r\n\r\n    QVector<ColumnVector>* data = m_ds->getData();\r\n    QVector<float>* b0Data = m_ds->getB0Data();\r\n\r\n    m_qBallVector.clear();\r\n\r\n    // inverse direction matrix for calculation:\r\n    //const matrixT A( pseudoinverse (sh_base( gradients, order ) ) );\r\n    Matrix B = FMath::sh_base( gradients, m_order );\r\n    Matrix A = ( B.t() * B ).i() * B.t();\r\n\r\n    int numThreads = GLFunctions::idealThreadCount;\r\n\r\n    int chunkSize = data->size() / numThreads;\r\n\r\n    int begin = m_id * chunkSize;\r\n    int end = m_id * chunkSize + chunkSize;\r\n\r\n    if ( m_id == numThreads - 1 )\r\n    {\r\n        end = data->size();\r\n    }\r\n\r\n    // for all voxels:\r\n    for ( int i = begin; i < end; ++i )\r\n    {\r\n        ColumnVector voxel( data->at( i ) / b0Data->at( i ) );\r\n\r\n        // regularize data data:\r\n        regularize_sqball( 0.15, 0.15, voxel );\r\n        voxel = FMath::vlog( FMath::vlog( voxel ) * ( -1 ) );\r\n        ColumnVector coeff = A * voxel;\r\n\r\n        for ( int k( 2 ); k <= m_order; k += 2 )\r\n        {\r\n            double frt_val = 2.0 * M_PI * boost::math::legendre_p<double>( k, 0 );\r\n            double lbt_val = -k * ( k + 1 );\r\n\r\n            for ( int degree = -k; degree <= k; degree++ )\r\n            {\r\n                int l = k * ( k + 1 ) / 2 + degree + 1;\r\n                coeff( l ) *= frt_val * lbt_val;\r\n            }\r\n        }\r\n\r\n        if ( b0Data->at( i ) > 0.0 )\r\n        {\r\n            coeff( 1 ) = 1.0 / sqrt( 4. * M_PI );\r\n        }\r\n\r\n        m_qBallVector.push_back( coeff );\r\n    }\r\n}\r\n\r\nvoid SharpQBallThread::regularize_sqball( const double par_1, const double par_2, ColumnVector& data )\r\n{\r\n    for ( int i = 1; i <= data.Nrows(); ++i )\r\n    {\r\n        if ( data( i ) < 0 )\r\n        {\r\n            data( i ) = 0.5 * par_1;\r\n        }\r\n        else if ( data( i ) < par_1 )\r\n        {\r\n            data( i ) = 0.5 * par_1 + 0.5 * FMath::pow2( data( i ) ) / par_1;\r\n        }\r\n        else if ( data( i ) < 1.0 - par_2 )\r\n        {\r\n            // do nothing with data\r\n        }\r\n        else if ( data( i ) < 1.0 )\r\n        {\r\n            data( i ) = 1.0 - 0.5 * par_2 - 0.5 * FMath::pow2( 1.0 - data( i ) ) / par_2;\r\n        }\r\n        else\r\n        {\r\n            data( i ) = 1.0 - 0.5 * par_2;\r\n        }\r\n    }\r\n}\r\n", "meta": {"hexsha": "1dcf35ff6f10c3e3bc9946bd0a125700c322a074", "size": 3244, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algos/sharpqballthread.cpp", "max_stars_repo_name": "rdmenezes/fibernavigator2", "max_stars_repo_head_hexsha": "bbb8bc8ff16790580d5b03fce7e1fad45fae1b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algos/sharpqballthread.cpp", "max_issues_repo_name": "rdmenezes/fibernavigator2", "max_issues_repo_head_hexsha": "bbb8bc8ff16790580d5b03fce7e1fad45fae1b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algos/sharpqballthread.cpp", "max_forks_repo_name": "rdmenezes/fibernavigator2", "max_forks_repo_head_hexsha": "bbb8bc8ff16790580d5b03fce7e1fad45fae1b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1472868217, "max_line_length": 103, "alphanum_fraction": 0.4876695438, "num_tokens": 994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.6266792976077915}}
{"text": "#ifndef YASMIC_BGL_KCORE\n#define YASMIC_BGL_KCORE\n\n/**\n * @file bgl_kcore.hpp\n * Implement the O(m) algorithm for computing the core number\n * of vertices in the graph.\n *\n * The algorithm comes from:\n *\n * Vladimir Batagelj and Matjaz Zaversnik, \"An O(m) Algorithm for Cores \n * Decomposition of Networks.\"  Sept. 1 2002.\n */\n\n/*\n * David Gleich\n * Stanford University\n * 14 February 2006\n */\n\n#if _MSC_VER >= 1400\n\t// disable the warning for ifstream::read\n    #pragma warning( push )\n\t#pragma warning( disable : 4996 )\n#endif // _MSC_VER >= 1400\n\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/iterator/reverse_iterator.hpp>\n\nnamespace boost\n{\n\n\ttemplate <class Graph, class KCoreMap, class PositionMap>\n\tvoid core_numbers(const Graph& g, KCoreMap kcm, PositionMap pos)\n\t{\n\t\ttypedef typename graph_traits<Graph>::vertex_descriptor vertex;\n\t\ttypedef typename graph_traits<Graph>::degree_size_type size_type;\n\n\t\tBGL_FORALL_VERTICES_T(v,g,Graph)\n\t\t{\n\t\t\tkcm[v] = 0;\n\t\t}\n\n\t\t// compute the degree of all vertices\n\t\tBGL_FORALL_EDGES_T(e,g,Graph)\n\t\t{\n\t\t\t++kcm[source(e,g)];\n\t\t}\n\n\t\tsize_type max_deg = 0;\n\n\t\t// compute the maximum degree\n\t\tBGL_FORALL_VERTICES_T(v,g,Graph)\n\t\t{\n\t\t\tif (kcm[v] > max_deg)\n\t\t\t{\n\t\t\t\tmax_deg = kcm[v];\n\t\t\t}\n\t\t}\n\n\t\t// now we sort vertices into bins by their degree \n\t\t// (we buffer this vector by 2 extra spots to make\n\t\t// some of the computations easier.\n\t\t//   1.  because deg > 0, we need max_deg+1 to index w/ deg itself\n\t\t//   2.  because we want to make things really easy, we extend\n\t\t//       the array one past degree to make computing partial_sums\n\t\t//       trivial\n\t\tstd::vector<size_type> bin(max_deg+2);\n\n\t\t// compute the size of each bin\n\t\tBGL_FORALL_VERTICES_T(v,g,Graph)\n\t\t{\n\t\t\t++bin[kcm[v]];\n\t\t}\n\n\t\t// this loop sets bin[d] to the starting position of vertices\n\t\t// with degree d in the vert array\n\t\tsize_type cur_pos = 0;\n\t\tfor (size_type cur_deg = 0; cur_deg < max_deg+2; ++cur_deg)\n\t\t{\n\t\t\tsize_type tmp = bin[cur_deg];\n\t\t\tbin[cur_deg] = cur_pos;\n\t\t\tcur_pos += tmp;\n\t\t}\n\n\t\t// place the vertices\n\t\tstd::vector<vertex> vert(num_vertices(g));\n\n\t\tBGL_FORALL_VERTICES_T(v,g,Graph)\n\t\t{\n\t\t\tpos[v] = bin[kcm[v]];\n\t\t\tvert[pos[v]] = v;\n\n\t\t\t++bin[kcm[v]];\n\t\t}\n\n\t\t// we ``abused'' bin while placing the vertices, now, \n\t\t// we need to restore it\n\n\t\tstd::copy(boost::make_reverse_iterator(bin.end()-2),\n\t\t\tboost::make_reverse_iterator(bin.begin()+1), \n\t\t\tboost::make_reverse_iterator(bin.end()-1));\n\n\t\tfor (size_type i=0; i < num_vertices(g); ++i)\n\t\t{\n\t\t\tvertex v = vert[i];\n\n\t\t\t// we are now going to remove vertex v from the graph,\n\t\t\t// but only implicitly.  That is, we will decrement\n\t\t\t// the degree of each of the neighbors of v, and\n\t\t\t// adjust the sorting of the arrays appropriately.\n\n\t\t\tBGL_FORALL_ADJ_T(v,u,g,Graph)\n\t\t\t{\n\t\t\t\t// if kcm[u] > kcm[v], then u is still in the graph,\n\t\t\t\t// if kvm[u] = kcm[v], then we'll remove u soon, and\n\t\t\t\t// it's core number is the same as v.\n\t\t\t\t// if kvm[u] < kcm[v], we've already removed u.\n\t\t\t\tif (kcm[u] > kcm[v])\n\t\t\t\t{\n\t\t\t\t\tsize_type deg_u = kcm[u];\n\t\t\t\t\tsize_type pos_u = pos[u];\n\t\t\t\t\t\n\n\t\t\t\t\t// w is the first vertex with the same degree as u\n\t\t\t\t\t// (this is the resort operation!)\n\t\t\t\t\tsize_type pos_w = bin[deg_u];\n\t\t\t\t\tvertex w = vert[pos_w];\n\n\t\t\t\t\tif (u != w)\n\t\t\t\t\t{\n\t\t\t\t\t\t// swap u and w\n\t\t\t\t\t\tpos[u] = pos_w;\n\t\t\t\t\t\tpos[w] = pos_u;\n\t\t\t\t\t\tvert[pos_w] = u;\n\t\t\t\t\t\tvert[pos_u] = w;\n\t\t\t\t\t}\n\n\t\t\t\t\t// now, the vertices array is sorted assuming\n\t\t\t\t\t// we perform the following step\n\n\t\t\t\t\t// start the set of vertices with degree of u \n\t\t\t\t\t// one into the future (this now points at vertex \n\t\t\t\t\t// w which we swapped with u).\n\t\t\t\t\t++bin[deg_u];\n\n\t\t\t\t\t// we are removing v from the graph, so u's degree\n\t\t\t\t\t// decreases\n\t\t\t\t\t--kcm[u];\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n#if _MSC_VER >= 1400\n\t// disable the warning for ifstream::read\n    #pragma warning( pop )\n#endif // _MSC_VER >= 1400\n\n\n#endif // YASMIC_BGL_KCORE\n\n\n", "meta": {"hexsha": "3274b88e80edb0ffb45d937c1f93e850843ce1dc", "size": 3904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "2A/Graphes/TPs/matlab_bgl/libmbgl/yasmic/bgl_kcore.hpp", "max_stars_repo_name": "anajmedd/ENSEEIHT-Projects", "max_stars_repo_head_hexsha": "e4077fe8882ae35be52e53f29a3a988a0d6f83f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2016-07-25T00:48:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T09:19:03.000Z", "max_issues_repo_path": "2A/Graphes/TPs/matlab_bgl/libmbgl/yasmic/bgl_kcore.hpp", "max_issues_repo_name": "anajmedd/ENSEEIHT-Projects", "max_issues_repo_head_hexsha": "e4077fe8882ae35be52e53f29a3a988a0d6f83f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-09-17T19:40:46.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-07T06:49:02.000Z", "max_forks_repo_path": "2A/Graphes/TPs/matlab_bgl/libmbgl/yasmic/bgl_kcore.hpp", "max_forks_repo_name": "anajmedd/ENSEEIHT-Projects", "max_forks_repo_head_hexsha": "e4077fe8882ae35be52e53f29a3a988a0d6f83f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2016-07-21T09:13:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-13T14:11:37.000Z", "avg_line_length": 23.2380952381, "max_line_length": 72, "alphanum_fraction": 0.6375512295, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6266705861494141}}
{"text": "/* @copyright The code is licensed under the MIT License\n *            <https://opensource.org/licenses/MIT>,\n *            Copyright (c) 2020 Christian Eskil Vaugelade Berg\n * @author Christian Eskil Vaugelade Berg\n*/\n#pragma once\n\n#include <orient/axis.hpp>\n#include <orient/detail/axis_traits.hpp>\n\n#include <Eigen/Dense>\n\n#include <type_traits>\n#include <utility>\n\nnamespace orient {\n\n// \\brief Calculate angle axis from rotation matrix\n// \\param R Source rotation matrix\n// \\return The angle axis\ntemplate<typename Scalar>\nEigen::Matrix<Scalar,3,1> angleAxisFromRotationMatrix(Eigen::Matrix<Scalar,3,3> const& R);\n\n// \\brief Calculate angle axis with partial derivatives from rotation matrix\n// \\param R Source rotation matrix\n// \\return A pair containing first the angle axis then secondly the Jacobian matrix\ntemplate<typename Scalar>\nstd::pair<Eigen::Matrix<Scalar,3,1>, Eigen::Matrix<Scalar, 3, 9>> angleAxisFromRotationMatrixWD(Eigen::Matrix<Scalar,3,3> const& R);\n\n// \\brief Calculate quaternion from rotation matrix\n// \\param R Source rotation matrix\n// \\return The quaternion\ntemplate<typename Scalar>\nEigen::Matrix<Scalar,4,1> quaternionFromRotationMatrix(Eigen::Matrix<Scalar,3,3> const& R);\n\n// \\brief Calculate quaternion with partial derivatives from rotation matrix\n// \\param R Source rotation matrix\n// \\return A pair containing first the quaternion then secondly the Jacobian matrix\ntemplate<typename Scalar>\nstd::pair<Eigen::Matrix<Scalar,4,1>, Eigen::Matrix<Scalar, 4, 9>> quaternionFromRotationMatrixWD(Eigen::Matrix<Scalar,3,3> const& R);\n\n// \\brief Calculate Euler angles from rotation matrix and a rotation order\n//        The order of rotation is expressed in instrinsic rotations.\n//        For example, the angles associated to a rotation sequence\n//        Rz(yaw) * Ry(pitch) * Rx(roll) = R\n//        is retrieve with \n//        auto ypr = eulerFromRotationMatrix<Axis::z, Axis::y, Axis::x>(R)\n//        where the angles in ypr are in the same order as the axes,\n//        i.e. [yaw, pitch, roll] in this example\n// \\param R Source rotation matrix\n// \\template-params A1,A2,A3 the intrinsic rotation order\n// \\return A vector containing the angles in intrinsic order \ntemplate<Axis A1, Axis A2, Axis A3, typename Scalar, typename Dummy>\nEigen::Matrix<Scalar,3,1> eulerFromRotationMatrix(Eigen::Matrix<Scalar,3,3> const& R);\n\n// \\brief Calculate Euler angles and partial derivatives from rotation matrix and a rotation order\n//        See above for more detail\n// \\param R Source rotation matrix\n// \\template-params A1,A2,A3 The intrinsic rotation order\n// \\return A pair containg first a vector with angles in intrinsic order and secondly the Jacobian matrix\ntemplate<Axis A1, Axis A2, Axis A3, typename Scalar, typename Dummy>\nstd::pair<Eigen::Matrix<Scalar,3,1>, Eigen::Matrix<Scalar, 3, 9>> eulerFromRotationMatrixWD(Eigen::Matrix<Scalar,3,3> const& R);\n\n}\n\n#include <orient/impl/aa_quat_from_rotation_matrix.hpp>\n#include <orient/impl/euler_from_rotation_matrix.hpp>\n", "meta": {"hexsha": "9b91fbf276bfc613ede3f1256e4b64976720109c", "size": 3003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orient/from_rotation_matrix.hpp", "max_stars_repo_name": "Eskilade/orient", "max_stars_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T07:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T09:23:29.000Z", "max_issues_repo_path": "include/orient/from_rotation_matrix.hpp", "max_issues_repo_name": "Eskilade/orient", "max_issues_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T02:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T01:42:47.000Z", "max_forks_repo_path": "include/orient/from_rotation_matrix.hpp", "max_forks_repo_name": "Eskilade/orient", "max_forks_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T04:26:22.000Z", "avg_line_length": 44.1617647059, "max_line_length": 133, "alphanum_fraction": 0.7452547453, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6266705845551476}}
{"text": "/**\n *  @file eigen_map.cpp\n *  @author Maximilian Harr <maximilian.harr@daimler.com>\n *  @date 29.06.2017\n *\n *  @brief Eigen map 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 <iostream>  /* Header that defines the standard input/output stream objects */\n#include <cstdlib>  /* Header that defines several general purpose functions */\n#include <string>\n#include <Eigen/Dense>  /* template library for linear algebra http://eigen.tuxfamily.org */\n#include <math.h> /* Defines M_PI for pi value */\n#include <Eigen/Eigenvalues> \n#include <Eigen/Geometry>\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  /* Map array of doubles in Eigen::Matrix3d */\n  double array[9];\n  for(int i = 0; i < 9; ++i) array[i] = i;\n  Eigen::Map< Eigen::Matrix3d> residual_0 = Eigen::Map<Eigen::Matrix3d>(array);\n  Eigen::Map< Eigen::Matrix<double, 9, 1> > residual_1 = Eigen::Map< Eigen::Matrix<double, 9, 1> >(array);\n  std::cout << \"residual_0: \" << std::endl << residual_0 << std::endl;\n  std::cout << \"res 0+0: \" << std::endl << residual_0 + residual_0 << std::endl;\n  std::cout << \"residual_1: \" << std::endl << residual_1 << std::endl;\n\n\t/* Map Eigen::Matrix3d to array of doubles */\n\tdouble array2[9];\n\tEigen::Map<Matrix<double,3,3,RowMajor> >(array2,3,3) = residual_0;\n\tstd::cout << \"Array2:\" << std::endl;\t\n\tfor(int i = 0; i < 9; ++i){\n\t\tstd::cout << array2[i] << \" \";\n\t}\n\tstd::cout << std::endl;\n\n  /* Cast Eigen VectorXd to Matrix of float */\n  Eigen::Vector3d vector_0;\n  vector_0 << 0,1,2;\n  Eigen::Matrix<float, 3, 1> p_m = vector_0.template cast<float>();\n  std::cout << \"p_m: \" << std::endl << p_m << 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: <filename> [options] \\n\\n\"\n                << \"<desription> \\n\\n\"\n                << \"Options: \\n\"\n                << \" -h                    show this help message and exit \\n\"\n                << \" -p <PARAMETER>        <description> \\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": "d9480b31432ae3d977928a2c197c51f85259d7b7", "size": 3292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/cpp_libs/src/eigen_map.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_map.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_map.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": 27.8983050847, "max_line_length": 106, "alphanum_fraction": 0.5647023086, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6266705783294083}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra. Eigen itself is part of the KDE project.\n//\n// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"main.h\"\n#include <Eigen/QR>\n\ntemplate<typename MatrixType> void qr(const MatrixType& m)\n{\n  /* this test covers the following files:\n     QR.h\n  */\n  int rows = m.rows();\n  int cols = m.cols();\n\n  typedef typename MatrixType::Scalar Scalar;\n  typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, MatrixType::ColsAtCompileTime> SquareMatrixType;\n  typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> VectorType;\n\n  MatrixType a = MatrixType::Random(rows,cols);\n  QR<MatrixType> qrOfA(a);\n  VERIFY_IS_APPROX(a, qrOfA.matrixQ() * qrOfA.matrixR());\n  VERIFY_IS_NOT_APPROX(a+MatrixType::Identity(rows, cols), qrOfA.matrixQ() * qrOfA.matrixR());\n\n  #if 0 // eigenvalues module not yet ready\n  SquareMatrixType b = a.adjoint() * a;\n\n  // check tridiagonalization\n  Tridiagonalization<SquareMatrixType> tridiag(b);\n  VERIFY_IS_APPROX(b, tridiag.matrixQ() * tridiag.matrixT() * tridiag.matrixQ().adjoint());\n\n  // check hessenberg decomposition\n  HessenbergDecomposition<SquareMatrixType> hess(b);\n  VERIFY_IS_APPROX(b, hess.matrixQ() * hess.matrixH() * hess.matrixQ().adjoint());\n  VERIFY_IS_APPROX(tridiag.matrixT(), hess.matrixH());\n  b = SquareMatrixType::Random(cols,cols);\n  hess.compute(b);\n  VERIFY_IS_APPROX(b, hess.matrixQ() * hess.matrixH() * hess.matrixQ().adjoint());\n  #endif\n}\n\nvoid test_eigen2_qr()\n{\n  for(int i = 0; i < 1; i++) {\n    CALL_SUBTEST_1( qr(Matrix2f()) );\n    CALL_SUBTEST_2( qr(Matrix4d()) );\n    CALL_SUBTEST_3( qr(MatrixXf(12,8)) );\n    CALL_SUBTEST_4( qr(MatrixXcd(5,5)) );\n    CALL_SUBTEST_4( qr(MatrixXcd(7,3)) );\n  }\n\n#ifdef EIGEN_TEST_PART_5\n  // small isFullRank test\n  {\n    Matrix3d mat;\n    mat << 1, 45, 1, 2, 2, 2, 1, 2, 3;\n    VERIFY(mat.qr().isFullRank());\n    mat << 1, 1, 1, 2, 2, 2, 1, 2, 3;\n    //always returns true in eigen2support\n    //VERIFY(!mat.qr().isFullRank());\n  }\n\n#endif\n}\n", "meta": {"hexsha": "76977e4c1cf2c7606aefefd3bf1cc5b04407bca6", "size": 2236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/PEST++/src/libs/Eigen/test/eigen2/eigen2_qr.cpp", "max_stars_repo_name": "usgs/neversink_workflow", "max_stars_repo_head_hexsha": "acd61435b8553e38d4a903c8cd7a3afc612446f9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "SCA/eigen_332/test/eigen2/eigen2_qr.cpp", "max_issues_repo_name": "JooseRajamaeki/TVCG18", "max_issues_repo_head_hexsha": "ddc73f422c267b1c38ede3ba20046efff46a6d74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 113.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T20:31:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T15:29:20.000Z", "max_forks_repo_path": "SCA/eigen_332/test/eigen2/eigen2_qr.cpp", "max_forks_repo_name": "JooseRajamaeki/TVCG18", "max_forks_repo_head_hexsha": "ddc73f422c267b1c38ede3ba20046efff46a6d74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 31.9428571429, "max_line_length": 104, "alphanum_fraction": 0.6878354204, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6266705658779294}}
{"text": "/* Boost numeric test of the runge kutta steppers test file\n\n Copyright 2012 Karsten Ahnert\n Copyright 2012 Mario Mulansky\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n*/\n\n// disable checked iterator warning for msvc\n#include <boost/config.hpp>\n#ifdef BOOST_MSVC\n    #pragma warning(disable:4996)\n#endif\n\n#define BOOST_TEST_MODULE numeric_runge_kutta\n\n#include <iostream>\n#include <cmath>\n\n#include <boost/array.hpp>\n\n#include <boost/test/unit_test.hpp>\n\n#include <boost/mpl/vector.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\nnamespace mpl = boost::mpl;\n\ntypedef double value_type;\n\ntypedef boost::array< double , 2 > state_type;\n\n// harmonic oscillator, analytic solution x[0] = sin( t )\nstruct osc\n{\n    void operator()( const state_type &x , state_type &dxdt , const double t ) const\n    {\n        dxdt[0] = x[1];\n        dxdt[1] = -x[0];\n    }\n};\n\n/* reset dispatcher */\ntemplate< class StepperCategory >\nstruct resetter\n{\n    template< class Stepper >\n    static void reset( Stepper &stepper ) { }\n};\n\ntemplate< >\nstruct resetter< explicit_error_stepper_fsal_tag >\n{\n    template< class Stepper >\n    static void reset( Stepper &stepper ) \n    { stepper.reset(); }\n};\n\n\nBOOST_AUTO_TEST_SUITE( numeric_runge_kutta_test )\n\n\n/* generic test for all runge kutta steppers */\ntemplate< class Stepper >\nstruct perform_runge_kutta_test\n{\n    void operator()( void )\n    {\n   \n        Stepper stepper;\n        const int o = stepper.order()+1; //order of the error is order of approximation + 1\n\n        const state_type x0 = {{ 0.0 , 1.0 }};\n        state_type x1;\n        const double t = 0.0;\n        /* do a first step with dt=0.1 to get an estimate on the prefactor of the error dx = f * dt^(order+1) */\n        double dt = 0.5;\n        stepper.do_step( osc() , x0 , t , x1 , dt );\n        const double f = 2.0 * std::abs( sin(dt) - x1[0] ) / std::pow( dt , o ); // upper bound\n        \n        std::cout << o << \" , \" << f << std::endl;\n\n        /* as long as we have errors above machine precision */\n        while( f*std::pow( dt , o ) > 1E-16 )\n        {\n            // reset stepper which require resetting (fsal steppers)\n            resetter< typename Stepper::stepper_category >::reset( stepper );\n            \n            stepper.do_step( osc() , x0 , t , x1 , dt );\n            std::cout << \"Testing dt=\" << dt << std::endl;\n            BOOST_CHECK_LT( std::abs( sin(dt) - x1[0] ) , f*std::pow( dt , o ) );\n            dt *= 0.5;\n        }\n    }\n};\n\n\n/* generic error test for all runge kutta steppers */\ntemplate< class Stepper >\nstruct perform_runge_kutta_error_test\n{\n    void operator()( void )\n    {\n        Stepper stepper;\n        const int o = stepper.error_order()+1; //order of the error is order of approximation + 1\n\n        const state_type x0 = {{ 0.0 , 1.0 }};\n        state_type x1 , x_err;\n        const double t = 0.0;\n        /* do a first step with dt=0.1 to get an estimate on the prefactor of the error dx = f * dt^(order+1) */\n        double dt = 0.5;\n        stepper.do_step( osc() , x0 , t , x1 , dt , x_err );\n        const double f = 2.0 * std::abs( x_err[0] ) / std::pow( dt , o );\n\n        std::cout << o << \" , \" << f << \" , \" << x0[0] << std::endl;\n\n        /* as long as we have errors above machine precision */\n        while( f*std::pow( dt , o ) > 1E-16 )\n        {\n            // reset stepper which require resetting (fsal steppers)\n            resetter< typename Stepper::stepper_category >::reset( stepper );\n            \n            stepper.do_step( osc() , x0 , t , x1 , dt , x_err );\n            std::cout << \"Testing dt=\" << dt << \": \" << x_err[1] << std::endl;\n            BOOST_CHECK_SMALL( std::abs( x_err[0] ) , f*std::pow( dt , o ) );\n            dt *= 0.5;\n        }\n    }\n};\n\n\ntypedef mpl::vector<\n    euler< state_type > ,\n    modified_midpoint< state_type > ,\n    runge_kutta4< state_type > ,\n    runge_kutta4_classic< state_type > ,\n    runge_kutta_cash_karp54_classic< state_type > ,\n    runge_kutta_cash_karp54< state_type > ,\n    runge_kutta_dopri5< state_type > ,\n    runge_kutta_fehlberg78< state_type >\n    > runge_kutta_steppers;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( runge_kutta_test , Stepper, runge_kutta_steppers )\n{\n    perform_runge_kutta_test< Stepper > tester;\n    tester();\n}\n\n\ntypedef mpl::vector<\n    runge_kutta_cash_karp54_classic< state_type > ,\n    runge_kutta_cash_karp54< state_type > ,\n    runge_kutta_dopri5< state_type > ,\n    runge_kutta_fehlberg78< state_type >\n    > runge_kutta_error_steppers;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( runge_kutta_error_test , Stepper, runge_kutta_error_steppers )\n{\n    perform_runge_kutta_error_test< Stepper > tester;\n    tester();\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "f51a840e069b65601cb171d1c4c8238b808de16d", "size": 4857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/test/numeric/runge_kutta.cpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/test/numeric/runge_kutta.cpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/test/numeric/runge_kutta.cpp", "max_forks_repo_name": "473867143/Prometheus", "max_forks_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 28.7396449704, "max_line_length": 112, "alphanum_fraction": 0.6230183241, "num_tokens": 1359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6266705628407245}}
{"text": "/*This program uses Rcpp attributes to import pure C++ functions into R. The main\nfunction takes in an anrmadillo matrix(which has already had the anova\nfilter applied to it) and parses through its rows. NA values are skipped \nand non-NA values are stored in a vector of vectors called groups, depending\non their group membership. All the non-NA values are concatenated into a vector which\nis sorted in ascending order. Each non-NA value is assigned a rank, all the ranks\nare stored in another vector called rankvec. The ranks are used in the \ncalculation of the Kruskall Wallis h statistic to then calculate the p-value of \nthat specific row.*/\n\n/*The fuction group_size takes one input, a vector of strings called group. This\nvector is an ordered character vector indicating what \"group\" factor level a \nspecific data element belongs to. This function makes a copy of group, called temp.\nNext a unique function is applied to temp, exposing the levels of the factor. \nNext we iterate through temp and count how many elements belong to each level, \nthese counts are stored in gsize.*/\n\n/*The function calculate_kwh takes two inputs, a vector of ranks and a vector \nof the number of non-NA values per group.This function implements the \nmathematical formula for Kruskal Wallis test statistic. It returns a numeric \nvalue(p-value).*/\n\n/*The function compute_pvalue, simply takes in the Kruskall Wallis test statistic\nand computes a p-value.*/\n\n/*The main function is the kwh function, it takes two inputs, an armadillo \nmatrix and a vector of strings called \"group\". The vector \"group\" is fed to\nthe group_size function which will return a vector of group sizes. One row \nof the armadillo matrix is stored in a vector named \"cp\". We iterate over\n\"cp\" and collect all non-NA values and store them in a vector of vectors\ncalled \"groups\". We iterate over \"groups\" and take the size of each group \nand store it in a vector called \"nonmiss\".Next we concatenate all the \nvectors from \"groups\" into one large vector called \"cpy.\" Next we sort \n\"cpy\" by its indices and store the indices in the vector \"yvec.\" Then\nwe allocate a vector \"rankvec\", the same size as \"yvec\". We assing a rank\nto each of the elements of \"cpy\" and keep them in the same order as \"yvec\".\nWe then take \"rankvec\" and and un-concatenate the vector into three smaller\nvectors which are stored in \"ranks\" (the ranks of each group). Finally \"ranks\"\nis input into calculate_kwh and a p-value is returned for that specific row\nof the armadillo matrix. This process is repeated untill the last row of the \nmatrix is reached, all the p-values are stored in order in a list named\n\"final.\"  */\n\n#include <RcppArmadillo.h>\n#include <boost/math/distributions/chi_squared.hpp>\n// [[Rcpp::plugins(\"cpp11\")]]\n// [[Rcpp::depends(RcppArmadillo)]]\n// [[Rcpp::depends(BH)]]\nusing namespace Rcpp;\n\nstd::vector<int> gp_size(std::vector<std::string> group)\n{\n  std::vector<std::string> temp;\n  temp = group;\n  \n  //std::sort(temp.begin(),temp.end());\n  \n  temp.erase( std::unique( temp.begin(), temp.end() ), temp.end() );\n  int tempsize = 0;\n  \n  tempsize = temp.size();\n  \n  std::vector<int> gsize(tempsize);\n  \n  for(unsigned int i = 0;i<group.size();i++)\n  {\n    for(unsigned int k=0;k<temp.size();k++)\n    {\n      if(group[i]==temp[k])\n        gsize[k]++;\n    }\n  }\n  \n  return gsize;\n}\n\ndouble calculate_kwh(std::vector <std::vector <double> > ranks, std::vector <double> nonmiss_sizes)\n{\n  std::vector <double> rsums;\n  double tempsum = 0,temporary = 0;\n  double n = 0,summation = 0, result = 0; \n  \n  for(unsigned int i = 0;i<nonmiss_sizes.size();i++)\n  {\n    n = n + nonmiss_sizes[i];\n  }\n  \n  for(unsigned int i = 0,j=0;i<ranks.size();i++)\n  {\n    for(int k = 0;k<nonmiss_sizes[j];k++)\n    {\n      tempsum = tempsum + ranks[i][k];\n    }\n    \n    temporary = pow(tempsum,2)/ nonmiss_sizes[i];\n    rsums.push_back(temporary);\n    tempsum = 0;\n    temporary = 0;\n    j++;\n  }\n  \n  for(unsigned int i = 0;i<rsums.size();i++)\n  {\n    summation = summation + rsums[i];\n  }\n  \n  result = ((12/(n*(n+1)))*summation)- 3*(n+1);\n  \n  return result;\n}\n\ndouble compute_pvalue(double h,std::vector<double> nonmiss)\n{\n  double p = 0;\n  int df = 0; \n  df = nonmiss.size()-1;\n  \n  boost::math::chi_squared mydist(df);\n  p = boost::math::cdf(mydist, h);\n  \n  return 1 - p;\n}\n\n// [[Rcpp::export]]\nstd::list<double> kw_rcpp(arma::mat mtr,std::vector<std::string> group)\n{\n  std::vector<std::string> unique_groups = group; \n  std::sort(unique_groups.begin(),unique_groups.end());\n  unique_groups.erase( std::unique( unique_groups.begin(), unique_groups.end() ), unique_groups.end() );\n  \n  std::list<double> final;\n  std:: vector<double> cp(mtr.n_cols);\n  std::vector<std::vector<double> >groups;\n  \n  double tempnonmis = 0;\n  \n  std::vector<double> nonmiss;\n  std::vector<double> tmp;\n  \n  for(unsigned int i = 0; i <mtr.n_rows;i++)\n  {\n        cp = arma::conv_to< std::vector<double> >::from(mtr.row(i));\n        \n        for (unsigned int i = 0; i < unique_groups.size(); i++)\n        {\n          for (unsigned int k = 0; k < cp.size(); k++)\n          {\n            if (ISNAN(cp[k])){\n              continue;\n            }\n            else if(unique_groups[i] == group[k]) {\n              tmp.push_back(cp[k]);\n            }\n          }\n          \n          groups.push_back(tmp);\n          tmp.clear();\n        \n       }\n    \n            int all_na_count = 0;\n    \n            for (unsigned int i = 0; i < groups.size(); i++)\n            {\n              if(groups[i].size()==0)\n              {\n                all_na_count++;\n              }\n    \n             else\n             {\n               tempnonmis = groups[i].size();\n               nonmiss.push_back(tempnonmis);\n             }\n           }\n\n            if((groups.size()-all_na_count) < 2)\n            {\n              final.push_back(NA_REAL);\n              nonmiss.clear();\n              groups.clear();\n            }\n    \n          else\n            {\n              std::vector<double> cpy;\n      \n              for(unsigned int i = 0; i <groups.size();i++)\n              {\n                if(groups[i].size() == 0)\n                {\n                  continue;\n                }\n                \n                else\n                {\n                  cpy.insert(cpy.end(), groups[i].begin(), groups[i].end());\n                }\n              }\n      \n              std::vector <double> rankvec (cpy.size());\n              std::vector<double> yvec(cpy.size());\n              std::size_t n(0);\n      \n              std::generate(yvec.begin(), yvec.end(), [&]{ return n++; });\n              std::sort(yvec.begin(), yvec.end(), [&](int i1, int i2) {return cpy[i1] < cpy[i2]; } );\n      \n              for(unsigned int i = 0,j = 1;i<yvec.size();i++)\n              {\n                rankvec[yvec[i]]= j;\n                j++;\n              }\n      \n              double tempr = 0;\n              std::vector<double>tempvec;\n              std::vector<std::vector<double> > ranks;\n      \n                for (unsigned int i = 0, j = 0; i <nonmiss.size(); i++)\n                {\n                    for (unsigned int i = 0; i < nonmiss[j]; i++)\n                    {\n                      tempr = rankvec[i];\n                      tempvec.push_back(tempr);\n                    }\n        \n                  ranks.push_back(tempvec);\n                  rankvec.erase(rankvec.begin(),rankvec.begin()+nonmiss[j]);\n                  tempvec.clear();\n        \n                  j++;\n                }\n      \n                double h = 0, p = 0;\n      \n                h = calculate_kwh(ranks,nonmiss);\n                p = compute_pvalue(h,nonmiss);\n                \n                final.push_back(p);\n      \n                nonmiss.clear();\n                groups.clear();\n                ranks.clear();\n                rankvec.clear();\n                yvec.clear();\n                cpy.clear();\n            }\n      }\n  \n  return final;\n}\n", "meta": {"hexsha": "6611b115bd7ae199c43387342ad44846be4f5e57", "size": 7922, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kw_rcpp.cpp", "max_stars_repo_name": "stanfill/pmartR", "max_stars_repo_head_hexsha": "93281912a8291169b1b0bc06498c4d3b03c73c4f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-05-16T21:59:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T15:49:49.000Z", "max_issues_repo_path": "src/kw_rcpp.cpp", "max_issues_repo_name": "stanfill/pmartR", "max_issues_repo_head_hexsha": "93281912a8291169b1b0bc06498c4d3b03c73c4f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 26.0, "max_issues_repo_issues_event_min_datetime": "2019-05-16T16:23:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:34:13.000Z", "max_forks_repo_path": "src/kw_rcpp.cpp", "max_forks_repo_name": "stanfill/pmartR", "max_forks_repo_head_hexsha": "93281912a8291169b1b0bc06498c4d3b03c73c4f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-04-13T20:38:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-07T18:38:26.000Z", "avg_line_length": 31.561752988, "max_line_length": 104, "alphanum_fraction": 0.5637465287, "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6265989464158164}}
{"text": "/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <vector>\n#include <random>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/interpolators/cardinal_trigonometric.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\n\nusing std::sin;\nusing boost::math::constants::two_pi;\nusing boost::math::interpolators::cardinal_trigonometric;\n\ntemplate<class Real>\nvoid test_constant()\n{\n    Real t0 = 0;\n    Real h = 1;\n    for(size_t n = 1; n < 20; ++n)\n    {\n      Real c = 8;\n      std::vector<Real> v(n, c);\n      auto ct = cardinal_trigonometric<decltype(v)>(v, t0, h);\n      CHECK_ULP_CLOSE(c, ct(0.3), 3);\n      CHECK_ULP_CLOSE(c*h*n, ct.integrate(), 3);\n      CHECK_ULP_CLOSE(c*c*h*n, ct.squared_l2(), 3);\n      CHECK_MOLLIFIED_CLOSE(Real(0), ct.prime(0.8), 25*std::numeric_limits<Real>::epsilon());\n      CHECK_MOLLIFIED_CLOSE(Real(0), ct.double_prime(0.8), 25*std::numeric_limits<Real>::epsilon());\n    }\n}\n\ntemplate<class Real>\nvoid test_interpolation_condition()\n{\n  std::mt19937 gen(1234);\n  std::uniform_real_distribution<Real> dis(1, 10);\n\n  for(size_t n = 1; n < 20; ++n) {\n    Real t0 = dis(gen);\n    Real h = dis(gen);\n    std::vector<Real> v(n);\n    for (size_t i = 0; i < n; ++i) {\n      v[i] = dis(gen);\n    }\n    auto ct = cardinal_trigonometric<decltype(v)>(v, t0, h);\n    for (size_t i = 0; i < n; ++i) {\n      Real arg = t0 + i*h;\n      Real expected = v[i];\n      Real computed = ct(arg);\n      if(!CHECK_ULP_CLOSE(expected, computed, 5*n))\n      {\n        std::cerr << \"  Samples: \" << n << \"\\n\";\n      }\n    }\n  }\n\n}\n\n\n#ifdef BOOST_HAS_FLOAT128\nvoid test_constant_q()\n{\n    __float128 t0 = 0;\n    __float128 h = 1;\n    for(size_t n = 1; n < 20; ++n)\n    {\n      __float128 c = 8;\n      std::vector<__float128> v(n, c);\n      auto ct = cardinal_trigonometric<decltype(v)>(v, t0, h);\n      CHECK_ULP_CLOSE(boost::multiprecision::float128(c), boost::multiprecision::float128(ct(0.3)), 3);\n      CHECK_ULP_CLOSE(boost::multiprecision::float128(c*h*n), boost::multiprecision::float128(ct.integrate()), 3);\n    }\n}\n#endif\n\n\ntemplate<class Real>\nvoid test_sampled_sine()\n{\n    using std::sin;\n    using std::cos;\n    for (unsigned n = 15; n < 50; ++n)\n    {\n      Real t0 = 0;\n      Real T = 1;\n      Real h = T/n;\n      std::vector<Real> v(n);\n      auto s = [&](Real t) { return sin(two_pi<Real>()*(t-t0)/T);};\n      auto s_prime = [&](Real t) { return two_pi<Real>()*cos(two_pi<Real>()*(t-t0)/T)/T;};\n      auto s_double_prime = [&](Real t) { return -two_pi<Real>()*two_pi<Real>()*sin(two_pi<Real>()*(t-t0)/T)/(T*T);};\n      for(size_t j = 0; j < v.size(); ++j)\n      {\n          Real t = t0 + j*h;\n          v[j] = s(t);\n      }\n      auto ct = cardinal_trigonometric<decltype(v)>(v, t0, h);\n      CHECK_ULP_CLOSE(T, ct.period(), 3);\n      std::mt19937 gen(1234);\n      std::uniform_real_distribution<Real> dist(0, 500);\n\n      unsigned j = 0;\n      while (j++ < 50) {\n        Real arg = dist(gen);\n        Real expected = s(arg);\n        Real computed = ct(arg);\n        CHECK_MOLLIFIED_CLOSE(expected, computed, std::numeric_limits<Real>::epsilon()*4000);\n\n        expected = s_prime(arg);\n        computed = ct.prime(arg);\n        CHECK_MOLLIFIED_CLOSE(expected, computed, 18000*std::numeric_limits<Real>::epsilon());\n\n        expected = s_double_prime(arg);\n        computed = ct.double_prime(arg);\n        CHECK_MOLLIFIED_CLOSE(expected, computed, 100000*std::numeric_limits<Real>::epsilon());\n\n      }\n      CHECK_MOLLIFIED_CLOSE(Real(0), ct.integrate(), std::numeric_limits<Real>::epsilon());\n    }\n}\n\ntemplate<class Real>\nvoid test_bump()\n{\n  using std::exp;\n  using std::abs;\n  using std::sqrt;\n  using std::pow;\n  auto bump = [](Real x)->Real { if (abs(x) >= 1) { return Real(0); } return exp(-Real(1)/(Real(1)-x*x)); };\n  auto bump_prime = [](Real x)->Real {\n      if (abs(x) >= 1) { return Real(0); }\n\n      return -2*x*exp(-Real(1)/(Real(1)-x*x))/pow(1-x*x,2);\n  };\n\n  auto bump_double_prime = [](Real x)->Real {\n      if (abs(x) >= 1) { return Real(0); }\n\n      return (6*pow(x,4)-2)*exp(-Real(1)/(Real(1)-x*x))/pow(1-x*x,4);\n  };\n\n\n  Real t0 = -1;\n  size_t n = 4096;\n  Real h = Real(2)/Real(n);\n\n  std::vector<Real> v(n);\n  for(size_t i = 0; i < n; ++i)\n  {\n      Real t = t0 + i*h;\n      v[i] = bump(t);\n  }\n\n  auto ct = cardinal_trigonometric<decltype(v)>(v, t0, h);\n  std::mt19937 gen(323723);\n  std::uniform_real_distribution<long double> dis(-0.9, 0.9);\n\n  size_t i = 0;\n  while (i++ < 1000)\n  {\n      Real t = static_cast<Real>(dis(gen));\n      Real expected = bump(t);\n      Real computed = ct(t);\n      if(!CHECK_MOLLIFIED_CLOSE(expected, computed, 2*std::numeric_limits<Real>::epsilon())) {\n          std::cerr << \"  Problem occured at abscissa \" << t << \"\\n\";\n      }\n\n      expected = bump_prime(t);\n      computed = ct.prime(t);\n      if(!CHECK_MOLLIFIED_CLOSE(expected, computed, 4000*std::numeric_limits<Real>::epsilon())) {\n          std::cerr << \"  Problem occured at abscissa \" << t << \"\\n\";\n      }\n\n      expected = bump_double_prime(t);\n      computed = ct.double_prime(t);\n      if(!CHECK_MOLLIFIED_CLOSE(expected, computed, 4000*4000*std::numeric_limits<Real>::epsilon())) {\n          std::cerr << \"  Problem occured at abscissa \" << t << \"\\n\";\n      }\n\n\n  }\n\n  // Wolfram Alpha:\n  // NIntegrate[Exp[-1/(1-x*x)],{x,-1,1}]\n  CHECK_ULP_CLOSE(Real(0.443993816168079437823L), ct.integrate(), 3);\n\n  // NIntegrate[Exp[-2/(1-x*x)],{x,-1,1}]\n  CHECK_ULP_CLOSE(Real(0.1330861208449942715569473279553285713625791551628130055345002588895389L), ct.squared_l2(), 1);\n\n\n}\n\n\nint main()\n{\n\n#ifdef TEST1\n    test_constant<float>();\n    test_sampled_sine<float>();\n    test_bump<float>();\n    test_interpolation_condition<float>();\n#endif\n\n\n#ifdef TEST2\n    test_constant<double>();\n    test_sampled_sine<double>();\n    test_bump<double>();\n    test_interpolation_condition<double>();\n#endif\n\n#ifdef TEST3\n    test_constant<long double>();\n    test_sampled_sine<long double>();\n    test_bump<long double>();\n    test_interpolation_condition<long double>();\n#endif\n\n#ifdef TEST4\n#ifdef BOOST_HAS_FLOAT128\ntest_constant_q();\n#endif\n#endif\n\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "99db9cd40349edee55655f947fa06bd5e8e49ae5", "size": 6386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/cardinal_trigonometric_test.cpp", "max_stars_repo_name": "btzy/boost-1.72.0-mirror", "max_stars_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T03:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T03:04:05.000Z", "max_issues_repo_path": "libs/math/test/cardinal_trigonometric_test.cpp", "max_issues_repo_name": "btzy/boost-1.72.0-mirror", "max_issues_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/test/cardinal_trigonometric_test.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": 27.2905982906, "max_line_length": 119, "alphanum_fraction": 0.6074224867, "num_tokens": 1929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6265989446352507}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXf;\nusing Eigen::VectorXf;\n\nnamespace hyped {\nnamespace utils {\nnamespace math {\n\n/**\n * @brief    This class is for filtering the data from sensors to smoothen it.\n */\nclass KalmanMultivariate {\n public:\n  /**\n   * @brief    Construct a new Kalman object with respective dimensions (with control)\n   *\n   * @param[in] n                       state dimensionality\n   * @param[in] m                       measurement dimensionality\n   * @param[in] k                       control dimensionality (default 0)\n   */\n  KalmanMultivariate(unsigned int n, unsigned int m, unsigned int k = 0);\n\n  /**\n   * @brief    Set dynamics model matrices (without control)\n   *\n   * @param[in] A                       state transition matrix\n   * @param[in] Q                       process noise covariance\n   */\n  void setDynamicsModel(MatrixXf &A, MatrixXf &Q);\n\n  /**\n   * @brief    Set dynamics model matrices (with control)\n   *\n   * @param[in] A                       state transition matrix\n   * @param[in] B                       control matrix\n   * @param[in] Q                       process noise covariance\n   */\n  void setDynamicsModel(MatrixXf &A, MatrixXf &B, MatrixXf &Q);\n\n  /**\n   * @brief    Set measurement model matrices\n   *\n   * @param[in] H                       measurement matrix\n   * @param[in] R                       measurement noise covariance\n   */\n  void setMeasurementModel(MatrixXf &H, MatrixXf &R);\n\n  /**\n   * @brief    Set model matrices (without control)\n   *\n   * @param[in] A                       state transition matrix\n   * @param[in] Q                       process noise covariance\n   * @param[in] H                       measurement matrix\n   * @param[in] R                       measurement noise covariance\n   */\n  void setModels(MatrixXf &A, MatrixXf &Q, MatrixXf &H, MatrixXf &R);\n\n  /**\n   * @brief    Set model matrices (with control)\n   *\n   * @param[in] A                       state transition matrix\n   * @param[in] B                       control matrix\n   * @param[in] Q                       process noise covariance\n   * @param[in] H                       measurement matrix\n   * @param[in] R                       measurement noise covariance\n   */\n  void setModels(MatrixXf &A, MatrixXf &B, MatrixXf &Q, MatrixXf &H, MatrixXf &R);\n\n  /**\n   * @brief    Update state transition matrix\n   *\n   * @param[in] A                       state transition matrix\n   */\n  void updateA(MatrixXf &A);\n\n  /**\n   * @brief    Update measurement covariance matrix\n   *\n   * @param[in] R                       measurement covariance matrix\n   */\n  void updateR(MatrixXf &R);\n\n  /**\n   * @brief    Set initial beliefs\n   *\n   * @param[in] x0                      initial state belief\n   * @param[in] P0                      initial state covariance (uncertainty)\n   */\n  void setInitial(VectorXf &x0, MatrixXf &P0);\n\n  /**\n   * @brief    Filter measurement and update state belief with covariance (without control)\n   *\n   * @param[in] z                       measurement vector\n   */\n  void filter(VectorXf &z);\n\n  /**\n   * @brief    Filter measurement and update state belief with covariance (with control)\n   *\n   * @param[in] u                       control vector\n   * @param[in] z                       measurement vector\n   */\n  void filter(VectorXf &u, VectorXf &z);\n\n  /**\n   * @brief     Get the state estimate\n   *\n   * @return    Returns the current state estimate\n   */\n  VectorXf &getStateEstimate();\n\n  /**\n   * @brief     Get the state uncertainty\n   *\n   * @return    Returns the current state covariance\n   */\n  MatrixXf &getStateCovariance();\n\n private:\n  /* problem dimensions */\n  unsigned int n_;  // state dimension\n  unsigned int m_;  // measurement dimension\n  unsigned int k_;  // control dimension (0 if not set)\n\n  /* dynamics model matrices */\n  MatrixXf A_;  // state transition matrix: n x n\n  MatrixXf B_;  // control matrix: n x k\n  MatrixXf Q_;  // process noise covariance: n x n\n\n  /* measurement model matrices */\n  MatrixXf H_;  // measurement matrix: m x n\n  MatrixXf R_;  // measurement noise covariance: m x m\n\n  /* state estimates */\n  VectorXf x_;  // state vector: n x 1\n  MatrixXf P_;  // state covariance: n x n\n  MatrixXf I_;  // identity matrix: n x n\n\n  /**\n   * @brief    Predict state belief with covariance based on dynamics (without control)\n   */\n  void predict();\n\n  /**\n   * @brief    Predict state belief with covariance based on dynamics (with control)\n   *\n   * @param[in] u                       control vector\n   */\n  void predict(VectorXf &u);\n\n  /**\n   * @brief    Correct state belief with covariance based on measurement\n   *\n   * @param[in] z                       measurement vector\n   */\n  void correct(VectorXf &z);\n};\n}  // namespace math\n}  // namespace utils\n}  // namespace hyped\n", "meta": {"hexsha": "c1428930d993c412cb0dc971e1cd280ccd9e6d82", "size": 4834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/math/kalman_multivariate.hpp", "max_stars_repo_name": "Hyp-ed/hyped-2022", "max_stars_repo_head_hexsha": "9cac4632b660f569629cf0ad4048787f6017905d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T16:22:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T18:14:31.000Z", "max_issues_repo_path": "src/utils/math/kalman_multivariate.hpp", "max_issues_repo_name": "Hyp-ed/hyped-2022", "max_issues_repo_head_hexsha": "9cac4632b660f569629cf0ad4048787f6017905d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 91.0, "max_issues_repo_issues_event_min_datetime": "2021-07-29T18:21:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:44:55.000Z", "max_forks_repo_path": "src/utils/math/kalman_multivariate.hpp", "max_forks_repo_name": "Hyp-ed/hyped-2022", "max_forks_repo_head_hexsha": "9cac4632b660f569629cf0ad4048787f6017905d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.296969697, "max_line_length": 91, "alphanum_fraction": 0.5695076541, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.6265989349365456}}
{"text": "/*\n   Copyright (C) 2015-2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n#include <cmath>\n#include <gtest/gtest.h>\n#include <boost/math/differentiation/autodiff.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"ising/mp_wrapper.hpp\"\n#include \"ising/free_energy/common.hpp\"\n#include \"ising/free_energy/square.hpp\"\n\nusing namespace boost::multiprecision;\nusing namespace ising::free_energy;\n\nTEST(IsingFreeEnergy, SquareFinite0) {\n  typedef double real_t;\n  unsigned Lx = 4;\n  unsigned Ly = 4;\n  auto Jx = convert<real_t>(\"1.5\");\n  auto Jy = convert<real_t>(\"2.5\");\n  auto t = convert<real_t>(\"2\");\n  auto vars = boost::math::differentiation::make_ftuple<real_t, 2, 2>(1 / t, 0);\n  auto& beta = std::get<0>(vars);\n  auto& h = std::get<1>(vars);\n  auto fc = square::finite_count(Lx, Ly, Jx, Jy, beta, h);\n  auto ff = square::finite(Lx, Ly, Jx, Jy, beta);\n  double eps = 1e-12;\n  EXPECT_TRUE(abs(free_energy(fc, beta, h) - free_energy(ff, beta)) < eps);\n  EXPECT_TRUE(abs(energy(fc, beta, h) - energy(ff, beta)) < eps);\n  EXPECT_TRUE(abs(specific_heat(fc, beta, h) - specific_heat(ff, beta)) < eps);\n}\n\nTEST(IsingFreeEnergy, SquareFinite1) {\n  typedef mp_wrapper<cpp_dec_float_50> real_t;\n  unsigned Lx = 4;\n  unsigned Ly = 4;\n  auto Jx = convert<real_t>(\"1.5\");\n  auto Jy = convert<real_t>(\"2.5\");\n  auto t = convert<real_t>(\"2\");\n  auto vars = boost::math::differentiation::make_ftuple<real_t, 2, 2>(1 / t, 0);\n  auto& beta = std::get<0>(vars);\n  auto& h = std::get<1>(vars);\n  auto fc = square::finite_count(Lx, Ly, Jx, Jy, beta, h);\n  auto ff = square::finite(Lx, Ly, Jx, Jy, beta);\n  double eps = 1e-40;\n  EXPECT_TRUE(abs(free_energy(fc, beta, h) - free_energy(ff, beta)) < eps);\n  EXPECT_TRUE(abs(energy(fc, beta, h) - energy(ff, beta)) < eps);\n  EXPECT_TRUE(abs(specific_heat(fc, beta, h) - specific_heat(ff, beta)) < eps);\n}\n\nTEST(IsingFreeEnergy, SquareFinite2) {\n  typedef mp_wrapper<cpp_dec_float_100> real_t;\n  unsigned Lx = 4;\n  unsigned Ly = 4;\n  auto Jx = convert<real_t>(\"1.5\");\n  auto Jy = convert<real_t>(\"2.5\");\n  auto t = convert<real_t>(\"2\");\n  auto vars = boost::math::differentiation::make_ftuple<real_t, 2, 2>(1 / t, 0);\n  auto& beta = std::get<0>(vars);\n  auto& h = std::get<1>(vars);\n  auto fc = square::finite_count(Lx, Ly, Jx, Jy, beta, h);\n  auto ff = square::finite(Lx, Ly, Jx, Jy, beta);\n  double eps = 1e-80;\n  EXPECT_TRUE(abs(free_energy(fc, beta, h) - free_energy(ff, beta)) < eps);\n  EXPECT_TRUE(abs(energy(fc, beta, h) - energy(ff, beta)) < eps);\n  EXPECT_TRUE(abs(specific_heat(fc, beta, h) - specific_heat(ff, beta)) < eps);\n}\n", "meta": {"hexsha": "08d345f0713ef76d23019ee6f65385dc00e33661", "size": 3133, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ising/free_energy/square_finite_gt.cpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "ising/free_energy/square_finite_gt.cpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "ising/free_energy/square_finite_gt.cpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6790123457, "max_line_length": 80, "alphanum_fraction": 0.6811362911, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6265631943482028}}
{"text": "// Unit test for the isEqualDouble function in testing_functions.cpp\n// This function determines if two numbers are equal within some tolerance\n// This is important because there is inherent error in double precision numbers\n// COMPLETE. This function works as intended. 2021/11/14\n\n\n// Include headers\n#include <iostream>\n#include <Eigen/Dense>\n#include \"../main/fvm_1D_functions.h\" \n#include \"../main/testing_functions.h\" \n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n\n    // Print what we are doing\n    cout << \"------------------------------------- \" << \\\n    \"This is a test of the isEqualDouble function.\" << \\\n    \" -------------------------------------\" << endl;    \n\n    // Set a tolerance\n    double TOL = 1e-10;\n\n    // Set some arbitrary value\n    double val = 1.1;\n\n    // We can test 4 different modes of this function to determine how well it works\n\n    // First, we will test to make sure that val+0.1*TOL is considered equal since it will by definition be within the tolerance\n    bool higher_within_TOL = isEqualDouble(val, val + 0.1*TOL, TOL);   // This should result in 1\n    if (higher_within_TOL == 1) {  // \n        cout << \"Test of higher but within tolerance is a success.\" << endl;\n    } \n    else {\n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of higher but within tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    }\n\n    // Test to make sure that val+1.1*TOL is not considered equal since it will by definition be outside the tolerance\n    bool higher_over_TOL = isEqualDouble(val, val + 1.1*TOL, TOL);   // This should result in 0\n    if (higher_over_TOL == 0) {  // \n        cout << \"Test of higher over tolerance is a success.\" << endl;\n    } \n    else {        \n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of higher over tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    }   \n\n    // Test to make sure that val-0.1*TOL is considered equal since it will by definition be within the tolerance\n    bool lower_within_TOL = isEqualDouble(val, val - 0.1*TOL, TOL);   // This should result in 1\n    if (lower_within_TOL == 1) {  // \n        cout << \"Test of lower but within tolerance is a success.\" << endl;\n    } \n    else {\n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of lower but within tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    } \n\n    // Test to make sure that val-1.1*TOL is not considered equal since it will by definition be outside the tolerance\n    bool lower_less_TOL = isEqualDouble(val, val - 1.1*TOL, TOL);   // This should result in 0\n    if (lower_less_TOL == 0) {  // \n        cout << \"Test of lower but outside tolerance is a success.\" << endl;\n    } \n    else {\n        cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of lower but outside tolerance is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n    } \n\n    cout << endl << endl;\n}", "meta": {"hexsha": "831376ef274d4e118fb17516e8d972ca4749a4ba", "size": 3038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FVM_1D/unitTests/test_isEqualDouble.cpp", "max_stars_repo_name": "Aquadorf/computational-skolar", "max_stars_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FVM_1D/unitTests/test_isEqualDouble.cpp", "max_issues_repo_name": "Aquadorf/computational-skolar", "max_issues_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FVM_1D/unitTests/test_isEqualDouble.cpp", "max_forks_repo_name": "Aquadorf/computational-skolar", "max_forks_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9736842105, "max_line_length": 128, "alphanum_fraction": 0.555957867, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.6265631915358268}}
{"text": "// Component\n#include \"CloudTransformer.hpp\"\n#include \"RosConversionHelper.hpp\"\n\n// Libararies\n#include <Eigen/Dense>\n#include <pcl/filters/passthrough.h>\n\n// Standard\n#include <utility>\n\nnamespace cm\n{\n\nvoid CloudTransformer::transformCloud(pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud, const tf::StampedTransform& tf, const geometry_msgs::Quaternion& q)\n{\n    geometry_msgs::Quaternion q_;\n    tf::quaternionTFToMsg(tf.getRotation(), q_);\n    const Eigen::Matrix3d pc_rot_mat = RosConversionHelper::quaternionMsgToRotationMatrix(q_);\n\n    const Eigen::Matrix3d rot_mat = RosConversionHelper::quaternionMsgToRotationMatrixIgnoreYaw(q).inverse()*pc_rot_mat.inverse();\n    Eigen::Matrix4d hom_tf;\n    hom_tf << rot_mat (0, 0), rot_mat(0, 1), rot_mat(0, 2), 0.0,\n              rot_mat (1, 0), rot_mat(1, 1), rot_mat(1, 2), 0.0,\n              rot_mat (2, 0), rot_mat(2, 1), rot_mat(2, 2), 0.0,\n              rot_mat (3, 0), rot_mat(3, 1), rot_mat(3, 2), 1.0;\n\n    pcl::PointCloud<pcl::PointXYZ> transformed_cloud;\n    pcl::transformPointCloud(*cloud, transformed_cloud, hom_tf);\n    *cloud = std::move(transformed_cloud);\n}\n\nvoid CloudTransformer::trimCloud(pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud, const float64_t band_m)\n{\n    pcl::PassThrough<pcl::PointXYZ> pass;\n    pass.setInputCloud(cloud);\n    pass.setFilterFieldName(\"z\");\n    pass.setFilterLimits(-band_m/2.0, band_m/2.0);    \n    pcl::PointCloud<pcl::PointXYZ> filtered_cloud;\n    pass.filter(filtered_cloud);\n    *cloud = std::move(filtered_cloud);\n}\n\n} // namespace cm", "meta": {"hexsha": "8ac9e5c502aa8ab8563f246197fb7909e50b9d6e", "size": 1529, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/costmap/src/types/helper/CloudTransformer.cpp", "max_stars_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_stars_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "catkin_ws/src/costmap/src/types/helper/CloudTransformer.cpp", "max_issues_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_issues_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/costmap/src/types/helper/CloudTransformer.cpp", "max_forks_repo_name": "WPI-Capstone-Project-Team-1-2020/Capstone-Final-Mile", "max_forks_repo_head_hexsha": "60cf6be95305ec720f001bf18327ae881168443c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.75, "max_line_length": 149, "alphanum_fraction": 0.6978417266, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6265590382976363}}
{"text": "// Example of using the GeographicLib::NearestNeighbor class.  WARNING: this\r\n// creates a file, pointset.xml or pointset.txt, in the current directory.\r\n// Read lat/lon locations from locations.txt and lat/lon queries from\r\n// queries.txt.  For each query print to standard output: the index for the\r\n// closest location and the distance to it.  Print statistics to standard error\r\n// at the end.\r\n\r\n#include <iostream>\r\n#include <exception>\r\n#include <vector>\r\n#include <fstream>\r\n#include <string>\r\n\r\n#if !defined(GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION)\r\n#define GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION 0\r\n#endif\r\n\r\n#if GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION\r\n// If Boost serialization is available, use it.\r\n#include <boost/archive/xml_iarchive.hpp>\r\n#include <boost/archive/xml_oarchive.hpp>\r\n#endif\r\n\r\n#include <GeographicLib/NearestNeighbor.hpp>\r\n#include <GeographicLib/Geodesic.hpp>\r\n#include <GeographicLib/DMS.hpp>\r\n\r\nusing namespace std;\r\nusing namespace GeographicLib;\r\n\r\n// A structure to hold a geographic coordinate.\r\nstruct pos {\r\n  double _lat, _lon;\r\n  pos(double lat = 0, double lon = 0) : _lat(lat), _lon(lon) {}\r\n};\r\n\r\n// A class to compute the distance between 2 positions.\r\nclass DistanceCalculator {\r\nprivate:\r\n  Geodesic _geod;\r\npublic:\r\n  explicit DistanceCalculator(const Geodesic& geod) : _geod(geod) {}\r\n  double operator() (const pos& a, const pos& b) const {\r\n    double d;\r\n    _geod.Inverse(a._lat, a._lon, b._lat, b._lon, d);\r\n    if ( !(d >= 0) )\r\n      // Catch illegal positions which result in d = NaN\r\n      throw GeographicErr(\"distance doesn't satisfy d >= 0\");\r\n    return d;\r\n  }\r\n};\r\n\r\nint main() {\r\n  try {\r\n    // Read in locations\r\n    vector<pos> locs;\r\n    double lat, lon;\r\n    string sa, sb;\r\n    {\r\n      ifstream is(\"locations.txt\");\r\n      if (!is.good())\r\n        throw GeographicErr(\"locations.txt not readable\");\r\n      while (is >> sa >> sb) {\r\n        DMS::DecodeLatLon(sa, sb, lat, lon);\r\n        locs.push_back(pos(lat, lon));\r\n      }\r\n      if (locs.size() == 0)\r\n        throw GeographicErr(\"need at least one location\");\r\n    }\r\n\r\n    // Define a distance function object\r\n    DistanceCalculator distance(Geodesic::WGS84());\r\n\r\n    // Create NearestNeighbor object\r\n    NearestNeighbor<double, pos, DistanceCalculator> pointset;\r\n\r\n    {\r\n      // Used saved object if it is available\r\n#if GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION\r\n      ifstream is(\"pointset.xml\");\r\n      if (is.good()) {\r\n        boost::archive::xml_iarchive ia(is);\r\n        ia >> BOOST_SERIALIZATION_NVP(pointset);\r\n      }\r\n#else\r\n      ifstream is(\"pointset.txt\");\r\n      if (is.good())\r\n        is >> pointset;\r\n#endif\r\n    }\r\n    // Is the saved pointset up-to-date?\r\n    if (pointset.NumPoints() != int(locs.size())) {\r\n      // else initialize it\r\n      pointset.Initialize(locs, distance);\r\n      // and save it\r\n#if GEOGRAPHICLIB_HAVE_BOOST_SERIALIZATION\r\n      ofstream os(\"pointset.xml\");\r\n      if (!os.good())\r\n        throw GeographicErr(\"cannot write to pointset.xml\");\r\n      boost::archive::xml_oarchive oa(os);\r\n      oa << BOOST_SERIALIZATION_NVP(pointset);\r\n#else\r\n      ofstream os(\"pointset.txt\");\r\n      if (!os.good())\r\n        throw GeographicErr(\"cannot write to pointset.txt\");\r\n      os << pointset << \"\\n\";\r\n#endif\r\n    }\r\n\r\n    ifstream is(\"queries.txt\");\r\n    double d;\r\n    int count = 0;\r\n    vector<int> k;\r\n    while (is >> sa >> sb) {\r\n      ++count;\r\n      DMS::DecodeLatLon(sa, sb, lat, lon);\r\n      d = pointset.Search(locs, distance, pos(lat, lon), k);\r\n      if (k.size() != 1)\r\n          throw GeographicErr(\"unexpected number of results\");\r\n      cout << k[0] << \" \" << d << \"\\n\";\r\n    }\r\n    int setupcost, numsearches, searchcost, mincost, maxcost;\r\n    double mean, sd;\r\n    pointset.Statistics(setupcost, numsearches, searchcost,\r\n                        mincost, maxcost, mean, sd);\r\n    int\r\n      totcost = setupcost + searchcost,\r\n      exhaustivecost = count * pointset.NumPoints();\r\n    cerr\r\n      << \"Number of distance calculations = \" << totcost << \"\\n\"\r\n      << \"With an exhaustive search = \" << exhaustivecost << \"\\n\"\r\n      << \"Ratio = \" << double(totcost) / exhaustivecost << \"\\n\"\r\n      << \"Efficiency improvement = \"\r\n      << 100 * (1 - double(totcost) / exhaustivecost) << \"%\\n\";\r\n  }\r\n  catch (const exception& e) {\r\n    cerr << \"Caught exception: \" << e.what() << \"\\n\";\r\n    return 1;\r\n  }\r\n}\r\n", "meta": {"hexsha": "4ed02e3ad2148ce2b4c075cfeb06a40f4d8e08ba", "size": 4396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example-NearestNeighbor.cpp", "max_stars_repo_name": "uav4geo/GeographicLib", "max_stars_repo_head_hexsha": "4427486381b405a02127688f1e7257cf85be912b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/example-NearestNeighbor.cpp", "max_issues_repo_name": "uav4geo/GeographicLib", "max_issues_repo_head_hexsha": "4427486381b405a02127688f1e7257cf85be912b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example-NearestNeighbor.cpp", "max_forks_repo_name": "uav4geo/GeographicLib", "max_forks_repo_head_hexsha": "4427486381b405a02127688f1e7257cf85be912b", "max_forks_repo_licenses": ["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.1773049645, "max_line_length": 80, "alphanum_fraction": 0.6191992721, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6265590296949868}}
{"text": "/* test_gamma.cpp\r\n *\r\n * Copyright Steven Watanabe 2010\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/gamma_distribution.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/math/distributions/gamma.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::gamma_distribution<>\r\n#define BOOST_RANDOM_DISTRIBUTION_NAME gamma\r\n#define BOOST_MATH_DISTRIBUTION boost::math::gamma_distribution<>\r\n#define BOOST_RANDOM_ARG1_TYPE double\r\n#define BOOST_RANDOM_ARG1_NAME alpha\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\r\n#define BOOST_RANDOM_ARG2_TYPE double\r\n#define BOOST_RANDOM_ARG2_NAME beta\r\n#define BOOST_RANDOM_ARG2_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(n) boost::uniform_real<>(0.00001, n)\r\n\r\n#include \"test_real_distribution.ipp\"\r\n", "meta": {"hexsha": "0f542916f128793eb61780f96a72b28eed71c14a", "size": 996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_gamma.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/random/test/test_gamma.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/test/test_gamma.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 34.3448275862, "max_line_length": 76, "alphanum_fraction": 0.7881526104, "num_tokens": 239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6265590137533968}}
{"text": "/*\n * Copyright Andrey Semashev 2020\n *\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/*!\n * \\file bit_floor.hpp\n *\n * This header defines \\c bit_floor algorithm, which produces a nearest power of 2 integer\n * that is less or equal to the input integer.\n */\n\n#ifndef BOOST_BIT_OPS_POW2_BIT_FLOOR_HPP_INCLUDED_\n#define BOOST_BIT_OPS_POW2_BIT_FLOOR_HPP_INCLUDED_\n\n#include <limits>\n#include <boost/bit_ops/detail/config.hpp>\n#include <boost/bit_ops/detail/type_traits/enable_if.hpp>\n#include <boost/bit_ops/detail/type_traits/is_integral.hpp>\n#include <boost/bit_ops/detail/type_traits/is_unsigned.hpp>\n#include <boost/bit_ops/count/countl_zero.hpp>\n\nnamespace boost {\nnamespace bit_ops {\n\n/*!\n * \\brief Returns the nearest power of 2 integer that is less or equal to \\a value\n *\n * \\pre \\a value must not be zero\n */\ntemplate< typename T >\ninline typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,\n    T\n>::type bit_floor_nz(T value) BOOST_NOEXCEPT\n{\n    return static_cast< T >(1u) << ((std::numeric_limits< T >::digits - 1u) - bit_ops::countl_zero_nz(value));\n}\n\n//! Returns the nearest power of 2 integer that is less or equal to \\a value, or 0 if \\a value is zero\ntemplate< typename T >\ninline typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,\n    T\n>::type bit_floor(T value) BOOST_NOEXCEPT\n{\n    return value == 0u ? static_cast< T >(0u) : bit_ops::bit_floor_nz(value);\n}\n\n} // namespace bit_ops\n} // namespace boost\n\n#endif // BOOST_BIT_OPS_POW2_BIT_FLOOR_HPP_INCLUDED_\n", "meta": {"hexsha": "0dd4181d98948bf711ebbcedd72316d163b4f096", "size": 1744, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/bit_ops/pow2/bit_floor.hpp", "max_stars_repo_name": "Lastique/bit_ops", "max_stars_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "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/bit_ops/pow2/bit_floor.hpp", "max_issues_repo_name": "Lastique/bit_ops", "max_issues_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "max_issues_repo_licenses": ["BSL-1.0"], "max_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/bit_ops/pow2/bit_floor.hpp", "max_forks_repo_name": "Lastique/bit_ops", "max_forks_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "max_forks_repo_licenses": ["BSL-1.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.1428571429, "max_line_length": 110, "alphanum_fraction": 0.7350917431, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6265582785038402}}
{"text": "/*\n * File: trim_dht.hpp\n * Created Date: 2020-01-01\n * Author: Lei Pan\n * Contact: <panlei7@gmail.com>\n *\n * Last Modified: Wednesday January 1st 2020 11:27:12 am\n *\n * MIT License\n *\n * Copyright (c) 2020 Lei Pan\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the 'Software'), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * -----\n * HISTORY:\n * Date      \t By\tComments\n * ----------\t---\n * ----------------------------------------------------------\n */\n\n#ifndef DHT_TRIM_DHT_H_\n#define DHT_TRIM_DHT_H_\n\n#include \"dht.hpp\"\n#include <Eigen/Dense>\n\nclass TrimDHT : public DiscreteHankelTransform {\npublic:\n  TrimDHT(int order, int nr, double rmax, int nexp);\n  ~TrimDHT();\n\n  Eigen::VectorXd perform(const Eigen::Ref<const Eigen::VectorXd> &src);\n\n  Eigen::VectorXd r_sampling();\n  Eigen::VectorXd k_sampling();\n\n  int get_nr() const;\n\nprivate:\n  Eigen::MatrixXd shift_matrix_;\n  double rmax_extend_;\n};\n\n#endif", "meta": {"hexsha": "ac4e1bbb66bcc8c05336bd9f9ae1408708622917", "size": 1877, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/trim_dht.hpp", "max_stars_repo_name": "pan3rock/discrete-hankel-transform", "max_stars_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/trim_dht.hpp", "max_issues_repo_name": "pan3rock/discrete-hankel-transform", "max_issues_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/trim_dht.hpp", "max_forks_repo_name": "pan3rock/discrete-hankel-transform", "max_forks_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T09:56:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T09:56:44.000Z", "avg_line_length": 31.2833333333, "max_line_length": 80, "alphanum_fraction": 0.7037826319, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6265582582976231}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 2020 by the deal.II authors\n *\n * This file is part of the deal.II library.\n *\n * The deal.II library is free software; you can use it, redistribute\n * it, and/or modify it under the terms of the GNU Lesser General\n * Public License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * The full text of the license can be found in the file LICENSE.md at\n * the top level directory of deal.II.\n *\n * ---------------------------------------------------------------------\n *\n * Authors: Wolfgang Bangerth, 1999,\n *          Guido Kanschat, 2011\n *          Luca Heltai, 2021\n */\n#include \"stokes.h\"\n\n#include <deal.II/lac/linear_operator.h>\n#include <deal.II/lac/linear_operator_tools.h>\n#include <deal.II/lac/solver_gmres.h>\n\n#include <deal.II/numerics/error_estimator.h>\n\n\nusing namespace dealii;\n\nnamespace\n{\n  std::vector<std::string>\n  get_component_names(int dim)\n  {\n    std::vector<std::string> names(dim + 1, \"u\");\n    names[dim] = \"p\";\n    return names;\n  }\n} // namespace\n\ntemplate <int dim>\nStokes<dim>::Stokes()\n  : BaseBlockProblem<dim>(get_component_names(dim),\n                          \"Stokes<\" + std::to_string(dim) + \">\")\n  , velocity(0)\n  , pressure(dim)\n{\n  // Output the vector result.\n  this->add_data_vector.connect([&](auto &data_out) {\n    std::vector<DataComponentInterpretation::DataComponentInterpretation>\n      interpretation(dim + 1,\n                     DataComponentInterpretation::component_is_part_of_vector);\n\n    interpretation[dim] = DataComponentInterpretation::component_is_scalar;\n\n    data_out.add_data_vector(this->locally_relevant_block_solution,\n                             this->component_names,\n                             DataOut<dim>::type_dof_data,\n                             interpretation);\n  });\n}\n\n\n\ntemplate <int dim>\nvoid\nStokes<dim>::assemble_system_one_cell(\n  const typename DoFHandler<dim>::active_cell_iterator &cell,\n  ScratchData &                                         scratch,\n  CopyData &                                            copy)\n{\n  auto &cell_matrix = copy.matrices[0];\n  auto &cell_rhs    = copy.vectors[0];\n\n  cell->get_dof_indices(copy.local_dof_indices[0]);\n\n  const auto &fe_values = scratch.reinit(cell);\n  cell_matrix           = 0;\n  cell_rhs              = 0;\n\n  for (const unsigned int q_index : fe_values.quadrature_point_indices())\n    {\n      for (const unsigned int i : fe_values.dof_indices())\n        {\n          const auto eps_v = fe_values[velocity].symmetric_gradient(\n            i, q_index); // SymmetricTensor<2,dim>\n          const auto div_v =\n            fe_values[velocity].divergence(i, q_index);         // double\n          const auto q = fe_values[pressure].value(i, q_index); // double\n\n          for (const unsigned int j : fe_values.dof_indices())\n            {\n              const auto eps_u = fe_values[velocity].symmetric_gradient(\n                j, q_index); // SymmetricTensor<2,dim>\n              const auto div_u =\n                fe_values[velocity].divergence(j, q_index);         // double\n              const auto p = fe_values[pressure].value(j, q_index); // double\n\n              cell_matrix(i, j) +=\n                (scalar_product(eps_v, eps_u) - p * div_v - q * div_u) *\n                fe_values.JxW(q_index); // dx\n            }\n          for (const unsigned int i : fe_values.dof_indices())\n            {\n              const auto comp_i = this->fe->system_to_component_index(i).first;\n              cell_rhs(i) +=\n                (fe_values.shape_value(i, q_index) * // phi_i(x_q)\n                 this->forcing_term.value(fe_values.quadrature_point(q_index),\n                                          comp_i) * // f(x_q)\n                 fe_values.JxW(q_index));           // dx\n            }\n        }\n    }\n\n  if (cell->at_boundary())\n    //  for(const auto face: cell->face_indices())\n    for (unsigned int f = 0; f < GeometryInfo<dim>::faces_per_cell; ++f)\n      if (this->neumann_ids.find(cell->face(f)->boundary_id()) !=\n          this->neumann_ids.end())\n        {\n          auto &fe_face_values = scratch.reinit(cell, f);\n          for (const unsigned int q_index :\n               fe_face_values.quadrature_point_indices())\n            for (const unsigned int i : fe_face_values.dof_indices())\n              {\n                const auto comp_i =\n                  this->fe->system_to_component_index(i).first;\n                cell_rhs(i) +=\n                  fe_face_values.shape_value(i, q_index) *\n                  this->neumann_boundary_condition.value(\n                    fe_face_values.quadrature_point(q_index), comp_i) *\n                  fe_face_values.JxW(q_index);\n              }\n        }\n}\n\n\ntemplate <int dim>\nvoid\nStokes<dim>::solve()\n{\n  TimerOutput::Scope                timer_section(this->timer, \"solve\");\n  SolverGMRES<LA::MPI::BlockVector> solver(this->solver_control);\n\n\n  LA::MPI::PreconditionAMG amg;\n  amg.initialize(this->system_block_matrix.block(0, 0));\n\n\n  solver.solve(this->system_block_matrix,\n               this->block_solution,\n               this->system_block_rhs,\n               PreconditionIdentity());\n  this->constraints.distribute(this->block_solution);\n  this->locally_relevant_block_solution = this->block_solution;\n}\n\n\ntemplate <int dim>\nvoid\nStokes<dim>::estimate()\n{\n  TimerOutput::Scope timer_section(this->timer, \"estimate\");\n  if (this->estimator_type == \"kelly\")\n    {\n      std::map<types::boundary_id, const Function<dim> *> neumann;\n      for (const auto id : this->neumann_ids)\n        neumann[id] = &this->neumann_boundary_condition;\n\n      QGauss<dim - 1> face_quad(this->fe->degree + 1);\n      KellyErrorEstimator<dim>::estimate(*this->mapping,\n                                         this->dof_handler,\n                                         face_quad,\n                                         neumann,\n                                         this->locally_relevant_block_solution,\n                                         this->error_per_cell,\n                                         this->fe->component_mask(velocity));\n    }\n  else\n    {\n      AssertThrow(false, ExcNotImplemented());\n    }\n  auto global_estimator = this->error_per_cell.l2_norm();\n  this->error_table.add_extra_column(\"estimator\", [global_estimator]() {\n    return global_estimator;\n  });\n  this->error_table.error_from_exact(*this->mapping,\n                                     this->dof_handler,\n                                     this->locally_relevant_block_solution,\n                                     this->exact_solution);\n}\n\n\n\ntemplate class Stokes<1>;\ntemplate class Stokes<2>;\ntemplate class Stokes<3>;", "meta": {"hexsha": "df113fd7c3d80cd7375581748c4139e75908eb80", "size": 6768, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/stokes.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/stokes.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/stokes.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1818181818, "max_line_length": 79, "alphanum_fraction": 0.569001182, "num_tokens": 1505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.6265240760458282}}
{"text": "/*(utf8)\n * This is a slight tweek of the\n * 1\u20ac Filter, template-compliant version\n * by Jonathan Aceituno <join@oin.name>\n * omiting timestamps, alowing for interger input,\n * and giving independant access to the lowpass filter.\n *\n * For details, see http://www.lifl.fr/~casiez/1euro\n * * quote * \"Note that parameters fcmin and beta have clear\n * conceptual relationships: if high speed lag is a problem,\n * increase beta; if slow speed jitter is a problem, decrease\n * fcmin.\"\n*/\n\n#include \"filter_base.hpp\"\n\n#include <boost/math/constants/constants.hpp>\n\n#define INIT_FREQ 120.\n#define INIT_CUTOFF 1.\n#define INIT_MIN 1.\n#define INIT_BETA 1.\n\nusing namespace boost::math::constants;\n\nnamespace value_filters\n{\ntemplate <typename T = double>\nclass low_pass_filter\n{\npublic:\n  low_pass_filter(double _freq = INIT_FREQ, double _dcutoff = INIT_CUTOFF)\n      : hatxprev {0}, xprev {0}, alpha {0}, hadprev {false}\n  {\n    set_alpha(_freq, _dcutoff);\n  }\n\n  T operator()(T x)\n  {\n    T hatx {0};\n\n    if (hadprev)\n    {\n      hatx = alpha * x + (1 - alpha) * hatxprev;\n    }\n    else\n    {\n      hatx = x;\n      hadprev = true;\n    }\n\n    hatxprev = hatx;\n    xprev = x;\n    return hatx;\n  }\n\n  T xprev {};\n  bool hadprev {};\n  double dcutoff {}, freq {};\n\n  void set_alpha(double cutoff, double _freq)\n  {\n    dcutoff = cutoff;\n    freq = _freq;\n    compute_alpha();\n  }\n\n  void set_amount(double amt)\n  {\n    set_alpha(pow(1 / (1 + amt), 2), freq);\n  }\n\n  void update()\n  {\n    compute_alpha();\n  }\n\nprivate:\n  T hatxprev{}, alpha{};\n\n  void compute_alpha()\n  {\n    T tau = one_div_two_pi<double>() * (1. / dcutoff);\n    double te = 1. / freq;\n\n    alpha = 1. / (1. + tau / te);\n  }\n};\n\ntemplate <typename T = double>\nstruct one_euro_filter\n{\n  one_euro_filter(\n      double _freq = INIT_FREQ, double _mincutoff = INIT_MIN,\n      double _beta = INIT_BETA, double _dcutoff = INIT_CUTOFF)\n      : freq {_freq}, beta {_beta}, dcutoff {_dcutoff}, mincutoff {_mincutoff}\n  {\n  }\n\n  T operator()(T x)\n  {\n    T dx {0};\n\n    if (xfilt_.hadprev)\n      dx = (x - xfilt_.xprev) * freq;\n\n    dxfilt_.set_alpha(dcutoff, freq);\n    T edx = dxfilt_(dx);\n    T cutoff = mincutoff + beta * std::abs(static_cast<double>(edx));\n\n    xfilt_.set_alpha(cutoff, freq);\n    return xfilt_(x);\n  }\n\n  double freq {}, beta {}, dcutoff {};\n\n  void set_amount(double amt)\n  {\n    if (amt <= 0.) amt = 0.0001;\n    // mincutoff is basicly the inverse of the amount of filtering\n    mincutoff = SCALED_AMOUNT - amt;\n  }\n\n  void update()\n  {\n  }\nprivate:\n  double mincutoff {};\n\n  low_pass_filter<T> xfilt_ {}, dxfilt_ {};\n};\n\n}\n", "meta": {"hexsha": "a8f74844e2443abe544ddd41ce036062edcbe351", "size": 2597, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/1efilter.hpp", "max_stars_repo_name": "jcelerier/dno", "max_stars_repo_head_hexsha": "18a823daed9904478802951f0a2e1141cf55bedb", "max_stars_repo_licenses": ["MIT"], "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/1efilter.hpp", "max_issues_repo_name": "jcelerier/dno", "max_issues_repo_head_hexsha": "18a823daed9904478802951f0a2e1141cf55bedb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/1efilter.hpp", "max_forks_repo_name": "jcelerier/dno", "max_forks_repo_head_hexsha": "18a823daed9904478802951f0a2e1141cf55bedb", "max_forks_repo_licenses": ["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.3805970149, "max_line_length": 78, "alphanum_fraction": 0.6261070466, "num_tokens": 772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.626524076045828}}
{"text": "#include \"gtest/gtest.h\"\n\n#include <sstream>\n#include <boost/scoped_ptr.hpp>\n\n#include \"wali/domains/matrix/Matrix.hpp\"\n\n#include \"fixtures-boolmatrix.hpp\"\n#include \"matrix-equal.hpp\"\n\nusing namespace testing::boolmatrix;\n\nnamespace wali {\nnamespace domains {\n\nTEST(wali$domains$matrix$BoolMatrix$$constructorAndMatrix, basicTest3x3)\n{\n    RandomMatrix1_3x3 f;\n    BoolMatrix m(f.mat);\n\n    EXPECT_EQ(m.matrix(), f.mat);\n}\n\n\n#define NUM_ELEMENTS(arr) ((sizeof arr)/(sizeof arr[0]))\n\nTEST(wali$domains$matrix$BoolMatrix$$equalAndIsZeroAndIsOne, battery)\n{\n    MatrixFixtures_3x3 f;\n    BoolMatrix mats[] = {\n        BoolMatrix(f.zero.mat),\n        BoolMatrix(f.id.mat),\n        BoolMatrix(f.r1.mat),\n        BoolMatrix(f.r2.mat),\n        BoolMatrix(f.ext_r1_r2.mat),\n        BoolMatrix(f.ext_r2_r1.mat),\n    };\n\n    for (size_t left=0; left<NUM_ELEMENTS(mats); ++left) {\n        for (size_t right=0; right<NUM_ELEMENTS(mats); ++right) {\n            EXPECT_EQ(left == right,\n                      mats[left].equal(&mats[right]));\n        }\n    }\n}\n\n\nTEST(wali$domains$matrix$BoolMatrix$$zero_raw, basicTest3x3)\n{\n    RandomMatrix1_3x3 f;\n    ZeroBackingMatrix_3x3 z;\n\n    BoolMatrix m(f.mat);\n    BoolMatrix mz(z.mat);\n\n    boost::scoped_ptr<BoolMatrix> result(m.zero_raw());\n\n    EXPECT_EQ(z.mat, result->matrix());\n    EXPECT_TRUE(mz.equal(result.get()));\n}\n\n\nTEST(wali$domains$matrix$BoolMatrix$$one_raw, basicTest3x3)\n{\n    RandomMatrix1_3x3 f;\n    IdBackingMatrix_3x3 z;\n\n    BoolMatrix m(f.mat);\n    BoolMatrix mid(z.mat);\n\n    boost::scoped_ptr<BoolMatrix> result(m.one_raw());\n\n    EXPECT_EQ(z.mat, result->matrix());\n    EXPECT_TRUE(mid.equal(result.get()));\n}\n\n\nTEST(wali$domains$matrix$BoolMatrix$$extend_raw, twoRandomMatrices)\n{\n    RandomMatrix1_3x3 f1;\n    RandomMatrix2_3x3 f2;\n    ExtendR1R2_3x3 fr12;\n    ExtendR2R1_3x3 fr21;\n\n    BoolMatrix m1(f1.mat);\n    BoolMatrix m2(f2.mat);\n\n    boost::scoped_ptr<BoolMatrix> result12(m1.extend_raw(&m2));\n    boost::scoped_ptr<BoolMatrix> result21(m2.extend_raw(&m1));\n\n    EXPECT_EQ(fr12.mat, result12->matrix());\n    EXPECT_EQ(fr21.mat, result21->matrix());\n}\n\n\nTEST(wali$domains$matrix$BoolMatrix$$extend_raw, extendAgainstZero)\n{\n    RandomMatrix1_3x3 f;\n    ZeroBackingMatrix_3x3 z;\n\n    BoolMatrix mf(f.mat);\n    BoolMatrix mz(z.mat);\n\n    boost::scoped_ptr<BoolMatrix>\n        result1Z(mf.extend_raw(&mz)),\n        resultZ1(mz.extend_raw(&mf)),\n        resultZZ(mz.extend_raw(&mz));\n\n    EXPECT_EQ(z.mat, result1Z->matrix());\n    EXPECT_EQ(z.mat, resultZ1->matrix());\n    EXPECT_EQ(z.mat, resultZZ->matrix());\n\n    EXPECT_TRUE(mz.equal(result1Z.get()));\n    EXPECT_TRUE(mz.equal(resultZ1.get()));\n    EXPECT_TRUE(mz.equal(resultZZ.get()));\n}\n\n\nTEST(wali$domains$matrix$BoolMatrix$$extend_raw, extendAgainstOne)\n{\n    RandomMatrix1_3x3 fr1;\n    IdBackingMatrix_3x3 id;\n\n    BoolMatrix mr1(fr1.mat);\n    BoolMatrix mid(id.mat);\n\n    boost::scoped_ptr<BoolMatrix>\n        result_R1_Id(mr1.extend_raw(&mid)),\n        result_Id_R1(mid.extend_raw(&mr1)),\n        result_Id_Id(mid.extend_raw(&mid));\n\n    EXPECT_EQ(fr1.mat, result_R1_Id->matrix());\n    EXPECT_EQ(fr1.mat, result_Id_R1->matrix());\n    EXPECT_EQ(id.mat,  result_Id_Id->matrix());\n\n    EXPECT_TRUE(mr1.equal(result_R1_Id.get()));\n    EXPECT_TRUE(mr1.equal(result_Id_R1.get()));\n    EXPECT_TRUE(mid.equal(result_Id_Id.get()));\n}\n\n\nTEST(wali$domains$matrix$BoolMatrix$$combine_raw, randomAndId)\n{\n    RandomMatrix1_3x3 f1;\n    IdBackingMatrix_3x3 f2;\n    CombineR1Id_3x3 fr;\n\n    BoolMatrix m1(f1.mat);\n    BoolMatrix m2(f2.mat);\n    BoolMatrix mr(fr.mat);\n\n    boost::scoped_ptr<BoolMatrix> result12(m1.combine_raw(&m2));\n    boost::scoped_ptr<BoolMatrix> result21(m2.combine_raw(&m1));\n\n    EXPECT_EQ(fr.mat, result12->matrix());\n    EXPECT_EQ(fr.mat, result21->matrix());\n\n    EXPECT_TRUE(mr.equal(result12.get()));\n    EXPECT_TRUE(mr.equal(result21.get()));\n}\n\n\nTEST(wali$domains$matrix$BoolMatrix$$print, random)\n{\n    RandomMatrix1_3x3 f;\n    BoolMatrix m(f.mat);\n    std::stringstream ss;\n\n    m.print(ss);\n\n    EXPECT_EQ(\"Matrix: [3,3]((1,1,0),(1,0,1),(0,0,1))\", ss.str());\n}\n\n\nTEST(wali$domains$matrix$BoolMatrix, callWaliTestSemElemImpl)\n{\n    RandomMatrix1_3x3 f;\n    sem_elem_t m = new BoolMatrix(f.mat);\n    test_semelem_impl(m);\n}\n\n}\n}\n", "meta": {"hexsha": "405009bcb863de24751a978ac4761e8139ccfc86", "size": 4269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/unit-tests/Source/AddOns/Domains/matrix/class-boolmatrix.cpp", "max_stars_repo_name": "jusito/WALi-OpenNWA", "max_stars_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T17:25:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T20:17:00.000Z", "max_issues_repo_path": "Tests/unit-tests/Source/AddOns/Domains/matrix/class-boolmatrix.cpp", "max_issues_repo_name": "jusito/WALi-OpenNWA", "max_issues_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-03-03T05:58:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-03T12:26:10.000Z", "max_forks_repo_path": "Tests/unit-tests/Source/AddOns/Domains/matrix/class-boolmatrix.cpp", "max_forks_repo_name": "jusito/WALi-OpenNWA", "max_forks_repo_head_hexsha": "2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-09-25T17:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T18:25:38.000Z", "avg_line_length": 23.2010869565, "max_line_length": 72, "alphanum_fraction": 0.6741625673, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6265021238565224}}
{"text": "#include <iostream>\r\n\r\nusing namespace std;\r\n#include <Eigen/Core>\r\n#include <Eigen/Dense>\r\n\r\n#define MATRIX_SIZE 50\r\n\r\n\r\nint main(int argc, char **argv)\r\n{\r\n    Eigen::Matrix<float, 2, 3> matrix_23;\r\n\r\n    return 0;\r\n}", "meta": {"hexsha": "296e5a3ec7f3976eeab635a9eb10e3ef5069d049", "size": 219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "develop_language/cpp/examples_code/eigen/useEigen.cpp", "max_stars_repo_name": "magic428/subjects_notes", "max_stars_repo_head_hexsha": "6930adbb3f445c11ca9d024abb12a53d6aca19e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-18T17:13:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-25T02:34:03.000Z", "max_issues_repo_path": "develop_language/cpp/examples_code/eigen/useEigen.cpp", "max_issues_repo_name": "magic428/subjects_notes", "max_issues_repo_head_hexsha": "6930adbb3f445c11ca9d024abb12a53d6aca19e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "develop_language/cpp/examples_code/eigen/useEigen.cpp", "max_forks_repo_name": "magic428/subjects_notes", "max_forks_repo_head_hexsha": "6930adbb3f445c11ca9d024abb12a53d6aca19e7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.6, "max_line_length": 42, "alphanum_fraction": 0.6392694064, "num_tokens": 57, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. Yes\n2. Yes", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.6264775458308035}}
{"text": "#include <utils.hpp>\n#include <iostream>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <partition.hpp>\n\nusing namespace boost::numeric::ublas;\n\nint main () {\n\n        int n = 4;\n        int partitionSize = 2;\n\n        CsrMatrix<double> m (n, n, n * n);\n        for (int i = 0; i < n; ++i)\n        {\n                for (int j = 0; j < n; ++j)\n                {\n                        m(i, j) = i * (j + 1) + 1;\n                }\n        }\n        auto ps = partition(m, 2);\n        std::cout << \"In:\" << std::endl; \n        std::cout << m << std::endl;\n        std::cout << \"Out: \" << std::endl;\n        for (int i = 0; i < ps.size(); ++i)\n        {\n            std::cout << ps[i] << std::endl;\n        }\n        \n        for (int i = 0; i < ps.size(); ++i)\n        {\n            for (int j = 0; j < n; ++j)\n            {\n                    for (int k = 0; k < partitionSize; ++k)\n                    {\n                            double got = ps[i](j, k);\n                            double exp = m(j, i * partitionSize + k); \n                            if (exp != got) {\n                                    std::cout << \"Error - exp: \" << exp << \" got: \" << got << std::endl;\n                                    return 1;\n                            }\n                    }\n            }\n        }\n        return 0;\n}\n", "meta": {"hexsha": "8077a37d37b0cec37476831415d3f44b730dd20d", "size": 1373, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/dfesnippets/sparse/test_partition.cpp", "max_stars_repo_name": "custom-computing-ic/dfe-snippets", "max_stars_repo_head_hexsha": "8721e6272c25f77360e2de423d8ff5a9299ee5b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T13:23:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T11:04:40.000Z", "max_issues_repo_path": "include/dfesnippets/sparse/test_partition.cpp", "max_issues_repo_name": "custom-computing-ic/dfe-snippets", "max_issues_repo_head_hexsha": "8721e6272c25f77360e2de423d8ff5a9299ee5b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2015-07-02T10:13:05.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-30T15:59:43.000Z", "max_forks_repo_path": "include/dfesnippets/sparse/test_partition.cpp", "max_forks_repo_name": "custom-computing-ic/dfe-snippets", "max_forks_repo_head_hexsha": "8721e6272c25f77360e2de423d8ff5a9299ee5b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-04-08T13:27:50.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-16T14:38:52.000Z", "avg_line_length": 28.6041666667, "max_line_length": 104, "alphanum_fraction": 0.3408594319, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6264775422644627}}
{"text": "#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n\n#include <ceres-error-terms/parameterization/quaternion-param-jpl.h>\n#include <maplab-common/pose_types.h>\n#include <maplab-common/quaternion-math.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\nusing namespace ceres_error_terms;  // NOLINT\n\nstruct CostFunctor {\n  explicit CostFunctor(const pose::Quaternion& reference)\n      : reference_(reference) {}\n  template <typename T>\n  bool operator()(const T* const x1, const T* const x2, T* residual) const {\n    typedef kindr::minimal::RotationQuaternionTemplate<T> QuaternionT;\n\n    const Eigen::Map<const Eigen::Quaternion<T> > quaternion1(x1);\n    const Eigen::Map<const Eigen::Quaternion<T> > quaternion2(x2);\n    Eigen::Map<Eigen::Matrix<T, 3, 1> > error(residual);\n\n    QuaternionT error_quaternion = common::signedQuaternionProductHamilton(\n        common::signedQuaternionProductHamilton(\n            QuaternionT(quaternion2), QuaternionT(quaternion1).inverse()),\n        QuaternionT(reference_.toImplementation().cast<T>()).inverse());\n    error = Eigen::Matrix<T, 3, 1>(\n        T(2.0) * error_quaternion.x(), T(2.0) * error_quaternion.y(),\n        T(2.0) * error_quaternion.z());\n    return true;\n  }\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n private:\n  pose::Quaternion reference_;\n};\n\n// The test verifies if 4 close-to-unit quaternions (with some random noise),\n// tied with relative rotations among x-axis:\n// * q1->q2 = +90deg\n// * q2->q3 = +90deg\n// * q3->q4 = +90deg\n// * q4->q1 = +90deg\n// and a predefined value of q1(1, 0, 0, 0) will end up with correct relative\n// and absolute rotations, i.e.:\n// * q1 = 0deg\n// * q2 = 90deg\n// * q3 = 180deg\n// * q4 = 270deg\nTEST(PosegraphErrorTerms, TwoPointsRotationSolving_Minimization) {\n  pose::Quaternion q1(1, 0, 0, 0);\n  pose::Quaternion q2(\n      0.9965159041385382, 0.06892005802323266, 0.020435594117957374,\n      0.042290245850220926);\n  pose::Quaternion q3(\n      0.9990182922767228, -0.007804703449117966, -0.026464453222036003,\n      0.03465791419330294);\n  pose::Quaternion q4(\n      0.9988646699884802, -0.00795566765132752, -0.043763237371076937,\n      0.01705454355380988);\n\n  // 90deg rotation as relative transformation between nodes\n  pose::Quaternion reference(sqrt(2) / 2, sqrt(2) / 2, 0, 0);\n\n  ceres::Problem problem;\n  ceres::CostFunction* cost_function =\n      new ceres::AutoDiffCostFunction<CostFunctor, 3, 4, 4>(\n          new CostFunctor(reference));\n\n  problem.AddResidualBlock(\n      cost_function, NULL, q1.toImplementation().coeffs().data(),\n      q2.toImplementation().coeffs().data());\n  problem.AddResidualBlock(\n      cost_function, NULL, q2.toImplementation().coeffs().data(),\n      q3.toImplementation().coeffs().data());\n  problem.AddResidualBlock(\n      cost_function, NULL, q3.toImplementation().coeffs().data(),\n      q4.toImplementation().coeffs().data());\n  problem.AddResidualBlock(\n      cost_function, NULL, q4.toImplementation().coeffs().data(),\n      q1.toImplementation().coeffs().data());\n\n  ceres::LocalParameterization* quaternion_parameterization =\n      new ceres_error_terms::JplQuaternionParameterization;\n  problem.SetParameterization(\n      q1.toImplementation().coeffs().data(), quaternion_parameterization);\n  problem.SetParameterization(\n      q2.toImplementation().coeffs().data(), quaternion_parameterization);\n  problem.SetParameterization(\n      q3.toImplementation().coeffs().data(), quaternion_parameterization);\n  problem.SetParameterization(\n      q4.toImplementation().coeffs().data(), quaternion_parameterization);\n\n  problem.SetParameterBlockConstant(q1.toImplementation().coeffs().data());\n\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\n  options.minimizer_progress_to_stdout = false;\n  options.gradient_tolerance = 1e-16;\n  options.function_tolerance = 1e-16;\n  options.parameter_tolerance = 1e-16;\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n\n  EXPECT_NEAR_KINDR_QUATERNION(\n      pose::Quaternion(q2 * q1.inverse()),\n      pose::Quaternion(sqrt(2) / 2, sqrt(2) / 2, 0, 0), 1e-8);\n  EXPECT_NEAR_KINDR_QUATERNION(\n      pose::Quaternion(q3 * q2.inverse()),\n      pose::Quaternion(sqrt(2) / 2, sqrt(2) / 2, 0, 0), 1e-8);\n  EXPECT_NEAR_KINDR_QUATERNION(\n      pose::Quaternion(q4 * q3.inverse()),\n      pose::Quaternion(sqrt(2) / 2, sqrt(2) / 2, 0, 0), 1e-8);\n  EXPECT_NEAR_KINDR_QUATERNION(\n      pose::Quaternion(q1 * q4.inverse()),\n      pose::Quaternion(sqrt(2) / 2, sqrt(2) / 2, 0, 0), 1e-8);\n\n  EXPECT_NEAR_KINDR_QUATERNION(q1, pose::Quaternion(1, 0, 0, 0), 1e-8);\n  EXPECT_NEAR_KINDR_QUATERNION(\n      q2, pose::Quaternion(sqrt(2) / 2, sqrt(2) / 2, 0, 0), 1e-8);\n  EXPECT_NEAR_KINDR_QUATERNION(q3, pose::Quaternion(0, 1, 0, 0), 1e-8);\n  EXPECT_NEAR_KINDR_QUATERNION(\n      q4, pose::Quaternion(-sqrt(2) / 2, sqrt(2) / 2, 0, 0), 1e-8);\n\n  LOG(INFO) << summary.BriefReport();\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "1b2ced2ad22280b4396e4969ea6209866d4276fa", "size": 5071, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/ceres-error-terms/test/test_few_points_quaternion_test.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/ceres-error-terms/test/test_few_points_quaternion_test.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/ceres-error-terms/test/test_few_points_quaternion_test.cc", "max_forks_repo_name": "AdronTech/maplab", "max_forks_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 661.0, "max_forks_repo_forks_event_min_datetime": "2017-11-28T07:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:06:29.000Z", "avg_line_length": 37.2867647059, "max_line_length": 77, "alphanum_fraction": 0.7004535595, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.6263154191853844}}
{"text": "#include <vector>\n#include <Eigen/Dense>\n\nusing std::vector; using std::string;\n\ntypedef Eigen::MatrixXd matrix;\n\nint atom(int ao_index, int orbitals_per_atom)\n{\n    return ao_index / orbitals_per_atom;\n}\n\nint orb_index(int ao_index, int orbitals_per_atom)\n{\n    return ao_index % orbitals_per_atom;\n}\n\nfloat chi_on_atom(int o1, int o2, int o3, double dipole)\n{\n    if (o1 == o2 && o3 == 0)\n        return 1.0;\n    else if (o1 == o3 && (o3 > 0 && o3 <= 3) && o2 == 0)\n        return dipole;\n    else if (o2 == o3 && (o3 > 0 && o3 <= 3) && o1 == 0)\n        return dipole;\n    return 0.0;\n}\n\nmatrix calculate_fock_matrix(matrix hamiltonian_matrix, matrix interaction_matrix, matrix density_matrix, int orbitals_per_atom, double dipole){\n    int ndof = hamiltonian_matrix.row(0).size();\n    matrix fock_matrix = hamiltonian_matrix;\n\n    for (int p = 0; p < ndof; p++)\n    {\n        int at_p = atom(p, orbitals_per_atom);\n        int orb_p = orb_index(p, orbitals_per_atom);\n        for (int orb_q = 0; orb_q < orbitals_per_atom; orb_q++)\n        {\n            int q = orb_q + at_p * orbitals_per_atom;\n            for (int orb_t = 0; orb_t < orbitals_per_atom; orb_t++)\n            {\n                int t = orb_t + at_p * orbitals_per_atom;\n                float chi_pqt = chi_on_atom(orb_p, orb_q, orb_t, dipole);\n                for (int r = 0; r < ndof; r++)\n                {\n                    int at_r = atom(r, orbitals_per_atom);\n                    int orb_r = orb_index(r, orbitals_per_atom);\n                    for (int orb_s = 0; orb_s < orbitals_per_atom; orb_s++)\n                    {\n                        int s = orb_s + at_r * orbitals_per_atom;\n                        for (int orb_u = 0; orb_u < orbitals_per_atom; orb_u++)\n                        {\n                            int u = orb_u + at_r * orbitals_per_atom;\n                            float chi_rsu = chi_on_atom(orb_r, orb_s, orb_u, dipole); \n                            fock_matrix(p,q) += 2.0 * chi_pqt * chi_rsu * interaction_matrix(t, u) * density_matrix(r, s);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    for (int p = 0; p < ndof; p++)\n    {\n        int at_p = atom(p, orbitals_per_atom);\n        int orb_p = orb_index(p, orbitals_per_atom);\n        for (int orb_s = 0; orb_s < orbitals_per_atom; orb_s++)\n        {\n            int s = orb_s + at_p * orbitals_per_atom;\n            for (int orb_u = 0; orb_u < orbitals_per_atom; orb_u++)\n            {\n                int u = orb_u + at_p * orbitals_per_atom;\n                float chi_psu = chi_on_atom(orb_p, orb_s, orb_u, dipole); \n                for (int q = 0; q < ndof; q++)\n                {\n                    int at_q = atom(q, orbitals_per_atom);\n                    int orb_q = orb_index(q, orbitals_per_atom);\n                    for (int orb_r = 0; orb_r < orbitals_per_atom; orb_r++)\n                    {\n                        int r = orb_r + at_q * orbitals_per_atom;\n                        for (int orb_t = 0; orb_t < orbitals_per_atom; orb_t++)\n                        {\n                            int t = orb_t + at_q * orbitals_per_atom;\n                            float chi_rqt = chi_on_atom(orb_r, orb_q, orb_t, dipole);\n                            fock_matrix(p,q) -= chi_rqt * chi_psu * interaction_matrix(t, u) * density_matrix(r, s);\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return fock_matrix;\n}\n\n", "meta": {"hexsha": "90d7b445a3d863ab46bd641974bb1cc45b4ea5d4", "size": 3487, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shared_lib/fock_matrix.cpp", "max_stars_repo_name": "Abdul-Zamani/qm_2019_sss_1", "max_stars_repo_head_hexsha": "fd665cccd90d8cf68cb97c8738cd32fb7981fe54", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shared_lib/fock_matrix.cpp", "max_issues_repo_name": "Abdul-Zamani/qm_2019_sss_1", "max_issues_repo_head_hexsha": "fd665cccd90d8cf68cb97c8738cd32fb7981fe54", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-24T01:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-24T01:45:23.000Z", "max_forks_repo_path": "shared_lib/fock_matrix.cpp", "max_forks_repo_name": "MolSSI-Education/qm_2019_sss_1", "max_forks_repo_head_hexsha": "c1b3c1d66dd32e47edc5214bc32c5e996a03db26", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-07-23T20:16:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-31T17:47:46.000Z", "avg_line_length": 37.0957446809, "max_line_length": 144, "alphanum_fraction": 0.4981359335, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6261757285741032}}
{"text": "/**\n * @file spherical_kernel.hpp\n * @author Neil Slagle\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#ifndef MLPACK_CORE_KERNELS_SPHERICAL_KERNEL_HPP\n#define MLPACK_CORE_KERNELS_SPHERICAL_KERNEL_HPP\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <mlpack/prereqs.hpp>\n\nnamespace mlpack {\nnamespace kernel {\n\n/**\n * The spherical kernel, which is 1 when the distance between the two argument\n * points is less than or equal to the bandwidth, or 0 otherwise.\n */\nclass SphericalKernel\n{\n public:\n  /**\n   * Construct the SphericalKernel with the given bandwidth.\n   */\n  SphericalKernel(const double bandwidth = 1.0) :\n    bandwidth(bandwidth),\n    bandwidthSquared(std::pow(bandwidth, 2.0))\n  { /* Nothing to do. */ }\n\n  /**\n   * Evaluate the spherical kernel with the given two vectors.\n   *\n   * @tparam VecTypeA Type of first vector.\n   * @tparam VecTypeB Type of second vector.\n   * @param a First vector.\n   * @param b Second vector.\n   * @return The kernel evaluation between the two vectors.\n   */\n  template<typename VecTypeA, typename VecTypeB>\n  double Evaluate(const VecTypeA& a, const VecTypeB& b) const\n  {\n    return\n        (metric::SquaredEuclideanDistance::Evaluate(a, b) <= bandwidthSquared) ?\n        1.0 : 0.0;\n  }\n  /**\n   * Obtains the convolution integral [integral K(||x-a||)K(||b-x||)dx]\n   * for the two vectors.\n   *\n   * @tparam VecTypeA Type of first vector (arma::vec, arma::sp_vec should be\n   *       expected).\n   * @tparam VecTypeB Type of second vector.\n   * @param a First vector.\n   * @param b Second vector.\n   * @return the convolution integral value.\n   */\n  template<typename VecTypeA, typename VecTypeB>\n  double ConvolutionIntegral(const VecTypeA& a, const VecTypeB& b) const\n  {\n    double distance = sqrt(metric::SquaredEuclideanDistance::Evaluate(a, b));\n    if (distance >= 2.0 * bandwidth)\n    {\n      return 0.0;\n    }\n    double volumeSquared = pow(Normalizer(a.n_rows), 2.0);\n\n    switch (a.n_rows)\n    {\n      case 1:\n        return 1.0 / volumeSquared * (2.0 * bandwidth - distance);\n        break;\n      case 2:\n        return 1.0 / volumeSquared *\n          (2.0 * bandwidth * bandwidth * acos(distance/(2.0 * bandwidth)) -\n          distance / 4.0 * sqrt(4.0*bandwidth*bandwidth-distance*distance));\n        break;\n      default:\n        Log::Fatal << \"The spherical kernel does not support convolution\\\n          integrals above dimension two, yet...\" << std::endl;\n        return -1.0;\n        break;\n    }\n  }\n  double Normalizer(size_t dimension) const\n  {\n    return pow(bandwidth, (double) dimension) * pow(M_PI, dimension / 2.0) /\n        std::tgamma(dimension / 2.0 + 1.0);\n  }\n\n  /**\n   * Evaluate the kernel when only a distance is given, not two points.\n   *\n   * @param t Argument to kernel.\n   */\n  double Evaluate(const double t) const\n  {\n    return (t <= bandwidth) ? 1.0 : 0.0;\n  }\n  double Gradient(double t)\n  {\n    return t == bandwidth ? arma::datum::nan : 0.0;\n  }\n\n  //! Serialize the object.\n  template<typename Archive>\n  void Serialize(Archive& ar, const unsigned int /* version */)\n  {\n    ar & data::CreateNVP(bandwidth, \"bandwidth\");\n    ar & data::CreateNVP(bandwidthSquared, \"bandwidthSquared\");\n  }\n\n private:\n  double bandwidth;\n  double bandwidthSquared;\n};\n\n//! Kernel traits for the spherical kernel.\ntemplate<>\nclass KernelTraits<SphericalKernel>\n{\n public:\n  //! The spherical kernel is normalized: K(x, x) = 1 for all x.\n  static const bool IsNormalized = true;\n  //! The spherical kernel doesn't include a squared distance.\n  static const bool UsesSquaredDistance = false;\n};\n\n} // namespace kernel\n} // namespace mlpack\n\n#endif\n", "meta": {"hexsha": "9c2303d92214ce1a40dba55694c2ac701c8985a0", "size": 3885, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/core/kernels/spherical_kernel.hpp", "max_stars_repo_name": "17minutes/mlpack", "max_stars_repo_head_hexsha": "8f4af1ec454a662dd7c990cf2146bfeb1bd0cb3a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-22T18:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:39:58.000Z", "max_issues_repo_path": "src/mlpack/core/kernels/spherical_kernel.hpp", "max_issues_repo_name": "17minutes/mlpack", "max_issues_repo_head_hexsha": "8f4af1ec454a662dd7c990cf2146bfeb1bd0cb3a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/core/kernels/spherical_kernel.hpp", "max_forks_repo_name": "17minutes/mlpack", "max_forks_repo_head_hexsha": "8f4af1ec454a662dd7c990cf2146bfeb1bd0cb3a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5661764706, "max_line_length": 80, "alphanum_fraction": 0.6643500644, "num_tokens": 1025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6261757180494508}}
{"text": "#ifndef STAN_MATH_FWD_MAT_FUN_DETERMINANT_HPP\n#define STAN_MATH_FWD_MAT_FUN_DETERMINANT_HPP\n\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/fwd/core.hpp>\n#include <stan/math/fwd/mat/fun/typedefs.hpp>\n#include <stan/math/prim/mat/fun/multiply.hpp>\n#include <stan/math/fwd/mat/fun/multiply.hpp>\n#include <stan/math/prim/mat/fun/inverse.hpp>\n#include <stan/math/fwd/mat/fun/inverse.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <vector>\n\nnamespace stan {\n  namespace math {\n\n    template<typename T, int R, int C>\n    inline\n    fvar<T>\n    determinant(const Eigen::Matrix<fvar<T>, R, C>& m) {\n      check_square(\"determinant\", \"m\", m);\n      Eigen::Matrix<T, R, C> m_deriv(m.rows(), m.cols());\n      Eigen::Matrix<T, R, C> m_val(m.rows(), m.cols());\n\n      for (size_type i = 0; i < m.rows(); i++) {\n        for (size_type j = 0; j < m.cols(); j++) {\n          m_deriv(i, j) = m(i, j).d_;\n          m_val(i, j) = m(i, j).val_;\n        }\n      }\n\n      Eigen::Matrix<T, R, C> m_inv = inverse(m_val);\n      m_deriv = multiply(m_inv, m_deriv);\n\n      fvar<T> result;\n      result.val_ = m_val.determinant();\n      result.d_ = result.val_ * m_deriv.trace();\n\n      // FIXME:  I think this will overcopy compared to retur fvar<T>(...);\n      return result;\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "162f22d341044e4f1667d3d45367a0a1e6442b0b", "size": 1348, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/fwd/mat/fun/determinant.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/fwd/mat/fun/determinant.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/fwd/mat/fun/determinant.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6808510638, "max_line_length": 75, "alphanum_fraction": 0.6275964392, "num_tokens": 393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6261566422508773}}
{"text": "#include \"TestsWithGL_pcp.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include \"MatrixCoefficientSet.hpp\"\n#include \"test_sim_core.h\"\n\ntemplate <size_t row_num>\nvoid disp_col_coefs(double col_coefs[row_num])\n{\n\tfor (size_t i = 0; i < row_num; i++)\n\t\tstd::cout << col_coefs[i] << \", \";\n\tstd::cout << \"\\n\";\n}\n\nvoid test_matrix_coefficient_set(void)\n{\n\tMatrixCoefficientSet<> mat;\n\n\tmat.init(5);\n\tfor (size_t i = 0; i < 5; i++)\n\t\tfor (size_t j = 0; j < 5; j++)\n\t\t\tmat.add_coefficient(i, j, double(i + j));\n\tmat.add_coefficient(3, 3, 2.0);\n\tmat.add_coefficient(1, 0, 3.5);\n\tmat.add_coefficient(2, 2, 1.0);\n\tmat.print();\n\n\tdouble col_coefs[5];\n\tstd::cout << mat.del_col_and_row(3, col_coefs) << \"\\n\";\n\tdisp_col_coefs<5>(col_coefs);\n\tstd::cout << mat.del_col_and_row(2, col_coefs) << \"\\n\";\n\tdisp_col_coefs<5>(col_coefs);\n\n\tmat.print();\n\n\tmat.add_coefficient(1, 2, 6.0);\n\tmat.add_coefficient(2, 2, 6.0);\n\n\tmat.print();\n\n\tEigen::SparseMatrix<double> g_kmat(5, 5);\n\tg_kmat.setFromTriplets(mat.begin(), mat.end());\n\tstd::cout << g_kmat << \"\\n\";\n\n\tmat.init(6);\n\tfor (size_t i = 0; i < 6; i++)\n\t\tfor (size_t j = 0; j < 6; j++)\n\t\t\tmat.add_coefficient(i, j, double(i + j));\n\tmat.add_coefficient(3, 3, 2.0);\n\tmat.add_coefficient(1, 0, 3.5);\n\tmat.add_coefficient(2, 2, 1.0);\n\tmat.print();\n\n\tEigen::SparseMatrix<double> g_kmat2(6, 6);\n\tg_kmat2.setFromTriplets(mat.begin(), mat.end());\n\tstd::cout << g_kmat2 << \"\\n\";\n\n\tsystem(\"pause\");\n}\n\n//void cal_stiffness_mat(double kmat[20][20], double E[3][3], double dN_dx[3][8]);\n\nvoid test_cal_stiffness_mat(void)\n{\n\tdouble E[3][3], dN_dx[3][8], kmat[20][20];\n\n\tmemset(kmat, 0, sizeof(double) * 20 * 20);\n\n\tdouble va = 0.0;\n\tEigen::Matrix<double, 3, 3> mat33;\n\tfor (size_t i = 0; i < 3; i++)\n\t\tfor (size_t j = 0; j < 3; j++)\n\t\t{\n\t\t\tmat33(i, j) = va;\n\t\t\tE[i][j] = va;\n\t\t\tva += 1.0;\n\t\t}\n\tstd::cout << mat33 << \"\\n\";\n\n\tEigen::Matrix<double, 3, 8> mat38;\n\tfor (size_t i = 0; i < 3; i++)\n\t\tfor (size_t j = 0; j < 8; j++)\n\t\t{\n\t\t\tmat38(i, j) = double(i + j);\n\t\t\tdN_dx[i][j] = double(i + j);\n\t\t}\n\tstd::cout << mat38 << \"\\n\";\n\n\tstd::cout << \"\\n\" << mat33 * mat38 << \"\\n\";\n\n\tEigen::Matrix<double, 8, 8> mat88 = mat38.transpose() * mat33 * mat38;\n\tstd::cout << \"\\n\" << mat88 << \"\\n\";\n\n\t//cal_stiffness_mat(kmat, E, dN_dx);\n\tfor (size_t i = 0; i < 10; i++)\n\t{\n\t\tfor (size_t j = 0; j < 10; j++)\n\t\t{\n\t\t\tstd::cout << kmat[i][j] << \", \";\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t}\n\n\tsystem(\"pause\");\n}\n", "meta": {"hexsha": "2cabc6e846979bc7a5152fc45cbe593313179c31", "size": 2403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TestsWithGL/test_matrix_coefficient_set.cpp", "max_stars_repo_name": "MingAtUWA/SimpleMPM2", "max_stars_repo_head_hexsha": "7a1d7c257c621123d85a0630e93d42ae25c70fb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TestsWithGL/test_matrix_coefficient_set.cpp", "max_issues_repo_name": "MingAtUWA/SimpleMPM2", "max_issues_repo_head_hexsha": "7a1d7c257c621123d85a0630e93d42ae25c70fb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TestsWithGL/test_matrix_coefficient_set.cpp", "max_forks_repo_name": "MingAtUWA/SimpleMPM2", "max_forks_repo_head_hexsha": "7a1d7c257c621123d85a0630e93d42ae25c70fb4", "max_forks_repo_licenses": ["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.25, "max_line_length": 82, "alphanum_fraction": 0.5888472742, "num_tokens": 915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6261566261408392}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGY_GEOGRAPHIC_AREA_BOX_HPP\n#define BOOST_GEOMETRY_STRATEGY_GEOGRAPHIC_AREA_BOX_HPP\n\n\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/srs/spheroid.hpp>\n#include <boost/geometry/strategies/spherical/get_radius.hpp>\n#include <boost/geometry/strategy/area.hpp>\n#include <boost/geometry/util/normalize_spheroidal_box_coordinates.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace area\n{\n\n// Based on the approach for spherical coordinate system:\n// https://math.stackexchange.com/questions/131735/surface-element-in-spherical-coordinates\n// http://www.cs.cmu.edu/afs/cs/academic/class/16823-s16/www/pdfs/appearance-modeling-3.pdf\n// https://www.astronomyclub.xyz/celestial-sphere-2/solid-angle-on-the-celestial-sphere.html\n// https://mathworld.wolfram.com/SolidAngle.html\n// https://en.wikipedia.org/wiki/Spherical_coordinate_system\n// and equations for spheroid:\n// https://en.wikipedia.org/wiki/Geographic_coordinate_conversion\n// https://en.wikipedia.org/wiki/Meridian_arc\n// Note that the equations use geodetic latitudes so we do not have to convert them.\n// assume(y_max > y_min);\n// assume(x_max > x_min);\n// M: a*(1-e^2) / (1-e^2*sin(y)^2)^(3/2);\n// N: a / sqrt(1-e^2*sin(y)^2);\n// O: N*cos(y)*M;\n// tellsimp(log(abs(e*sin(y_min)+1)), p_min);\n// tellsimp(log(abs(e*sin(y_min)-1)), m_min);\n// tellsimp(log(abs(e*sin(y_max)+1)), p_max);\n// tellsimp(log(abs(e*sin(y_max)-1)), m_max);\n// S: integrate(integrate(O, y, y_min, y_max), x, x_min, x_max);\n// combine(S);\n//\n// An alternative solution to the above formula was suggested by Charles Karney\n// https://github.com/boostorg/geometry/pull/832\n// The following are formulas for area of a box defined by the equator and some latitude,\n// not arbitrary box.\n// For e^2 > 0\n// dlambda*b^2*sin(phi)/2*(1/(1-e^2*sin(phi)^2) + atanh(e*sin(phi))/(e*sin(phi)))\n// For e^2 < 0\n// dlambda*b^2*sin(phi)/2*(1/(1-e^2*sin(phi)^2) + atan(ea*sin(phi))/(ea*sin(phi)))\n// where ea = sqrt(-e^2)\ntemplate\n<\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nclass geographic_box\n{\npublic:\n    template <typename Box>\n    struct result_type\n        : strategy::area::detail::result_type\n            <\n                Box,\n                CalculationType\n            >\n    {};\n\n    geographic_box() = default;\n\n    explicit geographic_box(Spheroid const& spheroid)\n        : m_spheroid(spheroid)\n    {}\n    \n    template <typename Box>\n    inline auto apply(Box const& box) const\n    {\n        typedef typename result_type<Box>::type return_type;\n\n        return_type const c0 = 0;\n        \n        return_type x_min = get_as_radian<min_corner, 0>(box); // lon\n        return_type y_min = get_as_radian<min_corner, 1>(box); // lat\n        return_type x_max = get_as_radian<max_corner, 0>(box);\n        return_type y_max = get_as_radian<max_corner, 1>(box);\n\n        math::normalize_spheroidal_box_coordinates<radian>(x_min, y_min, x_max, y_max);\n\n        if (x_min == x_max || y_max == y_min)\n        {\n            return c0;\n        }\n\n        return_type const e2 = formula::eccentricity_sqr<return_type>(m_spheroid);\n\n        return_type const x_diff = x_max - x_min;\n        return_type const sin_y_min = sin(y_min);\n        return_type const sin_y_max = sin(y_max);\n\n        if (math::equals(e2, c0))\n        {\n            // spherical formula\n            return_type const a = get_radius<0>(m_spheroid);\n            return x_diff * (sin_y_max - sin_y_min) * a * a;\n        }\n\n        return_type const c1 = 1;\n        return_type const c2 = 2;\n        return_type const b = get_radius<2>(m_spheroid);\n\n        /*\n        return_type const c4 = 4;\n        return_type const e = math::sqrt(e2);\n\n        return_type const p_min = log(math::abs(e * sin_y_min + c1));\n        return_type const p_max = log(math::abs(e * sin_y_max + c1));\n        return_type const m_min = log(math::abs(e * sin_y_min - c1));\n        return_type const m_max = log(math::abs(e * sin_y_max - c1));\n        return_type const n_min = e * sin_y_min * sin_y_min;\n        return_type const n_max = e * sin_y_max * sin_y_max;\n        return_type const d_min = e * n_min - c1;\n        return_type const d_max = e * n_max - c1;\n\n        // NOTE: For equal latitudes the original formula generated by maxima may give negative\n        //   result. It's caused by the order of operations, so here they're rearranged for\n        //   symmetry.\n        return_type const comp0 = (p_min - m_min) / (c4 * e * d_min);\n        return_type const comp1 = sin_y_min / (c2 * d_min);\n        return_type const comp2 = n_min * (m_min - p_min) / (c4 * d_min);\n        return_type const comp3 = (p_max - m_max) / (c4 * e * d_max);\n        return_type const comp4 = sin_y_max / (c2 * d_max);\n        return_type const comp5 = n_max * (m_max - p_max) / (c4 * d_max);\n        return_type const comp02 = comp0 + comp1 + comp2;\n        return_type const comp35 = comp3 + comp4 + comp5;\n\n        return b * b * x_diff * (comp02 - comp35);\n        */\n\n        return_type const comp0_min = c1 / (c1 - e2 * sin_y_min * sin_y_min);\n        return_type const comp0_max = c1 / (c1 - e2 * sin_y_max * sin_y_max);\n\n        // NOTE: For latitudes equal to 0 the original formula returns NAN\n        return_type comp1_min = 0, comp1_max = 0;\n        if (e2 > c0)\n        {\n            return_type const e = math::sqrt(e2);\n            return_type const e_sin_y_min = e * sin_y_min;\n            return_type const e_sin_y_max = e * sin_y_max;\n\n            comp1_min = e_sin_y_min == c0 ? c1 : atanh(e_sin_y_min) / e_sin_y_min;\n            comp1_max = e_sin_y_max == c0 ? c1 : atanh(e_sin_y_max) / e_sin_y_max;\n        }\n        else\n        {\n            return_type const ea = math::sqrt(-e2);\n            return_type const ea_sin_y_min = ea * sin_y_min;\n            return_type const ea_sin_y_max = ea * sin_y_max;\n\n            comp1_min = ea_sin_y_min == c0 ? c1 : atan(ea_sin_y_min) / ea_sin_y_min;\n            comp1_max = ea_sin_y_max == c0 ? c1 : atan(ea_sin_y_max) / ea_sin_y_max;\n        }\n\n        return_type const comp01_min = sin_y_min * (comp0_min + comp1_min);\n        return_type const comp01_max = sin_y_max * (comp0_max + comp1_max);\n\n        return b * b * x_diff * (comp01_max - comp01_min) / c2;\n    }\n\n    Spheroid model() const\n    {\n        return m_spheroid;\n    }\n\nprivate:\n    Spheroid m_spheroid;\n};\n\n\n}} // namespace strategy::area\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGY_GEOGRAPHIC_AREA_BOX_HPP\n", "meta": {"hexsha": "6c0943e0911774d1114d1ecb5865905c9ebfec7e", "size": 6787, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/strategy/geographic/area_box.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/geometry/strategy/geographic/area_box.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "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": "lib/boost_1.78.0/boost/geometry/strategy/geographic/area_box.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 35.3489583333, "max_line_length": 95, "alphanum_fraction": 0.64328864, "num_tokens": 1890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6261566224899218}}
{"text": "#include <math.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n\n#define M_SQRT5 2.2360679774997896964091736687313\n#define M_1_16 0.0625\n\n#define P(a, b) velocity(a, b)\n#define O(a, b) velocity(b, a)\n\nusing Eigen::MatrixXd;\n\n/*\n\nvar s = `Eigen::MatrixXf m(${pointsX.length}, 2);\\nm << `; for (var i = 0; i < pointsX.length; i++) s += pointsX[i] + \", \" + pointsY[i] + (i == pointsX.length-1 ? \";\" : \",\\n\")\n\nhttp://weitz.de/hobby/\n\n\n*/\n\nfloat velocity(float a, float b)\n{\n    float cosa = cosf(a);\n    float cosb = cosf(b);\n\n    float sina = sinf(a);\n    float sinb = sinf(b);\n\n    return (4. + 2. * M_SQRT2 * (sina - M_1_16 * sinb) * (sinb - M_1_16 * sina) * (cosa - cosb)) /\n           (2. + (M_SQRT5 - 1) * cosa + (3. - M_SQRT5) * cosb);\n}\n\nEigen::MatrixXf calcVectors(Eigen::MatrixXf m)\n{\n    Eigen::MatrixXf v = Eigen::MatrixXf::Zero(m.rows() - 1, 2);\n    for (int i = 1; i < m.rows(); i++)\n    {\n        float dx = m(i, 0) - m(i - 1, 0);\n        float dy = m(i, 1) - m(i - 1, 1);\n\n        v(i - 1, 0) = dx;\n        v(i - 1, 1) = dy;\n    }\n\n    return v;\n}\n\nEigen::VectorXf calcDistances(Eigen::MatrixXf m)\n{\n    Eigen::VectorXf d = Eigen::VectorXf::Zero(m.rows());\n\n    for (int i = 0; i < m.rows(); i++)\n    {\n        d[i] = sqrtf(m(i, 0) * m(i, 0) + m(i, 1) * m(i, 1));\n    }\n\n    return d;\n}\n\nEigen::VectorXf calcAngles(Eigen::MatrixXf m, Eigen::VectorXf d)\n{\n    assert(m.rows() == d.rows());\n\n    Eigen::VectorXf a = Eigen::VectorXf::Zero(m.rows() + 1);\n\n    for (int i = 1; i < m.rows(); i++)\n    {\n        // credtig goes to: https://de.mathworks.com/matlabcentral/answers/180131-how-can-i-find-the-angle-between-two-vectors-including-directional-information\n        float x1 = m(i - 1, 0);\n        float y1 = m(i - 1, 1);\n\n        float x2 = m(i, 0);\n        float y2 = m(i, 1);\n\n        a[i] = atan2f(x1 * y2 - y1 * x2, x1 * x2 + y1 * y2);\n    }\n\n    // last angle is zero\n\n    return a;\n}\n\n// Vectors a, b, c and d are const. They will not be modified\n// by the function. Vector f (the solution vector) is non-const\n// and thus will be calculated and updated by the function.\nvoid thomas_algorithm(const Eigen::VectorXf &a,\n                      const Eigen::VectorXf &b,\n                      const Eigen::VectorXf &c,\n                      const Eigen::VectorXf &d,\n                      Eigen::VectorXf &x)\n{\n    Eigen::Index N = c.rows();\n\n    // Create the temporary vectors\n    // Note that this is inefficient as it is possible to call\n    // this function many times. A better implementation would\n    // pass these temporary matrices by non-const reference to\n    // save excess allocation and deallocation\n    std::vector<float> c_star(N, 0.0);\n    std::vector<float> d_star(N, 0.0);\n\n    // This updates the coefficients in the first row\n    // Note that we should be checking for division by zero here\n    c_star[0] = c[0] / b[0];\n    d_star[0] = d[0] / b[0];\n\n    // Create the c_star and d_star coefficients in the forward sweep\n    for (int i = 1; i < N; i++)\n    {\n\n        float m = (b[i] - a[i] * c_star[i - 1]);\n        c_star[i] = c[i] / m;\n        d_star[i] = (d[i] - a[i] * d_star[i - 1]) / m;\n    }\n\n    // This is the reverse sweep, used to update the solution vector f\n    x[N - 1] = d_star[N - 1];\n    for (int i = N - 2; i >= 0; i--)\n    {\n        x[i] = d_star[i] - c_star[i] * x[i + 1];\n    }\n}\n\nvoid solveAlpha(const Eigen::VectorXf &d, const Eigen::VectorXf &g, Eigen::VectorXf &alpha)\n{\n    assert(d.rows() + 1 == g.rows());\n\n    Eigen::Index N = g.rows();\n\n    Eigen::VectorXf a = Eigen::VectorXf::Zero(N);\n    Eigen::VectorXf b = Eigen::VectorXf::Zero(N);\n    Eigen::VectorXf c = Eigen::VectorXf::Zero(N);\n    Eigen::VectorXf dd = Eigen::VectorXf::Zero(N);\n\n    for (int i = 1; i < (N - 1); i++)\n    {\n        a[i] = 1 / d[i - 1];\n        b[i] = (2 * d[i - 1] + 2 * d[i]) / (d[i - 1] * d[i]);\n        c[i] = 1 / d[i];\n        dd[i] = -(2 * g[i] * d[i] + g[i + 1] * d[i - 1]) / (d[i - 1] * d[i]);\n    }\n\n    float omega = 1.;\n    b[0] = 2. + omega;\n    c[0] = 2. * omega + 1.;\n    dd[0] = -c[0] * g[1];\n    a[N - 1] = 2. * omega + 1.;\n    b[N - 1] = 2. + omega;\n    dd[N - 1] = 0.;\n\n    thomas_algorithm(a, b, c, dd, alpha);\n}\n\nint main()\n{\n    Eigen::MatrixXf m(9, 2);\n    m << 61.21672821044922, 309.6958312988281,\n        263.11785888671875, 680.9885864257812,\n        509.5057067871094, 653.6121826171875,\n        807.2243041992188, 415.77947998046875,\n        300.7604675292969, 424.3345947265625,\n        141.63497924804688, 723.7642822265625,\n        206.65399169921875, 290.87451171875,\n        182.69961547851562, 545.8175048828125,\n        839.7338256835938, 602.2813720703125;\n\n    Eigen::Index N = m.rows();\n\n    // test velocity function\n    float test = P(1.2, 0.5) - O(0.5, 1.2);\n    printf(\"test [should be 0]: %f\\n\", test);\n\n    // calculate vectors\n    Eigen::MatrixXf v = calcVectors(m);\n    std::cout << \"Vectors:\" << std::endl;\n    std::cout << v << std::endl;\n\n    // calculate distances\n    Eigen::VectorXf d = calcDistances(v);\n    std::cout << \"Distances:\" << std::endl;\n    std::cout << d << std::endl;\n\n    // calculate angles\n    Eigen::VectorXf g = calcAngles(v, d);\n    std::cout << \"Gamma Angles:\" << std::endl;\n    std::cout << g << std::endl;\n\n    // prepare thomas algorithm\n    Eigen::VectorXf alpha = Eigen::VectorXf::Zero(N);\n    solveAlpha(d, g, alpha);\n    std::cout << \"Alpha Angles:\" << std::endl;\n    std::cout << alpha << std::endl;\n\n    // calculate beta, a, b, sx, sy\n    Eigen::VectorXf beta = Eigen::VectorXf::Zero(N);\n    Eigen::VectorXf a = Eigen::VectorXf::Zero(N);\n    Eigen::VectorXf b = Eigen::VectorXf::Zero(N);\n\n    Eigen::VectorXf sx1 = Eigen::VectorXf::Zero(N);\n    Eigen::VectorXf sy1 = Eigen::VectorXf::Zero(N);\n    Eigen::VectorXf sx2 = Eigen::VectorXf::Zero(N);\n    Eigen::VectorXf sy2 = Eigen::VectorXf::Zero(N);\n\n    for (int i = 0; i < N - 1; i++)\n    {\n        if (i < N - 2)\n        {\n            beta[i] = -alpha[i + 1] - g[i + 1];\n        }\n        else\n        {\n            beta[i] = -alpha[N - 1];\n        }\n\n        a[i] = P(alpha[i], beta[i]) * d[i] / 3.;\n        b[i] = O(alpha[i], beta[i]) * d[i] / 3.;\n\n        Eigen::Vector2f t(v(i, 0), v(i, 1));\n\n        Eigen::Vector2f v1(m(i, 0), m(i, 1));\n        Eigen::Vector2f v2(m(i + 1, 0), m(i + 1, 1));\n\n        Eigen::Rotation2D<float> rotAlpha(alpha[i]);\n        Eigen::Rotation2D<float> rotBeta(-beta[i]);\n\n        Eigen::Vector2f t1 = v1 + (rotAlpha * t).normalized() * a[i];\n        Eigen::Vector2f t2 = v2 - (rotBeta * t).normalized() * b[i];\n\n        sx1[i] = t1(0);\n        sy1[i] = t1(1);\n        sx2[i] = t2(0);\n        sy2[i] = t2(1);\n    }\n\n    std::cout << \"Beta Angles:\" << std::endl;\n    std::cout << beta << std::endl;\n\n    std::cout << \"a:\" << std::endl;\n    std::cout << a << std::endl;\n\n    std::cout << \"b:\" << std::endl;\n    std::cout << b << std::endl;\n\n    // print html stuff for chrome\n\n    std::cout << \"var canvas = document.createElement('canvas');\\n\"\n              << \"\\n\"\n              << \"document.body = document.createElement('body');\\n\"\n              << \"document.body.append(canvas);\\n\"\n              << \"\\n\"\n              << \"canvas.width = document.body.clientWidth;\\n\"\n              << \"canvas.height = document.body.clientHeight;\\n\"\n              << \"\\n\"\n              << \"var ctx = canvas.getContext('2d');\\n\"\n              << \"\\n\"\n              << \"ctx.beginPath();\\n\"\n              << \"\\n\";\n\n    std::ostringstream bezierString;\n    std::ostringstream pointString;\n\n    bezierString << \"ctx.moveTo(\" << m(0, 0) << \",\" << m(0, 1) << \");\\n\\n\";\n    pointString << \"ctx.beginPath(); ctx.arc(\"\n                << m(0, 0) << \",\" << m(0, 1)\n                << \", 5, 0, 2 * Math.PI, false); ctx.fill();\\n\";\n\n    for (int i = 0; i < N - 1; i++)\n    {\n        bezierString << \"ctx.bezierCurveTo(\"\n                     << sx1(i) << \",\" << sy1(i) << \",\"\n                     << sx2(i) << \",\" << sy2(i) << \",\"\n                     << m(i + 1, 0) << \",\" << m(i + 1, 1) << \");\\n\";\n\n        pointString << \"ctx.beginPath(); ctx.arc(\"\n                    << m(i + 1, 0) << \",\" << m(i + 1, 1)\n                    << \", 5, 0, 2 * Math.PI, false); ctx.fill();\\n\";\n    }\n\n    bezierString << \"\\nctx.stroke();\\n\\n\";\n\n    std::cout << bezierString.str() << pointString.str();\n\n    return 0;\n}", "meta": {"hexsha": "21e8f5fb82db20e1fa9113bcf37a33bc4473ce7f", "size": 8295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "playground/hobby/main.cpp", "max_stars_repo_name": "whymatter/albatross", "max_stars_repo_head_hexsha": "9e5455c8186d2cba9d5a5afdbb234c695200a5b4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-11T08:01:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T08:01:23.000Z", "max_issues_repo_path": "playground/hobby/main.cpp", "max_issues_repo_name": "whymatter/albatross", "max_issues_repo_head_hexsha": "9e5455c8186d2cba9d5a5afdbb234c695200a5b4", "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": "playground/hobby/main.cpp", "max_forks_repo_name": "whymatter/albatross", "max_forks_repo_head_hexsha": "9e5455c8186d2cba9d5a5afdbb234c695200a5b4", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0034965035, "max_line_length": 175, "alphanum_fraction": 0.5091018686, "num_tokens": 2828, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.6791786991753931, "lm_q1q2_score": 0.6261496681672606}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <typeinfo>\n#include <iostream>\n#include <cassert>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace std;\n    using mtl::lazy; using mtl::io::tout;\n    typedef mtl::dense_vector<double> vt;\n    \n    mtl::compressed2D<double> A0;\n    laplacian_setup(A0, 4, 15);\n    tout << \"A0 is\\n\" << A0 << endl;\n\n    vt v(60);\n    iota(v);\n    tout << \"v is \" << v << endl;\n\n    vt w1(A0 * v);\n    tout << \"A0 * v is \" << w1 << endl;\n\n    mtl::mat::poisson2D_dirichlet A(4, 15);\n    vt  w2(60);\n    w2= A * v;\n    tout << \"A * v is \" << w2 << endl;\n\n    if (one_norm(vt(w1 - w2)) > 0.001) throw \"Wrong result\";\n\n    w2+= A * v;\n    tout << \"w2+= A * v is \" << w2 << endl;\n    if (one_norm(vt(w1 + w1 - w2)) > 0.001) throw \"Wrong result\";\n\n    w2-= A * v;\n    tout << \"w2-= A * v is \" << w2 << endl;\n    if (one_norm(vt(w1 - w2)) > 0.001) throw \"Wrong result\";\n\n    vt w3( w2 - A * v );\n    double alpha;\n    (lazy(w3)= A * v) || (lazy(alpha)= lazy_dot(w3, v));\n\n    return 0;\n}\n", "meta": {"hexsha": "0747b4175a3de2d1afee45798d1eb318259c7043", "size": 1448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_free_3_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/matrix_free_3_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/matrix_free_3_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 25.8571428571, "max_line_length": 94, "alphanum_fraction": 0.5732044199, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6259752653609806}}
{"text": "#pragma once\n#include <Eigen/Dense>\n\nnamespace OneACPose {\n\n  using Vec2 = Eigen::Vector2d;\n  using Vec3 = Eigen::Vector3d;\n\n  using Mat2 = Eigen::Matrix2d;\n  using Mat3 = Eigen::Matrix3d;\n\n  using Mat23 = Eigen::Matrix<double, 2, 3>;\n  using Mat32 = Eigen::Matrix<double, 3, 2>;\n  using Mat34 = Eigen::Matrix<double, 3, 4>;\n\n  using RowVec2 = Eigen::Matrix<double, 1, 2, Eigen::RowMajor>;\n  using RowVec3 = Eigen::Matrix<double, 1, 3, Eigen::RowMajor>;\n  \n}", "meta": {"hexsha": "7fce315d082d5e5a43a9f8db3c8d10408e21d204", "size": 458, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/OneACPose/types.hpp", "max_stars_repo_name": "eivan/one-ac-pose", "max_stars_repo_head_hexsha": "79451626238f47130578c18b65e37cabd7332de1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-07-31T19:12:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T14:34:48.000Z", "max_issues_repo_path": "src/OneACPose/types.hpp", "max_issues_repo_name": "eivan/OneAC", "max_issues_repo_head_hexsha": "79451626238f47130578c18b65e37cabd7332de1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OneACPose/types.hpp", "max_forks_repo_name": "eivan/OneAC", "max_forks_repo_head_hexsha": "79451626238f47130578c18b65e37cabd7332de1", "max_forks_repo_licenses": ["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.1052631579, "max_line_length": 63, "alphanum_fraction": 0.672489083, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6259752542286826}}
{"text": "/*\nput generic functions in this file.\nvector operation::\n* dot product\n*= inplace scalar or elementwise multiplication\n/= inplace elementwise division\n+= inplace vector addition\n-= inplace vector substraction\n\nmatrix operation::\n+= inplace matrix addition\n/= usage: matrix /= cons\n*= usage: matrix *= cons\n*/\n#pragma once\n\n#include <cstddef>\n#include <string>\n#include <vector>\n#include <ctime>\n#include <cmath>\n#include <cstdlib>\n#include <sstream>\n#include <limits>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\ntypedef std::vector<double> vec_double;\ntypedef std::vector<std::vector<double>> matrix;\ntypedef std::vector<std::vector<double>> matrix_double;\n\ninline std::string vec_to_str(const vec_double& v) {\n    std::string str(\"\");\n    for (auto& x : v) {\n        str += std::to_string(x);\n        str += \" \";\n    }\n    return str;\n}\n\ninline std::string matrix_to_str(matrix_double& m){\n    std::stringstream ss;\n    ss.precision(2);\n    for(auto& row : m){\n        for(auto& ele : row){\n            ss<< ele <<\" \";\n        }\n        ss << \"\\n\";\n    }\n    return ss.str();\n}\n\ninline matrix_double& operator+= (matrix_double& m1, const matrix_double& m2){\n    //for debug \n    if(m1.size() != m2.size()){\n        std::cout<<\"different size!\"<<std::endl;\n        std::cout<<\"m1 \"<<m1.size()<<\" \";\n        for(size_t x = 0; x < m1.size(); x++){\n            std::cout<<m1[x].size()<<\" \";\n        }\n        std::cout<<std::endl<<\"m2 \"<<m2.size()<<\" \";\n        for(size_t x = 0; x < m2.size(); x++){\n            std::cout<<m2[x].size()<<\" \";\n        }\n        std::cout<<std::endl;\n    }\n    //end\n    \n    for(size_t r = 0; r < m1.size(); r++){\n        for(size_t c = 0; c < m1[r].size(); c++){\n            m1[r][c] += m2[r][c];\n        }\n    }\n    return m1;\n}\n\ninline matrix_double& operator/= (matrix_double& m, const double coe){\n    for(size_t r = 0; r < m.size(); r++){\n        for(size_t c = 0; c < m[r].size(); c++){\n            m[r][c] /= coe;\n        }\n    }\n    return m;\n}\ninline matrix_double& operator*= (matrix_double& m, const double coe){\n    for(size_t r = 0; r < m.size(); r++){\n        for(size_t c = 0; c < m[r].size(); c++){\n            m[r][c] *= coe;\n        }\n    }\n    return m;\n}\n\ninline matrix_double operator*(const matrix_double& m, const double coe){\n    matrix_double result;\n    for(size_t r = 0; r < m.size(); r++){\n        result.push_back(vec_double(m[r].size(), 0));\n        for(size_t c = 0; c < m[r].size(); c++){\n            result[r][c] = m[r][c] * coe;\n        }\n    }\n    return result;\n}\n\n/*\ninline matrix& operator+= (matrix& ma, const matrix& mb) {\n\n    int m = ma.size();\n    int n = ma[0].size();\n    for (int i=0; i < m; i++)\n      for (int j=0; j< n; j++)\n        ma[i][j] += mb[i][j];\n    return ma;\n}\n*/\n\ninline double sum(const vec_double& v){\n  double result = 0;\n  for(auto ele : v){\n    result += ele;\n  }\n  return result;\n}\n// Inner Product : tolerance the case where length(va) <= length(vb)\ninline double operator* (const vec_double& va, const vec_double& vb) {\n    int n = va.size();\n    double sum = 0.0;\n    for (int i=0; i < n; i++) sum += va[i] * vb[i];\n    return sum;\n}\n\n// Vector Addition\ninline vec_double& operator+= (vec_double& va, const vec_double& vb) {\n    int n = va.size();\n    for (int i=0; i < n; i++) va[i] += vb[i];\n    return va;\n}\ninline vec_double operator+ (const vec_double& va, const vec_double& vb) {\n    int n = va.size();\n    vec_double result(n, 0.0);\n    for (int i=0; i < n; i++) result[i] = va[i] + vb[i];\n    return result;\n}\n\ninline vec_double& operator-= (vec_double& va, const vec_double& vb) {\n    int n = va.size();\n    for (int i=0; i < n; i++) va[i] -= vb[i];\n    return va;\n}\n\n// Scalar multiplication and division\ninline vec_double& operator*= (vec_double& va, const double& c) {\n    int n = va.size();\n    for (int i=0; i < n; i++) va[i] *= c;\n    return va;\n}\ninline vec_double operator* (const double& c, const vec_double& va) {\n    int n = va.size();\n    vec_double result(n, 0.0);\n    for (int i=0; i < n; i++) result[i] = va[i] * c;\n    return result;\n}\ninline vec_double& operator/= (vec_double& va, const double& c) {\n    int n = va.size();\n    for (int i=0; i < n; i++) va[i] /= c;\n    return va;\n}\n// elementwise division\ninline vec_double& operator /=(vec_double& a, const vec_double& b)\n{\n    std::size_t a_size = a.size();\n    for(std::size_t i = 0; i < a_size; i++)\n    {\n        a[i] = a[i]/b[i];\n    }\n    return a;\n}\n// elementwise multiplcation\ninline vec_double& operator *=(vec_double& a, const vec_double& b)\n{\n    std::size_t a_size = a.size();\n    for(std::size_t i = 0; i < a_size; i++)\n    {\n        a[i] = a[i]*b[i];\n    }\n    return a;\n}\n\n\n\nnamespace ublas = boost::numeric::ublas;\n/* Matrix inversion routine.\n   Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */\ntemplate<class T>\nbool InvertMatrix (const ublas::matrix<T>& input, ublas::matrix<T>& inverse) {\n\n typedef ublas::permutation_matrix<std::size_t> pmatrix;\n // create a working copy of the input\n ublas::matrix<T> A(input);\n // create a permutation matrix for the LU-factorization\n pmatrix pm(A.size1());\n // perform LU-factorization\n int res = lu_factorize(A,pm);\n       if( res != 0 ) return false;\n // create identity matrix of \"inverse\"\n inverse.assign(ublas::identity_matrix<T>(A.size1()));\n // backsubstitute to get the inverse\n lu_substitute(A, pm, inverse);\n return true;\n}\n\n\ninline bool MatrixInversion(matrix& input){\n  int n=input.size();\n  ublas::matrix<double> input2 (n,n);\n  ublas::matrix<double> output2 (n,n);\n  for(int i=0;i<n;i++){\n    for(int j=0;j<n;j++){\n      input2(i,j)=input[i][j];\n    }\n  }\n\n  if(!InvertMatrix(input2,output2))\n    return false;\n\n\n  for(int i=0;i<n;i++){\n    for(int j=0;j<n;j++){\n      input[i][j]=output2(i,j);\n    }\n  }\n}\n\ninline void MatrixVectormultiplication(const matrix& A,const vec_double& B,vec_double& output){\n  int m=A.size();\n  int n=A[0].size();\n  for(int i=0;i<m;i++){\n    for(int j=0;j<n;j++){\n      output[i]+=A[i][j]*B[j];\n    }\n  }\n\n\n}\n", "meta": {"hexsha": "85be651a1a1876858ce6bc426ee55c4deed5226a", "size": 6220, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mllib/Utility.hpp", "max_stars_repo_name": "Christina-hshi/Boosting-with-Husky", "max_stars_repo_head_hexsha": "1744f0c90567a969d3e50d19f27f358f5865d2f6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T02:10:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-23T02:10:10.000Z", "max_issues_repo_path": "mllib/Utility.hpp", "max_issues_repo_name": "Christina-hshi/Boosting-with-Husky", "max_issues_repo_head_hexsha": "1744f0c90567a969d3e50d19f27f358f5865d2f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mllib/Utility.hpp", "max_forks_repo_name": "Christina-hshi/Boosting-with-Husky", "max_forks_repo_head_hexsha": "1744f0c90567a969d3e50d19f27f358f5865d2f6", "max_forks_repo_licenses": ["Apache-2.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.9799196787, "max_line_length": 95, "alphanum_fraction": 0.579903537, "num_tokens": 1836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6259154440669451}}
{"text": "// Original source code from:\n// https://github.com/stegua/MyBlogEntries/tree/master/Dijkstra\n\n/// My typedefs\n#include <boost/cstdint.hpp>\n#include <boost/integer_traits.hpp>\n#include <inttypes.h>\n\ntypedef int32_t node_t;\ntypedef int32_t edge_t;\ntypedef int64_t cost_t;\n\n/// From STL library\n#include <fstream>\n\n#include <vector>\nusing std::vector;\n\n#include <string>\n\nusing std::make_pair;\nusing std::pair;\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/graph_traits.hpp>\nusing namespace boost;\n\ntypedef adjacency_list<vecS, vecS, directedS, no_property,\n                       property<edge_weight_t, cost_t>>\n    Digraph;\ntypedef graph_traits<Digraph>::vertex_descriptor Node;\ntypedef graph_traits<Digraph>::edge_descriptor Arc;\n\n/// Boost Timer\n#include <boost/progress.hpp>\nusing boost::timer;\n\nusing namespace boost;\n\n/// Read input data, build graph, and run Dijkstra\ncost_t runDijkstra(char *argv[]) {\n  /// Read instance from the OR-lib\n  std::ifstream infile(argv[1]);\n  if (!infile)\n    exit(EXIT_FAILURE);\n\n  int n; /// Number of variables\n  int m; /// Number of constraints\n\n  // reads file of the form\n  // #nodes #edges\n  // e_1 = v_i v_j cost[e_m]\n  // ..\n  // e_m = v_i v_j cost[e_m]\n\n  /// Read the first line\n  infile >> n >> m;\n  fprintf(stdout, \"n %d, m %d\\n\", n, m);\n  /// Build the graph\n  Digraph G(n);\n\n  int v, w;\n  cost_t c;\n  for (int i = 0; i < m; i++) {\n    infile >> v >> w >> c;\n    add_edge(v - 1, w - 1, c, G);\n  }\n\n  vector<Node> P(n);\n  vector<cost_t> D(n, std::numeric_limits<cost_t>::max());\n  cost_t T_dist;\n\n  timer TIMER;\n  for (int i = 0; i < 50; ++i) {\n    double t0 = TIMER.elapsed();\n    node_t S = i;\n    node_t T = n - 1 - i;\n    dijkstra_shortest_paths(G, S, predecessor_map(&P[0]).distance_map(&D[0]));\n    T_dist = D[T];\n    fprintf(stdout, \"Time %.4f Cost %\" PRId64 \"\\n\", TIMER.elapsed() - t0,\n            T_dist);\n  }\n  fprintf(stdout, \"Tot %.4f\\n\", TIMER.elapsed());\n\n  return T_dist;\n}\n\n///------------------------------------------------------------------------------------------\n/// Main function\nint main(int argc, char **argv) {\n  if (argc != 2) {\n    fprintf(stdout, \"usage: ./dijkstra <filename>\\n\");\n    exit(EXIT_FAILURE);\n  }\n  /// Measure overall time\n  timer TIMER;\n  /// Invoke the different Dijkstra algorithm implementations\n  cost_t T_dist = runDijkstra(argv);\n  /// Print basic figures\n  fprintf(stdout, \"Cost %\" PRId64 \" - Time %.3f\\n\", T_dist, TIMER.elapsed());\n\n  return 0;\n}\n", "meta": {"hexsha": "bd4765d3cdef2491834864a29f6b508c5094fad6", "size": 2519, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/dijkstra_bgl.cc", "max_stars_repo_name": "torressa/cpp_graph_benchmarks", "max_stars_repo_head_hexsha": "f1a39024afb09a476e431e019bdbcac1ea4aa76d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dijkstra_bgl.cc", "max_issues_repo_name": "torressa/cpp_graph_benchmarks", "max_issues_repo_head_hexsha": "f1a39024afb09a476e431e019bdbcac1ea4aa76d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dijkstra_bgl.cc", "max_forks_repo_name": "torressa/cpp_graph_benchmarks", "max_forks_repo_head_hexsha": "f1a39024afb09a476e431e019bdbcac1ea4aa76d", "max_forks_repo_licenses": ["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.9904761905, "max_line_length": 93, "alphanum_fraction": 0.6248511314, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6258500314978878}}
{"text": "/*=============================================================================\n\n  NifTK: A software platform for medical image computing.\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include \"niftkPointUtils.h\"\n#include <mitkCommon.h>\n#include <cmath>\n#include <boost/math/special_functions/fpclassify.hpp>\n\nnamespace niftk\n{\n\n//-----------------------------------------------------------------------------\ndouble CalculateStepSize(double *spacing)\n{\n  double stepSize = 0;\n  double smallestDimension = std::numeric_limits<double>::max();\n\n  for (int i = 0; i< 3; i++)\n  {\n    if (spacing[i] < smallestDimension)\n    {\n      smallestDimension = spacing[i];\n    }\n  }\n  stepSize = smallestDimension / 3.0;\n  return stepSize;\n}\n\n\n//-----------------------------------------------------------------------------\nbool AreDifferent(const mitk::Point3D& a, const mitk::Point3D& b)\n{\n  bool areDifferent = false;\n\n  for (int i = 0; i < 3; i++)\n  {\n    if (fabs(a[i] - b[i]) > 0.01)\n    {\n      areDifferent = true;\n      break;\n    }\n  }\n\n  return areDifferent;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble GetSquaredDistanceBetweenPoints(const mitk::Point3D& a, const mitk::Point3D& b)\n{\n    double distance = 0;\n\n    for (int i = 0; i < 3; i++)\n    {\n      distance += (a[i] - b[i])*(a[i] - b[i]);\n    }\n\n    return distance;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble GetRMSErrorBetweenPoints(\n  const mitk::PointSet& fixedPoints,\n  const mitk::PointSet& movingPoints,\n  const CoordinateAxesData * const transform)\n{\n  mitk::PointSet::DataType* itkPointSet = movingPoints.GetPointSet();\n  mitk::PointSet::PointsContainer* points = itkPointSet->GetPoints();\n  mitk::PointSet::PointsIterator pIt;\n  mitk::PointSet::PointIdentifier pointID;\n  mitk::PointSet::PointType fixedPoint;\n  mitk::PointSet::PointType movingPoint;\n  mitk::PointSet::PointType transformedMovingPoint;\n\n  double rmsError = 0;\n  unsigned long int numberOfPointsUsed = 0;\n\n  for (pIt = points->Begin(); pIt != points->End(); ++pIt)\n  {\n    pointID = pIt->Index();\n    movingPoint = movingPoints.GetPoint(pointID);\n\n    if (fixedPoints.GetPointIfExists(pointID, &fixedPoint))\n    {\n      if (transform != NULL)\n      {\n        transformedMovingPoint = transform->MultiplyPoint(movingPoint);\n        rmsError += GetSquaredDistanceBetweenPoints(fixedPoint, transformedMovingPoint);\n      }\n      else\n      {\n        rmsError += GetSquaredDistanceBetweenPoints(fixedPoint, movingPoint);\n      }\n      numberOfPointsUsed++;\n    }\n  }\n  if (numberOfPointsUsed > 0)\n  {\n    rmsError /= static_cast<double>(numberOfPointsUsed);\n    rmsError = sqrt(rmsError);\n  }\n  else\n  {\n    rmsError = 0;\n  }\n  return rmsError;\n}\n\n\n//-----------------------------------------------------------------------------\nvoid GetDifference(const mitk::Point3D& a, const mitk::Point3D& b, mitk::Point3D& output)\n{\n  for (int i = 0; i < 3; i++)\n  {\n    output[i] = a[i] - b[i];\n  }\n}\n\n\n//-----------------------------------------------------------------------------\ndouble Length(mitk::Point3D& vector)\n{\n  double length = 0;\n  for (int i = 0; i < 3; i++)\n  {\n    length += vector[i]*vector[i];\n  }\n  if (length > 0)\n  {\n    length = sqrt(length);\n  }\n  return length;\n}\n\n\n//-----------------------------------------------------------------------------\nvoid Normalise(mitk::Point3D& vector)\n{\n  double length = Length(vector);\n  if (length > 0)\n  {\n    for (int i = 0; i < 3; i++)\n    {\n      vector[i] /= length;\n    }\n  }\n}\n\n\n//-----------------------------------------------------------------------------\ndouble FindLargestDistanceBetweenTwoPoints(const mitk::PointSet& input)\n{\n  double maxSquaredDistance = 0;\n\n  mitk::PointSet::PointsContainer* inputContainer = input.GetPointSet()->GetPoints();\n  mitk::PointSet::PointsConstIterator outerIt = inputContainer->Begin();\n  mitk::PointSet::PointsConstIterator innerIt = inputContainer->Begin();\n  mitk::PointSet::PointsConstIterator iterEnd = inputContainer->End();\n\n  for ( ; outerIt != iterEnd; ++outerIt)\n  {\n    for ( ; innerIt != iterEnd; ++innerIt)\n    {\n      double squaredDistance = GetSquaredDistanceBetweenPoints(input.GetPoint(outerIt->Index()), input.GetPoint(innerIt->Index()));\n      if (squaredDistance > maxSquaredDistance)\n      {\n        maxSquaredDistance = squaredDistance;\n      }\n    }\n  }\n  return sqrt(maxSquaredDistance);\n}\n\n\n//-----------------------------------------------------------------------------\nint CopyPointSets(const mitk::PointSet& input, mitk::PointSet& output)\n{\n  output.Clear();\n\n  mitk::PointSet::PointsContainer* inputContainer = input.GetPointSet()->GetPoints();\n  mitk::PointSet::PointsConstIterator inputIt = inputContainer->Begin();\n  mitk::PointSet::PointsConstIterator inputEnd = inputContainer->End();\n  for ( ; inputIt != inputEnd; ++inputIt)\n  {\n    output.InsertPoint(inputIt->Index(), input.GetPoint(inputIt->Index()));\n  }\n  return output.GetSize();\n}\n\n\n//-----------------------------------------------------------------------------\nvoid ScalePointSets(const mitk::PointSet& input, mitk::PointSet& output, double scaleFactor)\n{\n  output.Clear();\n\n  mitk::PointSet::PointsContainer* inputContainer = input.GetPointSet()->GetPoints();\n  mitk::PointSet::PointsConstIterator inputIt = inputContainer->Begin();\n  mitk::PointSet::PointsConstIterator inputEnd = inputContainer->End();\n  mitk::PointSet::PointType point;\n\n  for ( ; inputIt != inputEnd; ++inputIt)\n  {\n    point = input.GetPoint(inputIt->Index());\n    point[0] *= scaleFactor;\n    point[1] *= scaleFactor;\n    point[2] *= scaleFactor;\n\n    output.InsertPoint(inputIt->Index(), point);\n  }\n}\n\n\n//-----------------------------------------------------------------------------\nvoid CopyValues(const mitk::Point3D& a, mitk::Point3D& b)\n{\n  for (int i = 0; i < 3; i++)\n  {\n    b[i] = a[i];\n  }\n}\n\n\n//-----------------------------------------------------------------------------\nvoid CrossProduct(const mitk::Point3D& a, const mitk::Point3D& b, mitk::Point3D& c)\n{\n  mitk::Point3D aCopy;\n  mitk::Point3D bCopy;\n  CopyValues(a, aCopy);\n  CopyValues(b, bCopy);\n  Normalise(aCopy);\n  Normalise(bCopy);\n\n  c[0] = aCopy[1]*bCopy[2] - bCopy[1]*aCopy[2];\n  c[1] = -1 * (aCopy[0]*bCopy[2] - bCopy[0]*aCopy[2]);\n  c[2] = aCopy[0]*bCopy[1] - bCopy[0]*aCopy[1];\n}\n\n\n//-----------------------------------------------------------------------------\nvoid ComputeNormalFromPoints(const mitk::Point3D& a, const mitk::Point3D& b, const mitk::Point3D& c, mitk::Point3D& output)\n{\n  mitk::Point3D aMinusB;\n  mitk::Point3D cMinusB;\n  GetDifference(a, b, aMinusB);\n  GetDifference(c, b, cMinusB);\n  CrossProduct(aMinusB, cMinusB, output);\n  Normalise(output);\n}\n\n\n//-----------------------------------------------------------------------------\nvoid TransformPointByVtkMatrix(\n    const vtkMatrix4x4* matrix,\n    const bool& isNormal,\n    mitk::Point3D& point\n    )\n{\n  double transformedPoint[4] = {0, 0, 0, 1};\n  vtkMatrix4x4* nonConstMatrix = const_cast<vtkMatrix4x4*>(matrix);\n\n  if(nonConstMatrix != NULL)\n  {\n    transformedPoint[0] = point[0];\n    transformedPoint[1] = point[1];\n    transformedPoint[2] = point[2];\n    transformedPoint[3] = 1;\n\n    nonConstMatrix->MultiplyPoint(transformedPoint, transformedPoint);\n\n    point[0] = transformedPoint[0];\n    point[1] = transformedPoint[1];\n    point[2] = transformedPoint[2];\n\n    if (isNormal)\n    {\n      double transformedOrigin[4] = {0, 0, 0, 1};\n      nonConstMatrix->MultiplyPoint(transformedOrigin, transformedOrigin);\n\n      point[0] = point[0] - transformedOrigin[0];\n      point[1] = point[1] - transformedOrigin[1];\n      point[2] = point[2] - transformedOrigin[2];\n    }\n  }\n}\n\n\n//-----------------------------------------------------------------------------\nvoid TransformPointsByVtkMatrix(\n    const mitk::PointSet& input,\n    const vtkMatrix4x4& matrix,\n    mitk::PointSet& output\n    )\n{\n  mitk::PointSet::DataType* itkPointSet = input.GetPointSet();\n  mitk::PointSet::PointsContainer* points = itkPointSet->GetPoints();\n  mitk::PointSet::PointsIterator pIt;\n  mitk::PointSet::PointIdentifier pointID;\n  mitk::PointSet::PointType point;\n\n  output.Clear();\n\n  for (pIt = points->Begin(); pIt != points->End(); ++pIt)\n  {\n    pointID = pIt->Index();\n    point = input.GetPoint(pointID);\n    TransformPointByVtkMatrix(&matrix, false, point);\n    output.InsertPoint(pointID, point);\n  }\n}\n\n\n//-----------------------------------------------------------------------------\nint FilterMatchingPoints(\n    const mitk::PointSet& fixedPointsIn,\n    const mitk::PointSet& movingPointsIn,\n    mitk::PointSet& fixedPointsOut,\n    mitk::PointSet& movingPointsOut\n    )\n{\n  int matchedPoints = 0;\n  fixedPointsOut.Clear();\n  movingPointsOut.Clear();\n\n  mitk::PointSet::DataType* fixedPointSet = fixedPointsIn.GetPointSet(0);\n  mitk::PointSet::PointsContainer* fixedPoints = fixedPointSet->GetPoints();\n  mitk::PointSet::DataType* movingPointSet = movingPointsIn.GetPointSet(0);\n  mitk::PointSet::PointsContainer* movingPoints = movingPointSet->GetPoints();\n\n  mitk::PointSet::PointsIterator fixedPointsIt;\n  mitk::PointSet::PointsIterator movingPointsIt;\n\n  mitk::PointSet::PointIdentifier pointID;\n  mitk::PointSet::PointType fixedPoint;\n  mitk::PointSet::PointType movingPoint;\n\n  for (fixedPointsIt = fixedPoints->Begin(); fixedPointsIt != fixedPoints->End(); ++fixedPointsIt)\n  {\n    pointID = fixedPointsIt->Index();\n    fixedPoint = fixedPointsIn.GetPoint(pointID);\n\n    for (movingPointsIt = movingPoints->Begin(); movingPointsIt != movingPoints->End(); ++movingPointsIt)\n    {\n      if (movingPointsIt->Index() == pointID)\n      {\n        movingPoint = movingPointsIn.GetPoint(pointID);\n\n        fixedPointsOut.InsertPoint(pointID, fixedPoint);\n        movingPointsOut.InsertPoint(pointID, movingPoint);\n        matchedPoints++;\n      }\n    }\n  }\n\n  return matchedPoints;\n}\n\n\n//-----------------------------------------------------------------------------\nint RemoveNaNPoints(\n    const mitk::PointSet& pointsIn,\n    mitk::PointSet& pointsOut\n    )\n{\n  int removedPoints = 0;\n  pointsOut.Clear();\n\n  mitk::PointSet::DataType* pointSet = pointsIn.GetPointSet(0);\n  mitk::PointSet::PointsContainer* points = pointSet->GetPoints();\n\n  mitk::PointSet::PointsIterator pointsIt;\n\n  mitk::PointSet::PointIdentifier pointID;\n  mitk::PointSet::PointType point;\n\n  for (pointsIt = points->Begin(); pointsIt != points->End(); ++pointsIt)\n  {\n    pointID = pointsIt->Index();\n    point = pointsIn.GetPoint(pointID);\n\n\n    if ( CheckForNaNPoint(point) )\n    {\n      removedPoints++;\n    }\n    else\n    {\n      pointsOut.InsertPoint(pointID, point);\n    }\n  }\n  return removedPoints;\n}\n\n\n//-----------------------------------------------------------------------------\nbool CheckForNaNPoint( const mitk::PointSet::PointType& point )\n{\n  if ( boost::math::isnan( point[0] ) || boost::math::isnan( point[1] ) || boost::math::isnan( point[2] ))\n  {\n    return true;\n  }\n  return false;\n}\n\n\n//-----------------------------------------------------------------------------\nmitk::Point3D ComputeCentroid(const mitk::PointSet& input)\n{\n  mitk::Point3D average;\n  average.Fill(0);\n\n  if (input.GetSize() > 0)\n  {\n    mitk::PointSet::DataType* pointSet = input.GetPointSet(0);\n    mitk::PointSet::PointsContainer* points = pointSet->GetPoints();\n    mitk::PointSet::PointsIterator pointsIt;\n    mitk::PointSet::PointType point;\n\n    for (pointsIt = points->Begin(); pointsIt != points->End(); ++pointsIt)\n    {\n      point = input.GetPoint(pointsIt->Index());\n      average[0] += point[0];\n      average[1] += point[1];\n      average[2] += point[2];\n    }\n\n    double numberOfPoints = static_cast<double>(input.GetSize());\n\n    average[0] /= numberOfPoints;\n    average[1] /= numberOfPoints;\n    average[2] /= numberOfPoints;\n  }\n\n  return average;\n}\n\n}\n", "meta": {"hexsha": "bc1d66b9918fc1d2b84676fe75043a7b54dff0d6", "size": 12176, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "MITK/Modules/Core/Common/niftkPointUtils.cxx", "max_stars_repo_name": "NifTK/NifTK", "max_stars_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T13:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T19:17:39.000Z", "max_issues_repo_path": "MITK/Modules/Core/Common/niftkPointUtils.cxx", "max_issues_repo_name": "NifTK/NifTK", "max_issues_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MITK/Modules/Core/Common/niftkPointUtils.cxx", "max_forks_repo_name": "NifTK/NifTK", "max_forks_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-08-20T07:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:55:27.000Z", "avg_line_length": 27.1180400891, "max_line_length": 131, "alphanum_fraction": 0.5776938239, "num_tokens": 3050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6258500282749974}}
{"text": "#include \"RBGL.hpp\"\n#include <boost/graph/graph_utility.hpp>\n\n\nusing namespace boost;\n\ntypedef adjacency_list<vecS, vecS, undirectedS,\n\t// vertex properties\n        property<vertex_index_t, int, \n    \tproperty<vertex_centrality_t, double> >, \n    \t// edge properties\n    \tproperty<edge_weight_t, double, \n    \tproperty<edge_centrality_t, double> > >\n    \tBCGraph;\n\n// Explicit instantiation of template function max_element circumvents \n// compiler error in llvm8 libc++\ntypedef graph_traits<BCGraph>::edge_descriptor Edge;\ntypedef graph_traits<BCGraph>::edge_iterator EdgeIterator;\ntypedef property_map < BCGraph, edge_centrality_t >::type EdgeCentralityMap;\ntypedef typename property_traits<EdgeCentralityMap>::value_type centrality_type;\ntypedef indirect_cmp<EdgeCentralityMap, std::less<centrality_type> > EdgeCentralityCompare;\n      \nEdgeIterator\nmax_element(EdgeIterator __first, EdgeIterator __last, EdgeCentralityCompare __comp)\n{\n    if (__first != __last)\n    {\n        EdgeIterator __i = __first;\n        while (++__i != __last)\n            if (__comp(*__first, *__i))\n                __first = __i;\n    }\n    return __first;\n}\n\n#include <boost/graph/bc_clustering.hpp>\n#include <boost/graph/betweenness_centrality.hpp>\n\n\n\nextern \"C\"\n{\n\n\n\tSEXP BGL_brandes_betweenness_centrality(SEXP num_verts_in, \n\t\tSEXP num_edges_in, SEXP R_edges_in, SEXP R_weights_in)\n        {\n    \t\tBCGraph g;\n\n\t\tint NV = Rf_asInteger(num_verts_in);\n\t\tint NE = Rf_asInteger(num_edges_in);\n\t\tint* edges_in = INTEGER(R_edges_in);\n\t\tdouble* weights_in = REAL(R_weights_in);\n\n\t\tfor (int i = 0; i < NE ; i++, edges_in += 2, weights_in++)\n\t\t    boost::add_edge(*edges_in, *(edges_in+1), *weights_in, g);\n\n\t\tSEXP anslst, bcvlst, enlst, bcelst, rbcvlst, dom;\n\t\tPROTECT(anslst = Rf_allocVector(VECSXP,5));\n\t\tPROTECT(bcvlst = Rf_allocMatrix(REALSXP, 1, NV));\n\t\tPROTECT(enlst = Rf_allocMatrix(INTSXP, 2, NE));\n\t\tPROTECT(bcelst = Rf_allocMatrix(REALSXP, 1, NE));\n\t\tPROTECT(rbcvlst = Rf_allocMatrix(REALSXP, 1, NV));\n\t\tPROTECT(dom = Rf_allocVector(REALSXP, 1));\n\n\t\tbrandes_betweenness_centrality(g, \n                        centrality_map(get(vertex_centrality, g)).\n\t\t\tedge_centrality_map(get(edge_centrality, g)).\n\t\t\tweight_map(get(edge_weight, g)));\n\n                property_map<BCGraph, vertex_centrality_t>::type \n\t\t\tv_map = get(vertex_centrality, g);\n                property_map<BCGraph, edge_centrality_t>::type \n\t\t\te_map = get(edge_centrality, g);\n\n                graph_traits < BCGraph>::vertex_iterator vi, v_end;\n                graph_traits < BCGraph>::edge_iterator ei, e_end;\n\n                int v = 0, e = 0;\n\n\t\tfor ( tie(vi, v_end) = vertices(g); vi != v_end; vi++ ) \n                    REAL(bcvlst)[v++] = v_map[*vi];\n\t\tfor ( v = 0, tie(ei, e_end) = edges(g); ei != e_end ; ei++ ) \n\t\t{\n\t\t    INTEGER(enlst)[v++] = source(*ei, g);\n\t\t    INTEGER(enlst)[v++] = target(*ei, g);\n                    REAL(bcelst)[e++] = e_map[*ei];\n                }\n\n\t\trelative_betweenness_centrality(g, get(vertex_centrality, g));\n                v_map = get(vertex_centrality, g);\n\n\t\tfor ( v = 0, tie(vi, v_end) = vertices(g); vi != v_end; vi++ ) \n                    REAL(rbcvlst)[v++] = v_map[*vi];\n\t\t\n\t\tdouble dominance = central_point_dominance(g,\n\t\t                  get(vertex_centrality, g));\n\n\t\tREAL(dom)[0] = dominance;\n\n\t\tSET_VECTOR_ELT(anslst,0,bcvlst);\n\t\tSET_VECTOR_ELT(anslst,1,bcelst);\n\t\tSET_VECTOR_ELT(anslst,2,rbcvlst);\n\t\tSET_VECTOR_ELT(anslst,3,dom);\n\t\tSET_VECTOR_ELT(anslst,4,enlst);\n\t\tUNPROTECT(6);\n\t\treturn(anslst);\n\t}\n\n\tclass clustering_threshold : public bc_clustering_threshold<double>\n\t{\n\t\ttypedef bc_clustering_threshold<double> inherited;\n\n\tpublic:\n\t        clustering_threshold(double threshold, const BCGraph& g, bool normalize)\n\t\t: inherited(threshold, g, normalize), iter(1) { }\n\n\t        bool operator()(double max_centrality, Edge e, const BCGraph& g)\n\t        {\n#if DEBUG\n                  std::cout << \"Iter: \" << iter << \" Max Centrality: \"\n                       << (max_centrality / dividend) << std::endl;\n#endif\n\t\t  ++iter;\n\t\t  return inherited::operator()(max_centrality, e, g);\n\t        }\n\n\tprivate:\n\t\t unsigned int iter;\n\t};\n\n\tSEXP BGL_betweenness_centrality_clustering (SEXP num_verts_in, \n\t\tSEXP num_edges_in, SEXP R_edges_in, SEXP R_weights_in,\n\t\tSEXP R_threshold,  SEXP R_normalize)\n        {\n    \t\tBCGraph g;\n\n\t\tint NE = Rf_asInteger(num_edges_in);\n\t\tint* edges_in = INTEGER(R_edges_in);\n\t\tdouble* weights_in = REAL(R_weights_in);\n\n\t\tfor (int i = 0; i < NE ; i++, edges_in += 2, weights_in++)\n\t\t    boost::add_edge(*edges_in, *(edges_in+1), *weights_in, g);\n\n\t\tdouble threshold = REAL(R_threshold)[0];\n\t\tbool normalize = LOGICAL(R_normalize)[0];\n\n\t\tbetweenness_centrality_clustering(g,\n\t\t\tclustering_threshold(threshold, g, normalize),\n\t\t\tget(edge_centrality, g));\n\n\t\t// betweenness_centrality_clustering(g,\n\t\t// \tclustering_threshold(threshold, g, normalize));\n\n\t\tSEXP anslst, cnt, bcvlst, bcelst;\n\t\tPROTECT(anslst = Rf_allocVector(VECSXP,3));\n\t\tPROTECT(cnt = Rf_allocVector(INTSXP, 1));\n\t\tPROTECT(bcvlst = Rf_allocMatrix(INTSXP, 2, num_edges(g)));\n\t\tPROTECT(bcelst = Rf_allocMatrix(REALSXP, 1, num_edges(g)));\n\n\t\tINTEGER(cnt)[0] = num_edges(g);\n\n\t\tproperty_map < BCGraph, edge_centrality_t >::type\n\t\t         ec = get(edge_centrality, g);\n\n\t\ttypedef graph_traits<BCGraph>::edge_iterator   edge_iterator;\n\t\tedge_iterator ei, e_end;\n\n#if DEBUG\n                std::cout << \" edge centralities: \";\n\t\tfor ( tie(ei, e_end) = edges(g); ei != e_end; ++ei )\n                        std::cout << \" \" << ec[*ei];\n                std::cout << std::endl;\n#endif\n\n\t\tint i = 0, j = 0;\n\t\tfor ( tie(ei, e_end) = edges(g); ei != e_end; ++ei )\n\t\t{\n\t\t\tINTEGER(bcvlst)[i++] = source(*ei, g);\n\t\t\tINTEGER(bcvlst)[i++] = target(*ei, g);\n\t\t\tREAL(bcelst)[j++] = ec[*ei];\n\t\t}\n\n\t\tSET_VECTOR_ELT(anslst,0,cnt);\n\t\tSET_VECTOR_ELT(anslst,1,bcvlst);\n\t\tSET_VECTOR_ELT(anslst,2,bcelst);\n\t\tUNPROTECT(4);\n\t\treturn(anslst);\n\t}\n}\n\n", "meta": {"hexsha": "277cab40f48677b28ebb80ab533f25583ef6e434", "size": 5916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bbc.cpp", "max_stars_repo_name": "HenrikBengtsson/RBGL", "max_stars_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "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/bbc.cpp", "max_issues_repo_name": "HenrikBengtsson/RBGL", "max_issues_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-09-05T02:26:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-30T20:28:53.000Z", "max_forks_repo_path": "src/bbc.cpp", "max_forks_repo_name": "HenrikBengtsson/RBGL", "max_forks_repo_head_hexsha": "9e34efd0dcab3babe1cea49b060a643bee79931c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-12-19T10:17:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T01:22:29.000Z", "avg_line_length": 30.6528497409, "max_line_length": 91, "alphanum_fraction": 0.6509465855, "num_tokens": 1756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6258500189150547}}
{"text": "#include \"software/new_geom/polynomial1d.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/QR>\n#include <list>\n#include <stdexcept>\n\n#include \"software/new_geom/geom_constants.h\"\n\nPolynomial1d::Polynomial1d() {}\n\nPolynomial1d::Polynomial1d(const std::vector<double> &coeffs) : coeffs(coeffs) {}\n\nPolynomial1d::Polynomial1d(const std::initializer_list<double> &coeffs)\n    : coeffs(std::vector<double>(coeffs))\n{\n}\n\nPolynomial1d::Polynomial1d(const std::vector<Polynomial1d::Constraint> constraints)\n{\n    // Check that we have at least two constraints\n    if (constraints.size() < 2)\n    {\n        throw std::invalid_argument(\n            \"Less then two constraints given, so no unique polynomial solution.\");\n    }\n\n    // Check that all inputs are unique\n    for (size_t i = 0; i < constraints.size(); i++)\n    {\n        for (size_t j = i + 1; j < constraints.size(); j++)\n        {\n            if (constraints[i].input == constraints[j].input)\n            {\n                throw std::invalid_argument(\n                    \"At least two inputs were equal, does not define a valid set of constraints\");\n            }\n        }\n    }\n\n    // Solve for the coefficients\n    Eigen::MatrixXd A(constraints.size(), constraints.size());\n    Eigen::VectorXd b(constraints.size());\n\n    for (size_t row_index = 0; row_index < constraints.size(); row_index++)\n    {\n        for (size_t col_index = 0; col_index < constraints.size(); col_index++)\n        {\n            A(row_index, col_index) =\n                std::pow(constraints[row_index].input, static_cast<double>(col_index));\n            b(row_index) = constraints[row_index].output;\n        }\n    }\n\n    const Eigen::VectorXd coeff_vector = A.fullPivLu().solve(b);\n\n    for (size_t i = 0; i < constraints.size(); i++)\n    {\n        coeffs.emplace_back(coeff_vector(i));\n    }\n}\n\ndouble Polynomial1d::getCoeff(unsigned int order) const\n{\n    if (order >= coeffs.size())\n    {\n        return 0;\n    }\n    else\n    {\n        return coeffs[order];\n    }\n}\n\nvoid Polynomial1d::setCoeff(unsigned int order, double coeff)\n{\n    if (order >= coeffs.size())\n    {\n        coeffs.resize(order + 1, 0);\n    }\n    coeffs[order] = coeff;\n}\n\nunsigned int Polynomial1d::getOrder() const\n{\n    if (coeffs.size() != 0)\n    {\n        for (unsigned int i = coeffs.size(); i > 0; i--)\n        {\n            if (std::abs(coeffs[i - 1]) >= GeomConstants::FIXED_EPSILON)\n            {\n                return i - 1;\n            }\n        }\n    }\n    // Zero polynomial treated as an order zero polynomial\n    return 0;\n}\n\ndouble Polynomial1d::valueAt(double val) const\n{\n    // Horner's Method:\n    // https://www.geeksforgeeks.org/horners-method-polynomial-evaluation/\n    unsigned int order = getOrder();\n    double retval      = getCoeff(order);\n    for (unsigned int i = 1; i <= order; i++)\n    {\n        retval = retval * val + getCoeff(order - i);\n    }\n    return retval;\n}\n\nPolynomial1d operator+(const Polynomial1d &p1, const Polynomial1d &p2)\n{\n    Polynomial1d sum;\n    unsigned int max_order = std::max(p1.getOrder(), p2.getOrder());\n    for (unsigned int i = 0; i <= max_order; i++)\n    {\n        sum.setCoeff(i, p1.getCoeff(i) + p2.getCoeff(i));\n    }\n    return sum;\n}\n\nPolynomial1d operator-(const Polynomial1d &p1, const Polynomial1d &p2)\n{\n    Polynomial1d difference;\n    unsigned int max_order = std::max(p1.getOrder(), p2.getOrder());\n    for (unsigned int i = 0; i <= max_order; i++)\n    {\n        difference.setCoeff(i, p1.getCoeff(i) - p2.getCoeff(i));\n    }\n    return difference;\n}\n\nPolynomial1d operator*(const Polynomial1d &p1, const Polynomial1d &p2)\n{\n    Polynomial1d product;\n    unsigned int p1_order = p1.getOrder();\n    unsigned int p2_order = p2.getOrder();\n    for (unsigned int i = 0; i <= p1_order; i++)\n    {\n        for (unsigned int j = 0; j <= p2_order; j++)\n        {\n            product.setCoeff(i + j,\n                             product.getCoeff(i + j) + (p1.getCoeff(i) * p2.getCoeff(j)));\n        }\n    }\n    return product;\n}\n\nPolynomial1d &operator+=(Polynomial1d &p1, const Polynomial1d &p2)\n{\n    return p1 = p1 + p2;\n}\n\nPolynomial1d &operator-=(Polynomial1d &p1, const Polynomial1d &p2)\n{\n    return p1 = p1 - p2;\n}\n\nPolynomial1d &operator*=(Polynomial1d &p1, const Polynomial1d &p2)\n{\n    return p1 = p1 * p2;\n}\n\nbool operator==(const Polynomial1d &p1, const Polynomial1d &p2)\n{\n    unsigned int p1_order = p1.getOrder();\n    unsigned int p2_order = p2.getOrder();\n    if (p1_order != p2_order)\n    {\n        return false;\n    }\n    for (unsigned int i = 0; i < p1_order; i++)\n    {\n        if (std::abs(p1.getCoeff(i) - p2.getCoeff(i)) >= GeomConstants::FIXED_EPSILON)\n        {\n            return false;\n        }\n    }\n    return true;\n}\n", "meta": {"hexsha": "0506ec5c148c3d1cc585935ec07bf590485a2d06", "size": 4716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/software/new_geom/polynomial1d.cpp", "max_stars_repo_name": "EvanMorcom/Software", "max_stars_repo_head_hexsha": "586fb3cf8dc2d93de194d9815af5de63caa7e318", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/software/new_geom/polynomial1d.cpp", "max_issues_repo_name": "EvanMorcom/Software", "max_issues_repo_head_hexsha": "586fb3cf8dc2d93de194d9815af5de63caa7e318", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/software/new_geom/polynomial1d.cpp", "max_forks_repo_name": "EvanMorcom/Software", "max_forks_repo_head_hexsha": "586fb3cf8dc2d93de194d9815af5de63caa7e318", "max_forks_repo_licenses": ["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.7704918033, "max_line_length": 98, "alphanum_fraction": 0.5969041561, "num_tokens": 1266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.625846909638813}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/detail/diff_div.hpp>\n#include <eve/function/diff/legendre.hpp>\n#include <type_traits>\n#include <boost/math/special_functions/legendre.hpp>\n\nTTS_CASE_TPL(\"Check diff(legendre) return type\", EVE_TYPE)\n{\n    TTS_EXPR_IS(eve::diff(eve::legendre)((unsigned int)(0), T()), T);\n}\n\nTTS_CASE_TPL(\"Check eve::diff(eve::legendre) behavior\", EVE_TYPE)\n{\n  if constexpr(eve::floating_value<T>)\n  {\n    using i_t = eve::as_integer_t<T,unsigned>;\n    TTS_ULP_EQUAL(eve::diff(eve::legendre)(2u, T{0.5}), T(boost::math::legendre_p_prime(2u, 0.5)), 2.0);\n    TTS_ULP_EQUAL(eve::diff(eve::legendre)(2u, T{0.1}), T(boost::math::legendre_p_prime(2u, 0.1)), 2.0);\n    TTS_ULP_EQUAL(eve::diff(eve::legendre)(3u, T{0.5}), T(boost::math::legendre_p_prime(3u, 0.5)), 2.0);\n    TTS_ULP_EQUAL(eve::diff(eve::legendre)(3u, T{0.1}), T(boost::math::legendre_p_prime(3u, 0.1)), 2.0);\n\n    TTS_ULP_EQUAL(eve::diff(eve::legendre)(i_t(2u), T{0.5}), T(boost::math::legendre_p_prime(2u, 0.5)), 2.0);\n    TTS_ULP_EQUAL(eve::diff(eve::legendre)(i_t(2u), T{0.1}), T(boost::math::legendre_p_prime(2u, 0.1)), 2.0);\n    TTS_ULP_EQUAL(eve::diff(eve::legendre)(i_t(3u), T{0.5}), T(boost::math::legendre_p_prime(3u, 0.5)), 2.0);\n    TTS_ULP_EQUAL(eve::diff(eve::legendre)(i_t(3u), T{0.1}), T(boost::math::legendre_p_prime(3u, 0.1)), 2.0);\n    TTS_ULP_EQUAL(eve::diff(eve::legendre)(i_t(5u), T{0.1}), T(boost::math::legendre_p_prime(5u, 0.1)), 2.0);\n  }\n}\n", "meta": {"hexsha": "023d3a45980aefacdcddafe4fc7569621793a1c1", "size": 1742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/core/legendre/diff/legendre.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/core/legendre/diff/legendre.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/core/legendre/diff/legendre.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.7714285714, "max_line_length": 109, "alphanum_fraction": 0.5941446613, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6258141200672993}}
{"text": "//  Boost common_factor_ct.hpp header file  ----------------------------------//\r\n\r\n//  (C) Copyright Daryle Walker and Stephen Cleary 2001-2002.\r\n//  Distributed under the Boost Software License, Version 1.0. (See\r\n//  accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  See http://www.boost.org for updates, documentation, and revision history. \r\n\r\n#ifndef BOOST_MATH_COMMON_FACTOR_CT_HPP\r\n#define BOOST_MATH_COMMON_FACTOR_CT_HPP\r\n\r\n#include <boost/math_fwd.hpp>  // self include\r\n#include <boost/config.hpp>  // for BOOST_STATIC_CONSTANT, etc.\r\n#include <boost/mpl/integral_c.hpp>\r\n\r\nnamespace boost\r\n{\r\nnamespace math\r\n{\r\n\r\n//  Implementation details  --------------------------------------------------//\r\n\r\nnamespace detail\r\n{\r\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\r\n    // Build GCD with Euclid's recursive algorithm\r\n    template < static_gcd_type Value1, static_gcd_type Value2 >\r\n    struct static_gcd_helper_t\r\n    {\r\n    private:\r\n        BOOST_STATIC_CONSTANT( static_gcd_type, new_value1 = Value2 );\r\n        BOOST_STATIC_CONSTANT( static_gcd_type, new_value2 = Value1 % Value2 );\r\n\r\n        #ifndef __BORLANDC__\r\n        #define BOOST_DETAIL_GCD_HELPER_VAL(Value) static_cast<static_gcd_type>(Value)\r\n        #else\r\n        typedef static_gcd_helper_t  self_type;\r\n        #define BOOST_DETAIL_GCD_HELPER_VAL(Value)  (self_type:: Value )\r\n        #endif\r\n\r\n        typedef static_gcd_helper_t< BOOST_DETAIL_GCD_HELPER_VAL(new_value1),\r\n         BOOST_DETAIL_GCD_HELPER_VAL(new_value2) >  next_step_type;\r\n\r\n        #undef BOOST_DETAIL_GCD_HELPER_VAL\r\n\r\n    public:\r\n        BOOST_STATIC_CONSTANT( static_gcd_type, value = next_step_type::value );\r\n    };\r\n\r\n    // Non-recursive case\r\n    template < static_gcd_type Value1 >\r\n    struct static_gcd_helper_t< Value1, 0UL >\r\n    {\r\n        BOOST_STATIC_CONSTANT( static_gcd_type, value = Value1 );\r\n    };\r\n#else\r\n    // Use inner class template workaround from Peter Dimov\r\n    template < static_gcd_type Value1 >\r\n    struct static_gcd_helper2_t\r\n    {\r\n        template < static_gcd_type Value2 >\r\n        struct helper\r\n        {\r\n            BOOST_STATIC_CONSTANT( static_gcd_type, value\r\n             = static_gcd_helper2_t<Value2>::BOOST_NESTED_TEMPLATE\r\n             helper<Value1 % Value2>::value );\r\n        };\r\n\r\n        template <  >\r\n        struct helper< 0UL >\r\n        {\r\n            BOOST_STATIC_CONSTANT( static_gcd_type, value = Value1 );\r\n        };\r\n    };\r\n\r\n    // Special case\r\n    template <  >\r\n    struct static_gcd_helper2_t< 0UL >\r\n    {\r\n        template < static_gcd_type Value2 >\r\n        struct helper\r\n        {\r\n            BOOST_STATIC_CONSTANT( static_gcd_type, value = Value2 );\r\n        };\r\n    };\r\n\r\n    // Build the GCD from the above template(s)\r\n    template < static_gcd_type Value1, static_gcd_type Value2 >\r\n    struct static_gcd_helper_t\r\n    {\r\n        BOOST_STATIC_CONSTANT( static_gcd_type, value\r\n         = static_gcd_helper2_t<Value1>::BOOST_NESTED_TEMPLATE\r\n         helper<Value2>::value );\r\n    };\r\n#endif\r\n\r\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\r\n    // Build the LCM from the GCD\r\n    template < static_gcd_type Value1, static_gcd_type Value2 >\r\n    struct static_lcm_helper_t\r\n    {\r\n        typedef static_gcd_helper_t<Value1, Value2>  gcd_type;\r\n\r\n        BOOST_STATIC_CONSTANT( static_gcd_type, value = Value1 / gcd_type::value\r\n         * Value2 );\r\n    };\r\n\r\n    // Special case for zero-GCD values\r\n    template < >\r\n    struct static_lcm_helper_t< 0UL, 0UL >\r\n    {\r\n        BOOST_STATIC_CONSTANT( static_gcd_type, value = 0UL );\r\n    };\r\n#else\r\n    // Adapt GCD's inner class template workaround for LCM\r\n    template < static_gcd_type Value1 >\r\n    struct static_lcm_helper2_t\r\n    {\r\n        template < static_gcd_type Value2 >\r\n        struct helper\r\n        {\r\n            typedef static_gcd_helper_t<Value1, Value2>  gcd_type;\r\n\r\n            BOOST_STATIC_CONSTANT( static_gcd_type, value = Value1\r\n             / gcd_type::value * Value2 );\r\n        };\r\n\r\n        template <  >\r\n        struct helper< 0UL >\r\n        {\r\n            BOOST_STATIC_CONSTANT( static_gcd_type, value = 0UL );\r\n        };\r\n    };\r\n\r\n    // Special case\r\n    template <  >\r\n    struct static_lcm_helper2_t< 0UL >\r\n    {\r\n        template < static_gcd_type Value2 >\r\n        struct helper\r\n        {\r\n            BOOST_STATIC_CONSTANT( static_gcd_type, value = 0UL );\r\n        };\r\n    };\r\n\r\n    // Build the LCM from the above template(s)\r\n    template < static_gcd_type Value1, static_gcd_type Value2 >\r\n    struct static_lcm_helper_t\r\n    {\r\n        BOOST_STATIC_CONSTANT( static_gcd_type, value\r\n         = static_lcm_helper2_t<Value1>::BOOST_NESTED_TEMPLATE\r\n         helper<Value2>::value );\r\n    };\r\n#endif\r\n\r\n}  // namespace detail\r\n\r\n\r\n//  Compile-time greatest common divisor evaluator class declaration  --------//\r\n\r\ntemplate < static_gcd_type Value1, static_gcd_type Value2 >\r\nstruct static_gcd : public mpl::integral_c<static_gcd_type, (detail::static_gcd_helper_t<Value1, Value2>::value) >\r\n{\r\n};  // boost::math::static_gcd\r\n\r\n\r\n//  Compile-time least common multiple evaluator class declaration  ----------//\r\n\r\ntemplate < static_gcd_type Value1, static_gcd_type Value2 >\r\nstruct static_lcm : public mpl::integral_c<static_gcd_type, (detail::static_lcm_helper_t<Value1, Value2>::value) >\r\n{\r\n};  // boost::math::static_lcm\r\n\r\n\r\n}  // namespace math\r\n}  // namespace boost\r\n\r\n\r\n#endif  // BOOST_MATH_COMMON_FACTOR_CT_HPP\r\n", "meta": {"hexsha": "339cbfccf73a7904915487eea8817728dc4b10e0", "size": 5511, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/math/common_factor_ct.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "master/core/third/boost/math/common_factor_ct.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/math/common_factor_ct.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 30.4475138122, "max_line_length": 115, "alphanum_fraction": 0.6399927418, "num_tokens": 1298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6258141125377663}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n\n#include <boost/geometry/extensions/nsphere/nsphere.hpp>\n\n\ntemplate <typename P, typename T>\nvoid test_area_circle()\n{\n    bg::model::nsphere<P, T> c;\n\n    bg::set<0>(c, 0);\n    bg::set<1>(c, 0);\n    bg::set_radius<0>(c, 2);\n\n    double d = bg::area(c);\n    BOOST_CHECK_CLOSE(d, 4 * 3.1415926535897932384626433832795, 0.001);\n}\n\n\n\nint test_main(int, char* [])\n{\n    test_area_circle<bg::model::point<double, 2, bg::cs::cartesian>, double>();\n    return 0;\n}\n", "meta": {"hexsha": "282c620fd519be5ef3cc5bfa4f84e41f0197cfc2", "size": 928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/nsphere/nsphere-area.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/test/nsphere/nsphere-area.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/test/nsphere/nsphere-area.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 24.4210526316, "max_line_length": 79, "alphanum_fraction": 0.7025862069, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6258141097591048}}
{"text": "/*\nCopyright (c) 2016 Bastien Durix\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n\n/**\n *  \\file DistanceField.cpp\n *  \\brief Defines functions related to distance field\n *  \\author Bastien Durix\n */\n\n#include \"DistanceField.h\"\n#include <boost/math/distributions/normal.hpp>\n#include <set>\n#include <nlopt.hpp>\n#include <iostream>\n\nunsigned int algorithm::skeletonization::closestInd(const boundary::DiscreteBoundary<2>::Ptr disbnd, const Eigen::Vector2d &C)\n{\n\tdouble distmin = 0.0;\n\tunsigned int ind = 0;\n\tfor(unsigned int i = 0; i < disbnd->getNbVertices(); i++)\n\t{\n\t\tEigen::Vector2d vec = disbnd->getCoordinates(i) - C;\n\t\tdouble dist = vec.norm();\n\t\t\n\t\tif(dist < distmin || i == 0)\n\t\t{\n\t\t\tdistmin = dist;\n\t\t\tind = i;\n\t\t}\n\t}\n\n\treturn ind;\n}\n\ndouble algorithm::skeletonization::fieldValue(const boundary::DiscreteBoundary<2>::Ptr disbnd, const Eigen::Vector2d &C, double noise)\n{\n\tboost::math::normal norm(0.0,noise);\n\t\n\tstd::vector<double> dists(disbnd->getNbVertices());\n\t\n\tdouble distmin = 0.0;\n\tfor(unsigned int i = 0; i < dists.size(); i++)\n\t{\n\t\tEigen::Vector2d vec = disbnd->getCoordinates(i) - C;\n\t\tdouble dist = vec.norm();\n\t\t\n\t\tif(dist < distmin || i == 0) distmin = dist;\n\t\t\n\t\tdists[i] = dist;\n\t}\n\t\n\tdouble denom = 0.0;\n\tdouble numer = 0.0;\n\t\n\tfor(unsigned int i = 0; i < dists.size(); i++)\n\t{\n\t\tdouble diff = dists[i] - distmin;\n\t\tdouble proba = 2.0*(1.0-boost::math::cdf(norm,diff));\n\t\t\n\t\tnumer += proba * dists[i];\n\t\t\n\t\tdenom += proba;\n\t}\n\t\n\tdouble val = numer/denom;\n\t\n\tif(val - distmin > 2.0)\n\tstd::cout << val - distmin << std::endl;\n\n\treturn val;\n}\n\ndouble algorithm::skeletonization::fieldValue(const boundary::DiscreteBoundary<2>::Ptr disbnd, const Eigen::Vector2d &C, Eigen::Vector2d &grad, double noise)\n{\n\tboost::math::normal norm(0.0,noise);\n\t\n\tstd::vector<double> dists(disbnd->getNbVertices());\n\t\n\tdouble distmin = 0.0;\n\tfor(unsigned int i = 0; i < dists.size(); i++)\n\t{\n\t\tEigen::Vector2d vec = disbnd->getCoordinates(i) - C;\n\t\tdouble dist = vec.norm();\n\t\t\n\t\tif(dist < distmin || i == 0) distmin = dist;\n\t\t\n\t\tdists[i] = dist;\n\t}\n\n\tdouble denom = 0.0;\n\tdouble numer = 0.0;\n\tEigen::Vector2d numvec(0.0,0.0);\n\t\n\tfor(unsigned int i = 0; i < dists.size(); i++)\n\t{\n\t\tEigen::Vector2d vec = disbnd->getCoordinates(i) - C;\n\t\tdouble diff = dists[i] - distmin;\n\t\tdouble proba = 2.0*(1.0-boost::math::cdf(norm,diff));\n\t\t\n\t\tnumer += proba * dists[i];\n\t\t\n\t\tnumvec += proba*vec.normalized();\n\t\t\n\t\tdenom += proba;\n\t}\n\t\n\tdouble val = numer/denom;\n\n\tif(val - distmin > 2.0)\n\tstd::cout << val - distmin << std::endl;\n\t\n\tgrad = numvec * (1.0/denom);\n\t\n\treturn val;\n}\n\nvoid algorithm::skeletonization::tangencyBoundary(const boundary::DiscreteBoundary<2>::Ptr disbnd,\n\t\t\t\t\t\t\t\t\t\t\t\t  const Eigen::Vector2d &C,\n\t\t\t\t\t\t\t\t\t\t\t\t  const double &rad,\n\t\t\t\t\t\t\t\t\t\t\t\t  double noise,\n\t\t\t\t\t\t\t\t\t\t\t\t  std::vector<std::list<unsigned int> > &v_ind,\n\t\t\t\t\t\t\t\t\t\t\t\t  double fac)\n{\n\tstd::vector<bool> used(disbnd->getNbVertices(),false);\n\tstd::vector<double> val(disbnd->getNbVertices());\n\tstd::vector<bool> isin(disbnd->getNbVertices(),false);\n\tfor(unsigned int i = 0; i < disbnd->getNbVertices(); i++)\n\t{\n\t\tval[i] = (disbnd->getVertex(i) - C).norm() - rad;\n\t\tif(val[i] < noise) isin[i] = true;\n\t}\n\t\n\tbool nochange = false;\n\t\n\tdo\n\t{\n\t\tnochange = true;\n\t\tfor(unsigned int i = 0; i < disbnd->getNbVertices(); i++)\n\t\t{\n\t\t\tif(!isin[i])\n\t\t\t{\n\t\t\t\tunsigned int prev = disbnd->getPrev(i);\n\t\t\t\tunsigned int next = disbnd->getNext(i);\n\t\t\t\tif((isin[prev] || isin[next]) && val[i] < fac)\n\t\t\t\t{\n\t\t\t\t\tisin[i] = true;\n\t\t\t\t\tnochange = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}while(!nochange);\n\t\n\tstd::list<std::list<unsigned int> > l_ind;\n\tfor(unsigned int i = 0; i < disbnd->getNbVertices(); i++)\n\t{\n\t\tif(isin[i] && !used[i])\n\t\t{\n\t\t\tstd::list<unsigned int> cind;\n\t\t\t\n\t\t\tused[i] = true;\n\t\t\tunsigned int indn = i;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tcind.push_back(indn);\n\t\t\t\tused[indn] = true;\n\t\t\t\tindn = disbnd->getNext(indn);\n\t\t\t}while(isin[indn] && indn != *(cind.begin()));\n\n\t\t\tunsigned int indp = i;\n\t\t\tcind.pop_front();\n\t\t\tdo\n\t\t\t{\n\t\t\t\tcind.push_front(indp);\n\t\t\t\tused[indp] = true;\n\t\t\t\tindp = disbnd->getPrev(indp);\n\t\t\t}while(isin[indp] && indp != *(cind.rbegin()));\n\t\t\tif(indp == *(cind.rbegin()))\n\t\t\t\tcind.push_front(indp);\n\t\t\t\n\t\t\twhile(val[*(cind.begin())] > noise)\n\t\t\t\tcind.pop_front();\n\t\t\twhile(val[*(cind.rbegin())] > noise)\n\t\t\t\tcind.pop_back();\n\t\t\tif(cind.size() > 1)\n\t\t\t\tl_ind.push_back(cind);\n\t\t}\n\t}\n\t\n\tl_ind.sort(\n\t\t[disbnd,C](const std::list<unsigned int> &c1, const std::list<unsigned int> &c2)\n\t\t{\n\t\t\tEigen::Vector2d p1 = disbnd->getVertex(*(c1.begin())) - C;\n\t\t\tEigen::Vector2d p2 = disbnd->getVertex(*(c2.begin())) - C;\n\t\t\tdouble ang1 = atan2(p1.y(),p1.x());\n\t\t\tdouble ang2 = atan2(p2.y(),p2.x());\n\t\t\treturn ang1 < ang2;\n\t\t});\n\tv_ind = std::vector<std::list<unsigned int> >(l_ind.begin(),l_ind.end());\n}\n\nstruct DataClosestCenter2d\n{\n\tconst boundary::DiscreteBoundary<2>::Ptr &disbnd;\n\tdouble noise;\n\t\n\tDataClosestCenter2d(\n\t\tconst boundary::DiscreteBoundary<2>::Ptr &disbnd_,\n\t\tdouble noise_) :\n\t\tdisbnd(disbnd_), noise(noise_) {};\n};\n\ndouble minClosestCenter2d(const std::vector<double> &vt, std::vector<double> &, void *dataFun)\n{\n\tDataClosestCenter2d *data = (DataClosestCenter2d*) dataFun;\n\t\n\tEigen::Vector2d C(vt[0],vt[1]);\n\t\n\tEigen::Vector2d grad;\n\talgorithm::skeletonization::fieldValue(data->disbnd, C, grad, data->noise);\n\t//return -algorithm::skeletonization::recFieldValue(data->vdisbnd, data->vdisshp, data->vcam, C, data->noise);\n\treturn grad.squaredNorm();\n}\n\nbool algorithm::skeletonization::closestCenter(const boundary::DiscreteBoundary<2>::Ptr disbnd, Eigen::Vector2d &C, double noise)\n{\n\tunsigned int nbiter = 10000;\n\t\n\tbool fini = false;\n\tdo\n\t{\n\t\tEigen::Vector2d grad;\n\t\tfieldValue(disbnd,C,grad,noise);\n\t\tfini = grad.norm() < 0.01*noise;\n\t\tif(!fini) C -= grad * noise * 0.1;\n\t\tnbiter--;\n\t}while(nbiter != 0 && !fini);\n\t\n\tstd::vector<double> lb(2);\n\tstd::vector<double> ub(2);\n\tstd::vector<double> C_init(2);\n\n\tEigen::Vector2d grad;\n\tdouble rad = fieldValue(disbnd,C,grad,noise);\n\t\n\tC_init[0] = C.x();\n\tC_init[1] = C.y();\n\t\n\tlb[0] = C.x() - rad*0.2;\n\tlb[1] = C.y() - rad*0.2;\n\t\n\tub[0] = C.x() + rad*0.2;\n\tub[1] = C.y() + rad*0.2;\n\t\n\tDataClosestCenter2d data(disbnd,noise);\n\n\tnlopt::opt opt(nlopt::LN_COBYLA, 2);\n\topt.set_lower_bounds(lb);\n\topt.set_upper_bounds(ub);\n\t\n\topt.set_min_objective(minClosestCenter2d, &data);\n\t\n\topt.set_xtol_rel(1e-2);\n\t\n\tdouble res;\n\topt.optimize(C_init, res);\n\tC.x() = C_init[0];\n\tC.y() = C_init[1];\n\n\treturn true;\n}\n\nvoid algorithm::skeletonization::closestCenterOnArc(const boundary::DiscreteBoundary<2>::Ptr disbnd,\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst Eigen::Vector2d &C,\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst std::pair<double,double> &pang,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdouble dist,\n\t\t\t\t\t\t\t\t\t\t\t\t\tEigen::Vector2d &Cmov,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdouble noise)\n{\n\tdouble step = noise / (dist*dist);\n\t\n\tdouble ang1 = pang.first;\n\tdouble ang2 = pang.second;\n\n\tEigen::Vector2d P1 = C + dist*Eigen::Vector2d(cos(ang1),sin(ang1));\n\tEigen::Vector2d P2 = C + dist*Eigen::Vector2d(cos(ang2),sin(ang2));\n\t\n\twhile(ang2 - ang1 > step)\n\t{\n\t\tdouble angmid = (ang1 + ang2) / 2.0;\n\t\t\n\t\tEigen::Vector2d grad;\n\t\tEigen::Vector2d vec(cos(angmid),sin(angmid));\n\t\tCmov = C + dist * vec;\n\t\tfieldValue(disbnd,Cmov,grad,noise);\n\t\t\n\t\t//double der = dist*(grad.y() * vec.x() - grad.x() * vec.y());\n\t\t//if(der < 0.0) ang1 = angmid;\n\t\t//if(der > 0.0) ang2 = angmid;\n\t\t\n\t\tEigen::Vector2d vec1 = (P1 - Cmov).normalized();\n\t\tEigen::Vector2d vec2 = (P2 - Cmov).normalized();\n\t\tdouble sim1 = grad.dot(vec1);\n\t\tdouble sim2 = grad.dot(vec2);\n\t\tif(sim1 > sim2) ang1 = angmid;\n\t\tif(sim2 > sim1) ang2 = angmid;\n\t}\n\n\tdouble angmid = (ang1 + ang2) / 2.0;\n\n\tEigen::Vector2d vec(cos(angmid),sin(angmid));\n\tCmov = C + dist * vec;\n}\n\nvoid algorithm::skeletonization::discontinuitiesOnArc(const boundary::DiscreteBoundary<2>::Ptr disbnd,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  const Eigen::Vector2d &C,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  const std::pair<double,double> &pang,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  double dist,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  std::vector<Eigen::Vector2d> &vecC,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  std::vector<std::pair<unsigned int,unsigned int> > &vecInd,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  double noise)\n{\n\tstd::list<Eigen::Vector2d> lisC;\n\tstd::list<std::pair<unsigned int,unsigned int> > lisInd;\n\tdouble step = noise / (dist*dist);\n\t\n\tdouble ang2 = pang.second;\n\tEigen::Vector2d P2 = C + dist*Eigen::Vector2d(cos(ang2),sin(ang2));\n\tunsigned int ind2 = closestInd(disbnd,P2);\n\t\n\tdouble ang1 = pang.first;\n\tEigen::Vector2d P1 = C + dist*Eigen::Vector2d(cos(ang1),sin(ang1));\n\tunsigned int ind1 = closestInd(disbnd,P1);\n\t\n\t//std::cout << \"disc \" << ind1 << \" \";\n\n\twhile(ind1 != ind2)\n\t{\n\t\twhile(ang2 - ang1 > step)\n\t\t{\n\t\t\tdouble angmid = (ang1 + ang2) / 2.0;\n\t\t\tEigen::Vector2d vec(cos(angmid),sin(angmid));\n\t\t\tEigen::Vector2d Cmov = C + dist * vec;\n\t\t\t\n\t\t\tunsigned int indmid = closestInd(disbnd,Cmov);\n\n\t\t\tif(indmid == ind1)\n\t\t\t{\n\t\t\t\tang1 = angmid;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tang2 = angmid;\n\t\t\t}\n\t\t}\n\t\t\n\t\tEigen::Vector2d P1 = C + dist*Eigen::Vector2d(cos(ang1),sin(ang1));\n\t\tunsigned int ind1b = closestInd(disbnd,P1);\n\t\tEigen::Vector2d P2 = C + dist*Eigen::Vector2d(cos(ang2),sin(ang2));\n\t\tunsigned int ind2b = closestInd(disbnd,P2);\n\n\t\tdouble angmid = (ang1 + ang2) / 2.0;\n\t\tEigen::Vector2d vec(cos(angmid),sin(angmid));\n\t\tEigen::Vector2d Cmov = C + dist * vec;\n\t\t\n\t\tlisC.push_back(Cmov);\n\t\tlisInd.push_back(std::make_pair(ind1b,ind2b));\n\t\t\n\t\tind1 = ind2b;\n\t\tang1 = ang2;\n\t\tang2 = pang.second;\n\t\t//std::cout << ind1 << \" \";\n\t}\n\t//std::cout << std::endl;\n\t\n\tvecC = std::vector<Eigen::Vector2d>(lisC.begin(),lisC.end());\n\tvecInd = std::vector<std::pair<unsigned int,unsigned int> >(lisInd.begin(),lisInd.end());\n}\n", "meta": {"hexsha": "2c147edb6e289a23e58e41e9f2fd1be3c017d2aa", "size": 10494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/algorithm/skeletonization/propagation/DistanceField.cpp", "max_stars_repo_name": "Ibujah/propagatedskeleton", "max_stars_repo_head_hexsha": "56a583e6f9907e68a388eec6ad179ad671ca156e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-29T08:40:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-30T11:06:46.000Z", "max_issues_repo_path": "src/lib/algorithm/skeletonization/propagation/DistanceField.cpp", "max_issues_repo_name": "Ibujah/propagatedskeleton", "max_issues_repo_head_hexsha": "56a583e6f9907e68a388eec6ad179ad671ca156e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/algorithm/skeletonization/propagation/DistanceField.cpp", "max_forks_repo_name": "Ibujah/propagatedskeleton", "max_forks_repo_head_hexsha": "56a583e6f9907e68a388eec6ad179ad671ca156e", "max_forks_repo_licenses": ["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.3668341709, "max_line_length": 157, "alphanum_fraction": 0.6408423861, "num_tokens": 3387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6258141074643141}}
{"text": "\r\n#include <vector>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <glload/gl_all.hpp>\r\n#include <glload/gl_load.hpp>\r\n\r\n#include <boost/tuple/tuple.hpp>\r\n#include \"glmesh/BoostDraw.h\"\r\n#include \"glmesh/CpuDataWriter.h\"\r\n#include \"glmesh/VertexFormat.h\"\r\n\r\n#include \"glmesh/Mesh.h\"\r\n#include \"glmesh/GenQuadrics.h\"\r\n#include \"GenHelper.h\"\r\n#include <glm/glm.hpp>\r\n\r\nnamespace glmesh\r\n{\r\n\tnamespace gen\r\n\t{\r\n\t\tnamespace\r\n\t\t{\r\n\t\t\tconst float g_pi = 3.1415726f;\r\n\t\t\tconst float g_2pi = g_pi * 2.0f;\r\n\t\t}\r\n\r\n\t\tMesh * UnitSphere( int numHorizSlices, int numVertSlices )\r\n\t\t{\r\n\t\t\t//The term \"ring\" refers to horizontal slices.\r\n\t\t\t//The term \"segment\" refers to vertical slices.\r\n\r\n\t\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t\t// Generate the vertex attribute data.\r\n\t\t\tnumHorizSlices = std::max(numHorizSlices, 1);\r\n\t\t\tnumVertSlices = std::max(numVertSlices, 3);\r\n\r\n\t\t\t//+2 to horizontal is for the top and bottom points, which are replicated due to texcoords.\r\n\t\t\tsize_t numRingVerts = numHorizSlices + 2;\r\n\t\t\t//+1 to vertical is for doubling up on the initial point, again due to texcoords.\r\n\t\t\tsize_t numSegVerts = numVertSlices + 1;\r\n\t\t\tsize_t attribCount = numSegVerts * numRingVerts;\r\n\r\n\t\t\tglmesh::AttributeList attribs;\r\n\t\t\tattribs.push_back(glmesh::AttribDesc(ATTR_POS, 3, glmesh::VDT_SINGLE_FLOAT, glmesh::ADT_FLOAT));\r\n\t\t\tattribs.push_back(glmesh::AttribDesc(ATTR_NORMAL, 3, glmesh::VDT_SINGLE_FLOAT, glmesh::ADT_FLOAT));\r\n\t\t\tattribs.push_back(glmesh::AttribDesc(ATTR_TEXCOORD, 2, glmesh::VDT_SINGLE_FLOAT, glmesh::ADT_FLOAT));\r\n\r\n\t\t\tVertexFormat fmt(attribs);\r\n\r\n\t\t\tCpuDataWriter writer(fmt, attribCount);\r\n\r\n\t\t\tfloat deltaSegTexCoord = 1.0f / numSegVerts;\r\n\t\t\tfloat deltaRingTexCoord = 1.0f / numRingVerts;\r\n\r\n\t\t\tfor(int segment = 0; segment < numVertSlices; ++segment)\r\n\t\t\t{\r\n\t\t\t\twriter.Attrib(0.0f, 1.0f, 0.0f);\r\n\t\t\t\twriter.Attrib(0.0f, 1.0f, 0.0f);\r\n\t\t\t\twriter.Attrib(deltaSegTexCoord * segment, 1.0f);\r\n\t\t\t}\r\n\r\n\t\t\twriter.Attrib(0.0f, 1.0f, 0.0f);\r\n\t\t\twriter.Attrib(0.0f, 1.0f, 0.0f);\r\n\t\t\twriter.Attrib(1.0f, 0.0f);\r\n\r\n\t\t\tfloat radThetaDelta = g_pi / (numHorizSlices + 1);\r\n\t\t\tfloat radRhoDelta = g_2pi / numVertSlices;\r\n\r\n\t\t\tfor(int ring = 0; ring < numHorizSlices; ++ring)\r\n\t\t\t{\r\n\t\t\t\tfloat radTheta = radThetaDelta * (ring + 1);\r\n\t\t\t\tfloat sinTheta = std::sin(radTheta);\r\n\t\t\t\tfloat cosTheta = std::cos(radTheta);\r\n\r\n\t\t\t\tfloat ringTexCoord = 1.0f - ((ring + 1) * deltaRingTexCoord);\r\n\r\n\t\t\t\tfor(int segment = 0; segment < numVertSlices; ++segment)\r\n\t\t\t\t{\r\n\t\t\t\t\tfloat radRho = radRhoDelta * segment;\r\n\t\t\t\t\tfloat sinRho = std::sin(-radRho);\r\n\t\t\t\t\tfloat cosRho = std::cos(-radRho);\r\n\r\n\t\t\t\t\tglm::vec3 currPos(sinTheta * cosRho, cosTheta, sinTheta * sinRho);\r\n\t\t\t\t\twriter.Attrib(currPos);\r\n\t\t\t\t\twriter.Attrib(currPos);\r\n\t\t\t\t\twriter.Attrib(deltaSegTexCoord * segment, ringTexCoord);\r\n\t\t\t\t}\r\n\r\n\t\t\t\twriter.Attrib(sinTheta, cosTheta, 0.0f);\r\n\t\t\t\twriter.Attrib(sinTheta, cosTheta, 0.0f);\r\n\t\t\t\twriter.Attrib(1.0f, ringTexCoord);\r\n\t\t\t}\r\n\r\n\t\t\tfor(int segment = 0; segment < numVertSlices; ++segment)\r\n\t\t\t{\r\n\t\t\t\twriter.Attrib(0.0f, -1.0f, 0.0f);\r\n\t\t\t\twriter.Attrib(0.0f, -1.0f, 0.0f);\r\n\t\t\t\twriter.Attrib(deltaSegTexCoord * segment, 0.0f);\r\n\t\t\t}\r\n\r\n\t\t\twriter.Attrib(0.0f, 1.0f, 0.0f);\r\n\t\t\twriter.Attrib(0.0f, 1.0f, 0.0f);\r\n\t\t\twriter.Attrib(1.0f, 0.0f);\r\n\r\n\t\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t\t//Generate the index data.\r\n\t\t\t//Restart index.\r\n\t\t\tGLuint restartIndex = writer.GetNumVerticesWritten();\r\n\r\n\t\t\tsize_t stripSize = ((2 * numVertSlices) + 2);\r\n\t\t\t//One strip for each ring vertex list, minus 1.\r\n\t\t\tsize_t numStrips = (numRingVerts - 1);\r\n\r\n\t\t\tsize_t numIndices = numStrips * stripSize;\r\n\t\t\t//Add one index between each strip for primitive restarting.\r\n\t\t\tnumIndices += (numStrips - 1);\r\n\r\n\t\t\tstd::vector<GLuint> indices;\r\n\t\t\tindices.reserve(numIndices);\r\n\r\n\t\t\tfor(size_t strip = 0; strip < numStrips; ++strip)\r\n\t\t\t{\r\n\t\t\t\tGLuint topRingIndex = (strip * numSegVerts);\r\n\t\t\t\tGLuint botRingIndex = ((strip + 1) * numSegVerts);\r\n\r\n\t\t\t\tfor(size_t segment = 0; segment < numSegVerts; ++segment)\r\n\t\t\t\t{\r\n\t\t\t\t\tindices.push_back(topRingIndex + segment);\r\n\t\t\t\t\tindices.push_back(botRingIndex + segment);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif(indices.size() != numIndices)\r\n\t\t\t\t\tindices.push_back(restartIndex);\r\n\t\t\t}\r\n\r\n\t\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t\t//Build the buffers.\r\n\t\t\tstd::vector<GLuint> buffers(2);\r\n\r\n\t\t\tgl::GenBuffers(2, &buffers[0]);\r\n\t\t\twriter.TransferToBuffer(gl::ARRAY_BUFFER, gl::STATIC_DRAW, buffers[0]);\r\n\r\n\t\t\t//vertex data done. Now build the index buffer.\r\n\t\t\tgl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, buffers[1]);\r\n\t\t\tgl::BufferData(gl::ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint),\r\n\t\t\t\t&indices[0], gl::STATIC_DRAW);\r\n\t\t\tgl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, 0);\r\n\r\n\t\t\t//Create VAOs.\r\n\t\t\tMeshVariantMap variantMap;\r\n\r\n\t\t\tgl::BindBuffer(gl::ARRAY_BUFFER, buffers[0]);\r\n\r\n\t\t\tGLuint currVao = 0;\r\n\r\n\t\t\tgl::GenVertexArrays(1, &currVao);\r\n\t\t\tgl::BindVertexArray(currVao);\r\n\t\t\tgl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, buffers[1]);\r\n\t\t\tfmt.BindAttribute(0, 0);\r\n\t\t\tAddVariantToMap(variantMap, currVao, 0);\r\n\r\n\t\t\tgl::GenVertexArrays(1, &currVao);\r\n\t\t\tgl::BindVertexArray(currVao);\r\n\t\t\tgl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, buffers[1]);\r\n\t\t\tfmt.BindAttribute(0, 0);\r\n\t\t\tfmt.BindAttribute(0, 1);\r\n\t\t\tAddVariantToMap(variantMap, currVao, VAR_NORMAL);\r\n\r\n\t\t\tgl::GenVertexArrays(1, &currVao);\r\n\t\t\tgl::BindVertexArray(currVao);\r\n\t\t\tgl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, buffers[1]);\r\n\t\t\tfmt.BindAttribute(0, 0);\r\n\t\t\tfmt.BindAttribute(0, 2);\r\n\t\t\tAddVariantToMap(variantMap, currVao, VAR_TEX_COORD);\r\n\r\n\t\t\tgl::GenVertexArrays(1, &currVao);\r\n\t\t\tgl::BindVertexArray(currVao);\r\n\t\t\tgl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, buffers[1]);\r\n\t\t\tfmt.BindAttribute(0, 0);\r\n\t\t\tfmt.BindAttribute(0, 1);\r\n\t\t\tfmt.BindAttribute(0, 2);\r\n\t\t\tAddVariantToMap(variantMap, currVao, VAR_TEX_COORD | VAR_NORMAL);\r\n\r\n\t\t\tgl::BindVertexArray(0);\r\n\t\t\tgl::BindBuffer(gl::ARRAY_BUFFER, 0);\r\n\r\n\t\t\t//////////////////////////////////////////////////////////////////////////\r\n\t\t\t//Create rendering commands.\r\n\t\t\tRenderCmdList renderCmds;\r\n\t\t\tif(glload::IsVersionGEQ(3, 1))\r\n\t\t\t{\r\n\t\t\t\t//Has primitive restart. Therefore, can draw two fans as one.\r\n\t\t\t\trenderCmds.PrimitiveRestartIndex(restartIndex);\r\n\t\t\t\trenderCmds.DrawElements(gl::TRIANGLE_STRIP, numIndices, gl::UNSIGNED_INT, 0);\r\n\t\t\t\trenderCmds.PrimitiveRestartIndex();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t//No restart. Must draw each strip one after the other.\r\n\t\t\t\tfor(size_t strip = 0; strip < numStrips; ++strip)\r\n\t\t\t\t{\r\n\t\t\t\t\tGLuint stripStart = strip * (stripSize + 1);\r\n\r\n\t\t\t\t\trenderCmds.DrawElements(gl::TRIANGLE_STRIP, stripSize, gl::UNSIGNED_INT,\r\n\t\t\t\t\t\tstripStart * sizeof(GLuint));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tGLuint mainVao = variantMap[\"lit-tex\"];\r\n\r\n\t\t\tMesh *pRet = new Mesh(buffers, mainVao, renderCmds, variantMap);\r\n\t\t\treturn pRet;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n", "meta": {"hexsha": "67cf5e837673ec5203edaa3918061a7da8c8cdad", "size": 6895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "glmesh/source/GenQuadrics.cpp", "max_stars_repo_name": "Morozov-5F/glsdk", "max_stars_repo_head_hexsha": "bff2b5074681bf3d2c438216e612d8a0ed80cead", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-13T20:38:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-13T20:38:23.000Z", "max_issues_repo_path": "glmesh/source/GenQuadrics.cpp", "max_issues_repo_name": "Morozov-5F/glsdk", "max_issues_repo_head_hexsha": "bff2b5074681bf3d2c438216e612d8a0ed80cead", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-10T13:39:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-12T10:50:56.000Z", "max_forks_repo_path": "glmesh/source/GenQuadrics.cpp", "max_forks_repo_name": "Morozov-5F/glsdk", "max_forks_repo_head_hexsha": "bff2b5074681bf3d2c438216e612d8a0ed80cead", "max_forks_repo_licenses": ["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.628440367, "max_line_length": 105, "alphanum_fraction": 0.6324873096, "num_tokens": 2042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6258141048469432}}
{"text": "// minphase.cc\n//\n// [y,ssp,iter] = minphase(h)\n// C++ implementation of minphase.m with the Eigen C++ template library:\n//   m-file for extracting the minimum phase factor from the \n//   linear-phase filter h. Input: h = (h(0) h(1)...h(N)] (row vector) \n//   where the h vector is the right half of a linear-phase FIR filter.\n//   It is presumed that any unit-circle zeros of h are of even multiplicity. \n//   Copyright (c) January 2002  by  H. J. Orchard and A. N. Willson, Jr.\n\n// Copyright (C) 2017 Robert G. Jenssen\n//\n// This program is free software; you can redistribute it and/or \n// modify it underthe terms of the GNU General Public License as \n// published by the Free Software Foundation; either version 3 of \n// the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n//\n// See the GNU General Public License for more details.\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n#include <cfloat>\n#include <Eigen/Eigen>\n#include <octave/oct.h>\n#include <octave/parse.h>\n\ntypedef Eigen::Matrix<long double,Eigen::Dynamic,1> EigenVectorNx1ld;\ntypedef Eigen::Matrix<long double,Eigen::Dynamic,Eigen::Dynamic>\n  EigenMatrixNxNld;\n\nDEFUN_DLD(minphase, args, nargout,\"[y,ssp,iter] = minphase(h)\")\n{\n\n  // Sanity checks\n  octave_idx_type nargin=args.length();\n  if ((nargin>1) || (nargout>3))\n    {\n      print_usage();\n    }\n\n  // Input arguments\n  ColumnVector h = args(0).column_vector_value();\n  octave_idx_type N=h.numel();\n    \n  // Output arguments\n  RowVector y(N);\n  long double ssp = LDBL_MAX;\n  octave_idx_type iter = 0;\n  \n  // Initialise ss\n  long double ss=ssp/2;\n\n  // Initialise column vector hh\n  EigenVectorNx1ld hh(N);\n  for(auto r=0;r<N;r++)\n    {\n      hh(r)=h(r);\n    }\n  \n  // Initialise column vectors yy, b and d\n  EigenVectorNx1ld yy(N);\n  EigenVectorNx1ld d(N);\n  EigenVectorNx1ld b(N);\n  for (auto r=0;r<N;r++)\n    {\n      yy(r)=0;\n      d(r)=0;\n    }\n  yy(0)=1;\n  \n  // Allocate A, Al and Ar\n  EigenMatrixNxNld A(N,N);\n  EigenMatrixNxNld Al(N,N);\n  EigenMatrixNxNld Ar(N,N);\n  \n  for (auto r=0;r<N;r++)\n    {\n      for (auto c=0;c<N;c++)\n        {   \n          A(r,c)=0;\n          Al(r,c)=0;\n          Ar(r,c)=0;\n        }\n    }\n\n  // Newton-Raphson iteration\n  while (ss < ssp)\n    {\n      yy=yy+d;\n      ssp=ss;\n      iter=iter+1;\n      \n      for(auto r=0;r<N;r++)\n        {\n          for (auto c=r;c<N;c++)\n            {   \n              Al(r,c-r)=yy(c);\n            }\n          for (auto c=0;c<(N-r);c++)\n            {   \n              Ar(r,c+r)=yy(c);\n            }\n        }\n      A=Al+Ar;\n      b=hh-(Al*yy);\n      d=A.colPivHouseholderQr().solve(b);\n      ss=d.norm();\n    }\n\n  // Done\n  for(auto r=0;r<N;r++)\n    {\n      y(r)=(double)(yy(r));\n    }\n  octave_value_list retval(nargout);\n  if (nargout >= 1)\n    {\n      retval(0)=y;\n    }\n  if (nargout >= 2)\n    {\n      retval(1)=(double)ssp;\n    }\n  if (nargout == 3)\n    {\n      retval(2)=iter;\n    }\n  return retval;\n}\n", "meta": {"hexsha": "58609162e18fe12300a2138cffea4aa93379c8b7", "size": 3195, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/minphase.cc", "max_stars_repo_name": "robertgj/DesignOfIIRFilters", "max_stars_repo_head_hexsha": "20b8f22b6097c5759209f80d57ce756cad9839a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-11-11T11:44:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-27T03:13:40.000Z", "max_issues_repo_path": "src/minphase.cc", "max_issues_repo_name": "robertgj/DesignOfIIRFilters", "max_issues_repo_head_hexsha": "20b8f22b6097c5759209f80d57ce756cad9839a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/minphase.cc", "max_forks_repo_name": "robertgj/DesignOfIIRFilters", "max_forks_repo_head_hexsha": "20b8f22b6097c5759209f80d57ce756cad9839a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-28T06:26:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T06:26:39.000Z", "avg_line_length": 23.8432835821, "max_line_length": 78, "alphanum_fraction": 0.5871674491, "num_tokens": 940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6258140994509103}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <fstream>\n#include <iostream>\n\n#include \"../include/KF.h\"\n#include \"../include/dsho.h\"\n#include \"../include/matern32.h\"\n#include \"../include/ndsho.h\"\n\n\nusing namespace Eigen;\nusing namespace std;\n\n// function to read a space separated file\n\nstd::vector<double> load_csv (const std::string & path) {\n    std::ifstream indata;\n    indata.open(path);\n    std::string line;\n    std::vector<double> values;\n    uint rows = 0;\n    while (std::getline(indata, line)) {\n        std::stringstream lineStream(line);\n        std::string cell;\n        while (std::getline(lineStream, cell, ' ')) {\n            //cout << std::stod(cell) << endl;\n            values.push_back(std::stod(cell));\n        }\n        ++rows;\n    }\n    return values;\n}\n\nint main()\n{\n\nstd::random_device rd;\nstd::mt19937 rng(rd());\n\n\n// read file with two component damped simple harmonic oscillator simulated data\n//std::vector<double> values = load_csv(\"two_comp_dsho.txt\");\n//cout << values.size() << endl;\n\n\n// map data to VectorXds\n//VectorXd times = Map<VectorXd, 0, InnerStride<2> > (values.data(), 10000);\n//VectorXd yi = Map<VectorXd, 0, InnerStride<2> > (values.data()+1, 10000);\nint vecsize = 10000;\nVectorXd yi(vecsize);\nVectorXd times = Eigen::VectorXd::Random(vecsize);\ntimes.array() += 1.0;\ntimes.array() *= (100*0.5);\nstd::sort(times.data(), times.data() + times.size());\n\n// this is the observational error vector\nVectorXd yerr = VectorXd::Ones(yi.size());\n\ndouble obs_err = 0.05;\nyerr.array() *= obs_err;\n\nstd::uniform_real_distribution<double> uniform(0, 5);\n\n// Now we run a bunch of tests\n\n// create a Matern 3/2 solver and get likelihood of data\ngpstate::matern32::Matern32Solver m32(times, yi, yerr,std::sqrt(10), 1.0);\ndouble log_likelihood = m32.KF_log_likelihood();\ncout << \"logL: \" << log_likelihood << endl;\n\n// simulate a Matern 3/2 on the times given by VectorXd times\nVectorXd y_sim;\nm32.simulate_Matern32(y_sim, rng);\n\n// set parameters for a 2 component DSHO model\nEigen::Vector2d omegas,Qpars,varfs;\nomegas << 1, 3*0.15915494309;\nQpars << 10, 10;\nvarfs << 1, 1;\n\n// set parameters for a single DSHO model\ndouble omega0=12;\ndouble Q=1;\ndouble varf=1;\n\n// simulate a single DSHO with parameters omega0, Q, varf\n// we simulate for various values of Q, and measure the simulated variance\n// objective is to verify that the variance specified by 'varf'\n// corresponds indeed to the actual simulated variance\n// (in other words, we are verifying the normalizations of our GPs)\ngpstate::dsho::DSHOSolver dsho(times,yi,yerr,omega0, Q, varf);\ndsho.simulate_DSHO(y_sim);\n\ndouble mean = y_sim.mean();\nEigen::VectorXd tmp = y_sim.array()-mean;\ndouble variance  = tmp.dot(tmp) / y_sim.rows();\nstd::cout << \"var1:\" << variance << std::endl;\n\nQ = 10;\ndsho.set_pars(omega0,Q,varf);\ndsho.simulate_DSHO(y_sim);\nmean = y_sim.mean();\ntmp = y_sim.array()-mean;\nvariance  = tmp.dot(tmp) / y_sim.rows();\nstd::cout << \"var2:\" << variance << std::endl;\n\nQ = 0.1;\ndsho.set_pars(omega0,Q,varf);\ndsho.simulate_DSHO(y_sim);\nmean = y_sim.mean();\ntmp = y_sim.array()-mean;\nvariance  = tmp.dot(tmp) / y_sim.rows();\nstd::cout << \"var3:\" << variance << std::endl;\n\nQ=10;\nomega0=6;\ndsho.set_pars(omega0,Q,varf);\ndsho.simulate_DSHO(y_sim);\nmean = y_sim.mean();\ntmp = y_sim.array()-mean;\nvariance  = tmp.dot(tmp) / y_sim.rows();\nstd::cout << \"var4:\" << variance << std::endl;\n\nomega0=120;\ndsho.set_pars(omega0,Q,varf);\ndsho.simulate_DSHO(y_sim);\nmean = y_sim.mean();\ntmp = y_sim.array()-mean;\nvariance  = tmp.dot(tmp) / y_sim.rows();\nstd::cout << \"var5:\" << variance << std::endl;\nlog_likelihood = dsho.KF_log_likelihood();\ncout << \"logL: \" << log_likelihood << endl;\n\n//std::exit(0);\n\nEigen::Matrix<double,1,1> omega_one, Qpar_one, varf_one;\nomega_one << 120;\nQpar_one << 10;\nvarf_one << 1;\n\n// Verify that the ndsho implementation is consistent with the dsho one\ngpstate::n_dsho::N_DSHOSolver ndsho(times,yi,yerr,omega_one, Qpar_one, varf_one);\nndsho.simulate_N_DSHO(y_sim, rng);\nmean = y_sim.mean();\ntmp = y_sim.array()-mean;\nvariance  = tmp.dot(tmp) / y_sim.rows();\nstd::cout << \"var6:\" << variance << std::endl;\nlog_likelihood = ndsho.KF_log_likelihood();\ncout << \"logL: \" << log_likelihood << endl;\n\n// write simulated vector to file GPtest.txt\nstd::ofstream file(\"GPtest.txt\");\nif (file.is_open())\n  {\n    file << \"#time y_sim\" << endl;\n    for(int i=0; i<times.rows(); i++)\n    {\n        file <<  times(i) <<\" \"<< y_sim(i) << endl;\n    }\n  }\n\n\n}\n", "meta": {"hexsha": "0a999508e217394cd47ff9c48548288008253c1a", "size": 4464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_varf.cpp", "max_stars_repo_name": "andres-jordan/gpstate", "max_stars_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-13T23:27:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-13T23:27:32.000Z", "max_issues_repo_path": "src/test_varf.cpp", "max_issues_repo_name": "andres-jordan/gpstate", "max_issues_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_varf.cpp", "max_forks_repo_name": "andres-jordan/gpstate", "max_forks_repo_head_hexsha": "4daabcd0b851318c581995836ebd81e6ecde6f54", "max_forks_repo_licenses": ["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.0545454545, "max_line_length": 81, "alphanum_fraction": 0.6724910394, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6258140945387487}}
{"text": "#pragma once\n\n#include <Geometry/LineSegment.hpp>\n\n#include <opencv2/core/core.hpp>\n#include <Eigen/Dense>\n\n#include <numeric>\n#include <vector>\n\nnamespace pcv\n{\n\n\n/**\n * Utility function to help determine \"leftness\" of a point compared to the line\n * segment drawn between the first two points. Leftness is indicated by a\n * negative return value, which is why the tempalate parameter must be signed.\n * Idea from Computational Geometry in C by Joseph O'Rourke.\n */\ntemplate<class SignedNumericType>\nSignedNumericType getTwiceSignedArea2D(\n    const Eigen::Matrix<SignedNumericType, 2, 1> &endpoint0,\n    const Eigen::Matrix<SignedNumericType, 2, 1> &endpoint1,\n    const Eigen::Matrix<SignedNumericType, 2, 1> &testpoint)\n{\n    static_assert(std::is_signed<SignedNumericType>::value);\n\n    // Aliases for more readable arithmetic.\n    const auto &a = endpoint0;\n    const auto &b = endpoint1;\n    const auto &c = testpoint;\n\n    return ((b.x() - a.x()) * (c.y() - a.y()))\n         - ((c.x() - a.x()) * (b.y() - a.y()));\n}\n\n\n/**\n * \\class ConvexPolygon\n * Create a polygon by specifying its vertices in a clockwise direction. Points\n * are 2D Eigen::Vectors.\n */\ntemplate<class NumericType>\nclass ConvexPolygon\n{\npublic:\n    ConvexPolygon() = default;\n\n\n    ConvexPolygon(const ConvexPolygon &polygon) = default;\n\n\n    /**\n     * Move construction leverages std::vector's move constructor.\n     */\n    ConvexPolygon(ConvexPolygon &&polygon) = default;\n\n\n    ~ConvexPolygon() = default;\n\n\n    ConvexPolygon(const std::vector<Eigen::Matrix<NumericType, 2, 1>> &vertices) : vertices(vertices)\n    {}\n\n\n    ConvexPolygon(std::vector<Eigen::Matrix<NumericType, 2, 1>> &&vertices) : vertices(vertices)\n    {}\n\n\n    void addVertex(Eigen::Matrix<NumericType, 2, 1> &&vertex)\n    {\n        vertices.emplace_back(vertex);\n    }\n\n\n    void addVertex(const Eigen::Matrix<NumericType, 2, 1> &vertex)\n    {\n        vertices.push_back(vertex);\n    }\n\n\n    std::vector<Eigen::Matrix<NumericType, 2, 1>> getVertices() const\n    {\n        return vertices;\n    }\n\n\n    /**\n     * Determine if a given point is inside or outside the polygon in O(n) where\n     * n is the number of vertices of the polygon. This function requires a\n     * point to be represented as two doubles, even if the points can be\n     * represented with integers or the polygon has a non-floating point\n     * templated NumericType. The current implementation does not account for\n     * floating-point error.\n     */\n    bool isPointContained(Eigen::Vector2d testPoint) const;\n\n    /**\n     * Constructs a ConvexPolygon representing the minimum size rectangle with\n     * sides perpendicular and parallel to the x-axis that completely encompasses\n     * all points in the polygon.\n     */\n    ConvexPolygon<NumericType> getBoundingBox() const;\n\n    /**\n     * Transforms the polygon in-place with a 3x3 homographic transformation\n     * matrix. Can only transform floating-point vertex definitions of polygons.\n     * This method is not thread-safe.\n     */\n    void transform(const Eigen::Matrix3d &transform);\n\n    /**\n     * Get the ConvexPolygon that bounds the intersection of the polygons. The\n     * public interface makes no runtime performance guarantee!\n     */\n    ConvexPolygon<double> getIntersectionWith(\n            const ConvexPolygon<NumericType> &rhsPoly) const;\n\nprivate:\n    std::vector<Eigen::Matrix<NumericType, 2, 1>> vertices;\n};\n\n/**\n * Need to use another template parameter for rhsPoly's numeric type.\n */\ntemplate<class NumericType>\nConvexPolygon<double> ConvexPolygon<NumericType>::getIntersectionWith(\n        const ConvexPolygon<NumericType> &rhsPoly) const\n{\n    const auto rhsVertices = rhsPoly.getVertices();\n    auto rhsPrevVertex = rhsVertices.back();\n    auto lhsPrevVertex = vertices.back();\n\n    ConvexPolygon<double> intersection(\n        std::accumulate(\n            std::cbegin(vertices),\n            std::cend(vertices),\n            std::vector<Eigen::Vector2d>{},\n            [&lhsPrevVertex, &rhsPrevVertex, &rhsVertices](\n                std::vector<Eigen::Vector2d> accumulator,\n                decltype(lhsPrevVertex) lhsVertexIter)\n            {\n                for (const auto &rhsVertexIter : rhsVertices)\n                {\n                    auto intersection = getSegmentIntersectionPoint2(\n                        lhsPrevVertex, lhsVertexIter, rhsPrevVertex, rhsVertexIter);\n                    if (intersection)\n                    {\n                        accumulator.emplace_back(*intersection);\n                    }\n                    rhsPrevVertex = rhsVertexIter;\n                }\n\n                lhsPrevVertex = lhsVertexIter;\n                return accumulator;\n            }));\n\n    return intersection;\n}\n\ntemplate<class NumericType>\nbool ConvexPolygon<NumericType>::isPointContained(\n    Eigen::Vector2d testPoint) const\n{\n    auto cachedVertex = vertices.back();\n\n    return std::accumulate(\n        std::cbegin(vertices),\n        std::cend(vertices),\n        true,\n        [&cachedVertex, testPoint](bool isContained, decltype(cachedVertex) vertexIter)\n        {\n            isContained &=\n                getTwiceSignedArea2D(\n                    static_cast<Eigen::Vector2d>(cachedVertex.template cast<double>()),\n                    static_cast<Eigen::Vector2d>(vertexIter.template cast<double>()),\n                    testPoint) <= 0;\n\n            cachedVertex = vertexIter;\n            return isContained;\n        });\n}\n\ntemplate<class NumericType>\nConvexPolygon<NumericType> ConvexPolygon<NumericType>::getBoundingBox() const\n{\n    NumericType minX = vertices[0].x();\n    NumericType minY = vertices[0].y();\n    NumericType maxX = vertices[0].x();\n    NumericType maxY = vertices[0].y();\n\n    // Start iterator one after the beginning.\n    const auto vertex = vertices.cbegin();\n    std::advance(vertices, 1);\n    for(; vertex != std::cend(vertex); std::next(vertex))\n    {\n        minX = std::min(vertex.x(), minX);\n        minY = std::min(vertex.y(), minY);\n        maxX = std::max(vertex.x(), maxX);\n        maxY = std::max(vertex.y(), maxY);\n    }\n\n    // This is weird, the size is not dynamic, it's 2 because the points are 2D.\n    ConvexPolygon<NumericType> output;\n    output.addVertex(Eigen::Matrix<NumericType, Eigen::Dynamic, Eigen::Dynamic>{\n        minX, minY});\n    output.addVertex(Eigen::Matrix<NumericType, Eigen::Dynamic, Eigen::Dynamic>{\n        minX, maxY});\n    output.addVertex(Eigen::Matrix<NumericType, Eigen::Dynamic, Eigen::Dynamic>{\n        maxX, maxY});\n    output.addVertex(Eigen::Matrix<NumericType, Eigen::Dynamic, Eigen::Dynamic>{\n        maxX, minY});\n\n    return output;\n}\n\n/**\n * An O(n) operation where n is the max of the two polygon's number of vertices.\n */\ntemplate<class NumericType>\nbool operator==(\n    const ConvexPolygon<NumericType> &lhs,\n    const ConvexPolygon<NumericType> &rhs)\n{\n    return lhs.getVertices() == rhs.getVertices();\n}\n\n\ntemplate<class NumericType>\nEigen::Matrix<NumericType, Eigen::Dynamic, Eigen::Dynamic>\nmakePolygonIntersectionEigenGrid(\n    const std::vector<ConvexPolygon<NumericType>> &polygons,\n    std::size_t gridRows,\n    std::size_t gridCols)\n{\n    static_assert(std::is_arithmetic<NumericType>::value,\n                  \"Must have numerical polygon type.\");\n\n    Eigen::Matrix<NumericType, Eigen::Dynamic, Eigen::Dynamic> mask =\n        Eigen::Matrix<NumericType, Eigen::Dynamic, Eigen::Dynamic>::Zero(gridRows, gridCols);\n\n    for (std::size_t r = 0; r < gridRows; ++r)\n    {\n        for (std::size_t c = 0; c < gridCols; ++c)\n        {\n            bool containment = true;\n            for (const auto &polygon : polygons)\n            {\n                containment &= polygon.isPointContained(Eigen::Vector2d{c, gridRows-r-1});\n            }\n            mask(r, c) = containment;\n        }\n    }\n\n    return mask;\n}\n\n\ntemplate<class PolygonNumericType, class MatNumericType>\nvoid makePolygonIntersectionOpencvGrid(\n    const std::vector<ConvexPolygon<PolygonNumericType>> &polygons,\n    std::size_t gridRows,\n    std::size_t gridCols,\n    cv::Mat_<MatNumericType> &output)\n{\n    cv::Mat_<MatNumericType> mask(gridRows, gridCols);\n\n    for (std::size_t r = 0; r < gridRows; ++r)\n    {\n        for (std::size_t c = 0; c < gridCols; ++c)\n        {\n            bool containment = true;\n            for (const auto &polygon : polygons)\n            {\n                containment &= polygon.isPointContained(Eigen::Vector2d{c, gridRows-r-1});\n            }\n            mask(r, c) = static_cast<MatNumericType>(containment);\n        }\n    }\n\n    output = mask;\n}\n\ntemplate<class NumericType>\ninline void ConvexPolygon<NumericType>::transform(const Eigen::Matrix3d &transformMatrix)\n{\n    static_assert(std::is_floating_point<NumericType>::value,\n                  \"Can only perform in-place transformations with floating-point\"\n                  \" polygons.\");\n\n    const auto &tform = transformMatrix;\n    std::transform(\n        std::begin(vertices), std::end(vertices), std::begin(vertices),\n        [tform](decltype(vertices[0]) vertex)\n        {\n            Eigen::Matrix<NumericType, 3, 1> homogenousVertex;\n            homogenousVertex << vertex[0], vertex[1], 1;\n\n            Eigen::Matrix<NumericType, 3, 1> homogenousNewVertex =\n                tform * homogenousVertex;\n\n            Eigen::Matrix<NumericType, 2, 1> newVertex;\n            newVertex << homogenousNewVertex[0], homogenousNewVertex[1];\n\n            // Bring back to pixel coordinates.\n            newVertex /= homogenousNewVertex[2];\n            return newVertex;\n        });\n}\n\n} // end namespace pcv\n", "meta": {"hexsha": "e7bcb0470ebd928350ec25135cd230f777013cb7", "size": 9582, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/Geometry/include/Geometry/ConvexPolygon.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/Geometry/include/Geometry/ConvexPolygon.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/Geometry/include/Geometry/ConvexPolygon.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": 30.6134185304, "max_line_length": 101, "alphanum_fraction": 0.636297224, "num_tokens": 2254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6258140942161676}}
{"text": "\n#define BOOST_NUMERIC_FUNCTIONAL_STD_COMPLEX_SUPPORT 1\n#define BOOST_NUMERIC_FUNCTIONAL_STD_VALARRAY_SUPPORT 1\n#define BOOST_NUMERIC_FUNCTIONAL_STD_VECTOR_SUPPORT 1\n#include <complex>\n#include <iostream>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/accumulators/statistics.hpp>\n\n// this code comes from:\n// http://hiankun.blogspot.de/2011/09/using-boost-accumulators-to-calculate.html\nint main(){\n  //using namespace boost::accumulators;\n    boost::accumulators::accumulator_set< double, boost::accumulators::stats<boost::accumulators::tag::variance> > acc_variance;\n \n    for (int i = 0; i < 10; i++){\n        std::cout << i << \", \";\n        acc_variance(i);\n    }\n \n    std::cout << std::endl << \"Variance = \"\n              << sqrt(boost::accumulators::variance(acc_variance)) << std::endl;\n\n    std::cout << std::endl << \"Mean = \"\n        << boost::accumulators::mean(acc_variance) << std::endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "e5ad7503ce28843d46906c8990ce7e2f870f636e", "size": 1041, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "audio_sync/varianceexample.cxx", "max_stars_repo_name": "mmccoo/nerd_mmccoo", "max_stars_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2017-06-21T07:46:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T01:39:02.000Z", "max_issues_repo_path": "audio_sync/varianceexample.cxx", "max_issues_repo_name": "zxh1986123/nerd_mmccoo", "max_issues_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T19:29:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-14T09:27:18.000Z", "max_forks_repo_path": "audio_sync/varianceexample.cxx", "max_forks_repo_name": "zxh1986123/nerd_mmccoo", "max_forks_repo_head_hexsha": "dc5a152105d65673679ef37ea5d1f7607e4f3b2c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-02-12T21:18:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T23:04:51.000Z", "avg_line_length": 32.53125, "max_line_length": 128, "alphanum_fraction": 0.7031700288, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7217431943271998, "lm_q1q2_score": 0.6257771588755294}}
{"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__INTERNAL__C1_HPP_\n#define SMOOTH__INTERNAL__C1_HPP_\n\n#include <Eigen/Core>\n\n#include \"common.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief C(1) Lie group of rotation and scaling\n *\n * Elements are on the form \\f$ k R \\f$ where \\f$ k > 0 \\f$ is a scalar and \\f$ R \\in SO(2) \\f$.\n *\n * Memory layout\n * -------------\n * Group:    a b\n * Tangent:  s \u03a9z\n *\n * Lie group Matrix form\n * ---------------------\n * [ b -a ]\n * [ a  b ]\n *\n * Lie algebra Matrix form\n * -----------------------\n * [ s -\u03a9z ]\n * [ \u03a9z  s ]\n *\n * Constraints\n * -----------\n * Group:   a * a - b * b > 0\n * Tangent: -pi < \u03a9z <= pi\n */\ntemplate<typename _Scalar>\nclass C1Impl\n{\npublic:\n  using Scalar = _Scalar;\n\n  static constexpr Eigen::Index RepSize = 2;\n  static constexpr Eigen::Index Dim     = 2;\n  static constexpr Eigen::Index Dof     = 2;\n\n  SMOOTH_DEFINE_REFS;\n\n  static void setIdentity(GRefOut g_out) { g_out << Scalar(0), Scalar(1); }\n\n  static void setRandom(GRefOut g_out)\n  {\n    using std::sin, std::cos;\n\n    const Scalar u = Eigen::internal::template random_impl<Scalar>::run(0, 2 * M_PI);\n    const Scalar t = Eigen::internal::template random_impl<Scalar>::run(0.01, 100);\n    g_out << t * sin(u), t * cos(u);\n  }\n\n  static void matrix(GRefIn g_in, MRefOut m_out) { m_out << g_in(1), -g_in(0), g_in(0), g_in(1); }\n\n  static void composition(GRefIn g_in1, GRefIn g_in2, GRefOut g_out)\n  {\n    g_out << g_in1[0] * g_in2[1] + g_in1[1] * g_in2[0], g_in1[1] * g_in2[1] - g_in1[0] * g_in2[0];\n  }\n\n  static void inverse(GRefIn g_in, GRefOut g_out)\n  {\n    const Scalar t = g_in[0] * g_in[0] + g_in[1] * g_in[1];\n    g_out << -g_in[0] / t, g_in[1] / t;\n  }\n\n  static void log(GRefIn g_in, TRefOut a_out)\n  {\n    using std::atan2, std::sqrt, std::log;\n\n    const Scalar t = sqrt(g_in[0] * g_in[0] + g_in[1] * g_in[1]);\n    a_out << log(t), atan2(g_in[0], g_in[1]);\n  }\n\n  static void Ad(GRefIn, TMapRefOut A_out) { A_out.setIdentity(); }\n\n  static void exp(TRefIn a_in, GRefOut g_out)\n  {\n    using std::cos, std::exp, std::sin;\n\n    const Scalar t = exp(a_in.x());\n    g_out << t * sin(a_in.y()), t * cos(a_in.y());\n  }\n\n  static void hat(TRefIn a_in, MRefOut A_out) { A_out << a_in(0), -a_in(1), a_in(1), a_in(0); }\n\n  static void vee(MRefIn A_in, TRefOut a_out)\n  {\n    a_out << (A_in(0, 0) + A_in(1, 1)) / Scalar(2), (A_in(1, 0) - A_in(0, 1)) / Scalar(2);\n  }\n\n  static void ad(TRefIn, TMapRefOut A_out) { A_out.setZero(); }\n\n  static void dr_exp(TRefIn, TMapRefOut A_out) { A_out.setIdentity(); }\n\n  static void dr_expinv(TRefIn, TMapRefOut A_out) { A_out.setIdentity(); }\n};\n\n}  // namespace smooth\n\n#endif  // SMOOTH__INTERNAL__C1_HPP_\n", "meta": {"hexsha": "0dd089e10386b3493a824919dc227242b619bdc4", "size": 3895, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/internal/c1.hpp", "max_stars_repo_name": "pettni/smooth", "max_stars_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T21:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T13:26:44.000Z", "max_issues_repo_path": "include/smooth/internal/c1.hpp", "max_issues_repo_name": "pettni/lie", "max_issues_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2021-07-07T21:13:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T04:40:37.000Z", "max_forks_repo_path": "include/smooth/internal/c1.hpp", "max_forks_repo_name": "pettni/lie", "max_forks_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T07:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:29:44.000Z", "avg_line_length": 29.7328244275, "max_line_length": 98, "alphanum_fraction": 0.6505776637, "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6257771539160664}}
{"text": "//\n// Created by matt on 21/01/2021.\n//\n\n#include \"simple_kf.h\"\n\n#include <iostream>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\nnamespace kf0 {\n\nKalmanFilter::KalmanFilter() {\n  // State, position (x, y) and velocity (x, y)\n  x_.setZero();\n  // Initialise covariance with high values\n  P_.setZero();\n  P_.diagonal() = Eigen::Vector4d::Constant(100.0);\n  // Process model\n  // v' = v\n  // p' = p + v*dt\n  F_.setIdentity();\n  F_(0, 2) = dt; // px' = px + vx*dt\n  F_(1, 3) = dt; // py' = py + vy*dt\n  // Process noise\n  Q_ = Eigen::Matrix<double, 4, 4>::Identity() * 2.0; // TODO placeholder\n  // Measurement model\n  // Measure position\n  H_.setZero();\n  H_(0, 0) = 1.0;\n  H_(1, 1) = 1.0;\n  // Measurement noise\n  R_.setIdentity(); // TODO placeholder\n\n  //    std::cout << \"F: \" << '\\n';\n  //    std::cout << F_ << '\\n';\n  //    std::cout << \"x: \" << '\\n';\n  //    std::cout << x_.transpose() << '\\n';\n  //    std::cout << \"P: \" << '\\n';\n  //    std::cout << P_ << '\\n';\n  //    std::cout << \"Q: \" << '\\n';\n  //    std::cout << Q_ << '\\n';\n  //    std::cout << \"H: \" << '\\n';\n  //    std::cout << H_ << '\\n';\n  //    std::cout << \"R: \" << '\\n';\n  //    std::cout << R_ << \"\\n\\n\";\n}\n\nEigen::Matrix<double, 4, 1> KalmanFilter::Predict() {\n  x_ = F_ * x_;\n  P_ = F_ * P_ * F_.transpose() + Q_;\n\n  //    std::cout << \"Predict\\n\";\n  //    std::cout << \"F: \" << '\\n';\n  //    std::cout << F_ << '\\n';\n  //    std::cout << \"x: \" << '\\n';\n  //    std::cout << x_.transpose() << '\\n';\n  //    std::cout << \"P: \" << '\\n';\n  //    std::cout << P_ << \"\\n\\n\";\n  return x_;\n}\n\nEigen::Matrix<double, 4, 1>\nKalmanFilter::Update(const Eigen::Matrix<double, 2, 1> &z) {\n  z_hat_ = H_ * x_;\n  y_ = z - z_hat_;\n  S_ = H_ * P_ * H_.transpose() + R_;\n  K_ = P_ * H_.transpose() * S_.inverse();\n  x_ = x_ + K_ * y_;\n  P_ = (Eigen::Matrix4d::Identity() - K_ * H_) * P_;\n\n  //    std::cout << \"Update\\n\";\n  //    std::cout << \"z: \" << '\\n';\n  //    std::cout << z.transpose() << '\\n';\n  //    std::cout << \"z_hat: \" << '\\n';\n  //    std::cout << z_hat_.transpose() << '\\n';\n  //    std::cout << \"y: \" << '\\n';\n  //    std::cout << y_.transpose() << '\\n';\n  //    std::cout << \"S: \" << '\\n';\n  //    std::cout << S_ << '\\n';\n  //    std::cout << \"K: \" << '\\n';\n  //    std::cout << K_ << '\\n';\n  //    std::cout << \"x: \" << '\\n';\n  //    std::cout << x_.transpose() << '\\n';\n  //    std::cout << \"P: \" << '\\n';\n  //    std::cout << P_ << \"\\n\\n\";\n\n  return x_;\n}\n\n} // namespace kf0", "meta": {"hexsha": "a7943b1592a47deaa759cf8c04d30c75da5959fb", "size": 2454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simple_kf.cpp", "max_stars_repo_name": "matt769/kalman_filters", "max_stars_repo_head_hexsha": "f99c4f6dac316a674e25dadd80f0f6455d962515", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simple_kf.cpp", "max_issues_repo_name": "matt769/kalman_filters", "max_issues_repo_head_hexsha": "f99c4f6dac316a674e25dadd80f0f6455d962515", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simple_kf.cpp", "max_forks_repo_name": "matt769/kalman_filters", "max_forks_repo_head_hexsha": "f99c4f6dac316a674e25dadd80f0f6455d962515", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6739130435, "max_line_length": 73, "alphanum_fraction": 0.4478402608, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.625685503266791}}
{"text": "// 1-d PIC code to solve plasma two-stream instability problem.\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <time.h>\n#include <blitz/array.h>\n#include <fftw.h>\n\nusing namespace blitz;\n\nvoid Output (char* fn1, char* fn2, double t, \n\t     Array<double,1> r, Array<double,1> v);\nvoid Density (Array<double,1> r, Array<double,1>& n);\nvoid Electric (Array<double,1> phi, Array<double,1>& E);\nvoid Poisson1D (Array<double,1>& u, Array<double,1> v, double kappa);\nvoid rk4_fixed (double& x, Array<double,1>& y, \n              void (*rhs_eval)(double, Array<double,1>, Array<double,1>&), \n              double h);\nvoid rhs_eval (double t, Array<double,1> y, Array<double,1>& dydt);\nvoid Load (Array<double,1> r, Array<double,1> v, Array<double,1>& y);\nvoid UnLoad (Array<double,1> y, Array<double,1>& r, Array<double,1>& v);\ndouble distribution (double vb);\n\ndouble L; int N, J;\n\nint main()\n{\n  // Parameters\n  L;            // Domain of solution 0 <= x <= L (in Debye lengths)\n  N;            // Number of electrons\n  J;            // Number of grid points\n  double vb;    // Beam velocity\n  double dt;    // Time-step (in inverse plasma frequencies)\n  double tmax;  // Simulation run from t = 0. to t = tmax\n\n  // Get parameters\n  printf (\"Please input N:  \"); scanf (\"%d\", &N);\n  printf (\"Please input vb:  \"); scanf (\"%lf\", &vb); \n  printf (\"Please input L:  \"); scanf (\"%lf\", &L);\n  printf (\"Please input J:  \"); scanf (\"%d\", &J);\n  printf (\"Please input dt:  \"); scanf (\"%lf\", &dt); \n  printf (\"Please input tmax:  \"); scanf (\"%lf\", &tmax);\n  int skip = int (tmax / dt) / 10;\n  if ((N < 1) || (J < 2) || (L <= 0.) || (vb <= 0.) \n      || (dt <= 0.) || (tmax <= 0.) || (skip < 1))\n    {\n      printf (\"Error - invalid input parameters\\n\");\n      exit (1);\n    }\n\n  // Set names of output files\n  char* phase[11]; char* data[11];\n  phase[0] = \"phase0.out\";phase[1] = \"phase1.out\";phase[2] = \"phase2.out\"; \n  phase[3] = \"phase3.out\";phase[4] = \"phase4.out\";phase[5] = \"phase5.out\"; \n  phase[6] = \"phase6.out\";phase[7] = \"phase7.out\";phase[8] = \"phase8.out\";\n  phase[9] = \"phase9.out\";phase[10] = \"phase10.out\";data[0] = \"data0.out\";  \n  data[1] = \"data1.out\"; data[2] = \"data2.out\"; data[3] = \"data3.out\"; \n  data[4] = \"data4.out\"; data[5] = \"data5.out\"; data[6] = \"data6.out\"; \n  data[7] = \"data7.out\"; data[8] = \"data8.out\"; data[9] = \"data9.out\"; \n  data[10] = \"data10.out\";\n\n  // Initialize solution\n  double t = 0.;\n  int seed = time (NULL); srand (seed);\n  Array<double,1> r(N), v(N);\n  for (int i = 0; i < N; i++)\n    {\n      r(i) = L * double (rand ()) / double (RAND_MAX);\n      v(i) = distribution (vb);\n    }\n  Output (phase[0], data[0], t, r, v);\n\n  // Evolve solution\n  Array<double,1> y(2*N);\n  Load (r, v, y);\n  for (int k = 1; k <= 10; k++)\n    {\n      for (int kk = 0; kk < skip; kk++)\n        {\n           // Take time-step\n           rk4_fixed (t, y, rhs_eval, dt);\n\n           // Make sure all coordinates in range 0 to L.\n           for (int i = 0; i < N; i++)\n             {\n               if (y(i) < 0.) y(i) += L;\n               if (y(i) > L) y(i) -= L;\n             }\n\t  \n           printf (\"t = %11.4e\\n\", t);\n        }\n      printf (\"Plot %3d\\n\", k);\n\n      // Output data\n      UnLoad (y, r, v);\n      Output(phase[k], data[k], t, r, v);\n    }\n\n  return 0;\n}\nThe following routine outputs the simulation data to various data-files.\n\n// Write data to output files\n\nvoid Output (char* fn1, char* fn2, double t,\n\t     Array<double,1> r, Array<double,1> v)\n{  \n  // Write phase-space data\n  FILE* file = fopen (fn1, \"w\");\n  for (int i = 0; i < N; i++)\n    fprintf (file, \"%e %e\\n\", r(i), v(i));\n  fclose (file);\n\n  // Write electric field data\n  Array<double,1> ne(J), n(J), phi(J), E(J);  \n  Density (r, ne);\n  for (int j = 0; j < J; j++)\n    n(j) = double (J) * ne(j) / double (N) - 1.;\n  double kappa = 2. * M_PI / L; \n  Poisson1D (phi, n, kappa);\n  Electric (phi, E);\n\n  file = fopen (fn2, \"w\");\n  for (int j = 0; j < J; j++)\n    {\n      double x = double (j) * L / double (J);\n      fprintf (file, \"%e %e %e %e\\n\", x, ne(j), n(j), E(j));\n    }\n  double x = L;\n  fprintf (file, \"%e %e %e %e\\n\", x, ne(0), n(0), E(0));\n  fclose (file);\n}\nThe following routine returns a random velocity distributed on a double Maxwellian distribution function corresponding to two counter-streaming beams. The algorithm used to achieve this is called the rejection method, and will be discussed later in this course.\n\n// Function to distribute electron velocities randomly so as \n// to generate two counter propagating warm beams of thermal\n// velocities unity and mean velocities +/- vb.\n// Uses rejection method.\n\ndouble distribution (double vb)\n{ \n  // Initialize random number generator\n  static int flag = 0;\n  if (flag == 0)\n    {\n      int seed = time (NULL);\n      srand (seed);\n      flag = 1;\n    }\n\n  // Generate random v value\n  double fmax = 0.5 * (1. + exp (-2. * vb * vb));\n  double vmin = - 5. * vb;\n  double vmax = + 5. * vb;\n  double v = vmin + (vmax - vmin) * double (rand ()) / double (RAND_MAX);\n\n  // Accept/reject value\n  double f = 0.5 * (exp (-(v - vb) * (v - vb) / 2.) +\n\t\t    exp (-(v + vb) * (v + vb) / 2.));\n  double x = fmax * double (rand ()) / double (RAND_MAX);\n  if (x > f) return distribution (vb);\n  else return v;\n}\nThe routine below evaluates the electron number density on an evenly spaced mesh given the instantaneous electron coordinates.\n\n// Evaluates electron number density n(0:J-1) from \n// array r(0:N-1) of electron coordinates.\n\nvoid Density (Array<double,1> r, Array<double,1>& n)\n{\n  // Initialize \n  double dx = L / double (J);\n  n = 0.;\n\n  // Evaluate number density.\n  for (int i = 0; i < N; i++)\n    {\n      int j = int (r(i) / dx);\n      double y = r(i) / dx - double (j);\n      n(j) += (1. - y) / dx;\n      if (j+1 == J) n(0) += y / dx;\n      else n(j+1) += y / dx;\n    }\n}\nThe following functions are wrapper routines for using the fftw library with periodic functions.\n\n// Functions to calculate Fourier transforms of real data \n// using fftw Fast-Fourier-Transform routine.\n// Input/ouput arrays are assumed to be of extent J.\n\n// Calculates Fourier transform of array f in arrays Fr and Fi\nvoid fft_forward (Array<double,1>f, Array<double,1>&Fr, \n      Array<double,1>& Fi)\n{\n  fftw_complex ff[J], FF[J];\n\n  // Load data\n  for (int j = 0; j < J; j++)\n    {\n      c_re (ff[j]) = f(j); c_im (ff[j]) = 0.;\n    }\n\n  // Call fftw routine\n  fftw_plan p = fftw_create_plan (J, FFTW_FORWARD, FFTW_ESTIMATE);\n  fftw_one (p, ff, FF);\n  fftw_destroy_plan (p); \n\n  // Unload data\n  for (int j = 0; j < J; j++)\n    {\n      Fr(j) = c_re (FF[j]); Fi(j) = c_im (FF[j]);\n    }\n\n  // Normalize data\n  Fr /= double (J);\n  Fi /= double (J);\n}\n\n// Calculates inverse Fourier transform of arrays Fr and Fi in array f\nvoid fft_backward (Array<double,1> Fr, Array<double,1> Fi, \n      Array<double,1>& f)\n{\n  fftw_complex ff[J], FF[J];\n\n  // Load data\n  for (int j = 0; j < J; j++)\n    {\n      c_re (FF[j]) = Fr(j); c_im (FF[j]) = Fi(j);\n    }\n\n  // Call fftw routine\n  fftw_plan p = fftw_create_plan (J, FFTW_BACKWARD, FFTW_ESTIMATE);\n  fftw_one (p, FF, ff);\n  fftw_destroy_plan (p); \n\n  // Unload data\n  for (int j = 0; j < J; j++)\n      f(j) = c_re (ff[j]); \n}\nThe following routine solves Poisson's equation in 1-D to find the instantaneous electric potential on a uniform grid.\n\n// Solves 1-d Poisson equation:\n//    d^u / dx^2 = v   for  0 <= x <= L\n// Periodic boundary conditions:\n//    u(x + L) = u(x),  v(x + L) = v(x)\n// Arrays u and v assumed to be of length J.\n// Now, jth grid point corresponds to\n//    x_j = j dx  for j = 0,J-1\n// where dx = L / J.\n// Also,\n//    kappa = 2 pi / L\n\nvoid Poisson1D (Array<double,1>& u, Array<double,1> v, double kappa)\n{\n  // Declare local arrays.\n  Array<double,1> Vr(J), Vi(J), Ur(J), Ui(J);\n\n  // Fourier transform source term\n  fft_forward (v, Vr, Vi);\n\n  // Calculate Fourier transform of u\n  Ur(0) = Ui(0) = 0.;\n  for (int j = 1; j <= J/2; j++)\n    {\n      Ur(j) = - Vr(j) / double (j * j) / kappa / kappa;\n      Ui(j) = - Vi(j) / double (j * j) / kappa / kappa;\n    } \n  for (int j = J/2; j < J; j++)\n    {\n      Ur(j) = Ur(J-j);\n      Ui(j) = - Ui(J-j);\n    }\n\n  // Inverse Fourier transform to obtain u\n  fft_backward (Ur, Ui, u);\n}\nThe following function evaluates the electric field on a uniform grid from the electric potential.\n\n// Calculate electric field from potential\n\nvoid Electric (Array<double,1> phi, Array<double,1>& E)\n{\n  double dx = L / double (J);\n\n  for (int j = 1; j < J-1; j++)\n    E(j) = (phi(j-1) - phi(j+1)) / 2. / dx;\n  E(0) = (phi(J-1) - phi(1)) / 2. / dx;\n  E(J-1) = (phi(J-2) - phi(0)) / 2. / dx;\n}\nThe following routine is the right-hand side routine for the electron equations of motion. Is is designed to be used with the fixed-step RK4 solver described earlier in this course.\n\n// Electron equations of motion:\n//    y(0:N-1)  = r_i\n//    y(N:2N-1) = dr_i/dt\n\nvoid rhs_eval (double t, Array<double,1> y, Array<double,1>& dydt)\n{\n  // Declare local arrays\n  Array<double,1> r(N), v(N), rdot(N), vdot(N), r0(N);\n  Array<double,1> ne(J), rho(J), phi(J), E(J);\n\n  // Unload data from y\n  UnLoad (y, r, v);\n\n  // Make sure all coordinates in range 0 to L\n  r0 = r;\n  for (int i = 0; i < N; i++)\n    {\n      if (r0(i) < 0.) r0(i) += L;\n      if (r0(i) > L) r0(i) -= L;\n    }\n\n  // Calculate electron number density\n  Density (r0, ne);\n\n  // Solve Poisson's equation\n  double n0 = double (N) / L;\n  for (int j = 0; j < J; j++)\n    rho(j) = ne(j) / n0 - 1.;\n  double kappa = 2. * M_PI / L; \n  Poisson1D (phi, rho, kappa);\n\n  // Calculate electric field\n  Electric (phi, E);\n\n  // Equations of motion\n  for (int i = 0; i < N; i++)\n    {\n      double dx = L / double (J);\n      int j = int (r0(i) / dx);\n      double y = r0(i) / dx - double (j);\n      \n      double Efield;\n      if (j+1 == J)\n         Efield = E(j) * (1. - y) + E(0) * y;\n      else\n         Efield = E(j) * (1. - y) + E(j+1) * y;\n\n      rdot(i) = v(i);\n      vdot(i) = - Efield;\n    }\n\n  // Load data into dydt\n  Load (rdot, vdot, dydt);\n}\nThe following functions load and unload the electron phase-space coordinates into the solution vector y used by the RK4 routine.\n\n// Load particle coordinates into solution vector\n\nvoid Load (Array<double,1> r, Array<double,1> v, Array<double,1>& y)\n{\n  for (int i = 0; i < N; i++)\n    {\n      y(i) = r(i);\n      y(N+i) = v(i);\n    }\n}\n\n// Unload particle coordinates from solution vector\n\nvoid UnLoad (Array<double,1> y, Array<double,1>& r, Array<double,1>& v)\n{\n  for (int i = 0; i < N; i++)\n    {\n      r(i) = y(i);\n      v(i) = y(N+i);\n    }\n}", "meta": {"hexsha": "04e20f6bb70aca09dbc30925539983b14289bb20", "size": 10598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CPP_Projects/Sample/ex2.cpp", "max_stars_repo_name": "GUNU-GO/SNUPI", "max_stars_repo_head_hexsha": "a73137699d9fc6ae8fa3d1522f341c04d8d43052", "max_stars_repo_licenses": ["MIT"], "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_Projects/Sample/ex2.cpp", "max_issues_repo_name": "GUNU-GO/SNUPI", "max_issues_repo_head_hexsha": "a73137699d9fc6ae8fa3d1522f341c04d8d43052", "max_issues_repo_licenses": ["MIT"], "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_Projects/Sample/ex2.cpp", "max_forks_repo_name": "GUNU-GO/SNUPI", "max_forks_repo_head_hexsha": "a73137699d9fc6ae8fa3d1522f341c04d8d43052", "max_forks_repo_licenses": ["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.7208672087, "max_line_length": 261, "alphanum_fraction": 0.5623702585, "num_tokens": 3525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.6256854917732791}}
{"text": "#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n#include <cmath>\n#include <iomanip>\n\nconst int precision = 100; // CHANGE FOR HIGHER PRECISION\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<precision> > arbFloat;\n\n// Prototypes\nbool isStringValid(std::string str);\nbool isNumberValid(arbFloat x);\n\nint main() {\n    // Multi-precision float declaration\n    arbFloat wnew = 0.0;\n    \n    // Input and check string input\n    std::cout << \"0 <= x <= 1e9\\nW(x), x = \";\n    std::string inputStr;\n    std::cin >> inputStr;\n    if(!isStringValid(inputStr)) return 2;\n    \n    // Convert to arbFloat and check number\n    arbFloat input = static_cast<arbFloat>(inputStr);\n    if(!isNumberValid(input)) return 3;\n    \n    std::cout << std::setprecision(precision) << \"\\nConvergence:\\n\";\n    \n    std::string firstStr, secondStr;\n    \n    // Calculations\n    int i;\n    for(i = 0; i <= 1e99; i++){\n        firstStr = wnew.convert_to<std::string>();\n        firstStr.resize(precision + 2);\n        \n        wnew = ((wnew * wnew) + input * exp(-wnew))/(1+wnew);\n        \n        secondStr = wnew.convert_to<std::string>();\n        secondStr.resize(precision + 2);\n        \n        std::cout << '\\t' << wnew << '\\n';\n        \n        if(firstStr == secondStr)\n            break;\n    }\n    \n    // Print result\n    std::cout << \"\\nW(\" << input << \") = \" << wnew << \"\\n\\n(rounded up to \"\n            << precision << \" digits, precise after \" << i << \" iterations)\\n\";\n\n    return 0;\n}\n\n// Check input\nbool isStringValid(std::string str){\n    // Check string containing multiple .\n    std::size_t pos = str.find('.', 0);\n    if(pos != std::string::npos){\n        pos = str.find('.', pos+1);\n        if(pos != std::string::npos){\n            std::cout << \"\\nError: Multiple decimal marks\\n\";\n            return false;\n        }\n    }\n    \n    // Check if NaN\n    try{\n        std::stod(str);\n    } catch(...){\n        std::cout << \"\\nError: NaN\\n\";\n    }\n    \n    return true;\n}\n\n// Check number\nbool isNumberValid(arbFloat x){\n    // Check if result is imaginary\n    if(x < 0){\n        std::cout << \"\\nError: Imaginary result\\n\";\n        return false;\n    }\n    \n    // Range check\n    if(x > 1e9){\n        std::cout << \"\\nError: Out of bounds\\n\";\n        return false;\n    }\n    \n    return true;\n}\n", "meta": {"hexsha": "6c70a157439db0a627dc6b00b6f168ebd7410269", "size": 2332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lambert-W-function/Lambert-W-function-v1.cpp", "max_stars_repo_name": "esote/mathematical-functions", "max_stars_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lambert-W-function/Lambert-W-function-v1.cpp", "max_issues_repo_name": "esote/mathematical-functions", "max_issues_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lambert-W-function/Lambert-W-function-v1.cpp", "max_forks_repo_name": "esote/mathematical-functions", "max_forks_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0752688172, "max_line_length": 97, "alphanum_fraction": 0.5536020583, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6256854903665865}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/src/Geometry/AngleAxis.h>\n\nusing namespace std;\nusing namespace Eigen;\n\nEigen::Matrix3d eulerAnglesToRotationMatrix(Eigen::Vector3d &theta);\nbool isRotationMatirx(Eigen::Matrix3d R);\nEigen::Vector3d rotationMatrixToEulerAngles(Eigen::Matrix3d &R);\n\nconst double ARC_TO_DEG = 57.29577951308238;\nconst double DEG_TO_ARC = 0.0174532925199433;\n\nint main1(){\n    double roll_deg = 0.5;      // \u7ed5X\u8f74\n    double pitch_deg = 0.8;     // \u7ed5Y\u8f74\n    double yaw_deg = 108.5;     // \u7ed5Z\u8f74\n\n    // \u8f6c\u5316\u4e3a\u5f27\u5ea6\n    double roll_arc = roll_deg * DEG_TO_ARC;    // \u7ed5X\u8f74\n    double pitch_arc = pitch_deg * DEG_TO_ARC;  // \u7ed5Y\u8f74\n    double yaw_arc = yaw_deg * DEG_TO_ARC;      // \u7ed5Z\u8f74\n\n    roll_arc =  1.12854674230422;    // \u7ed5X\u8f74\n    pitch_arc = 1.08062392168743;  // \u7ed5Y\u8f74\n    yaw_arc =   1.10953306595605;      // \u7ed5Z\u8f74\n\n}\n\nint main()\n{\n//    \u771f\u503c\u83b7\u53d6\n    double lc_r = 0.015;\n    double lc_p = 0.032;\n    double lc_y = 0.061;\n\n    double t_lc_x = 0.04;\n    double t_lc_y = 0.08;\n    double t_lc_z = -0.061;\n\n    Eigen::AngleAxisd roll(AngleAxisd(lc_r, Vector3d::UnitZ()));\n    Eigen::AngleAxisd pitch(AngleAxisd(-lc_p, Vector3d::UnitX()));\n    Eigen::AngleAxisd yaw(AngleAxisd(-lc_y, Vector3d::UnitY()));\n    Eigen::Matrix3d R_base;\n    R_base<<\n           0, -1, 0,\n        0, 0, -1,\n        1, 0,  0;\n    Matrix3d gt_R_lc;\n    gt_R_lc = roll * yaw * pitch;\n\n//0.0150279\n//-0.0609931\n//-0.0329161\n\n    Vector3d gt_t_lc = R_base * Eigen::Vector3d(t_lc_x, t_lc_y, t_lc_z);\n    Matrix3d gt_R_cl = gt_R_lc.transpose();\n    Vector3d gt_t_cl = -gt_R_cl * gt_t_lc;\n    cout <<setprecision(15)<<\"gt_rpy_cl:\\n\"<<gt_R_cl.eulerAngles(2,1,0)<<endl;\n    cout <<\"gt_R_cl:\\n\"<<gt_R_cl<<endl;\n    cout <<\"gt_t_cl:\\n\"<<gt_t_cl<<endl;\n\n    // \u8f6c\u5316\u4e3a\u5f27\u5ea6\n    double roll_arc = gt_R_cl.eulerAngles(2,1,0).z();    // \u7ed5X\u8f74\n    double pitch_arc = gt_R_cl.eulerAngles(2,1,0).y();  // \u7ed5Y\u8f74\n    double yaw_arc = gt_R_cl.eulerAngles(2,1,0).x();      // \u7ed5Z\u8f74\n\n\n    cout << endl;\n    cout << \"roll_arc = \" << roll_arc << endl;\n    cout << \"pitch_arc = \" << pitch_arc << endl;\n    cout << \"yaw_arc = \" << yaw_arc << endl;\n\n    // \u521d\u59cb\u5316\u6b27\u62c9\u89d2\uff08rpy\uff09,\u5bf9\u5e94\u7ed5x\u8f74\uff0c\u7ed5y\u8f74\uff0c\u7ed5z\u8f74\u7684\u65cb\u8f6c\u89d2\u5ea6\n    Eigen::Vector3d euler_angle(roll_arc, pitch_arc, yaw_arc);\n\n    // \u4f7f\u7528Eigen\u5e93\u5c06\u6b27\u62c9\u89d2\u8f6c\u6362\u4e3a\u65cb\u8f6c\u77e9\u9635\n    Eigen::Matrix3d rotation_matrix1, rotation_matrix2;\n    rotation_matrix1 = Eigen::AngleAxisd(euler_angle[2], Eigen::Vector3d::UnitZ()) *\n        Eigen::AngleAxisd(euler_angle[1], Eigen::Vector3d::UnitY()) *\n        Eigen::AngleAxisd(euler_angle[0], Eigen::Vector3d::UnitX());\n    cout << \"\\nrotation matrix1 =\\n\" << rotation_matrix1 << endl << endl;\n\n    // \u4f7f\u7528\u81ea\u5b9a\u4e49\u51fd\u6570\u5c06\u6b27\u62c9\u89d2\u8f6c\u6362\u4e3a\u65cb\u8f6c\u77e9\u9635\n    rotation_matrix2 = eulerAnglesToRotationMatrix(euler_angle);\n    cout << \"rotation matrix2 =\\n\" << rotation_matrix2 << endl << endl;\n\n    // \u4f7f\u7528Eigen\u5c06\u65cb\u8f6c\u77e9\u9635\u8f6c\u6362\u4e3a\u6b27\u62c9\u89d2\n    Eigen::Vector3d eulerAngle1 = rotation_matrix1.eulerAngles(2,1,0); // ZYX\u987a\u5e8f\uff0cyaw,pitch,roll\n    cout << \"roll_1 pitch_1 yaw_1 = \" << eulerAngle1[2] << \" \" << eulerAngle1[1]\n         << \" \" << eulerAngle1[0] << endl << endl;\n\n    // \u4f7f\u7528\u81ea\u5b9a\u4e49\u51fd\u6570\u5c06\u65cb\u8f6c\u77e9\u9635\u8f6c\u6362\u4e3a\u6b27\u62c9\u89d2\n    Eigen::Vector3d eulerAngle2 = rotationMatrixToEulerAngles(rotation_matrix1); // roll,pitch,yaw\n    cout << \"roll_2 pitch_2 yaw_2 = \" << eulerAngle2[0] << \" \" << eulerAngle2[1]\n         << \" \" << eulerAngle2[2] << endl << endl;\n\n    return 0;\n}\n\nEigen::Matrix3d eulerAnglesToRotationMatrix(Eigen::Vector3d &theta)\n{\n    Eigen::Matrix3d R_x;    // \u8ba1\u7b97\u65cb\u8f6c\u77e9\u9635\u7684X\u5206\u91cf\n    R_x <<\n        1,              0,               0,\n        0,  cos(theta[0]),  -sin(theta[0]),\n        0,  sin(theta[0]),   cos(theta[0]);\n\n    Eigen::Matrix3d R_y;    // \u8ba1\u7b97\u65cb\u8f6c\u77e9\u9635\u7684Y\u5206\u91cf\n    R_y <<\n        cos(theta[1]),   0, sin(theta[1]),\n        0,   1,             0,\n        -sin(theta[1]),  0, cos(theta[1]);\n\n    Eigen::Matrix3d R_z;    // \u8ba1\u7b97\u65cb\u8f6c\u77e9\u9635\u7684Z\u5206\u91cf\n    R_z <<\n        cos(theta[2]), -sin(theta[2]), 0,\n        sin(theta[2]),  cos(theta[2]), 0,\n        0,              0,             1;\n    Eigen::Matrix3d R = R_z * R_y * R_x;\n    return R;\n}\n\n\nbool isRotationMatirx(Eigen::Matrix3d R)\n{\n    double err=1e-6;\n    Eigen::Matrix3d shouldIdenity;\n    shouldIdenity=R*R.transpose();\n    Eigen::Matrix3d I=Eigen::Matrix3d::Identity();\n    return (shouldIdenity - I).norm() < err;\n}\n\nEigen::Vector3d rotationMatrixToEulerAngles(Eigen::Matrix3d &R)\n{\n    assert(isRotationMatirx(R));\n    double sy = sqrt(R(0,0) * R(0,0) + R(1,0) * R(1,0));\n    bool singular = sy < 1e-6;\n    double x, y, z;\n    if (!singular)\n    {\n        x = atan2( R(2,1), R(2,2));\n        y = atan2(-R(2,0), sy);\n        z = atan2( R(1,0), R(0,0));\n    }\n    else\n    {\n        x = atan2(-R(1,2), R(1,1));\n        y = atan2(-R(2,0), sy);\n        z = 0;\n    }\n    return {x, y, z};\n}\n", "meta": {"hexsha": "af774d3f08791ad64951714c431db6b8e5fbcbaf", "size": 4712, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "livox_sim_tool/src/codetest.cpp", "max_stars_repo_name": "zhijianglu/Livox_Cam_Simulator", "max_stars_repo_head_hexsha": "edeffef87ccfb0daa22081c8a8f24cdb7e4be455", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2022-01-15T05:10:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T13:15:45.000Z", "max_issues_repo_path": "livox_sim_tool/src/codetest.cpp", "max_issues_repo_name": "zhijianglu/Livox_Cam_Simulator", "max_issues_repo_head_hexsha": "edeffef87ccfb0daa22081c8a8f24cdb7e4be455", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "livox_sim_tool/src/codetest.cpp", "max_forks_repo_name": "zhijianglu/Livox_Cam_Simulator", "max_forks_repo_head_hexsha": "edeffef87ccfb0daa22081c8a8f24cdb7e4be455", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-01-15T05:10:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T08:04:30.000Z", "avg_line_length": 29.8227848101, "max_line_length": 98, "alphanum_fraction": 0.5952886248, "num_tokens": 1787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6256854822416154}}
{"text": "/**\n * Initializing the location of data points in the low-D space\n */\n#include <iostream>\n#include <armadillo>\n#include <chrono>\n#include <omp.h>\n#include <Eigen/Sparse>\n\n#define SCALE 0.0001\n\nusing namespace std;\nusing namespace arma;\nusing namespace Eigen;\n\nvoid Initialization (bool randominitializing, double** embedding, ofstream& logFile, int N, SparseMatrix<float> & graphSM, float MaxWeight, int DimLowSpace, int n_epochs){\n\n\tsrand(17);\n\t/**\n\t *  zero approximation in float precision\n\t */\n\tfloat epsilon=1e-6;\t\t\n\t/**\n\t * By deafult, low-D space dimensions are between -10 and 10 \n\t */\n\tint minDimLowDSpace=-10;\n\tint maxDimLowDSpace=10;    \n\n\tif (!randominitializing){\n\t\ttry{\n\t\t\tlogFile<<\" Spectral Initialization of Data in Lower Space\"<<endl;\n\t\t\tcout<<\" Spectral Initialization of Data in Lower Space\"<<endl;\n\n\t\t\t/**\n\t\t\t * graph is undirected weights (similarities) function for all the edges in the high-D space \n\t\t\t */\n\t\t\tfloat** graph = new float*[N];\n\t\t\tfor (int i = 0; i < N; ++i) { graph[i] = new float[N]; }\t\n\n            #pragma omp parallel for\n\t\t\tfor (int i = 0; i < N; ++i){\n\t\t\t\tfor (int j = 0; j < N; ++j){\n\t\t\t\t\tgraph[i][j]=0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int k=0; k<graphSM.outerSize(); ++k){\n\t\t\t\tfor (SparseMatrix<float>::InnerIterator it(graphSM,k); it; ++it) {\n\t\t\t\t\tgraph[it.row()][it.col()]=it.value();\n\t\t\t\t}\n\t\t\t} \n\n\t\t\t/**\n\t\t\t * Removing the small weights in accordance to https://github.com/lmcinnes/umap/blob/master/umap/umap_.py#L1032\n\t\t\t */\n            #pragma omp parallel for\n\t\t\tfor (int i = 0; i < N; ++i){\t\t\t\n\t\t\t\tfor (int j = 0; j < N; ++j){\n\t\t\t\t\tif (graph[i][j] <  epsilon) continue; \n\t\t\t\t\tif (graph[i][j] <  MaxWeight/n_epochs) graph[i][j]=0;  \n\t\t\t\t}\n\t\t\t}\t\n\n\t\t\t/**\n\t\t\t * DegreeMatrix is a diagonal matrix contains information about the degree of each vertex \n\t\t\t * sqrtDegreeMatrix transforms the diagonal values of DegreeMatrix by 1.0/sqrt()\n\t\t\t */\n\t\t\tfloat** sqrtDegreeMatrix = new float*[N];\n\t\t\tfor (int i = 0; i < N; ++i) { sqrtDegreeMatrix[i] = new float[N]; }\n\n\t\t\tfor (int i = 0; i < N; ++i){\n\t\t\t\tfor (int j = 0; j < N; ++j){\n\t\t\t\t\tsqrtDegreeMatrix[i][j]=0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < N; ++i) {\n\t\t\t\tfloat sum=0;\n\t\t\t\tfor (int j = 0; j < N; ++j) {\t\n\t\t\t\t\tsum+=graph[i][j];\n\t\t\t\t}\n\t\t\t\tsqrtDegreeMatrix[i][i]=1.0/sqrt(sum);\n\t\t\t}\n\t\t\t/**\n\t\t\t * aux_mem is the column-wise transformation of sqrtDegreeMatrix as needed by armadillo function fmat\n\t\t\t */\n\t\t\tfloat* aux_mem = new float[N*N];  \n\t\t\tfor (int i = 0; i < N; ++i){\n\t\t\t\tfor (int j = 0; j < N; ++j){\n\t\t\t\t\taux_mem[j*N+i]=sqrtDegreeMatrix[i][j];      \n\t\t\t\t}\n\t\t\t}\n\t\t\tdelete [] sqrtDegreeMatrix;\n\t\t\t/**\n\t\t\t * Making an armadillo sparse matrix spmatDegreeMatrix from sqrtDegreeMatrix\n\t\t\t */\n\t\t\tfmat matDegreeMatrix(aux_mem,N,N,false,true);\n\t\t\tsp_fmat spmatDegreeMatrix(matDegreeMatrix);    \n\t\t\t/**\n\t\t\t * aux_mem2 is the column-wise transformation of adjacencyMatrix as needed by armadillo function fmat\n\t\t\t */\n\t\t\tfloat* aux_mem2 = new float[N*N];  \n\t\t\tfor (int i = 0; i < N; ++i){\n\t\t\t\tfor (int j = 0; j < N; ++j){\n\t\t\t\t\taux_mem2[j*N+i]=graph[i][j];   //column-wise\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdelete[] graph;\n\n\t\t\t/**\n\t\t\t * Making an armadillo sparse matrix spmatadjacencyMatrix from adjacencyMatrix\n\t\t\t */\n\t\t\tfmat matadjacencyMatrix(aux_mem2,N,N,false,true);\n\t\t\tsp_fmat spmatadjacencyMatrix(matadjacencyMatrix);\n\t\t\t/**\n\t\t\t * Making an armadillo sparse matrix of identity \n\t\t\t */\t\t\t    \n\t\t\tsp_fmat Unity = speye<sp_fmat>(N,N); \n\t\t\t/**\n\t\t\t * Making an armadillo sparse matrix of Laplacian \n\t\t\t */\t\n\t\t\tsp_fmat laplacianMatrix;\n\t\t\tlaplacianMatrix= Unity-spmatDegreeMatrix*spmatadjacencyMatrix*spmatDegreeMatrix;\n\t\t\t/**\n\t\t\t * Solving eigenvalue and eigenvector for Laplacian matrix\n\t\t\t */\n\t\t\tfvec eigval;\n\t\t\tfmat eigvec;\n\t\t\teigs_sym(eigval, eigvec, laplacianMatrix, DimLowSpace+1 , \"sm\"); \n\t\t\t/**\n\t\t\t * Converting eigenvectors to tmpvector \n\t\t\t * will throw \"error: Mat::col(): index out of bounds\" if no eigvec was available\n\t\t\t */\n\t\t\ttypedef std::vector<float> stdvec;\n\t\t\tstd::vector< std::vector<float> > tmpvector;\n\n\t\t\tfor (int i = 1; i < DimLowSpace+1; ++i) {\n\t\t\t\tstdvec vectest = arma::conv_to< stdvec >::from(eigvec.col(i));\t\t\t\n\t\t\t\ttmpvector.push_back(vectest);  \n\t\t\t}\n\t\t\t/**\n\t\t\t * using tmpvector to intialize the locations of the points in low-D space\n\t\t\t * embedding should not be outside the chosen dimensions for low-D space\n\t\t\t */\n\t\t\tdouble maxembedding=0;\n\t\t\tfor (int j = 0; j < DimLowSpace; ++j) {    \n\t\t\t\tfor (int i = 0; i < N; ++i) {\n\t\t\t\t\tdouble tmp=tmpvector[j][i];\n\t\t\t\t\tembedding[i][j]= tmp;\n\n\t\t\t\t\tif (abs(tmp) > maxembedding) maxembedding=tmp;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdouble expansion=double(maxDimLowDSpace)/maxembedding;\n\n\t\t\t// Also adding a noise as prescribed in https://github.com/lmcinnes/umap/blob/master/umap/umap_.py#L1040\n\t\t\tunsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n\t\t\tstd::default_random_engine generator (seed);\n\t\t\tstd::normal_distribution<double> distribution (0.0,1.0);\t\t\t\t\t\n\n\t\t\tfor (int i = 0; i < N; ++i) {\t\t\t\n\t\t\t\tfor (int j = 0; j < DimLowSpace; ++j) { \t\t\t\n\t\t\t\t\tembedding[i][j] =embedding[i][j]* expansion+ SCALE*distribution(generator);\n\t\t\t\t}\n\t\t\t}\n\n\t\t} catch(std::exception& e){\n\t\t\tlogFile<<\" Spectral Initialization Failed. Will proceed with random initialization.\"<<endl; \n\t\t\tcout<<\" Spectral Initialization Failed. Will proceed with random initialization.\"<<endl; \n\t\t\trandominitializing=true ; }\n\t}\n\t/**\n\t * If the above procedure fails or randominitializing=1 as an input argument, the\n\t * location of the points are determined randomly \n\t */\n\tif (randominitializing){\n\t\tlogFile<<\" Random Initialization of Data in low-D Space\"<<endl;\n\t\tcout<<\" Random Initialization of Data in low-D Space\"<<endl;\n\t\tfor (int i = 0; i < N; ++i) {\n\t\t\tfor (int j = 0; j < DimLowSpace; ++j) {\n\t\t\t\tdouble tmp=(double)rand()/RAND_MAX;\n\t\t\t\tembedding[i][j]=minDimLowDSpace+(maxDimLowDSpace-minDimLowDSpace)*tmp;\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\n\treturn;\n}\n", "meta": {"hexsha": "e6c01353cf7ebfe50ef27a64b8f581172250507d", "size": 5853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dimension_reduction/UMAP/Shared-Memory-OpenMP/Initialization.cpp", "max_stars_repo_name": "mmvih/polus-plugins", "max_stars_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dimension_reduction/UMAP/Shared-Memory-OpenMP/Initialization.cpp", "max_issues_repo_name": "mmvih/polus-plugins", "max_issues_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dimension_reduction/UMAP/Shared-Memory-OpenMP/Initialization.cpp", "max_forks_repo_name": "mmvih/polus-plugins", "max_forks_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-26T19:23:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T19:23:57.000Z", "avg_line_length": 30.6439790576, "max_line_length": 171, "alphanum_fraction": 0.6292499573, "num_tokens": 1771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.6256773283965267}}
{"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__SO2_HPP_\n#define SMOOTH__SO2_HPP_\n\n#include <Eigen/Core>\n\n#include <complex>\n\n#include \"internal/lie_group_base.hpp\"\n#include \"internal/macro.hpp\"\n#include \"internal/so2.hpp\"\n\nnamespace smooth {\n\n// \\cond\ntemplate<typename Scalar>\nclass SO3;\n// \\endcond\n\n/**\n * @brief Base class for SO2 Lie group types.\n *\n * Internally represented as \\f$\\mathbb{U}(1)\\f$ (complex numbers).\n *\n * Memory layout\n * -------------\n *\n * - Group:    \\f$ \\mathbf{x} = [q_z, q_w] \\f$\n * - Tangent:  \\f$ \\mathbf{a} = [\\omega_z] \\f$\n *\n * Constraints\n * -----------\n *\n * - Group:   \\f$q_z^2 + q_w^2 = 1 \\f$\n * - Tangent: \\f$ -\\pi < \\omega_z \\leq \\pi \\f$\n *\n * Lie group matrix form\n * ---------------------\n *\n * \\f[\n * \\mathbf{X} =\n * \\begin{bmatrix}\n *  q_w & -q_z \\\\\n *  q_z &  q_w\n * \\end{bmatrix} \\in \\mathbb{R}^{2 \\times 2}\n * \\f]\n *\n *\n * Lie algebra matrix form\n * -----------------------\n *\n * \\f[\n * \\mathbf{a}^\\wedge =\n * \\begin{bmatrix}\n *   0 & -\\omega_z \\\\\n *  \\omega_z &   0 \\\\\n * \\end{bmatrix} \\in \\mathbb{R}^{2 \\times 2}\n * \\f]\n */\ntemplate<typename _Derived>\nclass SO2Base : public LieGroupBase<_Derived>\n{\n  using Base = LieGroupBase<_Derived>;\n\nprotected:\n  SO2Base() = default;\n\npublic:\n  SMOOTH_INHERIT_TYPEDEFS;\n\n  /**\n   * @brief Angle represetation.\n   */\n  Scalar angle() const { return Base::log().x(); }\n\n  /**\n   * @brief Complex number (U(1)) representation.\n   */\n  std::complex<Scalar> u1() const\n  {\n    return std::complex<Scalar>(static_cast<const _Derived &>(*this).coeffs().y(),\n      static_cast<const _Derived &>(*this).coeffs().x());\n  }\n\n  /**\n   * @brief Rotation action on 2D vector.\n   */\n  template<typename EigenDerived>\n  Eigen::Matrix<Scalar, 2, 1> operator*(const Eigen::MatrixBase<EigenDerived> & v) const\n  {\n    return Base::matrix() * v;\n  }\n\n  /**\n   * @brief Lift to SO3.\n   *\n   * Rotation of SO2 is embedded in SO3 as a rotation around the z axis.\n   *\n   * @note SO3 header must be included.\n   */\n  SO3<Scalar> lift_so3() const\n  {\n    using std::cos, std::sin;\n\n    const Scalar yaw = Base::log().x();\n    return SO3<Scalar>(Eigen::Quaternion<Scalar>(cos(yaw / 2), 0, 0, sin(yaw / 2)));\n  }\n};\n\n// \\cond\ntemplate<typename _Scalar>\nclass SO2;\n// \\endcond\n\n// \\cond\ntemplate<typename _Scalar>\nstruct lie_traits<SO2<_Scalar>>\n{\n  static constexpr bool is_mutable = true;\n\n  using Impl   = SO2Impl<_Scalar>;\n  using Scalar = _Scalar;\n\n  template<typename NewScalar>\n  using PlainObject = SO2<NewScalar>;\n};\n// \\endcond\n\n/**\n * @brief Storage implementation of SO2 Lie group.\n *\n * @see SO2Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass SO2 : public SO2Base<SO2<_Scalar>>\n{\n  using Base = SO2Base<SO2<_Scalar>>;\n  SMOOTH_GROUP_API(SO2);\n\npublic:\n  /**\n   * @brief Construct from coefficients.\n   *\n   * @param qz sine of rotation angle\n   * @param qw cosine of rotation angle\n   *\n   * @note Inputs are are normalized to ensure group constraint.\n   */\n  SO2(const Scalar & qz, const Scalar & qw)\n  {\n    using std::sqrt;\n\n    const Scalar n = sqrt(qw * qw + qz * qz);\n    coeffs_.x()    = qz / n;\n    coeffs_.y()    = qw / n;\n  }\n\n  /**\n   * @brief Construct from angle.\n   *\n   * @param angle angle of rotation (radians).\n   */\n  explicit SO2(const Scalar & angle)\n  {\n    using std::cos, std::sin;\n\n    coeffs_.x() = sin(angle);\n    coeffs_.y() = cos(angle);\n  }\n\n  /**\n   * @brief Construct from complex number.\n   *\n   * @param c complex number.\n   *\n   * @note Input is normalized to ensure group constraint.\n   */\n  SO2(const std::complex<Scalar> & c)\n  {\n    using std::sqrt;\n\n    const Scalar n = sqrt(c.imag() * c.imag() + c.real() * c.real());\n    coeffs_.x()    = c.imag() / n;\n    coeffs_.y()    = c.real() / n;\n  }\n};\n\nusing SO2f = SO2<float>;   ///< SO2 with float scalar representation\nusing SO2d = SO2<double>;  ///< SO2 with double scalar representation\n\n}  // namespace smooth\n\n// \\cond\ntemplate<typename _Scalar>\nstruct smooth::lie_traits<Eigen::Map<smooth::SO2<_Scalar>>>\n    : public lie_traits<smooth::SO2<_Scalar>>\n{};\n// \\endcond\n\n/**\n * @brief Memory mapping of SO2 Lie group.\n *\n * @see SO2Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass Eigen::Map<smooth::SO2<_Scalar>> : public smooth::SO2Base<Eigen::Map<smooth::SO2<_Scalar>>>\n{\n  using Base = smooth::SO2Base<Eigen::Map<smooth::SO2<_Scalar>>>;\n\n  SMOOTH_MAP_API(Map);\n};\n\n// \\cond\ntemplate<typename _Scalar>\nstruct smooth::lie_traits<Eigen::Map<const smooth::SO2<_Scalar>>>\n    : public lie_traits<smooth::SO2<_Scalar>>\n{\n  static constexpr bool is_mutable = false;\n};\n// \\endcond\n\n/**\n * @brief Const memory mapping of SO2 Lie group.\n *\n * @see SO2Base for memory layout.\n */\ntemplate<typename _Scalar>\nclass Eigen::Map<const smooth::SO2<_Scalar>>\n    : public smooth::SO2Base<Eigen::Map<const smooth::SO2<_Scalar>>>\n{\n  using Base = smooth::SO2Base<Eigen::Map<const smooth::SO2<_Scalar>>>;\n\n  SMOOTH_CONST_MAP_API(Map);\n};\n\n#endif  // SMOOTH__SO2_HPP_\n", "meta": {"hexsha": "6de5c05478e5c2f6ded21b7b2579984e6280872b", "size": 6172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/so2.hpp", "max_stars_repo_name": "NamDinhRobotics/smooth", "max_stars_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:18.000Z", "max_issues_repo_path": "include/smooth/so2.hpp", "max_issues_repo_name": "NamDinhRobotics/smooth", "max_issues_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/so2.hpp", "max_forks_repo_name": "NamDinhRobotics/smooth", "max_forks_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6475095785, "max_line_length": 97, "alphanum_fraction": 0.6485742061, "num_tokens": 1746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6256773276746673}}
{"text": "\n// solving A * X = B\n// in two steps -- factor (getrf()) and solve (getrs())\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/lapack/gesv.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/std_vector.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace traits = boost::numeric::bindings::traits;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cin;\nusing std::cout;\nusing std::endl; \n\ntypedef std::complex<double> cmpx; \ntypedef ublas::matrix<double, ublas::column_major> m_t;\ntypedef ublas::matrix<cmpx, ublas::column_major> cm_t;\n\n\nint main (int argc, char **argv) {\n  size_t n = 0;\n  if (argc > 1) {\n    n = atoi(argv [1]);\n  }\n\n  cout << endl; \n\n  if (n <= 0) {\n  cout << \"n -> \";\n  cin >> n; \n  }\n  if (n < 5) {\n    n = 5;\n    cout << \"min n = 5\" << endl; \n  }\n  cout << endl; \n  m_t a (n, n);   // system matrix \n\n  size_t nrhs = 2; \n  m_t x (n, nrhs), b (n, nrhs);  // b -- right-hand side matrix\n\n  init_symm (a); \n  //     [n   n-1 n-2  ... 1]\n  //     [n-1 n   n-1  ... 2]\n  // a = [n-2 n-1 n    ... 3]\n  //     [        ...       ]\n  //     [1   2   ...  n-1 n]\n\n  for (int i = 0; i < x.size1(); ++i) {\n    x (i, 0) = 1.;\n    x (i, 1) = 2.; \n  }\n  b = prod (a, x); \n  m_t a2 (a);  // for part 2\n  m_t b2 (b);\n\n  print_m (a, \"A\"); \n  cout << endl; \n  print_m (b, \"B\"); \n  cout << endl; \n\n  ublas::matrix_row<m_t> ar1 (a, 1), ar3 (a, 3);\n  ublas::matrix_row<m_t> br1 (b, 1), br3 (b, 3);\n  swap (ar1, ar3);   // swap rows to force pivoting \n  swap (br1, br3);\n  print_m (a, \"A\");  // print `new' system  \n  cout << endl; \n  print_m (b, \"B\"); \n  cout << endl; \n\n  std::vector<int> ipiv (n);  // pivot vector\n\n  lapack::getrf (a, ipiv);      // factor a\n  m_t ia (a);\n  lapack::getrs (a, ipiv, b);   // solve from factorization \n  print_m (b, \"X\"); \n  cout << endl; \n  lapack::getri (ia, ipiv);     // invert a\n  print_m (ia, \"InvA\"); \n  cout << endl; \n\n  print_v (ipiv, \"pivots\"); \n\n  cout << endl; \n\n  ublas::matrix_column<m_t> a2c1 (a2, 1), a2c4 (a2, 4);\n  ublas::matrix_row<m_t> b2r1 (b2, 1), b2r4 (b2, 4);\n  swap (a2c1, a2c4);   // swap columns\n  swap (b2r1, b2r4);\n  print_m (a2, \"A\");  // print `new' system  \n  cout << endl; \n  print_m (b2, \"B\"); \n  cout << endl; \n  \n  lapack::getrf (a2, ipiv); // factor a\n  m_t ia2 (a2);\n  lapack::getrs ('T', a2, ipiv, b2); // solve \n  print_m (b2, \"X\"); \n  cout << endl; \n  lapack::getri (ia2, ipiv); // invert a2\n  print_m (ia2, \"InvA2\"); \n  cout << endl; \n\n  print_v (ipiv, \"pivots\"); \n\n  cout << endl; \n}\n\n", "meta": {"hexsha": "4140e8ea5c7179ceb952c4cc0e868fd888959a12", "size": 2665, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libs/numeric/bindings/lapack/test/ublas_getrf_getrs.cc", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "libs/numeric/bindings/lapack/test/ublas_getrf_getrs.cc", "max_issues_repo_name": "inducer/boost-numeric-bindings", "max_issues_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/bindings/lapack/test/ublas_getrf_getrs.cc", "max_forks_repo_name": "inducer/boost-numeric-bindings", "max_forks_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 22.7777777778, "max_line_length": 63, "alphanum_fraction": 0.5470919325, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6256773129910377}}
{"text": "// VMD\u30e2\u30fc\u30b7\u30e7\u30f3\u3092\u5e73\u6ed1\u5316\u3059\u308b\n\n#include <map>\n#include <string>\n#include <vector>\n#include <Eigen/Core>\n#include <unsupported/Eigen/FFT>\n#include \"VMD.h\"\n#include \"MMDFileIOUtil.h\"\n#include \"interpolate.h\"\n#include \"reducevmd.h\"\n#include \"smoothvmd.h\"\n\nusing namespace Eigen;\nusing namespace MMDFileIOUtil;\nusing namespace std;\n\n// \u30ed\u30fc\u30d1\u30b9\u30d5\u30a3\u30eb\u30bf\u3002cutoff_freq\u3088\u308a\u9ad8\u3044\u5468\u6ce2\u6570\u6210\u5206\u3092\u9664\u53bb\u3059\u308b\nvoid lowpass_filter(vector<float>& v, float cutoff_freq)\n{\n  if (v.size() < 2) {\n    return;\n  }\n  FFT<float> fft;\n  vector<complex<float>> freqvec;\n  fft.fwd(freqvec, v);\n\n  // \u30d5\u30a3\u30eb\u30bf\u30ea\u30f3\u30b0\n  const float sampling_freq = 30.0; // \u30b5\u30f3\u30d7\u30ea\u30f3\u30b0\u5468\u6ce2\u6570[Hz]\u3002MMD\u306f30FPS\u306a\u306e\u3067\u3002\n  int data_size = v.size();\n  int cutoff_idx;\n  // \u6253\u3061\u5207\u308b\u4f4d\u7f6e(cutoff_idx)\u3092\u6c42\u3081\u308b\uff1a cutoff_idx / data_size = cutoff_freq / sampling_freq\n  cutoff_idx = cutoff_freq * data_size / sampling_freq;\n  \n  vector<complex<float>> filtered(data_size);\n  for (int i = 0; i < data_size; i++) {\n    if (i < cutoff_idx) {\n      filtered[i] = freqvec[i];\n    } else {\n      filtered[i] = 0.0;\n    }\n  }\n  fft.inv(v, filtered);\n}\n\n// \u30dc\u30fc\u30f3\u30ad\u30fc\u30d5\u30ec\u30fc\u30e0\u5217fv\u306e\u5024\u3092\u5e73\u6ed1\u5316\u3059\u308b\n// \u5f15\u6570fv\u306b\u306f\u540c\u4e00\u30dc\u30fc\u30f3\u306e\u30ad\u30fc\u30d5\u30ec\u30fc\u30e0\u304c\u30d5\u30ec\u30fc\u30e0\u756a\u53f7\u9806\u306b\u683c\u7d0d\u3055\u308c\u3066\u3044\u308b\u3082\u306e\u3068\u3059\u308b\nvoid smooth_bone_frame(vector<VMD_Frame>& fv, float cutoff_freq, bool bezier)\n{\n  sort(fv.begin(), fv.end());\n  fv = fill_bone_frame(fv, bezier); // \u30ad\u30fc\u30d5\u30ec\u30fc\u30e0\u306e\u9699\u9593\u3092\u306a\u304f\u3059\n  if (cutoff_freq < 0) {\n    return;\n  }\n  \n  // \u30ed\u30fc\u30d1\u30b9\u30d5\u30a3\u30eb\u30bf\u306b\u304b\u3051\u308b\n  vector<float> x;\n  for_each(fv.begin(), fv.end(), [&x](VMD_Frame f) { x.push_back(f.position.x()); });\n  lowpass_filter(x, cutoff_freq);\n  for (unsigned int i = 0; i < x.size(); i++) {\n    fv[i].position.x() = x[i];\n  }\n  vector<float> y;\n  for_each(fv.begin(), fv.end(), [&y](VMD_Frame f) { y.push_back(f.position.y()); });\n  lowpass_filter(y, cutoff_freq);\n  for (unsigned int i = 0; i < y.size(); i++) {\n    fv[i].position.y() = y[i];\n  }\n  vector<float> z;\n  for_each(fv.begin(), fv.end(), [&z](VMD_Frame f) { z.push_back(f.position.z()); });\n  lowpass_filter(z, cutoff_freq);\n  for (unsigned int i = 0; i < z.size(); i++) {\n    fv[i].position.z() = z[i];\n  }\n\n  // \u56de\u8ee2\u306e\u30ed\u30fc\u30d1\u30b9\u30d5\u30a3\u30eb\u30bf\n  // \u203b\u6b63\u3057\u3044\u3084\u308a\u65b9\u304c\u5206\u304b\u3089\u306a\u3044\u305f\u3081\u3001\u30af\u30a9\u30fc\u30bf\u30cb\u30aa\u30f3\u306e\u5404\u8981\u7d20\u306b\u5bfe\u3057\u3066\u30ed\u30fc\u30d1\u30b9\u30d5\u30a3\u30eb\u30bf\u3092\u639b\u3051\u3066\u3044\u308b\u3002\n  // TODO: \u30af\u30a9\u30fc\u30bf\u30cb\u30aa\u30f3\u306e\u30d5\u30fc\u30ea\u30a8\u5909\u63db\n  // \u540c\u3058\u56de\u8ee2\u3092\u8868\u3059\u30af\u30a9\u30fc\u30bf\u30cb\u30aa\u30f3\u304c\u6b63\u8ca02\u901a\u308a\u3042\u308b\u306e\u3067\u3001w\u306e\u7b26\u53f7\u304c\u6b63\u306e\u307b\u3046\u306b\u7d71\u4e00\u3059\u308b\n  for (unsigned int i = 0; i < fv.size(); i++) {\n    if (fv[i].rotation.w() < 0) {\n      fv[i].rotation.w() *= -1;\n      fv[i].rotation.x() *= -1;\n      fv[i].rotation.y() *= -1;\n      fv[i].rotation.z() *= -1;\n    }\n  }\n  vector<float> rx;\n  for_each(fv.begin(), fv.end(), [&rx](VMD_Frame f) { rx.push_back(f.rotation.x()); });\n  lowpass_filter(rx, cutoff_freq);\n  for (unsigned int i = 0; i < rx.size(); i++) {\n    fv[i].rotation.x() = rx[i];\n  }\n  vector<float> ry;\n  for_each(fv.begin(), fv.end(), [&ry](VMD_Frame f) { ry.push_back(f.rotation.y()); });\n  lowpass_filter(ry, cutoff_freq);\n  for (unsigned int i = 0; i < ry.size(); i++) {\n    fv[i].rotation.y() = ry[i];\n  }\n  vector<float> rz;\n  for_each(fv.begin(), fv.end(), [&rz](VMD_Frame f) { rz.push_back(f.rotation.z()); });\n  lowpass_filter(rz, cutoff_freq);\n  for (unsigned int i = 0; i < rz.size(); i++) {\n    fv[i].rotation.z() = rz[i];\n  }\n  vector<float> rw;\n  for_each(fv.begin(), fv.end(), [&rw](VMD_Frame f) { rw.push_back(f.rotation.w()); });\n  lowpass_filter(rw, cutoff_freq);\n  for (unsigned int i = 0; i < rw.size(); i++) {\n    fv[i].rotation.w() = rw[i];\n  }\n  // \u5404\u8981\u7d20(w, x, y, z)\u306b\u5bfe\u3057\u72ec\u7acb\u306b\u5909\u63db\u3092\u304b\u3051\u3066\u3044\u308b\u306e\u3067\u3001\u6b63\u898f\u5316\u3057\u3066\u304a\u304f\n  // \uff08\u6b63\u898f\u5316\u3057\u306a\u3044\u3068\u3001\u56de\u8ee2\u3057\u305f\u5148\u306e\u90e8\u5206\u304c\u6b6a\u3080\uff09\n  for (unsigned int i = 0; i < fv.size(); i++) {\n    fv[i].rotation.normalize();\n  }\n}\n\n// \u8868\u60c5\u30ad\u30fc\u30d5\u30ec\u30fc\u30e0\u5217mv\u306e\u5024\u3092\u5e73\u6ed1\u5316\u3059\u308b\n// \u5f15\u6570mv\u306b\u306f\u540c\u4e00\u30e2\u30fc\u30d5\u306e\u30ad\u30fc\u30d5\u30ec\u30fc\u30e0\u304c\u30d5\u30ec\u30fc\u30e0\u756a\u53f7\u9806\u306b\u683c\u7d0d\u3055\u308c\u3066\u3044\u308b\u3082\u306e\u3068\u3059\u308b\nvoid smooth_morph_frame(vector<VMD_Morph>& mv, float cutoff_freq)\n{\n  sort(mv.begin(), mv.end());\n  mv = fill_morph_frame(mv); // \u30ad\u30fc\u30d5\u30ec\u30fc\u30e0\u306e\u9699\u9593\u3092\u306a\u304f\u3059\n  if (cutoff_freq < 0) {\n    return;\n  }\n    \n  // \u30ed\u30fc\u30d1\u30b9\u30d5\u30a3\u30eb\u30bf\u306b\u304b\u3051\u308b\n  vector<float> w;\n  for_each(mv.begin(), mv.end(), [&w](VMD_Morph s) { w.push_back(s.weight); });\n  lowpass_filter(w, cutoff_freq);\n  for (unsigned int i = 0; i < w.size(); i++) {\n    mv[i].weight = w[i];\n    if (w[i] > 1.0) {\n      mv[i].weight = 1.0;\n    } else if (w[i] < 0.0) {\n      mv[i].weight = 0.0;\n    }\n  }\n}\n\n", "meta": {"hexsha": "59c9dfc003ebaeecdbc2e53dfa93a38422b1f5d9", "size": 4002, "ext": "cc", "lang": "C++", "max_stars_repo_path": "smoothvmd.cc", "max_stars_repo_name": "ikeno-ikeo/readfacevmd", "max_stars_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 49.0, "max_stars_repo_stars_event_min_datetime": "2018-05-19T07:28:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T07:16:06.000Z", "max_issues_repo_path": "smoothvmd.cc", "max_issues_repo_name": "ikeno-ikeo/readfacevmd", "max_issues_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-05-29T10:10:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T00:42:49.000Z", "max_forks_repo_path": "smoothvmd.cc", "max_forks_repo_name": "ikeno-ikeo/readfacevmd", "max_forks_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-03T20:58:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T09:06:47.000Z", "avg_line_length": 27.986013986, "max_line_length": 87, "alphanum_fraction": 0.611944028, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6256595036292683}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_LOGSPACE_SUB_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_LOGSPACE_SUB_HPP_INCLUDED\n\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/function/scalar/exp.hpp>\n#include <boost/simd/function/scalar/expm1.hpp>\n#include <boost/simd/function/scalar/is_eqz.hpp>\n#include <boost/simd/function/scalar/log.hpp>\n#include <boost/simd/function/scalar/log1p.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( logspace_sub_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0, A0 const& a1) const BOOST_NOEXCEPT\n    {\n      A0 x =  a1-a0;\n      if(is_eqz(x)) return Minf<A0>();\n      A0 tmp = (x > -Log_2<A0>()) ? bs::log(-expm1(x)) : bs::log1p(-exp(x));\n      return a0 + tmp;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "352524c0532b5177c4d79ce6db3caab239b3a5bc", "size": 1636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/logspace_sub.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/logspace_sub.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/logspace_sub.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.387755102, "max_line_length": 100, "alphanum_fraction": 0.5702933985, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6256594928101498}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl 2002 \n *\n * Permission to copy, modify, use and distribute this software \n * for any non-commercial or commercial purpose is granted provided \n * that this license appear on all copies of the software source code.\n *\n * Author assumes no responsibility whatsoever for its use and makes \n * no guarantees about its quality, correctness or reliability.\n *\n * Author acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_CBLAS1_OVERLOADS_HPP\n#define BOOST_NUMERIC_BINDINGS_CBLAS1_OVERLOADS_HPP\n\n#include <complex> \n#include <boost/numeric/bindings/atlas/cblas_inc.hpp>\n#include <boost/numeric/bindings/traits/type.hpp>\n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace atlas { namespace detail {\n\n    // dot <- x^T * y\n    // .. real types:    calls cblas_xdot\n    // .. complex types: calls cblas_xdotu\n    inline \n    float dot (int const N, float const* X, int const incX,\n               float const* Y, int const incY) {\n      return cblas_sdot (N, X, incX, Y, incY); \n    }\n    inline \n    double dot (int const N, double const* X, int const incX,\n                double const* Y, int const incY) {\n      return cblas_ddot (N, X, incX, Y, incY); \n    }\n    inline \n    traits::complex_f \n    dot (int const N, traits::complex_f const* X, int const incX,\n         traits::complex_f const* Y, int const incY) {\n      traits::complex_f val; \n      cblas_cdotu_sub (N, \n                       static_cast<void const*> (X), incX, \n                       static_cast<void const*> (Y), incY, \n                       static_cast<void*> (&val)); \n      return val; \n    }\n    inline \n    traits::complex_d \n    dot (int const N, traits::complex_d const* X, int const incX,\n         traits::complex_d const* Y, int const incY) {\n      traits::complex_d val; \n      cblas_zdotu_sub (N, \n                       static_cast<void const*> (X), incX, \n                       static_cast<void const*> (Y), incY, \n                       static_cast<void*> (&val)); \n      return val; \n    }\n\n    // dotu <- x^T * y  \n    // .. complex types only\n    inline \n    void dotu (int const N, traits::complex_f const* X, int const incX,\n               traits::complex_f const* Y, int const incY,\n               traits::complex_f* val) \n    {\n      cblas_cdotu_sub (N, \n                       static_cast<void const*> (X), incX, \n                       static_cast<void const*> (Y), incY, \n                       static_cast<void*> (val)); \n    }\n    inline \n    void dotu (int const N, traits::complex_d const* X, int const incX,\n               traits::complex_d const* Y, int const incY,\n               traits::complex_d* val) \n    {\n      cblas_zdotu_sub (N, \n                       static_cast<void const*> (X), incX, \n                       static_cast<void const*> (Y), incY, \n                       static_cast<void*> (val)); \n    }\n\n    // dotc <- x^H * y  \n    // .. complex types only \n    inline \n    void dotc (int const N, traits::complex_f const* X, int const incX,\n               traits::complex_f const* Y, int const incY,\n               traits::complex_f* val) \n    {\n      cblas_cdotc_sub (N, \n                       static_cast<void const*> (X), incX, \n                       static_cast<void const*> (Y), incY, \n                       static_cast<void*> (val)); \n    }\n    inline \n    void dotc (int const N, traits::complex_d const* X, int const incX,\n               traits::complex_d const* Y, int const incY,\n               traits::complex_d* val) \n    {\n      cblas_zdotc_sub (N, \n                       static_cast<void const*> (X), incX, \n                       static_cast<void const*> (Y), incY, \n                       static_cast<void*> (val)); \n    }\n\n    // nrm2 <- ||x||_2\n    inline \n    float nrm2 (int const N, float const* X, int const incX) {\n      return cblas_snrm2 (N, X, incX);\n    }\n    inline \n    double nrm2 (int const N, double const* X, int const incX) {\n      return cblas_dnrm2 (N, X, incX);\n    }\n    inline \n    float nrm2 (int const N, traits::complex_f const* X, int const incX) {\n      return cblas_scnrm2 (N, static_cast<void const*> (X), incX);\n    }\n    inline \n    double nrm2 (int const N, traits::complex_d const* X, int const incX) {\n      return cblas_dznrm2 (N, static_cast<void const*> (X), incX);\n    }\n\n    // asum <- ||re (x)|| + ||im (x)||\n    inline \n    float asum (int const N, float const* X, int const incX) {\n      return cblas_sasum (N, X, incX);\n    }\n    inline \n    double asum (int const N, double const* X, int const incX) {\n      return cblas_dasum (N, X, incX);\n    }\n    inline \n    float asum (int const N, traits::complex_f const* X, int const incX) {\n      return cblas_scasum (N, static_cast<void const*> (X), incX);\n    }\n    inline \n    double asum (int const N, traits::complex_d const* X, int const incX) {\n      return cblas_dzasum (N, static_cast<void const*> (X), incX);\n    }\n\n    // iamax <- 1st i: max (|re (x_i)| + |im (x_i)|)\n    inline \n    CBLAS_INDEX iamax (int const N, float const* X, int const incX) {\n      return cblas_isamax (N, X, incX);\n    }\n    inline \n    CBLAS_INDEX iamax (int const N, double const* X, int const incX) {\n      return cblas_idamax (N, X, incX);\n    }\n    inline \n    CBLAS_INDEX \n    iamax (int const N, traits::complex_f const* X, int const incX) {\n      return cblas_icamax (N, static_cast<void const*> (X), incX);\n    }\n    inline \n    CBLAS_INDEX \n    iamax (int const N, traits::complex_d const* X, int const incX) {\n      return cblas_izamax (N, static_cast<void const*> (X), incX);\n    }\n\n    // x <-> y\n    inline \n    void swap (int const N, float* X, int const incX,\n               float* Y, int const incY) {\n      cblas_sswap (N, X, incX, Y, incY); \n    }\n    inline \n    void swap (int const N, double* X, int const incX,\n               double* Y, int const incY) {\n      cblas_dswap (N, X, incX, Y, incY); \n    }\n    inline \n    void swap (int const N, traits::complex_f* X, int const incX,\n               traits::complex_f* Y, int const incY) {\n      cblas_cswap (N, \n                   static_cast<void*> (X), incX, \n                   static_cast<void*> (Y), incY); \n    }\n    inline \n    void swap (int const N, traits::complex_d* X, int const incX,\n               traits::complex_d* Y, int const incY) {\n      cblas_zswap (N, \n                   static_cast<void*> (X), incX, \n                   static_cast<void*> (Y), incY); \n    }\n\n    // y <- x\n    inline\n    void copy (int const N, float const* X, int const incX,\n               float* Y, int const incY) {\n      cblas_scopy (N, X, incX, Y, incY); \n    }\n    inline\n    void copy (int const N, double const* X, int const incX,\n               double* Y, int const incY) {\n      cblas_dcopy (N, X, incX, Y, incY); \n    }\n    inline \n    void copy (int const N, traits::complex_f const* X, int const incX,\n               traits::complex_f* Y, int const incY) {\n      cblas_ccopy (N, \n                   static_cast<void const*> (X), incX, \n                   static_cast<void*> (Y), incY); \n    }\n    inline \n    void copy (int const N, traits::complex_d const* X, int const incX,\n               traits::complex_d* Y, int const incY) {\n      cblas_zcopy (N, \n                   static_cast<void const*> (X), incX, \n                   static_cast<void*> (Y), incY); \n    }\n\n    // y <- alpha * x + y\n    inline\n    void axpy (int const N, \n               float const alpha, float const* X, int const incX, \n               float* Y, int const incY) \n    {\n      cblas_saxpy (N, alpha, X, incX, Y, incY);\n    }\n    inline\n    void axpy (int const N, \n               double const alpha, double const* X, int const incX, \n               double* Y, int const incY) \n    {\n      cblas_daxpy (N, alpha, X, incX, Y, incY);\n    }\n    inline\n    void axpy (int const N, \n               traits::complex_f const& alpha, \n               traits::complex_f const* X, int const incX, \n               traits::complex_f* Y, int const incY) \n    {\n      cblas_caxpy (N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void*> (Y), incY);\n    }\n    inline\n    void axpy (int const N, \n               traits::complex_d const& alpha, \n               traits::complex_d const* X, int const incX, \n               traits::complex_d* Y, int const incY) \n    {\n      cblas_zaxpy (N, \n                   static_cast<void const*> (&alpha), \n                   static_cast<void const*> (X), incX, \n                   static_cast<void*> (Y), incY);\n    }\n\n    // y <- alpha * x + beta * y\n    inline\n    void axpby (int const N, \n                float const alpha, float const* X, int const incX, \n                float const beta, float* Y, int const incY) \n    {\n      catlas_saxpby (N, alpha, X, incX, beta, Y, incY);\n    }\n    inline\n    void axpby (int const N, \n                double const alpha, double const* X, int const incX, \n                double const beta, double* Y, int const incY) \n    {\n      catlas_daxpby (N, alpha, X, incX, beta, Y, incY);\n    }\n    inline\n    void axpby (int const N, \n                traits::complex_f const& alpha, \n                traits::complex_f const* X, int const incX, \n                traits::complex_f const& beta, \n                traits::complex_f* Y, int const incY) \n    {\n      catlas_caxpby (N, \n                     static_cast<void const*> (&alpha), \n                     static_cast<void const*> (X), incX, \n                     static_cast<void const*> (&beta), \n                     static_cast<void*> (Y), incY);\n    }\n    inline\n    void axpby (int const N, \n                traits::complex_d const& alpha, \n                traits::complex_d const* X, int const incX, \n                traits::complex_d const& beta, \n                traits::complex_d* Y, int const incY) \n    {\n      catlas_zaxpby (N, \n                     static_cast<void const*> (&alpha), \n                     static_cast<void const*> (X), incX, \n                     static_cast<void const*> (&beta), \n                     static_cast<void*> (Y), incY);\n    }\n\n    // x_i <- alpha for all i\n    inline\n    void set (int const N, float const alpha, float* X, int const incX) {\n      catlas_sset (N, alpha, X, incX); \n    }\n    inline\n    void set (int const N, double const alpha, double* X, int const incX) {\n      catlas_dset (N, alpha, X, incX); \n    }\n    inline\n    void set (int const N, traits::complex_f const& alpha, \n              traits::complex_f* X, int const incX) {\n      catlas_cset (N, static_cast<void const*> (&alpha), \n                   static_cast<void*> (X), incX);\n    }\n    inline\n    void set (int const N, traits::complex_d const& alpha, \n              traits::complex_d* X, int const incX) {\n      catlas_zset (N, static_cast<void const*> (&alpha), \n                   static_cast<void*> (X), incX);\n    }\n\n    // x <- alpha * x\n    inline\n    void scal (int const N, float const alpha, float* X, int const incX) {\n      cblas_sscal (N, alpha, X, incX); \n    }\n    inline\n    void scal (int const N, double const alpha, double* X, int const incX) {\n      cblas_dscal (N, alpha, X, incX); \n    }\n    inline\n    void scal (int const N, traits::complex_f const& alpha, \n               traits::complex_f* X, int const incX) {\n      cblas_cscal (N, static_cast<void const*> (&alpha), \n                   static_cast<void*> (X), incX);\n    }\n    inline\n    void scal (int const N, float const alpha, \n               traits::complex_f* X, int const incX) {\n      cblas_csscal (N, alpha, static_cast<void*> (X), incX);\n    }\n    inline\n    void scal (int const N, traits::complex_d const& alpha, \n               traits::complex_d* X, int const incX) {\n      cblas_zscal (N, static_cast<void const*> (&alpha), \n                   static_cast<void*> (X), incX);\n    }\n    inline\n    void scal (int const N, double const alpha, \n               traits::complex_d* X, int const incX) {\n      cblas_zdscal (N, alpha, static_cast<void*> (X), incX);\n    }\n\n  }} // namepaces detail & atlas\n\n}}} \n\n\n#endif // BOOST_NUMERIC_BINDINGS_CBLAS1_OVERLOADS_HPP\n", "meta": {"hexsha": "eb3c399dedd0a3ad3745f83785087d0670daf886", "size": 12187, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/cblas1_overloads.hpp", "max_stars_repo_name": "jiaqiwang969/Kratos-test", "max_stars_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/cblas1_overloads.hpp", "max_issues_repo_name": "jiaqiwang969/Kratos-test", "max_issues_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/cblas1_overloads.hpp", "max_forks_repo_name": "jiaqiwang969/Kratos-test", "max_forks_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9470752089, "max_line_length": 76, "alphanum_fraction": 0.5433658817, "num_tokens": 3406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6256582447347824}}
{"text": "/*\n * This is part of the fl library, a C++ Bayesian filtering library\n * (https://github.com/filtering-library)\n *\n * Copyright (c) 2015 Max Planck Society,\n * \t\t\t\t Autonomous Motion Department,\n * \t\t\t     Institute for Intelligent Systems\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n */\n\n/**\n * \\file standard_gaussian.hpp\n * \\date May 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n * \\author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n */\n\n#pragma once\n\n\n#include <Eigen/Dense>\n\n#include <random>\n#include <type_traits>\n\n#include <fl/util/math.hpp>\n#include <fl/util/random.hpp>\n#include <fl/util/traits.hpp>\n#include <fl/util/types.hpp>\n#include <fl/distribution/interface/sampling.hpp>\n#include <fl/distribution/interface/moments.hpp>\n#include <fl/exception/exception.hpp>\n\nnamespace fl\n{\n\n/**\n * \\ingroup distributions\n */\ntemplate <typename StandardVariate>\nclass StandardGaussian\n    : public Sampling<StandardVariate>,\n      public Moments<\n                StandardVariate,\n                typename DiagonalSecondMomentOf<StandardVariate>::Type>\n{\npublic:\n    typedef StandardVariate Variate;\n\n    typedef Moments<\n                StandardVariate,\n                typename DiagonalSecondMomentOf<StandardVariate>::Type\n            > MomentsBase;\n\n    typedef typename MomentsBase::SecondMoment SecondMoment;\n    typedef typename MomentsBase::SecondMoment DiagonalSecondMoment;\n\npublic:\n    explicit\n    StandardGaussian(int dim = DimensionOf<StandardVariate>())\n        : dimension_ (dim),\n          mu_(Variate::Zero(dim, 1)),\n          cov_(DiagonalSecondMoment(dim)),\n          generator_(fl::seed()),\n          gaussian_distribution_(0.0, 1.0)\n    {\n        cov_.setIdentity();\n    }\n\n    virtual ~StandardGaussian() noexcept { }\n\n    virtual StandardVariate sample() const\n    {\n        StandardVariate gaussian_sample(dimension(), 1);\n\n        for (int i = 0; i < dimension_; i++)\n        {\n            gaussian_sample(i, 0) = gaussian_distribution_(generator_);\n        }\n\n        return gaussian_sample;\n    }\n\n    virtual int dimension() const\n    {\n        return dimension_;\n    }\n\n    virtual void dimension(int new_dimension)\n    {\n        if (dimension_ == new_dimension) return;\n\n        if (fl::IsFixed<StandardVariate::SizeAtCompileTime>())\n        {\n            fl_throw(\n                fl::ResizingFixedSizeEntityException(dimension_,\n                                                     new_dimension,\n                                                     \"Gaussian\"));\n        }\n\n        dimension_ = new_dimension;\n    }\n\n    virtual const Variate& mean() const\n    {\n        return mu_;\n    }\n\n    virtual const DiagonalSecondMoment& covariance() const\n    {\n        return cov_;\n    }\n\nprotected:\n    /** \\cond internal */\n    int dimension_;\n    Variate mu_;\n    DiagonalSecondMoment cov_;\n    mutable fl::mt11213b generator_;\n    mutable std::normal_distribution<Real> gaussian_distribution_;\n    /** \\endcond */\n};\n\n/**\n * Floating point implementation for Scalar types float, double and long double\n */\ntemplate <>\nclass StandardGaussian<Real>\n    : public Sampling<Real>,\n      public Moments<Real, Real>\n{\npublic:\n    StandardGaussian()\n        : mu_(0.),\n          var_(1.),\n          generator_(fl::seed()),\n          gaussian_distribution_(mu_, var_)\n    { }\n\n    Real sample() const\n    {\n        return gaussian_distribution_(generator_);\n    }\n\n    virtual const Real& mean() const\n    {\n        return mu_;\n    }\n\n    virtual const Real& covariance() const\n    {\n        return var_;\n    }\n\nprotected:\n    /** \\cond internal */\n    Real mu_;\n    Real var_;\n    mutable fl::mt11213b generator_;\n    mutable std::normal_distribution<Real> gaussian_distribution_;\n    /** \\endcond */\n};\n\n}\n", "meta": {"hexsha": "dd103b50b5294a07d06496eda1537edd42f7abc6", "size": 3866, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/distribution/standard_gaussian.hpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "include/fl/distribution/standard_gaussian.hpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "include/fl/distribution/standard_gaussian.hpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 23.0119047619, "max_line_length": 79, "alphanum_fraction": 0.6231246767, "num_tokens": 839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6256582425425242}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file GncPoseAveragingExample.cpp\n * @brief example of GNC estimating a single pose from pose priors possibly corrupted with outliers\n * You can run this example using: ./GncPoseAveragingExample nrInliers nrOutliers\n * e.g.,: ./GncPoseAveragingExample 10 5  (if the numbers are not specified, default\n * values nrInliers = 10 and nrOutliers = 10 are used)\n * @date May 8, 2021\n * @author Luca Carlone\n */\n\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/nonlinear/GncOptimizer.h>\n\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <boost/lexical_cast.hpp>\n\nusing namespace std;\nusing namespace gtsam;\n\nint main(int argc, char** argv){\n  cout << \"== Robust Pose Averaging Example === \" << endl;\n\n  // default number of inliers and outliers\n  size_t nrInliers = 10;\n  size_t nrOutliers = 10;\n\n  // User can pass arbitrary number of inliers and outliers for testing\n  if (argc > 1)\n    nrInliers = atoi(argv[1]);\n  if (argc > 2)\n    nrOutliers = atoi(argv[2]);\n  cout << \"nrInliers \" << nrInliers << \" nrOutliers \"<< nrOutliers << endl;\n\n  // Seed random number generator\n  random_device rd;\n  mt19937 rng(rd());\n  uniform_real_distribution<double> uniform(-10, 10);\n  normal_distribution<double> normalInliers(0.0, 0.05);\n\n  Values initial;\n  initial.insert(0, Pose3::identity()); // identity pose as initialization\n\n  // create ground truth pose\n  Vector6 poseGtVector;\n  for(size_t i = 0; i < 6; ++i){\n    poseGtVector(i) = uniform(rng);\n  }\n  Pose3 gtPose = Pose3::Expmap(poseGtVector); // Pose3( Rot3::Ypr(3.0, 1.5, 0.8), Point3(4,1,3) );\n\n  NonlinearFactorGraph graph;\n  const noiseModel::Isotropic::shared_ptr model = noiseModel::Isotropic::Sigma(6,0.05);\n  // create inliers\n  for(size_t i=0; i<nrInliers; i++){\n    Vector6 poseNoise;\n    for(size_t i = 0; i < 6; ++i){\n      poseNoise(i) = normalInliers(rng);\n    }\n    Pose3 poseMeasurement = gtPose.retract(poseNoise);\n    graph.add(gtsam::PriorFactor<gtsam::Pose3>(0,poseMeasurement,model));\n  }\n\n  // create outliers\n  for(size_t i=0; i<nrOutliers; i++){\n    Vector6 poseNoise;\n    for(size_t i = 0; i < 6; ++i){\n      poseNoise(i) = uniform(rng);\n    }\n    Pose3 poseMeasurement = gtPose.retract(poseNoise);\n    graph.add(gtsam::PriorFactor<gtsam::Pose3>(0,poseMeasurement,model));\n  }\n\n  GncParams<LevenbergMarquardtParams> gncParams;\n  auto gnc = GncOptimizer<GncParams<LevenbergMarquardtParams>>(graph,\n      initial,\n      gncParams);\n\n  Values estimate = gnc.optimize();\n  Pose3 poseError = gtPose.between( estimate.at<Pose3>(0) );\n  cout << \"norm of translation error: \" << poseError.translation().norm() <<\n      \" norm of rotation error: \" << poseError.rotation().rpy().norm() << endl;\n  // poseError.print(\"pose error: \\n \");\n  return 0;\n}\n", "meta": {"hexsha": "ad96934c8b78425dc16e6246073c10034555b995", "size": 3184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam_unstable/examples/GncPoseAveragingExample.cpp", "max_stars_repo_name": "h-rover/gtsam", "max_stars_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "gtsam_unstable/examples/GncPoseAveragingExample.cpp", "max_issues_repo_name": "h-rover/gtsam", "max_issues_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "gtsam_unstable/examples/GncPoseAveragingExample.cpp", "max_forks_repo_name": "h-rover/gtsam", "max_forks_repo_head_hexsha": "a0206e210d8f47b6ee295a1fbf95af84d98c5cf0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 32.1616161616, "max_line_length": 99, "alphanum_fraction": 0.6545226131, "num_tokens": 908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6256179064520172}}
{"text": "#ifndef __KALMANFILTER_MAIN_CPP__\n#define __KALMANFILTER_MAIN_CPP__\n\n#include <cstring>\n#include <string>\n#include <cstdio>\n#include <vector>\n\n#include <cmath>\n\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n\n#include <Eigen/Dense>\n\n#include \"KalmanFilter.hpp\"\n\n\n#define b printf(\"Line: %d\\n\", __LINE__);\n\n\nconst int STATE_DIMENSIONS = 5;\nconst int MEASUREMENT_DIMENSIONS = 5;\nconst int NUM_MEASUREMENTS = 6;\n\nconst double DELTA_T = 0.001;\nconst double LINEAR_VELOCITY = 0.14;\nconst double ANGULAR_VELOCITY = LINEAR_VELOCITY * tan(0);\nconst double ARBITRARY_VARIANCE = 0.1;\n\n/* Given data, resulting matrix arrangement:\n        Measurements:           Covariances:\n    0    odometer.x              Something arbitrary\n    1    GPS.x                   GPS.x covariance\n    2    odometer.y              Something arbitrary\n    3    GPS.y                   GPS.y covariance\n    4    odometer.\\theta         Something arbitrary\n    5    IMU.\\theta              IMU.\\theta covariance\n */\nconst int ODOM_X = 0;\nconst int ODOM_Y = 2;\nconst int ODOM_T = 4;\nconst int GPS_X = 1;\nconst int GPS_Y = 3;\nconst int IMU_T = 5;\nconst int X_ESTIMATE = 0;\nconst int Y_ESTIMATE = 1;\nconst int V_ESTIMATE = 2;\nconst int T_ESTIMATE = 3;\nconst int W_ESTIMATE = 4;\n\ntypedef struct {\n    std::string dataFilename;\n    std::string xyFilename;\n    std::string tFilename;\n    std::string vFilename;\n    std::string wFilename;\n    double stateCovarianceModifier;\n} Configurations;\n\n\ntypedef struct {\n    Eigen::VectorXd measurements;\n    Eigen::VectorXd variances;\n} DataItem;\n\nConfigurations processCmdLineArgs(int pArgc, char** pArgs);\n\nstd::vector<DataItem> readDataFile(const std::string& dataFileName);\n\nDataItem readDataLine(std::ifstream& fin);\n\nstd::vector<KalmanFilter::KalmanState> applyKalmanFilterToData(\n    Configurations& pConfigurations,\n    std::vector<DataItem>& pData);\n\nEigen::MatrixXd computeUpdatedNaturalModelMatrix(\n    int pStateDimensionality,\n    double pTimeStepMagnitude,\n    Eigen::VectorXd& pPreviousState);\n\nEigen::MatrixXd computeUpdatedStateNoiseCovariance(\n    int pStateDimensionality,\n    double pXPosCovariance,\n    double pYPosCovariance);\n\nEigen::MatrixXd computeUpdatedObservationNoiseCovariance(\n    int pObservationDimensionality,\n    double pXPosCovariance, \n    double pYPosCovariance,\n    double pTPosCovariance);\n\nEigen::VectorXd reduceDataToInputMeasurements(\n    Eigen::VectorXd& pMeasurementData,\n    int pNewVectorSize,\n    const std::vector<std::pair<int, int>>& pDataIndices);\n\nvoid writeDataToFile(\n    std::string pFileName,\n    std::vector<DataItem>& pInputData,\n    const std::vector<std::string>& pDataColumnLabels,\n    const std::vector<int>& pDataIndices,  \n    std::vector<KalmanFilter::KalmanState>& pKalmanOutputData,\n    const std::vector<std::string>& pOutputColumnLabels,\n    const std::vector<int>& pOutputIndices);\n\nvoid testSimpleKalmanFilter();\n\n\n\nint main(int argc, char** argv) {\n    Configurations configurations;\n\n    try {\n        puts(\"Initializing program...\");\n        configurations = processCmdLineArgs(argc, argv);\n\n        puts(\"Reading data...\");\n        std::vector<DataItem> data = readDataFile(configurations.dataFilename);\n\n        puts(\"Applying KalmanFilter...\");\n        std::vector<KalmanFilter::KalmanState> results =\n            applyKalmanFilterToData(configurations, data);\n\n        puts(\"Writing results to file...\");\n        writeDataToFile(\n            configurations.xyFilename,\n            data,\n            {\"Odom_X\", \"Odom_Y\", \"GPS_X\", \"GPS_Y\"},\n            {ODOM_X, ODOM_Y, GPS_X, GPS_Y},\n            results,\n            {\"X-estimate\", \"Y-estimate\"},\n            {X_ESTIMATE, Y_ESTIMATE}\n        );\n        writeDataToFile(\n            configurations.tFilename,\n            data,\n            {\"Odom_T\", \"IMU_T\"},\n            {ODOM_T, IMU_T},\n            results,\n            {\"T-estimate\",},\n            {T_ESTIMATE}\n        );\n        writeDataToFile(\n            configurations.vFilename,\n            data,\n            {},\n            {},\n            results,\n            {\"v-estimate\"},\n            {V_ESTIMATE}\n        );\n        writeDataToFile(\n            configurations.wFilename,\n            data,\n            {},\n            {},\n            results,\n            {\"w-estimate\",},\n            {W_ESTIMATE}\n        );\n\n    } catch (std::exception& e) {\n        puts(\"An error occured - program failure!\");\n        puts(e.what());\n    }\n\n    return 0;\n}\n\n\nConfigurations processCmdLineArgs(int pArgc, char** pArgs) {\n    Configurations configurations;\n    \n    if (pArgc < (3 + 1)) {\n        throw std::exception();\n    }\n\n// TODO: use strtok for cleaner arg parsing\n\n    for (int i = 1; i < pArgc; i += 2) {\n        if (strcmp(pArgs[i], \"-data\") == 0) {\n            configurations.dataFilename = pArgs[i + 1];\n        } else if (strcmp(pArgs[i], \"-xy\") == 0) {\n            configurations.xyFilename = pArgs[i + 1];\n        } else if (strcmp(pArgs[i], \"-theta\") == 0) {\n            configurations.tFilename = pArgs[i + 1];\n        } else if (strcmp(pArgs[i], \"-v\") == 0) {\n            configurations.vFilename = pArgs[i + 1];\n        } else if (strcmp(pArgs[i], \"-w\") == 0) {\n            configurations.wFilename = pArgs[i + 1];\n        } else if (strcmp(pArgs[i], \"-cov\") == 0) {\n            configurations.stateCovarianceModifier = atof(pArgs[i + 1]);\n        }\n    }\n\n    return configurations;\n}\n\n\nstd::vector<DataItem> readDataFile(const std::string& dataFileName) {\n    std::vector<DataItem> data;\n\n    try {\n        std::ifstream fin;\n        fin.clear();\n        fin.open(dataFileName.c_str());\n\n        std::string dummyString;\n        int dummy;\n        char delimeter;\n        DataItem temp;\n\n        fin >> dummyString;\n\n        temp = readDataLine(fin);\n\n        while (fin.good()) {\n            data.push_back(temp);\n\n            temp = readDataLine(fin);\n        }\n\n        fin.close();\n    } catch (std::exception& e) {\n        throw e;\n    }\n\n    return data;\n}\n\n\nDataItem readDataLine(std::ifstream& fin) {\n    DataItem dataItem;\n    dataItem.measurements.resize(NUM_MEASUREMENTS);\n    dataItem.variances.resize(NUM_MEASUREMENTS);\n\n    try {\n        int dummy;\n        char delimeter;\n\n        dataItem.measurements.setZero();\n        dataItem.variances.setConstant(NUM_MEASUREMENTS, 1, ARBITRARY_VARIANCE);\n\n        fin >>\n            dummy >> delimeter >>\n            dataItem.measurements(ODOM_X) >> delimeter >> // odometer.x\n            dataItem.measurements(ODOM_Y) >> delimeter >> // odometer.y\n            dataItem.measurements(ODOM_T) >> delimeter >> // odometer.\\theta\n            dataItem.measurements(IMU_T) >> delimeter >>  // IMU.\\theta\n            dataItem.variances(IMU_T) >> delimeter >>     // IMU.\\theta covariance\n            dataItem.measurements(GPS_X) >> delimeter >>  // GPS.x\n            dataItem.measurements(GPS_Y) >> delimeter >>  // GPS.y\n            dataItem.variances(GPS_X) >> delimeter >>     // GPS.x covariance\n            dataItem.variances(GPS_Y);                    // GPS.y covariance\n\n            dataItem.measurements(IMU_T) += 0.172; // calibration - just matches things to start\n    } catch (std::exception& e) {\n        throw e;\n    }\n\n    return dataItem;\n}\n\n\nstd::vector<KalmanFilter::KalmanState> applyKalmanFilterToData(\n    Configurations& pConfigurations,\n    std::vector<DataItem>& pData) {\n\n    std::vector<KalmanFilter::KalmanState> results;\n\n    try {\n        KalmanFilter kalmanFilter(STATE_DIMENSIONS, MEASUREMENT_DIMENSIONS);\n\n        Eigen::VectorXd tempMeasurements(NUM_MEASUREMENTS);\n        tempMeasurements = pData[0].measurements;\n\n        Eigen::VectorXd Z(MEASUREMENT_DIMENSIONS);\n        Z = reduceDataToInputMeasurements(\n            pData[0].measurements,\n            MEASUREMENT_DIMENSIONS,\n            {\n                {GPS_X, X_ESTIMATE},\n                {GPS_Y, Y_ESTIMATE},\n                {IMU_T, T_ESTIMATE}\n            }\n        );\n\n        Eigen::MatrixXd A(STATE_DIMENSIONS, STATE_DIMENSIONS);\n        A = computeUpdatedNaturalModelMatrix(\n                STATE_DIMENSIONS,\n                DELTA_T,\n                tempMeasurements\n        );\n\n        Eigen::MatrixXd B(STATE_DIMENSIONS, STATE_DIMENSIONS);\n        B.setIdentity(STATE_DIMENSIONS, STATE_DIMENSIONS);\n\n        Eigen::VectorXd u(STATE_DIMENSIONS);\n        u.setZero();\n\n        Eigen::MatrixXd H(MEASUREMENT_DIMENSIONS, STATE_DIMENSIONS);\n        H.setIdentity(MEASUREMENT_DIMENSIONS, STATE_DIMENSIONS);\n\n        Eigen::MatrixXd R(MEASUREMENT_DIMENSIONS, MEASUREMENT_DIMENSIONS);\n        R = computeUpdatedObservationNoiseCovariance(MEASUREMENT_DIMENSIONS, 0.1, 0.1, 0.01);\n\n        Eigen::MatrixXd Q(STATE_DIMENSIONS, STATE_DIMENSIONS);\n        Q = computeUpdatedStateNoiseCovariance(STATE_DIMENSIONS, 0.00001, 0.00001);\n        Q *= pConfigurations.stateCovarianceModifier;\n\n\n        KalmanFilter::KalmanState previousState;\n        previousState.state.resize(STATE_DIMENSIONS, 1);\n        previousState.state.setZero();\n        previousState.errorCovariance.resize(STATE_DIMENSIONS, STATE_DIMENSIONS);\n        previousState.errorCovariance.setIdentity();\n        previousState.errorCovariance *= 0.01;\n\n\n        kalmanFilter.setNaturalModel(A);\n        kalmanFilter.setControlModel(B);\n        kalmanFilter.setTransitionModel(H);\n        kalmanFilter.setStateNoiseCovariance(Q);\n        kalmanFilter.setMeasurementNoiseCovariance(R);\n\n        for (int i = 0; i < pData.size(); i++) {\n\n            A = computeUpdatedNaturalModelMatrix(\n                    STATE_DIMENSIONS,\n                    DELTA_T,\n                    previousState.state\n            );\n            R = computeUpdatedObservationNoiseCovariance(\n                    MEASUREMENT_DIMENSIONS,\n                    pData[i].variances(GPS_X),\n                    pData[i].variances(GPS_Y),\n                    pData[i].variances(IMU_T)\n            );\n            Z = reduceDataToInputMeasurements(\n                pData[i].measurements,\n                MEASUREMENT_DIMENSIONS,\n                {\n                    {GPS_X, X_ESTIMATE},\n                    {GPS_Y, Y_ESTIMATE},\n                    {IMU_T, T_ESTIMATE}\n                }\n            );\n\n            kalmanFilter.setNaturalModel(A);\n            kalmanFilter.setMeasurementNoiseCovariance(R);\n            previousState = kalmanFilter.KalmanFilterIteration(previousState, Z, u);\n\n            results.push_back(previousState);\n        }\n\n    } catch (std::exception& e) {\n        throw e;\n    }\n\n    return results;\n}\n\n\nEigen::MatrixXd computeUpdatedNaturalModelMatrix(\n    int pStateDimensionality,\n    double pTimeStepMagnitude,\n    Eigen::VectorXd& pPreviousState) {\n\n    double previousAngle = pPreviousState(T_ESTIMATE);\n    double previousAngularVelocity = pPreviousState(W_ESTIMATE);\n\n    Eigen::MatrixXd A(pStateDimensionality, pStateDimensionality);\n    A << 1, 0, pTimeStepMagnitude * cos(previousAngle), 0,                  0,\n         0, 1, pTimeStepMagnitude * sin(previousAngle), 0,                  0,\n         0, 0,                                       1, 0,                  0,\n         0, 0,                                       0, 1, pTimeStepMagnitude,\n         0, 0,                                       0, 0,                  1;\n\n    return A;\n}\n\n\nEigen::MatrixXd computeUpdatedStateNoiseCovariance(\n    int pStateDimensionality,\n    double pXPosCovariance,\n    double pYPosCovariance) {\n\n    Eigen::MatrixXd Q(pStateDimensionality, pStateDimensionality);\n    Q << pXPosCovariance,               0,     0,     0,     0,\n                       0, pYPosCovariance,     0,     0,     0,\n                       0,               0, 0.001,     0,     0,\n                       0,               0,     0, 0.001,     0,\n                       0,               0,     0,     0, 0.001;\n    return Q;\n}\n\n\nEigen::MatrixXd computeUpdatedObservationNoiseCovariance(\n    int pObservationDimensionality,\n    double pXPosCovariance, \n    double pYPosCovariance,\n    double pTPosCovariance) {\n\n    Eigen::MatrixXd R(pObservationDimensionality, pObservationDimensionality);\n    R << pXPosCovariance,               0,    0,               0,    0,\n                       0, pYPosCovariance,    0,               0,    0,\n                       0,               0, 0.01,               0,    0,\n                       0,               0,    0, pTPosCovariance,    0,\n                       0,               0,    0,               0, 0.01;\n\n    return R;\n}\n\n\nEigen::VectorXd reduceDataToInputMeasurements(\n    Eigen::VectorXd& pMeasurementData,\n    int pNewVectorSize,\n    const std::vector<std::pair<int, int>>& pDataIndices) {\n\n    Eigen::VectorXd newMeasurementVector(pNewVectorSize);\n    newMeasurementVector.setZero();\n\n    for (std::pair<int, int> indices : pDataIndices) {\n        newMeasurementVector(indices.second) = pMeasurementData(indices.first);\n    }\n\n    return newMeasurementVector;\n}\n\n\nvoid writeDataToFile(\n    std::string pFileName,\n    std::vector<DataItem>& pInputData,\n    const std::vector<std::string>& pDataColumnLabels,\n    const std::vector<int>& pDataIndices,  \n    std::vector<KalmanFilter::KalmanState>& pKalmanOutputData,\n    const std::vector<std::string>& pOutputColumnLabels,\n    const std::vector<int>& pOutputIndices) {\n\n    try {\n        std::ofstream fout;\n\n        fout.clear();\n        fout.open(pFileName + \".txt\");\n\n        std::string fileComment = \"# \";\n        fileComment += pFileName;\n        fileComment += \"data\";\n        fout << fileComment << std::endl;\n\n        fileComment = \"# time\\t\";\n        for (std::string label : pDataColumnLabels) {\n            fileComment += label;\n            fileComment += \"\\t\";\n        }\n        for (std::string label : pOutputColumnLabels) {\n            fileComment += label;\n            fileComment += \"\\t\";    \n        }\n        fout << fileComment << std::endl;\n\n        for (int i = 0; i < pKalmanOutputData.size(); i++) {\n            fout << std::setw(5);\n            fout << i << '\\t';\n\n            for (int index : pDataIndices) {\n                fout << std::setw(14);\n                fout << pInputData[i].measurements(index) << \"\\t\";\n            }\n            for (int index : pOutputIndices) {\n                fout << std::setw(14);\n                fout << pKalmanOutputData[i].state(index) << \"\\t\";\n            }\n\n            fout << std::endl;\n        }\n\n        fout.close();\n\n    } catch (std::exception& e) {\n        throw e;\n    }\n\n}\n\n\nvoid testSimpleKalmanFilter() {\n        Eigen::MatrixXd A(1,1); A << 1;\n        Eigen::MatrixXd B(1,1); B << 1;\n        Eigen::MatrixXd H(1,1); H << 1;\n        KalmanFilter::KalmanState state;\n            state.state.resize(1);\n            state.state << 0.0;\n            state.errorCovariance.resize(1,1);\n            state.errorCovariance << 1.0;\n        Eigen::VectorXd Z(1); Z << 0.390;\n        Eigen::VectorXd u(1); u << 0.0;\n        Eigen::MatrixXd Q(1,1); Q << 0.0;\n        Eigen::MatrixXd R(1,1); R << 0.1;\n\n        KalmanFilter kalmanFilter(1, 1);\n        kalmanFilter.setNaturalModel(A);\n        kalmanFilter.setControlModel(B);\n        kalmanFilter.setTransitionModel(H);\n        kalmanFilter.setStateNoiseCovariance(Q);\n        kalmanFilter.setMeasurementNoiseCovariance(R);\n\n        Z << 0.390;\n        state = kalmanFilter.KalmanFilterIteration(state, Z, u);\n        std::cout << \"state\\n\" << state.state << std::endl <<\n                  \"P\\n\" << state.errorCovariance << std::endl << std::endl;\n\n                          Z << 0.5;\n        state = kalmanFilter.KalmanFilterIteration(state, Z, u);\n        std::cout << \"state\\n\" << state.state << std::endl <<\n                  \"P\\n\" << state.errorCovariance << std::endl << std::endl;\n\n                          Z << 0.480;\n        state = kalmanFilter.KalmanFilterIteration(state, Z, u);\n        std::cout << \"state\\n\" << state.state << std::endl <<\n                  \"P\\n\" << state.errorCovariance << std::endl << std::endl;\n}\n\n#endif //__KALMANFILTER_MAIN_CPP__\n", "meta": {"hexsha": "cd41157ad3e99ff4ba6dbb919a3178e772de6e53", "size": 15950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CS791x_Fall14/Project01_KalmanFilter/KalmanFilter_main.cpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "CS791x_Fall14/Project01_KalmanFilter/KalmanFilter_main.cpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "CS791x_Fall14/Project01_KalmanFilter/KalmanFilter_main.cpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 30.265654649, "max_line_length": 96, "alphanum_fraction": 0.5774294671, "num_tokens": 3954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249076, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6256178920862225}}
{"text": "// Copyright (c) 2018-2019, University of Bremen, M. Farzalipour Tabriz\r\n// Copyrights licensed under the 2-Clause BSD License.\r\n// See the accompanying LICENSE.txt file for terms.\r\n\r\n#pragma once\r\n#include \"arma_io.hpp\"\r\n#include \"general_io.hpp\"\r\n#include \"slabcc_consts.hpp\"\r\n#include \"spline.hpp\"\r\n#include <armadillo>\r\n#include <fftw3.h>\r\n\r\n// These functions extend the functionality of the included Armadillo library by\r\n// providing:\r\n// (arma,iostream) << and >> operators for reading from iostreams to armadillo\r\n// types and vice versa fft/ifft functions for cube files: Wrappers for FFTW\r\n// with MATLAB/Octave scaling convention in FFT functions the forward FFT scales\r\n// by 1, and the reverse scales by 1/N. 3D ndgrid and 3D meshgrid 3D spline\r\n// interpolation 3D shift: by number of the elements along one axis or with a\r\n// relative 3D shift vector irowvec to matrix/cube size conversion scalar triple\r\n// product\r\n\r\n// a (very inefficient) 3D spline interpolation!\r\narma::cube interp3(const arma::rowvec &x, const arma::rowvec &y,\r\n                   const arma::rowvec &z, const arma::cube &v,\r\n                   const arma::rowvec &xi, const arma::rowvec &yi,\r\n                   const arma::rowvec &zi);\r\narma::cube interp3(const arma::cube &v, const arma::rowvec &xi,\r\n                   const arma::rowvec &yi, const arma::rowvec &zi);\r\n\r\n// Rectangular grid in 3D space\r\nstd::tuple<arma::cube, arma::cube, arma::cube>\r\nndgrid(const arma::rowvec &v1, const arma::rowvec &v2, const arma::rowvec &v3);\r\n\r\n// 3D meshgrid\r\nstd::tuple<arma::cube, arma::cube, arma::cube> meshgrid(const arma::rowvec &v1,\r\n                                                        const arma::rowvec &v2,\r\n                                                        const arma::rowvec &v3);\r\n\r\n// shifts a cube by a relative 3D vector [0 1]\r\narma::cube shift(arma::cube cube_in, arma::rowvec3 shifts);\r\n\r\n// Planar average of a cube in the defined direction\r\n// direction: 0,1,2 > x,y,z\r\narma::vec planar_average(const arma::uword &direction,\r\n                         const arma::cube &cube_in);\r\n\r\n// 1D FFT of complex data.\r\n// no normalization for forward FFT\r\narma::cx_vec fft(arma::cx_vec X);\r\n\r\n// 1D FFT of real data.\r\n// no normalization for forward FFT\r\narma::cx_vec fft(arma::vec X);\r\n\r\n// 3D FFT of complex data.\r\n// no normalization for forward FFT\r\narma::cx_cube fft(arma::cx_cube X);\r\n\r\n// 3D FFT of real data.\r\n// no normalization for forward FFT\r\narma::cx_cube fft(arma::cube X);\r\n\r\n// 1D inverse FFT of complex data.\r\n// normalized by N = X.n_elem\r\narma::cx_vec ifft(arma::cx_vec X);\r\n\r\n// 3D inverse FFT of complex data.\r\n// normalized by N = X.n_elem\r\narma::cx_cube ifft(arma::cx_cube X);\r\n\r\n// returns a cube size object from the values inside a vector\r\narma::SizeCube as_size(const arma::urowvec3 &vec);\r\n\r\n// returns a matrix size object from the values inside a vector\r\narma::SizeMat as_size(const arma::urowvec2 &vec);\r\n\r\n// element-wise fmod\r\narma::mat fmod(arma::mat mat_in, const double &denom) noexcept;\r\n\r\n// element-wise positive fmod\r\narma::mat fmod_p(arma::mat mat_in, const double &denom) noexcept;\r\n\r\n// positive fmod\r\ndouble fmod_p(double num, const double &denom) noexcept;\r\n\r\n// just a simple square! May cause overflows!!\r\ninline double square(const double &input) noexcept { return input * input; }\r\n\r\n// Poisson solver in 3D with anisotropic dielectric profiles\r\n// diel is the N*3 matrix of variations in dielectric tensor elements in\r\n// direction normal to the surface\r\narma::cx_cube poisson_solver_3D(const arma::cx_cube &rho, arma::mat diel,\r\n                                arma::rowvec3 lengths,\r\n                                arma::uword normal_direction);\r\n\r\n// generate a copy of the cube with the elements cyclic-shifted by N positions\r\n// along: dim=0: each row dim=1: each column dim=2: each slice\r\ntemplate <typename T>\r\narma::Cube<T> shift(const arma::Cube<T> &A, const arma::sword &N,\r\n                    const arma::uword &dim) {\r\n  arma::Cube<T> Shifted_A(arma::size(A));\r\n  const auto index_init = arma::regspace<arma::uvec>(0, A.n_elem - 1);\r\n  arma::imat sub_shift =\r\n      arma::conv_to<arma::imat>::from(arma::ind2sub(arma::size(A), index_init));\r\n  const arma::uword size = arma::size(A)(dim);\r\n  sub_shift.row(dim).for_each([&N, &size](arma::sword &i) noexcept {\r\n    i += N;\r\n    while (i < 0)\r\n      i += size;\r\n    i = i % size;\r\n  });\r\n\r\n  Shifted_A(arma::sub2ind(arma::size(A),\r\n                          arma::conv_to<arma::umat>::from(sub_shift))) =\r\n      A(index_init);\r\n\r\n  return Shifted_A;\r\n}\r\n\r\n// Undo a fftshift\r\ntemplate <typename T> arma::Row<T> ifftshift(const arma::Row<T> &A) {\r\n  return arma::shift(A, -1 * (A.n_elem / 2));\r\n}\r\n\r\n// Undo a fftshift\r\ntemplate <typename T> arma::Cube<T> ifftshift(arma::Cube<T> A) {\r\n  for (arma::uword i = 0; i < 3; ++i) {\r\n    A = arma::shift(A, -1 * (arma::size(A)(i) / 2), i);\r\n  }\r\n\r\n  return A;\r\n}\r\n\r\n// returns the size of a cube as a rowvec\r\ntemplate <typename T> arma::urowvec3 SizeVec(const arma::Cube<T> &c) {\r\n  const arma::SizeCube size = arma::size(c);\r\n  return arma::urowvec({size(0), size(1), size(2)});\r\n}\r\n\r\n// returns the size of a matrix as a rowvec\r\ntemplate <typename T> arma::urowvec2 SizeVec(const arma::Mat<T> &c) {\r\n  const arma::SizeMat size = arma::size(c);\r\n  return arma::urowvec({size(0), size(1)});\r\n}\r\n\r\n// sign of the val as -1/0/+1\r\ntemplate <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); }\r\n", "meta": {"hexsha": "eb382530a92dd9618630c89fa7958910e739154b", "size": 5465, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/slabcc_math.hpp", "max_stars_repo_name": "MFTabriz/slabcc", "max_stars_repo_head_hexsha": "1c8f91be145e2cccc35fddf6d8c79907c4b7cfe2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-22T03:33:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-21T21:42:30.000Z", "max_issues_repo_path": "src/slabcc_math.hpp", "max_issues_repo_name": "MFTabriz/slabcc", "max_issues_repo_head_hexsha": "1c8f91be145e2cccc35fddf6d8c79907c4b7cfe2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/slabcc_math.hpp", "max_forks_repo_name": "MFTabriz/slabcc", "max_forks_repo_head_hexsha": "1c8f91be145e2cccc35fddf6d8c79907c4b7cfe2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-04-19T02:26:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-07T07:32:31.000Z", "avg_line_length": 36.677852349, "max_line_length": 81, "alphanum_fraction": 0.6420860018, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.625617890976542}}
{"text": "//  Copyright (c) 2015 Boost.Test team\r\n//  Distributed under the Boost Software License, Version 1.0.\r\n//  (See accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  See http://www.boost.org/libs/test for the library home page.\r\n\r\n//[example_code\r\n#define BOOST_TEST_MODULE tolerance_03\r\n#include <boost/test/included/unit_test.hpp>\r\nnamespace utf = boost::unit_test;\r\n\r\ndouble x = 10.000000;\r\ndouble d =  0.000001;\r\n\r\nBOOST_AUTO_TEST_CASE(passing, * utf::tolerance(0.0001))\r\n{\r\n  BOOST_TEST(x == x + d); // equal with tolerance\r\n  BOOST_TEST(x >= x + d); // ==> greater-or-equal\r\n\r\n  BOOST_TEST(d == .0);    // small with tolerance\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(failing, * utf::tolerance(0.0001))\r\n{\r\n  BOOST_TEST(x - d <  x); // less, but still too close\r\n  BOOST_TEST(x - d != x); // unequal but too close\r\n\r\n  BOOST_TEST(d > .0);     // positive, but too small\r\n  BOOST_TEST(d < .0);     // not sufficiently negative\r\n}\r\n//]", "meta": {"hexsha": "03a461a6ef2eaea78957c96439c8dcf4a90028d6", "size": 967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/test/doc/examples/tolerance_03.run-fail.cpp", "max_stars_repo_name": "fineshift/boost", "max_stars_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/test/doc/examples/tolerance_03.run-fail.cpp", "max_issues_repo_name": "fineshift/boost", "max_issues_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/test/doc/examples/tolerance_03.run-fail.cpp", "max_forks_repo_name": "fineshift/boost", "max_forks_repo_head_hexsha": "67469225b1d640f8d0cdcec25b099d212c6bfa41", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.21875, "max_line_length": 66, "alphanum_fraction": 0.6577042399, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6256063354097057}}
{"text": "#include <Eigen/Dense>\n#include <Spectra/SymEigsSolver.h>\n#include <fstream>\n#include <ios>\n#include <iostream>\n#include <random>\n\n#include \"edlib/Hamiltonians/TITFIsing.hpp\"\n#include <edlib/edlib.hpp>\n\nint main(int argc, char* argv[])\n{\n    constexpr int N = 16;\n\n    using namespace edlib;\n    using UINT = uint32_t;\n\n    std::cout << \"#N: \" << N << std::endl;\n\n    std::vector<double> hs;\n    for(int i = 0; i <= 20; i++)\n    {\n        hs.emplace_back(i * 0.1);\n    }\n    for(auto h : hs)\n    {\n        Eigen::VectorXd ev[2];\n        {\n            Basis1DZ2<UINT> basis(N, 0, 1, false);\n            TITFIsing<UINT> ham(basis, 1.0, h);\n            const int dim = basis.getDim();\n\n            NodeMV mv(dim, 0, dim, ham);\n\n            Spectra::SymEigsSolver<double, Spectra::SMALLEST_ALGE, NodeMV> eigs(&mv, 2, 6);\n            eigs.init();\n            eigs.compute(10000, 1e-12, Spectra::SMALLEST_ALGE);\n            if(eigs.info() != Spectra::SUCCESSFUL)\n                return 1;\n            ev[0] = eigs.eigenvalues();\n        }\n        {\n            Basis1DZ2<UINT> basis(N, 0, -1, false);\n            TITFIsing<UINT> ham(basis, 1.0, h);\n            const int dim = basis.getDim();\n\n            NodeMV mv(dim, 0, dim, ham);\n\n            Spectra::SymEigsSolver<double, Spectra::SMALLEST_ALGE, NodeMV> eigs(&mv, 2, 6);\n            eigs.init();\n            eigs.compute(10000, 1e-12, Spectra::SMALLEST_ALGE);\n            if(eigs.info() != Spectra::SUCCESSFUL)\n                return 1;\n            ev[1] = eigs.eigenvalues();\n        }\n\n        printf(\"%f\\t%.10f\\t%.10f\\t%.10f\\t%.10f\\n\", h, ev[0](0), ev[0](1), ev[1](0), ev[1](1));\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "0e459efff6466fcee568b87b10dbc5a4e58ce946", "size": 1657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tfi.cpp", "max_stars_repo_name": "cecri/ExactDiagonalization", "max_stars_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tfi.cpp", "max_issues_repo_name": "cecri/ExactDiagonalization", "max_issues_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tfi.cpp", "max_forks_repo_name": "cecri/ExactDiagonalization", "max_forks_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7258064516, "max_line_length": 94, "alphanum_fraction": 0.5202172601, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6256063176784046}}
{"text": "// Boost.GIL (Generic Image Library) - tests\n//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n#include <boost/core/lightweight_test.hpp>\n#include <boost/gil/image_processing/hough_parameter.hpp>\n\nnamespace gil = boost::gil;\n\nvoid from_step_count_test()\n{\n    const double middle_point = 0.5;\n    const std::size_t step_count = 5;\n    const double neighborhood = 1.0;\n    auto param =\n        gil::hough_parameter<double>::from_step_count(middle_point, neighborhood, step_count);\n    BOOST_TEST(param.start_point == middle_point - neighborhood);\n    BOOST_TEST(param.step_count == step_count * 2 + 1);\n    BOOST_TEST(param.step_size == neighborhood / step_count);\n\n    bool middle_point_occured = false;\n    for (std::size_t i = 0; i < param.step_count; ++i)\n    {\n        auto current = param.start_point + param.step_size * i;\n        if (current == middle_point)\n        {\n            middle_point_occured = true;\n            break;\n        }\n    }\n    BOOST_TEST(middle_point_occured);\n}\n\nvoid from_step_size_test(const double middle_point, const double step_size,\n                         const double neighborhood)\n{\n    const std::size_t expected_step_count =\n        static_cast<std::size_t>(neighborhood / step_size) * 2 + 1;\n    auto param =\n        gil::hough_parameter<double>::from_step_size(middle_point, neighborhood, step_size);\n    BOOST_TEST(param.start_point == middle_point - step_size * std::floor(expected_step_count / 2));\n    BOOST_TEST(param.step_count == expected_step_count);\n    BOOST_TEST(param.step_size == step_size);\n\n    bool middle_point_occured = false;\n    for (std::size_t i = 0; i < param.step_count; ++i)\n    {\n        auto current = param.start_point + param.step_size * i;\n        if (current == middle_point)\n        {\n            middle_point_occured = true;\n            break;\n        }\n    }\n    BOOST_TEST(middle_point_occured);\n}\n\nvoid minimum_step_angle_test(const std::ptrdiff_t width, const std::ptrdiff_t height)\n{\n    const auto bigger_dim = width > height ? width : height;\n    const double expected_angle = std::atan2(1.0, bigger_dim);\n    BOOST_TEST(expected_angle == gil::minimum_angle_step({width, height}));\n}\n\nint main()\n{\n    from_step_count_test();\n    // ideal case\n    from_step_size_test(2.0, 0.25, 1.0);\n    from_step_size_test(5.0, 2, 5.0);\n    minimum_step_angle_test(1200, 800);\n    minimum_step_angle_test(800, 1200);\n    return boost::report_errors();\n}\n", "meta": {"hexsha": "8d1c7b4452c4e5912625b4234ee558ade4a191ec", "size": 2642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/image_processing/hough_parameter.cpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "test/core/image_processing/hough_parameter.cpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "test/core/image_processing/hough_parameter.cpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 33.4430379747, "max_line_length": 100, "alphanum_fraction": 0.6797880394, "num_tokens": 655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6256063156871214}}
{"text": "/*\n * Copyright 2009-2012 Karsten Ahnert\n * Copyright 2009-2012 Mario Mulansky\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <cmath>\n\n#include <boost/array.hpp>\n\ntemplate< size_t N >\nstruct phase_lattice\n{\n    typedef double value_type;\n    typedef boost::array< value_type , N > state_type;\n\n    value_type m_epsilon; \n    state_type m_omega;\n\n    phase_lattice() : m_epsilon( 6.0/(N*N) ) // should be < 8/N^2 to see phase locking\n    {\n        for( size_t i=1 ; i<N-1 ; ++i )\n            m_omega[i] = m_epsilon*(N-i);\n    }\n\n    void inline operator()( const state_type &x , state_type &dxdt , const double t ) const\n    {\n        double c = 0.0;\n\n        for( size_t i=0 ; i<N-1 ; ++i )\n        {\n            dxdt[i] = m_omega[i] + c;\n            c = ( x[i+1] - x[i] );\n            dxdt[i] += c;\n        }\n\n        //dxdt[N-1] = m_omega[N-1] + sin( x[N-1] - x[N-2] );\n    }\n\n};\n", "meta": {"hexsha": "6a8f44b58f05e110a60fe13af7fa58b59e77f230", "size": 1008, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/performance/phase_lattice.hpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/performance/phase_lattice.hpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/performance/phase_lattice.hpp", "max_forks_repo_name": "473867143/Prometheus", "max_forks_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 22.9090909091, "max_line_length": 91, "alphanum_fraction": 0.5634920635, "num_tokens": 319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6256063003684718}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2000 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Author: Wolfgang Bangerth, University of Heidelberg, 2000 \n */ \n\n\n// @sect3{Include files}  \n\n// \u50cf\u5f80\u5e38\u4e00\u6837\uff0c\u524d\u51e0\u4e2ainclude\u6587\u4ef6\u5df2\u7ecf\u77e5\u9053\u4e86\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u4e0d\u518d\u8bc4\u8bba\u5b83\u4eec\u3002\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/tensor.h> \n\n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/sparse_matrix.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/affine_constraints.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_values.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\n// \u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u9700\u8981\u77e2\u91cf\u503c\u7684\u6709\u9650\u5143\u3002\u5bf9\u8fd9\u4e9b\u7684\u652f\u6301\u53ef\u4ee5\u5728\u4e0b\u9762\u7684include\u6587\u4ef6\u4e2d\u627e\u5230\u3002\n\n#include <deal.II/fe/fe_system.h> \n\n// \u6211\u4eec\u5c06\u7528\u5e38\u89c4\u7684Q1\u5143\u7d20\u7ec4\u6210\u77e2\u91cf\u503c\u7684\u6709\u9650\u5143\u7d20\uff0c\u8fd9\u4e9b\u5143\u7d20\u53ef\u4ee5\u5728\u8fd9\u91cc\u627e\u5230\uff0c\u50cf\u5f80\u5e38\u4e00\u6837\u3002\n\n#include <deal.II/fe/fe_q.h> \n\n// \u8fd9\u53c8\u662fC++\u8bed\u8a00\u3002\n\n#include <fstream> \n#include <iostream> \n\n// \u6700\u540e\u4e00\u6b65\u548c\u4ee5\u524d\u7684\u7a0b\u5e8f\u4e00\u6837\u3002\u7279\u522b\u662f\uff0c\u5c31\u50cf\u5728 step-7 \u4e2d\u4e00\u6837\uff0c\u6211\u4eec\u628a\u8fd9\u4e2a\u7a0b\u5e8f\u6240\u7279\u6709\u7684\u4e00\u5207\u90fd\u6253\u5305\u5230\u4e00\u4e2a\u81ea\u5df1\u7684\u547d\u540d\u7a7a\u95f4\u4e2d\u3002\n\nnamespace Step8 \n{ \n  using namespace dealii; \n// @sect3{The <code>ElasticProblem</code> class template}  \n\n// \u4e3b\u7c7b\u9664\u4e86\u540d\u79f0\u5916\uff0c\u4e0e step-6 \u7684\u4f8b\u5b50\u76f8\u6bd4\u51e0\u4e4e\u6ca1\u6709\u53d8\u5316\u3002\n\n// \u552f\u4e00\u7684\u53d8\u5316\u662f\u4e3a <code>fe</code> \u53d8\u91cf\u4f7f\u7528\u4e86\u4e00\u4e2a\u4e0d\u540c\u7684\u7c7b\u3002\u6211\u4eec\u73b0\u5728\u4f7f\u7528\u7684\u4e0d\u662fFE_Q\u8fd9\u6837\u5177\u4f53\u7684\u6709\u9650\u5143\u7c7b\uff0c\u800c\u662f\u4e00\u4e2a\u66f4\u901a\u7528\u7684\u7c7b\uff0cFESystem\u3002\u4e8b\u5b9e\u4e0a\uff0cFESystem\u672c\u8eab\u5e76\u4e0d\u662f\u4e00\u4e2a\u771f\u6b63\u7684\u6709\u9650\u5143\uff0c\u56e0\u4e3a\u5b83\u6ca1\u6709\u5b9e\u73b0\u81ea\u5df1\u7684\u5f62\u72b6\u51fd\u6570\u3002\u76f8\u53cd\uff0c\u5b83\u662f\u4e00\u4e2a\u53ef\u4ee5\u7528\u6765\u5c06\u5176\u4ed6\u51e0\u4e2a\u5143\u7d20\u5806\u53e0\u5728\u4e00\u8d77\u5f62\u6210\u4e00\u4e2a\u77e2\u91cf\u503c\u7684\u6709\u9650\u5143\u7684\u7c7b\u3002\u5728\u6211\u4eec\u7684\u4f8b\u5b50\u4e2d\uff0c\u6211\u4eec\u5c06\u7ec4\u6210 <code>FE_Q(1)</code> \u5bf9\u8c61\u7684\u77e2\u91cf\u503c\u5143\u7d20\uff0c\u5982\u4e0b\u6240\u793a\uff0c\u5728\u8fd9\u4e2a\u7c7b\u7684\u6784\u9020\u51fd\u6570\u4e2d\u3002\n\n  template <int dim> \n  class ElasticProblem \n  { \n  public: \n    ElasticProblem(); \n    void run(); \n\n  private: \n    void setup_system(); \n    void assemble_system(); \n    void solve(); \n    void refine_grid(); \n    void output_results(const unsigned int cycle) const; \n\n    Triangulation<dim> triangulation; \n    DoFHandler<dim>    dof_handler; \n\n    FESystem<dim> fe; \n\n    AffineConstraints<double> constraints; \n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> system_matrix; \n\n    Vector<double> solution; \n    Vector<double> system_rhs; \n  }; \n// @sect3{Right hand side values}  \n\n// \u5728\u8fdb\u5165\u4e3b\u7c7b\u7684\u5b9e\u73b0\u4e4b\u524d\uff0c\u6211\u4eec\u58f0\u660e\u5e76\u5b9a\u4e49\u63cf\u8ff0\u53f3\u624b\u8fb9\u7684\u51fd\u6570\u3002\u8fd9\u4e00\u6b21\uff0c\u53f3\u624b\u8fb9\u662f\u5411\u91cf\u503c\uff0c\u89e3\u51b3\u65b9\u6848\u4e5f\u662f\u5982\u6b64\uff0c\u6240\u4ee5\u6211\u4eec\u5c06\u66f4\u8be6\u7ec6\u5730\u63cf\u8ff0\u4e3a\u6b64\u6240\u9700\u7684\u53d8\u5316\u3002\n\n// \u4e3a\u4e86\u9632\u6b62\u51fa\u73b0\u8fd4\u56de\u5411\u91cf\u6ca1\u6709\u88ab\u8bbe\u7f6e\u6210\u6b63\u786e\u5927\u5c0f\u7684\u60c5\u51b5\uff0c\u6211\u4eec\u5bf9\u8fd9\u79cd\u60c5\u51b5\u8fdb\u884c\u4e86\u6d4b\u8bd5\uff0c\u5426\u5219\u5c06\u5728\u51fd\u6570\u7684\u5f00\u59cb\u90e8\u5206\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38\u3002\u8bf7\u6ce8\u610f\uff0c\u5f3a\u5236\u8f93\u51fa\u53c2\u6570\u5df2\u7ecf\u5177\u6709\u6b63\u786e\u7684\u5927\u5c0f\u662fdeal.II\u4e2d\u7684\u4e00\u4e2a\u60ef\u4f8b\uff0c\u5e76\u4e14\u51e0\u4e4e\u5728\u6240\u6709\u5730\u65b9\u90fd\u5f3a\u5236\u6267\u884c\u3002\u539f\u56e0\u662f\uff0c\u5426\u5219\u6211\u4eec\u5c06\u4e0d\u5f97\u4e0d\u5728\u51fd\u6570\u5f00\u59cb\u65f6\u68c0\u67e5\uff0c\u5e76\u53ef\u80fd\u6539\u53d8\u8f93\u51fa\u5411\u91cf\u7684\u5927\u5c0f\u3002\u8fd9\u5f88\u6602\u8d35\uff0c\u800c\u4e14\u51e0\u4e4e\u603b\u662f\u4e0d\u5fc5\u8981\u7684\uff08\u5bf9\u51fd\u6570\u7684\u7b2c\u4e00\u6b21\u8c03\u7528\u4f1a\u5c06\u5411\u91cf\u8bbe\u7f6e\u4e3a\u6b63\u786e\u7684\u5927\u5c0f\uff0c\u968f\u540e\u7684\u8c03\u7528\u53ea\u9700\u8981\u505a\u591a\u4f59\u7684\u68c0\u67e5\uff09\u3002\u6b64\u5916\uff0c\u5982\u679c\u6211\u4eec\u4e0d\u80fd\u4f9d\u8d56\u5411\u91cf\u5df2\u7ecf\u5177\u6709\u6b63\u786e\u5927\u5c0f\u7684\u5047\u8bbe\uff0c\u90a3\u4e48\u68c0\u67e5\u548c\u53ef\u80fd\u8c03\u6574\u5411\u91cf\u5927\u5c0f\u7684\u64cd\u4f5c\u662f\u4e0d\u80fd\u88ab\u5220\u9664\u7684\uff1b\u8fd9\u4e0eAssert\u8c03\u7528\u662f\u4e00\u4e2a\u5951\u7ea6\uff0c\u5982\u679c\u7a0b\u5e8f\u5728\u4f18\u5316\u6a21\u5f0f\u4e0b\u7f16\u8bd1\uff0cAssert\u8c03\u7528\u5c06\u88ab\u5b8c\u5168\u5220\u9664\u3002\n\n// \u540c\u6837\uff0c\u5982\u679c\u7531\u4e8e\u67d0\u79cd\u610f\u5916\uff0c\u6709\u4eba\u8bd5\u56fe\u5728\u53ea\u6709\u4e00\u4e2a\u7a7a\u95f4\u7ef4\u5ea6\u7684\u60c5\u51b5\u4e0b\u7f16\u8bd1\u548c\u8fd0\u884c\u7a0b\u5e8f\uff08\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u5f39\u6027\u65b9\u7a0b\u6ca1\u6709\u4ec0\u4e48\u610f\u4e49\uff0c\u56e0\u4e3a\u5b83\u4eec\u8fd8\u539f\u4e3a\u666e\u901a\u7684\u62c9\u666e\u62c9\u65af\u65b9\u7a0b\uff09\uff0c\u6211\u4eec\u5728\u7b2c\u4e8c\u4e2a\u65ad\u8a00\u4e2d\u7ec8\u6b62\u7a0b\u5e8f\u3002\u7136\u800c\uff0c\u8be5\u7a0b\u5e8f\u5728\u4e09\u7ef4\u7a7a\u95f4\u4e2d\u4e5f\u80fd\u6b63\u5e38\u5de5\u4f5c\u3002\n\n  template <int dim> \n  void right_hand_side(const std::vector<Point<dim>> &points, \n                       std::vector<Tensor<1, dim>> &  values) \n  { \n    Assert(values.size() == points.size(), \n           ExcDimensionMismatch(values.size(), points.size())); \n    Assert(dim >= 2, ExcNotImplemented()); \n\n// \u8be5\u51fd\u6570\u7684\u5176\u4f59\u90e8\u5206\u5b9e\u73b0\u4e86\u8ba1\u7b97\u529b\u503c\u3002\u6211\u4eec\u5c06\u4f7f\u7528\u4e00\u4e2a\u4f4d\u4e8e(0.5,0)\u548c(-0.5,0)\u70b9\u5468\u56f4\u7684\u4e24\u4e2a\u5c0f\u5706\u5708\uff08\u6216\u7403\u4f53\uff0c\u57283D\u4e2d\uff09\u7684X\u65b9\u5411\u7684\u6052\u5b9a\uff08\u5355\u4f4d\uff09\u529b\uff0c\u4ee5\u53ca\u4f4d\u4e8e\u539f\u70b9\u5468\u56f4\u7684Y\u65b9\u5411\u7684\u529b\uff1b\u57283D\u4e2d\uff0c\u8fd9\u4e9b\u4e2d\u5fc3\u7684Z\u5206\u91cf\u4e5f\u662f\u96f6\u3002\n\n// \u4e3a\u6b64\uff0c\u8ba9\u6211\u4eec\u9996\u5148\u5b9a\u4e49\u4e24\u4e2a\u5bf9\u8c61\uff0c\u8868\u793a\u8fd9\u4e9b\u533a\u57df\u7684\u4e2d\u5fc3\u3002\u8bf7\u6ce8\u610f\uff0c\u5728\u6784\u5efa\u70b9\u5bf9\u8c61\u65f6\uff0c\u6240\u6709\u7684\u5206\u91cf\u90fd\u88ab\u8bbe\u7f6e\u4e3a\u96f6\u3002\n\n    Point<dim> point_1, point_2; \n    point_1(0) = 0.5; \n    point_2(0) = -0.5; \n\n    for (unsigned int point_n = 0; point_n < points.size(); ++point_n) \n      { \n\n// \u5982\u679c <code>points[point_n]</code> \u5904\u4e8e\u56f4\u7ed5\u8fd9\u4e9b\u70b9\u4e4b\u4e00\u7684\u534a\u5f84\u4e3a0.2\u7684\u5706\uff08\u7403\uff09\u4e2d\uff0c\u90a3\u4e48\u5c06X\u65b9\u5411\u7684\u529b\u8bbe\u7f6e\u4e3a1\uff0c\u5426\u5219\u4e3a0\u3002\n\n        if (((points[point_n] - point_1).norm_square() < 0.2 * 0.2) || \n            ((points[point_n] - point_2).norm_square() < 0.2 * 0.2)) \n          values[point_n][0] = 1.0; \n        else \n          values[point_n][0] = 0.0; \n\n// \u540c\u6837\u5730\uff0c\u5982\u679c <code>points[point_n]</code> \u5728\u539f\u70b9\u9644\u8fd1\uff0c\u90a3\u4e48\u5c06y\u529b\u8bbe\u7f6e\u4e3a1\uff0c\u5426\u5219\u4e3a0\u3002\n\n        if (points[point_n].norm_square() < 0.2 * 0.2) \n          values[point_n][1] = 1.0; \n        else \n          values[point_n][1] = 0.0; \n      } \n  } \n\n//  @sect3{The <code>ElasticProblem</code> class implementation}  \n// @sect4{ElasticProblem::ElasticProblem constructor}  \n\n// \u4e0b\u9762\u662f\u4e3b\u7c7b\u7684\u6784\u9020\u51fd\u6570\u3002\u5982\u524d\u6240\u8ff0\uff0c\u6211\u4eec\u60f3\u6784\u9020\u4e00\u4e2a\u7531\u591a\u4e2a\u6807\u91cf\u6709\u9650\u5143\u7ec4\u6210\u7684\u77e2\u91cf\u503c\u6709\u9650\u5143\uff08\u5373\uff0c\u6211\u4eec\u60f3\u6784\u9020\u77e2\u91cf\u503c\u5143\u7d20\uff0c\u4f7f\u5176\u6bcf\u4e2a\u77e2\u91cf\u6210\u5206\u90fd\u7531\u4e00\u4e2a\u6807\u91cf\u5143\u7d20\u7684\u5f62\u72b6\u51fd\u6570\u7ec4\u6210\uff09\u3002\u5f53\u7136\uff0c\u6211\u4eec\u60f3\u5806\u53e0\u5728\u4e00\u8d77\u7684\u6807\u91cf\u6709\u9650\u5143\u7684\u6570\u91cf\u7b49\u4e8e\u89e3\u51fd\u6570\u7684\u5206\u91cf\u6570\u91cf\uff0c\u7531\u4e8e\u6211\u4eec\u8003\u8651\u6bcf\u4e2a\u7a7a\u95f4\u65b9\u5411\u4e0a\u7684\u4f4d\u79fb\uff0c\u6240\u4ee5\u662f <code>dim</code> \u3002FESystem\u7c7b\u53ef\u4ee5\u5904\u7406\u8fd9\u4e2a\u95ee\u9898\uff1a\u6211\u4eec\u4f20\u9012\u7ed9\u5b83\u6211\u4eec\u60f3\u7ec4\u6210\u7cfb\u7edf\u7684\u6709\u9650\u5143\uff0c\u4ee5\u53ca\u5b83\u7684\u91cd\u590d\u9891\u7387\u3002\n\n  template <int dim> \n  ElasticProblem<dim>::ElasticProblem() \n    : dof_handler(triangulation) \n    , fe(FE_Q<dim>(1), dim) \n  {} \n\n// \u4e8b\u5b9e\u4e0a\uff0cFESystem\u7c7b\u8fd8\u6709\u51e0\u4e2a\u6784\u9020\u51fd\u6570\uff0c\u53ef\u4ee5\u8fdb\u884c\u66f4\u590d\u6742\u7684\u64cd\u4f5c\uff0c\u800c\u4e0d\u4ec5\u4ec5\u662f\u5c06\u51e0\u4e2a\u76f8\u540c\u7c7b\u578b\u7684\u6807\u91cf\u6709\u9650\u5143\u5806\u53e0\u5728\u4e00\u8d77\uff1b\u6211\u4eec\u5c06\u5728\u540e\u9762\u7684\u4f8b\u5b50\u4e2d\u4e86\u89e3\u8fd9\u4e9b\u53ef\u80fd\u6027\u3002\n\n//  @sect4{ElasticProblem::setup_system}  \n\n// \u8bbe\u7f6e\u65b9\u7a0b\u7ec4\u4e0e step-6 \u4f8b\u5b50\u4e2d\u4f7f\u7528\u7684\u51fd\u6570\u76f8\u540c\u3002DoFHandler\u7c7b\u548c\u8fd9\u91cc\u4f7f\u7528\u7684\u6240\u6709\u5176\u4ed6\u7c7b\u90fd\u5b8c\u5168\u77e5\u9053\u6211\u4eec\u8981\u4f7f\u7528\u7684\u6709\u9650\u5143\u662f\u77e2\u91cf\u503c\u7684\uff0c\u5e76\u4e14\u7167\u987e\u5230\u4e86\u6709\u9650\u5143\u672c\u8eab\u7684\u77e2\u91cf\u503c\u3002(\u4e8b\u5b9e\u4e0a\uff0c\u5b83\u4eec\u4e0d\u77e5\u9053\uff0c\u4f46\u8fd9\u4e0d\u9700\u8981\u56f0\u6270\u4f60\uff1a\u56e0\u4e3a\u5b83\u4eec\u53ea\u9700\u8981\u77e5\u9053\u6bcf\u4e2a\u9876\u70b9\u3001\u76f4\u7ebf\u548c\u5355\u5143\u6709\u591a\u5c11\u4e2a\u81ea\u7531\u5ea6\uff0c\u5b83\u4eec\u4e0d\u95ee\u5b83\u4eec\u4ee3\u8868\u4ec0\u4e48\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u8003\u8651\u7684\u6709\u9650\u5143\u662f\u77e2\u91cf\u503c\u7684\uff0c\u8fd8\u662f\u4f8b\u5982\u5728\u6bcf\u4e2a\u9876\u70b9\u4e0a\u6709\u51e0\u4e2a\u81ea\u7531\u5ea6\u7684\u6807\u91cfHermite\u5143)\u3002\n\n  template <int dim> \n  void ElasticProblem<dim>::setup_system() \n  { \n    dof_handler.distribute_dofs(fe); \n    solution.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n\n    constraints.clear(); \n    DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             Functions::ZeroFunction<dim>(dim), \n                                             constraints); \n    constraints.close(); \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, \n                                    dsp, \n                                    constraints, \n                                    /*keep_constrained_dofs =  */ false);\n\n    sparsity_pattern.copy_from(dsp); \n\n    system_matrix.reinit(sparsity_pattern); \n  } \n// @sect4{ElasticProblem::assemble_system}  \n\n// \u8fd9\u4e2a\u7a0b\u5e8f\u4e2d\u6700\u5927\u7684\u53d8\u5316\u662f\u521b\u5efa\u77e9\u9635\u548c\u53f3\u624b\u8fb9\uff0c\u56e0\u4e3a\u5b83\u4eec\u662f\u53d6\u51b3\u4e8e\u95ee\u9898\u7684\u3002\u6211\u4eec\u5c06\u4e00\u6b65\u4e00\u6b65\u5730\u5b8c\u6210\u8fd9\u4e2a\u8fc7\u7a0b  step-  \uff0c\u56e0\u4e3a\u5b83\u6bd4\u4ee5\u524d\u7684\u4f8b\u5b50\u8981\u590d\u6742\u4e00\u4e9b\u3002\n\n// \u7136\u800c\uff0c\u8fd9\u4e2a\u51fd\u6570\u7684\u524d\u51e0\u90e8\u5206\u548c\u4ee5\u524d\u4e00\u6837\uff1a\u8bbe\u7f6e\u4e00\u4e2a\u5408\u9002\u7684\u6b63\u4ea4\u516c\u5f0f\uff0c\u4e3a\u6211\u4eec\u4f7f\u7528\u7684\uff08\u77e2\u91cf\u503c\uff09\u6709\u9650\u5143\u4ee5\u53ca\u6b63\u4ea4\u5bf9\u8c61\u521d\u59cb\u5316\u4e00\u4e2aFEValues\u5bf9\u8c61\uff0c\u5e76\u58f0\u660e\u4e86\u4e00\u4e9b\u8f85\u52a9\u6570\u7ec4\u3002\u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u58f0\u660e\u4e86\u6c38\u8fdc\u76f8\u540c\u7684\u4e24\u4e2a\u7f29\u5199\u3002  <code>n_q_points</code>  \u548c  <code>dofs_per_cell</code>  \u3002\u6bcf\u4e2a\u5355\u5143\u7684\u81ea\u7531\u5ea6\u6570\u91cf\uff0c\u6211\u4eec\u73b0\u5728\u663e\u7136\u662f\u4ece\u7ec4\u6210\u7684\u6709\u9650\u5143\u4e2d\u8be2\u95ee\uff0c\u800c\u4e0d\u662f\u4ece\u5e95\u5c42\u7684\u6807\u91cfQ1\u5143\u4e2d\u8be2\u95ee\u3002\u5728\u8fd9\u91cc\uff0c\u5b83\u662f <code>dim</code> \u4e58\u4ee5Q1\u5143\u7d20\u7684\u6bcf\u4e2a\u5355\u5143\u7684\u81ea\u7531\u5ea6\u6570\uff0c\u5c3d\u7ba1\u8fd9\u4e0d\u662f\u6211\u4eec\u9700\u8981\u5173\u5fc3\u7684\u660e\u786e\u77e5\u8bc6\u3002\n\n  template <int dim> \n  void ElasticProblem<dim>::assemble_system() \n  { \n    QGauss<dim> quadrature_formula(fe.degree + 1); \n\n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     cell_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n// \u6b63\u5982\u524d\u9762\u7684\u4f8b\u5b50\u6240\u793a\uff0c\u6211\u4eec\u9700\u8981\u4e00\u4e2a\u5730\u65b9\u6765\u5b58\u50a8\u5355\u5143\u683c\u4e0a\u6240\u6709\u6b63\u4ea4\u70b9\u7684\u7cfb\u6570\u503c\u3002\u5728\u76ee\u524d\u7684\u60c5\u51b5\u4e0b\uff0c\u6211\u4eec\u6709\u4e24\u4e2a\u7cfb\u6570\uff0clambda\u548cmu\u3002\n\n    std::vector<double> lambda_values(n_q_points); \n    std::vector<double> mu_values(n_q_points); \n\n// \u597d\u5427\uff0c\u6211\u4eec\u4e5f\u53ef\u4ee5\u7701\u7565\u4e0a\u9762\u7684\u4e24\u4e2a\u6570\u7ec4\uff0c\u56e0\u4e3a\u6211\u4eec\u5c06\u5bf9lambda\u548cmu\u4f7f\u7528\u5e38\u6570\u7cfb\u6570\uff0c\u53ef\u4ee5\u8fd9\u6837\u58f0\u660e\u3002\u5b83\u4eec\u90fd\u4ee3\u8868\u51fd\u6570\u603b\u662f\u8fd4\u56de\u5e38\u91cf\u503c1.0\u3002\u5c3d\u7ba1\u6211\u4eec\u53ef\u4ee5\u5728\u77e9\u9635\u7684\u7ec4\u5408\u4e2d\u7701\u7565\u5404\u81ea\u7684\u7cfb\u6570\uff0c\u4f46\u4e3a\u4e86\u6f14\u793a\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u4f7f\u7528\u5b83\u4eec\u3002\n\n    Functions::ConstantFunction<dim> lambda(1.), mu(1.); \n\n// \u548c\u4e0a\u9762\u7684\u4e24\u4e2a\u5e38\u91cf\u51fd\u6570\u4e00\u6837\uff0c\u6211\u4eec\u5c06\u5728\u6bcf\u4e2a\u5355\u5143\u683c\u4e2d\u53ea\u8c03\u7528\u4e00\u6b21\u51fd\u6570right_hand_side\uff0c\u4ee5\u4f7f\u4e8b\u60c5\u66f4\u7b80\u5355\u3002\n\n    std::vector<Tensor<1, dim>> rhs_values(n_q_points); \n\n// \u73b0\u5728\u6211\u4eec\u53ef\u4ee5\u5f00\u59cb\u5bf9\u6240\u6709\u5355\u5143\u683c\u8fdb\u884c\u5faa\u73af\u3002\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_matrix = 0; \n        cell_rhs    = 0; \n\n        fe_values.reinit(cell); \n\n// \u63a5\u4e0b\u6765\u6211\u4eec\u5f97\u5230\u6b63\u4ea4\u70b9\u7684\u7cfb\u6570\u503c\u3002\u540c\u6837\uff0c\u5bf9\u4e8e\u53f3\u624b\u8fb9\u4e5f\u662f\u5982\u6b64\u3002\n\n        lambda.value_list(fe_values.get_quadrature_points(), lambda_values); \n        mu.value_list(fe_values.get_quadrature_points(), mu_values); \n        right_hand_side(fe_values.get_quadrature_points(), rhs_values); \n\n// \u7136\u540e\u5c06\u5c40\u90e8\u521a\u5ea6\u77e9\u9635\u7684\u6761\u76ee\u548c\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u7ec4\u5408\u8d77\u6765\u3002\u8fd9\u51e0\u4e4e\u662f\u4e00\u5bf9\u4e00\u5730\u9075\u5faa\u672c\u4f8b\u4ecb\u7ecd\u4e2d\u63cf\u8ff0\u7684\u6a21\u5f0f\u3002 \u5728\u4f4d\u7684\u51e0\u4e2a\u8bc4\u8bba\u4e4b\u4e00\u662f\uff0c\u6211\u4eec\u53ef\u4ee5\u8ba1\u7b97\u6570\u5b57  <code>comp(i)</code>  \uff0c\u5373\u4f7f\u7528\u4e0b\u9762\u7684  <code>fe.system_to_component_index(i).first</code>  \u51fd\u6570\u8c03\u7528\u5f62\u72b6\u51fd\u6570  <code>i</code>  \u7684\u552f\u4e00\u975e\u96f6\u5411\u91cf\u6210\u5206\u7684\u7d22\u5f15\u3002\n\n//\uff08\u901a\u8fc7\u8bbf\u95ee <code>system_to_component_index</code> \u51fd\u6570\u8fd4\u56de\u503c\u7684 <code>first</code> \u53d8\u91cf\uff0c\u4f60\u53ef\u80fd\u5df2\u7ecf\u731c\u5230\u5176\u4e2d\u8fd8\u6709\u66f4\u591a\u7684\u5185\u5bb9\u3002\u4e8b\u5b9e\u4e0a\uff0c\u8be5\u51fd\u6570\u8fd4\u56de\u4e00\u4e2a <code>std::pair@<unsigned int\uff0c\u65e0\u7b26\u53f7int @></code>, \uff0c\u5176\u4e2d\u7b2c\u4e00\u4e2a\u5143\u7d20\u662f <code>comp(i)</code> \uff0c\u7b2c\u4e8c\u4e2a\u5143\u7d20\u662f\u4ecb\u7ecd\u4e2d\u4e5f\u6307\u51fa\u7684\u503c <code>base(i)</code> \uff0c\u5373\u8fd9\u4e2a\u5f62\u72b6\u51fd\u6570\u5728\u8fd9\u4e2a\u7ec4\u4ef6\u4e2d\u6240\u6709\u975e\u96f6\u7684\u5f62\u72b6\u51fd\u6570\u4e2d\u7684\u7d22\u5f15\uff0c\u5373\u4ecb\u7ecd\u4e2d\u7684\u5b57\u5178 <code>base(i)</code> \u3002\u4e0d\u8fc7\uff0c\u8fd9\u4e0d\u662f\u6211\u4eec\u901a\u5e38\u611f\u5174\u8da3\u7684\u6570\u5b57\uff09\u3002)\n\n// \u6709\u4e86\u8fd9\u4e9b\u77e5\u8bc6\uff0c\u6211\u4eec\u5c31\u53ef\u4ee5\u628a\u5c40\u90e8\u77e9\u9635\u7684\u8d21\u732e\u96c6\u5408\u8d77\u6765\u3002\n\n        for (const unsigned int i : fe_values.dof_indices()) \n          { \n            const unsigned int component_i = \n              fe.system_to_component_index(i).first; \n\n            for (const unsigned int j : fe_values.dof_indices()) \n              { \n                const unsigned int component_j = \n                  fe.system_to_component_index(j).first; \n\n                for (const unsigned int q_point : \n                     fe_values.quadrature_point_indices()) \n                  { \n                    cell_matrix(i, j) += \n\n// \u7b2c\u4e00\u4e2a\u9879\u662f  $\\lambda \\partial_i u_i, \\partial_j v_j) + (\\mu \\partial_i u_j, \\partial_j v_i)$  \u3002\u6ce8\u610f\uff0c <code>shape_grad(i,q_point)</code> \u8fd4\u56de\u6b63\u4ea4\u70b9q_point\u5904\u7b2ci\u4e2a\u5f62\u72b6\u51fd\u6570\u7684\u552f\u4e00\u975e\u96f6\u5206\u91cf\u7684\u68af\u5ea6\u3002\u68af\u5ea6\u7684\u5206\u91cf <code>comp(i)</code> \u662f\u7b2ci\u4e2a\u5f62\u72b6\u51fd\u6570\u7684\u552f\u4e00\u975e\u96f6\u77e2\u91cf\u5206\u91cf\u76f8\u5bf9\u4e8ecomp(i)th\u5750\u6807\u7684\u5bfc\u6570\uff0c\u7531\u9644\u52a0\u7684\u62ec\u53f7\u8bbf\u95ee\u3002\n\n                      (                                                  // \n                        (fe_values.shape_grad(i, q_point)[component_i] * // \n                         fe_values.shape_grad(j, q_point)[component_j] * // \n                         lambda_values[q_point])                         // \n                        +                                                // \n                        (fe_values.shape_grad(i, q_point)[component_j] * // \n                         fe_values.shape_grad(j, q_point)[component_i] * // \n                         mu_values[q_point])                             // \n                        +                                                // \n\n// \u7b2c\u4e8c\u4e2a\u9879\u662f  $(\\mu \\nabla u_i, \\nabla v_j)$  \u3002\u6211\u4eec\u4e0d\u9700\u8981\u8bbf\u95ee\u68af\u5ea6\u7684\u5177\u4f53\u5206\u91cf\uff0c\u56e0\u4e3a\u6211\u4eec\u53ea\u9700\u8981\u8ba1\u7b97\u4e24\u4e2a\u68af\u5ea6\u7684\u6807\u91cf\u4e58\u79ef\uff0c\u8fd9\u4e2a\u95ee\u9898\u7531<tt>operator*</tt>\u7684\u91cd\u8f7d\u7248\u672c\u6765\u8d1f\u8d23\uff0c\u5c31\u50cf\u524d\u9762\u7684\u4f8b\u5b50\u4e00\u6837\u3002                            \u6ce8\u610f\uff0c\u901a\u8fc7\u4f7f\u7528<tt>?:</tt>\u64cd\u4f5c\u7b26\uff0c\u6211\u4eec\u53ea\u5728<tt>component_i</tt>\u7b49\u4e8e<tt>component_j</tt>\u65f6\u624d\u8fd9\u6837\u505a\uff0c\u5426\u5219\u4f1a\u52a0\u4e0a\u4e00\u4e2a\u96f6\uff08\u7f16\u8bd1\u5668\u4f1a\u5c06\u5176\u4f18\u5316\u6389\uff09\u3002\n\n                        ((component_i == component_j) ?        // \n                           (fe_values.shape_grad(i, q_point) * // \n                            fe_values.shape_grad(j, q_point) * // \n                            mu_values[q_point]) :              // \n                           0)                                  // \n                        ) *                                    // \n                      fe_values.JxW(q_point);                  // \n                  } \n              } \n          } \n\n// \u7ec4\u88c5\u53f3\u624b\u8fb9\u4e5f\u548c\u4ecb\u7ecd\u4e2d\u8ba8\u8bba\u7684\u4e00\u6837\u3002\n\n        for (const unsigned int i : fe_values.dof_indices()) \n          { \n            const unsigned int component_i = \n              fe.system_to_component_index(i).first; \n\n            for (const unsigned int q_point : \n                 fe_values.quadrature_point_indices()) \n              cell_rhs(i) += fe_values.shape_value(i, q_point) * \n                             rhs_values[q_point][component_i] * \n                             fe_values.JxW(q_point); \n          } \n\n// \u4ece\u5c40\u90e8\u81ea\u7531\u5ea6\u5230\u5168\u5c40\u77e9\u9635\u548c\u53f3\u624b\u5411\u91cf\u7684\u8f6c\u79fb\u4e0d\u53d6\u51b3\u4e8e\u6240\u8003\u8651\u7684\u65b9\u7a0b\uff0c\u56e0\u6b64\u4e0e\u4e4b\u524d\u6240\u6709\u7684\u4f8b\u5b50\u76f8\u540c\u3002\n\n        cell->get_dof_indices(local_dof_indices); \n        constraints.distribute_local_to_global( \n          cell_matrix, cell_rhs, local_dof_indices, system_matrix, system_rhs); \n      } \n  } \n\n//  @sect4{ElasticProblem::solve}  \n\n// \u89e3\u7b97\u5668\u5e76\u4e0d\u5173\u5fc3\u65b9\u7a0b\u7ec4\u7684\u6765\u6e90\uff0c\u53ea\u8981\u5b83\u4fdd\u6301\u6b63\u5b9a\u548c\u5bf9\u79f0\uff08\u8fd9\u662f\u4f7f\u7528CG\u89e3\u7b97\u5668\u7684\u8981\u6c42\uff09\uff0c\u800c\u8fd9\u4e2a\u65b9\u7a0b\u7ec4\u786e\u5b9e\u662f\u8fd9\u6837\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u4e0d\u9700\u8981\u6539\u53d8\u4efb\u4f55\u4e1c\u897f\u3002\n\n  template <int dim> \n  void ElasticProblem<dim>::solve() \n  { \n    SolverControl            solver_control(1000, 1e-12); \n    SolverCG<Vector<double>> cg(solver_control); \n\n    PreconditionSSOR<SparseMatrix<double>> preconditioner; \n    preconditioner.initialize(system_matrix, 1.2); \n\n    cg.solve(system_matrix, solution, system_rhs, preconditioner); \n\n    constraints.distribute(solution); \n  } \n// @sect4{ElasticProblem::refine_grid}  \n\n// \u5bf9\u7f51\u683c\u8fdb\u884c\u7ec6\u5316\u7684\u51fd\u6570\u4e0e step-6 \u7684\u4f8b\u5b50\u76f8\u540c\u3002\u6b63\u4ea4\u516c\u5f0f\u518d\u6b21\u9002\u5e94\u4e86\u7ebf\u6027\u5143\u7d20\u3002\u8bf7\u6ce8\u610f\uff0c\u8bef\u5dee\u4f30\u8ba1\u5668\u9ed8\u8ba4\u60c5\u51b5\u4e0b\u662f\u5c06\u4ece\u6709\u9650\u5143\u89e3\u7684\u6240\u6709\u5206\u91cf\u4e2d\u5f97\u5230\u7684\u4f30\u8ba1\u503c\u76f8\u52a0\uff0c\u4e5f\u5c31\u662f\u8bf4\uff0c\u5b83\u4f7f\u7528\u6240\u6709\u65b9\u5411\u7684\u4f4d\u79fb\uff0c\u6743\u91cd\u76f8\u540c\u3002\u5982\u679c\u6211\u4eec\u5e0c\u671b\u7f51\u683c\u53ea\u9002\u5e94x\u65b9\u5411\u7684\u4f4d\u79fb\uff0c\u6211\u4eec\u53ef\u4ee5\u7ed9\u51fd\u6570\u4f20\u9012\u4e00\u4e2a\u989d\u5916\u7684\u53c2\u6570\uff0c\u544a\u8bc9\u5b83\u8fd9\u6837\u505a\uff0c\u800c\u4e0d\u8003\u8651\u5176\u4ed6\u6240\u6709\u65b9\u5411\u7684\u4f4d\u79fb\u4f5c\u4e3a\u8bef\u5dee\u6307\u6807\u3002\u7136\u800c\uff0c\u5bf9\u4e8e\u76ee\u524d\u7684\u95ee\u9898\uff0c\u4f3c\u4e4e\u5e94\u8be5\u8003\u8651\u6240\u6709\u7684\u4f4d\u79fb\u5206\u91cf\uff0c\u800c\u4e14\u6743\u91cd\u76f8\u540c\u3002\n\n  template <int dim> \n  void ElasticProblem<dim>::refine_grid() \n  { \n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n\n    KellyErrorEstimator<dim>::estimate(dof_handler, \n                                       QGauss<dim - 1>(fe.degree + 1), \n                                       {}, \n                                       solution, \n                                       estimated_error_per_cell); \n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    estimated_error_per_cell, \n                                                    0.3, \n                                                    0.03); \n\n    triangulation.execute_coarsening_and_refinement(); \n  } \n// @sect4{ElasticProblem::output_results}  \n\n// \u8f93\u51fa\u7684\u60c5\u51b5\u4e0e\u4e4b\u524d\u7684\u4f8b\u5b50\u4e2d\u5df2\u7ecf\u663e\u793a\u8fc7\u7684\u5dee\u4e0d\u591a\u4e86\u3002\u552f\u4e00\u7684\u533a\u522b\u662f\uff0c\u6c42\u89e3\u51fd\u6570\u662f\u77e2\u91cf\u503c\u7684\u3002DataOut\u7c7b\u4f1a\u81ea\u52a8\u5904\u7406\u8fd9\u4e2a\u95ee\u9898\uff0c\u4f46\u6211\u4eec\u5fc5\u987b\u7ed9\u6c42\u89e3\u5411\u91cf\u7684\u6bcf\u4e2a\u5206\u91cf\u4e00\u4e2a\u4e0d\u540c\u7684\u540d\u5b57\u3002\n\n// \u4e3a\u4e86\u505a\u5230\u8fd9\u4e00\u70b9\uff0c DataOut::add_vector() \u51fd\u6570\u60f3\u8981\u4e00\u4e2a\u5b57\u7b26\u4e32\u7684\u5411\u91cf\u3002\u7531\u4e8e\u5206\u91cf\u7684\u6570\u91cf\u4e0e\u6211\u4eec\u5de5\u4f5c\u7684\u7ef4\u6570\u76f8\u540c\uff0c\u6211\u4eec\u4f7f\u7528\u4e0b\u9762\u7684 <code>switch</code> \u8bed\u53e5\u3002\n\n// \u6211\u4eec\u6ce8\u610f\u5230\uff0c\u4e00\u4e9b\u56fe\u5f62\u7a0b\u5e8f\u5bf9\u53d8\u91cf\u540d\u79f0\u4e2d\u5141\u8bb8\u7684\u5b57\u7b26\u6709\u9650\u5236\u3002\u56e0\u6b64\uff0cdeal.II\u53ea\u652f\u6301\u6240\u6709\u7a0b\u5e8f\u90fd\u652f\u6301\u7684\u8fd9\u4e9b\u5b57\u7b26\u7684\u6700\u5c0f\u5b50\u96c6\u3002\u57fa\u672c\u4e0a\uff0c\u8fd9\u4e9b\u5b57\u7b26\u662f\u5b57\u6bcd\u3001\u6570\u5b57\u3001\u4e0b\u5212\u7ebf\u548c\u5176\u4ed6\u4e00\u4e9b\u5b57\u7b26\uff0c\u4f46\u7279\u522b\u662f\u6ca1\u6709\u7a7a\u683c\u548c\u51cf\u53f7/\u6a2a\u7ebf\u3002\u5426\u5219\u8be5\u5e93\u5c06\u629b\u51fa\u4e00\u4e2a\u5f02\u5e38\uff0c\u81f3\u5c11\u5728\u8c03\u8bd5\u6a21\u5f0f\u4e0b\u662f\u8fd9\u6837\u3002\n\n// \u5728\u5217\u51fa\u4e861d\u30012d\u548c3d\u7684\u60c5\u51b5\u540e\uff0c\u5982\u679c\u6211\u4eec\u9047\u5230\u4e00\u4e2a\u6211\u4eec\u6ca1\u6709\u8003\u8651\u5230\u7684\u60c5\u51b5\uff0c\u8ba9\u7a0b\u5e8f\u6b7b\u4ea1\u662f\u4e00\u79cd\u5f88\u597d\u7684\u98ce\u683c\u3002\u8bf7\u8bb0\u4f4f\uff0c\u5982\u679c\u7b2c\u4e00\u4e2a\u53c2\u6570\u4e2d\u7684\u6761\u4ef6\u6ca1\u6709\u5f97\u5230\u6ee1\u8db3\uff0cAssert\u5b8f\u4f1a\u4ea7\u751f\u4e00\u4e2a\u5f02\u5e38\u3002\u5f53\u7136\uff0c\u6761\u4ef6 <code>false</code> \u6c38\u8fdc\u4e0d\u53ef\u80fd\u88ab\u6ee1\u8db3\uff0c\u6240\u4ee5\u53ea\u8981\u7a0b\u5e8f\u8fd0\u884c\u5230\u9ed8\u8ba4\u8bed\u53e5\uff0c\u5c31\u4f1a\u4e2d\u6b62\u3002\n\n  template <int dim> \n  void ElasticProblem<dim>::output_results(const unsigned int cycle) const \n  { \n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n\n    std::vector<std::string> solution_names; \n    switch (dim) \n      { \n        case 1: \n          solution_names.emplace_back(\"displacement\"); \n          break; \n        case 2: \n          solution_names.emplace_back(\"x_displacement\"); \n          solution_names.emplace_back(\"y_displacement\"); \n          break; \n        case 3: \n          solution_names.emplace_back(\"x_displacement\"); \n          solution_names.emplace_back(\"y_displacement\"); \n          solution_names.emplace_back(\"z_displacement\"); \n          break; \n        default: \n          Assert(false, ExcNotImplemented()); \n      } \n\n// \u5728\u4e3a\u89e3\u5411\u91cf\u7684\u4e0d\u540c\u7ec4\u6210\u90e8\u5206\u8bbe\u7f6e\u4e86\u540d\u79f0\u4e4b\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u5c06\u89e3\u5411\u91cf\u6dfb\u52a0\u5230\u8ba1\u5212\u8f93\u51fa\u7684\u6570\u636e\u5411\u91cf\u5217\u8868\u4e2d\u3002\u8bf7\u6ce8\u610f\uff0c\u4e0b\u9762\u7684\u51fd\u6570\u9700\u8981\u4e00\u4e2a\u5b57\u7b26\u4e32\u5411\u91cf\u4f5c\u4e3a\u7b2c\u4e8c\u4e2a\u53c2\u6570\uff0c\u800c\u6211\u4eec\u5728\u4ee5\u524d\u6240\u6709\u4f8b\u5b50\u4e2d\u4f7f\u7528\u7684\u51fd\u6570\u5728\u90a3\u91cc\u63a5\u53d7\u4e00\u4e2a\u5b57\u7b26\u4e32\u3002(\u4e8b\u5b9e\u4e0a\uff0c\u6211\u4eec\u4e4b\u524d\u4f7f\u7528\u7684\u51fd\u6570\u4f1a\u5c06\u5355\u4e2a\u5b57\u7b26\u4e32\u8f6c\u6362\u6210\u53ea\u6709\u4e00\u4e2a\u5143\u7d20\u7684\u5411\u91cf\uff0c\u5e76\u5c06\u5176\u8f6c\u53d1\u7ed9\u53e6\u4e00\u4e2a\u51fd\u6570)\u3002\n\n    data_out.add_data_vector(solution, solution_names); \n    data_out.build_patches(); \n\n    std::ofstream output(\"solution-\" + std::to_string(cycle) + \".vtk\"); \n    data_out.write_vtk(output); \n  } \n\n//  @sect4{ElasticProblem::run}  \n\n//  <code>run</code> \u51fd\u6570\u6240\u505a\u7684\u4e8b\u60c5\u4e0e step-6 \u4e2d\u7684\u76f8\u540c\uff0c\u6bd4\u5982\u8bf4\u3002\u8fd9\u4e00\u6b21\uff0c\u6211\u4eec\u4f7f\u7528\u5e73\u65b9[-1,1]^d\u4f5c\u4e3a\u57df\uff0c\u5728\u5f00\u59cb\u7b2c\u4e00\u6b21\u8fed\u4ee3\u4e4b\u524d\uff0c\u6211\u4eec\u5728\u5168\u5c40\u4e0a\u5bf9\u5176\u8fdb\u884c\u4e86\u56db\u6b21\u7ec6\u5316\u3002\n\n// \u7ec6\u5316\u7684\u539f\u56e0\u6709\u70b9\u610f\u5916\uff1a\u6211\u4eec\u4f7f\u7528QGauss\u6b63\u4ea4\u516c\u5f0f\uff0c\u5728\u6bcf\u4e2a\u65b9\u5411\u4e0a\u6709\u4e24\u4e2a\u70b9\u7528\u4e8e\u6574\u5408\u53f3\u624b\u8fb9\uff1b\u8fd9\u610f\u5473\u7740\u6bcf\u4e2a\u5355\u5143\u4e0a\u6709\u56db\u4e2a\u6b63\u4ea4\u70b9\uff08\u5728\u4e8c\u7ef4\uff09\u3002\u5982\u679c\u6211\u4eec\u53ea\u5bf9\u521d\u59cb\u7f51\u683c\u8fdb\u884c\u4e00\u6b21\u5168\u5c40\u7ec6\u5316\uff0c\u90a3\u4e48\u5728\u57df\u4e0a\u6bcf\u4e2a\u65b9\u5411\u4e0a\u5c31\u53ea\u6709\u56db\u4e2a\u6b63\u4ea4\u70b9\u3002\u7136\u800c\uff0c\u53f3\u4fa7\u51fd\u6570\u88ab\u9009\u62e9\u4e3a\u76f8\u5f53\u5c40\u90e8\u7684\uff0c\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u7eaf\u5c5e\u5076\u7136\uff0c\u6070\u597d\u6240\u6709\u7684\u6b63\u4ea4\u70b9\u90fd\u4f4d\u4e8e\u53f3\u4fa7\u51fd\u6570\u4e3a\u96f6\u7684\u70b9\u4e0a\uff08\u7528\u6570\u5b66\u672f\u8bed\u6765\u8bf4\uff0c\u6b63\u4ea4\u70b9\u6070\u597d\u5728\u53f3\u4fa7\u51fd\u6570\u7684<i>support</i>\u4e4b\u5916\u7684\u70b9\u4e0a\uff09\u3002\u8fd9\u6837\u4e00\u6765\uff0c\u7528\u6b63\u4ea4\u8ba1\u7b97\u7684\u53f3\u624b\u5411\u91cf\u5c06\u53ea\u5305\u542b\u96f6\uff08\u5c3d\u7ba1\u5982\u679c\u6211\u4eec\u5b8c\u5168\u7528\u79ef\u5206\u8ba1\u7b97\u53f3\u624b\u5411\u91cf\u7684\u8bdd\uff0c\u5b83\u5f53\u7136\u4f1a\u662f\u975e\u96f6\u7684\uff09\uff0c\u65b9\u7a0b\u7ec4\u7684\u89e3\u5c31\u662f\u96f6\u5411\u91cf\uff0c\u4e5f\u5c31\u662f\u4e00\u4e2a\u5904\u5904\u4e3a\u96f6\u7684\u6709\u9650\u5143\u51fd\u6570\u3002\u4ece\u67d0\u79cd\u610f\u4e49\u4e0a\u8bf4\uff0c\u6211\u4eec\u4e0d\u5e94\u8be5\u5bf9\u8fd9\u79cd\u60c5\u51b5\u7684\u53d1\u751f\u611f\u5230\u60ca\u8bb6\uff0c\u56e0\u4e3a\u6211\u4eec\u9009\u62e9\u4e86\u4e00\u4e2a\u5b8c\u5168\u4e0d\u9002\u5408\u624b\u5934\u95ee\u9898\u7684\u521d\u59cb\u7f51\u683c\u3002\n\n// \u4e0d\u5e78\u7684\u662f\uff0c\u5982\u679c\u79bb\u6563\u89e3\u662f\u5e38\u6570\uff0c\u90a3\u4e48KellyErrorEstimator\u7c7b\u8ba1\u7b97\u7684\u8bef\u5dee\u6307\u6807\u5bf9\u6bcf\u4e2a\u5355\u5143\u6765\u8bf4\u4e5f\u662f\u96f6\uff0c\u5bf9 Triangulation::refine_and_coarsen_fixed_number() \u7684\u8c03\u7528\u5c06\u4e0d\u4f1a\u6807\u8bb0\u4efb\u4f55\u5355\u5143\u8fdb\u884c\u7ec6\u5316\uff08\u5982\u679c\u6bcf\u4e2a\u5355\u5143\u7684\u6307\u793a\u8bef\u5dee\u662f\u96f6\uff0c\u4e3a\u4ec0\u4e48\u8981\u8fd9\u6837\u505a\uff1f\u56e0\u6b64\uff0c\u4e0b\u4e00\u6b21\u8fed\u4ee3\u4e2d\u7684\u7f51\u683c\u4e5f\u5c06\u53ea\u7531\u56db\u4e2a\u5355\u5143\u7ec4\u6210\uff0c\u540c\u6837\u7684\u95ee\u9898\u518d\u6b21\u53d1\u751f\u3002\n\n// \u7ed3\u8bba\u662f\uff1a\u867d\u7136\u6211\u4eec\u5f53\u7136\u4e0d\u4f1a\u628a\u521d\u59cb\u7f51\u683c\u9009\u62e9\u5f97\u975e\u5e38\u9002\u5408\u95ee\u9898\u7684\u7cbe\u786e\u89e3\u51b3\uff0c\u4f46\u6211\u4eec\u81f3\u5c11\u5fc5\u987b\u9009\u62e9\u5b83\uff0c\u4f7f\u5b83\u6709\u673a\u4f1a\u6355\u6349\u5230\u89e3\u51b3\u65b9\u6848\u7684\u91cd\u8981\u7279\u5f81\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u5b83\u9700\u8981\u80fd\u591f\u770b\u5230\u53f3\u624b\u8fb9\u7684\u60c5\u51b5\u3002\u56e0\u6b64\uff0c\u6211\u4eec\u8fdb\u884c\u4e86\u56db\u6b21\u5168\u5c40\u7ec6\u5316\u3002(\u4efb\u4f55\u66f4\u5927\u7684\u5168\u5c40\u7ec6\u5316\u6b65\u9aa4\u5f53\u7136\u4e5f\u53ef\u4ee5\u3002)\n\n  template <int dim> \n  void ElasticProblem<dim>::run() \n  { \n    for (unsigned int cycle = 0; cycle < 8; ++cycle) \n      { \n        std::cout << \"Cycle \" << cycle << ':' << std::endl; \n\n        if (cycle == 0) \n          { \n            GridGenerator::hyper_cube(triangulation, -1, 1); \n            triangulation.refine_global(4); \n          } \n        else \n          refine_grid(); \n\n        std::cout << \"   Number of active cells:       \" \n                  << triangulation.n_active_cells() << std::endl; \n\n        setup_system(); \n\n        std::cout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n                  << std::endl; \n\n        assemble_system(); \n        solve(); \n        output_results(cycle); \n      } \n  } \n} // namespace Step8 \n// @sect3{The <code>main</code> function}  \n\n// \u5728\u4e0a\u9762\u6700\u540e\u4e00\u884c\u5173\u95ed\u4e86 <code>Step8</code> \u547d\u540d\u7a7a\u95f4\u540e\uff0c\u4e0b\u9762\u662f\u7a0b\u5e8f\u7684\u4e3b\u8981\u529f\u80fd\uff0c\u53c8\u548c step-6 \u4e2d\u4e00\u6a21\u4e00\u6837\uff08\u5f53\u7136\uff0c\u9664\u4e86\u6539\u53d8\u4e86\u7c7b\u540d\uff09\u3002\n\nint main() \n{ \n  try \n    { \n      Step8::ElasticProblem<2> elastic_problem_2d; \n      elastic_problem_2d.run(); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n\n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n\n  return 0; \n} \n\n", "meta": {"hexsha": "26315aa71b5a8f5af8cb8cc2b0c302af87dff82b", "size": 17512, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-8/step-8.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-8/step-8.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-8/step-8.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1016949153, "max_line_length": 323, "alphanum_fraction": 0.6144929191, "num_tokens": 7131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.625562880046471}}
{"text": "#include <vector>\n\n#include <NTL/ZZ.h>\n\n#include \"../src/elements/element.hpp\"\n#include \"../src/algorithms/utils.hpp\"\n\n/* Example: using the remainder tree algorithm to search for Wilson primes.\n * This was the first application for the remainder tree algorithm and also is\n * one of the simplest. Wilson's theorem says that for all primes p, the following is true:\n *(p-1)! = -1 (mod p). A Wilson prime satisfies the same identity modulo p^2.\n *\n * Let A_0 = A_1 = 1, and A_n = n-1. Also set m_n to be n if n is prime, and 1 otherwise.\n * Then, if A_0 * A_1 * ... A_p = -1 (mod m_n), then m_n is a Wilson prime.\n */\n\n\nusing std::vector;\n\n/* The first decision to make is what kind of datatype to use. In this case it is clear that we only\n * need to use integers. However, for many applications such as those in polynomial rings or if the\n * recurrence relation of the dividends is of order higher than 1, other datatypes may be desired.\n * Most of the code was written with using NTL in mind. However, we wrap every value in the type Elt.\n * Elt is a templated class object which will forward constructors, operators, etc. to its underlying type.\n * To specialize it for a new type (for example, to optimize its .mulmod() method), create a new file in\n * src/elements and then include it in elt_custom.tpp\n * I recommend specialized the methods rather than the class itself. Take a look at elt_NTL.tpp for an example.\n */\nusing NTL::ZZ;\n\n//The convention here is to generate from lower bound---inclusive to upper---exclusive\nvector<Elt<ZZ>> gen_n(long lower, long upper) {\n    vector<Elt<ZZ>> output(upper-lower);\n\n    for(long i = lower; i < upper; ++i) {\n        if(i <= 1){\n            output[i] = Elt<ZZ>(1);\n        }\n        else {\n            output[i-lower] = Elt<ZZ> (i-1);\n        }\n    }\n    return output;\n}\n\n\nvector<Elt<ZZ>> gen_second_prime_power(long lower, long upper) {\n    vector<Elt<ZZ>> output(upper-lower);\n    \n    for(long i = lower; i < upper; i++){\n        ZZ n(i);\n        if(ProbPrime(n)) { //Technically a sieve is faster & more correct, but shouldn't make a big difference.\n                            //This is just an example anyway.\n            power(n, n, 2);\n            output[i-lower] = Elt<ZZ>(n);\n        }\n        else{\n            output[i-lower] = Elt<ZZ>(1);\n        }\n    }\n    return output;\n}\n\n\n\n//TODO: explain how to modify calculate_factorial and compute V", "meta": {"hexsha": "1c2e07f46184d1185fc8650c7fb8da68c7a0079a", "size": 2406, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/wilson.hpp", "max_stars_repo_name": "adienes/remainder-tree", "max_stars_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/wilson.hpp", "max_issues_repo_name": "adienes/remainder-tree", "max_issues_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/wilson.hpp", "max_forks_repo_name": "adienes/remainder-tree", "max_forks_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4545454545, "max_line_length": 111, "alphanum_fraction": 0.6500415628, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6255628729799015}}
{"text": "/*\n *  testOrientedVoxels.cpp\n *  Trogdor6\n *\n *  Created by Paul Hansen on 6/29/10.\n *  Copyright 2010 Stanford University. All rights reserved.\n *\n *  This file is covered by the MIT license.  See LICENSE.txt.\n */\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE TestVoxelizer\n\n#include <boost/test/unit_test.hpp>\n\n#include \"TensorGridConstants.h\"\n\n#include <iomanip>\n\nusing namespace std;\nusing namespace RLE;\nusing namespace YeeUtilities;\n\nBOOST_AUTO_TEST_CASE( EffectivePermittivity )\n{\n    double tolerance;\n    if (sizeof(Precision::Float) == sizeof(float))\n        tolerance = 1e-5;\n    else\n        tolerance = 1e-9;\n    vector<Precision::RationalFunction> materials(2);\n    materials[0] = 1.0;\n    materials[1] = 2.0;\n    \n    vector<DynamicRLE3<double> > fillFactors(2);\n    fillFactors[0].mark(0,0,0,0.5);\n    fillFactors[1].mark(0,0,0,0.5);\n    \n    DynamicRLE3<Precision::RationalFunction> inversePermittivity;\n    \n    // Parameters just to fill space in the TensorGridConstants constructor\n    const int WHATEVER = 0;\n    DynamicRLE3<Precision::RationalFunction> WHO_CARES;\n    TensorGridConstants tgc(WHATEVER, WHATEVER, WHO_CARES, Rect3i(0,0,0,0,0,0));\n    \n    // Test normal-to-surface diagonal component:\n    //  permittivity is harmonic mean\n    //  permittivity is of the form 1/a0, so the numerator of 1/eps is a0,\n    //   or 1/(harmonic mean).  The harmonic mean of 1 and 2 is 4/3, so a0 is \n    //   0.75.\n    {\n        DynamicRLE3<double> orientation;\n        orientation.mark(0,0,0,1.0);\n        inversePermittivity = tgc.diagonalElement(materials, fillFactors, orientation);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).numerator().order(), 0);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).denominator().order(), 0);\n        \n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).numerator()[0], 0.75, tolerance);\n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).denominator()[0], 1.0, tolerance);\n    }\n    \n    // Test parallel-to-surface diagonal component:\n    //  permittivity is arithmetic mean\n    //  1/a0 = 1.5, so a0 = 2/3\n    {\n        DynamicRLE3<double> orientation;\n        orientation.mark(0,0,0,0.0);\n        inversePermittivity = tgc.diagonalElement(materials, fillFactors, orientation);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).numerator().order(), 0);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).denominator().order(), 0);\n        \n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).numerator()[0], 2.0/3, tolerance);\n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).denominator()[0], 1.0, tolerance);\n    }\n    \n    // Test off-diagonal component for diagonal orientation tensor:\n    // should be zero.\n    {\n        DynamicRLE3<double> orientation;\n        orientation.mark(0,0,0,0.0);\n        inversePermittivity = tgc.offDiagonalElement(materials, fillFactors, orientation);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).numerator().order(), 0);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).denominator().order(), 0);\n        \n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).numerator()[0], 0.0, tolerance);\n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).denominator()[0], 1.0, tolerance);\n    }\n    \n    // Test a nonzero off-diagonal of the tensor.\n    {\n        double harmonicMean = 4.0/3;\n        double arithmeticMean = 1.5;\n        double orientation_ij = 0.5;\n        \n        double epsInv = orientation_ij*(1.0/harmonicMean - 1.0/arithmeticMean);\n        \n        DynamicRLE3<double> orientation;\n        orientation.mark(0,0,0, orientation_ij);\n        inversePermittivity = tgc.offDiagonalElement(materials,\n            fillFactors, orientation);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).numerator().order(), 0);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).denominator().order(), 0);\n        \n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).numerator()[0], epsInv, tolerance);\n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).denominator()[0], 1.0, tolerance);\n    }\n}\n\nBOOST_AUTO_TEST_CASE( BackgroundMaterial )\n{\n    double tolerance;\n    if (sizeof(Precision::Float) == sizeof(float))\n        tolerance = 1e-5;\n    else\n        tolerance = 1e-9;\n    vector<Precision::RationalFunction> materials(1);\n    materials[0] = 1.0;\n//    materials[1] = 2.0;\n    \n    vector<DynamicRLE3<double> > fillFactors(1);\n    fillFactors[0].mark(0,0,0,0.5);\n//    fillFactors[1].mark(0,0,0,0.5);\n    \n    DynamicRLE3<Precision::RationalFunction> inversePermittivity;\n    \n    // Parameters just to fill space in the TensorGridConstants constructor\n    const int WHATEVER = 0;\n    DynamicRLE3<Precision::RationalFunction> WHO_CARES;\n    TensorGridConstants tgc(WHATEVER, WHATEVER, WHO_CARES,\n        Rect3i(0,0,0,0,0,0),\n        Precision::RationalFunction(2.0));\n    \n    // Test normal-to-surface diagonal component:\n    //  permittivity is harmonic mean\n    //  permittivity is of the form 1/a0, so the numerator of 1/eps is a0,\n    //   or 1/(harmonic mean).  The harmonic mean of 1 and 2 is 4/3, so a0 is \n    //   0.75.\n    {\n        DynamicRLE3<double> orientation;\n        orientation.mark(0,0,0,1.0);\n        inversePermittivity = tgc.diagonalElement(materials,\n            fillFactors, orientation);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).numerator().order(), 0);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).denominator().order(), 0);\n        \n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).numerator()[0], 0.75, tolerance);\n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).denominator()[0], 1.0, tolerance);\n    }\n    \n    // Test parallel-to-surface diagonal component:\n    //  permittivity is arithmetic mean\n    //  1/a0 = 1.5, so a0 = 2/3\n    {\n        DynamicRLE3<double> orientation;\n        orientation.mark(0,0,0,0.0);\n        inversePermittivity = tgc.diagonalElement(materials,\n            fillFactors, orientation);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).numerator().order(), 0);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).denominator().order(), 0);\n        \n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).numerator()[0], 2.0/3, tolerance);\n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).denominator()[0], 1.0, tolerance);\n    }\n    \n    // Test off-diagonal component for diagonal orientation tensor:\n    // should be zero.\n    {\n        DynamicRLE3<double> orientation;\n        orientation.mark(0,0,0,0.0);\n        inversePermittivity = tgc.offDiagonalElement(materials, fillFactors, orientation);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).numerator().order(), 0);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).denominator().order(), 0);\n        \n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).numerator()[0], 0.0, tolerance);\n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).denominator()[0], 1.0, tolerance);\n    }\n    \n    // Test a nonzero off-diagonal of the tensor.\n    {\n        double harmonicMean = 4.0/3;\n        double arithmeticMean = 1.5;\n        double orientation_ij = 0.5;\n        \n        double epsInv = orientation_ij*(1.0/harmonicMean - 1.0/arithmeticMean);\n        \n        DynamicRLE3<double> orientation;\n        orientation.mark(0,0,0, orientation_ij);\n        inversePermittivity = tgc.offDiagonalElement(materials, fillFactors, orientation);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).numerator().order(), 0);\n        BOOST_CHECK_EQUAL(inversePermittivity.at(0,0,0).denominator().order(), 0);\n        \n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).numerator()[0], epsInv, tolerance);\n        BOOST_CHECK_CLOSE(inversePermittivity.at(0,0,0).denominator()[0], 1.0, tolerance);\n    }\n}\n\nBOOST_AUTO_TEST_CASE( Sensitivity_FillFactor_Analytical )\n{\n    double eps1 = 1.0, eps2 = 2.0;\n    double fill1 = 0.5, fill2 = 1.0 - fill1;\n    vector<Precision::RationalFunction> materials(2);\n    materials[0] = eps1;\n    materials[1] = eps2;\n    \n    vector<DynamicRLE3<double> > fillFactors(2);\n    fillFactors[0].mark(0,0,0, fill1);\n    fillFactors[1].mark(0,0,0, fill2);\n    \n    DynamicRLE3<Precision::RationalFunction> epsInv;\n    DynamicRLE3<Precision::RationalFunction> DepsInv;\n    \n    vector<DynamicRLE3<double> > dFillFactors(2);\n    dFillFactors[0].mark(0,0,0, 1.0);\n    dFillFactors[1].mark(0,0,0, -1.0);\n    DynamicRLE3<double> dOrientation; // all zeros!\n    \n    const int WHATEVER = 0;\n    DynamicRLE3<Precision::RationalFunction> WHO_CARES;\n    TensorGridConstants tgc(WHATEVER, WHATEVER, WHO_CARES, Rect3i(0,0,0,0,0,0));\n\n    \n    // Test normal-to-surface diagonal component:\n    //  permittivity is harmonic mean\n    //  permittivity is of the form 1/a0, so the numerator of 1/eps is a0,\n    //   or 1/(harmonic mean).  The harmonic mean of 1 and 2 is 4/3, so a0 is \n    //   0.75.\n    {\n        DynamicRLE3<double> orientation;\n        orientation.mark(0,0,0,1.0);\n        epsInv = tgc.diagonalElement(materials,\n            fillFactors, orientation);\n        DepsInv = *tgc.diagonalSensitivity(materials,\n            fillFactors, orientation, dFillFactors, dOrientation);\n        double Da0 = 1/eps1 - 1/eps2; // derive it yerself!\n        \n        BOOST_CHECK_CLOSE(DepsInv.at(0,0,0).numerator()[0], Da0, 1); // to 1%\n    }\n    \n    // Test parallel-to-surface diagonal component:\n    //  permittivity is arithmetic mean\n    //  1/a0 = 1.5, so a0 = 2/3\n    {\n        DynamicRLE3<double> orientation;\n        orientation.mark(0,0,0,0.0);\n        epsInv = tgc.diagonalElement(materials,\n            fillFactors, orientation);\n        DepsInv = *tgc.diagonalSensitivity(materials,\n            fillFactors, orientation, dFillFactors, dOrientation);\n        double meanEps = fill1*eps1 + fill2*eps2;\n        double Da0 = (eps2-eps1)/meanEps/meanEps; // derive it yerself!\n        \n        BOOST_CHECK_CLOSE(DepsInv.at(0,0,0).numerator()[0], Da0, 1); // to 1%\n    }\n}\n\n\n\n// Test sensitivity to variation of fill factors.\nBOOST_AUTO_TEST_CASE( Sensitivity_FillFactor_FiniteDifference )\n{\n    vector<Precision::RationalFunction> materials(2);\n    materials[0] = 1.0;\n    materials[1] = Precision::RationalFunction(\n        Precision::Polynomial(10.0, -20.0, 30.0),\n        Precision::Polynomial(11.0, -22.0, 33.0) );\n        \n    const int WHATEVER = 0;\n    DynamicRLE3<Precision::RationalFunction> WHO_CARES;\n    TensorGridConstants tgc(WHATEVER, WHATEVER, WHO_CARES, Rect3i(0,0,0,0,0,0));\n    \n//    typedef numeric_limits<Precision::Float> f;\n    const double DELTA = 0.01;\n    //const double DELTA = sqrt(f::epsilon());\n    const double TOLERANCE = 10*DELTA;\n//    cerr << \"Using DELTA = \" << DELTA << \", TOLERANCE = \" << TOLERANCE << \"\\n\";\n    \n    vector<DynamicRLE3<double> > fillFactors1(2), fillFactors2(2);\n    fillFactors1[0].mark(0,0,0,0.5);\n    fillFactors1[1].mark(0,0,0,0.5);\n    fillFactors2[0] = fillFactors1[0] + DELTA;\n    fillFactors2[1] = fillFactors1[1] - DELTA;\n    vector<DynamicRLE3<double> > dFillFactors(2);\n    dFillFactors[0] = (fillFactors2[0] - fillFactors1[0])/DELTA/2;\n    dFillFactors[1] = (fillFactors2[1] - fillFactors1[1])/DELTA/2;\n    \n    DynamicRLE3<double> orientation;\n    DynamicRLE3<double> dOrientation; // empty\n    orientation.mark(0,0,0, 0.4); // some arbitrary value.\n    \n    DynamicRLE3<Precision::RationalFunction> epsInv1, epsInv2;\n    DynamicRLE3<Precision::RationalFunction> epsInvSensitivity;\n    \n    epsInv1 = tgc.diagonalElement(materials, fillFactors1, orientation);\n    epsInv2 = tgc.diagonalElement(materials, fillFactors2, orientation);\n    epsInvSensitivity = *tgc.diagonalSensitivity(materials, fillFactors1, orientation, dFillFactors, dOrientation);\n    \n    TensorGridConstants::Differential diff(2*DELTA);\n    \n    if (0)\n    {\n        cerr << \"eps1:\\n\" << epsInv1 << \"\\n\";\n        cerr << \"eps2:\\n\" << epsInv2 << \"\\n\";\n        cerr << \"eps sensitivity: \" << epsInvSensitivity << \"\\n\";\n        cerr << \"by differential:\\n\" << diff(epsInv2.at(0,0,0), epsInv1.at(0,0,0))\n            << \"\\n\";\n    }\n    \n    double deltaNumer = epsInv2.at(0,0,0).numerator()[0] -\n        epsInv1.at(0,0,0).numerator()[0];\n    double deltaDenom = epsInv2.at(0,0,0).denominator()[0] -\n        epsInv1.at(0,0,0).denominator()[0];\n    double dNumer = epsInvSensitivity.at(0,0,0).numerator()[0];\n    double dDenom = epsInvSensitivity.at(0,0,0).denominator()[0];\n    \n    BOOST_CHECK_SMALL(dDenom, TOLERANCE*100); // technically zero\n    BOOST_CHECK_SMALL(deltaDenom, TOLERANCE*100); // technically zero\n    BOOST_CHECK_CLOSE(dNumer, deltaNumer/DELTA/2, 1.0); // to within 1% is ok\n}\n\n\n\nBOOST_AUTO_TEST_CASE( Sensitivity_Orientation_FiniteDifference )\n{\n    const int WHATEVER = 0;\n    DynamicRLE3<Precision::RationalFunction> WHO_CARES;\n    TensorGridConstants tgc(WHATEVER, WHATEVER, WHO_CARES, Rect3i(0,0,0,0,0,0));\n    \n    vector<Precision::RationalFunction> materials(2);\n    materials[0] = 1.0;\n    materials[1] = 2.0;\n    \n    typedef numeric_limits<Precision::Float> f;\n    const double DELTA = sqrt(f::epsilon());\n    const double TOLERANCE = 10*DELTA;\n    BOOST_TEST_MESSAGE(\"Using DELTA = \" << DELTA << \", TOLERANCE = \" << TOLERANCE);\n    \n    vector<DynamicRLE3<double> > fillFactors(2);\n    vector<DynamicRLE3<double> > deltaFillFactors(2);\n    fillFactors[0].mark(0,0,0,0.5);\n    fillFactors[1].mark(0,0,0,0.5);\n    \n    DynamicRLE3<double> orientation1, orientation2;\n    orientation1.mark(0,0,0, 0.4); // some arbitrary value.\n    orientation2 = orientation1 + DELTA;\n    DynamicRLE3<double> dOrientation = (orientation2 - orientation1)/DELTA;\n    \n    DynamicRLE3<Precision::RationalFunction> epsInv1, epsInv2;\n    DynamicRLE3<Precision::RationalFunction> epsInvSensitivity;\n    \n    epsInv1 = tgc.diagonalElement(materials, fillFactors,\n        orientation1);\n    epsInv2 = tgc.diagonalElement(materials, fillFactors,\n        orientation2);\n    epsInvSensitivity = *tgc.diagonalSensitivity(materials,\n        fillFactors, orientation1, deltaFillFactors, dOrientation);\n    \n//    cout << \"eps1:\\n\" << epsInv1 << \"\\n\";\n//    cout << \"eps2:\\n\" << epsInv2 << \"\\n\";\n//    cout << \"eps sensitivity: \" << epsInvSensitivity << \"\\n\";\n//    cout << \"diff:\\n\" << epsInv2 - epsInv1 << \"\\n\";\n    \n    double deltaNumer = epsInv2.at(0,0,0).numerator()[0] -\n        epsInv1.at(0,0,0).numerator()[0];\n    double deltaDenom = epsInv2.at(0,0,0).denominator()[0] -\n        epsInv1.at(0,0,0).denominator()[0];\n    double dNumer = epsInvSensitivity.at(0,0,0).numerator()[0];\n    double dDenom = epsInvSensitivity.at(0,0,0).denominator()[0];\n    \n    BOOST_CHECK_SMALL(dDenom, TOLERANCE*100); // technically zero; tolerance %\n    BOOST_CHECK_SMALL(deltaDenom, TOLERANCE*100); // technically zero\n    BOOST_CHECK_CLOSE(dNumer, deltaNumer/DELTA, TOLERANCE*100); // within 0.01%\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "3bd525be33af45788eb56c6546f7c3ca923f186c", "size": 14862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FDTD/tests/testTensorGridConstants.cpp", "max_stars_repo_name": "plisdku/trogdor6", "max_stars_repo_head_hexsha": "d77eb137dd0c03635c0016801ada54117697e521", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FDTD/tests/testTensorGridConstants.cpp", "max_issues_repo_name": "plisdku/trogdor6", "max_issues_repo_head_hexsha": "d77eb137dd0c03635c0016801ada54117697e521", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FDTD/tests/testTensorGridConstants.cpp", "max_forks_repo_name": "plisdku/trogdor6", "max_forks_repo_head_hexsha": "d77eb137dd0c03635c0016801ada54117697e521", "max_forks_repo_licenses": ["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.0078740157, "max_line_length": 115, "alphanum_fraction": 0.6579195263, "num_tokens": 4548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.625458453186218}}
{"text": "#include <Eigen/Dense>\n#include <gtest/gtest.h>\n#include <aikido/common/PseudoInverse.hpp>\n\nusing namespace aikido::common;\n\nTEST(PseudoInverse, Invertible)\n{\n  Eigen::Matrix2d mat;\n  mat.setIdentity();\n  Eigen::Matrix2d inverse = pseudoinverse(mat);\n\n  EXPECT_TRUE((inverse * mat).isApprox(Eigen::Matrix2d::Identity()));\n}\n\nTEST(PseudoInverse, Vector)\n{\n  Eigen::Vector2d vec(1, 1);\n\n  Eigen::MatrixXd inverse = pseudoinverse(vec);\n\n  EXPECT_DOUBLE_EQ((inverse * vec)(0, 0), 1);\n}\n\nTEST(PseudoInverse, Matrix)\n{\n  Eigen::MatrixXd mat(Eigen::MatrixXd::Random(3, 4));\n  Eigen::MatrixXd inverse = pseudoinverse(mat);\n\n  EXPECT_TRUE((mat * inverse).isApprox(Eigen::Matrix3d::Identity()));\n}\n", "meta": {"hexsha": "db7b9fad8a529292e2d8f2ab9a5d408ecffe591a", "size": 688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/common/test_PseudoInverse.cpp", "max_stars_repo_name": "usc-csci-545/aikido", "max_stars_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/common/test_PseudoInverse.cpp", "max_issues_repo_name": "usc-csci-545/aikido", "max_issues_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/common/test_PseudoInverse.cpp", "max_forks_repo_name": "usc-csci-545/aikido", "max_forks_repo_head_hexsha": "afd8b203c17cb0b05d7db436f8bffbbe2111a75a", "max_forks_repo_licenses": ["BSD-3-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.5, "max_line_length": 69, "alphanum_fraction": 0.7136627907, "num_tokens": 193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6254351873590913}}
{"text": "#include <stan/math/prim/mat.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\nusing Eigen::VectorXd;\n\nTEST(ProbDistributions,Dirichlet) {\n  Matrix<double,Dynamic,1> theta(3,1);\n  theta << 0.2, 0.3, 0.5;\n  Matrix<double,Dynamic,1> alpha(3,1);\n  alpha << 1.0, 1.0, 1.0;\n  EXPECT_FLOAT_EQ(0.6931472, stan::math::dirichlet_log(theta,alpha));\n  \n  Matrix<double,Dynamic,1> theta2(4,1);\n  theta2 << 0.01, 0.01, 0.8, 0.18;\n  Matrix<double,Dynamic,1> alpha2(4,1);\n  alpha2 << 10.5, 11.5, 19.3, 5.1;\n  EXPECT_FLOAT_EQ(-43.40045, stan::math::dirichlet_log(theta2,alpha2));\n}\n\nTEST(ProbDistributions,DirichletPropto) {\n  Matrix<double,Dynamic,1> theta(3,1);\n  theta << 0.2, 0.3, 0.5;\n  Matrix<double,Dynamic,1> alpha(3,1);\n  alpha << 1.0, 1.0, 1.0;\n  EXPECT_FLOAT_EQ(0.0, stan::math::dirichlet_log<true>(theta,alpha));\n  \n  Matrix<double,Dynamic,1> theta2(4,1);\n  theta2 << 0.01, 0.01, 0.8, 0.18;\n  Matrix<double,Dynamic,1> alpha2(4,1);\n  alpha2 << 10.5, 11.5, 19.3, 5.1;\n  EXPECT_FLOAT_EQ(0.0, stan::math::dirichlet_log<true>(theta2,alpha2));\n}\n\nTEST(ProbDistributions,DirichletBounds) {\n  Matrix<double,Dynamic,1> good_alpha(2,1), bad_alpha(2,1);\n  Matrix<double,Dynamic,1> good_theta(2,1), bad_theta(2,1);\n\n  good_theta << 0.25, 0.75;\n  good_alpha << 2, 3;\n  EXPECT_NO_THROW(stan::math::dirichlet_log(good_theta,good_alpha));\n\n  good_theta << 1.0, 0.0;\n  good_alpha << 2, 3;\n  EXPECT_NO_THROW(stan::math::dirichlet_log(good_theta,good_alpha))\n    << \"elements of theta can be 0\";\n\n\n  bad_theta << 0.25, 0.25;\n  EXPECT_THROW(stan::math::dirichlet_log(bad_theta,good_alpha),\n               std::domain_error)\n    << \"sum of theta is not 1\";\n\n  bad_theta << -0.25, 1.25;\n  EXPECT_THROW(stan::math::dirichlet_log(bad_theta,good_alpha),\n               std::domain_error)\n    << \"theta has element less than 0\";\n\n  bad_theta << -0.25, 1.25;\n  EXPECT_THROW(stan::math::dirichlet_log(bad_theta,good_alpha),\n               std::domain_error)\n    << \"theta has element less than 0\";\n\n  bad_alpha << 0.0, 1.0;\n  EXPECT_THROW(stan::math::dirichlet_log(good_theta,bad_alpha),\n               std::domain_error)\n    << \"alpha has element equal to 0\";\n\n  bad_alpha << -0.5, 1.0;\n  EXPECT_THROW(stan::math::dirichlet_log(good_theta,bad_alpha),\n               std::domain_error)\n    << \"alpha has element less than 0\";\n\n  bad_alpha = Matrix<double,Dynamic,1>(4,1);\n  bad_alpha << 1, 2, 3, 4;\n  EXPECT_THROW(stan::math::dirichlet_log(good_theta,bad_alpha),\n               std::invalid_argument)\n    << \"size mismatch: theta is a 2-vector, alpha is a 4-vector\";\n}\n\ndouble chi_square(std::vector<int> bin, std::vector<double> expect) {\n  double chi = 0;\n  for (size_t j = 0; j < bin.size(); j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n  return chi;\n}\n\nvoid test_dirichlet3_1(VectorXd alpha) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n\n  // bins 0 vs. 1 + 2\n  boost::math::beta_distribution<> dist(alpha(0), alpha(1) + alpha(2));\n  boost::math::chi_squared mydist(K - 1);\n\n  std::vector<double> loc(K - 1);\n  for (int i = 1; i < K; i++)\n    loc[i - 1] = quantile(dist, i / static_cast<double>(K));\n\n  std::vector<int> bin(K, 0);\n  std::vector<double> expect(K, N / static_cast<double>(K));\n\n  for (int count = 0; count < N; ++count) {\n    Eigen::VectorXd theta = stan::math::dirichlet_rng(alpha,rng);\n    int i;\n    for (i = 0; i < K-1 && theta(0) > loc[i]; ++i) ;\n    ++bin[i];\n  }\n  EXPECT_TRUE(chi_square(bin,expect) < quantile(complement(mydist, 1e-6)));  \n}\n\nvoid test_dirichlet3_2(VectorXd alpha) {\n  boost::random::mt19937 rng;\n  int N = 10000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::beta_distribution<> dist(alpha(1), alpha(0) + alpha(2));\n  boost::math::chi_squared mydist(K - 1);\n\n  std::vector<double> loc(K - 1);\n  for(size_t i = 0; i < loc.size(); i++)\n    loc[i] = quantile(dist, (i + 1.0) / K);\n\n\n  std::vector<int> bin(K, 0);\n  std::vector<double> expect(K);\n  for (int i = 0 ; i < K; i++)\n    expect[i] = N / K;\n\n  for (int count = 0; count < N; ++count) {\n    VectorXd a = stan::math::dirichlet_rng(alpha,rng);\n    int i = 0;\n    while (i < K-1 && a(1) > loc[i]) \n      ++i;\n    ++bin[i];\n   }\n\n  EXPECT_TRUE(chi_square(bin, expect) < quantile(complement(mydist, 1e-6)));\n}\n\n\n\nTEST(ProbDistributionsDirichlet, rngTest) {\n  VectorXd alpha(3);\n  alpha << 2.0, 3.0, 11.0;\n  test_dirichlet3_1(alpha);\n  test_dirichlet3_2(alpha);\n\n  VectorXd beta(3);\n  beta << 0.1, 0.01, 0.2;\n  test_dirichlet3_1(beta);\n  test_dirichlet3_2(beta);\n}\n\nTEST(ProbDistributionsDirichlet, random) {\n  boost::random::mt19937 rng;\n  VectorXd alpha(3);\n  alpha << 2.0, 3.0, 11.0;\n  EXPECT_NO_THROW(stan::math::dirichlet_rng(alpha, rng));\n\n  VectorXd beta(3);\n  beta << 0.001, 0.0001, 1e-10;\n  EXPECT_NO_THROW(stan::math::dirichlet_rng(beta, rng));\n}\n", "meta": {"hexsha": "a3e983e9fa23b1904e6ea71377b25ac5df9f3040", "size": 4935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/dirichlet_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/dirichlet_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/mat/prob/dirichlet_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.375, "max_line_length": 77, "alphanum_fraction": 0.6362715299, "num_tokens": 1773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6254351829664034}}
{"text": "#include <boost/graph/adjacency_matrix.hpp>\n#include <array>\n#include <utility>\n\nint main()\n{\n  enum { topLeft, topRight, bottomRight, bottomLeft };\n\n  std::array<std::pair<int, int>, 4> edges{{\n    std::make_pair(topLeft, topRight),\n    std::make_pair(topRight, bottomRight),\n    std::make_pair(bottomRight, bottomLeft),\n    std::make_pair(bottomLeft, topLeft)\n  }};\n\n  typedef boost::adjacency_matrix<boost::undirectedS> graph;\n  graph g{edges.begin(), edges.end(), 4};\n}", "meta": {"hexsha": "26f0b139794fd961adc03b49fbb6648122fe04e8", "size": 473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Example/graph_15/main.cpp", "max_stars_repo_name": "KwangjoJeong/Boost", "max_stars_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_stars_repo_licenses": ["MIT"], "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/graph_15/main.cpp", "max_issues_repo_name": "KwangjoJeong/Boost", "max_issues_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_issues_repo_licenses": ["MIT"], "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/graph_15/main.cpp", "max_forks_repo_name": "KwangjoJeong/Boost", "max_forks_repo_head_hexsha": "29c4e2422feded66a689e3aef73086c5cf95b6fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2777777778, "max_line_length": 60, "alphanum_fraction": 0.6976744186, "num_tokens": 128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6254351724915169}}
{"text": "/// @file raster_example1.cc\n/// @brief raster example\n/// @author Jeff Perry <jeffsp@gmail.com>\n/// @version 1.0\n/// @date 2013-01-14\n\n#include \"jack_rabbit/jack_rabbit.h\"\n#include <algorithm>\n#include <boost/lambda/lambda.hpp>\n#include <cmath>\n#include <complex>\n#include <fstream>\n#include <iostream>\n\nusing namespace boost::lambda;\nusing namespace jack_rabbit;\nusing namespace std;\n\n// Affine transformation helper\nclass Affine\n{\n    public:\n    Affine ()\n        : t_ (0), s_ (1)\n    { }\n    // Translate by 't' and scale by 's'\n    Affine (float t, float s)\n        : t_ (t), s_ (s)\n    { }\n    float To (size_t x) const\n    { return t_ + x * s_; }\n    size_t From (float x) const\n    { return static_cast<int> ((x - t_) / s_); }\n    private:\n    float t_, s_;\n};\n\n// Mandelbrot function object:\n// Map the Mandelbrot set onto a raster\ntemplate<typename T>\nclass Mandelbrot\n{\n    public:\n    Mandelbrot (size_t /*r*/, size_t /*c*/) { }\n    // Define coordinate mapping\n    void CoordMap (const Affine &ax, const Affine &ay)\n    { ax_ = ax; ay_ = ay; }\n    // Remap coordinate (r, c), and then determine if it's\n    // in the set or not.\n    T operator() (size_t r, size_t c) const\n    {\n        // Remap x and y\n        complex<float> z (ax_.To (c), ay_.To (r));\n        complex<float> k (z);\n        size_t count = 0;\n        // Iterate until we are kindof sure that the point\n        // is in the set, or until the point is sure to\n        // shoot off to infinity...\n        while (++count != ITER)\n        {\n            z = z * z + k;\n            if (norm (z) > 4.0)\n                // ... definitely not in the set\n                return OUT;\n        }\n        // ... probably in the set.\n        return IN;\n    }\n    private:\n    static const size_t ITER = 500;\n    static const T IN = 0;\n    static const T OUT = 255;\n    Affine ax_, ay_;\n};\n\n// PGM file writer helper\ntemplate<class T>\nvoid WritePGM (const T &m, ofstream &ofs)\n{\n    // Write a pgm header\n    ofs << \"P5\\n\"\n        << \"# Raster Example\\n\"\n        << m.cols () << ' ' << m.rows () << '\\n'\n        << \"255\\n\";\n\n    // Transform to a vector of chars\n    vector<char> mm (m.begin (), m.end ());\n\n    // Write the pgm pixels\n    const std::streamsize sz =\n        static_cast<std::streamsize> (mm.size ());\n    ofs.write (&mm[0], sz);\n}\n\nint main ()\n{\n    try\n    {\n        const size_t M = 256;\n        const size_t N = 256;\n\n        clog << \"Generating a \" << M << \"X\" << N\n            << \" image...\" << endl;\n\n        typedef raster<int> Image;\n\n        // Some matrices that will contain our images\n        Image m0 (M, N);\n        Image m1 (M / 3, N / 3);\n\n        // Our Mandelbrot functions\n        subscript_generator<Image::value_type,Mandelbrot>\n        mandel0 (m0.rows (), m0.cols ());\n        Affine ax0 (-2.2f, 3.0f / m0.rows ());\n        Affine ay0 (-1.7f, 3.0f / m0.rows ());\n        mandel0.CoordMap (ax0, ay0);\n\n        subscript_generator<Image::value_type,Mandelbrot>\n        mandel1 (m1.rows (), m1.cols ());\n        Affine ax1 (-0.28f, 0.30f / m1.rows ());\n        Affine ay1 (-0.92f, 0.30f / m1.rows ());\n        mandel1.CoordMap (ax1, ay1);\n\n        // Create the main image\n        generate (m0.begin (), m0.end (), mandel0);\n\n        // Lower contrast of the region to zoom\n        size_t r1 = ay0.From (ay1.To (0));\n        size_t c1 = ax0.From (ax1.To (0));\n        size_t r2 = ay0.From (ay1.To (m1.rows ()));\n        size_t c2 = ax0.From (ax1.To (m1.cols ()));\n        subregion s0 = m0.sub (\n            static_cast<int> (r1), static_cast<int> (c1),\n            r2 - r1, c2 - c1);\n        for_each (m0.begin (s0), m0.end (s0),\n            _1 = (_1 - 127) / 2 + 127);\n\n        // Create the zoomed image\n        generate (m1.begin (), m1.end (), mandel1);\n        // Copy the zoomed image to the main image...\n        subregion s1 = { m0.rows () / 9, m0.rows () / 9,\n            m1.rows (), m1.cols () };\n        copy (m1.begin (), m1.end (), m0.begin (s1));\n\n        // Lower contrast of the zoomed image\n        transform (m0.begin (s1), m0.end (s1), m0.begin (s1),\n            (_1 - 127) / 2 + 127);\n\n        // Save the image to a file\n        const string fn (\"raster_example1.pgm\");\n        clog << \"Writing image to \" << fn << \"...\" << endl;\n\n        ofstream ofs (fn.c_str ());\n        if (!ofs)\n            throw std::runtime_error (\"Could not open file for writing\");\n\n        WritePGM (m0, ofs);\n\n        return 0;\n    }\n    catch (const exception &e)\n    {\n        cerr << e.what () << endl;\n        return -1;\n    }\n}\n", "meta": {"hexsha": "2af6038cbc4b2f225358713c9d0c7093f77f9872", "size": 4536, "ext": "cc", "lang": "C++", "max_stars_repo_path": "jsp/rcm_denoising/jack_rabbit/examples/raster_example1.cc", "max_stars_repo_name": "jeffsp/kaggle_denoising", "max_stars_repo_head_hexsha": "ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-06-04T14:34:01.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-04T14:34:01.000Z", "max_issues_repo_path": "jsp/rcm_denoising/jack_rabbit/examples/raster_example1.cc", "max_issues_repo_name": "jeffsp/kaggle_denoising", "max_issues_repo_head_hexsha": "ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jsp/rcm_denoising/jack_rabbit/examples/raster_example1.cc", "max_forks_repo_name": "jeffsp/kaggle_denoising", "max_forks_repo_head_hexsha": "ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27", "max_forks_repo_licenses": ["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.1616766467, "max_line_length": 73, "alphanum_fraction": 0.5271164021, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6253987009228172}}
{"text": "#include <test/unit/math/prim/prob/hmm_util.hpp>\n#include <stan/math/prim/prob/hmm_hidden_state_prob.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/random.hpp>\n#include <test/unit/math/test_ad.hpp>\n#include <test/unit/util.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <vector>\n\nTEST_F(hmm_test, hidden_state_single_outcome) {\n  using stan::math::hmm_hidden_state_prob;\n\n  int n_states = 2;\n  Eigen::MatrixXd Gamma(n_states, n_states);\n  Gamma << 1, 0, 1, 0;\n  Eigen::VectorXd rho(n_states);\n  rho << 1, 0;\n\n  Eigen::MatrixXd prob = hmm_hidden_state_prob(log_omegas_, Gamma, rho);\n\n  for (int i = 0; i < n_transitions_; i++) {\n    EXPECT_EQ(prob(0, i), 1);\n    EXPECT_EQ(prob(1, i), 0);\n  }\n}\n\nTEST_F(hmm_test, hidden_state_identity_transition) {\n  // With an identity transition matrix, all latent probabilities\n  // are equal. Setting the log density to 1 for all states makes\n  // the initial prob drive the subsequent probabilities.\n  using stan::math::hmm_hidden_state_prob;\n  int n_states = 2;\n  Eigen::MatrixXd Gamma = Eigen::MatrixXd::Identity(n_states, n_states);\n  Eigen::MatrixXd log_omegas\n      = Eigen::MatrixXd::Ones(n_states, n_transitions_ + 1);\n\n  Eigen::MatrixXd prob = hmm_hidden_state_prob(log_omegas, Gamma, rho_);\n\n  for (int i = 0; i < n_transitions_; i++) {\n    EXPECT_FLOAT_EQ(prob(0, i), rho_(0));\n    EXPECT_FLOAT_EQ(prob(1, i), rho_(1));\n  }\n}\n\nTEST(hmm_test_nonstandard, hidden_state_symmetry) {\n  // In this two states situation, the latent states are\n  // symmetric, based on the observational log density,\n  // and transition matrix.\n  // The initial conditions introduces an asymmetry in the first\n  // state. The other hidden states all have probability 0.5.\n  using stan::math::hmm_hidden_state_prob;\n  int n_states = 2;\n  int n_transitions = 2;\n  Eigen::MatrixXd Gamma(n_states, n_states);\n  Gamma << 0.5, 0.5, 0.5, 0.5;\n  Eigen::VectorXd rho(n_states);\n  rho << 0.3, 0.7;\n  Eigen::MatrixXd log_omegas\n      = Eigen::MatrixXd::Ones(n_states, n_transitions + 1);\n\n  Eigen::MatrixXd prob = hmm_hidden_state_prob(log_omegas, Gamma, rho);\n\n  EXPECT_FLOAT_EQ(prob(0, 0), 0.3);\n  EXPECT_FLOAT_EQ(prob(1, 0), 0.7);\n\n  for (int i = 1; i < n_transitions; i++) {\n    EXPECT_FLOAT_EQ(prob(0, i), 0.5);\n    EXPECT_FLOAT_EQ(prob(1, i), 0.5);\n  }\n}\n", "meta": {"hexsha": "747784ab5b957fb704c27ddce94669aad2cc176a", "size": 2297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/prob/hmm_hidden_state_prob_test.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "test/unit/math/prim/prob/hmm_hidden_state_prob_test.cpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/prim/prob/hmm_hidden_state_prob_test.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 31.9027777778, "max_line_length": 72, "alphanum_fraction": 0.7013495864, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6253987009228172}}
{"text": "/*\n * Tools.cpp\n *\n *  Created on: Apr 22, 2014\n *      Author: wilfeli\n */\n\n#include <vector>\n#include <math.h>\n#include <algorithm>\n#include <iterator>\n#include <Eigen/Dense>\n#include <iostream>\n#include \"Tools.h\"\n\nusing Eigen::MatrixXd;\nusing std::vector;\n\nnamespace Tools{\n\nvoid\nmgrid(MatrixXd grid, MatrixXd* meshgrid){\n\t//creates meshgrid from vector of points\n\t//define number of steps for each input\n\tlong N_rows = grid.rows();\n\tint n_steps_i;\n\tdouble n_steps_i_int;\n\tint j_val;\n\n\tdouble val;\n\tvector<int> n_steps;\n\tvector<int> ac_n_steps;\n\tvector<vector<double>> values;\n\tvector<double> values_temp;\n\tac_n_steps.push_back(1);\n\n\n    //create list of values\n\tfor (int i=0; i < N_rows; i++){\n\t\t//n_steps\n\t\tn_steps_i_int = (grid(i,1) - grid(i,0))/grid(i,2);\n\n\t\tn_steps_i = static_cast<int>(floor(n_steps_i_int)) + 1;\n\t\tn_steps.push_back(n_steps_i);\n\t\tac_n_steps.push_back(ac_n_steps.back() * n_steps_i);\n        \n\t\tfor (int j=0; j<n_steps_i; j++){\n\t\t\tval = grid(i,0) + grid(i,2)*j;\n\t\t\tvalues_temp.push_back(val);\n\t\t};\n\n\t\tvalues.push_back(values_temp);\n\t\tvalues_temp.clear();\n\t};\n\n\n\t//create matrix and fill it with values\n\t(*meshgrid) = MatrixXd::Zero(N_rows, ac_n_steps.back());\n\n\tint step_length = ac_n_steps.back();\n\tfor (int i = 0; i < N_rows; i++){\n\t\tstep_length = step_length / n_steps[i];\n\t\tfor (int j = 0; j < ac_n_steps.back(); j++){\n\t\t\tj_val = ((int)(j/step_length))%n_steps[i];\n\t\t\t(*meshgrid)(i,j) = values[i][j_val];\n\n\t\t};\n\t};\n\n//\tstd::cout << (*meshgrid).transpose() << \"\\n\";\n\n};\n    \nvoid\nmgrid_test(MatrixXd grid, MatrixXd* meshgrid){\n    //creates meshgrid from vector of points\n    //reverse to correspond to python\n    long N_rows = grid.rows();\n    int n_steps_i;\n    double n_steps_i_int;\n    int j_val;\n    \n    double val;\n    vector<int> n_steps;\n    vector<int> ac_n_steps;\n    vector<vector<double>> values;\n    vector<double> values_temp;\n    ac_n_steps.push_back(1);\n    \n    \n    \n    for (int i=0; i < N_rows; i++){\n        //n_steps\n        n_steps_i_int = (grid(i,1) - grid(i,0))/grid(i,2);\n        \n        n_steps_i = static_cast<int>(floor(n_steps_i_int)) + 1;\n        n_steps.push_back(n_steps_i);\n        ac_n_steps.push_back(ac_n_steps.back() * n_steps_i);\n        \n        for (int j=0; j<n_steps_i; j++){\n            val = grid(i,0) + grid(i,2)*j;\n            values_temp.push_back(val);\n        };\n        \n        values.push_back(values_temp);\n        values_temp.clear();\n    };\n    \n    \n    //create matrix and fill it with values\n    (*meshgrid) = MatrixXd::Zero(N_rows, ac_n_steps.back());\n    \n    int step_length = 1;\n    for (int i = 0; i < N_rows; i++){\n        \n        for (int j = 0; j < ac_n_steps.back(); j++){\n            j_val = ((int)(j/step_length))%n_steps[i];\n            (*meshgrid)(i,j) = values[i][j_val];\n            \n        };\n        step_length = step_length * n_steps[i];\n    };\n    \n//    std::cout << (*meshgrid).transpose() << \"\\n\";\n    \n};\n    \n\n\n\n\nvoid\nprint_vector(std::vector<double> vec){\n\t//print all q\n\tfor (auto iter:vec){\n\t\tstd::cout << iter << \" \";\n\t};\n    \n    std::cout << std::endl;\n};\n    \nvoid\nprint_vector(std::vector<std::vector<double>> vec){\n    //print all q\n    for (auto iter:vec){\n        print_vector(iter);\n    };\n    \n};\n    \n    \n\nMyRNG::MyRNG(double seed_):state(seed_){\n    m_w = seed_;\n};\n    \n// Produce a uniform random sample from the open interval (0, 1).\n// The method will not return either end point.\ndouble\nMyRNG::GetUniform(){\n    // 0 <= u < 2^32\n\tuint64_t u = GetUint();\n    // The magic number below is 1/(2^32 + 2).\n    // The result is strictly between 0 and 1.\n    return (u + 1.0) * 2.328306435454494e-10;\n};\n    \n// This is the heart of the generator.\n// It uses George Marsaglia's MWC algorithm to produce an unsigned integer.\n// See http://www.bobwheeler.com/statistics/Password/MarsagliaPost.txt\n\nuint64_t\nMyRNG::GetUint(){\n    m_z = 36969 * (m_z & 65535) + (m_z >> 16);\n    m_w = 18000 * (m_w & 65535) + (m_w >> 16);\n    return (m_z << 16) + m_w;\n};\n\n    \n    \ndouble\nget_normal(double mean, double sigma, MyRNG& rng){\n    if(rng.hasSpare)\n\t{\n\t\trng.hasSpare = false;\n\t\treturn sigma * sqrt(rng.rn1) * sin(rng.rn2) + mean;\n\t}\n    \n\trng.hasSpare = true;\n    \n\trng.rn1 = rng.GetUniform();\n\tif(rng.rn1 < 1e-100) {rng.rn1 = 1e-100;};\n\trng.rn1 = -2 * log(rng.rn1);\n\trng.rn2 = rng.GetUniform() * M_PI * 2;\n    \n\treturn sigma*sqrt(rng.rn1) * cos(rng.rn2) + mean;\n    \n\n        \n};\n    \nint\nget_int(int min, int max, MyRNG& rng){\n\tuint64_t x_raw = rng.GetUint();\n    //clean state of rng to simplify code\n    rng.hasSpare = false;\n    \n    int x = min + (x_raw % (int)(max - min + 1));\n    \n    return x;\n    \n    \n};\n\n};\n", "meta": {"hexsha": "6b3b5bc4a229046c2173d796d4050772807d98a5", "size": 4642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Tools.cpp", "max_stars_repo_name": "wilfeli/DMGameBasic", "max_stars_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T23:12:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T08:54:19.000Z", "max_issues_repo_path": "src/Tools.cpp", "max_issues_repo_name": "wilfeli/DMGameBasic", "max_issues_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Tools.cpp", "max_forks_repo_name": "wilfeli/DMGameBasic", "max_forks_repo_head_hexsha": "ccc5e7ba08ee4e1959c60421692540cafb1faeed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-02T20:23:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-02T20:23:21.000Z", "avg_line_length": 21.4907407407, "max_line_length": 75, "alphanum_fraction": 0.5915553641, "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6253986987556939}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/Assign2D.hpp\"\n#include \"../util/DistanceFuncs.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../util/Munkres.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass Grid\n{\npublic:\n  using MatrixXd = Eigen::MatrixXd;\n  using VectorXd = Eigen::VectorXd;\n  using DataSet = FluidDataSet<std::string, double, 1>;\n\n  DataSet process(DataSet& in, index overSample = 1, index extent = 0,\n                  index axis = 0)\n  {\n    using namespace Eigen;\n    using namespace _impl;\n    using namespace std;\n\n    assert(in.dims() == 2);\n    index    N = in.size();\n    index    M = N * overSample;\n    ArrayXXd data = asEigen<Array>(in.getData());\n    double   xMin = data.col(0).minCoeff();\n    double   xMax = data.col(0).maxCoeff();\n    double   yMin = data.col(1).minCoeff();\n    double   yMax = data.col(1).maxCoeff();\n    double   area = (xMax - xMin) * (yMax - yMin);\n    double   size = static_cast<double>(N);\n    double   step = sqrt(area / M);\n    index    numCols, numRows;\n\n    if (area <= 0) return DataSet();\n\n    if (extent > 0)\n    {\n      numCols = (axis == 0) ? extent : lrint(ceil(size / extent));\n      numRows = (axis == 1) ? extent : lrint(ceil(size / extent));\n    }\n    else\n    {\n      numCols = lrint(ceil((xMax - xMin) / step));\n      numRows = lrint(ceil((yMax - yMin) / step));\n    }\n\n    ArrayXd colPos, rowPos;\n    if (extent > 0 && axis == 1)\n    {\n      rowPos = ArrayXidx::LinSpaced(M, 0, M - 1)\n                   .unaryExpr([&](const index x) { return x % numRows; })\n                   .cast<double>();\n      colPos = (ArrayXidx::LinSpaced(M, 0, M - 1) / numRows).cast<double>();\n    }\n    else\n    {\n      colPos = ArrayXidx::LinSpaced(M, 0, M - 1)\n                   .unaryExpr([&](const index x) { return x % numCols; })\n                   .cast<double>();\n      rowPos = (ArrayXidx::LinSpaced(M, 0, M - 1) / numCols).cast<double>();\n    }\n\n    ArrayXd  xPos = xMin + (colPos / (numCols - 1)) * (xMax - xMin);\n    ArrayXd  yPos = yMin + (rowPos / (numRows - 1)) * (yMax - yMin);\n    ArrayXXd grid(M, 2);\n    grid << xPos, yPos;\n    ArrayXXd cost = algorithm::DistanceMatrix<ArrayXXd>(data, grid, 1);\n    ArrayXidx  assignment(N);\n    bool     outcome = assign2D.process(cost, assignment);\n    if (!outcome) return DataSet();\n\n    DataSet    result(2);\n    auto       ids = in.getIds();\n    RealVector asignedPos(2);\n    for (index i = 0; i < N; i++)\n    {\n      asignedPos(0) = colPos(assignment(i));\n      asignedPos(1) = rowPos(assignment(i));\n      auto id = ids(i);\n      result.add(ids(i), asignedPos);\n    }\n    return result;\n  }\n\nprivate:\n  Assign2D assign2D;\n};\n}// namespace algorithm\n}// namespace fluid\n", "meta": {"hexsha": "f495da7af2e1d0540741d60d499f212edb2eece9", "size": 3189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/Grid.hpp", "max_stars_repo_name": "jamesb93/flucoma-core", "max_stars_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/algorithms/public/Grid.hpp", "max_issues_repo_name": "jamesb93/flucoma-core", "max_issues_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/algorithms/public/Grid.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5277777778, "max_line_length": 76, "alphanum_fraction": 0.6020696143, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383028, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.6253807432177793}}
{"text": "/******************************************************************************\n\n  This source file is part of the Avogadro project.\n\n  Copyright (C) 2010 Eric C. Brown\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************/\n\n#include \"qtaimmathutilities.h\"\n\n#include <cmath>\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n\nnamespace Avogadro {\nnamespace QtPlugins {\nnamespace QTAIMMathUtilities {\n\n  Matrix<qreal,3,1> eigenvaluesOfASymmetricThreeByThreeMatrix(const Matrix<qreal,3,3> &A)\n  {\n    SelfAdjointEigenSolver<Matrix<qreal, 3, 3> > eigensolver(A);\n    return eigensolver.eigenvalues();\n  }\n\n  Matrix<qreal,3,3> eigenvectorsOfASymmetricThreeByThreeMatrix(const Matrix<qreal,3,3> &A)\n  {\n    SelfAdjointEigenSolver<Matrix<qreal, 3, 3> > eigensolver(A);\n    return eigensolver.eigenvectors();\n  }\n\n  Matrix<qreal,4,1> eigenvaluesOfASymmetricFourByFourMatrix(const Matrix<qreal,4,4> &A)\n  {\n    SelfAdjointEigenSolver<Matrix<qreal, 4, 4> > eigensolver(A);\n    return eigensolver.eigenvalues();\n  }\n\n  Matrix<qreal,4,4> eigenvectorsOfASymmetricFourByFourMatrix(const Matrix<qreal,4,4> &A)\n  {\n    SelfAdjointEigenSolver<Matrix<qreal, 4, 4> > eigensolver(A);\n    return eigensolver.eigenvectors();\n  }\n\n  qint64 signOfARealNumber(qreal x)\n  {\n    if (x > 0.)\n      return  1;\n    else if (x == 0.)\n      return  0;\n    else\n      return -1;\n  }\n\n  qint64 signatureOfASymmetricThreeByThreeMatrix(const Matrix<qreal,3,3> &A)\n  {\n    SelfAdjointEigenSolver<Matrix<qreal, 3, 3> > eigensolver(A);\n    Matrix<qreal,3,1> eigenvalues=eigensolver.eigenvalues();\n\n    return signOfARealNumber(eigenvalues(0)) +\n        signOfARealNumber(eigenvalues(1)) +\n        signOfARealNumber(eigenvalues(2));\n  }\n\n  qreal ellipticityOfASymmetricThreeByThreeMatrix(const Matrix<qreal,3,3> &A)\n  {\n    SelfAdjointEigenSolver<Matrix<qreal, 3, 3> > eigensolver(A);\n    Matrix<qreal, 3, 1> eigenvalues=eigensolver.eigenvalues();\n\n    return (eigenvalues(0) / eigenvalues(1)) - 1.0 ;\n  }\n\n  qreal distance(const Matrix<qreal, 3, 1> &a, const Matrix<qreal, 3, 1> &b)\n  {\n    return sqrt(pow(a(0) - b(0), 2) +\n                pow(a(1) - b(1), 2) +\n                pow(a(2) - b(2), 2));\n  }\n\n  Matrix<qreal,3,1> sphericalToCartesian(const Matrix<qreal,3,1> &rtp,\n                                         const Matrix<qreal,3,1> &x0y0z0)\n  {\n    qreal r=rtp(0);\n    qreal theta=rtp(1);\n    qreal phi=rtp(2);\n\n    qreal x0=x0y0z0(0);\n    qreal y0=x0y0z0(1);\n    qreal z0=x0y0z0(2);\n\n    qreal costheta = cos(theta);\n    qreal cosphi   = cos(phi);\n    qreal sintheta = sin(theta);\n    qreal sinphi   = sin(phi);\n\n    Matrix<qreal, 3, 1> xyz(r * cosphi * sintheta + x0,\n                            r * sintheta * sinphi + y0,\n                            r * costheta          + z0);\n\n    return xyz;\n  }\n\n  Matrix<qreal, 3, 1> sphericalToCartesian(const Matrix<qreal, 3, 1> &rtp)\n  {\n    Matrix<qreal, 3, 1> x0y0z0(0., 0., 0.);\n\n    return  sphericalToCartesian(rtp, x0y0z0);\n  }\n\n  Matrix<qreal,3,1> cartesianToSpherical(const Matrix<qreal, 3, 1> &xyz,\n                                         const Matrix<qreal, 3, 1> &x0y0z0 )\n  {\n    qreal x=xyz(0);\n    qreal y=xyz(1);\n    qreal z=xyz(2);\n\n    qreal x0=x0y0z0(0);\n    qreal y0=x0y0z0(1);\n    qreal z0=x0y0z0(2);\n\n    qreal xshift = x - x0;\n    qreal yshift = y - y0;\n    qreal zshift = z - z0;\n\n    qreal length = sqrt(pow(xshift, 2) + pow(yshift, 2) + pow(zshift, 2));\n\n    Matrix<qreal, 3, 1> rtp;\n\n    if (length == 0.)\n      rtp << x0, y0, z0 ;\n    else if (xshift == 0. && yshift == 0.)\n      rtp << length, acos(zshift / length), 0.;\n    else\n      rtp << length, acos(zshift / length), atan2(xshift, yshift);\n\n    return rtp;\n  }\n\n  Matrix<qreal, 3, 1> cartesianToSpherical(const Matrix<qreal, 3, 1> &xyz)\n  {\n    Matrix<qreal, 3, 1> x0y0z0(0., 0., 0.);\n\n    return  cartesianToSpherical(xyz, x0y0z0);\n  }\n\n\n  // Cerjan-Miller-Baker-Popelier Methods\n  //\n  // Based on:\n  // Popelier, P.L.A. Comput. Phys. Comm. 1996, 93, 212.\n\n  Matrix<qreal, 3, 1> minusThreeSignatureLocatorGradient(const Matrix<qreal, 3, 1> &g,\n                                                         const Matrix<qreal, 3, 3> &H)\n  {\n    Matrix<qreal, 3, 1> value;\n\n    Matrix<qreal, 3, 1> b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n    Matrix<qreal, 3, 3> U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n    Matrix<qreal, 3, 1> F = U.transpose() * g;\n\n    Matrix<qreal, 4, 4> A;\n    A <<  b(0), 0.  , 0.  , F(0),\n    0.  , b(1), 0.  , F(1),\n    0.  , 0.  , b(2), F(2),\n    F(0), F(1), F(2), 0.   ;\n\n    Matrix<qreal, 4, 1> eval = eigenvaluesOfASymmetricFourByFourMatrix(A);\n\n    Matrix<qreal, 3, 1> lambda;\n    lambda << eval(3), eval(3), eval(3);\n\n    Matrix<qreal, 3, 1> denom;\n    denom = b - lambda;\n\n    for (qint64 i=0; i < 3; ++i)\n      if( denom(i) < SMALL )\n        denom(i)=denom(i)+SMALL;\n\n    Matrix<qreal, 3, 1> h;\n    h << 0., 0., 0.;\n\n    for (qint64 j = 0; j < 3; ++j)\n      for (qint64 i = 0; i < 3; ++i)\n        h(j) = h(j) + ( -F(i) * U(j, i) ) / denom(i);\n\n    value = h;\n\n    return value;\n  }\n\n  Matrix<qreal, 3, 1> minusOneSignatureLocatorGradient(const Matrix<qreal, 3, 1> &g,\n                                                       const Matrix<qreal,3,3> &H)\n  {\n    Matrix<qreal, 3, 1> value;\n\n    Matrix<qreal, 3, 1> b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n    Matrix<qreal, 3, 3> U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n    Matrix<qreal, 3, 1> F = U.transpose() * g;\n\n    Matrix<qreal, 3, 3> A;\n    A <<  b(0), 0.  ,  F(0),\n    0.  , b(1),  F(1),\n    F(0), F(1),  0.   ;\n\n    Matrix<qreal, 3, 1> eval = eigenvaluesOfASymmetricThreeByThreeMatrix(A);\n\n    Matrix<qreal, 3, 1> lambda;\n    lambda << eval(2), eval(2), (0.5) * (b(2) - sqrt(pow(b(2), 2) + 4.0 * pow(F(2), 2)));\n\n    Matrix<qreal, 3, 1> denom;\n    denom = b - lambda;\n\n    for (qint64 i = 0; i < 3; ++i)\n      if (denom(i) < SMALL)\n        denom(i) = denom(i) + SMALL;\n\n    Matrix<qreal, 3, 1> h;\n    h << 0., 0., 0.;\n\n    for (qint64 j = 0; j < 3; ++j)\n      for (qint64 i = 0; i < 3; ++i)\n        h(j) = h(j) + (-F(i) * U(j,i)) / denom(i);\n\n    value = h;\n\n    return value;\n  }\n\n  Matrix<qreal, 3, 1> plusOneSignatureLocatorGradient(const Matrix<qreal, 3, 1> &g,\n                                                      const Matrix<qreal,3,3> &H)\n  {\n    Matrix<qreal, 3, 1> value;\n\n    Matrix<qreal, 3, 1> b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n    Matrix<qreal, 3, 3> U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n    Matrix<qreal, 3, 1> F = U * g;\n\n    Matrix<qreal, 3, 3> A;\n    A <<  b(1), 0.  ,  F(1),\n    0.  , b(2),  F(2),\n    F(1), F(2),  0.;\n\n    Matrix<qreal, 3, 1> eval = eigenvaluesOfASymmetricThreeByThreeMatrix(A);\n\n    Matrix<qreal, 3, 1> lambda;\n    lambda << eval(2), eval(2), (0.5) * (b(0) + sqrt(pow(b(0), 2) + 4.0 * pow(F(0), 2)));\n\n    Matrix<qreal, 3, 1> denom;\n    denom = b - lambda;\n\n    for (qint64 i = 0; i < 3; ++i)\n      if (denom(i) < SMALL)\n        denom(i) = denom(i) + SMALL;\n\n    Matrix<qreal, 3, 1> h;\n    h << 0., 0., 0.;\n\n    for (qint64 j = 0; j < 3; ++j)\n      for (qint64 i = 0; i < 3; ++i)\n        h(j) = h(j) + (-F(i) * U(i, j)) / denom(i);\n\n    value = h;\n\n    return value;\n  }\n\n  Matrix<qreal,3,1> plusThreeSignatureLocatorGradient(const Matrix<qreal, 3, 1> &g,\n                                                      const Matrix<qreal, 3, 3> &H)\n  {\n    Matrix<qreal, 3, 1> value;\n\n    Matrix<qreal, 3, 1> b = eigenvaluesOfASymmetricThreeByThreeMatrix(H);\n    Matrix<qreal, 3, 3> U = eigenvectorsOfASymmetricThreeByThreeMatrix(H);\n\n    Matrix<qreal, 3, 1> F = U * g;\n\n    Matrix<qreal, 4, 4> A;\n    A <<  b(0), 0.  , 0.  , F(0),\n    0.  , b(1), 0.  , F(1),\n    0.  , 0.  , b(2), F(2),\n    F(0), F(1), F(2), 0.;\n\n    Matrix<qreal, 4, 1> eval = eigenvaluesOfASymmetricFourByFourMatrix(A);\n\n    Matrix<qreal, 3, 1> lambda;\n    lambda << eval(0), eval(0), eval(0);\n\n    Matrix<qreal, 3, 1> denom;\n    denom = b - lambda;\n\n    for (qint64 i = 0; i < 3; ++i)\n      if (denom(i) < SMALL)\n        denom(i) = denom(i) + SMALL;\n\n    Matrix<qreal, 3, 1> h;\n    h << 0., 0., 0.;\n\n    for (qint64 j = 0; j < 3; ++j)\n      for (qint64 i = 0; i < 3; ++i)\n        h(j) = h(j) + (-F(i) * U(i, j) ) / denom(i);\n\n    value = h;\n\n    return value;\n  }\n\n} // namespace QTAIMMathUtilities\n} // namespace QtPlugins\n} // namespace Avogadro\n", "meta": {"hexsha": "284d49d151390c585835c6a7c08bfbc691db8863", "size": 8727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "avogadro/qtplugins/qtaim/qtaimmathutilities.cpp", "max_stars_repo_name": "AlbertDeFusco/avogadrolibs", "max_stars_repo_head_hexsha": "572aad6d16295c91da684d180b6b2705070549c1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "avogadro/qtplugins/qtaim/qtaimmathutilities.cpp", "max_issues_repo_name": "AlbertDeFusco/avogadrolibs", "max_issues_repo_head_hexsha": "572aad6d16295c91da684d180b6b2705070549c1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "avogadro/qtplugins/qtaim/qtaimmathutilities.cpp", "max_forks_repo_name": "AlbertDeFusco/avogadrolibs", "max_forks_repo_head_hexsha": "572aad6d16295c91da684d180b6b2705070549c1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3573667712, "max_line_length": 90, "alphanum_fraction": 0.5541423169, "num_tokens": 3223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6253358382020187}}
{"text": "/*\n * Modulo_test.cpp\n *\n *  Created on: Sep 29, 2018\n *      Author: sergejkrivonos\n */\n#define BOOST_TEST_MODULE Modulo test\n#include <boost/test/unit_test.hpp>\n#include <omnn/math/Modulo.h>\n#include <omnn/math/Variable.h>\n\nusing namespace omnn::math;\nusing namespace boost::unit_test;\n\nBOOST_AUTO_TEST_CASE(Modulo_test)\n{\n    Variable va;\n    auto _ = (va + 5) / (va + 1);\n    auto p = (va + 5) % (va + 1);\n    BOOST_TEST(p == (4_v % (va + 1)));\n    p.Eval(va, 2);\n    p.optimize();\n    BOOST_TEST(7_v % 3 == p);\n}\n", "meta": {"hexsha": "1f44094bbd6f0ef2cfb813d6d9cd45164bece2de", "size": 518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/Modulo_test.cpp", "max_stars_repo_name": "ApusDT/openmind", "max_stars_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-25T06:47:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-25T06:47:44.000Z", "max_issues_repo_path": "omnn/math/test/Modulo_test.cpp", "max_issues_repo_name": "leannejdong/openmind", "max_issues_repo_head_hexsha": "69af704c420ffa89100ecd3709ad9ff39ee4da05", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "omnn/math/test/Modulo_test.cpp", "max_forks_repo_name": "leannejdong/openmind", "max_forks_repo_head_hexsha": "69af704c420ffa89100ecd3709ad9ff39ee4da05", "max_forks_repo_licenses": ["BSD-3-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.72, "max_line_length": 38, "alphanum_fraction": 0.6196911197, "num_tokens": 170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6253358235115111}}
{"text": "#include <cassert>\r\n#include <cmath>\r\n#include <complex>\r\n#include <vector>\r\n#include <Eigen/Core>\r\n\r\n#include \"Const.h\"\r\n#include \"Tract.h\"\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n\r\nTract::Tract(double c1, double dl, const double S[], int length) :\r\n\ta\t(130 * Const::pi),\r\n\tb\t(std::pow(30 * Const::pi, 2)),\r\n\tom0\t(pow(406 * Const::pi, 2)),\r\n\tc1\t(c1),\r\n\tdl\t(dl),\r\n\tS\t(length)\r\n{\r\n\tfor (int i = 0; i < length; i++)\r\n\t\tthis->S[i] = S[i];\r\n}\r\nTract::Tract(double c1, double dl, vector<double> &S) :\r\n\ta\t(130 * Const::pi),\r\n\tb\t(std::pow(30 * Const::pi, 2)),\r\n\tom0\t(pow(406 * Const::pi, 2)),\r\n\tc1\t(c1),\r\n\tdl\t(dl),\r\n\tS\t(S)\r\n{\r\n}\r\n\r\nTract::~Tract(void)\r\n{\r\n}\r\n\r\ncomplex<double> Tract::GetBeta(double f)\r\n{\r\n\tdouble omg = 2.0 * Const::pi * f;\r\n\tcomplex<double> s(0, omg);\r\n\treturn s * om0 / ((s + a) * s + b) + sqrt(s * c1);\r\n}\r\n\r\nvector<double> Tract::GetArea(void)\r\n{\r\n\treturn S;\r\n}\r\n\r\ndouble Tract::GetStartArea(void)\r\n{\r\n\treturn S.front();\r\n}\r\n\r\ndouble Tract::GetEndArea(void)\r\n{\r\n\treturn S.back();\r\n}\r\n\r\ndouble Tract::GetElemLength(void)\r\n{\r\n\treturn dl;\r\n}\r\n\r\nMatrix2cd Tract::ChainMatrix(double freq, int from)\r\n{\r\n\treturn ChainMatrix(freq, from, S.size() - 1);\r\n}\r\nMatrix2cd Tract::ChainMatrix(double freq, int from, int to)\r\n{\r\n\tdouble n = to - from + 1;\r\n\r\n\tdouble omg = 2.0 * Const::pi * freq;\r\n\tcomplex<double> s(0, omg);\r\n\r\n\tcomplex<double> loss = s * om0 / ((s + a) * s + b) + sqrt(s * c1);\r\n\tcomplex<double> gamma = sqrt((a + s) / (loss + s));\r\n\tcomplex<double> sigma = gamma * (loss + s) / Const::c;\r\n\r\n\tMatrix2cd r = Matrix2cd::Identity();\r\n\tcomplex<double> sh = sinh(sigma * dl);\r\n\tMatrix2cd K;\r\n    K(0, 0) = K(1, 1) = cosh(sigma * dl);\r\n\r\n    for (int i = 0; i < n; i++)\r\n    {\r\n        complex<double> coeff = -Const::rho * Const::c / S[from + i] * gamma;\r\n\r\n\t\tK(0, 1) = coeff * sh;\r\n        K(1, 0) = 1.0 / coeff * sh;\r\n\r\n        r = K * r;\r\n    }\r\n\r\n    return r;\r\n}\r\n", "meta": {"hexsha": "b1218913cb5a52790500098f195ca95b54d18772", "size": 1893, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Tract.cxx", "max_stars_repo_name": "kinoh/VoiceSynthesis", "max_stars_repo_head_hexsha": "4f9ce82c59419b0a54c38607521fa30fe3ad22af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T16:36:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-27T04:58:04.000Z", "max_issues_repo_path": "Tract.cxx", "max_issues_repo_name": "kinoh/VoiceSynthesis", "max_issues_repo_head_hexsha": "4f9ce82c59419b0a54c38607521fa30fe3ad22af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tract.cxx", "max_forks_repo_name": "kinoh/VoiceSynthesis", "max_forks_repo_head_hexsha": "4f9ce82c59419b0a54c38607521fa30fe3ad22af", "max_forks_repo_licenses": ["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.3163265306, "max_line_length": 78, "alphanum_fraction": 0.5499207607, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92522995296862, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6252376500187117}}
{"text": "\n// solving A * X = B\n// using driver function gesv()\n// with c_vector<> & c_matrix<> \n\n#include <cstddef>\n#include <iostream>\n#include <boost/numeric/bindings/lapack/driver/gesv.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/matrix_proxy.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/ublas/io.hpp> \n\nnamespace ublas = boost::numeric::ublas;\nnamespace bindings = boost::numeric::bindings;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef ublas::c_matrix<double, 4, 4> m4x4_t;\ntypedef ublas::c_matrix<double, 3, 3> m3x3_t;\ntypedef ublas::c_matrix<double, 2, 3> mrhs_t;\ntypedef ublas::c_vector<double, 5> v5_t; \n\nint main() {\n\n  cout << endl; \n  size_t n = 3;\n\n  m4x4_t a (n, n);   // system matrix \n  m4x4_t a_copy (n, n);   // system matrix \n\n//       [,1] [,2] [,3]\n//  [1,]    1    1    1\n//  [2,]    2    3    1\n//  [3,]    1   -1   -1\n\n  a(0,0) = 1.; a(0,1) = 1.; a(0,2) = 1.;\n  a(1,0) = 2.; a(1,1) = 3.; a(1,2) = 1.;\n  a(2,0) = 1.; a(2,1) = -1.; a(2,2) = -1.;\n  a_copy = a;\n\n  mrhs_t b (2, n);  // right-hand side matrix\n\n//          [,1] [,2]\n//     [1,]    4   10\n//     [2,]    9   11\n//     [3,]    2   12\n\n  b(0,0) =  4.;  b(1,0) = 10.;\n  b(0,1) =  9.;  b(1,1) = 11.;\n  b(0,2) = -2.;  b(1,2) = 12.;\n\n  m3x3_t a2; // for part 2\n  a2 = project (a, ublas::range (0,3), ublas::range (0,3)); \n  v5_t b2 (n); \n  b2 = row (b, 0);\n\n  // part 1:\n  cout << \"A: \" << a << endl; \n  cout << \"B: \" << ublas::trans(b) << endl; \n\n  std::vector< int > pivota( 100 );\n  lapack::gesv (a, pivota, bindings::trans(b));  \n\n  cout << \"X: \" << ublas::trans(b) << endl;\n  std::cout << \"---\" << std::endl;\n  cout << \"A: \" << a << endl; \n\n  cout << \"AX/B: \" << ublas::prod( a_copy, ublas::trans(b) ) << std::endl;\n\n  cout << endl; \n\n  // part 2:\n  cout << \"A: \" << a2 << endl; \n  cout << \"B: \" << b2 << endl; \n\n  std::vector< int > pivota2( 100 );\n lapack::gesv (a2, pivota2, b2);  \n  cout << \"X: \" << b2 << endl; \n\n  cout << endl; \n}\n\n", "meta": {"hexsha": "f6a93ab165656e9cc29ff1f901c52c1ab1135788", "size": 2163, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_gesv5.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_gesv5.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_gesv5.cc", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 24.3033707865, "max_line_length": 74, "alphanum_fraction": 0.5404530744, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.625086375855985}}
{"text": "#pragma once\n\n// Code adapted from https://github.com/propanoid/DBSCAN\n\n#include <vector>\n#include <algorithm>\n//#include <omp.h>\n\n// Any basic vector/matrix library should also work\n#include <Eigen/Core>\n\nnamespace clustering\n{\n\ttemplate<typename Vector, typename Matrix>\n\tclass DBSCAN\n\t{\n\tpublic:\n\t\ttypedef Vector FeaturesWeights;\n\t\ttypedef Matrix ClusterData;\n\t\ttypedef Matrix DistanceMatrix;\n\t\ttypedef std::vector<unsigned int> Neighbors;\n\t\ttypedef std::vector<int> Labels;\n\n\tprivate:\n\t\tdouble m_eps;\n\t\tsize_t m_min_elems;\n\t\tdouble m_dmin;\n\t\tdouble m_dmax;\n\n\t\tLabels m_labels;\n\n\tpublic:\n\n\t\t// 'eps' is the search space for neighbors in the range [0,1], where 0.0 is exactly self and 1.0 is entire dataset\n\t\tDBSCAN(double eps, size_t min_elems)\n\t\t\t: m_eps( eps )\n\t\t\t, m_min_elems( min_elems )\n\t\t\t, m_dmin(0.0)\n\t\t\t, m_dmax(0.0)\n\t\t{\n\t\t\treset();\n\t\t}\n\n\t\t// Call this to perform clustering, get results by calling 'get_labels()'\n\t\tvoid fit( const ClusterData & C )\n\t\t{\n\t\t\tconst FeaturesWeights W = std_weights( C.cols() );\n\t\t\twfit( C, W );\n\t\t}\n\n\t\tconst Labels & get_labels() const\n\t\t{\n\t\t\treturn m_labels;\n\t\t}\n\n\t\tvoid reset()\n\t\t{\n\t\t\tm_labels.clear();\n\t\t}\n\n\t\tvoid init(double eps, size_t min_elems)\n\t\t{\n\t\t\tm_eps = eps;\n\t\t\tm_min_elems = min_elems;\n\t\t}\n\n\t\t// Useful for testing\n\t\tstatic ClusterData gen_cluster_data( size_t features_num, size_t elements_num )\n\t\t{\n\t\t\tClusterData cl_d( elements_num, features_num );\n\t\t\tfor (size_t i = 0; i < elements_num; ++i)\n\t\t\t\tfor (size_t j = 0; j < features_num; ++j)\n\t\t\t\t\tcl_d(i, j) = (-1.0 + rand() * (2.0) / RAND_MAX);\n\t\t\treturn cl_d;\n\t\t}\n\n\t\tFeaturesWeights std_weights( size_t s )\n\t\t{\n\t\t\t// num cols\n\t\t\tFeaturesWeights ws( s );\n\n\t\t\tfor (size_t i = 0; i < s; ++i)\n\t\t\t\tws(i) = 1.0;\n\n\t\t\treturn ws;\n\t\t}\n\n\t\tvoid fit_precomputed( const DistanceMatrix & D )\n\t\t{\n\t\t\tprepare_labels( D.rows() );\n\t\t\tdbscan( D );\n\t\t}\n\n\t\tvoid wfit( const ClusterData & C, const FeaturesWeights & W )\n\t\t{\n\t\t\tprepare_labels( C.rows() );\n\t\t\tconst DistanceMatrix D = calc_dist_matrix( C, W );\n\t\t\tdbscan( D );\n\t\t}\n\n\tprivate:\n\t\tvoid prepare_labels( size_t s )\n\t\t{\n\t\t\tm_labels.resize(s, -1);\n\t\t}\n\n\t\tNeighbors find_neighbors(const DistanceMatrix & D, unsigned int pid)\n\t\t{\n\t\t\tNeighbors ne;\n\n\t\t\tfor (unsigned int j = 0; j < D.rows(); ++j)\n\t\t\t{\n\t\t\t\tif \t( D(pid, j) <= m_eps )\n\t\t\t\t{\n\t\t\t\t\tne.push_back(j);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ne;\n\t\t}\n\n\t\tconst DistanceMatrix calc_dist_matrix( const ClusterData & C, const FeaturesWeights & W )\n\t\t{\n\t\t\tClusterData cl_d = C;\n\n//#pragma omp parallel for\n\t\t\tfor (int i = 0; i < (int)cl_d.cols(); ++i)\n\t\t\t{\n\t\t\t\tauto col = cl_d.col(i);\n\n\t\t\t\tconst auto r = std::minmax_element( col.data(), col.data() + col.size() );\n\n\t\t\t\tdouble data_min = *r.first;\n\t\t\t\tdouble data_range = *r.second - *r.first;\n\n\t\t\t\tif (data_range == 0.0) { data_range = 1.0; }\n\n\t\t\t\tconst double scale = 1/data_range;\n\t\t\t\tconst double min = -1.0*data_min*scale;\n\n\t\t\t\tcol *= scale;\n\t\t\t\tcol += Vector::Constant(col.size(), min);\n\n\t\t\t\tcl_d.col(i) = col;\n\t\t\t}\n\n\t\t\t// rows x rows\n\t\t\tDistanceMatrix d_m( cl_d.rows(), cl_d.rows() );\n\t\t\tVector d_max( cl_d.rows() );\n\t\t\tVector d_min( cl_d.rows() );\n\n\t\t\tfor (int i = 0; i < (int)cl_d.rows(); ++i)\n\t\t\t{\n//#pragma omp parallel for\n\t\t\t\tfor (int j = i; j < (int)cl_d.rows(); ++j)\n\t\t\t\t{\n\t\t\t\t\td_m(i, j) = 0.0;\n\n\t\t\t\t\tif (i != j)\n\t\t\t\t\t{\n\t\t\t\t\t\tVector U = cl_d.row(i);\n\t\t\t\t\t\tVector V = cl_d.row(j);\n\n\t\t\t\t\t\tVector diff = ( U-V );\n\n\t\t\t\t\t\tfor(int k = 0; k < (int)diff.size(); k++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto e = diff[k];\n\t\t\t\t\t\t\td_m(i, j) += fabs(e)*W[k];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\td_m(j, i) = d_m(i, j);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst auto cur_row = d_m.row(i);\n\t\t\t\tconst auto mm = std::minmax_element( cur_row.data(), cur_row.data() + cur_row.size() );\n\n\t\t\t\td_max(i) = *mm.second;\n\t\t\t\td_min(i) = *mm.first;\n\t\t\t}\n\n\t\t\tm_dmin = *(std::min_element( d_min.data(), d_min.data() + d_min.size() ));\n\t\t\tm_dmax = *(std::max_element( d_max.data(), d_max.data() + d_max.size() ));\n\n\t\t\tm_eps = (m_dmax - m_dmin) * m_eps + m_dmin;\n\n\t\t\treturn d_m;\n\t\t}\n\n\t\tvoid dbscan( const DistanceMatrix & dm )\n\t\t{\n\t\t\tstd::vector<unsigned int> visited( dm.rows() );\n\n\t\t\tunsigned int cluster_id = 0;\n\n\t\t\tfor (unsigned int pid = 0; pid < dm.rows(); ++pid)\n\t\t\t{\n\t\t\t\tif ( !visited[pid] )\n\t\t\t\t{\n\t\t\t\t\tvisited[pid] = 1;\n\n\t\t\t\t\tNeighbors ne = find_neighbors(dm, pid );\n\n\t\t\t\t\tif (ne.size() >= m_min_elems)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_labels[pid] = cluster_id;\n\n\t\t\t\t\t\tfor (unsigned int i = 0; i < ne.size(); ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tunsigned int nPid = ne[i];\n\n\t\t\t\t\t\t\tif ( !visited[nPid] )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvisited[nPid] = 1;\n\n\t\t\t\t\t\t\t\tNeighbors ne1 = find_neighbors(dm, nPid);\n\n\t\t\t\t\t\t\t\tif ( ne1.size() >= m_min_elems )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfor (const auto & n1 : ne1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tne.push_back(n1);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( m_labels[nPid] == -1 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tm_labels[nPid] = cluster_id;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t++cluster_id;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n}\n", "meta": {"hexsha": "33feed59cbb0db04ef2c1e9b8190612245c55d2f", "size": 4817, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "hedcuter/code/DBSCAN.hpp", "max_stars_repo_name": "Yue-Hao/CS633", "max_stars_repo_head_hexsha": "01a3587454eceaa228834a1e0b091a031d985e7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hedcuter/code/DBSCAN.hpp", "max_issues_repo_name": "Yue-Hao/CS633", "max_issues_repo_head_hexsha": "01a3587454eceaa228834a1e0b091a031d985e7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hedcuter/code/DBSCAN.hpp", "max_forks_repo_name": "Yue-Hao/CS633", "max_forks_repo_head_hexsha": "01a3587454eceaa228834a1e0b091a031d985e7c", "max_forks_repo_licenses": ["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.0708333333, "max_line_length": 116, "alphanum_fraction": 0.5711023459, "num_tokens": 1538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6250863660630106}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nMatrixXcf a = MatrixXcf::Random(2,2);\ncout << \"Here is the matrix a\\n\" << a << endl;\n\ncout << \"Here is the matrix a^T\\n\" << a.transpose() << endl;\n\n\ncout << \"Here is the conjugate of a\\n\" << a.conjugate() << endl;\n\n\ncout << \"Here is the matrix a^*\\n\" << a.adjoint() << endl;\n\n\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "a556e177538224f8a9ad49bedec6d498c3c431c3", "size": 810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_tut_arithmetic_transpose_conjugate.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_tut_arithmetic_transpose_conjugate.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_tut_arithmetic_transpose_conjugate.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5, "max_line_length": 224, "alphanum_fraction": 0.6592592593, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.6250863463572931}}
{"text": "// https://www.codechef.com/problems/FCTRL2\n\n#include <bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp> \nusing namespace boost::multiprecision; \nusing namespace std;\n\nint main(){\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t\tint n;\n\t\tcin>>n;\n\t\tcpp_int fact = 1;\n\t\tfor(int i=1; i<=n; i++){\n\t\t\tfact *= i;\n\t\t}\n\t\tcout<<fact<<endl;\n\t}\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "b6ff4e2818c44d7810b60bab9401a289c83b3e65", "size": 335, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Competitive Programming/Codechef(begineer)/small_factorials.cpp", "max_stars_repo_name": "l0rdluc1f3r/CppCompetitiveProgramming", "max_stars_repo_head_hexsha": "71376b5a6182dc446811072c73a2b13f33110d4c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T06:38:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T06:38:53.000Z", "max_issues_repo_path": "Competitive Programming/Codechef(begineer)/small_factorials.cpp", "max_issues_repo_name": "l0rdluc1f3r/CppCompetitiveProgramming", "max_issues_repo_head_hexsha": "71376b5a6182dc446811072c73a2b13f33110d4c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Competitive Programming/Codechef(begineer)/small_factorials.cpp", "max_forks_repo_name": "l0rdluc1f3r/CppCompetitiveProgramming", "max_forks_repo_head_hexsha": "71376b5a6182dc446811072c73a2b13f33110d4c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.9642857143, "max_line_length": 44, "alphanum_fraction": 0.6089552239, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.6250654374433589}}
{"text": "#include <Eigen/Eigen>\n#include <iostream>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  typedef Matrix<double,4,Dynamic> Matrix4Xd;\nMatrix4Xd M = Matrix4Xd::Random(4,5);\nProjective3d P(Matrix4d::Random());\ncout << \"The matrix M is:\" << endl << M << endl << endl;\ncout << \"M.colwise().hnormalized():\" << endl << M.colwise().hnormalized() << endl << endl;\ncout << \"P*M:\" << endl << P*M << endl << endl;\ncout << \"(P*M).colwise().hnormalized():\" << endl << (P*M).colwise().hnormalized() << endl << endl;\n  return 0;\n}\n", "meta": {"hexsha": "7944a49c32bfe380df586b7e88bcc70772c84cb7", "size": 631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_DirectionWise_hnormalized.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_DirectionWise_hnormalized.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_DirectionWise_hnormalized.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": 26.2916666667, "max_line_length": 98, "alphanum_fraction": 0.648177496, "num_tokens": 191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436727, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.625065425880091}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix3d m = Matrix3d::Zero();\nm.triangularView<Eigen::Upper>().setOnes();\ncout << \"Here is the matrix m:\\n\" << m << endl;\nMatrix3d n = Matrix3d::Ones();\nn.triangularView<Eigen::Lower>() *= 2;\ncout << \"Here is the matrix n:\\n\" << n << endl;\ncout << \"And now here is m.inverse()*n, taking advantage of the fact that\"\n        \" m is upper-triangular:\\n\"\n     << m.triangularView<Eigen::Upper>().solve(n) << endl;\ncout << \"And this is n*m.inverse():\\n\"\n     << m.triangularView<Eigen::Upper>().solve<Eigen::OnTheRight>(n);\n\n  return 0;\n}\n", "meta": {"hexsha": "4f45adb2e0813b4c1e9fe512a0f3704a24d76eac", "size": 1004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_Triangular_solve.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_Triangular_solve.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_Triangular_solve.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 31.375, "max_line_length": 224, "alphanum_fraction": 0.6583665339, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6250300334925565}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n\nusing namespace std;\n\n#include <boost/timer.hpp>\n\n// for sophus\n#include <sophus/se3.hpp>\n\nusing Sophus::SE3d;\n\n// for eigen\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nusing namespace Eigen;\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include \"plot.h\"\n\nusing namespace cv;\n\n/**********************************************\n* \u672c\u7a0b\u5e8f\u6f14\u793a\u4e86\u5355\u76ee\u76f8\u673a\u5728\u5df2\u77e5\u8f68\u8ff9\u4e0b\u7684\u7a20\u5bc6\u6df1\u5ea6\u4f30\u8ba1\n* \u4f7f\u7528\u6781\u7ebf\u641c\u7d22 + NCC \u5339\u914d\u7684\u65b9\u5f0f\uff0c\u4e0e\u4e66\u672c\u7684 12.2 \u8282\u5bf9\u5e94\n* \u8bf7\u6ce8\u610f\u672c\u7a0b\u5e8f\u5e76\u4e0d\u5b8c\u7f8e\uff0c\u4f60\u5b8c\u5168\u53ef\u4ee5\u6539\u8fdb\u5b83\u2014\u2014\u6211\u5176\u5b9e\u5728\u6545\u610f\u66b4\u9732\u4e00\u4e9b\u95ee\u9898(\u8fd9\u662f\u501f\u53e3)\u3002\n***********************************************/\nstd::ofstream debug(\"debug.txt\");\n// ------------------------------------------------------------------\n// parameters\nconst int boarder = 20;         // \u8fb9\u7f18\u5bbd\u5ea6\nconst int width = 640;          // \u56fe\u50cf\u5bbd\u5ea6\nconst int height = 480;         // \u56fe\u50cf\u9ad8\u5ea6\nconst double fx = 481.2f;       // \u76f8\u673a\u5185\u53c2\nconst double fy = -480.0f;\nconst double cx = 319.5f;\nconst double cy = 239.5f;\nconst int ncc_window_size = 3;    // NCC \u53d6\u7684\u7a97\u53e3\u534a\u5bbd\u5ea6\nconst int ncc_area = (2 * ncc_window_size + 1) * (2 * ncc_window_size + 1); // NCC\u7a97\u53e3\u9762\u79ef\nconst double min_cov = 0.1;     // \u6536\u655b\u5224\u5b9a\uff1a\u6700\u5c0f\u65b9\u5dee\nconst double max_cov = 10;      // \u53d1\u6563\u5224\u5b9a\uff1a\u6700\u5927\u65b9\u5dee\n\n// ------------------------------------------------------------------\n// \u91cd\u8981\u7684\u51fd\u6570\n/// \u4ece REMODE \u6570\u636e\u96c6\u8bfb\u53d6\u6570\u636e\nbool readDatasetFiles(\n    const string &path,\n    vector<string> &color_image_files,\n    vector<SE3d> &poses,\n    cv::Mat &ref_depth\n);\n\n/**\n * \u6839\u636e\u65b0\u7684\u56fe\u50cf\u66f4\u65b0\u6df1\u5ea6\u4f30\u8ba1\n * @param ref           \u53c2\u8003\u56fe\u50cf\n * @param curr          \u5f53\u524d\u56fe\u50cf\n * @param T_C_R         \u53c2\u8003\u56fe\u50cf\u5230\u5f53\u524d\u56fe\u50cf\u7684\u4f4d\u59ff\n * @param depth         \u6df1\u5ea6\n * @param depth_cov     \u6df1\u5ea6\u65b9\u5dee\n * @return              \u662f\u5426\u6210\u529f\n */\nvoid update(\n    const Mat &ref,\n    const Mat &curr,\n    const SE3d &T_C_R,\n    Mat &depth,\n    Mat &depth_cov2\n);\n\n/**\n * \u6781\u7ebf\u641c\u7d22\n * @param ref           \u53c2\u8003\u56fe\u50cf\n * @param curr          \u5f53\u524d\u56fe\u50cf\n * @param T_C_R         \u4f4d\u59ff\n * @param pt_ref        \u53c2\u8003\u56fe\u50cf\u4e2d\u70b9\u7684\u4f4d\u7f6e\n * @param depth_mu      \u6df1\u5ea6\u5747\u503c\n * @param depth_cov     \u6df1\u5ea6\u65b9\u5dee\n * @param pt_curr       \u5f53\u524d\u70b9\n * @param epipolar_direction  \u6781\u7ebf\u65b9\u5411\n * @return              \u662f\u5426\u6210\u529f\n */\nbool epipolarSearch(\n    const Mat &ref,\n    const Mat &curr,\n    const SE3d &T_C_R,\n    const Vector2d &pt_ref,\n    const double &depth_mu,\n    const double &depth_cov,\n    Vector2d &pt_curr,\n    Vector2d &epipolar_direction\n);\n\n/**\n * \u66f4\u65b0\u6df1\u5ea6\u6ee4\u6ce2\u5668\n * @param pt_ref    \u53c2\u8003\u56fe\u50cf\u70b9\n * @param pt_curr   \u5f53\u524d\u56fe\u50cf\u70b9\n * @param T_C_R     \u4f4d\u59ff\n * @param epipolar_direction \u6781\u7ebf\u65b9\u5411\n * @param depth     \u6df1\u5ea6\u5747\u503c\n * @param depth_cov2    \u6df1\u5ea6\u65b9\u5411\n * @return          \u662f\u5426\u6210\u529f\n */\nbool updateDepthFilter(\n    const Vector2d &pt_ref,\n    const Vector2d &pt_curr,\n    const SE3d &T_C_R,\n    const Vector2d &epipolar_direction,\n    Mat &depth,\n    Mat &depth_cov2\n);\n\n/**\n * \u8ba1\u7b97 NCC \u8bc4\u5206\n * @param ref       \u53c2\u8003\u56fe\u50cf\n * @param curr      \u5f53\u524d\u56fe\u50cf\n * @param pt_ref    \u53c2\u8003\u70b9\n * @param pt_curr   \u5f53\u524d\u70b9\n * @return          NCC\u8bc4\u5206\n */\ndouble NCC(const Mat &ref, const Mat &curr, const Vector2d &pt_ref, const Vector2d &pt_curr);\n\n// \u53cc\u7ebf\u6027\u7070\u5ea6\u63d2\u503c\ninline double getBilinearInterpolatedValue(const Mat &img, const Vector2d &pt) {\n    uchar *d = &img.data[int(pt(1, 0)) * img.step + int(pt(0, 0))];\n    double xx = pt(0, 0) - floor(pt(0, 0));\n    double yy = pt(1, 0) - floor(pt(1, 0));\n    return ((1 - xx) * (1 - yy) * double(d[0]) +\n            xx * (1 - yy) * double(d[1]) +\n            (1 - xx) * yy * double(d[img.step]) +\n            xx * yy * double(d[img.step + 1])) / 255.0;\n}\n\n// ------------------------------------------------------------------\n// \u4e00\u4e9b\u5c0f\u5de5\u5177\n// \u663e\u793a\u4f30\u8ba1\u7684\u6df1\u5ea6\u56fe\n// void plotDepth(const Mat &depth_truth, const Mat &depth_estimate);\n\n// \u50cf\u7d20\u5230\u76f8\u673a\u5750\u6807\u7cfb\ninline Vector3d px2cam(const Vector2d px) {\n    return Vector3d(\n        (px(0, 0) - cx) / fx,\n        (px(1, 0) - cy) / fy,\n        1\n    );\n}\n\n// \u76f8\u673a\u5750\u6807\u7cfb\u5230\u50cf\u7d20\ninline Vector2d cam2px(const Vector3d p_cam) {\n    return Vector2d(\n        p_cam(0, 0) * fx / p_cam(2, 0) + cx,\n        p_cam(1, 0) * fy / p_cam(2, 0) + cy\n    );\n}\n\n// \u68c0\u6d4b\u4e00\u4e2a\u70b9\u662f\u5426\u5728\u56fe\u50cf\u8fb9\u6846\u5185\ninline bool inside(const Vector2d &pt) {\n    return pt(0, 0) >= boarder && pt(1, 0) >= boarder\n           && pt(0, 0) + boarder < width && pt(1, 0) + boarder <= height;\n}\n\n// // \u663e\u793a\u6781\u7ebf\u5339\u914d\n// void showEpipolarMatch(const Mat &ref, const Mat &curr, const Vector2d &px_ref, const Vector2d &px_curr);\n\n// // \u663e\u793a\u6781\u7ebf\n// void showEpipolarLine(const Mat &ref, const Mat &curr, const Vector2d &px_ref, const Vector2d &px_min_curr,\n//                       const Vector2d &px_max_curr);\n\n/// \u8bc4\u6d4b\u6df1\u5ea6\u4f30\u8ba1\nvoid evaludateDepth(const Mat &depth_truth, const Mat &depth_estimate);\n// ------------------------------------------------------------------\n\n\nint main(int argc, char **argv) {\n    if (argc != 2) {\n        cout << \"Usage: dense_mapping path_to_test_dataset\" << endl;\n        return -1;\n    }\n\n    // \u4ece\u6570\u636e\u96c6\u8bfb\u53d6\u6570\u636e\n    vector<string> color_image_files;\n    vector<SE3d> poses_TWC;\n    Mat ref_depth;\n    bool ret = readDatasetFiles(argv[1], color_image_files, poses_TWC, ref_depth);\n    if (ret == false) {\n        cout << \"Reading image files failed!\" << endl;\n        return -1;\n    }\n    cout << \"read total \" << color_image_files.size() << \" files.\" << endl;\n\n    // \u7b2c\u4e00\u5f20\u56fe\n    Mat ref = imread(color_image_files[0], 0);                // gray-scale image\n    SE3d pose_ref_TWC = poses_TWC[0];\n    double init_depth = 3.0;    // \u6df1\u5ea6\u521d\u59cb\u503c\n    double init_cov2 = 3.0;     // \u65b9\u5dee\u521d\u59cb\u503c\n    Mat depth(height, width, CV_64F, init_depth);             // \u6df1\u5ea6\u56fe\n    Mat depth_cov2(height, width, CV_64F, init_cov2);         // \u6df1\u5ea6\u56fe\u65b9\u5dee\n\n    for (int index = 1; index < color_image_files.size(); index++) {\n        cout << \"*** loop \" << index << \" ***\" << endl;\n        Mat curr = imread(color_image_files[index], 0);\n        if (curr.data == nullptr) continue;\n        SE3d pose_curr_TWC = poses_TWC[index];\n        SE3d pose_T_C_R = pose_curr_TWC.inverse() * pose_ref_TWC;   // \u5750\u6807\u8f6c\u6362\u5173\u7cfb\uff1a T_C_W * T_W_R = T_C_R\n        update(ref, curr, pose_T_C_R, depth, depth_cov2);\n        evaludateDepth(ref_depth, depth);\n        std::cout << \"after eval depth \" << std::endl;\n        plotDepth(ref_depth, depth);\n        // imshow(\"image\", curr);\n        // waitKey(1);\n        plotCur(curr);\n    }\n\n    cout << \"estimation returns, saving depth map ...\" << endl;\n    imwrite(\"depth.png\", depth);\n    cout << \"done.\" << endl;\n\n    debug.close();\n    return 0;\n}\n\nbool readDatasetFiles(\n    const string &path,\n    vector<string> &color_image_files,\n    std::vector<SE3d> &poses,\n    cv::Mat &ref_depth) {\n    ifstream fin(path + \"/first_200_frames_traj_over_table_input_sequence.txt\");\n    if (!fin) return false;\n\n    while (!fin.eof()) {\n        // \u6570\u636e\u683c\u5f0f\uff1a\u56fe\u50cf\u6587\u4ef6\u540d tx, ty, tz, qx, qy, qz, qw \uff0c\u6ce8\u610f\u662f TWC \u800c\u975e TCW\n        string image;\n        fin >> image;\n        double data[7];\n        for (double &d:data) fin >> d;\n\n        color_image_files.push_back(path + string(\"/images/\") + image);\n        poses.push_back(\n            SE3d(Quaterniond(data[6], data[3], data[4], data[5]),\n                 Vector3d(data[0], data[1], data[2]))\n        );\n        if (!fin.good()) break;\n    }\n    fin.close();\n\n    // load reference depth\n    fin.open(path + \"/depthmaps/scene_000.depth\");\n    ref_depth = cv::Mat(height, width, CV_64F);\n    if (!fin) return false;\n    for (int y = 0; y < height; y++)\n        for (int x = 0; x < width; x++) {\n            double depth = 0;\n            fin >> depth;\n            ref_depth.ptr<double>(y)[x] = depth / 100.0;\n        }\n\n    return true;\n}\n\n// \u5bf9\u6574\u4e2a\u6df1\u5ea6\u56fe\u8fdb\u884c\u66f4\u65b0\nvoid update(const Mat &ref, const Mat &curr, const SE3d &T_C_R, Mat &depth, Mat &depth_cov2) {\n    std::cout << curr.size() << \"\\n\";\n    for (int x = boarder; x < width - boarder; x++)\n    {\n        for (int y = boarder; y < height - boarder; y++) {\n            // \u904d\u5386\u6bcf\u4e2a\u50cf\u7d20\n            // std::cout << depth.size() << \" \" << depth_cov2.size() << \"\\n\";\n            if (depth_cov2.ptr<double>(y)[x] < min_cov || depth_cov2.ptr<double>(y)[x] > max_cov) // \u6df1\u5ea6\u5df2\u6536\u655b\u6216\u53d1\u6563\n                continue;\n            // \u5728\u6781\u7ebf\u4e0a\u641c\u7d22 (x,y) \u7684\u5339\u914d\n            Vector2d pt_curr;\n            Vector2d epipolar_direction;\n            bool ret = epipolarSearch(\n                ref,\n                curr,\n                T_C_R,\n                Vector2d(x, y),\n                depth.ptr<double>(y)[x],\n                sqrt(depth_cov2.ptr<double>(y)[x]),\n                pt_curr,\n                epipolar_direction\n            );\n\n            if (ret == false) // \u5339\u914d\u5931\u8d25\n                continue;\n\n            // debug << epipolar_direction.transpose() << \"\\n\";\n\n            // \u53d6\u6d88\u8be5\u6ce8\u91ca\u4ee5\u663e\u793a\u5339\u914d\n            // showEpipolarMatch(ref, curr, Vector2d(x, y), pt_curr);\n\n            // \u5339\u914d\u6210\u529f\uff0c\u66f4\u65b0\u6df1\u5ea6\u56fe\n            updateDepthFilter(Vector2d(x, y), pt_curr, T_C_R, epipolar_direction, depth, depth_cov2);\n        }\n    }\n}\n\n// \u6781\u7ebf\u641c\u7d22\n// \u65b9\u6cd5\u89c1\u4e66 12.2 12.3 \u4e24\u8282\nbool epipolarSearch(\n    const Mat &ref, const Mat &curr,\n    const SE3d &T_C_R, const Vector2d &pt_ref,\n    const double &depth_mu, const double &depth_cov,\n    Vector2d &pt_curr, Vector2d &epipolar_direction) {\n    Vector3d f_ref = px2cam(pt_ref);\n    f_ref.normalize();\n    Vector3d P_ref = f_ref * depth_mu;    // \u53c2\u8003\u5e27\u7684 P \u5411\u91cf\n\n    Vector2d px_mean_curr = cam2px(T_C_R * P_ref); // \u6309\u6df1\u5ea6\u5747\u503c\u6295\u5f71\u7684\u50cf\u7d20\n    double d_min = depth_mu - 3 * depth_cov, d_max = depth_mu + 3 * depth_cov;\n    if (d_min < 0.1) d_min = 0.1;\n    Vector2d px_min_curr = cam2px(T_C_R * (f_ref * d_min));    // \u6309\u6700\u5c0f\u6df1\u5ea6\u6295\u5f71\u7684\u50cf\u7d20\n    Vector2d px_max_curr = cam2px(T_C_R * (f_ref * d_max));    // \u6309\u6700\u5927\u6df1\u5ea6\u6295\u5f71\u7684\u50cf\u7d20\n\n    Vector2d epipolar_line = px_max_curr - px_min_curr;    // \u6781\u7ebf\uff08\u7ebf\u6bb5\u5f62\u5f0f\uff09\n    epipolar_direction = epipolar_line;        // \u6781\u7ebf\u65b9\u5411\n    epipolar_direction.normalize();\n    double half_length = 0.5 * epipolar_line.norm();    // \u6781\u7ebf\u7ebf\u6bb5\u7684\u534a\u957f\u5ea6\n    if (half_length > 100) half_length = 100;   // \u6211\u4eec\u4e0d\u5e0c\u671b\u641c\u7d22\u592a\u591a\u4e1c\u897f\n\n    // \u53d6\u6d88\u6b64\u53e5\u6ce8\u91ca\u4ee5\u663e\u793a\u6781\u7ebf\uff08\u7ebf\u6bb5\uff09\n    // showEpipolarLine( ref, curr, pt_ref, px_min_curr, px_max_curr );\n\n    // \u5728\u6781\u7ebf\u4e0a\u641c\u7d22\uff0c\u4ee5\u6df1\u5ea6\u5747\u503c\u70b9\u4e3a\u4e2d\u5fc3\uff0c\u5de6\u53f3\u5404\u53d6\u534a\u957f\u5ea6\n    double best_ncc = -1.0;\n    Vector2d best_px_curr;\n    for (double l = -half_length; l <= half_length; l += 0.7) { // l+=sqrt(2)\n        Vector2d px_curr = px_mean_curr + l * epipolar_direction;  // \u5f85\u5339\u914d\u70b9\n        if (!inside(px_curr))\n            continue;\n        // \u8ba1\u7b97\u5f85\u5339\u914d\u70b9\u4e0e\u53c2\u8003\u5e27\u7684 NCC\n        double ncc = NCC(ref, curr, pt_ref, px_curr);\n        if (ncc > best_ncc) {\n            best_ncc = ncc;\n            best_px_curr = px_curr;\n        }\n    }\n    if (best_ncc < 0.85f)      // \u53ea\u76f8\u4fe1 NCC \u5f88\u9ad8\u7684\u5339\u914d\n        return false;\n    pt_curr = best_px_curr;\n    return true;\n}\n\ndouble NCC(\n    const Mat &ref, const Mat &curr,\n    const Vector2d &pt_ref, const Vector2d &pt_curr) {\n    // \u96f6\u5747\u503c-\u5f52\u4e00\u5316\u4e92\u76f8\u5173\n    // \u5148\u7b97\u5747\u503c\n    double mean_ref = 0, mean_curr = 0;\n    vector<double> values_ref, values_curr; // \u53c2\u8003\u5e27\u548c\u5f53\u524d\u5e27\u7684\u5747\u503c\n    for (int x = -ncc_window_size; x <= ncc_window_size; x++)\n        for (int y = -ncc_window_size; y <= ncc_window_size; y++) {\n            double value_ref = double(ref.ptr<uchar>(int(y + pt_ref(1, 0)))[int(x + pt_ref(0, 0))]) / 255.0;\n            mean_ref += value_ref;\n\n            double value_curr = getBilinearInterpolatedValue(curr, pt_curr + Vector2d(x, y));\n            mean_curr += value_curr;\n\n            values_ref.push_back(value_ref);\n            values_curr.push_back(value_curr);\n        }\n\n    mean_ref /= ncc_area;\n    mean_curr /= ncc_area;\n\n    // \u8ba1\u7b97 Zero mean NCC\n    double numerator = 0, demoniator1 = 0, demoniator2 = 0;\n    for (int i = 0; i < values_ref.size(); i++) {\n        double n = (values_ref[i] - mean_ref) * (values_curr[i] - mean_curr);\n        numerator += n;\n        demoniator1 += (values_ref[i] - mean_ref) * (values_ref[i] - mean_ref);\n        demoniator2 += (values_curr[i] - mean_curr) * (values_curr[i] - mean_curr);\n    }\n    return numerator / sqrt(demoniator1 * demoniator2 + 1e-10);   // \u9632\u6b62\u5206\u6bcd\u51fa\u73b0\u96f6\n}\n\nbool updateDepthFilter(\n    const Vector2d &pt_ref,\n    const Vector2d &pt_curr,\n    const SE3d &T_C_R,\n    const Vector2d &epipolar_direction,\n    Mat &depth,\n    Mat &depth_cov2) {\n    // \u4e0d\u77e5\u9053\u8fd9\u6bb5\u8fd8\u6709\u6ca1\u6709\u4eba\u770b\n    // \u7528\u4e09\u89d2\u5316\u8ba1\u7b97\u6df1\u5ea6\n    SE3d T_R_C = T_C_R.inverse();\n    Vector3d f_ref = px2cam(pt_ref);\n    f_ref.normalize();\n    Vector3d f_curr = px2cam(pt_curr);\n    f_curr.normalize();\n\n    // \u65b9\u7a0b\n    // d_ref * f_ref = d_cur * ( R_RC * f_cur ) + t_RC\n    // f2 = R_RC * f_cur\n    // \u8f6c\u5316\u6210\u4e0b\u9762\u8fd9\u4e2a\u77e9\u9635\u65b9\u7a0b\u7ec4\n    // => [ f_ref^T f_ref, -f_ref^T f2 ] [d_ref]   [f_ref^T t]\n    //    [ f_2^T f_ref, -f2^T f2      ] [d_cur] = [f2^T t   ]\n    Vector3d t = T_R_C.translation();\n    Vector3d f2 = T_R_C.so3() * f_curr;\n    Vector2d b = Vector2d(t.dot(f_ref), t.dot(f2));\n    Matrix2d A;\n    A(0, 0) = f_ref.dot(f_ref);\n    A(0, 1) = -f_ref.dot(f2);\n    A(1, 0) = -A(0, 1);\n    A(1, 1) = -f2.dot(f2);\n    Vector2d ans = A.inverse() * b;\n    Vector3d xm = ans[0] * f_ref;           // ref \u4fa7\u7684\u7ed3\u679c\n    Vector3d xn = t + ans[1] * f2;          // cur \u7ed3\u679c\n    Vector3d p_esti = (xm + xn) / 2.0;      // P\u7684\u4f4d\u7f6e\uff0c\u53d6\u4e24\u8005\u7684\u5e73\u5747\n    double depth_estimation = p_esti.norm();   // \u6df1\u5ea6\u503c\n    // debug << depth_estimation << \"\\n\";\n\n    // \u8ba1\u7b97\u4e0d\u786e\u5b9a\u6027\uff08\u4ee5\u4e00\u4e2a\u50cf\u7d20\u4e3a\u8bef\u5dee\uff09\n    Vector3d p = f_ref * depth_estimation;\n    Vector3d a = p - t;\n    double t_norm = t.norm();\n    double a_norm = a.norm();\n    double alpha = acos(f_ref.dot(t) / t_norm);\n    double beta = acos(-a.dot(t) / (a_norm * t_norm));\n    // debug << alpha << \" \" << beta << \"\\n\";\n    Vector3d f_curr_prime = px2cam(pt_curr + epipolar_direction);\n    f_curr_prime.normalize();\n    double beta_prime = acos(f_curr_prime.dot(-t) / t_norm);\n    // debug << beta_prime << \"\\n\";\n    double gamma = M_PI - alpha - beta_prime;\n    double p_prime = t_norm * sin(beta_prime) / sin(gamma);\n    double d_cov = p_prime - depth_estimation;\n    double d_cov2 = d_cov * d_cov;\n    // debug << d_cov2  <<\"\\n\";\n\n    // \u9ad8\u65af\u878d\u5408\n    double mu = depth.ptr<double>(int(pt_ref(1, 0)))[int(pt_ref(0, 0))];\n    double sigma2 = depth_cov2.ptr<double>(int(pt_ref(1, 0)))[int(pt_ref(0, 0))];\n\n    double mu_fuse = (d_cov2 * mu + sigma2 * depth_estimation) / (sigma2 + d_cov2);\n    double sigma_fuse2 = (sigma2 * d_cov2) / (sigma2 + d_cov2);\n\n    // debug << mu_fuse << \"\\n\";\n    depth.ptr<double>(int(pt_ref(1, 0)))[int(pt_ref(0, 0))] = mu_fuse;\n    depth_cov2.ptr<double>(int(pt_ref(1, 0)))[int(pt_ref(0, 0))] = sigma_fuse2;\n\n    return true;\n}\n\n// // \u540e\u9762\u8fd9\u4e9b\u592a\u7b80\u5355\u6211\u5c31\u4e0d\u6ce8\u91ca\u4e86\uff08\u5176\u5b9e\u662f\u56e0\u4e3a\u61d2\uff09\n// void plotDepth(const Mat &depth_truth, const Mat &depth_estimate) {\n//     imshow(\"depth_truth\", depth_truth * 0.4);\n//     imshow(\"depth_estimate\", depth_estimate * 0.4);\n//     imshow(\"depth_error\", depth_truth - depth_estimate);\n//     waitKey(1);\n// }\n\nvoid evaludateDepth(const Mat &depth_truth, const Mat &depth_estimate) {\n    double ave_depth_error = 0;     // \u5e73\u5747\u8bef\u5dee\n    double ave_depth_error_sq = 0;      // \u5e73\u65b9\u8bef\u5dee\n    int cnt_depth_data = 0;\n    for (int y = boarder; y < depth_truth.rows - boarder; y++)\n    {\n        for (int x = boarder; x < depth_truth.cols - boarder; x++) {\n            double error = depth_truth.at<double>(y, x) - depth_estimate.at<double>(y, x);\n            ave_depth_error += error;\n            ave_depth_error_sq += error * error;\n            cnt_depth_data++;\n        }\n    }\n    ave_depth_error /= cnt_depth_data;\n    ave_depth_error_sq /= cnt_depth_data;\n\n    cout << \"Average squared error = \" << ave_depth_error_sq << \", average error: \" << ave_depth_error << endl;\n}\n\n// void showEpipolarMatch(const Mat &ref, const Mat &curr, const Vector2d &px_ref, const Vector2d &px_curr) {\n//     Mat ref_show, curr_show;\n//     cv::cvtColor(ref, ref_show, CV_GRAY2BGR);\n//     cv::cvtColor(curr, curr_show, CV_GRAY2BGR);\n\n//     cv::circle(ref_show, cv::Point2f(px_ref(0, 0), px_ref(1, 0)), 5, cv::Scalar(0, 0, 250), 2);\n//     cv::circle(curr_show, cv::Point2f(px_curr(0, 0), px_curr(1, 0)), 5, cv::Scalar(0, 0, 250), 2);\n\n//     imshow(\"ref\", ref_show);\n//     imshow(\"curr\", curr_show);\n//     waitKey(1);\n// }\n\n// void showEpipolarLine(const Mat &ref, const Mat &curr, const Vector2d &px_ref, const Vector2d &px_min_curr,\n//                       const Vector2d &px_max_curr) {\n\n//     Mat ref_show, curr_show;\n//     cv::cvtColor(ref, ref_show, CV_GRAY2BGR);\n//     cv::cvtColor(curr, curr_show, CV_GRAY2BGR);\n\n//     cv::circle(ref_show, cv::Point2f(px_ref(0, 0), px_ref(1, 0)), 5, cv::Scalar(0, 255, 0), 2);\n//     cv::circle(curr_show, cv::Point2f(px_min_curr(0, 0), px_min_curr(1, 0)), 5, cv::Scalar(0, 255, 0), 2);\n//     cv::circle(curr_show, cv::Point2f(px_max_curr(0, 0), px_max_curr(1, 0)), 5, cv::Scalar(0, 255, 0), 2);\n//     cv::line(curr_show, Point2f(px_min_curr(0, 0), px_min_curr(1, 0)), Point2f(px_max_curr(0, 0), px_max_curr(1, 0)),\n//              Scalar(0, 255, 0), 1);\n\n//     imshow(\"ref\", ref_show);\n//     imshow(\"curr\", curr_show);\n//     waitKey(1);\n// }\n", "meta": {"hexsha": "617f080109d230553a555bed316771c3792d9929", "size": 16390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch12/dense_mono/dense_mapping.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch12/dense_mono/dense_mapping.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch12/dense_mono/dense_mapping.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3913043478, "max_line_length": 120, "alphanum_fraction": 0.5725442343, "num_tokens": 5664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6250300318211903}}
{"text": "#include <iostream>\n#include \"greeter/greeter.hpp\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <loguru.hpp>\n\n\nint main(int argc, char* argv[]) {\n    using namespace boost::numeric::ublas;\n\n    greeter(\"Now running our demo program!\");\n\n    loguru::init(argc, argv);\n    loguru::add_file(\"tools-cpp1.log\", loguru::Truncate, loguru::Verbosity_MAX);\n\n    LOG_SCOPE_F(INFO, \"Program starts.\");\n\n    std::cout << \"Testing Boost Matrix example!\" << std::endl;\n    matrix<double> m (3, 3);\n    for (unsigned i = 0; i < m.size1 (); ++ i)\n        for (unsigned j = 0; j < m.size2 (); ++ j) {\n            m(i, j) = 3 * i + j;\n            LOG_SCOPE_F(INFO, \"Indices %d, %d.\", i, j);\n        }\n    std::cout << m << std::endl;\n    LOG_SCOPE_F(INFO, \"Program ends.\");\n\n    greeter(\"Demo program ends!\");\n\n    return 0;\n}\n", "meta": {"hexsha": "b743b625a38e60ffb8b550207816508984e1c0ec", "size": 855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/build-c++-demo/main.cpp", "max_stars_repo_name": "hortonuva/learning-build-tools", "max_stars_repo_head_hexsha": "65e6f48a687468abe6e17c06fc537159becaea5e", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/build-c++-demo/main.cpp", "max_issues_repo_name": "hortonuva/learning-build-tools", "max_issues_repo_head_hexsha": "65e6f48a687468abe6e17c06fc537159becaea5e", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/build-c++-demo/main.cpp", "max_forks_repo_name": "hortonuva/learning-build-tools", "max_forks_repo_head_hexsha": "65e6f48a687468abe6e17c06fc537159becaea5e", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1470588235, "max_line_length": 80, "alphanum_fraction": 0.5894736842, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886584, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6250300305445746}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <vector>\n#include <fstream>\n#include <iostream>\n#include <sophus/se3.h>\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef vector<Vector3d,Eigen::aligned_allocator<Vector3d> > VecVector3d;\ntypedef vector<Vector2d,Eigen::aligned_allocator<Vector2d> > VecVector2d;\n\ntypedef Matrix<double ,6,1> Vector6d;\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; //\u5185\u53c2\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 into p3d and p2d\n    //START YOUR CODE HERE\n    ifstream file1(p3d_file);\n    if(!file1.is_open())\n    {\n        perror(\"p3d open failed\");\n    }\n    ifstream file2(p2d_file);\n    if(!file2.is_open())\n    {\n        perror(\"p2d open failed\");\n    }\n    while (!file1.eof())\n    {\n        double p3[3] = {0};\n        for (auto &p:p3)\n        {\n            file1 >> p;\n        }\n        p3d.push_back(Vector3d(p3[0], p3[1], p3[2]));\n    }\n    while (!file2.eof())\n    {\n        double p2[2]={0};\n        for (auto& p:p2)\n        {\n            file2>>p;\n        }\n        Vector2d v(p2[0],p2[1]);\n        p2d.push_back(v);\n        //cout<<\"p2d \"<<v<<\" p3d \"<<Vector3d(p3[0],p3[1],p3[2])<<endl;\n    }\n    //END YOUR CODE HERE\n    assert( p3d.size() == p2d.size() ); //\u5982\u679c\u4e8c\u8005\u884c\u6570\u76f8\u7b49\uff0c\u5219\u800c\u5df2\u7ee7\u7eed\u6267\u884c\uff0c\u5426\u5219\u7a0b\u5e8f\u505c\u6b62\u8fd0\u884c\n\n    int iterations=100;\n    double cost=0,lastcost=0;\n    int nPoints=p3d.size();\n    cout<<\"points: \"<<nPoints<<endl;\n\n\n    Matrix3d I = Matrix3d::Identity(); //\u58f0\u660e\u5355\u4f4d\u77e9\u9635\n    Vector3d t ;\n    t.setZero();\n    //cout<< \"I:\\n\"<<I<<endl;\n    //cout<< \"t:\\n\"<<t<<endl;\n    Sophus::SE3 T_esti(I,t);//\u53d8\u6362\u77e9\u9635\n    //Sophus::SE3 T_esti;\n    cout<<\"T_esti:\\n\"<<T_esti.matrix()<<endl;\n\n\n\n   for (int iter = 0; iter <iterations ; ++iter) //\u8fed\u4ee3100\u6b21\n    {\n        Matrix<double,6,6> H = Matrix<double,6,6>::Zero();\n        Vector6d b = Vector6d::Zero();\n\n        cost=0;\n        //compute cost\n        for (int i = 0; i <p3d.size() ; ++i) //\u904d\u5386\u6570\u7ec4\n        {\n            //compute cost for p3d[i] and p2d[i]\n            //START YOUR CODE HERE\n            Vector2d ui=p2d[i]; //2*1 p2p\u70b9\n            //Vector3d pi=p3d[i];\n            //\uff087.34\uff094*4 \u7684\u53d8\u6362\u77e9\u9635 \u00d7 4*1\u76843d\u70b9\n\n            Vector4d pii = T_esti.matrix()*Vector4d(p3d[i][0],p3d[i][1],p3d[i][2],1);\n\n           // cout<< \"pii:\\n\"<< pii <<endl;\n           // cout<< \"k:\\n\" << k << endl;\n            // 3*1\u7684s*u =3*3 \u7684\u5185\u53c2 \u00d7 3*1\u7684(SE3*P)\n            Vector3d pi=k*Vector3d(pii[0],pii[1],pii[2]);//s*u\n\n            cout<< \"pi:\\n\"<< pi<<endl;\n\n            //\u6c42\u8bef\u5dee\n            Vector2d e( ui[0]-pi[0]/pi[2] , ui[1]-pi[1]/pi[2] ); //\u9664\u4ee5pi[2]\u662f\u5f52\u4e00\u5316\u8fc7\u7a0b\uff0c\u8bef\u5dee\u4e3a2*1\n            cost += e(0,0)*e(0,0)+e(1,0)*e(1,0);//e.transpose()*e;\n            //END YOUR CODE  HERE\n\n            //compute jacobian\n            Matrix<double,2,6> J; //\u5b9a\u4e492*6 \u96c5\u514b\u6bd4\n\n            //START YOUR CODE HERE\n            //7.45\n            J(0,0)=-fx/pii[2];\n            J(0,1)=0;\n            J(0,2)=fx*pii[0]/(pii[2]*pii[2]);\n            J(0,3)=fx*pii[0]*pii[1]/(pii[2]*pii[2]);\n            J(0,4)=-fx-fx*pii[0]*pii[0]/(pii[2]*pii[2]);\n            J(0,5)=fx*pii[1]/pii[2];\n\n            J(1,0)=0;\n            J(1,1)=-fy/pii[2];\n            J(1,2)=fy*pii[1]/(pii[2]*pii[2]);\n            J(1,3)=fy+fy*pii[2]*pii[2]/(pii[0]*pii[0]);\n            J(1,4)=-fy*pii[0]*pii[1]/(pii[2]*pii[2]);\n            J(1,5)=-fy*pii[0]/pii[2];\n            //END YOUR CODE HERE\n\n            H+=J.transpose()*J;\n            b+=-J.transpose()*e;\n        }\n\n        //solve dx\n        Vector6d dx;\n\n        //START YOUR CODE HERE\n        dx=H.ldlt().solve(b);\n        //END YOUR CODE HERE\n\n        cout<<\"iteration \"<<iter<<\" cost=\"<<cout.precision(12)<<cost<<endl;\n        if(isnan(dx[0]))\n        {\n            cout<<\"result is nan!\"<<endl;\n            break;\n        }\n\n        if(iter>0&&cost>=lastcost)\n        {\n            //cost increase,update is not good\n            cout<<\"cost: \"<<cout.precision(12)<<cost<<\", last cost: \"<<cout.precision(12)<<lastcost<<endl;\n            break;\n        }\n\n        //update your estimation\n        //START YOUR CODE HERE\n        T_esti=Sophus::SE3::exp(dx) * T_esti;\n\n        //END YOUR CODE HERE\n        lastcost=cost;\n        cout<<\"iteration \"<<iter<<\" cost=\"<<cout.precision(12)<<cost<<endl;\n    }\n\n    cout<<\"estimated pose: \\n\"<<T_esti.matrix()<<endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "67b8c054c16076751c34c35dda24390a63dd1ccc", "size": 4372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homework/homework_L5/GN-BA.cpp", "max_stars_repo_name": "MrCocoaCat/slambook", "max_stars_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-02-13T05:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-15T17:35:25.000Z", "max_issues_repo_path": "homework/homework_L5/GN-BA.cpp", "max_issues_repo_name": "MrCocoaCat/slambook", "max_issues_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework/homework_L5/GN-BA.cpp", "max_forks_repo_name": "MrCocoaCat/slambook", "max_forks_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-21T13:59:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-21T13:59:20.000Z", "avg_line_length": 26.496969697, "max_line_length": 106, "alphanum_fraction": 0.4908508692, "num_tokens": 1559, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476385, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6250232363104012}}
{"text": "/*\n * geometry.cpp\n * Copyright (C) 2018 exbot <exbot@ubuntu>\n *\n * Distributed under terms of the MIT license.\n */\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char **argv){\n\n\t\tIsometry3d T_cw1 = Isometry3d::Identity();\n\t\tIsometry3d T_cw2 = Isometry3d::Identity();\n\n\t\tQuaterniond q_cw1(0.55, 0.3, 0.2, 0.2);\n\t\tQuaterniond q_cw2(-0.1, 0.3, -0.7, 0.2);\n\n\t\tVector3d t_cw2(-0.1,0.4,0.8);\n\t\tVector3d t_cw1(0.7,1.1,0.2);\n\t\tVector3d p_c1(0.5,-0.1,0.2);\n\n\t\tT_cw1.rotate(q_cw1.normalized().toRotationMatrix());\n\t\tT_cw1.pretranslate(t_cw1);\n\t\tT_cw2.rotate(q_cw2.normalized().toRotationMatrix());\n\t\tT_cw2.pretranslate(t_cw2);\n\n\t\tVector3d p_c2 = T_cw2 * T_cw1.inverse() * p_c1;\n\t\tcout << \"P in camera2: \"<< endl << p_c2 << endl;\nreturn 1;\n}\n", "meta": {"hexsha": "baf4d8e07eba41b456628224b5020396f63ad485", "size": 819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slam/PA2_code/geometry.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/PA2_code/geometry.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/PA2_code/geometry.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": 22.75, "max_line_length": 54, "alphanum_fraction": 0.6727716728, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.6250232355423927}}
{"text": "#include <armadillo>\n#include \"mcpdft.h\"\n#include \"functional.h\"\n\nnamespace mcpdft {\n   /*================================================================*/\n   /*                      Exchange Functionals                      */\n   /*================================================================*/\n   Functional::Functional()  {}\n   Functional::~Functional() {}\n\n   double Functional::EX_LSDA(const MCPDFT *mc,\n                              const arma::vec &rho_a,\n                              const arma::vec &rho_b) {\n       const double alpha = (2.0/3.0);      // Slater value: a constant\n       const double Cx = (9.0/8.0) * alpha * pow(3.0/M_PI,1.0/3.0);\n\n       size_t npts = mc->get_npts();\n       arma::vec W(mc->get_w());\n\n       double exc = 0.0;\n       for (size_t p = 0; p < npts; p++) {\n           double exa = pow(2.0,1.0/3.0) * Cx * pow( rho_a(p), 4.0/3.0) ;\n           double exb = pow(2.0,1.0/3.0) * Cx * pow( rho_b(p), 4.0/3.0) ;\n           double ex_LSDA = exa + exb;\n           exc += - ex_LSDA * W(p);\n       }\n       return exc;\n   }\n\n   double Functional::EX_PBE(const MCPDFT *mc,\n\t\t             const arma::vec &rho_a,\n\t\t             const arma::vec &rho_b,\n\t\t             const arma::vec &sigma_aa,\n\t\t             const arma::vec &sigma_bb) {\n\n       const double delta = 0.06672455060314922;\n       const double MU = (1.0/3.0) * delta * M_PI * M_PI;\n       const double KAPPA = 0.804;\n       double tol = 1.0e-20;\n   \n       auto kF = [](double RHO) -> double {\n                 double dum = pow(3.0 * M_PI * M_PI * RHO ,1.0/3.0);\n                 return dum;\n       };\n   \n       auto eX = [=](double RHO) -> double {\n                 double temp = -(3.0 * kF(RHO)) / (4.0 * M_PI);\n                 return temp;\n       };\n   \n       auto FX = [=](double SIGMA) -> double {\n                 double temp = 1.0 + KAPPA - KAPPA * pow( (1.0 + (MU * pow(SIGMA,2.0)) / KAPPA ), -1.0 );\n                 return temp;\n       };\n   \n   \n       auto S = [=](double RHO, double SIGMA) -> double {\n                double temp = sqrt(SIGMA) / (2.0 * kF(RHO) * RHO);\n                return temp;\n       };\n   \n       size_t npts = mc->get_npts();\n       arma::vec W(mc->get_w());\n\n       double exc = 0.0;\n       for (int p = 0; p < npts; p++) {\n           double rhoa = rho_a(p);\n           double rhob = rho_b(p);\n           double rho = rhoa + rhob;\n           double sigmaaa = sigma_aa(p);\n           double sigmabb = sigma_bb(p);\n           double sigma = 0.0;\n           if ( rho > tol ) {\n              if ( rhoa < tol ){\n                 rho = rhob;\n                 sigmabb = std::max(0.0,sigmabb);\n                 sigma = sigmabb;\n   \n                 double zk = eX(2.0 * rho) * FX(S(2.0 * rho, 4.0 * sigma));\n                 exc += rho * zk * W(p);\n              }else if ( rhob < tol ){\n                       rho = rhoa;\n                       sigmaaa = std::max(0.0,sigmaaa);\n                       sigma = sigmaaa;\n                       double zk = eX(2.0 * rho) * FX(S(2.0 * rho, 4.0 * sigma));\n                       exc += rho * zk * W(p);\n              }else {\n                    double zka = rhoa * eX(2.0 * rhoa) * FX(S(2.0 * rhoa, 4.0 * sigmaaa));\n                    double zkb = rhob * eX(2.0 * rhob) * FX(S(2.0 * rhob, 4.0 * sigmabb));\n                    double zk = zka + zkb;\n                    exc += zk * W(p);\n              }\n           }else{\n                   exc += 0.0;\n                }\n       }\n       return exc;\n   }\n   /*================================================================*/\n   /*                    Correlation Functionals                     */\n   /*================================================================*/\n    double Functional::EC_VWN3(const MCPDFT *mc,\n                               const arma::vec &rho_a,\n                               const arma::vec &rho_b) {\n       double tol = 1.0e-20;\n\n       const double ecp1 = 0.03109070000;\n       const double ecp2 = -0.409286;\n       const double ecp3 = 13.0720;\n       const double ecp4 = 42.7198;\n       const double ecf1 = 0.01554535000;\n       const double ecf2 = -0.743294;\n       const double ecf3 = 20.1231;\n       const double ecf4 = 101.578;\n       const double d2Fz = 1.7099209341613656173;\n\n       size_t npts = mc->get_npts();\n       arma::vec W(mc->get_w());\n\n       auto x = [](double RHO) -> double {\n                double rs = pow( 3.0 / ( 4.0 * M_PI * RHO ) , 1.0/3.0 );\n                double dum = sqrt(rs);\n                return dum;\n       };\n       auto Fz = [](double ZETA) -> double {\n                 double dum = (pow((1.0 + ZETA) ,4.0/3.0) + pow((1.0 - ZETA) ,4.0/3.0) - 2.0) / (2.0 * pow(2.0,1.0/3.0) - 2.0);\n                 return dum;\n       };\n       auto X = [](double i, double c, double d) -> double {\n                double temp = pow(i,2.0) + c * i + d;\n                return temp;\n       };\n       auto Q = [](double c, double d) -> double {\n                double temp1 = sqrt( 4 * d - pow(c,2.0) );\n                return temp1;\n       };\n       auto q = [=](double RHO, double A, double p, double c, double d) -> double {\n                double dum1 = A * ( log( pow(x(RHO),2.0) / X(x(RHO),c,d) ) + 2.0 * c * atan( Q(c,d)/(2.0*x(RHO) + c) ) * pow(Q(c,d),-1.0)\n                            - c * p * ( log( pow(x(RHO)-p,2.0) / X(x(RHO),c,d) ) + 2.0 * (c + 2.0 * p) * atan( Q(c,d)/(2.0*x(RHO) + c) )\n                            * pow(Q(c,d),-1.0) ) * pow(X(p,c,d),-1.0) );\n                return dum1;\n       };\n       auto EcP = [=](double RHO) -> double {\n                  double dumm = q(RHO,ecp1,ecp2,ecp3,ecp4);\n                  return dumm;\n       };\n       auto EcF = [=](double RHO) -> double {\n                  double dum = q(RHO,ecf1,ecf2,ecf3,ecf4);\n                  return dum;\n       };\n\n       double exc = 0.0;\n       for (int p = 0; p < npts; p++) {\n           double rhoa = rho_a(p);\n           double rhob = rho_b(p);\n           double rho = rhoa + rhob;\n           double zeta = 0.0;\n           if ( rho > tol ) {\n              if ( rhoa < tol ){\n                 rho = rhob;\n                 zeta = 1.0;\n              }else if ( rhob < tol ){\n                       rho = rhoa;\n                       zeta = 1.0;\n              }else {/* if (!(rhoa < tol) && !(rhob < tol) ) */\n                    zeta = (rhoa - rhob) / rho;\n              }\n              double zk = EcP(rho) + Fz(zeta) * (EcF(rho) - EcP(rho));\n              exc += rho * zk * W(p);\n           }else{\n                   double zk = 0.0;\n                   exc += 0.0;\n                }\n       }\n       return exc;\n   }\n\n   double Functional::EC_PBE(const MCPDFT *mc,\n\t\t             const arma::vec &rho_a,\n\t\t             const arma::vec &rho_b,\n                             const arma::vec &sigma_aa,\n                             const arma::vec &sigma_ab,\n\t\t\t     const arma::vec &sigma_bb) {\n      double tol = 1.0e-20;\n      size_t npts = mc->get_npts();\n      arma::vec W(mc->get_w());\n      const double pa = 1.0;\n      const double Aa = 0.0168869;\n      const double a1a = 0.11125;\n      const double b1a = 10.357;\n      const double b2a = 3.6231;\n      const double b3a = 0.88026;\n      const double b4a = 0.49671;\n      const double pe = 1.0;\n      const double c0p = 0.0310907;\n      const double a1p = 0.21370;\n      const double b1p = 7.5957;\n      const double b2p = 3.5876;\n      const double b3p = 1.6382;\n      const double b4p = 0.49294;\n      const double c0f = 0.01554535;\n      const double a1f = 0.20548;\n      const double b1f = 14.1189;\n      const double b2f = 6.1977;\n      const double b3f = 3.3662;\n      const double b4f = 0.62517;\n      const double d2Fz = 1.7099209341613656173;\n      const double BETA = 0.06672455060314922;\n      const double GAMMA = 0.0310906908696549;\n\n      auto Fi = [=](double ZETA) -> double {\n                double dumm = 0.5 * (pow((1.0 + ZETA) ,2.0/3.0 ) + pow((1.0 - ZETA) ,2.0/3.0));\n                return dumm;\n      };\n\n      auto kF = [](double RHO) -> double {\n                double dum = pow(3.0 * M_PI * M_PI * RHO ,1.0/3.0);\n                return dum;\n      };\n\n      auto ks = [=](double RHO) -> double {\n                double temp = sqrt(4.0 * kF(RHO) / M_PI);\n                return temp;\n      };\n\n      auto Fz = [](double ZETA) -> double {\n                double dum = (pow((1.0 + ZETA) ,4.0/3.0) + pow((1.0 - ZETA) ,4.0/3.0) - 2.0) / (2.0 * pow(2.0,1.0/3.0) - 2.0);\n                return dum;\n      };\n\n      auto t = [=](double RHO, double SIGMA, double ZETA) -> double {\n               double temp = sqrt(SIGMA) / (2.0 * ks(RHO) * Fi(ZETA) * RHO);\n               return temp;\n      };\n\n      auto G = [](double r, double T, double a1, double b1, double b2, double b3, double b4, double p) -> double {\n               double dum = -2.0 * T * (1.0 + a1 * r) * log(1.0 + 0.5 * pow(T * (b1 * sqrt(r) + b2 * r + b3 * pow(r,3.0/2.0) + b4 * pow(r, p+1.0)) ,-1.0));\n               return dum;\n\n      };\n\n      auto Ac = [=](double r) -> double {\n                double temp = -G(r,Aa,a1a,b1a,b2a,b3a,b4a,pa);\n                return temp;\n      };\n\n      auto EcP = [=](double r) -> double {\n                 double dum = G(r,c0p,a1p,b1p,b2p,b3p,b4p,pe);\n                 return dum;\n      };\n\n      auto EcF = [=](double r) -> double {\n                 double dumm = G(r,c0f,a1f,b1f,b2f,b3f,b4f,pe);\n                 return dumm;\n      };\n\n      auto Ec = [=](double r, double ZETA) -> double {\n                double dum = EcP(r) + ( Ac(r) * Fz(ZETA) * (1.0 - pow(ZETA ,4.0)) ) / d2Fz + ( EcF(r) - EcP(r) ) * Fz(ZETA) * pow(ZETA ,4.0);\n                return dum;\n      };\n\n      auto A = [=](double r, double ZETA) -> double {\n               double dum = (BETA/GAMMA) * pow( exp(-Ec(r,ZETA) / (pow(Fi(ZETA),3.0) * GAMMA)) - 1.0, -1.0);\n               return dum;\n      };\n\n      auto H = [=](double RHO, double SIGMA, double r, double ZETA) -> double {\n               double temp = pow(Fi(ZETA),3.0) * GAMMA * log(1.0 + (BETA/GAMMA) * pow(t(RHO,SIGMA,ZETA) ,2.0) * (1.0 + A(r,ZETA) * pow(t(RHO,SIGMA,ZETA),2.0))\n                           / (1.0 + A(r,ZETA) * pow(t(RHO,SIGMA,ZETA),2.0) + pow(A(r,ZETA),2.0) * pow(t(RHO,SIGMA,ZETA),4.0)));\n               return temp;\n      };\n\n      double exc = 0.0;\n      for (int p = 0; p < npts; p++) {\n          double rhoa = rho_a(p);\n          double rhob = rho_b(p);\n          double rho = rhoa + rhob;\n          double zeta = (rhoa - rhob) / rho;\n          double rs =  pow( 3.0 / ( 4.0 * M_PI * rho) , 1.0/3.0 );\n          double sigmaaa = sigma_aa(p);\n          double sigmaab = sigma_ab(p);\n          double sigmabb = sigma_bb(p);\n          double sigma = sigmaaa + sigmabb + 2.0 * sigmaab;\n          if ( rho > tol ) {\n             if ( rhoa < tol ){\n                rho = rhob;\n                sigmabb = std::max(0.0,sigmabb);\n                sigma = sigmabb;\n                zeta = 1.0;\n             }else if ( rhob < tol ){\n                      rho = rhoa;\n                      sigmaaa = std::max(0.0,sigmaaa);\n                      sigma = sigmaaa;\n                      zeta = 1.0;\n             }else/* if (!(rhoa < tol) && !(rhob < tol) ) */{\n                      sigmaaa = std::max(0.0,sigmaaa);\n                      sigmabb = std::max(0.0,sigmabb);\n                      sigma = sigmaaa + sigmabb + 2.0 * sigmaab;\n             }\n             double zk = H(rho,sigma,rs,zeta) + Ec(rs,zeta);\n             exc += rho * zk * W(p);\n          }else{\n                  double zk = 0.0;\n                  exc += rho * zk * W(p);\n               }\n      }\n      return exc;\n   }\n}\n", "meta": {"hexsha": "c1dbde7bf919a5be424badb993d7f36f8b32058b", "size": 11575, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libfunc/functional.cc", "max_stars_repo_name": "SinaMostafanejad/libRDMInoles", "max_stars_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T14:23:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T08:41:55.000Z", "max_issues_repo_path": "src/libfunc/functional.cc", "max_issues_repo_name": "SinaMostafanejad/libRDMInoles", "max_issues_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libfunc/functional.cc", "max_forks_repo_name": "SinaMostafanejad/libRDMInoles", "max_forks_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-13T05:00:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-29T02:39:04.000Z", "avg_line_length": 37.2186495177, "max_line_length": 158, "alphanum_fraction": 0.4138228942, "num_tokens": 3617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6250232163383306}}
{"text": "//\n// Created by krab1k on 02/01/19.\n//\n\n#include <functional>\n#include <string>\n#include <cmath>\n#include <Eigen/LU>\n\n#include \"qeq.h\"\n#include \"../structures/atom.h\"\n#include \"../geometry.h\"\n#include \"../parameters.h\"\n\nCHARGEFW2_METHOD(QEq)\n\n\ndouble QEq::overlap_term(const Atom &atom_i, const Atom &atom_j, const std::string &type) const {\n    auto Ji = parameters_->atom()->parameter(atom::hardness)(atom_i);\n    auto Jj = parameters_->atom()->parameter(atom::hardness)(atom_j);\n    auto Rij = distance(atom_i, atom_j);\n    if (type == \"Nishimoto-Mataga\") {\n        return 1 / (Rij + 2 / (Ji + Jj));\n    } else if (type == \"Nishimoto-Mataga-Weiss\") {\n        const double f = 1.2;\n        return f / (Rij + (2 * f) / (Ji + Jj));\n    } else if (type == \"Ohno\") {\n        return 1 / std::sqrt(Rij * Rij + std::pow(2 / (Ji + Jj), 2));\n    } else if (type == \"Ohno-Klopman\") {\n        return 1 / std::sqrt(Rij * Rij + std::pow(1 / (2 * Ji) + 1 / (2 * Jj), 2));\n    } else if (type == \"DasGupta-Huzinaga\") {\n        const double k = 0.4;\n        return 1 / (Rij + 1 / (Ji / 2 * exp(k * Rij) + Jj / 2 * exp(k * Rij)));\n    } else /* (type == \"Louwen-Vogt\") */ {\n        const double gamma = (Ji + Jj) / 2;\n        return 1 / std::cbrt(1 / std::pow(gamma, 3) + std::pow(Rij, 3));\n    }\n}\n\n\nEigen::VectorXd QEq::EE_system(const std::vector<const Atom *> &atoms, double total_charge) const {\n\n    size_t n = atoms.size();\n\n    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(n + 1, n + 1);\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(n + 1);\n\n    const auto type = get_option_value<std::string>(\"overlap_term\");\n\n    for (size_t i = 0; i < n; i++) {\n        const auto &atom_i = *atoms[i];\n        A(i, i) = parameters_->atom()->parameter(atom::hardness)(atom_i);\n        b(i) = - parameters_->atom()->parameter(atom::electronegativity)(atom_i);\n        for (size_t j = i + 1; j < n; j++) {\n            const auto &atom_j = *atoms[j];\n            auto x = overlap_term(atom_i, atom_j, type);\n            A(i, j) = x;\n            A(j, i) = x;\n        }\n    }\n\n    A.row(n) = Eigen::VectorXd::Constant(n + 1, 1);\n    A.col(n) = Eigen::VectorXd::Constant(n + 1, 1);\n    A(n, n) = 0;\n    b(n) = total_charge;\n\n    return A.partialPivLu().solve(b).head(n);\n}\n\n\nstd::vector<double> QEq::calculate_charges(const Molecule &molecule) const {\n    auto f = [this](const std::vector<const Atom *> &atoms, double total_charge) -> Eigen::VectorXd {\n        return EE_system(atoms, total_charge);\n    };\n\n    Eigen::VectorXd q = solve_EE(molecule, f);\n    return std::vector<double>(q.data(), q.data() + q.size());\n}\n", "meta": {"hexsha": "899ad63a0cca710be12c3ece8fc0dd4b8e128c6b", "size": 2593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/qeq.cpp", "max_stars_repo_name": "danny305/ChargeFW2", "max_stars_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T15:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:38:09.000Z", "max_issues_repo_path": "src/methods/qeq.cpp", "max_issues_repo_name": "danny305/ChargeFW2", "max_issues_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-03-04T21:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T07:11:19.000Z", "max_forks_repo_path": "src/methods/qeq.cpp", "max_forks_repo_name": "danny305/ChargeFW2", "max_forks_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T00:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T05:47:39.000Z", "avg_line_length": 32.8227848101, "max_line_length": 101, "alphanum_fraction": 0.5634400309, "num_tokens": 832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951607140233, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.6249984660526646}}
{"text": "/*********************************************************************\n * BSD 3-Clause License\n *\n * Copyright (c) 2020 Northwestern University\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *  * Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n *\n *  * Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n *\n *  * Neither the name of the copyright holder nor the names of its\n *    contributors may be used to endorse or promote products derived from\n *    this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n/**\n * @file numerics.hpp\n * @author Boston Cleek\n * @date 30 Oct 2020\n * @brief Useful numerical utilities\n */\n#ifndef NUMERICS_HPP\n#define NUMERICS_HPP\n\n#include <cmath>\n#include <algorithm>\n// #include <numbers>\n\n#include <armadillo>\n\n#include <nav_msgs/Path.h>\n#include <tf2/LinearMath/Quaternion.h>\n\n#include <ergodic_exploration/collision.hpp>\n\nnamespace ergodic_exploration\n{\nusing arma::mat;\nusing arma::vec;\n\n// TODO: why gcc cant find numbers\nconstexpr double PI = 3.14159265358979323846;\n\n/**\n * @brief approximately compare two floating-point numbers\n * @param d1 - a number to compare\n * @param d2 - a second number to compare\n * @param epsilon - absolute threshold required for equality\n * @return true if abs(d1 - d2) < epsilon\n */\ninline bool almost_equal(double d1, double d2, double epsilon = 1.0e-12)\n{\n  return std::fabs(d1 - d2) < epsilon ? true : false;\n}\n\n/**\n * @brief Wraps angle between -pi and pi\n * @param rad - angle in radians\n * @return wrapped angle in radians\n */\ninline double normalize_angle_PI(double rad)\n{\n  // floating point remainder essentially this is fmod\n  const auto q = std::floor((rad + PI) / (2.0 * PI));\n  rad = (rad + PI) - q * 2.0 * PI;\n\n  if (rad < 0.0)\n  {\n    rad += 2.0 * PI;\n  }\n\n  return (rad - PI);\n}\n\n/**\n * @brief Wraps angle between 0 and 2pi or 0 to -2pi\n * @param rad - angle in radians\n * @return wrapped angle in radians\n */\ninline double normalize_angle_2PI(double rad)\n{\n  // floating point remainder essentially this is fmod\n  const auto q = std::floor(rad / (2.0 * PI));\n  rad = (rad)-q * 2.0 * PI;\n\n  if (rad < 0.0)\n  {\n    rad += 2.0 * PI;\n  }\n\n  return rad;\n}\n\n/**\n * @brief Get yaw from quaternion\n * @param qx - x-axis rotation component\n * @param qy - y-axis rotation component\n * @param qz - z-axis rotation component\n * @param qw - rotation magnitude\n * @return yaw (rad)\n */\ninline double getYaw(double qx, double qy, double qz, double qw)\n{\n  // TODO: add unit test\n  // Source: https://github.com/ros/geometry2/blob/noetic-devel/tf2/include/tf2/impl/utils.h#L122\n  const auto sqx = qx * qx;\n  const auto sqy = qy * qy;\n  const auto sqz = qz * qz;\n  const auto sqw = qw * qw;\n\n  // Normalization added from urdfom_headers\n  const auto sarg = -2.0 * (qx * qz - qw * qy) / (sqx + sqy + sqz + sqw);\n\n  // Cases derived from https://orbitalstation.wordpress.com/tag/quaternion/\n  if (sarg < -0.99999 || almost_equal(sarg, -0.99999))\n  {\n    return -2.0 * std::atan2(qy, qx);\n  }\n\n  else if (sarg > 0.99999 || almost_equal(sarg, 0.99999))\n  {\n    return 2.0 * std::atan2(qy, qx);\n  }\n\n  return std::atan2(2.0 * (qx * qy + qw * qz), sqw + sqx - sqy - sqz);\n}\n\n/**\n * @brief Euclidean distance between two points\n * @param x0 - x-position point 0\n * @param y0 - y-position point 0\n * @param x1 - x-position point 1\n * @param y1 - y-position point 1\n * @return euclidean distance\n */\ninline double distance(double x0, double y0, double x1, double y1)\n{\n  const auto dx = x1 - x0;\n  const auto dy = y1 - y0;\n  return std::sqrt(dx * dx + dy * dy);\n}\n\n/**\n * @brief Entropy of a single grid cell\n * @param p - probability grid cell is occupied represented as a decimal\n * @return entropy\n */\ninline double entropy(double p)\n{\n  // Assign zero information gain\n  if (almost_equal(0.0, p) || almost_equal(1.0, p) /*|| p < 0.0*/)\n  {\n    return 1e-3;\n  }\n\n  // unknowm: p = -1 => entropy(0.5) = 0.7\n  else if (p < 0.0)\n  {\n    return 0.7;\n  }\n\n  return -p * std::log(p) - (1.0 - p) * std::log(1.0 - p);\n}\n\n/**\n * @brief Convert polar to cartesian coordinates\n * @param angle - angle in radians\n * @param range - range measurement\n */\ninline vec polar2Cartesian(double angle, double range)\n{\n  const auto x = range * std::cos(angle);\n  const auto y = range * std::sin(angle);\n  return { x, y };\n}\n\n/**\n * @brief Convert polar to cartesian homogenous coordinates\n * @param angle - angle in radians\n * @param range - range measurement\n */\ninline vec polar2CartesianHomo(double angle, double range)\n{\n  const auto x = range * std::cos(angle);\n  const auto y = range * std::sin(angle);\n  return { x, y, 1.0 };\n}\n\n/**\n * @brief Construct 2D transformation matrix\n * @param x - x position\n * @param y - y position\n * @param angle - yaw in radians\n * @details 2D transformation\n */\ninline mat transform2d(double x, double y, double angle)\n{\n  const mat trans2d = { { std::cos(angle), -std::sin(angle), x },\n                        { std::sin(angle), std::cos(angle), y },\n                        { 0.0, 0.0, 1.0 } };\n\n  return trans2d;\n}\n\n/**\n * @brief Construct 2D transformation matrix\n * @param x - x position\n * @param y - y position\n * @details 2D transformation\n */\ninline mat transform2d(double x, double y)\n{\n  const mat trans2d = { { 1.0, 0.0, x }, { 0.0, 1.0, y }, { 0.0, 0.0, 1.0 } };\n\n  return trans2d;\n}\n\n/**\n * @brief Construct 2D transformation\n * @param angle - yaw in radians\n * @details 2D transformation\n */\ninline mat transform2d(double angle)\n{\n  const mat trans2d = { { std::cos(angle), -std::sin(angle), 0.0 },\n                        { std::sin(angle), std::cos(angle), 0.0 },\n                        { 0.0, 0.0, 1.0 } };\n  return trans2d;\n}\n\n/**\n * @brief Construct 2D transformation inverse\n * @param trans2d - 2D transformation\n * @details 2D transformation inverse\n */\ninline mat transform2dInv(const mat& trans2d)\n{\n  // R^T flip sign in sin\n  const auto stheta = -trans2d(1, 0);\n  const auto ctheta = trans2d(0, 0);\n  const auto theta = std::atan2(stheta, ctheta);\n\n  // p' = -R^T * p\n  const auto x = -(ctheta * trans2d(0, 2) - stheta * trans2d(1, 2));\n  const auto y = -(stheta * trans2d(0, 2) + ctheta * trans2d(1, 2));\n\n  return transform2d(theta, x, y);\n}\n\n/**\n * @brief Integrate a constant twist\n * @param x - current state [x, y, theta]\n * @param vb - current twist [vx, vy, w]\n * @param dt - time step\n * @return new pose\n */\ninline vec integrate_twist(const vec& x, const vec& u, double dt)\n{\n  // Eqn. 13.35 and 13.36 pg 471 Modern Robotics\n  // displacement b to b' (dx, dy, dth)\n  vec dqb(3);\n\n  // no rotation\n  if (almost_equal(u(2), 0.0))\n  {\n    dqb(0) = u(0) * dt;\n    dqb(1) = u(1) * dt;\n    dqb(2) = 0.0;\n  }\n\n  else\n  {\n    const vec vb = u * dt;\n    dqb(0) = (vb(0) * std::sin(vb(2)) + vb(1) * (std::cos(vb(2)) - 1.0)) / vb(2);\n\n    dqb(1) = (vb(1) * std::sin(vb(2)) + vb(0) * (1.0 - std::cos(vb(2)))) / vb(2);\n\n    dqb(2) = vb(2);\n  }\n\n  return x + transform2d(x(2)) * dqb;\n}\n\n/**\n * @brief Determine if control will cause a collision\n * @param collision - collision detector\n * @param grid - grid map\n * @param x0 - initial state\n * @param u - twist [vx, vy, w]\n * @param dt - time step in integration\n * @param horizon - length of integration\n * @return true if the control is collision free\n * @details The control is assumed to be constant and a twist is\n * integrated for a fixed amout of time\n */\ninline bool validate_control(const Collision& collision, const GridMap& grid,\n                             const vec& x0, const vec& u, double dt, double horizon)\n{\n  vec x = x0;\n  const auto steps = static_cast<unsigned int>(std::abs(horizon / dt));\n\n  for (unsigned int i = 0; i < steps; i++)\n  {\n    x = integrate_twist(x, u, dt);\n    x(2) = normalize_angle_PI(x(2));\n\n    if (collision.collisionCheck(grid, x))\n    {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n/**\n * @brief Visualize path from following a constant twist\n * @param x0 - current state\n * @param u - twist [vx, vy, w]\n * @param dt - time step\n * @param horizon - control horizon\n * @return trajectory\n */\ninline nav_msgs::Path constTwistPath(const std::string& map_frame_id, const vec& x0,\n                                     const vec& u, double dt, double horizon)\n{\n  nav_msgs::Path path;\n  path.header.frame_id = map_frame_id;\n\n  const auto steps = static_cast<unsigned int>(std::abs(horizon / dt));\n  path.poses.resize(steps);\n\n  vec x = x0;\n  for (unsigned int i = 0; i < steps; i++)\n  {\n    x = integrate_twist(x, u, dt);\n\n    path.poses.at(i).pose.position.x = x(0);\n    path.poses.at(i).pose.position.y = x(1);\n\n    tf2::Quaternion quat;\n    quat.setRPY(0.0, 0.0, normalize_angle_PI(x(2)));\n\n    path.poses.at(i).pose.orientation.x = quat.x();\n    path.poses.at(i).pose.orientation.y = quat.y();\n    path.poses.at(i).pose.orientation.z = quat.z();\n    path.poses.at(i).pose.orientation.w = quat.w();\n  }\n\n  return path;\n}\n\n}  // namespace ergodic_exploration\n#endif\n", "meta": {"hexsha": "6c8001ba2dac3b8929536a050344119d4c424f40", "size": 10117, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ergodic_exploration/numerics.hpp", "max_stars_repo_name": "bostoncleek/ergodic_exploration", "max_stars_repo_head_hexsha": "430e8293fc864af10088606ed07ed2d74c6a97d5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T22:04:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T09:21:27.000Z", "max_issues_repo_path": "include/ergodic_exploration/numerics.hpp", "max_issues_repo_name": "bostoncleek/ergodic_exploration", "max_issues_repo_head_hexsha": "430e8293fc864af10088606ed07ed2d74c6a97d5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ergodic_exploration/numerics.hpp", "max_forks_repo_name": "bostoncleek/ergodic_exploration", "max_forks_repo_head_hexsha": "430e8293fc864af10088606ed07ed2d74c6a97d5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-02-03T07:17:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T14:41:19.000Z", "avg_line_length": 27.269541779, "max_line_length": 97, "alphanum_fraction": 0.6362558071, "num_tokens": 2974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6249809173045126}}
{"text": "#include <armadillo>\n\nusing namespace arma;\n\narma::mat COMMON_TEST_WEIGHTS = {\n    {1, 1, 2},\n    {0, 0, 0},\n    {1, 0, 10},\n    {5000, 1, 10},\n    {-10, -3, -7},\n    {-10, 3, -7},\n};\n\narma::mat SIGNALS = {\n    {1, 0, 0, 0},\n    {0, 1, 0, 1},\n    {1, 1, 0, 0},\n};\n\nmat create_signals()\n{\n    mat signals = {{1, 0, 0, 0},\n                   {0, 1, 0, 1},\n                   {1, 1, 0, 0}};\n\n    return signals;\n}\n\nmat sum_signal(mat weights, mat signals)\n{\n    return weights * signals;\n}\n\nbool is_equal(mat x, mat y, float threshold = 0.001)\n{\n    return approx_equal(x, y, \"absdiff\", threshold);\n}\n\ntemplate <typename T>\nclass SolverTester\n{\npublic:\n    T m_solver;\n    arma::mat m_signals;\n\n    SolverTester(T solver)\n    {\n        m_solver = solver;\n        set_up();\n    }\n\n    void set_up()\n    {\n        m_signals = SIGNALS;\n        m_solver.set_library(m_signals);\n    }\n\n    mat model(mat weights, mat signals)\n    {\n        return weights * signals;\n    }\n\n    void test_solve(arma::mat weights, float tolerance = 0.001)\n    {\n        mat signal = model(weights, m_signals);\n        mat result = m_solver.solve(signal);\n        BOOST_TEST_MESSAGE(boost::unit_test::framework::current_test_case().p_name);\n        BOOST_TEST_MESSAGE(\"Expected: \" << weights);\n        BOOST_TEST_MESSAGE(\"Actual: \" << result);\n        BOOST_CHECK(is_equal(weights, result, tolerance));\n    }\n\n    void test_multiple_solve(arma::mat weights, float tolerance = 0.001)\n    {\n        for (int row = 0; row < weights.n_rows; row++)\n        {\n            arma::mat test_weights = weights.row(row);\n            set_up();\n            test_solve(test_weights, tolerance);\n        }\n    }\n\n    void test_state(arma::mat weights, float tolerance = 0.001)\n    {\n        // Test that solver produces same result without initialization of solver between\n        // State of the solver should not affect to result\n        set_up();\n        test_solve(weights, tolerance);\n        test_solve(weights, tolerance);\n    }\n\n    void test_common(float tolerance = 0.001)\n    {\n        arma::mat weights = {1, 1, 2};\n        test_state(weights, tolerance);\n        test_multiple_solve(COMMON_TEST_WEIGHTS, tolerance);\n    }\n};", "meta": {"hexsha": "1de7a0136ae81bb566b35f1b29c3a882fccb9b4f", "size": 2193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_utils.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": "tests/test_utils.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": "tests/test_utils.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": 22.3775510204, "max_line_length": 89, "alphanum_fraction": 0.5722754218, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6249672097628717}}
{"text": "#ifndef VECTOR3D_HEADER_DEFINED\n#define VECTOR3D_HEADER_DEFINED\n\n//#include <boost/functional/hash.hpp>\n\n\nconst double EPS_DBL = 1e-12;\n\nstruct vector3d{\n    double x;\n    double y;\n    double z;\n    \n    vector3d(double x_ = 0.0, double y_ = 0.0, double z_ = 0.0) : x(x_), y(y_), z(z_) {}\n    \n    double operator *(const vector3d& vec) const{\n        return x * vec.x + y * vec.y + z * vec.z;\n    }\n    vector3d operator / (double d) const {\n        return vector3d(x / d, y / d, z / d);\n    }\n    vector3d norm() const{\n        return *this / sqrt(*this * *this);\n    }\n    double length() const{\n        return sqrt(*this * *this);\n    }\n    double angle(const vector3d& vec) const{\n        return acos((*this * vec)/((*this).length() * vec.length()));\n    }\n    double distxy(const vector3d& vec) const{\n        return sqrt((x-vec.x)*(x-vec.x)+(y-vec.y)*(y-vec.y));\n    }\n    vector3d operator ^ (const vector3d& vec) const{\n        return vector3d(y*vec.z-z*vec.y, z*vec.x-x*vec.z,x*vec.y-y*vec.x);\n    }\n    vector3d operator + (const vector3d& vec) const{\n        return vector3d(x+vec.x,y+vec.y,z+vec.z);\n    }\n    vector3d operator - (const vector3d& vec) const{\n        return vector3d(x-vec.x,y-vec.y,z-vec.z);\n    }\n    \n    bool operator < (const vector3d& vec) const{\n        if(x<vec.x){\n            return true;\n        }\n        else if(((x-vec.x)<EPS_DBL) && (y<vec.y)){\n            return true;\n        }\n        else{\n            return false;\n        }\n    }\n    bool operator == (const vector3d& vec) const{\n        return (std::abs(x-vec.x)<EPS_DBL) && (std::abs(y-vec.y)<EPS_DBL);\n    }\n};\n\ninline std::ostream& operator << (std::ostream& os, const vector3d& vec){\n    os << \"<\" << vec.x << \", \" << vec.y << \", \" << vec.z << \">\";\n    return os;\n}\n\nstruct hash {\n    size_t operator() (const vector3d& vec) const {\n //       size_t seed = 0;\n //       boost::hash_combine(seed, vec.x);\n //       boost::hash_combine(seed, vec.y);\n //       return seed;\n    return std::hash<int>() ((int)(vec.y/25.0))+(((int)(vec.x/25.0)) << 16);\n        //        return (size_t)vec.y+((size_t)vec.x << 32);\n    }\n};\n\n#endif // VECTOR3D_HEADER_DEFINED\n", "meta": {"hexsha": "6967512f355b5bde0db54967de57145fd9a4ff9f", "size": 2160, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sources/vector3d.hpp", "max_stars_repo_name": "alexxxzzz/ValaisSun", "max_stars_repo_head_hexsha": "fca2610bf2f68df4c82a36e3f9464ca8f2de0b06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sources/vector3d.hpp", "max_issues_repo_name": "alexxxzzz/ValaisSun", "max_issues_repo_head_hexsha": "fca2610bf2f68df4c82a36e3f9464ca8f2de0b06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sources/vector3d.hpp", "max_forks_repo_name": "alexxxzzz/ValaisSun", "max_forks_repo_head_hexsha": "fca2610bf2f68df4c82a36e3f9464ca8f2de0b06", "max_forks_repo_licenses": ["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.0519480519, "max_line_length": 88, "alphanum_fraction": 0.5416666667, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.6249671990432477}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// weighted_median.hpp\n//\n//  Copyright 2006 Eric Niebler, Olivier Gygi. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_MEDIAN_HPP_EAN_28_10_2005\n#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_MEDIAN_HPP_EAN_28_10_2005\n\n#include <boost/mpl/placeholders.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/median.hpp>\n#include <boost/accumulators/statistics/weighted_p_square_quantile.hpp>\n#include <boost/accumulators/statistics/weighted_density.hpp>\n#include <boost/accumulators/statistics/weighted_p_square_cumulative_distribution.hpp>\n\nnamespace boost { namespace accumulators\n{\n\nnamespace impl\n{\n    ///////////////////////////////////////////////////////////////////////////////\n    // weighted_median_impl\n    //\n    /**\n        @brief Median estimation for weighted samples based on the \\f$P^2\\f$ quantile estimator\n\n        The \\f$P^2\\f$ algorithm for weighted samples is invoked with a quantile probability of 0.5.\n    */\n    template<typename Sample>\n    struct weighted_median_impl\n      : accumulator_base\n    {\n        // for boost::result_of\n        typedef typename numeric::functional::average<Sample, std::size_t>::result_type result_type;\n\n        weighted_median_impl(dont_care) {}\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            return weighted_p_square_quantile_for_median(args);\n        }\n    };\n\n    ///////////////////////////////////////////////////////////////////////////////\n    // with_density_weighted_median_impl\n    //\n    /**\n        @brief Median estimation for weighted samples based on the density estimator\n\n        The algorithm determines the bin in which the \\f$0.5*cnt\\f$-th sample lies, \\f$cnt\\f$ being\n        the total number of samples. It returns the approximate horizontal position of this sample,\n        based on a linear interpolation inside the bin.\n    */\n    template<typename Sample>\n    struct with_density_weighted_median_impl\n      : accumulator_base\n    {\n        typedef typename numeric::functional::average<Sample, std::size_t>::result_type float_type;\n        typedef std::vector<std::pair<float_type, float_type> > histogram_type;\n        typedef iterator_range<typename histogram_type::iterator> range_type;\n        // for boost::result_of\n        typedef float_type result_type;\n\n        template<typename Args>\n        with_density_weighted_median_impl(Args const &args)\n          : sum(numeric::average(args[sample | Sample()], (std::size_t)1))\n          , is_dirty(true)\n        {\n        }\n\n        void operator ()(dont_care)\n        {\n            this->is_dirty = true;\n        }\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            if (this->is_dirty)\n            {\n                this->is_dirty = false;\n\n                std::size_t cnt = count(args);\n                range_type histogram = weighted_density(args);\n                typename range_type::iterator it = histogram.begin();\n                while (this->sum < 0.5 * cnt)\n                {\n                    this->sum += it->second * cnt;\n                    ++it;\n                }\n                --it;\n                float_type over = numeric::average(this->sum - 0.5 * cnt, it->second * cnt);\n                this->median = it->first * over + (it + 1)->first * ( 1. - over );\n            }\n\n            return this->median;\n        }\n\n    private:\n        mutable float_type sum;\n        mutable bool is_dirty;\n        mutable float_type median;\n    };\n\n    ///////////////////////////////////////////////////////////////////////////////\n    // with_p_square_cumulative_distribution_weighted_median_impl\n    //\n    /**\n        @brief Median estimation for weighted samples based on the \\f$P^2\\f$ cumulative distribution estimator\n\n        The algorithm determines the first (leftmost) bin with a height exceeding 0.5. It\n        returns the approximate horizontal position of where the cumulative distribution\n        equals 0.5, based on a linear interpolation inside the bin.\n    */\n    template<typename Sample, typename Weight>\n    struct with_p_square_cumulative_distribution_weighted_median_impl\n      : accumulator_base\n    {\n        typedef typename numeric::functional::multiplies<Sample, Weight>::result_type weighted_sample;\n        typedef typename numeric::functional::average<weighted_sample, std::size_t>::result_type float_type;\n        typedef std::vector<std::pair<float_type, float_type> > histogram_type;\n        typedef iterator_range<typename histogram_type::iterator> range_type;\n        // for boost::result_of\n        typedef float_type result_type;\n\n        with_p_square_cumulative_distribution_weighted_median_impl(dont_care)\n          : is_dirty(true)\n        {\n        }\n\n        void operator ()(dont_care)\n        {\n            this->is_dirty = true;\n        }\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            if (this->is_dirty)\n            {\n                this->is_dirty = false;\n\n                range_type histogram = weighted_p_square_cumulative_distribution(args);\n                typename range_type::iterator it = histogram.begin();\n                while (it->second < 0.5)\n                {\n                    ++it;\n                }\n                float_type over = numeric::average(it->second - 0.5, it->second - (it - 1)->second);\n                this->median = it->first * over + (it + 1)->first * ( 1. - over );\n            }\n\n            return this->median;\n        }\n    private:\n        mutable bool is_dirty;\n        mutable float_type median;\n    };\n\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::weighted_median\n// tag::with_density_weighted_median\n// tag::with_p_square_cumulative_distribution_weighted_median\n//\nnamespace tag\n{\n    struct weighted_median\n      : depends_on<weighted_p_square_quantile_for_median>\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::weighted_median_impl<mpl::_1> impl;\n    };\n    struct with_density_weighted_median\n      : depends_on<count, weighted_density>\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::with_density_weighted_median_impl<mpl::_1> impl;\n    };\n    struct with_p_square_cumulative_distribution_weighted_median\n      : depends_on<weighted_p_square_cumulative_distribution>\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::with_p_square_cumulative_distribution_weighted_median_impl<mpl::_1, mpl::_2> impl;\n    };\n\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::weighted_median\n//\nnamespace extract\n{\n    extractor<tag::median> const weighted_median = {};\n}\n\nusing extract::weighted_median;\n// weighted_median(with_p_square_quantile) -> weighted_median\ntemplate<>\nstruct as_feature<tag::weighted_median(with_p_square_quantile)>\n{\n    typedef tag::weighted_median type;\n};\n\n// weighted_median(with_density) -> with_density_weighted_median\ntemplate<>\nstruct as_feature<tag::weighted_median(with_density)>\n{\n    typedef tag::with_density_weighted_median type;\n};\n\n// weighted_median(with_p_square_cumulative_distribution) -> with_p_square_cumulative_distribution_weighted_median\ntemplate<>\nstruct as_feature<tag::weighted_median(with_p_square_cumulative_distribution)>\n{\n    typedef tag::with_p_square_cumulative_distribution_weighted_median type;\n};\n\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "8109d17e506f3182e139fe80a636cec3fa99fd36", "size": 8166, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/accumulators/statistics/weighted_median.hpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-04-23T04:55:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T10:26:27.000Z", "max_issues_repo_path": "boost/accumulators/statistics/weighted_median.hpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T20:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-18T08:56:40.000Z", "max_forks_repo_path": "boost/accumulators/statistics/weighted_median.hpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T13:16:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:13:14.000Z", "avg_line_length": 34.6016949153, "max_line_length": 118, "alphanum_fraction": 0.6282145481, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7122321720225279, "lm_q1q2_score": 0.6249671982475417}}
{"text": "// (C) Copyright David Gleich 2007\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0 (See accompanying file\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\n\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/core_numbers.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <stdio.h>\n\nusing namespace boost;\n\nconst char* errstr = \"\";\n\nint test_1() {\n    // core numbers of sample graph\n    typedef adjacency_list<vecS,vecS,undirectedS> Graph;\n\n    Graph G(21);\n    add_edge(0,1,G);\n    add_edge(1,2,G);\n    add_edge(1,3,G);\n    add_edge(2,3,G);\n    add_edge(1,4,G);\n    add_edge(3,4,G);\n    add_edge(4,5,G);\n    add_edge(4,6,G);\n    add_edge(5,6,G);\n    add_edge(4,7,G);\n    add_edge(5,7,G);\n    add_edge(6,7,G);\n    add_edge(7,8,G);\n    add_edge(3,9,G);\n    add_edge(8,9,G);\n    add_edge(8,10,G);\n    add_edge(9,10,G);\n    add_edge(10,11,G);\n    add_edge(10,12,G);\n    add_edge(3,13,G);\n    add_edge(9,13,G);\n    add_edge(3,14,G);\n    add_edge(9,14,G);\n    add_edge(13,14,G);\n    add_edge(16,17,G);\n    add_edge(16,18,G);\n    add_edge(17,19,G);\n    add_edge(18,19,G);\n    add_edge(19,20,G);\n\n    std::vector<int> core_nums(num_vertices(G));\n    core_numbers(G,\n        make_iterator_property_map(core_nums.begin(), get(vertex_index,G)));\n\n    for (size_t i=0; i<num_vertices(G); ++i) {\n        printf(\"vertex %3lu : %i\\n\", (unsigned long)i, core_nums[i]);\n    }\n\n    int correct[21]={1,2,2,3,3,3,3,3,2,3,2,1,1,3,3,0,2,2,2,2,1};\n    for (size_t i=0; i<num_vertices(G); ++i) {\n        if (core_nums[i] != correct[i]) {\n            return 1; // error!\n        }\n    }\n    return 0;\n}\n\nint test_2() {\n    // core numbers of sample graph\n    typedef adjacency_list < listS, vecS, undirectedS,\n        no_property, property < edge_weight_t, int > > graph_t;\n    int num_nodes = 3;\n    typedef std::pair<int,int> Edge;\n\n    Edge edge_array[] = { Edge(0,1), Edge(0,2), Edge(1,2) };\n    int weights[] = {-1, -2, -2};\n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n    graph_t G(edge_array, edge_array + num_arcs, weights, num_nodes);\n    property_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, G);\n\n    std::vector<int> core_nums(num_vertices(G));\n    weighted_core_numbers(G,\n        make_iterator_property_map(core_nums.begin(), get(vertex_index,G)));\n\n    for (size_t i=0; i<num_vertices(G); ++i) {\n        printf(\"vertex %3lu : %i\\n\", (unsigned long)i, core_nums[i]);\n    }\n\n    int correct[3]={-1,-1,-4};\n    for (size_t i=0; i<num_vertices(G); ++i) {\n        if (core_nums[i] != correct[i]) {\n            return 1; // error!\n        }\n    }\n    return 0;\n}\n\nint test_3() {\n    // core numbers of a directed graph, the core numbers of a directed\n    // cycle are always one\n    typedef adjacency_list < vecS, vecS, directedS > graph_t;\n    int num_nodes = 5;\n    typedef std::pair<int,int> Edge;\n\n    Edge edge_array[] = { Edge(0,1),Edge(1,2),Edge(2,3),Edge(3,4),Edge(4,0) };\n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n    graph_t G(edge_array, edge_array + num_arcs, num_nodes);\n\n    std::vector<int> core_nums(num_vertices(G));\n    core_numbers(G,\n        make_iterator_property_map(core_nums.begin(), get(vertex_index,G)));\n\n    for (size_t i=0; i<num_vertices(G); ++i) {\n        printf(\"vertex %3lu : %i\\n\", (unsigned long)i, core_nums[i]);\n    }\n\n    int correct[5]={1,1,1,1,1};\n    for (size_t i=0; i<num_vertices(G); ++i) {\n        if (core_nums[i] != correct[i]) {\n            return 1; // error!\n        }\n    }\n    return 0;\n}\n\nint main(int, char **) {\n  int nfail = 0, ntotal = 0;\n  int rval;\n\n  const char* name;\n\n  name= \"core_numbers\";\n  rval= test_1(); ntotal++;\n  if (rval!= 0) { nfail++; printf(\"%20s  %50s\\n\", name, errstr); }\n  else { printf(\"%20s  success\\n\", name); }\n\n  name= \"weighted_core_numbers\";\n  rval= test_2(); ntotal++;\n  if (rval!= 0) { nfail++; printf(\"%20s  %50s\\n\", name, errstr); }\n  else { printf(\"%20s  success\\n\", name); }\n\n  name= \"directed_corenums\";\n  rval= test_3(); ntotal++;\n  if (rval!= 0) { nfail++; printf(\"%20s  %50s\\n\", name, errstr); }\n  else { printf(\"%20s  success\\n\", name); }\n\n  printf(\"\\n\");\n  printf(\"Total tests  : %3i\\n\", ntotal);\n  printf(\"Total failed : %3i\\n\", nfail);\n\n  return nfail!=0;\n}\n", "meta": {"hexsha": "733bf4a6fef6888c2af71c124fa05f3bb4877ad9", "size": 4286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/test/core_numbers_test.cpp", "max_stars_repo_name": "AishwaryaDoosa/Boost1.49", "max_stars_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/graph/test/core_numbers_test.cpp", "max_issues_repo_name": "ksundberg/boost-svn", "max_issues_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/graph/test/core_numbers_test.cpp", "max_forks_repo_name": "ksundberg/boost-svn", "max_forks_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "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": 27.4743589744, "max_line_length": 79, "alphanum_fraction": 0.5998600093, "num_tokens": 1392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7879312006227323, "lm_q1q2_score": 0.6249129243375313}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"../Optimizer/optimizer\"\nusing namespace std;\nusing namespace Eigen;\n\ndouble func (double x) {\n    return pow(x + 10, 2);\n}\n\nint main () {\n    cout << \"Using Function: (x + 10)^2 for single variable algorithms testing.\" << endl;\n    cout << \"Test Bounding Phase:\" << endl;\n    double ipt = 5.4;\n    Vector2d range = boundingPhase(func, ipt);\n    cout << \"Range from bounding Phase for initial point :\" << ipt << endl;\n    cout << range << endl;\n\n    cout << \"Derivatives at \" << ipt << endl;\n    cout << derivative(func, ipt) << endl;\n\n    cout << \"Finding optimal point using above range for Newton Rapshon Method.\" << endl;\n    cout << \"Optimal Point is: \";\n    cout << newtonRapshon (func, range) << endl;;\n}\n", "meta": {"hexsha": "23ac842841c80b701ccac4de3f843e9062ff871b", "size": 764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/test.cpp", "max_stars_repo_name": "kembolino/Optimizer", "max_stars_repo_head_hexsha": "f636b42d6ae82ab0a3eb9f8fcb4b2389bdffb880", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/test.cpp", "max_issues_repo_name": "kembolino/Optimizer", "max_issues_repo_head_hexsha": "f636b42d6ae82ab0a3eb9f8fcb4b2389bdffb880", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests/test.cpp", "max_forks_repo_name": "kembolino/Optimizer", "max_forks_repo_head_hexsha": "f636b42d6ae82ab0a3eb9f8fcb4b2389bdffb880", "max_forks_repo_licenses": ["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.3846153846, "max_line_length": 89, "alphanum_fraction": 0.6282722513, "num_tokens": 200, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6247081353959922}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_LINEARALGEBRA_HPP\n#define RW_MATH_LINEARALGEBRA_HPP\n\n/**\n * @file LinearAlgebra.hpp\n */\n#if !defined(SWIG)\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <limits>\n#endif \nnamespace rw { namespace math {\n\n    /** @addtogroup math */\n    /* @{*/\n\n    /**\n     * @brief Collection of Linear Algebra functions\n     */\n    class LinearAlgebra\n    {\n      public:\n        //! @brief Type for Eigen matrices used to reduce namespace cluttering.\n        template< class T = double > struct EigenMatrix\n        {\n            //! type of this matrix\n            typedef Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > type;\n        };\n\n        //! @brief Type for Eigen vectors, used to reduce namespace cluttering.\n        template< class T = double > struct EigenVector\n        {\n            //! type of this Vector\n            typedef Eigen::Matrix< T, Eigen::Dynamic, 1 > type;\n        };\n\n        /**\n         * @brief Performs a singular value decomposition (SVD)\n         *\n         * The SVD computes the decomposition\n         * \\f$ \\mathbf{M}=\\mathbf{U}*\\mathbf{DiagonalMatrix(\\sigma)}*\\mathbf{V}^T \\f$ .\n         *\n         * @param M [in] the matrix to decomposite\n         * @param U [out] Result matrix \\f$\\mathbf{U}\\f$\n         * @param sigma [out] The \\f$\\mathbf{sigma}\\f$ vector with diagonal elements\n         * @param V [out] Result matrix \\f$\\mathbf{V}\\f$\n         */\n        static void svd (const Eigen::Matrix<double,-1,-1>& M, Eigen::Matrix<double,-1,-1>& U, Eigen::Matrix<double,-1,1>& sigma,\n                         Eigen::Matrix<double,-1,-1>& V);\n\n        /**\n         * \\brief Calculates the moore-penrose (pseudo) inverse of a matrix\n         * @f$ \\mathbf{M}^+@f$\n         *\n         * \\param am [in] the matrix @f$ \\mathbf{M} @f$ to be inverted\n         *\n         * \\param precision [in] the precision to use, values below this\n         * treshold are considered singular\n         *\n         * \\return the pseudo-inverse @f$ \\mathbf{M}^+@f$ of @f$ \\mathbf{M} @f$\n         *\n         * \\f$ \\mathbf{M}^+=\\mathbf{V}\\mathbf{\\Sigma} ^+\\mathbf{U}^T \\f$ where\n         * \\f$ \\mathbf{V} \\f$, \\f$ \\mathbf{\\Sigma} \\f$ and \\f$ \\mathbf{U} \\f$\n         * are optained using Singular Value Decomposition (SVD)\n         *\n         *\n         */\n        static Eigen::Matrix<double,-1,-1> pseudoInverse (const Eigen::Matrix<double,-1,-1>& am, double precision = 1e-6);\n\n        /**\n         * @brief Checks the penrose conditions\n         * @param A [in] a matrix\n         * @param X [in] a pseudoinverse of A\n         * @param prec [in] the tolerance\n         *\n         * @return true if the pseudoinverse X of A fullfills the penrose\n         * conditions, false otherwise\n         *\n         * Checks the penrose conditions:\n         *\n         * @f$\n         * AXA = A\n         * @f$\n         *\n         * @f$\n         * XAX = X\n         * @f$\n         *\n         * @f$\n         * (AX)^T = AX\n         * @f$\n         *\n         * @f$\n         * (XA)^T = XA\n         * @f$\n         */\n        static bool checkPenroseConditions (const Eigen::Matrix<double,-1,-1>& A, const Eigen::Matrix<double,-1,-1>& X,\n                                            double prec);\n\n        /**\n         * \\brief Calculates matrix determinant\n         * \\param m [in] a square matrix\n         * \\return the matrix determinant\n         */\n        template< class R > static inline double det (const Eigen::MatrixBase< R >& m)\n        {\n            return m.determinant ();\n        }\n\n        /**\n         * @brief Calculates matrix inverse.\n         * @param M [in] input matrix @f$ \\mathbf{M} @f$ to invert\n         * @return output matrix @f$ \\mathbf{M}^{-1} @f$\n         **/\n        template< class T > static T inverse (const Eigen::MatrixBase< T >& M)\n        {\n            return M.inverse ();\n        }\n\n        /**\n         * @brief Checks if a given matrix is in SO(n) (special orthogonal)\n         * @param M [in] \\f$ \\mathbf{M} \\f$\n         * @return true if \\f$ M\\in SO(n) \\f$\n         *\n         * \\f$ SO(n) = {\\mathbf{R}\\in \\mathbb{R}^{n\\times n} :\n         * \\mathbf{R}\\mathbf{R}^T=\\mathbf{I}, det \\mathbf{R}=+1} \\f$\n         *\n         */\n        template< class R > static inline bool isSO (const Eigen::MatrixBase< R >& M)\n        {\n            return M.cols () == M.rows () && isProperOrthonormal (M);\n        }\n\n        /**\n         * @brief Checks if a given matrix is in SO(n) (special orthogonal)\n         * @param M [in] \\f$ \\mathbf{M} \\f$\n         * @param precision [in] the precision to use for floating point comparison\n         * @return true if \\f$ M\\in SO(n) \\f$\n         *\n         * \\f$ SO(n) = {\\mathbf{R}\\in \\mathbb{R}^{n\\times n} :\n         * \\mathbf{R}\\mathbf{R}^T=\\mathbf{I}, det \\mathbf{R}=+1} \\f$\n         *\n         */\n        template< class R >\n        static inline bool isSO (const Eigen::MatrixBase< R >& M, typename R::Scalar precision)\n        {\n            return M.cols () == M.rows () && isProperOrthonormal (M, precision);\n        }\n\n        /**\n         * @brief Checks if a given matrix is skew-symmetrical\n         * @param M [in] \\f$ \\mathbf{M} \\f$ the matrix to check\n         *\n         * @return true if the property\n         * \\f$ \\mathbf{M}=-\\mathbf{M}^T \\f$ holds,\n         * false otherwise.\n         */\n        template< class R > static inline bool isSkewSymmetric (const Eigen::MatrixBase< R >& M)\n        {\n            return (M + M.transpose ()).template lpNorm< Eigen::Infinity > () == 0.0;\n        }\n\n        /**\n         * @brief Checks if a given matrix is proper orthonormal\n         * @return true if the matrix is proper orthonormal, false otherwise\n         *\n         * A matrix is proper orthonormal if it is orthonormal and its determinant\n         * is equal to \\f$ +1 \\f$\n         */\n        template< class R >\n        static inline bool isProperOrthonormal (\n            const Eigen::MatrixBase< R >& r,\n            typename R::Scalar precision = std::numeric_limits< typename R::Scalar >::epsilon ())\n        {\n            return isOrthonormal (r, precision) && fabs (r.determinant () - 1.0) <= precision;\n        }\n\n        /**\n         * @brief Checks if a given matrix is orthonormal\n         * @return true if the matrix is orthonormal, false otherwise\n         *\n         * A matrix is orthonormal if all of it's column's are mutually orthogonal\n         * and all of it's column's has unit length.\n         *\n         * that is for any \\f$ i, j \\f$ the following holds\n         * \\f$ col_i . col_j = 0 \\f$ and \\f$ ||col_i|| = 1 \\f$\n         *\n         * Another nessesary and sufficient condition of orthonormal matrices is that\n         * \\f$ \\mathbf{M}\\mathbf{M}^T=I \\f$\n         */\n        template< class R >\n        static inline bool isOrthonormal (\n            const Eigen::MatrixBase< R >& r,\n            typename R::Scalar precision = std::numeric_limits< typename R::Scalar >::epsilon ())\n        {\n            return (r * r.transpose ()).isIdentity (precision);\n            // const Eigen::MatrixBase<R> m = r*r.transpose() ;\n            // return m.isIdentity(1e-15);\n            // double scale = m.norm();//m.lpNorm<Eigen::Infinity>();\n            // return scale == 0.0;\n        }\n\n        /**\n         * @brief Decomposition for a symmetric matrix.\n         * @param Am1 [in] a symmetric matrix.\n         * @return the decomposition as a pair with eigenvectors and eigenvalues.\n         */\n        template< class T >\n        // static std::pair<typename EigenMatrix<T>::type, typename EigenVector<T>::type >\n        // eigenDecompositionSymmetric(const typename EigenMatrix<T>::type& Am1)\n        static std::pair< typename EigenMatrix< T >::type, typename EigenVector< T >::type >\n        eigenDecompositionSymmetric (const Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic >& Am1)\n        {\n            Eigen::SelfAdjointEigenSolver< Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > >\n                eigenSolver;\n            eigenSolver.compute (Am1);\n            return std::make_pair (eigenSolver.eigenvectors (), eigenSolver.eigenvalues ());\n        }\n\n        /**\n         * @brief Eigen decomposition of a matrix.\n         * @param Am1 [in] the matrix.\n         * @return the decomposition as a pair with eigenvectors and eigenvalues.\n         */\n        template< class T >\n        static std::pair< typename EigenMatrix< std::complex< T > >::type,\n                          typename EigenVector< std::complex< T > >::type >\n        eigenDecomposition (const typename Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic >& Am1)\n        {\n            Eigen::EigenSolver< Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > > eigenSolver;\n            eigenSolver.compute (Am1);\n\n            Eigen::Matrix< std::complex< T >, Eigen::Dynamic, Eigen::Dynamic > vectors =\n                eigenSolver.eigenvectors ();\n            Eigen::Matrix< std::complex< T >, Eigen::Dynamic, 1 > values =\n                eigenSolver.eigenvalues ();\n            return std::make_pair (vectors, values);\n        }\n\n      private:\n    };\n\n    template<>\n    std::pair< typename LinearAlgebra::EigenMatrix< double >::type,\n               typename LinearAlgebra::EigenVector< double >::type >\n    LinearAlgebra::eigenDecompositionSymmetric< double > (const Eigen::MatrixXd& Am1);\n\n    template<>\n    std::pair< typename LinearAlgebra::EigenMatrix< std::complex< double > >::type,\n               typename LinearAlgebra::EigenVector< std::complex< double > >::type >\n    LinearAlgebra::eigenDecomposition< double > (const Eigen::MatrixXd& Am1);\n\n    /*@}*/\n}}    // namespace rw::math\n\n#endif    // end include guard\n", "meta": {"hexsha": "09dcf2561a0031af732daa987e440cef41eead93", "size": 10487, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/LinearAlgebra.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/LinearAlgebra.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/LinearAlgebra.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2737226277, "max_line_length": 129, "alphanum_fraction": 0.5442929341, "num_tokens": 2674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6246505511970994}}
{"text": "#pragma once\n\n#include <boost/variant.hpp>\n#include <csapex_point_cloud/math/mean.hpp>\n#include <pcl/point_types.h>\n\nnamespace csapex\n{\nnamespace clustering\n{\nclass ColorFeature\n{\npublic:\n    inline void create(...)\n    {\n    }\n\n    inline void create(const pcl::PointXYZI& point)\n    {\n        math::Mean<1> mean;\n        mean.add(point.intensity);\n        color = std::move(mean);\n    }\n\n    inline void create(const pcl::PointXYZRGB& point)\n    {\n        math::Mean<3> mean;\n        mean.add({ static_cast<double>(point.r), static_cast<double>(point.g), static_cast<double>(point.b) });\n        color = std::move(mean);\n    }\n\n    inline void merge(const ColorFeature& other)\n    {\n        static UpdateMean updater;\n        boost::apply_visitor(updater, color, other.color);\n    }\n\n    using DifferenceFunction = double (*)(const Eigen::Vector3d&, const Eigen::Vector3d&, const std::array<double, 3>&);\n\n    inline double difference(const DifferenceFunction& difference_fn, const std::array<double, 3>& weights, const ColorFeature& other) const\n    {\n        return boost::apply_visitor(Difference(difference_fn, weights), color, other.color);\n    }\n\nprivate:\n    struct UpdateMean : boost::static_visitor<void>\n    {\n        template <std::size_t N>\n        void operator()(math::Mean<N>& self, const math::Mean<N>& other) const\n        {\n            self += other;\n        }\n\n        template <std::size_t N1, std::size_t N2, typename = typename std::enable_if<N1 != N2>::type>\n        void operator()(math::Mean<N1>& self, const math::Mean<N2>& other) const\n        {\n        }\n    };\n\n    struct Difference : boost::static_visitor<double>\n    {\n        Difference(const DifferenceFunction& difference_fn, const std::array<double, 3>& weights) : difference_fn_(difference_fn), weights(weights)\n        {\n        }\n\n        /// greyscale case, use direct difference\n        double operator()(const math::Mean<1>& self, const math::Mean<1>& other) const\n        {\n            return std::abs(self.getMean() - other.getMean());\n        }\n\n        /// color case, use color difference function\n        double operator()(const math::Mean<3>& self, const math::Mean<3>& other) const\n        {\n            return difference_fn_(self.getMean(), other.getMean(), weights);\n        }\n\n        template <std::size_t N1, std::size_t N2, typename = typename std::enable_if<N1 != N2>::type>\n        double operator()(const math::Mean<N1>& self, const math::Mean<N2>& other) const\n        {\n            return 0.0;\n        }\n\n    private:\n        const DifferenceFunction& difference_fn_;\n        const std::array<double, 3>& weights;\n    };\n\nprivate:\n    boost::variant<math::Mean<1>, math::Mean<3>> color;\n};\n\n}  // namespace clustering\n}  // namespace csapex\n", "meta": {"hexsha": "65b9c500b676eb5e060ac759dda144bc28cafe0a", "size": 2754, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "csapex_point_cloud/src/clustering/data/feature_color.hpp", "max_stars_repo_name": "AdrianZw/csapex_core_plugins", "max_stars_repo_head_hexsha": "1b23c90af7e552c3fc37c7dda589d751d2aae97f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-02T15:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-06T22:09:33.000Z", "max_issues_repo_path": "csapex_point_cloud/src/clustering/data/feature_color.hpp", "max_issues_repo_name": "AdrianZw/csapex_core_plugins", "max_issues_repo_head_hexsha": "1b23c90af7e552c3fc37c7dda589d751d2aae97f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-14T19:53:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T19:53:30.000Z", "max_forks_repo_path": "csapex_point_cloud/src/clustering/data/feature_color.hpp", "max_forks_repo_name": "AdrianZw/csapex_core_plugins", "max_forks_repo_head_hexsha": "1b23c90af7e552c3fc37c7dda589d751d2aae97f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-10-12T00:55:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T17:49:25.000Z", "avg_line_length": 28.9894736842, "max_line_length": 147, "alphanum_fraction": 0.6169208424, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.624650541985874}}
{"text": "#include <iostream>\r\n#include <cstdint>\r\n#include <cmath>\r\n#include <utility>\r\n#include <fstream>\r\n#include <vector>\r\n\r\n#include <Eigen/Core>\r\n#include <Eigen/Dense>\r\n#include <Eigen/IterativeLinearSolvers>\r\n\r\n#include \"assemblyop.hpp\"\r\n#include \"preconditioner.cpp\"\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\n\r\nenum Preconditioner { NONE, DIAGONAL, BACKWARD, FORWARD };\r\n\r\n\r\npair<MatrixXd,MatrixXd> getRates(const string& fname) {\r\n\tvector<double> rates;\r\n\tdouble r;\r\n\r\n\tifstream file(fname, ios::in);\r\n\tif (!file.is_open()) {\r\n\t\tcout << \"Error: No such file \" << fname << endl;\r\n\t\texit(1);\r\n\t}\r\n\r\n\twhile (file >> r)\r\n\t\trates.push_back(r);\r\n\tfile.close();\r\n\r\n\tunsigned int k = (unsigned int) (sqrt(0.25 + (double) rates.size()) - 0.5);\r\n\r\n\tif (k*(k+1) != rates.size()) {\r\n\t\tcout << \"Error: Entries in \" << fname << \" are not properly formatted.\" << endl;\r\n\t}\r\n\r\n\tMatrixXd A(k,k);\r\n\tMatrixXd B(k,k);\r\n\r\n\tunsigned int ind = 0, i, j;\r\n\tfor (i = 0; i < k; i++) {\r\n\t\tfor (j = 0; j < i; j++)\r\n\t\t\tA(i,j) = A(j,i) = rates[ind++];\r\n\t\tA(i,i) = rates[ind++];\r\n\t}\r\n\tfor (i = 0; i < k; i++) {\r\n\t\tfor (j = 0; j < i; j++)\r\n\t\t\tB(i,j) = B(j,i) = rates[ind++];\r\n\t\tB(i,i) = rates[ind++];\r\n\t}\r\n\r\n\treturn make_pair(A,B);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nint main(int argc, char** argv) {\r\n\tif (argc < 4) {\r\n\t\tcout << \"Usage:\\t\" << argv[0] << \" mass rates moments [rescale [diagnostic [precond]]]\" << endl;\r\n\t\tcout << \"mass:\\tthe total number of units in the assembly system\" << endl;\r\n\t\tcout << \"rates:\\tthe filename containing the rate specification for the assembly system\" << endl;\r\n\t\tcout << \"moments:\\tthe number of uncentered moments to compute\" << endl;\r\n\t\tcout << \"rescale:\\t(optional) scale A(i,j) by this quantity. Default=1.0\" << endl;\r\n\t\tcout << \"diagnostic:\\t(optional) if present, output only the all-monomer value and the number of iterations.\" << endl;\r\n\t\tcout << \"precond:\\t(optional) if precond < 0, performs forward SOR(-precond);\" << endl << \"        \\tif precond = 0 (or absent), no preconditioning;\" << endl << \"        \\tif precond > 0, backward SOR(precond);\" << endl;\r\n\t\treturn 0;\r\n\t}\r\n\r\n\r\n\tuintmax_t mass = atoi(argv[1]);\r\n\r\n\tstring file(argv[2]);\r\n\tpair<MatrixXd,MatrixXd> pr = getRates(file);\r\n\r\n\tsize_t nmoments = atoi(argv[3]);\r\n\r\n\tdouble sigma = 1.0;\r\n\tif (argc > 4)\r\n\t\tsigma = atof(argv[4]);\r\n\tbool diagnostic = argc > 5;\r\n\tPreconditioner precond = NONE;\r\n\tdouble omega = 0.0;\r\n\tif (argc > 6) {\r\n\t\tprecond = DIAGONAL;\r\n\t\tomega = atof(argv[6]);\r\n\t\tif (omega < 0.0) {\r\n\t\t\tprecond = FORWARD;\r\n\t\t\tomega *= -1.0;\r\n\t\t}\r\n\t\telse if (omega > 0.0) {\r\n\t\t\tprecond = BACKWARD;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tMatrixXd B = get<1>(pr);\r\n\tsize_t n0 = B.rows()+1;\r\n\r\n\tPartitionList<uintmax_t> states(n0-1, mass);\r\n\r\n\tMatrixXd A = sigma * get<0>(pr);\r\n\tAssemblyOp<uintmax_t> Lambda(states, A, B);\r\n\tVectorXd b, c = VectorXd::Constant(states.size(), 1.0);\r\n\r\n\tif (precond == NONE) {\r\n\t\tBiCGSTAB< AssemblyOp<uintmax_t>, IdentityPreconditioner > solver(Lambda);\r\n\t\tfor (size_t i = 1; i <= nmoments; i++) {\r\n\t\t\tb = ((double) i) * c;\r\n\t\t\tc = solver.solve(b);\r\n\t\t\tif (diagnostic)\r\n\t\t\t\tcout << c(0) << '\\t' << solver.iterations() << endl;\r\n\t\t\telse\r\n\t\t\t\tcout << c.transpose() << endl;\r\n\t\t}\r\n\t}\r\n\telse if (precond == DIAGONAL) {\r\n\t\tBiCGSTAB< AssemblyOp<uintmax_t>, AssemblyDiagonalPreconditioner<uintmax_t> > solver(Lambda);\r\n\t\tfor (size_t i = 1; i <= nmoments; i++) {\r\n\t\t\tb = ((double) i) * c;\r\n\t\t\tc = solver.solve(b);\r\n\t\t\tif (diagnostic)\r\n\t\t\t\tcout << c(0) << '\\t' << solver.iterations() << endl;\r\n\t\t\telse\r\n\t\t\t\tcout << c.transpose() << endl;\r\n\t\t}\r\n\t}\r\n\telse if (precond == FORWARD) {\r\n\t\tBiCGSTAB< AssemblyOp<uintmax_t>, AssemblyLowerPreconditioner<uintmax_t> > solver(Lambda);\r\n\t\tsolver.preconditioner().setRelaxation(omega);\r\n\t\tfor (size_t i = 1; i <= nmoments; i++) {\r\n\t\t\tb = ((double) i) * c;\r\n\t\t\tc = solver.solve(b);\r\n\t\t\tif (diagnostic)\r\n\t\t\t\tcout << c(0) << '\\t' << solver.iterations() << endl;\r\n\t\t\telse\r\n\t\t\t\tcout << c.transpose() << endl;\r\n\t\t}\r\n\t}\r\n\telse if (precond == BACKWARD) {\r\n\t\tBiCGSTAB< AssemblyOp<uintmax_t>, AssemblyUpperPreconditioner<uintmax_t> > solver(Lambda);\r\n\t\tsolver.preconditioner().setRelaxation(omega);\r\n\t\tfor (size_t i = 1; i <= nmoments; i++) {\r\n\t\t\tb = ((double) i) * c;\r\n\t\t\tc = solver.solve(b);\r\n\t\t\tif (diagnostic)\r\n\t\t\t\tcout << c(0) << '\\t' << solver.iterations() << endl;\r\n\t\t\telse\r\n\t\t\t\tcout << c.transpose() << endl;\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0;\r\n\r\n}\r\n", "meta": {"hexsha": "a16d214d66db52f8b8903bb1092ee7e554bd397d", "size": 4346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moment-solver/src/solve.cpp", "max_stars_repo_name": "jasondark/dissertation", "max_stars_repo_head_hexsha": "3e1117ef0d14aa8d659f80df3edde1c266815856", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moment-solver/src/solve.cpp", "max_issues_repo_name": "jasondark/dissertation", "max_issues_repo_head_hexsha": "3e1117ef0d14aa8d659f80df3edde1c266815856", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moment-solver/src/solve.cpp", "max_forks_repo_name": "jasondark/dissertation", "max_forks_repo_head_hexsha": "3e1117ef0d14aa8d659f80df3edde1c266815856", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T01:05:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-18T01:05:58.000Z", "avg_line_length": 25.869047619, "max_line_length": 223, "alphanum_fraction": 0.5846755637, "num_tokens": 1346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6246295307849852}}
{"text": "#include <Engine/MeshEdit/Paramaterize.h>\n\n#include <Engine/MeshEdit/MinSurf.h>\n\n#include <Engine/Primitive/TriMesh.h>\n\n#include <math.h>\n \n#include <Eigen/Sparse>\n#include <MeshEdit\\MinSurf.cpp>\n\nusing namespace Ubpa;\n\nusing namespace std;\n\nusing namespace Eigen;\n\nParamaterize::Paramaterize(Ptr<TriMesh> triMesh)\n\t: heMesh(make_shared<HEMesh<V>>())\n{\n\tInit(triMesh);\n}\n\nvoid Paramaterize::Paramize() {\n\t//Ptr<TriMesh> triMesh_backup;\n\t//(*triMesh_backup) = (*triMesh);\n\t//const Ptr<HEMesh<V>> heMesh_backup;\n\t//(*heMesh_backup) = (*heMesh);\n\tauto bound = heMesh->Boundaries();\n\tvector<int> bound_idx;\n\t//get the index of the boundaries\n\tfor (auto& group : bound)\n\t{\n\t\tfor (auto ver : group)\n\t\t{\n\t\t\tbound_idx.push_back(heMesh->Index(ver->Pair()->End()));\n\t\t}\n\t}\n\n\tbound_idx.erase(std::unique(bound_idx.begin(), bound_idx.end()), bound_idx.end());\n\tstd::sort(bound_idx.begin(), bound_idx.end());\n\tconst auto& v = heMesh->Vertices();\n\n\tauto bound_size=bound_idx.size();\n\tauto len = ceil(bound_size / 4.0);\n\n\t//set parameter for the boundaries\n\tcout << \"bound_size\" << bound_size << endl;\n\n\t//auto bound_backup(bound);\n\t//bound_backup.assign(bound.begin(), bound.end());\n\tint i = 0;\n\tfor (auto& group : bound)   //map the boundary of the curve to the unit square\n\t{\n\t\t//auto& group = bound[3];\n\t\tfor (auto &p_v : group)\n\t\t{\n\t\t\tp_v->Pair()->End()->pos[2] = 0;\n\t\t\tif (i < len)\n\t\t\t{\n\t\t\t\tp_v->Pair()->End()->pos[0] = 0.0 + i * (1.0 / len);\n\t\t\t\tp_v->Pair()->End()->pos[1] = 0.0;\n\t\t\t}\n\t\t\telse if (i >= len && i < 2 * len)\n\t\t\t{\n\t\t\t\tp_v->Pair()->End()->pos[0] = 1.0;\n\t\t\t\tp_v->Pair()->End()->pos[1] = 0.0 + (i - len) * (1.0 / len);\n\t\t\t}\n\t\t\telse if (i >= 2 * len && i < 3 * len)\n\t\t\t{\n\t\t\t\tp_v->Pair()->End()->pos[0] = 1.0 - (i - 2 * len) * (1.0 / len);\n\t\t\t\tp_v->Pair()->End()->pos[1] = 1.0;\n\t\t\t}\n\t\t\telse if (i >= 3 * len)\n\t\t\t{\n\t\t\t\tp_v->Pair()->End()->pos[0] = 0.0;\n\t\t\t\tp_v->Pair()->End()->pos[1] = 1.0 - (i - 3 * len) * (1.0 / len);\n\t\t\t}\n\t\t\t\n\t\t\ti++;\n\t\t}\n\t}\n\t//cout << \"i:\" << i << endl;\n\n\t//set matrix \n\tconst auto mat_size = v.size() - bound_idx.size();\n\tSparseMatrix<double> mat(mat_size, mat_size);\n\tMatrixX2d right = Eigen::MatrixX2d::Zero(mat_size, 2);\n\n\tusing std::cout;\n\n\t//auto v_backup=v;\n\t//v_backup.assign(v.begin(), v.end());\n\tfor (auto vert : v)\n\t{\n\t\tint index = find_idx(bound_idx, heMesh->Index(vert));\n\t\tif (index != -1) //if vertex is not inthe boundaries\n\t\t{\n\t\t\tauto adj_v = vert->AdjVertices();  //get adjacent\n\t\t\tdouble degree = adj_v.size();\n\t\t\tif (index >= mat_size)\n\t\t\t{\n\t\t\t\tcout << \"index=\" << index << \"mat_size=\" << mat_size << endl;\n\t\t\t\tsystem(\"pause\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmat.coeffRef(index, index) += 1;\n\t\t\t}\n\t\t\tfor (auto v : adj_v)\n\t\t\t{\n\t\t\t\tint row_idx = find_idx(bound_idx, heMesh->Index(v));\n\t\t\t\tif (row_idx == -1)\n\t\t\t\t{\n\t\t\t\t\tfor (int i = 0; i < 2; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tright(index, i) += v->pos[i] / degree;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (index >= mat_size)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"index:\" << index << endl;\n\t\t\t\t\t\tsystem(\"pause\");\n\t\t\t\t\t}\n\t\t\t\t\telse\tif (row_idx >= mat_size)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << \"row_index:\" << row_idx << endl;\n\t\t\t\t\t\tsystem(\"pause\");\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmat.coeffRef(index, row_idx) -= 1 / degree;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//cout << mat << endl;\n\n\t//cout << right_ << endl;\n\n\tSparseLU<SparseMatrix<double>> solver;\n\tsolver.compute(mat);\n\n\tif (solver.info() != Success)\n\t{\n\t\tcerr << \"Unable to decompose the matrix\" << endl;\n\t}\n\n\tauto result = solver.solve(right);\n\n\n\tfor (auto &vert : v)\n\t{\n\t\tint idx = find_idx(bound_idx, heMesh->Index(vert));\n\t\tif (idx != -1)\n\t\t{\n\t\t\tvert->pos[2] = 0;\n\t\t\tfor (int i = 0; i < 2; i++)\n\t\t\t{\n\t\t\t\tvert->pos[i] = result(idx, i);\n\t\t\t}\n\t\t}\n\t}\n\n\t//update texcoords\n\tvector<pointf2> texcoords;\n\tfor (auto vert : v)\n\t{\n\t\ttexcoords.push_back({ vert->pos[0],vert->pos[1] });\n\t}\n\ttriMesh->Update(texcoords);\n\t\n\n\tfor (auto& group : bound)\n\t{\n\t\tfor (auto& p_v : group)\n\t\t{\n\t\t\tcout << p_v->Pair()->End()->pos[0] << \" \" << p_v->Pair()->End()->pos[1] << \" \" << p_v->Pair()->End()->pos[2] << endl;\n\t\t}\n\t}\n\n}\n\nvoid Paramaterize::Clear() {\n\theMesh->Clear();\n\ttriMesh = nullptr;\n}\n\nbool Paramaterize::Init(Ptr<TriMesh> triMesh) {\n\t// TODO\n\tClear();\n\n\tif (triMesh == nullptr)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is invalid\\n\");\n\t\treturn false;\n\t}\n\n\t// init half-edge structure\n\tsize_t nV = triMesh->GetPositions().size();\n\tvector<vector<size_t>> triangles;\n\ttriangles.reserve(triMesh->GetTriangles().size());\n\tfor (auto triangle : triMesh->GetTriangles())\n\t\ttriangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });\n\theMesh->Reserve(nV);\n\theMesh->Init(triangles);\n\n\tif (!heMesh->IsTriMesh() || !heMesh->HaveBoundary()) {\n\t\tprintf(\"ERROR::MinSurf::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is not a triangle mesh or hasn't a boundaries\\n\");\n\t\theMesh->Clear();\n\t\treturn false;\n\t}\n\n\t// triangle mesh's positions ->  half-edge structure's positions\n\tfor (int i = 0; i < nV; i++) {\n\t\tauto v = heMesh->Vertices().at(i);\n\t\tv->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t}\n\n\tthis->triMesh = triMesh;\n\treturn true;\n}\n\nbool Paramaterize::Run() {\n\tif (heMesh->IsEmpty() || !triMesh) {\n\t\tprintf(\"ERROR::MinSurf::Run\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\n\t//cout << \"paramize!\" << endl;\n\tParamize();\n\n\t// half-edge structure -> triangle mesh\n\tsize_t nV = heMesh->NumVertices();\n\tsize_t nF = heMesh->NumPolygons();\n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tpositions.reserve(nV);\n\tindice.reserve(3 * nF);\n\tfor (auto v : heMesh->Vertices())\n\t\tpositions.push_back(v->pos.cast_to<pointf3>());\n\tfor (auto f : heMesh->Polygons()) { // f is triangle\n\t\tfor (auto v : f->BoundaryVertice()) // vertices of the triangle\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t}\n\n\t//triMesh->Init(indice, positions);\n\n\treturn true;\n}\n\n//return the index of the vertex in the matrix above\nconst int Paramaterize::find_idx(std::vector<int>& vec, int idx)\n{\n\tauto N = vec.size();\n\tif (idx < vec[0]) return idx;\n\tif (idx > vec[N - 1]) return idx - N;\n\tfor (auto i = 0; i < N; i++)\n\t{\n\t\tif (idx == vec[i]) return -1;\n\t\tif (idx < vec[i])\n\t\t{\n\t\t\treturn idx - i;\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "7ebce105dbe7849c4efab8e82b610f21f1527e86", "size": 6139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/Paramaterize.cpp", "max_stars_repo_name": "Qinxin-Yan/USTC_CG-1", "max_stars_repo_head_hexsha": "80dc240bea879f000196986b98efcd0bbf8dec34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/Paramaterize.cpp", "max_issues_repo_name": "Qinxin-Yan/USTC_CG-1", "max_issues_repo_head_hexsha": "80dc240bea879f000196986b98efcd0bbf8dec34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/Paramaterize.cpp", "max_forks_repo_name": "Qinxin-Yan/USTC_CG-1", "max_forks_repo_head_hexsha": "80dc240bea879f000196986b98efcd0bbf8dec34", "max_forks_repo_licenses": ["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.3236363636, "max_line_length": 120, "alphanum_fraction": 0.5867405115, "num_tokens": 2038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6246295230227668}}
{"text": "/*\n * Matrix-vector multiply\n *\n * Information on Intel vector pragmas is available in the following link:\n * https://software.intel.com/en-us/cpp-compiler-developer-guide-and-reference-vector-1#58209E46-70EA-4C47-BED6-E69236C6680C\n */\n\n// https://en.cppreference.com/w/cpp/memory/c/aligned_alloc\n#include <cstdlib>  // aligned_alloc (C++11), std::aligned_alloc (C++17)\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <boost/align/aligned_allocator.hpp>\n#include <cmath>\n// #include \"papi.h\"\n#include \"simd.h\"\n#include \"environ.h\"\n#include \"utils.h\"\n#include \"vutils.h\"\n\n\n///////////////////////////////////////////////////////////////////////////////\n// USER CONFIGURATION\n///////////////////////////////////////////////////////////////////////////////\n// Square matrix dimension\nconst size_t N = 6;\n\n// Precision for floating-point operations\n// Valid values are: 4, 8\n#define REAL_TYPE 4\n\n\n///////////////////////////////////////////////////////////////////////////////\n// FP and SIMD\n///////////////////////////////////////////////////////////////////////////////\n// Precision for floating-point operations\n#if REAL_TYPE == 4\ntypedef float real;\ntypedef SIMD_FLT vreal;\n#elif REAL_TYPE == 8\ntypedef double real;\ntypedef SIMD_DBL vreal;\n#endif\n\n// Number of floating-point values that fit into a SIMD register\nconst int SIMD_STREAMS = SIMD_WIDTH_BYTES / sizeof(real);\nconst int LOG2STREAMS = std::log2(SIMD_STREAMS);\n\n\n///////////////////////////////////////////////////////////////////////////////\n// PROGRAM\n///////////////////////////////////////////////////////////////////////////////\ntemplate <typename T>\nusing aligned_vector = std::vector<T, boost::alignment::aligned_allocator<T, SIMD_WIDTH_BYTES>>;\n\n\nvoid gemv(\n    const size_t n,\n    const size_t lda,\n    const aligned_vector<real> v1,\n    const aligned_vector<real> v2,\n    aligned_vector<real> &dp)\n{\n    for (size_t row = 0; row < n; row++) {\n        for (size_t col = 0; col < n; col++) {\n            dp[row] += v1[row * lda + col] * v2[col];\n        }\n    }\n}\n\n\nvoid gemv_simd_tree_sum(\n    const size_t n,\n    const size_t lda,\n    const real *v1,\n    const real *v2,\n    real *dp)\n{\n#if defined(__INTEL_COMPILER)\n    __assume_aligned(v1, SIMD_WIDTH_BYTES);\n    __assume_aligned(v2, SIMD_WIDTH_BYTES);\n    const real *_v1 = v1;\n    const real *_v2 = v2;\n#elif defined(__GNUC__)\n    const real *_v1 = (real *)__builtin_assume_aligned(v1, SIMD_WIDTH_BYTES);\n    const real *_v2 = (real *)__builtin_assume_aligned(v2, SIMD_WIDTH_BYTES);\n#endif\n\n    for (size_t row = 0; row < n; row++) {\n        vreal vdp = simd_zero();\n        for (size_t col = 0; col < lda; col+=SIMD_STREAMS) {\n            vreal vv1 = simd_load(&_v1[row * lda + col]);\n            vreal vv2 = simd_load(&_v2[col]);\n#if defined(__FMA__)\n            vdp = simd_fmadd(vv1, vv2, vdp);\n#else\n            vv1 = simd_mul(vv1, vv2);\n            vdp = simd_add(vv1, vdp);\n#endif\n        }\n\n        // Binary tree sum reduction\n        for (size_t i = 0; i < LOG2STREAMS - 1; i++) {\n            vdp = simd_hadd(vdp, vdp);\n        }\n\n        real tdp[SIMD_STREAMS] __attribute__((aligned(SIMD_WIDTH_BYTES)));\n        simd_store(tdp, vdp);\n        // NOTE: 'dp' does need to be aligned because it is used to store a scalar value.\n#if SIMD_WIDTH_BITS == 128\n        // HADD from SSE3 does not interleave horizontal sums.\n        dp[row] = tdp[0] + tdp[1];\n#else\n        dp[row] = tdp[0] + tdp[SIMD_STREAMS / 2];\n#endif\n    }\n}\n\n\nvoid print_matrix(\n    const size_t n,\n    const size_t m,\n    const size_t lda,\n    const vector<real> v)\n{\n    for (size_t row = 0; row < n; row++) {\n        for (size_t col = 0; col < m; col++) {\n            std::cout << v[row * lda + col] << \", \";\n        }\n        std::cout << std::endl;\n    }\n\n}\n\n\nint main(int argc, char *argv[])\n{\n    int result = 0;\n\n    size_t num_matrices = 1;\n    if (argc > 1) {\n        num_matrices = std::atoi(argv[1]);\n    }\n\n    detectCPU();\n    detectSIMD();\n\n    std::cout << \"Alignment: \" << SIMD_WIDTH_BYTES << std::endl;\n    std::cout << \"Num. elems: \" << SIMD_STREAMS << std::endl;\n\n    // Number of elements in padded matrix column to conform with SIMD alignment\n    const size_t lda = (((N * sizeof(real)) / SIMD_WIDTH_BYTES) * SIMD_WIDTH_BYTES + SIMD_WIDTH_BYTES) / sizeof(real);\n    // For unaligned rows, set LDA to N\n    // const size_t lda = N;\n\n    // Create a vector of given size\n    aligned_vector<real> v1(N * lda);      // matrix\n    aligned_vector<real> v2(1 * lda, 1.);  // column vector, set to 1 --> add rows of matrix\n    aligned_vector<real> dp(N, 0);  // resulting column vector (dot products)\n\n    // Zero out extra rows used for padding, to prevent floating-point exception during vector multiplication.\n    // This memory elements are never modified, so set once.\n    memset(v2.data() + N, 0, (lda - N) * sizeof(real));\n\n    real *arr_A = NULL, *arr_B = NULL, *arr_C = NULL;\n    // scalar_malloc(&arr_A, SIMD_WIDTH_BYTES, SIMD_STREAMS);\n    // scalar_malloc(&arr_B, SIMD_WIDTH_BYTES, SIMD_STREAMS);\n    // scalar_malloc(&arr_C, SIMD_WIDTH_BYTES, SIMD_STREAMS);\n\n    for (int i = 0; i < SIMD_STREAMS; ++i) {\n        arr_A[i] = 1.;\n        arr_B[i] = (real)i;\n    }\n\n    vreal va = simd_load(arr_A);\n    vreal vb = simd_load(arr_B);\n    vreal vc = simd_add(va, vb);\n    simd_store(arr_C, vc);\n\n    for (int i = 0; i < SIMD_STREAMS; ++i) {\n        if (arr_C[i] != (arr_A[i] + arr_B[i]))\n            result += 1;\n        else\n            std::cout << arr_C[i] << std::endl;\n    }\n\n    scalar_free(&arr_A);\n    scalar_free(&arr_B);\n    scalar_free(&arr_C);\n\n    return result;\n}\n", "meta": {"hexsha": "ce5d7bd18ab3f45b2ef0c6886605ac691359647d", "size": 5610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/small_gemv/test.cpp", "max_stars_repo_name": "edponce/libsimdcpp", "max_stars_repo_head_hexsha": "2e6feefde884f91b91507ecbf2f75dacf6b191d6", "max_stars_repo_licenses": ["BSD-3-Clause", "MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-06-07T04:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-21T10:07:25.000Z", "max_issues_repo_path": "examples/small_gemv/test.cpp", "max_issues_repo_name": "edponce/libsimdcpp", "max_issues_repo_head_hexsha": "2e6feefde884f91b91507ecbf2f75dacf6b191d6", "max_issues_repo_licenses": ["BSD-3-Clause", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/small_gemv/test.cpp", "max_forks_repo_name": "edponce/libsimdcpp", "max_forks_repo_head_hexsha": "2e6feefde884f91b91507ecbf2f75dacf6b191d6", "max_forks_repo_licenses": ["BSD-3-Clause", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.067357513, "max_line_length": 124, "alphanum_fraction": 0.5682709447, "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6246295085124843}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[num_geometries\n//` Get the number of geometries making up a multi-geometry\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n\n\nint main()\n{\n    boost::geometry::model::multi_polygon\n        <\n            boost::geometry::model::polygon\n                <\n                    boost::geometry::model::d2::point_xy<double>\n                >\n        > mp;\n    boost::geometry::read_wkt(\"MULTIPOLYGON(((0 0,0 10,10 0,0 0),(1 1,1 9,9 1,1 1)),((10 10,10 7,7 10,10 10)))\", mp);\n    std::cout << \"Number of geometries: \" << boost::geometry::num_geometries(mp) << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[num_geometries_output\n/*`\nOutput:\n[pre\n Number of geometries: 2\n]\n*/\n//]\n", "meta": {"hexsha": "28f476d95cd71da5ade713b32bb7e8c6a9454be5", "size": 1159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/num_geometries.cpp", "max_stars_repo_name": "Manu343726/boost-cmake", "max_stars_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/num_geometries.cpp", "max_issues_repo_name": "Manu343726/boost-cmake", "max_issues_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/num_geometries.cpp", "max_forks_repo_name": "Manu343726/boost-cmake", "max_forks_repo_head_hexsha": "009c3843b49a56880d988ffdca6d909f881edb3d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 24.6595744681, "max_line_length": 117, "alphanum_fraction": 0.6574633305, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.8006920116079209, "lm_q1q2_score": 0.6245340843443572}}
{"text": "/* -*-C++-*- */\n/*\n   (c) Copyright 2001-2005, Hewlett-Packard Development Company, LP\n\n   See the file named COPYING for license details\n*/\n\n/** @file\n    \\brief Some simple functions for handling doubles\n*/\n\n#ifndef LINTEL_DOUBLE_HPP\n#define LINTEL_DOUBLE_HPP\n\n#include <algorithm>\n#include <math.h>\n\n#include <boost/config.hpp>\n\n#ifdef BOOST_MSVC\ninline bool isnan(double);\ninline bool isinf(double);\n#endif\n\n#undef abs\n// Performance notes for floating point: \n// on T2600:\n//    NaN != 0 NaN >= 0, etc are really slow\n//    v >= 0 for -inf is slightly faster than !isinf\n//    isnan(NaN) and isinf(INF) are about the same speed.\n\n/// \\brief a class for storing static functions for dealing with doubles; probably should\n/// have used a namespace.\nclass Double {\npublic:\n    static double default_epsilon; // relative to larger of two values.\n    // If handled by setEpsilonDigits/Bits, it means (approx) that the \n    // numbers agree to the first that many digits/bits\n    static void setEpsilonDigits(unsigned int digits) {\n\tdefault_epsilon = 1;\n\tfor(unsigned int i=0;i<digits;i++) {\n\t    default_epsilon /= 10.0;\n\t}\n    }\n    static void setEpsilonBits(unsigned int bits) {\n\tdefault_epsilon = 1;\n\tfor(unsigned int i=0;i<bits;i++) {\n\t    default_epsilon /= 2.0;\n\t}\n    }\n\n    static double abs(double a) {\n\treturn a<0 ? -a : a;\n    }\n    static bool eq(double a, double b, double epsilon) {\n\tdouble relto = std::min(abs(a),abs(b)); \n\tdouble diff = abs(a-b);\n\tif (relto == 0) {\n\t    return diff < epsilon;\n\t} else {\n\t    return diff/relto < epsilon;\n\t}\n    }\n    static bool eq(double a, double b) {\n\treturn eq(a,b,default_epsilon);\n    }\n    static bool leq(double a, double b) { \n\treturn a < b || eq(a,b); \n    }\n    static bool lt(double a, double b) {\n\treturn a < b && !eq(a,b);\n    }\n    static bool geq(double a, double b) {\n\treturn a > b || eq(a,b);\n    } \n    static bool gt(double a, double b) {\n\treturn a > b && !eq(a,b);\n    }\n    static const double NaN;\n    static const double Inf;\n    // Following routines somewhat useful for getting Linux to give\n    // the same results as other machines.  Discussion is found on:\n    // http://www.srware.com/linux_numerics.txt Unfortunately, you\n    // probably don't want to put linux in this mode most of the time;\n    // supposedly libm on Linux depends on the extra precision\n    // provided by 80 bit floats to calculate some of the complex math\n    // functions.  On non-linux, these routines are no-ops.\n    static void setFP64BitMode();\n    static void resetFPMode();\n\n    static void selfCheck();\n};\n\n#endif\n", "meta": {"hexsha": "4bf79ffa9a9fb0976f66fdc77b3177f771254edc", "size": 2576, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Lintel/Double.hpp", "max_stars_repo_name": "sbu-fsl/Lintel", "max_stars_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Lintel/Double.hpp", "max_issues_repo_name": "sbu-fsl/Lintel", "max_issues_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-05T21:20:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-05T21:56:51.000Z", "max_forks_repo_path": "include/Lintel/Double.hpp", "max_forks_repo_name": "sbu-fsl/Lintel", "max_forks_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1157894737, "max_line_length": 89, "alphanum_fraction": 0.6587732919, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.6245340687352975}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[point_xyz\n//` Declaration and use of the Boost.Geometry model::d3::point_xyz, modelling the Point Concept\n\n#include <iostream>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xyz.hpp>\n\nnamespace bg = boost::geometry;\n\nint main()\n{\n    bg::model::d3::point_xyz<double> point1;\n    bg::model::d3::point_xyz<double> point2(3, 4, 5); /*< Construct, assigning coordinates. >*/\n\n    bg::set<0>(point1, 1.0); /*< Set a coordinate, generic. >*/\n    point1.y(2.0); /*< Set a coordinate, class-specific ([*Note]: prefer `bg::set()`). >*/\n    point1.z(4.0);\n\n    double x = bg::get<0>(point1); /*< Get a coordinate, generic. >*/\n    double y = point1.y(); /*< Get a coordinate, class-specific ([*Note]: prefer `bg::get()`). >*/\n    double z = point1.z();\n\n    std::cout << x << \", \" << y << \", \" << z << std::endl;\n    return 0;\n}\n\n//]\n\n\n//[point_xyz_output\n/*`\nOutput:\n[pre\n1, 2, 4\n]\n*/\n//]\n", "meta": {"hexsha": "92f636eccb4b52efde0194fd77279209b69a1085", "size": 1231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/geometries/point_xyz.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/geometries/point_xyz.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/geometries/point_xyz.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": 26.1914893617, "max_line_length": 98, "alphanum_fraction": 0.6393176279, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6245340687352974}}
{"text": "/// \\file\n/// \\brief A file for detecting circle using a regression algorithm. This file is a library file\n///\n\n\n#include \"sensor_msgs/LaserScan.h\"\n#include \"nuslam/circle_detection.hpp\"\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <Eigen/SVD>\n#include <Eigen/Cholesky>\n#include <cmath>\n#include \"rigid2d/rigid2d.hpp\"\n\n\nusing std::cout;\nusing Eigen::Matrix;\nusing Eigen::Dynamic;\nusing Eigen::BDCSVD;\nusing Eigen::ComputeFullV;\nusing Eigen::ComputeFullU;\n\n\nusing Eigen::Vector4d;\nusing rigid2d::Vector2D;\n\ntypedef Matrix<double, Dynamic, 4> Matrix4dn;\ntypedef Matrix<double, 4, 4> Matrix4d;\n\n\n\nnamespace circleDetection\n{\n\n/// \\brief A constructor for Poin2d data type\n/// \\param x1 - x co-ordinate\n/// \\param y1 - y co-ordinate\nPoint2d::Point2d(double x1, double y1)\n{\n\n  x = x1;\n  y = y1;\n}\n\n/// \\brief A function that fits circle to the list of points given\n/// \\param CirclePoints -  A list containing points for which a circle needs to be fit.\nVector3d fitCircle(vector<Vector2D> circlePoints)\n{\n\n  Matrix4dn circleMatrix;\n  Matrix4d H, Hinv;\n  circleMatrix.resize(circlePoints.size(), 4);\n  Vector4d equCoeff;\n  size_t i;\n  double sum_x=0, sum_y=0, sum_z=0;\n  int pointsCount = circlePoints.size();\n\n  for(auto point: circlePoints)\n  {\n    sum_x += point.x;\n    sum_y += point.y;\n  }\n  double mean_x = sum_x / (double) circlePoints.size();\n  double mean_y = sum_y / (double) circlePoints.size();\n\n  for (auto& point:circlePoints)\n  {\n    point.x = point.x - mean_x;\n    point.y = point.y - mean_y;\n  }\n\n  std::cout << \"Here is the matrix m:\\n\" << circlePoints[0].x <<circlePoints[0].y << std::endl;\n\n\n  for(i=0; i < circlePoints.size(); i++)\n  {\n    circleMatrix(i, 0) = pow(circlePoints[i].x, 2) + pow(circlePoints[i].y, 2);\n    circleMatrix(i, 1) = circlePoints[i].x;\n    circleMatrix(i, 2) = circlePoints[i].y;\n    circleMatrix(i, 3) = 1.0;\n    sum_z += circleMatrix(i, 0);\n  }\n\n  double mean_z = sum_z / (double) pointsCount;\n\n  auto M = circleMatrix.transpose() * circleMatrix / pointsCount;\n\n  // Initialise H matrix\n  H(0,0) = 8 * mean_z;\n  H(0,1) = 0;\n  H(0,2) = 0;\n  H(0,3) = 2;\n  H(1,0) = 0;\n  H(1,1) = 1;\n  H(1,2) = 0;\n  H(1,3) = 0;\n  H(2,0) = 0;\n  H(2,1) = 0;\n  H(2,2) = 1;\n  H(2,3) = 0;\n  H(3,0) = 2;\n  H(3,1) = 0;\n  H(3,2) = 0;\n  H(3,3) = 0;\n\n\n  // Initialise H inverse matrix\n  Hinv(0,0) = 0;\n  Hinv(0,1) = 0;\n  Hinv(0,2) = 0;\n  Hinv(0,3) = 0.5;\n  Hinv(1,0) = 0;\n  Hinv(1,1) = 1;\n  Hinv(1,2) = 0;\n  Hinv(1,3) = 0;\n  Hinv(2,0) = 0;\n  Hinv(2,1) = 0;\n  Hinv(2,2) = 1;\n  Hinv(2,3) = 0;\n  Hinv(3,0) = 0.5;\n  Hinv(3,1) = 0;\n  Hinv(3,2) = 0;\n  Hinv(3,3) = -2 * mean_z;\n\n  BDCSVD<Matrix4dn> svdCircle( circleMatrix, ComputeFullV | ComputeFullU  );\n  auto sigmaValues = svdCircle.singularValues();\n  auto V = svdCircle.matrixV();\n\n\n  if(sigmaValues.size() ==4 && sigmaValues[3] > 1e-12)\n  {\n\n    auto sigmaMatrix = sigmaValues.asDiagonal();\n    auto Y = V * sigmaMatrix * V.transpose();\n    std::cout<< \"Y cols\" << Y.cols() <<\" Y rows\"<<Y.rows();\n    std::cout<< \"H cols\" << Hinv.cols() <<\" H rows\" << Hinv.rows();\n\n    std::cout << \"Here is the matrix m:\\n\" << Y << std::endl;\n    auto Q = Y * Hinv * Y;\n    Eigen::SelfAdjointEigenSolver<Matrix4dn> eig(Q);\n\n    auto eigVecQ = eig.eigenvectors();\n    auto eigValues = eig.eigenvalues();\n\n    double minEigValue = std::numeric_limits<double>::infinity();\n    int minEigIndex;\n\n    for(int i=0; i< eigValues.size(); i++)\n    {\n      if(eigValues[i] < minEigValue && eigValues[i] > 0)\n      {\n        minEigValue = eigValues[i];\n        minEigIndex = i;\n      }\n    }\n\n    Vector4d smallEigVec = {eigVecQ(0,minEigIndex), eigVecQ(1,minEigIndex), eigVecQ(2,minEigIndex), eigVecQ(3,minEigIndex)};\n\n    std::cout << \"Here is the matrix m:\\n\" << eigVecQ << std::endl;\n    std::cout << \"Here is the matrix m:\\n\" << smallEigVec << std::endl;\n    std::cout << \"Q eigen values\" << eigValues;\n\n    equCoeff = Y.colPivHouseholderQr().solve(smallEigVec);\n  }\n  else\n  {\n\n    equCoeff = {V(0,3), V(1,3), V(2,3), V(3,3)};\n  }\n\n  double a = -equCoeff[1] / equCoeff[0] / 2.0 + mean_x;\n  double b = -equCoeff[2] / equCoeff[0] / 2.0 + mean_y;\n  double r2 = (pow(equCoeff[1], 2) + pow(equCoeff[2], 2) - 4 * equCoeff[0] * equCoeff[3]) / (4.0 * pow(equCoeff[0], 2));\n  double r = sqrt(r2);\n  Vector3d circleCoeff = {a, b, r};\n\n\n\n\n std::cout << \"Here is the matrix m:\\n\" << circleMatrix << std::endl;\n std::cout << \"Here is the matrix m:\\n\" << M << std::endl;\n std::cout<< \"Sigma values\\n\"<<sigmaValues << std::endl;\n std::cout<< \"Circle coefficients\" << circleCoeff;\n std::cout<< \"x center\" << mean_x;\n std::cout<< \"y center\" << mean_y;\n return circleCoeff;\n\n\n}\n\n/// \\brief A function that calculates the least squares error for the estimated circle\n///        fitting parameters\n/// \\param observedPoints - All the points for which a circular fit needs to be done\n/// \\param circleCoeff - Circle parameters estimated\n\ndouble calculateError(const vector<Vector2D>& observedPoints, Vector3d circleCoeff)\n{\n  double totalError=0;\n  double error = 0;\n\n  for(auto point:observedPoints)\n  {\n    error = pow(point.x - circleCoeff[0], 2) + pow(point.y - circleCoeff[1], 2) - pow(circleCoeff[2], 2);\n    error = pow(error, 2);\n    totalError += error;\n  }\n  totalError = totalError / (double) observedPoints.size();\n  totalError = sqrt(totalError);\n  return totalError;\n\n}\n\n\n}\n\n\n\n\n", "meta": {"hexsha": "d6f299dbdfdf1e8bb1e9c63c4ebc1cbe8423f3ab", "size": 5322, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nuslam/src/circle_detection.cpp", "max_stars_repo_name": "nithin-gunamgari/turtlebot_slam", "max_stars_repo_head_hexsha": "4e755dc2c055b59a058d890f0cdb9a099e1a1a82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nuslam/src/circle_detection.cpp", "max_issues_repo_name": "nithin-gunamgari/turtlebot_slam", "max_issues_repo_head_hexsha": "4e755dc2c055b59a058d890f0cdb9a099e1a1a82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nuslam/src/circle_detection.cpp", "max_forks_repo_name": "nithin-gunamgari/turtlebot_slam", "max_forks_repo_head_hexsha": "4e755dc2c055b59a058d890f0cdb9a099e1a1a82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.301369863, "max_line_length": 124, "alphanum_fraction": 0.6219466366, "num_tokens": 1865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.6893056295505784, "lm_q1q2_score": 0.624503890504558}}
{"text": "//\r\n// $Id: LinearSolver.hpp 1195 2009-08-14 22:12:04Z chambm $\r\n//\r\n//\r\n// Original author: Darren Kessner <darren@proteowizard.org>\r\n//\r\n// Copyright 2007 Spielberg Family Center for Applied Proteomics \r\n//   Cedars Sinai Medical Center, Los Angeles, California  90048\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \r\n// you may not use this file except in compliance with the License. \r\n// You may obtain a copy of the License at \r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software \r\n// distributed under the License is distributed on an \"AS IS\" BASIS, \r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \r\n// See the License for the specific language governing permissions and \r\n// limitations under the License.\r\n//\r\n\r\n\r\n#ifndef _LINEARSOLVER_HPP_\r\n#define _LINEARSOLVER_HPP_\r\n\r\n\r\n#include \"pwiz/utility/misc/Export.hpp\"\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/lu.hpp>\r\n#include <boost/numeric/ublas/triangular.hpp>\r\n#include <boost/numeric/ublas/vector_proxy.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <stdexcept>\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <math.h>\r\n\r\n#include \"qr.hpp\"\r\n\r\nnamespace pwiz {\r\nnamespace math {\r\n\r\n\r\nenum PWIZ_API_DECL LinearSolverType {LinearSolverType_LU, LinearSolverType_QR};\r\n\r\n\r\ntemplate <LinearSolverType solver_type = LinearSolverType_LU>\r\nclass LinearSolver;\r\n\r\n\r\ntemplate<>\r\nclass LinearSolver<LinearSolverType_LU>\r\n{\r\npublic:\r\n\r\n    /// solve system of linear equations Ax = y using boost::ublas;\r\n    /// note: extra copying inefficiencies for ease of client use \r\n    template<typename matrix_type, typename vector_type>\r\n    vector_type solve(const matrix_type& A, \r\n                      const vector_type& y)\r\n    {\r\n        namespace ublas = boost::numeric::ublas;\r\n\r\n        matrix_type A_factorized = A;\r\n        ublas::permutation_matrix<size_t> pm(y.size());\r\n\r\n        int singular = lu_factorize(A_factorized, pm);\r\n        if (singular) throw std::runtime_error(\"[LinearSolver<LU>::solve()] A is singular.\");\r\n\r\n        vector_type result(y);\r\n        lu_substitute(A_factorized, pm, result);\r\n\r\n        return result;\r\n    }\r\n}; \r\n\r\n\r\ntemplate<>\r\nclass LinearSolver<LinearSolverType_QR>\r\n{\r\npublic:\r\n\r\n    /// solve system of linear equations Ax = y using boost::ublas;\r\n    /// note: extra copying inefficiencies for ease of client use \r\n    template<typename matrix_type, typename vector_type>\r\n    vector_type solve(const matrix_type& A, const vector_type& y)\r\n    {\r\n        typedef typename matrix_type::size_type size_type;\r\n        typedef typename matrix_type::value_type value_type;\r\n        \r\n        namespace ublas = boost::numeric::ublas;\r\n\r\n        matrix_type Q(A.size1(), A.size2()), R(A.size1(), A.size2());\r\n\r\n        qr (A, Q, R);\r\n\r\n        vector_type b = prod(trans(Q), y);\r\n\r\n        vector_type result;\r\n        if (R.size1() > R.size2())\r\n        {\r\n            size_type min = (R.size1() < R.size2() ? R.size1() : R.size2());\r\n\r\n            result = ublas::solve(subrange(R, 0, min, 0, min),\r\n                                  subrange(b, 0, min),\r\n                                  ublas::upper_tag());\r\n        }\r\n        else\r\n        {\r\n            result = ublas::solve(R, b, ublas::upper_tag());\r\n        }\r\n        return result;\r\n    }\r\n}; \r\n\r\n} // namespace math \r\n} // namespace pwiz\r\n\r\n\r\n#endif // _LINEARSOLVER_HPP_ \r\n\r\n", "meta": {"hexsha": "b41cdd4792996d4a073ee3cf463e380a32a598c8", "size": 3544, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/math/LinearSolver.hpp", "max_stars_repo_name": "edyp-lab/pwiz-mzdb", "max_stars_repo_head_hexsha": "d13ce17f4061596c7e3daf9cf5671167b5996831", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T08:33:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T06:14:54.000Z", "max_issues_repo_path": "pwiz/utility/math/LinearSolver.hpp", "max_issues_repo_name": "shze/pwizard-deb", "max_issues_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "pwiz/utility/math/LinearSolver.hpp", "max_forks_repo_name": "shze/pwizard-deb", "max_forks_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-02-03T09:41:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T18:42:36.000Z", "avg_line_length": 28.352, "max_line_length": 94, "alphanum_fraction": 0.6396726862, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.6245038870051861}}
{"text": "//Libraries\n#include <Eigen/Dense>\n#include \"MathFuncs.h\"\n#include \"AttitudeControl.h\"\n#include \"QuatRotEuler.h\"\n#include <stdio.h>\t\t/* printf */\n#include <stdlib.h>     /* system, NULL, EXIT_FAILURE */\n#include <math.h>\t\t/* pow, sqrt */\nusing Eigen::Matrix;\n// Constant definitions\n#define PI 3.14159265\n#define K_ROLL  5\t\t\t//Control gain for roll motion\n#define K_PITCH 5\t\t\t//Control gain for pitch motion\n#define K_YAW   0\t\t\t//Control gain for yaw motion\n#define K_WX    2\t\t\t//Control gain for angular velocity about x\n#define K_WY    2\t\t\t//Control gain for angular velocity about y\n#define K_WZ    1\t\t\t//Control gain for angular velocity about z\n#define KT_a\t1.09862e-6\t//Thrust coefficient for the quadrotor's propellers in function of PWM squared\n#define KT_b\t1.05000e-3\t//Thrust coefficient for the quadrotor's propellers in function of PWM\n#define KT_bSQR pow(KT_b,2)\n#define RAD     0.12\t\t//Radius of quadcopter (distance between center and farther tip of propeller)\n#define SIN_45  0.7071067\n#define COS_45  0.7071067\n#define Ctm     9.22e-3\n\n//Functions\n\n//Attitude error: e_r = 0.5*invSkew(Rref'*Rbw - Rbw'*Rref)\nMatrix<float, 3, 1> AttitudeErrorVector(Matrix<float, 3, 3> Rbw, Matrix<float, 3, 3> Rdes){\n\tMatrix<float, 3, 3> M_aux1 = Rdes.transpose()*Rbw; //M_aux1 = Rdes'*Rbw\n\tMatrix<float, 3, 3> M_aux2 = Rbw.transpose()*Rdes; //M_aux2 = Rbw'*Rdes\n\tMatrix<float, 3, 1> V_aux = invSkew(M_aux1-M_aux2);\t\t//V_aux = invSkew(M_aux1 - M_aux2)\n\n\treturn V_aux*-0.5; //0.5*V_aux\n}\n\n//Attitude control inputs: u_att = -Kr*e_r - Kw*e_w\nMatrix<float, 3, 1> AttitudeControlInputs(Matrix<float, 3, 3> Kr, Matrix<float, 3, 3> Kw, Matrix<float, 3, 1> e_r, Matrix<float, 3, 1> e_w){\n\tMatrix<float, 3, 1> V_aux1 = Kr*e_r*(-1); //V_aux1 = -Kr*e_r\n\tMatrix<float, 3, 1> V_aux2 = Kw*e_w*(-1); //V_aux2 = -Kw*e_w\n\t//PrintVec3(V_aux1, \"Proportional\");\n\t//PrintVec3(V_aux2, \"Derivative\");\n\n\t//return V_aux2;\n\n\treturn V_aux1+V_aux2; //V_aux1 + V_aux2\n}\n\n\n/*Return inputs to quadrotor for attitude control\nq[4];\t\t//Attitude quaternion\nRdes;\t\t//Desired rotation matrix\nw_bw[3];\t//Angular velocity of the system\nwDes[3];\t//Desired angular velocity\nu1;\t\t\t//Thrust \nThis algorithm was extracted from Mellinger, 2011: Minimum Snap Trajectory Generation and Control for Quadrotors*/\nMatrix<float, 4, 1> attitudeControl(Matrix<float, 4, 1> q, Matrix<float, 3, 3> Rdes, Matrix<float, 3, 1> w_bw, Matrix<float, 3, 1> wDes, float u1){\n\t\n\t//Controller gain matrices\n\tMatrix<float, 3, 1> K_eVec, K_wVec, e_r, e_w, u_att;\n\tMatrix<float, 4, 1> u;\n\tMatrix<float, 3, 3> K_r, K_w, Rbw;\n\n\tK_eVec << K_ROLL,\n\t\t\t  K_PITCH,\n\t\t\t  K_YAW;\t//Attitude error gains\n\tK_wVec << K_WX,\n\t\t\t  K_WY,\n\t\t\t  K_WZ;\t\t\t//Angular velocity gains\n\n\tK_r = K_eVec.asDiagonal();\n\tK_w = K_wVec.asDiagonal();\n\n\t//Get rotation matrix from quaternion\n\tRbw = Quat2rot(q); //Matrix obtained in the NED parameterization\n        //PrintMat3x3(Rbw);\n\t//PrintMat3x3(Rdes);\n\t\n\t//Attitude error: e_r = 0.5*invSkew(Rref'*Rbw - Rbw'*Rref)\n\te_r = AttitudeErrorVector(Rbw, Rdes);\n\t//PrintVec3(e_r, \"ErrorAtt\");\n\n\t//Angular velocity error: e_w = w_bw - wDes\n\te_w = w_bw-wDes;\n\n\t//Attitude control input: u_att = -K_r*e_r - K_w*e_w\n\tu_att = AttitudeControlInputs(K_r, K_w, e_r, e_w);\n\n\t//Saturate the attitude torques to the system so that they are not too high\n\tu_att << saturate(u_att(0), -20, 20),\n\t\t\t saturate(u_att(1), -20, 20),\n\t\t\t saturate(u_att(2), -20, 20);\n\n\t//Output variable (the negatives below are due to the fact of using NED coordinates instead of NWU)\n\t\n\tu <<       u1,\n\t\t u_att(0),\n\t\t u_att(1),\n\t\t u_att(2);\n\n\treturn u;\n}\n\n/* Convert inputs u = [Thrust, torque_roll, torque_pitch, torque_yaw] into pwm values (T coordinates)\nT coordinates assumes: u = [KT    KT    KT   KT   ] [pwm1^2]\n                            0     -KT*L 0    KT*L ] [pwm2^2]\n                            -KT*L 0     KT*L 0    ] [pwm3^2]\n                            KM    -KM   KM   -KM  ] [pwm4^2]    \nKT = thrust coefficient for the propellers\nKM = moment coefficient for the propellers */\n// Matrix<float, 4, 1> u2pwmTshape(Matrix<float, 4, 1> u){\n// \t//u = M.pwm^2 ==> pwm^2 = inv(M)*u\n\n// \tMatrix<float, 4, 4> inv_M;\n// \tMatrix<float, 4, 1> pwm_squared, pwm;\n\n// \tinv_M << 1 / (4 * KT), 0, -1 / (2 * KT * RAD), 1 / (4 * KM),\n// \t\t\t 1 / (4 * KT), -1 / (2 * KT * RAD), 0, -1 / (4 * KM),\n// \t\t\t 1 / (4 * KT), 0, 1 / (2 * KT * RAD), 1 / (4 * KM),\n// \t\t\t 1 / (4 * KT), 1 / (2 * KT * RAD), 0, -1 / (4 * KM);\n\n\t\n// \tpwm_squared = inv_M*u;\n\n// \t//Saturate pwm values before taking square root to avoid square root of negative numbers\n// \tfloat mean_pwmSq = u(0) / (4 * KT);\n// \tpwm_squared << saturate(pwm_squared(0), 0, 2 * mean_pwmSq),\n// \t\t\t\t   saturate(pwm_squared(1), 0, 2 * mean_pwmSq),\n// \t\t\t\t   saturate(pwm_squared(2), 0, 2 * mean_pwmSq),\n// \t\t\t\t   saturate(pwm_squared(3), 0, 2 * mean_pwmSq);\n\n// \t//Assign outputs (note that Mikicopter assign minimum value at 1000\n// \tpwm << sqrt(pwm_squared(0))/1000,\n// \t\t   sqrt(pwm_squared(1))/1000,\n// \t\t   sqrt(pwm_squared(2))/1000,\n// \t\t   sqrt(pwm_squared(3))/1000;\n// // PrintVec4(pwm,\"pwm\");\n// \treturn pwm;\n// }\n\nMatrix<float, 4, 1> Thrusts2PWM(Matrix<float, 4, 1> thrusts){\n\n\tMatrix<float, 4, 1> pwm;\n\tfloat val;\n\t// float KT_bSqr = pow(KT_b,2);\n\n\t//Solution to quadratic equation KT_a.x^2 + KT_b.x - thrust = 0\n\tfor (int i = 0; i < 4; i++){\n\t\tval = (-KT_b+sqrt(KT_bSQR + 4*thrusts(i)*KT_a))/(2*KT_a);\n\t\tpwm(i) = saturate(val,0,1000);\n\t}\n\n\t// pwm << sqrt(thrusts(0) / KT_a)/1000,\n\t// \t   sqrt(thrusts(1) / KT_a)/1000,\n\t// \t   sqrt(thrusts(2) / KT_a)/1000,\n\t// \t   sqrt(thrusts(3) / KT_a)/1000;\n\n\t//Assign outputs in range 0-1 (we calibrated KTs using 0-1000 range)\n\treturn pwm*0.001;\n}\n\n/* Convert inputs u = [Thrust, torque_roll, torque_pitch, torque_yaw] into pwm values (T coordinates)\nT coordinates assumes: u = [1    1   1    1  ] [PWM1(T1)]\n\t\t\t\t\t\t   [0   -L   0    L  ] [PWM2(T2)]\n\t\t\t\t\t\t   [-L   0   L    0  ] [PWM3(T3)]\n\t\t\t\t\t\t   [Ctm -Ctm Ctm -Ctm] [PWM4(T4)]\nCtm = ratio between Moment and Thrust per propeller */\nMatrix<float, 4, 1> u2pwmTshape(Matrix<float, 4, 1> u){\n\t//u = M.pwm^2 ==> pwm^2 = inv(M)*u\n\n\tMatrix<float, 4, 4> inv_M;\n\tMatrix<float, 4, 1> thrusts;\n\n\tinv_M << 1 / 4.0, 0,             -1 / (2 * RAD), 1 / (4 * Ctm),\n\t\t\t 1 / 4.0, -1 / (2 * RAD), 0,            -1 / (4 * Ctm),\n\t\t\t 1 / 4.0, 0,              1 / (2 * RAD), 1 / (4 * Ctm),\n\t\t\t 1 / 4.0, 1 / (2 * RAD),  0,            -1 / (4 * Ctm);\n\n\t\n\tthrusts = inv_M*u;\n\n\t//Saturate pwm values before taking square root to avoid square root of negative numbers\n\tfloat mean_thrusts = u(0) / 4.0;\n\tthrusts <<  saturate(thrusts(0), 0, 2 * mean_thrusts),\n\t\t\t    saturate(thrusts(1), 0, 2 * mean_thrusts),\n\t\t\t\tsaturate(thrusts(2), 0, 2 * mean_thrusts),\n\t\t\t\tsaturate(thrusts(3), 0, 2 * mean_thrusts);\n\n\treturn Thrusts2PWM(thrusts);\n}\n\n/* Convert inputs u = [Thrust, torque_roll, torque_pitch, torque_yaw] into pwm values (X coordinates)\nX coordinates assumes: u =[1    0      0       0 ] [1    1   1    1  ] [PWM1(T1)]\n\t\t\t\t\t\t  [0    cos(o) -sin(o) 0 ] [0   -L   0    L  ] [PWM2(T2)]\n\t\t\t\t\t\t  [0    sin(o) cos(o)  0 ] [-L   0   L    0  ] [PWM3(T3)]\n\t\t\t\t\t\t  [0    0      0       1 ] [Ctm -Ctm Ctm -Ctm] [PWM4(T4)]    \nCtm = ratio between Moment and Thrust per propeller */\nMatrix<float, 4, 1> u2pwmXshape(Matrix<float, 4, 1> u){\n\t// double angle = PI / 4;\t//Angle between T coordinates and X coordinates\n\tMatrix<float, 4, 4> Rot;\t\t\t\t//Rotation matrix (note that the inverse of a rotation matrix is its transpose)\n\t//u.v[3] = 0;\n\t// Rot(.M[0][0]) = 1; Rot.M[0][1] = 0;           Rot.M[0][2] = 0;          Rot.M[0][3] = 0;\n\t// Rot.M[1][0] = 0; Rot.M[1][1] = cos(angle);  Rot.M[1][2] = sin(angle); Rot.M[1][3] = 0;\n\t// Rot.M[2][0] = 0; Rot.M[2][1] = -sin(angle); Rot.M[2][2] = cos(angle); Rot.M[2][3] = 0;\n\t// Rot.M[3][0] = 0; Rot.M[3][1] = 0;           Rot.M[3][2] = 0;          Rot.M[3][3] = 1;\n\n\tRot << 1,       0,      0, 0,\n\t\t   0,  COS_45, SIN_45, 0,\n\t\t   0, -SIN_45, COS_45, 0,\n\t\t   0,       0,      0, 1;\n\t//PrintVec4(u,\"u\");\n\n\t//Multiply inverse of rotation matrix by input u\n\tMatrix<float, 4, 1> uX = Rot*u;\n\t//PrintMat4x4(Rot);\n\t//PrintVec4(uX,\"uX\");\n\t// u2pwmTshape2(uX);\n\treturn u2pwmTshape(uX);\n}\n", "meta": {"hexsha": "adc73b13fc013a98bc4fee0d74169f68b19a73ad", "size": 8134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/AGNC-Lab_Quad/multithreaded/control/AttitudeControl.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/AttitudeControl.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/AttitudeControl.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": 36.9727272727, "max_line_length": 147, "alphanum_fraction": 0.6025325793, "num_tokens": 3107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684334, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6245038724742157}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <sophus/se3.hpp>\n\nusing namespace std;\nusing namespace cv;\n\n// Functions Get the matching points\nvoid find_feature_matches(const Mat &img_1, const Mat &img_2,std::vector<KeyPoint> &keypoints_1,\n  std::vector<KeyPoint> &keypoints_2,std::vector<DMatch> &matches);\n\n// Functions to Change the pixel points into camera normalization points\nPoint2d pixel2cam(const Point2d &p, const Mat &K);\n\n// using SVD for getting the ICP problem \nvoid solveIcp(const vector<Point3f> & pts1,const vector<Point3f> & pts2, Mat & R, Mat &t );\n\n\nint main(int argc, char const *argv[])\n{\n if (argc != 5) {\n    cout << \"usage: pose_estimation_3d3d img1 img2 depth1 depth2\" << endl;\n    return 1;\n  }\n // ORB-BRIEF\n  Mat img_1 = imread(argv[1], CV_LOAD_IMAGE_COLOR);\n  Mat img_2 = imread(argv[2], CV_LOAD_IMAGE_COLOR);\n// Keypoints and corresponding pairs\n  std::vector<KeyPoint> keypoints_01;\n  std::vector<KeyPoint> keypoints_02;\n  std::vector<DMatch> matches;\n\n  find_feature_matches(img_1,img_2, keypoints_01,keypoints_02,matches);\n  cout<<\"There is totally \"<< matches.size()<<\" matches found\"<<endl;\n\n    // \u5efa\u7acb2D\u70b9\u5bf9\u5e94\u76843D\u70b9\n  Mat depth1 = imread(argv[3], CV_LOAD_IMAGE_UNCHANGED);       // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n  Mat depth2 = imread(argv[4], CV_LOAD_IMAGE_UNCHANGED);       // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n  Mat K = (Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1); // Camera \u5185\u53c2\n  vector<Point3f> pts1, pts2;\n\n for (DMatch m:matches) {\n     //\u627e\u5230 Pairs\u5bf9\u5e94\u76843D\u70b9\u5750\u6807 depth\n    ushort d1 = depth1.ptr<unsigned short>(int(keypoints_01[m.queryIdx].pt.y))[int(keypoints_01[m.queryIdx].pt.x)];   \n    ushort d2 = depth2.ptr<unsigned short>(int(keypoints_02[m.trainIdx].pt.y))[int(keypoints_02[m.trainIdx].pt.x)];\n    if (d1 == 0 || d2 == 0)   // bad depth\n      continue;\n    Point2d p1 = pixel2cam(keypoints_01[m.queryIdx].pt, K);   // Camera X'/Z', Y'/Z'\n    Point2d p2 = pixel2cam(keypoints_02[m.trainIdx].pt, K);\n    float dd1 = float(d1) / 5000.0;  // \u5b9a\u4e49\u4e00\u4e2a\u5355\u4f4d\u957f\u5ea6 \u5c31\u662f\u5b9a\u4e49\u4e00\u4e2aZ'\n    float dd2 = float(d2) / 5000.0;\n    pts1.push_back(Point3f(p1.x * dd1, p1.y * dd1, dd1));  // \u5b9a\u4e49\u4e00\u4e2a\u5355\u4f4d\u957f\u5ea6 \u5c31\u662f\u5b9a\u4e49\u4e00\u4e2aZ'\n    pts2.push_back(Point3f(p2.x * dd2, p2.y * dd2, dd2));\n  }\n\n  cout << \"3d-3d pairs: \" << pts1.size() << endl;\n   // Solve ICP by SVD\n   Mat R; Mat t;\n   solveIcp(pts1,pts2,R,t);\n   cout<< \"R is \"<<\"\\n\"<<R<<endl;\n   cout<<\"t is \"<<\"\\n\"<<t<<endl;\n \n// You can Also Using G2O for Bundle Adjustment\n\n    return 0;\n}\n\nvoid find_feature_matches(const Mat &img_1, const Mat &img_2,\n                          std::vector<KeyPoint> &keypoints_1,\n                          std::vector<KeyPoint> &keypoints_2,\n                          std::vector<DMatch> &matches) {\n  //-- \u521d\u59cb\u5316\n  Mat descriptors_1, descriptors_2;\n  // used in OpenCV3\n  Ptr<FeatureDetector> detector = ORB::create();\n  Ptr<DescriptorExtractor> descriptor = ORB::create();\n  // use this if you are in OpenCV2\n  // Ptr<FeatureDetector> detector = FeatureDetector::create ( \"ORB\" );\n  // Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( \"ORB\" );\n  Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n  //-- \u7b2c\u4e00\u6b65:\u68c0\u6d4b Oriented FAST \u89d2\u70b9\u4f4d\u7f6e\n  detector->detect(img_1, keypoints_1);\n  detector->detect(img_2, keypoints_2);\n\n  //-- \u7b2c\u4e8c\u6b65:\u6839\u636e\u89d2\u70b9\u4f4d\u7f6e\u8ba1\u7b97 BRIEF \u63cf\u8ff0\u5b50\n  descriptor->compute(img_1, keypoints_1, descriptors_1);\n  descriptor->compute(img_2, keypoints_2, descriptors_2);\n\n  //-- \u7b2c\u4e09\u6b65:\u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n  vector<DMatch> match;\n  //BFMatcher matcher ( NORM_HAMMING );\n  matcher->match(descriptors_1, descriptors_2, match);\n\n  //-- \u7b2c\u56db\u6b65:\u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n  double min_dist = 10000, max_dist = 0;\n\n  //\u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb\n  for (int i = 0; i < descriptors_1.rows; i++) {\n    double dist = match[i].distance;\n    if (dist < min_dist) min_dist = dist;\n    if (dist > max_dist) max_dist = dist;\n  }\n  //\u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n  for (int i = 0; i < descriptors_1.rows; i++) {\n    if (match[i].distance <= max(2 * min_dist, 30.0)) {\n      matches.push_back(match[i]);\n    }\n  }\n}\n\nPoint2d pixel2cam(const Point2d &p, const Mat &K) {\n  return Point2d\n    (\n      (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n      (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n    );\n}\n\n\nvoid solveIcp(const vector<Point3f> & pts1,const vector<Point3f> & pts2, Mat & R, Mat &t ){\n // \u8ba1\u7b97\u8d28\u5fc3\n Point3f p1_mean, p2_mean;  // p1 and p2 are pairs\nfor(int i =0; i<pts1.size();i++){\n    p1_mean+= pts1[i];\n    p2_mean+= pts2[i];\n    }\nint nums_points=pts1.size();\np1_mean =  p1_mean / nums_points;\np2_mean = p2_mean / nums_points;\n// \u5f97\u5230pts1 \u548c pts2 \u7684\u53bb\u6389\u8d28\u5fc3\u7684\u5750\u6807\nvector <Point3f> pts1_after(nums_points); // \u52a8\u6001\u5206\u914d\u5185\u5b58\nvector <Point3f> pts2_after(nums_points); // \u52a8\u6001\u5206\u914d\u5185\u5b58\n\nfor(int i =0;i<nums_points;i++){\npts1_after[i] = pts1[i] - p1_mean;\npts2_after[i] = pts2[i] - p2_mean;\n    }\n// Get W matrix \nEigen::Matrix3d W = Eigen::Matrix3d::Zero(); // init with 0\nfor(int i =0;i<pts1.size();i++){\n    W += Eigen::Vector3d(pts1_after[i].x, pts1_after[i].y,pts1_after[i].z) * Eigen::Vector3d(pts2_after[i].x, pts2_after[i].y, pts2_after[i].z).transpose();\n }\n cout<< \" W matirx for SVD to Solving the R is \"<<W<<endl;\n\n // \u5bf9 W \u8fdb\u884c SVD \u5206\u89e3\n  // SVD on W\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Eigen::Matrix3d U = svd.matrixU();\n  Eigen::Matrix3d V = svd.matrixV();\n  Eigen:: Matrix3d matrix_R = U *(V.transpose());\n  Eigen:: Vector3d t_ = Eigen::Vector3d(p1_mean.x,p1_mean.y,p1_mean.z) - matrix_R * Eigen::Vector3d(p2_mean.x,p2_mean.y,p2_mean.z) ;\n\n  R = (Mat_<double>(3,3)<<matrix_R(0,0),matrix_R(0,1),matrix_R(0,2),\n  matrix_R(1,0),matrix_R(1,1),matrix_R(1,2),\n  matrix_R(2,0),matrix_R(2,1),matrix_R(2,2));\n  t =(Mat_<double>(3,1)<<t_(0,0),t_(1,0),t_(2,0));\n\n}", "meta": {"hexsha": "22f9855b64e50616e0fe80eff7cad99b599cd588", "size": 6220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vision_slam/VO/pose_estimation/pose_estimation_3d3d.cpp", "max_stars_repo_name": "kant/VO", "max_stars_repo_head_hexsha": "2acf9cb88eb2ec43adc272b57fd140bcace53e97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-20T04:52:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T04:52:45.000Z", "max_issues_repo_path": "vision_slam/VO/pose_estimation/pose_estimation_3d3d.cpp", "max_issues_repo_name": "kant/VO", "max_issues_repo_head_hexsha": "2acf9cb88eb2ec43adc272b57fd140bcace53e97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vision_slam/VO/pose_estimation/pose_estimation_3d3d.cpp", "max_forks_repo_name": "kant/VO", "max_forks_repo_head_hexsha": "2acf9cb88eb2ec43adc272b57fd140bcace53e97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-05T23:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T23:30:49.000Z", "avg_line_length": 36.3742690058, "max_line_length": 156, "alphanum_fraction": 0.6704180064, "num_tokens": 2259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418116217418, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.6245023346846779}}
{"text": "//\n// Created by Xiang on 2017/12/19.\n//\n\n#include <opencv2/opencv.hpp>\n#include <string>\n#include <chrono>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace cv;\n\nstring file_1 = \"../LK1.png\";  // first image\nstring file_2 = \"../LK2.png\";  // second image\n\ninline double get(const cv::Mat &img, float x, float y) {\n    // boundary check\n    if (x < 0) x = 0;\n    if (y < 0) y = 0;\n    if (x >= img.cols - 1) x = img.cols - 2;\n    if (y >= img.rows - 1) y = img.rows - 2;\n    \n    double xx = x - floor(x);\n    double yy = y - floor(y);\n    int x_a1 = std::min(img.cols - 1, int(x) + 1);\n    int y_a1 = std::min(img.rows - 1, int(y) + 1);\n    \n    return (1 - xx) * (1 - yy) * img.at<uchar>(y, x)\n    + xx * (1 - yy) * img.at<uchar>(y, x_a1)\n    + (1 - xx) * yy * img.at<uchar>(y_a1, x)\n    + xx * yy * img.at<uchar>(y_a1, x_a1);\n}\n\n\nvoid opticalFlowLK_linear(const cv::Mat& img1, const cv::Mat& img2, \n                          const std::vector<cv::Point2f>& kps1, std::vector<cv::Point2f>& kps2,\n                          std::vector<bool>& success)\n{\n    kps2 = kps1;\n    success.resize(kps1.size(), true);\n    for (int iter = 0; iter < 10; ++iter)\n    {\n        for (int i = 0; i < kps1.size(); ++i)\n        {\n            auto& kp = kps1[i];\n            int half_w_size = 4;\n\n            int idx = 0;\n            Eigen::Matrix<double, Eigen::Dynamic, 2> A(static_cast<int>(std::pow(half_w_size*2+1, 2)), 2);\n            Eigen::Matrix<double, Eigen::Dynamic, 1> b(static_cast<int>(std::pow(half_w_size*2+1, 2)), 1);\n\n            for (int xx = -half_w_size; xx <= half_w_size; ++xx)\n            {\n                for (int yy = -half_w_size; yy <= half_w_size; ++yy)\n                {\n                    double grad_x = 0.5 * (get(img1, kp.x+xx+1, kp.y+yy) - get(img1, kp.x+xx-1, kp.y+yy));\n                    double grad_y = 0.5 * (get(img1, kp.x+xx, kp.y+yy+1) - get(img1, kp.x+xx, kp.y+yy-1));\n                    double grad_t = get(img2, kps2[i].x+xx, kps2[i].y+yy) - get(img1, kp.x+xx, kp.y+yy);\n                    A(idx, 0) = grad_x;\n                    A(idx, 1) = grad_y;\n                    b(idx, 0) = grad_t;\n                    ++idx;\n                }\n            }\n            Eigen::Vector2d uv = -(A.transpose() * A).inverse() * A.transpose() * b;\n\n            if (std::isnan(uv.x()) || std::isnan(uv.y()))\n            {\n                success[i] = false;\n            }\n\n            kps2[i].x += uv.x();\n            kps2[i].y += uv.y();\n        }\n    }\n}\n\nvoid opticalFlowLK_gauss_newton(const cv::Mat& img1, const cv::Mat& img2, \n                                const std::vector<cv::Point2f>& kps1, std::vector<cv::Point2f>& kps2,\n                                std::vector<bool>& success, bool inverse=false, bool reinit_kps2=true)\n{\n    if (reinit_kps2)\n    {\n        std::cout << \"re-init pts in img2 with points in img1\" << std::endl;\n        kps2 = kps1;\n    }\n    int max_iters = 10;\n    success.resize(kps1.size(), true);\n    for (int i = 0; i < kps1.size(); ++i)\n    {\n        Eigen::Matrix2d H = Eigen::Matrix2d::Zero();\n        Eigen::Vector2d g = Eigen::Vector2d::Zero();\n        double prev_cost = 0.0;\n        double cost = 0.0;\n        int half_w_size = 4;\n\n        for (int iter = 0; iter < max_iters; ++iter)\n        {\n            prev_cost = cost;\n            cost = 0.0;\n            if (!inverse)\n            {\n                H = Eigen::Matrix2d::Zero();\n                g = Eigen::Vector2d::Zero();\n            }\n            else\n            {\n                g = Eigen::Vector2d::Zero();\n            }\n\n            for (int xx = -half_w_size; xx <= half_w_size; ++xx)\n            {\n                for (int yy = -half_w_size; yy <= half_w_size; ++yy)\n                {\n                    double err = get(img1, kps1[i].x+xx, kps1[i].y+yy) - get(img2, kps2[i].x+xx, kps2[i].y+yy);\n                    double grad_x, grad_y;\n                    if (!inverse)\n                    {\n                        grad_x = 0.5 * (get(img2, kps2[i].x+xx+1, kps2[i].y+yy) -   get(img2, kps2[i].x+xx-1, kps2[i].y+yy));\n                        grad_y = 0.5 * (get(img2, kps2[i].x+xx,   kps2[i].y+yy+1) - get(img2, kps2[i].x+xx,   kps2[i].y+yy-1));\n                    }\n                    else if (iter == 0) // if inverse mode, j and H are only computed once\n                    {\n                        grad_x = 0.5 * (get(img1, kps1[i].x+xx+1, kps1[i].y+yy) -   get(img1, kps1[i].x+xx-1, kps1[i].y+yy));\n                        grad_y = 0.5 * (get(img1, kps1[i].x+xx,   kps1[i].y+yy+1) - get(img1, kps1[i].x+xx,   kps1[i].y+yy-1));\n                    }\n                    Eigen::Vector2d J(-grad_x, -grad_y);\n                    if (inverse == false || iter == 0)\n                    {\n                        H += J * J.transpose();\n                    }\n                    g += -J * err;\n                    cost += err * err;\n                }\n            }\n\n            Eigen::Vector2d uv = H.ldlt().solve(g);\n            if (std::isnan(uv.x()) || std::isnan(uv.y()))\n            {\n                success[i] = false;\n                break;\n            }\n\n            if (iter > 0 && prev_cost < cost)\n                break;\n\n            kps2[i].x += uv.x();\n            kps2[i].y += uv.y();\n\n            if (uv.norm() < 1e-2)\n                break; // converged\n        }\n    }\n\n    \n}\n\nvoid opticalFlowLK_gauss_newton_pyramid(const cv::Mat& img1, const cv::Mat& img2, \n                                        const std::vector<cv::Point2f>& kps1, std::vector<cv::Point2f>& kps2,\n                                        std::vector<bool>& success, int n_layers)\n{\n    int factor = 2;\n    double scale = 1.0 / std::pow(factor, n_layers-1);\n    std::vector<cv::Point2f> kps2_s;\n    for (int si = 0; si < n_layers; ++si)\n    {\n        std::cout << \"scale = \" << scale << \"\\n\";\n        cv::Mat img1_s;\n        cv::resize(img1, img1_s, cv::Size(), scale, scale);\n        cv::Mat img2_s;\n        cv::resize(img2, img2_s, cv::Size(), scale, scale);\n        std::vector<cv::Point2f> kps1_s = kps1;\n        for (auto& p : kps1_s)\n        {\n            p.x *= scale;\n            p.y *= scale;\n        }\n        std::cout << \"img size = \" << img1_s.size() << \"\\n\";\n        opticalFlowLK_gauss_newton(img1_s, img2_s, kps1_s, kps2_s, success, true, si==0);\n\n        if (si < n_layers-1)\n        {\n            for (auto& p : kps2_s)\n            {\n                p.x *= factor;\n                p.y *= factor;\n            }\n        }\n\n        scale *= factor;\n    }\n    kps2 = kps2_s;\n}\n\nint main(int argc, char **argv) {\n\n    // images, note they are CV_8UC1, not CV_8UC3\n    Mat img1 = imread(file_1, 0);\n    Mat img2 = imread(file_2, 0);\n\n    // key points, using GFTT here.\n    vector<KeyPoint> kp1;\n    Ptr<GFTTDetector> detector = GFTTDetector::create(500, 0.01, 20); // maximum 500 keypoints\n    detector->detect(img1, kp1);\n\n   \n    // // use opencv's flow for validation\n    // vector<Point2f> pt1, pt2;\n    // for (auto &kp: kp1) pt1.push_back(kp.pt);\n    // vector<uchar> status;\n    // vector<float> error;\n    // auto t1 = chrono::steady_clock::now();\n    // cv::calcOpticalFlowPyrLK(img1, img2, pt1, pt2, status, error);\n    // auto t2 = chrono::steady_clock::now();\n    // auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    // cout << \"optical flow by opencv: \" << time_used.count() << endl;\n\n\n    std::vector<cv::Point2f> pts1(kp1.size()), pts2;\n    for (int i = 0; i < kp1.size(); ++i)\n        pts1[i] = kp1[i].pt;\n    std::vector<uchar> status;\n    std::vector<float> errors;\n    auto t1 = chrono::steady_clock::now();\n    cv::calcOpticalFlowPyrLK(img1, img2, pts1, pts2, status, errors);\n    auto t2 = chrono::steady_clock::now();\n    auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"optical flow by opencv: \" << time_used.count() << endl;\n\n\n    Mat img2_CV;\n    cv::cvtColor(img2, img2_CV, CV_GRAY2BGR);\n    for (int i = 0; i < pts2.size(); i++) {\n        if (status[i]) {\n            cv::circle(img2_CV, pts2[i], 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_CV, pts1[i], pts2[i], cv::Scalar(0, 250, 0));\n        }\n    }\n    // cv::imshow(\"tracked by opencv\", img2_CV);\n    // cv::waitKey(0);\n    cv::imwrite(\"lk_opencv.png\", img2_CV);\n\n\n    // --- LK with linear solution\n    std::vector<cv::Point2f> pts3;\n    std::vector<bool> success;\n    t1 = chrono::steady_clock::now();\n    opticalFlowLK_linear(img1, img2, pts1, pts3, success);\n    t2 = chrono::steady_clock::now();\n    time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"optical flow by LK linear: \" << time_used.count() << endl;\n\n    Mat img2_LK;\n    cv::cvtColor(img2, img2_LK, CV_GRAY2BGR);\n    for (int i = 0; i < pts3.size(); i++) {\n        if (status[i]) {\n            cv::circle(img2_LK, pts3[i], 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_LK, pts1[i], pts3[i], cv::Scalar(0, 250, 0));\n        }\n    }\n    cv::imwrite(\"lk_linear.png\", img2_LK);\n\n\n    // --- LK with Gauss-Newton\n    std::vector<cv::Point2f> pts4;\n    t1 = chrono::steady_clock::now();\n    opticalFlowLK_gauss_newton(img1, img2, pts1, pts4, success, false);\n    t2 = chrono::steady_clock::now();\n    time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"optical flow by LK Gauss-Newton: \" << time_used.count() << endl;\n    Mat img2_GN;\n    cv::cvtColor(img2, img2_GN, CV_GRAY2BGR);\n    for (int i = 0; i < pts4.size(); i++) {\n        if (status[i]) {\n            cv::circle(img2_GN, pts4[i], 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_GN, pts1[i], pts4[i], cv::Scalar(0, 250, 0));\n        }\n    }\n    cv::imwrite(\"lk_gauss-newton.png\", img2_GN);\n\n    // --- LK with Gauss-Newton (inverse)\n    std::vector<cv::Point2f> pts5;\n    t1 = chrono::steady_clock::now();\n    opticalFlowLK_gauss_newton(img1, img2, pts1, pts5, success, true);\n    t2 = chrono::steady_clock::now();\n    time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"optical flow by LK Gauss-Newton inverse: \" << time_used.count() << endl;\n\n    Mat img2_GN_inv;\n    cv::cvtColor(img2, img2_GN_inv, CV_GRAY2BGR);\n    for (int i = 0; i < pts5.size(); i++) {\n        if (status[i]) {\n            cv::circle(img2_GN_inv, pts5[i], 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_GN_inv, pts1[i], pts5[i], cv::Scalar(0, 250, 0));\n        }\n    }\n    cv::imwrite(\"lk_gauss-newton_inverse.png\", img2_GN_inv);\n\n\n    // --- LK with Pyramidal Gauss-Newton (multi-layers)\n    std::vector<cv::Point2f> pts6;\n    t1 = chrono::steady_clock::now();\n    opticalFlowLK_gauss_newton_pyramid(img1, img2, pts1, pts6, success, 4);\n    t2 = chrono::steady_clock::now();\n    time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"optical flow by LK Pyramidal Gauss-Newton: \" << time_used.count() << endl;\n\n    Mat img2_GN_Py;\n    cv::cvtColor(img2, img2_GN_Py, CV_GRAY2BGR);\n    for (int i = 0; i < pts6.size(); i++) {\n        if (status[i]) {\n            cv::circle(img2_GN_Py, pts6[i], 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_GN_Py, pts1[i], pts6[i], cv::Scalar(0, 250, 0));\n        }\n    }\n    cv::imwrite(\"lk_gauss-newton_pyramidal.png\", img2_GN_Py);\n\n\n    return 0;\n}\n", "meta": {"hexsha": "357d652a25e599849cf21ac2009cdd5ed01798b5", "size": 11271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch8/optical_flow_lk.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch8/optical_flow_lk.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch8/optical_flow_lk.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": 35.0031055901, "max_line_length": 127, "alphanum_fraction": 0.5025286133, "num_tokens": 3637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6245019866839416}}
{"text": "//  Boost integer/static_log2.hpp header file  -------------------------------//\n\n//  (C) Copyright Daryle Walker 2001.  Permission to copy, use, modify, sell and\n//  distribute this software is granted provided this copyright notice appears \n//  in all copies.  This software is provided \"as is\" without express or\n//  implied warranty, and with no claim as to its suitability for any purpose. \n\n//  See http://www.boost.org for updates, documentation, and revision history. \n\n#ifndef BOOST_INTEGER_STATIC_LOG2_HPP\n#define BOOST_INTEGER_STATIC_LOG2_HPP\n\n#include <boost/integer_fwd.hpp>  // self include\n\n#include <boost/config.hpp>  // for BOOST_STATIC_CONSTANT\n#include <boost/limits.hpp>  // for std::numeric_limits\n\n\nnamespace boost\n{\n\n\n//  Implementation details  --------------------------------------------------//\n\nnamespace detail\n{\n\n// Forward declarations\ntemplate < unsigned long Val, int Place = 0, int Index\n = std::numeric_limits<unsigned long>::digits >\n    struct static_log2_helper_t;\n\ntemplate < unsigned long Val, int Place >\n    struct static_log2_helper_t< Val, Place, 1 >;\n\n// Recursively build the logarithm by examining the upper bits\ntemplate < unsigned long Val, int Place, int Index >\nstruct static_log2_helper_t\n{\nprivate:\n    BOOST_STATIC_CONSTANT( int, half_place = Index / 2 );\n    BOOST_STATIC_CONSTANT( unsigned long, lower_mask = (1ul << half_place)\n     - 1ul );\n    BOOST_STATIC_CONSTANT( unsigned long, upper_mask = ~lower_mask );\n    BOOST_STATIC_CONSTANT( bool, do_shift = (Val & upper_mask) != 0ul );\n\n    BOOST_STATIC_CONSTANT( unsigned long, new_val = do_shift ? (Val\n     >> half_place) : Val );\n    BOOST_STATIC_CONSTANT( int, new_place = do_shift ? (Place + half_place)\n     : Place );\n    BOOST_STATIC_CONSTANT( int, new_index = Index - half_place );\n\n    typedef static_log2_helper_t<new_val, new_place, new_index>  next_step_type;\n\npublic:\n    BOOST_STATIC_CONSTANT( int, value = next_step_type::value );\n\n};  // boost::detail::static_log2_helper_t\n\n// Non-recursive case\ntemplate < unsigned long Val, int Place >\nstruct static_log2_helper_t< Val, Place, 1 >\n{\npublic:\n    BOOST_STATIC_CONSTANT( int, value = Place );\n\n};  // boost::detail::static_log2_helper_t\n\n}  // namespace detail\n\n\n//  Compile-time log-base-2 evaluator class declaration  ---------------------//\n\ntemplate < unsigned long Value >\nstruct static_log2\n{\n    BOOST_STATIC_CONSTANT( int, value\n     = detail::static_log2_helper_t<Value>::value );\n};\n\ntemplate < >\nstruct static_log2< 0ul >\n{\n    // The logarithm of zero is undefined.\n};\n\n\n}  // namespace boost\n\n\n#endif  // BOOST_INTEGER_STATIC_LOG2_HPP\n", "meta": {"hexsha": "436250e090cf5539c5cdda751d78987acbb3c093", "size": 2623, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/integer/static_log2.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/integer/static_log2.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_28/boost/integer/static_log2.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["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.5108695652, "max_line_length": 80, "alphanum_fraction": 0.6984369043, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6245019866839416}}
{"text": "#ifndef CPPMATH_MATRIX_PSEUDOINVERSESVD_IMPL_HPP_\n#define CPPMATH_MATRIX_PSEUDOINVERSESVD_IMPL_HPP_\n\n#include <Eigen/Core>\n\n#include \"PseudoInverseSVD.hpp\"\n\nnamespace cppmath\n{\n    template< typename T >\n    PseudoInverseSVD< T >::PseudoInverseSVD( const T& matrix, float threshold ) :\n                    Eigen::JacobiSVD< T >( matrix, Eigen::ComputeThinU | Eigen::ComputeThinV ), m_threshold( threshold )\n    {\n        m_hasInverse = false;\n    }\n\n    template< typename T >\n    PseudoInverseSVD< T >::~PseudoInverseSVD< T >()\n    {\n    }\n\n    template< typename T >\n    const T& PseudoInverseSVD< T >::compute()\n    {\n        if( !m_hasInverse )\n        {\n            compute( &m_inverse );\n            m_hasInverse = true;\n        }\n        return m_inverse;\n    }\n\n    template< typename T >\n    void PseudoInverseSVD< T >::compute( T* const pinvmat ) const\n    {\n        if( m_hasInverse )\n        {\n            *pinvmat = m_inverse;\n        }\n        else\n        {\n\n            eigen_assert( Eigen::JacobiSVD< T >::m_isInitialized && \"SVD is not initialized.\" );\n            typename Eigen::JacobiSVD< T >::SingularValuesType singularValues_inv = Eigen::JacobiSVD< T >::m_singularValues;\n            for( long i = 0; i < Eigen::JacobiSVD< T >::m_workMatrix.cols(); ++i )\n            {\n                if( Eigen::JacobiSVD< T >::m_singularValues( i ) > m_threshold )\n                    singularValues_inv( i ) = 1.0 / Eigen::JacobiSVD< T >::m_singularValues( i );\n                else\n                    singularValues_inv( i ) = 0;\n            }\n            *pinvmat = ( Eigen::JacobiSVD< T >::m_matrixV * singularValues_inv.asDiagonal()\n                            * Eigen::JacobiSVD< T >::m_matrixU.transpose() );\n        }\n    }\n\n    template< typename T >\n    T PseudoInverseSVD< T >::operator*( const T& m )\n    {\n        if( !m_hasInverse )\n        {\n            compute( &m_inverse );\n            m_hasInverse = true;\n        }\n        return m_inverse * m;\n    }\n\n    template< typename T >\n    T PseudoInverseSVD< T >::operator*( const T& m ) const\n    {\n        if( m_hasInverse )\n        {\n            m_inverse * m;\n        }\n        else\n        {\n            T inv;\n            compute( &inv );\n            return inv * m;\n        }\n    }\n} /* namespace cppmath */\n\n#endif  // CPPMATH_MATRIX_PSEUDOINVERSESVD_IMPL_HPP_\n", "meta": {"hexsha": "32c4002ef88432a9649a4a57fee3b42279f893c0", "size": 2343, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cppmath/matrix/PseudoInverseSVD-impl.hpp", "max_stars_repo_name": "cpieloth/CppMath", "max_stars_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cppmath/matrix/PseudoInverseSVD-impl.hpp", "max_issues_repo_name": "cpieloth/CppMath", "max_issues_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cppmath/matrix/PseudoInverseSVD-impl.hpp", "max_forks_repo_name": "cpieloth/CppMath", "max_forks_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5647058824, "max_line_length": 124, "alphanum_fraction": 0.5394793, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7217432182679957, "lm_q1q2_score": 0.6244696138821292}}
{"text": "//\n// Copyright 2019 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n#ifndef BOOST_GIL_IMAGE_PROCESSING_HARRIS_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_HARRIS_HPP\n\n#include <boost/gil/image_view.hpp>\n#include <boost/gil/typedefs.hpp>\n#include <boost/gil/extension/numeric/kernel.hpp>\n\nnamespace boost { namespace gil {\n/// \\defgroup CornerDetectionAlgorithms\n/// \\brief Algorithms that are used to find corners in an image\n///\n/// These algorithms are used to find spots from which\n/// sliding the window will produce large intensity change\n\n\n/// \\brief function to record Harris responses\n/// \\ingroup CornerDetectionAlgorithms\n///\n/// This algorithm computes Harris responses\n/// for structure tensor represented by m11, m12_21, m22 views.\n/// Note that m12_21 represents both entries (1, 2) and (2, 1).\n/// Window length represents size of a window which is slided around\n/// to compute sum of corresponding entries. k is a discrimination\n/// constant against edges (usually in range 0.04 to 0.06).\n/// harris_response is an out parameter that will contain the Harris responses.\ntemplate <typename T, typename Allocator>\nvoid compute_harris_responses(\n    boost::gil::gray32f_view_t m11,\n    boost::gil::gray32f_view_t m12_21,\n    boost::gil::gray32f_view_t m22,\n    boost::gil::detail::kernel_2d<T, Allocator> weights,\n    float k,\n    boost::gil::gray32f_view_t harris_response)\n{\n    if (m11.dimensions() != m12_21.dimensions() || m12_21.dimensions() != m22.dimensions()) {\n        throw std::invalid_argument(\"m prefixed arguments must represent\"\n            \" tensor from the same image\");\n    }\n\n    std::ptrdiff_t const window_length = weights.size();\n    auto const width = m11.width();\n    auto const height = m11.height();\n    auto const half_length = window_length / 2;\n\n    for (auto y = half_length; y < height - half_length; ++y)\n    {\n        for (auto x = half_length; x < width - half_length; ++x)\n        {\n            float ddxx = 0;\n            float dxdy = 0;\n            float ddyy = 0;\n            for (gil::gray32f_view_t::coord_t y_kernel = 0;\n                y_kernel < window_length;\n                ++y_kernel) {\n                for (gil::gray32f_view_t::coord_t x_kernel = 0;\n                    x_kernel < window_length;\n                    ++x_kernel) {\n                    ddxx += m11(x + x_kernel - half_length, y + y_kernel - half_length)\n                        .at(std::integral_constant<int, 0>{}) * weights.at(x_kernel, y_kernel);\n                    dxdy += m12_21(x + x_kernel - half_length, y + y_kernel - half_length)\n                        .at(std::integral_constant<int, 0>{}) * weights.at(x_kernel, y_kernel);\n                    ddyy += m22(x + x_kernel - half_length, y + y_kernel - half_length)\n                        .at(std::integral_constant<int, 0>{}) * weights.at(x_kernel, y_kernel);\n                }\n            }\n            auto det = (ddxx * ddyy) - dxdy * dxdy;\n            auto trace = ddxx + ddyy;\n            auto harris_value = det - k * trace * trace;\n            harris_response(x, y).at(std::integral_constant<int, 0>{}) = harris_value;\n        }\n    }\n}\n\n}} //namespace boost::gil\n#endif\n", "meta": {"hexsha": "18185afd8164ef86db6baf3cf03e4843398e386a", "size": 3358, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/harris.hpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "include/boost/gil/image_processing/harris.hpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "include/boost/gil/image_processing/harris.hpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 40.4578313253, "max_line_length": 95, "alphanum_fraction": 0.6381774866, "num_tokens": 838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6244696110498527}}
{"text": "/*\n * $Revision: 565 $ $Date: 2011-02-15 16:00:43 -0800 (Tue, 15 Feb 2011) $\n *\n * Copyright by Astos Solutions GmbH, Germany\n *\n * this file is published under the Astos Solutions Free Public License\n * For details on copyright and terms of use see\n * http://www.astos.de/Astos_Solutions_Free_Public_License.html\n */\n\n#include \"GeneralEllipse.h\"\n#include <Eigen/QR>\n#include <cmath>\n\nusing namespace vesta;\nusing namespace Eigen;\nusing namespace std;\n\n\n/** Compute the principal semi-axes of the ellipsoid. The axes\n  * are the rows of the returned matrix. Note that there is no\n  * ordering of semi-major or semi-minor axes.\n  */\nMatrix<double, 3, 2>\nGeneralEllipse::principalSemiAxes() const\n{\n    Matrix2d S;\n    double s00 = m_generatingVectors.col(0).dot(m_generatingVectors.col(0));\n    double s01 = m_generatingVectors.col(0).dot(m_generatingVectors.col(1));\n    double s11 = m_generatingVectors.col(1).dot(m_generatingVectors.col(1));\n    double s10 = s01;\n    S << s00, s01, s10, s11;\n\n    SelfAdjointEigenSolver<Matrix2d> solver(S, true);\n    Vector2d e = solver.eigenvalues();\n    Matrix2d ev = solver.eigenvectors();\n\n    Matrix<double, 3, 2> result;\n    result.col(0) = ev(0, 0) * m_generatingVectors.col(0) + ev(1, 0) * m_generatingVectors.col(1);\n    result.col(1) = ev(0, 1) * m_generatingVectors.col(0) + ev(1, 1) * m_generatingVectors.col(1);\n\n    return result;\n}\n", "meta": {"hexsha": "de4bf085f2c84347344fa8ac4cc0de89b1bed7c5", "size": 1384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/vesta/GeneralEllipse.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "thirdparty/vesta/GeneralEllipse.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "thirdparty/vesta/GeneralEllipse.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 31.4545454545, "max_line_length": 98, "alphanum_fraction": 0.7030346821, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6244695981845093}}
{"text": "#include \"luminosityHadronic.h\"\n#include <gsl/gsl_sf_bessel.h>\n#include <fparameters/parameters.h>\n#include <fmath/RungeKutta.h>\n#include <nrMath/integrators.h>\n#include <fmath/interpolation.h>\n#include <flosses/crossSectionInel.h>\n#include <fmath/physics.h>\n#include <algorithm>\n\n#include <gsl/gsl_math.h>\n\n#include <boost/math/special_functions/bessel.hpp>\n\n\n\ndouble fntHadron(double x, const Particle& p, const double density, const SpaceCoord& psc) //funcion a integrar   x=Ecreator; L=L(Ega)\n{\t\n\tdouble Kpi = 0.17;\n\tdouble eval = p.mass*cLight2+x/Kpi;\n\t\n\t//double Ekin = Ep/Kpi;\n\t\n\tdouble distCreator = 0.0;\n\tif (eval < p.emax() && eval > p.emin()) {\n\t\tdistCreator = p.distribution.interpolate({ { 0, eval } }, &psc);\n\t}\n\t\n\t//double thr = 0.0016; //1GeV\n\t//double sigma = 30e-27*(0.95+0.06*log(Ekin/thr));\n\t\n\tdouble Eth = 1.22e9 * EV_TO_ERG;\n\tdouble l = log10((protonMass*cLight2+x/Kpi)/1.6); //evaluada en eval\n\tdouble sigma = 1.e-27 * (34.3+1.88*l+0.25*l*l) * P2(1.0 - pow(Eth/eval,4));\n\tdouble pionEmiss = cLight*density*sigma*distCreator/Kpi;  //sigma = crossSectionHadronicDelta(Ekin)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  //lo saco asi pongo la condicion Ekin > Ethr en el limite de la int\n\t\n\tdouble result = pionEmiss/sqrt(P2(x)-P2(chargedPionMass*cLight2));\n\treturn (x > chargedPionMass*cLight2 ? result : 0.0);\n}\n\ndouble luminosityNTHadronic(double E, const Particle& creator,\n\tconst double density, const SpaceCoord& psc)\n{\n\tdouble Kpi = 0.17;\n\tdouble thr = 0.0016; //1GeV\n\n\tdouble Max  = creator.emax();   //esto es un infinito \n\tdouble Min  = std::max(E+P2(chargedPionMass*cLight2)/(4*E),thr*Kpi); //== Ekin > Ethr\n\tMin = E+0.25*P2(chargedPionMass*cLight2)/E;\n\tdouble integral = integSimpsonLog(Min, Max,[&](double x)\n\t\t\t\t{\n\t\t\t\t\treturn fntHadron(x,creator,density,psc);\n\t\t\t\t},100);\n\t//double integral = RungeKuttaSimple(Min, Max, \n\t//\t[&](double x) {return fntHadron(x, creator, density, psc); }\n\t//);    //integra entre Emin y Emax\n\n\tdouble luminosity = 2.0*integral*P2(E); // [erg s^-1 cm^-3 ]\n\n\treturn luminosity; \n}\n\ndouble fntHadronTh(double x, const double temp, const double density, const SpaceCoord& psc) //funcion a integrar   x=Ecreator; L=L(Ega)\n{\t\n\tdouble Kpi = 0.17;\n\tdouble eval = protonMass*cLight2+x/Kpi;\n\t\n\t//double Ekin = Ep/Kpi;\n\tdouble g = eval / (protonMass*cLight2);\n\tdouble beta = sqrt(1.0-1.0/(g*g));\n\tdouble theta = boltzmann*temp/(protonMass*cLight2);\n\tdouble bessel = gsl_sf_bessel_Kn(2, 1.0/theta);\n\tdouble distCreator = (bessel > 0.0 ? density * g*g*beta / (theta*bessel) * exp(-g/theta) / (protonMass*cLight2) : 0.0);\n\t\n\t//double thr = 0.0016; //1GeV\n\t//double sigma = 30e-27*(0.95+0.06*log(Ekin/thr));\n\t\n\tdouble Eth = 1.22e9 * EV_TO_ERG;\n\tdouble l = log10((protonMass*cLight2+x/Kpi)/1.6); //evaluada en eval\n\tdouble sigma = 1.e-27 * (34.3+1.88*l+0.25*l*l) * P2(1.0 - pow(Eth/eval,4));\n\tdouble pionEmiss = cLight*density*sigma*distCreator/Kpi;  //sigma = crossSectionHadronicDelta(Ekin)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  //lo saco asi pongo la condicion Ekin > Ethr en el limite de la int\n\t\n\tdouble result = pionEmiss/sqrt(P2(x)-P2(chargedPionMass*cLight2));\n\treturn (x > chargedPionMass*cLight2 ? result : 0.0);\n}\n\ndouble luminosityThHadronic(double E, const double temp,\n\tconst double density, const SpaceCoord& psc)\n{\n\tdouble Kpi = 0.17;\n\tdouble thr = 0.0016; //1GeV\n\n\tdouble Max  = pow(10,1.5)*protonMass*cLight2;   //esto es un infinito \n\tdouble Min  = std::max(E+P2(chargedPionMass*cLight2)/(4*E),thr*Kpi); //== Ekin > Ethr\n\tMin = E+0.25*P2(chargedPionMass*cLight2)/E;\n\tdouble integral = (Min < Max ? integSimpsonLog(Min, Max,[&](double x)\n\t\t\t\t{\n\t\t\t\t\treturn fntHadronTh(x,temp, density,psc);\n\t\t\t\t},100) : 0.0);\n\t//double integral = RungeKuttaSimple(Min, Max, \n\t//\t[&](double x) {return fntHadron(x, creator, density, psc); }\n\t//);    //integra entre Emin y Emax\n\n\tdouble luminosity = 2.0*integral*P2(E); // [erg s^-1 cm^-3 ]\n\n\treturn 2.0*luminosity; \n}\n\n\n\n\n\n/*\nclass luminosityHadronic2;\n\ndouble heaviside(double x,double a,double b)\n{\n\treturn (a <= x && x <= b ? 1.0 : 0.0);\n}\n\ndouble auxf3(double dGeV, void *params)\n{\n\tstruct four_d_params *p = (struct four_d_params *) params;\n\tdouble sGeV = p->p1;\n\tdouble gx = p->p2;\n\tdouble GammaGeV = p->p3;\n\tdouble isoGeV = p->p4;\n\t\n\tdouble pGeV = protonMass*cLight2/1.6e-3;\n\tdouble piGeV = neutralPionMass*cLight2/1.6e-3;\n\tdouble gd = (sGeV + dGeV*dGeV - pGeV*pGeV)/(2.0*dGeV*sqrt(sGeV));\n\tdouble betad = sqrt(1.0-1.0/(gd*gd));\n\tdouble epi = (dGeV*dGeV+piGeV*piGeV-pGeV*pGeV)/(2.0*dGeV);\n\tdouble ppi = sqrt(epi*epi-piGeV*piGeV);\n\tdouble aux1 = 0.5/(betad*gd*ppi);   // REVISAR ESTE p_pi\n\tdouble aux2 = P2(dGeV-isoGeV)+GammaGeV*GammaGeV;\n\tdouble h = heaviside(gx*piGeV,gd*(epi-betad*ppi),gd*(epi+betad*ppi));\n\t\n\treturn aux1*h/aux2;    // [GeV^-3]\n\t\n}\n\ndouble inclusiveSigma(double sGeV)\n{\n\tdouble pGeV = protonMass*cLight2/1.6e-3;\n\tdouble piGeV = neutralPionMass*cLight2/1.6e-3;\n\tdouble eta=sqrt(P2(sGeV-P2(piGeV)-P2(2.0*pGeV))-4.0*P2(piGeV*2.0*pGeV))/(2.0*piGeV*sqrt(sGeV));\n\tdouble pthr = 0.78; //[GeV]\n\tdouble sigma=0.0;;\n\n\tdouble p = sqrt(P2(0.5*sGeV/pGeV-pGeV)-P2(pGeV));\n\t\n\tif (p >= pthr && p <= 0.96) {\n\t\tsigma = 0.032*eta*eta+0.04*pow(eta,6)+0.047*pow(eta,8);\n\t} else if (p > 0.96 && p <= 1.27) {\n\t\tsigma = 32.6*pow(p-0.8,3.21);\n\t} else if (p > 1.27 && p <= 8.0) {\n\t\tsigma = 5.4*pow(p-0.8,0.81);\n\t} else if (p > 8.0) {\n\t\tsigma = 32.0 * log(p) + 48.5 / sqrt(p) - 59.5;\n\t}\n\treturn 1.0e-27 * sigma;     // [cm^2]\n}\n\ndouble dsigma(double gx, double gr, double sGeV)\n{\n\tdouble error;\n\tint status;\n\t\n\tdouble GammaGeV = 0.0575;\n\tdouble pGeV = protonMass*cLight2/1.6e-3;\n\tdouble piGeV = neutralPionMass * cLight2 / 1.6e-3;\n\tdouble isoGeV = 1.236;\n\tdouble atan1 = atan((sqrt(sGeV)-pGeV-isoGeV)/GammaGeV);\n\tdouble atan2 = atan((pGeV+piGeV-isoGeV)/GammaGeV);\n\tdouble aux1 = GammaGeV/(atan1-atan2);\n\t\n\tdouble Min = pGeV+piGeV;\n\tdouble Max = sqrt(sGeV)-pGeV;\n\t\n\tstruct four_d_params auxf3_params = {sGeV,gx,GammaGeV,isoGeV};\n\tgsl_function gsl_auxf3;\n\t\tgsl_auxf3.function = &auxf3;\n\t\tgsl_auxf3.params = &auxf3_params;\n\t\n\tdouble integ = integrator_qags(&gsl_auxf3,Min,Max,0,1.0e-2,100,&error,&status);\n\t\n\treturn inclusiveSigma(sGeV)*aux1*integ*piGeV;  // [cm^2]\n}\n\ndouble auxf2(double gx, void *params)\n{\n\tstruct four_d_params *p = (struct four_d_params *) params;\n\tdouble gr = p->p1;\n\tdouble epi = p->p2;\n\tdouble normtemp = p->p3;\n\tdouble sGeV = p->p4;\n\t\n\tdouble piGeV = neutralPionMass*cLight2/1.6e-3;\n\tdouble g = epi/piGeV;\n\tdouble beta = sqrt(1.0-1.0/(g*g));\n\tdouble betax = sqrt(1.0-1.0/(gx*gx));\n\tdouble q = sqrt(2.0*(gr+1.0))/normtemp;\n\t\n\tdouble f1 = exp(-q*g*gx*(1.0-beta*betax))-exp(-q*g*gx*(1.0+beta*betax));\n\t\n\treturn f1/(betax*gx) * dsigma(gx,gr,sGeV);\n}\n\ndouble auxf(double gr, void *params)\n{\n\tdouble error;\n\tint status;\n\t\n\tstruct two_d_params *p = (struct two_d_params *) params;\n\tdouble epi = p->p1;\n\tdouble normtemp = p->p2;\n\t\n\tdouble piGeV = neutralPionMass*cLight2 / 1.6e-3;\n\tdouble pGeV = protonMass*cLight2/1.6e-3;\n\tdouble sGeV = 2.0*P2(pGeV)*(gr+1.0);\n\tdouble ji = (sGeV-4.0*P2(pGeV)+P2(piGeV))/(2.0*sqrt(sGeV));\n\tdouble Max = ji/piGeV;\n\t\n\tstruct four_d_params auxf2_params = {gr,epi,normtemp,sGeV};\n\tgsl_function gsl_auxf2;\n\t\tgsl_auxf2.function = &auxf2;\n\t\tgsl_auxf2.params = &auxf2_params;\n\t\n\tdouble integral = integrator_qags(&gsl_auxf2,1.0,Max,0,1.0e-2,100,&error,&status);\n\tdouble result = (gr*gr-1.0) / sqrt(2.0*(gr+1.0)) * integral;\n}\n\ndouble fPion(double epi, double density, double temp)\n{\n\tdouble error;\n\tint status;\n\t\n\tdouble normtemp = boltzmann* temp / (protonMass*cLight2);\n\tstruct two_d_params auxf_params = {epi,normtemp};\n\tgsl_function gsl_auxf;\n\t\tgsl_auxf.function = &auxf;\n\t\tgsl_auxf.params = &auxf_params;\n\n\tdouble k2 = boost::math::cyl_bessel_k(2, 1.0/normtemp);\n\tdouble piGeV = neutralPionMass*cLight2/1.6e-3;\n\tdouble constant = cLight*density*density/(4.0*piGeV*normtemp*k2*k2);\n\n\treturn constant * integrator_qags(&gsl_auxf,1.0,1.0e3,0,1.0e-2,100,&error,&status);\n}\n\ndouble fHadron(double epi, void *params)\n{\n\tstruct two_d_params *p = (struct two_d_params *) params;\n\tdouble density = p->p1;\n\tdouble temp= p->p2;\n\t\n\tdouble piGeV = neutralPionMass*cLight2/1.6e-3;\n\tdouble qpi = fPion(epi,density,temp);\n\treturn qpi / sqrt(P2(epi)-P2(piGeV));   // [cm-3 s-1 GeV-2]\n}\n\n\ndouble luminosityHadronic2(double E, const double density, double temp)\n{\n\tdouble error;\n\tint status;\n\t\n\tstruct two_d_params fHadron_params = {density,temp};\n\tgsl_function gsl_fHadron;\n\t\tgsl_fHadron.function = &fHadron;\n\t\tgsl_fHadron.params = &fHadron_params;\n\t\n\tdouble Kpi = 0.17;\n\tdouble thr = 0.0016; //1GeV\n\n\tdouble Min  = cHadron(E);\n\tMin = Min / 1.6e-3;\n\tdouble Max = 1.0e3;  // [en GeV]\n\t\n\tdouble integral = 2.0 * integrator_qags(&gsl_fHadron,Min,Max,0,1.0e-2,100,&error,&status);\n\t\t\n\tdouble jpp = integral * E*planck * 0.25/pi; // [erg s^-1 Hz^-1 cm^-3]\n\tjpp = jpp / (1.6e-3);\n\treturn jpp;\n}*/", "meta": {"hexsha": "c81bbaa565e25ea6e796aac85b5877e0addd67cb", "size": 8766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/fluminosities/luminosityNTHadronic.cpp", "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_issues_repo_path": "src/lib/fluminosities/luminosityNTHadronic.cpp", "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/fluminosities/luminosityNTHadronic.cpp", "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4375, "max_line_length": 136, "alphanum_fraction": 0.6711156742, "num_tokens": 3259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7217432062975978, "lm_q1q2_score": 0.6244695934919855}}
{"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_CSCD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_CSCD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the cosecant in degree: \\f$1/\\sin(180/(\\pi x))\\f$.\n\n\n    @par Header <boost/simd/function/cscd.hpp>\n\n    @par Note\n\n     As most other trigonometric function cscd can be called with a\n     second optional parameter  which is a tag on speed and accuracy\n     (see @ref cos for further details)\n\n\n    @see csc, cscpi,\n\n\n    @par Example:\n\n      @snippet cscd.cpp cscd\n\n    @par Possible output:\n\n      @snippet cscd.txt cscd\n\n  **/\n  IEEEValue cscd(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/cscd.hpp>\n#include <boost/simd/function/simd/cscd.hpp>\n\n#endif\n", "meta": {"hexsha": "3c8c4757627538f3f045259b77e72c6188c6c81f", "size": 1201, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/cscd.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/cscd.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/cscd.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.0961538462, "max_line_length": 100, "alphanum_fraction": 0.5886761032, "num_tokens": 282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6244341265811538}}
{"text": "#include <iostream>\n#include <gtest/gtest.h>\n#include \"../frame_transforms.h\"\n#include <boost/math/constants/constants.hpp>\n\nusing namespace snark::frame_transforms;\n\nTEST(transforms, dh_to_matrix)\n{\n    dh_transform T_dh;\n    T_dh.alpha=1;\n    T_dh.r=1;\n    T_dh.theta=boost::math::constants::pi<double>()/6;\n    T_dh.alpha=-boost::math::constants::pi<double>()/2;\n    EXPECT_LT((dh_to_matrix(T_dh)-(Eigen::Matrix4d()<<0.866025,0,-0.5,0.866025,0.5,0,0.866025,0.5,0,-1,0,0,0,0,0,1).finished()).norm(),1e-2);\n\n}\n\nTEST(transforms, dh_to_tr)\n{\n    dh_transform T_dh;\n    T_dh.alpha=1;\n    T_dh.r=1;\n    T_dh.theta=boost::math::constants::pi<double>()/6;\n    T_dh.alpha=-boost::math::constants::pi<double>()/2;\n    tr_transform T_tr=dh_to_tr(T_dh);\n    EXPECT_LT((homogeneous_transform(T_tr.rotation.toRotationMatrix(),T_tr.translation)-(Eigen::Matrix4d()<<0.866025,0,-0.5,0.866025,0.5,0,0.866025,0.5,0,-1,0,0,0,0,0,1).finished()).norm(),1e-2);\n\n}\n\nint main(int argc, char *argv[])\n{\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "3ae302685c5651ecc63e594168879abfa4b0627f", "size": 1054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/test/frame_transforms_test.cpp", "max_stars_repo_name": "jackiecx/snark", "max_stars_repo_head_hexsha": "492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T15:21:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T15:21:24.000Z", "max_issues_repo_path": "math/test/frame_transforms_test.cpp", "max_issues_repo_name": "jackiecx/snark", "max_issues_repo_head_hexsha": "492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/test/frame_transforms_test.cpp", "max_forks_repo_name": "jackiecx/snark", "max_forks_repo_head_hexsha": "492c1b6f26b9e3e8ea6fc66ad1a8c7f997f90ec6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2777777778, "max_line_length": 195, "alphanum_fraction": 0.674573055, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6244341210559111}}
{"text": "// -*- coding: utf-8 -*-\r\n#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN\r\n\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <doctest/doctest.h>\r\n//#include <fmt/format.h>\r\n#include <netoptim/min_cycle_ratio.hpp>\r\n#include <netoptim/neg_cycle.hpp> // import negCycleFinder\r\n#include <py2cpp/nx2bgl.hpp>\r\n#include <utility> // for std::pair\r\n#include <vector>\r\n\r\nusing graph_t = boost::adjacency_list<\r\n    boost::listS, boost::vecS, boost::directedS, boost::no_property,\r\n    boost::property<boost::edge_weight_t, int, boost::property<boost::edge_index_t, int>>>;\r\nusing Vertex  = boost::graph_traits<graph_t>::vertex_descriptor;\r\nusing Edge_it = boost::graph_traits<graph_t>::edge_iterator;\r\n\r\nstatic auto create_test_case1() -> xn::grAdaptor<graph_t>\r\n{\r\n    using Edge           = std::pair<int, int>;\r\n    const auto num_nodes = 5;\r\n    enum nodes\r\n    {\r\n        A,\r\n        B,\r\n        C,\r\n        D,\r\n        E\r\n    };\r\n    static Edge    edge_array[] = {Edge{A, B}, Edge{B, C}, Edge{C, D}, Edge{D, E}, Edge{E, A}};\r\n    int            weights[]    = {-5, 1, 1, 1, 1};\r\n    int            num_arcs     = sizeof(edge_array) / sizeof(Edge);\r\n    auto g = graph_t(edge_array, edge_array + num_arcs, weights, num_nodes);\r\n    return xn::grAdaptor<graph_t> {std::move(g)};\r\n}\r\n\r\nstatic auto create_test_case2() -> xn::grAdaptor<graph_t>\r\n{\r\n    using Edge           = std::pair<int, int>;\r\n    const auto num_nodes = 5;\r\n    enum nodes\r\n    {\r\n        A,\r\n        B,\r\n        C,\r\n        D,\r\n        E\r\n    };\r\n    static Edge    edge_array[] = {Edge{A, B}, Edge{B, C}, Edge{C, D}, Edge{D, E}, Edge{E, A}};\r\n    int            weights[]    = {2, 1, 1, 1, 1};\r\n    int            num_arcs     = sizeof(edge_array) / sizeof(Edge);\r\n    auto g = graph_t(edge_array, edge_array + num_arcs, weights, num_nodes);\r\n    return xn::grAdaptor<graph_t> {std::move(g)};\r\n}\r\n\r\nstatic auto create_test_case_timing() -> xn::grAdaptor<graph_t>\r\n{\r\n    using Edge           = std::pair<int, int>;\r\n    const auto num_nodes = 3;\r\n    enum nodes\r\n    {\r\n        A,\r\n        B,\r\n        C\r\n    };\r\n    static Edge    edge_array[] = {Edge{A, B}, Edge{B, A}, Edge{B, C}, Edge{C, B},\r\n                                Edge{B, C}, Edge{C, B}, Edge{C, A}, Edge{A, C}};\r\n    int            weights[]    = {7, 0, 3, 1, 6, 4, 2, 5};\r\n    int            num_arcs     = sizeof(edge_array) / sizeof(Edge);\r\n    auto g = graph_t(edge_array, edge_array + num_arcs, weights, num_nodes);\r\n    return xn::grAdaptor<graph_t> {std::move(g)};\r\n}\r\n\r\nauto do_case(xn::grAdaptor<graph_t>& G) -> bool\r\n{\r\n    using edge_t = typename xn::grAdaptor<graph_t>::edge_t;\r\n\r\n    const auto get_weight = [&](const edge_t& e) -> int {\r\n        const auto& weightmap = boost::get(boost::edge_weight, G);\r\n        return weightmap[e];\r\n    };\r\n\r\n    auto N = negCycleFinder<xn::grAdaptor<graph_t>>(G);\r\n    auto dist = std::vector<int>(G.number_of_nodes(), 0);\r\n    const auto cycle = N.find_neg_cycle(dist, get_weight);\r\n    return !cycle.empty();\r\n}\r\n\r\nTEST_CASE(\"Test Negative Cycle\")\r\n{\r\n    xn::grAdaptor<graph_t> G = create_test_case1();\r\n    // boost::property_map<graph_t, boost::edge_weight_t>::type weightmap =\r\n    // boost::get(boost::edge_weight, G); std::vector<Vertex>\r\n    // p(boost::num_vertices(G));\r\n    bool hasNeg = do_case(G);\r\n    CHECK(hasNeg);\r\n\r\n    // G = xn::path_graph(5, create_using=xn::DiGraph());\r\n    // hasNeg = do_case(G);\r\n    // CHECK(!hasNeg);\r\n}\r\n\r\nTEST_CASE(\"Test No Negative Cycle\")\r\n{\r\n    xn::grAdaptor<graph_t> G      = create_test_case2();\r\n    bool                   hasNeg = do_case(G);\r\n    CHECK(!hasNeg);\r\n    // fmt::print(\"The answer is {}.\\n\", hasNeg);\r\n}\r\n\r\nTEST_CASE(\"Test Timing Graph\")\r\n{\r\n    xn::grAdaptor<graph_t> G      = create_test_case_timing();\r\n    bool                   hasNeg = do_case(G);\r\n    CHECK(!hasNeg);\r\n    // fmt::print(\"The answer is {}.\\n\", hasNeg);\r\n}\r\n", "meta": {"hexsha": "310c7a80e313a3136f12420e63aa71c18352d752", "size": 3924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/src/main.cpp", "max_stars_repo_name": "luk036/netoptimcpp", "max_stars_repo_head_hexsha": "29b24cea62f5bf70ffc04777ecf92da187110845", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/src/main.cpp", "max_issues_repo_name": "luk036/netoptimcpp", "max_issues_repo_head_hexsha": "29b24cea62f5bf70ffc04777ecf92da187110845", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/src/main.cpp", "max_forks_repo_name": "luk036/netoptimcpp", "max_forks_repo_head_hexsha": "29b24cea62f5bf70ffc04777ecf92da187110845", "max_forks_repo_licenses": ["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.7, "max_line_length": 96, "alphanum_fraction": 0.5723751274, "num_tokens": 1127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6244341184090341}}
{"text": "#include <armadillo>\n#include <iostream>\n\nusing namespace arma;\n\nint main() {\n    const size_t nr_rows {3};\n    const size_t nr_cols {2};\n    mat A(nr_rows, nr_cols);\n    for (size_t j = 0; j < A.n_cols; j++)\n        for (size_t i = 0; i < A.n_rows; i++)\n            A(i, j) = sqrt(i + j);\n    A.print(\"A:\");\n    A.transform([] (double x) { return x*x; });\n    A.print(\"A.^2:\");\n    mat B = A.submat(span(0, 1), span(0, 1));\n    B.print(\"B:\");\n    rowvec x = A.row(2);\n    x.print(\"x:\");\n    x(0) = 19.0;\n    x(1) = -13.0;\n    A.print(\"A:\");\n    return 0;\n}\n", "meta": {"hexsha": "6e458b943e8215e9800f8075b644a13a015d05a1", "size": 558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Armadillo/elementwise.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Armadillo/elementwise.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Armadillo/elementwise.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 22.32, "max_line_length": 47, "alphanum_fraction": 0.4910394265, "num_tokens": 198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.6244341111628712}}
{"text": "// [[Rcpp::depends(BH)]]\n#include <boost/math/distributions/negative_binomial.hpp>\n\n#ifdef UNIT_TEST_CPP\n#include \"code.h\"\nNumberVector get_nbinom_pdf(NumberVectorArg size, NumberVectorArg prob, NumberVectorArg xs)\n#else\n#include <Rcpp.h>\n// [[Rcpp::export]]\nRcpp::NumericVector get_nbinom_pdf(Rcpp::NumericVector size, Rcpp::NumericVector prob, Rcpp::NumericVector xs)\n#endif // UNIT_TEST_CPP\n{\n#ifndef UNIT_TEST_CPP\n    using NumberVector = Rcpp::NumericVector;\n#endif\n    NumberVector results;\n    try {\n        if ((size.size() == 1) && (prob.size() == 1)) {\n            boost::math::negative_binomial_distribution<> dist(size.at(0), prob.at(0));\n            for (const auto& x : xs) {\n                results.push_back(boost::math::pdf(dist, x));\n            }\n        }\n    } catch (std::exception& e) {\n        // Bad size or prob parameters\n    }\n\n    return results;\n}\n\n/*\nLocal Variables:\nmode: c++\ncoding: utf-8-unix\ntab-width: nil\nc-file-style: \"stroustrup\"\nEnd:\n*/\n", "meta": {"hexsha": "9c858f317e452d0fd104925a719e44877eb1462b", "size": 978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/code.cpp", "max_stars_repo_name": "zettsu-t/nbinomPlot", "max_stars_repo_head_hexsha": "cba3608d2a149cd56522a7b934d21b8c03daa875", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/code.cpp", "max_issues_repo_name": "zettsu-t/nbinomPlot", "max_issues_repo_head_hexsha": "cba3608d2a149cd56522a7b934d21b8c03daa875", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/code.cpp", "max_forks_repo_name": "zettsu-t/nbinomPlot", "max_forks_repo_head_hexsha": "cba3608d2a149cd56522a7b934d21b8c03daa875", "max_forks_repo_licenses": ["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.0769230769, "max_line_length": 110, "alphanum_fraction": 0.6492842536, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389113, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6243797738080329}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2020 Tinko Bartels, Berlin, Germany.\n\n// Contributed and/or modified by Tinko Bartels,\n//   as part of Google Summer of Code 2020 program.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n\n#define BOOST_GEOMETRY_NO_BOOST_TEST\n\n#include <iostream>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/geometries/point.hpp>\n\n#include <boost/geometry/extensions/triangulation/strategies/cartesian/side_robust.hpp>\n#include <boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/expressions.hpp>\n#include <boost/geometry/extensions/generic_robust_predicates/strategies/cartesian/detail/stage_a.hpp>\n\n\nnamespace bg = boost::geometry;\nusing point = bg::model::point<double, 2, bg::cs::cartesian>;\n\ntemplate <typename CalculationType>\nstruct side_robust_with_static_filter\n{\nprivate:\n    using ct = CalculationType;\n    using expression = bg::detail::generic_robust_predicates::orient2d;\n    using filter = bg::detail::generic_robust_predicates::stage_a_static\n            <\n                expression,\n                ct\n            >;\n    filter m_filter;\npublic:\n    side_robust_with_static_filter(ct x_max, ct y_max, ct x_min, ct y_min)\n        : m_filter(x_max, y_max, x_max, y_max, x_max, y_max,\n                   x_min, y_min, x_min, y_min, x_min, y_min) {};\n\n    template\n    <\n        typename P1,\n        typename P2,\n        typename P  \n    >\n    inline int apply(P1 const& p1, P2 const& p2, P const& p) const\n    {\n        int sign = m_filter.apply(bg::get<0>(p1),\n                                  bg::get<1>(p1),\n                                  bg::get<0>(p2),\n                                  bg::get<1>(p2),\n                                  bg::get<0>(p),\n                                  bg::get<1>(p));\n        if(sign != bg::detail::generic_robust_predicates::sign_uncertain)\n        {\n            return sign;\n        }\n        else\n        {\n            //fallback if filter fails.\n            return bg::strategy::side::side_robust<double>::apply(p1, p2, p);\n        }\n    }\n};\n\nint main(int argc, char** argv)\n{\n    point p1(0.0, 0.0);\n    point p2(1.0, 1.0);\n    point p (0.0, 1.0);\n    side_robust_with_static_filter<double> static_strategy(2.0, 2.0, 1.0, 1.0);\n    std::cout << \"Side value: \" << static_strategy.apply(p1, p2, p) << \"\\n\"; \n    return 0;\n}\n", "meta": {"hexsha": "c18ef3c4f1687f9e2d354c517c4d1ac399cea2df", "size": 2530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/example/generic_robust_predicates/static_side_2d.cpp", "max_stars_repo_name": "BoostGSoC20/geometry", "max_stars_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T20:30:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T08:14:05.000Z", "max_issues_repo_path": "extensions/example/generic_robust_predicates/static_side_2d.cpp", "max_issues_repo_name": "Srutip04/geometry", "max_issues_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extensions/example/generic_robust_predicates/static_side_2d.cpp", "max_forks_repo_name": "Srutip04/geometry", "max_forks_repo_head_hexsha": "5b63bdc9086829c4c00bf9f5e23c664430acdd48", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:43:59.000Z", "avg_line_length": 31.625, "max_line_length": 106, "alphanum_fraction": 0.6134387352, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6243797689473286}}
{"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__INTERNAL__SE3_HPP_\n#define SMOOTH__INTERNAL__SE3_HPP_\n\n#include <Eigen/Core>\n\n#include \"common.hpp\"\n#include \"smooth/derivatives.hpp\"\n#include \"so3.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief SE(3) Lie Group represented as S^3 \u22c9 R3\n *\n * Memory layout\n * -------------\n * Group:    x y z qx qy qz qw\n * Tangent:  vx vy vz \u03a9x \u03a9y \u03a9z\n *\n * Lie group Matrix form\n * ---------------------\n * [ R T ]\n * [ 0 1 ]\n *\n * where R \u2208 SO(3) and T = [x y z] \u2208 R3\n *\n * Lie algebra Matrix form\n * -----------------------\n * [  0 -\u03a9z  \u03a9y vx]\n * [  \u03a9z  0 -\u03a9x vy]\n * [ -\u03a9y \u03a9x   0 vz]\n * [   0  0   0  0]\n *\n * Constraints\n * -----------\n * Group:   qx * qx + qy * qy + qz * qz + qw * qw = 1\n * Tangent: -pi < \u03a9x \u03a9y \u03a9z <= pi\n */\ntemplate<typename _Scalar>\nclass SE3Impl\n{\npublic:\n  using Scalar = _Scalar;\n\n  static constexpr Eigen::Index RepSize = 7;\n  static constexpr Eigen::Index Dim     = 4;\n  static constexpr Eigen::Index Dof     = 6;\n  static constexpr bool IsCommutative   = false;\n\n  SMOOTH_DEFINE_REFS;\n\n  static void setIdentity(GRefOut g_out)\n  {\n    g_out.template head<6>().setZero();\n    g_out(6) = Scalar(1);\n  }\n\n  static void setRandom(GRefOut g_out)\n  {\n    g_out.template head<3>().setRandom();\n    SO3Impl<Scalar>::setRandom(g_out.template tail<4>());\n  }\n\n  static void matrix(GRefIn g_in, MRefOut m_out)\n  {\n    m_out.setIdentity();\n    SO3Impl<Scalar>::matrix(g_in.template tail<4>(), m_out.template topLeftCorner<3, 3>());\n    m_out.template topRightCorner<3, 1>() = g_in.template head<3>();\n  }\n\n  static void composition(GRefIn g_in1, GRefIn g_in2, GRefOut g_out)\n  {\n    SO3Impl<Scalar>::composition(\n      g_in1.template tail<4>(), g_in2.template tail<4>(), g_out.template tail<4>());\n    Eigen::Matrix<Scalar, 3, 3> R1;\n    SO3Impl<Scalar>::matrix(g_in1.template tail<4>(), R1);\n    g_out.template head<3>().noalias() = R1 * g_in2.template head<3>() + g_in1.template head<3>();\n  }\n\n  static void inverse(GRefIn g_in, GRefOut g_out)\n  {\n    Eigen::Matrix<Scalar, 4, 1> so3inv;\n    SO3Impl<Scalar>::inverse(g_in.template tail<4>(), so3inv);\n\n    Eigen::Matrix<Scalar, 3, 3> Rinv;\n    SO3Impl<Scalar>::matrix(so3inv, Rinv);\n\n    g_out.template head<3>().noalias() = -Rinv * g_in.template head<3>();\n    g_out.template tail<4>()           = so3inv;\n  }\n\n  static void log(GRefIn g_in, TRefOut a_out)\n  {\n    using SO3TangentMap = Eigen::Matrix<Scalar, 3, 3>;\n\n    SO3Impl<Scalar>::log(g_in.template tail<4>(), a_out.template tail<3>());\n\n    SO3TangentMap M_dr_expinv, M_ad;\n    SO3Impl<Scalar>::dr_expinv(a_out.template tail<3>(), M_dr_expinv);\n    SO3Impl<Scalar>::ad(a_out.template tail<3>(), M_ad);\n    a_out.template head<3>().noalias() = (-M_ad + M_dr_expinv) * g_in.template head<3>();\n  }\n\n  static void Ad(GRefIn g_in, TMapRefOut A_out)\n  {\n    SO3Impl<Scalar>::matrix(g_in.template tail<4>(), A_out.template topLeftCorner<3, 3>());\n    SO3Impl<Scalar>::hat(g_in.template head<3>(), A_out.template topRightCorner<3, 3>());\n    A_out.template topRightCorner<3, 3>() *= A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomRightCorner<3, 3>() = A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomLeftCorner<3, 3>().setZero();\n  }\n\n  static void exp(TRefIn a_in, GRefOut g_out)\n  {\n    using SO3TangentMap = Eigen::Matrix<Scalar, 3, 3>;\n\n    SO3Impl<Scalar>::exp(a_in.template tail<3>(), g_out.template tail<4>());\n\n    SO3TangentMap M_dr_exp, M_Ad;\n    SO3Impl<Scalar>::dr_exp(a_in.template tail<3>(), M_dr_exp);\n    SO3Impl<Scalar>::Ad(g_out.template tail<4>(), M_Ad);\n\n    g_out.template head<3>().noalias() = M_Ad * M_dr_exp * a_in.template head<3>();\n  }\n\n  static void hat(TRefIn a_in, MRefOut A_out)\n  {\n    A_out.setZero();\n    SO3Impl<Scalar>::hat(a_in.template tail<3>(), A_out.template topLeftCorner<3, 3>());\n    A_out.template topRightCorner<3, 1>() = a_in.template head<3>();\n  }\n\n  static void vee(MRefIn A_in, TRefOut a_out)\n  {\n    SO3Impl<Scalar>::vee(A_in.template topLeftCorner<3, 3>(), a_out.template tail<3>());\n    a_out.template head<3>() = A_in.template topRightCorner<3, 1>();\n  }\n\n  static void ad(TRefIn a_in, TMapRefOut A_out)\n  {\n    SO3Impl<Scalar>::hat(a_in.template tail<3>(), A_out.template topLeftCorner<3, 3>());\n    SO3Impl<Scalar>::hat(a_in.template head<3>(), A_out.template topRightCorner<3, 3>());\n    A_out.template bottomRightCorner<3, 3>() = A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomLeftCorner<3, 3>().setZero();\n  }\n\n  static Eigen::Matrix<Scalar, 3, 3> calculate_q(TRefIn a)\n  {\n    using std::abs, std::sqrt, std::cos, std::sin;\n\n    const Scalar th2 = a.template tail<3>().squaredNorm();\n\n    const auto [A, B, C] = [&]() -> std::array<Scalar, 3> {\n      if (th2 < Scalar(eps2)) {\n        return {\n          // https://www.wolframalpha.com/input/?i=series+%28x+-+sin+x%29+%2F+x%5E3+at+x%3D0\n          Scalar(1) / Scalar(6) - th2 / Scalar(120),\n          // https://www.wolframalpha.com/input/?i=series+%28cos+x+-+1+%2B+x%5E2%2F2%29+%2F+x%5E4+at+x%3D0\n          Scalar(1) / Scalar(24) - th2 / Scalar(720),\n          // https://www.wolframalpha.com/input/?i=series+%28x+-+sin+x+-+x%5E3%2F6%29+%2F+x%5E5+at+x%3D0\n          -Scalar(1) / Scalar(120) + th2 / Scalar(5040),\n        };\n      } else {\n        const Scalar th = sqrt(th2), th_4 = th2 * th2, cTh = cos(th), sTh = sin(th);\n        return {\n          (th - sTh) / (th * th2),\n          (cTh - Scalar(1) + th2 / Scalar(2)) / th_4,\n          (th - sTh - th * th2 / Scalar(6)) / (th_4 * th),\n        };\n      }\n    }();\n\n    Eigen::Matrix<Scalar, 3, 3> V, W;\n    SO3Impl<Scalar>::hat(a.template head<3>(), V);\n    SO3Impl<Scalar>::hat(a.template tail<3>(), W);\n\n    const Scalar vdw                     = a.template tail<3>().dot(a.template head<3>());\n    const Eigen::Matrix<Scalar, 3, 3> WV = W * V, VW = V * W, WW = W * W;\n\n    // clang-format off\n    return Scalar(0.5) * V + A * (WV + VW - vdw * W) + B * (W * WV + VW * W + vdw * (3 * W - WW)) - C * 3 * vdw * WW;\n    // clang-format on\n  }\n\n  static std::pair<Eigen::Matrix3<Scalar>, Eigen::Matrix<Scalar, 3, 18>> calculate_Q_dQ(TRefIn a)\n  {\n    const Eigen::Vector3<Scalar> v = a.template head<3>();\n    const Eigen::Vector3<Scalar> w = a.template tail<3>();\n    const Scalar th2               = w.squaredNorm();\n\n    const auto [A, B, C, dA_over_th, dB_over_th, dC_over_th] = [&]() -> std::array<Scalar, 6> {\n      if (th2 < Scalar(eps2)) {\n        return {\n          Scalar(1) / Scalar(6) - th2 / Scalar(120),\n          Scalar(1) / Scalar(24) - th2 / Scalar(720),\n          -Scalar(1) / Scalar(120) + th2 / Scalar(5040),\n          -Scalar(1) / 60,\n          -Scalar(1) / 360,\n          Scalar(1) / 2520,\n        };\n      } else {\n        const Scalar th  = sqrt(th2);\n        const Scalar th3 = th2 * th;\n        const Scalar th4 = th2 * th2;\n        const Scalar th5 = th3 * th2;\n        const Scalar th6 = th3 * th3;\n        const Scalar th7 = th4 * th3;\n        const Scalar sTh = sin(th);\n        const Scalar cTh = cos(th);\n        return {\n          (th - sTh) / (th3),\n          (cTh - Scalar(1) + th2 / Scalar(2)) / th4,\n          (th - sTh - th * th2 / Scalar(6)) / th5,\n          -cTh / th4 - 2 / th4 + 3 * sTh / th5,\n          -1 / th4 - sTh / th5 - 4 * cTh / th6 + 4 / th6,\n          1 / (3 * th4) - cTh / th6 - 4 / th6 + 5 * sTh / th7,\n        };\n      }\n    }();\n\n    Eigen::Matrix<Scalar, 3, 3> V, W;\n    SO3Impl<Scalar>::hat(a.template head<3>(), V);\n    SO3Impl<Scalar>::hat(a.template tail<3>(), W);\n    const Scalar vdw = v.dot(w);\n\n    const Eigen::Matrix3<Scalar> WV = W * V, VW = V * W, WW = W * W, PA = WV + VW - vdw * W,\n                                 PB = W * WV + VW * W + vdw * (3 * W - WW), PC = -3 * vdw * WW;\n\n    Eigen::Matrix3<Scalar> Q = V / 2 + A * PA + B * PB + C * PC;\n\n    // part with derivatives from matrices\n    // clang-format off\n    Eigen:: Matrix<Scalar, 3, 18> dQ {{ w.x()*(B + 3*C)*(w.y()*w.y() + w.z()*w.z()),\n      w.y()*(-2*A + B*(w.y()*w.y() + w.z()*w.z()) + 3*C*(w.y()*w.y() + w.z()*w.z())),\n      w.z()*(-2*A + B*(w.y()*w.y() + w.z()*w.z()) + 3*C*(w.y()*w.y() + w.z()*w.z())),\n      v.x()*(B + 3*C)*(w.y()*w.y() + w.z()*w.z()),\n      -2*A*v.y() + B*v.y()*(w.y()*w.y() + w.z()*w.z()) + 2*B*w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()) + 3*C*(v.y()*w.y()*w.y() + v.y()*w.z()*w.z() + 2*w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())),\n      -2*A*v.z() + B*v.z()*(w.y()*w.y() + w.z()*w.z()) + 2*B*w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()) + 3*C*(v.z()*w.y()*w.y() + v.z()*w.z()*w.z() + 2*w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())),\n      -A*(w.x()*w.z() - w.y()) - B*w.x()*(w.x()*w.y() - 2*w.z()) - 3*C*w.x()*w.x()*w.y(),\n      A*(w.x() - w.y()*w.z()) - B*w.y()*(w.x()*w.y() - 2*w.z()) - 3*C*w.x()*w.y()*w.y(),\n      -A*w.z()*w.z() - B*w.x()*w.x() - B*w.x()*w.y()*w.z() - B*w.y()*w.y() + B*w.z()*w.z() - 3*C*w.x()*w.y()*w.z() + Scalar(0.5),\n      -A*(v.x()*w.z() - v.y()) - B*(v.x()*w.z() + v.x()*(w.x()*w.y() - 3*w.z()) + 2*v.z()*w.x() + w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.x()*w.x()*w.y() - 3*C*w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()),\n      A*(v.x() - v.y()*w.z()) - B*(v.y()*w.z() + v.y()*(w.x()*w.y() - 3*w.z()) + 2*v.z()*w.y() + w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.y()*w.x()*w.y() - 3*C*w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()),\n      -A*(v.x()*w.x() + v.y()*w.y() + 2*v.z()*w.z()) + B*(2*v.x()*w.x() + 2*v.y()*w.y() - v.z()*w.z() - v.z()*(w.x()*w.y() - 3*w.z())) - 3*C*v.z()*w.x()*w.y(),\n      A*(w.x()*w.y() + w.z()) - B*w.x()*(w.x()*w.z() + 2*w.y()) - 3*C*w.x()*w.x()*w.z(),\n      A*w.y()*w.y() + B*w.x()*w.x() - B*w.x()*w.y()*w.z() - B*w.y()*w.y() + B*w.z()*w.z() - 3*C*w.x()*w.y()*w.z() - Scalar(0.5),\n      A*(w.x() + w.y()*w.z()) - B*w.z()*(w.x()*w.z() + 2*w.y()) - 3*C*w.x()*w.z()*w.z(),\n      A*(v.x()*w.y() + v.z()) + B*(v.x()*w.y() - v.x()*(w.x()*w.z() + 3*w.y()) + 2*v.y()*w.x() - w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.x()*w.x()*w.z() - 3*C*w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()),\n      A*(v.x()*w.x() + 2*v.y()*w.y() + v.z()*w.z()) - B*(2*v.x()*w.x() - v.y()*w.y() + v.y()*(w.x()*w.z() + 3*w.y()) + 2*v.z()*w.z()) - 3*C*v.y()*w.x()*w.z(),\n      A*(v.x() + v.z()*w.y()) + B*(2*v.y()*w.z() + v.z()*w.y() - v.z()*(w.x()*w.z() + 3*w.y()) - w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.z()*w.x()*w.z() - 3*C*w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())\n      }, {\n      A*(w.x()*w.z() + w.y()) - B*w.x()*(w.x()*w.y() + 2*w.z()) - 3*C*w.x()*w.x()*w.y(),\n      A*(w.x() + w.y()*w.z()) - B*w.y()*(w.x()*w.y() + 2*w.z()) - 3*C*w.x()*w.y()*w.y(),\n      A*w.z()*w.z() + B*w.x()*w.x() - B*w.x()*w.y()*w.z() + B*w.y()*w.y() - B*w.z()*w.z() - 3*C*w.x()*w.y()*w.z() - Scalar(0.5),\n      A*(v.x()*w.z() + v.y()) + B*(v.x()*w.z() - v.x()*(w.x()*w.y() + 3*w.z()) + 2*v.z()*w.x() - w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.x()*w.x()*w.y() - 3*C*w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()),\n      A*(v.x() + v.y()*w.z()) + B*(v.y()*w.z() - v.y()*(w.x()*w.y() + 3*w.z()) + 2*v.z()*w.y() - w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.y()*w.x()*w.y() - 3*C*w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()),\n      A*(v.x()*w.x() + v.y()*w.y() + 2*v.z()*w.z()) - B*(2*v.x()*w.x() + 2*v.y()*w.y() - v.z()*w.z() + v.z()*(w.x()*w.y() + 3*w.z())) - 3*C*v.z()*w.x()*w.y(),\n      w.x()*(-2*A + B*(w.x()*w.x() + w.z()*w.z()) + 3*C*(w.x()*w.x() + w.z()*w.z())),\n      w.y()*(B + 3*C)*(w.x()*w.x() + w.z()*w.z()),\n      w.z()*(-2*A + B*(w.x()*w.x() + w.z()*w.z()) + 3*C*(w.x()*w.x() + w.z()*w.z())),\n      -2*A*v.x() + B*v.x()*(w.x()*w.x() + w.z()*w.z()) + 2*B*w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()) + 3*C*(v.x()*w.x()*w.x() + v.x()*w.z()*w.z() + 2*w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())),\n      v.y()*(B + 3*C)*(w.x()*w.x() + w.z()*w.z()),\n      -2*A*v.z() + B*v.z()*(w.x()*w.x() + w.z()*w.z()) + 2*B*w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()) + 3*C*(v.z()*w.x()*w.x() + v.z()*w.z()*w.z() + 2*w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())),\n      -A*w.x()*w.x() + B*w.x()*w.x() - B*w.x()*w.y()*w.z() - B*w.y()*w.y() - B*w.z()*w.z() - 3*C*w.x()*w.y()*w.z() + Scalar(0.5),\n      -A*(w.x()*w.y() - w.z()) + B*w.y()*(2*w.x() - w.y()*w.z()) - 3*C*w.y()*w.y()*w.z(),\n      -A*(w.x()*w.z() - w.y()) + B*w.z()*(2*w.x() - w.y()*w.z()) - 3*C*w.y()*w.z()*w.z(),\n      -A*(2*v.x()*w.x() + v.y()*w.y() + v.z()*w.z()) + B*(-v.x()*w.x() + v.x()*(3*w.x() - w.y()*w.z()) + 2*v.y()*w.y() + 2*v.z()*w.z()) - 3*C*v.x()*w.y()*w.z(),\n      -A*(v.y()*w.x() - v.z()) - B*(2*v.x()*w.y() + v.y()*w.x() - v.y()*(3*w.x() - w.y()*w.z()) + w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.y()*w.y()*w.z() - 3*C*w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()),\n      A*(v.y() - v.z()*w.x()) - B*(2*v.x()*w.z() + v.z()*w.x() - v.z()*(3*w.x() - w.y()*w.z()) + w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.z()*w.y()*w.z() - 3*C*w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())\n      }, {\n      -A*(w.x()*w.y() - w.z()) - B*w.x()*(w.x()*w.z() - 2*w.y()) - 3*C*w.x()*w.x()*w.z(),\n      -A*w.y()*w.y() - B*w.x()*w.x() - B*w.x()*w.y()*w.z() + B*w.y()*w.y() - B*w.z()*w.z() - 3*C*w.x()*w.y()*w.z() + Scalar(0.5),\n      A*(w.x() - w.y()*w.z()) - B*w.z()*(w.x()*w.z() - 2*w.y()) - 3*C*w.x()*w.z()*w.z(),\n      -A*(v.x()*w.y() - v.z()) - B*(v.x()*w.y() + v.x()*(w.x()*w.z() - 3*w.y()) + 2*v.y()*w.x() + w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.x()*w.x()*w.z() - 3*C*w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()),\n      -A*(v.x()*w.x() + 2*v.y()*w.y() + v.z()*w.z()) + B*(2*v.x()*w.x() - v.y()*w.y() - v.y()*(w.x()*w.z() - 3*w.y()) + 2*v.z()*w.z()) - 3*C*v.y()*w.x()*w.z(),\n      A*(v.x() - v.z()*w.y()) - B*(2*v.y()*w.z() + v.z()*w.y() + v.z()*(w.x()*w.z() - 3*w.y()) + w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.z()*w.x()*w.z() - 3*C*w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()),\n      A*w.x()*w.x() - B*w.x()*w.x() - B*w.x()*w.y()*w.z() + B*w.y()*w.y() + B*w.z()*w.z() - 3*C*w.x()*w.y()*w.z() - Scalar(0.5),\n      A*(w.x()*w.y() + w.z()) - B*w.y()*(2*w.x() + w.y()*w.z()) - 3*C*w.y()*w.y()*w.z(),\n      A*(w.x()*w.z() + w.y()) - B*w.z()*(2*w.x() + w.y()*w.z()) - 3*C*w.y()*w.z()*w.z(),\n      A*(2*v.x()*w.x() + v.y()*w.y() + v.z()*w.z()) - B*(-v.x()*w.x() + v.x()*(3*w.x() + w.y()*w.z()) + 2*v.y()*w.y() + 2*v.z()*w.z()) - 3*C*v.x()*w.y()*w.z(),\n      A*(v.y()*w.x() + v.z()) + B*(2*v.x()*w.y() + v.y()*w.x() - v.y()*(3*w.x() + w.y()*w.z()) - w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.y()*w.y()*w.z() - 3*C*w.z()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()),\n      A*(v.y() + v.z()*w.x()) + B*(2*v.x()*w.z() + v.z()*w.x() - v.z()*(3*w.x() + w.y()*w.z()) - w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())) - 3*C*v.z()*w.y()*w.z() - 3*C*w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()),\n      w.x()*(-2*A + B*(w.x()*w.x() + w.y()*w.y()) + 3*C*(w.x()*w.x() + w.y()*w.y())),\n      w.y()*(-2*A + B*(w.x()*w.x() + w.y()*w.y()) + 3*C*(w.x()*w.x() + w.y()*w.y())),\n      w.z()*(B + 3*C)*(w.x()*w.x() + w.y()*w.y()),\n      -2*A*v.x() + B*v.x()*(w.x()*w.x() + w.y()*w.y()) + 2*B*w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()) + 3*C*(v.x()*w.x()*w.x() + v.x()*w.y()*w.y() + 2*w.x()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())),\n      -2*A*v.y() + B*v.y()*(w.x()*w.x() + w.y()*w.y()) + 2*B*w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z()) + 3*C*(v.y()*w.x()*w.x() + v.y()*w.y()*w.y() + 2*w.y()*(v.x()*w.x() + v.y()*w.y() + v.z()*w.z())),\n      v.z()*(B + 3*C)*(w.x()*w.x() + w.y()*w.y()) }};\n    // clang-format on\n\n    // parts with dA, dB, dC\n    for (auto i = 0u; i < 3; ++i) {\n      const Scalar dA_dwi = dA_over_th * w(i);\n      const Scalar dB_dwi = dB_over_th * w(i);\n      const Scalar dC_dwi = dC_over_th * w(i);\n      for (auto j = 0u; j < 3; ++j) {\n        dQ.col(3 + i + 6 * j) += dA_dwi * PA.row(j).transpose() + dB_dwi * PB.row(j).transpose()\n                               + dC_dwi * PC.row(j).transpose();\n      }\n    }\n\n    return {Q, dQ};\n  }\n\n  static void dr_exp(TRefIn a_in, TMapRefOut A_out)\n  {\n    SO3Impl<Scalar>::dr_exp(a_in.template tail<3>(), A_out.template topLeftCorner<3, 3>());\n    A_out.template topRightCorner<3, 3>()    = calculate_q(-a_in);\n    A_out.template bottomRightCorner<3, 3>() = A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomLeftCorner<3, 3>().setZero();\n  }\n\n  static void dr_expinv(TRefIn a_in, TMapRefOut A_out)\n  {\n    SO3Impl<Scalar>::dr_expinv(a_in.template tail<3>(), A_out.template topLeftCorner<3, 3>());\n    A_out.template topRightCorner<3, 3>().noalias() = -A_out.template topLeftCorner<3, 3>()\n                                                    * calculate_q(-a_in)\n                                                    * A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomRightCorner<3, 3>() = A_out.template topLeftCorner<3, 3>();\n    A_out.template bottomLeftCorner<3, 3>().setZero();\n  }\n\n  static void d2r_exp(TRefIn a_in, THessRefOut H_out)\n  {\n    H_out.setZero();\n\n    // DERIVATIVES OF SO3 JACOBIAN\n    Eigen::Matrix<Scalar, 3, 9> Hso3;\n    SO3Impl<Scalar>::d2r_exp(a_in.template tail<3>(), Hso3);\n\n    for (auto i = 0u; i < 3; ++i) {\n      H_out.template block<3, 3>(0, 6 * i + 3)      = Hso3.template block<3, 3>(0, 3 * i);\n      H_out.template block<3, 3>(3, 18 + 6 * i + 3) = Hso3.template block<3, 3>(0, 3 * i);\n    }\n\n    // DERIVATIVE OF Q TERM\n    const auto [Q, dQ]                = calculate_Q_dQ(-a_in);\n    H_out.template block<3, 18>(3, 0) = -dQ;\n  }\n\n  static void d2r_expinv(TRefIn a_in, THessRefOut H_out)\n  {\n    H_out.setZero();\n\n    // DERIVATIVES OF SO3 JACOBIAN\n    Eigen::Matrix<Scalar, 3, 9> Hso3;\n    SO3Impl<Scalar>::d2r_expinv(a_in.template tail<3>(), Hso3);\n\n    for (auto i = 0u; i < 3; ++i) {\n      H_out.template block<3, 3>(0, 6 * i + 3)      = Hso3.template block<3, 3>(0, 3 * i);\n      H_out.template block<3, 3>(3, 18 + 6 * i + 3) = Hso3.template block<3, 3>(0, 3 * i);\n    }\n\n    // DERIVATIVE OF -J Q J TERM\n    auto [Q, dQ] = calculate_Q_dQ(-a_in);\n    dQ *= -1;  // account for -a_in\n\n    Eigen::Matrix3<Scalar> Jso3;\n    SO3Impl<Scalar>::dr_expinv(a_in.template tail<3>(), Jso3);\n    // Hso3 contains derivatives w.r.t. w, we extend for derivatives w.r.t. [v, w]\n    Eigen::Matrix<Scalar, 3, 18> Hso3_exp = Eigen::Matrix<Scalar, 3, 18>::Zero();\n    for (auto i = 0u; i < 3; ++i) {\n      Hso3_exp.template middleCols<3>(6 * i + 3) = Hso3.template middleCols<3>(3 * i);\n    }\n\n    const Eigen::Matrix3<Scalar> Jtmp       = Jso3 * Q;\n    const Eigen::Matrix<Scalar, 3, 18> Htmp = d_matrix_product(Jso3, Hso3_exp, Q, dQ);\n    H_out.template block<3, 18>(3, 0)       = -d_matrix_product(Jtmp, Htmp, Jso3, Hso3_exp);\n  }\n};\n\n}  // namespace smooth\n\n#endif  // SMOOTH__INTERNAL__SE3_HPP_\n", "meta": {"hexsha": "ddae25f2407b2652618305eee36c66b11ef979e7", "size": 19928, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/internal/se3.hpp", "max_stars_repo_name": "tgurriet/smooth", "max_stars_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/smooth/internal/se3.hpp", "max_issues_repo_name": "tgurriet/smooth", "max_issues_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/internal/se3.hpp", "max_forks_repo_name": "tgurriet/smooth", "max_forks_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.82, "max_line_length": 225, "alphanum_fraction": 0.4777699719, "num_tokens": 7808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6243797599928309}}
{"text": "#pragma once\n\n/* boost includes */\n#include <boost/math/quaternion.hpp>\n\n/* opencv includes */\n#include <opencv2/core/affine.hpp>\n#include <opencv2/core/core.hpp>\n\n/* pcl headers */\n#include <pcl/point_types.h>\n\n/* sys headers */\n#include <math.h>\n#include <cassert>\n#include <iostream>\n\ntemplate <class T>\nclass DualQuaternion {\nprivate:\n    /* Rotational part */\n    boost::math::quaternion<T> real;\n    /* Translation (displacement) part */\n    boost::math::quaternion<T> dual;\n\n    T dotProduct(boost::math::quaternion<T> q1, boost::math::quaternion<T> q2) {\n        return q1.R_component_1() * q2.R_component_1() + q1.R_component_2() * q2.R_component_2() +\n               q1.R_component_3() * q2.R_component_3() + q1.R_component_4() * q2.R_component_4();\n    }\n\n    boost::math::quaternion<T> normalize(boost::math::quaternion<T> q) { return q / boost::math::norm(q); }\n\n    /* FLOAT_EPSILON */\n    const float epsilon = 1.192092896e-07f;\n\npublic:\n    /* constructor for dual quaternion from rotation unit quaternion and translation quaternion */\n    DualQuaternion(boost::math::quaternion<T> rotation, boost::math::quaternion<T> translation)\n        : real(rotation), dual(translation) {}\n\n    /* constructor for dual quaternion from rotation quaternion and translation vector */\n    DualQuaternion(boost::math::quaternion<T> rotation, cv::Vec3f translation) {\n        real = normalize(rotation);\n        dual = (boost::math::quaternion<T>(0, translation[0], translation[1], translation[2]) * real) * 0.5f;\n    }\n\n    /* constructor for dual quaternion from Euler angles (yaw, pitch, roll) and translation vector */\n    DualQuaternion(T yaw, T pitch, T roll, T x, T y, T z) {\n        T cy = cos(yaw * 0.5);\n        T sy = sin(yaw * 0.5);\n        T cr = cos(roll * 0.5);\n        T sr = sin(roll * 0.5);\n        T cp = cos(pitch * 0.5);\n        T sp = sin(pitch * 0.5);\n\n        T qw = cy * cr * cp + sy * sr * sp;\n        T qx = cy * sr * cp - sy * cr * sp;\n        T qy = cy * cr * sp + sy * sr * cp;\n        T qz = sy * cr * cp - cy * sr * sp;\n\n        boost::math::quaternion<T> rotation(qw, qx, qy, qz);\n\n        DualQuaternion<T> dq(rotation, cv::Vec3f(x, y, z));\n\n        real = dq.getReal();\n        dual = dq.getDual();\n    }\n\n    /* constructor for dual quaternion from Euler-Rodrigues vector and translation vector */\n    DualQuaternion(cv::Vec3f rodrigues, cv::Vec3f translation) {\n        auto theta          = 2 * atan(cv::norm(rodrigues));  // rotation angle\n        auto axis           = rodrigues / theta;\n        auto axisNormalised = axis / cv::norm(axis);  // normalised rotation axis\n\n        auto s  = sin(0.5 * theta);\n        auto q1 = s * axisNormalised(0);\n        auto q2 = s * axisNormalised(1);\n        auto q3 = s * axisNormalised(2);\n        auto q4 = cos(0.5 * theta);\n\n        boost::math::quaternion<float> rotation(q4, q1, q2, q3);  // rotation quaternion\n        DualQuaternion<T> dq(normalize(rotation), translation);\n\n        real = dq.getReal();\n        dual = dq.getDual();\n    }\n\n    boost::math::quaternion<T> getReal() const { return real; }\n\n    boost::math::quaternion<T> getDual() const { return dual; }\n\n    boost::math::quaternion<T> getRotation() const { return real; }\n\n    cv::Vec3f getTranslation() const {\n        boost::math::quaternion<T> q = (dual * 2.0f) * boost::math::conj(real);\n        return cv::Vec3f(q.R_component_2(), q.R_component_3(), q.R_component_4());\n    }\n\n    DualQuaternion<T> operator+(const DualQuaternion<T>& other) {\n        return DualQuaternion<T>(real + other.getReal(), dual + other.getDual());\n    }\n\n    DualQuaternion<T>& operator+=(const DualQuaternion<T>& other) {\n        real += other.getReal();\n        dual += other.getDual();\n        return *this;\n    }\n\n    DualQuaternion<T> operator-(const DualQuaternion<T>& other) {\n        return DualQuaternion<T>(real - other.getReal(), dual - other.getDual());\n    }\n\n    DualQuaternion<T>& operator-=(const DualQuaternion<T>& other) {\n        real -= other.getReal();\n        dual -= other.getDual();\n        return *this;\n    }\n\n    /* TODO: allow 0.5*dq to be used */\n    DualQuaternion<T> operator*(T scale) { return DualQuaternion<T>(real, dual * scale); }\n\n    DualQuaternion<T>& operator*=(T scale) {\n        dual *= scale;\n        return *this;\n    }\n\n    DualQuaternion<T> operator*(const DualQuaternion<T>& other) {\n        return DualQuaternion<T>(real * other.getReal(), real * other.getDual() + dual * other.getReal());\n    }\n\n    DualQuaternion<T>& operator*=(const DualQuaternion<T>& other) {\n        /* Make sure the real is updated after dual to avoid using updated real */\n        dual = real * other.getDual() + dual * other.getReal();\n        real *= other.getReal();\n    }\n\n    DualQuaternion<T> conj() { return DualQuaternion<T>(boost::math::conj(real), boost::math::conj(dual)); }\n\n    DualQuaternion<T>& normalize() {\n        T magnitude = sqrtf(dotProduct(real, real));\n        assert(magnitude > epsilon);\n        real *= (1.0f / magnitude);\n        return *this;\n    }\n\n    ~DualQuaternion() {}\n\n    T getRoll() const {\n        boost::math::quaternion<T> q = real;\n\n        // roll (x-axis rotation)\n        float sinr = +2.0 * (q.R_component_1() * q.R_component_2() + q.R_component_3() * q.R_component_4());\n        float cosr = +1.0 - 2.0 * (q.R_component_2() * q.R_component_2() + q.R_component_3() * q.R_component_3());\n        T roll     = atan2(sinr, cosr);\n\n        if (roll > M_PI) {\n            roll -= M_PI_2;\n        }\n\n        return roll;\n    }\n\n    T getPitch() const {\n        boost::math::quaternion<T> q = real;\n\n        // pitch (y-axis rotation)\n        T pitch;\n        float sinp = +2.0 * (q.R_component_1() * q.R_component_3() - q.R_component_4() * q.R_component_2());\n\n        if (fabs(sinp) >= 1)\n            pitch = copysign(M_PI / 2, sinp);  // use 90 degrees if out of range\n        else {\n            pitch = asin(sinp);\n        }\n\n        return pitch;\n    }\n\n    T getYaw() const {\n        boost::math::quaternion<T> q = real;\n\n        // yaw (z-axis rotation)\n        float siny = +2.0 * (q.R_component_1() * q.R_component_4() + q.R_component_2() * q.R_component_3());\n        float cosy = +1.0 - 2.0 * (q.R_component_3() * q.R_component_3() + q.R_component_4() * q.R_component_4());\n        T yaw      = atan2(siny, cosy);\n\n        if (yaw > M_PI) {\n            yaw -= M_PI_2;\n        }\n\n        return yaw;\n    }\n\n    cv::Vec3f getEulerAngles() const { return cv::Vec3f(getRoll(), getPitch(), getYaw()); }\n\n    cv::Vec3f getRodrigues() {\n        auto q     = cv::Vec3f(real.R_component_2(), real.R_component_3(), real.R_component_4());\n        auto norm  = cv::norm(q);\n        auto theta = 2 * acos(real.R_component_1());\n\n        return tan(0.5 * theta) * q / norm;\n    }\n\n    pcl::PointXYZ transformVertex(pcl::PointXYZ v) {\n        cv::Vec3f vect(v.x, v.y, v.z);\n\n        cv::Vec3f realVect = cv::Vec3f(real.R_component_2(), real.R_component_3(), real.R_component_4());\n        cv::Vec3f dualVect = cv::Vec3f(dual.R_component_2(), dual.R_component_3(), dual.R_component_4());\n\n        cv::Vec3f result =\n            vect + 2.f * realVect.cross(realVect.cross(vect) + real.R_component_1() * vect) +\n            2.f * (real.R_component_1() * dualVect - dual.R_component_1() * realVect + realVect.cross(dualVect));\n\n        return pcl::PointXYZ(result[0], result[1], result[2]);\n    }\n\n    pcl::Normal transformNormal(pcl::Normal n) {\n        cv::Vec3f vect(n.data_c[0], n.data_c[1], n.data_c[2]);\n\n        cv::Vec3f realVect = cv::Vec3f(real.R_component_2(), real.R_component_3(), real.R_component_4());\n        cv::Vec3f dualVect = cv::Vec3f(dual.R_component_2(), dual.R_component_3(), dual.R_component_4());\n\n        cv::Vec3f result =\n            vect + 2.f * realVect.cross(realVect.cross(vect) + real.R_component_1() * vect) +\n            2.f * (real.R_component_1() * dualVect - dual.R_component_1() * realVect + realVect.cross(dualVect));\n\n        return pcl::Normal(result[0], result[1], result[2]);\n    }\n\n    friend std::ostream& operator<<(std::ostream& os, const DualQuaternion<T>& dq) {\n        return os << \"real: \" << dq.getReal() << \"\\ndual: \" << dq.getDual() << std::endl;\n    }\n};\n", "meta": {"hexsha": "f82a3f656ca58e2cc9cd837c27cca93f4d254d1d", "size": 8199, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dynfu/utils/dual_quaternion.hpp", "max_stars_repo_name": "chenguowen/dynfu", "max_stars_repo_head_hexsha": "5991e43144e9b3a95005c820f87900a6b21c7826", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T05:56:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T09:17:05.000Z", "max_issues_repo_path": "include/dynfu/utils/dual_quaternion.hpp", "max_issues_repo_name": "chenguowen/dynfu", "max_issues_repo_head_hexsha": "5991e43144e9b3a95005c820f87900a6b21c7826", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-29T12:29:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-14T15:33:12.000Z", "max_forks_repo_path": "include/dynfu/utils/dual_quaternion.hpp", "max_forks_repo_name": "chenguowen/dynfu", "max_forks_repo_head_hexsha": "5991e43144e9b3a95005c820f87900a6b21c7826", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-08-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T06:43:18.000Z", "avg_line_length": 35.0384615385, "max_line_length": 114, "alphanum_fraction": 0.5903158922, "num_tokens": 2302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.624353451319603}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <cstddef>\n#include <cassert>\n#include <limits>\n#include <Eigen/Sparse>\n\nusing namespace std;\n\nclass Array2D\n{\nprivate:\n\tvector<double> m_data;\n\tsize_t m_Nx, m_Ny;\n\npublic:\n\tArray2D(size_t nx, size_t ny, double val = 0.0) : m_Nx(nx), m_Ny(ny), m_data(nx*ny, val) {}\n\n\t// 0-based indexing\n\tdouble &at(int i, int j)\n\t{\n\t\tint idx = i + m_Nx * j;\n\t\treturn m_data[idx];\n\t}\n\n\tdouble at(int i, int j) const\n\t{\n\t\tint idx = i + m_Nx * j;\n\t\treturn m_data[idx];\n\t}\n\n\t// 1-based indexing\n\tdouble &operator()(int i, int j)\n\t{\n\t\treturn at(i - 1, j - 1);\n\t}\n\n\tdouble operator()(int i, int j) const\n\t{\n\t\treturn at(i - 1, j - 1);\n\t}\n};\n\nconst size_t WIDTH = 16;\nconst size_t DIGITS = 7;\n\nconst double L = 0.5; // m\nconst double D = 0.01; // m\nconst double Ue = 1.0; // m/s\nconst double Pe = 0.0;\nconst double rho = 1.225; // Kg/m3\nconst double mu = 3.737e-5; // Kg/m/s\n\nconst int Nx = 21, Ny = 11;\nconst double dx = L / (Nx - 1), dy = D / (Ny - 1);\nconst double dx2 = 2 * dx, dy2 = 2 * dy;\nconst double dxdx = dx * dx, dydy = dy * dy;\nvector<double> x(Nx, 0.0), y(Ny, 0.0);\n\nconst double dt = 0.001;\ndouble t = 0.0;\nint iter_cnt = 0;\nconst int MAX_ITER_NUM = 2000;\n\nconst double a = 2 * (dt / dxdx + dt / dydy);\nconst double b = -dt / dxdx;\nconst double c = -dt / dydy;\ndouble d_min = numeric_limits<double>::max(), d_max = numeric_limits<double>::min(), d_15_5 = 0.0;\n\nArray2D p(Nx, Ny, Pe), p_star1(Nx, Ny, Pe), p_star2(Nx, Ny, 0.0);\nArray2D u(Nx + 1, Ny, 0.0), u_star1(Nx + 1, Ny, 0.0), u_star2(Nx + 1, Ny, 0.0), u_wedge(Nx + 1, Ny, 0.0);\nArray2D A(Nx + 1, Ny, 0.0), A_star(Nx + 1, Ny, 0.0);\nArray2D v(Nx + 2, Ny + 1, 0.0), v_star1(Nx + 2, Ny + 1, 0.0), v_star2(Nx + 2, Ny + 1, 0.0), v_wedge(Nx + 2, Ny + 1, 0.0);\nArray2D B(Nx + 2, Ny + 1, 0.0), B_star(Nx + 2, Ny + 1, 0.0);\n\n// Full flowfield in TECPLOT ASCII Format.\nvoid output1()\n{\n\tArray2D u_interp(Nx, Ny, 0.0);\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tu_interp(i, 1) = 0.0; // Bottom\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 1; i <= Nx; ++i)\n\t\t\tu_interp(i, j) = (u(i, j) + u(i + 1, j)) / 2; // Inner\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tu_interp(i, Ny) = Ue; // Top\n\n\tArray2D v_interp(Nx, Ny, 0.0);\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tv_interp(i, 1) = 0.0; // Bottom\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t{\n\t\tv_interp(1, j) = 0.0; // Left\n\t\tfor (int i = 3; i <= Nx + 1; ++i)\n\t\t\tv_interp(i - 1, j) = (v(i, j) + v(i, j + 1)) / 2; // Inner and Right\n\t}\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tv_interp(i, Ny) = 0.0; // Top\n\n\t// Create Tecplot data file.\n\tofstream result(\"flow\" + to_string(iter_cnt) + \".dat\");\n\tif (!result)\n\t\tthrow \"Failed to create data file!\";\n\n\t// Header\n\tresult << \"TITLE = \\\"t=\" << t << \"\\\"\" << endl;\n\tresult << \"VARIABLES = \\\"X\\\", \\\"Y\\\", \\\"P\\\", \\\"U\\\", \\\"V\\\"\" << endl;\n\tresult << \"ZONE I=\" << Nx << \", J=\" << Ny << \", F=POINT\" << endl;\n\n\t// Flowfield data\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfor (int i = 1; i <= Nx; ++i)\n\t\t{\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << x[i - 1];\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << y[j - 1];\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << p(i, j);\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << u_interp(i, j);\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << v_interp(i, j);\n\t\t\tresult << endl;\n\t\t}\n\n\t// Finalize\n\tresult.close();\n}\n\n// Statistics at (15, 5) and i=15\nvoid output2(int iter)\n{\n\tstatic const string fn(\"history_at_15_5.txt\");\n\n\tofstream fout;\n\tif (iter == 0)\n\t{\n\t\tfout.open(fn, ios::out);\n\t\tif (!fout)\n\t\t\tthrow \"Failed to open history file.\";\n\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t\tfout << setw(WIDTH) << setprecision(DIGITS) << y[j];\n\t\tfout << endl;\n\t}\n\telse\n\t{\n\t\tfout.open(fn, ios::app);\n\t\tif (!fout)\n\t\t\tthrow \"Failed to open history file.\";\n\t}\n\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfout << setw(WIDTH) << setprecision(DIGITS) << u(15, j);\n\tfout << endl;\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfout << setw(WIDTH) << setprecision(DIGITS) << v(15, j);\n\tfout << endl;\n\tfout << d_15_5 << endl;\n\n\tfout.close();\n}\n\nvoid init()\n{\n\tcout << \"mu=\" << mu << endl;\n\tcout << \"dt=\" << dt << endl;\n\n\t// Init\n\tfor (int i = 1; i < Nx; ++i)\n\t\tx[i] = L * i / (Nx - 1); // X-Coordinates\n\tfor (int j = 1; j < Ny; ++j)\n\t\ty[j] = D * j / (Ny - 1); // Y-Coordinates\n\n\tfor (int i = 1; i <= Nx + 1; ++i)\n\t\tu(i, Ny) = Ue; // U at top\n\tv(15, 5) = 0.5; // Initial peak to ensure 2D flow structure\n}\n\n// Solve the pressure equation.\nvoid ImplicitMethod1()\n{\n\ttypedef Eigen::SparseMatrix<double> SpMat;\n\ttypedef Eigen::Triplet<double> T;\n\n\tconst int m = Nx * Ny;\n\tvector<T> coef;\n\tEigen::VectorXd rhs(m);\n\tSpMat A(m, m);\n\n\t// Calculating coefficients\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tconst int id_w = id - 1;\n\t\t\tconst int id_e = id + 1;\n\t\t\tconst int id_n = id + Nx;\n\t\t\tconst int id_s = id - Nx;\n\n\t\t\tif (i == 0 || i == Nx - 1) // Inlet and Outlet\n\t\t\t{\n\t\t\t\tcoef.emplace_back(id, id, 1.0);\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse if (j == 0) // Bottom\n\t\t\t{\n\t\t\t\tcoef.emplace_back(id, id, 1.0);\n\t\t\t\tcoef.emplace_back(id, id_n, -1.0);\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse if (j == Ny - 1) // Top\n\t\t\t{\n\t\t\t\tcoef.emplace_back(id, id, 1.0);\n\t\t\t\tcoef.emplace_back(id, id_s, -1.0);\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse // Inner\n\t\t\t{\n\t\t\t\t// Use 0-based interface\n\t\t\t\tconst double d = (rho * u_star1.at(i + 1, j) - rho * u_star1.at(i, j)) / dx + (rho * v_star1.at(i + 1, j + 1) - rho * v_star1.at(i + 1, j)) / dy;\n\n\t\t\t\tcoef.emplace_back(id, id, a);\n\t\t\t\tcoef.emplace_back(id, id_w, b);\n\t\t\t\tcoef.emplace_back(id, id_e, b);\n\t\t\t\tcoef.emplace_back(id, id_n, c);\n\t\t\t\tcoef.emplace_back(id, id_s, c);\n\t\t\t\trhs(id) = -d;\n\t\t\t}\n\t\t}\n\n\t// Construct sparse matrix\n\tA.setFromTriplets(coef.begin(), coef.end());\n\n\t// Solve the linear system: Ax = rhs\n\tEigen::SimplicialCholesky<SpMat> chl(A);\n\tEigen::VectorXd x = chl.solve(rhs);\n\n\t// Update p*\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tp_star1.at(i, j) = p.at(i, j) + x(id);\n\t\t}\n}\n\n// Solve the pressure-correction equation\nvoid ImplicitMethod2()\n{\n\ttypedef Eigen::SparseMatrix<double> SpMat;\n\ttypedef Eigen::Triplet<double> T;\n\n\tconst int m = Nx * Ny;\n\tvector<T> coef;\n\tEigen::VectorXd rhs(m);\n\tSpMat A(m, m);\n\n\t// Calculating coefficients\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tconst int id_w = id - 1;\n\t\t\tconst int id_e = id + 1;\n\t\t\tconst int id_n = id + Nx;\n\t\t\tconst int id_s = id - Nx;\n\n\t\t\tif (i == 0 || i == Nx - 1) // Inlet and Outlet\n\t\t\t{\n\t\t\t\tcoef.emplace_back(id, id, 1.0);\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse if (j == 0) // Bottom\n\t\t\t{\n\t\t\t\tcoef.emplace_back(id, id, 1.0);\n\t\t\t\tcoef.emplace_back(id, id_n, -1.0);\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse if (j == Ny - 1) // Top\n\t\t\t{\n\t\t\t\tcoef.emplace_back(id, id, 1.0);\n\t\t\t\tcoef.emplace_back(id, id_s, -1.0);\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse // Inner\n\t\t\t{\n\t\t\t\t// Use 0-based interface\n\t\t\t\tconst double d = (rho*u_wedge.at(i + 1, j) - rho * u_wedge.at(i, j)) / dx + (rho * v_wedge.at(i + 1, j + 1) - rho * v_wedge.at(i + 1, j)) / dy;\n\t\t\t\tif (d > d_max)\n\t\t\t\t\td_max = d;\n\t\t\t\tif (d < d_min)\n\t\t\t\t\td_min = d;\n\t\t\t\tif (i == 15 && j == 5)\n\t\t\t\t\td_15_5 = d;\n\n\t\t\t\tcoef.emplace_back(id, id, a);\n\t\t\t\tcoef.emplace_back(id, id_w, b);\n\t\t\t\tcoef.emplace_back(id, id_e, b);\n\t\t\t\tcoef.emplace_back(id, id_n, c);\n\t\t\t\tcoef.emplace_back(id, id_s, c);\n\t\t\t\trhs(id) = -d;\n\t\t\t}\n\t\t}\n\n\t// Construct sparse matrix\n\tA.setFromTriplets(coef.begin(), coef.end());\n\n\t// Solve the linear system: Ax = rhs\n\tEigen::SimplicialCholesky<SpMat> chl(A);\n\tEigen::VectorXd x = chl.solve(rhs);\n\n\t// Update p_prime\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tp_star2.at(i, j) = p_star1.at(i, j) + x(id);\n\t\t}\n}\n\nvoid PISO()\n{\n\t/********************************************** Prediction Step ***************************************************/\n\t// u* at inner points\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 2; i <= Nx; ++i)\n\t\t{\n\t\t\tconst double v_bar1 = 0.5*(v(i, j + 1) + v(i + 1, j + 1));\n\t\t\tconst double v_bar2 = 0.5*(v(i, j) + v(i + 1, j));\n\n\t\t\tconst double t11 = rho * pow(u(i + 1, j), 2) - rho * pow(u(i - 1, j), 2);\n\t\t\tconst double t12 = rho * u(i, j + 1)*v_bar1 - rho * u(i, j - 1)*v_bar2;\n\t\t\tconst double t21 = u(i + 1, j) - 2 * u(i, j) + u(i - 1, j);\n\t\t\tconst double t22 = u(i, j + 1) - 2 * u(i, j) + u(i, j - 1);\n\t\t\tA(i, j) = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tconst double dpdx = (p(i, j) - p(i - 1, j)) / dx;\n\n\t\t\tu_star1(i, j) = (rho * u(i, j) + A(i, j) * dt - dt * dpdx) / rho;\n\t\t}\n\n\t// u* at boundary\n\tfor (int i = 1; i <= Nx + 1; ++i)\n\t{\n\t\tu_star1(i, 1) = 0.0;\n\t\tu_star1(i, Ny) = Ue;\n\t}\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t{\n\t\tu_star1(1, j) = 2 * u_star1(2, j) - u_star1(3, j);\n\t\tu_star1(Nx + 1, j) = 2 * u_star1(Nx, j) - u_star1(Nx - 1, j);\n\t}\n\n\t// v* at inner points\n\tfor (int i = 3; i <= Nx + 1; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tconst double u_bar1 = 0.5 *(u(i, j - 1) + u(i, j));\n\t\t\tconst double u_bar2 = 0.5 *(u(i - 1, j - 1) + u(i - 1, j));\n\n\t\t\tconst double t11 = rho * v(i + 1, j) * u_bar1 - rho * v(i - 1, j) * u_bar2;\n\t\t\tconst double t12 = rho * pow(v(i, j + 1), 2) - rho * pow(v(i, j - 1), 2);\n\t\t\tconst double t21 = v(i + 1, j) - 2 * v(i, j) + v(i - 1, j);\n\t\t\tconst double t22 = v(i, j + 1) - 2 * v(i, j) + v(i, j - 1);\n\t\t\tB(i, j) = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tconst double dpdy = (p(i - 1, j) - p(i - 1, j - 1)) / dy;\n\n\t\t\tv_star1(i, j) = (rho * v(i, j) + B(i, j) * dt - dt * dpdy) / rho;\n\t\t}\n\n\t// v* at boundary\n\tfor (int j = 2; j <= Ny; ++j)\n\t{\n\t\tv_star1(2, j) = 0.0;\n\t\tv_star1(1, j) = -v_star1(3, j);\n\t\tv_star1(Nx + 2, j) = 2 * v_star1(Nx + 1, j) - v_star1(Nx, j);\n\t}\n\tfor (int i = 1; i <= Nx + 2; ++i)\n\t{\n\t\tv_star1(i, 1) = -v_star1(i, 2);\n\t\tv_star1(i, Ny + 1) = -v_star1(i, Ny);\n\t}\n\n\t/************************************************ Correction Step1 ************************************************/\n\t// Solve (p* - p)\n\tImplicitMethod1();\n\n\t// u** at inner points\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 2; i <= Nx; ++i)\n\t\t{\n\t\t\tconst double dpdx = (p_star1(i, j) - p_star1(i - 1, j)) / dx;\n\t\t\tu_star2(i, j) = (rho * u(i, j) + A(i, j) * dt - dt * dpdx) / rho;\n\t\t}\n\n\t// u** at boundary\n\tfor (int i = 1; i <= Nx + 1; ++i)\n\t{\n\t\tu_star2(i, 1) = 0.0;\n\t\tu_star2(i, Ny) = Ue;\n\t}\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t{\n\t\tu_star2(1, j) = 2 * u_star2(2, j) - u_star2(3, j);\n\t\tu_star2(Nx + 1, j) = 2 * u_star2(Nx, j) - u_star2(Nx - 1, j);\n\t}\n\n\t// v** at inner points\n\tfor (int i = 3; i <= Nx + 1; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tconst double dpdy = (p_star1(i - 1, j) - p_star1(i - 1, j - 1)) / dy;\n\t\t\tv_star2(i, j) = (rho * v(i, j) + B(i, j) * dt - dt * dpdy) / rho;\n\t\t}\n\n\t// v** at boundary\n\tfor (int j = 2; j <= Ny; ++j)\n\t{\n\t\tv_star2(2, j) = 0.0;\n\t\tv_star2(1, j) = -v_star2(3, j);\n\t\tv_star2(Nx + 2, j) = 2 * v_star2(Nx + 1, j) - v_star2(Nx, j);\n\t}\n\tfor (int i = 1; i <= Nx + 2; ++i)\n\t{\n\t\tv_star2(i, 1) = -v_star2(i, 2);\n\t\tv_star2(i, Ny + 1) = -v_star2(i, Ny);\n\t}\n\n\t/************************************************ Correction Step2 ************************************************/\n\t// u**^ at inner points\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 2; i <= Nx; ++i)\n\t\t{\n\t\t\tconst double v_bar1 = 0.5*(v_star1(i, j + 1) + v_star1(i + 1, j + 1));\n\t\t\tconst double v_bar2 = 0.5*(v_star1(i, j) + v_star1(i + 1, j));\n\n\t\t\tconst double t11 = rho * pow(u_star1(i + 1, j), 2) - rho * pow(u_star1(i - 1, j), 2);\n\t\t\tconst double t12 = rho * u_star1(i, j + 1)*v_bar1 - rho * u_star1(i, j - 1)*v_bar2;\n\t\t\tconst double t21 = u_star1(i + 1, j) - 2 * u_star1(i, j) + u_star1(i - 1, j);\n\t\t\tconst double t22 = u_star1(i, j + 1) - 2 * u_star1(i, j) + u_star1(i, j - 1);\n\t\t\tA_star(i, j) = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tu_wedge(i, j) = (rho * u_star2(i, j) + (A_star(i, j) - A(i, j)) * dt) / rho;\n\t\t}\n\n\t// v**^ at inner points\n\tfor (int i = 3; i <= Nx + 1; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tconst double u_bar1 = 0.5 *(u_star1(i, j - 1) + u_star1(i, j));\n\t\t\tconst double u_bar2 = 0.5 *(u_star1(i - 1, j - 1) + u_star1(i - 1, j));\n\n\t\t\tconst double t11 = rho * v_star1(i + 1, j) * u_bar1 - rho * v_star1(i - 1, j) * u_bar2;\n\t\t\tconst double t12 = rho * pow(v_star1(i, j + 1), 2) - rho * pow(v_star1(i, j - 1), 2);\n\t\t\tconst double t21 = v_star1(i + 1, j) - 2 * v_star1(i, j) + v_star1(i - 1, j);\n\t\t\tconst double t22 = v_star1(i, j + 1) - 2 * v_star1(i, j) + v_star1(i, j - 1);\n\t\t\tB_star(i, j) = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tv_wedge(i, j) = (rho * v_star2(i, j) + (B_star(i, j) - B(i, j)) * dt) / rho;\n\t\t}\n\n\td_min = numeric_limits<double>::max();\n\td_max = numeric_limits<double>::min();\n\tImplicitMethod2();\n\n\t/************************************************* Update u and v *************************************************/\n\t// Correct u at inner nodes\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 2; i <= Nx; ++i)\n\t\t{\n\t\t\tconst double dpdx = (p_star2(i, j) - p_star2(i - 1, j)) / dx;\n\t\t\tu(i, j) = (rho * u_wedge(i, j) - dt * dpdx) / rho;\n\t\t}\n\n\t// Linear extrapolation of u at virtual nodes\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t{\n\t\tu(1, j) = 2 * u(2, j) - u(3, j);\n\t\tu(Nx + 1, j) = 2 * u(Nx, j) - u(Nx - 1, j);\n\t}\n\n\t// Correct v at inner nodes\n\tfor (int i = 3; i <= Nx + 1; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tconst double dpdy = (p_star2(i - 1, j) - p_star2(i - 1, j - 1)) / dy;\n\t\t\tv(i, j) = (rho * v_wedge(i, j) - dt * dpdy) / rho;\n\t\t}\n\n\t// Linear extrapolation of v at right virtual nodes\n\tfor (int j = 2; j <= Ny; ++j)\n\t\tv(Nx + 2, j) = 2 * v(Nx + 1, j) - v(Nx, j);\n\n\t// Linear extrapolation of v at both top and bottom virtual nodes\n\t// No-Penetration at both top and bottom\n\tfor (int i = 1; i <= Nx + 2; ++i)\n\t{\n\t\tv(i, 1) = -v(i, 2);\n\t\tv(i, Ny + 1) = -v(i, Ny);\n\t}\n\n\t// Update p\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfor (int i = 1; i <= Nx; ++i)\n\t\t\tp(i, j) = p_star2(i, j);\n}\n\nbool check_convergence()\n{\n\t// Statistics of the mass flux residue\n\tcout << \"Max(d)=\" << d_max << \" Min(d)=\" << d_min << endl;\n\n\t// Statistics of u\n\tdouble u_max = numeric_limits<double>::min();\n\tdouble u_min = numeric_limits<double>::max();\n\tfor (int i = 2; i <= Nx; ++i)\n\t\tfor (int j = 1; j <= Ny; ++j)\n\t\t{\n\t\t\tu_max = max(u_max, u(i, j));\n\t\t\tu_min = min(u_min, u(i, j));\n\t\t}\n\tcout << \"Max(u)=\" << u_max << \" Min(u)=\" << u_min << endl;\n\n\t// Statistics of v\n\tdouble v_max = numeric_limits<double>::min();\n\tdouble v_min = numeric_limits<double>::max();\n\tfor (int i = 2; i <= Nx + 1; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tv_max = max(v_max, v(i, j));\n\t\t\tv_min = min(v_min, v(i, j));\n\t\t}\n\tcout << \"Max(v)=\" << v_max << \" Min(v)=\" << v_min << endl;\n\n\t// Statistics of p\n\tdouble p_max = numeric_limits<double>::min();\n\tdouble p_min = numeric_limits<double>::max();\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tfor (int j = 1; j <= Ny; ++j)\n\t\t{\n\t\t\tp_max = max(p_max, p(i, j));\n\t\t\tp_min = min(p_min, p(i, j));\n\t\t}\n\tcout << \"Max(p)=\" << p_max << \" Min(p)=\" << p_min << endl;\n\n\treturn iter_cnt > MAX_ITER_NUM || max(abs(d_max), abs(d_min)) < 1e-4;\n}\n\nvoid loop()\n{\n\tbool converged = false;\n\twhile (!converged)\n\t{\n\t\t++iter_cnt;\n\t\tcout << \"Iter\" << iter_cnt << \":\" << endl;\n\n\t\tPISO();\n\t\tt += dt;\n\n\t\toutput1();\n\t\toutput2(iter_cnt);\n\n\t\tconverged = check_convergence();\n\t}\n}\n\nint main(int argc, char *argv[])\n{\n\t// Initialize\n\tinit();\n\n\t// Output I.C.\n\toutput1();\n\toutput2(0);\n\n\t// Solve\n\tloop();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "bfe5d0873d69ea95b95393758a3f4e7265e62dc4", "size": 15422, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Couette/2D/PISO/main.cc", "max_stars_repo_name": "cangyu/CFD-book-of-Anderson", "max_stars_repo_head_hexsha": "cd8bd49b5e169c360d789054abe58c7139a3a9e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-07-22T14:20:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T10:36:38.000Z", "max_issues_repo_path": "Couette/2D/PISO/main.cc", "max_issues_repo_name": "cangyu/CFD-book-of-Anderson", "max_issues_repo_head_hexsha": "cd8bd49b5e169c360d789054abe58c7139a3a9e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Couette/2D/PISO/main.cc", "max_forks_repo_name": "cangyu/CFD-book-of-Anderson", "max_forks_repo_head_hexsha": "cd8bd49b5e169c360d789054abe58c7139a3a9e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-04T06:54:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T06:54:56.000Z", "avg_line_length": 26.4075342466, "max_line_length": 149, "alphanum_fraction": 0.5084943587, "num_tokens": 6310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6243340645189289}}
{"text": "#include \"laplacian_deformation.hpp\"\n\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n\n#include <math.h>\n\n#include <set>\n\nclass vec3 {\npublic:\n\tdouble x, y, z;\n\n\tvec3(double x, double y, double z) { this->x = x; this->y = y; this->z = z; }\n\n\tvec3(double v) { this->x = v; this->y = v; this->z = v; }\n\n\tvec3() { this->x = this->y = this->z = 0; }\n\n\tvec3& operator+=(const vec3& b) { (*this) = (*this) + b; return (*this); }\n\tvec3& operator-=(const vec3& b) { (*this) = (*this) - b; return (*this); }\n\n\tfriend vec3 operator-(const vec3& a, const vec3& b) { return vec3(a.x - b.x, a.y - b.y, a.z - b.z); }\n\tfriend vec3 operator+(const vec3& a, const vec3& b) { return vec3(a.x + b.x, a.y + b.y, a.z + b.z); }\n\tfriend vec3 operator*(const double s, const vec3& a) { return vec3(s * a.x, s * a.y, s * a.z); }\n\tfriend vec3 operator*(const vec3& a, const double s) { return s * a; }\n};\n\n\ntypedef Eigen::SparseMatrix<double> SpMat; \n\ntypedef Eigen::MatrixXd DMat; \n\ntypedef Eigen::Triplet<double> Triplet;\n\ntypedef Eigen::VectorXd Vec;\n\nstruct Sorter {\n\tbool operator()(const Triplet& a, const Triplet& b) {\n\t\tif (a.row() != b.row()) {\n\t\t\treturn a.row() < b.row();\n\t\t}\n\t\telse {\n\t\t\treturn a.col() < b.col();\n\t\t}\n\t}\n} sorter;\n\n\nstruct Entry {\n\tint a0;\n\tint a1;\n\tdouble a2;\n\n\tEntry(int a0_, int a1_, double a2_) : a0(a0_), a1(a1_), a2(a2_) {\n\t}\n};\n\nstruct SorterEntry {\n\tbool operator()(const Entry& a, const Entry& b) {\n\t\tif (a.a0 != b.a0) {\n\t\t\treturn a.a0 < b.a0;\n\t\t}\n\t\telse {\n\t\t\treturn a.a1 < b.a1;\n\t\t}\n\t}\n} sorterEntry;\n\nstd::vector<Triplet> calcEnergyMatrixCoeffs(\n\tconst Vec& roiPositions,\n\tconst Vec& delta,\n\tconst int nRoi,\n\n\tstd::vector<std::vector<int> > adj,\n\n\tconst std::vector<int>& rowBegins,\n\tconst std::vector<Triplet>& laplacianCoeffs\n) {\n\tstd::vector<DMat> Ts;\n\n\tTs.resize(nRoi);\n\n\tfor (int i = 0; i < nRoi; ++i) {\n\t\t// set of {i} and the neigbbours of i.\n\t\tstd::vector<int> iAndNeighbours;\n\n\t\tiAndNeighbours.push_back(i);\n\t\tfor (int j = 0; j < adj[i].size(); ++j) {\n\t\t\tiAndNeighbours.push_back(adj[i][j]);\n\t\t}\n\n\t\tDMat At(7, iAndNeighbours.size() * 3);\n\t\tfor (int row = 0; row < 7; ++row) {\n\t\t\tfor (int col = 0; col < iAndNeighbours.size() * 3; ++col) {\n\t\t\t\tAt(row, col) = 0.0f;\n\t\t\t}\n\t\t}\n\n\t\tfor (int j = 0; j < iAndNeighbours.size(); ++j) {\n\t\t\tint k = iAndNeighbours[j];\n\n\t\t\tdouble vk[3];\n\t\t\tvk[0] = roiPositions[3 * k + 0];\n\t\t\tvk[1] = roiPositions[3 * k + 1];\n\t\t\tvk[2] = roiPositions[3 * k + 2];\n\n\t\t\tconst int x = 0;\n\t\t\tconst int y = 1;\n\t\t\tconst int z = 2;\n\n\t\t\tAt(0, j * 3 + 0) = +vk[x];\n\t\t\tAt(1, j * 3 + 0) = 0;\n\t\t\tAt(2, j * 3 + 0) = +vk[z];\n\t\t\tAt(3, j * 3 + 0) = -vk[y];\n\t\t\tAt(4, j * 3 + 0) = +1;\n\t\t\tAt(5, j * 3 + 0) = 0;\n\t\t\tAt(6, j * 3 + 0) = 0;\n\n\t\t\tAt(0, j * 3 + 1) = +vk[y];\n\t\t\tAt(1, j * 3 + 1) = -vk[z];\n\t\t\tAt(2, j * 3 + 1) = 0;\n\t\t\tAt(3, j * 3 + 1) = +vk[x];\n\t\t\tAt(4, j * 3 + 1) = 0;\n\t\t\tAt(5, j * 3 + 1) = +1;\n\t\t\tAt(6, j * 3 + 1) = 0;\n\n\t\t\tAt(0, j * 3 + 2) = +vk[z];\n\t\t\tAt(1, j * 3 + 2) = +vk[y];\n\t\t\tAt(2, j * 3 + 2) = -vk[x];\n\t\t\tAt(3, j * 3 + 2) = 0;\n\t\t\tAt(4, j * 3 + 2) = 0;\n\t\t\tAt(5, j * 3 + 2) = 0;\n\t\t\tAt(6, j * 3 + 2) = 1;\n\t\t}\n\n\t\tDMat invprod = (At * At.transpose()).inverse();\n\t\tDMat pseudoinv = invprod * At;\n\t\tTs[i] = pseudoinv;\n\t\t// Ts[i] now contains (A^T A ) A^T (see equation 12 from paper.)\n\t}\n\n\tstd::vector<Triplet> result;\n\n\tstd::map<int, double> row;\n\n\tfor (int i = 0; i < (nRoi * 3); ++i) {\n\t\trow.clear();\n\t\t\n\t\t// add uniform weights to matrix(equation 2 from paper)\n\t\tfor (int ientry = rowBegins[i]; ientry < rowBegins[i + 1]; ++ientry) {\n\t\t\tTriplet t = laplacianCoeffs[ientry];\n\t\t\trow[t.col()] = t.value();\n\t\t}\n\t\n\t\t// get delta coordinates for the vertex.\n\t\tdouble dx = delta[int(i / 3) * 3 + 0];\n\t\tdouble dy = delta[int(i / 3) * 3 + 1];\n\t\tdouble dz = delta[int(i / 3) * 3 + 2];\n\n\t\tstd::vector<int> iAndNeighbours;\n\t\tiAndNeighbours.push_back(int(i / 3));\n\t\tfor (int j = 0; j < adj[int(i / 3)].size(); ++j) {\n\t\t\tiAndNeighbours.push_back(adj[int(i / 3)][j]);\n\t\t}\n\n\t\tDMat T = Ts[int(i / 3)];\n\n\t\tVec s = T.row(0);\n\t\tVec h1 = T.row(1);\n\t\tVec h2 = T.row(2);\n\t\tVec h3 = T.row(3);\n\t\tVec tx = T.row(4);\n\t\tVec ty = T.row(5);\n\t\tVec tz = T.row(6);\n\n\t\tif ((i % 3) == 0) { // x case.\n\t\t\tfor (int j = 0; j < T.row(0).size(); ++j) {\n\t\t\t\tint p = j % 3;\n\t\t\t\tint q = (int)floor((double)j / (double)3);\n\t\t\t\tint r = iAndNeighbours[q];\n\n\t\t\t\trow[p + 3 * r] -= dx * (+s[j]);\n\t\t\t\trow[p + 3 * r] -= dy * (-h3[j]);\n\t\t\t\trow[p + 3 * r] -= dz * (+h2[j]);\n\t\t\t}\n\t\t}\n\t\telse if ((i % 3) == 1) { // y case.\n\t\t\tfor (int j = 0; j < T.row(0).size(); ++j) {\n\t\t\t\tint p = j % 3;\n\t\t\t\tint q = (int)floor((double)j / (double)3);\n\t\t\t\tint r = iAndNeighbours[q];\n\n\t\t\t\trow[p + 3 * r] -= dx * (+h3[j]);\n\t\t\t\trow[p + 3 * r] -= dy * (+s[j]);\n\t\t\t\trow[p + 3 * r] -= dz * (-h1[j]);\n\t\t\t}\n\t\t}\n\t\telse if ((i % 3) == 2) { // z case.\n\t\t\tfor (int j = 0; j < T.row(0).size(); ++j) {\n\t\t\t\tint p = j % 3;\n\t\t\t\tint q = (int)floor((double)j / (double)3);\n\t\t\t\tint r = iAndNeighbours[q];\n\n\t\t\t\trow[p + 3 * r] -= dx * (-h2[j]);\n\t\t\t\trow[p + 3 * r] -= dy * (+h1[j]);\n\t\t\t\trow[p + 3 * r] -= dz * (+s[j]);\n\n\t\t\t}\n\t\t}\n\n\t\tfor (const auto& p : row) {\n\t\t\tresult.push_back(Triplet(i, p.first, p.second));\n\t\t}\n\t}\n\n\treturn result;\n}\n\ndouble hypot(double x, double y, double z) {\n\treturn sqrt(\n\t\tx * x +\n\t\ty * y +\n\t\tz * z);\n}\n\n// cotangent discretization of the laplacian.\nstd::vector<Triplet> calcCotangentLaplacianCoeffs(\n\n\tint* cells, const int nCells,\n\n\tconst std::vector<int>& roiMap,\n\n\tint nRoi,\n\tstd::vector<std::vector<int> > adj,\n\n\tstd::vector<int>& rowBegins,\n\n\tconst Vec& roiPositions\n) {\n\tstd::vector<Triplet> result;\n\n\tstd::vector<int> cells_flattened;\n\n\tfor (int i = 0; i < nCells; i += 3) {\n\t\tint c[3] = { roiMap[cells[i + 0]], roiMap[cells[i + 1]] , roiMap[cells[i + 2]] };\n\n\t\tif (c[0] == -1 || c[1] == -1 || c[2] == -1) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tcells_flattened.push_back(c[0]);\n\t\tcells_flattened.push_back(c[1]);\n\t\tcells_flattened.push_back(c[2]);\n\t}\n\n\tstd::map<std::pair<int, int>, double> laplacian;\n\n\n\tstd::vector<double> areas;\n\tfor (int i = 0; i < nRoi; ++i) {\n\t\tareas.push_back(0);\n\t}\n\n\tstd::vector<Entry> entries;\n\tfor (int i = 0; i < cells_flattened.size(); i += 3) {\n\t\tint ia = cells_flattened[i + 0];\n\t\tint ib = cells_flattened[i + 1];\n\t\tint ic = cells_flattened[i + 2];\n\n\t\tvec3 a = vec3(roiPositions[3 * ia + 0], roiPositions[3 * ia + 1], roiPositions[3 * ia + 2]);\n\t\tvec3 b = vec3(roiPositions[3 * ib + 0], roiPositions[3 * ib + 1], roiPositions[3 * ib + 2]);\n\t\tvec3 c = vec3(roiPositions[3 * ic + 0], roiPositions[3 * ic + 1], roiPositions[3 * ic + 2]);\n\n\t\tdouble abx = a.x - b.x;\n\t\tdouble aby = a.y - b.y;\n\t\tdouble abz = a.z - b.z;\n\n\t\tdouble bcx = b.x - c.x;\n\t\tdouble bcy = b.y - c.y;\n\t\tdouble bcz = b.z - c.z;\n\n\t\tdouble cax = c.x - a.x;\n\t\tdouble cay = c.y - a.y;\n\t\tdouble caz = c.z - a.z;\n\n\t\tdouble area = 0.5 * hypot(\n\t\t\taby * caz - abz * cay,\n\t\t\tabz * cax - abx * caz,\n\t\t\tabx * cay - aby * cax);\n\n\t\t//Skip thin triangles\n\t\tif (area < 1e-8) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tdouble w = -0.5 / area;\n\t\tdouble wa = w * (abx * cax + aby * cay + abz * caz);\n\t\tdouble wb = w * (bcx * abx + bcy * aby + bcz * abz);\n\t\tdouble wc = w * (cax * bcx + cay * bcy + caz * bcz);\n\n\t\tdouble varea = area / 3.0;\n\t\tareas[ia] += varea;\n\t\tareas[ib] += varea;\n\t\tareas[ic] += varea;\n\n\t\tentries.push_back(Entry(ib, ic, wa));\n\t\tentries.push_back(Entry(ic, ib, wa));\n\t\tentries.push_back(Entry(ic, ia, wb));\n\t\tentries.push_back(Entry(ia, ic, wb));\n\t\tentries.push_back(Entry(ia, ib, wc));\n\t\tentries.push_back(Entry(ib, ia, wc));\n\t}\n\n\tstd::vector<double> weights;\n\tfor (int i = 0; i < nRoi; ++i) {\n\t\tweights.push_back(0.0);\n\t}\n\n\tstd::sort(entries.begin(), entries.end(), sorterEntry);\n\n\tint ptr = 0;\n\n\tfor (int i = 0; i < entries.size(); ) {\n\n\t\tEntry entry = entries[i++];\n\n\t\twhile (\n\t\t\ti < entries.size() &&\n\t\t\tentries[i].a0 == entry.a0 &&\n\t\t\tentries[i].a1 == entry.a1) {\n\t\t\tentry.a2 += entries[i++].a2;\n\n\t\t}\n\n\t\tentry.a2 /= areas[entry.a0];\n\t\tweights[entry.a0] += entry.a2;\n\t\tentries[ptr++] = entry;\n\t}\n\n\tfor (int i = 0; i < ptr; ++i) {\n\t\tstd::pair<int, int> e(entries[i].a0, entries[i].a1);\n\t\tTriplet t(e.first, e.second, entries[i].a2);\n\t\tresult.push_back(t);\n\t}\n\n\tfor (int i = 0; i < nRoi; ++i) {\n\t\tTriplet t(i, i, -weights[i]);\n\t\tresult.push_back(t);\n\t}\n\tstd::sort(result.begin(), result.end(), sorter);\n\n\t{\n\t\tstd::vector<Triplet> result2;\n\n\t\tfor (int i = 0; i < result.size(); ++i) {\n\n\t\t\tTriplet a = result[i];\n\n\t\t\tresult2.push_back(Triplet(3 * a.row() + 0, 3 * a.col() + 0, a.value()));\n\n\t\t\tresult2.push_back(Triplet(3 * a.row() + 1, 3 * a.col() + 1, a.value()));\n\n\t\t\tresult2.push_back(Triplet(3 * a.row() + 2, 3 * a.col() + 2, a.value()));\n\n\t\t}\n\n\t\tresult = result2;\n\n\t\tstd::sort(result.begin(), result.end(), sorter);\n\t}\n\n\tint current = result[0].row();\n\trowBegins.push_back(0);\n\tfor (int i = 0; i < result.size(); ++i) {\n\n\t\tif (result[i].row() != current) {\n\t\t\trowBegins.push_back(i);\n\t\t\tcurrent = result[i].row();\n\t\t}\n\t}\n\trowBegins.push_back(result.size());\n\n\treturn result;\n}\n\nstd::vector<Triplet> calcUniformLaplacianCoeffs(\n\tint nRoi,\n\tstd::vector<std::vector<int> > adj,\n\n\tstd::vector<int>& rowBegins\n) {\n\tstd::vector<Triplet> result;\n\tstd::map<int, double> row;\n\n\tfor (int i = 0; i < (nRoi * 3); ++i) {\n\t\trowBegins.push_back(result.size());\n\t\trow.clear();\n\n\t\trow[(i % 3) + int(i / 3) * 3] = 1;\n\t\tdouble w = -1.0 / adj[int(i / 3)].size();\n\t\tfor (int j = 0; j < adj[int(i / 3)].size(); ++j) {\n\t\t\trow[(i % 3) + 3 * adj[int(i / 3)][j]] = w;\n\t\t}\n\n\t\tfor (const auto& p : row) {\n\t\t\tresult.push_back(Triplet(i, p.first, p.second));\n\t\t}\n\t}\n\trowBegins.push_back(result.size());\n\n\treturn result;\n}\n\nstruct State {\n\tbool RSI;\n\n\tVec roiDelta;\n\n\tSpMat augEnergyMatrixTrans;\n\tSpMat augNormalizeDeltaCoordinatesTrans;\n\n\tEigen::SimplicialCholesky<SpMat>*energyMatrixCholesky = nullptr;\n\tEigen::SimplicialCholesky<SpMat>*normalizeDeltaCoordinatesCholesky = nullptr;\n\n\tint* roiIndices;\n\tint nRoi;\n\n\tSpMat lapMat;\n\n\tstd::vector<double> roiDeltaLengths;\n\n\tVec b;\n};\n\nState s;\n\ndouble getLength(double ax, double ay, double az) {\n\treturn sqrt(ax*ax + ay * ay + az * az);\n}\n\nvoid freeDeform() {\n\tif (s.energyMatrixCholesky != nullptr) {\n\t\tdelete s.energyMatrixCholesky;\n\t\ts.energyMatrixCholesky = nullptr;\n\t}\n\tif (s.normalizeDeltaCoordinatesCholesky != nullptr) {\n\t\tdelete s.normalizeDeltaCoordinatesCholesky;\n\t\ts.normalizeDeltaCoordinatesCholesky = nullptr;\n\t}\n}\n\n/*\nFor reference, the equation numbers refer to the paper:\nhttps://people.eecs.berkeley.edu/~jrs/meshpapers/SCOLARS.pdf\n*/\nvoid prepareDeform(\n\tint* cells, const int nCells,\n\n\tdouble* positions, const int nPositions,\n\n\tint* roiIndices, const int nRoi,\n\n\tconst int unconstrainedBegin,\n\n\tbool RSI) {\n\n\t// free memory from previous call of prepareDeform()\n\tif (s.energyMatrixCholesky != nullptr) {\n\t\tdelete s.energyMatrixCholesky;\n\t\ts.energyMatrixCholesky = nullptr;\n\t}\n\tif (s.normalizeDeltaCoordinatesCholesky != nullptr) {\n\t\tdelete s.normalizeDeltaCoordinatesCholesky;\n\t\ts.normalizeDeltaCoordinatesCholesky = nullptr;\n\t}\n\n\tstd::vector<std::vector<int> > adj;\n\tstd::vector<int> roiMap(nPositions, -1);\n\n\t{\n\t\tfor (int i = 0; i < nRoi; ++i) {\n\t\t\troiMap[roiIndices[i]] = i;\n\t\t}\n\n\t\tadj.resize(nRoi);\n\t\tfor (int i = 0; i < adj.size(); ++i) {\n\t\t\tadj[i] = std::vector<int>();\n\t\t}\n\t\tfor (int i = 0; i < nCells; i += 3) {\n\t\t\tint c[3] = { cells[i + 0], cells[i + 1] , cells[i + 2] };\n\n\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\tint a = roiMap[c[j]];\n\n\t\t\t\tint b = roiMap[c[(j + 1) % 3]];\n\n\t\t\t\tif (a != -1 && b != -1) {\n\t\t\t\t\tadj[a].push_back(b);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// put all the positions of the vertices in ROI in a single vector.\n\tVec roiPositions(nRoi * 3);\n\t{\n\t\tint c = 0;\n\t\tfor (int i = 0; i < nRoi; ++i) {\n\t\t\tfor (int d = 0; d < 3; ++d) {\n\t\t\t\troiPositions[c++] = positions[3 * roiIndices[i] + d];\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::vector<int> rowBegins;\n\tstd::vector<Triplet> laplacianCoeffs;\n\t\n\t/*\n\t// cotangent laplacian doesnt yield any good results, for some reason :/\n\tso we don't use it. instead, use uniform.\n\tlaplacianCoeffs = calcCotangentLaplacianCoeffs(\n\t\t\n\t\tcells, nCells, \n\t\troiMap,\n\n\t\tnRoi,\n\t\tadj,\n\t\trowBegins,\n\t\n\t\troiPositions);\n\t\t*/\t\n\t  \n\tlaplacianCoeffs = calcUniformLaplacianCoeffs(nRoi, adj, rowBegins);\n\n\ts.lapMat = SpMat(nRoi * 3, nRoi * 3);\n\ts.lapMat.setFromTriplets(laplacianCoeffs.begin(), laplacianCoeffs.end());\n\n\t// by simply multiplying by the laplacian matrix, we can compute the laplacian coordinates(the delta coordinates)\n\t// of the vertices in ROI.\n\ts.roiDelta = s.lapMat * roiPositions;\n\n\t// we save away the original lengths of the delta coordinates.\n\t// we need these when normalizing the results of our solver.\n\t{\n\t\ts.roiDeltaLengths = std::vector<double>(s.roiDelta.size() / 3, 0.0f);\n\t\tfor (int i = 0; i < s.roiDelta.size() / 3; ++i) {\n\t\t\ts.roiDeltaLengths[i] = getLength(\n\t\t\t\ts.roiDelta[3 * i + 0],\n\t\t\t\ts.roiDelta[3 * i + 1],\n\t\t\t\ts.roiDelta[3 * i + 2]\n\t\t\t);\n\t\t}\n\t}\n\n\tstd::vector<Triplet> energyMatrixCoeffs;\n\n\t// num rows in augmented matrix. \n\t// notice that we put x, y, and z in a large single matrix, and therefore it is multiplied by 3.\n\tint M = (nRoi + unconstrainedBegin) * 3;\n\t// num columns in augmented matrix.\n\tint N = nRoi * 3;\n\n\tif (RSI) {\n\t\t// this matrix represents the first term of the energy (5).\n\t\tenergyMatrixCoeffs = calcEnergyMatrixCoeffs(\n\t\t\troiPositions,\n\t\t\ts.roiDelta, nRoi, adj, rowBegins, laplacianCoeffs);\n\n\t\tfor (int i = 0; i < unconstrainedBegin; ++i) {\n\t\t\tlaplacianCoeffs.push_back(Triplet(i * 3 + N + 0, 3 * i + 0, 1));\n\t\t\tlaplacianCoeffs.push_back(Triplet(i * 3 + N + 1, 3 * i + 1, 1));\n\t\t\tlaplacianCoeffs.push_back(Triplet(i * 3 + N + 2, 3 * i + 2, 1));\n\t\t}\n\n\t\tSpMat augMat(M, N);\n\t\taugMat.setFromTriplets(laplacianCoeffs.begin(), laplacianCoeffs.end());\n\t\ts.augNormalizeDeltaCoordinatesTrans = augMat.transpose();\n\n\t\ts.normalizeDeltaCoordinatesCholesky = new Eigen::SimplicialCholesky<SpMat>(s.augNormalizeDeltaCoordinatesTrans * augMat);\n\t}\n\telse {\n\t\t// if not rotation-scale-invariant, we simply use the regular laplacian matrix. This is the first term of the energy (4)\n\t\tenergyMatrixCoeffs = laplacianCoeffs;\n\t}\n\n\t// in order to add the second term of the energy (4) or (5), we now augment the matrix.\n\t{\n\t\t// we augment the matrix by adding constraints for the handles.\n\t\t// these constraints ensure that if the handles are dragged, the handles will strictly follow in the specified direction.\n\t\t// the handle vertices are not free, unlike the unconstrained vertices.\n\t\tfor (int i = 0; i < unconstrainedBegin; ++i) {\n\t\t\tenergyMatrixCoeffs.push_back(Triplet(i * 3 + N + 0, 3 * i + 0, 1));\n\t\t\tenergyMatrixCoeffs.push_back(Triplet(i * 3 + N + 1, 3 * i + 1, 1));\n\t\t\tenergyMatrixCoeffs.push_back(Triplet(i * 3 + N + 2, 3 * i + 2, 1));\n\t\t}\n\n\t\tSpMat augMat(M, N);\n\t\taugMat.setFromTriplets(energyMatrixCoeffs.begin(), energyMatrixCoeffs.end());\n\t\ts.augEnergyMatrixTrans = augMat.transpose();\n\n\t\t// for solving later, we need the cholesky decomposition of (transpose(augMat) * augMat)\n\t\t// this is a slow step! probably the slowest part of the entire algorithm.\n\t\ts.energyMatrixCholesky = new Eigen::SimplicialCholesky<SpMat>(s.augEnergyMatrixTrans * augMat);\n\t}\n\n\ts.b = Vec(M);\n\ts.roiIndices = roiIndices;\n\ts.nRoi = nRoi;\n\ts.RSI = RSI;\n}\n\nvoid doDeform(double* newHandlePositions, int nHandlePositions, double* outPositions) {\n\t{\n\t\tint count = 0;\n\t\tfor (int i = 0; i < s.roiDelta.size(); ++i) {\n\t\t\tif (s.RSI) {\n\t\t\t\t// following from our derivations, we must set all these to zero. \n\t\t\t\ts.b[count++] = 0.0f;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ts.b[count++] = s.roiDelta[i];\n\t\t\t}\n\t\t}\n\t\tfor (int j = 0; j < nHandlePositions; ++j) {\n\t\t\ts.b[count++] = newHandlePositions[j * 3 + 0];\n\t\t\ts.b[count++] = newHandlePositions[j * 3 + 1];\n\t\t\ts.b[count++] = newHandlePositions[j * 3 + 2];\n\t\t}\n\t}\n\n\tVec minimizerSolution;\n\t{\n\t\t// Now we solve \n\t\t// Ax = b\n\t\t// where A is the energy matrix, and the value of b depends on whether we are optimizing (4) or (5)\n\t\t// by solving, we obtain the deformed surface coordinates that minimizes either (4) or (5).\n\t\tVec y = s.augEnergyMatrixTrans * s.b;\n\t\tminimizerSolution = s.energyMatrixCholesky->solve(y);\n\t}\n\n\tif (s.RSI) {\n\t\t// if minimizing (5), a local scaling is introduced by the solver.\n\t\t// so we need to normalize the delta coordinates of the deformed vertices back to their\n\t\t// original lengths.\n\t\t// otherwise, the mesh will increase in size when manipulating the mesh, which is not desirable.\n\n\t\t// the normalization step is pretty simple:\n\t\t// we find the delta coordinates of our solution.\t\t\t\n\t\t// then we normalize these delta coordinates, so that their lengths match the lengths of the original, undeformed delta coordinates.\t\t\t\n\t\t// then we simply do a minimization to find the coordinates that are as close as possible to the normalized delta coordinates\t\n\t\t// and the solution of this minimization is our final solution.\n\n\t\tVec solutionDelta = s.lapMat * minimizerSolution;\n\n\t\tint count = 0;\n\t\tfor (int i = 0; i < s.roiDeltaLengths.size(); ++i) {\n\n\t\t\tdouble len = getLength(solutionDelta[3 * i + 0], solutionDelta[3 * i + 1], solutionDelta[3 * i + 2]);\n\t\t\tdouble originalLength = s.roiDeltaLengths[i];\n\t\t\tdouble scale = originalLength / len;\n\n\t\t\tfor (int d = 0; d < 3; ++d) {\n\t\t\t\ts.b[count++] = scale * solutionDelta[3 * i + d];\n\t\t\t}\n\t\t}\n\n\t\tVec y = s.augNormalizeDeltaCoordinatesTrans * s.b;\n\t\tVec normalizedSolution = s.normalizeDeltaCoordinatesCholesky->solve(y);\n\n\t\tfor (int i = 0; i < s.nRoi; ++i) {\n\t\t\tfor (int d = 0; d < 3; ++d) {\n\t\t\t\toutPositions[3 * s.roiIndices[i] + d] = normalizedSolution[3 * i + d];\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\tfor (int i = 0; i < s.nRoi; ++i) {\n\t\t\tfor (int d = 0; d < 3; ++d) {\n\t\t\t\toutPositions[3 * s.roiIndices[i] + d] = minimizerSolution[3 * i + d];\n\t\t\t}\n\t\t}\n\t}\n}\n\n", "meta": {"hexsha": "4a651db0ca07cd415c48c3f00e208f5db3ea6fef", "size": 17456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/laplacian_deformation.cpp", "max_stars_repo_name": "Inas-07/laplacian-deformation", "max_stars_repo_head_hexsha": "8ccbeee577972c7429a87f02a9663d26205330a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2017-07-31T07:32:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:46:31.000Z", "max_issues_repo_path": "cpp/src/laplacian_deformation.cpp", "max_issues_repo_name": "Inas-07/laplacian-deformation", "max_issues_repo_head_hexsha": "8ccbeee577972c7429a87f02a9663d26205330a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-05-21T19:17:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-27T00:49:07.000Z", "max_forks_repo_path": "cpp/src/laplacian_deformation.cpp", "max_forks_repo_name": "Inas-07/laplacian-deformation", "max_forks_repo_head_hexsha": "8ccbeee577972c7429a87f02a9663d26205330a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2017-08-18T21:50:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:18:00.000Z", "avg_line_length": 25.4460641399, "max_line_length": 137, "alphanum_fraction": 0.599335472, "num_tokens": 6313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.624334054046923}}
{"text": "\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <CGAL/Simple_cartesian.h>\n#include <cassert>\n#include <vector>\n#include <algorithm>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/algorithm.h>\n\nusing namespace CGAL;\n\ntypedef Simple_cartesian<double>         K;\ntypedef K::Point_2                    Point;\ntypedef Creator_uniform_2<int,Point>  Creator;\n\n\nvoid\ndisk(int N, double radius)\n{\n  std::cout.precision(12);\n  CGAL::Random_points_in_disc_2<Point> rng(radius);\n  std::cout << N << std::endl;\n  for(double i = 0; i < N; i++){\n    std::cout << *rng << std::endl;\n    ++rng;\n  }\n}\n\nint main(int argc, char* argv[])\n{\n  int N= 10;\n  double radius = 1;\n  try {\n\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n      (\"help\", \"Generator of perturbed points in a disk\")\n      (\"N\", po::value<int>(), \"generate N points\")\n      (\"radius\", po::value<double>(), \"radius of the disc\")\n      ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n      std::cout << desc << \"\\n\";\n      return 1;\n    }\n\n    if (vm.count(\"N\")) {\n      N = vm[\"N\"].as<int>();\n    }\n\n    if (vm.count(\"radius\")) {\n      radius = vm[\"radius\"].as<double>();\n    }\n  }\n  catch(std::exception& e) {\n    std::cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n\n  disk(N, radius);\n  return 0;\n}\n", "meta": {"hexsha": "736dd2ee956f1dc0cc8cbe47dd05dbf3d4ae477f", "size": 1425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Generator/benchmark/Generator/random_disc_2.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Generator/benchmark/Generator/random_disc_2.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Generator/benchmark/Generator/random_disc_2.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 20.652173913, "max_line_length": 60, "alphanum_fraction": 0.5852631579, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6243340498747993}}
{"text": "// \u00a9 2013 the Search Authors under the MIT license. See AUTHORS for the list of authors.\n\n#include \"utils.hpp\"\n#include \"safeops.hpp\"\n#include <boost/cstdint.hpp>\n#include <limits>\n#include <cmath>\n#include <functional>\n\nvoid fatal(const char*, ...);\n\nunsigned int ilog2(boost::uint32_t v) {\n\tif (!v)\n\t\treturn 0;\n\n\tunsigned int lg = 0;\n\n\tif (v & 0xFFFF0000) {\n\t\tlg += 16;\n\t\tv >>= 16;\n\t}\n\tif (v & 0xFF00) {\n\t\tlg += 8;\n\t\tv >>= 8;\n\t}\n\tif (v & 0xF0) {\n\t\tlg += 4;\n\t\tv >>= 4;\n\t}\n\tif (v & 0xC) {\n\t\tlg += 2;\n\t\tv >>= 2;\n\t}\n\tif (v & 0x2) {\n\t\tlg += 1;\n\t\tv >>= 1;\n\t}\n\treturn lg + 1;\n}\n\nunsigned long ipow(unsigned int b, unsigned int e) {\n\tunsigned long r = 1;\n\tfor (unsigned int i = 0; i < e; i++)\n\t\tr *= (unsigned long) b;\n\treturn r;\n}\n\nunsigned long fallfact(unsigned int x, unsigned int n) {\n\tunsigned long f = x;\n\tfor (unsigned int i = 1; i < n; i++)\n\t\tf *= (x - i);\n\treturn f;\n}\n\ndouble normcdf(double mu, double sigma, double x) {\n\treturn 0.5 * (1 + erf((x-mu)/sqrt(2*sigma*sigma)));\n}\n\ndouble phi(double x) {\n\tstatic const double sqrt2 = sqrt(2);\n\treturn 0.5 * (1 + erf(x/sqrt2));\n}\n\ndouble integrate(std::function<double(double)> getY, double start, double end, double stepsize) {\n\tdouble sum = 0;\n\tdouble y1 = 0;\n\tdouble y2 = getY(start);\n\tdouble cur = start;\n\tdouble next = start + stepsize;\n\tfor( ; next < end; cur = next, next+=stepsize) {\n\t\t\n\t\ty1 = y2;\n\t\ty2 = getY(next);\n\n\t\tsum += stepsize * ((y1 + y2) / 2);\n\t}\n\n\ty1 = y2;\n\ty2 = getY(end);\n\tnext = end;\n\tsum += (next - cur) * ((y1 + y2) / 2);\n\n\treturn sum;\n}\n\nNormal::Normal(double m, double s) : mean(m), stdev(s) {\n\tpdfcoeff = 1/(stdev*sqrt(2*M_PI));\n\tcdfcoeff = 1/(sqrt(2*stdev*stdev));\n}\n\ndouble Normal::pdf(double x) const {\n\treturn pdfcoeff * exp(-(x- mean)*(x-mean) / (2*stdev*stdev));\n}\n\ndouble Normal::cdf(double x) const {\n\treturn 0.5 * (1 + erf((x-mean)*cdfcoeff));\n}", "meta": {"hexsha": "b2e1fab2511ddb74a9759a474d95fb1017cc9046", "size": 1831, "ext": "cc", "lang": "C++", "max_stars_repo_path": "utils/math.cc", "max_stars_repo_name": "skiesel/search", "max_stars_repo_head_hexsha": "b9bb14810a85d6a486d603b3d81444c9d0b246b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T04:06:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T11:51:38.000Z", "max_issues_repo_path": "utils/math.cc", "max_issues_repo_name": "skiesel/search", "max_issues_repo_head_hexsha": "b9bb14810a85d6a486d603b3d81444c9d0b246b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-11-03T12:03:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-13T17:35:40.000Z", "max_forks_repo_path": "utils/math.cc", "max_forks_repo_name": "skiesel/search", "max_forks_repo_head_hexsha": "b9bb14810a85d6a486d603b3d81444c9d0b246b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-10-22T20:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-30T20:11:31.000Z", "avg_line_length": 18.8762886598, "max_line_length": 97, "alphanum_fraction": 0.587657018, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.6242602380111747}}
{"text": "#include \"quadrature/angular/gauss_legendre.h\"\n\n#include <deal.II/base/quadrature_lib.h>\n\nnamespace bart {\n\nnamespace quadrature {\n\nnamespace angular {\n\nGaussLegendre::GaussLegendre(const int n_points)\n    : n_points_(n_points) {\n  AssertThrow(n_points > 0,\n      dealii::ExcMessage(\"Error in constructor of GaussLegendre, n_points must \"\n                         \"be greater than or equal to 0\"))\n  this->set_description(\"Gauss-Legendre quadrature (1D)\");\n}\n\n\nstd::vector<GaussLegendre::PositionWeightPairType>\n    GaussLegendre::GenerateSet() const {\n  dealii::QGauss<1> gaussian_quadrature(n_points_);\n  std::vector<PositionWeightPairType> return_vector;\n\n  auto points = gaussian_quadrature.get_points();\n  auto weights = gaussian_quadrature.get_weights();\n\n  for (int i = 0; i < static_cast<int>(gaussian_quadrature.size()); ++i) {\n    CartesianPosition<1> x_position({points.at(i)[0]});\n    Weight weight(2*M_PI*weights.at(i));\n    return_vector.push_back({x_position, weight});\n  }\n\n  return return_vector;\n}\n\n} // namespace angular\n\n} // namespace quadrature\n\n} // namespace bart", "meta": {"hexsha": "b0c93b03a1892237f8168fbc2a7a3e3ca5385e36", "size": 1087, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/quadrature/angular/gauss_legendre.cc", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/quadrature/angular/gauss_legendre.cc", "max_issues_repo_name": "jsrehak/BART", "max_issues_repo_head_hexsha": "0460dfffbcf5671a730448de7f45cce39fd4a485", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/quadrature/angular/gauss_legendre.cc", "max_forks_repo_name": "jsrehak/BART", "max_forks_repo_head_hexsha": "0460dfffbcf5671a730448de7f45cce39fd4a485", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 26.512195122, "max_line_length": 80, "alphanum_fraction": 0.7184912603, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6242328064574049}}
{"text": "#include \"visualization/gl_shapes.hh\"\n#include \"visualization/opengl.hh\"\n\n#include \"geometry/geometry.hh\"\n\n#include <Eigen/Dense>\n\nnamespace sonder {\n\nvoid draw_coordinate_system() {\n  draw_coordinate_system(Eigen::Vector3f::Zero(), Eigen::Matrix3f::Identity());\n}\n\nvoid draw_coordinate_system(const se3 &pose) {\n  draw_coordinate_system(pose.translation(), pose.rotationMatrix());\n}\n\nvoid draw_coordinate_system(const Eigen::Vector3f &position, const Eigen::Matrix3f &orientation) {\n  glPushMatrix();\n\n  const Eigen::Quaternionf q(orientation);\n  glTranslate(position);\n  glRotate(q);\n\n  constexpr float narrow_scale = 0.05;\n  constexpr float wide_scale   = 0.5;\n  // Z\n  glPushMatrix();\n  glScalef(narrow_scale, narrow_scale, wide_scale);\n  glColor3f(0.0, 0.0, 1.0);\n  glTranslatef(0.0, 0.0, 1.0);\n  draw_cube();\n  glPopMatrix();\n\n  // Y\n  glPushMatrix();\n  glScalef(narrow_scale, wide_scale, narrow_scale);\n  glColor3f(0.0, 1.0, 0.0);\n  glTranslatef(0.0, 1.0, 0.0);\n  draw_cube();\n  glPopMatrix();\n\n  // X\n  glPushMatrix();\n  glScalef(wide_scale, narrow_scale, narrow_scale);\n  glColor3f(1.0, 0.0, 0.0);\n  glTranslatef(1.0, 0.0, 0.0);\n  draw_cube();\n  glPopMatrix();\n\n  glPopMatrix();\n}\n\nvoid draw_line(const Eigen::Vector3f &from, const Eigen::Vector3f &to) {\n  glBegin(GL_LINES);\n  {\n    glVertex(from);\n    glVertex(to);\n  }\n  glEnd();\n}\n\nvoid draw_line2d(const Eigen::Vector2f &from, const Eigen::Vector2f &to) {\n  glBegin(GL_LINES);\n  {\n    glVertex2f(from.x(), 1.0 - from.y());\n    glVertex2f(to.x(), 1.0 - to.y());\n  }\n  glEnd();\n}\n\nvoid draw_point2d(const Eigen::Vector2f &point, const float radius) {\n  glPushMatrix();\n  glTranslatef(point.x(), point.y(), -0.5f);\n  glutSolidSphere(radius, 16, 16);\n  glPopMatrix();\n}\n\nvoid draw_point(const Eigen::Vector3f &point, const float radius) {\n  glPushMatrix();\n  glTranslate(point);\n  glutSolidSphere(radius, 16, 16);\n  glPopMatrix();\n}\n\nvoid draw_circle(const Eigen::Vector3f &normal, const Eigen::Vector3f &center, const float radius) {\n  constexpr int   num_vertices   = 100;\n  constexpr float scaling_factor = 2.0f * M_PI / num_vertices;\n\n  //\n  // Build the circle in 2D on the x-y plane\n  //\n  Eigen::Array<float, 3, num_vertices> xy_plane_vertices;\n\n  for (int k = 0; k < num_vertices; ++k) {\n    const float t            = scaling_factor * static_cast<float>(k);\n    xy_plane_vertices.col(k) = Eigen::Vector3f(radius * std::cos(t), radius * std::sin(t), 0.0f);\n  }\n\n  //\n  // Transform the x-y plane circle to the normal plane\n  //\n\n  // A rotation between the Z axis and the circle normal\n  const Eigen::Quaternionf rotation = create_rotation_to(Eigen::Vector3f::UnitZ(), normal);\n\n  const se3 transform(rotation, center);\n\n  // Draw the lines (dotted)\n  // ((IF SOLID: GL_LINE_STRIP))\n  glBegin(GL_LINES);\n  {\n    for (int k = 0; k < num_vertices; ++k) {\n      glVertex(transform * xy_plane_vertices.col(k));\n    }\n  }\n  glEnd();\n}\n\nvoid draw_circle(const circle &ge_circle) {\n  draw_circle(ge_circle.normal, ge_circle.center, ge_circle.radius);\n}\n\nvoid draw_circular_section(const circular_section &section) {\n  constexpr int num_vertices = 100;\n\n  //\n  // Build the circle in 2D on the x-y plane\n  //\n  Eigen::Array<float, 3, num_vertices> xz_plane_vertices;\n  const float angle_per_vertex = section.arc_rads / static_cast<float>(num_vertices);\n  for (int k = 0; k < num_vertices; ++k) {\n    const float angle = (-section.arc_rads * 0.5f) + k * angle_per_vertex;\n    xz_plane_vertices.col(k) =\n        Eigen::Vector3f(section.radius * std::cos(angle), 0.0f, section.radius * std::sin(angle));\n  }\n\n  //\n  // Transform the x-z plane circle to the normal plane\n  //\n  const Eigen::Quaternionf rotation = rotation_from_xy(section.direction, section.normal);\n  const se3                transform(rotation, section.center);\n\n  // Draw the lines (dotted)\n  // ((IF SOLID: GL_LINE_STRIP))\n  glBegin(GL_LINE_STRIP);\n  {\n    for (int k = 0; k < num_vertices; ++k) {\n      glVertex(transform * xz_plane_vertices.col(k));\n    }\n  }\n  glEnd();\n  // glBegin(GL_LINES);\n  //{\n  //  glVertex(section.center);\n  //  glVertex(section.center + (section.direction * section.radius));\n  //}\n  // glEnd();\n}\n\nvoid draw_line(const line &ge_line) {\n  const Eigen::Vector3f scaled_direction = 10.0f * ge_line.direction;\n  draw_line(ge_line.point + scaled_direction, ge_line.point - scaled_direction);\n}\n\nvoid draw_plane(const plane &ge_plane) {\n  constexpr float       scale   = 5.0f;\n  const Eigen::Vector3f x_basis = any_perpendicular(ge_plane.normal).normalized();\n  const Eigen::Vector3f y_basis = x_basis.cross(ge_plane.normal).normalized();\n\n  glBegin(GL_QUADS);\n  {\n    glVertex((scale * x_basis) + ge_plane.point);\n    glVertex((scale * y_basis) + ge_plane.point);\n    glVertex(-(scale * x_basis) + ge_plane.point);\n    glVertex(-(scale * y_basis) + ge_plane.point);\n  }\n  glEnd();\n}\n\nvoid draw_cube() {\n  glBegin(GL_QUADS);\n  {\n    glVertex3f(-1.0, -1.0, -1.0);\n    glVertex3f(-1.0, -1.0, 1.0);\n    glVertex3f(-1.0, 1.0, 1.0);\n    glVertex3f(-1.0, 1.0, -1.0);\n\n    glVertex3f(-1.0, 1.0, -1.0);\n    glVertex3f(-1.0, 1.0, 1.0);\n    glVertex3f(1.0, 1.0, 1.0);\n    glVertex3f(1.0, 1.0, -1.0);\n\n    glVertex3f(1.0, 1.0, -1.0);\n    glVertex3f(1.0, 1.0, 1.0);\n    glVertex3f(1.0, -1.0, 1.0);\n    glVertex3f(1.0, -1.0, -1.0);\n\n    glVertex3f(1.0, -1.0, 1.0);\n    glVertex3f(1.0, -1.0, -1.0);\n    glVertex3f(-1.0, -1.0, -1.0);\n    glVertex3f(-1.0, -1.0, 1.0);\n\n    glVertex3f(-1.0, -1.0, 1.0);\n    glVertex3f(1.0, -1.0, 1.0);\n    glVertex3f(1.0, 1.0, 1.0);\n    glVertex3f(-1.0, 1.0, 1.0);\n\n    glVertex3f(-1.0, -1.0, -1.0);\n    glVertex3f(1.0, -1.0, -1.0);\n    glVertex3f(1.0, 1.0, -1.0);\n    glVertex3f(-1.0, 1.0, -1.0);\n  }\n  glEnd();\n}\n\n//\n// This isn't quite correct\n//\nvoid draw_sonar_view(const se3 &pose, const float max_bearing, const float max_elevation) {\n  constexpr float range = 20.0f;\n\n  const float x_sym = range * cos(max_bearing);\n  const float y_sym = range * sin(max_bearing);\n  const float z_sym = range * sin(max_elevation);\n\n  const Eigen::Vector3f symmetric_point(x_sym, y_sym, z_sym);\n\n  // draw_coordinate_system(pose.translation(), pose.rotationMatrix());\n  draw_coordinate_system(pose);\n\n  glPushMatrix();\n  glTranslate(pose.translation());\n  glRotate(pose.unit_quaternion());\n\n  glColor3f(0.9f, 0.0f, 0.0f);\n  glBegin(GL_LINE_STRIP);\n  {\n    glVertex3f(0.0, 0.0, 0.0);\n    glVertex3f(x_sym, y_sym, z_sym);\n    glVertex3f(x_sym, -y_sym, z_sym);\n\n    glVertex3f(0.0, 0.0, 0.0);\n    glVertex3f(x_sym, y_sym, -z_sym);\n    glVertex3f(x_sym, -y_sym, -z_sym);\n    glVertex3f(0.0, 0.0, 0.0);\n\n    glVertex3f(x_sym, -y_sym, -z_sym);\n    glVertex3f(x_sym, -y_sym, z_sym);\n\n    glVertex3f(x_sym, y_sym, z_sym);\n    glVertex3f(x_sym, y_sym, -z_sym);\n  }\n  glEnd();\n\n  glColor4f(0.2f, 0.7f, 0.0f, 0.2f);\n  // This does some weird stuff, meh\n  glBegin(GL_TRIANGLES);\n  {\n    glVertex3f(0.0, 0.0, 0.0);\n    glVertex3f(x_sym, y_sym, z_sym);\n    glVertex3f(x_sym, -y_sym, z_sym);\n\n    glVertex3f(0.0, 0.0, 0.0);\n    glVertex3f(x_sym, -y_sym, -z_sym);\n    glVertex3f(x_sym, y_sym, -z_sym);\n\n    glVertex3f(0.0, 0.0, 0.0);\n    glVertex3f(x_sym, -y_sym, -z_sym);\n    glVertex3f(x_sym, -y_sym, z_sym);\n\n    glVertex3f(0.0, 0.0, 0.0);\n    glVertex3f(x_sym, y_sym, z_sym);\n    glVertex3f(x_sym, y_sym, -z_sym);\n  }\n  glEnd();\n  glPopMatrix();\n}\n}", "meta": {"hexsha": "ae2537905a6557aeb2aa6b7007eaa58cf3b4ab9d", "size": 7295, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sonder/src/visualization/gl_shapes.cc", "max_stars_repo_name": "jpanikulam/sonder", "max_stars_repo_head_hexsha": "ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-24T07:52:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T07:52:39.000Z", "max_issues_repo_path": "sonder/src/visualization/gl_shapes.cc", "max_issues_repo_name": "jpanikulam/sonder", "max_issues_repo_head_hexsha": "ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sonder/src/visualization/gl_shapes.cc", "max_forks_repo_name": "jpanikulam/sonder", "max_forks_repo_head_hexsha": "ff3eece5f6a31d3bb2573d0e3e6dd5dafec7ffda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.146953405, "max_line_length": 100, "alphanum_fraction": 0.650719671, "num_tokens": 2423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6242328033901197}}
{"text": "/* -*-C++-*- */\n/*\n   (c) Copyright 2007, Hewlett-Packard Development Company, LP\n\n   See the file named COPYING for license details\n*/\n\n/** @file\n    implementation\n*/\n#include <Lintel/AssertBoost.hpp>\n#include <Lintel/LeastSquares.hpp>\n\n#include <boost/format.hpp>\n\nusing namespace std;\nusing boost::format;\n\nLeastSquares::Linear LeastSquares::fitLinearVertical(const WeightedData &data) {\n    double sum_w = 0,  sum_wx = 0, sum_wy = 0, sum_wxx = 0, sum_wxy = 0;\n\n    INVARIANT(data.size() > 1, \"must have at least 2 points for linear fit\");\n\n    for (WeightedData::const_iterator i = data.begin(); i != data.end(); ++i) {\n\tsum_w += i->weight;\n\tsum_wx += i->weight * i->x;\n\tsum_wy += i->weight * i->y;\n\tsum_wxx += i->weight * i->x * i->x;\n\tsum_wxy += i->weight * i->x * i->y;\n    }\n\n    Linear ret;\n    double denom = sum_w * sum_wxx - sum_wx * sum_wx;\n    INVARIANT(denom != 0.0, \"denominator is 0, aborting\");\n    ret.slope = (sum_w * sum_wxy - sum_wx * sum_wy) / denom;\n    ret.intercept = (sum_wy - ret.slope * sum_wx) / sum_w;\n\n    return ret;\n}\n\nvoid LeastSquares::printText(ostream &to) const {\n    for(WeightedData::const_iterator i = data.begin(); i != data.end(); ++i) {\n\tto << boost::format(\"%24.18g %24.18g %24.18g\\n\") % i->x % i->y % i->weight;\n    }\n}\n", "meta": {"hexsha": "724e91dcb9139f6fd00aaa98366d10cb4b14eeb6", "size": 1268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LeastSquares.cpp", "max_stars_repo_name": "sbu-fsl/Lintel", "max_stars_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LeastSquares.cpp", "max_issues_repo_name": "sbu-fsl/Lintel", "max_issues_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-05T21:20:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-05T21:56:51.000Z", "max_forks_repo_path": "src/LeastSquares.cpp", "max_forks_repo_name": "sbu-fsl/Lintel", "max_forks_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5652173913, "max_line_length": 80, "alphanum_fraction": 0.6269716088, "num_tokens": 416, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6242048468699588}}
{"text": "// inverse_gamma.hpp\n\n//  Copyright Paul A. Bristow 2010.\n//  Copyright John Maddock 2010.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_STATS_INVERSE_GAMMA_HPP\n#define BOOST_STATS_INVERSE_GAMMA_HPP\n\n// Inverse Gamma Distribution is a two-parameter family\n// of continuous probability distributions\n// on the positive real line, which is the distribution of\n// the reciprocal of a variable distributed according to the gamma distribution.\n\n// http://en.wikipedia.org/wiki/Inverse-gamma_distribution\n// http://rss.acs.unt.edu/Rdoc/library/pscl/html/igamma.html\n\n// See also gamma distribution at gamma.hpp:\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda366b.htm\n// http://mathworld.wolfram.com/GammaDistribution.html\n// http://en.wikipedia.org/wiki/Gamma_distribution\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/math/distributions/complement.hpp>\n\n#include <utility>\n\nnamespace boost{ namespace math\n{\nnamespace detail\n{\n\ntemplate <class RealType, class Policy>\ninline bool check_inverse_gamma_shape(\n      const char* function, // inverse_gamma\n      RealType shape, // shape aka alpha\n      RealType* result, // to update, perhaps with NaN\n      const Policy& pol)\n{  // Sources say shape argument must be > 0\n   // but seems logical to allow shape zero as special case,\n   // returning pdf and cdf zero (but not < 0).\n   // (Functions like mean, variance with other limits on shape are checked\n   // in version including an operator & limit below).\n   if((shape < 0) || !(boost::math::isfinite)(shape))\n   {\n      *result = policies::raise_domain_error<RealType>(\n         function,\n         \"Shape parameter is %1%, but must be >= 0 !\", shape, pol);\n      return false;\n   }\n   return true;\n} //bool check_inverse_gamma_shape\n\ntemplate <class RealType, class Policy>\ninline bool check_inverse_gamma_x(\n      const char* function,\n      RealType const& x,\n      RealType* result, const Policy& pol)\n{\n   if((x < 0) || !(boost::math::isfinite)(x))\n   {\n      *result = policies::raise_domain_error<RealType>(\n         function,\n         \"Random variate is %1% but must be >= 0 !\", x, pol);\n      return false;\n   }\n   return true;\n}\n\ntemplate <class RealType, class Policy>\ninline bool check_inverse_gamma(\n      const char* function, // TODO swap these over, so shape is first.\n      RealType scale,  // scale aka beta\n      RealType shape, // shape aka alpha\n      RealType* result, const Policy& pol)\n{\n   return check_scale(function, scale, result, pol)\n     && check_inverse_gamma_shape(function, shape, result, pol);\n} // bool check_inverse_gamma\n\n} // namespace detail\n\ntemplate <class RealType = double, class Policy = policies::policy<> >\nclass inverse_gamma_distribution\n{\npublic:\n   typedef RealType value_type;\n   typedef Policy policy_type;\n\n   inverse_gamma_distribution(RealType shape = 1, RealType scale = 1)\n      : m_shape(shape), m_scale(scale)\n   {\n      RealType result;\n      detail::check_inverse_gamma(\n        \"boost::math::inverse_gamma_distribution<%1%>::inverse_gamma_distribution\",\n        scale, shape, &result, Policy());\n   }\n\n   RealType shape()const\n   {\n      return m_shape;\n   }\n\n   RealType scale()const\n   {\n      return m_scale;\n   }\nprivate:\n   //\n   // Data members:\n   //\n   RealType m_shape;     // distribution shape\n   RealType m_scale;     // distribution scale\n};\n\ntypedef inverse_gamma_distribution<double> inverse_gamma;\n// typedef - but potential clash with name of inverse gamma *function*.\n// but there is a typedef for gamma\n//   typedef boost::math::gamma_distribution<Type, Policy> gamma;\n\n// Allow random variable x to be zero, treated as a special case (unlike some definitions).\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> range(const inverse_gamma_distribution<RealType, Policy>& /* dist */)\n{  // Range of permissible values for random variable x.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>(0, max_value<RealType>());\n}\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> support(const inverse_gamma_distribution<RealType, Policy>& /* dist */)\n{  // Range of supported values for random variable x.\n   // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\n   using boost::math::tools::max_value;\n   using boost::math::tools::min_value;\n   return std::pair<RealType, RealType>(0,  max_value<RealType>());\n}\n\ntemplate <class RealType, class Policy>\ninline RealType pdf(const inverse_gamma_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   static const char* function = \"boost::math::pdf(const inverse_gamma_distribution<%1%>&, %1%)\";\n\n   RealType shape = dist.shape();\n   RealType scale = dist.scale();\n\n   RealType result;\n   if(false == detail::check_inverse_gamma(function, scale, shape, &result, Policy()))\n   { // distribution parameters bad.\n      return result;\n   } \n   if(x == 0)\n   { // Treat random variate zero as a special case.\n      return 0;\n   }\n   else if(false == detail::check_inverse_gamma_x(function, x, &result, Policy()))\n   { // x bad.\n      return result;\n   }\n   result = scale / x;\n   if(result < tools::min_value<RealType>())\n      return 0;  // random variable is infinite or so close as to make no difference.\n   result = gamma_p_derivative(shape, result, Policy()) * scale;\n   if(0 != result)\n   {\n      if(x < 0)\n      {\n         // x * x may under or overflow, likewise our result,\n         // so be extra careful about the arithmetic:\n         RealType lim = tools::max_value<RealType>() * x;\n         if(lim < result)\n            return policies::raise_overflow_error<RealType, Policy>(function, \"PDF is infinite.\", Policy());\n         result /= x;\n         if(lim < result)\n            return policies::raise_overflow_error<RealType, Policy>(function, \"PDF is infinite.\", Policy());\n         result /= x;\n      }\n      result /= (x * x);\n   }\n   // better than naive\n   // result = (pow(scale, shape) * pow(x, (-shape -1)) * exp(-scale/x) ) / tgamma(shape);\n   return result;\n} // pdf\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const inverse_gamma_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   static const char* function = \"boost::math::cdf(const inverse_gamma_distribution<%1%>&, %1%)\";\n\n   RealType shape = dist.shape();\n   RealType scale = dist.scale();\n\n   RealType result;\n   if(false == detail::check_inverse_gamma(function, scale, shape, &result, Policy()))\n   { // distribution parameters bad.\n      return result;\n   }\n   if (x == 0)\n   { // Treat zero as a special case.\n     return 0;\n   }\n   else if(false == detail::check_inverse_gamma_x(function, x, &result, Policy()))\n   { // x bad\n      return result;\n   }\n   result = boost::math::gamma_q(shape, scale / x, Policy());\n   // result = tgamma(shape, scale / x) / tgamma(shape); // naive using tgamma\n   return result;\n} // cdf\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const inverse_gamma_distribution<RealType, Policy>& dist, const RealType& p)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n   using boost::math::gamma_q_inv;\n\n   static const char* function = \"boost::math::quantile(const inverse_gamma_distribution<%1%>&, %1%)\";\n\n   RealType shape = dist.shape();\n   RealType scale = dist.scale();\n\n   RealType result;\n   if(false == detail::check_inverse_gamma(function, scale, shape, &result, Policy()))\n      return result;\n   if(false == detail::check_probability(function, p, &result, Policy()))\n      return result;\n   if(p == 1)\n   {\n      return policies::raise_overflow_error<RealType>(function, 0, Policy());\n   }\n   result = gamma_q_inv(shape, p, Policy());\n   if((result < 1) && (result * tools::max_value<RealType>() < scale))\n      return policies::raise_overflow_error<RealType, Policy>(function, \"Value of random variable in inverse gamma distribution quantile is infinite.\", Policy());\n   result = scale / result;\n   return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const complemented2_type<inverse_gamma_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   static const char* function = \"boost::math::quantile(const gamma_distribution<%1%>&, %1%)\";\n\n   RealType shape = c.dist.shape();\n   RealType scale = c.dist.scale();\n\n   RealType result;\n   if(false == detail::check_inverse_gamma(function, scale, shape, &result, Policy()))\n      return result;\n   if(false == detail::check_inverse_gamma_x(function, c.param, &result, Policy()))\n      return result;\n\n   //result = 1. - gamma_q(shape, c.param / scale, Policy());\n   result = gamma_p(shape, scale/c.param, Policy());\n   return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const complemented2_type<inverse_gamma_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   static const char* function = \"boost::math::quantile(const inverse_gamma_distribution<%1%>&, %1%)\";\n\n   RealType shape = c.dist.shape();\n   RealType scale = c.dist.scale();\n   RealType q = c.param;\n\n   RealType result;\n   if(false == detail::check_inverse_gamma(function, scale, shape, &result, Policy()))\n      return result;\n   if(false == detail::check_probability(function, q, &result, Policy()))\n      return result;\n\n   if(q == 0)\n   {\n      return policies::raise_overflow_error<RealType>(function, 0, Policy());\n   }\n   result = gamma_p_inv(shape, q, Policy());\n   if((result < 1) && (result * tools::max_value<RealType>() < scale))\n      return policies::raise_overflow_error<RealType, Policy>(function, \"Value of random variable in inverse gamma distribution quantile is infinite.\", Policy());\n   result = scale / result;\n   return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType mean(const inverse_gamma_distribution<RealType, Policy>& dist)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   static const char* function = \"boost::math::mean(const inverse_gamma_distribution<%1%>&)\";\n\n   RealType shape = dist.shape();\n   RealType scale = dist.scale();\n\n   RealType result;\n\n   if(false == detail::check_scale(function, scale, &result, Policy()))\n   {\n     return result;\n   }\n   if((shape <= 1) || !(boost::math::isfinite)(shape))\n   {\n     result = policies::raise_domain_error<RealType>(\n       function,\n       \"Shape parameter is %1%, but for a defined mean it must be > 1\", shape, Policy());\n     return result;\n   }\n  result = scale / (shape - 1);\n  return result;\n} // mean\n\ntemplate <class RealType, class Policy>\ninline RealType variance(const inverse_gamma_distribution<RealType, Policy>& dist)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   static const char* function = \"boost::math::variance(const inverse_gamma_distribution<%1%>&)\";\n\n   RealType shape = dist.shape();\n   RealType scale = dist.scale();\n\n   RealType result;\n      if(false == detail::check_scale(function, scale, &result, Policy()))\n   {\n     return result;\n   }\n   if((shape <= 2) || !(boost::math::isfinite)(shape))\n   {\n     result = policies::raise_domain_error<RealType>(\n       function,\n       \"Shape parameter is %1%, but for a defined variance it must be > 2\", shape, Policy());\n     return result;\n   }\n   result = (scale * scale) / ((shape - 1) * (shape -1) * (shape -2));\n   return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType mode(const inverse_gamma_distribution<RealType, Policy>& dist)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   static const char* function = \"boost::math::mode(const inverse_gamma_distribution<%1%>&)\";\n\n   RealType shape = dist.shape();\n   RealType scale = dist.scale();\n\n   RealType result;\n   if(false == detail::check_inverse_gamma(function, scale, shape, &result, Policy()))\n   {\n      return result;\n   }\n   // Only defined for shape >= 0, but is checked by check_inverse_gamma.\n   result = scale / (shape + 1);\n   return result;\n}\n\n//template <class RealType, class Policy>\n//inline RealType median(const gamma_distribution<RealType, Policy>& dist)\n//{  // Wikipedia does not define median,\n     // so rely on default definition quantile(0.5) in derived accessors.\n//  return result.\n//}\n\ntemplate <class RealType, class Policy>\ninline RealType skewness(const inverse_gamma_distribution<RealType, Policy>& dist)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   static const char* function = \"boost::math::skewness(const inverse_gamma_distribution<%1%>&)\";\n\n   RealType shape = dist.shape();\n   RealType scale = dist.scale();\n   RealType result;\n\n   if(false == detail::check_scale(function, scale, &result, Policy()))\n   {\n     return result;\n   }\n   if((shape <= 3) || !(boost::math::isfinite)(shape))\n   {\n     result = policies::raise_domain_error<RealType>(\n       function,\n       \"Shape parameter is %1%, but for a defined skewness it must be > 3\", shape, Policy());\n     return result;\n   }\n   result = (4 * sqrt(shape - 2) ) / (shape - 3);\n   return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis_excess(const inverse_gamma_distribution<RealType, Policy>& dist)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   static const char* function = \"boost::math::kurtosis_excess(const inverse_gamma_distribution<%1%>&)\";\n\n   RealType shape = dist.shape();\n   RealType scale = dist.scale();\n\n   RealType result;\n   if(false == detail::check_scale(function, scale, &result, Policy()))\n   {\n     return result;\n   }\n   if((shape <= 4) || !(boost::math::isfinite)(shape))\n   {\n     result = policies::raise_domain_error<RealType>(\n       function,\n       \"Shape parameter is %1%, but for a defined kurtosis excess it must be > 4\", shape, Policy());\n     return result;\n   }\n   result = (30 * shape - 66) / ((shape - 3) * (shape - 4));\n   return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis(const inverse_gamma_distribution<RealType, Policy>& dist)\n{\n  static const char* function = \"boost::math::kurtosis(const inverse_gamma_distribution<%1%>&)\";\n   RealType shape = dist.shape();\n   RealType scale = dist.scale();\n\n   RealType result;\n\n  if(false == detail::check_scale(function, scale, &result, Policy()))\n   {\n     return result;\n   }\n   if((shape <= 4) || !(boost::math::isfinite)(shape))\n   {\n     result = policies::raise_domain_error<RealType>(\n       function,\n       \"Shape parameter is %1%, but for a defined kurtosis it must be > 4\", shape, Policy());\n     return result;\n   }\n  return kurtosis_excess(dist) + 3;\n}\n\n} // namespace math\n} // namespace boost\n\n// This include must be at the end, *after* the accessors\n// for this distribution have been defined, in order to\n// keep compilers that support two-phase lookup happy.\n#include <boost/math/distributions/detail/derived_accessors.hpp>\n\n#endif // BOOST_STATS_INVERSE_GAMMA_HPP\n", "meta": {"hexsha": "4f274d9cf69f32df61143601f9f875e8aa7c1374", "size": 15224, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "projects/MonkVG-Android/jni/boost/include/boost/math/distributions/inverse_gamma.hpp", "max_stars_repo_name": "smartmobili/MonkVG", "max_stars_repo_head_hexsha": "3fad9b73d30c13411e0ca47bd3e2cc803ac89a9d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T19:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T23:10:45.000Z", "max_issues_repo_path": "projects/MonkVG-Android/jni/boost/include/boost/math/distributions/inverse_gamma.hpp", "max_issues_repo_name": "smartmobili/MonkVG", "max_issues_repo_head_hexsha": "3fad9b73d30c13411e0ca47bd3e2cc803ac89a9d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-02T06:30:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T18:39:55.000Z", "max_forks_repo_path": "projects/MonkVG-Android/jni/boost/include/boost/math/distributions/inverse_gamma.hpp", "max_forks_repo_name": "smartmobili/MonkVG", "max_forks_repo_head_hexsha": "3fad9b73d30c13411e0ca47bd3e2cc803ac89a9d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-03-04T08:50:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T14:27:04.000Z", "avg_line_length": 33.1677559913, "max_line_length": 162, "alphanum_fraction": 0.6818181818, "num_tokens": 3762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6242048424701055}}
{"text": "#ifndef MPFR_SUPPORT\n#define MPFR_SUPPORT\n\n#include <boost/multiprecision/mpfr.hpp>\n#include <eigen3/Eigen/Core>\n#define PREC 300  //change this to change precision\n\ntypedef boost::multiprecision::number<mpfr_float_backend<PREC> > big_float;\n\nnamespace Eigen {\n  template<> struct NumTraits<big_float> {\n\n  typedef big_float Real;\n  typedef big_float NonInteger;\n  typedef big_float Nested;\n\n  enum {\n    IsComplex = 0,\n    IsInteger = 0,\n    IsSigned = 1,\n    RequireInitialization = 1,\n    ReadCost = 1,\n    AddCost = 3,\n    MulCost = 3\n  };\n  \n  };\n}\n\n\n\n#endif\n", "meta": {"hexsha": "518c25d6644141c45f2e530e6f0529c38dbc7229", "size": 564, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/mpmatrix.cc", "max_stars_repo_name": "dtaquinas/Measures", "max_stars_repo_head_hexsha": "0630e343e81051381dcb223a3290fe242180d617", "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/mpmatrix.cc", "max_issues_repo_name": "dtaquinas/Measures", "max_issues_repo_head_hexsha": "0630e343e81051381dcb223a3290fe242180d617", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mpmatrix.cc", "max_forks_repo_name": "dtaquinas/Measures", "max_forks_repo_head_hexsha": "0630e343e81051381dcb223a3290fe242180d617", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0909090909, "max_line_length": 75, "alphanum_fraction": 0.6968085106, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.624204840457633}}
{"text": "// Author(s): Jeroen Keiren\n// Copyright: see the accompanying file COPYING or copy at\n// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n/// \\file set_test.cpp\n/// \\brief Basic regression test for set expressions.\n\n#include <boost/test/minimal.hpp>\n\n#include \"mcrl2/data/standard.h\"\n#include \"mcrl2/data/set.h\"\n#include \"mcrl2/data/fset.h\"\n#include \"mcrl2/data/parse.h\"\n#include \"mcrl2/data/rewriter.h\"\n\n\nusing namespace mcrl2;\nusing namespace mcrl2::data;\nusing namespace mcrl2::data::sort_set;\nusing namespace mcrl2::data::sort_fset;\n\ntemplate <typename Predicate>\nvoid test_data_expression(const std::string& s, const variable_vector& v, Predicate p)\n{\n  std::cerr << \"testing data expression \" << s << std::endl;\n  data_expression e = parse_data_expression(s, v);\n  BOOST_CHECK(p(e));\n}\n\n/* Test case for various set expressions, based\n   on the following specification:\n\nproc P(s: Set(Nat)) = (1 in s) -> tau . P({} + s - {20} * {40})\n                    + ({10} < s) -> tau . P(!s)\n                    + (s <= {20} + Bag2Set({20:4, 30:3, 40:2})) -> tau . P(s)\n                    + (s <= { n:Nat | true }) -> tau . P(s);\n\ninit P({20, 30, 40});\n\n*/\nvoid set_expression_test()\n{\n  data::data_specification specification;\n\n  specification.add_context_sort(sort_pos::pos());\n  specification.add_context_sort(sort_set::set_(sort_pos::pos()));\n  specification.add_context_sort(sort_set::set_(sort_bool::bool_()));\n\n  data::rewriter normaliser(specification);\n\n  variable_vector v;\n  v.push_back(parse_variable(\"s:Set(Nat)\"));\n\n  test_data_expression(\"{x : Nat | x < 10}\", v, sort_set::is_constructor_application);\n  test_data_expression(\"!s\", v, sort_set::is_complement_application);\n  test_data_expression(\"s * {}\", v, sort_set::is_intersection_application);\n  test_data_expression(\"s * {1,2,3}\", v, sort_set::is_intersection_application);\n  test_data_expression(\"s - {3,1,2}\", v, sort_set::is_difference_application);\n  test_data_expression(\"1 in s\", v, sort_set::is_in_application);\n  test_data_expression(\"{} + s\", v, sort_set::is_union_application);\n  test_data_expression(\"(({} + s) - {20}) * {40}\", v, sort_set::is_intersection_application);\n  test_data_expression(\"{10} < s\", v, is_less_application<data_expression>);\n  test_data_expression(\"s <= {10}\", v, is_less_equal_application<data_expression>);\n  test_data_expression(\"{20} + {30}\", v, sort_set::is_union_application);\n\n  data_expression t1d1 = parse_data_expression(\"{1,2}\");\n  data_expression t1d2 = parse_data_expression(\"{2,1}\");\n  BOOST_CHECK(normaliser(t1d1) == normaliser(t1d2));\n\n  data_expression t1d1a = parse_data_expression(\"{1,2,3}\");\n  data_expression t1d2a = parse_data_expression(\"{2,1}\");\n  BOOST_CHECK(normaliser(t1d1a) != normaliser(t1d2a));\n\n  data_expression t2d1 = parse_data_expression(\"{1,2} == {1,2}\");\n  data_expression t2d2 = parse_data_expression(\"true\");\n  BOOST_CHECK(normaliser(t2d1) == normaliser(t2d2));\n\n  data_expression t2d1a = parse_data_expression(\"{1,2,3} == {1,2,1}\");\n  data_expression t2d2a = parse_data_expression(\"false\");\n  BOOST_CHECK(normaliser(t2d1a) == normaliser(t2d2a));\n\n  data_expression t3d1 = parse_data_expression(\"({1,2} != {2,3})\");\n  data_expression t3d2 = parse_data_expression(\"true\");\n  BOOST_CHECK(normaliser(t3d1) == normaliser(t3d2));\n\n  data_expression t4d1 = parse_data_expression(\"(!{1,2}) == {1,2}\");\n  data_expression t4d2 = parse_data_expression(\"false\");\n  BOOST_CHECK(normaliser(t4d1) == normaliser(t4d2));\n\n  data_expression t5d1 = parse_data_expression(\"(!!{1,2}) == {2,1}\");\n  data_expression t5d2 = parse_data_expression(\"true\");\n  BOOST_CHECK(normaliser(t5d1) == normaliser(t5d2));\n\n\n  data_expression e = parse_data_expression(\"{20}\", v);\n  BOOST_CHECK(sort_fset::is_cons_application(normaliser(e)));\n\n  e = parse_data_expression(\"{20, 30, 40}\", v);\n  BOOST_CHECK(sort_fset::is_cons_application(normaliser(e)));\n\n  data_expression t6d1 = parse_data_expression(\"{} == { b: Bool | true } - { true, false }\");\n  data_expression t6d2 = parse_data_expression(\"true\");\n\n  BOOST_CHECK(normaliser(t6d1) == normaliser(t6d2));\n\n  data_expression t7d1 = parse_data_expression(\"{ b: Bool | true } - { true, false } == {}\");\n  data_expression t7d2 = parse_data_expression(\"true\");\n  BOOST_CHECK(normaliser(t7d1) == normaliser(t7d2));\n\n}\n\nint test_main(int argc, char** argv)\n{\n  set_expression_test();\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "bf2dfdedb10eb203a86baa0ebee45696a6338498", "size": 4531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/data/test/set_test.cpp", "max_stars_repo_name": "gijskant/mcrl2-pmc", "max_stars_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/data/test/set_test.cpp", "max_issues_repo_name": "gijskant/mcrl2-pmc", "max_issues_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/data/test/set_test.cpp", "max_forks_repo_name": "gijskant/mcrl2-pmc", "max_forks_repo_head_hexsha": "9ea75755081b20623bc8fc7db27124d084e781fe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.837398374, "max_line_length": 93, "alphanum_fraction": 0.7018318252, "num_tokens": 1278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.624204840457633}}
{"text": "#include <Eigen/Dense>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\nEigen::MatrixXd read_matrix(std::string file_name);\n\nint main(int argc, char *argv[]) {\n    if (argc < 2) {\n        std::cerr << \"# error: no file specified\" << std::endl;\n        return 1;\n    }\n    Eigen::MatrixXd A = read_matrix(std::string(argv[1]));\n    std::cout << \"A =\" << std::endl << A << std::endl;\n    return 0;\n}\n\nEigen::MatrixXd read_matrix(std::string file_name) {\n    std::size_t nr_rows {0};\n    std::vector<double> elements;\n    std::size_t nr_cols {0};\n    std::ifstream ifs(file_name);\n    std::string line;\n    while (std::getline(ifs, line)) {\n        std::stringstream str(line);\n        double val;\n        std::size_t nr_vals {0};\n        while (str >> val) {\n            elements.push_back(val);\n            ++nr_vals;\n        }\n        if (nr_cols == 0) {\n            nr_cols = nr_vals;\n        } else  if (nr_vals > 0 && nr_vals != nr_cols) {\n            std::cerr << \"Error: incorrect file format\" << std::endl;\n            std::exit(1);\n        }\n        if (nr_vals > 0)\n            ++nr_rows;\n    }\n    ifs.close();\n    Eigen::MatrixXd matrix(nr_rows, nr_cols);\n    for (long i = 0; i < matrix.rows(); ++i)\n        for (long j = 0; j < matrix.cols(); ++j)\n            matrix(i, j) = elements[i*matrix.cols() + j];\n    return matrix;\n}\n", "meta": {"hexsha": "04aa28d07cc0d5c50624933c4a8fe37ab0f8a3e9", "size": 1367, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Eigen/read_matrix.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Eigen/read_matrix.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Eigen/read_matrix.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 27.8979591837, "max_line_length": 69, "alphanum_fraction": 0.5376737381, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6242048356828712}}
{"text": "/*!\n*\t@file\tCurvatureFlow.cpp\n*\t@brief\tImplementation of a curvature flow algorithm\n*/\n\n#include \"CurvatureFlow.h\"\n\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_sparse.hpp>\n\n#include <boost/numeric/bindings/traits/ublas_sparse.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n\n#include <boost/numeric/bindings/umfpack/umfpack.hpp>\n\nnamespace psalm\n{\n\n/*!\n*\tSets default values\n*/\n\nCurvatureFlow::CurvatureFlow()\n{\n\tnum_steps\t= 0;\n\tdt\t\t= 0.5;\n}\n\n/*!\n*\tApplies the curvature flow algorithm to the vertices of a given mesh.\n*\tThe size of timesteps needs to be set before. The input mesh is\n*\tirreversibly changed by this operation.\n*\n*\t@param\tinput_mesh Mesh on which the algorithm works.\n*\t@return\tfalse if an error occurred, else true\n*/\n\nbool CurvatureFlow::apply_to(mesh& input_mesh)\n{\n\tnamespace ublas = boost::numeric::ublas;\n\tnamespace umf = boost::numeric::bindings::umfpack;\n\n\tsize_t n = input_mesh.num_vertices();\n\tif(n == 0)\n\t\treturn(true); // silently ignore empty meshes\n\n\t// Stores x,y,z components of the vertices in the mesh\n\tublas::vector<double> X(n);\n\tublas::vector<double> Y(n);\n\tublas::vector<double> Z(n);\n\n\t// Fill vector with position data\n\tfor(size_t i = 0; i < n; i++)\n\t{\n\t\tconst v3ctor& pos = input_mesh.get_vertex(i)->get_position();\n\n\t\tX[i] = pos[0];\n\t\tY[i] = pos[1];\n\t\tZ[i] = pos[2];\n\t}\n\n\tfor(size_t i = 0; i < num_steps; i++)\n\t{\n\t\t// Prepare for \"solving\" the linear system (for now, this is something\n\t\t// akin to the explicit Euler method)\n\n\t\tublas::compressed_matrix<\tdouble,\n\t\t\t\t\t\tublas::column_major,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tublas::unbounded_array<int>,\n\t\t\t\t\t\tublas::unbounded_array<double> > M(n, n);\t// transformed matrix for the solving\n\t\t\t\t\t\t\t\t\t\t\t\t// process, i.e. id - dt*K, where K is\n\t\t\t\t\t\t\t\t\t\t\t\t// the matrix of the curvature operator\n\n\t\tM = ublas::identity_matrix<double>(n, n) - dt*calc_curvature_operator(input_mesh);\n\n\t\t// Solve x,y,z components independently. This may be slower,\n\t\t// but sufficient for small meshes.\n\n\t\tumf::symbolic_type<double> Symbolic;\n\t\tumf::numeric_type<double> Numeric;\n\n\t\tumf::symbolic(M, Symbolic);\n\t\tumf::numeric(M, Symbolic, Numeric);\n\n\t\tublas::vector<double> X_new(input_mesh.num_vertices());\n\t\tublas::vector<double> Y_new(input_mesh.num_vertices());\n\t\tublas::vector<double> Z_new(input_mesh.num_vertices());\n\n\t\tumf::solve(M, X_new, X, Numeric);\n\t\tumf::solve(M, Y_new, Y, Numeric);\n\t\tumf::solve(M, Z_new, Z, Numeric);\n\n\t\tX = X_new;\n\t\tY = Y_new;\n\t\tZ = Z_new;\n\n\t\tfor(size_t i = 0; i < n; i++)\n\t\t\tinput_mesh.get_vertex(i)->set_position(X[i], Y[i], Z[i]);\n\t}\n\n\treturn(true);\n}\n\n/*!\n*\tGiven an input mesh, calculates the curvature operator matrix for this\n*\tmesh. The matrix will be a _sparse_ matrix, hence the need for handling\n*\tit via boost.\n*\n*\t@param\tinput_mesh Mesh to be processed\n*\t@return\tSparse matrix describing the curvature operator\n*/\n\nboost::numeric::ublas::compressed_matrix<double> CurvatureFlow::calc_curvature_operator(mesh& input_mesh)\n{\n\tusing namespace boost::numeric::ublas;\n\tcompressed_matrix<double> K(input_mesh.num_vertices(), input_mesh.num_vertices()); // K as in \"Kurvature\"...\n\n\t// We iterate over all vertices and calculate the contributions of each\n\t// vertex to the corresponding entry of the matrix\n\n\tfor(size_t i = 0; i < input_mesh.num_vertices(); i++)\n\t{\n\t\tvertex* v = input_mesh.get_vertex(i);\n\t\tstd::vector<const vertex*> neighbours = v->get_neighbours();\n\n\t\t// FIXME: Used to update the correct matrix entries\n\t\t// below. This assumes that the IDs have been allocated\n\t\t// sequentially.\n\t\tsize_t cur_id = v->get_id();\n\n\t\t// Find \"opposing angles\" for all neighbours; these are\n\t\t// the $\\alpha_{ij}$ and $\\beta_{ij}$ values used for\n\t\t// calculating the discrete curvature\n\n\t\tfor(size_t j = 0; j < neighbours.size(); j++)\n\t\t{\n\t\t\tstd::pair<double, double> angles = v->find_opposite_angles(neighbours[j]);\n\t\t\tif(angles.first >= 0.0 && angles.second >= 0.0)\n\t\t\t{\n\t\t\t\t// calculate contribution to matrix entries\n\n\t\t\t\tdouble contribution = 1.0/tan(angles.first) + 1.0/tan(angles.second);\n\n\t\t\t\tK(cur_id, cur_id)\t\t\t+= contribution;\n\t\t\t\tK(cur_id, neighbours[j]->get_id())\t-= contribution;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Scale the ith row of the matrix by the Voronoi area around the ith\n\t// vertex; this works because the _first_ iterator of all matrix types\n\t// is dense, whereas the second iterator is sparse in this case\n\n\tsize_t i = 0;\n\tfor(compressed_matrix<double>::iterator1 it1 = K.begin1(); it1 != K.end1(); it1++)\n\t{\n\t\tdouble area = input_mesh.get_vertex(i)->calc_ring_area();\n\t\tif(area < 2*std::numeric_limits<double>::epsilon())\n\t\t{\n\t\t\t// skip on error or upon encountering a Voronoi area\n\t\t\t// that is too small\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor(compressed_matrix<double>::iterator2 it2 = it1.begin(); it2 != it1.end(); it2++)\n\t\t\t(*it2) /= 4.0*area;\n\n\t\ti++;\n\t}\n\n\treturn(K);\n}\n\n/*!\n*\tSets current value for the delta parameter (used per timestep).\n*\n*\t@param delta New value for delta parameter\n*/\n\nvoid CurvatureFlow::set_delta(double delta)\n{\n\tthis->dt = delta;\n}\n\n/*!\n*\t@returns Current value of delta parameter (used per timestep).\n*/\n\ndouble CurvatureFlow::get_delta()\n{\n\treturn(dt);\n}\n\n/*!\n*\tSets current value for the number of steps the algorithm is supposed to\n*\tperform.\n*\n*\t@param num_steps New value for the number of steps\n*/\n\nvoid CurvatureFlow::set_steps(size_t num_steps)\n{\n\tthis->num_steps = num_steps;\n}\n\n/*!\n*\t@returns Current number of steps the algorithm performs when being\n*\tapplied to a mesh.\n*/\n\nsize_t CurvatureFlow::get_steps()\n{\n\treturn(num_steps);\n}\n\n} // end of namespace \"psalm\"\n", "meta": {"hexsha": "b0a763873969e32e20d78fbc9a7e8f968aed1491", "size": 5599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FairingAlgorithms/CurvatureFlow.cpp", "max_stars_repo_name": "Pseudomanifold/psalm", "max_stars_repo_head_hexsha": "b9c3bc83950efb6efab8bb4775bf0421bee474d3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-07-21T14:53:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T09:12:54.000Z", "max_issues_repo_path": "FairingAlgorithms/CurvatureFlow.cpp", "max_issues_repo_name": "Pseudomanifold/psalm", "max_issues_repo_head_hexsha": "b9c3bc83950efb6efab8bb4775bf0421bee474d3", "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": "FairingAlgorithms/CurvatureFlow.cpp", "max_forks_repo_name": "Pseudomanifold/psalm", "max_forks_repo_head_hexsha": "b9c3bc83950efb6efab8bb4775bf0421bee474d3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-08T01:25:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-29T17:37:29.000Z", "avg_line_length": 25.45, "max_line_length": 109, "alphanum_fraction": 0.6920878728, "num_tokens": 1561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6241502157141354}}
{"text": "#include <PCP/Common/Option.h>\n#include <PCP/Common/Log.h>\n#include <PCP/Common/Progress.h>\n#include <PCP/Common/Colors.h>\n\n#include <PCP/Geometry/Geometry.h>\n#include <PCP/Geometry/Loader.h>\n\n#include <PCP/SpacePartitioning/KdTree.h>\n\n#include <Eigen/Eigenvalues>\n\n#include <Ponca/Fitting>\n\nusing namespace pcp;\n\nusing WeightKernel = Ponca::SmoothWeightKernel<Scalar>;\nusing WeightFunc   = Ponca::DistWeightFunc<ConstPoint, WeightKernel>;\nusing SphereFit    = Ponca::Basket<ConstPoint, WeightFunc, Ponca::OrientedSphereFit,\n                                                           Ponca::OrientedSphereScaleSpaceDer,\n                                                           Ponca::GLSParam,\n                                                           Ponca::GLSDer,\n                                                           Ponca::GLSGeomVar>;\n\nvoid colorize_and_save(Geometry& g, const std::vector<Scalar>& feature, const std::string& name, const std::string& path);\n\nint main(int argc, char *argv[])\n{\n    Option opt(argc, argv);\n    const String in_input    = opt.get_string(\"input\",  \"i\").set_required();\n    const String in_output   = opt.get_string(\"output\", \"o\").set_default(\".\");\n    const Scalar in_scale    = opt.get_float( \"scale\"      ).set_default(0.01);\n\n    bool ok = opt.ok();\n    if(!ok) return 1;\n    info() << opt;\n\n    Geometry g;\n    ok = Loader::Load(in_input, g);\n    if(!ok) return 1;\n    PCP_ASSERT(g.has_normals());\n    const int point_count = g.size();\n\n    g.build_kdtree();\n\n    const auto aabb = g.aabb();\n    const auto aabb_diag = aabb.diagonal().norm();\n    const auto radius = in_scale * aabb_diag;\n\n    auto prog = Progress(point_count);\n\n    std::vector<Scalar> feature_uc(point_count);\n    std::vector<Scalar> feature_ul(point_count);\n    std::vector<Scalar> feature_uq(point_count);\n    std::vector<Scalar> feature_gv(point_count);\n\n    #pragma omp parallel for\n    for(int i=0; i<point_count; ++i)\n    {\n        SphereFit fit;\n        fit.setWeightFunc(WeightFunc(radius));\n        fit.init(g[i]);\n        for(int j : g.kdtree().range_neighbors(i, radius))\n        {\n            fit.addNeighbor(g.at(j));\n        }\n\n        const auto status = fit.finalize();\n\n        if(status == Ponca::FIT_RESULT::STABLE)\n        {\n            feature_uc[i] = fit.m_uc / radius;\n            feature_ul[i] = 1 - fit.m_ul.norm();\n            feature_uq[i] = fit.m_uq * radius;\n            feature_gv[i] = std::sqrt(fit.geomVar());\n        }\n        else\n        {\n            warning() << \"Unstable fit at point \" << i;\n        }\n\n        ++prog;\n    }\n\n    g.request_colors();\n\n    colorize_and_save(g, feature_uc, \"uc\", in_output);\n    colorize_and_save(g, feature_ul, \"ul\", in_output);\n    colorize_and_save(g, feature_uq, \"uq\", in_output);\n    colorize_and_save(g, feature_gv, \"gv\", in_output);\n\n    return 0;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nvoid colorize_and_save(Geometry& g, const std::vector<Scalar>& feature, const std::string& name, const std::string& path)\n{\n    const int point_count = g.size();\n\n    const auto colormap = BiColormap::Jet();\n\n    limited_priority_queue<Scalar, std::greater<Scalar>> q(0.10 * point_count);\n\n    Scalar min = +std::numeric_limits<Scalar>::max();\n    Scalar max = -std::numeric_limits<Scalar>::max();\n    Scalar mean = 0;\n    for(int i=0; i<point_count; ++i)\n    {\n        q.push(std::abs(feature[i]));\n        min = std::min(min, feature[i]);\n        max = std::max(max, feature[i]);\n        mean += feature[i];\n    }\n    mean /= point_count;\n\n    const Scalar limit = q.bottom();\n\n    info() << name << \" in (\" << min << \",\" << max << \") mean=\" << mean << \" limit=\" << limit;\n\n    #pragma omp parallel for\n    for(int i=0; i<point_count; ++i)\n    {\n        g.color(i) = colormap(feature[i], limit);\n    }\n\n    Loader::Save(path+\"/\"+name+\".ply\", g, false);\n}\n\n", "meta": {"hexsha": "9853df0a69c9c6a5d14bcf3488dff8a6fa9ec2b5", "size": 3886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "figures/app/Figures/ComputeGeometricFeatures.cpp", "max_stars_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_stars_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T18:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T12:42:52.000Z", "max_issues_repo_path": "figures/app/Figures/ComputeGeometricFeatures.cpp", "max_issues_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_issues_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-12T08:51:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T09:38:17.000Z", "max_forks_repo_path": "figures/app/Figures/ComputeGeometricFeatures.cpp", "max_forks_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_forks_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T08:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T11:40:21.000Z", "avg_line_length": 29.8923076923, "max_line_length": 122, "alphanum_fraction": 0.5671641791, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6240982439590834}}
{"text": "//  Boost GCD & LCM common_factor.hpp test program  --------------------------//\r\n\r\n//  (C) Copyright Daryle Walker 2001.  Permission to copy, use, modify, sell\r\n//  and distribute this software is granted provided this copyright\r\n//  notice appears in all copies.  This software is provided \"as is\" without\r\n//  express or implied warranty, and with no claim as to its suitability for\r\n//  any purpose.\r\n\r\n//  See http://www.boost.org for most recent version including documentation.\r\n\r\n//  Revision History\r\n//  07 Nov 2001  Initial version (Daryle Walker)\r\n\r\n#define  BOOST_INCLUDE_MAIN\r\n\r\n#include <boost/config.hpp>              // for BOOST_MSVC\r\n#include <boost/cstdlib.hpp>             // for boost::exit_success\r\n#include <boost/math/common_factor.hpp>  // for boost::math::gcd, etc.\r\n#include <boost/test/test_tools.hpp>     // for main, BOOST_TEST\r\n\r\n#include <iostream>  // for std::cout (std::endl indirectly)\r\n\r\n\r\n// Control to determine what kind of built-in integers are used\r\n#ifndef CONTROL_INT_TYPE\r\n#define CONTROL_INT_TYPE  int\r\n#endif\r\n\r\n\r\n// Main testing function\r\nint\r\ntest_main\r\n(\r\n    int         ,   // \"argc\" is unused\r\n    char *      []  // \"argv\" is unused\r\n)\r\n{    \r\n    using std::cout;\r\n    using std::endl;\r\n\r\n#ifndef BOOST_MSVC\r\n    using boost::math::gcd;\r\n    using boost::math::static_gcd;\r\n    using boost::math::lcm;\r\n    using boost::math::static_lcm;\r\n#else\r\n    using namespace boost::math;\r\n#endif\r\n\r\n    typedef CONTROL_INT_TYPE  int_type;\r\n    typedef unsigned CONTROL_INT_TYPE uint_type;\r\n\r\n    // GCD tests\r\n    cout << \"Doing tests on gcd.\" << endl;\r\n\r\n    BOOST_TEST( gcd<int_type>(  1,  -1) ==  1 );\r\n    BOOST_TEST( gcd<int_type>( -1,   1) ==  1 );\r\n    BOOST_TEST( gcd<int_type>(  1,   1) ==  1 );\r\n    BOOST_TEST( gcd<int_type>( -1,  -1) ==  1 );\r\n    BOOST_TEST( gcd<int_type>(  0,   0) ==  0 );\r\n    BOOST_TEST( gcd<int_type>(  7,   0) ==  7 );\r\n    BOOST_TEST( gcd<int_type>(  0,   9) ==  9 );\r\n    BOOST_TEST( gcd<int_type>( -7,   0) ==  7 );\r\n    BOOST_TEST( gcd<int_type>(  0,  -9) ==  9 );\r\n    BOOST_TEST( gcd<int_type>( 42,  30) ==  6 );\r\n    BOOST_TEST( gcd<int_type>(  6,  -9) ==  3 );\r\n    BOOST_TEST( gcd<int_type>(-10, -10) == 10 );\r\n    BOOST_TEST( gcd<int_type>(-25, -10) ==  5 );\r\n    BOOST_TEST( gcd<int_type>(  3,   7) ==  1 );\r\n    BOOST_TEST( gcd<int_type>(  8,   9) ==  1 );\r\n    BOOST_TEST( gcd<int_type>(  7,  49) ==  7 );\r\n\r\n    // GCD tests\r\n    cout << \"Doing tests on unsigned-gcd.\" << endl;\r\n\r\n    BOOST_TEST( gcd<uint_type>(  1u,   1u) ==  1u );\r\n    BOOST_TEST( gcd<uint_type>(  0u,   0u) ==  0u );\r\n    BOOST_TEST( gcd<uint_type>(  7u,   0u) ==  7u );\r\n    BOOST_TEST( gcd<uint_type>(  0u,   9u) ==  9u );\r\n    BOOST_TEST( gcd<uint_type>( 42u,  30u) ==  6u );\r\n    BOOST_TEST( gcd<uint_type>(  3u,   7u) ==  1u );\r\n    BOOST_TEST( gcd<uint_type>(  8u,   9u) ==  1u );\r\n    BOOST_TEST( gcd<uint_type>(  7u,  49u) ==  7u );\r\n\r\n    cout << \"Doing tests on static_gcd.\" << endl;\r\n\r\n    BOOST_TEST( (static_gcd< 1,  1>::value) == 1 );\r\n    BOOST_TEST( (static_gcd< 0,  0>::value) == 0 );\r\n    BOOST_TEST( (static_gcd< 7,  0>::value) == 7 );\r\n    BOOST_TEST( (static_gcd< 0,  9>::value) == 9 );\r\n    BOOST_TEST( (static_gcd<42, 30>::value) == 6 );\r\n    BOOST_TEST( (static_gcd< 3,  7>::value) == 1 );\r\n    BOOST_TEST( (static_gcd< 8,  9>::value) == 1 );\r\n    BOOST_TEST( (static_gcd< 7, 49>::value) == 7 );\r\n\r\n    // LCM tests\r\n    cout << \"Doing tests on lcm.\" << endl;\r\n\r\n    BOOST_TEST( lcm<int_type>(  1,  -1) ==  1 );\r\n    BOOST_TEST( lcm<int_type>( -1,   1) ==  1 );\r\n    BOOST_TEST( lcm<int_type>(  1,   1) ==  1 );\r\n    BOOST_TEST( lcm<int_type>( -1,  -1) ==  1 );\r\n    BOOST_TEST( lcm<int_type>(  0,   0) ==  0 );\r\n    BOOST_TEST( lcm<int_type>(  6,   0) ==  0 );\r\n    BOOST_TEST( lcm<int_type>(  0,   7) ==  0 );\r\n    BOOST_TEST( lcm<int_type>( -5,   0) ==  0 );\r\n    BOOST_TEST( lcm<int_type>(  0,  -4) ==  0 );\r\n    BOOST_TEST( lcm<int_type>( 18,  30) == 90 );\r\n    BOOST_TEST( lcm<int_type>( -6,   9) == 18 );\r\n    BOOST_TEST( lcm<int_type>(-10, -10) == 10 );\r\n    BOOST_TEST( lcm<int_type>( 25, -10) == 50 );\r\n    BOOST_TEST( lcm<int_type>(  3,   7) == 21 );\r\n    BOOST_TEST( lcm<int_type>(  8,   9) == 72 );\r\n    BOOST_TEST( lcm<int_type>(  7,  49) == 49 );\r\n\r\n    cout << \"Doing tests on unsigned-lcm.\" << endl;\r\n\r\n    BOOST_TEST( lcm<uint_type>(  1u,   1u) ==  1u );\r\n    BOOST_TEST( lcm<uint_type>(  0u,   0u) ==  0u );\r\n    BOOST_TEST( lcm<uint_type>(  6u,   0u) ==  0u );\r\n    BOOST_TEST( lcm<uint_type>(  0u,   7u) ==  0u );\r\n    BOOST_TEST( lcm<uint_type>( 18u,  30u) == 90u );\r\n    BOOST_TEST( lcm<uint_type>(  3u,   7u) == 21u );\r\n    BOOST_TEST( lcm<uint_type>(  8u,   9u) == 72u );\r\n    BOOST_TEST( lcm<uint_type>(  7u,  49u) == 49u );\r\n\r\n    cout << \"Doing tests on static_lcm.\" << endl;\r\n\r\n    BOOST_TEST( (static_lcm< 1,  1>::value) ==  1 );\r\n    BOOST_TEST( (static_lcm< 0,  0>::value) ==  0 );\r\n    BOOST_TEST( (static_lcm< 6,  0>::value) ==  0 );\r\n    BOOST_TEST( (static_lcm< 0,  7>::value) ==  0 );\r\n    BOOST_TEST( (static_lcm<18, 30>::value) == 90 );\r\n    BOOST_TEST( (static_lcm< 3,  7>::value) == 21 );\r\n    BOOST_TEST( (static_lcm< 8,  9>::value) == 72 );\r\n    BOOST_TEST( (static_lcm< 7, 49>::value) == 49 );\r\n\r\n    return boost::exit_success;\r\n}\r\n", "meta": {"hexsha": "c7fb01f8ca6d2feea31f4796998af99843ed354b", "size": 5269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/math/test/common_factor_test.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/math/test/common_factor_test.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/math/test/common_factor_test.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6357142857, "max_line_length": 81, "alphanum_fraction": 0.5564623268, "num_tokens": 1847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.624097121276482}}
{"text": "///\\author Ethan Knox\n///\\date 10/6/2020.\n\n#ifndef PURDUE_PHYS_580_POINCARE\n#define PURDUE_PHYS_580_POINCARE\n#define _USE_MATH_DEFINES\n#endif //PURDUE_PHYS_580_POINCARE\n\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <limits>\n#include <iomanip>\n#include <functional>\n\n#include <boost/program_options.hpp>\n#include <boost/numeric/odeint.hpp>\n\nusing namespace std;\nusing namespace std::placeholders;\nnamespace opt = boost::program_options;\n\ntypedef std::vector<double> state_t;\ntypedef boost::numeric::odeint::runge_kutta4<state_t> rk4;\n\nint main(int argc, const char* argv[])\n{\n    double A, x_0, dx_0, Q, wd, sec_freq;\n    long n_pnts, n_wait, pnt_density;\n\n    opt::options_description params(\"Simulation Parameters\");\n    params.add_options()\n            (\"help,h\", \"Show Usage\")\n            (     \"n_wait\",opt::value<long>  (     &n_wait)->default_value(    100), \"Number of Cycles Ignored For Transients To Disappear\")\n            (     \"n_pnts\",opt::value<long>  (     &n_pnts)->default_value(   10000), \"Total Number of Cycles\")\n            (\"pnt_density\",opt::value<long>  (&pnt_density)->default_value(   1000), \"Solution Accuracy (dt)\")\n            (          \"A\",opt::value<double>(          &A)->default_value(    1.35), \"Amplitude\")\n            (        \"x_0\",opt::value<double>(        &x_0)->default_value(    0.2), \"Initial Angle\")\n            (        \"v_0\",opt::value<double>(       &dx_0)->default_value(    0.0), \"Initial Angular Frequency\")\n            (          \"Q\",opt::value<double>(          &Q)->default_value(    0.5), \"Quality Factor\")\n            (        \"w_d\",opt::value<double>(         &wd)->default_value(2.0/3.0), \"Driving Frequency\")\n            (   \"sec_freq\",opt::value<double>(   &sec_freq)->default_value(2.0/3.0), \"Sectioning Frequency\");\n\n    opt::variables_map vm;\n    opt::store(opt::parse_command_line(argc, argv, params), vm);\n\n    // Output help message if requested from the commandline\n    if (vm.count(\"help\")) {\n        std::cout << params << std::endl;\n        return 1;\n    } // Necessary to retrieve the values from 'program_options'\n    else {\n        opt::notify(vm);\n    }\n\n    // Constants\n    const long double dt = 2.0 * M_PI / (sec_freq * pnt_density);\n    const long double t_i = 2.0 * M_PI / sec_freq;\n    const long double t_f = (2.0 * M_PI * n_pnts) / sec_freq;\n    const long double N = (n_pnts - 1) * pnt_density;\n\n    // Initial Condition\n    state_t x{x_0, dx_0};\n    state_t dx_dt(2);\n\n    // Data Series\n    state_t x_series;\n    state_t dx_series;\n    state_t t_series;\n    x_series.reserve(N);\n    dx_series.reserve(N);\n    t_series.reserve(N);\n\n    // Data Recorder\n    auto observer = [&](const state_t& x, const double t) {\n        x_series.push_back(x.front());\n        dx_series.push_back(x.back());\n        t_series.push_back(t);\n    };\n\n    cout << \"Running Simulation...\\n\";\n    ofstream file(\"../data/poincare.dat\");\n    file << \"# t \\\\theta \\\\frac{d\\\\theta}{dt}\\n\";\n    file << setprecision(numeric_limits<long double>::digits10 + 1);\n\n    // ODE System\n    std::function<void(const state_t&, state_t&, double)> sys = [&](const state_t& x, state_t& dx_dt, const double t) {\n        dx_dt.front() = x.back();\n        dx_dt.back() = -sin(x.front()) - Q * x.back() + A * sin(wd * t);\n    };\n\n    // Integrate\n    boost::numeric::odeint::integrate_n_steps(rk4(), sys, x, t_i, dt, N, observer);\n\n    // Restrict the domain to [-pi, pi]\n    for(auto &theta : x_series){\n        theta = fmod(theta + M_PI, 2.0 * M_PI) - M_PI;\n    }\n\n    // Write data to file\n    for(size_t i=0; i<x_series.size(); i++){\n        if((i > pnt_density) && (i / pnt_density > n_wait) && (i % pnt_density == 0)){\n            file << std::scientific << t_series.at(i) << \" \" << x_series.at(i) << \" \" << dx_series.at(i) << \"\\n\";\n        }\n    }\n\n    cout << \"Done.\\n\\n\";\n    return 0;\n}", "meta": {"hexsha": "ecf35b61ff9436f8c54e938553fa88c7a74ae4dd", "size": 3892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homework/HW2/poincare/main.cpp", "max_stars_repo_name": "ethank5149/PurduePHYS580", "max_stars_repo_head_hexsha": "54d5d75737aa0d31ed723dd0e79c98dc01e71ca7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Homework/HW2/poincare/main.cpp", "max_issues_repo_name": "ethank5149/PurduePHYS580", "max_issues_repo_head_hexsha": "54d5d75737aa0d31ed723dd0e79c98dc01e71ca7", "max_issues_repo_licenses": ["MIT"], "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/HW2/poincare/main.cpp", "max_forks_repo_name": "ethank5149/PurduePHYS580", "max_forks_repo_head_hexsha": "54d5d75737aa0d31ed723dd0e79c98dc01e71ca7", "max_forks_repo_licenses": ["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.0630630631, "max_line_length": 140, "alphanum_fraction": 0.595323741, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6240634228886915}}
{"text": "//            Copyright Daniel Trebbien 2010.\n// Distributed under the Boost Software License, Version 1.0.\n//   (See accompanying file LICENSE_1_0.txt or the copy at\n//         http://www.boost.org/LICENSE_1_0.txt)\n\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <vector>\n#include <string>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/exception.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/read_dimacs.hpp>\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n#include <boost/graph/property_maps/constant_property_map.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/tuple/tuple.hpp>\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int> > undirected_graph;\ntypedef boost::property_map<undirected_graph, boost::edge_weight_t>::type weight_map_type;\ntypedef boost::property_traits<weight_map_type>::value_type weight_type;\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> undirected_unweighted_graph;\n\nstd::string test_dir;\n\nboost::unit_test::test_suite* init_unit_test_suite( int argc, char* argv[] ) {\n  if (argc != 2) {\n    std::cerr << \"Usage: \" << argv[0] << \" path-to-libs-graph-test\" << std::endl;\n    throw boost::unit_test::framework::setup_error(\"Invalid command line arguments\");\n  }\n  test_dir = argv[1];\n  return 0;\n}\n\nstruct edge_t\n{\n  unsigned long first;\n  unsigned long second;\n};\n\n// the example from Stoer & Wagner (1997)\nBOOST_AUTO_TEST_CASE(test0)\n{\n  typedef boost::graph_traits<undirected_graph>::vertex_descriptor vertex_descriptor;\n  typedef boost::graph_traits<undirected_graph>::edge_descriptor edge_descriptor;\n  \n  edge_t edges[] = {{0, 1}, {1, 2}, {2, 3},\n    {0, 4}, {1, 4}, {1, 5}, {2, 6}, {3, 6}, {3, 7}, {4, 5}, {5, 6}, {6, 7}};\n  weight_type ws[] = {2, 3, 4, 3, 2, 2, 2, 2, 2, 3, 1, 3};\n  undirected_graph g(edges, edges + 12, ws, 8, 12);\n  \n  weight_map_type weights = get(boost::edge_weight, g);\n  std::map<int, bool> parity;\n  boost::associative_property_map<std::map<int, bool> > parities(parity);\n  int w = boost::stoer_wagner_min_cut(g, weights, boost::parity_map(parities));\n  BOOST_CHECK_EQUAL(w, 4);\n  const bool parity0 = get(parities, 0);\n  BOOST_CHECK_EQUAL(parity0, get(parities, 1));\n  BOOST_CHECK_EQUAL(parity0, get(parities, 4));\n  BOOST_CHECK_EQUAL(parity0, get(parities, 5));\n  const bool parity2 = get(parities, 2);\n  BOOST_CHECK_NE(parity0, parity2);\n  BOOST_CHECK_EQUAL(parity2, get(parities, 3));\n  BOOST_CHECK_EQUAL(parity2, get(parities, 6));\n  BOOST_CHECK_EQUAL(parity2, get(parities, 7));\n}\n\nBOOST_AUTO_TEST_CASE(test1)\n{\n  { // if only one vertex, can't run `boost::stoer_wagner_min_cut`\n    typedef boost::graph_traits<undirected_graph>::vertex_descriptor vertex_descriptor;\n    typedef boost::graph_traits<undirected_graph>::edge_descriptor edge_descriptor;\n  \n    undirected_graph g;\n    add_vertex(g);\n    \n    BOOST_CHECK_THROW(boost::stoer_wagner_min_cut(g, get(boost::edge_weight, g)), boost::bad_graph);\n  }{ // three vertices with one multi-edge\n    typedef boost::graph_traits<undirected_graph>::vertex_descriptor vertex_descriptor;\n    typedef boost::graph_traits<undirected_graph>::edge_descriptor edge_descriptor;\n    \n    edge_t edges[] = {{0, 1}, {1, 2}, {1, 2}, {2, 0}};\n    weight_type ws[] = {3, 1, 1, 1};\n    undirected_graph g(edges, edges + 4, ws, 3, 4);\n    \n    weight_map_type weights = get(boost::edge_weight, g);\n    std::map<int, bool> parity;\n    boost::associative_property_map<std::map<int, bool> > parities(parity);\n    std::map<vertex_descriptor, vertex_descriptor> assignment;\n    boost::associative_property_map<std::map<vertex_descriptor, vertex_descriptor> > assignments(assignment);\n    int w = boost::stoer_wagner_min_cut(g, weights, boost::parity_map(parities).vertex_assignment_map(assignments));\n    BOOST_CHECK_EQUAL(w, 3);\n    const bool parity2 = get(parities, 2),\n      parity0 = get(parities, 0);\n    BOOST_CHECK_NE(parity2, parity0);\n    BOOST_CHECK_EQUAL(parity0, get(parities, 1));\n  }\n}\n\n// example by Daniel Trebbien\nBOOST_AUTO_TEST_CASE(test2)\n{\n  typedef boost::graph_traits<undirected_graph>::vertex_descriptor vertex_descriptor;\n  typedef boost::graph_traits<undirected_graph>::edge_descriptor edge_descriptor;\n  \n  edge_t edges[] = {{5, 2}, {0, 6}, {5, 6},\n    {3, 1}, {0, 1}, {6, 3}, {4, 6}, {2, 4}, {5, 3}};\n  weight_type ws[] = {1, 3, 4, 6, 4, 1, 2, 5, 2};\n  undirected_graph g(edges, edges + 9, ws, 7, 9);\n  \n  std::map<int, bool> parity;\n  boost::associative_property_map<std::map<int, bool> > parities(parity);\n  int w = boost::stoer_wagner_min_cut(g, get(boost::edge_weight, g), boost::parity_map(parities));\n  BOOST_CHECK_EQUAL(w, 3);\n  const bool parity2 = get(parities, 2);\n  BOOST_CHECK_EQUAL(parity2, get(parities, 4));\n  const bool parity5 = get(parities, 5);\n  BOOST_CHECK_NE(parity2, parity5);\n  BOOST_CHECK_EQUAL(parity5, get(parities, 3));\n  BOOST_CHECK_EQUAL(parity5, get(parities, 6));\n  BOOST_CHECK_EQUAL(parity5, get(parities, 1));\n  BOOST_CHECK_EQUAL(parity5, get(parities, 0));\n}\n\n// example by Daniel Trebbien\nBOOST_AUTO_TEST_CASE(test3)\n{\n  typedef boost::graph_traits<undirected_graph>::vertex_descriptor vertex_descriptor;\n  typedef boost::graph_traits<undirected_graph>::edge_descriptor edge_descriptor;\n  \n  edge_t edges[] = {{3, 4}, {3, 6}, {3, 5}, {0, 4}, {0, 1}, {0, 6}, {0, 7},\n    {0, 5}, {0, 2}, {4, 1}, {1, 6}, {1, 5}, {6, 7}, {7, 5}, {5, 2}, {3, 4}};\n  weight_type ws[] = {0, 3, 1, 3, 1, 2, 6, 1, 8, 1, 1, 80, 2, 1, 1, 4};\n  undirected_graph g(edges, edges + 16, ws, 8, 16);\n  \n  weight_map_type weights = get(boost::edge_weight, g);\n  std::map<int, bool> parity;\n  boost::associative_property_map<std::map<int, bool> > parities(parity);\n  int w = boost::stoer_wagner_min_cut(g, weights, boost::parity_map(parities));\n  BOOST_CHECK_EQUAL(w, 7);\n  const bool parity1 = get(parities, 1);\n  BOOST_CHECK_EQUAL(parity1, get(parities, 5));\n  const bool parity0 = get(parities, 0);\n  BOOST_CHECK_NE(parity1, parity0);\n  BOOST_CHECK_EQUAL(parity0, get(parities, 2));\n  BOOST_CHECK_EQUAL(parity0, get(parities, 3));\n  BOOST_CHECK_EQUAL(parity0, get(parities, 4));\n  BOOST_CHECK_EQUAL(parity0, get(parities, 6));\n  BOOST_CHECK_EQUAL(parity0, get(parities, 7));\n}\n\nBOOST_AUTO_TEST_CASE(test4)\n{\n  typedef boost::graph_traits<undirected_unweighted_graph>::vertex_descriptor vertex_descriptor;\n  typedef boost::graph_traits<undirected_unweighted_graph>::edge_descriptor edge_descriptor;\n  \n  edge_t edges[] = {{0, 1}, {1, 2}, {2, 3},\n    {0, 4}, {1, 4}, {1, 5}, {2, 6}, {3, 6}, {3, 7}, {4, 5}, {5, 6}, {6, 7},\n    {0, 4}, {6, 7}};\n  undirected_unweighted_graph g(edges, edges + 14, 8);\n  \n  std::map<vertex_descriptor, bool> parity;\n  boost::associative_property_map<std::map<vertex_descriptor, bool> > parities(parity);\n  std::map<vertex_descriptor, vertex_descriptor> assignment;\n  boost::associative_property_map<std::map<vertex_descriptor, vertex_descriptor> > assignments(assignment);\n  int w = boost::stoer_wagner_min_cut(g, boost::make_constant_property<edge_descriptor>(weight_type(1)), boost::vertex_assignment_map(assignments).parity_map(parities));\n  BOOST_CHECK_EQUAL(w, 2);\n  const bool parity0 = get(parities, 0);\n  BOOST_CHECK_EQUAL(parity0, get(parities, 1));\n  BOOST_CHECK_EQUAL(parity0, get(parities, 4));\n  BOOST_CHECK_EQUAL(parity0, get(parities, 5));\n  const bool parity2 = get(parities, 2);\n  BOOST_CHECK_NE(parity0, parity2);\n  BOOST_CHECK_EQUAL(parity2, get(parities, 3));\n  BOOST_CHECK_EQUAL(parity2, get(parities, 6));\n  BOOST_CHECK_EQUAL(parity2, get(parities, 7));\n}\n\n// The input for the `test_prgen` family of tests comes from a program, named\n// `prgen`, that comes with a package of min-cut solvers by Chandra Chekuri,\n// Andrew Goldberg, David Karger, Matthew Levine, and Cliff Stein. `prgen` was\n// used to generate input graphs and the solvers were used to verify the return\n// value of `boost::stoer_wagner_min_cut` on the input graphs.\n//\n// http://www.columbia.edu/~cs2035/code.html\n//\n// Note that it is somewhat more difficult to verify the parities because\n// \"`prgen` graphs\" often have several min-cuts. This is why only the cut\n// weight of the min-cut is verified.\n\n// 3 min-cuts\nBOOST_AUTO_TEST_CASE(test_prgen_20_70_2)\n{\n  typedef boost::graph_traits<undirected_graph>::vertex_descriptor vertex_descriptor;\n  typedef boost::graph_traits<undirected_graph>::edge_descriptor edge_descriptor;\n  \n  std::ifstream ifs((test_dir + \"/prgen_input_graphs/prgen_20_70_2.net\").c_str());\n  undirected_graph g;\n  boost::read_dimacs_min_cut(g, get(boost::edge_weight, g), boost::dummy_property_map(), ifs);\n  \n  std::map<vertex_descriptor, std::size_t> component;\n  boost::associative_property_map<std::map<vertex_descriptor, std::size_t> > components(component);\n  BOOST_CHECK_EQUAL(boost::connected_components(g, components), 1U); // verify the connectedness assumption\n  \n  BOOST_AUTO(distances, (boost::make_shared_array_property_map(num_vertices(g), weight_type(0), get(boost::vertex_index, g))));\n  typedef std::vector<vertex_descriptor>::size_type index_in_heap_type;\n  BOOST_AUTO(indicesInHeap, (boost::make_shared_array_property_map(num_vertices(g), index_in_heap_type(-1), get(boost::vertex_index, g))));\n  boost::d_ary_heap_indirect<vertex_descriptor, 22, BOOST_TYPEOF(indicesInHeap), BOOST_TYPEOF(distances), std::greater<weight_type> > pq(distances, indicesInHeap);\n  \n  int w = boost::stoer_wagner_min_cut(g, get(boost::edge_weight, g), boost::max_priority_queue(pq));\n  BOOST_CHECK_EQUAL(w, 3407);\n}\n\n// 7 min-cuts\nBOOST_AUTO_TEST_CASE(test_prgen_50_40_2)\n{\n  typedef boost::graph_traits<undirected_graph>::vertex_descriptor vertex_descriptor;\n  typedef boost::graph_traits<undirected_graph>::edge_descriptor edge_descriptor;\n  \n  std::ifstream ifs((test_dir + \"/prgen_input_graphs/prgen_50_40_2.net\").c_str());\n  undirected_graph g;\n  boost::read_dimacs_min_cut(g, get(boost::edge_weight, g), boost::dummy_property_map(), ifs);\n  \n  std::map<vertex_descriptor, std::size_t> component;\n  boost::associative_property_map<std::map<vertex_descriptor, std::size_t> > components(component);\n  BOOST_CHECK_EQUAL(boost::connected_components(g, components), 1U); // verify the connectedness assumption\n  \n  int w = boost::stoer_wagner_min_cut(g, get(boost::edge_weight, g));\n  BOOST_CHECK_EQUAL(w, 10056);\n}\n\n// 6 min-cuts\nBOOST_AUTO_TEST_CASE(test_prgen_50_70_2)\n{\n  typedef boost::graph_traits<undirected_graph>::vertex_descriptor vertex_descriptor;\n  typedef boost::graph_traits<undirected_graph>::edge_descriptor edge_descriptor;\n  \n  std::ifstream ifs((test_dir + \"/prgen_input_graphs/prgen_50_70_2.net\").c_str());\n  undirected_graph g;\n  boost::read_dimacs_min_cut(g, get(boost::edge_weight, g), boost::dummy_property_map(), ifs);\n  \n  std::map<vertex_descriptor, std::size_t> component;\n  boost::associative_property_map<std::map<vertex_descriptor, std::size_t> > components(component);\n  BOOST_CHECK_EQUAL(boost::connected_components(g, components), 1U); // verify the connectedness assumption\n  \n  int w = boost::stoer_wagner_min_cut(g, get(boost::edge_weight, g));\n  BOOST_CHECK_EQUAL(w, 21755);\n}\n", "meta": {"hexsha": "112bf495c7103a56b67e897b497bec5db2abdb51", "size": 11258, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/test/stoer_wagner_test.cpp", "max_stars_repo_name": "AishwaryaDoosa/Boost1.49", "max_stars_repo_head_hexsha": "67bdb3b36d72dec7414a62f3b050162e608ea266", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-04T17:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-04T17:43:16.000Z", "max_issues_repo_path": "libs/graph/test/stoer_wagner_test.cpp", "max_issues_repo_name": "ksundberg/boost-svn", "max_issues_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/graph/test/stoer_wagner_test.cpp", "max_forks_repo_name": "ksundberg/boost-svn", "max_forks_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4980237154, "max_line_length": 169, "alphanum_fraction": 0.7305915793, "num_tokens": 3283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6240634097811076}}
{"text": "//EuropeanOption.hpp\n//\n//Modification date: 6/17/15\n\n#ifndef EuropeanOption_hpp\n#define EuropeanOption_hpp\n\n#include \"Option.hpp\"\n#include \"GlobalFunctions.hpp\"\n#include <boost/math/distributions/normal.hpp>\n#include <vector>\n\n\nclass EuropeanOption : public Option\n{\nprotected:\n\tdouble T;\t\t\t//time till maturity\n\t\npublic:\n\t//Constructors\n\tEuropeanOption() : Option(), T(0.25)\t{\t}\n\tEuropeanOption(double new_S, double new_K, double new_T, double new_r, double new_sig) : Option(new_S,new_K,new_r,new_sig), T(new_T)\t{\t}\t\t//default b=r Black and Scholes stock option model (1973)\n\tEuropeanOption(double new_S, double new_K, double new_T, double new_r, double new_sig, double new_b) : Option(new_S, new_K, new_r, new_sig, new_b), T(new_T)\t{\t}\n\tEuropeanOption(const EuropeanOption& source) : Option(source), T(source.T)\t{\t}\n\n\t//Destructor\n\tvirtual ~EuropeanOption() {}\n\n\t//Operator overloads\n\tEuropeanOption& operator = (const EuropeanOption& source);\n\n\t//Getters\n\tdouble get_T() { return T; }\n\t\n\tvirtual void Print()const = 0;\n\n\t//Setters\t\n\tvoid set_T(double new_T) { T = new_T; }\n\t\n\t//Pricers (pure virtual functions)\t\n\tvirtual double Price()const = 0;\n\tvirtual double PricePCP(double PC)const = 0;\n\tvirtual double Price_S(double S1) = 0;\n\tvirtual double Price_K(double K1) = 0;\n\tvirtual double Price_T(double T1) = 0;\n\tvirtual double Price_r(double r1) = 0;\n\tvirtual double Price_sig(double sig1) = 0;\n\tvirtual double Price_b(double b1) = 0;\n\n\t//Checkers\n\tbool PutCallParity(double C, double P)const;\n\n\t//Greeks\n\tvirtual double Delta() const = 0;\n\tdouble Gamma() { return GammaGF(S, K, T, r, sig, b); }\t\t//Gamma is the same for put and call options\n\tdouble Gamma(double h) { return GammaGF(S, h, K, T, r, sig, b); }\n\tdouble Vega() { return VegaGF(S, K, T, r, sig, b); }\t\t//Vega is the same for put and call options, no need to define it in derived classes\n\tvirtual double Theta() const = 0;\n\tvirtual double Rho() const = 0;\n\n\n\t\t\n};\n\nclass EuropeanCallOption : public EuropeanOption\n{\npublic:\n\t//Constructors\n\tEuropeanCallOption() : EuropeanOption() {}\n\tEuropeanCallOption(double new_S, double new_K, double new_T, double new_r, double new_sig) : EuropeanOption(new_S, new_K, new_T, new_r, new_sig) {}\n\tEuropeanCallOption(double new_S, double new_K, double new_T, double new_r, double new_sig, double new_b) : EuropeanOption(new_S, new_K, new_T, new_r, new_sig, new_b) {}\n\tEuropeanCallOption(const EuropeanOption& source) : EuropeanOption(source) {}\n\n\t//Destructor\n\tvirtual ~EuropeanCallOption() {}\n\n\tEuropeanOption& operator = (const EuropeanOption& source);\n\n\tvoid Print()const;\n\n\t//Pricers\n\tdouble Price()const\t{\treturn CallPrice(S, K, T, r, sig, b);\t}\n\tdouble Price_S(double S1)\t{ return CallPrice(S1, K, T, r, sig, b); }\n\tdouble Price_K(double K1)\t{ return CallPrice(S, K1, T, r, sig, b); }\n\tdouble Price_T(double T1)\t{ return CallPrice(S, K, T1, r, sig, b); }\n\tdouble Price_r(double r1)\t{ return CallPrice(S, K, T, r1, sig, b); }\n\tdouble Price_sig(double sig1)\t{ return CallPrice(S, K, T, r, sig1, b); }\n\tdouble Price_b(double b1)\t{ return CallPrice(S, K, T, r, sig, b1); }\n\tdouble PricePCP(double P)const\t{ return CallPricePCP(P, S, K, T, r, b); }\n\t\n\t//Pricing function that returns vector. Used in combination with function pointer for better versatility\n\ttypedef double(EuropeanCallOption::*FunctionPointer)(double);\n\tstd::vector<double> Price(double LowerLimit, double UpperLimit, int Num, FunctionPointer Ptr );\n\t\n\t//Greeks\n\tdouble Delta()const { return CallDelta( S, K, T, r, sig, b); }\n\tdouble Delta_S(double S1) { return CallDelta(S1, K, T, r, sig, b); }\t\t//function to override spot price\n\tdouble Theta() const { return CallTheta(S, K, T, r, sig, b); }\n\tdouble Rho() const { return CallRho(S, K, T, r, sig, b); }\n\tdouble Delta(double h)const { return CallDelta(S, h, K, T, r, sig, b); }\n\t//double Gamma() { return GammaGF(S, K, T, r, sig, b); }\n\t//double Gamma(double h) { return GammaGF(S, h, K, T, r, sig, b); }\n\n};\n\nclass EuropeanPutOption : public EuropeanOption\n{\npublic:\n\t//Constructors\n\tEuropeanPutOption() : EuropeanOption() {}\n\tEuropeanPutOption(double new_S, double new_K, double new_T, double new_r, double new_sig) : EuropeanOption(new_S, new_K, new_T, new_r, new_sig) {}\n\tEuropeanPutOption(double new_S, double new_K, double new_T, double new_r, double new_sig, double new_b) : EuropeanOption(new_S, new_K, new_T, new_r, new_sig, new_b) {}\n\tEuropeanPutOption(const EuropeanOption& source) : EuropeanOption(source) {}\n\n\t//Destructor\n\tvirtual ~EuropeanPutOption() {}\n\n\tEuropeanOption& operator = (const EuropeanOption& source);\n\n\tvoid Print()const;\n\n\t//Pricers\n\tdouble Price()const\t\t{\treturn PutPrice(S, K, T, r, sig, b);\t}\n\tdouble PricePCP(double C)const\t\t{\treturn PutPricePCP(C, S, K, T, r, b);\t}\n\tdouble Price_S(double S1)\t{ return PutPrice(S1, K, T, r, sig, b); }\n\tdouble Price_K(double K1)\t{ return PutPrice(S, K1, T, r, sig, b); }\n\tdouble Price_T(double T1)\t{ return PutPrice(S, K, T1, r, sig, b); }\n\tdouble Price_r(double r1)\t{ return PutPrice(S, K, T, r1, sig, b); }\n\tdouble Price_sig(double sig1)\t{ return PutPrice(S, K, T, r, sig1, b); }\n\tdouble Price_b(double b1)\t{ return PutPrice(S, K, T, r, sig, b1); }\n\n\t//Pricing function that returns vector. Used in combination with function pointer for better versatility\n\ttypedef double(EuropeanPutOption::*FunctionPointer)(double);\n\tstd::vector<double> Price(double LowerLimit, double UpperLimit, int Num,const FunctionPointer Ptr);\n\n\t//Greeks\n\tdouble Delta()const { return PutDelta(S, K, T, r, sig, b); }\n\tdouble Delta_S(double S1) { return PutDelta(S1, K, T, r, sig, b); }\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//function to override spot price\n\tdouble Theta() const { return PutTheta(S, K, T, r, sig, b); }\n\tdouble Rho() const { return PutRho(S, K, T, r, sig, b); }\n\tdouble Delta(double h)const { return PutDelta(S, h, K, T, r, sig, b); }\n\t\n\n};\n\n\n#endif\n", "meta": {"hexsha": "6d3a93c46b564bce27e02b0ae304e7924bf30309", "size": 5814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "EuropeanOption.hpp", "max_stars_repo_name": "IlyaKul/OptionPricers", "max_stars_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EuropeanOption.hpp", "max_issues_repo_name": "IlyaKul/OptionPricers", "max_issues_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EuropeanOption.hpp", "max_forks_repo_name": "IlyaKul/OptionPricers", "max_forks_repo_head_hexsha": "4907e77994e75697ba7673673536c0312cd1e063", "max_forks_repo_licenses": ["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.2837837838, "max_line_length": 196, "alphanum_fraction": 0.7020983832, "num_tokens": 1733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6240293084881571}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/module/bessel.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/bessel_prime.hpp>\n#include <eve/detail/diff_div.hpp>\n\nEVE_TEST_TYPES( \"Check return types of sph_bessel_y0\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  TTS_EXPR_IS(eve::sph_bessel_y0(T(0)), T);\n  TTS_EXPR_IS(eve::sph_bessel_y0(v_t(0)), v_t);\n};\n\n EVE_TEST( \"Check behavior of sph_bessel_y0 on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(0.0, 5.5),\n                              eve::test::randoms(5.5, 9.5),\n                              eve::test::randoms(9.5, 60.0))\n         )\n   <typename T>(T const& a0, T const& a1, T const& a2)\n{\n  using v_t = eve::element_type_t<T>;\n  auto eve__sph_bessel_y0 =  [](auto x) { return eve::sph_bessel_y0(x); };\n  auto std__sph_bessel_y0 =  [](auto x)->v_t { return boost::math::sph_neumann(0u, double(x)); };\n\n  if constexpr( eve::platform::supports_invalids )\n  {\n    TTS_ULP_EQUAL(eve__sph_bessel_y0(eve::inf(eve::as<v_t>())), eve::zero(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_y0(eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_y0(eve::inf(eve::as< T>())),  eve::zero(eve::as< T>()), 0);\n    TTS_ULP_EQUAL(eve__sph_bessel_y0(eve::nan(eve::as< T>())), eve::nan(eve::as< T>()), 0);\n  }\n  TTS_ULP_EQUAL(eve__sph_bessel_y0(v_t(500)), std__sph_bessel_y0(v_t(500)), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0(v_t(10)), std__sph_bessel_y0(v_t(10))  , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0(v_t(5)),  std__sph_bessel_y0(v_t(5))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0(v_t(2)),  std__sph_bessel_y0(v_t(2))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0(v_t(1.5)),std__sph_bessel_y0(v_t(1.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0(v_t(0.5)),std__sph_bessel_y0(v_t(0.5)) , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0(v_t(1)),  std__sph_bessel_y0(v_t(1))   , 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0(v_t(0)),  eve::minf(eve::as<v_t>()), 0.0);\n\n  TTS_ULP_EQUAL(eve__sph_bessel_y0( T(500)),  T(std__sph_bessel_y0(v_t(500)) ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0( T(10)) ,  T(std__sph_bessel_y0( v_t(10)) ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0( T(5))  ,  T(std__sph_bessel_y0( v_t(5))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0( T(2))  ,  T(std__sph_bessel_y0( v_t(2))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0( T(1.5)),  T(std__sph_bessel_y0( v_t(1.5))), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0( T(0.5)),  T(std__sph_bessel_y0( v_t(0.5))), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0( T(1))  ,  T(std__sph_bessel_y0( v_t(1))  ), 6.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0( T(0))  , eve::minf(eve::as< T>()), 0.0);\n\n\n  TTS_ULP_EQUAL(eve__sph_bessel_y0(a0), map(std__sph_bessel_y0, a0), 10.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0(a1), map(std__sph_bessel_y0, a1), 10.0);\n  TTS_ULP_EQUAL(eve__sph_bessel_y0(a2), map(std__sph_bessel_y0, a2), 10.0);\n\n};\n\nEVE_TEST( \"Check behavior of diff(sph_bessel_y0) on wide\"\n        , eve::test::simd::ieee_reals\n        , eve::test::generate(eve::test::randoms(1.0, 10.0))\n        )\n  <typename T>(T a0 )\n{\n  auto eve__diff_bessel_y0 =  [](auto x) { return eve::diff(eve::sph_bessel_y0)(x); };\n  auto df = [](auto x){return eve::detail::centered_diffdiv(eve::sph_bessel_y0, x); };\n\n  TTS_RELATIVE_EQUAL(eve__diff_bessel_y0(a0),   df(a0), 1.0e-2);\n};\n", "meta": {"hexsha": "178d38cd1c7412107297a8562f7bf2f88ef9946e", "size": 3774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/sph_bessel_y0.cpp", "max_stars_repo_name": "clayne/eve", "max_stars_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/bessel/sph_bessel_y0.cpp", "max_issues_repo_name": "clayne/eve", "max_issues_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/bessel/sph_bessel_y0.cpp", "max_forks_repo_name": "clayne/eve", "max_forks_repo_head_hexsha": "dc268b5db474376e1c53f5a474f5bb42b7c4cb59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.7721518987, "max_line_length": 100, "alphanum_fraction": 0.631690514, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711870587667, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6239804506666998}}
{"text": "#include <iostream>\n#include <type.hpp>\n\n#include <Eigen/Eigen>\n\n#include \"Geometry/ParameterDesign/Bezier.hpp\"\n#include \"imgui/implot.h\"\n#include \"Visualization/Visualizer.h\"\n#include \"Geometry/ParameterDesign/ParameterCurve.h\"\n#include \"Geometry/ParameterDesign/Rational.h\"\n\nclass BezierVisualizer :public Visualizer\n{\nprotected:\n\tvoid AddPoint();\n\tvoid DragPoint();\n\n\tvoid draw(bool* p_open) override;\n\n\tstd::vector<Point2d> points;\n\tstd::vector<Float> weights;\n\tbool updated = true;\n\n\tvoid evaluate_bezier()\n\t{\n\t\tusing V = Eigen::Vector2d;\n\t\tauto temp_points = std::vector<Eigen::Vector2d>(3);\n\n\t\tpoints[0] = V(points[0].x(), 0);\n\t\tpoints[1] = V(0, points[1].y());\n\t\ttemp_points[0] = points[0];\n\t\ttemp_points[1] = V(points[0].x(), points[1].y());\n\t\ttemp_points[2] = V(2 * points[0].x(), 2 * points[1].y());\n\n\t\tweights = { 1,1,0 };\n\t\tRationalBSpline<3> RBS(temp_points, weights);\n\t\tRBS.evaluate();\n\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\txs[i] = RBS(ctr_points[i]).x();\n\t\t\tys[i] = RBS(ctr_points[i]).y();\n\t\t}\n\t\tweights = { 1,-1,0 };\n\t\ttemp_points[1] *= -1;\n\t\tRBS = RationalBSpline<3>(temp_points, weights);\n\n\t\tRBS.evaluate();\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\txs[i + Length] = RBS(1.0 - ctr_points[i]).x();\n\t\t\tys[i + Length] = RBS(1.0 - ctr_points[i]).y();\n\t\t}\n\n\t\tctr_xs.resize(points.size());\n\t\tctr_ys.resize(points.size());\n\n\t\tfor (int i = 0; i < points.size(); ++i)\n\t\t{\n\t\t\tctr_xs[i] = points[i].x();\n\t\t\tctr_ys[i] = points[i].y();\n\t\t}\n\t}\n\npublic:\n\tBezierVisualizer() {\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\tctr_points[i] = Float(i) / (Length - 1);\n\t\t\t//ctr_points[i + Length] = Float(i) / (Length - 1);\n\t\t}\n\n\t\tpoints.resize(2);\n\t\tpoints[0] = Eigen::Vector2d(2, 0);\n\t\tpoints[1] = Eigen::Vector2d(0, 1);\n\t}\n\tconst float Length = 1001;\n\n\tstd::vector<float> ctr_points = std::vector<float>(Length);\n\tstd::vector<float> xs = std::vector<float>(2 * Length);\n\tstd::vector<float> ys = std::vector<float>(2 * Length);\n\n\tstd::vector<float> ctr_xs = std::vector<float>(0);\n\tstd::vector<float> ctr_ys = std::vector<float>(0);\n};\n\nvoid BezierVisualizer::AddPoint()\n{\n\t//if (ImGui::IsMouseClicked(ImGuiMouseButton_Right))\n\t//{\n\t//\tauto pos = ImPlot::GetPlotMousePos();\n\t//\tpoints.emplace_back(pos.x, pos.y);\n\t//\tupdated = true;\n\t//}\n}\n\nvoid BezierVisualizer::DragPoint()\n{\n\tfor (int i = 0; i < points.size(); ++i)\n\t{\n\t\tauto& point = points[i];\n\t\tupdated |= ImPlot::DragPoint((\"Point \" + std::to_string(i)).c_str(), &point.x(), &point.y());\n\t}\n}\n\nvoid BezierVisualizer::draw(bool* p_open)\n{\n\tif (updated)\n\t{\n\t\tevaluate_bezier();\n\t\tupdated = false;\n\t}\n\tif (ImGui::BeginTabBar(\"Homework 2\")) {\n\t\tif (ImGui::BeginTabItem(\"Interpolation\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail(), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus)) {\n\t\t\t\tint delta = 667;\n\n\t\t\t\tImPlot::PlotLine(\"Bezier\", &xs[0], &ys[0], Length + delta);\n\n\t\t\t\tImPlot::PlotLine(\"Bezier\", &xs[Length + delta], &ys[Length + delta], Length - delta);\n\t\t\t\t//if (!ctr_xs.empty())\n\t\t\t\t//{\n\t\t\t\t//\tImPlot::PlotLine(\"ControlBox\", &ctr_xs[0], &ctr_ys[0], ctr_xs.size());\n\t\t\t\t//}\n\t\t\t\tAddPoint();\n\t\t\t\tDragPoint();\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\n\t\t\tImGui::EndTabItem();\n\t\t}\n\n\t\tImGui::EndTabBar();\n\t}\n\tImGui::End();\n}\n\nint main()\n{\n\tBezierVisualizer visualizer;\n\tvisualizer.RenderLoop();\n}", "meta": {"hexsha": "deb89813cb9a936cff5e3805acc48c4fd5a6380b", "size": 3281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/ParaCurves/test.cpp", "max_stars_repo_name": "Jerry-Shen0527/Numerical", "max_stars_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/ParaCurves/test.cpp", "max_issues_repo_name": "Jerry-Shen0527/Numerical", "max_issues_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/ParaCurves/test.cpp", "max_forks_repo_name": "Jerry-Shen0527/Numerical", "max_forks_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7847222222, "max_line_length": 132, "alphanum_fraction": 0.619323377, "num_tokens": 1086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6239804268283085}}
{"text": "/* This file is part of the Tomographer project, which is distributed under the\n * terms of the MIT license.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist\n * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include <cmath>\n\n#include <string>\n#include <iostream>\n#include <random>\n\n#include <boost/math/constants/constants.hpp>\n\n// definitions for Tomographer test framework -- this must be included before any\n// <Eigen/...> or <tomographer/...> header\n#include \"test_tomographer.h\"\n\n#include <tomographer/mathtools/random_unitary.h>\n\n\n\n// -----------------------------------------------------------------------------\n// fixture(s)\n\n\n\n// -----------------------------------------------------------------------------\n// test suites\n\n\nBOOST_AUTO_TEST_SUITE(test_mathtools_randomUnitary)\n\n\nBOOST_AUTO_TEST_CASE(basic)\n{\n  Eigen::MatrixXcd U(7,7);\n  \n  std::mt19937 rng(43423); // seeded, deterministic random number generator\n\n  // check that the given U is unitary, for a couple tries\n  \n  for (int k = 0; k < 1000; ++k) {\n    BOOST_MESSAGE(\"Running randomUnitary() for the \"<<k<<\"-th time\") ;\n\n    Tomographer::MathTools::randomUnitary(U, rng);\n    \n    MY_BOOST_CHECK_FLOATS_EQUAL((U * U.adjoint() - Eigen::MatrixXcd::Identity(7,7)).norm(), 0, 1e-12);\n    MY_BOOST_CHECK_FLOATS_EQUAL((U.adjoint() * U - Eigen::MatrixXcd::Identity(7,7)).norm(), 0, 1e-12);\n  }\n}\n\n//\n// Test that if we average rho over many random unitaries from randomUnitary, we get the\n// maximally mixed state; this then shows/indicates(?) that randomUnitary is indeed\n// distributed according to the Haar measures.\n//\nBOOST_AUTO_TEST_CASE(twirl_rho_gives_identity)\n{\n  Eigen::Matrix3cd rho;\n  rho << 0.2, 0, 0,\n         0, 0.5, 0,\n         0, 0, 0.3 ;\n\n  std::mt19937 rng(4832342u);\n\n  Eigen::Matrix3cd U;\n  \n  Eigen::Matrix3cd rhoTwirled(Eigen::Matrix3cd::Zero());\n\n  const int n_points = 10000;\n  for (int k = 0; k < n_points; ++k) {\n    Tomographer::MathTools::randomUnitary(U, rng);\n\n    rhoTwirled.noalias() += U*rho*U.adjoint();\n  }\n\n  rhoTwirled /= n_points;\n\n  BOOST_MESSAGE(\"rho averaged over random unitaries is  rhoTwirled = \\n\" << rhoTwirled);\n\n  MY_BOOST_CHECK_EIGEN_EQUAL(rhoTwirled, Eigen::Matrix3cd::Identity()/3.0, 0.5/std::sqrt((double)n_points));\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "5ed7e7aea7f7e73427487027ae802a17fc079735", "size": 3459, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/test_mathtools_random_unitary.cxx", "max_stars_repo_name": "Tomographer/tomographer", "max_stars_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T02:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T02:26:00.000Z", "max_issues_repo_path": "test/test_mathtools_random_unitary.cxx", "max_issues_repo_name": "Tomographer/tomographer", "max_issues_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-12T15:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T15:14:59.000Z", "max_forks_repo_path": "test/test_mathtools_random_unitary.cxx", "max_forks_repo_name": "Tomographer/tomographer", "max_forks_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-10-12T15:32:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-08T11:39:49.000Z", "avg_line_length": 31.7339449541, "max_line_length": 108, "alphanum_fraction": 0.6871928303, "num_tokens": 880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6239804218839775}}
{"text": "/* Small utility functions useful for point-based registration */\n#ifndef UTIL_INCLUDED \n#define UTIL_INCLUDED\n\n#include <Eigen/Dense>\n\nbool isApproxEqual(double a, double b, double eps);\n\nbool isApproxEqual(double a, double b);\n\nEigen::Vector3d find_pointset_average(const Eigen::MatrixXd& pointset);\n\nEigen::MatrixXd residuals_from_point(const Eigen::MatrixXd& pointset, const Eigen::Vector3d& point);\n\nEigen::VectorXd distances_between_pointsets(const Eigen::MatrixXd& pointset, const Eigen::MatrixXd& pointset_dash);\n\ndouble root_mean_square(const Eigen::VectorXd& v);\n\nEigen::Matrix4d compose_final_transform(const Eigen::Matrix3d& rotation, const Eigen::Vector3d& translation);\n\nEigen::MatrixXd apply_transform(const Eigen::MatrixXd& pointset, const Eigen::Matrix4d& transform);\n\nEigen::MatrixXd load_pointcloud_from_file(std::string filename);\n\nEigen::Matrix4d load_transform_from_file(std::string filename);\n\nvoid write_matrix_to_file(const Eigen::MatrixXd& matrix, std::string filename);\n#endif\n", "meta": {"hexsha": "22b4dc02ef729cc6f0d404557e25ea10a5aa793a", "size": 1004, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/PointMatching/Util.hpp", "max_stars_repo_name": "karnival/simple-registration", "max_stars_repo_head_hexsha": "0a7d952e566f0117c0d75f77337c23cfc97a3e7f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-04T00:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-04T00:54:17.000Z", "max_issues_repo_path": "Code/PointMatching/Util.hpp", "max_issues_repo_name": "karnival/simple-registration", "max_issues_repo_head_hexsha": "0a7d952e566f0117c0d75f77337c23cfc97a3e7f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/PointMatching/Util.hpp", "max_forks_repo_name": "karnival/simple-registration", "max_forks_repo_head_hexsha": "0a7d952e566f0117c0d75f77337c23cfc97a3e7f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-20T14:50:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-20T14:50:14.000Z", "avg_line_length": 34.6206896552, "max_line_length": 115, "alphanum_fraction": 0.8057768924, "num_tokens": 216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6239804212484162}}
{"text": "#ifndef POLICY_HPP\n#define POLICY_HPP\n\n#include <limits>\n#include \"helpers.hpp\"\n#include \"stats.hpp\"\n#include <boost/math/distributions/geometric.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/shared_ptr.hpp>\n\nusing boost::shared_ptr;\n\ntemplate<class PT>\nclass PolicyBase\n{\npublic:\n  PolicyBase(unsigned long horizon, const int arms) : \n    totalrewards(arms, 0), sample_index(arms, 0), horizon(horizon), totalsampled(arms,0), totalscore(0), arms(arms) {}\n\n  void simulate(const Table& rewards, const unsigned long t, const double mustar, \n    Stats& stats)\n  {\n    int arm = (static_cast<PT*>(this))->choosearm(t);\n    totalsampled[arm] += 1;\n    double outcome = rewards[arm][sample_index[arm]];\n    totalrewards[arm] += outcome;\n    sample_index[arm]++;\n    totalscore += outcome;\n    const double instantregret = (t*mustar) - totalscore;\n    #pragma omp critical\n    {\n      stats(instantregret, t);\n    }\n  }\n//protected:\n  vector<double> totalrewards;\n  vector<int> sample_index;\n  unsigned long horizon;\n  vector<double> totalsampled;\n  double totalscore;\n  const int arms;\n};\n\ntemplate<class PT>\nclass PolicyCollection\n{\npublic:\n  \n  void simulate(Table& rewards, const unsigned long t, const double mustar,\n    vector<Stats>& totalregret)\n  {\n    for (unsigned int i = 0; i < pcs.size(); ++i)\n    {\n      pcs[i]->simulate(rewards, t, mustar, totalregret[i]); \n    }\n  }\n\n  vector<shared_ptr<PT> > pcs;\n};\n\nclass ThompsonPolicy : public PolicyBase<ThompsonPolicy>\n{\npublic:\n  ThompsonPolicy(RandomSampleHelper& bh, unsigned long horizon, int arms, bool gaussian) :\n    PolicyBase<ThompsonPolicy>(horizon, arms), bh(bh), gaussian(gaussian) {}\n  int choosearm(int t)\n  {\n    int result = -1;\n    double max = -std::numeric_limits<double>::max();\n    for(int a = 0; a < arms; ++a)\n    {\n      if (totalsampled[a] == totalrewards[a])\n        return a;\n      const double samp = gaussian ? bh.sampleGaussian(totalrewards[a]/(1.0+totalsampled[a]), sqrt(1.0/(1.0+totalsampled[a]))) : \n        bh.sampleBeta(totalrewards[a] + 1, totalsampled[a] - totalrewards[a] + 1);\n      if(samp > max)\n      {\n        result = a;\n        max = samp;\n      }\n    }\n    return result;\n  }\n\nprivate:\n  RandomSampleHelper& bh;\n  bool gaussian;\n};\n\nclass UCB1Policy : public PolicyBase<UCB1Policy>\n{\npublic:\n  UCB1Policy(unsigned long horizon, int arms) :\n    PolicyBase<UCB1Policy>(horizon, arms) {}\n\n  int choosearm(int t)\n  {\n    int result = -1;\n    double max = -std::numeric_limits<double>::max();\n    if(t <= arms)\n      return t-1;\n    for(int a = 0; a < arms; ++a)\n    {\n      const double avg = double(totalrewards[a])/double(totalsampled[a]);\n      const double ucb = avg + sqrt(2*log(double(t))/double(totalsampled[a]));\n      if(ucb > max)\n      {\n        result = a;\n        max = ucb;\n      }\n    }\n    return result;\n  }\n};\n\nclass BayesUCBPolicy : public PolicyBase<BayesUCBPolicy>\n{\npublic:\n  BayesUCBPolicy(unsigned long horizon, int arms, bool gaussian) :\n    PolicyBase<BayesUCBPolicy>(horizon, arms), gaussian(gaussian) {}\n\n  int choosearm(int t)\n  {\n    int result = -1;\n    double max = -std::numeric_limits<double>::max();\n    if(t <= arms)\n      return t-1;\n    for(int a = 0; a < arms; ++a)\n    {\n      const double gamma = 1.0 - 1.0 / double(t);\n      double ucb = 0;\n      if (gaussian)\n      {\n        double mun = totalrewards[a]/(1.0+totalsampled[a]);\n        double sigman = sqrt(1.0/(1.0+totalsampled[a]));\n        boost::math::normal_distribution<double, policies::policy<> > normdist(mun,sigman);\n        ucb = boost::math::quantile(normdist, gamma);\n      }\n      else \n      {\n        ucb = ibeta_inv(totalrewards[a]+1, totalsampled[a]-totalrewards[a] + 1, gamma); \n      }\n      if(ucb > max)\n      {\n        result = a;\n        max = ucb;\n      }\n    }\n    return result;\n  }\nprivate:\n  bool gaussian;\n};\n\nclass NaivePolicy : public PolicyBase<NaivePolicy>\n{\npublic:\n  NaivePolicy(unsigned long horizon, int arms) :\n    PolicyBase<NaivePolicy>(horizon, arms) {}\n\n  int choosearm(int t)\n  {\n    int result = -1;\n    double max = -numeric_limits<double>::max();\n    if(t <= arms)\n      return t-1;\n    #ifdef PRINT_POLICY\n    cout << \"round [\" << t << \"]. \";\n    #endif\n    for(int a = 0; a < arms; ++a)\n    {\n      const double avg = double(totalrewards[a])/double(totalsampled[a]);\n      #ifdef PRINT_POLICY\n      cout << \"avg for arm [\" << a << \"] is [\" << avg << \"]. \";\n      #endif\n      if(avg > max)\n      {\n        result = a;\n        max = avg;\n      }\n    }\n    #ifdef PRINT_POLICY\n    cout << \"picked arm [\" << result << \"]\" << endl;\n    #endif\n    return result;\n  }\n};\n\nclass GittinsPolicy : public PolicyBase<GittinsPolicy>\n{\npublic:\n  GittinsPolicy(const Table3D& indices, unsigned long horizon, int arms, double b_param, bool gaussian) :\n    PolicyBase<GittinsPolicy>(horizon, arms), indices(indices), gaussian(gaussian), b_param(b_param)\n  {\n  }\n  \n  int choosearm(int it)\n  {\n    int result = -1;\n    double max = -1;\n    int offset = (int) b_param;\n    for(int a = 0; a < arms; ++a)\n    {\n      double gindex = 0;\n      double g = 1.0 - 1.0/(b_param + double(it));\n      if (indices.size() == 0)\n      {\n        if (gaussian)\n          gindex = approximategi2(g, totalrewards[a]/(1.0+totalsampled[a]), 1.0/sqrt(1+totalsampled[a]));\n        else\n          gindex = approximategi(g, totalrewards[a]+1, totalsampled[a]-totalrewards[a]+1); \n      }\n      else {\n        if (gaussian)\n          gindex = approximategi2(g, totalrewards[a]/(1.0+totalsampled[a]), 1.0/sqrt(1+totalsampled[a]));\n        else\n          gindex = indices[it + offset -1][totalrewards[a]][totalsampled[a]-totalrewards[a]];\n      }\n      if(gindex > max)\n      {\n        result = a;\n        max = gindex;\n      }\n      #ifdef PRINT_POLICY\n      cout << \"a\" << a << \" = \" << long(totalrewards[a]) << \". b = \" << long(totalsampled[a]-totalrewards[a]) << \". gindex = \" << gindex << \". \";  \n      #endif\n    }\n    #ifdef PRINT_POLICY\n    cout << endl;\n    #endif\n    return result;\n  }\nprivate:\n  const Table3D& indices;\n\n  double approximategi(double g, double a, double b)\n  {\n    const double mu = a/(a+b);\n    const double var = a*b/((a+b)*(a+b)*(a+b+1));\n    const static double c = -log(g);\n    return mu + sqrt(var)*psi(var/c); \n  }\n\n  double psi(const double s)\n  {\n    if(s<=0.2)\n      return sqrt(s/2.0);\n    if(s <= 1)\n      return 0.49 - 0.11/sqrt(s);\n    if (s <= 5)\n      return 0.63 - 0.26/sqrt(s);\n    if (s <= 15)\n      return 0.77 - 0.58/sqrt(s);\n    return sqrt(2*log(s) - log(log(s)) - log(16*M_PI));\n  }\n\n  double approximategi2(double g, double mun, double sigman)\n  {\n    return g == 0.0 ? 0.0 : mun + geefunc(sigman, g);\n  }\n\n  double geefunc(double s, double gamma)\n  {\n    return sqrt(-log(gamma))*bfunc(-s*s/log(gamma)); \n  }\n\n  double bfunc(double s)\n  {\n    if (s <= 1.0/7.0)\n      return s/sqrt(2);\n    if (s <= 100)\n      return exp(-0.02645*(log(s)*log(s)) + 0.89106*log(s) - 0.4873);\n    return sqrt(s)*sqrt(2*log(s) - log(log(s)) - log(16*PI));\n  }\n\n  bool gaussian;\n  double b_param;\n};\n\nclass IDSMinFunc\n{\npublic: \n  IDSMinFunc(double di, double dj, double gi, double gj)\n    : gi(gi), gj(gj), di(di), dj(dj)\n  {}\n  \n  double operator() (double q)\n  {\n    return (q*di + (1-q)*dj)*(q*di + (1-q)*dj)/(q*gi + (1-q)*gj);\n  }\n  \n  void print()\n  {\n    cout << \"gi:\" << gi << \". gj:\" << gj;\n    cout << \"di:\" << di << \". dj:\" << dj;\n    cout << endl;\n  }\nprivate:\n  double gi, gj, di, dj;\n};\n\nclass IDSPolicy : public PolicyBase<IDSPolicy>\n{\n  const vector<double>& uniforms;\n  int POINTS; \n  double RANGE;\n  double STEPSIZE;\npublic:\n  IDSPolicy(unsigned long horizon, const vector<double>& uniforms, int arms, bool gaussian_, int bpoints) :\n    PolicyBase<IDSPolicy>(horizon, arms), \n    uniforms(uniforms),\n    POINTS(gaussian_ ? 8000 : bpoints), \n    fi(arms, vector<double>(POINTS, 0)),\n    Fi(arms, vector<double>(POINTS, 0)),\n    Qi(arms, vector<double>(POINTS, 0)),\n    F(POINTS, 0),\n    gaussian(gaussian_),\n    lastret(-1)\n  {\n    RANGE = 40.0;\n    STEPSIZE = gaussian ? RANGE/double(POINTS) : 1.0/double(POINTS);\n    boost::math::normal_distribution<> normdist(0,1);\n    for(int i = 0; i < POINTS; ++i)\n    {\n      double Fprod = 1;\n      for(int a =0; a < arms; ++a)\n      {\n        double x = (gaussian ? -RANGE/2.0 : 0) + STEPSIZE*(i+0.5);\n        Fi[a][i] = gaussian ? cdf(normdist, x) : ibeta(1.0,1.0,x);\n        Fprod *= Fi[a][i];\n        fi[a][i] = gaussian ? pdf(normdist, x) : ibeta_derivative(1.0,1.0,x);\n        Qi[a][i] = gaussian ? 0 : 0.5*ibeta(1.0+1.0,1.0,x);\n      }\n      F[i] = Fprod;\n    }\n  }\n  \n  int choosearm(int t)\n  {\n\n    vector<double> delta(arms, 0);\n    vector<double> gee(arms, 0);\n    computeDeltasAndGees(delta, gee);\n    \n    int istar=-1,jstar=-1;\n    double qstar=-1.0;\n    setupRandomization(gee, delta, qstar, istar, jstar);\n    int ret= uniforms[t-1] < qstar ? istar : jstar;\n    assert (ret >= 0 && ret < arms);\n\n    //remember the last arm that was pulled, so we can update relevant values of fi, Fi, etc. on the next iteration\n    lastret = ret;\n    return ret;\n  }\n\n  double probOptimal(int arm)\n  {\n    double result = 0;\n    for(int i = 0; i < POINTS; ++i)\n    {\n      double fprod = 1;\n      for (int a = 0; a < arms; ++a)\n      {\n        fprod *= a == arm ? 1.0 : Fi[a][i];\n      }\n      result += fi[arm][i]*fprod;\n    }\n    return STEPSIZE*result;\n  }\n\n  static void setupRandomization(const vector<double>& gee,\n                          const vector<double>& delta,\n                          double& qstar,\n                          int& istar,\n                          int& jstar)\n  {\n    int arms = gee.size(); \n    double opt = numeric_limits<double>::max();\n    for(int j = 0; j < arms-1; ++j)\n    {\n      for(int i = j+1; i < arms; ++i)\n      {\n        IDSMinFunc minfun(delta[i], delta[j], gee[i], gee[j]); \n        std::pair<double,double> res = brent_find_minima(minfun, 0.0, 1.0, 20);\n        assert((res.second < opt) || !(i == 1 && j == 0));\n        if(res.second < opt)\n        {\n          opt = res.second;\n          istar = i; jstar = j;\n          qstar = res.first;\n        }\n      }\n    }\n  }\n\n  void computeDeltasAndGees(vector<double>& delta, vector<double>& gee)\n  {\n    vector<boost::math::normal_distribution<> > normdists;\n    vector<double> muns;\n    vector<double> sigmans;\n    for (int a = 0; a < arms; ++a)\n    {\n      double mu = totalrewards[a]/(1.0 + totalsampled[a]); \n      double sigma = sqrt(1.0/(1.0 + totalsampled[a])); \n      assert(!gaussian || abs(mu) < RANGE/2.0 - sigma);\n      muns.push_back(mu);\n      sigmans.push_back(sigma);\n      normdists.push_back(boost::math::normal_distribution<>(mu, sigma));\n    }\n    vector<double> as(arms, 0);\n    vector<double> bs(arms, 0); \n    vector<double> proboptimal(arms, 0);\n    for(int i=0; i < arms;++i)\n    {\n      as[i] = totalrewards[i]+1;\n      bs[i] = totalsampled[i]-totalrewards[i]+1;\n    }\n\n    if (lastret >= 0)\n    {\n      const boost::math::normal_distribution<>& newnormdist = normdists[lastret];\n      const int newa = totalrewards[lastret]+1;\n      const int newb = totalsampled[lastret] - totalrewards[lastret]+1;\n      for(int i = 0; i < POINTS; ++i)\n      {\n        double x =  (gaussian ? -RANGE/2.0 : 0.0) + (i+0.5)*STEPSIZE;\n        \n        fi[lastret][i] = gaussian ? pdf(newnormdist, x) : ibeta_derivative(newa,newb,x);\n        Fi[lastret][i] = gaussian ? cdf(newnormdist, x) : ibeta(newa,newb,x);\n        Qi[lastret][i] = gaussian ? 0 : double(newa)/double(newa+newb)*ibeta(newa+1,newb,x);\n        F[i] = 1;\n        for(int a = 0; a < arms; ++a)\n        {\n          F[i] *= Fi[a][i];\n        }\n      }\n    }\n\n    for(int a =0; a < arms; ++a)\n      proboptimal[a] = probOptimal(a);\n    #ifndef NDEBUG\n    double totalprob = 0;\n    for (int a = 0; a < arms; ++a)\n    {\n     totalprob += proboptimal[a];\n    }\n    if (abs(totalprob - 1.0) >=  1e-1)\n    {\n      cerr << \"probabilities must sum to one when in fact totalprob = \" << totalprob << endl;\n      for (int a = 0; a < arms; ++a)\n      {\n        cerr << \"totalsampled[\" << a << \"] = \" << totalsampled[a] << \". proboptimal[\" << a << \"] = \" << proboptimal[a] << endl;\n        cerr << \"totalrewards[\" << a << \"] = \" << totalrewards[a] << endl;\n      }\n      exit(1);\n    }\n    #endif\n    Table Ms(arms,vector<double>(arms,0));\n    for(int i = 0; i < arms;++i)\n    {\n      for(int j = 0; j < arms; ++j)\n      {\n        double sum=0;\n        if(i==j)\n        {  \n          for(int p=0;p < POINTS; ++p)\n          {\n            double x = (gaussian ? - RANGE/2.0 : 0) + (p+0.5)*STEPSIZE;\n            sum += x*fi[i][p]*F[p]/max(Fi[i][p],0.0000001);\n          }\n          sum*=STEPSIZE;\n          Ms[i][j] = sum/proboptimal[i];\n          assert(gaussian || (Ms[i][j] < 1 && Ms[i][j] > 0));\n          continue;\n        }\n        for(int p =0; p < POINTS;++p)\n        {\n          sum +=gaussian ? fi[i][p]*F[p]*fi[j][p]/max(Fi[i][p]*Fi[j][p],0.000001) : fi[i][p]*F[p]*Qi[j][p]/max(Fi[i][p]*Fi[j][p],0.000001); \n          if(isnan(sum))\n          {\n            cerr << \"sum is nan! probably cuz Fi[\"<<i<<\"][\"<<p<<\"]=\" << Fi[i][p] << \". \";\n            cerr << \"and Fi[\"<<j<<\"][\"<<p<<\"]=\" << Fi[j][p] << endl;\n            cerr << \"fi[\" << i << \"][\" << p <<\"]=\"<<fi[i][p] << endl;\n            cerr << \"Qi[\" << j << \"][\" << p <<\"]=\"<<Qi[j][p] << endl;\n            cerr << \"F[\" << p <<\"]=\"<< F[p] << endl;\n            cerr << \"the result is=\" << fi[i][p]*F[p]*Qi[j][p]/max(Fi[i][p]*Fi[j][p],0.000001) << endl;\n            cerr << \"the denominator is=\" << max(Fi[i][p]*Fi[j][p],0.000001) << endl;\n            cerr << \"the numerator is \" << fi[i][p]*F[p]*Qi[j][p] << endl;\n            exit(1);\n          }\n        }\n        sum*=STEPSIZE;\n        Ms[i][j] = gaussian ? muns[j] - sum * sigmans[j]*sigmans[j]/proboptimal[i] :  sum/proboptimal[i];\n        assert(!isnan(Ms[i][j]));\n      }\n    }\n    double rhostar=0;   \n    for(int i = 0; i < arms;++i)\n    {\n      rhostar += proboptimal[i]*Ms[i][i];\n    }\n    for(int i = 0; i < arms; ++i)\n    {\n      delta[i] = gaussian ? rhostar - muns[i] : rhostar - as[i]/(as[i]+bs[i]);\n      double geeval=0;\n      for(int j = 0; j < arms;++j)\n      {\n        geeval += gaussian ? proboptimal[j] * (Ms[j][i] - muns[i])*(Ms[j][i] - muns[i]) :  proboptimal[j]*kl(Ms[j][i], as[i]/(as[i]+bs[i]));\n        assert(!isnan(geeval));\n      }\n      gee[i] = geeval;\n    }\n  }\n  \n  Table fi;\n  Table Fi;\n  Table Qi;\n  vector<double> F;\n  bool gaussian;\n  int lastret;\n};\n\nclass GaussianIDSPolicy : public PolicyBase<GaussianIDSPolicy>\n{\n\npublic:\n  GaussianIDSPolicy(unsigned long horizon, RandUnif& rng, int arms) :\n    PolicyBase<GaussianIDSPolicy>(horizon, arms), unif(rng), horizon(horizon)\n  {\n  }\n\nprivate:\n  RandUnif& unif;\n  unsigned long horizon;\n};\n\nclass InterestingPolicy : public PolicyBase<InterestingPolicy>\n{\npublic:\n  InterestingPolicy(unsigned long horizon, int arms, double a_param, double b_param, bool gaussian, int numSteps = 1) :\n    PolicyBase<InterestingPolicy>(horizon, arms), a_param(a_param), b_param(b_param), gaussian(gaussian), numSteps(numSteps)\n  {\n  }\n\n  int choosearm(int it)\n  {\n    double t = double(it);\n    int result = -1;\n    double max = -numeric_limits<double>::max();\n    \n    double  gamma_t = 1.0 - a_param/(b_param + t);\n\n    for(int a = 0; a < arms; ++a)\n    {\n      #ifdef PRINT_POLICY\n      cout << \"discount for \" << a << \" is \" << gamma << \" \";\n      #endif\n      const double index = gaussian ? ::computeAGIGaussian(gamma_t, totalrewards[a]/(1+totalsampled[a]), 1.0/sqrt(1+totalsampled[a]))\n         : ::computeApproxGI(gamma_t, totalrewards[a] + 1, (long)(totalsampled[a] - totalrewards[a]) + 1, numSteps);\n      if(index > max)\n      {\n        result = a;\n        max = index;\n      }\n      #ifdef PRINT_POLICY\n      cout << \"a\" << a << \" = \" << long(totalrewards[a]) << \". b = \" << long(totalsampled[a]-totalrewards[a]) << \". gindex = \" << index << \". \";  \n      #endif\n    }\n    #ifdef PRINT_POLICY\n    cout << endl;\n    #endif\n    return result;\n  }\nprivate:\n  const double a_param, b_param;\n  bool gaussian;\n  int numSteps;\n};\n\n#endif\n", "meta": {"hexsha": "2a4fdd8607fb1bdb65530e77806f67e19fe6fdb6", "size": 16078, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/policy.hpp", "max_stars_repo_name": "gutin/FastGittins", "max_stars_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T12:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T16:14:34.000Z", "max_issues_repo_path": "cpp/policy.hpp", "max_issues_repo_name": "gutin/FastGittins", "max_issues_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/policy.hpp", "max_forks_repo_name": "gutin/FastGittins", "max_forks_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T02:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T02:40:39.000Z", "avg_line_length": 27.6729776248, "max_line_length": 147, "alphanum_fraction": 0.5500062197, "num_tokens": 5053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6239417043304967}}
{"text": "#include \"timer.hh\"\n#include <Eigen/Dense>\n#include <cstdlib>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef MatrixXf Matrix;\ntypedef RowVectorXf RowVector;\ntypedef VectorXf ColVector;\n\nclass NeuralNetwork\n{\n  vector<ColVector*> neuronLayers; // different layers of output network\n  vector<ColVector*> cacheLayers;  // values of layers before activation\n  vector<ColVector*> deltas;       // stores the error contribution of each neurons\n  vector<MatrixXf*> weights;       // the weights of connections between layers\n  vector<uint> topology;\n  double learningRate;\n  // enum { NeedsToAlign = (sizeof(neuronLayers)%16)==0 };\n\npublic:\n  // EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(NeedsToAlign)\n\n  NeuralNetwork( vector<uint> topology, double learningRate = 0.005f );\n\n  ColVector forward_propagation( ColVector& input );\n  void backward_propagation( ColVector& output );\n  void error_calculation( ColVector& output );\n  void update_weights();\n\n  double activationFunction( double x ) { return max( x, 0.0f ); }\n\n  ColVector activationFunction( ColVector& x ) { return x.cwiseMax( 0 ); }\n\n  double activationFunctionDerivative( double x )\n  {\n    if ( x >= 0 )\n      return 1;\n    else\n      return 0;\n  }\n\n  void print()\n  {\n    const IOFormat CleanFmt( 4, 0, \", \", \"\\n\", \"[\", \"]\" );\n    for ( uint i = 1; i < topology.size(); i++ ) {\n      cout << \"Weights Layer \" << i << \":\\n\"\n           << ( *weights[i - 1] ).format( CleanFmt ) << \"\\n\\n\"\n           << \"cacheLayers: Layer \" << i << \":\\n\"\n           << ( *cacheLayers[i] ).format( CleanFmt ) << \"\\n\\n\"\n           << \"neuronLayers Layer \" << i << \":\\n\"\n           << ( *neuronLayers[i] ).format( CleanFmt ) << \"\\n\\n\";\n    }\n  }\n};\n\nNeuralNetwork::NeuralNetwork( vector<uint> topology_, double learningRate_ )\n  : neuronLayers()\n  , cacheLayers()\n  , deltas()\n  , weights()\n  , topology( topology_ )\n  , learningRate( learningRate_ )\n{\n  topology = topology_;\n  learningRate = learningRate_;\n  for ( uint i = 0; i < topology.size(); i++ ) {\n    if ( i != topology.size() - 1 )\n      neuronLayers.push_back( new ColVector( topology[i] + 1 ) );\n    // +1 for biases\n    else\n      neuronLayers.push_back( new ColVector( topology[i] ) );\n\n    // initialize cache and delta vectors\n    cacheLayers.push_back( new ColVector( neuronLayers[i]->rows() ) );\n    deltas.push_back( new ColVector( neuronLayers[i]->rows() ) );\n\n    // setting up biases nodes\n    if ( i != topology.size() - 1 ) {\n      neuronLayers.back()->coeffRef( topology[i] ) = 1.0;\n      cacheLayers.back()->coeffRef( topology[i] ) = 1.0;\n    }\n\n    // initialize weights matrix\n    if ( i > 0 ) {\n      if ( i != topology.size() - 1 ) {\n        weights.push_back( new MatrixXf( topology[i] + 1, topology[i - 1] + 1 ) );\n\n        // random weights initialisation\n        weights.back()->setRandom();\n\n        // no \"normal\" weights into biases\n        weights.back()->row( topology[i] ).setZero();\n        weights.back()->coeffRef( topology[i], topology[i - 1] ) = 1.0;\n      } else {\n        weights.push_back( new MatrixXf( topology[i], topology[i - 1] + 1 ) );\n        weights.back()->setRandom();\n      }\n    }\n  }\n}\n\nColVector NeuralNetwork::forward_propagation( ColVector& input )\n{\n  // setting the input layer of the NN\n  // block takes 4 arguments : startRow, startCol, blockRows, blockCols\n\n  neuronLayers.front()->block( 0, 0, neuronLayers.front()->size() - 1, 1 ) = input;\n\n  // forward propagation\n  for ( uint i = 1; i < topology.size() - 1; i++ ) {\n    ( *cacheLayers[i] ) = ( *weights[i - 1] ) * ( *neuronLayers[i - 1] );\n    ( *neuronLayers[i] ) = activationFunction( *cacheLayers[i] );\n    // resetting back the bias NN node\n    neuronLayers[i]->coeffRef( topology[i] ) = 1.0;\n  }\n  // no activation at last layer\n  uint i = topology.size() - 1;\n  ( *cacheLayers[i] ) = ( *weights[i - 1] ) * ( *neuronLayers[i - 1] );\n  ( *neuronLayers[i] ) = *cacheLayers[i];\n\n  return *neuronLayers[topology.size() - 1];\n}\n\nvoid program_body()\n{\n  vector<uint> TOPOLOGY = { 5, 3, 2, 1 };\n  ColVector input( 5 );\n  input << 1.0f, -2.0f, 3.0f, -2.0f, 0.0f;\n  NeuralNetwork nn( TOPOLOGY );\n  uint64_t start = Timer::timestamp_ns();\n  ColVector output = nn.forward_propagation( input );\n  uint64_t end = Timer::timestamp_ns();\n  cout << end - start << endl;\n\n  const IOFormat CleanFmt( 4, 0, \", \", \"\\n\", \"[\", \"]\" );\n\n  cout << \"input:\\n\"\n       << input.format( CleanFmt ) << \"\\n\\n\"\n       << \"output:\\n\"\n       << output.format( CleanFmt ) << \"\\n\\n\";\n  nn.print();\n}\n\nint main()\n{\n  try {\n    ios::sync_with_stdio( false );\n    program_body();\n    return EXIT_SUCCESS;\n  } catch ( const exception& e ) {\n    cerr << e.what() << \"\\n\";\n    return EXIT_FAILURE;\n  }\n}\n", "meta": {"hexsha": "fb427cb2e0fb07e603b275a3904b41091640f043", "size": 4717, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/frontend/neuralnetwork.cc", "max_stars_repo_name": "stanford-stagecast/nnfun", "max_stars_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-04T23:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T06:57:30.000Z", "max_issues_repo_path": "src/frontend/neuralnetwork.cc", "max_issues_repo_name": "stanford-stagecast/nnfun", "max_issues_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/frontend/neuralnetwork.cc", "max_forks_repo_name": "stanford-stagecast/nnfun", "max_forks_repo_head_hexsha": "14300c4320b9b90b4f54d8fc49f66166a490c257", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6666666667, "max_line_length": 83, "alphanum_fraction": 0.6065295739, "num_tokens": 1360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6239416867594492}}
{"text": "#ifndef BART_SRC_CONVERGENCE_MOMENTS_CONVERGENCE_CHECKER_L_INFINITY_NORM_HPP_\n#define BART_SRC_CONVERGENCE_MOMENTS_CONVERGENCE_CHECKER_L_INFINITY_NORM_HPP_\n\n#include \"convergence/convergence_checker.hpp\"\n#include <deal.II/lac/vector.h>\n\nnamespace bart::convergence::moments {\n\n/*! \\brief Checks for convergence between flux moments using the percentage\n * change in the \\f$L_{\\infty}\\f$ norm, compared to the current iteration (\\f$i\\f$):\n *\n * \\f[\n *\n * \\Delta_i = \\frac{|\\phi_i - \\phi_{i-1}|_{\\infty}}{|\\phi_{i}|_{\\infty}}\n *\n * \\f]\n *\n * Convergence is achieved if \\f$\\Delta_i \\leq \\Delta_{\\text{max}}\\f$.\n * */\nclass ConvergenceCheckerLInfinityNorm : public ConvergenceChecker<dealii::Vector<double>> {\n public:\n  using Vector = dealii::Vector<double>;\n  explicit ConvergenceCheckerLInfinityNorm(const double max_delta = 1e-6) { max_delta_ = CheckNonNegative(max_delta); };\n\n  auto SetMaxDelta(const double& to_set) -> void override { max_delta_ = CheckNonNegative(to_set); };\n  auto IsConverged(const Vector &current_iteration, const Vector &previous_iteration) -> bool override {\n    Vector difference(current_iteration);\n    difference.add(-1, previous_iteration);\n    delta_ = difference.linfty_norm()/current_iteration.linfty_norm();\n    is_converged_ = delta_ <= max_delta_;\n    return is_converged_;\n  }\n\n private:\n  auto CheckNonNegative(const double to_check) -> double {\n    AssertThrow(to_check > 0, dealii::ExcMessage(\"Error in ConvergenceCheckerLInfinityNorm, max delta value to set must \"\n                                                 \"be greater than 0\"))\n    return to_check;\n  }\n};\n\n} // namespace bart::convergence::moments\n\n#endif //BART_SRC_CONVERGENCE_MOMENTS_CONVERGENCE_CHECKER_L_INFINITY_NORM_HPP_\n", "meta": {"hexsha": "33cf3516ff9fbedfad16ac63ecad10bcbfb2bc15", "size": 1728, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/convergence/moments/convergence_checker_l_infinity_norm.hpp", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "src/convergence/moments/convergence_checker_l_infinity_norm.hpp", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "src/convergence/moments/convergence_checker_l_infinity_norm.hpp", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 38.4, "max_line_length": 121, "alphanum_fraction": 0.734375, "num_tokens": 449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392909114835, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6239416846031702}}
{"text": "#include <boost/math/constants/constants.hpp>\n#include \"EnergyResolution.hh\"\n#include \"TypesFunctions.hh\"\n#include <fmt/format.h>\n#include <string.h>\n\nconstexpr double pi = boost::math::constants::pi<double>();\n\n\nEnergyResolution::EnergyResolution(bool propagate_matrix) :\nEnergyResolution({\"Eres_a\" , \"Eres_b\" , \"Eres_c\"}, propagate_matrix){\n\n}\n\nEnergyResolution::EnergyResolution(const std::vector<std::string>& pars, bool propagate_matrix) :\nHistSmearSparse(propagate_matrix)\n{\n  if(pars.size()!=3u){\n    throw std::runtime_error(\"Energy resolution should have exactly 3 parameters\");\n  }\n  variable_(&m_a, pars[0]);\n  variable_(&m_b, pars[1]);\n  variable_(&m_c, pars[2]);\n\n  transformation_(\"matrix\")\n      .input(\"Edges\", /*inactive*/true)\n      .output(\"FakeMatrix\")\n      .types(TypesFunctions::ifHist<0>, TypesFunctions::if1d<0>, TypesFunctions::toMatrix<0,0,0>)\n      .types(&EnergyResolution::getEdges)\n      .func(&EnergyResolution::calcMatrix);\n\n  add_transformation();\n  add_input();\n  set_open_input();\n}\n\nvoid EnergyResolution::getEdges(TypesFunctionArgs& fargs) {\n  m_edges = fargs.args[0].edges.data();\n}\n\ndouble EnergyResolution::relativeSigma(double Etrue) const noexcept {\n  return sqrt(pow(m_a, 2)+ pow(m_b, 2)/Etrue + pow(m_c/Etrue, 2));\n}\n\ndouble EnergyResolution::resolution(double Etrue, double Erec) const noexcept {\n  static const double twopisqr = std::sqrt(2*pi);\n  const double sigma = Etrue * relativeSigma(Etrue);\n  const double reldiff = (Etrue - Erec)/sigma;\n\n  return std::exp(-0.5*pow(reldiff, 2))/(twopisqr*sigma);\n}\n\nvoid EnergyResolution::calcMatrix(FunctionArgs& fargs) {\n  m_sparse_cache.setZero();\n\n  auto& ret = fargs.rets[0];\n  auto* edges = m_edges;\n  auto bins = ret.type.shape[0];\n  m_sparse_cache.resize(bins, bins);\n\n  /* fill the cache matrix with probalilities for number of events to leak to other bins */\n  /* colums corressponds to reconstrucred energy and rows to true energy */\n  auto bin_center = [edges](size_t index){ return (edges[index+1] + edges[index])/2; };\n  for (size_t etrue = 0; etrue < bins; ++etrue) {\n    double Etrue = bin_center(etrue);\n    double dEtrue = edges[etrue+1] - edges[etrue];\n\n    bool right_edge_reached{false};\n    /* precalculating probabilities for events in given bin to leak to\n     * neighbor bins  */\n    for (size_t erec = 0; erec < bins; ++erec) {\n      double Erec = bin_center(erec);\n      double rEvents = dEtrue*resolution(Etrue, Erec);\n\n      if (rEvents < 1E-10) {\n        if (right_edge_reached) {\n           break;\n        }\n        continue;\n      }\n      m_sparse_cache.insert(erec, etrue) = rEvents;\n      if (!right_edge_reached) {\n        right_edge_reached = true;\n      }\n    }\n  }\n  m_sparse_cache.makeCompressed();\n\n  if ( m_propagate_matrix )\n    fargs.rets[0].mat = m_sparse_cache;\n}\n", "meta": {"hexsha": "bc09e26b9c6c1daa5c3647d79aeed9fdc3eff2fa", "size": 2798, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/detector/EnergyResolution.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/detector/EnergyResolution.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/detector/EnergyResolution.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": 30.4130434783, "max_line_length": 97, "alphanum_fraction": 0.6851322373, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6239416781343327}}
{"text": "\n#include \"kmers/dirichlet-sampler.hpp\"\n#include <Eigen/Dense>\n#include <iostream>\n\nint main() {\n  std::random_device dev;\n  std::mt19937 rng(dev());\n\n  uint64_t N = 20;\n  Eigen::VectorXd alpha = Eigen::VectorXd::Ones(N);\n  Eigen::VectorXd theta = kmers::dirichlet_rng(alpha, rng);\n  std::vector<double> theta_sv(&theta[0], &theta[0] + N);\n  std::vector<uint64_t> y = kmers::multinomial_rng(10000, theta_sv, rng);\n  for (int n = 0; n < N; ++n) {\n    std::cout << \"theta[\" << n << \"] = \" << theta[n]\n\t      << \";  y[\" << n << \"] = \" << y[n]\n\t      << std::endl;\n  }\n}\n  \n", "meta": {"hexsha": "60ce0635405ad30afd152de00ac5f500bdc46aa3", "size": 570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kmers/src/main2.cpp", "max_stars_repo_name": "bob-carpenter/case-studies", "max_stars_repo_head_hexsha": "d9ac886989b08629f5fcedf6c9e06f3f1f1faff8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2019-04-25T15:24:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T03:18:12.000Z", "max_issues_repo_path": "kmers/src/main2.cpp", "max_issues_repo_name": "bob-carpenter/case-studies", "max_issues_repo_head_hexsha": "d9ac886989b08629f5fcedf6c9e06f3f1f1faff8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kmers/src/main2.cpp", "max_forks_repo_name": "bob-carpenter/case-studies", "max_forks_repo_head_hexsha": "d9ac886989b08629f5fcedf6c9e06f3f1f1faff8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T01:16:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-17T19:55:00.000Z", "avg_line_length": 25.9090909091, "max_line_length": 73, "alphanum_fraction": 0.5736842105, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.6238122277686612}}
{"text": "#include <blitz/array.h>\n#include <random/uniform.h>\n#include <bp_util.h>\n\nusing namespace blitz;\nusing namespace ranlib;\n\ntemplate <typename T>\nArray<T, 1> cnd(Array<T, 1> & x)\n{\n    int samples = x.numElements();\n    Array<T, 1> l(samples), k(samples), w(samples), res(samples);\n    Array<bool, 1> mask(samples);\n    T a1 = 0.31938153,\n      a2 =-0.356563782,\n      a3 = 1.781477937,\n      a4 =-1.821255978,\n      a5 = 1.330274429,\n      pp = 2.5066282746310002; // sqrt(2.0*PI)\n\n    l = abs(x);\n    k = 1.0 / (1.0 + 0.2316419 * l);\n    w = 1.0 - 1.0 / pp * exp(-1.0*l*l/2.0) * \\\n        (a1*k + \\\n         a2*(pow(k,(T)2)) + \\\n         a3*(pow(k,(T)3)) + \\\n         a4*(pow(k,(T)4)) + \\\n         a5*(pow(k,(T)5)));\n\n    mask    = x < 0.0;\n    res     = (w * cast<T>(!mask) + (1.0-w)* cast<T>(mask));\n    return res;\n}\n\ntemplate <typename T>\nT* pricing(size_t samples, size_t iterations, char flag, T x, T d_t, T r, T v)\n{\n    Array<T, 1> d1(samples), d2(samples), res(samples);\n    T* p    = (T*)malloc(sizeof(T)*samples);    // Intermediate results\n    T t     = d_t;                              // Initial delta\n\n    Array<T, 1> s(samples);                     // Initial uniform sampling\n    Uniform<T> rand;                            // values between 58-62\n    rand.seed((unsigned int)time(0));\n    s = rand.random() *4.0 +58.0;\n\n    for(size_t i=0; i<iterations; i++) {\n        d1 = (log(s/x) + (r+v*v/2.0)*t) / (v*sqrt(t));\n        d2 = d1-v*sqrt(t);\n        if (flag == 'c') {\n            res = s * cnd(d1) - x * exp(-r * t) * cnd(d2);\n        } else {\n            Array<T, 1> tmp1(samples), tmp2(samples);\n            tmp1 = -1.0*d2;\n            tmp2 = -1.0*d1;\n\n            res = x * exp(-r*t) * cnd(tmp1) - s*cnd(tmp2);\n        }\n        t += d_t;                               // Increment delta\n        p[i] = sum(res) / (T)samples;           // Result from timestep\n    }\n\n    return p;\n}\n\n//FLOP count: 2*s+i*(s*8+2*s*23) where s is samples and i is iterations\n\nint main(int argc, char* argv[])\n{\n    bp_util_type bp = bp_util_create(argc, argv, 2);\n    if (bp.args.has_error) {\n        return 1;\n    }\n    const size_t samples    = bp.args.sizes[0];\n    const size_t iterations = bp.args.sizes[1];\n\n    bp.timer_start();\n    double* prices = pricing(\n        samples, iterations,\n        'c', 65.0, 1.0 / 365.0,\n        0.08, 0.3\n    );\n    bp.timer_stop();\n    \n    bp.print(\"black_scholes(cpp11_blitz)\");\n    if (bp.args.verbose) {\n        cout << \", \\\"output\\\": [\";\n        for(size_t i=0; i<iterations; i++) {\n            cout << prices[i];\n            if (iterations-1!=i) {\n                cout << \", \";\n            }\n        }\n        cout << \"]\" << endl;\n    }\n\n    free(prices);\n    return 0;\n}\n\n\n", "meta": {"hexsha": "3ad007c742441a6b3e21395d91acb07f9d0ceac3", "size": 2727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchpress/benchmarks/black_scholes/cpp11_blitz/src/black_scholes.cpp", "max_stars_repo_name": "bh107/benchpress", "max_stars_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-03-31T15:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T21:30:49.000Z", "max_issues_repo_path": "benchpress/benchmarks/black_scholes/cpp11_blitz/src/black_scholes.cpp", "max_issues_repo_name": "bh107/benchpress", "max_issues_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-04-13T12:03:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-28T13:31:11.000Z", "max_forks_repo_path": "benchpress/benchmarks/black_scholes/cpp11_blitz/src/black_scholes.cpp", "max_forks_repo_name": "bh107/benchpress", "max_forks_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-06-28T08:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T17:30:25.000Z", "avg_line_length": 26.7352941176, "max_line_length": 78, "alphanum_fraction": 0.4756142281, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6237636926884541}}
{"text": "// find_root_example.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 root finding.\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//[root_find1\n/*`\nFirst we need some includes to access the normal distribution\n(and some std output of course).\n*/\n\n#include <boost/math/tools/roots.hpp> // root finding.\n\n#include <boost/math/distributions/normal.hpp> // for normal_distribution\n  using boost::math::normal; // typedef provides default type is double.\n\n#include <iostream>\n  using std::cout; using std::endl; using std::left; using std::showpoint; using std::noshowpoint;\n#include <iomanip>\n  using std::setw; using std::setprecision;\n#include <limits>\n  using std::numeric_limits;\n//] //[/root_find1]\n\nnamespace boost{ namespace math { namespace tools\n{\n\ntemplate <class F, class T, class Tol>\ninline std::pair<T, T> bracket_and_solve_root(F f, // functor \n                                              const T& guess,\n                                              const T& factor,\n                                              bool rising,\n                                              Tol tol, // binary functor specifying termination when tol(min, max) becomes true.\n                                              // eps_tolerance most suitable for this continuous function\n                                              boost::uintmax_t& max_iter); // explicit (rather than default) max iterations.\n// return interval as a pair containing result.\n\nnamespace detail\n{\n\n  // Functor for finding standard deviation:\n  template <class RealType, class Policy>\n  struct standard_deviation_functor\n  {\n     standard_deviation_functor(RealType m, RealType s, RealType d)\n        : mean(m), standard_deviation(s)\n     {\n     }\n     RealType operator()(const RealType& sd)\n     { // Unary functor - the function whose root is to be found.\n        if(sd <= tools::min_value<RealType>())\n        { // \n           return 1;\n        }\n        normal_distribution<RealType, Policy> t(mean, sd);\n        RealType qa = quantile(complement(t, alpha));\n        RealType qb = quantile(complement(t, beta));\n        qa += qb;\n        qa *= qa;\n        qa *= ratio;\n        qa -= (df + 1);\n        return qa;\n     } // operator()\n     RealType mean;\n     RealType standard_deviation;\n  }; // struct standard_deviation_functor\n} // namespace detail\n\ntemplate <class RealType, class Policy>\nRealType normal_distribution<RealType, Policy>::find_standard_deviation(\n      RealType difference_from_mean,\n      RealType mean,\n      RealType sd,\n      RealType hint) // Best guess available - current sd if none better?\n{\n   static const char* function = \"boost::math::normal_distribution<%1%>::find_standard_deviation\";\n\n   // Check for domain errors:\n   RealType error_result;\n   if(false == detail::check_probability(\n      function, sd, &error_result, Policy())\n      )\n      return error_result;\n\n   if(hint <= 0)\n   { // standard deviation can never be negative.\n      hint = 1;\n   }\n\n   detail::standard_deviation_functor<RealType, Policy> f(mean, sd, difference_from_mean);\n   tools::eps_tolerance<RealType> tol(policies::digits<RealType, Policy>());\n   boost::uintmax_t max_iter = 100;\n   std::pair<RealType, RealType> r = tools::bracket_and_solve_root(f, hint, RealType(2), false, tol, max_iter, Policy());\n   RealType result = r.first + (r.second - r.first) / 2;\n   if(max_iter == 100)\n   {\n      policies::raise_evaluation_error<RealType>(function, \"Unable to locate solution in a reasonable time:\"\n         \" either there is no answer to how many degrees of freedom are required\"\n         \" or the answer is infinite.  Current best guess is %1%\", result, Policy());\n   }\n   return result;\n} // find_standard_deviation\n} // namespace tools\n} // namespace math\n} // namespace boost\n\n\nint main()\n{\n  cout << \"Example: Normal distribution, root finding.\";\n  try\n  {\n\n//[root_find2\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//] [/root_find2]\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\nOutput is:\n\n\n\n*/\n", "meta": {"hexsha": "abcb936cb8640d11d5f4d3ccb96a7b7fe226dfeb", "size": 8882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/find_root_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_root_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_root_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": 37.0083333333, "max_line_length": 128, "alphanum_fraction": 0.6598739023, "num_tokens": 2311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6237636889166859}}
{"text": "// ========================================================================= //\n// Filename      :  test_neural_network.cpp\n// Creation Date :  2016-6-14\n// Created by    :  anfranek\n// ========================================================================= //\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\n#include <neural_network.h>\n\n/**\n * @brief TEST neural_network, NAND\n *\n * NAND implemented as neural network containing one neuron.\n */\nTEST(neural_network, NAND)\n{\n    NeuralNetwork<double, 2, 1> network;\n    network.getLayer<0>().weights << -2, -2;\n    network.getLayer<0>().biases << 3;\n\n    EXPECT_GT(network.feedforward(Eigen::Vector2d(0, 0))[0], 0.5);\n    EXPECT_GT(network.feedforward(Eigen::Vector2d(0, 1))[0], 0.5);\n    EXPECT_GT(network.feedforward(Eigen::Vector2d(1, 0))[0], 0.5);\n    EXPECT_LT(network.feedforward(Eigen::Vector2d(1, 1))[0], 0.5);\n}\n\n/**\n * @brief TEST neural_network, NAND_big_weights\n *\n * NAND implemented as neural network containing one neuron.\n * By using large weights and biases the results should be more distinct. I.e. 1 or 0.\n */\nTEST(neural_network, NAND_big_weights)\n{\n    NeuralNetwork<double, 2, 1> network;\n    network.getLayer<0>().weights << -2000, -2000;\n    network.getLayer<0>().biases << 3000;\n\n    EXPECT_DOUBLE_EQ(network.feedforward(Eigen::Vector2d(0, 0))[0], 1);\n    EXPECT_DOUBLE_EQ(network.feedforward(Eigen::Vector2d(0, 1))[0], 1);\n    EXPECT_DOUBLE_EQ(network.feedforward(Eigen::Vector2d(1, 0))[0], 1);\n    EXPECT_DOUBLE_EQ(network.feedforward(Eigen::Vector2d(1, 1))[0], 0);\n}\n\n/**\n * @brief TEST neural_network, two_bit_adder\n *\n * Two bit adder implemented as neural network.\n * The network is rather complicated since only fully connected networks are possible as of yet.\n */\nTEST(neural_network, two_bit_adder)\n{\n    NeuralNetwork<double, 2, 3, 3, 2> network;\n    network.getLayer<0>().weights << 1000, 0, -2000, -2000, 0, 1000;\n    network.getLayer<0>().biases << 0, 3000, 0;\n    network.getLayer<1>().weights << -2000, -2000, 0, 0, -2000, -2000, 0, 1000, 0;\n    network.getLayer<1>().biases << 3000, 3000, 0;\n    network.getLayer<2>().weights << -2000, -2000, 0, 0, 0, -4000;\n    network.getLayer<2>().biases << 3000, 3000;\n    EXPECT_EQ(network.feedforward(Eigen::Vector2d(-0.01, -0.01)), Eigen::Vector2d(0, 0));\n    EXPECT_EQ(network.feedforward(Eigen::Vector2d(-0.01, 1)), Eigen::Vector2d(1, 0));\n    EXPECT_EQ(network.feedforward(Eigen::Vector2d(1, -0.01)), Eigen::Vector2d(1, 0));\n    EXPECT_EQ(network.feedforward(Eigen::Vector2d(1, 1)), Eigen::Vector2d(0, 1));\n}\n", "meta": {"hexsha": "5c4fd67284ff2452f2aa02d5f5ddcdddc3a6efb7", "size": 2548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_neural_network.cpp", "max_stars_repo_name": "andy-held/gesture_recog", "max_stars_repo_head_hexsha": "2e7c0a399dbe0f4a02b37cd4ed42782b62018d10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_neural_network.cpp", "max_issues_repo_name": "andy-held/gesture_recog", "max_issues_repo_head_hexsha": "2e7c0a399dbe0f4a02b37cd4ed42782b62018d10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_neural_network.cpp", "max_forks_repo_name": "andy-held/gesture_recog", "max_forks_repo_head_hexsha": "2e7c0a399dbe0f4a02b37cd4ed42782b62018d10", "max_forks_repo_licenses": ["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.4705882353, "max_line_length": 96, "alphanum_fraction": 0.6334379906, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6237636873389638}}
{"text": "#pragma once\n\n#include <cmath>\n\n#ifdef __POPC__\n#undef USE_EIGEN\n#else\n#ifdef USE_EIGEN\n#include <Eigen/Dense>\n#endif\n#include <iostream>\n#endif\n\nnamespace light {\n\n#ifdef USE_EIGEN\nusing Vector = Eigen::Vector3f;\n#else\n  struct Vector {\n  float x, y, z;\n  Vector() {}\n  Vector(float x0, float y0, float z0) : x(x0), y(y0), z(z0) {}\n  Vector operator + (const Vector &b) const {\n    return Vector(x + b.x, y + b.y, z + b.z);\n  }\n  Vector& operator += (const Vector &b) {\n    x += b.x;\n    y += b.y;\n    z += b.z;\n    return *this;\n  }\n  Vector operator * (float b) const { return Vector(x*b, y*b, z*b); }\n  Vector& operator *= (float s) {\n    x *= s;\n    y *= s;\n    z *= s;\n    return *this;\n  }\n  Vector operator - (const Vector &b) const {\n    return Vector(x-b.x, y-b.y, z-b.z);\n  }\n  Vector operator - () const { return Vector(-x, -y, -z); }\n  Vector operator / (float b) const { return Vector(x/b, y/b, z/b); }\n  Vector cwiseProduct(const Vector &b) const {\n    return Vector(x*b.x, y*b.y, z*b.z);\n  }\n  Vector normalized() const { return *this * (1.f/sqrtf(x*x + y*y + z*z)); }\n  float squaredNorm() const { return x*x + y*y + z*z; }\n  float norm() const { return sqrtf(squaredNorm()); }\n  float dot(const Vector &b) const { return x*b.x + y*b.y + z*b.z; }\n  Vector cross(const Vector &b) const {\n    return Vector(y*b.z - z*b.y, z*b.x - x*b.z, x*b.y - y*b.x);\n  }\n  const float& operator () (size_t i) const { return i == 0 ? x : (i == 1 ? y : z); }\n  Vector abs() const {\n    return Vector(fabsf(x), fabsf(y), fabsf(z));\n  }\n  const Vector& array() const { return *this; } // For Eigen compatibility only\n  bool isZero() const { return x == 0.f && y == 0.f && z == 0.f; }\n  bool isNonZero() const { return x != 0.f || y != 0.f || z != 0.f; }\n};\n\n#endif\n\n} // end namespace light\n\n#ifndef __POPC__\n#ifndef USE_EIGEN\ninline\nstd::ostream& operator << (std::ostream &os, const light::Vector &v) {\n  os << v.x << \" \" << v.y << \" \" << v.z;\n  return os;\n}\n#endif\n#endif\n", "meta": {"hexsha": "d51d044bcdcb5550ea52a6317b35ef79e69d5831", "size": 1972, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/vector.hpp", "max_stars_repo_name": "mpups/light", "max_stars_repo_head_hexsha": "93f0212c40d86421014e676048f9ba59083da47b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/vector.hpp", "max_issues_repo_name": "mpups/light", "max_issues_repo_head_hexsha": "93f0212c40d86421014e676048f9ba59083da47b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vector.hpp", "max_forks_repo_name": "mpups/light", "max_forks_repo_head_hexsha": "93f0212c40d86421014e676048f9ba59083da47b", "max_forks_repo_licenses": ["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.9473684211, "max_line_length": 85, "alphanum_fraction": 0.5755578093, "num_tokens": 646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6237636773713313}}
{"text": "#include \"stdafx.h\"\r\n#include \"shape_sphere.h\"\r\n#include <boost/math/constants/constants.hpp>\r\n\r\nnamespace overdrive {\r\n\tnamespace render {\r\n\t\tnamespace shape {\r\n\t\t\tSphere::Sphere(\r\n\t\t\t\tfloat radius,\r\n\t\t\t\tunsigned int slices,\r\n\t\t\t\tunsigned int stacks\r\n\t\t\t):\r\n\t\t\t\tmVertexBuffer((slices + 1) * (stacks + 1)),\r\n\t\t\t\tmIndexBuffer((slices * 2 * (stacks - 1)) * 3)\r\n\t\t\t{\r\n\t\t\t\t{\r\n\t\t\t\t\tusing attributes::PositionNormalTexCoord;\r\n\t\t\t\t\tusing boost::math::float_constants::pi;\r\n\r\n\t\t\t\t\tfloat theta;\r\n\t\t\t\t\tfloat phi;\r\n\t\t\t\t\t\r\n\t\t\t\t\tfloat thetaFactor = 2.0f * pi / slices;\r\n\t\t\t\t\tfloat phiFactor = pi / stacks;\r\n\r\n\t\t\t\t\tglm::vec3 position;\r\n\t\t\t\t\tglm::vec3 normal;\r\n\t\t\t\t\tglm::vec2 texCoord;\r\n\r\n\t\t\t\t\tauto vertices = mVertexBuffer.map();\r\n\r\n\t\t\t\t\tunsigned int index = 0;\r\n\r\n\t\t\t\t\tfor (unsigned int i = 0; i <= slices; ++i) {\r\n\t\t\t\t\t\ttheta = i * thetaFactor;\r\n\r\n\t\t\t\t\t\ttexCoord.s = static_cast<float>(i) / stacks;\r\n\r\n\t\t\t\t\t\tfor (unsigned int j = 0; j <= stacks; ++j) {\r\n\t\t\t\t\t\t\tphi = j * phiFactor;\r\n\r\n\t\t\t\t\t\t\ttexCoord.t = static_cast<float>(j) / stacks;\r\n\r\n\t\t\t\t\t\t\tnormal.x = sinf(phi) * cosf(theta);\r\n\t\t\t\t\t\t\tnormal.y = sinf(phi) * sinf(theta);\r\n\t\t\t\t\t\t\tnormal.z = cosf(phi);\r\n\r\n\t\t\t\t\t\t\tposition = normal * radius;\r\n\r\n\t\t\t\t\t\t\tvertices[index++] = PositionNormalTexCoord{ position, normal, texCoord };\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t{\r\n\t\t\t\t\tauto indices = mIndexBuffer.map();\r\n\r\n\t\t\t\t\tunsigned int index = 0;\r\n\r\n\t\t\t\t\tfor (GLuint i = 0; i < slices; ++i) {\r\n\t\t\t\t\t\tGLuint stackStart = i * (stacks + 1);\r\n\t\t\t\t\t\tGLuint nextStackStart = (i + 1) * (stacks + 1);\r\n\r\n\t\t\t\t\t\tfor (GLuint j = 0; j < stacks; ++j) {\r\n\t\t\t\t\t\t\tif (j == 0) {\r\n\t\t\t\t\t\t\t\tindices[index    ] = stackStart;\r\n\t\t\t\t\t\t\t\tindices[index + 1] = stackStart + 1;\r\n\t\t\t\t\t\t\t\tindices[index + 2] = nextStackStart + 1;\r\n\r\n\t\t\t\t\t\t\t\tindex += 3;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if (j == (stacks - 1)) {\r\n\t\t\t\t\t\t\t\tindices[index    ] = stackStart + j;\r\n\t\t\t\t\t\t\t\tindices[index + 1] = stackStart + j + 1;\r\n\t\t\t\t\t\t\t\tindices[index + 2] = nextStackStart + j;\r\n\r\n\t\t\t\t\t\t\t\tindex += 3;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\tindices[index    ] = stackStart + j;\r\n\t\t\t\t\t\t\t\tindices[index + 1] = stackStart + j + 1;\r\n\t\t\t\t\t\t\t\tindices[index + 2] = nextStackStart + j + 1;\r\n\t\t\t\t\t\t\t\tindices[index + 3] = nextStackStart + j;\r\n\t\t\t\t\t\t\t\tindices[index + 4] = stackStart + j;\r\n\t\t\t\t\t\t\t\tindices[index + 5] = nextStackStart + j + 1;\r\n\r\n\t\t\t\t\t\t\t\tindex += 6;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tmVAO.attach(mIndexBuffer);\r\n\t\t\t\tmVAO.attach(mVertexBuffer);\r\n\t\t\t}\r\n\r\n\t\t\tvoid Sphere::draw() {\r\n\t\t\t\tmVAO.draw();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "meta": {"hexsha": "446afd34ae5c1e3aae12d0d73736eb41555d8e8c", "size": 2484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Overdrive/render/shape_sphere.cpp", "max_stars_repo_name": "png85/Overdrive", "max_stars_repo_head_hexsha": "e763827546354c7c75395ab1a82949a685ecb880", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T08:54:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-11T16:01:29.000Z", "max_issues_repo_path": "Overdrive/render/shape_sphere.cpp", "max_issues_repo_name": "png85/Overdrive", "max_issues_repo_head_hexsha": "e763827546354c7c75395ab1a82949a685ecb880", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-14T10:02:09.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-14T10:02:09.000Z", "max_forks_repo_path": "Overdrive/render/shape_sphere.cpp", "max_forks_repo_name": "png85/Overdrive", "max_forks_repo_head_hexsha": "e763827546354c7c75395ab1a82949a685ecb880", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-10-07T05:44:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T09:00:01.000Z", "avg_line_length": 24.3529411765, "max_line_length": 81, "alphanum_fraction": 0.5152979066, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.623753596740546}}
{"text": "#include <boost/math/constants/constants.hpp>\n#include \"EnergyResolutionInput.hh\"\n#include \"TypeClasses.hh\"\n#include \"TypesFunctions.hh\"\n#include <fmt/format.h>\n#include <string.h>\n\nconstexpr double pi = boost::math::constants::pi<double>();\n\nusing namespace TypeClasses;\n\nEnergyResolutionInput::EnergyResolutionInput(bool propagate_matrix) :\nHistSmearSparse(propagate_matrix)\n{\n  transformation_(\"matrix\")\n      .input(\"Edges\", /*inactive*/true)     // Input bin edges [N]\n      .input(\"RelSigma\")                    // Relative Sigma value for each bin center [N-1]\n      .output(\"FakeMatrix\")\n      .types(new CheckKindT<double>(DataKind::Hist, 0), new CheckKindT<double>(DataKind::Points, 1))\n      .types(new CheckNdimT<double>(1), new CheckSameTypesT<double>({0,1}, \"shape\"))\n      .types(TypesFunctions::toMatrix<0,0,0>)\n      .func(&EnergyResolutionInput::calcMatrix);\n\n  add_transformation();\n  add_input();\n  set_open_input();\n}\n\ndouble EnergyResolutionInput::resolution(double Etrue, double Erec, double RelSigma) const noexcept {\n  static const double twopisqr = std::sqrt(2*pi);\n  const double sigma = Etrue * RelSigma;\n  const double reldiff = (Etrue - Erec)/sigma;\n\n  return std::exp(-0.5*pow(reldiff, 2))/(twopisqr*sigma);\n}\n\nvoid EnergyResolutionInput::calcMatrix(FunctionArgs& fargs) {\n  m_sparse_cache.setZero();\n\n  auto& args = fargs.args;\n  auto* edges = args[0].type.edges.data();\n  auto& relsigmas = args[1].x;\n  auto& ret = fargs.rets[0];\n  size_t nbins = ret.type.shape[0];\n\n  m_sparse_cache.resize(nbins, nbins);\n\n  /* fill the cache matrix with probalilities for number of events to leak to other bins */\n  /* colums corressponds to reconstrucred energy and rows to true energy */\n  auto bin_center = [edges](size_t index){ return (edges[index+1] + edges[index])/2; };\n  for (size_t etrue = 0; etrue < nbins; ++etrue) {\n    auto Etrue   = bin_center(etrue);\n    auto dEtrue  = edges[etrue+1] - edges[etrue];\n    auto relsigma=relsigmas[etrue];\n\n    bool right_edge_reached{false};\n    /* precalculating probabilities for events in given bin to leak to\n     * neighbor bins  */\n    for (size_t erec = 0; erec < nbins; ++erec) {\n      auto Erec = bin_center(erec);\n      auto rEvents = dEtrue*resolution(Etrue, Erec, relsigma);\n\n      if (rEvents < 1E-10) {\n        if (right_edge_reached) {\n           break;\n        }\n        continue;\n      }\n      m_sparse_cache.insert(erec, etrue) = rEvents;\n      if (!right_edge_reached) {\n        right_edge_reached = true;\n      }\n    }\n  }\n  m_sparse_cache.makeCompressed();\n\n  if ( m_propagate_matrix )\n    fargs.rets[0].mat = m_sparse_cache;\n}\n", "meta": {"hexsha": "a02a1e0e14da5128e7416f496e7a141d61b5dbe7", "size": 2615, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/detector/EnergyResolutionInput.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/detector/EnergyResolutionInput.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/detector/EnergyResolutionInput.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": 32.6875, "max_line_length": 101, "alphanum_fraction": 0.6745697897, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.623744742642088}}
{"text": "#include <ros/ros.h>\n#include <geometry_msgs/PoseArray.h>\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <tf/transform_datatypes.h>\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <cmath>\n#include <cylbot_motion_model/multivariate_normal.h>\n#include <iostream>\n\n#define NUM_POSES 1000\n\ngeometry_msgs::PoseArray pose_array;\n\nEigen::internal::scalar_normal_dist_op<double> randN;\n//Eigen::internal::scalar_normal_dist_op<double>::rng.seed(1);\n\nvoid initialPoseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& pose_with_cov)\n{\n\tstd::cout << \"TESTING\" << std::endl;\n\tROS_INFO(\"Received a new pose\");\n\n\tEigen::VectorXd mean(3);\n\tEigen::MatrixXd covar(3, 3);\n\n\tmean << pose_with_cov->pose.pose.position.x,\n\t\tpose_with_cov->pose.pose.position.y,\n\t\ttf::getYaw(pose_with_cov->pose.pose.orientation);\n\tcovar << pose_with_cov->pose.covariance[0], 0,                                  0,\n\t\t     0,                                 pose_with_cov->pose.covariance[7],  0,\n\t\t     0,                            0,                                       pose_with_cov->pose.covariance[35];\n\n\tEigen::MatrixXd normTransform(3, 3);\n\tEigen::LLT<Eigen::MatrixXd> cholSolver(covar);\n\n\tif(cholSolver.info() == Eigen::Success)\n\t{\n\t\tnormTransform = cholSolver.matrixL();\n\t}\n\telse\n\t{\n\t\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigenSolver(covar);\n\t\tnormTransform = eigenSolver.eigenvectors() * eigenSolver.eigenvalues().cwiseSqrt().asDiagonal();\n\t}\n\n\tEigen::MatrixXd samples = (normTransform * Eigen::MatrixXd::NullaryExpr(3, NUM_POSES, randN)).colwise() + mean;\n\n\tROS_INFO_STREAM(\"\\nMean:\\n\" << mean << \"\\n\");\n\tROS_INFO_STREAM(\"\\nCov:\\n\" << covar << \"\\n\");\n\n\t// remove existing pose estimates\n\tpose_array.poses.clear();\n\tfor(int i=0; i<NUM_POSES; i++)\n\t{\n\t\tgeometry_msgs::Pose pose;\n\t\tpose.position.x = samples(0, i);\n\t\tpose.position.y = samples(1, i);\n\t\tpose.position.z = 0;\n\n\t\t// generate random yaw then convert it to a quaternion\n\t\tpose.orientation = tf::createQuaternionMsgFromRollPitchYaw(0, 0, samples(2, i));\n\t\t\n\t\tpose_array.poses.push_back(pose);\n\t}\n}\n\nint main(int argc, char** argv)\n{\n\tros::init(argc, argv, \"pose_array_test\");\n\tros::NodeHandle nh;\n\n\tros::Publisher pose_array_pub = nh.advertise<geometry_msgs::PoseArray>(\"pose_array_test\", 1);\n\tros::Subscriber initial_pose_sub = nh.subscribe<geometry_msgs::PoseWithCovarianceStamped>(\"/initialpose\", 10, &initialPoseCallback, ros::TransportHints().tcpNoDelay(false));\n\n\t// random number generator\n\tboost::mt19937 rng;\n\t\n\t// creates a normal distribution with 0 mean and std dev of 1\n\tboost::normal_distribution<> norm_dist(0.0, 1.0);\n\n\t// create a method of sampling the distribution\n\tboost::variate_generator<boost::mt19937, boost::normal_distribution<> > norm_rng(rng, norm_dist);\n\t\n\tpose_array.header.frame_id = \"/map\";\n\n\tros::Rate loop_rate(10);\n\twhile(ros::ok())\n\t{\n\t\tros::spinOnce();\n\t\t\n\t\tpose_array.header.stamp = ros::Time::now();\n\t\tpose_array_pub.publish(pose_array);\n\t\tloop_rate.sleep();\n\t}\n\t\n}\n", "meta": {"hexsha": "3940eb724879bdf1cb1f7b27548b545770ece52d", "size": 3015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cylbot_motion_model/src/pose_array_test.cpp", "max_stars_repo_name": "rhololkeolke/eecs_600_robot_project1", "max_stars_repo_head_hexsha": "8a4a567f436d2d26311b53cc2dcfde61d98e45e0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cylbot_motion_model/src/pose_array_test.cpp", "max_issues_repo_name": "rhololkeolke/eecs_600_robot_project1", "max_issues_repo_head_hexsha": "8a4a567f436d2d26311b53cc2dcfde61d98e45e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-08-22T13:33:39.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-23T23:01:57.000Z", "max_forks_repo_path": "src/cylbot_motion_model/src/pose_array_test.cpp", "max_forks_repo_name": "rhololkeolke/eecs_600_robot_project1", "max_forks_repo_head_hexsha": "8a4a567f436d2d26311b53cc2dcfde61d98e45e0", "max_forks_repo_licenses": ["BSD-3-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.0824742268, "max_line_length": 174, "alphanum_fraction": 0.6971807629, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6237447275169942}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n    This is an example illustrating the use of the epsilon-insensitive support vector \n    regression object from the dlib C++ Library.\n\n    In this example we will draw some points from the sinc() function and do a\n    non-linear regression on them.\n*/\n\n#include <iostream>\n#include <vector>\n\n#include <dlib/svm.h>\n\nusing namespace std;\nusing namespace dlib;\n\n// Here is the sinc function we will be trying to learn with the svr_trainer \n// object.\ndouble sinc(double x)\n{\n    if (x == 0)\n        return 1;\n    return sin(x)/x;\n}\n\nint main()\n{\n    // Here we declare that our samples will be 1 dimensional column vectors.  \n    typedef matrix<double,1,1> sample_type;\n\n    // Now we are making a typedef for the kind of kernel we want to use.  I picked the\n    // radial basis kernel because it only has one parameter and generally gives good\n    // results without much fiddling.\n    typedef radial_basis_kernel<sample_type> kernel_type;\n\n\n    std::vector<sample_type> samples;\n    std::vector<double> targets;\n\n    // The first thing we do is pick a few training points from the sinc() function.\n    sample_type m;\n    for (double x = -10; x <= 4; x += 1)\n    {\n        m(0) = x;\n\n        samples.push_back(m);\n        targets.push_back(sinc(x));\n    }\n\n    // Now setup a SVR trainer object.  It has three parameters, the kernel and\n    // two parameters specific to SVR.  \n    svr_trainer<kernel_type> trainer;\n    trainer.set_kernel(kernel_type(0.1));\n\n    // This parameter is the usual regularization parameter.  It determines the trade-off \n    // between trying to reduce the training error or allowing more errors but hopefully \n    // improving the generalization of the resulting function.  Larger values encourage exact \n    // fitting while smaller values of C may encourage better generalization.\n    trainer.set_c(10);\n\n    // Epsilon-insensitive regression means we do regression but stop trying to fit a data \n    // point once it is \"close enough\" to its target value.  This parameter is the value that \n    // controls what we mean by \"close enough\".  In this case, I'm saying I'm happy if the\n    // resulting regression function gets within 0.001 of the target value.\n    trainer.set_epsilon_insensitivity(0.001);\n\n    // Now do the training and save the results\n    decision_function<kernel_type> df = trainer.train(samples, targets);\n\n    // now we output the value of the sinc function for a few test points as well as the \n    // value predicted by SVR.\n    m(0) = 2.5; cout << sinc(m(0)) << \"   \" << df(m) << endl;\n    m(0) = 0.1; cout << sinc(m(0)) << \"   \" << df(m) << endl;\n    m(0) = -4;  cout << sinc(m(0)) << \"   \" << df(m) << endl;\n    m(0) = 5.0; cout << sinc(m(0)) << \"   \" << df(m) << endl;\n\n    // The output is as follows:\n    //  0.239389   0.23905\n    //  0.998334   0.997331\n    // -0.189201   -0.187636\n    // -0.191785   -0.218924\n\n    // The first column is the true value of the sinc function and the second\n    // column is the output from the SVR estimate.  \n\n    // We can also do 5-fold cross-validation and find the mean squared error and R-squared\n    // values.  Note that we need to randomly shuffle the samples first.  See the svm_ex.cpp \n    // for a discussion of why this is important. \n    randomize_samples(samples, targets);\n    cout << \"MSE and R-Squared: \"<< cross_validate_regression_trainer(trainer, samples, targets, 5) << endl;\n    // The output is: \n    // MSE and R-Squared: 1.65984e-05    0.999901\n}\n\n\n", "meta": {"hexsha": "a18edf24d50256640f44aa7bda7a4365c945868f", "size": 3568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/examples/svr_ex.cpp", "max_stars_repo_name": "maxmert/nlp-mitie", "max_stars_repo_head_hexsha": "ec3153ef2fe7a80e7cf3d80d14b388b8cd679343", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "examples/svr_ex.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "examples/svr_ex.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 36.7835051546, "max_line_length": 108, "alphanum_fraction": 0.6670403587, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6237014288385555}}
{"text": "/* \r\n   Copyright (c) Marshall Clow 2014.\r\n\r\n   Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n   file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n    For more information, see http://www.boost.org\r\n*/\r\n\r\n#include <iostream>\r\n#include <functional>\r\n\r\n#include <boost/config.hpp>\r\n#include <boost/algorithm/algorithm.hpp>\r\n\r\n#define BOOST_TEST_MAIN\r\n#include <boost/test/unit_test.hpp>\r\n\r\nnamespace ba = boost::algorithm;\r\n\r\nvoid test_power ()\r\n{\r\n    BOOST_CHECK ( ba::power(0, 0) == 1);\r\n    BOOST_CHECK ( ba::power(5, 0) == 1);\r\n    BOOST_CHECK ( ba::power(1, 1) == 1);\r\n    BOOST_CHECK ( ba::power(1, 4) == 1);\r\n    BOOST_CHECK ( ba::power(3, 2) == 9);\r\n    BOOST_CHECK ( ba::power(2, 3) == 8);\r\n    BOOST_CHECK ( ba::power(3, 3) == 27);\r\n    BOOST_CHECK ( ba::power(2, 30) == 0x40000000);\r\n    BOOST_CHECK ( ba::power(5L, 10) == 3125*3125);\r\n    BOOST_CHECK ( ba::power(18, 3) == 18*18*18);\r\n    \r\n    BOOST_CHECK ( ba::power(3,2) == ba::power(3,2, std::multiplies<int>()));\r\n    BOOST_CHECK ( ba::power(3,2, std::plus<int>()) == 6);\r\n}\r\n\r\n\r\nvoid test_power_constexpr ()\r\n{\r\n    BOOST_CXX14_CONSTEXPR bool check_zero_power1 =\r\n        ba::power(0, 0) == 1;\r\n    BOOST_CHECK(check_zero_power1);\r\n    BOOST_CXX14_CONSTEXPR bool check_zero_power2 =\r\n        ba::power(5, 0) == 1;\r\n    BOOST_CHECK(check_zero_power2);\r\n    BOOST_CXX14_CONSTEXPR bool check_one_base1 =\r\n        ba::power(1, 1) == 1;\r\n    BOOST_CHECK(check_one_base1);\r\n    BOOST_CXX14_CONSTEXPR bool check_one_base2 =\r\n        ba::power(1, 4) == 1;\r\n    BOOST_CHECK(check_one_base2);\r\n    BOOST_CXX14_CONSTEXPR bool check_power1 = \r\n        ba::power(3, 2) == 9;\r\n    BOOST_CHECK(check_power1);\r\n    BOOST_CXX14_CONSTEXPR bool check_power2 = \r\n        ba::power(2, 3) == 8;\r\n    BOOST_CHECK(check_power2);\r\n    BOOST_CXX14_CONSTEXPR bool check_power3 = \r\n        ba::power(3, 3) == 27;\r\n    BOOST_CHECK(check_power3);\r\n    BOOST_CXX14_CONSTEXPR bool check_power4 = \r\n        ba::power(2, 30) == 0x40000000;\r\n    BOOST_CHECK(check_power4);\r\n    BOOST_CXX14_CONSTEXPR bool check_power5 = \r\n        ba::power(5L, 10) == 3125*3125;\r\n    BOOST_CHECK(check_power5);\r\n    BOOST_CXX14_CONSTEXPR bool check_power6 = \r\n        ba::power(18, 3) == 18*18*18;\r\n    BOOST_CHECK(check_power6);\r\n    \r\n    BOOST_CXX14_CONSTEXPR bool check_multiple = \r\n        ba::power(3, 2, std::multiplies<int>()) == ba::power(3, 2);\r\n    BOOST_CHECK(check_multiple);\r\n    BOOST_CXX14_CONSTEXPR bool check_plus = \r\n        ba::power(3, 2, std::plus<int>()) == 6;\r\n    BOOST_CHECK(check_plus);\r\n}\r\n\r\n\r\nBOOST_AUTO_TEST_CASE( test_main ) {\r\n  test_power ();\r\n  test_power_constexpr ();\r\n}\r\n", "meta": {"hexsha": "138f59ad6c1032c86b05d0f0890e42bdcdc250ef", "size": 2678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/algorithm/test/power_test.cpp", "max_stars_repo_name": "Talustus/boost_src", "max_stars_repo_head_hexsha": "ffe074de008f6e8c46ae1f431399cf932164287f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/algorithm/test/power_test.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "third_party/boost/libs/algorithm/test/power_test.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 31.5058823529, "max_line_length": 80, "alphanum_fraction": 0.6277072442, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6237014217033576}}
{"text": "//\n// Created by Federico Vaccaro on 30/11/2018.\n#include <iostream>\n#include <string>\n#include <random>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <iterator>\n\n#include <sstream>\n#include <cmath>\n#include <iomanip>\n#include <boost/algorithm/string.hpp>\n#include <stdlib.h>\n\n#include \"csvio.h\"\n\n\n\nint main() {\n    const int nData = 183*324;  // number of experiments\n\n    std::default_random_engine generator;\n\n    std::vector<std::normal_distribution<float>> centroids;\n\n    std::normal_distribution<float> X0(3.0, 0.2);\n    std::normal_distribution<float> Y0(3.0, 0.5);\n\n    std::normal_distribution<float> X1(15.0, 1.0);\n    std::normal_distribution<float> Y1(17.0, 0.2);\n\n    std::normal_distribution<float> X2(10.5, 1.5);\n    std::normal_distribution<float> Y2(0.0, 1.5);\n\n    centroids.push_back(X0);\n    centroids.push_back(Y0);\n    centroids.push_back(X1);\n    centroids.push_back(Y1);\n    centroids.push_back(X2);\n    centroids.push_back(Y2);\n\n    std::vector<float> points;\n\n    const int nCentroids = centroids.size()/2;\n\n    points.resize(nData * 2);\n\n    for (int i = 0; i < nData; ++i) {\n        int centroid = i % nCentroids;\n        std::normal_distribution<float> X_i = centroids[centroid*2];\n        std::normal_distribution<float> Y_i = centroids[centroid*2 + 1];\n        int idx = i * 2;\n        points[idx] = X_i(generator);\n        points[idx+1] = Y_i(generator);\n\n    }\n    std::string delimiter = \";\";\n    std::string filename = \"../dataset.csv\";\n    write2VecTo(filename.c_str(), delimiter, points);\n    //read2VecFrom(filename.c_str(), delimiter, points);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "74bff4b8f86f3e0d2dbc0b28f80b2b73b1161e46", "size": 1623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CUDA_MeanShift/generator.cpp", "max_stars_repo_name": "fede-vaccaro/CUDA_MeanShift", "max_stars_repo_head_hexsha": "873f6b6f50b950f19c14ed1c89785dd0c3877128", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-04-13T05:11:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T14:20:42.000Z", "max_issues_repo_path": "CUDA_MeanShift/generator.cpp", "max_issues_repo_name": "fede-vaccaro/CUDA_MeanShift", "max_issues_repo_head_hexsha": "873f6b6f50b950f19c14ed1c89785dd0c3877128", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CUDA_MeanShift/generator.cpp", "max_forks_repo_name": "fede-vaccaro/CUDA_MeanShift", "max_forks_repo_head_hexsha": "873f6b6f50b950f19c14ed1c89785dd0c3877128", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T16:11:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-09T16:17:23.000Z", "avg_line_length": 24.223880597, "max_line_length": 72, "alphanum_fraction": 0.6531115219, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6236524233756814}}
{"text": "/*\ncompare the distribution from sampling result \nwith the original probabilistic distribution\nby using Earth Mover's Distance(EMD).\n\nGiven two probability density function a and b, the EMD is calculated as follows:\n\n  EMD(a, b) := integral_{x=-inf}^{+inf} { | A(x) - B(x) | }\nwhere A and B is cumulative distribution function of a and b. \n\n*/\n\n#include <map>\n#include <string>\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <numeric>\n#include <algorithm>\n#include <tuple>\n#include <random>\n\n#include <EigenRand/EigenRand>\n\ntemplate<typename ArrTy, typename PdfFn>\ndouble calc_emd_with_pdf(ArrTy&& arr, const std::tuple<PdfFn, double, double>& cdf_range, size_t step)\n{\n\tdouble ret = 0;\n\tauto arr_begin = arr.data();\n\tauto arr_end = arr_begin + arr.size();\n\tstd::sort(arr_begin, arr_end);\n\tconst auto& pdf = std::get<0>(cdf_range);\n\tconst auto& lb = std::get<1>(cdf_range), &rb = std::get<2>(cdf_range);\n\n\tEigen::ArrayXd cdf{ step };\n\tdouble acc = 0;\n\tfor (size_t i = 0; i < step; ++i)\n\t{\n\t\tconst double x = lb + (rb - lb) * i / step;\n\t\tcdf[i] = acc;\n\t\tacc += pdf(x);\n\t}\n\tcdf /= acc;\n\n\tsize_t arr_p = 0;\n\tfor (size_t i = 0; i < step; ++i)\n\t{\n\t\tconst double x = lb + (rb - lb) * i / step;\n\t\tarr_p = std::find_if(arr_begin + arr_p, arr_end, [&](double a) { return a > x; }) - arr_begin;\n\t\tdouble arr_cum = (double)arr_p / arr.size();\n\t\tret += std::abs(cdf[i] - arr_cum);\n\t}\n\treturn ret * (rb - lb) / step;\n}\n\ntemplate<typename ArrTy, typename CdfFn>\ndouble calc_emd_with_cdf(ArrTy&& arr, const std::tuple<CdfFn, double, double>& cdf_range, size_t step)\n{\n\tdouble ret = 0;\n\tauto arr_begin = arr.data();\n\tauto arr_end = arr_begin + arr.size();\n\tstd::sort(arr_begin, arr_end);\n\tconst auto& cdf = std::get<0>(cdf_range);\n\tconst auto& lb = std::get<1>(cdf_range), &rb = std::get<2>(cdf_range);\n\n\tsize_t arr_p = 0;\n\tfor (size_t i = 0; i < step; ++i)\n\t{\n\t\tconst double x = lb + (rb - lb) * i / step;\n\t\tarr_p = std::find_if(arr_begin + arr_p, arr_end, [&](double a) { return a > x; }) - arr_begin;\n\t\tdouble arr_cum = (double)arr_p / arr.size();\n\t\tret += std::abs(cdf(x) - arr_cum);\n\t}\n\treturn ret * (rb - lb) / step;\n}\n\n\ntemplate<typename ArrTy, typename PmfFn>\ndouble calc_kldiv(ArrTy&& arr, const std::tuple<PmfFn, int, int>& pmf_range)\n{\n\tdouble ret = 0;\n\tconst auto& pmf = std::get<0>(pmf_range);\n\tconst auto& b = std::get<1>(pmf_range), e = std::get<2>(pmf_range);\n\tEigen::ArrayXd p{ e - b + 1 }, q{ e - b + 1};\n\tp.setZero();\n\tfor (int i = 0; i < arr.size(); ++i)\n\t{\n\t\tif (arr[i] < b || arr[i] > e) continue;\n\t\tp[arr[i] - b] += 1;\n\t}\n\tp /= arr.size();\n\t\n\tfor (int i = b; i <= e; ++i) q[i - b] = pmf(i);\n\tq /= q.sum();\n\n\treturn (((p / q) + 1e-12).log() * p).sum();\n}\n\n\ndouble gamma_dist(double x, double alpha, double beta)\n{\n\tif (x <= 0) return 0;\n\treturn std::exp(-x / beta)\n\t\t/ (std::tgamma(alpha) * std::pow(beta, alpha))\n\t\t* std::pow(x, alpha - 1);\n}\n\ndouble chisquared_dist(double x, double n)\n{\n\tif (x <= 0) return 0;\n\treturn std::pow(x, n / 2 - 1) * std::exp(-x / 2) \n\t\t/ std::pow(2, n / 2) / std::tgamma(n / 2);\n}\n\ndouble student_t_dist(double x, double n)\n{\n\treturn std::pow(1 + x * x /n, -(n + 1) / 2);\n}\n\ndouble fisher_f_dist(double x, double m, double n)\n{\n\tif (x <= 0) return 0;\n\treturn std::sqrt((std::pow(m * x, m) * std::pow(n, n)) / std::pow(m * x + n, m + n)) / x;\n}\n\ndouble combination(int n, int c)\n{\n\tif (n == 0 || n == 1 || c == 0 || c == n) return 1;\n\tc = std::min(c, n - c);\n\t\n\tdouble ret = 1;\n\tfor (int i = 0; i < c; ++i)\n\t{\n\t\tret *= (n - i);\n\t\tret /= i + 1;\n\t}\n\treturn ret;\n}\n\ndouble binomial_dist(int x, int n, double p)\n{\n\treturn combination(n, x) * std::pow(p, x) * std::pow(1 - p, n - x);\n}\n\ndouble negative_binomial_dist(int x, int n, double p)\n{\n\treturn combination(n + x - 1, x) * std::pow(1 - p, x);\n}\n\nauto balanced_cdf = std::make_tuple([](double x) { return (x + 1) / 2; }, -1., 1.);\nauto ur_cdf = std::make_tuple([](double x) { return x; }, 0., 1.);\nauto normal_cdf = std::make_tuple([](double x) { return (1 + std::erf(x / std::sqrt(2))) / 2; }, -8., 8.);\nauto lognormal_cdf = std::make_tuple([](double x) { return (1 + std::erf(std::log(x) / std::sqrt(2))) / 2; }, 0., 4.);\nauto exp_cdf = std::make_tuple([](double x) { return 1 - std::exp(-x); }, 0., 32.);\nauto weibull_cdf = std::make_tuple([](double x) { return 1 - std::exp(-std::pow(x, 2)); }, 0., 32.);\nauto extreme_value_cdf = std::make_tuple([](double x) { return std::exp(-std::exp(1 - x)); }, -8., 24.);\nauto gamma11_pdf = std::make_tuple([](double x) { return gamma_dist(x, 1, 1); }, 0., 16.);\nauto gamma51_pdf = std::make_tuple([](double x) { return gamma_dist(x, 5, 1); }, 0., 16.);\nauto gamma21_pdf = std::make_tuple([](double x) { return gamma_dist(x, 0.2, 1); }, 0., 16.);\nauto chisquared_pdf = std::make_tuple([](double x) { return chisquared_dist(x, 7); }, 0., 64.);\nauto cauchy_cdf = std::make_tuple([](double x) { return std::atan(x) / Eigen::Rand::constant::pi + 0.5; }, -16., 16.);\nauto student5_pdf = std::make_tuple([](double x) { return student_t_dist(x, 5); }, -8., 8.);\nauto student20_pdf = std::make_tuple([](double x) { return student_t_dist(x, 20); }, -8., 8.);\nauto fisher11_cdf = std::make_tuple([](double x) { return 2 * std::atan(std::sqrt(x)) / Eigen::Rand::constant::pi; }, 0., 256.);\nauto fisher55_pdf = std::make_tuple([](double x) { return fisher_f_dist(x, 5, 5); }, 0., 16.);\n\nauto uniform10_pmf = std::make_tuple([](int x) { return 1; }, 0, 9);\nauto discrete_pmf = std::make_tuple([](int x) { return x + 1; }, 0, 5);\nauto poisson1_pmf = std::make_tuple([](int x) { return std::pow(1, x) / std::tgamma(x + 1); }, 0, 127);\nauto poisson16_pmf = std::make_tuple([](int x) { return std::pow(16, x) / std::tgamma(x + 1); }, 0, 127);\nauto binomial1_pmf = std::make_tuple([](int x) { return binomial_dist(x, 10, 0.5); }, 0, 10);\nauto binomial2_pmf = std::make_tuple([](int x) { return binomial_dist(x, 30, 0.75); }, 0, 30);\nauto binomial3_pmf = std::make_tuple([](int x) { return binomial_dist(x, 50, 0.25); }, 0, 50);\nauto negbinomial1_pmf = std::make_tuple([](int x) { return negative_binomial_dist(x, 10, 0.5); }, 0, 127);\nauto negbinomial2_pmf = std::make_tuple([](int x) { return negative_binomial_dist(x, 20, 0.25); }, 0, 127);\nauto negbinomial3_pmf = std::make_tuple([](int x) { return negative_binomial_dist(x, 30, 0.75); }, 0, 127);\nauto geometric25_pmf = std::make_tuple([](int x) { return std::pow(1 - 0.25, x); }, 0, 127);\nauto geometric75_pmf = std::make_tuple([](int x) { return std::pow(1 - 0.75, x); }, 0, 127);\n\ntemplate<typename Rng>\nstd::map<std::string, double> test_eigenrand_cont(size_t size, size_t step, size_t seed)\n{\n\tstd::map<std::string, double> ret;\n\tEigen::ArrayXf arr{ size };\n\tRng urng{ seed };\n\n\tarr = Eigen::Rand::balancedLike(arr, urng);\n\tret[\"balanced\"] = calc_emd_with_cdf(arr, balanced_cdf, step);\n\n\tarr = Eigen::Rand::uniformRealLike(arr, urng);\n\tret[\"uniformReal\"] = calc_emd_with_cdf(arr, ur_cdf, step);\n\n\tarr = Eigen::Rand::normalLike(arr, urng);\n\tret[\"normal\"] = calc_emd_with_cdf(arr, normal_cdf, step);\n\n\tarr = Eigen::Rand::lognormalLike(arr, urng);\n\tret[\"lognormal\"] = calc_emd_with_cdf(arr, lognormal_cdf, step);\n\n\tarr = Eigen::Rand::gammaLike(arr, urng, 1, 1);\n\tret[\"gamma(1,1)\"] = calc_emd_with_pdf(arr, gamma11_pdf, step);\n\n\tarr = Eigen::Rand::gammaLike(arr, urng, 5, 1);\n\tret[\"gamma(5,1)\"] = calc_emd_with_pdf(arr, gamma51_pdf, step);\n\n\tarr = Eigen::Rand::gammaLike(arr, urng, 0.2, 1);\n\tret[\"gamma(0.2,1)\"] = calc_emd_with_pdf(arr, gamma21_pdf, step);\n\n\tarr = Eigen::Rand::exponentialLike(arr, urng);\n\tret[\"exponential\"] = calc_emd_with_cdf(arr, exp_cdf, step);\n\n\tarr = Eigen::Rand::weibullLike(arr, urng, 2);\n\tret[\"weibull(2,1)\"] = calc_emd_with_cdf(arr, weibull_cdf, step);\n\n\tarr = Eigen::Rand::extremeValueLike(arr, urng, 1, 1);\n\tret[\"extremeValue(1,1)\"] = calc_emd_with_cdf(arr, extreme_value_cdf, step);\n\n\tarr = Eigen::Rand::chiSquaredLike(arr, urng, 7);\n\tret[\"chiSquared(7)\"] = calc_emd_with_pdf(arr, chisquared_pdf, step);\n\n\tarr = Eigen::Rand::cauchyLike(arr, urng);\n\tret[\"cauchy\"] = calc_emd_with_cdf(arr, cauchy_cdf, step);\n\n\tarr = Eigen::Rand::studentTLike(arr, urng, 1);\n\tret[\"studentT(1)\"] = calc_emd_with_cdf(arr, cauchy_cdf, step);\n\n\tarr = Eigen::Rand::studentTLike(arr, urng, 5);\n\tret[\"studentT(5)\"] = calc_emd_with_pdf(arr, student5_pdf, step);\n\n\tarr = Eigen::Rand::studentTLike(arr, urng, 20);\n\tret[\"studentT(20)\"] = calc_emd_with_pdf(arr, student20_pdf, step);\n\n\tarr = Eigen::Rand::fisherFLike(arr, urng, 1, 1);\n\tret[\"fisherF(1,1)\"] = calc_emd_with_cdf(arr, fisher11_cdf, step);\n\n\tarr = Eigen::Rand::fisherFLike(arr, urng, 5, 5);\n\tret[\"fisherF(5,5)\"] = calc_emd_with_pdf(arr, fisher55_pdf, step);\n\n#ifdef TEST_DOUBLE\n\tEigen::ArrayXd arrd{ size };\n\tarrd = Eigen::Rand::uniformRealLike(arrd, urng);\n\tret[\"uniformReal/double\"] = calc_emd_with_cdf(arrd, ur_cdf, step);\n\n\tarrd = Eigen::Rand::normalLike(arrd, urng);\n\tret[\"normal/double\"] = calc_emd_with_cdf(arrd, normal_cdf, step);\n\n\tarrd = Eigen::Rand::lognormalLike(arrd, urng);\n\tret[\"lognormal/double\"] = calc_emd_with_cdf(arrd, lognormal_cdf, step);\n\n\tarrd = Eigen::Rand::gammaLike(arrd, urng, 1, 1);\n\tret[\"gamma(1,1)/double\"] = calc_emd_with_pdf(arrd, gamma11_pdf, step);\n\n\tarrd = Eigen::Rand::gammaLike(arrd, urng, 5, 1);\n\tret[\"gamma(5,1)/double\"] = calc_emd_with_pdf(arrd, gamma51_pdf, step);\n\n\tarrd = Eigen::Rand::gammaLike(arrd, urng, 0.2, 1);\n\tret[\"gamma(0.2,1)/double\"] = calc_emd_with_pdf(arrd, gamma21_pdf, step);\n\n\tarrd = Eigen::Rand::exponentialLike(arrd, urng);\n\tret[\"exponential/double\"] = calc_emd_with_cdf(arrd, exp_cdf, step);\n\n\tarrd = Eigen::Rand::weibullLike(arrd, urng, 2);\n\tret[\"weibull(2,1)/double\"] = calc_emd_with_cdf(arrd, weibull_cdf, step);\n\n\tarrd = Eigen::Rand::extremeValueLike(arrd, urng, 1, 1);\n\tret[\"extremeValue(1,1)/double\"] = calc_emd_with_cdf(arrd, extreme_value_cdf, step);\n\n\tarrd = Eigen::Rand::chiSquaredLike(arrd, urng, 7);\n\tret[\"chiSquared(7)/double\"] = calc_emd_with_pdf(arrd, chisquared_pdf, step);\n\n\tarrd = Eigen::Rand::cauchyLike(arrd, urng);\n\tret[\"cauchy/double\"] = calc_emd_with_cdf(arrd, cauchy_cdf, step);\n\n\tarrd = Eigen::Rand::studentTLike(arrd, urng, 1);\n\tret[\"studentT(1)/double\"] = calc_emd_with_cdf(arrd, cauchy_cdf, step);\n\n\tarrd = Eigen::Rand::studentTLike(arrd, urng, 5);\n\tret[\"studentT(5)/double\"] = calc_emd_with_pdf(arrd, student5_pdf, step);\n\n\tarrd = Eigen::Rand::studentTLike(arrd, urng, 20);\n\tret[\"studentT(20)/double\"] = calc_emd_with_pdf(arrd, student20_pdf, step);\n\n\tarrd = Eigen::Rand::fisherFLike(arrd, urng, 1, 1);\n\tret[\"fisherF(1,1)/double\"] = calc_emd_with_cdf(arrd, fisher11_cdf, step);\n\n\tarrd = Eigen::Rand::fisherFLike(arrd, urng, 5, 5);\n\tret[\"fisherF(5,5)/double\"] = calc_emd_with_pdf(arrd, fisher55_pdf, step);\n#endif\n\treturn ret;\n}\n\ntemplate<typename Rng>\nstd::map<std::string, double> test_eigenrand_disc(size_t size, size_t step, size_t seed)\n{\n\tstd::map<std::string, double> ret;\n\tEigen::ArrayXi arri{ size };\n\tRng urng{ seed };\n\n\tarri = Eigen::Rand::uniformIntLike(arri, urng, 0, 9);\n\tret[\"uniformInt(0,9)\"] = calc_kldiv(arri, uniform10_pmf);\n\n\tarri = Eigen::Rand::discreteLike(arri, urng, { 1, 2, 3, 4, 5, 6 });\n\tret[\"discrete(1,2,3,4,5,6)\"] = calc_kldiv(arri, discrete_pmf);\n\n\tarri = Eigen::Rand::poissonLike(arri, urng, 1);\n\tret[\"poisson(1)\"] = calc_kldiv(arri, poisson1_pmf);\n\n\tarri = Eigen::Rand::poissonLike(arri, urng, 16);\n\tret[\"poisson(16)\"] = calc_kldiv(arri, poisson16_pmf);\n\n\tarri = Eigen::Rand::binomialLike(arri, urng, 10, 0.5);\n\tret[\"binomial(10,0.5)\"] = calc_kldiv(arri, binomial1_pmf);\n\n\tarri = Eigen::Rand::binomialLike(arri, urng, 30, 0.75);\n\tret[\"binomial(30,0.75)\"] = calc_kldiv(arri, binomial2_pmf);\n\n\tarri = Eigen::Rand::binomialLike(arri, urng, 50, 0.25);\n\tret[\"binomial(50,0.25)\"] = calc_kldiv(arri, binomial3_pmf);\n\n\tarri = Eigen::Rand::negativeBinomialLike(arri, urng, 10, 0.5);\n\tret[\"negativeBinomial(10,0.5)\"] = calc_kldiv(arri, negbinomial1_pmf);\n\n\tarri = Eigen::Rand::negativeBinomialLike(arri, urng, 20, 0.25);\n\tret[\"negativeBinomial(20,0.25)\"] = calc_kldiv(arri, negbinomial2_pmf);\n\n\tarri = Eigen::Rand::negativeBinomialLike(arri, urng, 30, 0.75);\n\tret[\"negativeBinomial(30,0.75)\"] = calc_kldiv(arri, negbinomial3_pmf);\n\n\tarri = Eigen::Rand::geometricLike(arri, urng, 0.25);\n\tret[\"geometric(0.25)\"] = calc_kldiv(arri, geometric25_pmf);\n\n\tarri = Eigen::Rand::geometricLike(arri, urng, 0.75);\n\tret[\"geometric(0.75)\"] = calc_kldiv(arri, geometric75_pmf);\n\treturn ret;\n}\n\nstd::map<std::string, double> test_old(size_t size, size_t step, size_t seed)\n{\n\tstd::map<std::string, double> ret;\n\tEigen::ArrayXf arr{ size };\n\n\tarr = Eigen::ArrayXf::Random(size);\n\tret[\"balanced\"] = calc_emd_with_cdf(arr, balanced_cdf, step);\n\treturn ret;\n}\n\nstd::map<std::string, double> test_cpp11_cont(size_t size, size_t step, size_t seed)\n{\n\tstd::map<std::string, double> ret;\n\tEigen::ArrayXf arr{ size };\n\tEigen::ArrayXd arrd{ size };\n\tstd::mt19937_64 urng{ seed };\n\n\t{\n\t\tstd::uniform_real_distribution<float> dist;\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"uniformReal\"] = calc_emd_with_cdf(arr, ur_cdf, step);\n\t\n\t{\n\t\tstd::uniform_real_distribution<double> dist;\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"uniformReal/double\"] = calc_emd_with_cdf(arrd, ur_cdf, step);\n\n\t{\n\t\tstd::normal_distribution<> dist;\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"normal\"] = calc_emd_with_cdf(arr, normal_cdf, step);\n\n\t{\n\t\tstd::normal_distribution<double> dist;\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"normal/double\"] = calc_emd_with_cdf(arrd, normal_cdf, step);\n\n\t{\n\t\tstd::lognormal_distribution<> dist;\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"lognormal\"] = calc_emd_with_cdf(arr, lognormal_cdf, step);\n\n\t{\n\t\tstd::lognormal_distribution<double> dist;\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"lognormal/double\"] = calc_emd_with_cdf(arrd, lognormal_cdf, step);\n\n\t{\n\t\tstd::gamma_distribution<> dist{ 1, 1 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"gamma(1,1)\"] = calc_emd_with_pdf(arr, gamma11_pdf, step);\n\n\t{\n\t\tstd::gamma_distribution<double> dist{ 1, 1 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"gamma(1,1)/double\"] = calc_emd_with_pdf(arrd, gamma11_pdf, step);\n\n\t{\n\t\tstd::gamma_distribution<> dist{ 5, 1 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"gamma(5,1)\"] = calc_emd_with_pdf(arr, gamma51_pdf, step);\n\n\t{\n\t\tstd::gamma_distribution<double> dist{ 5, 1 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"gamma(5,1)/double\"] = calc_emd_with_pdf(arrd, gamma51_pdf, step);\n\n\t{\n\t\tstd::gamma_distribution<> dist{ 0.2, 1 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"gamma(0.2,1)\"] = calc_emd_with_pdf(arr, gamma21_pdf, step);\n\n\t{\n\t\tstd::gamma_distribution<double> dist{ 0.2, 1 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"gamma(0.2,1)/double\"] = calc_emd_with_pdf(arrd, gamma21_pdf, step);\n\n\t{\n\t\tstd::exponential_distribution<> dist;\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"exponential\"] = calc_emd_with_cdf(arr, exp_cdf, step);\n\n\t{\n\t\tstd::exponential_distribution<double> dist;\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"exponential/double\"] = calc_emd_with_cdf(arrd, exp_cdf, step);\n\n\t{\n\t\tstd::weibull_distribution<> dist{ 2, 1 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"weibull(2,1)\"] = calc_emd_with_cdf(arr, weibull_cdf, step);\n\n\t{\n\t\tstd::weibull_distribution<double> dist{ 2, 1 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"weibull(2,1)/double\"] = calc_emd_with_cdf(arrd, weibull_cdf, step);\n\n\t{\n\t\tstd::extreme_value_distribution<> dist{ 1, 1 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"extremeValue(1,1)\"] = calc_emd_with_cdf(arr, extreme_value_cdf, step);\n\n\t{\n\t\tstd::extreme_value_distribution<double> dist{ 1, 1 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"extremeValue(1,1)/double\"] = calc_emd_with_cdf(arrd, extreme_value_cdf, step);\n\n\t{\n\t\tstd::chi_squared_distribution<> dist{ 7 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"chiSquared(7)\"] = calc_emd_with_pdf(arr, chisquared_pdf, step);\n\n\t{\n\t\tstd::chi_squared_distribution<double> dist{ 7 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"chiSquared(7)/double\"] = calc_emd_with_pdf(arrd, chisquared_pdf, step);\n\n\t{\n\t\tstd::cauchy_distribution<> dist{ 0, 1 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"cauchy\"] = calc_emd_with_cdf(arr, cauchy_cdf, step);\n\n\t{\n\t\tstd::cauchy_distribution<double> dist{ 0, 1 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"cauchy/double\"] = calc_emd_with_cdf(arrd, cauchy_cdf, step);\n\n\t{\n\t\tstd::student_t_distribution<> dist{ 1 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"studentT(1)\"] = calc_emd_with_cdf(arr, cauchy_cdf, step);\n\n\t{\n\t\tstd::student_t_distribution<double> dist{ 1 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"studentT(1)/double\"] = calc_emd_with_cdf(arrd, cauchy_cdf, step);\n\n\t{\n\t\tstd::student_t_distribution<> dist{ 5 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"studentT(5)\"] = calc_emd_with_pdf(arr, student5_pdf, step);\n\n\t{\n\t\tstd::student_t_distribution<double> dist{ 5 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"studentT(5)/double\"] = calc_emd_with_pdf(arrd, student5_pdf, step);\n\n\t{\n\t\tstd::student_t_distribution<> dist{ 20 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"studentT(20)\"] = calc_emd_with_pdf(arr, student20_pdf, step);\n\n\t{\n\t\tstd::student_t_distribution<double> dist{ 20 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"studentT(20)/double\"] = calc_emd_with_pdf(arrd, student20_pdf, step);\n\n\t{\n\t\tstd::fisher_f_distribution<> dist{ 1, 1 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"fisherF(1,1)\"] = calc_emd_with_cdf(arr, fisher11_cdf, step);\n\n\t{\n\t\tstd::fisher_f_distribution<double> dist{ 1, 1 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"fisherF(1,1)/double\"] = calc_emd_with_cdf(arrd, fisher11_cdf, step);\n\n\t{\n\t\tstd::fisher_f_distribution<> dist{ 5, 5 };\n\t\tarr = Eigen::ArrayXf::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"fisherF(5,5)\"] = calc_emd_with_pdf(arr, fisher55_pdf, step);\n\n\t{\n\t\tstd::fisher_f_distribution<double> dist{ 5, 5 };\n\t\tarrd = Eigen::ArrayXd::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"fisherF(5,5)/double\"] = calc_emd_with_pdf(arrd, fisher55_pdf, step);\n\treturn ret;\n}\n\nstd::map<std::string, double> test_cpp11_disc(size_t size, size_t step, size_t seed)\n{\n\tstd::map<std::string, double> ret;\n\tEigen::ArrayXi arri{ size };\n\tstd::mt19937_64 urng{ seed };\n\n\t{\n\t\tstd::uniform_int_distribution<> dist{ 0, 9 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"uniformInt(0,9)\"] = calc_kldiv(arri, uniform10_pmf);\n\n\t{\n\t\tstd::discrete_distribution<> dist{ 1, 2, 3, 4, 5, 6 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"discrete(1,2,3,4,5,6)\"] = calc_kldiv(arri, discrete_pmf);\n\n\t{\n\t\tstd::poisson_distribution<> dist{ 1 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"poisson(1)\"] = calc_kldiv(arri, poisson1_pmf);\n\n\t{\n\t\tstd::poisson_distribution<> dist{ 16 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"poisson(16)\"] = calc_kldiv(arri, poisson16_pmf);\n\n\t{\n\t\tstd::binomial_distribution<> dist{ 10, 0.5 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"binomial(10,0.5)\"] = calc_kldiv(arri, binomial1_pmf);\n\n\t{\n\t\tstd::binomial_distribution<> dist{ 30, 0.75 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"binomial(30,0.75)\"] = calc_kldiv(arri, binomial2_pmf);\n\n\t{\n\t\tstd::binomial_distribution<> dist{ 50, 0.25 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"binomial(50,0.25)\"] = calc_kldiv(arri, binomial3_pmf);\n\n\t{\n\t\tstd::negative_binomial_distribution<> dist{ 10, 0.5 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"negativeBinomial(10,0.5)\"] = calc_kldiv(arri, negbinomial1_pmf);\n\n\t{\n\t\tstd::negative_binomial_distribution<> dist{ 20, 0.25 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"negativeBinomial(20,0.25)\"] = calc_kldiv(arri, negbinomial2_pmf);\n\n\t{\n\t\tstd::negative_binomial_distribution<> dist{ 30, 0.75 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"negativeBinomial(30,0.75)\"] = calc_kldiv(arri, negbinomial3_pmf);\n\n\t{\n\t\tstd::geometric_distribution<> dist{ 0.25 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"geometric(0.25)\"] = calc_kldiv(arri, geometric25_pmf);\n\n\t{\n\t\tstd::geometric_distribution<> dist{ 0.75 };\n\t\tarri = Eigen::ArrayXi::NullaryExpr(size, [&]() { return dist(urng); });\n\t}\n\tret[\"geometric(0.75)\"] = calc_kldiv(arri, geometric75_pmf);\n\treturn ret;\n}\n\nint main(int argc, char** argv)\n{\n\tsize_t size = 32768, step = size * 8, repeat = 50;\n\n\tif (argc > 1) size = std::stoi(argv[1]);\n\tif (argc > 2) step = std::stoi(argv[2]);\n\n\tstd::map<std::string, double> err, errSq, kl, klSq;\n\n\tfor (size_t i = 0; i < repeat; ++i)\n\t{\n\t\tstd::cout << \"Repeat \" << i << \" ...\" << std::endl;\n\t\tfor (auto& p : test_eigenrand_cont<std::mt19937_64>(size, step, 42 * i))\n\t\t{\n\t\t\terr[p.first + \"\\t:EigenRand\"] += p.second;\n\t\t\terrSq[p.first + \"\\t:EigenRand\"] += p.second * p.second;\n\t\t}\n\n\t\tfor (auto& p : test_eigenrand_disc<std::mt19937_64>(size, step, 42 * i))\n\t\t{\n\t\t\tkl[p.first + \"\\t:EigenRand\"] += p.second;\n\t\t\tklSq[p.first + \"\\t:EigenRand\"] += p.second * p.second;\n\t\t}\n\n#if defined(EIGEN_VECTORIZE_SSE2) || defined(EIGEN_VECTORIZE_AVX) || defined(EIGEN_VECTORIZE_NEON)\n\t\tfor (auto& p : test_eigenrand_cont<Eigen::Rand::Vmt19937_64>(size, step, 42 * i))\n\t\t{\n\t\t\terr[p.first + \"\\t:ERand+Vrng\"] += p.second;\n\t\t\terrSq[p.first + \"\\t:ERand+Vrng\"] += p.second * p.second;\n\t\t}\n\n\t\tfor (auto& p : test_eigenrand_disc<Eigen::Rand::Vmt19937_64>(size, step, 42 * i))\n\t\t{\n\t\t\tkl[p.first + \"\\t:ERand+Vrng\"] += p.second;\n\t\t\tklSq[p.first + \"\\t:ERand+Vrng\"] += p.second * p.second;\n\t\t}\n#endif\n#ifndef SKIP_REFERENCE\n\t\tfor (auto& p : test_cpp11_cont(size, step, 42 * i))\n\t\t{\n\t\t\terr[p.first + \"\\t:C++11\"] += p.second;\n\t\t\terrSq[p.first + \"\\t:C++11\"] += p.second * p.second;\n\t\t}\n\n\t\tfor (auto& p : test_cpp11_disc(size, step, 42 * i))\n\t\t{\n\t\t\tkl[p.first + \"\\t:C++11\"] += p.second;\n\t\t\tklSq[p.first + \"\\t:C++11\"] += p.second * p.second;\n\t\t}\n\n\t\tfor (auto& p : test_old(size, step, 42 * i))\n\t\t{\n\t\t\terr[p.first + \"\\t:Old\"] += p.second;\n\t\t\terrSq[p.first + \"\\t:Old\"] += p.second * p.second;\n\t\t}\n#endif\n\t}\n\n\tstd::cout << \"[Earth Mover's Distance] Mean (Stdev)\" << std::endl;\n\tfor (auto& p : err)\n\t{\n\t\tdouble mean = p.second / repeat;\n\t\tdouble var = (errSq[p.first] / repeat) - mean * mean;\n\t\tsize_t sp = p.first.find('\\t');\n\t\tstd::cout << std::left << std::setw(28) << p.first.substr(0, sp);\n\t\tstd::cout << std::setw(14) << p.first.substr(sp + 1);\n\t\tstd::cout << \": \" << mean << \" (\" << std::sqrt(var) << \")\" << std::endl;\n\t}\n\tstd::cout << std::endl;\n\tstd::cout << \"[KL Divergence] Mean (Stdev)\" << std::endl;\n\tfor (auto& p : kl)\n\t{\n\t\tdouble mean = p.second / repeat;\n\t\tdouble var = (klSq[p.first] / repeat) - mean * mean;\n\t\tsize_t sp = p.first.find('\\t');\n\t\tstd::cout << std::left << std::setw(28) << p.first.substr(0, sp);\n\t\tstd::cout << std::setw(14) << p.first.substr(sp + 1);\n\t\tstd::cout << \": \" << mean << \" (\" << std::sqrt(var) << \")\" << std::endl;\n\t}\n\tstd::cout << std::endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "e40770af0f66af749a74b2aeb8ba122e7ffc35c6", "size": 24197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/accuracy.cpp", "max_stars_repo_name": "bab2min/EigenRand", "max_stars_repo_head_hexsha": "be563c3abc65864e8c8c70a444a374bbb9b70825", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 59.0, "max_stars_repo_stars_event_min_datetime": "2020-06-25T15:13:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T14:28:27.000Z", "max_issues_repo_path": "benchmark/accuracy.cpp", "max_issues_repo_name": "bab2min/EigenRand", "max_issues_repo_head_hexsha": "be563c3abc65864e8c8c70a444a374bbb9b70825", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2020-10-03T15:39:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:39:15.000Z", "max_forks_repo_path": "benchmark/accuracy.cpp", "max_forks_repo_name": "bab2min/EigenRand", "max_forks_repo_head_hexsha": "be563c3abc65864e8c8c70a444a374bbb9b70825", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T14:04:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:41:12.000Z", "avg_line_length": 34.1283497884, "max_line_length": 128, "alphanum_fraction": 0.644460057, "num_tokens": 8570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6236524055370067}}
{"text": "#ifndef _ECO_UTIL_HPP_\n#define _ECO_UTIL_HPP_\n\n#include <iostream>\n#include <string>\n#include <math.h>\n#include <algorithm>\n#include <complex>\n#include <opencv2/opencv.hpp>\n#include <Eigen/Dense>\n#include \"ffttools.hpp\"\n#include \"matrix_operator.hpp\"\n\nnamespace eco_tracker {\n\ntypedef std::vector<std::vector<Eigen::MatrixXcf> > EcoFeats;\n\nEcoFeats runFFt(const EcoFeats &xlw);\n\nvoid genGaussianYf(\n    const float& sigma_y,\n    const float& T_size,\n    const std::vector<Eigen::MatrixXcf>& k_x,\n    const std::vector<Eigen::MatrixXcf>& k_y,\n    std::vector<Eigen::MatrixXcf>& y_f);\n\nvoid genCosWindow(\n    const int& row,\n    const int& col,\n    Eigen::MatrixXcf& cos_window);\n\nEcoFeats initInterpolateFFt(\n    const EcoFeats& xlf,\n    const std::vector<Eigen::MatrixXcf>& interp1_fs,\n    const std::vector<Eigen::MatrixXcf>& interp2_fs);\n\nEcoFeats interpolateDFT(\n    const EcoFeats& xlf,\n    const std::vector<Eigen::MatrixXcf>& interp1_fs,\n    const std::vector<Eigen::MatrixXcf>& interp2_fs);\n\nEcoFeats computeFeautrePower(const EcoFeats &feats);\n\nEcoFeats compactFourierCoeff(const EcoFeats &xf);\n\nEcoFeats fullFourierCoeff(const EcoFeats &xf);\n\nstd::vector<Eigen::MatrixXcf> vectorFeature(const EcoFeats &x);\n\nvoid initProjectionMatrix(\n    const EcoFeats& init_sample,\n\tconst std::vector<int>& compressed_dim,\n    std::vector<Eigen::MatrixXcf>& project_matrix);\n\nEcoFeats projectFeature(\n    const EcoFeats& x, \n    const std::vector<Eigen::MatrixXcf>& project_matrix);\n\nEcoFeats projectFeatureMultScale(\n    const EcoFeats& x, \n    const std::vector<Eigen::MatrixXcf>& project_matrix);\n\nEcoFeats EcoFeatureDotDivide(\n    const EcoFeats &a,\n    const EcoFeats &b);\n\nstd::complex<float> EcoFeatInnerProduct(\n    const EcoFeats& f1,\n    const EcoFeats& f2);\n\nEcoFeats shiftSample(EcoFeats &xf,\n                     float x,\n                     float y,\n                     std::vector<Eigen::MatrixXcf> kx,\n                     std::vector<Eigen::MatrixXcf> ky);\n\nstd::vector<Eigen::MatrixXcf> getProjectMatEnergy(\n    const std::vector<Eigen::MatrixXcf> project_mat,\n    const std::vector<int>& feature_dim,\n\tconst std::vector<Eigen::MatrixXcf>& yf);\n\n} // namespace eco_tracker\n#endif", "meta": {"hexsha": "ef6429f19bc1169c25c84f2d6c77870171faf8b4", "size": 2194, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "app/inc/eco_util.hpp", "max_stars_repo_name": "lygbuaa/eco_tracker", "max_stars_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-04-20T05:38:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-08T06:30:41.000Z", "max_issues_repo_path": "app/inc/eco_util.hpp", "max_issues_repo_name": "lygbuaa/eco_tracker", "max_issues_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-06T11:12:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-10T11:27:12.000Z", "max_forks_repo_path": "app/inc/eco_util.hpp", "max_forks_repo_name": "lygbuaa/eco_tracker", "max_forks_repo_head_hexsha": "d77afb97d356769bfe5f7d9cb5e96b3cf40c4601", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-07-12T03:47:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T06:44:17.000Z", "avg_line_length": 26.4337349398, "max_line_length": 63, "alphanum_fraction": 0.7078395624, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137298, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.6236515848318408}}
{"text": "#include <Eigen/Dense>\n#include <matplotlibcpp.h>\n#include <vector>\n\nnamespace plt = matplotlibcpp;\nusing namespace Eigen;\n\nint main(){\n    using std::vector;\n\n    int n = 5000;\n    Eigen::VectorXd x(n), y(n), z(n), w = Eigen::VectorXd::Ones(n);\n    for (int i = 0; i < n; ++i)\n    {\n        double value = (1.0 + i) / n;\n        x(i) = value;\n        y(i) = value * value;\n        z(i) = value * value * value;\n    }\n\n    vector<double> xs(n), ys(n), zs(n), ws(n);\n\n    Map<VectorXd>(&xs[0], n) = x;\n    Map<VectorXd>(&ys[0], n) = y;\n    Map<VectorXd>(&zs[0], n) = z;\n    Map<VectorXd>(&ws[0], n) = w;\n\n    plt::loglog(xs, ys);                             // f(x) = x^2\n    plt::loglog(xs, ws, \"r--\");                      // f(x) = 1, red dashed line\n    plt::loglog(xs, zs, \"g:\"); // f(x) = x^3, green dots + label\n\n    plt::title(\"Some functions of $x$\"); // add a title\n\n    plt::save(\"sample_eigen2.png\");\n\n    return 0;\n}", "meta": {"hexsha": "4bbf7344085ccb5bfbc23f4c5a221c7829e6a014", "size": 928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/vis_eigen_vector_revised.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/vis_eigen_vector_revised.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/vis_eigen_vector_revised.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": 25.0810810811, "max_line_length": 81, "alphanum_fraction": 0.4892241379, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.623593377660767}}
{"text": "#include <armadillo>\n#include <iostream>\n\nusing namespace arma;\n\nint main(int argc, char *argv[]) {\n    if (argc < 2) {\n        std::cerr << \"# error: no file specified\" << std::endl;\n        return 1;\n    }\n    mat A;\n    A.load(argv[1], raw_ascii);\n    A.print(\"A:\");\n    std::cout << \"det(A) = \" << det(A) << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "a32a6d4f33009a35574def5f2ab50d3917c4b97e", "size": 339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Armadillo/read_matrix.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Armadillo/read_matrix.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Armadillo/read_matrix.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 19.9411764706, "max_line_length": 63, "alphanum_fraction": 0.5250737463, "num_tokens": 103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.737158174177441, "lm_q1q2_score": 0.6235933768193838}}
{"text": "#include <Eigen/Core>\n\nextern \"C\" double my_norm( double x, double y, double z )\n{\n  return ::Eigen::Vector3d{ x, y, z }.norm();\n}\n", "meta": {"hexsha": "d882fc4ff6e5c923b5a17a4daac4270d3895535f", "size": 131, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "example/my_norm.cxx", "max_stars_repo_name": "usagi/vcpkg_chii", "max_stars_repo_head_hexsha": "69d8fd635b77bdfa5a6035964e3425a8fa49d8c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T02:31:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-30T02:31:15.000Z", "max_issues_repo_path": "example/my_norm.cxx", "max_issues_repo_name": "usagi/vcpkg_chii", "max_issues_repo_head_hexsha": "69d8fd635b77bdfa5a6035964e3425a8fa49d8c6", "max_issues_repo_licenses": ["MIT"], "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/my_norm.cxx", "max_forks_repo_name": "usagi/vcpkg_chii", "max_forks_repo_head_hexsha": "69d8fd635b77bdfa5a6035964e3425a8fa49d8c6", "max_forks_repo_licenses": ["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.7142857143, "max_line_length": 57, "alphanum_fraction": 0.6335877863, "num_tokens": 41, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.6235807008469949}}
{"text": "\n// solving A * X = B\n// using driver function gesv()\n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/atlas/cblas.hpp>\n#include <boost/numeric/bindings/atlas/clapack.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/std_vector.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef std::complex<double> cmpx; \n\n#ifndef F_ROW_MAJOR\ntypedef ublas::matrix<double, ublas::column_major> m_t;\ntypedef ublas::matrix<cmpx, ublas::column_major> cm_t;\n#else\ntypedef ublas::matrix<double, ublas::row_major> m_t;\ntypedef ublas::matrix<cmpx, ublas::row_major> cm_t;\n#endif\n\nint main() {\n\n  cout << endl; \n  cout << \"real system:\" << endl << endl; \n\n  size_t n = 5;   \n  m_t a (n, n);   // system matrix \n\n  size_t nrhs = 2; \n  m_t x (n, nrhs); \n  // b -- right-hand side matrix:\n  // .. see leading comments for `gesv()' in clapack.hpp\n#ifndef F_ROW_MAJOR\n  m_t b (n, nrhs);\n#else\n  m_t b (nrhs, n);\n#endif\n\n  std::vector<int> ipiv (n);  // pivot vector\n\n  init_symm (a); \n  //     [n   n-1 n-2  ... 1]\n  //     [n-1 n   n-1  ... 2]\n  // a = [n-2 n-1 n    ... 3]\n  //     [        ...       ]\n  //     [1   2   ...  n-1 n]\n\n  m_t aa (a);  // copy of a, because a is `lost' after gesv()\n\n  ublas::matrix_column<m_t> xc0 (x, 0), xc1 (x, 1); \n  atlas::set (1., xc0);  // x[.,0] = 1\n  atlas::set (2., xc1);  // x[.,1] = 2\n#ifndef F_ROW_MAJOR\n  atlas::gemm (a, x, b);  // b = a x, so we know the result ;o) \n#else\n  // see leading comments for `gesv()' in clapack.hpp\n  ublas::matrix_row<m_t> br0 (b, 0), br1 (b, 1); \n  atlas::gemv (a, xc0, br0);  // b[0,.] = a x[.,0]\n  atlas::gemv (a, xc1, br1);  // b[1,.] = a x[.,1]  =>  b^T = a x\n#endif \n\n  print_m (a, \"A\"); \n  cout << endl; \n  print_m (b, \"B\"); \n  cout << endl; \n\n  atlas::gesv (a, ipiv, b);   // solving the system, b contains x \n  print_m (b, \"X\"); \n  cout << endl; \n\n#ifndef F_ROW_MAJOR\n  atlas::gemm (aa, b, x);     // check the solution \n#else\n  atlas::gemv (aa, br0, xc0);\n  atlas::gemv (aa, br1, xc1);\n#endif \n  print_m (x, \"B = A X\"); \n  cout << endl; \n\n  ////////////////////////////////////////////////////////\n\n  cout << endl; \n  cout << \"complex system:\" << endl << endl; \n  cm_t ca (3, 3);\n  cm_t cx (3, 1);\n#ifndef F_ROW_MAJOR\n  cm_t cb (3, 1);\n#else\n  cm_t cb (1, 3); \n#endif  \n\n  ca (0, 0) = cmpx (3, 0);\n  ca (0, 1) = cmpx (4, 2);\n  ca (0, 2) = cmpx (-7, 5);\n  ca (1, 0) = cmpx (4, -2);\n  ca (1, 1) = cmpx (-5, 0);\n  ca (1, 2) = cmpx (0, -3);\n  ca (2, 0) = cmpx (-7, -5);\n  ca (2, 1) = cmpx (0, 3);\n  ca (2, 2) = cmpx (2, 0);\n  print_m (ca, \"CA\"); \n  cout << endl; \n  cm_t caa (ca); \n  \n  ublas::matrix_column<cm_t> cx0 (cx, 0);\n  atlas::set (cmpx (1, -1), cx0);\n#ifndef F_ROW_MAJOR\n  ublas::matrix_column<cm_t> cb0 (cb, 0); \n#else\n  ublas::matrix_row<cm_t> cb0 (cb, 0); \n#endif\n  atlas::gemv (ca, cx0, cb0); \n  print_m (cb, \"CB\"); \n  cout << endl; \n  \n  int ierr = atlas::gesv (ca, cb); // with `internal' pivot vector\n  if (ierr == 0) {\n    print_m (cb, \"CX\");\n    cout << endl; \n    atlas::gemv (caa, cb0, cx0);\n    print_m (cx, \"CB\");\n  }\n  else\n    cout << \"matrix is singular\" << endl; \n\n  cout << endl; \n}\n\n", "meta": {"hexsha": "b91e94e892ef7af28d794045c2a99f656784790b", "size": 3440, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_gesv.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 24.0559440559, "max_line_length": 66, "alphanum_fraction": 0.5625, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.623386847861272}}
{"text": "\n#include \"eigen_gpu.h\"\n#include \"args.h\"\n\n#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET\n#include <Eigen/Eigen>\n#include <Eigen/Sparse>\n\n//----( randomization )-------------------------------------------------------\n\ninline float random_real () { return tanf(3 * (random_std() - 0.5f)); }\n\nvoid randomize (Vector<float> & x)\n{\n  for (size_t i = 0; i < x.size; ++i) {\n    x[i] = random_real();\n  }\n}\n\nvoid randomize (VectorXf & x)\n{\n  for (int i = 0; i < x.size(); ++i) {\n    x[i] = random_real();\n  }\n}\n\nvoid randomize (MatrixXf & x)\n{\n  for (int j = 0; j < x.cols(); ++j) {\n  for (int i = 0; i < x.rows(); ++i) {\n    x(i,j) = random_real();\n  }}\n}\n\nvoid randomize (MatrixSf & mat, float density)\n{\n  ASSERT_LT(0, density);\n  ASSERT_LT(density, 1);\n\n  Eigen::DynamicSparseMatrix<float> temp(mat.rows(), mat.cols());\n\n  const size_t X = mat.rows();\n  const size_t Y = mat.cols();\n\n  size_t num_entries = ceil(density * mat.rows() * mat.cols());\n  for (size_t e = 0; e < num_entries; ++e) {\n\n    int x,y;\n    do {\n      int xy = random_choice(X*Y);\n      x = xy % X;\n      y = xy / X;\n    } while (temp.coeff(x,y) > 0);\n\n    temp.coeffRef(x,y) = random_real();\n  }\n\n  mat = temp;\n}\n\n//----( tests )---------------------------------------------------------------\n\nvoid test_dense_matrix_matrix (\n    int rows,\n    int cols,\n    int width,\n    size_t iters,\n    bool trans_A,\n    bool trans_B)\n{\n  LOG(\"\\nTesting dense matrix-matrix product\"\n      << \" (op(A) = \" << (trans_A ? \"A\" : \"A'\")\n      << \", op(B) = \" << (trans_B ? \"B\" : \"B'\")\n      << \")\");\n\n  MatrixXf lhs(rows, cols);   randomize(lhs);\n  MatrixXf rhs(cols, width);  randomize(rhs);\n\n  if (trans_A) lhs.transposeInPlace();\n  if (trans_B) rhs.transposeInPlace();\n\n  //DEBUG(\"\")\n  //PRINT4(rows, cols, lhs.rows(), lhs.cols());\n\n  MatrixXf cpu_prod(rows, width);\n  MatrixXf gpu_prod(rows, width);\n\n  float speedup = 1;\n  {\n    Timer timer;\n\n    for (size_t i = 0; i < iters; ++i) {\n      if (trans_A) {\n        if (trans_B) cpu_prod = lhs.transpose() * rhs.transpose();\n        else         cpu_prod = lhs.transpose() * rhs;\n      } else {\n        if (trans_B) cpu_prod = lhs * rhs.transpose();\n        else         cpu_prod = lhs * rhs;\n      }\n    }\n\n    float rate = iters / timer.elapsed();\n    float gflops = rate * rows * cols * width * 1e-9f;\n    LOG(\"Cpu performed \" << rate << \" mul/sec = \" << gflops << \" gflops\");\n    speedup /= rate;\n  }\n\n  {\n    Timer timer;\n\n    for (size_t i = 0; i < iters; ++i) {\n      Gpu::matrix_multiply(lhs, trans_A, rhs, trans_B, gpu_prod);\n    }\n\n    float rate = iters / timer.elapsed();\n    float gflops = rate * rows * cols * width * 1e-9f;\n    LOG(\"Gpu performed \" << rate << \" mul/sec = \" << gflops << \" gflops\");\n    speedup *= rate;\n    PRINT(speedup);\n  }\n\n  //PRINT(as_vector(lhs));\n  //PRINT(as_vector(rhs));\n  //PRINT(as_vector(cpu_prod));\n  //PRINT(as_vector(gpu_prod));\n\n  float rms_lhs = lhs.norm() / sqrtf(lhs.size());\n  float rms_rhs = rhs.norm() / sqrtf(rhs.size());\n  float rms_error = (cpu_prod - gpu_prod).norm() / sqrtf(cpu_prod.size());\n  PRINT(rms_error);\n  ASSERTW_LT(rms_error, 1e-6f * rms_lhs * rms_rhs);\n}\n\nvoid test_sparse_matrix_vector (\n    int rows,\n    int cols,\n    float density,\n    size_t iters,\n    bool trans)\n{\n  LOG(\"\\nTesting sparse matrix-vector product\"\n      << (trans ? \" (transposed)\" : \"\"));\n\n  MatrixSf sparse(rows, cols);\n  randomize(sparse, density);\n\n  Gpu::SparseMultiplier multiply(sparse, 1);\n\n  VectorXf rhs(trans ? rows : cols);\n  randomize(rhs);\n\n  VectorXf cpu_prod(trans ? cols : rows);\n  VectorXf gpu_prod(trans ? cols : rows);\n\n  float speedup = 1;\n  {\n    Timer timer;\n\n    for (size_t i = 0; i < iters; ++i) {\n      if (trans) cpu_prod = sparse.transpose() * rhs;\n      else cpu_prod = sparse * rhs;\n    }\n\n    float rate = iters / timer.elapsed();\n    float gflops = rate * rows * cols * density * 1e-9f;\n    LOG(\"Cpu performed \" << rate << \" mul/sec = \" << gflops << \" gflops\");\n    speedup /= rate;\n  }\n\n  {\n    Timer timer;\n\n    for (size_t i = 0; i < iters; ++i) {\n      multiply.left_mul(rhs, gpu_prod, trans);\n    }\n\n    float rate = iters / timer.elapsed();\n    float gflops = rate * rows * cols * density * 1e-9f;\n    LOG(\"Gpu performed \" << rate << \" mul/sec = \" << gflops << \" gflops\");\n    speedup *= rate;\n    PRINT(speedup);\n  }\n\n  float rms_sparse = sparse.norm() / sqrtf(sparse.size());\n  float rms_rhs = rhs.norm() / sqrtf(rhs.size());\n  float rms_error = (cpu_prod - gpu_prod).norm() / sqrtf(cpu_prod.size());\n  PRINT(rms_error);\n  ASSERTW_LT(rms_error, 1e-6f * rms_sparse * rms_rhs);\n}\n\nvoid test_sparse_matrix_matrix (\n    int rows,\n    int cols,\n    int width,\n    float density,\n    size_t iters,\n    bool trans)\n{\n  LOG(\"\\nTesting sparse matrix-matrix product\"\n      << (trans ? \" (transposed)\" : \"\"));\n\n  MatrixSf sparse(rows, cols);\n  randomize(sparse, density);\n\n  Gpu::SparseMultiplier multiply(sparse, 64);\n\n  MatrixXf rhs(trans ? rows : cols, width);\n  randomize(rhs);\n\n  MatrixXf cpu_prod(trans ? cols : rows, width);\n  MatrixXf gpu_prod(trans ? cols : rows, width);\n\n  float speedup = 1;\n  {\n    Timer timer;\n\n    for (size_t i = 0; i < iters; ++i) {\n      if (trans) cpu_prod = sparse.transpose() * rhs;\n      else cpu_prod = sparse * rhs;\n    }\n\n    float rate = iters / timer.elapsed();\n    float gflops = rate * rows * cols * width * density * 1e-9f;\n    LOG(\"Cpu performed \" << rate << \" mul/sec = \" << gflops << \" gflops\");\n    speedup /= rate;\n  }\n\n  {\n    Timer timer;\n\n    for (size_t i = 0; i < iters; ++i) {\n      multiply.left_mul(rhs, gpu_prod, trans);\n    }\n\n    float rate = iters / timer.elapsed();\n    float gflops = rate * rows * cols * width * density * 1e-9f;\n    LOG(\"Gpu performed \" << rate << \" mul/sec = \" << gflops << \" gflops\");\n    speedup *= rate;\n    PRINT(speedup);\n  }\n\n  float rms_sparse = sparse.norm() / sqrtf(sparse.size());\n  float rms_rhs = rhs.norm() / sqrtf(rhs.size());\n  float rms_error = (cpu_prod - gpu_prod).norm() / sqrtf(cpu_prod.size());\n  PRINT(rms_error);\n  ASSERTW_LT(rms_error, 1e-6f * rms_sparse * rms_rhs);\n}\n\n//----( main )----------------------------------------------------------------\n\nconst char * help_message =\n\"Usage: eigen_gpu_test [ROWS] [COLS] [WIDTH] [DENSITY] [ITERS]\"\n;\n\nint main (int argc, char ** argv)\n{\n  Args args(argc, argv, help_message);\n  LOG(help_message);\n\n  int rows = args.pop(2048);\n  int cols = args.pop(4096);\n  int width = args.pop(1024);\n  float density = args.pop(0.01f);\n  size_t iters = args.pop(1);\n  PRINT5(rows, cols, width, density, iters);\n  // Test results below were generated with\n  // rows = 2048, cols = 4096, density = 0.01, iters = 1\n\n  test_sparse_matrix_vector(rows, cols, density, iters, false);\n  // Cpu performed 4830.92 mul/sec = 0.405247 gflops\n  // Gpu performed 242.131 mul/sec = 0.0203114 gflops\n  // rms_error = 0.0110587\n\n  test_sparse_matrix_vector(rows, cols, density, iters, true);\n  // Cpu performed 5780.35 mul/sec = 0.484891 gflops\n  // Gpu performed 14705.9 mul/sec = 1.23362 gflops\n  // rms_error = 0.00113682\n\n  test_sparse_matrix_matrix(rows, cols, width, density, iters, false);\n  // Cpu performed 0.700048 mul/sec = 0.0601337 gflops\n  // Gpu performed 1.75981 mul/sec = 0.151167 gflops\n  // rms_error = 0.0506754\n\n  test_sparse_matrix_matrix(rows, cols, width, density, iters, true);\n  // Cpu performed 0.643097 mul/sec = 0.0552416 gflops\n  // Gpu performed 34.4816 mul/sec = 2.96194 gflops\n  // rms_error = 0.00686571\n\n  test_dense_matrix_matrix(rows, cols, width, iters, false, false);\n  // Cpu performed 3.5864 mul/sec = 30.807 gflops\n  // Gpu performed 27.9431 mul/sec = 240.029 gflops\n  // rms_error = 21.362\n\n  // TODO get these working\n  //test_dense_matrix_matrix(rows, cols, width, iters, true, false);\n  //test_dense_matrix_matrix(rows, cols, width, iters, false, true);\n  //test_dense_matrix_matrix(rows, cols, width, iters, true, true);\n\n  LOG(\"\");\n  return 0;\n}\n\n", "meta": {"hexsha": "afa33c87bf92f5572f55e554c40dca8c10235807", "size": 7901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen_gpu_test.cpp", "max_stars_repo_name": "fritzo/kazoo", "max_stars_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T11:38:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-31T01:32:13.000Z", "max_issues_repo_path": "src/eigen_gpu_test.cpp", "max_issues_repo_name": "fritzo/kazoo", "max_issues_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigen_gpu_test.cpp", "max_forks_repo_name": "fritzo/kazoo", "max_forks_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0759075908, "max_line_length": 78, "alphanum_fraction": 0.5928363498, "num_tokens": 2402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6233868403518033}}
{"text": "#include <iostream>\n#include <cmath>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <sophus/so3.h>\n#include <sophus/se3.h>\n\nint main(int argc, char** argv) {\n  Eigen::Matrix3d R = Eigen::AngleAxisd(M_PI / 2, Eigen::Vector3d(0, 0, 1)).toRotationMatrix();  \n\n  Sophus::SO3 SO3_R(R);\n  \n  Sophus::SO3 SO3_V(0, 0, M_PI / 2);\n  \n  Eigen::Quaterniond Q(R);\n  Sophus::SO3 SO3_Q(Q);\n\n  std::cout << \"SO3 from matrix: \" << SO3_R << std::endl;\n  std::cout << \"SO3 from vector: \" << SO3_V << std::endl;\n  std::cout << \"SO3 from quaternion: \" << SO3_Q << std::endl;\n\n  Eigen::Vector3d so3 = SO3_R.log();\n  std::cout << \"so3 = \" << so3.transpose() << std::endl;\n\n  std::cout << \"so3 hat = \\n\" << Sophus::SO3::hat(so3) << std::endl;\n \n  std::cout << \"so3 hat vee = \" << Sophus::SO3::vee(Sophus::SO3::hat(so3)) << std::endl;\n\n  Eigen::Vector3d update_so3(1e-4, 0, 0);\n  Sophus::SO3 SO3_updated = Sophus::SO3::exp(update_so3) * SO3_R;\n  std::cout << \"SO3 updated = \" << SO3_updated << std::endl;\n\n  std::cout << \"op SE3\" << std::endl;\n\n  Eigen::Vector3d t(1, 0, 0);\n  Sophus::SE3 SE3_Rt(R, t);\n  Sophus::SE3 SE3_Qt(Q, t);\n\n  std::cout << \"SE3 from R, t = \\n\" << SE3_Rt << std::endl;\n  std::cout << \"SE3 from Q, t = \\n\" << SE3_Qt << std::endl;\n\n  typedef Eigen::Matrix<double, 6, 1> Vector6d;\n  Vector6d se3 = SE3_Rt.log();\n\n  std::cout << \"se3 = \\n\" << se3.transpose() << std::endl;\n\n  std::cout << \"se3 hat = \\n\" << Sophus::SE3::hat(se3) << std::endl;\n  std::cout << \"se3 hat vee = \\n\" << \n            Sophus::SE3::vee(Sophus::SE3::hat(se3)).transpose() << std::endl;\n\n  Vector6d update_se3;\n  update_se3.setZero();\n  update_se3(0, 0) = 1e-4d;\n  Sophus::SE3 SE3_updated = Sophus::SE3::exp(update_se3) * SE3_Rt;\n\n  std::cout << \"SE3 updated = \\n\" << SE3_updated.matrix() << std::endl;\n\n  return 0;\n}\n\n\n\n\n\n", "meta": {"hexsha": "e03498eecb6f6bf38d71c3ec89de22f41db3fc45", "size": 1801, "ext": "cc", "lang": "C++", "max_stars_repo_path": "VisionSLAM14/ch4/sophus_test/use_sophus.cc", "max_stars_repo_name": "DLonng/Go", "max_stars_repo_head_hexsha": "a67ac6d6501f9fadadec6a6cf766d4b4a356d572", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2020-04-10T01:53:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-31T03:43:10.000Z", "max_issues_repo_path": "VisionSLAM14/ch4/sophus_test/use_sophus.cc", "max_issues_repo_name": "DLonng/Go", "max_issues_repo_head_hexsha": "a67ac6d6501f9fadadec6a6cf766d4b4a356d572", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-10T07:08:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-14T07:47:01.000Z", "max_forks_repo_path": "VisionSLAM14/ch4/sophus_test/use_sophus.cc", "max_forks_repo_name": "DLonng/Go", "max_forks_repo_head_hexsha": "a67ac6d6501f9fadadec6a6cf766d4b4a356d572", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2020-04-05T11:49:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T10:23:37.000Z", "avg_line_length": 26.8805970149, "max_line_length": 97, "alphanum_fraction": 0.5891171571, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388252252041, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6233724148399314}}
{"text": "// Copyright 2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_custom_accumulators_builtin\n\n#include <boost/format.hpp>\n#include <boost/histogram.hpp>\n#include <cassert>\n#include <iostream>\n#include <sstream>\n\nint main() {\n  using namespace boost::histogram;\n  using mean = accumulators::mean<>;\n\n  // Create a 1D-profile, which computes the mean of samples in each bin.\n  auto h = make_histogram_with(dense_storage<mean>(), axis::integer<>(0, 2));\n  // The factory function `make_profile` is provided as a shorthand for this, so this is\n  // equivalent to the previous line: auto h = make_profile(axis::integer<>(0, 2));\n\n  // An argument marked as `sample` is passed to the accumulator.\n  h(0, sample(1)); // sample goes to first cell\n  h(0, sample(2)); // sample goes to first cell\n  h(1, sample(3)); // sample goes to second cell\n  h(1, sample(4)); // sample goes to second cell\n\n  std::ostringstream os;\n  for (auto&& x : indexed(h)) {\n    // Accumulators usually have methods to access their state. Use the arrow\n    // operator to access them. Here, `count()` gives the number of samples,\n    // `value()` the mean, and `variance()` the variance estimate of the mean.\n    os << boost::format(\"index %i count %i mean %.1f variance %.1f\\n\") % x.index() %\n              x->count() % x->value() % x->variance();\n  }\n  std::cout << os.str() << std::flush;\n  assert(os.str() == \"index 0 count 2 mean 1.5 variance 0.5\\n\"\n                     \"index 1 count 2 mean 3.5 variance 0.5\\n\");\n}\n\n//]\n", "meta": {"hexsha": "59c1e1c7a9fa7a09c81e9b9c74b12ea82f2f4c8e", "size": 1633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/histogram/examples/guide_custom_accumulators_builtin.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 188.0, "max_stars_repo_stars_event_min_datetime": "2019-02-08T14:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T08:37:05.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/histogram/examples/guide_custom_accumulators_builtin.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 186.0, "max_issues_repo_issues_event_min_datetime": "2016-05-05T14:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-20T22:38:43.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/histogram/examples/guide_custom_accumulators_builtin.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2019-02-09T16:16:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T20:24:36.000Z", "avg_line_length": 37.1136363636, "max_line_length": 88, "alphanum_fraction": 0.661971831, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6233724130910979}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Christopher Kormanyos 2020 - 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 <cmath>\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 <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/cbrt.hpp>\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/bindings/decwide_t.hpp>\n\n#include <math/wide_decimal/decwide_t_examples.h>\n\nnamespace\n{\n  constexpr std::uint32_t wide_decimal_digits10 = UINT32_C(1001);\n\n  using dec1001_t = math::wide_decimal::decwide_t<wide_decimal_digits10>;\n}\n\nbool math::wide_decimal::example009_boost_math_standalone()\n{\n  const dec1001_t x = dec1001_t(UINT32_C(123456789)) / 100U;\n\n  using std::cbrt;\n  using std::fabs;\n\n  // Compare wide-decimal's cube root function with that of Boost.Math.\n  // Also exercise several different interpretations of the constant pi.\n\n  const dec1001_t c       = cbrt(x / math::wide_decimal::pi<wide_decimal_digits10, typename dec1001_t::limb_type, std::allocator<void>, double>());\n\n  const dec1001_t control = boost::math::cbrt(x / boost::math::constants::pi<dec1001_t>());\n\n  const dec1001_t closeness = fabs(1 - (c / control));\n\n  const bool result_is_ok = closeness < (std::numeric_limits<dec1001_t>::epsilon() * 10);\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 <iomanip>\n#include <iostream>\n\nint main()\n{\n  const bool result_is_ok = math::wide_decimal::example009_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": "3b86aa417c45c4cdea175db4c1eeff9e66d58b6b", "size": 2453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example009_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/example009_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/example009_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": 29.5542168675, "max_line_length": 147, "alphanum_fraction": 0.6909906237, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6233318993607565}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"lsq.h\"\n\n\nint main() {\n    Eigen::MatrixXf A = Eigen::MatrixXf::Random(3,3);\n    Eigen::VectorXf b = Eigen::VectorXf::Random(3);\n    LSQ* lsq = new LSQ(A, b);\n    Eigen::VectorXf x = lsq->solve();\n    std::cout << x << std::endl;\n    delete lsq;\n}\n", "meta": {"hexsha": "aa81ad06a9e8fbcf5bc8570ddb57654ca75a82be", "size": 300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bijou/lsq/main.cpp", "max_stars_repo_name": "sonnyhu/bijou", "max_stars_repo_head_hexsha": "7085cdb25a0e111816b457c03dc492469d30c761", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bijou/lsq/main.cpp", "max_issues_repo_name": "sonnyhu/bijou", "max_issues_repo_head_hexsha": "7085cdb25a0e111816b457c03dc492469d30c761", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bijou/lsq/main.cpp", "max_forks_repo_name": "sonnyhu/bijou", "max_forks_repo_head_hexsha": "7085cdb25a0e111816b457c03dc492469d30c761", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4285714286, "max_line_length": 53, "alphanum_fraction": 0.5966666667, "num_tokens": 102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6232878844292921}}
{"text": "// File       : gemm_eigen.cpp\n// Created    : Tue 23 Oct 2018 02:57:27 PM CEST\n// Description: GEMM Eigen implementation\n// Copyright 2018 ETH Zurich. All Rights Reserved.\n\n#include <Eigen/Core>\n#include \"common.h\"\n\n// Wrapper to map pointer to Eigen matrix type (needed in benchmark)\ntemplate <typename T>\nusing EMat = Eigen::Map< Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic, Eigen::RowMajor> >;\n\n/**\n * @brief General matrix-matrix multiplication kernel (GEMM). Computes C = AB.\n * Eigen library implementation\n *\n * @param A Eigen matrix dimension p x r\n * @param B Eigen matrix dimension r x q\n * @param C Eigen matrix dimension p x q\n */\nvoid gemm_eigen(const EMat<Real>& A, const EMat<Real>& B, EMat<Real>& C)\n{\n    C.noalias() += A * B;\n}\n", "meta": {"hexsha": "e5fc0b922fca78b58f3436a43b4d7595b4e6a0d1", "size": 749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HPCI/exercises/ex04/solution_code/ispc_gemm/gemm_eigen.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": "HPCI/exercises/ex04/solution_code/ispc_gemm/gemm_eigen.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": "HPCI/exercises/ex04/solution_code/ispc_gemm/gemm_eigen.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.96, "max_line_length": 91, "alphanum_fraction": 0.694259012, "num_tokens": 206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6232659521679531}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      Mathworks. gravitysphericalharmonic, implement spherical harmonic representation of\n *        planetary gravity. Help documentation of MATLAB R2012a, 2012.\n *\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <cmath>\n#include <limits>\n\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"tudat/basics/testMacros.h\"\n#include \"tudat/math/basic/mathematicalConstants.h\"\n\n#include \"tudat/math/basic/coordinateConversions.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_coordinate_conversions )\n\n//! Test if spherical-to-Cartesian conversion is working correctly.\nBOOST_AUTO_TEST_CASE( testSphericalToCartesianConversion )\n{\n    using std::sqrt;\n    using mathematical_constants::PI;\n    using coordinate_conversions::convertSphericalToCartesian;\n\n    // Test 1: test conversion of: ( 0.0, 0.0, 0.0 ).\n    {\n        Eigen::Vector3d sphericalCoordinates( 0.0, 0.0, 0.0 );\n\n        // Convert spherical coordinates to Cartesian coordinates.\n        Eigen::Vector3d cartesianCoordinates = convertSphericalToCartesian( sphericalCoordinates );\n\n        // Expected cartesian coordinates.\n        Eigen::Vector3d expectedCartesianCoordinates( 0.0, 0.0, 0.0 );\n\n        // Check if converted Cartesian coordinates are correct.\n        TUDAT_CHECK_MATRIX_BASE( cartesianCoordinates, expectedCartesianCoordinates )\n                BOOST_CHECK_SMALL( cartesianCoordinates.coeff( row, col ),\n                                   std::numeric_limits< double >::min( ) );\n    }\n\n    // Test 2: test conversion of: ( 1.0, pi/6, pi/6 ), from Stewart (2003), Exercise 12.7.15.\n    {\n        Eigen::Vector3d sphericalCoordinates( 1.0, PI / 6.0, PI / 6.0 );\n\n        // Convert spherical coordinates to Cartesian coordinates.\n        Eigen::Vector3d cartesianCoordinates = convertSphericalToCartesian( sphericalCoordinates );\n\n        // Expected cartesian coordinates.\n        Eigen::Vector3d expectedCartesianCoordinates(\n                    sqrt( 3.0 ) / 4.0, 1.0 / 4.0, sqrt( 3.0 ) / 2.0 );\n\n        // Check if converted Cartesian coordinates are correct.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                    cartesianCoordinates, expectedCartesianCoordinates, 1.0e-15 );\n    }\n\n    // Test 3: test conversion of: ( 2.0, pi/4, pi/3 ), from Stewart (2003), Exercise 12.7.17.\n    {\n        Eigen::Vector3d sphericalCoordinates( 2.0, PI / 4.0, PI / 3.0 );\n\n        // Convert spherical coordinates to Cartesian coordinates.\n        Eigen::Vector3d cartesianCoordinates = convertSphericalToCartesian( sphericalCoordinates );\n\n        // Expected cartesian coordinates.\n        Eigen::Vector3d expectedCartesianCoordinates(\n                    0.5 * sqrt( 2.0 ), 0.5 * sqrt( 6.0 ), sqrt( 2.0 ) );\n\n        // Check if converted Cartesian coordinates are correct.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( cartesianCoordinates, expectedCartesianCoordinates,\n                                           std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 4: test conversion of: ( 2.0, pi/3, pi/4 , from Stewart (2003), Section 12.7,\n    //         Example 4.\n    {\n        Eigen::Vector3d sphericalCoordinates( 2.0, PI / 3.0, PI / 4.0 );\n\n        // Convert spherical coordinates to Cartesian coordinates.\n        Eigen::Vector3d cartesianCoordinates = convertSphericalToCartesian( sphericalCoordinates );\n\n        // Expected cartesian coordinates.\n        Eigen::Vector3d expectedCartesianCoordinates( sqrt( 1.5 ), sqrt( 1.5 ), 1.0 );\n\n        // Check if converted Cartesian coordinates are correct.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( cartesianCoordinates, expectedCartesianCoordinates,\n                                           std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\n//! Test if Cartesian-to-spherical conversion is working correctly.\nBOOST_AUTO_TEST_CASE( testCartesianToSphericalConversion )\n{\n    using std::acos;\n    using std::atan2;\n    using std::pow;\n    using std::sqrt;\n    using coordinate_conversions::convertCartesianToSpherical;\n    using mathematical_constants::PI;\n\n    // Test 1: Test conversion of: ( 0.0, 0.0, 0.0 ).\n    {\n        Eigen::Vector3d cartesianCoordinates = Eigen::Vector3d::Zero( );\n\n        // Expected vector in spherical coordinates.\n        Eigen::Vector3d expectedSphericalCoordinates = Eigen::Vector3d::Zero( );\n\n        // Result vector in spherical coordinates.\n        Eigen::Vector3d sphericalCoordinates = convertCartesianToSpherical( cartesianCoordinates );\n\n        // Check if converted spherical coordinates are correct.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( sphericalCoordinates, expectedSphericalCoordinates,\n                                           std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 2: Test conversion of: ( 1.0, sqrt( 3 ), 2 * sqrt(3) ), from Stewart (2003),\n    // Exercise 12.7.19.\n    {\n        Eigen::Vector3d cartesianCoordinates( 1.0, sqrt( 3. ), 2.0 * sqrt( 3. ) );\n\n        // Expected vector in spherical coordinates.\n        Eigen::Vector3d expectedSphericalCoordinates( 4.0, PI / 6.0, PI / 3.0 );\n\n        // Result vector in spherical coordinates.\n        Eigen::Vector3d sphericalCoordinates = convertCartesianToSpherical( cartesianCoordinates );\n\n        // Check if converted spherical coordinates are correct.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( sphericalCoordinates, expectedSphericalCoordinates,\n                                           std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 3: Test conversion of: ( 0.0, -1.0, -1.0 ), from Stewart (2003), Exercise 12.7.21.\n    {\n        Eigen::Vector3d cartesianCoordinates( 0.0, -1.0, -1.0 );\n\n        // Expected vector in spherical coordinates.\n        Eigen::Vector3d expectedSphericalCoordinates( sqrt( 2.0 ), 3.0 * PI / 4.0, -PI / 2.0 );\n\n        // Result vector in spherical coordinates.\n        Eigen::Vector3d sphericalCoordinates = Eigen::Vector3d::Zero( );\n\n        // Compute conversions.\n        sphericalCoordinates = convertCartesianToSpherical( cartesianCoordinates );\n\n        // Check if converted spherical coordinates are correct.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( sphericalCoordinates, expectedSphericalCoordinates,\n                                           std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 4: Test conversion of: ( 0.0, 2 sqrt( 3 ), -2.0 ), from Stewart (2003), Section 12.7,\n    // Example 5.\n    {\n        Eigen::Vector3d cartesianCoordinates( 0.0, 2.0 * sqrt( 3. ), -2.0 );\n\n        // Expected vector in spherical coordinates.\n        Eigen::Vector3d expectedSphericalCoordinates( 4.0, 2.0 * PI / 3.0, PI / 2.0 );\n\n        // Result vector in spherical coordinates.\n        Eigen::Vector3d sphericalCoordinates = convertCartesianToSpherical( cartesianCoordinates );\n\n        // Check if converted spherical coordinates are correct.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( sphericalCoordinates, expectedSphericalCoordinates,\n                                           std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\n// Test conversion from cylindrical (r, theta, z) to Cartesian (x, y, z) coordinates.\nBOOST_AUTO_TEST_CASE( testCylindricalToCartesianPositionCoordinateConversion )\n{\n    using mathematical_constants::PI;\n    using coordinate_conversions::xCartesianCoordinateIndex;\n    using coordinate_conversions::yCartesianCoordinateIndex;\n    using coordinate_conversions::zCartesianCoordinateIndex;\n\n    // Test 1: test conversion of ( 0.0, pi, 1.2 ).\n    {\n        // Set cylindrical coordinates.\n        const Eigen::Vector3d cylindricalCoordinates( 0.0, PI, 1.2 );\n\n        // Set expected Cartesian coordinates.\n        const Eigen::Vector3d expectedCartesianCoordinates( 0.0, 0.0, 1.2 );\n\n        // Convert cylindrical to Cartesian coordinates.\n        const Eigen::Vector3d computedCartesianCoordinates\n                = coordinate_conversions::\n                convertCylindricalToCartesian( cylindricalCoordinates );\n\n        // Check if computed Cartesian coordinates match expected values.\n        BOOST_CHECK_SMALL( computedCartesianCoordinates( xCartesianCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( computedCartesianCoordinates( yCartesianCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCartesianCoordinates( zCartesianCoordinateIndex ),\n                                    computedCartesianCoordinates( zCartesianCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 2: test conversion of ( 2.3, -pi/2, -3.5 ).\n    {\n        // Set cylindrical coordinates.\n        const Eigen::Vector3d cylindricalCoordinates( 2.3, -PI/2, -3.5 );\n\n        // Set expected Cartesian coordinates.\n        const Eigen::Vector3d expectedCartesianCoordinates( 2.3 * std::cos( -PI / 2.0 ),\n                                                            2.3 * std::sin( -PI / 2.0 ),\n                                                            -3.5 );\n\n        // Convert cylindrical to Cartesian coordinates.\n        const Eigen::Vector3d convertedCartesianCoordinates\n                = coordinate_conversions::\n                convertCylindricalToCartesian( cylindricalCoordinates );\n\n        // Check if converted Cartesian coordinates match expected values.\n        BOOST_CHECK_SMALL( convertedCartesianCoordinates ( xCartesianCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                    expectedCartesianCoordinates.segment( yCartesianCoordinateIndex, 2 ),\n                    convertedCartesianCoordinates.segment( yCartesianCoordinateIndex, 2 ),\n                    std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\n// Test conversion from cylindrical (r, theta, z, Vr, Vtheta, Vz) to Cartesian\n// (x, y, z, xdot, ydot, zdot) state.\nBOOST_AUTO_TEST_CASE( testCylindricalToCartesianPositionAndVelocityCoordinateConversion )\n{\n    using mathematical_constants::PI;\n    using coordinate_conversions::xCartesianCoordinateIndex;\n    using coordinate_conversions::yCartesianCoordinateIndex;\n    using coordinate_conversions::zCartesianCoordinateIndex;\n\n    // Test 1: test conversion of (2.1, pi/2.0, 1.2, 5.4, 4.5, -3.9).\n    {\n        // Set Cylindrical state (r, theta, z, Vr, Vtheta, Vz).\n        const Eigen::Vector6d cylindricalState =\n                ( Eigen::Vector6d( ) << 2.1, PI / 2.0, 1.2, 5.4, 4.5, -3.9 ).finished( );\n\n        // Set expected Cartesian state (x, y, z, xdot, ydot, zdot).\n        const Eigen::Vector6d expectedCartesianState =\n                ( Eigen::Vector6d( )\n                  << 2.1 * std::cos( PI / 2.0 ),\n                  2.1 * std::sin( PI / 2.0 ),\n                  1.2,\n                  5.4 * std::cos( PI / 2.0 ) - 4.5 * std::sin( PI / 2.0 ),\n                  5.4 * std::sin( PI / 2.0 ) + 4.5 * std::cos( PI / 2.0 ),\n                  -3.9 ).finished( );\n\n        // Convert cylindrical to Cartesian state (x, y, z, xdot, ydot, zdot).\n        const Eigen::Vector6d convertedCartesianState\n                = coordinate_conversions::\n                convertCylindricalToCartesianState( cylindricalState );\n\n        // Check if converted Cartesian state match expected state.\n        BOOST_CHECK_SMALL( convertedCartesianState ( xCartesianCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                    expectedCartesianState.segment( yCartesianCoordinateIndex, 5 ),\n                    convertedCartesianState.segment( yCartesianCoordinateIndex, 5 ),\n                    std::numeric_limits< double >::epsilon( ) );\n\n    }\n\n    // Test 2: test conversion of (0.0, 8.2*pi/3.0, -2.5, -5.8, 0.0, 1.7).\n    {\n        // Set Cylindrical state (r, theta, z, Vr, Vtheta, Vz).\n        const Eigen::Vector6d cylindricalState = ( Eigen::Vector6d( )\n                                                   << 0.0, 8.2 * PI / 3.0,\n                                                   -2.5, -5.8, 0.0, 1.7 ).finished( );\n\n        // Set expected Cartesian state (x, y, z, xdot, ydot, zdot).\n        const Eigen::Vector6d expectedCartesianState = ( Eigen::Vector6d( )\n                                                         << 0.0,\n                                                         0.0,\n                                                         -2.5,\n                                                         -5.8 * std::cos( 8.2 * PI / 3.0 ),\n                                                         -5.8 * std::sin( 8.2 * PI / 3.0 ),\n                                                         1.7 ).finished( );\n\n        // Convert cylindrical to Cartesian state (x, y, z, xdot, ydot, zdot).\n        const Eigen::Vector6d convertedCartesianState\n                = coordinate_conversions::\n                convertCylindricalToCartesianState( cylindricalState );\n\n        // Check if converted Cartesian state match expected state.\n        BOOST_CHECK_SMALL( convertedCartesianState( xCartesianCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( convertedCartesianState( yCartesianCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                    expectedCartesianState.segment( zCartesianCoordinateIndex, 4 ),\n                    convertedCartesianState.segment( zCartesianCoordinateIndex, 4 ),\n                    std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\n// Test conversion from Cartesian (x, y, z) to cylindrical (r, theta, z) coordinates.\nBOOST_AUTO_TEST_CASE( testCartesianToCylindricalPositionCoordinateConversion )\n{\n    using mathematical_constants::PI;\n    using coordinate_conversions::rCylindricalCoordinateIndex;\n    using coordinate_conversions::thetaCylindricalCoordinateIndex;\n    using coordinate_conversions::zCylindricalCoordinateIndex;\n\n    // Test 1: test conversion of ( 0.0, 0.0, 1.0 ).\n    {\n        // Set Cartesian coordinates (x, y, z).\n        const Eigen::Vector3d cartesianCoordinates( 0.0, 0.0, 1.0 );\n\n        // Set expected cylindrical coordinates (r, theta, z).\n        const Eigen::Vector3d expectedCylindricalCoordinates( 0.0, 0.0, 1.0 );\n\n        // Convert Cartesian to cylindrical coordinates (r, theta, z).\n        const Eigen::Vector3d convertedCylindricalCoordinates\n                = coordinate_conversions::\n                convertCartesianToCylindrical( cartesianCoordinates );\n\n        // Check if converted cylindrical coordinates match expected values.\n        BOOST_CHECK_SMALL( convertedCylindricalCoordinates( rCylindricalCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( convertedCylindricalCoordinates( thetaCylindricalCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCylindricalCoordinates( zCylindricalCoordinateIndex ),\n                                    convertedCylindricalCoordinates( zCylindricalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 2: test conversion of ( 0.0, 2.0, 1.0 ).\n    {\n        // Set Cartesian coordinates (x, y, z).\n        const Eigen::Vector3d cartesianCoordinates( 0.0, 2.0, 1.0 );\n\n        // Set expected cylindrical coordinates (r, theta, z).\n        const Eigen::Vector3d expectedCylindricalCoordinates( 2.0, PI / 2.0, 1.0 );\n\n        // Convert Cartesian to cylindrical coordinates (r, theta, z).\n        const Eigen::Vector3d convertedCylindricalCoordinates\n                = coordinate_conversions::\n                convertCartesianToCylindrical( cartesianCoordinates );\n\n        // Check if converted cylindrical coordinates match expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCylindricalCoordinates,\n                                           convertedCylindricalCoordinates,\n                                           std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 3: test conversion of ( 0.0, -2.0, -1.0 ).\n    {\n        // Set Cartesian coordinates (x, y, z).\n        const Eigen::Vector3d cartesianCoordinates( 0.0, -2.0, -1.0 );\n\n        // Set expected cylindrical coordinates (r, theta, z).\n        const Eigen::Vector3d expectedCylindricalCoordinates( 2.0, 3.0 * PI / 2.0, -1.0 );\n\n        // Convert Cartesian to cylindrical coordinates (r, theta, z).\n        const Eigen::Vector3d convertedCylindricalCoordinates\n                = coordinate_conversions::\n                convertCartesianToCylindrical( cartesianCoordinates );\n\n        // Check if converted cylindrical coordinates match expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCylindricalCoordinates,\n                                           convertedCylindricalCoordinates,\n                                           std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 4: test conversion of ( -5.0, -8.0, 5.0 ).\n    {\n        // Set Cartesian coordinates (x, y, z).\n        const Eigen::Vector3d cartesianCoordinates( -5.0, -8.0, 5.0 );\n\n        // Set expected cylindrical coordinates (r, theta, z).\n        const Eigen::Vector3d expectedCylindricalCoordinates( std::sqrt( 25.0 + 64.0 ),\n                                                              std::atan2( -8.0,-5.0 ) + 2.0 * PI,\n                                                              5.0 );\n\n        // Convert Cartesian to cylindrical coordinates (r, theta, z).\n        const Eigen::Vector3d convertedCylindricalCoordinates\n                = coordinate_conversions::\n                convertCartesianToCylindrical( cartesianCoordinates );\n\n        // Check if converted cylindrical coordinates match expected values.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCylindricalCoordinates,\n                                           convertedCylindricalCoordinates,\n                                           std::numeric_limits< double >::epsilon( ) );\n    }\n\n}\n\n// Test conversion from Cartesian (x, y, z, xdot, ydot, zdot) to cylindrical\n// (r, theta, z, Vr, Vtheta, Vz) state.\nBOOST_AUTO_TEST_CASE( testCartesianToCylindricalPositionAndVelocityCoordinateConversion )\n{\n    using mathematical_constants::PI;\n    using coordinate_conversions::rCylindricalCoordinateIndex;\n    using coordinate_conversions::thetaCylindricalCoordinateIndex;\n    using coordinate_conversions::zCylindricalCoordinateIndex;\n    using coordinate_conversions::rDotCylindricalCoordinateIndex;\n    using coordinate_conversions::vThetaCylindricalCoordinateIndex;\n    using coordinate_conversions::zDotCylindricalCoordinateIndex;\n\n    // Test 1: test conversion of ( 0.0, 0.0, 1.0, 5.0, 6.0, -9.0 ).\n    {\n        // Set Cartesian state (x,y,z,xdot,ydot,zdot).\n        const Eigen::Vector6d cartesianState = ( Eigen::Vector6d( )\n                                                 << 0.0, 0.0, 1.0, 5.0, 6.0, -9.0 ).finished( );\n\n        // Set expected cylindrical state (r, theta, z, Vr, Vtheta, Vz).\n        const Eigen::Vector6d expectedCylindricalState =\n                ( Eigen::Vector6d( )\n                                                           << 0.0, 0.0, 1.0,\n                                                           std::sqrt( 25.0 + 36.0 ),\n                                                           0.0, -9.0 ).finished( );\n\n        // Convert Cartesian to cylindrical state (r, theta, z, Vr, Vtheta, Vz).\n        const Eigen::Vector6d convertedCylindricalState\n                = coordinate_conversions::\n                convertCartesianToCylindricalState( cartesianState );\n\n        // Check that converted cylindrical state matches expected state.\n        BOOST_CHECK_SMALL( convertedCylindricalState( rCylindricalCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( convertedCylindricalState( thetaCylindricalCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCylindricalState( zCylindricalCoordinateIndex ),\n                                    convertedCylindricalState( zCylindricalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCylindricalState( rDotCylindricalCoordinateIndex ),\n                                    convertedCylindricalState( rDotCylindricalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( convertedCylindricalState( vThetaCylindricalCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCylindricalState( zDotCylindricalCoordinateIndex ),\n                                    convertedCylindricalState( zDotCylindricalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 2: test conversion of ( 2.0, 0.0, -5.0, -4.0, 6.0, -6.0 ).\n    {\n        // Set Cartesian state (x,y,z,xdot,ydot,zdot).\n        const Eigen::Vector6d cartesianState = ( Eigen::Vector6d( )\n                                                 << 2.0, 0.0, -5.0, -4.0, 6.0, -6.0 ).finished( );\n\n        // Set expected cylindrical state (r, theta, z, Vr, Vtheta, Vz).\n        const Eigen::Vector6d expectedCylindricalState = ( Eigen::Vector6d( )\n                                                           << 2.0, 0.0, -5.0,\n                                                           -4.0, 6.0, -6.0 ).finished( );\n\n        // Convert Cartesian to cylindrical state (r, theta, z, Vr, Vtheta, Vz).\n        const Eigen::Vector6d convertedCylindricalState\n                = coordinate_conversions::\n                convertCartesianToCylindricalState( cartesianState );\n\n        // Check that converted cylindrical state matches expected state.\n        BOOST_CHECK_CLOSE_FRACTION( expectedCylindricalState( rCylindricalCoordinateIndex ),\n                                    convertedCylindricalState( rCylindricalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( convertedCylindricalState( thetaCylindricalCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n                    expectedCylindricalState.segment( zCylindricalCoordinateIndex, 4 ),\n                    convertedCylindricalState.segment( zCylindricalCoordinateIndex, 4 ),\n                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 3: test conversion of ( -7.0, -4.0, 3.0, 5.0, -3.0, 7.0 ).\n    {\n        // Set Cartesian state (x,y,z,xdot,ydot,zdot).\n        const Eigen::Vector6d cartesianState = ( Eigen::Vector6d( )\n                                                 << -7.0, -4.0, 3.0, 5.0, -3.0, 7.0 ).finished( );\n\n        // Set expected cylindrical state (r, theta, z, Vr, Vtheta, Vz).\n        const Eigen::Vector6d expectedCylindricalState = ( Eigen::Vector6d( )\n                                                           << std::sqrt( 49.0 + 16.0 ),\n                                                           std::atan2( -4.0, -7.0 ) + 2.0 * PI,\n                                                           3.0,\n                                                           ( -7.0 * 5.0 + ( -4.0 ) * -3.0 )\n                                                           / std::sqrt( 49.0 + 16.0 ),\n                                                           ( -7.0 * -3.0 - ( -4.0 ) * 5.0 )\n                                                           / sqrt( 49.0 + 16.0 ), 7.0 ).finished( );\n\n        // Convert Cartesian to cylindrical state (r, theta, z, Vr, Vtheta, Vz).\n        const Eigen::Vector6d convertedCylindricalState\n                = coordinate_conversions::\n                convertCartesianToCylindricalState( cartesianState );\n\n        // Check that converted cylindrical state matches expected state.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCylindricalState, convertedCylindricalState,\n                                           std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\n// Test conversion from spherical to Cartesian gradient.\nBOOST_AUTO_TEST_CASE( test_SphericalToCartesianGradientConversion )\n{\n    // Define an arbitrary spherical gradient.\n    const Eigen::Vector3d sphericalGradient( -2.438146967844150, 1.103964186650749e4,\n                                             5.932496087870976e1 );\n\n    // Define an arbitrary spherical position vector.\n    const Eigen::Vector3d cartesianCoordinates( -7.0e6, 8.5e6, -6.5e6 );\n\n    // Compute Cartesian gradient.\n    const Eigen::Vector3d cartesianGradient = coordinate_conversions::\n            convertSphericalToCartesianGradient( sphericalGradient, cartesianCoordinates );\n\n    // Define expected Cartesian gradient. These values are obtained from the computations of\n    // 'gx', 'gy' and 'gz' in the MATLAB function 'gravitysphericalharmonics'. This function is\n    // described by Mathworks [2012].\n    const Eigen::Vector3d expectedCartesianGradient( 1.334464111786447, -1.620429182163669,\n                                                     1.240151677089496 );\n\n    // Check if the computed Cartesian gradient matches the expected value.\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianGradient, cartesianGradient, 1e-15 );\n}\n\n// Test derivative of Cartesian gradient, keeping spherical gradient constant.\nBOOST_AUTO_TEST_CASE( test_SphericalToCartesianGradientPartialDerivatives )\n{\n    // Define an arbitrary spherical gradient.\n    const Eigen::Vector3d sphericalGradient( -2.438146967844150, 1.103964186650749e4,\n                                             5.932496087870976e1 );\n\n    // Define an arbitrary spherical position vector.\n    const Eigen::Vector3d cartesianCoordinates( -7.0e6, 8.5e6, -6.5e6 );\n\n\n    // Define perturbation for numerical computation of partial\n    const Eigen::Vector3d cartesianCoordinatePerturbation( 10.0, 10.0, 10.0 );\n    Eigen::Vector3d perturbedCartesianCoordinates;\n\n    std::vector< Eigen::Matrix3d > matrixPartials;\n    matrixPartials.resize( 3 );\n\n    std::vector< Eigen::Matrix3d > subMatrices;\n    subMatrices.resize( 3 );\n    // Compute analytical partial (with sub-components)\n    coordinate_conversions::getDerivativeOfSphericalToCartesianGradient( sphericalGradient, cartesianCoordinates, subMatrices );\n\n    Eigen::Matrix3d uppPerturbedMatrix;\n    for( unsigned int i = 0; i < 3; i++ )\n    {\n        // Compute partial numerically.\n        perturbedCartesianCoordinates = cartesianCoordinates;\n        perturbedCartesianCoordinates( i ) += cartesianCoordinatePerturbation( i );\n        matrixPartials[ i ] = coordinate_conversions::getSphericalToCartesianGradientMatrix(\n                    perturbedCartesianCoordinates );\n\n        perturbedCartesianCoordinates = cartesianCoordinates;\n        perturbedCartesianCoordinates( i ) -= cartesianCoordinatePerturbation( i );\n        matrixPartials[ i ] -= coordinate_conversions::getSphericalToCartesianGradientMatrix(\n                    perturbedCartesianCoordinates );\n\n        matrixPartials[ i ] /= ( 2.0 * cartesianCoordinatePerturbation( i ) );\n\n        // Normalize components for uniform tolerance.\n        matrixPartials[ i ].block( 0, 0, 3, 1 ) = matrixPartials[ i ].block( 0, 0, 3, 1 ) / cartesianCoordinates.norm( );\n        subMatrices[ i ].block( 0, 0, 3, 1 ) = subMatrices[ i ].block( 0, 0, 3, 1 ) / cartesianCoordinates.norm( );\n\n        for( unsigned k = 0; k < 3; k++ )\n        {\n            for( unsigned l = 0; l < 3; l++ )\n            {\n                BOOST_CHECK_SMALL( std::fabs( matrixPartials[ i ]( k, l ) - subMatrices[ i ]( k, l ) ), 1.0E-23 );\n            }\n\n        }\n    }\n}\n\n// Test conversion from Cartesian (x, y, z, xdot, ydot, zdot) to Spherical (radius, azimuth,\n// elevation, radial velocity, azimuthal velocity, elevational velocity) state.\nBOOST_AUTO_TEST_CASE( testCartesianToSphericalStateConversion )\n{\n    using mathematical_constants::PI;\n    using coordinate_conversions::radiusSphericalCoordinateIndex;\n    using coordinate_conversions::azimuthSphericalCoordinateIndex;\n    using coordinate_conversions::elevationSphericalCoordinateIndex;\n    using coordinate_conversions::radialVelocitySphericalCoordinateIndex;\n    using coordinate_conversions::azimuthVelocitySphericalCoordinateIndex;\n    using coordinate_conversions::elevationVelocitySphericalCoordinateIndex;\n    using coordinate_conversions::convertCartesianToSphericalState;\n    using std::sqrt;\n\n    // Test 1: test conversion of ( 0.0, 0.0, 1.0, 5.0, 6.0, -9.0 ).\n    {\n        // Set Cartesian state (x, y , z, xdot, ydot, zdot).\n        const Eigen::Vector6d cartesianState\n                = ( Eigen::Vector6d( ) << 0.0, 0.0, 1.0, 5.0, 6.0, -9.0 ).finished( );\n\n        // Set expected spherical state (r, theta, phi, Vr, Vtheta, Vphi).\n        const Eigen::Vector6d expectedSphericalState\n                = ( Eigen::Vector6d( ) << 1.0, 0.0, PI / 2.0, -9.0, 6.0, -5.0 ).finished( );\n\n        // Convert Cartesian to spherical state.\n        const Eigen::Vector6d convertedSphericalState\n                = convertCartesianToSphericalState( cartesianState );\n\n        // Check that converted spherical state matches expected spherical state.\n        BOOST_CHECK_CLOSE_FRACTION( expectedSphericalState( radiusSphericalCoordinateIndex ),\n                                    convertedSphericalState( radiusSphericalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( convertedSphericalState( azimuthSphericalCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedSphericalState( elevationSphericalCoordinateIndex ),\n                                    convertedSphericalState( elevationSphericalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedSphericalState(\n                                        radialVelocitySphericalCoordinateIndex ),\n                                    convertedSphericalState(\n                                        radialVelocitySphericalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedSphericalState(\n                                        azimuthVelocitySphericalCoordinateIndex ),\n                                    convertedSphericalState(\n                                        azimuthVelocitySphericalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedSphericalState(\n                                        elevationVelocitySphericalCoordinateIndex ),\n                                    convertedSphericalState(\n                                        elevationVelocitySphericalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 2: test conversion of ( 2.0, 0.0, 0.0, -4.0, 6.0, -6.0 ).\n    {\n        // Set Cartesian state (x, y , z, xdot, ydot, zdot).\n        const Eigen::Vector6d cartesianState\n                = ( Eigen::Vector6d( ) << 2.0, 0.0, 0.0, -4.0, 6.0, -6.0 ).finished( );\n\n        // Set expected spherical state (r, theta, phi, Vr, Vtheta, Vphi).\n        const Eigen::Vector6d expectedSphericalState\n                = ( Eigen::Vector6d( ) << 2.0, 0.0, 0.0, -4.0, 6.0, -6.0 ).finished( );\n\n        // Convert Cartesian to spherical state ( r, theta, phi, Vr, Vtheta, Vphi).\n        const Eigen::Vector6d convertedSphericalState\n                = convertCartesianToSphericalState( cartesianState );\n\n        // Check that converted spherical state matches expected spherical state.\n        BOOST_CHECK_CLOSE_FRACTION( expectedSphericalState( radiusSphericalCoordinateIndex ),\n                                    convertedSphericalState( radiusSphericalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( convertedSphericalState( azimuthSphericalCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( convertedSphericalState( elevationSphericalCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedSphericalState(\n                                        radialVelocitySphericalCoordinateIndex ),\n                                    convertedSphericalState(\n                                        radialVelocitySphericalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedSphericalState(\n                                        azimuthVelocitySphericalCoordinateIndex ),\n                                    convertedSphericalState(\n                                        azimuthVelocitySphericalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedSphericalState(\n                                        elevationVelocitySphericalCoordinateIndex ),\n                                    convertedSphericalState(\n                                        elevationVelocitySphericalCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 3: test conversion of ( -1.0, -1.0, sqrt( 2.0 ), -1.0, 1.0, sqrt( 2.0 ) ).\n    {\n        // Set Cartesian state ( x, y, z, xdot, ydot, zdot).\n        const Eigen::Vector6d cartesianState\n                = ( Eigen::Vector6d( )\n                    << -1.0, -1.0, sqrt( 2.0 ), -1.0, 1.0, sqrt( 2.0 ) ).finished( );\n\n        // Set expected spherical state (r, theta, phi, Vr, Vtheta, Vphi).\n        const Eigen::Vector6d expectedSphericalState\n                = ( Eigen::Vector6d( )\n                    << 2.0, -PI * 3.0 / 4.0, PI / 4.0, 1.0, -sqrt( 2.0 ), 1.0 ).finished( );\n\n        // Convert Cartesian to spherical state (r, theta, phi, Vr, Vtheta, Vphi).\n        const Eigen::Vector6d convertedSphericalState\n                = convertCartesianToSphericalState( cartesianState );\n\n        // Check that converted spherical state matches the expected spherical state.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedSphericalState, convertedSphericalState,\n                                           std::numeric_limits< double >::epsilon( ) );\n    }\n}\n\n// Test conversion from spherical (radius, azimuth, elevation, radial velocity, azimuthal velocity,\n// elevational velocity) to Cartesian state (x, y, z, xdot, ydot, zdot).\nBOOST_AUTO_TEST_CASE( testSphericalToCartesianStateConversion )\n{\n    using mathematical_constants::PI;\n    using coordinate_conversions::xCartesianCoordinateIndex;\n    using coordinate_conversions::yCartesianCoordinateIndex;\n    using coordinate_conversions::zCartesianCoordinateIndex;\n    using coordinate_conversions::xDotCartesianCoordinateIndex;\n    using coordinate_conversions::yDotCartesianCoordinateIndex;\n    using coordinate_conversions::zDotCartesianCoordinateIndex;\n    using coordinate_conversions::convertSphericalToCartesianState;\n    using std::sqrt;\n\n    // Test 1: test conversion of ( 1.0, 0.0, pi/2, -9.0, 6.0, -5.0 ).\n    {\n        // Set Spherical state (r, theta, phi, Vr, Vtheta, Vphi).\n        const Eigen::Vector6d sphericalState\n                = ( Eigen::Vector6d( ) << 1.0, 0.0, PI / 2.0, -9.0, 6.0, -5.0 ).finished( );\n\n        // Set expected Cartesian state (x, y, z, xdot, ydot, zdot).\n        const Eigen::Vector6d expectedCartesianState\n                = ( Eigen::Vector6d( ) << 0.0, 0.0, 1.0, 5.0, 6.0, -9.0 ).finished( );\n\n        // Convert spherical to Cartesian state.\n        const Eigen::Vector6d convertedCartesianState\n                = convertSphericalToCartesianState( sphericalState );\n\n        // Check that converted Cartesian state matches expected state.\n        BOOST_CHECK_SMALL( convertedCartesianState( xCartesianCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( convertedCartesianState( yCartesianCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCartesianState( zCartesianCoordinateIndex ),\n                                    convertedCartesianState( zCartesianCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCartesianState( xDotCartesianCoordinateIndex ),\n                                    convertedCartesianState( xDotCartesianCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCartesianState( yDotCartesianCoordinateIndex ),\n                                    convertedCartesianState( yDotCartesianCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCartesianState( zDotCartesianCoordinateIndex ),\n                                    convertedCartesianState( zDotCartesianCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 2: test conversion of ( 2.0, 0.0, 0.0, -4.0, 6.0, -6.0 ).\n    {\n        // Set spherical state (r, theta, phi, Vr, Vtheta, Vphi).\n        const Eigen::Vector6d sphericalState\n                = ( Eigen::Vector6d( ) << 2.0, 0.0, 0.0, -4.0, 6.0, -6.0 ).finished( );\n\n        // Set expected Cartesian state ( x, y, z, xdot, ydot, zdot).\n        const Eigen::Vector6d expectedCartesianState\n                = ( Eigen::Vector6d( ) << 2.0, 0.0, 0.0, -4.0, 6.0, -6.0 ).finished( );\n\n        // Convert spherical to Cartesian state.\n        const Eigen::Vector6d convertedCartesianState\n                = convertSphericalToCartesianState( sphericalState );\n\n        // Check that converted Cartesian state matches expected state.\n        BOOST_CHECK_CLOSE_FRACTION( expectedCartesianState( xCartesianCoordinateIndex ),\n                                    convertedCartesianState( xCartesianCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( convertedCartesianState( yCartesianCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_SMALL( convertedCartesianState( zCartesianCoordinateIndex ),\n                           std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCartesianState( xDotCartesianCoordinateIndex ),\n                                    convertedCartesianState( xDotCartesianCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCartesianState( yDotCartesianCoordinateIndex ),\n                                    convertedCartesianState( yDotCartesianCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n\n        BOOST_CHECK_CLOSE_FRACTION( expectedCartesianState( zDotCartesianCoordinateIndex ),\n                                    convertedCartesianState( zDotCartesianCoordinateIndex ),\n                                    std::numeric_limits< double >::epsilon( ) );\n    }\n\n    // Test 3: test conversion of ( 2.0, -3*pi/4, pi/4, 1.0, -sqrt( 2.0 ), 1.0 ).\n    {\n        // Set spherical state (r, theta, phi, Vr, Vtheta, Vphi).\n        const Eigen::Vector6d sphericalState\n                = ( Eigen::Vector6d( )\n                    << 2.0, -PI * 3.0 / 4.0, PI / 4.0, 1.0, -sqrt( 2.0 ), 1.0 ).finished( );\n\n        // Set expected Cartesian state (x, y, z, xdot, ydot, zdot).\n        const Eigen::Vector6d expectedCartesianState\n                = ( Eigen::Vector6d( )\n                    << -1.0, -1.0, sqrt( 2.0 ), -1.0, 1.0, sqrt( 2.0 ) ).finished( );\n\n        // Convert spherical to Cartesian state.\n        const Eigen::Vector6d convertedCartesianState\n                = convertSphericalToCartesianState( sphericalState );\n\n        // Check that converted Cartesian state matches the expected state.\n        TUDAT_CHECK_MATRIX_CLOSE_FRACTION( expectedCartesianState, convertedCartesianState,\n                                           1.0e-15 );\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "3cf592f5553e78cef6ef7265465a6341754386ae", "size": 41545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/math/basic/unitTestCoordinateConversions.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/math/basic/unitTestCoordinateConversions.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/math/basic/unitTestCoordinateConversions.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.1656804734, "max_line_length": 128, "alphanum_fraction": 0.6022144662, "num_tokens": 9596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6232659378475269}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/LU>\n\n#include <iostream>\n#include <iomanip>\n\n#include \"timer.h\"\n\n// Models a resistence between node i,j with i < j (could, in principle, handle different resistences)\ntypedef std::pair< int, int>            resistor;\n// Vector containing all resistences in the circuit (excluded the variable one, which is modelled afterwards)\ntypedef std::vector< resistor >         resistor_topology;\n// Models a ground or source of voltage, indexes store the node connected to the ground/source through a resistence\ntypedef std::tuple<int, int, double>    voltage;\n// Vector containing a voltage object for each node connected to sink or source.\ntypedef std::vector< voltage >          voltage_topology;\n\n//! \\brief Class implementing the topology of the circuit (cf. Figure)\n//! Computes impedance of the entire circuit (between node 16 and 17) exploiting\n//! the SMW formula for the inversion of low rank perturbations of a matrix A0,\n//! whose factorization in known in advance\ntemplate <class Matrix>\nclass ImpedanceMap {\n    static const std::size_t nnodes = 15; //< Compile time hard-coded size of circuit\npublic:\n    //! \\brief Constructor: Builds system matrix and rhs and performs lu decomposition\n    //! The lu decomposition is stored in lu and can be reused in the SMW formula\n    //! to avoid expensive matrix solves for repeated usages of the operator()\n    //! \\param R_ resistence R\n    //! \\param W_ source voltage W at node 16, gound is 0 at node 17\n    ImpedanceMap(double R_, double W_) : R(R_), W(W_) {\n        // In the following, instead of specifying directly the entries of A\\_0 and of rhs\n        // we define some auxiliary structure and automatically generate the right entries for\n        // the structures we specified.\n        // This way: we avoid silly mistakes, avoid a very long list of matrix entreis specifications,\n        // have a flexible way (we may easily change the topology) and automatically take care of shifting the indices\n        // Of course, if you want, you can manually put each entry in the matrix and rhs. The result (should) be the same)\n        \n        // We implement the topology of the resistances by pushing each\n        // Resistance between node i < j in a std::vector of pair (i,j) \\in \\mathbb{N}^2\n        // This way we can automatically build a symmetric matrix, take care of indexing \n        // and avoid dumb mistakes during the matrix filling\n        resistor_topology T;\n        T.reserve(23);\n        T.push_back(resistor(1,2));\n        T.push_back(resistor(1,5));\n        T.push_back(resistor(2,5));\n        T.push_back(resistor(2,3));\n        T.push_back(resistor(2,14));\n        T.push_back(resistor(3,4));\n        T.push_back(resistor(3,15));\n        T.push_back(resistor(4,6));\n        T.push_back(resistor(4,15));\n        T.push_back(resistor(5,7));\n        T.push_back(resistor(5,14));\n        T.push_back(resistor(6,9));\n        T.push_back(resistor(6,15));\n        T.push_back(resistor(7,10));\n        T.push_back(resistor(7,11));\n        T.push_back(resistor(8,9));\n        T.push_back(resistor(8,12));\n        T.push_back(resistor(8,13));\n        T.push_back(resistor(8,15));\n        T.push_back(resistor(9,13));\n        T.push_back(resistor(10,11));\n        T.push_back(resistor(11,12));\n        T.push_back(resistor(12,13));\n        // Default matrix entries sert to one (varistor)\n        T.push_back(resistor(14,15));\n        \n        // We implement voltage gound and source topology by specifiying which node is connected to ground/source\n        // trough a resistance. This will be also part of rhs\n        voltage_topology S;\n        S.reserve(4);\n        S.push_back(voltage(6, 16, W));\n        S.push_back(voltage(7, 17, 0));\n        S.push_back(voltage(11,17, 0));\n        S.push_back(voltage(14,17, 0));\n        \n        // Automatically build A0 filling from topology\n        Matrix A0 = Matrix::Zero(nnodes, nnodes);\n        for(auto it: T) {\n            // Shift indeces down by 1\n            auto i = it.first - 1;\n            auto j = it.second - 1;\n            // Fill diagonal: each resistance contributes += R into the diagonal of both nodes\n            A0(i,i) += 1;\n            A0(j,j) += 1;\n            // Fill the off diagonal (negative part in \\Delta W_{i,j}, the matrix is kept symmetric\n            A0(i,j) -= 1;\n            A0(j,i) -= 1;\n        }\n        \n        // Fill in the rest (source and ground), i.e. components with $\\Delta W_{i,j}$ with j > 15\n        // Each node i connected to ground or source contributes to the rhs with R * W (R resistence between node i and ground/source\n        // node, W is voltage at sink or source) and to its own diagonal with R\n        rhs = Matrix::Zero(nnodes,1);\n        for(auto it: S) {\n            // Shift index down by 1 and get voltage in W2\n            int i = std::get<0>(it) - 1;\n            auto W2 = std::get<2>(it);\n            // Add voltage in rhs (resistance assumed to be R)\n            rhs(i) += W2;\n            // Add resistance to matrix diagonal: contribution of source current\n            A0(i,i) += 1;\n        }\n        \n        // Precompute lu factorizaion of A0\n        lu = A0.lu();\n    };\n    \n    //! \\brief Compute the impedance given the resistence variable R_x\n    //! Use SMW formula for low rank perturbations to avoid expensive inversion\n    //! if factorization of the base system matrix is already known\n    //! \\param Rx resistence R_x > 0 of the varistor between node 14 and 15\n    //! \\return impedance = W  * I of the system A(R_x)\n    double operator()(double Rx) {\n        // Store the scaled factor for convenience\n        double fac = R/Rx;\n        \n        // There are many ways to create the same matrix u*v\n        // Create U, the 15x2 matrix in (A+UV)\n        Matrix U = Matrix::Zero(nnodes, 1);\n        U(13) = -1;\n        U(14) = 1;\n        // V will be U tranps\n        \n        //// Use SMW formula to compute (A + UU')^{-1} rhs\n        // Formula is A^{-1} rhs - A^{-1} * u * (I + V*A^{-1}*U)^{-1} V * A^{-1}\n        \n        // Start by precomputing A^{-1} rhs (needed twice), column vector of length 15\n        auto Ainvrhs = lu.solve(rhs);\n        // The precompute A^{-1} U (15x2 matrix), needed twice\n        auto Ainvu = lu.solve(U);\n        // The compute alpha, 2x2 matrix whose inverse is cheap\n        auto alpha = (Matrix::Identity(2,2) + U.transpose() / -1 * (1-fac) * Ainvu).inverse();\n        // Put the formula toghether, x is a 15x1 column vector containing voltages at each node (except 16,17, prescribed)\n        auto x = Ainvrhs - Ainvu * alpha * U.transpose() / -1 * (1-fac) * Ainvrhs;\n        \n        // Compute the current I = \\Delta W_{16,5} / R and then impedance = W / I\n        // \\Delta W_{16,5} = (W - x_5)\n        return W * R / (W - x(5));\n    };\nprivate:\n    Eigen::PartialPivLU< Matrix > lu; //< Store lu decomposition of a for efficiency\n    double R, W; //< Resistance R and source voltage W\n    Matrix rhs; //< Store rhs vector prescribing sink and source voltages\n};\n\nint main(void) {\n    ImpedanceMap<Eigen::MatrixXd> IM = ImpedanceMap<Eigen::MatrixXd>(1, 1);\n    std::cout << \"Impedance [R = 1]: \" << IM(1) << std::endl;\n    \n    std::cout << std::setw(30) << \"Impedance [Ohm]\" << std::setw(30) << \"R_x [Ohm]\" << std::endl;\n    std::cout << std::setw(30) << IM(0)             << std::setw(30) << \" \" << 0 << std::endl;\n    std::cout << std::setw(30) << IM(0.1)           << std::setw(30) << \" \" << 0.1 << std::endl;\n    for(auto Rx = 1; Rx <= 1024; Rx *= 2) {\n        std::cout << std::setw(30) << IM(Rx)        << std::setw(30) << \" \" << Rx << std::endl;\n    }\n    \n    timer<> tmr;\n    tmr.start();\n    ImpedanceMap<Eigen::MatrixXd> IM2 = ImpedanceMap<Eigen::MatrixXd>(1, 1);\n    IM2(1);\n    tmr.stop();\n    std::cout << \"Took:             \" << tmr.min().count() / 1000000. << \" ms\" << std::endl;\n    \n}\n", "meta": {"hexsha": "df70f63d1de84179d75c410b794d97dc4ca8dd30", "size": 7886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS3/solutions_ps3/impedancemap.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS3/solutions_ps3/impedancemap.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS3/solutions_ps3/impedancemap.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6627218935, "max_line_length": 133, "alphanum_fraction": 0.6001775298, "num_tokens": 2135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6231470366710767}}
{"text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <Eigen/Core>\n#include <QApplication>\n#include <visoptslider/visoptslider.hpp>\n#include <optimization-test-functions.hpp>\n\nint main(int argc, char *argv[])\n{\n    QApplication app(argc, argv);\n\n    // Define the target function and bound\n    constexpr int num_dimensions = 3;\n    constexpr auto target_function = [](const Eigen::VectorXd& x)\n    {\n        return otf::GetValue(x, otf::FunctionType::Rosenbrock);\n    };\n    const Eigen::Vector3d upper_bound(+ 2.0, + 2.0, + 2.0);\n    const Eigen::Vector3d lower_bound(- 2.0, - 2.0, - 2.0);\n    constexpr double maximum_value = 200.0;\n    constexpr double minimum_value = 0.0;\n\n    // Optional settings\n    const std::vector<std::string> labels = { \"x1\", \"x2\", \"x3\" };\n    constexpr bool show_values = true;\n    constexpr int resolution = 200;\n\n    // Instantiate and initialize the widget\n    visopt::SlidersWidget sliders_widget;\n    sliders_widget.initialize(num_dimensions,\n                              target_function,\n                              upper_bound,\n                              lower_bound,\n                              maximum_value,\n                              minimum_value,\n                              labels,\n                              show_values,\n                              resolution);\n\n    // Set a callback function\n    sliders_widget.setCallback([&sliders_widget]()\n    {\n        std::cout << sliders_widget.getArgument().transpose() << std::endl;\n    });\n\n    // Show the widget\n    sliders_widget.show();\n    return app.exec();\n}\n", "meta": {"hexsha": "b7e8c7a6504c1e9675a95c25b86a4077923a4570", "size": 1585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/simple_test.cpp", "max_stars_repo_name": "yuki-koyama/visoptslider", "max_stars_repo_head_hexsha": "6443107392e9cb5ee4d215f9eec30e780957bae6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-02-28T13:02:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-10T09:56:25.000Z", "max_issues_repo_path": "tests/simple_test.cpp", "max_issues_repo_name": "yuki-koyama/visoptslider", "max_issues_repo_head_hexsha": "6443107392e9cb5ee4d215f9eec30e780957bae6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-07-09T23:38:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-16T05:23:38.000Z", "max_forks_repo_path": "tests/simple_test.cpp", "max_forks_repo_name": "yuki-koyama/visoptslider", "max_forks_repo_head_hexsha": "6443107392e9cb5ee4d215f9eec30e780957bae6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-03-19T22:33:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-10T09:56:29.000Z", "avg_line_length": 31.0784313725, "max_line_length": 75, "alphanum_fraction": 0.5798107256, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6231470338532931}}
{"text": "// Copyright Nick Thompson, 2020\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_INTERPOLATORS_PCHIP_HPP\n#define BOOST_MATH_INTERPOLATORS_PCHIP_HPP\n#include <memory>\n#include <boost/math/interpolators/detail/cubic_hermite_detail.hpp>\n\nnamespace boost::math::interpolators {\n\ntemplate<class RandomAccessContainer>\nclass pchip {\npublic:\n    using Real = typename RandomAccessContainer::value_type;\n\n    pchip(RandomAccessContainer && x, RandomAccessContainer && y,\n          Real left_endpoint_derivative = std::numeric_limits<Real>::quiet_NaN(),\n          Real right_endpoint_derivative = std::numeric_limits<Real>::quiet_NaN())\n    {\n        if (x.size() < 4)\n        {\n            throw std::domain_error(\"Must be at least four data points.\");\n        }\n        RandomAccessContainer s(x.size(), std::numeric_limits<Real>::quiet_NaN());\n        if (isnan(left_endpoint_derivative))\n        {\n            // O(h) finite difference derivative:\n            // This, I believe, is the only derivative guaranteed to be monotonic:\n            s[0] = (y[1]-y[0])/(x[1]-x[0]);\n        }\n        else\n        {\n            s[0] = left_endpoint_derivative;\n        }\n\n        for (decltype(s.size()) k = 1; k < s.size()-1; ++k) {\n            Real hkm1 = x[k] - x[k-1];\n            Real dkm1 = (y[k] - y[k-1])/hkm1;\n\n            Real hk = x[k+1] - x[k];\n            Real dk = (y[k+1] - y[k])/hk;\n            Real w1 = 2*hk + hkm1;\n            Real w2 = hk + 2*hkm1;\n            if ( (dk > 0 && dkm1 < 0) || (dk < 0 && dkm1 > 0) || dk == 0 || dkm1 == 0)\n            {\n                s[k] = 0;\n            }\n            else\n            {\n                s[k] = (w1+w2)/(w1/dkm1 + w2/dk);\n            }\n\n        }\n        // Quadratic extrapolation at the other end:\n        auto n = s.size();\n        if (isnan(right_endpoint_derivative))\n        {\n            s[n-1] = (y[n-1]-y[n-2])/(x[n-1] - x[n-2]);\n        }\n        else\n        {\n            s[n-1] = right_endpoint_derivative;\n        }\n        impl_ = std::make_shared<detail::cubic_hermite_detail<RandomAccessContainer>>(std::move(x), std::move(y), std::move(s));\n    }\n\n    Real operator()(Real x) const {\n        return impl_->operator()(x);\n    }\n\n    Real prime(Real x) const {\n        return impl_->prime(x);\n    }\n\n    friend std::ostream& operator<<(std::ostream & os, const pchip & m)\n    {\n        os << *m.impl_;\n        return os;\n    }\n\n    void push_back(Real x, Real y) {\n        using std::abs;\n        using std::isnan;\n        if (x <= impl_->x_.back()) {\n             throw std::domain_error(\"Calling push_back must preserve the monotonicity of the x's\");\n        }\n        impl_->x_.push_back(x);\n        impl_->y_.push_back(y);\n        impl_->dydx_.push_back(std::numeric_limits<Real>::quiet_NaN());\n        auto n = impl_->size();\n        impl_->dydx_[n-1] = (impl_->y_[n-1]-impl_->y_[n-2])/(impl_->x_[n-1] - impl_->x_[n-2]);\n        // Now fix s_[n-2]:\n        auto k = n-2;\n        Real hkm1 = impl_->x_[k] - impl_->x_[k-1];\n        Real dkm1 = (impl_->y_[k] - impl_->y_[k-1])/hkm1;\n\n        Real hk = impl_->x_[k+1] - impl_->x_[k];\n        Real dk = (impl_->y_[k+1] - impl_->y_[k])/hk;\n        Real w1 = 2*hk + hkm1;\n        Real w2 = hk + 2*hkm1;\n        if ( (dk > 0 && dkm1 < 0) || (dk < 0 && dkm1 > 0) || dk == 0 || dkm1 == 0)\n        {\n            impl_->dydx_[k] = 0;\n        }\n        else\n        {\n            impl_->dydx_[k] = (w1+w2)/(w1/dkm1 + w2/dk);\n        }\n    }\n\nprivate:\n    std::shared_ptr<detail::cubic_hermite_detail<RandomAccessContainer>> impl_;\n};\n\n}\n#endif", "meta": {"hexsha": "3a37ddf67a65aaa44da5784b417cd476b2786eb5", "size": 3720, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/math/interpolators/pchip.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": "3rdparty/boost_1_73_0/boost/math/interpolators/pchip.hpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": "3rdparty/boost_1_73_0/boost/math/interpolators/pchip.hpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": 31.2605042017, "max_line_length": 128, "alphanum_fraction": 0.5255376344, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6231470187249786}}
{"text": "#ifndef MLT_MODELS_REGRESSORS_RIDGE_REGRESSION_HPP\n#define MLT_MODELS_REGRESSORS_RIDGE_REGRESSION_HPP\n\n#include <type_traits>\n\n#include <Eigen/Core>\n\n#include \"linear_regressor.hpp\"\n#include \"../../utils/linear_solvers.hpp\"\n\nnamespace mlt {\nnamespace models {\nnamespace regressors {\n\tusing namespace utils::linear_solvers;\n\n\ttemplate <class Solver = SVDSolver>\n\tclass RidgeRegression : public LinearRegressor<RidgeRegression<Solver>> {\n\tpublic:\n\t\texplicit RidgeRegression(double regularization, bool fit_intercept = true) : LinearRegressor(fit_intercept),\n\t\t\t_regularization(regularization), _solver(Solver()) {}\n\n\t\ttemplate <class S, class = enable_if<is_same<decay_t<S>, Solver>::value>>\n\t\texplicit RidgeRegression(double regularization, S&& solver, bool fit_intercept = true) : LinearRegressor(fit_intercept),\n\t\t\t_regularization(regularization), _solver(forward<S>(solver)) {}\n\n\t\tSelf& fit(Features input, Target target, bool = true) {\n\t\t\tMatrixXd input_prime(input.rows() + (_fit_intercept ? 1 : 0), input.cols());\n\t\t\tinput_prime.topRows(input.rows()) << input;\n\t\t\tMatrixXd reg = MatrixXd::Identity(input_prime.rows(), input_prime.rows()) * _regularization;\n\n\t\t\tif (_fit_intercept) {\n\t\t\t\tinput_prime.bottomRows<1>() = VectorXd::Ones(input.cols());\n\t\t\t\treg(reg.rows() - 1, reg.cols() - 1) = 0;\n\t\t\t}\n\n\t\t\t_set_coefficients(_solver.compute((input_prime * input_prime.transpose() + reg)).solve(input_prime * target.transpose()).transpose());\n\n\t\t\treturn _self();\n\t\t}\n\n\tprotected:\n\t\tdouble _regularization;\n\t\tSolver _solver;\n\t};\n}\n}\n}\n#endif", "meta": {"hexsha": "7851906689cb898231bd034a2b94fe5508c051b6", "size": 1538, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/models/regressors/ridge_regression.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/mlt/models/regressors/ridge_regression.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlt/models/regressors/ridge_regression.hpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0416666667, "max_line_length": 137, "alphanum_fraction": 0.7392717815, "num_tokens": 376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6231447156826978}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <stdexcept>\n#include <functional>\n#include <mutex>\n#include <Eigen/Geometry>\n\n#ifndef SIMPLE_DTW_HPP\n#define SIMPLE_DTW_HPP\n\nnamespace simple_dtw\n{\n    template<typename FirstDatatype, typename SecondDatatype, typename DistanceFn,\n             typename FirstAllocator = std::allocator<FirstDatatype>,\n             typename SecondAllocator = std::allocator<SecondDatatype>>\n    class SimpleDTW\n    {\n    private:\n\n        void InitializeMatrix(const size_t first_sequence_size, const size_t second_sequence_size)\n        {\n            const ssize_t rows = (ssize_t)first_sequence_size + 1;\n            const ssize_t cols = (ssize_t)second_sequence_size + 1;\n            if (dtw_matrix_.rows() < rows || dtw_matrix_.cols() < cols)\n            {\n                dtw_matrix_ = Eigen::MatrixXd::Zero(rows, cols);\n                if (rows > 1 && cols > 1)\n                {\n                    for (ssize_t row = 1; row < rows; row++)\n                    {\n                        dtw_matrix_(row, 0) = std::numeric_limits<double>::infinity();\n                    }\n                    for (ssize_t col = 1; col < cols; col++)\n                    {\n                        dtw_matrix_(0, col) = std::numeric_limits<double>::infinity();\n                    }\n                }\n            }\n\n        }\n\n        Eigen::MatrixXd dtw_matrix_;\n\n    public:\n\n        SimpleDTW()\n        {\n            InitializeMatrix(0, 0);\n        }\n\n        SimpleDTW(const size_t first_sequence_size, const size_t second_sequence_size)\n        {\n            InitializeMatrix(first_sequence_size, second_sequence_size);\n        }\n\n        double EvaluateWarpingCost(\n                const std::vector<FirstDatatype, FirstAllocator>& first_sequence,\n                const std::vector<SecondDatatype, SecondAllocator>& second_sequence,\n                const DistanceFn& distance_fn)\n        {\n            InitializeMatrix(first_sequence.size(), second_sequence.size());\n            //Compute DTW cost for the two sequences\n            for (ssize_t i = 1; i <= (ssize_t)first_sequence.size(); i++)\n            {\n                const FirstDatatype& first_item = first_sequence[(size_t)i - 1];\n                for (ssize_t j = 1; j <= (ssize_t)second_sequence.size(); j++)\n                {\n                    const SecondDatatype& second_item = second_sequence[(size_t)j - 1];\n                    const double index_cost = distance_fn(first_item, second_item);\n                    double prev_cost = 0.0;\n                    // Get the three neighboring values from the matrix to use for the update\n                    double im1j = dtw_matrix_(i - 1, j);\n                    double im1jm1 = dtw_matrix_(i - 1, j - 1);\n                    double ijm1 = dtw_matrix_(i, j - 1);\n                    // Start the update step\n                    if (im1j < im1jm1 && im1j < ijm1)\n                    {\n                        prev_cost = im1j;\n                    }\n                    else if (ijm1 < im1j && ijm1 < im1jm1)\n                    {\n                        prev_cost = ijm1;\n                    }\n                    else\n                    {\n                        prev_cost = im1jm1;\n                    }\n                    // Update the value in the matrix\n                    const double new_cost = index_cost + prev_cost;\n                    dtw_matrix_(i, j) = new_cost;\n                }\n            }\n            //Return total path cost\n            const double warping_cost = dtw_matrix_((ssize_t)first_sequence.size(), (ssize_t)second_sequence.size());\n            return warping_cost;\n        }\n    };\n\n    // DistanceFn must match the prototype std::function<double(const FirstDataype&, const SecondDatatype&)>\n    template<typename FirstDatatype, typename SecondDatatype, typename DistanceFn,\n             typename FirstAllocator = std::allocator<FirstDatatype>,\n             typename SecondAllocator = std::allocator<SecondDatatype>>\n    inline double ComputeDTWDistance(\n            const std::vector<FirstDatatype, FirstAllocator>& first_sequence,\n            const std::vector<SecondDatatype, SecondAllocator>& second_sequence,\n            const DistanceFn& distance_fn)\n    {\n        SimpleDTW<FirstDatatype, SecondDatatype, DistanceFn, FirstAllocator, SecondAllocator> dtw_evaluator;\n        return dtw_evaluator.EvaluateWarpingCost(first_sequence, second_sequence, distance_fn);\n    }\n}\n\n#endif // SIMPLE_DTW_HPP\n", "meta": {"hexsha": "ca3a225b6437b52cb6b15526991694d3094460df", "size": 4543, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/simple_dtw.hpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/simple_dtw.hpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/simple_dtw.hpp", "max_forks_repo_name": "473867143/Prometheus", "max_forks_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 38.5, "max_line_length": 117, "alphanum_fraction": 0.5546995378, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.7248702880639792, "lm_q1q2_score": 0.6231447000454562}}
{"text": "//\n// Copyright (c) 2020 CNRS INRIA\n//\n\n#include \"pinocchio/autodiff/cppad.hpp\"\n#include \"pinocchio/multibody/model.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n\n#include \"utils/model-generator.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nusing namespace pinocchio;\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_joint_configuration)\n{\n  typedef double Scalar;\n  using CppAD::AD;\n  using CppAD::NearEqual;\n  \n  typedef AD<Scalar> ADScalar;\n\n  typedef pinocchio::ModelTpl<Scalar> Model;\n\n  Model model; buildAllJointsModel(model);\n  Eigen::VectorXd q2 = Eigen::VectorXd::Random(model.nq);\n  Eigen::VectorXd q1 = Eigen::VectorXd::Random(model.nq);\n  normalize(model,q1);\n  normalize(model,q2);\n  \n  Eigen::VectorXd v = Eigen::VectorXd::Random(model.nv);\n  std::vector<Eigen::VectorXd> results_q(2,Eigen::VectorXd::Zero(model.nq));\n  std::vector<Eigen::VectorXd> results_v(2,Eigen::VectorXd::Zero(model.nv));\n  \n  typedef pinocchio::ModelTpl<ADScalar> ADModel;\n  typedef ADModel::ConfigVectorType ADConfigVectorType;\n  ADModel ad_model = model.cast<ADScalar>();\n  ADConfigVectorType ad_q1(model.nq);\n  ADConfigVectorType ad_q2(model.nq);\n  ADConfigVectorType ad_v(model.nv);\n\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,1> VectorX;\n  typedef Eigen::Matrix<ADScalar,Eigen::Dynamic,1> VectorXAD;\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> MatrixX;\n  typedef Eigen::Matrix<ADScalar,Eigen::Dynamic,Eigen::Dynamic> MatrixXAD;\n  \n  //Integrate\n  {\n    VectorXAD ad_x(model.nq+model.nv);\n    ad_x << q1.cast<ADScalar>(), v.cast<ADScalar>();\n    CppAD::Independent(ad_x);\n    ad_q1 = ad_x.head(model.nq);\n    ad_v = ad_x.tail(model.nv);\n    \n    VectorXAD ad_y(model.nq);\n    pinocchio::integrate(ad_model,ad_q1,ad_v,ad_y);\n    CppAD::ADFun<Scalar> ad_fun(ad_x,ad_y);\n    \n    CPPAD_TESTVECTOR(Scalar) x_eval((size_t)(ad_x.size()));\n    Eigen::Map<VectorX>(x_eval.data(),ad_x.size()) << q1,v;\n    CPPAD_TESTVECTOR(Scalar) y_eval((size_t)(ad_y.size()));\n    y_eval = ad_fun.Forward(0,x_eval);\n    results_q[0] = Eigen::Map<VectorX>(y_eval.data(),ad_y.size());\n    \n    pinocchio::integrate(model,q1,v,results_q[1]);\n    BOOST_CHECK(results_q[0].isApprox(results_q[1]));\n    \n    Eigen::Map<VectorX>(x_eval.data(),ad_x.size()) << q1,VectorX::Zero(model.nv);\n    y_eval = ad_fun.Forward(0,x_eval);\n    results_q[0] = Eigen::Map<VectorX>(y_eval.data(),ad_y.size());\n    BOOST_CHECK(results_q[0].isApprox(q1));\n  }\n\n  //Difference\n  {\n    VectorXAD ad_x(model.nq+model.nq);\n    ad_x << q1.cast<ADScalar>(), q2.cast<ADScalar>();\n    CppAD::Independent(ad_x);\n    ad_q1 = ad_x.head(model.nq);\n    ad_q2 = ad_x.tail(model.nq);\n    \n    VectorXAD ad_y(model.nv);\n    pinocchio::difference(ad_model,ad_q1,ad_q2,ad_y);\n    CppAD::ADFun<Scalar> ad_fun(ad_x,ad_y);\n    \n    CPPAD_TESTVECTOR(Scalar) x_eval((size_t)(ad_x.size()));\n    Eigen::Map<VectorX>(x_eval.data(),ad_x.size()) << q1,q2;\n    CPPAD_TESTVECTOR(Scalar) y_eval((size_t)(ad_y.size()));\n    y_eval = ad_fun.Forward(0,x_eval);\n    results_v[0] = Eigen::Map<VectorX>(y_eval.data(),ad_y.size());\n    \n    pinocchio::difference(model,q1,q2,results_v[1]);\n    BOOST_CHECK(results_v[0].isApprox(results_v[1]));\n    \n    Eigen::Map<VectorX>(x_eval.data(),ad_x.size()) << q1,q1;\n    y_eval = ad_fun.Forward(0,x_eval);\n    results_v[0] = Eigen::Map<VectorX>(y_eval.data(),ad_y.size());\n    BOOST_CHECK(results_v[0].isZero());\n  }\n\n  //dDifference\n  std::vector<MatrixX> results_J0(2,MatrixX::Zero(model.nv,model.nv));\n  std::vector<MatrixX> results_J1(2,MatrixX::Zero(model.nv,model.nv));\n  {\n    VectorXAD ad_x(model.nq+model.nq);\n    ad_x << q1.cast<ADScalar>(), q2.cast<ADScalar>();\n    CppAD::Independent(ad_x);\n    ad_q1 = ad_x.head(model.nq);\n    ad_q2 = ad_x.tail(model.nq);\n    \n    MatrixXAD ad_y(2*model.nv,model.nv);\n    pinocchio::dDifference(ad_model,ad_q1,ad_q2,ad_y.topRows(model.nv),pinocchio::ARG0);\n    pinocchio::dDifference(ad_model,ad_q1,ad_q2,ad_y.bottomRows(model.nv),pinocchio::ARG1);\n    VectorXAD ad_y_flatten = Eigen::Map<VectorXAD>(ad_y.data(),ad_y.size());\n    CppAD::ADFun<Scalar> ad_fun(ad_x,ad_y_flatten);\n    \n    CPPAD_TESTVECTOR(Scalar) x_eval((size_t)(ad_x.size()));\n    Eigen::Map<VectorX>(x_eval.data(),ad_x.size()) << q1, q2;\n    CPPAD_TESTVECTOR(Scalar) y_eval((size_t)(ad_y.size()));\n    y_eval = ad_fun.Forward(0,x_eval);\n    results_J0[0] = Eigen::Map<MatrixX>(y_eval.data(),ad_y.rows(),ad_y.cols()).topRows(model.nv);\n    results_J1[0] = Eigen::Map<MatrixX>(y_eval.data(),ad_y.rows(),ad_y.cols()).bottomRows(model.nv);\n    \n    // w.r.t q1\n    pinocchio::dDifference(model,q1,q2,results_J0[1],pinocchio::ARG0);\n    BOOST_CHECK(results_J0[0].isApprox(results_J0[1]));\n    \n    // w.r.t q2\n    pinocchio::dDifference(model,q1,q2,results_J1[1],pinocchio::ARG1);\n    BOOST_CHECK(results_J1[0].isApprox(results_J1[1]));\n    \n    Eigen::Map<VectorX>(x_eval.data(),ad_x.size()) << q1, q1;\n    y_eval = ad_fun.Forward(0,x_eval);\n    results_J0[0] = Eigen::Map<MatrixX>(y_eval.data(),ad_y.rows(),ad_y.cols()).topRows(model.nv);\n    results_J1[0] = Eigen::Map<MatrixX>(y_eval.data(),ad_y.rows(),ad_y.cols()).bottomRows(model.nv);\n    \n    BOOST_CHECK((-results_J0[0]).isIdentity());\n    BOOST_CHECK(results_J1[0].isIdentity());\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "a6913a708b37ae0cca550a02058beb27cb0b0c1d", "size": 5321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/cppad-joint-configurations.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "unittest/cppad-joint-configurations.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "unittest/cppad-joint-configurations.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 36.1972789116, "max_line_length": 100, "alphanum_fraction": 0.6878406315, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6231446899294367}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_random.h>\n#include <OpenTissue/core/math/big/big_types.h>\n#include <OpenTissue/core/math/big/big_generate_random.h>\n#include <OpenTissue/core/math/big/big_is_orthonormal.h>\n#include <OpenTissue/core/math/big/big_gram_schmidt.h>\n\n#include <OpenTissue/core/math/big/big_generate_PD.h>\n#include <OpenTissue/core/math/big/big_generate_PSD.h>\n#include <OpenTissue/core/math/big/big_is_symmetric.h>\n\n\n#include <OpenTissue/core/math/big/io/big_matlab_write.h>\n\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_math_big_modified_gram_schmidt);\n\nBOOST_AUTO_TEST_CASE(random_test_case)\n{\n  typedef ublas::compressed_matrix<double> matrix_type;\n\n  matrix_type A;\n\n  for(size_t tst=0;tst<5;++tst)\n  {\n    OpenTissue::math::big::generate_random(10, 10, A);\n\n    bool not_ortho = !OpenTissue::math::big::is_orthonormal( A );\n    BOOST_CHECK(not_ortho);\n\n    OpenTissue::math::big::gram_schmidt(A);\n\n    bool did_it = OpenTissue::math::big::is_orthonormal( A );\n    BOOST_CHECK(did_it);\n  }\n\n\n  {\n    using namespace OpenTissue::math::big;\n    OpenTissue::math::big::fast_generate_PD( 10, A );\n\n    std::cout << \"A = \" << A << \";\" <<std::endl;\n\n    bool is_ok = OpenTissue::math::big::is_symmetric( A );\n    BOOST_CHECK(is_ok);\n\n    OpenTissue::math::big::generate_PSD( 10, A, 0.5 );\n\n    std::cout << \"B = \" << A << \";\" <<std::endl;\n\n    bool is_also_ok = OpenTissue::math::big::is_symmetric( A );\n    BOOST_CHECK(is_also_ok);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "547c905e23b72804b535a673ffd45abdec299051", "size": 1981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/math/big/mgs/src/unit_mgs.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/math/big/mgs/src/unit_mgs.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/math/big/mgs/src/unit_mgs.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 28.3, "max_line_length": 78, "alphanum_fraction": 0.7349823322, "num_tokens": 537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6231446796075448}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions.hpp>\n\nTEST(ProbDistributionsPoisson, error_check) {\n  using std::log;\n\n  boost::random::mt19937 rng;\n  EXPECT_NO_THROW(stan::math::poisson_rng(6, rng));\n\n  EXPECT_THROW(stan::math::poisson_rng(-6, rng), std::domain_error);\n\n  EXPECT_NO_THROW(stan::math::poisson_rng(1e9, rng));\n\n  EXPECT_THROW(stan::math::poisson_rng(pow(2.0, 31), rng), std::domain_error);\n\n  EXPECT_NO_THROW(stan::math::poisson_log_rng(6, rng));\n\n  EXPECT_NO_THROW(stan::math::poisson_log_rng(-6, rng));\n\n  EXPECT_NO_THROW(stan::math::poisson_log_rng(log(1e9), rng));\n\n  EXPECT_THROW(stan::math::poisson_log_rng(log(pow(2.0, 31)), rng),\n               std::domain_error);\n}\n\nTEST(ProbDistributionsPoisson, chiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  int N = 1000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::poisson_distribution<> dist(5);\n  boost::math::chi_squared mydist(K - 1);\n\n  int loc[K - 1];\n  for (int i = 1; i < K; i++)\n    loc[i - 1] = i - 1;\n\n  int count = 0;\n  double bin[K];\n  double expect[K];\n  for (int i = 0; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N * pdf(dist, i);\n  }\n  expect[K - 1] = N * (1 - cdf(dist, K - 1));\n\n  while (count < N) {\n    int a = stan::math::poisson_rng(5, rng);\n    int i = 0;\n    while (i < K - 1 && a > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n  }\n\n  double chi = 0;\n\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsPoisson, chiSquareGoodnessFitTest2) {\n  using std::log;\n\n  boost::random::mt19937 rng;\n  int N = 1000;\n  int K = boost::math::round(2 * std::pow(N, 0.4));\n  boost::math::poisson_distribution<> dist(5);\n  boost::math::chi_squared mydist(K - 1);\n\n  int loc[K - 1];\n  for (int i = 1; i < K; i++)\n    loc[i - 1] = i - 1;\n\n  int count = 0;\n  double bin[K];\n  double expect[K];\n  for (int i = 0; i < K; i++) {\n    bin[i] = 0;\n    expect[i] = N * pdf(dist, i);\n  }\n  expect[K - 1] = N * (1 - cdf(dist, K - 1));\n\n  while (count < N) {\n    int a = stan::math::poisson_log_rng(log(5), rng);\n    int i = 0;\n    while (i < K - 1 && a > loc[i])\n      ++i;\n    ++bin[i];\n    count++;\n  }\n\n  double chi = 0;\n\n  for (int j = 0; j < K; j++)\n    chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]);\n\n  EXPECT_TRUE(chi < quantile(complement(mydist, 1e-6)));\n}\n", "meta": {"hexsha": "29d21aaa8715df19a4bc1efe5ee40271bac2ae24", "size": 2508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/prob/poisson_test.cpp", "max_stars_repo_name": "sakrejda/math", "max_stars_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/math/prim/scal/prob/poisson_test.cpp", "max_issues_repo_name": "sakrejda/math", "max_issues_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/math/prim/scal/prob/poisson_test.cpp", "max_forks_repo_name": "sakrejda/math", "max_forks_repo_head_hexsha": "3cc99955807cf1f4ea51efd79aa3958b74d24af2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3495145631, "max_line_length": 78, "alphanum_fraction": 0.5825358852, "num_tokens": 891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.623097772101931}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, log_inv_logit) {\n  using stan::math::log_inv_logit;\n  using std::log;\n  using stan::math::inv_logit;\n\n  EXPECT_FLOAT_EQ(log(inv_logit(-7.2)), log_inv_logit(-7.2));\n  EXPECT_FLOAT_EQ(log(inv_logit(0.0)), log_inv_logit(0.0));\n  EXPECT_FLOAT_EQ(log(inv_logit(1.9)), log_inv_logit(1.9));\n}\n\nTEST(MathFunctions, log_inv_logit_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  \n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::log_inv_logit(nan));\n}\n", "meta": {"hexsha": "b7f72657cd925f076e3dd9fb57ed66995ae80893", "size": 617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log_inv_logit_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log_inv_logit_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/log_inv_logit_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.380952381, "max_line_length": 61, "alphanum_fraction": 0.71636953, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6230977672770311}}
{"text": "#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector2.hpp>\n#include <boost/numeric/bindings/traits/ublas_sparse.hpp>\n#include <boost/numeric/bindings/mumps/mumps_driver.hpp>\n#include <iostream>\n#include <fstream>\n#include <complex>\n\ntemplate <typename T>\nint test() {\n  namespace ublas = ::boost::numeric::ublas ;\n  namespace mumps = ::boost::numeric::bindings::mumps ;\n\n\n  int const n = 10 ;\n\n  typedef ublas::coordinate_matrix<T, ublas::column_major, 1, ublas::unbounded_array<int> > coo_type ;\n\n  coo_type coo( n, n, n + 6 ) ;\n\n  for (int i=0; i<n; ++i) coo(i,i) = i+1.0 ;\n  coo(2,3) = T(1.0) ;\n  coo(2,4) = T(1.0) ;\n  coo(5,6) = T(-1.0) ;\n  coo(2,6) = T(1.0) ;\n  coo(9,0) = T(1.0) ;\n  coo(2,7) = T(-1.0) ;\n\n  coo.sort() ;\n  std::cout << \"matrix \" << coo << std::endl ;\n\n  ublas::vector<T> v( 10 ) ;\n  ublas::vector<T> w( 10 ) ;\n\n  std::fill( w.begin(), w.end(), 1.0 ) ;\n\n  for (int i=1; i<n; ++i) {\n    w(i) += w(i-1) ;\n  }\n\n  for (int i=0; i<n; ++i) {\n    v[i] = T(coo(i,i)) * w[i] ;\n  }\n  v[2] += T(coo(2,3)) * w[3] ;\n  v[2] += T(coo(2,4)) * w[4] ;\n  v[5] += T(coo(5,6)) * w[6] ;\n  v[2] += T(coo(2,6)) * w[6] ;\n  v[9] += T(coo(9,0)) * w[0] ;\n  v[2] += T(coo(2,7)) * w[7] ;\n  std::cout << \"rhs : \" << v << std::endl ;\n\n  mumps::mumps< coo_type > mumps_coo ;\n\n  mumps_coo.icntl[2]=mumps_coo.icntl[3] = 0 ;\n\n  // Analysis\n  mumps_coo.job = 1 ;\n  matrix_integer_data( mumps_coo, coo ) ;\n  driver( mumps_coo ) ;\n\n  // Factorization\n  mumps_coo.job = 2 ;\n  matrix_value_data( mumps_coo, coo ) ;\n  driver( mumps_coo ) ;\n\n  // Solve\n  mumps_coo.job = 3 ;\n  rhs_sol_value_data( mumps_coo, v ) ;\n  driver( mumps_coo ) ;\n\n  std::cout << \"w : \" << w << std::endl ;\n  std::cout << \"v : \" << v << std::endl ;\n\n  if ( norm_2( v - w ) > 1.e-10 * norm_2( v ) ) return 1 ;\n\n  return 0 ;\n}\n\nint main() {\n  if ( test<float>() ) return 1 ;\n  if ( test<double>() ) return 2 ;\n  if ( test< std::complex<float> >() ) return 3 ;\n  if ( test< std::complex<double> >() ) return 4 ;\n  return 0 ;\n}\n", "meta": {"hexsha": "382f15cf95cddfddca94fc845d5b6d0cbef38494", "size": 2105, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/bindings/mumps/test/mumps_ublas.cpp", "max_stars_repo_name": "inducer/boost-numeric-bindings", "max_stars_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "libs/numeric/bindings/mumps/test/mumps_ublas.cpp", "max_issues_repo_name": "inducer/boost-numeric-bindings", "max_issues_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/bindings/mumps/test/mumps_ublas.cpp", "max_forks_repo_name": "inducer/boost-numeric-bindings", "max_forks_repo_head_hexsha": "1f994e8a2e161cddb6577eacc76b7bc358701cbe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 23.9204545455, "max_line_length": 102, "alphanum_fraction": 0.5605700713, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6230977565776117}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[perimeter\n//` Calculate the perimeter of a polygon\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\nnamespace bg = boost::geometry; /*< Convenient namespace alias >*/\n\nint main()\n{\n    // Calculate the perimeter of a cartesian polygon\n    bg::model::polygon<bg::model::d2::point_xy<double> > poly;\n    bg::read_wkt(\"POLYGON((0 0,3 4,5 -5,-2 -4, 0 0))\", poly);\n    double perimeter = bg::perimeter(poly);\n    std::cout << \"Perimeter: \" << perimeter << std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[perimeter_output\n/*`\nOutput:\n[pre\nPerimeter: 25.7627\n]\n*/\n//]\n", "meta": {"hexsha": "130d8fdee57c571e201ec0570f4d12e3f74df554", "size": 980, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/perimeter.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "doc/src/examples/algorithms/perimeter.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "doc/src/examples/algorithms/perimeter.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 22.7906976744, "max_line_length": 79, "alphanum_fraction": 0.6918367347, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496523, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6230503084393392}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2015 Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include <rokko/rokko.hpp>\n#include <rokko/lapack.h>\n#include <boost/lexical_cast.hpp>\n\ntypedef rokko::localized_vector<double> vector_t;\ntypedef rokko::localized_matrix<double, rokko::matrix_col_major> matrix_t;\n\nint main(int argc, char *argv[]) {\n  int info;\n  int n = 6;\n  if (argc > 1) n = boost::lexical_cast<int>(argv[1]);\n  std::cout << \"n = \" << n << std::endl;\n\n  // generate symmmetric random martix\n  matrix_t mat = matrix_t::Random(n, n);\n  mat += mat.transpose().eval(); // eval() is required to avoid aliasing issue\n  std::cout << \"Input random matrix A:\\n\" << mat << std::endl;\n\n  // diagonalization\n  vector_t w(n);\n  matrix_t v = mat; // v will be overwritten by eigenvectors\n  info = LAPACKE_dsyev(LAPACK_COL_MAJOR, 'V', 'U', n, &v(0, 0), n, &w(0));\n  std::cout << \"Eigenvalues:\\n\" << w << std::endl;\n  std::cout << \"Eigenvectors:\\n\" << v << std::endl;\n\n  // check correctness of diagonalization\n  matrix_t wmat = matrix_t::Zero(n, n);\n  for (int i = 0; i < n; ++i) wmat(i, i) = w(i);\n  matrix_t check = v.transpose() * mat * v;\n  std::cout << \"Vt * A * V:\\n\" << check << std::endl;\n  std::cout << \"| W - Vt * A * V | = \" << (wmat - check).norm() << std::endl;\n}\n", "meta": {"hexsha": "bb39e668dae0dc7219361429d5370aeeb95af3c6", "size": 1646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cxx/lapack/diagonalization.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/cxx/lapack/diagonalization.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/cxx/lapack/diagonalization.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4090909091, "max_line_length": 78, "alphanum_fraction": 0.5856622114, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6230502973386741}}
{"text": "// ------ language=\"C++\" file=\"src/test-rk4.cc\"\n#include \"methods.hh\"\n#include \"types.hh\"\n\n#include <argagg/argagg.hpp>\n\n#include <vector>\n#include <cstdlib>\n#include <cmath>\n#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace pint;\n\n// ------ begin <<harmonic-oscillator>>[0]\ntemplate <typename real_t, typename vector_t>\nODE<real_t, vector_t> harmonic_oscillator\n    ( real_t omega_0\n    , real_t zeta )\n{\n    return [=] (real_t t, vector_t const &y) {\n        return vector_t\n            ( y[1]\n            , -2 * zeta * omega_0 * y[1] - omega_0*omega_0 * y[0] );\n    };\n}\n// ------ end\n// ------ begin <<backward-euler-harmonic-oscillator>>[0]\ntemplate <typename real_t, typename vector_t>\nIntegral<real_t, vector_t> backward_euler_harmonic_oscillator\n    ( real_t omega_0\n    , real_t zeta )\n{\n    return [=]\n        ( vector_t const &y\n        , real_t t_init\n        , real_t t_end ) -> vector_t\n    {\n        real_t h = t_end - t_init;\n        real_t d = 1 + 2*h*omega_0*zeta;\n        real_t q = y[0] / (1 + h * (1 - y[1] / d));\n        real_t p = (y[1] - h*omega_0*omega_0*q) / d;\n        return vector_t(q, p);\n    };\n}\n// ------ end\n\ntemplate <typename real_t, typename vector_t>\nstd::vector<vector_t> solve_iterative\n    ( IterationStep<real_t, vector_t> step\n    , std::vector<vector_t> const &y_0\n    , std::vector<real_t> const &t\n    , real_t abs_err\n    , unsigned max_iter )\n{\n    std::vector<vector_t> y = y_0;\n\n    for (unsigned i = 0; i < t.size(); ++i) {\n        std::cout << t[i] << \" \" << y[i][0] << \" \" << y[i][1] << std::endl;\n    }\n    std::cout << \"\\n\\n\";\n\n    for (unsigned i = 0; i < max_iter; ++i) {\n        auto y_next = step(y, t);\n        real_t max_err = 0.0;\n        for (unsigned i = 0; i < t.size(); ++i) {\n            real_t err = (y_next[i] - y[i]).norm();\n            max_err = (err > max_err ? err : max_err);\n        }\n        y = y_next;\n\n        std::cout << \"# iteration=\" << i + 1\n                  << \" max_abs_err=\" << max_err << \"\\n\";\n        for (unsigned i = 0; i < t.size(); ++i) {\n            std::cout << t[i] << \" \" << y[i][0] << \" \" << y[i][1] << std::endl;\n        }\n        std::cout << \"\\n\\n\";\n    }\n    return y;\n}\n\nint main(int argc, char **argv)\n{\n    argagg::parser argparser\n        {{ { \"help\",   {\"-h\", \"--help\"}\n           , \"shows this help message\", 0 }\n         , { \"omega0\", {\"--omega0\"}\n           , \"undamped angular frequency (default 1.0)\", 1 }\n         , { \"zeta\",   {\"--zeta\"}\n           , \"damping ratio (default 0.5)\", 1 }\n         , { \"n\",      {\"--n\"}\n           , \"number of time slices (default 9)\", 1 }\n         , { \"h\",      {\"--h\"}\n           , \"size of time step in fine integrator (default 0.01)\", 1 }\n        }};\n\n    argagg::parser_results args;\n    try {\n        args = argparser.parse(argc, argv);\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    if (args[\"help\"]) {\n        std::cerr << \"Parareal test case: harmonic oscillator\\n\";\n        std::cerr << argparser;\n        return EXIT_SUCCESS;\n    }\n\n    using real_t = double;\n    using vector_t = Eigen::Vector2d;\n\n    unsigned n    = args[\"n\"].as<unsigned>(9);\n    real_t h      = args[\"h\"].as<real_t>(0.01);\n    real_t omega0 = args[\"omega0\"].as<real_t>(1.0);\n    real_t zeta   = args[\"zeta\"].as<real_t>(0.5);\n\n    auto ts = linspace<real_t>(0, 15.0, n);\n    auto ode = harmonic_oscillator<real_t, vector_t>(omega0, zeta);\n    auto rk4 = runge_kutta_4<real_t, vector_t>(ode);\n    auto coarse = backward_euler_harmonic_oscillator<real_t, vector_t>(omega0, zeta);\n    // auto coarse = backward_euler<real_t, vector_t>(ode, 1e-6);\n    auto fine = iterate_step<real_t, vector_t>(rk4, h); \n    auto y_0 = solve(coarse, vector_t(1.0, 0.0), ts);\n\n    auto t_ref = linspace<real_t>(0, 15.0, 100);\n    auto y_ref = solve(fine, vector_t(1.0, 0.0), t_ref);\n    for (unsigned i = 0; i < t_ref.size(); ++i) {\n        std::cout << t_ref[i] << \" \" << y_ref[i][0] << \" \" << y_ref[i][1] << std::endl;\n    }\n    std::cout << \"\\n\\n\";\n\n    auto y = solve_iterative\n        ( parareal(coarse, fine)\n        , y_0\n        , ts\n        , 1e-6\n        , n );\n\n    return EXIT_SUCCESS;\n}\n// ------ end\n", "meta": {"hexsha": "9991111a3d21cf2b3c4e9739a0534cea3879f9ca", "size": 4207, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/test-rk4.cc", "max_stars_repo_name": "NLESC-JCER/parareal", "max_stars_repo_head_hexsha": "d7ee673556a6afa201fe88927a2a2095a6451b84", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-01T19:31:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-08T13:52:49.000Z", "max_issues_repo_path": "src/test-rk4.cc", "max_issues_repo_name": "NLESC-JCER/parareal", "max_issues_repo_head_hexsha": "d7ee673556a6afa201fe88927a2a2095a6451b84", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test-rk4.cc", "max_forks_repo_name": "NLESC-JCER/parareal", "max_forks_repo_head_hexsha": "d7ee673556a6afa201fe88927a2a2095a6451b84", "max_forks_repo_licenses": ["Apache-2.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.2152777778, "max_line_length": 87, "alphanum_fraction": 0.5241264559, "num_tokens": 1358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6230502928413161}}
{"text": "#include <Eigen/Dense>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include \"Configuration.hpp\"\n#include \"MatrixSolver.hpp\"\n#include \"matrixIO.hpp\"\n\nusing namespace Eigen;\n\nint main(int argc, char *argv[])\n{\n  std::cout << \"SIDEMADE \u2013 Simple Dense Matrix Decomposition\\n\"\n            << std::endl;\n\n  if (argc != 2) {\n    std::cerr << \"SIDEMADE needs to be called with exactly one argument \u2013 the \"\n              << \"configuration file, e.g. 'sidemade config.yml'.\" << std::endl;\n    return -1;\n  }\n\n  // read configuration\n  Configuration configuration{std::string{argv[1]}};\n\n  // create solver\n  MatrixSolver solver{configuration.decompositionType};\n\n  // set a different arbitrary seed for the random generator to avoid a match\n  // between random matrices (generated with a seed of 0) and random vectors\n  srand(1000);\n\n  // fill matrix and vector structures\n  // A is read from file, b is set randomly, x is the solution\n  const MatrixXd A = matrixIO::openData(configuration.matrixFileName,\n                                        configuration.matrixSize);\n  const VectorXd b = VectorXd::Random(configuration.matrixSize);\n  VectorXd       x = VectorXd(configuration.matrixSize);\n\n  // solve A * x = b\n  std::cout << \"Solving ...\\n\"\n            << std::endl;\n  solver.solve(A, b, x);\n\n  const double resAbs = (A * x - b).norm(); // norm() computes l2 norm\n  const double relRes = resAbs / x.norm();\n  // std::cout << \"Solution is:\\n\" << x << std::endl;\n  std::cout << \"Absolute l2 residual is: \" << resAbs << std::endl;\n  std::cout << \"Relative l2 residual is: \" << relRes << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "23a3e749f7f4d1bf7057424133a71837a8f586b0", "size": 1620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "kimkroener/testing-boost-exercise", "max_stars_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "kimkroener/testing-boost-exercise", "max_issues_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2022-01-29T01:07:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T16:49:23.000Z", "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "kimkroener/testing-boost-exercise", "max_forks_repo_head_hexsha": "8e71e735624e59142303c1c25c2aed74fbd43e0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-01T16:22:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T16:22:19.000Z", "avg_line_length": 31.1538461538, "max_line_length": 80, "alphanum_fraction": 0.6432098765, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6230470299270423}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd ones = MatrixXd::Ones(3,3);\ncout << \"The operator norm of the 3x3 matrix of ones is \"\n     << ones.selfadjointView<Lower>().operatorNorm() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "66c0feaf100c9ea7b93633ba18d814fb49d0a9e5", "size": 308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_SelfAdjointView_operatorNorm.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_SelfAdjointView_operatorNorm.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_SelfAdjointView_operatorNorm.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.25, "max_line_length": 61, "alphanum_fraction": 0.6818181818, "num_tokens": 86, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6230386383651999}}
{"text": "// An example showing TEASER++ registration with the Stanford bunny model\n#include <chrono>\n#include <iostream>\n#include <random>\n\n#include <Eigen/Core>\n\n#include <teaser/log.h>\n#include <teaser/ply_io.h>\n#include <teaser/registration.h>\n\n// Macro constants for generating noise and outliers\n#define NOISE_BOUND 0.05\n#define N_OUTLIERS 1700\n#define OUTLIER_TRANSLATION_LB 5\n#define OUTLIER_TRANSLATION_UB 10\n\ninline double getAngularError(Eigen::Matrix3d R_exp, Eigen::Matrix3d R_est) {\n  return std::abs(std::acos(fmin(fmax(((R_exp.transpose() * R_est).trace() - 1) / 2, -1.0), 1.0)));\n}\n\nvoid addNoiseAndOutliers(Eigen::Matrix<double, 3, Eigen::Dynamic>& tgt) {\n  //int N_OUTLIERS = tgt.size() * 90 / 100;\n  // Add uniform noise\n  Eigen::Matrix<double, 3, Eigen::Dynamic> noise =\n      Eigen::Matrix<double, 3, Eigen::Dynamic>::Random(3, tgt.cols()) * NOISE_BOUND;\n  NOISE_BOUND / 2;\n  tgt = tgt + noise;\n\n  // Add outliers\n  std::random_device rd;\n  std::mt19937 gen(rd());\n  std::uniform_int_distribution<> dis2(0, tgt.cols() - 1); // pos of outliers\n  std::uniform_int_distribution<> dis3(OUTLIER_TRANSLATION_LB,\n                                       OUTLIER_TRANSLATION_UB); // random translation\n  std::vector<bool> expected_outlier_mask(tgt.cols(), false);\n  for (int i = 0; i < N_OUTLIERS; ++i) {\n    int c_outlier_idx = dis2(gen);\n    assert(c_outlier_idx < expected_outlier_mask.size());\n    expected_outlier_mask[c_outlier_idx] = true;\n    tgt.col(c_outlier_idx).array() += dis3(gen); // random translation\n  }\n}\n\nint main() {\n  // Load the .ply file\n  teaser::PLYReader reader;\n  teaser::PointCloud src_cloud;\n  auto status = reader.read(\"./example_data/bun_zipper_res3.ply\", src_cloud);\n  int N = src_cloud.size();\n\n  // Convert the point cloud to Eigen\n  Eigen::Matrix<double, 3, Eigen::Dynamic> src(3, N);\n  for (size_t i = 0; i < N; ++i) {\n    src.col(i) << src_cloud[i].x, src_cloud[i].y, src_cloud[i].z;\n  }\n\n  // Homogeneous coordinates\n  Eigen::Matrix<double, 4, Eigen::Dynamic> src_h;\n  src_h.resize(4, src.cols());\n  src_h.topRows(3) = src;\n  src_h.bottomRows(1) = Eigen::Matrix<double, 1, Eigen::Dynamic>::Ones(N);\n\n  // Apply an arbitrary SE(3) transformation\n  Eigen::Matrix4d T;\n  // clang-format off\n  T << 9.96926560e-01,  6.68735757e-02, -4.06664421e-02, -1.15576939e-01,\n      -6.61289946e-02, 9.97617877e-01,  1.94008687e-02, -3.87705398e-02,\n      4.18675510e-02, -1.66517807e-02,  9.98977765e-01, 1.14874890e-01,\n      0,              0,                0,              1;\n  // clang-format on\n\n  // Apply transformation\n  Eigen::Matrix<double, 4, Eigen::Dynamic> tgt_h = T * src_h;\n  Eigen::Matrix<double, 3, Eigen::Dynamic> tgt = tgt_h.topRows(3);\n\n  // Add some noise & outliers\n  addNoiseAndOutliers(tgt);\n\n  // Run TEASER++ registration\n  // Prepare solver parameters\n  teaser::RobustRegistrationSolver::Params params;\n  params.noise_bound = NOISE_BOUND;\n  params.cbar2 = 1;\n  params.estimate_scaling = false;\n  params.rotation_max_iterations = 100;\n  params.rotation_gnc_factor = 1.4;\n  params.rotation_estimation_algorithm =\n      teaser::RobustRegistrationSolver::ROTATION_ESTIMATION_ALGORITHM::GNC_TLS;\n  params.rotation_cost_threshold = 0.005;\n\n  // Solve with TEASER++\n  teaser::RobustRegistrationSolver solver(params);\n  std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\n  solver.solve(src, tgt);\n  std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n\n  auto solution = solver.getSolution();\n\n  // Compare results\n  std::cout << \"=====================================\" << std::endl;\n  std::cout << \"          TEASER++ Results           \" << std::endl;\n  std::cout << \"=====================================\" << std::endl;\n  std::cout << \"Expected rotation: \" << std::endl;\n  std::cout << T.topLeftCorner(3, 3) << std::endl;\n  std::cout << \"Estimated rotation: \" << std::endl;\n  std::cout << solution.rotation << std::endl;\n  std::cout << \"Error (deg): \" << getAngularError(T.topLeftCorner(3, 3), solution.rotation)\n            << std::endl;\n  std::cout << std::endl;\n  std::cout << \"Expected translation: \" << std::endl;\n  std::cout << T.topRightCorner(3, 1) << std::endl;\n  std::cout << \"Estimated translation: \" << std::endl;\n  std::cout << solution.translation << std::endl;\n  std::cout << \"Error (m): \" << (T.topRightCorner(3, 1) - solution.translation).norm() << std::endl;\n  std::cout << std::endl;\n  std::cout << \"Number of correspondences: \" << N << std::endl;\n  std::cout << \"Number of outliers: \" << N_OUTLIERS << std::endl;\n  std::cout << \"Time taken (s): \"\n            << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() /\n                   1000000.0\n            << std::endl;\n}\n", "meta": {"hexsha": "61704e09b3b6f48b62c02af9586326f3cf5eb8ee", "size": 4719, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/teaser_cpp_ply/teaser_cpp_ply.cc", "max_stars_repo_name": "Liraz-Benbenishti/TEASER-plusplus", "max_stars_repo_head_hexsha": "a0d9da261a3009a5dca2faab431dbcb908b1dffa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-10T17:12:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T17:12:23.000Z", "max_issues_repo_path": "examples/teaser_cpp_ply/teaser_cpp_ply.cc", "max_issues_repo_name": "Liraz-Benbenishti/TEASER-plusplus", "max_issues_repo_head_hexsha": "a0d9da261a3009a5dca2faab431dbcb908b1dffa", "max_issues_repo_licenses": ["MIT"], "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/teaser_cpp_ply/teaser_cpp_ply.cc", "max_forks_repo_name": "Liraz-Benbenishti/TEASER-plusplus", "max_forks_repo_head_hexsha": "a0d9da261a3009a5dca2faab431dbcb908b1dffa", "max_forks_repo_licenses": ["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.0564516129, "max_line_length": 100, "alphanum_fraction": 0.6446280992, "num_tokens": 1414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6230386279611376}}
{"text": "// (C) Copyright Andrew Sutton 2007\r\n//\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0 (See accompanying file\r\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[inclusive_mean_geodesic_example\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\n#include <boost/graph/directed_graph.hpp>\r\n#include <boost/graph/exterior_property.hpp>\r\n#include <boost/graph/floyd_warshall_shortest.hpp>\r\n#include <boost/graph/geodesic_distance.hpp>\r\n#include \"helper.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\n// This template structure defines the function that we will apply\r\n// to compute both the per-vertex mean geodesic distances and the\r\n// graph's mean geodesic distance.\r\ntemplate <typename Graph,\r\n          typename DistanceType,\r\n          typename ResultType,\r\n          typename Divides = divides<ResultType> >\r\nstruct inclusive_average\r\n{\r\n    typedef DistanceType distance_type;\r\n    typedef ResultType result_type;\r\n\r\n    result_type operator ()(distance_type d, const Graph& g)\r\n    {\r\n        if(d == numeric_values<distance_type>::infinity()) {\r\n            return numeric_values<result_type>::infinity();\r\n        }\r\n        else {\r\n            return div(result_type(d), result_type(num_vertices(g)));\r\n        }\r\n    }\r\n    Divides div;\r\n};\r\n\r\n// The Page type stores the name of each vertex in the graph and\r\n// represents web pages that can be navigated to.\r\nstruct WebPage\r\n{\r\n    string name;\r\n};\r\n\r\n// The Link type stores an associated probability of traveling\r\n// from one page to another.\r\nstruct Link\r\n{\r\n    float probability;\r\n};\r\n\r\n// Declare the graph type and its vertex and edge types.\r\ntypedef directed_graph<WebPage, Link> Graph;\r\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\r\ntypedef graph_traits<Graph>::edge_descriptor Edge;\r\n\r\n// The name map provides an abstract accessor for the names of\r\n// each vertex. This is used during graph creation.\r\ntypedef property_map<Graph, string WebPage::*>::type NameMap;\r\n\r\n// Declare a matrix type and its corresponding property map that\r\n// will contain the distances between each pair of vertices.\r\ntypedef exterior_vertex_property<Graph, float> DistanceProperty;\r\ntypedef DistanceProperty::matrix_type DistanceMatrix;\r\ntypedef DistanceProperty::matrix_map_type DistanceMatrixMap;\r\n\r\n// Declare the weight map as an accessor into the bundled\r\n// edge property.\r\ntypedef property_map<Graph, float Link::*>::type WeightMap;\r\n\r\n// Declare a container and its corresponding property map that\r\n// will contain the resulting mean geodesic distances of each\r\n// vertex in the graph.\r\ntypedef exterior_vertex_property<Graph, float> GeodesicProperty;\r\ntypedef GeodesicProperty::container_type GeodesicContainer;\r\ntypedef GeodesicProperty::map_type GeodesicMap;\r\n\r\nstatic float exclusive_geodesics(const Graph&, DistanceMatrixMap, GeodesicMap);\r\nstatic float inclusive_geodesics(const Graph&, DistanceMatrixMap, GeodesicMap);\r\n\r\nint\r\nmain(int argc, char *argv[])\r\n{\r\n    // Create the graph, a name map that providse abstract access\r\n    // to the web page names, and the weight map as an accessor to\r\n    // the edge weights (or probabilities).\r\n    Graph g;\r\n    NameMap nm(get(&WebPage::name, g));\r\n    WeightMap wm(get(&Link::probability, g));\r\n\r\n    // Read the weighted graph from standard input.\r\n    read_weighted_graph(g, nm, wm, cin);\r\n\r\n    // Compute the distances between all pairs of vertices using\r\n    // the Floyd-Warshall algorithm. The weight map was created\r\n    // above so it could be populated when the graph was read in.\r\n    DistanceMatrix distances(num_vertices(g));\r\n    DistanceMatrixMap dm(distances, g);\r\n    floyd_warshall_all_pairs_shortest_paths(g, dm, weight_map(wm));\r\n\r\n    // Create the containers and the respective property maps that\r\n    // will contain the mean geodesics averaged both including\r\n    // self-loop distances and excluding them.\r\n    GeodesicContainer exclude(num_vertices(g));\r\n    GeodesicContainer include(num_vertices(g));\r\n    GeodesicMap exmap(exclude, g);\r\n    GeodesicMap inmap(include, g);\r\n\r\n    float ex = exclusive_geodesics(g, dm, exmap);\r\n    float in = inclusive_geodesics(g, dm, inmap);\r\n\r\n    // Print the mean geodesic distance of each vertex and finally,\r\n    // the graph itself.\r\n    cout << setw(12) << setiosflags(ios::left) << \"vertex\";\r\n    cout << setw(12) << setiosflags(ios::left) << \"excluding\";\r\n    cout << setw(12) << setiosflags(ios::left) << \"including\" << endl;\r\n    graph_traits<Graph>::vertex_iterator i, end;\r\n    for(tie(i, end) = vertices(g); i != end; ++i) {\r\n        cout << setw(12) << setiosflags(ios::left)\r\n             << g[*i].name\r\n             << setw(12) << get(exmap, *i)\r\n             << setw(12) << get(inmap, *i) << endl;\r\n    }\r\n    cout << \"small world (excluding self-loops): \" << ex << endl;\r\n    cout << \"small world (including self-loops): \" << in << endl;\r\n\r\n    return 0;\r\n}\r\n\r\nfloat\r\nexclusive_geodesics(const Graph& g, DistanceMatrixMap dm, GeodesicMap gm)\r\n{\r\n    // Compute the mean geodesic distances, which excludes distances\r\n    // of self-loops by default. Return the measure for the entire graph.\r\n    return all_mean_geodesics(g, dm, gm);\r\n}\r\n\r\n\r\nfloat\r\ninclusive_geodesics(const Graph &g, DistanceMatrixMap dm, GeodesicMap gm)\r\n{\r\n    // Create a new measure object for computing the mean geodesic\r\n    // distance of all vertices. This measure will actually be used\r\n    // for both averages.\r\n    inclusive_average<Graph, float, float> m;\r\n\r\n    // Compute the mean geodesic distance using the inclusive average\r\n    // to account for self-loop distances. Return the measure for the\r\n    // entire graph.\r\n    return all_mean_geodesics(g, dm, gm, m);\r\n}\r\n//]\r\n", "meta": {"hexsha": "81e359e645f8119daa2c25b8afd1f978a2936ead", "size": 5729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/inclusive_mean_geodesic.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/graph/example/inclusive_mean_geodesic.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/example/inclusive_mean_geodesic.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 36.0314465409, "max_line_length": 80, "alphanum_fraction": 0.6976784779, "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6230386276589773}}
{"text": "/*\n * resizing_lattice.cpp\n *\n * Demonstrates the usage of resizing of the state type during integration.\n * Examplary system is a strongly nonlinear, disordered Hamiltonian lattice\n * where the spreading of energy is invastigated\n *\n * Copyright 2009-2012 Karsten Ahnert and Mario Mulansky.\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n */\n\n#include <iostream>\n#include <utility>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/ref.hpp>\n#include <boost/random.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n//[ resizing_lattice_system_class\ntypedef vector< double > coord_type;\ntypedef pair< coord_type , coord_type > state_type;\n\nstruct compacton_lattice\n{\n    const int m_max_N;\n    const double m_beta;\n    int m_pot_start_index;\n    vector< double > m_pot;\n\n    compacton_lattice( int max_N , double beta , int pot_start_index )\n        : m_max_N( max_N ) , m_beta( beta ) , m_pot_start_index( pot_start_index ) , m_pot( max_N )\n    {\n        srand( time( NULL ) );\n        // fill random potential with iid values from [0,1]\n        boost::mt19937 rng;\n        boost::uniform_real<> unif( 0.0 , 1.0 );\n        boost::variate_generator< boost::mt19937&, boost::uniform_real<> > gen( rng , unif );\n        generate( m_pot.begin() , m_pot.end() , gen );\n    }\n\n    void operator()( const coord_type &q , coord_type &dpdt )\n    {\n        // calculate dpdt = -dH/dq of this hamiltonian system\n        // dp_i/dt = - V_i * q_i^3 - beta*(q_i - q_{i-1})^3 + beta*(q_{i+1} - q_i)^3\n        const int N = q.size();\n        double diff = q[0] - q[N-1];\n        for( int i=0 ; i<N ; ++i )\n        {\n            dpdt[i] = - m_pot[m_pot_start_index+i] * q[i]*q[i]*q[i] -\n                    m_beta * diff*diff*diff;\n            diff = q[(i+1) % N] - q[i];\n            dpdt[i] += m_beta * diff*diff*diff;\n        }\n    }\n\n    void energy_distribution( const coord_type &q , const coord_type &p , coord_type &energies )\n    {\n        // computes the energy per lattice site normalized by total energy\n        const size_t N = q.size();\n        double en = 0.0;\n        for( size_t i=0 ; i<N ; i++ )\n        {\n            const double diff = q[(i+1) % N] - q[i];\n            energies[i] = p[i]*p[i]/2.0\n                + m_pot[m_pot_start_index+i]*q[i]*q[i]*q[i]*q[i]/4.0\n                + m_beta/4.0 * diff*diff*diff*diff;\n            en += energies[i];\n        }\n        en = 1.0/en;\n        for( size_t i=0 ; i<N ; i++ )\n        {\n            energies[i] *= en;\n        }\n    }\n\n    double energy( const coord_type &q , const coord_type &p )\n    {\n        // calculates the total energy of the excitation\n        const size_t N = q.size();\n        double en = 0.0;\n        for( size_t i=0 ; i<N ; i++ )\n        {\n            const double diff = q[(i+1) % N] - q[i];\n            en += p[i]*p[i]/2.0\n                + m_pot[m_pot_start_index+i]*q[i]*q[i]*q[i]*q[i] / 4.0\n                + m_beta/4.0 * diff*diff*diff*diff;\n        }\n        return en;\n    }\n\n    void change_pot_start( const int delta )\n    {\n        m_pot_start_index += delta;\n    }\n};\n//]\n\n//[ resizing_lattice_resize_function\nvoid do_resize( coord_type &q , coord_type &p , coord_type &distr , const int N )\n{\n    q.resize( N );\n    p.resize( N );\n    distr.resize( N );\n}\n//]\n\nconst int max_N = 1024;\nconst double beta = 1.0;\n\nint main()\n{\n    //[ resizing_lattice_initialize\n    //start with 60 sites\n    const int N_start = 60;\n    coord_type q( N_start , 0.0 );\n    q.reserve( max_N );\n    coord_type p( N_start , 0.0 );\n    p.reserve( max_N );\n    // start with uniform momentum distribution over 20 sites\n    fill( p.begin()+20 , p.end()-20 , 1.0/sqrt(20.0) );\n\n    coord_type distr( N_start , 0.0 );\n    distr.reserve( max_N );\n\n    // create the system\n    compacton_lattice lattice( max_N , beta , (max_N-N_start)/2 );\n\n    //create the stepper, note that we use an always_resizer because state size might change during steps\n    typedef symplectic_rkn_sb3a_mclachlan< coord_type , coord_type , double , coord_type , coord_type , double ,\n            range_algebra , default_operations , always_resizer > hamiltonian_stepper;\n    hamiltonian_stepper stepper;\n    hamiltonian_stepper::state_type state = make_pair( q , p );\n    //]\n\n    //[ resizing_lattice_steps_loop\n    double t = 0.0;\n    const double dt = 0.1;\n    const int steps = 10000;\n    for( int step = 0 ; step < steps ; ++step )\n    {\n        stepper.do_step( boost::ref(lattice) , state , t , dt );\n        lattice.energy_distribution( state.first , state.second , distr );\n        if( distr[10] > 1E-150 )\n        {\n            do_resize( state.first , state.second , distr , state.first.size()+20 );\n            rotate( state.first.begin() , state.first.end()-20 , state.first.end() );\n            rotate( state.second.begin() , state.second.end()-20 , state.second.end() );\n            lattice.change_pot_start( -20 );\n            cout << t << \": resized left to \" << distr.size() << \", energy = \" << lattice.energy( state.first , state.second ) << endl;\n        }\n        if( distr[distr.size()-10] > 1E-150 )\n        {\n            do_resize( state.first , state.second , distr , state.first.size()+20 );\n            cout << t << \": resized right to \" << distr.size() << \", energy = \" << lattice.energy( state.first , state.second ) << endl;\n        }\n        t += dt;\n    }\n    //]\n\n    cout << \"final lattice size: \" << distr.size() << \", final energy: \" << lattice.energy( state.first , state.second ) << endl;\n}\n", "meta": {"hexsha": "70993e99e051b9fc826a3d802d109bae51b1c898", "size": 5595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/resizing_lattice.cpp", "max_stars_repo_name": "datacratic/boost-svn", "max_stars_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T18:18:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T18:18:10.000Z", "max_issues_repo_path": "libs/numeric/odeint/examples/resizing_lattice.cpp", "max_issues_repo_name": "datacratic/boost-svn", "max_issues_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/odeint/examples/resizing_lattice.cpp", "max_forks_repo_name": "datacratic/boost-svn", "max_forks_repo_head_hexsha": "fcfba33e940cdb150b18d1d03821dcb30af52a94", "max_forks_repo_licenses": ["BSL-1.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.1065088757, "max_line_length": 136, "alphanum_fraction": 0.5789097408, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6230386047786166}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <tuple>\n#include <vector>\n#include <queue>\n#include <boost/algorithm/string.hpp>\n#include <math.h>\n#include <chrono>\n#include <stdlib.h>\n\nusing namespace std;\n\ntypedef std::chrono::high_resolution_clock Clock;\ntypedef std::vector<vector<int>> AdjList;\n\n\ndouble distance(const tuple<int, int> &p1, const tuple<int, int> &p2) {\n  return sqrt( (std::get<0>(p1) - std::get<0>(p2)) * (std::get<0>(p1) - std::get<0>(p2)) + (std::get<1>(p1) - std::get<1>(p2)) * (std::get<1>(p1) - std::get<1>(p2)) );\n}\n\nstd::vector<std::vector<double>> createAdjMatrix (const std::vector<std::tuple<int, int>> &nodes){\n  std::vector<std::vector<double>> adjMatrix(nodes.size(), vector<double>(nodes.size()));\n  for (int i = 0; i < nodes.size(); i++) {\n    for (int j = 0; j < nodes.size(); j++){\n      adjMatrix[i][j] = distance(nodes[i], nodes[j]); \n    }\n  }\n  return adjMatrix;\n}\n\ndouble pathWeightVsReverse(std::vector<int> &path, int i, int j, const std::vector<std::vector<double>> &adjMatrix){ \n  if (j-1 < 0)\n    return ( adjMatrix[path[i]][path[(i+1)%path.size()]] + adjMatrix[path[path.size()-1]][path[j]] ) - ( adjMatrix[path[i]][path[path.size()-1]] + adjMatrix[path[(i+1)%path.size()]][path[j]] ); \n  else\n    return ( adjMatrix[path[i]][path[(i+1)%path.size()]] + adjMatrix[path[j-1]][path[j]] ) - ( adjMatrix[path[i]][path[j-1]] + adjMatrix[path[(i+1)%path.size()]][path[j]] ); \n}\n\nvoid printTour(std::vector<int> &tour, const std::vector<tuple<int,int>> &nodes, std::string name){ \n  //cout << name << \"  TOUR: \"; \n  for ( const auto &i : tour) {\n     cout << \"(\" << get<0>(nodes[i]) << \", \" << get<1>(nodes[i]) << \")\" << endl;\n  }\n}\n\nvoid printTour(std::vector<int> &tour){ \n  cout << \"TOUR: \"; \n  for ( const auto &i : tour) {\n    cout << i << \" \";\n  }\n  cout << endl;\n}\n\nvoid reverseSubtour (std::vector<int> &tour, int &i, int &j) {\n  if (j <= i) {\n    /**/\n    vector <int> subtour = vector<int>(tour.begin() + i + 1, tour.end()); \n    subtour.insert(subtour.end(),  tour.begin(), tour.begin() + j);  \n\n    int index = i+1;\n    for (std::vector<int>::reverse_iterator it = subtour.rbegin(); it != subtour.rend(); it++) {\n      tour[index%tour.size()] = *it;\n      index += 1;\n    }\n    \n    //cout << \"REVERSING SUBOTUR: \" << i << \", \" << j << endl;\n    /* \n    int tourSize = tour.size();\n    int a = i + 1;\n    int b = (j-1) < 0 ? tourSize - 1 : j -1;\n    int tmp;\n    for (int c = 0; c < (tourSize - i + j - 2)/2; c++) {\n        //printTour(tour);\n        //cout << tourSize - i + j - 1 - c << \"\\tswapping a: \" << a << \", b: \" << b << endl; \n        //cout << \"\\tswapping tour[a]: \" << tour[a] << \", tour[b]: \" << tour[b] << endl; \n        tmp = tour[a];\n        tour[a] = tour[b];\n        tour[b] = tmp;\n        a = (a + 1) % tourSize;\n        b = (b - 1) < 0 ? tourSize - 1 : b - 1;\n        //cout <<\"\\t\\t\" << a << \", \" << b << endl; \n    }\n   */ \n  } else {\n    std::reverse(tour.begin() + i + 1, tour.begin() + j);\n  }\n}\n\ndouble tourWeight(std::vector<int> tour, std::vector<std::vector<double>> adjMatrix) {\n  double tourWeight = 0;\n  for (int i = 0; i < tour.size(); i++)\n    tourWeight += adjMatrix[tour[i]][tour[(i+1)%tour.size()]];\n  return tourWeight;\n}\n\nstd::vector<int> reverseTours (std::vector<int> &tour, const std::vector<std::tuple<int, int>> &nodes, const std::vector<std::vector<double>> &adjMatrix){\n  int counter = 0;\n  int tourSize = tour.size();\n  int tourSizeSq = tourSize*tourSize;\n  int subtourSize;\n  \n  while (counter < tourSizeSq) {\n    for (int i = 0; i < tourSize; i++) {\n      for (int j = 0; j < tourSize; j++){\n        \n        subtourSize = ((j <= i) ? ((tourSize - i) + j) : (j - i));\n\n        if (subtourSize > 3) {\n           if (pathWeightVsReverse(tour, i, j, adjMatrix) > 0) {\n             reverseSubtour(tour, i, j); \n             counter = 0;\n           }\n        }\n        counter += 1; \n        if (counter > tourSizeSq) { goto label2; }\n      }\n    } \n  }\nlabel2:\n  \n  return tour;\n}\n\nstd::vector<std::tuple<int,int>> readPipedInput() {\n  std::string line;\n  std::vector<std::string> strs;\n  std::vector<std::tuple<int, int>> nodes;\n  int i = 0; int j = 0;\n  std::string black_dot = \"0\";\n  while (std::getline(std::cin, line))  {\n    boost::split(strs, line, boost::is_any_of(\" \\n\"));\n    for (std::vector<std::string>::const_iterator it = strs.begin(); it != strs.end(); ++it) {\n        if (*it == black_dot){nodes.push_back(std::make_tuple(i, j));} \n        j += 1;\n     }\n    i += 1;\n    j = 0;\n  }\n  return nodes;\n}\nstd::vector<std::tuple<int, int>> readInput(string const &str1) {\n  string line;\n  std::vector<std::string> strs;\n  std::vector<std::tuple<int, int>> nodes;\n  ifstream myfile (str1);\n  int i = 0; int j = 0;\n  std::basic_string<char> black_dot = \"0\";\n  if (myfile.is_open())\n  {\n    while ( getline (myfile,line) )\n    {\n      boost::split(strs, line, boost::is_any_of(\" \\n\"));\n      for (std::vector<std::string>::const_iterator it = strs.begin(); it != strs.end(); ++it) {\n          if (*it == black_dot){nodes.push_back(std::make_tuple(i, j));} \n          j += 1;\n       }\n      i += 1;\n      j = 0;\n    }\n    myfile.close();\n  }\n  else cout << \"Unable to open file\"; \n  return nodes;\n}\n\nstruct compareNodeWeight {\n  bool operator()(const std::tuple<double, int, int> &lhs, std::tuple<double,int,int> &rhs) {\n    return std::get<0>(lhs) >  std::get<0>(rhs); \n  }\n};\n\nint searchHeap(std::vector<std::tuple<double,int,int>> &heap, int vertex) {\n  for (int i = 0; i < heap.size(); i++) {\n    if (std::get<1>(heap[i]) == vertex) {\n      return i; \n    }\n  }\n  return -1;\n}\n\nvoid siftUp(std::vector<std::tuple<double,int,int>> &heap, int index) {\n  int parent = (index - 1) / 2;\n  double indexValue = std::get<0>(heap[parent]);\n  double parentValue = std::get<0>(heap[index]);\n  std::tuple<double,int,int> tmp; \n\n  while (index != 0 && std::get<0>(heap[(index-1)/2]) > std::get<0>(heap[index]) ) {\n    parent = (index - 1) / 2;\n    indexValue = std::get<0>(heap[index]);\n    parentValue = std::get<0>(heap[parent]);\n    tmp = heap[index];\n    heap[index] = heap[parent];\n    heap[parent] = tmp;\n    index = parent;\n  }\n}\n\nstd::vector<std::tuple<int,int>> prims (std::vector<std::vector<double>> adjMatrix) {\n  std::vector<int> knownNodes(adjMatrix.size(), 0); // knownNodes[i] = 0 iff i is not known, else 1\n  \n  std::vector<std::tuple<double,int,int>> heap;\n  for (int i = 1; i < adjMatrix.size(); i++ ){\n    heap.push_back(std::make_tuple(INT_MAX, i, -1)); \n  } \n  \n  heap.push_back(std::make_tuple(0, 0, -1)); \n  std::make_heap(heap.begin(), heap.end(), compareNodeWeight());\n\n  std::tuple<double, int, int> minVal;\n  double weight; int u; int u_prev;\n  std::vector<std::tuple<int,int>> edges;  \n  int index;\n\n  while (heap.size() > 0) {\n    std::pop_heap(heap.begin(), heap.end(), compareNodeWeight());\n    minVal = heap.back(); \n    heap.pop_back();\n    weight = std::get<0>(minVal);\n    u = std::get<1>(minVal);\n    u_prev = std::get<2>(minVal);\n    \n    if (knownNodes[u] == 0) {\n      knownNodes[u] = 1;\n      if (u_prev != -1) {\n        edges.push_back(std::make_tuple(u, u_prev));\n      }\n    }\n    for (int v = 0; v < adjMatrix.size(); v++ ) { \n      if (knownNodes[v] == 0) {\n        index = searchHeap(heap, v);\n        if (index != -1) {\n          if (weight + adjMatrix[u][v] < std::get<0>(heap[index])) {\n            heap[index] = std::make_tuple(weight + adjMatrix[u][v], v, u);\n            siftUp(heap, index);\n          }\n        }\n      }\n    }   \n  } \n  return edges;\n}\n\nstd::vector<vector<int>> constructAdjList(std::vector<std::tuple<int,int>> &MST, const std::vector<std::tuple<int,int>> &nodes) {\n  std::vector<std::vector<int>> adjList(nodes.size(), std::vector<int>());\n\n  for (int i = 0; i < MST.size(); i++) {\n    std::tuple<int,int> edge = MST[i];\n    adjList[std::get<0>(edge)].push_back(std::get<1>(edge));\n    adjList[std::get<1>(edge)].push_back(std::get<0>(edge));\n  }\n  return adjList;\n}\n\nstd::vector<int> DFSUtil(int v, bool visited[], const std::vector<std::vector<int>> &adjList, std::vector<int> &tour) {\n    visited[v] = true;\n    tour.push_back(v);\n \n    for (std::vector<int>::const_iterator i = adjList[v].begin(); i != adjList[v].end(); ++i)\n        if (!visited[*i])\n            DFSUtil(*i, visited, adjList, tour);\n    return tour;\n}\n \nstd::vector<int> DFS(int v, const std::vector<std::vector<int>> adjList) {\n    bool *visited = new bool[adjList.size()];\n    for (int i = 0; i < adjList.size(); i++)\n        visited[i] = false;\n    std::vector<int> dfsTour; \n    std::vector<int> tour = DFSUtil(v, visited, adjList, dfsTour);\n    return tour;\n}\n\nstd::vector<int> nearestNeighbor(std::vector<int> &tour, const std::vector<std::vector<double>> &adjMatrix) {\n  int visitedVertices[adjMatrix.size()] = {0};\n  int visitedCount = 0;\n\n  int currentVertex = 0;\n  int nextVertex;\n  double minEdgeWeight;\n   \n\n  std::vector<int> nnTour;\n \n  while(visitedCount < adjMatrix.size()) {\n    nnTour.push_back(currentVertex);\n    minEdgeWeight = INT_MAX;\n    for (int v = 0; v < adjMatrix.size(); v++){\n      if (!visitedVertices[v] && currentVertex != v && adjMatrix[currentVertex][v] < minEdgeWeight) {\n        minEdgeWeight = adjMatrix[currentVertex][v];\n        nextVertex = v;\n      }\n    }\n    visitedVertices[currentVertex] = 1;\n    currentVertex = nextVertex; \n    visitedCount+=1;\n  }\n  return nnTour;\n\n}\n\n\nint main (int argc, char *argv[]) {\n  /*\n  std::string input_file = argv[1];\n  cout << \"INPUT FILE: \" << input_file << endl;\n  const std::basic_string<char> T = input_file;\n  */\n  const std::vector<std::tuple<int, int>> nodes = readPipedInput(); \n\n  std::vector<int> tour;\n  for (int i=0; i<nodes.size(); ++i) tour.push_back(i);\n  //printTour(tour, nodes, \"ORIGINAL\");\n  \n  //cout << \"Number of cities: \" << tour.size() << endl;\n  auto t1 = Clock::now();\n  const std::vector<std::vector<double>> adjMatrix = createAdjMatrix(nodes);\n  auto t2 = Clock::now();\n  /*std::cout << \"Create AdjMatrix Delta t2-t1: \" \n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()\n            << \" milliseconds\" << std::endl;\n  */\n//  tour = nearestNeighbor(tour, adjMatrix);\n//  printTour(tour, nodes, \"NEAREST NEIGHBOR\");\n  \n  t1 = Clock::now();\n  std::vector<tuple<int,int>> MST = prims(adjMatrix);\n  t2 = Clock::now();\n  /*std::cout << \"PRIMS Delta t2-t1: \" \n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()\n            << \" milliseconds\" << std::endl;\n  */\n  \n  t1 = Clock::now();\n  const std::vector<vector<int>> adjList = constructAdjList(MST, nodes);\n  t2 = Clock::now();\n  /*std::cout << \"Construct AdjList  Delta t2-t1: \" \n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()\n            << \" milliseconds\" << std::endl;\n  */\n  t1 = Clock::now();\n  tour = DFS(0, adjList); \n  t2 = Clock::now();\n  //printTour(tour, nodes, \"DFS\");\n  /*std::cout << \"DFS  Delta t2-t1: \" \n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()\n            << \" seconds\" << std::endl;\n  */\n\n  t1 = Clock::now();\n  std::vector<int> reversedTour = reverseTours(tour, nodes, adjMatrix);\n  t2 = Clock::now();\n  printTour(tour, nodes, \"REVERSED\");\n  /*cout << \"Number of cities: \" << tour.size() << endl;\n  std::cout << \"Reverse Tour Delta t2-t1: \" \n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()\n            << \" milliseconds\" << std::endl;\n  */\n  return 0;\n}\n", "meta": {"hexsha": "36ca01e5eccf349732b41726e28232007acaa508", "size": 11477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/closedcurve.cpp", "max_stars_repo_name": "Dellvan7/closed-curve", "max_stars_repo_head_hexsha": "dc2b391e0d41cb9f2292171241bb4cae619487a6", "max_stars_repo_licenses": ["MIT"], "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/closedcurve.cpp", "max_issues_repo_name": "Dellvan7/closed-curve", "max_issues_repo_head_hexsha": "dc2b391e0d41cb9f2292171241bb4cae619487a6", "max_issues_repo_licenses": ["MIT"], "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/closedcurve.cpp", "max_forks_repo_name": "Dellvan7/closed-curve", "max_forks_repo_head_hexsha": "dc2b391e0d41cb9f2292171241bb4cae619487a6", "max_forks_repo_licenses": ["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.8805555556, "max_line_length": 194, "alphanum_fraction": 0.5676570532, "num_tokens": 3584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072387, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.623012424201718}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Surface_mesh.h>\n\n#include <CGAL/optimal_bounding_box.h>\n#include <CGAL/Polygon_mesh_processing/measure.h>\n#include <CGAL/IO/read_off_points.h>\n\n#include <fstream>\n#include <iostream>\n#include <utility>\n#include <limits>\n\n#ifdef BUILD_PY\n\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/list.hpp>\n\n#endif\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::Point_3                                     Point;\ntypedef Kernel::Aff_transformation_3                        Aff_transformation;\ntypedef CGAL::Surface_mesh<Point>                           Surface_mesh;\n\n\n/**\n * returns the transformation matrix and the \n */\nstd::pair<std::array<double, 16>, std::array<double,3>> createOptimalBoundingBox(std::string pathToSTL)\n{\n  std::ifstream stream(pathToSTL);\n  std::list<Point> p;\n  if (!stream || !CGAL::read_off_points(stream, std::back_inserter(p)))\n  {\n      std::cerr << \"Error: cannot read file data\" << std::endl;\n      throw std::exception();\n  }\n  // compute rotated optimal bounding box\n  std::array<Point, 8> obb_points;\n  CGAL::oriented_bounding_box(p, obb_points, CGAL::parameters::use_convex_hull(true));\n  \n  /* untested */\n  Aff_transformation tf;\n  CGAL::oriented_bounding_box(p, tf, CGAL::parameters::use_convex_hull(true));\n  \n  std::array<double, 6> bb_min_max;\n  for(int i = 0; i < 3; i++)\n  {\n    bb_min_max[i*2+0] = DBL_MIN;\n    bb_min_max[i*2+1] = DBL_MAX;\n\n  }\n  // rotate points such that the bounding is axis aligned \n  // and get the minimum and maximum values for each axis\n  std::array<Point, 8> obb_points_rotated;\n  for(int i = 0; i < obb_points.size(); i++)\n  {\n    obb_points_rotated[i] = tf.transform(obb_points[i]);\n    bb_min_max[0] = std::max(bb_min_max[0], obb_points_rotated[i].x());\n    bb_min_max[1] = std::min(bb_min_max[1], obb_points_rotated[i].x());\n    bb_min_max[2] = std::max(bb_min_max[2], obb_points_rotated[i].y());\n    bb_min_max[3] = std::min(bb_min_max[3], obb_points_rotated[i].y());\n    bb_min_max[4] = std::max(bb_min_max[4], obb_points_rotated[i].z());\n    bb_min_max[5] = std::min(bb_min_max[5], obb_points_rotated[i].z());\n  }\n\n  std::array<double,3> bb_size;\n  bb_size[0] =  bb_min_max[0] - bb_min_max[1]; \n  bb_size[1] =  bb_min_max[2] - bb_min_max[3];\n  bb_size[2] =  bb_min_max[4] - bb_min_max[5];\n  //std::cout << \"size xyz: \" << bb_size[0] <<  \" \" << bb_size[1] << \" \" << bb_size[1] << std::endl;\n\n  double offset_x = bb_size[0]/2 - bb_min_max[0];\n  double offset_y = bb_size[1]/2 - bb_min_max[2];\n  double offset_z = bb_size[2]/2 - bb_min_max[4];\n  //std::cout << \"x_off: \" << offset_x << \" y_off: \"  << offset_y << \" z_off: \" << offset_z << \" \" << std::endl;\n\n  // apply offset to each point of the bounding box for when it is written to file\n  Kernel::Vector_3 off(offset_x, offset_y, offset_z);\n  for(int i = 0; i<8; i++)\n  {\n    obb_points_rotated[i] += off;\n  }\n\n  // Create mesh, both rotated and not rotated and write each to a file\n  Surface_mesh obb_sm;\n  CGAL::make_hexahedron(obb_points[0], obb_points[1], obb_points[2], obb_points[3],\n                        obb_points[4], obb_points[5], obb_points[6], obb_points[7], obb_sm);\n  std::ofstream(\"box.off\") << obb_sm;\n  Surface_mesh obb_sm_rotated;\n  CGAL::make_hexahedron(obb_points_rotated[0], obb_points_rotated[1], obb_points_rotated[2], obb_points_rotated[3],\n                        obb_points_rotated[4], obb_points_rotated[5], obb_points_rotated[6], obb_points_rotated[7], obb_sm_rotated);\n  std::ofstream(\"box_rotated.off\") << obb_sm_rotated;\n\n  // put the values from the affine transformation matrix into a standard cpp array\n  std::array<double,16> tf_array;\n  for(int i = 0; i < 4; i++)\n  {\n    for(int j = 0; j < 4; j++)\n    {\n      tf_array[i*4+j] = tf.m(i,j);\n    }\n  }\n  // translation of the bounding box is not included in the affine transformation matrix\n  // therefore we add it here\n  Kernel::Vector_3 off_rotated = tf.inverse().transform(off);\n  tf_array[3] = -off_rotated.x();\n  tf_array[7] = -off_rotated.y();\n  tf_array[11] = -off_rotated.z();\n  \n  return std::make_pair(tf_array, bb_size);\n}\n\n#ifdef BUILD_PY\nboost::python::list optimalBoundingBoxWrapper(std::string filename)\n{\n  std::pair<std::array<double, 16>, std::array<double,3>> bb_tf_and_size = createOptimalBoundingBox(filename);\n  boost::python::list return_value;\n  \n  boost::python::list py_tf;\n  for (double d : bb_tf_and_size.first)\n  {\n    py_tf.append(d);\n  }\n  boost::python::list py_bb_size;\n  for (double limit : bb_tf_and_size.second)\n  {\n    py_bb_size.append(limit);\n  }\n  return_value.append(py_tf);\n  return_value.append(py_bb_size);\n\n  return return_value;\n}\nBOOST_PYTHON_MODULE(py_optimal_bounding_box)\n{\n    using namespace boost::python;\n\n    def(\"create_optimal_bounding_box\", &optimalBoundingBoxWrapper);\n}\n#endif\n\n// main function if it is called by itself, takes filename as cli input\n// prints resulting bounding box and saves it as .off file\nint main(int argc, char** argv)\n{\n  if(argc != 2)\n  {\n      std::cerr << \"Usage: \" << argv[0] << \" <input file.off>\" << std::endl;\n      return EXIT_FAILURE;\n  }\n  auto a = createOptimalBoundingBox(argv[1]);\n  // TODO do something with result\n} ", "meta": {"hexsha": "53bfeb829dc872d647d34ad6b81026057ad9f3ec", "size": 5327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimal_bounding_box.cpp", "max_stars_repo_name": "bit-bots/simplify_urdf_collision", "max_stars_repo_head_hexsha": "1520284893ae629ca5b804c32ce0dfe66efde944", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/optimal_bounding_box.cpp", "max_issues_repo_name": "bit-bots/simplify_urdf_collision", "max_issues_repo_head_hexsha": "1520284893ae629ca5b804c32ce0dfe66efde944", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimal_bounding_box.cpp", "max_forks_repo_name": "bit-bots/simplify_urdf_collision", "max_forks_repo_head_hexsha": "1520284893ae629ca5b804c32ce0dfe66efde944", "max_forks_repo_licenses": ["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.9299363057, "max_line_length": 132, "alphanum_fraction": 0.6750516238, "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.6230124136385807}}
{"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_ATANH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATANH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-hyperbolic\n    Function object implementing atanh capabilities\n\n    Returns the hyperbolic tangent argument \\f$\\frac12\\log\\frac{1+x}{1-x}\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type @c T\n\n    @code\n    T r = atanh(x);\n    @endcode\n\n    @par Decorators\n\n    - raw_  is faster but inaccurate near Zero\n\n\n    @see log, Half, oneminus, inc\n\n  **/\n  Value atanh(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/atanh.hpp>\n#include <boost/simd/function/simd/atanh.hpp>\n\n#endif\n", "meta": {"hexsha": "abd23e50af0ce1a6eb63f1417dc3f56b379e2cdc", "size": 1085, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/atanh.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "include/boost/simd/function/atanh.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/atanh.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 22.1428571429, "max_line_length": 100, "alphanum_fraction": 0.5797235023, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.7154240079185318, "lm_q1q2_score": 0.6228461942536577}}
{"text": "#define BOOST_TEST_NO_LIB\n#include <boost/test/auto_unit_test.hpp>\n\n#include \"coconut/pulp/math/Angle.hpp\"\n#include \"coconut/pulp/math/Rotation.hpp\"\n\nusing namespace coconut;\nusing namespace coconut::pulp;\nusing namespace coconut::pulp::math;\n\nnamespace /* anonymous */ {\n\nBOOST_AUTO_TEST_SUITE(PulpTestSuite);\nBOOST_AUTO_TEST_SUITE(PulpMathTestSuite);\nBOOST_AUTO_TEST_SUITE(PulpMathRotationTestSuite);\n\nBOOST_AUTO_TEST_CASE(AppliesRotationToVector) {\n\tconst auto rotation = Rotation({ 2.0f, 1.0f, 3.0f }, -23.0_deg);\n\n\tconst auto start = Vec3(1.0f, 3.0f, 5.0f);\n\tconst auto end = Vec3(1.565343f, 3.60607f, 4.421081f);\n\tconst auto rotated = rotation.apply(start);\n\tBOOST_CHECK_EQUAL(rotated, end);\n}\n\nBOOST_AUTO_TEST_CASE(AppendsRotations) {\n\tconst auto first = Rotation({ 2.0f, 1.0f, 3.0f }, -23.0_deg);\n\tconst auto then = Rotation({ 0.0f, 1.0f, 0.0f }, 180.0_deg);\n\tconst auto rotation = first << then;\n\n\tconst auto start = Vec3(1.0f, 3.0f, 5.0f);\n\tconst auto end = Vec3(-1.565343f, 3.60607f, -4.421081f);\n\tconst auto rotated = rotation.apply(start);\n\tBOOST_CHECK_EQUAL(rotated, end);\n}\n\nBOOST_AUTO_TEST_CASE(LinearlyInterpolatesRotations) {\n\tconst auto r1 = Rotation({ 0.0f, 1.0f, 0.0f }, 0.0_deg);\n\tconst auto r2 = Rotation({ 0.0f, 1.0f, 0.0f }, 10.0_deg);\n\n\tconst auto interpolated = lerp(r1, r2, 0.25f);\n\tconst auto expected = Rotation({ 0.0f, 1.0f, 0.0f }, 2.5_deg);\n\n\tBOOST_CHECK_EQUAL(interpolated.rotationQuaternion(), expected.rotationQuaternion());\n}\n\nBOOST_AUTO_TEST_CASE(SphericallyLinearlyInterpolatesRotations) {\n\tconst auto r1 = Rotation({ 0.0f, 1.0f, 0.0f }, 0.0_deg);\n\tconst auto r2 = Rotation({ 0.0f, 1.0f, 0.0f }, 90.0_deg);\n\n\tconst auto interpolated = slerp(r1, r2, 0.25f);\n\tconst auto expected = Rotation({ 0.0f, 1.0f, 0.0f }, degrees(90.0f * 0.25f));\n\n\tBOOST_CHECK_EQUAL(interpolated.rotationQuaternion(), expected.rotationQuaternion());\n}\n\nBOOST_AUTO_TEST_SUITE_END(/* PulpMathRotationTestSuite */);\nBOOST_AUTO_TEST_SUITE_END(/* PulpMathTestSuite */);\nBOOST_AUTO_TEST_SUITE_END(/* PulpTestSuite */);\n\n} // anonymous namespace\n", "meta": {"hexsha": "da4baf8d947f284257b8b1ea7adeabd49a498af1", "size": 2051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "coconut-pulp-math/src/test/c++/coconut/pulp/math/Rotation.cpp", "max_stars_repo_name": "mikosz/coconut", "max_stars_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T12:01:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T12:01:54.000Z", "max_issues_repo_path": "coconut-pulp-math/src/test/c++/coconut/pulp/math/Rotation.cpp", "max_issues_repo_name": "mikosz/coconut", "max_issues_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coconut-pulp-math/src/test/c++/coconut/pulp/math/Rotation.cpp", "max_forks_repo_name": "mikosz/coconut", "max_forks_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0806451613, "max_line_length": 85, "alphanum_fraction": 0.7328132618, "num_tokens": 678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6228461760045267}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <boost/numeric/meta_math/power_of_2.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n\nvoid test_power_of_2() \n{\n    using namespace meta_math;\n\n    MTL_THROW_IF(power_of_2<0>::value != 1, mtl::runtime_error(\"wrong value\"));\n    MTL_THROW_IF(power_of_2<1>::value != 2, mtl::runtime_error(\"wrong value\"));\n    MTL_THROW_IF(power_of_2<2>::value != 4, mtl::runtime_error(\"wrong value\"));\n    MTL_THROW_IF(power_of_2<3>::value != 8, mtl::runtime_error(\"wrong value\"));\n}\n\n\nint main() \n{\n    test_power_of_2();\n    return 0;\n}\n", "meta": {"hexsha": "74045f24e34506bd7349596ba0bed56bf859540a", "size": 981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/power_of_2_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/power_of_2_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/power_of_2_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 30.65625, "max_line_length": 94, "alphanum_fraction": 0.6982670744, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6228461668748562}}
{"text": "/* test_cauchy.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n\r\n#include <boost/random/cauchy_distribution.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/math/distributions/cauchy.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::cauchy_distribution<>\r\n#define BOOST_RANDOM_DISTRIBUTION_NAME cauchy\r\n#define BOOST_MATH_DISTRIBUTION boost::math::cauchy\r\n#define BOOST_RANDOM_ARG1_TYPE double\r\n#define BOOST_RANDOM_ARG1_NAME median\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(-n, n)\r\n#define BOOST_RANDOM_ARG2_TYPE double\r\n#define BOOST_RANDOM_ARG2_NAME sigma\r\n#define BOOST_RANDOM_ARG2_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(n) boost::uniform_real<>(0.001, n)\r\n\r\n#include \"test_real_distribution.ipp\"\r\n", "meta": {"hexsha": "d7645c4eb5ad458250158e3ed70bb21264695cc1", "size": 982, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_cauchy.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/random/test/test_cauchy.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/random/test/test_cauchy.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 33.8620689655, "max_line_length": 74, "alphanum_fraction": 0.7871690428, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6228461659181374}}
{"text": "// Copyright Nick Thompson, 2019\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_TEST_MODULE vector_barycentric_rational\n\n#include <cmath>\n#include <random>\n#include <array>\n#include <Eigen/Dense>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/type_index.hpp>\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/math/interpolators/barycentric_rational.hpp>\n#include <boost/math/interpolators/vector_barycentric_rational.hpp>\n\nusing std::sqrt;\nusing std::abs;\nusing std::numeric_limits;\n\ntemplate<class Real>\nvoid test_agreement_with_1d()\n{\n    std::cout << \"Testing with 1D interpolation on type \"\n              << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n    std::mt19937 gen(4723);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> t(100);\n    std::vector<Eigen::Vector2d> y(100);\n    t[0] = dis(gen);\n    y[0][0] = dis(gen);\n    y[0][1] = dis(gen);\n    for (size_t i = 1; i < t.size(); ++i)\n    {\n        t[i] = t[i-1] + dis(gen);\n        y[i][0] = dis(gen);\n        y[i][1] = dis(gen);\n    }\n\n    std::vector<Eigen::Vector2d> y_copy = y;\n    std::vector<Real> t_copy = t;\n    std::vector<Real> t_copy0 = t;\n    std::vector<Real> t_copy1 = t;\n\n    std::vector<Real> y_copy0(y.size());\n    std::vector<Real> y_copy1(y.size());\n    for (size_t i = 0; i < y.size(); ++i) {\n        y_copy0[i] = y[i][0];\n        y_copy1[i] = y[i][1];\n    }\n\n    boost::random::uniform_real_distribution<Real> dis2(t[0], t[t.size()-1]);\n    boost::math::interpolators::vector_barycentric_rational<decltype(t), decltype(y)> interpolator(std::move(t), std::move(y));\n    boost::math::interpolators::barycentric_rational<Real> scalar_interpolator0(std::move(t_copy0), std::move(y_copy0));\n    boost::math::interpolators::barycentric_rational<Real> scalar_interpolator1(std::move(t_copy1), std::move(y_copy1));\n\n\n    Eigen::Vector2d z;\n\n    size_t samples = 0;\n    while (samples++ < 1000)\n    {\n        Real t = dis2(gen);\n        interpolator(z, t);\n        BOOST_CHECK_CLOSE(z[0], scalar_interpolator0(t), 10000*numeric_limits<Real>::epsilon());\n        BOOST_CHECK_CLOSE(z[1], scalar_interpolator1(t), 10000*numeric_limits<Real>::epsilon());\n    }\n}\n\n\ntemplate<class Real>\nvoid test_interpolation_condition_eigen()\n{\n    std::cout << \"Testing interpolation condition for barycentric interpolation on Eigen vectors of type \"\n              << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n    std::mt19937 gen(4723);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> t(100);\n    std::vector<Eigen::Vector2d> y(100);\n    t[0] = dis(gen);\n    y[0][0] = dis(gen);\n    y[0][1] = dis(gen);\n    for (size_t i = 1; i < t.size(); ++i)\n    {\n        t[i] = t[i-1] + dis(gen);\n        y[i][0] = dis(gen);\n        y[i][1] = dis(gen);\n    }\n\n    std::vector<Eigen::Vector2d> y_copy = y;\n    std::vector<Real> t_copy = t;\n    boost::math::interpolators::vector_barycentric_rational<decltype(t), decltype(y)> interpolator(std::move(t), std::move(y));\n\n    Eigen::Vector2d z;\n    for (size_t i = 0; i < t_copy.size(); ++i)\n    {\n        interpolator(z, t_copy[i]);\n        BOOST_CHECK_CLOSE(z[0], y_copy[i][0], 100*numeric_limits<Real>::epsilon());\n        BOOST_CHECK_CLOSE(z[1], y_copy[i][1], 100*numeric_limits<Real>::epsilon());\n    }\n}\n\ntemplate<class Real>\nvoid test_interpolation_condition_std_array()\n{\n    std::cout << \"Testing interpolation condition for barycentric interpolation on std::array vectors of type \"\n              << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n    std::mt19937 gen(4723);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> t(100);\n    std::vector<std::array<Real, 2>> y(100);\n    t[0] = dis(gen);\n    y[0][0] = dis(gen);\n    y[0][1] = dis(gen);\n    for (size_t i = 1; i < t.size(); ++i)\n    {\n        t[i] = t[i-1] + dis(gen);\n        y[i][0] = dis(gen);\n        y[i][1] = dis(gen);\n    }\n\n    std::vector<std::array<Real, 2>> y_copy = y;\n    std::vector<Real> t_copy = t;\n    boost::math::interpolators::vector_barycentric_rational<decltype(t), decltype(y)> interpolator(std::move(t), std::move(y));\n\n    std::array<Real, 2> z;\n    for (size_t i = 0; i < t_copy.size(); ++i)\n    {\n        interpolator(z, t_copy[i]);\n        BOOST_CHECK_CLOSE(z[0], y_copy[i][0], 100*numeric_limits<Real>::epsilon());\n        BOOST_CHECK_CLOSE(z[1], y_copy[i][1], 100*numeric_limits<Real>::epsilon());\n    }\n}\n\n\ntemplate<class Real>\nvoid test_interpolation_condition_ublas()\n{\n    std::cout << \"Testing interpolation condition for barycentric interpolation ublas vectors of type \"\n              << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n    std::mt19937 gen(4723);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> t(100);\n    std::vector<boost::numeric::ublas::vector<Real>> y(100);\n    t[0] = dis(gen);\n    y[0].resize(2);\n    y[0][0] = dis(gen);\n    y[0][1] = dis(gen);\n    for (size_t i = 1; i < t.size(); ++i)\n    {\n        t[i] = t[i-1] + dis(gen);\n        y[i].resize(2);\n        y[i][0] = dis(gen);\n        y[i][1] = dis(gen);\n    }\n\n    std::vector<Real> t_copy = t;\n    std::vector<boost::numeric::ublas::vector<Real>> y_copy = y;\n\n    boost::math::interpolators::vector_barycentric_rational<decltype(t), decltype(y)> interpolator(std::move(t), std::move(y));\n\n    boost::numeric::ublas::vector<Real> z(2);\n    for (size_t i = 0; i < t_copy.size(); ++i)\n    {\n        interpolator(z, t_copy[i]);\n        BOOST_CHECK_CLOSE(z[0], y_copy[i][0], 100*numeric_limits<Real>::epsilon());\n        BOOST_CHECK_CLOSE(z[1], y_copy[i][1], 100*numeric_limits<Real>::epsilon());\n    }\n}\n\ntemplate<class Real>\nvoid test_interpolation_condition_high_order()\n{\n    std::cout << \"Testing interpolation condition in high order for barycentric interpolation on type \" << boost::typeindex::type_id<Real>().pretty_name()  << \"\\n\";\n    std::mt19937 gen(5);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> t(100);\n    std::vector<Eigen::Vector2d> y(100);\n    t[0] = dis(gen);\n    y[0][0] = dis(gen);\n    y[0][1] = dis(gen);\n    for (size_t i = 1; i < t.size(); ++i)\n    {\n        t[i] = t[i-1] + dis(gen);\n        y[i][0] = dis(gen);\n        y[i][1] = dis(gen);\n    }\n\n    std::vector<Eigen::Vector2d> y_copy = y;\n    std::vector<Real> t_copy = t;\n    boost::math::interpolators::vector_barycentric_rational<decltype(t), decltype(y)> interpolator(std::move(t), std::move(y), 5);\n\n    Eigen::Vector2d z;\n    for (size_t i = 0; i < t_copy.size(); ++i)\n    {\n        interpolator(z, t_copy[i]);\n        BOOST_CHECK_CLOSE(z[0], y_copy[i][0], 100*numeric_limits<Real>::epsilon());\n        BOOST_CHECK_CLOSE(z[1], y_copy[i][1], 100*numeric_limits<Real>::epsilon());\n    }\n}\n\n\ntemplate<class Real>\nvoid test_constant_eigen()\n{\n    std::cout << \"Testing that constants are interpolated correctly using barycentric interpolation on Eigen vectors of type \"\n              << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    std::mt19937 gen(6);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> t(100);\n    std::vector<Eigen::Vector2d> y(100);\n    t[0] = dis(gen);\n    Real constant0 = dis(gen);\n    Real constant1 = dis(gen);\n    y[0][0] = constant0;\n    y[0][1] = constant1;\n    for (size_t i = 1; i < t.size(); ++i)\n    {\n        t[i] = t[i-1] + dis(gen);\n        y[i][0] = constant0;\n        y[i][1] = constant1;\n    }\n\n    std::vector<Eigen::Vector2d> y_copy = y;\n    std::vector<Real> t_copy = t;\n    boost::math::interpolators::vector_barycentric_rational<decltype(t), decltype(y)> interpolator(std::move(t), std::move(y));\n\n    Eigen::Vector2d z;\n    for (size_t i = 0; i < t_copy.size(); ++i)\n    {\n        // Don't evaluate the constant at x[i]; that's already tested in the interpolation condition test.\n        Real t = t_copy[i] + dis(gen);\n        z = interpolator(t);\n        BOOST_CHECK_CLOSE(z[0], constant0, 100*sqrt(numeric_limits<Real>::epsilon()));\n        BOOST_CHECK_CLOSE(z[1], constant1, 100*sqrt(numeric_limits<Real>::epsilon()));\n        Eigen::Vector2d zprime = interpolator.prime(t);\n        Real zero_0 = zprime[0];\n        Real zero_1 = zprime[1];\n        BOOST_CHECK_SMALL(zero_0, sqrt(numeric_limits<Real>::epsilon()));\n        BOOST_CHECK_SMALL(zero_1, sqrt(numeric_limits<Real>::epsilon()));\n    }\n}\n\n\ntemplate<class Real>\nvoid test_constant_std_array()\n{\n    std::cout << \"Testing that constants are interpolated correctly using barycentric interpolation on std::array vectors of type \"\n              << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    std::mt19937 gen(6);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> t(100);\n    std::vector<std::array<Real, 2>> y(100);\n    t[0] = dis(gen);\n    Real constant0 = dis(gen);\n    Real constant1 = dis(gen);\n    y[0][0] = constant0;\n    y[0][1] = constant1;\n    for (size_t i = 1; i < t.size(); ++i)\n    {\n        t[i] = t[i-1] + dis(gen);\n        y[i][0] = constant0;\n        y[i][1] = constant1;\n    }\n\n    std::vector<std::array<Real,2>> y_copy = y;\n    std::vector<Real> t_copy = t;\n    boost::math::interpolators::vector_barycentric_rational<decltype(t), decltype(y)> interpolator(std::move(t), std::move(y));\n\n    std::array<Real, 2> z;\n    for (size_t i = 0; i < t_copy.size(); ++i)\n    {\n        // Don't evaluate the constant at x[i]; that's already tested in the interpolation condition test.\n        Real t = t_copy[i] + dis(gen);\n        z = interpolator(t);\n        BOOST_CHECK_CLOSE(z[0], constant0, 100*sqrt(numeric_limits<Real>::epsilon()));\n        BOOST_CHECK_CLOSE(z[1], constant1, 100*sqrt(numeric_limits<Real>::epsilon()));\n        std::array<Real, 2> zprime = interpolator.prime(t);\n        Real zero_0 = zprime[0];\n        Real zero_1 = zprime[1];\n        BOOST_CHECK_SMALL(zero_0, sqrt(numeric_limits<Real>::epsilon()));\n        BOOST_CHECK_SMALL(zero_1, sqrt(numeric_limits<Real>::epsilon()));\n    }\n}\n\n\ntemplate<class Real>\nvoid test_constant_high_order()\n{\n    std::cout << \"Testing that constants are interpolated correctly using barycentric interpolation on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    std::mt19937 gen(6);\n    boost::random::uniform_real_distribution<Real> dis(0.1f, 1);\n    std::vector<Real> t(100);\n    std::vector<Eigen::Vector2d> y(100);\n    t[0] = dis(gen);\n    Real constant0 = dis(gen);\n    Real constant1 = dis(gen);\n    y[0][0] = constant0;\n    y[0][1] = constant1;\n    for (size_t i = 1; i < t.size(); ++i)\n    {\n        t[i] = t[i-1] + dis(gen);\n        y[i][0] = constant0;\n        y[i][1] = constant1;\n    }\n\n    std::vector<Eigen::Vector2d> y_copy = y;\n    std::vector<Real> t_copy = t;\n    boost::math::interpolators::vector_barycentric_rational<decltype(t), decltype(y)> interpolator(std::move(t), std::move(y), 5);\n\n    Eigen::Vector2d z;\n    for (size_t i = 0; i < t_copy.size(); ++i)\n    {\n        // Don't evaluate the constant at x[i]; that's already tested in the interpolation condition test.\n        Real t = t_copy[i] + dis(gen);\n        z = interpolator(t);\n        BOOST_CHECK_CLOSE(z[0], constant0, 100*sqrt(numeric_limits<Real>::epsilon()));\n        BOOST_CHECK_CLOSE(z[1], constant1, 100*sqrt(numeric_limits<Real>::epsilon()));\n        Eigen::Vector2d zprime = interpolator.prime(t);\n        Real zero_0 = zprime[0];\n        Real zero_1 = zprime[1];\n        BOOST_CHECK_SMALL(zero_0, sqrt(numeric_limits<Real>::epsilon()));\n        BOOST_CHECK_SMALL(zero_1, sqrt(numeric_limits<Real>::epsilon()));\n    }\n}\n\n\ntemplate<class Real>\nvoid test_weights()\n{\n    std::cout << \"Testing weights are calculated correctly using barycentric interpolation on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n\n    std::mt19937 gen(9);\n    boost::random::uniform_real_distribution<Real> dis(0.005, 0.01);\n    std::vector<Real> t(100);\n    std::vector<Eigen::Vector2d> y(100);\n    t[0] = dis(gen);\n    y[0][0] = dis(gen);\n    y[0][1] = dis(gen);\n    for (size_t i = 1; i < t.size(); ++i)\n    {\n        t[i] = t[i-1] + dis(gen);\n        y[i][0] = dis(gen);\n        y[i][1] = dis(gen);\n    }\n\n    std::vector<Eigen::Vector2d> y_copy = y;\n    std::vector<Real> t_copy = t;\n    boost::math::interpolators::detail::vector_barycentric_rational_imp<decltype(t), decltype(y)> interpolator(std::move(t), std::move(y), 1);\n\n    for (size_t i = 1; i < t_copy.size() - 1; ++i)\n    {\n        Real w = interpolator.weight(i);\n        Real w_expect = 1/(t_copy[i] - t_copy[i - 1]) + 1/(t_copy[i+1] - t_copy[i]);\n        if (i % 2 == 0)\n        {\n            BOOST_CHECK_CLOSE(w, -w_expect, 0.00001);\n        }\n        else\n        {\n            BOOST_CHECK_CLOSE(w, w_expect, 0.00001);\n        }\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(vector_barycentric_rational)\n{\n    test_weights<double>();\n    test_constant_eigen<double>();\n    test_constant_std_array<double>();\n    test_constant_high_order<double>();\n    test_interpolation_condition_eigen<double>();\n    test_interpolation_condition_ublas<double>();\n    test_interpolation_condition_std_array<double>();\n    test_interpolation_condition_high_order<double>();\n    test_agreement_with_1d<double>();\n}\n", "meta": {"hexsha": "f8050d2427a1f2f279108859215caeb2d0c535d1", "size": 13527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_vector_barycentric_rational.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/test_vector_barycentric_rational.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/test_vector_barycentric_rational.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 35.0440414508, "max_line_length": 169, "alphanum_fraction": 0.6158793524, "num_tokens": 3984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6228461615924816}}
{"text": "// Copyright (C) 2010  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n\n\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <dlib/statistics.h>\n#include <dlib/rand.h>\n#include <dlib/svm.h>\n#include <algorithm>\n#include <dlib/matrix.h>\n#include <cmath>\n\n#include \"tester.h\"\n\nnamespace  \n{\n\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.statistics\");\n\n\n\n    class statistics_tester : public tester\n    {\n    public:\n        statistics_tester (\n        ) :\n            tester (\"test_statistics\",\n                    \"Runs tests on the statistics component.\")\n        {}\n\n        void test_random_subset_selector ()\n        {\n            random_subset_selector<double> rand_set;\n\n            for (int j = 0; j < 30; ++j)\n            {\n                print_spinner();\n\n                running_stats<double> rs, rs2;\n\n                rand_set.set_max_size(1000);\n\n                for (double i = 0; i < 100000; ++i)\n                {\n                    rs.add(i);\n                    rand_set.add(i);\n                }\n\n\n                for (unsigned long i = 0; i < rand_set.size(); ++i)\n                    rs2.add(rand_set[i]);\n\n\n                dlog << LDEBUG << \"true mean:    \" << rs.mean();\n                dlog << LDEBUG << \"true sampled: \" << rs2.mean();\n                double ratio = rs.mean()/rs2.mean();\n                DLIB_TEST_MSG(0.96 < ratio  && ratio < 1.04, \" ratio: \" << ratio);\n            }\n\n\n            {\n                random_subset_selector<int> r1, r2;\n                r1.set_max_size(300);\n                for (int i = 0; i < 4000; ++i)\n                    r1.add(i);\n\n                ostringstream sout;\n                serialize(r1, sout);\n                istringstream sin(sout.str());\n                deserialize(r2, sin);\n\n                DLIB_TEST(r1.size() == r2.size());\n                DLIB_TEST(r1.max_size() == r2.max_size());\n                DLIB_TEST(r1.next_add_accepts() == r2.next_add_accepts());\n                DLIB_TEST(std::equal(r1.begin(), r1.end(), r2.begin()));\n\n                for (int i = 0; i < 4000; ++i)\n                {\n                    r1.add(i);\n                    r2.add(i);\n                }\n\n                DLIB_TEST(r1.size() == r2.size());\n                DLIB_TEST(r1.max_size() == r2.max_size());\n                DLIB_TEST(r1.next_add_accepts() == r2.next_add_accepts());\n                DLIB_TEST(std::equal(r1.begin(), r1.end(), r2.begin()));\n            }\n        }\n\n        void test_random_subset_selector2 ()\n        {\n            random_subset_selector<double> rand_set;\n            DLIB_TEST(rand_set.next_add_accepts() == false);\n            DLIB_TEST(rand_set.size() == 0);\n            DLIB_TEST(rand_set.max_size() == 0);\n\n            for (int j = 0; j < 30; ++j)\n            {\n                print_spinner();\n\n                running_stats<double> rs, rs2;\n\n                rand_set.set_max_size(1000);\n                DLIB_TEST(rand_set.next_add_accepts() == true);\n\n                for (double i = 0; i < 100000; ++i)\n                {\n                    rs.add(i);\n                    if (rand_set.next_add_accepts())\n                        rand_set.add(i);\n                    else\n                        rand_set.add();\n                }\n\n                DLIB_TEST(rand_set.size() == 1000);\n                DLIB_TEST(rand_set.max_size() == 1000);\n\n                for (unsigned long i = 0; i < rand_set.size(); ++i)\n                    rs2.add(rand_set[i]);\n\n\n                dlog << LDEBUG << \"true mean:    \" << rs.mean();\n                dlog << LDEBUG << \"true sampled: \" << rs2.mean();\n                double ratio = rs.mean()/rs2.mean();\n                DLIB_TEST_MSG(0.96 < ratio  && ratio < 1.04, \" ratio: \" << ratio);\n            }\n        }\n\n        void test_running_cross_covariance ()\n        {\n            running_cross_covariance<matrix<double> > rcc1, rcc2;\n\n            matrix<double,0,1> xm, ym;\n            const int num = 40;\n\n            dlib::rand rnd;\n            for (int i = 0; i < num; ++i)\n            {\n                matrix<double,0,1> x = randm(4,1,rnd);\n                matrix<double,0,1> y = randm(4,1,rnd);\n\n                xm += x/num;\n                ym += y/num;\n\n                if (i < 15)\n                    rcc1.add(x,y);\n                else\n                    rcc2.add(x,y);\n            }\n\n            rnd.clear();\n            matrix<double> cov;\n            for (int i = 0; i < num; ++i)\n            {\n                matrix<double,0,1> x = randm(4,1,rnd);\n                matrix<double,0,1> y = randm(4,1,rnd);\n                cov += (x-xm)*trans(y-ym);\n            }\n            cov /= num-1;\n\n            running_cross_covariance<matrix<double> > rcc = rcc1 + rcc2;\n            DLIB_TEST(max(abs(rcc.covariance_xy()-cov)) < 1e-14);\n            DLIB_TEST(max(abs(rcc.mean_x()-xm)) < 1e-14);\n            DLIB_TEST(max(abs(rcc.mean_y()-ym)) < 1e-14);\n        }\n\n        std::map<unsigned long,double> dense_to_sparse ( \n            const matrix<double,0,1>& x\n        )\n        {\n            std::map<unsigned long,double> temp;\n            for (long i = 0; i < x.size(); ++i)\n                temp[i] = x(i);\n            return temp;\n        }\n\n        void test_running_cross_covariance_sparse()\n        {\n            running_cross_covariance<matrix<double> > rcc1, rcc2;\n\n            running_covariance<matrix<double> > rc1, rc2;\n\n            matrix<double,0,1> xm, ym;\n            const int num = 40;\n\n            rc1.set_dimension(4);\n            rc2.set_dimension(4);\n\n            rcc1.set_dimensions(4,5);\n            rcc2.set_dimensions(4,5);\n\n            dlib::rand rnd;\n            for (int i = 0; i < num; ++i)\n            {\n                matrix<double,0,1> x = randm(4,1,rnd);\n                matrix<double,0,1> y = randm(5,1,rnd);\n\n                xm += x/num;\n                ym += y/num;\n\n                if (i < 15)\n                {\n                    rcc1.add(x,dense_to_sparse(y));\n                    rc1.add(x);\n                }\n                else if (i < 30)\n                {\n                    rcc2.add(dense_to_sparse(x),y);\n                    rc2.add(dense_to_sparse(x));\n                }\n                else\n                {\n                    rcc2.add(dense_to_sparse(x),dense_to_sparse(y));\n                    rc2.add(x);\n                }\n            }\n\n            rnd.clear();\n            matrix<double> cov, cov2;\n            for (int i = 0; i < num; ++i)\n            {\n                matrix<double,0,1> x = randm(4,1,rnd);\n                matrix<double,0,1> y = randm(5,1,rnd);\n                cov += (x-xm)*trans(y-ym);\n                cov2 += (x-xm)*trans(x-xm);\n            }\n            cov /= num-1;\n            cov2 /= num-1;\n\n            running_cross_covariance<matrix<double> > rcc = rcc1 + rcc2;\n            DLIB_TEST_MSG(max(abs(rcc.covariance_xy()-cov)) < 1e-14, max(abs(rcc.covariance_xy()-cov)));\n            DLIB_TEST(max(abs(rcc.mean_x()-xm)) < 1e-14);\n            DLIB_TEST(max(abs(rcc.mean_y()-ym)) < 1e-14);\n\n            running_covariance<matrix<double> > rc = rc1 + rc2;\n            DLIB_TEST(max(abs(rc.covariance()-cov2)) < 1e-14);\n            DLIB_TEST(max(abs(rc.mean()-xm)) < 1e-14);\n        }\n\n        void test_running_covariance (\n        )\n        {\n            dlib::rand rnd;\n            std::vector<matrix<double,0,1> > vects;\n\n            running_covariance<matrix<double,0,1> > cov, cov2;\n            DLIB_TEST(cov.in_vector_size() == 0);\n\n            for (unsigned long dims = 1; dims < 5; ++dims)\n            {\n                for (unsigned long samps = 2; samps < 10; ++samps)\n                {\n                    vects.clear();\n                    cov.clear();\n                    DLIB_TEST(cov.in_vector_size() == 0);\n                    for (unsigned long i = 0; i < samps; ++i)\n                    {\n                        vects.push_back(randm(dims,1,rnd));\n                        cov.add(vects.back());\n\n                    }\n                    DLIB_TEST(cov.in_vector_size() == (long)dims);\n\n                    DLIB_TEST(equal(mean(mat(vects)), cov.mean()));\n                    DLIB_TEST_MSG(equal(covariance(mat(vects)), cov.covariance()),\n                              max(abs(covariance(mat(vects)) - cov.covariance()))\n                              << \"   dims = \" << dims << \"   samps = \" << samps\n                              );\n                }\n            }\n\n            for (unsigned long dims = 1; dims < 5; ++dims)\n            {\n                for (unsigned long samps = 2; samps < 10; ++samps)\n                {\n                    vects.clear();\n                    cov.clear();\n                    cov2.clear();\n                    DLIB_TEST(cov.in_vector_size() == 0);\n                    for (unsigned long i = 0; i < samps; ++i)\n                    {\n                        vects.push_back(randm(dims,1,rnd));\n                        if ((i%2) == 0)\n                            cov.add(vects.back());\n                        else\n                            cov2.add(vects.back());\n\n                    }\n                    DLIB_TEST((cov+cov2).in_vector_size() == (long)dims);\n\n                    DLIB_TEST(equal(mean(mat(vects)), (cov+cov2).mean()));\n                    DLIB_TEST_MSG(equal(covariance(mat(vects)), (cov+cov2).covariance()),\n                              max(abs(covariance(mat(vects)) - (cov+cov2).covariance()))\n                              << \"   dims = \" << dims << \"   samps = \" << samps\n                              );\n                }\n            }\n\n        }\n\n        void test_running_stats()\n        {\n            print_spinner();\n\n            running_stats<double> rs, rs2;\n\n            running_scalar_covariance<double> rsc1, rsc2;\n            running_scalar_covariance_decayed<double> rscd1(1000000), rscd2(1000000);\n\n            for (double i = 0; i < 100; ++i)\n            {\n                rs.add(i);\n\n                rsc1.add(i,i);\n                rsc2.add(i,i);\n                rsc2.add(i,-i);\n\n                rscd1.add(i,i);\n                rscd2.add(i,i);\n                rscd2.add(i,-i);\n            }\n\n            // make sure the running_stats and running_scalar_covariance agree\n            DLIB_TEST_MSG(std::abs(rs.mean() - rsc1.mean_x()) < 1e-10, std::abs(rs.mean() - rsc1.mean_x()));\n            DLIB_TEST(std::abs(rs.mean() - rsc1.mean_y()) < 1e-10);\n            DLIB_TEST(std::abs(rs.stddev() - rsc1.stddev_x()) < 1e-10);\n            DLIB_TEST(std::abs(rs.stddev() - rsc1.stddev_y()) < 1e-10);\n            DLIB_TEST(std::abs(rs.variance() - rsc1.variance_x()) < 1e-10);\n            DLIB_TEST(std::abs(rs.variance() - rsc1.variance_y()) < 1e-10);\n            DLIB_TEST(rs.current_n() == rsc1.current_n());\n\n            DLIB_TEST(std::abs(rsc1.correlation() - 1) < 1e-10);\n            DLIB_TEST(std::abs(rsc2.correlation() - 0) < 1e-10);\n\n\n            const double s = 99/100.0;\n            const double ss = std::sqrt(s);;\n            DLIB_TEST_MSG(std::abs(rs.mean() - rscd1.mean_x()) < 1e-2, std::abs(rs.mean() - rscd1.mean_x()) << \" \" << rscd1.mean_x());\n            DLIB_TEST(std::abs(rs.mean() - rscd1.mean_y()) < 1e-2);\n            DLIB_TEST_MSG(std::abs(ss*rs.stddev() - rscd1.stddev_x()) < 1e-2, std::abs(ss*rs.stddev() - rscd1.stddev_x()));\n            DLIB_TEST(std::abs(ss*rs.stddev() - rscd1.stddev_y()) < 1e-2);\n            DLIB_TEST_MSG(std::abs(s*rs.variance() - rscd1.variance_x()) < 1e-2, std::abs(s*rs.variance() - rscd1.variance_x()));\n            DLIB_TEST(std::abs(s*rs.variance() - rscd1.variance_y()) < 1e-2);\n            DLIB_TEST(std::abs(rscd1.correlation() - 1) < 1e-2);\n            DLIB_TEST(std::abs(rscd2.correlation() - 0) < 1e-2);\n\n\n\n            // test serialization of running_stats\n            ostringstream sout;\n            serialize(rs, sout);\n            istringstream sin(sout.str());\n            deserialize(rs2, sin);\n            // make sure the running_stats and running_scalar_covariance agree\n            DLIB_TEST_MSG(std::abs(rs2.mean() - rsc1.mean_x()) < 1e-10, std::abs(rs2.mean() - rsc1.mean_x()));\n            DLIB_TEST(std::abs(rs2.mean() - rsc1.mean_y()) < 1e-10);\n            DLIB_TEST(std::abs(rs2.stddev() - rsc1.stddev_x()) < 1e-10);\n            DLIB_TEST(std::abs(rs2.stddev() - rsc1.stddev_y()) < 1e-10);\n            DLIB_TEST(std::abs(rs2.variance() - rsc1.variance_x()) < 1e-10);\n            DLIB_TEST(std::abs(rs2.variance() - rsc1.variance_y()) < 1e-10);\n            DLIB_TEST(rs2.current_n() == rsc1.current_n());\n\n            rsc1.clear();\n            rsc1.add(1, -1);\n            rsc1.add(0, 0);\n            rsc1.add(1, -1);\n            rsc1.add(0, 0);\n            rsc1.add(1, -1);\n            rsc1.add(0, 0);\n\n            DLIB_TEST(std::abs(rsc1.covariance() - -0.3) < 1e-10);\n        }\n\n        void test_skewness_and_kurtosis_1()\n        {\n\n            dlib::rand rnum;\n            running_stats<double> rs1;\n\n            double tp = 0;\n\n            rnum.set_seed(\"DlibRocks\");\n\n            for(int i = 0; i< 1000000; i++)\n            {\n                tp = rnum.get_random_gaussian();\n                rs1.add(tp);\n            }   \n\n            // check the unbiased skewness and excess kurtosis of one million Gaussian\n            // draws are both near_vects zero.\n            DLIB_TEST(abs(rs1.skewness()) < 0.1);\n            DLIB_TEST(abs(rs1.ex_kurtosis()) < 0.1);\n        }\n\n        void test_skewness_and_kurtosis_2()\n        {\n\n            string str = \"DlibRocks\";\n\n            for(int j = 0; j<5 ; j++)\n            {\n                matrix<double,1,100000> dat;\n                dlib::rand rnum;\n                running_stats<double> rs1;\n     \n                double tp = 0;\n                double n = 100000;\n                double xb = 0;\n    \n                double sknum = 0;\n                double skdenom = 0;\n                double unbi_skew = 0;\n    \n                double exkurnum = 0;\n                double exkurdenom = 0;\n                double unbi_exkur = 0;\n\n                random_shuffle(str.begin(), str.end());\n                rnum.set_seed(str);\n\n                for(int i = 0; i<n; i++)\n                {\n                    tp = rnum.get_random_gaussian();\n                    rs1.add(tp);\n                    dat(i)=tp;\n                    xb += dat(i);\n                }   \n    \n                xb = xb/n;\n\n                for(int i = 0; i < n; i++ )\n                { \n                    sknum += pow(dat(i) - xb,3);\n                    skdenom += pow(dat(i) - xb,2);\n                    exkurnum += pow(dat(i) - xb,4);\n                    exkurdenom += pow(dat(i)-xb,2);\n                }\n\n                sknum = sknum/n;\n                skdenom = pow(skdenom/n,1.5);\n                exkurnum = exkurnum/n;\n                exkurdenom = pow(exkurdenom/n,2);\n    \n                unbi_skew = sqrt(n*(n-1))/(n-2)*sknum/skdenom;\n                unbi_exkur = (n-1)*((n+1)*(exkurnum/exkurdenom-3)+6)/((n-2)*(n-3));\n\n                dlog << LINFO << \"Skew Diff: \" <<  unbi_skew - rs1.skewness();\n                dlog << LINFO << \"Kur Diff: \" << unbi_exkur - rs1.ex_kurtosis();\n                \n                // Test an alternative implementation of the unbiased skewness and excess\n                // kurtosis against the one in running_stats.\n                DLIB_TEST(abs(unbi_skew - rs1.skewness()) < 1e-10);\n                DLIB_TEST(abs(unbi_exkur - rs1.ex_kurtosis()) < 1e-10);\n            }\n        }\n\n        void test_randomize_samples()\n        {\n            std::vector<unsigned int> t(15),u(15),v(15);\n\n            for (unsigned long i = 0; i < t.size(); ++i)\n            {\n                t[i] = i;\n                u[i] = i+1;\n                v[i] = i+2;\n            }\n            randomize_samples(t,u,v);\n\n            DLIB_TEST(t.size() == 15);\n            DLIB_TEST(u.size() == 15);\n            DLIB_TEST(v.size() == 15);\n\n            for (unsigned long i = 0; i < t.size(); ++i)\n            {\n                const unsigned long val = t[i];\n                DLIB_TEST(u[i] == val+1);\n                DLIB_TEST(v[i] == val+2);\n            }\n        }\n        void test_randomize_samples2()\n        {\n            dlib::matrix<int,15,1> t(15),u(15),v(15);\n\n            for (long i = 0; i < t.size(); ++i)\n            {\n                t(i) = i;\n                u(i) = i+1;\n                v(i) = i+2;\n            }\n            randomize_samples(t,u,v);\n\n            DLIB_TEST(t.size() == 15);\n            DLIB_TEST(u.size() == 15);\n            DLIB_TEST(v.size() == 15);\n\n            for (long i = 0; i < t.size(); ++i)\n            {\n                const long val = t(i);\n                DLIB_TEST(u(i) == val+1);\n                DLIB_TEST(v(i) == val+2);\n            }\n        }\n\n        void another_test()\n        {\n            std::vector<double> a;\n\n            running_stats<double> rs1, rs2;\n\n            for (int i = 0; i < 10; ++i)\n            {\n                rs1.add(i);\n                a.push_back(i);\n            }\n\n            DLIB_TEST(std::abs(variance(mat(a)) - rs1.variance()) < 1e-13);\n            DLIB_TEST(std::abs(stddev(mat(a)) - rs1.stddev()) < 1e-13);\n            DLIB_TEST(std::abs(mean(mat(a)) - rs1.mean()) < 1e-13);\n\n            for (int i = 10; i < 20; ++i)\n            {\n                rs2.add(i);\n                a.push_back(i);\n            }\n\n            DLIB_TEST(std::abs(variance(mat(a)) - (rs1+rs2).variance()) < 1e-13);\n            DLIB_TEST(std::abs(mean(mat(a)) - (rs1+rs2).mean()) < 1e-13);\n            DLIB_TEST((rs1+rs2).current_n() == 20);\n\n            running_scalar_covariance<double> rc1, rc2, rc3;\n            dlib::rand rnd;\n            for (double i = 0; i < 10; ++i)\n            {\n                const double a = i + rnd.get_random_gaussian();\n                const double b = i + rnd.get_random_gaussian();\n                rc1.add(a,b);\n                rc3.add(a,b);\n            }\n            for (double i = 11; i < 20; ++i)\n            {\n                const double a = i + rnd.get_random_gaussian();\n                const double b = i + rnd.get_random_gaussian();\n                rc2.add(a,b);\n                rc3.add(a,b);\n            }\n\n            DLIB_TEST(std::abs((rc1+rc2).mean_x() - rc3.mean_x()) < 1e-13);\n            DLIB_TEST(std::abs((rc1+rc2).mean_y() - rc3.mean_y()) < 1e-13);\n            DLIB_TEST_MSG(std::abs((rc1+rc2).variance_x() - rc3.variance_x()) < 1e-13, std::abs((rc1+rc2).variance_x() - rc3.variance_x()));\n            DLIB_TEST(std::abs((rc1+rc2).variance_y() - rc3.variance_y()) < 1e-13);\n            DLIB_TEST(std::abs((rc1+rc2).covariance() - rc3.covariance()) < 1e-13);\n            DLIB_TEST((rc1+rc2).current_n() == rc3.current_n());\n\n        }\n\n        void test_average_precision()\n        {\n            std::vector<bool> items;\n            DLIB_TEST(average_precision(items) == 1);\n            DLIB_TEST(average_precision(items,1) == 0);\n\n            items.push_back(true);\n            DLIB_TEST(average_precision(items) == 1);\n            DLIB_TEST(std::abs(average_precision(items,1) - 0.5) < 1e-14);\n\n            items.push_back(true);\n            DLIB_TEST(average_precision(items) == 1);\n            DLIB_TEST(std::abs(average_precision(items,1) - 2.0/3.0) < 1e-14);\n\n            items.push_back(false);\n\n            DLIB_TEST(average_precision(items) == 1);\n            DLIB_TEST(std::abs(average_precision(items,1) - 2.0/3.0) < 1e-14);\n\n            items.push_back(true);\n\n            DLIB_TEST(std::abs(average_precision(items) - (2.0+3.0/4.0)/3.0) < 1e-14);\n\n            items.push_back(true);\n\n            DLIB_TEST(std::abs(average_precision(items)   - (2.0 + 4.0/5.0 + 4.0/5.0)/4.0) < 1e-14);\n            DLIB_TEST(std::abs(average_precision(items,1) - (2.0 + 4.0/5.0 + 4.0/5.0)/5.0) < 1e-14);\n        }\n\n\n        template <typename sample_type>\n        void check_distance_metrics (\n            const std::vector<frobmetric_training_sample<sample_type> >& samples\n        )\n        {\n            running_stats<double> rs;\n            for (unsigned long i = 0; i < samples.size(); ++i)\n            {\n                for (unsigned long j = 0; j < samples[i].near_vects.size(); ++j)\n                {\n                    const double d1 = length_squared(samples[i].anchor_vect - samples[i].near_vects[j]);\n                    for (unsigned long k = 0; k < samples[i].far_vects.size(); ++k)\n                    {\n                        const double d2 = length_squared(samples[i].anchor_vect - samples[i].far_vects[k]);\n                        rs.add(d2-d1);\n                    }\n                }\n            }\n\n            dlog << LINFO << \"dist gap max:    \"<< rs.max();\n            dlog << LINFO << \"dist gap min:    \"<< rs.min();\n            dlog << LINFO << \"dist gap mean:   \"<< rs.mean();\n            dlog << LINFO << \"dist gap stddev: \"<< rs.stddev();\n            DLIB_TEST(rs.min() >= 0.99);\n            DLIB_TEST(rs.mean() >= 0.9999);\n        }\n\n        void test_vector_normalizer_frobmetric(dlib::rand& rnd)\n        { \n            print_spinner();\n            typedef matrix<double,0,1> sample_type;\n            vector_normalizer_frobmetric<sample_type> normalizer;\n\n            std::vector<frobmetric_training_sample<sample_type> > samples;\n            frobmetric_training_sample<sample_type> samp;\n\n            const long key = 1;\n            const long dims = 5;\n            // Lets make some two class training data.  Each sample will have dims dimensions but\n            // only the one with index equal to key will be meaningful.  In particular, if the key\n            // dimension is > 0 then the sample is class +1 and -1 otherwise.  \n\n            long k = 0;\n            for (int i = 0; i < 50; ++i)\n            {\n                samp.clear();\n                samp.anchor_vect = gaussian_randm(dims,1,k++);\n                if (samp.anchor_vect(key) > 0)\n                    samp.anchor_vect(key) = rnd.get_random_double() + 5;\n                else\n                    samp.anchor_vect(key) = -(rnd.get_random_double() + 5);\n\n                matrix<double,0,1> temp;\n\n                for (int j = 0; j < 5; ++j)\n                {\n                    // Don't always put an equal number of near_vects and far_vects vectors into the\n                    // training samples.\n                    const int numa = rnd.get_random_32bit_number()%2 + 1;\n                    const int numb = rnd.get_random_32bit_number()%2 + 1;\n\n                    for (int num = 0; num < numa; ++num)\n                    {\n                        temp = gaussian_randm(dims,1,k++); temp(key) = 0.1;\n                        //temp = gaussian_randm(dims,1,k++); temp(key) = std::abs(temp(key));\n                        if (samp.anchor_vect(key) > 0) samp.near_vects.push_back(temp);\n                        else                    samp.far_vects.push_back(temp);\n                    }\n\n                    for (int num = 0; num < numb; ++num)\n                    {\n                        temp = gaussian_randm(dims,1,k++); temp(key) = -0.1;\n                        //temp = gaussian_randm(dims,1,k++); temp(key) = -std::abs(temp(key));\n                        if (samp.anchor_vect(key) < 0) samp.near_vects.push_back(temp);\n                        else                    samp.far_vects.push_back(temp);\n                    }\n                }\n                samples.push_back(samp);\n            }\n\n            normalizer.set_epsilon(0.0001);\n            normalizer.set_c(100);\n            normalizer.set_max_iterations(6000);\n            normalizer.train(samples);\n\n            dlog << LINFO << \"learned transform: \\n\" << normalizer.transform();\n\n            matrix<double,0,1> total;\n\n            for (unsigned long i = 0; i < samples.size(); ++i)\n            {\n                samples[i].anchor_vect = normalizer(samples[i].anchor_vect);\n                total += samples[i].anchor_vect;\n                for (unsigned long j = 0; j < samples[i].near_vects.size(); ++j)\n                    samples[i].near_vects[j] = normalizer(samples[i].near_vects[j]);\n                for (unsigned long j = 0; j < samples[i].far_vects.size(); ++j)\n                    samples[i].far_vects[j] = normalizer(samples[i].far_vects[j]);\n            }\n            total /= samples.size();\n            dlog << LINFO << \"sample transformed means: \"<< trans(total);\n            DLIB_TEST(length(total) < 1e-9);\n            check_distance_metrics(samples);\n\n            // make sure serialization works\n            stringstream os;\n            serialize(normalizer, os);\n            vector_normalizer_frobmetric<sample_type> normalizer2;\n            deserialize(normalizer2, os);\n            DLIB_TEST(equal(normalizer.transform(), normalizer2.transform()));\n            DLIB_TEST(equal(normalizer.transformed_means(), normalizer2.transformed_means()));\n            DLIB_TEST(normalizer.in_vector_size() == normalizer2.in_vector_size());\n            DLIB_TEST(normalizer.out_vector_size() == normalizer2.out_vector_size());\n            DLIB_TEST(normalizer.get_max_iterations() == normalizer2.get_max_iterations());\n            DLIB_TEST(std::abs(normalizer.get_c() - normalizer2.get_c()) < 1e-14);\n            DLIB_TEST(std::abs(normalizer.get_epsilon() - normalizer2.get_epsilon()) < 1e-14);\n\n        }\n\n        void prior_frobnorm_test()\n        {\n            frobmetric_training_sample<matrix<double,0,1> > sample;\n            std::vector<frobmetric_training_sample<matrix<double,0,1> > > samples;\n\n            matrix<double,3,1> x, near_, far_;\n            x    = 0,0,0;\n            near_ = 1,0,0;\n            far_  = 0,1,0;\n\n            sample.anchor_vect = x;\n            sample.near_vects.push_back(near_);\n            sample.far_vects.push_back(far_);\n\n            samples.push_back(sample);\n\n            vector_normalizer_frobmetric<matrix<double,0,1> > trainer;\n            trainer.set_c(100);\n            print_spinner();\n            trainer.train(samples);\n\n            matrix<double,3,3> correct;\n            correct = 0, 0, 0,\n                      0, 1, 0, \n                      0, 0, 0;\n\n            dlog << LDEBUG << trainer.transform();\n            DLIB_TEST(max(abs(trainer.transform()-correct)) < 1e-8);\n\n            trainer.set_uses_identity_matrix_prior(true);\n            print_spinner();\n            trainer.train(samples);\n            correct = 1, 0, 0,\n                      0, 2, 0, \n                      0, 0, 1;\n\n            dlog << LDEBUG << trainer.transform();\n            DLIB_TEST(max(abs(trainer.transform()-correct)) < 1e-8);\n\n        }\n\n        void test_lda ()\n        {\n            // This test makes sure we pick the right direction in a simple 2D -> 1D LDA\n            typedef matrix<double,2,1> sample_type;\n\n            std::vector<unsigned long> labels;\n            std::vector<sample_type> samples;\n            for (int i=0; i<4; i++)\n            {\n                sample_type s;\n                s(0) = i;\n                s(1) = i+1;\n                samples.push_back(s);\n                labels.push_back(1);       \n\n                sample_type s1;\n                s1(0) = i+1;\n                s1(1) = i;\n                samples.push_back(s1);      \n                labels.push_back(2);       \n            }\n\n            matrix<double> X;  \n            X.set_size(8,2);\n            for (int i=0; i<8; i++){\n                X(i,0) = samples[i](0);\n                X(i,1) = samples[i](1);\n            }  \n\n            matrix<double,0,1> mean;   \n\n            dlib::compute_lda_transform(X,mean,labels,1);\n\n            std::vector<double> vals1, vals2;\n            for (unsigned long i = 0; i < samples.size(); ++i)\n            {\n                double val = X*samples[i]-mean;\n                if (i%2 == 0)\n                    vals1.push_back(val);\n                else\n                    vals2.push_back(val);\n                dlog << LINFO << \"1D LDA output: \" << val;\n            }\n\n            if (vals1[0] > vals2[0])\n                swap(vals1, vals2);\n\n            const double err = equal_error_rate(vals1, vals2).first;\n            dlog << LINFO << \"LDA ERR: \" << err;\n            DLIB_TEST(err == 0);\n            DLIB_TEST(equal_error_rate(vals2, vals1).first == 1);\n        }\n\n        void perform_test (\n        )\n        {\n            prior_frobnorm_test();\n            dlib::rand rnd;\n            for (int i = 0; i < 5; ++i)\n                test_vector_normalizer_frobmetric(rnd);\n\n            test_random_subset_selector();\n            test_random_subset_selector2();\n            test_running_covariance();\n            test_running_cross_covariance();\n            test_running_cross_covariance_sparse();\n            test_running_stats();\n            test_skewness_and_kurtosis_1();\n            test_skewness_and_kurtosis_2();\n            test_randomize_samples();\n            test_randomize_samples2();\n            another_test();\n            test_average_precision();\n            test_lda();\n        }\n    } a;\n\n}\n\n\n", "meta": {"hexsha": "ba2cba066dda205263af148fdee1975adb1e7dd2", "size": 29029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib/dlib/test/statistics.cpp", "max_stars_repo_name": "mohitjain4395/mosip", "max_stars_repo_head_hexsha": "20ee978dc539be42c8b79cd4b604fdf681e7b672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 139.0, "max_stars_repo_stars_event_min_datetime": "2018-02-23T14:03:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T12:10:52.000Z", "max_issues_repo_path": "dlib/dlib/test/statistics.cpp", "max_issues_repo_name": "mohitjain4395/mosip", "max_issues_repo_head_hexsha": "20ee978dc539be42c8b79cd4b604fdf681e7b672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2018-03-10T06:11:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-12T07:27:42.000Z", "max_forks_repo_path": "dlib/dlib/test/statistics.cpp", "max_forks_repo_name": "mohitjain4395/mosip", "max_forks_repo_head_hexsha": "20ee978dc539be42c8b79cd4b604fdf681e7b672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 52.0, "max_forks_repo_forks_event_min_datetime": "2018-03-06T11:20:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T12:46:09.000Z", "avg_line_length": 34.8487394958, "max_line_length": 140, "alphanum_fraction": 0.4574735609, "num_tokens": 7463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7853085859124003, "lm_q1q2_score": 0.6228329206837837}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <iostream>\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  int xmin = atoi(argv[1]);\n  int xmax = atoi(argv[2]);\n  int xlen = atoi(argv[3]);\n  int ymin = atoi(argv[4]);\n  int ymax = atoi(argv[5]);\n  int ylen = atoi(argv[6]);\n  int dx = (xmax-xmin)/(xlen-1);\n  int dy = (ymax-ymin)/(ylen-1);    \n   \n  // declare three 3x3 matrices of complex<long double> elements\n  matrix<std::complex<long double> > m(xlen, ylen);\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.size1(); c++) {\n      // enumerated matrix entries\n\n      m(r,c) = (xmin + r*dx) + ((ymin + c * dy) * std::complex<long double>(0,1));\n    }\n  }\n\n  // print to screen as demonstration\n    \n  for (unsigned int i=0; i<xlen; i++) {\n        for (unsigned int j=0; j<ylen; j++) {\n            std::cout << m(i,j) << \"\\t\";\n        }\n        std::cout << std::endl;\n    }\n}\n", "meta": {"hexsha": "a4fd5027082f2a5c8390aceb100d12470ea89f8c", "size": 1136, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/blas/complexP.cc", "max_stars_repo_name": "chapman-cs510-2017f/cw-13-chelseakristasharon", "max_stars_repo_head_hexsha": "605c057eddb91d7ca65f1ddfb620926ce3fe5b09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/blas/complexP.cc", "max_issues_repo_name": "chapman-cs510-2017f/cw-13-chelseakristasharon", "max_issues_repo_head_hexsha": "605c057eddb91d7ca65f1ddfb620926ce3fe5b09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/blas/complexP.cc", "max_forks_repo_name": "chapman-cs510-2017f/cw-13-chelseakristasharon", "max_forks_repo_head_hexsha": "605c057eddb91d7ca65f1ddfb620926ce3fe5b09", "max_forks_repo_licenses": ["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.4186046512, "max_line_length": 82, "alphanum_fraction": 0.5721830986, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.622827425442857}}
{"text": "/* \n * Copyright 2009-2015 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <votca/tools/linalg.h>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_eigen.h>\n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\n\nvoid linalg_invert( ub::matrix<double> &A, ub::matrix<double> &V){\n        // matrix inversion using gsl\n        \n        gsl_error_handler_t *handler = gsl_set_error_handler_off();\n\tconst size_t N = A.size1();\n\t// signum s (for LU decomposition)\n\tint s;\n        //make copy of A as A is destroyed by GSL\n        ub::matrix<double> work=A;\n        V.resize(N, N, false);\n        \n\t// Define all the used matrices\n        gsl_matrix_view A_view = gsl_matrix_view_array(&work(0,0), N, N);\n        gsl_matrix_view V_view = gsl_matrix_view_array(&V(0,0), N, N);\n\tgsl_permutation * perm = gsl_permutation_alloc (N);\n        \n\t// Make LU decomposition of matrix A_view\n\tgsl_linalg_LU_decomp (&A_view.matrix, perm, &s);\n\n\t// Invert the matrix A_view\n\t(void)gsl_linalg_LU_invert (&A_view.matrix, perm, &V_view.matrix);\n\n        gsl_set_error_handler(handler);\n        \n\t// return (status != 0);\n}\n\n}}\n", "meta": {"hexsha": "cd189d6eeb9d2e795e5886607d9cf633df7470a7", "size": 1760, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/linalg/gsl/invert.cc", "max_stars_repo_name": "Pallavi-Banerjee21/votca.tools", "max_stars_repo_head_hexsha": "b6ccf63a744ca890ec75ba96201a0005a905909b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libtools/linalg/gsl/invert.cc", "max_issues_repo_name": "Pallavi-Banerjee21/votca.tools", "max_issues_repo_head_hexsha": "b6ccf63a744ca890ec75ba96201a0005a905909b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libtools/linalg/gsl/invert.cc", "max_forks_repo_name": "Pallavi-Banerjee21/votca.tools", "max_forks_repo_head_hexsha": "b6ccf63a744ca890ec75ba96201a0005a905909b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3448275862, "max_line_length": 75, "alphanum_fraction": 0.6914772727, "num_tokens": 453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6228274149548301}}
{"text": "#include <iostream>\n#include <utility>\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n\nusing namespace std;\nusing namespace boost;\ntypedef adjacency_list<listS, vecS, directedS, no_property, property<edge_weight_t, int>> Graph;\ntypedef Graph::vertex_descriptor Vertex;\ntypedef pair<int, int> Edge;\n\nint main(int argc, char* argv[])\n{\n  enum { A, B, C, D, E, N };\n  const int num_vertices = N;\n  Edge edge_array[] = { Edge(A,B), Edge(A,D), Edge(C,A), Edge(D,C), Edge(C,E), Edge(B,D), Edge(D,E) };\n  const int num_edges = sizeof(edge_array)/sizeof(Edge);\n  int weights[] = { 1, 2, 1, 2, 7, 3, 1};\n  Graph g(edge_array, edge_array + num_vertices, weights, num_vertices);\n  cout << \"edges(g) = \";\n  Graph::edge_iterator EdgeI, EdgeLast;\n  for (tie(EdgeI, EdgeLast) = edges(g); EdgeI != EdgeLast; ++EdgeI)\n    cout << \"(\" << source(*EdgeI, g) << \",\" << target(*EdgeI, g) << \") \";\n  cout << endl;\n  vector<int> distances(num_vertices);\n  Vertex start = *(vertices(g).first);\n  dijkstra_shortest_paths(g, start, distance_map(&distances[0]));\n  cout << \"distances from start vertex:\" << endl;\n  Graph::vertex_iterator VertexI, VertexLast;\n  \n  for(tie(VertexI, VertexLast) = vertices(g); VertexI != VertexLast; ++VertexI)\n    cout << \"distance(\" << *VertexI << \") = \" << distances[*VertexI] << endl;\n  cout << endl;\n  return 0;\n}\n", "meta": {"hexsha": "4592cc7750a2bc38dc7ad84511db20eddc46d834", "size": 1386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "practice/graph4.cpp", "max_stars_repo_name": "ShiZhan/graph-study", "max_stars_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-03-14T07:27:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-15T03:11:31.000Z", "max_issues_repo_path": "practice/graph4.cpp", "max_issues_repo_name": "Zhan2012/graph-study", "max_issues_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practice/graph4.cpp", "max_forks_repo_name": "Zhan2012/graph-study", "max_forks_repo_head_hexsha": "a983bdad09397b07885f75509baeefd5b9b7464f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4594594595, "max_line_length": 102, "alphanum_fraction": 0.6645021645, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6228274094588139}}
{"text": "#include <igl/boundary_facets.h>\r\n#include <igl/colon.h>\r\n#include <igl/cotmatrix.h>\r\n#include <igl/jet.h>\r\n#include <igl/min_quad_with_fixed.h>\r\n#include <igl/readOFF.h>\r\n#include <igl/setdiff.h>\r\n#include <igl/slice.h>\r\n#include <igl/slice_into.h>\r\n#include <igl/unique.h>\r\n#include <igl/opengl/glfw/Viewer.h>\r\n#include <Eigen/Sparse>\r\n#include <iostream>\r\n#include \"tutorial_shared_path.h\"\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n  using namespace Eigen;\r\n  using namespace std;\r\n  MatrixXd V;\r\n  MatrixXi F;\r\n  igl::readOFF(TUTORIAL_SHARED_PATH \"/camelhead.off\",V,F);\r\n  // Find boundary edges\r\n  MatrixXi E;\r\n  igl::boundary_facets(F,E);\r\n  // Find boundary vertices\r\n  VectorXi b,IA,IC;\r\n  igl::unique(E,b,IA,IC);\r\n  // List of all vertex indices\r\n  VectorXi all,in;\r\n  igl::colon<int>(0,V.rows()-1,all);\r\n  // List of interior indices\r\n  igl::setdiff(all,b,in,IA);\r\n\r\n  // Construct and slice up Laplacian\r\n  SparseMatrix<double> L,L_in_in,L_in_b;\r\n  igl::cotmatrix(V,F,L);\r\n  igl::slice(L,in,in,L_in_in);\r\n  igl::slice(L,in,b,L_in_b);\r\n\r\n  // Dirichlet boundary conditions from z-coordinate\r\n  VectorXd bc;\r\n  VectorXd Z = V.col(2);\r\n  igl::slice(Z,b,bc);\r\n\r\n  // Solve PDE\r\n  SimplicialLLT<SparseMatrix<double > > solver(-L_in_in);\r\n  VectorXd Z_in = solver.solve(L_in_b*bc);\r\n  // slice into solution\r\n  igl::slice_into(Z_in,in,Z);\r\n\r\n  // Alternative, short hand\r\n  igl::min_quad_with_fixed_data<double> mqwf;\r\n  // Linear term is 0\r\n  VectorXd B = VectorXd::Zero(V.rows(),1);\r\n  // Empty constraints\r\n  VectorXd Beq;\r\n  SparseMatrix<double> Aeq;\r\n  // Our cotmatrix is _negative_ definite, so flip sign\r\n  igl::min_quad_with_fixed_precompute((-L).eval(),b,Aeq,true,mqwf);\r\n  igl::min_quad_with_fixed_solve(mqwf,B,bc,Beq,Z);\r\n\r\n  // Pseudo-color based on solution\r\n  MatrixXd C;\r\n  igl::jet(Z,true,C);\r\n\r\n  // Plot the mesh with pseudocolors\r\n  igl::opengl::glfw::Viewer viewer;\r\n  viewer.data().set_mesh(V, F);\r\n  viewer.data().show_lines = false;\r\n  viewer.data().set_colors(C);\r\n  viewer.launch();\r\n}\r\n", "meta": {"hexsha": "3a7aa1614cb24538ca001b1feb68d22a56c01231", "size": 2016, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdf-net/lib/submodules/libigl/tutorial/303_LaplaceEquation/main.cpp", "max_stars_repo_name": "hardikk13/nglod", "max_stars_repo_head_hexsha": "6c6c66ce1b39c5a3515cafc290ec903ae90b506e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/tutorial/303_LaplaceEquation/main.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/tutorial/303_LaplaceEquation/main.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 27.2432432432, "max_line_length": 68, "alphanum_fraction": 0.6731150794, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6228273984667807}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/random/mersenne_twister.hpp>\n#include <math/prim/scal/prob/util.hpp>\n#include <vector>\n\nTEST(ProbDistributionsBernoulliLogit, error_check) {\n  boost::random::mt19937 rng;\n\n  EXPECT_NO_THROW(stan::math::bernoulli_logit_rng(-3.5, rng));\n  EXPECT_THROW(\n      stan::math::bernoulli_logit_rng(stan::math::positive_infinity(), rng),\n      std::domain_error);\n}\n\nTEST(ProbDistributionsBernoulliLogit, logitChiSquareGoodnessFitTest) {\n  boost::random::mt19937 rng;\n  // number of samples\n  int N = 10000;\n\n  // logit-transformed probability\n  double parameter = -0.5;\n  // actual probability\n  double prob = stan::math::inv_logit(-0.5);\n\n  std::vector<double> expected;\n  expected.push_back(N * (1 - prob));\n  expected.push_back(N * prob);\n\n  std::vector<int> counts(2);\n  for (int i = 0; i < N; ++i) {\n    ++counts[stan::math::bernoulli_logit_rng(parameter, rng)];\n  }\n\n  assert_chi_squared(counts, expected, 1e-6);\n}\n", "meta": {"hexsha": "b844cb61547ec50594dc6d25e4e9f6f0fb8f40d2", "size": 988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/scal/prob/bernoulli_logit_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/prim/scal/prob/bernoulli_logit_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/prim/scal/prob/bernoulli_logit_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7027027027, "max_line_length": 76, "alphanum_fraction": 0.705465587, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6228273884827593}}
{"text": "#ifndef COORDINATE_CALCULATION\n#define COORDINATE_CALCULATION\n\n#include \"util/coordinate.hpp\"\n\n#include <boost/optional.hpp>\n\n#include <utility>\n\nnamespace osrm\n{\nnamespace util\n{\nnamespace coordinate_calculation\n{\n\nnamespace detail\n{\nconst constexpr long double DEGREE_TO_RAD = 0.017453292519943295769236907684886;\nconst constexpr long double RAD_TO_DEGREE = 1. / DEGREE_TO_RAD;\n// earth radius varies between 6,356.750-6,378.135 km (3,949.901-3,963.189mi)\n// The IUGG value for the equatorial radius is 6378.137 km (3963.19 miles)\nconst constexpr long double EARTH_RADIUS = 6372797.560856;\n}\n\n//! Takes the squared euclidean distance of the input coordinates. Does not return meters!\nstd::uint64_t squaredEuclideanDistance(const Coordinate lhs, const Coordinate rhs);\n\ndouble haversineDistance(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\ndouble greatCircleDistance(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\ninline std::pair<double, FloatCoordinate> projectPointOnSegment(const FloatCoordinate &source,\n                                                                const FloatCoordinate &target,\n                                                                const FloatCoordinate &coordinate)\n{\n    const FloatCoordinate slope_vector{target.lon - source.lon, target.lat - source.lat};\n    const FloatCoordinate rel_coordinate{coordinate.lon - source.lon, coordinate.lat - source.lat};\n    // dot product of two un-normed vectors\n    const auto unnormed_ratio = static_cast<double>(slope_vector.lon * rel_coordinate.lon) +\n                                static_cast<double>(slope_vector.lat * rel_coordinate.lat);\n    // squared length of the slope vector\n    const auto squared_length = static_cast<double>(slope_vector.lon * slope_vector.lon) +\n                                static_cast<double>(slope_vector.lat * slope_vector.lat);\n\n    if (squared_length < std::numeric_limits<double>::epsilon())\n    {\n        return {0, source};\n    }\n\n    const double normed_ratio = unnormed_ratio / squared_length;\n    double clamped_ratio = normed_ratio;\n    if (clamped_ratio > 1.)\n    {\n        clamped_ratio = 1.;\n    }\n    else if (clamped_ratio < 0.)\n    {\n        clamped_ratio = 0.;\n    }\n\n    return {clamped_ratio,\n            {\n                FloatLongitude(1.0 - clamped_ratio) * source.lon +\n                    target.lon * FloatLongitude(clamped_ratio),\n                FloatLatitude(1.0 - clamped_ratio) * source.lat +\n                    target.lat * FloatLatitude(clamped_ratio),\n            }};\n}\n\ndouble perpendicularDistance(const Coordinate segment_source,\n                             const Coordinate segment_target,\n                             const Coordinate query_location);\n\ndouble perpendicularDistance(const Coordinate segment_source,\n                             const Coordinate segment_target,\n                             const Coordinate query_location,\n                             Coordinate &nearest_location,\n                             double &ratio);\n\nCoordinate centroid(const Coordinate lhs, const Coordinate rhs);\n\ndouble bearing(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\n// Get angle of line segment (A,C)->(C,B)\ndouble computeAngle(const Coordinate first, const Coordinate second, const Coordinate third);\n\n// find the center of a circle through three coordinates\nboost::optional<Coordinate> circleCenter(const Coordinate first_coordinate,\n                                         const Coordinate second_coordinate,\n                                         const Coordinate third_coordinate);\n\n// find the radius of a circle through three coordinates\ndouble circleRadius(const Coordinate first_coordinate,\n                    const Coordinate second_coordinate,\n                    const Coordinate third_coordinate);\n\n// factor in [0,1]. Returns point along the straight line between from and to. 0 returns from, 1\n// returns to\nCoordinate interpolateLinear(double factor, const Coordinate from, const Coordinate to);\n\n} // ns coordinate_calculation\n} // ns util\n} // ns osrm\n\n#endif // COORDINATE_CALCULATION\n", "meta": {"hexsha": "9edc5bdeefb933cea7b5dc1c18b7a2b4c20d45c5", "size": 4152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/util/coordinate_calculation.hpp", "max_stars_repo_name": "megatontech/osrm-backend", "max_stars_repo_head_hexsha": "cb834ccefcb9e3b81d9577565ddce9569f7bfe82", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/util/coordinate_calculation.hpp", "max_issues_repo_name": "megatontech/osrm-backend", "max_issues_repo_head_hexsha": "cb834ccefcb9e3b81d9577565ddce9569f7bfe82", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/util/coordinate_calculation.hpp", "max_forks_repo_name": "megatontech/osrm-backend", "max_forks_repo_head_hexsha": "cb834ccefcb9e3b81d9577565ddce9569f7bfe82", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8037383178, "max_line_length": 99, "alphanum_fraction": 0.6712427746, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.6228049499525533}}
{"text": "//\n// Created by Amir Masoud Abdol on 2020-04-11\n//\n\n#include \"TestStrategy.h\"\n\n#include <boost/math/distributions/students_t.hpp>\n\nusing namespace sam;\nusing boost::math::students_t;\n\nvoid TTest::run(Experiment *experiment) {\n\n  static ResultType res{};\n\n  // The first group is always the control group\n  for (int i{experiment->setup.nd()}, d{0}; i < experiment->setup.ng();\n       ++i, ++d %= experiment->setup.nd()) {\n\n    if (params.var_equal) {\n      res = two_samples_t_test_equal_sd((*experiment)[d].mean_, (*experiment)[d].stddev_,\n                                        (*experiment)[d].nobs_, (*experiment)[i].mean_,\n                                        (*experiment)[i].stddev_, (*experiment)[i].nobs_,\n                                        params.alpha, params.alternative);\n    } else {\n      res = two_samples_t_test_unequal_sd((*experiment)[d].mean_, (*experiment)[d].stddev_,\n                                          (*experiment)[d].nobs_, (*experiment)[i].mean_,\n                                          (*experiment)[i].stddev_, (*experiment)[i].nobs_,\n                                          params.alpha,\n                                          params.alternative);\n    }\n\n    (*experiment)[i].stats_ = res.tstat;\n    (*experiment)[i].pvalue_ = res.pvalue;\n    (*experiment)[i].sig_ = res.sig;\n  }\n}\n\nTTest::ResultType TTest::t_test(const arma::Row<float> &dt1,\n                                const arma::Row<float> &dt2, float alpha,\n                                TestStrategy::TestAlternative alternative) {\n  return t_test(arma::mean(dt1), arma::stddev(dt1), dt1.size(), arma::mean(dt2),\n                arma::stddev(dt2), dt2.size(), alpha, alternative, true);\n}\n\nTTest::ResultType TTest::t_test(float Sm1, float Sd1, float Sn1, float Sm2,\n                                float Sd2, float Sn2, float alpha,\n                                TestStrategy::TestAlternative alternative,\n                                bool equal_var = false) {\n\n  if (Sm1 == 0.) {\n    return single_sample_t_test(Sm1, Sm2, Sd2, Sn2, alpha, alternative);\n  }\n\n  if (equal_var) {\n    return two_samples_t_test_equal_sd(Sm1, Sd1, Sn1, Sm2, Sd2, Sn2, alpha,\n                                       alternative);\n  } else {\n    return two_samples_t_test_unequal_sd(Sm1, Sd1, Sn1, Sm2, Sd2, Sn2, alpha,\n                                         alternative);\n  }\n}\n\nstd::pair<float, bool>\nTTest::compute_pvalue(float t_stat, float df, float alpha, TestStrategy::TestAlternative alternative) {\n  \n  using boost::math::students_t;\n  students_t dist(df);\n  \n  double p{0};\n  bool sig{false};\n  \n  if (alternative == TestStrategy::TestAlternative::TwoSided) {\n    // Mean != M\n    p = 2. * cdf(complement(dist, fabs(t_stat)));\n    if (p < alpha) { // Alternative \"NOT REJECTED\"\n      sig = true;\n    } else { // Alternative \"REJECTED\"\n      sig = false;\n    }\n  }\n  \n  if (alternative == TestStrategy::TestAlternative::Greater) {\n    // Mean  > M\n    p = cdf(dist, t_stat);\n    if (p > alpha) { // Alternative \"NOT REJECTED\"\n      sig = true;\n    } else { // Alternative \"REJECTED\"\n      sig = false;\n    }\n  }\n  \n  if (alternative == TestStrategy::TestAlternative::Less) {\n    // Mean  < M\n    p = cdf(complement(dist, t_stat));\n    if (p > alpha) { // Alternative \"NOT REJECTED\"\n      sig = true;\n    } else { // Alternative \"REJECTED\"\n      sig = false;\n    }\n  }\n  \n  return std::make_pair(p, sig);\n}\n\n///\n/// A Students t test applied to a single set of data. We are testing the null\n/// hypothesis that the true mean of the sample is M, and that any variation is\n/// down to chance.  We can also test the alternative hypothesis that any\n/// difference is not down to chance\n///\n/// @note       Obtained from [Boost Library\n///             Example](https://www.boost.org/doc/libs/1_69_0/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/paired_st.html).\n///\n/// @param      M      True Mean.\n/// @param      Sm     Sample Mean.\n/// @param      Sd     Sample Standard Deviation.\n/// @param      Sn     Sample Size.\n/// @param      alpha  Significance Level.\n/// @return     TTest::ResultType\n///\nTTest::ResultType\nTTest::single_sample_t_test(float M, float Sm, float Sd, unsigned Sn,\n                            float alpha,\n                            TestStrategy::TestAlternative alternative) {\n\n  bool sig = false;\n\n  // Difference in means:\n  float diff = Sm - M;\n\n  // Degrees of freedom:\n  float df = Sn - 1;\n\n  // t-statistic:\n  float t_stat = diff * sqrt(float(Sn)) / Sd;\n\n  //\n  // Finally define our distribution, and get the probability:\n  //\n  students_t dist(df);\n  float p = 0;\n\n  //\n  // Finally print out results of alternative hypothesis:\n  //\n\n  if (alternative == TestStrategy::TestAlternative::TwoSided) {\n    // Mean != M\n    p = 2 * cdf(complement(dist, fabs(t_stat)));\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Greater) {\n    // Mean  > M\n    p = cdf(dist, t_stat);\n    if (p > alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Less) {\n    // Mean  < M\n    p = cdf(complement(dist, t_stat));\n    if (p > alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  return {.tstat = t_stat, .df = df, .pvalue = p, .sig = sig};\n}\n\n///\n/// A Students t test applied to two sets of data. We are testing the null\n/// hypothesis that the two samples have the same mean and that any difference\n/// if due to chance.\n///\n/// @note       Obtained from [Boost Library\n///             Example](https://www.boost.org/doc/libs/1_69_0/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/paired_st.html).\n///\n/// @param      Sm1    Sample Mean 1.\n/// @param      Sd1    Sample Standard Deviation 1.\n/// @param      Sn1    Sample Size 1.\n/// @param      Sm2    Sample Mean 2.\n/// @param      Sd2    Sample Standard Deviation 2.\n/// @param      Sn2    Sample Size 2.\n/// @param      alpha  Significance Level.\n/// @return     TTest::ResultType\n///\nTTest::ResultType TTest::two_samples_t_test_equal_sd(\n    float Sm1, float Sd1, unsigned Sn1, float Sm2, float Sd2, unsigned Sn2,\n    float alpha, TestStrategy::TestAlternative alternative) {\n\n  bool sig = false;\n\n  // Degrees of freedom:\n  float df = Sn1 + Sn2 - 2;\n\n  // Pooled variance and hence standard deviation:\n  float sp = sqrt(((Sn1 - 1) * Sd1 * Sd1 + (Sn2 - 1) * Sd2 * Sd2) / df);\n\n  // NOTE: I had to do this, I don't want my simulations fail.\n  // While this is not perfect, it allows me to handle an edge case\n  // SAM should not throw and should continue working.\n  if (!(isgreater(sp, 0) or isless(sp, 0))) {\n    // Samples are almost equal and elements are constant\n    sp += std::numeric_limits<float>::epsilon();\n  }\n\n  // t-statistic:\n  float t_stat = (Sm1 - Sm2) / (sp * sqrt(1.0 / Sn1 + 1.0 / Sn2));\n\n  //\n  // Define our distribution, and get the probability:\n  //\n  students_t dist(df);\n  float p = 0;\n\n  //\n  // Finally print out results of alternative hypothesis:\n  //\n\n  if (alternative == TestStrategy::TestAlternative::TwoSided) {\n    // Sample 1 Mean != Sample 2 Mean\n    p = 2 * cdf(complement(dist, fabs(t_stat)));\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Greater) {\n    // Sample 1 Mean <  Sample 2 Mean\n    p = cdf(dist, t_stat);\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Less) {\n\n    // Sample 1 Mean >  Sample 2 Mean\n    p = cdf(complement(dist, t_stat));\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else\n      sig = false; // Alternative \"REJECTED\"\n  }\n\n  return {.tstat = t_stat, .df = df, .pvalue = p, .sig = sig};\n}\n\n///\n/// A Students t test applied to two sets of data with _unequal_ variance. We\n/// are testing the null hypothesis that the two samples have the same mean and\n/// that any difference is due to chance.\n///\n/// @note       Obtained from [Boost Library\n///             Example](https://www.boost.org/doc/libs/1_69_0/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/paired_st.html).\n///\n/// @param      Sm1    Sample Mean 1.\n/// @param      Sd1    Sample Standard Deviation 1.\n/// @param      Sn1    Sample Size 1.\n/// @param      Sm2    Sample Mean 2.\n/// @param      Sd2    Sample Standard Deviation 2.\n/// @param      Sn2    Sample Size 2.\n/// @param      alpha  Significance Level.\n/// @return     TTest::ResultType\n///\nTTest::ResultType TTest::two_samples_t_test_unequal_sd(\n    float Sm1, float Sd1, unsigned Sn1, float Sm2, float Sd2, unsigned Sn2,\n    float alpha, TestStrategy::TestAlternative alternative) {\n\n  bool sig = false;\n\n  // Degrees of freedom:\n  float df = Sd1 * Sd1 / Sn1 + Sd2 * Sd2 / Sn2;\n  df *= df;\n  float t1 = Sd1 * Sd1 / Sn1;\n  t1 *= t1;\n  t1 /= (Sn1 - 1);\n  float t2 = Sd2 * Sd2 / Sn2;\n  t2 *= t2;\n  t2 /= (Sn2 - 1);\n  df /= (t1 + t2);\n\n  // t-statistic:\n  float t_stat = (Sm1 - Sm2) / sqrt(Sd1 * Sd1 / Sn1 + Sd2 * Sd2 / Sn2);\n\n  //\n  // Define our distribution, and get the probability:\n  //\n  students_t dist(df);\n  float p = 0;\n\n  //\n  // Finally print out results of alternative hypothesis:\n  //\n\n  if (alternative == TestStrategy::TestAlternative::TwoSided) {\n    // Sample 1 Mean != Sample 2 Mean\n    p = 2 * cdf(complement(dist, fabs(t_stat)));\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Greater) {\n    // Sample 1 Mean <  Sample 2 Mean\n    p = cdf(dist, t_stat);\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else // Alternative \"REJECTED\"\n      sig = false;\n  }\n\n  if (alternative == TestStrategy::TestAlternative::Less) {\n    // Sample 1 Mean >  Sample 2 Mean\n    p = cdf(complement(dist, t_stat));\n    if (p < alpha) // Alternative \"NOT REJECTED\"\n      sig = true;\n    else\n      sig = false; // Alternative \"REJECTED\"\n  }\n\n  return {.tstat = t_stat, .df = df, .pvalue = p, .sig = sig};\n}\n", "meta": {"hexsha": "d25398244cf751eae240ed33d7709bf22011fe90", "size": 10322, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TSTTest.cpp", "max_stars_repo_name": "amirmasoudabdol/SAM", "max_stars_repo_head_hexsha": "7f3f520d1bfeef71c682e6dd6bd9f2278d7cfd9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-25T20:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:21:41.000Z", "max_issues_repo_path": "src/TSTTest.cpp", "max_issues_repo_name": "amirmasoudabdol/SAM", "max_issues_repo_head_hexsha": "7f3f520d1bfeef71c682e6dd6bd9f2278d7cfd9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TSTTest.cpp", "max_forks_repo_name": "amirmasoudabdol/SAM", "max_forks_repo_head_hexsha": "7f3f520d1bfeef71c682e6dd6bd9f2278d7cfd9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8119402985, "max_line_length": 130, "alphanum_fraction": 0.5907769812, "num_tokens": 2844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.622804375193325}}
{"text": "#include \"functions/division.hh\"\n#include <boost/test/unit_test.hpp>\n#include \"functions/full_function_defs.hh\"\n#include \"functions/operators.hh\"\n#include \"functions/std_functions.hh\"\n#include \"pointwise_equal.hh\"\n\nBOOST_AUTO_TEST_CASE(reciprocal_test) {\n  using namespace manifolds;\n\n  Division<Sin, Cos> t;\n  BOOST_CHECK_EQUAL(t(2), std::sin(2) / std::cos(2));\n  auto d1 = Sin()(x) / Log()(x);\n  auto d2 = Pow()(x, y) / Tan()(x);\n  auto m12 = MultiplyRaw(d1, d2);\n  static_assert(Simplifies<decltype(m12)>::value, \"\");\n  auto m12s = Simplify(m12);\n  PointwiseEqual(m12, m12s, pointwise_default_num_points, 1E-11, 0.1, 20);\n  auto d12 = DivideRaw(d1, d2);\n  static_assert(Simplifies<decltype(d12)>::value, \"\");\n  auto d12s = Simplify(d12);\n  PointwiseEqual(d12s, d12, pointwise_default_num_points, 1E-11, 0.001, 20);\n}\n", "meta": {"hexsha": "70d73b2f085627696dfcd5615edfbc3c4c42631a", "size": 820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_division.cpp", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/tests/test_division.cpp", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/tests/test_division.cpp", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["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.1666666667, "max_line_length": 76, "alphanum_fraction": 0.7085365854, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.6227692327294154}}
{"text": "// ========================================================================== //\n// Copyright (c) 2014-2019 The University of Texas at Austin.                 //\n// All rights reserved.                                                       //\n//                                                                            //\n// Licensed under the Apache License, Version 2.0 (the \"License\");            //\n// you may not use this file except in compliance with the License.           //\n// A copy of the License is included with this software in the file LICENSE.  //\n// If your copy does not contain the License, you may obtain a copy of the    //\n// License at:                                                                //\n//                                                                            //\n//     https://www.apache.org/licenses/LICENSE-2.0                            //\n//                                                                            //\n// Unless required by applicable law or agreed to in writing, software        //\n// distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT  //\n// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.           //\n// See the License for the specific language governing permissions and        //\n// limitations under the License.                                             //\n//                                                                            //\n// ========================================================================== //\n\n#pragma once\n\n#include <iostream>\n#include \"dtypes.h\" \n\n#include <boost/math/quaternion.hpp>\n#include <cmath>\n\ntypedef boost::math::quaternion<double> quaternion;\n\nnamespace gxy\n{\n\nclass Q\n{\npublic:\n\tQ() { zero(); }\n\tQ(quaternion q) : q(q) {}\n\tQ(vec3f axis) { q = quaternion(0.0, axis.x, axis.y, axis.z); }\n\tQ(vec3f u, float r) { q =  quaternion(cos(r/2), sin(r/2)*u.x, sin(r/2)*u.y, sin(r/2)*u.z); }\n\n\t~Q() {}\n\n\tQ operator*(const Q& q) const\n\t{\n\t\treturn Q(this->q * q.q);\n\t}\n\n\tvoid print(std::ostream& o)\n\t{\n\t}\n\n\tvec3f rotate(vec3f v)\n\t{\n\t\tquaternion qr = this->q * quaternion(0.0, v.x, v.y, v.z) * conj(this->q);\n\t\treturn vec3f( qr.R_component_2(), qr.R_component_3(),qr.R_component_4());\n\t}\n\n\tvoid zero() { q = quaternion(1.0, 0.0, 0.0, 0.0); }\n\n\tquaternion get() { return q; }\n\nprivate:\n\tquaternion q;\n};\n\nclass Trackball\n{\npublic:\n\tTrackball(float s = 1) : size(s) {}\n\t~Trackball() {}\n\n\tvoid spin(float p1x, float p1y, float p2x, float p2y)\n\t{\n    vec3f axis;      /* Axis of rotation */\n    float phi;       /* how much to rotate about axis */\n    vec3f p1, p2, d;\n    float t;\n\n    if (p1x == p2x && p1y == p2y)\n\t\t\treturn;\n\n    /*\n     * First, figure out z-coordinates for projection of P1 and P2 to\n     * deformed sphere\n     */\n    p1 = vec3f(p1x, p1y, project_to_sphere(size,p1x,p1y));\n    p2 = vec3f(p2x, p2y, project_to_sphere(size,p2x,p2y));\n\n    /*\n     *  Now, we want the cross product of P1 and P2\n     */\n    cross(p2,p1,axis);\n    normalize(axis);\n\n    /*\n     *  Figure out how much to rotate around that axis.\n     */\n    sub(p1,p2,d);\n    t = len(d) / (2.0*size);\n\n    /*\n     * Avoid problems with out-of-control values...\n     */\n    if (t > 1.0) t = 1.0;\n    if (t < -1.0) t = -1.0;\n    phi = 2.0 * asin(t);\n\n\t\tcurrent = current * Q(axis, phi);\n\n\t\treturn;\n\t}\n\n\tvec3f rotate_vector(vec3f v)\n\t{\n\t\tquaternion qr = current.get() * quaternion(0.0, v.x, v.y, v.z) * conj(current.get());\n\t\treturn vec3f( qr.R_component_2(), qr.R_component_3(),qr.R_component_4());\n\t}\n\n\tQ get() { return current; }\n\n\tvoid reset() { current.zero(); }\n\nprivate:\n\tQ current;\n\tfloat size;\n\n\tfloat project_to_sphere(float r, float x, float y)\n\t{\n    float d, t, z;\n\n    d = sqrt(x*x + y*y);\n    if (d < r * 0.70710678118654752440)\n        z = sqrt(r*r - d*d);\n    else\n\t\t{\n        t = r / 1.41421356237309504880;\n        z = t*t / d;\n    }\n    return z;\n\t}\n};\n\n}\n", "meta": {"hexsha": "13249f4bde5493a4b4d96e2f69936f76feac0681", "size": 3900, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/multiserver/trackball.hpp", "max_stars_repo_name": "BruceCherniak/Galaxy", "max_stars_repo_head_hexsha": "239cdd6ae060916ea8c1ba225e386095b785a702", "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/multiserver/trackball.hpp", "max_issues_repo_name": "BruceCherniak/Galaxy", "max_issues_repo_head_hexsha": "239cdd6ae060916ea8c1ba225e386095b785a702", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multiserver/trackball.hpp", "max_forks_repo_name": "BruceCherniak/Galaxy", "max_forks_repo_head_hexsha": "239cdd6ae060916ea8c1ba225e386095b785a702", "max_forks_repo_licenses": ["Apache-2.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.8965517241, "max_line_length": 93, "alphanum_fraction": 0.4917948718, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.6227692308571114}}
{"text": "#include <cmath>\n#include <boost/test/unit_test.hpp>\n#include \"Werk/Math/ContinuousEma.hpp\"\n\nBOOST_AUTO_TEST_SUITE(ContinuousEmaTest)\n\nBOOST_AUTO_TEST_CASE(testEmpty) {\n\n\tWerk::ContinuousEma ema(10.0);\n\tBOOST_CHECK_EQUAL(ema.halfLife(), 10.0);\n\tBOOST_CHECK(ema.factor() < 1.0/10.0);\n\tBOOST_CHECK(std::isnan(ema.value()));\n}\n\nBOOST_AUTO_TEST_CASE(testConstant) {\n\n\tWerk::ContinuousEma ema(10.0);\n\tBOOST_CHECK(std::isnan(ema.value()));\n\tema.sample(0.0, 10.0);\n\tBOOST_CHECK_EQUAL(ema.value(), 10.0);\n\tema.sample(4.0, 10.0);\n\tBOOST_CHECK_EQUAL(ema.value(), 10.0);\n\tema.sample(17.0, 10.0);\n\tBOOST_CHECK_EQUAL(ema.value(), 10.0);\n}\n\n\nBOOST_AUTO_TEST_CASE(testDecreasing)\n{\n\tWerk::ContinuousEma ema(60.0);\n\n\tBOOST_CHECK(std::isnan(ema.value()));\n\tema.sample(0.0, 10.0);\n\n\tBOOST_CHECK_EQUAL(ema.value(), 10.0);\n\tema.sample(13.0, 0.0);\n\tBOOST_CHECK(ema.value() < 10.0);\n\n\tdouble value = ema.value();\n\tema.sample(19.0, 0.0);\n\tBOOST_CHECK(ema.value() < value);\n}\n\nBOOST_AUTO_TEST_CASE(testIncreasing)\n{\n\tWerk::ContinuousEma ema(60.0);\n\n\tBOOST_CHECK(std::isnan(ema.value()));\n\tema.sample(0.0, 10.0);\n\tBOOST_CHECK_EQUAL(ema.value(), 10.0);\n\tema.sample(7.0, 13.0);\n\tBOOST_CHECK(ema.value() > 10);\n\n\tdouble value = ema.value();\n\tema.sample(19.0, 20.0);\n\tBOOST_CHECK(ema.value() > value);\n}\n\nBOOST_AUTO_TEST_CASE(testOscillating)\n{\n\tWerk::ContinuousEma ema(10.0);\n\n\tBOOST_CHECK(std::isnan(ema.value()));\n\tema.sample(0.0, 10.0);\n\tBOOST_CHECK_EQUAL(ema.value(), 10.0);\n\tema.sample(10.0, 0.0);\n\tBOOST_CHECK_CLOSE(ema.value(), 5.0, 0.5);\n\tema.sample(20.0, 10.0);\n\tBOOST_CHECK_CLOSE(ema.value(), 7.5, 0.5);\n\tema.sample(30.0, 0.0);\n\tBOOST_CHECK_CLOSE(ema.value(), 3.75, 0.5);\n}\n\nBOOST_AUTO_TEST_CASE(testNan)\n{\n\tWerk::ContinuousEma ema(60.0);\n\n\tBOOST_CHECK(std::isnan(ema.value()));\n\tema.sample(0.0, 10.0);\n\tBOOST_CHECK_EQUAL(ema.value(), 10.0);\n\tema.sample(3.0, std::numeric_limits<double>::quiet_NaN());\n\tBOOST_CHECK(std::isnan(ema.value()));\n\tema.sample(5.0, 10.0);\n\tBOOST_CHECK_EQUAL(ema.value(), 10.0);\n}\n\nBOOST_AUTO_TEST_CASE(testInfiniteHalfLife)\n{\n\tWerk::ContinuousEma ema(std::numeric_limits<double>::infinity());\n\n\tBOOST_CHECK(std::isnan(ema.value()));\n\tema.sample(0.0, 10.0);\n\tBOOST_CHECK_EQUAL(ema.value(), 10.0);\n\tema.sample(3.0, 15.0);\n\tBOOST_CHECK_EQUAL(ema.value(), 10.0);\n\tema.sample(15.0, 2310.0);\n\tBOOST_CHECK_EQUAL(ema.value(), 10.0);\n}\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "f667fee2d0ca27839510a399fb60c7ffc44f40b8", "size": 2363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/WerkTest/Math/ContinuousEma.cpp", "max_stars_repo_name": "mish24/werk", "max_stars_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/WerkTest/Math/ContinuousEma.cpp", "max_issues_repo_name": "mish24/werk", "max_issues_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WerkTest/Math/ContinuousEma.cpp", "max_forks_repo_name": "mish24/werk", "max_forks_repo_head_hexsha": "2f8822842fb8f68a4402775d1d3b41021b5a9945", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.63, "max_line_length": 66, "alphanum_fraction": 0.6991112992, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6227692156157496}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_HYPOT_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_HYPOT_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/scal/fun/square.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the length of the hypoteneuse of a right triangle with\n * opposite and adjacent side lengths given by the specified\n * arguments (C++11).  In symbols, if the arguments are\n * <code>x</code> and <code>y</code>, the result is <code>sqrt(x *\n * x + y * y)</code>.\n *\n * @param x First argument.\n * @param y Second argument.\n * @return Length of hypoteneuse of right triangle with opposite\n * and adjacent side lengths x and y.\n */\ntemplate <typename T1, typename T2>\ninline return_type_t<T1, T2> hypot(const T1& x, const T2& y) {\n  using std::sqrt;\n  return sqrt(square(x) + square(y));\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "110a9d03d2ebd62fb0792bfc1ebca0ba3a46154e", "size": 911, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/math/prim/scal/fun/hypot.hpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "src/stan/math/prim/scal/fun/hypot.hpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "src/stan/math/prim/scal/fun/hypot.hpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6060606061, "max_line_length": 66, "alphanum_fraction": 0.7167947311, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.6227692043819255}}
{"text": "/**\n * \\Description:\n * this node is used to estimate the absoulte location of the robot using the optimization library  \"RobOptim\".\n * It subscribe to:\n * - /beacon_distances\n * It publishes to:\n * - /robot_pose\n *\n * SERRANO&ALI_ECN_M1_2017\n */\n\n// Cpp\n#include <stdexcept>\n#include <sstream>\n#include <stdio.h>\n#include <vector>\n#include <iostream>\n#include <stdlib.h>\n#include <string>\n#include <math.h>\n\n// Boost\n#include <boost/shared_ptr.hpp>\n\n// RobOptim\n#include <roboptim/core/linear-function.hh>\n#include <roboptim/core/differentiable-function.hh>\n#include <roboptim/core/twice-differentiable-function.hh>\n#include <roboptim/core/io.hh>\n#include <roboptim/core/solver.hh>\n#include <roboptim/core/solver-factory.hh>\n\n//ROS\n#include \"ros/ros.h\"\n#include <geometry_msgs/Pose2D.h>\n#include <std_msgs/Float64MultiArray.h>\n\n// blue beacon coordinates\n#define X1 0\n#define Y1 0\n// red beacon coordinates\n#define X2 0\n#define Y2 190\n// green beacon coordinates\n#define X3 350\n#define Y3 0\n// upper and lower bounds of map\n#define LB 0\n#define UB 400\n\n// global variables\nfloat blue_distance, red_distance, green_distance;\nbool are_dist_available = false;\nros::Publisher pose_pub;\n\nusing namespace roboptim;\nusing namespace std;\n\n// function to minimize\nstruct F : public TwiceDifferentiableFunction\n{\n    F () : TwiceDifferentiableFunction (2, 1, \"(x[0]-X1)^2 + (x[1]-Y1)^2 + (x[0]-X2)^2 + (x[1]-Y2)^2 + (x[0]-X3)^2 + (x[1]-Y3)^2\")\n    {\n    }\n\n    void impl_compute (result_ref result, const_argument_ref x) const\n    {\n        result[0] = pow(x[0]-X1, 2) + pow(x[1]-Y1, 2) + pow(x[0]-X2, 2) + pow(x[1]-Y2, 2) + pow(x[0]-X3, 2) + pow(x[1]-Y3, 2);\n    }\n\n    void impl_gradient (gradient_ref grad, const_argument_ref x, size_type) const\n    {\n        grad << 2*(x[0]-X1) + 2*(x[0]-X2) + 2*(x[0]-X3),\n                2*(x[1]-Y1) + 2*(x[1]-Y2) + 2*(x[1]-Y3);\n    }\n\n    void impl_hessian (hessian_ref h, const_argument_ref x, size_type) const\n    {\n        h << 6.0, 0.0,\n                0.0, 6.0;\n    }\n};\n\n// constraint 1\nstruct G0 : public TwiceDifferentiableFunction\n{\n    G0 () : TwiceDifferentiableFunction (2, 1, \"(x[0]-X1)^2 + (x[1]-Y1)^2\")\n    {\n    }\n\n    void impl_compute (result_ref result, const_argument_ref x) const\n    {\n        result[0] = pow(x[0]-X1, 2) + pow(x[1]-Y1, 2);\n    }\n\n    void impl_gradient (gradient_ref grad, const_argument_ref x, size_type) const\n    {\n        grad << 2*(x[0]-X1),\n                2*(x[1]-Y1);\n    }\n\n    void impl_hessian (hessian_ref h, const_argument_ref x, size_type) const\n    {\n        h << 2.0, 0.0,\n                0.0, 2.0;\n    }\n};\n\n// constraint 2\nstruct G1 : public TwiceDifferentiableFunction\n{\n    G1 () : TwiceDifferentiableFunction (2, 1, \"(x[0]-X2)^2 + (x[1]-Y2)^2\")\n    {\n    }\n\n    void impl_compute (result_ref result, const_argument_ref x) const\n    {\n        result[0] = pow(x[0]-X2, 2) + pow(x[1]-Y2, 2);\n    }\n\n    void impl_gradient (gradient_ref grad, const_argument_ref x, size_type) const\n    {\n        grad << 2*(x[0]-X2),\n                2*(x[1]-Y2);\n    }\n\n    void impl_hessian (hessian_ref h, const_argument_ref x, size_type) const\n    {\n        h << 2.0, 0.0,\n                0.0, 2.0;\n    }\n};\n\n// constraint 3\nstruct G2 : public TwiceDifferentiableFunction\n{\n    G2 () : TwiceDifferentiableFunction (2, 1, \"(x[0]-X3)^2 + (x[1]-Y3)^2\")\n    {\n    }\n\n    void impl_compute (result_ref result, const_argument_ref x) const\n    {\n        result[0] = pow(x[0]-X3, 2) + pow(x[1]-Y3, 2);\n    }\n\n    void impl_gradient (gradient_ref grad, const_argument_ref x, size_type) const\n    {\n        grad << 2*(x[0]-X3),\n                2*(x[1]-Y3);\n    }\n\n    void impl_hessian (hessian_ref h, const_argument_ref x, size_type) const\n    {\n        h << 2.0, 0.0,\n                0.0, 2.0;\n    }\n};\n\n// Callback functions\nvoid getDistanceCallback(std_msgs::Float64MultiArray distances)\n{\n    are_dist_available = true;\n    blue_distance = distances.data[0];\n    red_distance = distances.data[1];\n    green_distance = distances.data[2];\n}\n\nint main (int argc, char** argv)\n{\n\n    //ROS Initialization\n    ros::init(argc, argv, \"triangulation_optimization\");\n\n    // Define your node handles\n    ros::NodeHandle nh, nh_loc(\"~\");\n\n    // Declare your subscribers\n    ros::Subscriber dist_sub = nh.subscribe<std_msgs::Float64MultiArray>(\"beacon_distances\", 1, getDistanceCallback);\n\n    // Declare your publishers\n    pose_pub = nh.advertise<geometry_msgs::Pose2D>(\"robot_pose\", 1);\n\n    // node initilization\n    // ...\n\n    // rate\n    ros::Rate rate(30); // Hz\n    while (ros::ok()){\n        ros::spinOnce();\n\n        // node code\n        if (!are_dist_available) {\n            ROS_INFO(\"Waiting for distances\");\n            continue;\n        }\n\n        // ------------ RobOptim ---------------\n        typedef Solver<EigenMatrixDense> solver_t;\n\n        // Create cost function.\n        boost::shared_ptr<F> f (new F ());\n\n        // Create problem.\n        solver_t::problem_t pb (f);\n\n        // Set bounds for all optimization parameters.\n        // 1. < x_i < 5. (x_i in [1.;5.])\n        for (Function::size_type i = 0; i < pb.function ().inputSize (); ++i)\n            pb.argumentBounds ()[i] = Function::makeInterval (LB, UB);\n\n\n        // Set the starting point.\n        Function::vector_t start (pb.function ().inputSize ());\n        start << 150.,100.;\n        pb.startingPoint() = start;\n\n        // Create constraints.\n        boost::shared_ptr<G0> g0 (new G0 ());\n        boost::shared_ptr<G1> g1 (new G1 ());\n        boost::shared_ptr<G2> g2 (new G2 ());\n\n        F::intervals_t bounds;\n        solver_t::problem_t::scaling_t scaling;\n\n        // Add constraints\n        bounds.push_back(Function::makeLowerInterval( pow(blue_distance, 2) ));  // blue beacon distance\n        scaling.push_back (1.);\n        pb.addConstraint (g0, bounds, scaling);\n\n        bounds.clear ();\n        scaling.clear ();\n\n        bounds.push_back(Function::makeLowerInterval( pow(red_distance, 2) ));   // red beacon distance\n        scaling.push_back (1.);\n        pb.addConstraint (g1, bounds, scaling);\n\n        bounds.clear ();\n        scaling.clear ();\n\n        bounds.push_back(Function::makeLowerInterval( pow(green_distance, 2) )); // green beacon distance\n        scaling.push_back (1.);\n        pb.addConstraint (g2, bounds, scaling);\n\n        bounds.clear ();\n        scaling.clear ();\n\n        // Initialize solver.\n\n        // Here we are relying on the CFSQP solver.\n        // You may change this string to load the solver you wish to use:\n        //  - Ipopt: \"ipopt\", \"ipopt-sparse\", \"ipopt-td\"\n        //  - Eigen: \"eigen-levenberg-marquardt\"\n        //  etc.\n        // The plugin is built for a given solver type, so choose it adequately.\n        SolverFactory<solver_t> factory (\"ipopt\", pb);\n        solver_t& solver = factory ();\n\n        // Compute the minimum and retrieve the result.\n        solver_t::result_t res = solver.minimum ();\n\n        // Display solver information.\n        // std::cout << solver << std::endl;\n\n        // Check if the minimization has succeeded.\n\n        // Process the result\n        switch (res.which ())\n        {\n        case solver_t::SOLVER_VALUE:\n        {\n            // Get the result.\n            Result& result = boost::get<Result> (res);\n\n            // Display the result.\n            std::cout << \"A solution has been found: \" << std::endl << result << std::endl;\n            geometry_msgs::Pose2D pose_msg;\n            pose_msg.x = result.x[0];\n            pose_msg.y = result.x[1];\n            pose_msg.theta = 0;\n            pose_pub.publish(pose_msg);\n            break;\n        }\n\n        case solver_t::SOLVER_VALUE_WARNINGS:\n        {\n            // Get the result.\n            ResultWithWarnings& result = boost::get<ResultWithWarnings> (res);\n\n            // Display the result.\n            std::cout << \"A solution w/warning has been found: \" << std::endl\n                      << result << std::endl;\n\n            break;\n        }\n\n        case solver_t::SOLVER_NO_SOLUTION:\n        case solver_t::SOLVER_ERROR:\n        {\n            std::cout << \"A solution should have been found. Failing...\"\n                      << std::endl\n                      << boost::get<SolverError> (res).what ()\n                      << std::endl;\n\n            break;\n        }\n        }\n\n        are_dist_available = false;\n\n        rate.sleep();\n    }\n}\n\n", "meta": {"hexsha": "dd3c4d328b21230ac162bce2f7e6de718635cbfb", "size": 8379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/turtle_ekf/src/optimization.cpp", "max_stars_repo_name": "mahmoud-a-ali/TurtleBot_M1_Project", "max_stars_repo_head_hexsha": "a848c5b16fc2521acf265256cfbf9b7206f549d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-18T05:59:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T07:47:44.000Z", "max_issues_repo_path": "src/turtle_ekf/src/optimization.cpp", "max_issues_repo_name": "mahmoud-a-ali/TurtleBot_M1_Project", "max_issues_repo_head_hexsha": "a848c5b16fc2521acf265256cfbf9b7206f549d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/turtle_ekf/src/optimization.cpp", "max_forks_repo_name": "mahmoud-a-ali/TurtleBot_M1_Project", "max_forks_repo_head_hexsha": "a848c5b16fc2521acf265256cfbf9b7206f549d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-11T07:47:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-11T07:47:45.000Z", "avg_line_length": 26.6847133758, "max_line_length": 130, "alphanum_fraction": 0.5779926005, "num_tokens": 2343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6227361778712052}}
{"text": "/*\n * DIPlib 3.0\n * This file contains the thin plate spline functionality\n *\n * (c)2019, Cris Luengo.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"diplib/library/numeric.h\"\n\n#if defined(__GNUG__) || defined(__clang__)\n// For this file, turn off -Wsign-conversion, Eigen is really bad at this!\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wsign-conversion\"\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#if __GNUC__ >= 7 || __clang_major__ >= 12\n#pragma GCC diagnostic ignored \"-Wint-in-bool-context\"\n#endif\n#if __GNUC__ >= 9\n#pragma GCC diagnostic ignored \"-Wdeprecated-copy\"\n#endif\n#endif\n\n#include <Eigen/QR>\n#include <Eigen/Cholesky>\n\nnamespace dip {\n\nnamespace {\n\ndfloat RadialBasis( dfloat r ) {\n   return r > 0 ? r * r * std::log( r ) : 0;\n}\n\n} // namespace\n\nThinPlateSpline::ThinPlateSpline(\n      FloatCoordinateArray coordinate,    // use std::move if you can!\n      FloatCoordinateArray const& value,  // correspondence points\n      dfloat lambda\n) {\n   // NOTE: `source` and `destination` are already checked for sizes\n   c_ = std::move( coordinate );\n   dip::uint nPoints = c_.size();\n   dip::uint nDims = c_[ 0 ].size();\n\n   // Create matrices L and b\n   DIP_ASSERT( value.size() == nPoints );\n   dip::uint N = nPoints + nDims + 1;\n   Eigen::MatrixXd L( N, N );\n   L.fill( 0 );\n   Eigen::MatrixXd b( N, nDims );\n   b.fill( 0 );\n   dfloat alpha = 0;\n   for( dip::uint ii = 0; ii < nPoints; ++ii ) {\n      for( dip::uint jj = 0; jj < ii; ++jj ) {\n         L( ii, jj ) = L( jj, ii ); // Previously computed, L is symmetric\n      }\n      for( dip::uint jj = ii + 1; jj < nPoints; ++jj ) {\n         dfloat d = Distance( c_[ ii ], c_[ jj ] );\n         L( ii, jj ) = RadialBasis( d );\n         alpha += d;\n      }\n      L( ii, nPoints ) = 1;\n      for( dip::uint jj = 0; jj < nDims; ++jj ) {\n         L( ii, nPoints + 1 + jj ) = c_[ ii ][ jj ];\n         b( ii, jj ) = value[ ii ][ jj ] - c_[ ii ][ jj ];\n      }\n   }\n   if( lambda > 0.0 ) {\n      alpha /= static_cast< dfloat >( nPoints * ( nPoints - 1 ) / 2 );\n      alpha *= alpha * lambda;\n      for( dip::uint ii = 0; ii < nPoints; ++ii ) {\n         L( ii, ii ) = alpha;\n      }\n   }\n   for( dip::uint jj = 0; jj < nDims + 1; ++jj ) {\n      L.row( nPoints + jj ) = L.col( nPoints + jj );\n   }\n\n   // Solve equation Lx=b for x\n   // Using Eigen::Ref to get in-place decomposition, it re-uses L to store the decomposition.\n   Eigen::HouseholderQR <Eigen::Ref< Eigen::MatrixXd >> decomposition( L );\n   //Eigen::ColPivHouseholderQR <Eigen::Ref< Eigen::MatrixXd >> decomposition( L );\n   // TODO: Eigen::HouseholderQR is faster but less accurate than Eigen::ColPivHouseholderQR. Which one to pick?\n   x_.resize( N * nDims );\n   Eigen::Map< Eigen::MatrixXd >( x_.data(), N, nDims ) = decomposition.solve( b );\n}\n\n// Evaluates the thin plate spline function at point `pt`.\nFloatArray ThinPlateSpline::Evaluate( FloatArray const& pt ) {\n   dip::uint nPoints = c_.size();\n   dip::uint nDims = c_[ 0 ].size();\n   dip::uint N = nPoints + nDims + 1;\n   Eigen::Map <Eigen::MatrixXd> x( x_.data(), N, nDims );\n   // Note: w( ii, jj ) = x( ii, jj ), and a( ii, jj ) = x( nPoints + ii, jj )\n   FloatArray res = pt;\n   for( dip::uint ii = 0; ii < nPoints; ++ii ) {\n      dfloat scale = RadialBasis( Distance( pt, c_[ ii ] ));\n      for( dip::uint jj = 0; jj < nDims; ++jj ) {\n         res[ jj ] += x( ii, jj ) * scale;\n      }\n   }\n   for( dip::uint jj = 0; jj < nDims; ++jj ) {\n      res[ jj ] += x( nPoints, jj );\n   }\n   for( dip::uint ii = 0; ii < nDims; ++ii ) {\n      for( dip::uint jj = 0; jj < nDims; ++jj ) {\n         res[ jj ] += x( nPoints + 1 + ii, jj ) * pt[ ii ];\n      }\n   }\n   return res;\n}\n\n} // namespace dip\n\n#if defined(__GNUG__) || defined(__clang__)\n#pragma GCC diagnostic pop\n#endif\n", "meta": {"hexsha": "c065eb012bf9ac16c1775f9405bfa72f59de2a4a", "size": 4295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/support/thin_plate_spline.cpp", "max_stars_repo_name": "KDAB/diplib", "max_stars_repo_head_hexsha": "e55d56fab4982dfaeb0cc080d68e199973fec0e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-07T01:02:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T01:02:57.000Z", "max_issues_repo_path": "src/support/thin_plate_spline.cpp", "max_issues_repo_name": "KDAB/diplib", "max_issues_repo_head_hexsha": "e55d56fab4982dfaeb0cc080d68e199973fec0e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/support/thin_plate_spline.cpp", "max_forks_repo_name": "KDAB/diplib", "max_forks_repo_head_hexsha": "e55d56fab4982dfaeb0cc080d68e199973fec0e1", "max_forks_repo_licenses": ["Apache-2.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.786259542, "max_line_length": 112, "alphanum_fraction": 0.5976717113, "num_tokens": 1295, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.622736176133702}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <geometry.hpp>\n\n// reference: https://www.kalmanfilter.net/multiSummary.html fuck http://ros-developer.com/2019/04/10/kalman-filter-explained-with-python-code-from-scratch/\n// Everything is fitted for 2d tracking\n\nclass Kalman{\npublic:\n    static const int    nx = 4,\n                        nu = 2,\n                        nz = 2, NUM_VARS = 1;\n\n    //  Actual state\n    Eigen::Matrix<double, nx, 1> Xn;\n    // Output state\n    Eigen::Matrix<double, nz, 1> Zn;\n    // State transition matrix\n    Eigen::Matrix<double, nx, nx> F;\n    // Control matrix\n    Eigen::Matrix<double, nx, nu> G;\n    // Covariance matrix\n    Eigen::Matrix<double, nx, nx> P;\n    // Process covariance matrix\n    Eigen::Matrix<double, nx, nx> Q;\n    // Uncertainty matrix\n    Eigen::Matrix<double, nz, nz> R;\n    // Observation matrix\n    Eigen::Matrix<double, nz, nx> H;\n    // Kalman gain matrix\n    Eigen::Matrix<double, nx, nz> K;\n    // Identity matrix\n    Eigen::Matrix<double, nx, nx> I;\n\n    float dt;\n\n    // Variable indexes\n    static const int iX  = 0; // X position\n    static const int iY  = 1; // Y position\n    static const int idX = 2; // X velocity\n    static const int idY = 3; // Y velocity\n\n    Kalman(){\n        // Prediction matrices\n        F.setIdentity();\n        G.setZero();\n        Q.setIdentity();\n        P.setIdentity();\n\n        H <<    1, 0, 0, 0,\n                0, 1, 0, 0;\n\n        R <<    1, 0,\n                0, 1;\n    }\n\n    Kalman(double iniX, double inidX, double iniY, double inidY){\n        Xn(iX)  = iniX;\n        Xn(idX) = inidX;\n        Xn(iY)  = iniY;\n        Xn(idY) = inidY;\n\n        // Prediction matrices\n        F = F.setIdentity();\n        G = G.setZero();\n        Q = Q.setIdentity();\n\n        R = R.setIdentity();\n        R *= 5;\n\n        P = P.setIdentity();\n\n        H = H.setZero();\n        H(iX, iX) = 1;\n        H(iY, iY) = 1;\n\n        I = I.Identity();\n    }\n\n    void init(double iniX, double iniY, double dt){\n        Xn(iX)  = iniX;\n        Xn(idX) = 0;\n        Xn(iY)  = iniY;\n        Xn(idY) = 0;\n        this->dt = dt;\n\n        F(iX, idX) = dt;\n        F(iY, idY) = dt;\n        G(iX, iX) = 0.5 * dt * dt;\n        G(iY, iY) = 0.5 * dt * dt;\n        G(idX, iX) = dt;\n        G(idY, iY) = dt;\n\n        Q = G * 1 * G.transpose();\n    }\n\n    // // Prediction method for object tracking\n    // void predict(){\n    //     // Predict:   Xn+1 = F * Xn + G * Un\n    //     Xn = F * Xn;\n\n    // }\n\n    // Prediction method for object tracking\n    void predict(){\n        // Predict:   Xn+1 = F * Xn + G * Un\n        Xn = F * Xn;\n\n        P  = F * P * F.transpose() + Q; \n    }\n\n    void update(int x, int y){\n        // Zn\n        Zn <<   x,\n                y;\n\n        // K\n        K = P * H.transpose() * (H * P * H.transpose() + R).inverse();\n\n        // Xn\n        Xn = Xn + K * (Zn - H * Xn);\n\n        // P\n        Eigen::Matrix<double, nx, nx> I;\n        I = I.Identity();\n        // P = P * (I.Identity() - K * H);\n        // P = (I - K * H) * P * (I - K * H).transpose() + K * R * K.transpose();\n        P = P * (I - K * H);\n    }\n\n    std::pair<double, double> getPosition(){\n        return {Xn(iX), Xn(iY)};\n    }\n};", "meta": {"hexsha": "77e654f53643995bb6b214592a58fc382ebc93f1", "size": 3205, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kalman.hpp", "max_stars_repo_name": "SebaHiga/simple_tracker", "max_stars_repo_head_hexsha": "0670ee09a0dfc94c817f9bb148e1d382b117d370", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kalman.hpp", "max_issues_repo_name": "SebaHiga/simple_tracker", "max_issues_repo_head_hexsha": "0670ee09a0dfc94c817f9bb148e1d382b117d370", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kalman.hpp", "max_forks_repo_name": "SebaHiga/simple_tracker", "max_forks_repo_head_hexsha": "0670ee09a0dfc94c817f9bb148e1d382b117d370", "max_forks_repo_licenses": ["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.7407407407, "max_line_length": 156, "alphanum_fraction": 0.471450858, "num_tokens": 1019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6227361668008932}}
{"text": "#ifndef enhancer_hpp\n#define enhancer_hpp\n\n#include <cmath>\n#include <Eigen/Core>\n\nnamespace enhancer\n{\n#if defined(ENHANCER_WITH_LIFT_GAMMA_GAIN)\n    constexpr int NUM_PARAMETERS = 12;\n#else\n    constexpr int NUM_PARAMETERS = 5;\n#endif\n\n    ///////////////////////////////////////////////////////////\n    // Interface\n    ///////////////////////////////////////////////////////////\n\n    inline Eigen::Vector3d enhance(const Eigen::Vector3d& input_rgb, const Eigen::VectorXd& parameters);\n\n    ///////////////////////////////////////////////////////////\n    // Implementation\n    ///////////////////////////////////////////////////////////\n\n    namespace internal\n    {\n        inline Eigen::Vector3d convertRgbToLinearRgb(const Eigen::Vector3d& rgb)\n        {\n            return rgb.array().pow(2.2).matrix();\n        }\n\n        inline Eigen::Vector3d convertLinearRgbToRgb(const Eigen::Vector3d& linear_rgb)\n        {\n            return linear_rgb.array().pow(1.0 / 2.2).matrix();\n        }\n\n        // Y'UV (BT.709) to linear RGB\n        // Values are from https://en.wikipedia.org/wiki/YUV\n        inline Eigen::Vector3d yuv2rgb(const Eigen::Vector3d& yuv)\n        {\n            constexpr double m[9] = { +1.00000, +1.00000, +1.00000,   // 1st column\n                                      +0.00000, -0.21482, +2.12798,   // 2nd column\n                                      +1.28033, -0.38059, +0.00000 }; // 3rd column\n            return Eigen::Map<const Eigen::Matrix3d>(m) * yuv;\n        }\n\n        // Linear RGB to Y'UV (BT.709)\n        // Values are from https://en.wikipedia.org/wiki/YUV\n        inline Eigen::Vector3d rgb2yuv(const Eigen::Vector3d& rgb)\n        {\n            constexpr double m[9] = { +0.21260, -0.09991, +0.61500,   // 1st column\n                                      +0.71520, -0.33609, -0.55861,   // 2nd column\n                                      +0.07220, +0.43600, -0.05639 }; // 3rd column\n            return Eigen::Map<const Eigen::Matrix3d>(m) * rgb;\n        }\n\n        inline double rgb2h(const Eigen::Vector3d& rgb)\n        {\n            const double r = rgb(0);\n            const double g = rgb(1);\n            const double b = rgb(2);\n            const double M = std::max({r, g, b});\n            const double m = std::min({r, g, b});\n\n            double h;\n            if (M == m)      h = 0.0;\n            else if (m == b) h = 60.0 * (g - r) / (M - m) + 60.0;\n            else if (m == r) h = 60.0 * (b - g) / (M - m) + 180.0;\n            else if (m == g) h = 60.0 * (r - b) / (M - m) + 300.0;\n            else             abort();\n            h /= 360.0;\n            if (h < 0.0) {\n                ++ h;\n            } else if (h > 1.0) {\n                -- h;\n            }\n            return h;\n        }\n\n        inline double rgb2s4hsv(const Eigen::Vector3d& rgb)\n        {\n            const double r = rgb(0);\n            const double g = rgb(1);\n            const double b = rgb(2);\n            const double M = std::max({r, g, b});\n            const double m = std::min({r, g, b});\n\n            if (M < 1e-14) return 0.0;\n            return (M - m) / M;\n        }\n\n        inline double rgb2s4hsl(const Eigen::Vector3d& rgb)\n        {\n            const double r = rgb(0);\n            const double g = rgb(1);\n            const double b = rgb(2);\n            const double M = std::max({r, g, b});\n            const double m = std::min({r, g, b});\n\n            if (M - m < 1e-14) return 0.0;\n            return (M - m) / (1.0 - std::abs(M + m - 1.0));\n        }\n\n        inline Eigen::Vector3d hsl2rgb(const Eigen::Vector3d& hsl)\n        {\n            auto hue2rgb = [](const double f1, const double f2, double hue)\n            {\n                if (hue < 0.0) hue += 1.0;\n                if (hue > 1.0) hue -= 1.0;\n\n                double res;\n                if ((6.0 * hue) < 1.0)\n                    res = f1 + (f2 - f1) * 6.0 * hue;\n                else if ((2.0 * hue) < 1.0)\n                    res = f2;\n                else if ((3.0 * hue) < 2.0)\n                    res = f1 + (f2 - f1) * ((2.0 / 3.0) - hue) * 6.0;\n                else\n                    res = f1;\n                return res;\n            };\n\n            if (hsl.y() == 0.0)\n            {\n                return Eigen::Vector3d(hsl.z(), hsl.z(), hsl.z());\n            }\n\n            const double f2 = (hsl.z() < 0.5) ? hsl.z() * (1.0 + hsl.y()) : (hsl.z() + hsl.y()) - (hsl.y() * hsl.z());\n            const double f1 = 2.0 * hsl.z() - f2;\n\n            Eigen::Vector3d rgb;\n            rgb(0) = hue2rgb(f1, f2, hsl.x() + (1.0 / 3.0));\n            rgb(1) = hue2rgb(f1, f2, hsl.x());\n            rgb(2) = hue2rgb(f1, f2, hsl.x() - (1.0 / 3.0));\n\n            return rgb;\n        }\n\n        inline Eigen::Vector3d rgb2hsv(const Eigen::Vector3d& rgb)\n        {\n            const double& r = rgb(0);\n            const double& g = rgb(1);\n            const double& b = rgb(2);\n\n            const double M = std::max({r, g, b});\n\n            const double h = rgb2h(rgb);\n            const double s = rgb2s4hsv(rgb);\n            const double v = M;\n\n            return Eigen::Vector3d(h, s, v);\n        }\n\n        inline double rgb2l(const Eigen::Vector3d& rgb)\n        {\n            const double r = rgb(0);\n            const double g = rgb(1);\n            const double b = rgb(2);\n            const double M = std::max({r, g, b});\n            const double m = std::min({r, g, b});\n\n            return 0.5 * (M + m);\n        }\n\n        inline Eigen::Vector3d hsv2rgb(const Eigen::Vector3d& hsv)\n        {\n            const double& h = hsv(0);\n            const double& s = hsv(1);\n            const double& v = hsv(2);\n\n            if (s < 1e-14)\n            {\n                return Eigen::Vector3d(v, v, v);\n            }\n\n            const double h6 = h * 6.0;\n            const int    i  = static_cast<int>(floor(h6)) % 6;\n            const double f  = h6 - static_cast<double>(i);\n            const double p  = v * (1 - s);\n            const double q  = v * (1 - (s * f));\n            const double t  = v * (1 - (s * (1 - f)));\n            double r, g, b;\n            switch(i)\n            {\n                case 0: r = v; g = t; b = p; break;\n                case 1: r = q; g = v; b = p; break;\n                case 2: r = p; g = v; b = t; break;\n                case 3: r = p; g = q; b = v; break;\n                case 4: r = t; g = p; b = v; break;\n                case 5: r = v; g = p; b = q; break;\n            }\n\n            return Eigen::Vector3d(r, g, b);\n        }\n\n        inline Eigen::Vector3d rgb2hsl(const Eigen::Vector3d& rgb)\n        {\n            const double h = rgb2h(rgb);\n            const double s = rgb2s4hsl(rgb);\n            const double l = rgb2l(rgb);\n\n            return Eigen::Vector3d(h, s, l);\n        }\n\n        inline float clamp(const float value) { return std::max(0.0, std::min(static_cast<double>(value), 1.0)); }\n        inline Eigen::Vector3d clamp(const Eigen::Vector3d& v) { return Eigen::Vector3d(clamp(v.x()), clamp(v.y()), clamp(v.z())); }\n\n        inline Eigen::Vector3d changeColorBalance(const Eigen::Vector3d& inputRgb, const Eigen::Vector3d& shift)\n        {\n            constexpr double a     = 0.250;\n            constexpr double b     = 0.333;\n            constexpr double scale = 0.700;\n\n            const double          lightness = rgb2l(inputRgb);\n            const Eigen::Vector3d midtones  = (clamp((lightness - b) / a + 0.5) * clamp((lightness + b - 1.0) / (- a) + 0.5) * scale) * shift;\n            const Eigen::Vector3d newColor  = clamp(inputRgb + midtones);\n            const Eigen::Vector3d newHsl    = rgb2hsl(newColor);\n\n            return hsl2rgb(Eigen::Vector3d(newHsl(0), newHsl(1), lightness));\n        }\n\n        inline Eigen::Vector3d applyLiftGammaGainEffect(const Eigen::Vector3d& linear_rgb,\n                                                        const Eigen::Vector3d& lift,\n                                                        const Eigen::Vector3d& gamma,\n                                                        const Eigen::Vector3d& gain)\n        {\n            const Eigen::Array3d lift_applied_linear_rgb  = ((linear_rgb.array() - Eigen::Array3d::Ones()) * (Eigen::Array3d::Constant(2.0) - lift.array()) + Eigen::Array3d::Ones()).max(0.0);\n            const Eigen::Array3d gain_applied_linear_rgb  = lift_applied_linear_rgb * gain.array();\n            const Eigen::Array3d gamma_applied_linear_rgb = gain_applied_linear_rgb.pow(gamma.array().inverse());\n\n            return gamma_applied_linear_rgb.matrix();\n        }\n\n        inline Eigen::Vector3d applyTemperatureTintEffect(const Eigen::Vector3d& linear_rgb, const double temperature, const double tint)\n        {\n            constexpr double scale = 0.10;\n\n            return clamp(yuv2rgb(rgb2yuv(linear_rgb) + temperature * scale * Eigen::Vector3d(0.0, -1.0, 1.0) + tint * scale * Eigen::Vector3d(0.0, 1.0, 1.0)));\n        }\n\n        inline Eigen::Vector3d applyBrightnessEffect(const Eigen::Vector3d& linear_rgb, const double brightness)\n        {\n            constexpr double scale = 1.5;\n\n            return linear_rgb.array().pow(1.0 / (1.0 + scale * brightness)).matrix();\n        }\n\n        inline Eigen::Vector3d applySaturationEffect(const Eigen::Vector3d& linear_rgb, const double saturation)\n        {\n            const Eigen::Vector3d hsv = rgb2hsv(clamp(linear_rgb));\n            const double s = clamp(hsv(1) * (saturation + 1.0));\n\n            return hsv2rgb(Eigen::Vector3d(hsv(0), s, hsv(2)));\n        }\n\n        inline Eigen::Vector3d applyContrastEffect(const Eigen::Vector3d& linear_rgb, const double contrast)\n        {\n            constexpr double pi_4 = 3.14159265358979 * 0.25;\n\n            const double contrast_coef = std::tan((contrast + 1.0) * pi_4);\n            \n            return convertRgbToLinearRgb((contrast_coef * (convertLinearRgbToRgb(linear_rgb) - Eigen::Vector3d::Constant(0.5)) + Eigen::Vector3d::Constant(0.5)).array().max(0.0));\n        }\n\n        inline Eigen::Vector3d enhance(const Eigen::Vector3d& input_rgb, const Eigen::VectorXd& parameters)\n        {\n            assert(parameters.size() == NUM_PARAMETERS);\n\n            const double brightness  = clamp(parameters[0]) - 0.5;\n            const double contrast    = clamp(parameters[1]) - 0.5;\n            const double saturation  = clamp(parameters[2]) - 0.5;\n\n#if defined(ENHANCER_WITH_LIFT_GAMMA_GAIN)\n            const Eigen::Vector3d lift  = Eigen::Vector3d::Constant(0.5) + clamp(parameters.segment<3>(3)); // [0.5, 1.5]^3\n            const Eigen::Vector3d gamma = Eigen::Vector3d::Constant(0.5) + clamp(parameters.segment<3>(6)); // [0.5, 1.5]^3\n            const Eigen::Vector3d gain  = Eigen::Vector3d::Constant(0.5) + clamp(parameters.segment<3>(9)); // [0.5, 1.5]^3\n#else\n            const double temperature = clamp(parameters[3]) - 0.5;\n            const double tint        = clamp(parameters[4]) - 0.5;\n#endif\n\n            Eigen::Vector3d linear_rgb = convertRgbToLinearRgb(input_rgb);\n\n#if defined(ENHANCER_WITH_LIFT_GAMMA_GAIN)\n            // Lift/Gamma/Gain\n            linear_rgb = applyLiftGammaGainEffect(linear_rgb, lift, gamma, gain);\n#else\n            // Approximate temperature/tint effect\n            linear_rgb = applyTemperatureTintEffect(linear_rgb, temperature, tint);\n#endif\n\n            // Brightness\n            linear_rgb = applyBrightnessEffect(linear_rgb, brightness);\n\n            // Contrast\n            linear_rgb = applyContrastEffect(linear_rgb, contrast);\n\n            // Saturation\n            linear_rgb = applySaturationEffect(linear_rgb, saturation);\n\n            return clamp(convertLinearRgbToRgb(linear_rgb));\n        }\n\n        inline Eigen::Vector3d enhance_v1(const Eigen::Vector3d& input_rgb, const Eigen::VectorXd& parameters)\n        {\n            assert(parameters.size() == NUM_PARAMETERS);\n\n            const double          brightness  = parameters[0] - 0.5;\n            const double          contrast    = parameters[1] - 0.5;\n            const double          saturation  = parameters[2] - 0.5;\n            const Eigen::Vector3d balance     = parameters.segment<3>(3) - Eigen::Vector3d::Constant(0.5);\n\n            // color balance\n            Eigen::Vector3d rgb = changeColorBalance(input_rgb, balance);\n\n            // brightness\n            rgb *= 1.0 + brightness;\n\n            // contrast\n            constexpr double pi_4 = 3.14159265358979 * 0.25;\n            const double contrast_coef = std::tan((contrast + 1.0) * pi_4);\n            rgb = contrast_coef * (rgb - Eigen::Vector3d::Constant(0.5)) + Eigen::Vector3d::Constant(0.5);\n\n            // clamp\n            rgb = clamp(rgb);\n\n            // saturation\n            Eigen::Vector3d hsv = rgb2hsv(rgb);\n            double s = hsv.y();\n            s *= saturation + 1.0;\n            hsv(1) = clamp(s);\n            const Eigen::Vector3d output_rgb = hsv2rgb(hsv);\n\n            return output_rgb;\n        }\n    }\n\n    inline Eigen::Vector3d enhance(const Eigen::Vector3d& input_rgb, const Eigen::VectorXd& parameters)\n    {\n        return internal::enhance(input_rgb, parameters);\n    }\n}\n\n#endif /* enhancer_hpp */\n", "meta": {"hexsha": "66779499bd86e3c8a160a65bc40bc7216ad41230", "size": 13100, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/enhancer/enhancer.hpp", "max_stars_repo_name": "yuki-koyama/enhancer", "max_stars_repo_head_hexsha": "ade340f75ba5f63f25d564d643ec76df29e4aa8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-09-09T21:50:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T01:25:19.000Z", "max_issues_repo_path": "include/enhancer/enhancer.hpp", "max_issues_repo_name": "yuki-koyama/enhancer", "max_issues_repo_head_hexsha": "ade340f75ba5f63f25d564d643ec76df29e4aa8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-08-09T10:25:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T07:35:22.000Z", "max_forks_repo_path": "include/enhancer/enhancer.hpp", "max_forks_repo_name": "yuki-koyama/enhancer", "max_forks_repo_head_hexsha": "ade340f75ba5f63f25d564d643ec76df29e4aa8b", "max_forks_repo_licenses": ["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.9710144928, "max_line_length": 191, "alphanum_fraction": 0.4992366412, "num_tokens": 3600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.6227361626805943}}
{"text": "/**@file get_initial_calib.hpp\n * @brief Header file containing required headers and methods\n *        for computing initial intrinsic calibration matrix.\n *\n * Detailed description follows here.\n * @author     : Abhinav Modi, Kartik Madhira\n * \n * Copyright 2019 MIT License\n */\n\n#pragma once\n\n#include <iostream>\n#include <vector>\n#include \"Eigen/Dense\"\n#include \"Eigen/Core\"\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <boost/filesystem.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\nusing namespace Eigen; //NOLINT\nusing std::vector;\nusing std::cout;\n\n\n /**\n  * @brief get_corners outputs corners of the input checkerboard image.\n  * @param board_image  - input checkerboard image.\n  * @param pattern_size - tuple(num_rows, num_columns) in the checkerboard.\n  * @param show_corners - flag to enable display of input image with corners. \n  * @return vector of corners points in the input checkerboard image.\n  */\nvector<cv::Point2f> get_corners(cv::Mat board_image, cv::Size pattern_size,\n                                bool show_corners);\n\n /**\n  * @brief get_V_matrix outputs V matrix. \n  * @param corner_vector - vector of corner points of the checkerboard image.  \n  * @param square_size   - size of the square pattern in the checkerboard.\n  * @param pattern_size  - tuple(num_rows, num_columns) in the checkerboard. \n  * @return 2D matrix of shape(12,2) containing V values \n  */\nMatrixXf get_V_matrix(vector<cv::Point2f> corner_vector, float square_size,\n                        cv::Size pattern_size);\n\n/**\n * @brief get_homography computes homography matrix using image and world coords\n * @param world_corners - (N, 2) matrix of world coordinates  \n * @param square_size   - (N, 2) matrix of image coordinates\n * @return (3, 3) homography matrix  \n */\ncv::Mat get_homography(cv::Mat world_corners, cv::Mat image_corners);\n\n/**\n * @brief create_V_matrix computes V matrix using homography\n * @param world_corners - (N, 2) matrix of world coordinates  \n * @param square_size   - (N, 2) matrix of image coordinates\n * @return (3, 3) homography matrix  \n */\nMatrixXf create_V_matrix(const cv::Mat& H);\n\n/**\n * @brief get_vij_matrix is a helper function to compute vij matrix\n * @param vij - reference to the vij matrix for computing V matrix    \n * @param H   - const reference to the Homography matrix \n * @param i   - index i for vij \n * @param j   - index j for vij\n */\nvoid get_vij_matrix(MatrixXf& vij, const cv::Mat& H, int i, int j); //NOLINT\n\nMatrixXf get_initial_K(const MatrixXf& V);\n\nMatrixXf get_B_matrix(const MatrixXf& rt_eigen_matrix);\n\nMatrix3f compute_K(const MatrixXf& B);\n\n", "meta": {"hexsha": "4f2225df40cee5182dcd36851c93ae83005439c9", "size": 2709, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/get_initial_calib.hpp", "max_stars_repo_name": "abhi1625/camera-calibration", "max_stars_repo_head_hexsha": "d34a96245d86ed36432db3037919348d7d3a7846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-15T01:57:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T08:03:33.000Z", "max_issues_repo_path": "src/get_initial_calib.hpp", "max_issues_repo_name": "abhi1625/camera-calibration", "max_issues_repo_head_hexsha": "d34a96245d86ed36432db3037919348d7d3a7846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-09-17T21:08:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-24T18:46:55.000Z", "max_forks_repo_path": "src/get_initial_calib.hpp", "max_forks_repo_name": "abhi1625/camera-calibration", "max_forks_repo_head_hexsha": "d34a96245d86ed36432db3037919348d7d3a7846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-16T03:22:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T03:22:22.000Z", "avg_line_length": 33.8625, "max_line_length": 80, "alphanum_fraction": 0.7150239941, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6227317329273427}}
{"text": "#include \"dsl_compiler.h\"\n#include \"placeholders.h\"\n#include \"test_ctx_fixture.h\"\n\n#include <boost/range/algorithm.hpp>\n\n#include <gtest/gtest.h>\n\nnamespace{\n        using namespace dsl_compiler;\n        using namespace dsl_compiler::placeholders;\n\n        using FibTest = BasicCtxFixture<struct tag_test_fib>;\n\n        TEST_F( FibTest, First20 ){\n\n                auto max_fib = 20;\n\n                struct tag_lag1{};\n                struct tag_lag2{};\n                struct tag_n{};\n\n                auto lag1 = placeholder<tag_lag1>();\n                auto lag2 = placeholder<tag_lag2>();\n                auto n = placeholder<tag_n>();\n\n                auto stmt = (\n                        lag1 = 1\n                      , lag2 = 1\n                      , push(lag1)\n                      , push(lag2)\n                      , for_( n = 2, n < max_fib , n += 1 )\n                        (\n                                _1 = lag1 + lag2\n                              , lag1 = lag2\n                              , lag2 = _1\n                              , push(lag2)\n                        )\n                );\n\n                auto prog = compile(stmt);\n\n                prog.execute(ctx);\n\n                std::vector<int> known = {1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765};\n                std::vector<int> result;\n                boost::for_each( ctx.get_stack(), [&result](auto _){ result.emplace_back(static_cast<int>(_));});\n                ASSERT_EQ( boost::equal( known , result ), true );\n        }\n\n}\n\n\n", "meta": {"hexsha": "f55918df33fe883c82489628759745efbf2d6938", "size": 1546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_fib.cpp", "max_stars_repo_name": "sweeterthancandy/2stage", "max_stars_repo_head_hexsha": "9807b7fc063ed4726f594724ba61f6b4399b2ca2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_fib.cpp", "max_issues_repo_name": "sweeterthancandy/2stage", "max_issues_repo_head_hexsha": "9807b7fc063ed4726f594724ba61f6b4399b2ca2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_fib.cpp", "max_forks_repo_name": "sweeterthancandy/2stage", "max_forks_repo_head_hexsha": "9807b7fc063ed4726f594724ba61f6b4399b2ca2", "max_forks_repo_licenses": ["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.6296296296, "max_line_length": 113, "alphanum_fraction": 0.4372574386, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.622598637296694}}
{"text": "//----------------------------------*-C++-*-------------------=---------------//\n/**\n *  @file  test_SphericalHarmonics.cc\n *  @brief Test of SphericalHarmonics class.\n *  @note  Copyright (C) Jeremy Roberts 2012-2013\n */\n//----------------------------------------------------------------------------//\n\n// LIST OF TEST FUNCTIONS\n#define TEST_LIST                                 \\\n        FUNC(test_SphericalHarmonics)             \\\n        FUNC(test_SphericalHarmonics_integration)\n\n#include \"utilities/TestDriver.hh\"\n#include \"angle/SphericalHarmonics.hh\"\n#include \"angle/QuadratureFactory.hh\"\n#ifdef DETRAN_ENABLE_BOOST\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n#include <boost/math/special_functions/factorials.hpp>\nusing boost::math::spherical_harmonic_r;\nusing boost::math::spherical_harmonic_i;\nusing boost::math::factorial;\n#endif\n#include \"utilities/Constants.hh\"\n#include <cstdio>\n// Setup\n/* ... */\n\nusing namespace detran_angle;\nusing namespace detran_utilities;\nusing namespace detran_test;\nusing std::cout;\nusing std::endl;\nusing std::printf;\n\nint main(int argc, char *argv[])\n{\n  RUN(argc, argv);\n}\n\n//----------------------------------------------------------------------------//\n// TEST DEFINITIONS\n//----------------------------------------------------------------------------//\n\nint test_SphericalHarmonics(int argc, char *argv[])\n{\n  double mu  = 0.350021174581540677777041;\n  double eta = 0.350021174581540677777041;\n  double xi  = 0.868890300722201205229788;\n  TEST(soft_equiv(SphericalHarmonics::Y_lm(0, 0, mu, eta, xi), 1.0));\n  TEST(soft_equiv(SphericalHarmonics::Y_lm(1,-1, mu, eta, xi), eta));\n  TEST(soft_equiv(SphericalHarmonics::Y_lm(1, 0, mu, eta, xi), xi));\n  TEST(soft_equiv(SphericalHarmonics::Y_lm(1, 1, mu, eta, xi), mu));\n  return 0;\n}\n\n/*\n *  This test compares the accuracy of 3-D quadratures.  In\n *  particular, we test a quadrature on the following\n *  moments:\n *\n *    (2/pi)int( cos(phi)^m * sin(phi)^(l+1) * sin(theta)^l, phi=0..pi/2, theta=0..pi/2)\n *\n *    l, m   even\n *\n *  = 1/(m+1)                                 for l = 0\n *    (l/2-1/2)!(m/2-1/2)! / (l/2+m/2+1/2)!   for l >= 0\n *\n *  The level symmetric quadrature integrates these exactly for\n *  N >= k + l, where N is the order (= twice the polar/octant)\n *\n *  This could be made a public function at some point.\n */\nint test_SphericalHarmonics_integration(int argc, char *argv[])\n{\n  InputDB::SP_input inp(new InputDB());\n  inp->put<int>(\"quad_number_polar_octant\",   4);\n  inp->put<int>(\"quad_number_azimuth_octant\", 4);\n  inp->put<std::string>(\"quad_type\", \"asqr-asdr\");\n  QuadratureFactory::SP_quadrature Q = QuadratureFactory::build(inp, 3);\n\n  int L = 6;\n\n  vec2_dbl err(L + 1, vec_dbl(L + 1, 0.0));\n\n  for (int ll = 0; ll <= L; ++ll)\n  {\n    int l = 2*ll;\n    for (int mm = 0; mm <= L; ++mm)\n    {\n      int m = 2*mm;\n\n      // Compute the reference\n      double ref;\n      if (l == 0)\n      {\n        ref = 1.0 / (m + 1.0);\n      }\n      else\n      {\n        ref = 1.0 / (l + m + 1.0);\n        for (int i = 1; i < l; i+=2)\n        {\n          double den = m + i;\n          ref *= (double)i / den;\n        }\n      }\n      ref *= four_pi;\n\n      double val = 0.0;\n      for (int o = 0; o < 8; ++o)\n      {\n        for (int a = 0; a < Q->number_angles_octant(); ++a)\n        {\n          double mu  = Q->mu(o, a);\n          //double eta = Q->eta(o, a);\n          double xi  = Q->xi(o, a);\n          val += Q->weight(a) * std::pow(mu, m) * std::pow(xi, l);\n        }\n      }\n      err[ll][mm] = 100.0*(val-ref)/ref;\n    }\n  }\n\n  // Print a table of errors\n  cout << \" NUMBER OF ANGLES = \" << Q->number_angles() << endl;\n  printf(\"  l \\\\ m \");\n  for (int mm = 0; mm <= L; ++mm)\n    printf(\"  %3i         \", 2*mm);\n  printf(\"\\n ------\");\n  for (int mm = 0; mm <= L; ++mm)\n    printf(\"--------------\");\n  printf(\"\\n\");\n  for (int ll = 0; ll <= L; ++ll)\n  {\n    int l = 2*ll;\n    printf(\" %3i |\", l);\n    for (int mm = 0; mm <= L; ++mm)\n    {\n      int m = 2*mm;\n      printf(\" %12.6f \", err[ll][mm]);\n    }\n    printf(\"\\n\");\n  }\n\n  return 0;\n}\n\n//----------------------------------------------------------------------------//\n//              end of test_SphericalHarmonics.cc\n//----------------------------------------------------------------------------//\n", "meta": {"hexsha": "ba9215a28fdfa684b134f28f50dcbd65929a0629", "size": 4289, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/angle/test/test_SphericalHarmonics.cc", "max_stars_repo_name": "baklanovp/libdetran", "max_stars_repo_head_hexsha": "820efab9d03ae425ccefb9520bdb6c086fdbf939", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T16:20:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-10T13:40:16.000Z", "max_issues_repo_path": "src/angle/test/test_SphericalHarmonics.cc", "max_issues_repo_name": "baklanovp/libdetran", "max_issues_repo_head_hexsha": "820efab9d03ae425ccefb9520bdb6c086fdbf939", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T21:24:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-16T00:56:44.000Z", "max_forks_repo_path": "src/angle/test/test_SphericalHarmonics.cc", "max_forks_repo_name": "baklanovp/libdetran", "max_forks_repo_head_hexsha": "820efab9d03ae425ccefb9520bdb6c086fdbf939", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-03-07T16:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T00:14:23.000Z", "avg_line_length": 28.2171052632, "max_line_length": 88, "alphanum_fraction": 0.500816041, "num_tokens": 1272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583167, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6225986247642091}}
{"text": "/* Small utility functions useful for point-based registration */\n#include <Util.hpp>\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <exception>\n\n#include <Eigen/Dense>\n#include <Exceptions.hpp>\n\nbool isApproxEqual(double a, double b, double eps) {\n    // Check whether a and b are equal, to within tolerance eps.\n    auto diff = std::abs(a - b);\n    return diff < eps;\n}\n\nbool isApproxEqual(double a, double b) {\n    // Epsilon not specified, default to 0.001;\n    return isApproxEqual(a, b, 0.001);\n}\n\nEigen::Vector3d find_pointset_average(const Eigen::MatrixXd& pointset) {\n    auto average = pointset.rowwise().mean();\n    return average;\n}\n\nEigen::MatrixXd residuals_from_point(const Eigen::MatrixXd& pointset, const Eigen::Vector3d& point) {\n    return pointset.colwise() - point;\n}\n\nEigen::VectorXd distances_between_pointsets(const Eigen::MatrixXd& pointset, const Eigen::MatrixXd& pointset_dash) {\n    return (pointset - pointset_dash).colwise().norm();\n}\n\ndouble root_mean_square(const Eigen::VectorXd& v) {\n    return sqrt((v.cwiseProduct(v)).mean());\n}\n\nEigen::Matrix4d compose_final_transform(const Eigen::Matrix3d& rotation, const Eigen::Vector3d& translation) {\n    // Compose 3x3 rotation and 3d vector translation to get a joint rotation+translation.\n    // Final transform is a 4x4 rigid transform matrix, with rotation part in the top-left 3x3, and translation in the top-right 3x1.\n    Eigen::Matrix4d final_transform;\n    final_transform.block(0,0,3,3) << rotation;\n    final_transform.block(0,3,3,1) << translation;\n    final_transform.block(3,0,1,3) << 0, 0, 0;\n    final_transform.block(3,3,1,1) << 1;\n\n    return final_transform;\n}\n\nEigen::MatrixXd apply_transform(const Eigen::MatrixXd& pointset, const Eigen::Matrix4d& transform) {\n    // Need to add a one on the end of each vector, for the translation part of the transform.\n    Eigen::MatrixXd pointset_augmented(4,pointset.cols());\n    pointset_augmented.block(0,0,3,pointset.cols()) << pointset;\n    pointset_augmented.block(3,0,1,pointset.cols()) << Eigen::MatrixXd::Constant(1, pointset.cols(), 1);\n\n    auto proposed_pointset = transform * pointset_augmented;\n\n    // Now remove the unnecessary bottom row of the transformed pointset.\n    auto proposed_pointset_reduced = proposed_pointset.block(0,0,3,pointset.cols());\n\n    return proposed_pointset_reduced;\n}\n\nEigen::MatrixXd load_pointcloud_from_file(std::string filename) {\n    int max_points = 1E6;\n    int line_counter = 0;\n    Eigen::MatrixXd points(3,max_points);\n\n    std::ifstream infile;\n    infile.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n    try {\n        infile.open(filename);\n    \n        double x, y, z;\n    \n        while(infile >> x >> y >> z) {\n            points.col(line_counter) << x, y, z;\n            line_counter++;\n        }\n\n    } catch(std::ifstream::failure e) {\n        if(!infile.eof()) {\n            // Any reason other than EOF is a failure. TODO: give a specific error message for non-existent file.\n            std::cerr << \"Could not read file \" << filename << std::endl;\n            throw(PointMatchingEx);\n        } else{\n            infile.close();\n\n            auto pointcloud = points.block(0,0,3,line_counter);\n            return pointcloud;\n        }\n    }\n\n}\n\nEigen::Matrix4d load_transform_from_file(std::string filename) {\n    int line_counter = 0;\n    Eigen::Matrix4d transform;\n\n    std::ifstream infile;\n    infile.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n    try {\n        infile.open(filename);\n    \n        double a, b, c, d;\n    \n        while(infile >> a >> b >> c >> d) {\n            transform.row(line_counter) << a, b, c, d;\n            line_counter++;\n        }\n\n    } catch(std::ifstream::failure e) {\n        if(!infile.eof()) {\n            // Any reason other than EOF is a failure. TODO: give a specific error message for non-existent file.\n            std::cerr << \"Could not read file \" << filename << std::endl;\n            throw(PointMatchingEx);\n        } else if(infile.eof() && line_counter == 4) {\n            infile.close();\n            return transform;\n        } else {\n            std::cerr << \"Could not read file \" << filename << std::endl;\n            throw(PointMatchingEx);\n        }\n    }\n\n}\n\nvoid write_matrix_to_file(const Eigen::MatrixXd& matrix, std::string filename) {\n    std::ofstream outfile(filename);\n    if(outfile.is_open()) {\n        outfile << matrix;\n    }\n}\n", "meta": {"hexsha": "3c2969760a0024a154b6c0ffb06978803e904f18", "size": 4451, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Code/PointMatching/Util.cc", "max_stars_repo_name": "karnival/simple-registration", "max_stars_repo_head_hexsha": "0a7d952e566f0117c0d75f77337c23cfc97a3e7f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-04T00:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-04T00:54:17.000Z", "max_issues_repo_path": "Code/PointMatching/Util.cc", "max_issues_repo_name": "karnival/simple-registration", "max_issues_repo_head_hexsha": "0a7d952e566f0117c0d75f77337c23cfc97a3e7f", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/PointMatching/Util.cc", "max_forks_repo_name": "karnival/simple-registration", "max_forks_repo_head_hexsha": "0a7d952e566f0117c0d75f77337c23cfc97a3e7f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-20T14:50:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-20T14:50:14.000Z", "avg_line_length": 32.2536231884, "max_line_length": 133, "alphanum_fraction": 0.647494945, "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6225986247642091}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\r\n/*\r\n\r\n    This is an example showing how to define custom kernel functions for use with \r\n    the machine learning tools in the dlib C++ Library.\r\n\r\n    This example assumes you are somewhat familiar with the machine learning\r\n    tools in dlib.  In particular, you should be familiar with the krr_trainer\r\n    and the matrix object.  So you may want to read the krr_classification_ex.cpp\r\n    and matrix_ex.cpp example programs if you haven't already.\r\n*/\r\n\r\n\r\n#include <iostream>\r\n#include <dlib/svm.h>\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n/*\r\n    Here we define our new kernel.  It is the UKF kernel from \r\n        Facilitating the applications of support vector machine by using a new kernel\r\n        by Rui Zhang and Wenjian Wang.\r\n\r\n\r\n    \r\n    In the context of the dlib library a kernel function object is an object with \r\n    an interface with the following properties:\r\n        - a public typedef named sample_type\r\n        - a public typedef named scalar_type which should be a float, double, or \r\n          long double type.\r\n        - an overloaded operator() that operates on two items of sample_type \r\n          and returns a scalar_type.  \r\n        - a public typedef named mem_manager_type that is an implementation of \r\n          dlib/memory_manager/memory_manager_kernel_abstract.h or\r\n          dlib/memory_manager_global/memory_manager_global_kernel_abstract.h or\r\n          dlib/memory_manager_stateless/memory_manager_stateless_kernel_abstract.h \r\n        - an overloaded == operator that tells you if two kernels are\r\n          identical or not.\r\n\r\n    Below we define such a beast for the UKF kernel.  In this case we are expecting the \r\n    sample type (i.e. the T type) to be a dlib::matrix.  However, note that you can design \r\n    kernels which operate on any type you like so long as you meet the above requirements.\r\n*/\r\n\r\ntemplate < typename T >\r\nstruct ukf_kernel\r\n{\r\n    typedef typename T::type             scalar_type;\r\n    typedef          T                   sample_type;\r\n    // If your sample type, the T, doesn't have a memory manager then\r\n    // you can use dlib::default_memory_manager here.\r\n    typedef typename T::mem_manager_type mem_manager_type;\r\n\r\n    ukf_kernel(const scalar_type g) : sigma(g) {}\r\n    ukf_kernel() : sigma(0.1) {}\r\n\r\n    scalar_type sigma;\r\n\r\n    scalar_type operator() (\r\n        const sample_type& a,\r\n        const sample_type& b\r\n    ) const\r\n    { \r\n        // This is the formula for the UKF kernel from the above referenced paper.\r\n        return 1/(length_squared(a-b) + sigma);\r\n    }\r\n\r\n    bool operator== (\r\n        const ukf_kernel& k\r\n    ) const\r\n    {\r\n        return sigma == k.sigma;\r\n    }\r\n};\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n/*\r\n    Here we define serialize() and deserialize() functions for our new kernel.  Defining\r\n    these functions is optional.  However, if you don't define them you won't be able\r\n    to save your learned decision_function objects to disk. \r\n*/\r\n\r\ntemplate < typename T >\r\nvoid serialize ( const ukf_kernel<T>& item, std::ostream& out)\r\n{\r\n    // save the state of the kernel to the output stream\r\n    serialize(item.sigma, out);\r\n}\r\n\r\ntemplate < typename T >\r\nvoid deserialize ( ukf_kernel<T>& item, std::istream& in )\r\n{\r\n    deserialize(item.sigma, in);\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\n/*\r\n    This next thing, the kernel_derivative specialization is optional.  You only need\r\n    to define it if you want to use the dlib::reduced2() or dlib::approximate_distance_function() \r\n    routines.  If so, then you need to supply code for computing the derivative of your kernel as \r\n    shown below.  Note also that you can only do this if your kernel operates on dlib::matrix\r\n    objects which represent column vectors.\r\n*/\r\n\r\nnamespace dlib\r\n{\r\n    template < typename T >\r\n    struct kernel_derivative<ukf_kernel<T> >\r\n    {\r\n        typedef typename T::type             scalar_type;\r\n        typedef          T                   sample_type;\r\n        typedef typename T::mem_manager_type mem_manager_type;\r\n\r\n        kernel_derivative(const ukf_kernel<T>& k_) : k(k_){}\r\n\r\n        sample_type operator() (const sample_type& x, const sample_type& y) const\r\n        {\r\n            // return the derivative of the ukf kernel with respect to the second argument (i.e. y)\r\n            return 2*(x-y)*std::pow(k(x,y),2);\r\n        }\r\n\r\n        const ukf_kernel<T>& k;\r\n    };\r\n}\r\n\r\n// ----------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    // We are going to be working with 2 dimensional samples and trying to perform\r\n    // binary classification on them using our new ukf_kernel.\r\n    typedef matrix<double, 2, 1> sample_type;\r\n\r\n    typedef ukf_kernel<sample_type> kernel_type;\r\n\r\n\r\n    // Now let's generate some training data\r\n    std::vector<sample_type> samples;\r\n    std::vector<double> labels;\r\n    for (double r = -20; r <= 20; r += 0.9)\r\n    {\r\n        for (double c = -20; c <= 20; c += 0.9)\r\n        {\r\n            sample_type samp;\r\n            samp(0) = r;\r\n            samp(1) = c;\r\n            samples.push_back(samp);\r\n\r\n            // if this point is less than 13 from the origin\r\n            if (sqrt(r*r + c*c) <= 13)\r\n                labels.push_back(+1);\r\n            else\r\n                labels.push_back(-1);\r\n\r\n        }\r\n    }\r\n    cout << \"samples generated: \" << samples.size() << endl;\r\n    cout << \"  number of +1 samples: \" << sum(mat(labels) > 0) << endl;\r\n    cout << \"  number of -1 samples: \" << sum(mat(labels) < 0) << endl;\r\n\r\n\r\n    // A valid kernel must always give rise to kernel matrices which are symmetric \r\n    // and positive semidefinite (i.e. have nonnegative eigenvalues).  This next\r\n    // bit of code makes a kernel matrix and checks if it has these properties.\r\n    const matrix<double> K = kernel_matrix(kernel_type(0.1), randomly_subsample(samples, 500));\r\n    cout << \"\\nIs it symmetric? (this value should be 0): \"<< min(abs(K - trans(K))) << endl;\r\n    cout << \"Smallest eigenvalue (should be >= 0):      \"  << min(real_eigenvalues(K)) << endl;\r\n\r\n\r\n    // here we make an instance of the krr_trainer object that uses our new kernel.\r\n    krr_trainer<kernel_type> trainer;\r\n    trainer.use_classification_loss_for_loo_cv();\r\n\r\n\r\n    // Finally, let's test how good our new kernel is by doing some leave-one-out cross-validation.\r\n    cout << \"\\ndoing leave-one-out cross-validation\" << endl;\r\n    for (double sigma = 0.01; sigma <= 100; sigma *= 3)\r\n    {\r\n        // tell the trainer the parameters we want to use\r\n        trainer.set_kernel(kernel_type(sigma));\r\n\r\n        std::vector<double> loo_values; \r\n        trainer.train(samples, labels, loo_values);\r\n\r\n        // Print sigma and the fraction of samples correctly classified during LOO cross-validation.\r\n        const double classification_accuracy = mean_sign_agreement(labels, loo_values);\r\n        cout << \"sigma: \" << sigma << \"     LOO accuracy: \" << classification_accuracy << endl;\r\n    }\r\n\r\n\r\n\r\n\r\n    const kernel_type kern(10);\r\n    // Since it is very easy to make a mistake while coding a derivative it is a good idea\r\n    // to compare your derivative function against a numerical approximation and see if\r\n    // the results are similar.  If they are very different then you probably made a \r\n    // mistake.  So here we compare the results at a test point. \r\n    cout << \"\\nThese vectors should match, if they don't then we coded the kernel_derivative wrong!\" << endl;\r\n    cout << \"approximate derivative: \\n\" <<               derivative(kern)(samples[0],samples[100]) << endl;\r\n    cout << \"exact derivative: \\n\" << kernel_derivative<kernel_type>(kern)(samples[0],samples[100]) << endl;\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "333389460b8e844051265f69c817fa12a783f60c", "size": 8036, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/using_custom_kernels_ex.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/using_custom_kernels_ex.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "examples/using_custom_kernels_ex.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4497607656, "max_line_length": 110, "alphanum_fraction": 0.6114982578, "num_tokens": 1769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7799929002541067, "lm_q1q2_score": 0.6225800197136071}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/ext/boost/mpl/vector.hpp>\n#include <boost/hana/ext/std/integral_constant.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/next.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/vector.hpp>\n\n#include <type_traits>\nnamespace hana = boost::hana;\nnamespace mpl = boost::mpl;\n\n\nnamespace with_mpl {\n//! [mpl]\nusing types = mpl::vector<long, float, short, float, long, long double>;\nusing number_of_floats = mpl::fold<\n    types,\n    mpl::int_<0>,\n    mpl::if_<std::is_floating_point<mpl::_2>,\n        mpl::next<mpl::_1>,\n        mpl::_1\n    >\n>::type;\nstatic_assert(number_of_floats::value == 3, \"\");\n//! [mpl]\n}\n\nnamespace with_hana {\n//! [hana]\nconstexpr auto types = hana::tuple_t<long, float, short, float, long, long double>;\nBOOST_HANA_CONSTEXPR_LAMBDA auto number_of_floats = hana::foldl(\n    types,\n    hana::int_<0>,\n    [](auto count, auto t) {\n        return hana::if_(hana::trait<std::is_floating_point>(t),\n            count + hana::int_<1>,\n            count\n        );\n    }\n);\nBOOST_HANA_CONSTANT_CHECK(number_of_floats == hana::int_<3>);\n//! [hana]\n}\n\nint main() { }\n", "meta": {"hexsha": "443f37e5ad4c61df1dde6aca5fd25f81c21fcc64", "size": 1494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/tutorial/mpl_cheatsheet.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/tutorial/mpl_cheatsheet.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/tutorial/mpl_cheatsheet.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3220338983, "max_line_length": 83, "alphanum_fraction": 0.6793842035, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6225097001806905}}
{"text": "//\n// Created by jack on 9/13/20.\n//\n\n#include \"feature_extracter.h\"\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\n#include \"glog/logging.h\"\n\nnamespace nautilus::input_processing {\n\nstd::vector<Eigen::Vector2f> GetNeighborhood(\n    const std::vector<Eigen::Vector2f>& points, size_t point_index,\n    size_t neighbors_per_side, double max_neighbor_distance) {\n  std::vector<Eigen::Vector2f> neighbors;\n  // Left side neighbors.\n  for (size_t neighbor_idx =\n           std::max(static_cast<size_t>(0), point_index - neighbors_per_side);\n       neighbor_idx < point_index; neighbor_idx++) {\n    if ((points[point_index] - points[neighbor_idx]).norm() <=\n        max_neighbor_distance) {\n      neighbors.push_back(points[neighbor_idx]);\n    }\n  }\n  // Right side neighbors.\n  for (size_t neighbor_idx = point_index + 1;\n       neighbor_idx < std::min(points.size(), point_index + neighbors_per_side);\n       neighbor_idx++) {\n    neighbors.push_back(points[neighbor_idx]);\n  }\n  return neighbors;\n}\n\nEigen::Vector2f ComputeMean(const std::vector<Eigen::Vector2f>& neighborhood) {\n  // Compute the mean and return the mean vector.\n  Eigen::Vector2f mean_vector(0, 0);\n  for (const auto& p : neighborhood) {\n    mean_vector += p;\n  }\n  return (1.0 / neighborhood.size()) * mean_vector;\n}\n\nstd::vector<std::pair<double, Eigen::Vector2f>> ComputeSmoothnessScores(\n    const std::vector<Eigen::Vector2f>& points,\n    std::vector<float>* unsorted_scores, int neighbors_per_side,\n    double max_neighbor_distance, int min_neighbor_num) {\n  // For each point used the smoothness formula.\n  // This formula is computing a scatter matrix for every point and its\n  // neighborhood. Then the smoothness score is the smallest eigenvalue /\n  // largest eigenvalue.\n  std::vector<std::pair<double, Eigen::Vector2f>> smoothness_scores;\n  for (size_t i = 0; i < points.size(); i++) {\n    const auto& point = points[i];\n    // Get the points around point, and then include point.\n    std::vector<Eigen::Vector2f> neighborhood =\n        GetNeighborhood(points, i, neighbors_per_side, max_neighbor_distance);\n    if (neighborhood.size() < static_cast<size_t>(min_neighbor_num)) {\n      // Skip this iteration if not enough neighbors.\n      continue;\n    }\n    neighborhood.push_back(point);\n    // Compute the neighborhood of point and all the points around it.\n    const Eigen::Vector2f mean_vector = ComputeMean(neighborhood);\n    // Now get the scatter matrix using the formula summation from 1 to n of all\n    // points (Xi - m)(Xi - m)^T\n    Eigen::Matrix2f scatter_matrix;\n    scatter_matrix << 0, 0, 0, 0;\n    for (const auto& p : neighborhood) {\n      Eigen::Matrix2f temp =\n          (p - mean_vector) * ((p - mean_vector).transpose());\n      scatter_matrix += temp;\n    }\n    Eigen::EigenSolver<Eigen::Matrix2f> eigen_solver;\n    eigen_solver.compute(scatter_matrix);\n    // Smoothness score is smaller eigen value / larger eigen value so it is [0,\n    // 1].\n    auto eigen_values = eigen_solver.eigenvalues();\n    CHECK_EQ(eigen_values.rows(), 2);\n    double eigen_value_1 = eigen_values(0, 0).real();\n    double eigen_value_2 = eigen_values(1, 0).real();\n    double smoothness_score = std::min(eigen_value_1, eigen_value_2) /\n                              std::max(eigen_value_1, eigen_value_2);\n    if (smoothness_score < 0 || smoothness_score > 1) {\n      std::cout << smoothness_score << std::endl;\n      std::cout << \"Eigen Values: \" << eigen_value_1 << \" \" << eigen_value_2\n                << std::endl;\n    }\n    smoothness_scores.emplace_back(smoothness_score, point);\n    unsorted_scores->push_back(smoothness_score);\n  }\n  return smoothness_scores;\n}\n\nFeatureExtractor::FeatureExtractor(const std::vector<Eigen::Vector2f>& points,\n                                   double threshold, double distance_threshold,\n                                   int neighbor_num, int max_edge_num,\n                                   int max_planar_num, int min_neighbor_num)\n    : threshold_(threshold),\n      distance_threshold_(distance_threshold),\n      neighbors_per_side_(neighbor_num),\n      max_edge_number_(max_edge_num),\n      max_planar_number_(max_planar_num),\n      min_neighbor_num_(min_neighbor_num) {\n  // Compute the smoothness scores of every point once.\n  smoothness_points_ =\n      ComputeSmoothnessScores(points, &unordered_scores_, neighbors_per_side_,\n                              max_neighbor_distance_, min_neighbor_num_);\n  // Now sort the points based on their smoothness.\n  std::sort(smoothness_points_.begin(), smoothness_points_.end(),\n            [](const std::pair<double, Eigen::Vector2f>& point_a,\n               const std::pair<double, Eigen::Vector2f>& point_b) {\n              return point_a.first < point_b.first;\n            });\n}\n\nbool validFeaturePoint(std::pair<double, Eigen::Vector2f> point,\n                       std::vector<Eigen::Vector2f> points, double threshold,\n                       double distance_threshold, size_t max_size,\n                       bool is_edge = false) {\n  // Planar points must be less than the threshold, and edge points must be more\n  // than the threshold.\n  if (!is_edge && point.first > threshold) {\n    return false;\n  }\n  if (is_edge && point.first < threshold) {\n    return false;\n  }\n  // We can accept points.\n  if (points.size() >= max_size) {\n    return false;\n  }\n  // Not close to any of the other points.\n  for (const auto& p : points) {\n    if ((p - point.second).norm() < distance_threshold) {\n      return false;\n    }\n  }\n  return true;\n}\n\nstd::vector<Eigen::Vector2f> FeatureExtractor::GetPlanarPoints() {\n  std::vector<Eigen::Vector2f> planar_points;\n  // Super simple O(n^2) algorithm to find the planar points.\n  for (size_t i = 0; i < smoothness_points_.size(); i++) {\n    if (validFeaturePoint(smoothness_points_[i], planar_points, threshold_,\n                          distance_threshold_, max_planar_number_)) {\n      planar_points.push_back(smoothness_points_[i].second);\n    }\n  }\n  return planar_points;\n}\n\nstd::vector<Eigen::Vector2f> FeatureExtractor::GetEdgePoints() {\n  std::vector<Eigen::Vector2f> edge_points;\n  for (int i = smoothness_points_.size() - 1; i >= 0; i--) {\n    if (validFeaturePoint(smoothness_points_[i], edge_points, threshold_,\n                          distance_threshold_, max_edge_number_, true)) {\n      edge_points.push_back(smoothness_points_[i].second);\n    }\n  }\n  return edge_points;\n}\n\nstd::vector<float> FeatureExtractor::GetSmoothnessScores() {\n  return unordered_scores_;\n}\n}  // namespace nautilus::input_processing\n", "meta": {"hexsha": "8422fa340a6f12a61e154a5a9aa6252d951427d2", "size": 6556, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/input/feature_extracter.cc", "max_stars_repo_name": "ut-amrl/nautilus", "max_stars_repo_head_hexsha": "d7c1f5b03e7bea54be87565da2a8845b044a28b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T19:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T19:17:15.000Z", "max_issues_repo_path": "src/input/feature_extracter.cc", "max_issues_repo_name": "ut-amrl/nautilus", "max_issues_repo_head_hexsha": "d7c1f5b03e7bea54be87565da2a8845b044a28b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-08-27T20:49:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-25T22:40:49.000Z", "max_forks_repo_path": "src/input/feature_extracter.cc", "max_forks_repo_name": "ut-amrl/nautilus", "max_forks_repo_head_hexsha": "d7c1f5b03e7bea54be87565da2a8845b044a28b5", "max_forks_repo_licenses": ["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.3391812865, "max_line_length": 80, "alphanum_fraction": 0.6694630872, "num_tokens": 1598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6225096938312161}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <g2o/core/auto_differentiation.h>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <chrono>\n#include <sophus/se3.hpp>\n\nusing namespace std;\nusing namespace cv;\n\nvoid find_feature_matches(const Mat &img_1, const Mat &img_2,\n                          std::vector<KeyPoint> &keypoints_1,\n                          std::vector<KeyPoint> &keypoints_2,\n                          std::vector<DMatch> &matches) {\n  Mat descriptors_1, descriptors_2;\n  // used in OpenCV3\n  Ptr<FeatureDetector> detector = ORB::create();\n  Ptr<DescriptorExtractor> descriptor = ORB::create();\n  // use this if you are in OpenCV2\n  // Ptr<FeatureDetector> detector = FeatureDetector::create ( \"ORB\" );\n  // Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( \"ORB\" );\n  Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n  detector->detect(img_1, keypoints_1);\n  detector->detect(img_2, keypoints_2);\n\n  descriptor->compute(img_1, keypoints_1, descriptors_1);\n  descriptor->compute(img_2, keypoints_2, descriptors_2);\n\n  vector<DMatch> match;\n  // BFMatcher matcher ( NORM_HAMMING );\n  matcher->match(descriptors_1, descriptors_2, match);\n\n  double min_dist = 10000, max_dist = 0;\n\n  for (int i = 0; i < descriptors_1.rows; i++) {\n    double dist = match[i].distance;\n    if (dist < min_dist) min_dist = dist;\n    if (dist > max_dist) max_dist = dist;\n  }\n\n  printf(\"-- Max dist : %f \\n\", max_dist);\n  printf(\"-- Min dist : %f \\n\", min_dist);\n\n  for (int i = 0; i < descriptors_1.rows; i++) {\n    if (match[i].distance <= max(2 * min_dist, 30.0)) {\n      matches.push_back(match[i]);\n    }\n  }\n}\n\nPoint2d pixel2cam(const Point2d &p, const Mat &K) {\n  return Point2d(\n    (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n    (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n  );\n}\n\n\n\n// Solve ICP with linear algebra (SVD solution)\nvoid pose_estimation_3d3d(vector<Eigen::Vector3d> pts1,\n                          vector<Eigen::Vector3d> pts2,\n                          Eigen::Matrix3d &R, Eigen::Vector3d &t) {\n  Eigen::Vector3d c1(0.0, 0.0, 0.0), c2(0.0, 0.0, 0.0);\n  for (auto& p : pts1)\n    c1 += p;\n  c1 /= pts1.size();\n  for (auto& p : pts2)\n    c2 += p;\n  c2 /= pts2.size();\n\n  for (auto& p : pts1)\n    p -= c1;\n  for (auto& p : pts2)\n    p -= c2;\n  \n  Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n  for (int i = 0; i < pts1.size(); ++i)\n  {\n    W += pts1[i] * pts2[i].transpose();\n  }\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  R = svd.matrixU() * svd.matrixV().transpose();\n  if (R.determinant() < 0)\n    R = -R;\n\n  t = c1 - R * c2;\n}\n\nclass VertexPose: public g2o::BaseVertex<6, Sophus::SE3d>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n      \n    virtual void setToOriginImpl() override {\n      _estimate = Sophus::SE3d();\n    }\n\n    virtual void oplusImpl(const double* update) override {\n      Eigen::Matrix<double, 6, 1> u;\n      u << update[0], update[1], update[2], update[3], update[4], update[5];\n      _estimate = Sophus::SE3d::exp(u) * _estimate;\n    }\n\n  virtual bool read(istream &in) override {}\n  virtual bool write(ostream &out) const override {}\n};\n\n\nclass EdgeICP: public g2o::BaseUnaryEdge<3, Eigen::Vector3d, VertexPose>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n    EdgeICP(const Eigen::Vector3d& X2): _X2(X2) {}\n\n    virtual void computeError() override {\n      const VertexPose* v = static_cast<VertexPose*>(_vertices[0]);\n      Sophus::SE3d Rt = v->estimate();\n      _error = measurement() - Rt * _X2;\n    }\n\n    virtual void linearizeOplus() override {\n      // fill _jacobianOPlusXi;\n      const VertexPose* v = static_cast<VertexPose*>(_vertices[0]);\n      Sophus::SE3d Rt = v->estimate();\n      Eigen::Vector3d X2_transf = Rt * _X2;\n      _jacobianOplusXi.block<3, 3>(0, 0) = -Eigen::Matrix3d::Identity();\n      _jacobianOplusXi.block<3, 3>(0, 3) = Sophus::SO3d::hat(X2_transf);\n    }\n\n    // Auto-diff is not working well. No idea why\n    // template <class T>\n    // bool operator() (const T* params, T* errors) const {\n    //   const Eigen::Map<const Sophus::SE3<T>> Rt_sophus(params);\n    //   Eigen::Matrix<T, 3, 1> X2(T(_X2.x()), T(_X2.y()), T(_X2.z()));\n    //   Eigen::Matrix<T, 3, 1> X2_transf = Rt_sophus * X2;\n    //   errors[0] = T(_measurement[0]) - X2_transf.x();\n    //   errors[1] = T(_measurement[1]) - X2_transf.y();\n    //   errors[2] = T(_measurement[2]) - X2_transf.z();\n    //   return true;\n    // }\n    // G2O_MAKE_AUTO_AD_FUNCTIONS;\n\n\n\n    virtual bool read(std::istream&) override {}\n    virtual bool write(std::ostream&) const override {}\n\n  private:\n    Eigen::Vector3d _X2;\n};\n\n\n// Solve ICP with non-linear optimization\nvoid bundleAdjustment(\n  const vector<Eigen::Vector3d> &pts1,\n  const vector<Eigen::Vector3d> &pts2,\n  Eigen::Matrix3d &R, Eigen::Vector3d &t) {\n\n    Sophus::SE3d pose_init(R, t);\n\n    typedef g2o::BlockSolverX BlockSolverType;\n    typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType;\n    auto solver = new g2o::OptimizationAlgorithmLevenberg(\n      g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm(solver);\n    optimizer.setVerbose(true);\n\n    VertexPose *vertex_pose = new VertexPose();\n    vertex_pose->setId(0);\n    vertex_pose->setEstimate(pose_init);\n    optimizer.addVertex(vertex_pose);\n\n    for (int i = 0; i < pts1.size(); ++i)\n    {\n      EdgeICP *edge = new EdgeICP(pts2[i]);\n      edge->setVertex(0, vertex_pose);\n      edge->setMeasurement(pts1[i]);\n      edge->setInformation(Eigen::Matrix3d::Identity());\n      optimizer.addEdge(edge);\n    }\n\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    optimizer.initializeOptimization();\n    optimizer.optimize(50);\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"optimization ICP costs time: \" << time_used.count() << \" seconds.\" << endl;\n    \n    Sophus::SE3d optim_pose = vertex_pose->estimate();\n    R = optim_pose.so3().unit_quaternion().toRotationMatrix();\n    t = optim_pose.translation();\n  }\n\nint main(int argc, char **argv) {\n  // if (argc != 5) {\n  //   cout << \"usage: pose_estimation_3d3d img1 img2 depth1 depth2\" << endl;\n  //   return 1;\n  // }\n  string f1 = \"../1.png\"; //argv[1];\n  string f2 = \"../2.png\"; //argv[2];\n  string f3 = \"../1_depth.png\"; //argv[3];\n  string f4 = \"../2_depth.png\"; //argv[3];\n\n  Mat img_1 = imread(f1, CV_LOAD_IMAGE_COLOR);\n  Mat img_2 = imread(f2, CV_LOAD_IMAGE_COLOR);\n\n  vector<KeyPoint> keypoints_1, keypoints_2;\n  vector<DMatch> matches;\n  find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n\n  Mat depth1 = imread(f3, CV_LOAD_IMAGE_UNCHANGED);\n  Mat depth2 = imread(f4, CV_LOAD_IMAGE_UNCHANGED);\n  Mat K = (Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n  Eigen::Matrix3d K_eigen;\n  K_eigen << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1;\n  std::vector<Eigen::Vector3d> pts1, pts2;\n\n  for (DMatch m:matches) {\n    ushort d1 = depth1.ptr<unsigned short>(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)];\n    ushort d2 = depth2.ptr<unsigned short>(int(keypoints_2[m.trainIdx].pt.y))[int(keypoints_2[m.trainIdx].pt.x)];\n    if (d1 == 0 || d2 == 0)   // bad depth\n      continue;\n    Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n    Point2d p2 = pixel2cam(keypoints_2[m.trainIdx].pt, K);\n    float dd1 = float(d1) / 5000.0;\n    float dd2 = float(d2) / 5000.0;\n    pts1.push_back(Eigen::Vector3d(p1.x * dd1, p1.y * dd1, dd1));\n    pts2.push_back(Eigen::Vector3d(p2.x * dd2, p2.y * dd2, dd2));\n  }\n\n  cout << \"3d-3d pairs: \" << pts1.size() << endl;\n  Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\n  Eigen::Vector3d t = Eigen::Vector3d::Zero();\n  pose_estimation_3d3d(pts1, pts2, R, t);\n  cout << \"ICP via SVD results: \" << endl;\n  cout << \"R = \" << R << endl;\n  cout << \"t = \" << t.transpose() << endl;\n  // cout << \"R_inv = \" << R.t() << endl;\n  // cout << \"t_inv = \" << -R.t() * t << endl;\n\n  // verify p1 = R * p2 + t\n  double total_error = 0.0;\n  for (int i = 0; i < pts1.size(); i++) {\n    total_error += (pts1[i] - (R * pts2[i] + t)).norm();\n  }\n  std::cout << \"Mean error (SVD): \" << total_error / pts1.size() << \"\\n\";\n\n\n  cout << \"calling bundle adjustment\" << endl;\n  R = Eigen::Matrix3d::Identity();\n  t = Eigen::Vector3d::Zero();\n  bundleAdjustment(pts1, pts2, R, t);\n\n  // verify p1 = R * p2 + t\n  total_error = 0.0;\n  for (int i = 0; i < pts1.size(); i++) {\n    total_error += (pts1[i] - (R * pts2[i] + t)).norm();\n  }\n  std::cout << \"Mean error (BA): \" << total_error / pts1.size() << \"\\n\";\n}\n\n", "meta": {"hexsha": "3e3b2e687dd1430ec6d0886ee16cb7a7c47ce69d", "size": 9228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7/pose_estimation_3d3d_icp.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch7/pose_estimation_3d3d_icp.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch7/pose_estimation_3d3d_icp.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1942446043, "max_line_length": 113, "alphanum_fraction": 0.6315561335, "num_tokens": 2981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6225096910237348}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n// With contributions from Cornelius Steinhardt\n\n#ifndef MTL_MATRIX_LU_INCLUDE\n#define MTL_MATRIX_LU_INCLUDE\n\n#include <cmath>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/utility/lu_matrix_type.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/matrix/upper.hpp>\n#include <boost/numeric/mtl/matrix/lower.hpp>\n#include <boost/numeric/mtl/matrix/permutation.hpp>\n#include <boost/numeric/mtl/operation/adjoint.hpp>\n#include <boost/numeric/mtl/operation/lower_trisolve.hpp>\n#include <boost/numeric/mtl/operation/upper_trisolve.hpp>\n#include <boost/numeric/mtl/operation/max_pos.hpp>\n#include <boost/numeric/mtl/operation/swap_row.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl { namespace matrix {\n\n/// LU factorization in place (without pivoting and optimization so far)\n/** eps is tolerance for pivot element. If less or equal the matrix is considered singular.\n    eps is given as double right now, might be refactored to the magnitude type of the value type in the future. **/\ntemplate <typename Matrix>\nvoid inline lu(Matrix& LU, double eps= 0)\n{\n    vampir_trace<5023> tracer;\n    using std::abs;\n    MTL_THROW_IF(num_rows(LU) != num_cols(LU), matrix_not_square());\n\n    for (std::size_t k= 0; k < num_rows(LU)-1; k++) {\n\tif(abs(LU[k][k]) <= eps) throw matrix_singular(); \n\tirange r(k+1, imax); // Interval [k+1, n-1]\n\tLU[r][k]/= LU[k][k];\n\tLU[r][r]-= LU[r][k] * LU[k][r];\n    }\n}\n\n/// LU factorization in place (with pivoting and without optimization so far)\n/** eps is tolerance for pivot element. If less or equal the matrix is considered singular.\n    eps is given as double right now, might be refactored to the magnitude type of the value type in the future. **/\ntemplate <typename Matrix, typename PermuationVector>\nvoid inline lu(Matrix& A, PermuationVector& P, double eps= 0)\n{\n    vampir_trace<5024> tracer;\n    using math::zero; using std::abs;\n    typedef typename Collection<Matrix>::size_type    size_type;\n    size_type ncols = num_cols(A), nrows = num_rows(A);\n\n    MTL_THROW_IF(ncols != nrows , matrix_not_square());\n    P.change_dim(nrows);\n\n    for (size_type i= 0; i < nrows; i++)\n        P[i]= i;\n\n    for (size_type i= 0; i < nrows-1; i++) {\n\tirange r(i+1, imax), ir(i, i+1); // Intervals [i+1, n-1], [i, i]\n\tsize_type rmax= max_abs_pos(A[irange(i, imax)][ir]).first + i;\n\tswap_row(A, i, rmax); \n\tswap_row(P, i, rmax);\n\t\n\tif(abs(A[i][i]) <= eps) throw matrix_singular(); // other gmres test doesn't work\n       \n\tA[r][i]/= A[i][i];              // Scale column i\n\tA[r][r]-= A[r][i] * A[i][r]; \t // Decrease bottom right block of matrix\n    }\n}\n\n\n/// LU factorization without factorization that returns the matrix\n/** eps is tolerance for pivot element. If less or equal the matrix is considered singular.\n    eps is given as double right now, might be refactored to the magnitude type of the value type in the future. **/\ntemplate <typename Matrix>\nMatrix inline lu_f(const Matrix& A, double eps= 0)\n{\n    vampir_trace<5025> tracer;\n    Matrix LU(A);\n    lu(LU, eps);\n    return LU;\n}\n\n/// Solve Ax = b by LU factorization without pivoting; vector x is returned\ntemplate <typename Matrix, typename Vector>\nVector inline lu_solve_straight(const Matrix& A, const Vector& b, double eps= 0)\n{\n    vampir_trace<5026> tracer;\n    Matrix LU(A);\n    lu(LU, eps);\n    return upper_trisolve(upper(LU), unit_lower_trisolve(strict_lower(LU), b));\n}\n\n/// Solve LUx = b by with forward and backward-LU subsitution, lu(LU) was allready done\ntemplate <typename Matrix, typename Vector>\nVector inline lu_solve_apply(const Matrix& LU, const Vector& b)\n{\n    vampir_trace<5026> tracer;\n    return upper_trisolve(upper(LU), unit_lower_trisolve(strict_lower(LU), b));\n}\n\n/// Apply the factorization L*U with permutation P on vector b to solve Ax = b\ntemplate <typename Matrix, typename PermVector, typename Vector>\nVector inline lu_apply(const Matrix& LU, const PermVector& P, const Vector& b)\n{\n    vampir_trace<5027> tracer;\n    return upper_trisolve(upper(LU), unit_lower_trisolve(strict_lower(LU), Vector(matrix::permutation(P) * b)));\n}\n\n\n/// Solve Ax = b by LU factorization with column pivoting; vector x is returned\ntemplate <typename Matrix, typename Vector>\nVector inline lu_solve(const Matrix& A, const Vector& b, double eps= 0)\n{\n    vampir_trace<5028> tracer;\n    mtl::vector::dense_vector<std::size_t, vector::parameters<> > P(num_rows(A));\n    Matrix                    LU(A);\n\n    lu(LU, P, eps);\n    return lu_apply(LU, P, b);\n}\n\n\n/// Apply the factorization L*U with permutation P on vector b to solve adjoint(A)x = b\n/** That is \\f$P^{-1}(LU)^H x = b\\f$ --> \\f$x= P^{-1}L^{-H} U^{-H} b\\f$ where \\f$P^{{-1}^{{-1}^H}} = P^{-1}\\f$ **/\ntemplate <typename Matrix, typename PermVector, typename Vector>\nVector inline lu_adjoint_apply(const Matrix& LU, const PermVector& P, const Vector& b)\n{\n    vampir_trace<5029> tracer;\n    return Vector(trans(matrix::permutation(P)) * unit_upper_trisolve(adjoint(LU), lower_trisolve(adjoint(LU), b)));\n}\n\n\n/// Solve \\f$adjoint(A)x = b\\f$ by LU factorization with column pivoting; vector x is returned\ntemplate <typename Matrix, typename Vector>\nVector inline lu_adjoint_solve(const Matrix& A, const Vector& b, double eps= 0)\n{\n    vampir_trace<5030> tracer;\n    mtl::vector::dense_vector<std::size_t, vector::parameters<> > P(num_rows(A));\n    Matrix                    LU(A);\n\n    lu(LU, P, eps);\n    return lu_adjoint_apply(LU, P, b);\n}\n\n/// Class that keeps LU factorization (and permutation); using column pivoting\ntemplate <typename Matrix>\nclass lu_solver\n{\n    typedef typename mtl::traits::lu_matrix_type<Matrix>::type            matrix_type;\n    typedef mtl::vector::dense_vector<std::size_t, vector::parameters<> > permutation_type;\n  public:\n    /// Construct from matrix \\p A and use optionally threshold \\p eps in factorization\n    explicit lu_solver(const Matrix& A, double eps= 0) \n      : LU(A), P(num_rows(A))\n    {\n\tlu(LU, P, eps);\n    }\n\n    /// Solve A*x = b with factorization from constructor\n    template <typename VectorIn, typename VectorOut>\n    void solve(const VectorIn& b, VectorOut& x) const\n    {\n\tx= upper_trisolve(upper(LU), unit_lower_trisolve(strict_lower(LU), VectorIn(matrix::permutation(P) * b)));\n    }\n    /// Solve \\f$adjoint(A)x = b\\f$ using LU factorization\n    template <typename VectorIn, typename VectorOut>\n    void adjoint_solve(const VectorIn& b, VectorOut& x) const\n    {\n\tx= trans(matrix::permutation(P)) * unit_upper_trisolve(adjoint(LU), lower_trisolve(adjoint(LU), b));\n    }\n\n  private:\n    matrix_type      LU;\n    permutation_type P;\n};\n\n\n}} // namespace mtl::matrix \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// ### For illustration purposes\n#if 0\n\nnamespace mtl { namespace matrix {\n\ntemplate <typename Matrix>\nvoid inline lu(Matrix& LU)\n{\n    MTL_THROW_IF(num_rows(LU) != num_cols(LU), matrix_not_square());\n\n    typedef typename Collection<Matrix>::value_type   value_type;\n    typedef typename Collection<Matrix>::size_type    size_type;\n\n    size_type n= num_rows(LU);\n    for (size_type k= 0; k < num_rows(LU); k++) {\n\tvalue_type pivot= LU[k][k];\n\tfor (size_type j= k+1; j < n; j++) {\n\t    value_type alpha= LU[j][k]/= pivot;\n\t    for (size_type i= k+1; i < n; i++)\n\t\tLU[j][i]-= alpha * LU[k][i];\n\t}\n    }\n}\n\n\n\n}} // namespace mtl::matrix\n\n#endif\n\n#endif // MTL_MATRIX_LU_INCLUDE\n", "meta": {"hexsha": "a80c60f86d4a5bbc48a9be245c6c9d00e9d979e1", "size": 7910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/lu.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/lu.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/operation/lu.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6859504132, "max_line_length": 116, "alphanum_fraction": 0.6901390645, "num_tokens": 2193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095497, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6225096881901401}}
{"text": "#include <iostream>\n#include <typeinfo>\r\n#define BOOST_TEST_MODULE DenseMIAMultTests\n#include \"MIAConfig.h\"\r\n#ifdef MIA_USE_HEADER_ONLY_TESTS\r\n#include <boost/test/included/unit_test.hpp>\r\n#else\r\n#include <boost/test/unit_test.hpp>\r\n#endif\r\n\n#include \"DenseMIA.h\"\n#include \"Index.h\"\n\n\n\n\n\r\ntemplate<class _data_type>\r\nvoid mult_work(size_t dim1, size_t dim2){\r\n\r\n    LibMIA::MIAINDEX i;\n    LibMIA::MIAINDEX j;\n    LibMIA::MIAINDEX k;\r\n    LibMIA::MIAINDEX l;\r\n    LibMIA::MIAINDEX m;\r\n    LibMIA::MIAINDEX n;\n\n    LibMIA::DenseMIA<_data_type,4> a(dim1,dim2,dim1,dim2);\r\n    LibMIA::DenseMIA<_data_type,4> b(dim2,dim2,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,2> b2(dim2,dim2);\r\n\r\n    LibMIA::DenseMIA<_data_type,4> c;\r\n    LibMIA::DenseMIA<_data_type,2> c2;\r\n    LibMIA::DenseMIA<_data_type,4> c_result(dim1,dim1,dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,2> c_result2(dim1,dim1);\r\n    LibMIA::DenseMIA<_data_type,4> c_result3(dim1,dim2,dim1,dim2);\r\n    LibMIA::DenseMIA<_data_type,4> c_result4(dim2,dim2,dim2,dim2);\r\n\r\n    LibMIA::DenseMIA<_data_type,1> d(dim2);\r\n    LibMIA::DenseMIA<_data_type,2> d2(dim2,dim2);\r\n\r\n    b.ones();\r\n\r\n    //set each the values of a to increment along inner product indices\r\n    size_t val,entries=((dim2*dim2+1)*dim2*dim2)/2;\r\n    for(size_t _i=0;_i<dim1;++_i){\r\n        for(size_t _k=0;_k<dim1;++_k){\r\n            val=1;\r\n            for(size_t _j=0;_j<dim2;++_j){\r\n                for(size_t _l=0;_l<dim2;++_l){\r\n                    a.at(_i,_j,_k,_l)=val++;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n    for(size_t _i=0;_i<dim1;++_i){\r\n        for(size_t _j=0;_j<dim1;++_j){\r\n\r\n            for(size_t _k=0;_k<dim1;++_k){\r\n                for(size_t _l=0;_l<dim1;++_l){\r\n                    c_result.at(_i,_j,_k,_l)=entries;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    c(i,k,m,n)=a(i,j,k,l)*b(j,l,m,n);\r\n    BOOST_CHECK_MESSAGE(c==c_result,std::string(\"Inner/Outer Product 1 for \")+typeid(_data_type).name() );\r\n\r\n\r\n    c(i,k,m,n)=a(i,l,k,j)*b(l,j,m,n);\r\n    BOOST_CHECK_MESSAGE(c==c_result,std::string(\"Inner/Outer Product 2 for \")+typeid(_data_type).name());\r\n\r\n    c(i,k,m,n)=a(i,j,k,l)*b(l,j,m,n);\r\n    BOOST_CHECK_MESSAGE(c==c_result,std::string(\"Inner/Outer Product 3 for \")+typeid(_data_type).name());\r\n\r\n//    test inner and element-wise product. Have b be assigned a scalar value that increases while traversing i\r\n    val=0;\r\n    for(size_t _i=0;_i<dim1;++_i){\r\n        val++;\r\n        for(size_t _j=0;_j<dim1;++_j){\r\n            c_result2.at(_i,_j)=val*entries;\r\n            for(size_t _k=0;_k<dim2;++_k){\r\n                for(size_t _l=0;_l<dim2;++_l){\r\n                    b.at(_k,_l,_i,_j)=val;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    c2(i,j)=a(!i,k,!j,l)*b(k,l,!i,!j);\r\n    BOOST_CHECK_MESSAGE(c2==c_result2,std::string(\"Inner/Element-Wise Product 1 for \")+typeid(_data_type).name());\r\n\r\n\r\n    c2(i,j)=a(!i,l,!j,k)*b(k,l,!i,!j);\r\n    BOOST_CHECK_MESSAGE(c2==c_result2,std::string(\"Inner/Element-Wise Product 2 for \")+typeid(_data_type).name());\r\n    c2(j,i)=a(!j,l,!i,k)*b(k,l,!j,!i);\r\n    BOOST_CHECK_MESSAGE(c2==c_result2,std::string(\"Inner/Element-Wise Product 3 for \")+typeid(_data_type).name());\r\n\r\n    //test inter outer products\r\n    val=1;\r\n    a.ones();\r\n    for(size_t _i=0;_i<dim2;++_i){\r\n\r\n        for(size_t _j=0;_j<dim2;++_j){\r\n            b2.at(_i,_j)=val++;\r\n        }\r\n    }\r\n\r\n    c_result3.zeros();\r\n    for(size_t _i=0;_i<dim1;++_i){\r\n        for(size_t _k=0;_k<dim1;++_k){\r\n            val=1;\r\n            for(size_t _j=0;_j<dim2;++_j){\r\n                for(size_t _l=0;_l<dim2;++_l){\r\n                    c_result3.at(_i,_j,_k,_l)=val++;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    c(i,j,k,l)=a(i,!j,k,!l)*b2(!j,!l);\r\n\r\n\r\n    BOOST_CHECK_MESSAGE(c==c_result3,std::string(\"Outer/Element-Wise Product 1 for \")+typeid(_data_type).name());\r\n    c(i,j,k,l)=a(k,!j,i,!l)*b2(!j,!l);\r\n    BOOST_CHECK_MESSAGE(c==c_result3,std::string(\"Outer/Element-Wise Product 2 for \")+typeid(_data_type).name());\r\n\r\n    c(i,j,k,l)=a(k,!l,i,!j)*b2(!j,!l);\r\n    BOOST_CHECK_MESSAGE(c==c_result3,std::string(\"Outer/Element-Wise Product 3 for \")+typeid(_data_type).name());\r\n\r\n\r\n    c_result4.zeros();\r\n    for(size_t _i=0;_i<dim2;++_i){\r\n        for(size_t _j=0;_j<dim2;++_j){\r\n            val=1;\r\n            for(size_t _k=0;_k<dim2;++_k){\r\n                for(size_t _l=0;_l<dim2;++_l){\r\n                    c_result4.at(_i,_j,_k,_l)=val++;\r\n                }\r\n            }\r\n        }\r\n    }\r\n    d2.ones();\r\n    c(i,j,k,l)=b2(k,l)*d2(i,j);\r\n    BOOST_CHECK_MESSAGE(c==c_result4,std::string(\"Outer/Outer Product 1 for \")+typeid(_data_type).name());\r\n\r\n    c(i,j,k,l)=b2(k,l)*d2(j,i);\r\n    BOOST_CHECK_MESSAGE(c==c_result4,std::string(\"Outer/Outer Product 2 for \")+typeid(_data_type).name());\r\n\r\n    c(i,j,k,l)=d2(j,i)*b2(k,l);\r\n    BOOST_CHECK_MESSAGE(c==c_result4,std::string(\"Outer/Outer Product 3 for \")+typeid(_data_type).name());\r\n\r\n\r\n\r\n\r\n    val=1;\r\n    for(size_t _i=0;_i<dim2;++_i)\r\n        d.at(_i)=val++;\r\n\r\n    size_t val2;\r\n    c_result3.zeros();\r\n    for(size_t _i=0;_i<dim1;++_i){\r\n        for(size_t _k=0;_k<dim1;++_k){\r\n            val=1;\r\n            for(size_t _j=0;_j<dim2;++_j){\r\n                val2=1;\r\n                for(size_t _l=0;_l<dim2;++_l){\r\n                    c_result3.at(_i,_j,_k,_l)=val++*val2++;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n    c(i,j,k,l)=~(a(i,!j,k,!!l)*b2(!j,!!l))*d(!l);\r\n    BOOST_CHECK_MESSAGE(c==c_result3,std::string(\"Repeated Element-Wise Product 1 for \")+typeid(_data_type).name());\r\n\r\n    //repeat inner/outer product test but use a ternary inner product instead\r\n    d2.ones();\r\n    b.ones();\r\n    for(size_t _i=0;_i<dim1;++_i){\r\n        for(size_t _k=0;_k<dim1;++_k){\r\n            val=1;\r\n            for(size_t _j=0;_j<dim2;++_j){\r\n                for(size_t _l=0;_l<dim2;++_l){\r\n                    a.at(_i,_j,_k,_l)=val++;\r\n                }\r\n            }\r\n        }\r\n    }\r\n    c(i,k,m,n)=~(a(i,!j,k,!l)*b(!j,!l,m,n))*d2(j,l);\r\n    BOOST_CHECK_MESSAGE(c==c_result,std::string(\"Ternary Inner Product 1 for \")+typeid(_data_type).name() );\r\n    c(i,k,m,n)=~(a(i,!j,k,!l)*b(!j,!l,m,n))*d2(l,j);\r\n    BOOST_CHECK_MESSAGE(c==c_result,std::string(\"Ternary Inner Product 2 for \")+typeid(_data_type).name() );\r\n    c(i,k,m,n)=~(a(i,!l,k,!j)*b(!j,!l,m,n))*d2(l,j);\r\n    BOOST_CHECK_MESSAGE(c==c_result,std::string(\"Ternary Inner Product 3 for \")+typeid(_data_type).name() );\r\n\r\n\r\n    //now we test two MIAs get reduced down to data_type because of a pure inner product\r\n    d.ones();\r\n    _data_type _data=d(l)*d(l);\r\n    BOOST_CHECK_MESSAGE(_data==d.dim(0),std::string(\"Complete reduction 1 via inner product \")+typeid(_data_type).name() );\r\n\r\n    d2.ones();\r\n    _data=d2(i,j)*d2(i,j);\r\n    BOOST_CHECK_MESSAGE(_data==d2.dim(0)*d2.dim(1),std::string(\"Complete reduction 2 via inner product \")+typeid(_data_type).name() );\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( DenseMIAMultTests )\n{\n\r\n       // mult_work<double>(2,2);\n\r\n    mult_work<double>(3,3);\n    mult_work<float>(3,3);\r\n    mult_work<int>(3,3);\r\n    mult_work<long>(3,3);\r\n\r\n\r\n    mult_work<double>(4,3);\n    mult_work<float>(4,3);\r\n    mult_work<int>(4,3);\r\n    mult_work<long>(4,3);\r\n\r\n\r\n    mult_work<double>(3,4);\n    mult_work<float>(3,4);\r\n    mult_work<int>(3,4);\r\n    mult_work<long>(3,4);\r\n\n\n}\n", "meta": {"hexsha": "d738c02675f2480228488257a2be1ea04645e994", "size": 7345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/DenseMIA/dense_mia_mult_test.cpp", "max_stars_repo_name": "extragoya/LibNT", "max_stars_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T05:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T05:11:32.000Z", "max_issues_repo_path": "src/tests/DenseMIA/dense_mia_mult_test.cpp", "max_issues_repo_name": "extragoya/LibNT", "max_issues_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/DenseMIA/dense_mia_mult_test.cpp", "max_forks_repo_name": "extragoya/LibNT", "max_forks_repo_head_hexsha": "60372bf4e3c5d6665185358c4756da4fe547f093", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-21T15:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-21T15:38:23.000Z", "avg_line_length": 30.9915611814, "max_line_length": 135, "alphanum_fraction": 0.5528931246, "num_tokens": 2420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6224923648891346}}
{"text": "#ifndef EXPSUM_ESPRIT_HPP\n#define EXPSUM_ESPRIT_HPP\n\n#include <armadillo>\n\nnamespace expsum\n{\n\n//\n// Naive implementation of ESPRIT algorithm\n//\ntemplate <typename T>\nclass esprit\n{\npublic:\n    using size_type   = arma::uword;\n    using value_type  = T;\n    using vector_type = arma::Col<value_type>;\n    using matrix_type = arma::Mat<value_type>;\n\n    using real_type        = typename matrix_type::pod_type;\n    using real_vector_type = arma::Col<real_type>;\n    using real_matrix      = arma::Mat<real_type>;\n\n    using complex_type        = std::complex<real_type>;\n    using complex_vector_type = arma::Col<complex_type>;\n    using complex_matrix_type = arma::Mat<complex_type>;\n\nprivate:\n    constexpr static const bool is_complex =\n        arma::is_complex<value_type>::value;\n\n    size_type nrows_;\n    size_type ncols_;\n    size_type nterms_;\n    complex_vector_type exponent_;\n    complex_vector_type weight_;\n\npublic:\n    // Default constructor\n    esprit() = default;\n\n    //\n    // @N number of sample data\n    // @L window size. This is equals to the number of\n    // rows of generalized Hankel matrix.\n    //\n    // @M maxumum number of terms used for the exponential sum.\n    // `N >= L >= N / 2 + 1 >= 1` and `N - L + 1 >= M >= 1`.\n    //\n    esprit(size_type N, size_type L)\n        : nrows_(L),\n          ncols_(N - L + 1),\n          nterms_(),\n          exponent_(ncols_),\n          weight_(ncols_)\n    {\n        assert(nrows_ >= ncols_ && ncols_ >= 1);\n    }\n    // Default copy constructor\n    esprit(const esprit&) = default;\n    // Defautl move constructor\n    esprit(esprit&&) = default;\n    // Default destructor\n    ~esprit() = default;\n    // Default assignment operator\n    esprit& operator=(const esprit&) = default;\n    // Default move assignment operator\n    esprit& operator=(esprit&& rhs) = default;\n\n    // @return number of sampling data\n    size_type size() const\n    {\n        return nrows_ + ncols_ - 1;\n    }\n\n    // @return number of rows of trajectory matrix\n    size_type nrows() const\n    {\n        return nrows_;\n    }\n\n    // @return number of columns of trajectory matrix. This should be a upper\n    //         bound of the number of exponential functions.\n    size_type ncols() const\n    {\n        return ncols_;\n    }\n\n    //\n    //  Reset data sizes and reallocate memories for working space, if\n    // necessary.\n    //\n    // @N number of sample data\n    // @L window size. This is equals to the number of rows of generalized\n    //    Hankel matrix.\n    // @M maxumum number of terms used for the exponential sum.\n    //    `N >= L >= N / 2 >= 1` and `N - L + 1 >= M >= 1`.\n    //\n    void resize(size_type N, size_type L, size_type M)\n    {\n        nrows_ = L;\n        ncols_ = N - L + 1;\n\n        assert(nrows_ >= M && ncols_ >= M && M >= 1);\n\n        nterms_ = 0;\n        exponent_.resize(M);\n        weight_.resize(M);\n    }\n\n    //\n    // Compute non-linear approximation of by as the exponential sums.\n    //\n    // @f values of the target function sampled on the equispaced grid. The\n    //    first `size()` elemnets of `f` are used as a sampled data.\n    //\n    // @eps small positive number `(0 < eps < 1)` that controlls the accuracy of\n    //      the fit.\n    //\n    // @x0 argument of first sampling data\n    //\n    // @delta spacing between neighbouring sample points\n    //\n    template <typename U>\n    typename std::enable_if<arma::is_arma_type<U>::value>::type\n    fit(const U& f, real_type x0, real_type delta, real_type eps);\n\n    //\n    // @return Vector view to the exponents.\n    //\n    auto exponents() const -> decltype(exponent_.head(nterms_))\n    {\n        return exponent_.head(nterms_);\n    }\n    //\n    // @return Vector view to the weights.\n    //\n    auto weights() const -> decltype(weight_.head(nterms_))\n    {\n        return weight_.head(nterms_);\n    }\n\n    //\n    // Evaluate exponential sum at a point\n    //\n    complex_type eval_at(real_type x) const\n    {\n        return arma::sum(arma::exp(-x * exponents()) % weights());\n    }\n\nprivate:\n    template <typename U>\n    typename std::enable_if<arma::is_arma_type<U>::value>::type\n    compute_nodes(const U& f, real_type eps);\n    void compute_weights(complex_vector_type& b);\n};\n\ntemplate <typename T>\ntemplate <typename U>\ntypename std::enable_if<arma::is_arma_type<U>::value>::type\nesprit<T>::fit(const U& f, real_type x0, real_type delta, real_type eps)\n{\n    assert(f.is_vec() && f.n_elem >= size());\n    assert(real_type() < eps && eps < real_type(1));\n    compute_nodes(f, eps);\n    //\n    // Calculate weights of exponentials\n    //\n    if (nterms_ > 0)\n    {\n        complex_vector_type b(size());\n        for (size_type k = 0; k < size(); ++k)\n        {\n            b(k) = f(k);\n        }\n        compute_weights(b);\n        //\n        // Adjust computed paremeters\n        //\n        auto xi_ = exponent_.head(nterms_);\n        auto w_  = weight_.head(nterms_);\n        xi_      = -arma::log(xi_) / delta;\n        if (x0 != real_type())\n        {\n            w_ %= arma::exp(-xi_ * x0);\n        }\n    }\n}\n\ntemplate <typename T>\ntemplate <typename U>\ntypename std::enable_if<arma::is_arma_type<U>::value>::type\nesprit<T>::compute_nodes(const U& f, real_type eps)\n{\n    //\n    // Setup general fast Hankel matrix-vector product.\n    //\n    matrix_type H(nrows(), ncols());\n    for (size_type j = 0; j < ncols(); ++j)\n    {\n        for (size_type i = 0; i < nrows(); ++i)\n        {\n            H(i, j) = f(i + j);\n        }\n    }\n    // Compute SVD of Hankel matrix H.f\n    real_vector_type sigma(ncols());\n    matrix_type W(ncols(), ncols()); // right singular vector\n    matrix_type dummy;               // left singular vector (not computed)\n    arma::svd_econ(dummy, sigma, W, H, \"right\");\n\n    size_type rank = 1;\n    auto cutoff    = sigma(0) * eps;\n    while (rank < sigma.size())\n    {\n        if (sigma(rank) < cutoff)\n        {\n            break;\n        }\n        ++rank;\n    }\n\n    auto W0 = W.submat(arma::span(0, ncols() - 2), arma::span(0, rank - 1));\n    auto W1 = W.submat(arma::span(1, ncols() - 1), arma::span(0, rank - 1));\n    //\n    // Compute eigenvalue of matrix pencil zA - B, with matrix A, B defined\n    // as follows:\n    //\n    matrix_type A(W0.t() * W0);\n    matrix_type B(W1.t() * W0);\n\n    complex_vector_type eigvals(exponent_.memptr(), rank,\n                                /*copy_aux_mem*/ false, /*struct*/ true);\n    if (!arma::eig_pair(eigvals, B, A))\n    {\n        throw std::runtime_error(\"(esprit::fit) eig_pair failed...\");\n    }\n\n    nterms_ = rank;\n}\n\ntemplate <typename T>\nvoid esprit<T>::compute_weights(complex_vector_type& b)\n{\n    //\n    // Solve (dual) Vanermonde system  V * x = b\n    //\n    //\n    // REMARK: Here exponent(i) contains the value of exp(zeta(i)), not\n    // exponet zeta(i) itself.\n    //\n\n    complex_matrix_type V(b.size(), nterms_);\n    for (size_type i = 0; i < V.n_cols; ++i)\n    {\n        const auto z = exponent_(i);\n        V(0, i) = real_type(1);\n        for (size_type j = 1; j < V.n_rows; ++j)\n        {\n            V(j, i) = V(j - 1, i) * z; // z[i]**j\n        }\n    }\n\n    complex_vector_type x(weight_.memptr(), nterms_, /*copy_aux_mem*/ false,\n                          /*strict*/ true);\n    arma::solve(x, V, b);\n    return;\n}\n\n} // namespace: expsum\n\n#endif /* EXPSUM_ESPRIT_HPP */\n", "meta": {"hexsha": "e36df58dbcbfc4264cb2c5a2a96878c871a6ddb9", "size": 7317, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/fitting/esprit.hpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/expsum/fitting/esprit.hpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/expsum/fitting/esprit.hpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.704379562, "max_line_length": 80, "alphanum_fraction": 0.5749624163, "num_tokens": 1999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199754937772, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6224923643970709}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2019-2020, University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#include <boost/random.hpp>\n#include \"crocoddyl/core/solvers/box-qp.hpp\"\n#include \"unittest_common.hpp\"\n\nusing namespace boost::unit_test;\nusing namespace crocoddyl_unit_test;\n\nvoid test_constructor() {\n  // Setup the test\n  std::size_t nx = random_int_in_range(1, 100);\n  crocoddyl::BoxQP boxqp(nx);\n\n  // Test dimension of the decision vector\n  BOOST_CHECK(boxqp.get_nx() == nx);\n}\n\nvoid test_unconstrained_qp_with_identity_hessian() {\n  std::size_t nx = random_int_in_range(2, 5);\n  crocoddyl::BoxQP boxqp(nx);\n  boxqp.set_reg(0.);\n\n  Eigen::MatrixXd hessian = Eigen::MatrixXd::Identity(nx, nx);\n  Eigen::VectorXd gradient = Eigen::VectorXd::Random(nx);\n  Eigen::VectorXd lb = -std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);\n  Eigen::VectorXd ub = std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);\n  Eigen::VectorXd xinit(nx);\n  crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit);\n\n  // Checking the solution of the problem. Note that it the negative of the gradient since Hessian\n  // is identity matrix\n  BOOST_CHECK((sol.x + gradient).isMuchSmallerThan(1.0, 1e-9));\n\n  // Checking the solution against a regularized case\n  double reg = random_real_in_range(1e-9, 1e2);\n  boxqp.set_reg(reg);\n  crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit);\n  BOOST_CHECK((sol_reg.x + gradient / (1 + reg)).isMuchSmallerThan(1.0, 1e-9));\n\n  // Checking the all bounds are free and zero clamped\n  BOOST_CHECK(sol.free_idx.size() == nx);\n  BOOST_CHECK(sol.clamped_idx.size() == 0);\n  BOOST_CHECK(sol_reg.free_idx.size() == nx);\n  BOOST_CHECK(sol_reg.clamped_idx.size() == 0);\n}\n\nvoid test_unconstrained_qp() {\n  std::size_t nx = random_int_in_range(2, 5);\n  crocoddyl::BoxQP boxqp(nx);\n  boxqp.set_reg(0.);\n\n  Eigen::MatrixXd H = Eigen::MatrixXd::Random(nx, nx);\n  Eigen::MatrixXd hessian = H.transpose() * H;\n  hessian = 0.5 * (hessian + hessian.transpose()).eval();\n  Eigen::VectorXd gradient = Eigen::VectorXd::Random(nx);\n  Eigen::VectorXd lb = -std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);\n  Eigen::VectorXd ub = std::numeric_limits<double>::infinity() * Eigen::VectorXd::Ones(nx);\n  Eigen::VectorXd xinit(nx);\n  crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit);\n\n  // Checking the solution against the KKT solution\n  Eigen::VectorXd xkkt = -hessian.inverse() * gradient;\n  BOOST_CHECK((sol.x - xkkt).isMuchSmallerThan(1.0, 1e-9));\n\n  // Checking the solution against a regularized KKT problem\n  double reg = random_real_in_range(1e-9, 1e2);\n  boxqp.set_reg(reg);\n  crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit);\n  Eigen::VectorXd xkkt_reg = -(hessian + reg * Eigen::MatrixXd::Identity(nx, nx)).inverse() * gradient;\n  BOOST_CHECK((sol_reg.x - xkkt_reg).isMuchSmallerThan(1.0, 1e-9));\n\n  // Checking the all bounds are free and zero clamped\n  BOOST_CHECK(sol.free_idx.size() == nx);\n  BOOST_CHECK(sol.clamped_idx.size() == 0);\n  BOOST_CHECK(sol_reg.free_idx.size() == nx);\n  BOOST_CHECK(sol_reg.clamped_idx.size() == 0);\n}\n\nvoid test_box_qp_with_identity_hessian() {\n  std::size_t nx = random_int_in_range(2, 5);\n  crocoddyl::BoxQP boxqp(nx);\n  boxqp.set_reg(0.);\n\n  Eigen::MatrixXd hessian = Eigen::MatrixXd::Identity(nx, nx);\n  Eigen::VectorXd gradient = Eigen::VectorXd::Ones(nx);\n  for (std::size_t i = 0; i < nx; ++i) {\n    gradient(i) *= random_real_in_range(-1., 1.);\n  }\n  Eigen::VectorXd lb = Eigen::VectorXd::Zero(nx);\n  Eigen::VectorXd ub = Eigen::VectorXd::Ones(nx);\n  Eigen::VectorXd xinit(nx);\n  crocoddyl::BoxQPSolution sol = boxqp.solve(hessian, gradient, lb, ub, xinit);\n\n  // The analytical solution is the a bounded, and negative, gradient\n  Eigen::VectorXd negbounded_gradient(nx), negbounded_gradient_reg(nx);\n  std::size_t nf = nx, nc = 0, nf_reg = nx, nc_reg = 0;\n  double reg = random_real_in_range(1e-9, 1e2);\n  for (std::size_t i = 0; i < nx; ++i) {\n    negbounded_gradient(i) = std::max(std::min(-gradient(i), ub(i)), lb(i));\n    negbounded_gradient_reg(i) = std::max(std::min(-gradient(i) / (1 + reg), ub(i)), lb(i));\n    if (negbounded_gradient(i) != -gradient(i)) {\n      nc += 1;\n      nf -= 1;\n    }\n    if (negbounded_gradient_reg(i) != -gradient(i) / (1 + reg)) {\n      nc_reg += 1;\n      nf_reg -= 1;\n    }\n  }\n\n  // Checking the solution of the problem. Note that it the negative of the gradient since Hessian\n  // is identity matrix\n  BOOST_CHECK((sol.x - negbounded_gradient).isMuchSmallerThan(1.0, 1e-9));\n\n  // Checking the solution against a regularized case\n  boxqp.set_reg(reg);\n  crocoddyl::BoxQPSolution sol_reg = boxqp.solve(hessian, gradient, lb, ub, xinit);\n  BOOST_CHECK((sol_reg.x - negbounded_gradient / (1 + reg)).isMuchSmallerThan(1.0, 1e-9));\n\n  // Checking the all bounds are free and zero clamped\n  BOOST_CHECK(sol.free_idx.size() == nf);\n  BOOST_CHECK(sol.clamped_idx.size() == nc);\n  BOOST_CHECK(sol_reg.free_idx.size() == nf_reg);\n  BOOST_CHECK(sol_reg.clamped_idx.size() == nc_reg);\n}\n\nvoid register_unit_tests() {\n  framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_constructor)));\n  framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_unconstrained_qp_with_identity_hessian)));\n  framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_unconstrained_qp)));\n  framework::master_test_suite().add(BOOST_TEST_CASE(boost::bind(&test_box_qp_with_identity_hessian)));\n}\n\nbool init_function() {\n  register_unit_tests();\n  return true;\n}\n\nint main(int argc, char* argv[]) { return ::boost::unit_test::unit_test_main(&init_function, argc, argv); }\n", "meta": {"hexsha": "edaa0f08eed85a1b16d390bb34ab9ab8d98de68b", "size": 5962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/test_boxqp.cpp", "max_stars_repo_name": "Capri2014/crocoddyl", "max_stars_repo_head_hexsha": "341874fbad4507d6ed4e05e18e4a9cedf5470d01", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-25T13:17:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-25T13:17:23.000Z", "max_issues_repo_path": "unittest/test_boxqp.cpp", "max_issues_repo_name": "Capri2014/crocoddyl", "max_issues_repo_head_hexsha": "341874fbad4507d6ed4e05e18e4a9cedf5470d01", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/test_boxqp.cpp", "max_forks_repo_name": "Capri2014/crocoddyl", "max_forks_repo_head_hexsha": "341874fbad4507d6ed4e05e18e4a9cedf5470d01", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5578231293, "max_line_length": 113, "alphanum_fraction": 0.6871855082, "num_tokens": 1682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199511728004, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6224923463224992}}
{"text": "#include \"complexfun.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include <boost/variant.hpp>\n#include <stdexcept>\n#include <cmath>\n#include <string>\n#include <complex>\n\nnamespace \n{\n    const double pi= std::acos(-1.0);\n    void validate(PASTNode astnode, ParsersHelper& ph, const std::string& fnname)\n    {\n        auto myParserHelper(ph);\n        if (astnode->ch.size()!=2)\n          throw std::runtime_error(fnname+\" should have exactly one argument\");\n        auto secondCh = *astnode->ch.rbegin();\n        ph.parse(secondCh);\n        if (secondCh->token.tokenType != Complex)\n          throw std::runtime_error(\"The argument of \"+fnname+\" must be Complex\");\n    }\n}\n\n\nnamespace HT\n{\n    void magnitude(PASTNode astnode, ParsersHelper& ph)\n    {\n        validate(astnode, ph, \"magnitude\");\n        auto w (boost::get<ComplexType>((*astnode->ch.rbegin())->token.info));\n        w.toinexact();\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n\n        auto res = std::hypotl(w.getRealD(), w.getImagD());\n        astnode->token.info = ComplexType(res);\n\n        astnode->remove();\n    }\n    void angle(PASTNode astnode, ParsersHelper& ph)\n    {\n        validate(astnode, ph, \"magnitude\");\n        auto w (boost::get<ComplexType>((*astnode->ch.rbegin())->token.info));\n        w.toinexact();\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n\n        auto res = std::atan2(w.getImagD(), w.getRealD());\n        if (std::fabs(res+ pi)<1e-6) res = -res;\n        astnode->token.info = ComplexType(res);\n\n        astnode->remove();\n    }\n\n}\n\n\n", "meta": {"hexsha": "80ed2dd89ccbd05733300fbf7c3155d8c286da74", "size": 1616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/complexfun.cpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "funs/complexfun.cpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funs/complexfun.cpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9333333333, "max_line_length": 81, "alphanum_fraction": 0.6058168317, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.622416766674772}}
{"text": "/*\nMIT License\n\nCopyright (c) 2019 Xiaohong Chen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#ifndef BOOST_UBLAS_GMRES_HPP\n#define BOOST_UBLAS_GMRES_HPP\n\n#include \"preconditioner.hpp\"\n#include \"krylov_solvers_config.hpp\"\n\n#include <tuple>\n#include <cmath>\n#include <type_traits>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n\n// test\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n\nnamespace boost { namespace numeric { namespace ublas {\n\nnamespace detail {\n// Calculate the Given rotation matrix\ntemplate<typename T>\nBOOST_UBLAS_INLINE std::tuple<T, T> givens_rotation(T x1, T x2) {\n    T d = sqrt(x1*x1 + x2*x2);\n    if (d == T/*zero*/()) divide_by_zero().raise();\n    return std::make_tuple(x1/d, -x2/d);\n}\n\n// apply Givens rotations on the jth column of the upper Hessenberg matrix.\ntemplate<class V1, class V2>\nvoid apply_givens_rotation(V1& h, V2& cs, V2& sn,\n                           typename vector_traits<V2>::size_type j) {\n    typedef typename V2::size_type size_type;\n    typedef typename V2::value_type value_type;\n\n    BOOST_UBLAS_CHECK (cs.size() == sn.size(), bad_size ());\n    BOOST_UBLAS_CHECK (cs.size() > j, bad_size ());\n\n    // apply Givens rotation over the first j - 1 entries on jth column of the upper Hessenberg matrix.\n    for (size_type i = 0; i < j; ++i) {\n        value_type tmp = cs(i)*h(i) - sn(i)*h(i+1);\n        h(i+1) = sn(i)*h(i) + cs(i)*h(i+1);\n        h(i) = tmp;\n    }\n    // update Givens rotation matrix.\n    if (j < h.size() - 1) {\n        BOOST_UBLAS_CHECK (h.size() > j + 1, bad_size ());\n        std::tie(cs(j), sn(j)) = givens_rotation(h(j), h(j+1));\n        // eliminate h(j+1).\n        h(j) = cs(j)*h(j) - sn(j)*h(j+1);\n        h(j+1) = value_type/*zero*/();\n    }\n    else {\n        cs(j) = value_type(1.0);\n        sn(j) = value_type/*zero*/();\n    }\n}\n\ntemplate<class F1, class F2, class M, class V>\nvoid arnoldi(const F1& A, const F2& PInv, M& Q, V& h, typename matrix_traits<M>::size_type j) {\n    typedef typename M::size_type size_type;\n    typedef typename M::value_type value_type;\n    typedef M matrix_type;\n    typedef vector<value_type> vector_type;\n\n    BOOST_UBLAS_CHECK(Q.size2() > j + 1, bad_size());\n\n    matrix_column<matrix_type> q(Q, j+1);\n    q.assign(PInv(A(column(Q, j))));\n    size_type size1 = Q.size1();\n    vector_range<V> hr(h, range(0, j+1));\n    // CGS2\n    axpy_prod(q, project(Q, range(0, size1), range(0, j+1)), hr, true);\n    axpy_prod(project(Q, range(0, size1), range(0, j+1)), -hr, q, false);\n    vector_type tmp(j+1, 0.0);\n    axpy_prod(q, project(Q, range(0, size1), range(0, j+1)), tmp, false);\n    axpy_prod(project(Q, range(0, size1), range(0, j+1)), -tmp, q, false);\n    hr.plus_assign(tmp);\n\n    if (j < size1 - 1) {\n        BOOST_UBLAS_CHECK(h.size() > j + 1, bad_size());\n        h(j+1) = norm_2(q);\n        q /= h(j+1);\n    }\n    else {\n        q *= value_type/*zero*/();\n    }\n}\n\ntemplate <typename T>\nclass is_matrix_expression\n{\nprivate:\n    template<typename E>\n    static constexpr std::true_type  test(const matrix_expression<E> *);\n    static constexpr std::false_type test(...);\npublic:\n    static constexpr bool value = decltype(test(std::declval<T*>()))::value;\n    typedef decltype(test(std::declval<T*>())) type;\n};\n\ntemplate <typename T>\nconstexpr bool is_matrix_expression_v = is_matrix_expression<T>::value;\n\ntemplate <typename T>\nusing is_matrix_expression_t = typename is_matrix_expression<T>::type;\n\ntemplate<class F1, class F2, class E, class V, typename Int, typename Floating>\nstd::tuple<Int, Floating>\ngmres_impl(const F1& A, const F2& PInv, const vector_expression<E>& b, V& x,\n           Int max_iter_, Int restart_iter_, Floating tol_, std::false_type) {\n    typedef typename V::value_type value_type;\n    typedef typename V::size_type size_type;\n    typedef matrix<value_type, column_major> matrix_type;\n    typedef banded_matrix<value_type, column_major> banded_matrix_type;\n    typedef vector<value_type> vector_type;\n    typedef unit_vector<value_type> unit_vector_type;\n    typedef std::tuple<Int, Floating> return_type;\n\n    BOOST_UBLAS_CHECK(b().size() == x.size(), bad_size());\n    BOOST_UBLAS_CHECK(restart_iter_ > Int/*zero*/(), bad_argument());\n    BOOST_UBLAS_CHECK(max_iter_ > Int/*zero*/(), bad_argument());\n    BOOST_UBLAS_CHECK(tol_ > Floating/*zero*/(), bad_argument());\n\n    size_type n = x.size();\n    // adjust max_iter and restart_iter\n    size_type max_iter = std::min(n, static_cast<size_type>(max_iter_));\n    size_type restart_iter = std::min(n, static_cast<size_type>(restart_iter_));\n    value_type tol = static_cast<value_type>(tol_);\n    if (restart_iter > max_iter) restart_iter = max_iter;\n\n    vector_type r = PInv(b - A(x));\n    value_type r_norm = norm_2(r);\n    value_type b_norm = norm_2(PInv(b));\n    if (b_norm == value_type/*zero*/()) {\n        x *= value_type/*zero*/();\n        return return_type(Int/*zero*/(), Floating/*zero*/());\n    }\n    value_type error = norm_2(r) / b_norm;\n    if (error < tol) return return_type(Int/*zero*/(), error);\n\n    vector_type sn(restart_iter, value_type/*zero*/());\n    vector_type cs(restart_iter, value_type/*zero*/());\n\n    matrix_type Q(n, restart_iter + 1, value_type/*zero*/());\n    banded_matrix_type H(n, restart_iter, 1, restart_iter);\n\n    size_type num_iter = 1;\n    while (num_iter <= max_iter) {\n        column(Q, 0).assign(r / r_norm);\n        vector_type beta = r_norm * unit_vector_type(restart_iter + 1, 0);\n\n        size_type j = size_type/*zero*/();\n        for (; j < restart_iter && num_iter <= max_iter; ++j, ++num_iter) {\n            // run arnoldi\n            matrix_column<banded_matrix_type> H_j(H, j);\n            detail::arnoldi(A, PInv, Q, H_j, j);\n\n            // eliminate the last element in H jth column and update the rotation matrix\n            detail::apply_givens_rotation(H_j, cs, sn, j);\n\n            // update the residual vector\n            beta(j+1) = sn(j)*beta(j);\n            beta(j) = cs(j)*beta(j);\n            error  = std::abs(beta(j+1)) / b_norm;\n\n            if (error <= tol) {\n                // update x\n                auto y = solve(project(H, range(0, j+1), range(0, j+1)),\n                               project(beta, range(0, j+1)), upper_tag());\n                axpy_prod(project(Q, range(0, n), range(0, j+1)), y, x, false);\n                return return_type(num_iter, error);\n            }\n        }\n        // update x\n        auto y = solve(project(H, range(0, j), range(0, j)),\n                       project(beta, range(0, j)), upper_tag());\n        axpy_prod(project(Q, range(0, n), range(0, j)), y, x, false);\n\n        r = PInv(b - A(x));\n        r_norm = norm_2(r);\n        error = norm_2(r) / b_norm;\n        if (error < tol) return return_type(num_iter, error);\n    }\n    return return_type(max_iter, error);\n}\n\ntemplate<class M, class F, class E, class V, typename Int, typename Floating>\nstd::tuple<Int, Floating>\ngmres_impl(const M& A, const F& PInv, const vector_expression<E>& b, V& x,\n           Int max_iter, Int restart_iter, Floating tol, std::true_type) {\n    return gmres_impl([&A](const auto& v){return ublas::prod(A, v);}, PInv,\n                      b, x, max_iter, restart_iter, tol, std::false_type());\n}\n\n} // end namespace detail\n\n\ntemplate <class M, class F = identity_precond<M> >\nclass gmres {\npublic:\n    // param\n    struct param {\n        int max_iter = 10;\n        int restart_iter = 10;\n        double tol = 1e-6;\n    };\n\n    typedef std::tuple<int, double> return_type;\n\n    gmres(const M& A)\n        : A_(A), PInv_(A) {}\n\n    gmres(const M& A, const param& p)\n        : A_(A), PInv_(A), param_(p) {}\n\n    gmres(const M& A, const F& PInv)\n        : A_(A), PInv_(PInv) {}\n\n    gmres(const M& A, F&& PInv)\n        : A_(A), PInv_(std::move(PInv)) {}\n\n    gmres(const M& A, const F& PInv, const param& p)\n        : A_(A), PInv_(PInv), param_(p) {}\n\n    gmres(const M& A, F&& PInv, const param& p)\n        : A_(A), PInv_(PInv), param_(p) {}\n\n    gmres(const gmres&) = delete;\n    gmres(gmres&&) = delete;\n    gmres& operator=(const gmres&) = delete;\n    gmres& operator=(gmres&&) = delete;\n\n    param get_param() const {\n        return param_;\n    }\n\n    void set_param(const param& p) {\n        param_ = p;\n    }\n\n    template<class E, class V>\n    return_type operator()(const vector_expression<E>& b, V& x) const {\n        return detail::gmres_impl(A_, PInv_, b, x,\n                                  param_.max_iter,\n                                  param_.restart_iter,\n                                  param_.tol,\n                                  detail::is_matrix_expression_t<M>());\n    }\n\nprivate:\n    const M& A_;\n    F PInv_;\n    param param_;\n};\n\n} // end namespace ublas\n} // end namespace numeric\n} // end namespace boost\n\n#endif\n", "meta": {"hexsha": "331f926d3dfbfec000108269aac2ae2d07bba708", "size": 10003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gmres.hpp", "max_stars_repo_name": "xiaohongchen1991/krylov-solvers", "max_stars_repo_head_hexsha": "148d7bb4107a80c9e1771d77a0d589afb74d5744", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T20:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T02:46:55.000Z", "max_issues_repo_path": "include/gmres.hpp", "max_issues_repo_name": "xiaohongchen1991/krylov-solvers", "max_issues_repo_head_hexsha": "148d7bb4107a80c9e1771d77a0d589afb74d5744", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gmres.hpp", "max_forks_repo_name": "xiaohongchen1991/krylov-solvers", "max_forks_repo_head_hexsha": "148d7bb4107a80c9e1771d77a0d589afb74d5744", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3745704467, "max_line_length": 103, "alphanum_fraction": 0.6282115365, "num_tokens": 2748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6223986617433861}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[boost_fusion\r\n//` Shows how to combine Boost.Fusion with Boost.Geometry\r\n\r\n#include <iostream>\r\n\r\n#include <boost/fusion/include/adapt_struct_named.hpp>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_fusion.hpp>\r\n\r\n\r\nstruct sample_point\r\n{\r\n    double x, y, z;\r\n};\r\n\r\nBOOST_FUSION_ADAPT_STRUCT(sample_point, (double, x) (double, y) (double, z))\r\nBOOST_GEOMETRY_REGISTER_BOOST_FUSION_CS(cs::cartesian)\r\n\r\nint main()\r\n{\r\n    sample_point a, b, c;\r\n    \r\n    // Set coordinates the Boost.Geometry way (one of the ways)\r\n    boost::geometry::assign_values(a, 3, 2, 1);\r\n    \r\n    // Set coordinates the Boost.Fusion way\r\n    boost::fusion::at_c<0>(b) = 6;\r\n    boost::fusion::at_c<1>(b) = 5;\r\n    boost::fusion::at_c<2>(b) = 4;\r\n    \r\n    // Set coordinates the native way\r\n    c.x = 9;\r\n    c.y = 8;\r\n    c.z = 7;\r\n    \r\n    std::cout << \"Distance a-b: \" << boost::geometry::distance(a, b) << std::endl;\r\n    std::cout << \"Distance a-c: \" << boost::geometry::distance(a, c) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n//[boost_fusion_output\r\n/*`\r\nOutput:\r\n[pre\r\nDistance a-b: 5.19615\r\nDistance a-c: 10.3923\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "b49cd39dbd0e5dc7d848366a551ccbe5d668f66e", "size": 1497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/geometries/adapted/boost_fusion.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/geometry/doc/src/examples/geometries/adapted/boost_fusion.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/geometry/doc/src/examples/geometries/adapted/boost_fusion.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7619047619, "max_line_length": 83, "alphanum_fraction": 0.6386105544, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.622398657811343}}
{"text": "/**\n * Copyright (C) Omar Thor <omarthoro@gmail.com> - All Rights Reserved\n * Unauthorized copying of this file, via any medium is strictly prohibited\n * Proprietary and confidential\n *\n * Written by Omar Thor <omarthoro@gmail.com>, 2017\n */\n\n//#include \"sp/util/timing.hpp\"\n//#include \"sp/util/rand.hpp\"\n//#include \"sp/util/typename.hpp\"\n\n#include <iostream>\n#include <iomanip>\n#define BOOST_TEST_MODULE sp_algo_nn\n#include <boost/test/unit_test.hpp>\n#include \"sp/algo/nn.hpp\"\n#include \"sp/algo/nn/gradient_check.hpp\"\n#include \"assert_matrix.hpp\"\n\nusing namespace sp::algo::nn;\nusing namespace sp::testing;\n\nBOOST_AUTO_TEST_CASE(test_activation_tanh_fprop_bprop) {\n\n    using tanh_act_layer = tanh_layer<volume_dims<1, 3, 3>>;\n    tanh_act_layer layer;\n\n    layer.configure(1, true);\n\n    /* stage 2 */\n    tensor_4 in = generate_inputs_for(layer);\n    tensor_4 out(1, 1, 3, 3);\n\n    tensor_4 prev_delta(1, 1, 3, 3);\n    tensor_4 out_delta(1, 1, 3, 3);\n    tensor_4 expected_out(1, 1, 3, 3);\n    tensor_4 expected_prev_delta(1, 1, 3, 3);\n\n    in.setValues({{{\n        {0.0f, 1.0f, 2.0f},\n        {1.0f, 2.0f, 3.0f},\n        {2.0f, 3.0f, 4.0f},\n    }}});\n    prev_delta.setZero();\n    out_delta.setValues({{{\n        {-1.0f, 2.0f, 3.0f},\n        { 4.0f, 5.0f, 6.0f},\n        { 7.0f, 8.0f, 9.0f}\n    }}});\n\n    /* perform activation forward propagation*/\n    layer.forward_prop(in, out);\n\n    BOOST_REQUIRE((std::is_same_v<tanh_act_layer::activation_op_type, tanh_activation_op>));\n    auto op = tanh_act_layer::activation_op_type();\n    auto dop = tanh_act_layer::activation_op_deriv_type();\n    expected_out.setValues({{{ //Simply performs acti(x) for every value in input\n        {op(in(0, 0, 0, 0)), op(in(0, 0, 0, 1)), op(in(0, 0, 0, 2))},\n        {op(in(0, 0, 1, 0)), op(in(0, 0, 1, 1)), op(in(0, 0, 1, 2))},\n        {op(in(0, 0, 2, 0)), op(in(0, 0, 2, 1)), op(in(0, 0, 2, 2))},\n    }}});\n\n    assert_tensor_equals(expected_out, out);\n\n    layer.backward_prop(in, prev_delta, out, out_delta);\n\n    expected_prev_delta.setValues({{{ //act_delta(x, y, ...) = prev_delta(x, y, ...) * deriv_op(prev_delta(x, y, ...))\n        {out_delta(0, 0, 0, 0) * dop(out(0, 0, 0, 0)), out_delta(0, 0, 0, 1) * dop(out(0, 0, 0, 1)), out_delta(0, 0, 0, 2) * dop(out(0, 0, 0, 2))},\n        {out_delta(0, 0, 1, 0) * dop(out(0, 0, 1, 0)), out_delta(0, 0, 1, 1) * dop(out(0, 0, 1, 1)), out_delta(0, 0, 1, 2) * dop(out(0, 0, 1, 2))},\n        {out_delta(0, 0, 2, 0) * dop(out(0, 0, 2, 0)), out_delta(0, 0, 2, 1) * dop(out(0, 0, 2, 1)), out_delta(0, 0, 2, 2) * dop(out(0, 0, 2, 2))},\n    }}});\n\n    assert_tensor_equals(expected_prev_delta, prev_delta);\n}\nBOOST_AUTO_TEST_CASE(test_activation_layer_grad_check) {\n    using layer_type = tanh_layer<volume_dims<10, 3, 3>>;\n\n    constexpr float_t epsilon = 1e-2f;\n    constexpr size_t batch_size = 1;\n    layer_type layer;\n\n    layer.weight_initializer = gauss_weight_initializer(-1.0f, 1.0f);\n    layer.bias_initializer = gauss_weight_initializer(-1.0f, 1.0f);\n\n    /* setup weights and dimensions */\n    layer.configure(batch_size, true);\n\n    auto in = generate_inputs_for(layer, batch_size);\n\n    for(size_t i = 0; i < 100; ++i) {\n        auto in_selected  = gradient_random_input(layer);\n        auto out_selected = gradient_random_output(layer);\n\n        /* Perform numerical and analytics gradient */\n        /* estimate */\n        auto n = numerical_gradient (layer, in, in_selected, out_selected);\n        /* actual */\n        auto a = analytical_gradient(layer, in, in_selected, out_selected);\n\n        /* Validate result */\n        BOOST_CHECK_MESSAGE(std::abs(a-n) <= epsilon, \"Gradient check |\" << std::setprecision(15) << a << \" - \" << n << \"| < \" << epsilon);\n    }\n}\n", "meta": {"hexsha": "8ebbc532ee9835239f0670709179f089532706d0", "size": 3708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_nn_activation.cpp", "max_stars_repo_name": "thorigin/sp", "max_stars_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_nn_activation.cpp", "max_issues_repo_name": "thorigin/sp", "max_issues_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_nn_activation.cpp", "max_forks_repo_name": "thorigin/sp", "max_forks_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3142857143, "max_line_length": 147, "alphanum_fraction": 0.6173139159, "num_tokens": 1282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6223986552313009}}
{"text": "#ifndef FILTER_HPP\n# define FILTER_HPP\n\n#include <Eigen/Dense>\n\n#include \"nav_types.hpp\"\n#include \"prop.hpp\"\n\nDiagonalMatrix<double,9> compute_process_noise(const double& dt) {\n  DiagonalMatrix<double,9> Q;\n  double qa = Q_ACCEL_PSD * dt,\n    qv = qa * dt * 0.5,\n    qr = qv * dt * 2.0 / 3.0,\n    qw = Q_GYRO_PSD * dt;\n  Q.diagonal() << qr, qr, qr, qa, qa, qa, qw, qw, qw;\n  return Q;\n}\n\n\nclass Filter {\npublic:\n  Filter(const double& time, const Eigen::Matrix<double,6,1>& rv)\n    : Phi(Cov::Identity())\n    , P(Cov::Zero())\n    , X(State::Zero())\n    , dX(State::Zero())\n  {\n    // Initialize covariance to some reasonable values\n    P.diagonal() <<\n      rv,\n      0.5, 0.5, 0.5,\n      0.0001, 0.0001, 0.0001,\n      0.00001, 0.00001, 0.00001,\n      0.1, 0.1, 0.1,\n      0.1, 0.1, 0.1,\n      0.1, 0.1, 0.1,\n      0.1, 0.1, 0.1,\n      0.1, 0.1, 0.1;\n\n    // Initialize state to some reasonable values\n    X[0] = 6375000.0;\n    X[4] = 10.0;\n  }\n\n\n  /** @brief Having propagated for a while in a Prop object, prepare\n   **        the filter to receive an update at or just before the current\n   **        time.\n   *\n   * This method computes the covariance at the current time using the\n   * posterior covariance from the last update and the propagated\n   * state transition matrix.\n   *\n   */\n  void prepare_for_update(const Prop& prop) {\n    double dt = prop.time - time;\n    DiagonalMatrix<double,9> Q = compute_process_noise(dt);\n\n    Phi << prop.Phi_xx, prop.Phi_xb, Matrix<double,21,30>::Zero();\n    for (size_t ii = 0; ii < 21; ++ii) {\n      Phi(ii+9,ii+9) = prop.Phi_bb.diagonal()(ii);\n    }\n\n    P = Phi * (P * Phi.transpose());\n    for (size_t ii = 0; ii < 9; ++ii) {\n      P(ii,ii) += Q.diagonal()(ii);\n    }\n\n    for (size_t ii = 0; ii < 3; ++ii) {\n      X[ii]    = prop.r_imu_inrtl(ii);\n      X[ii+3]  = prop.v_imu_inrtl(ii);\n      X[ii+6]  = 0.0;\n      X[ii+9]  = prop.b_acc(ii);\n      X[ii+12] = prop.b_gyro(ii);\n    }\n    \n    time = prop.time;\n    // FIXME: Make sure this is symmetric after.\n  }\n\n  double time; /* (s)  time of state/covariance validity */\n  Cov Phi;     /* (--) state transition matrix */\n  Cov P;       /* (--) state covariance */\n  State X;     /* (--) state */\n  State dX;    /* (--) pending state update */\n};\n\n#endif\n", "meta": {"hexsha": "0c3207077eda459dde8935886fbd9e9825f0d888", "size": 2257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/filter.hpp", "max_stars_repo_name": "openlunar/nav", "max_stars_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/filter.hpp", "max_issues_repo_name": "openlunar/nav", "max_issues_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "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/filter.hpp", "max_forks_repo_name": "openlunar/nav", "max_forks_repo_head_hexsha": "37240000c542f4d42979a83ac5bebb3ab2c01fe4", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3595505618, "max_line_length": 74, "alphanum_fraction": 0.5613646433, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6223703052378007}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_2.h>\n#include <CGAL/Triangulation_face_base_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_with_info_2.h>\n#include <boost/pending/disjoint_sets.hpp>\n#include <vector>\n#include <tuple>\n#include <algorithm>\n#include <iostream>\n#include <queue>\n#include <limits>\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_2<K>   Vb;\ntypedef CGAL::Triangulation_face_base_with_info_2<int, K>  Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb>            Tds;\ntypedef CGAL::Delaunay_triangulation_2<K,Tds>                  Delaunay;\n\ntypedef K::FT FT;\n\nusing namespace std;\n\nstruct Neighbor {\n  int vertex;\n  FT width;\n};\n\nvoid solve(int numPoints) {\n\n  long x, y;\n  vector<K::Point_2> pts(numPoints);\n  for (int i = 0; i < numPoints; ++i) {\n    cin >> x >> y;\n    pts[i] = {x, y};\n  }\n  Delaunay dt;\n  dt.insert(pts.begin(), pts.end());\n  \n  int id = 1;\n  for (auto f = dt.finite_faces_begin(); f != dt.finite_faces_end(); ++f) {\n    f->info() = id++;\n  }\n\n  int n = id;\n  vector<vector<Neighbor>> neighbors(n);\n  for (auto f = dt.finite_faces_begin(); f != dt.finite_faces_end(); ++f) {\n    int u = f->info();\n    \n    for (int i = 0; i < 3; ++i) {\n      auto f2 = f->neighbor(i);\n      int v = dt.is_infinite(f2) ? 0 : f2->info();\n      auto p1 = f->vertex((i + 1) % 3)->point();\n      auto p2 = f->vertex((i + 2) % 3)->point();\n      FT width = CGAL::squared_distance(p1, p2);\n      \n      neighbors[u].push_back({v, width});\n      if (v == 0) {\n        neighbors[v].push_back({u, width});\n      }\n    }\n  }\n  \n  FT maxValue = FT(numeric_limits<long>::max());\n  \n  vector<FT> width(n, -1);\n  priority_queue<tuple<FT, int>> queue; \n  queue.push({maxValue, 0});\n  \n  while (!queue.empty()) {\n\n    FT w = get<0>(queue.top());\n    int u = get<1>(queue.top());\n    queue.pop();\n\n    if (width[u] != -1) {\n      continue;\n    }\n    \n    width[u] = w;\n\n    for (Neighbor n : neighbors[u]) {\n      FT wn = CGAL::min(n.width, w);\n      queue.push({wn, n.vertex});\n    }\n  }\n\n  int m;\n  cin >> m;\n  long d;\n  for (int i = 0; i < m; ++i) {\n    cin >> x >> y >> d;\n    \n    K::Point_2 p(x, y);\n    \n    if (CGAL::squared_distance(p, dt.nearest_vertex(p)->point()) < FT(d)) {\n      cout << \"n\";\n      continue;\n    }\n    \n    auto f = dt.locate(p);\n    int v = dt.is_infinite(f) ? 0 : f->info();\n\n    if (width[v] >= FT(4) * FT(d)) {\n      cout << \"y\";\n    }\n    else {\n      cout << \"n\";\n    }\n    \n  }\n  cout << endl;\n}\n\n\nint main() {\n  ios_base::sync_with_stdio(false);\n  int n; \n  cin >> n;\n  while (n != 0) {\n    solve(n);\n    cin >> n;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "c98c049c525474d2ebd2b879902767406a7c89eb", "size": 2799, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/h1n1.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/h1n1.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/h1n1.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 21.8671875, "max_line_length": 75, "alphanum_fraction": 0.5744908896, "num_tokens": 901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.6223651663408809}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string> // for string class\n#include <math.h>\n#include <iostream>\n#include <cmath>\n#include <array>\n#include <complex>\n#include<time.h>\n#include \"mex.h\"\n#include <omp.h>\n\n//#define EIGEN_USE_MKL_ALL\n#include <Eigen/Dense>\n// #include <Eigen/Sparse>\n// #include <unsupported/Eigen/CXX11/Tensor>\n// #include <Eigen/LU>\n// #include <unsupported/Eigen/KroneckerProduct>\n#include <Eigen/Core>\n// #include <Eigen/SVD>\n// #include<unsupported/Eigen/SparseExtra>\n\n#define PI acos(-1.0)\n\n\nusing namespace Eigen;\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n  //*********************************************\n\n  double *val_Node_Coord = (double *) mxGetPr(mxGetField(prhs[0], 0, \"Node_Coord\"));\n  int m_Node_Coord = mxGetM(mxGetField(prhs[0], 0, \"Node_Coord\"));\n  int n_Node_Coord = mxGetN(mxGetField(prhs[0], 0, \"Node_Coord\"));\n  Eigen::MatrixXd Node_Coord = Map < MatrixXd > (val_Node_Coord,m_Node_Coord,n_Node_Coord);\n\n  double *val_Node_Coord_ndgrid = (double *) mxGetPr(mxGetField(prhs[0], 0, \"Node_Coord_ndgrid\"));\n  int m_Node_Coord_ndgrid = mxGetM(mxGetField(prhs[0], 0, \"Node_Coord_ndgrid\"));\n  int n_Node_Coord_ndgrid = mxGetN(mxGetField(prhs[0], 0, \"Node_Coord_ndgrid\"));\n  Eigen::MatrixXd Node_Coord_ndgrid = Map < MatrixXd > (val_Node_Coord_ndgrid,m_Node_Coord_ndgrid,n_Node_Coord_ndgrid);\n\n  double *val_node_index_total= (double *) mxGetPr(mxGetField(prhs[0], 0, \"node_index_total\"));\n  int m_node_index_total = mxGetM(mxGetField(prhs[0], 0, \"node_index_total\"));\n  Eigen::VectorXd node_index_total = Map < VectorXd > (val_node_index_total,m_node_index_total);\n\n\n  int nnode=Node_Coord_ndgrid.rows();\n  Eigen::MatrixXd corr_index(nnode,1); corr_index.setZero();\n\n\n// Eigen::MatrixXd a(3,3);\n// a<<1,2,3,\n// 4,5,6,\n// 7,8,9;\n// std::cout << a<< '\\n';\n// Eigen::VectorXd b=Eigen::Map<VectorXd>(a.data(), a.cols()*a.rows());\n// std::cout << b.transpose() << '\\n';\n// std::cout <<Eigen::Map<VectorXd>(a.data(), a.cols()*a.rows()) << '\\n';\n\n  // int p, n;\n  // double sum;\n  // sum = 0.0;\n  // n = 100;\n  // #pragma omp parallel for shared(n) private(p) reduction(+: sum)\n  // for(p = 0; p<n; p++){\n  //   sum += 1.0;\n  //   std::cout << \"/* message */\"<< sum << '\\n';\n  // }\n  // mexPrintf(\"sum = %f\\n\",sum);\n  int i=0;\n  #pragma omp parallel for private(i) shared(Node_Coord_ndgrid,Node_Coord,node_index_total,corr_index)\n  for (i = 0; i < nnode; i++) {\n    Eigen::Vector3d coord = Node_Coord_ndgrid.row(i);\n    MatrixXf::Index index;\n\n    // Eigen::MatrixXd temp=Node_Coord.rowwise()-coord.transpose();\n    // Eigen::VectorXd coordx = temp.rowwise().norm();;\n    // std::cout << \"/* ***** */\" << '\\n';\n    // std::cout <<  coord.transpose() << '\\n';\n    // // std::cout << \"/* message */\" << '\\n';\n    // // std::cout << temp.block<5,3>(0,0) << '\\n';\n    // std::cout << \"/* message */\" << '\\n';\n    // std::cout << coordx.head(5) << '\\n';\n    // std::cout << \"/* message */\" << '\\n';\n    // coordx.minCoeff(&index);\n    // std::cout << index << \" ***  \"<< node_index_total(index)<< '\\n';\n\n\n    (Node_Coord.rowwise()-coord.transpose()).rowwise().norm().minCoeff(&index);\n    // std::cout << index << \" ***  \"<< node_index_total(index)<< '\\n';\n    corr_index(i,0)=node_index_total(index);\n  }\n\n\n\n  //\t* Out put *//* Out put *//* Out put *//* Out put *//* Out put *//* Out put */\n  plhs[0] = mxCreateDoubleMatrix((mwSize) nnode, (mwSize) 1, mxREAL);\n  double *corr_index_out = mxGetPr(plhs[0]); // pointer pr_out will manage data in COLUMN Major.\n  Eigen::Map < MatrixXd > (corr_index_out, nnode,1) = corr_index;\n};\n", "meta": {"hexsha": "23086769860a5449226ab62d9af956c94e3605ce", "size": 3619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab/matlab_mex/src_mex/multi_threaded/corr_index_mex.cpp", "max_stars_repo_name": "shadialameddin/numerical_tools_and_friends", "max_stars_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matlab/matlab_mex/src_mex/multi_threaded/corr_index_mex.cpp", "max_issues_repo_name": "shadialameddin/numerical_tools_and_friends", "max_issues_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matlab/matlab_mex/src_mex/multi_threaded/corr_index_mex.cpp", "max_forks_repo_name": "shadialameddin/numerical_tools_and_friends", "max_forks_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1359223301, "max_line_length": 119, "alphanum_fraction": 0.6247582205, "num_tokens": 1131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6221827288580124}}
{"text": "\n#include \"TestWindow.h\"\n#include \"planecalib/PlaneCalibSystem.h\"\n#include \"planecalib/HomographyCalibration.h\"\n#include \"planecalib/Map.h\"\n#include \"planecalib/PoseTracker.h\"\n#include \"../PlaneCalibApp.h\"\n#include <opencv2/imgproc.hpp>\n#include <Eigen/Dense>\n#include <ceres/ceres.h>\n\nnamespace planecalib\n{\nvoid TestWindow::showHelp() const\n{\n\tBaseWindow::showHelp();\n\tMYAPP_LOG << \"Just tests.\";\n}\n\nclass ImageInterpolation : public ceres::SizedCostFunction<1, 2> {\npublic:\n\tImageInterpolation(const cv::Mat1b &img, const cv::Mat1s &imgDx, const cv::Mat1s &imgDy);\n\n\tvirtual bool Evaluate(double const* const* parameters,\n\t\tdouble* residuals,\n\t\tdouble** jacobians) const;\n\nprotected:\n\tconst cv::Mat1b &mImg;\n\tconst cv::Mat1s &mImgDx;\n\tconst cv::Mat1s &mImgDy;\n\n\ttemplate<class T>\n\tT interpolate(const cv::Mat_<T> &img, const double x, const double y) const;\n};\n\nImageInterpolation::ImageInterpolation(const cv::Mat1b &img, const cv::Mat1s &imgDx, const cv::Mat1s &imgDy):\n\tmImg(img), mImgDx(imgDx), mImgDy(imgDy)\n{\n}\n\nbool ImageInterpolation::Evaluate(double const* const* parameters,\n\tdouble* residuals,\n\tdouble** jacobians) const\n{\n\tint u0 = (int)parameters[0][0];\n\tint v0 = (int)parameters[0][1];\n\t//residuals[0] = mImg(v0, u0);\n\n\tdouble u = parameters[0][0];\n\tdouble v = parameters[0][1];\n\tresiduals[0] = interpolate(mImg, u, v);\n\tif (jacobians)\n\t{\n\t\t//jacobians[0][0] = mImgDx(v0, u0);\n\t\t//jacobians[0][1] = mImgDy(v0, u0);\n\t\tjacobians[0][0] = interpolate(mImgDx, u, v);\n\t\tjacobians[0][1] = interpolate(mImgDy, u, v);\n\t}\n\treturn true;\n}\n\ntemplate<class T>\nT ImageInterpolation::interpolate(const cv::Mat_<T> &img, const double x, const double y) const\n{\n\tint x0 = (int)x;\n\tint y0 = (int)y;\n\t\n\tdouble dx = x - x0;\n\tdouble dy = y - y0;\n\t\n\tint x1 = x0+1;\n\tif (x1 == img.cols)\n\t\tx1--;\n\tint y1 = y0+1;\n\tif (y1 == img.rows)\n\t\ty1--;\n\n\tint v00 = (int)img(y0, x0);\n\tint v10 = (int)img(y1, x0);\n\tdouble v0 = v00*(1 - dy) + v10*dy;\n\n\tint v01 = (int)img(y0, x1);\n\tint v11 = (int)img(y1, x1);\n\tdouble v1 = v01*(1 - dy) + v11*dy;\n\n\tT val = T(v0*(1-dx)+v1*dx);\n\treturn val;\n}\n\n\nclass ErrorClass\n{\npublic:\n\tErrorClass(const cv::Mat1b &refImg, const cv::Mat1s &refDx, const cv::Mat1s &refDy, const std::vector<Eigen::Vector3i> &evalPositions, const cv::Mat1b &img, const cv::Mat1s &imgDx, const cv::Mat1s &imgDy);\n\n\ttemplate<class T>\n\tvoid evalRaw(const T * const paramsA, const T * const paramsB, const T * const paramsC, T *residuals, T*validCount)  const;\n\n\ttemplate<class T>\n\tbool operator() (const T * const paramsA, const T * const paramsB, const T * const paramsC, T *residuals)  const;\n\n\tconst cv::Mat1b &mRefImg;\n\tconst cv::Mat1s &mRefDx;\n\tconst cv::Mat1s &mRefDy;\n\tconst std::vector<Eigen::Vector3i> &mEvalPositions;\n\tconst cv::Mat1b &mImg;\n\tconst cv::Mat1s &mImgDx;\n\tconst cv::Mat1s &mImgDy;\n\n\tceres::CostFunctionToFunctor<1, 2> mInterp;\n};\n\nErrorClass::ErrorClass(const cv::Mat1b &refImg, const cv::Mat1s &refDx, const cv::Mat1s &refDy, const std::vector<Eigen::Vector3i> &evalPositions, const cv::Mat1b &img, const cv::Mat1s &imgDx, const cv::Mat1s &imgDy) :\nmRefImg(refImg), mRefDx(refDx), mRefDy(refDy), mEvalPositions(evalPositions), mImg(img), mImgDx(imgDx), mImgDy(imgDy), mInterp(new ImageInterpolation(img, imgDx, imgDy))\n{\n}\n\ntemplate<class T>\nbool ErrorClass::operator() (const T * const paramsA, const T * const paramsB, const T * const paramsC, T *residuals)  const\n{\n\tT validCountT;\n\n\tthis->evalRaw(paramsA, paramsB, paramsC, residuals, &validCountT);\n\tfor (int i = 0; i < (int)mEvalPositions.size(); i++)\n\t{\n\t\tresiduals[i] /= validCountT;\n\t}\n\n\treturn true;\n}\n\ntemplate<class T>\nvoid ErrorClass::evalRaw(const T * const paramsA, const T * const paramsB, const T * const paramsC, T *residuals, T*validCountT)  const\n{\n\tEigen::Map<Eigen::Matrix3Xi> evalPositionsMap((int*)mEvalPositions.data(), 3, mEvalPositions.size());\n\tEigen::Matrix<T, 3, Eigen::Dynamic> refPos = evalPositionsMap.cast<T>();\n\n\tEigen::Matrix<T, 3, 3> H;\n\t//H << T(1), T(0), params[0], T(0), T(1), params[1], T(0), T(0), T(1);\n\tH << paramsB[0], paramsB[1], paramsA[0], paramsB[2], paramsB[3], paramsA[1], paramsC[0], paramsC[1], paramsC[2];\n\n\tEigen::Matrix<T, 3, Eigen::Dynamic> imgPos3 = H*refPos;\n\n\tEigen::Matrix<T, 2, Eigen::Dynamic> imgPos;\n\t//Eigen::Matrix<T, 2, 100> imgPos;\n\timgPos.resize(2, imgPos3.cols());\n\timgPos.row(0) = imgPos3.row(0).array() / imgPos3.row(2).array();\n\timgPos.row(1) = imgPos3.row(1).array() / imgPos3.row(2).array();\n\n\tint validCount = 0;\n\tfor (int i = 0; i < (int)mEvalPositions.size(); i++)\n\t{\n\t\tT *imgPosi = &imgPos(0, i);\n\n\t\tdouble imgUd = CeresUtils::ToDouble(imgPosi[0]);\n\t\tdouble imgVd = CeresUtils::ToDouble(imgPosi[1]);\n\t\tif (imgUd < 0 || imgVd < 0 || imgUd > mImg.cols - 1 || imgVd > mImg.rows - 1)\n\t\t{\n\t\t\tresiduals[i] = T(0);\n\t\t\tcontinue;\n\t\t}\n\n\t\tT imgVal;\n\t\tmInterp(imgPosi, &imgVal);\n\n\t\tauto &refPosi = mEvalPositions[i];\n\t\tT refVal = T(mRefImg(refPosi[1], refPosi[0]));\n\n\t\tresiduals[i] = imgVal - refVal;\n\t\tvalidCount++;\n\t}\n\n\t*validCountT = T(validCount);\n}\n\nbool TestWindow::init(PlaneCalibApp *app, const Eigen::Vector2i &imageSize)\n{\n\tBaseWindow::init(app, imageSize);\n\n\tmRefTexture.create(GL_LUMINANCE, eutils::ToSize(imageSize));\n\tmImgTexture.create(GL_LUMINANCE, eutils::ToSize(imageSize));\n\tmCostTexture.create(GL_LUMINANCE, eutils::ToSize(imageSize));\n\tmEvalPositionsTexture.create(GL_LUMINANCE, eutils::ToSize(imageSize));\n\n\tloadRefFrame();\n\n\tresize();\n\n\treturn true;\n}\n\nvoid TestWindow::loadRefFrame()\n{\n\tconst int kMinGradientSq = 10 * 10;\n\n\tmRefKeyframe = mApp->getSystem().getMap().getKeyframes()[0].get();\n\tmRefImg = mApp->getSystem().getMap().getKeyframes()[0]->getImage(0);\n\n\tcv::Sobel(mRefImg, mRefDx, CV_16S, 1, 0, 1);\n\tcv::Sobel(mRefImg, mRefDy, CV_16S, 0, 1, 1);\n\n\tcv::Mat1b evalPosImg;\n\tevalPosImg.create(mRefImg.size());\n\n\tfor (Eigen::Vector3i p(0, 0, 1); p[1] < mRefImg.rows; p[1]++)\n\t{\n\t\tfor (p[0] = 0; p[0] < mRefImg.cols; p[0]++)\n\t\t{\n\t\t\tconst auto &dx = mRefDx(p[1], p[0]);\n\t\t\tconst auto &dy = mRefDy(p[1], p[0]);\n\t\t\tconst auto dmSq = dx*dx + dy*dy;\n\t\t\tif (dmSq > kMinGradientSq)\n\t\t\t{\n\t\t\t\tmEvalPositions.push_back(p);\n\t\t\t\tevalPosImg(p[1], p[0]) = (uchar)(255 * 0.3f);\n\t\t\t}\n\t\t\telse\n\t\t\t\tevalPosImg(p[1], p[0]) = 0;\n\t\t}\n\t}\n\n\tmPose = Eigen::Matrix3f::Identity();\n\n\tmRefTexture.update(mRefImg);\n\n\tmCostTexture.update(mRefImg);\n\n\tmEvalPositionsTexture.update(evalPosImg);\n}\nvoid TestWindow::alignAffine(const cv::Mat1b &img, const cv::Mat1s &imgDx, const cv::Mat1s &imgDy, Eigen::Matrix3fr &pose, TextureHelper &tex)\n{\n\t//Solver options\n\tceres::Solver::Options options;\n\toptions.linear_solver_type = ceres::CGNR;\n\t//options.dense_linear_algebra_library_type = ceres::LAPACK;\n\n\toptions.max_num_iterations = 500;\n\toptions.num_threads = 4;\n\toptions.num_linear_solver_threads = 4;\n\toptions.logging_type = ceres::SILENT;\n\toptions.minimizer_progress_to_stdout = false;\n\n\tEigen::Vector2d paramsA;\n\tEigen::Vector4d paramsB;\n\tEigen::Vector3d paramsC;\n\t//paramsA << 0,0;\n\t//paramsB << 1, 0, 0, 1;\n\t//paramsC << 0, 0, 1;\n\t\n\tEigen::Matrix3fr pose0;\n\t//pose0 = Eigen::Matrix3f::Identity();\n\tpose0 = pose;\n\tparamsA << pose0(0, 2), pose0(1, 2);\n\tparamsB << pose0(0, 0), pose0(0, 1), pose0(1, 0), pose0(1, 1);\n\tparamsC << pose0(2, 0), pose0(2, 1), pose0(2, 2);\n\n\t//Problem\n\tceres::Problem problem;\n\tproblem.AddParameterBlock(paramsA.data(), paramsA.size());\n\tproblem.AddParameterBlock(paramsB.data(), paramsB.size());\n\tproblem.AddParameterBlock(paramsC.data(), paramsC.size());\n\t//problem.SetParameterBlockConstant(paramsB.data());\n\tproblem.SetParameterBlockConstant(paramsC.data());\n\n\tauto *errorFunc = new ErrorClass(mRefImg, mRefDx, mRefDy, mEvalPositions, img, imgDx, imgDy);\n\tproblem.AddResidualBlock(new ceres::AutoDiffCostFunction<ErrorClass, ceres::DYNAMIC, 2, 4, 3>(\n\t\terrorFunc, mEvalPositions.size()),\n\t\tNULL, paramsA.data(), paramsB.data(), paramsC.data());\n\n\tceres::Solver::Summary summary;\n\t{\n\t\tProfileSection s(\"TestSolve\");\n\t\tceres::Solve(options, &problem, &summary);\n\t}\n\n\tMYAPP_LOG << \"-----------------Align affine-----------------\\n\";\n\tMYAPP_LOG << summary.FullReport();\n\tMYAPP_LOG << \"ParamsA: \" << paramsA << \"\\n\";\n\tMYAPP_LOG << \"ParamsB: \" << paramsB << \"\\n\";\n\tMYAPP_LOG << \"ParamsC: \" << paramsC << \"\\n\";\n\n\tpose << paramsB[0], paramsB[1], paramsA[0], paramsB[2], paramsB[3], paramsA[1], paramsC[0], paramsC[1], paramsC[2];\n\n\t//Cost\n\tstd::vector<double> residuals;\n\tdouble validCount;\n\tresiduals.resize(errorFunc->mEvalPositions.size());\n\terrorFunc->evalRaw(paramsA.data(), paramsB.data(), paramsC.data(), residuals.data(), &validCount);\n\tMYAPP_LOG << \"Valid count: \" << validCount << \"\\n\";\n\n\tcv::Mat1b costImg;\n\tcostImg.create(errorFunc->mImg.size());\n\tcostImg.setTo(0);\n\tfor (int i = 0; i < errorFunc->mEvalPositions.size(); i++)\n\t{\n\t\tauto &pos = errorFunc->mEvalPositions[i];\n\t\tuchar val = cv::saturate_cast<uchar>(std::abs(residuals[i]) * 50);\n\t\tcostImg(pos[1], pos[0]) = val;\n\t}\n\n\ttex.update(costImg);\n}\n\nvoid TestWindow::alignHomography(const cv::Mat1b &img, const cv::Mat1s &imgDx, const cv::Mat1s &imgDy, Eigen::Matrix3fr &pose, TextureHelper &tex)\n{\n\t//Solver options\n\tceres::Solver::Options options;\n\toptions.linear_solver_type = ceres::CGNR;\n\t//options.dense_linear_algebra_library_type = ceres::LAPACK;\n\n\toptions.max_num_iterations = 500;\n\toptions.num_threads = 4;\n\toptions.num_linear_solver_threads = 4;\n\toptions.logging_type = ceres::SILENT;\n\toptions.minimizer_progress_to_stdout = false;\n\n\tEigen::Vector2d paramsA;\n\tEigen::Vector4d paramsB;\n\tEigen::Vector3d paramsC;\n\t//paramsA << 0,0;\n\t//paramsB << 1, 0, 0, 1;\n\t//paramsC << 0, 0, 1;\n\tEigen::Matrix3fr pose0;\n\t//pose0 = Eigen::Matrix3f::Identity();\n\tpose0 = pose;\n\tparamsA << pose0(0, 2), pose0(1, 2);\n\tparamsB << pose0(0, 0), pose0(0, 1), pose0(1, 0), pose0(1, 1);\n\tparamsC << pose0(2, 0), pose0(2, 1), pose0(2, 2);\n\n\t//Problem\n\tceres::Problem problem;\n\tproblem.AddParameterBlock(paramsA.data(), paramsA.size());\n\tproblem.AddParameterBlock(paramsB.data(), paramsB.size());\n\t\n\t//std::vector<int> constantIdx;\n\t//constantIdx.push_back(2);\n\t//problem.AddParameterBlock(paramsC.data(), paramsC.size(), new ceres::SubsetParameterization(3,constantIdx));\n\tproblem.AddParameterBlock(paramsC.data(), paramsC.size());\n\n\t//problem.SetParameterBlockConstant(paramsB.data());\n\t//problem.SetParameterBlockConstant(paramsC.data());\n\n\tauto *errorFunc = new ErrorClass(mRefImg, mRefDx, mRefDy, mEvalPositions, img, imgDx, imgDy);\n\tproblem.AddResidualBlock(new ceres::AutoDiffCostFunction<ErrorClass, ceres::DYNAMIC, 2, 4, 3>(\n\t\terrorFunc, mEvalPositions.size()),\n\t\tNULL, paramsA.data(), paramsB.data(), paramsC.data());\n\n\tceres::Solver::Summary summary;\n\t{\n\t\tProfileSection s(\"TestSolve\");\n\t\tceres::Solve(options, &problem, &summary);\n\t}\n\n\tMYAPP_LOG << \"-----------------Align homography-----------------\\n\";\n\tMYAPP_LOG << summary.FullReport();\n\tMYAPP_LOG << \"ParamsA: \" << paramsA << \"\\n\";\n\tMYAPP_LOG << \"ParamsB: \" << paramsB << \"\\n\";\n\tMYAPP_LOG << \"ParamsC: \" << paramsC << \"\\n\";\n\n\tpose << paramsB[0], paramsB[1], paramsA[0], paramsB[2], paramsB[3], paramsA[1], paramsC[0], paramsC[1], paramsC[2];\t\n\n\t//Cost\n\tstd::vector<double> residuals;\n\tdouble validCount;\n\tresiduals.resize(errorFunc->mEvalPositions.size());\n\terrorFunc->evalRaw(paramsA.data(), paramsB.data(), paramsC.data(), residuals.data(), &validCount);\n\tMYAPP_LOG << \"Valid count: \" << validCount << \"\\n\";\n\n\tcv::Mat1b costImg;\n\tcostImg.create(errorFunc->mImg.size());\n\tcostImg.setTo(0);\n\tfor (int i = 0; i < errorFunc->mEvalPositions.size(); i++)\n\t{\n\t\tauto &pos = errorFunc->mEvalPositions[i];\n\t\tuchar val = cv::saturate_cast<uchar>(std::abs(residuals[i]) * 50);\n\t\tcostImg(pos[1], pos[0]) = val;\n\t}\n\n\ttex.update(costImg);\n}\n\nvoid TestWindow::updateState()\n{\n\tshared_lock<shared_mutex> lockRead(mApp->getSystem().getMap().getMutex());\n\n\tif (mApp->getSystem().getMap().getKeyframes()[0].get() != mRefKeyframe)\n\t\tloadRefFrame();\n\n\tconst TrackingFrame *frame = mApp->getSystem().getTracker().getFrame();\n\tif (!frame)\n\t\treturn;\n\n\t//mPose = Eigen::Matrix3f::Identity();\n\t//mPose0 = mPose;\n\n\tcv::Mat1b img;\n\tcv::Mat1s imgDx;\n\tcv::Mat1s imgDy;\n\n\timg = frame->getOriginalPyramid()[0];\n\tcv::Sobel(img, imgDx, CV_16S, 1, 0, 1);\n\tcv::Sobel(img, imgDy, CV_16S, 0, 1, 1);\n\n\tmImgTexture.update(img);\n\n\t//mPoseAffine = mPoseHomography = Eigen::Matrix3fr::Identity();\n\n\t//alignAffine(img, imgDx, imgDy, mPoseAffine, mCostAffineTexture);\n\talignHomography(img, imgDx, imgDy, mPose, mCostTexture);\n\n\t//Corners\n\tEigen::Matrix<float, 3, 4> refCorners;\n\n\trefCorners <<\n\t\t0, 0, mRefImg.cols, mRefImg.cols,\n\t\t0, mRefImg.rows, mRefImg.rows, 0,\n\t\t1,1,1,1;\n\n\tEigen::Matrix<float, 3, 4> corners3;\n\tcorners3 = mPose.inverse() * refCorners;\n\tmCornerPos.row(0) = corners3.row(0).array() / corners3.row(2).array();\n\tmCornerPos.row(1) = corners3.row(1).array() / corners3.row(2).array();\n}\n\nvoid TestWindow::resize()\n{\n\tauto screenSize = UserInterfaceInfo::Instance().getScreenSize();\n\tmTiler.configDevice(Eigen::Vector2i::Zero(), screenSize, 2, 1);\n\tmTiler.fillTiles();\n\n\t//Tile 0 - Alignment\n\tfloat scale = 1.5f;\n\tEigen::Vector2i sizeScaled = (scale*mImageSize.cast<float>()).cast<int>();\n\tEigen::Vector2f padding = (sizeScaled - mImageSize).cast<float>();\n\tEigen::Matrix4f offsetMat;\n\toffsetMat << 1, 0, 0, padding[0] / 2, 0, 1, 0, padding[1] / 2, 0, 0, 1, 0, 0, 0, 0, 1;\n\n\tmTiler.setImageMVP(0, sizeScaled);\n\tmTiler.multiplyMVP(0, offsetMat);\n\n\t//Tile 1 - Cost\n\tmTiler.setImageMVP(1, mImageSize);\n\n\t//Tile 2 - absolute\n\tint smallImgWidth = (int)(screenSize[0] * 0.2f);\n\tfloat imgAspect = (float)mImageSize[0] / mImageSize[1];\n\tint smallImgHeight = (int)(smallImgWidth / imgAspect);\n\n\tEigen::Vector2i smallImgSize(smallImgWidth, smallImgHeight);\n\tEigen::Vector2i smallImgOrigin(screenSize[0] - smallImgSize[0], 0);\n\tmTiler.addAbsoluteTile(smallImgOrigin, smallImgSize);\n\tmTiler.setImageMVP(2, mImageSize);\n}\n\nvoid TestWindow::draw()\n{\n\t//Generic vertices\n\tstd::vector<Eigen::Vector4f> vertices;\n\tstd::vector<Eigen::Vector2f> textureCoords;\n\tTextureShader::CreateVertices(mImageSize, vertices, textureCoords);\n\n\t///////////////////////////\n\t// Homography\n\t// Alignment\n\tmTiler.setActiveTile(0);\n\tmShaders->getTextureWarp().setMVPMatrix(mTiler.getMVP());\n\tmShaders->getColor().setMVPMatrix(mTiler.getMVP());\n\n\tglEnable(GL_BLEND);\n\tglBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA);\n\tmShaders->getTextureWarp().renderTextureAsAlpha(mRefTexture.getTarget(), mRefTexture.getId(), Eigen::Matrix3fr::Identity(), StaticColors::Green(), mImageSize);\n\tmShaders->getTextureWarp().renderTextureAsAlpha(mImgTexture.getTarget(), mImgTexture.getId(), mPose, StaticColors::Red(), mImageSize);\n\n\tmShaders->getColor().drawVertices(GL_LINE_LOOP, (Eigen::Vector2f*)mCornerPos.data(), mCornerPos.cols(), StaticColors::Green());\n\n\n\t//Cost\n\tmTiler.setActiveTile(1);\n\tmShaders->getTexture().setMVPMatrix(mTiler.getMVP());\n\tmShaders->getTexture().renderTexture(mCostTexture.getTarget(), mCostTexture.getId(), eutils::FromSize(mCostTexture.getSize()));\n\n\t//Absolute\n\tmTiler.setActiveTile(2);\n\tmShaders->getTexture().setMVPMatrix(mTiler.getMVP());\n\tmShaders->getTextureWarp().setMVPMatrix(mTiler.getMVP());\n\tmShaders->getTexture().renderTexture(mCurrentImageTextureTarget, mCurrentImageTextureId, mImageSize);\n\n\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\tmShaders->getTextureWarp().renderTextureAsAlpha(mEvalPositionsTexture.getTarget(), mEvalPositionsTexture.getId(), Eigen::Matrix3fr::Identity(), StaticColors::Blue(), mImageSize);\n}\n\n} /* namespace dtslam */\n", "meta": {"hexsha": "7141dd69e5b06c7e3e51c2eafd679b6d2d205a56", "size": 15371, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/planecalib_ui/windows/TestWindow.cpp", "max_stars_repo_name": "joshjo/planecalib", "max_stars_repo_head_hexsha": "1d7cffac5cab39c7fbfb67e8e3a4b42340ef5e13", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-05-29T14:30:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-10T13:31:43.000Z", "max_issues_repo_path": "code/planecalib_ui/windows/TestWindow.cpp", "max_issues_repo_name": "joshjo/planecalib", "max_issues_repo_head_hexsha": "1d7cffac5cab39c7fbfb67e8e3a4b42340ef5e13", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T21:00:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-28T22:02:03.000Z", "max_forks_repo_path": "code/planecalib_ui/windows/TestWindow.cpp", "max_forks_repo_name": "joshjo/planecalib", "max_forks_repo_head_hexsha": "1d7cffac5cab39c7fbfb67e8e3a4b42340ef5e13", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2016-08-05T14:35:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T21:23:16.000Z", "avg_line_length": 31.1153846154, "max_line_length": 218, "alphanum_fraction": 0.6907813415, "num_tokens": 5130, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6221827203753034}}
{"text": "#ifndef HOPS_LINEARMODEL_HPP\n#define HOPS_LINEARMODEL_HPP\n\n#define _USE_MATH_DEFINES\n\n#include <math.h>\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <utility>\n\nnamespace hops {\n    template<typename Matrix, typename Vector>\n    class LinearModel {\n    public:\n        using MatrixType = Matrix;\n        using VectorType = Vector;\n\n        LinearModel(VectorType measuredData, MatrixType dataCovariance, MatrixType linearModel);\n\n        /**\n         * @brief Evaluates the negative log likelihood for input x.\n         * @param x\n         * @return\n         */\n        typename MatrixType::Scalar computeNegativeLogLikelihood(const VectorType &x) const;\n\n        MatrixType computeExpectedFisherInformation(const VectorType &) const;\n\n        VectorType computeLogLikelihoodGradient(const VectorType &x) const;\n\n    private:\n        VectorType measuredData;\n        MatrixType dataCovariance;\n        MatrixType inverseCovariance;\n        MatrixType linearModel;\n        typename MatrixType::Scalar logNormalizationConstant;\n    };\n\n    template<typename MatrixType, typename VectorType>\n    LinearModel<MatrixType, VectorType>::LinearModel(\n            VectorType measuredData,\n            MatrixType dataCovariance,\n            MatrixType linearModel) :\n            measuredData(std::move(measuredData)),\n            dataCovariance(std::move(dataCovariance)),\n            linearModel(std::move(linearModel)) {\n        Eigen::LLT<MatrixType, Eigen::Upper> solver(this->dataCovariance);\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> matrixL = solver.matrixL();\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> matrixU = solver.matrixU();\n        Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> inverseMatrixL = matrixL.inverse();\n        inverseCovariance = inverseMatrixL * inverseMatrixL.transpose();\n\n        logNormalizationConstant = -static_cast<typename MatrixType::Scalar>(this->measuredData.rows()) / 2 *\n                                   std::log(2 * M_PI)\n                                   - matrixL.diagonal().array().log().sum();\n    }\n\n    template<typename MatrixType, typename VectorType>\n    typename MatrixType::Scalar\n    LinearModel<MatrixType, VectorType>::computeNegativeLogLikelihood(const VectorType &x) const {\n        return -logNormalizationConstant +\n               0.5 * static_cast<typename MatrixType::Scalar>((linearModel * x - measuredData).transpose() *\n                                                              inverseCovariance * (linearModel * x - measuredData));\n    }\n\n    template<typename MatrixType, typename VectorType>\n    MatrixType\n    LinearModel<MatrixType, VectorType>::computeExpectedFisherInformation(const VectorType &) const {\n        return inverseCovariance;\n    }\n\n    template<typename MatrixType, typename VectorType>\n    VectorType\n    LinearModel<MatrixType, VectorType>::computeLogLikelihoodGradient(const VectorType &x) const {\n        return -inverseCovariance * (linearModel*x - measuredData);\n    }\n}\n\n#endif //HOPS_LINEARMODEL_HPP\n", "meta": {"hexsha": "38b2be0ca12a8a8968ae3b52b9b18753cf42f734", "size": 3133, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/Model/LinearModel.hpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/Model/LinearModel.hpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/Model/LinearModel.hpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6790123457, "max_line_length": 118, "alphanum_fraction": 0.6750718162, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6221478371721084}}
{"text": "#include \"statistics.hpp\"\n\n#include <armadillo>\n\n\nvoid moment_function_4th(const arma::vec &seq,\n                         const int width,\n                         arma::vec &momfunc4)\n{\n  int num_seq = seq.n_rows;\n  int idx = 0;\n  for (int k = 0; k < width; ++k) {\n    for (int j = 0; j <= k; ++j) {\n      for (int i = 0; i <= j; ++i) {\n        if (i == 0 && k > 0 && k == j) continue;\n        double sum = 0;\n        for (int n = 0; n < num_seq - k; ++n) {\n          sum += seq(n) * seq(n + i) * seq(n + j) * seq(n + k);\n        }\n        momfunc4(idx) += sum;\n        idx++;\n      }\n    }\n  }\n}\n\nvoid cumulants_2nd(const arma::vec &seq,\n                   const int width,\n                   arma::vec &cum2)\n{\n  for (int i = 0; i < width; ++i) {\n    double sum = 0.;\n    for (int j = 0; j <= seq.n_elem - width; ++j) {\n      sum += seq(j) * seq(j + i);\n    }\n    cum2(i) += sum;\n  }\n}\n\n\nvoid cumulants_4th(const arma::vec &seq,\n                   const int n2,\n                   const int n4,\n                   arma::vec &cum4)\n{\n  int num_seq = seq.n_rows;\n  arma::vec cum2(n2, arma::fill::zeros);\n  cumulants_2nd(seq, n2, cum2);\n  double pwr = cum2(0) / num_seq;\n  double scale2 = 1.0 / cum2(0);\n  cum2 *= scale2;\n\n  arma::vec mfunc4(n4, arma::fill::zeros);\n  moment_function_4th(seq, n2, mfunc4);\n  double scale4 = 1.0 / (num_seq * std::pow(pwr, 2));\n\n  int idx = 0;\n  for (int k = 0; k < n2; ++k) {\n    for (int j = 0; j <= k; ++j) {\n      for (int i = 0; i <= j; ++i) {\n        if (i == 0 && k > 0 && k == j) continue;\n        double m4g = cum2(i) * cum2(k - j) + cum2(j) * cum2(k - i)\n          + cum2(k) * cum2(j - i);\n        cum4(idx) += (scale4 * mfunc4(idx) - m4g) * (n2 - k) / n2;\n\n        idx++;\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "aea09bb80ddebbf28ca3388d3d5b38148a943c52", "size": 1735, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/statistics.cc", "max_stars_repo_name": "pan3rock/c4we", "max_stars_repo_head_hexsha": "f4df270eab0554f4c887e0bba7f2689800c0f6e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-02T07:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T07:56:12.000Z", "max_issues_repo_path": "src/statistics.cc", "max_issues_repo_name": "pan3rock/c4we", "max_issues_repo_head_hexsha": "f4df270eab0554f4c887e0bba7f2689800c0f6e7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/statistics.cc", "max_forks_repo_name": "pan3rock/c4we", "max_forks_repo_head_hexsha": "f4df270eab0554f4c887e0bba7f2689800c0f6e7", "max_forks_repo_licenses": ["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.4366197183, "max_line_length": 66, "alphanum_fraction": 0.4461095101, "num_tokens": 620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.622147836320417}}
{"text": "#include \"fhd_math.h\"\n#include <math.h>\n#include <float.h>\n#include <assert.h>\n#include <Eigen/Dense>\n\nfhd_vec2 fhd_vec2_sub(fhd_vec2 a, fhd_vec2 b) {\n  fhd_vec2 r;\n  r.x = a.x - b.x;\n  r.y = a.y - b.y;\n  return r;\n}\n\nfhd_vec2 fhd_vec2_normalize(fhd_vec2 v) {\n  const float a = sqrtf(v.x * v.x + v.y * v.y);\n  return fhd_vec2{v.x / a, v.y / a};\n}\n\nfhd_vec2 fhd_vec2_mul(fhd_vec2 a, float s) { return {a.x * s, a.y * s}; }\n\nfhd_vec2 fhd_vec2_mul_pcw(fhd_vec2 a, fhd_vec2 b) {\n  return {a.x * b.x, a.y * b.y};\n}\n\nfloat fhd_vec2_distance(fhd_vec2 a, fhd_vec2 b) {\n  return hypotf(b.x - a.x, b.y - a.y);\n}\n\nfloat fhd_vec2_length(fhd_vec2 v) { return sqrtf(v.x * v.x + v.y * v.y); }\n\nfhd_vec3 fhd_vec3_normalize(fhd_vec3 v) {\n  const float a = sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);\n  return fhd_vec3{v.x / a, v.y / a, v.z / a};\n}\n\nfloat fhd_vec3_dot(fhd_vec3 a, fhd_vec3 b) {\n  return a.x * b.x + a.y * b.y + a.z * b.z;\n}\n\nfhd_vec3 fhd_vec3_sub(fhd_vec3 a, fhd_vec3 b) {\n  fhd_vec3 r;\n  r.x = a.x - b.x;\n  r.y = a.y - b.y;\n  r.z = a.z - b.z;\n  return r;\n}\n\nfhd_vec3 fhd_vec3_cross(fhd_vec3 u, fhd_vec3 v) {\n  const float t1 = u.x - u.y;\n  const float t2 = v.y + v.z;\n  const float t3 = u.x * v.z;\n  const float t4 = t1 * t2 - t3;\n\n  fhd_vec3 r;\n  r.x = v.y * (t1 - u.z) - t4;\n  r.y = u.z * v.x - t3;\n  r.z = t4 - u.y * (v.x - t2);\n\n  return r;\n}\n\nvoid fhd_aabb_expand(fhd_aabb* bbox, fhd_vec2 point) {\n  if (point.x < bbox->top_left.x)\n    bbox->top_left.x = point.x;\n  else if (point.x > bbox->bot_right.x)\n    bbox->bot_right.x = point.x;\n\n  if (point.y < bbox->top_left.y)\n    bbox->top_left.y = point.y;\n  else if (point.y > bbox->bot_right.y)\n    bbox->bot_right.y = point.y;\n}\n\nfhd_vec2 fhd_aabb_center(const fhd_aabb* bbox) {\n  return {(bbox->bot_right.x + bbox->top_left.x) * 0.5f,\n          (bbox->bot_right.y + bbox->top_left.y) * 0.5f};\n}\n\nbool fhd_aabb_overlap(const fhd_aabb* a, const fhd_aabb* b) {\n  if (a->bot_right.x < b->top_left.x || a->top_left.x > b->bot_right.x)\n    return false;\n  if (a->bot_right.y < b->top_left.y || a->top_left.y > b->bot_right.y)\n    return false;\n\n  return true;\n}\n\nfhd_vec2 fhd_aabb_size(const fhd_aabb* a) {\n  fhd_vec2 r;\n  r.x = a->bot_right.x - a->top_left.x;\n  r.y = a->bot_right.y - a->top_left.y;\n  return r;\n}\n\nfhd_aabb fhd_aabb_from_points(const fhd_vec2* points, int len) {\n  assert(len >= 2);\n\n  fhd_aabb bbox = {{FLT_MAX, FLT_MAX}, {-FLT_MAX, -FLT_MAX}};\n\n  for (int i = 0; i < len; i++) {\n    fhd_aabb_expand(&bbox, points[i]);\n  }\n\n  return bbox;\n}\n\nfloat fhd_plane_point_dist(fhd_plane p, fhd_vec3 q) {\n  return (fhd_vec3_dot(p.n, q) - p.d) / fhd_vec3_dot(p.n, p.n);\n}\n\nfhd_plane fhd_make_plane(fhd_vec3 a, fhd_vec3 b, fhd_vec3 c) {\n  fhd_plane p;\n  p.n = fhd_vec3_normalize(\n      fhd_vec3_cross(fhd_vec3_sub(b, a), fhd_vec3_sub(c, a)));\n  p.d = fhd_vec3_dot(p.n, a);\n  return p;\n}\n\nfloat fhd_fast_atan2(float y, float x) {\n  const float THRQTR_PI = 3.f * F_PI_4;\n  float r, angle;\n  float abs_y = fabs(y) + 1e-10f;\n  if (x < 0.0f) {\n    r = (x + abs_y) / (abs_y - x);\n    angle = THRQTR_PI;\n  } else {\n    r = (x - abs_y) / (x + abs_y);\n    angle = F_PI_4;\n  }\n  angle += (0.1963f * r * r - 0.9817f) * r;\n  if (y < 0.0f)\n    return -angle;\n  else\n    return angle;\n}\n\nfhd_vec3 fhd_pcl_normal(const fhd_vec3* points, int len) {\n  Eigen::Matrix3f A = Eigen::Matrix3f::Zero();\n  Eigen::Vector3f b = Eigen::Vector3f::Zero();\n  for (int i = 0; i < len; i++) {\n    const fhd_vec3 v = points[i];\n    A(0, 0) += v.x * v.x;\n    A(0, 1) += v.x * v.y;\n    A(0, 2) += v.x;\n    A(1, 0) += v.x * v.y;\n    A(1, 1) += v.y * v.y;\n    A(1, 2) += v.y;\n    A(2, 0) += v.x;\n    A(2, 1) += v.y;\n\n    b(0) += v.x * v.z;\n    b(1) += v.y * v.z;\n    b(2) += v.z;\n  }\n\n  A(2, 2) += float(len);\n  Eigen::Vector3f solution = A.llt().solve(b);\n  return fhd_vec3_normalize(fhd_vec3{solution(0), solution(1), solution(2)});\n}\n", "meta": {"hexsha": "e6b7af652aaeac0a45d015daa73391cf58520e2b", "size": 3856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fhd_math.cpp", "max_stars_repo_name": "seemk/FastHumanDetection", "max_stars_repo_head_hexsha": "097564ba703dbcbe9737c63882e7dc986646e328", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2016-04-10T19:37:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-26T10:38:07.000Z", "max_issues_repo_path": "src/fhd_math.cpp", "max_issues_repo_name": "seemk/FastHumanDetection", "max_issues_repo_head_hexsha": "097564ba703dbcbe9737c63882e7dc986646e328", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-06-04T16:12:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-02T23:08:22.000Z", "max_forks_repo_path": "src/fhd_math.cpp", "max_forks_repo_name": "seemk/FastHumanDetection", "max_forks_repo_head_hexsha": "097564ba703dbcbe9737c63882e7dc986646e328", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-06-13T04:48:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T15:28:13.000Z", "avg_line_length": 24.1, "max_line_length": 77, "alphanum_fraction": 0.5879149378, "num_tokens": 1561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6221478172946613}}
{"text": "//! [dot-main]\n#include <boost/simd/function/load.hpp>\n#include <boost/simd/function/sum.hpp>\n#include <boost/simd/pack.hpp>\n\ntemplate <typename Value>\nValue scaldot(Value* first1, Value* last1, Value* first2)\n{\n  Value v(0);\n\n  for (; first1 < last1; ++first1, ++first2) {\n    v += (*first1) * (*first2);\n  }\n  return v;\n}\n\ntemplate <typename Value>\nValue simddot(Value* first1, Value* last1, Value* first2)\n{\n  namespace bs = boost::simd;\n  using pack_t = bs::pack<Value>;\n\n  pack_t tmp{0};\n  int card = pack_t::static_size;\n\n  for (; first1 + card <= last1; first1 += card, first2 += card) {\n    // Load current values from the datasets\n    pack_t x1 = bs::load<pack_t>(first1);\n    pack_t x2 = bs::load<pack_t>(first2);\n    // Computation\n    tmp = tmp + x1 * x2;\n  }\n\n  Value dot_product = bs::sum(tmp);\n  for (; first1 < last1; ++first1, ++first2) {\n    dot_product += (*first1) * (*first2);\n  }\n\n  return dot_product;\n}\n\nint main()\n{\n  namespace bs = boost::simd;\n  using pack_t = bs::pack<float>;\n\n  const size_t size = 113;\n  float card_float  = bs::cardinal_of<pack_t>();\n\n  std::vector<float> v1(size), v2(size);\n  std::iota(v1.begin(), v1.end(), 0);\n  std::iota(v2.begin(), v2.end(), 1);\n  std::cout << \"scalar dot product output \" << scaldot(v1.data(), v1.data() + size, v2.data())\n            << std::endl;\n  std::cout << \"simd   dot product output \" << simddot(v1.data(), v1.data() + size, v2.data())\n            << std::endl;\n};\n// This code can be compiled using (for instance for gcc)\n// g++ dotmain.cpp -msse4.2 -std=c++11 -O3 -DNDEBUG -o dotmain\n// -I/path_to/boost_simd/ -I/path_to/boost/\n//! [dot-main]\n", "meta": {"hexsha": "8a09f83069778ee27d36e5d112ce4c5b5a917580", "size": 1625, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/dotmain.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "doc/examples/dotmain.cpp", "max_issues_repo_name": "dendisuhubdy/boost.simd", "max_issues_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/examples/dotmain.cpp", "max_forks_repo_name": "dendisuhubdy/boost.simd", "max_forks_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 26.2096774194, "max_line_length": 94, "alphanum_fraction": 0.6147692308, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.62188857012707}}
{"text": "// Copyright Paul A. Bristow 2018\r\n\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Example of most basic call of both lambert W functions.\r\n// Only requires C++03 \r\n// (and optionally a call of max_digits10 to show precision).\r\n\r\n#include <boost/math/special_functions/lambert_w.hpp> // For lambert_w0 and wm1 functions.\r\n\r\n#include <iostream>\r\n#include <iomanip>\r\n\r\nint main()\r\n{\r\n  double z = 2.0;\r\n  double w0 = boost::math::lambert_w0(z);\r\n  std::cout.setf(std::ios_base::showpoint); // Include any trailing zeros.\r\n  std::cout.precision(std::numeric_limits<double>::max_digits10); // Show all possibly significant digits.\r\n  // Avoid using max_digfigs10 so as many old compilers can run the most basic lambert_w0 test?\r\n  // Require to get max_digits10\r\n  //   [ run lambert_w_basic_example.cpp  : : : [ requires cxx11_numeric_limits ] ]\r\n  std::cout << \" lambert_w0(\" << z << \") = \" << w0 << std::endl; // lambert_w0(2.00000) = 0.852606\r\n  z = -0.2;\r\n  double wm1 = boost::math::lambert_wm1(z);\r\n  std::cout << \" lambert_wm1(\" << z << \") = \" << wm1 << std::endl; // lambert_wm1(-0.200000) = -2.54264\r\n  return 0;\r\n} // int main()\r\n", "meta": {"hexsha": "41b757b75822dd77a77b67e89b03f1858d0f1afd", "size": 1255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/libs/math/example/lambert_w_basic_example.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/lambert_w_basic_example.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/lambert_w_basic_example.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": 40.4838709677, "max_line_length": 107, "alphanum_fraction": 0.6685258964, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6218093496473531}}
{"text": "\n#ifndef Utils_LinearRegression_hpp\n#define Utils_LinearRegression_hpp\n\n/** @file LinearRegression.hpp\n  * @brief \n  * @author C.D. Clark III\n  * @date 07/07/17\n  */\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\nnamespace RUC {\n\n/*\n * @breif Perform least-squared linear regression on a set of x-y data points.\n *\n * @param x vector containing x coordinates of point to fit.\n * @param y vector containing y coordinates of point to fit.\n * @return A 2x1 matrix containing the y-intercept (element 0) and slope (element 1) of the fit.\n */\ntemplate<typename T>\nMatrix<T,2,1> LinearRegression( const Matrix<T,Dynamic,1> &x, const Matrix<T,Dynamic,1> &y )\n{\n  // given vectors x = | x0 | and y = | y0 | of x,y pairs,\n  //                   | x1 | and     | y1 |\n  //                   | .. | and     | .. |\n  //                   | xn | and     | yn |\n  //\n  // construct matrix X = | 1 x0 ] see https://en.wikipedia.org/wiki/Linear_least_squares_(mathematics)\n  //                      | 1 x1 ]\n  //                      | .... ]\n  //                      | 1 xn ]\n  //\n  // then coefficients matrix B = | b | that minimize sum of residuals is\n  //                              | m |\n  //\n  // is found by solveing X^T X B = X^T y,\n  // so\n  //       B = (X^T X)^-1 X^T y;\n\n  // matrix X\n  assert( x.size() == y.size() );\n\n  auto N = x.size();\n\n  Matrix<T,Dynamic,2> X(N,2);\n  // fill first column with 1's\n  X.block(0,0,N,1) = Matrix<T,Dynamic,1>::Constant(N,1,1);\n  // fill second column with x values\n  X.block(0,1,N,1) = x;\n\n  // need the transpose of X\n  auto Xtrans = X.transpose();\n\n  auto fit = (Xtrans*X).inverse()*Xtrans*y;\n\n  Matrix<T,2,1> ret;\n  ret[0] = fit[0];\n  ret[1] = fit[1];\n\n  return ret;\n}\n\n}\n\n\n#endif // include protector\n", "meta": {"hexsha": "33f5cff641dcee35b21d0e3a6204651a14fc10dd", "size": 1742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libArrhenius/Utils/LinearRegression.hpp", "max_stars_repo_name": "CD3/libArrhenius", "max_stars_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libArrhenius/Utils/LinearRegression.hpp", "max_issues_repo_name": "CD3/libArrhenius", "max_issues_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libArrhenius/Utils/LinearRegression.hpp", "max_forks_repo_name": "CD3/libArrhenius", "max_forks_repo_head_hexsha": "2cf65c9935c1661c6150ddfd86a999cf2fff2691", "max_forks_repo_licenses": ["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.8857142857, "max_line_length": 103, "alphanum_fraction": 0.5516647532, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6218093496473531}}
{"text": "#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <cmath>\n#include <cstddef>\n#include <dcs/debug.hpp>\n#include <dcs/math/random/mersenne_twister.hpp>\n#include <dcs/math/stats/distribution/mmpp.hpp>\n#include <dcs/test.hpp>\n\n\nstatic const double tol(1.0e-5);\n\n\nDCS_TEST_DEF( rand )\n{\n\tDCS_DEBUG_TRACE(\"Test Case: Random Variate Generation\");\n\n\ttypedef double real_type;\n\ttypedef ::boost::numeric::ublas::matrix<real_type> matrix_type;\n\ttypedef ::boost::numeric::ublas::vector<real_type> vector_type;\n\ttypedef ::std::size_t size_type;\n\n\tconst size_type n(2);\n\tconst unsigned long seed(5489UL);\n\n\tvector_type lambda(n);\n\tlambda(0) = 20;\n\tlambda(1) = 2;\n\n\tmatrix_type Q(n,n);\n\tQ(0,0) = -2; Q(0,1) =  2;\n\tQ(1,0) =  1; Q(1,1) = -1;\n\n\t::dcs::math::stats::mmpp_distribution<real_type> mmpp(lambda, Q);\n\tDCS_DEBUG_TRACE(\"Q: \" << mmpp.Q());\n\tDCS_DEBUG_TRACE(\"lambda: \" << mmpp.lambda());\n\n\t::dcs::math::random::mt19937 rng(seed);\n\n\treal_type res;\n\treal_type expect;\n\n\tres = ::dcs::math::stats::rand(mmpp, rng);\n\texpect = 0.107375;\n\tDCS_DEBUG_TRACE(\"x[1] \" << ::std::fixed << res);\n\tDCS_TEST_CHECK_CLOSE( res, expect, tol );\n}\n\nint main()\n{\n\tDCS_TEST_BEGIN();\n\n\tDCS_TEST_DO( rand );\n\n\tDCS_TEST_END();\n}\n", "meta": {"hexsha": "0cca4f7d83a3e13bf8d10d0385d39614474d9101", "size": 1230, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/src/dcs/test/math/stats/mmpp.cpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/src/dcs/test/math/stats/mmpp.cpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/src/dcs/test/math/stats/mmpp.cpp", "max_forks_repo_name": "sguazt/dcsxx-commons", "max_forks_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5789473684, "max_line_length": 66, "alphanum_fraction": 0.6853658537, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.7217431943271998, "lm_q1q2_score": 0.6218093290461488}}
{"text": "// Unit test for the cons2prim function in fvm_1d_functions.cpp\n// This function calculates the conservative variables based on the primitive variables for the 1D Euler equations\n// COMPLETE. This function works as intended. 2021/11/21\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"../main/fvm_1D_functions.h\" \n#include \"../main/testing_functions.h\" \n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n    \n    // Print what we are doing\n    cout << \"------------------------------------- \" << \\\n    \"This is a test of the cons2prim function.\" << \\\n    \" -------------------------------------\" << endl;    \n\n    // Set the input parameters to the cons2prim function\n    double gasGamma = 5./3.;   // Use standard gasGamma of 5/3\n\n    // Make an array of primitive variables such that there are two elements in each 1D array\n    Array<ArrayXd, 3, 1> Q;\n    Q(0) = ArrayXd::Zero(2) + 1.5;\n    Q(1) = ArrayXd::Zero(2) + 3.15;\n    Q(2) = ArrayXd::Zero(2) + 7.8075;\n\n    // Set the exact values for the primitive variables\n    Array<ArrayXd, 3, 1> V_exact;\n    V_exact(0) = ArrayXd::Zero(2) + 1.5;\n    V_exact(1) = ArrayXd::Zero(2) + 2.1;\n    V_exact(2) = ArrayXd::Zero(2) + 3.0;\n\n    // Initialize an array of conservative variables\n    Array<ArrayXd, 3, 1> V;\n    for (int var = 0; var < 3; var++ ) {\n        V(var) = ArrayXd::Zero(2);\n    }\n\n    // Calculate what the conserved variables are\n    cons2prim(gasGamma, Q, V);\n\n    // Set the acceptable tolerance. (Somewhat arbitrarily chosen)\n    double TOL = 1e-14;\n\n    // Determine if the two arrays are equal\n    Array<Array<bool,Dynamic,1>, 3, 1> boolArray = isEqualArray1D_of_Array1D(V, V_exact, TOL);\n\n    // Get the minimum value of the boolean array.\n    // If it is 0, then at least one value in this array is incorrect    \n    for (int var = 0; var < 3; var++) {\n        if (boolArray(var).minCoeff() == 0) {\n            cout << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl \\\n        << \"Test of cons2prim is a failure.\" << endl \\\n        << \"!!!!!!!!!!!!!!!!!!!!!!!!!!\" << endl;\n        break;\n        }\n        else if (var == 2) {\n            cout << \"Test of cons2prim is a success.\" << endl;\n        }\n    }\n \n    cout << endl << endl;\n}", "meta": {"hexsha": "091b67b0df30d71013645c8dcc06c47bb6e3efac", "size": 2207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FVM_1D/unitTests/test_cons2prim.cpp", "max_stars_repo_name": "Aquadorf/computational-skolar", "max_stars_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FVM_1D/unitTests/test_cons2prim.cpp", "max_issues_repo_name": "Aquadorf/computational-skolar", "max_issues_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FVM_1D/unitTests/test_cons2prim.cpp", "max_forks_repo_name": "Aquadorf/computational-skolar", "max_forks_repo_head_hexsha": "77ebab70fe22a9e48b7d187b965781fe941e3ae1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9538461538, "max_line_length": 114, "alphanum_fraction": 0.5718169461, "num_tokens": 639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6217759758868463}}
{"text": "#ifdef HOPS_GUROBI_FOUND\n\n#define BOOST_TEST_MODULE LinearProgramGurobiImplTestSuite\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/included/unit_test.hpp>\n#include <Eigen/Core>\n#include <hops/hops.hpp>\n\nBOOST_AUTO_TEST_SUITE(LinearProgrammingGurobiImpl)\n\n    BOOST_AUTO_TEST_CASE(solveSmallTestProblem) {\n        Eigen::VectorXd expectedParameters(2);\n        expectedParameters << 8.0 / 3, 2.0 / 3;\n\n        hops::LinearProgramSolution expectedSolution(10. / 3, expectedParameters, hops::LinearProgramStatus::OPTIMAL);\n\n        Eigen::MatrixXd A(3, 2);\n        A << 1, 2, 4, 2, -1, 1;\n        Eigen::VectorXd b(3);\n        b << 4, 12, 1;\n        Eigen::VectorXd obj(2);\n        obj << 1, 1;\n        hops::LinearProgramGurobiImpl linearProgram(A, b);\n        hops::LinearProgramSolution actualSolution = linearProgram.solve(obj);\n\n        BOOST_CHECK_CLOSE(actualSolution.objectiveValue, expectedSolution.objectiveValue, 0.0001);\n        BOOST_CHECK(actualSolution.optimalParameters.isApprox(expectedSolution.optimalParameters));\n        BOOST_CHECK(actualSolution.status == expectedSolution.status);\n    }\n\n    BOOST_AUTO_TEST_CASE(computeChebyshevCenter) {\n        Eigen::VectorXd expectedChebyshevCenter(2);\n        expectedChebyshevCenter << 0.29289321881345, 0.29289321881345;\n\n        Eigen::MatrixXd A(3, 2);\n        Eigen::VectorXd b(3);\n        A << 1, 1,\n                -1, 0,\n                0, -1;\n        b << 1, 0, 0;\n\n        auto linearProgram = hops::LinearProgramGurobiImpl(A, b);\n        auto actualChebyshevCenter = linearProgram.computeChebyshevCenter();\n\n        BOOST_CHECK(actualChebyshevCenter.optimalParameters.isApprox(expectedChebyshevCenter, 1e-12));\n    }\n\n    BOOST_AUTO_TEST_CASE(computeChebyshevCenterIsStableUnderRepeatedCalculations) {\n        Eigen::MatrixXd A(3, 2);\n        Eigen::VectorXd b(3);\n        A << 1, 1,\n                -1, 0,\n                0, -1;\n        b << 1, 0, 0;\n\n        auto linearProgram = hops::LinearProgramGurobiImpl(A, b);\n        auto actualChebyshevCenter1 = linearProgram.computeChebyshevCenter();\n        auto actualChebyshevCenter2 = linearProgram.computeChebyshevCenter();\n        auto actualChebyshevCenter3 = linearProgram.computeChebyshevCenter();\n        auto actualChebyshevCenter4 = linearProgram.computeChebyshevCenter();\n\n        BOOST_CHECK(actualChebyshevCenter1 == actualChebyshevCenter2);\n        BOOST_CHECK(actualChebyshevCenter1 == actualChebyshevCenter3);\n        BOOST_CHECK(actualChebyshevCenter1 == actualChebyshevCenter4);\n        BOOST_CHECK(actualChebyshevCenter2 == actualChebyshevCenter3);\n        BOOST_CHECK(actualChebyshevCenter2 == actualChebyshevCenter4);\n        BOOST_CHECK(actualChebyshevCenter3 == actualChebyshevCenter4);\n    }\n\n    BOOST_AUTO_TEST_CASE(removeSingleRedundantConstraintTest) {\n        Eigen::MatrixXd expectedA(4, 2);\n        expectedA << 1, 0, 0, 1, -1, 0, 0, -1;\n        Eigen::VectorXd expectedb(4);\n        expectedb << 1, 1, 1, 1;\n\n        Eigen::MatrixXd A(5, 2);\n        A << 1, 0, 0, 1, -1, 0, 0, -1, 1, 0;\n        Eigen::VectorXd b(5);\n        b << 1, 1, 1, 1, 2;\n\n        auto linearProgram = hops::LinearProgramGurobiImpl(A, b);\n        auto[actualA, actualb] = linearProgram.removeRedundantConstraints(1e-15);\n\n        BOOST_CHECK(actualA.isApprox(expectedA));\n        BOOST_CHECK(actualb.isApprox(expectedb));\n    }\n\n    BOOST_AUTO_TEST_CASE(removeSeveralRedundantConstraintsTest) {\n        Eigen::MatrixXd expectedA(4, 2);\n        expectedA << 1, 0, 0, 1, -1, 0, 0, -1;\n        Eigen::VectorXd expectedB(4);\n        expectedB << 1, 1, 1, 1;\n\n        Eigen::MatrixXd A(10, 2);\n        A << 1, 0, 0, 1, -1, 0, 0, -1, 1, 0,\n                1, 0, 1, 0, 1, 0, 1, 0, 1, 0;\n        Eigen::VectorXd b(10);\n        b << 1, 1, 1, 1, 2, 7, 4, 2, 100, 5;\n\n        auto linearProgram = hops::LinearProgramGurobiImpl(A, b);\n        auto[actualA, actualB] = linearProgram.removeRedundantConstraints(1e-15);\n        BOOST_CHECK(actualA.isApprox(expectedA));\n        BOOST_CHECK(actualB.isApprox(expectedB));\n    }\n\n    BOOST_AUTO_TEST_CASE(computeUnconstrainedDimensions) {\n        std::vector<long> expectedUnboundDirections{1, -1};\n\n        Eigen::MatrixXd A(2, 2);\n        A << 0, 1, 0, -1;\n        Eigen::VectorXd b(2);\n        b << 1, 1;\n\n        auto linearProgram = hops::LinearProgramGurobiImpl(A, b);\n        auto actualUnboundDirections = linearProgram.computeUnconstrainedDimensions();\n\n        BOOST_CHECK(actualUnboundDirections == expectedUnboundDirections);\n    }\n\n    BOOST_AUTO_TEST_CASE(addConstraintsToUnconstrainedDimensions) {\n        Eigen::MatrixXd expectedA(4, 2);\n        expectedA << 0, 1, 0, -1, 1, 0, -1, 0;\n        Eigen::VectorXd expectedB(4);\n        expectedB << 1, 1, 3, 2;\n\n        Eigen::MatrixXd A(2, 2);\n        A << 0, 1, 0, -1;\n        Eigen::VectorXd b(2);\n        b << 1, 1;\n\n        auto linearProgram = hops::LinearProgramGurobiImpl(A, b);\n        auto[actualA, actualB] = linearProgram.addBoxConstraintsToUnconstrainedDimensions(2, 3);\n\n        BOOST_CHECK(actualA == expectedA);\n        BOOST_CHECK(actualB == expectedB);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n\n#endif //HOPS_GUROBI_FOUND\n", "meta": {"hexsha": "1306c377e70700cf4d6adb0f4fd3bfb022249f3e", "size": 5154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/LinearProgram/LinearProgramGurobiImplTestSuite.cpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "tests/LinearProgram/LinearProgramGurobiImplTestSuite.cpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "tests/LinearProgram/LinearProgramGurobiImplTestSuite.cpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2957746479, "max_line_length": 118, "alphanum_fraction": 0.6459060924, "num_tokens": 1522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6217759697097333}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <vector>\n\nusing Eigen::Map;\nusing Eigen::MatrixXd;\nusing Eigen::MatrixXf;\nusing Eigen::VectorXd;\nusing Eigen::VectorXf;\nusing namespace std;\n\nclass ANN\n{\nprivate:\n    MatrixXd Wh, W0;\n    VectorXd bh, b0;\n    int input_layer = 5 * 5, hidden_layer = 16, output_layer;\n    double lr = 1.;\n    double eps = 1e-6;\n\npublic:\n    ANN(vector<MatrixXd *> &train_symbols)\n    {\n        double HI = 2., LO = -2.;\n        double range = HI - LO;\n\n        output_layer = train_symbols.size();\n\n        Wh = MatrixXd::Random(hidden_layer, input_layer);\n        Wh = (Wh + MatrixXd::Constant(hidden_layer, input_layer, 1.)) * range / 2.;\n        Wh = (Wh + MatrixXd::Constant(hidden_layer, input_layer, LO));\n\n        bh = VectorXd::Zero(hidden_layer);\n\n        W0 = MatrixXd::Random(output_layer, hidden_layer);\n        W0 = (W0 + MatrixXd::Constant(output_layer, hidden_layer, 1.)) * range / 2.;\n        W0 = (W0 + MatrixXd::Constant(output_layer, hidden_layer, LO));\n\n        b0 = VectorXd::Zero(output_layer);\n        train(train_symbols);\n    }\n\n    double sigmoid(double x)\n    {\n        return 1.0 / (1.0 + exp(-x));\n    }\n\n    void train(vector<MatrixXd *> train_symbols)\n    {\n        MatrixXd EW0, EWh, EI0, EIh;\n        do\n        {\n            int i = 0;\n            for (std::vector<MatrixXd *>::iterator it = train_symbols.begin(); it != train_symbols.end(); ++it)\n            {\n                MatrixXd yd = MatrixXd::Zero(output_layer, 1);\n                yd(i) = 1.;\n                // Forward pass\n                MatrixXd X = **it;\n                Map<VectorXd> X_flat(X.data(), X.size());\n\n                MatrixXd Vh = Wh * X_flat + bh;\n                MatrixXd Zh = Vh.unaryExpr([](double x) { return 1.0 / (1.0 + exp(-x)); });\n                MatrixXd U0 = W0 * Zh + b0;\n                MatrixXd Y0 = U0.unaryExpr([](double x) { return 1.0 / (1.0 + exp(-x)); });\n\n                // Backward propagation\n                MatrixXd EA0 = Y0 - yd;\n                EI0 = EA0.cwiseProduct(Y0.cwiseProduct((MatrixXd)(1 - Y0.array())));\n                EW0 = EI0 * Zh.transpose();\n                MatrixXd EAh = W0.transpose() * EI0;\n                EIh = EAh.cwiseProduct(Zh.cwiseProduct((MatrixXd)(1 - Zh.array())));\n                EWh = EIh * X_flat.transpose();\n\n                //Update params\n                W0 = (W0 - lr * EW0);\n                Wh = (Wh - lr * EWh);\n                b0 = (b0 + lr * EI0);\n                bh = (bh + lr * EIh);\n\n                i += 1;\n            }\n        } while (!(EW0.isZero(eps) && EWh.isZero(eps) && EI0.isZero(eps) && EIh.isZero(eps)));\n    }\n\n    VectorXd *test(MatrixXd &symbol)\n    {\n        MatrixXd X = symbol;\n        Map<VectorXd> X_flat(X.data(), X.size());\n\n        MatrixXd Vh = Wh * X_flat + bh;\n        MatrixXd Zh = Vh.unaryExpr([](double x) { return 1.0 / (1.0 + exp(-x)); });\n        MatrixXd U0 = W0 * Zh + b0;\n        MatrixXd *Y0 = new MatrixXd(U0.rows(), U0.cols());\n        *Y0 << U0.unaryExpr([](double x) { return 1.0 / (1.0 + exp(-x)); });\n        return (VectorXd *)Y0;\n    }\n};\n\nint main()\n{\n    srand((unsigned int)time(0));\n    vector<MatrixXd *> train_symbols;\n    MatrixXd m1, m2;\n    m1 = MatrixXd::Random(5, 5);\n    train_symbols.push_back(&m1);\n    m2 = MatrixXd::Random(5, 5);\n    train_symbols.push_back(&m2);\n    ANN a(train_symbols);\n    VectorXd *y2 = a.test(m2);\n    cout << *y2 << '\\n';\n    VectorXd *y1 = a.test(m1);\n    cout << *y1 << '\\n';\n}\n", "meta": {"hexsha": "2f75b666f9b128b4ca0530341b911d79989d80d5", "size": 3507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lab2/ANN.cpp", "max_stars_repo_name": "DominikSpiljak/Advanced-Algorithms-and-Data-Structures", "max_stars_repo_head_hexsha": "54821168abbf90e9fe3a810189fe57fba435bb3f", "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": "lab2/ANN.cpp", "max_issues_repo_name": "DominikSpiljak/Advanced-Algorithms-and-Data-Structures", "max_issues_repo_head_hexsha": "54821168abbf90e9fe3a810189fe57fba435bb3f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab2/ANN.cpp", "max_forks_repo_name": "DominikSpiljak/Advanced-Algorithms-and-Data-Structures", "max_forks_repo_head_hexsha": "54821168abbf90e9fe3a810189fe57fba435bb3f", "max_forks_repo_licenses": ["Apache-2.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.2327586207, "max_line_length": 111, "alphanum_fraction": 0.5166809239, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871156, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.6217564109652639}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <iterator>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Random.h>\n\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/Polyhedron_items_with_id_3.h>\n#include <CGAL/IO/Polyhedron_iostream.h>\n\n#include <CGAL/Surface_mesh_shortest_path.h>\n#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>\n#include <CGAL/boost/graph/iterator.h>\n\n#include <boost/variant.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef CGAL::Polyhedron_3<Kernel, CGAL::Polyhedron_items_with_id_3> Polyhedron_3;\ntypedef CGAL::Surface_mesh_shortest_path_traits<Kernel, Polyhedron_3> Traits;\ntypedef CGAL::Surface_mesh_shortest_path<Traits> Surface_mesh_shortest_path;\ntypedef Traits::Barycentric_coordinate Barycentric_coordinate;\ntypedef boost::graph_traits<Polyhedron_3> Graph_traits;\ntypedef Graph_traits::vertex_iterator vertex_iterator;\ntypedef Graph_traits::face_iterator face_iterator;\ntypedef Graph_traits::vertex_descriptor vertex_descriptor;\ntypedef Graph_traits::face_descriptor face_descriptor;\ntypedef Graph_traits::halfedge_descriptor halfedge_descriptor;\n\n// A model of SurfaceMeshShortestPathVisitor storing simplicies\n// using boost::variant\nstruct Sequence_collector\n{\n  typedef boost::variant< vertex_descriptor,\n                         std::pair<halfedge_descriptor,double>,\n                         std::pair<face_descriptor, Barycentric_coordinate> > Simplex;\n  std::vector< Simplex > sequence;\n\n  void operator()(halfedge_descriptor he, double alpha)\n  {\n\n    sequence.push_back( std::make_pair(he, alpha) );\n  }\n\n  void operator()(vertex_descriptor v)\n  {\n    sequence.push_back( v );\n  }\n\n  void operator()(face_descriptor f, Barycentric_coordinate alpha)\n  {\n    sequence.push_back( std::make_pair(f, alpha) );\n  }\n};\n\n// A visitor to print what a variant contains using boost::apply_visitor\nstruct Print_visitor : public boost::static_visitor<> {\n  int i;\n  Polyhedron_3& g;\n\n  Print_visitor(Polyhedron_3& g) :i(-1), g(g) {}\n\n  void operator()(vertex_descriptor v)\n  {\n    std::cout << \"#\" << ++i << \" : Vertex : \" << get(boost::vertex_index, g)[v] << \"\\n\";\n  }\n\n  void operator()(const std::pair<halfedge_descriptor,double>& h_a)\n  {\n    std::cout << \"#\" << ++i << \" : Edge : \" << get(CGAL::halfedge_index, g)[h_a.first] << \" , (\"\n                                            << 1.0 - h_a.second << \" , \"\n                                            << h_a.second << \")\\n\";\n  }\n\n  void operator()(const std::pair<face_descriptor, Barycentric_coordinate>& f_bc)\n  {\n    std::cout << \"#\" << ++i << \" : Face : \" << get(CGAL::face_index, g)[f_bc.first] << \" , (\"\n                                            << f_bc.second[0] << \" , \"\n                                            << f_bc.second[1] << \" , \"\n                                            << f_bc.second[2] << \")\\n\";\n  }\n};\n\nint main(int argc, char** argv)\n{\n  // read input polyhedron\n  Polyhedron_3 polyhedron;\n  std::ifstream input((argc>1)?argv[1]:\"data/elephant.off\");\n  input >> polyhedron;\n  input.close();\n\n  // initialize indices of vertices, halfedges and facets\n  CGAL::set_halfedgeds_items_id(polyhedron);\n\n  // pick up a random face\n  const size_t randSeed = argc > 2 ? std::atoi(argv[2]) : 7915421;\n  CGAL::Random rand(randSeed);\n  const int target_face_index = rand.get_int(0, num_faces(polyhedron));\n  face_iterator face_it = faces(polyhedron).first;\n  std::advance(face_it,target_face_index);\n  // ... and define a barycentric coordinate inside the face\n  Barycentric_coordinate face_location = {{0.25, 0.5, 0.25}};\n\n  // construct a shortest path query object and add a source point\n  Surface_mesh_shortest_path shortest_paths(polyhedron);\n  shortest_paths.add_source_point(*face_it, face_location);\n\n  // pick a random target point inside a face\n  face_it = faces(polyhedron).first;\n  std::advance(face_it, rand.get_int(0, num_faces(polyhedron)));\n\n  // collect the sequence of simplicies crossed by the shortest path\n  Sequence_collector sequence_collector;\n  shortest_paths.shortest_path_sequence_to_source_points(*face_it, face_location, sequence_collector);\n\n  // print the sequence using the visitor pattern\n  Print_visitor print_visitor(polyhedron);\n  for (size_t i = 0; i < sequence_collector.sequence.size(); ++i)\n    boost::apply_visitor(print_visitor, sequence_collector.sequence[i]);\n\n  return 0;\n}\n", "meta": {"hexsha": "d29c38a9d7af1a3f783346c97075945956a5a998", "size": 4409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Surface_mesh_shortest_path/examples/Surface_mesh_shortest_path/shortest_path_sequence.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Surface_mesh_shortest_path/examples/Surface_mesh_shortest_path/shortest_path_sequence.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Surface_mesh_shortest_path/examples/Surface_mesh_shortest_path/shortest_path_sequence.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.272, "max_line_length": 102, "alphanum_fraction": 0.6919936494, "num_tokens": 1118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6217451869830325}}
{"text": "#pragma once\n\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n#include <unsupported/Eigen/NumericalDiff>\n#include \"grid3d.hpp\"\n#include <ros/ros.h>\n\n// std\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n// Generic functor for Eigen Levenberg-Marquardt minimizer\ntemplate<typename _Scalar, int NX = Dynamic, int NY = Dynamic>\nstruct Functor {\n    typedef _Scalar Scalar;\n    enum {\n        InputsAtCompileTime = NX,\n        ValuesAtCompileTime = NY\n    };\n    typedef Eigen::Matrix<Scalar, InputsAtCompileTime, 1> InputType;\n    typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, 1> ValueType;\n    typedef Eigen::Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime> JacobianType;\n\n    const int m_inputs, m_values;\n\n    Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n\n    Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n    int inputs() const { return m_inputs; }\n\n    int values() const { return m_values; }\n};\n\nstruct PoseEstimator : Functor<double> {\n    /**\n     * Default amount of sensors needed for Eigen templated structure\n     * @param numberOfSensors you can however choose any number of sensors here\n     */\n    PoseEstimator(int numberOfSensors = 4);\n    ~PoseEstimator(){\n      delete grid;\n    }\n\n    /**\n     * This is the function that is called in each iteration\n     * @param x the pose vector (3 rotational parameters)\n     * @param fvec the error function (the difference between the sensor positions)\n     * @return\n     */\n    int operator()(const VectorXd &x, VectorXd &fvec) const;\n\n    VectorXd pose;\n    vector<Vector3d> sensor_pos, sensor_angle, sensor_target;\n    int numberOfSensors = 4;\n    Grid<float> *grid;\n    float theta_range, theta_min;\n};\n", "meta": {"hexsha": "4da88c753e0ab1bed04f376ad129285a8bf19bd8", "size": 1810, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ball_in_socket_estimator/pose_estimator.hpp", "max_stars_repo_name": "Devanthro/ball_in_socket_estimator", "max_stars_repo_head_hexsha": "5793db2dfd22b693c082694c2130a16c92164d70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-10-22T03:29:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-24T21:04:01.000Z", "max_issues_repo_path": "include/ball_in_socket_estimator/pose_estimator.hpp", "max_issues_repo_name": "Devanthro/ball_in_socket_estimator", "max_issues_repo_head_hexsha": "5793db2dfd22b693c082694c2130a16c92164d70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ball_in_socket_estimator/pose_estimator.hpp", "max_forks_repo_name": "Devanthro/ball_in_socket_estimator", "max_forks_repo_head_hexsha": "5793db2dfd22b693c082694c2130a16c92164d70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-08T10:13:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T10:13:50.000Z", "avg_line_length": 28.7301587302, "max_line_length": 89, "alphanum_fraction": 0.7049723757, "num_tokens": 435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6217451740571267}}
{"text": "//****************************************************************************\n// (c) 2008, 2009 by the openOR Team\n//****************************************************************************\n// The contents of this file are available under the GPL v2.0 license\n// or under the openOR comercial license. see\n//   /Doc/openOR_free_license.txt or\n//   /Doc/openOR_comercial_license.txt\n// for Details.\n//****************************************************************************\n/**\n* @file\n* @author Christian Winne\n* @ingroup openOR_core_math\n*/\n\n#ifndef openOR_core_Math_detail_determinant_impl_hpp\n#define openOR_core_Math_detail_determinant_impl_hpp\n\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/void.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n#include <openOR/Math/matrix.hpp>\n\n\nnamespace openOR {\n\tnamespace Math {\n\t\tnamespace Impl {\n\n\t\t\ttemplate<class Type, int Dim>\n\t\t\tstruct Determinant {\n\t\t\t\ttypename MatrixTraits<Type>::ValueType operator()(const Type& mat) const {\n\t\t\t\t\t// function has to be implemented\n\n\t\t\t\t\tBOOST_MPL_ASSERT((boost::is_same<Type, boost::mpl::void_>));\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t//determinant of 2x2 matrix\n\t\t\ttemplate<class Type>\n\t\t\tstruct Determinant<Type, 2> {\n\t\t\t\ttypename MatrixTraits<Type>::ValueType operator()(const Type& mat) const {\n\t\t\t\t\treturn Math::get<0, 0>(mat) * Math::get<1, 1>(mat) - Math::get<0, 1>(mat) * Math::get<1, 0>(mat);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t//determinant of 3x3 matrix\n\t\t\ttemplate<class Type>\n\t\t\tstruct Determinant<Type, 3> {\n\t\t\t\ttypename MatrixTraits<Type>::ValueType operator()(const Type& mat) const {\n\t\t\t\t\treturn Math::get<0, 0>(mat) * Math::get<1, 1>(mat) * Math::get<2, 2>(mat) +\n\t\t\t\t\t\tMath::get<0, 1>(mat) * Math::get<1, 2>(mat) * Math::get<2, 0>(mat) +\n\t\t\t\t\t\tMath::get<0, 2>(mat) * Math::get<1, 0>(mat) * Math::get<2, 1>(mat) -\n\t\t\t\t\t\tMath::get<2, 0>(mat) * Math::get<1, 1>(mat) * Math::get<0, 2>(mat) -\n\t\t\t\t\t\tMath::get<2, 1>(mat) * Math::get<1, 2>(mat) * Math::get<0, 0>(mat) -\n\t\t\t\t\t\tMath::get<2, 2>(mat) * Math::get<1, 0>(mat) * Math::get<0, 1>(mat);\n\t\t\t\t}\n\t\t\t};\n\t\t\t//determinant of 4x4 matrix\n\t\t\ttemplate<class Type>\n\t\t\tstruct Determinant<Type, 4> {\n\t\t\t\ttypename MatrixTraits<Type>::ValueType operator()(const Type& mat) const {\n\t\t\t\t\treturn   Math::get<0, 0>(mat) * Math::get<1, 1>(mat) * Math::get<2, 2>(mat) * Math::get<3, 3>(mat) +\n\t\t\t\t\t\tMath::get<0, 0>(mat) * Math::get<1, 2>(mat) * Math::get<2, 3>(mat) * Math::get<3, 1>(mat) +\n\t\t\t\t\t\tMath::get<0, 0>(mat) * Math::get<1, 3>(mat) * Math::get<2, 1>(mat) * Math::get<3, 2>(mat) +\n\n\t\t\t\t\t\tMath::get<0, 1>(mat) * Math::get<1, 0>(mat) * Math::get<2, 3>(mat) * Math::get<3, 2>(mat) +\n\t\t\t\t\t\tMath::get<0, 1>(mat) * Math::get<1, 2>(mat) * Math::get<2, 0>(mat) * Math::get<3, 3>(mat) +\n\t\t\t\t\t\tMath::get<0, 1>(mat) * Math::get<1, 3>(mat) * Math::get<2, 2>(mat) * Math::get<3, 0>(mat) +\n\n\t\t\t\t\t\tMath::get<0, 2>(mat) * Math::get<1, 0>(mat) * Math::get<2, 1>(mat) * Math::get<3, 3>(mat) +\n\t\t\t\t\t\tMath::get<0, 2>(mat) * Math::get<1, 1>(mat) * Math::get<2, 3>(mat) * Math::get<3, 0>(mat) +\n\t\t\t\t\t\tMath::get<0, 2>(mat) * Math::get<1, 3>(mat) * Math::get<2, 0>(mat) * Math::get<3, 1>(mat) +\n\n\t\t\t\t\t\tMath::get<0, 3>(mat) * Math::get<1, 0>(mat) * Math::get<2, 2>(mat) * Math::get<3, 1>(mat) +\n\t\t\t\t\t\tMath::get<0, 3>(mat) * Math::get<1, 1>(mat) * Math::get<2, 0>(mat) * Math::get<3, 2>(mat) +\n\t\t\t\t\t\tMath::get<0, 3>(mat) * Math::get<1, 2>(mat) * Math::get<2, 1>(mat) * Math::get<3, 0>(mat) -\n\n\t\t\t\t\t\tMath::get<0, 0>(mat) * Math::get<1, 1>(mat) * Math::get<2, 3>(mat) * Math::get<3, 2>(mat) -\n\t\t\t\t\t\tMath::get<0, 0>(mat) * Math::get<1, 2>(mat) * Math::get<2, 1>(mat) * Math::get<3, 3>(mat) -\n\t\t\t\t\t\tMath::get<0, 0>(mat) * Math::get<1, 3>(mat) * Math::get<2, 2>(mat) * Math::get<3, 1>(mat) -\n\n\t\t\t\t\t\tMath::get<0, 1>(mat) * Math::get<1, 0>(mat) * Math::get<2, 2>(mat) * Math::get<3, 3>(mat) -\n\t\t\t\t\t\tMath::get<0, 1>(mat) * Math::get<1, 2>(mat) * Math::get<2, 3>(mat) * Math::get<3, 0>(mat) - \n\t\t\t\t\t\tMath::get<0, 1>(mat) * Math::get<1, 3>(mat) * Math::get<2, 0>(mat) * Math::get<3, 2>(mat) -\n\n\t\t\t\t\t\tMath::get<0, 2>(mat) * Math::get<1, 0>(mat) * Math::get<2, 3>(mat) * Math::get<3, 1>(mat) -\n\t\t\t\t\t\tMath::get<0, 2>(mat) * Math::get<1, 1>(mat) * Math::get<2, 0>(mat) * Math::get<3, 3>(mat) -\n\t\t\t\t\t\tMath::get<0, 2>(mat) * Math::get<1, 3>(mat) * Math::get<2, 1>(mat) * Math::get<3, 0>(mat) -\n\n\t\t\t\t\t\tMath::get<0, 3>(mat) * Math::get<1, 0>(mat) * Math::get<2, 1>(mat) * Math::get<3, 2>(mat) -\n\t\t\t\t\t\tMath::get<0, 3>(mat) * Math::get<1, 1>(mat) * Math::get<2, 2>(mat) * Math::get<3, 0>(mat) -\n\t\t\t\t\t\tMath::get<0, 3>(mat) * Math::get<1, 2>(mat) * Math::get<2, 0>(mat) * Math::get<3, 1>(mat);\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t}\n\t}\n}\n\n\n#endif\n", "meta": {"hexsha": "ff9d435afe8003a578af0aa2577f578a5467c2e6", "size": 4594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/include/openOR/Math/detail/determinant_impl.hpp", "max_stars_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_stars_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/include/openOR/Math/detail/determinant_impl.hpp", "max_issues_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_issues_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/include/openOR/Math/detail/determinant_impl.hpp", "max_forks_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_forks_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1730769231, "max_line_length": 105, "alphanum_fraction": 0.5306922072, "num_tokens": 1872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755218, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6217061295379654}}
{"text": "\n// #include <Eigen/Dense>\n#include <opencv2/opencv.hpp>\n#include <numeric>\n#include <vector>\n#include \"kernel.h\"\n#include \"distance.h\"\n#include \"meanshift.h\"\n\n\nusing namespace ModelFitting;\n\n// #define EPSILON 0.00000001\n// #define CLUSTER_EPSILON 0.5\n\nMeanShift::MeanShift():\n        max_iterations(100000),\n\t\tmax_inner_iterations(10000)\n{\n\n}\n\nMeanShift::MeanShift(\n    double (*_distance_metirc)(cv::Mat &, cv::Mat &, const int &) ,\n    double (*_kernel)(const double &, const double &)): \n    MeanShift()\n{\n    this->calculate_distance = _distance_metirc;\n    this->calculate_kernel = _kernel;\n}\n\nMeanShift::~MeanShift()\n{\n}\n\nvoid MeanShift::cluster(\n    cv::InputArray _data_pts, \n    cv::OutputArray _clusters_centers, \n    std::vector<std::vector<int>> &_cluster_pts,\n    double kernel_bandwidth)\n{\n    // initialization\n    const cv::Mat data_pts = _data_pts.getMat();\n    const int dim_num = data_pts.cols;\n    const int pts_num = data_pts.rows;\n    \n    std::cout << dim_num << \", \" << pts_num << std::endl;\n    // std::cout << data_pts << std::endl;\n    int cluster_num = 0;\n    const double bandwidth_sq = kernel_bandwidth * kernel_bandwidth;\n    const double hald_bandwith = static_cast<double>(kernel_bandwidth/2);\n    const double stop_threshold = static_cast<double>(1e-3*kernel_bandwidth); \n\n    std::vector<int> init_pts_inds(pts_num); // initial points indices\n    std::iota(init_pts_inds.begin(), init_pts_inds.end(), 0);\n\n    // double stop_threshold = 1e-3 * kernel_bandwidth; // need casting\n\n    std::vector<int> been_visited(pts_num,0);\n    std::vector<cv::Mat> cluster_votes;//(pts_num,std::vector<int>(pts_num, 0));\n    cv::Mat current_cluster_votes;\n    std::vector<cv::Mat> clusters_centers;\n\n    cv::RNG gen;\n    int tmp_idx, pt_idx;\n    cv::Mat current_mean, old_mean;\n    std::vector<int> current_cluster_members(0);\n\n    // Iterate over all data points\n    int iters = 0;\n    while (init_pts_inds.size() && iters++ < max_iterations)// && num pf iterations)\n    {\n        tmp_idx = gen.uniform(0,init_pts_inds.size());\n        pt_idx = init_pts_inds[tmp_idx];\n        //\n        current_mean = data_pts.row(pt_idx);\n        current_cluster_members.resize(0);\n        current_cluster_votes = cv::Mat_<int>(1,pts_num, 0);//.resize(pts_num, 0);\n        //\n        int inner_iters = 0;\n        while(inner_iters++ < max_inner_iterations)\n        {\n            // std::cout << max_inner_iterations << std::endl;\n            // mean shift procedure\n            // 1. Compute the mean shift vector m\n            // 2. translate the old mean\n            // 1.1 iterate over all points and find indices of points \n            //     that its distances from the current mean is less than the bandwidth\n            // 1.2 vote for those points as clusters\n            // 1.3 pass those points ||(current_mean - pts_i)/bandwidth|| to the kernel\n            // 1.4 sum the return values of the kernel\n            old_mean = current_mean.clone();\n            current_mean = cv::Mat::zeros(1, data_pts.cols, data_pts.type());\n\n            meanshift(\n                data_pts,\n                pts_num,\n                dim_num,\n                old_mean, \n                current_mean,\n                current_cluster_votes,\n                current_cluster_members,\n                been_visited,\n                kernel_bandwidth);\n\n            // checking stopping condition for current cluster\n            if(this->calculate_distance(current_mean, old_mean, dim_num) < stop_threshold)\n            {\n                // std::cout << this->calculate_distance(current_mean, old_mean, dim_num) << std::endl;\n                // check for merge posibilities\n                int merge_with = -1;\n                for(size_t c = 0; c < cluster_num; c++)\n                {\n                    // distance from posible new cluster max to old cluster max\n                    double dist_to_other = this->calculate_distance(current_mean, clusters_centers.at(c), dim_num);\n                    if(dist_to_other < hald_bandwith)\n                    {\n                        merge_with = c;\n                        break;\n                    }\n                }\n\n                if (merge_with > -1)\n                {\n                    clusters_centers.at(merge_with) = 0.5 * (current_mean + clusters_centers.at(merge_with));\n                    cluster_votes.at(merge_with) += current_cluster_votes;\n                }\n                else\n                {\n                    // increment cluster numbers\n                    ++cluster_num;\n                    // record the current mean\n                    clusters_centers.push_back(current_mean);\n                    cluster_votes.push_back(current_cluster_votes);\n                }\n                break;\n            }\n        }\n\n        // remove visited points\n        init_pts_inds.erase(\n            std::remove_if(\n                init_pts_inds.begin(),\n                init_pts_inds.end(),\n                [been_visited](int pts_idx){ return been_visited.at(pts_idx) == 1;}\n            ),\n            init_pts_inds.end()\n        );\n    }\n    \n    // assigning points to clusters\n    std::vector<int> pts_cluster_votes(pts_num, 0);\n    std::vector<int> pts_cluster_idx(pts_num, -1);\n    \n    for (size_t pt_idx = 0; pt_idx < pts_num; pt_idx++)\n    {\n        for (size_t cluster_idx = 0; cluster_idx < cluster_num; cluster_idx++)\n        {\n            if(pts_cluster_votes.at(pt_idx) < cluster_votes.at(cluster_idx).at<int>(pt_idx))\n            {\n                pts_cluster_votes.at(pt_idx) = cluster_votes.at(cluster_idx).at<int>(pt_idx);\n                pts_cluster_idx.at(pt_idx) = cluster_idx;\n            }\n        }\n        \n    }\n    \n    \n    // refactor centers as Mat(center_num, dim_num)\n    _clusters_centers.create(static_cast<int>(cluster_votes.size()), dim_num, data_pts.type());\n\tcv::Mat const &clusters_ref = _clusters_centers.getMatRef();\n\tfor (auto i = 0; i < clusters_centers.size(); ++i)\n\t\tclusters_centers[i].copyTo(clusters_ref.row(i));\n    \n\n    // refactor cluster points as a vector of vectors of points indices\n    _cluster_pts.resize(cluster_votes.size());\n\tfor (size_t i = 0; i < pts_cluster_idx.size(); ++i)\n\t{\n\t\tif (pts_cluster_idx[i] == -1)\n\t\t\tcontinue;\n\t\t_cluster_pts[pts_cluster_idx[i]].push_back(i);\n\t}\n    \n\n    return;\n}\n\n\nvoid MeanShift::meanshift(\n    const cv::Mat &_data_pts,\n    const int _pts_num,\n    const int _dim_num,\n    cv::Mat &_old_mean, \n    cv::Mat &_new_mean,\n    cv::Mat &_current_cluster_votes,\n    std::vector<int> &_current_culster_members,\n    std::vector<int> &_been_visited,\n    const double _kernel_bandwidth)\n{\n    // mean shift procedure\n    // 1. Compute the mean shift vector m\n    // 2. translate the old mean\n    // 1.1 iterate over all points and find indices of points \n    //     that its distances from the current mean is less than the bandwidth\n    double distance_val = 0;\n    double kernel_val = 0;\n    double normalizer = 0;\n    int window_members_num = 0;\n    cv::Mat current_pt;\n    for (size_t idx = 0; idx < _pts_num; idx++)\n    {\n        // calculate the distance\n        current_pt = _data_pts.row(idx);\n        distance_val = this->calculate_distance(_old_mean, current_pt, _dim_num);\n        \n        if(distance_val <= _kernel_bandwidth)\n        {\n        // 1.2 vote for those points as clusters\n            ++_current_cluster_votes.at<int>(idx);\n        // 1.3 pass those points ||(current_mean - pts_i)/bandwidth|| to the kernel\n            kernel_val = this->calculate_kernel(distance_val, _kernel_bandwidth);\n            ++window_members_num;\n        // 1.4 sum the return values of the kernel\n            _new_mean += _data_pts.row(idx) * kernel_val;\n            normalizer += kernel_val;\n            _been_visited.at(idx) = 1;\n            _current_culster_members.push_back(idx);\n            \n        }\n        idx++;\n        \n    }\n    if(window_members_num == 0)\n    {\n        _new_mean = _old_mean;\n        return;\n    }\n    _new_mean /= normalizer;\n}", "meta": {"hexsha": "fea0dc44b590fe190d26c955436a006340ec63be", "size": 8007, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "lib/meanshift.cxx", "max_stars_repo_name": "SohilZidan/mean-shift-clustering", "max_stars_repo_head_hexsha": "5483b97018c707ff0822f106f54083d1cf76f7be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/meanshift.cxx", "max_issues_repo_name": "SohilZidan/mean-shift-clustering", "max_issues_repo_head_hexsha": "5483b97018c707ff0822f106f54083d1cf76f7be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/meanshift.cxx", "max_forks_repo_name": "SohilZidan/mean-shift-clustering", "max_forks_repo_head_hexsha": "5483b97018c707ff0822f106f54083d1cf76f7be", "max_forks_repo_licenses": ["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.3625, "max_line_length": 115, "alphanum_fraction": 0.5889846384, "num_tokens": 1866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6217061275611717}}
{"text": "#include \"registration.h\"\n#include <Eigen/Cholesky>\n#include <vector>\n\nstruct SPoint2D\n{\n\tdouble x[2];\n};\n\ndouble ComputeAngle(const Eigen::Vector2d& input_one, const Eigen::Vector2d& input_two)\n{\n\t//compute theta\n\t//when e_im.dot(e_i) = 1.0, theta = pi;\n\tconst double r_sinT = input_one(0)*input_two(1) - input_one(1)*input_two(0);\n\tconst double r_cosT = -input_one.dot(input_two);\n\treturn atan2(r_sinT, r_cosT);\n}\n\ndouble sgn(const double& x)\n{\n\treturn (x >= 0) ? 1.0 : -1.0;\n}\n\n\ndouble ComputeOmegaFromAngle(const double& theta)\n{\n\tconst double sinT = sin(theta);\n\tconst double cosT = cos(theta);\n\tconst double tan_phi_over_2 = sgn(sinT) * sqrt((1.0+cosT)/(max(0.0, 1.0-cosT) + 1.0e-10));\n\treturn 2.0 * tan_phi_over_2;\n}\n\ndouble computeOmega(const Eigen::Vector2d& input_one, const Eigen::Vector2d& input_two)\n{\n\t//compute 2.0 * tan(phi / 2.0)\n\t//phi = pi - theta\n\treturn ComputeOmegaFromAngle(ComputeAngle(input_one, input_two));\t\n}\n\ndouble sampleDistanceField(const SImage<double, 1>& in_df, const SRegion& in_region, const Eigen::Vector2d& x)\n{\n\tassert(in_df.width == in_df.height);\n\tassert(in_region.right-in_region.left == in_region.top-in_region.bottom);\n\n\tEigen::Vector2d proj_x = x;\n\tproj_x(0) = std::max(in_region.left, std::min(in_region.right, x(0)));\n\tproj_x(1) = std::max(in_region.bottom, std::min(in_region.top, x(1)));\n\n\tconst double dist_scale = (in_region.right-in_region.left) / in_df.width;\n\n\tdouble fi = (proj_x(0) - in_region.left) * in_df.width / (in_region.right - in_region.left);\n\tdouble fj = (proj_x(1) - in_region.bottom) * in_df.height / (in_region.top - in_region.bottom);\n\tdouble _i = floor(fi);\n\tdouble _j = floor(fj);\n\n\tint i = std::max(0, std::min(in_df.width-1, int(_i)));\n\tint j = std::max(0, std::min(in_df.height-1, int(_j)));\n\tint ip = std::min(in_df.width-1, i+1);\n\tint jp = std::min(in_df.height-1, j+1);\n\n\tdouble s = fi - _i;\n\tdouble t = fj - _j;\n\n\tdouble dist_proj = (1.0 - t) * (s * in_df.ptr[j*in_df.width+ip] + (1.0-s) * in_df.ptr[j*in_df.width+i])\n\t\t+ t * (s * in_df.ptr[jp*in_df.width+ip] + (1.0-s) * in_df.ptr[jp*in_df.width+i]);\n\n\treturn dist_proj * dist_scale + (proj_x - x).norm();\n}\n\ndouble integrateDF2OverSegment(const SParameters* in_params, const Eigen::Vector2d& x1, const Eigen::Vector2d& x2, const double rest_length)\n{\n\tdouble tot = 0.0;\n\tconst double len = rest_length / in_params->substep_fit;\n\n\t//printf(\"integ_DF: \");\n\tfor(int i=0; i<in_params->substep_fit; i++)\n\t{\n\t\tconst Eigen::Vector2d& p1 = x1 + (x2-x1) * double(i)/double(in_params->substep_fit);\n\t\tconst Eigen::Vector2d& p2 = x1 + (x2-x1) * double(i+1)/double(in_params->substep_fit);\n\t\t\n\t\tconst double d1 = sampleDistanceField(in_params->df, in_params->region, p1);\n\t\tconst double d2 = sampleDistanceField(in_params->df, in_params->region, p2);\n\n\t\t//printf(\"[%f, %f, %f], \", d1, d2, len);\n\n\t\tconst double e1 = 0.5 * (exp(d1) + exp(-d1)) - 1.0;\n\t\tconst double e2 = 0.5 * (exp(d2) + exp(-d2)) - 1.0;\n\n\t\t//tot += 0.5 * (d1*d1+d2*d2) * len;\n\t\ttot += 0.5 * (e1*e1+e2*e2) * len;\n\t}\n\t//printf(\"\\n\");\n\n\treturn tot;\n}\n\ninline double computeSegmentElasticEnergy(const Eigen::Vector2d& p1, const Eigen::Vector2d& p2, const double& YA, const double& rest_length)\n{\n\tconst Eigen::Vector2d diff = p1 - p2;\n\treturn 0.5 * YA * rest_length\n\t\t* (diff.norm() / rest_length - 1)\n\t\t* (diff.norm() / rest_length - 1);\n}\n\ninline double computeSegmentBendingEnergy(const Eigen::Vector2d& pp, const Eigen::Vector2d& pc, const Eigen::Vector2d& pn, \n\tconst double& alpha, const double& rest_length_p, const double& rest_length_n, const double& theta)\n{\n\tconst Eigen::Vector2d e_im = pc - pp;\n\tconst Eigen::Vector2d e_i = pn - pc;\n\n\t/*\n\tdouble omega = 2.0 * fabs(e_im(0)*e_i(1)-e_im(1)*e_i(0)) / (e_im.norm()*e_i.norm() + e_im.dot(e_i));\n\tdouble omega_bar = 2.0 * fabs(tan(phi*0.5));\n\t//*/\n\tdouble omega = computeOmega(e_im, e_i);\n\tdouble omega_bar = ComputeOmegaFromAngle(theta);\n\treturn alpha * (omega - omega_bar) * (omega - omega_bar) / (rest_length_p + rest_length_n);\n}\n\ndouble computeEnergy_elastic(const SParameters* in_params, const SCurve* in_curve, const Eigen::Matrix2Xd& in_position)\n{\n\tint nSegs = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 1;\n\n\tdouble energy = 0.0;\n\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % in_curve->nVertices;\n\t\tenergy += computeSegmentElasticEnergy(in_position.col(ip), in_position.col(i), in_params->YA, in_curve->restLengths(i));\n\t}\n\n\treturn energy;\n}\n\ndouble computeEnergy_bending(const SParameters* in_params, const SCurve* in_curve, const Eigen::Matrix2Xd& in_position)\n{\n\tint nAngles = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 2; \n\n\tdouble energy = 0.0;\n\n\tfor(int i=0; i<nAngles; i++)\n\t{\n\t\tint iim = in_curve->closed ? \n\t\t\t(i + in_curve->nVertices - 1) % in_curve->nVertices : i;\n\t\tint ii = in_curve->closed ? i : i + 1;\n\t\tint iip = in_curve->closed ? (i + 1) % in_curve->nVertices : i + 2;\n\n\t\tdouble restL_m = in_curve->closed ? in_curve->restLengths((i + in_curve->nVertices - 1) % in_curve->nVertices) : \n\t\t\tin_curve->restLengths(i);\n\t\tdouble restL = in_curve->closed ? in_curve->restLengths(i) : \n\t\t\tin_curve->restLengths(i+1);\n\n\t\tenergy += computeSegmentBendingEnergy(in_position.col(iim), in_position.col(ii), in_position.col(iip),\n\t\t\tin_params->alpha, restL_m, restL, in_curve->restAngles(i));\n\t}\n\n\treturn energy;\n}\n\ndouble computeEnergy_fit(const SParameters* in_params, const SCurve* in_curve, const Eigen::Matrix2Xd& in_position)\n{\n\tint nSegs = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 1;\n\n\tdouble energy = 0.0;\n\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % in_curve->nVertices;\n\t\tdouble int_df_seg = integrateDF2OverSegment(in_params, in_position.col(i), in_position.col(ip), in_curve->restLengths(i));\n\t\tenergy += 0.5 * in_params->fit * int_df_seg;\n\t}\n\n\treturn energy;\n}\n\ndouble ComputeEnergy(const SParameters* in_params, const SCurve* in_curve, const SVar& in_vars)\n{\n\tconst double E_elastic = computeEnergy_elastic(in_params, in_curve, in_vars.pos);\n\tconst double E_bending = computeEnergy_bending(in_params, in_curve, in_vars.pos);\n\tconst double E_fit = computeEnergy_fit(in_params, in_curve, in_vars.pos);\n\treturn E_elastic + E_bending + E_fit;\n}\n\nvoid compute_f_elastic(const SParameters* in_params, const SCurve* in_curve, const Eigen::Matrix2Xd& in_position, Eigen::VectorXd& io_f, int offset_row)\n{\n\tint nSegs = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 1;\n\n\tassert(io_f.rows() >= nSegs + offset_row);\n\tassert(in_curve->nVertices == in_position.cols());\n\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % in_curve->nVertices;\n\t\tconst Eigen::Vector2d diff = in_position.col(ip) - in_position.col(i);\n\t\tio_f(i+offset_row) = sqrt(0.5 * in_params->YA * in_curve->restLengths(i)) * (diff.norm() / in_curve->restLengths(i) - 1);\n\t}\n}\n\nvoid compute_f_bending(const SParameters* in_params, const SCurve* in_curve, const Eigen::Matrix2Xd& in_position, Eigen::VectorXd& io_f, int offset_row)\n{\n\tint nAngles = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 2; \n\n\tassert(io_f.rows() >= nAngles + offset_row);\n\tassert(in_curve->nVertices == in_position.cols());\n\n\tfor(int i=0; i<nAngles; i++)\n\t{\n\t\tint iim = in_curve->closed ? \n\t\t\t(i + in_curve->nVertices - 1) % in_curve->nVertices : i;\n\t\tint ii = in_curve->closed ? i : i + 1;\n\t\tint iip = in_curve->closed ? (i + 1) % in_curve->nVertices : i + 2;\n\n\t\tdouble restL_m = in_curve->closed ? in_curve->restLengths((i + in_curve->nVertices - 1) % in_curve->nVertices) : \n\t\t\tin_curve->restLengths(i);\n\t\tdouble restL = in_curve->closed ? in_curve->restLengths(i) : \n\t\t\tin_curve->restLengths(i+1);\n\n\t\tconst Eigen::Vector2d e_im = in_position.col(ii) - in_position.col(iim);\n\t\tconst Eigen::Vector2d e_i = in_position.col(iip) - in_position.col(ii);\n\n\t\t/*\n\t\tdouble omega = 2.0 * fabs(e_im(0)*e_i(1)-e_im(1)*e_i(0)) / (e_im.norm()*e_i.norm() + e_im.dot(e_i));\n\t\tdouble omega_bar = 2.0 * fabs(tan(in_curve->restAngles(i)*0.5));\n\t\t//*/\n\t\tdouble omega = computeOmega(e_im, e_i);\n\t\tdouble omega_bar = ComputeOmegaFromAngle(in_curve->restAngles(i));\n\t\tio_f(i+offset_row) = sqrt(in_params->alpha/(restL_m + restL)) * (omega - omega_bar);\n\t}\n}\n\nvoid compute_f_fit(const SParameters* in_params, const SCurve* in_curve, const Eigen::Matrix2Xd& in_position, Eigen::VectorXd& io_f, int offset_row)\n{\n\tint nSegs = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 1;\n\n\tassert(io_f.rows() >= nSegs + offset_row);\n\tassert(in_curve->nVertices == in_position.cols());\n\n\t//printf(\"int_seg: \");\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % in_curve->nVertices;\n\t\tdouble int_df_seg = integrateDF2OverSegment(in_params, in_position.col(i), in_position.col(ip), in_curve->restLengths(i));\n\t\t//printf(\"%f, \", int_df_seg);\n\t\tio_f(i+offset_row) = sqrt(in_params->fit * 0.5) * sqrt(int_df_seg);\n\t}\n\t//printf(\"\\n\");\n}\n\nvoid Compute_f(const SParameters* in_params, const SCurve* in_curve, const SVar& in_vars, Eigen::VectorXd& io_f)\n{\n\tint nSegs = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 1;\n\tint nAngles = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 2; \n\n\tint nElems = nSegs + nAngles + nSegs;\n\n\tassert(io_f.rows() == nElems);\n\tassert(in_curve->nVertices == in_vars.pos.cols());\n\tassert(in_curve->nVertices == in_vars.pos.cols());\n\n\tio_f.setZero();\n\n\tcompute_f_elastic(in_params, in_curve, in_vars.pos, io_f, 0);\n\tcompute_f_bending(in_params, in_curve, in_vars.pos, io_f, nSegs);\n\tcompute_f_fit(in_params, in_curve, in_vars.pos, io_f, nSegs+nAngles);\n\n\t/*\n\tprintf(\"f: [\");\n\tfor(int i=0; i<nElems; i++)\n\t{\n\t\tif(i<nElems-1) printf(\"%f, \", io_f(i));\n\t\telse printf(\"%f]\\n\", io_f(i));\n\t}\n\t//*/\n}\n\nvoid computeNumericalDerivative_elastic(const SParameters* in_params, const SCurve* in_curve, const Eigen::Matrix2Xd& in_position, double epsilon, Eigen::MatrixXd& io_jacobian, int offset_row)\n{\n\tint nSegs = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 1;\n\n\tassert(io_jacobian.rows() >= nSegs + offset_row);\n\tassert(io_jacobian.cols() == in_curve->nVertices * 2);\n\n\tconst Eigen::Vector2d dx(epsilon, 0.0); \n\tconst Eigen::Vector2d dy(0.0, epsilon);\n\n\t//dJ/dxi, dJ/dyi\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\t//l_i is a function of x_i, x_{i+1}, y_i and y_{i+1}\n\t\tint ip = (i+1) % in_curve->nVertices;\n\n\t\tconst Eigen::Vector2d xi = in_position.col(i);\n\t\tconst Eigen::Vector2d xip = in_position.col(ip);\n\n\t\tconst Eigen::Vector2d diff0 = xip - xi;\n\t\tconst double fi = sqrt(in_params->YA * in_curve->restLengths(i) * 0.5) * (diff0.norm() / in_curve->restLengths(i) - 1);\n\n\t\t//dJ/dxi_i\n\t\tconst Eigen::Vector2d xi_dx = xi + dx;\n\t\tconst Eigen::Vector2d diff1 = xip - xi_dx;\n\t\tconst double fi_i_dx = sqrt(in_params->YA * in_curve->restLengths(i) * 0.5) * (diff1.norm() / in_curve->restLengths(i) - 1);\n\t\tio_jacobian(i+offset_row, i) = (fi_i_dx - fi) / epsilon;\n\n\t\t//dJ/dyi_i\n\t\tconst Eigen::Vector2d xi_dy = xi + dy;\n\t\tconst Eigen::Vector2d diff2 = xip - xi_dy;\n\t\tconst double fi_i_dy = sqrt(in_params->YA * in_curve->restLengths(i) * 0.5) * (diff2.norm() / in_curve->restLengths(i) - 1);\n\t\tio_jacobian(i+offset_row, i+in_curve->nVertices) = (fi_i_dy - fi) / epsilon;\n\n\t\t//dJ/dxi_ip\n\t\tconst Eigen::Vector2d xip_dx = xip + dx;\n\t\tconst Eigen::Vector2d diff3 = xip_dx - xi;\n\t\tconst double fi_ip_dx = sqrt(in_params->YA * in_curve->restLengths(i) * 0.5) * (diff3.norm() / in_curve->restLengths(i) - 1);\n\t\tio_jacobian(i+offset_row, ip) = (fi_ip_dx - fi) / epsilon;\n\t\t\n\t\t//dJ/dyi_i\n\t\tconst Eigen::Vector2d xip_dy = xip + dy;\n\t\tconst Eigen::Vector2d diff4 = xip_dy - xi;\n\t\tconst double fi_ip_dy = sqrt(in_params->YA * in_curve->restLengths(i) * 0.5) * (diff4.norm() / in_curve->restLengths(i) - 1);\n\t\tio_jacobian(i+offset_row, ip+in_curve->nVertices) = (fi_ip_dy - fi) / epsilon;\n\t}\n}\n\nvoid computeNumericalDerivative_bending(const SParameters* in_params, const SCurve* in_curve, const Eigen::Matrix2Xd& in_position, double epsilon, Eigen::MatrixXd& io_jacobian, int offset_row)\n{\n\tint nAngles = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 2; \n\n\tassert(io_jacobian.rows() >= nAngles + offset_row);\n\tassert(io_jacobian.cols() == in_curve->nVertices * 2);\n\n\tconst Eigen::Vector2d dx(epsilon, 0.0); \n\tconst Eigen::Vector2d dy(0.0, epsilon);\n\n\t//dB/dxi, dB/dyi\n\tfor(int i=0; i<nAngles; i++)\n\t{\n\t\tint iim = in_curve->closed ? \n\t\t\t(i + in_curve->nVertices - 1) % in_curve->nVertices : i;\n\t\tint ii = in_curve->closed ? i : i + 1;\n\t\tint iip = in_curve->closed ? (i + 1) % in_curve->nVertices : i + 2;\n\n\t\tdouble restL_m = in_curve->restLengths(iim);\n\t\tdouble restL = in_curve->restLengths(ii);\n\n\t\tconst Eigen::Vector2d xim = in_position.col(iim);\n\t\tconst Eigen::Vector2d xi = in_position.col(ii);\n\t\tconst Eigen::Vector2d xip = in_position.col(iip);\n\n\t\tconst Eigen::Vector2d xim_dx = xim + dx; const Eigen::Vector2d xim_dy = xim + dy;\n\t\tconst Eigen::Vector2d xi_dx = xi + dx; const Eigen::Vector2d xi_dy = xi + dy;\n\t\tconst Eigen::Vector2d xip_dx = xip + dx; const Eigen::Vector2d xip_dy = xip + dy;\n\n\t\tconst Eigen::Vector2d e_prev = xi - xim;\n\t\tconst Eigen::Vector2d e_next = xip - xi;\n\n\t\tconst Eigen::Vector2d e_prev_im_dx = xi - xim_dx; const Eigen::Vector2d e_prev_im_dy = xi - xim_dy;\n\t\tconst Eigen::Vector2d e_prev_i_dx = xi_dx - xim; const Eigen::Vector2d e_prev_i_dy = xi_dy - xim;\n\n\t\tconst Eigen::Vector2d e_next_i_dx = xip - xi_dx; const Eigen::Vector2d e_next_i_dy = xip - xi_dy;\n\t\tconst Eigen::Vector2d e_next_ip_dx = xip_dx - xi; const Eigen::Vector2d e_next_ip_dy = xip_dy - xi;\n\n\t\t/*\n\t\tconst double omega = 2.0 * fabs(e_prev(0)*e_next(1)-e_prev(1)*e_next(0)) / (e_prev.norm()*e_next.norm() + e_prev.dot(e_next));\n\n\t\tconst double omega_im_dx = 2.0 * fabs(e_prev_im_dx(0)*e_next(1)-e_prev_im_dx(1)*e_next(0)) / (e_prev_im_dx.norm()*e_next.norm() + e_prev_im_dx.dot(e_next));\n\t\tconst double omega_im_dy = 2.0 * fabs(e_prev_im_dy(0)*e_next(1)-e_prev_im_dy(1)*e_next(0)) / (e_prev_im_dy.norm()*e_next.norm() + e_prev_im_dy.dot(e_next));\n\t\tconst double omega_i_dx = 2.0 * fabs(e_prev_i_dx(0)*e_next_i_dx(1)-e_prev_i_dx(1)*e_next_i_dx(0)) / (e_prev_i_dx.norm()*e_next_i_dx.norm() + e_prev_i_dx.dot(e_next_i_dx));\n\t\tconst double omega_i_dy = 2.0 * fabs(e_prev_i_dy(0)*e_next_i_dy(1)-e_prev_i_dy(1)*e_next_i_dy(0)) / (e_prev_i_dy.norm()*e_next_i_dy.norm() + e_prev_i_dy.dot(e_next_i_dy));\n\t\tconst double omega_ip_dx = 2.0 * fabs(e_prev(0)*e_next_ip_dx(1)-e_prev(1)*e_next_ip_dx(0)) / (e_prev.norm()*e_next_ip_dx.norm() + e_prev.dot(e_next_ip_dx));\n\t\tconst double omega_ip_dy = 2.0 * fabs(e_prev(0)*e_next_ip_dy(1)-e_prev(1)*e_next_ip_dy(0)) / (e_prev.norm()*e_next_ip_dy.norm() + e_prev.dot(e_next_ip_dy));\n\t\t//*/\n\n\t\tconst double omega = computeOmega(e_prev, e_next);\n\n\t\tconst double omega_im_dx = computeOmega(e_prev_im_dx, e_next);\n\t\tconst double omega_im_dy = computeOmega(e_prev_im_dy, e_next);\n\t\tconst double omega_i_dx = computeOmega(e_prev_i_dx, e_next_i_dx);\n\t\tconst double omega_i_dy = computeOmega(e_prev_i_dy, e_next_i_dy);\n\t\tconst double omega_ip_dx = computeOmega(e_prev, e_next_ip_dx);\n\t\tconst double omega_ip_dy = computeOmega(e_prev, e_next_ip_dy);\t\t\n\n\t\tconst double fi = sqrt(in_params->alpha/(restL_m + restL)) * omega; //omega_bar will be cancelled out, so omit it\n\t\tconst double fi_im_dx = sqrt(in_params->alpha/(restL_m + restL)) * omega_im_dx;\n\t\tconst double fi_im_dy = sqrt(in_params->alpha/(restL_m + restL)) * omega_im_dy;\n\t\tconst double fi_i_dx = sqrt(in_params->alpha/(restL_m + restL)) * omega_i_dx;\n\t\tconst double fi_i_dy = sqrt(in_params->alpha/(restL_m + restL)) * omega_i_dy;\n\t\tconst double fi_ip_dx = sqrt(in_params->alpha/(restL_m + restL)) * omega_ip_dx;\n\t\tconst double fi_ip_dy = sqrt(in_params->alpha/(restL_m + restL)) * omega_ip_dy;\n\t\t\n\t\tio_jacobian(i+offset_row, iim) = (fi_im_dx - fi) / epsilon;\n\t\tio_jacobian(i+offset_row, iim+in_curve->nVertices) = (fi_im_dy - fi) / epsilon;\n\n\t\tio_jacobian(i+offset_row, ii) = (fi_i_dx - fi) / epsilon;\n\t\tio_jacobian(i+offset_row, ii+in_curve->nVertices) = (fi_i_dy - fi) / epsilon;\n\n\t\tio_jacobian(i+offset_row, iip) = (fi_ip_dx - fi) / epsilon;\n\t\tio_jacobian(i+offset_row, iip+in_curve->nVertices) = (fi_ip_dy - fi) / epsilon;\n\t}\n}\n\nvoid computeNumericalDerivative_fit(const SParameters* in_params, const SCurve* in_curve, const Eigen::Matrix2Xd& in_position, double epsilon, Eigen::MatrixXd& io_jacobian, int offset_row)\n{\n\tint nSegs = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 1;\n\n\tassert(io_jacobian.rows() >= nSegs + offset_row);\n\tassert(io_jacobian.cols() == in_curve->nVertices * 2);\n\n\tconst Eigen::Vector2d dx(epsilon, 0.0); \n\tconst Eigen::Vector2d dy(0.0, epsilon);\n\n\t//dfit/dxi, dfit/dyi\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\t//l_i is a function of x_i, x_{i+1}, y_i and y_{i+1}\n\t\tint ip = (i+1) % in_curve->nVertices;\n\n\t\tconst Eigen::Vector2d xi = in_position.col(i);\n\t\tconst Eigen::Vector2d xip = in_position.col(ip);\n\t\tconst double restL = in_curve->restLengths(i);\n\n\t\tconst double fi = sqrt(in_params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_params, xi, xip, restL));\n\n\t\t//dfit/dxi_i\n\t\tconst Eigen::Vector2d xi_dx = xi + dx;\n\t\tconst double fi_i_dx = sqrt(in_params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_params, xi_dx, xip, restL));\n\t\tio_jacobian(i+offset_row, i) = (fi_i_dx - fi) / epsilon;\n\n\t\t//dfit/dyi_i\n\t\tconst Eigen::Vector2d xi_dy = xi + dy;\n\t\tconst double fi_i_dy = sqrt(in_params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_params, xi_dy, xip, restL));\n\t\tio_jacobian(i+offset_row, i+in_curve->nVertices) = (fi_i_dy - fi) / epsilon;\n\n\t\t//dfit/dxi_ip\n\t\tconst Eigen::Vector2d xip_dx = xip + dx;\n\t\tconst double fi_ip_dx = sqrt(in_params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_params, xi, xip_dx, restL));\n\t\tio_jacobian(i+offset_row, ip) = (fi_ip_dx - fi) / epsilon;\n\t\t\n\t\t//dfit/dyi_i\n\t\tconst Eigen::Vector2d xip_dy = xip + dy;\n\t\tconst double fi_ip_dy = sqrt(in_params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_params, xi, xip_dy, restL));\n\t\tio_jacobian(i+offset_row, ip+in_curve->nVertices) = (fi_ip_dy - fi) / epsilon;\n\t}\n}\n\nvoid ComputeNumericalDerivative(const SParameters* in_params, const SCurve* in_curve, const SVar& in_vars, double epsilon, Eigen::MatrixXd& io_jacobian)\n{\n\tint nSegs = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 1;\n\tint nAngles = in_curve->closed ? in_curve->nVertices : in_curve->nVertices - 2; \n\n\t//assert(io_jacobian.rows() == nSegs + nAngles + nSegs);\n\t//assert(io_jacobian.cols() == in_curve->nVertices * 2);\n\t//assert(in_vars.pos.cols() == in_curve->nVertices);\n\t//assert(in_vars.conf.cols() == in_curve->nVertices);\n\n\tio_jacobian.setZero();\n\n\tcomputeNumericalDerivative_elastic(in_params, in_curve, in_vars.pos, epsilon, io_jacobian, 0);\n\tcomputeNumericalDerivative_bending(in_params, in_curve, in_vars.pos, epsilon, io_jacobian, nSegs);\n\tcomputeNumericalDerivative_fit(in_params, in_curve, in_vars.pos, epsilon, io_jacobian, nSegs+nAngles);\n\n\t/*\n\tprintf(\"B: [\\n\");\n\tfor(int j=0; j<io_jacobian.rows(); j++)\n\t{\n\t\tprintf(\"[\");\n\t\tfor(int i=0; i<io_jacobian.cols(); i++)\n\t\t{\n\t\t\tif(i<io_jacobian.cols()-1) printf(\"%f, \", io_jacobian(j, i));\n\t\t\telse printf(\"%f],\\n\", io_jacobian(j, i));\n\t\t}\n\t}\n\tprintf(\"]\\n\");\n\t//*/\n}\n\nvoid UpdateRestLength(const Eigen::Matrix2Xd& in_position, SCurve* io_curve)\n{\n\tint nSegs = io_curve->closed ? io_curve->nVertices : io_curve->nVertices - 1;\n\tassert(io_curve->nVertices == in_position.cols());\n\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % io_curve->nVertices;\n\t\tconst Eigen::Vector2d diff = in_position.col(ip) - in_position.col(i);\n\t\tio_curve->restLengths(i) = diff.norm();\n\t}\n}\n\nvoid UpdateCurveSubdivision(const SParameters* in_params, SVar& io_initial_vars, SVar& io_vars, SCurve* io_curve, SSolverVars& io_solver_vars)\n{\n\tint nSegs = io_curve->closed ? io_curve->nVertices : io_curve->nVertices - 1;\n\t//assert(io_curve->nVertices == in_position.cols());\n\n\tstd::vector<SPoint2D> pos;\n\tstd::vector<double> angles;\n\tstd::vector<int> vids;\n\n\tbool subdivided = false;\n\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tSPoint2D p; p.x[0] = io_vars.pos.col(i)(0); p.x[1] = io_vars.pos.col(i)(1);\n\t\tpos.push_back(p);\n\t\tvids.push_back(io_curve->vertexIDs(i));\n\n\t\tif(i!=0 || io_curve->closed) angles.push_back(io_curve->restAngles(i));\n\n\t\tint ip = (i+1) % io_curve->nVertices;\n\t\tconst Eigen::Vector2d diff = io_vars.pos.col(ip) - io_vars.pos.col(i);\n\t\tif(diff.norm() > in_params->refLength)\n\t\t{\n\t\t\tSPoint2D p;\n\t\t\tp.x[0] = (io_vars.pos.col(ip)(0) + io_vars.pos.col(i)(0)) * 0.5;\n\t\t\tp.x[1] = (io_vars.pos.col(ip)(1) + io_vars.pos.col(i)(1)) * 0.5;\n\t\t\tpos.push_back(p);\n\t\t\t//angles.push_back((io_curve->restAngles(i) + io_curve->restAngles(ip)) * 0.5);\n\t\t\tangles.push_back(PI);\n\t\t\tvids.push_back(-1);\n\t\t\tsubdivided = true;\n\t\t}\n\t}\n\n\tif(!io_curve->closed)\n\t{\n\t\tint ilast = io_curve->nVertices-1;\n\t\tSPoint2D p; p.x[0] = io_vars.pos.col(ilast)(0); p.x[1] = io_vars.pos.col(ilast)(1);\n\t\tpos.push_back(p);\n\t\tvids.push_back(io_curve->vertexIDs(ilast));\n\t}\n\n\tio_curve->nVertices = pos.size();\n\tnSegs = io_curve->closed ? io_curve->nVertices : io_curve->nVertices - 1;\n\tio_curve->restLengths.resize(nSegs);\n\tint nAngles = io_curve->closed ? io_curve->nVertices : io_curve->nVertices - 2; \n\tio_curve->restAngles.resize(nAngles);\n\tio_curve->vertexIDs.resize(io_curve->nVertices);\n\n\tresize(io_vars, io_curve->nVertices);\n\tresize(io_initial_vars, io_curve->nVertices);\n\n\tfor(int i=0; i<io_curve->nVertices; i++)\n\t{\n\t\tio_vars.pos.col(i)(0) = pos[i].x[0];\n\t\tio_vars.pos.col(i)(1) = pos[i].x[1];\n\t\tio_vars.conf(i) = 0.0;\n\t\tio_curve->vertexIDs(i) = vids[i];\n\t}\n\n\tnSegs = io_curve->closed ? io_curve->nVertices : io_curve->nVertices - 1;\n\tfor(int i=0; i<nSegs; i++)\n\t{\n\t\tint ip = (i+1) % io_curve->nVertices;\n\t\tconst Eigen::Vector2d diff = io_vars.pos.col(ip) - io_vars.pos.col(i);\n\t\tio_curve->restLengths(i) = diff.norm();\n\t}\n\n\tfor(int i=0; i<nAngles; i++)\n\t\tio_curve->restAngles(i) = angles[i];\n\n\tio_initial_vars = io_vars;\n\n\tinitSolverVars(in_params, io_curve, io_initial_vars, io_solver_vars, true);\n}\n\nbool SecantLMMethodSingleUpdate(const SParameters* in_params, const SCurve* in_curve, const SVar& in_initial_vars, SSolverVars& io_solver_vars, SVar& solution)\n{\n\tif(io_solver_vars.found || io_solver_vars.k > in_params->kmax)\n\t\treturn true;\n\n\tio_solver_vars.k++;\n\tio_solver_vars.A_muI = io_solver_vars.B.transpose() * io_solver_vars.B + io_solver_vars.mu * io_solver_vars.I;\n\tio_solver_vars.h = io_solver_vars.A_muI.ldlt().solve(-io_solver_vars.g);\n\n\tif(io_solver_vars.h.norm() <= in_params->epsilon_2 * (io_solver_vars.x.pos.norm() + in_params->epsilon_2))\n\t\tio_solver_vars.found = true;\n\telse\n\t{\n\t\tfor(int q=0; q<io_solver_vars.nV; q++)\n\t\t{\n\t\t\tio_solver_vars.xnew.pos(0, q) = io_solver_vars.x.pos(0, q) + io_solver_vars.h(q);\n\t\t\tio_solver_vars.xnew.pos(1, q) = io_solver_vars.x.pos(1, q) + io_solver_vars.h(q + io_solver_vars.nV);\n\t\t}\n\t}\n\t\t\t\n\tdouble Fnew = 0.5 * ComputeEnergy(in_params, in_curve, io_solver_vars.xnew);\n\tdouble F = 0.5 * ComputeEnergy(in_params, in_curve, io_solver_vars.x);\n\n\tdouble gain_denom = - io_solver_vars.h.dot(io_solver_vars.B.transpose() * io_solver_vars.f) \n\t\t- 0.5 * io_solver_vars.h.dot(io_solver_vars.B.transpose() * io_solver_vars.B * io_solver_vars.h);\n\tdouble gain = (F - Fnew) / gain_denom;\n\n\tif(gain > 0)\n\t{\n\t\tio_solver_vars.x = io_solver_vars.xnew;\n\t\tCompute_f(in_params, in_curve, io_solver_vars.x, io_solver_vars.f);\n\t\tComputeNumericalDerivative(in_params, in_curve, io_solver_vars.x, io_solver_vars.epsilon, io_solver_vars.B);\n\t\tio_solver_vars.g = io_solver_vars.B.transpose() * io_solver_vars.f;\n\t\tio_solver_vars.found = (io_solver_vars.g.lpNorm<Eigen::Infinity>() <= in_params->epsilon_1);\n\t\tprintf(\"k: %d, gain: %f, |g|_inf: %f\\n\", io_solver_vars.k, gain, io_solver_vars.g.lpNorm<Eigen::Infinity>());\n\t\tio_solver_vars.mu = io_solver_vars.mu * std::max(1.0/3.0, 1.0 - (2.0 * gain - 1.0) * (2.0 * gain - 1.0) * (2.0 * gain - 1.0));\n\t\tio_solver_vars.nu = 2.0;\n\t}\n\telse\n\t{\n\t\tio_solver_vars.mu = io_solver_vars.mu * io_solver_vars.nu;\n\t\tio_solver_vars.nu = io_solver_vars.nu * 2.0;\n\t}\n\n\tif(io_solver_vars.found)\n\t\tprintf(\"found in %d steps\\n\", io_solver_vars.k);\n\n\tsolution = io_solver_vars.x;\n\n\treturn io_solver_vars.found || io_solver_vars.k > in_params->kmax;\n}\n\nvoid ShowFeaturePoints(const SCurve* in_curve, const SVar& solution)\n{\n\tprintf(\"Feature points:\\n\");\n\tfor(int i=0; i<in_curve->nVertices; i++)\n\t{\n\t\tif(in_curve->vertexIDs(i) >= 0)\n\t\t{\n\t\t\tprintf(\"%d: %f, %f\\n\", in_curve->vertexIDs(i), solution.pos.col(i).x(), solution.pos.col(i).y());\n\t\t}\n\t}\n}\n\nvoid SecantLMMethod(const SParameters* in_params, SCurve* in_curve, SVar& in_initial_vars, SSolverVars& io_solver_vars, SVar& solution)\n{\n\tinitSolverVars(in_params, in_curve, in_initial_vars, io_solver_vars);\n\n\twhile(1)\n\t{\n\t\tif(SecantLMMethodSingleUpdate(in_params, in_curve, in_initial_vars, io_solver_vars, solution))\n\t\t\tbreak;\n\t\tUpdateCurveSubdivision(in_params, in_initial_vars, solution, in_curve, io_solver_vars);\n\t}\n\n\tprintf(\"found in %d steps\\n\", io_solver_vars.k);\n\tsolution = io_solver_vars.x;\n\tShowFeaturePoints(in_curve, solution);\n}\n", "meta": {"hexsha": "42cc251e3181d5bfc47af5479e9583ab2ccfd85b", "size": 24871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/folding_planner/src/Registration.cpp", "max_stars_repo_name": "roop-pal/robotic-folding", "max_stars_repo_head_hexsha": "a0e062ac6d23cd07fe10e3f45abc4ba50e533141", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T16:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T03:15:55.000Z", "max_issues_repo_path": "catkin_ws/src/folding_planner/src/Registration.cpp", "max_issues_repo_name": "roop-pal/robotic-folding", "max_issues_repo_head_hexsha": "a0e062ac6d23cd07fe10e3f45abc4ba50e533141", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-17T04:39:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-17T04:39:38.000Z", "max_forks_repo_path": "catkin_ws/src/folding_planner/src/Registration.cpp", "max_forks_repo_name": "roop-pal/robotic-folding", "max_forks_repo_head_hexsha": "a0e062ac6d23cd07fe10e3f45abc4ba50e533141", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-03-18T14:13:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-15T15:03:51.000Z", "avg_line_length": 38.6195652174, "max_line_length": 192, "alphanum_fraction": 0.6980821037, "num_tokens": 8104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6217061007770888}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// chi_square_summand.hpp                                                    //\n//                                                                           //\n//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_COMMON_CHISQ_SUMMAND_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_COMMON_CHISQ_SUMMAND_HPP_ER_2010\n#include <boost/numeric/conversion/converter.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace contingency_table{\nnamespace pearson_chi_square_statistic{\n\n    // The sum over all cells of this quantity is a fraction, f, of Pearson's \n    // Chi-square statistic. If (expected, observed) are expressed in counts,\n    // f = 1. If they are expressed in frequencies, f = 1/n, where n is the\n    // total number of counts.\n    template<typename T1,typename T2,typename T3>\n    T1  chi_square_summand(const T2& expected, const T3& observed)\n    {\n        typedef boost::numeric::converter<T1,T2> conv2_;\n        typedef boost::numeric::converter<T1,T3> conv3_;\n        T1 summand = conv2_::convert( expected ) - conv3_::convert( observed );\n        summand *= summand;\n        return summand / conv2_::convert( expected );\n    }\n\n\n}// pearson_chi_square_statistic\n}// contingency_table\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "30f4d6df914e56af1dbbfdbf5e8398fb52db8bc8", "size": 1734, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/common/chi_square_summand.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_parametric/boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/common/chi_square_summand.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_parametric/boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/common/chi_square_summand.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.35, "max_line_length": 111, "alphanum_fraction": 0.6020761246, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.6216989845922994}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main()\n{\n    using namespace mtl;\n    \n    dense2D<int> A(2, 2), B(2, 2), C(4, 4);\n    \n    for (size_t r= 0; r < 2; ++r)\n        for (size_t c= 0; c < 2; ++c) {\n            A[r][c]= (r+1) * 10 + c+1;\n            B[r][c]= (r+1) * 1000 + (c+1) * 100;\n        }\n        \n    C= kron(A, B);\n    std::cout << \"kron(A, B) is\\n\" << C;\n    \n    MTL_THROW_IF(C[0][0] != 12100, mtl::runtime_error(\"Wrong value in C[0][0]\"));\n    MTL_THROW_IF(C[3][3] != 48400, mtl::runtime_error(\"Wrong value in C[3][3]\"));\n\n    return 0;\n}\n", "meta": {"hexsha": "33ee54e35147fa9c4979eef3de8190d1af602073", "size": 1022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/kron_test.cpp", "max_stars_repo_name": "shikharvashistha/mtl4", "max_stars_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/kron_test.cpp", "max_issues_repo_name": "shikharvashistha/mtl4", "max_issues_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/kron_test.cpp", "max_forks_repo_name": "shikharvashistha/mtl4", "max_forks_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 27.6216216216, "max_line_length": 94, "alphanum_fraction": 0.5694716243, "num_tokens": 345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6216976796274851}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd X = MatrixXd::Random(4,4);\nMatrixXd A = X * X.transpose();\ncout << \"Here is a random positive-definite matrix, A:\" << endl << A << endl << endl;\n\nSelfAdjointEigenSolver<MatrixXd> es(A);\nMatrixXd sqrtA = es.operatorSqrt();\ncout << \"The square root of A is: \" << endl << sqrtA << endl;\ncout << \"If we square this, we get: \" << endl << sqrtA*sqrtA << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "db04269ceaea7eeeb8ce972a1adf480ae05badac", "size": 847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_SelfAdjointEigenSolver_operatorSqrt.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_SelfAdjointEigenSolver_operatorSqrt.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_SelfAdjointEigenSolver_operatorSqrt.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 29.2068965517, "max_line_length": 224, "alphanum_fraction": 0.6694214876, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.7520125793176223, "lm_q1q2_score": 0.6216976557686263}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//! \\file\r\n//!\\brief Tests for cbrt(fixed_point) round::fastest. Along the way, also test numerous fixed_point arithmetic operations.\r\n\r\n#define BOOST_TEST_MODULE test_negatable_math_cbrt_fastest\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <cmath>\r\n#include <iomanip>\r\n#include <iostream>\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/math/special_functions/cbrt.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nnamespace local\r\n{\r\n  template<typename FixedPointType>\r\n  const FixedPointType& tolerance_maker(const int fuzzy_bits)\r\n  {\r\n    static const FixedPointType the_tolerance = ldexp(FixedPointType(1), FixedPointType::resolution + fuzzy_bits);\r\n\r\n    return the_tolerance;\r\n  }\r\n\r\n  template<typename FixedPointType,\r\n           typename FloatPointType = typename FixedPointType::float_type>\r\n  void test_cbrt(const int fuzzy_bits)\r\n  {\r\n    // Use at least 6 resolution bits.\r\n    // Use at least 8 range bits.\r\n\r\n    BOOST_STATIC_ASSERT(-FixedPointType::resolution >= 6);\r\n    BOOST_STATIC_ASSERT( FixedPointType::range      >= 8);\r\n\r\n    const FixedPointType a1 (  2L    );                                      const FloatPointType b1(  2L    );\r\n    const FixedPointType a2 (  3L    );                                      const FloatPointType b2(  3L    );\r\n    const FixedPointType a3 (  8.375L);                                      const FloatPointType b3(  8.375L);\r\n    const FixedPointType a4 ( 64.125L);                                      const FloatPointType b4( 64.125L);\r\n    const FixedPointType a5 (100.875L);                                      const FloatPointType b5(100.875L);\r\n    const FixedPointType a6 (FixedPointType(  1) /  3);                      const FloatPointType b6(FloatPointType(  1) /  3);\r\n    const FixedPointType a7 (FixedPointType( 12) / 10);                      const FloatPointType b7(FloatPointType( 12) / 10);\r\n    const FixedPointType a8 (FixedPointType(111) / 10);                      const FloatPointType b8(FloatPointType(111) / 10);\r\n    const FixedPointType a9 (boost::math::constants::phi<FixedPointType>()); const FloatPointType b9(boost::math::constants::phi<FloatPointType>());\r\n\r\n    // Use boost::math::cbrt for fixed-point negatable because cbrt(negatable) is not yet implemented.\r\n    // Do not use a using directive for boost::math::cbrt() until cbrt is implemented for fixed-point negatable.\r\n    BOOST_CHECK_CLOSE_FRACTION(boost::math::cbrt(a1), FixedPointType(boost::math::cbrt(b1)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(boost::math::cbrt(a2), FixedPointType(boost::math::cbrt(b2)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(boost::math::cbrt(a3), FixedPointType(boost::math::cbrt(b3)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(boost::math::cbrt(a4), FixedPointType(boost::math::cbrt(b4)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(boost::math::cbrt(a5), FixedPointType(boost::math::cbrt(b5)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(boost::math::cbrt(a6), FixedPointType(boost::math::cbrt(b6)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(boost::math::cbrt(a7), FixedPointType(boost::math::cbrt(b7)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(boost::math::cbrt(a8), FixedPointType(boost::math::cbrt(b8)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n    BOOST_CHECK_CLOSE_FRACTION(boost::math::cbrt(a9), FixedPointType(boost::math::cbrt(b9)), tolerance_maker<FixedPointType>(fuzzy_bits));\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_math_cbrt_fastest)\r\n{\r\n  // Test cbrt() for negatable round::fastest in various key digit regions.\r\n\r\n  { typedef boost::fixed_point::negatable< 8,  -7, boost::fixed_point::round::fastest> fixed_point_type; local::test_cbrt<fixed_point_type>(4); }\r\n  { typedef boost::fixed_point::negatable<15, -16, boost::fixed_point::round::fastest> fixed_point_type; local::test_cbrt<fixed_point_type>(((-fixed_point_type::resolution + 9) * 2) / 10); }\r\n  { typedef boost::fixed_point::negatable<63, -64, boost::fixed_point::round::fastest> fixed_point_type; local::test_cbrt<fixed_point_type>(((-fixed_point_type::resolution + 9) * 1) / 10); }\r\n}\r\n", "meta": {"hexsha": "b64b0f94b1454e9bd2fcbb4421744963c33f8d57", "size": 4689, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_math_cbrt_fastest.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_math_cbrt_fastest.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_math_cbrt_fastest.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": 62.52, "max_line_length": 191, "alphanum_fraction": 0.6875666453, "num_tokens": 1248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117769928211, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6216976465791875}}
{"text": "#include \"GL_Logger.h\"\n#include \"KeySpline.h\"\n#include <Eigen/Geometry>\n#include \"Transform.h\"\n#include <glm/gtc/type_ptr.hpp>\n#include <glm/gtc/quaternion.hpp>\n#include <GLFW/glfw3.h>\n\n/**\n * Calculate the lenght of a segment using a Gaussian Quadrature\n * @param  u1 the first time point\n * @param  u2 the second point of the segemnt\n * @param  Gk 4 control poitns describing the spline\n * @return    the length of the segment.\n */\nfloat gaussQuad3(float u1, float u2, const Eigen::MatrixXf & Gk, const Eigen::Matrix4f & B){\n    float w[] = {5/9.0,8/9.0,5/9.0};\n    float x[] = {-sqrtf(3/5.0),0,sqrtf(3/5.0)};\n    float pointSummation = 0;\n    for(int i = 0; i < 3; i++){\n        float u = (u2-u1)/2.0 * x[i] + (u1 + u2)/2.0;\n        Eigen::Vector4f du;\n        du << 0,1,2*u,3*u*u;\n        pointSummation+= w[i]*(Gk*B*du).norm();\n    }\n    return pointSummation * (u2-u1)/2.0;\n}\n\n//Calculate the fernet frame of a point.\nglm::vec3 getNormalVector(const Eigen::Matrix4f & B, const Eigen::Vector3f points[],\n    float u){\n    Eigen::MatrixXf G(3,4);\n    G << points[0](0), points[1](0), points[2](0), points[3](0),\n         points[0](1), points[1](1), points[2](1), points[3](1),\n         points[0](2), points[1](2), points[2](2), points[3](2);\n\n    Eigen::Vector4f dUVec, d2UVec;\n    dUVec << 0.0f, 1.0f, 2*u, 3*u*u;\n    dUVec= dUVec.transpose();\n\n\n    Eigen::Vector3f Tvec = (G*B*dUVec).normalized(); //T Vector\n    return glm::vec3(Tvec(0),Tvec(1),Tvec(2));\n}\n\nKeySpline::KeySpline():\nnumSplines(0),\nusTableDirty(true)\n{\n    setSplineType(CATMULL);\n    vao.addAttribute(0,vertexBuffer);\n};\nKeySpline::~KeySpline(){};\n\nvoid KeySpline::setSplineType(SplineType t){\n    switch (t){\n        case CATMULL:\n            this->B << 0.0f, -1.0f,  2.0f, -1.0f,\n                       2.0f,  0.0f, -5.0f,  3.0f,\n                       0.0f,  1.0f,  4.0f, -3.0f,\n                       0.0f,  0.0f, -1.0f,  1.0f;\n            this->B*=0.5;\n            break;\n        case BSPLINE:\n            this->B  << 1.0f, -3.0f,  3.0f, -1.0f,\n                        4.0f,  0.0f, -6.0f,  3.0f,\n                        1.0f,  3.0f,  3.0f, -3.0f,\n                        0.0f,  0.0f,  0.0f,  1.0f;\n            this->B /= 6.0f;\n            break;\n    }\n    if(this->type != t){\n        recalculateTable(6);\n        this->type = t;\n    }\n}\n\nvoid KeySpline::addNode(const SplineNode & node){\n    nodePos.push_back(node.getPosition());\n    nodeRot.push_back(node.getRotation());\n    if(nodePos.size() >= 3){\n        std::cout << \"Increasing splines\" << std::endl;\n        numSplines++;\n    }\n    if(numSplines > 0){\n           recalculateTable(6);\n    }\n    updateVBO = true;\n}\n\n//Replace with Geometry shader later\nvoid KeySpline::draw(){\n    if(updateVBO && numSplines > 0){\n\n        Eigen::MatrixXf G(3,nodePos.size() + 1);\n        Eigen::MatrixXf Gk(3,4);\n        for(int i = 0; i < nodePos.size(); i++){\n            G.block<3,1>(0,i) = nodePos[i];\n        }\n        G.block<3,1>(0,nodePos.size()) = nodePos.back();\n        std::vector<glm::vec3>  positions;\n        positions.clear();\n        for(int k = 0; k < numSplines; k++){\n            Gk = G.block<3,4>(0,k);\n            int n = 32;\n            for(int i = 0; i < n; i++){\n                float u = i/(n-1.0f);\n                Eigen::Vector4f uVec(1.0,u,u*u,u*u*u);\n                Eigen::Vector3f P=Gk*B*uVec;\n                positions.push_back(glm::vec3(P(0),P(1),P(2)));\n            }\n        }\n        vertexBuffer.setData(positions);\n        updateVBO = false;\n    }\n    if (numSplines > 0)\n    {\n        vao.bind();\n        GL_Logger::LogError(\"Could not bind spline vao\");\n\n        glDrawArrays(GL_LINE_STRIP,0,vertexBuffer.getNumVerts());\n        GL_Logger::LogError(\"Could not draw spline\");\n        vao.unbind();\n\n    }\n    //Drawing code here\n}\nvoid KeySpline::close(){\n    nodePos.push_back(nodePos[0]);\n    nodeRot.push_back(nodeRot[0]);\n    //n-2,n-1,n,0\n    nodePos.push_back(nodePos[1]);\n    nodeRot.push_back(nodeRot[1]);\n    //n-1,n,0,1\n    nodePos.push_back(nodePos[2]);\n    nodeRot.push_back(nodeRot[2]);\n    //n,0,1,2\n    numSplines+=3;\n}\n\nTransform KeySpline::transformAt(float s){\n    assert(numSplines > 0);\n\n    float kfloat;\n    float uu = s;\n    float u = std::modf(uu, &kfloat);\n    int k = (int)std::floor(kfloat) % numSplines;\n    Eigen::MatrixXf GPos(3,4);\n    Eigen::MatrixXf GRot(4,4);\n    std::vector<Eigen::Vector3f> cappedPos(nodePos);\n    cappedPos.push_back(nodePos.back());\n    for(int i = 0; i < 4; i++){\n        GPos.block<3,1>(0,i) = cappedPos[k+i];\n    }\n    Eigen::Vector4f uVec(1.0,u,u*u,u*u*u);\n    Eigen::Vector3f P= GPos * B * uVec;\n    Transform t;\n    t.setPosition(glm::vec3(P(0),P(1),P(2)));\n    t.lookAlong(getNormalVector(B,&(cappedPos[k]),u));\n    return t;\n}\n\n\nfloat KeySpline::sToU(float s)\n{\n    float sMod = std::fmod(s,usTable.back().second);\n    if(usTableDirty)\n    {\n        recalculateTable(6);\n        usTableDirty = false;\n    }\n    int i = 0;\n    float last = 0;\n    float cur = 0;\n\n    while( i < (int)usTable.size() && sMod >= cur){\n        i++;\n        last = cur;\n        cur = usTable[i].second;\n        \n    }\n    if(i == 0){\n        return 0;\n    }\n    float interpolationConst = (sMod-last)/(cur-last);\n    return (1-interpolationConst)*usTable[i-1].first + interpolationConst*usTable[i].first;\n\n}\n\nvoid KeySpline::recalculateTable(int discretization){\n    if(numSplines == 0)\n        return;\n    usTable.clear();\n    int ncps = (int)nodePos.size();\n    Eigen::MatrixXf G(3,ncps + 1);\n    Eigen::MatrixXf Gk(3,4);\n\n    usTable.push_back(std::make_pair(0.0f,0.0f));\n    float s = 0;\n    for(int i = 0; i < ncps; ++i) {\n            G.block<3,1>(0,i) = nodePos[i];\n    }\n    //assign last node duplicate to cap the spline\n    G.block<3,1>(0,ncps) = nodePos.back();\n    ncps++;\n    for(int k = 0; k < ncps - 3; ++k) {\n        int n = discretization; // table resolution discretization\n            // Gk is the 3x4 block starting at column k\n        Gk = G.block<3,4>(0,k);\n        for(int i = 0; i < n-1; ++i) {\n            float u = i / (n - 1.0f);\n            float u2 = u+1.0/(n - 1);\n                // Compute spline point at u\n            float ds = gaussQuad3(u, u2 , Gk, B);\n            usTable.push_back(std::make_pair(u2+k,(s+=ds)));\n        }\n    }\n\n}\n\nint KeySpline::getNumNodes()\n{\n    return nodePos.size();\n}\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "16499804a6f735990ef51389a9351eba687a8d47", "size": 6340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/BezierCurves/KeySpline.cpp", "max_stars_repo_name": "kyle-piddington/SharkProject", "max_stars_repo_head_hexsha": "d34d27cd7a7fbd385dd9edccd69b2d2257be70f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util/BezierCurves/KeySpline.cpp", "max_issues_repo_name": "kyle-piddington/SharkProject", "max_issues_repo_head_hexsha": "d34d27cd7a7fbd385dd9edccd69b2d2257be70f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util/BezierCurves/KeySpline.cpp", "max_forks_repo_name": "kyle-piddington/SharkProject", "max_forks_repo_head_hexsha": "d34d27cd7a7fbd385dd9edccd69b2d2257be70f2", "max_forks_repo_licenses": ["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.2103004292, "max_line_length": 92, "alphanum_fraction": 0.5380126183, "num_tokens": 2162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305638, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.6216843506656553}}
{"text": "/*\r\n This program is free software; you can redistribute it and/or modify it under\r\n the terms of the European Union Public Licence - EUPL v.1.1 as published by\r\n the European Commission.\r\n\r\n This program is distributed in the hope that it will be useful, but WITHOUT\r\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r\n FOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1\r\n for more details.\r\n\r\n You should have received a copy of the European Union Public Licence - EUPL v.1.1\r\n along with this program.\r\n\r\n Further information about the European Union Public Licence - EUPL v.1.1 can\r\n also be found on the world wide web at http://ec.europa.eu/idabc/eupl\r\n\r\n*/\r\n\r\n/*\r\n ------ Copyright (C) 2011 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\r\n*/\r\n\r\n //------------------ Author: Catarina Silva  -------------------------------------------------\r\n// ------------------ E-mail: (catsilva20@gmail.com) ------------------------------------------\r\n\r\n#include \"attitudeintegration.h\"\r\n#include <Eigen/Core>\r\n#include <Eigen/Geometry>\r\n#include <Astro-Core/EODE/eode.h>\r\n#include <Astro-Core/statevector.h>\r\n\r\nusing namespace Eigen;\r\n\r\ntypedef Eigen::Matrix< double, 3, 3 > \tMyMatrix3d;\r\ntypedef Eigen::Matrix< double, 3, 1 > \tMyVector3d;\r\ntypedef Eigen::Matrix< double, 4, 4 > \tMyMatrix4d;\r\ntypedef Eigen::Matrix< double, 4, 1 > \tMyVector4d;\r\n\r\n//Integrates the Euler equation and the quaternion rates equation.\r\n//Inputs: initial body rates, inertia matrix and moments (now = 0)\r\n//The propagation will use the Runge Kutta 4 integrator\r\n//Outputs: final euler angles or quaternions\r\n\r\n// WRITE THE REFERENCE OF THE FORMULAS\r\n\r\n/**\r\n  * Derivative of the Euler equation\r\n  *\r\n  * @param bodyRates        initial body rates\r\n  * @param inertiaMatrix    inertia matrix\r\n  *\r\n  * @return derivBodyRates  body rates derivatives\r\n  */\r\nvoid derivEulerEquation (VectorXd bodyRates, double time, VectorXd inertiaANDmoments, VectorXd& derivBodyRates)\r\n{\r\n    double p = bodyRates[0];\r\n    double q = bodyRates[1];\r\n    double r = bodyRates[2];\r\n\r\n    static double bodyCoeffs[9]={\r\n        0,  -r,   q,\r\n        r,   0,  -p,\r\n       -q,   p,   0\r\n    };\r\n    static const Matrix3d bodyMatrix(bodyCoeffs);\r\n\r\n    //the input of derivEulerEquation needs to be a VectorXd (in this case, 12elements vector).\r\n    //This vector will include the components of the INERTIA MATRIX (the first 9 elements), and\r\n    //the components of the external MOMENTS applied to the vehicle (last 3 elements)\r\n    double I11 = inertiaANDmoments[0];\r\n    double I12 = inertiaANDmoments[1];\r\n    double I13 = inertiaANDmoments[2];\r\n    double I21 = inertiaANDmoments[3];\r\n    double I22 = inertiaANDmoments[4];\r\n    double I23 = inertiaANDmoments[5];\r\n    double I31 = inertiaANDmoments[6];\r\n    double I32 = inertiaANDmoments[7];\r\n    double I33 = inertiaANDmoments[8];\r\n\r\n    //External Moments\r\n    double M1 = inertiaANDmoments[9];\r\n    double M2 = inertiaANDmoments[10];\r\n    double M3 = inertiaANDmoments[11];\r\n\r\n    Vector3d Moments(M1,M2,M3);\r\n\r\n    static double inertiaCoeffs[9] = {\r\n        I11, I12, I13,\r\n        I21, I22, I23,\r\n        I31, I32, I33\r\n\r\n    };\r\n    static const Matrix3d inertiaMatrix(inertiaCoeffs);\r\n\r\n    //Euler's equation\r\n    Matrix3d multipInertia= inertiaMatrix * inertiaMatrix.transpose();\r\n    Matrix3d inertiaTimesBodyMatrix = bodyMatrix * multipInertia;\r\n\r\n    derivBodyRates = Moments - inertiaTimesBodyMatrix * bodyRates;\r\n}\r\n\r\n/**\r\n  * Propagate the Euler equation\r\n  *\r\n  * @param initbodyRates    initial body rates\r\n  * @param time\r\n  * @param timeStep\r\n  * @param inertiaMatrix\r\n  *\r\n  * @return body rates      final body rates\r\n  */\r\nVector3d propagateEulerEquation(const Vector3d& initbodyRates,\r\n                                double time,\r\n                                double timeStep,\r\n                                const Matrix3d& inertiaMatrix)\r\n{\r\n    //Convert Vector3d to VectorSd so it can be fed to RK4\r\n    VectorXd theBodyRates;\r\n    theBodyRates << initbodyRates[0], initbodyRates[1],initbodyRates[2];\r\n\r\n    //Convert the matrix3d of the inertia matrix to a vectorXd, so it can be an input in the intregator\r\n    VectorXd inertiaMatrix_Vector;\r\n\r\n    inertiaMatrix_Vector[0] = inertiaMatrix(0,0);\r\n    inertiaMatrix_Vector[1] = inertiaMatrix(0,1);\r\n    inertiaMatrix_Vector[2] = inertiaMatrix(0,2);\r\n    inertiaMatrix_Vector[3] = inertiaMatrix(1,0);\r\n    inertiaMatrix_Vector[4] = inertiaMatrix(1,1);\r\n    inertiaMatrix_Vector[5] = inertiaMatrix(1,2);\r\n    inertiaMatrix_Vector[6] = inertiaMatrix(2,0);\r\n    inertiaMatrix_Vector[7] = inertiaMatrix(2,1);\r\n    inertiaMatrix_Vector[8] = inertiaMatrix(2,2);\r\n\r\n    //For now, a Runge Kutta 4 will be used. Later, this can be changed to a better integrator (Runge Kutta 7,8 ex.)\r\n    rk4(theBodyRates, 3, time, timeStep, derivEulerEquation, inertiaMatrix_Vector);\r\n\r\n    //Returns the body rates, after integration\r\n    Vector3d integratedBodyRates;\r\n    integratedBodyRates[0] = theBodyRates[0];\r\n    integratedBodyRates[1] = theBodyRates[1];\r\n    integratedBodyRates[2] = theBodyRates[2];\r\n    return integratedBodyRates;\r\n}\r\n\r\n/**\r\n  * This function calculates the quaternions rates\r\n  *\r\n  * @param initQuaternions  initial quaternions\r\n  * @param parameters       body rates\r\n  * @param time\r\n  *\r\n  * @return derivative      quaternions derivatives\r\n  */\r\n\r\n//This function calculates the derivatives of the quaternions\r\nvoid derivQUATERNIONS (VectorXd initQuaternions, double time, VectorXd parameters, VectorXd& derivative)\r\n{\r\n    double p = parameters[0];\r\n    double q = parameters[1];\r\n    double r = parameters[2];\r\n\r\n    static double bodyCoeffs[16]= {\r\n        0, -p, -q, -r,\r\n        p, 0, r, -q,\r\n        q, -r, 0, p,\r\n        r, q, -p, 0\r\n    };\r\n    static const MyMatrix4d bodyRatesMatrix(bodyCoeffs);\r\n    derivative = bodyRatesMatrix * initQuaternions;\r\n}\r\n\r\n/**\r\n  * This function integrates the quaternions rates\r\n  *\r\n  * @param quaternions  initial quaternions\r\n  * @param time         time\r\n  * @param timeStep     time step of the integration\r\n  * @param bodyrates\r\n  *\r\n  * @return quats       final quaternions\r\n  */\r\n\r\nQuaterniond propagateQUATERNIONS(Quaterniond& quaternions,\r\n                                 double time,\r\n                                 double timeStep,\r\n                                 Vector3d bodyrates)\r\n{\r\n\r\n    VectorXd parameters(3);\r\n    parameters << bodyrates[0], bodyrates[1], bodyrates[2];\r\n\r\n    VectorXd quats(4);\r\n    quats << quaternions.coeffs().coeffRef(0), quaternions.coeffs().coeffRef(1),\r\n    quaternions.coeffs().coeffRef(2), quaternions.coeffs().coeffRef(3);\r\n\r\n    rk4 (quats, 4, time, timeStep, derivQUATERNIONS, parameters);\r\n\r\n    //Transform VectorXd to quaternions\r\n    Quaterniond propagatedQuaternion(quats(0),quats(1), quats(2),quats(3));\r\n\r\n    return propagatedQuaternion;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "78aaadae8cbf175eda6e72ccf4278205c70882be", "size": 6927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Astro-Core/attitudeintegration.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Astro-Core/attitudeintegration.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Astro-Core/attitudeintegration.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 33.7902439024, "max_line_length": 117, "alphanum_fraction": 0.6517973149, "num_tokens": 1795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.6216534077263669}}
{"text": "#include <ros/ros.h>\n#include \"ros_utils.hpp\"\n#include \"kinematics.hpp\"\n#include \"estimators.hpp\"\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n#include <Eigen/Dense>\n#include <unistd.h>\n#include <math.h>\n\n#include <gtsam/config.h>\n#include <gtsam/base/VectorSpace.h>\n#include <gtsam/base/Vector.h>\n#include <gtsam/dllexport.h>\n#include <boost/serialization/nvp.hpp>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/inference/Key.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/nonlinear/NonlinearFactor.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/nonlinear/Marginals.h>\n#include <gtsam/nonlinear/Values.h>\n#include <gtsam/geometry/Point2.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/sam/BearingRangeFactor.h>\n#include <gtsam/base/OptionalJacobian.h>\n#include <gtsam/inference/LabeledSymbol.h>\n\n#include <gtsam_node/ArticulatedAngles.h>\n#include <gtsam_node/CanData.h>\n#include \"std_msgs/String.h\"\n#include \"geometry_msgs/PoseWithCovarianceStamped.h\"\n#include \"geometry_msgs/Twist.h\"\n#include \"ackermann_msgs/AckermannDrive.h\"\n\n#include <visualization_msgs/Marker.h>\n#include <cmath>\n\nusing namespace std;\nusing namespace gtsam;\n\n\n\nclass CircleFactor: public NoiseModelFactor1<Vector5> {\n  \n  Vector3 circle_;\n\n public:\n  \n  typedef boost::shared_ptr<CircleFactor> shared_ptr;\n\n  CircleFactor(Key j, Vector3 circle, const SharedNoiseModel& model):\n    NoiseModelFactor1<Vector5>(model, j), circle_(circle) {}\n\n  virtual ~CircleFactor() {}\n\n  Vector evaluateError(const Vector5& po,\n                       boost::optional<Matrix&> H = boost::none) const override {\n\n    /*                 \n    double err = 1/(pow(po[0]-circle_[0],2)+pow(po[1]-circle_[1],2)-pow(circle_[2],2));\n    \n    double ctrval = 0.05;\n    double jX = (ctrval*(2*po[0] - 2*circle_[0]))/pow(pow(po[0]-circle_[0],2)+pow(po[1]-circle_[1],2)-pow(circle_[2],2),2);\n    double jY = (ctrval*(2*po[1] - 2*circle_[1]))/pow(pow(po[0]-circle_[0],2)+pow(po[1]-circle_[1],2)-pow(circle_[2],2),2);\n   \n    if (H) (*H) = (Matrix(1, 5) << jX, jY, 0.0, 0.0, 0.0).finished();\n    return (Vector(1) << err*ctrval).finished(); \n    /**/\n    //\n    double ctrval = 0.05;\n    double err = (1/(pow(2,(ctrval*((pow(po[0]-circle_[0],2)+pow(po[1]-circle_[1],2)-pow(circle_[2],2))/pow(circle_[2],2))))))-1;\n    \n    \n    double jX = (-0.6931471*ctrval*(po[0]-circle_[0])*pow(2,(1-(ctrval*((pow(po[0]-circle_[0],2)+pow(po[1]-circle_[1],2)-pow(circle_[2],2))/pow(circle_[2],2)) ))))/pow(circle_[2],2);\n    double jY = (-0.6931471*ctrval*(po[1]-circle_[1])*pow(2,(1-(ctrval*((pow(po[0]-circle_[0],2)+pow(po[1]-circle_[1],2)-pow(circle_[2],2))/pow(circle_[2],2)) ))))/pow(circle_[2],2);\n   \n    if (H) (*H) = (Matrix(1, 5) << jX, jY, 0.0, 0.0, 0.0).finished();\n    //ROS_INFO_STREAM(\"errY: \" << err << \"\");\n    //ROS_INFO_STREAM(\"errYJ: \" << jY << \"\");\n    return (Vector(1) << err).finished();\n    /**/ \n  }\n\n  \n\n  gtsam::NonlinearFactor::shared_ptr clone() const override {\n    return boost::static_pointer_cast<gtsam::NonlinearFactor>(\n        gtsam::NonlinearFactor::shared_ptr(new CircleFactor(*this))); }\n\n};  // CircleFactor\n\n\n\n\n\nclass PolyPointFactor: public NoiseModelFactor2<Vector8,Vector5> {\n  \n  private:\n    using This = PolyPointFactor;\n    using Base = gtsam::NoiseModelFactor2<Vector8, Vector5>;\n\n    Vector8 mpoly_;\n    Vector5 mpoint_;\n    gtsam::Key j_;\n  public:\n        \n    typedef boost::shared_ptr<PolyPointFactor> shared_ptr;\n\n    PolyPointFactor(Key i, Key j, Vector8 mpoly, Vector5 mpoint, const SharedNoiseModel& model)\n        : Base(model, i, j), mpoly_(mpoly), mpoint_(mpoint),j_(j) {}\n\n    virtual ~PolyPointFactor() \n    {}\n\n    double getPoly(const double& x, const Vector8& p8) const \n    {\n        double y;\n        y = (p8[0]*pow(x,7))+(p8[1]*pow(x,6))+(p8[2]*pow(x,5))+(p8[3]*pow(x,4))+(p8[4]*pow(x,3))+(p8[5]*pow(x,2))+(p8[6]*x)+p8[7];\n\n        \n        return y; // order p0 x^7 -> p7 x^1 \n    }\n\n    double diffPoly(const double& x, const Vector8& p8) const \n    {\n        double y;\n        y = (7*p8[0]*pow(x,6))+(6*p8[1]*pow(x,5))+(5*p8[2]*pow(x,4))+(4*p8[3]*pow(x,3))+(3*p8[4]*pow(x,2))+(2*p8[5]*x)+p8[6];\n        \n        return y; // order p0 x^7 -> p7 x^1 \n    }  \n\n    double diff2Poly(const double& x, const Vector8& p8) const \n    {\n        double y;\n        y = (42*p8[0]*pow(x,5))+(30*p8[1]*pow(x,4))+(20*p8[2]*pow(x,3))+(12*p8[3]*pow(x,2))+(6*p8[4]*x)+(2*p8[5]);\n        \n        return y; // order p0 x^7 -> p7 x^1 \n    }  \n\n\n\n     Vector evaluateError(const Vector8& p8, const Vector5& p5,\n        boost::optional<Matrix&> H1 = boost::none, boost::optional<Matrix&> H2 = boost::none) const override \n    {\n        //PrintKey(j_);\n        gtsam::Vector err(13); \n        err = Vector::Zero(13);\n        err[9] =  p5[1] - getPoly(p5[0],p8);\n        //ROS_INFO_STREAM(\"errY: \" << err[9] << \"\");\n\n        double errYx = diffPoly(p5[0],p8);\n        double errY2x = diff2Poly(p5[0],p8);\n        double curve = abs(errY2x)/pow((pow(errYx,2)+1),1.5);\n        double ctrVal = 1;\n        double curveMax = 0.1;\n        //err[11] =  1/(pow(2,ctrVal*(curveMax - curve)));\n        err[9] = err[9] + 1/(pow(2,ctrVal*(curveMax - curve)));\n        ROS_INFO_STREAM(\"Curve: \" << curve << \"\");\n        //ROS_INFO_STREAM(\"errCurve: \" << err[11] << \"\");\n\n        //curve = (abs(42*p0*x^5+30*p1*x^4+20*p2*x^3+12*p3*x^2+6*p4*x+2*p5)/(1+(7*p0*x^6+6*p1*x^5+5p2*x^4+4*p3*x^3+3*p4*x^2+2*p5*x+p6)^2)^(3/2))\n\n        //errCurve = 1/2^(a*(m-(((abs(42*p0*x^5+30*p1*x^4+20*p2*x^3+12*p3*x^2+6*p4*x+2*p5)/(1+(7*p0*x^6+6*p1*x^5+5p2*x^4+4*p3*x^3+3*p4*x^2+2*p5*x+p6)^2)^(3/2))))\n        \n/**/    \n        gtsam::Vector crvJp(7); \n        crvJp = Vector::Zero(7);\n        double lnCtr = -0.6931471*ctrVal;\n        double deno = (pow(2,ctrVal*(curveMax - curve)));\n        double eqp1 = (errYx* abs(errY2x))/(pow( (pow(errYx,2)+1),2.5));\n        double eqp2 = pow( (pow(errYx,2)+1) ,1.5) *abs(errY2x);\n\n\n        crvJp[0] = (lnCtr*(( (21* pow(p5[0],6)* eqp1)  - ((42*pow(p5[0],5) *  errY2x)  / eqp2))))   / deno;\n       \n        crvJp[1] = (lnCtr*(( (18* pow(p5[0],5)* eqp1)  - ((30*pow(p5[0],4) *  errY2x)  / eqp2))))   / deno;\n        \n        crvJp[2] = (lnCtr*(( (15* pow(p5[0],4)* eqp1)  - ((20*pow(p5[0],3) *  errY2x)  / eqp2))))   / deno;\n       \n        crvJp[3] = (lnCtr*(( (12* pow(p5[0],3)* eqp1)  - ((12*pow(p5[0],2) *  errY2x)  / eqp2))))   / deno;\n      \n        crvJp[4] = (lnCtr*(( (9*  pow(p5[0],2)* eqp1)  - ((6*      p5[0]   *  errY2x)  / eqp2))))   / deno;\n   \n        crvJp[5] = (lnCtr*(( (6*      p5[0]*    eqp1)  - ((2*                 errY2x)  / eqp2))))   / deno;\n       \n        crvJp[6] = (lnCtr*   3*     errYx* abs(errY2x)) / (pow( (pow(errYx,2)+1),2.5)*deno);\n        /*\n        if (isnan(crvJp[0])) {crvJp[0] = 0.0;}\n        if (isnan(crvJp[1])) {crvJp[1] = 0.0;}\n        if (isnan(crvJp[2])) {crvJp[2] = 0.0;}\n        if (isnan(crvJp[3])) {crvJp[3] = 0.0;}\n        if (isnan(crvJp[4])) {crvJp[4] = 0.0;}\n        if (isnan(crvJp[5])) {crvJp[5] = 0.0;}\n        if (isnan(crvJp[6])) {crvJp[6] = 0.0;}\n        \n        /*\n        ROS_INFO_STREAM(\"crvJp6: \" << crvJp[6] << \"\");\n        ROS_INFO_STREAM(\"crvJp5: \" << crvJp[5] << \"\");\n        ROS_INFO_STREAM(\"crvJp4: \" << crvJp[4] << \"\");\n        ROS_INFO_STREAM(\"crvJp3: \" << crvJp[3] << \"\");\n        ROS_INFO_STREAM(\"crvJp2: \" << crvJp[2] << \"\");\n        ROS_INFO_STREAM(\"crvJp1: \" << crvJp[1] << \"\");\n        ROS_INFO_STREAM(\"crvJp0: \" << crvJp[0] << \"\");\n        */\n\n\n        if (H1) (*H1) = (Matrix(13, 8) <<   0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                            -pow(p5[0],7)+crvJp[0], -pow(p5[0],6)+crvJp[1], -pow(p5[0],5)+crvJp[2], -pow(p5[0],4)+crvJp[3], -pow(p5[0],3)+crvJp[4], -pow(p5[0],2)+crvJp[5], -p5[0]+crvJp[6], -1.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0).finished();\n          //crvJp0, crvJp1, crvJp2, crvJp3, crvJp4, crvJp5, crvJp6, 0.0,\n          //crvJp[0], crvJp[1], crvJp[2], crvJp[3], crvJp[4], crvJp[5], crvJp[6], 0.0,\n        //(-1)*errYx\n        //double kdot = (0.6931471*ctrVal)/(pow(2,ctrVal*( curveMax - curve)));\n        //-pow(p5[0],7), -pow(p5[0],6), -pow(p5[0],5), -pow(p5[0],4), -pow(p5[0],3), -pow(p5[0],2), -p5[0], -1.0,\n        if (H2) (*H2) = (Matrix(13, 5) <<   0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0,                                            \n                                            0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 1.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 1.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 1.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 1.0).finished();\n        return err;\n    }\n   \n    gtsam::NonlinearFactor::shared_ptr clone() const override {\n      return boost::static_pointer_cast<gtsam::NonlinearFactor>(\n        gtsam::NonlinearFactor::shared_ptr(new PolyPointFactor(*this))); }\n\n};  // PolyPointFactor\n\n\n\n\n\nclass ppFactor: public NoiseModelFactor2<Vector5,Vector5> {\n  \n  private:\n    using This = ppFactor;\n    using Base = gtsam::NoiseModelFactor2<Vector5, Vector5>;\n  public:\n    typedef boost::shared_ptr<ppFactor> shared_ptr;\n    ppFactor(Key i, Key j, Vector5 pointA, Vector5 pointB, const SharedNoiseModel& model)\n        : Base(model, i, j) {}\n\n    virtual ~ppFactor() \n    {}\n     Vector evaluateError(const Vector5& pA, const Vector5& pB,\n        boost::optional<Matrix&> H1 = boost::none, boost::optional<Matrix&> H2 = boost::none) const override \n    {\n        \n        gtsam::Vector err(10); \n        err = Vector::Zero(10);\n        double dis = 0.1;\n        err[0] =  pA[0] - pB[0] + dis ;\n        err[5] =  pB[0] - pA[0] - dis ;\n\n        if (H1) (*H1) = (Matrix(10, 5) <<   1.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            -1.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0).finished();\n      \n        if (H2) (*H2) = (Matrix(10, 5) <<   -1.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            1.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0,\n                                            0.0, 0.0, 0.0, 0.0, 0.0,                                            \n                                            0.0, 0.0, 0.0, 0.0, 0.0, \n                                            0.0, 0.0, 0.0, 0.0, 0.0).finished();\n        return err;\n    }\n   \n    gtsam::NonlinearFactor::shared_ptr clone() const override {\n      return boost::static_pointer_cast<gtsam::NonlinearFactor>(\n        gtsam::NonlinearFactor::shared_ptr(new ppFactor(*this))); }\n\n};  // point<->point Factor\n\n\n\n\ndouble getPolyY(const double& x, const Vector8& p8)  //only for illustration purposes \n{\n    double y;\n    y = (p8[0]*pow(x,7))+(p8[1]*pow(x,6))+(p8[2]*pow(x,5))+(p8[3]*pow(x,4))+(p8[4]*pow(x,3))+(p8[5]*pow(x,2))+(p8[6]*x)+ p8[7];\n    return y; // order x^7 -> x^0 \n}\n\nint main(int argc, char **argv)\n{\n\n    using namespace gtsam_node;\n    using namespace ast;\n    using namespace ast::ros;\n    ::ros::init(argc, argv, \"gtsam_node\");\n    NodeHandle nh;\n    \n    /*--------------------------------------------| Get Params |---------------------------------------------*/\n    CarParams carParams;\n    MheParams mheParams;\n    ParamsIn(carParams, mheParams, nh); //TODO: change mhe to graph (just old name )\n    /*-------------------------------------------------------------------------------------------------------*/\n    \n    /*-----------------------------------------------| Rviz |-------------------------------------------------*/\n    ::ros::Publisher marker_pub = nh.advertise<visualization_msgs::Marker>(\"GTSAM_points\", 10);\n    /*--------------------------------------------------------------------------------------------------------*/\n    \n    ROS_INFO_STREAM(\"Estimator loop rate: \"<< mheParams.loopRate <<\"\");\n\n    sleep(2);\n    ::ros::Rate loop_rate(mheParams.loopRate);\n    while(::ros::ok())\n    {\n        auto now = ::ros::Time::now();\n        /*---------------------------------| Rviz initialization |--------------------------------------------*/\n        visualization_msgs::Marker points, pointsInit, PointOpt, line_strip, circleObst;\n        circleObst.header.frame_id = PointOpt.header.frame_id = pointsInit.header.frame_id = points.header.frame_id = line_strip.header.frame_id = \"/gtsam_frame\";\n        circleObst.header.stamp = points.header.stamp = line_strip.header.stamp = PointOpt.header.stamp = pointsInit.header.stamp = now;\n        circleObst.ns = pointsInit.ns = PointOpt.ns = points.ns = line_strip.ns = \"points_and_lines\";\n        circleObst.action = pointsInit.action = PointOpt.action = points.action = line_strip.action = visualization_msgs::Marker::ADD;\n        circleObst.pose.orientation.w = pointsInit.pose.orientation.w = PointOpt.pose.orientation.w = points.pose.orientation.w = line_strip.pose.orientation.w = 1.0;\n\n        points.id = 0; line_strip.id = 1; pointsInit.id = 2; PointOpt.id = 3; circleObst.id = 4;\n        points.type = visualization_msgs::Marker::POINTS;\n        line_strip.type = visualization_msgs::Marker::LINE_STRIP;\n        pointsInit.type = visualization_msgs::Marker::POINTS;\n        PointOpt.type = visualization_msgs::Marker::POINTS;\n        circleObst.type = visualization_msgs::Marker::LINE_STRIP;\n        // POINTS markers use x and y scale for width/height respectively\n        points.scale.x = 0.2; points.scale.y = 0.2;  points.scale.z = 0.0;\n        pointsInit.scale.x = 0.05; pointsInit.scale.y = 0.05; pointsInit.scale.z = 0.0;\n        PointOpt.scale.x = 0.05; PointOpt.scale.y = 0.05; PointOpt.scale.z = 0.0;\n        points.color.g = 1.0; points.color.a = 1.0;\n        line_strip.color.b = 1.0; line_strip.color.a = 1.0;\n        line_strip.scale.x = 0.02; line_strip.scale.y = 0.02; line_strip.scale.z = 0.0;\n        circleObst.scale.x = 0.01;circleObst.scale.y = 0.01;circleObst.scale.z = 0.0; circleObst.color.a = 1.0;\n        circleObst.color.b = 1.0; circleObst.color.g = 1.0;\n        pointsInit.color.r = 1.0; pointsInit.color.a = 1.0;\n        PointOpt.color.r = 1.0; PointOpt.color.b = 1.0; PointOpt.color.a = 1.0;\n        /*--------------------------------------------------------------------------------------------------------*/\n\n\n        NonlinearFactorGraph graph;\n        /*---------------------------------------| polynomal node |-----------------------------------------------*/\n        gtsam::Vector polyPriorSigmas(8);\n        polyPriorSigmas << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ;\n        auto priorPolyNoise = gtsam::noiseModel::Diagonal::Sigmas(polyPriorSigmas);\n        gtsam::Vector polyParams(8);\n        polyParams << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ; // order x^7 -> x^0 \n        //polyParams << 0.001, -0.036, 0.294, -0.808, -0.505, 4.54, -2.492, 1.500; // order x^7 -> x^0 \n        //graph.addPrior(Symbol('l', 0), polyParams, priorPolyNoise);\n        /*--------------------------------------------------------------------------------------------------------*/\n\n        /*--------------------------------| polynomal<->point factor |--------------------------------------------*/\n        gtsam::Vector polyPointSigmas(13);\n        polyPointSigmas << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ;\n        auto polyPointNoise = gtsam::noiseModel::Diagonal::Sigmas(polyPointSigmas);\n\n        gtsam::Vector po1(5), po2(5), poj(5) ;\n        po1 << -3.0, 3.0, 0.0, 0.5, 0.0;\n        poj << 0.0, 0.0, 0.0, 0.5, 0.0;\n        po2 << 3.0, -3.0, 0.0, 0.5, 0.0;\n        gtsam::Vector poPriorSigmas(5);\n        poPriorSigmas << 0.0, 0.0, 0.0, 0.0, 0.0;\n        auto priorPoNoise = gtsam::noiseModel::Diagonal::Sigmas(poPriorSigmas);\n        graph.addPrior(Symbol('p', 0), po1, priorPoNoise);   //add prior on first point\n        graph.addPrior(Symbol('p', 59), po2, priorPoNoise);   //add prior on first point\n        geometry_msgs::Point pois; \n        pois.x = po1[0];\n        pois.y = po1[1];\n        points.points.push_back(pois);\n        pois.x = po2[0];\n        pois.y = po2[1];\n        points.points.push_back(pois);\n\n        std::vector<gtsam::Vector5> poses;\n        for(size_t j = 0; j < 60; ++j) // create vector of poses\n        {\n          poses.push_back(poj);\n        }\n        \n        for(size_t j = 0; j < poses.size(); ++j) //add polynoaml<->point factors to the graph\n        {\n          graph.push_back(boost::make_shared<PolyPointFactor>(Symbol('l', 0), Symbol('p', j), polyParams, poses[j], polyPointNoise));\n          ROS_INFO_STREAM(\"key: \"<< j <<\"\");\n        }\n        /*--------------------------------------------------------------------------------------------------------*/\n\n\n        /*-----------------------------------| point<->point factor |---------------------------------------------*/\n        gtsam::Vector ppSigmas(10);\n        ppSigmas << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n        auto ppNoise = gtsam::noiseModel::Diagonal::Sigmas(ppSigmas);\n\n        for (size_t j = 0; j < (poses.size()-1); ++j)   //add distance factor in x direction between each neighbouring point \n        {\n          graph.push_back(boost::make_shared<ppFactor>(Symbol('p', j), Symbol('p', j+1), poses[j], poses[j+1], ppNoise));\n        }\n        /*--------------------------------------------------------------------------------------------------------*/\n        \n\n        /*--------------------------------------| obstacle  factor |----------------------------------------------*/\n        auto circleNoise = noiseModel::Diagonal::Sigmas(Vector1(0.0));  // 10cm std on x,y\n        gtsam::Vector circle0(3),circle1(3); //x, y, r\n        circle0 <<  0.5, 2.6, 0.5;\n        circle1 << 0.2, 0.0, 0.6;\n        \n        for(size_t j = 0; j < poses.size(); ++j) \n        {\n          graph.push_back(boost::make_shared<CircleFactor>(Symbol('p', j), circle0, circleNoise));\n          graph.push_back(boost::make_shared<CircleFactor>(Symbol('p', j), circle1, circleNoise));\n        }\n        /*--------------------------------------------------------------------------------------------------------*/\n        ROS_INFO_STREAM(\"/////////////////////////////////////////////////////////\");\n        //graph.print(\"\\nFactor Graph:\\n\");  // cout the graph\n\n        /*----------------------------| graph optimization initialization |----------------------------------------*/\n        Values initialEstimate;\n        \n        gtsam::Vector po0init(8);\n        //po0init << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0; \n        po0init << 0.0, 0.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0;\n        initialEstimate.insert(Symbol('l', 0), po0init);\n\n        geometry_msgs::Point poisInit;\n        gtsam::Vector po1init(5);\n        po1init << -3.1, 3.1, 0.0, 0.5, 0.0;\n        poisInit.x = po1init[0];\n        poisInit.y = po1init[1];\n        pointsInit.points.push_back(poisInit);\n        \n        for (size_t j = 0; j < poses.size(); ++j)   //points.size()\n        {\n          initialEstimate.insert(Symbol('p', j), po1init);\n        }\n        //initialEstimate.print(\"\\nInitial Estimate:\\n\");  // print\n        /*--------------------------------------------------------------------------------------------------------*/\n        \n\n\n\n        /*-------------------------------------| optimize the graph  |---------------------------------------------*/\n        LevenbergMarquardtOptimizer optimizer(graph, initialEstimate);\n        Values result = optimizer.optimize();\n        //result.print(\"Final Result:\\n\");\n        geometry_msgs::Point poisOpt;\n        \n        Vector8 polyUpdate = result.at<Vector8>(Symbol('l', 0));\n        for (size_t j = 0; j < poses.size(); ++j)   //points.size()\n        {\n          Vector5 x_update = result.at<Vector5>(Symbol('p', j));\n          poisOpt.x = x_update[0];\n          poisOpt.y = x_update[1];\n          PointOpt.points.push_back(poisOpt);\n        }\n\n        Marginals marginals(graph, result);\n        /*\n        cout << \"polynomial covariance:\\n\" << marginals.marginalCovariance(Symbol('l', 0)) << endl;\n        cout << \"p1 covariance:\\n\" << marginals.marginalCovariance(Symbol('p', 0)) << endl;\n        cout << \"p2 covariance:\\n\" << marginals.marginalCovariance(Symbol('p', 1)) << endl;\n        cout << \"p3 covariance:\\n\" << marginals.marginalCovariance(Symbol('p', 2)) << endl;\n        cout << \"p4 covariance:\\n\" << marginals.marginalCovariance(Symbol('p', 3)) << endl;\n        cout << \"p5 covariance:\\n\" << marginals.marginalCovariance(Symbol('p', 4)) << endl;\n        /**/\n        /*--------------------------------------------------------------------------------------------------------*/\n\n        /*------------------------------------| graph result to rviz  |-------------------------------------------*/\n        \n        auto circle1bst = circleObst;\n        circle1bst.id = 5;\n        for (double i = 0; i < 100; ++i)\n        {\n        geometry_msgs::Point p;\n        p.x = ((double)i/10) - 5;\n        p.y = getPolyY(p.x, polyUpdate);\n        p.z = 0;\n        line_strip.points.push_back(p);\n        }\n        for (double i = 0; i < (2 * M_PI); i = i + (M_PI/50))\n        {\n        geometry_msgs::Point p;\n        p.x = circle0[2] * cos(i) + circle0[0];\n        p.y = circle0[2] * sin(i) + circle0[1];\n        p.z = 0;\n        circleObst.points.push_back(p);\n        }\n        \n        for (double i = 0; i < (2 * M_PI); i = i + (M_PI/50))\n        {\n        geometry_msgs::Point p;\n        p.x = circle1[2] * cos(i) + circle1[0];\n        p.y = circle1[2] * sin(i) + circle1[1];\n        p.z = 0;\n        circle1bst.points.push_back(p);\n        }\n        \n\n        marker_pub.publish(circleObst);\n        marker_pub.publish(circle1bst);\n        marker_pub.publish(line_strip);\n        marker_pub.publish(points);\n        //marker_pub.publish(pointsInit);\n        marker_pub.publish(PointOpt);\n\n        /*--------------------------------------------------------------------------------------------------------*/\n        auto loopTime =  ::ros::Time::now() - now;\n        ROS_INFO_STREAM(\"loop time\" << loopTime.toSec());\n\n        ::ros::spinOnce();\n        loop_rate.sleep();\n\n    }\n\n    return 0;\n}\n\n/*\ngtsam::Vector crvJp(7); \n        crvJp = Vector::Zero(7);\n        crvJp[0] = (-0.6931471*ctrVal*(((21* pow(p5[0],6)* errYx*  sqrt( pow(errYx,2)  +1))/ abs(errY2x))  - ((42*pow(p5[0],5) *  pow( (pow(errYx,2)+1) ,1.5))  / (errY2x*abs(errY2x))  )))  / (pow(2,ctrVal*(p5[3] - curveMax)));\n        //if (isnan(crvJp[0])) {crvJp[0] = 0.0;}\n        crvJp[1] = (-0.6931471*ctrVal*(((18* pow(p5[0],5)* errYx*  sqrt( pow(errYx,2)  +1))/ abs(errY2x))  - ((30*pow(p5[0],4) *  pow( (pow(errYx,2)+1) ,1.5))  / (errY2x*abs(errY2x))  )))  / (pow(2,ctrVal*(p5[3] - curveMax)));\n        //if (isnan(crvJp[1])) {crvJp[1] = 0.0;}\n        crvJp[2] = (-0.6931471*ctrVal*(((15* pow(p5[0],4)* errYx*  sqrt( pow(errYx,2)  +1))/ abs(errY2x))  - ((20*pow(p5[0],3) *  pow( (pow(errYx,2)+1) ,1.5))  / (errY2x*abs(errY2x))  )))  / (pow(2,ctrVal*(p5[3] - curveMax)));\n        //if (isnan(crvJp[2])) {crvJp[2] = 0.0;}\n        crvJp[3] = (-0.6931471*ctrVal*(((12* pow(p5[0],3)* errYx*  sqrt( pow(errYx,2)  +1))/ abs(errY2x))  - ((12*pow(p5[0],2) *  pow( (pow(errYx,2)+1) ,1.5))  / (errY2x*abs(errY2x))  )))  / (pow(2,ctrVal*(p5[3] - curveMax)));\n        //if (isnan(crvJp[3])) {crvJp[3] = 0.0;}\n        crvJp[4] = (-0.6931471*ctrVal*(((9*  pow(p5[0],2)* errYx*  sqrt( pow(errYx,2)  +1))/ abs(errY2x))  - ((6*      p5[0]   *  pow( (pow(errYx,2)+1) ,1.5))  / (errY2x*abs(errY2x))  )))  / (pow(2,ctrVal*(p5[3] - curveMax)));\n        //if (isnan(crvJp[4])) {crvJp[4] = 0.0;}\n        crvJp[5] = (-0.6931471*ctrVal*(((6*      p5[0]*    errYx*  sqrt( pow(errYx,2)  +1))/ abs(errY2x))  - ((2*                 pow( (pow(errYx,2)+1) ,1.5))  / (errY2x*abs(errY2x))  )))  / (pow(2,ctrVal*(p5[3] - curveMax)));\n        //if (isnan(crvJp[5])) {crvJp[5] = 0.0;}\n        crvJp[6] = (-0.6931471*ctrVal*   3*                errYx*  sqrt( pow(errYx,2)  +1))                                                                                     /(abs(errY2x)*pow(2,ctrVal*(p5[3] - curveMax)));\n        //if (isnan(crvJp[6])) {crvJp[6] = 0.0;}\n        */\n\n        ", "meta": {"hexsha": "7b94f80ebe6ac8aa370a27a2572facd688313e50", "size": 26345, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gtsam_node.cpp", "max_stars_repo_name": "crt-adas/adas_path_planning", "max_stars_repo_head_hexsha": "601e2d27fb538e0d3e5ecec50972002394675b36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gtsam_node.cpp", "max_issues_repo_name": "crt-adas/adas_path_planning", "max_issues_repo_head_hexsha": "601e2d27fb538e0d3e5ecec50972002394675b36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gtsam_node.cpp", "max_forks_repo_name": "crt-adas/adas_path_planning", "max_forks_repo_head_hexsha": "601e2d27fb538e0d3e5ecec50972002394675b36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.7109929078, "max_line_length": 226, "alphanum_fraction": 0.4666160562, "num_tokens": 9141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6216533912333375}}
{"text": "#include <iostream>\r\n#define ARMA_DONT_USE_WRAPPER\r\n#include <armadillo>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\nusing namespace arma;\r\n\r\n// g++ mat2.cpp -o mat2 -std=c++11 -O2 -larmadillo -framework Accelerate\r\n\r\n\r\nint\r\nmain(int argc, char** argv)\r\n  {\r\n      float pi=M_PI;\r\n      float eu=std::exp(1.0);\r\n      float raiz= sqrt(2);\r\n      float raiz1= pow(pi,0.3333);\r\n      float coseno = cos(pi/4);\r\n      float cdiag = pow(7,0.3333);\r\n      \r\n      mat A(10,10, fill::zeros); //A(fila, columna)\r\n      cout << \"A.n_rows: \" << A.n_rows << endl;\r\n      cout << \"A.n_cols: \" << A.n_cols << endl;\r\n      A.rows(0,4) += pi;\r\n      A.rows(5,9) += eu;\r\n      A.save(\"A1.txt\", raw_ascii);\r\n      \r\n      mat B(10,10, fill::zeros);\r\n      cout << \"B.n_rows: \" << B.n_rows << endl;\r\n      cout << \"B.n_cols: \" << B.n_cols << endl;\r\n      B.col(0) += raiz;\r\n      B.col(2) += raiz;\r\n      B.col(4) += raiz;\r\n      B.col(8) += raiz;\r\n      B.col(1) += raiz1;\r\n      B.col(6) += raiz1;\r\n      B.col(7) += raiz1;\r\n      B.col(3) += coseno;\r\n      B.col(5) += coseno;\r\n      B.col(9) += coseno;\r\n      B.save(\"B1.txt\", raw_ascii);\r\n      \r\n      mat C = repelem(A, 1, 1);\r\n      C.diag() += cdiag;\r\n      C.save(\"C1.txt\", raw_ascii);\r\n      \r\n      mat D(10,10, fill::randu);\r\n      mat E(10,10, fill::zeros );\r\n\r\n      E += pow((A.t()+B),-1 ) + (pow(A,-1)*pow(B,0.3333)*pow(D,0.2)) - (pow(D,-1)*B.t()*(A.t()*pow(C,-1))) + D*(cos(C)*sin(A)+pow(sin(B),2)) ;\r\n      E.save(\"E1.txt\", raw_ascii);\r\n      \r\n      mat F(10,10, fill::zeros);\r\n      \r\n      F += exp(C)*D + exp(A)*sin(A) + (sqrt(pow(pi, 3))/exp(pi))*cos(D) - log10(sqrt(pi/8))*pow(cos(B),4) + pow(sin(D.t()*pow(C,3)*A),-1)+ E*(cos(D)+sin(D));\r\n      F.save(\"F1.txt\", raw_ascii);\r\n      \r\n      cout << \"C.n_rows: \" << C.n_rows << endl;\r\n      cout << \"C.n_cols: \" << C.n_cols << endl;\r\n      cout << \"D.n_rows: \" << D.n_rows << endl;\r\n      cout << \"D.n_cols: \" << D.n_cols << endl;\r\n      cout << \"E.n_rows: \" << E.n_rows << endl;\r\n      cout << \"E.n_cols: \" << E.n_cols << endl;\r\n      cout << \"F.n_rows: \" << F.n_rows << endl;\r\n      cout << \"F.n_cols: \" << F.n_cols << endl;\r\n      \r\n      return 0;\r\n      \r\n  }\r\n\r\n", "meta": {"hexsha": "02d4bace293d6ae80d451a7ff7fe126ad4b85854", "size": 2173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "robotica/mat2.cpp", "max_stars_repo_name": "Jacobprojects/UACJ-Robotica", "max_stars_repo_head_hexsha": "62ef2adf02e615b8b1733045148401c98e28a663", "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": "robotica/mat2.cpp", "max_issues_repo_name": "Jacobprojects/UACJ-Robotica", "max_issues_repo_head_hexsha": "62ef2adf02e615b8b1733045148401c98e28a663", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "robotica/mat2.cpp", "max_forks_repo_name": "Jacobprojects/UACJ-Robotica", "max_forks_repo_head_hexsha": "62ef2adf02e615b8b1733045148401c98e28a663", "max_forks_repo_licenses": ["Apache-2.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.1805555556, "max_line_length": 158, "alphanum_fraction": 0.4661757938, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6216533901993779}}
{"text": "\r\n\r\n#pragma once\r\n\r\n#include <list>\r\n#include <vector>\r\n#include <NTL/ZZ.h>\r\n#include <math/mpz_class.hh>\r\n#include <math.h>\r\n#include <algorithm>    // std::min\r\n#include <float.h>\r\n#include <limits.h>\r\nusing namespace std;\r\nstruct encnum\r\n{\r\n\tint  exponent;\r\n\tmpz_class mantissa;\r\n\t//double plaintext;\r\n};\r\nclass Paillier {\r\n public:\r\n    Paillier(const std::vector<mpz_class> &pk, gmp_randstate_t state);\r\n    std::vector<mpz_class> pubkey() const { return { n, g }; }\r\n    encnum encrypt_f(double plaintext);\r\n    std::vector  <std::vector<encnum>> encryptMatrix(const std::vector < std::vector<double> > &p);\r\n    encnum encode( double plaintext) const;\r\n    \r\n    encnum sub_f(const encnum &a, const encnum &b) const;\r\n    encnum add_f(const encnum &a, const encnum &b) const;\r\n    std::vector  <std::vector<encnum>> addMatrix(const std::vector < std::vector<encnum> > &c0, const std::vector < std::vector<encnum> > &c1) ;\r\n    std::vector  <std::vector<encnum>> multConstMatrixbyMatrix(const std::vector < std::vector<double> > &c, const std::vector < std::vector<encnum> > &mat) ;\r\n    std::vector  <std::vector<encnum>> multMatrixbyConstMatrix(const std::vector < std::vector<encnum> > &mat , const std::vector < std::vector<double> > &c) ;\r\n    \r\n    encnum decrease_exponent_too(const encnum &y,const int new_exp) const;\r\n    encnum constMult_f(const double &m, const encnum &c) const; \r\n\tvector < vector<encnum> > multMatrixbyConst( double alpha,const vector < vector<encnum> > &mat) ;\r\n\r\n\t\r\n    mpz_class encrypt(const mpz_class &plaintext);\r\n    mpz_class add(const mpz_class &c0, const mpz_class &c1) const;\r\n    mpz_class sub(const mpz_class &c0, const mpz_class &c1) const;\r\n    mpz_class constMult(const mpz_class &m, const mpz_class &c) const;\r\n    mpz_class constMult(long m, const mpz_class &c) const;\r\n    mpz_class constMult(const mpz_class &c, long m) const { return constMult(m,c); };\r\n    mpz_class scalarize(const mpz_class &c);\r\n    void refresh(mpz_class &c);\r\n    mpz_class random_encryption();\r\n\r\n    mpz_class dot_product(const std::vector<mpz_class> &c, const std::vector<mpz_class> &v);\r\n    mpz_class dot_product(const std::vector<mpz_class> &c, const std::vector<long> &v);\r\n    void rand_gen(size_t niter = 100, size_t nmax = 1000);\r\n    double logbase(double base, double x) const;\r\n\r\n    void printMatrix(std::vector  <std::vector<double>> &Mat);\r\n    \r\n    const double precision = 0.00000001 ; //0.00000001 0.001\r\n    bool acc_per = false;\r\n    int max_exponent = 0;\r\n\t//int exponent;\r\n\t//int int_rep;\r\n    int BASE = 10;\r\n    double LOG2_BASE = log2(BASE);\r\n    double FLOAT_MANTISSA_BITS = LDBL_MANT_DIG;\r\n    encnum zero_enc;\r\n   // double max_int = n.get_d()/3 -1;\r\n    //double nsquare = n.get_d() * n.get_d() ;\r\n protected:\r\n    /* Public key */\r\n    const mpz_class n, g;\r\n\r\n\r\n    \r\n    /* Randomness state */\r\n    gmp_randstate_t _randstate;\r\n\r\n    /* Cached values */\r\n    const uint nbits;\r\n    const mpz_class n2;\r\n    bool good_generator;\r\n    \r\n    /* Pre-computed randomness */\r\n    std::list<mpz_class> rqueue;\r\n};\r\n\r\nclass Paillier_priv : public Paillier {\r\n public:\r\n    Paillier_priv(const std::vector<mpz_class> &sk, gmp_randstate_t state);\r\n    std::vector<mpz_class> privkey() const { return { p, q, g, a }; }\r\n    void find_crt_factors();\r\n    \r\n    // if a !=0, and if you are encrypting using the private key, use this function\r\n    // 75% speedup\r\n    mpz_class encrypt(const mpz_class &plaintext);\r\n    \r\n\r\n    // no speedup compared to the fast_encrypt\r\n    mpz_class fast_encrypt_precompute(const mpz_class &plaintext);\r\n\r\n    mpz_class decrypt(const mpz_class &ciphertext) const;\r\n    static std::vector<mpz_class> keygen(gmp_randstate_t state, uint nbits = 1024, uint abits = 256);\r\n    double decrypt_f(encnum x) const;\r\n    std::vector< std::vector<double> > decryptMatrix(const std::vector < std::vector<encnum> > &c);\r\n\r\n protected:\r\n    /* Private key, including g from public part; n=pq */\r\n    const mpz_class p, q;\r\n    const mpz_class a;      /* non-zero for fast mode */\r\n\r\n    /* Cached values */\r\n    const bool fast;\r\n    const mpz_class p2, q2;\r\n    mpz_class e_p2, e_q2;\r\n    const mpz_class two_p, two_q;\r\n    const mpz_class pinv, qinv;\r\n    const mpz_class hp, hq;\r\n};\r\n\r\nclass Paillier_priv_fast : public Paillier_priv {\r\npublic:\r\n    Paillier_priv_fast(const std::vector<mpz_class> &sk, gmp_randstate_t state);\r\n    void precompute_powers();\r\n    mpz_class compute_g_star_power(const mpz_class &x);\r\n    static std::vector<mpz_class> keygen(gmp_randstate_t state, uint nbits = 1024);\r\n    \r\n    mpz_class encrypt(const mpz_class &plaintext);\r\nprivate:\r\n    const mpz_class g_star_;\r\n    const mpz_class phi_n;\r\n    const mpz_class phi_n2;\r\n    const uint phi_n2_bits;\r\n    std::vector<mpz_class> g_star_powers_p_;\r\n    std::vector<mpz_class> g_star_powers_q_;\r\n};\r\n", "meta": {"hexsha": "6635714b53a878654b81b5ff4e43ca59fd4db471", "size": 4856, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Source/crypto/paillier.hh", "max_stars_repo_name": "TarekIbnZiad/CryptoImg", "max_stars_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-05T18:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T07:33:10.000Z", "max_issues_repo_path": "Source/crypto/paillier.hh", "max_issues_repo_name": "TarekIbnZiad/CryptoImg", "max_issues_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/crypto/paillier.hh", "max_forks_repo_name": "TarekIbnZiad/CryptoImg", "max_forks_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-11T00:32:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T23:35:20.000Z", "avg_line_length": 36.2388059701, "max_line_length": 160, "alphanum_fraction": 0.6692751236, "num_tokens": 1337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7057850216484837, "lm_q1q2_score": 0.6216533759147864}}
{"text": "/*\n * ex1x.cpp\n *\n *  Created on: 25.04.2017\n *\n *  Author: Daniel Rehfeldt\n *\n *  Compile: g++ ex1x.cpp -o ex1x -O3 -std=c++14 -Wall\n */\n\n#include <vector>\n#include <cmath>\n#include <limits>\n#include <iostream>\n#include <fstream>\n#include <cassert>\n#include <boost/spirit/include/qi.hpp>\n\n\nint main(int argc, char* argv[])\n{\n    // check number of parameters\n    if( argc != 2 )\n    {\n       // tell the user how to run the program\n       std::cerr << \"Usage: \" << argv[0] << \" filename\" << std::endl;\n       exit(EXIT_FAILURE);\n    }\n\n    /* start of definitions for geometric mean */\n\n    std::vector<double> valvec[2];\n    double geomean[2] {0.0, 0.0};\n    int geomeancount[2] {0, 0};\n\n    // get number of multiplications in geo mean computation guaranteed to be without underflow; unfortunately, constexpr is not supported here by c++14\n    const int nmults = std::log2(std::numeric_limits<double>::min()) / std::log2(0.5);\n\n    assert(nmults > 0);\n    assert(std::ilogb(std::numeric_limits<double>::max()) + 1 <= std::numeric_limits<int>::max() / nmults); // guard against overflow of exponent\n\n    // compute logarithm of product of values entries in range [start, end)\n    auto subsetlog = [](auto start, auto end, std::vector<double> & values)\n    {\n       // split values into mantissa and exponent\n       int exponentsum = 0;\n       double mantissaprod = 1.0;\n       for( auto j = start; j < end; j++ )\n       {\n            int ex;\n            mantissaprod *= std::frexp(values[j], &ex);\n            exponentsum += ex;\n       }\n       return std::log2(mantissaprod) + exponentsum;\n    };\n\n    /* end of definitions for geometric mean */\n\n    unsigned int nlines = 0;\n\n    std::ifstream file (argv[1], std::ifstream::in);\n    std::string strline;\n\n    // read line by line\n    while( getline(file, strline) )\n    {\n       nlines++;\n\n       using namespace boost::spirit;\n       using qi::int_;\n       using qi::double_;\n       using qi::phrase_parse;\n       using ascii::space;\n\n       double value;\n       int location;\n\n       // iterator which will be changed by parse method\n       auto it = strline.begin();\n\n       // parse line as int;int;double and ignore whitespaces\n       bool success = phrase_parse(it, strline.end(),\n             int_ >> ';' >> int_[([&location](int i){ location = i; })] >> ';' >> double_[([&value](double i){ value = i; })]\n                      , space);\n\n       if( success && it == strline.end() )\n       {\n          if( location < 1 || location > 2 || value <= 0 || std::isnan(value) || value <= 0 )\n             continue;\n\n          // finally, store the value\n          valvec[--location].push_back(value);\n\n          // update geo mean?\n          assert(valvec[location].size() <= std::numeric_limits<int>::max());\n          assert(int(valvec[location].size()) - geomeancount[location] <= nmults);\n          if( int(valvec[location].size()) - geomeancount[location] == nmults )\n          {\n             geomean[location] += subsetlog(geomeancount[location], int(valvec[location].size()), valvec[location]);\n             geomeancount[location] = int(valvec[location].size());\n          }\n       }\n    }\n\n    file.close();\n\n    // update and print geo mean\n    for( int i = 0; i < 2; i++ )\n    {\n      geomean[i] += subsetlog(geomeancount[i], int(valvec[i].size()), valvec[i]);\n      geomean[i] /= double(valvec[i].size());\n      geomean[i] = std::pow(2.0, geomean[i]);\n\n      std::cout << \"Valid values Loc\" << i + 1 <<  \" \" << valvec[i].size() << \" with geo mean: \" << geomean[i] << std::endl;\n    }\n    std::cout << \"File: \" << argv[1] << \" with \" << nlines << \" lines \" << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "bf0886956fea5c54f92986b6e01b21a7bf1f7a82", "size": 3664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "01_Exercise/ex1x.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "01_Exercise/ex1x.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "01_Exercise/ex1x.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 30.5333333333, "max_line_length": 152, "alphanum_fraction": 0.5665938865, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6216275192832591}}
{"text": "// NOTE: this is a subset sum problem\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <numeric>\n#include <string>\n#include <vector>\n\n#include <boost/range/adaptor/reversed.hpp>\n#include <boost/range/irange.hpp>\n\n// this recursive function will go through all possible combinations of weights, starting with the last weight in the list,\n// which is indicated by parameter 'last', until the sum (or what's left of it) is reached\ntemplate<typename Set, typename Sets, typename W, typename T, typename N>\nauto find_subset(Set&& subset, Sets&& subsets, const W& weights, const T& tbl_has_sum, N row, N sum_left) -> void {\n\n\tconst auto only_one_element_left = (row == 0);\n\n\t// first base case: only one weight left (first of the weights), sum is non-zero\n\t// and the final weight to be added to reach 'sum_left' is the the first weight\n\tif(only_one_element_left && (sum_left > 0) && tbl_has_sum[row][sum_left]) {\n\n\t\tsubset.push_back(weights[row]);\n\n\t\tsubsets.push_back(subset);\n\n\t} else if(only_one_element_left && (sum_left == 0)) {\n\n\t\t// second base case: only one weight left, there's no more sum left\n\t\t// to add to, so the current subset can be added to the collection\n\t\tsubsets.push_back(subset);\n\n\t} else {\n\n\t\tconst auto prev_row = (row - 1);\n\n\t\t// first recursive case: the matrix tells us whether or not sum_left\n\t\t// can be formed without the current weight but with all previous weights\n\t\tif(tbl_has_sum[prev_row][sum_left]) {\n\n\t\t\t// there are potentially two successive calls to find_subset, which means the passed subset will be modified\n\t\t\t// both times - but on the same recursion level we need the subset to be the same, so the first call will get\n\t\t\t// a copy, and when the recursion for that copy is finished, which at that point will be modified, we can continue\n\t\t\t// to the second call with the original that we started the recursion with\n\t\t\tauto new_subset = subset;\n\n\t\t\tfind_subset(new_subset, subsets, weights, tbl_has_sum, prev_row, sum_left);\n\t\t}\n\n\t\tconst auto weight = weights[row];\n\n\t\tconst auto new_sum_left = (sum_left - weight);\n\n\t\t// second recursive case: to make access to the matrix safe, we need to check first,\n\t\t// if the current weight can be added without going over the sum we need - if the first\n\t\t// check is successful, the matrix will tell us, whether or not the previous row can\n\t\t// create the sum 'sum_left - weight' - if the answer is 'yes', we can add the current\n\t\t// weight to the current subset and make another recursive call\n\t\tif((sum_left >= weight) && tbl_has_sum[prev_row][new_sum_left]) {\n\n\t\t\tsubset.push_back(weight);\n\n\t\t\tfind_subset(subset, subsets, weights, tbl_has_sum, prev_row, new_sum_left);\n\t\t}\n\t}\n}\n\n// this function is based on: https://stackoverflow.com/a/45427013/699211\ntemplate<typename T, typename N>\nauto find_subsets(const T& weights, N sum) {\n\n\tauto subsets = std::vector<T>{};\n\n\t// in dynamic programming, the first row of the lookup matrix\n\t// represents zero elements (empty subsets), so normally such\n\t// a matrix would have (n + 1) rows, but since we won't do anything\n\t// with that particular row, we might just as well stick to n rows\n\tconst auto rows = weights.size();\n\n\tusing VectorBool = std::vector<std::uint8_t>;\n\tusing Matrix = std::vector<VectorBool>;\n\n\t// todo: rename lookup\n\n\t// this is a truth table - matrix[i][s] returns true or false to indicate the answer to the question:\n\t// \"using the first i items in the array can we find a subset sum to s?\"\n\tauto tbl_has_sum = Matrix(rows);\n\n\tconst auto columns = (sum + 1);\n\n\tfor(auto& row : tbl_has_sum) {\n\t\trow = VectorBool(columns);\n\t\t// first column represents subset sum = 0, which is true for all sets\n\t\trow.front() = true;\n\t}\n\n\t// first element of the weights container\n\tconst auto first = weights.front();\n\n\t// if the first element of weights is <= sum, then the set containing that weight will have it as subset sum,\n\t// allowing to check if it's possible to combine that weight with any of the subset sums of the previous row\n\t// to see if we can create the subset sum we are looking for\n\tif (first <= sum) {\n\t\ttbl_has_sum.front()[first] = true;\n\t}\n\n\tfor(const auto row : boost::irange({1}, rows)) {\n\n\t\tfor(const auto col : boost::irange({}, columns)) {\n\n\t\t\tauto& cell = tbl_has_sum[row][col];\n\n\t\t\tconst auto weight = weights[row];\n\t\t\tconst auto& prev_row = tbl_has_sum[row-1];\n\t\t\tconst auto cell_prev_row = prev_row[col];\n\n\t\t\t// ensure we don't accidentally go out of bounds\n\t\t\tif(weight <= col) {\n\t\t\t\t// this checks if the subset sum 'col' can be formed by\n\t\t\t\t// a) the previous set of weights (cell_prev_row) or\n\t\t\t\t// b) if subset sum 'col-weight' is formable by the previous set\n\t\t\t\t// this is the implementation of the following logic:\n\t\t\t\t// set X with subset-sum k has subset-sum k1 if subset X1 has subset-sum (k - k1)\n\t\t\t\tcell = (cell_prev_row || prev_row[col-weight]);\n\t\t\t} else {\n\t\t\t\tcell = cell_prev_row;\n\t\t\t}\n\t\t}\n\t}\n\n\t// start recursion\n\tfind_subset(T{}, subsets, weights, tbl_has_sum, (rows - 1), sum);\n\n\treturn subsets;\n}\n\ntemplate<typename T>\nauto find_min_sets(const T& subsets) {\n\n\tusing value_type = decltype(subsets.size());\n\tauto min_size = std::numeric_limits<value_type>::max();\n\n\tauto min_sets = T{};\n\n\tfor(const auto& subset : subsets) {\n\n\t\tconst auto subset_size = subset.size();\n\n\t\t// we don't need any sets that have size > min_size\n\t\t// so if a smaller set is found, the min_sets collection\n\t\t// can immediately be replaced\n        if(subset_size < min_size) {\n        \tmin_size = subset_size;\n        \tmin_sets = {subset};\n        } else if(subset_size == min_size) {\n        \tmin_sets.push_back(subset);\n        }\n\t}\n\n\treturn min_sets;\n}\n\n// =======================================\n// SOME TEMPLATE NONSENSE FOR DEDUCING THE\n// INNERMOST TYPE OF A NESTED CONTAINER\n// =======================================\ntemplate<typename T, typename = std::void_t<>>\nstruct innermost_value_type {\n    using type = T;\n};\n\ntemplate<typename T>\nstruct innermost_value_type<T, std::void_t<typename T::value_type>> {\n    using type = typename innermost_value_type<typename T::value_type>::type;\n};\n\ntemplate<typename T>\nusing innermost_value_type_t = typename innermost_value_type<T>::type;\n// =======================================\n// END OF TEMPLATE NONSENSE\n// =======================================\n\ntemplate<typename T>\nauto find_min_quantum_entanglement(const T& min_sets) {\n\n\tusing ValueType = innermost_value_type_t<T>;\n\n\tauto min_value = std::numeric_limits<ValueType>::max();\n\n\tfor(const auto& min_set : min_sets) {\n\n\t\tconst auto begin = min_set.begin();\n\t\tconst auto end   = min_set.end();\n\t\tconst auto init  = ValueType{1};\n\t\tconst auto binop = std::multiplies{};\n\n\t\tconst auto new_value = std::accumulate(begin, end, init, binop);\n\n\t\tmin_value = std::min(min_value, new_value);\n\t}\n\n\treturn min_value;\n}\n\nint main() {\n\n\tconst auto filename = std::string{\"weights.txt\"};\n\tauto file = std::fstream{filename};\n\n\tif(file.is_open()) {\n\n\t\tauto weights = std::vector<std::uint64_t>{};\n\n\t\tusing NumericType = innermost_value_type_t<decltype(weights)>;\n\n\t\tusing stream_iterator = std::istream_iterator<NumericType>;\n\n\t\tconst auto begin = stream_iterator{file};\n\t\tconst auto end   = stream_iterator{};\n\t\tconst auto init  = NumericType{};\n\t\tconst auto binop = [&weights] (auto acc, auto weight) {\n\t\t\tweights.push_back(weight);\n\t\t\treturn (acc + weight);\n\t\t};\n\n\t\tconst auto total_weight = std::accumulate(begin, end, init, binop);\n\n\t\tconst auto n_groups = 3;\n\n\t\tconst auto sum_per_group = (total_weight / n_groups);\n\n\t\tstd::sort(weights.begin(), weights.end());\n\n\t\tconst auto subsets = find_subsets(weights, sum_per_group);\n\n\t\tconst auto min_sets = find_min_sets(subsets);\n\n\t\tstd::cout << find_min_quantum_entanglement(min_sets) << std::endl;\n\n\t} else {\n\t\tstd::cerr << \"Error! Could not open \\\"\" << filename << \"\\\"!\" << std::endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "738d3ab05573ef50c620f595257560fb75d110b4", "size": 7850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 24 Part 1/main.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 24 Part 1/main.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 24 Part 1/main.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7813765182, "max_line_length": 123, "alphanum_fraction": 0.6884076433, "num_tokens": 1969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.621627498751916}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n#include <map>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass NNActivations\n{\n\npublic:\n  enum class Activation { kLinear, kSigmoid, kReLU, kTanh };\n\n  using ArrayXXd = Eigen::ArrayXXd;\n  using ActivationsMap =\n      std::map<Activation, std::function<void(Eigen::Ref<Eigen::ArrayXXd>,\n                                              Eigen::Ref<Eigen::ArrayXXd>)>>;\n\n  static ActivationsMap& activation()\n  {\n    static ActivationsMap _funcs = {\n        {Activation::kLinear,\n         [](Eigen::Ref<Eigen::ArrayXXd> in, Eigen::Ref<Eigen::ArrayXXd> out) {\n           out = in;\n         }},\n        {Activation::kSigmoid,\n         [](Eigen::Ref<Eigen::ArrayXXd> in, Eigen::Ref<Eigen::ArrayXXd> out) {\n           out = 1 / (1 + (-in).exp());\n         }},\n        {Activation::kReLU,\n         [](Eigen::Ref<Eigen::ArrayXXd> in, Eigen::Ref<Eigen::ArrayXXd> out) {\n           out = in.max(0);\n         }},\n        {Activation::kTanh,\n         [](Eigen::Ref<Eigen::ArrayXXd> in, Eigen::Ref<Eigen::ArrayXXd> out) {\n           out = (in.exp() - (-in).exp()) / (in.exp() + (-in).exp());\n         }},\n    };\n    return _funcs;\n  }\n\n  // derivative from output of activation\n  static ActivationsMap& derivative()\n  {\n    static ActivationsMap _funcs = {\n        {Activation::kLinear,\n         [](Eigen::Ref<Eigen::ArrayXXd> in, Eigen::Ref<Eigen::ArrayXXd> out) {\n           out = ArrayXXd::Ones(in.rows(), in.cols());\n         }},\n        {Activation::kSigmoid,\n         [](Eigen::Ref<Eigen::ArrayXXd> in, Eigen::Ref<Eigen::ArrayXXd> out) {\n           out = in * (1 - in);\n         }},\n        {Activation::kReLU,\n         [](Eigen::Ref<Eigen::ArrayXXd> in, Eigen::Ref<Eigen::ArrayXXd> out) {\n           out = (in > 0).cast<double>();\n         }},\n        {Activation::kTanh,\n         [](Eigen::Ref<Eigen::ArrayXXd> in, Eigen::Ref<Eigen::ArrayXXd> out) {\n           out = 1 - in.square();\n         }}};\n    return _funcs;\n  }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "4e20d3dd8187cbac382dde489593690c06c0950c", "size": 2442, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/NNFuncs.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/util/NNFuncs.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/util/NNFuncs.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 30.525, "max_line_length": 78, "alphanum_fraction": 0.5831285831, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6215795238999955}}
{"text": "#include \"QSLIM.h\"\n\n#include <wmtk/TriMesh.h>\n#include <wmtk/utils/VectorUtils.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <wmtk/ExecutionScheduler.hpp>\n#include <wmtk/utils/TupleUtils.hpp>\n\nusing namespace wmtk;\nusing namespace qslim;\n\n// called in collapse_edge_after. update the quadric for v\n// adding the A, b , c for two vertices of the old edge and store at the vert_attr of new vertex\nvoid QSLIM::update_quadrics(const Tuple& new_v)\n{\n    vertex_attrs[new_v.vid(*this)].Q = {\n        cache.local().Q1.A + cache.local().Q2.A,\n        cache.local().Q1.b + cache.local().Q2.b,\n        cache.local().Q1.c + cache.local().Q2.c};\n}\n\n// want to store the A, b, c for each face as face attribute\nQuadrics QSLIM::compute_quadric_for_face(const TriMesh::Tuple& f_tuple)\n{\n    Quadrics Q;\n    Eigen::Vector3d n = face_attrs[f_tuple.fid(*this)].n;\n    Q.A = n * n.transpose();\n    double d = -n.dot(vertex_attrs[oriented_tri_vertices(f_tuple)[0].vid(*this)].pos);\n    Q.b = d * n;\n    Q.c = d * d;\n    return Q;\n}\ndouble QSLIM::compute_cost_for_e(const TriMesh::Tuple& v_tuple)\n{\n    // first get Q\n    Quadrics Q1 = vertex_attrs[v_tuple.vid(*this)].Q;\n    Quadrics Q2 = vertex_attrs[v_tuple.switch_vertex(*this).vid(*this)].Q;\n    Quadrics Q = {Q1.A + Q2.A, Q1.b + Q2.b, Q1.c + Q2.c};\n    double cost = 0.0;\n    Eigen::Vector3d vbar(0.0, 0.0, 0.0);\n    Eigen::Vector3d v1 = vertex_attrs[v_tuple.vid(*this)].pos;\n    Eigen::Vector3d v2 = vertex_attrs[v_tuple.switch_vertex(*this).vid(*this)].pos;\n\n    // test if A is invertible\n    // not invertible vbar is smallest of two vertices\n    // if A is invertible, compute vbar using A.inv@b\n    if (Q.A.determinant() < 1e-10 && Q.A.determinant() > -1e-10) {\n        // not invertible\n        if ((v1.transpose() * Q1.A * v1 + 2 * Q1.b.dot(v1) + Q1.c) <\n            (v2.transpose() * Q2.A * v2 + 2 * Q2.b.dot(v2) + Q2.c))\n            vbar = v1;\n        else\n            vbar = v2;\n\n    } else {\n        vbar = -Q.A.inverse() * Q.b;\n    }\n    cost = (vbar.dot(Q.A * vbar) + 2 * Q.b.dot(vbar) + Q.c);\n    // the cost has to greater than 0\n    if (cost < 0 && cost > -1e-15)\n        cost = 0; // floating point error\n    else if (cost < 0)\n        wmtk::logger().info(\n            \"cost is {} smaller than zero \\n Q.A is \\n{} \\nQ.b \\n{}\\n Q.c \\n {} \\nvbar is\\n{} \"\n            \" \",\n            cost,\n            Q.A,\n            Q.b,\n            Q.c,\n            vbar);\n    // wmtk::logger().info(\"cost is smaller than zero\");\n    edge_attrs[v_tuple.eid(*this)].vbar = vbar;\n    return cost;\n}\n\nbool QSLIM::invariants(const std::vector<Tuple>& new_tris)\n{\n    if (m_has_envelope) {\n        for (auto& t : new_tris) {\n            std::array<Eigen::Vector3d, 3> tris;\n            auto vs = t.oriented_tri_vertices(*this);\n            for (auto j = 0; j < 3; j++) tris[j] = vertex_attrs[vs[j].vid(*this)].pos;\n            if (m_envelope.is_outside(tris)) return false;\n        }\n    }\n    return true;\n}\n\nbool QSLIM::write_triangle_mesh(std::string path)\n{\n    Eigen::MatrixXd V = Eigen::MatrixXd::Zero(vert_capacity(), 3);\n    for (auto& t : get_vertices()) {\n        auto i = t.vid(*this);\n        V.row(i) = vertex_attrs[i].pos;\n    }\n\n    Eigen::MatrixXi F = Eigen::MatrixXi::Constant(tri_capacity(), 3, -1);\n    for (auto& t : get_faces()) {\n        auto i = t.fid(*this);\n        auto vs = oriented_tri_vertices(t);\n        for (int j = 0; j < 3; j++) {\n            F(i, j) = vs[j].vid(*this);\n        }\n    }\n\n    return igl::write_triangle_mesh(path, V, F);\n}\n\nbool QSLIM::collapse_edge_before(const Tuple& t)\n{\n    if (!ConcurrentTriMesh::collapse_edge_before(t)) return false;\n    if (vertex_attrs[t.vid(*this)].freeze || vertex_attrs[t.switch_vertex(*this).vid(*this)].freeze)\n        return false;\n    cache.local().v1p = vertex_attrs[t.vid(*this)].pos;\n    cache.local().v2p = vertex_attrs[t.switch_vertex(*this).vid(*this)].pos;\n    cache.local().Q1 = vertex_attrs[t.vid(*this)].Q;\n    cache.local().Q2 = vertex_attrs[t.switch_vertex(*this).vid(*this)].Q;\n    cache.local().vbar = edge_attrs[t.eid(*this)].vbar;\n    return true;\n}\n\n\nbool QSLIM::collapse_edge_after(const TriMesh::Tuple& t)\n{\n    auto vid = t.vid(*this);\n    vertex_attrs[vid].pos = cache.local().vbar;\n    // update the quadrics\n    update_quadrics(t);\n    return true;\n}\n\n\nstd::vector<TriMesh::Tuple> QSLIM::new_edges_after(const std::vector<TriMesh::Tuple>& tris) const\n{\n    std::vector<TriMesh::Tuple> new_edges;\n    std::vector<TriMesh::Tuple> one_ring_verts;\n    for (auto t : tris) {\n        auto incident_verts = t.oriented_tri_vertices(*this);\n        for (auto j = 0; j < 3; j++) one_ring_verts.push_back(incident_verts[j]);\n    }\n    for (auto v : one_ring_verts) {\n        auto incident_edges = get_one_ring_edges_for_vertex(v);\n        for (auto e : incident_edges) new_edges.push_back(e);\n    }\n    wmtk::unique_edge_tuples(*this, new_edges);\n    return new_edges;\n}\n\nbool QSLIM::collapse_qslim(int target_vert_number)\n{\n    auto collect_all_ops = std::vector<std::pair<std::string, Tuple>>();\n    int starting_num = get_vertices().size();\n    for (auto& loc : get_edges()) collect_all_ops.emplace_back(\"edge_collapse\", loc);\n\n    auto renew = [](auto& m, auto op, auto& tris) {\n        auto edges = m.new_edges_after(tris);\n        auto optup = std::vector<std::pair<std::string, Tuple>>();\n        for (auto& e : edges) optup.emplace_back(\"edge_collapse\", e);\n        return optup;\n    };\n    auto measure_priority = [this](auto& m, auto op, const Tuple& new_e) {\n        return -compute_cost_for_e(new_e);\n    };\n    auto setup_and_execute = [&](auto executor) {\n        executor.num_threads = NUM_THREADS;\n        executor.renew_neighbor_tuples = renew;\n        executor.priority = measure_priority;\n        executor.stopping_criterion_checking_frequency = std::numeric_limits<int>::max();\n        executor.stopping_criterion_checking_frequency = target_vert_number > 0\n                                                             ? starting_num - target_vert_number - 1\n                                                             : std::numeric_limits<int>::max();\n        executor.stopping_criterion = [](auto& m) { return true; };\n        executor.is_weight_up_to_date = [&collect_all_ops, this](auto& m, auto& ele) {\n            auto& [val, op, e] = ele;\n            //if (val > 0) return false; // priority is negated.\n            double pri = -compute_cost_for_e(e);\n            if (((val - pri) * (val - pri)) > 1e-8) {\n                wmtk::logger().info(\"the priority is different val is {}, pri is {}\", val, pri);\n                return false;\n            }\n            return true;\n        };\n        executor(*this, collect_all_ops);\n    };\n\n    if (NUM_THREADS > 0) {\n        auto executor = wmtk::ExecutePass<QSLIM, ExecutionPolicy::kPartition>();\n        executor.lock_vertices = [](auto& m, const auto& e, int task_id) {\n            return m.try_set_edge_mutex_two_ring(e, task_id);\n        };\n        setup_and_execute(executor);\n    } else {\n        auto executor = wmtk::ExecutePass<QSLIM, ExecutionPolicy::kSeq>();\n        setup_and_execute(executor);\n    }\n    return true;\n}", "meta": {"hexsha": "88247c43933694abe7df13c4d4c8a44a7ba9c56f", "size": 7148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/QSLIM/src/qslim/QSLIM.cpp", "max_stars_repo_name": "wildmeshing/wildmeshing-toolkit", "max_stars_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T08:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T00:19:41.000Z", "max_issues_repo_path": "app/QSLIM/src/qslim/QSLIM.cpp", "max_issues_repo_name": "wildmeshing/wildmeshing-toolkit", "max_issues_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86.0, "max_issues_repo_issues_event_min_datetime": "2021-12-03T01:46:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T19:33:17.000Z", "max_forks_repo_path": "app/QSLIM/src/qslim/QSLIM.cpp", "max_forks_repo_name": "wildmeshing/wildmeshing-toolkit", "max_forks_repo_head_hexsha": "7f4c60e5a6d366d9c3850b720b42b610e10600c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-26T08:29:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T22:10:42.000Z", "avg_line_length": 36.101010101, "max_line_length": 100, "alphanum_fraction": 0.5966703973, "num_tokens": 2031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6215795234882037}}
{"text": "\ufeff// MLpackTest.cpp : \u6b64\u6587\u4ef6\u5305\u542b \"main\" \u51fd\u6570\u3002\u7a0b\u5e8f\u6267\u884c\u5c06\u5728\u6b64\u5904\u5f00\u59cb\u5e76\u7ed3\u675f\u3002\n//\n\n#include <iostream>\n#include <armadillo>\n#include <mlpack/core.hpp>\n\n#include \"mlpack/methods/random_forest/random_forest.hpp\"\n#include \"mlpack/methods/decision_tree/random_dimension_select.hpp\"\n#include \"mlpack/methods/adaboost/adaboost.hpp\"\n\n#include <mlpack/core/hpt/hpt.hpp>\n#include <mlpack/core/cv/k_fold_cv.hpp>\n#include <mlpack/core/cv/metrics/accuracy.hpp>\n#include <mlpack/core/cv/metrics/precision.hpp>\n#include <mlpack/core/cv/metrics/recall.hpp>\n#include <mlpack/core/cv/metrics/F1.hpp>\n\nusing namespace mlpack;\nusing namespace mlpack::tree;\nusing namespace mlpack::cv;\nusing namespace mlpack::hpt;\n\n\n\nint main()\n{\n\tstd::string msg = \"\";\n\tarma::mat dataset;\n\tbool loaded = mlpack::data::Load(\"data.csv\", dataset);\n\tif (!loaded) {\n\t\tstd::cout << \"Load data file failed\\n\";\n\t}\n\telse {\n\t\t/*msg += \"Load data file successfully\\n\";\n\t\tmsg += \"Get DATA \" + std::to_string(dataset.n_rows) + \" X \" + std::to_string(dataset.n_cols) + \"\\n\";\n\t\tarma::Row<size_t> labels;\n\t\tlabels = arma::conv_to<arma::Row<size_t>>::from(dataset.row(dataset.n_rows - 1));\n\t\tdataset.shed_row(dataset.n_rows - 1);*/\n\n\t\t//model selection\n\t\t/*RandomForest<GiniGain, RandomDimensionSelect> rf;\n\t\trf = RandomForest<GiniGain, RandomDimensionSelect>(dataset, labels, 3, 30);*/\n\n\t\t/*const size_t k = 15;\n\t\n\n\t\tKFoldCV<RandomForest<GiniGain, RandomDimensionSelect>, Accuracy> cv_rf_clf(k,dataset, labels, 3, true);\n\t\tdouble cvAcc_1 = cv_rf_clf.Evaluate(40, 1, 1e-6, 9);\n\t\tauto rf_1 = cv_rf_clf.Model();\n\t\tarma::Row<size_t> predictions_1;\n\t\trf_1.Classify(dataset, predictions_1);\n\t\tdouble cvPrecision_1 = Precision<Binary>::Evaluate(rf_1, dataset, labels);\n\t\tdouble cvRecall_1 = Recall<Binary>::Evaluate(rf_1, dataset, labels);\n\t\tdouble cvF1_1 = F1<Binary>::Evaluate(rf_1, dataset, labels);\n\n\t\tconst size_t correct_1 = arma::accu(predictions_1 == labels);\n\t\tmsg += \"\\nRandom Forest:\";\n\t\tmsg += \"\\nTraining Accuracy: \" + std::to_string((double(correct_1) / double(labels.n_elem)));\n\t\tmsg += \"\\nKFoldCV Accuracy: \" + std::to_string(cvAcc_1);\n\t\tmsg += \"\\nPrecision: \" + std::to_string(cvPrecision_1);\n\t\tmsg += \"\\nRecall: \" + std::to_string(cvRecall_1);\n\t\tmsg += \"\\nF1: \" + std::to_string(cvF1_1);\n\t\tstd::cout << msg;*/\n\n\t\t/*HyperParameterTuner<RandomForest<GiniGain, RandomDimensionSelect>, Accuracy, KFoldCV> hpt_rf(k, dataset, labels, 3, true);\n\t\tarma::vec numTreesSet = { 5, 7, 10};\n\t\tarma::vec minimumLeafSizeSet = { 1,2,3 };\n\t\tarma::vec minimumGainSplitSet = { 1e-5, 1e-3, 1e-2};\n\t\tarma::vec maximumDepthSet = { 3,4,5 };\n\t\tdouble a,b,c,d;\n\t\tstd::tie(a, b, c, d) = hpt_rf.Optimize(numTreesSet, minimumLeafSizeSet, minimumGainSplitSet, maximumDepthSet);\n\t\tstd::cout << a << b << c << d;*/\n\n\t\t//\n\t\t///*adaboost::AdaBoost<DecisionStump<>> adaclf;\n\t\t//adaclf = adaboost::AdaBoost<DecisionStump<>>(dataset, labels, 3, wl_1);*/\n\t\t/*DecisionStump<> wl_1;\n\t\tmsg = \"\\nAdaboost-DecisionStump:\";\n\t\tKFoldCV<adaboost::AdaBoost<DecisionStump<>>, Accuracy> cv_ada_clf(k, dataset, labels, 3, true);\n\t\tdouble cvAcc_2 = cv_ada_clf.Evaluate(wl_1, 25, 1e-2);\n\t\tauto rf_2 = cv_ada_clf.Model();\n\t\tarma::Row<size_t> predictions_2;\n\t\trf_2.Classify(dataset, predictions_2);\n\t\tdouble cvPrecision_2 = Precision<Binary>::Evaluate(rf_2, dataset, labels);\n\t\tdouble cvRecall_2 = Recall<Binary>::Evaluate(rf_2, dataset, labels);\n\t\tdouble cvF1_2 = F1<Binary>::Evaluate(rf_2, dataset, labels);\n\n\t\tconst size_t correct_2 = arma::accu(predictions_2 == labels);\n\t\tmsg += \"\\nTraining Accuracy: \" + std::to_string((double(correct_2) / double(labels.n_elem)));\n\t\tmsg += \"\\nKFoldCV Accuracy: \" + std::to_string(cvAcc_2);\n\t\tmsg += \"\\nPrecision: \" + std::to_string(cvPrecision_2);\n\t\tmsg += \"\\nRecall: \" + std::to_string(cvRecall_2);\n\t\tmsg += \"\\nF1: \" + std::to_string(cvF1_2);\n\t\tstd::cout << msg;*/\n\n\t\t/*DecisionStump<> wl_1;\n\t\tHyperParameterTuner<adaboost::AdaBoost<DecisionStump<>>, Accuracy, KFoldCV> hpt_ada_ds(k, dataset, labels, 3, true);\n\t\tarma::vec iterationsSet{5, 10, 15, 20, 30, 40, 50};\n\t\tarma::vec toleranceSet{1, 0.1, 0.01, 0.001, 0.0001};\n\t\tdouble bestIterations, bestTolerance;\n\t\tstd::tie(bestIterations, bestTolerance) = hpt_ada_ds.Optimize(Fixed(wl_1), iterationsSet, toleranceSet);\n\t\tstd::cout << \"bestIterations: \" << bestIterations << \"\\n\" << \"bestTolerance: \" << bestTolerance;*/\n\n\t\t/*const size_t correct = arma::accu(predictions == labels);\n\t\tmsg += \"\\nTraining Accuracy: \" + std::to_string((double(correct_2) / double(labels.n_elem)));\n\t\tmsg += \"\\nKFoldCV Accuracy: \" + std::to_string(cvAcc_2);\n\t\tmsg += \"\\nPrecision: \" + std::to_string(cvPrecision_2);\n\t\tmsg += \"\\nRecall: \" + std::to_string(cvRecall_2);\n\t\tmsg += \"\\nF1: \" + std::to_string(cvF1_2);\n\t\tstd::cout << msg;*/\n\n\t\t///*init mlpack adaboost type\n\t\t//adaboost::AdaBoost<Perceptron<>> adaclf;\n\t\t//adaclf = adaboost::AdaBoost<>(dataset, labels, 3, wl_1);*/\n\t\t/*perceptron::Perceptron<> wl_2;\n\t\tmsg = \"\\nAdaboost-Perceptron:\";\n\t\tKFoldCV<adaboost::AdaBoost<>, Accuracy> cv_ada_P_clf(k, dataset, labels, 3, true);\n\t\tdouble cvAcc_3 = cv_ada_P_clf.Evaluate(wl_2);\n\t\tauto rf_3 = cv_ada_P_clf.Model();\n\t\tarma::Row<size_t> predictions_3;\n\t\trf_3.Classify(dataset, predictions_3);\n\t\tdouble cvPrecision_3 = Precision<Binary>::Evaluate(rf_3, dataset, labels);\n\t\tdouble cvRecall_3 = Recall<Binary>::Evaluate(rf_3, dataset, labels);\n\t\tdouble cvF1_3 = F1<Binary>::Evaluate(rf_3, dataset, labels);\n\n\t\tconst size_t correct_3 = arma::accu(predictions_3 == labels);\n\t\tmsg += \"\\nTraining Accuracy: \" + std::to_string((double(correct_3) / double(labels.n_elem)));\n\t\tmsg += \"\\nKFoldCV Accuracy: \" + std::to_string(cvAcc_3);\n\t\tmsg += \"\\nPrecision: \" + std::to_string(cvPrecision_3);\n\t\tmsg += \"\\nRecall: \" + std::to_string(cvRecall_3);\n\t\tmsg += \"\\nF1: \" + std::to_string(cvF1_3);\n\t\tstd::cout << msg;*/\n\n\n\t\t\n\t\t///*DecisionTree<> dtclf;\n\t\t//dtclf = DecisionTree<>(dataset, labels, 3);*/\n\t\t/*msg = \"\\nDecision Tree:\";\n\t\tAllDimensionSelect tempSelect = AllDimensionSelect();\n\t\tKFoldCV<DecisionTree<>, Accuracy> cv_dt_clf(k, dataset, labels, 3, true);\n\t\tdouble cvAcc_4 = cv_dt_clf.Evaluate(9, 1e-5, 3, tempSelect);\n\t\tauto rf_4 = cv_dt_clf.Model();\n\t\tarma::Row<size_t> predictions_4;\n\t\trf_4.Classify(dataset, predictions_4);\n\t\tdouble cvPrecision_4 = Precision<Binary>::Evaluate(rf_4, dataset, labels);\n\t\tdouble cvRecall_4 = Recall<Binary>::Evaluate(rf_4, dataset, labels);\n\t\tdouble cvF1_4 = F1<Binary>::Evaluate(rf_4, dataset, labels);\n\n\t\tconst size_t correct_4 = arma::accu(predictions_4 == labels);\n\t\tmsg += \"\\nTraining Accuracy: \" + std::to_string((double(correct_4) / double(labels.n_elem)));\n\t\tmsg += \"\\nKFoldCV Accuracy: \" + std::to_string(cvAcc_4);\n\t\tmsg += \"\\nPrecision: \" + std::to_string(cvPrecision_4);\n\t\tmsg += \"\\nRecall: \" + std::to_string(cvRecall_4);\n\t\tmsg += \"\\nF1: \" + std::to_string(cvF1_4);\n\t\tstd::cout << msg;*/\n\n\t\t/*HyperParameterTuner<DecisionTree<>, Accuracy, KFoldCV> hpt_dt(k, dataset, labels, 3, true);\n\t\tarma::vec minLeafSet{3, 6, 9};\n\t\tarma::vec minSpitSet{0.0001, 0.00001, 0.000001, 0.0000001};\n\t\tarma::vec maxDepthSet{2, 3, 4, 5};\n\t\tAllDimensionSelect tempSelect = AllDimensionSelect();\n\t\tdouble BestminLeafSet, BestminSpitSet, BestmaxDepthSet;\n\t\tstd::tie(BestminLeafSet, BestminSpitSet, BestmaxDepthSet) = hpt_dt.Optimize(minLeafSet, minSpitSet, maxDepthSet, Fixed(tempSelect));\n\t\tstd::cout << BestminLeafSet << \",\" << BestminSpitSet <<\",\"<< BestmaxDepthSet;\n\t\t//BestminLeafSet << 9 << BestminSpitSet << 0.0001 << BestmaxDepthSet << 5;\n\t\t*/\n\n\t\t/*const size_t correct = arma::accu(predictions == labels);\n\t\tmsg += \"\\nTraining Accuracy: \" + std::to_string((double(correct_2) / double(labels.n_elem)));\n\t\tmsg += \"\\nKFoldCV Accuracy: \" + std::to_string(cvAcc_2);\n\t\tmsg += \"\\nPrecision: \" + std::to_string(cvPrecision_2);\n\t\tmsg += \"\\nRecall: \" + std::to_string(cvRecall_2);\n\t\tmsg += \"\\nF1: \" + std::to_string(cvF1_2);\n\t\tstd::cout << msg;\n\t\t\n\t\t/*adaboost::AdaBoost<DecisionTree<>> adaclf;\n\t\tdtclf = DecisionTree<>(dataset, labels, 3);*/\n\t\t/*DecisionTree<> wl_3;\n\t\tmsg = \"\\nAdaboost-DecisionTree:\";\n\t\tKFoldCV<adaboost::AdaBoost<DecisionTree<>>, Accuracy> cv_ada_dt_clf(k, dataset, labels, 3, true);\n\t\tdouble cvAcc_5 = cv_ada_dt_clf.Evaluate(wl_3);\n\t\tauto rf_5 = cv_ada_dt_clf.Model();\n\t\tarma::Row<size_t> predictions_5;\n\t\trf_5.Classify(dataset, predictions_5);\n\t\tdouble cvPrecision_5 = Precision<Binary>::Evaluate(rf_5, dataset, labels);\n\t\tdouble cvRecall_5 = Recall<Binary>::Evaluate(rf_5, dataset, labels);\n\t\tdouble cvF1_5 = F1<Binary>::Evaluate(rf_5, dataset, labels);\n\n\t\tconst size_t correct_5 = arma::accu(predictions_5 == labels);\n\t\tmsg += \"\\nTraining Accuracy: \" + std::to_string((double(correct_5) / double(labels.n_elem)));\n\t\tmsg += \"\\nKFoldCV Accuracy: \" + std::to_string(cvAcc_5);\n\t\tmsg += \"\\nPrecision: \" + std::to_string(cvPrecision_5);\n\t\tmsg += \"\\nRecall: \" + std::to_string(cvRecall_5);\n\t\tmsg += \"\\nF1: \" + std::to_string(cvF1_5);\n\t\tstd::cout << msg;*/\n\n\n\t\t//mlpack::data::Save<adaboost::AdaBoost<DecisionStump<>>>(\"AdaModel.xml\", \"AdaModel\", rf_2);\n\t\t//mlpack::data::Save<RandomForest<GiniGain, RandomDimensionSelect>>(\"RFModel.xml\", \"RFModel\", rf_1);\n\t\n\t\tRandomForest<GiniGain, RandomDimensionSelect> clf;\n\t\tmlpack::data::Load(\"RFModel.xml\", \"RFModel\", clf);\n\t\tmsg = \"Reload it : \";\n\t\t/*double cvPrecision2 = Precision<Binary>::Evaluate(clf, dataset, labels);\n\t\tmsg += \"\\nPrecision: \" + std::to_string(cvPrecision2);\n\t\tdouble cvRecall2 = Recall<Binary>::Evaluate(clf, dataset, labels);\n\t\tmsg += \"\\nRecall: \" + std::to_string(cvRecall2);\n\t\tdouble cvF12 = F1<Binary>::Evaluate(clf, dataset, labels);\n\t\tmsg += \"\\nF1: \" + std::to_string(cvF12);*/\n\t\tstd::cout << msg;\n\t\tarma::mat sample(\"94.0458,0.281167,1.02107,0.00181479,0.122677,0.00073466,-18.2187,12.0354,-8.20159,347,162,316,\"\n\t\t\t\"265,405,151,380,140,316,129,265,136,425,254,566,312,390,349,201,266,3,311,168,348\");\n\t\tarma::mat probabilities;\n\t\tarma::Row<size_t> predictions;\n\t\tclf.Classify(sample, predictions, probabilities);\n\t\t//arma::u64 result = predictions.at(0);\n\t\t//std::cout << \"\\nClassification result: \" << predictions << \"\\n\" << \"Probabilities: \" <<arma::mean(probabilities.t());\n\t\tarma::Mat<double> result = arma::mean(probabilities.t());\n\t\tstd::cout << typeid(result[0]).name() << std::endl;\n\t\tstd::cout << result.at(1) << std::endl;\n\t\tstd::cout << result.at(2) << std::endl;\n\t}\n}\n\n", "meta": {"hexsha": "795140f1a6aebf2464efe117cead8b8501e7257f", "size": 10224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/MLpackTrain/MLpackTest.cpp", "max_stars_repo_name": "ICEJM1020/MeetingSpy", "max_stars_repo_head_hexsha": "789f5edad6a94a332846e4ed785dcc72713a8d78", "max_stars_repo_licenses": ["MIT"], "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/MLpackTrain/MLpackTest.cpp", "max_issues_repo_name": "ICEJM1020/MeetingSpy", "max_issues_repo_head_hexsha": "789f5edad6a94a332846e4ed785dcc72713a8d78", "max_issues_repo_licenses": ["MIT"], "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/MLpackTrain/MLpackTest.cpp", "max_forks_repo_name": "ICEJM1020/MeetingSpy", "max_forks_repo_head_hexsha": "789f5edad6a94a332846e4ed785dcc72713a8d78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2389380531, "max_line_length": 134, "alphanum_fraction": 0.6879890454, "num_tokens": 3443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267728417086, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6215795214700752}}
{"text": "/***************************************************************************\n/* Javier Juan Albarracin - jajuaal1@ibime.upv.es                         */\n/* Universidad Politecnica de Valencia, Spain                             */\n/*                                                                        */\n/* Copyright (C) 2018 Javier Juan Albarracin                              */\n/*                                                                        */\n/***************************************************************************\n* Classic image feature extraction algorithms                              *\n***************************************************************************/\n\n#define cimg_display 0\n#include <CImg.h>\n#include <CImgMATLAB.hpp>\n#include <EigenMATLAB.hpp>\n#include <ScalarMATLAB.hpp>\n#include <STDMATLAB.hpp>\n#include <vector>\n#include <cmath>\n#include <omp.h>\n\n#define INF 1e+300\n\nusing namespace cimg_library;\n\n\nclass ImageFeatureExtraction\n{\npublic:\n\ttemplate<typename T>\n\tstatic CImg<double> FirstOrderCentralMoments(const CImg<T> &image, const CImg<bool> &mask, const std::vector<int> &radius);\n\ttemplate<typename T>\n\tstatic CImg<double> LocalMedianMAD(const CImg<T> &image, const CImg<bool> &mask, const std::vector<int> &radius);\n\ttemplate<typename T>\n\tstatic CImg<double> LocalEnergy(const CImg<T> &image, const CImg<bool> &mask, const std::vector<int> &radius);\n\ttemplate<typename T>\n\tstatic CImg<double> LocalEntropy(const CImg<T> &image, const CImg<bool> &mask, const std::vector<int> &radius, const int nbins);\n}\n\ntemplate<typename T>\nCImg<double> ImageFeatureExtraction::FirstOrderCentralMoments(const CImg<T> &image, const CImg<bool> &mask, const std::vector<int> &radius)\n{\n\tCImg<double> F(image.width(), image.height(), image.depth(), 7);\n\t\n    #pragma omp parallel for\n\tfor (int x = 0; x < image.width(); ++x)\n\t{\n\t\tfor (int y = 0; y < image.height(); ++y)\n\t\t{\n\t\t\tfor (int z = 0; z < image.depth(); ++z)\n\t\t\t{\n\t\t\t\tfor (int f = 0; f < 7; ++f)\n\t\t\t\t\tF(x, y, z, f) = 0;\n\t\t\t\t\n\t\t\t\tif (!mask(x, y, z))\t\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\t// Local Mean\n\t\t\t\tint n = 0;\n\t\t\t\tdouble mu = 0;\n\t\t\t\tfor (int xx = -radius[0]; xx <= radius[0]; ++xx)\n\t\t\t\t{\n\t\t\t\t\tconst int xr = x + xx;\n\t\t\t\t\tif (xr < 0 || xr >= image.width())\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\n\t\t\t\t\tfor (int yy = -radius[1]; yy <= radius[1]; ++yy)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst int yr = y + yy;\n\t\t\t\t\t\tif (yr < 0 || yr >= image.height())\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tfor (int zz = -radius[2]; zz <= radius[2]; ++zz)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst int zr = z + zz;\n\t\t\t\t\t\t\tif (zr < 0 || zr >= image.depth())\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (!mask(xr, yr, zr))\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tmu += image(xr, yr, zr);\n\t\t\t\t\t\t\t++n;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmu = n == 0 ? image(x, y, z) : mu / (double) n;\n\t\t\t\t\n\t\t\t\t// Variance, Skewness, Kurtosis, Energy0, Energy1\n\t\t\t\tn = 0;\n\t\t\t\tdouble var = 0;\n\t\t\t\tdouble skw = 0;\n\t\t\t\tdouble krt = 0;\n\t\t\t\tdouble energy0 = 0;\n\t\t\t\tdouble energy1 = 0;\n\t\t\t\tdouble max = -INF;\n\t\t\t\tdouble min = INF;\n\t\t\t\tfor (int xx = -radius[0]; xx <= radius[0]; ++xx)\n\t\t\t\t{\n\t\t\t\t\tconst int xr = x + xx;\n\t\t\t\t\tif (xr < 0 || xr >= image.width())\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\n\t\t\t\t\tfor (int yy = -radius[1]; yy <= radius[1]; ++yy)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst int yr = y + yy;\n\t\t\t\t\t\tif (yr < 0 || yr >= image.height())\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (int zz = -radius[2]; zz <= radius[2]; ++zz)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst int zr = z + zz;\n\t\t\t\t\t\t\tif (zr < 0 || zr >= image.depth())\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (!mask(xr, yr, zr))\n\t\t\t\t\t\t\t\tcontinue;\n\t\n\t\t\t\t\t\t\tconst double value = image(xr, yr, zr);\n\t\t\t\t\t\t\tconst double diff = value - mu;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar += (diff * diff);\n                            skw += (diff * diff * diff);\n                            krt += (diff * diff * diff * diff);\n\t\t\t\t\t\t\tenergy0 += (value * value);\n\t\t\t\t\t\t\tenergy1 += value;\n\t\t\t\t\t\t\tmax = value > max ? value : max;\n\t\t\t\t\t\t\tmin = value < min ? value : min;\n\t\t\t\t\t\t\t++n;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tF(x, y, z, 0) = mu;\n\t\t\t\tF(x, y, z, 1) = n <= 1 ? 0 : var / (double) (n - 1);\n\t\t\t\tF(x, y, z, 2) = n <= 0 || var == 0 ? 0 : (skw / (double) n) / pow(var / (double) n, 1.5);\n\t\t\t\tF(x, y, z, 3) = n <= 0 || var == 0 ? 0 : ((krt / (double) n) / pow(var / (double) n, 2)) - 3;\n\t\t\t\tF(x, y, z, 4) = n == 0 ? 0 : energy0 / (double) n;\n\t\t\t\tF(x, y, z, 5) = n == 0 ? 0 : (energy1 * energy1) / (double) (n * n);\n\t\t\t\tF(x, y, z, 6) = max - min;\n\t\t\t}\n\t\t}\n\t}\n\treturn F;\n}\n\ntemplate<typename T>\nCImg<double> ImageFeatureExtraction::LocalEntropy(const CImg<T> &image, const CImg<bool> &mask, const std::vector<int> &radius, const int nbins)\n{\n\tCImg<double> F(image.width(), image.height(), image.depth());\n\tconst double ratio = 256 / (double) nbins;\n\t\n\t#pragma omp parallel for\n\tfor (int x = 0; x < image.width(); ++x)\n\t{\n\t\tfor (int y = 0; y < image.height(); ++y)\n\t\t{\n\t\t\tfor (int z = 0; z < image.depth(); ++z)\n\t\t\t{\n\t\t\t\tF(x, y, z) = 0;\n\t\t\t\t\n\t\t\t\tif (!mask(x, y, z))\t\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tint n = 0;\n\t\t\t\tstd::vector<int> bins(nbins, 0);\n\t\t\t\tfor (int xx = -radius[0]; xx <= radius[0]; ++xx)\n\t\t\t\t{\n\t\t\t\t\tconst int xr = x + xx;\n\t\t\t\t\tif (xr < 0 || xr >= image.width())\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\n\t\t\t\t\tfor (int yy = -radius[1]; yy <= radius[1]; ++yy)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst int yr = y + yy;\n\t\t\t\t\t\tif (yr < 0 || yr >= image.height())\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (int zz = -radius[2]; zz <= radius[2]; ++zz)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst int zr = z + zz;\n\t\t\t\t\t\t\tif (zr < 0 || zr >= image.depth())\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (!mask(xr, yr, zr))\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tbins[std::floor((double) image(xr, yr, zr) / ratio)]++;\n\t\t\t\t\t\t\tn++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (n == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tdouble H = 0;\n\t\t\t\tfor (int i = 0; i < nbins; i++)\n\t\t\t\t{\n\t\t\t\t\tconst double p = bins[i] / (double) n;\n\t\t\t\t\tif (p > 0)\n\t\t\t\t\t\tH += p * log(p);\n\t\t\t\t}\n\t\t\t\tF(x, y, z) = -H;\n\t\t\t}\n\t\t}\n\t}\n\treturn F;\n}\n\ntemplate<typename T>\nCImg<double> ImageFeatureExtraction::LocalMedianMAD(const CImg<T> &image, const CImg<bool> &mask, const std::vector<int> &radius)\n{\n\tconst int N = (2 * radius[0] + 1) * (2 * radius[1] + 1) * (2 * radius[2] + 1);\n\tconst int mid = (int) std::floor((double) N / 2.0);\n\t\n\tCImg<double> F(image.width(), image.height(), image.depth(), 2);\n\t\t\n\t#pragma omp parallel for\n\tfor (int x = 0; x < image.width(); ++x)\n\t{\n\t\tfor (int y = 0; y < image.height(); ++y)\n\t\t{\n\t\t\tfor (int z = 0; z < image.depth(); ++z)\n\t\t\t{\n\t\t\t\tF(x, y, z, 0) = 0;\n\t\t\t\tF(x, y, z, 1) = 0;\n\t\t\t\t\n\t\t\t\tif (!mask(x, y, z))\t\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tstd::vector<double> patch;\n\t\t\t\tfor (int xx = -radius[0]; xx <= radius[0]; ++xx)\n\t\t\t\t{\n\t\t\t\t\tconst int xr = x + xx;\n\t\t\t\t\tif (xr < 0 || xr >= image.width())\n\t\t\t\t\t{\n\t\t\t\t\t\tpatch.push_back(image(x, y, z));\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tfor (int yy = -radius[1]; yy <= radius[1]; ++yy)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst int yr = y + yy;\n\t\t\t\t\t\tif (yr < 0 || yr >= image.height())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpatch.push_back(image(x, y, z));\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (int zz = -radius[2]; zz <= radius[2]; ++zz)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst int zr = z + zz;\n\t\t\t\t\t\t\tif (zr < 0 || zr >= image.depth())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tpatch.push_back(image(x, y, z));\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tpatch.push_back(image(xr, yr, zr));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Sort data and get median value\n\t\t\t\tstd::sort(patch.begin(), patch.end());\n\t\t\t\tdouble median = patch[mid];\n\t\t\t\tF(x, y, z, 0) = median;\n\t\t\t\t\n\t\t\t\t// Compute MAD\n\t\t\t\tstd::vector<double> residues;\n\t\t\t\tfor (int l = 0; l < N; l++)\n\t\t\t\t\tresidues.push_back(std::abs(patch[l] - median));\n\t\t\t\t\n\t\t\t\t// Sort data and get median value\n\t\t\t\tstd::sort(residues.begin(), residues.end());\n\t\t\t\tF(x, y, z, 1) = residues[mid];\n\t\t\t}\n\t\t}\n\t}\n\treturn F;\n}\n", "meta": {"hexsha": "55d2a78a5dce5c4a2c7ac13579e647b77329c8c0", "size": 7564, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ImageFeatureExtraction.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": "ImageFeatureExtraction.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": "ImageFeatureExtraction.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": 27.1111111111, "max_line_length": 144, "alphanum_fraction": 0.4707826547, "num_tokens": 2382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6215795113386029}}
{"text": "/******************************************************************************\r\nCreated By : Zhang Zhimin\r\nCreated On : 2012/11/22\r\nPurpose    :  \r\n********************************************************************************/\r\n\r\n#pragma once\r\n\r\n#include <skynet/config.hpp>\r\n#include <skynet/utility/math.hpp>\r\n#include <skynet/utility/serialization.hpp>\r\n#include <skynet/utility/eigen_lib.hpp>\r\n\r\n#include <Eigen/Core>\r\n#include <Eigen/LU>\r\n\r\nnamespace skynet{namespace statistics{\r\n\r\n\r\n\ttemplate <typename T>\r\n\tclass gauss_function;\r\n\r\n\t//template <typename T>\r\n\ttemplate <>\r\n\tclass gauss_function<float> : public unary_function<float, float>{\r\n\t\tstatic_assert(std::is_floating_point<float>::value, \"the normal function template T should be float point type.\");\r\n\tpublic:\r\n\t\ttypedef float\t\t\tvalue_type;\r\n\t\ttypedef value_type\t\tpoint_type;\r\n\r\n\t\tgauss_function() {}\r\n\r\n\t\tgauss_function(value_type mean, value_type sigma): m_mean(mean), m_sigma(sigma) {\r\n\t\t\tinit();\r\n\t\t}\r\n\r\n\t\tvoid mean(value_type mean)\t\t\t{ m_mean = mean; init(); }\r\n\t\tvalue_type mean() const\t\t\t\t{ return m_mean; }\r\n\t\tvoid sigma(value_type sigma)\t\t{ m_sigma = sigma; init(); }\r\n\t\tvalue_type sigma() const\t\t\t{ return m_sigma; }\r\n\t\tvoid covariance(value_type cov)\t\t{ m_sigma = sqrt(cov); init(); }\r\n\t\tvalue_type covariance() const\t\t{ return sqr(m_sigma); }\r\n\r\n\t\tvalue_type operator()(const value_type & x) const{\r\n\t\t\treturn\texp(-sqr(x-m_mean)/m_2sqr_sigma) / m_sigma_sqrt_2pi;\r\n\t\t}\r\n\r\n\t\ttemplate <typename Archive>\r\n\t\tvoid serialize(Archive &ar, unsigned int){\r\n\t\t\tar & boost::serialization::make_nvp(\"mean\", m_mean);\r\n\t\t\tar & boost::serialization::make_nvp(\"sigma\", m_sigma);\r\n\r\n\t\t\tinit();\r\n\t\t}\r\n\r\n\tprotected:\r\n\t\tvoid init() {\r\n\t\t\tm_sigma_sqrt_2pi = m_sigma * sqrt(2 * PI);\r\n\t\t\tm_2sqr_sigma = 2 * sqr(m_sigma);\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tvalue_type\t\tm_mean;\r\n\t\tvalue_type\t\tm_sigma;\r\n\r\n\t\tvalue_type\t\tm_sigma_sqrt_2pi;\r\n\t\tvalue_type\t\tm_2sqr_sigma;\r\n\t};\r\n\r\n\ttemplate <>\r\n\tclass gauss_function<double> : public unary_function<double, double>{\r\n\t\tstatic_assert(std::is_floating_point<double>::value, \"the normal function template T should be double point type.\");\r\n\tpublic:\r\n\t\ttypedef double\t\t\tvalue_type;\r\n\t\ttypedef value_type\t\tpoint_type;\r\n\r\n\t\tgauss_function(value_type mean, value_type sigma): m_mean(mean), m_sigma(sigma) {\r\n\t\t\tinit();\r\n\t\t}\r\n\r\n\t\tvoid mean(value_type mean)\t\t\t{ m_mean = mean; init(); }\r\n\t\tvalue_type mean() const\t\t\t\t{ return m_mean; }\r\n\t\tvoid sigma(value_type sigma)\t\t{ m_sigma = sigma; init(); }\r\n\t\tvalue_type sigma() const\t\t\t{ return m_sigma; }\r\n\t\tvalue_type covariance() const\t\t{ return sqr(m_sigma); }\r\n\r\n\r\n\r\n\t\tvalue_type operator()(const value_type & x) const{\r\n\t\t\treturn\texp(-sqr(x-m_mean)/m_2sqr_sigma) / m_sigma_sqrt_2pi;\r\n\t\t}\r\n\r\n\tprotected:\r\n\t\tvoid init() {\r\n\t\t\tm_sigma_sqrt_2pi = m_sigma * sqrt(2 * PI);\r\n\t\t\tm_2sqr_sigma = 2 * sqr(m_sigma);\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tvalue_type\t\tm_mean;\r\n\t\tvalue_type\t\tm_sigma;\r\n\r\n\t\tvalue_type\t\tm_sigma_sqrt_2pi;\r\n\t\tvalue_type\t\tm_2sqr_sigma;\r\n\t};\r\n\r\n\ttemplate <>\r\n\tclass gauss_function<Eigen::VectorXd> : public std::unary_function<Eigen::VectorXd, double>{\r\n\tpublic:\r\n\t\ttypedef Eigen::VectorXd\t\t\tvalue_type;\r\n\t\ttypedef Eigen::MatrixXd\t\t\tmatrix_type;\r\n\r\n\t\tgauss_function(){}\r\n\r\n\t\tgauss_function(const gauss_function & g): m_mean(g.m_mean), m_covariance(g.m_covariance), m_inv_cov(g.m_inv_cov), m_scale(g.m_scale){}\r\n\r\n\t\tvoid attach(matrix_type  feature_matrix){\r\n\t\t\tm_mean.resize(feature_matrix.rows());\r\n\t\t\tm_mean.setZero();\r\n\t\t\tfor (int i = 0; i < feature_matrix.cols(); ++i){\r\n\t\t\t\tm_mean += feature_matrix.col(i);\r\n\t\t\t}\r\n\r\n\t\t\tm_mean /= feature_matrix.cols();\r\n\r\n\t\t\tfor (int i = 0; i < feature_matrix.cols(); ++i){\r\n\t\t\t\tfeature_matrix.col(i) -= m_mean;\r\n\t\t\t}\r\n\r\n\t\t\tm_covariance = feature_matrix * feature_matrix.transpose();\r\n\t\t\tm_covariance /= feature_matrix.cols();\r\n\t\t\tm_inv_cov = m_covariance.inverse();\r\n\r\n\t\t\tm_scale = sqrt(m_covariance.determinant()) * sqrt(std::pow((2*PI), m_mean.rows()));\r\n\t\t}\r\n\r\n\t\tresult_type\t operator()(const argument_type &x) const{\r\n\t\t\tauto x_sub_mean = x - m_mean;\r\n\t\t\tauto dis = -0.5 * (x_sub_mean.transpose() * m_inv_cov * x_sub_mean);\r\n\t\t\tdouble dis_d = dis.value();\r\n\t\t\treturn std::exp(dis_d)/m_scale;\r\n\t\t}\r\n\r\n\t\tvoid mean(const value_type &mean)\t\t{ m_mean = mean; }\r\n\t\tvalue_type mean() const\t\t\t\t\t{ return m_mean; }\r\n\r\n\t\ttemplate <typename Archive>\r\n\t\tvoid serialize(Archive &ar, const unsigned int &){\r\n\t\t\t ar & boost::serialization::make_nvp(\"mean_feature\", m_mean);\r\n\t\t\t ar & boost::serialization::make_nvp(\"covariance\", m_covariance);\r\n\t\t\t ar & boost::serialization::make_nvp(\"inv_covariance\", m_inv_cov);\r\n\t\t\t ar & boost::serialization::make_nvp(\"scale\", m_scale);\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tvalue_type\t\t\t\t\t\tm_mean;\r\n\r\n\t\tmatrix_type\t\t\t\t\t\tm_covariance;\t\r\n\t\tmatrix_type\t\t\t\t\t\tm_inv_cov;\r\n\t\tdouble\t\t\t\t\t\t\tm_scale;\r\n\r\n\t};\r\n\r\n\r\n}}\r\n", "meta": {"hexsha": "1bfadd7286b7a88fc72908a48db54f992ea18e0a", "size": 4778, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "skynet/statistics/distribution.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/distribution.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/distribution.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": 28.7831325301, "max_line_length": 137, "alphanum_fraction": 0.6452490582, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.6215620201719547}}
{"text": "/**\n * @file OrientationUtils.hpp\n * @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de)\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft.\n * @date 2019-10-08\n */\n\n#pragma once\n\n#include <Eigen/Geometry>\n\nnamespace momentumopt {\n\n  /** computes the error between two quaternions by rotating the desired orientation\n   *  back by the current orientation, and taking the logarithm of the result.\n   */\n  Eigen::Vector3d orientationError(const Eigen::Quaternion<double>& desired_orientation,\n                                   const Eigen::Quaternion<double>& current_orientation);\n\n  /** computation of the required angular velocity to move from a current orientation\n   *  to a desired orientation in a given time interval. Angular velocity can be returned\n   *  in body or world coordinates.\n   */\n  Eigen::Vector3d requiredAngularVelocity(const Eigen::Quaternion<double>& desired_orientation,\n                                          const Eigen::Quaternion<double>& current_orientation,\n                                          const double& time_step, bool in_body_coordinates=false);\n\n  /** integration of a quaternion given an angular velocity given either in\n   *  body or world coordinates and a time interval for integration\n   */\n  Eigen::Quaternion<double> integrateAngularVelocity(const Eigen::Quaternion<double>& current_orientation,\n                                                     const Eigen::Vector3d& angular_velocity,\n                                                     const double& time_step, bool in_body_coordinates=false);\n\n}\n", "meta": {"hexsha": "06d48bc91d8532350bb9a1db78fc046857b112db", "size": 1629, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "momentumopt/include/momentumopt/utilities/OrientationUtils.hpp", "max_stars_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_stars_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T17:39:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T00:38:22.000Z", "max_issues_repo_path": "momentumopt/include/momentumopt/utilities/OrientationUtils.hpp", "max_issues_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_issues_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-11T19:54:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T13:41:47.000Z", "max_forks_repo_path": "momentumopt/include/momentumopt/utilities/OrientationUtils.hpp", "max_forks_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_forks_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-15T14:36:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T10:42:19.000Z", "avg_line_length": 44.027027027, "max_line_length": 110, "alphanum_fraction": 0.6660527931, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6215495704920311}}
{"text": "// Copyright (C) 2017 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (sweeney.chris.m@gmail.com)\n\n#include \"theia/sfm/pose/relative_pose_from_two_points_with_known_rotation.h\"\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <glog/logging.h>\n#include <vector>\n\nnamespace theia {\n\n// We use the epipolar constraint to solve for the unknown relative position:\n//\n//   p1^t * [t]_x * p2 = 0\n//\n// By stacking this constraint for both correspondences, we can constraint the 2\n// degrees of freedom in our unknown relative position and solve for the\n// solution easily.\nbool RelativePoseFromTwoPointsWithKnownRotation(\n    const Eigen::Vector2d rotated_features1[2],\n    const Eigen::Vector2d rotated_features2[2],\n    Eigen::Vector3d* relative_position2) {\n  CHECK_NOTNULL(relative_position2);\n\n  // The epipolar constraint can be rewritten in terms of the rotated features p\n  // an d q as:\n  //\n  // p2 * q1 * t3 - p2 * t1 - q1 * t2 + q2 * t1 - p1 * q2 * t3 + p1 * t2 = 0\n  //\n  // Note that p3 and q3 are both 1.0, so they do not appear in this\n  // equation. These constraints are stacked together to form a linear system\n  // whose null space reveals the relative position.\n  Eigen::Matrix<double, 2, 3> epipolar_constraint;\n  for (int i = 0; i < 2; i++) {\n    epipolar_constraint(i, 0) =\n        -rotated_features1[i].y() + rotated_features2[i].y();\n    epipolar_constraint(i, 1) =\n        -rotated_features2[i].x() + rotated_features1[i].x();\n    epipolar_constraint(i, 2) =\n        rotated_features1[i].y() * rotated_features2[i].x() -\n        rotated_features1[i].x() * rotated_features2[i].y();\n  }\n\n  // Compute the null space of this matrix.\n  Eigen::FullPivLU<Eigen::Matrix<double, 2, 3> > linear_solver(\n      epipolar_constraint);\n  // If the null space is greater than 1 dimension then the linear system is\n  // ill-conditioned or otherwise degenerate and the relative position cannot be\n  // solved for.\n  if (linear_solver.dimensionOfKernel() != 1) {\n    return false;\n  }\n  // Extract the relative position as the null space kernel.\n  *relative_position2 = linear_solver.kernel().normalized();\n  return true;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "244209118452ef2dd966493628e2c3a0fe7c3627", "size": 3857, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/relative_pose_from_two_points_with_known_rotation.cc", "max_stars_repo_name": "maxchernet/TheiaSfM", "max_stars_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 770.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T14:32:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:54:33.000Z", "max_issues_repo_path": "src/theia/sfm/pose/relative_pose_from_two_points_with_known_rotation.cc", "max_issues_repo_name": "maxchernet/TheiaSfM", "max_issues_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 237.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T18:50:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T05:21:48.000Z", "max_forks_repo_path": "src/theia/sfm/pose/relative_pose_from_two_points_with_known_rotation.cc", "max_forks_repo_name": "maxchernet/TheiaSfM", "max_forks_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 278.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T06:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:25:21.000Z", "avg_line_length": 42.3846153846, "max_line_length": 80, "alphanum_fraction": 0.722323049, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339556397749, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6215495497110813}}
{"text": "/**\n * @file tests/bayesian_linear_regression_test.cpp \n * @author Clement Mercier\n *\n * Test for BayesianLinearRegression.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n\n#include <mlpack/core/data/load.hpp>\n#include <mlpack/methods/bayesian_linear_regression/bayesian_linear_regression.hpp>\n#include <mlpack/methods/linear_regression/linear_regression.hpp>\n\n#include <boost/test/unit_test.hpp>\n\nusing namespace mlpack::regression;\nusing namespace mlpack::data;\n\nBOOST_AUTO_TEST_SUITE(BayesianLinearRegressionTest);\n\nvoid GenerateProblem(arma::mat& matX,\n                     arma::rowvec& y,\n                     size_t nPoints,\n                     size_t nDims,\n                     float sigma = 0.0)\n{\n  matX = arma::randn(nDims, nPoints);\n  arma::colvec omega = arma::randn(nDims);\n  // Compute y and add noise.\n  y = omega.t() * matX + arma::randn(nPoints).t() * sigma;\n}\n\n// Ensure that predictions are close enough to the target\n// for a free noise dataset.\nBOOST_AUTO_TEST_CASE(BayesianLinearRegressionRegressionTest)\n{\n  arma::mat matX;\n  arma::rowvec y, predictions;\n\n  GenerateProblem(matX, y, 200, 10);\n\n  // Instanciate and train the estimator.\n  BayesianLinearRegression estimator(true);\n  estimator.Train(matX, y);\n  estimator.Predict(matX, predictions);\n\n  // Check the predictions are close enough to the targets in a free noise case.\n  for (size_t i = 0; i < y.size(); i++)\n    BOOST_REQUIRE_CLOSE(predictions[i], y[i], 1e-6);\n\n  // Check that the estimated variance is zero.\n  BOOST_REQUIRE_SMALL(estimator.Variance(), 1e-6);\n}\n\n// Verify centerData and scaleData equal false do not affect the solution.\nBOOST_AUTO_TEST_CASE(TestCenter0ScaleData0)\n{\n  arma::mat matX;\n  arma::rowvec y;\n  size_t nDims = 30, nPoints = 100;\n\n  GenerateProblem(matX, y, nPoints, nDims, 0.5);\n\n  BayesianLinearRegression estimator(false, false);\n\n  estimator.Train(matX, y);\n\n  // Check dataOffset is empty.\n  BOOST_REQUIRE(estimator.DataOffset().n_elem == 0);\n\n  // To be neutral responseOffset must be 0.\n  BOOST_REQUIRE(estimator.ResponsesOffset() == 0);\n\n  // Check dataScale is empty.\n  BOOST_REQUIRE(estimator.DataScale().n_elem == 0);\n}\n\n// Verify that centering and normalization are correct.\nBOOST_AUTO_TEST_CASE(TestCenterDataTrueScaleDataTrue)\n{\n  arma::mat matX;\n  arma::rowvec y;\n  size_t nDims = 5, nPoints = 100;\n  GenerateProblem(matX, y, nPoints, nDims, 0.5);\n\n  BayesianLinearRegression estimator(true, true);\n  estimator.Train(matX, y);\n\n  arma::colvec xMean = arma::mean(matX, 1);\n  arma::colvec xStd = arma::stddev(matX, 0, 1);\n  double yMean = arma::mean(y);\n\n  BOOST_REQUIRE_SMALL((double) abs(sum(estimator.DataOffset() - xMean)), 1e-6);\n  BOOST_REQUIRE_SMALL((double) abs(sum(estimator.DataScale() - xStd)), 1e-6);\n  BOOST_REQUIRE_CLOSE(estimator.ResponsesOffset(), yMean, 1e-6);\n}\n\n// Make sure a model with center ans scale option set is different than a model\n// without it set.\nBOOST_AUTO_TEST_CASE(OptionsMakeModelDifferent)\n{\n  arma::mat matX;\n  arma::rowvec y;\n  size_t nDims = 10, nPoints = 100;\n  GenerateProblem(matX, y, nPoints, nDims, 0.5);\n\n  BayesianLinearRegression blr(false, false), blrC(true, false),\n      blrCS(true, true);\n\n  blr.Train(matX, y);\n  blrC.Train(matX, y);\n  blrCS.Train(matX, y);\n\n  for (size_t i = 0; i < nDims; ++i)\n    BOOST_REQUIRE((blr.Omega()(i) != blrC.Omega()(i)) &&\n                  (blr.Omega()(i) != blrCS.Omega()(i)) &&\n                  (blrC.Omega()(i) != blrCS.Omega()(i)));\n}\n\n// Check that Train() does not fail with two colinear vectors.\nBOOST_AUTO_TEST_CASE(SingularMatix)\n{\n  arma::mat matX;\n  arma::rowvec y;\n\n  GenerateProblem(matX, y, 200, 10);\n  // Now the first and the second rows are indentical.\n  matX.row(1) = matX.row(0);\n\n  BayesianLinearRegression estimator;\n  estimator.Train(matX, y);\n}\n\n// Check that std are well computed/coherent. At least higher than the\n// estimated predictive variance.\nBOOST_AUTO_TEST_CASE(PredictiveUncertainties)\n{\n  arma::mat matX;\n  arma::rowvec y;\n\n  GenerateProblem(matX, y, 100, 10, 1);\n\n  BayesianLinearRegression estimator(true, true);\n  estimator.Train(matX, y);\n\n  arma::rowvec responses, std;\n  estimator.Predict(matX, responses, std);\n  const double estStd = sqrt(estimator.Variance());\n\n  for (size_t i = 0; i < matX.n_cols; i++)\n    BOOST_REQUIRE_GT(std[i], estStd);\n\n  // Check that the estimated variance is close to 1.\n  BOOST_REQUIRE_CLOSE(estStd, 1, 30);\n}\n\n// Check the solution is equal to the classical ridge.\nBOOST_AUTO_TEST_CASE(EqualtoRidge)\n{\n  arma::mat matX;\n  arma::rowvec y, blrPred, ridgePred;\n\n  size_t trial = 0;\n  for ( ; trial < 3; ++trial)\n  {\n    GenerateProblem(matX, y, 100, 10, 1);\n\n    BayesianLinearRegression blr(false, false);\n    blr.Train(matX, y);\n\n    LinearRegression ridge(matX, y, blr.Alpha() / blr.Beta(), false);\n\n    blr.Predict(matX, blrPred);\n    ridge.Predict(matX, ridgePred);\n\n    // If the predictions seem far off, just try again.\n    if (arma::norm(blrPred - ridgePred) > 1e-5)\n      continue;\n\n    // Check the predictions are close enough between ridge and our blr.\n    for (size_t i = 0; i < y.size(); ++i)\n      BOOST_REQUIRE_CLOSE(blrPred[i], ridgePred[i], 1);\n\n    // Exit once a test case has completed.\n    break;\n  }\n\n  BOOST_REQUIRE_LT(trial, 3);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "d0c34509b943e1dd27dcee3e61bf788fad160ad8", "size": 5517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/bayesian_linear_regression_test.cpp", "max_stars_repo_name": "tejasvi/mlpack", "max_stars_repo_head_hexsha": "9bc159c52d13139834cc89e8669fe65fc97fa107", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-09T17:58:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T17:58:29.000Z", "max_issues_repo_path": "src/mlpack/tests/bayesian_linear_regression_test.cpp", "max_issues_repo_name": "R-Aravind/mlpack", "max_issues_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/bayesian_linear_regression_test.cpp", "max_forks_repo_name": "R-Aravind/mlpack", "max_forks_repo_head_hexsha": "99d11a9b4d379885cf7f8160d8c71fb792fa1bbc", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-20T19:38:10.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-20T19:38:10.000Z", "avg_line_length": 28.2923076923, "max_line_length": 83, "alphanum_fraction": 0.6929490665, "num_tokens": 1557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6215495489913803}}
{"text": "#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublasx/operation/seq.hpp>\n#include <cstddef>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = ::boost::numeric::ublas;\nnamespace ublasx = ::boost::numeric::ublasx;\n\n\nstatic const std::size_t tol = 1.0e-5;\n\n\nBOOST_UBLASX_TEST_DEF( test_range )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Range\");\n\n\ttypedef double value_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\n\tconst std::size_t n(3);\n\n\tvector_type res;\n\tvector_type expect_res;\n\n\tres = ublasx::seq(5, 5+n);\n\texpect_res = vector_type(n);\n\texpect_res(0) = 5;\n\texpect_res(1) = 6;\n\texpect_res(2) = 7;\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"res = \" << res );\n\tBOOST_UBLASX_DEBUG_TRACE( \"expect res = \" << expect_res );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect_res, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_slice_incr )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Slice - Increasing\");\n\n\ttypedef double value_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\n\tconst std::size_t n(9);\n\n\tvector_type res;\n\tvector_type expect_res;\n\n\tres = ublasx::seq(4, 2, n);\n\texpect_res = vector_type(n);\n\tstd::size_t v(4);\n\tfor (std::size_t i = 0; i < n; ++i)\n\t{\n\t\texpect_res(i) = v;\n\t\tv += 2;\n\t}\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"res = \" << res );\n\tBOOST_UBLASX_DEBUG_TRACE( \"expect res = \" << expect_res );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect_res, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_slice_decr )\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Case: Slice - Decreasing\");\n\n\ttypedef double value_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\n\tconst std::size_t n(9);\n\n\tvector_type res;\n\tvector_type expect_res;\n\n\tres = ublasx::seq(4, -2, n);\n\texpect_res = vector_type(n);\n\tshort v(4);\n\tfor (std::size_t i = 0; i < n; ++i)\n\t{\n\t\texpect_res(i) = v;\n\t\tv -= 2;\n\t}\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"res = \" << res );\n\tBOOST_UBLASX_DEBUG_TRACE( \"expect res = \" << expect_res );\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect_res, n, tol );\n}\n\n\nint main()\n{\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Suite: 'seq' operation\");\n\n\tBOOST_UBLASX_TEST_BEGIN();\n\n\tBOOST_UBLASX_TEST_DO( test_range );\n\tBOOST_UBLASX_TEST_DO( test_slice_incr );\n\tBOOST_UBLASX_TEST_DO( test_slice_decr );\n\n\tBOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "c0614cab17cdf665f6aa987deeb09431e5095b35", "size": 2305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/seq.cpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/numeric/ublasx/test/seq.cpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/ublasx/test/seq.cpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.7452830189, "max_line_length": 65, "alphanum_fraction": 0.7162689805, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.8080672158638527, "lm_q1q2_score": 0.621468525945655}}
{"text": "#define BOOST_TEST_MODULE test_utils\n\n#include <boost/test/unit_test.hpp>\n#include <Utils/utils.h>\n\nBOOST_AUTO_TEST_SUITE(utils_boost)\n\n    BOOST_AUTO_TEST_CASE(hello_world) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double f = 0.1;\n        auto sum = add(f, 10);\n\n        auto product = f * 10;\n\n        BOOST_TEST_MESSAGE(\" - sum: \" << sum);\n        BOOST_TEST_MESSAGE(\" - product: \" << product);\n        BOOST_TEST_MESSAGE(\" - diff \" << sum - product);\n        BOOST_TEST(sum == product, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(hello_world2) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double f = 0.1;\n        auto sum = add(f, 10);\n\n        auto product = f * 10;\n\n        BOOST_TEST_MESSAGE(\" - sum: \" << sum);\n        BOOST_TEST_MESSAGE(\" - product: \" << product);\n        BOOST_TEST_MESSAGE(\" - diff \" << sum - product);\n        BOOST_TEST(sum == product, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(annual_cap1) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 100;\n        double annual_rate = 10.0 / 100;\n        int number_of_years = 2;\n        double theoretical_value = 121; // (100*(1.1)^2)\n\n        auto calculated_value = annual_capitalization(amount, annual_rate, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_capitalization: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(period_cap1) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 100;\n        double annual_rate = 10.0 / 100;\n        int periods_per_year = 2;\n        int number_of_years = 1;\n        double theoretical_value = 110.25; // (100*(1.0.5)^2)\n\n        auto calculated_value = period_capitalization(amount, annual_rate, periods_per_year, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_capitalization: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(continuous_cap1) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double amount = 100;\n        double annual_rate = 10.0 / 100;\n        int number_of_years = 2;\n        double theoretical_value = 122.140275816; // (100*(1.1)^2) rounded to second\n\n        auto calculated_value = continuous_capitalization(amount, annual_rate, number_of_years);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_capitalization: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-8));\n    }\n\n    BOOST_AUTO_TEST_CASE(fwd_rate1) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double zero_coupon_total = 0.04;\n        int years_total = 2;\n\n        double zero_coupon_partial = 0.03;\n        int years_partial = 1;\n\n        double theoretical_value = 0.05; // (100*(1.1)^2) rounded to second\n\n        auto calculated_value = forward_rate(zero_coupon_total, years_total, zero_coupon_partial, years_partial);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_fwd_rate: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-15));\n    }\n\n    BOOST_AUTO_TEST_CASE(annual_to_cont1) {\n            BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n            double annual_rate = 0.12;\n\n            double theoretical_value = 0.1133286853; // ln(1.12)\n\n            auto calculated_value = annual_to_continuous_rate(1, annual_rate);\n\n            BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n            BOOST_TEST_MESSAGE(\" - known_fwd_rate: \" << theoretical_value);\n            BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n            BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-10));\n    }\n\n    BOOST_AUTO_TEST_CASE(cont_to_annual) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        double continuous_rate = 0.11332868531; //(e^0.1)-1\n\n        double theoretical_value = 0.12; // (e^0.1)-1\n\n        auto calculated_value = continuous_to_annual_rate(1, continuous_rate);\n\n        BOOST_TEST_MESSAGE(\" - calculated_value: \" << calculated_value);\n        BOOST_TEST_MESSAGE(\" - known_fwd_rate: \" << theoretical_value);\n        BOOST_TEST_MESSAGE(\" - diff \" << calculated_value - theoretical_value);\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-9));\n    }\n\n    /*\n    BOOST_AUTO_TEST_CASE(actual_count) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n\n\t\t\t  const double notional = 100;\n\t\t\t\tconst std::vector<double> CashFlows = {2.99, 2.98, 2.97, 101.60};\n\t\t\t\tconst int sPeriods = 2;\n\t\t\t  const double tPPeriods = 2.0;\n\t\t\t\tconst int mPeriod = 1;\n\n\t\t\t\t//Bono_TIR bond = Bono_TIR(notional, CashFlows, sPeriods, tPPeriods, mPeriod);\n\n\t\t\t\t//Bono_TIR bond = Bono_TIR();\n\n\t\t\t\tdouble expected_values = \t6.76;\n\t\t\t\t//double calculated_values = bond(notional, CashFlows, sPeriods, tPPeriods, mPeriod);\n\n\t\t\t\tdouble calculated_values = bond.cbrt(6.76);\n\n        BOOST_TEST_MESSAGE(\" - Calculated Value: \" << calculated_values);\n        BOOST_TEST_MESSAGE(\" - Expected Value: \" << expected_values);\n        BOOST_TEST_MESSAGE(\" - Diff \" << calculated_values - expected_values);\n        BOOST_TEST(expected_values == calculated_values, boost::test_tools::tolerance(1e-15));\n    }*/\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "2383322462c9d3162f15c4d0a88ed561cf75ac97", "size": 6169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "assignment1/src/Utils/tests/test.cpp", "max_stars_repo_name": "paulochang/frontoffice-assignment1", "max_stars_repo_head_hexsha": "574c62dedfc0a5c060924a38d51b80aaca48ff23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-04-24T14:51:37.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-24T14:51:39.000Z", "max_issues_repo_path": "assignment1/src/Utils/tests/test.cpp", "max_issues_repo_name": "paulochang/frontoffice-assignment1", "max_issues_repo_head_hexsha": "574c62dedfc0a5c060924a38d51b80aaca48ff23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment1/src/Utils/tests/test.cpp", "max_forks_repo_name": "paulochang/frontoffice-assignment1", "max_forks_repo_head_hexsha": "574c62dedfc0a5c060924a38d51b80aaca48ff23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0802469136, "max_line_length": 113, "alphanum_fraction": 0.6662343978, "num_tokens": 1478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.8080672135527632, "lm_q1q2_score": 0.6214685241682418}}
{"text": "#pragma once\n\n// equations based on: https://mste.illinois.edu/regression/directory.html\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/covariance.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/accumulators/statistics/variates/covariate.hpp>\n\n// alternative iterator implementation\ntemplate <typename _InputIter0, typename _InputIter1>\ndecltype(auto) lineFitting(_InputIter0 begin0, _InputIter0 end0,\n                           _InputIter1 begin1) {\n    using _ResType = decltype((*begin0) * (*begin1));\n    namespace ba = boost::accumulators;\n\n    ba::accumulator_set<\n        _ResType, ba::stats<ba::tag::variance,\n                            ba::tag::covariance<_ResType, ba::tag::covariate1>>>\n        stat_x;\n\n    ba::accumulator_set<_ResType, ba::stats<ba::tag::mean>> stat_y;\n\n    std::for_each(begin0, end0, [&begin1, &stat_x, &stat_y](const _ResType& x) {\n        stat_y(*begin1);\n        stat_x(x, ba::covariate1 = *begin1++);\n    });\n    const auto slope = ba::covariance(stat_x) / ba::variance(stat_x);\n    return std::make_pair(slope, ba::mean(stat_y) - slope * ba::mean(stat_x));\n}\n", "meta": {"hexsha": "2712c045330a35a54175f84486461989c74f8576", "size": 1216, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "functionFitting/lineFitting.hpp", "max_stars_repo_name": "sWombacher/Utility", "max_stars_repo_head_hexsha": "bb38fb090fd11fd36c07a318e7c6a301e0e21322", "max_stars_repo_licenses": ["WTFPL", "Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-25T21:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-25T21:56:12.000Z", "max_issues_repo_path": "functionFitting/lineFitting.hpp", "max_issues_repo_name": "sWombacher/Utility", "max_issues_repo_head_hexsha": "bb38fb090fd11fd36c07a318e7c6a301e0e21322", "max_issues_repo_licenses": ["WTFPL", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functionFitting/lineFitting.hpp", "max_forks_repo_name": "sWombacher/Utility", "max_forks_repo_head_hexsha": "bb38fb090fd11fd36c07a318e7c6a301e0e21322", "max_forks_repo_licenses": ["WTFPL", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0, "max_line_length": 80, "alphanum_fraction": 0.6858552632, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6214685226241471}}
{"text": "#include \"include/MMVII_all.h\"\n#include <boost/math/special_functions/fpclassify.hpp>\n\nnamespace MMVII\n{\n\n// return the variance of  exponential distribution of parameter \"a\" ( i.e proportiona to  \"a^|x|\")\ndouble Sigma2FromFactExp(double a)\n{\n   return (2*a) / Square(1-a);\n}\n\n// return the value of \"a\" such that  exponential distribution of parameter \"a\" has variance S2\n// i.e. this the \"inverse\" function of Sigma2FromFactExp\n\ndouble FactExpFromSigma2(double aS2)\n{\n    return (aS2+1 - sqrt(Square(aS2+1)-Square(aS2))  ) / aS2 ;\n}\n\n/* *************************************** */\n/*                                         */\n/*        cComputeStdDev                   */\n/*                                         */\n/* *************************************** */\n\ntemplate <class Type> cComputeStdDev<Type>::cComputeStdDev() :\n   mSomW   (0.0),\n   mSomWV  (0.0),\n   mSomWV2 (0.0)\n{\n}\n\ntemplate <class Type> void cComputeStdDev<Type>::Add(const Type & aW,const Type & aV)\n{\n    mSomW   += aW;\n    mSomWV  += aW *aV;\n    mSomWV2 += aW * Square(aV);\n}\n\n\ntemplate <class Type> void cComputeStdDev<Type>::SelfNormalize()\n{\n    MMVII_ASSERT_INVERTIBLE_VALUE(mSomW);\n     \n    mSomWV  /= mSomW;\n    mSomWV2  /= mSomW;\n    mSomWV2 -= Square(mSomWV);\n    mStdDev = std::sqrt(std::max(Type(0.0),mSomWV2));\n}\n\ntemplate <class Type> Type cComputeStdDev<Type>::NormalizedVal(const Type & aVal)  const\n{\n    MMVII_ASSERT_INVERTIBLE_VALUE(mStdDev);\n    return (aVal-mSomWV) / mStdDev;\n}\n\ntemplate <class Type> cComputeStdDev<Type>  cComputeStdDev<Type>::Normalize() const\n{\n     cComputeStdDev<Type> aRes = *this;\n     aRes.SelfNormalize();\n     return aRes;\n}\n\n\n/* ============================================= */\n/*      cMatIner2Var<Type>                       */\n/* ============================================= */\n\ntemplate <class Type> cMatIner2Var<Type>::cMatIner2Var() :\n   mS0  (0.0),\n   mS1  (0.0),\n   mS11 (0.0),\n   mS2  (0.0),\n   mS12 (0.0),\n   mS22 (0.0)\n{\n}\ntemplate <class Type> void cMatIner2Var<Type>::Add(const double & aPds,const Type & aV1,const Type & aV2)\n{\n    mS0  += aPds;\n    mS1  += aPds * aV1;\n    mS11 += aPds * aV1 * aV1 ;\n    mS2  += aPds * aV2;\n    mS12 += aPds * aV1 * aV2 ;\n    mS22 += aPds * aV2 * aV2 ;\n}\n\ntemplate <class Type> void cMatIner2Var<Type>::Normalize()\n{\n     MMVII_ASSERT_INVERTIBLE_VALUE(mS0);\n\n     mS1 /= mS0;\n     mS2 /= mS0;\n     mS11 /= mS0;\n     mS12 /= mS0;\n     mS22 /= mS0;\n     mS11 -= Square(mS1);\n     mS12 -= mS1 * mS2;\n     mS22 -= mS2 * mS2;\n}\n\ntemplate <class Type> cMatIner2Var<double> StatFromImageDist(const cDataIm2D<Type> & aIm)\n{\n    cMatIner2Var<double> aRes;\n    for (const auto & aP : aIm)\n    {\n         aRes.Add(aIm.GetV(aP),aP.x(),aP.y());\n    }\n    aRes.Normalize();\n    return aRes;\n}\n\n#define INSTANTIATE_MAT_INER(TYPE)\\\ntemplate class cMatIner2Var<TYPE>;\\\ntemplate  class cComputeStdDev<TYPE>;\\\ntemplate  cMatIner2Var<double> StatFromImageDist(const cDataIm2D<TYPE> & aIm);\n\n\nINSTANTIATE_MAT_INER(tREAL4)\nINSTANTIATE_MAT_INER(tREAL8)\nINSTANTIATE_MAT_INER(tREAL16)\n\n/* *********************************************** */\n/*                                                 */\n/*        cUB_ComputeStdDev<Dim>                   */\n/*                                                 */\n/* *********************************************** */\n\ntemplate  <const int Dim> cUB_ComputeStdDev<Dim>::cUB_ComputeStdDev() :\n    mSomW   (0.0),\n    mSomWW  (0.0)\n{\n    for (int aD=0 ; aD<Dim ; aD++)\n    {\n        mSomWV[aD] = 0.0;\n        mSomWVV[aD] = 0.0;\n    }\n}\n\ntemplate  <const int Dim> void cUB_ComputeStdDev<Dim>::Add(const  double *  aVal,const double & aPds)\n{\n    mSomW += aPds;\n    mSomWW += Square(aPds);\n    for (int aD=0 ; aD<Dim ; aD++)\n    {\n        mSomWV[aD] += aPds * aVal[aD];\n        mSomWVV[aD] += aPds * Square(aVal[aD]);\n    }\n}\ntemplate  <const int Dim>  double cUB_ComputeStdDev<Dim>::DeBiasFactor() const\n{\n    MMVII_INTERNAL_ASSERT_strong(mSomW>0,\"No value in DeBiasFactor\");\n    return   1 - mSomWW/Square(mSomW);\n}\n\ntemplate  <const int Dim> bool    cUB_ComputeStdDev<Dim>::OkForUnBiasedVar() const\n{\n   return (mSomW>0)  && (DeBiasFactor()!=0);\n}\n\ntemplate  <const int Dim> const double *   cUB_ComputeStdDev<Dim>::ComputeUnBiasedVar()\n{\n    /* At least, this formula is correct :\n         - when all weight are equal => 1-1/N\n         - when all but one weight are 0 => 0 \n         - and finally if all are equal or 0\n    */\n    double aDebias = DeBiasFactor();\n    MMVII_INTERNAL_ASSERT_strong(aDebias>0,\"No var can be computed in ComputeVar\");\n\n    for (int aD=0 ; aD<Dim ; aD++)\n    {\n        double aAver = mSomWV[aD] / mSomW;\n        double aVar  = mSomWVV[aD] / mSomW;\n        aVar = aVar - Square(aAver);\n        mVar[aD] = std::max(0.0,aVar) /aDebias;\n    }\n\n   return mVar;\n}\n\ntemplate  <const int Dim> const double *   cUB_ComputeStdDev<Dim>::ComputeBiasedVar()\n{\n    for (int aD=0 ; aD<Dim ; aD++)\n    {\n        double aAver = mSomWV[aD] / mSomW;\n        double aVar  = mSomWVV[aD] / mSomW;\n        aVar = aVar - Square(aAver);\n        mBVar[aD] = std::max(0.0,aVar);\n    }\n\n   return mBVar;\n}\n\n\n\n\n\ntemplate class cUB_ComputeStdDev<1>;\n\nvoid BenchUnbiasedStdDev()\n{\n    for (int aNbTest = 0 ; aNbTest<1000 ; aNbTest++)\n    {\n         int aNbVar = 1 + RandUnif_N(3);\n         int aNbTir = aNbVar;\n         int aNbComb = pow(aNbVar,aNbTir);\n         std::vector<double> aVecVals = VRandUnif_0_1(aNbVar);\n         std::vector<double> aVecWeight = VRandUnif_0_1(aNbVar);\n// aVecWeight =  std::vector<double> (aNbVar,1.0);\n\n         // compute the average of all empirical variance\n         double aMoyVar=0;\n         for (int aFlag=0 ; aFlag < aNbComb ; aFlag++) // Explore all combinaison\n         {\n             cUB_ComputeStdDev<1> aUBS;\n             for (int aVar=0 ; aVar < aNbVar ; aVar++) // All Variable of this realization\n             {\n                 int aNumVar = (aFlag / round_ni(pow(aNbVar,aVar))) % aNbVar; // \"Majic\" formula to exdtrac p-adic decomp\n                 aUBS.Add(&(aVecVals.at(aNumVar)),aVecWeight.at(aNumVar));\n             }\n             aMoyVar += aUBS.ComputeBiasedVar()[0];\n         }\n         aMoyVar /= aNbComb;\n\n         cUB_ComputeStdDev<1> aUBS;\nStdOut() << \"WWW=\" ;\n         for (int aK=0 ; aK<aNbVar ; aK++)\n         {\nStdOut() << \" \" << aVecWeight.at(aK) ;\n            aUBS.Add(&(aVecVals.at(aK)),aVecWeight.at(aK));\n         }\nStdOut() << \"\\n\" ;\n         StdOut() << \"MOYVAR \" << aMoyVar <<  \" \" <<  aUBS.DeBiasFactor() *  aUBS.ComputeBiasedVar()[0] \n                  << \" DBF=\" <<  aUBS.DeBiasFactor() << \"\\n\";\ngetchar();\n    }\n}\n\n/* *********************************************** */\n/*                                                 */\n/*            Test Exp Filtre                      */\n/*                                                 */\n/* *********************************************** */\n\n// Test Sigma2FromFactExp\ntemplate <class Type> void TestVarFilterExp(cPt2di aP0,cPt2di aP1,const Type & aV0,double aFx,double aFy,int aNbIt)\n{\n   cPt2di aPMil = (aP0+aP1) / 2;\n   cRect2 aRect2(aP0,aP1);\n\n   cIm2D<Type> aIm(aP0,aP1,nullptr,eModeInitImage::eMIA_Null);\n   cDataIm2D<Type> & aDIm = aIm.DIm();\n\n   // 1- Make 1 iteration of expon filter on a Direc, check variance and aver\n   aDIm.InitDirac(aPMil,aV0);\n\n   ExponentialFilter(true,aDIm,aNbIt,aRect2,aFx,aFy);\n   cMatIner2Var<double>  aMat = StatFromImageDist(aDIm);\n\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S1() - aPMil.x()) < 1e-5  ,\"Average Exp\")\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S2() - aPMil.y()) < 1e-5  ,\"Average Exp\")\n\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S11()-Sigma2FromFactExp(aFx) * aNbIt)<1e-5,\"Var Exp\");\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S22()-Sigma2FromFactExp(aFy) * aNbIt)<1e-5,\"Var Exp\");\n}\n\n\n\ntemplate <class Type> void TestVarFilterExp(cPt2di aSz,double aStdDev,int aNbIter,double aEps)\n{\n   cIm2D<Type> aIm(cPt2di(0,0),aSz,nullptr,eModeInitImage::eMIA_Null);\n   cDataIm2D<Type> & aDIm = aIm.DIm();\n   cPt2di aPMil = aSz / 2;\n   double aV0 = 2.0;\n\n   // 1- Make 1 iteration of expon filter on a Direc, check variance and aver\n   aDIm.InitDirac(aPMil,aV0);\n\n   ExpFilterOfStdDev(aDIm,aNbIter,aStdDev);\n   cMatIner2Var<double>  aMat = StatFromImageDist(aDIm);\n\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S11()-Square(aStdDev))<aEps,\"Std dev\");\n   MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S22()-Square(aStdDev))<aEps,\"Std dev\");\n}\n\nvoid BenchStat()\n{\n   TestVarFilterExp<double>(cPt2di(-2,2),cPt2di(400,375),2.0,0.6,0.67,1);\n   TestVarFilterExp<double>(cPt2di(-2,2),cPt2di(400,375),2.0,0.6,0.67,3);\n\n   // Test Sigma2FromFactExp\n   for (int aK=1 ; aK<100 ; aK++)\n   {\n        double aS2 = aK / 5.0;\n        double aF = FactExpFromSigma2(aS2);\n        {\n           // Check both formula are inverse of each others\n           double aCheckS2 = Sigma2FromFactExp(aF);\n           MMVII_INTERNAL_ASSERT_bench(std::abs( aS2 - aCheckS2 ) < 1e-5  ,\"Sigma2FromFactExp\")\n         \n        }\n        {\n           // Check formula Sigma2FromFactExp on exponential filters\n           TestVarFilterExp<double>(cPt2di(0,0),cPt2di(4000,3),2.0,aF,0,1);\n        }\n   }\n\n   TestVarFilterExp<double>(cPt2di(300,300),2.0,2,1e-6);\n   TestVarFilterExp<float>(cPt2di(300,300),5.0,3,1e-3);\n}\n\n\n\n};\n\n", "meta": {"hexsha": "c4de577980607fd04e749bfecc0607dfaaef3f89", "size": 9234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MMVII/src/UtiMaths/uti_stat.cpp", "max_stars_repo_name": "kikislater/micmac", "max_stars_repo_head_hexsha": "3009dbdad62b3ad906ec882b74b85a3db86ca755", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-30T09:27:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-30T09:27:49.000Z", "max_issues_repo_path": "MMVII/src/UtiMaths/uti_stat.cpp", "max_issues_repo_name": "kikislater/micmac", "max_issues_repo_head_hexsha": "3009dbdad62b3ad906ec882b74b85a3db86ca755", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MMVII/src/UtiMaths/uti_stat.cpp", "max_forks_repo_name": "kikislater/micmac", "max_forks_repo_head_hexsha": "3009dbdad62b3ad906ec882b74b85a3db86ca755", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0377358491, "max_line_length": 121, "alphanum_fraction": 0.5685510071, "num_tokens": 3078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.621468519725091}}
{"text": "#include <math_lib/vec_base.h>\n\n#include <math_lib/intersection.h>\n\n#include <boost/qvm/vec_operations.hpp>\n\n#include <gtest/gtest.h>\n\nusing namespace pagoda;\n\nTEST(PlaneVsPlaneIntersectionTest, when_the_planes_intersect_should_return_a_line_intersection)\n{\n\tPlane<float> p1(Vec3F{1, 0, 0}, 0);\n\tPlane<float> p2(Vec3F{0, 1, 0}, 0);\n\n\tauto i = intersection(p1, p2);\n\tEXPECT_EQ(i.m_type, PlaneIntersectionType::Type::Intersection);\n\tEXPECT_EQ(boost::qvm::dot(i.m_intersection.GetSupportVector(), p1.GetNormal()), 0);\n\tEXPECT_EQ(boost::qvm::dot(i.m_intersection.GetSupportVector(), p2.GetNormal()), 0);\n}\n\nTEST(PlaneVsPlaneIntersectionTest, when_the_planes_dont_intersect_should_return_no_intersection)\n{\n\tPlane<float> p1(Vec3F{1, 0, 0}, 0);\n\tPlane<float> p2(Vec3F{1, 0, 0}, 1);\n\n\tauto i = intersection(p1, p2);\n\tEXPECT_EQ(i.m_type, PlaneIntersectionType::Type::NoIntersection);\n}\n\nTEST(PlaneVsPlaneIntersectionTest, when_the_planes_are_coplanar_should_return_coplanar_intersection)\n{\n\tPlane<float> p1(Vec3F{1, 0, 0}, 0);\n\tPlane<float> p2(Vec3F{1, 0, 0}, 0);\n\n\tauto i = intersection(p1, p2);\n\tEXPECT_EQ(i.m_type, PlaneIntersectionType::Type::Coplanar);\n}\n\nTEST(PlaneVsLineIntersectionTest, when_the_plane_and_line_intersect_should_return_the_intersection_point)\n{\n\tPlane<float> p(Vec3F{1, 0, 0}, 0);\n\tLine3D<float> l(Vec3F{0, 0, 0}, Vec3F{1, 0, 0});\n\n\tauto i = intersection(p, l);\n\tEXPECT_EQ(i.m_type, PlaneLineIntersection::Type::Intersection);\n\tEXPECT_TRUE(i.m_intersection == (Vec3F{0, 0, 0}));\n}\n\nTEST(PlaneVsLineIntersectionTest, when_the_plane_and_line_dont_intersect_should_return_no_intersection)\n{\n\tPlane<float> p(Vec3F{1, 0, 0}, 0);\n\tLine3D<float> l(Vec3F{1, 0, 0}, Vec3F{0, 1, 0});\n\n\tauto i = intersection(p, l);\n\tEXPECT_EQ(i.m_type, PlaneLineIntersection::Type::NoIntersection);\n}\n\nTEST(PlaneVsLineIntersectionTest, when_the_plane_and_line_are_coplanar_should_return_coplanar)\n{\n\tPlane<float> p(Vec3F{1, 0, 0}, 0);\n\tLine3D<float> l(Vec3F{0, 0, 0}, Vec3F{0, 1, 0});\n\n\tauto i = intersection(p, l);\n\tEXPECT_EQ(i.m_type, PlaneLineIntersection::Type::Coplanar);\n}\n\nTEST(PlaneVsLineIntersectionTest, has_intersection_test)\n{\n\t// clang-format off\n\tstd::vector<std::tuple<Plane<float>, Line3D<float>, Vec3F>> tests = {\n\t    {Plane<float>::FromPointAndNormal({0, 0, 0}, {1, 0, 0}), Line3D<float>::FromTwoPoints({-5, -5, 0}, {5, -5, 0}), Vec3F{0, -5, 0}}\n    };\n\t// clang-format on\n\n\tfor (const auto &t : tests)\n\t{\n\t\tauto i = intersection(std::get<0>(t), std::get<1>(t));\n\t\tEXPECT_TRUE(i.m_intersection == std::get<2>(t));\n\t}\n}\n\n", "meta": {"hexsha": "2b40d96a742cd0f4f3a9f9c6d0e390c60dc75283", "size": 2528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/unit_tests/math_lib/intersections.cpp", "max_stars_repo_name": "diegoarjz/selector", "max_stars_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-16T17:35:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-12T14:37:27.000Z", "max_issues_repo_path": "tests/unit_tests/math_lib/intersections.cpp", "max_issues_repo_name": "diegoarjz/selector", "max_issues_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 47.0, "max_issues_repo_issues_event_min_datetime": "2019-05-27T15:24:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T17:54:54.000Z", "max_forks_repo_path": "tests/unit_tests/math_lib/intersections.cpp", "max_forks_repo_name": "diegoarjz/selector", "max_forks_repo_head_hexsha": "976abd0d9e721639e6314e2599ef7e6f3dafdc4f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4578313253, "max_line_length": 133, "alphanum_fraction": 0.7274525316, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.621468501792993}}
{"text": "#include <armadillo>\n#include <vector>\n#include <set>\n#include <map>\n\nusing namespace std;\nusing namespace arma;\n\nstruct Hormiga {\n    vector<int> camino;\n    double costoCamino;\n};\n\nostream& operator<<(ostream& os, const Hormiga& hormiga)\n{\n    os << \"Recorrido: \";\n\n    for (int ciudad : hormiga.camino)\n        os << ciudad << ' ';\n\n    os << \"\\nCosto del camino: \" << hormiga.costoCamino << endl;\n\n    return os;\n}\n\nclass ColoniaHormigas {\npublic:\n    ColoniaHormigas(string rutaArchivoDistancias,\n                    int nHormigas,\n                    int nEpocas,\n                    double sigma_cero,\n                    double alpha,\n                    double beta,\n                    double tasaEvaporacion,\n                    double Q);\n\n    double calcularCosto(const vector<int>& camino);\n    Hormiga buscarCamino();\n    int seleccionarVecino(int ciudadActual, set<int> vecinos);\n    Hormiga encontrarSolucion();\n    void depositarFeromonas();\n\nprivate:\n    vector<Hormiga> m_hormiguero;\n    mat m_distancias;\n    mat m_feromonas;\n    const int m_nHormigas;\n    const int m_nEpocas;\n    const double m_alpha;\n    const double m_beta;\n    const double m_Q;\n    const double m_tasaEvaporacion;\n    unsigned int m_nCiudades;\n    int m_nodoOrigen;\n};\n\nColoniaHormigas::ColoniaHormigas(string rutaArchivoDistancias,\n                                 int nHormigas,\n                                 int nEpocas,\n                                 double sigma_cero,\n                                 double alpha,\n                                 double beta,\n                                 double tasaEvaporacion,\n                                 double Q)\n    : m_nHormigas{nHormigas}\n    , m_nEpocas{nEpocas}\n    , m_alpha{alpha}\n    , m_beta{beta}\n    , m_Q{Q}\n    , m_tasaEvaporacion{tasaEvaporacion}\n{\n    m_distancias.load(rutaArchivoDistancias);\n\n    if (!m_distancias.is_square())\n        throw runtime_error(\"La matriz le\u00edda no es cuadrada\");\n\n    m_nCiudades = m_distancias.n_rows;\n    m_nodoOrigen = randi(1, distr_param(1, m_nCiudades))(0);\n\n    m_feromonas = randu(m_distancias.n_rows, m_distancias.n_cols) * sigma_cero;\n    //    m_feromonas = mat(m_nCiudades, m_nCiudades);\n    //    m_feromonas.fill(sigma_cero);\n}\n\ndouble ColoniaHormigas::calcularCosto(const vector<int>& camino)\n{\n    double costo = 0;\n\n    for (unsigned int i = 0; i < camino.size() - 1; ++i) {\n        const int ciudad1 = camino.at(i);\n        const int ciudad2 = camino.at(i + 1);\n\n        if (ciudad1 == ciudad2)\n            throw runtime_error(\"Las ciudades son iguales\");\n\n        costo += m_distancias(ciudad1 - 1, ciudad2 - 1);\n    }\n\n    return costo;\n}\n\nHormiga ColoniaHormigas::buscarCamino()\n{\n    Hormiga hormiga;\n    hormiga.camino = {m_nodoOrigen};\n\n    set<int> vecinos;\n    for (unsigned int i = 1; i <= m_nCiudades; ++i)\n        vecinos.insert(i);\n\n    vecinos.erase(m_nodoOrigen);\n\n    while (!vecinos.empty()) {\n        const int ciudad = seleccionarVecino(hormiga.camino.back(), vecinos);\n        hormiga.camino.push_back(ciudad);\n        vecinos.erase(ciudad);\n    }\n\n    // Cuando salgo del bucle, pas\u00e9 por todas las ciudades.\n    // Solo falta volver a la ciudad inicial.\n    hormiga.camino.push_back(m_nodoOrigen);\n\n    return hormiga;\n}\n\nint ColoniaHormigas::seleccionarVecino(int ciudadActual,\n                                       set<int> vecinos)\n{\n    map<int, double> probabilidadVecino;\n    double sumaProbabilidades = 0;\n\n    // Calculo el numerador y el denominador de la expresi\u00f3n de la diapositiva\n    for (int vecino : vecinos) {\n        const double probabilidad = pow(m_feromonas(ciudadActual - 1, vecino - 1), m_alpha)\n                                    / pow(m_distancias(ciudadActual - 1, vecino - 1), m_beta);\n        //        const double probabilidad = pow(m_feromonas(ciudadActual - 1, vecino - 1), m_alpha);\n        probabilidadVecino[vecino] = probabilidad;\n        sumaProbabilidades += probabilidad;\n    }\n\n    // Normalizo cada numerador por el denominador calculado\n    for (auto& p : probabilidadVecino)\n        p.second /= sumaProbabilidades;\n\n    // Ahora que tengo las probabilidades normalizadas,\n    // selecciono un vecino\n    const double moneda = randu(1).eval()(0);\n    double probAcumulada = 0;\n\n    for (const auto& p : probabilidadVecino) {\n        probAcumulada += p.second;\n\n        if (moneda <= probAcumulada)\n            return p.first;\n    }\n\n    throw runtime_error(\"Nunca se deber\u00eda llegar hasta ac\u00e1\");\n\n    //    pair<int, double> mejor{0, 0};\n\n    //    for (const auto& p : probabilidadVecino) {\n    //        if (p.second > mejor.second)\n    //            mejor = p;\n    //    }\n\n    //    return mejor.first;\n}\n\nHormiga ColoniaHormigas::encontrarSolucion()\n{\n    for (int epoca = 1; epoca <= m_nEpocas; ++epoca) {\n        m_hormiguero.clear();\n\n        // Para cada hormiga, busco un camino que recorra todas\n        // las ciudades.\n        for (int i = 0; i < m_nHormigas; ++i)\n            m_hormiguero.push_back(buscarCamino());\n\n        // Me fijo si todas las hormigas tienen el mismo camino\n        bool todosIguales = true;\n        for (const Hormiga& hormiga : m_hormiguero) {\n            if (hormiga.camino != m_hormiguero.front().camino) {\n                todosIguales = false;\n                break;\n            }\n        }\n\n        if (todosIguales) {\n            Hormiga solucion = m_hormiguero.front();\n            solucion.costoCamino = calcularCosto(solucion.camino);\n\n            return solucion;\n        }\n\n        // Evaporar feromonas\n        m_feromonas *= (1 - m_tasaEvaporacion);\n\n        // Depositar feromonas\n        depositarFeromonas();\n    }\n\n    // Si se llega hasta ac\u00e1 las hormigas no convergieron\n    // a un \u00fanico camino.\n    throw runtime_error(\"No se encontr\u00f3 una soluci\u00f3n\");\n}\n\nvoid ColoniaHormigas::depositarFeromonas()\n{\n    if (m_hormiguero.empty())\n        throw runtime_error(\"El hormiguero est\u00e1 vac\u00edo\");\n\n    for (Hormiga& hormiga : m_hormiguero) {\n        hormiga.costoCamino = calcularCosto(hormiga.camino);\n        const double deltaFeromonas = m_Q / hormiga.costoCamino;\n\n        for (unsigned int i = 0; i < hormiga.camino.size() - 1; ++i) {\n            const int ciudad1 = hormiga.camino.at(i);\n            const int ciudad2 = hormiga.camino.at(i + 1);\n\n            if (ciudad1 == ciudad2)\n                throw runtime_error(\"Las ciudades son iguales\");\n\n            m_feromonas(ciudad1 - 1, ciudad2 - 1) += deltaFeromonas;\n            //\t\t\tm_feromonas(ciudad2 - 1, ciudad1 - 1) += deltaFeromonas;\n        }\n    }\n}\n", "meta": {"hexsha": "302f90a71cc4f468cdd04ad5d56e1b067078053a", "size": 6542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia4/colonia_hormigas.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/colonia_hormigas.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/colonia_hormigas.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.6929824561, "max_line_length": 102, "alphanum_fraction": 0.5958422501, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.685949467848392, "lm_q1q2_score": 0.6214632316857382}}
{"text": "/**\n * @file\n *\n * @copyright\n * SPDX-License-Identifier: Apache-2.0\n *\n * @test @b eigen_sparse\n * @parblock\n * This piece of code aims to stress test the exec (in particular FMA)\n * by repetitively solving the set of linear equations represented by\n * Ax=b where A is a sparse real symmetric matrix uings Cholskey method.\n * The decomposition function is from the 3rd party library Eigen.\n * A random double precision sparse real symmetric matrix (A) and a\n * random vector (b) are generated as inputs and then\n * Eigen::SimplicialCholesky is used to solve the problem Ax=b. The\n * result vector is compared against a golden result that is computed\n * during init.\n *\n * @note Although the test should run fine on a single thread, it is\n * only expected to catch defects if run on at least 2 cores.\n * @endparblock\n */\n\n#include <memory>\n\n#include <sandstone.h>\n\n#include <Eigen/Sparse>\n\n\nconstexpr size_t n=256;\nnamespace {\nstruct EigenSparseTestData {\n    Eigen::SparseMatrix<double> A{n,n};\n    Eigen::VectorXd b{n};\n    Eigen::VectorXd golden{n};\n};\n}\n\nstatic int initialize_problem(EigenSparseTestData *d)\n{\n    try {\n        std::vector<Eigen::Triplet<double>> trip;\n        for(size_t i=0; i<n; ++i) {\n            for(size_t j=i+1; j<n; ++j) {\n                double x = frandom_scale(1.0);\n                if(x < 0.1) {\n                    trip.push_back(Eigen::Triplet<double>(i,j,x));\n                    if (j>i)\n                        trip.push_back(Eigen::Triplet<double>(j,i,x));\n                }\n            }\n        }\n        for(size_t i=0; i<n; ++i) {\n            double x = fabs(frandom_scale(1.0)) + 0.05;\n            trip.push_back(Eigen::Triplet<double>(i,i,x));\n        }\n        d->A.setFromTriplets(trip.begin(), trip.end());\n        d->b = Eigen::VectorXd::Random(n);\n    } catch (...) {\n        log_error(\"Exception on Eigen code, most probably OOM\");\n        return EXIT_SKIP;\n    }\n\n    return 0;\n}\n\nstatic int eigen_sparse_init(struct test *test) {\n    auto d = std::make_unique<EigenSparseTestData>();\n    int ret = initialize_problem(d.get());\n    if (ret)\n        return ret;\n    Eigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver;\n    try {\n        d->golden = solver.compute(d->A).solve(d->b);\n    } catch (...) {\n        log_error(\"Exception on Eigen code, most probably OOM\");\n        return EXIT_SKIP;\n    }\n    if (solver.info() != Eigen::Success) {\n        report_fail(test);\n        return EXIT_FAILURE;\n    }\n\n    test->data = d.release();\n    return EXIT_SUCCESS;\n}\n\nstatic int eigen_sparse_cleanup(struct test *test) {\n    delete static_cast<EigenSparseTestData *>(test->data);\n    return EXIT_SUCCESS;\n}\n\nstatic int eigen_sparse_run(struct test *test, int cpu) {\n    auto d = static_cast<EigenSparseTestData *>(test->data);\n    do {\n        Eigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver;\n        Eigen::VectorXd x;\n        try {\n            x = solver.compute(d->A).solve(d->b);\n        } catch (...) {\n            report_fail_msg(\"Exception on Eigen code, most probably OOM\");\n        }\n        if (solver.info() != Eigen::Success) {\n            report_fail(test);\n            return EXIT_FAILURE;\n        }\n        if (x != d->golden) {\n            report_fail(test);\n            return EXIT_FAILURE;\n        }\n    } while (test_time_condition(test));\n    return EXIT_SUCCESS;\n}\n\nDECLARE_TEST(eigen_sparse, \"Eigen sparse linear algebra payload. Solve Ax=b using Cholskey (real symmetric A)\")\n  .groups = DECLARE_TEST_GROUPS(&group_math),\n  .test_init = eigen_sparse_init,\n  .test_run = eigen_sparse_run,\n  .test_cleanup = eigen_sparse_cleanup,\n  .minimum_cpu = cpu_haswell,\n  .desired_duration = -1,\n  .quality_level = TEST_QUALITY_PROD,\nEND_DECLARE_TEST\n", "meta": {"hexsha": "95855b8782573cded634aa2d60953e98e7733c4b", "size": 3734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/eigen_sparse/eigen_sparse.cpp", "max_stars_repo_name": "thiagomacieira/opendcdiag", "max_stars_repo_head_hexsha": "b5b0140b44d7616de40edd0eb08aa916de370015", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/eigen_sparse/eigen_sparse.cpp", "max_issues_repo_name": "thiagomacieira/opendcdiag", "max_issues_repo_head_hexsha": "b5b0140b44d7616de40edd0eb08aa916de370015", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/eigen_sparse/eigen_sparse.cpp", "max_forks_repo_name": "thiagomacieira/opendcdiag", "max_forks_repo_head_hexsha": "b5b0140b44d7616de40edd0eb08aa916de370015", "max_forks_repo_licenses": ["Apache-2.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.872, "max_line_length": 111, "alphanum_fraction": 0.6205141939, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.621463224683105}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"AlgorithmUtils.hpp\"\n#include \"FluidEigenMappings.hpp\"\n#include \"../public/WindowFuncs.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n\nnamespace fluid {\nnamespace algorithm {\n\n// This implements Foote's novelty curve\nclass Novelty\n{\n\npublic:\n  using ArrayXd = Eigen::ArrayXd;\n  using ArrayXXd = Eigen::ArrayXXd;\n  using MatrixXd = Eigen::MatrixXd;\n  using VectorXd = Eigen::VectorXd;\n\n  Novelty(index maxSize) : mKernelStorage(maxSize, maxSize) {}\n\n  void init(index kernelSize, index nDims)\n  {\n    assert(kernelSize % 2);\n    mKernelSize = kernelSize;\n    mNDims = nDims;\n    createKernel();\n    mSimilarity = MatrixXd::Zero(mKernelSize, mKernelSize);\n    mBufer = MatrixXd::Zero(mKernelSize, nDims);\n  }\n\n  double processFrame(const ArrayXd& input)\n  {\n    using std::vector;\n    mBufer.block(0, 0, mKernelSize - 1, mNDims) =\n        mBufer.block(1, 0, mKernelSize - 1, mNDims);\n    ArrayXXd x = mBufer.block(mKernelSize - 1, 0, 1, mNDims);\n    VectorXd in1 = input.matrix();\n    mBufer.block(mKernelSize - 1, 0, 1, mNDims) = in1.transpose();\n    VectorXd tmp = mBufer * input.matrix();\n    VectorXd norm =\n        mBufer.rowwise().norm().cwiseMax(epsilon) * input.matrix().norm();\n    norm = norm.cwiseMax(epsilon);\n    tmp = (tmp.array() / norm.array()).matrix();\n    mSimilarity.block(0, 0, mKernelSize - 1, mKernelSize - 1) =\n        mSimilarity.block(1, 1, mKernelSize - 1, mKernelSize - 1);\n    ArrayXXd x1 = mSimilarity.block(0, mKernelSize - 1, mKernelSize, 1);\n    mSimilarity.block(0, mKernelSize - 1, mKernelSize, 1) = tmp;\n    mSimilarity.block(mKernelSize - 1, 0, 1, mKernelSize) = tmp.transpose();\n    double result = (mSimilarity.array() * mKernel).sum();\n    return result / mNorm;\n  }\n\nprivate:\n  void createKernel()\n  {\n    mKernel = mKernelStorage.block(0, 0, mKernelSize, mKernelSize);\n    index   h = (mKernelSize - 1) / 2;\n    ArrayXd gaussian = ArrayXd::Zero(mKernelSize);\n    WindowFuncs::map()[WindowFuncs::WindowTypes::kGaussian](mKernelSize,\n                                                            gaussian);\n    MatrixXd tmp = gaussian.matrix() * gaussian.matrix().transpose();\n    tmp.block(h, 0, h + 1, h) *= -1;\n    tmp.block(0, h, h, h + 1) *= -1;\n    mKernel = tmp.array();\n    mNorm = mKernel.square().sum();\n  }\n\n  index    mKernelSize{3};\n  index    mNDims{513};\n  ArrayXXd mKernel;\n  ArrayXXd mKernelStorage;\n  MatrixXd mSimilarity;\n  MatrixXd mBufer;\n  double   mNorm{1.};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "f1c69384bb32cbe9aec109b494c6340a2027fac8", "size": 2916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/Novelty.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/util/Novelty.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/util/Novelty.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": 32.043956044, "max_line_length": 76, "alphanum_fraction": 0.6687242798, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009573133051, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.6213812539446976}}
{"text": "\ufeff//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"FullyConnected.hpp\"\n\n#include <boost/assert.hpp>\n\nnamespace armnn\n{\n\nvoid FullyConnected(const float*      inputData,\n                    float*            outputData,\n                    const TensorInfo& inputTensorInfo,\n                    const TensorInfo& outputTensorInfo,\n                    const float*      weightData,\n                    const float*      biasData,\n                    bool              transposeWeights)\n{\n    unsigned int N = outputTensorInfo.GetShape()[1]; // Outputs Vector Size.\n\n    BOOST_ASSERT(inputTensorInfo.GetNumDimensions() > 1); // Needs some data.\n\n    unsigned int K = 1; // Total number of activations in the input.\n    for (unsigned int i = 1; i < inputTensorInfo.GetNumDimensions(); i++)\n    {\n        K *= inputTensorInfo.GetShape()[i];\n    }\n\n    for (unsigned int n = 0; n < inputTensorInfo.GetShape()[0]; n++)\n    {\n        for (unsigned int channelOutput = 0; channelOutput < N; channelOutput++)\n        {\n            float outval = 0.f;\n\n            for (unsigned int channelInput = 0; channelInput < K; channelInput++)\n            {\n                float weight;\n                if (transposeWeights)\n                {\n                    weight = weightData[channelOutput * K + channelInput];\n                }\n                else\n                {\n                    weight = weightData[channelInput * N + channelOutput];\n                }\n\n                outval += weight * inputData[n * K + channelInput];\n            }\n\n            if (biasData)\n            {\n                outval += biasData[channelOutput];\n            }\n\n            outputData[n * N + channelOutput] = outval;\n        }\n    }\n}\n\n} //namespace armnn\n", "meta": {"hexsha": "bf5814d2ad4bf7896d0f9ab7e4cbbea446a3eb59", "size": 1783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/reference/workloads/FullyConnected.cpp", "max_stars_repo_name": "jnorwood/armnn", "max_stars_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T00:15:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T00:15:10.000Z", "max_issues_repo_path": "src/backends/reference/workloads/FullyConnected.cpp", "max_issues_repo_name": "jnorwood/armnn", "max_issues_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/backends/reference/workloads/FullyConnected.cpp", "max_forks_repo_name": "jnorwood/armnn", "max_forks_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3015873016, "max_line_length": 81, "alphanum_fraction": 0.5148625911, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6213138802084596}}
{"text": "#pragma once\n\n#include <Eigen/Core>\nusing namespace Eigen;\n\n#include <autodiff/forward.hpp>\n#include <autodiff/forward/eigen.hpp>\nusing namespace autodiff;\n\n#include <samson/so3.hpp>\n\nnamespace samson::robot\n{\n    using namespace samson::se3;\n\n    auto fk(const Matrix4dual &M, const MatrixXdual &S, const VectorXdual &theta)\n    {\n        Matrix4dual T = M;\n        for (int i = 0; i < S.rows(); ++i)\n        {\n            Vector6dual Vi = S.row(i);\n            dual thetai = theta(i);\n            Vi *= thetai;\n            T *= exp(Vi);\n        }\n        return T;\n    }\n\n} // namespace samson::robot", "meta": {"hexsha": "afa72e44303329cef48c08ebaec9811edbd02243", "size": 602, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/samson/robot.hpp", "max_stars_repo_name": "tingelst/samson", "max_stars_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/samson/robot.hpp", "max_issues_repo_name": "tingelst/samson", "max_issues_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/samson/robot.hpp", "max_forks_repo_name": "tingelst/samson", "max_forks_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7586206897, "max_line_length": 81, "alphanum_fraction": 0.5780730897, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.933430805473952, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.6211147200153827}}
{"text": "/*=========================================================================\n\n  Program:   Small Body Geophysical Analysis\n  Module:    SBGATPolyhedronGravityModel.hpp\n\n  Class derived from VTK's vtkPolyDataAlgorithm by Benjamin Bercovici  \n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*/\n\n/**\n@file SBGATPolyhedronGravityModel.hpp\n@class  SBGATPolyhedronGravityModel\n@author Benjamin Bercovici\n@date October 2018\n\n@brief  Evaluation of potential, acceleration caused by a constant-density polyhedron\n @details Computes the potential, acceleration caused by a polyhedron\n of constant density by evaluating the so called Polyhedron Gravity Model as derived by Werner and Scheeres.\nThe input must be a topologically-closed polyhedron. This class will always use results expressed in `meters` as their distance unit (e.g accelerations in m/s^2, potentials in m^2/s^2,...) . Unit consistency is enforced through the use of the SetScaleMeters()\nand SetScaleKiloMeters() method. \n\nSee Werner, R. A., & Scheeres, D. J. (1997). Exterior gravitation of a polyhedron derived and compared with harmonic and mascon gravitation representations of asteroid 4769 Castalia. Celestial Mechanics and Dynamical Astronomy, 65(3), 313\u2013344. https://doi.org/10.1007/BF00053511\nfor further details. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n@copyright MIT License, Benjamin Bercovici and Jay McMahon\n*/\n\n#ifndef SBGATPolyhedronGravityModel_hpp\n#define SBGATPolyhedronGravityModel_hpp\n\n#include <vtkFiltersCoreModule.h> // For export macro\n#include <vtkPolyDataAlgorithm.h>\n#include <armadillo>\n#include <SBGATMassProperties.hpp>\n\n\nclass VTKFILTERSCORE_EXPORT SBGATPolyhedronGravityModel : public SBGATMassProperties{\npublic:\n\n  /**\n   * Constructs with initial values of zero.\n   */\n\n  static SBGATPolyhedronGravityModel *New();\n\n  vtkTypeMacro(SBGATPolyhedronGravityModel,vtkPolyDataAlgorithm);\n  void PrintSelf(std::ostream& os, vtkIndent indent) override;\n  void PrintHeader(std::ostream& os, vtkIndent indent) override;\n  void PrintTrailer(std::ostream& os, vtkIndent indent) override;\n\n\n  /**\n  Evaluates the Polyhedron Gravity Model potential at the specified point assuming \n  a constant density\n  @param point pointer to coordinates of queried point, expressed in the same frame as\n  the polydata\n  @return PGM potential evaluated at the queried point (m ^ 2/ s ^2)\n  */\n  double GetPotential(double const * point) const;\n\n  /**\n  Evaluates the Polyhedron Gravity Model potential at the specified point assuming \n  a constant density\n  @param point coordinates of queried point, expressed in the same frame as\n  the polydata\n  @return PGM potential evaluated at the queried point (m ^ 2 / s ^2)\n  */\n  double GetPotential(const arma::vec::fixed<3> & point) const;\n\n  /**\n  Evaluates the Polyhedron Gravity Model potential and acceleration at the specified point assuming \n  a constant density\n  @param point coordinates of queried point, expressed in the same frame as\n  the polydata used to construct the PGM\n  @param[out] potential PGM potential evaluated at the queried point (m ^ 2 / s ^2)\n  @param[out] acc PGM acceleration evaluated at the queried point (m / s ^2)\n  */\n  void GetPotentialAcceleration(double const * point,double & potential, \n    arma::vec::fixed<3> & acc) const;\n\n\n  /**\n  Evaluates the Polyhedron Gravity Model potential and acceleration at the specified point assuming \n  a constant density\n  @param point coordinates of queried point, expressed in the same frame as\n  the polydata used to construct the PGM\n  @param[out] potential PGM potential evaluated at the queried point (m ^ 2 / s ^2)\n  @param[out] acc PGM acceleration evaluated at the queried point (m / s ^2)\n  */\n  void GetPotentialAcceleration(const arma::vec::fixed<3> & point,double & potential, \n    arma::vec::fixed<3> & acc) const;\n\n\n/**\nEvaluates the Polyhedron Gravity Model potential, acceleration and gravity gradient matrix at the specified point assuming \na constant density\n@param point coordinates of queried point, expressed in the same frame as\nthe polydata used to construct the PGM\n@param[out] potential PGM potential evaluated at the queried point (m ^ 2 / s ^2)\n@param[out] acc PGM acceleration evaluated at the queried point (m / s ^2)\n@param[out] gravity_gradient_mat PGM gravity gradient matrix evaluated at the queried point (1 / s ^2)\n*/\n  void GetPotentialAccelerationGravityGradient(double const  * point,double & potential, \n    arma::vec::fixed<3> & acc,arma::mat::fixed<3,3> & gravity_gradient_mat) const ;\n\n\n/**\nGet the body-fixed acceleration at the center of the specified facet\n@param f facet index \n@return body-fixed acceleration (m/s^2)\n*/\n  arma::vec::fixed<3> GetBodyFixedAccelerationf(const int & f) const;\n\n\n\n/**\nEvaluates the Polyhedron Gravity Model potential, acceleration and gravity gradient matrix at the specified point assuming \na constant density\n@param point coordinates of queried point, expressed in the same frame as\nthe polydata used to construct the PGM\n@param[out] potential PGM potential evaluated at the queried point (m ^ 2 / s ^2)\n@param[out] acc PGM acceleration evaluated at the queried point (m / s ^2)\n@param[out] gravity_gradient_mat PGM gravity gradient matrix evaluated at the queried point (1 / s ^2)\n*/\n  void GetPotentialAccelerationGravityGradient(const arma::vec::fixed<3> & point,double & potential, \n    arma::vec::fixed<3> & acc,arma::mat::fixed<3,3> & gravity_gradient_mat) const ;\n\n\n\n/**\nEvaluates the Polyhedron Gravity Model gravity gradient matrix at the specified point assuming \na constant density\n@param point coordinates of queried point, expressed in the same frame as\nthe polydata used to construct the PGM\n@param[out] gravity_gradient_mat PGM gravity gradient matrix evaluated at the queried point (1 / s ^2)\n*/\n  arma::mat::fixed<3,3> GetGravityGradient(const arma::vec::fixed<3> & point) const ;\n\n\n\n\n  /**\n  Evaluates the Polyhedron Gravity Model acceleration at the specified point assuming \n  a constant density\n  @param point coordinates of queried point, expressed in the same frame as\n  the polydata used to construct the PGM\n  @return PGM acceleration evaluated at the queried point (m / s ^2)\n  */\n  arma::vec::fixed<3> GetAcceleration(const arma::vec::fixed<3> & point) const;\n\n  /**\n  Evaluates the Polyhedron Gravity Model acceleration at the specified point assuming \n  a constant density\n  @param point pointer to coordinates of queried point, expressed in the same frame as\n  the input polydata\n  @return PGM acceleration evaluated at the queried point (m / s ^2)\n  */\n  arma::vec::fixed<3> GetAcceleration(double const * point) const;\n\n  /** \n  Determines whether the provided point lies inside or outside the shape\n  @param point coordinates of queried point, expressed in the same frame as\n  the polydata\n  @param tolerance\n  @return true if the polydata contains the point, false otherwise\n  */\n  bool Contains(double const * point, double tol = 1e-8) const;\n\n  /** \n  Determines whether the provided point lies inside or outside the shape\n  @param point coordinates of queried point, expressed in the same frame as\n  the polydata\n  @param tolerance\n  @return true if the polydata contains the point, false otherwise\n  */\n  bool Contains(const arma::vec::fixed<3> & point,double tol = 1e-8) const;\n\n  /**\n  Computes the slope as the center of the designated facet\n  @param f facet index\n  @return slope (rad)\n  */\n  double GetSlope(const int & f ) const;\n\n\n  /**\n  Get polyhedron mass. Must have set the density and call\n  @return mass (kg)\n  */\n  double GetMass() const{\n    return this -> density * this -> GetVolume() * std::pow(this -> scaleFactor,3);\n  }\n\n  /**\n  Return the performance factor of the f-th facet at the specified position\n  @param pos position of field point\n  @param f facet index\n  @return omega_f\n  */\n  double GetPerformanceFactor(const arma::vec::fixed<3> & pos, const int & f) const;\n\n  /**\n  Return the performance factor of the f-th facet at the specified position\n  @param pos position of field point\n  @param f facet index\n  @return omega_f\n  */\n  double GetPerformanceFactor( const double * pos, const int & f) const;\n\n  /**\n  Return the wire potential of the e-th edge at the specified position\n  @param pos position of field point\n  @param e edge index\n  @return L_e\n  */\n  double GetLe(const arma::vec::fixed<3> & pos, const int & e) const;\n\n  /**\n  Return the wire potential of the e-th edge at the specified position\n  @param pos position of field point\n  @param e edge index\n  @return L_e\n  */\n  double GetLe( const double * pos, const int & e) const;\n\n\n\n  /**\n  Evaluates the Polyhedron Gravity Model at the surface of the specified surface elements in the provided shape\n  @param[in] selected_shape shape for which the surface polyhedron gravity model must be computed\n  @param[in] queried_elements vector of elements indices where the polyhedron gravity model should be evaluated\n  @param[in] is_in_meters true if the shape coordinates were expressed in meters, false if they were expressed in kilometers\n  @param[in] density shape bulk density in kg/m^3\n  @param[in] omega fixed angular velocity of shape expressed in rad/s\n  @param[out] slopes vector storing the gravitational slopes (degrees) evaluated at the center of each queried element \n  @param[out] inertial_potentials vector storing the inertial gravitational potentials (m^2/s^2) evaluated at the center of each queried element \n  @param[out] body_fixed_potentials vector storing the inertial gravitational potentials (m^2/s^2) evaluated at the center of each queried element \n  @param[out] inertial_acc_magnitudes vector storing the inertial gravitational acceleration magnitudes  (m/s^2) evaluated at the center of each queried element \n  @param[out] body_fixed_acc_magnitudes vector storing the body-fixed gravitational acceleration magnitudes (m/s^2) evaluated at the center of each queried element \n  */\n  static void ComputeSurfacePGM(\n    vtkSmartPointer<vtkPolyData> selected_shape,\n    const std::vector<unsigned int> & queried_elements,\n    bool is_in_meters,\n    double density,\n    const arma::vec::fixed<3> & omega,\n    std::vector<double> & slopes,\n    std::vector<double> & inertial_potentials,\n    std::vector<double> & body_fixed_potentials,\n    std::vector<double> & inertial_acc_magnitudes,\n    std::vector<double> & body_fixed_acc_magnitudes);\n\n\n\n\n  /**\n  Saves the provided Polyhedron Gravity Model to a file\n  @param[in] selected_shape shape for which the surface polyhedron gravity model must be computed\n  @param[in] queried_elements shape indices of elements where the polyhedron gravity model should be evaluated\n  @param[in] is_in_meters true if the shape coordinates were expressed in meters, false if they were expressed in kilometers\n  @param[in] mass mass of shape model (kg)\n  @param[in] omega fixed angular velocity of shape (rad/s)\n  @param[in] slopes vector storing the gravitational slopes (degrees) evaluated at the center of each queried element \n  @param[in] inertial_potentials vector storing the inertial gravitational potentials (m^2/s^2) evaluated at the center of each queried element \n  @param[in] body_fixed_potentials vector storing the inertial gravitational potentials (m^2/s^2) evaluated at the center of each queried element \n  @param[in] inertial_acc_magnitudes vector storing the inertial gravitational acceleration magnitudes  (m/s^2) evaluated at the center of each queried element \n  @param[in] body_fixed_acc_magnitudes vector storing the body-fixed gravitational acceleration magnitudes (m/s^2) evaluated at the center of each queried element \n  @param[in] path save path (ex: \"pgm_surface.json\")\n  */\n  static void SaveSurfacePGM(vtkSmartPointer<vtkPolyData> selected_shape,\n    const std::vector<unsigned int> & queried_elements,\n    bool is_in_meters,\n    const double & mass,\n    const arma::vec::fixed<3> & omega,\n    const std::vector<double> & slopes,\n    const std::vector<double> & inertial_potentials,\n    const std::vector<double> & body_fixed_potentials,\n    const std::vector<double> & inertial_acc_magnitudes,\n    const std::vector<double> & body_fixed_acc_magnitudes,\n    std::string path);\n\n\n/**\n  Saves the provided Polyhedron Gravity Model to a file\n  @param[in] selected_shape shape for which the surface polyhedron gravity model must be computed\n  @param[in] queried_elements shape indices of elements where the polyhedron gravity model should be evaluated\n  @param[in] is_in_meters true if the shape coordinates were expressed in meters, false if they were expressed in kilometers\n  @param[in] mass mass of shape model (kg)\n  @param[in] omega fixed angular velocity of shape (rad/s)\n  @param[in] slopes vector storing the gravitational slopes (degrees) evaluated at the center of each queried element \n  @param[in] inertial_potentials vector storing the inertial gravitational potentials (m^2/s^2) evaluated at the center of each queried element \n  @param[in] body_fixed_potentials vector storing the inertial gravitational potentials (m^2/s^2) evaluated at the center of each queried element \n  @param[in] inertial_acc_magnitudes vector storing the inertial gravitational acceleration magnitudes  (m/s^2) evaluated at the center of each queried element \n  @param[in] body_fixed_acc_magnitudes vector storing the body-fixed gravitational acceleration magnitudes (m/s^2) evaluated at the center of each queried element \n  @param[in] slope_sds vector storing the standard deviation in the gravitational slopes (degrees) evaluated at the center of each queried element \n  @param[in] path save path (ex: \"pgm_surface.json\")\n  */\nstatic void SaveSurfacePGM(vtkSmartPointer<vtkPolyData> selected_shape,\n  const std::vector<unsigned int> & queried_elements,\n  bool is_in_meters,\n  const double & mass,\n  const arma::vec::fixed<3> & omega,\n  const std::vector<double> & slopes,\n  const std::vector<double> & inertial_potentials,\n  const std::vector<double> & body_fixed_potentials,\n  const std::vector<double> & inertial_acc_magnitudes,\n  const std::vector<double> & body_fixed_acc_magnitudes,\n  const std::vector<double> & slope_sds,\n  std::string path);\n\n  /**\n  Loads a previously computed surface Polyhedron Gravity Model from a file\n  @param[out] mass mass of shape model (kg)\n  @param[out] omega fixed angular velocity of shape (rad/s)\n  @param[out] slopes vector storing the gravitational slopes (degrees) evaluated at the center of each queried element \n  @param[out] inertial_potentials vector storing the inertial gravitational potentials (m^2/s^2) evaluated at the center of each queried element \n  @param[out] body_fixed_potentials vector storing the body-fixed gravitational potentials (m^2/s^2) evaluated at the center of each queried element \n  @param[out] inertial_acc_magnitudes vector storing the inertial gravitational acceleration magnitudes  (m/s^2) evaluated at the center of each queried element \n  @param[out] body_fixed_acc_magnitudes vector storing the body-fixed gravitational acceleration magnitudes (m/s^2) evaluated at the center of each queried element \n  @param[out] slope_sds standard deviation in the surface slopes (deg)\n  @param[in] path load path (ex: \"pgm_surface.json\")\n  */\n  static void LoadSurfacePGM(double & mass,\n    arma::vec::fixed<3> & omega,\n    std::vector<double> & slopes,\n    std::vector<double> & inertial_potentials,\n    std::vector<double> & body_fixed_potentials,\n    std::vector<double> & inertial_acc_magnitudes,\n    std::vector<double> & body_fixed_acc_magnitudes,\n    std::vector<double> & slope_sds,\n    std::string path);\n\n\n  /**\n  Return the Xe^E vector holding the e-th edge dyadic factors (Le,r_ie_0^T,Ee^T)^T\n  @param pos field point\n  @param e edge index\n  @return Xe^E vector holding the e-th edge dyadic factors\n  */\n  arma::vec::fixed<10> GetXe(const arma::vec::fixed<3> & pos,const int & e) const;\n\n\n  /**\n  Return the Xf^F vector holding the f-th facet dyadic factors (omega_f,r_if_0^T,Ff^T)^T\n  @param pos field point\n  @param f facet index\n  @return Xf^F vector holding the f-th facet dyadic factors\n  */\n  arma::vec::fixed<10> GetXf(const arma::vec::fixed<3> & pos,const int & f) const;\n\n  /**\n  Return the parametrization of the designated edge dyad Ee. This dyad \n  is stored in a flattened double container holding nine values and ordered like so\n\n  E = {\n    {E[0], E[1],  E[2]},\n    {E[3], E[4],  E[5]},\n    {E[6], E[7],  E[8]}\n  };\n  Due to the symmetric nature of E, its parametrization is \n  {E[0],E[4],E[8],E[1],E[2],E[5]};\n\n  @param e edge index \n  @return Ee dyad parametrization\n  */  \n  arma::vec::fixed<6> GetEeParam(const int & e) const;\n\n\n  /**\n  Return the parametrization of the designated facet dyad Ff. This dyad \n  is stored in a flattened double container holding nine values and ordered like so\n\n  F = {\n    {F[0], F[1],  F[2]},\n    {F[3], F[4],  F[5]},\n    {F[6], F[7],  F[8]}\n  };\n  Due to the symmetric nature of E, its parametrization is \n  {F[0],F[4],F[8],F[1],F[2],F[5]};\n\n  @param f facet index \n  @return Ff dyad parametrization\n  */  \n  arma::vec::fixed<6> GetFfParam(const int & f) const;\n\n\n  /**\n  Return the contribution of a specific edge to the potential at a specified field point\n  @param Xe vector of dyadic coefficients for edge e at the prescribed fieldpoint\n  @return contribution to the potential of this specific edge at the prescribed fieldpoint\n  */\n  static double GetUe(const arma::vec::fixed<10> & Xe);\n\n\n  /**\n  Return the contribution of a specific facet to the potential at a specified field point\n  @param Xf vector of dyadic coefficients for facet f at the prescribed fieldpoint\n  @return contribution to the potential of this specific facet at the prescribed fieldpoint\n  */\n  static double GetUf(const arma::vec::fixed<10> & Xf);\n\n\n  /**\n  Return the contribution of a specific edge to the acceleration at a specified field point\n  @param Xe vector of dyadic coefficients for edge e at the prescribed fieldpoint\n  @return contribution to the potential of this specific edge at the prescribed fieldpoint\n  */\n  static arma::vec::fixed<3> GetAe(const arma::vec::fixed<10> & Xe);\n\n\n  /**\n  Return the contribution of a specific facet to the acceleration at a specified field point\n  @param Xf vector of dyadic coefficients for facet f at the prescribed fieldpoint\n  @return contribution to the potential of this specific facet at the prescribed fieldpoint\n  */\n  static arma::vec::fixed<3> GetAf(const arma::vec::fixed<10> & Xf);\n\n  /**\n  Set the angular velocity vector\n  @param Omega angular velocity expressed in body-frame (rad/s)\n  */\n  void SetOmega(arma::vec::fixed<3> Omega){this -> Omega = Omega;}\n\n  /**\n  Return the angular velocity vector\n  @return Omega angular velocity expressed in body-frame (rad/s)\n  */\n  arma::vec::fixed<3> GetOmega() const {return this -> Omega;}\n\nprotected:\n  SBGATPolyhedronGravityModel();\n  ~SBGATPolyhedronGravityModel() override;\n\n  void Clear();\n\n  int RequestData(vtkInformation* request,\n    vtkInformationVector** inputVector,\n    vtkInformationVector* outputVector) override;\n\n  double ** facet_dyads;\n  double ** edge_dyads;\n\n  arma::vec::fixed<3> Omega;\n\n\nprivate:\n  SBGATPolyhedronGravityModel(const SBGATPolyhedronGravityModel&) = delete;\n  void operator=(const SBGATPolyhedronGravityModel&) = delete;\n};\n\n#endif\n\n\n", "meta": {"hexsha": "a59c66c2ca9b67236cc3d0dcf9be61ed4f8244b7", "size": 19657, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SbgatCore/include/SbgatCore/SBGATPolyhedronGravityModel.hpp", "max_stars_repo_name": "bbercovici/SBGAT", "max_stars_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T02:47:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T05:25:44.000Z", "max_issues_repo_path": "SbgatCore/include/SbgatCore/SBGATPolyhedronGravityModel.hpp", "max_issues_repo_name": "bbercovici/SBGAT", "max_issues_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2017-02-09T15:38:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-25T20:53:37.000Z", "max_forks_repo_path": "SbgatCore/include/SbgatCore/SBGATPolyhedronGravityModel.hpp", "max_forks_repo_name": "bbercovici/SBGAT", "max_forks_repo_head_hexsha": "93e935baff49eb742470d7d593931f0573f0c062", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T12:20:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T12:20:25.000Z", "avg_line_length": 42.6399132321, "max_line_length": 278, "alphanum_fraction": 0.7444167472, "num_tokens": 4865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6210786306223401}}
{"text": "/* ---------------------------------------------------------------------\r\n *\r\n * Copyright (C) 1999 - 2019 by the deal.II authors\r\n *\r\n * This file is part of the deal.II library.\r\n *\r\n * The deal.II library is free software; you can use it, redistribute\r\n * it, and/or modify it under the terms of the GNU Lesser General\r\n * Public License as published by the Free Software Foundation; either\r\n * version 2.1 of the License, or (at your option) any later version.\r\n * The full text of the license can be found in the file LICENSE.md at\r\n * the top level of the deal.II distribution.\r\n *\r\n * ---------------------------------------------------------------------\r\n *\r\n * based on deal.II step-1\r\n */\r\n\r\n\r\n#include <deal.II/grid/grid_generator.h>\r\n#include <deal.II/grid/grid_out.h>\r\n#include <deal.II/grid/manifold_lib.h>\r\n#include <deal.II/grid/tria.h>\r\n#include <deal.II/grid/tria_accessor.h>\r\n#include <deal.II/grid/tria_iterator.h>\r\n\r\n#include <cmath>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <tuple>\r\n\r\nusing namespace dealii;\r\n\r\nstd::tuple<int, int, int> func_tuple(const Triangulation<2> &tri) \r\n// Function returns multivalue: # active cells, # cells, Levels\r\n{\r\n  return std::make_tuple<int, int, int>(tri.n_levels(), \r\n                                        tri.n_cells(), \r\n                                        tri.n_active_cells());\r\n}\r\n\r\nvoid\r\nfirst_grid()\r\n{\r\n  Triangulation<2> triangulation;\r\n\r\n  GridGenerator::hyper_cube(triangulation);\r\n\r\n  triangulation.refine_global(4);\r\n\r\n  std::ofstream out(\"grid-1.svg\");\r\n  GridOut       grid_out;\r\n  grid_out.write_svg(triangulation, out);\r\n  std::cout << \"Grid written to grid-1.svg\" << std::endl;\r\n\r\n  // Triangualtion tuple construction\r\n  auto vals_tri = func_tuple(triangulation);\r\n  std::cout << \"Number of Levels\"<< \"\\t\" << std::get<0>(vals_tri) << \"\\n\" \r\n            << \"Number of cells\"<< \"\\t\" << std::get<1>(vals_tri) << \"\\n\"\r\n            << \"Number of active cells\" << \"\\t\" << std::get<2>(vals_tri) << \"\\n\";\r\n}\r\n\r\n\r\n\r\nvoid\r\nsecond_grid()\r\n{\r\n  Triangulation<2> triangulation;\r\n\r\n  const Point<2> center(1, 0);\r\n  const double   inner_radius = 0.5, outer_radius = 1.0;\r\n  GridGenerator::hyper_shell(\r\n    triangulation, center, inner_radius, outer_radius, 10);\r\n  for (unsigned int step = 0; step < 5; ++step)\r\n    {\r\n      for (auto &cell : triangulation.active_cell_iterators())\r\n        {\r\n          for (const auto v : cell->vertex_indices())\r\n            {\r\n              const double distance_from_center =\r\n                center.distance(cell->vertex(v));\r\n\r\n              if (std::fabs(distance_from_center - inner_radius) <=\r\n                  1e-6 * inner_radius)\r\n                {\r\n                  cell->set_refine_flag();\r\n                  break;\r\n                }\r\n            }\r\n        }\r\n        triangulation.reset_manifold(0); // Reset to default manifold: Flat\r\n\r\n      triangulation.execute_coarsening_and_refinement();\r\n    }\r\n\r\n\r\n  std::ofstream out(\"grid-2.svg\");\r\n  GridOut       grid_out;\r\n  grid_out.write_svg(triangulation, out);\r\n\r\n  std::cout << \"Grid written to grid-2.svg\" << std::endl;\r\n\r\n  // Triangualtion tuple construction\r\n  auto vals_tri = func_tuple(triangulation);\r\n  std::cout << \"Number of Levels\"<< \"\\t\" << std::get<0>(vals_tri) << \"\\n\" \r\n            << \"Number of cells\"<< \"\\t\" << std::get<1>(vals_tri) << \"\\n\"\r\n            << \"Number of active cells\" << \"\\t\" << std::get<2>(vals_tri) << \"\\n\";\r\n}\r\n\r\nvoid\r\nthird_grid()\r\n{\r\n  Triangulation<2> triangulation;\r\n  const double LFT = -0.5;\r\n  const double RGT =  0.5;\r\n\r\n  GridGenerator::hyper_L(triangulation, LFT, RGT, true);\r\n\r\n  std::ofstream out(\"grid-3.svg\");\r\n  GridOut       grid_out;\r\n  grid_out.write_svg(triangulation, out);\r\n  std::cout << \"Grid written to grid-3.svg\" << std::endl;\r\n    \r\n  // Triangualtion tuple construction\r\n  auto vals_tri3 = func_tuple(triangulation);\r\n  std::cout << \"Number of Levels\"<< \"\\t\" << std::get<0>(vals_tri3) << \"\\n\" \r\n            << \"Number of cells\"<< \"\\t\" << std::get<1>(vals_tri3) << \"\\n\"\r\n            << \"Number of active cells\" << \"\\t\" << std::get<2>(vals_tri3) << \"\\n\";\r\n\r\n  const unsigned int initial_global_refinement = 1 ;\r\n\r\n  triangulation.refine_global(initial_global_refinement);\r\n  std::ofstream out_global_refine(\"grid-4.svg\");\r\n\r\n  grid_out.write_svg(triangulation, out_global_refine);\r\n  std :: cout << \"Grid written to grid-4.svg\" << std::endl;\r\n\r\n  // Triangualtion tuple construction\r\n  auto vals_tri4 = func_tuple(triangulation);\r\n  std::cout << \"Number of Levels\"<< \"\\t\" << std::get<0>(vals_tri4) << \"\\n\" \r\n            << \"Number of cells\"<< \"\\t\" << std::get<1>(vals_tri4) << \"\\n\"\r\n            << \"Number of active cells\" << \"\\t\" << std::get<2>(vals_tri4) << \"\\n\";\r\n\r\n  const Point<2> corner(0, 0);\r\n  const double corner_dist = 0.3333;\r\nfor(unsigned int step = 0; step < 3; step++)\r\n{\r\n    for (auto &cell : triangulation.active_cell_iterators())\r\n    {\r\n      for( const auto v : cell->vertex_indices())\r\n      {\r\n        const double distance_from_corner = corner.distance(cell->center(v));\r\n        //std :: cout << distance_from_corner << \"\\n\";\r\n\r\n        if(std :: fabs(distance_from_corner <= corner_dist))\r\n        {\r\n          cell->set_refine_flag();\r\n          break;\r\n        }\r\n        else\r\n        {\r\n          break;\r\n        }\r\n\r\n      }\r\n\r\n    }\r\n\r\n  triangulation.execute_coarsening_and_refinement();\r\n}\r\n  std :: ofstream out_reentrant(\"grid-5.svg\");\r\n\r\n  grid_out.write_svg(triangulation, out_reentrant);\r\n  std :: cout << \"Grid written to grid-5.svg\" <<std :: endl;\r\n\r\n  // Triangualtion tuple construction\r\n  auto vals_tri5 = func_tuple(triangulation);\r\n  std::cout << \"Number of Levels\"<< \"\\t\" << std::get<0>(vals_tri5) << \"\\n\" \r\n            << \"Number of cells\"<< \"\\t\" << std::get<1>(vals_tri5) << \"\\n\"\r\n            << \"Number of active cells\" << \"\\t\" << std::get<2>(vals_tri5) << \"\\n\";\r\n}\r\n\r\nvoid\r\nspherical_grid()\r\n{\r\n  const Point<2> center(0, 0);\r\n  const double outer_radius = 1.0;\r\n\r\n  Triangulation<2> triangulation;\r\n  GridGenerator :: hyper_ball(triangulation, center, outer_radius);\r\n  triangulation.reset_all_manifolds();\r\n  triangulation.set_all_manifold_ids_on_boundary(0);\r\n\r\n  std::ofstream out(\"grid-6.svg\");\r\n  GridOut       grid_out;\r\n  grid_out.write_svg(triangulation, out);\r\n  std::cout << \"Grid written to grid-6.svg\" << std::endl;\r\n\r\n  // Spherical Manifold on Boundary\r\n\r\n  const SphericalManifold<2> manifold(center);\r\n  Triangulation<2> tria_boundary;\r\n\r\n  GridGenerator :: hyper_ball(tria_boundary, center, outer_radius, true);\r\n  tria_boundary.reset_all_manifolds();\r\n  tria_boundary.set_all_manifold_ids_on_boundary(0);\r\n  tria_boundary.set_manifold(0, manifold);\r\n  tria_boundary.refine_global(2);\r\n\r\n  std::ofstream out_boundary(\"grid-7.svg\");\r\n  grid_out.write_svg(tria_boundary, out_boundary);\r\n  std::cout << \"Grid written to grid-7.svg\" << std::endl;\r\n\r\n  // Spherical Manifold Everywhere\r\n\r\n  Triangulation<2> tria_everywhere;\r\n\r\n  GridGenerator :: hyper_ball(tria_everywhere, center, outer_radius, true);\r\n  tria_everywhere.reset_all_manifolds();\r\n  tria_everywhere.set_all_manifold_ids(0);\r\n  tria_everywhere.set_manifold(0, manifold);\r\n  tria_everywhere.refine_global(2);\r\n\r\n  std::ofstream out_eveywhere(\"grid-8.svg\");\r\n  grid_out.write_svg(tria_everywhere, out_eveywhere);\r\n  std::cout << \"Grid written to grid-8.svg\" << std::endl;\r\n\r\n  // Spherical Manifold Except center\r\n\r\n  Triangulation<2> tria_except_center;\r\n\r\n  GridGenerator :: hyper_ball(tria_except_center, center, outer_radius, true);\r\n  tria_except_center.reset_all_manifolds();\r\n  for (unsigned int step = 0; step <2; step++)\r\n  {\r\n    for (auto &cell : tria_except_center.active_cell_iterators())\r\n    {\r\n      if (std :: fabs(cell->center().norm() > 0))\r\n      {\r\n        tria_except_center.set_all_manifold_ids(0);\r\n        tria_except_center.set_manifold(0, manifold);\r\n        cell->refine_flag_set();\r\n      }\r\n      tria_except_center.refine_global();\r\n    }\r\n    tria_except_center.execute_coarsening_and_refinement();\r\n  }\r\n  std::ofstream out_except_center(\"grid-9.svg\");\r\n  grid_out.write_svg(tria_except_center, out_except_center);\r\n  std::cout << \"Grid written to grid-9.svg\" << std::endl;\r\n\r\n  \r\n}\r\n\r\n\r\nint main()\r\n{\r\n  first_grid();\r\n  second_grid();\r\n  third_grid();\r\n  spherical_grid();\r\n}\r\n\r\n", "meta": {"hexsha": "2631a5553b3f4828f3a8ae877a2c859bb45b36c8", "size": 8287, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/step-1.cc", "max_stars_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-GandhiYogesh", "max_stars_repo_head_hexsha": "b982a603f94dc8ba6f8d8bd435a5042e918b5f22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/step-1.cc", "max_issues_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-GandhiYogesh", "max_issues_repo_head_hexsha": "b982a603f94dc8ba6f8d8bd435a5042e918b5f22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/step-1.cc", "max_forks_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-GandhiYogesh", "max_forks_repo_head_hexsha": "b982a603f94dc8ba6f8d8bd435a5042e918b5f22", "max_forks_repo_licenses": ["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.3901515152, "max_line_length": 83, "alphanum_fraction": 0.6113189333, "num_tokens": 2153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.6210648304257694}}
{"text": "#include \"xpbd/green_strain_elastic_constraint.h\"\n\n#include <Eigen/Dense>\n#include <eigen/SVD>\n\nnamespace xpbd {\n\ngreen_strain_elastic_constraint_t::green_strain_elastic_constraint_t(\n    std::initializer_list<index_type> indices,\n    positions_type const& p,\n    scalar_type young_modulus,\n    scalar_type poisson_ratio,\n    scalar_type const alpha)\n    : base_type(indices, alpha), V0_{0.}, DmInv_{}, mu_{}, lambda_{}\n{\n    assert(indices.size() == 4u);\n\n    auto const v1 = this->indices().at(0);\n    auto const v2 = this->indices().at(1);\n    auto const v3 = this->indices().at(2);\n    auto const v4 = this->indices().at(3);\n\n    auto const p1 = p.row(v1);\n    auto const p2 = p.row(v2);\n    auto const p3 = p.row(v3);\n    auto const p4 = p.row(v4);\n\n    Eigen::Matrix3d Dm;\n    Dm.col(0) = (p1 - p4).transpose();\n    Dm.col(1) = (p2 - p4).transpose();\n    Dm.col(2) = (p3 - p4).transpose();\n\n    V0_     = (1. / 6.) * Dm.determinant();\n    DmInv_  = Dm.inverse();\n    mu_     = (young_modulus) / (2. * (1 + poisson_ratio));\n    lambda_ = (young_modulus * poisson_ratio) / ((1 + poisson_ratio) * (1 - 2 * poisson_ratio));\n}\n\ngreen_strain_elastic_constraint_t::scalar_type\ngreen_strain_elastic_constraint_t::signed_volume(positions_type const& V) const\n{\n    Eigen::RowVector3d const p1 = V.row(indices()[0]);\n    Eigen::RowVector3d const p2 = V.row(indices()[1]);\n    Eigen::RowVector3d const p3 = V.row(indices()[2]);\n    Eigen::RowVector3d const p4 = V.row(indices()[3]);\n\n    Eigen::Matrix3d Ds;\n    Ds.col(0)      = (p1 - p4).transpose();\n    Ds.col(1)      = (p2 - p4).transpose();\n    Ds.col(2)      = (p3 - p4).transpose();\n    auto const vol = (1. / 6.) * Ds.determinant();\n    return vol;\n}\n\nvoid green_strain_elastic_constraint_t::project(\n    positions_type& p,\n    masses_type const& m,\n    scalar_type& lagrange,\n    scalar_type const dt) const\n{\n    auto const v1 = this->indices().at(0);\n    auto const v2 = this->indices().at(1);\n    auto const v3 = this->indices().at(2);\n    auto const v4 = this->indices().at(3);\n\n    auto const p1 = p.row(v1);\n    auto const p2 = p.row(v2);\n    auto const p3 = p.row(v3);\n    auto const p4 = p.row(v4);\n\n    auto const w1 = 1. / m(v1);\n    auto const w2 = 1. / m(v2);\n    auto const w3 = 1. / m(v3);\n    auto const w4 = 1. / m(v4);\n\n    auto const Vsigned        = signed_volume(p);\n    bool const is_V_positive  = Vsigned >= 0.;\n    bool const is_V0_positive = V0_ >= 0.;\n    bool const is_tet_inverted =\n        (is_V_positive && !is_V0_positive) || (!is_V_positive && is_V0_positive);\n    scalar_type constexpr epsilon = 1e-20;\n\n    Eigen::Matrix3d Ds;\n    Ds.col(0) = (p1 - p4).transpose();\n    Ds.col(1) = (p2 - p4).transpose();\n    Ds.col(2) = (p3 - p4).transpose();\n\n    Eigen::Matrix3d const F = Ds * DmInv_;\n    Eigen::Matrix3d const I = Eigen::Matrix3d::Identity();\n\n    // TODO: Implement correct inversion handling described in\n    // Irving, Geoffrey, Joseph Teran, and Ronald Fedkiw. \"Invertible finite elements for robust\n    // simulation of large deformation.\" Proceedings of the 2004 ACM SIGGRAPH/Eurographics symposium\n    // on Computer animation. 2004.\n    // scalar_type psi{};\n    // Eigen::Matrix3d Piola;\n    Eigen::JacobiSVD<Eigen::Matrix3d> UFhatV(F, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::Vector3d const Fsigma = UFhatV.singularValues();\n    Eigen::Matrix3d Fhat;\n    Fhat.setZero();\n    Fhat(0, 0) = Fsigma(0);\n    Fhat(1, 1) = Fsigma(1);\n    Fhat(2, 2) = Fsigma(2);\n\n    Eigen::Matrix3d U       = UFhatV.matrixU();\n    Eigen::Matrix3d const V = UFhatV.matrixV();\n\n    if (is_tet_inverted)\n    {\n        Fhat(2, 2) = -Fhat(2, 2);\n        U.col(2)   = -U.col(2);\n    }\n\n    // stress reaches maximum at 58% compression\n    scalar_type constexpr min_singular_value = 0.577;\n    Fhat(0, 0)                               = std::max(Fhat(0, 0), min_singular_value);\n    Fhat(1, 1)                               = std::max(Fhat(1, 1), min_singular_value);\n    Fhat(2, 2)                               = std::max(Fhat(2, 2), min_singular_value);\n\n    Eigen::Matrix3d const Ehat     = 0.5 * (Fhat.transpose() * Fhat - I);\n    scalar_type const EhatTrace    = Ehat.trace();\n    Eigen::Matrix3d const Piolahat = Fhat * ((2. * mu_ * Ehat) + (lambda_ * EhatTrace * I));\n\n    Eigen::Matrix3d const E  = U * Ehat * V.transpose();\n    scalar_type const Etrace = E.trace();\n    scalar_type const psi = mu_ * (E.array() * E.array()).sum() + 0.5 * lambda_ * Etrace * Etrace;\n\n    Eigen::Matrix3d const Piola = U * Piolahat * V.transpose();\n\n    // H is the negative gradient of the elastic potential\n    scalar_type const V0     = std::abs(V0_);\n    Eigen::Matrix3d const H  = -V0 * Piola * DmInv_.transpose();\n    Eigen::Vector3d const f1 = H.col(0);\n    Eigen::Vector3d const f2 = H.col(1);\n    Eigen::Vector3d const f3 = H.col(2);\n    Eigen::Vector3d const f4 = -(f1 + f2 + f3);\n\n    // clang-format off\n     auto const weighted_sum_of_gradients =\n        w1 * f1.squaredNorm() +\n        w2 * f2.squaredNorm() +\n        w3 * f3.squaredNorm() +\n        w4 * f4.squaredNorm();\n    // clang-format on\n\n    if (weighted_sum_of_gradients < epsilon)\n        return;\n\n    scalar_type const C           = V0 * psi;\n    scalar_type const alpha_tilde = alpha_ / (dt * dt);\n    scalar_type const delta_lagrange =\n        -(C + alpha_tilde * lagrange) / (weighted_sum_of_gradients + alpha_tilde);\n\n    lagrange += delta_lagrange;\n    // because f = - grad(potential), then grad(potential) = -f and thus grad(C) = -f\n    p.row(v1) += w1 * -f1 * delta_lagrange;\n    p.row(v2) += w2 * -f2 * delta_lagrange;\n    p.row(v3) += w3 * -f3 * delta_lagrange;\n    p.row(v4) += w4 * -f4 * delta_lagrange;\n}\n\ngreen_strain_elastic_constraint_t::scalar_type\ngreen_strain_elastic_constraint_t::evaluate(positions_type const& p, masses_type const& m) const\n{\n    auto const v1 = this->indices().at(0);\n    auto const v2 = this->indices().at(1);\n    auto const v3 = this->indices().at(2);\n    auto const v4 = this->indices().at(3);\n\n    auto const p1 = p.row(v1);\n    auto const p2 = p.row(v2);\n    auto const p3 = p.row(v3);\n    auto const p4 = p.row(v4);\n\n    auto const w1 = 1. / m(v1);\n    auto const w2 = 1. / m(v2);\n    auto const w3 = 1. / m(v3);\n    auto const w4 = 1. / m(v4);\n\n    auto const Vsigned        = signed_volume(p);\n    bool const is_V_positive  = Vsigned >= 0.;\n    bool const is_V0_positive = V0_ >= 0.;\n    bool const is_tet_inverted =\n        (is_V_positive && !is_V0_positive) || (!is_V_positive && is_V0_positive);\n    scalar_type constexpr epsilon = 1e-20;\n\n    Eigen::Matrix3d Ds;\n    Ds.col(0) = (p1 - p4).transpose();\n    Ds.col(1) = (p2 - p4).transpose();\n    Ds.col(2) = (p3 - p4).transpose();\n\n    Eigen::Matrix3d const F = Ds * DmInv_;\n    Eigen::Matrix3d const I = Eigen::Matrix3d::Identity();\n\n    // TODO: Implement correct inversion handling described in\n    // Irving, Geoffrey, Joseph Teran, and Ronald Fedkiw. \"Invertible finite elements for robust\n    // simulation of large deformation.\" Proceedings of the 2004 ACM SIGGRAPH/Eurographics symposium\n    // on Computer animation. 2004.\n    // scalar_type psi{};\n    // Eigen::Matrix3d Piola;\n    Eigen::JacobiSVD<Eigen::Matrix3d> UFhatV(F, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::Vector3d const Fsigma = UFhatV.singularValues();\n    Eigen::Matrix3d Fhat;\n    Fhat.setZero();\n    Fhat(0, 0) = Fsigma(0);\n    Fhat(1, 1) = Fsigma(1);\n    Fhat(2, 2) = Fsigma(2);\n\n    Eigen::Matrix3d U       = UFhatV.matrixU();\n    Eigen::Matrix3d const V = UFhatV.matrixV();\n\n    if (is_tet_inverted)\n    {\n        Fhat(2, 2) = -Fhat(2, 2);\n        U.col(2)   = -U.col(2);\n    }\n\n    // stress reaches maximum at 58% compression\n    scalar_type constexpr min_singular_value = 0.577;\n    Fhat(0, 0)                               = std::max(Fhat(0, 0), min_singular_value);\n    Fhat(1, 1)                               = std::max(Fhat(1, 1), min_singular_value);\n    Fhat(2, 2)                               = std::max(Fhat(2, 2), min_singular_value);\n\n    Eigen::Matrix3d const Ehat     = 0.5 * (Fhat.transpose() * Fhat - I);\n    scalar_type const EhatTrace    = Ehat.trace();\n    Eigen::Matrix3d const Piolahat = Fhat * ((2. * mu_ * Ehat) + (lambda_ * EhatTrace * I));\n\n    Eigen::Matrix3d const E  = U * Ehat * V.transpose();\n    scalar_type const Etrace = E.trace();\n    scalar_type const psi = mu_ * (E.array() * E.array()).sum() + 0.5 * lambda_ * Etrace * Etrace;\n\n    scalar_type const V0 = std::abs(V0_);\n    scalar_type const C = V0 * psi;\n    return C;\n}\n\n} // namespace xpbd", "meta": {"hexsha": "c243964216b48414b85fce164e504d8927ba2f33", "size": 8528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/xpbd/green_strain_elastic_constraint.cpp", "max_stars_repo_name": "Q-Minh/position-based-dynamics", "max_stars_repo_head_hexsha": "23fcf93bddd5daf425cdc3443da05760cc1343ec", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T23:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:30:58.000Z", "max_issues_repo_path": "src/xpbd/green_strain_elastic_constraint.cpp", "max_issues_repo_name": "Q-Minh/position-based-dynamics", "max_issues_repo_head_hexsha": "23fcf93bddd5daf425cdc3443da05760cc1343ec", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/xpbd/green_strain_elastic_constraint.cpp", "max_forks_repo_name": "Q-Minh/position-based-dynamics", "max_forks_repo_head_hexsha": "23fcf93bddd5daf425cdc3443da05760cc1343ec", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9831223629, "max_line_length": 100, "alphanum_fraction": 0.6069418386, "num_tokens": 2725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666335, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.621064181435913}}
{"text": "#include <iostream>\n#include <cstdint>\n#include <Eigen/Dense>\n\n#include \"hnf.hpp\"\n\ntemplate<class Derived>\nbool is_rowHNF(const Eigen::MatrixBase<Derived> &mat) noexcept\n{\n    for(int i = 0, j = 0; j < mat.cols() && i < mat.rows(); ++j) {\n        for(int k = i+1; k < mat.rows(); ++k)\n            if (mat(k,j) != 0)\n                return false;\n        if (mat(i,j) != 0) {\n            for(int k = 0; k < i; ++k)\n                if (mat(k,j) < 0 || mat(i,j) < mat(k,j))\n                    return false;\n            ++i;\n        }\n    }\n\n    return true;\n}\n\ntemplate<class Derived>\nbool is_colHNF(const Eigen::MatrixBase<Derived> &mat) noexcept\n{\n    return is_rowHNF(mat.transpose().eval());\n}\n\ntemplate<class Derived>\nbool is_unimodular(const Eigen::MatrixBase<Derived> &mat) noexcept\n{\n    return std::abs(mat.determinant()) == 1;\n}\n\nint main(int argc, char*argv[])\n{\n    std::cout << \"==========\" << std::endl;\n    std::cout << \"Invalid size matrices should be rejected.\" << std::endl;\n    std::cout << \"==========\" << std::endl;\n    {\n        using namespace khover;\n\n        Eigen::Matrix<int,6,4> mat, a, b;\n        Eigen::Matrix<int,4,6> c, d;\n        Eigen::Matrix<int,3,3> e;\n\n        auto fst = hnf_LLL<rowops>(mat,std::tie(b,c,d),std::tie(a,b));\n        auto snd = hnf_LLL<rowops>(mat,std::tie(c,d),std::tie(a,b,c));\n        auto trd = hnf_LLL<colops>(mat,std::tie(c,d,e),std::tie(a,b));\n        auto fth = hnf_LLL<colops>(mat,std::tie(c,d),std::tie(e,a,b));\n\n        if(fst || snd || trd || fth)\n        {\n            std::cout << \"Failed to detect wrong size matrices\" << std::endl;\n            return -1;\n        }\n    }\n\n    std::cout << \"==========\" << std::endl;\n    std::cout << \"Row HNF\" << std::endl;\n    std::cout << \"==========\" << std::endl;\n    {\n        Eigen::Matrix<std::int64_t, 3,4> mat0;\n        mat0 <<\n            1, 2, 3, 4,\n            5, 6, 7, 8,\n            9, 10, 11, 12;\n        auto mat = mat0;\n        auto u = Eigen::Matrix<std::int64_t,3,3>::Identity().eval();\n        auto rk = khover::hnf_LLL<typename khover::rowops>(mat,std::tie(u),std::tuple<>{});\n\n        if (!is_rowHNF(mat) || u*mat != mat0 || !is_unimodular(u) || !rk || *rk!=2)\n        {\n            std::cout << \"mat=\" << std::endl;\n            std::cout << mat << std::endl;\n            std::cout << std::endl;\n            std::cout << \"u=\" << std::endl;\n            std::cout << u << std::endl;\n            std::cout << \"rk=\" << (rk ? *rk : -1) << std::endl;\n            std::cout << \"u*mat=\" << std::endl;\n            std::cout << u*mat << std::endl;\n            return -1;\n        }\n    }\n    {\n        Eigen::Matrix<std::int64_t, 3,4> mat0;\n        mat0 <<\n            0, 1, 2, 3,\n            4, 5, 6, 7,\n            8, 9,10,11;\n        auto mat = mat0;\n        auto u = Eigen::Matrix<std::int64_t,3,3>::Identity().eval();\n        auto rk = khover::hnf_LLL<typename khover::rowops>(mat,std::tie(u),std::tuple<>{});\n\n        if (!is_rowHNF(mat) || u*mat != mat0 || !is_unimodular(u) || !rk || *rk!=2)\n        {\n            std::cout << \"mat=\" << std::endl;\n            std::cout << mat << std::endl;\n            std::cout << std::endl;\n            std::cout << \"u=\" << std::endl;\n            std::cout << u << std::endl;\n            std::cout << \"rk=\" << (rk ? *rk : -1) << std::endl;\n            std::cout << \"u*mat=\" << std::endl;\n            std::cout << u*mat << std::endl;\n            return -1;\n        }\n    }\n\n    std::cout << \"==========\" << std::endl;\n    std::cout << \"Column HNF\" << std::endl;\n    std::cout << \"==========\" << std::endl;\n    {\n        Eigen::Matrix<std::int64_t, 5,4> mat0;\n        mat0 <<\n            1, 2, 4, 7,\n            2, 3, 4, 5,\n            6, 7, 8, 9,\n            1, 1, 2, 3,\n            5, 8, 13, 21;\n        auto mat = mat0;\n        Eigen::Matrix<std::int64_t,4,4> u = decltype(u)::Identity();\n        Eigen::Matrix<std::int64_t,4,4> v = decltype(v)::Identity();\n        auto rk = khover::hnf_LLL<typename khover::colops>(mat,std::tie(u),std::tie(v));\n\n        if (!is_colHNF(mat) || mat*u != mat0\n            || v*u != Eigen::Matrix<std::int64_t,4,4>::Identity()\n            || !rk || *rk != 4)\n        {\n            std::cout << \"mat=\" << std::endl;\n            std::cout << mat << std::endl;\n            std::cout << std::endl;\n            std::cout << \"u=\" << std::endl;\n            std::cout << u << std::endl;\n            std::cout << \"rk=\" << (rk ? *rk : -1) << std::endl;\n            return -1;\n        }\n    }\n    {\n        Eigen::Matrix<std::int64_t,3,3> mat0;\n        mat0 <<\n            1, 1, 0,\n           -1, 0, 1,\n            0,-1,-1;\n\n        Eigen::Matrix<std::int64_t,3,3> u0;\n        u0 <<\n            1, 0, 0,\n           -1, 1, 0,\n            1, 0, 1;\n        decltype(mat0) mat = mat0;\n        decltype(u0) u = u0;\n        Eigen::Matrix<std::int64_t,3,3> v = decltype(v)::Identity();\n        auto rk = khover::hnf_LLL<typename khover::colops>(\n            mat,std::tie(u),std::tie(v));\n\n        if (!is_colHNF(mat) || mat*u != mat0*u0\n            || v*u != u0\n            || !rk || *rk != 2)\n        {\n            ERR_MSG(\n                \"mat=\\n\" << mat << std::endl\n                << \"u=\\n\" << u << std::endl\n                << \"v=\\n\" << v << std::endl\n                << \"rk=\" << (rk ? *rk : -1) << std::endl\n                << \"mat0*u0=\\n\" << mat0*u0 << std::endl\n                << \"mat*u=\\n\" << mat*u << std::endl\n                << \"v*u=\\n\" << v*u\n                );\n            return -1;\n        }\n    }\n    {\n        Eigen::Matrix<std::int64_t, 3,4> mat0;\n        mat0 <<\n            0, 1, 2, 3,\n            4, 5, 6, 7,\n            8, 9,10,11;\n        auto mat = mat0;\n        auto u = Eigen::Matrix<std::int64_t,4,4>::Identity().eval();\n        auto rk = khover::hnf_LLL<typename khover::colops>(mat,std::tie(u),std::tuple<>{});\n\n        if (!is_colHNF(mat) || mat*u != mat0 || !is_unimodular(u) || !rk || *rk!=2)\n        {\n            ERR_MSG(\n                \"mat=\\n\" << mat << std::endl\n                << \"u=\\n\" << u << std::endl\n                << \"rk=\" << (rk ? *rk : -1) << std::endl\n                << \"mat*u=\\n\" << mat*u\n                );\n            return -1;\n        }\n    }\n    {\n        Eigen::Matrix<std::int64_t, 9,27> mat0;\n        mat0 <<\n            1, 0, 0, 0, 0, 1, 0, 1, 3, 0, 0, 1, 0, 0, 0,-1, 0, 0, 0, 1, 3,-1, 0, 0,-3, 0, 0,\n            0, 1, 0, 1, 0,-3, 0,-3,-8, 1, 0,-3, 0, 0, 0, 0,-1, 0, 0,-3,-8, 0,-1, 0, 0,-3, 0,\n            0, 0, 1, 0, 1, 3, 1, 3, 6, 0, 1, 3, 0, 0, 0, 0, 0,-1, 1, 3, 6, 0, 0,-1, 0, 0,-3,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 1, 3, 0, 0, 0, 3, 1, 3, 8, 0, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0,-6, 0, 0,-8, 0, 0, 0, 0, 0,-8, 0, 8, 0,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 1, 3, 9, 0, 0, 0, 1, 3, 9, 0, 0, 8,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0,-3, 0, 1, 0, 0, 0,-3, 0, 1,-6, 2, 6,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 1,-3,-3, 0, 0, 0, 1,-3,-3, 0,-12,-16,\n            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 2, 6, 6;\n        auto mat = mat0;\n        auto u = Eigen::Matrix<std::int64_t,27,27>::Identity().eval();\n        auto v = Eigen::Matrix<std::int64_t,27,27>::Identity().eval();\n        auto rk = khover::hnf_LLL<khover::colops>(mat,std::tie(u),std::tie(v));\n\n        if (!is_colHNF(mat)\n            || mat*u != mat0\n            || !(u*v).isIdentity() ||\n            !rk || *rk!=7)\n        {\n            ERR_MSG(\n                \"mat=\\n\" << mat << std::endl\n                << \"u=\\n\" << u << std::endl\n                << \"rk=\" << (rk ? *rk : -1) << std::endl\n                << \"mat*u=\\n\" << mat*u\n                );\n            return -1;\n        }\n        std::cout << mat.leftCols(1+*rk) << std::endl;\n    }\n\n    std::cout << \"==========\" << std::endl;\n    std::cout << \"HNF of zero matrices\" << std::endl;\n    std::cout << \"==========\" << std::endl;\n    {\n        using matrix_t = Eigen::Matrix<std::int64_t,Eigen::Dynamic,Eigen::Dynamic>;\n        matrix_t zmat;\n\n        for(std::size_t r = 0; r < 5; ++r) {\n            for(std::size_t c = 0; c < 5; ++c) {\n                // test row HNF\n                zmat = matrix_t::Zero(r,c);\n                auto rowrk = khover::hnf_LLL<khover::rowops>(zmat, {}, {});\n                if (!rowrk || *rowrk != 0 || !zmat.isZero()) {\n                    std::cout << \"row HNF of zero is not zero!\" << std::endl;\n                    std::cout << \"rk=\" << (rowrk ? *rowrk : -1) << std::endl;\n                    std::cout << zmat << std::endl;\n                    return -1;\n                }\n                // test column HNF\n                zmat.setZero();\n                auto colrk = khover::hnf_LLL<khover::colops>(zmat, {}, {});\n                if (!colrk || *colrk!=0 || !zmat.isZero()) {\n                    std::cout << \"column HNF of zero is not zero!\" << std::endl;\n                    std::cout << \"rk=\" << (colrk ? *colrk : -1) << std::endl;\n                    std::cout << zmat << std::endl;\n                    return -1;\n                }\n            }\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "6c19efde8d44417c34bc64091369705428402ee0", "size": 9113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/hnf_test.cpp", "max_stars_repo_name": "Junology/khover", "max_stars_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T06:48:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T06:50:39.000Z", "max_issues_repo_path": "test/hnf_test.cpp", "max_issues_repo_name": "Junology/khover", "max_issues_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/hnf_test.cpp", "max_forks_repo_name": "Junology/khover", "max_forks_repo_head_hexsha": "1970689d4505ddd0887ec4f44888f91af816eae0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9157088123, "max_line_length": 94, "alphanum_fraction": 0.4019532536, "num_tokens": 3299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.621064172850574}}
{"text": "#pragma once\n#include <tuple>\n#include <vector>\n#include <Eigen/Dense>\n\n\ntypedef std::tuple<double, double, double, double, double> quintet;\ntypedef std::tuple<std::vector<double>, double, double, double, double>\n        vquintet;\n\n\n// user interface\n\nnamespace fine {\nEigen::VectorXd heston_formula(std::vector<double> strikes,\n                               std::vector<double> maturities,\n                               double underlying_price, double volatility,\n                               double interest_rate, double kappa, double theta,\n                               double nu, double rho);\n\nEigen::VectorXd heston_delta(std::vector<double> strikes,\n                             std::vector<double> maturities,\n                             double underlying_price, double volatility,\n                             double interest_rate, double kappa, double theta,\n                             double nu, double rho);\n\nEigen::VectorXd heston_vega(std::vector<double> strikes,\n                            std::vector<double> maturities,\n                            double underlying_price, double volatility,\n                            double interest_rate, double kappa, double theta,\n                            double nu, double rho);\n\nquintet heston_calibration(std::vector<double> prices,\n                           std::vector<double> strikes,\n                           std::vector<double> maturities,\n                           double underlying_price,\n                           double interest_rate);\n\nvquintet heston_calibration_ts(std::vector<double> prices,\n                               std::vector<double> strikes,\n                               std::vector<double> maturities,\n                               std::vector<double> underlying_prices,\n                               double interest_rate);\n\ndouble heston_calibrate_vol(std::vector<double> prices,\n                            std::vector<double> strikes,\n                            std::vector<double> maturities,\n                            double underlying_price, double interest_rate,\n                            double kappa, double theta, double nu, double rho);\n}\n", "meta": {"hexsha": "96f8b3566b7125b954762c374fdf0d8858249e66", "size": 2159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cppfine/fine.hpp", "max_stars_repo_name": "dougmvieira/fine", "max_stars_repo_head_hexsha": "ac00d9e0f3cda26b97bafbc9fa2d41dab233bc40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cppfine/fine.hpp", "max_issues_repo_name": "dougmvieira/fine", "max_issues_repo_head_hexsha": "ac00d9e0f3cda26b97bafbc9fa2d41dab233bc40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppfine/fine.hpp", "max_forks_repo_name": "dougmvieira/fine", "max_forks_repo_head_hexsha": "ac00d9e0f3cda26b97bafbc9fa2d41dab233bc40", "max_forks_repo_licenses": ["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.3333333333, "max_line_length": 80, "alphanum_fraction": 0.5340435387, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.6210641716373263}}
{"text": "\n\n#ifndef SIMPLEMLP_HPP\n#define SIMPLEMLP_HPP\n\n#include <string>\n#include <vector>\n#include <Eigen/Dense>\n#include <cstdlib>\n#include \"iostream\"\n#include <fstream>\n#include <cmath>\n\nnamespace rai {\n\nnamespace FuncApprox {\n\nenum class ActivationType {\n  linear,\n  relu,\n  tanh,\n  softsign\n};\n\ntemplate<typename Dtype, ActivationType activationType>\nstruct Activation {\n  inline void nonlinearity(Eigen::Matrix<Dtype, -1, -1> &output) {}\n  inline void nonlinearity(Eigen::Matrix<Dtype, -1, 1> &output) {}\n};\n\ntemplate<typename Dtype>\nstruct Activation<Dtype, ActivationType::relu> {\n  inline void nonlinearity(Eigen::Matrix<Dtype, -1, -1> &output) {\n    output = output.cwiseMax(0.0);\n  }\n\n  inline void nonlinearity(Eigen::Matrix<Dtype, -1, 1> &output) {\n    output = output.cwiseMax(0.0);\n  }\n};\n\ntemplate<typename Dtype>\nstruct Activation<Dtype, ActivationType::tanh> {\n  inline void nonlinearity(Eigen::Matrix<Dtype, -1, -1> &output) {\n    output = output.array().tanh();\n  }\n  inline void nonlinearity(Eigen::Matrix<Dtype, -1, 1> &output) {\n    output = output.array().tanh();\n  }\n};\n\ntemplate<typename Dtype>\nstruct Activation<Dtype, ActivationType::softsign> {\n  inline void nonlinearity(Eigen::Matrix<Dtype, -1, -1> &output) {\n    for (int i = 0; i < output.size(); i++) {\n      output[i] = output[i] / (std::abs(output[i]) + 1.0);\n    }\n  }\n\n  inline void nonlinearity(Eigen::Matrix<Dtype, -1, 1> &output) {\n    for (int i = 0; i < output.size(); i++) {\n      output[i] = output[i] / (std::abs(output[i]) + 1.0);\n    }\n  }\n};\n\ntemplate<typename Dtype, int StateDim, int ActionDim, ActivationType activationType>\nclass MLP_fullyconnected {\n\n public:\n  typedef Eigen::Matrix<Dtype, ActionDim, 1> Action;\n  typedef Eigen::Matrix<Dtype, StateDim, 1> State;\n\n  MLP_fullyconnected(std::vector<int> hiddensizes) {\n    const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \"\\n\");\n\n    layersizes.push_back(StateDim);\n    layersizes.reserve(layersizes.size() + hiddensizes.size());\n    layersizes.insert(layersizes.end(), hiddensizes.begin(), hiddensizes.end());\n    layersizes.push_back(ActionDim);\n    ///[input hidden output]\n\n    params.resize(2 * (layersizes.size() - 1));\n    Ws.resize(layersizes.size() - 1);\n    bs.resize(layersizes.size() - 1);\n    lo.resize(layersizes.size());\n    Stdev.resize(ActionDim);\n\n    for (int i = 0; i < params.size(); i++) {\n      int paramSize = 0;\n\n      if (i % 2 == 0) ///W resize\n      {\n        Ws[i / 2].resize(layersizes[i / 2 + 1], layersizes[i / 2]);\n        params[i].resize(layersizes[i / 2] * layersizes[i / 2 + 1]);\n      }\n      if (i % 2 == 1) ///b resize\n      {\n        bs[(i - 1) / 2].resize(layersizes[(i + 1) / 2]);\n        params[i].resize(layersizes[(i + 1) / 2]);\n      }\n    }\n\n  }\n\n  bool load_eigen_from_binary(const std::string filename, Eigen::Matrix<Dtype, Eigen::Dynamic, Eigen::Dynamic> &data) {\n    std::ifstream in(filename, std::ios::in | std::ios::binary);\n    if (!in.is_open()) {\n      return false;\n    }\n    size_t rows = 0;\n    size_t cols = 0;\n    in.read((char *) (&rows), sizeof(size_t));\n    in.read((char *) (&cols), sizeof(size_t));\n    data.resize(rows, cols);\n    in.read((char *) data.data(), rows * cols * sizeof(Dtype));\n\n    in.close();\n    return true;\n  }\n\n  void updateParamFromBin(std::string fileName) {\n    Eigen::Matrix<Dtype, -1, -1> temp;\n    load_eigen_from_binary(fileName, temp);\n\n    size_t pos = 0;\n\n    for (int i = 0; i < params.size(); i++) {\n      int paramSize = 0;\n      for (size_t j = 0; j < params[i].size(); j++) {\n        params[i](j) = temp.data()[pos++];\n      }\n      if (i % 2 == 0) ///W copy\n      {\n        memcpy(Ws[i / 2].data(), params[i].data(), sizeof(Dtype) * Ws[i / 2].size());\n      }\n      if (i % 2 == 1) ///b copy\n      {\n        memcpy(bs[(i - 1) / 2].data(), params[i].data(), sizeof(Dtype) * bs[(i - 1) / 2].size());\n      }\n    }\n  }\n\n  void updateParamFromBin_noesis(std::string fileName) {\n    Eigen::Matrix<Dtype, -1, -1> temp;\n    load_eigen_from_binary(fileName, temp);\n\n    for (int i = 0; i < params.size(); i++) {\n      int paramSize = 0;\n\n      if (i % 2 == 0) ///W resize\n      {\n        Ws[i / 2].resize(layersizes[i / 2 + 1], layersizes[i / 2]);\n        params[i].resize(layersizes[i / 2] * layersizes[i / 2 + 1]);\n      }\n      if (i % 2 == 1) ///b resize\n      {\n        bs[(i - 1) / 2].resize(layersizes[(i + 1) / 2]);\n        params[i].resize(layersizes[(i + 1) / 2]);\n      }\n    }\n\n\n\n    /// output layer\n\n    size_t pos = 0;\n\n    // Wo\n    for (size_t j = 0; j <params.end()[-2].size(); j++) {\n      params.end()[-2](j) = temp.data()[pos++];\n    }\n\n    // bo\n    for (size_t j = 0; j <params.end()[-1].size(); j++) {\n      params.end()[-1](j) = temp.data()[pos++];\n    }\n\n    memcpy(Ws.back().data(), params.end()[-2].data(), sizeof(Dtype) * Ws.back().size());\n    memcpy(bs.back().data(), params.end()[-1].data(), sizeof(Dtype) * bs.back().size());\n\n\n    for (int i = 0; i < params.size() - 2; i++) {\n      int paramSize = 0;\n      for (size_t j = 0; j < params[i].size(); j++) {\n        params[i](j) = temp.data()[pos++];\n      }\n      if (i % 2 == 0) ///W copy\n      {\n        memcpy(Ws[i / 2].data(), params[i].data(), sizeof(Dtype) * Ws[i / 2].size());\n      }\n      if (i % 2 == 1) ///b copy\n      {\n        memcpy(bs[(i - 1) / 2].data(), params[i].data(), sizeof(Dtype) * bs[(i - 1) / 2].size());\n      }\n    }\n  }\n\n\n  void updateParamFromTxt(std::string fileName) {\n    const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \"\\n\");\n\n    std::ifstream indata;\n    indata.open(fileName);\n    std::string line;\n    getline(indata, line);\n    std::stringstream lineStream(line);\n    std::string cell;\n\n    int totalN = 0;\n    ///assign parameters\n    for (int i = 0; i < params.size(); i++) {\n      int paramSize = 0;\n\n      while (std::getline(lineStream, cell, ',')) { ///Read param\n        params[i](paramSize++) = std::stod(cell);\n        if (paramSize == params[i].size()) break;\n      }\n      totalN += paramSize;\n      if (i % 2 == 0) ///W copy\n        memcpy(Ws[i / 2].data(), params[i].data(), sizeof(Dtype) * Ws[i / 2].size());\n      if (i % 2 == 1) ///b copy\n        memcpy(bs[(i - 1) / 2].data(), params[i].data(), sizeof(Dtype) * bs[(i - 1) / 2].size());\n    }\n\n  }\n\n  inline Action forward(State &state) {\n\n    lo[0] = state;\n\n    for (int cnt = 0; cnt < Ws.size() - 1; cnt++) {\n      lo[cnt + 1] = Ws[cnt] * lo[cnt] + bs[cnt];\n      activation_.nonlinearity(lo[cnt + 1]);\n    }\n\n    lo[lo.size() - 1] = Ws[Ws.size() - 1] * lo[lo.size() - 2] + bs[bs.size() - 1]; /// output layer\n    return lo.back();\n  }\n\n\n  inline Action forwardtemp(State &state) {\n    Eigen::Matrix<Dtype, -1, 1> temp;\n    temp = state;\n\n    for (int cnt = 0; cnt < Ws.size() - 1; cnt++) {\n      temp = Ws[cnt] * temp + bs[cnt];\n      activation_.nonlinearity(temp);\n    }\n    temp = Ws.back() * temp + bs.back(); /// output layer\n    return temp;\n  }\n\n private:\n  std::vector<Eigen::Matrix<Dtype, -1, 1>> params;\n  std::vector<Eigen::Matrix<Dtype, -1, -1>> Ws;\n  std::vector<Eigen::Matrix<Dtype, -1, 1>> bs;\n  std::vector<Eigen::Matrix<Dtype, -1, 1>> lo;\n\n  Activation<Dtype, activationType> activation_;\n  Action Stdev;\n\n  std::vector<int> layersizes;\n  bool isTanh = false;\n};\n\n}\n\n}\n\n#endif //SIMPLEMLP_HPP\n", "meta": {"hexsha": "bcdb3c8c56d24774b2e924d863673e069db4710b", "size": 7327, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common/SimpleMLPLayer.hpp", "max_stars_repo_name": "xdaNvidia/learning_quadrupedal_locomotion_over_challenging_terrain_supplementary", "max_stars_repo_head_hexsha": "2f94b13455ff16e26d1acd6a984f1f88f7824e31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 94.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T08:47:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:33:49.000Z", "max_issues_repo_path": "include/common/SimpleMLPLayer.hpp", "max_issues_repo_name": "lixuechuan123/learning_quadrupedal_locomotion_over_challenging_terrain_supplementary", "max_issues_repo_head_hexsha": "277d19b007fd3109956d1ea0cc9e0cd50d3ecb5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-25T09:41:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-04T06:58:11.000Z", "max_forks_repo_path": "include/common/SimpleMLPLayer.hpp", "max_forks_repo_name": "lixuechuan123/learning_quadrupedal_locomotion_over_challenging_terrain_supplementary", "max_forks_repo_head_hexsha": "277d19b007fd3109956d1ea0cc9e0cd50d3ecb5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2020-10-22T13:36:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T01:17:14.000Z", "avg_line_length": 26.9375, "max_line_length": 119, "alphanum_fraction": 0.5638051044, "num_tokens": 2315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6210641618387397}}
{"text": "/**\n * expression test\n * @author Tobias Weber <tweber@ill.fr>\n * @date 28-mar-20\n * @license GPLv3, see 'LICENSE' file\n *\n * g++-10 -std=c++20 -I.. -o expr expr.cpp ../libs/log.cpp\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE Expr Test\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n\n#include \"libs/expr.h\"\n#include \"libs/str.h\"\n#include \"libs/maths.h\"\n\n\nusing t_types_real = std::tuple<double, float>;\nusing t_types_int = std::tuple<int, long>;\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_expr_real, t_real, t_types_real)\n{\n\tstatic constexpr t_real eps = 1e-6;\n\ttl2::ExprParser<t_real> parser;\n\n\tbool ok = parser.parse(\"1 + 2*3\");\n\tauto result = parser.eval();\n\tBOOST_TEST(ok);\n\tBOOST_TEST(tl2::equals<t_real>(result, 7, eps));\n\n\tok = parser.parse(\"4 + 5*6\");\n\tresult = parser.eval();\n\tBOOST_TEST(ok);\n\tBOOST_TEST(tl2::equals<t_real>(result, 34, eps));\n\n\tok = parser.parse(\" - (sqrt(4)-5)^3 -  5/2 \");\n\tresult = parser.eval();\n\tBOOST_TEST(ok);\n\tBOOST_TEST(tl2::equals<t_real>(result, 24.5, eps));\n\n\tok = parser.parse(\"-cos(sin(1.23*pi))^(-1.2 + 3.2)\");\n\tresult = parser.eval();\n\tBOOST_TEST(ok);\n\tBOOST_TEST(tl2::equals<t_real>(result, -0.6228, 1e-3));\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_expr_func, t_real, t_types_real)\n{\n\tstatic constexpr t_real eps = 1e-6;\n\tauto tupres = tl2::eval_expr<std::string, t_real>(\"\\t2 + \\t2*3*4\\n\");\n\n\tBOOST_TEST(\n\t\tstd::get<0>(tupres),\n\t\ttl2::equals<t_real>(std::get<1>(tupres), 14., eps));\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_expr_int, t_int, t_types_int)\n{\n\ttl2::ExprParser<t_int> parser;\n\n\tbool ok = parser.parse(\"1 + 2*3\");\n\tt_int result = parser.eval();\n\tBOOST_TEST(ok);\n\tBOOST_TEST(result == 7);\n\n\tok = parser.parse(\"4 + 5*6\");\n\tresult = parser.eval();\n\tBOOST_TEST(ok);\n\tBOOST_TEST(result == 34);\n}\n", "meta": {"hexsha": "8e4ace232e91718e0f3ed3f34f04ae837bbf0a58", "size": 2820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/expr.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/expr.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/expr.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 29.0721649485, "max_line_length": 79, "alphanum_fraction": 0.6439716312, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424334245618, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6210228688522197}}
{"text": "/*\n * concatenate Eigen matrices\n * by R. Falque\n * 03/07/2019\n */\n\n#ifndef EIGEN_FIND_HPP\n#define EIGEN_FIND_HPP\n\n#include <iostream>\n#include <Eigen/Core>\n\n\n\n// https://stackoverflow.com/a/21496281/2562693\n//template <typename T>\n//inline Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> concatenate(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> in_1, \n//                                                                    Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> in_2, \n//                                                                    int direction);\n\ntemplate <typename T>\ninline Eigen::VectorXi find(Eigen::Matrix<T, Eigen::Dynamic, 1> X, T x){\n    Eigen::VectorXi elements( (X.array() == x).count() );\n\n    int counter =0;\n    for (int i=0; i<X.rows(); i++)\n        if (X(i) == x) {\n            elements(counter) = i;\n            counter ++;\n        }\n    return elements;\n};\n\ntemplate <typename T>\ninline Eigen::VectorXi find(Eigen::Matrix<T, 1, Eigen::Dynamic> X, T x){\n    Eigen::VectorXi elements( (X.array() == x).count() );\n\n    int counter =0;\n    for (int i=0; i<X.rows(); i++)\n        if (X(i) == x) {\n            elements(counter) = i;\n            counter ++;\n        }\n    return elements;\n};\n\n\ntemplate <typename T>\ninline Eigen::Matrix<T, 1, Eigen::Dynamic> boolean_selection(Eigen::Matrix<T, 1, Eigen::Dynamic> X, Eigen::VectorXi selection){\n    \n    std::vector <T> vector_handle;\n\n    int counter =0;\n    for (int i=0; i<X.rows(); i++)\n        if (selection(i) == 1) \n            vector_handle.push_back(X(i));\n\n    Eigen::Matrix<T, 1, Eigen::Dynamic> elements = Eigen::Map<Eigen::Matrix<T, 1, Eigen::Dynamic>, Eigen::Unaligned>(vector_handle.data(), vector_handle.size());\n\n    return elements;\n};\n\ninline Eigen::VectorXd index_slice(Eigen::VectorXd X, Eigen::VectorXi selection){\n    Eigen::VectorXd out;\n    out.resize(selection.cols());\n\n    for (int i=0; i<selection.cols(); i++)\n        out(i) = X(selection(i));\n\n    return out;\n};\n\n//https://stackoverflow.com/a/21068014/2562693\ntemplate <typename T>\ninline void removeRow(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& matrix, unsigned int rowToRemove)\n{\n    unsigned int numRows = matrix.rows()-1;\n    unsigned int numCols = matrix.cols();\n\n    if( rowToRemove < numRows )\n        matrix.block(rowToRemove,0,numRows-rowToRemove,numCols) = matrix.block(rowToRemove+1,0,numRows-rowToRemove,numCols);\n\n    matrix.conservativeResize(numRows,numCols);\n}\n\ntemplate <typename T>\ninline void removeCol(Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& matrix, unsigned int colToRemove)\n{\n    unsigned int numRows = matrix.rows();\n    unsigned int numCols = matrix.cols()-1;\n\n    if( colToRemove < numCols )\n        matrix.block(0,colToRemove,numRows,numCols-colToRemove) = matrix.block(0,colToRemove+1,numRows,numCols-colToRemove);\n\n    matrix.conservativeResize(numRows,numCols);\n}\n\n#endif\n", "meta": {"hexsha": "1a765d60193f840760cd9154c00bf841c746c1ca", "size": 2884, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/EigenTools/find.hpp", "max_stars_repo_name": "rFalque/normals_transfer", "max_stars_repo_head_hexsha": "c0c27fb6e3bce32123489442f3b606f9be00b56e", "max_stars_repo_licenses": ["MIT"], "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/EigenTools/find.hpp", "max_issues_repo_name": "rFalque/normals_transfer", "max_issues_repo_head_hexsha": "c0c27fb6e3bce32123489442f3b606f9be00b56e", "max_issues_repo_licenses": ["MIT"], "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/EigenTools/find.hpp", "max_forks_repo_name": "rFalque/normals_transfer", "max_forks_repo_head_hexsha": "c0c27fb6e3bce32123489442f3b606f9be00b56e", "max_forks_repo_licenses": ["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.1313131313, "max_line_length": 161, "alphanum_fraction": 0.6217059639, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.6210228661386428}}
{"text": "#include <Eigen/Core>\n#include <catch2/catch.hpp>\n#include <random>\n#include <vector>\n#include \"ear/common/geom.hpp\"\n#include \"ear/common_types.hpp\"\n\nusing namespace ear;\n\nTEST_CASE(\"PolarPosition\") {\n  auto position = GENERATE(std::make_pair(0.0, 0.0), std::make_pair(0.0, 30.0),\n                           std::make_pair(30.0, 0.0));\n  double az = position.first;\n  double el = position.second;\n  REQUIRE(toCartesianVector3d(PolarPosition(az, el, 1.0))\n              .isApprox(cart(az, el, 1.0)));\n  REQUIRE(toCartesianVector3d(PolarPosition(az, el, 2.0))\n              .isApprox(cart(az, el, 2.0)));\n  REQUIRE(toNormalisedVector3d(PolarPosition(az, el, 2.0))\n              .isApprox(cart(az, el, 1.0)));\n}\n\nTEST_CASE(\"cart\") {\n  REQUIRE(cart(0.0, 0.0, 1.0).isApprox(Eigen::Vector3d(0.0, 1.0, 0.0)));\n  REQUIRE(cart(0.0, 0.0, 2.0).isApprox(Eigen::Vector3d(0.0, 2.0, 0.0)));\n  REQUIRE(cart(0.0, 45.0, sqrt(2.0)).isApprox(Eigen::Vector3d(0.0, 1.0, 1.0)));\n  REQUIRE(cart(45.0, 0.0, sqrt(2.0)).isApprox(Eigen::Vector3d(-1.0, 1.0, 0.0)));\n}\n\nTEST_CASE(\"test_azimuth\") {\n  REQUIRE(azimuth(Eigen::Vector3d(1.0, 1.0, 0.0)) == Approx(-45.0));\n}\n\nTEST_CASE(\"test_elevation\") {\n  REQUIRE(elevation(Eigen::Vector3d(0.0, 1.0, 1.0)) == Approx(45.0));\n  REQUIRE(elevation(Eigen::Vector3d(std::sqrt(2.0), std::sqrt(2.0), 2.0)) ==\n          Approx(45.0));\n}\n\nTEST_CASE(\"test_relative_angle\") {\n  REQUIRE(relativeAngle(0.0, 10.0) == 10.0);\n  REQUIRE(relativeAngle(10.0, 10.0) == 10.0);\n  REQUIRE(relativeAngle(11.0, 10.0) == 370.0);\n  REQUIRE(relativeAngle(370.0, 10.0) == 370.0);\n  REQUIRE(relativeAngle(371.0, 10.0) == 360.0 + 370.0);\n}\n\nTEST_CASE(\"test_inside_angle_range\") {\n  REQUIRE(insideAngleRange(0, 0, 10));\n  REQUIRE(insideAngleRange(5, 0, 10));\n  REQUIRE(insideAngleRange(10, 0, 10));\n\n  REQUIRE(insideAngleRange(0, 10, 00));\n  REQUIRE(!insideAngleRange(5, 10, 0));\n  REQUIRE(insideAngleRange(15, 10, 0));\n  REQUIRE(insideAngleRange(10, 10, 0));\n\n  REQUIRE(insideAngleRange(0, -10, 10));\n  REQUIRE(!insideAngleRange(180, -10, 10));\n  REQUIRE(!insideAngleRange(-180, -10, 10));\n\n  REQUIRE(insideAngleRange(0, -180, 180));\n  REQUIRE(!insideAngleRange(0, -181, 181));\n  REQUIRE(insideAngleRange(0, -180, 180, 1));\n\n  REQUIRE(insideAngleRange(180, 180, -180));\n  REQUIRE(insideAngleRange(180, 180, -180, 1));\n  REQUIRE(!insideAngleRange(90, 180, -180));\n\n  REQUIRE(insideAngleRange(0, 0, 0));\n  REQUIRE(insideAngleRange(0, 0, 0, 1));\n  REQUIRE(!insideAngleRange(90, 0, 0));\n\n  REQUIRE(insideAngleRange(0, 1, 2, 2));\n  REQUIRE(insideAngleRange(-1, 1, 2, 2));\n  REQUIRE(insideAngleRange(359, 1, 2, 2));\n}\n\n/** @brief Are a and b the same, module some reversal or shift? */\nbool inSameOrder(Eigen::MatrixXd a, Eigen::MatrixXd b) {\n  // just produce all shifted and reversed versions of a, and compare\n  // against b. Inefficient but simple.\n  Eigen::MatrixXd a_shifted(a.rows(), a.cols());\n  Eigen::MatrixXd a_shifted_rev(a.rows(), a.cols());\n  Eigen::VectorXi indices(a.rows());\n  for (int offset = 0; offset < a.rows(); ++offset) {\n    a_shifted << a.bottomRows(a.rows() - offset), a.topRows(offset);\n    if (a_shifted.isApprox(b)) {\n      return true;\n    }\n    a_shifted_rev << a_shifted.colwise().reverse();\n    if (a_shifted_rev.isApprox(b)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nTEST_CASE(\"test_order_vertices_random\") {\n  Eigen::MatrixXd ngon1(4, 3);\n  Eigen::MatrixXd ngon2(4, 3);\n  Eigen::MatrixXd ngon3(5, 3);\n  Eigen::MatrixXd ngon4(5, 3);\n  ngon1 << cartT(30.0, 0.0, 1.0), cartT(-30.0, 0.0, 1.0),\n      cartT(-30.0, 30.0, 1.0), cartT(30.0, 30.0, 1.0);\n  ngon2 << cartT(30.0, 0.0, 1.0), cartT(-30.0, 0.0, 1.0),\n      cartT(-30.0, 30.0, 1.0), cartT(30.0, 30.0, 1.0);\n  ngon3 << cartT(30.0, 30.0, 1.0), cartT(0.0, 30.0, 1.0),\n      cartT(-30.0, 30.0, 1.0), cartT(-110.0, 30.0, 1.0),\n      cartT(110.0, 30.0, 1.0);\n  ngon4 << cartT(30.0, 0.0, 1.0), cartT(0.0, 0.0, 1.0), cartT(-30.0, 0.0, 1.0),\n      cartT(-110.0, 0.0, 1.0), cartT(110.0, 0.0, 1.0);\n  std::vector<Eigen::MatrixXd> ngons = {ngon1, ngon2, ngon3, ngon4};\n\n  std::default_random_engine generator;\n  std::normal_distribution<double> distribution(0.0, 1.0);\n  auto normal = [&](double) { return distribution(generator); };\n\n  for (const auto& orderedNgon : ngons) {\n    int numberOfNgons = static_cast<int>(orderedNgon.rows());\n    Eigen::MatrixXd orderedNgonRandomized;\n    Eigen::MatrixXd unorderedNgon;\n    Eigen::MatrixXd reorderedNgon;\n    Eigen::VectorXi indices;\n\n    for (int i = 0; i < 10; ++i) {\n      if (i == 0) {\n        orderedNgonRandomized = orderedNgon;\n      } else {\n        Eigen::Matrix3d T = Eigen::Matrix3d::NullaryExpr(3, 3, normal);\n        Eigen::Vector3d offset = Eigen::Vector3d::NullaryExpr(3, normal);\n        orderedNgonRandomized =\n            (orderedNgon * T).rowwise() + offset.transpose();\n      }\n\n      Eigen::VectorXi orderVec =\n          Eigen::VectorXi::LinSpaced(numberOfNgons, 0, numberOfNgons);\n      do {\n        unorderedNgon = orderedNgonRandomized(orderVec, Eigen::all);\n        indices = ngonVertexOrder(unorderedNgon);\n        reorderedNgon = unorderedNgon(indices, Eigen::all);\n        REQUIRE(inSameOrder(reorderedNgon, orderedNgonRandomized));\n      } while (std::next_permutation(orderVec.begin(), orderVec.end()));\n    }\n  }\n}\n\nTEST_CASE(\"test_order_vertices_no_random\") {\n  Eigen::MatrixXd orderedNgon(5, 3);\n  Eigen::MatrixXd unorderedNgon;\n  Eigen::MatrixXd reorderedNgon;\n  Eigen::VectorXi indices;\n  orderedNgon << cartT(30.0, 0.0, 1.0),  //\n      cartT(0.0, 0.0, 1.0),  //\n      cartT(-30.0, 0.0, 1.0),  //\n      cartT(-30.0, 30.0, 1.0),  //\n      cartT(30.0, 30.0, 1.0);\n  Eigen::VectorXi orderVec = Eigen::VectorXi::LinSpaced(\n      orderedNgon.rows(), 0, static_cast<int>(orderedNgon.rows()));\n  do {\n    unorderedNgon = orderedNgon(orderVec, Eigen::all);\n    indices = ngonVertexOrder(unorderedNgon);\n    reorderedNgon = unorderedNgon(indices, Eigen::all);\n    REQUIRE(inSameOrder(reorderedNgon, orderedNgon));\n  } while (std::next_permutation(orderVec.begin(), orderVec.end()));\n}\n\nTEST_CASE(\"test_local_coordinate_system\") {\n  Eigen::RowVector3d x{1.0, 0.0, 0.0};\n  Eigen::RowVector3d y{0.0, 1.0, 0.0};\n  Eigen::RowVector3d z{0.0, 0.0, 1.0};\n  Eigen::Matrix3d expected;\n\n  REQUIRE(localCoordinateSystem(0, 0).isApprox(Eigen::Matrix3d::Identity()));\n  expected << -y, x, z;\n  REQUIRE(localCoordinateSystem(-90, 0).isApprox(expected));\n  expected << y, -x, z;\n  REQUIRE(localCoordinateSystem(90, 0).isApprox(expected));\n  expected << -x, -y, z;\n  REQUIRE(localCoordinateSystem(180, 0).isApprox(expected));\n  expected << x, z, -y;\n  REQUIRE(localCoordinateSystem(0, 90).isApprox(expected));\n  expected << x, -z, y;\n  REQUIRE(localCoordinateSystem(0, -90).isApprox(expected));\n  expected << -y, z, -x;\n  REQUIRE(localCoordinateSystem(-90, 90).isApprox(expected));\n}\n", "meta": {"hexsha": "0617a718d4838574ecfd557541852290d0bbf528", "size": 6801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/geom_tests.cpp", "max_stars_repo_name": "valnoel/libear", "max_stars_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/geom_tests.cpp", "max_issues_repo_name": "valnoel/libear", "max_issues_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/geom_tests.cpp", "max_forks_repo_name": "valnoel/libear", "max_forks_repo_head_hexsha": "1e9c162f00bff20c66adc1e75c3014ed919a6ed4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1755319149, "max_line_length": 80, "alphanum_fraction": 0.644169975, "num_tokens": 2440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727027, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6210228602983623}}
{"text": "#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <chrono>\n\n#include <opencv2/opencv.hpp>\n\n#include <opencv2/core/cuda.hpp>\n#include <opencv2/cudaimgproc.hpp>\n#include <opencv2/cudafeatures2d.hpp>\n#include <opencv2/xfeatures2d/cuda.hpp>\n#include <opencv2/cudaarithm.hpp>\n#include <opencv2/cudawarping.hpp>\n\n#include <Eigen/Dense>\n\n#define PI 3.14285714286\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace std::chrono;\n\nstruct imageData {\n    std::string imageName = \"\";\n    double latitude = 0;\n    double longitude = 0;\n    double altitudeFeet = 0;\n    double altitudeMeter = 0;\n    double roll = 0;\n    double pitch = 0;\n    double yaw = 0;\n};\n\ncv::Mat computeUnRotMatrix (imageData& pose) {\n    double a = (pose.yaw * PI) / 180;\n    double b = (pose.pitch * PI) / 180;\n    double g = (pose.roll * PI) / 180;\n    Matrix3d Rz;\n    Rz << cos (a), -sin (a), 0,\n          sin (a), cos (a), 0,\n          0, 0, 1;\n    Matrix3d Ry;\n    Ry << cos (b), 0, sin (b),\n          0, 1, 0,\n          -sin (b), 0, cos (b);\n    Matrix3d Rx;\n    Rx << 1, 0, 0,\n          0, cos (g), -sin (g),\n          0, sin (g), cos (g);\n    Matrix3d R = Rz * (Rx * Ry);\n    R(0,2) = 0;\n    R(1,2) = 0;\n    R(2,2) = 1;\n    Matrix3d Rtrans = R.transpose ();\n    Matrix3d InvR = Rtrans.inverse ();\n    cv::Mat transformation = (cv::Mat_<double>(3,3) << InvR(0,0), InvR(0,1), InvR(0,2),\n                                                       InvR(1,0), InvR(1,1), InvR(1,2),\n                                                       InvR(2,0), InvR(2,1), InvR(2,2));\n    return transformation;\n}\n\nvoid printMat (cv::Mat& mat) {\n    int rows = mat.rows;\n    int cols = mat.cols;\n    for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++) {\n            std::cout << mat.at<double>(i,j) << \" \";\n        }\n        std::cout << std::endl;\n    }\n}\n\ncv::Mat warpPerspectiveWithPadding (const cv::Mat& image, cv::Mat& transformation) {\n    int height = image.rows;\n    int width = image.cols;\n    cv::Mat small_img;\n    cv::resize (image, small_img, cv::Size (width/2, height/2));\n    std::vector<cv::Point2f> corners = {cv::Point2f (0,0), cv::Point2f (0,height/2),\n                                   cv::Point2f (width/2,height/2), cv::Point2f (width/2,0)};\n    std::vector<cv::Point2f> warpedCorners;\n    cv::perspectiveTransform (corners, warpedCorners, transformation);\n    float xMin = 1e9, xMax = -1e9;\n    float yMin = 1e9, yMax = -1e9;\n    for (int i = 0; i < 4; i++) {\n        xMin = (xMin > warpedCorners[i].x)? warpedCorners[i].x : xMin;\n        xMax = (xMax < warpedCorners[i].x)? warpedCorners[i].x : xMax;\n        yMin = (yMin > warpedCorners[i].y)? warpedCorners[i].y : yMin;\n        yMax = (yMax < warpedCorners[i].y)? warpedCorners[i].y : yMax;\n    }\n    int xMin_ = (xMin - 0.5);\n    int xMax_ = (xMax + 0.5);\n    int yMin_ = (yMin - 0.5);\n    int yMax_ = (yMax + 0.5);\n    cv::Mat translation = (cv::Mat_<double>(3,3) << 1, 0, -xMin_, 0, 1, -yMin_, 0, 0, 1);\n    cv::Mat fullTransformation = translation * transformation;\n    cv::cuda::GpuMat result;\n    cv::cuda::GpuMat gpu_img (small_img);\n    cv::cuda::GpuMat gpu_ft (fullTransformation);\n    cv::cuda::warpPerspective (gpu_img, result, fullTransformation,\n                                cv::Size (xMax_-xMin_, yMax_-yMin_));\n    cv::Mat result_ (result.size(), result.type());\n    result.download (result_);\n    return result_;\n}\n\ncv::Mat combinePair (cv::Mat& img1, cv::Mat& img2) {\n\n    cv::cuda::GpuMat img1_gpu (img1), img2_gpu (img2);\n    cv::cuda::GpuMat img1_gray_gpu, img2_gray_gpu;\n\n    cv::cuda::cvtColor (img1_gpu, img1_gray_gpu, cv::COLOR_BGR2GRAY);\n    cv::cuda::cvtColor (img2_gpu, img2_gray_gpu, cv::COLOR_BGR2GRAY);\n\n    cv::cuda::GpuMat mask1;\n    cv::cuda::GpuMat mask2;\n\n    cv::cuda::threshold (img1_gray_gpu, mask1, 1, 255, cv::THRESH_BINARY);\n    cv::cuda::threshold (img2_gray_gpu, mask2, 1, 255, cv::THRESH_BINARY);\n\n    cv::cuda::SURF_CUDA detector;\n\n    cv::cuda::GpuMat keypoints1_gpu, descriptors1_gpu;\n    detector (img1_gray_gpu, mask1, keypoints1_gpu, descriptors1_gpu);\n    \n    std::vector<cv::KeyPoint> keypoints1;\n    detector.downloadKeypoints (keypoints1_gpu, keypoints1);\n\n    cv::cuda::GpuMat keypoints2_gpu, descriptors2_gpu;\n    detector(img2_gray_gpu, mask2, keypoints2_gpu, descriptors2_gpu);\n    \n    std::vector<cv::KeyPoint> keypoints2;\n    detector.downloadKeypoints (keypoints2_gpu, keypoints2);\n\n    cv::Ptr<cv::cuda::DescriptorMatcher> matcher =\n        cv::cuda::DescriptorMatcher::createBFMatcher ();\n\n    std::vector<std::vector<cv::DMatch>> knn_matches;\n    matcher->knnMatch (descriptors2_gpu, descriptors1_gpu, knn_matches, 2);\n\n    std::vector<cv::DMatch> matches;\n    std::vector<std::vector<cv::DMatch>>::const_iterator it;\n    for (it = knn_matches.begin(); it != knn_matches.end(); ++it) {\n        if(it->size() > 1 && (*it)[0].distance/(*it)[1].distance < 0.55) {\n            matches.push_back((*it)[0]);\n        }\n    }\n\n    std::vector<cv::Point2f> src_pts;\n    std::vector<cv::Point2f> dst_pts;\n    for (auto m : matches) {\n        src_pts.push_back (keypoints2[m.queryIdx].pt);\n        dst_pts.push_back (keypoints1[m.trainIdx].pt);\n    }\n\n    cv::Mat A = cv::estimateRigidTransform(src_pts, dst_pts, false);\n    int height1 = img1.rows, width1 = img1.cols;\n    int height2 = img2.rows, width2 = img2.cols;\n\n    std::vector<std::vector<float>> corners1 {{0,0},{0,height1},{width1,height1},{width1,0}};\n    std::vector<std::vector<float>> corners2 {{0,0},{0,height2},{width2,height2},{width2,0}};\n\n    std::vector<std::vector<float>> warpedCorners2 (4, std::vector<float>(2));\n    std::vector<std::vector<float>> allCorners = corners1;\n\n    for (int i = 0; i < 4; i++) {\n        float cornerX = corners2[i][0];\n        float cornerY = corners2[i][1];\n        warpedCorners2[i][0] = A.at<double> (0,0) * cornerX +\n                            A.at<double> (0,1) * cornerY + A.at<double> (0,2);\n        warpedCorners2[i][1] = A.at<double> (1,0) * cornerX +\n                            A.at<double> (1,1) * cornerY + A.at<double> (1,2);\n        allCorners.push_back (warpedCorners2[i]);\n    }\n\n    float xMin = 1e9, xMax = -1e9;\n    float yMin = 1e9, yMax = -1e9;\n    for (int i = 0; i < 7; i++) {\n        xMin = (xMin > allCorners[i][0])? allCorners[i][0] : xMin;\n        xMax = (xMax < allCorners[i][0])? allCorners[i][0] : xMax;\n        yMin = (yMin > allCorners[i][1])? allCorners[i][1] : yMin;\n        yMax = (yMax < allCorners[i][1])? allCorners[i][1] : yMax;\n    }\n    int xMin_ = (xMin - 0.5);\n    int xMax_ = (xMax + 0.5);\n    int yMin_ = (yMin - 0.5);\n    int yMax_ = (yMax + 0.5);\n\n    cv::Mat translation = (cv::Mat_<double>(3,3) << 1, 0, -xMin_, 0, 1, -yMin_, 0, 0, 1);\n\n    cv::cuda::GpuMat warpedResImg;\n    cv::cuda::warpPerspective (img1_gpu, warpedResImg, translation,\n                               cv::Size (xMax_-xMin_, yMax_-yMin_));\n\n    cv::cuda::GpuMat warpedImageTemp;\n    cv::cuda::warpPerspective (img2_gpu, warpedImageTemp, translation,\n                                cv::Size (xMax_ - xMin_, yMax_ - yMin_));\n    cv::cuda::GpuMat warpedImage2;\n    cv::cuda::warpAffine (warpedImageTemp, warpedImage2, A,\n                          cv::Size (xMax_ - xMin_, yMax_ - yMin_));\n\n    cv::cuda::GpuMat mask;\n    cv::cuda::threshold (warpedImage2, mask, 1, 255, cv::THRESH_BINARY);\n    int type = warpedResImg.type();\n\n    warpedResImg.convertTo (warpedResImg, CV_32FC3);\n    warpedImage2.convertTo (warpedImage2, CV_32FC3);\n    mask.convertTo (mask, CV_32FC3, 1.0/255);\n    cv::Mat mask_;\n    mask.download (mask_);\n\n    cv::cuda::GpuMat dst (warpedImage2.size(), warpedImage2.type());\n    cv::cuda::multiply (mask, warpedImage2, warpedImage2);\n\n    cv::Mat diff_ = cv::Scalar::all (1.0) - mask_;\n    cv::cuda::GpuMat diff (diff_);\n    cv::cuda::multiply(diff, warpedResImg, warpedResImg);\n    cv::cuda::add (warpedResImg, warpedImage2, dst);\n    dst.convertTo (dst, type);\n\n    cv::Mat ret;\n    dst.download (ret);\n    return ret;\n}\n\ncv::Mat combine (std::vector<cv::Mat>& imageList) {\n    cv::Mat result = imageList[0];\n    for (int i = 1; i < imageList.size(); i++) {\n        cv::Mat image = imageList[i];\n        cout << i << endl;\n        auto start = high_resolution_clock::now();\n        result = combinePair (result, image);\n        auto end = high_resolution_clock::now();\n        auto duration = duration_cast<microseconds> (end-start);\n        cout << \"time taken by the functions: \" << duration.count() << endl;\n        float h = result.rows;\n        float w = result.cols;\n        if (h > 4000 || w > 4000) {\n            if (h > 4000) {\n                float hx = 4000.0/h;\n                h = h * hx;\n                w = w * hx;\n            }\n            else if (w > 4000) {\n                float wx = 4000.0/w;\n                w = w * wx;\n                h = h * wx;\n            }\n        }\n        cout << h << \" \" << w << endl;\n        cv::resize (result, result, cv::Size (w, h));\n    }\n    return result;\n}\n\nvoid readData (std::string& filename,\n               std::vector<imageData>& dataMatrix) {\n    std::ifstream file;\n    file.open (filename);\n    if (file.is_open()) {\n        std::string line;\n        while (getline (file, line)) {\n            std::stringstream ss (line);\n            std::string word;\n            imageData id;\n            int i = 0;\n            while (getline (ss, word, ',')) {\n                if (i == 0)\t{ id.imageName = word; }\n                else if (i == 1) { id.latitude = stof(word); }\n                else if (i == 2) { id.longitude = stof(word); }\n                else if (i == 3) {\n                    id.altitudeFeet = stof (word);\n                    id.altitudeMeter = id.altitudeFeet * 0.3048;\n                }\n                else if (i == 4) { id.yaw = stof(word); }\n                else if (i == 5) { id.pitch = stof(word); }\n                else if (i == 6) { id.roll = stof(word); }\n                i++;\n            }\n            dataMatrix.push_back (id);\n        }\n    }\n}\n\nvoid getImageList (std::vector<cv::Mat>& imageList,\n                   std::vector<imageData>& dataMatrix,\n                   std::string base_path) {\n    for (auto data : dataMatrix) {\n        std::string img_path = base_path + data.imageName;\n        cv::Mat img = cv::imread (img_path, 1);\n        // cout << img.empty () << endl;\n        // cout << img_path << endl;\n        imageList.push_back (img);\n    }\n}\n\nvoid changePerspective (std::vector<cv::Mat>& imageList,\n                        std::vector<imageData>& dataMatrix) {\n    std::cout << \"Warping Images Now\" << std::endl;\n    int n = imageList.size();\n    for (int i = 0; i < n; i++) {\n        cv::Mat M = computeUnRotMatrix (dataMatrix[i]);\n        cv::Mat correctedImage = warpPerspectiveWithPadding (imageList[i], M);\n\n        cv::imwrite (\"/home/ksakash/misc/Drone-Image-Stitching/temp/\"\n                     +dataMatrix[i].imageName, correctedImage);\n    }\n    std::cout << \"Image Warping Done\" << std::endl;\n}\n\nint main () {\n    std::string filename = \"/home/ksakash/misc/Drone-Image-Stitching/datasets/imageData.txt\";\n    std::vector<imageData> dataMatrix;\n    readData (filename, dataMatrix);\n    std::vector<cv::Mat> imageList;\n    std::string base_path = \"/home/ksakash/misc/Drone-Image-Stitching/datasets/images/\";\n    getImageList (imageList, dataMatrix, base_path);\n    changePerspective (imageList, dataMatrix);\n    imageList.clear();\n    base_path = \"/home/ksakash/misc/Drone-Image-Stitching/temp/\";\n    getImageList (imageList, dataMatrix, base_path);\n    cv::Mat result = combine (imageList);\n    cv::imwrite (\"/home/ksakash/misc/Drone-Image-Stitching/results/result.png\", result);\n    return 0;\n}\n", "meta": {"hexsha": "498b4ff980361bbe0333defa1b089df254cf0a83", "size": 11720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "ksakash/cuda_stitch", "max_stars_repo_head_hexsha": "7bd0e0fa402f020f25efa73bb3481ded07b90794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-26T04:52:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:09:30.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "ksakash/cuda_stitch", "max_issues_repo_head_hexsha": "7bd0e0fa402f020f25efa73bb3481ded07b90794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-27T11:40:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-30T16:15:20.000Z", "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "ksakash/cuda_stitch", "max_forks_repo_head_hexsha": "7bd0e0fa402f020f25efa73bb3481ded07b90794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-06T13:51:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T04:07:03.000Z", "avg_line_length": 35.8409785933, "max_line_length": 93, "alphanum_fraction": 0.5690273038, "num_tokens": 3631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937711, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.6209943237244333}}
{"text": "//\n// Created by krab1k on 31/10/18.\n//\n\n#include <vector>\n#include <cmath>\n#include <Eigen/LU>\n\n#include \"kcm.h\"\n#include \"../structures/molecule.h\"\n#include \"../parameters.h\"\n\nCHARGEFW2_METHOD(KCM)\n\n\nstd::vector<double> KCM::calculate_charges(const Molecule &molecule) const {\n\n    size_t n = molecule.atoms().size();\n    size_t m = molecule.bonds().size();\n\n    Eigen::MatrixXd W = Eigen::MatrixXd::Zero(m, m);\n    Eigen::MatrixXd B = Eigen::MatrixXd::Zero(m, n);\n    Eigen::VectorXd chi0 = Eigen::VectorXd::Zero(n);\n\n    /* Compute\n     *  q = (B.T @ W @ B + I)^-1 @ chi0 - chi0\n     */\n\n    for (size_t i = 0; i < n; i++) {\n        chi0(i) = parameters_->atom()->parameter(atom::electronegativity)(molecule.atoms()[i]);\n    }\n\n    for (size_t i = 0; i < m; i++) {\n        auto &bond = molecule.bonds()[i];\n        auto &first = bond.first();\n        auto &second = bond.second();\n\n        W(i, i) = 1 / (parameters_->atom()->parameter(atom::hardness)(first) +\n                            parameters_->atom()->parameter(atom::hardness)(second));\n\n        B(i, first.index()) = 1;\n        B(i, second.index()) = -1;\n    }\n\n    Eigen::VectorXd q = (B.transpose() * W * B + Eigen::MatrixXd::Identity(n, n)).partialPivLu().solve(chi0) - chi0;\n    return std::vector<double>(q.data(), q.data() + q.size());\n}\n", "meta": {"hexsha": "e561f3f845f45a55129527606deecd96e6f3fc4d", "size": 1308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/kcm.cpp", "max_stars_repo_name": "danny305/ChargeFW2", "max_stars_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T15:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:38:09.000Z", "max_issues_repo_path": "src/methods/kcm.cpp", "max_issues_repo_name": "danny305/ChargeFW2", "max_issues_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-03-04T21:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T07:11:19.000Z", "max_forks_repo_path": "src/methods/kcm.cpp", "max_forks_repo_name": "danny305/ChargeFW2", "max_forks_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T00:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T05:47:39.000Z", "avg_line_length": 27.25, "max_line_length": 116, "alphanum_fraction": 0.5688073394, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.6209657516902775}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2022, Jeferson Lima\n * All Rights Reserved\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n *  @file   examples/translation_ex.cpp\n *  @author Jeferson Lima\n *  @brief  Translation Matrix Example \n *  @date   Mar 11, 2022\n **/\n\n#include <iostream>\n#include <Eigen/Core>\n\nvoid trans3dVec(const Eigen::Matrix<float, 4, 1>& v,\n                Eigen::Matrix<float, 4, 1>& r,\n\t\tconst Eigen::Matrix<float, 3, 1>& q)\n{\n\n  Eigen::Matrix<float, 4, 4> translation;\n  translation << 1.0, 0.0, 0.0, q[0],\n                 0.0, 1.0, 0.0, q[1],\n\t\t 0.0, 0.0, 1.0, q[2],\n\t\t 0.0, 0.0, 0.0, 1.0;\n    \n  std::cout << \"v values: \\n\" << v << std::endl;\n  std::cout << \"translation values: \\n\" << translation << std::endl;\n\n  r = translation * v;\n\n}\n\n\nint main(int argc, char* argv[])\n{\n\n  Eigen::Matrix<float, 4, 1> v;\n  Eigen::Matrix<float, 4, 1> r;\n  Eigen::Matrix<float, 3, 1> Q;\n\n  // init matrix\n  v << 0.5, 0.5, 0.0, 1.0;\n  Q << 1.0, 1.0, 0.0;\n\n  trans3dVec(v, r, Q);\n\n  std::cout << \"r:\\n\" << r << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "e075c015982aa402856cd2f4ac63277d5c403635", "size": 1184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/1/translation_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/translation_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/translation_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": 22.3396226415, "max_line_length": 80, "alphanum_fraction": 0.4814189189, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6209046412501951}}
{"text": "#include \"../GEFE_utility.h\"\n#include <armadillo>\n#include \"gtest/gtest.h\"\n#include <string>\n\n// Compares the normalized eigenvector values produced by GEFE with those\n// produced by Armadillo's eig_sym().\nvoid compareGEFEwithARMA(const arma::mat& H) {\n    assert(H.is_square());\n    std::string column_numbers;\n    int numbers[H.n_rows];\n    std::iota(numbers, numbers + H.n_rows,0);\n    for (auto number : numbers) {\n        column_numbers += std::to_string(number);\n        column_numbers += \" \";\n    }\n    const arma::vec ii(column_numbers);\n\n    arma::vec arma_eigvals;\n    arma::mat arma_eigvecs;\n    arma::eig_sym(arma_eigvals, arma_eigvecs, H);\n\n    for (int current_column = 0; current_column < H.n_cols; ++current_column) {\n        const arma::vec gefe_eigvecs_column_j = getEigenvectorFromEigenvalues(H, ii, /*j=*/current_column);\n        const arma::vec arma_eigvecs_column_j = arma::square(arma_eigvecs.col(current_column)); // Normalized.\n        for (const double current_row : gefe_eigvecs_column_j) {\n            EXPECT_DOUBLE_EQ(arma_eigvecs_column_j[current_row], gefe_eigvecs_column_j[current_row]);\n        }\n    }\n}\n\nTEST(TwoByTwo, Hermitian) {\n    const arma::mat H1(\"-0.2414 0.3160;\"\n                       \"0.3160 -0.8649\");\n    compareGEFEwithARMA(H1);\n\n    const arma::mat H2(\"2.7694 0.8425;\"\n                       \"0.8425 0.7254\");\n    compareGEFEwithARMA(H2);\n}", "meta": {"hexsha": "41ea3d87208ddb6715d4e96437589a504ae80b11", "size": 1391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/testing/GEFE_test.cpp", "max_stars_repo_name": "cgyurgyik/EigenvectorsFromEigenvalues", "max_stars_repo_head_hexsha": "53ccbc879ddf9784a12a1635334dd3a9108efa23", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-16T01:27:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-16T01:27:57.000Z", "max_issues_repo_path": "cpp/testing/GEFE_test.cpp", "max_issues_repo_name": "cgyurgyik/eigenvectors-from-eigenvalues", "max_issues_repo_head_hexsha": "53ccbc879ddf9784a12a1635334dd3a9108efa23", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-16T01:39:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-19T16:12:16.000Z", "max_forks_repo_path": "cpp/testing/GEFE_test.cpp", "max_forks_repo_name": "cgyurgyik/EigenvectorsFromEigenvalues", "max_forks_repo_head_hexsha": "53ccbc879ddf9784a12a1635334dd3a9108efa23", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-19T03:18:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T03:18:44.000Z", "avg_line_length": 34.775, "max_line_length": 110, "alphanum_fraction": 0.6606757728, "num_tokens": 392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034369, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6209046269926292}}
{"text": "/**\n * \\file libs/numeric/ublasx/test/pow.cpp\n *\n * \\brief Test suite for the \\c pow operation.\n *\n * Copyright (c) 2015, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublasx/operation/pow.hpp>\n#include <cmath>\n#include <complex>\n#include <cstddef>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = ::boost::numeric::ublas;\nnamespace ublasx = ::boost::numeric::ublasx;\n\n\nstatic const double tol = 1.0e-5;\n\n\nBOOST_UBLASX_TEST_DEF( test_real_matrix_positive_exponent )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real Matrix - Positive Exponent\" );\n\n\ttypedef double value_type;\n\ttypedef std::size_t size_type;\n\ttypedef ublas::matrix<value_type> matrix_type;\n\n\tconst size_type n = 2;\n\tconst double exp = 3;\n\n\tmatrix_type A(n,n);\n\n\tA(0,0) = 1; A(0,1) = 2;\n\tA(1,0) = 4; A(1,1) = 5;\n\n\tmatrix_type R;\n\tmatrix_type expect_R;\n\n\tR = ublasx::pow(A, exp);\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n\tBOOST_UBLASX_DEBUG_TRACE( \"pow(A, \" << exp << \") = \" << R );\n\n\texpect_R = A;\n\tfor (size_type i = 0; i < (exp-1); ++i)\n\t{\n\t\texpect_R = ublas::prod(expect_R, A);\n\t}\n\n\tBOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( R, expect_R, n, n, tol );\n}\n\nBOOST_UBLASX_TEST_DEF( test_real_matrix_negative_exponent )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real Matrix - Negative Exponent\" );\n\n\ttypedef double value_type;\n\ttypedef std::size_t size_type;\n\ttypedef ublas::matrix<value_type> matrix_type;\n\n\tconst size_type n = 2;\n\tconst double exp = -3;\n\n\tmatrix_type A(n,n);\n\n\tA(0,0) = 1; A(0,1) = 2;\n\tA(1,0) = 4; A(1,1) = 5;\n\n\tmatrix_type R;\n\tmatrix_type expect_R;\n\n\tR = ublasx::pow(A, exp);\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n\tBOOST_UBLASX_DEBUG_TRACE( \"pow(A, \" << exp << \") = \" << R );\n\n\tmatrix_type invA(n,n);\n\tinvA(0,0) = -5.0/3.0; invA(0,1) =  2.0/3.0;\n\tinvA(1,0) =  4.0/3.0; invA(1,1) = -1.0/3.0;\n\n\texpect_R = invA;\n\tfor (size_type i = 0; i < (-exp-1); ++i)\n\t{\n\t\texpect_R = ublas::prod(expect_R, invA);\n\t}\n\n\n\tBOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( R, expect_R, n, n, tol );\n}\n\nBOOST_UBLASX_TEST_DEF( test_real_matrix_zero_exponent )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real Matrix - Zero Exponent\" );\n\n\ttypedef double value_type;\n\ttypedef std::size_t size_type;\n\ttypedef ublas::matrix<value_type> matrix_type;\n\n\tconst size_type n = 2;\n\tconst double exp = 0;\n\n\tmatrix_type A(n,n);\n\n\tA(0,0) = 1; A(0,1) = 2;\n\tA(1,0) = 4; A(1,1) = 5;\n\n\tmatrix_type R;\n\tmatrix_type expect_R = ublas::identity_matrix<value_type>(n);\n\n\tR = ublasx::pow(A, exp);\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n\tBOOST_UBLASX_DEBUG_TRACE( \"pow(A, \" << exp << \") = \" << R );\n\n\tBOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( R, expect_R, n, n, tol );\n}\n\nBOOST_UBLASX_TEST_DEF( test_complex_matrix_positive_exponent )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"Test Case: Complex Matrix - Positive Exponent\" );\n\n\ttypedef std::complex<double> in_value_type;\n\ttypedef in_value_type out_value_type;\n\ttypedef std::size_t size_type;\n\ttypedef ublas::matrix<in_value_type> in_matrix_type;\n\ttypedef ublas::matrix<out_value_type> out_matrix_type;\n\n\tconst size_type n = 2;\n\tconst int exp = 3;\n\n\tin_matrix_type A(n,n);\n\n\tA(0,0) = in_value_type(1,2); A(0,1) = in_value_type(2,3);\n\tA(1,0) = in_value_type(4,5); A(1,1) = in_value_type(5,6);\n\n\tout_matrix_type R;\n\tout_matrix_type expect_R;\n\n\tR = ublasx::pow(A, exp);\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n\tBOOST_UBLASX_DEBUG_TRACE( \"pow(A, \" << exp << \") = \" << R );\n\n\texpect_R = A;\n\tfor (size_type i = 0; i < (exp-1); ++i)\n\t{\n\t\texpect_R = ublas::prod(expect_R, A);\n\t}\n\n\tBOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( R, expect_R, n, n, tol );\n}\n\n\nint main()\n{\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Suite: 'pow' operation\");\n\n\tBOOST_UBLASX_TEST_BEGIN();\n\n\tBOOST_UBLASX_TEST_DO( test_real_matrix_positive_exponent );\n\tBOOST_UBLASX_TEST_DO( test_real_matrix_negative_exponent );\n\tBOOST_UBLASX_TEST_DO( test_real_matrix_zero_exponent );\n\tBOOST_UBLASX_TEST_DO( test_complex_matrix_positive_exponent );\n\n\tBOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "2be85f6e44fc27eae332f27b461c00f4d85fb39f", "size": 4226, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/pow.cpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/numeric/ublasx/test/pow.cpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/ublasx/test/pow.cpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4777777778, "max_line_length": 77, "alphanum_fraction": 0.6947468055, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312056025699, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6208355729910108}}
{"text": "#include <dlib/optimization.h>\n\n#include <bfgs/bfgs.h>\n#include <bfgs/dval.h>\n\n\nint _fun_call = 0;\n\n// Rosenbrock's function.\nclass FRosen\n{\nprivate:\n\tconst double _p1;\n\n\ttemplate <typename T>\n\tT _f(const T& x1, const T& x2) const\n\t{\n\t\t++_fun_call;\n\t\tT v1 = x2 - x1 * x1;\n\t\tT v2 = _p1 - x1;\n\t\tT res = 100.0 * v1 * v1 + v2 * v2 + 1.0;\n\t\treturn res;\n\t}\n\npublic:\n\tFRosen(double p1 = 1.0):\n\t\t_p1(p1)\n\t{\n\t}\n\n\tdouble operator()(const dlib::matrix<double,0,1>& m) const\n\t{\n\t\treturn _f(m(0), m(1));\n\t}\n\n\tdouble operator()(const double* const x, int n) const\n\t{\n\t\treturn _f(x[0], x[1]);\n\t}\n\n\tDVal<0> operator()(const DVal<0>* const x, uint32_t n) const\n\t{\n\t\treturn _f(x[0], x[1]);\n\t}\n\n\ttemplate <uint32_t N>\n\tDVal<N> operator()(const DVal<N>* const x, uint32_t n) const\n\t{\n\t\treturn _f(x[0], x[1]);\n\t}\n};\n\n\n// Simple function.\nclass FSimple\n{\nprivate:\n\tconst double _p1;\n\n\ttemplate <typename T>\n\tT _f(const T& x1, const T& x2) const\n\t{\n\t\t++_fun_call;\n\t\treturn _p1 * x1 * x1 + x2 * x2 + x1 + x2;\n\t}\n\npublic:\n\tFSimple(double p1 = 1.0):\n\t\t_p1(p1)\n\t{\n\t}\n\n\tdouble operator()(const dlib::matrix<double,0,1>& m) const\n\t{\n\t\treturn _f(m(0), m(1));\n\t}\n\n\tdouble operator()(const double* const x, int n) const\n\t{\n\t\treturn _f(x[0], x[1]);\n\t}\n\n\tDVal<0> operator()(const DVal<0>* const x, uint32_t n) const\n\t{\n\t\treturn _f(x[0], x[1]);\n\t}\n\n\ttemplate <uint32_t N>\n\tDVal<N> operator()(const DVal<N>* const x, uint32_t n) const\n\t{\n\t\treturn _f(x[0], x[1]);\n\t}\n};\n\ntemplate <typename fun>\nvoid test(const fun& f)\n{\n\tconst int iter = 1000;\n\t// const int iter = 1;\n\n\t{\n\t\tdlib::matrix<double,0,1> dlib_point = {-1.0, -1.0};\n\t\tdouble dlib_y;\n\n\t\tauto beg = std::chrono::steady_clock::now();\n\t\tfor (int i = 0; i < iter; ++i)\n\t\t{\n\t\t\t_fun_call = 0;\n\t\t\tdlib_point(0) = -1.0;\n\t\t\tdlib_point(1) = -1.0;\n\t\t\tdlib_y = dlib::find_min_using_approximate_derivatives(\n\t\t\t\t\tdlib::bfgs_search_strategy(),\n\t\t\t\t\t// dlib::gradient_norm_stop_strategy(1e-7, 1000),\n\t\t\t\t\tdlib::objective_delta_stop_strategy(1e-7, 1000),\n\t\t\t\t\tf,\n\t\t\t\t\tdlib_point,\n\t\t\t\t\t-1,\n\t\t\t\t\t1e-8);\n\t\t}\n\n\t\tauto end = std::chrono::steady_clock::now();\n\t\tdouble dt = std::chrono::duration_cast<std::chrono::nanoseconds>(end - beg).count() * 1e-9;\n\n\t\tstd::cout << \"\\tdlib\" << std::endl;\n\t\tstd::cout << \"fun_call: \" << _fun_call << \"\\ndt (us): \" << 1e6 * dt / iter << \"\\nsolution: \" << dlib_y  << std::endl <<  dlib_point;\n\t}\n\n\tBFGS bfgs;\n\tbfgs.set_grad_eps(1e-8);\n\tbfgs.set_stop_grad_eps(1e-7);\n\tbfgs.set_stop_step_eps(1e-7);\n\tbfgs.set_max_iter(1000);\n\tbfgs.set_line_central_diff(false);\n\n\t{\n\t\tbfgs.set_lbfgs_m(0);\n\t\tconst uint32_t n = 2;\n\t\tdouble bfgs_point[n] = {-1.0, -1.0};\n\t\tdouble bfgs_y = bfgs.find_min_num(f, bfgs_point, n);\n\n\t\tauto beg = std::chrono::steady_clock::now();\n\t\tfor (int i = 0; i < iter; ++i)\n\t\t{\n\t\t\t_fun_call = 0;\n\t\t\tbfgs_point[0] = -1.0;\n\t\t\tbfgs_point[1] = -1.0;\n\t\t\tbfgs_y = bfgs.find_min_num(f, bfgs_point, n);\n\t\t}\n\t\tauto end = std::chrono::steady_clock::now();\n\t\tdouble dt = std::chrono::duration_cast<std::chrono::nanoseconds>(end - beg).count() * 1e-9;\n\n\t\tstd::cout << \"\\tbfgs num\" << std::endl;\n\t\tstd::cout << \"fun_call: \" << _fun_call << \"\\ndt (us): \" << 1e6 * dt / iter << \"\\nsolution: \" << bfgs_y << std::endl;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tstd::cout << bfgs_point[i] << std::endl;\n\t}\n\n\t{\n\t\tbfgs.set_lbfgs_m(5);\n\t\tconst uint32_t n = 2;\n\t\tdouble bfgs_point[n] = {-1.0, -1.0};\n\t\tdouble bfgs_y = bfgs.find_min_num(f, bfgs_point, n);\n\n\t\tauto beg = std::chrono::steady_clock::now();\n\t\tfor (int i = 0; i < iter; ++i)\n\t\t{\n\t\t\t_fun_call = 0;\n\t\t\tbfgs_point[0] = -1.0;\n\t\t\tbfgs_point[1] = -1.0;\n\t\t\tbfgs_y = bfgs.find_min_num(f, bfgs_point, n);\n\t\t}\n\t\tauto end = std::chrono::steady_clock::now();\n\t\tdouble dt = std::chrono::duration_cast<std::chrono::nanoseconds>(end - beg).count() * 1e-9;\n\n\t\tstd::cout << \"\\tlbfgs num\" << std::endl;\n\t\tstd::cout << \"fun_call: \" << _fun_call << \"\\ndt (us): \" << 1e6 * dt / iter << \"\\nsolution: \" << bfgs_y << std::endl;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tstd::cout << bfgs_point[i] << std::endl;\n\t}\n\n\t{\n\t\tbfgs.set_lbfgs_m(0);\n\t\tconst uint32_t n = 2;\n\t\tdouble bfgs_point[n] = {-1.0, -1.0};\n\t\tdouble bfgs_y = bfgs.find_min_auto(f, bfgs_point, n);\n\n\t\tauto beg = std::chrono::steady_clock::now();\n\t\tfor (int i = 0; i < iter; ++i)\n\t\t{\n\t\t\t_fun_call = 0;\n\t\t\tbfgs_point[0] = -1.0;\n\t\t\tbfgs_point[1] = -1.0;\n\t\t\tbfgs_y = bfgs.find_min_auto(f, bfgs_point, n);\n\t\t}\n\t\tauto end = std::chrono::steady_clock::now();\n\t\tdouble dt = std::chrono::duration_cast<std::chrono::nanoseconds>(end - beg).count() * 1e-9;\n\n\t\tstd::cout << \"\\tbfgs auto dynamic\" << std::endl;\n\t\tstd::cout << \"fun_call: \" << _fun_call << \"\\ndt (us): \" << 1e6 * dt / iter << \"\\nsolution: \" << bfgs_y << std::endl;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tstd::cout << bfgs_point[i] << std::endl;\n\t}\n\n\t{\n\t\tbfgs.set_lbfgs_m(0);\n\t\tconst uint32_t n = 2;\n\t\tdouble bfgs_point[n] = {-1.0, -1.0};\n\t\tdouble bfgs_y = bfgs.find_min_auto<2>(f, bfgs_point, n);\n\n\t\tauto beg = std::chrono::steady_clock::now();\n\t\tfor (int i = 0; i < iter; ++i)\n\t\t{\n\t\t\t_fun_call = 0;\n\t\t\tbfgs_point[0] = -1.0;\n\t\t\tbfgs_point[1] = -1.0;\n\t\t\tbfgs_y = bfgs.find_min_auto<2>(f, bfgs_point, n);\n\t\t}\n\t\tauto end = std::chrono::steady_clock::now();\n\t\tdouble dt = std::chrono::duration_cast<std::chrono::nanoseconds>(end - beg).count() * 1e-9;\n\n\t\tstd::cout << \"\\tbfgs auto fixed\" << std::endl;\n\t\tstd::cout << \"fun_call: \" << _fun_call << \"\\ndt (us): \" << 1e6 * dt / iter << \"\\nsolution: \" << bfgs_y << std::endl;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t\tstd::cout << bfgs_point[i] << std::endl;\n\t}\n\n\tstd::cout << std::endl;\n}\n\nint main()\n{\n\tstd::cout.precision(9);\n\n\tfor (int i = 1; i <= 100; i *= 10)\n\t\ttest(FRosen(i));\n\tfor (int i = 1; i <= 100; i *= 10)\n\t\ttest(FSimple(i));\n\n\treturn 0;\n}", "meta": {"hexsha": "6b794ae6b9b882ef90cd923cafc6a354704c76b1", "size": 5637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/dlib/main.cpp", "max_stars_repo_name": "IOdissey/bfgs", "max_stars_repo_head_hexsha": "56ffb8eea3045b6468d9cb8e64f112bc44d5f8f8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/dlib/main.cpp", "max_issues_repo_name": "IOdissey/bfgs", "max_issues_repo_head_hexsha": "56ffb8eea3045b6468d9cb8e64f112bc44d5f8f8", "max_issues_repo_licenses": ["Apache-2.0"], "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/dlib/main.cpp", "max_forks_repo_name": "IOdissey/bfgs", "max_forks_repo_head_hexsha": "56ffb8eea3045b6468d9cb8e64f112bc44d5f8f8", "max_forks_repo_licenses": ["Apache-2.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.4875, "max_line_length": 134, "alphanum_fraction": 0.5886109633, "num_tokens": 2228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.620835565143472}}
{"text": "/**\n * @ file avgvalboundary_test.cc\n * @ brief NPDE homework AvgValBoundary code\n * @ author Simon Meierhans, edited by Oliver Rietmann\n * @ date 11.03.2019\n * @ copyright Developed at ETH Zurich\n */\n\n#include \"../avgvalboundary.h\"\n\n#include <gtest/gtest.h>\n#include <lf/assemble/assemble.h>\n#include <lf/io/io.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <memory>\n\nnamespace AvgValBoundary::test {\n\nconstexpr char mesh_file[] = CURRENT_SOURCE_DIR \"/../../meshes/square.msh\";\n\nconstexpr auto const_one = [](Eigen::Vector2d x) -> double { return 1.0; };\n\nTEST(AvgValBoundary, TestH1SemiNorm) {\n  // obtain dofh for lagrangian finite element space\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader(std::move(mesh_factory), mesh_file);\n  auto mesh = reader.mesh();\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh);\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n\n  // get solution of test problem\n  Eigen::VectorXd mu = solveTestProblem(dofh);\n  // compute H1 seminorm\n  double h1s_norm = compH1seminorm(dofh, mu);\n\n  ASSERT_NEAR(h1s_norm, 0.151178, 0.00001);\n}\n\nTEST(AvgValBoundary, TestBoundaryFunctional) {\n  // obtain dofh for lagrangian finite element space\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader(std::move(mesh_factory), mesh_file);\n  auto mesh = reader.mesh();\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh);\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n\n  // get solution of test problem\n  Eigen::VectorXd mu = solveTestProblem(dofh);\n  // compute boundary functional\n  double boundary_functional = compBoundaryFunctional(dofh, mu, const_one);\n  ASSERT_NEAR(boundary_functional, 0.77546, 0.00001);\n}\n}  // namespace AvgValBoundary::test\n", "meta": {"hexsha": "a718a66e8e125a566438f80c9a81f5fbcf0bf475", "size": 1931, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/AvgValBoundary/templates/test/avgvalboundary_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/AvgValBoundary/templates/test/avgvalboundary_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/AvgValBoundary/templates/test/avgvalboundary_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 32.7288135593, "max_line_length": 75, "alphanum_fraction": 0.7276022786, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.620835565143472}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nMatrix3f m = Matrix3f::Random();\nMatrix3f y = Matrix3f::Random();\ncout << \"Here is the matrix m:\" << endl << m << endl;\ncout << \"Here is the matrix y:\" << endl << y << endl;\nMatrix3f x;\nx = m.fullPivHouseholderQr().solve(y);\nassert(y.isApprox(m*x));\ncout << \"Here is a solution x to the equation mx=y:\" << endl << x << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "3cfd86713ad08a3d0fa1de4631ffa70896ee9fd4", "size": 858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_FullPivHouseholderQR_solve.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_FullPivHouseholderQR_solve.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_FullPivHouseholderQR_solve.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8125, "max_line_length": 224, "alphanum_fraction": 0.6701631702, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6208102504542724}}
{"text": "/**\n * @file gradientflow_main.cc\n * @brief NPDE homework GradientFlow code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <iostream>\n#include <vector>\n\n#include \"gradientflow.h\"\n\nconst static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                       Eigen::DontAlignCols, \", \", \"\\n\");\n\nint main() {\n  // Parameters and initial condition of the Gradient Flow ODE\n  double T = 0.1;\n  double lambda = 10.0;\n  Eigen::Vector2d d(1.0, 0.0);\n  Eigen::Vector2d y0(1.0, 0.0);\n\n  // Approximate exact solution using small timesteps\n  int M_ref = 10000;\n  std::cout << \"T = \" << T << \", lambda = \" << lambda << std::endl;\n  Eigen::Vector2d y_ref =\n      GradientFlow::SolveGradientFlow(d, lambda, y0, T, M_ref).back();\n\n  std::cout << \"Final value (exact): \" << y_ref.transpose().format(CSVFormat)\n            << std::endl;\n\n  // Compute error table\n  Eigen::VectorXi M(6);\n  M << 10, 20, 40, 80, 160, 320;\n  std::cout << \"Error table:\\n\";\n  std::cout << \"M\\t error norm\" << std::endl;\n  for (int i = 0; i < M.size(); ++i) {\n    Eigen::Vector2d y_approx =\n        GradientFlow::SolveGradientFlow(d, lambda, y0, T, M(i)).back();\n    std::cout << M(i) << \"\\t\" << (y_approx - y_ref).norm() << \"\\t\" << std::endl;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "516169071bd8122644a0d62925b0a6120e4b3a50", "size": 1330, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/GradientFlow/templates/gradientflow_main.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/GradientFlow/templates/gradientflow_main.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/GradientFlow/templates/gradientflow_main.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 28.2978723404, "max_line_length": 80, "alphanum_fraction": 0.5984962406, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6208102464821403}}
{"text": "#include <chrono>\n#include <random>\n#include <mpi.h>\n#include <boost/program_options.hpp>\n#include \"io.hpp\"\n#include \"myDist.hpp\"\n#include \"matGen_scalapack.hpp\"\n#include \"io_mpi.hpp\"\n\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[]){\n\n  MPI_Init(&argc, &argv);\n\n  po::options_description descp(\"Artificial Matrices with ScaLAPACK: Options\");\n\n  descp.add_options()\n       (\"help,h\",\"show the help\"\n\t\t \"Attention, for the current implementation of parallel IO, please make sure N/mbsize/dim0 == 0 and N/bbsize/dim1 == 0\")\n       (\"N\", po::value<std::size_t>()->default_value(10), \"number of row and column of matrices to be generated.\")\n       (\"dim0\", po::value<int>()->default_value(1), \"first dimension of 2D MPI cartesian grid.\")    \n       (\"dim1\", po::value<int>()->default_value(1), \"second dimension of 2D MPI cartesian grid.\")       \n       (\"mbsize\", po::value<std::size_t>()->default_value(5), \"ScaLAPACK block size in the first dimension of 2D MPI cartesian grid.\")\n       (\"nbsize\", po::value<std::size_t>()->default_value(5), \"ScaLAPACK block size in the second dimension of 2D MPI cartesian grid.\")\n       (\"dmax\", po::value<double>()->default_value(1), \"A scalar which scales the generated eigenvalues, this makes\"\n\t\t\t\t\t\t\t \" the maximum absolute eigenvalue is abs(dmax).\" )\n       (\"epsilon\", po::value<double>()->default_value(0.1), \"This value is epsilon.\" ) \n       (\"myDist\", po::value<std::size_t>()->default_value(0), \"Specifies my externel setup distribution for generating eigenvalues:\\n \"\n\t\t\t\t\t\t\t      \"0: Uniform eigenspectrum lambda_k = dmax * (epsilon + k * (1 - epsilon) / n for k = 0, ..., n-1)\\n \"\n                                                              \"1: Geometric eigenspectrum lambda_k =lambda_k = epsilon^[(n - k) / n] for k = 0, ..., n-1) \\n\")\n       (\"mean\", po::value<double>()->default_value(0.5), \"Mean value of Normal distribution for the randomness.\" )\n       (\"stddev\", po::value<double>()->default_value(1.0), \"Standard deviation value of Normal distribution for the randomness.\" )\n  ;  \n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, descp), vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << descp << std::endl;\n    return 1;\n  }\n  \n  //will be parsered by boost\n  //2D dimmension of MPI grid\n  int dim0 = vm[\"dim0\"].as<int>();\n  int dim1 = vm[\"dim1\"].as<int>();  \n  //size of matrix to be generated\n  std::size_t N = vm[\"N\"].as<std::size_t>();\n  //block size of scalapack\n  std::size_t mbsize = vm[\"mbsize\"].as<std::size_t>();\n  std::size_t nbsize = vm[\"nbsize\"].as<std::size_t>();\n  //for the randomness with normal distribution\n  double mean = vm[\"mean\"].as<double>();\n  double stddev = vm[\"stddev\"].as<double>();\n  double dmax = vm[\"dmax\"].as<double>();\n  double eps = vm[\"epsilon\"].as<double>();\n  std::size_t dist = vm[\"myDist\"].as<std::size_t>();\n\n  std::string mode;\n\n  if(dist == 0){\n    mode= \"Uniform\";\n  }else if(dist == 1){\n    mode = \"Geometric\";\n  }\n  \n  int rank;\n  MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n  int myproc, nprocs;\n  blacs_pinfo( &myproc, &nprocs );\n\n  int ictxt;\n  int val;\n  blacs_get( &ictxt, &i_zero, &val );\n  blacs_gridinit( &ictxt, 'C', &dim0, &dim1 );\n\n\n  std::chrono::high_resolution_clock::time_point start, end;\n  std::chrono::duration<double> elapsed;\n\n  start = std::chrono::high_resolution_clock::now();\n \n  double *A;\n  \n  if(dist == 0){\n      A = matGen_scalapack<double>(ictxt, N, mbsize, nbsize,\n                        \t       mean, stddev, myUniformDist<double>, N, eps, dmax);\n  }else if(dist == 1){\n      A = matGen_scalapack<double>(ictxt, N, mbsize, nbsize,\n                                       mean, stddev, myGeometricDist<double>, N, eps, dmax);  \n  }else{\n      A = matGen_scalapack<double>(ictxt, N, mbsize, nbsize, mean, stddev, \n\t\t      \t\t[](std::size_t n, int x){\n                \t\t    double *eigenv = new double[n];\n                \t\t    for(auto k = 0; k < n; k++){\n                    \t\t\teigenv[k] = k * (x + 1);\n                \t\t    }\n                \t\t    return eigenv;\n            \t\t        }, N, 1);\n  \n  }\n\n  end = std::chrono::high_resolution_clock::now();\n\n  elapsed = std::chrono::duration_cast<std::chrono::duration<double>>(end - start);\n  \n  if(rank == 0) std::cout << \"]> matrix generated in \" << elapsed.count() << \" seconds\" << std::endl;\n \n  std::ostringstream out_str;\n\n  out_str << std::scientific << \"matgen_m_\" << N << \"_\" << mode << \"_eps_\"<< eps << \"_dmax_\" << dmax\n            << \".bin\";\n\n  start = std::chrono::high_resolution_clock::now();\n\n  wrtMatIntoBinaryMPI<double>(ictxt, A, out_str.str(), N, mbsize, nbsize);\n\n  end = std::chrono::high_resolution_clock::now();\n\n  elapsed = std::chrono::duration_cast<std::chrono::duration<double>>(end - start);\n\n  double gb = (double)N * (double)N * sizeof(double)/1024.0/1024.0/1024.0;\n\n  if(rank == 0) \n    std::cout << \"]> matrix wrote in binary \" << out_str.str() << \" of \" << gb << \"GB in \" \n\t<< elapsed.count() << \" seconds\" << std::endl;\n\n  if(N <= 10){\n      double matdiff = matDiff(ictxt, A, N, mbsize, nbsize, out_str.str());\n  } \n\n  delete[] A;\n\n  MPI_Finalize();\t\n\n}\n", "meta": {"hexsha": "3cf1e024130369a8356341a48d5f6c5c25a1e92a", "size": 5115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/driver_scalapack.cpp", "max_stars_repo_name": "SMG2S/DEMAGIS", "max_stars_repo_head_hexsha": "9332fb687129d15024d49eb0a7027b552c1c91c7", "max_stars_repo_licenses": ["MIT"], "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/driver_scalapack.cpp", "max_issues_repo_name": "SMG2S/DEMAGIS", "max_issues_repo_head_hexsha": "9332fb687129d15024d49eb0a7027b552c1c91c7", "max_issues_repo_licenses": ["MIT"], "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/driver_scalapack.cpp", "max_forks_repo_name": "SMG2S/DEMAGIS", "max_forks_repo_head_hexsha": "9332fb687129d15024d49eb0a7027b552c1c91c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T18:31:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-09T18:33:05.000Z", "avg_line_length": 36.7985611511, "max_line_length": 158, "alphanum_fraction": 0.5974584555, "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6208102389243181}}
{"text": "#ifndef DATASETS_HPP\n#define DATASETS_HPP\n\n#include <Eigen/Core>\n#include <vector>\n\n#include \"misc.hpp\"\n\nstd::tuple<Eigen::MatrixXd, Eigen::MatrixXd> house_value_dataset() {\n    auto input_v = parse_csv<double>(\"house_data.csv\", ',');\n    Eigen::MatrixXd input(input_v.size(), 3);\n    Eigen::VectorXd target(input_v.size(), 1);\n\n    auto i = 0;\n    for (const auto& row : input_v) {\n        input(i, 0) = 1;\n        for (auto j = 0; j < 2; j++) {\n            input(i, j + 1) = row[j];\n        }\n        target(i) = row[2];\n        i++;\n    }\n\n    return std::make_tuple(input, target);\n}\n\ninline Eigen::VectorXd correlatedData(double x) {\n    return (Eigen::VectorXd(4) << 1, x, 2 * x, 0.5 * x*x).finished();\n}\n\ninline Eigen::VectorXd correlatedTarget(double x) {\n    return (Eigen::VectorXd(2) << 5 * x + 3, x).finished();\n}\n\nstd::tuple<Eigen::MatrixXd, Eigen::MatrixXd> correlated_data_dataset(int n) {\n    Eigen::VectorXd points = Eigen::VectorXd::Random(n, 1) * 100;\n    Eigen::MatrixXd input(points.rows(), correlatedData(1).rows());\n    Eigen::MatrixXd target(points.rows(), correlatedTarget(1).rows());\n\n    for (auto i = 0; i < points.rows(); i++) {\n        input.row(i) = correlatedData(points(i)).topRows(input.cols());\n        target.row(i) = correlatedTarget(points(i));\n    }\n\n    return std::make_tuple(input, target);\n}\n#endif", "meta": {"hexsha": "f8d3cf93f2cf98fd676ced3973094a1ea345f745", "size": 1341, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/examples/datasets.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/examples/datasets.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/datasets.hpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5319148936, "max_line_length": 77, "alphanum_fraction": 0.6114839672, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6208102388277079}}
{"text": "#include <simpleuv/triangulate.h>\n#include <Eigen/Dense>\n#include <cmath>\n\nnamespace simpleuv\n{\n\nstatic Eigen::Vector3d norm(const Eigen::Vector3d &p1, const Eigen::Vector3d &p2, const Eigen::Vector3d &p3)\n{\n    auto side1 = p2 - p1;\n    auto side2 = p3 - p1;\n    auto perp = side1.cross(side2);\n    return perp.normalized();\n}\n\nstatic float angle360(const Eigen::Vector3d &a, const Eigen::Vector3d &b, const Eigen::Vector3d &direct)\n{\n    auto angle = atan2((a.cross(b)).norm(), a.dot(b)) * 180.0 / 3.1415926;\n    auto c = a.cross(b);\n    if (c.dot(direct) < 0) {\n        angle += 180;\n    }\n    return angle;\n}\n\nstatic Eigen::Vector3d vertexToEigenVector3d(const Vertex &vertex)\n{\n    return Eigen::Vector3d(vertex.xyz[0], vertex.xyz[1], vertex.xyz[2]);\n}\n\nstatic bool pointInTriangle(const Eigen::Vector3d &a, const Eigen::Vector3d &b, const Eigen::Vector3d &c, const Eigen::Vector3d &p)\n{\n    auto u = b - a;\n    auto v = c - a;\n    auto w = p - a;\n    auto vXw = v.cross(w);\n    auto vXu = v.cross(u);\n    if (vXw.dot(vXu) < 0.0) {\n        return false;\n    }\n    auto uXw = u.cross(w);\n    auto uXv = u.cross(v);\n    if (uXw.dot(uXv) < 0.0) {\n        return false;\n    }\n    auto denom = uXv.norm();\n    auto r = vXw.norm() / denom;\n    auto t = uXw.norm() / denom;\n    return r + t <= 1.0;\n}\n\nstatic Eigen::Vector3d ringNorm(const std::vector<Vertex> &vertices, const std::vector<size_t> &ring)\n{\n    Eigen::Vector3d normal;\n    for (size_t i = 0; i < ring.size(); ++i) {\n        auto j = (i + 1) % ring.size();\n        auto k = (i + 2) % ring.size();\n        const auto &enter = vertexToEigenVector3d(vertices[ring[i]]);\n        const auto &cone = vertexToEigenVector3d(vertices[ring[j]]);\n        const auto &leave = vertexToEigenVector3d(vertices[ring[k]]);\n        normal += norm(enter, cone, leave);\n    }\n    return normal.normalized();\n}\n\nvoid triangulate(const std::vector<Vertex> &vertices, std::vector<Face> &faces, const std::vector<size_t> &ring)\n{\n    if (ring.size() < 3)\n        return;\n    std::vector<size_t> fillRing = ring;\n    Eigen::Vector3d direct = ringNorm(vertices, fillRing);\n    while (fillRing.size() > 3) {\n        bool newFaceGenerated = false;\n        for (decltype(fillRing.size()) i = 0; i < fillRing.size(); ++i) {\n            auto j = (i + 1) % fillRing.size();\n            auto k = (i + 2) % fillRing.size();\n            const auto &enter = vertexToEigenVector3d(vertices[fillRing[i]]);\n            const auto &cone = vertexToEigenVector3d(vertices[fillRing[j]]);\n            const auto &leave = vertexToEigenVector3d(vertices[fillRing[k]]);\n            auto angle = angle360(cone - enter, leave - cone, direct);\n            if (angle >= 1.0 && angle <= 179.0) {\n                bool isEar = true;\n                for (size_t x = 0; x < fillRing.size() - 3; ++x) {\n                    auto fourth = vertexToEigenVector3d(vertices[(i + 3 + k) % fillRing.size()]);\n                    if (pointInTriangle(enter, cone, leave, fourth)) {\n                        isEar = false;\n                        break;\n                    }\n                }\n                if (isEar) {\n                    Face newFace;\n                    newFace.indices[0] = fillRing[i];\n                    newFace.indices[1] = fillRing[j];\n                    newFace.indices[2] = fillRing[k];\n                    faces.push_back(newFace);\n                    fillRing.erase(fillRing.begin() + j);\n                    newFaceGenerated = true;\n                    break;\n                }\n            }\n        }\n        if (!newFaceGenerated)\n            break;\n    }\n    if (fillRing.size() == 3) {\n        Face newFace;\n        newFace.indices[0] = fillRing[0];\n        newFace.indices[1] = fillRing[1];\n        newFace.indices[2] = fillRing[2];\n        faces.push_back(newFace);\n    }\n}\n\n}\n", "meta": {"hexsha": "f325572dae9cfc4a9d2459a323a0e73148052ddc", "size": 3811, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simpleuv/triangulate.cpp", "max_stars_repo_name": "Erkaman/simpleuv", "max_stars_repo_head_hexsha": "65ac665f39eaa561f0d3fb81a30f8dda5be9fdb6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simpleuv/triangulate.cpp", "max_issues_repo_name": "Erkaman/simpleuv", "max_issues_repo_head_hexsha": "65ac665f39eaa561f0d3fb81a30f8dda5be9fdb6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simpleuv/triangulate.cpp", "max_forks_repo_name": "Erkaman/simpleuv", "max_forks_repo_head_hexsha": "65ac665f39eaa561f0d3fb81a30f8dda5be9fdb6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-29T13:44:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-29T13:44:20.000Z", "avg_line_length": 33.1391304348, "max_line_length": 131, "alphanum_fraction": 0.5452637103, "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6207813360802722}}
{"text": "/** @file 33.cpp Problem 33: Digit canceling fractions\n *\n * The fraction 49/98 is a curious fraction, as an inexperienced mathematician\n * in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which\n * is correct, is obtained by cancelling the 9s.\n\n * We shall consider fractions like, 30/50 = 3/5, to be trivial examples.\n *\n * There are exactly four non-trivial examples of this type of fraction, less\n * than one in value, and containing two digits in the numerator and\n * denominator.\n *\n * If the product of these four fractions is given in its lowest common terms,\n * find the value of the denominator.\n */\n\n/// @cond\n#include <boost/multiprecision/cpp_int.hpp> // cpp_rational, denominator\n\n#include <iostream> // cout\n/// @endcond\n\nusing boost::multiprecision::cpp_rational;\n\nbool equal(int n1, int d1, int n2, int d2)\n{\n    return d1 && d2 && cpp_rational(n1, d1) == cpp_rational(n2, d2);\n}\n\nint main()\n{\n    cpp_rational r = 1;\n    for (int i = 10; i < 100; ++i) {\n        for (int j = i + 1; j < 100; ++j) {\n            if (i % 10 == 0 && j % 10 == 0)\n                continue;   // Skip trivial examples.\n            int a = i / 10, b = i % 10,\n                c = j / 10, d = j % 10;\n            if (       (b == d && equal(i, j, a, c))\n                    || (b == c && equal(i, j, a, d))\n                    || (a == d && equal(i, j, b, c))\n                    || (a == c && equal(i, j, b, d)))\n                r *= cpp_rational(i, j);\n        }\n    }\n    std::cout << denominator(r) << std::endl;\n}\n", "meta": {"hexsha": "fa34dde3dc6d5f2f1f7e7a4aec178f73dd047d16", "size": 1533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/33.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/33.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/33.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": 31.9375, "max_line_length": 79, "alphanum_fraction": 0.5577299413, "num_tokens": 447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.6207813323133509}}
{"text": "// Copyright 2022 Eugen Hartmann. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include <chrono>\n#include <iostream>\n#include <format>\n\n#include <boost/exception/diagnostic_information.hpp>\n#include <boost/exception_ptr.hpp>\n\n#include <openssl/bn.h>\n\n#include \"base-helpers.h\"\n#include \"diffie-hellman-boost.h\"\n\nusing cpp_int = boost::multiprecision::cpp_int;\n\nstatic std::string\nConverCPPIntToHex(const boost::multiprecision::cpp_int& num) {\n  std::stringstream ss;\n  ss << std::uppercase << std::hex << num;\n  std::string hex = ss.str();\n  // Add the top 0 if necessary\n  if (hex.size() % 2) {\n    hex = \"0\" + hex;\n  }\n  return hex;\n}\n\nstatic boost::multiprecision::cpp_int\nConveryHexToCPPInt(std::string_view hex) {\n  return boost::multiprecision::cpp_int{std::string(\"0x\") + std::string(hex)};\n}\n\nDiffieHellmanBoost::DiffieHellmanBoost() {\n}\n\nDiffieHellmanBoost::~DiffieHellmanBoost() {\n}\n\nstd::string_view DiffieHellmanBoost::GetImplementationName() const {\n  return \"boost cpp_int DH\";\n}\n\nResult DiffieHellmanBoost::GenerateParameters(int primeLengthInBits, int generator) {\n  if (generator <= 1) {\n    return Result{Result::Fail, \"Bad generator value.\"};\n  }\n\n  try {\n    unsigned int minMillerRabinChecks = GetMillerRabinMinChecks(primeLengthInBits);\n\n    // We must use different generators for the tests and prime generation,\n    // otherwise we get false positives.\n    // https://www.boost.org/doc/libs/1_60_0/libs/multiprecision/doc/html/boost_multiprecision/tut/primetest.html\n    boost::random::mt11213b primeGenerator(clock());\n    boost::random::mt19937 testGenerator(clock());\n\n    std::array<std::uint16_t, Primes.size()> mods{};\n\n    while (true) {\n      cpp_int prime = ProbableSafePrime(primeLengthInBits, generator, primeGenerator);\n      if (miller_rabin_test(prime, minMillerRabinChecks, testGenerator)) {\n        // The value is probably prime, see if (prime - 1) / 2 is also prime.\n        if (miller_rabin_test((prime - 1) / 2, minMillerRabinChecks, testGenerator)) {\n          prime_ = std::move(prime);\n          generator_ = cpp_int{generator};\n          break;\n        }\n      }\n    }\n  } catch (const boost::exception& e) {\n    return {Result::Fail, boost::diagnostic_information(e)};\n  }\n\n  return {Result::Success};\n}\n\nResult DiffieHellmanBoost::SetParameters(std::string_view hexPrime, std::string_view hexGenerator) {\n  try {\n    prime_ = ConveryHexToCPPInt(hexPrime);\n    generator_ = ConveryHexToCPPInt(hexGenerator);\n\n  } catch (const boost::exception& e) {\n    return {Result::Fail, boost::diagnostic_information(e)};\n  }\n\n  return Result{Result::Success};\n}\nResult DiffieHellmanBoost::GetParameters(std::string* hexPrime, std::string* hexGenerator) const {\n  try {\n    *hexPrime = ConverCPPIntToHex(prime_);\n    *hexGenerator = ConverCPPIntToHex(generator_);\n\n  } catch (const boost::exception& e) {\n    return {Result::Fail, boost::diagnostic_information(e)};\n  }\n\n  return Result{Result::Success};\n}\n\nResult DiffieHellmanBoost::GenerateKeys() {\n  try {\n    // It will return prime len - 1 anyway because we always set the top bit.\n    // For example, 255 for a 256 bit prime.\n    unsigned int len = boost::multiprecision::msb(prime_);\n\n    // Configure the generator.\n    cpp_int max = cpp_int{1} << len;\n    boost::random::uniform_int_distribution<cpp_int> generatePrivateKey{0, max};\n    boost::random::mt11213b privateKeyGenerator(clock());\n\n    // Generate the private key.\n    cpp_int privateKey = generatePrivateKey(privateKeyGenerator);\n\n    // Derive the public key.\n    cpp_int publicKey = boost::multiprecision::powm(generator_, privateKey, prime_);\n\n    privateKey_ = std::move(privateKey);\n    publicKey_ = std::move(publicKey);\n\n  } catch (const boost::exception& e) {\n    return {Result::Fail, boost::diagnostic_information(e)};\n  }\n\n  return {Result::Success};\n}\n\nResult DiffieHellmanBoost::GetPrivateKey(std::string* hexPrivateKey) const {\n  try {\n    hexPrivateKey->clear();\n    hexPrivateKey->append(ConverCPPIntToHex(privateKey_));\n    if (hexPrivateKey->empty()) {\n      return {Result::Fail, \"The private key is empty.\"};\n    }\n  } catch (const boost::exception& e) {\n    return {Result::Fail, boost::diagnostic_information(e)};\n  }\n\n  return Result{Result::Success};\n}\n\nResult DiffieHellmanBoost::GetPublicKey(std::string* hexPublicKey) const {\n  try {\n    hexPublicKey->clear();\n    hexPublicKey->append(ConverCPPIntToHex(publicKey_));\n    if (hexPublicKey->empty()) {\n      return {Result::Fail, \"The public key is empty.\"};\n    }\n  } catch (const boost::exception& e) {\n    return {Result::Fail, boost::diagnostic_information(e)};\n  }\n\n  return Result{Result::Success};\n}\n\nstatic Result CheckPublicKey(const boost::multiprecision::cpp_int& prime,\n    const boost::multiprecision::cpp_int& publicKey) {\n  try {\n    if (publicKey <= 1) {\n      return {Result::Fail, \"The public key is too small.\"};\n    }\n    if (publicKey >= prime) {\n      return {Result::Fail, \"The public key is too large.\"};\n    }\n\n  } catch (const boost::exception& e) {\n    return {Result::Fail, boost::diagnostic_information(e)};\n  }\n   \n  return {Result::Success};\n}\n\nResult DiffieHellmanBoost::DeriveSharedSecret(std::string_view hexPeerPublicKey,\n    std::string* hexSharedSecret) const {\n  try {\n    cpp_int peerPublicKey = ConveryHexToCPPInt(hexPeerPublicKey);\n\n    if (Result result = CheckPublicKey(prime_, peerPublicKey); !result) {\n      return result;\n    }\n\n    cpp_int sharedSecret = boost::multiprecision::powm(peerPublicKey, privateKey_, prime_);\n    *hexSharedSecret = ConverCPPIntToHex(sharedSecret);\n\n  } catch (const boost::exception& e) {\n    return {Result::Fail, boost::diagnostic_information(e)};\n  }\n  return {Result::Success};\n}\n\nstd::tuple<int, int> DiffieHellmanBoost::GetPrimeLength() const {\n  try {\n    // bytes = (bits - 1) / 8 + 1\n    return {boost::multiprecision::msb(prime_) + 1,\n      boost::multiprecision::msb(prime_) / 8 + 1};\n  } catch (...) {\n  }\n\n  return {-1, -1};\n}\n\nstd::tuple<int, int> DiffieHellmanBoost::GetPrivateKeyLength() const {\n  try {\n    return {boost::multiprecision::msb(privateKey_) + 1,\n      boost::multiprecision::msb(privateKey_) / 8 + 1};\n  } catch (...) {\n  }\n\n  return {-1, -1};\n}\n\nstd::tuple<int, int> DiffieHellmanBoost::GetPublicKeyLength() const {\n  try {\n    return {boost::multiprecision::msb(publicKey_) + 1,\n      boost::multiprecision::msb(publicKey_) / 8 + 1};\n  } catch (...) {\n  }\n\n  return {-1, -1};\n}\n\nunsigned int DiffieHellmanBoost::GetMillerRabinMinChecks(int primeLengthInBits) {\n  if (primeLengthInBits > 2048) {\n    return 128;\n  }\n  return 64;\n}\n\nint DiffieHellmanBoost::GetTrivialDivisionNum(int primeLengthInBits) {\n  if (primeLengthInBits <= 512) {\n    return 64;\n  } else if (primeLengthInBits <= 1024) {\n    return 128;\n  } else if (primeLengthInBits <= 2048) {\n    return 384;\n  } else if (primeLengthInBits <= 4096) {\n    return 1024;\n  }\n  return Primes.size();\n}\n\nstd::tuple<cpp_int, cpp_int> DiffieHellmanBoost::GetAddRem(int generator) {\n  // See dh_builtin_genparams\n  // libressl: crypto\\dh\\dh_gen.c \n  boost::multiprecision::cpp_int add, rem;\n  switch (generator) {\n  case 2:\n    add = 24;\n    rem = 11;\n    break;\n  case 5:\n    add = 10;\n    rem = 3;\n    break;\n  default:\n    add = 2;\n    rem = 1;\n  }\n  return {add, rem};\n}\n\ncpp_int DiffieHellmanBoost::ProbableSafePrime(int primeLengthInBits,\n    int generator, boost::random::mt11213b& primeGenerator) {\n  int trivialDivisionNum = GetTrivialDivisionNum(primeLengthInBits);\n  std::uint64_t maxDelta = 0xFFFFFFFFFFFFFFFFULL - Primes[trivialDivisionNum - 1];\n\n  // Prepare cpp_int add/rem for the generator.\n  auto [add, rem] = GetAddRem(generator);\n\n  // Prepare the top bit.\n  cpp_int topBit = cpp_int{0x80} << (primeLengthInBits - 8);\n\n  // Prepare the bottom bit.\n  cpp_int bottomBit{1};\n\n  // Generation limits.\n  cpp_int max = cpp_int{1} << primeLengthInBits;\n  boost::random::uniform_int_distribution<cpp_int> generatePrime{0, max};\n\n  cpp_int rnd;\n  while (true) {\n    rnd = generatePrime(primeGenerator);\n\n    // Add top/bottom.\n    rnd = rnd | topBit | bottomBit;\n\n    // The prime should fulfill the condition prime % add == rem\n    // in order to suit a given generator.\n    cpp_int mod = rnd % add;\n    rnd = rnd - mod + rem;\n\n    // Probably the second condition is overhead?\n    if (boost::multiprecision::msb(rnd) + 1 < primeLengthInBits || rnd < 5) {\n      rnd += add;\n    }\n\n    auto [success, delta] = IncreaseProbabilityOfBeingPrime(primeLengthInBits, rnd, add);\n    if (success) {\n      rnd += delta;\n      break;\n    }\n  }\n\n  return rnd;\n}\n\nstd::tuple<bool, std::uint64_t>\nDiffieHellmanBoost::IncreaseProbabilityOfBeingPrime(int primeLengthInBits,\n    cpp_int rnd, cpp_int add) {  \n  int trivialDivisionNum = GetTrivialDivisionNum(primeLengthInBits);\n\n  std::uint64_t maxDelta = 0xFFFFFFFFFFFFFFFFULL - Primes[trivialDivisionNum - 1];\n  std::uint64_t rnd64bit = rnd.convert_to<std::uint64_t>();\n  std::uint64_t add64bit = add.convert_to<std::uint64_t>();\n  std::uint64_t delta = 0;\n\n  auto mods = std::make_unique<std::uint16_t[]>(Primes.size());\n\n  for (int i = 1; i < trivialDivisionNum; ++i) {\n    cpp_int mod = rnd % Primes[i];\n    mods[i] = mod.convert_to<std::uint16_t>();\n  }  \n\n  bool continueTesting = true;\n  while (continueTesting) {\n    continueTesting = false;\n    for (int i = 1; i < trivialDivisionNum; ++i) {\n      // Check if it is a prime.\n      if (primeLengthInBits <= 31 && delta <= 0x7FFFFFFF) {\n        std::uint64_t sq = static_cast<std::uint64_t>(Primes[i]) *\n          static_cast<std::uint64_t>(Primes[i]);\n        if (sq > rnd64bit + delta) {\n          return {true, delta};\n        }\n      }\n      // prime mod p == 1 implies q = (prime - 1) / 2 is divisible by p.\n      if ((mods[i] + delta) % Primes[i] <= 1) {\n        delta += add64bit;\n        if (delta > maxDelta) {\n          return {false, 0};\n        }\n        continueTesting = true;\n        break;\n      }\n    }\n  }\n\n  return {true, delta};\n}", "meta": {"hexsha": "38dce852ff081ebeec5e52121b38a559413e2573", "size": 10027, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/diffie-hellman-boost.cpp", "max_stars_repo_name": "Eugen15/diffie-hellman-cpp", "max_stars_repo_head_hexsha": "436ed068b45e07d09d1e5fb167709f7e96da1312", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2022-02-14T02:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:13:25.000Z", "max_issues_repo_path": "src/diffie-hellman-boost.cpp", "max_issues_repo_name": "eugen15/diffie-hellman-cpp", "max_issues_repo_head_hexsha": "436ed068b45e07d09d1e5fb167709f7e96da1312", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/diffie-hellman-boost.cpp", "max_forks_repo_name": "eugen15/diffie-hellman-cpp", "max_forks_repo_head_hexsha": "436ed068b45e07d09d1e5fb167709f7e96da1312", "max_forks_repo_licenses": ["BSD-3-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.566951567, "max_line_length": 113, "alphanum_fraction": 0.6710880622, "num_tokens": 2780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6207813247075796}}
{"text": "//\n// Created by kerail on 10.07.16.\n//\n\n#ifndef DAISU_SO3_HPP\n#define DAISU_SO3_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <cmath>\n#include <limits>\n\ntemplate<class T>\nclass SO3 {\n public:\n  typedef Eigen::Matrix<T, 3, 1> Vector3;\n  typedef Eigen::Matrix<T, 3, 3> Matrix33;\n  typedef Eigen::Quaternion<T> Quaternion;\n\n  SO3(const T &x, const T &y, const T &z) {\n    m_coeffs = Eigen::Vector3d(x, y, z);\n  }\n\n  SO3(const Vector3 &v) {\n    m_coeffs = v;\n  }\n\n  SO3(T angle, const Vector3 &v) {\n    m_coeffs = v * angle;\n  }\n\n  SO3(const Quaternion &q_) {\n    fromQuaternion(q_);\n  }\n\n  SO3(const Matrix33 &m) {\n    assert(isRotationMatrix(m));\n    //TODO: implement\n  }\n\n  Matrix33 getMatrix() const {\n    Matrix33 m;\n    const Vector3 &cfs = m_coeffs;\n\n    T l2 = cfs.squaredNorm();\n    T l = sqrt(l2);\n\n    T sn_l, cs1_ll, cs;\n    if (l == T(0)) {\n      // if l is 0 sin(x)/x = 1\n      sn_l = T(1);\n    } else {\n      sn_l = sin(l) / l;\n    }\n\n    cs = cos(l);\n    static const T c_pi4096 = cos(M_PI / T(4096));\n    if (cs > c_pi4096) {//fabs(l) < M_PI/T(4096)\n      // when l is near nezo, we need to switch to more precise formula\n      if (l2 == T(0)) {\n        // when l2 is zero, we can precisely calculate limit\n        cs1_ll = 1 / T(2);\n      } else {\n        // 1 - cos(x) = 2 * sin(x/2)^2\n        T sn = sin(l / T(2));\n        cs1_ll = T(2) * sn * sn / l2;\n      }\n    } else {\n      // here l2 > 0 because abs(l) > pi/4096\n      cs1_ll = (T(1) - cs) / l2;\n    }\n\n    Vector3 sn_ax = sn_l * m_coeffs;\n    Vector3 cs1_l_ax = cs1_ll * m_coeffs;\n\n    T tmp;\n    tmp = cs1_l_ax.x() * m_coeffs.y();\n    m.coeffRef(0, 1) = tmp - sn_ax.z();\n    m.coeffRef(1, 0) = tmp + sn_ax.z();\n\n    tmp = cs1_l_ax.x() * m_coeffs.z();\n    m.coeffRef(0, 2) = tmp + sn_ax.y();\n    m.coeffRef(2, 0) = tmp - sn_ax.y();\n\n    tmp = cs1_l_ax.y() * m_coeffs.z();\n    m.coeffRef(1, 2) = tmp - sn_ax.x();\n    m.coeffRef(2, 1) = tmp + sn_ax.x();\n\n    m.diagonal() = (cs1_l_ax.cwiseProduct(m_coeffs)).array() + cs;\n\n//    Vector3 sq = cs1_l_ax.cwiseProduct(m_coeffs);\n//    m.coeffRef(0, 0) = 1 + (-sq.y() - sq.z());\n//    m.coeffRef(1, 1) = 1 + (-sq.x() - sq.z());\n//    m.coeffRef(2, 2) = 1 + (-sq.x() - sq.y());\n\n    // Rotation matrix checks\n    assert(isRotationMatrix(m));\n    return m;\n  }\n\n  Quaternion getQuaternion() const {\n    const Vector3 cf2 = m_coeffs / T(2);\n    T a = cf2.norm();\n    if (a > T(0)) {\n      T sn = sin(a) / a;\n      return Quaternion(cos(a), cf2.x() * sn, cf2.y() * sn, cf2.z() * sn);\n    } else {\n      return Quaternion(T(1), cf2.x(), cf2.y(), cf2.z());\n    }\n  }\n\n  Vector3 rotateVector(const Vector3 &v) const {\n    T l2 = m_coeffs.squaredNorm();\n    T l = sqrt(l2);\n\n    T sa_l, ca, ca1_ll;\n    if (l == T(0)) {\n      sa_l = 1;\n    } else {\n      sa_l = sin(l) / l;\n    }\n\n    ca = cos(l);\n\n    static const T c_pi4096 = cos(M_PI / T(4096));\n    if (ca > c_pi4096) {//fabs(l) < M_PI/T(4096)\n      // when l is near nezo, we need to switch to more precise formula\n      if (l2 == T(0)) {\n        // when l2 is zero, we can precisely calculate limit\n        ca1_ll = 1 / T(2);\n      } else {\n        // 1 - cos(x) = 2 * sin(x/2)^2\n        T sn = sin(l / T(2));\n        ca1_ll = T(2) * sn * sn / l2;\n      }\n    } else {\n      // here l2 > 0 because abs(l) > pi/4096\n      ca1_ll = (T(1) - ca) / l2;\n    }\n\n    return v * ca + (m_coeffs * sa_l).cross(v) + m_coeffs * ((m_coeffs.dot(v)) * ca1_ll);\n  }\n\n  Vector3 coeffs() const {\n    return m_coeffs;\n  }\n\n  T getAngle() const {\n    return m_coeffs.norm();\n  }\n\n  Vector3 getAxis() const {\n    T a = getAngle();\n    return a > 0 ? (Vector3) (m_coeffs / a) : m_coeffs;\n  }\n\n  SO3<T> inverted() const {\n    return SO3<T>(-m_coeffs);\n  }\n\n  SO3<T> operator *(const SO3<T> &r) {\n    SO3<T> l(*this);\n    return l *= r;\n  }\n\n  SO3<T> &operator *=(const SO3<T> &l) {\n    fromQuaternion(getQuaternion() * l.getQuaternion());\n    return *this;\n  }\n\n  SO3<T> operator ~() {\n    return inverted();\n  }\n\n private:\n  Vector3 m_coeffs;\n\n  void fromQuaternion(const Quaternion &q_) {\n    const Quaternion &q = q_.w() >= T(0) ? q_ : Quaternion(-q_.coeffs());\n\n    const Vector3 &qv = q.vec();\n    T sinha = qv.norm();\n    if (sinha > T(0)) {\n      T angle = T(2) * atan2(sinha, q.w()); //NOTE: signed\n      m_coeffs = qv * (angle / sinha);\n    } else {\n      // if l is too small, its norm can be equal 0 but norm_inf greater 0\n      // probably w is much bigger that vec, use it as length\n      m_coeffs = qv * (T(2) / q.w()); ////NOTE: signed\n    }\n  }\n  bool isRotationMatrix(const Matrix33 &m) const {\n    return ((m * m.transpose() - Matrix33::Identity()).norm() < 1e-10)\n           && (fabs(fabs(m.determinant()) - 1) < 1e-10);\n  }\n};\n\ntypedef SO3<double> SO3d;\ntypedef SO3<float> SO3f;\n\n#endif //DAISU_SO3_HPP\n", "meta": {"hexsha": "2da3b5e2a7ef740082f9d62769eb5e3282b0674b", "size": 4783, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geom/SO3.hpp", "max_stars_repo_name": "kerail/Daisu", "max_stars_repo_head_hexsha": "d028dd44bf94c3a94897b508beae4efc384bffd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geom/SO3.hpp", "max_issues_repo_name": "kerail/Daisu", "max_issues_repo_head_hexsha": "d028dd44bf94c3a94897b508beae4efc384bffd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geom/SO3.hpp", "max_forks_repo_name": "kerail/Daisu", "max_forks_repo_head_hexsha": "d028dd44bf94c3a94897b508beae4efc384bffd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6782178218, "max_line_length": 89, "alphanum_fraction": 0.533974493, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.6207402511490417}}
{"text": "\n/********************************************************************************************/\n/*                                                                                          */\n/*                                HSO3.hpp header file                                      */\n/*                                                                                          */\n/* This file is not currently part of the Boost library. It is simply an example of the use */\n/* quaternions can be put to. Hopefully it will be useful too.                              */\n/*                                                                                          */\n/* This file provides tools to convert between quaternions and R^3 rotation matrices.       */\n/*                                                                                          */\n/********************************************************************************************/\n\n//  (C) Copyright Hubert Holin 2001.\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef TEST_HSO3_HPP\n#define TEST_HSO3_HPP\n\n#include <algorithm>\n\n#if    defined(__GNUC__) && (__GNUC__ < 3)\n#include <boost/limits.hpp>\n#else\n#include <limits>\n#endif\n\n#include <stdexcept>\n#include <string>\n\n#include <boost/math/quaternion.hpp>\n\n\n#if    defined(__GNUC__) && (__GNUC__ < 3)\n// gcc 2.x ignores function scope using declarations, put them here instead:\nusing    namespace ::std;\nusing    namespace ::boost::math;\n#endif\n\ntemplate<typename TYPE_FLOAT>\nstruct  R3_matrix\n{\n    TYPE_FLOAT a11, a12, a13;\n    TYPE_FLOAT a21, a22, a23;\n    TYPE_FLOAT a31, a32, a33;\n};\n\n\n// Note:    the input quaternion need not be of norm 1 for the following function\n\ntemplate<typename TYPE_FLOAT>\nR3_matrix<TYPE_FLOAT>    quaternion_to_R3_rotation(::boost::math::quaternion<TYPE_FLOAT> const & q)\n{\n    using    ::std::numeric_limits;\n\n    TYPE_FLOAT    a = q.R_component_1();\n    TYPE_FLOAT    b = q.R_component_2();\n    TYPE_FLOAT    c = q.R_component_3();\n    TYPE_FLOAT    d = q.R_component_4();\n\n    TYPE_FLOAT    aa = a*a;\n    TYPE_FLOAT    ab = a*b;\n    TYPE_FLOAT    ac = a*c;\n    TYPE_FLOAT    ad = a*d;\n    TYPE_FLOAT    bb = b*b;\n    TYPE_FLOAT    bc = b*c;\n    TYPE_FLOAT    bd = b*d;\n    TYPE_FLOAT    cc = c*c;\n    TYPE_FLOAT    cd = c*d;\n    TYPE_FLOAT    dd = d*d;\n\n    TYPE_FLOAT    norme_carre = aa+bb+cc+dd;\n\n    if    (norme_carre <= numeric_limits<TYPE_FLOAT>::epsilon())\n    {\n        ::std::string            error_reporting(\"Argument to quaternion_to_R3_rotation is too small!\");\n        ::std::underflow_error   bad_argument(error_reporting);\n\n        throw(bad_argument);\n    }\n\n    R3_matrix<TYPE_FLOAT>    out_matrix;\n\n    out_matrix.a11 = (aa+bb-cc-dd)/norme_carre;\n    out_matrix.a12 = 2*(-ad+bc)/norme_carre;\n    out_matrix.a13 = 2*(ac+bd)/norme_carre;\n    out_matrix.a21 = 2*(ad+bc)/norme_carre;\n    out_matrix.a22 = (aa-bb+cc-dd)/norme_carre;\n    out_matrix.a23 = 2*(-ab+cd)/norme_carre;\n    out_matrix.a31 = 2*(-ac+bd)/norme_carre;\n    out_matrix.a32 = 2*(ab+cd)/norme_carre;\n    out_matrix.a33 = (aa-bb-cc+dd)/norme_carre;\n\n    return(out_matrix);\n}\n\n\n    template<typename TYPE_FLOAT>\n    void    find_invariant_vector(  R3_matrix<TYPE_FLOAT> const & rot,\n                                    TYPE_FLOAT & x,\n                                    TYPE_FLOAT & y,\n                                    TYPE_FLOAT & z)\n    {\n        using    ::std::sqrt;\n\n        using    ::std::numeric_limits;\n\n        TYPE_FLOAT    b11 = rot.a11 - static_cast<TYPE_FLOAT>(1);\n        TYPE_FLOAT    b12 = rot.a12;\n        TYPE_FLOAT    b13 = rot.a13;\n        TYPE_FLOAT    b21 = rot.a21;\n        TYPE_FLOAT    b22 = rot.a22 - static_cast<TYPE_FLOAT>(1);\n        TYPE_FLOAT    b23 = rot.a23;\n        TYPE_FLOAT    b31 = rot.a31;\n        TYPE_FLOAT    b32 = rot.a32;\n        TYPE_FLOAT    b33 = rot.a33 - static_cast<TYPE_FLOAT>(1);\n\n        TYPE_FLOAT    minors[9] =\n        {\n            b11*b22-b12*b21,\n            b11*b23-b13*b21,\n            b12*b23-b13*b22,\n            b11*b32-b12*b31,\n            b11*b33-b13*b31,\n            b12*b33-b13*b32,\n            b21*b32-b22*b31,\n            b21*b33-b23*b31,\n            b22*b33-b23*b32\n        };\n\n        TYPE_FLOAT *        where = ::std::max_element(minors, minors+9);\n\n        TYPE_FLOAT          det = *where;\n\n        if    (det <= numeric_limits<TYPE_FLOAT>::epsilon())\n        {\n            ::std::string            error_reporting(\"Underflow error in find_invariant_vector!\");\n            ::std::underflow_error   processing_error(error_reporting);\n\n            throw(processing_error);\n        }\n\n        switch    (where-minors)\n        {\n            case 0:\n\n                z = static_cast<TYPE_FLOAT>(1);\n\n                x = (-b13*b22+b12*b23)/det;\n                y = (-b11*b23+b13*b21)/det;\n\n                break;\n\n            case 1:\n\n                y = static_cast<TYPE_FLOAT>(1);\n\n                x = (-b12*b23+b13*b22)/det;\n                z = (-b11*b22+b12*b21)/det;\n\n                break;\n\n            case 2:\n\n                x = static_cast<TYPE_FLOAT>(1);\n\n                y = (-b11*b23+b13*b21)/det;\n                z = (-b12*b21+b11*b22)/det;\n\n                break;\n\n            case 3:\n\n                z = static_cast<TYPE_FLOAT>(1);\n\n                x = (-b13*b32+b12*b33)/det;\n                y = (-b11*b33+b13*b31)/det;\n\n                break;\n\n            case 4:\n\n                y = static_cast<TYPE_FLOAT>(1);\n\n                x = (-b12*b33+b13*b32)/det;\n                z = (-b11*b32+b12*b31)/det;\n\n                break;\n\n            case 5:\n\n                x = static_cast<TYPE_FLOAT>(1);\n\n                y = (-b11*b33+b13*b31)/det;\n                z = (-b12*b31+b11*b32)/det;\n\n                break;\n\n            case 6:\n\n                z = static_cast<TYPE_FLOAT>(1);\n\n                x = (-b23*b32+b22*b33)/det;\n                y = (-b21*b33+b23*b31)/det;\n\n                break;\n\n            case 7:\n\n                y = static_cast<TYPE_FLOAT>(1);\n\n                x = (-b22*b33+b23*b32)/det;\n                z = (-b21*b32+b22*b31)/det;\n\n                break;\n\n            case 8:\n\n                x = static_cast<TYPE_FLOAT>(1);\n\n                y = (-b21*b33+b23*b31)/det;\n                z = (-b22*b31+b21*b32)/det;\n\n                break;\n\n            default:\n\n                ::std::string        error_reporting(\"Impossible condition in find_invariant_vector\");\n                ::std::logic_error   processing_error(error_reporting);\n\n                throw(processing_error);\n\n                break;\n        }\n\n        TYPE_FLOAT    vecnorm = sqrt(x*x+y*y+z*z);\n\n        if    (vecnorm <= numeric_limits<TYPE_FLOAT>::epsilon())\n        {\n            ::std::string            error_reporting(\"Overflow error in find_invariant_vector!\");\n            ::std::overflow_error    processing_error(error_reporting);\n\n            throw(processing_error);\n        }\n\n        x /= vecnorm;\n        y /= vecnorm;\n        z /= vecnorm;\n    }\n\n\n    template<typename TYPE_FLOAT>\n    void    find_orthogonal_vector( TYPE_FLOAT x,\n                                    TYPE_FLOAT y,\n                                    TYPE_FLOAT z,\n                                    TYPE_FLOAT & u,\n                                    TYPE_FLOAT & v,\n                                    TYPE_FLOAT & w)\n    {\n        using    ::std::abs;\n        using    ::std::sqrt;\n\n        using    ::std::numeric_limits;\n\n        TYPE_FLOAT    vecnormsqr = x*x+y*y+z*z;\n\n        if    (vecnormsqr <= numeric_limits<TYPE_FLOAT>::epsilon())\n        {\n            ::std::string            error_reporting(\"Underflow error in find_orthogonal_vector!\");\n            ::std::underflow_error   processing_error(error_reporting);\n\n            throw(processing_error);\n        }\n\n        TYPE_FLOAT        lambda;\n\n        TYPE_FLOAT        components[3] =\n        {\n            abs(x),\n            abs(y),\n            abs(z)\n        };\n\n        TYPE_FLOAT *    where = ::std::min_element(components, components+3);\n\n        switch    (where-components)\n        {\n            case 0:\n\n                if    (*where <= numeric_limits<TYPE_FLOAT>::epsilon())\n                {\n                    v =\n                    w = static_cast<TYPE_FLOAT>(0);\n                    u = static_cast<TYPE_FLOAT>(1);\n                }\n                else\n                {\n                    lambda = -x/vecnormsqr;\n\n                    u = static_cast<TYPE_FLOAT>(1) + lambda*x;\n                    v = lambda*y;\n                    w = lambda*z;\n                }\n\n                break;\n\n            case 1:\n\n                if    (*where <= numeric_limits<TYPE_FLOAT>::epsilon())\n                {\n                    u =\n                    w = static_cast<TYPE_FLOAT>(0);\n                    v = static_cast<TYPE_FLOAT>(1);\n                }\n                else\n                {\n                    lambda = -y/vecnormsqr;\n\n                    u = lambda*x;\n                    v = static_cast<TYPE_FLOAT>(1) + lambda*y;\n                    w = lambda*z;\n                }\n\n                break;\n\n            case 2:\n\n                if    (*where <= numeric_limits<TYPE_FLOAT>::epsilon())\n                {\n                    u =\n                    v = static_cast<TYPE_FLOAT>(0);\n                    w = static_cast<TYPE_FLOAT>(1);\n                }\n                else\n                {\n                    lambda = -z/vecnormsqr;\n\n                    u = lambda*x;\n                    v = lambda*y;\n                    w = static_cast<TYPE_FLOAT>(1) + lambda*z;\n                }\n\n                break;\n\n            default:\n\n                ::std::string        error_reporting(\"Impossible condition in find_invariant_vector\");\n                ::std::logic_error   processing_error(error_reporting);\n\n                throw(processing_error);\n\n                break;\n        }\n\n        TYPE_FLOAT    vecnorm = sqrt(u*u+v*v+w*w);\n\n        if    (vecnorm <= numeric_limits<TYPE_FLOAT>::epsilon())\n        {\n            ::std::string            error_reporting(\"Underflow error in find_orthogonal_vector!\");\n            ::std::underflow_error   processing_error(error_reporting);\n\n            throw(processing_error);\n        }\n\n        u /= vecnorm;\n        v /= vecnorm;\n        w /= vecnorm;\n    }\n\n\n    // Note:    we want [[v, v, w], [r, s, t], [x, y, z]] to be a direct orthogonal basis\n    //            of R^3. It might not be orthonormal, however, and we do not check if the\n    //            two input vectors are colinear or not.\n\n    template<typename TYPE_FLOAT>\n    void    find_vector_for_BOD(TYPE_FLOAT x,\n                                TYPE_FLOAT y,\n                                TYPE_FLOAT z,\n                                TYPE_FLOAT u,\n                                TYPE_FLOAT v,\n                                TYPE_FLOAT w,\n                                TYPE_FLOAT & r,\n                                TYPE_FLOAT & s,\n                                TYPE_FLOAT & t)\n    {\n        r = +y*w-z*v;\n        s = -x*w+z*u;\n        t = +x*v-y*u;\n    }\n\n\n\ntemplate<typename TYPE_FLOAT>\ninline bool                                is_R3_rotation_matrix(R3_matrix<TYPE_FLOAT> const & mat)\n{\n    using    ::std::abs;\n\n    using    ::std::numeric_limits;\n\n    return    (\n                !(\n                    (abs(mat.a11*mat.a11+mat.a21*mat.a21+mat.a31*mat.a31 - static_cast<TYPE_FLOAT>(1)) > static_cast<TYPE_FLOAT>(10)*numeric_limits<TYPE_FLOAT>::epsilon())||\n                    (abs(mat.a11*mat.a12+mat.a21*mat.a22+mat.a31*mat.a32 - static_cast<TYPE_FLOAT>(0)) > static_cast<TYPE_FLOAT>(10)*numeric_limits<TYPE_FLOAT>::epsilon())||\n                    (abs(mat.a11*mat.a13+mat.a21*mat.a23+mat.a31*mat.a33 - static_cast<TYPE_FLOAT>(0)) > static_cast<TYPE_FLOAT>(10)*numeric_limits<TYPE_FLOAT>::epsilon())||\n                    //(abs(mat.a11*mat.a12+mat.a21*mat.a22+mat.a31*mat.a32 - static_cast<TYPE_FLOAT>(0)) > static_cast<TYPE_FLOAT>(10)*numeric_limits<TYPE_FLOAT>::epsilon())||\n                    (abs(mat.a12*mat.a12+mat.a22*mat.a22+mat.a32*mat.a32 - static_cast<TYPE_FLOAT>(1)) > static_cast<TYPE_FLOAT>(10)*numeric_limits<TYPE_FLOAT>::epsilon())||\n                    (abs(mat.a12*mat.a13+mat.a22*mat.a23+mat.a32*mat.a33 - static_cast<TYPE_FLOAT>(0)) > static_cast<TYPE_FLOAT>(10)*numeric_limits<TYPE_FLOAT>::epsilon())||\n                    //(abs(mat.a11*mat.a13+mat.a21*mat.a23+mat.a31*mat.a33 - static_cast<TYPE_FLOAT>(0)) > static_cast<TYPE_FLOAT>(10)*numeric_limits<TYPE_FLOAT>::epsilon())||\n                    //(abs(mat.a12*mat.a13+mat.a22*mat.a23+mat.a32*mat.a33 - static_cast<TYPE_FLOAT>(0)) > static_cast<TYPE_FLOAT>(10)*numeric_limits<TYPE_FLOAT>::epsilon())||\n                    (abs(mat.a13*mat.a13+mat.a23*mat.a23+mat.a33*mat.a33 - static_cast<TYPE_FLOAT>(1)) > static_cast<TYPE_FLOAT>(10)*numeric_limits<TYPE_FLOAT>::epsilon())\n                )\n            );\n}\n\n\ntemplate<typename TYPE_FLOAT>\n::boost::math::quaternion<TYPE_FLOAT>    R3_rotation_to_quaternion(    R3_matrix<TYPE_FLOAT> const & rot,\n                                                                    ::boost::math::quaternion<TYPE_FLOAT> const * hint = 0)\n{\n    using    ::boost::math::abs;\n\n    using    ::std::abs;\n    using    ::std::sqrt;\n\n    using    ::std::numeric_limits;\n\n    if    (!is_R3_rotation_matrix(rot))\n    {\n        ::std::string        error_reporting(\"Argument to R3_rotation_to_quaternion is not an R^3 rotation matrix!\");\n        ::std::range_error   bad_argument(error_reporting);\n\n        throw(bad_argument);\n    }\n\n    ::boost::math::quaternion<TYPE_FLOAT>    q;\n\n    if    (\n            (abs(rot.a11 - static_cast<TYPE_FLOAT>(1)) <= numeric_limits<TYPE_FLOAT>::epsilon())&&\n            (abs(rot.a22 - static_cast<TYPE_FLOAT>(1)) <= numeric_limits<TYPE_FLOAT>::epsilon())&&\n            (abs(rot.a33 - static_cast<TYPE_FLOAT>(1)) <= numeric_limits<TYPE_FLOAT>::epsilon())\n        )\n    {\n        q = ::boost::math::quaternion<TYPE_FLOAT>(1);\n    }\n    else\n    {\n        TYPE_FLOAT    cos_theta = (rot.a11+rot.a22+rot.a33-static_cast<TYPE_FLOAT>(1))/static_cast<TYPE_FLOAT>(2);\n        TYPE_FLOAT    stuff = (cos_theta+static_cast<TYPE_FLOAT>(1))/static_cast<TYPE_FLOAT>(2);\n        TYPE_FLOAT    cos_theta_sur_2 = sqrt(stuff);\n        TYPE_FLOAT    sin_theta_sur_2 = sqrt(1-stuff);\n\n        TYPE_FLOAT    x;\n        TYPE_FLOAT    y;\n        TYPE_FLOAT    z;\n\n        find_invariant_vector(rot, x, y, z);\n\n        TYPE_FLOAT    u;\n        TYPE_FLOAT    v;\n        TYPE_FLOAT    w;\n\n        find_orthogonal_vector(x, y, z, u, v, w);\n\n        TYPE_FLOAT    r;\n        TYPE_FLOAT    s;\n        TYPE_FLOAT    t;\n\n        find_vector_for_BOD(x, y, z, u, v, w, r, s, t);\n\n        TYPE_FLOAT    ru = rot.a11*u+rot.a12*v+rot.a13*w;\n        TYPE_FLOAT    rv = rot.a21*u+rot.a22*v+rot.a23*w;\n        TYPE_FLOAT    rw = rot.a31*u+rot.a32*v+rot.a33*w;\n\n        TYPE_FLOAT    angle_sign_determinator = r*ru+s*rv+t*rw;\n\n        if        (angle_sign_determinator > +numeric_limits<TYPE_FLOAT>::epsilon())\n        {\n            q = ::boost::math::quaternion<TYPE_FLOAT>(cos_theta_sur_2, +x*sin_theta_sur_2, +y*sin_theta_sur_2, +z*sin_theta_sur_2);\n        }\n        else if    (angle_sign_determinator < -numeric_limits<TYPE_FLOAT>::epsilon())\n        {\n            q = ::boost::math::quaternion<TYPE_FLOAT>(cos_theta_sur_2, -x*sin_theta_sur_2, -y*sin_theta_sur_2, -z*sin_theta_sur_2);\n        }\n        else\n        {\n            TYPE_FLOAT    desambiguator = u*ru+v*rv+w*rw;\n\n            if    (desambiguator >= static_cast<TYPE_FLOAT>(1))\n            {\n                q = ::boost::math::quaternion<TYPE_FLOAT>(0, +x, +y, +z);\n            }\n            else\n            {\n                q = ::boost::math::quaternion<TYPE_FLOAT>(0, -x, -y, -z);\n            }\n        }\n    }\n\n    if    ((hint != 0) && (abs(*hint+q) < abs(*hint-q)))\n    {\n        return(-q);\n    }\n\n    return(q);\n}\n\n#endif /* TEST_HSO3_HPP */\n", "meta": {"hexsha": "ed91a58613b963b13b936a8c36a68f46f46b4778", "size": 16064, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/HSO3.hpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/HSO3.hpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/HSO3.hpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 31.5599214145, "max_line_length": 175, "alphanum_fraction": 0.4893550797, "num_tokens": 3892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297781091839, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.6207402456285935}}
{"text": "//\r\n\r\n#include <string>\r\n#include <vector>\r\n//#include <tuple>\r\n#include <cstdio>\r\n\r\n#include <Eigen/Sparse>\r\n\r\n#include \"SparseMatrix.hpp\"\r\n#include \"SparseVector.hpp\"\r\n#include \"DenseVector.hpp\"\r\n#include \"KernelComposer.hpp\"\r\n#include \"KernelComposerHelpers.hpp\"\r\n\r\n#include \"gtest/gtest.h\"\r\n\r\nTEST(KCEndToEnd,Thermal){\r\n    swSim::KernelComposer ThermalKernel;\r\n    swSim::SparseMatrix DiffusionKernel;\r\n    swSim::SparseVector SurfaceFlux;\r\n    swSim::DenseVector TikTemp;\r\n    swSim::DenseVector TocTemp;\r\n\r\n    std::vector<double> HeatPulse;\r\n    \r\n    std::vector<double> TikTempStdVec;\r\n    std::vector<double> TocTempStdVec;\r\n    Eigen::SparseVector<double> SurfaceFluxEigVec;\r\n    Eigen::SparseMatrix<double,1> DiffusionKernelEigMat;\r\n    \r\n    double Fo=0.125;\r\n    int Nx,Ny,Nz,Nt,N,idx;\r\n    Nx=100;Ny=100;Nz=100;Nt=10000;N=Nx*Ny*Nz;\r\n    \r\n    DiffusionKernelEigMat.resize(N,N);\r\n    SurfaceFluxEigVec.resize(N);\r\n    for(int kz=0;kz<Nz;kz++){\r\n        for(int ky=0;ky<Ny;ky++){\r\n            for(int kx=0;kx<Nx;kx++){\r\n                idx=kx+Nx*(ky+Ny*kz);\r\n                DiffusionKernelEigMat.coeffRef(idx,idx)=1.0;\r\n                if(kx>0 && kx<(Nx-1) &&\r\n                   ky>0 && ky<(Ny-1) &&\r\n                   kz>0 && kz<(Nz-1)){\r\n                    DiffusionKernelEigMat.coeffRef(idx,idx)-=6.0*Fo;\r\n                    DiffusionKernelEigMat.coeffRef(idx,idx-1)=Fo;\r\n                    DiffusionKernelEigMat.coeffRef(idx,idx+1)=Fo;\r\n                    DiffusionKernelEigMat.coeffRef(idx,idx-Nx)=Fo;\r\n                    DiffusionKernelEigMat.coeffRef(idx,idx+Nx)=Fo;\r\n                    DiffusionKernelEigMat.coeffRef(idx,idx-(Nx*Ny))=Fo;\r\n                    DiffusionKernelEigMat.coeffRef(idx,idx+(Nx*Ny))=Fo;\r\n                };\r\n                TikTempStdVec.push_back(0.0);\r\n                TocTempStdVec.push_back(0.0);\r\n            };\r\n        };\r\n    };\r\n    DiffusionKernelEigMat.makeCompressed();\r\n    for(int ky=(Ny*7/16);ky<(Ny*9/16);ky++){\r\n        for(int kx=(Nx*7/16);kx<(Nx*9/16);kx++){\r\n            SurfaceFluxEigVec.coeffRef(kx+Nx*ky)=1.0;\r\n        };\r\n    };\r\n    for(int kt=0;kt<Nt/2;kt++){\r\n        HeatPulse.push_back(1.0);\r\n    };\r\n    \r\n    DiffusionKernel.mat=DiffusionKernelEigMat;\r\n    TikTemp.setVector(TikTempStdVec);\r\n    TocTemp.setVector(TocTempStdVec);\r\n    SurfaceFlux.vec=SurfaceFluxEigVec;\r\n    \r\n    ThermalKernel.setSparseMatrix(&DiffusionKernel);\r\n    ThermalKernel.setDenseVector(&TikTemp);\r\n    ThermalKernel.setDenseVector(&TocTemp);\r\n    ThermalKernel.setSparseVector(&SurfaceFlux);\r\n    \r\n    //Configure test, ensure configuration is correct\r\n    ASSERT_FALSE(ThermalKernel.isCommitted());\r\n    ASSERT_EQ(ThermalKernel.setSPMV(DiffusionKernel.getName(),\r\n                TikTemp.getName(),TocTemp.getName(),1.0,0.0),swSim::KC_OK);\r\n    ASSERT_EQ(ThermalKernel.setSPaXPY(SurfaceFlux.getName(),\r\n                TocTemp.getName(),&HeatPulse),swSim::KC_OK);\r\n    ASSERT_EQ(ThermalKernel.setSPMV(DiffusionKernel.getName(),\r\n                TocTemp.getName(),TikTemp.getName(),1.0,0.0),swSim::KC_OK);\r\n    ASSERT_EQ(ThermalKernel.setSPaXPY(SurfaceFlux.getName(),\r\n                TikTemp.getName(),&HeatPulse),swSim::KC_OK);\r\n    ASSERT_EQ(ThermalKernel.kernelCommit(),swSim::KC_OK);\r\n    ASSERT_TRUE(ThermalKernel.isCommitted());\r\n    ASSERT_EQ(ThermalKernel.run(Nt),swSim::KC_OK);\r\n    ASSERT_EQ(ThermalKernel.getDeviceData(TikTemp.getName()),swSim::KC_OK);\r\n    ASSERT_EQ(ThermalKernel.kernelDecommit(),swSim::KC_OK);\r\n    ASSERT_FALSE(ThermalKernel.isCommitted());\r\n    \r\n    FILE* pfile;\r\n    pfile=fopen(\"ThermalSim.dat\",\"wb\");\r\n    ASSERT_NE(pfile,nullptr);\r\n    fwrite(TikTemp.getValueArray(),sizeof(double),N,pfile);\r\n    fclose(pfile);\r\n};", "meta": {"hexsha": "17e805541b404e3843b33a058d27558ef44f8518", "size": 3719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/src/KCThermalTest.cpp", "max_stars_repo_name": "nasa/swSim", "max_stars_repo_head_hexsha": "348ba39ea149711a2285916a2dcddc2c71da4859", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T09:49:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T09:54:54.000Z", "max_issues_repo_path": "testing/src/KCThermalTest.cpp", "max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-21-00042", "max_issues_repo_head_hexsha": "348ba39ea149711a2285916a2dcddc2c71da4859", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "testing/src/KCThermalTest.cpp", "max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-21-00042", "max_forks_repo_head_hexsha": "348ba39ea149711a2285916a2dcddc2c71da4859", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-04-27T09:52:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:22:16.000Z", "avg_line_length": 36.8217821782, "max_line_length": 76, "alphanum_fraction": 0.6195213767, "num_tokens": 1036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178928, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.6207402454013508}}
{"text": "/**\n *\n * \\copyright\n * Copyright (c) 2012-2022, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include <tclap/CmdLine.h>\n\n#include <algorithm>\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <memory>\n#include <numeric>\n\n#include \"Applications/FileIO/AsciiRasterInterface.h\"\n#include \"GeoLib/AABB.h\"\n#include \"GeoLib/Point.h\"\n#include \"GeoLib/Raster.h\"\n\ndouble compute2DGaussBellCurveValues(GeoLib::Point const& point,\n                                     GeoLib::AABB const& aabb)\n{\n    auto const sigma_x = (aabb.getMaxPoint() - aabb.getMinPoint())[0] / 3;\n    auto const sigma_y = (aabb.getMaxPoint() - aabb.getMinPoint())[1] / 3;\n\n    auto const mid_point = (aabb.getMaxPoint() + aabb.getMinPoint()) / 2;\n\n    return std::exp(\n        -0.5 * std::pow((point[0] - mid_point[0]), 2) / std::pow(sigma_x, 2) -\n        0.5 * std::pow((point[1] - mid_point[1]), 2) / std::pow(sigma_y, 2));\n}\n\ndouble computeSinXSinY(GeoLib::Point const& point, GeoLib::AABB const& aabb)\n{\n    auto const aabb_size = aabb.getMaxPoint() - aabb.getMinPoint();\n    auto const offset = aabb.getMinPoint();\n\n    return std::sin((point[0] - offset[0]) / aabb_size[0] *\n                    boost::math::double_constants::pi) *\n           std::sin((point[1] - offset[1]) / aabb_size[1] *\n                    boost::math::double_constants::pi);\n}\n\nint main(int argc, char* argv[])\n{\n    TCLAP::CmdLine cmd(\"Add values to raster.\", ' ', \"0.1\");\n\n    TCLAP::ValueArg<std::string> out_raster_arg(\n        \"o\",\n        \"output_raster\",\n        \"the output raster is stored to a file of this name\",\n        true,\n        \"\",\n        \"filename for raster output\");\n    cmd.add(out_raster_arg);\n\n    TCLAP::ValueArg<double> scaling_arg(\n        \"\",\n        \"scaling_value\",\n        \"value the function sin(x pi) sin(y pi) will be scaled with\",\n        false,\n        1,\n        \"double value\");\n    cmd.add(scaling_arg);\n\n    TCLAP::ValueArg<double> offset_arg(\n        \"\",\n        \"offset_value\",\n        \"constant added to the function 'scaling * sin(x pi) * sin(y pi)'\",\n        false,\n        0,\n        \"double value\");\n    cmd.add(offset_arg);\n\n    TCLAP::ValueArg<double> ll_x_arg(\n        \"\",\n        \"ll_x\",\n        \"x coordinate of lower left point of axis aligned rectangular region\",\n        false,\n        0,\n        \"double value\");\n    cmd.add(ll_x_arg);\n    TCLAP::ValueArg<double> ll_y_arg(\n        \"\",\n        \"ll_y\",\n        \"y coordinate of lower left point of axis aligned rectangular region\",\n        false,\n        0,\n        \"double value\");\n    cmd.add(ll_y_arg);\n    TCLAP::ValueArg<double> ur_x_arg(\"\",\n                                     \"ur_x\",\n                                     \"x coordinate of the upper right point of \"\n                                     \"axis aligned rectangular region\",\n                                     false,\n                                     0,\n                                     \"double value\");\n    cmd.add(ur_x_arg);\n    TCLAP::ValueArg<double> ur_y_arg(\"\",\n                                     \"ur_y\",\n                                     \"y coordinate of the upper right point of \"\n                                     \"axis aligned rectangular region\",\n                                     false,\n                                     0,\n                                     \"double value\");\n\n    cmd.add(ur_y_arg);\n    std::vector<std::string> allowed_functions_vector{\"sinxsiny\", \"exp\"};\n    TCLAP::ValuesConstraint<std::string> allowed_functions(\n        allowed_functions_vector);\n    TCLAP::ValueArg<std::string> function_arg(\n        \"f\", \"function\", \"Name of the function used to modify the raster\", true,\n        \"\", &allowed_functions);\n    cmd.add(function_arg);\n    TCLAP::ValueArg<std::string> input_arg(\"i\", \"input\",\n                                           \"Name of the input raster (*.asc)\",\n                                           true, \"\", \"input file name\");\n    cmd.add(input_arg);\n\n    cmd.parse(argc, argv);\n\n    std::array input_points = {\n        GeoLib::Point{{ll_x_arg.getValue(), ll_y_arg.getValue(), 0}},\n        GeoLib::Point{{ur_x_arg.getValue(), ur_y_arg.getValue(), 0}}};\n    GeoLib::AABB const aabb{std::begin(input_points), std::end(input_points)};\n\n    auto const s = scaling_arg.getValue();\n    auto const offset = offset_arg.getValue();\n\n    std::unique_ptr<GeoLib::Raster> const raster(\n        FileIO::AsciiRasterInterface::getRasterFromASCFile(\n            input_arg.getValue()));\n    auto const& header = raster->getHeader();\n    auto const& origin = header.origin;\n\n    std::function<double(GeoLib::Point const& p, GeoLib::AABB const& aabb)>\n        computeFunctionValue = function_arg.getValue() == \"sinxsiny\"\n                                   ? computeSinXSinY\n                                   : compute2DGaussBellCurveValues;\n\n    for (std::size_t r = 0; r < header.n_rows; r++)\n    {\n        for (std::size_t c = 0; c < header.n_cols; c++)\n        {\n            GeoLib::Point const p{{origin[0] + header.cell_size * c,\n                                   origin[1] + header.cell_size * r, 0.0}};\n            if (!aabb.containsPoint(p, std::numeric_limits<double>::epsilon()))\n            {\n                continue;\n            }\n\n            (*raster)(r, c) += offset + s * computeFunctionValue(p, aabb);\n        }\n    }\n\n    FileIO::AsciiRasterInterface::writeRasterAsASC(*raster,\n                                                   out_raster_arg.getValue());\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4005867b72bf40d85ad2385c272d25e78e21dd7e", "size": 5681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Applications/Utils/GeoTools/addDataToRaster.cpp", "max_stars_repo_name": "garibay-j/ogs", "max_stars_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Applications/Utils/GeoTools/addDataToRaster.cpp", "max_issues_repo_name": "garibay-j/ogs", "max_issues_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Applications/Utils/GeoTools/addDataToRaster.cpp", "max_forks_repo_name": "garibay-j/ogs", "max_forks_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6402439024, "max_line_length": 80, "alphanum_fraction": 0.537229361, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787536, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6207402417210521}}
{"text": "/**\n * @file solvecauchyproblem.cc\n * @brief NPDE exam problem summer 2019 \"CLEmpiricFlux\" code\n * @author Oliver Rietmann\n * @date 19.07.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"solvecauchyproblem.h\"\n#include \"uniformcubicspline.h\"\n\n#include <cmath>\n\n#include <Eigen/Core>\n\nnamespace CLEmpiricFlux {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector2d findSupport(const UniformCubicSpline &f,\n                            Eigen::Vector2d initsupp, double t) {\n  Eigen::Vector2d result;\n#if SOLUTION\n  Eigen::Vector2d speed = {f.derivative(-1.0), f.derivative(1.0)};\n  result = initsupp + t * speed;\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 */\ntemplate <typename FUNCTOR>\nEigen::VectorXd semiDiscreteRhs(const Eigen::VectorXd &mu0, double h,\n                                FUNCTOR &&numFlux) {\n  int m = mu0.size();\n  Eigen::VectorXd mu1(m);\n#if SOLUTION\n  mu1(0) = -1.0 / h * (numFlux(mu0(0), mu0(1)) - numFlux(mu0(0), mu0(0)));\n  for (int j = 1; j < m - 1; ++j) {\n    mu1(j) =\n        -1.0 / h * (numFlux(mu0(j), mu0(j + 1)) - numFlux(mu0(j - 1), mu0(j)));\n  }\n  mu1(m - 1) =\n      -1.0 / h *\n      (numFlux(mu0(m - 1), mu0(m - 1)) - numFlux(mu0(m - 2), mu0(m - 1)));\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return mu1;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\ntemplate <typename FUNCTOR>\nEigen::VectorXd RalstonODESolver(FUNCTOR &&rhs, Eigen::VectorXd mu0, double tau,\n                                 int n) {\n#if SOLUTION\n  for (int i = 0; i < n; ++i) {\n    Eigen::VectorXd k1 = rhs(mu0);\n    Eigen::VectorXd k2 = rhs(mu0 + tau * 2.0 / 3.0 * k1);\n    mu0 = mu0 + 0.25 * tau * (k1 + 3.0 * k2);\n  }\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return mu0;\n}\n/* SAM_LISTING_END_3 */\n\n/* SAM_LISTING_BEGIN_4 */\nEigen::VectorXd solveCauchyProblem(const UniformCubicSpline &f,\n                                   const Eigen::VectorXd &mu0, double h,\n                                   double T) {\n  Eigen::VectorXd muT(mu0.size());\n#if SOLUTION\n  double tau = std::min(h / std::abs(f.derivative(-1.0)),\n                        h / std::abs(f.derivative(1.0)));\n  double n = (int)std::floor(T / tau);\n  GodunovFlux godunovFlux(f);\n  auto rhs = [h, &godunovFlux](const Eigen::VectorXd &mu) {\n    return semiDiscreteRhs(mu, h, godunovFlux);\n  };\n  muT = RalstonODESolver(rhs, mu0, tau, n);\n#else\n  //====================\n  // Your code goes here\n  //====================\n#endif\n  return muT;\n}\n/* SAM_LISTING_END_4 */\n\n}  // namespace CLEmpiricFlux\n", "meta": {"hexsha": "334edf33d41b2616c0309afc863d0fb473c84600", "size": 2674, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/CLEmpiricFlux/mastersolution/solvecauchyproblem.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "developers/CLEmpiricFlux/mastersolution/solvecauchyproblem.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "developers/CLEmpiricFlux/mastersolution/solvecauchyproblem.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4752475248, "max_line_length": 80, "alphanum_fraction": 0.5519820494, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6207342738466815}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of variable class.\n */\n#include \"num_collect/auto_diff/forward/variable.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_template_test_macros.hpp>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n#include \"eigen_approx.h\"\n#include \"num_collect/auto_diff/forward/create_diff_variable.h\"\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\n    \"num_collect::auto_diff::forward::variable<Scalar>\", \"\", float, double) {\n    using variable_type = num_collect::auto_diff::forward::variable<TestType>;\n\n    SECTION(\"construct with all arguments\") {\n        constexpr auto value = static_cast<TestType>(1.234);\n        constexpr auto diff = static_cast<TestType>(2.345);\n        const auto var = variable_type(value, diff);\n\n        REQUIRE_THAT(var.value(), Catch::Matchers::WithinRel(value));\n        REQUIRE(var.has_diff());\n        REQUIRE_THAT(var.diff(), Catch::Matchers::WithinRel(diff));\n    }\n\n    SECTION(\"construct with one argument\") {\n        constexpr auto value = static_cast<TestType>(1.234);\n        const auto var = variable_type(value);\n\n        REQUIRE_THAT(var.value(), Catch::Matchers::WithinRel(value));\n        REQUIRE_FALSE(var.has_diff());\n        REQUIRE_THROWS(var.diff());\n    }\n\n    SECTION(\"construct without arguments\") {\n        constexpr auto value = static_cast<TestType>(0.0);\n        const auto var = variable_type();\n\n        REQUIRE_THAT(var.value(), Catch::Matchers::WithinRel(value));\n        REQUIRE_FALSE(var.has_diff());\n        REQUIRE_THROWS(var.diff());\n    }\n\n    SECTION(\"add a variable\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = variable_type(3.456, -4.567);\n        variable_type var = var1;\n        var += var2;\n        REQUIRE_THAT(var.value(),\n            Catch::Matchers::WithinRel(var1.value() + var2.value()));\n        REQUIRE_THAT(\n            var.diff(), Catch::Matchers::WithinRel(var1.diff() + var2.diff()));\n    }\n\n    SECTION(\"add a value\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = static_cast<TestType>(3.456);\n        variable_type var = var1;\n        var += var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1.value() + var2));\n        REQUIRE_THAT(var.diff(), Catch::Matchers::WithinRel(var1.diff()));\n    }\n\n    SECTION(\"subtract a variable\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = variable_type(3.456, -4.567);\n        variable_type var = var1;\n        var -= var2;\n        REQUIRE_THAT(var.value(),\n            Catch::Matchers::WithinRel(var1.value() - var2.value()));\n        REQUIRE_THAT(\n            var.diff(), Catch::Matchers::WithinRel(var1.diff() - var2.diff()));\n    }\n\n    SECTION(\"subtract a value\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = static_cast<TestType>(3.456);\n        variable_type var = var1;\n        var -= var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1.value() - var2));\n        REQUIRE_THAT(var.diff(), Catch::Matchers::WithinRel(var1.diff()));\n    }\n\n    SECTION(\"multiply a variable\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = variable_type(3.456, -4.567);\n        variable_type var = var1;\n        var *= var2;\n        REQUIRE_THAT(var.value(),\n            Catch::Matchers::WithinRel(var1.value() * var2.value()));\n        REQUIRE_THAT(var.diff(),\n            Catch::Matchers::WithinRel(\n                var2.value() * var1.diff() + var1.value() * var2.diff()));\n    }\n\n    SECTION(\"multiply a value\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = static_cast<TestType>(3.456);\n        variable_type var = var1;\n        var *= var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1.value() * var2));\n        REQUIRE_THAT(\n            var.diff(), Catch::Matchers::WithinRel(var2 * var1.diff()));\n    }\n\n    SECTION(\"divide by a variable\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = variable_type(3.456, -4.567);\n        variable_type var = var1;\n        var /= var2;\n        REQUIRE_THAT(var.value(),\n            Catch::Matchers::WithinRel(var1.value() / var2.value()));\n        REQUIRE_THAT(var.diff(),\n            Catch::Matchers::WithinRel(\n                (var2.value() * var1.diff() - var1.value() * var2.diff()) /\n                (var2.value() * var2.value())));\n    }\n\n    SECTION(\"divide by a value\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = static_cast<TestType>(3.456);\n        variable_type var = var1;\n        var /= var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1.value() / var2));\n        REQUIRE_THAT(\n            var.diff(), Catch::Matchers::WithinRel(var1.diff() / var2));\n    }\n}\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\n    \"num_collect::auto_diff::forward::variable<Scalar> operators\", \"\", float,\n    double) {\n    using variable_type = num_collect::auto_diff::forward::variable<TestType>;\n\n    SECTION(\"variable + variable\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = variable_type(3.456, -4.567);\n        const auto var = var1 + var2;\n        REQUIRE_THAT(var.value(),\n            Catch::Matchers::WithinRel(var1.value() + var2.value()));\n        REQUIRE_THAT(\n            var.diff(), Catch::Matchers::WithinRel(var1.diff() + var2.diff()));\n    }\n\n    SECTION(\"value + variable\") {\n        const auto var1 = static_cast<TestType>(1.234);\n        const auto var2 = variable_type(3.456, -4.567);\n        const auto var = var1 + var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1 + var2.value()));\n        REQUIRE_THAT(var.diff(), Catch::Matchers::WithinRel(var2.diff()));\n    }\n\n    SECTION(\"variable + value\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = static_cast<TestType>(3.456);\n        const auto var = var1 + var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1.value() + var2));\n        REQUIRE_THAT(var.diff(), Catch::Matchers::WithinRel(var1.diff()));\n    }\n\n    SECTION(\"variable - variable\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = variable_type(3.456, -4.567);\n        const auto var = var1 - var2;\n        REQUIRE_THAT(var.value(),\n            Catch::Matchers::WithinRel(var1.value() - var2.value()));\n        REQUIRE_THAT(\n            var.diff(), Catch::Matchers::WithinRel(var1.diff() - var2.diff()));\n    }\n\n    SECTION(\"value - variable\") {\n        const auto var1 = static_cast<TestType>(1.234);\n        const auto var2 = variable_type(3.456, -4.567);\n        const auto var = var1 - var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1 - var2.value()));\n        REQUIRE_THAT(var.diff(), Catch::Matchers::WithinRel(-var2.diff()));\n    }\n\n    SECTION(\"variable - value\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = static_cast<TestType>(3.456);\n        const auto var = var1 - var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1.value() - var2));\n        REQUIRE_THAT(var.diff(), Catch::Matchers::WithinRel(var1.diff()));\n    }\n\n    SECTION(\"variable * variable\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = variable_type(3.456, -4.567);\n        const auto var = var1 * var2;\n        REQUIRE_THAT(var.value(),\n            Catch::Matchers::WithinRel(var1.value() * var2.value()));\n        REQUIRE_THAT(var.diff(),\n            Catch::Matchers::WithinRel(\n                var2.value() * var1.diff() + var1.value() * var2.diff()));\n    }\n\n    SECTION(\"value * variable\") {\n        const auto var1 = static_cast<TestType>(1.234);\n        const auto var2 = variable_type(3.456, -4.567);\n        const auto var = var1 * var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1 * var2.value()));\n        REQUIRE_THAT(\n            var.diff(), Catch::Matchers::WithinRel(var1 * var2.diff()));\n    }\n\n    SECTION(\"variable * value\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = static_cast<TestType>(3.456);\n        const auto var = var1 * var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1.value() * var2));\n        REQUIRE_THAT(\n            var.diff(), Catch::Matchers::WithinRel(var2 * var1.diff()));\n    }\n\n    SECTION(\"variable / variable\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = variable_type(3.456, -4.567);\n        const auto var = var1 / var2;\n        REQUIRE_THAT(var.value(),\n            Catch::Matchers::WithinRel(var1.value() / var2.value()));\n        REQUIRE_THAT(var.diff(),\n            Catch::Matchers::WithinRel(\n                (var2.value() * var1.diff() - var1.value() * var2.diff()) /\n                (var2.value() * var2.value())));\n    }\n\n    SECTION(\"value / variable\") {\n        const auto var1 = static_cast<TestType>(1.234);\n        const auto var2 = variable_type(3.456, -4.567);\n        const auto var = var1 / var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1 / var2.value()));\n        REQUIRE_THAT(var.diff(),\n            Catch::Matchers::WithinRel(\n                (-var1 * var2.diff()) / (var2.value() * var2.value())));\n    }\n\n    SECTION(\"variable / variable\") {\n        const auto var1 = variable_type(1.234, 2.345);\n        const auto var2 = static_cast<TestType>(3.456);\n        const auto var = var1 / var2;\n        REQUIRE_THAT(\n            var.value(), Catch::Matchers::WithinRel(var1.value() / var2));\n        REQUIRE_THAT(\n            var.diff(), Catch::Matchers::WithinRel(var1.diff() / var2));\n    }\n}\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\n    \"num_collect::auto_diff::forward::variable<Scalar, Vector> operations\", \"\",\n    float, double) {\n    using diff_type = Eigen::Matrix<TestType, 2, 1>;\n    using variable_type =\n        num_collect::auto_diff::forward::variable<TestType, diff_type>;\n\n    const variable_type left =\n        num_collect::auto_diff::forward::create_diff_variable<TestType,\n            diff_type>(1.234, 2, 0);\n    const variable_type right =\n        num_collect::auto_diff::forward::create_diff_variable<TestType,\n            diff_type>(2.345, 2, 1);\n\n    SECTION(\"addition\") {\n        const variable_type res = left + right;\n        REQUIRE_THAT(res.value(),\n            Catch::Matchers::WithinRel(left.value() + right.value()));\n        REQUIRE_THAT(res.diff(), eigen_approx(left.diff() + right.diff()));\n    }\n\n    SECTION(\"subtraction\") {\n        const variable_type res = left - right;\n        REQUIRE_THAT(res.value(),\n            Catch::Matchers::WithinRel(left.value() - right.value()));\n        REQUIRE_THAT(res.diff(), eigen_approx(left.diff() - right.diff()));\n    }\n\n    SECTION(\"multiplication\") {\n        const variable_type res = left * right;\n        REQUIRE_THAT(res.value(),\n            Catch::Matchers::WithinRel(left.value() * right.value()));\n        REQUIRE_THAT(res.diff(),\n            eigen_approx(\n                right.value() * left.diff() + left.value() * right.diff()));\n    }\n\n    SECTION(\"division\") {\n        const variable_type res = left / right;\n        REQUIRE_THAT(res.value(),\n            Catch::Matchers::WithinRel(left.value() / right.value()));\n        REQUIRE_THAT(res.diff(),\n            eigen_approx(\n                (right.value() * left.diff() - left.value() * right.diff()) /\n                (right.value() * right.value())));\n    }\n}\n\nTEST_CASE(\"Eigen::Matrix<num_collect::auto_diff::forward::variable>\") {\n    using diff_type = Eigen::Vector2d;\n    using variable_type =\n        num_collect::auto_diff::forward::variable<double, diff_type>;\n    using vector_type = Eigen::Matrix<variable_type, 2, 1>;\n    using num_collect::auto_diff::forward::create_diff_variable;\n\n    const auto vec =\n        vector_type(create_diff_variable<double, diff_type>(1.234, 2, 0),\n            create_diff_variable<double, diff_type>(2.345, 2, 1));\n\n    SECTION(\"prod\") {\n        const variable_type res = vec.prod();\n        REQUIRE_THAT(res.value(),\n            Catch::Matchers::WithinRel(vec(0).value() * vec(1).value()));\n        REQUIRE_THAT(res.diff(),\n            eigen_approx(diff_type(vec(1).value(), vec(0).value())));\n    }\n}\n", "meta": {"hexsha": "e0fcbcbc1f708e6296433c3bbb592ad2fb53519c", "size": 13106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/auto_diff/forward/variable_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units/auto_diff/forward/variable_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units/auto_diff/forward/variable_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6609195402, "max_line_length": 79, "alphanum_fraction": 0.5994964139, "num_tokens": 3171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.6207342621712847}}
{"text": "#ifndef AUTOENCODER_H\n#define AUTOENCODER_H\n\n#include \"../../core/utility.hpp\"\n#include \"../../eigen/eigen.hpp\"\n\n#ifdef OCV_TEST_AUTOENCODER\n#include \"../utility/gradient_checking.hpp\"\n#endif\n\n#include \"../../profile/measure.hpp\"\n#include \"propagation.hpp\"\n\n#include <Eigen/Dense>\n\n#include <opencv2/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <Eigen/Dense>\n\n#include <fstream>\n#include <random>\n\n/*! \\file autoencoder.hpp\n    \\brief implement the algorithm--autoencoder based on\\n\n    the description of UFLDL, these codes are develop based\\n\n    on the example on the website(http://eric-yuan.me/simple-deep-network/)\n*/\n\n/*!\n *  \\addtogroup ocv\n *  @{\n */\nnamespace ocv{\n\n/*!\n *  \\addtogroup ml\n *  @{\n */\nnamespace ml{\n\ntemplate<typename T = double>\nclass autoencoder\n{\npublic:\n    using EigenMat = eigen::MatRowMajor<T>;\n\n    struct layer\n    {\n        layer() :\n            cost_{0.0}\n        {\n\n        }\n        layer(int input_size, int hidden_size,\n              double cost = 0) :\n            cost_{cost}\n        {            \n            std::random_device rd;\n            std::default_random_engine re(rd());\n            std::uniform_real_distribution<T> ur(0, 1);\n            ur(re);\n            w1_.resize(hidden_size, input_size);\n            w2_.resize(input_size, hidden_size);\n            b1_ = EigenMat::Zero(hidden_size, 1);\n            b2_ = EigenMat::Zero(input_size, 1);\n\n            for(size_t row = 0; row != w1_.rows(); ++row){\n                for(size_t col = 0; col != w1_.cols(); ++col){\n                    w1_(row, col) = ur(re);\n                }\n            }\n            for(size_t row = 0; row != w2_.rows(); ++row){\n                for(size_t col = 0; col != w2_.cols(); ++col){\n                    w2_(row, col) = ur(re);\n                }\n            }\n\n            double const R  = std::sqrt(6) /\n                    std::sqrt(hidden_size + input_size + 1);\n            w1_ = w1_.array() * 2 * R - R;\n            w2_ = w2_.array() * 2 * R - R;\n\n            w1_grad_ = EigenMat::Zero(hidden_size, input_size);\n            w2_grad_ = EigenMat::Zero(input_size, hidden_size);\n            b1_grad_ = EigenMat::Zero(hidden_size, 1);\n            b2_grad_ = EigenMat::Zero(input_size, 1);\n        }\n\n        EigenMat w1_;\n        EigenMat w2_;\n        EigenMat b1_;\n        EigenMat b2_;\n        EigenMat w1_grad_;\n        EigenMat w2_grad_;\n        EigenMat b1_grad_;\n        EigenMat b2_grad_;\n        double cost_;\n    };\n\n    explicit autoencoder(cv::AutoBuffer<int> const &hidden_size) :\n        reuse_layer_{false}\n    {\n        set_hidden_layer_size(hidden_size);\n    }\n\n    autoencoder& operator=(autoencoder const&) = delete;\n    autoencoder& operator=(autoencoder &&) = delete;\n    autoencoder(autoencoder const&) = delete;\n    autoencoder(autoencoder &&) = delete;    \n\n    EigenMat const& get_last_features() const\n    {\n        return eactivation_;\n    }\n\n    std::vector<layer> const& get_layer() const\n    {\n        return layers_;\n    }\n\n    /**\n     * @brief read the train result from the file(xml)\n     * @param file the file save the train result\n     */\n    void read(std::string const &file)\n    {\n        cv::FileStorage in(file, cv::FileStorage::READ);\n        int layer_size = 0;\n        in[\"layer_size\"]>>layer_size;\n        in[\"batch_size\"]>>params_.batch_size_;\n        in[\"beta_\"]>>params_.beta_;\n        in[\"eps_\"]>>params_.eps_;\n        in[\"lambda_\"]>>params_.lambda_;\n        in[\"lrate_\"]>>params_.lrate_;\n        in[\"max_iter_\"]>>params_.max_iter_;\n        in[\"sparse_\"]>>params_.sparse_;\n        params_.hidden_size_.resize(layer_size);\n        layers_.clear();\n        for(int i = 0; i != layer_size; ++i){\n            cv_layer ls;\n            auto const Index = std::to_string(i);\n            in[\"w1_\" + Index] >> ls.w1_;\n            in[\"w2_\" + Index] >> ls.w2_;\n            in[\"w1_grad_\" + Index] >> ls.w1_grad_;\n            in[\"w2_grad_\" + Index] >> ls.w2_grad_;\n            in[\"b1_\" + Index] >> ls.b1_;\n            in[\"b2_\" + Index] >> ls.b2_;\n            in[\"b1_grad_\" + Index] >> ls.b1_grad_;\n            in[\"b2_grad_\" + Index] >> ls.b2_grad_;\n            in[\"hidden_size_\" + Index]>>\n                                         params_.hidden_size_[i];\n            layer el;\n            convert(ls, el);\n            layers_.emplace_back(el);\n        }\n        cv::Mat activation;\n        in[\"activation\"] >> activation;\n        eigen::cv2eigen_cpy(activation, eactivation_);\n    }\n\n    /**\n     * @brief Set the batch divide parameter, this parameter\\n\n     * will determine the fraction of the samples will be use\\n\n     * when finding the cost\n     * @param size set up the mini-batch size every time the\\n\n     * iteration will use\n     */\n    void set_batch_size(int size)\n    {\n        params_.batch_size_ = size;\n    }\n\n    /**\n     * @brief set the beta of autoencoder\n     * @param beta the weight of the sparsity penalty term.\\n\n     * Must be real positive number.The default value is 3\n     */\n    void set_beta(double beta)\n    {\n        params_.beta_ = beta;\n    }\n\n    /**\n         * @brief set the epsillon\n         * @param eps The desired accuracy or change in parameters\\n\n         *  at which the iterative algorithm stops.\n         */\n    void set_epsillon(double eps){\n        params_.eps_ = eps;\n    }\n\n    /**\n     * @brief set the hidden layers size\n     * @param size size of each hidden layers,must bigger\\n\n     * than zero.The default value is 0\n     */\n    void set_hidden_layer_size(cv::AutoBuffer<int> const &size)\n    {\n        params_.hidden_size_ = size;\n    }\n\n    /**\n     * @brief set the lambda of the regularization term\n     * @param lambda the weight of the regularization term.\\n\n     * Must be real positive number.The default value is 3e-3\n     */\n    void set_lambda(double lambda)\n    {\n        params_.lambda_ = lambda;\n    }\n\n    /**\n     * @brief set the learning rate\n     * @param The larger the lrate, the faster we approach the solution,\\n\n     *  but larger lrate may incurr divergence, must be real\\n\n     *  positive number.The default value is 2e-2\n     */\n    void set_learning_rate(double lrate)\n    {\n        params_.lrate_ = lrate;\n    }\n\n    /**\n     * @brief set maximum iteration time\n     * @param iter the maximum iteration time of the algorithm.\\n\n     * The default value is 80000\n     */\n    void set_max_iter(int iter)\n    {\n\n        params_.max_iter_ = iter;\n    }\n\n    /**\n     * @brief set the sparsity penalty\n     * @param sparse Constraint of the hidden neuron, the lower it is,\\n\n     * the sparser the output of the layer would be.The default\\n\n     * value is 0.1\n     */\n    void set_sparse(double sparse)\n    {\n        params_.sparse_ = sparse;\n    }\n\n    /**\n     * @brief set the trained layer should be reuse or not\n     * @param reuse true will reuse the trained layer if exist;else\\n\n     * the train function will start a new training process\n     */\n    void set_reuse_layer(bool reuse)\n    {\n        reuse_layer_ = reuse;\n    }\n\n    /**\n     * @brief train by sparse autoencoder\n     * @param input the input image, type must be double.\\n\n     * input contains one training example per column\n     */\n\n    /*! \\brief example.\n     *\\code\n     * ocv::eigen::EigenMat buffer(16*16, 10000);\n     * cv::Mat train = ocv::eigen::eigen2cv_ref(buffer);\n     * //read_mnist will read the data of mnist into cv::Mat\n     * read_mnist(train, \"train_0\", 10000);\n     * train /= 255.0;\n     *\n     * cv::AutoBuffer<int> hidden_size(2);\n     * hidden_size[0] = buffer.cols() * 3 / 4;\n     * hidden_size[1] = hidden_size[0];\n     * ocv::ml::autoencoder encoder(hidden_size);\n     * encoder.set_batch_fraction(20);\n     * encoder.train(train);\n     * encoder.write(\"train.xml\");\n     *\\endcode\n    */\n    template<typename Derived>\n    void train(Eigen::MatrixBase<Derived> const &input)\n    {\n        if(!reuse_layer_){\n            layers_.clear();\n        }\n        std::random_device rd;\n        std::default_random_engine re(rd());\n        int const Batch = get_batch_size(input.cols());\n        int const RandomSize = input.cols() != Batch ?\n                    input.cols() - Batch - 1 : 0;\n        std::uniform_int_distribution<int>\n                uni_int(0, RandomSize);\n\n#ifdef OCV_TEST_AUTOENCODER\n        gradient_check();\n#endif\n\n        for(size_t i = 0; i < params_.hidden_size_.size(); ++i){\n            Eigen::MatrixBase<Derived> const &TmpInput =\n                    i == 0 ? input\n                           : eactivation_;\n            if(!reuse_layer_){\n                layer es(TmpInput.rows(), params_.hidden_size_[i]);               \n                reduce_cost(uni_int, re, Batch, TmpInput, es);\n                generate_activation(es, TmpInput,\n                                    i==0?true:false);\n                layers_.push_back(es);\n            }else{                \n                if(layers_.size() <= i){\n                    layers_.emplace_back(static_cast<int>(TmpInput.rows()),\n                                         params_.hidden_size_[i]);\n                }\n                reduce_cost(uni_int, re, Batch, TmpInput, layers_[i]);                \n                generate_activation(layers_[i], TmpInput,\n                                    i==0?true:false);\n            }\n        }\n        act_.clear();\n        buffer_.clear();//*/\n    }\n\n    /**\n     * @brief write the training result into the file(xml)\n     * @param file the name of the file\n     */\n    void write(std::string const &file) const\n    {\n        cv::FileStorage out(file, cv::FileStorage::WRITE);\n        out<<\"layer_size\"<<static_cast<int>(layers_.size());\n        out<<\"batch_size\"<<params_.batch_size_;\n        out<<\"beta_\"<<params_.beta_;\n        out<<\"eps_\"<<params_.eps_;\n        out<<\"lambda_\"<<params_.lambda_;\n        out<<\"lrate_\"<<params_.lrate_;\n        out<<\"max_iter_\"<<params_.max_iter_;\n        out<<\"sparse_\"<<params_.sparse_;\n        for(size_t i = 0; i != layers_.size(); ++i){\n            cv_layer ls;\n            convert(layers_[i], ls);\n            auto const Index = std::to_string(i);\n            out<<(\"w1_\" + Index)<<ls.w1_;\n            out<<(\"w2_\" + Index)<<ls.w2_;\n            out<<(\"w1_grad_\" + Index)<<ls.w1_grad_;\n            out<<(\"w2_grad_\" + Index)<<ls.w2_grad_;\n            out<<(\"b1_\" + Index)<<ls.b1_;\n            out<<(\"b2_\" + Index)<<ls.b2_;\n            out<<(\"b1_grad_\" + Index)<<ls.b1_grad_;\n            out<<(\"b2_grad_\" + Index)<<ls.b2_grad_;\n            out<<(\"hidden_size_\" + Index)<<\n                 params_.hidden_size_[i];\n        }\n        cv::Mat const Activation = eigen::eigen2cv_ref(eactivation_);\n        out<<\"activation\"<<Activation;\n    }\nprivate:\n    using MatType = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n    using Mapper = Eigen::Map<MatType, Eigen::Aligned>;\n    using MapperConst = Eigen::Map<const MatType, Eigen::Aligned>;\n\n    struct activation\n    {\n        void clear()\n        {\n            hidden_.resize(0, 0);\n            output_.resize(0, 0);\n        }\n\n        EigenMat hidden_;\n        EigenMat output_;\n    };\n\n    struct buffer\n    {\n        void clear()\n        {\n            delta2_.resize(0, 0);\n            delta3_.resize(0, 0);\n            delta_buffer_.resize(0, 0);\n            pj_.resize(0, 0);\n            pj_r0_.resize(0, 0);\n            pj_r1_.resize(0, 0);\n        }\n\n        EigenMat delta2_;\n        EigenMat delta3_;\n        EigenMat delta_buffer_;\n        EigenMat pj_; //the average activation of hidden units\n        EigenMat pj_r0_; //same as pj_ expect 0(set to max() of double)\n        EigenMat pj_r1_; //same as pj_ expect 1(set to max() of double)\n    };\n\n    struct cv_layer\n    {\n        cv_layer() :\n            cost_{0}\n        {\n        }\n        cv_layer(int input_size, int hidden_size,\n                 int mat_type,\n                 double cost = 0) :\n            cost_{cost}\n        {\n            w1_.create(hidden_size, input_size, mat_type);\n            w2_.create(input_size, hidden_size, mat_type);\n            b1_.create(hidden_size, 1, mat_type);\n            b2_.create(input_size, 1, mat_type);\n\n            generate_random_value<T>(w1_, 0.12);\n            generate_random_value<T>(w2_, 0.12);\n            generate_random_value<T>(b1_, 0.12);\n            generate_random_value<T>(b2_, 0.12);\n\n            w1_grad_ = cv::Mat::zeros(hidden_size, input_size, mat_type);\n            w2_grad_ = cv::Mat::zeros(input_size, hidden_size, mat_type);\n            b1_grad_ = cv::Mat::zeros(hidden_size, 1, mat_type);\n            b2_grad_ = cv::Mat::zeros(input_size, 1, mat_type);\n        }\n\n        cv::Mat w1_;\n        cv::Mat w2_;\n        cv::Mat b1_;\n        cv::Mat b2_;\n        cv::Mat w1_grad_;\n        cv::Mat w2_grad_;\n        cv::Mat b1_grad_;\n        cv::Mat b2_grad_;\n        double cost_;\n    };\n\n    struct criteria\n    {\n        criteria() :\n            batch_size_{100},\n            beta_{3},\n            eps_{1e-8},\n            lambda_{3e-3},\n            lrate_{2e-2},\n            max_iter_{80000},\n            sparse_{0.1}\n        {\n\n        }\n\n        int batch_size_;\n        double beta_;\n        double eps_;\n        cv::AutoBuffer<int> hidden_size_;\n        double lambda_;\n        double lrate_; //learning rate\n        int max_iter_;\n        double sparse_;\n    };\n\n    void convert(cv_layer const &input,\n                 layer &output) const\n    {\n        eigen::cv2eigen_cpy(input.b1_, output.b1_);\n        eigen::cv2eigen_cpy(input.b2_, output.b2_);\n        eigen::cv2eigen_cpy(input.w1_, output.w1_);\n        eigen::cv2eigen_cpy(input.w2_, output.w2_);\n        eigen::cv2eigen_cpy(input.b1_grad_, output.b1_grad_);\n        eigen::cv2eigen_cpy(input.b2_grad_, output.b2_grad_);\n        eigen::cv2eigen_cpy(input.w1_grad_, output.w1_grad_);\n        eigen::cv2eigen_cpy(input.w2_grad_, output.w2_grad_);\n    }\n    void convert(layer const &input,\n                 cv_layer &output) const\n    {\n        eigen::eigen2cv_cpy(input.b1_, output.b1_);\n        eigen::eigen2cv_cpy(input.b2_, output.b2_);\n        eigen::eigen2cv_cpy(input.w1_, output.w1_);\n        eigen::eigen2cv_cpy(input.w2_, output.w2_);\n        eigen::eigen2cv_cpy(input.b1_grad_, output.b1_grad_);\n        eigen::eigen2cv_cpy(input.b2_grad_, output.b2_grad_);\n        eigen::eigen2cv_cpy(input.w1_grad_, output.w1_grad_);\n        eigen::eigen2cv_cpy(input.w2_grad_, output.w2_grad_);\n    }\n\n    template<typename Derived>\n    void compute_cost(Eigen::MatrixBase<Derived> const &input,\n                      layer &es)\n    {\n        //std::cout<<&input(0, 0)<<\"\\n\";\n        get_last_features(input, es);\n        //std::cout<<\"get activation\\n\";\n        auto const NSamples = input.cols();\n        //square error of back propagation(first half)\n        double const SquareError =\n                ((act_.output_.array() - input.array()).pow(2.0) / 2.0).\n                sum() / NSamples;\n        //std::cout<<\"square error : \"<<SquareError<<\"\\n\";\n        // the second part is weight decay part\n        double const WeightError =\n                ((es.w1_.array() * es.w1_.array()).sum() +\n                 (es.w2_.array() * es.w2_.array()).sum()) *\n                (params_.lambda_ / 2.0);\n        //std::cout<<\"weight error : \"<<WeightError<<\"\\n\";\n\n        // now calculate pj which is the average activation of hidden units\n        buffer_.pj_ = act_.hidden_.rowwise().sum() / NSamples;\n        //prevent division by zero\n        buffer_.pj_r0_ = (buffer_.pj_.array() != 0.0).\n                select(buffer_.pj_, 1000);\n        buffer_.pj_r1_ = (buffer_.pj_.array() != 1.0).\n                select(buffer_.pj_, -1000);//*/\n\n        //the third part of overall cost function is the sparsity part\n        double const Sparse = params_.sparse_;\n        //beta * sum(sparse * log[sparse/pj] +\n        //           (1 - sparse) * log[(1-sparse)/(1-pj)])\n        double const SparseError =\n                ( (Sparse * (Sparse / (buffer_.pj_r0_.array())).log()) +\n                  (1.0-Sparse)*((1.0-Sparse)/(1.0-buffer_.pj_r1_.array())).log()).sum() *\n                params_.beta_;\n        //std::cout<<\"Sparse error : \"<<SparseError<<\"\\n\";\n        es.cost_ = SquareError + WeightError + SparseError;//*/\n    }\n\n    template<typename Derived>\n    void compute_gradient(Eigen::MatrixBase<Derived> const &input,\n                          layer &es)\n    {\n        auto const NSamples = input.cols();\n        buffer_.delta3_ =\n                ((act_.output_.array() - input.array()) / NSamples) *\n                ((1.0 - act_.output_.array()) * act_.output_.array());\n        //std::cout<<buffer_.delta3_<<\"\\n\\n\";\n        es.w2_grad_.noalias() = buffer_.delta3_*act_.hidden_.transpose();\n        es.w2_grad_ = (es.w2_grad_.array()) +\n                params_.lambda_ * es.w2_.array();\n        es.b2_grad_ = buffer_.delta3_.rowwise().sum();\n\n        get_delta_2(buffer_.delta3_, es, NSamples);\n        es.w1_grad_.noalias() = buffer_.delta2_*input.transpose();\n        es.w1_grad_ = (es.w1_grad_.array()) +\n                params_.lambda_ * es.w1_.array();\n        es.b1_grad_ = buffer_.delta2_.rowwise().sum();\n    }\n\n    template<typename Derived>\n    void generate_activation(layer const &ls,\n                             Eigen::MatrixBase<Derived> const &temp_input,\n                             bool no_overlap = true)\n    {\n#ifdef OCV_MEASURE_TIME\n        auto const TGen =\n                time::measure<>::duration([&]()\n        { generate_activation_impl(ls, temp_input,\n                                   no_overlap); });\n        std::cout<<\"time of generate last layer activation : \"<<TGen.count()<<\"\\n\\n\";\n#else\n        generate_activation_impl(ls, temp_input, no_overlap);\n#endif\n    }\n\n    template<typename Derived>\n    void generate_activation_impl(layer const &ls,\n                                  Eigen::MatrixBase<Derived> const &temp_input,\n                                  bool no_overlap = true)\n    {\n        forward_propagation(temp_input, ls.w1_,\n                            ls.b1_, eactivation_,\n                            no_overlap);\n    }\n\n    template<typename Derived>\n    void get_last_features(Eigen::MatrixBase<Derived> const &input,\n                        layer &es)\n    {\n        forward_propagation(input, es.w1_, es.b1_, act_.hidden_);\n        forward_propagation(act_.hidden_, es.w2_, es.b2_, act_.output_);\n    }\n    int get_batch_size(int sample_size) const\n    {\n        return std::min(params_.batch_size_, sample_size);\n    }\n\n    template<typename Derived>\n    void get_delta_2(Eigen::MatrixBase<Derived> const &delta_3,\n                     layer const &es,\n                     size_t sample_size)\n    {\n        buffer_.delta_buffer_ =\n                (params_.beta_ / sample_size) *\n                (-params_.sparse_/(buffer_.pj_r0_.array()) +\n                 (1.0-params_.sparse_)/(1.0-buffer_.pj_r1_.array()));\n\n        Mapper Map(buffer_.delta_buffer_.data(),\n                   buffer_.delta_buffer_.size());\n        buffer_.delta2_.noalias() = es.w2_.transpose() * delta_3;\n        buffer_.delta2_.colwise() += Map;\n        buffer_.delta2_ =\n                buffer_.delta2_.array() *\n                ((1.0 - act_.hidden_.array()) * act_.hidden_.array());\n    }\n\n    void gradient_check()\n    {\n        EigenMat const Input = EigenMat::Random(8, 2);\n        layer es(Input.rows(), Input.rows() / 2);\n        layer es_copy = es;\n        gradient_checking gc;\n        auto func = [&](EigenMat &theta)->T\n        {\n            es.w1_.swap(theta);\n            compute_cost(Input, es);\n            auto const Cost = es.cost_;\n            es.w1_.swap(theta);\n\n            return Cost;\n        };\n        EigenMat const Gradient =\n                gc.compute_gradient(es.w1_,\n                                    func);\n\n        compute_cost(Input, es_copy);\n        compute_gradient(Input, es_copy);\n\n        std::cout<<std::boolalpha<<\"pass : \"<<\n                   gc.compare_gradient(Gradient, es_copy.w1_grad_)<<\"\\n\";\n    }\n\n    template<typename Derived>\n    void reduce_cost(std::uniform_int_distribution<int> const &uni_int,\n                     std::default_random_engine &re,\n                     int batch, Eigen::MatrixBase<Derived> const &input,\n                     layer &ls)\n    {\n        double last_cost = 0.0;\n        auto const LRate = params_.lrate_;\n#ifndef  OCV_MEASURE_TIME\n        for(int j = 0; j != params_.max_iter_; ++j){\n            int const X = uni_int(re);\n            auto const &Temp = input.block(0, X,\n                                           input.rows(), batch);\n            compute_cost(Temp, ls);            \n\n#ifdef OCV_PRINT_COST\n            std::cout<<j<<\" : cost : \"<<ls.cost_\n                    <<\", random : \"<<X<<\"\\n\";\n#endif\n\n            if(std::abs(last_cost - ls.cost_) < params_.eps_ ||\n                    ls.cost_ <= 0.0){\n                break;\n            }\n\n            compute_gradient(Temp, ls);\n            //std::cout<<ls.w1_<<\"\\n\\n\";\n\n            last_cost = ls.cost_;\n            update_weight(ls);\n            //std::cout<<ls.b2_grad_<<\"\\n\\n\";\n        }\n#else\n        double t_cost = 0;\n        double t_gra = 0;\n        double t_update = 0;\n        int iter_time = 1;\n        for(int j = 0; j != params_.max_iter_; ++j){\n            int const X = uni_int(re);\n            auto const &Temp = input.block(0, X,\n                                           input.rows(), batch);\n            t_cost +=\n                    time::measure<>::execution([&]()\n            { compute_cost(Temp, ls); });\n\n#ifdef OCV_PRINT_COST\n            std::cout<<j<<\" : cost : \"<<ls.cost_\n                    <<\", random : \"<<X<<\"\\n\";\n#endif\n\n            if(std::abs(last_cost - ls.cost_) < params_.eps_ ||\n                    ls.cost_ <= 0.0){\n                break;\n            }\n\n            t_gra +=\n                    time::measure<>::execution([&]()\n            { compute_gradient(Temp, ls); });\n            ++iter_time;\n\n            last_cost = ls.cost_;\n            t_update +=\n                    time::measure<>::execution([&]()\n            { update_weight(ls); });            \n        }\n\n        std::cout<<\"total encoder cost time : \"<<t_cost<<\"\\n\";\n        std::cout<<\"total gradient cost time : \"<<t_gra<<\"\\n\";\n        std::cout<<\"total update time : \"<<t_gra<<\"\\n\";\n        std::cout<<\"total time of update weight and bias : \"<<t_update<<\"\\n\";\n        std::cout<<\"average encoder cost time : \"<<t_cost / iter_time<<\"\\n\";\n        std::cout<<\"average gradient cost time : \"<<t_gra / iter_time<<\"\\n\";\n        std::cout<<\"average update time : \"<<t_gra / iter_time<<\"\\n\";\n        std::cout<<\"average time of update weight and bias : \"<<t_update / iter_time<<\"\\n\";\n#endif\n        params_.lrate_ = LRate;\n    }\n\n    void update_weight(layer &ls)\n    {\n        update_weight(ls.w1_grad_, ls.w1_);\n        update_weight(ls.w2_grad_, ls.w2_);\n        update_weight(ls.b1_grad_, ls.b1_);\n        update_weight(ls.b2_grad_, ls.b2_);\n    }\n\n    template<typename Derived>\n    void update_weight(Eigen::MatrixBase<Derived> const &gradient,\n                       Eigen::MatrixBase<Derived> &weight)\n    {\n        weight = weight.array() -\n                params_.lrate_ * gradient.array();\n    }\n\n    activation act_;\n    buffer buffer_;\n    criteria params_;\n    EigenMat eactivation_;\n    std::vector<layer> layers_;\n    bool reuse_layer_;\n};\n\n} /*! @} End of Doxygen Groups*/\n\n} /*! @} End of Doxygen Groups*/\n\n#endif // AUTOENCODER_H\n", "meta": {"hexsha": "1acfb2e32895ac7319c7d1dc0122f560fc887aab", "size": 23380, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ml/deep_learning/autoencoder.hpp", "max_stars_repo_name": "stereomatchingkiss/ocv_libs", "max_stars_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-12-17T05:28:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T02:59:29.000Z", "max_issues_repo_path": "ml/deep_learning/autoencoder.hpp", "max_issues_repo_name": "stereomatchingkiss/ocv_libs", "max_issues_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ml/deep_learning/autoencoder.hpp", "max_forks_repo_name": "stereomatchingkiss/ocv_libs", "max_forks_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-05-10T11:20:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T17:06:06.000Z", "avg_line_length": 32.1153846154, "max_line_length": 91, "alphanum_fraction": 0.5380239521, "num_tokens": 5814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.620663327053236}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// weighted_kurtosis.hpp\n//\n//  Copyright 2006 Olivier Gygi, Daniel Egloff. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_KURTOSIS_HPP_EAN_28_10_2005\n#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_KURTOSIS_HPP_EAN_28_10_2005\n\n#include <limits>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n#include <boost/accumulators/statistics/weighted_moment.hpp>\n#include <boost/accumulators/statistics/weighted_mean.hpp>\n\nnamespace boost { namespace accumulators\n{\n\nnamespace impl\n{\n    ///////////////////////////////////////////////////////////////////////////////\n    // weighted_kurtosis_impl\n    /**\n        @brief Kurtosis estimation for weighted samples\n\n        The kurtosis of a sample distribution is defined as the ratio of the 4th central moment and the square of the 2nd central\n        moment (the variance) of the samples, minus 3. The term \\f$ -3 \\f$ is added in order to ensure that the normal distribution\n        has zero kurtosis. The kurtosis can also be expressed by the simple moments:\n\n        \\f[\n            \\hat{g}_2 =\n                \\frac\n                {\\widehat{m}_n^{(4)}-4\\widehat{m}_n^{(3)}\\hat{\\mu}_n+6\\widehat{m}_n^{(2)}\\hat{\\mu}_n^2-3\\hat{\\mu}_n^4}\n                {\\left(\\widehat{m}_n^{(2)} - \\hat{\\mu}_n^{2}\\right)^2} - 3,\n        \\f]\n\n        where \\f$ \\widehat{m}_n^{(i)} \\f$ are the \\f$ i \\f$-th moment and \\f$ \\hat{\\mu}_n \\f$ the mean (first moment) of the\n        \\f$ n \\f$ samples.\n\n        The kurtosis estimator for weighted samples is formally identical to the estimator for unweighted samples, except that\n        the weighted counterparts of all measures it depends on are to be taken.\n    */\n    template<typename Sample, typename Weight>\n    struct weighted_kurtosis_impl\n      : accumulator_base\n    {\n        typedef typename numeric::functional::multiplies<Sample, Weight>::result_type weighted_sample;\n        // for boost::result_of\n        typedef typename numeric::functional::average<weighted_sample, weighted_sample>::result_type result_type;\n\n        weighted_kurtosis_impl(dont_care)\n        {\n        }\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            return numeric::average(\n                        accumulators::weighted_moment<4>(args)\n                        - 4. * accumulators::weighted_moment<3>(args) * weighted_mean(args)\n                        + 6. * accumulators::weighted_moment<2>(args) * weighted_mean(args) * weighted_mean(args)\n                        - 3. * weighted_mean(args) * weighted_mean(args) * weighted_mean(args) * weighted_mean(args)\n                      , ( accumulators::weighted_moment<2>(args) - weighted_mean(args) * weighted_mean(args) )\n                        * ( accumulators::weighted_moment<2>(args) - weighted_mean(args) * weighted_mean(args) )\n                   ) - 3.;\n        }\n    };\n\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::weighted_kurtosis\n//\nnamespace tag\n{\n    struct weighted_kurtosis\n      : depends_on<weighted_mean, weighted_moment<2>, weighted_moment<3>, weighted_moment<4> >\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::weighted_kurtosis_impl<mpl::_1, mpl::_2> impl;\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::weighted_kurtosis\n//\nnamespace extract\n{\n    extractor<tag::weighted_kurtosis> const weighted_kurtosis = {};\n\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_kurtosis)\n}\n\nusing extract::weighted_kurtosis;\n\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "d51db5cd38d1e02479d8fb438fa1a8ec0d715503", "size": 4153, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/accumulators/statistics/weighted_kurtosis.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T00:29:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T02:59:16.000Z", "max_issues_repo_path": "boost/boost/accumulators/statistics/weighted_kurtosis.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2015-07-22T07:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:03:06.000Z", "max_forks_repo_path": "boost/boost/accumulators/statistics/weighted_kurtosis.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 39.179245283, "max_line_length": 131, "alphanum_fraction": 0.6219600289, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.620663327053236}}
{"text": "\r\n// Copyright 2017 Daniel James.\r\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// clang-format off\r\n#include \"../helpers/prefix.hpp\"\r\n#include <boost/unordered_map.hpp>\r\n#include <boost/unordered_set.hpp>\r\n#include \"../helpers/postfix.hpp\"\r\n// clang-format on\r\n\r\n#include \"../helpers/test.hpp\"\r\n#include <map>\r\n\r\n// Pretty inefficient, but the test is fast enough.\r\n// Might be too slow if we had larger primes?\r\nbool is_prime(std::size_t x)\r\n{\r\n  if (x == 2) {\r\n    return true;\r\n  } else if (x == 1 || x % 2 == 0) {\r\n    return false;\r\n  } else {\r\n    // y*y <= x had rounding errors, so instead use y <= (x/y).\r\n    for (std::size_t y = 3; y <= (x / y); y += 2) {\r\n      if (x % y == 0) {\r\n        return false;\r\n        break;\r\n      }\r\n    }\r\n\r\n    return true;\r\n  }\r\n}\r\n\r\nvoid test_next_prime(std::size_t value)\r\n{\r\n  std::size_t x = boost::unordered::detail::next_prime(value);\r\n  BOOST_TEST(is_prime(x));\r\n  BOOST_TEST(x >= value);\r\n}\r\n\r\nvoid test_prev_prime(std::size_t value)\r\n{\r\n  std::size_t x = boost::unordered::detail::prev_prime(value);\r\n  BOOST_TEST(is_prime(x));\r\n  BOOST_TEST(x <= value);\r\n  if (x > value) {\r\n    BOOST_LIGHTWEIGHT_TEST_OSTREAM << x << \",\" << value << std::endl;\r\n  }\r\n}\r\n\r\nUNORDERED_AUTO_TEST (next_prime_test) {\r\n  BOOST_TEST(!is_prime(0));\r\n  BOOST_TEST(!is_prime(1));\r\n  BOOST_TEST(is_prime(2));\r\n  BOOST_TEST(is_prime(3));\r\n  BOOST_TEST(is_prime(13));\r\n  BOOST_TEST(!is_prime(4));\r\n  BOOST_TEST(!is_prime(100));\r\n\r\n  BOOST_TEST(boost::unordered::detail::next_prime(0) > 0);\r\n\r\n  // test_prev_prime doesn't work for values less than 17.\r\n  // Which should be okay, unless an allocator has a really tiny\r\n  // max_size?\r\n  const std::size_t min_prime = 17;\r\n\r\n  // test_next_prime doesn't work for values greater than this,\r\n  // which might be a problem if you've got terrabytes of memory?\r\n  // I seriously doubt the container would work well at such sizes\r\n  // regardless.\r\n  const std::size_t max_prime = 4294967291ul;\r\n\r\n  std::size_t i;\r\n\r\n  BOOST_TEST(is_prime(min_prime));\r\n  BOOST_TEST(is_prime(max_prime));\r\n\r\n  for (i = 0; i < 10000; ++i) {\r\n    if (i < min_prime) {\r\n      BOOST_TEST(boost::unordered::detail::prev_prime(i) == min_prime);\r\n    } else {\r\n      test_prev_prime(i);\r\n    }\r\n    test_next_prime(i);\r\n  }\r\n\r\n  std::size_t last = i - 1;\r\n  for (; i > last; last = i, i += i / 5) {\r\n    if (i > max_prime) {\r\n      BOOST_TEST(boost::unordered::detail::next_prime(i) == max_prime);\r\n    } else {\r\n      test_next_prime(i);\r\n    }\r\n    test_prev_prime(i);\r\n  }\r\n}\r\n\r\nRUN_TESTS()\r\n", "meta": {"hexsha": "7562fa8401eef5c87cb8c136a1fd541c718f240b", "size": 2653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/unordered/test/unordered/detail_tests.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/unordered/test/unordered/detail_tests.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/unordered/test/unordered/detail_tests.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 26.0098039216, "max_line_length": 80, "alphanum_fraction": 0.6185450433, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6206633021766944}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <boost/math/special_functions/expint.hpp>\n#include <eve/function/exp_int.hpp>\n#include <eve/function/exp.hpp>\n#include <eve/function/oneminus.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/platform.hpp>\n#include <cmath>\n\nTTS_CASE_TPL(\"Check eve::exp_int return type\", EVE_TYPE)\n{\n  TTS_EXPR_IS(eve::exp_int(T(0), T(0)), T);\n  TTS_EXPR_IS(eve::exp_int(0, T(0)), T);\n}\n\nTTS_CASE_TPL(\"Check eve::exp_int behavior\", EVE_TYPE)\n{\n  auto eve__exp_int   =  [](auto x, auto y) { return eve::exp_int(x, y); };\n  auto boost__exp_int =  [](auto x, auto y) { return boost::math::expint(x, y); };\n\n//   if constexpr( eve::platform::supports_invalids )\n//   {\n//     TTS_IEEE_EQUAL(eve__exp_int(T(1), eve::nan(eve::as<T>()))  , eve::nan(eve::as<T>()) );\n//     TTS_IEEE_EQUAL(eve__exp_int(T(1), eve::inf(eve::as<T>()))   , T(0) );\n//   }\n\n\n  for(int i=1; i < 4 ; ++i)\n  {\n    TTS_ULP_EQUAL(eve__exp_int(T(i), T(0))  , eve::rec(T(i-1)), 0.5);\n    TTS_ULP_EQUAL(eve__exp_int(T(i), T(0.5)), T(boost__exp_int(i, 0.5)), 2.0);\n    TTS_ULP_EQUAL(eve__exp_int(T(i), T(1))  , T(boost__exp_int(i, 1.0)), 4.0);\n    TTS_ULP_EQUAL(eve__exp_int(T(i), T(10)) , T(boost__exp_int(i, 10.0)), 0.5);\n  }\n  for(int i=1; i < 4 ; ++i)\n  {\n    TTS_ULP_EQUAL(eve__exp_int(i, T(0))  , eve::rec(T(i-1)), 0.5);\n    TTS_ULP_EQUAL(eve__exp_int(i, T(0.5)), T(boost__exp_int(i, 0.5)), 2.0);\n    TTS_ULP_EQUAL(eve__exp_int(i, T(1))  , T(boost__exp_int(i, 1.0)), 4.0);\n    TTS_ULP_EQUAL(eve__exp_int(i, T(10)) , T(boost__exp_int(i, 10.0)), 0.5);\n  }\n  using elt_t =  eve::element_type_t<T>;\n\n  TTS_ULP_EQUAL(eve__exp_int(elt_t(2.0), elt_t(0.5)), (boost__exp_int(elt_t(2), elt_t(0.5))), 2.0);\n  TTS_ULP_EQUAL(eve__exp_int(elt_t(6000), elt_t(0.5)), (boost__exp_int(elt_t(6000), elt_t(0.5))), 3.0);\n}\n", "meta": {"hexsha": "75c2a2041afa67b1384d978936de7f86d1993f98", "size": 2146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/special/exp_int/regular/exp_int.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/special/exp_int/regular/exp_int.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/special/exp_int/regular/exp_int.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0181818182, "max_line_length": 103, "alphanum_fraction": 0.5810810811, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6206109972661517}}
{"text": "/**\n * @file debuggingfem_main.cc\n * @brief NPDE homework ParametricElementMatrices code\n * @author Simon Meierhans\n * @date 27/03/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/refinement/refinement.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <memory>\n#include <vector>\n\n#include \"locallaplaceqfe.h\"\n#include \"qfeinterpolator.h\"\n#include \"qfeprovidertester.h\"\n\nusing size_type = lf::base::size_type;\n\nint main() {\n  // read mesh\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader(std::move(mesh_factory),\n                            CURRENT_SOURCE_DIR \"/../meshes/square_64.msh\");\n  auto mesh = reader.mesh();\n\n  // refine mesh\n  const int reflevels = 4;\n  std::shared_ptr<lf::refinement::MeshHierarchy> multi_mesh_p =\n      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(mesh, reflevels);\n  lf::refinement::MeshHierarchy &multi_mesh{*multi_mesh_p};\n  lf::base::size_type L = multi_mesh.NumLevels();\n\n  // vector holding pointers to the different element matrix providers\n  std::vector<std::unique_ptr<DebuggingFEM::EntityMatrixProvider>>\n      element_matrix_provider;\n  element_matrix_provider.emplace_back(\n      std::make_unique<DebuggingFEM::LocalLaplaceQFE1>());\n  element_matrix_provider.emplace_back(\n      std::make_unique<DebuggingFEM::LocalLaplaceQFE2>());\n  element_matrix_provider.emplace_back(\n      std::make_unique<DebuggingFEM::LocalLaplaceQFE3>());\n  const int num_emp = element_matrix_provider.size();\n\n  // vectors accumulating the computed errors\n  Eigen::MatrixXd H1SMerr(L, num_emp);\n  Eigen::VectorXi N(L);\n\n  for (int level = 0; level < L; ++level) {\n    // set up fespace and dof handler for the mesh at the current level\n    auto mesh_p = multi_mesh.getMesh(level);\n    lf::uscalfe::FeSpaceLagrangeO2<double> fespace(mesh_p);\n    const auto &dofh = fespace.LocGlobMap();\n\n    // Dimension of finite element space\n    N[level] = dofh.NumDofs();\n\n    // compute error for each element matrix provider\n    for (int i = 0; i < num_emp; ++i) {\n      // function to interpolateOntoQuadFE\n      auto f = [](const Eigen::VectorXd &x) -> double {\n        return std::exp(x(1) * x(1) + x(0) * x(0));\n      };\n      double energy = 0.0;\n      // Matrix in triplet format holding Galerkin for LocalLaplaceQFEX matrix,\n      // zero initially.\n      DebuggingFEM::QFEProviderTester qfe_provider_tester(\n          dofh, *element_matrix_provider[i]);\n      // compute the energy and error\n      energy = qfe_provider_tester.energyOfInterpolant(f);\n      H1SMerr(level, i) = std::abs(23.76088 - energy);\n    }\n  }\n\n  // Tabular output of the results\n  std::cout << std::left << std::setw(10) << \"N\" << std::setw(20)\n            << \"Assember 1\" << std::setw(20) << \"Assembler 2\" << std::setw(20)\n            << \"Assembler 3\" << std::endl;\n  for (int level = 0; level < L; ++level) {\n    std::cout << std::left << std::setw(10) << N[level] << std::setw(20)\n              << H1SMerr(level, 0) << std::setw(20) << H1SMerr(level, 1)\n              << std::setw(20) << H1SMerr(level, 2) << std::endl;\n  }\n\n  // Write .csv file and plot it by a python script\n  Eigen::MatrixXd data(L, num_emp + 1);\n  data.col(0) = N.cast<double>();\n  data.rightCols(num_emp) = H1SMerr;\n  const static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                         Eigen::DontAlignCols, \", \", \"\\n\");\n  std::ofstream error_file;\n  error_file.open(\"error.csv\");\n  error_file << data.format(CSVFormat) << std::endl;\n  error_file.close();\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/error.csv\" << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot_error.py \" CURRENT_BINARY_DIR\n              \"/error.csv \" CURRENT_BINARY_DIR \"/error.eps\");\n\n  return 0;\n}\n", "meta": {"hexsha": "a979c43e304338534cd0c32930414c206c7e74c9", "size": 3934, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/DebuggingFEM/mastersolution/debuggingfem_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/DebuggingFEM/mastersolution/debuggingfem_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/DebuggingFEM/mastersolution/debuggingfem_main.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 35.7636363636, "max_line_length": 80, "alphanum_fraction": 0.6626842908, "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.620607669078932}}
{"text": "#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <utility>\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <common_robotics_utilities/math.hpp>\n#include <common_robotics_utilities/simple_hierarchical_clustering.hpp>\n#include <common_robotics_utilities/simple_kmeans_clustering.hpp>\n\nint main(int argc, char** argv)\n{\n  const size_t num_points\n      = (argc >= 2) ? static_cast<size_t>(atoi(argv[1])) : 1000;\n  std::cout << \"Generating \" << num_points << \" points...\" << std::endl;\n  const int64_t seed = 42;\n  std::mt19937_64 prng(seed);\n  std::uniform_real_distribution<double> dist(0.0, 10.0);\n  std::vector<Eigen::VectorXd> random_points(num_points);\n  std::vector<size_t> indices(num_points);\n  for (size_t idx = 0; idx < num_points; idx++)\n  {\n    const double x = dist(prng);\n    const double y = dist(prng);\n    Eigen::VectorXd random_point(3);\n    random_point << x, y, 0.0;\n    random_points[idx] = random_point;\n    indices[idx] = idx;\n  }\n  const std::vector<bool> use_parallel_options = {false, true};\n  for (const bool use_parallel : use_parallel_options)\n  {\n    std::cout << \"Complete-link hierarchical clustering \" << num_points\n              << \" points...\" << std::endl;\n    std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&)>\n        distance_fn = [] (const Eigen::VectorXd& v1, const Eigen::VectorXd& v2)\n    {\n      return common_robotics_utilities::math::Distance(v1, v2);\n    };\n    const Eigen::MatrixXd distance_matrix\n        = common_robotics_utilities::math\n            ::BuildPairwiseDistanceMatrixParallel(random_points, distance_fn);\n    const std::vector<std::vector<size_t>> hierarchical_index_clusters\n        = common_robotics_utilities::simple_hierarchical_clustering\n            ::ClusterWithDistanceMatrix<int64_t>(\n                indices, distance_matrix, 1.0,\n                common_robotics_utilities::simple_hierarchical_clustering\n                    ::ClusterStrategy::COMPLETE_LINK, use_parallel).first;\n    std::vector<Eigen::VectorXd> hierarchical_clustered_points = random_points;\n    for (size_t cluster_idx = 0;\n         cluster_idx < hierarchical_index_clusters.size(); cluster_idx++)\n    {\n      const std::vector<size_t>& current_cluster\n          = hierarchical_index_clusters[cluster_idx];\n      const double cluster_num = 1.0 + (double)cluster_idx;\n      for (size_t element_idx = 0; element_idx < current_cluster.size();\n           element_idx++)\n      {\n        const size_t index = current_cluster[element_idx];\n        hierarchical_clustered_points.at(index)(2) = cluster_num;\n      }\n    }\n    std::cout << \"K-means clustering \" << num_points << \" points...\"\n              << std::endl;\n    std::function<Eigen::VectorXd(const std::vector<Eigen::VectorXd>&)>\n        average_fn = [] (const std::vector<Eigen::VectorXd>& cluster)\n    {\n      return common_robotics_utilities::math::AverageEigenVectorXd(cluster);\n    };\n    const std::vector<int32_t> kmeans_labels\n        = common_robotics_utilities::simple_kmeans_clustering::Cluster(\n            random_points, distance_fn, average_fn, 50, 42, true, use_parallel);\n    std::vector<Eigen::VectorXd> kmeans_clustered_points = random_points;\n    for (size_t idx = 0; idx < kmeans_clustered_points.size(); idx++)\n    {\n      kmeans_clustered_points.at(idx)(2) = kmeans_labels.at(idx);\n    }\n    std::cout << \"Saving to CSV...\" << std::endl;\n    const std::string hierarchical_log_file_name\n        = (use_parallel) ? \"/tmp/test_parallel_hierarchical_clustering.csv\"\n                         : \"/tmp/test_hierarchical_clustering.csv\";\n    std::ofstream hierarchical_log_file(\n        hierarchical_log_file_name, std::ios_base::out);\n    if (!hierarchical_log_file.is_open())\n    {\n      std::cerr << \"\\x1b[31;1m Unable to create folder/file to log to: \"\n                << hierarchical_log_file_name << \"\\x1b[0m \\n\";\n      throw std::invalid_argument(\"Log filename must be write-openable\");\n    }\n    for (size_t idx = 0; idx < num_points; idx++)\n    {\n      const Eigen::VectorXd& point = hierarchical_clustered_points.at(idx);\n      hierarchical_log_file << point(0) << \",\" << point(1) << \",\" << point(2)\n                            << std::endl;\n    }\n    hierarchical_log_file.close();\n    const std::string kmeans_log_file_name\n        = (use_parallel) ? \"/tmp/test_parallel_kmeans_clustering.csv\"\n                         : \"/tmp/test_kmeans_clustering.csv\";\n    std::ofstream kmeans_log_file(kmeans_log_file_name, std::ios_base::out);\n    if (!kmeans_log_file.is_open())\n    {\n      std::cerr << \"\\x1b[31;1m Unable to create folder/file to log to: \"\n                << kmeans_log_file_name << \"\\x1b[0m \\n\";\n      throw std::invalid_argument(\"Log filename must be write-openable\");\n    }\n    for (size_t idx = 0; idx < num_points; idx++)\n    {\n      const Eigen::VectorXd& point = kmeans_clustered_points.at(idx);\n      kmeans_log_file << point(0) << \",\" << point(1) << \",\" << point(2)\n                      << std::endl;\n    }\n    kmeans_log_file.close();\n  }\n  std::cout << \"Done saving, you can plot as a 3d scatterplot to see clustering\"\n            << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "0181406a0ca30672448490231aa845589b2bd924", "size": 5156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/clustering_example.cpp", "max_stars_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_stars_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/clustering_example.cpp", "max_issues_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_issues_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/clustering_example.cpp", "max_forks_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_forks_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6115702479, "max_line_length": 80, "alphanum_fraction": 0.6530256012, "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6205586522426886}}
{"text": "#include \"triangle.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include <boost/variant.hpp>\n#include <stdexcept>\n#include <complex>\nnamespace\n{\n    ComplexType validate(PASTNode astnode, ParsersHelper& ph, const std::string& fnname)\n    {\n        auto myParserHelper(ph);\n        if (astnode->ch.size()!=2)\n          throw std::runtime_error(fnname+\" can only have one parameter\");\n        auto & secondCh = *astnode->ch.rbegin();\n        ph.parse(secondCh);\n        if (secondCh->token.tokenType != Complex)\n          throw std::runtime_error(\"The argument of \"+fnname+\" must be complex\");\n        return boost::get<ComplexType>(secondCh->token.info).toinexact();\n    }\n}\n\nnamespace HT\n{\n    void sin(PASTNode astnode, ParsersHelper& ph)\n    {\n        \n        auto cast = validate(astnode, ph, \"sin\");\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        auto a = std::complex<long double>(cast.getRealD(), cast.getImagD());\n        auto ans = std::sin(a);\n        astnode->token.info = ComplexType(\n                    ans.real(),\n                    ans.imag()\n                    );\n        astnode->remove();\n    }\n    void cos(PASTNode astnode, ParsersHelper& ph)\n    {\n\n        auto cast = validate(astnode, ph, \"cos\");\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        auto a = std::complex<long double>(cast.getRealD(), cast.getImagD());\n        auto ans = std::cos(a);\n        astnode->token.info = ComplexType(\n                    ans.real(),\n                    ans.imag()\n                    );\n        astnode->remove();\n    }\n    void tan(PASTNode astnode, ParsersHelper& ph)\n    {\n\n        auto cast = validate(astnode, ph, \"tan\");\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        auto a = std::complex<long double>(cast.getRealD(), cast.getImagD());\n        auto ans = std::tan(a);\n        astnode->token.info = ComplexType(\n                    ans.real(),\n                    ans.imag()\n                    );\n        astnode->remove();\n    }\n    void asin(PASTNode astnode, ParsersHelper& ph)\n    {\n\n        auto cast = validate(astnode, ph, \"asin\");\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        auto a = std::complex<long double>(cast.getRealD(), cast.getImagD());\n        auto ans = std::asin(a);\n        if (a.imag() == 0.0 && a.real()>1.0) ans = std::complex<long double>(ans.real(), -ans.imag());\n        astnode->token.info = ComplexType(\n                    ans.real(),\n                    ans.imag()\n                    );\n        astnode->remove();\n    }\n    void acos(PASTNode astnode, ParsersHelper& ph)\n    {\n\n        auto cast = validate(astnode, ph, \"acos\");\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        auto a = std::complex<long double>(cast.getRealD(), cast.getImagD());\n        LOG(\"arg of acos:\"<<a)\n        auto ans = std::acos(a);\n        LOG(\"acos=\"<<ans)\n        if (a.imag() == 0.0 && a.real()>1.0) ans = std::complex<long double>(ans.real(), -ans.imag());\n        astnode->token.info = ComplexType(\n                    ans.real(),\n                    ans.imag()\n                    );\n        astnode->remove();\n    }\n    void atan(PASTNode astnode, ParsersHelper& ph)\n    {\n\n        auto cast = validate(astnode, ph, \"atan\");\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n        auto a = std::complex<long double>(cast.getRealD(), cast.getImagD());\n        auto ans = std::atan(a);\n        astnode->token.info = ComplexType(\n                    ans.real(),\n                    ans.imag()\n                    );\n        astnode->remove();\n    }\n\n}\n\n\n", "meta": {"hexsha": "915858ea35cab2aedd67d7fa081954fb5192f52c", "size": 3728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/triangle.cpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "funs/triangle.cpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funs/triangle.cpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8632478632, "max_line_length": 102, "alphanum_fraction": 0.5276287554, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6205586473816682}}
{"text": "#include <ctime>\n#include <gtest/gtest.h>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n\n#include \"slick/math/se3.h\"\n#include \"slick/test/unittest/util.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace slick;\n\n// constructors tests ==========================================================\ntemplate <typename T>\nvoid DefaultConstructor_Test() {\n  // for double precision\n  SE3Group<T> trans;\n  EXPECT_MATRIX_NEAR(Eigen::Matrix<T, 2, 2>::Identity(), trans.get_rotation().get_matrix(),\n                     Gap<T>());\n  EXPECT_MATRIX_NEAR(Eigen::Matrix<T, 2, 1>::Zero(), trans.get_translation(),\n                     Gap<T>());\n}\n\nTEST(SE3Test, DefaultConstructor) {\n  DefaultConstructor_Test<double>();\n  DefaultConstructor_Test<float>();\n}\n\ntemplate <typename T>\nvoid FromSO3VectorConstructor_Test() {\n  Eigen::Matrix<T, 3, 1> aaxis = Eigen::Matrix<T, 3, 1>::Random();\n  aaxis.normalize();\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n  aaxis *= angle;\n  SO3Group<T> rot(aaxis);\n  Eigen::Matrix<T, 3, 1> t = Eigen::Matrix<T, 3, 1>::Random();\n  SE3Group<T> trans(rot, t);\n\n  EXPECT_MATRIX_NEAR(rot.get_matrix(), trans.get_rotation().get_matrix(),\n                     Gap<T>());\n  EXPECT_MATRIX_NEAR(t, trans.get_translation(),\n                     Gap<T>());\n}\n\nTEST(SE3Test, FromSO3VectorConstructor) {\n  FromSO3VectorConstructor_Test<double>();\n  FromSO3VectorConstructor_Test<float>();\n}\n\n\ntemplate <typename T>\nvoid FromVectorConstructor_Test() {\n  Eigen::Matrix<T, 3, 1> aaxis = Eigen::Matrix<T, 3, 1>::Random();\n  aaxis.normalize();\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand());\n\n  aaxis *= angle;\n  SO3Group<T> rot(aaxis);\n\n  Eigen::Matrix<T, 6, 1> v;\n  v.segment(0, 3) = Eigen::Matrix<T, 3, 1>::Random();\n  v.segment(3, 3) = aaxis;\n  SE3Group<T> trans(v);\n\n  EXPECT_MATRIX_NEAR(rot.get_matrix(), trans.get_rotation().get_matrix(),\n                     Gap<T>());\n}\n\nTEST(SE3Test, FromVectorConstructor) {\n  FromVectorConstructor_Test<double>();\n  FromVectorConstructor_Test<float>();\n}\n\n\n// template <typename T>\n// void FromListInitializerConstructor_Test() {\n//   SE3Group<T> rot{1, 0, 0, 1};\n//   EXPECT_MATRIX_NEAR(Eigen::Matrix<T, 2, 2>::Identity(), rot.get_matrix(),\n//                      Gap<T>());\n\n//   EXPECT_NEAR(0.0, rot.ln(), Gap<T>());\n// }\n\n// TEST(SE3Test, FromListInitializerConstructor) {\n//   FromListInitializerConstructor_Test<double>();\n//   FromListInitializerConstructor_Test<float>();\n// }\n\n// se2 specific functions ======================================================\ntemplate <typename T>\nvoid Ln_Test() {\n  Eigen::Matrix<T, 3, 1> aaxis = Eigen::Matrix<T, 3, 1>::Random();\n  aaxis.normalize();\n  std::srand(std::time(0));  // use current time as seed for random generator\n  auto angle = T(std::rand()) / T(RAND_MAX) * 2 * M_PI;\n  aaxis *= angle;\n  SO3Group<T> rot(aaxis);\n  Eigen::Matrix<T, 3, 1> t = Eigen::Matrix<T, 3, 1>::Random();\n  SE3Group<T> trans(rot, t);\n\n  Eigen::Matrix<T, 3, 1> est_axis = trans.ln().segment(3, 3);\n  T d = est_axis.dot(aaxis);\n  if (d < 0) {\n    auto a = -est_axis.norm() + 2 * M_PI;\n    est_axis = -est_axis.normalized() * a;\n  }\n  EXPECT_MATRIX_NEAR(aaxis, est_axis, Gap<T>());\n}\n\nTEST(SE3Test, Ln) {\n  Ln_Test<double>();\n  Ln_Test<float>();\n}\n\ntemplate <typename T>\nvoid Inverse_Test() {\n  Eigen::Matrix<T, 6, 1> v = Eigen::Matrix<T, 6, 1>::Random();\n  SE3Group<T> trans(v);\n  Eigen::Matrix<T, 3, 3> m_inv = trans.get_rotation().get_matrix().inverse();\n  EXPECT_MATRIX_NEAR(m_inv, trans.inverse().get_rotation().get_matrix(), Gap<T>());\n  // EXPECT_MATRIX_NEAR(-t, trans.inverse().get_translation(), Gap<T>());\n}\n\nTEST(SE3Test, Inverse) {\n  Inverse_Test<double>();\n  Inverse_Test<float>();\n}\n\ntemplate <typename T>\nvoid SE3RightHandMulOperator_Test() {\n  Eigen::Matrix<T, 6, 1> v = Eigen::Matrix<T, 6, 1>::Random();\n  SE3Group<T> trans1(v);\n  Eigen::Matrix<T, 4, 4> mtrans1 = Eigen::Matrix<T, 4, 4>::Identity();\n  mtrans1.block(0, 0, 3, 4) = trans1.get_matrix();\n\n  v = Eigen::Matrix<T, 6, 1>::Random();\n  SE3Group<T> trans2(v);\n  Eigen::Matrix<T, 4, 4> mtrans2 = Eigen::Matrix<T, 4, 4>::Identity();\n  mtrans2.block(0, 0, 3, 4) = trans2.get_matrix();\n\n  EXPECT_MATRIX_NEAR((mtrans1 * mtrans2).block(0, 0, 3, 4), \n    (trans1 * trans2).get_matrix(), Gap<T>());\n}\n\nTEST(SE3Test, SE3RightHandMulOperator) {\n  SE3RightHandMulOperator_Test<double>();\n  SE3RightHandMulOperator_Test<float>();\n}\n\ntemplate <typename T>\nvoid MatrixRightHandMulOperator_Test() {\n  Eigen::Matrix<T, 6, 1> v = Eigen::Matrix<T, 6, 1>::Random();\n  SE3Group<T> trans(v);\n  Eigen::Matrix<T, 4, 4> mtrans = Eigen::Matrix<T, 4, 4>::Identity();\n  mtrans.block(0, 0, 3, 4) = trans.get_matrix();\n\n  Eigen::Matrix<T, 4, 4> mrand = Eigen::Matrix<T, 4, 4>::Random();\n  EXPECT_MATRIX_NEAR(mtrans * mrand, trans * mrand, Gap<T>());\n}\n\nTEST(SE3Test, MatrixRightHandMulOperator) {\n  MatrixRightHandMulOperator_Test<double>();\n  MatrixRightHandMulOperator_Test<float>();\n}\n\ntemplate <typename T>\nvoid MatrixLeftHandMulOperator_Test() {\n  Eigen::Matrix<T, 6, 1> v = Eigen::Matrix<T, 6, 1>::Random();\n  SE3Group<T> trans(v);\n  Eigen::Matrix<T, 4, 4> mtrans = Eigen::Matrix<T, 4, 4>::Identity();\n  mtrans.block(0, 0, 3, 4) = trans.get_matrix();\n\n  Eigen::Matrix<T, 4, 4> mrand = Eigen::Matrix<T, 4, 4>::Random();\n  EXPECT_MATRIX_NEAR(mrand*mtrans , mrand*trans, Gap<T>());\n}\n\nTEST(SE3Test, MatrixLeftHandMulOperator) {\n  MatrixLeftHandMulOperator_Test<double>();\n  MatrixLeftHandMulOperator_Test<float>();\n}\n\nint main(int argc, char** argv) {\n  std::vector<char*> vars(argc+1);\n  for (int i = 0; i < argc; ++i)\n    vars[i] = argv[i];\n  char ca[50];\n  sprintf(ca, \"--gtest_repeat=%d\", NSAMPLES);\n  vars[argc] = ca;\n  argc++;\n  ::testing::InitGoogleTest(&argc, &vars.front());\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "5cabf0eafb8ff54f6217315025fd352b84ca816f", "size": 5873, "ext": "cc", "lang": "C++", "max_stars_repo_path": "slick/test/unittest/math_se3_unittest.cc", "max_stars_repo_name": "williammc/Slick", "max_stars_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-13T05:26:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-13T05:26:40.000Z", "max_issues_repo_path": "slick/test/unittest/math_se3_unittest.cc", "max_issues_repo_name": "williammc/Slick", "max_issues_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slick/test/unittest/math_se3_unittest.cc", "max_forks_repo_name": "williammc/Slick", "max_forks_repo_head_hexsha": "67dec11ea252e7e3a7d6097369a0f313cf1d2fdd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9642857143, "max_line_length": 91, "alphanum_fraction": 0.63868551, "num_tokens": 1759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782276, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.620558625958465}}
{"text": "/*******************************************************************************\n*\n*  Filename    : parameter_arithmatics.cc\n*  Description : Testing the arithmatics of paramters\n*  Author      : Yi-Mu \"Enoch\" Chen [ ensc@hep1.phys.ntu.edu.tw ]\n*\n*******************************************************************************/\n#include \"ManagerUtils/Maths/interface/Parameter.hpp\"\n#include <iostream>\n#include <vector>\n\n#include <boost/format.hpp>\nusing namespace std;\nusing namespace mgr;\n\nvoid\nAddTest( const vector<Parameter>& list )\n{\n    for( size_t i = 0; i < list.size(); ++i ){\n        cout << list[ i ].CentralValue();\n\n        if( i != list.size() - 1 ){\n            cout << \"+\";\n        }\n        else{\n            cout << \" & \";\n        }\n    }\n\n    const Parameter sum = SumUncorrelated( list );\n    cout << sum.CentralValue() << \"&\" << sum.AbsUpperError() << \"&\" << sum.AbsLowerError() << endl;\n}\n\nvoid\nProdTest( const vector<double> chain )\n{\n    Parameter original  = Poisson::Minos( chain.front() );\n    Parameter finalpass = Poisson::Minos( chain.back() );\n    vector<Parameter> prodlist;\n    prodlist.push_back( original );\n    cout << chain.front() << flush;\n\n    for( size_t i = 0; i < chain.size() - 1; ++i ){\n        cout << boost::format( \"\\\\times\\\\frac{%lg}{%lg}\" ) % chain[ i + 1 ] % chain[ i ] << flush;\n        prodlist.push_back( Efficiency::Minos( chain[ i + 1 ], chain[ i ] ) );\n    }\n\n    cout << \"&\" << flush;\n    const Parameter product = ProdUncorrelated( prodlist );\n    cout << product.CentralValue() << \"&\" << product.AbsUpperError() << \"&\" << product.AbsLowerError() << endl;\n}\n\nint\nmain( int argc, char const* argv[] )\n{\n    cout << \">>>> Addition testing: Sum to 100\" << endl;\n    {\n        Parameter a = Poisson::Minos( 10 );\n        Parameter b = Poisson::Minos( 20 );\n        Parameter c = Poisson::Minos( 30 );\n        Parameter d = Poisson::Minos( 40 );\n        Parameter e = Poisson::Minos( 50 );\n        Parameter f = Poisson::Minos( 60 );\n        Parameter g = Poisson::Minos( 70 );\n        Parameter h = Poisson::Minos( 80 );\n        Parameter i = Poisson::Minos( 90 );\n        cout << \"Direct value: \" << FloatingPoint( Poisson::Minos( 100 ), 4 ) << endl;\n        AddTest( { e, e } );\n        AddTest( { d, f } );\n        AddTest( { c, g } );\n        AddTest( { b, h } );\n        AddTest( { a, i } );\n        AddTest( { a, c, c, c } );\n        AddTest( { b, b, b, b, b } );\n        AddTest( { a, a, a, a, a, a, a, a, a, a } );\n        cout << endl;\n    }\n    cout << \">>>> Addition testing: Sum to 1000\" << endl;\n    {\n        Parameter a = Poisson::Minos( 100 );\n        Parameter b = Poisson::Minos( 200 );\n        Parameter c = Poisson::Minos( 300 );\n        Parameter d = Poisson::Minos( 400 );\n        Parameter e = Poisson::Minos( 500 );\n        Parameter f = Poisson::Minos( 600 );\n        Parameter g = Poisson::Minos( 700 );\n        Parameter h = Poisson::Minos( 800 );\n        Parameter i = Poisson::Minos( 900 );\n        cout << \"Direct value: \" << FloatingPoint( Poisson::Minos( 1000 ), 4 ) << endl;\n        AddTest( { e, e } );\n        AddTest( { d, f } );\n        AddTest( { c, g } );\n        AddTest( { b, h } );\n        AddTest( { a, i } );\n        AddTest( { a, c, c, c } );\n        AddTest( { b, b, b, b, b } );\n        AddTest( { a, a, a, a, a, a, a, a, a, a } );\n        cout << endl;\n    }\n    cout << \">>>> Addition testing: Partial addition to 100\" << endl;\n    {\n        Parameter a = Poisson::Minos( 20 );\n        cout << \"Direct value: \" << FloatingPoint( Poisson::Minos( 100 ), 4 ) << endl;\n        cout << \"(20+20+20+20+20) & \" << FloatingPoint( Sum( a, a, a, a, a ), 4 ) << endl;\n        cout << \"(20+20)+(20+20+20) & \" << FloatingPoint( Sum( Sum( a, a ), Sum( a, a, a ) ), 4 ) << endl;\n        cout << \"(20+20)+(20+20)+20 & \" << FloatingPoint( Sum( Sum( a, a ), Sum( a, a ), a ), 4 ) << endl;\n        cout << \"(((20+20)+20)+20)+20 )& \" << FloatingPoint( Sum( Sum( Sum( Sum( a, a ), a ), a ), a ), 4 ) << endl;\n        cout << endl;\n    }\n    cout << \">>>> Product testing: Product to 50\" << endl;\n    {\n        cout << \"Direct value : \" << FloatingPoint( Poisson::Minos( 50 ), 4 ) << endl;\n        ProdTest( { 100, 50 } );\n        ProdTest( { 100, 75, 50 } );\n        ProdTest( { 100, 75, 60, 50 } );\n        ProdTest( { 200, 100, 75, 60, 50 } );\n        cout << endl;\n    }\n    cout << \">>> Product test: Partial product \" << endl;\n    {\n        Parameter a  = Poisson::Minos( 200 );\n        Parameter e1 = Efficiency::Minos( 100, 200 );\n        Parameter e2 = Efficiency::Minos( 75, 100 );\n        Parameter e3 = Efficiency::Minos( 60, 75 );\n        Parameter e4 = Efficiency::Minos( 50, 60 );\n        cout << \"Direct value: \" << FloatingPoint( Poisson::Minos( 50 ), 4 ) << endl;\n        cout << \"(a*b*c*d*e)\" << FloatingPoint( Prod( a, e1, e2, e3, e4 ), 4 ) << endl;\n        cout << \"(a*b)*(c*d*e)\" << FloatingPoint( Prod( Prod( a, e1 ), Prod( e2, e3, e4 ) ), 4 ) << endl;\n        cout << \"(a*b)*(c*d)*e\" << FloatingPoint( Prod( Prod( a, e1 ), Prod( e2, e3 ), e4 ), 4 ) << endl;\n        cout << \"((((a*b)*c)*d)*e)\" << FloatingPoint( Prod( Prod( Prod( Prod( a, e1 ), e2 ), e3 ), e4 ), 4 ) << endl;\n    }\n    cout << \"\\n>>> Another product test: Scale factor tests\" << endl;\n    {\n        Parameter s( 1, 0, 0 );\n        Parameter a( 0.9867, 0.0060, 0.0060 );\n        Parameter b( 0.9791, 0.0132, 0.0132 );\n        Parameter c( 0.9384, 0.0022, 0.0023 );\n        cout << FloatingPoint( a, 3 ) << endl;\n        cout << FloatingPoint( b, 3 ) << endl;\n        cout << FloatingPoint( c, 3 ) << endl;\n        cout << FloatingPoint( Prod( a, b, c ), 3 ) << endl;\n        cout << FloatingPoint( s *= a, 3 ) << endl;\n        cout << FloatingPoint( s *= b, 3 ) << endl;\n        cout << FloatingPoint( s *= c, 3 ) << endl;\n    }\n    cout << \"\\n>> Specical case testing \" << endl;\n    {\n        Parameter a( 11394.14521, +3455.26185, +2904.08486 );\n        Parameter b( 1.65585, +1.88848, +0.83634 );\n        cout << FloatingPoint( a, 5 ) << endl;\n        cout << FloatingPoint( b, 5 ) << endl;\n        a += b;\n        cout << FloatingPoint( a, 5 ) << endl;\n    }\n    cout << \"\\n>>> Scale case testing\" << endl;\n    {\n        Parameter a( 0, 0, 0 );\n        Parameter b = Poisson::Minos( 10 );\n        cout << FloatingPoint( b, 5 ) << endl;\n        cout << FloatingPoint( a + b, 5 ) << endl;\n        cout << FloatingPoint( b + a, 5 ) << endl;\n    }\n    cout << \"\\n>>> Scale product testing\" << endl;\n    {\n        Parameter a( 1, 0.001, 0.2 );\n        Parameter b( 100, 0.1, 0.2 );\n        Parameter c( 1000, 100, 200 );\n        cout << FloatingPoint( Prod( a, b ), 3 ) << endl;\n        cout << FloatingPoint( Prod( b, c ), 3 ) << endl;\n        // cout << FloatingPoint( Prod(c,b), 3 ) << endl;\n        // cout << FloatingPoint( Prod(a,b,c), 3 ) << endl;\n    }\n    cout << \"\\n>>> Product test \" << endl;\n    {\n        Parameter results = Prod(\n            Parameter( 1, 0.0107266, 0.0107266 ),\n            Parameter( 1, 0.0329748, 0.0279871 ),\n            Parameter( 1,         0,  0.170623 ),\n            Parameter( 1,  0.133084,   0.13232 ),\n            Parameter( 1, 0.0243757, 0.0240791 ),\n            Parameter( 1, 0.0257803, 0.0254051 ),\n            Parameter( 1, 0.0249153, 0.0249153 ),\n            Parameter( 1,  0.163553,  0.163553 ),\n            Parameter( 1, 0.0547323, 0.0542217 ),\n            Parameter( 1,     0.046,     0.046 ),\n            Parameter( 1,      0.03,      0.03 )\n            );\n        cout << FloatingPoint( results, 3 ) << endl;\n    }\n    cout << \"\\n>>> Product test\" << endl;\n    {\n        Parameter a( 1, 1.46, 0.787 );\n        Parameter b( 1, 0.046, 0.046 );\n        Parameter c( 1, 0.03, 0.03 );\n        cout << FloatingPoint( Prod( a, b, c ), 5 ) << endl;\n        cout << FloatingPoint( Prod( a, b ), 5 ) << endl;\n        cout << FloatingPoint( Prod( b, c ), 5 ) << endl;\n        cout << FloatingPoint( Prod( a, c ), 5 ) << endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "746f96fbcbe0ef10eef05c3f7b111200a3142136", "size": 7960, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Maths/test/parameter_arithmatics.cc", "max_stars_repo_name": "sam7k9621/ManagerUtils", "max_stars_repo_head_hexsha": "7b9317df002b3df6f23ae9e559d35bb1fc15b6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Maths/test/parameter_arithmatics.cc", "max_issues_repo_name": "sam7k9621/ManagerUtils", "max_issues_repo_head_hexsha": "7b9317df002b3df6f23ae9e559d35bb1fc15b6f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Maths/test/parameter_arithmatics.cc", "max_forks_repo_name": "sam7k9621/ManagerUtils", "max_forks_repo_head_hexsha": "7b9317df002b3df6f23ae9e559d35bb1fc15b6f6", "max_forks_repo_licenses": ["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.4059405941, "max_line_length": 117, "alphanum_fraction": 0.4831658291, "num_tokens": 2556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7057850216484839, "lm_q1q2_score": 0.6204886203389077}}
{"text": "#include <Eigen/Dense>\n\n#include \"DenseMatrix.h\"\n\nstruct RawSubmatrixData::Impl {\n    Eigen::MatrixXd RawData;\n\n  public:\n    Impl() = default;\n};\n\nRawSubmatrixData::RawSubmatrixData() : pImpl {std::make_unique<Impl>()} {}\n\nRawSubmatrixData::~RawSubmatrixData() = default;\nRawSubmatrixData::RawSubmatrixData(RawSubmatrixData&&) noexcept = default;\nRawSubmatrixData& RawSubmatrixData::operator=(RawSubmatrixData&&) noexcept = default;\n\nvoid RawSubmatrixData::add_to_position(double value, uint32_t i, uint32_t j) {\n    pImpl->RawData(i, j) += value;\n}\n\nstd::ostream& operator<<(std::ostream& os, const RawSubmatrixData& decomposition) {\n    os << decomposition.pImpl->RawData << std::endl;\n    return os;\n}\n\nvoid RawSubmatrixData::resize(\n    uint32_t matrix_in_space_basis_size_i,\n    uint32_t matrix_in_space_basis_size_j) {\n    // TODO: is it the fastest way to initialize pImpl->RawData?\n    pImpl->RawData.resize(matrix_in_space_basis_size_i, matrix_in_space_basis_size_j);\n    pImpl->RawData.fill(0);\n}\n\nvoid RawSubmatrixData::diagonalize() {\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;\n    es.compute(pImpl->RawData, Eigen::ComputeEigenvectors);\n    std::cout << es.eigenvalues() << std::endl;\n    std::cout << es.eigenvectors() << std::endl;\n}\n", "meta": {"hexsha": "f37f237a450f5e2c074b7a3d052b2768ef4ec5d6", "size": 1262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/entities/data_structures/DenseMatrix_eigen-matrix-xd.cpp", "max_stars_repo_name": "ruthenium96/july", "max_stars_repo_head_hexsha": "62f93b33253cd7324b36c851afc58b6f80c00248", "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/entities/data_structures/DenseMatrix_eigen-matrix-xd.cpp", "max_issues_repo_name": "ruthenium96/july", "max_issues_repo_head_hexsha": "62f93b33253cd7324b36c851afc58b6f80c00248", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-11-28T14:29:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T08:16:20.000Z", "max_forks_repo_path": "src/entities/data_structures/DenseMatrix_eigen-matrix-xd.cpp", "max_forks_repo_name": "ruthenium96/july", "max_forks_repo_head_hexsha": "62f93b33253cd7324b36c851afc58b6f80c00248", "max_forks_repo_licenses": ["Apache-2.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.7804878049, "max_line_length": 86, "alphanum_fraction": 0.7313787639, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6204564717201827}}
{"text": "#include <iostream>\n#include <cmath>\n#include <pcl/ModelCoefficients.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/filters/project_inliers.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/point_types.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/filters/passthrough.h>\n#include <pcl/features/normal_3d.h>\n#include <pcl/filters/radius_outlier_removal.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/segmentation/extract_clusters.h>\n#include <Eigen/Core>\n#include <pcl/common/transforms.h>\n#include <pcl/common/common.h>\n#include <pcl/common/time.h>\n#include <pcl/common/angles.h>\n#include <pcl/registration/transformation_estimation_svd.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl_ros/point_cloud.h>\n\n#include <ros/ros.h>\n#include <boost/foreach.hpp>\n\n#include <vision_module/obj_mass.h>\n#include <vision_module/rotation_matrix.h>\n#include <vision_module/bbox_size.h>\n\n\nusing namespace std;\ntypedef pcl::PointXYZ PointType;\n\nstatic ros::Subscriber sub;\nstatic ros::Publisher pub1;\nstatic ros::Publisher pub2;\nstatic ros::Publisher pub3;\n\n\n// Get N bits of the string from back to front.\nchar* Substrend(char*str,int n)\n{\n\tchar *substr=(char*)malloc(n+1);\n\tint length=strlen(str);\n\tif (n>=length)\n\t{\n\t\tstrcpy(substr,str);\n\t\treturn substr;\n\t}\n\tint k=0;\n\tfor (int i=length-n;i<length;i++)\n\t{\n\t\tsubstr[k]=str[i];\n\t\tk++;\n\t}\n\tsubstr[k]='\\0';\n\treturn substr;\n}\n\n\nvoid callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr& cloud)\n{\n    printf (\"Cloud: width = %d, height = %d\\n\", cloud->width, cloud->height);\n    // TODO\uff1a process the data point.\n    \n    Eigen::Vector4f pcaCentroid;\n    pcl::compute3DCentroid(*cloud, pcaCentroid);\n    Eigen::Matrix3f covariance;\n    pcl::computeCovarianceMatrixNormalized(*cloud, pcaCentroid, covariance);\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigen_solver(covariance, Eigen::ComputeEigenvectors);\n    Eigen::Matrix3f eigenVectorsPCA = eigen_solver.eigenvectors();\n    Eigen::Vector3f eigenValuesPCA = eigen_solver.eigenvalues();\n\n\n    //Correct vertical between main directions\n    eigenVectorsPCA.col(2) = eigenVectorsPCA.col(0).cross(eigenVectorsPCA.col(1)); \n    eigenVectorsPCA.col(0) = eigenVectorsPCA.col(1).cross(eigenVectorsPCA.col(2));\n    eigenVectorsPCA.col(1) = eigenVectorsPCA.col(2).cross(eigenVectorsPCA.col(0));\n\n    std::cout << \"eigenValue(3x1):\\n\" << eigenValuesPCA << std::endl;\n    std::cout << \"eigenVector(3x3):\\n\" << eigenVectorsPCA << std::endl;\n    std::cout << \"mass center in camera coordinate system(4x1):\\n\" << pcaCentroid << std::endl;\n\n    Eigen::Matrix4f tm = Eigen::Matrix4f::Identity();\n    Eigen::Matrix4f tm_inv = Eigen::Matrix4f::Identity();\n    tm.block<3, 3>(0, 0) = eigenVectorsPCA.transpose();   //R.\n    tm.block<3, 1>(0, 3) = -1.0f * (eigenVectorsPCA.transpose()) *(pcaCentroid.head<3>());//  -R*t\n    tm_inv = tm.inverse();\n\n    //std::cout << \"transformation matrix(4x4):\\n\" << tm << std::endl;\n    std::cout << \"transformation matrix tm'(4x4):\\n\" << tm_inv << std::endl;\n\n\n    pcl::PointCloud<PointType>::Ptr transformedCloud(new pcl::PointCloud<PointType>);\n    pcl::transformPointCloud(*cloud, *transformedCloud, tm);\n\n    PointType min_p1, max_p1;\n    Eigen::Vector3f c1, c;\n    pcl::getMinMax3D(*transformedCloud, min_p1, max_p1);\n    c1 = 0.5f*(min_p1.getVector3fMap() + max_p1.getVector3fMap());\n\n    //std::cout << \"center c1(3x1):\\n\" << c1 << std::endl;\n\n    Eigen::Affine3f tm_inv_aff(tm_inv);\n    pcl::transformPoint(c1, c, tm_inv_aff);\n\n    Eigen::Vector3f whd, whd1;\n    whd1 = max_p1.getVector3fMap() - min_p1.getVector3fMap();\n    whd = whd1;\n    float sc1 = (whd1(0) + whd1(1) + whd1(2)) / 3;\n\n    std::cout << \"3D properties:\"<< std::endl;\n    std::cout << \"mass center(3x1):\\n\" << pcaCentroid << std::endl;\n    std::cout << \"rotation matrix(3x3):\\n\" << tm_inv.block<3, 3>(0, 0) << std::endl;\n    std::cout << \"bounding box size:\"<< std::endl;\n    std::cout << \"width=\" << whd1(0) << endl;\n    std::cout << \"height=\" << whd1(1) << endl;\n    std::cout << \"depth=\" << whd1(2) << endl;\n    //std::cout << \"scale1=\" << sc1 << endl;\n\n\n    /*const Eigen::Quaternionf bboxQ(tm_inv.block<3, 3>(0, 0));\n    const Eigen::Vector3f    bboxT(c);\n    auto euler = bboxQ1.toRotationMatrix().eulerAngles(0, 1, 2);\n    std::cout << \"Euler from quaternion in roll, pitch, yaw\"<< std::endl << euler/3.14*180 << std::endl;*/\n\n    //Convert the camera coordinate position from the camera coordinate system to the world coordinate system.(1,1,1,0,90,-90)\n    /*Eigen::Matrix4f tw = Eigen::Matrix4f::Identity();\n    Eigen::Matrix4f tw_inv = Eigen::Matrix4f::Identity();\n    Eigen::Vector4f tw_centroid;\n    tw(0,0) = 0.0; tw(0,1) = 1.0; tw(0,2) = 0.0; tw(0,3) = 1.0;\n    tw(1,0) = 1.0; tw(1,1) = 0.0; tw(1,2) = 0.0; tw(1,3) = 1.0;\n    tw(2,0) = 0.0; tw(2,1) = 0.0; tw(2,2) = -1.0; tw(2,3) = 1.0;\n    tw_inv = tw.inverse();\n    tw_centroid = tw_inv * pcaCentroid;\n    std::cout << \"mass center in World coordinate system(4x1):\\n\" << tw_centroid << std::endl;\n    */\n\n    vision_module::obj_mass o_mass;\n    vision_module::rotation_matrix r_matrix;\n    vision_module::bbox_size b_size;\n    \n    //publish mass center of object\n    o_mass.x = tm_inv(0,3);\n    o_mass.y = tm_inv(1,3);\n    o_mass.z = tm_inv(2,3);\n    pub1.publish(o_mass);\n\n    //publish rotation matrix from object to camera\n    r_matrix.r11 = tm_inv(0,0);\n    r_matrix.r21 = tm_inv(1,0);\n    r_matrix.r31 = tm_inv(2,0);\n    r_matrix.r12 = tm_inv(0,1);\n    r_matrix.r22 = tm_inv(1,1);\n    r_matrix.r32 = tm_inv(2,1);\n    r_matrix.r13 = tm_inv(0,2);\n    r_matrix.r23 = tm_inv(1,2);\n    r_matrix.r33 = tm_inv(2,2);    \n    pub2.publish(r_matrix);\n\n    //publish mass center of object\n    b_size.width = whd1(0);\n    b_size.height = whd1(1);\n    b_size.depth = whd1(2);\n    pub3.publish(b_size);\n\n    //pub.publish(pose_information);\n  \n}\n\nint main(int argc, char** argv)\n{\n  std::cout<<\"Init the pose information node:\" <<std::endl;\n  ros::init(argc, argv, \"pose_information\");\n  ros::NodeHandle nh;\n  sub = nh.subscribe<pcl::PointCloud<pcl::PointXYZ>> (\"region_growing\", 1000, callback);\n  pub1 = nh.advertise<vision_module::obj_mass> (\"obj_mass\", 1000);\n  pub2 = nh.advertise<vision_module::rotation_matrix> (\"rotation_matrix\", 1000);\n  pub3 = nh.advertise<vision_module::bbox_size> (\"BBox_size\", 1000);\n  ros::spin();\n}\n", "meta": {"hexsha": "1a58c21e7cdf5b61a7f0fd5cd9ea74dde85a9d14", "size": 6491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vision_module/src/pose_information.cpp", "max_stars_repo_name": "voyage03/Robot-Vision-Module", "max_stars_repo_head_hexsha": "fd236a7f75473b55b692ca861f532bdd48b58a1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vision_module/src/pose_information.cpp", "max_issues_repo_name": "voyage03/Robot-Vision-Module", "max_issues_repo_head_hexsha": "fd236a7f75473b55b692ca861f532bdd48b58a1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vision_module/src/pose_information.cpp", "max_forks_repo_name": "voyage03/Robot-Vision-Module", "max_forks_repo_head_hexsha": "fd236a7f75473b55b692ca861f532bdd48b58a1f", "max_forks_repo_licenses": ["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.8978494624, "max_line_length": 126, "alphanum_fraction": 0.6684640271, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282706, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.620456471541507}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n    \n    const unsigned n= 10;\n    dense2D<float, mat::parameters<col_major> > B(n, n);\n\n    mat::hessian_setup(B, 1.0);\n    \n    std::cout << \"one_norm(B) is \" << one_norm(B)<< \"\\n\";\n    std::cout << \"infinity_norm(B) is \" << infinity_norm(B)<< \"\\n\";\n    std::cout << \"frobenius_norm(B) is \" << frobenius_norm(B)<< \"\\n\";\n    \n    return 0;\n}\n", "meta": {"hexsha": "e74087476e14bab801b9590e15ef6dfdb10410d5", "size": 450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_norms.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/matrix_norms.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/matrix_norms.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 23.6842105263, "max_line_length": 69, "alphanum_fraction": 0.5755555556, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6204564612509903}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include \"main.h\"\r\n\r\n#include <Eigen/CXX11/Tensor>\r\n\r\nusing Eigen::Tensor;\r\nusing Eigen::DefaultDevice;\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_evals()\r\n{\r\n  Tensor<float, 2, DataLayout> input(3, 3);\r\n  Tensor<float, 1, DataLayout> kernel(2);\r\n\r\n  input.setRandom();\r\n  kernel.setRandom();\r\n\r\n  Tensor<float, 2, DataLayout> result(2,3);\r\n  result.setZero();\r\n  Eigen::array<Tensor<float, 2>::Index, 1> dims3{{0}};\r\n\r\n  typedef TensorEvaluator<decltype(input.convolve(kernel, dims3)), DefaultDevice> Evaluator;\r\n  Evaluator eval(input.convolve(kernel, dims3), DefaultDevice());\r\n  eval.evalTo(result.data());\r\n  EIGEN_STATIC_ASSERT(Evaluator::NumDims==2ul, YOU_MADE_A_PROGRAMMING_MISTAKE);\r\n  VERIFY_IS_EQUAL(eval.dimensions()[0], 2);\r\n  VERIFY_IS_EQUAL(eval.dimensions()[1], 3);\r\n\r\n  VERIFY_IS_APPROX(result(0,0), input(0,0)*kernel(0) + input(1,0)*kernel(1));  // index 0\r\n  VERIFY_IS_APPROX(result(0,1), input(0,1)*kernel(0) + input(1,1)*kernel(1));  // index 2\r\n  VERIFY_IS_APPROX(result(0,2), input(0,2)*kernel(0) + input(1,2)*kernel(1));  // index 4\r\n  VERIFY_IS_APPROX(result(1,0), input(1,0)*kernel(0) + input(2,0)*kernel(1));  // index 1\r\n  VERIFY_IS_APPROX(result(1,1), input(1,1)*kernel(0) + input(2,1)*kernel(1));  // index 3\r\n  VERIFY_IS_APPROX(result(1,2), input(1,2)*kernel(0) + input(2,2)*kernel(1));  // index 5\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_expr()\r\n{\r\n  Tensor<float, 2, DataLayout> input(3, 3);\r\n  Tensor<float, 2, DataLayout> kernel(2, 2);\r\n  input.setRandom();\r\n  kernel.setRandom();\r\n\r\n  Tensor<float, 2, DataLayout> result(2,2);\r\n  Eigen::array<ptrdiff_t, 2> dims;\r\n  dims[0] = 0;\r\n  dims[1] = 1;\r\n  result = input.convolve(kernel, dims);\r\n\r\n  VERIFY_IS_APPROX(result(0,0), input(0,0)*kernel(0,0) + input(0,1)*kernel(0,1) +\r\n                                input(1,0)*kernel(1,0) + input(1,1)*kernel(1,1));\r\n  VERIFY_IS_APPROX(result(0,1), input(0,1)*kernel(0,0) + input(0,2)*kernel(0,1) +\r\n                                input(1,1)*kernel(1,0) + input(1,2)*kernel(1,1));\r\n  VERIFY_IS_APPROX(result(1,0), input(1,0)*kernel(0,0) + input(1,1)*kernel(0,1) +\r\n                                input(2,0)*kernel(1,0) + input(2,1)*kernel(1,1));\r\n  VERIFY_IS_APPROX(result(1,1), input(1,1)*kernel(0,0) + input(1,2)*kernel(0,1) +\r\n                                input(2,1)*kernel(1,0) + input(2,2)*kernel(1,1));\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_modes() {\r\n  Tensor<float, 1, DataLayout> input(3);\r\n  Tensor<float, 1, DataLayout> kernel(3);\r\n  input(0) = 1.0f;\r\n  input(1) = 2.0f;\r\n  input(2) = 3.0f;\r\n  kernel(0) = 0.5f;\r\n  kernel(1) = 1.0f;\r\n  kernel(2) = 0.0f;\r\n\r\n  Eigen::array<ptrdiff_t, 1> dims;\r\n  dims[0] = 0;\r\n  Eigen::array<std::pair<ptrdiff_t, ptrdiff_t>, 1> padding;\r\n\r\n  // Emulate VALID mode (as defined in\r\n  // http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).\r\n  padding[0] = std::make_pair(0, 0);\r\n  Tensor<float, 1, DataLayout> valid(1);\r\n  valid = input.pad(padding).convolve(kernel, dims);\r\n  VERIFY_IS_EQUAL(valid.dimension(0), 1);\r\n  VERIFY_IS_APPROX(valid(0), 2.5f);\r\n\r\n  // Emulate SAME mode (as defined in\r\n  // http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).\r\n  padding[0] = std::make_pair(1, 1);\r\n  Tensor<float, 1, DataLayout> same(3);\r\n  same = input.pad(padding).convolve(kernel, dims);\r\n  VERIFY_IS_EQUAL(same.dimension(0), 3);\r\n  VERIFY_IS_APPROX(same(0), 1.0f);\r\n  VERIFY_IS_APPROX(same(1), 2.5f);\r\n  VERIFY_IS_APPROX(same(2), 4.0f);\r\n\r\n  // Emulate FULL mode (as defined in\r\n  // http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html).\r\n  padding[0] = std::make_pair(2, 2);\r\n  Tensor<float, 1, DataLayout> full(5);\r\n  full = input.pad(padding).convolve(kernel, dims);\r\n  VERIFY_IS_EQUAL(full.dimension(0), 5);\r\n  VERIFY_IS_APPROX(full(0), 0.0f);\r\n  VERIFY_IS_APPROX(full(1), 1.0f);\r\n  VERIFY_IS_APPROX(full(2), 2.5f);\r\n  VERIFY_IS_APPROX(full(3), 4.0f);\r\n  VERIFY_IS_APPROX(full(4), 1.5f);\r\n}\r\n\r\ntemplate <int DataLayout>\r\nstatic void test_strides() {\r\n  Tensor<float, 1, DataLayout> input(13);\r\n  Tensor<float, 1, DataLayout> kernel(3);\r\n  input.setRandom();\r\n  kernel.setRandom();\r\n\r\n  Eigen::array<ptrdiff_t, 1> dims;\r\n  dims[0] = 0;\r\n  Eigen::array<ptrdiff_t, 1> stride_of_3;\r\n  stride_of_3[0] = 3;\r\n  Eigen::array<ptrdiff_t, 1> stride_of_2;\r\n  stride_of_2[0] = 2;\r\n\r\n  Tensor<float, 1, DataLayout> result;\r\n  result = input.stride(stride_of_3).convolve(kernel, dims).stride(stride_of_2);\r\n\r\n  VERIFY_IS_EQUAL(result.dimension(0), 2);\r\n  VERIFY_IS_APPROX(result(0), (input(0)*kernel(0) + input(3)*kernel(1) +\r\n                               input(6)*kernel(2)));\r\n  VERIFY_IS_APPROX(result(1), (input(6)*kernel(0) + input(9)*kernel(1) +\r\n                               input(12)*kernel(2)));\r\n}\r\n\r\nvoid test_cxx11_tensor_convolution()\r\n{\r\n  CALL_SUBTEST(test_evals<ColMajor>());\r\n  CALL_SUBTEST(test_evals<RowMajor>());\r\n  CALL_SUBTEST(test_expr<ColMajor>());\r\n  CALL_SUBTEST(test_expr<RowMajor>());\r\n  CALL_SUBTEST(test_modes<ColMajor>());\r\n  CALL_SUBTEST(test_modes<RowMajor>());\r\n  CALL_SUBTEST(test_strides<ColMajor>());\r\n  CALL_SUBTEST(test_strides<RowMajor>());\r\n}\r\n", "meta": {"hexsha": "81a7a1fd2a888835608cdf713d6b893d55b51b57", "size": 5511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/unsupported/test/cxx11_tensor_convolution.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/unsupported/test/cxx11_tensor_convolution.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/unsupported/test/cxx11_tensor_convolution.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": 36.74, "max_line_length": 93, "alphanum_fraction": 0.6436218472, "num_tokens": 1811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6204283799263778}}
{"text": "/*\r\n [auto_generated]\r\n boost/numeric/odeint/stepper/detail/adams_bashforth_coefficients.hpp\r\n\r\n [begin_description]\r\n Definition of the coefficients for the Adams-Bashforth method.\r\n [end_description]\r\n\r\n Copyright 2009-2011 Karsten Ahnert\r\n Copyright 2009-2011 Mario Mulansky\r\n\r\n Distributed under the Boost Software License, Version 1.0.\r\n (See accompanying file LICENSE_1_0.txt or\r\n copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n\r\n#ifndef BOOST_NUMERIC_ODEINT_STEPPER_DETAIL_ADAMS_BASHFORTH_COEFFICIENTS_HPP_INCLUDED\r\n#define BOOST_NUMERIC_ODEINT_STEPPER_DETAIL_ADAMS_BASHFORTH_COEFFICIENTS_HPP_INCLUDED\r\n\r\n#include <boost/array.hpp>\r\n\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\nnamespace odeint {\r\nnamespace detail {\r\n\r\ntemplate< class Value , size_t Steps >\r\nclass adams_bashforth_coefficients ;\r\n\r\ntemplate< class Value >\r\nclass adams_bashforth_coefficients< Value , 1 > : public boost::array< Value , 1 >\r\n{\r\npublic:\r\n    adams_bashforth_coefficients( void )\r\n    : boost::array< Value , 1 >()\r\n      {\r\n        (*this)[0] = static_cast< Value >( 1 );\r\n      }\r\n};\r\n\r\n\r\ntemplate< class Value >\r\nclass adams_bashforth_coefficients< Value , 2 > : public boost::array< Value , 2 >\r\n{\r\npublic:\r\n    adams_bashforth_coefficients( void )\r\n    : boost::array< Value , 2 >()\r\n      {\r\n        (*this)[0] = static_cast< Value >( 3 ) / static_cast< Value >( 2 );\r\n        (*this)[1] = -static_cast< Value >( 1 ) / static_cast< Value >( 2 );\r\n      }\r\n};\r\n\r\n\r\ntemplate< class Value >\r\nclass adams_bashforth_coefficients< Value , 3 > : public boost::array< Value , 3 >\r\n{\r\npublic:\r\n    adams_bashforth_coefficients( void )\r\n    : boost::array< Value , 3 >()\r\n      {\r\n        (*this)[0] = static_cast< Value >( 23 ) / static_cast< Value >( 12 );\r\n        (*this)[1] = -static_cast< Value >( 4 ) / static_cast< Value >( 3 );\r\n        (*this)[2] = static_cast< Value >( 5 ) / static_cast< Value >( 12 );\r\n      }\r\n};\r\n\r\n\r\ntemplate< class Value >\r\nclass adams_bashforth_coefficients< Value , 4 > : public boost::array< Value , 4 >\r\n{\r\npublic:\r\n    adams_bashforth_coefficients( void )\r\n    : boost::array< Value , 4 >()\r\n      {\r\n        (*this)[0] = static_cast< Value >( 55 ) / static_cast< Value >( 24 );\r\n        (*this)[1] = -static_cast< Value >( 59 ) / static_cast< Value >( 24 );\r\n        (*this)[2] = static_cast< Value >( 37 ) / static_cast< Value >( 24 );\r\n        (*this)[3] = -static_cast< Value >( 3 ) / static_cast< Value >( 8 );\r\n      }\r\n};\r\n\r\n\r\ntemplate< class Value >\r\nclass adams_bashforth_coefficients< Value , 5 > : public boost::array< Value , 5 >\r\n{\r\npublic:\r\n    adams_bashforth_coefficients( void )\r\n    : boost::array< Value , 5 >()\r\n      {\r\n        (*this)[0] = static_cast< Value >( 1901 ) / static_cast< Value >( 720 );\r\n        (*this)[1] = -static_cast< Value >( 1387 ) / static_cast< Value >( 360 );\r\n        (*this)[2] = static_cast< Value >( 109 ) / static_cast< Value >( 30 );\r\n        (*this)[3] = -static_cast< Value >( 637 ) / static_cast< Value >( 360 );\r\n        (*this)[4] = static_cast< Value >( 251 ) / static_cast< Value >( 720 );\r\n      }\r\n};\r\n\r\n\r\ntemplate< class Value >\r\nclass adams_bashforth_coefficients< Value , 6 > : public boost::array< Value , 6 >\r\n{\r\npublic:\r\n    adams_bashforth_coefficients( void )\r\n    : boost::array< Value , 6 >()\r\n      {\r\n        (*this)[0] = static_cast< Value >( 4277 ) / static_cast< Value >( 1440 );\r\n        (*this)[1] = -static_cast< Value >( 2641 ) / static_cast< Value >( 480 );\r\n        (*this)[2] = static_cast< Value >( 4991 ) / static_cast< Value >( 720 );\r\n        (*this)[3] = -static_cast< Value >( 3649 ) / static_cast< Value >( 720 );\r\n        (*this)[4] = static_cast< Value >( 959 ) / static_cast< Value >( 480 );\r\n        (*this)[5] = -static_cast< Value >( 95 ) / static_cast< Value >( 288 );\r\n      }\r\n};\r\n\r\n\r\ntemplate< class Value >\r\nclass adams_bashforth_coefficients< Value , 7 > : public boost::array< Value , 7 >\r\n{\r\npublic:\r\n    adams_bashforth_coefficients( void )\r\n    : boost::array< Value , 7 >()\r\n      {\r\n        (*this)[0] = static_cast< Value >( 198721 ) / static_cast< Value >( 60480 );\r\n        (*this)[1] = -static_cast< Value >( 18637 ) / static_cast< Value >( 2520 );\r\n        (*this)[2] = static_cast< Value >( 235183 ) / static_cast< Value >( 20160 );\r\n        (*this)[3] = -static_cast< Value >( 10754 ) / static_cast< Value >( 945 );\r\n        (*this)[4] = static_cast< Value >( 135713 ) / static_cast< Value >( 20160 );\r\n        (*this)[5] = -static_cast< Value >( 5603 ) / static_cast< Value >( 2520 );\r\n        (*this)[6] = static_cast< Value >( 19087 ) / static_cast< Value >( 60480 );\r\n      }\r\n};\r\n\r\n\r\ntemplate< class Value >\r\nclass adams_bashforth_coefficients< Value , 8 > : public boost::array< Value , 8 >\r\n{\r\npublic:\r\n    adams_bashforth_coefficients( void )\r\n    : boost::array< Value , 8 >()\r\n      {\r\n        (*this)[0] = static_cast< Value >( 16083 ) / static_cast< Value >( 4480 );\r\n        (*this)[1] = -static_cast< Value >( 1152169 ) / static_cast< Value >( 120960 );\r\n        (*this)[2] = static_cast< Value >( 242653 ) / static_cast< Value >( 13440 );\r\n        (*this)[3] = -static_cast< Value >( 296053 ) / static_cast< Value >( 13440 );\r\n        (*this)[4] = static_cast< Value >( 2102243 ) / static_cast< Value >( 120960 );\r\n        (*this)[5] = -static_cast< Value >( 115747 ) / static_cast< Value >( 13440 );\r\n        (*this)[6] = static_cast< Value >( 32863 ) / static_cast< Value >( 13440 );\r\n        (*this)[7] = -static_cast< Value >( 5257 ) / static_cast< Value >( 17280 );\r\n      }\r\n};\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n} // detail\r\n} // odeint\r\n} // numeric\r\n} // boost\r\n\r\n\r\n\r\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_DETAIL_ADAMS_BASHFORTH_COEFFICIENTS_HPP_INCLUDED\r\n", "meta": {"hexsha": "cacde33cd1b4a3f35ebcb03f85e209041c52af21", "size": 5705, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/numeric/odeint/stepper/detail/adams_bashforth_coefficients.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-22T03:43:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T18:20:27.000Z", "max_issues_repo_path": "third_party/boost/numeric/odeint/stepper/detail/adams_bashforth_coefficients.hpp", "max_issues_repo_name": "PXLVision/opengv", "max_issues_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T16:34:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-06T17:29:22.000Z", "max_forks_repo_path": "third_party/boost/numeric/odeint/stepper/detail/adams_bashforth_coefficients.hpp", "max_forks_repo_name": "PXLVision/opengv", "max_forks_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2015-03-26T10:28:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T10:09:12.000Z", "avg_line_length": 33.7573964497, "max_line_length": 88, "alphanum_fraction": 0.5936897458, "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6204283796235514}}
{"text": "// Test ../include/Spectra/LinAlg/BKLDLT.h\n#include <Eigen/Core>\n#include <Spectra/LinAlg/BKLDLT.h>\n\nusing namespace Spectra;\n\n#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\n// Solve (A - s * I)x = b\nvoid run_test(const MatrixXd& A, const VectorXd& b, double s)\n{\n    BKLDLT<double> decompL(A, Eigen::Lower, s);\n    REQUIRE(decompL.info() == SUCCESSFUL);\n\n    BKLDLT<double> decompU(A, Eigen::Upper, s);\n    REQUIRE(decompU.info() == SUCCESSFUL);\n\n    VectorXd solL = decompL.solve(b);\n    VectorXd solU = decompU.solve(b);\n    REQUIRE((solL - solU).cwiseAbs().maxCoeff() == 0.0);\n\n    const double tol = 1e-9;\n    VectorXd resid = A * solL - s * solL - b;\n    INFO(\"||(A - s * I)x - b||_inf = \" << resid.cwiseAbs().maxCoeff());\n    REQUIRE(resid.cwiseAbs().maxCoeff() == Approx(0.0).margin(tol));\n}\n\nTEST_CASE(\"BKLDLT decomposition of symmetric real matrix [10x10]\", \"[BKLDLT]\")\n{\n    std::srand(123);\n    const int n = 10;\n    MatrixXd A = MatrixXd::Random(n, n);\n    A = (A + A.transpose()).eval();\n    VectorXd b = VectorXd::Random(n);\n    const double shift = 1.0;\n\n    run_test(A, b, shift);\n}\n\nTEST_CASE(\"BKLDLT decomposition of symmetric real matrix [100x100]\", \"[BKLDLT]\")\n{\n    std::srand(123);\n    const int n = 100;\n    MatrixXd A = MatrixXd::Random(n, n);\n    A = (A + A.transpose()).eval();\n    VectorXd b = VectorXd::Random(n);\n    const double shift = 1.0;\n\n    run_test(A, b, shift);\n}\n\nTEST_CASE(\"BKLDLT decomposition of symmetric real matrix [1000x1000]\", \"[BKLDLT]\")\n{\n    std::srand(123);\n    const int n = 1000;\n    MatrixXd A = MatrixXd::Random(n, n);\n    A = (A + A.transpose()).eval();\n    VectorXd b = VectorXd::Random(n);\n    const double shift = 1.0;\n\n    run_test(A, b, shift);\n}\n", "meta": {"hexsha": "91acf887b6b4d29569f80a68148c874ba4aefa4c", "size": 1757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/test/BKLDLT.cpp", "max_stars_repo_name": "mushroom-x/Misc3D", "max_stars_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2022-02-09T11:56:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:45:04.000Z", "max_issues_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/test/BKLDLT.cpp", "max_issues_repo_name": "mushroom-x/Misc3D", "max_issues_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2022-02-26T08:58:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:19:05.000Z", "max_forks_repo_path": "3rdparty/teaser_plusplus/3rdparty/spectra/test/BKLDLT.cpp", "max_forks_repo_name": "mushroom-x/Misc3D", "max_forks_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T06:59:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:03:11.000Z", "avg_line_length": 26.223880597, "max_line_length": 82, "alphanum_fraction": 0.6237905521, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6204283745717171}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2019, The University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n//\n// This file was originally part of Exotica, cf.\n// https://github.com/ipab-slmc/exotica/blob/master/exotica_core/include/exotica_core/tools/box_qp.h\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_SOLVERS_BOX_QP_HPP_\n#define CROCODDYL_CORE_SOLVERS_BOX_QP_HPP_\n\n#include <Eigen/Cholesky>\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace crocoddyl {\nstruct BoxQPSolution {\n  BoxQPSolution(const Eigen::MatrixXd& Hff_inv_in, const Eigen::VectorXd& x_in, const std::vector<size_t>& free_idx_in,\n                const std::vector<size_t>& clamped_idx_in)\n      : Hff_inv(Hff_inv_in), x(x_in), free_idx(free_idx_in), clamped_idx(clamped_idx_in) {}\n\n  Eigen::MatrixXd Hff_inv;\n  Eigen::MatrixXd x;\n  std::vector<size_t> free_idx;\n  std::vector<size_t> clamped_idx;\n};\n\n// Based on Yuval Tassa's BoxQP\n// Cf. https://www.mathworks.com/matlabcentral/fileexchange/52069-ilqg-ddp-trajectory-optimization\ninline BoxQPSolution BoxQP(const Eigen::MatrixXd& H, const Eigen::VectorXd& q, const Eigen::VectorXd& b_low,\n                           const Eigen::VectorXd& b_high, const Eigen::VectorXd& x_init, const double gamma,\n                           const int max_iterations, const double epsilon, const double lambda) {\n  if (max_iterations < 0) {\n    throw std::runtime_error(\"Max iterations needs to be positive.\");\n  }\n\n  int it = 0;\n  Eigen::VectorXd delta_xf(x_init.size()), x = x_init;\n  std::vector<size_t> clamped_idx, free_idx;\n  Eigen::VectorXd grad = q + H * x_init;\n  Eigen::MatrixXd Hff, Hfc, Hff_inv(H.rows(), H.cols());\n  Eigen::LLT<Eigen::MatrixXd> Hff_inv_llt = Eigen::LLT<Eigen::MatrixXd>(H.rows());\n\n  Hff_inv_llt.compute(Eigen::MatrixXd::Identity(H.rows(), H.cols()) * lambda + H);\n  Hff_inv_llt.solveInPlace(Hff_inv);\n\n  if (grad.lpNorm<Eigen::Infinity>() <= epsilon) {\n    return BoxQPSolution(Hff_inv, x_init, free_idx, clamped_idx);\n  }\n\n  while (grad.lpNorm<Eigen::Infinity>() > epsilon && it < max_iterations) {\n    ++it;\n    grad.noalias() = q + H * x;\n    clamped_idx.clear();\n    free_idx.clear();\n\n    for (int i = 0; i < grad.size(); ++i) {\n      if ((x(i) == b_low(i) && grad(i) > 0) || (x(i) == b_high(i) && grad(i) < 0)) {\n        clamped_idx.push_back(i);\n      } else {\n        free_idx.push_back(i);\n      }\n    }\n\n    if (free_idx.size() == 0) {\n      return BoxQPSolution(Hff_inv, x, free_idx, clamped_idx);\n    }\n\n    Hff.resize(free_idx.size(), free_idx.size());\n    Hfc.resize(free_idx.size(), clamped_idx.size());\n\n    if (clamped_idx.size() == 0) {\n      Hff = H;\n    } else {\n      for (size_t i = 0; i < free_idx.size(); ++i) {\n        for (size_t j = 0; j < free_idx.size(); ++j) {\n          Hff(i, j) = H(free_idx[i], free_idx[j]);\n        }\n      }\n\n      for (size_t i = 0; i < free_idx.size(); ++i) {\n        for (size_t j = 0; j < clamped_idx.size(); ++j) {\n          Hfc(i, j) = H(free_idx[i], clamped_idx[j]);\n        }\n      }\n    }\n\n    // NOTE: Array indexing not supported in current eigen version\n    Eigen::VectorXd q_free(free_idx.size()), x_free(free_idx.size()), x_clamped(clamped_idx.size());\n    for (size_t i = 0; i < free_idx.size(); ++i) {\n      q_free(i) = q(free_idx[i]);\n      x_free(i) = x(free_idx[i]);\n    }\n\n    for (size_t j = 0; j < clamped_idx.size(); ++j) {\n      x_clamped(j) = x(clamped_idx[j]);\n    }\n\n    // The dimension of Hff has changed - reinitialise LLT\n    // Hff_inv_llt = Eigen::LLT<Eigen::MatrixXd>(Hff.rows());\n    // Hff_inv_llt.compute(Eigen::MatrixXd::Identity(Hff.rows(), Hff.cols()) * lambda + Hff);\n    // Hff_inv_llt.solveInPlace(Hff_inv);\n    // TODO: Use Cholesky, however, often unstable without adapting lambda.\n    Hff_inv = (Eigen::MatrixXd::Identity(Hff.rows(), Hff.cols()) * lambda + Hff).inverse();\n\n    if (clamped_idx.size() == 0) {\n      // std::cout << \"Hff_inv=\" << Hff_inv.rows() << \"x\" << Hff_inv.cols() << \", q_free=\" << q_free.size() << \",\n      // x_free=\" << x_free.size() << std::endl;\n      delta_xf.noalias() = -Hff_inv * (q_free)-x_free;\n    } else {\n      delta_xf.noalias() = -Hff_inv * (q_free + Hfc * x_clamped) - x_free;\n    }\n\n    double f_old = (0.5 * x.transpose() * H * x + q.transpose() * x)(0);\n    static const Eigen::VectorXd alpha_space = Eigen::VectorXd::LinSpaced(10, 1.0, 0.1);\n\n    bool armijo_reached = false;\n    Eigen::VectorXd x_new(x.size()), x_diff(x.size());\n    for (int ai = 0; ai < alpha_space.rows(); ++ai) {\n      x_new = x;\n      for (size_t i = 0; i < free_idx.size(); ++i) {\n        x_new(free_idx[i]) = std::max(std::min(x(free_idx[i]) + alpha_space[ai] * delta_xf(i), b_high(i)), b_low(i));\n      }\n\n      double f_new = (0.5 * x_new.transpose() * H * x_new + q.transpose() * x_new)(0);\n      x_diff.noalias() = x - x_new;\n\n      // armijo criterion>\n      double armijo_coef = (f_old - f_new) / (grad.transpose() * x_diff + 1e-5);\n      if (armijo_coef > gamma) {\n        armijo_reached = true;\n        x = x_new;\n        break;\n      }\n    }\n\n    // break if no step made\n    if (!armijo_reached) break;\n  }\n\n  return BoxQPSolution(Hff_inv, x, free_idx, clamped_idx);\n}\n\ninline BoxQPSolution BoxQP(const Eigen::MatrixXd& H, const Eigen::VectorXd& q, const Eigen::VectorXd& b_low,\n                           const Eigen::VectorXd& b_high, const Eigen::VectorXd& x_init) {\n  const double epsilon = 1e-5;\n  const double gamma = 0.1;\n  const int max_iterations = 100;\n  const double lambda = 1e-5;\n  return BoxQP(H, q, b_low, b_high, x_init, gamma, max_iterations, epsilon, lambda);\n}\n}  // namespace crocoddyl\n\n#endif  // CROCODDYL_CORE_SOLVERS_BOX_QP_HPP_\n", "meta": {"hexsha": "2388f71c748c2bd47f18ca0f4cd92a1a936528fd", "size": 5822, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/solvers/box-qp.hpp", "max_stars_repo_name": "jcarpent/crocoddyl", "max_stars_repo_head_hexsha": "155999999f1fbd0c5760875584c540e2bc13645b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-21T12:11:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-21T12:11:15.000Z", "max_issues_repo_path": "include/crocoddyl/core/solvers/box-qp.hpp", "max_issues_repo_name": "boyali/crocoddyl", "max_issues_repo_head_hexsha": "155999999f1fbd0c5760875584c540e2bc13645b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crocoddyl/core/solvers/box-qp.hpp", "max_forks_repo_name": "boyali/crocoddyl", "max_forks_repo_head_hexsha": "155999999f1fbd0c5760875584c540e2bc13645b", "max_forks_repo_licenses": ["BSD-3-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.6163522013, "max_line_length": 119, "alphanum_fraction": 0.60391618, "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.620428374571717}}
{"text": "// -----------------------------------------------------------------------\r\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\r\n//\r\n// Copyright (c) German Cancer Research Center (DKFZ),\r\n// Software development for Integrated Diagnostics and Therapy (SIDT).\r\n// ALL RIGHTS RESERVED.\r\n// See rttbCopyright.txt or\r\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html\r\n//\r\n// This software is distributed WITHOUT ANY WARRANTY; without even\r\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n// PURPOSE.  See the above copyright notices for more information.\r\n//\r\n//------------------------------------------------------------------------\r\n\r\n#include \"rttbLinearInterpolation.h\"\r\n\r\n#include <boost/make_shared.hpp>\r\n\r\nnamespace rttb\r\n{\r\n\tnamespace interpolation\r\n\t{\r\n\r\n\t\tDoseTypeGy LinearInterpolation::trilinear(std::array<double, 3> target,\r\n\t\t        boost::shared_ptr<DoseTypeGy[]> values) const\r\n\t\t{\r\n\t\t\t//4 linear interpolation in x direction\r\n\t\t\tDoseTypeGy c_00 = values[0] * (1.0 - target[0]) + values[1] * target[0];\r\n\t\t\tDoseTypeGy c_10 = values[2] * (1.0 - target[0]) + values[3] * target[0];\r\n\t\t\tDoseTypeGy c_01 = values[4] * (1.0 - target[0]) + values[5] * target[0];\r\n\t\t\tDoseTypeGy c_11 = values[6] * (1.0 - target[0]) + values[7] * target[0];\r\n\r\n\t\t\t//combine result in y direction\r\n\t\t\tDoseTypeGy c_0 = c_00 * (1.0 - target[1]) + c_10 * target[1];\r\n\t\t\tDoseTypeGy c_1 = c_01 * (1.0 - target[1]) + c_11 * target[1];\r\n\r\n\t\t\t//finally incorporate z direction\r\n\t\t\treturn (c_0 * (1.0 - target[2]) + c_1 * target[2]);\r\n\t\t}\r\n\r\n\t\tDoseTypeGy LinearInterpolation::getValue(const WorldCoordinate3D& aWorldCoordinate) const\r\n\t\t{\r\n\t\t\t//proper initialization of target and values\r\n\t\t\tstd::array<double, 3> target = {0.0, 0.0, 0.0};\r\n      auto values = boost::make_shared<DoseTypeGy[]>(8);\r\n\t\t\tgetNeighborhoodVoxelValues(aWorldCoordinate, 8, target, values);\r\n\r\n\t\t\treturn trilinear(target, values);\r\n\t\t}\r\n\r\n\t}\r\n}\r\n", "meta": {"hexsha": "f399052ed2ce9b59c77b7d6b2555cd0930c46337", "size": 1951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/interpolation/rttbLinearInterpolation.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "code/interpolation/rttbLinearInterpolation.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/interpolation/rttbLinearInterpolation.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 36.1296296296, "max_line_length": 92, "alphanum_fraction": 0.6201947719, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6203817331508037}}
{"text": "#include <mex.h> \n#include <math.h>\n#include <iostream>\n#include <vector>\n\n#include <igl/matlab/MexStream.h>\n#include <igl/matlab/parse_rhs.h>\n#include <igl/matlab/prepare_lhs.h>\n#include <igl/matlab/validate_arg.h>\n\n#include <igl/PI.h>\n#include <igl/forward_kinematics.h>\n#include <igl/directed_edge_parents.h>\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid euler_to_quat(const Eigen::Vector3d& euler, Eigen::Quaterniond& q) {\n\n  q = Eigen::AngleAxisd(euler(2), Eigen::Vector3d::UnitZ())\n      * Eigen::AngleAxisd(euler(1), Eigen::Vector3d::UnitY())\n      * Eigen::AngleAxisd(euler(0), Eigen::Vector3d::UnitX());\n}\n\n\nvoid euler_to_quat(const Eigen::Vector3d& euler, const Eigen::Affine3d& a, Eigen::Quaterniond& q) {\n  q = Eigen::AngleAxisd(euler(2), a.rotation().col(2))\n      * Eigen::AngleAxisd(euler(1), a.rotation().col(1))\n      * Eigen::AngleAxisd(euler(0), a.rotation().col(0));\n  // q = Eigen::AngleAxisd(euler(0), a.rotation().col(0))\n  //     * Eigen::AngleAxisd(euler(1), a.rotation().col(1))\n  //     * Eigen::AngleAxisd(euler(2), a.rotation().col(2));\n}\n\n\nvoid read_pnt_anim(std::string anim_file,\n    const Eigen::MatrixXd& C,\n    const Eigen::VectorXd& center,\n    const double& scale,\n    std::vector<Eigen::MatrixXd>& T_list)\n{\n  FILE* file;\n  file= fopen(anim_file.c_str(), \"rb\");\n\n  int dim = 3;//= C.cols();\n\n  double degree2radian = igl::PI/180.0;\n\n  int num_bone, num_frame;\n  double val = 0;\n\n  typedef std::vector<Eigen::Quaterniond,\n      Eigen::aligned_allocator<Eigen::Quaterniond> > RotationList;\n\n\n  fscanf(file, \"%d %d\\n\", &num_bone, &num_frame);\n  T_list.resize(num_frame);\n  //std::cout<<\"num_bone: \"<<num_bone<<\", num_frame: \"<<num_frame<<std::endl;\n\n  std::vector<Eigen::Vector3d> rest_tran_list(num_bone);\n  std::vector<Eigen::Affine3d> rest_affine_list(num_bone);\n\n  for(int i=0; i<num_bone ; i++){\n    Eigen::Vector3d rest_tran;\n    for (int j = 0; j < dim; j++) {\n      fscanf(file, \"%lf\", &val);\n      rest_tran(j) = val;\n    }\n    rest_tran_list[i] = (rest_tran-center)/scale;\n\n    Eigen::Vector3d euler;\n    for (int j = 0; j < dim; j++) {\n      fscanf(file, \"%lf\", &val);\n      euler(j) = val;\n    }\n    euler = euler.array() * degree2radian;\n    Eigen::Quaterniond q;\n    euler_to_quat(euler, q);\n    Eigen::Affine3d root_affine = Eigen::Affine3d::Identity();\n    root_affine.rotate(q);\n    rest_affine_list[i] = root_affine;\n    //std::cout<<\"i: \"<<i<<\", mat: \"<<root_affine.matrix()<<std::endl;\n  }\n  RotationList rot_list(num_bone);\n  std::vector<Eigen::Vector3d> tran_list(num_bone);\n\n  for (int k = 0; k < num_frame; k++) {\n    for (int i = 0; i < num_bone; i++) {\n      Eigen::Vector3d tran;\n      for (int j = 0; j < dim; j++) {\n        fscanf(file, \"%lf\", &val);\n        tran(j) = val;\n      }\n      tran = (tran - center)/scale;\n      Eigen::Vector3d euler;\n      for (int j = 0; j < dim; j++) {\n        fscanf(file, \"%lf\", &val);\n        euler(j) = val;\n      }\n      euler = euler.array() * degree2radian;\n      Eigen::Quaterniond q;\n      euler_to_quat(euler, rest_affine_list[i], q);\n      //std::cout<<\"1 i: \"<<i<<\", mat: \"<<rest_affine_list[i].rotation()<<std::endl;\n\n      q = rest_affine_list[i].rotation().transpose()*q;\n\n      //euler_to_quat(euler, q);\n\n      //std::cout<<\"q w: \"<<q.w()<<\"< vec: \"<<q.vec()<<std::endl;\n\n      const Eigen::Vector3d cn = C.row(i).transpose();\n\n      tran_list[i] = tran - rest_tran_list[i] + cn-q*cn;\n      //tran_list[i] = tran - rest_tran_list[i];\n      rot_list[i] = q;\n    }\n    RotationList vQ = rot_list;\n    std::vector<Eigen::Vector3d> vT= tran_list;\n    //igl::forward_kinematics(C, BE, P, rot_list, tran_list, vQ, vT);\n\n    Eigen::MatrixXd T(num_bone * (dim+1), dim);\n    for (int i = 0; i < num_bone; i++) {\n      Eigen::Affine3d a = Eigen::Affine3d::Identity();\n      a.translate(vT[i]);\n      a.rotate(vQ[i]);\n      T.block(i * (dim+1), 0, dim+1, dim) = a.matrix().transpose().block(0, 0, dim+1, dim);\n    }\n    T_list[k] = T;\n  }\n  fclose(file);\n\n}\n\n\n// void read_pnt_anim(std::string anim_file,\n//     std::vector<Eigen::MatrixXd>& T_list)\n// {\n//   FILE* file;\n//   file= fopen(anim_file.c_str(), \"rb\");\n\n//   int dim = 3;//= C.cols();\n\n//   double degree2radian = igl::PI/180.0;\n\n//   int num_bone, num_frame;\n//   double val = 0;\n\n//   typedef std::vector<Eigen::Quaterniond,\n//       Eigen::aligned_allocator<Eigen::Quaterniond> > RotationList;\n\n\n//   fscanf(file, \"%d %d\\n\", &num_bone, &num_frame);\n//   T_list.resize(num_frame);\n//   //std::cout<<\"num_bone: \"<<num_bone<<\", num_frame: \"<<num_frame<<std::endl;\n\n//   std::vector<Eigen::Vector3d> rest_tran_list(num_bone);\n//   std::vector<Eigen::Affine3d> rest_affine_list(num_bone);\n\n//   for(int i=0; i<num_bone ; i++){\n//     Eigen::Vector3d rest_tran;\n//     for (int j = 0; j < dim; j++) {\n//       fscanf(file, \"%lf\", &val);\n//       rest_tran(j) = val;\n//     }\n//     rest_tran_list[i] = rest_tran;\n\n//     Eigen::Vector3d euler;\n//     for (int j = 0; j < dim; j++) {\n//       fscanf(file, \"%lf\", &val);\n//       euler(j) = val;\n//     }\n//     euler = euler.array() * degree2radian;\n//     Eigen::Quaterniond q;\n//     euler_to_quat(euler, q);\n//     Eigen::Affine3d root_affine = Eigen::Affine3d::Identity();\n//     root_affine.rotate(q);\n//     rest_affine_list[i] = root_affine;\n//   }\n//   RotationList rot_list(num_bone);\n//   std::vector<Eigen::Vector3d> tran_list(num_bone);\n\n//   for (int k = 0; k < num_frame; k++) {\n//     for (int i = 0; i < num_bone; i++) {\n//       Eigen::Vector3d tran;\n//       for (int j = 0; j < dim; j++) {\n//         fscanf(file, \"%lf\", &val);\n//         tran(j) = val;\n//       }\n//       Eigen::Vector3d euler;\n//       for (int j = 0; j < dim; j++) {\n//         fscanf(file, \"%lf\", &val);\n//         euler(j) = val;\n//       }\n//       euler = euler.array() * degree2radian;\n//       Eigen::Quaterniond q;\n//       euler_to_quat(euler, rest_affine_list[i], q);\n\n//       tran_list[i] = tran - rest_tran_list[i];\n//       rot_list[i] = q;\n//     }\n//     RotationList vQ = rot_list;\n//     std::vector<Eigen::Vector3d> vT= tran_list;\n//     //igl::forward_kinematics(C, BE, P, rot_list, tran_list, vQ, vT);\n\n//     Eigen::MatrixXd T(num_bone * (dim+1), dim);\n//     for (int i = 0; i < num_bone; i++) {\n//       Eigen::Affine3d a = Eigen::Affine3d::Identity();\n//       a.translate(vT[i]);\n//       a.rotate(vQ[i]);\n//       T.block(i * (dim+1), 0, dim+1, dim) = a.matrix().transpose().block(0, 0, dim+1, dim);\n//     }\n//     T_list[k] = T;\n//   }\n//   fclose(file);\n// }\n\nvoid read_pnt_anim(std::string anim_file,\n    Eigen::MatrixXd C,\n    std::vector<Eigen::MatrixXd>& T_list)\n{\n  FILE* file;\n  file= fopen(anim_file.c_str(), \"rb\");\n\n  int dim = 3;//= C.cols();\n\n  double degree2radian = igl::PI/180.0;\n\n  int num_bone, num_frame;\n  double val = 0;\n\n  typedef std::vector<Eigen::Quaterniond,\n      Eigen::aligned_allocator<Eigen::Quaterniond> > RotationList;\n\n\n  fscanf(file, \"%d %d\\n\", &num_bone, &num_frame);\n  T_list.resize(num_frame);\n  //std::cout<<\"num_bone: \"<<num_bone<<\", num_frame: \"<<num_frame<<std::endl;\n\n  std::vector<Eigen::Vector3d> rest_tran_list(num_bone);\n  std::vector<Eigen::Affine3d> rest_affine_list(num_bone);\n\n  for(int i=0; i<num_bone ; i++){\n    Eigen::Vector3d rest_tran;\n    for (int j = 0; j < dim; j++) {\n      fscanf(file, \"%lf\", &val);\n      rest_tran(j) = val;\n    }\n    rest_tran_list[i] = rest_tran;\n\n    Eigen::Vector3d euler;\n    for (int j = 0; j < dim; j++) {\n      fscanf(file, \"%lf\", &val);\n      euler(j) = val;\n    }\n    euler = euler.array() * degree2radian;\n    Eigen::Quaterniond q;\n    euler_to_quat(euler, q);\n    Eigen::Affine3d root_affine = Eigen::Affine3d::Identity();\n    root_affine.rotate(q);\n    rest_affine_list[i] = root_affine;\n  }\n  RotationList rot_list(num_bone);\n  std::vector<Eigen::Vector3d> tran_list(num_bone);\n\n  for (int k = 0; k < num_frame; k++) {\n    for (int i = 0; i < num_bone; i++) {\n      Eigen::Vector3d tran;\n      for (int j = 0; j < dim; j++) {\n        fscanf(file, \"%lf\", &val);\n        tran(j) = val;\n      }\n      Eigen::Vector3d euler;\n      for (int j = 0; j < dim; j++) {\n        fscanf(file, \"%lf\", &val);\n        euler(j) = val;\n      }\n      euler = euler.array() * degree2radian;\n      Eigen::Quaterniond q;\n      euler_to_quat(euler, rest_affine_list[i], q);\n\n      q = rest_affine_list[i].rotation().transpose()*q;\n\n      const Eigen::Vector3d cn = C.row(i).transpose();\n\n      tran_list[i] = tran - rest_tran_list[i] + cn-q*cn;\n      rot_list[i] = q;//cn-q*cn;//q;\n    }\n    RotationList vQ = rot_list;\n    std::vector<Eigen::Vector3d> vT= tran_list;\n    //igl::forward_kinematics(C, BE, P, rot_list, tran_list, vQ, vT);\n\n    Eigen::MatrixXd T(num_bone * (dim+1), dim);\n    for (int i = 0; i < num_bone; i++) {\n      Eigen::Affine3d a = Eigen::Affine3d::Identity();\n      a.translate(vT[i]);\n      a.rotate(vQ[i]);\n      T.block(i * (dim+1), 0, dim+1, dim) = a.matrix().transpose().block(0, 0, dim+1, dim);\n    }\n    T_list[k] = T;\n  }\n  fclose(file);\n}\n\n\nvoid mexFunction(\n  int          nlhs,\n  mxArray      *plhs[],\n  int          nrhs,\n  const mxArray *prhs[])\n{\n    Eigen::MatrixXd C;\n    Eigen::MatrixXi BE;\n    Eigen::VectorXi P;\n    Eigen::VectorXd center;\n    double scale;\n    char* anim_file = mxArrayToString(prhs[0]);\n\n    igl::matlab::parse_rhs_double(prhs+1, C);\n    igl::matlab::parse_rhs_double(prhs+2, center);\n    scale = (double) *mxGetPr(prhs[3]);\n\n\n\n\n    std::vector<Eigen::MatrixXd> T_list;\n    //read_pnt_anim(anim_file, center, scale, T_list);\n    //read_pnt_anim(anim_file, C, T_list);\n    read_pnt_anim(anim_file, C, center, scale, T_list);\n\n\n    plhs[0] = mxCreateCellMatrix(T_list.size(),1);\n\n    mxArray *x;\n    for(int i=0; i<T_list.size(); i++){\n        const int m = T_list[i].rows();\n        const int n = T_list[i].cols();\n        x = mxCreateDoubleMatrix(m,n, mxREAL);\n        Eigen::Map< Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> > map(mxGetPr(x),m,n);\n        map = T_list[i].template cast<double>();\n        mxSetCell(plhs[0], i, x);\n    }\n    return;\n}", "meta": {"hexsha": "d50591a2a24af3e077d228e9afae97057ec9b60e", "size": 10044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab-include/mex/read_3d_pnt_anim.cpp", "max_stars_repo_name": "ErisZhang/complementary-dynamics", "max_stars_repo_head_hexsha": "87d11804b79d37199669645dd12ce6f00fce513c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T11:03:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T00:58:26.000Z", "max_issues_repo_path": "matlab-include/mex/read_3d_pnt_anim.cpp", "max_issues_repo_name": "ErisZhang/complementary-dynamics", "max_issues_repo_head_hexsha": "87d11804b79d37199669645dd12ce6f00fce513c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matlab-include/mex/read_3d_pnt_anim.cpp", "max_forks_repo_name": "ErisZhang/complementary-dynamics", "max_forks_repo_head_hexsha": "87d11804b79d37199669645dd12ce6f00fce513c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-25T06:39:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-18T03:19:00.000Z", "avg_line_length": 29.1130434783, "max_line_length": 99, "alphanum_fraction": 0.5832337714, "num_tokens": 3243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045966995027, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6203817310653501}}
{"text": "/// \\file\n/// Maintainer: Luzian Hug\n/// Created: 25.03.2018\n///\n///\n\n#include \"kmeans.h\"\n#include \"spatial/uniform_grid.h\"\n#include <Eigen/Dense>\n#include <boost/log/trivial.hpp>\n#include <iostream>\n\nnamespace MouseTrack {\n\nKMeans::KMeans(int K) : _k(K) {\n  // empty\n}\n\nstd::vector<Cluster> KMeans::operator()(const PointCloud &cloud) const {\n  BOOST_LOG_TRIVIAL(trace) << \"KMeans algorithm started\";\n  // Convert point cloud to Eigen vectors\n\n  if (cloud.size() == 0) {\n    return std::vector<Cluster>();\n  }\n\n  const int dims = cloud.charDim();\n  PointList means(dims, K());\n  PointList prevMeans;\n\n  PointList points;\n  points.resize(dims, cloud.size());\n  for (PointIndex i = 0; i < cloud.size(); i += 1) {\n    auto v = cloud[i].characteristic();\n    points.col(i) = v;\n  }\n\n  // TODO: get kmeans++ initialization\n  means = points.block(0, 0, dims, K());\n\n  Eigen::VectorXd min = points.rowwise().minCoeff();\n  Eigen::VectorXd max = points.rowwise().maxCoeff();\n  Eigen::VectorXd bb_size = max - min;\n\n  BOOST_LOG_TRIVIAL(debug) << \"KMeans: bb: \" << bb_size;\n\n  std::lock_guard<std::mutex> lock(_oracleMutex);\n  if (_cachedOracle.get() == nullptr ||\n      !(bb_size.array() <= _cachedBoundingBox.array()).all()) {\n    bb_size *= 1.5;\n    OFactory::Query q;\n    q.dimensions = bb_size.size();\n    q.bb_size = &bb_size;\n    _cachedOracle = oracleFactory().forQuery(q);\n    _cachedBoundingBox = bb_size;\n  }\n  Oracle &oracle = *_cachedOracle;\n\n  std::vector<Cluster> clusters(K()), prevClusters;\n\n  BOOST_LOG_TRIVIAL(debug) << \"KMeans: Starting iterations.\";\n  do {\n    // assign clusters\n    BOOST_LOG_TRIVIAL(trace) << \"KMeans: Assigning clusters\";\n    oracle.compute(means);\n    prevClusters = std::move(clusters);\n    clusters = std::vector<Cluster>(K());\n    std::vector<std::vector<PointIndex>> allCs = oracle.find_closest(points, 1);\n    for (int i = 0; i < points.cols(); ++i) {\n      auto &cs = allCs[i];\n      if (cs.empty()) {\n        BOOST_LOG_TRIVIAL(error)\n            << \"Couldn't find nearest mean for point \" << i << \" (\"\n            << points.col(i) << \"), assigning to 1\";\n        cs.push_back(1);\n      }\n      clusters[cs[0]].points().push_back(i);\n    }\n\n    // calculate new cluster centers\n    BOOST_LOG_TRIVIAL(trace) << \"KMeans: Assigning centroids\";\n    prevMeans = means;\n    for (PointIndex c = 0; c < clusters.size(); ++c) {\n      PointList assigned(dims, clusters[c].points().size());\n      for (PointIndex i = 0; i < clusters[c].points().size(); ++i) {\n        int pi = clusters[c].points()[i];\n        assigned.col(i) = points.col(pi);\n      }\n      Eigen::VectorXd mean =\n          assigned.array().rowwise().sum() / (assigned.cols() + .000001);\n      means.col(c) = mean;\n    }\n  } while (!meansConverged(means, prevMeans) &&\n           !assignmentConverged(clusters, prevClusters, cloud.size()));\n\n  std::stringstream ss;\n  ss << clusters[0].points().size();\n  for (size_t i = 1; i < clusters.size(); ++i) {\n    ss << \", \" << clusters[i].points().size();\n  }\n\n  BOOST_LOG_TRIVIAL(trace) << \"K-Means cluster sizes: \" << ss.str();\n\n  return clusters;\n}\n\nvoid KMeans::K(int k) { _k = k; }\nint KMeans::K() const { return _k; }\n\nvoid KMeans::centroidThreshold(double threshold) {\n  _centroidThreshold = threshold;\n}\n\ndouble KMeans::centroidThreshold() const { return _centroidThreshold; }\n\nvoid KMeans::assignmentThreshold(double threshold) {\n  _assignmentThreshold = threshold;\n}\n\ndouble KMeans::assignmentThreshold() const { return _assignmentThreshold; }\n\nKMeans::OFactory &KMeans::oracleFactory() { return _oracleFactory; }\n\nconst KMeans::OFactory &KMeans::oracleFactory() const { return _oracleFactory; }\n\nbool KMeans::meansConverged(const PointList &newMeans,\n                            const PointList &lastMeans) const {\n  auto centroidChange = (lastMeans - newMeans).colwise().norm();\n  Precision change = centroidChange.maxCoeff();\n  BOOST_LOG_TRIVIAL(trace) << \"worst means change: \" << change;\n  return change <= centroidThreshold();\n}\nbool KMeans::assignmentConverged(const std::vector<Cluster> &newClusters,\n                                 const std::vector<Cluster> &lastClusters,\n                                 int totalPoints) const {\n  int switched = 0;\n  for (int i = 0; i < K(); ++i) {\n    // rough estimate how many points changed assignment\n    int delta =\n        newClusters[i].points().size() - lastClusters[i].points().size();\n    delta = std::abs(delta);\n    switched += delta;\n  }\n  // double-counting??\n  // switched /= 2;\n  Precision switchedPercentage = switched / (Precision)totalPoints;\n  BOOST_LOG_TRIVIAL(trace) << \"switched change: \" << switched << \"/\"\n                           << totalPoints << \" (\" << (switchedPercentage * 100)\n                           << \"%)\";\n  return switchedPercentage <= assignmentThreshold();\n}\n\n} // namespace MouseTrack\n", "meta": {"hexsha": "1e81ac922d40812e2267b30f5520e3ab45c1d989", "size": 4825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/clustering/kmeans.cpp", "max_stars_repo_name": "itko/scanbox", "max_stars_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-09T09:30:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T09:30:23.000Z", "max_issues_repo_path": "lib/clustering/kmeans.cpp", "max_issues_repo_name": "itko/scanbox", "max_issues_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2018-03-19T20:54:52.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-16T12:36:59.000Z", "max_forks_repo_path": "lib/clustering/kmeans.cpp", "max_forks_repo_name": "itko/scanbox", "max_forks_repo_head_hexsha": "9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-03-14T20:00:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-14T20:00:43.000Z", "avg_line_length": 31.3311688312, "max_line_length": 80, "alphanum_fraction": 0.6263212435, "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6203817234194668}}
{"text": "#include <boost/random.hpp>\r\n\r\nboost::lagged_fibonacci1279 Tools::gen_;\r\n\r\nEigen::MatrixXd Tools::getWGNoise(const Eigen::MatrixXd& std,\r\n\tconst Eigen::MatrixXd& bias,Index rows, Index cols)\r\n{\r\n\tboost::normal_distribution<> g(0, 1);\r\n\tEigen::MatrixXd ret= Eigen::MatrixXd::Zero(rows,cols);\r\n\tfor (Index i=0;i<rows;++i)\r\n\t{\r\n\t    for (Index j=0; j<cols; ++j)\r\n            ret(i,j)=g(gen_);\r\n\t}\r\n\tret=std*ret+bias;\r\n\r\n\treturn ret;\r\n}\r\n", "meta": {"hexsha": "94bdaef604f69b2f52bb7c64685b85036dac01db", "size": 434, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "unit-testings/tools.hxx", "max_stars_repo_name": "mmurooka/state-observation", "max_stars_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-11-01T16:10:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-09T00:03:46.000Z", "max_issues_repo_path": "unit-testings/tools.hxx", "max_issues_repo_name": "mmurooka/state-observation", "max_issues_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-10-18T09:06:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-26T04:22:09.000Z", "max_forks_repo_path": "unit-testings/tools.hxx", "max_forks_repo_name": "mmurooka/state-observation", "max_forks_repo_head_hexsha": "4a6b8eb6fa841cf706a074132fb24b50e8534e35", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-06-19T09:00:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-11T06:14:51.000Z", "avg_line_length": 22.8421052632, "max_line_length": 62, "alphanum_fraction": 0.6359447005, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6203810676855044}}
{"text": "/* Boost check_gmp.cpp test file\n\n Copyright 2009 Karsten Ahnert\n Copyright 2009 Mario Mulansky\n\n This file tests the odeint library with the gmp arbitrary precision types\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n*/\n\n#define BOOST_TEST_MODULE odeint_gmp\n\n#include <gmpxx.h>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\n\nusing namespace boost::unit_test;\nusing namespace boost::numeric::odeint;\n\nconst int precision = 1024;\n\ntypedef mpf_class value_type;\ntypedef boost::array< value_type , 1 > state_type;\n\n\nvoid constant_system( state_type &x , state_type &dxdt , value_type t )\n{\n    dxdt[0] = value_type( 1.0 , precision );\n}\n\n\nBOOST_AUTO_TEST_CASE( gmp )\n{\n    /* We have to specify the desired precision in advance! */\n    mpf_set_default_prec( precision );\n\n    mpf_t eps_ , unity;\n    mpf_init( eps_ ); mpf_init( unity );\n    mpf_set_d( unity , 1.0 );\n    mpf_div_2exp( eps_ , unity , precision-1 ); // 2^(-precision+1) : smallest number that can be represented with used precision\n    value_type eps( eps_ );\n\n    runge_kutta4< state_type , value_type > stepper;\n    state_type x;\n    x[0] = 0.0;\n\n    stepper.do_step( constant_system , x , 0.0 , 0.1 );\n\n    BOOST_MESSAGE( eps );\n    BOOST_CHECK_MESSAGE( abs( x[0] - value_type( 0.1 , precision ) ) < eps , x[0] - 0.1 );\n}\n", "meta": {"hexsha": "78326006ceb5eb3b19168f1ef6913909a4b279d9", "size": 1468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/test_external/gmp/check_gmp.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "libs/numeric/odeint/test_external/gmp/check_gmp.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "libs/numeric/odeint/test_external/gmp/check_gmp.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 25.7543859649, "max_line_length": 129, "alphanum_fraction": 0.7084468665, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6203810521815921}}
{"text": "/// \\file\n\n#ifndef PERCEPTRON_INCLUDED\n#define PERCEPTRON_INCLUDED\n\n#include <iostream>\n#include <cstdlib>\n#include <Eigen/Dense>\n#include <tbb/tbb.h>\n\nnamespace neuralnetwork\n{\n  \n  enum InOutType\n  {\n    DYNAMIC = -1\n  };\n  \n  /// \\brief Les entrees et sorties du Perceptron sont un simple vecteur Eigen\n  template<typename t, int INPUT_SIZE>\n  using InOut = Eigen::Matrix<t, INPUT_SIZE, 1>;\n  \n  /// \\brief On definit dans ce namespace quelques fonctions d'activations, on peut tout de meme en definir ailleurs l'important etant qu'elles aient un unique argument de type double et qu'elles renvoient un double\n  namespace activation\n  {\n    double SIGMOID(double x)\n    {\n      return 1.0/(1 + exp(-x));\n      \n    }\n    \n    double D_SIGMOID(double x)\n    {\n      double res = exp(x)/pow(exp(x)+1, 2);\n      if (res!=res)\n      {\n        res = 0.0001;\n      }\n      return res;\n    }\n    double AFFINE(double x)\n    {\n      return x;\n    }\n    double D_AFFINE(double x)\n    {\n      return 1.0;\n    }\n  }\n \n  /// \\brief Classe de noeud de propagation (calculs) du graphe de feed forward\n  /// \\class Forward_Node\n  class Forward_Node\n  {\n    private:\n      \n      /// \\brief Matrice a laquelle est affecte le noeud du graphe\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>* weights;\n      \n      /// \\brief Agregation en sortie\n      Eigen::Matrix<double, Eigen::Dynamic, 1>* agreg_out;\n      \n      /// \\brief Activation en sortie\n      Eigen::Matrix<double, Eigen::Dynamic, 1>* act_out;\n      \n      /// \\brief Activation en entree\n      Eigen::Matrix<double, Eigen::Dynamic, 1>* act_in;\n      \n      /// \\brief Fonction d'activation\n      double (*f)(double);\n      \n      /// \\brief Premiere ligne de la matrice dont s'occupe le noeud\n      int first_row;\n      \n      /// \\brief Premiere colonne de la matrice dont s'occupe le noeud (a priori 0)\n      int first_col;\n      \n      /// \\brief Nombre de lignes dont s'occupe le noeud\n      int nb_rows;\n      \n      /// \\brief Nombre de colonnes dont s'occupe le noeud (a priori la largeur de la matrice)\n      int nb_cols;\n        \n    public:\n      \n      /// \\brief Constructeur\n      /// \\param w Matrice a laquelle est affecte le noeud du graphe\n      /// \\param act Activation en entree\n      /// \\param agreg Agregation en sortie\n      /// \\param act2 Activation en sortie\n      /// \\param f_act Fonction d'activation\n      /// \\param f_row Premiere ligne de la matrice dont s'occupe le noeud\n      /// \\param f_col Premiere colonne de la matrice dont s'occupe le noeud (a priori 0)\n      /// \\param n_rows Nombre de lignes dont s'occupe le noeud\n      /// \\param n_cols Nombre de colonnes dont s'occupe le noeud (a priori la largeur de la matrice)\n      Forward_Node\n      (\n        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>* w,\n        Eigen::Matrix<double, Eigen::Dynamic, 1>* act,\n        Eigen::Matrix<double, Eigen::Dynamic, 1>* agreg,\n        Eigen::Matrix<double, Eigen::Dynamic, 1>* act2,\n        double(*f_act)(double),\n        int f_row,\n        int f_col,\n        int n_rows,\n        int n_cols\n      ):\n      weights(w),\n      agreg_out(agreg),\n      act_out(act2),\n      act_in(act),\n      f(f_act),\n      first_row(f_row),\n      first_col(f_col),\n      nb_rows(n_rows),\n      nb_cols(n_cols)\n      {}\n\n      void operator()(tbb::flow::continue_msg m)\n      {\n        agreg_out->block(first_row, 0, nb_rows, 1) = (weights->block(first_row, first_col, nb_rows, nb_cols) * (*act_in));\n        for(int i = first_row; i < first_row + nb_rows; ++i)\n        {\n          act_out->operator()(i) = f(agreg_out->operator()(i));\n        }\n      }\n        \n  };\n\n  /// \\brief Classe de noeud de retropropagation (calculs) du graphe de retropropagation\n  /// \\class Backward_Node\n  class Backward_Node\n  {\n    private:\n      \n      /// \\brief Matrice a laquelle est affecte le noeud du graphe\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>* weights;\n      \n      /// \\brief Agregation en entree\n      Eigen::Matrix<double, Eigen::Dynamic, 1>* agreg_in;\n      \n      /// \\brief Erreur en sortie\n      Eigen::Matrix<double, Eigen::Dynamic, 1>* err_out;\n      \n      /// \\brief Erreur en entree\n      Eigen::Matrix<double, Eigen::Dynamic, 1>* err_in;\n      \n      /// \\brief Derivee de la fonction d'activation\n      double (*df)(double);\n      \n      /// \\brief Premiere ligne de la matrice dont s'occupe le noeud\n      int first_row;\n      \n      /// \\brief Premiere colonne de la matrice dont s'occupe le noeud (a priori 0)\n      int first_col;\n      \n      /// \\brief Nombre de lignes dont s'occupe le noeud\n      int nb_rows;\n      \n      /// \\brief Nombre de colonnes dont s'occupe le noeud (a priori la largeur de la matrice)\n      int nb_cols;\n              \n    public:\n      /// \\brief Constructeur\n      /// \\param w Transposee de la matrice a laquelle est affecte le noeud du graphe\n      /// \\param err Erreur en entree\n      /// \\param agreg Agregation en entree\n      /// \\param err2 Erreur en sortie\n      /// \\param df_act Derive de la fonction d'activation\n      /// \\param f_row Premiere ligne de la tranposee dont s'occupe le noeud\n      /// \\param f_col Premiere colonne de la transposee dont s'occupe le noeud (a priori 0)\n      /// \\param n_rows Nombre de lignes dont s'occupe le noeud\n      /// \\param n_cols Nombre de colonnes dont s'occupe le noeud (a priori la largeur de la tranposee)\n      Backward_Node\n      (\n        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>* w,\n        Eigen::Matrix<double, Eigen::Dynamic, 1>* err,\n        Eigen::Matrix<double, Eigen::Dynamic, 1>* agreg,\n        Eigen::Matrix<double, Eigen::Dynamic, 1>* err2,\n        double(*df_act)(double),\n        int f_row,\n        int f_col,\n        int n_rows,\n        int n_cols\n      ):\n      weights(w),\n      agreg_in(agreg),\n      err_out(err2),\n      err_in(err),\n      df(df_act),\n      first_row(f_row),\n      first_col(f_col),\n      nb_rows(n_rows),\n      nb_cols(n_cols) \n      {}\n      \n      void operator()(tbb::flow::continue_msg m)\n      {\n        err_out->block(first_row, 0, nb_rows, 1) = weights->transpose().block(first_row, first_col, nb_rows, nb_cols)* (*err_in);\n        for(int i = first_row; i < first_row + nb_rows; ++i)\n        {\n          err_out->operator()(i) = df(agreg_in->operator()(i)) * err_out->operator()(i);\n        }\n      }\n  };\n    \n  /// \\brief Classe de noeud de mise a jour (calculs) du graphe de retropropagation\n  /// \\class Update_Node\n  class Update_Node\n  {\n    private:\n      \n      /// \\brief Matrice a laquelle est affecte le noeud du graphe\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>* weights;\n      \n      /// \\brief Pas d'apprentissage\n      double step;\n      \n      /// \\brief Erreur en entree\n      Eigen::Matrix<double, Eigen::Dynamic, 1>* err;\n      \n      /// \\brief Activation en sortie\n      Eigen::Matrix<double, Eigen::Dynamic, 1>* act;\n      \n      /// \\brief Premiere ligne de la matrice dont s'occupe le noeud\n      int first_row;\n      \n      /// \\brief Premiere colonne de la matrice dont s'occupe le noeud (a priori 0)\n      int first_col;\n      \n      /// \\brief Nombre de lignes dont s'occupe le noeud\n      int nb_rows;\n      \n      /// \\brief Nombre de colonnes dont s'occupe le noeud (a priori la largeur de la matrice)\n      int nb_cols;\n        \n    public:\n      /// \\brief Constructeur\n      /// \\param w Matrice a laquelle est affecte le noeud du graphe\n      /// \\param s Pas d'apprentissage\n      /// \\param e Erreur en entree\n      /// \\param a Activation en sortie\n      /// \\param f_act Fonction d'activation\n      /// \\param f_row Premiere ligne de la matrice dont s'occupe le noeud\n      /// \\param f_col Premiere colonne de la matrice dont s'occupe le noeud (a priori 0)\n      /// \\param n_rows Nombre de lignes dont s'occupe le noeud\n      /// \\param n_cols Nombre de colonnes dont s'occupe le noeud (a priori la largeur de la matrice)\n      Update_Node\n      (\n        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>* w,\n        double s,\n        Eigen::Matrix<double, Eigen::Dynamic, 1>* e,\n        Eigen::Matrix<double, Eigen::Dynamic, 1>* a,\n        int f_row,\n        int f_col,\n        int n_rows,\n        int n_cols\n      ):\n      weights(w),\n      step(s),\n      err(e),\n      act(a),\n      first_row(f_row),\n      first_col(f_col),\n      nb_rows(n_rows),\n      nb_cols(n_cols) \n      {}\n      \n      void operator()(tbb::flow::continue_msg m)\n      {\n          for(int i = first_row; i < first_row + nb_rows; ++i)\n          {\n            weights->block(i, first_col, 1, nb_cols) += step * err->operator()(i) * act->transpose();\n          }\n      }\n        \n  }; \n  \n  /// \\brief Classe de noeud d'attente des graphes de feed forwards et de retropropagation\n  /// \\class Wait_Node \n  class Wait_Node\n  {\n    private:\n        \n    public:\n      Wait_Node()\n      {}\n      \n      void operator()(tbb::flow::continue_msg m)\n      {\n      }        \n  };\n  \n  \n  /// \\brief Classe Perceptron\n  /// \\class Perceptron\n  /// \\tparam DEPTH nombres de couches du perceptron sans compter la couche d'entr\u00e9e\n  template<std::size_t DEPTH>\n  class Perceptron\n  {\n\n    public:\n      \n      /// \\brief Constructeur, les poids du reseau sont initialises entre deux bornes de maniere aleatoire, on definit egalement la taille des couches et leurs fonctions d'activation\n      /// \\param min Valeur minimal d'un poids du reseau\n      /// \\param max Valeur maximal d'un poids du reseau\n      /// \\param args Trois arguments pour definie une couche, le premier est le nombre de neurone de la couche, le deuxieme est est la fonction d'activation, le troisieme est la derivee de la fonction d'activation. Les trois premiers arguments definissent la premiere couche cachee, les trois suivants la deuxieme couche cachee, etc... la fonction d'activation et sa derivee doivent etre des pointeurs sur fonction qui prennent un double et retourne un double\n      template <typename ...Args>\n      Perceptron(double min, double max, Args... args);\n      \n      /// \\brief Initialisation aleatoire des poids du reseau entre deux bornes\n      /// \\param min Valeur minimal d'un poids du reseau\n      /// \\param max Valeur maximal d'un poids du reseau\n      /// \\return Rien\n      void initWeights(double min, double max);\n      \n      /// \\brief Accesseur des poids du reseau\n      /// \\param couch La couche a laquelle appartient le neurone qui a le poids sur une de ses entrees\n      /// \\param neuron Le neurone de la couche\n      /// \\param previous Le neurone de la couche precedente\n      /// \\return Accesseur sur le poids\n      double& weight(std::size_t couch, std::size_t neuron, std::size_t previous);\n      \n      /// \\brief Nombre de poids de chaque neurone d'une couche\n      /// \\param couch La couche en question\n      /// \\return le nombre de poids pour un neurone de la couche en question\n      std::size_t weights_count(std::size_t couch);\n      \n      /// \\brief Profondeur du reseau\n      /// \\return La profondeur du reseau sans prendre en compte la couche d'entree\n      std::size_t depth();\n      \n      /// \\brief Nombre de neurones d'une couche donnee\n      /// \\param couch La couche en question\n      /// \\return Nombre de neurones de la couche en question\n      std::size_t couch_size(std::size_t couch);\n      \n      //Eigen::Matrix<double, Eigen::Dynamic, 1> agreg(std::size_t couch);\n      /// \\brief Les dernieres agregations enregistrees pour une couche donnee (methode principalement utile au debugage)\n      /// \\param couch La couche en question\n      /// \\return une entree-sortie de neurones qui comporte toutes les dernieres agregation enregistrees de la couche en question\n      neuralnetwork::InOut<double,neuralnetwork::InOutType::DYNAMIC> agreg(std::size_t couch);\n      \n      //Eigen::Matrix<double, Eigen::Dynamic, 1> activation(std::size_t couch);\n      /// \\brief Les dernieres activations enregistrees pour une couche donnee (methode principalement utile au debugage)\n      /// \\param couch La couche en question\n      /// \\return une entree-sortie de neurones qui comporte toutes les dernieres activations enregistrees de la couche en question\n      neuralnetwork::InOut<double,neuralnetwork::InOutType::DYNAMIC> activation(std::size_t couch);\n      \n      \n      /// \\brief Ecrit la matrice des poids d'une couche, une ligne correspond a un neurone, les poids sont dans l'odre des entrees provenant de la couche precedente et les agregations et activations de cette couche (methode principalement utile au debugage)\n      /// \\param out reference sur le flux de sortie ou l'on veut afficher les informations\n      /// \\param i La couche en question\n      /// \\return Rien\n      void printMatrixCouch(std::ostream& out, std::size_t i);\n      \n      /// \\brief Evalue une entree avec le reseau\n      /// \\param in L'entree a evaluer\n      /// \\param out La sortie du reseau\n      /// \\param saveAgreg Si place a true, les agregations des differentes couches seront enregistrees\n      /// \\param saveActivation Si place a true, les activations des differentes couches seront enregistrees\n      /// \\tparam tin type d'entree du reseau (a priori un double)\n      /// \\tparam INPUT_SIZE taille d'entree du reseau\n      /// \\tparam tout type des sorties du reseau (a priori un double)\n      /// \\tparam OUTPUT_SIZE taille de sortie du reseau\n      template<typename tin, int INPUT_SIZE, typename tout, int OUTPUT_SIZE>\n      void feedForward(neuralnetwork::InOut<tin, INPUT_SIZE>& in, neuralnetwork::InOut<tout, OUTPUT_SIZE>& out, bool saveAgreg, bool saveActivation);\n     \n      /// \\brief Applique la fonction d'activation sur l'agregation calulee d'une couche\n      /// \\param in L'aggregation calculee de la couche fi\n      /// \\param fi La couche en question\n      /// \\return Rien\n      /// \\tparam tin type de l'agreation (a priori un double)\n      /// \\tparam INPUT_SIZE taille de la couche\n      /// \\tparam tout type de l'activation (a priori un double)\n      /// \\tparam OUTPUT_SIZE taille de la couche\n      /// \\todo possibilite de se passer de in si feedForward enregistre systematiquement l'agregation\n      template<typename t, int INPUT_SIZE>\n      void applyActivation(neuralnetwork::InOut<t, INPUT_SIZE>& in, std::size_t fi);\n      \n      /// \\brief Applique l'algorithme de retropropagation du gradient avec un jeu d'exemples afin d'entrainer le reseau\n      /// \\param ins Tableau des exemples d'entrees du reseau\n      /// \\param outs Tableau des sorties attendues pour chaque exemple de ins (organises dans le meme ordre)\n      /// \\param n Nombre d'exemples\n      /// \\param step Pas d'apprentissage\n      /// \\return Rien\n      /// \\tparam tin type des entrees (a priori double)\n      /// \\tparam INPUT_SIZE taille d'entree du reseau\n      /// \\tparam tout type des sorties du reseau (a priori double)\n      /// \\tparam OUTPUT_SIZE taille de sortie du reseau\n      template<typename tin, int INPUT_SIZE, typename tout, int OUTPUT_SIZE>\n      void backpropagation(neuralnetwork::InOut<tin, INPUT_SIZE>* ins, neuralnetwork::InOut<tout, OUTPUT_SIZE>* outs, std::size_t n, double step);\n      \n      /// \\brief Initailise les graphes TBB pour le feed forward et la retropropagation\n      /// \\param step Pas d'apprentissage\n      /// \\param nb_threads En combien de lignes on decoupe chaque matrice et chaque transposee (meme nombre que les threads conseille)\n      /// \\return Rien\n      void initGraph(double step, int nb_threads);\n      \n      /// \\brief Evalue une entree avec le reseau avec TBB\n      /// \\param in L'entree a evaluer\n      /// \\param out La sortie du reseau\n      /// \\return Rien\n      /// \\tparam tin type d'entree du reseau (a priori un double)\n      /// \\tparam INPUT_SIZE taille d'entree du reseau\n      /// \\tparam tout type des sorties du reseau (a priori un double)\n      /// \\tparam OUTPUT_SIZE taille de sortie du reseau\n      /// \\return Rien\n      template<typename tin, int INPUT_SIZE, typename tout, int OUTPUT_SIZE>\n      void parallel_feedForward(neuralnetwork::InOut<tin, INPUT_SIZE>& in, neuralnetwork::InOut<tout, OUTPUT_SIZE>& out);\n      \n      /// \\brief Applique l'algorithme de retropropagation du gradient avec un jeu d'exemples afin d'entrainer le reseau avec TBB\n      /// \\param ins Tableau des exemples d'entrees du reseau\n      /// \\param outs Tableau des sorties attendues pour chaque exemple de ins (organises dans le meme ordre)\n      /// \\param n Nombre d'exemples\n      /// \\param step Pas d'apprentissage\n      /// \\return Rien\n      /// \\tparam tin type des entrees (a priori double)\n      /// \\tparam INPUT_SIZE taille d'entree du reseau\n      /// \\tparam tout type des sorties du reseau (a priori double)\n      /// \\tparam OUTPUT_SIZE taille de sortie du reseau\n      template<typename tin, int INPUT_SIZE, typename tout, int OUTPUT_SIZE>\n      void parallel_backpropagation(neuralnetwork::InOut<tin, INPUT_SIZE>* ins, neuralnetwork::InOut<tout, OUTPUT_SIZE>* outs, std::size_t n, double step);\n      \n    private:\n      \n      /// \\brief Methode utilitaire pour le constructeur, on definit egalement la taille des couches et leurs fonctions d'activation. Cette methode parcourt recursivement toutes les couches\n      /// \\param n Couche a parametrer\n      /// \\param input_size Nombres de poids pour les neurones de cette couche, egal au nombre de neurones de la couche precedente\n      /// \\param neurons Taille de cette couche en nombres de neurones\n      /// \\param f Fonction d'activation de cette couche\n      /// \\param df Derivee de la fonction d'activation de cette couche\n      /// \\param args Parametres pour les couches suivantes\n      /// \\return Rien\n      template<typename... Args>\n      void init(unsigned int n, int input_size, int neurons, double (*f)(double), double (*df)(double), Args ...args);\n      \n      /// \\brief Dernier appel de init pour la derniere couche a parametrer\n      void init(unsigned int n, int input_size, int neurons, double (*f)(double), double (*df)(double));\n      \n      /// \\brief tableau des fonctions d'activations, une par couche\n      double (*m_array_f[DEPTH])(double);\n      \n      /// \\brief tableau des derivees des fonctions d'activations, une par couche\n      double (*m_array_df[DEPTH])(double);\n      \n      /// \\brief profondeur du reseau\n      const std::size_t m_size = DEPTH;\n     \n      /// \\brief tableau des matrices des couches. Une ligne represente les poids d'un neurone, l'element i de la ligne j represente le poids reliant le sortie du neurones i de la couche precedente avec le neurone j de la couche actuelle\n      Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> m_array_matrix[DEPTH];\n      \n      /// \\brief tableau des agregations\n      Eigen::Matrix<double, Eigen::Dynamic, 1> m_array_agreg[DEPTH];\n      \n      /// \\brief tableau des activations\n      Eigen::Matrix<double, Eigen::Dynamic, 1> m_array_act[DEPTH];\n      \n      /// \\brief tableau des erreurs\n      Eigen::Matrix<double, Eigen::Dynamic, 1> m_array_err[DEPTH];\n      \n      /// \\brief Vecteur d'entree du graph\n      Eigen::Matrix<double, Eigen::Dynamic, 1> m_first_graph_vector;\n      \n      /// \\brief Noeuds des neurones du graphe pour le feed forward\n      std::vector<std::vector<tbb::flow::continue_node<tbb::flow::continue_msg>>> m_forward_neurons;\n      \n      /// \\brief Noeuds d'attente des neurones du graphe pour le feed forward\n      std::vector<tbb::flow::continue_node<tbb::flow::continue_msg>> m_forward_waits;\n      \n      /// \\brief Graphe du reseau pour le feed forward\n      tbb::flow::graph m_graph_forward;\n\n      /// \\brief Noeuds des neurones du graphe pour la retropropagation\n      std::vector<std::vector<tbb::flow::continue_node<tbb::flow::continue_msg>>> m_backward_neurons;\n      \n      /// \\brief Noeuds d'attente des neurones du graphe pour la retropropagation\n      std::vector<tbb::flow::continue_node<tbb::flow::continue_msg>> m_backward_waits;      \n      \n      /// \\brief Graphe du reseau pour le backward\n      tbb::flow::graph m_graph_backward;\n      \n      /// \\brief Noeuds des neurones du graphe pour la mise a jour des poids\n      std::vector<std::vector<tbb::flow::continue_node<tbb::flow::continue_msg>>> m_update_neurons;\n\n      \n  };\n}\n\n/// \\fn std::ostream& operator<<(std::ostream& out, neuralnetwork::Perceptron<DEPTH> p)\n/// \\brief Affiche les matrices de poids du reseau et les agregations et activations de chaque couche (methode principalement utile au debugage)\n/// \\param out reference sur le flux de sortie ou l'on veut afficher les informations\n/// \\param p Perceptron a afficher\n/// \\return out avec de nouvelles informations concernant le reseau dedans\n/// \\warning La fonction est incoherente, une partie des informations est ecrite dans out et l'autre dans std::cout. Cette fonction sert principalement au debugage\ntemplate<std::size_t DEPTH>\nstd::ostream& operator<<(std::ostream& out, neuralnetwork::Perceptron<DEPTH> p)\n{\n  out << DEPTH <<\" couches\" << std::endl;\n  for(int i = 0; i < DEPTH; ++i)\n  {\n    out << \"Couche \" << i <<std::endl;\n    p.printMatrixCouch(out, i);\n    //getchar();\n    out << std::endl;\n    out << \"Agregation:\" << std::endl << p.agreg(i);\n    //getchar();\n    out << std::endl;\n    out << \"Activation:\" << std::endl << p.activation(i);\n    //getchar();\n    out << std::endl;\n  }\n\n  return out;\n}\n\ntemplate<std::size_t DEPTH>\ntemplate <typename ...Args>\nneuralnetwork::Perceptron<DEPTH>::Perceptron(double min, double max, Args... args)\n{\n  init(0, args...);\n  initWeights(min, max);\n  m_first_graph_vector.resize(m_array_matrix[0].cols(), 1);\n}\n\n\ntemplate<std::size_t DEPTH>\ntemplate<typename... Args>\nvoid neuralnetwork::Perceptron<DEPTH>::init(unsigned int n, int input_size, int neurons, double (*f)(double), double (*df)(double), Args ...args)\n{\n  //On dimensionne la matrice representant la couche et les vecteurs d'agreations, d'activations et d'erreurs pour cette meme couche\n  m_array_err[n].resize(neurons, 1);\n  m_array_agreg[n].resize(neurons, 1);\n  m_array_act[n].resize(neurons, 1);\n  m_array_matrix[n].resize(neurons, input_size);\n\n  //On donne la bonne fonction et la bonne derivee a la couche\n  m_array_f[n] = f;\n  m_array_df[n] = df;\n  if(n < DEPTH )\n  {\n    init(n+1, neurons, args...);\n  }\n}\n\ntemplate<std::size_t DEPTH>\nvoid neuralnetwork::Perceptron<DEPTH>::init(unsigned int n, int input_size, int neurons, double (*f)(double), double (*df)(double))\n{\n  m_array_agreg[n].resize(neurons, 1);\n  m_array_act[n].resize(neurons, 1);\n  m_array_err[n].resize(neurons, 1);\n  m_array_matrix[n].resize(neurons, input_size);\n  m_array_f[n] = f;\n  m_array_df[n] = df;\n}\n\ntemplate<std::size_t DEPTH>\nvoid neuralnetwork::Perceptron<DEPTH>::initWeights(double min, double max)\n{\n  for(unsigned int i = 0; i < depth() ;++i)\n  {\n    for(unsigned int j = 0; j < couch_size(i); ++j)\n    {\n      for(unsigned int k = 0; k < weights_count(i); ++k)\n      {\n        weight(i, j, k) = (std::rand()/(static_cast<double>(RAND_MAX) + 1.0)) * (max - min) + min;\n      }\n    }\n    \n  }\n}\n\ntemplate<std::size_t DEPTH>\nvoid neuralnetwork::Perceptron<DEPTH>::initGraph(double step, int nb_threads)\n{\n  \n  //Feed forward\n  for(unsigned int i = 0; i < depth(); ++i)\n  {\n    int first_row = 0;\n    tbb::flow::continue_node<tbb::flow::continue_msg> new_wait (m_graph_forward, Wait_Node());\n    m_forward_waits.push_back(new_wait);\n    std::vector<tbb::flow::continue_node<tbb::flow::continue_msg>> new_couch;\n    for(int j = 0; j < nb_threads; ++j)\n    {\n      int nb_rows;\n      int nb_cols = m_array_matrix[i].cols();\n      //Repartition des lignes entre les noeuds\n      if(j < (m_array_matrix[i].rows() % nb_threads))\n      {\n        nb_rows = couch_size(i) / nb_threads + 1;\n      }\n      else\n      {\n        nb_rows = couch_size(i) / nb_threads;\n      }\n      int first_col = 0;\n      \n      //Pour n'importe quel couche hormis la premiere, l'entree est l'activation de la i-1eme couche, sinon c'est le vecteur d'entree\n      if(i != 0)\n      {\n        tbb::flow::continue_node<tbb::flow::continue_msg> new_node (\n                                  m_graph_forward,\n                                  neuralnetwork::Forward_Node(\n                                         &(m_array_matrix[i]),\n                                         &(m_array_act[i - 1]),\n                                         &(m_array_agreg[i]),\n                                         &(m_array_act[i]),\n                                         m_array_f[i],\n                                         first_row,\n                                         first_col,\n                                         nb_rows,\n                                         nb_cols\n                                         \n                                  )\n                                  );\n        new_couch.push_back(new_node);\n      }\n      else\n      {\n        tbb::flow::continue_node<tbb::flow::continue_msg> new_node (\n                                  m_graph_forward,\n                                  neuralnetwork::Forward_Node(\n                                         &(m_array_matrix[i]),\n                                         &(m_first_graph_vector),\n                                         &(m_array_agreg[i]),\n                                         &(m_array_act[i]),\n                                         m_array_f[i],\n                                         first_row,\n                                         first_col,\n                                         nb_rows,\n                                         nb_cols\n                                  )\n                                  );\n        new_couch.push_back(new_node);\n      }\n      first_row += nb_rows;\n    }\n    m_forward_neurons.push_back(new_couch);\n  }\n  \n  //On lie les couches aux noeuds barrieres\n  for(unsigned int i = 0; i < m_forward_waits.size(); ++i)\n  {\n    for(unsigned int j = 0; j < m_forward_neurons[i].size(); ++j)\n    {\n      tbb::flow::make_edge(m_forward_neurons[i][j], m_forward_waits[i]);\n      if(i != 0)\n      {\n        tbb::flow::make_edge(m_forward_waits[i - 1], m_forward_neurons[i][j]);\n      }\n    }\n  }\n\n  //Backward\n  for(unsigned int i = 1; i < DEPTH; ++i)\n  {\n    int first_row = 0;\n    tbb::flow::continue_node<tbb::flow::continue_msg> new_wait (m_graph_backward, Wait_Node());\n    m_backward_waits.push_back(new_wait);\n    std::vector<tbb::flow::continue_node<tbb::flow::continue_msg>> new_couch;\n    for(int j = 0; j < nb_threads; ++j)\n    {\n        int nb_rows;\n        int nb_cols = m_array_matrix[i].transpose().cols();\n        //Repartition des lignes entre les noeuds\n        if(j < (m_array_matrix[i].transpose().rows() % nb_threads))\n        {\n          nb_rows = m_array_matrix[i].transpose().rows() / nb_threads + 1;\n        }\n        else\n        {\n          nb_rows = m_array_matrix[i].transpose().rows() / nb_threads;\n        }\n        int first_col = 0;\n        tbb::flow::continue_node<tbb::flow::continue_msg> new_node (\n                                  m_graph_backward,\n                                  neuralnetwork::Backward_Node(\n                                         &(m_array_matrix[i]),\n                                         &(m_array_err[i]),\n                                         &(m_array_agreg[i - 1]),\n                                         &(m_array_err[i - 1]),\n                                         m_array_df[i - 1],\n                                         first_row,\n                                         first_col,\n                                         nb_rows,\n                                         nb_cols\n                                  )\n                                  );\n        new_couch.push_back(new_node);\n        first_row += nb_rows;\n    }\n    m_backward_neurons.push_back(new_couch);\n  }\n  \n  //On lie les couches aux noeuds barrieres\n  for(unsigned int i = 0; i < m_backward_neurons.size(); ++i)\n  {\n    for(unsigned int j = 0; j < m_backward_neurons[i].size(); ++j)\n    {\n      tbb::flow::make_edge(m_backward_neurons[i][j], m_backward_waits[i]);\n      if(i != m_backward_neurons.size() - 1)\n      {\n        tbb::flow::make_edge(m_backward_waits[i + 1], m_backward_neurons[i][j]);\n      }\n    }\n  }\n  \n  //Update\n  for(unsigned int i = 0; i < DEPTH; ++i)\n  {\n    int first_row = 0;\n    std::vector<tbb::flow::continue_node<tbb::flow::continue_msg>> new_couch;\n    for(int j = 0; j < nb_threads; ++j)\n      {\n          int nb_rows;\n          int nb_cols = m_array_matrix[i].cols();\n          //Repartition des lignes entre les noeuds\n          if(j < (m_array_matrix[i].rows() % nb_threads))\n          {\n            nb_rows = couch_size(i) / nb_threads + 1;\n          }\n          else\n          {\n            nb_rows = couch_size(i) / nb_threads;\n          }\n          int first_col = 0;\n          //Pour n'importe quel couche hormis la premiere, l'entree est l'activation de la i-1eme couche, sinon c'est le vecteur d'entree\n          if(i > 0)\n          {\n            tbb::flow::continue_node<tbb::flow::continue_msg> new_node (\n                                  m_graph_backward,\n                                  neuralnetwork::Update_Node(\n                                         &(m_array_matrix[i]),\n                                         step,\n                                         &(m_array_err[i]),\n                                         &(m_array_act[i - 1]),\n                                         first_row,\n                                         first_col,\n                                         nb_rows,\n                                         nb_cols\n                                  )\n                                  );\n            new_couch.push_back(new_node);\n          }\n          else\n          {\n            tbb::flow::continue_node<tbb::flow::continue_msg> new_node (\n                                  m_graph_backward,\n                                  neuralnetwork::Update_Node(\n                                         &(m_array_matrix[i]),\n                                         step,\n                                         &(m_array_err[i]),\n                                         &(m_first_graph_vector),\n                                         first_row,\n                                         first_col,\n                                         nb_rows,\n                                         nb_cols\n                                  )\n                                  );\n            new_couch.push_back(new_node);\n          }\n          first_row += nb_rows;\n      }\n      m_update_neurons.push_back(new_couch);\n    }\n    \n    for(unsigned int i = 1; i < m_update_neurons.size(); ++i)\n    {\n      for(unsigned int j = 0; j < m_update_neurons[i].size(); ++j)\n      {\n        tbb::flow::make_edge(m_backward_waits[i - 1], m_update_neurons[i][j]);\n      }\n    }\n    for(unsigned int j = 0; j < m_update_neurons[0].size(); ++j)\n    {\n        tbb::flow::make_edge(m_backward_waits[0], m_update_neurons[0][j]);\n    }\n  \n}\n\ntemplate<std::size_t DEPTH>\ndouble& neuralnetwork::Perceptron<DEPTH>::weight(std::size_t couch, std::size_t neuron, std::size_t previous)\n{\n  return m_array_matrix[couch](neuron, previous);\n}\n \ntemplate<std::size_t DEPTH>\nstd::size_t neuralnetwork::Perceptron<DEPTH>::weights_count(std::size_t couch)\n{\n  return m_array_matrix[couch].cols();\n}\n\ntemplate<std::size_t DEPTH>\nstd::size_t neuralnetwork::Perceptron<DEPTH>::depth()\n{\n  return m_size;\n}\n\ntemplate<std::size_t DEPTH>\nstd::size_t neuralnetwork::Perceptron<DEPTH>::couch_size(std::size_t couch)\n{\n  return m_array_matrix[couch].rows();\n}\n\ntemplate<std::size_t DEPTH>\nvoid neuralnetwork::Perceptron<DEPTH>::printMatrixCouch(std::ostream& out, std::size_t i)\n{\n  std::cout << m_array_matrix[i];\n}\n\ntemplate<std::size_t DEPTH>\nEigen::Matrix<double, Eigen::Dynamic, 1> neuralnetwork::Perceptron<DEPTH>::agreg(std::size_t couch)\n{\n  return m_array_agreg[couch];\n}\n  \ntemplate<std::size_t DEPTH>\nEigen::Matrix<double, Eigen::Dynamic, 1> neuralnetwork::Perceptron<DEPTH>::activation(std::size_t couch)\n{\n  return m_array_act[couch];\n}\n\ntemplate<std::size_t DEPTH>\ntemplate<typename t, int INPUT_SIZE>\nvoid neuralnetwork::Perceptron<DEPTH>::applyActivation(neuralnetwork::InOut<t, INPUT_SIZE>& in, std::size_t fi)\n{\n  for(int i = 0; i < in.size(); ++i)\n  {\n    in(i) = m_array_f[fi](in(i));\n  }\n}\n\ntemplate<std::size_t DEPTH>\ntemplate<typename tin, int INPUT_SIZE, typename tout, int OUTPUT_SIZE>\nvoid neuralnetwork::Perceptron<DEPTH>::feedForward(neuralnetwork::InOut<tin, INPUT_SIZE>& in, neuralnetwork::InOut<tout, OUTPUT_SIZE>& out, bool saveAgreg, bool saveActivation)\n{\n  InOut<tin, neuralnetwork::InOutType::DYNAMIC> tmp;\n  \n  //feed forward pour le premiere couche\n  tmp = m_array_matrix[0]*in;\n  \n  if(saveAgreg)\n  {\n    m_array_agreg[0] = tmp;\n  }\n  applyActivation(tmp, 0);\n  if(saveActivation)\n  {\n    m_array_act[0] = tmp;\n  }\n\n  //feed forward pour les autres couches\n  for(unsigned int i = 1; i < DEPTH; ++i)\n  {\n    tmp = m_array_matrix[i] * tmp;\n    if(saveAgreg)\n    {\n      m_array_agreg[i] = tmp;\n    }\n    applyActivation(tmp, i);\n    if(saveActivation)\n    {\n      m_array_act[i] = tmp;\n    }\n  }\n\n  out = tmp;\n}\n\ntemplate<std::size_t DEPTH>\ntemplate<typename tin, int INPUT_SIZE, typename tout, int OUTPUT_SIZE>\nvoid neuralnetwork::Perceptron<DEPTH>::backpropagation(neuralnetwork::InOut<tin, INPUT_SIZE>* ins, neuralnetwork::InOut<tout, OUTPUT_SIZE>* outs, std::size_t n, double step)\n{\n  neuralnetwork::InOut<tout, Eigen::Dynamic> out;\n  neuralnetwork::InOut<tout, Eigen::Dynamic> err;\n  \n  //Pour chaque exemple d'entrainement\n  for(unsigned int i = 0; i < n; ++i)\n  {\n    //On evalue un exemple avec le reseau\n    feedForward(ins[i], out, true, true);\n    \n    //On calcul l'erreur en sortie\n    \n    //difference entre la sortie desiree et la sortie attendue\n    err = outs[i] - out;\n    //df(agreg)*(sortie_desiree - sortie_attendue)\n    for(unsigned int j = 0; j < err.size(); ++j)\n    {\n      err(j) = m_array_df[DEPTH - 1](m_array_agreg[DEPTH - 1](j)) * err(j);\n    }\n    m_array_err[DEPTH - 1] = err;\n\n    //Erreur pour les autres couches\n    //erreur(j - 1) = df(agreg) * matriceJ.transpose * erreur(j)\n    for(unsigned int j = DEPTH - 1; j > 0; --j)\n    {\n      err = m_array_matrix[j].transpose() * m_array_err[j];\n      for(int k = 0; k < err.size(); ++k)\n      {\n        err(k) = m_array_df[j - 1](m_array_agreg[j - 1](k)) * err(k);\n      }\n      m_array_err[j - 1] = err;\n    }\n\n    //Mise a jour des poids\n    for(unsigned int j = 0; j < DEPTH; ++j)\n    {\n      for(unsigned int k = 0; k < couch_size(j); ++k)\n      {\n        for(unsigned int l = 0; l < weights_count(j); ++l)\n        {\n          if(j > 0)\n          {\n            weight(j, k, l) += step * m_array_err[j](k) * m_array_act[j - 1](l);\n          }\n          //Pour la premiere couche on prend le vecteur d'entree\n          else\n          {\n            weight(j, k, l) += step * m_array_err[j](k) * ins[i](l);\n          }\n        }\n      }\n    }\n\n  }\n}\n\ntemplate<std::size_t DEPTH>\ntemplate<typename tin, int INPUT_SIZE, typename tout, int OUTPUT_SIZE>\nvoid neuralnetwork::Perceptron<DEPTH>::parallel_feedForward(neuralnetwork::InOut<tin, INPUT_SIZE>& in, neuralnetwork::InOut<tout, OUTPUT_SIZE>& out)\n{ \n  //On initialise le vecteur d'entree\n  m_first_graph_vector.resize(in.size());\n  for(int i = 0; i < in.size(); ++i)\n  {\n    m_first_graph_vector[i] = in[i];\n  }\n  \n  //On lance le feed forward\n  for(unsigned int i = 0; i < m_forward_neurons[0].size(); ++i)\n  {\n    m_forward_neurons[0][i].try_put(tbb::flow::continue_msg());\n  }\n  \n  m_graph_forward.wait_for_all();\n  out = m_array_act[DEPTH - 1];\n}\n\ntemplate<std::size_t DEPTH>\ntemplate<typename tin, int INPUT_SIZE, typename tout, int OUTPUT_SIZE>\nvoid neuralnetwork::Perceptron<DEPTH>::parallel_backpropagation(neuralnetwork::InOut<tin, INPUT_SIZE>* ins, neuralnetwork::InOut<tout, OUTPUT_SIZE>* outs, std::size_t n, double step)\n{\n  neuralnetwork::InOut<tout, Eigen::Dynamic> out;\n  neuralnetwork::InOut<tout, Eigen::Dynamic> err;\n  \n  //Pour chaque exemple d'entrainement\n  for(unsigned int i = 0; i < n; ++i)\n  {\n    //On evalue un exemple avec le reseau\n    parallel_feedForward(ins[i], out);\n    //feedForward(ins[i], out, true, true);\n    \n    //On calcul l'erreur en sortie\n    //difference entre la sortie desiree et la sortie attendue\n    err = outs[i] - out;\n    for(unsigned int j = 0; j < err.size(); ++j)\n    {\n      err(j) = m_array_df[DEPTH - 1](m_array_agreg[DEPTH - 1](j)) * err(j);\n    }\n    m_array_err[DEPTH - 1] = err;\n    \n    //On lance la retropropagation\n    for(unsigned int j = 0; j < m_backward_neurons.back().size(); ++j)\n    {\n      m_backward_neurons.back()[j].try_put(tbb::flow::continue_msg());\n    }\n    m_graph_backward.wait_for_all();\n    \n  }\n}\n\n#endif\n", "meta": {"hexsha": "d6dc15e51d211b33aaaee0c4835eaf8417af0394", "size": 36920, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Perceptron.hpp", "max_stars_repo_name": "Projet-ReseauDeNeurones-M1CHPS/MNISTNN2", "max_stars_repo_head_hexsha": "bf7e0f8a114d2ca492d1c2c6c76fe348857ab4ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Perceptron.hpp", "max_issues_repo_name": "Projet-ReseauDeNeurones-M1CHPS/MNISTNN2", "max_issues_repo_head_hexsha": "bf7e0f8a114d2ca492d1c2c6c76fe348857ab4ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Perceptron.hpp", "max_forks_repo_name": "Projet-ReseauDeNeurones-M1CHPS/MNISTNN2", "max_forks_repo_head_hexsha": "bf7e0f8a114d2ca492d1c2c6c76fe348857ab4ff", "max_forks_repo_licenses": ["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.4822335025, "max_line_length": 460, "alphanum_fraction": 0.5987540628, "num_tokens": 9503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6202981930255936}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nnamespace icarus::types\n{\n    using Scalar = float;\n    using Vector3 = Eigen::Matrix<Scalar, 3, 1>;\n    using Quaternion = Eigen::Quaternion<Scalar>;\n}\n", "meta": {"hexsha": "d87b0e2be29caa6a84e7699066a2d7897d687bb8", "size": 217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "icarus/include/icarus/sensor/Algebra.hpp", "max_stars_repo_name": "Icarus-Quadro/Icarus", "max_stars_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "icarus/include/icarus/sensor/Algebra.hpp", "max_issues_repo_name": "Icarus-Quadro/Icarus", "max_issues_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "icarus/include/icarus/sensor/Algebra.hpp", "max_forks_repo_name": "Icarus-Quadro/Icarus", "max_forks_repo_head_hexsha": "10c4f1e804432d8cd11541f3e7342a12acec79f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0833333333, "max_line_length": 49, "alphanum_fraction": 0.6912442396, "num_tokens": 54, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.7154240079185318, "lm_q1q2_score": 0.6202981884542763}}
{"text": "//  (C) Copyright 2006 Eric Niebler, Olivier Gygi.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Test case for weighted_tail_mean.hpp\n\n#define BOOST_NUMERIC_FUNCTIONAL_STD_COMPLEX_SUPPORT\n#define BOOST_NUMERIC_FUNCTIONAL_STD_VALARRAY_SUPPORT\n#define BOOST_NUMERIC_FUNCTIONAL_STD_VECTOR_SUPPORT\n\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <boost/accumulators/statistics/weighted_tail_mean.hpp>\n#include <boost/accumulators/statistics/weighted_tail_quantile.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    // tolerance in %\n    double epsilon = 1;\n\n    std::size_t n = 100000; // number of MC steps\n    std::size_t c = 25000; // cache size\n\n    accumulator_set<double, stats<tag::non_coherent_weighted_tail_mean<right> >, double >\n        acc0( right_tail_cache_size = c );\n    accumulator_set<double, stats<tag::non_coherent_weighted_tail_mean<left> >, double >\n        acc1( left_tail_cache_size = c );\n\n    // random number generators\n    boost::lagged_fibonacci607 rng;\n\n    for (std::size_t i = 0; i < n; ++i)\n    {\n        double smpl = std::sqrt(rng());\n        acc0(smpl, weight = 1./smpl);\n    }\n\n    for (std::size_t i = 0; i < n; ++i)\n    {\n        double smpl = rng();\n        acc1(smpl*smpl, weight = smpl);\n    }\n\n    // check uniform distribution\n    BOOST_CHECK_CLOSE( non_coherent_weighted_tail_mean(acc0, quantile_probability = 0.95), 0.975, epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_weighted_tail_mean(acc0, quantile_probability = 0.975), 0.9875, epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_weighted_tail_mean(acc0, quantile_probability = 0.99), 0.995, epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_weighted_tail_mean(acc0, quantile_probability = 0.999), 0.9995, epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_weighted_tail_mean(acc1, quantile_probability = 0.05), 0.025, epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_weighted_tail_mean(acc1, quantile_probability = 0.025), 0.0125, epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_weighted_tail_mean(acc1, quantile_probability = 0.01), 0.005, epsilon );\n    BOOST_CHECK_CLOSE( non_coherent_weighted_tail_mean(acc1, quantile_probability = 0.001), 0.0005, 5*epsilon );\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_tail_mean test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n\n", "meta": {"hexsha": "d7a6aa3e3252014e86024424b1ce68995a27b48e", "size": 2935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/weighted_tail_mean.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/accumulators/test/weighted_tail_mean.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/accumulators/test/weighted_tail_mean.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": 37.6282051282, "max_line_length": 112, "alphanum_fraction": 0.6977853492, "num_tokens": 744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6202981874201043}}
{"text": "//  (C) Copyright Raffi Enficiaud 2014.\n//  Distributed under the Boost Software License, Version 1.0.\n//  (See accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n\n//  See http://www.boost.org/libs/test for the library home page.\n\n//[example_code\n#define BOOST_TEST_MODULE dataset_example68\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n#include <sstream>\n\nnamespace bdata = boost::unit_test::data;\n\n// Dataset generating a Fibonacci sequence\nclass fibonacci_dataset {\npublic:\n    // Samples type is int\n    enum { arity = 1 };\n\n    struct iterator {\n\n        iterator() : a(1), b(1) {}\n\n        int operator*() const   { return b; }\n        void operator++()\n        {\n            a = a + b;\n            std::swap(a, b);\n        }\n    private:\n        int a;\n        int b; // b is the output\n    };\n\n    fibonacci_dataset()             {}\n\n    // size is infinite\n    bdata::size_t   size() const    { return bdata::BOOST_TEST_DS_INFINITE_SIZE; }\n\n    // iterator\n    iterator        begin() const   { return iterator(); }\n};\n\nnamespace boost { namespace unit_test { namespace data { namespace monomorphic {\n  // registering fibonacci_dataset as a proper dataset\n  template <>\n  struct is_dataset<fibonacci_dataset> : boost::mpl::true_ {};\n}}}}\n\n// Creating a test-driven dataset\nBOOST_DATA_TEST_CASE(\n    test1,\n    fibonacci_dataset() ^ bdata::make( { 1, 2, 3, 5, 8, 13, 21, 35, 56 } ),\n    fib_sample, exp)\n{\n      BOOST_TEST(fib_sample == exp);\n}\n//]\n", "meta": {"hexsha": "8d69fbb5b3c3e78bd6fdd5c969ff298affbdb34d", "size": 1576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/dataset_example68.run-fail.cpp", "max_stars_repo_name": "rainerdeyke/test", "max_stars_repo_head_hexsha": "d44509b4e4d25afb32e8832e404b38e95681a6bd", "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": "doc/examples/dataset_example68.run-fail.cpp", "max_issues_repo_name": "rainerdeyke/test", "max_issues_repo_head_hexsha": "d44509b4e4d25afb32e8832e404b38e95681a6bd", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/examples/dataset_example68.run-fail.cpp", "max_forks_repo_name": "rainerdeyke/test", "max_forks_repo_head_hexsha": "d44509b4e4d25afb32e8832e404b38e95681a6bd", "max_forks_repo_licenses": ["BSL-1.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.4193548387, "max_line_length": 82, "alphanum_fraction": 0.6345177665, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6202981874201043}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_XFORM_HPP\n#define MCL_XFORM_HPP 1\n\n#include <Eigen/Geometry>\n\nnamespace mcl\n{\n\ntemplate <typename T>\nclass XForm\n{\nprotected:\n\tEigen::Matrix<T,4,4> data;\n\npublic:\n\ttemplate <typename U> using Vec3 = Eigen::Matrix<U,3,1>;\n\n\tXForm()\n\t{\n\t\tsetIdentity();\n\t}\n\n\ttemplate <typename U>\n\tXForm(const XForm<U> &xf)\n\t{\n\t\tdata = xf.data.template cast<T>();\n\t}\n\n\tconst Eigen::Matrix<T,4,4>& matrix() const\n\t{\n\t\treturn data;\n\t}\n\n\tEigen::Matrix<T,4,4>& matrix()\n\t{\n\t\treturn data;\n\t}\n\n\tT operator()(int i, int j) const\n\t{\n\t\treturn data(i,j);\n\t}\n\n\tT& operator()(int i, int j)\n\t{\n\t\treturn data(i,j);\n\t}\n\n\tVec3<T> operator*(const Vec3<T> &v)\n\t{\n\t\treturn (Eigen::Transform<T,3,Eigen::Affine>(data) * v);\n\t}\n\n\tEigen::Matrix<T,2,1> operator*(const Eigen::Matrix<T,2,1> &v)\n\t{\n\t\tVec3<T> v3(v[0], v[1], 0);\n\t\tv3 = Eigen::Transform<T,3,Eigen::Affine>(data) * v3;\n\t\treturn Eigen::Matrix<T,2,1>(v3[0], v3[1]);\n\t}\n\n\tvoid setZero()\n\t{\n\t\tdata.setZero();\n\t}\n\n\tvoid setIdentity()\n\t{\n\t\tdata.setZero();\n\t\tdata.diagonal().array() = 1;\n\t}\n\n\t// Makes an identity matrix\n\tstatic inline XForm<T> identity()\n\t{\n\t\tXForm<T> r;\n\t\tr.setIdentity();\n\t\treturn r;\n\t}\n\n\t// Makes a scale matrix\n\t// Usage: XForm<float> s = xform::make_scale(1.f, 2.f, 3.f);\n\tstatic inline XForm<T> make_scale(T x, T y, T z)\n\t{\n\t\tXForm<T> r;\n\t\tr.setZero();\n\t\tr(0,0) = x;\n\t\tr(1,1) = y;\n\t\tr(2,2) = z;\n\t\tr(3,3) = 1;\n\t\treturn r;\n\t}\n\n\tstatic inline XForm<T> make_scale(T x)\n\t{\n\t\treturn make_scale(x,x,x);\n\t}\n\n\t// Makes a translation matrix\n\t// Usage: XForm<float> t = xform::make_trans(1.f, 2.f, 3.f);\n\tstatic inline XForm<T> make_trans(T x, T y, T z)\n\t{\n\t\tXForm<T> r;\n\t\tr.setIdentity();\n\t\tr(0,3) = x;\n\t\tr(1,3) = y;\n\t\tr(2,3) = z;\n\t\tr(3,3) = z;\n\t\treturn r;\n\t}\n\n\tstatic inline XForm<T> make_trans(const Vec3<T> &t)\n\t{\n\t\treturn make_trans(t[0],t[1],t[2]);\n\t}\n\n\t// Makes a rotation matrix\n\t// Usage: Xform<float> t = xform::make_rot(45.f, Vec3f(0,1,0));\n\tstatic inline XForm<T> make_rotate(T angle_deg, const Vec3<T> &axis)\n\t{\n\t\tT rad_deg = angle_deg * M_PI / 180.0;\n\t\tEigen::AngleAxis<T> rx(axis[0]*rad_deg, Eigen::Vector3d::UnitX());\n\t\tEigen::AngleAxis<T> ry(axis[1]*rad_deg, Eigen::Vector3d::UnitY());\n\t\tEigen::AngleAxis<T> rz(axis[2]*rad_deg, Eigen::Vector3d::UnitZ());\n\t\tEigen::Quaternion<T> q = rx * ry * rz;\n\t\tXForm<T> r;\n\t\tr.data.template block<3,3>(0,0) = q.matrix();\n\t\treturn r;\n\t}\n\n\tstatic inline XForm<T> make_rotate_to(Vec3<T> d)\n\t{\n\t\td.normalize();\n\t\tconst Vec3<T> up(0,1,0);\n\t\tT denom = (d+up).dot(d+up);\n\t\tXForm<T> xf;\n\t\txf.setIdentity();\n\t\tif(denom==0 && std::abs(d[1]-1) <= 1e-12){ return xf; }\n\t\telse if (denom==0 && std::abs(d[1]+1) <= 1e-12) {\n\t\t\treturn make_rotate(180,Vec3<T>(1,0,0));\n\t\t}\n\n\t\t// Householder refl\n\t\tEigen::Matrix3d I = Eigen::Matrix3d::Identity();\n\t\tEigen::Matrix3d R = 2.0 * (d+up) * (d+up).transpose();\n\t\tR *= (1.0/denom);\n\t\tR -= I;\n\t\tfor( int i=0; i<3; ++i ){\n\t\t\tfor( int j=0; j<3; ++j ){\n\t\t\t\txf(i,j) = R(i,j);\n\t\t\t}\n\t\t}\n\n\t\treturn xf;\n\t}\n\n\t// Makes a view matrix\n\t// Usage: XForm<float> v = XForm::make_view(eye, viewdir, Vec3f(0,1,0));\n\tstatic inline XForm<T> make_view(const Vec3<T> &eye, const Vec3<T> &dir, const Vec3<T> &up)\n\t{\n\t\tVec3<T> w = dir*-1.f; w.normalize();\n\t\tVec3<T> u = up.cross(w);\n\t\tVec3<T> v = w.cross(u);\n\t\tXForm<T> r;\n\t\tr.setIdentity();\n\t\tfor (int i=0; i<3; ++i)\n\t\t{\n\t\t\tr.data()[4*i] = u[i];\n\t\t\tr.data()[4*i+1] = v[i];\n\t\t\tr.data()[4*i+2] = w[i];\n\t\t}\n\t\tr.data()[12] = -eye.dot(u);\n\t\tr.data()[13] = -eye.dot(v);\n\t\tr.data()[14] = -eye.dot(w);\n\t\treturn r;\n\t}\n\n\t// Makes a view matrix (from a lookat point)\n\t// Usage: XForm<float> v = XForm::make_lookat(eye, Vec3f(0,0,0), Vec3f(0,1,0));\n\tstatic inline XForm<T> make_lookat(const Vec3<T> &eye, const Vec3<T> &point, const Vec3<T> &up)\n\t{\n\t\tVec3<T> dir = point-eye;\n\t\treturn make_view(eye,dir,up);\n\t}\n\n\t// Makes a perspective matrix\n\t// Usage: XForm<float> p = XForm::make_persp(45, width/height, 1e-3f, 1e6f);\n\tstatic inline XForm<T> make_persp(T fov_deg, T aspect, T near, T far)\n\t{\n\t\tT fov = fov_deg * M_PI / 180.f;\n\t\tT cossinf = std::cos(fov/2.f) / std::sin(fov/2.f);\n\t\tXForm<T> r;\n\t\tr.setIdentity();\n\t\tr(0,0) = cossinf/aspect;\n\t\tr.data.data()[5] = cossinf;\n\t\tr.data.data()[10] = -(near+far)/(far-near);\n\t\tr.data.data()[14] = -(2.f*near*far)/(far-near);\n\t\tr.data.data()[11] = -1.f;\n\t\tr.data.data()[15] = 0.f;\n\t\treturn r;\n\t}\n\n\tstatic inline std::string to_string(const XForm<T> &xf)\n\t{\n\t\tstd::stringstream ss;\n\t\tss << xf.data;\n\t\treturn ss.str();\n\t}\n\n\tstatic inline XForm<T> from_string(const std::string &s)\n\t{\n\t\tstd::stringstream ss; ss << s;\n\t\tXForm<T> result;\n\t\tss >> result.data;\n\t\treturn result;\n\t}\n\n\n\t// Multiply every row (vertex) by the xform\n\t// Works for 2D or 3D (cols)\n\ttemplate <typename DerivedV>\n\tvoid apply(Eigen::MatrixBase<DerivedV> &V)\n\t{\n\t\tint nv = V.rows();\n\t\tint nc = V.cols();\n\t\tEigen::Transform<T,3,Eigen::Affine> r(data);\n\t\tfor (int i=0; i<nv; ++i)\n\t\t{\n\t\t\tVec3<T> vi = Vec3<T>::Zero();\n\t\t\tfor (int j=0; j<nc; ++j) { vi[j] = V(i,j); }\n\t\t\tvi = r * vi;\n\t\t\tfor (int j=0; j<nc; ++j) { V(i,j) = vi[j]; }\n\t\t}\n\t}\n};\n\n\ntemplate <class T>\nstatic inline XForm<T> operator*(const XForm<T> &xf1, const XForm<T> &xf2)\n{\n\tXForm<T> xf;\n\txf.matrix() = xf1.matrix() * xf2.matrix();\n\treturn xf;\n}\n\n} // ns mcl\n\n#endif\n", "meta": {"hexsha": "683c7ae55424df42a8ce18c94138de1e2e2c2fbd", "size": 5237, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/XForm.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/XForm.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/XForm.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8645418327, "max_line_length": 96, "alphanum_fraction": 0.5896505633, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6202007339603683}}
{"text": "#include \"../data/data.h\"\n\n#include <dlib/dnn.h>\n#include <dlib/matrix.h>\n\n#include <iostream>\n#include <random>\n\nint main() {\n  using namespace dlib;\n\n  size_t n = 10000;\n  size_t seed = 45345;\n  auto data = GenerateData(-1.5, 1.5, n, seed, false);\n\n  std::vector<matrix<double>> x(n);\n  std::vector<matrix<double>> y_data(n);\n\n  for (size_t i = 0; i < n; ++i) {\n    x[i].set_size(1, 1);\n    x[i](0, 0) = data.first[i];\n\n    y_data[i].set_size(1, 1);\n    y_data[i](0, 0) = data.second[i];\n  }\n\n  // normalize data\n  vector_normalizer<matrix<double>> normalizer_x;\n  vector_normalizer<matrix<double>> normalizer_y;\n\n  // let the normalizer learn the mean and standard deviation of the samples\n  normalizer_x.train(x);\n  normalizer_y.train(y_data);\n\n  std::vector<float> y(n);\n\n  // now normalize each sample\n  for (size_t i = 0; i < x.size(); ++i) {\n    x[i] = normalizer_x(x[i]);\n    y_data[i] = normalizer_y(y_data[i]);\n    y[i] = static_cast<float>(y_data[i](0, 0));\n  }\n\n  using NetworkType = loss_mean_squared<\n      fc<1, htan<fc<8, htan<fc<16, htan<fc<32, input<matrix<double>>>>>>>>>>;\n  NetworkType network;\n  float weight_decay = 0.0001f;\n  float momentum = 0.5f;\n  sgd solver(weight_decay, momentum);\n  dnn_trainer<NetworkType> trainer(network, solver);\n  trainer.set_learning_rate(0.01);\n  trainer.set_learning_rate_shrink_factor(1);  // disable learning rate changes\n  trainer.set_mini_batch_size(64);\n  trainer.set_max_num_epochs(500);\n  trainer.be_verbose();\n  trainer.train(x, y);\n  network.clean();\n\n  // auto predictions = network(new_x);\n\n  return 0;\n}\n", "meta": {"hexsha": "21ddb4eec3a1ce4cbfcc6bf321a9b5b014f8349a", "size": 1572, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter10/dlib/mlp-dlib.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter10/dlib/mlp-dlib.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter10/dlib/mlp-dlib.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 24.9523809524, "max_line_length": 79, "alphanum_fraction": 0.6622137405, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6202007280426374}}
{"text": "//\n// Created by Michele Fornino on 5/5/18.\n\n// This is the base code for the MarkovChains project. It provides a few examples of instantiations and usage of the\n// classes MarkovChain.h and MarkovChainSimulations.h\n//\n\n//#include \"DenseDTMC.h\"\n//#include \"DenseCTMC.h\"\n//#include \"SparseCTMC.h\"\n//#include \"SimCTMC.h\"\n\n#include \"MarkovChain.h\"\n#include \"MarkovChainSimulations.h\"\n#include <iostream>\n//#include <vector>\n//#include <Eigen/Dense>\n//#include <Eigen/Sparse>\n//#include <Eigen/SparseLU>\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace MarkovChain;\nusing namespace MarkovChainSimulations;\n\nint main() {\n\n\n\n//    typedef SparseMatrix<double, RowMajor> SMr;\n//    typedef Triplet<double> T;\n    //// Dense Discrete Time Markov Chain\n/*\n    // Populate Transition Matrix from Rouwenhorst convenience function\n    DenseDTMC chain = DenseDTMC::discretizeAR1_Rouwenhorst();\n\n    // Populate DenseDTMC object and compute sample path\n    DenseDTMC::ManySimDTMC simulations;\n    simulations = chain.simDenseDTMC();\n*/\n    DenseCTMC chain1; chain1.discretizeAR1_Rouwenhorst();\n//    DenseDTMC chain2; chain2.discretizeAR1_Rouwenhorst();\n    SimCTMC simulation1 = chain1.simulateMarkovChain(2);\n//    SimDTMC simulation2 = chain2.simulateMarkovChain(2);\n\n//    cout << chain1;\n//    cout << chain2;\n//    cout << simulation1;\n//    cout << simulation2;\n\n\n//#pragma omp declare reduction (merge : std::vector<SimCTMC> : omp_out.insert(omp_out.end(), omp_in.begin(), omp_in.end()))\n    MultSimCTMC prova;\n//#pragma omp parallel for reduction(merge: prova)\n    for (int k = 0; k < 80; k += 1){\n        prova.emplace_back(chain1.simulateMarkovChain(2, 10000));\n    }\n\n    cout << \"DONE SIMULATING!!\\n\";\n\n    cout << prova[79];\n\n//    MultSimDTMC prova; prova.emplace_back(simulation2); prova.emplace_back(simulation2);\n//    saveToFile(prova);\n\n//    simulation2.saveToFile();\n//    MarkovChain<ContinuousTime, MatrixXd> chain = MarkovChain<Continuous, MatrixXd>::discretizeAR1_Rouwenhorst();\n\n    //// Sparse Continuous Time Markov Chain\n    // Populate Infinitesimal Generator\n//    SMr Q(4,4);\n//    vector<T> tripletQ; tripletQ.reserve(10);\n//    tripletQ.emplace_back(T(0,0,-0.25));\n//    tripletQ.emplace_back(T(0,1, 0.25));\n//    tripletQ.emplace_back(T(1,0, 0.15));\n//    tripletQ.emplace_back(T(1,1,-0.50));\n//    tripletQ.emplace_back(T(1,2, 0.35));\n//    tripletQ.emplace_back(T(3,3,-0.25));\n//    tripletQ.emplace_back(T(3,2, 0.25));\n//    tripletQ.emplace_back(T(2,1, 0.25));\n//    tripletQ.emplace_back(T(2,2,-0.50));\n//    tripletQ.emplace_back(T(2,3, 0.25));\n//    Q.setFromTriplets(tripletQ.begin(), tripletQ.end());\n//\n//    // Populate State Vector (Eigen vector of double)\n//    VectorXd S(4); S(0) = -0.5; S(1) = 0; S(2) = 0.5; S(3) = 1;\n\n    // Populate SparseCTMC object and compute sample path\n//    SparseCTMC chain = SparseCTMC(Q, S);\n//    SparseCTMC::ManySimCTMC simulations = chain.simSparseCTMC();\n\n\n    //// Dense Continuous Time Markov Chain\n/*\n    // Populate Infinitesimal Generator\n    MatrixXd Q(4,4);\n    Q(0,0) = -0.03; Q(0,1) =  0.02; Q(0,2) =  0.01; Q(0,3) =  0.00;\n    Q(1,0) =  0.10; Q(1,1) = -0.55; Q(1,2) =  0.30; Q(1,3) =  0.15;\n    Q(2,0) =  0.10; Q(2,1) =  0.25; Q(2,2) = -0.60; Q(2,3) =  0.25;\n    Q(3,0) =  0.10; Q(3,1) =  0.15; Q(3,2) =  0.30; Q(3,3) = -0.55;\n\n    // Populate State Vector (Eigen vector of double)\n    VectorXd S(4); S(0) = -0.5; S(1) = 0; S(2) = 0.5; S(3) = 1;\n\n    // Populate DenseCTMC object and compute sample path\n    DenseCTMC chain = DenseCTMC(Q, S);\n    DenseCTMC::ManySimCTMC simulations = chain.simDenseCTMC();\n*/\n\n    //// Display Results\n//    cout << \"Stationary Distribution:\\n\" << chain.getStationaryDistribution() << \"\\n\";\n//    cout << \"Simulation:\\n\\n\" << simulations[0];\n\n    return 0;\n}", "meta": {"hexsha": "a7c9d68b8e959aba970ca87f49b146b602f906fa", "size": 3784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/markovchains/main.cpp", "max_stars_repo_name": "mfornino/showcase", "max_stars_repo_head_hexsha": "892d14b9d440c90835a8838b7a9db9c4f232d58b", "max_stars_repo_licenses": ["MIT"], "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/markovchains/main.cpp", "max_issues_repo_name": "mfornino/showcase", "max_issues_repo_head_hexsha": "892d14b9d440c90835a8838b7a9db9c4f232d58b", "max_issues_repo_licenses": ["MIT"], "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/markovchains/main.cpp", "max_forks_repo_name": "mfornino/showcase", "max_forks_repo_head_hexsha": "892d14b9d440c90835a8838b7a9db9c4f232d58b", "max_forks_repo_licenses": ["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.9043478261, "max_line_length": 124, "alphanum_fraction": 0.6506342495, "num_tokens": 1255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6202007243493716}}
{"text": "/*\n    MIT License\n\n    Copyright (c) 2021 Zhepei Wang (wangzhepei@live.com)\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n*/\n\n#ifndef TRAJECTORY_HPP\n#define TRAJECTORY_HPP\n\n#include \"gcopter/root_finder.hpp\"\n\n#include <Eigen/Eigen>\n\n#include <iostream>\n#include <cmath>\n#include <cfloat>\n#include <vector>\n\ntemplate <int D>\nclass Piece\n{\npublic:\n    typedef Eigen::Matrix<double, 3, D + 1> CoefficientMat;\n    typedef Eigen::Matrix<double, 3, D> VelCoefficientMat;\n    typedef Eigen::Matrix<double, 3, D - 1> AccCoefficientMat;\n\nprivate:\n    double duration;\n    CoefficientMat coeffMat;\n\npublic:\n    Piece() = default;\n\n    Piece(double dur, const CoefficientMat &cMat)\n        : duration(dur), coeffMat(cMat) {}\n\n    inline int getDim() const\n    {\n        return 3;\n    }\n\n    inline int getDegree() const\n    {\n        return D;\n    }\n\n    inline double getDuration() const\n    {\n        return duration;\n    }\n\n    inline const CoefficientMat &getCoeffMat() const\n    {\n        return coeffMat;\n    }\n\n    inline Eigen::Vector3d getPos(const double &t) const\n    {\n        Eigen::Vector3d pos(0.0, 0.0, 0.0);\n        double tn = 1.0;\n        for (int i = D; i >= 0; i--)\n        {\n            pos += tn * coeffMat.col(i);\n            tn *= t;\n        }\n        return pos;\n    }\n\n    inline Eigen::Vector3d getVel(const double &t) const\n    {\n        Eigen::Vector3d vel(0.0, 0.0, 0.0);\n        double tn = 1.0;\n        int n = 1;\n        for (int i = D - 1; i >= 0; i--)\n        {\n            vel += n * tn * coeffMat.col(i);\n            tn *= t;\n            n++;\n        }\n        return vel;\n    }\n\n    inline Eigen::Vector3d getAcc(const double &t) const\n    {\n        Eigen::Vector3d acc(0.0, 0.0, 0.0);\n        double tn = 1.0;\n        int m = 1;\n        int n = 2;\n        for (int i = D - 2; i >= 0; i--)\n        {\n            acc += m * n * tn * coeffMat.col(i);\n            tn *= t;\n            m++;\n            n++;\n        }\n        return acc;\n    }\n\n    inline Eigen::Vector3d getJer(const double &t) const\n    {\n        Eigen::Vector3d jer(0.0, 0.0, 0.0);\n        double tn = 1.0;\n        int l = 1;\n        int m = 2;\n        int n = 3;\n        for (int i = D - 3; i >= 0; i--)\n        {\n            jer += l * m * n * tn * coeffMat.col(i);\n            tn *= t;\n            l++;\n            m++;\n            n++;\n        }\n        return jer;\n    }\n\n    inline CoefficientMat normalizePosCoeffMat() const\n    {\n        CoefficientMat nPosCoeffsMat;\n        double t = 1.0;\n        for (int i = D; i >= 0; i--)\n        {\n            nPosCoeffsMat.col(i) = coeffMat.col(i) * t;\n            t *= duration;\n        }\n        return nPosCoeffsMat;\n    }\n\n    inline VelCoefficientMat normalizeVelCoeffMat() const\n    {\n        VelCoefficientMat nVelCoeffMat;\n        int n = 1;\n        double t = duration;\n        for (int i = D - 1; i >= 0; i--)\n        {\n            nVelCoeffMat.col(i) = n * coeffMat.col(i) * t;\n            t *= duration;\n            n++;\n        }\n        return nVelCoeffMat;\n    }\n\n    inline AccCoefficientMat normalizeAccCoeffMat() const\n    {\n        AccCoefficientMat nAccCoeffMat;\n        int n = 2;\n        int m = 1;\n        double t = duration * duration;\n        for (int i = D - 2; i >= 0; i--)\n        {\n            nAccCoeffMat.col(i) = n * m * coeffMat.col(i) * t;\n            n++;\n            m++;\n            t *= duration;\n        }\n        return nAccCoeffMat;\n    }\n\n    inline double getMaxVelRate() const\n    {\n        VelCoefficientMat nVelCoeffMat = normalizeVelCoeffMat();\n        Eigen::VectorXd coeff = RootFinder::polySqr(nVelCoeffMat.row(0)) +\n                                RootFinder::polySqr(nVelCoeffMat.row(1)) +\n                                RootFinder::polySqr(nVelCoeffMat.row(2));\n        int N = coeff.size();\n        int n = N - 1;\n        for (int i = 0; i < N; i++)\n        {\n            coeff(i) *= n;\n            n--;\n        }\n        if (coeff.head(N - 1).squaredNorm() < DBL_EPSILON)\n        {\n            return getVel(0.0).norm();\n        }\n        else\n        {\n            double l = -0.0625;\n            double r = 1.0625;\n            while (fabs(RootFinder::polyVal(coeff.head(N - 1), l)) < DBL_EPSILON)\n            {\n                l = 0.5 * l;\n            }\n            while (fabs(RootFinder::polyVal(coeff.head(N - 1), r)) < DBL_EPSILON)\n            {\n                r = 0.5 * (r + 1.0);\n            }\n            std::set<double> candidates = RootFinder::solvePolynomial(coeff.head(N - 1), l, r,\n                                                                      FLT_EPSILON / duration);\n            candidates.insert(0.0);\n            candidates.insert(1.0);\n            double maxVelRateSqr = -INFINITY;\n            double tempNormSqr;\n            for (std::set<double>::const_iterator it = candidates.begin();\n                 it != candidates.end();\n                 it++)\n            {\n                if (0.0 <= *it && 1.0 >= *it)\n                {\n                    tempNormSqr = getVel((*it) * duration).squaredNorm();\n                    maxVelRateSqr = maxVelRateSqr < tempNormSqr ? tempNormSqr : maxVelRateSqr;\n                }\n            }\n            return sqrt(maxVelRateSqr);\n        }\n    }\n\n    inline double getMaxAccRate() const\n    {\n        AccCoefficientMat nAccCoeffMat = normalizeAccCoeffMat();\n        Eigen::VectorXd coeff = RootFinder::polySqr(nAccCoeffMat.row(0)) +\n                                RootFinder::polySqr(nAccCoeffMat.row(1)) +\n                                RootFinder::polySqr(nAccCoeffMat.row(2));\n        int N = coeff.size();\n        int n = N - 1;\n        for (int i = 0; i < N; i++)\n        {\n            coeff(i) *= n;\n            n--;\n        }\n        if (coeff.head(N - 1).squaredNorm() < DBL_EPSILON)\n        {\n            return getAcc(0.0).norm();\n        }\n        else\n        {\n            double l = -0.0625;\n            double r = 1.0625;\n            while (fabs(RootFinder::polyVal(coeff.head(N - 1), l)) < DBL_EPSILON)\n            {\n                l = 0.5 * l;\n            }\n            while (fabs(RootFinder::polyVal(coeff.head(N - 1), r)) < DBL_EPSILON)\n            {\n                r = 0.5 * (r + 1.0);\n            }\n            std::set<double> candidates = RootFinder::solvePolynomial(coeff.head(N - 1), l, r,\n                                                                      FLT_EPSILON / duration);\n            candidates.insert(0.0);\n            candidates.insert(1.0);\n            double maxAccRateSqr = -INFINITY;\n            double tempNormSqr;\n            for (std::set<double>::const_iterator it = candidates.begin();\n                 it != candidates.end();\n                 it++)\n            {\n                if (0.0 <= *it && 1.0 >= *it)\n                {\n                    tempNormSqr = getAcc((*it) * duration).squaredNorm();\n                    maxAccRateSqr = maxAccRateSqr < tempNormSqr ? tempNormSqr : maxAccRateSqr;\n                }\n            }\n            return sqrt(maxAccRateSqr);\n        }\n    }\n\n    inline bool checkMaxVelRate(const double &maxVelRate) const\n    {\n        double sqrMaxVelRate = maxVelRate * maxVelRate;\n        if (getVel(0.0).squaredNorm() >= sqrMaxVelRate ||\n            getVel(duration).squaredNorm() >= sqrMaxVelRate)\n        {\n            return false;\n        }\n        else\n        {\n            VelCoefficientMat nVelCoeffMat = normalizeVelCoeffMat();\n            Eigen::VectorXd coeff = RootFinder::polySqr(nVelCoeffMat.row(0)) +\n                                    RootFinder::polySqr(nVelCoeffMat.row(1)) +\n                                    RootFinder::polySqr(nVelCoeffMat.row(2));\n            double t2 = duration * duration;\n            coeff.tail<1>()(0) -= sqrMaxVelRate * t2;\n            return RootFinder::countRoots(coeff, 0.0, 1.0) == 0;\n        }\n    }\n\n    inline bool checkMaxAccRate(const double &maxAccRate) const\n    {\n        double sqrMaxAccRate = maxAccRate * maxAccRate;\n        if (getAcc(0.0).squaredNorm() >= sqrMaxAccRate ||\n            getAcc(duration).squaredNorm() >= sqrMaxAccRate)\n        {\n            return false;\n        }\n        else\n        {\n            AccCoefficientMat nAccCoeffMat = normalizeAccCoeffMat();\n            Eigen::VectorXd coeff = RootFinder::polySqr(nAccCoeffMat.row(0)) +\n                                    RootFinder::polySqr(nAccCoeffMat.row(1)) +\n                                    RootFinder::polySqr(nAccCoeffMat.row(2));\n            double t2 = duration * duration;\n            double t4 = t2 * t2;\n            coeff.tail<1>()(0) -= sqrMaxAccRate * t4;\n            return RootFinder::countRoots(coeff, 0.0, 1.0) == 0;\n        }\n    }\n};\n\ntemplate <int D>\nclass Trajectory\n{\nprivate:\n    typedef std::vector<Piece<D>> Pieces;\n    Pieces pieces;\n\npublic:\n    Trajectory() = default;\n\n    Trajectory(const std::vector<double> &durs,\n               const std::vector<typename Piece<D>::CoefficientMat> &cMats)\n    {\n        int N = std::min(durs.size(), cMats.size());\n        pieces.reserve(N);\n        for (int i = 0; i < N; i++)\n        {\n            pieces.emplace_back(durs[i], cMats[i]);\n        }\n    }\n\n    inline int getPieceNum() const\n    {\n        return pieces.size();\n    }\n\n    inline Eigen::VectorXd getDurations() const\n    {\n        int N = getPieceNum();\n        Eigen::VectorXd durations(N);\n        for (int i = 0; i < N; i++)\n        {\n            durations(i) = pieces[i].getDuration();\n        }\n        return durations;\n    }\n\n    inline double getTotalDuration() const\n    {\n        int N = getPieceNum();\n        double totalDuration = 0.0;\n        for (int i = 0; i < N; i++)\n        {\n            totalDuration += pieces[i].getDuration();\n        }\n        return totalDuration;\n    }\n\n    inline Eigen::Matrix3Xd getPositions() const\n    {\n        int N = getPieceNum();\n        Eigen::Matrix3Xd positions(3, N + 1);\n        for (int i = 0; i < N; i++)\n        {\n            positions.col(i) = pieces[i].getCoeffMat().col(D);\n        }\n        positions.col(N) = pieces[N - 1].getPos(pieces[N - 1].getDuration());\n        return positions;\n    }\n\n    inline const Piece<D> &operator[](int i) const\n    {\n        return pieces[i];\n    }\n\n    inline Piece<D> &operator[](int i)\n    {\n        return pieces[i];\n    }\n\n    inline void clear(void)\n    {\n        pieces.clear();\n        return;\n    }\n\n    inline typename Pieces::const_iterator begin() const\n    {\n        return pieces.begin();\n    }\n\n    inline typename Pieces::const_iterator end() const\n    {\n        return pieces.end();\n    }\n\n    inline typename Pieces::iterator begin()\n    {\n        return pieces.begin();\n    }\n\n    inline typename Pieces::iterator end()\n    {\n        return pieces.end();\n    }\n\n    inline void reserve(const int &n)\n    {\n        pieces.reserve(n);\n        return;\n    }\n\n    inline void emplace_back(const Piece<D> &piece)\n    {\n        pieces.emplace_back(piece);\n        return;\n    }\n\n    inline void emplace_back(const double &dur,\n                             const typename Piece<D>::CoefficientMat &cMat)\n    {\n        pieces.emplace_back(dur, cMat);\n        return;\n    }\n\n    inline void append(const Trajectory<D> &traj)\n    {\n        pieces.insert(pieces.end(), traj.begin(), traj.end());\n        return;\n    }\n\n    inline int locatePieceIdx(double &t) const\n    {\n        int N = getPieceNum();\n        int idx;\n        double dur;\n        for (idx = 0;\n             idx < N &&\n             t > (dur = pieces[idx].getDuration());\n             idx++)\n        {\n            t -= dur;\n        }\n        if (idx == N)\n        {\n            idx--;\n            t += pieces[idx].getDuration();\n        }\n        return idx;\n    }\n\n    inline Eigen::Vector3d getPos(double t) const\n    {\n        int pieceIdx = locatePieceIdx(t);\n        return pieces[pieceIdx].getPos(t);\n    }\n\n    inline Eigen::Vector3d getVel(double t) const\n    {\n        int pieceIdx = locatePieceIdx(t);\n        return pieces[pieceIdx].getVel(t);\n    }\n\n    inline Eigen::Vector3d getAcc(double t) const\n    {\n        int pieceIdx = locatePieceIdx(t);\n        return pieces[pieceIdx].getAcc(t);\n    }\n\n    inline Eigen::Vector3d getJer(double t) const\n    {\n        int pieceIdx = locatePieceIdx(t);\n        return pieces[pieceIdx].getJer(t);\n    }\n\n    inline Eigen::Vector3d getJuncPos(int juncIdx) const\n    {\n        if (juncIdx != getPieceNum())\n        {\n            return pieces[juncIdx].getCoeffMat().col(D);\n        }\n        else\n        {\n            return pieces[juncIdx - 1].getPos(pieces[juncIdx - 1].getDuration());\n        }\n    }\n\n    inline Eigen::Vector3d getJuncVel(int juncIdx) const\n    {\n        if (juncIdx != getPieceNum())\n        {\n            return pieces[juncIdx].getCoeffMat().col(D - 1);\n        }\n        else\n        {\n            return pieces[juncIdx - 1].getVel(pieces[juncIdx - 1].getDuration());\n        }\n    }\n\n    inline Eigen::Vector3d getJuncAcc(int juncIdx) const\n    {\n        if (juncIdx != getPieceNum())\n        {\n            return pieces[juncIdx].getCoeffMat().col(D - 2) * 2.0;\n        }\n        else\n        {\n            return pieces[juncIdx - 1].getAcc(pieces[juncIdx - 1].getDuration());\n        }\n    }\n\n    inline double getMaxVelRate() const\n    {\n        int N = getPieceNum();\n        double maxVelRate = -INFINITY;\n        double tempNorm;\n        for (int i = 0; i < N; i++)\n        {\n            tempNorm = pieces[i].getMaxVelRate();\n            maxVelRate = maxVelRate < tempNorm ? tempNorm : maxVelRate;\n        }\n        return maxVelRate;\n    }\n\n    inline double getMaxAccRate() const\n    {\n        int N = getPieceNum();\n        double maxAccRate = -INFINITY;\n        double tempNorm;\n        for (int i = 0; i < N; i++)\n        {\n            tempNorm = pieces[i].getMaxAccRate();\n            maxAccRate = maxAccRate < tempNorm ? tempNorm : maxAccRate;\n        }\n        return maxAccRate;\n    }\n\n    inline bool checkMaxVelRate(const double &maxVelRate) const\n    {\n        int N = getPieceNum();\n        bool feasible = true;\n        for (int i = 0; i < N && feasible; i++)\n        {\n            feasible = feasible && pieces[i].checkMaxVelRate(maxVelRate);\n        }\n        return feasible;\n    }\n\n    inline bool checkMaxAccRate(const double &maxAccRate) const\n    {\n        int N = getPieceNum();\n        bool feasible = true;\n        for (int i = 0; i < N && feasible; i++)\n        {\n            feasible = feasible && pieces[i].checkMaxAccRate(maxAccRate);\n        }\n        return feasible;\n    }\n};\n\n#endif", "meta": {"hexsha": "905aa994253f32a9e59f99b3f6e742bbb4aad35b", "size": 15534, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gcopter/include/gcopter/trajectory.hpp", "max_stars_repo_name": "RENyunfan/GCOPTER", "max_stars_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T11:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:17:51.000Z", "max_issues_repo_path": "gcopter/include/gcopter/trajectory.hpp", "max_issues_repo_name": "RENyunfan/GCOPTER", "max_issues_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gcopter/include/gcopter/trajectory.hpp", "max_forks_repo_name": "RENyunfan/GCOPTER", "max_forks_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3968253968, "max_line_length": 94, "alphanum_fraction": 0.5092699884, "num_tokens": 3969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.620200723014693}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  EigenSolver<MatrixXf> es;\nMatrixXf A = MatrixXf::Random(4,4);\nes.compute(A, /* computeEigenvectors = */ false);\ncout << \"The eigenvalues of A are: \" << es.eigenvalues().transpose() << endl;\nes.compute(A + MatrixXf::Identity(4,4), false); // re-use es to compute eigenvalues of A+I\ncout << \"The eigenvalues of A+I are: \" << es.eigenvalues().transpose() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "16720817aa58ffe3d8ecae8f1fc3e1f85507aeb7", "size": 512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_EigenSolver_compute.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_EigenSolver_compute.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_EigenSolver_compute.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9473684211, "max_line_length": 90, "alphanum_fraction": 0.6796875, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6202007024580214}}
{"text": "#include \"LayoutMaker.hpp\"\n\n#include <Eigen/SparseCore>\n#include <Spectra/SymEigsSolver.h>\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include <unordered_set>\n#include <unordered_map>\n#include <iostream>\n#include <numeric>\n#include <stack>\n#include \"UnionFind.hpp\"\n\nnamespace LayoutMaker {\n\nstruct LayoutContext {\n\n\tuint32_t next_id;\n\tconst std::shared_ptr<TriangleMesh> p_mesh;\n\tconst uint32_t max_depth;\n\tconst uint32_t max_cluster_size;\n\tconst uint32_t max_spectral_size;\n\tstd::vector<uint32_t> final_cluster;\n\tconst uint32_t max_iterations_eigen;\n\tconst float error_eigen;\n\n\tLayoutContext(\n\t\tconst std::shared_ptr<TriangleMesh> p_mesh,\n\t\tuint32_t max_depth,\n\t\tuint32_t max_cluster_size,\n\t\tuint32_t max_spectral_size,\n\t\tuint32_t max_iterations_eigen,\n\t\tfloat error_eigen) :\n\t\tnext_id(0), p_mesh(p_mesh), max_depth(max_depth),\n\t\tmax_cluster_size(max_cluster_size),\n\t\tmax_spectral_size(max_spectral_size),\n\t\tmax_iterations_eigen(max_iterations_eigen),\n\t\terror_eigen(error_eigen)\n\t{\n\t\tfinal_cluster.resize(p_mesh->get_vertices().size(), 0);\n\t}\n};\n\nvoid vertex_laplacian_layout(\n\tLayoutContext& context,\n\tconst uint32_t depth,\n\tconst std::unordered_multimap<uint32_t, uint32_t>& vert2face,\n\tconst std::unordered_set<uint32_t>& vertices_indices) {\n\n\t\n\t// Termination if conditions fulfilled\n\tif (vertices_indices.empty()) {\n\t\treturn;\n\t}\n\tif (depth >= context.max_depth) {\n\t\tstd::cout << \"Broke on depth \" << depth << \" with vertices \" << vertices_indices.size() << std::endl;\n\t\tassert(false);\n\t}\n\tif (depth >= context.max_depth || vertices_indices.size() <= context.max_cluster_size) {\n\t\tconst uint32_t id = context.next_id++;\n\t\tfor (uint32_t idx : vertices_indices) {\n\t\t\tcontext.final_cluster[idx] = id;\n\t\t}\n\t\treturn;\n\t}\n\n\tstd::unordered_map<uint32_t, uint32_t> old2new_vert;\n\tstd::vector<uint32_t> new2old_vert(vertices_indices.size());\n\told2new_vert.reserve(vertices_indices.size());\n\t{\n\t\tstd::unordered_set<uint32_t>::const_iterator it = vertices_indices.begin();\n\t\tfor (uint32_t i = 0; i < (uint32_t)vertices_indices.size(); ++i, ++it) {\n\t\t\told2new_vert.insert({ *it, i });\n\t\t\tnew2old_vert[i] = *it;\n\t\t}\n\t}\n\n\t// Compute second smallest eigenvector\n\tstd::vector<uint32_t> vert_degree(vertices_indices.size(), 0);\n\tstd::vector< Eigen::Triplet<float>> triplet_list;\n\ttriplet_list.reserve(3 * vertices_indices.size());\n\t// Fill connectivity\n\tstd::unordered_set<uint32_t>::const_iterator it = vertices_indices.begin();\n\tfor (uint32_t v_new = 0; v_new < (uint32_t)vertices_indices.size(); ++v_new, ++it) {\n\t\tuint32_t v_old = *it;\n\t\tauto range = vert2face.equal_range(v_old);\n\t\tstd::for_each(range.first, range.second,\n\t\t\t[&](const std::pair<const uint32_t, uint32_t>& f_id) {\n\t\t\t\tconst Eigen::Array3i& face = context.p_mesh->get_faces().at(f_id.second);\n\t\t\t\tfor (uint32_t j = 0; j < 3; ++j) {\n\t\t\t\t\tuint32_t v2_old = face[j];\n\t\t\t\t\tif (v2_old != v_old) {\n\t\t\t\t\t\tif (vertices_indices.count(v2_old) != 0) {\n\t\t\t\t\t\t\tvert_degree[v_new] += 1;\n\t\t\t\t\t\t\tuint32_t v2_new = old2new_vert.at(v2_old);\n\t\t\t\t\t\t\ttriplet_list.push_back(Eigen::Triplet<float>(v_new, v2_new, -1.f));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t}\n\n\t// fill degree triplets\n\tfor (uint32_t i = 0; i < (uint32_t)vertices_indices.size(); ++i) {\n\t\ttriplet_list.push_back(Eigen::Triplet<float>(i, i, (float)vert_degree[i]));\n\t}\n\n\n\t// Square sparse matrix\n\tEigen::SparseMatrix<float> laplacian(vertices_indices.size(), vertices_indices.size());\n\tlaplacian.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\tlaplacian.makeCompressed();\n\n\tSpectra::SparseSymMatProd<float> op(laplacian);\n\t// Get Fiedler vector\n\t// Compute second smallest eigenvector\n\tSpectra::SymEigsSolver<Spectra::SparseSymMatProd<float>> eigs(op, 2, 4);\n\teigs.init();\n\n\tEigen::Index num_values = eigs.compute(Spectra::SortRule::SmallestAlge,\n\t\tcontext.max_iterations_eigen, context.error_eigen,\n\t\tSpectra::SortRule::LargestAlge);\n\n\tif (num_values != 2) {\n\t\tstd::cerr << \"Error: num eigenvalues computed is \" << num_values << std::endl;\n\t\treturn;\n\t}\n\t// Get results\n\tif (eigs.info() != Spectra::CompInfo::Successful) {\n\t\tstd::cout << \"Error: No eigenvalues. Computation not successful!\" << std::endl;\n\t\treturn;\n\t}\n\n\tfloat eigenvalue = eigs.eigenvalues()[0];\n\tif (eigenvalue <= 0) {\n\t\tstd::cerr << \"Error: Fiedler eigenvalue is less than 0. Not a connected graph!!\" << std::endl;\n\t\tstd::cerr << \"Computed eigenvalues \" << eigenvalue << std::endl;\n\n\t\treturn;\n\t}\n\n\tconst Eigen::VectorXf eigenvectors = eigs.eigenvectors().col(0);\n\n\n\t// Output or continue\n\t{\n\t\tuint32_t size_cluster_0 = 0;\n\t\tfor (uint32_t i = 0; i < (uint32_t)eigenvectors.size(); ++i) {\n\t\t\tif (eigenvectors[i] < 0.0f) {\n\t\t\t\tsize_cluster_0 += 1;\n\t\t\t}\n\t\t}\n\t\tstd::unordered_set<uint32_t> indices_0, indices_1;\n\t\tindices_0.reserve(size_cluster_0);\n\t\tindices_1.reserve((uint32_t)eigenvectors.size() - size_cluster_0);\n\n\t\tfor (uint32_t i = 0; i < (uint32_t)eigenvectors.size(); ++i) {\n\t\t\tif (eigenvectors[i] < 0.0f) {\n\t\t\t\tindices_0.insert(new2old_vert[i]);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tindices_1.insert(new2old_vert[i]);\n\t\t\t}\n\t\t}\n\n\t\tvertex_laplacian_layout(context, depth + 1, vert2face,\n\t\t\t\tindices_0);\n\t\t\n\t\tvertex_laplacian_layout(context, depth + 1, vert2face,\n\t\t\t\tindices_1);\n\t\t\n\t}\n\n}\n\n\n\nvoid vertex_clustering_layout(\n\tLayoutContext& context,\n\tconst std::unordered_multimap<uint32_t, uint32_t>& vert2face) {\n\tif (context.p_mesh->get_vertices().empty()) {\n\t\treturn;\n\t}\n\n\tconst std::vector<Eigen::Vector3f>& vertices_mesh = context.p_mesh->get_vertices();\n\n\tstruct OctNodeTask {\n\t\tstd::vector<uint32_t> vertices;\n\t\tuint32_t depth;\n\t\tEigen::Vector3f mid_coord;\n\t};\n\n\tEigen::Vector3f minBBox = Eigen::Vector3f::Constant( std::numeric_limits<float>::infinity());\n\tEigen::Vector3f maxBBox = Eigen::Vector3f::Constant(-std::numeric_limits<float>::infinity());\n\n\tfor (const Eigen::Vector3f& v : context.p_mesh->get_vertices()) {\n\t\tminBBox = minBBox.cwiseMin(v);\n\t\tmaxBBox = maxBBox.cwiseMax(v);\n\t}\n\n\tconst float octree_size = (maxBBox - minBBox).maxCoeff();\n\n\tstd::stack<OctNodeTask> tasks;\n\tstd::array<std::vector<uint32_t>, 8> child_verts;\n\n\tstd::unordered_set<uint32_t> vert_indices_spectral;\n\tstd::vector<std::vector<uint32_t>> vert_indices_per_set_buffer;\n\n\tvert_indices_spectral.reserve(vertices_mesh.size() * 3 / 2);\n\n\t// Create root node\n\t{\n\t\tOctNodeTask root;\n\t\troot.vertices.resize(context.p_mesh->get_vertices().size());\n\t\tstd::iota(root.vertices.begin(), root.vertices.end(), 0);\n\t\troot.depth = 0;\n\t\troot.mid_coord = (maxBBox + minBBox) * 0.5f;\n\t\ttasks.push(std::move(root));\n\t}\n\n\t// Do not create octree if not needed\n\tif (tasks.top().vertices.size() < context.max_spectral_size) {\n\t\tvert_indices_spectral.clear();\n\t\tvert_indices_spectral.insert(tasks.top().vertices.begin(), tasks.top().vertices.end());\n\t\t// Spectral classification\n\t\tvertex_laplacian_layout(\n\t\t\tcontext,\n\t\t\t0, // depth\n\t\t\tvert2face,\n\t\t\tvert_indices_spectral\n\t\t);\n\t\treturn;\n\t}\n\n\t// process octree\n\twhile (!tasks.empty()) {\n\t\tconst OctNodeTask task = std::move(tasks.top());\n\t\ttasks.pop();\n\n\t\tconst float size_node = octree_size / static_cast<float>(1 << task.depth);\n\n\t\t// Clear childs\n\t\tfor (auto& v : child_verts)  v.clear();\n\n\t\t// Classify vertices into the 8 childs\n\t\tfor (const uint32_t& i : task.vertices) {\n\t\t\tconst Eigen::Vector3f dir = vertices_mesh[i] - task.mid_coord;\n\t\t\tuint32_t k =\n\t\t\t\t((dir.x() >= 0.f ? 1 : 0) << 0) +\n\t\t\t\t((dir.y() >= 0.f ? 1 : 0) << 1) +\n\t\t\t\t((dir.z() >= 0.f ? 1 : 0) << 2);\n\n\t\t\tchild_verts[k].push_back(i);\n\t\t}\n\n\t\t// Keep generating tasks or cluster\n\t\tfor (uint32_t k = 0; k < 8; ++k) {\n\t\t\tif (child_verts[k].empty()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (child_verts[k].size() < context.max_spectral_size) {\n\t\t\t\tUnionFind<uint32_t> uf(child_verts[k]);\n\t\t\t\tfor (uint32_t v : child_verts[k]) {\n\t\t\t\t\tauto range = vert2face.equal_range(v);\n\t\t\t\t\tstd::for_each(range.first, range.second,\n\t\t\t\t\t\t[&](const std::pair<const uint32_t, uint32_t>& f_id) {\n\t\t\t\t\t\t\tconst Eigen::Array3i& face = context.p_mesh->get_faces().at(f_id.second);\n\t\t\t\t\t\t\tfor (uint32_t j = 0; j < 3; ++j) {\n\t\t\t\t\t\t\t\tuint32_t v2 = face[j];\n\t\t\t\t\t\t\t\tif (v2 != v) {\n\t\t\t\t\t\t\t\t\tuf.union_sets(v, v2);\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}\n\n\t\t\t\tif (uf.get_num_sets() != 1) {\n\t\t\t\t\tif (vert_indices_per_set_buffer.size() < uf.get_num_sets()) {\n\t\t\t\t\t\tvert_indices_per_set_buffer.resize(uf.get_num_sets());\n\t\t\t\t\t}\n\t\t\t\t\t\tuf.get_elements_of_sets(&vert_indices_per_set_buffer);\n\t\t\t\t\t\tfor (const std::vector<uint32_t>& verts : vert_indices_per_set_buffer) {\n\t\t\t\t\t\t\tvert_indices_spectral.clear();\n\t\t\t\t\t\t\tvert_indices_spectral.insert(verts.begin(), verts.end());\n\t\t\t\t\t\t\t// Spectral classification\n\t\t\t\t\t\t\tvertex_laplacian_layout(\n\t\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\t\t0, // depth\n\t\t\t\t\t\t\t\tvert2face,\n\t\t\t\t\t\t\t\tvert_indices_spectral\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tvert_indices_spectral.clear();\n\t\t\t\t\tvert_indices_spectral.insert(child_verts[k].begin(), child_verts[k].end());\n\t\t\t\t\t// Spectral classification\n\t\t\t\t\tvertex_laplacian_layout(\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t0, // depth\n\t\t\t\t\t\tvert2face,\n\t\t\t\t\t\tvert_indices_spectral\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tEigen::Vector3f dir = { k & 0b1 ? 1.f : -1.f, k & 0b10 ? 1.f : -1.f, k & 0b100 ? 1.f : -1.f };\n\t\t\t\tOctNodeTask newT;\n\t\t\t\tnewT.depth = task.depth + 1;\n\t\t\t\tnewT.mid_coord = task.mid_coord + 0.25f * size_node * dir;\n\t\t\t\tnewT.vertices = child_verts[k];\n\t\t\t\ttasks.push(std::move(newT));\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\n}\n\nstd::vector<uint32_t>\nget_mapping_optimized_layout(\n\tconst std::shared_ptr<TriangleMesh> p_mesh,\n\tconst uint32_t max_depth,\n\tconst uint32_t max_cluster_size,\n\tconst uint32_t max_spectral_size,\n\tconst uint32_t max_number_interations_eigen,\n\tconst float eigen_error)\n\n{\n\n\tuint32_t num_vertices = (uint32_t) p_mesh->get_vertices().size();\n\n\tstd::unordered_set<uint32_t> vert_indices;\n\tvert_indices.reserve(num_vertices);\n\tfor (uint32_t i = 0; i < num_vertices; ++i) {\n\t\tvert_indices.insert(i);\n\t}\n\n\tstd::unordered_multimap<uint32_t, uint32_t> vert2face;\n\tvert2face.reserve(num_vertices);\n\tfor (uint32_t f = 0; f < (uint32_t)p_mesh->get_faces().size(); ++f) {\n\t\tfor (uint32_t j = 0; j < 3; ++j) {\n\t\t\tvert2face.insert({ p_mesh->get_faces()[f][j], f});\n\t\t}\n\t}\n\n\tLayoutContext context(p_mesh, max_depth, max_cluster_size, max_spectral_size,\n\t\tmax_number_interations_eigen, eigen_error);\n\t\t\n\tvertex_clustering_layout(context, vert2face);\n\t\t\n\treturn context.final_cluster;\n}\n\n}", "meta": {"hexsha": "1e6ea6a90174564a7674fdbe201f85bdfe25eeeb", "size": 10214, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LayoutMaker.cpp", "max_stars_repo_name": "SirKoto/mesh_layout_optimization", "max_stars_repo_head_hexsha": "54e144ad893192164ee2217a2b05e9fb28957819", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LayoutMaker.cpp", "max_issues_repo_name": "SirKoto/mesh_layout_optimization", "max_issues_repo_head_hexsha": "54e144ad893192164ee2217a2b05e9fb28957819", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LayoutMaker.cpp", "max_forks_repo_name": "SirKoto/mesh_layout_optimization", "max_forks_repo_head_hexsha": "54e144ad893192164ee2217a2b05e9fb28957819", "max_forks_repo_licenses": ["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.691011236, "max_line_length": 103, "alphanum_fraction": 0.6838652829, "num_tokens": 3048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6201987018181115}}
{"text": "// unit test file sinhc.hpp for the special functions test suite\r\n\r\n//  (C) Copyright Hubert Holin 2003.\r\n//  Distributed under the Boost Software License, Version 1.0. (See\r\n//  accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n#include <functional>\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <complex>\r\n\r\n\r\n#include <boost/math/special_functions/sinhc.hpp>\r\n\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\n\r\nBOOST_TEST_CASE_TEMPLATE_FUNCTION(sinhc_pi_test, T)\r\n{\r\n    using    ::std::abs;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::sinhc_pi;\r\n    \r\n    \r\n    BOOST_MESSAGE(\"Testing sinhc_pi in the real domain for \"\r\n        << string_type_name<T>::_() << \".\");\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(),\r\n        (abs(sinhc_pi<T>(static_cast<T>(0))-static_cast<T>(1)))\r\n        (numeric_limits<T>::epsilon()));\r\n}\r\n\r\n\r\nBOOST_TEST_CASE_TEMPLATE_FUNCTION(sinhc_pi_complex_test, T)\r\n{\r\n    using    ::std::abs;\r\n    using    ::std::sin;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::sinhc_pi;\r\n    \r\n    \r\n    BOOST_MESSAGE(\"Testing sinhc_pi in the complex domain for \"\r\n        << string_type_name<T>::_() << \".\");\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(),\r\n        (abs(sinhc_pi<T>(::std::complex<T>(0, 1))-\r\n             ::std::complex<T>(sin(static_cast<T>(1)))))\r\n        (numeric_limits<T>::epsilon()));\r\n}\r\n\r\n\r\nvoid    sinhc_pi_manual_check()\r\n{\r\n    using    ::boost::math::sinhc_pi;\r\n    \r\n    \r\n    BOOST_MESSAGE(\" \");\r\n    BOOST_MESSAGE(\"sinc_pi\");\r\n    \r\n    for    (int i = 0; i <= 100; i++)\r\n    {\r\n        BOOST_MESSAGE( ::std::setw(15)\r\n                    << sinhc_pi<float>(static_cast<float>(i-50)/\r\n                                                static_cast<float>(50))\r\n                    << ::std::setw(15)\r\n                    << sinhc_pi<double>(static_cast<double>(i-50)/\r\n                                                static_cast<double>(50))\r\n                    << ::std::setw(15)\r\n                    << sinhc_pi<long double>(static_cast<long double>(i-50)/\r\n                                                static_cast<long double>(50)));\r\n    }\r\n    \r\n    BOOST_MESSAGE(\" \");\r\n}\r\n    \r\n\r\n", "meta": {"hexsha": "8b48df3df242ade24baf1d2a707f993ad75767fb", "size": 2272, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/math/special_functions/sinhc_test.hpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/math/special_functions/sinhc_test.hpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/special_functions/sinhc_test.hpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 27.0476190476, "max_line_length": 80, "alphanum_fraction": 0.5259683099, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.620148238343271}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/rmat_graph_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <iostream>\n#include <ctime>\n#include <stdio.h>\n\nusing namespace boost;\ntypedef adjacency_list<> Graph;\ntypedef rmat_iterator<minstd_rand, Graph> RMATGen;\ntypedef graph_traits<Graph>::vertex_iterator vertex_iter;\ntypedef property_map<Graph, vertex_index_t>::type IndexMap;\n\nint main(int argc, char* argv[])\n{\n\tif (argc < 3) {\n\t\tfprintf(stderr, \"usage: make_graph #vertices, #numedges\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\tstd::size_t n = atol(argv[1]);\n\tstd::size_t m = atol(argv[2]);\n\n\tfprintf(stderr, \"Vertices = %ld\\n\", n);\n\tfprintf(stderr, \"Edges = %ld\\n\", m);\n\n\tstd::clock_t start;\n\tstart = std::clock();\n\tminstd_rand gen;\n\tRMATGen gen_it(gen, n, m, 0.57, 0.19, 0.19, 0.05, true);\n\tRMATGen gen_end;\n\tfor (; gen_it != gen_end; ++gen_it) {\n\t\tstd::cout << gen_it->first << \" \" << gen_it->second << std::endl;\n\t}\n#if 0\n\t// Create graph with 100 nodes and 400 edges\n\tGraph g(RMATGen(gen, n, m, 0.57, 0.19, 0.19, 0.05, true), RMATGen(), n);\n\n\tIndexMap index = get(vertex_index, g);\n\n\t// Get vertex set\n#if 0\n\tstd::pair<vertex_iter, vertex_iter> vp;\n\tfor (vp = vertices(g); vp.first != vp.second; ++vp.first)\n\t\tstd::cout << index[*vp.first] <<  \" \";\n\tstd::cout << std::endl;\n#endif\n\n\t// Get edge set\n\tgraph_traits<Graph>::edge_iterator ei, ei_end;\n\tfor (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n\t\tstd::cout << index[source(*ei, g)]<< \" \" << index[target(*ei, g)] << \"\\n\";\n#endif\n\n\tstd::cerr << \"The time to build the graph = \" << (std::clock()-start)/(double)CLOCKS_PER_SEC << std::endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "fc8a5336b7c9f0040b5cd7bc6f8f1bb2b902b179", "size": 1686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "flash-graph/tools/rmat-gen.cpp", "max_stars_repo_name": "STEMHA/FlashGraph", "max_stars_repo_head_hexsha": "a16ec7a31b2e0f167a2af76ce494d3dbb25ca256", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-03-30T08:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T15:25:16.000Z", "max_issues_repo_path": "flash-graph/tools/rmat-gen.cpp", "max_issues_repo_name": "STEMHA/FlashGraph", "max_issues_repo_head_hexsha": "a16ec7a31b2e0f167a2af76ce494d3dbb25ca256", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "flash-graph/tools/rmat-gen.cpp", "max_forks_repo_name": "STEMHA/FlashGraph", "max_forks_repo_head_hexsha": "a16ec7a31b2e0f167a2af76ce494d3dbb25ca256", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-19T03:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-06T06:57:13.000Z", "avg_line_length": 29.0689655172, "max_line_length": 107, "alphanum_fraction": 0.6660735469, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.620148238343271}}
{"text": "/*\nMIT License\n\nCopyright (c) 2016 Vernam Group\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include \"../include/fntru.h\"\n#include <math.h>\n#include <NTL/mat_ZZ.h>\n#include <NTL/RR.h>\n\n////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////\n// Compute sigma it is larger than sqrt(q)\nlong sigma(long n, long logq, long e){\n\tlong s;\n\n\tRR n_ \t\t= to_RR(n);\n\tRR q_\t\t= to_RR(\"2\");\tq_ = power(q_, logq);\n\tRR e_ \t\t= power(to_RR(\"2\"), -e);//to_RR(e);\n\tRR s_;\n\n\ts_ = 2*n_*sqrt(log(8*n_*q_)/log(2.0));\n\ts_ = log(s_)/log(2.0);\n\ts_ = s_ + to_RR((0.5-2/e_)*logq);\n\treturn s = to_long(s_);\n}\n// Create fntru\nfntru::fntru(int cyclotM_, int bitsizeMod_, int radixSize_,  ZZ messagePrime_){\n\n\tn =  new ssntru(cyclotM_, 1, bitsizeMod_, 1, messagePrime_, 1);\n\tint sig = sigma(*n->Pointer_N(), bitsizeMod_, 80);\t//Compute sigma and set\n\n\tn->SetSigma(sig);\t// Set Sigma\n\tn->Func_SetModulus();\n\tn->Func_ModulusFind(1, bitsizeMod_);\n\tn->Func_ComputeKeys();\n\n\tradixSize\t= radixSize_;\t// Set radix size\n\tmatrixDim \t= (bitsizeMod_/radixSize) + ((bitsizeMod_%radixSize == 0)? 0 : 1); // Compute matrix size = total bitsize / wordsize\n/////////////////////////////////////////////////\n\t//Compute powers of radix\n\tPowTwo \t\t= new ZZ[matrixDim];\n\tZZ c = to_ZZ(\"1\");\n\tc = c << radixSize;\n\tPowTwo[0] = 1;\n\tfor(int i=1; i<matrixDim; i++)\n\t\tPowTwo[i] = PowTwo[i-1]*c;\n/////////////////////////////////////////////////\n\t//Set arrays in the matrix\n\tmulMat.row = new vec_ZZX[matrixDim];\n\tfor(int i=0; i<matrixDim; i++)\n\t\tmulMat.row[i].SetLength(matrixDim);\n}\n\n//Initialize matrix\nvoid fntru::InitializeCipher(fntru_cipher &m){\n\tm.row.SetLength(matrixDim);\n\tm.len = matrixDim;\n}\n//Compute the bit decomposition oof the given polynomial\nvoid fntru::BitDecomp(vec_ZZX &BD, ZZX &c, int N, int bitlen){\n\tZZX r;\n\tZZ t;\n\tint b[radixSize], t_;\n\tfor(int i=0; i<bitlen; i++){\n\t\tfor(int j=0; j<N; j++){\n\t\t\tt_ = 0;\n\t\t\tfor(int k=0; k<radixSize; k++)\n\t\t\t\tb[k] = bit(coeff(c, j), radixSize*i+k);\n\n\t\t\tfor(int k=0; k<radixSize; k++)\n\t\t\t\tt_  = t_ + (b[k] << k);\n\n\t\t\tt = to_ZZ(t_);\n\t\t\tSetCoeff(r, j, t);\n\t\t}\n\t\tBD[i] = r;\n\t}\n}\n///////////////////////////////////////////////\n// Create the polynomial by using the bit decomposition vector\nvoid fntru::BitDecompInv(ZZX &out, vec_ZZX &BD, int bitlen){\n\tZZX t;\n\tt = 0;\n\tfor(int i=0; i<bitlen; i++){\n\t\tt = t + BD[i]*PowTwo[i];\n\t}\n\tout = t;\n}\n\n//////////////// FLATTEN ////////////////////////\n//Take the ciphertext and apply flattening\nvoid fntru::Flatten(fntru_cipher &c){\n\tFlatten(c, *n->Pointer_N(), matrixDim);\n}\n\nvoid fntru::Flatten(fntru_cipher &c, int &degree, int &l){\n\t\tFlatten(c.row, degree, l);\n}\n// Apply flattening for the vector\n// First apply inverse bit decomposition and later apply bit decomposition\nvoid fntru::Flatten(vec_ZZX &BD, int &degree, int &l){\n\tZZX t;\n\n\tBitDecompInv(t, BD, l);\n\tfor(int i=0; i<degree; i++)\n\t\tSetCoeff(t, i, coeff(t, i) %(*n->Pointer_Q(0)));\n\n\tBitDecomp(BD, t, degree, l);\n}\n// Apply flattening to the matrix (row by row)\nvoid fntru::Flatten(mat_ZZX &c, int &degree, int &l){\n\tfor(int i=0; i<l; i++){\n\t\tFlatten(c.row[i], degree, l);\n\t}\n}\n//////////////// FLATTEN ////////////////////////\n\n\nvoid fntru::Encrypt(fntru_cipher &c, ZZX m){\n\tZZX zero;\n\tZZX E[matrixDim];\n\tmat_ZZX tempCipher;\n\n\t// Set Temp matrix\n\ttempCipher.row = new vec_ZZX[matrixDim];\n\tfor(int i=0; i<matrixDim; i++)\n\t\ttempCipher.row[i].SetLength(matrixDim);\n\n\t// Encryption vector\n\tzero = 0;\n\tfor(int i=0; i<matrixDim; i++)\n\t\tE[i] = n->Prim_Encrypt(zero, 0);\n\n\t// Binary Decomp of encryption vector into the temp matrix\n\tfor(int i=0;i<matrixDim; i++)\n\t\tBitDecomp(tempCipher.row[i], E[i], *n->Pointer_N(), matrixDim);\n\n\t// add message\n\tfor(int i=0; i<matrixDim; i++)\n\t\ttempCipher.row[i][i] = tempCipher.row[i][i]+m;\n\n\t// flatten\n\tFlatten(tempCipher, *n->Pointer_N(), matrixDim);\n\n\t// convert matrix into the encryption vector\n\tfor(int i=0;i<matrixDim; i++)\n\t\tBitDecompInv(c.row[i], tempCipher.row[i], matrixDim);\n\n\t// free memory\n\tfor(int i=0; i<matrixDim; i++)\n\t\ttempCipher.row[i].kill();\n}\n\nvoid fntru::Decrypt(ZZX &m, fntru_cipher &c){\n\tm = n->Prim_Decrypt(c.row[0], 0);\n}\n\n// if sel == 1: do l*l matrix multiplication by matrix*vector\n// if sel == 0: do 1*l matrix multiplication by vector*vector\n// When we are computing multiplication, we optimize it by performing\n// vector*matrix multiplication. This way we do not need the flattening, since\n// we do not do matrix*matrix multiplication.\n//\n// The function has 2 options. When we do vector=matrix*vector, it results in\n// a ciphertext vector. All the elements (ntru ciphers) inside fntru_cipher is computed.\n// In case of vector=vector*vector, we only compute the first row (first ntru cipher).\n// This way we reduce the computation by a factor of matrixDim (number of ciphertexts inside fntru_cipher)\n// If the second option is used it destroys the structure of fntru_cipher. Only first element\n// protects its ciphertext form. Therefore, the user should use that as the output while evaluating all the circuit.\nvoid fntru::Mult(fntru_cipher &c, fntru_cipher &a, fntru_cipher &b, int sel){\n\tif(sel == 1){\n\t\t//Bit decompose all the rows of the operand to turn it into a matrix\n\t\tfor(int i=0; i<matrixDim; i++)\n\t\t\tBitDecomp( mulMat.row[i], a.row[i], *n->Pointer_N(), matrixDim);\n\t\t// compute matrix multiplication\n\t\tMatrixVectorMul(c.row, mulMat, b.row, matrixDim, *n);\n\n\t\tPolyReduce(c, matrixDim, *n);\n\t\tCoeffReduce(c, matrixDim, *n);\n\t\t// clear temp matrix\n\t\tfor(int i=0; i<matrixDim; i++)\n\t\t\tfor(int j=0; j<matrixDim; j++)\n\t\t\t\tmulMat.row[i][j]=0;\n\t}\n\telse {\n\t\t// Bit decompose only first ciphertext\n\t\tBitDecomp( mulMat.row[0], a.row[0], *n->Pointer_N(), matrixDim);\n\t\tVectorDotProd(c.row[0], mulMat.row[0], b.row, matrixDim, *n);\n\n\t\t// !!!TODO: Add a function for row\n\t\tn->Arith_PolyReduce(c.row[0], c.row[0]);\n\t\tfor(int j=0; j< (*n->Pointer_N()); j++)\n\t\t\tSetCoeff(c.row[0], j, coeff(c.row[0], j) % (*n->Pointer_Q(0)));\n\t\t// Clear Matrix\n\t\tfor(int j=0; j<matrixDim; j++)\n\t\t\tmulMat.row[0][j]=0;\n\t}\n}\n\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////////////////////////\n//Compute matrix multiplication\nvoid MatrixMul(mat_ZZX &c, mat_ZZX &a, mat_ZZX &b, int &vectorLength, ssntru &n){\n\tZZX t;\n\tfor(int i=0; i<vectorLength; i++){\n\t\tfor(int j=0; j<vectorLength; j++){\n\t\t\tt = 0;\n\t\t\tfor(int k=0; k<vectorLength; k++)\n\t\t\t\tt = t + a.row[i][k]*b.row[k][j];\n\n\t\t\tn.Arith_PolyReduce(t,t);\n\t\t\tc.row[i][j] = t;\n\t\t}\n\t}\n}\n\n// Compute the dot product of two vectors. In other words, we compute multiplication\n// between the first row of the matrix and the input ciphertext vector.\n// If thread is defined it uses NTL thread routine to compute the multiplications.\nvoid VectorDotProd(ZZX &c, vec_ZZX &a, vec_ZZX &b, int &vectorLength, ssntru &n){\n#ifdef Thread\n\tZZX tt[vectorLength];\n\tPartitionInfo pinfo(vectorLength);\n\tlong cnt = pinfo.NumIntervals();\n\tNTL_EXEC_INDEX(cnt, index)\n\t\t\tlong first, last;\n\t\t\tpinfo.interval(first, last, index);\n\t\t\tfor (int k = first; k<last; k++) {\n\t\t\t\tmul(tt[k], a[k], b[k]);\n\t\t\t}\n\tNTL_EXEC_INDEX_END\n\n\tc = 0;\n\tfor (int k = 0; k<vectorLength; k++)\n\t\tc = c + tt[k];\n#endif\n\n#ifndef Thread\n\tc = 0;\n\tZZX tt;\n\tfor (int k = 0; k<vectorLength; k++){\n\t\tmul(tt, a[k], b[k]);\n//\t\tmul(tt, a[k], b[k]);\n\t\tc=c+tt;\n\t}\n#endif\n}\n\n\n//Matrix vector multiplication. TODO: Check 3 options for which one is more optimized for speed and area.\nvoid MatrixVectorMul(vec_ZZX &c, mat_ZZX &a, vec_ZZX &b, int &vectorLength, ssntru &n){\n\n#ifdef Thread\n#ifdef MULT1\n\tZZX acc, tmp;\n\n\tZZX t, t2;\n\tZZX tt[vectorLength];\n\n\tfor (int i = 0; i<vectorLength; i++) {\n\t\t//clear(acc);\n\t\tacc = 0;\n\n\t\tPartitionInfo pinfo(vectorLength);\n\t\tlong cnt = pinfo.NumIntervals();\n\n\t\tNTL_EXEC_INDEX(cnt, index)\n\t\t\tlong first, last;\n\t\t\tpinfo.interval(first, last, index);\n\t\t\tfor (int k = first; k<last; k++) {\n\t\t\t\tmul(tt[k], a.row[i][k], b[k]);\n\t\t\t}\n\t\tNTL_EXEC_INDEX_END\n\n\t\tacc = 0;\n\t\tfor(int j=0; j<vectorLength; j++)\n\t\t\tacc = acc + tt[j];\n\t\tc[i] = acc;\n\t}\n#endif\n#ifdef MULT2\n\tZZX acc, tmp;\n\n\tZZX t, t2;\n\tZZX tt[vectorLength];\n\n\tmyTimerReal tr;\n\tdouble multtime = 0, addtime = 0;\n\tfor (int i = 0; i<vectorLength; i++) {\n\t\t//clear(acc);\n\t\tacc = 0;\n\t\tstart(tr);\n\t\tPartitionInfo pinfo(vectorLength);\n\t\tlong cnt = pinfo.NumIntervals();\n\n\t\tNTL_EXEC_INDEX(cnt, index)\n\t\t\tlong first, last;\n\t\t\tpinfo.interval(first, last, index);\n\t\t\tfor (int k = first; k<last; k++) {\n\t\t\t\tmul(tt[k], a.row[i][k], b[k]);\n\t\t\t}\n\t\tNTL_EXEC_INDEX_END\n\t\tstop(tr);\n\t\tmulttime += getseconds(tr);\n\t\tacc = 0;\n\t\tstart(tr);\n\t\tfor(int j=0; j<vectorLength; j++)\n\t\t\tacc = acc + tt[j];\n\t\tc[i] = acc;\n\t\tstop(tr);\n\t\taddtime += getseconds(tr);\n\t}\n\n#endif\n#ifdef MULT3\n\tZZX tmp;\n\n\tZZX t, t2;\n\tZZX acc[vectorLength], tt[vectorLength];\n\n\tfor(int j=0; j<vectorLength; j++){\n\t\tacc[j] = 0;\n\t\tc[j] = 0;\n\t}\n\n\tfor (int i = 0; i<vectorLength; i++) {\n\n\t\tPartitionInfo pinfo(vectorLength);\n\t\tlong cnt = pinfo.NumIntervals();\n\n\t\tNTL_EXEC_INDEX(cnt, index)\n\t\t\tlong first, last;\n\t\t\tpinfo.interval(first, last, index);\n\t\t\tfor (int k = first; k<last; k++) {\n\t\t\t\tmul(tt[k], a.row[k][i], b[i]);\n\t\t\t}\n\t\tNTL_EXEC_INDEX_END\n\n\n\t\tfor(int j=0; j<vectorLength; j++)\n\t\t\tc[j] = c[j] + tt[j];\n\n//\t\tfor(int j=0; j<vectorLength; j++)\n//\t\t\tc[j] = c[j] + acc[j];\n\t}\n#endif\n#endif\n\n#ifndef Thread\n\tZZX acc, tmp;\n\tZZX t, t2;\n\tZZX tt[vectorLength];\n\n\tfor (int i = 0; i<vectorLength; i++) {\n\t\tacc = 0;\n\t\tfor (int k = 0; k<vectorLength; k++)\n\t\t\tmul(tt[k], a.row[i][k], b[k]);\n\n\t\tacc = 0;\n\t\tfor(int j=0; j<vectorLength; j++)\n\t\t\tacc = acc + tt[j];\n\t\tc[i] = acc;\n\t}\n\n#endif\n}\n// Coefficient modulus reduction for all ciphertexts in fntru ciphertext\nvoid CoeffReduce(fntru_cipher &c, int &vectorLength, ssntru &n){\n\tfor(int i=0; i<vectorLength; i++)\n\t\tfor(int j=0; j< (*n.Pointer_N()); j++)\n\t\t\tSetCoeff(c.row[i], j, coeff(c.row[i], j) % (*n.Pointer_Q(0)));\n}\n// Polynomial modulus reduction for all ciphertexts in fntru ciphertext\nvoid PolyReduce(fntru_cipher &c, int &vectorLength, ssntru &n){\n\tfor(int i=0; i<vectorLength; i++)\n\t\tn.Arith_PolyReduce(c.row[i], c.row[i]);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////////////////////////\n//////////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid fntru::AND(fntru_cipher &c, fntru_cipher &a, fntru_cipher &b, int sel){\n\tMult(c, a, b, sel);\n}\n\nvoid fntru::XOR(fntru_cipher &c, fntru_cipher &a, fntru_cipher &b, int sel){\n\n\tif(sel == 1){\n\t\tZZX t[a.len];\n\t\tfor(int i=0; i<a.len; i++)\n\t\t\tt[i] = a.row[i] + b.row[i];\n\n\t\tMult(c, a, b, 1);\n\t\tfor(int i=0; i<a.len; i++)\n\t\t\tc.row[i] = t[i] - 2*c.row[i];\n\n\t\tPolyReduce(c, c.len, *n);\n\t\tCoeffReduce(c, c.len, *n);\n\t}\n\telse if(sel == 0){\n\t\tZZX t;\n\t\tint vecSize = 1;\n\t\tt = a.row[0] + b.row[0];\n\t\tMult(c, a, b, 0);\n\t\tc.row[0] = t - 2*c.row[0];\n\t\tPolyReduce(c, vecSize, *n);\n\t\tCoeffReduce(c, vecSize, *n);\n\t}\n}\n\nvoid fntru::OR(fntru_cipher &c, fntru_cipher &a, fntru_cipher &b, int sel){\n\n\tif(sel == 1){\n\t\tZZX t[a.len];\n\t\tfor(int i=0; i<a.len; i++)\n\t\t\tt[i] = a.row[i] + b.row[i];\n\n\t\tMult(c, a, b, 1);\n\t\tfor(int i=0; i<a.len; i++)\n\t\t\tc.row[i] = t[i] - c.row[i];\n\n\t\tPolyReduce(c, c.len, *n);\n\t\tCoeffReduce(c, c.len, *n);\n\t}\n\telse if(sel == 0){\n\t\tZZX t;\n\t\tint vecSize = 1;\n\t\tt = a.row[0] + b.row[0];\n\t\tMult(c, a, b, 0);\n\t\tc.row[0] = t - c.row[0];\n\t\tPolyReduce(c, vecSize, *n);\n\t\tCoeffReduce(c, vecSize, *n);\n\t}\n}\n\nvoid fntru::NOT(fntru_cipher &c, fntru_cipher &a, int sel){\n\n\tif(sel == 1){\n\t\tZZX two;\n\t\ttwo = to_ZZ(\"1\");\n\t\tfor(int i=0; i<a.len; i++){\n\t\t\tc.row[i] = two - a.row[i];\n\t\t\ttwo = two << 1;\n\t\t}\n\t\tCoeffReduce(c, c.len, *n);\n\t}\n\telse if(sel == 0){\n\t\tint vecSize = 1;\n\t\tc.row[0] = to_ZZ(\"1\") - a.row[0];\n\t\tCoeffReduce(c, vecSize, *n);\n\t}\n}\n\n\nvoid fntru::NAND(fntru_cipher &c, fntru_cipher &a, fntru_cipher &b, int sel){\n\n\tMult(c, a, b, sel);\n\tif(sel == 1){\n\t\tZZX two;\n\t\ttwo = to_ZZ(\"1\");\n\t\tfor(int i=0; i<a.len; i++){\n\t\t\tc.row[i] = two - c.row[i];\n\t\t\ttwo = two << 1;\n\t\t}\n\t\tCoeffReduce(c, c.len, *n);\n\t}\n\telse if(sel == 0){\n\t\tint vecSize = 1;\n\t\tc.row[0] = to_ZZ(\"1\") - c.row[0];\n\t\tCoeffReduce(c, vecSize, *n);\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "b9d20710e0d8672920b7680de9ccadc47a25f740", "size": 13415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fntru.cpp", "max_stars_repo_name": "vernamlab/FNTRU", "max_stars_repo_head_hexsha": "31fadb5c1231df41ed6c903cb3a88f89f21ffcf2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-01-12T16:49:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-15T11:46:02.000Z", "max_issues_repo_path": "src/fntru.cpp", "max_issues_repo_name": "vernamlab/FNTRU", "max_issues_repo_head_hexsha": "31fadb5c1231df41ed6c903cb3a88f89f21ffcf2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fntru.cpp", "max_forks_repo_name": "vernamlab/FNTRU", "max_forks_repo_head_hexsha": "31fadb5c1231df41ed6c903cb3a88f89f21ffcf2", "max_forks_repo_licenses": ["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.3113207547, "max_line_length": 128, "alphanum_fraction": 0.5908311592, "num_tokens": 4271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6200674041713202}}
{"text": "#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n#include <gtest/gtest.h>\n#include <array>\n\n\nTEST(Eigen, TensorSlice) {\n\tEigen::Tensor<double, 3> m(3, 10, 10);          //Initialize\n\tm.setRandom();                               //Set random values \n\tstd::array<long, 3> offset = { 0,0,0 };         //Starting point\n\tstd::array<long, 3> extent = { 1,10,10 };       //Finish point\n\tstd::array<long, 2> shape2 = { 10,10 };         //Shape of desired rank-2 tensor (matrix)\n\tstd::cout << m.slice(offset, extent).reshape(shape2) << std::endl;  //Extract slice and reshape it into a 10x10 matrix.\n}", "meta": {"hexsha": "63a1a5b696c7e9d533c1f0001dde4ab3ba8f2eb3", "size": 609, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/general_util_tests/eigen_cpp_test.cpp", "max_stars_repo_name": "sandialabs/gate-public", "max_stars_repo_head_hexsha": "59cdf39c8df07208eb4a02815a9b4585fb40138f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-30T05:36:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T05:36:06.000Z", "max_issues_repo_path": "test/general_util_tests/eigen_cpp_test.cpp", "max_issues_repo_name": "sandialabs/gate-public", "max_issues_repo_head_hexsha": "59cdf39c8df07208eb4a02815a9b4585fb40138f", "max_issues_repo_licenses": ["MIT"], "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/general_util_tests/eigen_cpp_test.cpp", "max_forks_repo_name": "sandialabs/gate-public", "max_forks_repo_head_hexsha": "59cdf39c8df07208eb4a02815a9b4585fb40138f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6, "max_line_length": 120, "alphanum_fraction": 0.60591133, "num_tokens": 178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6200674036361117}}
{"text": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// With contributions from Cornelius Steinhardt\n\n#include <cstdlib>\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/mtl/operation/cuppen.hpp>\n\nusing namespace std;\n\nconst double \t\t\ttol= 1.0e-5;\n\ntemplate <typename Matrix, typename Value, typename Vector>\nvoid test_vector(const Matrix& A, const Value& alpha, const Vector& v, int i)\n{\n    Vector diff(A*v-alpha*v), v1(A*v), v2(alpha*v); // , diff(v1-v2);\n    if (size(v1) < 17) \t\n\tcout << \"A*v is     \" << v1 << \"\\nalpha*v is \" << v2 << '\\n';\n    if (two_norm(diff) > tol) cout << \"two_norm(difference) of the \" << i << \"-th eigenvector is \" << two_norm(diff) << '\\n'; // throw \"wrong eigenvector\";\n}\n\ntemplate <typename Matrix, typename Value, typename Vector>\nvoid test(const Matrix& B, Matrix& BQ, Value scaling, Vector& lambda_b)\n{\n    if (num_rows(B) <= 20)\n\tstd::cout << \"B=\\n\" << B << \"\\n\";\n\n    mtl::dense_vector<double> eig_b= eigenvalue_symmetric(B,22);\n    sort(eig_b);\n    eig_b*= scaling;\n    std::cout<<\"eigenvalues with QR =\"<< eig_b <<\"\\n\";\n    \n    cuppen(B, BQ, lambda_b);\n    lambda_b*= scaling;\n    // std::cout<<\"B  =\\n\"<< B <<\"\\n\";\n    if (num_rows(B) <= 20)\n\tstd::cout<<\"Q  =\\n\"<< BQ <<\"\\n\";\n    std::cout<<\"eigenvalues with Cuppen =\"<< lambda_b <<\"\\n\";\n    \n    eig_b-= lambda_b;\n    std::cout<<\"two_norm(diff)  =\"<< two_norm(eig_b) <<\"\\n\";\n    MTL_THROW_IF(two_norm(eig_b) > tol, mtl::runtime_error(\"Cuppen computes wrong eigenvalues\"));\n\n    Matrix Bs(scaling * B);\n    for (unsigned i= 0; i < num_rows(B); i++)\n\ttest_vector(Bs, lambda_b[i], mtl::dense_vector<double>(BQ[mtl::iall][i]), i);\n}\n\nint main(int argc, char** argv)\n{\n    using namespace mtl;\n    int size= 16;\n    if (argc > 1) size= atoi(argv[1]);\n\n    dense_vector<double>        eig, lam(2), lambda(4),  lambda_b(size), eig_b(size);\n#if 1\n    dense2D<double> Mini(2, 2), QM(2, 2);\n    Mini= 1, 2, 2, -11;\n    cuppen(Mini, QM, lam);\n    \n    std::cout << \"eigenvalues of Mini  =\" << lam <<\"\\n\";\n    std::cout << \"eigenvectors of Mini are\\n\" << QM;    \n#endif\n\n    double array[][4]= {{1,  2,   0,  0},\n                        {2, -9,  -2,  0},\n                        {0, -2,   1,  3},\n                        {0,  0,   3, 10}};\n    dense2D<double> A(array), Q(4,4);\n    std::cout << \"A=\\n\" << A << \"\\n\";\n\n    eig= eigenvalue_symmetric(A,22);\n    sort(eig);\n    std::cout<<\"eigenvalues  =\"<< eig <<\"\\n\";\n    \n    cuppen(A, Q, lambda);\n    std::cout<<\"A  =\\n\"<< A <<\"\\n\";\n    std::cout<<\"Q  =\\n\"<< Q <<\"\\n\";\n    std::cout<<\"eigenvalues  =\"<< lambda <<\"\\n\";\n   \n\n    eig-= lambda;\n    std::cout<<\"two_norm(diff)  =\"<< two_norm(eig) <<\"\\n\";\n    MTL_THROW_IF(two_norm(eig) > tol, mtl::runtime_error(\"Cuppen computes wrong eigenvalues\"));\n\n    for (unsigned i= 0; i < num_rows(A); i++)\n\ttest_vector(A, lambda[i], dense_vector<double>(Q[iall][i]), i);\n\n    \n    dense2D<double> B(size,size), BQ(size,size);\n    B= 0; BQ= 0;\n    \n    const double scale= 64.0 / double(size);\n    for(int i= 1; i < size ; i++){\n      B[i][i]= scale*i+6;\n      B[i][i-1]= 1;\n      B[i-1][i]= 1;\n    }\n    B[0][0]= 6;\n\n    test(B, BQ, 1.0, lambda_b);\n    \n    const double maxv= B[size-1][size-1];\n    B/= maxv;\n    test(B, BQ, maxv, lambda_b);\n\n#if 0\n    // Poisson equation cannot be solved, double eigenvalues are now correctly handled by the secular equation\n    // but Q_tilde in cuppen contains nans (0/0)\n    int lsize= 4;\n    if (argc > 1) lsize= atoi(argv[1]);\n\n    dense2D<double> C(lsize, lsize), CQ(lsize, lsize);\n    C= 0; CQ= 0;\n    \n    C[0][0]= 2;\n    for(int i= 1; i < lsize; i++) {\n\tC[i][i]= 2;\n\tC[i][i-1]= -1;\n\tC[i-1][i]= -1;\n    }\n    cout << \"The matrix of the 1D-Poisson equations I\\n\" << C << '\\n';\n\t\n\n    dense_vector<double> lambda_c(lsize);\n    cuppen(C, CQ, lambda_c);\n\n    if (lsize <= 100)\n\tcout << \"The eigenvalues of the 1D-Poisson equations are \" << lambda_c << '\\n';\n    if (lsize <= 20)\n\tcout << \"The eigenvectors of the 1D-Poisson equations are\\n\" << CQ << '\\n';\n\n    for (unsigned i= 0; i < num_rows(C); i++);\n\t//test_vector(C, lambda_c[i], dense_vector<double>(CQ[iall][i]));\n#endif\n    \n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "0e964f1ec1e354e0c4950afe7f49e9ced25c25de", "size": 4530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/cuppen_svd_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/cuppen_svd_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/cuppen_svd_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 29.6078431373, "max_line_length": 155, "alphanum_fraction": 0.5701986755, "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6200057398036205}}
{"text": "#include <shift/math/utility.hpp>\n#include <shift/core/boost_disable_warnings.hpp>\n#include <boost/test/unit_test.hpp>\n#include <shift/core/boost_restore_warnings.hpp>\n\nusing namespace shift::math;\n\nBOOST_AUTO_TEST_CASE(utility_almost_equal)\n{\n  const auto value1 = 0.2;\n  const auto value2 = 1.0 / std::sqrt(5.0) / std::sqrt(5.0);\n\n  BOOST_CHECK_NE(value1, value2);\n  BOOST_CHECK(almost_equal(value1, value2));\n}\n\nBOOST_AUTO_TEST_CASE(utility_is_power_of_two)\n{\n  static_assert(!is_power_of_two(0x00000000u), \"Error in is_power_of_two\");\n  static_assert(is_power_of_two(0x00000001u), \"Error in is_power_of_two\");\n  static_assert(is_power_of_two(0x00000002u), \"Error in is_power_of_two\");\n  static_assert(!is_power_of_two(0x00000003u), \"Error in is_power_of_two\");\n  static_assert(is_power_of_two(0x80000000u), \"Error in is_power_of_two\");\n}\n\nBOOST_AUTO_TEST_CASE(utility_next_power_of_two)\n{\n  static_assert(next_power_of_two(0x00000100u) == 0x00000200u,\n                \"Error in next_power_of_two.\");\n  static_assert(next_power_of_two(0x00001001u) == 0x00002000u,\n                \"Error in next_power_of_two.\");\n  static_assert(next_power_of_two(0x00110111u) == 0x00200000u,\n                \"Error in next_power_of_two.\");\n  static_assert(next_power_of_two(0x01ffffffu) == 0x02000000u,\n                \"Error in next_power_of_two.\");\n  static_assert(next_power_of_two(0x40000000u) == 0x80000000u,\n                \"Error in next_power_of_two.\");\n  static_assert(next_power_of_two(0x00000000u) == 0x00000001u,\n                \"Error in next_power_of_two.\");\n  static_assert(next_power_of_two(0x80000000u) == 0x00000000u,\n                \"Error in next_power_of_two.\");\n}\n\ntemplate <typename T>\nvoid test_NaNs()\n{\n  if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    BOOST_CHECK(is_nan(quiet_nan<T>()));\n  else\n    BOOST_CHECK(!is_nan(quiet_nan<T>()));\n\n  if constexpr (std::numeric_limits<T>::has_signaling_NaN)\n    BOOST_CHECK(is_nan(signaling_nan<T>()));\n  else\n    BOOST_CHECK(!is_nan(signaling_nan<T>()));\n\n  if constexpr (std::numeric_limits<T>::has_quiet_NaN &&\n                std::numeric_limits<T>::has_signaling_NaN)\n  {\n    // Comparison of any value with a NaN value returns false.\n    BOOST_CHECK_NE(quiet_nan<T>(), T{0});\n    BOOST_CHECK_NE(signaling_nan<T>(), T{0});\n\n    // Comparison of two identical NaN values should also return false.\n    /// ToDo: Visual C++ fails here. Find the reason why.\n    BOOST_CHECK_NE(quiet_nan<T>(), quiet_nan<T>());\n    BOOST_CHECK_NE(signaling_nan<T>(), signaling_nan<T>());\n\n    // Comparison of different NaN values should return false as well.\n    BOOST_CHECK_NE(quiet_nan<T>(), signaling_nan<T>());\n\n    // Signalling and quiet NaN values should be different in binary\n    // representation.\n    auto qnan = quiet_nan<T>();\n    auto snan = signaling_nan<T>();\n    BOOST_CHECK(std::memcmp(&qnan, &snan, sizeof(T)) != 0);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(utility_float_NaNs)\n{\n  test_NaNs<float>();\n  test_NaNs<double>();\n  test_NaNs<long double>();\n}\n\nBOOST_AUTO_TEST_CASE(utility_integer_NaNs)\n{\n  test_NaNs<char>();\n  test_NaNs<short>();\n  test_NaNs<int>();\n}\n\nBOOST_AUTO_TEST_CASE(utility_literals)\n{\n  using namespace shift::math::literals;\n\n  BOOST_CHECK_EQUAL(static_cast<float>(180_deg), pi<float>);\n  BOOST_CHECK_EQUAL(180_deg, pi<double>);\n  BOOST_CHECK_EQUAL(180_fdeg, pi<float>);\n\n  BOOST_CHECK_EQUAL(static_cast<float>(180.0_deg), pi<float>);\n  BOOST_CHECK_EQUAL(180.0_deg, pi<double>);\n  BOOST_CHECK_EQUAL(180.0_fdeg, pi<float>);\n}\n", "meta": {"hexsha": "64d79dae354f2a37aac61745fde1c8ea53cc63e4", "size": 3500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "shift/math/test/utility.cpp", "max_stars_repo_name": "cspanier/shift", "max_stars_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-11-28T18:14:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-06T07:44:36.000Z", "max_issues_repo_path": "shift/math/test/utility.cpp", "max_issues_repo_name": "cspanier/shift", "max_issues_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-06T21:01:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-19T07:52:52.000Z", "max_forks_repo_path": "shift/math/test/utility.cpp", "max_forks_repo_name": "cspanier/shift", "max_forks_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_forks_repo_licenses": ["Apache-2.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.0188679245, "max_line_length": 75, "alphanum_fraction": 0.718, "num_tokens": 963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6200057371262384}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Core>\n\n#include <sophus/se3.h>\n#include <sophus/so3.h>\n\n#include <gtsam/slam/dataset.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/nonlinear/GaussNewtonOptimizer.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n\nusing namespace std;\nusing Sophus::SE3;\nusing Sophus::SO3;\n\n/************************************************\n * \u672c\u7a0b\u5e8f\u6f14\u793a\u5982\u4f55\u7528 gtsam \u8fdb\u884c\u4f4d\u59ff\u56fe\u4f18\u5316\n * sphere.g2o \u662f\u4eba\u5de5\u751f\u6210\u7684\u4e00\u4e2a Pose graph\uff0c\u6211\u4eec\u6765\u4f18\u5316\u5b83\u3002\n * \u4e0e g2o \u76f8\u4f3c\uff0c\u5728 gtsam \u4e2d\u6dfb\u52a0\u7684\u662f\u56e0\u5b50\uff0c\u76f8\u5f53\u4e8e\u8bef\u5dee\n * **********************************************/\n\nint main ( int argc, char** argv )\n{\n    if ( argc != 2 )\n    {\n        cout<<\"Usage: pose_graph_gtsam sphere.g2o\"<<endl;\n        return 1;\n    }\n    ifstream fin ( argv[1] );\n    if ( !fin )\n    {\n        cout<<\"file \"<<argv[1]<<\" does not exist.\"<<endl;\n        return 1;\n    }\n\n    // TO-DO\uff1a\u4f7f\u7528gtsam\u7684\u56e0\u5b50\u56fe\u4f18\u5316\u65b9\u6cd5\n    gtsam::NonlinearFactorGraph::shared_ptr graph ( new gtsam::NonlinearFactorGraph );  // gtsam\u7684\u56e0\u5b50\u56fe\n    gtsam::Values::shared_ptr initial ( new gtsam::Values ); // \u521d\u59cb\u503c\n    // \u4eceg2o\u6587\u4ef6\u4e2d\u8bfb\u53d6\u8282\u70b9\u548c\u8fb9\u7684\u4fe1\u606f\n    int cntVertex=0, cntEdge = 0;\n    cout<<\"reading from g2o file\"<<endl;\n    \n    while ( !fin.eof() )\n    {\n        string tag;\n        fin>>tag;\n        if ( tag == \"VERTEX_SE3:QUAT\" )\n        {\n            // \u9876\u70b9\n            gtsam::Key id;\n            fin>>id;\n            double data[7];\n            for ( int i=0; i<7; i++ ) fin>>data[i];\n            // \u8f6c\u6362\u81f3gtsam\u7684Pose3\n            gtsam::Rot3 R = gtsam::Rot3::Quaternion ( data[6], data[3], data[4], data[5] );\n            gtsam::Point3 t ( data[0], data[1], data[2] );\n            initial->insert ( id, gtsam::Pose3 ( R,t ) );       // \u6dfb\u52a0\u521d\u59cb\u503c\n            cntVertex++;\n        }\n        else if ( tag == \"EDGE_SE3:QUAT\" )\n        {\n            // \u8fb9\uff0c\u5bf9\u5e94\u5230\u56e0\u5b50\u56fe\u4e2d\u7684\u56e0\u5b50\n            gtsam::Matrix m = gtsam::I_6x6;     // \u4fe1\u606f\u77e9\u9635\n            gtsam::Key id1, id2;\n            fin>>id1>>id2;\n            double data[7];\n            for ( int i=0; i<7; i++ ) fin>>data[i];\n            gtsam::Rot3 R = gtsam::Rot3::Quaternion ( data[6], data[3], data[4], data[5] );\n            gtsam::Point3 t ( data[0], data[1], data[2] );\n            for ( int i=0; i<6; i++ )\n                for ( int j=i; j<6; j++ )\n                {\n                    double mij;\n                    fin>>mij;\n                    m ( i,j ) = mij;\n                    m ( j,i ) = mij;\n                }\n                \n            // g2o\u7684\u4fe1\u606f\u77e9\u9635\u5b9a\u4e49\u65b9\u5f0f\u4e0egtsam\u4e0d\u540c\uff0c\u8fd9\u91cc\u5bf9\u5b83\u8fdb\u884c\u4fee\u6539\n            gtsam::Matrix mgtsam = gtsam::I_6x6;\n            mgtsam.block<3,3> ( 0,0 ) = m.block<3,3> ( 3,3 ); // cov rotation\n            mgtsam.block<3,3> ( 3,3 ) = m.block<3,3> ( 0,0 ); // cov translation\n            mgtsam.block<3,3> ( 0,3 ) = m.block<3,3> ( 0,3 ); // off diagonal\n            mgtsam.block<3,3> ( 3,0 ) = m.block<3,3> ( 3,0 ); // off diagonal\n            \n            // \u5355\u72ec\u4e66\u5199\u566a\u58f0\u6a21\u578b\n            gtsam::SharedNoiseModel model = gtsam::noiseModel::Gaussian::Information ( mgtsam );        // \u9ad8\u65af\u566a\u58f0\u6a21\u578b\n            gtsam::NonlinearFactor::shared_ptr factor ( \n                new gtsam::BetweenFactor<gtsam::Pose3> ( id1, id2, gtsam::Pose3 ( R,t ), model ) // \u6dfb\u52a0\u4e00\u4e2a\u56e0\u5b50\n            );\n            graph->push_back ( factor );\n            cntEdge++;\n        }\n        if ( !fin.good() )\n            break;\n    }\n    \n    cout<<\"read total \"<<cntVertex<<\" vertices, \"<<cntEdge<<\" edges.\"<<endl;\n    // \u56fa\u5b9a\u7b2c\u4e00\u4e2a\u9876\u70b9\uff0c\u5728gtsam\u4e2d\u76f8\u5f53\u4e8e\u6dfb\u52a0\u4e00\u4e2a\u5148\u9a8c\u56e0\u5b50 \n    gtsam::NonlinearFactorGraph graphWithPrior = *graph;\n    gtsam::noiseModel::Diagonal::shared_ptr priorModel = \n        gtsam::noiseModel::Diagonal::Variances (\n            ( gtsam::Vector ( 6 ) <<1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6 ).finished() \n        );\n    gtsam::Key firstKey = 0;\n    for ( const gtsam::Values::ConstKeyValuePair& key_value: *initial )\n    {\n        cout<<\"Adding prior to g2o file \"<<endl;\n        // prior\u5148\u9a8c\u56e0\u5b50\n        graphWithPrior.add ( gtsam::PriorFactor<gtsam::Pose3> ( \n            key_value.key, key_value.value.cast<gtsam::Pose3>(), priorModel ) \n        );\n        break;\n    }\n\n    // \u5f00\u59cb\u56e0\u5b50\u56fe\u4f18\u5316\uff0c\u914d\u7f6e\u4f18\u5316\u9009\u9879\n    cout<<\"optimizing the factor graph\"<<endl;\n    // \u6211\u4eec\u4f7f\u7528 LM \u4f18\u5316\n    gtsam::LevenbergMarquardtParams params_lm;\n    params_lm.setVerbosity(\"ERROR\");\n    params_lm.setMaxIterations(20); // \u4e8b\u5b9e\u4e0a5\u6b21\u5c31\u6536\u655b\u4e86\n    params_lm.setLinearSolverType(\"MULTIFRONTAL_QR\");\n    gtsam::LevenbergMarquardtOptimizer optimizer_LM( graphWithPrior, *initial, params_lm );\n    \n    // \u4f60\u53ef\u4ee5\u5c1d\u8bd5\u4e0b GN\n    // gtsam::GaussNewtonParams params_gn;\n    // params_gn.setVerbosity(\"ERROR\");\n    // params_gn.setMaxIterations(20);\n    // params_gn.setLinearSolverType(\"MULTIFRONTAL_QR\");\n    // gtsam::GaussNewtonOptimizer optimizer ( graphWithPrior, *initial, params_gn );\n    \n    gtsam::Values result = optimizer_LM.optimize();\n    cout<<\"Optimization complete\"<<endl;\n    cout<<\"initial error: \"<<graph->error ( *initial ) <<endl;\n    cout<<\"final error: \"<<graph->error ( result ) <<endl;\n\n    cout<<\"done. write to g2o ... \"<<endl;\n    // \u5199\u5165 g2o \u6587\u4ef6\uff0c\u540c\u6837\u4f2a\u88c5\u6210 g2o \u4e2d\u7684\u9876\u70b9\u548c\u8fb9\uff0c\u4ee5\u4fbf\u7528 g2o_viewer \u67e5\u770b\u3002\n    // \u9876\u70b9\n    ofstream fout ( \"result_gtsam.g2o\" );\n    for ( const gtsam::Values::ConstKeyValuePair& key_value: result )\n    {\n        gtsam::Pose3 pose = key_value.value.cast<gtsam::Pose3>();\n        gtsam::Point3 p = pose.translation();\n        gtsam::Quaternion q = pose.rotation().toQuaternion();\n        fout<<\"VERTEX_SE3:QUAT \"<<key_value.key<<\" \"\n            <<p.x() <<\" \"<<p.y() <<\" \"<<p.z() <<\" \"\n            <<q.x()<<\" \"<<q.y()<<\" \"<<q.z()<<\" \"<<q.w()<<\" \"<<endl;\n    }\n    // \u8fb9 \n    for ( gtsam::NonlinearFactor::shared_ptr factor: *graph )\n    {\n        gtsam::BetweenFactor<gtsam::Pose3>::shared_ptr f = dynamic_pointer_cast<gtsam::BetweenFactor<gtsam::Pose3>>( factor );\n        if ( f )\n        {\n            gtsam::SharedNoiseModel model = f->noiseModel();\n            gtsam::noiseModel::Gaussian::shared_ptr gaussianModel = dynamic_pointer_cast<gtsam::noiseModel::Gaussian>( model );\n            if ( gaussianModel )\n            {\n                // write the edge information \n                gtsam::Matrix info = gaussianModel->R().transpose() * gaussianModel->R();\n                gtsam::Pose3 pose = f->measured();\n                gtsam::Point3 p = pose.translation();\n                gtsam::Quaternion q = pose.rotation().toQuaternion();\n                fout<<\"EDGE_SE3:QUAT \"<<f->key1()<<\" \"<<f->key2()<<\" \"\n                    <<p.x() <<\" \"<<p.y() <<\" \"<<p.z() <<\" \"\n                    <<q.x()<<\" \"<<q.y()<<\" \"<<q.z()<<\" \"<<q.w()<<\" \";\n                gtsam::Matrix infoG2o = gtsam::I_6x6;\n                infoG2o.block(0,0,3,3) = info.block(3,3,3,3); // cov translation\n                infoG2o.block(3,3,3,3) = info.block(0,0,3,3); // cov rotation\n                infoG2o.block(0,3,3,3) = info.block(0,3,3,3); // off diagonal\n                infoG2o.block(3,0,3,3) = info.block(3,0,3,3); // off diagonal\n                for ( int i=0; i<6; i++ )\n                    for ( int j=i; j<6; j++ )\n                    {\n                        fout<<infoG2o(i,j)<<\" \";\n                    }\n                fout<<endl;\n            }\n        }\n    }\n    fout.close();\n    cout<<\"done.\"<<endl;\n}\n", "meta": {"hexsha": "0425e3bb8aa3064c9df70af4f89220437c475010", "size": 7122, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch11/pose_graph_gtsam.cpp", "max_stars_repo_name": "billamiable/slambook", "max_stars_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-29T05:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:27:43.000Z", "max_issues_repo_path": "ch11/pose_graph_gtsam.cpp", "max_issues_repo_name": "billamiable/slambook", "max_issues_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch11/pose_graph_gtsam.cpp", "max_forks_repo_name": "billamiable/slambook", "max_forks_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-28T11:53:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-04T02:59:20.000Z", "avg_line_length": 37.8829787234, "max_line_length": 127, "alphanum_fraction": 0.5164279697, "num_tokens": 2305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6200057365600962}}
{"text": "//\n// Created by haohanwang on 1/24/16.\n//\n\n#include \"LinearRegression.hpp\"\n\n#include <Eigen/Dense>\n#include <stdexcept>\n#include <iostream>\n#include <unordered_map>\n\n#ifdef BAZEL\n#include \"Models/ModelOptions.hpp\"\n#else\n#include \"ModelOptions.hpp\"\n#endif\n\nusing namespace Eigen;\nusing namespace std;\n\n\nLinearRegression::LinearRegression() {\n    L1_reg = default_L1_reg;\n    L2_reg = default_L2_reg;\n    betaAll = MatrixXf::Ones(1,1);\n    logisticFlag = false;\n};\n\n\nLinearRegression::LinearRegression(const unordered_map<string, string>& options) {\n    try {\n        L1_reg = stof(options.at(\"lambda\"));\n    } catch (std::out_of_range& oor) {\n        L1_reg = default_L1_reg;\n    }\n    try {\n        L2_reg = stof(options.at(\"L2_lambda\"));\n    } catch (std::out_of_range& oor) {\n        L2_reg = default_L2_reg;\n    }\n    betaAll = MatrixXf::Ones(1,1);\n    logisticFlag = false;\n};\n\nvoid LinearRegression::assertReadyToRun() {\n    // X and y matrices must be initialized with the same number of rows for a LR run to make sense.\n    const bool ready = ((X.rows() > 0) && (X.rows() == y.rows())\n                     && (X.cols() > 0) && (y.cols() > 0));\n    const string err_str = \"X and Y matrices of size (\" + to_string(X.rows()) + \",\" + to_string(X.cols()) + \"), and (\"\n            + to_string(y.rows()) + \",\" + to_string(y.cols()) + \") are not compatible.\";\n    checkLogisticRegression();\n    if (!ready) {\n        //throw runtime_error(err_str);\n    }\n}\n\nvoid LinearRegression::setL1_reg(float l1) { L1_reg = l1; };\n\nvoid LinearRegression::setL2_reg(float l2) { L2_reg = l2; };\n\nfloat LinearRegression::cost() {\n    if (logisticFlag){\n        return 0.5 * (y - (X * beta).unaryExpr(&sigmoid)).squaredNorm()/X.rows() + L1_reg * beta.lpNorm<1>() + L2_reg * beta.squaredNorm();\n    }\n    else{\n        return 0.5 * (y - X * beta).squaredNorm()/X.rows() + L1_reg * beta.lpNorm<1>() + L2_reg * beta.squaredNorm();\n    }\n};\n\nMatrixXf LinearRegression::derivative() {\n    return ((-1.0 * X.transpose() * (y - X * beta)).array() + L1_reg * (beta.array() / beta.cwiseAbs().array()).sum() +\n           L2_reg * beta.sum()).matrix();\n};\n\nMatrixXf LinearRegression::proximal_derivative() {\n    if (logisticFlag){\n        return -1.0 * X.transpose() * (y - (X * beta).unaryExpr(&sigmoid));\n    }\n    else{\n        return -1.0 * X.transpose() * (y - X * beta);\n    }\n};\n\nMatrixXf LinearRegression::proximal_operator(VectorXf in, float lr) {\n    if (L1_reg == 0 && L2_reg == 0){\n        return in;\n    }\n    if (L1_reg != 0 && L2_reg == 0){\n        VectorXf sign = ((in.array()>0).matrix()).cast<float>();//sign\n        sign += -1.0*((in.array()<0).matrix()).cast<float>();\n        in = ((in.array().abs()-lr*L1_reg).max(0)).matrix();//proximal\n        return (in.array()*sign.array()).matrix();//proximal multipled back with sign\n    }\n    else if (L2_reg != 0){\n        return in/(1+2*lr*L2_reg);\n    }\n    else{\n        VectorXf sign = ((in.array()>0).matrix()).cast<float>();\n        sign += -1.0*((in.array()<0).matrix()).cast<float>();\n        in = ((in.array().abs()-lr*L1_reg).max(0)).matrix();\n        in = in.array()*sign.array()/(1+2*lr*L2_reg);\n        return in.matrix();\n    }\n}\n\nvoid LinearRegression::updateBetaAll(MatrixXf b) {\n    if (betaAll.rows() == 1){\n        betaAll = b;\n    }\n    else{\n        betaAll.conservativeResize(betaAll.rows(),betaAll.cols()+1);\n        betaAll.col(betaAll.cols()-1) = b;\n    }\n}\n\nMatrixXf LinearRegression::getBetaAll() {\n    return betaAll;\n}\n\nfloat LinearRegression::getL1_reg() {\n    return L1_reg;\n}\n\nfloat LinearRegression::getL2_reg() {\n    return L2_reg;\n}\n", "meta": {"hexsha": "873aef1196d192815d515f3f527c8b191ccda8c1", "size": 3605, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Models/LinearRegression.cpp", "max_stars_repo_name": "blengerich/jenkins_test", "max_stars_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T00:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-06T16:40:52.000Z", "max_issues_repo_path": "src/Models/LinearRegression.cpp", "max_issues_repo_name": "blengerich/jenkins_test", "max_issues_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2016-11-11T22:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T21:55:57.000Z", "max_forks_repo_path": "src/Models/LinearRegression.cpp", "max_forks_repo_name": "blengerich/jenkins_test", "max_forks_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-02-01T09:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T14:40:43.000Z", "avg_line_length": 28.3858267717, "max_line_length": 139, "alphanum_fraction": 0.5914008322, "num_tokens": 1049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6199848387933319}}
{"text": "// Standard includes\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <algorithm>\n#include <string>\n#include <vector>\n\n// For date parsing\n#include <boost/date_time/local_time/local_time.hpp>\n\n// For converting WGS84 <-> LTP coordinates\n#include <GeographicLib/Geocentric.hpp>\n#include <GeographicLib/LocalCartesian.hpp>\n\n// Main entry point\nint main(int argc, char* argv[])\n{\n\t// We are in science here :)\n\tstd::cout.precision(16);\n\n\t// Base station coordinates (Friday)\n\tdouble org_lat = 51.710979902;\n\tdouble org_lon = -0.210839049;   \n\tdouble org_alt = 141.1027;\n\n\t// Setup a converter\n\tGeographicLib::Geocentric wgs84_ecef(\n\t\tGeographicLib::Constants::WGS84_a(), \n\t\tGeographicLib::Constants::WGS84_f()\n\t);\n\tGeographicLib::LocalCartesian   wgs84_enu(\n\t\torg_lat, \n\t\torg_lon, \n\t\torg_alt, \n\t\twgs84_ecef\n\t); \n\t\n\t// Argument check\n\tif (argc < 2)\n\t{\n\t\tstd::cout << \"Usage: \" << argv[0] << \" <file> \" << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::ifstream \tnamefile(argv[1]);\n\tstd::string \tinput;\n\tint counter = 0;\n\tint line    = 0;\n\n\t// Eat up the heading\n\tfor (int i = 0; i < 15; i++)\n\t\tnamefile >> input;\n\n  \tboost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1)); \n    \n\t// Now process the data\n\tstd::string d, t;\n\tdouble x, y, z;\n\tdouble lat, lon, alt, en, ee, eu, ede, edn, edu, age, ratio;\n\tint q, ns;\n\twhile(namefile >> d >> t >> lat >> lon >> alt >> q >> ns >> en >> ee >> eu >> edn >> ede >> edu >> age >> ratio)\n\t{\n\t\t// Extract a meaningful value in seconds\n\t    std::stringstream ss;\n\t    boost::local_time::local_date_time ldt(boost::local_time::not_a_date_time);\n\t    boost::local_time::local_time_input_facet* input_facet = new boost::local_time::local_time_input_facet();\n\t    input_facet->format(\"%Y/%m/%d %H:%M:%s\");\n\t    ss.imbue(std::locale(ss.getloc(), input_facet));\n\t\tss << d << \" \" << t;\n \t\tss >> ldt;\n\n \t\tboost::posix_time::ptime a = ldt.utc_time();\n    \tboost::posix_time::ptime epoch(boost::gregorian::date(1970,1,1));\n    \tdouble ms = (a - epoch).total_milliseconds();\n    \tms /= 1e3;\n\n \t\t// Convert value to LTP\n\t\twgs84_enu.Forward(\n\t\t\tlat, \n\t\t\tlon, \n\t\t\talt,\n\t\t\tx,\n\t\t\ty,\n\t\t\tz\n\t\t);\n\n\t\t// Print seconds, WGS84 and LTP\n\t\tstd::cout << ms << \",\" << lat << \",\" << lon << \",\" << alt << \",\" << x << \",\" << y  << \",\" << z << std::endl;\n\t}\n\n\t// Success\n\treturn 0;\n}\n", "meta": {"hexsha": "082e338ba075572bc133917cde08155c015d84db", "size": 2300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/waypoint_test/wgs84_to_ltp.cpp", "max_stars_repo_name": "jiangchenzhu/crates_zhejiang", "max_stars_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "thirdparty/waypoint_test/wgs84_to_ltp.cpp", "max_issues_repo_name": "jiangchenzhu/crates_zhejiang", "max_issues_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/waypoint_test/wgs84_to_ltp.cpp", "max_forks_repo_name": "jiangchenzhu/crates_zhejiang", "max_forks_repo_head_hexsha": "711c9fafbdc775114345ab0ca389656db9d20df7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2105263158, "max_line_length": 113, "alphanum_fraction": 0.6208695652, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.619932095323014}}
{"text": "#pragma once\n\n#include \"modprop/compo/Interfaces.h\"\n\n#include <Eigen/Cholesky>\n#include <iostream>\n\nnamespace percepto\n{\n\n// TODO Support other types of decompositions\ntemplate <typename Data>\nclass LogDeterminantCost\n: public Source<double>\n{\npublic:\n\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n\ttypedef Data InputType;\n\ttypedef Source<Data> InputSourceType;\n\ttypedef Sink<Data> SinkType;\n\ttypedef Source<double> OutputSourceType;\n\n\tLogDeterminantCost()\n\t: _input( this ), _scale( 1.0 ), _initialized( false ) {}\n\n\tLogDeterminantCost( const LogDeterminantCost& other )\n\t: _input( this ), _scale( other._scale ), _initialized( other._initialized ),\n\t_dody( other.dody ) {}\n\n\tvoid SetSource( InputSourceType* r ) { r->RegisterConsumer( &_input ); }\n\tvoid SetScale( double s ) { _scale = s; }\n\n\tvirtual unsigned int OutputDim() const { return 1; }\n\n\tvirtual void Foreprop()\n\t{\n\t\tInputType input = _input.GetInput();\n\t\tif( input.rows() != input.cols() )\n\t\t{\n\t\t\tthrow std::invalid_argument( \"LogDeterminantCost: Input must be square.\" );\n\t\t}\n\n\t\t_initialized = false;\n\n\t\t_solver = _solver.compute( input );\n\t\tVectorType d( _solver.vectorD() );\n\t\tif( !( d.array() > 0.0 ).all() )\n\t\t{\n\t\t\tstd::cout << \"in: \" << input << std::endl;\n\t\t\tstd::cout << \"D: \" << d.transpose() << std::endl;\n\t\t\tthrow std::invalid_argument( \"LogDeterminantCost: Input determinant must be positive.\" );\n\t\t}\n\t\tdouble logdet = 0;\n\t\tfor( unsigned int i = 0; i < _solver.vectorD().size(); ++i )\n\t\t{\n\t\t\tlogdet += std::log( _solver.vectorD()(i) );;\n\t\t}\n\t\tOutputSourceType::SetOutput( logdet );\n\t\tOutputSourceType::Foreprop();\n\t}\n\n\tvirtual void BackpropImplementation( const MatrixType& nextDodx )\n\t{\n\t\tif( !_initialized )\n\t\t{\n\t\t\tInputType input = _input.GetInput();\n\t\t\tInputType inputInv = _solver.solve( MatrixType::Identity( input.rows(), input.cols() ) );\n\t\t\tstd::cout << \"input: \" << input << std::endl;\n\t\t\tstd::cout << \"inputInv: \" << inputInv << std::endl;\n\t\t\t_dody = Eigen::Map<MatrixType>( inputInv.data(), 1, inputInv.size() );\n\t\t\t_initialized = true;\n\t\t}\n\n\t\tif( nextDodx.size() == 0 )\n\t\t{\n\t\t\t_input.Backprop( _dody );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"thisDodx: \" << nextDodx * _dody << std::endl;\n\t\t\t_input.Backprop( nextDodx * _dody );\n\t\t}\n\t}\n\nprivate:\n\n\ttypedef Eigen::LDLT<Data> SolverType;\n\t\n\tSinkType _input;\n\tdouble _scale;\n\tbool _initialized;\n\tMatrixType _dody;\n\tSolverType _solver;\n};\n\n}", "meta": {"hexsha": "130f21d175e43ed5a3085e8124d47af969932a42", "size": 2356, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/modprop/optim/LogDeterminantCost.hpp", "max_stars_repo_name": "Humhu/modprop", "max_stars_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-10T00:54:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-10T00:54:53.000Z", "max_issues_repo_path": "include/modprop/optim/LogDeterminantCost.hpp", "max_issues_repo_name": "Humhu/modprop", "max_issues_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/modprop/optim/LogDeterminantCost.hpp", "max_forks_repo_name": "Humhu/modprop", "max_forks_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0408163265, "max_line_length": 92, "alphanum_fraction": 0.6668081494, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6199320909786254}}
{"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_ULPDIST_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ULPDIST_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-ieee\n    This function object returns ulp distance between its arguments.\n\n    It is often difficult to answer to the following question: \"are\n    these two floating computations results similar enough?\". The\n    ulpdist is a way to answer which is tuned for relative errors\n    estimations and peculiarly adapted to cope with the limited bits\n    accuracy of floating point representations.\n\n\n    @par Header <boost/simd/function/ulpdist.hpp>\n\n    @par Notes\n\n    - If the common type is integral  @c ulpdist is the same as @c dist\n\n    - If the common type is floating point the ulpdist is is computed,\n    by the above described method.\n\n    The method is the following:\n\n     - If one and only one of the parameters is @ref Nan the result is @ref Nan,\n     if both are Nans the result is @ref Zero\n\n     - Else, properly normalize the two numbers by the same factor in a way\n     that the largest of the two numbers exponents will be brought to\n     zero\n\n     - Return the absolute difference of these normalized numbers\n      divided by the rounding error Eps\n\n    The rounding error is the ulp (unit in the last place) value, i.e. the\n    floating number, the exponent of which is 0 and the mantissa is all zeros\n    but a 1 in the last digit (it is not hard coded that way however).\n    This means \\f$2^{-23}\\f$ for float and \\f$2^{-52}\\f$ for double.\n\n    \\arg For instance if two floating numbers (of same type) have an ulpdist of\n    @ref Zero that means that their floating representation are identical or they are\n    both Nans.\n\n    \\arg Generally equality up to 0.5 ulp is the best that one can wish beyond\n    strict equality.\n\n    \\arg Typically if a double is compared to the float representation of\n    its floating conversion (they are exceptions as for fully representable\n    reals) the ulpdist will be around \\f$2^{26.5}\\f$ (~\\f$10^8\\f$)\n\n    \\arg  @c ulpdist(1.0,1+Eps\\<double\\>())==0.5\n    \\arg  @c ulpdist(1.0,1+Eps\\<double\\>()/2)==0.0\n    \\arg  @c ulpdist(1.0,1-Eps\\<double\\>()/2)==0.25\n    \\arg  @c ulpdist(1.0,1-Eps\\<double\\>())==0.5\n    \\arg  @c ulpdist(double(Pi\\<float\\>()),Pi\\<double\\>())==9.84293e+07\n\n    @see ulp, Eps, eps\n\n    @par Example:\n\n      @snippet ulpdist.cpp ulpdist\n\n    @par Possible output:\n\n      @snippet ulpdist.txt ulpdist\n\n  **/\n  IEEEValue ulpdist(IEEEValue const& x, IEEEValue const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/ulpdist.hpp>\n#include <boost/simd/function/simd/ulpdist.hpp>\n\n#endif\n", "meta": {"hexsha": "dc57a218ff7749d21b5110b493368ec94b23dad5", "size": 3043, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/ulpdist.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/ulpdist.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/ulpdist.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 33.4395604396, "max_line_length": 100, "alphanum_fraction": 0.6542885311, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6199244723527996}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n#include \"general.h\"\n\nusing EigenMatrix = Eigen::MatrixXd;\nusing EigenVector = Eigen::VectorXd;\n\nEigenMatrix oneD()\n{\n    EigenMatrix m(1,4);\n    m(0,0) = 3;\n    m(0,1) = 2.5;\n    m(0,2) = -1;\n    m(0,3) = 1.5;\n    return m;\n}\n\nEigenMatrix lapack_oneD()\n{\n    auto eigenM = oneD();\n    int n = eigenM.cols();\n    std::cout << \"Cols: \" << n << std::endl;\n    int nn = n ;\n    int rc = nn;\n    int nnp = nn;\n    int one = 1;\n    double *w = nullptr;\n    double *aux = nullptr;\n    double *aux2 = nullptr;\n    w = (double*)malloc(sizeof(double)*nn);\n    aux = (double*)malloc(sizeof(double)*nn);\n    aux2 = (double*)malloc(sizeof(double)*nn);\n    for(int i=0;i<nn;i++)\n      w[i] = eigenM(0, i+1) - eigenM(0, i); /* Dy */\n\n    for(int i=0;i<nn-1;i++){\n        aux[i] = 2;\n        aux2[i] = -1;\n    }\n    aux[nn-1] = 2;\n\n    dpttrf_(&nnp, aux, aux2, &rc);\n    std::cout << \"LDL factorization:\" << std::endl;\n    std::cout << \"aux (Diagonal):\" << std::endl;\n    for(int i=0;i<nn;i++) {\n      std::cout << aux[i] << \", \";\n    }\n    std::cout << std::endl;\n    std::cout << \"aux2 (SubDiagonal):\" << std::endl;\n    for(int i=0;i<nn;i++) {\n      std::cout << aux2[i] << \", \";\n    }\n    std::cout << std::endl;\n    dpttrs_(&nnp, &one, aux, aux2, w, &nnp, &rc);\n\n    std::cout << \"Solution w:\" << std::endl;\n    for(int i=0;i<nn;i++)\n      std::cout << w[i] << \", \";\n    std::cout << std::endl;\n\n    EigenVector m(4);\n    for(int i=0;i<nn;i++)\n      m(i) = w[i];\n    std::cout << m << std::endl;\n\n    if(w) free(w);\n    if(aux) free(aux);\n    if(aux2) free(aux2);\n\n    return m;\n}\n\n/* https://eigen.tuxfamily.org/dox/group__TutorialMapClass.html */\nEigenMatrix eigen_lapack_equivalent_oneD()\n{\n    // Solve X in A*X = B, where A is triangular definite\n    EigenMatrix eigenM(4,4);\n    {\n        EigenVector diag(eigenM.cols());\n        diag.setConstant(2);\n        EigenVector subUpperDiag(eigenM.cols());\n        subUpperDiag.setConstant(-1);\n        eigenM.diagonal() = diag;\n        eigenM.diagonal(1) = subUpperDiag;\n        eigenM.diagonal(-1) = subUpperDiag;\n    }\n    std::cout << \"Matrix eigenM:\\n\" << eigenM << std::endl;\n    EigenVector b(eigenM.cols());\n    EigenMatrix oneM = oneD();\n    for (int i = 0; i < oneM.cols(); ++i) {\n        b[i] = oneM(0, i+1) - oneM(0, i); /* Dy */\n    }\n\n    // EigenVector v = eigenM.llt().solve(b);\n    // EigenVector v = eigenM.ldlt().solve(b);\n    Eigen::LDLT<EigenMatrix> ldltOfM(eigenM);\n    EigenVector v = ldltOfM.solve(b);\n    std::cout << v << std::endl;\n    // EigenVector v = eigenM.colPivHouseholderQr().solve(b);\n    EigenMatrix ldltMatrix = ldltOfM.matrixLDLT();\n    std::cout << ldltMatrix << std::endl;\n    EigenMatrix lMatrix = ldltOfM.matrixL();\n    std::cout << lMatrix << std::endl;\n    std::cout << \"Diagonal of LDLT:\" << std::endl;\n    std::cout << ldltMatrix.diagonal() << std::endl;\n    std::cout << \"SubDiagonal of LDLT:\" << std::endl;\n    std::cout << ldltMatrix.diagonal(-1) << std::endl;\n\n    return v;\n}\n\n/// The idea is that input and output are raw pointers to couple with existing code\nEigenMatrix eigen_interface_raw_pointers_oneD()\n{\n    // Create the typemaps\n    using EigenMatrixMap = Eigen::Map<EigenMatrix>;\n    using EigenMatrixReadOnlyMap = Eigen::Map<const EigenMatrix>;\n    using EigenVectorMap = Eigen::Map<EigenVector>;\n    using EigenVectorReadOnlyMap = Eigen::Map<const EigenVector>;\n    // Populate values using Eigen (just because easier)\n    EigenMatrix eigenM(4,4);\n    {\n        EigenVector diag(eigenM.cols());\n        diag.setConstant(2);\n        EigenVector subUpperDiag(eigenM.cols());\n        subUpperDiag.setConstant(-1);\n        eigenM.diagonal() = diag;\n        eigenM.diagonal(1) = subUpperDiag;\n        eigenM.diagonal(-1) = subUpperDiag;\n    }\n    std::cout << \"Matrix eigenM:\\n\" << eigenM << std::endl;\n    EigenVector b(eigenM.cols());\n    EigenMatrix oneM = oneD();\n    for (int i = 0; i < oneM.cols(); ++i) {\n        b[i] = oneM(0, i+1) - oneM(0, i); /* Dy */\n    }\n    // Set input raw pointers\n    int nn = eigenM.cols();\n    double *w = (double*)malloc(sizeof(double)*nn);\n    for(int i=0;i<nn;i++) w[i] = b[i];\n    // w is b as input (Ax=b), and solution x as output in lapack code.\n    // http://www.netlib.org/lapack/lapack-3.1.1/html/dpttrs.f.html\n    // Create a VectorMap of w to interact with Eigen\n    EigenVectorMap wMap(w, b.size());\n    EigenVector v = eigenM.ldlt().solve(wMap);\n    std::cout << \"v:\\n\" << v << std::endl;\n    std::cout << \"b:\\n\" << b << std::endl;\n    std::cout << \"wMap:\\n\" << wMap << std::endl;\n    wMap = eigenM.ldlt().solve(wMap);\n    std::cout << \"InPlace wMap:\\n\" << wMap << std::endl;\n    v = wMap;\n    if(w) free(w);\n    return v;\n}\n\nint main()\n{\n    bool test_passed = true;\n    std::cout << \"-- oneD Eigen --\" << std::endl;\n    auto mOneD = oneD();\n    std::cout << mOneD << std::endl;\n    std::cout << \"-- lapack (from PN_TV1_Weighted) --\" << std::endl;\n    auto mLapack = lapack_oneD();\n    std::cout << \"-- eigen equivalent cholesky --\" << std::endl;\n    auto mEigen = eigen_lapack_equivalent_oneD();\n    if(mLapack != mEigen){\n        std::cerr << \"Result vectors between mLapack and mEigen are not equal\"  << std::endl;\n        test_passed = false;\n    }\n    std::cout << \"-- eigen interface with raw pointers --\" << std::endl;\n    auto mEigenRaw = eigen_interface_raw_pointers_oneD();\n    if(mLapack != mEigenRaw){\n        std::cerr << \"Result vectors between mLapack and mEigenRaw are not equal\"  << std::endl;\n        test_passed = false;\n    }\n\n    if(!test_passed) return EXIT_FAILURE;\n}\n", "meta": {"hexsha": "3acaf3ea41e95fec5209d3b785a55e9db530eaef", "size": 5583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_use_eigen.cpp", "max_stars_repo_name": "dzenanz/proxTV", "max_stars_repo_head_hexsha": "4f7e2370a7134c871f0cb23aa6107d1d9fa775f0", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_use_eigen.cpp", "max_issues_repo_name": "dzenanz/proxTV", "max_issues_repo_head_hexsha": "4f7e2370a7134c871f0cb23aa6107d1d9fa775f0", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-14T07:40:40.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-14T07:40:40.000Z", "max_forks_repo_path": "test/test_use_eigen.cpp", "max_forks_repo_name": "dzenanz/proxTV", "max_forks_repo_head_hexsha": "4f7e2370a7134c871f0cb23aa6107d1d9fa775f0", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-08-16T00:15:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T21:09:03.000Z", "avg_line_length": 31.1899441341, "max_line_length": 96, "alphanum_fraction": 0.5751388143, "num_tokens": 1770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.619914115398874}}
{"text": "#include \"gtest/gtest.h\"\n#include <Eigen/Core>\n#include \"util/common.h\"\n#include \"util/resource_usage.h\"\n#include <omp.h>\nusing namespace PS;\nTEST(EIGEN3, perf) {\n\n  int n = 3000;\n  Eigen::MatrixXd a = Eigen::MatrixXd::Random(n,n);\n  Eigen::MatrixXd b = Eigen::MatrixXd::Random(n,1);\n\n\n  auto tv = tic();\n  Eigen::MatrixXd c = a * b;\n  LL << toc(tv);\n\n  tv = tic();\n  Eigen::MatrixXd d = a * b;\n  LL << toc(tv);\n}\n// #include \"util/eigen3.h\"\n\n// TEST(EIGEN3, LOADXY) {\n//   using namespace PS;\n//   DSMat X_;\n//   DVec Y_;\n//   auto t = tic();\n//   LoadXY(\"../data/rcv1.train\", 0, 5000, &Y_, &X_);\n//   LL << toc(t);\n\n//   DSMat data_;\n//   DVec label_;\n\n//   LoadXY(\"../data/smalldata\", 0, 10, &label_, &data_);\n\n//   LL << data_;\n\n//   CHECK_EQ(data_.coeffRef(4, 2), -29);\n//   CHECK_EQ(data_.coeffRef(6, 4), -26);\n//   CHECK_EQ(data_.coeffRef(1, 0), 46);\n//   CHECK_EQ(data_.coeffRef(8, 1), 33);\n//   CHECK_EQ(data_.coeffRef(1, 4), -13);\n//   CHECK_EQ(data_.coeffRef(0, 0), 0);\n//   CHECK_EQ(data_.coeffRef(9, 4), -48);\n\n//   // TODO test the correctness\n// }\n", "meta": {"hexsha": "f4d02646fef623a19befdf1771128ce292443341", "size": 1063, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/test/eigen3_test.cc", "max_stars_repo_name": "yipeiw/parameter_server", "max_stars_repo_head_hexsha": "07cbfbf2dc727ee0787d7e66e58a1f7fd8333aff", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-07-21T21:30:59.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-21T21:30:59.000Z", "max_issues_repo_path": "src/test/eigen3_test.cc", "max_issues_repo_name": "yipeiw/parameter_server", "max_issues_repo_head_hexsha": "07cbfbf2dc727ee0787d7e66e58a1f7fd8333aff", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/eigen3_test.cc", "max_forks_repo_name": "yipeiw/parameter_server", "max_forks_repo_head_hexsha": "07cbfbf2dc727ee0787d7e66e58a1f7fd8333aff", "max_forks_repo_licenses": ["Apache-2.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.693877551, "max_line_length": 57, "alphanum_fraction": 0.5813734713, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6199141097813194}}
{"text": "/* test_binomial_distribution.cpp\r\n *\r\n * Copyright Steven Watanabe 2010\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id: test_binomial_distribution.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $\r\n *\r\n */\r\n\r\n#include <boost/random/binomial_distribution.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::binomial_distribution<>\r\n#define BOOST_RANDOM_ARG1 t\r\n#define BOOST_RANDOM_ARG2 p\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1\r\n#define BOOST_RANDOM_ARG2_DEFAULT 0.5\r\n#define BOOST_RANDOM_ARG1_VALUE 10\r\n#define BOOST_RANDOM_ARG2_VALUE 0.25\r\n\r\n#define BOOST_RANDOM_DIST0_MIN 0\r\n#define BOOST_RANDOM_DIST0_MAX 1\r\n#define BOOST_RANDOM_DIST1_MIN 0\r\n#define BOOST_RANDOM_DIST1_MAX 10\r\n#define BOOST_RANDOM_DIST2_MIN 0\r\n#define BOOST_RANDOM_DIST2_MAX 10\r\n\r\n#define BOOST_RANDOM_TEST1_PARAMS\r\n#define BOOST_RANDOM_TEST1_MIN 0\r\n#define BOOST_RANDOM_TEST1_MAX 1\r\n\r\n#define BOOST_RANDOM_TEST2_PARAMS (10, 0.25)\r\n#define BOOST_RANDOM_TEST2_MIN 0\r\n#define BOOST_RANDOM_TEST2_MAX 10\r\n\r\n#include \"test_distribution.ipp\"\r\n", "meta": {"hexsha": "fc3a5ff075fa9916eb5533df9eeee60a6a229c5f", "size": 1134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/test_binomial_distribution.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/random/test/test_binomial_distribution.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/random/test/test_binomial_distribution.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 29.8421052632, "max_line_length": 84, "alphanum_fraction": 0.8007054674, "num_tokens": 292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6199141084835305}}
{"text": "#ifndef _UNIVERSAL_APPROXIMATOR_HPP\n#define _UNIVERSAL_APPROXIMATOR_HPP\n\n#include <armadillo>\n#include <vector>\n#include <math.h>\n\nusing namespace arma;\nusing namespace std;\n\nclass universal_approximator {\n    double sigma;\n    vector<long double> w;\n    vector<long double> G;\npublic:\n    universal_approximator(const vector<double> &x, const vector<double> &y,\n                           double lambda);\n\n    double gaussian(double xi, double xj);\n\n    double get_output(double x);\n\n    vector<double> test(const vector<double> &x);\n};\n\n\n\n\n\n\n\n\n\n#endif", "meta": {"hexsha": "954afde8f4370c2eacf7875e1256e26bf0919696", "size": 553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Universal_Aproximator/src/universal_approximator.hpp", "max_stars_repo_name": "jesuswr/RBF", "max_stars_repo_head_hexsha": "0d11d763ccc75616f7e08ed9822ac3968f2533fe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Universal_Aproximator/src/universal_approximator.hpp", "max_issues_repo_name": "jesuswr/RBF", "max_issues_repo_head_hexsha": "0d11d763ccc75616f7e08ed9822ac3968f2533fe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Universal_Aproximator/src/universal_approximator.hpp", "max_forks_repo_name": "jesuswr/RBF", "max_forks_repo_head_hexsha": "0d11d763ccc75616f7e08ed9822ac3968f2533fe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.2647058824, "max_line_length": 76, "alphanum_fraction": 0.6907775769, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936879, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6199141035148702}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include \"gtest/gtest.h\"\n#include \"interpolate.h\"\n#include \"VMD.h\"\n\nVMD_Frame recreate_bezier_parameter(VMD_Frame head, VMD_Frame tail)\n{\n  vector<VMD_Frame> fv = {head, tail};\n  fv = fill_bone_frame(fv, true);\n  optimize_bezier_parameter(tail, fv, head.number, tail.number);\n  return tail;\n}\n\nTEST(InterpolationTest, BezierCurveFitting) {\n  Eigen::Quaternionf q1(Eigen::AngleAxisf(3.14f/4, Eigen::Vector3f::UnitY()));\n  VMD_Frame head = VMD_Frame(\"center\", 10, Eigen::Vector3f(1, 2, 3), q1);\n  Eigen::Quaternionf q2(Eigen::AngleAxisf(3.14f/4, Eigen::Vector3f::UnitX()));\n  VMD_Frame tail = VMD_Frame(\"center\", 20, Eigen::Vector3f(2, -2, 2), q2);\n  VMD_Frame f;\n\n  tail.set_interpolation_x(10, 100, 110, 30);\n  f = recreate_bezier_parameter(head, tail);\n  for (int i = 0; i < 64; i += 4) {\n    EXPECT_NEAR(f.interpolation[i], tail.interpolation[i], 5) << \"i = \" << i;\n  }\n\n  tail.set_interpolation_r(20, 5, 90, 127);\n  f = recreate_bezier_parameter(head, tail);\n  for (int i = 0; i < 64; i += 4) {\n    EXPECT_NEAR(f.interpolation[i], tail.interpolation[i], 5) << \"i = \" << i;\n  }\n\n}\n", "meta": {"hexsha": "28b9093edf2903e1d70adc4ab4ee0a929d1a07a3", "size": 1186, "ext": "cc", "lang": "C++", "max_stars_repo_path": "UnitTest/InterpolationTest.cc", "max_stars_repo_name": "AotoKaburaki/Reborn", "max_stars_repo_head_hexsha": "5519e4eeca43c1df3e9bfc0d3d40c01542bb6bd5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-06-03T07:47:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T14:48:41.000Z", "max_issues_repo_path": "UnitTest/InterpolationTest.cc", "max_issues_repo_name": "AotoKaburaki/Reborn", "max_issues_repo_head_hexsha": "5519e4eeca43c1df3e9bfc0d3d40c01542bb6bd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UnitTest/InterpolationTest.cc", "max_forks_repo_name": "AotoKaburaki/Reborn", "max_forks_repo_head_hexsha": "5519e4eeca43c1df3e9bfc0d3d40c01542bb6bd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-31T23:56:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-31T23:56:24.000Z", "avg_line_length": 31.2105263158, "max_line_length": 78, "alphanum_fraction": 0.676222597, "num_tokens": 399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6199140942264436}}
{"text": "// Copyright 2019 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <trajectory_math/float_comparison.h>\n#include <trajectory_math/trajectory_algorithms.h>\n\n#include <Eigen/Geometry>\n\nnamespace bookbot {\ndouble TriangleArea(Eigen::Vector2d start_point, Eigen::Vector2d corner_point,\n                    Eigen::Vector2d end_point) {\n  const Eigen::Vector3d corner_to_start{start_point[0] - corner_point[0],\n                                        start_point[1] - corner_point[1], 0};\n  const Eigen::Vector3d corner_to_end{end_point[0] - corner_point[0],\n                                      end_point[1] - corner_point[1], 0};\n  return 0.5 *\n         std::abs(Eigen::Vector3d(corner_to_start.cross(corner_to_end))[2]);\n}\n\ndouble ApproximateCurvatureMagnitude(Eigen::Vector2d start_point,\n                                     Eigen::Vector2d corner_point,\n                                     Eigen::Vector2d end_point) {\n  const double area = TriangleArea(start_point, corner_point, end_point);\n  const double start_to_corner =\n      Eigen::Vector2d(start_point - corner_point).squaredNorm();\n  const double start_to_end =\n      Eigen::Vector2d(start_point - end_point).squaredNorm();\n  const double corner_to_end =\n      Eigen::Vector2d(corner_point - end_point).squaredNorm();\n  const double normalization = start_to_corner * start_to_end * corner_to_end;\n  if (ApproxZero(normalization)) {\n    return 0.;\n  }\n  return 4 * area / std::sqrt(normalization);\n}\n\n}  // namespace bookbot\n", "meta": {"hexsha": "a046c1ef5b0d0035b110d94949441644ab6dfc67", "size": 2016, "ext": "cc", "lang": "C++", "max_stars_repo_path": "trajectory_math/src/point_algorithms.cc", "max_stars_repo_name": "google/bookbot-navigation", "max_stars_repo_head_hexsha": "5e5a17a022fe2d7137e7047e913020a3b7a0ff02", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-05-17T15:42:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T02:12:38.000Z", "max_issues_repo_path": "trajectory_math/src/point_algorithms.cc", "max_issues_repo_name": "google/bookbot-navigation", "max_issues_repo_head_hexsha": "5e5a17a022fe2d7137e7047e913020a3b7a0ff02", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "trajectory_math/src/point_algorithms.cc", "max_forks_repo_name": "google/bookbot-navigation", "max_forks_repo_head_hexsha": "5e5a17a022fe2d7137e7047e913020a3b7a0ff02", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-05-03T16:24:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-10T13:07:43.000Z", "avg_line_length": 41.1428571429, "max_line_length": 78, "alphanum_fraction": 0.6879960317, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6199140935775492}}
{"text": "#include \"LSCM.h\"\n#include <assert.h>\n#include <math.h>\n#include <float.h>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <sstream>\n#include <Eigen/IterativeLinearSolvers>\n\nusing namespace MeshLib;\n\ntypedef Eigen::SparseMatrix<double> SpMat;\ntypedef Eigen::VectorXd VectorXd;\n\nLSCM::LSCM(Mesh * mesh) {\n\tm_mesh = mesh;\n}\n\nLSCM::~LSCM(){}\n\nvoid LSCM::set_coefficients() {\n\tfor (MeshEdgeIterator eiter(m_mesh); !eiter.end(); ++eiter) {\n\t\tEdge * e = *eiter;\n\t\te_l(e) = m_mesh->edge_length(e);\n\t}\n\n\tfor (MeshFaceIterator fiter(m_mesh); !fiter.end(); ++fiter) {\n\t\tPoint  p[3];\n\t\tFace *f = *fiter;\n\n\t\tdouble l[3];\n\t\tHalfEdge * he = f->halfedge();\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tEdge * e = he->edge();\n\t\t\tl[j] = e_l(e);\n\t\t\the = he->he_next();\n\t\t}\n\n\t\tdouble a = acos((l[0]*l[0] + l[2]*l[2] - l[1]*l[1]) / (2*l[0]*l[2]));\n\n\t\tp[0] = Point(0, 0, 0);\n\t\tp[1] = Point(l[0], 0, 0);\n\t\tp[2] = Point(l[2]*cos(a), l[2]*sin(a), 0);\n\n\t\tPoint n = (p[1]-p[0]) ^ (p[2]-p[0]);\n\t\tdouble area = n.norm() / 2.0;\n\t\tn /= area;\n\n\t\the = f->halfedge();\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tPoint s = (n ^ (p[(j + 1) % 3] - p[j])) / sqrt(area);\n\t\t\tc_s(he) = s;\n\t\t\the = he->he_next();\n\t\t}\n\t}\n}\n\nvoid LSCM::project() {\n\tset_coefficients();\n\n\tstd::vector<Vertex*> vertices;\n    std::vector<Face*> faces;\n\n\tfor (MeshVertexIterator viter(m_mesh); !viter.end(); ++viter){\n\t\tVertex * v = *viter;\n\t\tif (v->string().substr(0,3) != \"fix\") {\n\t\t\tvertices.push_back(v);\n\t\t}\n\t\telse {\n\t\t\tm_fix_vertices.push_back(v);\n\t\t}\n\t}\n\tassert(m_fix_vertices.size()>=2);\n\n\tfor (int k = 0; k < (int)vertices.size(); k++ ){\n\t\tv_idx(vertices[k]) = k;\n\t}\n\tfor (int k = 0; k < (int)m_fix_vertices.size(); k++) {\n\t\tv_idx(m_fix_vertices[k]) = k;\n\t\tVertex *v = m_fix_vertices[k];\n\t\tstd::string tmp;\n\t\tdouble uv0, uv1;\n\t\tstd::stringstream(v->string()) >> tmp >> uv0 >> uv1;\n\t\tv_uv(v) = Point2(uv0, uv1);\n\t}\n\n\tint fn = m_mesh->numFaces();\n\tint\tvfn = m_fix_vertices.size();\n\tint\tvn = m_mesh->numVertices() - vfn;\n\t\n\ttypedef Eigen::Triplet<double> T;\n\tstd::vector<T> tripletList1;\n\tstd::vector<T> tripletList2;\n\ttripletList1.reserve(fn);\n\ttripletList2.reserve(fn);\n\tVectorXd b(vfn * 2);\n\n\tint fid = 0;\n\tfor (MeshFaceIterator fiter(m_mesh); !fiter.end(); ++fiter, ++fid) {\n\t\tFace *f = *fiter;\n\t\tHalfEdge *he = f->halfedge();\n\n\t\tfor (int j = 0; j < 3; j++) {\n\t\t\tPoint s = c_s(he);\n\n\t\t\tVertex * v = he->he_next()->target();\n\t\t\tint vid = v_idx(v);\n\n\t\t\tif (v->string().substr(0,3) != \"fix\") {\n\t\t\t\ttripletList1.push_back(T(fid,vid,s[0]));\n\t\t\t\ttripletList1.push_back(T(fn + fid, vn + vid, s[0]));\n\t\t\t\ttripletList1.push_back(T(fid, vn + vid, -s[1]));\n\t\t\t\ttripletList1.push_back(T(fn + fid, vid, s[1]));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tPoint2 uv = v_uv(v);\n\n\t\t\t\ttripletList2.push_back(T(fid, vid, s[0]));\n\t\t\t\ttripletList2.push_back(T(fn + fid, vfn + vid, s[0]));\n\t\t\t\ttripletList2.push_back(T(fid, vfn + vid, -s[1]));\n\t\t\t\ttripletList2.push_back(T(fn + fid, vid, s[1]));\n\n\t\t\t\tb[vid] = uv[0];\n\t\t\t\tb[vfn + vid] = uv[1];\n\t\t\t}\n\t\t\the = he->he_next();\n\t\t}\n\t}\n\tSpMat A(2*fn, 2*vn);\n\tSpMat B(2*fn, 2*vfn);\n\n\tA.setFromTriplets(tripletList1.begin(), tripletList1.end());\n\tB.setFromTriplets(tripletList2.begin(), tripletList2.end());\n\n\tVectorXd r, x;\n\tr = B * b;\n\tr = r * -1;\n\n    // Solve the linear system Ax = r\n\tEigen::LeastSquaresConjugateGradient<Eigen::SparseMatrix<double>> lscg;\n\tlscg.compute(A);\n\tx = lscg.solve(r);\n\n\tfor (int i = 0; i < vn; i++) {\n\t\tVertex * v = vertices[i];\n\t\tv_uv(v) = Point2(x[i], x[i + vn]);\n\t}\n\tfor (MeshVertexIterator viter(m_mesh); !viter.end(); viter++) {\n\t\tVertex * v = *viter;\n\t\tPoint2 p = v_uv(v);\n\t\tPoint p3(p[0], p[1], 0);\n\t\tv->point() = p3;\n\t}\n}\n", "meta": {"hexsha": "4e4396cb7d41aca94c10ad30dbfe3f2d13f86496", "size": 3588, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LSCM.cpp", "max_stars_repo_name": "JolleyLabCHOP/lscm", "max_stars_repo_head_hexsha": "f113dbee9fd4cfedeb4ea66a19df92dfbea2d6a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2018-09-13T09:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T02:06:53.000Z", "max_issues_repo_path": "src/LSCM.cpp", "max_issues_repo_name": "JolleyLabCHOP/lscm", "max_issues_repo_head_hexsha": "f113dbee9fd4cfedeb4ea66a19df92dfbea2d6a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-09-26T04:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T18:25:14.000Z", "max_forks_repo_path": "src/LSCM.cpp", "max_forks_repo_name": "JolleyLabCHOP/lscm", "max_forks_repo_head_hexsha": "f113dbee9fd4cfedeb4ea66a19df92dfbea2d6a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-08-19T08:33:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T01:23:48.000Z", "avg_line_length": 23.1483870968, "max_line_length": 72, "alphanum_fraction": 0.5791527313, "num_tokens": 1343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.6198806717585426}}
{"text": "#include \"LonLatDistance.h\"\n\n#include <boost/math/constants/constants.hpp>\n#include <macgyver/Exception.h>\n\nnamespace SmartMet\n{\nnamespace Plugin\n{\nnamespace TimeSeries\n{\n/// @brief Earth's quatratic mean radius for WGS-84\nstatic const double EARTH_RADIUS_IN_METERS = 6372797.560856;\n\ndouble deg_to_rad(const double& degrees)\n{\n  try\n  {\n    return degrees * (boost::math::constants::pi<double>() / 180.0);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP, \"Operation failed!\", nullptr);\n  }\n}\n\ndouble rad_to_deg(const double& radians)\n{\n  try\n  {\n    return radians * (180.0 / boost::math::constants::pi<double>());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP, \"Operation failed!\", nullptr);\n  }\n}\n\n/**\n * Returns the (initial) bearing from this point to the supplied point, in degrees\n *   see http://williams.best.vwh.net/avform.htm#Crs\n *\n * @param   {LatLon} point: Latitude/longitude of destination point\n * @returns {Number} Initial bearing in degrees from North\n */\ndouble initial_bearing(const std::pair<double, double>& from, const std::pair<double, double>& to)\n{\n  try\n  {\n    double lat1 = deg_to_rad(from.second);\n    double lat2 = deg_to_rad(to.second);\n    double dLon = deg_to_rad(to.first - from.first);\n\n    double y = sin(dLon) * cos(lat2);\n    double x = (cos(lat1) * sin(lat2)) - (sin(lat1) * cos(lat2) * cos(dLon));\n    double brng = atan2(y, x);\n\n    return fmod((rad_to_deg(brng) + 360.0), 360.0);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP, \"Operation failed!\", nullptr);\n  }\n}\n\n/**\n * Returns final bearing arriving at supplied destination point from this point; the final bearing\n * will differ from the initial bearing by varying degrees according to distance and latitude\n *\n * @param   {LatLon} point: Latitude/longitude of destination point\n * @returns {Number} Final bearing in degrees from North\n */\ndouble final_bearing(const std::pair<double, double>& from, const std::pair<double, double>& to)\n{\n  try\n  {\n    // get initial bearing from supplied point back to this point...\n    double lat1 = deg_to_rad(to.second);\n    double lat2 = deg_to_rad(from.second);\n    double dLon = deg_to_rad(from.first - to.first);\n\n    double y = sin(dLon) * cos(lat2);\n    double x = (cos(lat1) * sin(lat2)) - (sin(lat1) * cos(lat2) * cos(dLon));\n    double brng = atan2(y, x);\n    // ... & reverse it by adding 180\u00b0\n    return fmod((rad_to_deg(brng) + 180.0), 360.0);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP, \"Operation failed!\", nullptr);\n  }\n}\n\n/**\n * Returns the midpoint between this point and the supplied point.\n *   see http://mathforum.org/library/drmath/view/51822.html for derivation\n *\n * @param   {LatLon} point: Latitude/longitude of destination point\n * @returns {LatLon} Midpoint between this point and the supplied point\n */\nstd::pair<double, double> midpoint(const std::pair<double, double>& from,\n                                   const std::pair<double, double>& to)\n{\n  try\n  {\n    double lat1 = deg_to_rad(from.second);\n    double lon1 = deg_to_rad(from.first);\n    double lat2 = deg_to_rad(to.second);\n    double dLon = deg_to_rad(to.first - from.first);\n\n    double Bx = cos(lat2) * cos(dLon);\n    double By = cos(lat2) * sin(dLon);\n\n    double lat3 = atan2(sin(lat1) + sin(lat2), sqrt((cos(lat1) + Bx) * (cos(lat1) + Bx) + By * By));\n    double lon3 = lon1 + atan2(By, cos(lat1) + Bx);\n    double pi(boost::math::constants::pi<double>());\n    lon3 = fmod(lon3 + (3 * pi), 2 * pi) - pi;  // normalise to -180..+180\u00ba\n\n    return std::pair<double, double>(rad_to_deg(lon3), rad_to_deg(lat3));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP, \"Operation failed!\", nullptr);\n  }\n}\n\n/**\n * Returns the destination point from this point having travelled the given distance (in km) on the\n * given initial bearing (bearing may vary before destination is reached)\n *\n *   see http://williams.best.vwh.net/avform.htm#LL\n *\n * @param   {Number} brng: Initial bearing in degrees\n * @param   {Number} dist: Distance in km\n * @returns {LatLon} Destination point\n */\nstd::pair<double, double> destination_point(const std::pair<double, double>& from,\n                                            const std::pair<double, double>& to,\n                                            const double& distance)\n{\n  try\n  {\n    double brng(initial_bearing(from, to));\n\n    double dist = distance /\n                  (EARTH_RADIUS_IN_METERS / 1000.0);  // convert dist to angular distance in radians\n    brng = deg_to_rad(brng);\n    double lat1 = deg_to_rad(from.second);\n    double lon1 = deg_to_rad(from.first);\n\n    double lat2 = asin(sin(lat1) * cos(dist) + cos(lat1) * sin(dist) * cos(brng));\n    double lon2 =\n        lon1 + atan2(sin(brng) * sin(dist) * cos(lat1), cos(dist) - sin(lat1) * sin(lat2));\n    double pi(boost::math::constants::pi<double>());\n    lon2 = fmod(lon2 + 3 * pi, 2 * pi) - pi;  // normalise to -180..+180\u00ba\n\n    return {rad_to_deg(lon2), rad_to_deg(lat2)};\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP, \"Operation failed!\", nullptr);\n  }\n}\n\n/** @brief Computes the arc, in radian, between two WGS-84 positions.\n *\n * The result is equal to <code>Distance(from,to)/EARTH_RADIUS_IN_METERS</code>\n *    <code>= 2*asin(sqrt(h(d/EARTH_RADIUS_IN_METERS )))</code>\n *\n * where:<ul>\n *    <li>d is the distance in meters between 'from' and 'to' positions.</li>\n *    <li>h is the haversine function: <code>h(x)=sin\u00b2(x/2)</code></li>\n * </ul>\n *\n * The haversine formula gives:\n *    <code>h(d/R) = h(from.lat-to.lat)+h(from.lon-to.lon)+cos(from.lat)*cos(to.lat)</code>\n *\n * @sa http://en.wikipedia.org/wiki/Law_of_haversines\n */\ndouble arc_in_radians(const std::pair<double, double>& from, const std::pair<double, double>& to)\n{\n  try\n  {\n    double latitudeArc = deg_to_rad(from.second - to.second);\n    double longitudeArc = deg_to_rad(from.first - to.first);\n    double latitudeH = sin(latitudeArc * 0.5);\n    latitudeH *= latitudeH;\n    double lontitudeH = sin(longitudeArc * 0.5);\n    lontitudeH *= lontitudeH;\n    double tmp = cos(deg_to_rad(from.second)) * cos(deg_to_rad(to.second));\n    return 2.0 * asin(sqrt(latitudeH + tmp * lontitudeH));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP, \"Operation failed!\", nullptr);\n  }\n}\n\n/** @brief Computes the distance, in meters, between two WGS-84 positions.\n *\n * The result is equal to <code>EARTH_RADIUS_IN_METERS*ArcInRadians(from,to)</code>\n *\n * @sa ArcInRadians\n */\ndouble distance_in_meters(const std::pair<double, double>& from,\n                          const std::pair<double, double>& to)\n{\n  try\n  {\n    return EARTH_RADIUS_IN_METERS * arc_in_radians(from, to);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP, \"Operation failed!\", nullptr);\n  }\n}\n\ndouble distance_in_kilometers(const std::pair<double, double>& from,\n                              const std::pair<double, double>& to)\n{\n  try\n  {\n    return (distance_in_meters(from, to) / 1000.0);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP, \"Operation failed!\", nullptr);\n  }\n}\n\n}  // namespace TimeSeries\n}  // namespace Plugin\n}  // namespace SmartMet\n", "meta": {"hexsha": "caa7da014af4491db388b5322b20236846009c3e", "size": 7061, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "timeseries/LonLatDistance.cpp", "max_stars_repo_name": "fmidev/smartmet-plugin-timeseries", "max_stars_repo_head_hexsha": "11210635f18cb774e906a0ac0431152ec0c80cb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "timeseries/LonLatDistance.cpp", "max_issues_repo_name": "fmidev/smartmet-plugin-timeseries", "max_issues_repo_head_hexsha": "11210635f18cb774e906a0ac0431152ec0c80cb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T20:30:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-20T08:14:08.000Z", "max_forks_repo_path": "timeseries/LonLatDistance.cpp", "max_forks_repo_name": "fmidev/smartmet-plugin-timeseries", "max_forks_repo_head_hexsha": "11210635f18cb774e906a0ac0431152ec0c80cb2", "max_forks_repo_licenses": ["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.1752136752, "max_line_length": 100, "alphanum_fraction": 0.6414105651, "num_tokens": 1972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6197687501365189}}
{"text": "/**\n * @file radical_main.cpp\n * @author Nishant Mehta\n *\n * Test for RADICAL.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/radical/radical.hpp>\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nBOOST_AUTO_TEST_SUITE(RadicalTest);\n\nusing namespace mlpack;\nusing namespace mlpack::radical;\nusing namespace std;\nusing namespace arma;\n\nBOOST_AUTO_TEST_CASE(Radical_Test_Radical3D)\n{\n  mat matX;\n  data::Load(\"data_3d_mixed.txt\", matX);\n\n  Radical rad(0.175, 5, 100, matX.n_rows - 1);\n\n  mat matY;\n  mat matW;\n  rad.DoRadical(matX, matY, matW);\n\n  mat matYT = trans(matY);\n  double valEst = 0;\n\n  for (uword i = 0; i < matYT.n_cols; i++)\n  {\n    vec y = vec(matYT.col(i));\n    valEst += rad.Vasicek(y);\n  }\n\n  mat matS;\n  data::Load(\"data_3d_ind.txt\", matS);\n  rad.DoRadical(matS, matY, matW);\n\n  matYT = trans(matY);\n  double valBest = 0;\n\n  for (uword i = 0; i < matYT.n_cols; i++)\n  {\n    vec y = vec(matYT.col(i));\n    valBest += rad.Vasicek(y);\n  }\n\n  BOOST_REQUIRE_CLOSE(valBest, valEst, 0.25);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b8c14348683fa65fabeb733f2dd6f9647946ec83", "size": 1342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/radical_test.cpp", "max_stars_repo_name": "NaxAlpha/mlpack-build", "max_stars_repo_head_hexsha": "1f0c1454d4b35eb97ff115669919c205cee5bd1c", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-22T18:12:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T10:39:58.000Z", "max_issues_repo_path": "src/mlpack/tests/radical_test.cpp", "max_issues_repo_name": "kosmaz/Mlpack", "max_issues_repo_head_hexsha": "62100ddca45880a57e7abb0432df72d285e5728b", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/radical_test.cpp", "max_forks_repo_name": "kosmaz/Mlpack", "max_forks_repo_head_hexsha": "62100ddca45880a57e7abb0432df72d285e5728b", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.0, "max_line_length": 78, "alphanum_fraction": 0.6833084948, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6197374995379638}}
{"text": "//\n// Created by Alex Beccaro on 18/12/17.\n//\n\n#include \"problem29.hpp\"\n#include <boost/unordered_set.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <generics.hpp>\n\nusing boost::unordered_set;\nusing boost::multiprecision::uint1024_t;\nusing generics::int_pow;\n\nnamespace problems {\n    uint32_t problem29::solve(uint32_t max_base, uint32_t max_exp) {\n        unordered_set<uint1024_t> powers;\n\n        for (uint32_t a = 2; a <= max_base; a++)\n            for (uint32_t b = 2; b <= max_exp; b++)\n                powers.insert(int_pow<uint1024_t>(a, b));\n\n        return (uint32_t) powers.size();\n    }\n}", "meta": {"hexsha": "5051073cb96874d9f7b9a4fef1a7204b9e96123f", "size": 612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/problems/1-50/29/problem29.cpp", "max_stars_repo_name": "abeccaro/project-euler", "max_stars_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:17:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:17:15.000Z", "max_issues_repo_path": "src/problems/1-50/29/problem29.cpp", "max_issues_repo_name": "abeccaro/project-euler", "max_issues_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problems/1-50/29/problem29.cpp", "max_forks_repo_name": "abeccaro/project-euler", "max_forks_repo_head_hexsha": "c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5, "max_line_length": 68, "alphanum_fraction": 0.6617647059, "num_tokens": 167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6197374880665388}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2014 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Points_3D_off_io.h>\n\n#include <boost/variant.hpp>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Alpha_shape_3.h>\n#include <CGAL/Alpha_shape_vertex_base_3.h>\n#include <CGAL/Alpha_shape_cell_base_3.h>\n#include <CGAL/iterator.h>\n\n#include <fstream>\n#include <cmath>\n#include <string>\n#include <tuple>  // for tuple<>\n#include <map>\n#include <utility>  // for pair<>\n#include <list>\n#include <vector>\n\n// Alpha_shape_3 templates type definitions\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef CGAL::Alpha_shape_vertex_base_3<Kernel> Vb;\ntypedef CGAL::Alpha_shape_cell_base_3<Kernel> Fb;\ntypedef CGAL::Triangulation_data_structure_3<Vb, Fb> Tds;\ntypedef CGAL::Delaunay_triangulation_3<Kernel, Tds> Triangulation_3;\ntypedef CGAL::Alpha_shape_3<Triangulation_3> Alpha_shape_3;\n\n// From file type definition\ntypedef Kernel::Point_3 Point;\n\n// filtration with alpha values needed type definition\ntypedef Alpha_shape_3::FT Alpha_value_type;\ntypedef CGAL::Object Object;\ntypedef CGAL::Dispatch_output_iterator<\nCGAL::cpp11::tuple<Object, Alpha_value_type>,\nCGAL::cpp11::tuple<std::back_insert_iterator< std::vector<Object> >,\n    std::back_insert_iterator< std::vector<Alpha_value_type> > > > Dispatch;\ntypedef Alpha_shape_3::Cell_handle Cell_handle;\ntypedef Alpha_shape_3::Facet Facet;\ntypedef Alpha_shape_3::Edge Edge;\ntypedef std::list<Alpha_shape_3::Vertex_handle> Vertex_list;\n\n// gudhi type definition\ntypedef Gudhi::Simplex_tree<> Simplex_tree;\ntypedef Simplex_tree::Vertex_handle Simplex_tree_vertex;\ntypedef std::map<Alpha_shape_3::Vertex_handle, Simplex_tree_vertex > Alpha_shape_simplex_tree_map;\ntypedef std::pair<Alpha_shape_3::Vertex_handle, Simplex_tree_vertex> Alpha_shape_simplex_tree_pair;\ntypedef std::vector< Simplex_tree_vertex > Simplex_tree_vector_vertex;\n\nVertex_list from(const Cell_handle& ch) {\n  Vertex_list the_list;\n  for (auto i = 0; i < 4; i++) {\n#ifdef DEBUG_TRACES\n    std::cout << \"from cell[\" << i << \"]=\" << ch->vertex(i)->point() << std::endl;\n#endif  // DEBUG_TRACES\n    the_list.push_back(ch->vertex(i));\n  }\n  return the_list;\n}\n\nVertex_list from(const Facet& fct) {\n  Vertex_list the_list;\n  for (auto i = 0; i < 4; i++) {\n    if (fct.second != i) {\n#ifdef DEBUG_TRACES\n      std::cout << \"from facet=[\" << i << \"]\" << fct.first->vertex(i)->point() << std::endl;\n#endif  // DEBUG_TRACES\n      the_list.push_back(fct.first->vertex(i));\n    }\n  }\n  return the_list;\n}\n\nVertex_list from(const Edge& edg) {\n  Vertex_list the_list;\n  for (auto i = 0; i < 4; i++) {\n    if ((edg.second == i) || (edg.third == i)) {\n#ifdef DEBUG_TRACES\n      std::cout << \"from edge[\" << i << \"]=\" << edg.first->vertex(i)->point() << std::endl;\n#endif  // DEBUG_TRACES\n      the_list.push_back(edg.first->vertex(i));\n    }\n  }\n  return the_list;\n}\n\nVertex_list from(const Alpha_shape_3::Vertex_handle& vh) {\n  Vertex_list the_list;\n#ifdef DEBUG_TRACES\n  std::cout << \"from vertex=\" << vh->point() << std::endl;\n#endif  // DEBUG_TRACES\n  the_list.push_back(vh);\n  return the_list;\n}\n\nint main(int argc, char * const argv[]) {\n  // program args management\n  if (argc != 2) {\n    std::cerr << \"Usage: \" << argv[0]\n        << \" path_to_off_file \\n\";\n    return 0;\n  }\n\n  // Read points from file\n  std::string offInputFile(argv[1]);\n  // Read the OFF file (input file name given as parameter) and triangulate points\n  Gudhi::Points_3D_off_reader<Point> off_reader(offInputFile);\n  // Check the read operation was correct\n  if (!off_reader.is_valid()) {\n    std::cerr << \"Unable to read file \" << argv[1] << std::endl;\n    return 0;\n  }\n  // Retrieve the triangulation\n  std::vector<Point> lp = off_reader.get_point_cloud();\n\n  // alpha shape construction from points. CGAL has a strange behavior in REGULARIZED mode.\n  Alpha_shape_3 as(lp.begin(), lp.end(), 0, Alpha_shape_3::GENERAL);\n#ifdef DEBUG_TRACES\n  std::cout << \"Alpha shape computed in GENERAL mode\" << std::endl;\n#endif  // DEBUG_TRACES\n\n  // filtration with alpha values from alpha shape\n  std::vector<Object> the_objects;\n  std::vector<Alpha_value_type> the_alpha_values;\n\n  Dispatch disp = CGAL::dispatch_output<Object, Alpha_value_type>(std::back_inserter(the_objects),\n      std::back_inserter(the_alpha_values));\n\n  as.filtration_with_alpha_values(disp);\n#ifdef DEBUG_TRACES\n  std::cout << \"filtration_with_alpha_values returns : \" << the_objects.size() << \" objects\" << std::endl;\n#endif  // DEBUG_TRACES\n\n  Alpha_shape_3::size_type count_vertices = 0;\n  Alpha_shape_3::size_type count_edges = 0;\n  Alpha_shape_3::size_type count_facets = 0;\n  Alpha_shape_3::size_type count_cells = 0;\n\n  // Loop on objects vector\n  Vertex_list vertex_list;\n  Simplex_tree simplex_tree;\n  Alpha_shape_simplex_tree_map map_cgal_simplex_tree;\n  std::vector<Alpha_value_type>::iterator the_alpha_value_iterator = the_alpha_values.begin();\n  for (auto object_iterator : the_objects) {\n    // Retrieve Alpha shape vertex list from object\n    if (const Cell_handle * cell = CGAL::object_cast<Cell_handle>(&object_iterator)) {\n      vertex_list = from(*cell);\n      count_cells++;\n    } else if (const Facet * facet = CGAL::object_cast<Facet>(&object_iterator)) {\n      vertex_list = from(*facet);\n      count_facets++;\n    } else if (const Edge * edge = CGAL::object_cast<Edge>(&object_iterator)) {\n      vertex_list = from(*edge);\n      count_edges++;\n    } else if (const Alpha_shape_3::Vertex_handle * vertex =\n              CGAL::object_cast<Alpha_shape_3::Vertex_handle>(&object_iterator)) {\n      count_vertices++;\n      vertex_list = from(*vertex);\n    }\n    // Construction of the vector of simplex_tree vertex from list of alpha_shapes vertex\n    Simplex_tree_vector_vertex the_simplex_tree;\n    for (auto the_alpha_shape_vertex : vertex_list) {\n      Alpha_shape_simplex_tree_map::iterator the_map_iterator = map_cgal_simplex_tree.find(the_alpha_shape_vertex);\n      if (the_map_iterator == map_cgal_simplex_tree.end()) {\n        // alpha shape not found\n        Simplex_tree_vertex vertex = map_cgal_simplex_tree.size();\n#ifdef DEBUG_TRACES\n        std::cout << \"vertex [\" << the_alpha_shape_vertex->point() << \"] not found - insert_simplex \" << vertex << \"\\n\";\n#endif  // DEBUG_TRACES\n        the_simplex_tree.push_back(vertex);\n        map_cgal_simplex_tree.insert(Alpha_shape_simplex_tree_pair(the_alpha_shape_vertex, vertex));\n      } else {\n        // alpha shape found\n        Simplex_tree_vertex vertex = the_map_iterator->second;\n#ifdef DEBUG_TRACES\n        std::cout << \"vertex [\" << the_alpha_shape_vertex->point() << \"] found in \" << vertex << std::endl;\n#endif  // DEBUG_TRACES\n        the_simplex_tree.push_back(vertex);\n      }\n    }\n    // Construction of the simplex_tree\n#ifdef DEBUG_TRACES\n    std::cout << \"filtration = \" << *the_alpha_value_iterator << std::endl;\n#endif  // DEBUG_TRACES\n    simplex_tree.insert_simplex(the_simplex_tree, std::sqrt(*the_alpha_value_iterator));\n    if (the_alpha_value_iterator != the_alpha_values.end())\n      ++the_alpha_value_iterator;\n    else\n      std::cerr << \"This shall not happen\" << std::endl;\n  }\n#ifdef DEBUG_TRACES\n  std::cout << \"vertices \\t\\t\" << count_vertices << std::endl;\n  std::cout << \"edges \\t\\t\" << count_edges << std::endl;\n  std::cout << \"facets \\t\\t\" << count_facets << std::endl;\n  std::cout << \"cells \\t\\t\" << count_cells << std::endl;\n\n\n  std::cout << \"Information of the Simplex Tree:\\n\";\n  std::cout << \"  Number of vertices = \" << simplex_tree.num_vertices() << \" \";\n  std::cout << \"  Number of simplices = \" << simplex_tree.num_simplices() << std::endl << std::endl;\n#endif  // DEBUG_TRACES\n\n#ifdef DEBUG_TRACES\n  std::cout << \"Iterator on vertices: \\n\";\n  for (auto vertex : simplex_tree.complex_vertex_range()) {\n    std::cout << vertex << \" \";\n  }\n#endif  // DEBUG_TRACES\n\n  std::cout << simplex_tree << std::endl;\n\n#ifdef DEBUG_TRACES\n  std::cout << std::endl << std::endl << \"Iterator on simplices:\\n\";\n  for (auto simplex : simplex_tree.complex_simplex_range()) {\n    std::cout << \"   \";\n    for (auto vertex : simplex_tree.simplex_vertex_range(simplex)) {\n      std::cout << vertex << \" \";\n    }\n    std::cout << std::endl;\n  }\n#endif  // DEBUG_TRACES\n#ifdef DEBUG_TRACES\n  std::cout << std::endl << std::endl << \"Iterator on Simplices in the filtration, with [filtration value]:\\n\";\n  for (auto f_simplex : simplex_tree.filtration_simplex_range()) {\n    std::cout << \"   \" << \"[\" << simplex_tree.filtration(f_simplex) << \"] \";\n    for (auto vertex : simplex_tree.simplex_vertex_range(f_simplex)) {\n      std::cout << vertex << \" \";\n    }\n    std::cout << std::endl;\n  }\n#endif  // DEBUG_TRACES\n#ifdef DEBUG_TRACES\n  std::cout << std::endl << std::endl << \"Iterator on Simplices in the filtration, and their boundary simplices:\\n\";\n  for (auto f_simplex : simplex_tree.filtration_simplex_range()) {\n    std::cout << \"   \" << \"[\" << simplex_tree.filtration(f_simplex) << \"] \";\n    for (auto vertex : simplex_tree.simplex_vertex_range(f_simplex)) {\n      std::cout << vertex << \" \";\n    }\n    std::cout << std::endl;\n\n    for (auto b_simplex : simplex_tree.boundary_simplex_range(f_simplex)) {\n      std::cout << \"      \" << \"[\" << simplex_tree.filtration(b_simplex) << \"] \";\n      for (auto vertex : simplex_tree.simplex_vertex_range(b_simplex)) {\n        std::cout << vertex << \" \";\n      }\n      std::cout << std::endl;\n    }\n  }\n#endif  // DEBUG_TRACES\n\n  return 0;\n}\n", "meta": {"hexsha": "e455c42674c8b4726652cc0cae7b255426326b8f", "size": 9834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Simplex_tree/example/example_alpha_shapes_3_simplex_tree_from_off_file.cpp", "max_stars_repo_name": "jmarino/gudhi-devel", "max_stars_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-27T03:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T21:14:14.000Z", "max_issues_repo_path": "src/Simplex_tree/example/example_alpha_shapes_3_simplex_tree_from_off_file.cpp", "max_issues_repo_name": "jmarino/gudhi-devel", "max_issues_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-25T16:03:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T07:36:21.000Z", "max_forks_repo_path": "src/Simplex_tree/example/example_alpha_shapes_3_simplex_tree_from_off_file.cpp", "max_forks_repo_name": "jmarino/gudhi-devel", "max_forks_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-06T12:36:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T14:53:13.000Z", "avg_line_length": 37.1094339623, "max_line_length": 120, "alphanum_fraction": 0.6899532235, "num_tokens": 2645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6197374841378638}}
{"text": "#include <MNIST.h>\n#include <Matrix.h>\n#include <Function.h>\n#include <Random.h>\n#include <Eigen/Dense>\n#include \"TwoLayerNet.h\"\n\nstatic constexpr std::size_t ITERS_NUM  = 10000;\nstatic constexpr std::size_t BATCH_SIZE = 100;\nstatic constexpr double LEARNING_RATE = 0.1;\n\nint main() {\n    MNIST mnistTrain;\n    if (mnistTrain.load(\"./../dataset/train-images-idx3-ubyte\", \"./../dataset/train-labels-idx1-ubyte\") != 0) {\n        std::fprintf(stderr, \"Failed to load MNIST training set.\\n\");\n        return -1;\n    }\n\n    MNIST mnistTest;\n    if (mnistTest.load(\"./../dataset/t10k-images-idx3-ubyte\", \"./../dataset/t10k-labels-idx1-ubyte\") != 0) {\n        std::fprintf(stderr, \"Failed to load MNIST test set.\\n\");\n        return -1;\n    }\n\n    const MatrixXd& XTrain = mnistTrain.getImages();\n    const VectorXi& tTrain = mnistTrain.getLabels();  \n    const MatrixXd& XTest = mnistTest.getImages();\n    const VectorXi& tTest = mnistTest.getLabels();  \n\n    const std::size_t iterPerEpoch = std::max(XTrain.rows() / BATCH_SIZE, 1ul);\n\n    TwoLayerNet network(784, 50, 10);\n    for (std::size_t i = 0; i < ITERS_NUM; ++i) {\n        const std::vector<std::size_t> batchIndex = choice(XTrain.rows(), BATCH_SIZE);\n\n        const MatrixXd XBatch = createMatrixXdBatch(XTrain, batchIndex);\n        const VectorXi tBatch = createVectorXiBatch(tTrain, batchIndex);\n\n        network.gradient(XBatch, tBatch);\n        network.update(LEARNING_RATE);\n\n        if (i % iterPerEpoch == 0) {\n            const double trainAcc = network.accuracy(XTrain, tTrain);\n            const double testAcc = network.accuracy(XTest, tTest);\n            std::printf(\"train acc, test acc | %lf, %lf\\n\", trainAcc, testAcc);\n        }\n    }   \n  \n    return 0;\n}\n", "meta": {"hexsha": "efb0092b7e89504f704fdb55c09b90588c65f2a9", "size": 1728, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch05/TrainNeuralNet.cpp", "max_stars_repo_name": "chgzm/deep-learning-from-scratch-cpp", "max_stars_repo_head_hexsha": "72d2ab03e548147e7e26d38f69d56da8a919ec56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch05/TrainNeuralNet.cpp", "max_issues_repo_name": "chgzm/deep-learning-from-scratch-cpp", "max_issues_repo_head_hexsha": "72d2ab03e548147e7e26d38f69d56da8a919ec56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch05/TrainNeuralNet.cpp", "max_forks_repo_name": "chgzm/deep-learning-from-scratch-cpp", "max_forks_repo_head_hexsha": "72d2ab03e548147e7e26d38f69d56da8a919ec56", "max_forks_repo_licenses": ["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.8823529412, "max_line_length": 111, "alphanum_fraction": 0.6412037037, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.619707205096928}}
{"text": "#pragma once\n\n#include <vector>\n\n#include <Eigen/Geometry>\n\nnamespace common_robotics_utilities\n{\nnamespace conversions\n{\nEigen::Quaterniond QuaternionFromRPY(const double R,\n                                     const double P,\n                                     const double Y);\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Quaterniond QuaternionFromUrdfRPY(const double R,\n                                         const double P,\n                                         const double Y);\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromRotationMatrix(\n    const Eigen::Matrix3d& rot_matrix);\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromQuaternion(const Eigen::Quaterniond& quat);\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromIsometry3d(const Eigen::Isometry3d& trans);\n\nEigen::Isometry3d TransformFromXYZRPY(const double x,\n                                      const double y,\n                                      const double z,\n                                      const double roll,\n                                      const double pitch,\n                                      const double yaw);\n\nEigen::Isometry3d TransformFromRPY(const Eigen::Vector3d& translation,\n                                   const Eigen::Vector3d& rotation);\n\nEigen::Isometry3d TransformFromRPY(const Eigen::VectorXd& components);\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfXYZRPY(const double x,\n                                          const double y,\n                                          const double z,\n                                          const double roll,\n                                          const double pitch,\n                                          const double yaw);\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfRPY(const Eigen::Vector3d& translation,\n                                       const Eigen::Vector3d& rotation);\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfRPY(const Eigen::VectorXd& components);\n\nEigen::VectorXd TransformToRPY(const Eigen::Isometry3d& transform);\n\nEigen::Vector3d StdVectorDoubleToEigenVector3d(\n    const std::vector<double>& vector);\n\nEigen::VectorXd StdVectorDoubleToEigenVectorXd(\n    const std::vector<double>& vector);\n\nstd::vector<double> EigenVector3dToStdVectorDouble(\n    const Eigen::Vector3d& point);\n\nstd::vector<double> EigenVectorXdToStdVectorDouble(\n    const Eigen::VectorXd& eigen_vector);\n\n// Takes <x, y, z, w> as is the ROS custom!\nEigen::Quaterniond StdVectorDoubleToEigenQuaterniond(\n    const std::vector<double>& vector);\n\n// Returns <x, y, z, w> as is the ROS custom!\nstd::vector<double> EigenQuaterniondToStdVectorDouble(\n    const Eigen::Quaterniond& quat);\n}  // namespace conversions\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "827d4d3b0a6d67d833072e3de79e12c82c793664", "size": 2841, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common_robotics_utilities/conversions.hpp", "max_stars_repo_name": "hidmic/common_robotics_utilities", "max_stars_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-10-15T19:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T01:35:16.000Z", "max_issues_repo_path": "include/common_robotics_utilities/conversions.hpp", "max_issues_repo_name": "hidmic/common_robotics_utilities", "max_issues_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T19:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-21T15:08:21.000Z", "max_forks_repo_path": "include/common_robotics_utilities/conversions.hpp", "max_forks_repo_name": "hidmic/common_robotics_utilities", "max_forks_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-10-17T21:12:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-18T03:53:47.000Z", "avg_line_length": 35.5125, "max_line_length": 74, "alphanum_fraction": 0.6085885252, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.6195533271561579}}
{"text": "#include <list>                // std::list\n#include <boost/format.hpp>    // only needed for printing\n#include <functional>          // std::ref\n#include <numeric>             // std::accumulate\n#include \"histogram.h\"\n#include \"vars.h\"\n\nstd::list<double> init_bins(int cell_no) {\n    //initalise histogram bins db\n    std::vector<int> b(cell_no + 1);\n    std::iota(b.begin(), b.end(), 0);\n\n    \n    double cell_L = cell_length;\n    std::vector<double> db(b.begin(), b.end());\n    std::transform(db.begin(), db.end(), db.begin(), [&cell_L](auto& c) {return c * cell_L;});\n\n    std::list<double> bins(db.begin(), db.end());\n\n    return bins;\n}\n\nstd::vector<double> rho_dist(std::vector<double> x) {\n\n    std::list<double> bins_list = init_bins(std::round(L / cell_length));\n    //auto bins = axis::regular<double, use_default, axis::option::none_t>{ axis::step(cell_length), 0, L };\n\n    auto bins = axis::variable<double, use_default, axis::option::none_t>(bins_list);\n\n    auto h_rho = make_histogram(bins); //initialise histogram of length L with bins of width cell_length\n\n    std::for_each(x.begin(), x.end(), std::ref(h_rho)); //populate histogram with x_evolved\n\n    std::vector<double> vec_h_rho(h_rho.axis().size());\n    \n    for (unsigned i = 0; i < vec_h_rho.size(); i++) {        \n        vec_h_rho[i] = h_rho.at(i); //convert hist to vector because C++ can't deal with autos :(\n    }\n    return vec_h_rho;\n}\n\n/*\n* Create averaged cell velocity distribution using density histogram\n*/\n\nstd::vector<double> cell_velocity_dist(std::vector<double> v, std::vector<double> x) {\n    \n    std::vector<double> vel_hist;\n    unsigned cum_bincount = 0;\n\n    // calculate all the mean cell velocities bar the last cell\n    for (unsigned i = 0; i != x.size(); i++) {\n        unsigned n_i = x.at(i);\n\n        if (n_i == 0) {\n            vel_hist.push_back(0);\n        }\n\n        else {\n            double splice_sum = std::accumulate(v.begin() + cum_bincount, v.begin() + (cum_bincount + n_i), 0.0);\n            double cell_vbar = splice_sum / n_i;\n            vel_hist.push_back(cell_vbar);\n            cum_bincount += n_i;\n        }\n\n    }\n    return vel_hist;\n\n}\n/*\n* Create histograms {h_rho,h_j} for a sample run\n*/\nstd::vector<std::vector<double>> rho_j_dist(std::vector<double> x, std::vector<double> v, std::list<double> bins_list) {\n\n    //std::list<double> bins_list = init_bins(std::round(L / cell_length));\n    //auto bins = axis::regular<double, use_default, axis::option::none_t>{ axis::step(cell_length), 0, L };\n    auto bins = axis::variable<>(bins_list);\n\n    auto h_rho = make_histogram(bins); //initialise histogram of length L with bins of width cell_length\n\n    std::for_each(x.begin(), x.end(), std::ref(h_rho)); //populate histogram with x_evolved\n\n    std::vector<double> vec_h_rho(h_rho.axis().size());\n\n    for (unsigned i = 0; i != vec_h_rho.size(); i++) {\n        vec_h_rho[i] = h_rho.at(i); //convert hist to vector because C++ can't deal with autos    }\n    }\n\n    std::vector<double> h_v = cell_velocity_dist(v, vec_h_rho);\n    \n    std::vector<double> h_j(h_v.size());\n\n    for (unsigned i = 0; i < h_v.size(); i++) {\n        h_j[i] = h_v[i] *h_rho.at(i);\n    }\n\n    return { vec_h_rho,h_v };\n}\n\n\n/*\n* compute averaged_rho_dist with a matrix of rod_positions (dim. no_samples * no_rods) as input\n*/\nauto averaged_rho_dist(std::vector<std::vector<double>> x_matrix) {\n\n    auto bins = axis::regular<double, use_default, axis::option::none_t>{ axis::step(cell_length), 0, L };\n\n    auto h_rho = make_histogram(bins); //initialise histogram of length L with bins of width cell_length\n\n    for (unsigned i = 0; i < x_matrix.size(); i++) {\n        for (unsigned i = 0; i < x_matrix[i].size(); i++) {\n            std::for_each(x_matrix[i].begin(), x_matrix[i].end(), std::ref(h_rho));\n        }\n    }\n\n    return h_rho / x_matrix.size();\n}\n\n\n", "meta": {"hexsha": "666e70b114f0fff8e0754ea75e2648af84f1de82", "size": 3867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "histogram.cpp", "max_stars_repo_name": "IraPelidae/Classical-Nonlinear-Response", "max_stars_repo_head_hexsha": "e18c3c287100ddd5a5d389ca6e895a8100df1cfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "histogram.cpp", "max_issues_repo_name": "IraPelidae/Classical-Nonlinear-Response", "max_issues_repo_head_hexsha": "e18c3c287100ddd5a5d389ca6e895a8100df1cfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "histogram.cpp", "max_forks_repo_name": "IraPelidae/Classical-Nonlinear-Response", "max_forks_repo_head_hexsha": "e18c3c287100ddd5a5d389ca6e895a8100df1cfc", "max_forks_repo_licenses": ["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.225, "max_line_length": 120, "alphanum_fraction": 0.6216705456, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6195198947874345}}
{"text": "#include <CGAL/Simple_cartesian.h>\n\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/boost/graph/graph_traits_Surface_mesh.h>\n\n#include <CGAL/subdivision_method_3.h>\n#include <CGAL/Timer.h>\n\n#include <boost/lexical_cast.hpp>\n\n#include <iostream>\n#include <fstream>\n\ntypedef CGAL::Simple_cartesian<double>          Kernel;\ntypedef CGAL::Surface_mesh<Kernel::Point_3>     PolygonMesh;\n\nusing namespace std;\nusing namespace CGAL;\nnamespace params = CGAL::parameters;\n\nint main(int argc, char **argv) {\n  if (argc > 4) {\n    cerr << \"Usage: Sqrt3_subdivision [d] [filename_in] [filename_out] \\n\";\n    cerr << \"         d -- the depth of the subdivision (default: 1) \\n\";\n    cerr << \"         filename_in -- the input mesh (.off) (default: data/quint_tris.off) \\n\";\n    cerr << \"         filename_out -- the output mesh (.off) (default: result.off)\" << endl;\n    return 1;\n  }\n\n  int d = (argc > 1) ? boost::lexical_cast<int>(argv[1]) : 2;\n  const std::string in_file = (argc > 2) ? argv[2] : CGAL::data_file_path(\"meshes/quint_tris.off\");\n  const char* out_file = (argc > 3) ? argv[3] : \"result.off\";\n\n  PolygonMesh pmesh;\n  std::ifstream in(in_file);\n  if(in.fail()) {\n    std::cerr << \"Could not open input file \" << in_file << std::endl;\n    return 1;\n  }\n  in >> pmesh;\n\n  Timer t;\n  t.start();\n  Subdivision_method_3::Sqrt3_subdivision(pmesh, params::number_of_iterations(d));\n  std::cerr << \"Done (\" << t.time() << \" s)\" << std::endl;\n\n  std::ofstream out(out_file);\n  out << pmesh;\n\n  return 0;\n}\n", "meta": {"hexsha": "231e0be4b7e27f89bd4f15a44ca9db70369aa2d2", "size": 1498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Subdivision_method_3/examples/Subdivision_method_3/Sqrt3_subdivision.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Subdivision_method_3/examples/Subdivision_method_3/Sqrt3_subdivision.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Subdivision_method_3/examples/Subdivision_method_3/Sqrt3_subdivision.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 28.8076923077, "max_line_length": 99, "alphanum_fraction": 0.6455273698, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6195198792050927}}
{"text": "//\n// Copyright (c) 2015-2019 CNRS INRIA\n// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n//\n\n#ifndef __spatial_explog_hpp__\n#define __spatial_explog_hpp__\n\n#include <Eigen/Geometry>\n\n#include \"pinocchio/fwd.hpp\"\n#include \"pinocchio/utils/static-if.hpp\"\n#include \"pinocchio/math/fwd.hpp\"\n#include \"pinocchio/math/sincos.hpp\"\n#include \"pinocchio/math/taylor-expansion.hpp\"\n#include \"pinocchio/spatial/motion.hpp\"\n#include \"pinocchio/spatial/skew.hpp\"\n#include \"pinocchio/spatial/se3.hpp\"\n\nnamespace pinocchio\n{\n  /// \\brief Exp: so3 -> SO3.\n  ///\n  /// Return the integral of the input angular velocity during time 1.\n  ///\n  /// \\param[in] v The angular velocity vector.\n  ///\n  /// \\return The rotational matrix associated to the integration of the angular velocity during time 1.\n  ///\n  template<typename Vector3Like>\n  typename Eigen::Matrix<typename Vector3Like::Scalar,3,3,PINOCCHIO_EIGEN_PLAIN_TYPE(Vector3Like)::Options>\n  exp3(const Eigen::MatrixBase<Vector3Like> & v)\n  {\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Vector3Like, v, 3, 1);\n\n    typedef typename Vector3Like::Scalar Scalar;\n    typedef typename PINOCCHIO_EIGEN_PLAIN_TYPE(Vector3Like) Vector3LikePlain;\n    typedef Eigen::Matrix<Scalar,3,3,Vector3LikePlain::Options> Matrix3;\n    \n    const Scalar t2 = v.squaredNorm();\n    \n    const Scalar t = math::sqrt(t2);\n    if(t > TaylorSeriesExpansion<Scalar>::template precision<3>())\n    {\n      Scalar ct,st; SINCOS(t,&st,&ct);\n      const Scalar alpha_vxvx = (1 - ct)/t2;\n      const Scalar alpha_vx = (st)/t;\n      Matrix3 res(alpha_vxvx * v * v.transpose());\n      res.coeffRef(0,1) -= alpha_vx * v[2]; res.coeffRef(1,0) += alpha_vx * v[2];\n      res.coeffRef(0,2) += alpha_vx * v[1]; res.coeffRef(2,0) -= alpha_vx * v[1];\n      res.coeffRef(1,2) -= alpha_vx * v[0]; res.coeffRef(2,1) += alpha_vx * v[0];\n      res.diagonal().array() += ct;\n      \n      return res;\n    }\n    else\n    {\n      const Scalar alpha_vxvx = Scalar(1)/Scalar(2) - t2/24;\n      const Scalar alpha_vx = Scalar(1) - t2/6;\n      Matrix3 res(alpha_vxvx * v * v.transpose());\n      res.coeffRef(0,1) -= alpha_vx * v[2]; res.coeffRef(1,0) += alpha_vx * v[2];\n      res.coeffRef(0,2) += alpha_vx * v[1]; res.coeffRef(2,0) -= alpha_vx * v[1];\n      res.coeffRef(1,2) -= alpha_vx * v[0]; res.coeffRef(2,1) += alpha_vx * v[0];\n      res.diagonal().array() += Scalar(1) - t2/2;\n      \n      return res;\n    }\n  }\n  \n  /// \\brief Same as \\ref log3\n  ///\n  /// \\param[in] R the rotation matrix.\n  /// \\param[out] theta the angle value.\n  ///\n  /// \\return The angular velocity vector associated to the rotation matrix.\n  ///\n  template<typename Matrix3Like>\n  Eigen::Matrix<typename Matrix3Like::Scalar,3,1,PINOCCHIO_EIGEN_PLAIN_TYPE(Matrix3Like)::Options>\n  log3(const Eigen::MatrixBase<Matrix3Like> & R,\n       typename Matrix3Like::Scalar & theta)\n  {\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE(Matrix3Like, R, 3, 3);\n\n    typedef typename Matrix3Like::Scalar Scalar;\n    typedef Eigen::Matrix<Scalar,3,1,PINOCCHIO_EIGEN_PLAIN_TYPE(Matrix3Like)::Options> Vector3;\n    \n    static const Scalar PI_value = PI<Scalar>();\n    \n    Vector3 res;\n    const Scalar tr = R.trace();\n    if(tr > Scalar(3))       theta = 0; // acos((3-1)/2)\n    else if(tr < Scalar(-1)) theta = PI_value; // acos((-1-1)/2)\n    else                     theta = math::acos((tr - Scalar(1))/Scalar(2));\n    assert(theta == theta && \"theta contains some NaN\"); // theta != NaN\n    \n    // From runs of hpp-constraints/tests/logarithm.cc: 1e-6 is too small.\n    if (theta < PI_value - 1e-2)\n    {\n      const Scalar t = ((theta > TaylorSeriesExpansion<Scalar>::template precision<3>())\n                        ? theta / sin(theta)\n                        : Scalar(1)) / Scalar(2);\n      res(0) = t * (R (2, 1) - R (1, 2));\n      res(1) = t * (R (0, 2) - R (2, 0));\n      res(2) = t * (R (1, 0) - R (0, 1));\n    }\n    else\n    {\n      // 1e-2: A low value is not required since the computation is\n      // using explicit formula. However, the precision of this method\n      // is the square root of the precision with the antisymmetric\n      // method (Nominal case).\n      const Scalar cphi = cos(theta - PI_value);\n      const Scalar beta  = theta*theta / ( Scalar(1) + cphi );\n      Vector3 tmp((R.diagonal().array() + cphi) * beta);\n      res(0) = (R (2, 1) > R (1, 2) ? Scalar(1) : Scalar(-1)) * (tmp[0] > Scalar(0) ? sqrt(tmp[0]) : Scalar(0));\n      res(1) = (R (0, 2) > R (2, 0) ? Scalar(1) : Scalar(-1)) * (tmp[1] > Scalar(0) ? sqrt(tmp[1]) : Scalar(0));\n      res(2) = (R (1, 0) > R (0, 1) ? Scalar(1) : Scalar(-1)) * (tmp[2] > Scalar(0) ? sqrt(tmp[2]) : Scalar(0));\n    }\n    \n    return res;\n  }\n  \n  /// \\brief Log: SO3 -> so3.\n  ///\n  /// Pseudo-inverse of log from \\f$ SO3 -> { v \\in so3, ||v|| \\le pi } \\f$.\n  ///\n  /// \\param[in] R The rotation matrix.\n  ///\n  /// \\return The angular velocity vector associated to the rotation matrix.\n  ///\n  template<typename Matrix3Like>\n  Eigen::Matrix<typename Matrix3Like::Scalar,3,1,PINOCCHIO_EIGEN_PLAIN_TYPE(Matrix3Like)::Options>\n  log3(const Eigen::MatrixBase<Matrix3Like> & R)\n  {\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Matrix3Like, R, 3, 3);\n\n    typename Matrix3Like::Scalar theta;\n    return log3(R.derived(),theta);\n  }\n\n  ///\n  /// \\brief Derivative of \\f$ \\exp{r} \\f$\n  /// \\f[\n  ///     \\frac{\\sin{||r||}}{||r||}                       I_3\n  ///   - \\frac{1-\\cos{||r||}}{||r||^2}                   \\left[ r \\right]_x\n  ///   + \\frac{1}{||n||^2} (1-\\frac{\\sin{||r||}}{||r||}) r r^T\n  /// \\f]\n  ///\n  template<typename Vector3Like, typename Matrix3Like>\n  void Jexp3(const Eigen::MatrixBase<Vector3Like> & r,\n             const Eigen::MatrixBase<Matrix3Like> & Jexp)\n  {\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Vector3Like, r   , 3, 1);\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Matrix3Like, Jexp, 3, 3);\n\n    Matrix3Like & Jout = PINOCCHIO_EIGEN_CONST_CAST(Matrix3Like,Jexp);\n    typedef typename Matrix3Like::Scalar Scalar;\n\n    Scalar n2 = r.squaredNorm(),a,b,c;\n    Scalar n = math::sqrt(n2);\n    \n    if (n < TaylorSeriesExpansion<Scalar>::template precision<3>())\n    {\n      a =   Scalar(1)           - n2/Scalar(6);\n      b = - Scalar(1)/Scalar(2) - n2/Scalar(24);\n      c =   Scalar(1)/Scalar(6) - n2/Scalar(120);\n    }\n    else\n    {\n      Scalar n_inv = Scalar(1)/n;\n      Scalar n2_inv = n_inv * n_inv;\n      Scalar cn,sn; SINCOS(n,&sn,&cn);\n\n      a = sn*n_inv;\n      b = - (1-cn)*n2_inv;\n      c = n2_inv * (1 - a);\n    }\n\n    Jout.diagonal().setConstant(a);\n\n    Jout(0,1) = -b*r[2]; Jout(1,0) = -Jout(0,1);\n    Jout(0,2) =  b*r[1]; Jout(2,0) = -Jout(0,2);\n    Jout(1,2) = -b*r[0]; Jout(2,1) = -Jout(1,2);\n\n    Jout.noalias() += c * r * r.transpose();\n  }\n\n  template<typename Scalar, typename Vector3Like, typename Matrix3Like>\n  void Jlog3(const Scalar & theta,\n             const Eigen::MatrixBase<Vector3Like> & log,\n             const Eigen::MatrixBase<Matrix3Like> & Jlog)\n  {\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Vector3Like,  log, 3, 1);\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Matrix3Like, Jlog, 3, 3);\n\n    Matrix3Like & Jout = PINOCCHIO_EIGEN_CONST_CAST(Matrix3Like,Jlog);\n\n    if (theta < TaylorSeriesExpansion<Scalar>::template precision<3>())\n    {\n      const Scalar alpha = Scalar(1)/Scalar(12) + theta*theta / Scalar(720);\n      Jout.noalias() = alpha * log * log.transpose();\n      \n      Jout.diagonal().array() += Scalar(0.5) * (2 - theta*theta / Scalar(6));\n      \n      // Jlog += r_{\\times}/2\n      addSkew(0.5 * log, Jlog);\n    }\n    else\n    {\n      // Jlog = alpha I\n      Scalar ct,st; SINCOS(theta,&st,&ct);\n      const Scalar st_1mct = st/(Scalar(1)-ct);\n      \n      const Scalar alpha = Scalar(1)/(theta*theta) - st_1mct/(Scalar(2)*theta);\n      Jout.noalias() = alpha * log * log.transpose();\n\n      Jout.diagonal().array() += Scalar(0.5) * (theta*st_1mct);\n\n      // Jlog += r_{\\times}/2\n      addSkew(0.5 * log, Jlog);\n    }\n  }\n\n  template<typename Matrix3Like1, typename Matrix3Like2>\n  void Jlog3(const Eigen::MatrixBase<Matrix3Like1> & R,\n             const Eigen::MatrixBase<Matrix3Like2> & Jlog)\n  {\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Matrix3Like1,    R, 3, 3);\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Matrix3Like2, Jlog, 3, 3);\n\n    typedef typename Matrix3Like1::Scalar Scalar;\n    typedef Eigen::Matrix<Scalar,3,1,PINOCCHIO_EIGEN_PLAIN_TYPE(Matrix3Like1)::Options> Vector3;\n\n    Scalar t;\n    Vector3 w(log3(R,t));\n    Jlog3(t,w,PINOCCHIO_EIGEN_CONST_CAST(Matrix3Like2,Jlog));\n  }\n  \n  ///\n  /// \\brief Exp: se3 -> SE3.\n  ///\n  /// Return the integral of the input twist during time 1.\n  ///\n  /// \\param[in] nu The input twist.\n  ///\n  /// \\return The rigid transformation associated to the integration of the twist during time 1.\n  ///\n  template<typename MotionDerived>\n  SE3Tpl<typename MotionDerived::Scalar,PINOCCHIO_EIGEN_PLAIN_TYPE(typename MotionDerived::Vector3)::Options>\n  exp6(const MotionDense<MotionDerived> & nu)\n  {\n    typedef typename MotionDerived::Scalar Scalar;\n    enum { Options = PINOCCHIO_EIGEN_PLAIN_TYPE(typename MotionDerived::Vector3)::Options };\n\n    typedef SE3Tpl<Scalar,Options> SE3;\n    \n    SE3 res;\n    typename SE3::LinearType & trans = res.translation();\n    typename SE3::AngularType & rot = res.rotation();\n    \n    const typename MotionDerived::ConstAngularType & w = nu.angular();\n    const typename MotionDerived::ConstLinearType & v = nu.linear();\n    \n    Scalar alpha_wxv, alpha_v, alpha_w, diagonal_term;\n    const Scalar t2 = w.squaredNorm();\n    const Scalar t = math::sqrt(t2);\n    Scalar ct,st; SINCOS(t,&st,&ct);\n    const Scalar inv_t2 = Scalar(1)/t2;\n    \n    alpha_wxv = internal::if_then_else(t<TaylorSeriesExpansion<Scalar>::template precision<3>(),\n                                       Scalar(1)/Scalar(2) - t2/24,\n                                       (Scalar(1) - ct)*inv_t2);\n    \n    alpha_v = internal::if_then_else(t<TaylorSeriesExpansion<Scalar>::template precision<3>(),\n                                     Scalar(1) - t2/6,\n                                     (st)/t);\n    \n    alpha_w = internal::if_then_else(t<TaylorSeriesExpansion<Scalar>::template precision<3>(),\n                                     (Scalar(1)/Scalar(6) - t2/120),\n                                     (Scalar(1) - alpha_v)*inv_t2);\n    \n    diagonal_term = internal::if_then_else(t<TaylorSeriesExpansion<Scalar>::template precision<3>(),\n                                           Scalar(1) - t2/2,\n                                           ct);\n    \n    // Linear\n    trans.noalias() = (alpha_v*v + (alpha_w*w.dot(v))*w + alpha_wxv*w.cross(v));\n    \n    // Rotational\n    rot.noalias() = alpha_wxv * w * w.transpose();\n    rot.coeffRef(0,1) -= alpha_v * w[2]; rot.coeffRef(1,0) += alpha_v * w[2];\n    rot.coeffRef(0,2) += alpha_v * w[1]; rot.coeffRef(2,0) -= alpha_v * w[1];\n    rot.coeffRef(1,2) -= alpha_v * w[0]; rot.coeffRef(2,1) += alpha_v * w[0];\n    rot.diagonal().array() += diagonal_term;\n    \n    return res;\n  }\n\n  /// \\brief Exp: se3 -> SE3.\n  ///\n  /// Return the integral of the input spatial velocity during time 1.\n  ///\n  /// \\param[in] v The twist represented by a vector.\n  ///\n  /// \\return The rigid transformation associated to the integration of the twist vector during time 1..\n  ///\n  template<typename Vector6Like>\n  SE3Tpl<typename Vector6Like::Scalar,PINOCCHIO_EIGEN_PLAIN_TYPE(Vector6Like)::Options>\n  exp6(const Eigen::MatrixBase<Vector6Like> & v)\n  {\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Vector6Like, v, 6, 1);\n\n    MotionRef<const Vector6Like> nu(v.derived());\n    return exp6(nu);\n  }\n\n  /// \\brief Log: SE3 -> se3.\n  ///\n  /// Pseudo-inverse of exp from SE3 -> { v,w \\in se3, ||w|| < 2pi }.\n  ///\n  /// \\param[in] M The rigid transformation.\n  ///\n  /// \\return The twist associated to the rigid transformation during time 1.\n  ///\n  template <typename Scalar, int Options>\n  MotionTpl<Scalar,Options>\n  log6(const SE3Tpl<Scalar,Options> & M)\n  {\n    typedef SE3Tpl<Scalar,Options> SE3;\n    typedef MotionTpl<Scalar,Options> Motion;\n    typedef typename SE3::Vector3 Vector3;\n\n    typename SE3::ConstAngularRef R = M.rotation();\n    typename SE3::ConstLinearRef p = M.translation();\n    \n    Scalar t;\n    Vector3 w(log3(R,t)); // t in [0,\u03c0]\n    const Scalar t2 = t*t;\n    Scalar alpha, beta;\n    if (t < TaylorSeriesExpansion<Scalar>::template precision<3>())\n    {\n      alpha = Scalar(1) - t2/Scalar(12) - t2*t2/Scalar(720);\n      beta = Scalar(1)/Scalar(12) + t2/Scalar(720);\n    }\n    else\n    {\n      Scalar st,ct; SINCOS(t,&st,&ct);\n      alpha = t*st/(Scalar(2)*(Scalar(1)-ct));\n      beta = Scalar(1)/t2 - st/(Scalar(2)*t*(Scalar(1)-ct));\n    }\n    \n    return Motion(alpha * p - 0.5 * w.cross(p) + beta * w.dot(p) * w,\n                  w);\n  }\n\n  /// \\brief Log: SE3 -> se3.\n  ///\n  /// Pseudo-inverse of exp from SE3 -> { v,w \\in se3, ||w|| < 2pi }.\n  ///\n  /// \\param[in] R The rigid transformation represented as an homogenous matrix.\n  ///\n  /// \\return The twist associated to the rigid transformation during time 1.\n  ///\n  template<typename Matrix4Like>\n  MotionTpl<typename Matrix4Like::Scalar,Eigen::internal::traits<Matrix4Like>::Options>\n  log6(const Eigen::MatrixBase<Matrix4Like> & M)\n  {\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Matrix4Like, M, 4, 4);\n\n    SE3Tpl<typename Matrix4Like::Scalar,Eigen::internal::traits<Matrix4Like>::Options> m(M);\n    return log6(m);\n  }\n\n  /// \\brief Derivative of exp6\n  /// Computed as the inverse of Jlog6\n  template<typename MotionDerived, typename Matrix6Like>\n  void Jexp6(const MotionDense<MotionDerived>     & nu,\n             const Eigen::MatrixBase<Matrix6Like> & Jexp)\n  {\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Matrix6Like, Jexp, 6, 6);\n\n    typedef typename MotionDerived::Scalar Scalar;\n    typedef typename MotionDerived::Vector3 Vector3;\n    typedef Eigen::Matrix<Scalar, 3, 3, Vector3::Options> Matrix3;\n    Matrix6Like & Jout = PINOCCHIO_EIGEN_CONST_CAST(Matrix6Like,Jexp);\n\n    const typename MotionDerived::ConstLinearType  & v = nu.linear();\n    const typename MotionDerived::ConstAngularType & w = nu.angular();\n    const Scalar t2 = w.squaredNorm();\n    const Scalar t = math::sqrt(t2);\n\n    // Matrix3 J3;\n    // Jexp3(w, J3);\n    Jexp3(w, Jout.template bottomRightCorner<3,3>());\n    Jout.template topLeftCorner<3,3>() = Jout.template bottomRightCorner<3,3>();\n\n    Scalar beta, beta_dot_over_theta;\n    if (t < TaylorSeriesExpansion<Scalar>::template precision<3>())\n    {\n      beta                = Scalar(1)/Scalar(12) + t2/Scalar(720);\n      beta_dot_over_theta = Scalar(1)/Scalar(360);\n    }\n    else\n    {\n      const Scalar tinv = Scalar(1)/t,\n                   t2inv = tinv*tinv;\n      Scalar st,ct; SINCOS (t, &st, &ct);\n      const Scalar inv_2_2ct = Scalar(1)/(Scalar(2)*(Scalar(1)-ct));\n\n      beta = t2inv - st*tinv*inv_2_2ct;\n      beta_dot_over_theta = -Scalar(2)*t2inv*t2inv +\n        (Scalar(1) + st*tinv) * t2inv * inv_2_2ct;\n    }\n\n    Vector3 p (Jout.template topLeftCorner<3,3>().transpose() * v);\n    Scalar wTp (w.dot (p));\n    Matrix3 J (alphaSkew(.5, p) +\n          (beta_dot_over_theta*wTp)                *w*w.transpose()\n          - (t2*beta_dot_over_theta+Scalar(2)*beta)*p*w.transpose()\n          + wTp * beta                             * Matrix3::Identity()\n          + beta                                   *w*p.transpose());\n\n    Jout.template topRightCorner<3,3>().noalias() =\n      - Jout.template topLeftCorner<3,3>() * J;\n    Jout.template bottomLeftCorner<3,3>().setZero();\n  }\n\n  /** \\brief Derivative of log6\n   *  \\f[\n   *  \\left(\\begin{array}{cc}\n   *  \\text{Jlog3}(R) & J * \\text{Jlog3}(R) \\\\\n   *            0     &     \\text{Jlog3}(R) \\\\\n   *  \\end{array}\\right)\n   *  \\f]\n   *  where\n   *  \\f[\n   *  \\def\\rot{R}\n   *  \\begin{eqnarray}\n   *  J &=& \n   *  \\left.\\frac{1}{2}[\\mathbf{p}]_{\\times} + \\dot{\\beta} (||r||) \\frac{\\rot^T\\mathbf{p}}{||r||}\\rot\\rot^T\n   *  - (||r||\\dot{\\beta} (||r||) + 2 \\beta(||r||)) \\mathbf{p}\\rot^T\\right.\\\\\n   *  &&\\left. + \\rot^T\\mathbf{p}\\beta (||r||)I_3 + \\beta (||r||)\\rot\\mathbf{p}^T\\right.\n   *  \\end{eqnarray}\n   *  \\f]\n   *  and\n   *  \\f[ \\beta(x)=\\left(\\frac{1}{x^2} - \\frac{\\sin x}{2x(1-\\cos x)}\\right) \\f]\n   */\n  template<typename Scalar, int Options, typename Matrix6Like>\n  void Jlog6(const SE3Tpl<Scalar, Options> & M,\n             const Eigen::MatrixBase<Matrix6Like> & Jlog)\n  {\n    PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE (Matrix6Like, Jlog, 6, 6);\n\n    typedef SE3Tpl<Scalar,Options> SE3;\n    typedef typename SE3::Vector3 Vector3;\n    Matrix6Like & value = PINOCCHIO_EIGEN_CONST_CAST(Matrix6Like,Jlog);\n\n    typename SE3::ConstAngularRef R = M.rotation();\n    typename SE3::ConstLinearRef p = M.translation();\n    \n    Scalar t;\n    Vector3 w(log3(R,t));\n    \n    // value is decomposed as following:\n    // value = [ A, B;\n    //           C, D ]\n    typedef Eigen::Block<Matrix6Like,3,3> Block33;\n    Block33 A = value.template topLeftCorner<3,3>();\n    Block33 B = value.template topRightCorner<3,3>();\n    Block33 C = value.template bottomLeftCorner<3,3>();\n    Block33 D = value.template bottomRightCorner<3,3>();\n    \n    Jlog3(t, w, A);\n    D = A;\n\n    const Scalar t2 = t*t;\n    Scalar beta, beta_dot_over_theta;\n    if(t < TaylorSeriesExpansion<Scalar>::template precision<3>())\n    {\n      beta                = Scalar(1)/Scalar(12) + t2/Scalar(720);\n      beta_dot_over_theta = Scalar(1)/Scalar(360);\n    }\n    else\n    {\n      const Scalar tinv = Scalar(1)/t,\n                   t2inv = tinv*tinv;\n      Scalar st,ct; SINCOS (t, &st, &ct);\n      const Scalar inv_2_2ct = Scalar(1)/(Scalar(2)*(Scalar(1)-ct));\n\n      beta = t2inv - st*tinv*inv_2_2ct;\n      beta_dot_over_theta = -Scalar(2)*t2inv*t2inv +\n        (Scalar(1) + st*tinv) * t2inv * inv_2_2ct;\n    }\n\n    Scalar wTp = w.dot(p);\n\n    Vector3 v3_tmp((beta_dot_over_theta*wTp)*w - (t2*beta_dot_over_theta+Scalar(2)*beta)*p);\n    // C can be treated as a temporary variable\n    C.noalias() = v3_tmp * w.transpose();\n    C.noalias() += beta * w * p.transpose();\n    C.diagonal().array() += wTp * beta;\n    addSkew(.5*p,C);\n    \n    B.noalias() = C * A;\n    C.setZero();\n  }\n} // namespace pinocchio\n\n#include \"pinocchio/spatial/explog-quaternion.hpp\"\n\n#endif //#ifndef __spatial_explog_hpp__\n", "meta": {"hexsha": "e4a8816ff7390cdec73c5335a4be2390aa63d9e2", "size": 18261, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spatial/explog.hpp", "max_stars_repo_name": "francois-keith/pinocchio", "max_stars_repo_head_hexsha": "52aacd09ee82c20119a0609e3e314b4e3ddb098f", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spatial/explog.hpp", "max_issues_repo_name": "francois-keith/pinocchio", "max_issues_repo_head_hexsha": "52aacd09ee82c20119a0609e3e314b4e3ddb098f", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spatial/explog.hpp", "max_forks_repo_name": "francois-keith/pinocchio", "max_forks_repo_head_hexsha": "52aacd09ee82c20119a0609e3e314b4e3ddb098f", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-25T13:34:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T13:34:37.000Z", "avg_line_length": 35.666015625, "max_line_length": 112, "alphanum_fraction": 0.6033075954, "num_tokens": 5684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6195198792050925}}
{"text": "/*  Example code adapted from adept-1.0 advection example\n\n    Copyright (C) 2012-2013 Robin Hogan and the University of Reading\n\n    Contact email address: r.j.hogan@reading.ac.uk\n\n    This file is part of the Adept library.\n\n    This library is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <cmath>\n#include <iostream>\n#include <boost/format.hpp>\n#include <vector>\n\n#include <adept.h>\n\n#define NX 100\nusing namespace adept;\n\n// Lax-Wendroff scheme applied to linear advection\nvoid\nlax_wendroff(int nt, double c, const adouble q_init[NX], adouble q[NX])\n{\n    preallocate_statements((nt+1)*NX*3);\n    preallocate_operations((nt+1)*NX*7);\n    adouble flux[NX-1];                        // Fluxes between boxes\n    for (int i=0; i<NX; i++) {\n        q[i] = q_init[i]; // Initialize q\n    }\n    for (int j=0; j<nt; j++)\n    {\n        for (int i=0; i<NX-1; i++) {\n            flux[i] = 0.5*c*(q[i]+q[i+1]+c*(q[i]-q[i+1]));\n        }\n        for (int i=1; i<NX-1; i++) {\n            q[i] += flux[i-1]-flux[i];\n        }\n        q[0] = q[NX-2];\n        q[NX-1] = q[1];          // Treat boundary conditions\n    }\n}\n\n// Toon advection scheme applied to linear advection\nvoid\ntoon(int nt, double c, const adouble q_init[NX], adouble q[NX])\n{\n    preallocate_statements((nt+1)*NX*3);\n    preallocate_operations((nt+1)*NX*9);\n    adouble flux[NX-1];                        // Fluxes between boxes\n    for (int i=0; i<NX; i++) {\n        q[i] = q_init[i]; // Initialize q\n    }\n    for (int j=0; j<nt; j++) {                 // Main loop in time\n        for (int i=0; i<NX-1; i++) {\n            flux[i] = (exp(c*log(q[i]/q[i+1]))-1.0) \n                * q[i]*q[i+1] / (q[i]-q[i+1]);\n        }\n        for (int i=1; i<NX-1; i++) {\n            q[i] += flux[i-1]-flux[i];\n        }\n        q[0] = q[NX-2]; q[NX-1] = q[1];          // Treat boundary\n                                                 // conditions\n    }\n}\n\nint\nmain(int argc, char** argv)\n{\n    double pi = 4.0*atan(1.0);\n    double q_init[NX];\n    \n    int nt = 100;\n    int nr = 500;\n    double dt = 0.125;\n    adept::Stack adept_stack;\n\n    for (int i = 0; i < NX; i++) {\n        q_init[i] = (0.5+0.5*sin((i*2.0*pi)/(NX-1.5)))+0.0001;\n    }\n\n    for (int j = 0; j < nr; j++)\n    {\n        adouble adept_q_init[NX];\n        adouble adept_q[NX];\n\n        adept::set_values(adept_q_init, NX, q_init);\n        adept_stack.new_recording();\n        toon(nt, dt, adept_q_init, adept_q);\n\n        adept_stack.independent(adept_q_init, NX);\n        adept_stack.dependent(adept_q, NX);\n\n        double jacobian[NX*NX];\n        adept_stack.jacobian(jacobian);\n\n        if (j == 1) {\n            for (int p = 0; p < 5; ++p) {\n                std::cout << \"  \";\n                for (int q = 0; q < 5; ++q) {\n                    std::cout << boost::format(\"%.16e\") % jacobian[p + q*NX] << \" \";\n                }\n                std::cout << std::endl;\n            }\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "4e60880b50e558dc9dcc05df293073f09b9fb394", "size": 3536, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/bench_advection_adept.cpp", "max_stars_repo_name": "gyzhangqm/adjac", "max_stars_repo_head_hexsha": "49e19123b7abee390ecfc29ae8c6327bc957690a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2017-07-18T18:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-12T19:01:59.000Z", "max_issues_repo_path": "examples/bench_advection_adept.cpp", "max_issues_repo_name": "pv/adjac", "max_issues_repo_head_hexsha": "49e19123b7abee390ecfc29ae8c6327bc957690a", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/bench_advection_adept.cpp", "max_forks_repo_name": "pv/adjac", "max_forks_repo_head_hexsha": "49e19123b7abee390ecfc29ae8c6327bc957690a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-07-30T21:02:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-23T19:12:17.000Z", "avg_line_length": 29.2231404959, "max_line_length": 84, "alphanum_fraction": 0.5359162896, "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6195198619119812}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXd ones = MatrixXd::Ones(3,3);\nVectorXcd eivals = ones.eigenvalues();\ncout << \"The eigenvalues of the 3x3 matrix of ones are:\" << endl << eivals << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "a7f967a2e6799b44408b711398ce57718a97142e", "size": 311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_eigenvalues.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_eigenvalues.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_eigenvalues.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4375, "max_line_length": 83, "alphanum_fraction": 0.6881028939, "num_tokens": 89, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.619309980694197}}
{"text": "#include \"tetrahedron.h\"\r\n\r\n#include <Eigen/Eigen>\r\n\r\n\r\nTetrahedron::Tetrahedron(const Eigen::MatrixXd& V, const Eigen::VectorXi& indices, const Eigen::VectorXi& faces, double shear, double bulk)\r\n: FiniteElement(V, indices, faces, shear, bulk)\r\n{\r\n\t// Compute inverse initial deformation\r\n\tRotation dX;\r\n\tconst auto root = _X.row(3);\r\n\tdX << _X.row(0) - root, _X.row(1) - root, _X.row(2) - root;\r\n\t_invdX = dX.inverse();\r\n\r\n\t// Compute volume\r\n\t_volume = dX.determinant() / 6;\r\n\tif (_volume < 0.0)\r\n\t{\r\n\t\tstd::cout << \"Negative volume, invalid configuration\" << std::endl;\r\n\t}\r\n}\r\n\r\nTetrahedron::~Tetrahedron()\r\n{\r\n\r\n}\r\n\r\n\r\ndouble Tetrahedron::compute_U(const Eigen::MatrixXd& E) const\r\n{\r\n\tconst double trE = E.trace();\r\n\tconst double trSqr = E.cwiseProduct(E).sum();\r\n\treturn (_shear / 2 * trE * trE + _bulk * trSqr) * _volume;\r\n}\r\n\r\nEigen::MatrixXd Tetrahedron::compute_F(const Eigen::MatrixXd& x) const\r\n{\r\n\tRotation du;\r\n\tconst auto& root = x.row(3);\r\n\tdu << x.row(0) - root, x.row(1) - root, x.row(2) - root;\r\n\treturn du * _invdX;\r\n}\r\n\r\nEigen::MatrixXd Tetrahedron::compute_E(const Eigen::MatrixXd& F) const\r\n{\r\n\treturn (F.transpose() * F - Rotation::Identity()) / 2;\r\n}\r\n\r\n\r\nEigen::MatrixXd Tetrahedron::compute_dUdE(const Eigen::MatrixXd& E) const\r\n{\r\n\tEigen::MatrixXd I = Rotation::Identity();\r\n\treturn (_shear * E.trace() * I + 2 * _bulk * E) * _volume;\r\n}\r\n\r\nEigen::MatrixXd Tetrahedron::compute_dEdF(const Eigen::MatrixXd& F) const\r\n{\r\n\treturn  F.transpose();\r\n}\r\n\r\nEigen::MatrixXd Tetrahedron::compute_dFdx(const Eigen::MatrixXd& x, int32_t i, int32_t j) const\r\n{\r\n\tRotation dF = Rotation::Zero();\r\n\tif (i < 3)\r\n\t{\r\n\t\tdF(i, j) = 1.0;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdF.col(j) = Vec3(-1.0, -1.0, -1.0);\r\n\t}\r\n\treturn dF * _invdX;\r\n}\r\n\r\nEigen::MatrixXd Tetrahedron::compute_ddFddx(const Eigen::MatrixXd& x) const\r\n{\r\n\treturn _invdX;\r\n}\r\n\r\nEigen::MatrixXd Tetrahedron::compute_ddEddF(const Eigen::MatrixXd& F) const\r\n{\r\n\treturn Eigen::Matrix3d::Identity();\r\n}\r\n\r\nTensor Tetrahedron::compute_ddUddE(const Eigen::MatrixXd& E) const\r\n{\r\n\tTensor out(E.rows(), E.cols(), Eigen::Matrix3d::Zero());\r\n\t\r\n\t// Edge/Corner entries\r\n\tfor (int i = 0; i < E.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < E.cols(); j++)\r\n\t\t{\r\n\t\t\tout(i, j)(i, j) += 2 * _bulk * _volume;\r\n\t\t}\r\n\t}\r\n\r\n\t// Diagonal entries\r\n\tfor (int i = 0; i < E.rows(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < E.cols(); j++)\r\n\t\t{\r\n\t\t\tout(i, i)(j, j) += _shear * _volume;\r\n\t\t}\r\n\t}\r\n\r\n\treturn out;\r\n}", "meta": {"hexsha": "31ae866cf47effb61c3b0372c52978e8d1ba711a", "size": 2429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tetrahedron.cpp", "max_stars_repo_name": "AngryLizard/BendyPrint", "max_stars_repo_head_hexsha": "78334d07f7f14cb46cd1bf6a51fc8554a61052e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tetrahedron.cpp", "max_issues_repo_name": "AngryLizard/BendyPrint", "max_issues_repo_head_hexsha": "78334d07f7f14cb46cd1bf6a51fc8554a61052e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tetrahedron.cpp", "max_forks_repo_name": "AngryLizard/BendyPrint", "max_forks_repo_head_hexsha": "78334d07f7f14cb46cd1bf6a51fc8554a61052e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4907407407, "max_line_length": 140, "alphanum_fraction": 0.6167146974, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6193099743564107}}
{"text": "#include \"smooth_alg.hpp\"\n\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include <Eigen/QR>\n#include <Eigen/LU>\n#include <Eigen/SparseLU>\n\n// -----------------------------------------------------------------------------\n\ntypedef Eigen::Triplet<double, int> Triplet;\n/// declares a column-major sparse matrix type of double\ntypedef Eigen::SparseMatrix<double> Sparse_mat;\n\n// -----------------------------------------------------------------------------\n\n/// @return A sparse representation of the normalized Laplacian\n/// list[ith_row][list of columns] = Triplet(ith_row, jth_column, matrix value)\nstatic\nstd::vector<std::vector<Triplet>>\nget_normalized_laplacian(const std::vector< Vec3 >& vertices,\n                         const std::vector< std::vector<int> >& edges )\n{\n    unsigned nv = unsigned(vertices.size());\n    std::vector<std::vector<Triplet>> mat_elemts(nv);\n    for(int i = 0; i < nv; ++i)\n        mat_elemts[i].reserve(10);\n\n    for(int i = 0; i < nv; ++i)\n    {\n        const Vec3 c_pos = vertices[i];\n\n        //get laplacian\n        double sum = 0.;\n        int nb_edges = edges[i].size();\n        for(int e = 0; e < nb_edges; ++e)\n        {\n            int next_edge = (e + 1           ) % nb_edges;\n            int prev_edge = (e + nb_edges - 1) % nb_edges;\n\n            Vec3 v1 = c_pos                 - vertices[edges[i][prev_edge]];\n            Vec3 v2 = vertices[edges[i][e]] - vertices[edges[i][prev_edge]];\n            Vec3 v3 = c_pos                 - vertices[edges[i][next_edge]];\n            Vec3 v4 = vertices[edges[i][e]] - vertices[edges[i][next_edge]];\n\n            double cotan1 = (v1.dot(v2)) / (1e-6 + (v1.cross(v2)).norm() );\n            double cotan2 = (v3.dot(v4)) / (1e-6 + (v3.cross(v4)).norm() );\n\n            double w = (cotan1 + cotan2)*0.5;\n            sum += w;\n            mat_elemts[i].push_back( Triplet(i, edges[i][e], w) );\n        }\n\n        for( Triplet& t : mat_elemts[i] )\n            t = Triplet( t.row(), t.col(), t.value() / sum);\n\n        mat_elemts[i].push_back( Triplet(i, i, -1.0) );\n    }\n    return mat_elemts;\n}\n\n// -----------------------------------------------------------------------------\n\nstatic\nstd::vector< std::vector<float> >\nget_cotan_weights(const std::vector< Vec3 >& vertices,\n                  const std::vector< std::vector<int> >& edges)\n{\n    unsigned nv = unsigned(vertices.size());\n    std::vector< std::vector<float> > weights(nv);\n\n    for(int i = 0; i < nv; ++i)\n    {\n        const Vec3 c_pos = vertices[i];\n        double sum = 0.;\n        int nb_edges = edges[i].size();\n        weights[i].resize( nb_edges );\n        for(int e = 0; e < nb_edges; ++e)\n        {\n            int next_edge = (e + 1           ) % nb_edges;\n            int prev_edge = (e + nb_edges - 1) % nb_edges;\n\n            Vec3 v1 = c_pos                 - vertices[edges[i][prev_edge]];\n            Vec3 v2 = vertices[edges[i][e]] - vertices[edges[i][prev_edge]];\n            Vec3 v3 = c_pos                 - vertices[edges[i][next_edge]];\n            Vec3 v4 = vertices[edges[i][e]] - vertices[edges[i][next_edge]];\n\n            double cotan1 = (v1.dot(v2)) / (1e-6 + (v1.cross(v2)).norm() );\n            double cotan2 = (v3.dot(v4)) / (1e-6 + (v3.cross(v4)).norm() );\n\n            double w = (cotan1 + cotan2)*0.5;\n            weights[i][e] = w;\n        }\n    }\n    return weights;\n}\n\n//------------------------------------------------------------------------------\n\nstd::vector< Vec3 >\nsmooth_iterative(const std::vector< Vec3 >& in_vertices,\n                 const std::vector< std::vector<int> >& edges,\n                 int nb_iter,\n                 float alpha)\n{\n    unsigned nb_vertices = unsigned(in_vertices.size());\n    std::vector< std::vector<float> > cotan_weights = get_cotan_weights(in_vertices, edges);\n\n    std::vector< Vec3 > buffer_vertices( nb_vertices );\n    std::vector< Vec3 > source = in_vertices;\n\n    if(nb_iter == 0){\n        return in_vertices;\n    }\n\n    Vec3* src_vertices = source.data();\n    Vec3* dst_vertices = buffer_vertices.data();\n    for(int k = 0; k < nb_iter; k++)\n    {\n        for( int i = 0; i < nb_vertices; i++)\n        {\n#if 0\n            if( _topo->is_vert_on_side( i ) ){\n                dst_vertices[i] = src_vertices[i];\n                continue;\n            }\n#endif\n\n            Vec3 cog(0.f);\n            float sum = 0.f;\n            size_t nb_neighs = edges[i].size();\n            for(size_t n = 0; n < nb_neighs; n++)\n            {\n                Vert_idx neigh = edges[i][n];\n                float w = cotan_weights[i][n];\n                cog += src_vertices[neigh] * w;\n                sum += w;\n            }\n            float t = alpha;\n            dst_vertices[i] = (cog / sum) * t + src_vertices[i] * (1.f - t);\n\n        }\n\n        std::swap(dst_vertices, src_vertices);\n    }\n\n    return (nb_iter%2 == 1) ? buffer_vertices : source;\n}\n\n//------------------------------------------------------------------------------\n\n//explicit\nstd::vector< Vec3 >\nexplicit_laplacian_smoothing(const std::vector< Vec3 >& in_vertices,\n                             const std::vector< std::vector<int> >& edges,\n                             int nb_iter,\n                             float alpha)\n{\n    unsigned nb_vertices = unsigned(in_vertices.size());\n\n    std::vector<Eigen::VectorXd> xyz;\n    std::vector<Eigen::VectorXd> rhs;\n\n    xyz.resize(3, Eigen::VectorXd::Zero(nb_vertices));\n    rhs.resize(3, Eigen::VectorXd::Zero(nb_vertices));\n\n    for(int i = 0; i < nb_vertices; ++i)\n    {\n        Vec3 pos = in_vertices[i];\n        xyz[0][i] = pos.x;\n        xyz[1][i] = pos.y;\n        xyz[2][i] = pos.z;\n    }\n\n    // Build laplacian\n    std::vector<std::vector<Triplet>> mat_elemts = get_normalized_laplacian(in_vertices, edges);\n    Eigen::SparseMatrix<double> L(nb_vertices, nb_vertices);\n    std::vector<Triplet> triplets;\n    triplets.reserve(nb_vertices * 10);\n    for( const std::vector<Triplet>& row : mat_elemts)\n        for( const Triplet& elt : row )\n            triplets.push_back( elt );\n\n    L.setFromTriplets(triplets.begin(), triplets.end());\n\n    Eigen::SparseMatrix<double> I = Eigen::MatrixXd::Identity(nb_vertices, nb_vertices).sparseView();\n    L = I + L*alpha;\n\n    //L = L*L*L*L*L*L*L*L*L*L;\n    rhs = xyz;\n    for(int n = 0; n < nb_iter; n++){\n        for(int k = 0; k < 3; k++){\n            xyz[k] = (L * xyz[k]);\n        }\n    }\n\n    std::vector< Vec3 > out_verts(nb_vertices);\n    for(int i = 0; i < nb_vertices; ++i){\n        Vec3 v;\n        v.x = xyz[0][i];\n        v.y = xyz[1][i];\n        v.z = xyz[2][i];\n        out_verts[i] = v;\n    }\n\n    return out_verts;\n}\n\n//------------------------------------------------------------------------------\n\n//implicit\nstd::vector< Vec3 >\nimplicit_laplacian_smoothing(const std::vector< Vec3 >& in_vertices,\n                             const std::vector< std::vector<int> >& edges,\n                             int nb_iter,\n                             float alpha)\n{\n    unsigned nb_vertices = unsigned(in_vertices.size());\n\n    std::vector<Eigen::VectorXd> xyz;\n    std::vector<Eigen::VectorXd> rhs;\n\n    xyz.resize(3, Eigen::VectorXd::Zero(nb_vertices));\n    rhs.resize(3, Eigen::VectorXd::Zero(nb_vertices));\n\n    for(int i = 0; i < nb_vertices; ++i)\n    {\n        Vec3 pos = in_vertices[i];\n        rhs[0][i] = pos.x;\n        rhs[1][i] = pos.y;\n        rhs[2][i] = pos.z;\n    }\n\n\n    // Build laplacian\n    std::vector<std::vector<Triplet>> mat_elemts = get_normalized_laplacian(in_vertices, edges);\n    Eigen::SparseMatrix<double> L(nb_vertices, nb_vertices);\n    std::vector<Triplet> triplets;\n    triplets.reserve(nb_vertices * 10);\n    for( const std::vector<Triplet>& row : mat_elemts)\n        for( const Triplet& elt : row )\n            triplets.push_back( elt );\n\n    L.setFromTriplets(triplets.begin(), triplets.end());\n\n    Eigen::SparseMatrix<double> I = Eigen::MatrixXd::Identity(nb_vertices, nb_vertices).sparseView();\n    L = I - L*alpha;\n\n    L = L*L*L;\n\n    // Solve for x, y, z\n    Eigen::SparseLU<Sparse_mat> solver;\n    solver.compute( L );\n\n    for(int k = 0; k < 3; k++){\n        xyz[k] = solver.solve(rhs[k]);\n    }\n\n    std::vector< Vec3 > out_verts(nb_vertices);\n    for(int i = 0; i < nb_vertices; ++i){\n        Vec3 v;\n        v.x = xyz[0][i];\n        v.y = xyz[1][i];\n        v.z = xyz[2][i];\n        out_verts[i] = v;\n    }\n\n    return out_verts;\n}\n\n\n", "meta": {"hexsha": "89c6190ca0655f261b181bc1353b93d6ce62546b", "size": 8391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/smooth_alg.cpp", "max_stars_repo_name": "brainexcerpts/laplacian_smoothing_triangle_mesh", "max_stars_repo_head_hexsha": "8c02c8323ed47ce683339132a9f386cf1ba2a6de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-22T23:30:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T23:50:16.000Z", "max_issues_repo_path": "src/smooth_alg.cpp", "max_issues_repo_name": "brainexcerpts/laplacian_smoothing_triangle_mesh", "max_issues_repo_head_hexsha": "8c02c8323ed47ce683339132a9f386cf1ba2a6de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/smooth_alg.cpp", "max_forks_repo_name": "brainexcerpts/laplacian_smoothing_triangle_mesh", "max_forks_repo_head_hexsha": "8c02c8323ed47ce683339132a9f386cf1ba2a6de", "max_forks_repo_licenses": ["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.6240875912, "max_line_length": 101, "alphanum_fraction": 0.5085210344, "num_tokens": 2213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.682573734412324, "lm_q1q2_score": 0.6193074946335021}}
{"text": "#include <exception>\n#include <NTL/ZZ.h>\n#include \"RSA.h\"\n\nconst char *KeyError::what() {\n\treturn \"Tried to decrypt using a public key.\";\n}\n\n\n// Input: m, integer representation of plaintext\n// key, the RSA public key\n// Output: c, integer representation of ciphertext\nvoid encrypt(NTL::ZZ& c, const NTL::ZZ& m, const RSAkey& key) {\n\tPowerMod(c, m, key.get_param(\"e\"), key.get_param(\"n\"));\n}\n\n// Input: c, integer representation of ciphertext\n// key, the RSA private key\n// Output: m, integer representation of plaintext\nvoid decrypt(NTL::ZZ& m, const NTL::ZZ& c, const RSAkey& key) {\n\tif(key.is_private()) {\n\t\tPowerMod(m, c, key.get_param(\"d\"), key.get_param(\"n\"));\n\t} else {\n\t\tthrow KeyError();\n\t}\n}\n", "meta": {"hexsha": "c7b970b2d164152e09e07422a87c17df9342d5a6", "size": 702, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RSA.cpp", "max_stars_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_stars_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RSA.cpp", "max_issues_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_issues_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RSA.cpp", "max_forks_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_forks_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 63, "alphanum_fraction": 0.6794871795, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.6193074794947151}}
{"text": "// Copyright Andr\u00e1s Vukics 2006\u20132020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#include \"MathExtensions.h\"\n\n#include <boost/math/special_functions/factorials.hpp>\n\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_math.h>\n#include <gsl/gsl_sf.h>\n\n#include <stdexcept>\n\n  \nconst double cppqedutils::PI(M_PI);\nconst double cppqedutils::SQRTPI(M_SQRTPI);\nconst double cppqedutils::EULER(M_E);\n\nint cppqedutils::sign(double x) {return GSL_SIGN(x);}\nint cppqedutils::fcmp(double x, double y, double eps) {return gsl_fcmp(x,y,eps);}\n\ndouble cppqedutils::sqr(double x) {return gsl_pow_2(x);}\n\ndouble cppqedutils::sqrAbs(dcomp x) {return sqr(real(x))+sqr(imag(x));} // saves the sqrt\n\ndouble cppqedutils::fact(unsigned n)\n{\n  if (n>GSL_SF_FACT_NMAX) throw std::out_of_range(\"Factorial of\"+std::to_string(n));\n  return gsl_sf_fact(n);\n}\n\ndouble cppqedutils::choose(unsigned n, unsigned m)\n{\n  return gsl_sf_choose(n,m);\n}\n\ndcomp cppqedutils::coherentElement(unsigned long n, dcomp alpha)\n{\n  using namespace boost::math;\n  return n ? n<max_factorial<double>::value ? pow(alpha,n)/sqrt(factorial<double>(n)) \n                                            : pow(2*n*PI,-.25)*pow(alpha/sqrt(n/EULER),n)\n           : 1.;\n}\n", "meta": {"hexsha": "0349a78675095fa5ed193c5c277a166a04d9c974", "size": 1257, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDutils/MathExtensions.cc", "max_stars_repo_name": "vukics/cppqed", "max_stars_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T14:00:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T15:12:11.000Z", "max_issues_repo_path": "CPPQEDutils/MathExtensions.cc", "max_issues_repo_name": "vukics/cppqed", "max_issues_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T11:18:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T20:11:23.000Z", "max_forks_repo_path": "CPPQEDutils/MathExtensions.cc", "max_forks_repo_name": "vukics/cppqed", "max_forks_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T10:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T18:29:01.000Z", "avg_line_length": 29.9285714286, "max_line_length": 132, "alphanum_fraction": 0.7048528242, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.6193074785105087}}
{"text": "/**\n * @file activation_functions_test.cpp\n * @author Marcus Edel\n * @author Dhawal Arora\n *\n * Tests for the various activation functions.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/activation_functions/logistic_function.hpp>\n#include <mlpack/methods/ann/activation_functions/identity_function.hpp>\n#include <mlpack/methods/ann/activation_functions/softsign_function.hpp>\n#include <mlpack/methods/ann/activation_functions/tanh_function.hpp>\n#include <mlpack/methods/ann/activation_functions/rectifier_function.hpp>\n\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n#include <mlpack/methods/ann/performance_functions/mse_function.hpp>\n\n#include <mlpack/methods/ann/layer/bias_layer.hpp>\n#include <mlpack/methods/ann/layer/linear_layer.hpp>\n#include <mlpack/methods/ann/layer/base_layer.hpp>\n#include <mlpack/methods/ann/layer/binary_classification_layer.hpp>\n#include <mlpack/methods/ann/layer/leaky_relu_layer.hpp>\n#include <mlpack/methods/ann/layer/hard_tanh_layer.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(ActivationFunctionsTest);\n\n// Be careful!  When writing new tests, always get the boolean value and store\n// it in a temporary, because the Boost unit test macros do weird things and\n// will cause bizarre problems.\n\n// Generate dataset for activation function tests.\nconst arma::colvec activationData(\"-2 3.2 4.5 -100.2 1 -1 2 0\");\n\n/*\n * Implementation of the activation function test.\n *\n * @param input Input data used for evaluating the activation function.\n * @param target Target data used to evaluate the activation.\n *\n * @tparam ActivationFunction Activation function used for the check.\n */\ntemplate<class ActivationFunction>\nvoid CheckActivationCorrect(const arma::colvec input, const arma::colvec target)\n{\n  // Test the activation function using a single value as input.\n  for (size_t i = 0; i < target.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(ActivationFunction::fn(input.at(i)),\n        target.at(i), 1e-3);\n  }\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  ActivationFunction::fn(input, activations);\n  for (size_t i = 0; i < activations.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/*\n * Implementation of the activation function derivative test.\n *\n * @param input Input data used for evaluating the activation function.\n * @param target Target data used to evaluate the activation.\n *\n * @tparam ActivationFunction Activation function used for the check.\n */\ntemplate<class ActivationFunction>\nvoid CheckDerivativeCorrect(const arma::colvec input, const arma::colvec target)\n{\n  // Test the calculation of the derivatives using a single value as input.\n  for (size_t i = 0; i < target.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(ActivationFunction::deriv(input.at(i)),\n        target.at(i), 1e-3);\n  }\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives;\n  ActivationFunction::deriv(input, derivatives);\n  for (size_t i = 0; i < derivatives.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/*\n * Implementation of the activation function inverse test.\n *\n * @param input Input data used for evaluating the activation function.\n * @param target Target data used to evaluate the activation.\n *\n * @tparam ActivationFunction Activation function used for the check.\n */\ntemplate<class ActivationFunction>\nvoid CheckInverseCorrect(const arma::colvec input)\n{\n    // Test the calculation of the inverse using a single value as input.\n  for (size_t i = 0; i < input.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(ActivationFunction::inv(ActivationFunction::fn(\n        input.at(i))), input.at(i), 1e-3);\n  }\n\n  // Test the calculation of the inverse using the entire vector as input.\n  arma::colvec activations;\n  ActivationFunction::fn(input, activations);\n  ActivationFunction::inv(activations, activations);\n\n  for (size_t i = 0; i < input.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), input.at(i), 1e-3);\n  }\n}\n\n/*\n * Implementation of the HardTanH activation function test. The function is\n * implemented as a HardTanH Layer in hard_tanh_layer.hpp\n *\n * @param input Input data used for evaluating the HardTanH activation function.\n * @param target Target data used to evaluate the HardTanH activation.\n */\nvoid CheckHardTanHActivationCorrect(const arma::colvec input,\n                                    const arma::colvec target)\n{\n  HardTanHLayer<> htf;\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  htf.Forward(input, activations);\n  for (size_t i = 0; i < activations.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/*\n * Implementation of the HardTanH activation function derivative test. The\n * derivative is implemented as HardTanH Layer in hard_tanh_layer.hpp\n *\n * @param input Input data used for evaluating the HardTanH activation function.\n * @param target Target data used to evaluate the HardTanH activation.\n */\nvoid CheckHardTanHDerivativeCorrect(const arma::colvec input,\n                                    const arma::colvec target)\n{\n  HardTanHLayer<> htf;\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives;\n\n  // This error vector will be set to 1 to get the derivatives.\n  arma::colvec error(input.n_elem);\n  htf.Backward(input, (arma::colvec)error.ones(), derivatives);\n  for (size_t i = 0; i < derivatives.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/*\n * Implementation of the LeakyReLU activation function test. The function is  \n * implemented as LeakyReLU layer in the file leaky_relu_layer.hpp\n * \n * @param input Input data used for evaluating the LeakyReLU activation function.\n * @param target Target data used to evaluate the LeakyReLU activation.\n */\nvoid CheckLeakyReLUActivationCorrect(const arma::colvec input,\n                                     const arma::colvec target)\n{\n  LeakyReLULayer<> lrf;\n\n  // Test the activation function using the entire vector as input.\n  arma::colvec activations;\n  lrf.Forward(input, activations);\n  for (size_t i = 0; i < activations.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3);\n  }\n}\n\n/*\n * Implementation of the LeakyReLU activation function derivative test. \n * The derivative function is implemented as LeakyReLU layer in the file \n * leaky_relu_layer.hpp\n *\n * @param input Input data used for evaluating the LeakyReLU activation function.\n * @param target Target data used to evaluate the LeakyReLU activation.\n */\n\nvoid CheckLeakyReLUDerivativeCorrect(const arma::colvec input, \n                                     const arma::colvec target)\n{\n  LeakyReLULayer<> lrf;\n\n  // Test the calculation of the derivatives using the entire vector as input.\n  arma::colvec derivatives;\n\n  // This error vector will be set to 1 to get the derivatives.\n  arma::colvec error(input.n_elem);\n  lrf.Backward(input, (arma::colvec)error.ones(), derivatives);\n  for (size_t i = 0; i < derivatives.n_elem; i++)\n  {\n    BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3);\n  }\n}\n\n/**\n * Basic test of the tanh function.\n */\nBOOST_AUTO_TEST_CASE(TanhFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-0.96402758 0.9966824 0.99975321 -1 \\\n                                         0.76159416 -0.76159416 0.96402758 0\");\n\n  const arma::colvec desiredDerivatives(\"0.07065082 0.00662419 0.00049352 0 \\\n                                         0.41997434 0.41997434 0.07065082 1\");\n\n  CheckActivationCorrect<TanhFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<TanhFunction>(desiredActivations, desiredDerivatives);\n  CheckInverseCorrect<TanhFunction>(desiredActivations);\n}\n\n/**\n * Basic test of the logistic function.\n */\nBOOST_AUTO_TEST_CASE(LogisticFunctionTest)\n{\n  const arma::colvec desiredActivations(\"1.19202922e-01 9.60834277e-01 \\\n                                         9.89013057e-01 3.04574e-44 \\\n                                         7.31058579e-01 2.68941421e-01 \\\n                                         8.80797078e-01 0.5\");\n\n  const arma::colvec desiredDerivatives(\"0.10499359 0.03763177 0.01086623 \\\n                                         3.04574e-44 0.19661193 0.19661193 \\\n                                         0.10499359 0.25\");\n\n  CheckActivationCorrect<LogisticFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<LogisticFunction>(desiredActivations,\n      desiredDerivatives);\n  CheckInverseCorrect<LogisticFunction>(activationData);\n}\n\n/**\n * Basic test of the softsign function.\n */\nBOOST_AUTO_TEST_CASE(SoftsignFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-0.66666667 0.76190476 0.81818182 \\\n                                         -0.99011858 0.5 -0.5 0.66666667 0\");\n\n  const arma::colvec desiredDerivatives(\"0.11111111 0.05668934 0.03305785 \\\n                                         9.7642e-05 0.25 0.25 0.11111111 1\");\n\n  CheckActivationCorrect<SoftsignFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<SoftsignFunction>(desiredActivations,\n      desiredDerivatives);\n  CheckInverseCorrect<SoftsignFunction>(desiredActivations);\n}\n\n/**\n * Basic test of the identity function.\n */\nBOOST_AUTO_TEST_CASE(IdentityFunctionTest)\n{\n  const arma::colvec desiredDerivatives = arma::ones<arma::colvec>(\n      activationData.n_elem);\n\n  CheckActivationCorrect<IdentityFunction>(activationData, activationData);\n  CheckDerivativeCorrect<IdentityFunction>(activationData, desiredDerivatives);\n}\n\n/**\n * Basic test of the rectifier function.\n */\nBOOST_AUTO_TEST_CASE(RectifierFunctionTest)\n{\n  const arma::colvec desiredActivations(\"0 3.2 4.5 0 1 0 2 0\");\n\n  const arma::colvec desiredDerivatives(\"0 1 1 0 1 0 1 0\");\n\n  CheckActivationCorrect<RectifierFunction>(activationData, desiredActivations);\n  CheckDerivativeCorrect<RectifierFunction>(desiredActivations,\n      desiredDerivatives);\n}\n\n/**\n * Basic test of the LeakyReLU function.\n */\nBOOST_AUTO_TEST_CASE(LeakyReLUFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-0.06 3.2 4.5 -3.006 \\\n                                         1 -0.03 2 0\");\n\n  const arma::colvec desiredDerivatives(\"0.03 1 1 0.03 \\\n                                         1 0.03 1 1\");\n\n  CheckLeakyReLUActivationCorrect(activationData, desiredActivations);\n  CheckLeakyReLUDerivativeCorrect(desiredActivations, desiredDerivatives);\n}\n\n/**\n * Basic test of the HardTanH function.\n */\nBOOST_AUTO_TEST_CASE(HardTanHFunctionTest)\n{\n  const arma::colvec desiredActivations(\"-1 1 1 -1 \\\n                                         1 -1 1 0\");\n\n  const arma::colvec desiredDerivatives(\"0 0 0 0 \\\n                                         1 1 0 1\");\n\n  CheckHardTanHActivationCorrect(activationData, desiredActivations);\n  CheckHardTanHDerivativeCorrect(activationData, desiredDerivatives);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\n", "meta": {"hexsha": "c14769e0c7aebbe0fbfb382596fc6a8fb442cd32", "size": 11158, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/activation_functions_test.cpp", "max_stars_repo_name": "abhinvgpta/mlpack", "max_stars_repo_head_hexsha": "c5573b26c0f5c78037e4b82e75ccbcef6f254694", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:20.000Z", "max_issues_repo_path": "src/mlpack/tests/activation_functions_test.cpp", "max_issues_repo_name": "decltypeme/mlpack", "max_issues_repo_head_hexsha": "e3b418918fffce382ce9d8ceee9d9349ca199611", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/activation_functions_test.cpp", "max_forks_repo_name": "decltypeme/mlpack", "max_forks_repo_head_hexsha": "e3b418918fffce382ce9d8ceee9d9349ca199611", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0182926829, "max_line_length": 81, "alphanum_fraction": 0.7090876501, "num_tokens": 2783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6193001895063203}}
{"text": "/*\n * Using Erasthostenes' sieve, print the first 2,000,000 numbers\n * darkturo 2014\n */\n#include <iostream>\n#include <fstream>\n#include <bitset>\n#include <ctime>\n#include <limits>\n#include <boost/spirit/include/karma.hpp>\n\n#define TIMEDIFF(start, stop) 1000.0 * (stop - start)/CLOCKS_PER_SEC\n#define MAXNUMBER 32452843\n#define BUFFER_SIZE 8l * MAXNUMBER \n\nclass ErasthostenesSieve\n{\n   std::bitset<MAXNUMBER> listOfNaturals;\n   std::ofstream output;\n   int counter; \n   char * buffer;\n   char * p_input;\n\n   public:\n   ErasthostenesSieve() : \n           output(\"primesEveryWhere.txt\", std::ios::out | std::ios::trunc),\n           counter(0)\n   {\n      listOfNaturals.set();\n      listOfNaturals.set(0, false); // 1 is not prime\n\n      buffer = new char[BUFFER_SIZE];\n      p_input = buffer;\n   }\n\n   ~ErasthostenesSieve()\n   {\n      if (p_input != buffer)\n         output.write(buffer, p_input - buffer);  // flush\n      output.close();\n   }\n\n   int applyTheSieve()\n   {\n      int base = 2;\n      print( base );\n\n      for (base = 3; base * base < MAXNUMBER; base += 2 )\n      {\n         if (not listOfNaturals[base - 1]) \n            continue;\n\n         print( base );\n         \n         for (int pivot = base + base ; pivot <= MAXNUMBER; pivot += base)\n         {\n            listOfNaturals.set(pivot - 1, false);\n         }\n      }\n\n      for (; base <= MAXNUMBER; base += 2)\n      {\n         if (listOfNaturals[base - 1])\n            print( base );\n      }\n      return counter;\n   }\n\n   private:\n   inline void print(int number)\n   {\n      doPrint(number);\n      counter ++;\n   }\n\n   inline void doPrint(int number)\n   {\n      boost::spirit::karma::generate(p_input, boost::spirit::int_, number);\n#if BOOST_VERSION > 103600\n      *p_input++ = '\\n';\n#else\n      p_input += strlen(p_input);\n      *p_input++ = '\\n';\n#endif\n   }\n};\n\nint main(int argc, char ** argv)\n{\n   clock_t t1, t2;\n\n   t1 = std::clock();\n\n   ErasthostenesSieve siever;\n   int printedPrimes = siever.applyTheSieve();\n\n   t2 = std::clock();\n\n   // Summary\n   std::cout.precision(std::numeric_limits<double>::digits10);\n   std::cerr << \"Used \" << std::fixed << TIMEDIFF(t1, t2)\n             << \" msecs to calculate \" << printedPrimes\n             << \" primes.\" << std::endl;\n}\n", "meta": {"hexsha": "4fd3490019210886b9f1181b620f2412e2fe98ad", "size": 2249, "ext": "cc", "lang": "C++", "max_stars_repo_path": "c++/heisenberg.cc", "max_stars_repo_name": "darkturo/primo", "max_stars_repo_head_hexsha": "055d564ecb1106c23e2327f4e8921d111472492f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-07T16:35:32.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-07T16:35:32.000Z", "max_issues_repo_path": "c++/heisenberg.cc", "max_issues_repo_name": "darkturo/primo", "max_issues_repo_head_hexsha": "055d564ecb1106c23e2327f4e8921d111472492f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/heisenberg.cc", "max_forks_repo_name": "darkturo/primo", "max_forks_repo_head_hexsha": "055d564ecb1106c23e2327f4e8921d111472492f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.419047619, "max_line_length": 75, "alphanum_fraction": 0.570475767, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.74316801430083, "lm_q1q2_score": 0.6193001847660791}}
{"text": "/* test_derivatives.cpp - Test derivatives of mathematical functions \n\n    Copyright (C) 2017 European Centre for Medium-Range Weather Forecasts\n\n    Author: Robin Hogan <r.j.hogan@ecmwf.int>\n\n  Copying and distribution of this file, with or without modification,\n  are permitted in any medium without royalty provided the copyright\n  notice and this notice are preserved.  This file is offered as-is,\n  without any warranty.\n\n*/\n\n#include <adept_arrays.h>\n\n\n#define TEST_UNARY_FUNC(FUNC)\t\t\t\t\t\\\n  {\t\t\t\t\t\t\t\t\\\n    std::cout << \"  Checking \" << #FUNC << \"... \\t\";\t\t\\\n    aVector x = x_save;\t\t\t\t\t\\\n    stack.new_recording();\t\t\t\t\t\\\n    aVector y = FUNC(x);\t\t\t\t\t\\\n    Vector dy_dx_num  = (FUNC(x_save+dx)-FUNC(x_save)) / dx;\t\\\n    Vector dy_dx_adept(N);\t\t\t\t\t\\\n    for (int i = 0; i < N; ++i) {\t\t\t\t\\\n      x[i].set_gradient(1.0);\t\t\t\t\t\\\n      stack.forward();\t\t\t\t\t\t\\\n      y[i].get_gradient(dy_dx_adept[i]);\t\t\t\\\n    }\t\t\t\t\t\t\t\t\\\n    Real max_err\t\t\t\t\t\t\\\n      = maxval(abs(dy_dx_adept-dy_dx_num));\t\t\t\\\n    Real max_frac_err\t\t\t\t\t\t\\\n      = maxval(abs(dy_dx_adept-dy_dx_num)/dy_dx_adept);\t\t\\\n    if (max_err == 0) {\t\t\t\t\t\t\\\n      std::cout << \"max error = 0: PASSED\\n\";\t\t\t\\\n    }\t\t\t\t\t\t\t\t\\\n    if (max_frac_err <= MAX_FRAC_ERR) {\t\t\t\t\\\n      std::cout << \"max fractional error = \" << max_frac_err\t\\\n\t\t<< \": PASSED\\n\";\t\t\t\t\\\n    }\t\t\t\t\t\t\t\t\\\n    else {\t\t\t\t\t\t\t\\\n      std::cout << \"max fractional error = \"\t\t\t\\\n\t\t<< max_frac_err << \": FAILED\\n\";\t\t\\\n      std::cout << \"    Adept     dy/dx = \"\t\t\t\\\n\t\t<< dy_dx_adept << \"\\n\";\t\t\t\t\\\n      std::cout << \"    Numerical dy/dx = \" << dy_dx_num << \"\\n\";\t\\\n      error_too_large = true;\t\t\t\t\t\\\n    }\t\t\t\t\t\t\t\t\\\n  }\n\n#define TEST_BINARY_FUNC(FUNC)\t\t\t\t\t\\\n  {\t\t\t\t\t\t\t\t\\\n    std::cout << \"  Checking \" << #FUNC << \"... \\t\";\t\t\\\n    aVector x = x_save;\t\t\t\t\t\\\n    aVector y = y_save;\t\t\t\t\t\t\\\n    stack.new_recording();\t\t\t\t\t\\\n    aVector z = FUNC(x,y);\t\t\t\t\t\\\n    Vector dz_dx_num\t\t\t\t\t\t\\\n      = (FUNC(x_save+dx,y_save)-FUNC(x_save,y_save)) / dx; \\\n    Vector dz_dy_num\t\t\t\t\t\t\\\n      = (FUNC(x_save,y_save+dy)-FUNC(x_save,y_save)) / dy;\t\\\n    Vector dz_dx_adept(N);\t\t\t\t\t\\\n    Vector dz_dy_adept(N);\t\t\t\t\t\\\n    for (int i = 0; i < N; ++i) {\t\t\t\t\\\n      z[i].set_gradient(1.0);\t\t\t\t\t\\\n      stack.reverse();\t\t\t\t\t\t\\\n      x[i].get_gradient(dz_dx_adept[i]);\t\t\t\\\n      y[i].get_gradient(dz_dy_adept[i]);\t\t\t\\\n    }\t\t\t\t\t\t\t\t\\\n    Real max_err\t\t\t\t\t\t\\\n      = std::max(maxval(abs(dz_dx_adept-dz_dx_num)),\t\t\\\n\t\t maxval(abs(dz_dy_adept-dz_dy_num)));\t\t\\\n    Real max_frac_err\t\t\t\t\t\t\\\n      = std::max(maxval(abs(dz_dx_adept-dz_dx_num)/dz_dx_adept),\t\\\n\t\t maxval(abs(dz_dy_adept-dz_dy_num)/dz_dy_adept));\t\\\n    if (max_err == 0) {\t\t\t\t\t\t\\\n      std::cout << \"max error = 0: PASSED\\n\";\t\t\t\\\n    }\t\t\t\t\t\t\t\t\\\n    if (max_frac_err <= MAX_FRAC_ERR) {\t\t\t\t\\\n      std::cout << \"max fractional error = \" << max_frac_err\t\\\n\t\t<< \": PASSED\\n\";\t\t\t\t\\\n    }\t\t\t\t\t\t\t\t\\\n    else {\t\t\t\t\t\t\t\\\n      std::cout << \"max fractional error = \"\t\t\t\\\n\t\t<< max_frac_err << \": FAILED\\n\";\t\t\\\n      std::cout << \"    Adept     dz/dx = \" << dz_dx_adept << \"\\n\";\t\\\n      std::cout << \"    Adept     dz/dy = \" << dz_dy_adept << \"\\n\";\t\\\n      std::cout << \"    Numerical dz/dx = \" << dz_dx_num << \"\\n\";\t\\\n      std::cout << \"    Numerical dz/dy = \" << dz_dy_num << \"\\n\";\t\\\n      error_too_large = true;\t\t\t\t\t\\\n    }\t\t\t\t\t\t\t\t\\\n  }\n\n\nint\nmain(int argc, const char** argv) {\n  using namespace adept;\n\n  Stack stack;\n\n  static const int N             = 12;\n  static const Real MAX_FRAC_ERR = 1.0e-5;\n\n  Vector x_save(N);\n  x_save = 0.2;\n  x_save << 0.01, 0.4, 0.99;\n\n  Vector y_save(N);\n  y_save = 0.7;\n  y_save << 0.9, 0.6, 0.1;\n\n  Real dx = 1.0e-8;\n\n  if (sizeof(Real) < 8) {\n    // Single precision only works with larger perturbations\n    dx = 1.0e-5;\n  }\n\n  Real dy = dx;\n\n  bool error_too_large = false;  \n\n  std::cout << \"EVALUATING UNARY FUNCTIONS\\n\";\n  std::cout << \"For functions of the form y=FUNC(x), where x=\" << x_save << \",\\n\";\n  std::cout << \"checking that fractional difference between dy/dx computed using Adept\\n\";\n  std::cout << \"and numerically by perturbing x by \" << dx << \" is less than \" << MAX_FRAC_ERR << \".\\n\";    \n\n  \n  TEST_UNARY_FUNC(-); // Unary minus\n  TEST_UNARY_FUNC(+); // Unary plus\n  TEST_UNARY_FUNC(log);\n  TEST_UNARY_FUNC(log10);\n  TEST_UNARY_FUNC(sin);\n  TEST_UNARY_FUNC(cos);\n  TEST_UNARY_FUNC(tan);\n  TEST_UNARY_FUNC(asin);\n  TEST_UNARY_FUNC(acos);\n  TEST_UNARY_FUNC(atan);\n  TEST_UNARY_FUNC(sinh);\n  TEST_UNARY_FUNC(cosh);\n  TEST_UNARY_FUNC(tanh);\n  TEST_UNARY_FUNC(abs);\n  TEST_UNARY_FUNC(fabs);\n  TEST_UNARY_FUNC(exp);\n  TEST_UNARY_FUNC(sqrt);\n  TEST_UNARY_FUNC(ceil);\n  TEST_UNARY_FUNC(floor);\n  TEST_UNARY_FUNC(log2);\n  TEST_UNARY_FUNC(expm1);\n  TEST_UNARY_FUNC(exp2);\n  TEST_UNARY_FUNC(log1p);\n  TEST_UNARY_FUNC(asinh);\n  TEST_UNARY_FUNC(acosh);\n  TEST_UNARY_FUNC(atanh);\n  TEST_UNARY_FUNC(erf);\n  TEST_UNARY_FUNC(erfc);\n  TEST_UNARY_FUNC(cbrt);\n  TEST_UNARY_FUNC(round);\n  TEST_UNARY_FUNC(trunc);\n  TEST_UNARY_FUNC(rint);\n  TEST_UNARY_FUNC(nearbyint);\n\n  std::cout << \"EVALUATING BINARY FUNCTIONS\\n\";\n  std::cout << \"For functions of the form z=FUNC(x,y), where x=\" << x_save << \",\\n\";\n  std::cout << \"and y=\" << y_save << \", checking that fractional difference between\\n\";\n  std::cout << \"dz/dx and dz/dy computed using Adept and numerically by perturbing\\n\";\n  std::cout << \"x and y by \" << dx << \" is less than \" << MAX_FRAC_ERR << \".\\n\";    \n\n  TEST_BINARY_FUNC(pow);\n  TEST_BINARY_FUNC(atan2);\n  TEST_BINARY_FUNC(max);\n  TEST_BINARY_FUNC(min);\n  TEST_BINARY_FUNC(fmax);\n  TEST_BINARY_FUNC(fmin);\n\n\n  if (error_too_large) {\n    std::cerr << \"*** Error: fractional error in the derivatives of some functions too large\\n\";\n\n    if (sizeof(Real) < 8) {\n      std::cerr << \"*** (but you are using less than double precision so it is not surprising)\\n\";\n    }\n\n    return 1;\n  }\n  else {\n    return 0;\n  }\n}\n", "meta": {"hexsha": "50983c5fa711c34ea09113b7d098c400a61ae748", "size": 5794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_derivatives.cpp", "max_stars_repo_name": "yairchu/Adept-2", "max_stars_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 131.0, "max_stars_repo_stars_event_min_datetime": "2016-07-06T04:06:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T22:34:47.000Z", "max_issues_repo_path": "test/test_derivatives.cpp", "max_issues_repo_name": "yairchu/Adept-2", "max_issues_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-06-20T20:20:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T14:55:01.000Z", "max_forks_repo_path": "test/test_derivatives.cpp", "max_forks_repo_name": "yairchu/Adept-2", "max_forks_repo_head_hexsha": "3b4f898c74139618464ccd8e8df0934aed9ed6a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-10-07T00:07:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T17:51:17.000Z", "avg_line_length": 30.4947368421, "max_line_length": 108, "alphanum_fraction": 0.5790472903, "num_tokens": 1893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245911726382, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6193001722093384}}
{"text": "//\n//  Eigenvalues of the radial part of a 3D exponential well\n//\n// compile with:\n//     g++ -std=c++11 exp_well_3d.cpp -o exp_well_3d -I$HOME/miniconda3/include/ -O3\n//\n// using the a Miniconda install of boost for the headers\n\n#include <cstdio>\n#include <iostream>\n#include <cmath>\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\ntypedef boost::array< long double , 2 > vec_type;\ntypedef runge_kutta_cash_karp54< vec_type > error_stepper_type;\ntypedef controlled_runge_kutta< error_stepper_type > controlled_stepper_type;\ntypedef runge_kutta4< vec_type > stepper;\n\n\nstruct ode{\n\n    long double m;\n    long double energy;\n    long double a;\n    long double k;\n    long double l;     // angluar quantum number\n\n    void operator()( const vec_type &vec , vec_type &dvecdx , double r)\n    {\n        dvecdx[0] = vec[1];\n        dvecdx[1] =  -2.0*vec[1]/r - (2*m*(energy - k*(exp(a*r) - 1.0)) - (l*(l+1)/(r*r)))*vec[0];\n    }\n};\n\nstruct nothing{\n\n    void operator()( const vec_type &vec , const double r){\n\n    }\n};\n\n\nvoid print_exp_well_psi_final(double k, double a, double m){\n    controlled_stepper_type controlled_stepper;\n\n    // Energy sweep range\n    double min_energy = 0.000001;\n    double max_energy = 10 * 0.00094;    // kBT = 0.00094 Ha\n\n    int l_max = 50;                       // Maximum value of the l qunatum number\n\n    double r_init = 0.001;               // Where to start the propogation from\n    double r_final = 1.7;                // Where to end   '   '  as there is a divergence at r=0\n\n    int n_steps = 20000;\n\n\n    for (int l = 0; l <= l_max; l++ ){\n\n        double prev_psi_final = 0.0;         // Final value of Psi i.e. Psi(r_final) for each eigenvalue\n\n\n        for (int i = 0; i < n_steps; i++){\n\n            double energy = min_energy + ((max_energy - min_energy) * i) / n_steps;\n\n            vec_type vec = { 1.0 , 1E-20 }; // initial conditions\n            integrate_adaptive( make_controlled< error_stepper_type >( 1.0e-10 , 1.0e-10 ),\n                               ode {m , energy, a, k, static_cast<long double>(l)},\n                               vec,\n                               r_init,\n                               r_final,\n                               1E-10,\n                               nothing {}\n                               );\n\n            // If the product of the previous Psi(r_final) and the current one is negative\n            // there must be a zero between them, i.e. a normalaisable WF\n            if (prev_psi_final * vec[0] < 0){\n                // cout << energy << endl;\n                cout << energy << '\\t' << l << endl;\n\n            }\n\n            // Reset the previous Psi(r_final)\n            prev_psi_final = vec[0];\n\n        } // Energy\n    }  // l\n}\n\nint main(int argc, char **argv){\n\n    freopen(\"eigenvals_co2.txt\",\"w\", stdout);\n    cout << \"Eigenvalue / Ha    l number\" << endl;\n\n    double k_co2 = 0.00220873;                   // prefactor for the exponential well\n\n    double k = 0.0001;\n    double a = 2.832 * 0.529177;             // exponent in the expoential well\n    double m = 48 * 1822.888486;             // mass in atomic units from amu\n\n    print_exp_well_psi_final(k_co2, a, m);\n\n    return 0;\n}\n", "meta": {"hexsha": "d2f753c6fa610a4336b3895e9936210d878f6b41", "size": 3270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "4/figs/figX7/exp_well_3d.cpp", "max_stars_repo_name": "t-young31/thesis", "max_stars_repo_head_hexsha": "2dea31ef64f4b7d55b8bdfc2094bab6579a529e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4/figs/figX7/exp_well_3d.cpp", "max_issues_repo_name": "t-young31/thesis", "max_issues_repo_head_hexsha": "2dea31ef64f4b7d55b8bdfc2094bab6579a529e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4/figs/figX7/exp_well_3d.cpp", "max_forks_repo_name": "t-young31/thesis", "max_forks_repo_head_hexsha": "2dea31ef64f4b7d55b8bdfc2094bab6579a529e0", "max_forks_repo_licenses": ["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.4594594595, "max_line_length": 104, "alphanum_fraction": 0.5587155963, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6192817332683008}}
{"text": "// Copyright (c) 2020 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#include <gtest/gtest.h>\n#include <boost/geometry.hpp>\n#include \"pyinterp/detail/math/radial_basis_functions.hpp\"\n\nnamespace math = pyinterp::detail::math;\n\nstatic void test_1d(math::RadialBasisFunction function) {\n  auto x = Eigen::Matrix<double, 1, 9>::LinSpaced(9, 0, 10);\n  auto y = x.array().sin();\n  auto rbf =\n      math::RBF<double>(std::numeric_limits<double>::quiet_NaN(), 0, function);\n  auto yi = rbf.interpolate(x, y, x);\n\n  ASSERT_EQ(y.size(), yi.size());\n  for (Eigen::Index ix = 0; ix < yi.size(); ++ix) {\n    EXPECT_NEAR(y(ix), yi(ix), 1e-9);\n  }\n}\n\nstatic void test_2d(math::RadialBasisFunction function) {\n  Eigen::Matrix<double, 2, 50> x = Eigen::Matrix<double, 2, 50>::Random();\n  Eigen::Matrix<double, 50, 1> y =\n      (x.row(0).array().pow(2) - x.row(1).array().pow(2)).array().exp();\n  auto rbf =\n      math::RBF<double>(std::numeric_limits<double>::quiet_NaN(), 0, function);\n  auto yi = rbf.interpolate(x, y, x);\n\n  ASSERT_EQ(y.size(), yi.size());\n  for (Eigen::Index ix = 0; ix < yi.size(); ++ix) {\n    EXPECT_NEAR(y(ix), yi(ix), 1e-9);\n  }\n}\n\nstatic void test_3d(math::RadialBasisFunction function) {\n  Eigen::Matrix<double, 3, 50> x = Eigen::Matrix<double, 3, 50>::Random();\n  Eigen::Matrix<double, 50, 1> y =\n      (x.row(0).array().pow(2) - x.row(1).array().pow(2)).array().exp();\n  auto rbf =\n      math::RBF<double>(std::numeric_limits<double>::quiet_NaN(), 0, function);\n  auto yi = rbf.interpolate(x, y, x);\n\n  ASSERT_EQ(y.size(), yi.size());\n  for (Eigen::Index ix = 0; ix < yi.size(); ++ix) {\n    EXPECT_NEAR(y(ix), yi(ix), 1e-9);\n  }\n}\n\nTEST(math_rbf, 1d) {\n  test_1d(math::RadialBasisFunction::Cubic);\n  test_1d(math::RadialBasisFunction::Gaussian);\n  test_1d(math::RadialBasisFunction::InverseMultiquadric);\n  test_1d(math::RadialBasisFunction::Linear);\n  test_1d(math::RadialBasisFunction::Multiquadric);\n  test_1d(math::RadialBasisFunction::ThinPlate);\n}\n\nTEST(math_rbf, 2d) {\n  test_2d(math::RadialBasisFunction::Cubic);\n  test_2d(math::RadialBasisFunction::Gaussian);\n  test_2d(math::RadialBasisFunction::InverseMultiquadric);\n  test_2d(math::RadialBasisFunction::Linear);\n  test_2d(math::RadialBasisFunction::Multiquadric);\n  test_2d(math::RadialBasisFunction::ThinPlate);\n}\n\nTEST(math_rbf, 3d) {\n  test_3d(math::RadialBasisFunction::Cubic);\n  test_3d(math::RadialBasisFunction::Gaussian);\n  test_3d(math::RadialBasisFunction::InverseMultiquadric);\n  test_3d(math::RadialBasisFunction::Linear);\n  test_3d(math::RadialBasisFunction::Multiquadric);\n  test_3d(math::RadialBasisFunction::ThinPlate);\n}\n\nTEST(math_rbf, point) {\n  Eigen::Matrix<double, 3, 50> x = Eigen::Matrix<double, 3, 50>::Random();\n  Eigen::Matrix<double, 50, 1> y =\n      (x.row(0).array().pow(2) - x.row(1).array().pow(2)).array().exp();\n  auto rbf = math::RBF<double>(std::numeric_limits<double>::quiet_NaN(), 0,\n                               math::RadialBasisFunction::Cubic);\n\n  auto xi = Eigen::Matrix<double, 3, 1>();\n  for (Eigen::Index ix = 0; ix < xi.cols(); ++ix) {\n    xi << x.col(ix);\n    auto yi = rbf.interpolate(x, y, xi);\n\n    ASSERT_EQ(yi.size(), 1);\n    EXPECT_NEAR(y(ix), yi(0), 1e-9);\n  }\n}\n", "meta": {"hexsha": "a951f6dfb2ae5497d143bd608eed0f0f65476e91", "size": 3279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/tests/math_rbf.cpp", "max_stars_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_stars_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-19T14:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-19T14:54:23.000Z", "max_issues_repo_path": "src/pyinterp/core/tests/math_rbf.cpp", "max_issues_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_issues_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/tests/math_rbf.cpp", "max_forks_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_forks_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5157894737, "max_line_length": 79, "alphanum_fraction": 0.6617871302, "num_tokens": 1092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6192817290467221}}
{"text": "/*\n * Copyright 2018-2019 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <eigen-osqp/CSCMatrix.h>\n#include <eigen-osqp/OSQP.h>\n#include <iostream>\n\nint main()\n{\n    int nrVar = 6;\n    int nrConstr = 5;\n    auto inf = std::numeric_limits<double>::infinity();\n\n    Eigen::SparseMatrix<double> Q(nrVar, nrVar);\n    Q.setIdentity();\n    Eigen::SparseMatrix<double> A(nrConstr, nrVar);\n    std::vector<Eigen::Triplet<double>> nz = {\n        { 0, 0, 1. },\n        { 0, 1, -1. },\n        { 0, 2, 1. },\n        { 0, 4, 3. },\n        { 0, 5, 1. },\n        { 1, 0, -1. },\n        { 1, 2, -3. },\n        { 1, 3, -4. },\n        { 1, 4, 5. },\n        { 1, 5, 6. },\n        { 2, 0, 2. },\n        { 2, 1, 5. },\n        { 2, 2, 3. },\n        { 2, 4, 1. },\n        { 3, 1, 1. },\n        { 3, 3, 1. },\n        { 3, 4, 2. },\n        { 3, 5, -1. },\n        { 4, 0, -1. },\n        { 4, 2, 2. },\n        { 4, 3, 1. },\n        { 4, 4, 1. },\n    };\n\n    A.setFromTriplets(nz.cbegin(), nz.cend());\n\n    Eigen::VectorXd c(nrVar);\n    Eigen::VectorXd AL(nrConstr);\n    Eigen::VectorXd AU(nrConstr);\n    Eigen::VectorXd XL(nrVar);\n    Eigen::VectorXd XU(nrVar);\n    c << 1., 2., 3., 4., 5., 6.;\n    AL << 1., 2., 3., -inf, -inf;\n    AU << 1., 2., 3., -1., 2.5;\n    XL << -1000., -10000., 0., -1000., -1000., -1000.;\n    XU << 10000., 100., 1.5, 100., 100., 1000.;\n\n    Eigen::OSQP qp;\n\n    qp.problem(nrVar, nrConstr);\n    bool success = qp.solve(Q, c, A, AL, AU, XL, XU);\n\n    Eigen::VectorXd result = qp.result();\n\n    std::cout << \"Problem:\"\n              << \"\\n\\tminimize 0.5*x'*Q*x + c'*x\"\n              << \"\\n\\twith     AL <= A <= AU\"\n              << \"\\n\\t         XL <= x <= XU\"\n              << \"\\n\\nQ:\\n\"\n              << Q\n              << \"\\nc:\\n\"\n              << c.transpose()\n              << \"\\nA:\\n\"\n              << A\n              << \"\\nAL:\\n\"\n              << AL.transpose()\n              << \"\\nAU:\\n\"\n              << AU.transpose()\n              << \"\\nXL:\\n\"\n              << XL.transpose()\n              << \"\\nXU:\\n\"\n              << XU.transpose()\n              << \"\\n\\n\\nSolution:\\n\"\n              << result.transpose() << std::endl;\n\n    std::cout << \"\\nPress enter to quit\" << std::endl;\n    std::cin.get();\n}\n", "meta": {"hexsha": "6975fc1c3cf00959da09cf783b0a311f9b5d87ac", "size": 2255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/sparse_matrix_qp.cpp", "max_stars_repo_name": "jrl-umi3218/eigen-osqp", "max_stars_repo_head_hexsha": "6b21a48e4c15f977bd9a5bc0b2863653f0a9cd10", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-19T02:46:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-11T15:21:29.000Z", "max_issues_repo_path": "examples/sparse_matrix_qp.cpp", "max_issues_repo_name": "jrl-umi3218/eigen-osqp", "max_issues_repo_head_hexsha": "6b21a48e4c15f977bd9a5bc0b2863653f0a9cd10", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-04-24T12:04:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-20T00:24:17.000Z", "max_forks_repo_path": "examples/sparse_matrix_qp.cpp", "max_forks_repo_name": "jrl-umi3218/eigen-osqp", "max_forks_repo_head_hexsha": "6b21a48e4c15f977bd9a5bc0b2863653f0a9cd10", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-19T02:36:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-07T04:15:32.000Z", "avg_line_length": 25.3370786517, "max_line_length": 55, "alphanum_fraction": 0.3920177384, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.6192817206035643}}
{"text": "/**\n * @file mirk_test.cc\n * @brief NPDE homework MIRK code\n * @author Philippe Peter\n * @date 14.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"../mirk.h\"\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\nnamespace MIRK::test {\n\nTEST(MIRK, Newton2Steps) {\n  Eigen::Vector2d x(-1.0, 1.0);\n\n  // f(x,y) = [e^x,e^y]\n  auto f = [](Eigen::Vector2d x) {\n    return Eigen::Vector2d(std::exp(x(0)), std::exp(x(1)));\n  };\n\n  auto df = [](Eigen::Vector2d x) {\n    Eigen::Matrix2d df;\n    df << std::exp(x(0)), 0, 0, std::exp(x(1));\n    return df;\n  };\n\n  // For exp(y): f(y) =  f'(y) for all y and one Newton step satisfies\n  // y_{n+1} = y_n - 1\n  Eigen::Vector2d x_2ref(-3.0, -1.0);\n\n  // Compute error\n  Eigen::Vector2d x_2 = Newton2Steps(f, df, x);\n  double err = (x_2 - x_2ref).norm();\n  EXPECT_NEAR(0.0, err, 1E-7);\n}\n\n}  // namespace MIRK::test", "meta": {"hexsha": "26511b63983bc18f89f259ccf7486f09116aee6d", "size": 856, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MIRK/templates/test/mirk_test.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/MIRK/templates/test/mirk_test.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/MIRK/templates/test/mirk_test.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 20.8780487805, "max_line_length": 70, "alphanum_fraction": 0.5852803738, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6192167874122922}}
{"text": "#include <gtest/gtest.h>\n\n#include \"mfem.hpp\"\nusing namespace mfem;\n\n#include <iostream>\n#include <fstream>\n#include <chrono>\n#include <random>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"../include/core/config.hpp\"\n#include \"../include/mymfem/utilities.hpp\"\n\nusing namespace std;\n\n\nTEST(MfemUtil, getUpperTriangle)\n{\n    // CSR sparse matrix\n    int sizeA = 8;\n    int rowPtrA[9] = { 0, 4, 7, 9, 11, 12, 15, 17, 20 };\n    int colIdA[20] = { 0,    2,       5, 6,\n                          1, 2,    4,\n                             2,             7,\n                                   3,       6,\n                          1,\n                             2,       5,    7,\n                          1,             6,\n                             2,          6, 7 };\n    double dataA[20] = { 7.0,      1.0,           2.0, 7.0,\n                             -4.0, 8.0,      2.0,\n                                   1.0,                     5.0,\n                                        7.0,           9.0,\n                             -4.0,\n                                   7.0,           3.0,      8.0,\n                              1.0,                    11.0,\n                                  -3.0,                2.0, 5.0 };\n\n    // create a Sparse matrix\n    SparseMatrix trueA(rowPtrA, colIdA, dataA, sizeA, sizeA,\n                   false, false, true);\n\n    // get upper triangle\n    SparseMatrix& UA = get_upper_triangle (trueA);\n\n    // diagA = UA + UA.transpose() - trueA\n    SparseMatrix diagA (*Add(UA, *Transpose(UA)));\n    diagA.Add(-1, trueA);\n\n    Vector trueDiagA, errDiagA;\n    trueA.GetDiag(trueDiagA);\n    diagA.GetDiag(errDiagA);\n    errDiagA -= trueDiagA;\n\n    double TOL = 1E-8;\n    ASSERT_LE(errDiagA.Normlinf(), TOL);\n}\n\n\n/* Test the point location algorithm implemented in class PointLocator\n * for meshes with local refinement, generated by _serial_ code\n*/\nTEST(MfemUtil, pointLocator1)\n{\n    std::string input_dir\n            = \"../input/poisson_singular_gammaShaped_bisecRefine/\";\n\n    int lx1 = 1;\n    const std::string mesh_file1 = input_dir+\"mesh_lx\"+to_string(lx1);\n\n    int lx2 = 6;\n    const std::string mesh_file2 = input_dir+\"mesh_lx\"+to_string(lx2);\n\n    //std::cout << mesh_file1 << std::endl;\n    //std::cout << mesh_file2 << std::endl;\n\n    Mesh mesh1(mesh_file1.c_str());\n    Mesh mesh2(mesh_file2.c_str());\n\n    const IntegrationRule *ir = nullptr;\n    ir = &IntRules.Get(2, 3);\n\n    std::random_device rd;     // initialise (seed) engine\n    std::mt19937 rng(rd());    // random-number engine used\n    std::uniform_int_distribution<int> uni(0,mesh1.GetNE()-1);\n\n    auto elId1 = uni(rng);\n    //std::cout << \"Generate in element:\" << elId1 << std::endl;\n    //elId1 = 3;\n    ElementTransformation *trans1 = mesh1.GetElementTransformation(elId1);\n    DenseMatrix true_x(mesh1.Dimension(), ir->GetNPoints());\n    Vector xk;\n    for (int k=0; k < true_x.NumCols(); k++) {\n        true_x.GetColumnReference(k,xk);\n        trans1->Transform(ir->IntPoint(k), xk);\n    }\n\n    Array <int> elIds1(true_x.NumCols());\n    Array <IntegrationPoint> ips1(true_x.NumCols());\n\n    Array <int> elIds2(true_x.NumCols());\n    Array <IntegrationPoint> ips2(true_x.NumCols());\n\n    auto start1 = std::chrono::high_resolution_clock::now();\n    mesh2.FindPoints(true_x, elIds1, ips1);\n    auto end1 = std::chrono::high_resolution_clock::now();\n\n    auto start2 = std::chrono::high_resolution_clock::now();\n    PointLocator point_locator(&mesh2);\n    int init_elId = 0;\n    for (int k=0; k < true_x.NumCols(); k++) {\n        Vector xk;\n        true_x.GetColumn(k, xk);\n        std::tie (elIds2[k],ips2[k]) = point_locator(xk, init_elId);\n        init_elId = elIds2[k];\n    }\n    auto end2 = std::chrono::high_resolution_clock::now();\n\n    ElementTransformation *trans2 = nullptr;\n    Vector x1, x2, x;\n    double TOL = 1E-8;\n    for (int k=0; k < true_x.NumCols(); k++)\n    {\n        trans2 = mesh2.GetElementTransformation(elIds1[k]);\n        trans2->Transform(ips1[k], x1);\n\n        trans2 = mesh2.GetElementTransformation(elIds2[k]);\n        trans2->Transform(ips2[k], x2);\n\n        true_x.GetColumn(k,x);\n\n        Vector xmx1(x.Size()), xmx2(x.Size());\n        subtract(x, x1, xmx1);\n        subtract(x, x2, xmx2);\n\n        ASSERT_LE(xmx1.Norml1(), TOL);\n        ASSERT_LE(xmx2.Norml1(), TOL);\n    }\n\n    auto duration1 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end1 - start1);\n    auto duration2 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end2 - start2);\n\n    std::cout << \"Run times: \"\n              << \"\\t slow  \" << duration1.count()\n              << \"\\t fast  \" << duration2.count() << std::endl;\n}\n\n/* Test the point location algorithm implemented in class PointLocator\n * for quasi-uniform meshes, generated by _serial_ code.\n * The shared vertices table is generated, but expected to be empty.\n*/\nTEST(MfemUtil, pointLocator2)\n{\n    std::string input_dir = \"../input/poisson_smooth_unitSquare/\";\n\n    int lx1 = 1;\n    const std::string mesh_file1 = input_dir+\"mesh_lx\"+to_string(lx1);\n\n    int lx2 = 6;\n    const std::string mesh_file2 = input_dir+\"mesh_lx\"+to_string(lx2);\n\n    //std::cout << mesh_file1 << std::endl;\n    //std::cout << mesh_file2 << std::endl;\n\n    Mesh mesh1(mesh_file1.c_str());\n    Mesh mesh2(mesh_file2.c_str());\n\n    const IntegrationRule *ir = nullptr;\n    ir = &IntRules.Get(2, 3);\n\n    std::random_device rd;     // initialise (seed) engine\n    std::mt19937 rng(rd());    // random-number engine used\n    std::uniform_int_distribution<int> uni(0,mesh1.GetNE()-1);\n\n    auto elId1 = uni(rng);\n    ElementTransformation *trans1 = mesh1.GetElementTransformation(elId1);\n    DenseMatrix true_x(mesh1.Dimension(), ir->GetNPoints());\n    Vector xk;\n    for (int k=0; k < true_x.NumCols(); k++) {\n        true_x.GetColumnReference(k,xk);\n        trans1->Transform(ir->IntPoint(k), xk);\n    }\n\n    Array <int> elIds1(true_x.NumCols());\n    Array <IntegrationPoint> ips1(true_x.NumCols());\n\n    Array <int> elIds2(true_x.NumCols());\n    Array <IntegrationPoint> ips2(true_x.NumCols());\n\n    auto start1 = std::chrono::high_resolution_clock::now();\n    mesh2.FindPoints(true_x, elIds1, ips1);\n    auto end1 = std::chrono::high_resolution_clock::now();\n\n    bool has_shared_vertices = true;\n    auto start2 = std::chrono::high_resolution_clock::now();\n    PointLocator point_locator(&mesh2, has_shared_vertices);\n    int init_elId = 0;\n    for (int k=0; k < true_x.NumCols(); k++) {\n        Vector xk;\n        true_x.GetColumn(k, xk);\n        std::tie (elIds2[k],ips2[k]) = point_locator(xk, init_elId);\n        init_elId = elIds2[k];\n    }\n    auto end2 = std::chrono::high_resolution_clock::now();\n\n    ElementTransformation *trans2 = nullptr;\n    Vector x1, x2, x;\n    double TOL = 1E-8;\n    for (int k=0; k < true_x.NumCols(); k++)\n    {\n        trans2 = mesh2.GetElementTransformation(elIds1[k]);\n        trans2->Transform(ips1[k], x1);\n\n        trans2 = mesh2.GetElementTransformation(elIds2[k]);\n        trans2->Transform(ips2[k], x2);\n\n        true_x.GetColumn(k,x);\n\n        Vector xmx1(x.Size()), xmx2(x.Size());\n        subtract(x, x1, xmx1);\n        subtract(x, x2, xmx2);\n\n        ASSERT_LE(xmx1.Norml1(), TOL);\n        ASSERT_LE(xmx2.Norml1(), TOL);\n    }\n\n    auto duration1 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end1 - start1);\n    auto duration2 = std::chrono::duration_cast\n            <std::chrono::microseconds>(end2 - start2);\n\n    std::cout << \"Run times: \"\n              << \"\\t slow  \" << duration1.count()\n              << \"\\t fast  \" << duration2.count() << std::endl;\n}\n\n/* Test the point location algorithm implemented in class PointLocator\n * for quasi-uniform meshes, generated by _parallel_ code.\n * The shared vertices table is generated.\n*/\nTEST(MfemUtil, pointLocator3)\n{\n    std::string input_dir = \"../input/poisson_smooth_unitSquare/\";\n\n    int lx1 = 1;\n    const std::string mesh_file1 = input_dir+\"pmesh_lx\"+to_string(lx1);\n\n    int lx2 = 6;\n    const std::string mesh_file2 = input_dir+\"pmesh_lx\"+to_string(lx2);\n\n    //std::cout << mesh_file1 << std::endl;\n    //std::cout << mesh_file2 << std::endl;\n\n    Mesh mesh1(mesh_file1.c_str());\n    Mesh mesh2(mesh_file2.c_str());\n\n    const IntegrationRule *ir = nullptr;\n    ir = &IntRules.Get(2, 3);\n\n    std::random_device rd;     // initialise (seed) engine\n    std::mt19937 rng(rd());    // random-number engine used\n    std::uniform_int_distribution<int> uni(0,mesh1.GetNE()-1);\n\n    auto elId1 = uni(rng);\n    ElementTransformation *trans1 = mesh1.GetElementTransformation(elId1);\n    DenseMatrix true_x(mesh1.Dimension(), ir->GetNPoints());\n    Vector xk;\n    for (int k=0; k < true_x.NumCols(); k++) {\n        true_x.GetColumnReference(k,xk);\n        trans1->Transform(ir->IntPoint(k), xk);\n    }\n\n    Array <int> elIds(true_x.NumCols());\n    Array <IntegrationPoint> ips(true_x.NumCols());\n\n    bool has_shared_vertices = true;\n    auto start = std::chrono::high_resolution_clock::now();\n    PointLocator point_locator(&mesh2, has_shared_vertices);\n    int init_elId = 0;\n    for (int k=0; k < true_x.NumCols(); k++) {\n        Vector xk;\n        true_x.GetColumn(k, xk);\n        std::tie (elIds[k],ips[k]) = point_locator(xk, init_elId);\n        init_elId = elIds[k];\n    }\n    auto end = std::chrono::high_resolution_clock::now();\n\n    ElementTransformation *trans2 = nullptr;\n    Vector xp, x;\n    double TOL = 1E-8;\n    for (int k=0; k < true_x.NumCols(); k++)\n    {\n        trans2 = mesh2.GetElementTransformation(elIds[k]);\n        trans2->Transform(ips[k], xp);\n\n        true_x.GetColumn(k,x);\n\n        Vector xmxp(x.Size());\n        subtract(x, xp, xmxp);\n\n        ASSERT_LE(xmxp.Norml1(), TOL);\n    }\n\n    auto duration = std::chrono::duration_cast\n            <std::chrono::microseconds>(end - start);\n\n    std::cout << \"Run time: \"\n              << duration.count() << std::endl;\n}\n", "meta": {"hexsha": "764240486325f3822f18fb4141b0f8b590e70f9b", "size": 9930, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_utilities.cpp", "max_stars_repo_name": "pratyuksh/NumHypSys", "max_stars_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_utilities.cpp", "max_issues_repo_name": "pratyuksh/NumHypSys", "max_issues_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_utilities.cpp", "max_forks_repo_name": "pratyuksh/NumHypSys", "max_forks_repo_head_hexsha": "29e03f9cc0572178701525210561b152d89999d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5238095238, "max_line_length": 74, "alphanum_fraction": 0.5847935549, "num_tokens": 2821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6192167646188271}}
{"text": "#include <PCP/Curvature/Curvature.h>\n#include <PCP/Curvature/Weight.h>\n\n#include <PCP/Geometry/Geometry.h>\n\n#include <PCP/SpacePartitioning/KdTree.h>\n\n#include <Eigen/Eigenvalues>\n\nnamespace pcp {\n\nPointWiseEstimationData CurvatureComputer_PCAPlane::compute(const Geometry& points, int i, Scalar r) const\n{\n    Matrix3 C      = Matrix3::Zero();\n    Vector3 m      = Vector3::Zero();\n    Scalar  sum_w  = 0;\n\n    int nei_count = 0;\n\n    for(int j : points.kdtree().range_neighbors(i, r))\n    {\n        const Scalar w = weight(points[i], points[j], r);\n        m      += w * (points[j] - points[i]);\n        C      += w * (points[j] - points[i]) * (points[j] - points[i]).transpose();\n        sum_w  += w;\n        ++nei_count;\n    }\n\n    if(nei_count < NEI_COUNT_MIN || sum_w < SUM_WEIGHT_MIN)\n        return PointWiseEstimationData::Invalid();\n\n    m /= sum_w;\n    C = C/sum_w - m * m.transpose();\n\n    // eigenvalues are positive and ordered\n    // eigenvectors are normalized\n    Eigen::SelfAdjointEigenSolver<Matrix3> solver(C);\n    Vector3 N = solver.eigenvectors().col(0);\n\n    const Scalar H = 8 * m.dot(N); // *  1/r^2\n\n    return PointWiseEstimationData(666, 666, -H, N, Vector3::Constant(666), Vector3::Constant(666), nei_count); // -1 due to convention\n}\n\n} // namespace pcp\n", "meta": {"hexsha": "4b3febed8f8aa476b5ab3046092b00dfa8046088", "size": 1284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "figures/src/PCP/Curvature/Methods/PCAPlane.cpp", "max_stars_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_stars_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T18:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T12:42:52.000Z", "max_issues_repo_path": "figures/src/PCP/Curvature/Methods/PCAPlane.cpp", "max_issues_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_issues_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-12T08:51:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T09:38:17.000Z", "max_forks_repo_path": "figures/src/PCP/Curvature/Methods/PCAPlane.cpp", "max_forks_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_forks_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T08:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T11:40:21.000Z", "avg_line_length": 27.9130434783, "max_line_length": 135, "alphanum_fraction": 0.6277258567, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.6654105653819836, "lm_q1q2_score": 0.6191367487200535}}
{"text": "// SPDX-License-Identifier: MIT\n// Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval\n\n#ifndef LSQ_SOLVER_H_7JQG4\n#define LSQ_SOLVER_H_7JQG4\n\n#include <Eigen/Dense>\n\n#include <zisa/config.hpp>\n#include <zisa/grid/grid.hpp>\n#include <zisa/math/poly2d.hpp>\n#include <zisa/reconstruction/stencil.hpp>\n#include <zisa/reconstruction/weno_poly.hpp>\n\nnamespace zisa {\n\n/// Solve the least-squares problem for the reconstruction.\n/** WENO-AO defines the reconstruction polynomial as the polynomial\n * which approximates the cell-averages on a given stencil the best, in a\n * least-squares sense.\n *\n * This class solves those LSQ problems.\n */\nclass LSQSolver {\nprivate:\n  using LDLT = Eigen::LDLT<Eigen::MatrixXd>;\n\npublic:\n  LSQSolver() = default;\n  LSQSolver(const std::shared_ptr<Grid> &grid, const Stencil &stencil);\n\n  /// Solve the LSQ problem with right-hand side `rhs`.\n  template <class Poly>\n  Poly solve(const array_const_view<double, 2, row_major> &rhs) const;\n\n  /// Indistinguishable by calls to the public interface.\n  bool operator==(const LSQSolver &other) const;\n\n  /// Can be distinguished by calls to the public interface.\n  bool operator!=(const LSQSolver &other) const;\n\nprivate:\n  template <class Poly>\n  Poly solve_impl(const array_const_view<double, 2, row_major> &rhs) const;\n\n  int n_dims() const;\n\nprivate:\n  std::shared_ptr<Grid> grid;\n  int_t i_cell;\n  int order;\n\n  LDLT ldlt;\n  Eigen::MatrixXd A;\n};\n\nEigen::MatrixXd assemble_weno_ao_matrix(const Grid &grid,\n                                        const Stencil &stencil);\n\nEigen::MatrixXd assemble_weno_ao_matrix(\n    const Grid &grid, const array_const_view<int_t, 1> &stencil, int order);\n\n} // namespace zisa\n#endif /* end of include guard */\n", "meta": {"hexsha": "c7498a171b3bc5e8d9ce7a40340855419f1f3484", "size": 1724, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/zisa/reconstruction/lsq_solver.hpp", "max_stars_repo_name": "1uc/ZisaFVM", "max_stars_repo_head_hexsha": "75fcedb3bece66499e011228a39d8a364b50fd74", "max_stars_repo_licenses": ["MIT"], "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/zisa/reconstruction/lsq_solver.hpp", "max_issues_repo_name": "1uc/ZisaFVM", "max_issues_repo_head_hexsha": "75fcedb3bece66499e011228a39d8a364b50fd74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/zisa/reconstruction/lsq_solver.hpp", "max_forks_repo_name": "1uc/ZisaFVM", "max_forks_repo_head_hexsha": "75fcedb3bece66499e011228a39d8a364b50fd74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T11:52:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T11:52:51.000Z", "avg_line_length": 26.5230769231, "max_line_length": 76, "alphanum_fraction": 0.722737819, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964035, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.619096544330908}}
{"text": "#include \"ugl/random/normal_distribution.h\"\n\n#include <cmath>\n#include <random>\n\n#include <Eigen/Eigenvalues>\n\n#include \"random_engine.h\"\n\nnamespace ugl::random\n{\n\nugl::MatrixD create_transform(const ugl::MatrixD& covariance)\n{\n    Eigen::SelfAdjointEigenSolver<ugl::MatrixD> eigen_solver(covariance);\n    return eigen_solver.eigenvectors() * eigen_solver.eigenvalues().cwiseSqrt().asDiagonal();\n}\n\nNormalDistribution<1>::NormalDistribution(double mean, double variance)\n    : mean_(mean)\n    , variance_(variance)\n    , stddev_(std::sqrt(variance))\n{\n}\n\ndouble NormalDistribution<1>::sample() const\n{\n    std::normal_distribution distribution{mean_, stddev_};\n    return distribution(internal::rng);\n}\n\ndouble NormalDistribution<1>::sample(double mean, double variance)\n{\n    std::normal_distribution distribution{mean, std::sqrt(variance)};\n    return distribution(internal::rng);\n}\n\n} // namespace ugl::random\n", "meta": {"hexsha": "07b745f2c4c5e6202ad3ce2fa96f821dc92d7b47", "size": 913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/random/normal_distribution.cpp", "max_stars_repo_name": "kullken/ugl", "max_stars_repo_head_hexsha": "ec8651967643d5cb8bd9ae9e39a082469e96841a", "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/random/normal_distribution.cpp", "max_issues_repo_name": "kullken/ugl", "max_issues_repo_head_hexsha": "ec8651967643d5cb8bd9ae9e39a082469e96841a", "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/random/normal_distribution.cpp", "max_forks_repo_name": "kullken/ugl", "max_forks_repo_head_hexsha": "ec8651967643d5cb8bd9ae9e39a082469e96841a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4102564103, "max_line_length": 93, "alphanum_fraction": 0.7447973713, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6190965417762168}}
{"text": "//\n// Helper utilities for simulators.\n//\n\n#pragma once\n\n#include <ilqr/ilqr_taylor_expansions.hh> // Definition of dynamics function.\n\n#include <Eigen/Dense>\n\n#include <functional>\n\nnamespace simulators\n{\n\ntemplate<int dim>\nusing Vector = Eigen::Matrix<double, dim, 1>;\n\n// Wrapper struct so we can use template paramters.\ntemplate<int xdim, int udim>\nstruct RK4 \n{\nusing Dynamics = std::function<Vector<xdim>(const Vector<xdim> &x, const Vector<udim> &u)>;\n\n// 4th order Runge-Kutta integration of an ODE given by dynamics.\nstatic Vector<xdim> rk4(const double dt,\n        const Vector<xdim> state, \n        const Vector<udim> control,\n        const Dynamics &dynamics) \n{\n\n    // This cannot be changed\n    constexpr double RK4_INTEGRATION_CONSTANT = 1.0/6.0;\n\n    // Formula from: http://mathworld.wolfram.com/Runge-KuttaMethod.html \n    const Vector<xdim> k1 = dynamics(state, control);\n    const Vector<xdim> k2 = dynamics(state + 0.5*dt*k1, control);\n    const Vector<xdim> k3 = dynamics(state + 0.5*dt*k2, control);\n    const Vector<xdim> k4 = dynamics(state + dt*k3, control);\n\n    const Vector<xdim> result = state + RK4_INTEGRATION_CONSTANT*dt*(k1 + 2.0*(k2 + k3) + k4);\n    return result;\n}\n\n};\n\nconstexpr double INTEGRATION_FREQUENCY = 5;\nconstexpr double MIN_INTEGRATION_DT = 1e-2;\n\n\nEigen::VectorXd step(const Eigen::VectorXd &state, const Eigen::VectorXd &control, \n                     const double dt, const ilqr::DynamicsFunc &dynamics, \n                     const double min_integration_dt = MIN_INTEGRATION_DT,\n                     const double integration_frequency  = INTEGRATION_FREQUENCY\n                     );\n\n} // namespace simulators\n", "meta": {"hexsha": "cc30175f1ae024fdcb69f9dc575c82894278519d", "size": 1664, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/experiments/simulators/simulator_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/experiments/simulators/simulator_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/experiments/simulators/simulator_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": 28.6896551724, "max_line_length": 94, "alphanum_fraction": 0.6826923077, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6190965365014427}}
{"text": "//\n// Created by sam on 04/12/17.\n//\n\n#ifndef PERCEPTRON_NEURON_HPP\n#define PERCEPTRON_NEURON_HPP\n\n#include <iostream>\n#include <vector>\n#include <boost/numeric/ublas/vector.hpp>\n\n\nclass Neuron {\nprivate:\n    boost::numeric::ublas::vector<double> weights;\n    double gradient;\n\n    double (*functionAct)(double);\n\npublic:\n    Neuron(const boost::numeric::ublas::vector<double> &weights, double (*functionAct)(double));\n\n    /**\n     *\n     * @param entries\n     * @return the output of the neuron with the function\n     */\n    double getOutput(boost::numeric::ublas::vector<double> const &entries);\n\n    void correctWeitghs(boost::numeric::ublas::vector<double> const &e, double result, double expected);\n\n    const boost::numeric::ublas::vector<double> &getWeights() const;\n\n    void setWeights(const boost::numeric::ublas::vector<double> &weights);\n\n    void setFunctionAct(double (*functionAct)(double));\n};\n\n\n#endif //PERCEPTRON_NEURON_HPP\n", "meta": {"hexsha": "b29b66634b51bf7f644f13125e3ca4bd033cef6b", "size": 944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/perceptron/Neuron.hpp", "max_stars_repo_name": "SamBlaise/perceptron_cpp", "max_stars_repo_head_hexsha": "e2a7375f8254e2f683454f42e4c9089d99e59d66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/perceptron/Neuron.hpp", "max_issues_repo_name": "SamBlaise/perceptron_cpp", "max_issues_repo_head_hexsha": "e2a7375f8254e2f683454f42e4c9089d99e59d66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-07T21:44:33.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-13T23:10:24.000Z", "max_forks_repo_path": "src/perceptron/Neuron.hpp", "max_forks_repo_name": "SamBlaise/perceptron_cpp", "max_forks_repo_head_hexsha": "e2a7375f8254e2f683454f42e4c9089d99e59d66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0243902439, "max_line_length": 104, "alphanum_fraction": 0.7002118644, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515259, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6190965365014426}}
{"text": "// Boost.Geometry\n// Unit Test\n\n// Copyright (c) 2016-2017 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <sstream>\n\n#include \"test_formula.hpp\"\n#include \"inverse_cases.hpp\"\n\n#include <boost/geometry/formulas/vincenty_inverse.hpp>\n#include <boost/geometry/formulas/thomas_inverse.hpp>\n#include <boost/geometry/formulas/andoyer_inverse.hpp>\n\n\nvoid check_inverse(std::string const& name,\n                   expected_results const& results,\n                   bg::formula::result_inverse<double> const& result,\n                   expected_result const& expected,\n                   expected_result const& reference,\n                   double reference_error)\n{\n    std::stringstream ss;\n    ss << \"(\" << results.p1.lon << \" \" << results.p1.lat << \")->(\" << results.p2.lon << \" \" << results.p2.lat << \")\";\n\n    check_one(name + \"_d  \" + ss.str(),\n              result.distance, expected.distance, reference.distance, reference_error);\n    check_one(name + \"_a  \" + ss.str(),\n              result.azimuth, expected.azimuth, reference.azimuth, reference_error, true);\n    check_one(name + \"_ra \" + ss.str(),\n              result.reverse_azimuth, expected.reverse_azimuth, reference.reverse_azimuth, reference_error, true);\n    check_one(name + \"_rl \" + ss.str(),\n              result.reduced_length, expected.reduced_length, reference.reduced_length, reference_error);\n    check_one(name + \"_gs \" + ss.str(),\n              result.geodesic_scale, expected.geodesic_scale, reference.geodesic_scale, reference_error);\n}\n\nvoid test_all(expected_results const& results)\n{\n    double const d2r = bg::math::d2r<double>();\n    double const r2d = bg::math::r2d<double>();\n\n    double lon1r = results.p1.lon * d2r;\n    double lat1r = results.p1.lat * d2r;\n    double lon2r = results.p2.lon * d2r;\n    double lat2r = results.p2.lat * d2r;\n\n    // WGS84\n    bg::srs::spheroid<double> spheroid(6378137.0, 6356752.3142451793);\n\n    bg::formula::result_inverse<double> result_v, result_t, result_a;\n\n    typedef bg::formula::vincenty_inverse<double, true, true, true, true, true> vi_t;\n    result_v = vi_t::apply(lon1r, lat1r, lon2r, lat2r, spheroid);\n    result_v.azimuth *= r2d;\n    result_v.reverse_azimuth *= r2d;\n    check_inverse(\"vincenty\", results, result_v, results.vincenty, results.reference, 0.0000001);\n\n    typedef bg::formula::thomas_inverse<double, true, true, true, true, true> th_t;\n    result_t = th_t::apply(lon1r, lat1r, lon2r, lat2r, spheroid);\n    result_t.azimuth *= r2d;\n    result_t.reverse_azimuth *= r2d;\n    check_inverse(\"thomas\", results, result_t, results.thomas, results.reference, 0.00001);\n\n    typedef bg::formula::andoyer_inverse<double, true, true, true, true, true> an_t;\n    result_a = an_t::apply(lon1r, lat1r, lon2r, lat2r, spheroid);\n    result_a.azimuth *= r2d;\n    result_a.reverse_azimuth *= r2d;\n    check_inverse(\"andoyer\", results, result_a, results.andoyer, results.reference, 0.001);\n}\n\nint test_main(int, char*[])\n{\n    for (size_t i = 0; i < expected_size; ++i)\n    {\n        test_all(expected[i]);\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "e72cf3bb5bd54817b81e4e70b511f863091f5ccb", "size": 3308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/test/formulas/inverse.cpp", "max_stars_repo_name": "BALL-Contrib/contrib_boost_1.66.0", "max_stars_repo_head_hexsha": "122e8c80115a62b635c36356375a3a1bc5ae0d02", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 918.0, "max_stars_repo_stars_event_min_datetime": "2016-12-22T02:53:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:21:35.000Z", "max_issues_repo_path": "libs/geometry/test/formulas/inverse.cpp", "max_issues_repo_name": "BALL-Contrib/contrib_boost_1.66.0", "max_issues_repo_head_hexsha": "122e8c80115a62b635c36356375a3a1bc5ae0d02", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 203.0, "max_issues_repo_issues_event_min_datetime": "2016-12-27T12:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:46:55.000Z", "max_forks_repo_path": "libs/geometry/test/formulas/inverse.cpp", "max_forks_repo_name": "BALL-Contrib/contrib_boost_1.66.0", "max_forks_repo_head_hexsha": "122e8c80115a62b635c36356375a3a1bc5ae0d02", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 122.0, "max_forks_repo_forks_event_min_datetime": "2016-12-22T17:38:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T14:25:49.000Z", "avg_line_length": 37.5909090909, "max_line_length": 117, "alphanum_fraction": 0.6729141475, "num_tokens": 900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6190965315574517}}
{"text": "\n#include \"CubicInterpolation/FindParameter.hpp\"\n\n#include <boost/math/tools/roots.hpp>\n#include <cassert>\n\nnamespace cubic_splines {\nnamespace detail {\ndouble _find_parameter(std::function<double(double)> const &f,\n                        std::function<double(double)> const &df, double x_guess,\n                        double lower, double upper) {\n  assert(((void)\"find_parameter call is not well defined\", lower < upper));\n  auto func = [&f, &df](double x) { return std::make_tuple(f(x), df(x)); };\n\n  if (std::isnan(x_guess)) {\n    auto bisec_tolerance = (upper - lower) * 1e-2;\n    auto tol = [&bisec_tolerance](double min, double max) {\n      return (std::abs(max - min) < bisec_tolerance) ? true : false;\n    };\n    std::tie(lower, upper) = boost::math::tools::bisect(f, lower, upper, tol);\n    x_guess = (lower + upper) / 2;\n    if (lower == upper)\n      return lower;\n  }\n\n  return boost::math::tools::newton_raphson_iterate(func, x_guess, lower, upper, 20);\n}\n} // namespace detail\n} // namespace cubic_splines\n", "meta": {"hexsha": "6b7470fb472a03c24d34a0204801b6c589b34e1e", "size": 1022, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/detail/FindParameter.cxx", "max_stars_repo_name": "maxnoe/cubic_interpolation", "max_stars_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-07T15:35:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T06:59:47.000Z", "max_issues_repo_path": "src/detail/FindParameter.cxx", "max_issues_repo_name": "maxnoe/cubic_interpolation", "max_issues_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-02-12T11:46:11.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T09:03:01.000Z", "max_forks_repo_path": "src/detail/FindParameter.cxx", "max_forks_repo_name": "maxnoe/cubic_interpolation", "max_forks_repo_head_hexsha": "5e272ed3b2697a72bdbc4978b7eb7494c333bd5f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-02-12T14:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-19T13:33:52.000Z", "avg_line_length": 34.0666666667, "max_line_length": 85, "alphanum_fraction": 0.6418786693, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6190883128522385}}
{"text": "#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n\nstd::complex<long double> ;\n\nComplexPlane::ComplexPlane()\n{\n\n    // Implementation of default constructor\n    // set up min/max/len\n    : xmin(-10)\n    , xmax(10)\n    , xlen(20)\n    , ymin(-10)\n    , ymax(10)\n    , ylen(20)\n\n{};\n\n    using namespace boost::numeric::ublas;\n    slice real (xmin, xmax, xlen);\n    slice imag (ymin, ymax, ylen);\n\n    for (unsigned r = 0; r < real.size(); ++ r) {\n        for (unsigned c = 0; c < imag.size(); ++ c){\n            this-> plane(real,imag) = real(r)+imag(c)*1i;\n        }\n    }\n}\n", "meta": {"hexsha": "c2940476513fe4b7eba9650b523f811b40dacd2f", "size": 648, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/blas/ComplexPlane.cc", "max_stars_repo_name": "chapman-cs510-2016f/cw-13-needcoffee", "max_stars_repo_head_hexsha": "a0455d507e6e10271bec593fcb43c001ae2aff2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/blas/ComplexPlane.cc", "max_issues_repo_name": "chapman-cs510-2016f/cw-13-needcoffee", "max_issues_repo_head_hexsha": "a0455d507e6e10271bec593fcb43c001ae2aff2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/blas/ComplexPlane.cc", "max_forks_repo_name": "chapman-cs510-2016f/cw-13-needcoffee", "max_forks_repo_head_hexsha": "a0455d507e6e10271bec593fcb43c001ae2aff2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.25, "max_line_length": 57, "alphanum_fraction": 0.5740740741, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6190882919730257}}
{"text": "#include \"NumUtils.h\"\n\n#include <NTL/RR.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <cassert>\n#include <cmath>\n\n#include \"CZZ.h\"\n\nvoid NumUtils::sampleGauss(ZZX& res, const long& size, const double& stdev) {\n\tstatic double const Pi = 4.0 * atan(1.0);\n\tstatic long const bignum = 0xfffffff;\n\tres.SetLength(size);\n\n\tfor (long i = 0; i < size; i+=2) {\n\t\tdouble r1 = (1 + RandomBnd(bignum)) / ((double)bignum + 1);\n\t\tdouble r2 = (1 + RandomBnd(bignum)) / ((double)bignum + 1);\n\t\tdouble theta=2 * Pi * r1;\n\t\tdouble rr= sqrt(-2.0 * log(r2)) * stdev;\n\t\tassert(rr < 8 * stdev); // sanity-check, no more than 8 standard deviations\n\t\t// Generate two Gaussians RV's, rounded to integers\n\t\tlong x1 = (long) floor(rr * cos(theta) + 0.5);\n\t\tSetCoeff(res, i, x1);\n\t\tif(i + 1 < size) {\n\t\t\tlong x2 = (long) floor(rr * sin(theta) + 0.5);\n\t\t\tSetCoeff(res, i + 1, x2);\n\t\t}\n\t}\n}\n\nvoid NumUtils::sampleHWT(ZZX& res, const long& size, const long& h) {\n\tres.SetLength(size);\n\tlong idx = 0;\n\tZZ tmp = RandomBits_ZZ(h);\n\twhile(idx < h) {\n\t\tlong i = RandomBnd(size);\n\t\tif(res.rep[i] == 0) {\n\t\t\tres.rep[i] = (bit(tmp, idx) == 0) ? ZZ(1) : ZZ(-1);\n\t\t\tidx++;\n\t\t}\n\t}\n}\n\nvoid NumUtils::sampleZO(ZZX& res, const long& size) {\n\tres.SetLength(size);\n\tZZ tmp = RandomBits_ZZ(2 * size);\n\tfor (long i = 0; i < size; ++i) {\n\t\tres.rep[i] = (bit(tmp, 2 * i) == 0) ? ZZ(0) : (bit(tmp, 2 * i + 1) == 0) ? ZZ(1) : ZZ(-1);\n\t}\n}\n\nvoid NumUtils::sampleBinary(ZZX& res, const long& size, const long& h) {\n\tres.SetLength(size);\n\tlong idx = 0;\n\twhile(idx < h) {\n\t\tlong i = RandomBnd(size);\n\t\tif(res.rep[i] == 0) {\n\t\t\tres.rep[i] = ZZ(1);\n\t\t\tidx++;\n\t\t}\n\t}\n}\n\nvoid NumUtils::sampleBinary(ZZX& res, const long& size) {\n\tres.SetLength(size);\n\tZZ tmp = RandomBits_ZZ(size);\n\tfor (long i = 0; i < size; ++i) {\n\t\tres.rep[i] = (bit(tmp, i) == 0) ? ZZ(0) : ZZ(1);\n\t}\n}\n\nvoid NumUtils::sampleUniform2(ZZX& res, const long& size, const long& logBnd) {\n\tres.SetLength(size);\n\tfor (long i = 0; i < size; i++) {\n\t\tres.rep[i] = RandomBits_ZZ(logBnd);\n\t}\n}\n\nvoid NumUtils::fftRaw(CZZ*& vals, const long& size, SchemeAux& aux, const bool& isForward) {\n\tfor (long i = 1, j = 0; i < size; ++i) {\n\t\tlong bit = size >> 1;\n\t\tfor (; j >= bit; bit>>=1) {\n\t\t\tj -= bit;\n\t\t}\n\t\tj += bit;\n\t\tif(i < j) {\n\t\t\tswap(vals[i], vals[j]);\n\t\t}\n\t}\n\tif(isForward) {\n\t\tfor (long len = 2; len <= size; len <<= 1) {\n\t\t\tlong MoverLen = aux.M / len;\n\t\t\tfor (long i = 0; i < size; i += len) {\n\t\t\t\tfor (long j = 0; j < len / 2; ++j) {\n\t\t\t\t\tCZZ u = vals[i + j];\n\t\t\t\t\tCZZ v = vals[i + j + len / 2];\n\t\t\t\t\tRR tmp1 = to_RR(v.r) * (aux.ksiPowsr[j * MoverLen] + aux.ksiPowsi[j * MoverLen]);\n\t\t\t\t\tRR tmpr = tmp1 - to_RR(v.r + v.i) * aux.ksiPowsi[j * MoverLen];\n\t\t\t\t\tRR tmpi = tmp1 + to_RR(v.i - v.r) * aux.ksiPowsr[j * MoverLen];\n\t\t\t\t\tv.r = to_ZZ(tmpr);\n\t\t\t\t\tv.i = to_ZZ(tmpi);\n\t\t\t\t\tvals[i + j] = u + v;\n\t\t\t\t\tvals[i + j + len / 2] = u - v;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (long len = 2; len <= size; len <<= 1) {\n\t\t\tlong MoverLen = aux.M / len;\n\t\t\tfor (long i = 0; i < size; i += len) {\n\t\t\t\tfor (long j = 0; j < len / 2; ++j) {\n\t\t\t\t\tCZZ u = vals[i + j];\n\t\t\t\t\tCZZ v = vals[i + j + len / 2];\n\t\t\t\t\tRR tmp1 = to_RR(v.r) * (aux.ksiPowsr[(len - j) * MoverLen] + aux.ksiPowsi[(len - j) * MoverLen]);\n\t\t\t\t\tRR tmpr = tmp1 - to_RR(v.r + v.i) * aux.ksiPowsi[(len - j) * MoverLen];\n\t\t\t\t\tRR tmpi = tmp1 + to_RR(v.i - v.r) * aux.ksiPowsr[(len - j) * MoverLen];\n\t\t\t\t\tv.r = to_ZZ(tmpr);\n\t\t\t\t\tv.i = to_ZZ(tmpi);\n\t\t\t\t\tvals[i + j] = u + v;\n\t\t\t\t\tvals[i + j + len / 2] = u - v;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid NumUtils::fft(CZZ*& vals, const long& size, SchemeAux& aux) {\n\tfftRaw(vals, size, aux, true);\n}\n\nvoid NumUtils::fftInv(CZZ*& vals, const long& size, SchemeAux& aux) {\n\tfftRaw(vals, size, aux, false);\n\tlong logSize = log2(size);\n\tfor (long i = 0; i < size; ++i) {\n\t\tvals[i] >>= logSize;\n\t}\n}\n\nvoid NumUtils::fftInvLazy(CZZ*& vals, const long& size, SchemeAux& aux) {\n\tfftRaw(vals, size, aux, false);\n}\n\nvoid NumUtils::fftSpecial(CZZ*& vals, const long& size, SchemeAux& aux) {\n\tfor (int i = 1, j = 0; i < size; ++i) {\n\t\tlong bit = size >> 1;\n\t\tfor (; j>=bit; bit>>=1) {\n\t\t\tj -= bit;\n\t\t}\n\t\tj += bit;\n\t\tif(i < j) {\n\t\t\tswap(vals[i], vals[j]);\n\t\t}\n\t}\n\tfor (long len = 2; len <= size; len <<= 1) {\n\t\tlong loglen = log2(len);\n\t\tlong Mover2Len = aux.M / len / 2;\n\t\tfor (long i = 0; i < size; i += len) {\n\t\t\tfor (long j = 0; j < len / 2; ++j) {\n\t\t\t\tCZZ u = vals[i + j];\n\t\t\t\tCZZ v = vals[i + j + len / 2];\n\t\t\t\tRR tmp1 = to_RR(v.r) * (aux.ksiPowsr[(2 * j + 1) * Mover2Len] + aux.ksiPowsi[(2 * j + 1) * Mover2Len]);\n\t\t\t\tRR tmpr = tmp1 - to_RR(v.r + v.i) * aux.ksiPowsi[(2 * j + 1) * Mover2Len];\n\t\t\t\tRR tmpi = tmp1 + to_RR(v.i - v.r) * aux.ksiPowsr[(2 * j + 1) * Mover2Len];\n\t\t\t\tv.r = to_ZZ(tmpr);\n\t\t\t\tv.i = to_ZZ(tmpi);\n\t\t\t\tvals[i + j] = u + v;\n\t\t\t\tvals[i + j + len / 2] = u - v;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid NumUtils::fftSpecialInv(CZZ*& vals, const long& size, SchemeAux& aux) {\n\tfftRaw(vals, size, aux, false);\n\tlong logsize = log2(size);\n\tlong Mover2size = aux.M / size / 2;\n\tfor (long i = 0; i < size; ++i) {\n\t\tRR tmp1 = to_RR(vals[i].r) * (aux.ksiPowsr[(2 * size - i) * Mover2size] + aux.ksiPowsi[(2 * size - i) * Mover2size]);\n\t\tRR tmpr = tmp1 - to_RR(vals[i].r + vals[i].i) * aux.ksiPowsi[(2 * size - i) * Mover2size];\n\t\tRR tmpi = tmp1 + to_RR(vals[i].i - vals[i].r) * aux.ksiPowsr[(2 * size - i) * Mover2size];\n\t\tvals[i].r = to_ZZ(tmpr);\n\t\tvals[i].i = to_ZZ(tmpi);\n\t\tvals[i] >>= logsize;\n\t}\n}\n", "meta": {"hexsha": "b90708a1f6b4ba7168b185764839f85b761c5941", "size": 5365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NumUtils.cpp", "max_stars_repo_name": "K-miran/HELR", "max_stars_repo_head_hexsha": "c94951f2691d55defc82f95d3144c831eb6c8796", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:56:15.000Z", "max_issues_repo_path": "src/NumUtils.cpp", "max_issues_repo_name": "yuejiayang/HELR", "max_issues_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-25T02:54:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-09T10:48:39.000Z", "max_forks_repo_path": "src/NumUtils.cpp", "max_forks_repo_name": "yuejiayang/HELR", "max_forks_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-01-20T13:31:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T02:20:39.000Z", "avg_line_length": 28.6898395722, "max_line_length": 119, "alphanum_fraction": 0.5455731594, "num_tokens": 2151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.6190744548378642}}
{"text": "\n#include \"glog/logging.h\"\n#include <armadillo>\n\n#include \"pclem_math.h\"\n\n#include \"matrix33.h\"\n\nnamespace pclem {\n    Matrix33::Matrix33() : values{} {}\n\n    // The values are given row-major.\n    Matrix33::Matrix33(const std::array<double,9>& values) : values(values) {}\n\n    double Matrix33::get_element(const int& i, const int& j) const {\n        return values[i*3 + j];\n    }\n\n    Matrix33 Matrix33::identity() {\n        return Matrix33({1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0});\n    }\n\n    bool Matrix33::operator==(const Matrix33& other) const {\n        for(int i=0; i < 9; i++) {\n            if(!approximatelyEqual(values[i], other.values[i], 1e-10)) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    Vector3 Matrix33::get_column(int i) const {\n        return Vector3(values[i], values[3+i], values[6+i]);\n    }\n\n    double Matrix33::trace() const {\n        return values[0] + values[4] + values[8];\n    }\n\n    // Returns the eigenvalues in descending order. The first column\n    // of the matrix is the eigenvector of the largest eigenvalue, and\n    // so on.\n    std::pair<Vector3, Matrix33> Matrix33::eigen_decomposition() const {\n\n        VLOG(10) << \"Extracting eigenvalues...\";\n\n        if(symetric(1e-10)) {\n            return symetrical_eigen_decomposition();\n        } else {\n            return general_eigen_decomposition();\n        }\n    }\n\n\n    std::pair<Vector3, Matrix33> Matrix33::symetrical_eigen_decomposition() const {\n        arma::mat33 arma_cov_mat(values.data());\n        arma::vec arma_eigvals;\n        arma::mat arma_eigvecs;\n\n        if(!arma::eig_sym(arma_eigvals, arma_eigvecs, arma_cov_mat)) {\n            LOG(WARNING) << \"Eigenvalues decomposition failed.\";\n        }\n\n        Vector3 eigvals;\n        std::array<double,9> eigvecs_values;\n        for(int i=0; i < 3; i++) {\n            eigvals[i] = arma_eigvals[2-i];\n\n            for(int j=0; j < 3; j++) {\n                eigvecs_values[i*3 + j] = arma_eigvecs(i,2-j);\n            }\n        }\n\n        return std::make_pair(eigvals, Matrix33(eigvecs_values));\n    }\n\n    std::pair<Vector3, Matrix33> Matrix33::general_eigen_decomposition() const {\n        arma::mat33 arma_cov_mat(values.data());\n        arma::cx_vec arma_eigvals;\n        arma::cx_mat arma_eigvecs;\n\n        if(!arma::eig_gen(arma_eigvals, arma_eigvecs, arma_cov_mat)) {\n            LOG(WARNING) << \"Eigenvalues decomposition failed.\";\n        }\n\n        Vector3 eigvals;\n        std::array<double,9> eigvecs_values;\n        for(int i=0; i < 3; i++) {\n            eigvals[i] = arma_eigvals[2-i].real();\n\n            for(int j=0; j < 3; j++) {\n                eigvecs_values[i*3 + j] = arma_eigvecs(j,i).real();\n            }\n        }\n\n        return std::make_pair(eigvals, Matrix33(eigvecs_values));\n    }\n\n    std::array<double,9> Matrix33::inverse() const {\n        VLOG(11) << \"Inverting matrix...\";\n\n        arma::mat33 arma_cov_mat(values.data());\n        arma::mat33 arma_inv_of_cov = arma::pinv(arma_cov_mat + arma::eye(3,3));\n\n        VLOG(11) << \"PseudoInverse error \" << arma::norm(arma_cov_mat*arma_inv_of_cov - arma::eye(3,3));\n\n        std::array<double,9> inverse;\n        for(auto i = 0; i < 3; i++) {\n            for(auto j = 0; j < 3; j++) {\n                inverse[i*3 + j] = arma_inv_of_cov(i,j);\n            }\n        }\n\n        VLOG(11) << \"Done inverting matrix.\";\n        return inverse;\n    }\n\n    double Matrix33::det() const {\n        return get_element(0,0) * (get_element(1,1) * get_element(2,2) - get_element(2, 1) * get_element(1,2)) -\n            get_element(0,1) * (get_element(1,0) * get_element(2,2) - get_element(1,2) * get_element(2,0)) +\n            get_element(0,2) * (get_element(1,0) * get_element(2,1) + get_element(2,0) * get_element(1,1));\n    }\n\n    std::ostream& operator<<(std::ostream& os, const Matrix33& v) {\n        for(int i=0; i < 8; i++) {\n            os << v.values[i] << \",\";\n        }\n        os << v.values[8];\n    }\n\n    void Matrix33::set_element(const int& i, const int& j, const double value) {\n        values[i*3 + j] = value;\n    }\n\n    std::ofstream& operator<<(std::ofstream& ofs, const Matrix33& v) {\n        for(int i=0; i < 8; i++) {\n            ofs << v.values[i] << \",\";\n        }\n        ofs << v.values[8];\n\n        return ofs;\n    }\n\n    bool Matrix33::symetric(double epsilon) const {\n        for(int i = 0; i < 3; i++) {\n            for(int j = 0; j < 3; j++) {\n                if(!approximatelyEqual(get_element(i, j), get_element(i, j), epsilon)) {\n                        return false;\n                }\n            }\n        }\n\n        return true;\n    }\n\n\n    Matrix33 Matrix33::zeros() {\n        return Matrix33({0.0});\n    }\n}\n", "meta": {"hexsha": "95f35f57b860c05fb3544999d22cdc0609ca2562", "size": 4711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pclem_lib/src/matrix33.cpp", "max_stars_repo_name": "davidlandry93/pclem", "max_stars_repo_head_hexsha": "20c10eddae1b226d83c89f9ef15acb121b29a421", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pclem_lib/src/matrix33.cpp", "max_issues_repo_name": "davidlandry93/pclem", "max_issues_repo_head_hexsha": "20c10eddae1b226d83c89f9ef15acb121b29a421", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-11-16T19:08:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-12T02:05:36.000Z", "max_forks_repo_path": "pclem_lib/src/matrix33.cpp", "max_forks_repo_name": "davidlandry93/pclem", "max_forks_repo_head_hexsha": "20c10eddae1b226d83c89f9ef15acb121b29a421", "max_forks_repo_licenses": ["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.2608695652, "max_line_length": 112, "alphanum_fraction": 0.5421354277, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.6190744415348717}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>, Randi Cabezas <rcabezas@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <dpMM/basemeasure.hpp>\n#include <dpMM/niw.hpp>\n\n/*\n * NIW base measure; integrates over Normal distribution parameters\n */\ntemplate<typename T>\nclass NiwMarginalized : public BaseMeasure<T>\n{\npublic:\n  NIW<T> niw0_;\n  NIW<T> niw_;\n\n  NiwMarginalized(const NIW<T>& niw);\n  ~NiwMarginalized();\n\n  virtual baseMeasureType getBaseMeasureType() const {return(NIW_MARGINALIZED); }\n\n  virtual BaseMeasure<T>* copy();\n\n  T logLikelihood(const Matrix<T,Dynamic,1>& x) const;\n\n  void posterior(const Matrix<T,Dynamic,Dynamic>& x, const VectorXu& z,\n      uint32_t k);\n\n  T logPdfUnderPrior() const;\n\n  void print() const ;\n  virtual uint32_t getDim() const {return(uint32_t(niw_.D_));};\n};\n\n/*\n * NIW base measure; samples Normal distribution parameters\n */\ntemplate<typename T>\nclass NiwSampled : public BaseMeasure<T>\n{\npublic:\n  NIW<T> niw0_;\n  Normal<T> normal_;\n\n  NiwSampled(const NIW<T>& niw);\n  NiwSampled(const NIW<T>& niw, const Normal<T> &normal);\n  ~NiwSampled();\n\n  virtual baseMeasureType getBaseMeasureType() const {return(NIW_SAMPLED); }\n\n  virtual BaseMeasure<T>* copy();\n  virtual NiwSampled<T>* copyNative();\n\n  T logLikelihood(const Matrix<T,Dynamic,1>& x) const;\n  T logLikelihood(const Matrix<T,Dynamic,Dynamic>& x, uint32_t i) const\n    {return logLikelihood(x.col(i));};\n  // assumes vector [N, sum(x), flatten(sum(outer(x,x)))]\n  T logLikelihoodFromSS(const Matrix<T,Dynamic,1>& x) const;\n  void posterior(const Matrix<T,Dynamic,Dynamic>& x, const VectorXu& z,\n    uint32_t k);\n  void posterior(const vector<Matrix<T,Dynamic,Dynamic> >&x, const\n      VectorXu& z, uint32_t k);\n  void posteriorFromSS(const vector<Matrix<T,Dynamic,1> >&x, const\n      VectorXu& z, uint32_t k);\n  void posteriorFromSS(const Matrix<T,Dynamic,1> &x);\n  void sample();\n\n\n  T logPdfUnderPrior() const;\n  T logPdfUnderPriorMarginalized() const;\n  T logPdfUnderPriorMarginalizedMerged(const shared_ptr<NiwSampled<T> >& other) const;\n\n  T logPdfUnderPriorMarginalized(const Matrix<T,Dynamic,1>& x) {return 0.;};\n\n  virtual NiwSampled<T>* merge(const NiwSampled<T>& other);\n  void fromMerge(const NiwSampled<T>& niwA, const NiwSampled<T>& niwB);\n\n  void print() const;\n  virtual uint32_t getDim() const {return(uint32_t(normal_.D_));};\n\n  const Matrix<T,Dynamic,Dynamic>& scatter() const {return niw0_.scatter();};\n  const Matrix<T,Dynamic,1>& mean() const {return niw0_.mean();};\n  T count() const {return niw0_.count();};\n//  T& count() {return niw0_.count_;};\n  const Matrix<T,Dynamic,1>& getMean() const {return normal_.mu_;};\n\n  const Matrix<T,Dynamic,Dynamic>& Sigma() const {return normal_.Sigma();};\nprivate:\n\n};\n\ntypedef NiwSampled<double> NiwSampledd;\ntypedef NiwSampled<float> NiwSampledf;\n\n// ---------------------------------------------------------------------------\n\n\ntemplate<typename T>\nNiwSampled<T>::NiwSampled(const NIW<T>& niw)\n  : niw0_(niw), normal_(niw0_.sample())\n{};\n\ntemplate<typename T>\nNiwSampled<T>::NiwSampled(const NIW<T>& niw, const Normal<T> &normal)\n : niw0_(niw), normal_(normal)\n{};\n\ntemplate<typename T>\nNiwSampled<T>::~NiwSampled()\n{};\n\ntemplate<typename T>\nBaseMeasure<T>* NiwSampled<T>::copy()\n{\n  NiwSampled<T>* niwSampled = new NiwSampled<T>(niw0_);\n  niwSampled->normal_ = normal_;\n  return niwSampled;\n};\n\ntemplate<typename T>\nNiwSampled<T>* NiwSampled<T>::copyNative()\n{\n  NiwSampled<T>* niwSampled = new NiwSampled<T>(niw0_);\n  niwSampled->normal_ = normal_;\n  return niwSampled;\n};\n\ntemplate<typename T>\nT NiwSampled<T>::logLikelihood(const Matrix<T,Dynamic,1>& x) const\n{\n//  normal_.print();\n  T logLike = normal_.logPdf(x);\n//  cout<<x.transpose()<<\" -> \" <<logLike<<endl;\n//  cout<<x.transpose()<<\" -> \" <<normal_.logPdfSlower(x)<<endl;\n  return logLike;\n};\n\n// assumes vector [N, sum(x), flatten(sum(outer(x,x)))]\ntemplate<typename T>\nT NiwSampled<T>::logLikelihoodFromSS(const Matrix<T,Dynamic,1>& x) const\n{\n//  normal_.print();\n  uint32_t D = niw0_.D_;\n  T count = x(0);\n  Matrix<T,Dynamic,1> mean(D);\n  if(count>0)\n\t  mean = x.middleRows(1,D)/count;\n  else\n\t  mean = Matrix<T,Dynamic,1>::Zero(D); //this should not matter since everything gets multiplied by 0 counts\n\n  //NOTE: Eigen::Map does not like const data, so this cast is needed to strip const data from input\n  //alternatively the input could be changed to non-const, but this is cleaner from the outside\n  T* datPtr = const_cast<T*>(&(x.data()[(D+1)]));\n  Matrix<T,Dynamic,Dynamic> scatter = \n    Map<Matrix<T,Dynamic,Dynamic> >(datPtr,D,D);\n  scatter -= (mean*mean.transpose())*count;\n\n  T logLike = normal_.logPdf(scatter,mean,count);\n  //  cout<<x.transpose()<<\" -> \" <<logLike<<endl;\n  //  cout<<x.transpose()<<\" -> \" <<normal_.logPdfSlower(x)<<endl;\n  return logLike;\n};\n\ntemplate<typename T>\nvoid NiwSampled<T>::posterior(const Matrix<T,Dynamic,Dynamic>& x,\n    const VectorXu& z, uint32_t k)\n{\n  normal_ = niw0_.posterior(x,z,k).sample();\n};\n\ntemplate<typename T>\nvoid NiwSampled<T>::posterior(const vector<Matrix<T,Dynamic,Dynamic> >&x,\n\tconst VectorXu& z, uint32_t k)\n{\n\tnormal_ = niw0_.posterior(x,z,k).sample();\n}\n\ntemplate<typename T>\nvoid NiwSampled<T>::posteriorFromSS(const vector<Matrix<T,Dynamic,1> > &x, const VectorXu& z, uint32_t k)\n{\n\tnormal_ = niw0_.posteriorFromSS(x,z,k).sample();\n}\n\ntemplate<typename T>\nvoid NiwSampled<T>::posteriorFromSS(const Matrix<T,Dynamic,1> &x)\n{\n\tnormal_ = niw0_.posteriorFromSS(x).sample();\n}\n\ntemplate<typename T>\nT NiwSampled<T>::logPdfUnderPrior() const\n{\n  return niw0_.logPdf(normal_);\n};\n\ntemplate<typename T>\nT NiwSampled<T>::logPdfUnderPriorMarginalized() const\n{\n  // evaluates log pdf of sufficient statistics stored within niw0_\n//  niw0_.print();\n  return niw0_.logPdfMarginalized();\n};\n\ntemplate<typename T>\nT NiwSampled<T>::logPdfUnderPriorMarginalizedMerged(\n    const shared_ptr<NiwSampled<T> >& other) const\n{\n  return niw0_.logPdfUnderPriorMarginalizedMerged(other->niw0_);\n};\n\ntemplate<typename T>\nvoid NiwSampled<T>::fromMerge(const NiwSampled<T>& niwA,\n  const NiwSampled<T>& niwB)\n{\n  niw0_.fromMerge(niwA.niw0_,niwB.niw0_);\n  normal_ = niw0_.posterior().sample();\n};\n\ntemplate<typename T>\nNiwSampled<T>* NiwSampled<T>::merge(const NiwSampled<T>& other)\n{\n  NiwSampled<T>* newNiw = this->copyNative();\n  newNiw->niw0_.fromMerge(niw0_,other.niw0_);\n  newNiw->sample();\n  return newNiw;\n};\n\n\ntemplate<typename T>\nvoid NiwSampled<T>::sample()\n{\n  normal_ = niw0_.posterior().sample();\n};\n\ntemplate<typename T>\nvoid NiwSampled<T>::print() const\n{\n  niw0_.posterior().print();\n  normal_.print();\n};\n\n// ----------------------------------------------------------------------------\n\ntemplate<typename T>\nNiwMarginalized<T>::NiwMarginalized(const NIW<T>& niw)\n  : niw0_(niw),niw_(niw)\n{};\n\ntemplate<typename T>\nNiwMarginalized<T>::~NiwMarginalized()\n{};\n\ntemplate<typename T>\nBaseMeasure<T>* NiwMarginalized<T>::copy()\n{\n  return new NiwMarginalized<T>(niw0_);\n};\n\ntemplate<typename T>\nT NiwMarginalized<T>::logLikelihood(const Matrix<T,Dynamic,1>& x) const\n{\n  return niw_.logProb(x);\n};\n\ntemplate<typename T>\nvoid NiwMarginalized<T>::posterior(const Matrix<T,Dynamic,Dynamic>& x,\n    const VectorXu& z, uint32_t k)\n{\n  niw_ = niw0_.posterior(x,z,k);\n};\n\ntemplate<typename T>\nT NiwMarginalized<T>::logPdfUnderPrior() const\n{\n  // 0 since we integrate over parameters -> there is no parameters for which\n  // we would want to eval a pdf\n  return 0.0;\n};\n\ntemplate<typename T>\nvoid NiwMarginalized<T>::print() const\n{\n  niw0_.posterior().print();\n};\n", "meta": {"hexsha": "2937db81fc69db17178b9c9273b74648b96833af", "size": 7640, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/niwBaseMeasure.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/dpMM/niwBaseMeasure.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dpMM/niwBaseMeasure.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 26.2542955326, "max_line_length": 109, "alphanum_fraction": 0.6920157068, "num_tokens": 2306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6190167535551042}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_LOG2_E_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_LOG2_E_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Log2_e Log2_e (function template)\n\n  Generates the constant \\f$\\log_2(e)\\f$\n\n  @headerref{<boost/simd/constant/log2_e.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Log2_e();\n      @endcode\n\n  2.  @code\n      template<typename T> T Log2_e( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T that evaluates to \\f$\\log_2(e)\\f$.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c T that evaluates to `T(1.4426950408889634073599246810019)`\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/log2_e.hpp>\n#include <boost/simd/constant/simd/log2_e.hpp>\n\n#endif\n", "meta": {"hexsha": "c41a11c6f6e6f8be06bbe95d06e7a0fb3ff65cd1", "size": 1488, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/log2_e.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/log2_e.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/log2_e.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 29.1764705882, "max_line_length": 100, "alphanum_fraction": 0.5288978495, "num_tokens": 342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.839733983715524, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6190167508347157}}
{"text": "#ifndef SHAPES_SPHERE_HPP\n#define SHAPES_SPHERE_HPP\n\n#include <math/point3d.hpp>\n\n#include <boost/optional.hpp>\n\nnamespace math { struct ray3d; }\n\nnamespace shapes\n{\n\nstruct intersection_info;\n\nstruct sphere\n{\n  math::point3d center;\n  float radius;\n};\n\ninline bool operator==(sphere lhs, sphere rhs)\n{\n  return std::tie(lhs.center, lhs.radius) == std::tie(rhs.center, rhs.radius);\n}\n\ninline bool operator!=(sphere lhs, sphere rhs)\n{\n  return !(lhs == rhs);\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// 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<shapes::intersection_info> closest_intersection(shapes::sphere shape, math::ray3d ray);\n\n}\n\n#endif\n", "meta": {"hexsha": "b294d9f4221b6b368dfd76c36374936280cd2e37", "size": 1024, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/shapes/sphere.hpp", "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.hpp", "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.hpp", "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": 21.3333333333, "max_line_length": 103, "alphanum_fraction": 0.7333984375, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6190020806277418}}
{"text": "//  (C) Copyright John Maddock 2005-2021.\n//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_CCMATH_HYPOT_HPP\n#define BOOST_MATH_CCMATH_HYPOT_HPP\n\n#include <cmath>\n#include <array>\n#include <limits>\n#include <type_traits>\n#include <boost/math/tools/config.hpp>\n#include <boost/math/tools/is_constant_evaluated.hpp>\n#include <boost/math/ccmath/sqrt.hpp>\n#include <boost/math/ccmath/abs.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/detail/swap.hpp>\n\nnamespace boost::math::ccmath {\n\nnamespace detail {\n\ntemplate <typename T>\ninline constexpr T hypot_impl(T x, T y) noexcept\n{\n    x = boost::math::ccmath::abs(x);\n    y = boost::math::ccmath::abs(y);\n\n    if (y > x)\n    {\n        boost::math::ccmath::detail::swap(x, y);\n    }\n\n    if(x * std::numeric_limits<T>::epsilon() >= y)\n    {\n        return x;\n    }\n\n    T rat = y / x;\n    return x * boost::math::ccmath::sqrt(1 + rat * rat);\n}\n\n} // Namespace detail\n\ntemplate <typename Real, std::enable_if_t<!std::is_integral_v<Real>, bool> = true>\ninline constexpr Real hypot(Real x, Real y) noexcept\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))\n    {\n        return boost::math::ccmath::abs(x) == Real(0) ? boost::math::ccmath::abs(y) :\n               boost::math::ccmath::abs(y) == Real(0) ? boost::math::ccmath::abs(x) :\n               boost::math::ccmath::isinf(x) ? std::numeric_limits<Real>::infinity() :\n               boost::math::ccmath::isinf(y) ? std::numeric_limits<Real>::infinity() :\n               boost::math::ccmath::isnan(x) ? std::numeric_limits<Real>::quiet_NaN() :\n               boost::math::ccmath::isnan(y) ? std::numeric_limits<Real>::quiet_NaN() :\n               boost::math::ccmath::detail::hypot_impl(x, y);\n    }\n    else\n    {\n        using std::hypot;\n        return hypot(x, y);\n    }\n}\n\ntemplate <typename T1, typename T2>\ninline constexpr auto hypot(T1 x, T2 y) noexcept\n{\n    if(BOOST_MATH_IS_CONSTANT_EVALUATED(x))\n    {\n        // If the type is an integer (e.g. epsilon == 0) then set the epsilon value to 1 so that type is at a minimum \n        // cast to double\n        constexpr auto T1p = std::numeric_limits<T1>::epsilon() > 0 ? std::numeric_limits<T1>::epsilon() : 1;\n        constexpr auto T2p = std::numeric_limits<T2>::epsilon() > 0 ? std::numeric_limits<T2>::epsilon() : 1;\n        \n        using promoted_type = \n                              #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n                              std::conditional_t<T1p <= LDBL_EPSILON && T1p <= T2p, T1,\n                              std::conditional_t<T2p <= LDBL_EPSILON && T2p <= T1p, T2,\n                              #endif\n                              std::conditional_t<T1p <= DBL_EPSILON && T1p <= T2p, T1,\n                              std::conditional_t<T2p <= DBL_EPSILON && T2p <= T1p, T2, double\n                              #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n                              >>>>;\n                              #else\n                              >>;\n                              #endif\n\n        return boost::math::ccmath::hypot(promoted_type(x), promoted_type(y));\n    }\n    else\n    {\n        using std::hypot;\n        return hypot(x, y);\n    }\n}\n\ninline constexpr float hypotf(float x, float y) noexcept\n{\n    return boost::math::ccmath::hypot(x, y);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr long double hypotl(long double x, long double y) noexcept\n{\n    return boost::math::ccmath::hypot(x, y);\n}\n#endif\n\n} // Namespaces\n\n#endif // BOOST_MATH_CCMATH_HYPOT_HPP\n", "meta": {"hexsha": "b71376cbb4592cf59eaddb05c8060b5abbc6d400", "size": 3773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/hypot.hpp", "max_stars_repo_name": "twLQCD/math", "max_stars_repo_head_hexsha": "4e74c1251ec4ead2ab0e953d5e59b2de96a439ef", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "include/boost/math/ccmath/hypot.hpp", "max_issues_repo_name": "twLQCD/math", "max_issues_repo_head_hexsha": "4e74c1251ec4ead2ab0e953d5e59b2de96a439ef", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "include/boost/math/ccmath/hypot.hpp", "max_forks_repo_name": "twLQCD/math", "max_forks_repo_head_hexsha": "4e74c1251ec4ead2ab0e953d5e59b2de96a439ef", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 32.8086956522, "max_line_length": 118, "alphanum_fraction": 0.5966074742, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6190020706825192}}
{"text": "/*\n * This file is part of bogus, a C++ sparse block matrix library.\n *\n * Copyright 2013 Gilles Daviet <gdaviet@gmail.com>\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/.\n*/\n\n\n#ifndef BOGUS_EIGEN_LINEAR_SOLVERS\n#define BOGUS_EIGEN_LINEAR_SOLVERS\n\n#include \"../Utils/LinearSolverBase.hpp\"\n\n#include <Eigen/LU>\n#include <Eigen/Cholesky>\n\nnamespace bogus {\n\ntemplate<typename Decomposition, typename RhsType>\nstruct EigenSolveResult\n{\n#if EIGEN_VERSION_AT_LEAST(3,2,90)\n\t  typedef const Eigen::Solve< Decomposition, RhsType > Type ;\n#else\n\t  typedef Eigen::internal::solve_retval< Decomposition, RhsType > Type ;\n#endif\n};\n\ntemplate < typename Derived >\nstruct LinearSolverTraits< LU< Eigen::MatrixBase< Derived > > >\n{\n\ttypedef typename Derived::PlainObject MatrixType ;\n\ttypedef Eigen::FullPivLU< MatrixType > FactType ;\n\n\ttemplate < typename RhsT > struct Result {\n\t\ttypedef typename EigenSolveResult< FactType, RhsT >::Type Type ;\n\t} ;\n\ttemplate < typename RhsT >\n\tstruct Result< Eigen::MatrixBase< RhsT > > {\n\t\ttypedef typename Result< RhsT >::Type Type ;\n\t} ;\n} ;\n\n\ntemplate < typename Derived >\nstruct LU< Eigen::MatrixBase< Derived > >\n\t\t: public LinearSolverBase< LU< Eigen::MatrixBase< Derived > > >\n{\n\ttypedef Eigen::MatrixBase< Derived > MatrixType ;\n\ttypedef LinearSolverTraits< LU< MatrixType > > Traits ;\n\n\tLU() {}\n\ttemplate< typename OtherDerived >\n\texplicit LU ( const Eigen::MatrixBase< OtherDerived >& mat )\n\t\t: m_fact( mat )\n\t{}\n\n\ttemplate< typename OtherDerived >\n\tLU< Eigen::MatrixBase< Derived > >& compute ( const Eigen::MatrixBase< OtherDerived >& mat )\n\t{\n\t\tm_fact.compute( mat ) ;\n\t\treturn *this ;\n\t}\n\n\ttemplate < typename RhsT, typename ResT >\n\tvoid solve( const Eigen::MatrixBase< RhsT >& rhs, ResT& res ) const\n\t{\n\t\tres = m_fact.solve( rhs ) ;\n\t}\n\n\ttemplate < typename RhsT >\n\ttypename Traits::template Result< Eigen::MatrixBase< RhsT > >::Type\n\tsolve( const Eigen::MatrixBase< RhsT >& rhs ) const\n\t{\n\t\treturn m_fact.solve( rhs ) ;\n\t}\n\n  private:\n\ttypename Traits::FactType m_fact ;\n} ;\n\ntemplate < typename Scalar, int Rows, int Cols = Rows, int Options = 0 >\nstruct DenseLU : public LU< Eigen::MatrixBase< Eigen::Matrix< Scalar, Rows, Cols, Options > > >\n{\n\tDenseLU() {}\n\ttemplate< typename OtherDerived >\n\texplicit DenseLU ( const Eigen::MatrixBase< OtherDerived >& mat )\n\t\t: LU< Eigen::MatrixBase< Eigen::Matrix< Scalar, Rows, Cols, Options > > >( mat )\n\t{}\n} ;\n\ntemplate < typename Derived >\nstruct LinearSolverTraits< LDLT< Eigen::MatrixBase< Derived > > >\n{\n\ttypedef typename Derived::PlainObject MatrixType ;\n\ttypedef Eigen::LDLT< MatrixType > FactType ;\n\n\ttemplate < typename RhsT > struct Result {\n\t\ttypedef typename EigenSolveResult< FactType, RhsT >::Type Type ;\n\t} ;\n\ttemplate < typename RhsT >\n\tstruct Result< Eigen::MatrixBase< RhsT > > {\n\t\ttypedef typename Result< RhsT >::Type Type ;\n\t} ;\n} ;\n\n\ntemplate < typename Derived >\nstruct LDLT< Eigen::MatrixBase< Derived > >\n\t\t: public LinearSolverBase< LDLT< Eigen::MatrixBase< Derived > > >\n{\n\ttypedef Eigen::MatrixBase< Derived > MatrixType ;\n\ttypedef LinearSolverTraits< LDLT< MatrixType > > Traits ;\n\n\tLDLT() {}\n\ttemplate< typename OtherDerived >\n\texplicit LDLT ( const Eigen::MatrixBase< OtherDerived >& mat )\n\t\t: m_fact( mat )\n\t{}\n\n\ttemplate< typename OtherDerived >\n\tLDLT< Eigen::MatrixBase< Derived > >& compute ( const Eigen::MatrixBase< OtherDerived >& mat )\n\t{\n\t\tm_fact.compute( mat ) ;\n\t\treturn *this ;\n\t}\n\n\ttemplate < typename RhsT, typename ResT >\n\tvoid solve( const Eigen::MatrixBase< RhsT >& rhs, ResT& res ) const\n\t{\n\t\tres = m_fact.solve( rhs ) ;\n\t}\n\n\ttemplate < typename RhsT >\n\ttypename Traits::template Result< Eigen::MatrixBase< RhsT > >::Type\n\tsolve( const Eigen::MatrixBase< RhsT >& rhs ) const\n\t{\n\t\treturn m_fact.solve( rhs ) ;\n\t}\n\n  private:\n\ttypename Traits::FactType m_fact ;\n} ;\n\ntemplate < typename Scalar, int Rows, int Options = 0 >\nstruct DenseLDLT : public LDLT< Eigen::MatrixBase< Eigen::Matrix< Scalar, Rows, Rows, Options > > >\n{\n\tDenseLDLT() {}\n\ttemplate< typename OtherDerived >\n\texplicit DenseLDLT ( const Eigen::MatrixBase< OtherDerived >& mat )\n\t\t: LDLT< Eigen::MatrixBase< Eigen::Matrix< Scalar, Rows, Rows, Options > > >( mat )\n\t{}\n} ;\n\ntemplate < typename Derived, typename RhsT >\ntypename LinearSolverTraits< Derived >::template Result< Eigen::MatrixBase< RhsT > >::Type operator*\n\t( const LinearSolverBase< Derived >& solver, const Eigen::MatrixBase< RhsT >& rhs )\n{\n  return solver.solve( rhs ) ;\n}\n\n\n} //namespace bogus\n\n\n#endif\n", "meta": {"hexsha": "87362f1684fff5724a1bd5aa25b05bc0c1cefb54", "size": 4624, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/src/Core/Eigen/EigenLinearSolvers.hpp", "max_stars_repo_name": "sjokic/WallDestruction", "max_stars_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T11:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T11:30:05.000Z", "max_issues_repo_path": "include/src/Core/Eigen/EigenLinearSolvers.hpp", "max_issues_repo_name": "sjokic/WallDestruction", "max_issues_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/src/Core/Eigen/EigenLinearSolvers.hpp", "max_forks_repo_name": "sjokic/WallDestruction", "max_forks_repo_head_hexsha": "2e1c000096df4aa027a91ff1732ce50a205b221a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2, "max_line_length": 100, "alphanum_fraction": 0.7013408304, "num_tokens": 1240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6190020552103628}}
{"text": "#include \"penalized_gd_solver.h\"\n#include \"../../common.h\"\n#include \"../../logging/easylogging++.h\"\n#include <armadillo>\n\nusing arma::mat;\nusing arma::pow;\nusing arma::sum;\n\nPenalizedGDSolver::PenalizedGDSolver(const arma::mat &L,\n                                     const double lr,\n                                     const int max_iter,\n                                     const double termination_threshold,\n                                     const double penalty)\n    : GDSolver(L, lr, max_iter, termination_threshold)\n{\n    m_penalty = penalty;\n};\n\nmat PenalizedGDSolver::objective(mat estimate, mat expected)\n{\n    arma::uvec negative_indices = arma::find(m_x < 0);\n    arma::mat x_negative_only = arma::abs(m_x.cols(negative_indices));\n    arma::mat penalty = m_penalty * arma::sum(x_negative_only, 1);\n    arma::mat rmse_value = rmse(estimate, expected);\n    arma::mat objective_value = rmse_value + penalty;\n    LOG(DEBUG) << \"Round \" << m_round;\n    LOG(DEBUG) << \"Solution \" << m_x;\n    LOG(DEBUG) << \"Penalty \" << penalty;\n    LOG(DEBUG) << \"RMSE \" << rmse_value;\n    LOG(DEBUG) << \"Objective \" << objective_value;\n    return objective_value;\n}", "meta": {"hexsha": "f4fcf019bf8794d88f0c0b02ee3f218da41f9c77", "size": 1162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/numerical/gradient_descent/penalized_gd_solver.cpp", "max_stars_repo_name": "omyllymaki/math", "max_stars_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-04T03:43:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T09:12:24.000Z", "max_issues_repo_path": "src/numerical/gradient_descent/penalized_gd_solver.cpp", "max_issues_repo_name": "omyllymaki/math", "max_issues_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/numerical/gradient_descent/penalized_gd_solver.cpp", "max_forks_repo_name": "omyllymaki/math", "max_forks_repo_head_hexsha": "05c44762aae43268fa965104c19ba86c4284c549", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2121212121, "max_line_length": 72, "alphanum_fraction": 0.6006884682, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.618975973377438}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/ellint_rc.hpp>\n\n#include <boost/math/special_functions/ellint_rc.hpp>\n#include <eve/wide.hpp>\n\n\nTTS_CASE_TPL(\"Check eve::ellint_rc behavior\", EVE_TYPE)\n{\n  using elt_t = eve::element_type_t<T>;\n  TTS_ULP_EQUAL(eve::ellint_rc(T(0.2), T(0.4)),  T(boost::math::ellint_rc(elt_t(0.2), elt_t(0.4))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rc(T(1.5), T(1)),T(boost::math::ellint_rc(elt_t(1.5), elt_t(1))), 1.0);\n  TTS_ULP_EQUAL(eve::ellint_rc(T(0), T(5)),  T(boost::math::ellint_rc(elt_t(0), elt_t(5))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rc(T(2), T(5)),  T(boost::math::ellint_rc(elt_t(2), elt_t(5))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rc(T(2), T(2)),  T(boost::math::ellint_rc(elt_t(2), elt_t(2))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rc(T(2), T(0.1)),  T(boost::math::ellint_rc(elt_t(2), elt_t(0.1))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rc(T(1.0e38), T(0.1)),  T(boost::math::ellint_rc(elt_t(1.0e38), elt_t(0.1))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rc(T(1.0), T(1.0e38)),  T(boost::math::ellint_rc(elt_t(1.0),elt_t(1.0e38))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rc(T(1.0e38), T(1.0e38)),  T(boost::math::ellint_rc(elt_t(1.0e38),elt_t(1.0e38))),   1.0);\n}\n\n", "meta": {"hexsha": "a49ca205996c5aca4e4f7a5b602a28843a87da89", "size": 1497, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/elliptic/ellint_rc/regular/ellint_rc.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/elliptic/ellint_rc/regular/ellint_rc.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/elliptic/ellint_rc/regular/ellint_rc.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.4642857143, "max_line_length": 118, "alphanum_fraction": 0.5684702739, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6189759727485908}}
{"text": "// test_linear_systems_of_equations.cpp\n// (c) Tivole\n\n#include <boost/test/unit_test.hpp>\n#include \"../src/numerary.hpp\"\n\nnamespace numerary\n{\n    \n    BOOST_AUTO_TEST_SUITE(TestLinearSystemsOfEquations)\n\n    BOOST_AUTO_TEST_CASE(test_gauss_elimination)\n    {\n        double **a = new double*[3];\n        double *y = new double[3];\n        double *x = new double[3];\n        double *expected_x = new double[3];\n        short int result;\n\n        for (int i = 0; i < 3; i ++)\n            a[i] = new double[3];\n\n        expected_x[0] = 5.0/2.0;\n        expected_x[1] = 2.0/3.0;\n        expected_x[2] = 2.0/9.0;\n\n        a[0][0] = 2;\n        a[0][1] = -1;\n        a[0][2] = 3;\n\n        a[1][0] = 2;\n        a[1][1] = 2;\n        a[1][2] = 3;\n\n        a[2][0] = -2;\n        a[2][1] = 3;\n        a[2][2] = 0;\n\n        y[0] = 5;\n        y[1] = 7;\n        y[2] = -3;\n\n        result = Numerary::linear_systems_of_equations(a, y, x, 3, \"gauss\");\n\n        for (int i = 0; i < 3; i ++) BOOST_CHECK(fabs(expected_x[i] - x[i]) < 1.e-7);\n\n        for (int i = 0; i < 3; i++) delete[] a[i];\n\n        delete[] a;\n        delete[] x;\n        delete[] y;\n        delete[] expected_x;\n        \n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n}\n\n", "meta": {"hexsha": "d811b408fadb1eb7fca0f62aa1c1e1c9e6cb4981", "size": 1218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_linear_systems_of_equations.cpp", "max_stars_repo_name": "tivole/Numerary", "max_stars_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-02-21T06:09:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T10:00:06.000Z", "max_issues_repo_path": "test/test_linear_systems_of_equations.cpp", "max_issues_repo_name": "tivole/Ti_Numerary", "max_issues_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_linear_systems_of_equations.cpp", "max_forks_repo_name": "tivole/Ti_Numerary", "max_forks_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T11:12:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T11:12:27.000Z", "avg_line_length": 20.6440677966, "max_line_length": 85, "alphanum_fraction": 0.4729064039, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6189759679877183}}
{"text": "/*\n * lorenz.hpp\n *\n * Copyright 2011 Mario Mulansky\n * Copyright 2012 Karsten Ahnert\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n#ifndef LORENZ_HPP_\n#define LORENZ_HPP_\n\n#include <boost/array.hpp>\n\nstruct lorenz\n{\n    template< class state_type >\n    void inline operator()( const state_type &x , state_type &dxdt , const double t ) const\n    {\n        const double sigma = 10.0;\n        const double R = 28.0;\n        const double b = 8.0 / 3.0;\n        dxdt[0] = sigma * ( x[1] - x[0] );\n        dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n        dxdt[2] = x[0]*x[1] - b * x[2];\n    }\n};\n\n\n#endif /* LORENZ_HPP_ */\n", "meta": {"hexsha": "c1ea37c9e7569053e4f0468ca77760132491f152", "size": 737, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/performance/lorenz.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/performance/lorenz.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/performance/lorenz.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 21.6764705882, "max_line_length": 91, "alphanum_fraction": 0.5956580733, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6189759679877181}}
{"text": "// SPDX-License-Identifier: Apache-2.0\n// Copyright 2021 - 2021, the Anboto author and contributors\n#include <Core/Core.h>\n#include <Functions4U/Functions4U.h>\n#include <Eigen/Eigen.h>\n#include \"Permutations.h\"\n\n\nnamespace Upp {\n\nusing namespace Eigen;\n\nBuffer<Buffer<int>> PermutationsWithRepetition(int nVals, int nOptionsVal) {\n\tBuffer<Buffer<int>> list; \n\n\tint num = int(pow(nOptionsVal, nVals));\n\tlist.Alloc(nVals);\n\tfor (int ip = 0; ip < nVals; ++ip) {\n\t\tlist[ip].Alloc(num);\n\t\tint nrep = int(pow(nOptionsVal, ip));\n\t\tint val = 0, irep = 0;\n\t\tfor (int i = 0; i < num; ++i) {\n\t\t\tlist[ip][i] = val;\n\t\t\tirep++;\n\t\t\tif (irep >= nrep) {\n\t\t\t\tirep = 0;\n\t\t\t\tval++;\n\t\t\t\tif (val >= nOptionsVal)\n\t\t\t\t\tval = 0;\n\t\t\t}\n\t\t}\n\t}\n\treturn list;\n}\n\t\n}", "meta": {"hexsha": "732afe446d7a54bfedfbd0383dc6b17465e9a473", "size": 735, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STEM4U/Permutations.cpp", "max_stars_repo_name": "anboto/Anboto", "max_stars_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T12:07:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:40:45.000Z", "max_issues_repo_path": "STEM4U/Permutations.cpp", "max_issues_repo_name": "anboto/Anboto", "max_issues_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-03-20T10:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T19:50:32.000Z", "max_forks_repo_path": "STEM4U/Permutations.cpp", "max_forks_repo_name": "anboto/Anboto", "max_forks_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T09:15:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T09:15:18.000Z", "avg_line_length": 20.4166666667, "max_line_length": 76, "alphanum_fraction": 0.6258503401, "num_tokens": 244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276107, "lm_q2_score": 0.7122321964553658, "lm_q1q2_score": 0.6188064104365942}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/containers/t4mesh/t4mesh.h>\n#include <OpenTissue/core/geometry/geometry_compute_inscribed_circumscribed_radius_quality_measure.h>\n#include <OpenTissue/core/geometry/geometry_compute_volume_length_quality_measure.h>\n#include <OpenTissue/core/geometry/geometry_compute_inscribed_radius_length_quality_measure.h>\n#include <OpenTissue/core/containers/t4mesh/util/t4mesh_compute_mesh_quality.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_t4mesh_compute_mesh_quality);\n\nBOOST_AUTO_TEST_CASE(quality_testing)\n{\n  typedef OpenTissue::math::BasicMathTypes<double, size_t>   math_types;\n  typedef OpenTissue::t4mesh::T4Mesh< math_types >           mesh_type;\n  typedef math_types::vector3_type                           vector3_type;\n  typedef vector3_type::value_type                           real_type;\n\n  std::vector<vector3_type> c;\n  c.resize( 6 );\n  c[0] = vector3_type(0,0,0);\n  c[1] = vector3_type(0,0,1);\n  c[2] = vector3_type(0,1,0);\n  c[3] = vector3_type(0,1,1);\n  c[4] = vector3_type(1,0,0);\n  c[5] = vector3_type(1,0,1);\n\n  mesh_type M;\n  M.insert( c[0] );\n  M.insert( c[1] );\n  M.insert( c[2] );\n  M.insert( c[3] );\n  M.insert( c[4] );\n  M.insert( c[5] );\n  M.insert(0,1,2,3);\n  M.insert(0,1,2,4);\n\n  {\n    using namespace OpenTissue::geometry;\n    std::vector<real_type> Q;\n    OpenTissue::t4mesh::compute_mesh_quality( M, c, Q, &(compute_inscribed_circumscribed_radius_quality_measure<vector3_type>)  );\n\n    BOOST_CHECK(Q.size() == 2);\n  }\n  {\n    using namespace OpenTissue::geometry;\n    std::vector<real_type> Q;\n    OpenTissue::t4mesh::compute_mesh_quality( M,Q, &(compute_inscribed_circumscribed_radius_quality_measure<vector3_type>)  );\n\n    BOOST_CHECK(Q.size() == 2);\n  }\n  {\n    using namespace OpenTissue::geometry;\n    std::vector<real_type> Q;\n    OpenTissue::t4mesh::compute_mesh_quality( M,c, Q, &(compute_volume_length_quality_measure<vector3_type>)  );\n\n    BOOST_CHECK(Q.size() == 2);\n  }\n  {\n    using namespace OpenTissue::geometry;\n    std::vector<real_type> Q;\n    OpenTissue::t4mesh::compute_mesh_quality( M,Q, &(compute_volume_length_quality_measure<vector3_type>)  );\n\n    BOOST_CHECK(Q.size() == 2);\n  }\n  {\n    using namespace OpenTissue::geometry;\n    std::vector<real_type> Q;\n    OpenTissue::t4mesh::compute_mesh_quality( M, c, Q, &(compute_inscribed_radius_length_quality_measure<vector3_type>)  );\n\n    BOOST_CHECK(Q.size() == 2);\n  }\n  {\n    using namespace OpenTissue::geometry;\n    std::vector<real_type> Q;\n    OpenTissue::t4mesh::compute_mesh_quality( M, Q, &(compute_inscribed_radius_length_quality_measure<vector3_type>)  );\n    BOOST_CHECK(Q.size() == 2);\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "1e1119d660559dce4c3f10b621d8cb9a8790d5f4", "size": 3168, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/containers/t4mesh_compute_mesh_quality/src/unit_t4mesh_compute_mesh_quality.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/containers/t4mesh_compute_mesh_quality/src/unit_t4mesh_compute_mesh_quality.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/containers/t4mesh_compute_mesh_quality/src/unit_t4mesh_compute_mesh_quality.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 33.7021276596, "max_line_length": 130, "alphanum_fraction": 0.7231691919, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826789824086, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6188064022417212}}
{"text": "// ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there.\n//\n\n#include <iostream>\n#include <boost/math/differentiation/autodiff.hpp>\n#include \"Instrument.h\"\n#include \"Interpolator.h\"\n#include \"Holiday.h\"\n#include \"Utility.h\"\n#include \"YearFraction.h\"\n\nusing namespace boost::math::differentiation;\ntypedef boost::gregorian::date date;\n\n\n//class FixedCashFlow {\n//private:\n//    double _flow;\n//\n//public:\n//    double accural_yf;\n//    double coupon_rate;\n//    double payment_date;\n//    double notional;\n//\n//    FixedCashFlow() {\n//        accural_yf = 1.0;\n//        coupon_rate = 0.02;\n//        notional = 1000000.0;\n//\n//    }\n//\n//    double get_flow() {\n//        _flow = notional * accural_yf * coupon_rate;\n//        return _flow;\n//    }\n//\n//};\n//\n//double get_dsc() {\n//    return 0.9;\n//}\n//\n//template <typename T>\n//T plus(T const& x, T const& y) {\n//\n//    return x + y;\n//}\n//\n//static class FixedFlowCalculator {\n//\n//private:\n//    const static unsigned Order = 2;                  // Highest order derivative to be calculated.\n//    \n//    template <typename T>\n//    static T _price(double const& flow, T const& DF) {\n//        return flow * DF;\n//    }\n//\n//public:\n//    auto static price(FixedCashFlow& cf) {\n//        auto const df = make_fvar<double, Order>(get_dsc());\n//        auto const pv = _price(cf.get_flow(), df);\n//        return pv;\n//    }\n//};\n\n\n//int main()\n//{\n//    deriv2 deriv_obj = deriv2(2.0);\n//    deriv_obj.show_value();\n//    std::cout << \"Hello World!\\n\";\n//\n//    FixedCashFlow a_cash = FixedCashFlow();\n//    std::cout << \"my flow is: \" << a_cash.get_flow() << std::endl;\n//    auto pv = FixedFlowCalculator::price(a_cash);\n//\n//    std::cout << \"PV = \" << pv.derivative(0) << std::endl;\n//    std::cout << \"dPV/dDF = \" << pv.derivative(1) << std::endl;\n//\n//    auto pv2 = plus(pv,pv);\n//    std::cout << \"PV = \" << pv2.derivative(0) << std::endl;\n//    std::cout << \"dPV/dDF = \" << pv2.derivative(1) << std::endl;\n//\n//    //using namespace boost::math::differentiation;\n//\n//    //constexpr unsigned Order = 5;                  // Highest order derivative to be calculated.\n//    //auto const x = make_fvar<double, Order>(2.0);  // Find derivatives at x=2.\n//    //auto const y = fourth_power(x);\n//    //for (unsigned i = 0; i <= Order; ++i)\n//    //    std::cout << \"y.derivative(\" << i << \") = \" << y.derivative(i) << std::endl;\n//\n//}\n\n// Equations and function/variable names are from\n// https://en.wikipedia.org/wiki/Greeks_(finance)#Formulas_for_European_option_Greeks\n// Standard normal probability density function\ntemplate<typename X>\nX phi(const X& x)\n{\n    return boost::math::constants::one_div_root_two_pi<double>() * exp(-0.5 * x * x);\n}\n// Standard normal cumulative distribution function\ntemplate<typename X>\nX Phi(const X& x)\n{\n    return 0.5 * erfc(-boost::math::constants::one_div_root_two<double>() * x);\n}\nenum CP { call, put };\n// Assume zero annual dividend yield (q=0).\nusing namespace boost::math::differentiation;\n\ntemplate<typename Price, typename Sigma, typename Tau, typename Rate>\npromote<Price, Sigma, Tau, Rate>\nblack_scholes_option_price(CP cp, double K, const Price& S, const Sigma& sigma, const Tau& tau, const Rate& r)\n{\n    using namespace std;\n    const auto d1 = (log(S / K) + (r + sigma * sigma / 2) * tau) / (sigma * sqrt(tau));\n    const auto d2 = (log(S / K) + (r - sigma * sigma / 2) * tau) / (sigma * sqrt(tau));\n    if (cp == call)\n        return S * Phi(d1) - exp(-r * tau) * K * Phi(d2);\n    else\n        return exp(-r * tau) * K * Phi(-d2) - S * Phi(-d1);\n}\n\n\nint main()\n{\n    const double K = 100.0; // Strike price.\n    auto const S = make_fvar<double, 3>(105); // Stock price.\n    auto const sigma = make_fvar<double, 0, 3>(5); // Volatility.\n    auto const tau = make_fvar<double, 0, 0, 1>(30.0 / 365);  // Time to expiration in years. (30 days).\n    auto const r = make_fvar<double, 0, 0, 0, 1>(1.25 / 100); // Interest rate.\n\n    const auto call_price = black_scholes_option_price(call, K, S, sigma, tau, r);\n    const auto put_price = black_scholes_option_price(put, K, S, sigma, tau, r);\n    // Compare automatically calculated greeks by autodiff with formulas for greeks.\n    // https://en.wikipedia.org/wiki/Greeks_(finance)#Formulas_for_European_option_Greeks\n\n    const double d1 = static_cast<double>((log(S / K) + (r + sigma * sigma / 2) * tau) / (sigma * sqrt(tau)));\n    const double d2 = static_cast<double>((log(S / K) + (r - sigma * sigma / 2) * tau) / (sigma * sqrt(tau)));\n    const double formula_call_delta = +Phi(+d1);\n    const double formula_put_delta = -Phi(-d1);\n    const double formula_vega = static_cast<double>(S * phi(d1) * sqrt(tau));\n    const double formula_call_theta = static_cast<double>(-S * phi(d1) * sigma / (2 * sqrt(tau)) - r * K * exp(-r * tau) * Phi(+d2));\n    const double formula_put_theta = static_cast<double>(-S * phi(d1) * sigma / (2 * sqrt(tau)) + r * K * exp(-r * tau) * Phi(-d2));\n    const double formula_call_rho = static_cast<double>(+K * tau * exp(-r * tau) * Phi(+d2));\n    const double formula_put_rho = static_cast<double>(-K * tau * exp(-r * tau) * Phi(-d2));\n    const double formula_gamma = static_cast<double>(phi(d1) / (S * sigma * sqrt(tau)));\n    const double formula_vanna = static_cast<double>(-phi(d1) * d2 / sigma);\n    const double formula_charm = static_cast<double>(phi(d1) * (d2 * sigma * sqrt(tau) - 2 * r * tau) / (2 * tau * sigma * sqrt(tau)));\n    const double formula_vomma = static_cast<double>(S * phi(d1) * sqrt(tau) * d1 * d2 / sigma);\n    const double formula_veta = static_cast<double>(-S * phi(d1) * sqrt(tau) * (r * d1 / (sigma * sqrt(tau)) - (1 + d1 * d2) / (2 * tau)));\n    const double formula_speed = static_cast<double>(-phi(d1) * (d1 / (sigma * sqrt(tau)) + 1) / (S * S * sigma * sqrt(tau)));\n    const double formula_zomma = static_cast<double>(phi(d1) * (d1 * d2 - 1) / (S * sigma * sigma * sqrt(tau)));\n    const double formula_color =\n        static_cast<double>(-phi(d1) / (2 * S * tau * sigma * sqrt(tau)) * (1 + (2 * r * tau - d2 * sigma * sqrt(tau)) * d1 / (sigma * sqrt(tau))));\n    const double formula_ultima = -formula_vega * static_cast<double>((d1 * d2 * (1 - d1 * d2) + d1 * d1 + d2 * d2) / (sigma * sigma));\n    std::cout << std::setprecision(std::numeric_limits<double>::digits10)\n        << \"autodiff black-scholes call price = \" << call_price.derivative(0, 0, 0, 0) << '\\n'\n        << \"autodiff black-scholes put  price = \" << put_price.derivative(0, 0, 0, 0) << '\\n'\n        << \"\\n## First-order Greeks\\n\"\n        << \"autodiff call delta = \" << call_price.derivative(1, 0, 0, 0) << '\\n'\n        << \" formula call delta = \" << formula_call_delta << '\\n'\n        << \"autodiff call vega  = \" << call_price.derivative(0, 1, 0, 0) << '\\n'\n        << \" formula call vega  = \" << formula_vega << '\\n'\n        << \"autodiff call theta = \" << -call_price.derivative(0, 0, 1, 0) << '\\n' // minus sign due to tau = T-time\n        << \" formula call theta = \" << formula_call_theta << '\\n'\n        << \"autodiff call rho   = \" << call_price.derivative(0, 0, 0, 1) << '\\n'\n        << \" formula call rho   = \" << formula_call_rho << '\\n'\n        << '\\n'\n        << \"autodiff put delta = \" << put_price.derivative(1, 0, 0, 0) << '\\n'\n        << \" formula put delta = \" << formula_put_delta << '\\n'\n        << \"autodiff put vega  = \" << put_price.derivative(0, 1, 0, 0) << '\\n'\n        << \" formula put vega  = \" << formula_vega << '\\n'\n        << \"autodiff put theta = \" << -put_price.derivative(0, 0, 1, 0) << '\\n'\n        << \" formula put theta = \" << formula_put_theta << '\\n'\n        << \"autodiff put rho   = \" << put_price.derivative(0, 0, 0, 1) << '\\n'\n        << \" formula put rho   = \" << formula_put_rho << '\\n'\n        << \"\\n## Second-order Greeks\\n\"\n        << \"autodiff call gamma = \" << call_price.derivative(2, 0, 0, 0) << '\\n'\n        << \"autodiff put  gamma = \" << put_price.derivative(2, 0, 0, 0) << '\\n'\n        << \"      formula gamma = \" << formula_gamma << '\\n'\n        << \"autodiff call vanna = \" << call_price.derivative(1, 1, 0, 0) << '\\n'\n        << \"autodiff put  vanna = \" << put_price.derivative(1, 1, 0, 0) << '\\n'\n        << \"      formula vanna = \" << formula_vanna << '\\n'\n        << \"autodiff call charm = \" << -call_price.derivative(1, 0, 1, 0) << '\\n'\n        << \"autodiff put  charm = \" << -put_price.derivative(1, 0, 1, 0) << '\\n'\n        << \"      formula charm = \" << formula_charm << '\\n'\n        << \"autodiff call vomma = \" << call_price.derivative(0, 2, 0, 0) << '\\n'\n        << \"autodiff put  vomma = \" << put_price.derivative(0, 2, 0, 0) << '\\n'\n        << \"      formula vomma = \" << formula_vomma << '\\n'\n        << \"autodiff call veta = \" << call_price.derivative(0, 1, 1, 0) << '\\n'\n        << \"autodiff put  veta = \" << put_price.derivative(0, 1, 1, 0) << '\\n'\n        << \"      formula veta = \" << formula_veta << '\\n'\n        << \"\\n## Third-order Greeks\\n\"\n        << \"autodiff call speed = \" << call_price.derivative(3, 0, 0, 0) << '\\n'\n        << \"autodiff put  speed = \" << put_price.derivative(3, 0, 0, 0) << '\\n'\n        << \"      formula speed = \" << formula_speed << '\\n'\n        << \"autodiff call zomma = \" << call_price.derivative(2, 1, 0, 0) << '\\n'\n        << \"autodiff put  zomma = \" << put_price.derivative(2, 1, 0, 0) << '\\n'\n        << \"      formula zomma = \" << formula_zomma << '\\n'\n        << \"autodiff call color = \" << call_price.derivative(2, 0, 1, 0) << '\\n'\n        << \"autodiff put  color = \" << put_price.derivative(2, 0, 1, 0) << '\\n'\n        << \"      formula color = \" << formula_color << '\\n'\n        << \"autodiff call ultima = \" << call_price.derivative(0, 3, 0, 0) << '\\n'\n        << \"autodiff put  ultima = \" << put_price.derivative(0, 3, 0, 0) << '\\n'\n        << \"      formula ultima = \" << formula_ultima << '\\n'\n        ;\n\n\n\n    auto v = std::vector<double>{ 1.0, 2.0, 5.0, 10.0 };\n    auto v2 = std::vector<double>{ 10.0, 20.0, 50.0, 100.0 };\n    auto interp_1 = LinearInterpolator<double, double>(v, v2);\n    std::cout << \"interp function: \" << interp_1.interp(2.5) << std::endl;\n    std::cout << \"interp function: \" << interp_1.interp(12.5) << std::endl;\n    std::cout << \"interp function: \" << interp_1.interp(0.5) << std::endl;\n    Holiday us_holiday;\n    date day1{ 2021, 5, 31 };\n    std::cout << \"is \" << day1 << \" a holiday: \" << us_holiday.is_holiday(day1) << std::endl;\n    date day2 = bus_day_shift(day1, 30, us_holiday);\n    std::cout << \"So after adj current date is \" << day2  << std::endl;\n\n    std::string aa = \"1y\";\n    std::string bb = \"6m\";\n\n    std::cout << \"test function 1y: \" << tenor_to_year(aa) << std::endl;\n    std::cout << \"test function 6m: \" << tenor_to_year(bb) << std::endl;\n\n    FixedCashFlow cf(1000000.00, 0.02, day1, day2, DCC::A30360);\n    CashFlowSchedule cfs(1000000.0, 0.02, day1, 2, \"10Y\");\n    cfs.show();\n    return 0;\n}\n\n// Run program: Ctrl + F5 or Debug > Start Without Debugging menu\n// Debug program: F5 or Debug > Start Debugging menu\n\n// Tips for Getting Started: \n//   1. Use the Solution Explorer window to add/manage files\n//   2. Use the Team Explorer window to connect to source control\n//   3. Use the Output window to see build output and other messages\n//   4. Use the Error List window to view errors\n//   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project\n//   6. In the future, to open this project again, go to File > Open > Project and select the .sln file\n", "meta": {"hexsha": "ee26aeed5efc315aafb4a55257f1581cb0f59e80", "size": 11547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RatesLib.cpp", "max_stars_repo_name": "enojoker/RatesLib", "max_stars_repo_head_hexsha": "4564c270ca9cfd05d8d2238266b762f2e75b3286", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RatesLib.cpp", "max_issues_repo_name": "enojoker/RatesLib", "max_issues_repo_head_hexsha": "4564c270ca9cfd05d8d2238266b762f2e75b3286", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RatesLib.cpp", "max_forks_repo_name": "enojoker/RatesLib", "max_forks_repo_head_hexsha": "4564c270ca9cfd05d8d2238266b762f2e75b3286", "max_forks_repo_licenses": ["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.560483871, "max_line_length": 148, "alphanum_fraction": 0.5788516498, "num_tokens": 3709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.618786436024069}}
{"text": "#include <dlib/dnn.h>\n#include <dlib/matrix.h>\n\n#include <iostream>\n#include <random>\n\nusing namespace dlib;\n\nusing NetworkType = loss_mean_squared<fc<1, input<matrix<double>>>>;\nusing SampleType = matrix<double, 1, 1>;\nusing KernelType = linear_kernel<SampleType>;\n\nfloat func(float x) {\n  return 4.f + 0.3f * x;  // line coeficients\n}\n\nvoid TrainAndSaveKRR(const std::vector<matrix<double>>& x,\n                     const std::vector<float>& y) {\n  krr_trainer<KernelType> trainer;\n  trainer.set_kernel(KernelType());\n  decision_function<KernelType> df = trainer.train(x, y);\n  serialize(\"dlib-krr.dat\") << df;\n}\n\nvoid LoadAndPredictKRR(const std::vector<matrix<double>>& x) {\n  decision_function<KernelType> df;\n\n  deserialize(\"dlib-krr.dat\") >> df;\n\n  // Predict\n\n  std::cout << \"KRR predictions \\n\";\n  for (auto& v : x) {\n    auto p = df(v);\n    std::cout << static_cast<double>(p) << std::endl;\n  }\n}\n\nvoid TrainAndSaveNetwork(const std::vector<matrix<double>>& x,\n                         const std::vector<float>& y) {\n  NetworkType network;\n  sgd solver;\n  dnn_trainer<NetworkType> trainer(network, solver);\n  trainer.set_learning_rate(0.0001);\n  trainer.set_mini_batch_size(50);\n  trainer.set_max_num_epochs(300);\n  trainer.be_verbose();\n  trainer.train(x, y);\n  network.clean();\n\n  serialize(\"dlib-net.dat\") << network;\n  net_to_xml(network, \"net.xml\");\n}\n\nvoid LoadAndPredictNetwork(const std::vector<matrix<double>>& x) {\n  NetworkType network;\n\n  deserialize(\"dlib-net.dat\") >> network;\n\n  // Predict\n  auto predictions = network(x);\n\n  std::cout << \"Net predictions \\n\";\n  for (auto p : predictions) {\n    std::cout << static_cast<double>(p) << std::endl;\n  }\n}\n\nint main() {\n  size_t n = 1000;\n  std::vector<matrix<double>> x(n);\n  std::vector<float> y(n);\n\n  std::random_device rd;\n  std::mt19937 re(rd());\n  std::uniform_real_distribution<float> dist(-1.5, 1.5);\n\n  // generate data\n  for (size_t i = 0; i < n; ++i) {\n    x[i].set_size(1, 1);\n    x[i](0, 0) = i;\n\n    y[i] = func(i) + dist(re);\n  }\n\n  // normalize data\n  vector_normalizer<matrix<double>> normalizer_x;\n  // let the normalizer learn the mean and standard deviation of the samples\n  normalizer_x.train(x);\n  // now normalize each sample\n  for (size_t i = 0; i < x.size(); ++i) {\n    x[i] = normalizer_x(x[i]);\n  }\n\n  TrainAndSaveNetwork(x, y);\n  TrainAndSaveKRR(x, y);\n\n  // Generate new data\n  std::cout << \"Target values \\n\";\n  std::vector<matrix<double>> new_x(5);\n  for (size_t i = 0; i < 5; ++i) {\n    new_x[i].set_size(1, 1);\n    new_x[i](0, 0) = i;\n    new_x[i] = normalizer_x(new_x[i]);\n    std::cout << func(i) << std::endl;\n  }\n\n  // Predict\n  LoadAndPredictNetwork(new_x);\n  LoadAndPredictKRR(new_x);\n\n  return 0;\n}\n", "meta": {"hexsha": "cc958cc5ce4823ace914d1e63739b74bbd43e066", "size": 2711, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter12/dlib/dlib-save.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter12/dlib/dlib-save.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter12/dlib/dlib-save.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 23.7807017544, "max_line_length": 76, "alphanum_fraction": 0.6414607156, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.6187864217453308}}
{"text": "#ifndef UTIL_HPP\n#define UTIL_HPP\n\n#define SCREEN_WIDTH 1024\n#define SCREEN_HEIGHT 550\n#define SCALE 30.f\n#define PI 3.1459\n#define EXP 2.71828182845904523536\n#define DELIM \",\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nnamespace ublas = boost::numeric::ublas;\ntypedef ublas::matrix<float> matrix;\ntypedef ublas::vector<float> vector;\n\ninline float\nrandom_float (float min, float max)\n{\n  float random = ((float) rand()) / (float) RAND_MAX;\n  float range = max - min;\n  return (random*range) + min;\n}\n\ninline vector\nsigmoid(vector z)\n{\n  for (unsigned long i=0; i < z.size(); ++i)\n  {\n    z(i) = (1.f / (1.f + std::pow(EXP, -z(i))));\n  }\n  return z;\n}\n\ninline std::vector<matrix> split_theta(vector theta, int inputs, int hidden)\n{\n  std::vector<matrix> split_T;\n  matrix Theta1(inputs,hidden);\n  matrix Theta2(hidden+1,1);\n\n  int w_index = 0;\n  for (int i=0; i < hidden; ++i)\n  {\n    for(int k=0; k < inputs; ++k)\n    {\n      Theta1(k,i) = theta(w_index);\n      ++w_index;\n    }\n  }\n\n  for(int j=0; j < hidden; ++j)\n  {\n    Theta2(j,0) = theta(w_index);\n    ++w_index;\n  }\n\n  split_T.push_back(Theta1);\n  split_T.push_back(Theta2);\n\n  return(split_T);\n}\n\n#endif\n", "meta": {"hexsha": "32301fab4ca8d03f9517b2ddd0a358b944076849", "size": 1244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/util.hpp", "max_stars_repo_name": "clomax/pong_neural_net", "max_stars_repo_head_hexsha": "67d3cc9a87c043fc3d05779c83e19030394bcbd2", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util.hpp", "max_issues_repo_name": "clomax/pong_neural_net", "max_issues_repo_head_hexsha": "67d3cc9a87c043fc3d05779c83e19030394bcbd2", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util.hpp", "max_forks_repo_name": "clomax/pong_neural_net", "max_forks_repo_head_hexsha": "67d3cc9a87c043fc3d05779c83e19030394bcbd2", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8484848485, "max_line_length": 76, "alphanum_fraction": 0.6495176849, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.6187864184706451}}
{"text": "#include \"ann.h\"\n#include <boost/range/algorithm/for_each.hpp>\n#include <algorithm>\n\nnamespace ann {\n\n\nfloat calculateLoss(const math::MatrixF &currentOutput, const math::MatrixF &expectedOutput)\n{\n    auto m = static_cast<float>(expectedOutput.getRowCount());\n    auto hatLog = currentOutput.apply(std::logf);\n    auto yml = expectedOutput.hadamardProduct(hatLog);\n    auto LSum = math::sum(yml);\n    auto L = -(1.0f / m) * LSum;\n    return L;\n}\n\nfloat sigmoid(float value)\n{\n    return 1 / (1 + std::expf(value));\n}\n\nfloat sigmoidDerived(float value)\n{\n    const auto s = sigmoid(value);\n    return s * (1.0f - s);\n}\n\nfloat leakyLRU(float value)\n{\n    return std::max<float>(0.01f * value, value);\n}\n\nfloat leakyLRUDerived(float value)\n{\n    return (value < 0.0f) ? 0.01f : 1.0f;\n}\n\n\nvoid ANN::configureNetwork(size_t inputSize)\n{\n    Layer::layerFx f = [](const math::MatrixF &m) {\n        return m.apply(leakyLRU);\n    };\n\n    Layer::layerFx fd = [](const math::MatrixF &m) {\n        return m.apply(leakyLRUDerived);\n    };\n\n    const size_t layerSize1 = 128;\n    const size_t layerSize2 = 64;\n\n    mLayers.emplace_back(inputSize, layerSize1, f, fd);\n    mLayers.emplace_back(layerSize1, layerSize2, f, fd);\n    mLayers.emplace_back(layerSize2, 10, math::columnWiseSoftMax<float>, fd);\n}\n\n\nfloat ANN::train(const math::MatrixF &input, const math::MatrixF &expectedOutput)\n{\n    auto inputData = input;\n    boost::for_each(mLayers, [&inputData](Layer &layer){\n        inputData = layer.feedForward(inputData);\n    });\n\n    auto loss = calculateLoss(mLayers.back().getResult(), expectedOutput);\n\n    auto d = mLayers.back().beginBackPropagation(expectedOutput);\n    std::for_each(mLayers.rbegin() + 1, mLayers.rend(), [&d](Layer &layer){\n        d = layer.calculateGradients(d);\n    });\n\n    boost::for_each(mLayers, [](Layer &layer){\n        layer.applyGradients(0.5f);\n    });\n\n    return loss;\n}\n\nconst math::MatrixF& ANN::test(const math::MatrixF &input)\n{\n    auto inputData = input;\n    boost::for_each(mLayers, [&inputData](Layer &layer) {\n        inputData = layer.feedForward(inputData);\n    });\n    return mLayers.back().getResult();\n}\n\nIANN::trainData ANN::collectTrainData()\n{\n    trainData result;\n\n    auto activationResult = mLayers.back().getResult();\n    const uint32_t numberOfSamples = static_cast<uint32_t>(activationResult.getColumnCount());\n    result.push_back(numberOfSamples);\n    for (size_t i = 0; i < numberOfSamples; ++i)\n    {\n        const uint32_t predictionLabel = static_cast<uint32_t>(math::getMaxElementIndex(activationResult.columnBegin(i), activationResult.columnEnd(i)));\n        result.push_back(predictionLabel);\n    }\n    return result;\n}\n\n}", "meta": {"hexsha": "44f33fec63d1940f4cfb1cd62759a7122d97a3bc", "size": 2685, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libs/ann_lib/src/ann.cpp", "max_stars_repo_name": "elnoir/ge_test", "max_stars_repo_head_hexsha": "a85a6ea95452005c4c6428faa80b1a8b3d4fd6a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libs/ann_lib/src/ann.cpp", "max_issues_repo_name": "elnoir/ge_test", "max_issues_repo_head_hexsha": "a85a6ea95452005c4c6428faa80b1a8b3d4fd6a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libs/ann_lib/src/ann.cpp", "max_forks_repo_name": "elnoir/ge_test", "max_forks_repo_head_hexsha": "a85a6ea95452005c4c6428faa80b1a8b3d4fd6a4", "max_forks_repo_licenses": ["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.8173076923, "max_line_length": 153, "alphanum_fraction": 0.6703910615, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.6187864184706451}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n#include \"graphe.h\"\n\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\ntypedef std::vector<vecteur> matrice;\n\ntypedef std::pair<nombre, nombre> paire;\ntypedef std::vector<paire> vecteur_paire;\n\nENREGISTRER_PROBLEME(83, \"Path sum: four ways\") {\n    // In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, \n    // by moving left, right, up, and down, is indicated in bold red and is equal to 2297.\n    //\n    // Find the minimal path sum, in matrix.txt (right click and \"Save Link/Target As...\"), a 31K \n    // text file containing a 80 by 80 matrix, from the top left to the bottom right by moving left, \n    // right, up, and down.\n    matrice m;\n    std::ifstream ifs(\"data/p083_matrix.txt\");\n    std::string ligne;\n    while (ifs >> ligne) {\n        std::vector<std::string> v;\n        boost::split(v, ligne, boost::is_any_of(\",\"));\n        vecteur l;\n        for (const auto &s: v) {\n            l.push_back(std::stoull(s));\n        }\n        m.push_back(std::move(l));\n    }\n\n    const nombre taille = m.size();\n    graphe::Dijkstra::graphe graphe;\n    for (nombre i = 0; i < taille; ++i)\n        for (nombre j = 0; j < taille; ++j) {\n            vecteur_paire v;\n            const nombre poids = m[i][j];\n            if (i > 0)\n                v.emplace_back((i - 1) * taille + j, poids);\n            if (j > 0)\n                v.emplace_back(i * taille + j - 1, poids);\n            if (i < taille - 1)\n                v.emplace_back((i + 1) * taille + j, poids);\n            if (j < taille - 1)\n                v.emplace_back(i * taille + j + 1, poids);\n\n            graphe[i * taille + j] = v;\n        }\n\n    graphe::Dijkstra dijkstra(graphe, 0, (taille - 1) * (taille + 1));\n    nombre resultat = dijkstra.algorithme() + m[taille - 1][taille - 1];\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "907a1b19ece413a8af325a221cb6846316732cc2", "size": 1959, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme083.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme083.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme0xx/probleme083.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": 34.3684210526, "max_line_length": 101, "alphanum_fraction": 0.5758039816, "num_tokens": 567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6187864184380404}}
{"text": "#include \"RefinedDynamicalSystem.h\"\n#include <boost/timer.hpp>\n#include <set>\n#include <Eigen/QR>\n#include <Eigen/Eigenvalues>\n\nnamespace abstract{\n\n/// Constructs an empty buffer\ntemplate<class scalar>\nCegarSystem<scalar>::CegarSystem(int dimension,int idimension) :\n  DynamicalSystem<scalar>(dimension,idimension)\n{}\n\n/// Solves the Sylvester equation AX+XB=C for X\ntemplate<class scalar>\ntypename CegarSystem<scalar>::MatrixS CegarSystem<scalar>::solveSylvester(const MatrixS &A,const MatrixS &B,const MatrixS &C,bool BisDiagonal)\n{\n  MatrixS U,V;\n  SolverMatrixType refA,refB;\n  interToRef(refA,A);\n  interToRef(refB,B);\n  Eigen::RealSchur<SolverMatrixType> realSchur(refA.transpose());\n  refToInter(U,realSchur.matrixU());//We want transposed so keep it this way\n  refA=realSchur.matrixT().transpose();//Lower triangular\n  if (BisDiagonal) {\n    V=MatrixS::Identity(C.rows(),refB.rows());\n  }\n  else {\n    interToRef(refB,B);\n    realSchur.compute(refB);\n    refToInter(V,realSchur.matrixU());\n    refB=realSchur.matrixT();\n  }\n  MatrixS result=U*C*V;\n  for (int row=0;row<result.rows();row++) {\n    for (int col=0;col<result.cols();col++) {\n      for (int i=0;i<row;i++) {\n        result.coeffRef(row,col)-=refA.coeff(row,i)*result.coeff(i,col);\n      }\n      for (int i=0;i<col;i++) {\n        result.coeffRef(row,col)-=result.coeff(row,i)*refB.coeff(i,col);\n      }\n      result.coeffRef(row,col)/=refA.coeff(row,row)+refB.coeff(col,col);\n    }\n  }\n  return result;\n}\n\n/// Retrieves the characteristic polynomial coefficients of the dynamics\ntemplate <class scalar>\ntypename CegarSystem<scalar>::MatrixS CegarSystem<scalar>::getDynamicPolynomialCoefficients()\n{\n  MatrixC result=MatrixC::Zero(2,m_dimension+1);\n  result.coeffRef(0,0)=ms_one;\n  result.coeffRef(0,1)=-m_eigenValues.coeff(0,0);\n  for (int i=1;i<m_dimension;i++) {\n    result.row(1)=-result.row(0)*m_eigenValues.coeff(i,i);\n    result.block(0,1,1,i+1)+=result.block(1,0,1,i+1);\n  }\n  return result.real();\n}\n\n/// Retrieves the reachability matrix [B AB A^2B ...A^{n-1}B]\ntemplate <class scalar>\ntypename CegarSystem<scalar>::MatrixS CegarSystem<scalar>::getReachabilityMatrix()\n{\n  MatrixS result(m_sensitivity.rows(),m_dimension*m_sensitivity.cols());\n  result.block(0,0,m_sensitivity.rows(),m_sensitivity.cols())=m_sensitivity;\n  MatrixS multiplier=m_dynamics;\n  for (int i=1;i<m_dimension;i++)\n  {\n    result.block(0,i*m_sensitivity.cols(),m_sensitivity.rows(),m_sensitivity.cols())=multiplier*m_sensitivity;\n    multiplier*=m_dynamics;\n  }\n  if (ms_trace_dynamics) ms_logger.logData(result,\"Reachability Matrix\");\n  return result;\n}\n\n/// Retrieves the reachability matrix [1 a1 a2...a_{n-1};0 1 a1 ... a_{n-2}...]\ntemplate <class scalar>\ntypename CegarSystem<scalar>::MatrixS CegarSystem<scalar>::getCanonicalReachabilityMatrix()\n{\n  //TODO: not sure how this works on MIMO\n  MatrixS result=MatrixS::Identity(m_sensitivity.rows(),m_dimension*m_sensitivity.cols());\n  MatrixS coefficients=getDynamicPolynomialCoefficients();\n  if (ms_trace_dynamics>=eTraceDynamics) {\n    MatrixS matrix=coefficients.row(0);\n    ms_logger.logData(matrix,\"Coefficients\");\n  }\n  for (int i=1;i<m_dimension;i++) result.block(i-1,i,1,m_dimension-i)=coefficients.block(0,1,1,m_dimension-i);\n  if (ms_trace_dynamics>=eTraceDynamics) ms_logger.logData(result,\"Canonical Reachability Matrix\");\n  return result;\n}\n\n/// Retrieves the transform matrix T : z=T^{-1}x turns A,B,C into controllable canonical form\ntemplate <class scalar>\ntypename CegarSystem<scalar>::MatrixS CegarSystem<scalar>::getReachableCanonicalTransformMatrix()\n{\n  MatrixS result=getReachabilityMatrix()*getCanonicalReachabilityMatrix();\n  return result.inverse();\n}\n\n/// Retrieves the observability matrix [C CA CA^2 ...CA^{n-1}]^T\ntemplate <class scalar>\ntypename CegarSystem<scalar>::MatrixS CegarSystem<scalar>::getObservabilityMatrix()\n{\n  MatrixS result(m_dimension*m_outputSensitivity.rows(),m_outputSensitivity.cols());\n  result.block(0,0,m_outputSensitivity.rows(),m_outputSensitivity.cols())=m_outputSensitivity;\n  MatrixS multiplier=m_dynamics;\n  for (int i=1;i<m_dimension;i++)\n  {\n    result.block(i*m_outputSensitivity.rows(),0,m_outputSensitivity.rows(),m_outputSensitivity.cols())=m_outputSensitivity*multiplier;\n    multiplier*=m_dynamics;\n  }\n  return result;\n}\n\n/// Retrieves the observability matrix [1 0 ...;a1 1 0 ...;...;a_{n-1}...a1 1]^-1\ntemplate <class scalar>\ntypename CegarSystem<scalar>::MatrixS CegarSystem<scalar>::getInverseCanonicalObservabilityMatrix()\n{\n  //TODO: not sure how this works on MIMO\n  MatrixS result=MatrixS::Identity(m_dimension*m_outputSensitivity.rows(),m_outputSensitivity.cols());\n  MatrixS coefficients=getDynamicPolynomialCoefficients();\n  for (int i=0;i<m_dimension;i++) {\n    for (int j=0;j<i;j++) {\n      result.coeffRef(i,j)=coefficients.coeff(0,m_dimension-i-j-1);\n    }\n  }\n  return result;\n}\n\n/// Retrieves the transform matrix T : z=T^{-1}x turns A,B,C into observable canonical form\ntemplate <class scalar>\ntypename CegarSystem<scalar>::MatrixS CegarSystem<scalar>::getObservableCanonicalTransformMatrix()\n{\n  return getObservabilityMatrix().inverse()*getInverseCanonicalObservabilityMatrix();\n}\n\n/// Retrieves the reference gain\ntemplate <class scalar>\ntypename CegarSystem<scalar>::MatrixS CegarSystem<scalar>::getReferenceGain()\n{\n  return m_outputSensitivity*((m_dynamics-(m_sensitivity*m_feedback)).inverse()*m_sensitivity);\n}\n\n/// Retrieves the reach tube at the given iteration\ntemplate <class scalar>\n/// Retrieves refined dynamics given a safety specification\nAbstractPolyhedra<scalar>& CegarSystem<scalar>::getRefinedDynamics(int refinements,powerS iteration,int directions,inputType_t inputType)\n{\n  AbstractPolyhedra<scalar>&reachTube=getAbstractReachTube(iteration,2,directions,inputType);\n  if (ms_trace_dynamics>=eTraceDynamics) {\n    reachTube.logTableau(\"PreCegar:\",true);\n    reachTube.logVertices(true);\n  }\n  //if (m_safeReachTube.getPolyhedra().contains(reachTube)) return getAbstractDynamics(inputType);\n  if (!m_safeReachTube.isEmpty()) {\n    AbstractPolyhedra<scalar> bounds=synthesiseDynamicBounds(m_inputType,m_safeReachTube.getPolyhedra(eEigenSpace));\n    if (ms_trace_dynamics>=eTraceDynamics) {\n      bounds.logTableau(\"Projected Bounds: \",true);\n    }\n    for(int i=0;(i<refinements) && refineAbstractDynamics(bounds);i++);\n    if (ms_trace_dynamics>=eTraceDynamics) {\n      AbstractPolyhedra<scalar>& result=getRefinedAbstractReachTube(eNormalSpace);\n      result.logTableau(\"PosCegar:\",true);\n      result.logVertices(true);\n    }\n  }\n  return getAbstractDynamics(inputType);\n}\n\n/// Synthesises a bound on the dynamics given a known guard and eigenvectors.\ntemplate<class scalar>\nAbstractPolyhedra<scalar> CegarSystem<scalar>::synthesiseDynamicBounds(inputType_t inputType,AbstractPolyhedra<scalar> &end)\n{\n  m_inputType=inputType;\n  MatrixS vectors;\n  int numVertices;\n  getAbstractVertices(end.getDirections(),vectors,numVertices);\n  vectors.transposeInPlace();\n  MatrixS supports(vectors.rows(),1);\n  MatrixS endSupports=end.getSupports();\n  int perTemplate=supports.rows()/endSupports.rows();\n  for (int i=0;i<endSupports.rows();i++)\n  {\n    for (int j=0;j<perTemplate;j++) {\n      supports.coeffRef(i*perTemplate+j,0)=endSupports.coeff(i,0);\n    }\n  }\n  if (m_inputType>eNoInputs) {\n    MatrixS inSupports=m_accelVertices*end.getDirections();\n    demergeAccelInSupports(supports,inSupports,endSupports.rows());\n  }\n  AbstractPolyhedra<scalar> bounds;\n  bounds.load(vectors,supports);\n  if (ms_trace_dynamics>=eTraceAll) {\n    bounds.logTableau(\"Full Bounds\",true);\n  }\n  bounds.removeRedundancies();\n  return bounds;\n}\n\n/// Creates a model for the quantization noise as an input specification\ntemplate<class scalar>\nAbstractPolyhedra<scalar> CegarSystem<scalar>::generateNoiseInput()\n{\n  int odimension=(m_odimension>0) ? m_odimension : m_dimension;\n  int ndimension=1;\n  AbstractPolyhedra<scalar> result(ndimension);\n  int fbits=m_paramValues.coeff(eNumBits,1)-m_paramValues.coeff(eNumBits,2);\n  if (fbits<=0) fbits=m_paramValues.coeff(eNumBits,0);\n  if (fbits<=0) fbits=func::getDefaultPrec();\n  scalar lsb=func::pow(this->ms_two,-fbits);\n  MatrixS faces(2*ndimension,ndimension);\n  MatrixS supports(2*ndimension,1);\n  faces.block(0,0,ndimension,ndimension)=MatrixS::Identity(ndimension,ndimension);\n  faces.block(ndimension,0,ndimension,ndimension)=-MatrixS::Identity(ndimension,ndimension);\n  scalar fb_noise=m_feedback.cwiseAbs().sum()/*lpNorm<1>()*/+this->ms_one;//|Noise|<(|K|_1+1)lsb assuming q1,q2=1lsb,(q3:=q1->K) = (|K|_1q1+q2)\n  supports.coeffRef(0,0)=lsb*(fb_noise);\n  supports.coeffRef(1,0)=supports.coeff(0,0);\n  result.load(faces,supports);\n  return result;\n}\n\n/// Creates a model for the input of the closed loop\ntemplate<class scalar>\nAbstractPolyhedra<scalar> CegarSystem<scalar>::generateFeedbackInput(int fdimension,bool makeNoise,MatrixS &sensitivity)\n{\n  AbstractPolyhedra<scalar> inputs(0);\n  if (m_reference.getDimension()>0) {\n    inputs.copy(m_reference);\n    fdimension=m_reference.getDimension();\n  }\n  if (m_idimension>fdimension) {\n    MatrixS inputFaces=m_inputs.getFaceDirections().rightCols(m_idimension-fdimension);\n    MatrixS inSupports=m_inputs.getSupports();\n    inputs.concatenate(inputFaces,inSupports);\n  }\n  if (makeNoise) {\n    //m_closedLoop.setInputType(eVariableInputs);\n    AbstractPolyhedra<scalar> noiseInputs=generateNoiseInput();\n    inputs.concatenate(noiseInputs);\n    sensitivity.conservativeResize(m_dimension,inputs.getDimension());\n    sensitivity.block(0,inputs.getDimension()-noiseInputs.getDimension(),m_dimension,noiseInputs.getDimension())=MatrixS::Ones(m_dimension,noiseInputs.getDimension());\n  }\n  return inputs;\n}\n\n/// Retrieves a list of iterations whose reach set fails the specification\ntemplate<class scalar>\nbool CegarSystem<scalar>::findCounterExampleIterations(powerList &iterations,AbstractPolyhedra<scalar> &bounds)\n{\n  AbstractPolyhedra<scalar>& dynamics=getAbstractDynamics(m_inputType);\n  MatrixS &vertices=dynamics.getVertices(true);\n  bool found=false;\n  for (int i=0;i<vertices.rows();i++) {\n    MatrixS point=vertices.row(i);\n    if (!bounds.isInside(point)) {\n      findIterations(point,iterations);\n      found=true;\n    }\n  }\n  return found;\n}\n\n/// Refines the abstraction in order to meet the safety specification\ntemplate<class scalar>\nbool CegarSystem<scalar>::refineAbstractDynamics(AbstractPolyhedra<scalar> &bounds,powerList &iterations)\n{\n  AbstractPolyhedra<scalar>& dynamics=getAbstractDynamics(m_inputType);\n  if (findCounterExampleIterations(iterations,bounds)) {\n    typename powerList::iterator it;\n    for (it=iterations.begin();it!=iterations.end();it++) {\n      addSupportsAtIteration(dynamics,it->first,m_maxIterations);\n    }\n    return true;\n  }\n  return false;\n}\n\n/// Corrects the support set by the input offset\ntemplate <class scalar>\nvoid CegarSystem<scalar>::demergeAccelInSupports(MatrixS &supports,MatrixS &inSupports,int numTemplates)\n{\n  if (!m_hasOnes || (m_inputType==eVariableInputs))  {\n    for (int row=0;row<numTemplates;row++) {\n      int pos=row*m_numVertices;\n      supports.coeffRef(pos,0)-=inSupports.coeff(0,row);\n      for (int point=1;point<m_numVertices;point++) {\n        supports.coeffRef(pos+point,0)-=inSupports.coeff(point%inSupports.rows(),row);\n      }\n    }\n  }\n}\n\n\n/// Retrieves the support set for the inputs\ntemplate <class scalar>\ntypename JordanMatrix<scalar>::MatrixS& CegarSystem<scalar>::getRefinedAccelInSupports()\n{\n  if (m_hasOnes && (m_inputType==eVariableInputs)) {\n    AbstractPolyhedra<scalar>& inputDynamics=getAbstractDynamics(eParametricInputs);\n    MatrixS supports;\n    inputDynamics.maximiseAll(m_abstractInputVertices,supports);\n    m_accelInSupports=supports.transpose();\n    if (ms_trace_dynamics>=eTraceAbstraction) ms_logger.logData(m_accelInSupports,\"Input Supports\",true);\n  }\n  return m_accelInSupports;\n}\n\n/// Retrieves the reach tube at the given iteration\ntemplate <class scalar>\nAbstractPolyhedra<scalar>& CegarSystem<scalar>::getRefinedAbstractReachTube(space_t space,bool guarded)\n{\n  boost::timer timer;\n  AbstractPolyhedra<scalar>& init=m_initialState.getPolyhedra(eEigenSpace);\n  AbstractPolyhedra<scalar>& dynamics=getAbstractDynamics(m_inputType);\n\n  MatrixS& templates=getTemplates(eEigenSpace);\n  if (ms_trace_time) ms_logger.logData(timer.elapsed()*1000,\"Abstract Vertices: \",true);\n  MatrixS supports;\n  if (!dynamics.maximiseAll(m_abstractVertices,supports)) processError(dynamics.getName());\n\n  if (m_inputType>eNoInputs) getRefinedAccelInSupports();\n  if (ms_trace_dynamics>=eTraceAll) {\n    traceSupports(templates,supports,dynamics,m_abstractVertices);\n  }\n  if (m_inputType>eNoInputs) {\n    mergeAccelInSupports(supports,templates.cols());\n    if (ms_trace_dynamics>=eTraceAll) {\n      ms_logger.logData(m_abstractVertices,supports,\"Combined\",true);\n    }\n  }\n  mergeAbstractSupports(templates,supports);\n  MatrixS faces=templates.transpose();\n  m_pAbstractReachTube->mergeLoad(init,faces,supports,eEigenSpace);\n  AbstractPolyhedra<scalar>& result=m_pAbstractReachTube->getPolyhedra(space);\n  if (guarded) getGuardedReachTube(result,space);\n  if (ms_trace_dynamics>=eTraceAbstraction) result.logTableau();\n  m_reachTime=timer.elapsed()*1000;\n  result.setCalculationTime(m_reachTime);\n  if (ms_trace_time) ms_logger.logData(m_reachTime,\"Abstract Reach Time: \",true);\n  return result;\n}\n\n#ifdef USE_LDOUBLE\n  #ifdef USE_SINGLES\n    template class CegarSystem<long double>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class CegarSystem<ldinterval>;\n  #endif\n#endif\n#ifdef USE_MPREAL\n  #ifdef USE_SINGLES\n    template class CegarSystem<mpfr::mpreal>;\n  #endif\n  #ifdef USE_INTERVALS\n    template class CegarSystem<mpinterval>;\n  #endif\n#endif\n\n}\n", "meta": {"hexsha": "a1ab16587c365f7195ecaa7da69aaf68e4b7c351", "size": 13748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/RefinedDynamicalSystem.cpp", "max_stars_repo_name": "SSV-Group/dsverifier", "max_stars_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-08-29T19:23:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-18T22:27:21.000Z", "max_issues_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/RefinedDynamicalSystem.cpp", "max_issues_repo_name": "SSV-Group/dsverifier", "max_issues_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 64.0, "max_issues_repo_issues_event_min_datetime": "2016-09-10T16:29:44.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-15T14:31:06.000Z", "max_forks_repo_path": "toolbox-dssynth/dssynth-tool/benchmark-runner/AACegar/src/RefinedDynamicalSystem.cpp", "max_forks_repo_name": "SSV-Group/dsverifier", "max_forks_repo_head_hexsha": "1daca4704216edf9a360b4a39e00663d94646ad1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-10-09T21:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-05T10:05:32.000Z", "avg_line_length": 37.5628415301, "max_line_length": 167, "alphanum_fraction": 0.7509455921, "num_tokens": 3723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.6187864184009322}}
{"text": "#include \"config.h\"\n#include \"Scene_points_with_normal_item.h\"\n#include \"Scene_polygon_soup_item.h\"\n#include \"Scene_polyhedron_item.h\"\n#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>\n#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n\n#include <CGAL/Random.h>\n\n#include <CGAL/Shape_detection_3.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Alpha_shape_2.h>\n\n#include <QObject>\n#include <QAction>\n#include <QMainWindow>\n#include <QApplication>\n#include <QtPlugin>\n#include <QMessageBox>\n\n#include <boost/foreach.hpp>\n\n#include \"ui_Point_set_shape_detection_plugin.h\"\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Epic_kernel;\ntypedef Epic_kernel::Point_3 Point;\n//typedef CGAL::Point_with_normal_3<Epic_kernel> Point_with_normal;\n//typedef std::vector<Point_with_normal> Point_list;\n//typedef CGAL::Identity_property_map<Point_with_normal> PointPMap;\n//typedef CGAL::Normal_of_point_with_normal_pmap<Epic_kernel> NormalPMap;\nusing namespace CGAL::Three;\nclass Polyhedron_demo_point_set_shape_detection_plugin :\n  public QObject,\n  public Polyhedron_demo_plugin_helper\n{\n  Q_OBJECT\n    Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)\n    Q_PLUGIN_METADATA(IID \"com.geometryfactory.PolyhedronDemo.PluginInterface/1.0\")\n    QAction* actionDetect;\n\npublic:\n  void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface) {\n    actionDetect = new QAction(tr(\"Point Set Shape Detection\"), mainWindow);\n    actionDetect->setObjectName(\"actionDetect\");\n\n    Polyhedron_demo_plugin_helper::init(mainWindow, scene_interface);\n  }\n\n  bool applicable(QAction*) const {\n    Scene_points_with_normal_item* item =\n      qobject_cast<Scene_points_with_normal_item*>(scene->item(scene->mainSelectionIndex()));\n    if (item && item->has_normals())\n      return true;\n    return false;\n  }\n\n  QList<QAction*> actions() const {\n    return QList<QAction*>() << actionDetect;\n  }\n\n  public Q_SLOTS:\n    void on_actionDetect_triggered();\n\nprivate:\n\n  typedef Kernel::Plane_3 Plane_3;\n  \n  void build_alpha_shape (Point_set& points, const Plane_3& plane,\n                          Scene_polyhedron_item* item, double epsilon);\n\n}; // end Polyhedron_demo_point_set_shape_detection_plugin\n\nclass Point_set_demo_point_set_shape_detection_dialog : public QDialog, private Ui::PointSetShapeDetectionDialog\n{\n  Q_OBJECT\npublic:\n  Point_set_demo_point_set_shape_detection_dialog(QWidget * /*parent*/ = 0)\n  {\n    setupUi(this);\n  }\n\n  //QString shapeDetectionMethod() const { return m_shapeDetectionMethod->currentText(); }\n  double cluster_epsilon() const { return m_cluster_epsilon_field->value(); }\n  double epsilon() const { return m_epsilon_field->value(); }\n  unsigned int min_points() const { return m_min_pts_field->value(); }\n  double normal_tolerance() const { return m_normal_tolerance_field->value(); }\n  double search_probability() const { return m_probability_field->value(); }\n  double gridCellSize() const { return 1.0; }\n  bool detect_plane() const { return planeCB->isChecked(); } \n  bool detect_sphere() const { return sphereCB->isChecked(); } \n  bool detect_cylinder() const { return cylinderCB->isChecked(); } \n  bool detect_torus() const { return torusCB->isChecked(); } \n  bool detect_cone() const { return coneCB->isChecked(); }\n  bool generate_alpha() const { return m_generate_alpha->isChecked(); }\n  bool generate_subset() const { return !(m_do_not_generate_subset->isChecked()); }\n};\n\nvoid Polyhedron_demo_point_set_shape_detection_plugin::on_actionDetect_triggered() {\n  CGAL::Random rand(time(0));\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n\n  Scene_points_with_normal_item* item =\n    qobject_cast<Scene_points_with_normal_item*>(scene->item(index));\n\n  Scene_points_with_normal_item::Bbox bb = item->bbox();\n \n  double diam = bb.diagonal_length();\n\n  if(item)\n  {\n    // Gets point set\n    Point_set* points = item->point_set();\n\n    if(points == NULL)\n      return;\n\n    //Epic_kernel::FT diag = sqrt(((points->bounding_box().max)() - (points->bounding_box().min)()).squared_length());\n\n    // Gets options\n    Point_set_demo_point_set_shape_detection_dialog dialog;\n    if(!dialog.exec())\n      return;\n\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n\n    typedef CGAL::Identity_property_map<Point_set::Point_with_normal> PointPMap;\n    typedef CGAL::Normal_of_point_with_normal_pmap<Point_set::Geom_traits> NormalPMap;\n\n    typedef CGAL::Shape_detection_3::Efficient_RANSAC_traits<Epic_kernel, Point_set, PointPMap, NormalPMap> Traits;\n    typedef CGAL::Shape_detection_3::Efficient_RANSAC<Traits> Shape_detection;\n\n    Shape_detection shape_detection;\n    shape_detection.set_input(*points);\n\n    // Shapes to be searched for are registered by using the template Shape_factory\n    if(dialog.detect_plane()){\n        shape_detection.add_shape_factory<CGAL::Shape_detection_3::Plane<Traits> >();\n      }\n    if(dialog.detect_cylinder()){\n      shape_detection.add_shape_factory<CGAL::Shape_detection_3::Cylinder<Traits> >();\n    }\n    if(dialog.detect_torus()){\n       shape_detection.add_shape_factory< CGAL::Shape_detection_3::Torus<Traits> >();\n    }\n    if(dialog.detect_cone()){\n      shape_detection.add_shape_factory< CGAL::Shape_detection_3::Cone<Traits> >();\n    }\n    if(dialog.detect_sphere()){\n      shape_detection.add_shape_factory< CGAL::Shape_detection_3::Sphere<Traits> >();\n    }\n\n    // Parameterization of the shape detection using the Parameters structure.\n    Shape_detection::Parameters op;\n    op.probability = dialog.search_probability();       // probability to miss the largest primitive on each iteration.\n    op.min_points = dialog.min_points();          // Only extract shapes with a minimum number of points.\n    op.epsilon = dialog.epsilon();          // maximum euclidean distance between point and shape.\n    op.cluster_epsilon = dialog.cluster_epsilon();    // maximum euclidean distance between points to be clustered.\n    op.normal_threshold = dialog.normal_tolerance();   // normal_threshold < dot(surface_normal, point_normal); maximum normal deviation.\n\n    // The actual shape detection.\n    shape_detection.detect(op);\n\n    std::cout << shape_detection.shapes().size() << \" shapes found\" << std::endl;\n    //print_message(QString(\"%1 shapes found.\").arg(shape_detection.number_of_shapes()));\n    int index = 0;\n    BOOST_FOREACH(boost::shared_ptr<Shape_detection::Shape> shape, shape_detection.shapes())\n    {\n      CGAL::Shape_detection_3::Cylinder<Traits> *cyl;\n      cyl = dynamic_cast<CGAL::Shape_detection_3::Cylinder<Traits> *>(shape.get());\n      if (cyl != NULL){\n        if(cyl->radius() > diam){\n          continue;\n        }\n      }\n        \n      Scene_points_with_normal_item *point_item = new Scene_points_with_normal_item;\n      BOOST_FOREACH(std::size_t i, shape->indices_of_assigned_points())\n        point_item->point_set()->push_back((*points)[i]);\n      \n      unsigned char r, g, b;\n      r = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n      g = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n      b = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n      point_item->setRbgColor(r, g, b);\n\n      // Providing a useful name consisting of the order of detection, name of type and number of inliers\n      std::stringstream ss;\n      if (dynamic_cast<CGAL::Shape_detection_3::Cylinder<Traits> *>(shape.get())){\n        CGAL::Shape_detection_3::Cylinder<Traits> * cyl \n          = dynamic_cast<CGAL::Shape_detection_3::Cylinder<Traits> *>(shape.get());\n        ss << item->name().toStdString() << \"_cylinder_\" << cyl->radius() << \"_\";\n      }\n      else if (dynamic_cast<CGAL::Shape_detection_3::Plane<Traits> *>(shape.get()))\n        {\n          ss << item->name().toStdString() << \"_plane_\";\n\n          if (dialog.generate_alpha ())\n            {\n              // If plane, build alpha shape\n              Scene_polyhedron_item* poly_item = new Scene_polyhedron_item;\n\n              Plane_3 plane = (Plane_3)(*(dynamic_cast<CGAL::Shape_detection_3::Plane<Traits>*>(shape.get ())));\n              build_alpha_shape (*(point_item->point_set()), plane,\n                                 poly_item, dialog.cluster_epsilon());\n          \n              poly_item->setRbgColor(r-32, g-32, b-32);\n              poly_item->setName(QString(\"%1%2_alpha_shape\").arg(QString::fromStdString(ss.str()))\n                                 .arg (QString::number (shape->indices_of_assigned_points().size())));\n              poly_item->setRenderingMode (Flat);\n              scene->addItem(poly_item);\n            }\n        }\n      else if (dynamic_cast<CGAL::Shape_detection_3::Cone<Traits> *>(shape.get()))\n        ss << item->name().toStdString() << \"_cone_\";\n      else if (dynamic_cast<CGAL::Shape_detection_3::Torus<Traits> *>(shape.get()))\n        ss << item->name().toStdString() << \"_torus_\";\n      else if (dynamic_cast<CGAL::Shape_detection_3::Sphere<Traits> *>(shape.get()))\n        ss << item->name().toStdString() << \"_sphere_\";\n\n\n      ss << shape->indices_of_assigned_points().size();\n\n      //names[i] = ss.str(\t\t\n      point_item->setName(QString::fromStdString(ss.str()));\n      point_item->set_has_normals(true);\n      point_item->setRenderingMode(item->renderingMode());\n      if (dialog.generate_subset())\n        scene->addItem(point_item);\n      else\n        delete point_item;\n\n      ++index;\n    }\n\n    // Updates scene\n    scene->itemChanged(index);\n\n    QApplication::restoreOverrideCursor();\n\n    //     Warn user, maybe choice of parameters is unsuitable\n    //         if (nb_points_to_remove > 0)\n    //         {\n    //           QMessageBox::information(NULL,\n    //                                    tr(\"Points selected for removal\"),\n    //                                    tr(\"%1 point(s) are selected for removal.\\nYou may delete or reset the selection using the item context menu.\")\n    //                                    .arg(nb_points_to_remove));\n    //         }\n    item->setVisible(false);\n  }\n}\n\nvoid Polyhedron_demo_point_set_shape_detection_plugin::build_alpha_shape\n(Point_set& points, const Plane_3& plane, Scene_polyhedron_item* item, double epsilon)\n{\n  typedef Kernel::Point_2  Point_2;\n  typedef CGAL::Alpha_shape_vertex_base_2<Kernel> Vb;\n  typedef CGAL::Alpha_shape_face_base_2<Kernel>  Fb;\n  typedef CGAL::Triangulation_data_structure_2<Vb,Fb> Tds;\n  typedef CGAL::Delaunay_triangulation_2<Kernel,Tds> Triangulation_2;\n  typedef CGAL::Alpha_shape_2<Triangulation_2>  Alpha_shape_2;\n\n\n  std::vector<Point_2> projections;\n  projections.reserve (points.size ());\n\n  for (std::size_t i = 0; i < points.size (); ++ i)\n    projections.push_back (plane.to_2d (points[i]));\n\n  Alpha_shape_2 ashape (projections.begin (), projections.end (), epsilon);\n  \n  std::map<Alpha_shape_2::Vertex_handle, std::size_t> map_v2i;\n\n  Scene_polygon_soup_item *soup_item = new Scene_polygon_soup_item;\n  \n  soup_item->init_polygon_soup(points.size(), ashape.number_of_faces ());\n  std::size_t current_index = 0;\n\n  for (Alpha_shape_2::Finite_faces_iterator it = ashape.finite_faces_begin ();\n       it != ashape.finite_faces_end (); ++ it)\n    {\n      if (ashape.classify (it) != Alpha_shape_2::INTERIOR)\n        continue;\n\n      for (int i = 0; i < 3; ++ i)\n        {\n          if (map_v2i.find (it->vertex (i)) == map_v2i.end ())\n            {\n              map_v2i.insert (std::make_pair (it->vertex (i), current_index ++));\n              Point p = plane.to_3d (it->vertex (i)->point ());\n              soup_item->new_vertex (p.x (), p.y (), p.z ());\n            }\n        }\n      soup_item->new_triangle (map_v2i[it->vertex (0)],\n                               map_v2i[it->vertex (1)],\n                               map_v2i[it->vertex (2)]);\n    }\n\n  soup_item->orient();\n  soup_item->exportAsPolyhedron (item->polyhedron());\n  \n  delete soup_item;\n}\n\n\n#include <QtPlugin>\n\n#include \"Point_set_shape_detection_plugin.moc\"\n", "meta": {"hexsha": "7fd7479ed8ef4f3101bf6661a01a72697c09bf4b", "size": 11956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_shape_detection_plugin.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_shape_detection_plugin.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_shape_detection_plugin.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8181818182, "max_line_length": 153, "alphanum_fraction": 0.6808297089, "num_tokens": 2866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6187581431402149}}
{"text": "//\n// Copyright 2005-2007 Adobe Systems Incorporated\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n\n#include <boost/gil/image.hpp>\n#include <boost/gil/typedefs.hpp>\n#include <boost/gil/extension/io/jpeg.hpp>\n\n// Creates a synthetic image defining the Mandelbrot set.\n// The example relies on a virtual_2d_locator to iterate over the pixels in the destination view.\n// The pixels (of type rgb8_pixel_t) are generated programmatically, and the code shows how to access\n// the colour channels and set them to arbitrary values.\n\n\nusing namespace boost::gil;\n\n// Models a Unary Function\ntemplate <typename P>   // Models PixelValueConcept\nstruct mandelbrot_fn\n{\n    using point_t = boost::gil::point_t;\n    using const_t = mandelbrot_fn;\n    using value_type = P;\n    using reference = value_type;\n    using const_reference = value_type;\n    using argument_type = point_t;\n    using result_type = reference;\n    static constexpr bool is_mutable =false;\n\n    value_type                    _in_color,_out_color;\n    point_t                       _img_size;\n    static const int MAX_ITER=100;        // max number of iterations\n\n    mandelbrot_fn() {}\n    mandelbrot_fn(const point_t& sz, const value_type& in_color, const value_type& out_color) : _in_color(in_color), _out_color(out_color), _img_size(sz) {}\n\n    result_type operator()(const point_t& p) const {\n        // normalize the coords to (-2..1, -1.5..1.5)\n        // (actually make y -1.0..2 so it is asymmetric, so we can verify some view factory methods)\n        double t=get_num_iter(point<double>(p.x/(double)_img_size.x*3-2, p.y/(double)_img_size.y*3-1.0f));//1.5f));\n        t=pow(t,0.2);\n\n        value_type ret;\n        for (std::size_t k=0; k<num_channels<P>::value; ++k)\n            ret[k]=(typename channel_type<P>::type)(_in_color[k]*t + _out_color[k]*(1-t));\n        return ret;\n    }\n\nprivate:\n    double get_num_iter(const point<double>& p) const {\n        point<double> Z(0,0);\n        for (int i=0; i<MAX_ITER; ++i) {\n            Z = point<double>(Z.x*Z.x - Z.y*Z.y + p.x, 2*Z.x*Z.y + p.y);\n            if (Z.x*Z.x + Z.y*Z.y > 4)\n                return i/(double)MAX_ITER;\n        }\n        return 0;\n    }\n};\n\nint main()\n{\n    using deref_t = mandelbrot_fn<rgb8_pixel_t>;\n    using point_t = deref_t::point_t;\n    using locator_t = virtual_2d_locator<deref_t,false>;\n    using my_virt_view_t = image_view<locator_t>;\n\n    boost::function_requires<PixelLocatorConcept<locator_t>>();\n    gil_function_requires<StepIteratorConcept<locator_t::x_iterator>>();\n\n    point_t dims(200,200);\n    my_virt_view_t mandel(dims, locator_t(point_t(0,0), point_t(1,1), deref_t(dims, rgb8_pixel_t(255,0,255), rgb8_pixel_t(0,255,0))));\n    write_view(\"out-mandelbrot.jpg\",mandel, jpeg_tag{});\n\n    return 0;\n}\n", "meta": {"hexsha": "fd89975ec93ed3b515f0ad229466799dfdd929e3", "size": 2876, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/mandelbrot.cpp", "max_stars_repo_name": "DhruvaG2000/gil", "max_stars_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/mandelbrot.cpp", "max_issues_repo_name": "DhruvaG2000/gil", "max_issues_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/mandelbrot.cpp", "max_forks_repo_name": "DhruvaG2000/gil", "max_forks_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5061728395, "max_line_length": 156, "alphanum_fraction": 0.6655076495, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6187435968294649}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include <eve/function/ellint_rg.hpp>\n#include <boost/math/special_functions/ellint_rg.hpp>\n#include <eve/wide.hpp>\n\n\nTTS_CASE_TPL(\"Check eve::ellint_rg behavior\", EVE_TYPE)\n{\n  using elt_t = eve::element_type_t<T>;\n  TTS_ULP_EQUAL(eve::ellint_rg(T(0.2), T(0.4), T(0)),  T(boost::math::ellint_rg(elt_t(0.2), elt_t(0.4), elt_t(0))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rg(T(1.5), T(1), T(7)),T(boost::math::ellint_rg(elt_t(1.5), elt_t(1), elt_t(7))), 1.0);\n  TTS_ULP_EQUAL(eve::ellint_rg(T(2), T(0), T(7)),  T(boost::math::ellint_rg(elt_t(2), elt_t(0), elt_t(7))),   1.5);\n  TTS_ULP_EQUAL(eve::ellint_rg(T(0), T(5), T(7)),  T(boost::math::ellint_rg(elt_t(0), elt_t(5), elt_t(7))),   1.0);\n  TTS_ULP_EQUAL(eve::ellint_rg(T(2), T(5), T(7)),  T(boost::math::ellint_rg(elt_t(2), elt_t(5), elt_t(7))),   1.0);\n                                                                        }\n", "meta": {"hexsha": "a8a0091e3ca42af53f764fbbb855392a67b7e857", "size": 1197, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/real/elliptic/ellint_rg/regular/ellint_rg.hpp", "max_stars_repo_name": "orao/eve", "max_stars_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/unit/module/real/elliptic/ellint_rg/regular/ellint_rg.hpp", "max_issues_repo_name": "orao/eve", "max_issues_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/unit/module/real/elliptic/ellint_rg/regular/ellint_rg.hpp", "max_forks_repo_name": "orao/eve", "max_forks_repo_head_hexsha": "a8bdc6a9cab06d905e8749354cde63776ab76846", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.4090909091, "max_line_length": 123, "alphanum_fraction": 0.5054302423, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.618743587227036}}
{"text": "/* ------------------------------------------------------------------*\\\n                        \u2566\u2550\u2557\u2554\u2550\u2557\u2554\u2566\u2557\u2554\u2550\u2557\u2554\u2550\u2557\u2554\u2550\u2557\n                        \u2560\u2566\u255d\u2551 \u2551\u2551\u2551\u2551\u255a\u2550\u2557\u2551 \u2551\u2551  \n                        \u2569\u255a\u2550\u255a\u2550\u255d\u2569 \u2569\u255a\u2550\u255d\u255a\u2550\u255d\u255a\u2550\u255d\n Reduced Order Modelling, Simulation, Optimization of Coupled Systems \n                            2017-2021\n\n Authors : \n Ashwin Nayak, Andres Prieto, Daniel Fernandez Comesana\n \n Disclaimer :\n In downloading this SOFTWARE you are deemed to have read and agreed to \n the following terms: This SOFTWARE has been designed with an exclusive \n focus on civil applications. It is not to be used for any illegal, \n deceptive, misleading or unethical purpose or in any military \n applications. This includes ANY APPLICATION WHERE THE USE OF THE \n SOFTWARE MAY RESULT IN DEATH, PERSONAL INJURY OR SEVERE PHYSICAL \n OR ENVIRONMENTAL DAMAGE. Any redistribution of the software must \n retain this disclaimer. BY INSTALLING, COPYING, OR OTHERWISE USING \n THE SOFTWARE, YOU AGREE TO THE TERMS ABOVE. IF YOU DO NOT AGREE TO \n THESE TERMS, DO NOT INSTALL OR USE THE SOFTWARE\n\n Acknowledgements:\n The ROMSOC project has received funding from the European Union\u2019s \n Horizon 2020 research and innovation programme under the Marie \n Sk\u0142odowska-Curie Grant Agreement No. 765374.\n\\*-------------------------------------------------------------------*/\n\n// Include necessary PYBIND files\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\nnamespace py = pybind11;\n\n// Include necessary DOLFIN classes\n#include <dolfin/function/Expression.h>\n#include <dolfin/function/Constant.h>\n\n// Include necessary BOOST classes\n#include <boost/math/special_functions/legendre.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/hankel.hpp>\n\n#include <complex>\n#include <iostream>\nclass ScatteringExact_Re : public dolfin::Expression {\n    public:\n    double p0, k, a;\n    ScatteringExact_Re() : dolfin::Expression(), p0(1.0), k(400.),  a(0.05){}\n\n    void eval(Eigen::Ref<Eigen::VectorXd> values, Eigen::Ref<const Eigen::VectorXd> x) const {\n\n        using namespace boost::math;\n\n        std::complex<double> one_i(0.0,1.0);\n\n        double r = x.norm();\n\n        // Compute Scattered field\n        double tol = 1e-10;\n        int l=0;\n        int N=50;\n        std::complex<double> p_sc = 0., p_sc_add = 0.;\n\n        auto J = [&] () -> std::complex<double> {\n                        return ((double)l* sph_bessel(l,k*a) / (k*a) ) - sph_bessel(l+1,k*a);\n                    };\n\n        auto H = [&] () -> std::complex<double> {\n                        return ((double)l* sph_hankel_1(l,k*a) / (k*a) ) - sph_hankel_1(l+1,k*a);\n                    };\n\n        p_sc_add = - p0 * J()* sph_hankel_1(l,k*r) * legendre_p(l,x[0]/r)/ H();\n        p_sc += p_sc_add;\n\n        while ((l<N) && (abs(p_sc_add/p_sc) > tol)) {\n            ++l;\n            std::complex<double>  A_l = (2*l+1.0)*std::pow(one_i,l)*J()/H();\n            p_sc_add = -p0 * A_l * sph_hankel_1(l,k*r) * legendre_p(l,x[0]/r);\n            p_sc += p_sc_add;\n        }\n\n        values[0] = cos(k*x[0]) + p_sc.real();\n    }\n\n};\n\nPYBIND11_MODULE(SIGNATURE, m) {\n    py::class_<ScatteringExact_Re, std::shared_ptr<ScatteringExact_Re>, dolfin::Expression>\n    (m, \"ScatteringExact_Re\")\n    .def(py::init<>())\n    .def_readwrite(\"p0\", &ScatteringExact_Re::p0)\n    .def_readwrite(\"k\", &ScatteringExact_Re::k)\n    .def_readwrite(\"a\", &ScatteringExact_Re::a)\n    ;\n}\n", "meta": {"hexsha": "d48d53d5328dab16c7edcd360fa92a3193d58686", "size": 3433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/02_scattering_sphere/planewave_scattering/exact/uex_re.cpp", "max_stars_repo_name": "ROMSOC/benchmarks-acoustic-propagation", "max_stars_repo_head_hexsha": "14dbe64c0279d25053e17c63b3797d6395cd50cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-21T15:46:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T02:18:56.000Z", "max_issues_repo_path": "source/02_scattering_sphere/planewave_scattering/exact/uex_re.cpp", "max_issues_repo_name": "ROMSOC/benchmarks-acoustic-propagation", "max_issues_repo_head_hexsha": "14dbe64c0279d25053e17c63b3797d6395cd50cc", "max_issues_repo_licenses": ["MIT"], "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/02_scattering_sphere/planewave_scattering/exact/uex_re.cpp", "max_forks_repo_name": "ROMSOC/benchmarks-acoustic-propagation", "max_forks_repo_head_hexsha": "14dbe64c0279d25053e17c63b3797d6395cd50cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-02T00:48:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T00:48:51.000Z", "avg_line_length": 35.7604166667, "max_line_length": 97, "alphanum_fraction": 0.5953976114, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747657, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6186720095499708}}
{"text": "// ism.cpp: test to validate that a matrix is an M matrix\n//\n// Copyright (C) 2017-2020 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 <boost/numeric/mtl/mtl.hpp>\n#include <hprblas>\n#include <matpak/isa/ism.hpp>\n\n// Selects posits or floats\n#define USE_POSIT 0\n\ntemplate<typename Matrix>\nbool isMatrixAnMMatrix(const Matrix& A) {\n\treturn false;\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\n#if USE_POSIT\n\tusing Ty     = sw::unum::posit<8, 0>;\n\tusing Matrix = mtl::dense2D< Ty >;\n\tusing Vector = mtl::dense_vector< Ty >;\n#else\n\tusing Ty     = float;\n\tusing Matrix = mtl::dense2D<float>;\n\tusing Vector = mtl::dense_vector<float>;\n#endif\n\n\tconstexpr int n = 3; // Number of states\n\n\tmtl::dense2D<Ty> A(n, n); // System dynamics matrix\n    \n\tA = 1;  // create identity matrix\n\n\tif (sw::hprblas::ism(A)) {\n\t\tcout << \"A is an M-matrix\\n\" << A << '\\n';\n\t} else {\n\t\tcout << \"A is not an M-Matrix\\n\" << A << '\\n';\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": "d11ca55af8921d0cdc17f705f4e7e74b9af06c37", "size": 1835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/matpak/ism.cpp", "max_stars_repo_name": "fossabot/hpr-blas", "max_stars_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/matpak/ism.cpp", "max_issues_repo_name": "fossabot/hpr-blas", "max_issues_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/matpak/ism.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": 24.7972972973, "max_line_length": 97, "alphanum_fraction": 0.6719346049, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6186170187015773}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//! \\file\r\n//!\\brief Tests for the hyperbolic arcsine function of (fixed_point) for a small digit range.\r\n\r\n#include <cmath>\r\n\r\n#define BOOST_TEST_MODULE test_negatable_func_hyperbolic_arcsine_small\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_func_hyperbolic_arcsine_small)\r\n{\r\n  typedef boost::fixed_point::negatable<7, -24> fixed_point_type;\r\n  typedef fixed_point_type::float_type          float_point_type;\r\n\r\n  const fixed_point_type tol = ldexp(fixed_point_type(1), fixed_point_type::resolution + 4);\r\n\r\n  using std::asinh;\r\n\r\n  // Check positive arguments.\r\n  for(int i = 0; i < 16; ++i)\r\n  {\r\n    const fixed_point_type x = asinh(fixed_point_type(i) / fixed_point_type(3.1415926535897932385L));\r\n    const float_point_type y = asinh(float_point_type(i) / float_point_type(3.1415926535897932385L));\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n\r\n  // Check negative arguments.\r\n  for(int i = 0; i < 16; ++i)\r\n  {\r\n    const fixed_point_type x = asinh(fixed_point_type(-i) / fixed_point_type(3.1415926535897932385L));\r\n    const float_point_type y = asinh(float_point_type(-i) / float_point_type(3.1415926535897932385L));\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n\r\n  fixed_point_type x;\r\n  float_point_type y;\r\n\r\n  // Check the valid zero argument.\r\n  x = asinh(0);\r\n  y = float_point_type(0);\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n\r\n  // Check a positive argument clost to 0.\r\n  x = asinh(1 / (fixed_point_type(97) / 10));\r\n  y = asinh(1 / (float_point_type(97) / 10));\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n\r\n  // Check a negative argument clost to 0.\r\n  x = asinh(-1 / (fixed_point_type(97) / 10));\r\n  y = asinh(-1 / (float_point_type(97) / 10));\r\n\r\n  BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n}\r\n", "meta": {"hexsha": "c61d642935a9e9b1915a7bee5c227ac95f190943", "size": 2303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_hyperbolic_arcsine_small.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_func_hyperbolic_arcsine_small.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_func_hyperbolic_arcsine_small.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8676470588, "max_line_length": 103, "alphanum_fraction": 0.6882327399, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6186170148872324}}
{"text": "#include <stan/math/prim/arr.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <vector>\n\nTEST(MathFunctions, sumZeroSize) {\n  std::vector<double> x;\n  EXPECT_FLOAT_EQ(0.0, stan::math::sum(x));\n}\n\nTEST(MathFunctions, sum) {\n  std::vector<double> x(3);\n\n  x[0] = 1.0;\n  x[1] = 2.0;\n  x[2] = 3.0;\n\n  EXPECT_FLOAT_EQ(6.0, stan::math::sum(x));\n}\n\nTEST(MathFunctions, sub_nan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  std::vector<double> x(3);\n\n  x[0] = 1.0;\n  x[1] = 2.0;\n  x[2] = nan;\n\n  EXPECT_PRED1(boost::math::isnan<double>, stan::math::sum(x));\n}\nTEST(MathMatrix, sum_vector_int) {\n  std::vector<int> x(3);\n  EXPECT_EQ(0, stan::math::sum(x));\n  x[0] = 1;\n  x[1] = 2;\n  x[2] = 3;\n  EXPECT_EQ(6, stan::math::sum(x));\n}\n", "meta": {"hexsha": "98e2fcdbc54c59313bcefb3922be66916490907c", "size": 800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/arr/fun/sum_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/prim/arr/fun/sum_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/prim/arr/fun/sum_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0, "max_line_length": 63, "alphanum_fraction": 0.625, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6186170146454771}}
{"text": "/*\n * This example is based on the MTL tutorial\n * http://www.simunova.com/docs/mtl4/html/using__solvers.html\n */\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/numeric/itl/itl.hpp>\n#include \"idr_s.hpp\"\n\nusing namespace mtl;\nusing namespace itl;\n\nint main(int, char**)\n{\n    const int size = 40, N = size * size; \n    typedef compressed2D<double>  matrix_type;\n    size_t s = 2;\n\n    // Set up a matrix 1,600 x 1,600 with 5-point-stencil\n    matrix_type                   A(N, N);\n    mat::laplacian_setup(A, size, size);\n\n    // Create an ILU(0) preconditioner\n    pc::ilu_0<matrix_type>        P(A);\n    \n    // Set b such that x == 1 is solution; start with x == 0\n    dense_vector<double>          x(N, 1.0), b(N);\n    b= A * x; x= 0;\n    \n    // Termination criterion: r < 1e-6 * b or N iterations\n    noisy_iteration<double>       iter(b, 500, 1.e-6);\n    \n    // Solve Ax == b with left preconditioner P\n    idr_s(A, x, b, P, iter, s);\n\n    return 0;\n}\n", "meta": {"hexsha": "1b5b13302e3f3907e876aaeaf522ec9eb911b619", "size": 986, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ex1.cpp", "max_stars_repo_name": "astudillor/idrs_mtl", "max_stars_repo_head_hexsha": "c9600401fe65ecffe813740c440797c4272cccad", "max_stars_repo_licenses": ["MIT"], "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/ex1.cpp", "max_issues_repo_name": "astudillor/idrs_mtl", "max_issues_repo_head_hexsha": "c9600401fe65ecffe813740c440797c4272cccad", "max_issues_repo_licenses": ["MIT"], "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/ex1.cpp", "max_forks_repo_name": "astudillor/idrs_mtl", "max_forks_repo_head_hexsha": "c9600401fe65ecffe813740c440797c4272cccad", "max_forks_repo_licenses": ["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.9473684211, "max_line_length": 61, "alphanum_fraction": 0.6024340771, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6185390715718694}}
{"text": "#define BOOST_TEST_MODULE \"test_eigen\"\n\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost/test/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mill/math/Matrix.hpp>\n#include <mill/math/Vector.hpp>\n#include <mill/math/EigenSolver.hpp>\n\n#include <random>\n#include <iostream>\nconstexpr static unsigned int seed = 32479327;\nconstexpr static std::size_t N = 1000;\n\ninline double\ndeterminant(const mill::Matrix<double, 3, 3>& mat)\n{\n    return mat(0,0) * mat(1,1) * mat(2,2) +\n           mat(1,0) * mat(2,1) * mat(0,2) +\n           mat(2,0) * mat(0,1) * mat(1,2) -\n           mat(0,0) * mat(2,1) * mat(1,2) -\n           mat(2,0) * mat(1,1) * mat(0,2) -\n           mat(1,0) * mat(0,1) * mat(2,2);\n}\n\nBOOST_AUTO_TEST_CASE(eigenvalues)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(0., 1.0);\n    mill::JacobiEigenSolver solver;\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        mill::Matrix<double, 3, 3> mat;\n        double det = 0.;\n        while(det == 0.)\n        {\n            for(std::size_t i=0; i<3; ++i)\n                for(std::size_t j=i; j<3; ++j)\n                    if(i==j)\n                        mat(i,j) = uni(mt);\n                    else\n                        mat(i,j) = mat(j,i) = uni(mt);\n            det = determinant(mat);\n        }\n\n        auto ev = solver.solve(mat);\n\n        for(std::size_t i=0; i<3; ++i)\n        {\n            mill::Matrix<double, 3, 3> M = mat;\n\n            for(std::size_t j=0; j<3; ++j)\n                M(j, j) -= ev.at(i).first;\n\n            const mill::Vector<double, 3> vec = M * ev.at(i).second;\n            BOOST_CHECK_SMALL(vec[0], 1e-6);\n            BOOST_CHECK_SMALL(vec[1], 1e-6);\n            BOOST_CHECK_SMALL(vec[2], 1e-6);\n        }\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(eigenvalues_dynamic)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(0.0, 1.0);\n    mill::JacobiEigenSolver solver;\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        mill::Matrix<double, mill::DYNAMIC, mill::DYNAMIC> mat({10u, 10u});\n        for(std::size_t i=0; i<mat.col(); ++i)\n        {\n            for(std::size_t j=i; j<mat.row(); ++j)\n            {\n                if(i == j)\n                {\n                    mat(i, j) = uni(mt);\n                }\n                else\n                {\n                    mat(i, j) = mat(j, i) = uni(mt);\n                }\n            }\n        }\n\n        auto ev = solver.solve(mat);\n        for(std::size_t i=0; i<mat.row(); ++i)\n        {\n            auto M = mat;\n\n            for(std::size_t j=0; j<mat.row(); ++j)\n            {\n                M(j, j) -= ev.at(i).first;\n            }\n\n            const auto vec = M * ev.at(i).second;\n            BOOST_CHECK(vec.len() == M.row());\n            BOOST_CHECK(vec.row() == M.row());\n            BOOST_CHECK(vec.col() == 1);\n            for(std::size_t j=0; j<vec.len(); ++j)\n            {\n                BOOST_CHECK_SMALL(vec[j], 1e-5);\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "105155edf66e138cdf91a7f7d36c78c5ab2d7170", "size": 3068, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math/test_eigen.cpp", "max_stars_repo_name": "ToruNiina/Coffee-mill", "max_stars_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-12-11T07:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T07:33:37.000Z", "max_issues_repo_path": "tests/math/test_eigen.cpp", "max_issues_repo_name": "ToruNiina/Coffee-mill", "max_issues_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/math/test_eigen.cpp", "max_forks_repo_name": "ToruNiina/Coffee-mill", "max_forks_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1504424779, "max_line_length": 75, "alphanum_fraction": 0.4788135593, "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6185390674706503}}
{"text": "#pragma once\n\n#include <math.h>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n#include <acado/acado_optimal_control.hpp>\n#include <acado_toolkit.hpp>\n#include <map>\n// #include \"log.h\"\n#include \"mission_planner_types.hpp\"\n#include <trajectory_planner.hpp>\n\ntypedef trajectory_planner::state state;\n\n//! MissionPlannerInspection class\n/*!\n * Abstract base class for mission planner. It cannot be instantiated\n */\n\nclass MissionPlannerInspection : public trajectory_planner::TrajectoryPlanner{\n\n public:\n\n  /**\n   * @brief constructor of the class\n   */\n  MissionPlannerInspection(const trajectory_planner::parameters _param, const inspection_params _inspection_params);\n\n  /**\n   * @brief destructor of the class\n   */\n  virtual ~MissionPlannerInspection();\n\n  /**\n   * @brief changes the desired point to inspect\n   *\n   * @param _point point to inspect\n   */\n  void setPointToInspect(const Eigen::Vector3d &_point) {\n    point_to_inspect_ = std::move(_point);\n  }\n\n  /**\n   * @brief gives the desired point to inspect\n   *\n   * @return point to inspect\n   */\n  Eigen::Vector3d getPointToInspect() { return point_to_inspect_; }\n\n  /**\n   * @brief changes the desired distance to the inspection point\n   *\n   * @param _distance distance to the inspection point\n   */\n  void setDistanceToInspect(const float &_distance) {\n    distance_to_inspect_point_ = _distance;\n  }\n\n  /**\n   * @brief increases/decreases the desired distance to the inspection point\n   *\n   * @param _distance true if increase, false if decrease\n   */\n  void incDistanceToInspect(const bool &_distance) {\n    if (_distance)  setDistanceToInspect(distance_to_inspect_point_ + inspection_params_.inc_distance);\n    else            setDistanceToInspect(distance_to_inspect_point_ - inspection_params_.inc_distance);\n  }\n\n  /**\n   * @brief gives the distance to the inspection point\n   *\n   * @return distance to the inspection point\n   */\n  float getDistanceToInspect() { return distance_to_inspect_point_; }\n\n  /**\n   * @brief changes the desired relative angle of the drones\n   *\n   * @param _angle angle\n   */\n  void setRelativeAngle(const float &_angle) { relative_angle_ = _angle; }\n\n  /**\n   * @brief gives the relative angle\n   *\n   * @return relative angle\n   */\n  float getRelativeAngle() { return relative_angle_; }\n\n  /**\n   * @brief gives the current formation angle of a UAV\n   *\n   * @return formation angle\n   */\n  float getFormationAngle(const int &_id) { return calculateFormationAngle(_id); }\n\n  /**\n   * @brief gives the current inspection distance of a UAV\n   *\n   * @return inspection distance\n   */\n  float getInspectionDistance(const int &_id) { return calculateInspectionDistance(_id); }\n\n  /**\n   * @brief gives the mission status\n   *\n   * @return mission status: true if activated, false if not activated\n   */\n  float getMissionStatus() { return mission_status_; }\n\n  /**\n   * @brief sets the current time (obtained from ROS::Time)\n   */\n  void setCurrentTime(float time_) {current_time_ = time_;}\n\n  /**\n   * @brief sets the mission status\n   *\n   * @param _status mission status\n   */\n  void setMissionStatus(const bool &_status) { mission_status_ = _status; }\n\n  /**\n   * @brief changes the flight mode of the formation\n   *\n   * @param _mode mode\n   */\n  void setFlightMode(const uint &_mode) { flight_mode_ = _mode; }\n\n  /**\n   * @brief increases/decreases the relative angle of the drones\n   *\n   * @param _angle true if increase, false if decrease\n   */\n  void incRelativeAngle(const bool &_angle) {\n    if (_angle)  setRelativeAngle(relative_angle_ + inspection_params_.inc_angle);\n    else         setRelativeAngle(relative_angle_ - inspection_params_.inc_angle);\n  }\n\n  /**\n   * @brief fits a given point to the cylinder/circle where the drones are\n   * moving around\n   *\n   * @param point desired point to fit on the cylinder/circle\n   * @return point on the cylinder/circle\n   */\n  Eigen::Vector3d pointOnCircle(const Eigen::Vector3d point);\n\n  /**\n   * @brief gets the angle of a given point based on the inspection point\n   *\n   * @param point desired point to infer its angle\n   * @return angle (between 0 and PI)\n   */\n  float getPointAngle(const Eigen::Vector3d &_point);\n\n  /**\n   * @brief function that returns if path to describe between two point is clockwise or anticlockwise\n   *\n   * @param _point1 point to start\n   * @param _point2 point to finish\n   * \n   * @return true if clockwise\n   * @return false if anticlockwise\n   */\n  bool isClockwise(const Eigen::Vector3d &_point1, const Eigen::Vector3d &_point2);\n\n  /**\n   * @brief sets a new bunch of waypoints\n   */\n  void setGoals(const std::vector<trajectory_planner::state> &_waypoints) {\n    goals_.clear();\n    for (auto &waypoint : _waypoints) {\n      goals_.push_back(waypoint);\n    }\n  }\n\n\n protected:\n  bool mission_status_ = false;\n  state last_goal_;\n  Eigen::Vector3d point_to_inspect_ = Eigen::Vector3d::Zero();\n  float distance_to_inspect_point_ = 3;\n  float relative_angle_ = 0.7;\n  std::map<int, float> inspection_distance_;\n  std::map<int, float> formation_angle_;\n  inspection_params inspection_params_;\n\n  /**\n   * @brief refreshes the value of the goal points\n   */\n  void refreshGoals() {\n    for (auto &goal : goals_) {\n      goal.pos = pointOnCircle(goal.pos);\n    }\n  }\n\n  /**\n   * @brief gets the total angle to travel given an initial and a final angle\n   *\n   * @param _initial_angle initial angle\n   * @param _final_angle final angle\n   * @return total angle to travel\n   */\n  float getTotalAngle(const float &_initial_angle, const float &_final_angle);\n\n  /**\n   * @brief calculates the formation angle that the leader UAV has with the _id follower UAV\n   *\n   * @param _id id of the follower UAV\n   * @return formation angle\n   */\n  float calculateFormationAngle(const int &_id);\n\n  /**\n   * @brief calculates the inspection distance of the _id UAV\n   *\n   * @param _id id of the follower UAV\n   * @return inspection distance\n   */\n  float calculateInspectionDistance(const int &_id);\n\n\n private:\n  /**\n   * @brief returns an initial trajectory to inspect for the drone according to\n   * the initial pose\n   *\n   * @param initial_pose initial pose of the drone\n   * @return vector of states of the trajectory\n   */\n  virtual std::vector<state> initialTrajectory(\n      const state &initial_pose) = 0;\n\n  /**\n   * @brief returns the inspection trajectory for the drone according to\n   * the initial pose\n   *\n   * @param initial_pose initial pose of the drone\n   * @return vector of states of the trajectory\n   */\n  virtual std::vector<state> inspectionTrajectory(\n      const state &initial_pose) = 0;\n\n  /**\n   * @brief virtual function that makes the following checks\n   *\n   * @return true if all checks are passed\n   * @return false if any ot the check is not passed\n   */\n  virtual bool checks() {\n    std::cout << \"check mission planner abstract\" << std::endl;\n  }\n\n  /**\n   * @brief check if the formation has to inspect\n   *\n   * @return true if the formation has to inspect\n   * @return false if the formation does not have to inspect\n   */\n  virtual bool inspecting();\n\n  /**\n   * @brief gives an initial orientation according to a trajectory given\n   *\n   * @param traj trajectory\n   */\n  virtual void initialOrientation(std::vector<state> &traj);\n\n\n};", "meta": {"hexsha": "c61790f9c9af6ee980713272b6aea9f4ba0f01ef", "size": 7268, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/mission_planner/include/mission_planner_inspection.hpp", "max_stars_repo_name": "grvcTeam/inspection_trajectory_planning", "max_stars_repo_head_hexsha": "edda79eec7b1c2e0d4bada3f7a8faf3be192cda4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/mission_planner/include/mission_planner_inspection.hpp", "max_issues_repo_name": "grvcTeam/inspection_trajectory_planning", "max_issues_repo_head_hexsha": "edda79eec7b1c2e0d4bada3f7a8faf3be192cda4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-03-09T10:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-31T14:13:06.000Z", "max_forks_repo_path": "packages/mission_planner/include/mission_planner_inspection.hpp", "max_forks_repo_name": "grvcTeam/inspection_trajectory_planning", "max_forks_repo_head_hexsha": "edda79eec7b1c2e0d4bada3f7a8faf3be192cda4", "max_forks_repo_licenses": ["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.8191881919, "max_line_length": 116, "alphanum_fraction": 0.6913869015, "num_tokens": 1799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6185109806116549}}
{"text": "#include <array>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <string_view>\n#include <unordered_map>\n\n#include <boost/range/irange.hpp>\n#include <boost/range/istream_range.hpp>\n\nenum class Cmd { on, off, toggle };\n\nusing uint64 = std::uint64_t;\n\nstruct Position {\n\tuint64 row, col;\n};\n\nstruct EndPoints {\n\tstd::string state;\n\tPosition first, last;\n};\n\nauto& operator>>(std::istream& in, Position& pos) {\n\treturn in >> pos.row >> pos.col;\n}\n\nauto& operator>>(std::istream& in, EndPoints& pos) {\n\treturn in >> pos.state >> pos.first >> pos.last;\n}\n\nauto get_total_brightness(std::fstream& file) {\n\n\tconstexpr auto gridlen = uint64{1000};\n\tconstexpr auto numlights = (gridlen * gridlen);\n\n\tauto grid = std::array<uint64, numlights>{};\n\n\tconst auto commands = std::unordered_map<std::string_view, Cmd>{\n\t\t{\"on\", Cmd::on},\n\t\t{\"off\", Cmd::off},\n\t\t{\"toggle\", Cmd::toggle}\n\t};\n\n\tconst auto stream = boost::istream_range<EndPoints>(file);\n\n\tfor(const auto& endpoints : stream) {\n\n\t\tconst auto command = commands.find(endpoints.state)->second;\n\n\t\tconst auto& first = endpoints.first;\n\t\tconst auto& last  = endpoints.last;\n\n\t\tconst auto begin_row = first.row;\n\t\tconst auto end_row   = (last.row + 1);\n\n\t\tfor(const auto row : boost::irange(begin_row, end_row)) {\n\n\t\t\tconst auto begin_col = first.col;\n\t\t\tconst auto end_col   = (last.col + 1);\n\n\t\t\tfor(const auto col : boost::irange(begin_col, end_col)) {\n\n\t\t\t\tconst auto pos = (row * gridlen + col);\n\n\t\t\t\tswitch(command) {\n\t\t\t\t\tcase Cmd::on:\n\t\t\t\t\t\t++grid[pos];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Cmd::off:\n\t\t\t\t\t\tgrid[pos] -= (grid[pos] > 0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase Cmd::toggle:\n\t\t\t\t\t\tgrid[pos] += 2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tstd::cerr << \"WTF?!? Something went really wrong!\" << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn std::accumulate(grid.begin(), grid.end(), uint64{});\n}\n\nint main() {\n\n\tconst auto filename = std::string{\"instructions.txt\"};\n\tauto file = std::fstream{filename};\n\n\tif(file.is_open()) {\n\n\t\tstd::cout << get_total_brightness(file) << std::endl;\n\n\t} else {\n\t\tstd::cerr << \"Error! Could not open \\\"\" << filename << \"\\\"!\" << std::endl;\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "ef8c888becd0e0a6ca8f8b9de99a57389fd0b41f", "size": 2121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day 06 Part 2/main.cpp", "max_stars_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_stars_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-19T20:19:18.000Z", "max_issues_repo_path": "Day 06 Part 2/main.cpp", "max_issues_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_issues_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day 06 Part 2/main.cpp", "max_forks_repo_name": "Miroslav-Cetojevic/aoc-2015", "max_forks_repo_head_hexsha": "2807fcd3fc684843ae4222b25af6fd086fac77f5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0, "max_line_length": 76, "alphanum_fraction": 0.6341348421, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6185109799540441}}
{"text": "#include \"potentials.hpp\"\n#include \"metropolis.hpp\"\n#include \"distance.hpp\"\n#include <cmath>\n#include <cassert>\n#include <stdexcept>\n#include <boost/algorithm/string.hpp>\n#include \"yaml-cpp/yaml.h\"\n\nnamespace pauth {\n\nusing namespace arma;\n\ndouble abstract_LJ_full_potential::_U(const metropolis &sim) const {\n\n  const auto &molecular_ids = sim.molecular_ids();\n  const auto &positions = sim.positions();\n  const auto &edge_lengths = sim.edge_lengths();\n  const auto N = sim.N();\n  double potential = 0;\n\n  #pragma omp parallel for reduction(+:potential)\n  for (auto i = size_t{0}; i < N - 1; ++i) {\n    for (auto j = i + 1; j < N; ++j) {\n\n      const double rij2 = sim.m(positions.col(i), positions.col(j), \n                                edge_lengths);\n      const double rzero = get_rzero(molecular_ids[i], molecular_ids[j]);\n      const double rat2 = (rzero * rzero) / rij2;\n      const double rat6 = rat2 * rat2 * rat2;\n\n      potential += 4.0 * get_well_depth(molecular_ids[i], molecular_ids[j]) *\n                   (rat6 * rat6 - rat6);\n    }\n  }\n\n  return potential;\n}\n\ndouble abstract_LJ_full_potential::_delta_U(const metropolis &sim, const size_t j,\n                                       arma::vec &rn_j) const {\n  \n  const auto &molecular_ids = sim.molecular_ids();\n  const auto &positions = sim.positions();\n  const auto &ro_j = positions.col(j);\n  const auto &edge_lengths = sim.edge_lengths();\n  const auto N = sim.N();\n  double dU = 0;\n\n  #pragma omp parallel for reduction(+:dU)\n  for (auto i = size_t{0}; i < N; ++i) {\n    if (i == j) continue;\n\n    const auto well_depth = get_well_depth(molecular_ids[i], molecular_ids[j]);\n    double rij2 = sim.m(positions.col(i), ro_j, edge_lengths);\n    double rzero = get_rzero(molecular_ids[i], molecular_ids[j]);\n    double rat2 = (rzero * rzero) / rij2;\n    double rat6 = rat2 * rat2 * rat2;\n\n    const double Uo = 4.0 * well_depth * (rat6 * rat6 - rat6);\n    \n    rij2 = sim.m(positions.col(i), rn_j, edge_lengths);\n    rzero = get_rzero(molecular_ids[i], molecular_ids[j]);\n    rat2 = (rzero * rzero) / rij2;\n    rat6 = rat2 * rat2 * rat2;\n\n    const double Un = 4.0 * well_depth * (rat6 * rat6 - rat6);\n   \n    dU += Un - Uo;\n  }\n\n  return dU;\n}\n\narma::vec abstract_LJ_full_potential::_forceij(const metropolis &sim, const size_t i,\n                                          const size_t j) const {\n  const auto &molecular_ids = sim.molecular_ids();\n  const auto &positions = sim.positions();\n  const auto &edge_lengths = sim.edge_lengths();\n  const auto rij = sim.rij(positions.col(i), positions.col(j), edge_lengths);\n  const double _rij2 = dot(rij, rij);\n  const double rzero = get_rzero(molecular_ids[i], molecular_ids[j]);\n  const double rat2 = (rzero * rzero) / _rij2;\n  const double rat6 = rat2 * rat2 * rat2;\n  const double rat8 = rat6 * rat2;\n  const double well_depth = get_well_depth(molecular_ids[i], molecular_ids[j]);\n\n  return rij / rzero * well_depth * (48.0 * rat8 * rat6 - 24.0 * rat8);\n}\n\ndouble abstract_LJ_cutoff_potential::_U(const metropolis &sim) const {\n\n  const auto &molecular_ids = sim.molecular_ids();\n  const auto &positions = sim.positions();\n  const auto &edge_lengths = sim.edge_lengths();\n  const auto N = sim.N();\n  double potential = 0;\n\n  #pragma omp parallel for reduction(+:potential)\n  for (auto i = size_t{0}; i < N - 1; ++i) {\n    for (auto j = i + 1; j < N; ++j) {\n\n      const double rij2 = sim.m(positions.col(i), positions.col(j), \n                                edge_lengths);\n\n      if (rij2 <= _rc2) {\n\n        const double rzero = get_rzero(molecular_ids[i], molecular_ids[j]);\n        const double rz2 = rzero * rzero;\n        const double rz4 = rz2 * rz2;\n        const double rz8 = rz4 * rz4;\n\n        const double dudr_rc = 6.0 * (rz4 * rz2 * rzero) / (_rc7)-12.0 *\n                               (rz8 * rz4 * rzero) / (_rc13);\n        const double u_rc = ((rz8 * rz4) / (_rc12) - (rz4 * rz2) / (_rc6));\n\n        const double rat2 = rz2 / rij2;\n        const double rat6 = rat2 * rat2 * rat2;\n\n        potential += 4.0 * get_well_depth(molecular_ids[i], molecular_ids[j]) *\n                     ((rat6 * rat6 - rat6) - u_rc -\n                      (std::sqrt(rij2) - _cutoff) * dudr_rc);\n      }\n    }\n  }\n\n  return potential;\n}\n\ndouble abstract_LJ_cutoff_potential::_delta_U(const metropolis &sim, \n                                              const size_t j,\n                                              arma::vec &rn_j) const {\n  \n  const auto &molecular_ids = sim.molecular_ids();\n  const auto &positions = sim.positions();\n  const auto &ro_j = positions.col(j);\n  const auto &edge_lengths = sim.edge_lengths();\n  const auto N = sim.N();\n  double dU = 0;\n\n  #pragma omp parallel for reduction(+:dU)\n  for (auto i = size_t{0}; i < N; ++i) {\n    if (i == j) continue;\n\n    const auto rzero = get_rzero(molecular_ids[i], molecular_ids[j]);\n    const auto well_depth = get_well_depth(molecular_ids[i], molecular_ids[j]);\n    const double rz2 = rzero * rzero;\n    const double rz4 = rz2 * rz2;\n    const double rz8 = rz4 * rz4;\n\n    const double dudr_rc = 6.0 * (rz4 * rz2 * rzero) / (_rc7)-12.0 *\n                           (rz8 * rz4 * rzero) / (_rc13);\n    const double u_rc = ((rz8 * rz4) / (_rc12) - (rz4 * rz2) / (_rc6));\n\n    double Uo = 0.0;\n    double rij2 = sim.m(positions.col(i), ro_j, edge_lengths);\n    \n    if (rij2 <= _rc2) {\n      const double rat2 = rz2 / rij2;\n      const double rat6 = rat2 * rat2 * rat2;\n\n      Uo = 4.0 * well_depth *\n           ((rat6 * rat6 - rat6) - u_rc - \n            (std::sqrt(rij2) - _cutoff) * dudr_rc);\n    }\n    \n    double Un = 0.0;\n    rij2 = sim.m(positions.col(i), rn_j, edge_lengths);\n    \n    if (rij2 <= _rc2) {\n      const double rat2 = rz2 / rij2;\n      const double rat6 = rat2 * rat2 * rat2;\n\n      Un = 4.0 * well_depth *\n           ((rat6 * rat6 - rat6) - u_rc - \n            (std::sqrt(rij2) - _cutoff) * dudr_rc);\n    }\n   \n    dU += Un - Uo;\n  }\n\n  return dU;\n}\n\narma::vec abstract_LJ_cutoff_potential::_forceij(const metropolis &sim, \n                                                 const size_t i,\n                                                 const size_t j) const {\n\n  const auto &molecular_ids = sim.molecular_ids();\n  const auto &positions = sim.positions();\n  const auto &edge_lengths = sim.edge_lengths();\n  const auto _rij = sim.rij(positions.col(i), positions.col(j), edge_lengths);\n  const double _rij2 = dot(_rij, _rij);\n\n  if (_rij2 <= _rc2) {\n\n    const double rzero = get_rzero(molecular_ids[i], molecular_ids[j]);\n    const double rz2 = rzero * rzero;\n    const double rz4 = rz2 * rz2;\n    const double rz8 = rz4 * rz4;\n\n    const double dudr_rc = 24.0 * (rz4 * rz2 * rzero) / (_rc7)-48.0 *\n                           (rz8 * rz4 * rzero) / (_rc13);\n\n    const double rat2 = rz2 / _rij2;\n    const double rat6 = rat2 * rat2 * rat2;\n    const double rat8 = rat6 * rat2;\n    const double well_depth =\n        get_well_depth(molecular_ids[i], molecular_ids[j]);\n\n    return _rij / rzero * well_depth *\n           (48.0 * rat8 * rat6 - 24.0 * rat8 + dudr_rc / std::sqrt(_rij2));\n  }\n\n  return arma::zeros(sim.D());\n}\n\ndouble abstract_spring_potential::_U(const metropolis &sim) const {\n\n  const auto N = sim.N();\n  const auto &molecular_ids = sim.molecular_ids();\n  const auto& positions = sim.positions();\n  double potential = 0;\n\n  #pragma omp parallel for reduction(+:potential)\n  for (auto i = size_t{0}; i < N; ++i) {\n    const double r2 = dot(positions.col(i), positions.col(i));\n    potential += 0.5 * get_k(molecular_ids[i]) * r2;\n  }\n\n  return potential;\n}\n\ndouble abstract_spring_potential::_delta_U(const metropolis &sim,\n                                           const size_t j,\n                                           arma::vec &rn_j) const {\n  const arma::vec &ro_j = sim.positions().col(j);\n  return 0.5 * get_k(sim.molecular_ids()[j]) * \n         (dot(rn_j, rn_j) - dot(ro_j, ro_j));\n}\n\nconst_poly_spring_potential::const_poly_spring_potential(\n    const std::initializer_list<double> &coeffs)\n    : pcoeffs(coeffs) {\n\n  for (size_t i = 1; i < pcoeffs.size(); ++i)\n    fcoeffs.push_back(pcoeffs[i] * 2 * i);\n}\n\ndouble const_poly_spring_potential::_U(const metropolis &sim) const {\n\n  const auto N = sim.N();\n  const auto& positions = sim.positions();\n  double potential = 0;\n\n  #pragma omp parallel for reduction(+:potential)\n  for (auto i = size_t{0}; i < N; ++i) {\n    double Ui = 0.0;\n    const double r2 = dot(positions.col(i), positions.col(i));\n    for (auto p = size_t{0}; p < pcoeffs.size(); ++p) {\n      double x = 1;\n      for (auto k = size_t{0}; k < p; ++k)\n        x *= r2;\n      Ui += pcoeffs[p] * x;\n    }\n    potential += Ui;\n  }\n\n  return potential;\n}\n\ndouble const_poly_spring_potential::_delta_U(const metropolis &sim,\n                                             const size_t j,\n                                             arma::vec &rn_j) const {\n  const arma::vec &ro_j = sim.positions().col(j);\n\n  double Uo = 0.0;\n  double r2 = dot(ro_j, ro_j);\n  for (auto p = size_t{0}; p < pcoeffs.size(); ++p) {\n    double x = 1;\n    for (auto k = size_t{0}; k < p; ++k)\n      x *= r2;\n    Uo += pcoeffs[p] * x;\n  }\n\n  double Un = 0.0;\n  r2 = dot(rn_j, rn_j);\n  for (auto p = size_t{0}; p < pcoeffs.size(); ++p) {\n    double x = 1;\n    for (auto k = size_t{0}; k < p; ++k)\n      x *= r2;\n    Un += pcoeffs[p] * x;\n  }\n\n  return Un - Uo;\n}\n\narma::vec const_poly_spring_potential::_forceij(const metropolis &sim, const size_t, \n                                                const size_t) const {\n  return arma::zeros(sim.D());\n}\n\ndouble const_quad_spring_potential::_U(const metropolis &sim) const {\n\n  const auto N = sim.N();\n  const auto &positions = sim.positions();\n  double potential = 0;\n\n  #pragma omp parallel for reduction(+:potential)\n  for (auto i = size_t{0}; i < N; ++i) {\n    const double r2 = dot(positions.col(i), positions.col(i));\n    potential += a * r2 * r2 + b * r2 + c;\n  }\n\n  return potential;\n}\n\ndouble const_quad_spring_potential::_delta_U(const metropolis &sim,\n                                             const size_t j,\n                                             arma::vec &rn_j) const {\n  const arma::vec &ro_j = sim.positions().col(j);\n  const double r2o = dot(ro_j, ro_j);\n  const double r2n = dot(rn_j, rn_j);\n\n  return a * (r2n*r2n - r2o*r2o) + b * (r2n - r2o);\n}\n\narma::vec abstract_spring_potential::_forceij(const metropolis &sim, \n                                                      const size_t, \n                                                      const size_t) const {\n  return arma::zeros(sim.D());\n}\n\narma::vec const_quad_spring_potential::_forceij(const metropolis &sim, const size_t, \n                                                const size_t) const {\n  return arma::zeros(sim.D());\n}\n\ndouble twostate_int_potential::_U(const metropolis &sim) const {\n\n  const auto N = sim.N();\n  const auto &positions = sim.positions();\n\n  double potential = 0.0;\n\n  #pragma omp parallel for reduction(+:potential)\n  for (auto i = size_t{0}; i < N; ++i) {\n    assert(_check_x(positions.col(i)));\n    potential += _Ui(positions.col(i));\n  }\n\n  #pragma omp parallel for reduction(+:potential)\n  for (auto i = size_t{0}; i < N; ++i) {\n    for (auto j = size_t{i+1}; j < N; ++j) {\n      potential += _Ui(positions.col(i)) * _Ui(positions.col(j));\n    }\n  }\n\n  return potential;\n}\n\ndouble twostate_int_potential::_delta_U(const metropolis &sim, const size_t j,\n                                        arma::vec &rn_j) const {\n\n  const auto N = sim.N();\n  const auto &positions = sim.positions();\n\n  double dUi = _Ui(rn_j) - _Ui(positions.col(j));\n  \n  double U2 = 0.0;\n  #pragma omp parallel for reduction(+:U2)\n  for (auto i = size_t{0}; i < N; ++i) {\n    if (i == j) continue;\n    U2 += _Ui(positions.col(i));\n  }\n  \n  return dUi + dUi * U2;\n  \n}\n\narma::vec twostate_int_potential::_forceij(const metropolis &sim, const size_t, \n                                           const size_t) const {\n  return arma::zeros(sim.D());\n}\n\nabstract_LJ_lookup_potential::abstract_LJ_lookup_potential(const char *fname) {\n  vector<string> molecular_strs;\n  const auto well_params = YAML::LoadFile(fname);\n\n  for (const auto &well_param : well_params) {\n    auto molecular_pair_str = well_param.first.as<string>();\n    boost::split(molecular_strs, molecular_pair_str, boost::is_any_of(\",\"));\n    for (auto &molecular_str : molecular_strs) boost::trim(molecular_str);\n    if (molecular_names_to_ids.count(molecular_strs[0]) &&\n        molecular_names_to_ids.count(molecular_strs[1])) {\n      unordered_pair<molecular_id> key { \n        molecular_names_to_ids.at(molecular_strs[0]),\n        molecular_names_to_ids.at(molecular_strs[1]) \n      };\n      _well_depth_map[key] = well_param.second[\"epsilon\"].as<double>();\n      _rzero_map[key] = well_param.second[\"sigma\"].as<double>();\n    }\n    else throw runtime_error(string(\"Molecular pair \") + \n                             well_param.first.as<string>() + \n                             string(\" not found.\"));\n  }\n}\n\ndouble abstract_LJ_lookup_potential::_get_well_depth(const molecular_id id1,\n                                                     const molecular_id id2) const {\n  unordered_pair<molecular_id> key { id1, id2 };\n  return _well_depth_map.at(key);\n}\n\ndouble abstract_LJ_lookup_potential::_get_rzero(const molecular_id id1,\n                                                const molecular_id id2) const {\n  unordered_pair<molecular_id> key { id1, id2 };\n  return _rzero_map.at(key);\n}\n\ndouble dipole_electric_potential::_U(const metropolis &sim) const {\n\n  const auto N = sim.N();\n  const auto &positions = sim.positions();\n  double sum = 0.0;\n\n  #pragma omp parallel for reduction(+:sum)\n  for (auto i = size_t{0}; i < N; ++i) {\n    auto& positionsi = positions.col(i);\n    for (auto& kv : _efield)\n      sum += -(positionsi(kv.first) * kv.second(positionsi));\n  }\n\n  return sum;\n\n}\n\ndouble dipole_electric_potential::_delta_U(const metropolis &sim, \n  const size_t j, arma::vec &dx) const {\n\n  auto& positionsj = sim.positions().col(j);\n\n  double sum = 0.0;\n  for (auto& kv : _efield)\n    sum += -(dx(kv.first) * kv.second(positionsj));\n\n  return sum;\n  \n}\n\narma::vec dipole_electric_potential::_forceij(const metropolis &sim, \n    const size_t, const size_t) const { return arma::zeros(sim.D()); }\n\ndouble abstract_dipole_strain_potential::_U(const metropolis &sim) const {\n  \n  const auto N = sim.N();\n  const auto &positions = sim.positions();\n  const auto &ids = sim.molecular_ids();\n  double sum = 0.0;\n\n  #pragma omp parallel for reduction(+:sum)\n  for (auto i = size_t{0}; i < N; ++i) {\n\n    auto& xsi = positions.col(i);\n    auto pi = p(xsi);\n\n    // Ui = 1/2 * p . X p\n    sum += arma::dot(pi, inv_chi(xsi, ids[i]) * pi);\n\n  }\n\n  return 0.5 * sum;\n\n}\n\ndouble abstract_dipole_strain_potential::_delta_U(const metropolis &sim, \n    const size_t j, arma::vec &dx) const {\n\n  auto& xs = sim.positions().col(j);\n  const auto id = sim.molecular_ids()[j];\n  auto xs_new = xs + dx;\n\n  auto pi = p(xs);\n  auto pnew = p(xs_new);\n\n  return 0.5 * (arma::dot(pi, inv_chi(xs, id) * pi) - \n                arma::dot(pnew, inv_chi(xs_new, id) * pnew));\n\n}\n\narma::vec abstract_dipole_strain_potential::_forceij\n  (const metropolis &sim, const size_t, const size_t) const {\n  return arma::zeros(sim.D()); \n}\n\n// definitions for pure virtual destructors\nabstract_potential::~abstract_potential() {}\nabstract_LJ_potential::~abstract_LJ_potential() {}\nabstract_LJ_full_potential::~abstract_LJ_full_potential() {}\nabstract_LJ_lookup_potential::~abstract_LJ_lookup_potential() {}\nabstract_LJ_cutoff_potential::~abstract_LJ_cutoff_potential() {}\nabstract_spring_potential::~abstract_spring_potential() {}\nabstract_dipole_strain_potential::~abstract_dipole_strain_potential() {}\nabstract_dipole_strain_2d_potential::~abstract_dipole_strain_2d_potential() {}\nabstract_dipole_strain_3d_potential::~abstract_dipole_strain_3d_potential() {}\nabstract_dipole_strain_linear_potential::~abstract_dipole_strain_linear_potential() {}\n\n} // namespace pauth\n", "meta": {"hexsha": "41e04d8a8c7bcfbd47ec3b316bf2bef07deb6d7d", "size": 16050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/potentials.cpp", "max_stars_repo_name": "grasingerm/port-authority", "max_stars_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/potentials.cpp", "max_issues_repo_name": "grasingerm/port-authority", "max_issues_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/potentials.cpp", "max_forks_repo_name": "grasingerm/port-authority", "max_forks_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5324165029, "max_line_length": 86, "alphanum_fraction": 0.6029906542, "num_tokens": 4539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6185109776010153}}
{"text": "// Copyright [2020] Yoonyoung (Jamie) Cho\n\n#include <fmt/format.h>\n#include <Eigen/Core>\n\n#include <boost/functional/hash.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/random.hpp>\n\n#include <unordered_map>\n\n#include \"bglpy/graph.hpp\"\n#include \"bglpy/rrt.hpp\"\n\nstatic const float SquaredDistance(const cho::graph::Node2D& src,\n                                   const cho::graph::Node2D& dst) {\n  const float dx = (src.x - dst.x);\n  const float dy = (src.y - dst.y);\n  return dx * dx + dy * dy;\n}\n\nfloat WorkspaceDistance(const cho::graph::Node2D& node) {\n  using Point = cho::graph::Node2D;\n  static constexpr const float kHipJointOffset = 0.0110;\n  static constexpr const float kKneeLinkLength = 0.0285;\n  static constexpr const float kHipLinkLength = 0.0175;\n\n  static constexpr const float kSmallRadius = kKneeLinkLength - kHipLinkLength;\n  static constexpr const float kLargeRadius = kKneeLinkLength + kHipLinkLength;\n\n  const Point center_a{kHipJointOffset, 0.0f};\n  const Point center_b{-kHipJointOffset, 0.0f};\n  const float radius_a = std::sqrt(SquaredDistance(node, center_a));\n  const float radius_b = std::sqrt(SquaredDistance(node, center_b));\n\n  const std::array<float, 4> distances{\n      {radius_a - kSmallRadius, radius_b - kSmallRadius,\n       kLargeRadius - radius_a, kLargeRadius - radius_b}};\n  const float dist = *std::min_element(distances.begin(), distances.end());\n  return dist;\n}\n\nint main(const int argc, const char* const argv[]) {\n  const cho::graph::Workspace ws{{-0.035, -0.044}, {0.035, 0.044}};\n  const cho::graph::RrtSettings settings{ws, 512, 1e-3, 1e-3};\n  cho::graph::Rrt rrt{settings, cho::graph::SdfFun(WorkspaceDistance)};\n  const cho::graph::Node2D& source{0.0032096, 0.03201624};\n  const cho::graph::Node2D& target{0.01301248, -0.01502493};\n  const std::vector<cho::graph::Node2D>& path =\n      rrt.GetTrajectory(source, target);\n  fmt::print(\"Source : {} {}\\n\", source.x, source.y);\n  fmt::print(\"Target : {} {}\\n\", target.x, target.y);\n  for (const auto& point : path) {\n    fmt::print(\"{} {}\\n\", point.x, point.y);\n  }\n\n  // Eigen::Matrix<std::uint8_t, Eigen::Dynamic, Eigen::Dynamic> grid =\n  // decltype(grid)::Zero(3, 5); const cho::VecVector2i& path =\n  // cho::graph::FindPath(grid, { 0, 0 }, { 2, 4 }); for (const auto& v : path)\n  // {\n  //    fmt::print(\"P {} {}\\n\", v.x(), v.y());\n  //}\n  return 0;\n}\n", "meta": {"hexsha": "a37883edcac4cb67129a38a5e61763da3514c15d", "size": 2364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "astarcpp/graph/src/main.cpp", "max_stars_repo_name": "yycho0108/AStarExplorations", "max_stars_repo_head_hexsha": "15c391a61afb0f1436f54b712eb3850cb029f4ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "astarcpp/graph/src/main.cpp", "max_issues_repo_name": "yycho0108/AStarExplorations", "max_issues_repo_head_hexsha": "15c391a61afb0f1436f54b712eb3850cb029f4ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "astarcpp/graph/src/main.cpp", "max_forks_repo_name": "yycho0108/AStarExplorations", "max_forks_repo_head_hexsha": "15c391a61afb0f1436f54b712eb3850cb029f4ce", "max_forks_repo_licenses": ["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.3692307692, "max_line_length": 79, "alphanum_fraction": 0.6679357022, "num_tokens": 718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6185109651782591}}
{"text": "/**\n * @file 1dwaveabsorbingbc_main.cc\n * @brief NPDE homework \"1DWaveAbsorbingBC\" code\n * @author Oliver Rietmann\n * @date 08.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n\n#include \"1dwaveabsorbingbc.h\"\n\nusing namespace WaveAbsorbingBC1D;\n\nconst static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n                                       Eigen::DontAlignCols, \", \", \"\\n\");\n\nint main() {\n  /* SAM_LISTING_BEGIN_1 */\n  double c = 1.0;\n  double T = 7.0;\n  unsigned int N = 100;\n  unsigned int m = 2000;\n  Eigen::MatrixXd R = waveLeapfrogABC(c, T, N, m);\n  Eigen::VectorXd t = Eigen::VectorXd::LinSpaced(m + 1, 0.0, T);\n\n  // print the data, e.g. to a .csv file, in a suitable way\n  std::ofstream solution_file;\n\n  solution_file.open(\"solution.csv\");\n  Eigen::MatrixXd tR(m + 1, N + 2);\n  tR.col(0) = t;\n  tR.block(0, 1, m + 1, N + 1) = R;\n  solution_file << tR.format(CSVFormat) << std::endl;\n  solution_file.close();\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/solution.csv\" << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR \"/viswave.py \" CURRENT_BINARY_DIR\n              \"/solution.csv \" CURRENT_BINARY_DIR \"/solution.eps\");\n  /* SAM_LISTING_END_1 */\n\n  std::pair<Eigen::VectorXd, Eigen::VectorXd> energies =\n      computeEnergies(R, c, T / m);\n  Eigen::VectorXd E_pot = energies.first;\n  Eigen::VectorXd E_kin = energies.second;\n\n  /* SAM_LISTING_BEGIN_2 */\n  std::ofstream energies_file;\n  energies_file.open(\"energies.csv\");\n  energies_file << t.transpose().format(CSVFormat) << std::endl\n                << E_pot.transpose().format(CSVFormat) << std::endl\n                << E_kin.transpose().format(CSVFormat) << std::endl;\n  energies_file.close();\n  std::cout << \"Generated \" CURRENT_BINARY_DIR \"/energies.csv\" << std::endl;\n  std::system(\"python3 \" CURRENT_SOURCE_DIR\n              \"/visenergies.py \" CURRENT_BINARY_DIR\n              \"/energies.csv \" CURRENT_BINARY_DIR \"/energies.eps\");\n/* SAM_LISTING_END_2 */\n\n  return 0;\n}\n", "meta": {"hexsha": "b4c8f4dd3644b8802cba285db7b901cfc49cf665", "size": 2036, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/1DWaveAbsorbingBC/mastersolution/1dwaveabsorbingbc_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/1DWaveAbsorbingBC/mastersolution/1dwaveabsorbingbc_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/1DWaveAbsorbingBC/mastersolution/1dwaveabsorbingbc_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 31.8125, "max_line_length": 77, "alphanum_fraction": 0.6512770138, "num_tokens": 583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.8289388125473628, "lm_q1q2_score": 0.6185035708781959}}
{"text": "/*(utf8)\nSimple moving average filter\n*/\n\n#include \"filter_base.hpp\"\n#include <boost/circular_buffer.hpp>\n\nnamespace value_filters\n{\n\ntemplate <typename T = double>\nclass floating_average : public filter_base<T>\n{\n\npublic:\n  floating_average()\n  {\n    set_amount(SCALED_AMOUNT);\n  }\n\n  T operator()(T x)\n  {\n    T sum {0};\n\n    this->buffer.push_back(x);\n\n    for (T v : this->buffer)\n      sum += v;\n\n    return sum / this->buffer.size();\n  }\n\n  void set_amount(double amt)\n  {\n    if (amt <= 1)\n      amt = 1;\n    this->buffer.set_capacity(amt);\n  };\n\nprivate:\n  boost::circular_buffer<T> buffer {0};\n};\n\n}\n", "meta": {"hexsha": "b439af74e58b8fea827134a0762285632dfcadb1", "size": 609, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/average.hpp", "max_stars_repo_name": "thibaudk/dno", "max_stars_repo_head_hexsha": "27b7c8040c9739e2ddf78bf6ffcaabf9730d6d2a", "max_stars_repo_licenses": ["MIT"], "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/average.hpp", "max_issues_repo_name": "thibaudk/dno", "max_issues_repo_head_hexsha": "27b7c8040c9739e2ddf78bf6ffcaabf9730d6d2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-03T21:58:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T20:23:47.000Z", "max_forks_repo_path": "include/average.hpp", "max_forks_repo_name": "thibaudk/dno", "max_forks_repo_head_hexsha": "27b7c8040c9739e2ddf78bf6ffcaabf9730d6d2a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:54:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:54:40.000Z", "avg_line_length": 13.5333333333, "max_line_length": 46, "alphanum_fraction": 0.6239737274, "num_tokens": 164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6185035693519596}}
{"text": "#ifndef BODY_HPP\n#define BODY_HPP\n\n#include <armadillo>\n#include \"Math.hpp\"\n\nclass Body\n{\npublic:\n    Body();\n    ~Body() {};\n\n    arma::mat get_TBI();\n    arma::vec get_POSITION();\n    arma::vec get_VELOCITY();\n    arma::vec get_ACCELERATION();\n    arma::vec get_ANG_VEL();\n    arma::vec get_ANGLE();\n    arma::vec get_ANGLE_ACC();\n\nprotected:\n    arma::vec POSITION;\n    arma::vec VELOCITY;\n    arma::vec ACCELERATION;\n    arma::vec ANGLE;\n    arma::vec ANGLE_VEL;\n    arma::vec ANGLE_ACC;\n    arma::mat M;\n    arma::mat I;\n    arma::vec FORCE;\n    arma::vec TORQUE;\n    arma::mat TBI;\n};\n\nclass Ground : public Body\n{\npublic:\n    Ground();\n    ~Ground() {};\n};\n\nclass Mobilized_body : public Body\n{\npublic:\n    Mobilized_body(arma::vec PosIn, arma::vec VelIn, arma::vec AccIn, arma::vec AttIn\n        , arma::vec ANG_VEL_In, arma::vec ANG_ACC_In, double MIn, arma::vec IIn\n        , arma::vec F_In, arma::vec T_In);\n    ~Mobilized_body();\n};\n\n#endif  //BODY_HPP", "meta": {"hexsha": "1dd7bd14a692ed0911e08e6a4bae6899984f147c", "size": 964, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Body.hpp", "max_stars_repo_name": "j8xixo12/Multibody-Dynamics-Solver", "max_stars_repo_head_hexsha": "6102a97b00e3ce59db7fb95acc25be5bd8711984", "max_stars_repo_licenses": ["MIT"], "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/Body.hpp", "max_issues_repo_name": "j8xixo12/Multibody-Dynamics-Solver", "max_issues_repo_head_hexsha": "6102a97b00e3ce59db7fb95acc25be5bd8711984", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Body.hpp", "max_forks_repo_name": "j8xixo12/Multibody-Dynamics-Solver", "max_forks_repo_head_hexsha": "6102a97b00e3ce59db7fb95acc25be5bd8711984", "max_forks_repo_licenses": ["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.9019607843, "max_line_length": 85, "alphanum_fraction": 0.6234439834, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6184334807783577}}
{"text": "/*\r\n * lorenz_gmpxx.cpp\r\n *\r\n * This example demonstrates how odeint can be used with arbitrary precision types.\r\n *\r\n * Copyright 2011-2012 Karsten Ahnert\r\n * Copyright 2011-2012 Mario Mulansky\r\n *\r\n * Distributed under the Boost Software License, Version 1.0.\r\n * (See accompanying file LICENSE_1_0.txt or\r\n * copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n\r\n\r\n#include <iostream>\r\n#include <boost/array.hpp>\r\n\r\n#include <gmpxx.h>\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\n//[ gmpxx_lorenz\r\ntypedef mpf_class value_type;\r\ntypedef boost::array< value_type , 3 > state_type;\r\n\r\nstruct lorenz\r\n{\r\n    void operator()( const state_type &x , state_type &dxdt , value_type t ) const\r\n    {\r\n        const value_type sigma( 10.0 );\r\n        const value_type R( 28.0 );\r\n        const value_type b( value_type( 8.0 ) / value_type( 3.0 ) );\r\n\r\n        dxdt[0] = sigma * ( x[1] - x[0] );\r\n        dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\r\n        dxdt[2] = -b * x[2] + x[0] * x[1];\r\n    }\r\n};\r\n//]\r\n\r\n\r\n\r\n\r\nstruct streaming_observer\r\n{\r\n    std::ostream& m_out;\r\n\r\n    streaming_observer( std::ostream &out ) : m_out( out ) { }\r\n\r\n    template< class State , class Time >\r\n    void operator()( const State &x , Time t ) const\r\n    {\r\n        m_out << t;\r\n        for( size_t i=0 ; i<x.size() ; ++i ) m_out << \"\\t\" << x[i] ;\r\n        m_out << \"\\n\";\r\n    }\r\n};\r\n\r\n\r\n\r\n\r\n\r\n\r\nint main( int argc , char **argv )\r\n{\r\n    //[ gmpxx_integration\r\n    const int precision = 1024;\r\n    mpf_set_default_prec( precision );\r\n\r\n    state_type x = {{ value_type( 10.0 ) , value_type( 10.0 ) , value_type( 10.0 ) }};\r\n\r\n    cout.precision( 1000 );\r\n    integrate_const( runge_kutta4< state_type , value_type >() ,\r\n            lorenz() , x , value_type( 0.0 ) , value_type( 10.0 ) , value_type( value_type( 1.0 ) / value_type( 10.0 ) ) ,\r\n            streaming_observer( cout ) );\r\n    //]\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "6d06b2db45da4c6595bb2bde7d975a599409294a", "size": 1958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/gmpxx/lorenz_gmpxx.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/gmpxx/lorenz_gmpxx.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/gmpxx/lorenz_gmpxx.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 23.3095238095, "max_line_length": 123, "alphanum_fraction": 0.5766087845, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835534888481, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6184035157747989}}
{"text": "//  Copyright Evan Miller 2020\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <boost/math/tools/ulps_plot.hpp>\n#include <boost/core/demangle.hpp>\n#include <boost/math/distributions/kolmogorov_smirnov.hpp>\n\nusing boost::math::tools::ulps_plot;\n\nint main() {\n    using PreciseReal = long double;\n    using CoarseReal = float;\n\n    boost::math::kolmogorov_smirnov_distribution<CoarseReal> dist_coarse(10);\n    auto pdf_coarse = [&, dist_coarse](CoarseReal x) {\n        return boost::math::pdf(dist_coarse, x);\n    };\n    boost::math::kolmogorov_smirnov_distribution<PreciseReal> dist_precise(10);\n    auto pdf_precise = [&, dist_precise](PreciseReal x) {\n        return boost::math::pdf(dist_precise, x);\n    };\n\n    int samples = 2500;\n    int width = 800;\n    PreciseReal clip = 100;\n\n    std::string filename1 = \"kolmogorov_smirnov_pdf_\" + boost::core::demangle(typeid(CoarseReal).name()) + \".svg\";\n    auto plot1 = ulps_plot<decltype(pdf_precise), PreciseReal, CoarseReal>(pdf_precise, 0.0, 1.0, samples);\n    plot1.clip(clip).width(width);\n    std::string title1 = \"Kolmogorov-Smirnov PDF (N=10) ULP plot at \" + boost::core::demangle(typeid(CoarseReal).name()) + \" precision\";\n    plot1.title(title1);\n    plot1.vertical_lines(10);\n    plot1.add_fn(pdf_coarse);\n    plot1.write(filename1);\n}\n", "meta": {"hexsha": "04261a03ee39b4ecf5255d6ddf2e35d9bdc0a25a", "size": 1468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reporting/accuracy/plot_kolmogorov_smirnov_pdf.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "reporting/accuracy/plot_kolmogorov_smirnov_pdf.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/reporting/accuracy/plot_kolmogorov_smirnov_pdf.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.641025641, "max_line_length": 136, "alphanum_fraction": 0.704359673, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6184035049222182}}
{"text": "#include <iomanip>\n#include <iostream>\n\n#include <mxpfit/approx_sph_bessel.hpp>\n\n// #include <mxpfit/math/sph_bessel.hpp>\n\n#include <boost/math/special_functions/bessel.hpp>\n\n//==============================================================================\n// Main\n//==============================================================================\n\nusing Index              = Eigen::Index;\nusing Real               = double;\nusing Complex            = std::complex<Real>;\nusing RealArray          = Eigen::Array<Real, Eigen::Dynamic, 1>;\nusing ComplexArray       = Eigen::Array<Complex, Eigen::Dynamic, 1>;\nusing ExponentialSumType = mxpfit::ExponentialSum<Complex, Complex>;\n\nvoid sph_bessel_kernel_error(int l, const RealArray& x,\n                             const ExponentialSumType& ret,\n                             bool verbose_print = false)\n{\n    RealArray exact(x.size());\n    RealArray approx(x.size());\n\n    for (Index i = 0; i < x.size(); ++i)\n    {\n        // exact(i)  = math::sph_bessel_j(l, x(i));\n        exact(i)  = boost::math::sph_bessel(l, x(i));\n        approx(i) = std::real(ret(x(i)));\n    }\n\n    RealArray abserr(Eigen::abs(exact - approx));\n\n    if (verbose_print)\n    {\n        for (Index i = 0; i < x.size(); ++i)\n        {\n            std::cout << std::setw(24) << x(i) << ' '      // point\n                      << std::setw(24) << exact(i) << ' '  // exact value\n                      << std::setw(24) << approx(i) << ' ' // approximation\n                      << std::setw(24) << abserr(i) << '\\n';\n        }\n    }\n\n    Index imax;\n    abserr.maxCoeff(&imax);\n\n    std::cout << \"\\n  abs. error in interval [\" << x(0) << \",\"\n              << x(x.size() - 1) << \"]\\n\"\n              << \"    maximum : \" << abserr(imax) << '\\n'\n              << \"    averaged: \" << abserr.sum() / x.size() << std::endl;\n}\n\nint main()\n{\n    std::cout.precision(15);\n    std::cout.setf(std::ios::scientific);\n\n    const Real threshold = 1.0e-12;\n    const Real eps       = Eigen::NumTraits<Real>::epsilon();\n    const Index lmax     = 20;\n    const Index N        = 1000000; // # of sampling points\n\n    std::cout\n        << \"# Approximation of spherical Bessel function by exponential sum\\n\";\n\n    RealArray x = Eigen::pow(10.0, RealArray::LinSpaced(N, -5.0, 7.0));\n    ExponentialSumType ret;\n    mxpfit::ApproxSphBesselFunction<Real> sph_bessel_approx;\n    for (Index l = 0; l <= lmax; ++l)\n    {\n        std::cout << \"\\n# --- order \" << l;\n        ret = sph_bessel_approx.compute(l, threshold);\n        const auto thresh_weight =\n            std::max(eps, threshold) / std::sqrt(Real(ret.size()));\n        ret = mxpfit::removeIf(\n            ret, [=](const Complex& /*exponent*/, const Complex& wi) {\n                return std::abs(std::real(wi)) < thresh_weight &&\n                       std::abs(std::imag(wi)) < thresh_weight;\n            });\n\n        const bool verbose = false;\n        sph_bessel_kernel_error(l, x, ret, verbose);\n        std::cout << \" (\" << ret.size() << \" terms approximation)\\n\";\n        std::cout << \"# real(exponent), imag(exponent), real(weight), \"\n                     \"imag(weight)\\n\";\n        for (Index i = 0; i < ret.size(); ++i)\n        {\n            std::cout << std::setw(24) << std::real(ret.exponent(i)) << '\\t'\n                      << std::setw(24) << std::imag(ret.exponent(i)) << '\\t'\n                      << std::setw(24) << std::real(ret.weight(i)) << '\\t'\n                      << std::setw(24) << std::imag(ret.weight(i)) << '\\n';\n        }\n        std::cout << '\\n' << std::endl;\n\n        // std::cout << \"# no. of terms and (exponents, weights)\\n\" << ret <<\n        // '\\n'; std::cout << \"# sum of weights: \" << ret.weights().sum() <<\n        // '\\n';\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "95f5b426211f3187f062c52c9a189d30722ac113", "size": 3737, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/approx_sph_bessel.cpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "examples/approx_sph_bessel.cpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "examples/approx_sph_bessel.cpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2547169811, "max_line_length": 80, "alphanum_fraction": 0.4789938453, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6184034988581874}}
{"text": "/* Copyright 2021-2022 Massachusetts Institute of Technology\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n        https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\n        limitations under the License.\n==============================================================================*/\n\n#define CATCH_CONFIG_MAIN\n\n#include <catch2/catch.hpp>\n\n#include <iostream>\n#include <Eigen/Dense>\n\n#include <gentl/types.h>\n#include <gentl/util/randutils.h>\n#include <gentl/inference/particle_filter.h>\n\nusing gentl::GenerateOptions;\nusing gentl::UpdateOptions;\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\nusing Eigen::indexing::all;\nusing std::valarray;\n\n// *******************************************************************\n// ** forward algorithm to compute ground truth marginal likelihood **\n// *******************************************************************\n\ndouble hmm_forward_alg(const VectorXd& prior,\n                       const MatrixXd& emission_dists,\n                       const MatrixXd& transition_dists,\n                       const std::vector<size_t>& emissions) {\n    assert(prior.rows() == emission_dists.cols());\n    assert(prior.rows() == transition_dists.cols());\n    assert(transition_dists.rows() == transition_dists.rows());\n    double marginal_likelihood = 1.0;\n    VectorXd alpha = prior; // copy\n    for (auto emission : emissions) {\n        auto likelihoods = emission_dists(emission, all).transpose();\n        VectorXd prev_posterior = (alpha.array() * likelihoods.array()).matrix();\n        double denom = prev_posterior.sum();\n        prev_posterior /= denom;\n        alpha = transition_dists * prev_posterior;\n        marginal_likelihood *= denom;\n    }\n    return marginal_likelihood;\n}\n\nTEST_CASE(\"hmm forward algorithm\", \"[particle filtering]\") {\n\n    // test the hmm_forward_alg on a hand-calculated example\n    VectorXd prior {{0.4, 0.6}};\n    MatrixXd emission_dists {\n            {0.1, 0.9}, // dist for state 0\n            {0.7, 0.3} // dist for state 1\n    };\n    emission_dists.transposeInPlace();\n    MatrixXd transition_dists {\n            {0.5, 0.5}, // dist. for state 0\n            {0.2, 0.8} // dist. for state 1\n    };\n    transition_dists.transposeInPlace();\n    std::vector<size_t> obs {1, 0};\n    double expected_marginal_likelihood = 0.0;\n    // z = [0, 0]\n    expected_marginal_likelihood += prior(0) * transition_dists(0, 0) * emission_dists(obs[0], 0) * emission_dists(obs[1], 0);\n    // z = [0, 1]\n    expected_marginal_likelihood += prior(0) * transition_dists(1, 0) * emission_dists(obs[0], 0) * emission_dists(obs[1], 1);\n    // z = [1, 0]\n    expected_marginal_likelihood += prior(1) * transition_dists(0, 1) * emission_dists(obs[0], 1) * emission_dists(obs[1], 0);\n    // z = [1, 1]\n    expected_marginal_likelihood += prior(1) * transition_dists(1, 1)* emission_dists(obs[0], 1) * emission_dists(obs[1], 1);\n    auto actual_marginal_likelihood = hmm_forward_alg(prior, emission_dists, transition_dists, obs);\n    REQUIRE(std::abs(actual_marginal_likelihood - expected_marginal_likelihood) < 1e-16);\n}\n\n// ************************************************************************\n// ** minimum HMM implementation for testing particle filter correctness **\n// ************************************************************************\n\nclass HMMParams {\n    friend class HMM;\n    friend class HMMTrace;\nprivate:\n    const size_t num_states_;\n    const MatrixXd emission_matrix_;\n    std::discrete_distribution<size_t> prior_dist_;\n    std::vector<std::discrete_distribution<size_t>> transition_dists_;\npublic:\n    HMMParams(const VectorXd& prior, const MatrixXd& emission_matrix, const MatrixXd& transition_matrix) :\n            emission_matrix_(emission_matrix), num_states_(emission_matrix.cols()) {\n        if (transition_matrix.rows() != num_states_ || transition_matrix.cols() != num_states_)\n            throw std::logic_error(\"dimension mismatch\");\n        prior_dist_ = std::discrete_distribution<size_t>(prior.cbegin(), prior.cend());\n        for (auto i = 0; i < num_states_; i++) {\n            auto column_vector = transition_matrix(all, i);\n            assert(std::abs(column_vector.sum() - 1.0) < 1e-16);\n            transition_dists_.emplace_back(column_vector.begin(), column_vector.end());\n        }\n    }\n};\n\nclass ParameterStore {};\n\nclass Extend {};\n\nstruct NewObservation {\n    size_t value;\n    NewObservation(size_t value_) : value(value_) {}\n};\n\nclass HMMTrace;\n\nclass HMM {\n    friend class HMMTrace;\n    size_t num_time_steps_;\n    HMMParams& params_;\nprivate:\npublic:\n    explicit HMM(HMMParams& params) : num_time_steps_(0), params_(params) {}\n    std::pair<std::unique_ptr<HMMTrace>,double> generate(\n            std::mt19937& rng, ParameterStore&, const NewObservation& observation,\n            const GenerateOptions& options) const;\n\n};\n\nclass HMMTrace {\n    friend class HMM;\n    HMM model_;\n    std::vector<size_t> emissions_;\n    std::vector<size_t> latents_;\nprivate:\n    HMMTrace(const HMMTrace& other) = default;\n    HMMTrace(HMM model, size_t emission, size_t latent) :\n            emissions_(std::initializer_list<size_t>({emission})),\n            latents_(std::initializer_list<size_t>({latent})),\n            model_(model) {}\npublic:\n    double update(\n            std::mt19937& rng, const Extend&, const NewObservation& observation,\n            const UpdateOptions& options) {\n        if (options.save() || options.precompute_gradient())\n            throw std::logic_error(\"not implemented\");\n        size_t latent = model_.params_.transition_dists_[latents_.back()](rng);\n        double log_weight = std::log(model_.params_.emission_matrix_(observation.value, latent));\n        latents_.emplace_back(latent);\n        emissions_.emplace_back(observation.value);\n        model_.num_time_steps_ += 1;\n        return log_weight;\n    }\n    std::unique_ptr<HMMTrace> fork() {\n        // NOTE: this trace implementation is not efficient, it copies entire histories unnecessarily\n        return std::unique_ptr<HMMTrace>(new HMMTrace(*this));\n    }\n};\n\nstd::pair<std::unique_ptr<HMMTrace>,double> HMM::generate(\n        std::mt19937& rng, ParameterStore&, const NewObservation& observation,\n        const GenerateOptions& options) const {\n    if (options.precompute_gradient())\n        throw std::logic_error(\"not implemented\");\n    size_t latent = params_.prior_dist_(rng);\n    double log_weight = std::log(params_.emission_matrix_(observation.value, latent));\n    auto trace = std::unique_ptr<HMMTrace>(new HMMTrace(*this, observation.value, latent));\n    return {std::move(trace), log_weight};\n}\n\n\nTEST_CASE(\"hmm particle filter\", \"[particle filtering]\") {\n\n    gentl::randutils::seed_seq_fe128 seed_seq {0};\n    std::mt19937 rng(seed_seq);\n\n    VectorXd prior {{0.2, 0.3, 0.5}};\n    MatrixXd emission_matrix {\n            {0.1, 0.2, 0.7},\n            {0.2, 0.7, 0.1},\n            {0.7, 0.2, 0.1}\n    };\n    emission_matrix.transposeInPlace();\n    MatrixXd transition_matrix {\n            {0.4, 0.4, 0.2},\n            {0.2, 0.3, 0.5},\n            {0.9, 0.05, 0.05}\n    };\n    transition_matrix.transposeInPlace();\n    HMMParams params {\n        prior, emission_matrix, transition_matrix\n    };\n\n    HMM model {params};\n\n    // test particle filter\n    std::vector<size_t> data = {0, 0, 1, 2};\n    double expected = std::log(hmm_forward_alg(prior, emission_matrix, transition_matrix, data));\n\n    std::vector<NewObservation> observations;\n    for (auto datum : data)\n        observations.emplace_back(datum);\n\n    size_t num_particles = 10000;\n    gentl::smc::ParticleSystem<HMMTrace,std::mt19937> filter{num_particles, rng};\n    auto observations_it = observations.cbegin();\n    ParameterStore store{};\n    filter.init_step(model, store, *observations_it++);\n    using std::cerr, std::endl;\n    while (observations_it != observations.cend()) {\n        filter.step(Extend{}, *observations_it++);\n        double ess = filter.effective_sample_size();\n        cerr << \"effective sample size: \" << ess << endl;\n        double log_weight = filter.resample();\n        cerr << \"log weight from resample: \" << log_weight << endl;\n    }\n    double actual = filter.log_marginal_likelihood_estimate();\n    cerr << \"actual: \" << actual << \", expected: \" << expected << endl;\n    REQUIRE(std::abs(actual - expected) < 0.02);\n}\n", "meta": {"hexsha": "796717cda6a0b0f50f250ce71f5703341b41a8bf", "size": 8703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/particle_filter.cpp", "max_stars_repo_name": "OpenGen/GenTL", "max_stars_repo_head_hexsha": "ee29ac4a954d3951ae6d9ad5ae0ab8285d30d3a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-19T06:16:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T06:16:09.000Z", "max_issues_repo_path": "tests/particle_filter.cpp", "max_issues_repo_name": "OpenGen/GenTL", "max_issues_repo_head_hexsha": "ee29ac4a954d3951ae6d9ad5ae0ab8285d30d3a5", "max_issues_repo_licenses": ["Apache-2.0"], "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/particle_filter.cpp", "max_forks_repo_name": "OpenGen/GenTL", "max_forks_repo_head_hexsha": "ee29ac4a954d3951ae6d9ad5ae0ab8285d30d3a5", "max_forks_repo_licenses": ["Apache-2.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.1710526316, "max_line_length": 126, "alphanum_fraction": 0.6393197748, "num_tokens": 2112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6184034905565673}}
{"text": "<%\ncfg['compiler_args'] = ['-std=c++11','-DUSE_DOUBLE']\ncfg['include_dirs'] = ['eigen', 'include']\ncfg['sources'] = ['./HODLR_Matrix.cpp',\n    './HODLR_Node.cpp',\n    './HODLR_Tree.cpp',\n    './HODLR_Tree_NonSPD.cpp',\n    './HODLR_Tree_SPD.cpp',\n    './KDTree.cpp',\n    './sample_funs.cpp',\n    './predict.cpp']\nsetup_pybind11(cfg)\n%>\n\n#include <squaredeMat.hpp> //squared exponential kernel\n#include <squaredeP1Mat.hpp>\n#include <random>\n#include <chrono>\n#include <iostream>\n#include <fstream>\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <Eigen/Dense>\n#include \"HODLR_Tree.hpp\"\n#include \"sample_funs.h\"\n\nusing std::gamma_distribution;\nusing std::uniform_real_distribution;\nusing std::normal_distribution;\n\nnamespace py = pybind11;\n\nvoid predict_module(py::module &);\n\nEigen::VectorXd samplefstar_HODLR(Eigen::MatrixXd X, Eigen::MatrixXd Y, Eigen::MatrixXd Xtest, double sig, double rho, double tau, HODLR_Tree* T, double multiplier, std::function<float()> &r_std_normal, int s) {\n  \n    /* \n       Sample a draw of the GP function f*|f, sig, rho, tau, x*.\n       Assume a squared exponential Gaussian Process based on \n       observed function f at new test points x*.\n    */\n\n    int Ntest =  Xtest.rows();  \n    int N =  X.rows();\n    int D =  X.cols();\n   \n    double sigsq = pow(sig, 2.0);\n    double tmpSSR;\n    \n    Eigen::VectorXd fstarsamp(Ntest);\n    Eigen::VectorXd KobsNew(N);\n    \n    for (int i = 0; i < Ntest; i++) {\n      Eigen::RowVectorXd Xtest_i = Xtest.row(i);\n      \n      // Covariance between X and Xtest\n      for (int j = 0; j < N; j++) {\n        Eigen::RowVectorXd tmp = X.row(j) - Xtest_i;\n        tmpSSR = 0.0;\n        for (int d = 0; d < D; d++) {\n          tmpSSR = tmpSSR + pow(tmp(d), 2.0);\n        }\n        KobsNew(j) = sigsq * exp(- tmpSSR * rho);\n      }\n\n      // Variance at Xtest\n      double kNewNew = sigsq + 1e-8;\n      \n      // Posterior mean and variance of f* at xtest(i)\n      double sdstar = pow(kNewNew - (multiplier * KobsNew.transpose() * T->solve(tau * KobsNew))(0, 0), 0.5);\n      double mustar = (multiplier * KobsNew.transpose() * T->solve(tau * Y))(0, 0);\n\n      auto normal_samp = r_std_normal();\n\n      fstarsamp(i) =  sdstar * normal_samp + mustar;     \n    }\n    \n    return fstarsamp;\n}\n\nEigen::VectorXd get_transition_probs_byind(Eigen::VectorXi rhovec_inds, double krnl, int ind_current) {\n  /*\n    Creates transition probability matrix for Metropolis Hastings update of lengthscale\n  */\n  int nrhos = rhovec_inds.rows();\n  Eigen::VectorXd prop_prob(nrhos);\n  for (int i = 0; i < nrhos; i++) {\n    prop_prob(i) = exp(-krnl * pow((double)rhovec_inds(i) - (double)ind_current, 2.0));\n  }\n  prop_prob(ind_current) = 0.0;\n  double sumInv = 1.0 / prop_prob.sum();\n  prop_prob = sumInv * prop_prob;\n  return prop_prob;\n}\n\npy::list sampleGP_HODLR(Eigen::MatrixXd X, Eigen::VectorXd Y, \n                          double sig, Eigen::VectorXd rho_choices, double tau,\n                          bool regression=true,\n                          bool Gibbs_ls=false, bool default_MHkernel=true, \n                          double numeric_MHkernel=-1.0,\n                          double a_f=1, double b_f=1,\n                          double a_tau=1, double b_tau=1, \n                          double tol=1e-12, int M=20, \n                          bool save_fsamps=true, unsigned int seed=169, \n                          int burnin=1000, int nsamps=100, int thin=10, bool verbose=false) {\n  /*\n    C++ sample hyperparameter and function draws \n    from a squared exponential Gaussian Process\n    based on observed data y having precision tau.\n    X   -matrix of locations\n    Y   -matrix of observed data\n    tau -data precision \n    sig -function std deviation\n    rho -length-scale\n    a_f and b_f - prior sig^(-2) ~ Ga(a_f/2, b_f/2)\n    a_tau and b_tau - prior tau ~ Ga(a_tau/2, b_tau/2)\n    tol -specified tolerance for accuracy of calculations\n    Gibbs_ls: bool, whether to use Gibbs or MH to sample length scale\n    M   -Max submatrix size\n  */\n  \n  // For sampling random numbers\n  std::mt19937 generator(seed);\n\n  // For sampling standard uniforms (for MH acceptance evaluation)\n  uniform_real_distribution<float> unif(0, 1); \n  std::function<float()> runif = bind(unif, generator);\n\n  // For sampling standard normals (e.g. for sampling f)\n  normal_distribution<float> normal(0, 1);\n  std::function<float()> r_std_normal = bind(normal, generator);\n  \n  // Data sizes and initializing fsamp and params / transformed params\n  int N = X.rows();\n\n  Eigen::VectorXd KobsNew(N);\n  Eigen::VectorXd fsamp(N);\n\n  double sqrt_tau;\n  if (!regression) { // If you observe non-noisy data\n    fsamp = Y;\n  } \n  else {\n    sqrt_tau = pow(tau, 0.5);\n  }\n\n  double sigsq = pow(sig, 2.0);\n  double prec_f = 1 / sigsq;\n  \n  // Set up HODLR details\n  int n_levels = log(N / M) / log(2);\n  bool is_sym = true; \n  bool is_pd  = true;\n\n  // Create rho and matrices for each value option\n  int nrhos = rho_choices.rows();\n  Eigen::MatrixXd transition_probs_mat(nrhos,nrhos);\n  bool fix_ls;\n  int rho_ind;\n\n  Eigen::VectorXd logdetK_all(nrhos);\n  SQRExponential_Kernel* K_tmp;\n  HODLR_Tree* S_tmp;\n  std::vector<HODLR_Tree*> Svec;\n  Svec.reserve(nrhos);\n\n  if (nrhos != 1) {\n    fix_ls = false; \n    rho_ind = round(nrhos / 2);\n    if (!Gibbs_ls) {\n      // Make transition probability matrix from each \"view\" of the data\n      // (i.e., from each index at which you could make a proposal)\n      bool cond1 = (numeric_MHkernel > 0); \n      double krnl;\n      if (cond1 | default_MHkernel) {\n        if (cond1) {\n          krnl = numeric_MHkernel; \n        }\n\n        if (default_MHkernel) {\n          krnl = 1.0 / pow((double)nrhos, 1.0); \n        }\n\n        Eigen::VectorXi rhovec_inds(nrhos);\n        for (int i = 0; i < nrhos; i++) {\n          rhovec_inds(i) = i;\n        }\n        for (int i = 0; i < nrhos; i++) { // Each col is \"view\" from that index.\n          transition_probs_mat.col(i) = get_transition_probs_byind(rhovec_inds, krnl, i);\n        }\n      } else{\n        printf(\"default_MHkernel must be TRUE or numeric_MHkernel needs to be set > 0(see function description for details).\"); \n      }\n    }\n  } \n  else {\n    fix_ls = true;\n    rho_ind = 0;\n    if (verbose) {\n      printf(\"Length scale fixed to provided input: %.2f.\\n\", rho_choices(rho_ind));\n      printf(\"To sample length scale from discrete options provide vector rho_choices.\\n\");\n    }\n  }\n\n  // Svec here is K in the paper\n  for (int i = 0; i < nrhos; i++) {\n    // Set up squared exponential kernel K with sigf fixed to 1.\n    K_tmp  = new SQRExponential_Kernel(X, N, 1, rho_choices(i));\n    S_tmp  = new HODLR_Tree(n_levels, tol, K_tmp); // Without noise (i.e., Sigma)\n    Svec.push_back(S_tmp);\n    Svec[i]->assembleTree(is_sym, is_pd);\n    Svec[i]->factorize();\n    logdetK_all(i) = Svec[i]->logDeterminant();\n  }\n\n  // Initialize first sample of rho\n  double rho = rho_choices(rho_ind); \n\n  // Set up storage\n  int samp_count = 0;\n  int total_draws = burnin + nsamps * thin;\n  Eigen::VectorXd tau_save(nsamps);\n  Eigen::VectorXd sigf_save(nsamps);\n  Eigen::VectorXd rho_save(nsamps);\n  int nsamps_f = nsamps;\n  if (!save_fsamps) {\n    nsamps_f = 0;\n  }\n  Eigen::MatrixXd f_save(N, nsamps_f);\n  \n  for (int s = 0; s < total_draws; s++) {\n    bool save_samps = (s >= burnin) & (((s + 1) % thin) == 0);\n  \n    // Non-noisy data\n    if (regression) {\n      \n      // Assemble the kernel with noise term tau\n      SQRExponentialP1_Kernel* L  = new SQRExponentialP1_Kernel(X, N, sig, rho, tau);\n      HODLR_Tree* T = new HODLR_Tree(n_levels, tol, L); // With noise (i.e. Sigma + I/tau)\n      T->assembleTree(is_sym, is_pd);\n      T->factorize();\n\n      // Sample f\n      fsamp = samplef_HODLR(X, Y, sig, tau, T, Svec[rho_ind], r_std_normal);\n\n      delete T;\n      delete L;\n    }\n    \n    // Sample function variance\n    prec_f = sample_prec_f(Svec[rho_ind], fsamp, a_f, b_f, generator);\n    sig = pow(prec_f, -0.5); \n    sigsq = pow(sig, 2.0);\n\n    // Sample length scale\n    if (!fix_ls) {\n      if (Gibbs_ls) { \n        rho_ind = sample_rho_gibbs(prec_f, fsamp, Svec, logdetK_all, generator);\n      } \n      else { \n        rho_ind = sample_rho_mh(rho_ind, transition_probs_mat, prec_f, fsamp, Svec, logdetK_all, generator, runif);\n      }\n      rho = rho_choices(rho_ind);\n    }\n    \n    // Sample noise precision\n    if (regression) {\n      tau = sample_tau(Y, fsamp, a_tau, b_tau, generator);\n      sqrt_tau = pow(tau, 0.5);\n    }\n    \n    if ((s == burnin) and verbose) {\n      printf(\"Finished with burnin, beginning sampling. \\n\");\n    }\n    if ((10 * (s + 1) % total_draws == 0) and verbose) {\n      printf(\"%d%% done \\n\", 100 * (s + 1) / total_draws);\n    }\n    \n    // Save samples if you're past burnin\n    if (save_samps) {\n      if (regression) {\n        tau_save(samp_count) = tau;\n      }\n      sigf_save(samp_count) = sig;\n      rho_save(samp_count) = rho;\n      \n      if (save_fsamps) {\n        f_save.col(samp_count) = fsamp;\n      }\n\n      samp_count = samp_count + 1;\n    }\n    \n  } // END for (int s=0; s < total_draws; s++)\n\n  delete S_tmp;\n  delete K_tmp;\n  std::vector<HODLR_Tree*>().swap(Svec);\n  \n  py::list out;\n  out.append(tau_save);\n  out.append(sigf_save);\n  out.append(rho_save);\n  out.append(f_save);\n  return out;\n}\n\nPYBIND11_MODULE(sample, m) {\n    m.doc() = \"C++ Implementation of FIFA-GP.\";\n    m.def(\"samplegp\", &sampleGP_HODLR, \"1-d GP.\");\n    predict_module(m);\n}", "meta": {"hexsha": "1814eb4780b7b2eb4b2c7f7171663b45acc34241", "size": 9445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fifa_gp/sample.cpp", "max_stars_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_stars_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fifa_gp/sample.cpp", "max_issues_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_issues_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fifa_gp/sample.cpp", "max_forks_repo_name": "vittorioorlandi/STA663_FIFA_GP", "max_forks_repo_head_hexsha": "cb5532f8104fa630b8ea6930f414e3228349ae52", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2724358974, "max_line_length": 211, "alphanum_fraction": 0.6088935945, "num_tokens": 2804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6183080627497807}}
{"text": "#include \"CGAL_point_transform_function.hpp\"\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Regular_triangulation_3.h>\n#include <CGAL/Regular_triangulation_euclidean_traits_3.h>\n#include <CGAL/Fixed_alpha_shape_3.h>\n#include <CGAL/Triangulation_vertex_base_with_info_3.h>\n#include <CGAL/Fixed_alpha_shape_vertex_base_3.h>\n#include <CGAL/Fixed_alpha_shape_cell_base_3.h>\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <utility>\n#include <iterator>\n#include <stdexcept>\n\n#include <iostream>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Regular_triangulation_euclidean_traits_3<K> Gt;\ntypedef CGAL::Triangulation_vertex_base_with_info_3<unsigned int, Gt> Tb;\ntypedef CGAL::Fixed_alpha_shape_vertex_base_3<Gt, Tb> Vb;\ntypedef CGAL::Fixed_alpha_shape_cell_base_3<Gt> Fb;\ntypedef CGAL::Triangulation_data_structure_3<Vb,Fb> Tds;\ntypedef CGAL::Regular_triangulation_3<Gt,Tds> Triangulation_3;\ntypedef CGAL::Fixed_alpha_shape_3<Triangulation_3> Fixed_alpha_shape_3;\ntypedef Fixed_alpha_shape_3::Cell_handle Cell_handle;\ntypedef Fixed_alpha_shape_3::Vertex_handle Vertex_handle;\ntypedef Fixed_alpha_shape_3::Facet Facet;\ntypedef Fixed_alpha_shape_3::Edge Edge;\ntypedef Gt::Weighted_point Weighted_point;\ntypedef Gt::Bare_point Bare_point;\n\ntemplate <typename T>\nT* init_mem(unsigned int size, const T& init_val){\n\tT* mem = (T*)malloc(sizeof(T)*size);\n\tif(!mem){\n\t\tthrow std::runtime_error(\"Insufficient memory\");\n\t}\n\tfor(unsigned int i = 0; i < size; ++i){\n\t\tmem[i] = init_val;\n\t}\n\treturn mem;\n}\n\nvoid alpha_shapes(\n\tunsigned int num_points, double alpha, \n\tconst double* points, const double* weights, \n\tunsigned int* num_edges, unsigned int** edges, \n\tunsigned int* num_triangles, unsigned int** triangles, \n\tunsigned int* num_tetrahedra, unsigned int** tetrahedra\n){\n\tbusv::CGALPointTransformFunction<Gt> tfunc(points, weights);\n\tunsigned int i;\n\n\tstd::cout << \"alpha \" << alpha << std::endl;\n\n\t//build one alpha_shape with alpha=0\n\tFixed_alpha_shape_3 as(\n\t\tboost::make_transform_iterator(boost::counting_iterator<unsigned int>(0), tfunc), \n\t\tboost::make_transform_iterator(boost::counting_iterator<unsigned int>(num_points), tfunc), \n\t\talpha\n\t);\n\n\n\ti = 0;\n\t*num_edges = std::distance(as.finite_edges_begin(), as.finite_edges_end());\n\t*edges = init_mem<unsigned int>((*num_edges)*2, 0);\n\tfor(Fixed_alpha_shape_3::Finite_edges_iterator it = as.finite_edges_begin(), eit = as.finite_edges_end(); it!= eit; ++it){\n\t\tFixed_alpha_shape_3::Edge e = *it;\n\t\t//if(as.classify(e) == Fixed_alpha_shape_3::SINGULAR){\n\t\tif(as.classify(e) != Fixed_alpha_shape_3::EXTERIOR){\n\t\t\t(*edges)[i] = e.first->vertex(e.second)->info();\n\t\t\t(*edges)[i+1] = e.first->vertex(e.third)->info();\n\t\t\ti += 2;\n\t\t}\n//\t\t(*edges)[i] = it->vertex(0)->info();\n//\t\t(*edges)[i+1] = it->vertex(1)->info();\n\t}\n\t*num_edges = i/2;\n\n\ti = 0;\n\t*num_triangles = std::distance(as.finite_facets_begin(), as.finite_facets_end());\n\t*triangles = init_mem<unsigned int>((*num_triangles)*3, 0);\n\tfor(Fixed_alpha_shape_3::Finite_facets_iterator it = as.finite_facets_begin(), eit = as.finite_facets_end(); it!= eit; ++it){\n\t\tFixed_alpha_shape_3::Facet f = *it;\n\t\t//if(as.classify(f) == Fixed_alpha_shape_3::SINGULAR){\n\t\tif(as.classify(f) != Fixed_alpha_shape_3::EXTERIOR){\n\t\t\t(*triangles)[i] = f.first->vertex((f.second+1)%4)->info();\n\t\t\t(*triangles)[i+1] = f.first->vertex((f.second+2)%4)->info();\n\t\t\t(*triangles)[i+2] = f.first->vertex((f.second+3)%4)->info();\n\t\t\ti += 3;\n\t\t}\n\t}\n\t*num_triangles = i/3;\n\n\ti = 0;\n\t*num_tetrahedra = std::distance(as.finite_cells_begin(), as.finite_cells_end());\n\t*tetrahedra = init_mem<unsigned int>((*num_tetrahedra)*4, 0);\n\tfor(Fixed_alpha_shape_3::Finite_cells_iterator it = as.finite_cells_begin(), eit = as.finite_cells_end(); it!= eit; ++it){\n\t\tFixed_alpha_shape_3::Cell c = *it;\n\t\t//if(as.classify(it) == Fixed_alpha_shape_3::INTERIOR){\n//\t\tif(as.classify(it) != Fixed_alpha_shape_3::EXTERIOR){\n\t\t\t(*tetrahedra)[i] = c.vertex(0)->info();\n\t\t\t(*tetrahedra)[i+1] = c.vertex(1)->info();\n\t\t\t(*tetrahedra)[i+2] = c.vertex(2)->info();\n\t\t\t(*tetrahedra)[i+3] = c.vertex(3)->info();\n\t\t\ti += 4;\n//\t\t}\n\t}\n\t*num_tetrahedra = i/4;\n}\t\n\n\n", "meta": {"hexsha": "3e8d8c1114f4223481882e2035370226e07cfeda", "size": 4224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/alpha_shapes/inex_unfinished/alpha_shapes.cpp", "max_stars_repo_name": "academicRobot/mmstructlib", "max_stars_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/alpha_shapes/inex_unfinished/alpha_shapes.cpp", "max_issues_repo_name": "academicRobot/mmstructlib", "max_issues_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/alpha_shapes/inex_unfinished/alpha_shapes.cpp", "max_forks_repo_name": "academicRobot/mmstructlib", "max_forks_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3805309735, "max_line_length": 126, "alphanum_fraction": 0.7284564394, "num_tokens": 1310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425377849806, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.6183048300665269}}
{"text": "#ifndef TASK_VQEPARAMETERGENERATOR_HPP_\n#define TASK_VQEPARAMETERGENERATOR_HPP_\n\n#include \"XACC.hpp\"\n#include <Eigen/Dense>\n#include <boost/math/constants/constants.hpp>\n\nnamespace xacc {\nnamespace vqe {\n\nclass VQEParameterGenerator {\n\npublic:\n\n\tstatic Eigen::VectorXd generateParameters(const int nParameters, std::shared_ptr<Communicator> comm) {\n\n\t\tif (xacc::optionExists(\"vqe-parameters\")) {\n\t\t\tif (xacc::getOption(\"vqe-task\") == \"sweep-1d\") {\n\t\t\t\tauto paramStr = xacc::getOption(\"vqe-parameters\");\n\n\t\t\t\t// HERE WE COULD HAVE SOMETHING LIKE EITHER\n\t\t\t\t// 50:-3.14,3.14 or\n\t\t\t\t// -3.14,3.14\n\t\t\t\tstd::vector<std::string> split, colon;\n\t\t\t\tboost::split(split, paramStr, boost::is_any_of(\",\"));\n\t\t\t\tint nSteps = 50;\n\t\t\t\tstd::string minVal;\n\t\t\t\tif (boost::contains(paramStr, \":\")) {\n\t\t\t\t\tboost::split(colon, split[0], boost::is_any_of(\":\"));\n\t\t\t\t\tnSteps = std::stoi(colon[0]);\n\t\t\t\t\tminVal = colon[1];\n\t\t\t\t} else {\n\t\t\t\t\tminVal = split[0];\n\t\t\t\t}\n\n\t\t\t\treturn Eigen::VectorXd::LinSpaced(nSteps, std::stod(minVal),\n\t\t\t\t\t\tstd::stod(split[1]));\n\t\t\t} else {\n\t\t\t\tauto paramStr = xacc::getOption(\"vqe-parameters\");\n\t\t\t\tstd::vector<std::string> split;\n\t\t\t\tboost::split(split, paramStr, boost::is_any_of(\",\"));\n\t\t\t\tEigen::VectorXd params(nParameters);\n\t\t\t\tfor (int i = 0; i < split.size(); i++) {\n\t\t\t\t\tparams(i) = std::stod(split[i]);\n\t\t\t\t}\n\n\t\t\t\treturn params;\n\t\t\t}\n\t\t} else {\n\t\t\tstd::srand(time(0));\n\t\t\tauto pi = boost::math::constants::pi<double>();\n\t\t\tEigen::VectorXd rand;\n\n\t\t\tstd::vector<double> data;\n\n\t\t\t// Random parameters between -pi and pi\n\t\t\tif (comm->rank() == 0) {\n\t\t\t\trand = -1.0 * pi * Eigen::VectorXd::Ones(nParameters)\n\t\t\t\t\t\t+ (Eigen::VectorXd::Random(nParameters) * 0.5\n\t\t\t\t\t\t\t\t+ Eigen::VectorXd::Ones(nParameters) * 0.5)\n\t\t\t\t\t\t\t\t* (pi - (-1 * pi));\n\t\t\t\tdata.resize(rand.size());\n\t\t\t\tEigen::VectorXd::Map(&data[0], rand.size()) = rand;\n\t\t\t}\n\n\t\t\tcomm->broadcast(data, 0);\n\n\t\t\tif (comm->rank() != 0) {\n\t\t\t\trand = Eigen::Map<Eigen::VectorXd>(data.data(), data.size());\n\t\t\t}\n\t\t\treturn rand;\n\t\t}\n\t}\n\n};\n}\n}\n\n\n#endif /* VQETASK_STATEPREPARATIONEVALUATOR_HPP_ */\n", "meta": {"hexsha": "5759e7c77c58c59bfc85ea7ebf3ef7213e01045d", "size": 2062, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "task/VQEParameterGenerator.hpp", "max_stars_repo_name": "czhao39/xacc-vqe", "max_stars_repo_head_hexsha": "4ad1d9308794e28c37772b7ea29cd3923388168a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task/VQEParameterGenerator.hpp", "max_issues_repo_name": "czhao39/xacc-vqe", "max_issues_repo_head_hexsha": "4ad1d9308794e28c37772b7ea29cd3923388168a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task/VQEParameterGenerator.hpp", "max_forks_repo_name": "czhao39/xacc-vqe", "max_forks_repo_head_hexsha": "4ad1d9308794e28c37772b7ea29cd3923388168a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4567901235, "max_line_length": 103, "alphanum_fraction": 0.6178467507, "num_tokens": 634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219503, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.6182965733003082}}
{"text": "#include <iostream>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_dogleg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n#include <cmath>\n#include <chrono>\n\nusing namespace std; \n\n/* Curve fitting for function \"y = e^(a*x*x + b*x + c)\"\nOnly need a single vertex with three parameter a,b,c in it. \nAll edges are unary edges connected to the only vertex\n*/\n\n// vertices as optimization target\n// inherent from g2o::BaseVertex, predefined Vertex\nclass CurveFittingVertex: public g2o::BaseVertex<3, Eigen::Vector3d>\n{\n    public: \n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n        virtual void setToOriginImpl(){\n            _estimate << 0, 0, 0;\n        }\n\n        virtual void oplusImpl( const double* update ) // \u66f4\u65b0\n        {\n            _estimate += Eigen::Vector3d(update);\n        }\n        \n        // read and write leave empty\n        virtual bool read( istream& in ) {}\n        virtual bool write( ostream& out ) const {}\n};\n\n// edges to compute error\nclass CurveFittingEdge: public g2o::BaseUnaryEdge<1, double, CurveFittingVertex>\n{\n    public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    CurveFittingEdge( double x ): BaseUnaryEdge(), _x(x) {}\n\n    void computeError(){\n        const CurveFittingVertex* v = static_cast<const CurveFittingVertex*>(_vertices[0]);\n        const Eigen::Vector3d abc = v->estimate();\n        _error(0, 0) = _measurement - std::exp(abc(0, 0)*_x*_x + abc(1, 0)*_x + abc(2, 0));\n    }\n    virtual bool read( istream& in ) {}\n    virtual bool write( ostream& out ) const {}\n    public: \n        double _x;\n};\n\nint main(){\n    cv::RNG rng;  \n    double a=1.0, b=2.0, c=1.0;   // Real parameters     \n    int N = 200; \n    double w_sigma=1.0;                   \n<<<<<<< HEAD\n=======\n\n>>>>>>> d3aa7eab7a66633ee6b6716534884a999f4bfb7a\n    vector<double> x_data, y_data;      // generated data\n\n    cout<<\"generating data: \"<<endl;\n    for ( int i=0; i<N; i++ )\n    {\n        double x = i/100.0;\n        x_data.push_back ( x );\n        y_data.push_back (\n            exp ( a*x*x + b*x + c ) + rng.gaussian ( w_sigma )\n        );\n        cout<<x_data[i]<<\" \"<<y_data[i]<<endl;\n    }\n\n    double parameters[3] = {0,0,0};  // Parameters need to be solved\n\n    typedef g2o::BlockSolver<g2o::BlockSolverTraits<3, 1>> Block;   // input 3 dims, output 1 dims\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>(); \n\n    Block *solver_ptr = new Block(linearSolver);\n\n    g2o::OptimizationAlgorithmLevenberg *solver = new g2o::OptimizationAlgorithmLevenberg(solver_ptr);\n\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm (solver);\n    optimizer.setVerbose(true);\n\n    // add Vertex as optimization target \n\n    CurveFittingVertex *v = new CurveFittingVertex();\n    v->setEstimate(Eigen::Vector3d(0, 0, 0));\n    v->setId(0);\n    optimizer.addVertex(v);\n\n    for(int i=0;i<N;i++){\n        CurveFittingEdge *edge = new CurveFittingEdge(x_data[i]);\n        edge->setId(i);\n        edge->setVertex(0, v);\n        edge->setMeasurement(y_data[i]);\n        edge->setInformation(Eigen::Matrix<double, 1, 1>::Identity()*1/(w_sigma*w_sigma));\n        optimizer.addEdge(edge);\n    } \n\n    // Execute optimization. \n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    optimizer.initializeOptimization();\n    optimizer.optimize(100);\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    \n    chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>( t2-t1 );\n    cout<<\"solve time cost = \"<<time_used.count()<<\" seconds. \"<<endl;\n\n    Eigen::Vector3d parameter_estimate = v->estimate();\n    cout << \"Estimate model\" << parameter_estimate.transpose() << endl;\n\n}", "meta": {"hexsha": "a9389c00d8c7d068a43c2c5b5945c2932248b348", "size": 3967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "optimization/g2o_curve_fitting.cpp", "max_stars_repo_name": "shen338/MySLAM", "max_stars_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optimization/g2o_curve_fitting.cpp", "max_issues_repo_name": "shen338/MySLAM", "max_issues_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optimization/g2o_curve_fitting.cpp", "max_forks_repo_name": "shen338/MySLAM", "max_forks_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_forks_repo_licenses": ["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.5163934426, "max_line_length": 102, "alphanum_fraction": 0.646332241, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6182965641611418}}
{"text": "/*!\n  \\file gpp_knowledge_gradient_optimization.hpp\n  \\rst\n  1. OVERVIEW OF KNOWLEDGE GRADIENT WHAT ARE WE TRYING TO DO?\n  2. IMPLEMENTATION NOTES\n  3. CITATIONS\n\n    **1. OVERVIEW OF KNOWLEDGE GRADIENT; WHAT ARE WE TRYING TO DO?**\n\n    .. Note:: these comments are copied in Python: interfaces/__init__.py\n\n    The optimization process models the objective using a Gaussian process (GP) prior\n    (also called a GP predictor) based on the specified covariance and the input\n    data (e.g., through member functions ComputeMeanOfPoints, ComputeVarianceOfPoints).  Using the GP,\n    we can compute the knowledge gradient (KG) from sampling any particular point.  KG\n    is defined relative to the best currently known value, and it represents what the\n    algorithm believes is the most likely outcome from sampling a particular point in parameter\n    space (aka conducting a particular experiment).\n\n    See KnowledgeGradientEvaluator class docs for further details on computing KG.\n    Both support ComputeKnowledgeGradient() and ComputeGradKnowledgeGradient().\n\n    The behavior of the GP is controlled by its underlying\n    covariance function and the data/uncertainty of prior points (experiments).\n\n    With the ability of the compute KG, the final step is to optimize\n    to find the best KG.  This is done using multistart gradient descent (MGD), in\n    ComputeKGOptimalPointsToSample(). This method wraps a MGD call and falls back on random search\n    if that fails. See gpp_optimization.hpp for multistart/optimization templates. This method\n    can evaluate and optimize KG at serval points simultaneously; e.g., if we wanted to run 4 simultaneous\n    experiments, we can use KG to select all 4 points at once.\n\n    Additionally, there are use cases where we have existing experiments that are not yet complete but\n    we have an opportunity to start some new trials. For example, maybe we are a drug company currently\n    testing 2 combinations of dosage levels. We got some new funding, and can now afford to test\n    3 more sets of dosage parameters. Ideally, the decision on the new experiments should depend on\n    the existence of the 2 ongoing tests. We may not have any data from the ongoing experiments yet;\n    e.g., they are [double]-blind trials. If nothing else, we would not want to duplicate any\n    existing experiments! So we want to solve 3-KG using the knowledge of the 2 ongoing experiments.\n\n    We call this q,p-KG, so the previous example would be 3,2-KG. So q is the number of new\n    (simultaneous) experiments to select. In code, this would be the size of the output from KG\n    optimization (i.e., ``best_points_to_sample``, of which there are ``q = num_to_sample points``).\n    p is the number of ongoing/incomplete experiments to take into account (i.e., ``points_being_sampled``\n    of which there are ``p = num_being_sampled`` points).\n\n    Back to optimization: the idea behind gradient descent is simple.  The gradient gives us the\n    direction of steepest ascent (negative gradient is steepest descent).  So each iteration, we\n    compute the gradient and take a step in that direction.  The size of the step is not specified\n    by GD and is left to the specific implementation.  Basically if we take steps that are\n    too large, we run the risk of over-shooting the solution and even diverging.  If we\n    take steps that are too small, it may take an intractably long time to reach the solution.\n    Thus the magic is in choosing the step size; we do not claim that our implementation is\n    perfect, but it seems to work reasonably.  See ``gpp_optimization.hpp`` for more details about\n    GD as well as the template definition.\n\n    For particularly difficult problems or problems where gradient descent's parameters are not\n    well-chosen, GD can fail to converge.  If this happens, we can fall back on heuristics;\n    e.g., 'dumb' search (i.e., evaluate EI at a large number of random points and take the best\n    one). Naive search lives in: ComputeOptimalPointsToSampleViaLatinHypercubeSearch<>().\n\n    **2. IMPLEMENTATION NOTES**\n\n    a. This file has a few primary endpoints for KG optimization:\n\n       i. ComputeKGOptimalPointsToSampleWithRandomStarts<>():\n\n          Solves the q,p-KG problem.\n\n          Takes in a gaussian_process describing the prior, domain, config, etc.; outputs the next best point(s) (experiment)\n          to sample (run). Uses gradient descent.\n\n       ii. ComputeKGOptimalPointsToSampleViaLatinHypercubeSearch<>():\n\n           Estimates the q,p-KG problem.\n\n           Takes in a gaussian_process describing the prior, domain, etc.; outputs the next best point(s) (experiment)\n           to sample (run). Uses 'dumb' search.\n\n       iii. ComputeKGOptimalPointsToSample<>() (Recommended):\n\n            Solves the q,p-KG problem.\n\n            Wraps the previous two items; relies on gradient descent and falls back to \"dumb\" search if it fails.\n\n       .. NOTE::\n           See ``gpp_knowledge_gradient_optimization.cpp``'s header comments for more detailed implementation notes.\n\n           There are also several other functions with external linkage in this header; these\n           are provided primarily to ease testing and to permit lower level access from python.\n\n    b. See ``gpp_common.hpp`` header comments for additional implementation notes.\n\n    **3. CITATIONS**\n\n    a. Gaussian Processes for Machine Learning.\n       Carl Edward Rasmussen and Christopher K. I. Williams. 2006.\n       Massachusetts Institute of Technology.  55 Hayward St., Cambridge, MA 02142.\n       http://www.gaussianprocess.org/gpml/ (free electronic copy)\n\n    b. The Knowledge-Gradient Policy for Correlated Normal Beliefs.\n       P.I. Frazier, W.B. Powell & S. Dayanik.\n       INFORMS Journal on Computing, 2009.\n\n    c. Differentiation of the Cholesky Algorithm.\n       S. P. Smith. 1995.\n       Journal of Computational and Graphical Statistics. Volume 4. Number 2. p134-147\n\n    d. A Multi-points Criterion for Deterministic Parallel Global Optimization based on Gaussian Processes.\n       David Ginsbourger, Rodolphe Le Riche, and Laurent Carraro.  2008.\n       D\u00b4epartement 3MI. Ecole Nationale Sup\u00b4erieure des Mines. 158 cours Fauriel, Saint-Etienne, France.\n       ginsbourger@emse.fr, leriche@emse.fr, carraro@emse.fr\n\\endrst*/\n\n#ifndef MOE_OPTIMAL_LEARNING_CPP_GPP_EXPECTED_IMPROVEMENT_MCMC_OPTIMIZATION_HPP_\n#define MOE_OPTIMAL_LEARNING_CPP_GPP_EXPECTED_IMPROVEMENT_MCMC_OPTIMIZATION_HPP_\n\n#include <algorithm>\n#include <limits>\n#include <memory>\n#include <vector>\n\n#include <stdlib.h>\n#include <queue>\n\n#include <boost/math/distributions/normal.hpp>  // NOLINT(build/include_order)\n\n#include \"gpp_common.hpp\"\n#include \"gpp_domain.hpp\"\n#include \"gpp_exception.hpp\"\n#include \"gpp_covariance.hpp\"\n#include \"gpp_logging.hpp\"\n#include \"gpp_math.hpp\"\n#include \"gpp_optimization.hpp\"\n#include \"gpp_optimizer_parameters.hpp\"\n#include \"gpp_knowledge_gradient_mcmc_optimization.hpp\"\n#include \"gpp_random.hpp\"\n\nnamespace optimal_learning {\n\nstruct ExpectedImprovementMCMCState;\n/*!\\rst\n  A class to encapsulate the computation of knowledge gradient and its spatial gradient. This class handles the\n  general KG computation case using monte carlo integration; it can support q,p-KG optimization. It is designed to work\n  with any GaussianProcess.  Additionally, this class has no state and within the context of KG optimization, it is\n  meant to be accessed by const reference only.\n\n  The random numbers needed for KG computation will be passed as parameters instead of contained as members to make\n  multithreading more straightforward.\n\\endrst*/\nclass ExpectedImprovementMCMCEvaluator final {\n public:\n  using StateType = ExpectedImprovementMCMCState;\n  /*!\\rst\n    Constructs a KnowledgeGradientEvaluator object.  All inputs are required; no default constructor nor copy/assignment are allowed.\n\n    \\param\n      :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n        that describes the underlying GP\n      :discrete_pts[dim][num_pts]: the set of points to approximate the KG factor\n      :num_pts: number of points in discrete_pts\n      :num_mc_iterations: number of monte carlo iterations\n      :best_so_far: best (minimum) objective function value (in ``points_sampled_value``)\n  \\endrst*/\n  ExpectedImprovementMCMCEvaluator(const GaussianProcessMCMC& gaussian_process_mcmc,\n                                   int num_mc_iterations, double const * best_so_far,\n                                   std::vector<typename ExpectedImprovementState::EvaluatorType> * evaluator_vector);\n\n\n  int dim() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return dim_;\n  }\n\n  int num_mcmc() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return num_mcmc_hypers_;\n  }\n\n  std::vector<ExpectedImprovementEvaluator> * expected_improvement_evaluator_list() const noexcept OL_WARN_UNUSED_RESULT {\n    return expected_improvement_evaluator_lst;\n  }\n\n  std::vector<double> best_so_far_list(double const * best_so_far) const noexcept OL_WARN_UNUSED_RESULT {\n    std::vector<double> result(num_mcmc_hypers_);\n    std::copy(best_so_far, best_so_far + num_mcmc_hypers_, result.data());\n    return result;\n  }\n\n  /*!\\rst\n    Wrapper for ComputeKnowledgeGradient(); see that function for details.\n  \\endrst*/\n  double ComputeObjectiveFunction(StateType * ei_state) const OL_NONNULL_POINTERS OL_WARN_UNUSED_RESULT {\n    return ComputeExpectedImprovement(ei_state);\n  }\n\n  /*!\\rst\n    Wrapper for ComputeGradKnowledgeGradient(); see that function for details.\n  \\endrst*/\n  void ComputeGradObjectiveFunction(StateType * ei_state, double * restrict grad_EI) const OL_NONNULL_POINTERS {\n    ComputeGradExpectedImprovement(ei_state, grad_EI);\n  }\n\n  /*!\\rst\n    Computes the knowledge gradient\n    \\param\n      :kg_state[1]: properly configured state object\n    \\output\n      :kg_state[1]: state with temporary storage modified; ``normal_rng`` modified\n    \\return\n      the knowledge gradient from sampling ``points_to_sample`` with ``points_being_sampled`` concurrent experiments\n  \\endrst*/\n  double ComputeExpectedImprovement(StateType * ei_state) const OL_NONNULL_POINTERS OL_WARN_UNUSED_RESULT;\n\n  /*!\\rst\n    Computes the (partial) derivatives of the knowledge gradient with respect to each point of ``points_to_sample``.\n    As with ComputeKnowledgeGradient(), this computation accounts for the effect of ``points_being_sampled``\n    concurrent experiments.\n\n    ``points_to_sample`` is the \"q\" and ``points_being_sampled`` is the \"p\" in q,p-KG.\n\n    \\param\n      :kg_state[1]: properly configured state object\n    \\output\n      :kg_state[1]: state with temporary storage modified; ``normal_rng`` modified\n      :grad_KG[dim][num_to_sample]: gradient of KG, ``\\pderiv{KG(Xq \\cup Xp)}{Xq_{d,i}}`` where ``Xq`` is ``points_to_sample``\n      and ``Xp`` is ``points_being_sampled`` (grad KG from sampling ``points_to_sample`` with\n      ``points_being_sampled`` concurrent experiments wrt each dimension of the points in ``points_to_sample``)\n  \\endrst*/\n  void ComputeGradExpectedImprovement(StateType * ei_state, double * restrict grad_EI) const OL_NONNULL_POINTERS;\n\n  OL_DISALLOW_DEFAULT_AND_COPY_AND_ASSIGN(ExpectedImprovementMCMCEvaluator);\n\n private:\n  //! spatial dimension (e.g., entries per point of points_sampled)\n  const int dim_;\n  //! number of mcmc hyperparameters\n  int num_mcmc_hypers_;\n  //! number of monte carlo iterations\n  int num_mc_iterations_;\n  //! best (minimum) objective function value (in points_sampled_value)\n  std::vector<double> best_so_far_;\n  //! pointer to gaussian process used in KG computations\n  const GaussianProcessMCMC * gaussian_process_mcmc_;\n  //! pointer to gaussian process used in KG computations\n  std::vector<typename ExpectedImprovementState::EvaluatorType> * expected_improvement_evaluator_lst;\n};\n\n/*!\\rst\n  State object for KnowledgeGradientEvaluator.  This tracks the points being sampled in concurrent experiments\n  (``points_being_sampled``) ALONG with the points currently being evaluated via knowledge gradient for future experiments\n  (called ``points_to_sample``); these are the p and q of q,p-KG, respectively.  ``points_to_sample`` joined with\n  ``points_being_sampled`` is stored in ``union_of_points`` in that order.\n\n  This struct also tracks the state of the GaussianProcess that underlies the knowledge gradient computation: the GP state\n  is built to handle the initial ``union_of_points``, and subsequent updates to ``points_to_sample`` in this object also update\n  the GP state.\n\n  This struct also holds a pointer to a random number generator needed for Monte Carlo integrated KG computations.\n\n  .. WARNING::\n       Users MUST guarantee that multiple state objects DO NOT point to the same RNG (in a multithreaded env).\n\n  See general comments on State structs in ``gpp_common.hpp``'s header docs.\n\\endrst*/\nstruct ExpectedImprovementMCMCState final {\n  using EvaluatorType = ExpectedImprovementMCMCEvaluator;\n\n  /*!\\rst\n    Constructs an KnowledgeGradientMCMCState object with a specified source of randomness for the purpose of computing KG\n    (and its gradient) over the specified set of points to sample.\n    This establishes properly sized/initialized temporaries for KG computation, including dependent state from the\n    associated Gaussian Process (which arrives as part of the kg_evaluator).\n\n    .. WARNING:: This object is invalidated if the associated kg_evaluator is mutated.  SetupState() should be called to reset.\n\n    .. WARNING::\n         Using this object to compute gradients when ``configure_for_gradients`` := false results in UNDEFINED BEHAVIOR.\n\n    \\param\n      :kg_evaluator: knowledge gradient evaluator object that specifies the parameters & GP for KG evaluation\n      :points_to_sample[dim][num_to_sample]: points at which to evaluate KG and/or its gradient to check their value in future experiments (i.e., test points for GP predictions)\n      :points_being_sampled[dim][num_being_sampled]: points being sampled in concurrent experiments\n      :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n      :num_being_sampled: number of points being sampled in concurrent experiments (i.e., the \"p\" in q,p-KG)\n      :configure_for_gradients: true if this object will be used to compute gradients, false otherwise\n      :normal_rng[1]: pointer to a properly initialized\\* NormalRNG object\n\n    .. NOTE::\n         \\* The NormalRNG object must already be seeded.  If multithreaded computation is used for KG, then every state object\n         must have a different NormalRNG (different seeds, not just different objects).\n  \\endrst*/\n  ExpectedImprovementMCMCState(const EvaluatorType& ei_evaluator, double const * restrict points_to_sample,\n                               double const * restrict points_being_sampled, int num_to_sample_in,\n                               int num_being_sampled_in, int const * restrict gradients_in, int num_gradients_in,\n                               bool configure_for_gradients, NormalRNGInterface * normal_rng_in,\n                               std::vector<typename ExpectedImprovementEvaluator::StateType> * ei_state_vector);\n\n  ExpectedImprovementMCMCState(ExpectedImprovementMCMCState&& other);\n\n  /*!\\rst\n    Create a vector with the union of points_to_sample and points_being_sampled (the latter is appended to the former).\n\n    Note the l-value return. Assigning the return to a std::vector<double> or passing it as an argument to the ctor\n    will result in copy-elision or move semantics; no copying/performance loss.\n\n    \\param:\n      :points_to_sample[dim][num_to_sample]: points at which to evaluate KG and/or its gradient to check their value in future experiments (i.e., test points for GP predictions)\n      :points_being_sampled[dim][num_being_sampled]: points being sampled in concurrent experiments\n      :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n      :num_being_sampled: number of points being sampled in concurrent experiments (i.e., the \"p\" in q,p-KG)\n      :dim: the number of spatial dimensions of each point array\n    \\return\n      std::vector<double> with the union of the input arrays: points_being_sampled is *appended* to points_to_sample\n  \\endrst*/\n  static std::vector<double> BuildUnionOfPoints(double const * restrict points_to_sample,\n                                                double const * restrict points_being_sampled,\n                                                int num_to_sample, int num_being_sampled,\n                                                int dim) noexcept OL_WARN_UNUSED_RESULT {\n    std::vector<double> union_of_points(dim*(num_to_sample + num_being_sampled));\n    std::copy(points_to_sample, points_to_sample + dim*num_to_sample, union_of_points.data());\n    std::copy(points_being_sampled, points_being_sampled + dim*num_being_sampled,\n              union_of_points.data() + dim*num_to_sample);\n    return union_of_points;\n  }\n\n  int GetProblemSize() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return dim*num_to_sample;\n  }\n\n  /*!\\rst\n    Get the ``points_to_sample``: potential future samples whose KG (and/or gradients) are being evaluated\n\n    \\output\n      :points_to_sample[dim][num_to_sample]: potential future samples whose KG (and/or gradients) are being evaluated\n  \\endrst*/\n  void GetCurrentPoint(double * restrict points_to_sample) const noexcept OL_NONNULL_POINTERS {\n    std::copy(union_of_points.data(), union_of_points.data() + num_to_sample*dim, points_to_sample);\n  }\n\n  /*!\\rst\n    Change the potential samples whose KG (and/or gradient) are being evaluated.\n    Update the state's derived quantities to be consistent with the new points.\n\n    \\param\n      :kg_evaluator: expected improvement evaluator object that specifies the parameters & GP for KG evaluation\n      :points_to_sample[dim][num_to_sample]: potential future samples whose KG (and/or gradients) are being evaluated\n  \\endrst*/\n  void SetCurrentPoint(const EvaluatorType& kg_evaluator,\n                       double const * restrict points_to_sample_in) OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Configures this state object with new ``points_to_sample``, the location of the potential samples whose KG is to be evaluated.\n    Ensures all state variables & temporaries are properly sized.\n    Properly sets all dependent state variables (e.g., GaussianProcess's state) for KG evaluation.\n\n    .. WARNING::\n         This object's state is INVALIDATED if the ``kg_evaluator`` (including the GaussianProcess it depends on) used in\n         SetupState is mutated! SetupState() should be called again in such a situation.\n\n    \\param\n      :kg_evaluator: knowledge gradient evaluator object that specifies the parameters & GP for KG evaluation\n      :points_to_sample[dim][num_to_sample]: potential future samples whose KG (and/or gradients) are being evaluated\n  \\endrst*/\n  void SetupState(const EvaluatorType& ei_evaluator, double const * restrict points_to_sample);\n\n  // size information\n  //! spatial dimension (e.g., entries per point of ``points_sampled``)\n  const int dim;\n  //! number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n  const int num_to_sample;\n  //! number of points being sampled concurrently (i.e., the \"p\" in q,p-KG)\n  const int num_being_sampled;\n  //! number of derivative terms desired (usually 0 for no derivatives or num_to_sample)\n  const int num_derivatives;\n  //! number of points in union_of_points: num_to_sample + num_being_sampled\n  const int num_union;\n\n  // gradients index\n  std::vector<int> gradients;\n  // the number of gradients observations\n  int num_gradients_to_sample;\n\n  //! points currently being sampled; this is the union of the points represented by \"q\" and \"p\" in q,p-KG\n  //! ``points_to_sample`` is stored first in memory, immediately followed by ``points_being_sampled``\n  std::vector<double> union_of_points;\n\n  //! gaussian process state\n  std::vector<typename ExpectedImprovementEvaluator::StateType> * ei_state_list;\n\n  OL_DISALLOW_DEFAULT_AND_COPY_AND_ASSIGN(ExpectedImprovementMCMCState);\n};\n\nstruct OnePotentialSampleExpectedImprovementMCMCState;\n/*!\\rst\n  A class to encapsulate the computation of knowledge gradient and its spatial gradient. This class handles the\n  general KG computation case using monte carlo integration; it can support q,p-KG optimization. It is designed to work\n  with any GaussianProcess.  Additionally, this class has no state and within the context of KG optimization, it is\n  meant to be accessed by const reference only.\n\n  The random numbers needed for KG computation will be passed as parameters instead of contained as members to make\n  multithreading more straightforward.\n\\endrst*/\nclass OnePotentialSampleExpectedImprovementMCMCEvaluator final {\n public:\n  using StateType = OnePotentialSampleExpectedImprovementMCMCState;\n  /*!\\rst\n    Constructs a KnowledgeGradientEvaluator object.  All inputs are required; no default constructor nor copy/assignment are allowed.\n\n    \\param\n      :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n        that describes the underlying GP\n      :discrete_pts[dim][num_pts]: the set of points to approximate the KG factor\n      :num_pts: number of points in discrete_pts\n      :num_mc_iterations: number of monte carlo iterations\n      :best_so_far: best (minimum) objective function value (in ``points_sampled_value``)\n  \\endrst*/\n  OnePotentialSampleExpectedImprovementMCMCEvaluator(const GaussianProcessMCMC& gaussian_process_mcmc, double const * best_so_far,\n                                                     std::vector<typename OnePotentialSampleExpectedImprovementState::EvaluatorType> * evaluator_vector);\n\n\n  int dim() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return dim_;\n  }\n\n  int num_mcmc() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return num_mcmc_hypers_;\n  }\n\n  std::vector<OnePotentialSampleExpectedImprovementEvaluator> * expected_improvement_evaluator_list() const noexcept OL_WARN_UNUSED_RESULT {\n    return expected_improvement_evaluator_lst;\n  }\n\n  std::vector<double> best_so_far_list(double const * best_so_far) const noexcept OL_WARN_UNUSED_RESULT {\n    std::vector<double> result(num_mcmc_hypers_);\n    std::copy(best_so_far, best_so_far + num_mcmc_hypers_, result.data());\n    return result;\n  }\n\n  /*!\\rst\n    Wrapper for ComputeKnowledgeGradient(); see that function for details.\n  \\endrst*/\n  double ComputeObjectiveFunction(StateType * ei_state) const OL_NONNULL_POINTERS OL_WARN_UNUSED_RESULT {\n    return ComputeExpectedImprovement(ei_state);\n  }\n\n  /*!\\rst\n    Wrapper for ComputeGradKnowledgeGradient(); see that function for details.\n  \\endrst*/\n  void ComputeGradObjectiveFunction(StateType * ei_state, double * restrict grad_EI) const OL_NONNULL_POINTERS {\n    ComputeGradExpectedImprovement(ei_state, grad_EI);\n  }\n\n  /*!\\rst\n    Computes the knowledge gradient\n    \\param\n      :kg_state[1]: properly configured state object\n    \\output\n      :kg_state[1]: state with temporary storage modified; ``normal_rng`` modified\n    \\return\n      the knowledge gradient from sampling ``points_to_sample`` with ``points_being_sampled`` concurrent experiments\n  \\endrst*/\n  double ComputeExpectedImprovement(StateType * ei_state) const OL_NONNULL_POINTERS OL_WARN_UNUSED_RESULT;\n\n  /*!\\rst\n    Computes the (partial) derivatives of the knowledge gradient with respect to each point of ``points_to_sample``.\n    As with ComputeKnowledgeGradient(), this computation accounts for the effect of ``points_being_sampled``\n    concurrent experiments.\n\n    ``points_to_sample`` is the \"q\" and ``points_being_sampled`` is the \"p\" in q,p-KG.\n\n    \\param\n      :kg_state[1]: properly configured state object\n    \\output\n      :kg_state[1]: state with temporary storage modified; ``normal_rng`` modified\n      :grad_KG[dim][num_to_sample]: gradient of KG, ``\\pderiv{KG(Xq \\cup Xp)}{Xq_{d,i}}`` where ``Xq`` is ``points_to_sample``\n      and ``Xp`` is ``points_being_sampled`` (grad KG from sampling ``points_to_sample`` with\n      ``points_being_sampled`` concurrent experiments wrt each dimension of the points in ``points_to_sample``)\n  \\endrst*/\n  void ComputeGradExpectedImprovement(StateType * ei_state, double * restrict grad_EI) const OL_NONNULL_POINTERS;\n\n  OL_DISALLOW_DEFAULT_AND_COPY_AND_ASSIGN(OnePotentialSampleExpectedImprovementMCMCEvaluator);\n\n private:\n  //! spatial dimension (e.g., entries per point of points_sampled)\n  const int dim_;\n  //! number of mcmc hyperparameters\n  int num_mcmc_hypers_;\n  //! best (minimum) objective function value (in points_sampled_value)\n  std::vector<double> best_so_far_;\n  //! pointer to gaussian process used in KG computations\n  const GaussianProcessMCMC * gaussian_process_mcmc_;\n  //! pointer to gaussian process used in KG computations\n  std::vector<typename OnePotentialSampleExpectedImprovementState::EvaluatorType> * expected_improvement_evaluator_lst;\n};\n\n/*!\\rst\n  State object for KnowledgeGradientEvaluator.  This tracks the points being sampled in concurrent experiments\n  (``points_being_sampled``) ALONG with the points currently being evaluated via knowledge gradient for future experiments\n  (called ``points_to_sample``); these are the p and q of q,p-KG, respectively.  ``points_to_sample`` joined with\n  ``points_being_sampled`` is stored in ``union_of_points`` in that order.\n\n  This struct also tracks the state of the GaussianProcess that underlies the knowledge gradient computation: the GP state\n  is built to handle the initial ``union_of_points``, and subsequent updates to ``points_to_sample`` in this object also update\n  the GP state.\n\n  This struct also holds a pointer to a random number generator needed for Monte Carlo integrated KG computations.\n\n  .. WARNING::\n       Users MUST guarantee that multiple state objects DO NOT point to the same RNG (in a multithreaded env).\n\n  See general comments on State structs in ``gpp_common.hpp``'s header docs.\n\\endrst*/\nstruct OnePotentialSampleExpectedImprovementMCMCState final {\n  using EvaluatorType = OnePotentialSampleExpectedImprovementMCMCEvaluator;\n\n  /*!\\rst\n    Constructs an KnowledgeGradientMCMCState object with a specified source of randomness for the purpose of computing KG\n    (and its gradient) over the specified set of points to sample.\n    This establishes properly sized/initialized temporaries for KG computation, including dependent state from the\n    associated Gaussian Process (which arrives as part of the kg_evaluator).\n\n    .. WARNING:: This object is invalidated if the associated kg_evaluator is mutated.  SetupState() should be called to reset.\n\n    .. WARNING::\n         Using this object to compute gradients when ``configure_for_gradients`` := false results in UNDEFINED BEHAVIOR.\n\n    \\param\n      :kg_evaluator: knowledge gradient evaluator object that specifies the parameters & GP for KG evaluation\n      :points_to_sample[dim][num_to_sample]: points at which to evaluate KG and/or its gradient to check their value in future experiments (i.e., test points for GP predictions)\n      :points_being_sampled[dim][num_being_sampled]: points being sampled in concurrent experiments\n      :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n      :num_being_sampled: number of points being sampled in concurrent experiments (i.e., the \"p\" in q,p-KG)\n      :configure_for_gradients: true if this object will be used to compute gradients, false otherwise\n      :normal_rng[1]: pointer to a properly initialized\\* NormalRNG object\n\n    .. NOTE::\n         \\* The NormalRNG object must already be seeded.  If multithreaded computation is used for KG, then every state object\n         must have a different NormalRNG (different seeds, not just different objects).\n  \\endrst*/\n  OnePotentialSampleExpectedImprovementMCMCState(const EvaluatorType& ei_evaluator, double const * restrict point_to_sample,\n                                                 double const * restrict OL_UNUSED(points_being_sampled),\n                                                 int OL_UNUSED(num_to_sample_in), int OL_UNUSED(num_being_sampled_in),\n                                                 bool configure_for_gradients, NormalRNGInterface * OL_UNUSED(normal_rng_in),\n                                                 std::vector<typename OnePotentialSampleExpectedImprovementEvaluator::StateType> * ei_state_vector);\n\n  OnePotentialSampleExpectedImprovementMCMCState(OnePotentialSampleExpectedImprovementMCMCState&& other);\n\n  int GetProblemSize() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return dim*num_to_sample;\n  }\n\n  /*!\\rst\n    Get the ``points_to_sample``: potential future samples whose KG (and/or gradients) are being evaluated\n\n    \\output\n      :points_to_sample[dim][num_to_sample]: potential future samples whose KG (and/or gradients) are being evaluated\n  \\endrst*/\n  void GetCurrentPoint(double * restrict points_to_sample) const noexcept OL_NONNULL_POINTERS {\n    std::copy(point_to_sample.data(), point_to_sample.data() + dim, points_to_sample);\n  }\n\n  /*!\\rst\n    Change the potential samples whose KG (and/or gradient) are being evaluated.\n    Update the state's derived quantities to be consistent with the new points.\n\n    \\param\n      :kg_evaluator: expected improvement evaluator object that specifies the parameters & GP for KG evaluation\n      :points_to_sample[dim][num_to_sample]: potential future samples whose KG (and/or gradients) are being evaluated\n  \\endrst*/\n  void SetCurrentPoint(const EvaluatorType& kg_evaluator,\n                       double const * restrict points_to_sample_in) OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Configures this state object with new ``points_to_sample``, the location of the potential samples whose KG is to be evaluated.\n    Ensures all state variables & temporaries are properly sized.\n    Properly sets all dependent state variables (e.g., GaussianProcess's state) for KG evaluation.\n\n    .. WARNING::\n         This object's state is INVALIDATED if the ``kg_evaluator`` (including the GaussianProcess it depends on) used in\n         SetupState is mutated! SetupState() should be called again in such a situation.\n\n    \\param\n      :kg_evaluator: knowledge gradient evaluator object that specifies the parameters & GP for KG evaluation\n      :points_to_sample[dim][num_to_sample]: potential future samples whose KG (and/or gradients) are being evaluated\n  \\endrst*/\n  void SetupState(const EvaluatorType& ei_evaluator, double const * restrict points_to_sample);\n\n  // size information\n  //! spatial dimension (e.g., entries per point of ``points_sampled``)\n  const int dim;\n  //! number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n  const int num_to_sample = 1;\n\n  //! number of derivative terms desired (usually 0 for no derivatives or num_to_sample)\n  const int num_derivatives;\n\n  //! point at which to evaluate EI and/or its gradient (e.g., to check its value in future experiments)\n  std::vector<double> point_to_sample;\n\n  //! gaussian process state\n  std::vector<typename OnePotentialSampleExpectedImprovementEvaluator::StateType> * ei_state_list;\n\n  OL_DISALLOW_DEFAULT_AND_COPY_AND_ASSIGN(OnePotentialSampleExpectedImprovementMCMCState);\n};\n\n/*!\\rst\n  Set up vector of ExpectedImprovementEvaluator::StateType.\n\n  This is a utility function just for reducing code duplication.\n\n  \\param\n    :kg_evaluator: evaluator object associated w/the state objects being constructed\n    :points_to_sample[dim][num_to_sample]: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate KG and/or its gradient\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrently experiments\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-KG)\n    :max_num_threads: maximum number of threads for use by OpenMP (generally should be <= # cores)\n    :configure_for_gradients: true if these state objects will be used to compute gradients, false otherwise\n    :state_vector[arbitrary]: vector of state objects, arbitrary size (usually 0)\n    :normal_rng[max_num_threads]: a vector of NormalRNG objects that provide the (pesudo)random source for MC integration\n  \\output\n    :state_vector[max_num_threads]: vector of states containing ``max_num_threads`` properly initialized state objects\n\\endrst*/\ninline OL_NONNULL_POINTERS void SetupExpectedImprovementMCMCState(\n    const OnePotentialSampleExpectedImprovementMCMCEvaluator& ei_evaluator,\n    double const * restrict points_to_sample,\n    double const * restrict points_being_sampled,\n    int num_to_sample,\n    int num_being_sampled,\n    int const * restrict gradients, int num_gradients,\n    int max_num_threads,\n    bool configure_for_gradients,\n    NormalRNG * normal_rng,\n    std::vector<typename OnePotentialSampleExpectedImprovementEvaluator::StateType> * ei_state_vector,\n    std::vector<typename OnePotentialSampleExpectedImprovementMCMCEvaluator::StateType> * state_vector) {\n  state_vector->reserve(max_num_threads);\n  for (int i = 0; i < max_num_threads; ++i) {\n    //kg_state_vector.reserve(0);\n    state_vector->emplace_back(ei_evaluator, points_to_sample, points_being_sampled, num_to_sample,\n                               num_being_sampled, configure_for_gradients,\n                               normal_rng + i, ei_state_vector+i);\n  }\n}\n\n/*!\\rst\n  Set up vector of ExpectedImprovementEvaluator::StateType.\n\n  This is a utility function just for reducing code duplication.\n\n  \\param\n    :kg_evaluator: evaluator object associated w/the state objects being constructed\n    :points_to_sample[dim][num_to_sample]: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate KG and/or its gradient\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrently experiments\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-KG)\n    :max_num_threads: maximum number of threads for use by OpenMP (generally should be <= # cores)\n    :configure_for_gradients: true if these state objects will be used to compute gradients, false otherwise\n    :state_vector[arbitrary]: vector of state objects, arbitrary size (usually 0)\n    :normal_rng[max_num_threads]: a vector of NormalRNG objects that provide the (pesudo)random source for MC integration\n  \\output\n    :state_vector[max_num_threads]: vector of states containing ``max_num_threads`` properly initialized state objects\n\\endrst*/\ninline OL_NONNULL_POINTERS void SetupExpectedImprovementMCMCState(\n    const ExpectedImprovementMCMCEvaluator& ei_evaluator,\n    double const * restrict points_to_sample,\n    double const * restrict points_being_sampled,\n    int num_to_sample,\n    int num_being_sampled,\n    int const * restrict gradients, int num_gradients,\n    int max_num_threads,\n    bool configure_for_gradients,\n    NormalRNG * normal_rng,\n    std::vector<typename ExpectedImprovementEvaluator::StateType> * ei_state_vector,\n    std::vector<typename ExpectedImprovementMCMCEvaluator::StateType> * state_vector) {\n  state_vector->reserve(max_num_threads);\n  for (int i = 0; i < max_num_threads; ++i) {\n    //kg_state_vector.reserve(0);\n    state_vector->emplace_back(ei_evaluator, points_to_sample, points_being_sampled, num_to_sample,\n                               num_being_sampled, gradients, num_gradients, configure_for_gradients,\n                               normal_rng + i, ei_state_vector+i);\n  }\n}\n\n/*!\\rst\n  Solve the q,p-KG problem (see ComputeKGOptimalPointsToSample and/or header docs) by optimizing the knowledge gradient.\n  Optimization is done using restarted Gradient Descent, via GradientDescentOptimizer<...>::Optimize() from\n  ``gpp_optimization.hpp``.  Please see that file for details on gradient descent and see gpp_optimizer_parameters.hpp\n  for the meanings of the GradientDescentParameters.\n\n  This function is just a simple wrapper that sets up the Evaluator's State and calls a general template for restarted GD.\n\n  This function does not perform multistarting or employ any other robustness-boosting heuristcs; it only\n  converges if the ``initial_guess`` is close to the solution. In general,\n  ComputeOptimalPointsToSample() (see below) is preferred. This function is meant for:\n\n  1. easier testing;\n  2. if you really know what you're doing.\n\n  Solution is guaranteed to lie within the region specified by ``domain``; note that this may not be a\n  true optima (i.e., the gradient may be substantially nonzero).\n\n  \\param\n    :kg_evaluator: reference to object that can compute ExpectedImprovement and its spatial gradient\n    :optimizer_parameters: GradientDescentParameters object that describes the parameters controlling KG optimization\n      (e.g., number of iterations, tolerances, learning rate)\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :initial_guess[dim][num_to_sample]: initial guess for gradient descent\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-KG)\n    :normal_rng[1]: a NormalRNG object that provides the (pesudo)random source for MC integration\n  \\output\n    :normal_rng[1]: NormalRNG object will have its state changed due to random draws\n    :next_point[dim][num_to_sample]: points yielding the best KG according to gradient descent\n\\endrst*/\ntemplate <typename ExpectedImprovementMCMCEvaluator, typename DomainType>\nvoid RestartedGradientDescentEIMCMCOptimization(const ExpectedImprovementMCMCEvaluator& ei_evaluator,\n                                                const GradientDescentParameters& optimizer_parameters,\n                                                const DomainType& domain, double const * restrict initial_guess,\n                                                double const * restrict points_being_sampled, int num_to_sample,\n                                                int num_being_sampled, NormalRNG * normal_rng,\n                                                double * restrict next_point) {\n  if (unlikely(optimizer_parameters.max_num_restarts <= 0)) {\n    return;\n  }\n  int dim = ei_evaluator.dim();\n\n  int num_derivatives = (*ei_evaluator.expected_improvement_evaluator_list())[0].gaussian_process()->num_derivatives();\n  std::vector<int> derivatives((*ei_evaluator.expected_improvement_evaluator_list())[0].gaussian_process()->derivatives());\n\n  std::vector<typename ExpectedImprovementEvaluator::StateType> ei_state_vector;\n\n  OL_VERBOSE_PRINTF(\"Expected Improvement Optimization via %s:\\n\", OL_CURRENT_FUNCTION_NAME);\n\n  bool configure_for_gradients = true;\n  typename ExpectedImprovementEvaluator::StateType ei_state(ei_evaluator, initial_guess,\n                                                            points_being_sampled, num_to_sample,\n                                                            num_being_sampled,\n                                                            derivatives.data(), num_derivatives,\n                                                            configure_for_gradients,\n                                                            normal_rng, &ei_state_vector);\n\n  using RepeatedDomain = RepeatedDomain<DomainType>;\n  RepeatedDomain repeated_domain(domain, num_to_sample);\n  GradientDescentOptimizer<ExpectedImprovementMCMCEvaluator, RepeatedDomain> gd_opt;\n  gd_opt.Optimize(ei_evaluator, optimizer_parameters, repeated_domain, &ei_state);\n  ei_state.GetCurrentPoint(next_point);\n}\n\n/*!\\rst\n  Perform multistart gradient descent (MGD) to solve the q,p-KG problem (see ComputeKGOptimalPointsToSample and/or\n  header docs).  Starts a GD run from each point in ``start_point_set``.  The point corresponding to the\n  optimal KG\\* is stored in ``best_next_point``.\n\n  \\* Multistarting is heuristic for global optimization. KG is not convex so this method may not find the true optimum.\n\n  This function wraps MultistartOptimizer<>::MultistartOptimize() (see ``gpp_optimization.hpp``), which provides the multistarting\n  component. Optimization is done using restarted Gradient Descent, via GradientDescentOptimizer<...>::Optimize() from\n  ``gpp_optimization.hpp``. Please see that file for details on gradient descent and see ``gpp_optimizer_parameters.hpp``\n  for the meanings of the GradientDescentParameters.\n\n  This function (or its wrappers, e.g., ComputeOptimalPointsToSampleWithRandomStarts) are the primary entry-points for\n  gradient descent based KG optimization in the ``optimal_learning`` library.\n\n  Users may prefer to call ComputeKGOptimalPointsToSample(), which applies other heuristics to improve robustness.\n\n  Currently, during optimization, we recommend that the coordinates of the initial guesses not differ from the\n  coordinates of the optima by more than about 1 order of magnitude. This is a very (VERY!) rough guideline for\n  sizing the domain and num_multistarts; i.e., be wary of sets of initial guesses that cover the space too sparsely.\n\n  Solution is guaranteed to lie within the region specified by ``domain``; note that this may not be a\n  true optima (i.e., the gradient may be substantially nonzero).\n\n  .. WARNING::\n       This function fails ungracefully if NO improvement can be found!  In that case,\n       ``best_next_point`` will always be the first point in ``start_point_set``.\n       ``found_flag`` will indicate whether this occured.\n\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :optimizer_parameters: GradientDescentParameters object that describes the parameters controlling EI optimization\n      (e.g., number of iterations, tolerances, learning rate)\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_dynamic), chunk_size (0).\n    :start_point_set[dim][num_to_sample][num_multistarts]: set of initial guesses for MGD (one block of num_to_sample points per multistart)\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :discrete_pts[dim][num_pts]: points to approximate KG\n    :num_multistarts: number of points in set of initial guesses\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-KG)\n    :num_pts: number of points in discrete_pts\n    :best_so_far: value of the best mean value so far in discrete_pts\n    :max_int_steps: maximum number of MC iterations\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n    :noise: variance of measurement noise\n  \\output\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :found_flag[1]: true if ``best_next_point`` corresponds to a nonzero KG\n    :best_next_point[dim][num_to_sample]: points yielding the best KG according to MGD\n\\endrst*/\ntemplate <typename DomainType>\nOL_NONNULL_POINTERS void ComputeEIMCMCOptimalPointsToSampleViaMultistartGradientDescent(\n    GaussianProcessMCMC& gaussian_process_mcmc,\n    const GradientDescentParameters& optimizer_parameters,\n    const DomainType& domain,\n    const ThreadSchedule& thread_schedule,\n    double const * restrict start_point_set,\n    double const * restrict points_being_sampled,\n    int num_multistarts,\n    int num_to_sample,\n    int num_being_sampled,\n    double const * best_so_far,\n    int max_int_steps,\n    NormalRNG * normal_rng,\n    bool * restrict found_flag,\n    double * restrict best_next_point) {\n  if (unlikely(num_multistarts <= 0)) {\n    OL_THROW_EXCEPTION(LowerBoundException<int>, \"num_multistarts must be > 1\", num_multistarts, 1);\n  }\n\n  bool configure_for_gradients = true;\n  if (num_to_sample == 1 && num_being_sampled == 0) {\n    std::vector<typename OnePotentialSampleExpectedImprovementState::EvaluatorType> ei_evaluator_lst;\n    OnePotentialSampleExpectedImprovementMCMCEvaluator ei_evaluator(gaussian_process_mcmc, best_so_far, &ei_evaluator_lst);\n\n    int num_derivatives = (*ei_evaluator.expected_improvement_evaluator_list())[0].gaussian_process()->num_derivatives();\n    std::vector<int> derivatives((*ei_evaluator.expected_improvement_evaluator_list())[0].gaussian_process()->derivatives());\n\n    std::vector<typename OnePotentialSampleExpectedImprovementMCMCEvaluator::StateType> state_vector;\n    std::vector<std::vector<typename OnePotentialSampleExpectedImprovementEvaluator::StateType>> ei_state_vector(thread_schedule.max_num_threads);\n    SetupExpectedImprovementMCMCState(ei_evaluator, start_point_set, points_being_sampled,\n                                      num_to_sample, num_being_sampled, derivatives.data(), num_derivatives,\n                                      thread_schedule.max_num_threads, configure_for_gradients,\n                                      normal_rng, ei_state_vector.data(), &state_vector);\n\n    std::vector<double> EI_starting(num_multistarts);\n    for (int i=0; i<num_multistarts; ++i){\n      state_vector[0].SetCurrentPoint(ei_evaluator, start_point_set + i*num_to_sample*gaussian_process_mcmc.dim());\n      EI_starting[i] = ei_evaluator.ComputeExpectedImprovement(&state_vector[0]);\n    }\n\n    std::priority_queue<std::pair<double, int>> q;\n    int k = 20; // number of indices we need\n    for (int i = 0; i < EI_starting.size(); ++i) {\n      if (i < k){\n        q.push(std::pair<double, int>(-EI_starting[i], i));\n      }\n      else{\n        if (q.top().first > -EI_starting[i]){\n          q.pop();\n          q.push(std::pair<double, int>(-EI_starting[i], i));\n        }\n      }\n    }\n\n    std::vector<double> top_k_starting(k*num_to_sample*gaussian_process_mcmc.dim());\n    for (int i = 0; i < k; ++i) {\n      int ki = q.top().second;\n      for (int d = 0; d<num_to_sample*gaussian_process_mcmc.dim(); ++d){\n        top_k_starting[i*num_to_sample*gaussian_process_mcmc.dim() + d] = start_point_set[ki*num_to_sample*gaussian_process_mcmc.dim() + d];\n      }\n      q.pop();\n    }\n\n    // init winner to be first point in set and 'force' its value to be 0.0; we cannot do worse than this\n    OptimizationIOContainer io_container(state_vector[0].GetProblemSize(), 0.0, top_k_starting.data());\n\n    using RepeatedDomain = RepeatedDomain<DomainType>;\n    RepeatedDomain repeated_domain(domain, num_to_sample);\n    GradientDescentOptimizer<OnePotentialSampleExpectedImprovementMCMCEvaluator, RepeatedDomain> gd_opt;\n    MultistartOptimizer<GradientDescentOptimizer<OnePotentialSampleExpectedImprovementMCMCEvaluator, RepeatedDomain> > multistart_optimizer;\n    multistart_optimizer.MultistartOptimize(gd_opt, ei_evaluator, optimizer_parameters,\n                                            repeated_domain, thread_schedule, top_k_starting.data(),\n                                            k, state_vector.data(), nullptr, &io_container);\n    *found_flag = io_container.found_flag;\n    std::copy(io_container.best_point.begin(), io_container.best_point.end(), best_next_point);\n  } else {\n    std::vector<typename ExpectedImprovementState::EvaluatorType> ei_evaluator_lst;\n    ExpectedImprovementMCMCEvaluator ei_evaluator(gaussian_process_mcmc, max_int_steps, best_so_far, &ei_evaluator_lst);\n\n    int num_derivatives = (*ei_evaluator.expected_improvement_evaluator_list())[0].gaussian_process()->num_derivatives();\n    std::vector<int> derivatives((*ei_evaluator.expected_improvement_evaluator_list())[0].gaussian_process()->derivatives());\n\n    std::vector<typename ExpectedImprovementMCMCEvaluator::StateType> state_vector;\n    std::vector<std::vector<typename ExpectedImprovementEvaluator::StateType>> ei_state_vector(thread_schedule.max_num_threads);\n    SetupExpectedImprovementMCMCState(ei_evaluator, start_point_set, points_being_sampled,\n                                      num_to_sample, num_being_sampled, derivatives.data(), num_derivatives,\n                                      thread_schedule.max_num_threads, configure_for_gradients,\n                                      normal_rng, ei_state_vector.data(), &state_vector);\n\n    std::vector<double> EI_starting(num_multistarts);\n    for (int i=0; i<num_multistarts; ++i){\n      state_vector[0].SetCurrentPoint(ei_evaluator, start_point_set + i*num_to_sample*gaussian_process_mcmc.dim());\n      EI_starting[i] = ei_evaluator.ComputeExpectedImprovement(&state_vector[0]);\n    }\n\n    std::priority_queue<std::pair<double, int>> q;\n    int k = 20; // number of indices we need\n    for (int i = 0; i < EI_starting.size(); ++i) {\n      if (i < k){\n        q.push(std::pair<double, int>(-EI_starting[i], i));\n      }\n      else{\n        if (q.top().first > -EI_starting[i]){\n          q.pop();\n          q.push(std::pair<double, int>(-EI_starting[i], i));\n        }\n      }\n    }\n\n    std::vector<double> top_k_starting(k*num_to_sample*gaussian_process_mcmc.dim());\n    for (int i = 0; i < k; ++i) {\n      int ki = q.top().second;\n      for (int d = 0; d<num_to_sample*gaussian_process_mcmc.dim(); ++d){\n        top_k_starting[i*num_to_sample*gaussian_process_mcmc.dim() + d] = start_point_set[ki*num_to_sample*gaussian_process_mcmc.dim() + d];\n      }\n      q.pop();\n    }\n\n    // init winner to be first point in set and 'force' its value to be 0.0; we cannot do worse than this\n    OptimizationIOContainer io_container(state_vector[0].GetProblemSize(), 0.0, top_k_starting.data());\n\n    using RepeatedDomain = RepeatedDomain<DomainType>;\n    RepeatedDomain repeated_domain(domain, num_to_sample);\n    GradientDescentOptimizer<ExpectedImprovementMCMCEvaluator, RepeatedDomain> gd_opt;\n    MultistartOptimizer<GradientDescentOptimizer<ExpectedImprovementMCMCEvaluator, RepeatedDomain> > multistart_optimizer;\n    multistart_optimizer.MultistartOptimize(gd_opt, ei_evaluator, optimizer_parameters,\n                                            repeated_domain, thread_schedule, top_k_starting.data(),\n                                            k, state_vector.data(), nullptr, &io_container);\n    *found_flag = io_container.found_flag;\n    std::copy(io_container.best_point.begin(), io_container.best_point.end(), best_next_point);\n  }\n}\n\n/*!\\rst\n  Function to evaluate Knowledge Gradient (q,p-KG) over a specified list of ``num_multistarts`` points.\n  Optionally outputs the KG at each of these points.\n  Outputs the point of the set obtaining the maximum KG value.\n\n  Generally gradient descent is preferred but when they fail to converge this may be the only \"robust\" option.\n  This function is also useful for plotting or debugging purposes (just to get a bunch of KG values).\n\n  This function is just a wrapper that builds the required state objects and a NullOptimizer object and calls\n  MultistartOptimizer<...>::MultistartOptimize(...); see gpp_optimization.hpp.\n\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_static), chunk_size (0).\n    :initial_guesses[dim][num_to_sample][num_multistarts]: list of points at which to compute KG\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :discrete_pts[dim][num_pts]: points to approximate KG\n    :num_multistarts: number of points to check\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-KG)\n    :num_pts: number of points in discrete_pts\n    :best_so_far: value of the best mean value so far in discrete_pts\n    :max_int_steps: maximum number of MC iterations\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n    :noise: variance of measurement noise\n  \\output\n    :found_flag[1]: true if best_next_point corresponds to a nonzero KG\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :function_values[num_multistarts]: KG evaluated at each point of ``initial_guesses``, in the same order as\n      ``initial_guesses``; never dereferenced if nullptr\n    :best_next_point[dim][num_to_sample]: points yielding the best KG according to dumb search\n\\endrst*/\nvoid EvaluateEIMCMCAtPointList(GaussianProcessMCMC& gaussian_process_mcmc,\n                               const ThreadSchedule& thread_schedule,\n                               double const * restrict initial_guesses,\n                               double const * restrict points_being_sampled,\n                               int num_multistarts, int num_to_sample,\n                               int num_being_sampled, double const * best_so_far,\n                               int max_int_steps, bool * restrict found_flag, NormalRNG * normal_rng,\n                               double * restrict function_values,\n                               double * restrict best_next_point);\n\n/*!\\rst\n  Perform multistart gradient descent (MGD) to solve the q,p-KG problem (see ComputeKGOptimalPointsToSample and/or\n  header docs), starting from ``num_multistarts`` points selected randomly from the within the domain.\n\n  This function is a simple wrapper around ComputeOptimalPointsToSampleViaMultistartGradientDescent(). It additionally\n  generates a set of random starting points and is just here for convenience when better initial guesses are not\n  available.\n\n  See ComputeKGOptimalPointsToSampleViaMultistartGradientDescent() for more details.\n\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :optimizer_parameters: GradientDescentParameters object that describes the parameters controlling KG optimization\n      (e.g., number of iterations, tolerances, learning rate)\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_dynamic), chunk_size (0).\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :discrete_pts[dim][num_pts]: points to approximate KG\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-KG)\n    :num_pts: number of points in discrete_pts\n    :best_so_far: value of the best mean value so far in discrete_pts\n    :max_int_steps: maximum number of MC iterations\n    :uniform_generator[1]: a UniformRandomGenerator object providing the random engine for uniform random numbers\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n    :noise: variance of measurement noise\n  \\output\n    :found_flag[1]: true if best_next_point corresponds to a nonzero KG\n    :uniform_generator[1]: UniformRandomGenerator object will have its state changed due to random draws\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :best_next_point[dim][num_to_sample]: points yielding the best KG according to MGD\n\\endrst*/\ntemplate <typename DomainType>\nvoid ComputeEIMCMCOptimalPointsToSampleWithRandomStarts(GaussianProcessMCMC& gaussian_process_mcmc,\n                                                        const GradientDescentParameters& optimizer_parameters,\n                                                        const DomainType& domain, const ThreadSchedule& thread_schedule,\n                                                        double const * restrict points_being_sampled,\n                                                        int num_to_sample, int num_being_sampled,\n                                                        double const * best_so_far,\n                                                        int max_int_steps, bool * restrict found_flag,\n                                                        UniformRandomGenerator * uniform_generator, NormalRNG * normal_rng,\n                                                        double * restrict best_next_point) {\n/*\n  int grid_size = 100;\n  std::vector<double> starting_points(gaussian_process_mcmc.dim()*optimizer_parameters.num_multistarts*num_to_sample);\n  std::vector<double> temp_points(gaussian_process_mcmc.dim()*grid_size*num_to_sample);\n  std::vector<double> function_values(grid_size, 0.0);\n\n  // GenerateUniformPointsInDomain() is allowed to return fewer than the requested number of multistarts\n  RepeatedDomain<DomainType> repeated_domain(domain, num_to_sample);\n  int num_multistarts = optimizer_parameters.num_multistarts;\n\n  for (int i = 0; i < num_multistarts; ++i){\n      repeated_domain.GenerateUniformPointsInDomain(grid_size, uniform_generator, temp_points.data());\n      EvaluateEIMCMCAtPointList(gaussian_process_mcmc, thread_schedule, temp_points.data(),\n                                points_being_sampled, grid_size, num_to_sample,\n                                num_being_sampled, best_so_far, max_int_steps, found_flag, normal_rng,\n                                function_values.data(), starting_points.data() + i*num_to_sample*gaussian_process_mcmc.dim());\n  }\n*/\n  std::vector<double> starting_points(gaussian_process_mcmc.dim()*optimizer_parameters.num_multistarts*num_to_sample);\n  RepeatedDomain<DomainType> repeated_domain(domain, num_to_sample);\n  int num_multistarts = repeated_domain.GenerateUniformPointsInDomain(optimizer_parameters.num_multistarts,\n                                                                      uniform_generator, starting_points.data());\n  ComputeEIMCMCOptimalPointsToSampleViaMultistartGradientDescent(gaussian_process_mcmc, optimizer_parameters, domain,\n                                                                 thread_schedule, starting_points.data(),\n                                                                 points_being_sampled, num_multistarts,\n                                                                 num_to_sample, num_being_sampled,\n                                                                 best_so_far, max_int_steps,\n                                                                 normal_rng, found_flag, best_next_point);\n#ifdef OL_WARNING_PRINT\n  if (false == *found_flag) {\n    OL_WARNING_PRINTF(\"WARNING: %s DID NOT CONVERGE\\n\", OL_CURRENT_FUNCTION_NAME);\n    OL_WARNING_PRINTF(\"First multistart point was returned:\\n\");\n    PrintMatrixTrans(starting_points.data(), num_to_sample, gaussian_process_mcmc.dim());\n  }\n#endif\n}\n\n/*!\\rst\n  Perform a random, naive search to \"solve\" the q,p-KG problem (see ComputeKGOptimalPointsToSample and/or\n  header docs).  Evaluates KG at ``num_multistarts`` points (e.g., on a latin hypercube) to find the\n  point with the best KG value.\n\n  Generally gradient descent is preferred but when they fail to converge this may be the only \"robust\" option.\n\n  Solution is guaranteed to lie within the region specified by ``domain``; note that this may not be a\n  true optima (i.e., the gradient may be substantially nonzero).\n\n  Wraps EvaluateKGAtPointList(); constructs the input point list with a uniform random sampling from the given Domain object.\n\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_static), chunk_size (0).\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :discrete_pts[dim][num_pts]: points to approximate KG\n    :num_multistarts: number of random points to check\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-KG)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-KG)\n    :num_pts: number of points in discrete_pts\n    :best_so_far: value of the best mean value so far in discrete_pts\n    :max_int_steps: maximum number of MC iterations\n    :uniform_generator[1]: a UniformRandomGenerator object providing the random engine for uniform random numbers\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n    :noise: variance of measurement noise\n  \\output\n    found_flag[1]: true if best_next_point corresponds to a nonzero KG\n    :uniform_generator[1]: UniformRandomGenerator object will have its state changed due to random draws\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :best_next_point[dim][num_to_sample]: points yielding the best KG according to dumb search\n\\endrst*/\ntemplate <typename DomainType>\nvoid ComputeEIMCMCOptimalPointsToSampleViaLatinHypercubeSearch(GaussianProcessMCMC& gaussian_process_mcmc,\n                                                               const DomainType& domain,\n                                                               const ThreadSchedule& thread_schedule,\n                                                               double const * restrict points_being_sampled,\n                                                               int num_multistarts, int num_to_sample,\n                                                               int num_being_sampled, double const * best_so_far,\n                                                               int max_int_steps,\n                                                               bool * restrict found_flag,\n                                                               UniformRandomGenerator * uniform_generator,\n                                                               NormalRNG * normal_rng,\n                                                               double * restrict best_next_point) {\n  std::vector<double> initial_guesses(gaussian_process_mcmc.dim()*num_multistarts*num_to_sample);\n  RepeatedDomain<DomainType> repeated_domain(domain, num_to_sample);\n  num_multistarts = repeated_domain.GenerateUniformPointsInDomain(num_multistarts, uniform_generator,\n                                                                  initial_guesses.data());\n\n  EvaluateEIMCMCAtPointList(gaussian_process_mcmc, thread_schedule, initial_guesses.data(),\n                            points_being_sampled, num_multistarts, num_to_sample,\n                            num_being_sampled, best_so_far, max_int_steps,\n                            found_flag, normal_rng, nullptr, best_next_point);\n}\n\n\n/*!\\rst\n  Solve the q,p-KG problem (see header docs) by optimizing the knowledge gradient.\n  Uses multistart gradient descent, \"dumb\" search, and/or other heuristics to perform the optimization.\n\n  This is the primary entry-point for KG optimization in the optimal_learning library. It offers our best shot at\n  improving robustness by combining higher accuracy methods like gradient descent with fail-safes like random/grid search.\n\n  Returns the optimal set of q points to sample CONCURRENTLY by solving the q,p-KG problem.  That is, we may want to run 4\n  experiments at the same time and maximize the KG across all 4 experiments at once while knowing of 2 ongoing experiments\n  (4,2-KG). This function handles this use case. Evaluation of q,p-KG (and its gradient) for q > 1 or p > 1 is expensive\n  (requires monte-carlo iteration), so this method is usually very expensive.\n\n  Wraps ComputeKGOptimalPointsToSampleWithRandomStarts() and ComputeKGOptimalPointsToSampleViaLatinHypercubeSearch().\n\n  Compared to ComputeHeuristicPointsToSample() (``gpp_heuristic_expected_improvement_optimization.hpp``), this function\n  makes no external assumptions about the underlying objective function. Instead, it utilizes a feature of the\n  GaussianProcess that allows the GP to account for ongoing/incomplete experiments.\n\n  .. NOTE:: These comments were copied into multistart_knowledge_gradient_optimization() in cpp_wrappers/knowledge_gradient.py.\n\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :optimizer_parameters: GradientDescentParameters object that describes the parameters controlling KG optimization\n      (e.g., number of iterations, tolerances, learning rate)\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_dynamic), chunk_size (0).\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :discrete_pts[dim][num_pts]: points to approximate KG\n    :num_to_sample: how many simultaneous experiments you would like to run (i.e., the q in q,p-KG)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-KG)\n    :num_pts: number of points in discrete_pts\n    :best_so_far: value of the best mean value so far in discrete_pts\n    :max_int_steps: maximum number of MC iterations\n    :lhc_search_only: whether to ONLY use latin hypercube search (and skip gradient descent EI opt)\n    :num_lhc_samples: number of samples to draw if/when doing latin hypercube search\n    :uniform_generator[1]: a UniformRandomGenerator object providing the random engine for uniform random numbers\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n    :noise: variance of measurement noise\n  \\output\n    :found_flag[1]: true if best_points_to_sample corresponds to a nonzero KG if sampled simultaneously\n    :uniform_generator[1]: UniformRandomGenerator object will have its state changed due to random draws\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :best_points_to_sample[num_to_sample*dim]: point yielding the best KG according to MGD\n\\endrst*/\ntemplate <typename DomainType>\nvoid ComputeEIMCMCOptimalPointsToSample(GaussianProcessMCMC& gaussian_process_mcmc,\n                                        const GradientDescentParameters& optimizer_parameters,\n                                        const DomainType& domain, const ThreadSchedule& thread_schedule,\n                                        double const * restrict points_being_sampled,\n                                        int num_to_sample, int num_being_sampled,\n                                        double const * best_so_far,\n                                        int max_int_steps, bool lhc_search_only,\n                                        int num_lhc_samples, bool * restrict found_flag,\n                                        UniformRandomGenerator * uniform_generator,\n                                        NormalRNG * normal_rng, double * restrict best_points_to_sample);\n// template explicit instantiation declarations, see gpp_common.hpp header comments, item 6\nextern template void ComputeEIMCMCOptimalPointsToSample(\n    GaussianProcessMCMC& gaussian_process_mcmc, const GradientDescentParameters& optimizer_parameters,\n    const TensorProductDomain& domain, const ThreadSchedule& thread_schedule,\n    double const * restrict points_being_sampled,\n    int num_to_sample, int num_being_sampled,\n    double const * best_so_far, int max_int_steps, bool lhc_search_only,\n    int num_lhc_samples, bool * restrict found_flag, UniformRandomGenerator * uniform_generator,\n    NormalRNG * normal_rng, double * restrict best_points_to_sample);\nextern template void ComputeEIMCMCOptimalPointsToSample(\n    GaussianProcessMCMC& gaussian_process_mcmc, const GradientDescentParameters& optimizer_parameters,\n    const SimplexIntersectTensorProductDomain& domain, const ThreadSchedule& thread_schedule,\n    double const * restrict points_being_sampled,\n    int num_to_sample, int num_being_sampled,\n    double const * best_so_far, int max_int_steps, bool lhc_search_only, int num_lhc_samples, bool * restrict found_flag,\n    UniformRandomGenerator * uniform_generator, NormalRNG * normal_rng, double * restrict best_points_to_sample);\n}  // end namespace optimal_learning\n\n#endif  // MOE_OPTIMAL_LEARNING_CPP_GPP_HEURISTIC_EXPECTED_IMPROVEMENT_OPTIMIZATION_HPP_", "meta": {"hexsha": "a3eb26404100737dd48c1887eed2caeebb2a5bb6", "size": 70264, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "moe/optimal_learning/cpp/gpp_expected_improvement_mcmc_optimization.hpp", "max_stars_repo_name": "AliBaheri/Cornell-MOE", "max_stars_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moe/optimal_learning/cpp/gpp_expected_improvement_mcmc_optimization.hpp", "max_issues_repo_name": "AliBaheri/Cornell-MOE", "max_issues_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moe/optimal_learning/cpp/gpp_expected_improvement_mcmc_optimization.hpp", "max_forks_repo_name": "AliBaheri/Cornell-MOE", "max_forks_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T14:48:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-02T14:48:26.000Z", "avg_line_length": 58.455906822, "max_line_length": 177, "alphanum_fraction": 0.7282961403, "num_tokens": 15557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.618296557608216}}
{"text": "/**\n   $ g++ -I/path/to/boost sieve.cpp -o sieve && sieve 10000000\n */\n#include <inttypes.h> // uintmax_t\n#include <limits>\n#include <cmath>\n#include <iostream>\n#include <sstream>\n#include <vector>\n\n#include <boost/lambda/lambda.hpp>\n\n\nint main(int argc, char *argv[])\n{\n  using namespace std;\n  using namespace boost::lambda;\n\n  int limit = 10000;\n  if (argc == 2) {\n    stringstream ss(argv[--argc]);\n    ss >> limit;\n\n    if (limit < 1 or ss.fail()) {\n      cerr << \"USAGE:\\n  sieve LIMIT\\n\\nwhere LIMIT in the range [1, \"\n\t   << numeric_limits<int>::max() << \")\" << endl;\n      return 2;\n    }\n  }\n\n  // print primes less then 100\n  primesupto(100, cout << _1 << \" \");\n  cout << endl;\n\n  // find number of primes less then limit and their sum\n  int count = 0;\n  uintmax_t sum = 0;\n  primesupto(limit, (var(sum) += _1, var(count) += 1));\n\n  cout << \"limit sum pi(n)\\n\"\n       << limit << \" \" << sum << \" \" << count << endl;\n}\n", "meta": {"hexsha": "9c213d01c0176b5e29cd709639c15733a9e4b96c", "size": 929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-2.cpp", "max_stars_repo_name": "djgoku/RosettaCodeData", "max_stars_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_stars_repo_licenses": ["Info-ZIP"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-29T20:08:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:16:05.000Z", "max_issues_repo_path": "Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-2.cpp", "max_issues_repo_name": "djgoku/RosettaCodeData", "max_issues_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_issues_repo_licenses": ["Info-ZIP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-2.cpp", "max_forks_repo_name": "djgoku/RosettaCodeData", "max_forks_repo_head_hexsha": "91df62d46142e921b3eacdb52b0316c39ee236bc", "max_forks_repo_licenses": ["Info-ZIP"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-13T04:19:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T04:19:31.000Z", "avg_line_length": 21.6046511628, "max_line_length": 70, "alphanum_fraction": 0.581270183, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6182965556248731}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Core>\n\nclass Belief {\npublic:\n\tvoid propagateBelief(Mat &P1, Point &qNear, Point &qNew, double &sigma, Mat &P2)\n\t{\n\t\tdx1 = qNear.x - qNew.x;\n\t\tdy1 = qNear.y - qNew.y;\n\t\tdz1 = qNear.z - qNew.z;\n\n\t\tr = sqrt(pow(dx1, 2) + pow(dy1, 2) + pow(dz1, 2));\n\n\t\tEigen::MatrixXd H(1, DIM);\n\n\t\tH.row(0) << (1 / r)*dx1, (1 / r)*dy1, (1 / r)*dz1;\n\n\t\tz = 1 / (1 + r * r);\n\t\tR = sigma * sigma;\n\n\t\tP_prd = P1 + GQG;\n\t\tS = (H * P_prd * H.transpose()).value() + M * R * M;\n\n\t\tK = (1 / S) * (P_prd * H.transpose());\n\t\tP2 = (I - (K*H)) * P_prd;\n\t}\n\nprivate:\n\tMat I = Eigen::MatrixXd::Identity(DIM, DIM);\n\tMat A = I;\n\tMat B = I;\n\tMat G = I;\n\n\tMat GQG = G * Q * G.transpose();\n\n\tMat P_prd, P2;\n\n\tfloat processNoise = 0.028;\n\tMat Q = pow(processNoise, 2) * I;\n\tdouble M = 1;\n\tdouble R, z, S, r;\n\tdouble dx1, dy1, dz1;\n\tEigen::MatrixXd H = Eigen::MatrixXd(1, DIM);\n\tEigen::MatrixXd K;\n};\n\n\n", "meta": {"hexsha": "ba8e3bdd640b2025fd8cb90beaddd54901668847", "size": 902, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/belief.hpp", "max_stars_repo_name": "saihv/rrbt", "max_stars_repo_head_hexsha": "3003b617f53e3455d67707307e0f0d52c2f83500", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T08:51:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T02:07:56.000Z", "max_issues_repo_path": "include/belief.hpp", "max_issues_repo_name": "saihv/rrbt", "max_issues_repo_head_hexsha": "3003b617f53e3455d67707307e0f0d52c2f83500", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/belief.hpp", "max_forks_repo_name": "saihv/rrbt", "max_forks_repo_head_hexsha": "3003b617f53e3455d67707307e0f0d52c2f83500", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-22T07:36:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T03:42:03.000Z", "avg_line_length": 18.7916666667, "max_line_length": 81, "alphanum_fraction": 0.5487804878, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.6182576785250055}}
{"text": "#pragma once\n#include <fmt/core.h>\n#include <Eigen/Dense>\n#include <random>\n\ntemplate<typename T>\nusing PCoord = Eigen::Matrix<T, 1, 3>;\n\nenum JastrowType {\n    SIMPLE_JASTROW,\n};\n\nenum AtomicWfnType {\n    VB,\n    MO,\n};\n\ntemplate<typename T>\nclass WaveFn {\npublic:\n    virtual ~WaveFn(){};\n    // return the value of wave function\n    virtual T value(const PCoord<T>&)=0;\n\n    // return three components of grad wave function\n    virtual PCoord<T> grad(const PCoord<T>&)=0;\n    \n    // return laplacian of the wave function\n    virtual T laplace(const PCoord<T>&)=0;\n};\n\n// Simple Wave function $$\\phi(r) = (1+cr)e^{-\\alpha r}$$\ntemplate <typename T>\nclass AtomicWaveFn: public WaveFn<T> {\npublic:\n    AtomicWaveFn(T c, T alpha): c(c), alpha(alpha) {};\n    ~AtomicWaveFn(){};\n\n    T value(const PCoord<T>& coord) {\n        auto r = coord.norm();\n        auto ar = alpha*r;\n        return (1+c*r)*std::exp(-ar);\n    }\n\n    PCoord<T> grad(const PCoord<T>& coord) {\n        auto r = coord.norm();\n        auto ar = alpha*r;\n        auto coeff = (c-alpha*(c*r+1))*std::exp(-ar);\n        return coeff*coord.normalized();\n    }\n\n    T laplace(const PCoord<T>& coord) {\n        auto r = coord.norm();\n        auto ar = alpha*r;\n        return (c*(ar*(ar-4)+2) + alpha*(ar-2))*std::exp(-ar)/r;\n    }\n\nprivate:\n    T c, alpha;\n};\n\n// Composed Wave functions: VB\ntemplate<typename T>\nclass VBWaveFn: public WaveFn<T> {\npublic:\n    VBWaveFn(T c, T alpha, const PCoord<T>& R1, const PCoord<T>& R2): \n        c(c), alpha(alpha), R1(R1), R2(R2) {\n        phi1 = new AtomicWaveFn<T>(c, alpha);\n        phi2 = new AtomicWaveFn<T>(c, alpha);\n    }\n\n    ~VBWaveFn() {\n        delete phi1, phi2;\n    }\n\n    T value(const PCoord<T>& r) {\n        return phi1->value(r-R1)*phi2->value(r-R2);\n    }\n    \n    PCoord<T> grad(const PCoord<T>& r) {\n        return phi2->value(r-R2)*phi1->grad(r-R1) + \n               phi1->value(r-R1)*phi2->grad(r-R2);\n    }\n\n    T laplace(const PCoord<T>& r) {\n        return phi2->value(r-R2)*phi1->laplace(r-R1) + \n               phi1->value(r-R1)*phi2->laplace(r-R2) +\n               2*(phi1->grad(r-R1)).dot(phi2->grad(r-R2));\n    }\n\nprivate:\n    T c, alpha;\n    PCoord<T> R1, R2;\n    AtomicWaveFn<T>* phi1;\n    AtomicWaveFn<T>* phi2;\n};\n\n// Composed Wave functions: MO\ntemplate <typename T>\nclass MOWaveFn: public WaveFn<T> {\npublic:\n    MOWaveFn(T c, T alpha, const PCoord<T>& R1, const PCoord<T>& R2): \n        c(c), alpha(alpha), R1(R1), R2(R2) {\n        phi1 = new AtomicWaveFn<T>(c, alpha);\n        phi2 = new AtomicWaveFn<T>(c, alpha);\n    }\n\n    T value(const PCoord<T>& r) {\n        return phi1->value(r-R1)+phi2->value(r-R2);\n    }\n    \n    PCoord<T> grad(const PCoord<T>& r) {\n        return phi1->grad(r-R1) + phi2->grad(r-R2);\n    }\n\n    T laplace(const PCoord<T>& r) {\n        return phi1->laplace(r-R1) + phi2->laplace(r-R2);\n    }\n\nprivate:\n    T c, alpha;\n    PCoord<T> R1, R2;\n    AtomicWaveFn<T>* phi1;\n    AtomicWaveFn<T>* phi2;\n};\n\n// Define Jastrow wavefunction\ntemplate<typename T>\n// class JastrowWfn: public WaveFn<T> {\nclass JastrowWfn {\npublic:\n    JastrowWfn(T factor): factor(factor) {}\n\n    ~JastrowWfn() {}\n\n    inline T value(const PCoord<T>& r1, const PCoord<T>& r2) {\n        return std::exp(-ufunc(r1, r2));\n    }\n\n    // The gradient is symmetric w.r.t r1 and r2\n    std::pair<PCoord<T>, PCoord<T>> \n    grad(const PCoord<T>& r1, const PCoord<T>& r2) {\n        auto val = value(r1, r2);\n        auto r12 = r1 - r2;\n        auto r = r12.norm();\n        auto dv = -r12/(2*r*std::pow(1+r/factor, 2));\n        return {-dv*val, dv*val};\n    }\n\n    std::pair<T, T> \n    laplace(const PCoord<T>& r1, const PCoord<T>& r2) {\n        auto val = value(r1, r2);\n        auto r = (r1 - r2).norm();\n        auto dv = -1/(2*std::pow(1+r/factor, 2));\n        auto d2v = -1/(r*std::pow(1+r/factor, 3));\n        auto ret = (dv*dv - d2v)*val;\n        return {ret, ret};\n    }\nprivate:\n    T factor;\n    inline T ufunc(const PCoord<T>& r1, const PCoord<T> r2) {\n        auto r = (r1 - r2).norm();\n        return factor/(2 + 2*r/factor);\n    }\n};\n\ntemplate<typename T, JastrowType Jastrow, AtomicWfnType AtomicWfn>\nclass H2Mol {\n\npublic:\n    const JastrowType jastrow_type = Jastrow;\n    const AtomicWfnType atomicwfn_type = AtomicWfn;\n\n    H2Mol(T factor, T c, T alpha, const PCoord<T>& R1, const PCoord<T>& R2):\n        R1(R1), R2(R2) {\n        switch (Jastrow) {\n            case JastrowType::SIMPLE_JASTROW:\n                jastrow = new JastrowWfn<T>(factor);\n                break;\n            default:\n                throw std::runtime_error(\"Invalid jastrow function.\");\n                break;\n        }\n\n        switch(AtomicWfn) {\n            case AtomicWfnType::MO:\n                atomicwfn = new MOWaveFn<T>(c, alpha, R1, R2);\n                break;\n            case AtomicWfnType::VB:\n                atomicwfn = new VBWaveFn<T>(c, alpha, R1, R2);\n                break;\n            default:\n                throw std::runtime_error(\"Invalid atomic wave function\");\n                break;\n        }\n    }\n\n    ~H2Mol() {\n        delete jastrow;\n        delete atomicwfn;\n    }\n\n    // Notice this calculate \\psi^* \\psi\n    T density(const PCoord<T>& r1, const PCoord<T>& r2) {\n        return std::pow(jastrow->value(r1, r2)* \\\n               atomicwfn->value(r1)*atomicwfn->value(r2), 2);\n    }\n\n    // Calculate the energy with current density\n    T energy(const PCoord<T>& r1, const PCoord<T>& r2) {\n        T ret = 0.0;\n        PCoord<T> dJdr1, dJdr2;\n        T d2Jdr1, d2Jdr2;\n        auto jval = jastrow->value(r1, r2);\n        std::tie(d2Jdr1, d2Jdr2) = jastrow->laplace(r1, r2);\n        std::tie(dJdr1, dJdr2) = jastrow->grad(r1, r2);\n        ret += (d2Jdr1+d2Jdr2)/jval;\n        auto val1 = atomicwfn->value(r1);\n        auto val2 = atomicwfn->value(r2);\n        ret += atomicwfn->laplace(r1)/val1;\n        ret += atomicwfn->laplace(r2)/val2;\n        \n        ret += 2*dJdr1.dot(atomicwfn->grad(r1))/(jval*val1);\n        ret += 2*dJdr2.dot(atomicwfn->grad(r2))/(jval*val2);\n\n        ret = -0.5*ret; // kintetic energy\n\n        ret += -1.0/(r1-R1).norm();\n        ret += -1.0/(r1-R2).norm();\n        ret += -1.0/(r2-R1).norm();\n        ret += -1.0/(r2-R2).norm();\n        ret += 1.0/(r1-r2).norm();\n        ret += 1.0/(R1-R2).norm();\n\n        return ret;\n    }\n\nprivate:\n    JastrowWfn<T>* jastrow = nullptr;\n    WaveFn<T>* atomicwfn = nullptr;\n    PCoord<T> R1, R2;\n};\n\n\ntemplate<typename T> //, typename wfn>\nclass H2MolQMC {\npublic:\n    H2MolQMC(T factor, T c, T alpha, const PCoord<T>& R1, const PCoord<T>& R2, T dr): dr(dr){\n        mol = new H2Mol<T, JastrowType::SIMPLE_JASTROW, AtomicWfnType::MO>(factor, c, alpha, R1, R2);\n    }\n\n    ~H2MolQMC() {\n        delete mol;\n    }\n\n    std::pair<T, T> sample(int maxstep=10000) {\n        \n        // Thsi method return the number between [-1, 1]\n        PCoord<T> r1 = PCoord<T>::Random(); \n        PCoord<T> r2 = PCoord<T>::Random();\n\n        PCoord<T> r1_new, r2_new;\n        T energy = mol->energy(r1, r2);\n        T density = mol->density(r1, r2);\n        std::uniform_real_distribution<T> rnum(0, 1);\n\n        //energy_old = mol->energy();\n        T energy_tot = 0.0;\n        T energy_sq_tot = 0.0;\n        int accept = 0;\n        for(int i=0; i<maxstep; i++) {\n\n            dr = std::max(dr, 0.1);\n            dr = std::min(dr, 10.0);\n\n            r1_new = r1 + dr*PCoord<T>::Random();\n            r2_new = r2 + dr*PCoord<T>::Random();\n\n            auto dtmp = mol->density(r1_new, r2_new);\n            auto ratio = dtmp/density;\n            \n            if(ratio > 1 || ratio > rnum(rgen)) {\n                r1 = r1_new;\n                r2 = r2_new;\n                density = dtmp;\n                energy = mol->energy(r1, r2);\n                accept += 1;\n            }\n\n            if(static_cast<T>(accept)/(i+1) > 0.5) dr*=scale;\n            else dr/=scale;\n\n            energy_tot += energy;\n            energy_sq_tot += energy*energy;\n        }\n        auto energy_avg = energy_tot/maxstep;\n        auto energy_std = std::sqrt(energy_sq_tot/maxstep - energy_avg*energy_avg);\n        fmt::print(\"Accept ratio: {}\\n\", (double) accept/maxstep);\n        return {energy_avg, energy_std};\n    }\n\nprivate:\n    H2Mol<T, JastrowType::SIMPLE_JASTROW, AtomicWfnType::MO>* mol;\n    PCoord<T> R1, R2;\n    T dr;\n    std::random_device rd;\n    std::mt19937 rgen{rd()};\n    const T scale = 1.01;\n    // T c, alpha;\n};", "meta": {"hexsha": "1c5d69e2a58d79207a427e3849f89407e6ccce45", "size": 8416, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cc/hydrogen.hpp", "max_stars_repo_name": "zxjzxj9/SimpleQMC", "max_stars_repo_head_hexsha": "6382150bbe39683727665542459966fe3961eb56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cc/hydrogen.hpp", "max_issues_repo_name": "zxjzxj9/SimpleQMC", "max_issues_repo_head_hexsha": "6382150bbe39683727665542459966fe3961eb56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cc/hydrogen.hpp", "max_forks_repo_name": "zxjzxj9/SimpleQMC", "max_forks_repo_head_hexsha": "6382150bbe39683727665542459966fe3961eb56", "max_forks_repo_licenses": ["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.1483870968, "max_line_length": 101, "alphanum_fraction": 0.5383792776, "num_tokens": 2698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.6181683816911148}}
{"text": "#pragma once\n#include <cstddef>\n#include <random>\n#include <functional>\n#include <vector>\n#include <limits>\n#include <iostream>\n#include <boost/multiprecision/number.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/math/special_functions/prime.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n\nnamespace mp = boost::multiprecision;\nnamespace math = boost::math;\nnamespace rnd = boost::random;\n\nnamespace rsa {\n\n    struct random {\n\n        boost::mt19937_64 generator;\n\n        void init_generator(const uint64_t seed) {\n            generator = boost::mt19937_64(seed);\n        }\n\n        static auto& default_random() {\n            static random rand;\n            return rand;\n        }\n\n    };\n\n    template<unsigned int N>\n    struct num_utils {\n\n        using number = mp::number<mp::backends::cpp_int_backend<N, N, mp::unsigned_magnitude, mp::unchecked, void>>;\n        using signed_number = mp::number<mp::backends::cpp_int_backend<2 * N, 2 * N, mp::signed_magnitude, mp::unchecked, void>>;\n\n        static auto get_int_random(const number min = std::numeric_limits<number>::min(),\n                                   const number max = std::numeric_limits<number>::max()) {\n            rnd::uniform_int_distribution<number> dist(min, max);\n            return std::bind(dist, std::ref(random::default_random().generator));\n\n        }\n\n        static auto generate_random_prime(const unsigned int k = 100) {\n            const auto rand = get_int_random();\n            while(true) {\n                const auto n = rand();\n                for (unsigned int i = 0; i < math::max_prime; ++i)\n                    if (n % math::prime(i) == 0)\n                        goto next;\n                if (mp::miller_rabin_test(n, k))\n                    return n;\n                next:\n                continue;\n            }\n        }\n\n        static auto bezout_identity(const signed_number& a, const signed_number& b) {\n            if (a == 0)\n                return std::make_pair(signed_number(0), signed_number(1));\n            const auto buff = bezout_identity(b % a, a);\n            return std::make_pair(buff.second - (b / a) * buff.first, buff.first);\n        }\n\n        template<typename It>\n        static auto bytes_to_number(It begin, const It& end) {\n            number result;\n            mp::import_bits(result, begin, end, 8);\n            return result;\n        }\n\n        static auto number_to_bytes(const number& number) {\n            std::array<char, N / 8> result;\n            result.fill(0);\n            mp::export_bits(number, result.rbegin(), 8, false);\n            return result;\n        }\n\n    };\n\n}// namespace rsa\n", "meta": {"hexsha": "0376c67817c511c7fa9e97cd46f186fdf8c5f730", "size": 2753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils.hpp", "max_stars_repo_name": "GoldFeniks/RSA", "max_stars_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_stars_repo_licenses": ["MIT"], "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.hpp", "max_issues_repo_name": "GoldFeniks/RSA", "max_issues_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_issues_repo_licenses": ["MIT"], "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.hpp", "max_forks_repo_name": "GoldFeniks/RSA", "max_forks_repo_head_hexsha": "0e5020202d03a84a217bd2cfd416a09590a71b37", "max_forks_repo_licenses": ["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.6436781609, "max_line_length": 129, "alphanum_fraction": 0.582273883, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254318, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6181683731458051}}
{"text": "//\n//  Neural.cpp\n//  \n//\n//  Created by Zac Schulwolf on 12/27/16.\n//\n// Based on http://neuralnetworksanddeeplearning.com/chap1.html\n// Compile by g++ -I \"$(brew --prefix eigen)/include/eigen3\" Neural.cpp -o Neural\n\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <ctime> //for random stuff\n#include <list> //for list of Matrices for biases and weights\nusing namespace Eigen;\nusing namespace std;\n\n\n\n\n\nvoid Biases(list<MatrixXd> &biases, VectorXi sizes){ //NEEDS TO BE OPTIMIZED inline?\n    int r;\n    for(int i=0; i <sizes.rows()-1;i++){\n        r=sizes[i+1];\n        biases.push_back(MatrixXd::Random(r,1));\n    }\n    \n    cout << endl << \"Biases:\" << endl; //print biases\n    for (list<MatrixXd>::iterator itb = biases.begin(); itb != biases.end(); itb++) //print biases\n        cout << *itb << endl <<endl; //print biases\n}\n\n\nvoid Weights(list<MatrixXd> &weights, VectorXi sizes){ //NEEDS TO BE OPTIMIZED inline?\n    int x,y;\n    for(int i=0; i <sizes.rows()-1;i++){\n\n        y=sizes[i+1];\n        x=sizes[i];\n        weights.push_back(MatrixXd::Random(y,x));\n    }\n    \n    cout << endl << \"Weights:\" << endl; //print weights\n    for (list<MatrixXd>::iterator itw = weights.begin(); itw != weights.end(); itw++) //print weights\n        cout << *itw << endl <<endl; //print weights\n}\n\n\n\nclass Network{\n    int num_layers;\n    VectorXi sizes;\n    list<MatrixXd> biases;\n    list<MatrixXd> weights;\n    \n    VectorXd sigmoid(ArrayXd z){\n        return (1/(1+exp(-z))).vector();\n    }\n    \n    \npublic:\n    Network(VectorXi Sizes){ //constructor\n        struct timespec tm; //time for random seed\n        clock_gettime(CLOCK_REALTIME,&tm); //time for random seed\n        srand(tm.tv_nsec); //This makes the Eigen random different each time        NEEDS TO BE OPTIMIZED\n        \n        num_layers = Sizes.rows();\n        sizes = Sizes;\n        Biases(biases,sizes);\n        Weights(weights,sizes);\n        \n        \n    }\n    \n    VectorXd feedforward(VectorXd a){ //probably needs to be private\n\t\tMatrixXd b;\n        MatrixXd w;\n        list<MatrixXd>::iterator itb = biases.begin();\n        list<MatrixXd>::iterator itw = weights.begin();\n        cout << \"sizes.rows() = \" << sizes.rows()<<endl;\n        \n        \n        /*for (list<MatrixXd>::iterator itb = biases.begin(); itb != biases.end(); itb++){ //print biases\n            b = *itb;\n        }*/\n        \n        \n        for (int i=0; i<sizes.rows()-1;i++,itb++,itw++){\n            ///cout << \"asdjkasldjsakldjaklsdjlkas\\n\";\n            //b.resize((*itb).rows(),(*itb).cols());\n            //w.resize((*itw).rows(),(*itw).cols());\n            \n            cout << (*itb).rows() << endl << (*itb).cols() << endl << endl;\n            cout << (*itw).rows() << endl << (*itw).cols() << endl << endl;\n            b= *itb;\n            w= *itw;\n            cout << \"*itb:\\n\"<< *itb << endl <<endl; //print biases\n            cout << \"*itw:\\n\"<< *itw << endl <<endl; //print weights\n\n            //cout << \"itb at \" << i << \" is:\\n\" << *itb << endl;\n            //cout << \"itw at \" << i << \" is:\\n\" << *itw << endl;\n            cout << \"a:\\n\" << a << endl << \"w:\\n\" << w << endl <<\"a.matrix()\\n\" << a.matrix() << endl << \"b.array():\\n\" << b.array() << endl;\n            \n            \n            a = sigmoid((a * w).array() + b.array()); //w.row(0) is there because weights is always a vector but its easier to store it as a matrix\n            cout << endl << endl << a << endl << endl;\n            \n        }\n        return a;\n    }\n\n};\n\nint main(){\n    VectorXi s(3);\n    s << 1,2,3;\n    Network a(s);\n    ArrayXd arr(2);\n    arr << 1,2;\n    a.feedforward(arr);\n    \n    return 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "81de30a3f1fad921078d573893f9a7d1ec0d449d", "size": 3657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Neural.cpp", "max_stars_repo_name": "zacswolf/MNISTNeuralNetwork", "max_stars_repo_head_hexsha": "9eae847f3fb756329ce26c2ca3062aa7f29c83c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Neural.cpp", "max_issues_repo_name": "zacswolf/MNISTNeuralNetwork", "max_issues_repo_head_hexsha": "9eae847f3fb756329ce26c2ca3062aa7f29c83c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Neural.cpp", "max_forks_repo_name": "zacswolf/MNISTNeuralNetwork", "max_forks_repo_head_hexsha": "9eae847f3fb756329ce26c2ca3062aa7f29c83c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8897058824, "max_line_length": 147, "alphanum_fraction": 0.5211922341, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.6992544210587586, "lm_q1q2_score": 0.6181683718778684}}
{"text": "\r\n#include <fstream>\r\n\r\n#include <boost/format.hpp>\r\n\r\n#include \"DelaunayTriangulation.h\"\r\n#include \"DT_Circle.h\"\r\n\r\nbool isContained(Triangle * t, Vertex * p);\r\nbool inCircle(Triangle *a, Vertex * pr);\r\nbool inCircle(Vertex * a, Vertex * b, Vertex * c, Vertex * d);\r\nCircle circleForPoints(Vertex * a, Vertex * b, Vertex * c);\r\nVertex pointAlongLine2D(Vertex * a, Vertex * b, double tn = 0.5);\r\nbool onEdge(Vertex * a, Vertex * b, Vertex * pr);\r\ndouble distance2Point(Vertex * a, Vertex * b, Vertex * pr);\r\n\r\n\r\n//\r\n// Friend functions of Triangle & Vertex\r\n//\r\nbool isContained(Triangle * t, Vertex * p) {\r\n    double x = p->getX();\r\n    double y = p->getY();\r\n    \r\n    double x1 = t->data[0]->getX();\r\n    double y1 = t->data[0]->getY();\r\n    \r\n    double x2 = t->data[1]->getX();\r\n    double y2 = t->data[1]->getY();\r\n    \r\n    double x3 = t->data[2]->getX();\r\n    double y3 = t->data[2]->getY();\r\n    \r\n    double denom = 1.0 / (x1*(y2 - y3) + y1*(x3 - x2) + x2*y3 - y2*x3);\r\n    \r\n    double t1 = (x*(y3 - y1) + y*(x1 - x3) - x1*y3 + y1*x3) *  denom;\r\n    double t2 = (x*(y2 - y1) + y*(x1 - x2) - x1*y2 + y1*x2) * -denom;\r\n    \r\n    if (0.0 <= t1 && t1 <= 1.0 &&\r\n        0.0 <= t2 && t2 <= 1.0 &&\r\n        t1 + t2 <= 1.0)\r\n        return true;\r\n    else\r\n        return false;\r\n}\r\n\r\nbool inCircle(Triangle *a, Vertex * pr)\r\n{\r\n    Vertex ** p = a->getVertices();\r\n    return inCircle(p[0],p[1],p[2],pr);\r\n}\r\n\r\nbool inCircle(Vertex * a, Vertex * b, Vertex * c, Vertex * d)\r\n{\r\n    double xa = a->getX();\r\n    double xb = b->getX();\r\n    double xc = c->getX();\r\n    double xd = d->getX();\r\n    \r\n    double ya = a->getY();\r\n    double yb = b->getY();\r\n    double yc = c->getY();\r\n    double yd = d->getY();\r\n    \r\n    double sa = xa * xa + ya * ya;\r\n    double sb = xb * xb + yb * yb;\r\n    double sc = xc * xc + yc * yc;\r\n    double sd = xd * xd + yd * yd;\r\n    \r\n    double det = 0.0;\r\n    det  = xa * ( yb * (sc - sd) - sb * (yc - yd) + (yc * sd - yd * sc) );\r\n    det -= ya * ( xb * (sc - sd) - sb * (xc - xd) + (xc * sd - xd * sc) );\r\n    det += sa * ( xb * (yc - yd) - yb * (xc - xd) + (xc * yd - xd * yc) );\r\n    det -=      ( xb * (yc * sd - yd * sc) - yb * (xc * sd - xd * sc) + sb * (xc * yd - xd * yc) );\r\n    \r\n    if (det > 0.0)\r\n        return true;\r\n    else\r\n        return false;\r\n}\r\n\r\nCircle circleForPoints(Vertex * a, Vertex * b, Vertex * c)\r\n{\r\n    double x1 = a->getX();\r\n    double x2 = b->getX();\r\n    double x3 = c->getX();\r\n    \r\n    double y1 = a->getY();\r\n    double y2 = b->getY();\r\n    double y3 = c->getY();\r\n    \r\n    double X2 = (double)(x2-x1);\r\n    double X3 = (double)(x3-x1);\r\n    double Y2 = (double)(y2-y1);\r\n    double Y3 = (double)(y3-y1);\r\n    \r\n    double alpha = X3 / X2;\r\n    \r\n    double bx2 = (x2+x1) * X2;\r\n    double bx3 = (x3+x1) * X3;\r\n    double by2 = (y2+y1) * Y2;\r\n    double by3 = (y3+y1) * Y3;\r\n    \r\n    double h = 0.0;\r\n    double k = 0.0;\r\n    double r = 0.0;\r\n    \r\n    k = bx3 + by3 - alpha * (bx2 + by2);\r\n    k /= 2 * (Y3 - alpha * Y2);\r\n    \r\n    h = bx2 + by2 - 2 * k * Y2;\r\n    h /= 2 * X2;\r\n    \r\n    r = sqrt( (x1 - h)*(x1 - h) + (y1 - k)*(y1 - k) );\r\n    \r\n    return Circle(h,k,r);\r\n}\r\n\r\nVertex pointAlongLine2D(Vertex * a, Vertex * b, double tn)\r\n{\r\n    double nx = a->getX() + tn * (b->getX() - a->getX());\r\n    double ny = a->getY() + tn * (b->getY() - a->getY());\r\n    return Vertex(nx,ny);\r\n}\r\n\r\nbool onEdge(Vertex * a, Vertex * b, Vertex * pr) {\r\n    double minx = (a->getX() <= b->getX())? a->getX() : b->getX();\r\n    double maxx = (a->getX() >= b->getX())? a->getX() : b->getX();\r\n    \r\n    double miny = (a->getY() <= b->getY())? a->getY() : b->getY();\r\n    double maxy = (a->getY() >= b->getY())? a->getY() : b->getY();\r\n    \r\n    if (pr->getX() < minx)\r\n        return false;\r\n    else if (pr->getX() > maxx)\r\n        return false;\r\n    else if (pr->getY() < miny)\r\n        return false;\r\n    else if (pr->getY() > maxy)\r\n        return false;\r\n    else\r\n        return distance2Point(a,b,pr) < Constants::DIST_THRESH;\r\n}\r\n\r\ndouble distance2Point(Vertex * a, Vertex * b, Vertex * pr) {\r\n    double nx = b->getX() - a->getX();\r\n    double ny = b->getY() - a->getY();\r\n    \r\n    double nmag = sqrt(nx * nx + ny * ny);\r\n    \r\n    double px = pr->getX() - a->getX();\r\n    double py = pr->getY() - a->getY();\r\n    \r\n    //double pmag = sqrt(px * px + py * py);\r\n    \r\n    double dnp = nx * px + ny * py; // dot(n,p)\r\n    \r\n    double dnpx = nx * dnp / (nmag * nmag);\r\n    double dnpy = ny * dnp / (nmag * nmag);\r\n    \r\n    double perx = dnpx - px;\r\n    double pery = dnpy - py;\r\n    \r\n    return sqrt(perx * perx + pery * pery);\r\n}\r\n\r\n\r\nvoid DelaunayTriangulation::permute()\r\n{\r\n    std::srand(pts.len());\r\n    for (int i = 0; i < pts.len(); i++) {\r\n        rPerm[i] = i;\r\n    }\r\n    for (int i = pts.len() - 1; i >= 0; i--) {\r\n        int j = std::rand() % (i + 1);\r\n        int temp = rPerm[i];\r\n        rPerm[i] = rPerm[j];\r\n        rPerm[j] = temp;\r\n    }\r\n}\r\n\r\nvoid DelaunayTriangulation::init()\r\n{\r\n    omg1.set( 3.0 * M, 0.0);\r\n    omg2.set( 0.0, 3.0 * M);\r\n    omg3.set(-3.0 * M, -3.0 * M);\r\n    Triangle * itri = dag.get();\r\n    itri->setVertices(&omg1, &omg2, &omg3);\r\n}\r\n\r\nDelaunayTriangulation::DelaunayTriangulation() : M(0)\r\n{\r\n}\r\n\r\nDelaunayTriangulation::~DelaunayTriangulation()\r\n{\r\n}\r\n\r\nvoid DelaunayTriangulation::addPt(double x, double y, double z = 0.0)\r\n{\r\n\tVertex * v = pts.get();\r\n\tif (nullptr != v) {\r\n\t\tv->set(x, y, z);\r\n        \r\n        int max = (x >= y) ? x : y;\r\n        if (M <= max)\r\n            M = max;\r\n\t}\r\n\telse {\r\n\t\tfprintf(stdout,\"WARNING: Pool of points is empty!\\n\");\r\n\t}\r\n}\r\n\r\nVertex * DelaunayTriangulation::getPoint(int i)\r\n{\r\n    int rPerm_[10] = {2, 9, 7, 8, 4, 1, 3, 0, 6, 5};\r\n    return pts[rPerm_[i]];\r\n    //return pts[rPerm[i]];\r\n}\r\n\r\n///\r\n// ValidEdge(\u2206, pr,D(P))\r\n// Let \u2206adj be the triangle opposite to pr and adjacent to \u2206\r\n// if InCircle(\u2206adj , pr) then\r\n//     (* We have to make an edge flip *)\r\n//     flip(\u2206,\u2206adj, pr,D(P))\r\n//     Let \u2206\u2032 and \u2206\u2032\u2032 be the two new triangles, recursively legalize them\r\n//     ValidEdge(\u2206\u2032, pr,D(P))\r\n//     ValidEdge(\u2206\u2032\u2032, pr,D(P))\r\n// end if\r\n///\r\nvoid DelaunayTriangulation::validEdge(Triangle *a, Vertex *pr)\r\n{\r\n    TriangleList<Constants::adjListSize> copy;\r\n    \r\n    // Let \u2206adj be the triangle opposite to pr and adjacent to \u2206\r\n    dag.findAdjacentTriangle(a, pr, false);\r\n    copy.copy(dag.adjList);\r\n    if (copy.len > 1) {\r\n        \r\n        Vertex ** points = copy[1]->getVertices();\r\n        Circle c = circleForPoints(points[0], points[1], points[2]);\r\n        bool answer1 = c.pointInside(pr->getX(), pr->getY());\r\n        bool answer2 = inCircle(copy[1], pr);\r\n        \r\n        if (answer1 != answer2) {\r\n            fprintf(stdout, \"WARNING: inCircle produced wrong answer.\\n\");\r\n            fprintf(stdout, \"\\t%s\\n\", c.to_json().dump().c_str());\r\n            fprintf(stdout, \"\\t%s\\n\", a->to_json().dump().c_str());\r\n            fprintf(stdout, \"\\t%s\\n\", pr->to_json().dump().c_str());\r\n        }\r\n        \r\n        if (answer1) {\r\n            Triangle *n[2];\r\n            dag.flip(copy[0],copy[1],pr,n);\r\n            validEdge(n[0], pr);\r\n            validEdge(n[1], pr);\r\n        }\r\n    }\r\n}\r\n\r\nvoid DelaunayTriangulation::compute()\r\n{\r\n\tif (pts.len() < 3) {\r\n\t\tfprintf(stdout, \"WARNING: Not enough points added to Pool\\n\");\r\n\t\treturn;\r\n\t}\r\n\r\n\tinit();\r\n\tpermute();\r\n    \r\n    logPoints();\r\n    json j;\r\n    \r\n\tfor (int i = 0; i < pts.len(); i++) {\r\n        Vertex * p = getPoint(i);\r\n\r\n        logStep(i, p);\r\n        \r\n        dag.findTriangleContainingPoint(p);\r\n        if (2 == dag.adjList.len) { // on edge\r\n            dag.divideOnEdge(dag.adjList[0], dag.adjList[1], p);\r\n        } else { // on interior\r\n            dag.divideOnInterior(dag.adjList[0], p);\r\n        }\r\n        \r\n        \r\n        TriangleList<Constants::splitListSize> copy;\r\n        copy.copy(dag.splitList);\r\n        for (int i = 0; i < copy.len; i++) {\r\n            assert(true == copy[i]->isValid());\r\n            validEdge(copy[i], p);\r\n        }\r\n\t}\r\n    \r\n    //\r\n    // removing all triangles with the initial fake points added to DAG.\r\n    //\r\n    dag.removeTriangleContainingPoint(omg1);\r\n    dag.removeTriangleContainingPoint(omg2);\r\n    dag.removeTriangleContainingPoint(omg3);\r\n    json sol = dag.to_json();\r\n    std::ofstream log;\r\n    log.open (\"solution.json\");\r\n    log << sol.dump();\r\n    log.close();\r\n}\r\n\r\nvoid DelaunayTriangulation::logStep(int loop, Vertex * p)\r\n{\r\n    json j;\r\n    j[\"loop\"] = loop;\r\n    j[\"point\"] = p->to_json();\r\n    j[\"dag\"] = dag.len();\r\n\r\n    std::ofstream log;\r\n    log.open (str(boost::format(\"loop_%05d.json\") % dag.len()));\r\n    log << j.dump();\r\n    log.close();\r\n}\r\n\r\nvoid DelaunayTriangulation::logPoints()\r\n{\r\n    std::ofstream log;\r\n    log.open (\"points.json\");\r\n    json j;\r\n    j.push_back(omg1.to_json());\r\n    j.push_back(omg2.to_json());\r\n    j.push_back(omg3.to_json());\r\n    for (int i = 0; i < pts.len(); i++) {\r\n        j.push_back( pts[i]->to_json() );\r\n    }\r\n    log << j.dump();\r\n    log.close();\r\n}", "meta": {"hexsha": "2b2777a48d51b5b62324cc2b275bf89676eaf08a", "size": 9032, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tacmap/DelaunayTriangulation.cpp", "max_stars_repo_name": "parrishmyers/tacmap", "max_stars_repo_head_hexsha": "21c494723e482b3622362278144613819e21dafc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tacmap/DelaunayTriangulation.cpp", "max_issues_repo_name": "parrishmyers/tacmap", "max_issues_repo_head_hexsha": "21c494723e482b3622362278144613819e21dafc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tacmap/DelaunayTriangulation.cpp", "max_forks_repo_name": "parrishmyers/tacmap", "max_forks_repo_head_hexsha": "21c494723e482b3622362278144613819e21dafc", "max_forks_repo_licenses": ["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.9611940299, "max_line_length": 100, "alphanum_fraction": 0.4944641275, "num_tokens": 2904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6181683676052137}}
{"text": "//  Routines for computing p-values of occurrence overlaps using the hypergeometric distribution\n//\n\n#ifndef INCLUDED_overlap_probs_HH\n#define INCLUDED_overlap_probs_HH\n\n#include \"misc.hh\"\n#include <boost/math/distributions/hypergeometric.hpp>\n\ninline\nReal\nproduct_cdf( Real const x )\n{\n\treturn x - x*log(x);\n}\n\ninline\nReal\ncompute_overlap_pvalue(\n\tSize const overlap,\n\tSize const count1,\n\tSize const count2,\n\tSize const total\n)\n{\n\tusing namespace boost::math;\n\t// whats the smallest possible overlap? max( 0, count1+count2-total )\n\tif ( overlap==0 || count1==total || count2==total || count1+count2 >= total+overlap ) return 1.0;\n\thypergeometric_distribution<> hgd( count1, count2, total );\n\treturn cdf( complement( hgd, overlap-1 ) ); // need overlap-1 to be a valid overlap value!\n}\n\n\ninline // silly?\nReal\ncompute_overlap_pvalue_with_bias(\n\tbools const & occs1,\n\tbools const & occs2,\n\tReals const & subject_bias_factor\n)\n{\n\tReal pval(1.);\n\n\tSize table[2][2];\n\n\ttable[0][0] = table[0][1] = table[1][0] = table[1][1] = 0;\n\n\tSize const total( occs1.size() );\n\truntime_assert( occs2.size() == total );\n\truntime_assert( subject_bias_factor.size() == total );\n\n\tfor ( Size i=0; i< total; ++i ) { ++table[ occs1[i] ][ occs2[i] ]; }\n\n\tSize const overlap( table[1][1] ), total1( table[1][0] + table[1][1] ), total2( table[0][1] + table[1][1] );\n\n\tif ( overlap > 0 && total1 < total && total2 < total ) {\n\t\tReal bias(1.0);\n\t\tfor ( Size i=0; i< total; ++i ) {\n\t\t\tif ( occs1[i] && occs2[i] ) bias *= subject_bias_factor[i];\n\t\t}\n\t\tpval = min( 1.0, bias * compute_overlap_pvalue( overlap, total1, total2, total ) );\n\t}\n\n\treturn pval;\n}\n\n#endif\n", "meta": {"hexsha": "aca6833ece98ef334bacfb077e870bc46d8e2db7", "size": 1634, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/overlap_probs.hh", "max_stars_repo_name": "wangshun1121/pubtcrs", "max_stars_repo_head_hexsha": "779ceca2e19c03d5172010527da8d7bf9c8d5923", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/overlap_probs.hh", "max_issues_repo_name": "wangshun1121/pubtcrs", "max_issues_repo_head_hexsha": "779ceca2e19c03d5172010527da8d7bf9c8d5923", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/overlap_probs.hh", "max_forks_repo_name": "wangshun1121/pubtcrs", "max_forks_repo_head_hexsha": "779ceca2e19c03d5172010527da8d7bf9c8d5923", "max_forks_repo_licenses": ["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.0294117647, "max_line_length": 109, "alphanum_fraction": 0.6738066095, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.6688802471698041, "lm_q1q2_score": 0.6181402103648036}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/Numerik/numsoft/kaskade7/                        */\n/*                                                                           */\n/*  Copyright (C) 2002-2009 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef STRAINTENSORS_HH\n#define STRAINTENSORS_HH\n\n#include <utility>\n#include <boost/math/constants/constants.hpp>\n#include <dune/common/fmatrix.hh>\n\n#include \"fem/fixdune.hh\"\n#include \"fem/diffops/elasto.hh\"\n#include \"linalg/wrappedMatrix.hh\"\n\nnamespace Kaskade\n{\n  /// \\todo docme\n  template <class Scalar, int dim, bool byValue = true>\n  class CauchyGreenTensor\n  {\n  public:\n    typedef Dune::FieldMatrix<Scalar,dim,dim> Argument;\n    typedef Argument ReturnType;\n\n    explicit CauchyGreenTensor(Argument const& F_) : F(F_) {}\n\n    CauchyGreenTensor(CauchyGreenTensor const&) = default;\n    CauchyGreenTensor& operator=(CauchyGreenTensor const&) = default;\n\n    ReturnType d0() const { return transpose(F)*F; }\n\n    ReturnType d1(Argument const& dF1) const\n    {\n      Argument const& G = transpose(dF1)*F;\n      return G + transpose(G);\n    }\n\n    ReturnType d2(Argument const& dF1, Argument const& dF2) const\n    {\n      Argument const& G = transpose(dF1)*dF2;\n      return G + transpose(G);\n    }\n\n    ReturnType d3(Argument const&, Argument const&, Argument const&) const { return zero; }\n\n  private:\n    typename std::conditional<byValue,Argument,Argument const&>::type F;\n    Argument zero = Argument(0);\n  };\n\n  template <class Scalar,bool byValue>\n  class CauchyGreenTensor<Scalar,3,byValue>\n  {\n    static constexpr int dim = 3;\n  public:\n    typedef Dune::FieldMatrix<Scalar,dim,dim> Argument;\n    typedef Argument ReturnType;\n\n    explicit CauchyGreenTensor(Argument const& F_) : F(F_) {}\n\n    CauchyGreenTensor(CauchyGreenTensor const&) = default;\n    CauchyGreenTensor& operator=(CauchyGreenTensor const&) = default;\n\n    __attribute__((always_inline)) ReturnType d0() const\n    {\n      tmp = 0;\n      for(size_t i=0; i<dim; ++i)\n        for(size_t j=0; j<dim; ++j)\n          for(size_t k=0; k<dim; ++k)\n            tmp[i][j] += F[k][i]*F[k][j];\n\n      return tmp;// transpose(F)*F;\n    }\n\n    __attribute__((always_inline)) ReturnType d1(Argument const& dF1) const\n    {\n      tmp = 0;\n      for(size_t i=0; i<dim; ++i)\n        for(size_t j=0; j<dim; ++j)\n          for(size_t k=0; k<dim; ++k)\n            tmp[i][j] += F[k][i]*dF1[k][j] + dF1[k][i]*F[k][j];\n\n      return tmp;// G + transpose(G);\n    }\n\n    __attribute__((always_inline)) ReturnType d2(Argument const& dF1, Argument const& dF2) const\n    {\n      tmp = 0;\n      for(size_t i=0; i<dim; ++i)\n        for(size_t j=0; j<dim; ++j)\n          for(size_t k=0; k<dim; ++k)\n            tmp[i][j] += dF2[k][i]*dF1[k][j] + dF1[k][i]*dF2[k][j];\n      return tmp;\n    }\n\n    __attribute__((always_inline)) ReturnType d3(Argument const&, Argument const&, Argument const&) const { return zero; }\n\n  private:\n    typename std::conditional<byValue,Argument,Argument const&>::type F;\n    Argument zero = Argument(0);\n    mutable Argument tmp;\n  };\n\n//   /// \\todo docme\n//   template <class Scalar, int dim>\n//   class ElasticLinearizedGreenLagrangeTensor\n//   {\n//   public:\n//     ElasticLinearizedGreenLagrangeTensor() = default;\n// \n//     ElasticLinearizedGreenLagrangeTensor(Dune::FieldMatrix<Scalar,dim,dim> const& du, Dune::FieldMatrix<Scalar,dim,dim> const& inelasticStrain_)\n//       : elasticStrain(du), inelasticStrain(inelasticStrain_)\n//     {}\n// \n//     auto d0() const { return elasticStrain.d0() - inelasticStrain; }\n// \n//     template <class Arg>\n//     auto d1(Arg const& arg) const { return elasticStrain.d1(arg); }\n// \n//     template <class Arg>\n//     auto d2(Arg const& arg1, Arg const& arg2) const { return elasticStrain.d2(arg1,arg2); }\n// \n//     template <class Arg>\n//     auto d3(Arg const& arg1, Arg const& arg2, Arg const& arg3) const { return elasticStrain.d3(arg1,arg2,arg3); }\n// \n//   private:\n//     LinearizedGreenLagrangeTensor<Scalar,dim> elasticStrain;\n//     Dune::FieldMatrix<Scalar,dim,dim> inelasticStrain;\n//   };\n// \n\n  /// \\todo docme\n  template <class Scalar, int dim, class Tensor = WrappedMatrix<Scalar,dim> >\n  class Deviator\n  {\n  public:\n    typedef typename Tensor::Argument Argument;\n    typedef Dune::FieldMatrix<Scalar,dim,dim> ReturnType;\n\n    explicit Deviator(Tensor const& s_) : s(s_), I(unitMatrix<Scalar,dim>()) {}\n\n    ReturnType d0() const\n    {\n      return s.d0() - boost::math::constants::third<Scalar>() * trace(s.d0()) * I;\n    }\n\n    ReturnType d1(Argument const& dF) const\n    {\n      return s.d1(dF) - boost::math::constants::third<Scalar>() * trace(s.d1(dF)) * I;\n    }\n\n    ReturnType d2(Tensor const& dF1, Tensor const& dF2) const\n    {\n      return s.d2(dF1,dF2) - boost::math::constants::third<Scalar>() * trace(s.d2(dF1,dF2)) * I;\n    }\n\n    ReturnType d3(Tensor const& dF1, Tensor const& dF2, Tensor const& dF3) const\n    {\n      return s.d3(dF1,dF2,dF3) - boost::math::constants::third<Scalar>() * trace(s.d3s(dF1,dF2,dF3)) * I;\n    }\n\n  private:\n    Tensor s;\n    ReturnType zero = ReturnType(0), I;\n  };\n}\n\n#endif\n", "meta": {"hexsha": "f1539241c587c3b5b38c4e45bb309bcd05314fbc", "size": 5747, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/utilities/straintensors.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/utilities/straintensors.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:33.000Z", "max_forks_repo_path": "Kaskade/utilities/straintensors.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 32.2865168539, "max_line_length": 147, "alphanum_fraction": 0.5717765791, "num_tokens": 1622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6181173525428634}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  typedef Matrix<float,1,Dynamic> MatrixType;\ntypedef Map<MatrixType> MapType;\ntypedef Map<const MatrixType> MapTypeConst;   // a read-only map\nconst int n_dims = 5;\n  \nMatrixType m1(n_dims), m2(n_dims);\nm1.setRandom();\nm2.setRandom();\nfloat *p = &m2(0);  // get the address storing the data for m2\nMapType m2map(p,m2.size());   // m2map shares data with m2\nMapTypeConst m2mapconst(p,m2.size());  // a read-only accessor for m2\n\ncout << \"m1: \" << m1 << endl;\ncout << \"m2: \" << m2 << endl;\ncout << \"Squared euclidean distance: \" << (m1-m2).squaredNorm() << endl;\ncout << \"Squared euclidean distance, using map: \" <<\n  (m1-m2map).squaredNorm() << endl;\nm2map(3) = 7;   // this will change m2, since they share the same array\ncout << \"Updated m2: \" << m2 << endl;\ncout << \"m2 coefficient 2, constant accessor: \" << m2mapconst(2) << endl;\n/* m2mapconst(2) = 5; */   // this yields a compile-time error\n\n  return 0;\n}\n", "meta": {"hexsha": "115c3ff8ffe3b373ec4d7faf183dbd65efa41434", "size": 1047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tutorial_Map_using.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_Map_using.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_Map_using.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7941176471, "max_line_length": 73, "alphanum_fraction": 0.6638013372, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6180089197917226}}
{"text": "/* \n * File:   Activation.hpp\n * Author: heshan\n *\n * Created on June 7, 2018, 11:17 AM\n */\n\n#ifndef ACTIVATION_HPP\n#define ACTIVATION_HPP\n\n#include <cmath>\n#include <Eigen>\n\nclass Activation {\npublic:\n    Activation();\n    Activation(const Activation& orig);\n    virtual ~Activation();\n    \n    static double sigmoid(double);\n    static Eigen::MatrixXd sigmoid(Eigen::MatrixXd);\n    static double sigmoidDeriv(double);\n    static Eigen::MatrixXd sigmoidDeriv(Eigen::MatrixXd);\n    static Eigen::MatrixXd maxPoolDelta(double, double, Eigen::MatrixXd, int ,int);\n    \nprivate:\n\n};\n\n#endif /* ACTIVATION_HPP */\n\n", "meta": {"hexsha": "569e279acdc4f3d949d5f8f72aeacb4c983df351", "size": 610, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ProfilingModule/Profilers/LSTMCNnet/CNNet/Activation.hpp", "max_stars_repo_name": "pasindubawantha/sherlock-framework", "max_stars_repo_head_hexsha": "92d64fbc86256a61c6b00b7ca9eb0a17634c7446", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ProfilingModule/Profilers/LSTMCNnet/CNNet/Activation.hpp", "max_issues_repo_name": "pasindubawantha/sherlock-framework", "max_issues_repo_head_hexsha": "92d64fbc86256a61c6b00b7ca9eb0a17634c7446", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ProfilingModule/Profilers/LSTMCNnet/CNNet/Activation.hpp", "max_forks_repo_name": "pasindubawantha/sherlock-framework", "max_forks_repo_head_hexsha": "92d64fbc86256a61c6b00b7ca9eb0a17634c7446", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.0625, "max_line_length": 83, "alphanum_fraction": 0.6885245902, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.8006919925839875, "lm_q1q2_score": 0.6180089082477633}}
{"text": "/**\n * @ file avgvalboundary.cc\n * @ brief NPDE homework AvgValBoundary code\n * @ author Simon Meierhans, edited by Oliver Rietmann\n * @ date 11.03.2019\n * @ copyright Developed at ETH Zurich\n */\n\n#include \"avgvalboundary.h\"\n\n#include <lf/assemble/assemble.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/refinement/refinement.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseLU>\n#include <cmath>\n#include <memory>\n#include <utility>\n#include <vector>\n\nnamespace AvgValBoundary {\n\n/**\n * @brief computes H1 seminorm over the computational domain\n * @param dofh DofHandler of FEspace.\n *        u coefficient vector\n */\n/* SAM_LISTING_BEGIN_1 */\ndouble compH1seminorm(const lf::assemble::DofHandler &dofh,\n                      const Eigen::VectorXd &u) {\n  double result = 0.0;\n  //====================\n  \n  auto alpha = [] (Eigen::Vector2d x) { return 1.0; };\n  auto beta = [] (Eigen::Vector2d x) { return 0.0; };\n  auto gamma = [] (Eigen::Vector2d x) { return 0.0; };\n\n\n  Eigen::SparseMatrix<double> A = compGalerkinMatrix(dofh, alpha, gamma, beta);\n\n\n  result = std::sqrt( u.transpose()*A*u );\n\n  //====================\n  return result;\n}\n/* SAM_LISTING_END_1 */\n\n/**\n * @brief solves pde for some simple test problem with\n *        alpha = beta = gamma := 1.0 and load f := 1.0\n * @param dofh DofHandler of FEspace.\n */\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd solveTestProblem(const lf::assemble::DofHandler &dofh) {\n  // Obtain Galerkin matrix for alpha = beta = gamma := 1.0\n  auto const_one = [](Eigen::Vector2d x) -> double { return 1.0; };\n  auto A = compGalerkinMatrix(dofh, const_one, const_one, const_one);\n\n  // Set up load vector\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(dofh.Mesh());\n  lf::mesh::utils::MeshFunctionConstant mf_identity{1.0};\n  lf::uscalfe::ScalarLoadElementVectorProvider elvec_builder(fe_space,\n                                                             mf_identity);\n  Eigen::VectorXd phi(dofh.NumDofs());\n  phi.setZero();\n  AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n  // Solve system of linear equations\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(A);\n  Eigen::VectorXd mu = solver.solve(phi);\n\n  return mu;\n}\n/* SAM_LISTING_END_2 */\n\n/** @brief generate sequence of nested triangular meshes with L+1 levels */\n/* SAM_LISTING_BEGIN_3 */\nstd::shared_ptr<lf::refinement::MeshHierarchy> generateTestMeshSequence(\n    unsigned int L) {\n  auto mesh = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3, 1.0 / 3.0);\n  std::shared_ptr<lf::refinement::MeshHierarchy> meshes =\n      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(mesh, L);\n  return meshes;\n}\n/* SAM_LISTING_END_3 */\n\n/**\n * @brief Compute the boundary functional values for a sequence of L meshes\n * @param L The number of meshes in the sequence\n * @returns A vector of pairs containing the number of DOFs and value of the\n *\t    boundary functional for each level\n */\n/* SAM_LISTING_BEGIN_5 */\nstd::vector<std::pair<unsigned int, double>> approxBoundaryFunctionalValues(\n    unsigned int L) {\n  std::vector<std::pair<unsigned int, double>> result;\n  //====================\n  // Your code goes here\n  //====================\n  return result;\n}\n/* SAM_LISTING_END_5 */\n\n}  // namespace AvgValBoundary\n", "meta": {"hexsha": "ff83b71db892c0b3e7b308f11c18cfe74145c2c4", "size": 3358, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/AvgValBoundary/mysolution/avgvalboundary.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/AvgValBoundary/mysolution/avgvalboundary.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/AvgValBoundary/mysolution/avgvalboundary.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2522522523, "max_line_length": 79, "alphanum_fraction": 0.6703394878, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.8006919997179627, "lm_q1q2_score": 0.6180089053496567}}
{"text": "// Copyright (c) 2017 Evan S Weinberg\n// Test code for a real operator.\n\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <string>\n#include <sstream>\n#include <complex>\n#include <random>\n\n// Borrow dense matrix eigenvalue routines.\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n#include \"blas/generic_vector.h\"\n#include \"inverters/generic_cg.h\"\n#include \"inverters/generic_ca_cg.h\"\n#include \"inverters/generic_cheby_ca_cg.h\"\n\nusing namespace std; \n\n// Define a function that just has varying values along the diagonal.\n// Makes it easy to control the condition number.\nstruct scale_info {\n  int size;\n  double* scale_vec;\n  double lambda_min; // minimum eigenvalue\n  double lambda_max; // maximum eigenvalues\n  bool log_distribute; // randomly distribute evenly or logarithmically?\n\n  scale_info(int size, double lambda_min, double lambda_max, bool log_distribute, std::mt19937& generator)\n   : size(size), lambda_min(lambda_min), lambda_max(lambda_max), log_distribute(log_distribute) {\n\n    scale_vec = allocate_vector<double>(size);\n\n    // First: gurantee lambda_min and lambda_max exist.\n    scale_vec[0] = lambda_min;\n    scale_vec[1] = lambda_max;\n\n    if (log_distribute) {\n      double log_lambda_min = log(lambda_min);\n      double log_lambda_max = log(lambda_max);\n      random_uniform(scale_vec+2, size-2, generator, log_lambda_min, log_lambda_max);\n      exp_vector(scale_vec+2, size-2);\n    } else {\n      random_uniform(scale_vec+2, size-2, generator, lambda_min, lambda_max);\n    }\n  }\n\n  scale_info(int size, std::mt19937& generator)\n   : scale_info(size, 1., 10., true, generator) { ; }\n\n  ~scale_info() {\n    deallocate_vector(&scale_vec);\n  }\n\n\n};\n\n// Define a function that just has varying values along the diagonal.\nvoid scale_function(complex<double>* rhs, complex<double>* lhs, void* extra_data) {\n  scale_info& info = *((scale_info*)(extra_data));\n  cxtyz(info.scale_vec, lhs, rhs, info.size);\n}\n\n\n// Prepare vectors for various tests.\nvoid reset_vectors(complex<double>* rhs, complex<double>* lhs, complex<double>* check, complex<double>* rhs_backup, int size)\n{\n  zero_vector(lhs, size);\n  copy_vector(rhs, rhs_backup, size);\n  zero_vector(check, size);\n}\n\n\nint main(int argc, char** argv)\n{  \n    //double *lattice; // Holds the gauge field.\n  complex<double> *lhs, *rhs, *rhs_backup, *check; // For some Kinetic terms.\n  double explicit_resid = 0.0;\n  double bnorm = 0.0;\n  inversion_info invif;\n  std::mt19937 generator (1337u); // RNG, 1337u is the seed. \n\n  // Basic information about the linop\n  int size = 8192;\n  double lambda_min = 1e-6;\n  double lambda_max = 10;\n  \n  // Parameters related to solve.\n  double tol = 1e-8;\n  int max_iter = 1000;\n  \n  // Vectors. \n  lhs = allocate_vector<complex<double>>(size);\n  rhs = allocate_vector<complex<double>>(size);\n  rhs_backup = allocate_vector<complex<double>>(size);\n  check = allocate_vector<complex<double>>(size);\n\n  // Set up a default rhs.\n  random_uniform(rhs_backup, size, generator, 0.5, 1.5);\n  \n  // Zero out vectors, set rhs to standard backed up version\n  reset_vectors(rhs, lhs, check, rhs_backup, size);\n\n  // Set up operator.\n  scale_info scinf(size, lambda_min, lambda_max, false, generator);\n  \n  // Get norm for rhs.\n  bnorm = sqrt(norm2sq(rhs, size));\n\n  printf(\"Solving A [lhs] = [rhs] for lhs, using a random source. Operator has eigenvalues distributed between %e and %e \\n\\n\", lambda_min, lambda_max);\n\n  /****************\n  * NORMAL SOLVES *\n  ****************/\n  \n  // lhs = A^(-1) rhs\n  // Arguments:\n  // 1: lhs\n  // 2: rhs\n  // 3: size of vector\n  // 4: maximum iterations\n  // 5: residual\n  // 5a for gcr_restart: how often to restart.\n  // 5b for richardson, minres: overrelaxation parameter (can leave this out, assumes 1)\n  // 5c for richardson: how often to check the residual\n  // 6: function pointer\n  // 7: \"extra data\": \n  // 8: optional, verbosity information.\n\n  inversion_verbose_struct verb(VERB_DETAIL, \"Details: \");\n\n  /* CG */\n  reset_vectors(rhs, lhs, check, rhs_backup, size);\n  invif = minv_vector_cg(lhs, rhs, size, max_iter, tol, scale_function, &scinf, &verb);\n  if (invif.success == true)\n  {\n    printf(\"Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/bnorm);\n  }\n  else // failed, maybe.\n  {\n    printf(\"Potential error! Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/bnorm);\n  }\n  printf(\"Computing [check] = A [lhs] as a confirmation.\\n\");\n  // Check and make sure we get the right answer.\n  scale_function(check, lhs, &scinf);\n  explicit_resid = sqrt(diffnorm2sq(rhs, check, size))/bnorm; // sqrt(|rhs - check|^2)/bnorm\n  printf(\"[check] should equal [rhs]. The residual is %15.20e.\\n\\n\", explicit_resid);\n  \n\n  /* CA-CG */\n  for (int ca_s = 2; ca_s <= 30; ca_s++)\n  {\n    reset_vectors(rhs, lhs, check, rhs_backup, size);\n    invif = minv_vector_ca_cg(lhs, rhs, size, max_iter, tol, ca_s, scale_function, &scinf, &verb);\n    if (invif.success == true)\n    {\n      printf(\"Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/bnorm);\n    }\n    else // failed, maybe.\n    {\n      printf(\"Potential error! Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/bnorm);\n    }\n    printf(\"Computing [check] = A [lhs] as a confirmation.\\n\");\n    // Check and make sure we get the right answer.\n    scale_function(check, lhs, &scinf);\n    explicit_resid = sqrt(diffnorm2sq(rhs, check, size))/bnorm; // sqrt(|rhs - check|^2)/bnorm\n    printf(\"[check] should equal [rhs]. The residual is %15.20e.\\n\\n\", explicit_resid);\n\n\n    reset_vectors(rhs, lhs, check, rhs_backup, size);\n    // invif = minv_vector_cheby_ca_cg(lhs, rhs, size, max_iter, tol, 1.01*lambda_max, ca_s, scale_function, &scinf, &verb); // assume lambda_min = 0\n    invif = minv_vector_cheby_ca_cg(lhs, rhs, size, max_iter, tol, lambda_min, lambda_max, ca_s, scale_function, &scinf, &verb);\n    if (invif.success == true)\n    {\n      printf(\"Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/bnorm);\n    }\n    else // failed, maybe.\n    {\n      printf(\"Potential error! Algorithm %s took %d iterations to reach a tolerance of %.8e.\\n\", invif.name.c_str(), invif.iter, sqrt(invif.resSq)/bnorm);\n    }\n    printf(\"Computing [check] = A [lhs] as a confirmation.\\n\");\n    // Check and make sure we get the right answer.\n    scale_function(check, lhs, &scinf);\n    explicit_resid = sqrt(diffnorm2sq(rhs, check, size))/bnorm; // sqrt(|rhs - check|^2)/bnorm\n    printf(\"[check] should equal [rhs]. The residual is %15.20e.\\n\\n\", explicit_resid);\n  }\n  \n\n  //////////////\n  // CLEAN UP //\n  //////////////\n\n  // Free the lattice.\n  //delete[] lattice;\n  deallocate_vector(&lhs);\n  deallocate_vector(&rhs);\n  deallocate_vector(&rhs_backup);\n  deallocate_vector(&check);\n  return 0;\n}\n\n\n", "meta": {"hexsha": "66f656dd0b8f10800743f0de77a6905a0a3b3c3d", "size": 7017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/n09_cheby_ca_cg/test_cheby_ca_cg.cpp", "max_stars_repo_name": "weinbe2/quantum-linalg", "max_stars_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/n09_cheby_ca_cg/test_cheby_ca_cg.cpp", "max_issues_repo_name": "weinbe2/quantum-linalg", "max_issues_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/n09_cheby_ca_cg/test_cheby_ca_cg.cpp", "max_forks_repo_name": "weinbe2/quantum-linalg", "max_forks_repo_head_hexsha": "ce852dc459c8a5010f777f219c0dc6623ec918e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0631067961, "max_line_length": 154, "alphanum_fraction": 0.6769274619, "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6180006507897096}}
{"text": "/*******************************************************************************\n * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.\n * \n * Licensed under the MIT License (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://opensource.org/licenses/MIT\n * \n * Developers:\n *   Sebastian Niemann - Lead developer\n *   Daniel Kiechle - Unit testing\n ******************************************************************************/\n#include <Expected.hpp>\nusing armadilloJava::Expected;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <cmath>\nusing std::log;\nusing std::sqrt;\nusing std::pow;\n\n#include <fstream>\nusing std::ofstream;\n\n#include <streambuf>\nusing std::streambuf;\n\n#include <utility>\nusing std::pair;\n\n#include <armadillo>\nusing arma::Mat;\nusing arma::Col;\nusing arma::uword;\nusing arma::abs;\nusing arma::eps;\nusing arma::exp;\nusing arma::exp2;\nusing arma::exp10;\nusing arma::trunc_exp;\nusing arma::log;\nusing arma::log2;\nusing arma::log10;\nusing arma::trunc_log;\nusing arma::sqrt;\nusing arma::square;\nusing arma::floor;\nusing arma::ceil;\nusing arma::round;\nusing arma::sign;\nusing arma::sin;\nusing arma::asin;\nusing arma::sinh;\nusing arma::asinh;\nusing arma::cos;\nusing arma::acos;\nusing arma::cosh;\nusing arma::acosh;\nusing arma::tan;\nusing arma::atan;\nusing arma::tanh;\nusing arma::atanh;\nusing arma::cumsum;\nusing arma::hist;\nusing arma::sort;\nusing arma::sort_index;\nusing arma::stable_sort_index;\nusing arma::trans;\nusing arma::unique;\nusing arma::toeplitz;\nusing arma::circ_toeplitz;\nusing arma::accu;\nusing arma::min;\nusing arma::max;\nusing arma::prod;\nusing arma::sum;\nusing arma::mean;\nusing arma::median;\nusing arma::stddev;\nusing arma::var;\nusing arma::cor;\nusing arma::cov;\nusing arma::diagmat;\nusing arma::is_finite;\n\n#include <InputClass.hpp>\nusing armadilloJava::InputClass;\n\n#include <Input.hpp>\nusing armadilloJava::Input;\n\nnamespace armadilloJava {\n  class ExpectedGenColVec : public Expected {\n    public:\n      ExpectedGenColVec() {\n        cout << \"Compute ExpectedGenColVec(): \" << endl;\n\n        vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({\n          InputClass::GenColVec\n        });\n\n        for (vector<pair<string, void*>> input : inputs) {\n          _fileSuffix = \"\";\n\n          int n = 0;\n          for (pair<string, void*> value : input) {\n            switch (n) {\n              case 0:\n                _fileSuffix += value.first;\n                _genColVec = *static_cast<Col<double>*>(value.second);\n                break;\n            }\n            ++n;\n          }\n\n          cout << \"Using input: \" << _fileSuffix << endl;\n\n          expectedArmaAbs();\n          expectedArmaEps();\n          expectedArmaExp();\n          expectedArmaExp2();\n          expectedArmaExp10();\n          expectedArmaTrunc_exp();\n          expectedArmaLog();\n          expectedArmaLog2();\n          expectedArmaLog10();\n          expectedArmaTrunc_log();\n          expectedArmaSqrt();\n          expectedArmaSquare();\n          expectedArmaFloor();\n          expectedArmaCeil();\n          expectedArmaRound();\n          expectedArmaSign();\n          expectedArmaSin();\n          expectedArmaAsin();\n          expectedArmaSinh();\n          expectedArmaAsinh();\n          expectedArmaCos();\n          expectedArmaAcos();\n          expectedArmaCosh();\n          expectedArmaAcosh();\n          expectedArmaTan();\n          expectedArmaAtan();\n          expectedArmaTanh();\n          expectedArmaAtanh();\n          expectedArmaCumsum();\n          expectedArmaHist();\n          expectedArmaSort();\n          expectedArmaSort_index();\n          expectedArmaStable_sort_index();\n          expectedArmaTrans();\n          expectedArmaUnique();\n          expectedArmaNegate();\n          expectedArmaReciprocal();\n          expectedArmaToeplitz();\n          expectedArmaCirc_toeplitz();\n          expectedArmaAccu();\n          expectedArmaMin();\n          expectedArmaMax();\n          expectedArmaProd();\n          expectedArmaSum();\n          expectedArmaMean();\n          expectedArmaMedian();\n          expectedArmaStddev();\n          expectedArmaVar();\n          expectedArmaCor();\n          expectedArmaCov();\n          expectedArmaDiagmat();\n          expectedArmaIs_finite();\n          expectedMat();\n\t\t  expectedColVecSize();\n\t\t  expectedColVecT();\n\t\t  expectedColVecPrint();\n\t\t  expectedColVecRaw_print();\n\t\t  expectedColIs_finite();\n\t\t  expectedColMinA();\n\t\t  expectedColMaxA();\n\t\t  expectedColMinB();\n\t\t  expectedColMaxB();\n\t\t  expectedColIs_empty();\n\t\t\t\n\t\t\t\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n    protected:\n      Col<double> _genColVec;\n\n      void expectedArmaAbs() {\n        cout << \"- Compute expectedArmaAbs() ... \";\n        save<double>(\"Arma.abs\", abs(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaEps() {\n        cout << \"- Compute expectedArmaEps() ... \";\n        save<double>(\"Arma.eps\", eps(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaExp() {\n        cout << \"- Compute expectedArmaExp() ... \";\n        save<double>(\"Arma.exp\", exp(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaExp2() {\n        cout << \"- Compute expectedArmaExp2() ... \";\n        save<double>(\"Arma.exp2\", exp2(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaExp10() {\n        cout << \"- Compute expectedArmaExp10() ... \";\n        save<double>(\"Arma.exp10\", exp10(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrunc_exp() {\n        cout << \"- Compute expectedArmaTrunc_exp() ... \";\n        save<double>(\"Arma.trunc_exp\", trunc_exp(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaLog() {\n        cout << \"- Compute expectedArmaLog() ... \";\n        save<double>(\"Arma.log\", log(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaLog2() {\n        cout << \"- Compute expectedArmaLog2() ... \";\n        save<double>(\"Arma.log2\", log2(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaLog10() {\n        cout << \"- Compute expectedArmaLog10() ... \";\n        save<double>(\"Arma.log10\", log10(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrunc_log() {\n        cout << \"- Compute expectedArmaTrunc_log() ... \";\n        save<double>(\"Arma.trunc_log\", trunc_log(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSqrt() {\n        cout << \"- Compute expectedArmaSqrt() ... \";\n        save<double>(\"Arma.sqrt\", sqrt(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSquare() {\n        cout << \"- Compute expectedArmaSquare() ... \";\n        save<double>(\"Arma.square\", square(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaFloor() {\n        cout << \"- Compute expectedArmaFloor() ... \";\n        save<double>(\"Arma.floor\", floor(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCeil() {\n        cout << \"- Compute expectedArmaCeil() ... \";\n        save<double>(\"Arma.ceil\", ceil(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaRound() {\n        cout << \"- Compute expectedArmaRound() ... \";\n        save<double>(\"Arma.round\", round(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSign() {\n        cout << \"- Compute expectedArmaSign() ... \";\n        save<double>(\"Arma.sign\", sign(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSin() {\n        cout << \"- Compute expectedArmaSin() ... \";\n        save<double>(\"Arma.sin\", sin(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAsin() {\n        cout << \"- Compute expectedArmaAsin() ... \";\n        save<double>(\"Arma.asin\", asin(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSinh() {\n        cout << \"- Compute expectedArmaSinh() ... \";\n        save<double>(\"Arma.sinh\", sinh(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAsinh() {\n        cout << \"- Compute expectedArmaAsinh() ... \";\n        save<double>(\"Arma.asinh\", asinh(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCos() {\n        cout << \"- Compute expectedArmaCos() ... \";\n        save<double>(\"Arma.cos\", cos(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAcos() {\n        cout << \"- Compute expectedArmaAcos() ... \";\n        save<double>(\"Arma.acos\", acos(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCosh() {\n        cout << \"- Compute expectedArmaCosh() ... \";\n        save<double>(\"Arma.cosh\", cosh(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAcosh() {\n        cout << \"- Compute expectedArmaAcosh() ... \";\n\n        /*\n         * acosh behaves buggy on some systems, with acosh(inf) = nan instead of inf\n         */\n        //save<double>(\"Arma.acosh\", acosh(_genColVec));\n\n        Mat<double> expected = _genColVec;\n        expected.transform([](double value) {\n          return log(value + sqrt(pow(value, 2) - 1));\n        });\n        save<double>(\"Arma.acosh\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTan() {\n        cout << \"- Compute expectedArmaTan() ... \";\n        save<double>(\"Arma.tan\", tan(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAtan() {\n        cout << \"- Compute expectedArmaAtan() ... \";\n        save<double>(\"Arma.atan\", atan(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTanh() {\n        cout << \"- Compute expectedArmaTanh() ... \";\n        save<double>(\"Arma.tanh\", tanh(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAtanh() {\n        cout << \"- Compute expectedArmaAtanh() ... \";\n        save<double>(\"Arma.atanh\", atanh(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCumsum() {\n        cout << \"- Compute expectedArmaCumsum() ... \";\n        save<double>(\"Arma.cumsum\", cumsum(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaHist() {\n        cout << \"- Compute expectedArmaHist() ... \";\n        save<uword>(\"Arma.hist\", hist(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSort() {\n        if(!_genColVec.is_finite()) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaSort() ... \";\n        save<double>(\"Arma.sort\", sort(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSort_index() {\n        if(!_genColVec.is_finite()) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaSort_index() ... \";\n        save<uword>(\"Arma.sort_index\", sort_index(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaStable_sort_index() {\n        if(!_genColVec.is_finite()) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaStable_sort_index() ... \";\n        save<uword>(\"Arma.stable_sort_index\", stable_sort_index(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrans() {\n        cout << \"- Compute expectedArmaTrans() ... \";\n        save<double>(\"Arma.trans\", trans(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaUnique() {\n        cout << \"- Compute expectedArmaUnique() ... \";\n        save<double>(\"Arma.unique\", unique(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaNegate() {\n        cout << \"- Compute expectedArmaNegate() ... \";\n        save<double>(\"Arma.negate\", -_genColVec);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaReciprocal() {\n        cout << \"- Compute expectedArmaReciprocal() ... \";\n        save<double>(\"Arma.reciprocal\", 1/_genColVec);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaToeplitz() {\n        cout << \"- Compute expectedArmaToeplitz() ... \";\n        save<double>(\"Arma.toeplitz\", toeplitz(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCirc_toeplitz() {\n        cout << \"- Compute expectedArmaCirc_toeplitz() ... \";\n        save<double>(\"Arma.circ_toeplitz\", circ_toeplitz(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAccu() {\n        cout << \"- Compute expectedArmaAccu() ... \";\n        save<double>(\"Arma.accu\", Mat<double>({accu(_genColVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMin() {\n        cout << \"- Compute expectedArmaMin() ... \";\n        save<double>(\"Arma.min\", Mat<double>({min(_genColVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMax() {\n        cout << \"- Compute expectedArmaMax() ... \";\n        save<double>(\"Arma.max\", Mat<double>({max(_genColVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaProd() {\n        cout << \"- Compute expectedArmaProd() ... \";\n        save<double>(\"Arma.prod\", Mat<double>({prod(_genColVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSum() {\n        cout << \"- Compute expectedArmaSum() ... \";\n        save<double>(\"Arma.sum\", Mat<double>({sum(_genColVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMean() {\n        cout << \"- Compute expectedArmaMean() ... \";\n        save<double>(\"Arma.mean\", Mat<double>({mean(_genColVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMedian() {\n        cout << \"- Compute expectedArmaMedian() ... \";\n        save<double>(\"Arma.median\", Mat<double>({median(_genColVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaStddev() {\n        cout << \"- Compute expectedArmaStddev() ... \";\n        save<double>(\"Arma.stddev\", Mat<double>({stddev(_genColVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaVar() {\n        cout << \"- Compute expectedArmaVar() ... \";\n        save<double>(\"Arma.var\", Mat<double>({var(_genColVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCor() {\n        cout << \"- Compute expectedArmaCor() ... \";\n        save<double>(\"Arma.cor\", Mat<double>({cor(_genColVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCov() {\n        cout << \"- Compute expectedArmaCov() ... \";\n        save<double>(\"Arma.cov\", Mat<double>({cov(_genColVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaDiagmat() {\n        cout << \"- Compute expectedArmaDiagmat() ... \";\n        save<double>(\"Arma.diagmat\", diagmat(_genColVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaIs_finite() {\n        cout << \"- Compute expectedArmaIs_finite() ... \";\n\n        if(is_finite(_genColVec)) {\n          save<double>(\"Arma.is_finite\", Mat<double>({1.0}));\n        } else {\n          save<double>(\"Arma.is_finite\", Mat<double>({0.0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMat() {\n        cout << \"- Compute expectedMat() ... \";\n        save<double>(\"Mat\", _genColVec);\n        cout << \"done.\" << endl;\n      }\n\t  \n\t  void expectedColVecSize() {\n\t\t  cout << \"- Compute expectedColVecSize() ... \";\n\t\t  save<double>(\"Col.size\", Mat<double>({static_cast<double>(_genColVec.size())}));\n\t\t  cout << \"done.\" << endl;\n      }\n\t  \n\t  void expectedColVecT() {\n\t\t  cout << \"- Compute expectedColVecT() ... \";\n\t\t  save<double>(\"Col.t\", _genColVec.t());\n\t\t  cout << \"done.\" << endl;\n      }\n\t  \n\t  void expectedColVecPrint() {\n\t\t  cout << \"- Compute expectedColVecPrint() ... \";\n\t\t  \n\t\t  ofstream expected(_filepath + \"Col.print(\" + _fileSuffix + \").txt\");\n\t\t  streambuf* previousBuffer = cout.rdbuf(expected.rdbuf());\n\t\t  \n\t\t  _genColVec.print();\n\t\t  \n\t\t  cout.rdbuf(previousBuffer);\n\t\t  \n\t\t  cout << \"done.\" << endl;\n      }\n\t  \n\t  void expectedColVecRaw_print() {\n\t\t  cout << \"- Compute expectedColVecRaw_print() ... \";\n\t\t  \n\t\t  ofstream expected(_filepath + \"Col.raw_print(\" + _fileSuffix + \").txt\");\n\t\t  streambuf* previousBuffer = cout.rdbuf(expected.rdbuf());\n\t\t  \n\t\t  _genColVec.raw_print();\n\t\t  \n\t\t  cout.rdbuf(previousBuffer);\n\t\t  \n\t\t  cout << \"done.\" << endl;\n      }\n\n      void expectedColIs_finite() {\n        cout << \"- Compute expectedColIs_finite() ... \";\n\n        if(_genColVec.is_finite()) {\n          save<double>(\"Col.is_finite\", Col<double>({1}));\n        } else {\n          save<double>(\"Col.is_finite\", Col<double>({0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColMinA() {\n        cout << \"- Compute expectedColMinA() ... \";\n        double value;\n        value = _genColVec.min();\n        save<double>(\"Col.minA\", Col<double>({value}));\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColMaxA() {\n        cout << \"- Compute expectedColMaxA() ... \";\n        double value;\n        value = _genColVec.max();\n        save<double>(\"Col.maxA\", Col<double>({value}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColMinB() {\n        cout << \"- Compute expectedColMinB() ... \";\n        uword value;\n        _genColVec.min(value);\n        save<double>(\"Col.minB\", Col<double>({static_cast<double>(value)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColMaxB() {\n        cout << \"- Compute expectedColMaxB() ... \";\n        uword value;\n        _genColVec.max(value);\n        save<double>(\"Col.maxB\", Col<double>({static_cast<double>(value)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedColIs_empty() {\n        cout << \"- Compute expectedColIs_empty() ... \";\n\n        if(_genColVec.is_empty()) {\n          save<double>(\"Col.is_empty\", Col<double>({1}));\n        } else {\n          save<double>(\"Col.is_empty\", Col<double>({0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n\n  };\n}\n", "meta": {"hexsha": "ecabf7020896c17e2f7289aae78adeabdc60485a", "size": 17966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/src/ExpectedGenColVec.cpp", "max_stars_repo_name": "SebastianNiemann/ArmadilloJava", "max_stars_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T02:13:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-15T07:43:53.000Z", "max_issues_repo_path": "src/test/cpp/src/ExpectedGenColVec.cpp", "max_issues_repo_name": "sebiniemann/ArmadilloJava", "max_issues_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-10-20T21:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T21:53:47.000Z", "max_forks_repo_path": "src/test/cpp/src/ExpectedGenColVec.cpp", "max_forks_repo_name": "sebiniemann/ArmadilloJava", "max_forks_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T17:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:45:14.000Z", "avg_line_length": 28.071875, "max_line_length": 84, "alphanum_fraction": 0.5383502171, "num_tokens": 4508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825635346563, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6180006420500126}}
{"text": "// Albert Huang <albert@csail.mit.edu>\n//\n// Implementation of \n//\n//    Berthold K. P. Horn, \n//    \"Closed-form solution of absolute orientation using unit quaternions\",\n//    Journal of the Optical society of America A, Vol. 4, April 1987\n\n#ifndef __absolute_orientation_horn__\n#define __absolute_orientation_horn__\n\n#include <assert.h>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n\n/**\n * absolute_orientation_horn:\n * @P1: a matrix of dimension [3 x num_points]\n * @P2: a matrix of dimension [3 x num_points]\n * @result: output parameter\n *\n * Given two point sets P1 and P2, with each point p1_i in set P1 matched with\n * a point p2_i in P2, compute the rigid body transformation (isometry) M that\n * minimizes\n *\n * \\sum ||p2_i - M p1_i||\n *\n * returns: 0 on success, -1 on failure\n */\ntemplate <typename DerivedA, typename DerivedB>\nint absolute_orientation_horn(const Eigen::MatrixBase<DerivedA>& P1, \n        const Eigen::MatrixBase<DerivedB>& P2,\n        Eigen::Isometry3d* result)\n{\n    int num_points = P1.cols();\n    assert(P1.cols() == P2.cols());\n    assert(P1.rows() == 3 && P2.rows() == 3);\n    if(num_points < 3)\n        return -1;\n\n    // compute centroids of point sets\n    Eigen::Vector3d P1_centroid = P1.rowwise().sum() / num_points;\n    Eigen::Vector3d P2_centroid = P2.rowwise().sum() / num_points;\n\n    Eigen::MatrixXd R1 = P1;\n    R1.colwise() -= P1_centroid;\n    Eigen::MatrixXd R2 = P2;\n    R2.colwise() -= P2_centroid;\n\n    // compute matrix M\n    double Sxx = R1.row(0).dot(R2.row(0));\n    double Sxy = R1.row(0).dot(R2.row(1));\n    double Sxz = R1.row(0).dot(R2.row(2));\n    double Syx = R1.row(1).dot(R2.row(0));\n    double Syy = R1.row(1).dot(R2.row(1));\n    double Syz = R1.row(1).dot(R2.row(2));\n    double Szx = R1.row(2).dot(R2.row(0));\n    double Szy = R1.row(2).dot(R2.row(1));\n    double Szz = R1.row(2).dot(R2.row(2));\n\n    double A00 = Sxx + Syy + Szz;\n    double A01 = Syz - Szy;\n    double A02 = Szx - Sxz;\n    double A03 = Sxy - Syx;\n    double A11 = Sxx - Syy - Szz;\n    double A12 = Sxy + Syx;\n    double A13 = Szx + Sxz;\n    double A22 = -Sxx + Syy - Szz;\n    double A23 = Syz + Szy;\n    double A33 = -Sxx - Syy + Szz;\n\n    // prepare matrix for eigen analysis\n    Eigen::Matrix4d N;\n    N << A00, A01, A02, A03,\n        A01, A11, A12, A13,\n        A02, A12, A22, A23,\n        A03, A13, A23, A33;\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix4d> eigensolver(N);\n\n    // rotation quaternion is the eigenvector with greatest eigenvalue\n    Eigen::Vector4d eigvals = eigensolver.eigenvalues();\n    int max_eigen_ind = 0;\n    double max_eigen_val = eigvals(0);\n    for(int i=1; i<4; i++) {\n        if(eigvals(i) > max_eigen_val) {\n            max_eigen_val = eigvals(i);\n            max_eigen_ind = i;\n        }\n    }\n    Eigen::Vector4d quat = eigensolver.eigenvectors().col(max_eigen_ind);\n    Eigen::Quaterniond rotation(quat[0], quat[1], quat[2], quat[3]);\n \n    // now compute the resulting isometry\n    result->setIdentity();\n    result->translate(P2_centroid - rotation * P1_centroid);\n    result->rotate(rotation);\n\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "4b528dcbbcd5cac0b6a8ad420294a129ad9a9eca", "size": 3106, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "navigation_layer/fovis/libfovis/libfovis/libfovis/absolute_orientation_horn.hpp", "max_stars_repo_name": "kartavya2000/Anahita", "max_stars_repo_head_hexsha": "9afbf6c238658188df7d0d97b2fec3bd48028c03", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-03-21T15:18:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-28T07:52:10.000Z", "max_issues_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/absolute_orientation_horn.hpp", "max_issues_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_issues_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-10-03T12:14:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-07T09:33:14.000Z", "max_forks_repo_path": "perception/rwth_people_tracker/rwth_visual_odometry/3rd_party/fovis/libfovis/absolute_orientation_horn.hpp", "max_forks_repo_name": "VisualComputingInstitute/CROWDBOT_perception", "max_forks_repo_head_hexsha": "df98f3f658c39fb3fa4ac0456f1214f7918009f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2018-09-09T12:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-03T09:28:19.000Z", "avg_line_length": 30.4509803922, "max_line_length": 78, "alphanum_fraction": 0.6310367032, "num_tokens": 996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6180006419253301}}
{"text": "/*\n * Copyright Nick Thompson, 2021\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/math/tools/config.hpp>\n#ifndef BOOST_MATH_NO_THREAD_LOCAL_WITH_NON_TRIVIAL_TYPES\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <random>\n#include <array>\n#include <boost/core/demangle.hpp>\n#include <boost/math/interpolators/bezier_polynomial.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing boost::math::interpolators::bezier_polynomial;\n\ntemplate<typename Real>\nvoid test_linear()\n{\n    std::vector<std::array<Real, 2>> control_points(2);\n    control_points[0] = {0.0, 0.0};\n    control_points[1] = {1.0, 1.0};\n    auto control_points_copy = control_points;\n    auto bp = bezier_polynomial(std::move(control_points_copy));\n\n    // P(0) = P_0:\n    CHECK_ULP_CLOSE(control_points[0][0], bp(0)[0], 3);\n    CHECK_ULP_CLOSE(control_points[0][1], bp(0)[1], 3);\n\n    // P(1) = P_n:\n    CHECK_ULP_CLOSE(control_points[1][0], bp(1)[0], 3);\n    CHECK_ULP_CLOSE(control_points[1][1], bp(1)[1], 3);\n\n    for (Real t = Real(1)/32; t < 1; t += Real(1)/32) {\n        Real expected0 = (1-t)*control_points[0][0] + t*control_points[1][0];\n        CHECK_ULP_CLOSE(expected0, bp(t)[0], 3);\n    }\n\n    // P(1) = P_n:\n    std::array<Real, 2> endpoint{1,2};\n    bp.edit_control_point(endpoint, 1);\n    CHECK_ULP_CLOSE(endpoint[0], bp(1)[0], 3);\n    CHECK_ULP_CLOSE(endpoint[1], bp(1)[1], 3);\n\n}\n\ntemplate<typename Real>\nvoid test_quadratic()\n{\n    std::vector<std::array<Real, 2>> control_points(3);\n    control_points[0] = {0.0, 0.0};\n    control_points[1] = {1.0, 1.0};\n    control_points[2] = {2.0, 2.0};\n    auto control_points_copy = control_points;\n    auto bp = bezier_polynomial(std::move(control_points_copy));\n\n    // P(0) = P_0:\n    auto computed_point = bp(0);\n    CHECK_ULP_CLOSE(control_points[0][0], computed_point[0], 3);\n    CHECK_ULP_CLOSE(control_points[0][1], computed_point[1], 3);\n    auto computed_dp = bp.prime(0);\n    CHECK_ULP_CLOSE(2*(control_points[1][0] - control_points[0][0]), computed_dp[0], 3);\n    CHECK_ULP_CLOSE(2*(control_points[1][1] - control_points[0][1]), computed_dp[1], 3);\n\n    // P(1) = P_n:\n    computed_point = bp(1);\n    CHECK_ULP_CLOSE(control_points[2][0], computed_point[0], 3);\n    CHECK_ULP_CLOSE(control_points[2][1], computed_point[1], 3);\n}\n\n// All points on a Bezier polynomial fall into the convex hull of the control polygon.\ntemplate<typename Real>\nvoid test_convex_hull()\n{\n    std::vector<std::array<Real, 2>> control_points(4);\n    control_points[0] = {0.0, 0.0};\n    control_points[1] = {0.0, 1.0};\n    control_points[2] = {1.0, 1.0};\n    control_points[3] = {1.0, 0.0};\n    auto bp = bezier_polynomial(std::move(control_points));\n\n    for (Real t = 0; t <= 1; t += Real(1)/32) {\n        auto p = bp(t);\n        CHECK_LE(p[0], Real(1));\n        CHECK_LE(Real(0), p[0]);\n        CHECK_LE(p[1], Real(1));\n        CHECK_LE(Real(0), p[1]);\n    }\n}\n\n// Reversal Symmetry: If q(t) is the Bezier polynomial which consumes the control points in reversed order from p(t),\n// then p(t) = q(1-t).\ntemplate<typename Real>\nvoid test_reversal_symmetry()\n{\n    std::vector<std::array<Real, 3>> control_points(10);\n    std::uniform_real_distribution<Real> dis(-1,1);\n    std::mt19937_64 gen;\n    for (size_t i = 0; i < control_points.size(); ++i) {\n        for (size_t j = 0; j < 3; ++j) {\n            control_points[i][j] = dis(gen);\n        }\n    }\n\n    auto control_points_copy = control_points;\n    auto bp0 = bezier_polynomial(std::move(control_points_copy));\n\n    control_points_copy = control_points;\n    std::reverse(control_points_copy.begin(), control_points_copy.end());\n    auto bp1 = bezier_polynomial(std::move(control_points_copy));\n    auto P0 = bp0(Real(0));\n    CHECK_ULP_CLOSE(control_points[0][0], P0[0], 3);\n    CHECK_ULP_CLOSE(control_points[0][1], P0[1], 3);\n    CHECK_ULP_CLOSE(control_points[0][2], P0[2], 3);\n    auto P1 = bp0(Real(1));\n    CHECK_ULP_CLOSE(control_points.back()[0], P1[0], 3);\n    CHECK_ULP_CLOSE(control_points.back()[1], P1[1], 3);\n    CHECK_ULP_CLOSE(control_points.back()[2], P1[2], 3);\n\n    P0 = bp1(Real(1));\n    CHECK_ULP_CLOSE(control_points[0][0], P0[0], 3);\n    CHECK_ULP_CLOSE(control_points[0][1], P0[1], 3);\n    CHECK_ULP_CLOSE(control_points[0][2], P0[2], 3);\n\n    P1 = bp1(Real(0));\n    CHECK_ULP_CLOSE(control_points.back()[0], P1[0], 3);\n    CHECK_ULP_CLOSE(control_points.back()[1], P1[1], 3);\n    CHECK_ULP_CLOSE(control_points.back()[2], P1[2], 3);\n\n    for (Real t = 0; t <= 1; t += 1.0) {\n        auto P0 = bp0(t);\n        auto P1 = bp1(1.0-t);\n        if (!CHECK_ULP_CLOSE(P0[0], P1[0], 3)) {\n            std::cerr << \"  Error at t = \" << t << \"\\n\";\n        }\n        CHECK_ULP_CLOSE(P0[1], P1[1], 3);\n        CHECK_ULP_CLOSE(P0[2], P1[2], 3);\n    }\n}\n\n// Linear precision: If all control points lie *equidistantly* on a line, then the Bezier curve falls on a line.\n// See Bezier and B-spline techniques, Section 2.8, Remark 8.\ntemplate<typename Real>\nvoid test_linear_precision()\n{\n    std::vector<std::array<Real, 3>> control_points(10);\n    std::array<Real, 3> P0 = {1,1,1};\n    std::array<Real, 3> Pf = {2,2,2};\n    control_points[0] = P0;\n    control_points[9] = Pf;\n    for (size_t i = 1; i < 9; ++i) {\n        Real t = Real(i)/(control_points.size()-1);\n        control_points[i][0] = (1-t)*P0[0] + t*Pf[0];\n        control_points[i][1] = (1-t)*P0[1] + t*Pf[1];\n        control_points[i][2] = (1-t)*P0[2] + t*Pf[2];\n    }\n\n    auto bp = bezier_polynomial(std::move(control_points));\n    for (Real t = 0; t < 1; t += Real(1)/32) {\n        std::array<Real, 3> P;\n        P[0] = (1-t)*P0[0] + t*Pf[0];\n        P[1] = (1-t)*P0[1] + t*Pf[1];\n        P[2] = (1-t)*P0[2] + t*Pf[2];\n\n        auto computed = bp(t);\n        CHECK_ULP_CLOSE(P[0], computed[0], 3);\n        CHECK_ULP_CLOSE(P[1], computed[1], 3);\n        CHECK_ULP_CLOSE(P[2], computed[2], 3);\n\n        std::array<Real, 3> dP;\n        dP[0] = Pf[0] - P0[0];\n        dP[1] = Pf[1] - P0[1];\n        dP[2] = Pf[2] - P0[2];\n        auto dpComputed = bp.prime(t);\n        CHECK_ULP_CLOSE(dP[0], dpComputed[0], 5);\n    }\n}\n\nint main()\n{\n    test_linear<float>();\n    test_linear<double>();\n    test_quadratic<float>();\n    test_quadratic<double>();\n    test_convex_hull<float>();\n    test_convex_hull<double>();\n    test_linear_precision<float>();\n    test_linear_precision<double>();\n    test_reversal_symmetry<float>();\n    test_reversal_symmetry<double>();\n#ifdef BOOST_HAS_FLOAT128\n    test_linear<float128>();\n    test_quadratic<float128>();\n    test_convex_hull<float128>();\n#endif\n    return boost::math::test::report_errors();\n}\n\n#else\nint main() {\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "4e7a11748cd0a1724331bc1bb008962a4131ddf9", "size": 6864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/bezier_polynomial_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/bezier_polynomial_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/bezier_polynomial_test.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 32.6857142857, "max_line_length": 117, "alphanum_fraction": 0.6219405594, "num_tokens": 2241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.841825655188238, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.61800064192533}}
{"text": "// Copyright  (C)  2008  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n\n// Version: 1.0\n// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// URL: http://www.orocos.org/kdl\n\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// Lesser General Public License for more details.\n\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n\n//implementation of svd according to (Maciejewski and Klein,1989)\n//and (Braun, Ulrey, Maciejewski and Siegel,2002)\n\n/**\n * \\file svd_eigen_Macie.hpp\n * provides Maciejewski's implementation for SVD.\n */\n\n#ifndef SVD_EIGEN_MACIE\n#define SVD_EIGEN_MACIE\n\n#include <Eigen/Core>\n\n\nnamespace KDL\n{\n\n\t/**\n\t * svd_eigen_Macie provides Maciejewski implementation for SVD.\n\t *\n\t * computes the singular value decomposition of a matrix A, such that\n\t * A=U*Sm*V\n\t *\n\t * (Maciejewski and Klein,1989) and (Braun, Ulrey, Maciejewski and Siegel,2002)\n\t *\n\t * \\param A [INPUT] is an \\f$m \\times n\\f$-matrix, where \\f$ m \\geq n \\f$.\n\t * \\param S [OUTPUT] is an \\f$n\\f$-vector, representing the diagonal elements of the diagonal matrix Sm.\n\t * \\param U [INPUT/OUTPUT] is an \\f$m \\times m\\f$ orthonormal matrix.\n\t * \\param V [INPUT/OUTPUT] is an \\f$n \\times n\\f$ orthonormal matrix.\n\t * \\param B [TEMPORARY] is an \\f$m \\times n\\f$ matrix used for temporary storage.\n\t * \\param tempi [TEMPORARY] is an \\f$m\\f$ vector used for temporary storage.\n\t * \\param threshold [INPUT] Threshold to determine orthogonality.\n\t * \\param toggle [INPUT] toggle this boolean variable on each call of this routine.\n\t * \\return number of sweeps.\n\t */\n    int svd_eigen_Macie(const Eigen::MatrixXd& A,Eigen::MatrixXd& U,Eigen::VectorXd& S, Eigen::MatrixXd& V,\n                        Eigen::MatrixXd& B, Eigen::VectorXd& tempi,\n                        double threshold,bool toggle);\n\n\n}\n#endif\n", "meta": {"hexsha": "2f6263de653f38b004495d147342e3106d514397", "size": 2468, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/orocos_kinematics_dynamics/orocos_kdl/src/utilities/svd_eigen_Macie.hpp", "max_stars_repo_name": "matchRos/simulation_multirobots", "max_stars_repo_head_hexsha": "286c5add84d521ad371b2c8961dea872c34e7da2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-06T15:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:21:40.000Z", "max_issues_repo_path": "src/orocos_kinematics_dynamics/orocos_kdl/src/utilities/svd_eigen_Macie.hpp", "max_issues_repo_name": "matchRos/simulation_multirobots", "max_issues_repo_head_hexsha": "286c5add84d521ad371b2c8961dea872c34e7da2", "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/orocos_kinematics_dynamics/orocos_kdl/src/utilities/svd_eigen_Macie.hpp", "max_forks_repo_name": "matchRos/simulation_multirobots", "max_forks_repo_head_hexsha": "286c5add84d521ad371b2c8961dea872c34e7da2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-04T09:16:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T09:16:28.000Z", "avg_line_length": 37.9692307692, "max_line_length": 107, "alphanum_fraction": 0.7098865478, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6180006400662973}}
{"text": "/* \n// Copyright 2018 University of Liege\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n//     http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Authors:\n// - Adrien Crovato\n*/\n\n//// Body to body/field potential influence coefficient computation\n// Compute doublet and source potential influence coefficient between 2 surface panels\n// Katz and Plotkin (2001), Low-Speed Aerodynamics. Program 12\n//\n// Inputs:\n// - wakeFlag: defines if wake or body panel\n// - idTgt: index of target panel\n// - idSrc: index of influencing panel\n// - x, y, z: coordinates of target panel center in panel axis\n// - x1, y1, x2, y2, x3, y3, x4, y4: coordinates of influencing panel vertices in panel axis\n//\n// Output:\n// - coeff: array of AIC ([0] = mu, [1] = tau)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <array>\n#include \"infcB.h\"\n\n#define PI 3.14159\n\nusing namespace std;\nusing namespace Eigen;\n\narray<double,2> infcB(bool wakeFlag,int idTgt, int idSrc, double x, double y, double z,\n                      double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {\n\n    // Temporary\n    RowVector4d xV, yV; // Local vertices\n    RowVector4d d, r, e, h, F, G; // coefficients\n    double mu = 0, tau = 0; // AIC\n    array<double,2> coeff;\n\n    xV(0) = x1; xV(1) = x2; xV(2) = x3; xV(3) = x4;\n    yV(0) = y1; yV(1) = y2; yV(2) = y3; yV(3) = y4;\n\n    //// Wake panels\n    if (wakeFlag) {\n\n        // Coefficients\n        for (int i = 1; i <= 4; ++i) {\n            int j = i%4 + 1;\n\n            r(i-1) = sqrt((x - xV(i-1))*(x - xV(i-1)) + (y - yV(i-1))*(y - yV(i-1)) + z * z);\n            e(i-1) = (x - xV(i-1))*(x - xV(i-1)) + z*z;\n            h(i-1) = (x - xV(i-1)) * (y - yV(i-1));\n        }\n        for (int i = 1; i <= 4; ++i) {\n            int j = i%4 + 1;\n\n            F(i-1) = (yV(j-1) - yV(i-1))*e(i-1) - (xV(j-1) - xV(i-1))*h(i-1);\n            G(i-1) = (yV(j-1) - yV(i-1))*e(j-1) - (xV(j-1) - xV(i-1))*h(j-1);\n        }\n\n        // Doublet\n        for (int i = 1; i <= 4; ++i) {\n            int j = i % 4 + 1;\n\n            mu = mu + atan2(z * (xV(j-1) - xV(i-1)) * (F(i-1) * r(j-1) - G(i-1) * r(i-1)),\n                            z * z * (xV(j-1) - xV(i-1)) * (xV(j-1) - xV(i-1)) * r(i-1) * r(j-1) + F(i-1) * G(i-1));\n        }\n        mu = -1 / (4 * PI) * mu;\n        tau = 0;\n    }\n\n    //// Body panels\n    else {\n        // Coefficients\n        for (int i = 1; i <= 4; ++i) {\n            int j = i%4 + 1;\n\n            d(i-1) = sqrt((xV(j-1) - xV(i-1))*(xV(j-1) - xV(i-1)) + (yV(j-1) - yV(i-1))*(yV(j-1) - yV(i-1)));\n            r(i-1) = sqrt((x - xV(i-1))*(x - xV(i-1)) + (y - yV(i-1))*(y - yV(i-1)) + z * z);\n        }\n\n        if (idTgt == idSrc) {\n            // Source\n            for (int i = 1; i <= 4; ++i) {\n                int j = i % 4 + 1;\n\n                tau = tau + ((x - xV(i-1)) * (yV(j-1) - yV(i-1)) - (y - yV(i-1)) * (xV(j-1) - xV(i-1))) / d(i-1) *\n                            log((r(i-1) + r(j-1) + d(i-1)) / (r(i-1) + r(j-1) - d(i-1)));\n            }\n            mu = 0.5;\n            tau = -1 / (4 * PI) * tau;\n        }\n        else {\n            // Coefficients\n            for (int i = 1; i <= 4; ++i) {\n                e(i-1) = (x - xV(i-1))*(x - xV(i-1)) + z*z;\n                h(i-1) = (x - xV(i-1)) * (y - yV(i-1));\n            }\n            for (int i = 1; i <= 4; ++i) {\n                int j = i%4 + 1;\n\n                F(i-1) = (yV(j-1) - yV(i-1))*e(i-1) - (xV(j-1) - xV(i-1))*h(i-1);\n                G(i-1) = (yV(j-1) - yV(i-1))*e(j-1) - (xV(j-1) - xV(i-1))*h(j-1);\n            }\n\n            // Doublet\n            for (int i = 1; i <= 4; ++i) {\n                int j = i % 4 + 1;\n\n                mu = mu + atan2(z * (xV(j-1) - xV(i-1)) * (F(i-1) * r(j-1) - G(i-1) * r(i-1)),\n                                      z * z * (xV(j-1) - xV(i-1)) * (xV(j-1) - xV(i-1)) * r(i-1) * r(j-1) + F(i-1) * G(i-1));\n            }\n            mu = -1 / (4 * PI) * mu;\n            // Source\n            for (int i = 1; i <= 4; ++i) {\n                int j = i % 4 + 1;\n\n                tau = tau + ((x - xV(i-1)) * (yV(j-1) - yV(i-1)) - (y - yV(i-1)) * (xV(j-1) - xV(i-1))) / d(i-1) *\n                                log((r(i-1) + r(j-1) + d(i-1)) / (r(i-1) + r(j-1) - d(i-1)));\n            }\n            tau = -1 / (4 * PI) * tau - z * mu;\n        }\n    }\n    coeff[0] = mu;\n    coeff[1] = tau;\n\n    return  coeff;\n}", "meta": {"hexsha": "9fcd8e692860cfc5b569c3d4ec4cacaed52d2698", "size": 4835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/infcB.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/infcB.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/infcB.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2907801418, "max_line_length": 125, "alphanum_fraction": 0.4279214064, "num_tokens": 1851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.6178591981668456}}
{"text": "#include \"utils.hpp\"\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/integer.hpp>\nusing namespace std;\nusing Bint = boost::multiprecision::cpp_int;\n\nstring BruteForceFactorizer_cppfunc(string s){\n    Bint n(s);\n    Bint sqrt_n = boost::multiprecision::sqrt(n);\n    for(Bint i=2;i<=sqrt_n+1;i++){\n        if(n%i==0){\n            return i.str();\n        }\n    }\n    return \"1\";\n}\n", "meta": {"hexsha": "1f4ebf4485b6aecdb8e197fea1cfc355a07d7851", "size": 406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BruteForceFactorizer_cpp.cpp", "max_stars_repo_name": "FullteaR/factorizer", "max_stars_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BruteForceFactorizer_cpp.cpp", "max_issues_repo_name": "FullteaR/factorizer", "max_issues_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BruteForceFactorizer_cpp.cpp", "max_forks_repo_name": "FullteaR/factorizer", "max_forks_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5555555556, "max_line_length": 49, "alphanum_fraction": 0.6403940887, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.6177911055526731}}
{"text": "#include <catch.hpp>\n#include <Eigen/Core>\n#include <random>\n\n#include \"check_adjoint.h\"\n#include \"test_utils.h\"\n#include \"renderer_adjoint.cuh\"\n\n\n\nTEST_CASE(\"Adjoint-Cross\", \"[adjoint]\")\n{\n\ttypedef empty TmpStorage_t;\n\ttypedef VectorXr Vector_t;\n\t\n\tauto forward = [](const Vector_t& x, TmpStorage_t* tmp) -> Vector_t\n\t{\n\t\tconst real3 a = fromEigen3(x.head(3));\n\t\tconst real3 b = fromEigen3(x.tail(3));\n\t\tconst real3 c = cross(a, b);\n\t\treturn toEigen(c);\n\t};\n\tauto adjoint = [](const Vector_t& x, const Vector_t& e, const Vector_t& g,\n\t\tVector_t& z, const TmpStorage_t& tmp)\n\t{\n\t\tconst real3 a = fromEigen3(x.head(3));\n\t\tconst real3 b = fromEigen3(x.tail(3));\n\t\tconst real3 adj_c = fromEigen3(g);\n\t\treal3 adj_a = make_real3(0), adj_b = make_real3(0);\n\t\tkernel::adjCross(a, b, adj_c, adj_a, adj_b);\n\t\tz.head(3) = toEigen(adj_a);\n\t\tz.tail(3) = toEigen(adj_b);\n\t};\n\n\tstd::default_random_engine rnd(42);\n\tstd::normal_distribution<real_t> distr;\n\tint N = 20;\n\tfor (int i=0; i<N; ++i)\n\t{\n\t\tINFO(\"N=\" << i);\n\t\tconst real3 a = make_real3(\n\t\t\tdistr(rnd), distr(rnd), distr(rnd));\n\t\tconst real3 b = make_real3(\n\t\t\tdistr(rnd), distr(rnd), distr(rnd));\n\t\tVector_t x(6);\n\t\tx.head(3) = toEigen(a);\n\t\tx.tail(3) = toEigen(b);\n\n\t\tcheckAdjoint<Vector_t, TmpStorage_t>(x, forward, adjoint);\n\t}\n}\n\n\nTEST_CASE(\"Adjoint-Normalize\", \"[adjoint]\")\n{\n\ttypedef empty TmpStorage_t;\n\ttypedef Vector3r Vector_t;\n\n\tauto forward = [](const Vector_t& x, TmpStorage_t* tmp) -> Vector_t\n\t{\n\t\tconst real3 a = fromEigen3(x);\n\t\tconst real3 c = normalize(a);\n\t\treturn toEigen(c);\n\t};\n\tauto adjoint = [](const Vector_t& x, const Vector_t& e, const Vector_t& g,\n\t\tVector_t& z, const TmpStorage_t& tmp)\n\t{\n\t\tconst real3 a = fromEigen3(x);\n\t\tconst real3 adj_c = fromEigen3(g);\n\t\treal3 adj_a = kernel::adjNormalize(a, adj_c);\n\t\tz = toEigen(adj_a);\n\t};\n\n\tstd::default_random_engine rnd(42);\n\tstd::normal_distribution<real_t> distr;\n\tint N = 20;\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tINFO(\"N=\" << i);\n\t\tconst real3 a = make_real3(\n\t\t\tdistr(rnd), distr(rnd), distr(rnd));\n\t\tVector_t x = toEigen(a);\n\n\t\tcheckAdjoint<Vector_t, TmpStorage_t>(x, forward, adjoint,\n\t\t\t1e-6, 1e-3, 1e-5);\n\t}\n}\n\n", "meta": {"hexsha": "99d01c7630a8e858818b07d9a02ee66f8a00e10b", "size": 2137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/testAdjointUtils.cpp", "max_stars_repo_name": "shamanDevel/DiffDVR", "max_stars_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-08-02T04:51:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:02:27.000Z", "max_issues_repo_path": "unittests/testAdjointUtils.cpp", "max_issues_repo_name": "shamanDevel/DiffDVR", "max_issues_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-04T14:23:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T10:30:13.000Z", "max_forks_repo_path": "unittests/testAdjointUtils.cpp", "max_forks_repo_name": "shamanDevel/DiffDVR", "max_forks_repo_head_hexsha": "99fbe9f114d0097daf402bde2ae35f18dade335d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-16T10:23:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T02:51:43.000Z", "avg_line_length": 24.0112359551, "max_line_length": 75, "alphanum_fraction": 0.6588675714, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.617778584907562}}
{"text": "#include \"ps/ps.h\"\n#include \"cmath\"\n#include \"lr.h\"\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <fstream>\n\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::VectorXi;\nusing Eigen::ArrayXd;\n\nnamespace lrprox {\n\n  LR::LR(int num_dims)\n    : num_dims_(num_dims) {\n    initWeight_();\n  }\n\n  double LR::cost(const MatrixXd &X, const VectorXi &y) {\n    // minimize negative log prob\n    VectorXd term_in_sigmoid = - y.cast<double>().cwiseProduct(X * weight_);\n    // do not take average\n    return term_in_sigmoid.array().exp().log1p().matrix().sum();\n  }\n\n  VectorXd LR::grad(const MatrixXd &X, const VectorXi &y) {\n    ArrayXd term1 = 1 - ((- y.cast<double>().cwiseProduct(X * weight_)).array().exp() + 1).inverse();\n    return -X.transpose() * (term1 * y.cast<double>().array()).matrix();\n  }\n//\n//  VectorXi predict(const MatrixXd &X);\n//\n  const VectorXd& LR::getWeight() {\n    return weight_;\n  }\n  void LR::updateWeight(const std::vector<double>& weight) {\n//    for (int i = 0; i < weight.size(); i++) {\n//      weight_(i) = weight[i];\n//    }\n    weight_ = VectorXd::Map(&weight[0], weight_.size());\n  }\n  void LR::updateWeight(const VectorXd& weight) {\n    weight_ = weight;\n  }\n//\n//  bool saveModel(std::string &filename);\n\n  void LR::initWeight_() {\n//    weight_ = VectorXd::Random(num_dims_);\n    weight_ = VectorXd::Ones(num_dims_);\n  }\n\n\n//bool LR::SaveModel(std::string& filename) {\n//  std::ofstream fout(filename.c_str());\n//  fout << num_feature_dim_ << std::endl;\n//  for (int i = 0; i < num_feature_dim_; ++i) {\n//    fout << weight_[i] << ' ';\n//  }\n//  fout << std::endl;\n//  fout.close();\n//  return true;\n//}\n\n//std::string LR::DebugInfo() {\n//  std::ostringstream out;\n//  for (size_t i = 0; i < weight_.size(); ++i) {\n//    out << weight_[i] << \" \";\n//  }\n//  return out.str();\n//}\n\n//  float LR::Sigmoid_(std::vector<float> feature) {\n//    float z = 0;\n//    for (size_t j = 0; j < weight_.size(); ++j) {\n//      z += weight_[j] * feature[j];\n//    }\n//    return 1. / (1. + exp(-z));\n//  }\n\n} // namespace lrprox\n", "meta": {"hexsha": "843d63c80385a31766fab0428620d2f6faebfe46", "size": 2092, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/LR_proximal/src/lr.cc", "max_stars_repo_name": "xcgoner/ps-lite-new", "max_stars_repo_head_hexsha": "39754e97b4b23dc6f90ab6fc22b3e1a918f48093", "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/LR_proximal/src/lr.cc", "max_issues_repo_name": "xcgoner/ps-lite-new", "max_issues_repo_head_hexsha": "39754e97b4b23dc6f90ab6fc22b3e1a918f48093", "max_issues_repo_licenses": ["Apache-2.0"], "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/LR_proximal/src/lr.cc", "max_forks_repo_name": "xcgoner/ps-lite-new", "max_forks_repo_head_hexsha": "39754e97b4b23dc6f90ab6fc22b3e1a918f48093", "max_forks_repo_licenses": ["Apache-2.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.3255813953, "max_line_length": 101, "alphanum_fraction": 0.59416826, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6177495713089906}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_LOGSQRT2PI_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_LOGSQRT2PI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-constant\n\n    Generate value \\f$\\log\\sqrt{2\\pi}\\f$\n\n\n    @par Header <boost/simd/constant/logsqrt2pi.hpp>\n\n    @par Semantic:\n\n    @code\n    T r = Logsqrt2pi<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = log(sqrt(2*Pi<T>());\n    @endcode\n\n    @return The Logsqrt2pi constant for the proper type\n  **/\n  template<typename T> T Logsqrt2pi();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n      Generate the  constant logsqrt2pi.\n\n      @return The Logsqrt2pi constant for the proper type\n    **/\n    Value Logsqrt2pi<Value>();\n  }\n} }\n#endif\n\n#include <boost/simd/constant/scalar/logsqrt2pi.hpp>\n#include <boost/simd/constant/simd/logsqrt2pi.hpp>\n\n#endif\n", "meta": {"hexsha": "0f2679879b667ac71eb03c024e2cdab7f06c860d", "size": 1279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/logsqrt2pi.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/constant/logsqrt2pi.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/constant/logsqrt2pi.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 22.0517241379, "max_line_length": 100, "alphanum_fraction": 0.5801407349, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6177495557936393}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\nusing namespace Eigen;\nusing namespace std;\nint main()\n{\n    MatrixXd m = MatrixXd::Random(3,3);\n    m = (m + MatrixXd::Constant(3,3,1.2)) * 50;\n    cout << \"m =\" << endl << m << endl;\n    VectorXd v(3);\n    v << 1, 2, 3;\n    cout << \"m * v =\" << endl << m * v << endl;\n\n    MatrixXf mat = MatrixXf::Random(2, 3);\n    std::cout << mat << std::endl << std::endl;\n    mat = (MatrixXf(2,2) << 0, 1, 1, 0).finished() * mat;\n    std::cout << mat << std::endl;\n}\n", "meta": {"hexsha": "1417918a3bd33c95d8e6748c528b90974b89f3ae", "size": 500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snippets/eigen-finished.cpp", "max_stars_repo_name": "district10/snippet-manager", "max_stars_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-04T09:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-19T17:46:34.000Z", "max_issues_repo_path": "snippets/eigen-finished.cpp", "max_issues_repo_name": "district10/snippet-manager", "max_issues_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snippets/eigen-finished.cpp", "max_forks_repo_name": "district10/snippet-manager", "max_forks_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-31T04:14:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-02T01:22:39.000Z", "avg_line_length": 26.3157894737, "max_line_length": 57, "alphanum_fraction": 0.528, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6177057747601062}}
{"text": "/* C++ headers */\n#include <random>\n\n/* boost test framework. */\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_ALTERNATIVE_INIT_API\n#define BOOST_TEST_MODULE math library test\n#include <boost/test/unit_test.hpp>\n\n// enable loading of SIMD types.\n#define ML_INCLUDE_SIMD\n\n/* user headers. */\n#include \"ml/all.h\"\n\n/*\n * Helpers.\n */\n\nvoid random_initialize_real_std_vector(std::size_t n, std::vector<ml::vec4>& v)\n{\n    std::random_device rnd_device;\n    std::mt19937 mersenne_engine{rnd_device()};\n    std::uniform_real_distribution<float> dist{-1, 1};\n\n    auto gen = [&dist, &mersenne_engine]()\n    {\n        return ml::vec4{dist(mersenne_engine), dist(mersenne_engine), dist(mersenne_engine), dist(mersenne_engine)};\n    };\n\n    v.resize(n);\n    generate(std::begin(v), std::end(v), gen);\n}\n\n/*\n * memory alignment.\n */\ninline bool\n  is_aligned(const void* ptr, std::uintptr_t alignment) noexcept\n{\n    auto iptr = reinterpret_cast<std::uintptr_t>(ptr);\n    return !(iptr % alignment);\n}\n\nBOOST_AUTO_TEST_SUITE(math)\n\n/*\n * vec2 tests.\n */\n\nBOOST_AUTO_TEST_CASE(vec2)\n{\n    ml::vec2 v1{1, 0}, v2{0, 1};\n    BOOST_TEST(v1.area(v2) == 1.0f);\n\n    ml::vec2 v3{std::cos(M_PI / 4), std::sin(M_PI / 4)};\n    ml::vec2 v4{std::cos(M_PI / 4 + M_PI / 2), std::sin(M_PI / 4 + M_PI / 2)};\n    BOOST_TEST(v3.area(v4) == 1.0f, boost::test_tools::tolerance(1e-6f));\n}\n\n/*\n * tvec2 tests.\n */\n\nBOOST_AUTO_TEST_CASE(tvec2)\n{\n    ml::tvec2<ml::fixed_24_8_t> v = {1.23, 2.24};\n    BOOST_TEST(ml::to_float(v.x) == 1.23f, boost::test_tools::tolerance(4e-3f));\n    BOOST_TEST(ml::to_float(v.y) == 2.24f, boost::test_tools::tolerance(4e-3f));\n}\n\n/*\n * vec2_fixed tests.\n */\n\nBOOST_AUTO_TEST_CASE(vec2_fixed)\n{\n    const ml::vec2_fixed<8> v1{1, 0}, v2{0, 1};\n    BOOST_TEST(v1.area(v2) == ml::vec2_fixed<8>::type{1});\n    BOOST_TEST(v2.area(v1) == ml::vec2_fixed<8>::type{-1});\n    BOOST_TEST(v1.area(v1) == ml::vec2_fixed<8>::type{0});\n    BOOST_TEST(v2.area(v2) == ml::vec2_fixed<8>::type{0});\n}\n\n/*\n * vec4 tests.\n */\n\n// check that we actually using both non-simd and simd types.\nstatic_assert(!std::is_same<ml::vec4, ml::simd::vec4>::value);\nstatic_assert(!std::is_same<ml::mat4x4, ml::simd::mat4x4>::value);\n\n// paranoid checks.\nstatic_assert(sizeof(ml::vec4) == 4 * sizeof(float));\nstatic_assert(sizeof(ml::vec4) == sizeof(__m128));\n\nBOOST_AUTO_TEST_CASE(vec4_alignment)\n{\n    std::vector<ml::vec4> v;\n    random_initialize_real_std_vector(10, v);\n\n    // check vector alignment while being paranoid.\n    BOOST_TEST_MESSAGE(\"Checking 16-byte vector alignment\");\n    for(size_t i = 0; i < v.size(); ++i)\n    {\n        BOOST_CHECK(is_aligned(&v[i], 16));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(vec4_simd_initialization)\n{\n    ml::simd::vec4 v1{1, 2, 3, 4};\n    ml::simd::vec4 v2{1, 2, 3};\n    ml::simd::vec4 v3{ml::vec3{1, 2, 3}, 4};\n\n    BOOST_TEST((v1.x == 1 && v1.y == 2 && v1.z == 3 && v1.w == 4));\n    BOOST_TEST((v2.x == 1 && v2.y == 2 && v2.z == 3 && v2.w == 1)); /* w-component defaults to one if not specified. */\n    BOOST_TEST((v3.x == 1 && v3.y == 2 && v3.z == 3 && v3.w == 4));\n\n    float v[4] = {1, 2, 3, 4};\n    ml::simd::vec4 v4{v};\n    ml::vec4 v5{v};\n\n    BOOST_TEST((v4.x == 1 && v4.y == 2 && v4.z == 3 && v4.w == 4));\n    BOOST_TEST((v5.x == 1 && v5.y == 2 && v5.z == 3 && v5.w == 4));\n}\n\nBOOST_AUTO_TEST_CASE(vec4_simd_comparisons)\n{\n    BOOST_TEST((ml::simd::vec4(1, 2, 3, 4) == ml::simd::vec4(1, 2, 3, 4)));\n    BOOST_TEST(!(ml::simd::vec4(1, 2, 3, 4) == ml::simd::vec4(1, 2, 3, 0)));\n    BOOST_TEST(!(ml::simd::vec4(1, 2, 3, 4) != ml::simd::vec4(1, 2, 3, 4)));\n    BOOST_TEST((ml::simd::vec4(1, 2, 3, 4) != ml::simd::vec4(1, 2, 3, 0)));\n}\n\nBOOST_AUTO_TEST_CASE(vec4_component_product)\n{\n    BOOST_TEST((ml::vec4(1, 2, 3, 4) * ml::vec4(4, 3, 2, 1) == ml::vec4(4, 6, 6, 4)));\n    BOOST_TEST((ml::vec4(0, 1, 0, 1) * ml::vec4(-1, 0, -1, 0) == ml::vec4(0, 0, 0, 0)));\n    BOOST_TEST((ml::vec4(-2, -3, 3, 2) * ml::vec4(-1, 0, 4, -4) == ml::vec4(2, 0, 12, -8)));\n}\n\nBOOST_AUTO_TEST_CASE(vec4_simd_component_product)\n{\n    BOOST_TEST((ml::simd::vec4(1, 2, 3, 4) * ml::simd::vec4(4, 3, 2, 1) == ml::simd::vec4(4, 6, 6, 4)));\n    BOOST_TEST((ml::simd::vec4(0, 1, 0, 1) * ml::simd::vec4(-1, 0, -1, 0) == ml::simd::vec4(0, 0, 0, 0)));\n    BOOST_TEST((ml::simd::vec4(-2, -3, 3, 2) * ml::simd::vec4(-1, 0, 4, -4) == ml::simd::vec4(2, 0, 12, -8)));\n}\n\nBOOST_AUTO_TEST_CASE(vec4_dot)\n{\n    BOOST_TEST(ml::dot(ml::vec4(1, -1, 1, -1), ml::vec4(1, -1, 1, -1)) == 4);\n    BOOST_TEST(ml::dot(ml::vec4(1, 2, 3, 4), ml::vec4(4, 3, 2, 1)) == 20);\n    BOOST_TEST(ml::dot(ml::vec4(1, 2, 3, 4), ml::vec4(-2, 1, -4, 3)) == 0);\n}\n\nBOOST_AUTO_TEST_CASE(vec4_simd_dot)\n{\n    BOOST_TEST(ml::dot(ml::simd::vec4(1, -1, 1, -1), ml::simd::vec4(1, -1, 1, -1)) == 4);\n    BOOST_TEST(ml::dot(ml::simd::vec4(1, 2, 3, 4), ml::simd::vec4(4, 3, 2, 1)) == 20);\n    BOOST_TEST(ml::dot(ml::simd::vec4(1, 2, 3, 4), ml::simd::vec4(-2, 1, -4, 3)) == 0);\n}\n\nBOOST_AUTO_TEST_CASE(vec4_is_zero)\n{\n    BOOST_TEST(!ml::vec4(0, 0, 0, 1).is_zero());\n    BOOST_TEST(ml::vec4(0, 0, 0, 0).is_zero());\n}\n\nBOOST_AUTO_TEST_CASE(vec4_simd_is_zero)\n{\n    BOOST_TEST(!ml::simd::vec4(0, 0, 0, 1).is_zero());\n    BOOST_TEST(ml::simd::vec4(0, 0, 0, 0).is_zero());\n}\n\n/*\n * mat4x4 tests.\n */\n\n// compare non-simd and simd vec4\nbool operator==(const ml::vec4& v1, const ml::simd::vec4& v2)\n{\n    return v1.x == v2.x && v1.y == v2.y && v1.z == v2.z && v1.w == v2.w;\n}\n\n// compare non-simd and simd mat4x4\nbool operator==(const ml::mat4x4& m1, const ml::simd::mat4x4& m2)\n{\n    return m1.rows[0] == m2.rows[0] && m1.rows[1] == m2.rows[1] && m1.rows[2] == m2.rows[2] && m1.rows[3] == m2.rows[3];\n}\n\n// initialize simd vec4 from non-simd vec4\nml::simd::vec4 vec_simd_init(const ml::vec4& v)\n{\n    return {v.x, v.y, v.z, v.w};\n}\n\n// initialize simd mat4x4 from non-simd mat4x4\nml::simd::mat4x4 mat_simd_init(const ml::mat4x4& m)\n{\n    return {vec_simd_init(m.rows[0]), vec_simd_init(m.rows[1]), vec_simd_init(m.rows[2]), vec_simd_init(m.rows[3])};\n}\n\nBOOST_AUTO_TEST_CASE(mat4x4_multiplication)\n{\n    ml::mat4x4 m1{\n      {1, 2, 3, 4},\n      {2, 4, 3, 1},\n      {3, 1, 4, 2},\n      {4, 2, 1, 3}};\n    m1 = m1 * m1;\n\n    ml::simd::mat4x4 m2{\n      {1, 2, 3, 4},\n      {2, 4, 3, 1},\n      {3, 1, 4, 2},\n      {4, 2, 1, 3}};\n    m2 = m2 * m2;\n\n    BOOST_TEST((m1.rows[0] == m2.rows[0]));\n    BOOST_TEST((m1.rows[1] == m2.rows[1]));\n    BOOST_TEST((m1.rows[2] == m2.rows[2]));\n    BOOST_TEST((m1.rows[3] == m2.rows[3]));\n\n    m1.transpose();\n    m2.transpose();\n\n    // for better tracking in case of test failure.\n    auto m1_t = m1;\n    auto m2_t = m2;\n    BOOST_TEST((m1_t.rows[0] == m2_t.rows[0]));\n    BOOST_TEST((m1_t.rows[1] == m2_t.rows[1]));\n    BOOST_TEST((m1_t.rows[2] == m2_t.rows[2]));\n    BOOST_TEST((m1_t.rows[3] == m2_t.rows[3]));\n}\n\ntemplate<typename T>\nT get_random_vec4()\n{\n    return {static_cast<float>(rand() % 9 - 5), static_cast<float>(rand() % 9 - 5), static_cast<float>(rand() % 9 - 5), static_cast<float>(rand() % 9 + 1)};\n}\n\ntemplate<typename M, typename T>\nM get_random_mat()\n{\n    return {\n      get_random_vec4<T>(),\n      get_random_vec4<T>(),\n      get_random_vec4<T>(),\n      get_random_vec4<T>()};\n}\n\nBOOST_AUTO_TEST_CASE(mat4x4_randomized_multiplication)\n{\n    // random multiplication tests.\n    for(int i = 0; i < 1000; ++i)\n    {\n        ml::mat4x4 rm1 = get_random_mat<ml::mat4x4, ml::vec4>();\n        ml::mat4x4 rm2 = get_random_mat<ml::mat4x4, ml::vec4>();\n\n        ml::simd::mat4x4 rm1_simd = mat_simd_init(rm1), rm2_simd = mat_simd_init(rm2);\n\n        ml::mat4x4 res = rm1 * rm2;\n        ml::simd::mat4x4 res_simd = rm1_simd * rm2_simd;\n\n        BOOST_REQUIRE(res.rows[0] == res_simd.rows[0]);\n        BOOST_REQUIRE(res.rows[1] == res_simd.rows[1]);\n        BOOST_REQUIRE(res.rows[2] == res_simd.rows[2]);\n        BOOST_REQUIRE(res.rows[3] == res_simd.rows[3]);\n    }\n}\n\n/*\n * math functions.\n */\n\nBOOST_AUTO_TEST_CASE(lerp)\n{\n    BOOST_TEST(ml::lerp<float>(0.3f, 1.f, 2.f) == static_cast<float>(1.f * (1.f - 0.3f) + 2.f * 0.3f), boost::test_tools::tolerance(1e-8f));\n    BOOST_TEST(ml::lerp<double>(0.3, 1, 2) == static_cast<double>(1.0 * (1.0 - 0.3) + 2.0 * 0.3), boost::test_tools::tolerance(1e-8));\n\n    ml::vec4 a{1.1, 2.2, 3.3, 4.4};\n    ml::vec4 b{-9.3, -10.4, -11.5, -12.6};\n    ml::vec4 l{ml::lerp<ml::vec4>(0.4, a, b)};\n    BOOST_TEST(l.x == -3.06f, boost::test_tools::tolerance(1e-6f));\n    BOOST_TEST(l.y == -2.84f, boost::test_tools::tolerance(1e-6f));\n    BOOST_TEST(l.z == -2.62f, boost::test_tools::tolerance(1e-6f));\n    BOOST_TEST(l.w == -2.4f, boost::test_tools::tolerance(1e-6f));\n\n    for(int i = 0; i < 100; ++i)\n    {\n        float t = static_cast<float>(i) / 100.f;\n\n        l = ml::lerp(t, a, b);\n        BOOST_TEST(l.x == ml::lerp(t, a.x, b.x), boost::test_tools::tolerance(1e-5f));\n        BOOST_TEST(l.y == ml::lerp(t, a.y, b.y), boost::test_tools::tolerance(1e-5f));\n        BOOST_TEST(l.z == ml::lerp(t, a.z, b.z), boost::test_tools::tolerance(1e-5f));\n        BOOST_TEST(l.w == ml::lerp(t, a.w, b.w), boost::test_tools::tolerance(1e-5f));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(radians_degrees)\n{\n    /* these are just linear transformations.... */\n\n    BOOST_TEST(ml::to_radians(0) == 0);\n    BOOST_TEST(ml::to_radians(90) == static_cast<float>(M_PI_2), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_radians(180) == static_cast<float>(M_PI), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_radians(270) == static_cast<float>(3 * M_PI_2), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_radians(360) == static_cast<float>(2 * M_PI), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_radians(-90) == static_cast<float>(-M_PI_2), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_radians(-180) == static_cast<float>(-M_PI), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_radians(-270) == static_cast<float>(-3 * M_PI_2), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_radians(-360) == static_cast<float>(-2 * M_PI), boost::test_tools::tolerance(1e-9f));\n\n    BOOST_TEST(ml::to_degrees(0) == 0);\n    BOOST_TEST(ml::to_degrees(static_cast<float>(M_PI_2)) == static_cast<float>(90), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_degrees(static_cast<float>(M_PI)) == static_cast<float>(180), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_degrees(static_cast<float>(3 * M_PI_2)) == static_cast<float>(270), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_degrees(static_cast<float>(2 * M_PI)) == static_cast<float>(360), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_degrees(static_cast<float>(-M_PI_2)) == static_cast<float>(-90), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_degrees(static_cast<float>(-M_PI)) == static_cast<float>(-180), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_degrees(static_cast<float>(-3 * M_PI_2)) == static_cast<float>(-270), boost::test_tools::tolerance(1e-9f));\n    BOOST_TEST(ml::to_degrees(static_cast<float>(-2 * M_PI)) == static_cast<float>(-360), boost::test_tools::tolerance(1e-9f));\n\n    for(int i = 0; i < 100; ++i)\n    {\n        BOOST_TEST(ml::to_radians(ml::to_degrees(static_cast<float>(i))) == static_cast<float>(i), boost::test_tools::tolerance(1e-6f));\n        BOOST_TEST(ml::to_degrees(ml::to_radians(static_cast<float>(i))) == static_cast<float>(i), boost::test_tools::tolerance(1e-6f));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "2173b294a0db331bed44433c82a3b5d303b4043e", "size": 11416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math.cpp", "max_stars_repo_name": "flubbe/ml", "max_stars_repo_head_hexsha": "0877924e7b7e21d0cb4b781617006aca2e13c1c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math.cpp", "max_issues_repo_name": "flubbe/ml", "max_issues_repo_head_hexsha": "0877924e7b7e21d0cb4b781617006aca2e13c1c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math.cpp", "max_forks_repo_name": "flubbe/ml", "max_forks_repo_head_hexsha": "0877924e7b7e21d0cb4b781617006aca2e13c1c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1796407186, "max_line_length": 156, "alphanum_fraction": 0.6096706377, "num_tokens": 4343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6177057594604425}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/function/scalar/div.hpp>\n#include <simd_test.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/two.hpp>\n\n\nSTF_CASE_TPL (\" divreal\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  using bs::div;\n  using r_t = decltype(div(T(), T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t,T);\n\n  // specific values tests\n#ifndef STF_NO_INVALIDS\n  STF_IEEE_EQUAL(div(bs::Inf<T>(), bs::Inf<T>(), bs::floor), bs::Nan<r_t>());\n  STF_IEEE_EQUAL(div(bs::Minf<T>(), bs::Minf<T>(), bs::floor), bs::Nan<r_t>());\n  STF_IEEE_EQUAL(div(bs::Nan<T>(), bs::Nan<T>(), bs::floor), bs::Nan<r_t>());\n#endif\n  STF_EQUAL(div(T(4),T(0), bs::floor), bs::Inf<r_t>());\n  STF_EQUAL(div(T(4),T(3), bs::floor), bs::One<r_t>());\n  STF_EQUAL(div(bs::Mone<T>(), bs::Mone<T>(), bs::floor), bs::One<r_t>());\n  STF_EQUAL(div(bs::One<T>(), bs::One<T>(), bs::floor), bs::One<r_t>());\n  STF_EQUAL(div(bs::Mone<T>(),bs::Zero<T>(), bs::floor), bs::Minf<r_t>());\n  STF_EQUAL(div(bs::One<T>(), bs::One<T>(), bs::floor), bs::One<r_t>());\n  STF_EQUAL(div(bs::One<T>(),bs::Zero<T>(), bs::floor), bs::Inf<r_t>());\n  STF_IEEE_EQUAL(div(bs::Zero<T>(),bs::Zero<T>(), bs::floor), bs::Nan<r_t>());\n} // end of test for floating_\n\nSTF_CASE_TPL (\" divunsigned_int\",  STF_UNSIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  using bs::div;\n  using r_t = decltype(div(T(), T()));\n\n  STF_TYPE_IS(r_t,T);\n\n  // specific values tests\n  STF_EQUAL(div(T(4),T(0), bs::floor), bs::Valmax<r_t>());\n  STF_EQUAL(div(T(4),T(3), bs::floor), T(1));\n  STF_EQUAL(div(bs::One<T>(), bs::One<T>(), bs::floor), bs::One<r_t>());\n  STF_EQUAL(div(bs::Valmax<T>(),  bs::Two<T>(), bs::floor), bs::Valmax<r_t>()/bs::Two<T>());\n} // end of test for unsigned_int_\n\nSTF_CASE_TPL (\" divsigned_int\",  STF_SIGNED_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  using bs::div;\n  using r_t = decltype(div(T(), T()));\n\n  STF_TYPE_IS(r_t,T);\n\n  // specific values tests\n  STF_EQUAL(div(T(-4),T(0), bs::floor), bs::Valmin<r_t>());\n  STF_EQUAL(div(T(4),T(0), bs::floor), bs::Valmax<r_t>());\n  STF_EQUAL(div(T(4),T(3), bs::floor), T(1));\n  STF_EQUAL(div(T(-4),T(-3), bs::floor), T(1));\n  STF_EQUAL(div(T(4),T(-3), bs::floor), T(-2));\n  STF_EQUAL(div(T(-4),T(3), bs::floor), T(-2));\n  STF_EQUAL(div(bs::Mone<T>(), bs::Mone<T>(), bs::floor), bs::One<r_t>());\n  STF_EQUAL(div(bs::One<T>(), bs::One<T>(), bs::floor), bs::One<r_t>());\n} // end of test for signed_int_\n\n\n", "meta": {"hexsha": "577cc28fccf37e7ddf7ebfe3b2e8ba0ea0bab85f", "size": 3053, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/divfloor.cpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/function/scalar/divfloor.cpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/scalar/divfloor.cpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2317073171, "max_line_length": 100, "alphanum_fraction": 0.586308549, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.617705086464397}}
{"text": "#pragma once\n\n/**\n *  Classical sign domain.\n *\n *  This is actually the extended sign domain defined in \"Tutorial on\n *  Static Inference of Numeric Invariants by Abstract Interpretation\"\n *  by A. Mine 2017.\n */\n\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/backward_assign_operations.hpp>\n#include <crab/domains/interval.hpp>\n#include <crab/domains/separate_domains.hpp>\n#include <crab/support/stats.hpp>\n\n#include <boost/optional.hpp>\n\n#include <type_traits>\n\nnamespace crab {\nnamespace domains {\n\nenum class sign_interval {\n  BOT, // empty interval\n  LTZ, // [-oo,0)\n  GTZ, // (0, +oo]\n  EQZ, // [0,0]\n  NEZ, // [-oo,0) U (0, +oo]\n  GEZ, // [0, +oo]\n  LEZ, // [-oo,0]\n  TOP, // [-oo,+oo]\n       /*\n                TOP\n               / | \\\n              /  |  \\\n            LEZ NEZ  GEZ\n             |\\ /  \\/|\n             |/ EQZ \\|\n            LTZ  |  GTZ\n              \\  |  /\n               \\ | /\n                BOT\n        */\n};\n\ntemplate <typename Number> class sign {\n  static_assert(std::is_same<Number, ikos::z_number>::value,\n                \"Class sign only defined over ikos::z_number\");\n\n  using sign_t = sign<Number>;\n  using interval_t = ikos::interval<Number>;\n  using bound_t = ikos::bound<Number>;\n  sign_interval m_sign;\n\n  constexpr Number get_zero() const { return Number(0); }\n  constexpr Number get_plus_one() const { return Number(1); }\n  constexpr Number get_minus_one() const { return Number(-1); }\n\n  sign_t shiftOp(const sign_t &o) const {\n    // The shift operation is shl, lshr, or ashr\n    // zero is special\n    if (is_bottom() || o.is_bottom()) {\n      return bottom();\n    } else {\n      if (equal_zero() || o.equal_zero()) {\n        return *this;\n      } else {\n        return top();\n      }\n    }\n  }\n\n  sign_t defaultOp(const sign_t &o) const {\n    if (is_bottom() || o.is_bottom()) {\n      return bottom();\n    } else {\n      return top();\n    }\n  }\n\n  explicit sign(sign_interval s) : m_sign(s) {}\n\npublic:\n  explicit sign(bool is_bottom)\n      : m_sign(is_bottom ? sign_interval::BOT : sign_interval::TOP) {}\n\n  explicit sign(Number c) : m_sign(sign_interval::TOP) {\n    Number zero(get_zero());\n    if (c == zero) {\n      m_sign = sign_interval::EQZ;\n    } else if (c < zero) {\n      m_sign = sign_interval::LTZ;\n    } else /* (c > zero) */ {\n      m_sign = sign_interval::GTZ;\n    }\n  }\n\n  /* MODIFY HERE if not integers */  \n  sign_t from_interval(const interval_t &i) const {\n    Number zero(get_zero());\n    Number plus_one(get_plus_one());\n    Number minus_one(get_minus_one());\n    if (i.is_bottom()) {\n      return sign_t::bottom();\n    } else if (i.is_top()) {\n      return sign_t::top();\n    } else if (i <= interval_t(zero, zero)) {\n      return sign_t(sign_interval::EQZ);\n    } else if (i <= interval_t(bound_t::minus_infinity(), minus_one)) {\n      return sign_t(sign_interval::LTZ);\n    } else if (i <= interval_t(bound_t::minus_infinity(), zero)) {\n      return sign_t(sign_interval::LEZ);\n    } else if (i <= interval_t(plus_one, bound_t::plus_infinity())) {\n      return sign_t(sign_interval::GTZ);\n    } else if (i <= interval_t(zero, bound_t::plus_infinity())) {\n      return sign_t(sign_interval::GEZ);\n    } else {\n      // unreachable\n      return sign_t::top();\n    }\n  }\n\n  /* MODIFY HERE if not integers */  \n  interval_t to_interval() const {\n    Number zero(get_zero());\n    Number plus_one(get_plus_one());\n    Number minus_one(get_minus_one());\n    if (is_bottom()) {\n      return interval_t::bottom();\n    } else if (is_top()) {\n      return interval_t::top();\n    } else if (equal_zero()) {\n      return interval_t(zero);\n    } else if (less_than_zero()) {\n      return interval_t(bound_t::minus_infinity(), minus_one);\n    } else if (greater_than_zero()) {\n      return interval_t(plus_one, bound_t::plus_infinity());\n    } else if (less_or_equal_than_zero()) {\n      return interval_t(bound_t::minus_infinity(), zero);\n    } else if (greater_or_equal_than_zero()) {\n      return interval_t(zero, bound_t::plus_infinity());\n    } else /* not_equal_zero*/ {\n      // we cannot express not_equal_zero in an interval\n      return interval_t::top();\n    }\n  }\n\n  static sign_t bottom() { return sign(true); }\n\n  static sign_t top() { return sign(false); }\n\n  static sign_t mk_equal_zero() { return sign_t(sign_interval::EQZ); }\n\n  static sign_t mk_less_than_zero() { return sign_t(sign_interval::LTZ); }\n\n  static sign_t mk_greater_than_zero() { return sign_t(sign_interval::GTZ); }\n\n  static sign_t mk_less_or_equal_than_zero() {\n    return sign_t(sign_interval::LEZ);\n  }\n\n  static sign_t mk_greater_or_equal_than_zero() {\n    return sign_t(sign_interval::GEZ);\n  }\n\n  static sign_t mk_not_equal_zero() { return sign_t(sign_interval::NEZ); }\n\n  bool is_bottom() const { return m_sign == sign_interval::BOT; }\n\n  bool is_top() const { return m_sign == sign_interval::TOP; }\n\n  bool equal_zero() const { return m_sign == sign_interval::EQZ; }\n\n  bool less_than_zero() const { return m_sign == sign_interval::LTZ; }\n\n  bool greater_than_zero() const { return m_sign == sign_interval::GTZ; }\n\n  bool less_or_equal_than_zero() const { return m_sign == sign_interval::LEZ; }\n\n  bool greater_or_equal_than_zero() const {\n    return m_sign == sign_interval::GEZ;\n  }\n\n  bool not_equal_zero() const { return m_sign == sign_interval::NEZ; }\n\n  bool operator<=(const sign_t &o) const {\n    if (is_bottom() || o.is_top()) {\n      return true;\n    } else if (o.is_bottom() || is_top()) {\n      return false;\n    } else {\n      // operands are not either top or bottom\n      if (m_sign == sign_interval::LTZ) {\n        return o.m_sign == m_sign || o.m_sign == sign_interval::LEZ ||\n               o.m_sign == sign_interval::NEZ;\n      } else if (m_sign == sign_interval::GTZ) {\n        return o.m_sign == m_sign || o.m_sign == sign_interval::GEZ ||\n               o.m_sign == sign_interval::NEZ;\n      } else if (m_sign == sign_interval::EQZ) {\n        return o.m_sign == m_sign || o.m_sign == sign_interval::LEZ ||\n               o.m_sign == sign_interval::GEZ;\n      } else {\n        /* m_sign == sign_interval::LEZ || m_sign == sign_interval::GEZ m_sign\n         * == sign_interval::NEZ */\n        return m_sign == o.m_sign;\n      }\n    }\n  }\n\n  bool operator==(const sign_t &o) const { return (m_sign == o.m_sign); }\n\n  sign_t operator|(const sign_t &o) const {\n    if (is_bottom() || o.is_top()) {\n      return o;\n    } else if (is_top() || o.is_bottom()) {\n      return *this;\n    } else {\n      // operands are not either top or bottom\n      if (m_sign == sign_interval::LTZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n          return *this;\n        case sign_interval::GTZ:\n        case sign_interval::NEZ:\n          return sign_t(sign_interval::NEZ);\n        case sign_interval::EQZ:\n        case sign_interval::LEZ:\n          return sign_t(sign_interval::LEZ);\n        case sign_interval::GEZ:\n          return sign_t(sign_interval::TOP);\n        default:\n          CRAB_ERROR(\"sign::operator| unreachable 1\");\n        }\n      } else if (m_sign == sign_interval::GTZ) {\n        switch (o.m_sign) {\n        case sign_interval::GTZ:\n          return *this;\n        case sign_interval::LTZ:\n        case sign_interval::NEZ:\n          return sign_t(sign_interval::NEZ);\n        case sign_interval::EQZ:\n        case sign_interval::GEZ:\n          return sign_t(sign_interval::GEZ);\n        case sign_interval::LEZ:\n          return sign_t(sign_interval::TOP);\n        default:\n          CRAB_ERROR(\"sign::operator| unreachable 2\");\n        }\n      } else if (m_sign == sign_interval::EQZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n        case sign_interval::LEZ:\n          return sign_t(sign_interval::LEZ);\n        case sign_interval::GTZ:\n        case sign_interval::GEZ:\n          return sign_t(sign_interval::GEZ);\n        case sign_interval::EQZ:\n          return *this;\n        case sign_interval::NEZ:\n          return top();\n        default:\n          CRAB_ERROR(\"sign::operator| unreachable 3\");\n        }\n      } else if (m_sign == sign_interval::LEZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n        case sign_interval::EQZ:\n        case sign_interval::LEZ:\n          return *this;\n        case sign_interval::GTZ:\n        case sign_interval::NEZ:\n        case sign_interval::GEZ:\n          return top();\n        default:\n          CRAB_ERROR(\"sign::operator| unreachable 4\");\n        }\n      } else if (m_sign == sign_interval::NEZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n        case sign_interval::GTZ:\n        case sign_interval::NEZ:\n          return *this;\n        case sign_interval::EQZ:\n        case sign_interval::LEZ:\n        case sign_interval::GEZ:\n          return top();\n        default:\n          CRAB_ERROR(\"sign::operator| unreachable 5\");\n        }\n      } else if (m_sign == sign_interval::GEZ) {\n        switch (o.m_sign) {\n        case sign_interval::EQZ:\n        case sign_interval::GTZ:\n        case sign_interval::GEZ:\n          return *this;\n        case sign_interval::LTZ:\n        case sign_interval::LEZ:\n        case sign_interval::NEZ:\n          return top();\n        default:\n          CRAB_ERROR(\"sign::operator| unreachable 6\");\n        }\n      }\n    }\n    CRAB_ERROR(\"sign::operator| unreachable 7\");\n  }\n\n  sign_t operator&(const sign_t &o) const {\n    if (is_bottom() || o.is_top())\n      return *this;\n    else if (is_top() || o.is_bottom()) {\n      return o;\n    } else {\n      // operands are not either top or bottom\n      if (m_sign == sign_interval::LTZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n          return *this;\n        case sign_interval::GTZ:\n        case sign_interval::EQZ:\n        case sign_interval::GEZ:\n          return bottom();\n        case sign_interval::LEZ:\n        case sign_interval::NEZ:\n          return sign_t(sign_interval::LTZ);\n        default:\n          CRAB_ERROR(\"sign::operator& unreachable 1\");\n        }\n      } else if (m_sign == sign_interval::GTZ) {\n        switch (o.m_sign) {\n        case sign_interval::GTZ:\n          return *this;\n        case sign_interval::LTZ:\n        case sign_interval::EQZ:\n        case sign_interval::LEZ:\n          return bottom();\n        case sign_interval::GEZ:\n        case sign_interval::NEZ:\n          return sign_t(sign_interval::GTZ);\n        default:\n          CRAB_ERROR(\"sign::operator& unreachable 2\");\n        }\n      } else if (m_sign == sign_interval::EQZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n        case sign_interval::GTZ:\n        case sign_interval::NEZ:\n          return bottom();\n        case sign_interval::GEZ:\n        case sign_interval::LEZ:\n        case sign_interval::EQZ:\n          return *this;\n        default:\n          CRAB_ERROR(\"sign::operator& unreachable 3\");\n        }\n      } else if (m_sign == sign_interval::LEZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n        case sign_interval::EQZ:\n        case sign_interval::LEZ:\n          return o;\n        case sign_interval::NEZ:\n          return sign_t(sign_interval::LTZ);\n        case sign_interval::GTZ:\n          return bottom();\n        case sign_interval::GEZ:\n          return sign_t(sign_interval::EQZ);\n        default:\n          CRAB_ERROR(\"sign::operator& unreachable 4\");\n        }\n      } else if (m_sign == sign_interval::GEZ) {\n        switch (o.m_sign) {\n        case sign_interval::EQZ:\n        case sign_interval::GTZ:\n        case sign_interval::GEZ:\n          return o;\n        case sign_interval::LTZ:\n          return bottom();\n        case sign_interval::LEZ:\n          return sign_t(sign_interval::EQZ);\n        case sign_interval::NEZ:\n          return sign_t(sign_interval::GTZ);\n        default:\n          CRAB_ERROR(\"sign::operator& unreachable 5\");\n        }\n      } else if (m_sign == sign_interval::NEZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n        case sign_interval::GTZ:\n        case sign_interval::NEZ:\n          return o;\n        case sign_interval::LEZ:\n          return sign_t(sign_interval::LTZ);\n        case sign_interval::GEZ:\n          return sign_t(sign_interval::GTZ);\n        case sign_interval::EQZ:\n          return bottom();\n        default:\n          CRAB_ERROR(\"sign::operator& unreachable 6\");\n        }\n      }\n    }\n    CRAB_ERROR(\"sign::operator& unreachable 7\");\n  }\n\n  // addition\n  sign_t operator+(const sign_t &o) const {\n    if (is_bottom() || o.is_bottom()) {\n      return bottom();\n    } else if (is_top() || o.is_top()) {\n      return top();\n    } else {\n      // operands are not either top or bottom\n      if (m_sign == sign_interval::LTZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n        case sign_interval::EQZ:\n        case sign_interval::LEZ:\n          return *this;\n        case sign_interval::GTZ:\n        case sign_interval::NEZ:\n        case sign_interval::GEZ:\n          return top();\n        default:\n          CRAB_ERROR(\"sign::operator+ unreachable 1\");\n        }\n      } else if (m_sign == sign_interval::GTZ) {\n        switch (o.m_sign) {\n        case sign_interval::GTZ:\n        case sign_interval::EQZ:\n        case sign_interval::GEZ:\n          return *this;\n        case sign_interval::LTZ:\n        case sign_interval::LEZ:\n        case sign_interval::NEZ:\n          return top();\n        default:\n          CRAB_ERROR(\"sign::operator+ unreachable 2\");\n        }\n      } else if (m_sign == sign_interval::LEZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n        case sign_interval::EQZ:\n        case sign_interval::LEZ:\n          return *this;\n        case sign_interval::GTZ:\n        case sign_interval::NEZ:\n        case sign_interval::GEZ:\n          return top();\n        default:\n          CRAB_ERROR(\"sign::operator+ unreachable 2\");\n        }\n      } else if (m_sign == sign_interval::GEZ) {\n        switch (o.m_sign) {\n        case sign_interval::GTZ:\n        case sign_interval::GEZ:\n        case sign_interval::EQZ:\n          return *this;\n        case sign_interval::LTZ:\n        case sign_interval::LEZ:\n        case sign_interval::NEZ:\n          return top();\n        default:\n          CRAB_ERROR(\"sign::operator+ unreachable 2\");\n        }\n      } else if (m_sign == sign_interval::EQZ) {\n        return o;\n      } else /* (m_sign == sign_interval::NEZ)*/ {\n        return top();\n      }\n    }\n  }\n\n  // subtraction\n  sign_t operator-(const sign_t &o) const {\n    if (is_bottom() || o.is_bottom()) {\n      return bottom();\n    } else if (is_top() || o.is_top()) {\n      return top();\n    } else {\n      switch (o.m_sign) {\n      case sign_interval::GTZ:\n        return *this + sign_t(sign_interval::LTZ);\n      case sign_interval::GEZ:\n        return *this + sign_t(sign_interval::LEZ);\n      case sign_interval::EQZ:\n        return *this;\n      case sign_interval::LTZ:\n        return *this + sign_t(sign_interval::GTZ);\n      case sign_interval::LEZ:\n        return *this + sign_t(sign_interval::GEZ);\n      default: /*sign_interval::NEZ*/\n        return top();\n      }\n    }\n  }\n\n  // multiplication\n  sign_t operator*(const sign_t &o) const {\n    if (is_bottom() || o.is_bottom()) {\n      return bottom();\n    } else if (equal_zero() || o.equal_zero()) {\n      return sign_t(sign_interval::EQZ);\n    } else if (is_top() || o.is_top()) {\n      return top();\n    } else if (not_equal_zero() || o.not_equal_zero()) {\n      return top();\n    } else {\n      // operands are not either top, bottom, zero, or non-zero\n      if (m_sign == sign_interval::LTZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n          return sign_t(sign_interval::GTZ);\n        case sign_interval::LEZ:\n          return sign_t(sign_interval::GEZ);\n        case sign_interval::GTZ:\n          return sign_t(sign_interval::LTZ);\n        case sign_interval::GEZ:\n          return sign_t(sign_interval::LEZ);\n        default:\n          CRAB_ERROR(\"sign::operator* unreachable 1\");\n        }\n      } else if (m_sign == sign_interval::GTZ) {\n        return o;\n      } else if (m_sign == sign_interval::LEZ) {\n        switch (o.m_sign) {\n        case sign_interval::LTZ:\n        case sign_interval::LEZ:\n          return sign_t(sign_interval::GEZ);\n        case sign_interval::GTZ:\n        case sign_interval::GEZ:\n          return sign_t(sign_interval::LEZ);\n        default:\n          CRAB_ERROR(\"sign::operator* unreachable 2\");\n        }\n      } else if (m_sign == sign_interval::GEZ) {\n        switch (o.m_sign) {\n        case sign_interval::GTZ:\n        case sign_interval::GEZ:\n          return sign_t(sign_interval::GEZ);\n        case sign_interval::LTZ:\n        case sign_interval::LEZ:\n          return sign_t(sign_interval::LEZ);\n        default:\n          CRAB_ERROR(\"sign::operator* unreachable 3\");\n        }\n      }\n    }\n    CRAB_ERROR(\"sign::operator* unreachable 4\");\n  }\n\n  // signed division\n  sign_t operator/(const sign_t &o) const {\n    if (is_bottom() || o.is_bottom()) {\n      return bottom();\n    } else if (o.equal_zero()) {\n      return bottom();\n    } else if (equal_zero()) {\n      return *this;\n    } else if (is_top() || o.is_top()) {\n      return top();\n    } else if (not_equal_zero() || o.not_equal_zero()) {\n      return top();\n    } else {\n      // Once we exclude top, bottom, zero, and non-zero\n      // signed division is like multiplication\n      return (*this) * o;\n    }\n  }\n\n  // division and remainder operations\n\n  sign_t UDiv(const sign_t &o) const { return defaultOp(o); }\n\n  sign_t SRem(const sign_t &o) const { return defaultOp(o); }\n\n  sign_t URem(const sign_t &o) const { return defaultOp(o); }\n\n  // bitwise operations\n  sign_t And(const sign_t &o) const {\n    // zero is special\n    if (is_bottom() || o.is_bottom()) {\n      return bottom();\n    } else {\n      if (equal_zero() || o.equal_zero()) {\n        return sign_t(sign_interval::EQZ);\n      } else {\n        return top();\n      }\n    }\n  }\n\n  sign_t Or(const sign_t &o) const {\n    // zero is special\n    if (is_bottom() || o.is_bottom()) {\n      return bottom();\n    } else {\n      if (equal_zero()) {\n        return o;\n      } else if (o.equal_zero()) {\n        return *this;\n      } else {\n        return top();\n      }\n    }\n  }\n\n  sign_t Xor(const sign_t &o) const { return Or(o); }\n\n  sign_t Shl(const sign_t &o) const { return shiftOp(o); }\n\n  sign_t LShr(const sign_t &o) const { return shiftOp(o); }\n\n  sign_t AShr(const sign_t &o) const { return shiftOp(o); }\n\n  void write(crab::crab_os &o) const {\n    switch (m_sign) {\n    case sign_interval::BOT:\n      o << \"_|_\";\n      return;\n    case sign_interval::LTZ:\n      o << \"[-oo,-1]\";\n      return;\n    case sign_interval::GTZ:\n      o << \"[1,+oo]\";\n      return;\n    case sign_interval::EQZ:\n      o << \"[0,0]\";\n      return;\n    case sign_interval::NEZ:\n      o << \"[-oo,-1] U [1,+oo]\";\n      return;\n    case sign_interval::GEZ:\n      o << \"[0,+oo]\";\n      return;\n    case sign_interval::LEZ:\n      o << \"[-oo,0]\";\n      return;\n    default: /*sign_interval::TOP*/\n      o << \"[-oo,+oo]\";\n    }\n  }\n\n  friend inline crab_os &operator<<(crab_os &o, const sign_t &c) {\n    c.write(o);\n    return o;\n  }\n};\n\ntemplate <typename Number, typename VariableName>\nclass sign_domain final : public crab::domains::abstract_domain_api<\n                              sign_domain<Number, VariableName>> {\npublic:\n  using sign_domain_t = sign_domain<Number, VariableName>;\n  using abstract_domain_t = crab::domains::abstract_domain_api<sign_domain_t>;\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::interval_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::reference_constraint_t;\n  using typename abstract_domain_t::variable_or_constant_t;\n  using typename abstract_domain_t::variable_t;\n  using typename abstract_domain_t::variable_vector_t;\n  using typename abstract_domain_t::variable_or_constant_vector_t;    \n  using sign_t = sign<Number>;\n  using number_t = Number;\n  using varname_t = VariableName;\n\nprivate:\n  using interval_domain_t = ikos::interval_domain<number_t, varname_t>;\n  using separate_domain_t = ikos::separate_domain<variable_t, sign_t>;\n\nprivate:\n  separate_domain_t m_env;\n\n  sign_domain(separate_domain_t &&env) : m_env(std::move(env)) {}\n\n  void solve_constraints(const linear_constraint_system_t &csts) {\n\n    // Solve < and > constraints\n    auto solve_strict_inequality = [this](const variable_t &v, sign_t rhs, bool is_less_than) {\n          sign_t lhs = m_env[v];\n\t  CRAB_LOG(\"sign-domain\",\n\t\t   crab::outs() << v << \"=\" << lhs;\n\t\t   if (is_less_than) {\n\t\t     crab::outs() << \" < \";\n\t\t   } else {\n\t\t     crab::outs() << \" > \";\n\t\t   }\n\t\t   crab::outs() << rhs << \"\\n\";);\n\t  \n\t  if (rhs.equal_zero()) {\n\t    m_env.set(v, m_env[v] & (is_less_than ?\n\t\t\t\t     sign_t::mk_less_than_zero():\n\t\t\t\t     sign_t::mk_greater_than_zero()));\n\t    CRAB_LOG(\"sign-domain\",\n\t\t     crab::outs() << \"\\t\" << \"Refined \" << v  << \"=\" << m_env[v] << \"\\n\";);\n\t    if (is_bottom()) return;\t    \n\t  } else {\n\t    if (!is_less_than) {\n\t      std::swap(lhs, rhs);\n\t    }\n\t    if ((lhs.greater_than_zero() || lhs.greater_or_equal_than_zero()) &&\n\t\t(rhs.less_than_zero() || rhs.less_or_equal_than_zero())) {\n\t      set_to_bottom();\n\t      CRAB_LOG(\"sign-domain\",\n\t\t       crab::outs() << \"\\t\" << \"Refined _|_\\n\";);\n\t      return;\n\t    }\n\t  }};\n\n    // Solve <= and >= constraints\n    auto solve_inequality = [this](const variable_t &v, sign_t rhs, bool is_less_equal) {\n          sign_t lhs = m_env[v];\n\t  CRAB_LOG(\"sign-domain\",\n\t\t   crab::outs() << v << \"=\" << lhs;\n\t\t   if (is_less_equal) {\n\t\t     crab::outs() << \" <= \";\n\t\t   } else {\n\t\t     crab::outs() << \" >= \";\t\t     \n\t\t   }\n\t\t   crab::outs() << rhs << \"\\n\";);\n\t  \n\t  if (rhs.equal_zero()) {\n\t    m_env.set(v, m_env[v] & (is_less_equal ?\n\t\t\t\t     sign_t::mk_less_or_equal_than_zero():\n\t\t\t\t     sign_t::mk_greater_or_equal_than_zero()));\n\t    CRAB_LOG(\"sign-domain\",\n\t\t     crab::outs() << \"\\t\" << \"Refined \" << v  << \"=\" << m_env[v] << \"\\n\";);\n\t    if (is_bottom()) return;\n\t  } else {\n\t    if (!is_less_equal) {\n\t      std::swap(lhs, rhs);\n\t    }\n\t    if (lhs.greater_or_equal_than_zero() && rhs.less_than_zero()) {\n\t      set_to_bottom();\n\t      CRAB_LOG(\"sign-domain\",\n\t\t       crab::outs() << \"\\t\" << \"Refined _|_\\n\";);\t      \n\t      return;\n\t    }\n\t    if (lhs.greater_than_zero() && (rhs.less_than_zero() || rhs.less_or_equal_than_zero())) {\n\t      set_to_bottom();\n\t      CRAB_LOG(\"sign-domain\",\n\t\t       crab::outs() << \"\\t\" << \"Refined _|_\\n\";);\n\t      return;\n\t    }\n\t  }};\n    \n    if (!is_bottom()) {\n      for (auto const &c : csts) {\n        if (c.is_inequality() && c.is_unsigned()) {\n          continue;\n        }\n        if (c.is_tautology()) {\n          continue;\n        }\n        if (c.is_contradiction()) {\n          set_to_bottom();\n          return;\n        }\n\n\tstd::vector<std::pair<variable_t, sign_t>> less_than, less_equal;\n\tstd::vector<std::pair<variable_t, sign_t>> greater_than, greater_equal;\n\tstd::vector<std::pair<variable_t, sign_t>> equal, not_equal;\n\t\n        extract_sign_constraints(c, less_than, less_equal,\n\t\t\t\t greater_than, greater_equal, equal, not_equal);\n\n\tCRAB_LOG(\"sign-domain\",\n\t\t crab::outs() << \"Adding \" << c << \"\\n\";);\n\n\tfor (auto kv: less_than) {\n\t  solve_strict_inequality(kv.first, kv.second, true /*less_than*/);\n\t}\n\tfor (auto kv: greater_than) {\n\t  solve_strict_inequality(kv.first, kv.second, false /*greater_than*/);\n\t}\n\n\tfor (auto kv: less_equal) {\n\t  solve_inequality(kv.first, kv.second, true /*less_equal_than*/);\t  \n\t}\n\n\tfor (auto kv: greater_equal) {\n\t  solve_inequality(kv.first, kv.second, false /*greater_equal_than*/);\t  \n\t}\n\t\t\n\tfor (auto kv: equal) {\n          sign_t lhs = m_env[kv.first];\n          sign_t rhs = kv.second;\n\t  CRAB_LOG(\"sign-domain\",\n\t\t   crab::outs() << kv.first << \"=\" << lhs << \" == \" << rhs << \"\\n\";);\n\t  m_env.set(kv.first, m_env[kv.first] & rhs);\n\t  CRAB_LOG(\"sign-domain\",\n\t\t   crab::outs() << \"\\t\" << \"Refined \" << kv.first  << \"=\" << m_env[kv.first] << \"\\n\";);\n\t  if (is_bottom()) return;\t  \n\t}\n\n\tfor (auto kv: not_equal) {\n          sign_t lhs = m_env[kv.first];\n          sign_t rhs = kv.second;\n\t  CRAB_LOG(\"sign-domain\",\n\t\t   crab::outs() << kv.first << \"=\" << lhs << \" != \" << rhs << \"\\n\";);\n\t  if (rhs.equal_zero()) {\n\t    m_env.set(kv.first,\n\t\t      m_env[kv.first] & sign_t::mk_not_equal_zero());\n\t    CRAB_LOG(\"sign-domain\",\n\t\t     crab::outs() << \"\\t\" << \"Refined \" << kv.first  << \"=\" << m_env[kv.first] << \"\\n\";);\n\t    if (is_bottom()) return;\t    \n\t  } else if (rhs.not_equal_zero()) {\n\t    m_env.set(kv.first, m_env[kv.first] & sign_t::mk_equal_zero());\n\t    CRAB_LOG(\"sign-domain\",\n\t\t     crab::outs() << \"\\t\" << \"Refined \" << kv.first  << \"=\" << m_env[kv.first] << \"\\n\";);\n\t    if (is_bottom()) return;\t    \n\t  }\n\t}\n      }\n    }\n  }\n\n  // Extract constraints of the form v OP sign where OP = {<, <=, >, >=, ==, != }\n  void\n  extract_sign_constraints(const linear_constraint_t &c,\n\t\t\t   std::vector<std::pair<variable_t, sign_t>> &less_than,\n                           std::vector<std::pair<variable_t, sign_t>> &less_equal,\n\t\t\t   std::vector<std::pair<variable_t, sign_t>> &greater_than,\n                           std::vector<std::pair<variable_t, sign_t>> &greater_equal,\n\t\t\t   std::vector<std::pair<variable_t, sign_t>> &equal,\n\t\t\t   std::vector<std::pair<variable_t, sign_t>> &not_equal) {\n    auto e = c.expression();\n    for (auto kv : e) {\n      variable_t pivot = kv.second;\n      sign_t res = compute_residual(e, pivot) / sign_t(kv.first);\n      if (res.is_bottom()) {\n\t// this shouldn't happen\n\tcontinue;\n      }\n      if (!res.is_top()) {\n\tif (c.is_strict_inequality()) {\n\t  if (kv.first < number_t(0)) {\n\t    greater_than.push_back({pivot,res});\n\t  } else {\n\t    less_than.push_back({pivot,res});\n\t  } \n\t} else if (c.is_inequality()) {\n\t  if (kv.first < number_t(0)) {\n\t    greater_equal.push_back({pivot,res});\n\t  } else {\n\t    less_equal.push_back({pivot,res});\n\t  } \n\t} else if (c.is_equality()) {\n\t  equal.push_back({pivot,res});\t  \t  \n\t} else if (c.is_disequation()) {\n\t  not_equal.push_back({pivot,res});\t  \n\t}\n      }\n    }\n  }\n\n  sign_t compute_residual(const linear_expression_t &e, variable_t pivot) {\n    sign_t residual(-e.constant());\n    for (auto kv : e) {\n      const variable_t &v = kv.second;\n      if (v.index() != pivot.index()) {\n        residual = residual - (sign_t(kv.first) * m_env[v]);\n      }\n    }\n    return residual;\n  }\n\n  sign_t eval_expr(const linear_expression_t &expr) const {\n    if (is_bottom())\n      return sign_t::bottom();\n    \n    sign_t r(expr.constant());\n    for (auto kv : expr) {\n      sign_t c(kv.first);\n      r = r + (c * m_env[kv.second]);\n    }\n    return r;\n  }\n\npublic:\n  sign_domain_t make_top() const override {\n    return sign_domain_t(separate_domain_t::top());\n  }\n\n  sign_domain_t make_bottom() const override {\n    return sign_domain_t(separate_domain_t::bottom());\n  }\n\n  void set_to_top() override {\n    sign_domain abs(separate_domain_t::top());\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() override {\n    sign_domain abs(separate_domain_t::bottom());\n    std::swap(*this, abs);\n  }\n\n  sign_t get_sign(const variable_t &v) const {\n    return m_env[v];\n  }\n\n  void set_sign(const variable_t &v, sign_t s) {\n    m_env.set(v, s);\n  }\n  \n  sign_domain() : m_env(separate_domain_t::top()) {}\n\n  sign_domain(const sign_domain_t &e) : m_env(e.m_env) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n  }\n\n  sign_domain(sign_domain_t &&e) : m_env(std::move(e.m_env)) {}\n\n  sign_domain_t &operator=(const sign_domain_t &o) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n    if (this != &o) {\n      m_env = o.m_env;\n    }\n    return *this;\n  }\n\n  sign_domain_t &operator=(sign_domain_t &&o) {\n    if (this != &o) {\n      m_env = std::move(o.m_env);\n    }\n    return *this;\n  }\n\n  bool is_bottom() const override { return m_env.is_bottom(); }\n\n  bool is_top() const override { return m_env.is_top(); }\n\n  bool operator<=(const sign_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.leq\");\n    crab::ScopedCrabStats __st__(domain_name() + \".leq\");\n    return (m_env <= o.m_env);\n  }\n\n  void operator|=(const sign_domain_t &o) override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n    CRAB_LOG(\"sign-domain\",\n             crab::outs() << \"Join \" << m_env << \" and \" << o.m_env << \"\\n\";);\n    m_env = m_env | o.m_env;\n    CRAB_LOG(\"sign-domain\", crab::outs() << \"Res=\" << m_env << \"\\n\";);\n  }\n\n  sign_domain_t operator|(const sign_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n    return (m_env | o.m_env);\n  }\n\n  sign_domain_t operator&(const sign_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.meet\");\n    crab::ScopedCrabStats __st__(domain_name() + \".meet\");\n    return (m_env & o.m_env);\n  }\n\n  sign_domain_t operator||(const sign_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.widening\");\n    crab::ScopedCrabStats __st__(domain_name() + \".widening\");\n    return (m_env | o.m_env);\n  }\n\n  sign_domain_t widening_thresholds(\n      const sign_domain_t &o,\n      const crab::iterators::thresholds<number_t> &ts) const override {\n    crab::CrabStats::count(domain_name() + \".count.widening\");\n    crab::ScopedCrabStats __st__(domain_name() + \".widening\");\n    return (m_env | o.m_env);\n  }\n\n  sign_domain_t operator&&(const sign_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.narrowing\");\n    crab::ScopedCrabStats __st__(domain_name() + \".narrowing\");\n    return (m_env & o.m_env);\n  }\n\n  void operator-=(const variable_t &v) override {\n    crab::CrabStats::count(domain_name() + \".count.forget\");\n    crab::ScopedCrabStats __st__(domain_name() + \".forget\");\n    m_env -= v;\n  }\n\n  interval_t operator[](const variable_t &v) override {\n    return m_env[v].to_interval();\n  }\n\n  void operator+=(const linear_constraint_system_t &csts) override {\n    crab::CrabStats::count(domain_name() + \".count.add_constraints\");\n    crab::ScopedCrabStats __st__(domain_name() + \".add_constraints\");\n    solve_constraints(csts);\n  }\n\n  void assign(const variable_t &x, const linear_expression_t &e) override {\n    crab::CrabStats::count(domain_name() + \".count.assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".assign\");\n    CRAB_LOG(\"sign-domain\",\n\t     crab::outs() << x << \" := \" << e << \"\\n\";);\n    if (boost::optional<variable_t> v = e.get_variable()) {\n      m_env.set(x, m_env[(*v)]);\n    } else {\n      m_env.set(x, eval_expr(e));\n    }\n    CRAB_LOG(\"sign-domain\",\n\t     crab::outs() << \"RES=\" << m_env[x] << \"\\n\";);\n  }\n\n  void apply(crab::domains::arith_operation_t op, const variable_t &x,\n             const variable_t &y, const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    sign_t yi = m_env[y];\n    sign_t zi = m_env[z];\n    sign_t xi = sign_t::bottom();\n\n    switch (op) {\n    case crab::domains::OP_ADDITION:\n      xi = yi + zi;\n      break;\n    case crab::domains::OP_SUBTRACTION:\n      xi = yi - zi;\n      break;\n    case crab::domains::OP_MULTIPLICATION:\n      xi = yi * zi;\n      break;\n    case crab::domains::OP_SDIV:\n      xi = yi / zi;\n      break;\n    case crab::domains::OP_UDIV:\n      xi = yi.UDiv(zi);\n      break;\n    case crab::domains::OP_SREM:\n      xi = yi.SRem(zi);\n      break;\n    case crab::domains::OP_UREM:\n      xi = yi.URem(zi);\n      break;\n    default:\n      CRAB_ERROR(\"Operation \", op, \" not supported\");\n    }\n    m_env.set(x, xi);\n  }\n\n  void apply(crab::domains::arith_operation_t op, const variable_t &x,\n             const variable_t &y, number_t k) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    sign_t yi = m_env[y];\n    sign_t zi(k);\n    sign_t xi = sign_t::bottom();\n\n    switch (op) {\n    case crab::domains::OP_ADDITION:\n      xi = yi + zi;\n      break;\n    case crab::domains::OP_SUBTRACTION:\n      xi = yi - zi;\n      break;\n    case crab::domains::OP_MULTIPLICATION:\n      xi = yi * zi;\n      break;\n    case crab::domains::OP_SDIV:\n      xi = yi / zi;\n      break;\n    case crab::domains::OP_UDIV:\n      xi = yi.UDiv(zi);\n      break;\n    case crab::domains::OP_SREM:\n      xi = yi.SRem(zi);\n      break;\n    case crab::domains::OP_UREM:\n      xi = yi.URem(zi);\n      break;\n    default:\n      CRAB_ERROR(\"Operation \", op, \" not supported\");\n    }\n    m_env.set(x, xi);\n  }\n\n  // intrinsics operations\n  void intrinsic(std::string name,\n\t\t const variable_or_constant_vector_t &inputs,\n                 const variable_vector_t &outputs) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", domain_name());\n  }\n\n  void backward_intrinsic(std::string name,\n\t\t\t  const variable_or_constant_vector_t &inputs,\n                          const variable_vector_t &outputs,\n                          const sign_domain_t &invariant) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", domain_name());\n  }\n\n  // backward arithmetic operations\n  void backward_assign(const variable_t &x, const linear_expression_t &e,\n                       const sign_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_assign\");\n    // TODO\n  }\n\n  void backward_apply(crab::domains::arith_operation_t op, const variable_t &x,\n                      const variable_t &y, number_t z,\n                      const sign_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_apply\");\n    // TODO\n  }\n\n  void backward_apply(crab::domains::arith_operation_t op, const variable_t &x,\n                      const variable_t &y, const variable_t &z,\n                      const sign_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_apply\");\n    // TODO\n  }\n\n  // cast operations\n  void apply(crab::domains::int_conv_operation_t /*op*/, const variable_t &dst,\n             const variable_t &src) override {\n    // ignore the widths\n    assign(dst, src);\n  }\n\n  // bitwise operations\n  void apply(crab::domains::bitwise_operation_t op, const variable_t &x,\n             const variable_t &y, const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    sign_t yi = m_env[y];\n    sign_t zi = m_env[z];\n    sign_t xi = sign_t::bottom();\n\n    switch (op) {\n    case crab::domains::OP_AND: {\n      xi = yi.And(zi);\n      break;\n    }\n    case crab::domains::OP_OR: {\n      xi = yi.Or(zi);\n      break;\n    }\n    case crab::domains::OP_XOR: {\n      xi = yi.Xor(zi);\n      break;\n    }\n    case crab::domains::OP_SHL: {\n      xi = yi.Shl(zi);\n      break;\n    }\n    case crab::domains::OP_LSHR: {\n      xi = yi.LShr(zi);\n      break;\n    }\n    case crab::domains::OP_ASHR: {\n      xi = yi.AShr(zi);\n      break;\n    }\n    default:\n      CRAB_ERROR(\"unreachable\");\n    }\n    m_env.set(x, xi);\n  }\n\n  void apply(crab::domains::bitwise_operation_t op, const variable_t &x,\n             const variable_t &y, number_t k) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    sign_t yi = m_env[y];\n    sign_t zi(k);\n    sign_t xi = sign_t::bottom();\n\n    switch (op) {\n    case crab::domains::OP_AND: {\n      xi = yi.And(zi);\n      break;\n    }\n    case crab::domains::OP_OR: {\n      xi = yi.Or(zi);\n      break;\n    }\n    case crab::domains::OP_XOR: {\n      xi = yi.Xor(zi);\n      break;\n    }\n    case crab::domains::OP_SHL: {\n      xi = yi.Shl(zi);\n      break;\n    }\n    case crab::domains::OP_LSHR: {\n      xi = yi.LShr(zi);\n      break;\n    }\n    case crab::domains::OP_ASHR: {\n      xi = yi.AShr(zi);\n      break;\n    }\n    default:\n      CRAB_ERROR(\"unreachable\");\n    }\n    m_env.set(x, xi);\n  }\n\n  virtual void select(const variable_t &lhs, const linear_constraint_t &cond,\n                      const linear_expression_t &e1,\n                      const linear_expression_t &e2) override {\n    crab::CrabStats::count(domain_name() + \".count.select\");\n    crab::ScopedCrabStats __st__(domain_name() + \".select\");\n\n    if (!is_bottom()) {\n      sign_domain_t inv1(*this);\n      inv1 += cond;\n      if (inv1.is_bottom()) {\n        assign(lhs, e2);\n        return;\n      }\n\n      sign_domain_t inv2(*this);\n      inv2 += cond.negate();\n      if (inv2.is_bottom()) {\n        assign(lhs, e1);\n        return;\n      }\n\n      m_env.set(lhs, eval_expr(e1) | eval_expr(e2));\n    }\n  }\n\n  /// sign_domain implements only standard abstract operations of\n  /// a numerical domain so it is intended to be used as a leaf domain\n  /// in the hierarchy of domains.\n  BOOL_OPERATIONS_NOT_IMPLEMENTED(sign_domain_t)\n  ARRAY_OPERATIONS_NOT_IMPLEMENTED(sign_domain_t)\n  REGION_AND_REFERENCE_OPERATIONS_NOT_IMPLEMENTED(sign_domain_t)\n\n  void forget(const variable_vector_t &variables) override {\n    if (is_bottom() || is_top()) {\n      return;\n    }\n    for (auto const &var : variables) {\n      this->operator-=(var);\n    }\n  }\n\n  void project(const variable_vector_t &variables) override {\n    crab::CrabStats::count(domain_name() + \".count.project\");\n    crab::ScopedCrabStats __st__(domain_name() + \".project\");\n\n    m_env.project(variables);\n  }\n\n  void rename(const variable_vector_t &from,\n              const variable_vector_t &to) override {\n    crab::CrabStats::count(domain_name() + \".count.rename\");\n    crab::ScopedCrabStats __st__(domain_name() + \".rename\");\n\n    m_env.rename(from, to);\n  }\n\n  void expand(const variable_t &x, const variable_t &new_x) override {\n    crab::CrabStats::count(domain_name() + \".count.expand\");\n    crab::ScopedCrabStats __st__(domain_name() + \".expand\");\n\n    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    m_env.set(new_x, m_env[x]);\n  }\n\n  void normalize() override {}\n\n  void minimize() override {}\n\n  void write(crab::crab_os &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.write\");\n    crab::ScopedCrabStats __st__(domain_name() + \".write\");\n\n    m_env.write(o);\n  }\n\n  linear_constraint_system_t to_linear_constraint_system() const override {\n    crab::CrabStats::count(domain_name() +\n                           \".count.to_linear_constraint_system\");\n    crab::ScopedCrabStats __st__(domain_name() +\n                                 \".to_linear_constraint_system\");\n\n    linear_constraint_system_t csts;\n\n    if (this->is_bottom()) {\n      csts += linear_constraint_t::get_false();\n      return csts;\n    }\n\n    for (auto it = m_env.begin(); it != m_env.end(); ++it) {\n      const variable_t &v = it->first;\n      const sign_t &s = it->second;\n      if (s.equal_zero()) {\n        csts += linear_constraint_t(v == number_t(0));\n      } else if (s.less_than_zero()) {\n        csts += linear_constraint_t(v < number_t(0));\n      } else if (s.greater_than_zero()) {\n        csts += linear_constraint_t(v > number_t(0));\n      } else if (s.less_or_equal_than_zero()) {\n        csts += linear_constraint_t(v <= number_t(0));\n      } else if (s.greater_or_equal_than_zero()) {\n        csts += linear_constraint_t(v >= number_t(0));\n      } else {\n        // we cannot represent not_equal_zero as a linear constraint\n        continue;\n      }\n    }\n    return csts;\n  }\n\n  disjunctive_linear_constraint_system_t\n  to_disjunctive_linear_constraint_system() const override {\n    auto lin_csts = to_linear_constraint_system();\n    if (lin_csts.is_false()) {\n      return disjunctive_linear_constraint_system_t(true /*is_false*/);\n    } else if (lin_csts.is_true()) {\n      return disjunctive_linear_constraint_system_t(false /*is_false*/);\n    } else {\n      return disjunctive_linear_constraint_system_t(lin_csts);\n    }\n  }\n\n  std::string domain_name() const override { return \"SignDomain\"; }\n\n}; // class sign_domain\n} // namespace domains\n} // namespace crab\n\nnamespace crab {\nnamespace domains {\ntemplate <typename Number, typename VariableName>\nstruct abstract_domain_traits<sign_domain<Number, VariableName>> {\n  using number_t = Number;\n  using varname_t = VariableName;\n};\n\n} // namespace domains\n} // namespace crab\n", "meta": {"hexsha": "914d098262ea964757770f8b534b2a8b8867fdaa", "size": 40907, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/sign_domain.hpp", "max_stars_repo_name": "LinerSu/crab", "max_stars_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 152.0, "max_stars_repo_stars_event_min_datetime": "2016-02-28T06:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:44:56.000Z", "max_issues_repo_path": "include/crab/domains/sign_domain.hpp", "max_issues_repo_name": "LinerSu/crab", "max_issues_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-07-03T06:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:09:32.000Z", "max_forks_repo_path": "include/crab/domains/sign_domain.hpp", "max_forks_repo_name": "LinerSu/crab", "max_forks_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-11-22T15:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T00:46:57.000Z", "avg_line_length": 30.1451731761, "max_line_length": 95, "alphanum_fraction": 0.5924902828, "num_tokens": 10783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511579973932, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6177047588865506}}
{"text": "/*\n * Copyright (c) 2011 Seiya Tokui <beam.web@gmail.com>\n * Copyright (c) 2014 Burkhard Ritter <burkhard@ualberta.ca>\n * This code is distributed under the MIT license.\n *\n * A very simple example program demonstrating how to use Arpaca.\n *\n * To compile this program: \n * g++ \\\n *    -I [/path/to/eigen] \\\n *    really_simple_example.cpp \\\n *    -L [/path/to/libarpack.a] \\\n *    -larpack \\\n *    -o really_simple_example\n *\n * This assumes that arpaca.hpp is in the same directory.\n */\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include \"arpaca.hpp\"\nusing namespace Eigen;\nusing namespace arpaca;\n\nint main()\n{\n    // Matrix dimension\n    const int n_dim = 4;\n    // Number of eigenvalues to compute\n    const int n_ev = 3;\n    // Which eigenvalues to compute\n    const EigenvalueType type = ALGEBRAIC_SMALLEST;\n\n    // A self-adjoint random dense matrix of size n_dim x n_dim and the\n    // corresponding sparse matrix\n    MatrixXd dm = MatrixXd::Random(n_dim,n_dim).selfadjointView<Upper>();\n    SparseMatrix<double> sm = dm.sparseView();\n\n    // Solve for the eigenvalues\n    SymmetricEigenSolver<double> s = Solve(sm, n_ev, type);\n\n    // Output\n    std::cout << \"Matrix: \" << std::endl << std::endl\n              << dm << std::endl << std::endl << std::endl\n              << \"Its \" << n_ev << \" smallest eigenvalues: \"\n              << std::endl << std::endl\n              << s.eigenvalues() << std::endl << std::endl\n              << \"And the corresponding eigenvectos: \"\n              << std::endl << std::endl\n              << s.eigenvectors() << std::endl;\n}\n", "meta": {"hexsha": "298da131d5c6d9feb79abf532164e621a57ccf97", "size": 1597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "really_simple_example.cpp", "max_stars_repo_name": "meznom/arpaca", "max_stars_repo_head_hexsha": "91af2357a73ed7f5cd0d300e40283a59244c7c25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-05T17:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-05T17:29:06.000Z", "max_issues_repo_path": "really_simple_example.cpp", "max_issues_repo_name": "meznom/arpaca", "max_issues_repo_head_hexsha": "91af2357a73ed7f5cd0d300e40283a59244c7c25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "really_simple_example.cpp", "max_forks_repo_name": "meznom/arpaca", "max_forks_repo_head_hexsha": "91af2357a73ed7f5cd0d300e40283a59244c7c25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1320754717, "max_line_length": 73, "alphanum_fraction": 0.6161552912, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.617704755863222}}
{"text": "#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n#include <boost/numeric/bindings/ublas/matrix_sparse.hpp>\n#include <boost/numeric/bindings/mumps/mumps_driver.hpp>\n#include <iostream>\n#include <fstream>\n#include <complex>\n\ntemplate <typename T>\nint test(double eps)\n{\n  namespace ublas = ::boost::numeric::ublas ;\n  namespace mumps = ::boost::numeric::bindings::mumps ;\n\n\n  int const n = 10 ;\n\n  typedef ublas::coordinate_matrix<T, ublas::column_major, 1, ublas::unbounded_array<int> > coo_type ;\n\n  coo_type coo(n, n, n + 6) ;\n\n  for(int i=0; i<n; ++i) coo(i,i) = i+1.0 ;\n  coo(2,3) = T(1.0) ;\n  coo(2,4) = T(1.0) ;\n  coo(5,6) = T(-1.0) ;\n  coo(2,6) = T(1.0) ;\n  coo(9,0) = T(1.0) ;\n  coo(2,7) = T(-1.0) ;\n\n  coo.sort() ;\n  std::cout << \"matrix \" << coo << std::endl ;\n\n  ublas::vector<T> v(10) ;\n  ublas::vector<T> w(10) ;\n\n  std::fill(w.begin(), w.end(), 1.0) ;\n\n  for(int i=1; i<n; ++i)\n  {\n    w(i) += w(i-1) ;\n  }\n\n  for(int i=0; i<n; ++i)\n  {\n    v[i] = T(coo(i,i)) * w[i] ;\n  }\n  v[2] += T(coo(2,3)) * w[3] ;\n  v[2] += T(coo(2,4)) * w[4] ;\n  v[5] += T(coo(5,6)) * w[6] ;\n  v[2] += T(coo(2,6)) * w[6] ;\n  v[9] += T(coo(9,0)) * w[0] ;\n  v[2] += T(coo(2,7)) * w[7] ;\n  std::cout << \"rhs : \" << v << std::endl ;\n\n  mumps::mumps< coo_type > mumps_coo ;\n\n  mumps_coo.icntl[2]=mumps_coo.icntl[3] = 0 ;\n\n  // Analysis\n  mumps_coo.job = 1 ;\n  matrix_integer_data(mumps_coo, coo) ;\n  driver(mumps_coo) ;\n\n  // Factorization\n  mumps_coo.job = 2 ;\n  matrix_value_data(mumps_coo, coo) ;\n  driver(mumps_coo) ;\n\n  // Solve\n  mumps_coo.job = 3 ;\n  rhs_sol_value_data(mumps_coo, v) ;\n  driver(mumps_coo) ;\n\n  std::cout << \"w : \" << w << std::endl ;\n  std::cout << \"v : \" << v << std::endl ;\n\n  if(norm_2(v - w) > eps * norm_2(v)) return 1 ;\n\n  return 0 ;\n}\n\nint main()\n{\n  if(test<float>(1e-5)) return 1 ;\n  if(test<double>(1e-10)) return 2 ;\n  if(test< std::complex<float> >(1e-5)) return 3 ;\n  if(test< std::complex<double> >(1e-10)) return 4 ;\n  return 0 ;\n}\n", "meta": {"hexsha": "4cf1750f5593c1d6879b60de3810f1d4ca11aad9", "size": 2084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/mumps/test/mumps_ublas.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/mumps/test/mumps_ublas.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/mumps/test/mumps_ublas.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 22.652173913, "max_line_length": 102, "alphanum_fraction": 0.5729366603, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6177047511104697}}
{"text": "// Implement SparseLibrary requirements using Eigen\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n#include <Eigen/SparseLU>\n\nstruct EigenShim {\n    using value_t = double;\n    using triplet_t = Eigen::Triplet<value_t>;\n\n    template<typename Value>\n    struct sparse_wrapper_t {\n        using wrapped_t = Eigen::SparseMatrix<Value>;\n        using index_t = typename wrapped_t::StorageIndex;\n        template<typename Iter>     // or use ForwardIterator concept\n        sparse_wrapper_t(index_t rows, index_t cols, Iter a, Iter b) : mat_(rows, cols) {\n            mat_.setFromTriplets(a, b);\n        }\n        sparse_wrapper_t(wrapped_t mat) : mat_(std::move(mat)) {}\n\n        // define the product of two sparse wrappers\n        friend sparse_wrapper_t operator*(sparse_wrapper_t const& a, sparse_wrapper_t const& b) {\n            return Eigen::SparseMatrix<value_t>(a.wrapped() * b.wrapped());\n        }\n\n        friend std::ostream & operator<<(std::ostream& os, sparse_wrapper_t const& m) {\n            using namespace Eigen;\n            IOFormat OctaveFmt(FullPrecision, 0, \", \", \";\\n\", \"\", \"\", \"[\", \"]\");\n\n            Matrix<value_t, Dynamic, Dynamic> dense = m.wrapped();   // convert to dense\n\n            os << dense.format(OctaveFmt);\n            return os;\n        }\n\n        wrapped_t const & wrapped() const { return mat_; }\n\n    private:\n\n        wrapped_t mat_;\n    };\n\n    using sparsemat_t = sparse_wrapper_t<value_t>;\n    using index_t = sparsemat_t::index_t;\n\n    template<typename Value, typename Index>\n    struct lu_wrapper_t {\n        using wrapped_t = Eigen::SparseLU<Eigen::SparseMatrix<Value>, Eigen::COLAMDOrdering<Index>>;\n\n        lu_wrapper_t( sparsemat_t const & mat ) : lu_(mat.wrapped()) {\n            assert(lu_.info() == Eigen::Success);\n        }\n\n        sparse_wrapper_t<Value> solve( sparsemat_t const & rhs ) const {\n            return sparse_wrapper_t<Value>(lu_.solve(rhs.wrapped()));\n        }\n\n    private:\n        wrapped_t lu_;\n    };\n\n    template<typename Value, typename Index>\n    struct qr_wrapper_t {\n        using wrapped_t = Eigen::SparseQR<Eigen::SparseMatrix<Value>, Eigen::COLAMDOrdering<Index>>;\n\n        qr_wrapper_t( sparsemat_t const & mat ) : qr_(mat.wrapped()) {}\n\n        sparsemat_t Q() const {\n            using namespace Eigen;\n            // Sadly Eigen cannot directly return the Q as a sparse matrix\n            // What it *can* do is multiply times a dense matrix\n            Matrix<value_t, Dynamic, Dynamic> identity(qr_.rows(), qr_.rank());\n            identity.setIdentity();\n\n            Matrix<value_t, Dynamic, Dynamic> result = qr_.matrixQ() * identity;\n\n            // finally, convert to sparse\n            return SparseMatrix<value_t>(result.sparseView());\n        }\n\n    private:\n        wrapped_t qr_;\n    };\n\n    using lu_t = lu_wrapper_t<value_t, index_t>;\n    using qr_t = qr_wrapper_t<value_t, index_t>;\n\n\n};\n\n", "meta": {"hexsha": "d406fc5048b6a030640c940bc00a6901a6c1bf16", "size": 2901, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "policies/eigen_shim.hpp", "max_stars_repo_name": "jefftrull/SparseMatrixLibraries", "max_stars_repo_head_hexsha": "0eeb36e56dc78566f093531d2718d168d788a708", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-04-30T10:29:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T23:31:34.000Z", "max_issues_repo_path": "policies/eigen_shim.hpp", "max_issues_repo_name": "jefftrull/SparseMatrixLibraries", "max_issues_repo_head_hexsha": "0eeb36e56dc78566f093531d2718d168d788a708", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "policies/eigen_shim.hpp", "max_forks_repo_name": "jefftrull/SparseMatrixLibraries", "max_forks_repo_head_hexsha": "0eeb36e56dc78566f093531d2718d168d788a708", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-22T23:44:34.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-22T23:44:34.000Z", "avg_line_length": 32.2333333333, "max_line_length": 100, "alphanum_fraction": 0.6211651155, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6176910883163413}}
{"text": "#include <vector>\n#include <random>\n#include <gtest/gtest.h>\n#include <boost/multiprecision/gmp.hpp>\nusing namespace std;\nnamespace bm = boost::multiprecision;\n\ntemplate<typename F>\nvoid digit_dc_inner(const vector<int> &num, int base, vector<int> &cur, int d, F &f) { // enumerate all [1, num] with same length\n    if (d == (int)num.size()) {\n        f(num, base, (int)num.size());\n        return;\n    }\n    for (int i = 0; i < num[d]; ++i) {\n        if (d == 0 && i == 0) continue;\n\n        cur.push_back(i);\n        f(cur, base, (int)num.size());\n        cur.pop_back();\n    }\n\n    cur.push_back(num[d]);\n    digit_dc_inner(num, base, cur, d + 1, f);\n    cur.pop_back();\n}\n\ntemplate<typename F>\nvoid digit_dc(const vector<int> &num, int base, F &f) { // enumerate all [1, num]\n    // shorter than num\n    for (int len = 1; len < (int)num.size(); ++len) {\n        for (int i = 1; i < base; ++i) {\n            vector<int> cur = {i};\n            f(cur, base, len);\n        }\n    }\n    // the same length with num\n    vector<int> cur;\n    digit_dc_inner<F>(num, base, cur, 0, f);\n}\n\nstd::mt19937 gen;\nstd::uniform_int_distribution<> dist_base(2, 20);\nstd::uniform_int_distribution<> dist_length(1, 100);\n\nvector<int> random_number(int length, int base) {\n    std::uniform_int_distribution<> dist0(1, base - 1);\n    std::uniform_int_distribution<> dist(0, base - 1);\n\n    vector<int> v;\n    for (int i = 0; i < length; ++i) {\n        if (i == 0) v.push_back(dist0(gen));\n        else v.push_back(dist(gen));\n    }\n    return v;\n}\nbm::mpz_int to_mpz(vector<int> num, int base) {\n    bm::mpz_int z = 0;\n    for (int i = 0; i < (int)num.size(); ++i)\n        z = z * base + num[i];\n    return z;\n}\n\nTEST(Random, Print) {\n    struct printer {\n        void operator()(const vector<int> &v, int base, int length) {\n            for (int i = 0; i < (int)v.size(); ++i) {\n                printf(\"%d\", v[i]);\n            }\n            for (int i = (int)v.size(); i < length; ++i)\n                printf(\"X\");\n            printf(\"\\n\");\n        }\n    };\n    int base = 10;\n    static const int TEST_SIZE = 3;\n\n    for (int test_case = 0; test_case < TEST_SIZE; ++test_case) {\n        int length = std::uniform_int_distribution<>(1, 10)(gen);\n        vector<int> num = random_number(length, base);\n\n        printer p;\n        digit_dc(num, base, p);\n    }\n}\n\nTEST(Random, Count) {\n    struct counter {\n        bm::mpz_int cnt = 0;\n        void operator()(const vector<int> &v, int base, int length) {\n            cnt += pow(bm::mpz_int(base), length - (int)v.size());\n        }\n    };\n\n    static const int TEST_SIZE = 500;\n    for (int test_case = 0; test_case < TEST_SIZE; ++test_case) {\n        int base = dist_base(gen);\n        int length = dist_length(gen);\n        vector<int> num = random_number(length, base);\n\n        bm::mpz_int expected = to_mpz(num, base);\n\n        counter c;\n        digit_dc(num, base, c);\n        bm::mpz_int answer = c.cnt;\n\n        EXPECT_EQ(expected, answer);\n    }\n}\nTEST(Random, Sum) {\n    struct summer {\n        bm::mpz_int cnt = 0;\n        void operator()(const vector<int> &v, int base, int length) {\n            int left = length - (int)v.size();\n            bm::mpz_int p = pow(bm::mpz_int(base), left);\n            cnt += to_mpz(v, base) * p * p;\n            cnt += p * (p - 1) / 2;\n        }\n    };\n\n    static const int TEST_SIZE = 100;\n    for (int test_case = 0; test_case < TEST_SIZE; ++test_case) {\n        int base = dist_base(gen);\n        int length = dist_length(gen);\n        vector<int> num = random_number(length, base);\n        bm::mpz_int z = to_mpz(num, base);\n        bm::mpz_int expected = z * (z + 1) / 2;\n\n        summer s;\n        digit_dc(num, base, s);\n        bm::mpz_int answer = s.cnt;\n\n        EXPECT_EQ(expected, answer);\n    }\n}\n\n", "meta": {"hexsha": "cade24e1ec135f678d0df1475632ec62b1390120", "size": 3788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/digit_dc_test.cpp", "max_stars_repo_name": "georeth/OJLIBS", "max_stars_repo_head_hexsha": "de59d4fd21255cc2f0a580db7726b634449e6885", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-03-26T03:54:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T13:10:43.000Z", "max_issues_repo_path": "test/digit_dc_test.cpp", "max_issues_repo_name": "georeth/OJLIBS", "max_issues_repo_head_hexsha": "de59d4fd21255cc2f0a580db7726b634449e6885", "max_issues_repo_licenses": ["MIT"], "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/digit_dc_test.cpp", "max_forks_repo_name": "georeth/OJLIBS", "max_forks_repo_head_hexsha": "de59d4fd21255cc2f0a580db7726b634449e6885", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-03-06T09:59:14.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-06T09:59:14.000Z", "avg_line_length": 27.8529411765, "max_line_length": 129, "alphanum_fraction": 0.5398627244, "num_tokens": 1084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6176910855924602}}
{"text": "// Copyright (C) 2011  Davis E. King (davis@dlib.net)\n// License: Boost Software License   See LICENSE.txt for the full license.\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <ctime>\n#include <dlib/optimization.h>\n#include <dlib/rand.h>\n\n#include \"tester.h\"\n\nnamespace  \n{\n    using namespace test;\n    using namespace dlib;\n    using namespace std;\n\n    logger dlog(\"test.find_max_factor_graph_viterbi\");\n\n// ----------------------------------------------------------------------------------------\n\n    dlib::rand rnd;\n\n// ----------------------------------------------------------------------------------------\n\n    template <\n        unsigned long O,\n        unsigned long NS,\n        unsigned long num_nodes,\n        bool all_negative \n        >\n    class map_problem\n    {\n    public:\n        unsigned long order() const { return O; }\n        unsigned long num_states() const { return NS; }\n\n        map_problem()\n        {\n            data = randm(number_of_nodes(),(long)std::pow(num_states(),(double)order()+1), rnd);\n            if (all_negative)\n                data = -data;\n        }\n\n        unsigned long number_of_nodes (\n        ) const\n        {\n            return num_nodes;\n        }\n\n        template <\n            typename EXP \n            >\n        double factor_value (\n            unsigned long node_id,\n            const matrix_exp<EXP>& node_states\n        ) const\n        {\n            if (node_states.size() == 1)\n                return data(node_id, node_states(0));\n            else if (node_states.size() == 2)\n                return data(node_id, node_states(0) + node_states(1)*NS);\n            else if (node_states.size() == 3)\n                return data(node_id, (node_states(0) + node_states(1)*NS)*NS + node_states(2));\n            else \n                return data(node_id, ((node_states(0) + node_states(1)*NS)*NS + node_states(2))*NS + node_states(3));\n        }\n\n        matrix<double> data;\n    };\n\n\n// ----------------------------------------------------------------------------------------\n\n    template <\n        typename map_problem\n        >\n    void brute_force_find_max_factor_graph_viterbi (\n        const map_problem& prob,\n        std::vector<unsigned long>& map_assignment\n    )\n    {\n        using namespace dlib::impl;\n        const int order = prob.order();\n        const int num_states = prob.num_states();\n\n        map_assignment.resize(prob.number_of_nodes());\n        double best_score = -std::numeric_limits<double>::infinity();\n        matrix<unsigned long,1,0> node_states;\n        node_states.set_size(prob.number_of_nodes());\n        node_states = 0;\n        do\n        {\n            double score = 0;\n            for (unsigned long i = 0; i < prob.number_of_nodes(); ++i)\n            {\n                score += prob.factor_value(i, (colm(node_states,range(i,i-std::min<int>(order,i)))));\n            }\n\n            if (score > best_score)\n            {\n                for (unsigned long i = 0; i < map_assignment.size(); ++i)\n                    map_assignment[i] = node_states(i);\n                best_score = score;\n            }\n\n        } while(advance_state(node_states,num_states));\n\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    template <\n        unsigned long order,\n        unsigned long num_states,\n        unsigned long num_nodes,\n        bool all_negative\n        >\n    void do_test_()\n    {\n        dlog << LINFO << \"order: \"<< order \n                      << \"  num_states:   \" << num_states\n                      << \"  num_nodes:    \" << num_nodes\n                      << \"  all_negative: \" << all_negative;\n\n        for (int i = 0; i < 25; ++i)\n        {\n            print_spinner();\n            map_problem<order,num_states,num_nodes,all_negative> prob;\n            std::vector<unsigned long> assign, assign2;\n            brute_force_find_max_factor_graph_viterbi(prob, assign);\n            find_max_factor_graph_viterbi(prob, assign2);\n\n            DLIB_TEST_MSG(mat(assign) == mat(assign2),\n                          trans(mat(assign))\n                          << trans(mat(assign2))\n                          );\n        }\n    }\n\n    template <\n        unsigned long order,\n        unsigned long num_states,\n        unsigned long num_nodes\n        >\n    void do_test()\n    {\n        do_test_<order,num_states,num_nodes,false>();\n    }\n\n    template <\n        unsigned long order,\n        unsigned long num_states,\n        unsigned long num_nodes\n        >\n    void do_test_negative()\n    {\n        do_test_<order,num_states,num_nodes,true>();\n    }\n\n// ----------------------------------------------------------------------------------------\n\n    class test_find_max_factor_graph_viterbi : public tester\n    {\n    public:\n        test_find_max_factor_graph_viterbi (\n        ) :\n            tester (\"test_find_max_factor_graph_viterbi\",\n                    \"Runs tests on the find_max_factor_graph_viterbi routine.\")\n        {}\n\n        void perform_test (\n        )\n        {\n            do_test<1,3,0>();\n            do_test<1,3,1>();\n            do_test<1,3,2>();\n            do_test<0,3,2>();\n            do_test_negative<0,3,2>();\n\n            do_test<1,3,8>();\n            do_test<2,3,7>();\n            do_test_negative<2,3,7>();\n            do_test<3,3,8>();\n            do_test<4,3,8>();\n            do_test_negative<4,3,8>();\n            do_test<0,3,8>();\n            do_test<4,3,1>();\n            do_test<4,3,0>();\n\n            do_test<3,2,1>();\n            do_test<3,2,0>();\n            do_test<3,2,2>();\n            do_test<2,2,1>();\n            do_test_negative<3,2,1>();\n            do_test_negative<3,2,0>();\n            do_test_negative<3,2,2>();\n            do_test_negative<2,2,1>();\n\n            do_test<0,3,0>();\n            do_test<1,2,8>();\n            do_test<2,2,7>();\n            do_test<3,2,8>();\n            do_test<0,2,8>();\n\n            do_test<1,1,8>();\n            do_test<2,1,8>();\n            do_test<3,1,8>();\n            do_test<0,1,8>();\n        }\n    } a;\n\n}\n\n\n\n\n", "meta": {"hexsha": "82754aefd7791a850d9b4681a488f33406dd3586", "size": 6067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dlib/test/find_max_factor_graph_viterbi.cpp", "max_stars_repo_name": "prathyusha12924/eye-gaze", "max_stars_repo_head_hexsha": "a80ad54b46e9cef4e743b53aaff035de83f27154", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11719.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T22:38:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:45:04.000Z", "max_issues_repo_path": "dlib/test/find_max_factor_graph_viterbi.cpp", "max_issues_repo_name": "KiLJ4EdeN/dlib", "max_issues_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2518.0, "max_issues_repo_issues_event_min_datetime": "2015-01-04T04:38:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:55:43.000Z", "max_forks_repo_path": "dlib/test/find_max_factor_graph_viterbi.cpp", "max_forks_repo_name": "KiLJ4EdeN/dlib", "max_forks_repo_head_hexsha": "eb1f08ce6ab3ca6f9d10425d899103de3c0df56c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3308.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T14:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:20:07.000Z", "avg_line_length": 27.8302752294, "max_line_length": 117, "alphanum_fraction": 0.4699192352, "num_tokens": 1342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6176910755333682}}
{"text": "/**\n * @file lstm_peephole_test.cpp\n * @author Marcus Edel\n *\n * Tests the LSTM peepholes.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/layer/lstm_layer.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\n\nBOOST_AUTO_TEST_SUITE(LSTMPeepholeTest);\n\n/*\n * Test the peephole connections in the forward pass. The test is a modification\n * of the peephole test originally written by Tom Schaul.\n */\nBOOST_AUTO_TEST_CASE(LSTMPeepholeForwardTest)\n{\n  double state1 = 0.2;\n  double state2 = 0.345;\n  double state3 = -0.135;\n  double state4 = 10000;\n\n  arma::colvec input, output;\n\n  LSTMLayer<> hiddenLayer0(1, 6, true);\n\n  hiddenLayer0.InGatePeepholeWeights() = arma::mat(\"3\");\n  hiddenLayer0.ForgetGatePeepholeWeights() = arma::mat(\"4\");\n  hiddenLayer0.OutGatePeepholeWeights() = arma::mat(\"5\");\n\n  // Set the LSTM state to state1 (state = inGateActivation * cellActivation\n  // = 1 / (1 + e^(-1000)) * tanh(atanh(0.2)) = 1 * 0.2 = 0.2).\n  // outputActivation = outGateActivation * stateActivation\n  // = tanh((0.2)) * (1 / (1 + e^1000)) = 0.\n  input << state4 << state4 << std::atanh(state1) << -state4;\n  hiddenLayer0.FeedForward(input, output);\n  BOOST_REQUIRE_CLOSE(output(0), 0, 1e-3);\n\n  // Verify that the LSTM state is correctly stored.\n  input.clear();\n  input << -state4 << state4 << state4 << state4;\n  hiddenLayer0.FeedForward(input, output);\n  BOOST_REQUIRE_CLOSE(output(0), std::tanh(state1), 1e-3);\n\n  // Add state2 to the LSTM state.\n  // state = state + forgateGateActivation * state(t - 1) = 0.345 + 1 * 0.2 =\n  // 0.545\n  input.clear();\n  input << state4 << state4 << std::atanh(state2) << state4;\n  hiddenLayer0.FeedForward(input, output);\n  BOOST_REQUIRE_CLOSE(output(0), std::tanh(state1 + state2), 1e-3);\n\n  // Verify the peephole connection to the forgetgate (weight = 4) by\n  // neutralizing its contibution and therefore dividing the LSTM state value\n  // by 2.\n  input.clear();\n  input << -state4 << -(state1 + state2) * 4 << state4 << state4;\n  hiddenLayer0.FeedForward(input, output);\n  BOOST_REQUIRE_CLOSE(output(0), std::tanh((state1 + state2) / 2), 1e-3);\n\n  // Verify the peephole connection to the inputgate (weight = 3) by\n  // neutralizing its contibution and therefore dividing the provided input\n  // by 2.\n  input.clear();\n  input << -(state1 + state2) / 2 * 3 << -state4 << std::atanh(state3)\n        << state4;\n  hiddenLayer0.FeedForward(input, output);\n  BOOST_REQUIRE_CLOSE(output(0), std::tanh(state3 / 2), 1e-3);\n\n  // Verify the peephole connection to the outputgate (weight = 5) by\n  // neutralizing its contibution and therefore dividing the provided output\n  // by 2.\n  input.clear();\n  input << -state4 << state4 << state4 << -state3 / 2 * 5;\n  hiddenLayer0.FeedForward(input, output);\n  BOOST_REQUIRE_CLOSE(output(0), std::tanh(state3 / 2) / 2, 1e-3);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "6192e64123bde2755de21155a67503ebbabdd371", "size": 2932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/lstm_peephole_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:20.000Z", "max_issues_repo_path": "src/mlpack/tests/lstm_peephole_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/lstm_peephole_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3181818182, "max_line_length": 80, "alphanum_fraction": 0.6858799454, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6176910753242603}}
{"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_NEXTPOW2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_NEXTPOW2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing nextpow2 capabilities\n\n    Returns the greatest integer n such that abs_s(x) is greater or equal to \\f$2^n\\f$\n\n    @par Semantic:\n\n    @code\n    auto n = nextpow2(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    auto n = floor(log2(saturated_(abs)(x)));\n    @endcode\n\n    @see floor, log2, abs, saturated\n  **/\n  Value nextpow2(Value const & x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/nextpow2.hpp>\n#include <boost/simd/function/simd/nextpow2.hpp>\n\n#endif\n", "meta": {"hexsha": "9070a2d707cdbf26905c59f1ec27357712385261", "size": 1087, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/nextpow2.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/nextpow2.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/nextpow2.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": 23.1276595745, "max_line_length": 100, "alphanum_fraction": 0.5777368905, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6176910702947143}}
{"text": "#pragma once\n\n#include <boost/multiprecision/gmp.hpp>\n\nusing CodeNumber = int32_t;\n\n// The following typedefs are used for coefficients of equations\nusing Coeff16 = int16_t;\nusing Coeff32 = int32_t;\nusing Coeff64 = int64_t;\n\nusing Integer = boost::multiprecision::mpz_int;\n\nusing Rational = boost::multiprecision::mpq_rational;\n", "meta": {"hexsha": "e3b96d0beb065209d814b2745e7259a38c58dd3a", "size": 328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/backend/headers/numbers.hpp", "max_stars_repo_name": "wadymwadim/normandeau", "max_stars_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/backend/headers/numbers.hpp", "max_issues_repo_name": "wadymwadim/normandeau", "max_issues_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/backend/headers/numbers.hpp", "max_forks_repo_name": "wadymwadim/normandeau", "max_forks_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8666666667, "max_line_length": 64, "alphanum_fraction": 0.7804878049, "num_tokens": 84, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6176910702947142}}
{"text": "#include <catch2/catch.hpp>\n#include <iostream>\n#include <Eigen/Dense>\n#include <igl/opengl/glfw/Viewer.h>\n#include <igl/readSTL.h>\n#include <igl/readOFF.h>\n#include <methods_config.h>\n\nusing namespace Eigen;\nusing namespace std;\n\nSCENARIO(\"icp\", \"[icp.h]\")\n{\n  const Eigen::MatrixXd V = (Eigen::MatrixXd(8, 3) <<\n                                                   0.0, 0.0, 0.0,\n      0.0, 0.0, 1.0,\n      0.0, 1.0, 0.0,\n      0.0, 1.0, 1.0,\n      1.0, 0.0, 0.0,\n      1.0, 0.0, 1.0,\n      1.0, 1.0, 0.0,\n      1.0, 1.0, 1.0).finished();\n\n  const Eigen::MatrixXi F = (Eigen::MatrixXi(12, 3) <<\n                                                    1, 7, 5,\n      1, 3, 7,\n      1, 4, 3,\n      1, 2, 4,\n      3, 8, 7,\n      3, 4, 8,\n      5, 7, 8,\n      5, 8, 6,\n      1, 5, 6,\n      1, 6, 2,\n      2, 6, 8,\n      2, 8, 4).finished().array() - 1;\n\n  // Plot the mesh\n  igl::opengl::glfw::Viewer viewer;\n  viewer.data().set_mesh(V, F);\n  viewer.data().set_face_based(true);\n  viewer.launch();\n}\n\nSCENARIO(\"midsole icp\", \"[icp.h]\")\n{\n  Eigen::MatrixXd VA;\n  Eigen::MatrixXi FA;\n  const std::string dir = SOURCE_DIR;\n  igl::readOFF(dir + \"/test/test_data/test_11D.off\", VA, FA);\n\n  Eigen::MatrixXd VB;\n  Eigen::MatrixXi FB;\n  const std::string dir2 = SOURCE_DIR;\n  igl::readOFF(dir2 + \"/test/test_data/test_11D_rotated.off\", VB, FB);\n\n  // merge meshes for viewer\n  // Concatenate (VA,FA) and (VB,FB) into (V,F)\n  Eigen::MatrixXd V(VA.rows()+VB.rows(),VA.cols());\n  V<<VA,VB;\n  Eigen::MatrixXi F(FA.rows()+FB.rows(),FA.cols());\n  F<<FA,(FB.array()+VA.rows());\n\n  // blue color for faces of first mesh, orange for second\n  Eigen::MatrixXd C(F.rows(),3);\n  C<<\n   Eigen::RowVector3d(0.2,0.3,0.8).replicate(FA.rows(),1),\n      Eigen::RowVector3d(1.0,0.7,0.2).replicate(FB.rows(),1);\n\n  // Plot the mesh\n  igl::opengl::glfw::Viewer viewer;\n  viewer.data().set_mesh(V, F);\n  viewer.data().set_colors(C);\n  viewer.data().set_face_based(true);\n  viewer.launch();\n}", "meta": {"hexsha": "15b69a05d2708282cb5bf9879c231853e9b44c30", "size": 1952, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fitter/test/icp.cpp", "max_stars_repo_name": "jdilla52/meshFitter", "max_stars_repo_head_hexsha": "7adfd5a00a394e459c8213701ea05f681c4ea207", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fitter/test/icp.cpp", "max_issues_repo_name": "jdilla52/meshFitter", "max_issues_repo_head_hexsha": "7adfd5a00a394e459c8213701ea05f681c4ea207", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fitter/test/icp.cpp", "max_forks_repo_name": "jdilla52/meshFitter", "max_forks_repo_head_hexsha": "7adfd5a00a394e459c8213701ea05f681c4ea207", "max_forks_repo_licenses": ["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.6842105263, "max_line_length": 70, "alphanum_fraction": 0.5522540984, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6176910702947142}}
{"text": "#include <Eigen/Core>\n#include \"drakeGeometryUtil.h\"\n#include \"testUtil.h\"\n#include <iostream>\n#include <cmath>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid testExpmap2quat(const Vector4d &quat);\n\nvoid testRotationConversionFunctions()\n{\n  int ntests = 100;\n  default_random_engine generator;\n  // quat2axis, axis2quat\n  for (int i = 0; i < ntests; i++) {\n    Vector4d q = uniformlyRandomQuat(generator);\n    auto a = quat2axis(q);\n    auto q_back = axis2quat(a);\n    valuecheck(acos(abs(q.transpose() * q_back)), 0.0, 1e-6);\n  }\n  // quat2rotmat, rotmat2quat\n  for (int i = 0; i < ntests; i++) {\n    Vector4d q = uniformlyRandomQuat(generator);\n    Matrix3d R = quat2rotmat(q);\n    Vector4d q_back = rotmat2quat(R);\n    valuecheck(acos(abs(q.transpose() * q_back)), 0.0, 1e-6);\n  }\n  // quat2rpy, rpy2quat\n  for (int i = 0; i < ntests; i++) {\n    Vector4d q = uniformlyRandomQuat(generator);\n    Vector3d rpy = quat2rpy(q);\n    Vector4d q_back = rpy2quat(rpy);\n    valuecheck(acos(abs(q.transpose() * q_back)), 0.0, 1e-6);\n  }\n  // rotmat2axis, axis2rotmat\n  for (int i = 0; i < ntests; i++) {\n    Matrix3d R = uniformlyRandomRotmat(generator);\n    Vector4d a = rotmat2axis(R);\n    Matrix3d R_back = axis2rotmat(a);\n    valuecheckMatrix(R, R_back, 1e-6);\n  }\n  // rotmat2rpy, rpy2rotmat\n  for (int i = 0; i < ntests; i++) {\n    Matrix3d R = uniformlyRandomRotmat(generator);\n    Vector3d rpy = rotmat2rpy(R);\n    Matrix3d R_back = rpy2rotmat(rpy);\n    valuecheckMatrix(R, R_back, 1e-6);\n  }\n  // rpy2axis, axis2rpy\n  for (int i = 0; i < ntests; i++) {\n    Vector3d rpy = uniformlyRandomRPY(generator);\n    Vector4d axis = rpy2axis(rpy);\n    Vector3d rpy_back = axis2rpy(axis);\n    valuecheckMatrix(rpy, rpy_back, 1e-6);\n  }\n  // expmap2quat, quat2expmap\n  Vector4d quat_degenerate = Vector4d::Zero();\n  quat_degenerate(0) = 1.0;\n  testExpmap2quat(quat_degenerate);\n  quat_degenerate(0) = -1.0;\n  testExpmap2quat(quat_degenerate);\n  for (int i = 0; i<ntests; i++)\n  {\n    Vector4d quat = uniformlyRandomQuat(generator);\n    testExpmap2quat(quat);\n  }\n  // quat2eigenQuaternion\n  Vector4d quat = uniformlyRandomQuat(generator);\n  Quaterniond eigenQuat = quat2eigenQuaternion(quat);\n  Matrix3d R_expected = quat2rotmat(quat);\n  Matrix3d R_eigen = eigenQuat.matrix();\n  valuecheckMatrix(R_expected, R_eigen, 1e-6);\n}\n\nvoid testDHomogTrans(int ntests) {\n  Isometry3d T;\n  std::default_random_engine generator;\n\n  for (int testnr = 0; testnr < ntests; testnr++) {\n    Vector4d q = uniformlyRandomQuat(generator);\n    T = Quaterniond(q(0), q(1), q(2), q(3));\n    //  T.setIdentity();\n    //  T = AngleAxisd(M_PI_2, Vector3d(1.0, 0.0, 0.0));\n\n    const int nv = 6;\n    const int nq = 7;\n\n    auto S = Matrix<double, 6, Dynamic>::Random(6, nv).eval();\n//    setLinearIndices(S);\n//    S.setIdentity();\n//    std::cout << S << \"\\n\\n\";\n\n    auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n//    setLinearIndices(qdot_to_v);\n//    std::cout << qdot_to_v << \"\\n\\n\";\n\n    auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n    volatile auto vol = dT;\n    //  std::cout << dT << std::endl << std::endl;\n  }\n}\n\nvoid testDHomogTransInv(int ntests, bool check) {\n  Isometry3d T;\n  std::default_random_engine generator;\n  for (int testnr = 0; testnr < ntests; testnr++) {\n    Vector4d q = uniformlyRandomQuat(generator);\n//    T = Quaterniond(q(0), q(1), q(2), q(3)) * Translation3d(Vector3d::Random());\n    T = Quaterniond(q(0), q(1), q(2), q(3));\n\n    const int nv = 6;\n    const int nq = 7;\n\n    auto S = Matrix<double, 6, Dynamic>::Random(6, nv).eval();\n    auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n\n    auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n    auto dTInv = dHomogTransInv(T, dT);\n    volatile auto vol = dTInv;\n\n    if (check) {\n      auto dTInvInv = dHomogTransInv(T.inverse(), dTInv);\n\n      if (!dT.matrix().isApprox(dTInvInv.matrix(), 1e-10)) {\n        std::cout << \"dTInv:\\n\" << dTInv << \"\\n\\n\";\n        std::cout << \"dT:\\n\" << dT << \"\\n\\n\";\n        std::cout << \"dTInvInv:\\n\" << dTInvInv << \"\\n\\n\";\n        std::cout << \"dTInvInv - dT:\\n\" << dTInvInv - dT << \"\\n\\n\";\n\n        throw std::runtime_error(\"wrong\");\n      }\n    }\n  }\n}\n\nvoid testDTransformAdjoint(int ntests) {\n  const int nv = 6;\n  const int nq = 34;\n  const int cols_X = 3;\n\n  Isometry3d T;\n  std::default_random_engine generator;\n\n  for (int testnr = 0; testnr < ntests; testnr++) {\n    Vector4d q = uniformlyRandomQuat(generator);\n    T = Quaterniond(q(0), q(1), q(2), q(3)) * Translation3d(Vector3d::Random());\n    auto S = Matrix<double, 6, Dynamic>::Random(6, nv).eval();\n    auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n    auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n    auto X = Matrix<double, 6, Dynamic>::Random(6, cols_X).eval();\n    auto dX = MatrixXd::Random(X.size(), nq).eval();\n//    auto dX = Matrix<double, X.SizeAtCompileTime, nq>::Random().eval();\n    auto dAdT_times_X = dTransformSpatialMotion(T, X, dT, dX).eval();\n    volatile auto vol = dAdT_times_X;\n  }\n}\n\nvoid testDTransformAdjointTranspose(int ntests) {\n  const int nv = 6;\n  const int nq = 34;\n  const int cols_X = 3;\n\n  Isometry3d T;\n  std::default_random_engine generator;\n\n  for (int testnr = 0; testnr < ntests; testnr++) {\n    Vector4d q = uniformlyRandomQuat(generator);\n    T = Quaterniond(q(0), q(1), q(2), q(3)) * Translation3d(Vector3d::Random());\n    auto S = Matrix<double, 6, Dynamic>::Random(6, nv).eval();\n    auto qdot_to_v = MatrixXd::Random(nv, nq).eval();\n    auto dT = dHomogTrans(T, S, qdot_to_v).eval();\n    auto X = Matrix<double, 6, Dynamic>::Random(6, cols_X).eval();\n    auto dX = MatrixXd::Random(X.size(), nq).eval();\n//    auto dX = Matrix<double, X.SizeAtCompileTime, nq>::Random().eval();\n    auto dAdTtranspose_times_X = dTransformSpatialForce(T, X, dT, dX).eval();\n    volatile auto vol = dAdTtranspose_times_X;\n  }\n}\n\nvoid testNormalizeVec(int ntests) {\n  const int x_rows = 4;\n\n  for (int testnr = 0; testnr < ntests; testnr++) {\n    auto x = Matrix<double, x_rows, 1>::Random().eval();\n    Matrix<double, x_rows, 1> x_norm;\n    Matrix<double, x_rows, x_rows> dx_norm;\n    Matrix<double, x_rows * x_rows, x_rows> ddx_norm;\n    normalizeVec(x, x_norm, &dx_norm, &ddx_norm);\n//    std::cout << \"gradientNumRows: \" << gradientNumRows(x_rows, x_rows, 1) << std::endl;\n\n    volatile auto volx_norm = x_norm;\n    volatile auto voldx_norm = dx_norm;\n    volatile auto volddx_norm = ddx_norm;\n\n//    std::cout << \"x_norm:\\n\" << x_norm << std::endl << std::endl;\n//    std::cout << \"dx_norm:\\n\" << dx_norm << std::endl << std::endl;\n//    std::cout << \"ddx_norm:\\n\" << ddx_norm << std::endl << std::endl;\n  }\n}\n\nvoid testSpatialCrossProduct()\n{\n  auto a = (Matrix<double, TWIST_SIZE, 1>::Random()).eval();\n  auto b = (Matrix<double, TWIST_SIZE, TWIST_SIZE>::Identity()).eval();\n  auto a_crm_b = crossSpatialMotion(a, b);\n  auto a_crf_b = crossSpatialForce(a, b);\n  valuecheckMatrix(a_crf_b, -a_crm_b.transpose(), 1e-8);\n}\n\nvoid testdrpy2rotmat()\n{\n  default_random_engine generator;\n  Vector3d rpy = uniformlyRandomRPY(generator);\n  Matrix3d R = rpy2rotmat(rpy);\n  Matrix<double,9,3> dR = drpy2rotmat(rpy);\n  Matrix<double,9,3> dR_num = Matrix<double,9,3>::Zero();\n  for(int i = 0;i<3;i++)\n  {\n    Vector3d err = Vector3d::Zero();\n    err(i) = 1e-7;\n    Vector3d rpyi = rpy+err;\n    Matrix3d Ri = rpy2rotmat(rpyi);\n    Matrix3d Ri_err = (Ri-R)/err(i);\n    for(int j = 0;j<9;j++)\n    {\n      dR_num(j,i) = Ri_err(j);\n      valuecheck(dR(j,i),dR_num(j,i),1e-3);\n    }\n  }\n}\n\nvoid testExpmap2quat(const Vector4d &quat)\n{\n  auto expmap = quat2expmap(quat,1);\n  auto quat_back  = expmap2quat(expmap.value(),2);\n  valuecheck(std::abs(quat.transpose() * quat_back.value()), 1.0, 1e-8);\n  Matrix3d expmap_back = expmap.gradient().value()*quat_back.gradient().value();\n  Matrix3d identity = Matrix3d::Identity();\n  valuecheckMatrix(expmap_back,identity,1E-10);\n}\n\nint main(int argc, char **argv)\n{\n  testRotationConversionFunctions();\n\n  int ntests = 100000;\n  std::cout << \"testDHomogTrans elapsed time: \" << measure<>::execution(testDHomogTrans, ntests) << std::endl;\n  std::cout << \"testDHomogTransInv elapsed time: \" << measure<>::execution(testDHomogTransInv, ntests, false) << std::endl;\n  std::cout << \"testDTransformAdjoint elapsed time: \" << measure<>::execution(testDTransformAdjoint, ntests) << std::endl;\n  std::cout << \"testDTransformAdjointTranspose elapsed time: \" << measure<>::execution(testDTransformAdjointTranspose, ntests) << std::endl;\n  std::cout << \"testNormalizeVec elapsed time: \" << measure<>::execution(testNormalizeVec, ntests) << std::endl;\n\n  testDHomogTransInv(1000, true);\n  testSpatialCrossProduct();\n\ttestdrpy2rotmat();\n\n  return 0;\n}\n", "meta": {"hexsha": "d13fa09063b6510745064b29af50291fddbd763d", "size": 8655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "drake/util/test/testDrakeGeometryUtil.cpp", "max_stars_repo_name": "ericmanzi/double_pendulum_lqr", "max_stars_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T09:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T21:59:27.000Z", "max_issues_repo_path": "drake/util/test/testDrakeGeometryUtil.cpp", "max_issues_repo_name": "ericmanzi/double_pendulum_lqr", "max_issues_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drake/util/test/testDrakeGeometryUtil.cpp", "max_forks_repo_name": "ericmanzi/double_pendulum_lqr", "max_forks_repo_head_hexsha": "76bba3091295abb7d412c4a3156258918f280c96", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-08-24T20:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-24T20:32:03.000Z", "avg_line_length": 33.1609195402, "max_line_length": 140, "alphanum_fraction": 0.646909301, "num_tokens": 2890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430436757312, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.617678930096273}}
{"text": "#pragma once\n// tools\n#include <boost/tuple/tuple.hpp>\n#pragma once\n// mesh\n#include \"Triangulation.hpp\"\n// PDE\n#include \"OseenProblem.hpp\"\n#include \"BoundaryCondition.hpp\"\n// FEs\n#include \"AbstractFiniteElement.hpp\"\n// for global system matrix\n#include \"CSlCMatrix.hpp\"\n#include \"CSCMatrix.hpp\"\n\nnamespace FEM {\n\n\tnamespace Mixed {\n\n\t\tboost::tuple<\n\t\t\tCSlCMatrix<double>, // diffusion + convection + reaction matrix\n\t\t\tCSCMatrix<double>, CSCMatrix<double>, // divirgence matrices \n\t\t\tstd::vector<double> // rhs vector\n\t\t>\n\t\tassembleSystem(\n\t\t\tOseenProblem2D const &, // (1) PDE,\n\t\t\tTriangulation const &, // (2) discretized domain (mesh), and BCs that connects (1) and (2):\n\t\t\tVectorBoundaryCondition2D const &, // natural BC,\n\t\t\tVectorBoundaryCondition2D const &, // essential BC;\n\t\t\tTriangularScalarFiniteElement const &, // for each velocity component\n\t\t\tTriangularScalarFiniteElement const &, // for pressure\n\t\t\tboost::optional<Index&> activeElementIndex = boost::none // index of the active element\t\n\t\t);\n\n\t}\n}\n", "meta": {"hexsha": "26c45d1ae5f25c6b01eb15475994498e87eb1dc5", "size": 1017, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sln/Tools/MixedFEM.hpp", "max_stars_repo_name": "frfly/CATSPDEs", "max_stars_repo_head_hexsha": "41bcc7cf4fe5636572603199e807fa6c7c25dd93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-09T13:30:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T19:37:44.000Z", "max_issues_repo_path": "sln/Tools/MixedFEM.hpp", "max_issues_repo_name": "frfly/CATSPDEs", "max_issues_repo_head_hexsha": "41bcc7cf4fe5636572603199e807fa6c7c25dd93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-04-10T09:07:58.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-10T09:07:58.000Z", "max_forks_repo_path": "sln/Tools/MixedFEM.hpp", "max_forks_repo_name": "frfly/Solving-elliptic-equation-using-FEM", "max_forks_repo_head_hexsha": "41bcc7cf4fe5636572603199e807fa6c7c25dd93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-12-08T15:45:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T21:44:50.000Z", "avg_line_length": 27.4864864865, "max_line_length": 94, "alphanum_fraction": 0.7187807276, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.6176270444371937}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::distributions::normal::derivative_log_unnormalized_pdf.hpp //\n//                                                                                  //\n//  (C) Copyright 2009 Erwann Rogard                                                //\n//  Use, modification and distribution are subject to the                           //\n//  Boost Software License, Version 1.0. (See accompanying file                     //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)                //\n//////////////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_NORMAL_DERIVATIVE_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_NORMAL_DERIVATIVE_LOG_UNNORMALIZED_PDF_HPP_ER_2009\n#include <boost/math/distributions/normal.hpp>\n#include <boost/numeric/conversion/converter.hpp>\n//#include <boost/math/policies/policy.hpp>//TODO\n\nnamespace boost{\nnamespace math{\n\n    template<typename T,typename P>\n    T\n    derivative_log_unnormalized_pdf(\n        const boost::math::normal_distribution<T,P>& d,\n        const T& x\n    ){\n        typedef boost::numeric::converter<T,int> int2real_t;\n        T mu = d.location();\n        T sigma = d.scale();\n\n        T z = (x-mu)/sigma;\n        T dz = int2real_t::convert(1)/sigma;\n        return (- z) * dz;\n    }\n    \n}// math\n}// boost\n\n#endif\n", "meta": {"hexsha": "008b695efd06c6f4225a8ec69c31c977d59104f5", "size": 1506, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/normal/derivative_log_unnormalized_pdf.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/normal/derivative_log_unnormalized_pdf.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distribution_toolkit/boost/statistics/detail/distribution_toolkit/distributions/normal/derivative_log_unnormalized_pdf.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7027027027, "max_line_length": 103, "alphanum_fraction": 0.5398406375, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6176270389617479}}
{"text": "/**\n * @file\n * @brief Unit tests for local element matrix builders\n * @author Tobias Rohner\n * @date January 2021\n * @copyright MIT License\n */\n\n#include <gtest/gtest.h>\n#include <lf/assemble/assemble.h>\n#include <lf/fe/fe.h>\n#include <lf/fe/test_utils/test_utils.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/quad/quad.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <cmath>\n#include <iostream>\n\nnamespace lf::fe::test {\n\nTEST(lf_fe, diffusion_mat_test) {\n  // Building the test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh();\n  // Use a relatively high polynomial degree\n  const unsigned degree = 15;\n  const auto fe_space =\n      std::make_shared<lf::fe::HierarchicScalarFESpace<double>>(mesh_p, degree);\n\n  // The analytic solution\n  const auto u = [](const Eigen::VectorXd &x) -> double {\n    return std::sin(base::kPi * x[0]) * std::sin(base::kPi * x[1]);\n  };\n  const lf::mesh::utils::MeshFunctionGlobal mf_u(u);\n\n  // Define the load function of the manufactured solution\n  const auto load = [](const Eigen::Vector2d &x) -> double {\n    return 2 * base::kPi * base::kPi * std::sin(base::kPi * x[0]) *\n           std::sin(base::kPi * x[1]);\n  };\n  const lf::mesh::utils::MeshFunctionGlobal mf_load(load);\n\n  // Assemble the system matrix and right hand side\n  const lf::assemble::DofHandler &dofh = fe_space->LocGlobMap();\n  lf::assemble::COOMatrix<double> A_COO(dofh.NumDofs(), dofh.NumDofs());\n  Eigen::VectorXd rhs = Eigen::VectorXd::Zero(dofh.NumDofs());\n  std::cout << \"> Assembling System Matrix\" << std::endl;\n  const lf::mesh::utils::MeshFunctionConstant<double> mf_alpha(1);\n  lf::fe::DiffusionElementMatrixProvider element_matrix_provider(fe_space,\n                                                                 mf_alpha);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, element_matrix_provider,\n                                      A_COO);\n  std::cout << \"> Assembling right Hand Side\" << std::endl;\n  lf::fe::ScalarLoadElementVectorProvider element_vector_provider(fe_space,\n                                                                  mf_load);\n  lf::assemble::AssembleVectorLocally(0, dofh, element_vector_provider, rhs);\n\n  // Enforce zero dirichlet boundary conditions\n  std::cout << \"> Enforcing Boundary Conditions\" << std::endl;\n  const auto boundary = lf::mesh::utils::flagEntitiesOnBoundary(mesh_p);\n  const auto selector = [&](unsigned int idx) -> std::pair<bool, double> {\n    const auto &entity = dofh.Entity(idx);\n    return {entity.Codim() > 0 && boundary(entity), 0};\n  };\n  lf::assemble::FixFlaggedSolutionComponents(selector, A_COO, rhs);\n\n  // Solve the LSE using the cholesky decomposition\n  std::cout << \"> Solving LSE\" << std::endl;\n  Eigen::SparseMatrix<double> A = A_COO.makeSparse();\n  Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(A);\n  const Eigen::VectorXd solution = solver.solve(rhs);\n  const lf::fe::MeshFunctionFE<double, double> mf_numeric(fe_space, solution);\n  const lf::fe::MeshFunctionGradFE<double, double> mf_numeric_grad(fe_space,\n                                                                   solution);\n\n  // Compute the L2 error\n  std::cout << \"> Computing Error Norms\" << std::endl;\n  const auto qr_segment =\n      lf::quad::make_QuadRule(lf::base::RefEl::kSegment(), 2 * degree - 1);\n  const auto qr_tria =\n      lf::quad::make_QuadRule(lf::base::RefEl::kTria(), 2 * degree - 1);\n  const auto qr_quad =\n      lf::quad::make_QuadRule(lf::base::RefEl::kQuad(), 2 * degree - 1);\n  const auto quadrule_provider = [&](const lf::mesh::Entity &entity) {\n    const lf::base::RefEl refel = entity.RefEl();\n    switch (refel) {\n      case lf::base::RefEl::kTria():\n        return qr_tria;\n      case lf::base::RefEl::kSegment():\n        return qr_segment;\n      case lf::base::RefEl::kQuad():\n        return qr_quad;\n      default:\n        return lf::quad::make_QuadRule(refel, 2 * degree - 1);\n    }\n  };\n  const double L2_err = std::sqrt(lf::fe::IntegrateMeshFunction(\n      *mesh_p, lf::mesh::utils::squaredNorm(mf_u - mf_numeric),\n      quadrule_provider));\n\n  // Assert that the L2 error is small enough\n  ASSERT_NEAR(L2_err, 0, 1e-5);\n}\n\nTEST(lf_fe, mass_mat_test) {\n  // Building the test mesh\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh();\n  // Use a relatively high polynomial degree\n  const unsigned degree = 15;\n  const auto fe_space =\n      std::make_shared<lf::fe::HierarchicScalarFESpace<double>>(mesh_p, degree);\n\n  // Define some right hand side\n  const auto load = [](const Eigen::Vector2d &x) -> double {\n    return 2 * base::kPi * base::kPi * std::sin(base::kPi * x[0]) *\n           std::sin(base::kPi * x[1]);\n  };\n  const lf::mesh::utils::MeshFunctionGlobal mf_load(load);\n\n  // Assemble the system matrix and right hand side\n  const lf::assemble::DofHandler &dofh = fe_space->LocGlobMap();\n  lf::assemble::COOMatrix<double> A_COO(dofh.NumDofs(), dofh.NumDofs());\n  Eigen::VectorXd rhs = Eigen::VectorXd::Zero(dofh.NumDofs());\n  std::cout << \"> Assembling System Matrix\" << std::endl;\n  const lf::mesh::utils::MeshFunctionConstant<double> mf_gamma(1);\n  lf::fe::MassElementMatrixProvider element_matrix_provider(fe_space, mf_gamma);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, element_matrix_provider,\n                                      A_COO);\n  std::cout << \"> Assembling right Hand Side\" << std::endl;\n  lf::fe::ScalarLoadElementVectorProvider element_vector_provider(fe_space,\n                                                                  mf_load);\n  lf::assemble::AssembleVectorLocally(0, dofh, element_vector_provider, rhs);\n\n  // Enforce zero dirichlet boundary conditions\n  std::cout << \"> Enforcing Boundary Conditions\" << std::endl;\n  const auto boundary = lf::mesh::utils::flagEntitiesOnBoundary(mesh_p);\n  const auto selector = [&](unsigned int idx) -> std::pair<bool, double> {\n    const auto &entity = dofh.Entity(idx);\n    return {entity.Codim() > 0 && boundary(entity), 0};\n  };\n  lf::assemble::FixFlaggedSolutionComponents(selector, A_COO, rhs);\n\n  // Solve the LSE using the cholesky decomposition\n  std::cout << \"> Solving LSE\" << std::endl;\n  Eigen::SparseMatrix<double> A = A_COO.makeSparse();\n  Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(A);\n  const Eigen::VectorXd solution = solver.solve(rhs);\n  const lf::fe::MeshFunctionFE<double, double> mf_numeric(fe_space, solution);\n  const lf::fe::MeshFunctionGradFE<double, double> mf_numeric_grad(fe_space,\n                                                                   solution);\n\n  // Compute the L2 error\n  std::cout << \"> Computing Error Norms\" << std::endl;\n  const auto qr_segment =\n      lf::quad::make_QuadRule(lf::base::RefEl::kSegment(), 2 * degree - 1);\n  const auto qr_tria =\n      lf::quad::make_QuadRule(lf::base::RefEl::kTria(), 2 * degree - 1);\n  const auto qr_quad =\n      lf::quad::make_QuadRule(lf::base::RefEl::kQuad(), 2 * degree - 1);\n  const auto quadrule_provider = [&](const lf::mesh::Entity &entity) {\n    const lf::base::RefEl refel = entity.RefEl();\n    switch (refel) {\n      case lf::base::RefEl::kTria():\n        return qr_tria;\n      case lf::base::RefEl::kSegment():\n        return qr_segment;\n      case lf::base::RefEl::kQuad():\n        return qr_quad;\n      default:\n        return lf::quad::make_QuadRule(refel, 2 * degree - 1);\n    }\n  };\n  const double L2_err = std::sqrt(lf::fe::IntegrateMeshFunction(\n      *mesh_p, lf::mesh::utils::squaredNorm(mf_load - mf_numeric),\n      quadrule_provider));\n\n  // Assert that the L2 error is small enough\n  ASSERT_NEAR(L2_err, 0, 1e-5);\n}\n\ntemplate <class SCALAR_TEST, class SCALAR_TRIAL, class EMP, class EVALUATOR>\nvoid CheckElementMatrixProvider(const ScalarFESpace<SCALAR_TEST> &fes_test,\n                                const ScalarFESpace<SCALAR_TRIAL> &fes_trial,\n                                const EMP &emp, EVALUATOR &&evaluator,\n                                base::dim_t codim = 0) {\n  Eigen::Matrix<SCALAR_TEST, Eigen::Dynamic, 1> coeff_test(\n      fes_test.LocGlobMap().NumDofs());\n  Eigen::Matrix<SCALAR_TRIAL, Eigen::Dynamic, 1> coeff_trial(\n      fes_trial.LocGlobMap().NumDofs());\n  coeff_test.setZero();\n  coeff_trial.setZero();\n\n  using scalar_matrix_t = decltype(evaluator(coeff_test, coeff_trial));\n\n  // assemble the matrix:\n  assemble::COOMatrix<scalar_matrix_t> coo_matrix(coeff_test.rows(),\n                                                  coeff_trial.rows());\n  assemble::AssembleMatrixLocally(codim, fes_trial.LocGlobMap(),\n                                  fes_test.LocGlobMap(), emp, coo_matrix);\n  Eigen::Matrix<scalar_matrix_t, Eigen::Dynamic, Eigen::Dynamic> system_matrix =\n      coo_matrix.makeDense();\n\n  for (base::size_type i = 0; i < coeff_test.rows(); ++i) {\n    coeff_test(i) = 1.;\n    for (base::size_type j = 0; j < coeff_trial.rows(); ++j) {\n      coeff_trial(j) = 1.;\n      scalar_matrix_t result = evaluator(coeff_test, coeff_trial);\n      auto entry = system_matrix(i, j);\n      ASSERT_LT(std::abs(result - system_matrix(i, j)), 1e-7);\n      coeff_trial(j) = 0.;\n    }\n    coeff_test(i) = 0;\n  }\n}\n\ntemplate <class SCALAR, class EVP, class EVALUATOR>\nvoid CheckEntityVectorProvider(const ScalarFESpace<SCALAR> &fes_test,\n                               const EVP &evp, EVALUATOR &&evaluator,\n                               base::dim_t codim) {\n  Eigen::Matrix<SCALAR, Eigen::Dynamic, 1> coeff_test(\n      fes_test.LocGlobMap().NumDofs());\n  coeff_test.setZero();\n\n  using scalar_vector_t = decltype(evaluator(coeff_test));\n\n  // assemble the vector:\n  Eigen::Matrix<scalar_vector_t, Eigen::Dynamic, 1> vector(coeff_test.rows());\n  vector.setZero();\n  assemble::AssembleVectorLocally(codim, fes_test.LocGlobMap(), evp, vector);\n\n  for (base::size_type i = 0; i < coeff_test.rows(); ++i) {\n    coeff_test(i) = 1;\n    auto result = evaluator(coeff_test);\n    auto entry = vector(i);\n    ASSERT_LT(std::abs(result - entry), 1e-7);\n    coeff_test(i) = 0;\n  }\n}\n\nTEST(lf_fe, DiffusionElementMatrixProviderComplexCoeff) {\n  // get a mesh of affine elements so that the element matrices can be\n  // calculated exactly.\n  auto mesh = lf::mesh::test_utils::GenerateHybrid2DTestMesh(5);\n\n  //// Generate a variable order hierarchic fe space:\n  auto fe_space = std::make_shared<HierarchicScalarFESpace<double>>(\n      mesh, [&](const mesh::Entity &e) { return (mesh->Index(e)) % 2 + 1; });\n\n  auto max_degree = 2;\n\n  //// complex diffusion coefficient:\n  auto alpha = [&](const mesh::Entity &e, const Eigen::MatrixXd &local) {\n    return std::vector<double>(local.cols(), mesh->Index(e) + 10.);\n  };\n\n  DiffusionElementMatrixProvider emp(fe_space, alpha);\n\n  // calculate every element of the matrix with MeshFunctions:\n  auto evaluator = [&](const Eigen::VectorXd &test_coeff,\n                       const Eigen::VectorXd &trial_coeff) {\n    auto mf_grad_test = MeshFunctionGradFE(fe_space, test_coeff);\n    auto mf_grad_trial = MeshFunctionGradFE(fe_space, trial_coeff);\n    return lf::fe::IntegrateMeshFunction(\n        *mesh, transpose(mf_grad_test) * (alpha * mf_grad_trial),\n        2 * (max_degree))(0);\n  };\n\n  CheckElementMatrixProvider(*fe_space, *fe_space, emp, evaluator);\n}\n\nTEST(lf_fe, DiffusionElementMatrixProviderTensorCoeff) {\n  // get a mesh of affine elements so that the element matrices can be\n  // calculated exactly.\n  auto mesh = lf::mesh::test_utils::GenerateHybrid2DTestMesh(5);\n  //// Generate a variable order hierarchic fe space:\n  auto fe_space = std::make_shared<HierarchicScalarFESpace<double>>(\n      mesh, [&](const mesh::Entity &e) { return (mesh->Index(e)) % 2 + 1; });\n\n  auto max_degree = 2;\n\n  auto alpha2 = mesh::utils::MeshFunctionGlobal([](const Eigen::Vector2d &x) {\n    return (Eigen::Matrix2d() << 1, x.x(), x.y(), 2).finished();\n  });\n  DiffusionElementMatrixProvider emp2(fe_space, alpha2);\n  auto evaluator2 = [&](const Eigen::VectorXd &test_coeff,\n                        const Eigen::VectorXd &trial_coeff) {\n    auto mf_grad_test = MeshFunctionGradFE(fe_space, test_coeff);\n    auto mf_grad_trial = MeshFunctionGradFE(fe_space, trial_coeff);\n    return lf::fe::IntegrateMeshFunction(\n        *mesh, transpose(mf_grad_test) * (alpha2 * mf_grad_trial),\n        2 * (max_degree))(0);\n  };\n  CheckElementMatrixProvider(*fe_space, *fe_space, emp2, evaluator2);\n}\n\nTEST(lf_fe, DiffusionElementMatrixProviderComplexFESpace) {\n  // get a mesh of affine elements so that the element matrices can be\n  // calculated exactly.\n  auto mesh = lf::mesh::test_utils::GenerateHybrid2DTestMesh(5);\n\n  //// complex diffusion coefficient:\n  auto alpha = [&](const mesh::Entity &e, const Eigen::MatrixXd &local) {\n    return std::vector<double>(local.cols(), mesh->Index(e) + 10.);\n  };\n\n  // with a complex fe_space:\n  auto fes_complex = test_utils::MakeComplexLagrangeO1FeSpace(mesh);\n  DiffusionElementMatrixProvider emp3(fes_complex, alpha);\n  auto evaluator3 = [&](const Eigen::VectorXcd &test_coeff,\n                        const Eigen::VectorXcd &trial_coeff) {\n    auto mf_grad_test = MeshFunctionGradFE(fes_complex, test_coeff);\n    auto mf_grad_trial = MeshFunctionGradFE(fes_complex, trial_coeff);\n    return lf::fe::IntegrateMeshFunction(\n        *mesh, adjoint(mf_grad_test) * (alpha * mf_grad_trial), 2)(0);\n  };\n  CheckElementMatrixProvider(*fes_complex, *fes_complex, emp3, evaluator3);\n}\n\nTEST(lf_fe, MassElementMatrixProvider) {\n  auto mesh = mesh::test_utils::GenerateHybrid2DTestMesh(5);\n\n  auto g = [&](const mesh::Entity &e, const Eigen::MatrixXd &local) {\n    return std::vector<double>(local.cols(), mesh->Index(e) + 10.);\n  };\n\n  auto fes = std::make_shared<HierarchicScalarFESpace<double>>(mesh, 1);\n  MassElementMatrixProvider emp(fes, g);\n  auto evaluator = [&](const Eigen::VectorXd &test_coeff,\n                       Eigen::VectorXd &trial_coeff) {\n    auto mf_test = MeshFunctionFE(fes, test_coeff);\n    auto mf_trial = MeshFunctionFE(fes, trial_coeff);\n    return IntegrateMeshFunction(*mesh, mf_test * mf_trial * g, 2);\n  };\n  CheckElementMatrixProvider(*fes, *fes, emp, evaluator);\n}\n\nTEST(lf_fe, MassElementMatrixProviderComplex) {\n  auto mesh = mesh::test_utils::GenerateHybrid2DTestMesh(5);\n\n  auto g = mesh::utils::MeshFunctionConstant(std::complex<double>{1, 2});\n\n  auto fes = fe::test_utils::MakeComplexLagrangeO1FeSpace(mesh);\n  MassElementMatrixProvider emp(fes, g);\n  auto evaluator = [&](const Eigen::VectorXcd &test_coeff,\n                       Eigen::VectorXcd &trial_coeff) {\n    auto mf_test = MeshFunctionFE(fes, test_coeff);\n    auto mf_trial = MeshFunctionFE(fes, trial_coeff);\n    return IntegrateMeshFunction(*mesh, conjugate(mf_test) * mf_trial * g, 2);\n  };\n  CheckElementMatrixProvider(*fes, *fes, emp, evaluator);\n}\n\nTEST(lf_fe, MassEdgeMatrixProvider) {\n  auto mesh = mesh::test_utils::GenerateHybrid2DTestMesh(5);\n\n  auto g = [&](const mesh::Entity &e, const Eigen::MatrixXd &local) {\n    return std::vector<double>(local.cols(), mesh->Index(e) + 10.);\n  };\n  auto fes = std::make_shared<HierarchicScalarFESpace<double>>(mesh, 1);\n  MassEdgeMatrixProvider emp(fes, g);\n  auto evaluator = [&](const Eigen::VectorXd &test_coeff,\n                       const Eigen::VectorXd &trial_coeff) {\n    auto mf_test = MeshFunctionFE(fes, test_coeff);\n    auto mf_trial = MeshFunctionFE(fes, trial_coeff);\n    return IntegrateMeshFunction(*mesh, mf_test * g * mf_trial, 2,\n                                 base::PredicateTrue{}, 1);\n  };\n  CheckElementMatrixProvider(*fes, *fes, emp, evaluator, 1);\n}\n\nTEST(lf_fe, MassEdgeMatrixProviderComplex) {\n  auto mesh = mesh::test_utils::GenerateHybrid2DTestMesh(5);\n\n  auto g = mesh::utils::MeshFunctionConstant(std::complex<double>{1, 2});\n  auto fes = test_utils::MakeComplexLagrangeO1FeSpace(mesh);\n  auto selector = [&](const mesh::Entity &e) {\n    LF_ASSERT_MSG(e.Codim() == 1, \"This is not an edge.\");\n    return mesh->Index(e) < 7;\n  };\n  MassEdgeMatrixProvider emp(fes, g, selector);\n  auto evaluator = [&](const Eigen::VectorXcd &test_coeff,\n                       const Eigen::VectorXcd &trial_coeff) {\n    auto mf_test = MeshFunctionFE(fes, test_coeff);\n    auto mf_trial = MeshFunctionFE(fes, trial_coeff);\n    return IntegrateMeshFunction(*mesh, conjugate(mf_test) * g * mf_trial, 2,\n                                 selector, 1);\n  };\n  CheckElementMatrixProvider(*fes, *fes, emp, evaluator, 1);\n}\n\nTEST(lf_fe, ScalarLoadElementVectorProvider_complex) {\n  auto mesh = mesh::test_utils::GenerateHybrid2DTestMesh(5);\n\n  auto g = mesh::utils::MeshFunctionConstant(std::complex<double>{1, 2});\n  auto fes = test_utils::MakeComplexLagrangeO1FeSpace(mesh);\n  ScalarLoadElementVectorProvider evp(fes, g);\n  auto evaluator = [&](const Eigen::VectorXcd &test_coeff) {\n    auto mf_test = MeshFunctionFE(fes, test_coeff);\n    return IntegrateMeshFunction(*mesh, conjugate(mf_test) * g, 2);\n  };\n  CheckEntityVectorProvider(*fes, evp, evaluator, 0);\n}\n\nTEST(lf_fe, ScalarLoadEdgeVectorProvider_complex) {\n  auto mesh = mesh::test_utils::GenerateHybrid2DTestMesh(5);\n\n  auto g = mesh::utils::MeshFunctionConstant(std::complex<double>{1, 2});\n  auto fes = test_utils::MakeComplexLagrangeO1FeSpace(mesh);\n  auto selector = [&](const mesh::Entity &e) {\n    LF_ASSERT_MSG(e.Codim() == 1, \"This is not an edge.\");\n    return mesh->Index(e) < 7;\n  };\n  ScalarLoadEdgeVectorProvider evp(fes, g, selector);\n  auto evaluator = [&](const Eigen::VectorXcd &test_coeff) {\n    auto mf_test = MeshFunctionFE(fes, test_coeff);\n    return IntegrateMeshFunction(*mesh, conjugate(mf_test) * g, 2, selector, 1);\n  };\n  CheckEntityVectorProvider(*fes, evp, evaluator, 1);\n}\n\n}  // namespace lf::fe::test\n", "meta": {"hexsha": "c7e57208f71f73ea09ba10f3bb7867affae5012c", "size": 17631, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/lf/fe/test/loc_comp_tests.cc", "max_stars_repo_name": "Fytch/lehrfempp", "max_stars_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T19:55:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T16:38:06.000Z", "max_issues_repo_path": "lib/lf/fe/test/loc_comp_tests.cc", "max_issues_repo_name": "Fytch/lehrfempp", "max_issues_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 151.0, "max_issues_repo_issues_event_min_datetime": "2018-05-27T13:01:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-04T14:50:50.000Z", "max_forks_repo_path": "lib/lf/fe/test/loc_comp_tests.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": 41.5825471698, "max_line_length": 80, "alphanum_fraction": 0.6653054279, "num_tokens": 4795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.6176270257863444}}
{"text": "/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n#define _USE_MATH_DEFINES\n#include <cmath>\n\n#include <boost/math/special_functions/polygamma.hpp>\n\n#include \"beanmachine/graph/graph.h\"\n#include \"beanmachine/graph/util.h\"\n\nnamespace beanmachine {\nnamespace util {\n\n// see https://core.ac.uk/download/pdf/41787448.pdf\nconst double PHI_APPROX_GAMMA = 1.702;\n\nbool approx_zero(double val) {\n  return std::abs(val) < graph::PRECISION;\n}\n\nbool sample_logodds(std::mt19937& gen, double logodds) {\n  if (logodds < 0) {\n    double wt = exp(logodds);\n    std::bernoulli_distribution dist(wt / (1 + wt));\n    return dist(gen);\n  } else {\n    double wt = exp(-logodds);\n    std::bernoulli_distribution dist(wt / (1 + wt));\n    return not dist(gen);\n  }\n}\n\nbool sample_logprob(std::mt19937& gen, double logprob) {\n  if (logprob > 0)\n    return true;\n  else {\n    std::bernoulli_distribution dist(std::exp(logprob));\n    return dist(gen);\n  }\n}\n\nbool flip_coin_with_log_prob(std::mt19937& gen, double logprob) {\n  return sample_logprob(gen, logprob);\n}\n\ndouble sample_beta(std::mt19937& gen, double a, double b) {\n  std::gamma_distribution<double> distrib_a(a, 1);\n  std::gamma_distribution<double> distrib_b(b, 1);\n  double x = distrib_a(gen);\n  double y = distrib_b(gen);\n  if ((x + y) == 0.0) {\n    return graph::PRECISION;\n  }\n  double p = x / (x + y);\n  return p;\n}\n\ndouble logistic(double logodds) {\n  return 1.0 / (1.0 + std::exp(-logodds));\n}\n\ndouble Phi(double x) {\n  return 0.5 * (1 + std::erf(x / M_SQRT2));\n}\n\ndouble Phi_approx(double x) {\n  return 1.0 / (1.0 + std::exp(-PHI_APPROX_GAMMA * x));\n}\n\ndouble Phi_approx_inv(double z) {\n  return (std::log(z) - std::log(1 - z)) / PHI_APPROX_GAMMA;\n}\n\ndouble log_sum_exp(const std::vector<double>& values) {\n  // find the max and subtract it out\n  double max = values[0];\n  for (std::vector<double>::size_type idx = 1; idx < values.size(); idx++) {\n    if (values[idx] > max) {\n      max = values[idx];\n    }\n  }\n  double sum = 0;\n  for (auto value : values) {\n    sum += std::exp(value - max);\n  }\n  return std::log(sum) + max;\n}\n\ndouble log_sum_exp(double a, double b) {\n  double max_val = a > b ? a : b;\n  double sum = std::exp(a - max_val) + std::exp(b - max_val);\n  return std::log(sum) + max_val;\n}\n\ndouble polygamma(int n, double x) {\n  return boost::math::polygamma(n, x);\n}\n\ndouble log1pexp(double x) {\n  if (x <= -37) {\n    return std::exp(x);\n  } else if (x <= 18) {\n    return std::log1p(std::exp(x));\n  } else if (x <= 33.3) {\n    return x + std::exp(-x);\n  } else {\n    return x;\n  }\n}\n\ndouble log1mexp(double x) {\n  assert(x <= 0);\n  if (x < -0.693) {\n    return std::log1p(-std::exp(x));\n  } else {\n    return std::log(-std::expm1(x));\n  }\n}\n\n} // namespace util\n} // namespace beanmachine\n", "meta": {"hexsha": "faa9faae2caa4089a3ba59df9e61a522179270c1", "size": 2891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/beanmachine/graph/util.cpp", "max_stars_repo_name": "horizon-blue/beanmachine-1", "max_stars_repo_head_hexsha": "b13e4e3e28ffb860947eb8046863b0cabb581222", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-22T13:19:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T13:19:14.000Z", "max_issues_repo_path": "src/beanmachine/graph/util.cpp", "max_issues_repo_name": "horizon-blue/beanmachine-1", "max_issues_repo_head_hexsha": "b13e4e3e28ffb860947eb8046863b0cabb581222", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/beanmachine/graph/util.cpp", "max_forks_repo_name": "horizon-blue/beanmachine-1", "max_forks_repo_head_hexsha": "b13e4e3e28ffb860947eb8046863b0cabb581222", "max_forks_repo_licenses": ["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.7637795276, "max_line_length": 76, "alphanum_fraction": 0.6343825666, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.617627020139232}}
{"text": "\n/* http://melpon.org/wandbox/permlink/paCC61fxm2muS5lc */\n\n//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include \"max_plus.hpp\"\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n\nusing namespace boost;\n\ntemplate <typename Graph, typename ParentMap> struct edge_writer {\n  edge_writer(const Graph &g, const ParentMap &p) : m_g(g), m_parent(p) {}\n\n  template <typename Edge>\n  void operator()(std::ostream &out, const Edge &e) const {\n    out << \"[label=\\\"\" << get(edge_weight, m_g, e) << \"\\\"\";\n    typename graph_traits<Graph>::vertex_descriptor u = source(e, m_g),\n                                                    v = target(e, m_g);\n    if (m_parent[v] == u)\n      out << \", color=\\\"black\\\"\";\n    else\n      out << \", color=\\\"grey\\\"\";\n    out << \"]\";\n  }\n  const Graph &m_g;\n  ParentMap m_parent;\n};\ntemplate <typename Graph, typename Parent>\nedge_writer<Graph, Parent> make_edge_writer(const Graph &g, const Parent &p) {\n  return edge_writer<Graph, Parent>(g, p);\n}\n\nstruct EdgeProperties {\n  fun::maxPlus<int> weight;\n};\n\nint main() {\n  enum { u, v, x, y, z, N };\n  char name[] = {'u', 'v', 'x', 'y', 'z'};\n  typedef std::pair<int, int> E;\n  const int n_edges = 10;\n  E edge_array[] = {E(u, y), E(u, x), E(u, v), E(v, u), E(x, y),\n                    E(x, v), E(y, v), E(y, z), E(z, u), E(z, x)};\n  fun::maxPlus<int> weight[n_edges] = {-4, 8, 5, -2, 9, -3, 7, 2, 6, 7};\n\n  typedef adjacency_list<vecS, vecS, directedS, no_property, EdgeProperties>\n      Graph;\n  Graph g(edge_array, edge_array + n_edges, N);\n\n  graph_traits<Graph>::edge_iterator ei, ei_end;\n  property_map<Graph, fun::maxPlus<int> EdgeProperties::*>::type weight_pmap =\n      get(&EdgeProperties::weight, g);\n  int i = 0;\n  for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei, ++i)\n    weight_pmap[*ei] = weight[i];\n\n  std::vector<fun::maxPlus<int>> distance(N,\n                                          (std::numeric_limits<short>::max)());\n  std::vector<std::size_t> parent(N);\n  for (i = 0; i < N; ++i)\n    parent[i] = i;\n  distance[z] = 0;\n\n  bool r = bellman_ford_shortest_paths(g, int(N),\n                                       weight_map(weight_pmap)\n                                           .distance_map(&distance[0])\n                                           .predecessor_map(&parent[0]));\n\n  if (r)\n    for (i = 0; i < N; ++i)\n      std::cout << name[i] << \": \" << std::setw(3) << distance[i] << \" \"\n                << name[parent[i]] << std::endl;\n  else\n    std::cout << \"negative cycle\" << std::endl;\n  std::cout << '\\n';\n\n  // std::ofstream dot_file(\"figs/bellman-eg.dot\");\n  auto &dot_file = std::cout;\n\n  dot_file << \"digraph D {\\n\"\n           << \"  rankdir=LR\\n\"\n           << \"  size=\\\"5,3\\\"\\n\"\n           << \"  ratio=\\\"fill\\\"\\n\"\n           << \"  edge[style=\\\"bold\\\"]\\n\"\n           << \"  node[shape=\\\"circle\\\"]\\n\";\n\n  {\n    for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n      graph_traits<Graph>::edge_descriptor e = *ei;\n      graph_traits<Graph>::vertex_descriptor u = source(e, g), v = target(e, g);\n      // VC++ doesn't like the 3-argument get function, so here\n      // we workaround by using 2-nested get()'s.\n      dot_file << \"  \" << name[u] << \" -> \" << name[v] << \"[label=\\\"\"\n               << get(get(&EdgeProperties::weight, g), e) << \"\\\"\";\n      if (parent[v] == u)\n        dot_file << \", color=\\\"black\\\"\";\n      else\n        dot_file << \", color=\\\"grey\\\"\";\n      dot_file << \"]\\n\";\n    }\n  }\n  dot_file << \"}\\n\";\n  return EXIT_SUCCESS;\n}\n\n//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\n//#include \"max_plus.hpp\"\n\nusing namespace boost;\n\ntemplate <typename Graph, typename ParentMap> struct edge_writer {\n  edge_writer(const Graph &g, const ParentMap &p) : m_g(g), m_parent(p) {}\n\n  template <typename Edge>\n  void operator()(std::ostream &out, const Edge &e) const {\n    out << \"[label=\\\"\" << get(edge_weight, m_g, e) << \"\\\"\";\n    typename graph_traits<Graph>::vertex_descriptor u = source(e, m_g),\n                                                    v = target(e, m_g);\n    if (m_parent[v] == u)\n      out << \", color=\\\"black\\\"\";\n    else\n      out << \", color=\\\"grey\\\"\";\n    out << \"]\";\n  }\n  const Graph &m_g;\n  ParentMap m_parent;\n};\ntemplate <typename Graph, typename Parent>\nedge_writer<Graph, Parent> make_edge_writer(const Graph &g, const Parent &p) {\n  return edge_writer<Graph, Parent>(g, p);\n}\n\nstruct EdgeProperties {\n  int weight;\n};\n\nint main() {\n  enum { u, v, x, y, z, N };\n  char name[] = {'u', 'v', 'x', 'y', 'z'};\n  typedef std::pair<int, int> E;\n  const int n_edges = 10;\n  E edge_array[] = {E(u, y), E(u, x), E(u, v), E(v, u), E(x, y),\n                    E(x, v), E(y, v), E(y, z), E(z, u), E(z, x)};\n  int weight[n_edges] = {-4, 8, 5, -2, 9, -3, 7, 2, 6, 7};\n\n  typedef adjacency_list<vecS, vecS, directedS, no_property, EdgeProperties>\n      Graph;\n  Graph g(edge_array, edge_array + n_edges, N);\n\n  graph_traits<Graph>::edge_iterator ei, ei_end;\n  property_map<Graph, int EdgeProperties::*>::type weight_pmap =\n      get(&EdgeProperties::weight, g);\n  int i = 0;\n  for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei, ++i)\n    weight_pmap[*ei] = weight[i];\n\n  std::vector<int> distance(N, (std::numeric_limits<short>::max)());\n  std::vector<std::size_t> parent(N);\n  for (i = 0; i < N; ++i)\n    parent[i] = i;\n  distance[z] = 0;\n\n  bool r = bellman_ford_shortest_paths(g, int(N),\n                                       weight_map(weight_pmap)\n                                           .distance_map(&distance[0])\n                                           .predecessor_map(&parent[0]));\n\n  if (r)\n    for (i = 0; i < N; ++i)\n      std::cout << name[i] << \": \" << std::setw(3) << distance[i] << \" \"\n                << name[parent[i]] << std::endl;\n  else\n    std::cout << \"negative cycle\" << std::endl;\n  std::cout << '\\n';\n\n  // std::ofstream dot_file(\"figs/bellman-eg.dot\");\n  auto &dot_file = std::cout;\n\n  dot_file << \"digraph D {\\n\"\n           << \"  rankdir=LR\\n\"\n           << \"  size=\\\"5,3\\\"\\n\"\n           << \"  ratio=\\\"fill\\\"\\n\"\n           << \"  edge[style=\\\"bold\\\"]\\n\"\n           << \"  node[shape=\\\"circle\\\"]\\n\";\n\n  {\n    for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n      graph_traits<Graph>::edge_descriptor e = *ei;\n      graph_traits<Graph>::vertex_descriptor u = source(e, g), v = target(e, g);\n      // VC++ doesn't like the 3-argument get function, so here\n      // we workaround by using 2-nested get()'s.\n      dot_file << \"  \" << name[u] << \" -> \" << name[v] << \"[label=\\\"\"\n               << get(get(&EdgeProperties::weight, g), e) << \"\\\"\";\n      if (parent[v] == u)\n        dot_file << \", color=\\\"black\\\"\";\n      else\n        dot_file << \", color=\\\"grey\\\"\";\n      dot_file << \"]\\n\";\n    }\n  }\n  dot_file << \"}\\n\";\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "e0b31e26692bd94efae0ebd900fc3b8d10b3e9ad", "size": 7723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "coliru/main_max_plus.cpp", "max_stars_repo_name": "luk036/fun", "max_stars_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "coliru/main_max_plus.cpp", "max_issues_repo_name": "luk036/fun", "max_issues_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coliru/main_max_plus.cpp", "max_forks_repo_name": "luk036/fun", "max_forks_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5782608696, "max_line_length": 80, "alphanum_fraction": 0.5280331477, "num_tokens": 2197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290699, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6175939042904852}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/geometry/algorithms/make.hpp>\n#include <boost/geometry/algorithms/append.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/ring.hpp>\n#include <boost/geometry/geometries/concepts/ring_concept.hpp>\n#include <boost/geometry/geometries/adapted/c_array.hpp>\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/geometry/io/dsv/write.hpp>\n\n#include <test_common/test_point.hpp>\n\nBOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\n\n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n#include <initializer_list>\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n\ntemplate <typename P>\nbg::model::ring<P> create_ring()\n{   \n    bg::model::ring<P> r1;\n    P p1;\n    P p2;\n    P p3;\n    P p4;\n    bg::assign_values(p1, 2, 2);\n    bg::assign_values(p2, 2, 0);\n    bg::assign_values(p3, 0, 0);\n    bg::assign_values(p4, 0, 2);\n    \n    bg::append(r1, p1);\n    bg::append(r1, p2);\n    bg::append(r1, p3);\n    bg::append(r1, p4);\n    bg::append(r1, p1);\n    return r1;\n}\n\ntemplate <typename P, typename T>\nvoid check_point(P& to_check, T x, T y)\n{\n    BOOST_CHECK_EQUAL(bg::get<0>(to_check), x);\n    BOOST_CHECK_EQUAL(bg::get<1>(to_check), y);\n}\n\ntemplate <typename R, typename P>\nvoid check_ring(R& to_check, P p1, P p2, P p3, P p4)\n{   \n    check_point(to_check[0], bg::get<0>(p1), bg::get<1>(p1));\n    check_point(to_check[1], bg::get<0>(p2), bg::get<1>(p2));\n    check_point(to_check[2], bg::get<0>(p3), bg::get<1>(p3));\n    check_point(to_check[3], bg::get<0>(p4), bg::get<1>(p4));\n    check_point(to_check[4], bg::get<0>(p1), bg::get<1>(p1));\n}\n\ntemplate <typename P>\nvoid test_default_constructor()\n{\n    bg::model::ring<P> r1(create_ring<P>());\n    check_ring(r1, P(2, 2), P(2, 0), P(0, 0), P(0, 2));\n}\n\ntemplate <typename P>\nvoid test_copy_constructor()\n{\n    bg::model::ring<P> r1 = create_ring<P>();\n    check_ring(r1, P(2, 2), P(2, 0), P(0, 0), P(0, 2));\n}\n\ntemplate <typename P>\nvoid test_copy_assignment()\n{\n    bg::model::ring<P> r1(create_ring<P>()), r2;\n    r2 = r1;\n    check_ring(r2, P(2, 2), P(2, 0), P(0, 0), P(0, 2));\n}\n\ntemplate <typename P>\nvoid test_concept()\n{   \n    typedef bg::model::ring<P> R;\n\n    BOOST_CONCEPT_ASSERT( (bg::concepts::ConstRing<R>) );\n    BOOST_CONCEPT_ASSERT( (bg::concepts::Ring<R>) );\n\n    typedef typename bg::coordinate_type<R>::type T;\n    typedef typename bg::point_type<R>::type PR;\n    boost::ignore_unused<T, PR>();\n}\n\ntemplate <typename P>\nvoid test_all()\n{   \n    test_default_constructor<P>();\n    test_copy_constructor<P>();\n    test_copy_assignment<P>();\n    test_concept<P>();\n}\n\ntemplate <typename P>\nvoid test_custom_ring(bg::model::ring<P> IL)\n{   \n    bg::model::ring<P> r1(IL);\n    std::ostringstream out;\n    out << bg::dsv(r1);\n    BOOST_CHECK_EQUAL(out.str(), \"((3, 3), (3, 0), (0, 0), (0, 3), (3, 3))\");\n}\n\ntemplate <typename P>\nvoid test_custom()\n{   \n#ifdef BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n    std::initializer_list<P> IL = {P(3, 3), P(3, 0), P(0, 0), P(0, 3), P(3, 3)};\n    test_custom_ring<P>(IL);\n#endif//BOOST_NO_CXX11_HDR_INITIALIZER_LIST\n}\n\ntemplate <typename CS>\nvoid test_cs()\n{\n    test_all<bg::model::point<int, 2, CS> >();\n    test_all<bg::model::point<float, 2, CS> >();\n    test_all<bg::model::point<double, 2, CS> >();\n\n    test_custom<bg::model::point<double, 2, CS> >();\n}\n\n\nint test_main(int, char* [])\n{   \n    test_cs<bg::cs::cartesian>();\n    test_cs<bg::cs::spherical<bg::degree> >();\n    test_cs<bg::cs::spherical_equatorial<bg::degree> >();\n    test_cs<bg::cs::geographic<bg::degree> >();\n\n    test_custom<bg::model::d2::point_xy<double> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "e743780905ae5a78dc5c16403291ad7ca4cce661", "size": 4127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/geometries/ring.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": "test/geometries/ring.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/test/geometries/ring.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": 26.4551282051, "max_line_length": 80, "alphanum_fraction": 0.6583474679, "num_tokens": 1335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6175938978286719}}
{"text": "/*\n   Copyright (C) 2015-2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n// Critical temperature of square lattice Ising model\n\n// reference: L. Onsager, Phys. Rev. 65, 117 (1944)\n\n#pragma once\n\n#include <cmath>\n#include <stdexcept>\n#include <boost/math/differentiation/autodiff.hpp>\n#include <standards/newton.hpp>\n\nnamespace {\n  \ntemplate<typename T>\nstruct func {\n  func(T Jx, T Jy) : Jx_(Jx), Jy_(Jy) {}\n  auto operator()(T beta) const -> decltype(boost::math::differentiation::make_fvar<T, 1>(beta)) {\n    using std::sinh;\n    auto beta_fvar = boost::math::differentiation::make_fvar<T, 1>(beta);\n    return sinh(2 * Jx_ * beta_fvar) * sinh(2 * Jy_ * beta_fvar) - 1;\n  }\n  T Jx_, Jy_;\n};\n\n}\n\nnamespace ising {\nnamespace tc {\n\ntemplate<typename T>\ninline T square(T Jx, T Jy) {\n  Jx = abs(Jx);\n  Jy = abs(Jy);\n  if (Jx * Jy <= 0) throw(std::invalid_argument(\"Jx * Jy should be non-zero\"));\n  auto result = standards::newton_1d(func<T>(Jx, Jy), 1 / (2 * (Jx + Jy)));\n  if (!result.second) throw(std::runtime_error(\"convergence error\"));\n  return 1 / result.first;\n}\n\n} // end namespace tc\n} // end namespace ising\n", "meta": {"hexsha": "69a120666cb7b0cbbc198e2418340255775b0823", "size": 1674, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ising/tc/square.hpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "ising/tc/square.hpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "ising/tc/square.hpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8620689655, "max_line_length": 98, "alphanum_fraction": 0.6899641577, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619436290698, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6175938950540178}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <cmath>\n#include <ctime>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing namespace std;\n\nconst int MATCH_MIN = 0;\nconst int MATCH_MAX = 1;\n\n/*\n * readMatrix\n * read a file into a matrix object\n * file must have matrix dimension as first line\n * matrix must be square\n */\nvoid readMatrix(const char* filename, MatrixXd& m) {\n  ifstream fin(filename);\n  \n  if (!fin) {\n    cout << \"Cannot open file.\" << endl;\n    return;\n  }\n  \n  // read in matrix dimensions and\n  // create a matrix of that size\n  int n_rows, n_cols;\n  fin >> n_rows >> n_cols;\n  MatrixXd temp(n_rows, n_cols);\n  \n  // read elements into the temporary matrix\n  for (int i=0; i<n_rows; i++) {\n    for (int j=0; j<n_cols; j++) {\n      fin >> temp(i,j);\n    }\n  }\n  fin.close();\n  \n  // if the dimensions are equal (square matrix), we're done\n  // else, have to figure out larger dimension and pad with matrix max\n  if (n_rows == n_cols) {\n    m = temp;\n  }\n  else {\n    float max_elem = temp.maxCoeff(); // find the max element\n    float dim = max(n_rows, n_cols); // find the dimension for the new, square matrix\n    m.resize(dim,dim);\n    // fill the matrix with the elements from temp and pad with max element\n    for (int i=0; i < dim; i++) {\n      for (int j=0; j < dim; j++) {\n        if (i >= n_rows || j >= n_cols) m(i,j) = max_elem;\n        else m(i,j) = temp(i,j);\n      }\n    }\n  }\n}\n\n/*\n * reduce\n * reduces matrix based on row and column minimums\n */\nvoid reduce(MatrixXd& m) {\n  // subtract row minimum from each row\n  for (int i=0; i<m.rows(); i++) {\n    float minElement = m.row(i).minCoeff();\n    VectorXd rMinusMin(m.rows());\n    rMinusMin.fill(-minElement);\n    m.row(i) += rMinusMin;\n  }\n}\n\n/*\n * hasMark\n * if there is a starred/primed zero in the given row/col, returns it's index\n * else, returns -1\n */\nint hasMark(VectorXd& v) {  \n  for (int i=0; i<v.size(); i++) {\n    if (v(i)) {\n      return i;\n    }\n  }\n  return -1;\n}\n\n/*\n * swapStarsAndPrimes\n * Swap stars and primes based on step 5 of Hungarian algorithm\n * Z0 is uncovered primed zero we've found\n * Z1 is the stared zero in the column of Z0 (if any)\n * Z2 is the primed zero in the row of Z1 (will always be one)\n * ...continue series until we reach a primed zero with no starred zero in its column\n * Unstar each starred zero, star each primed zero, erase all primes and uncover every line in the matrix\n */\nvoid swapStarsAndPrimes(int i, int j, MatrixXd& stars, MatrixXd& primes) {\n  int primeRow = i;\n  int primeCol = j;\n  \n  bool done = false;\n  while (!done) {\n    // find row index of row that has a 0* in the same col as the current 0'\n    VectorXd col = stars.col(primeCol);\n    int starInPrimeColRow = hasMark(col); \n    \n    if (starInPrimeColRow < 0) {\n      // star the prime we're looking at\n      primes(primeRow, primeCol) = 0;\n      stars(primeRow, primeCol) = 1;\n      done = true;\n    }\n    else {\n      // find which col has a 0' in the same row as z1\n      VectorXd row = primes.row(starInPrimeColRow);\n      int primeInStarRowCol = hasMark(row);\n      \n      // star first primed zero\n      primes(primeRow, primeCol) = 0;\n      stars(primeRow, primeCol) = 1;\n      //primes(starInPrimeColRow, primeInStarRowCol) = 0;\n      //stars(starInPrimeColRow, primeInStarRowCol) = 1;\n      \n      // unstar starred zero\n      stars(starInPrimeColRow, primeCol) = 0;\n      \n      // set index of last prime, will check it's column for 0*s next\n      primeRow = starInPrimeColRow;\n      primeCol = primeInStarRowCol;\n    }\n  }\n  // clear primes\n  primes.fill(0);\n}\n\n/*\n * findMatching\n * implementation of the Hungarian matching algorithm\n * referenced from: http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html\n */\nvoid findMatching(MatrixXd& m, MatrixXd& result, int type) {\n  MatrixXd n = m; // make a copy of m for reducing\n  int dim = n.rows(); // dimension of matrix, used for checking if we've reduced\n                      // the matrix enough yet\n  \n  MatrixXd stars(m.rows(), m.cols()); // matrix for storing our \"starred\" 0s (0*)\n  stars.fill(0);\n  MatrixXd primes(m.rows(), m.cols()); // matrix for storing our \"primed\" 0s (0')\n  primes.fill(0);\n  VectorXd rowCover(m.rows()); // keep track of which rows are \"covered\"\n  rowCover.fill(0);\n  VectorXd colCover(m.cols()); // keep track of which columns are \"covered\"\n  colCover.fill(0);\n  \n  // to do maximization rather than minimization, we have to\n  // transform the matrix by subtracting every value from the maximum\n  if (type == MATCH_MAX) {\n    float max = n.maxCoeff();\n    MatrixXd maxMat(n.rows(), n.cols());\n    maxMat.fill(max);\n    n = maxMat - n;\n  }\n  \n  // Step 1 \n  // Reduce matrix\n  reduce(n);\n  \n  // Step 2\n  // Find a zero in the matrix. If there is no starred zero in \n  // its row or column, star Z. Repeat for each element in the matrix.\n  for (int i=0; i<n.rows(); i++) {\n    for (int j=0; j<n.cols(); j++) {\n      if (n(i,j) == 0 && !rowCover(i) && !colCover(j)) {\n        stars(i,j) = 1;\n        rowCover(i) = 1;\n        colCover(j) = 1;\n      }\n    }\n  }\n  // covers need to be cleared for following steps\n  rowCover.fill(0);\n  colCover.fill(0);\n  \n  while (true) {\n    // Step 3\n    // Cover all columns that have a starred zero\n    // If the number of columns with starred zeroes equals the matrix\n    // dimensions, we are done! Otherwise, move on to step 4.\n    step3:\n    for (int j=0; j<n.cols(); j++) {\n      VectorXd col = stars.col(j);\n      if (hasMark(col) >= 0) {\n        colCover(j) = 1;\n      }\n    }\n    if (colCover.sum() == dim) {\n      result = stars;\n      return;\n    }\n    \n    // Step 4\n    // Find a non-covered zero and prime it\n    step4:\n    for (int i=0; i<n.rows(); i++) {\n      for (int j=0; j<n.cols(); j++) {\n        if (n(i,j) == 0 && !rowCover(i) && !colCover(j)) {\n          primes(i,j) = 1;\n          // if no starred zero in the row...\n          VectorXd row = stars.row(i);\n          if (hasMark(row) < 0) {\n            // Step 5\n            // swap stars and primes            \n            swapStarsAndPrimes(i, j, stars, primes);\n    \n            // clear lines\n            rowCover.fill(0);\n            colCover.fill(0);\n            \n            goto step3;\n          }\n          else {\n            // cover row\n            rowCover(i) = 1;\n            \n            // uncover column of the starred zero in the same row\n            int col = hasMark(row);\n            colCover(col) = 0;\n          }\n        }\n      }\n    }\n    \n    // Step 6\n    // Should now be no more uncovered zeroes\n    // Get the minimum uncovered element\n    float min = 1000000;\n    for (int i=0; i<n.rows(); i++) {\n      for (int j=0; j<n.cols(); j++) {\n        if (!rowCover(i) && !colCover(j) && n(i,j) < min) {\n          min = n(i,j);\n        }\n      }\n    }\n    \n    // Subtract minimum from uncovered elements, add it to elements covered twice\n    for (int i=0; i<n.rows(); i++) {\n      for (int j=0; j<n.cols(); j++) {\n        if (!rowCover(i) && !colCover(j)) {\n          n(i,j) -= min;\n        }\n        else if (rowCover(i) && colCover(j)) {\n          n(i,j) += min;\n        }\n      }\n    }\n    \n    goto step4;\n  }\n}\n\n/*\n * main()\n */\nint main(int argc, char *argv[])\n{\n  if (argc != 2) {\n    cout << \"Usage: ./a.out [matrixfile]\" << endl;\n    return 0;\n  }\n  \n  // times\n\tclock_t start, end;\n  float elapsedTime;\n\n  // random seed\n  srand((unsigned)time(0));\n\n\t// start time\n  start = clock();\n  \n  // read in the matrix file\n  MatrixXd m(1,1);\n  readMatrix(argv[1], m);\n  \n  // create an empty matrix to put the result in\n  MatrixXd result(m.rows(), m.cols());\n  result.fill(0);\n  \n  // run the Hungarian (Munkres) algorithm to find the maximal matching\n  findMatching(m, result, MATCH_MIN);\n  \n  MatrixXd mask = m.cwiseProduct(result);\n  int sum = mask.sum();\n  \n  cout << \"ORIGINAL MATRIX\" << endl;\n  cout << m << endl;\n  cout << endl;\n  cout << \"ASSIGNMENT RESULT\" << endl;\n  cout << result << endl;\n  cout << endl;\n  cout << \"FINAL SUM\" << endl;\n  cout << sum << endl;\n  \n  \n  // stop time\n  end = clock();\n\telapsedTime = (float)(end - start) / CLOCKS_PER_SEC;\n  cout << \"Completed in: \" << elapsedTime << \" s\" << endl;\n    \n  return 0;\n}\n", "meta": {"hexsha": "81f159859a7e436cb4595fe091f6088132cdd285", "size": 8278, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matching.cpp", "max_stars_repo_name": "emstresh/HungarianAlgorithm", "max_stars_repo_head_hexsha": "22ad42237ed227406760de4fddaa4685f9face60", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-06-09T06:48:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T01:43:38.000Z", "max_issues_repo_path": "matching.cpp", "max_issues_repo_name": "emstresh/HungarianAlgorithm", "max_issues_repo_head_hexsha": "22ad42237ed227406760de4fddaa4685f9face60", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-27T17:42:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-27T23:03:16.000Z", "max_forks_repo_path": "matching.cpp", "max_forks_repo_name": "emstresh/HungarianAlgorithm", "max_forks_repo_head_hexsha": "22ad42237ed227406760de4fddaa4685f9face60", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-01-26T06:38:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T13:33:04.000Z", "avg_line_length": 26.1135646688, "max_line_length": 105, "alphanum_fraction": 0.5770717565, "num_tokens": 2384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6175938867486249}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <list>\n#include <numeric>\n#include <random>\n#include <vector>\n#include \"cnn/metric-util.h\"\n#include <initializer_list>\n#include <Eigen/LU>\n\nusing namespace std;\nnamespace cnn { namespace metric {\n\n    cnn::real cosine_similarity(const std::vector<cnn::real> &s1, const std::vector<cnn::real> &s2)\n    {\n        cnn::real flt = 0.0;\n        cnn::real flt1 = 0.0, flt2 = 0.0;\n\n        for (int k = 0; k < s1.size(); k++)\n        {\n            flt += s1[k] * s2[k];\n            flt1 += s1[k] * s1[k];\n            flt2 += s2[k] * s2[k];\n        }\n\n        if (flt1 == 0.0) flt1 = FLT_EPSILON;\n        if (flt2 == 0.0) flt2 = FLT_EPSILON;\n        flt1 = sqrt(flt1);\n        flt2 = sqrt(flt2);\n\n        cnn::real val = flt / (flt1 * flt2);\n\n        return val;\n    }\n\n    int levenshtein_distance(const vector<std::string> &s1, const vector<std::string> &s2)\n    {\n        // To change the type this function manipulates and returns, change\n        // the return type and the types of the two variables below.\n        int s1len = s1.size();\n        int s2len = s2.size();\n\n        auto column_start = (decltype(s1len))1;\n\n        auto column = new decltype(s1len)[s1len + 1];\n        std::iota(column + column_start, column + s1len + 1, column_start);\n\n        for (auto x = column_start; x <= s2len; x++) {\n            column[0] = x;\n            auto last_diagonal = x - column_start;\n            for (auto y = column_start; y <= s1len; y++) {\n                auto old_diagonal = column[y];\n                auto possibilities = {\n                    column[y] + 1,\n                    column[y - 1] + 1,\n                    last_diagonal + (s1[y - 1] == s2[x - 1] ? 0 : 1)\n                };\n                column[y] = std::min(possibilities);\n                last_diagonal = old_diagonal;\n            }\n        }\n        auto result = column[s1len];\n        delete[] column;\n        return result;\n    }\n} }\n", "meta": {"hexsha": "2ad8c14e412d0e1813565c5b2622e190b59dc7f3", "size": 1955, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cnn/metric-util.cc", "max_stars_repo_name": "kaishengyao/cnn", "max_stars_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-09-10T07:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-17T03:02:38.000Z", "max_issues_repo_path": "cnn/metric-util.cc", "max_issues_repo_name": "kaishengyao/cnn", "max_issues_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cnn/metric-util.cc", "max_forks_repo_name": "kaishengyao/cnn", "max_forks_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-09-08T12:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-26T07:32:47.000Z", "avg_line_length": 29.1791044776, "max_line_length": 99, "alphanum_fraction": 0.5135549872, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451416, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.617555276090276}}
{"text": "/*\n * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT)\n *\n * This software may be modified and distributed under the terms of the\n * BSD 3-Clause license. See the accompanying LICENSE file for details.\n */\n\n#include <iostream>\n#include <memory>\n\n#include <BayesFilters/AdditiveStateModel.h>\n#include <BayesFilters/GaussianLikelihood.h>\n#include <BayesFilters/GPFPrediction.h>\n#include <BayesFilters/GPFCorrection.h>\n#include <BayesFilters/InitSurveillanceAreaGrid.h>\n#include <BayesFilters/Resampling.h>\n#include <BayesFilters/SimulatedLinearSensor.h>\n#include <BayesFilters/SimulatedStateModel.h>\n#include <BayesFilters/SIS.h>\n#include <BayesFilters/UKFPrediction.h>\n#include <BayesFilters/UKFCorrection.h>\n#include <BayesFilters/utils.h>\n#include <BayesFilters/WhiteNoiseAcceleration.h>\n\n#include <Eigen/Dense>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nclass UPFSimulation : public SIS\n{\npublic:\n    UPFSimulation\n    (\n        std::size_t num_particle,\n        std::size_t state_size,\n        std::size_t simulation_steps,\n        /* Initial covariance of the Gaussian belief associated to each particle. */\n        Ref<MatrixXd> initial_covariance,\n        std::unique_ptr<ParticleSetInitialization> initialization,\n        std::unique_ptr<PFPrediction> prediction,\n        std::unique_ptr<PFCorrection> correction,\n        std::unique_ptr<Resampling> resampling\n    ) noexcept :\n        SIS(num_particle, state_size, std::move(initialization), std::move(prediction), std::move(correction), std::move(resampling)),\n        simulation_steps_(simulation_steps),\n        initial_covariance_(initial_covariance)\n    { }\n\nprotected:\n    bool runCondition() override\n    {\n        if (getFilteringStep() < simulation_steps_)\n            return true;\n        else\n            return false;\n    }\n\n    std::vector<std::string> log_filenames(const std::string& prefix_path, const std::string& prefix_name) override\n    {\n        std::vector<std::string> sis_filenames = SIS::log_filenames(prefix_path, prefix_name);\n\n        /* Add file names for logging of the conditional expected value. */\n        sis_filenames.push_back(prefix_path + \"/\" + prefix_name + \"_mean\");\n\n        return  sis_filenames;\n    }\n\n    VectorXd mean_extraction(const ParticleSet& particles) const\n    {\n        /* Extract the conditional expected value of the filtered state\n           given all the measurements up to the current time step. */\n        return particles.state() * particles.weight().array().exp().matrix();\n    }\n\n    bool initialization() override\n    {\n        if (!SIS::initialization())\n            return false;\n\n        /* Initialize initial mean and covariance for each particle. */\n        for (std::size_t i = 0; i < pred_particle_.components; i++)\n        {\n            /* Set mean equal to the particle position. */\n            pred_particle_.mean(i) = pred_particle_.state(i);\n\n            /* Set the covariance obtained within the ctor. */\n            pred_particle_.covariance(i) = initial_covariance_;\n        }\n\n        return true;\n    }\n\n    void log() override\n    {\n        VectorXd mean = mean_extraction(cor_particle_);\n\n        logger(pred_particle_.state().transpose(), pred_particle_.weight().transpose(),\n               cor_particle_.state().transpose(), cor_particle_.weight().transpose(),\n               mean.transpose());\n    }\n\nprivate:\n    std::size_t simulation_steps_;\n\n    Eigen::MatrixXd initial_covariance_;\n};\n\n\nint main()\n{\n    std::cout << \"Running an unscented particle filter on a simulated target.\" << std::endl;\n    std::cout << \"Data is logged in the test folder with prefix testUPF.\" << std::endl;\n\n    /* A set of parameters needed to run an unscented particle filter in a simulated environment. */\n    double surv_x = 1000.0;\n    double surv_y = 1000.0;\n    std::size_t num_particle_x = 100;\n    std::size_t num_particle_y = 100;\n    std::size_t num_particle = num_particle_x * num_particle_y;\n    Vector4d initial_state(10.0f, 0.0f, 10.0f, 0.0f);\n    std::size_t simulation_time = 100;\n    std::size_t state_size = 4;\n\n    /* Unscented transform parameters.*/\n    double alpha = 1.0;\n    double beta = 2.0;\n    double kappa = 0.0;\n\n    /* Step 1 - Initialization */\n\n    Matrix4d initial_covariance;\n    initial_covariance << pow(0.05, 2), 0,            0,            0,\n                          0,            pow(0.05, 2), 0,            0,\n                          0,            0,            pow(0.01, 2), 0,\n                          0,            0,            0,            pow(0.01, 2);\n\n    /* Initialize particle initialization class. */\n    std::unique_ptr<ParticleSetInitialization> grid_initialization = utils::make_unique<InitSurveillanceAreaGrid>(surv_x, surv_y, num_particle_x, num_particle_y);\n\n\n    /* Step 2 - Prediction */\n\n    /* Step 2.1 - Define the state model. */\n\n    /* Initialize a white noise acceleration state model. */\n    double T = 1.0f;\n    double tilde_q = 10.0f;\n\n    std::unique_ptr<AdditiveStateModel> wna = utils::make_unique<WhiteNoiseAcceleration>(T, tilde_q);\n\n    /* Step 2.2 - Define the prediction step */\n\n    /* Initialize the kalman particle filter prediction step that wraps a Gaussian prediction step,\n       in this case an unscented kalman filter prediction step. */\n    std::unique_ptr<GaussianPrediction> upf_prediction = utils::make_unique<UKFPrediction>(std::move(wna), state_size, alpha, beta, kappa);\n    std::unique_ptr<PFPrediction> gpf_prediction = utils::make_unique<GPFPrediction>(std::move(upf_prediction));\n\n\n    /* Step 3 - Correction */\n\n    /* Step 3.1 - Define where the measurement are originated from (simulated in this case). */\n\n    /* Initialize simulated target model with a white noise acceleration. */\n    std::unique_ptr<StateModel> target_model = utils::make_unique<WhiteNoiseAcceleration>(T, tilde_q);\n    std::unique_ptr<SimulatedStateModel> simulated_state_model = utils::make_unique<SimulatedStateModel>(std::move(target_model), initial_state, simulation_time);\n    simulated_state_model->enable_log(\".\", \"testUPF\");\n\n    /* Initialize a measurement model (a linear sensor reading x and y coordinates). */\n    std::unique_ptr<AdditiveMeasurementModel> simulated_linear_sensor = utils::make_unique<SimulatedLinearSensor>(std::move(simulated_state_model));\n    simulated_linear_sensor->enable_log(\".\", \"testUPF\");\n\n\n    /* Step 3.2 - Define the likelihood model. */\n\n    /* Initialize an exponential likelihood as measurement likelihood. */\n    std::unique_ptr<LikelihoodModel> exp_likelihood = utils::make_unique<GaussianLikelihood>();\n\n    /* Step 3.3 - Define the correction step. */\n\n    /* An additional state model is required to make the transitionProbability of the state model available\n       to the particle filter correction step. */\n    std::unique_ptr<StateModel> transition_probability_model = utils::make_unique<WhiteNoiseAcceleration>(T, tilde_q);\n\n    /* Initialize the particle filter correction step that wraps a Guassian correction step,\n       in this case an unscented kalman filter correction step. */\n    std::unique_ptr<GaussianCorrection> upf_correction = utils::make_unique<UKFCorrection>(std::move(simulated_linear_sensor), state_size, alpha, beta, kappa);\n    std::unique_ptr<PFCorrection> gpf_correction = utils::make_unique<GPFCorrection>(std::move(upf_correction), std::move(exp_likelihood), std::move(transition_probability_model));\n\n\n    /* Step 4 - Resampling */\n\n    /* Initialize a resampling algorithm. */\n    std::unique_ptr<Resampling> resampling = utils::make_unique<Resampling>();\n\n\n    /* Step 5 - Assemble the particle filter. */\n    std::cout << \"Constructing unscented particle filter...\" << std::flush;\n    UPFSimulation upf(num_particle, state_size, simulation_time, initial_covariance, std::move(grid_initialization), std::move(gpf_prediction), std::move(gpf_correction), std::move(resampling));\n    upf.enable_log(\".\", \"testUPF\");\n    std::cout << \"done!\" << std::endl;\n\n\n    /* Step 6 - Prepare the filter to be run */\n    std::cout << \"Booting unscented particle filter...\" << std::flush;\n    upf.boot();\n    std::cout << \"completed!\" << std::endl;\n\n\n    /* Step 7 - Run the filter and wait until it is closed */\n    /* Note that since this is a simulation, the filter will end upon simulation termination */\n    std::cout << \"Running unscented particle filter...\" << std::flush;\n    upf.run();\n    std::cout << \"waiting...\" << std::flush;\n\n    if (!upf.wait())\n        return EXIT_FAILURE;\n\n    std::cout << \"completed!\" << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "ab7b9f48c386d28d50204619e14a6dbd269213ed", "size": 8552, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_UPF/main.cpp", "max_stars_repo_name": "vesor/bayes-filters-lib", "max_stars_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T02:52:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T07:06:39.000Z", "max_issues_repo_path": "test/test_UPF/main.cpp", "max_issues_repo_name": "vesor/bayes-filters-lib", "max_issues_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_UPF/main.cpp", "max_forks_repo_name": "vesor/bayes-filters-lib", "max_forks_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T08:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T08:20:28.000Z", "avg_line_length": 38.1785714286, "max_line_length": 194, "alphanum_fraction": 0.6796071094, "num_tokens": 2043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6175552632382348}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    double           array[][3]= {{1., 2., 3.}, {4., 5., 6.}, {7., 8., 9.}};\n    dense2D<double>  A(array), A2, A3;\n\n    // Creating a permutation matrix from a vector (or an array respectively)\n    int indices[]= {1, 2, 0};\n    mat::traits::permutation<>::type P= mat::permutation(indices);\n    std::cout << \"\\nP =\\n\" << P;    \n\n    // Permutating rows\n    A2= P * A;\n    std::cout << \"\\nP * A =\\n\" << A2;\n    \n    // Permutating columns\n    A3= A2 * trans(P);\n    std::cout << \"\\nA2 * trans(P) =\\n\" << A3;\n\n    dense_vector<double> v(array[2]), w(P * v);\n    std::cout << \"\\nP * v =\\n\" << w << \"\\n\";\n    \n    return 0;\n}\n", "meta": {"hexsha": "b28474f84f5e3b58cbe5f63867d916f2449bcee6", "size": 731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/permutation.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/permutation.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/permutation.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 25.2068965517, "max_line_length": 77, "alphanum_fraction": 0.5102599179, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6175552624665427}}
{"text": "//\r\n// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n\r\n#include <OpenTissue/core/math/math_basic_types.h>\r\n#include <OpenTissue/collision/gjk/gjk_signed_distance_to_edge_face_voronoi_plane.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <OpenTissue/utility/utility_push_boost_filter.h>\r\n#include <boost/test/auto_unit_test.hpp>\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\r\n\r\n#include <cmath>\r\n\r\nusing namespace OpenTissue;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_collision_gjk_signed_distance_to_edge_face_vp);\r\n\r\nBOOST_AUTO_TEST_CASE(case_by_case_test)\r\n{\r\n  typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\r\n  typedef math_types::vector3_type                         vector3_type;\r\n  typedef math_types::real_type                            real_type;\r\n\r\n\r\n  vector3_type a = vector3_type(0.0, 0.0, 0.0);\r\n  vector3_type b = vector3_type(1.0, 0.0, 0.0);;\r\n  vector3_type c = vector3_type(0.0, 1.0, 0.0);;\r\n\r\n  // Front side of AB voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-0.5, -1.0,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n  }\r\n  // Back side of AB voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-0.5, 1.0,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n  }\r\n  // In AB voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-0.5, 0.0,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n  // Front side of AC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-1.0, 0.5,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n  }\r\n  // Back side of AC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 1.0, 0.5,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n  }\r\n  // In AC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.0, 0.5,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n  // Front side of BC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 1.0, 1.0,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.70710678118654752440084436210485, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.70710678118654752440084436210485, 0.01 );\r\n  }\r\n  // Back side of BC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.0, 0.0,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK_CLOSE( sign_p, -0.70710678118654752440084436210485, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, -0.70710678118654752440084436210485, 0.01 );\r\n  }\r\n  // In BC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.5, 0.5,  1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, c, a); \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n\r\n\r\n\r\n  // We just used a point above the face plane, next we will try using a test point lying in the face plane\r\n\r\n\r\n\r\n  // Front side of AB voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-0.5, -1.0,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n  }\r\n  // Back side of AB voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-0.5, 1.0,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n  }\r\n  // In AB voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-0.5, 0.0,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n  // Front side of AC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-1.0, 0.5,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n  }\r\n  // Back side of AC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 1.0, 0.5,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n  }\r\n  // In AC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.0, 0.5,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n  // Front side of BC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 1.0, 1.0,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.70710678118654752440084436210485, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.70710678118654752440084436210485, 0.01 );\r\n  }\r\n  // Back side of BC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.0, 0.0,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK_CLOSE( sign_p, -0.70710678118654752440084436210485, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, -0.70710678118654752440084436210485, 0.01 );\r\n  }\r\n  // In BC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.5, 0.5,  0.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, c, a); \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n\r\n\r\n\r\n  // Finally we will use a test point lying below the face-plane\r\n\r\n\r\n\r\n  // Front side of AB voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-0.5, -1.0,  -1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n  }\r\n  // Back side of AB voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-0.5, 1.0,  -1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n  }\r\n  // In AB voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-0.5, 0.0,  -1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, b, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, a, c);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n  // Front side of AC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type(-1.0, 0.5,  -1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\r\n  }\r\n  // Back side of AC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 1.0, 0.5,  -1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\r\n  }\r\n  // In AC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.0, 0.5,  -1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, a, c, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, a, b);      \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n  // Front side of BC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 1.0, 1.0,  -1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.70710678118654752440084436210485, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.70710678118654752440084436210485, 0.01 );\r\n  }\r\n  // Back side of BC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.0, 0.0, -1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, c, a);\r\n    BOOST_CHECK_CLOSE( sign_p, -0.70710678118654752440084436210485, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, -0.70710678118654752440084436210485, 0.01 );\r\n  }\r\n  // In BC voronoi plane\r\n  {\r\n    vector3_type p = vector3_type( 0.5, 0.5, -1.0);\r\n    real_type sign_p = 0.0; \r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, b, c, a); \r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n\r\n    sign_p = OpenTissue::gjk::detail::signed_distance_to_edge_face_voronoi_plane(p, c, b, a);\r\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\r\n  }\r\n\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "5ab7a0e1649dd67ac4fe2d4de4b7ed18058344d6", "size": 13087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/collision/gjk/sign_dist2edge_face_vp/src/unit_sign_dist2edge_face_vp.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/collision/gjk/sign_dist2edge_face_vp/src/unit_sign_dist2edge_face_vp.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/collision/gjk/sign_dist2edge_face_vp/src/unit_sign_dist2edge_face_vp.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 40.5170278638, "max_line_length": 108, "alphanum_fraction": 0.661801788, "num_tokens": 4493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6175552624665427}}
{"text": "#include <tdp/testing/testing.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <tdp/manifold/SO3.h>\n#include <tdp/manifold/rotation.h>\n#include <tdp/manifold/SE3.h>\n\n#include <tdp/data/managed_image.h>\n#include <tdp/eigen/dense.h>\n#include <tdp/preproc/pc.h>\n\nusing namespace tdp;\n\n\nTEST(SE3, setup) {\n  \n  SE3d T;\n  std::cout << T << std::endl;\n\n  double theta = 15.*M_PI/180.;\n  Eigen::Matrix4d Tmu_;\n  Tmu_ << 1, 0, 0, 0,\n         0, cos(theta), sin(theta), 0,\n         0, -sin(theta), cos(theta), 0,\n           0,0,0,1;\n  SE3d Tmu(Tmu_);\n  \n  std::cout << Tmu << std::endl;\n  std::cout << T*Tmu << std::endl;\n  std::cout << T << std::endl;\n  std::cout << Tmu*T << std::endl;\n\n  std::cout << Tmu.Inverse()*Tmu << std::endl;\n\n//  SE3f T1(SO3f::Rx(ToRad(10.)), Eigen::Vector3f(0,0,1));\n//  std::cout << T1 << std::endl;\n//  std::cout << T1*Eigen::Vector3f(1,0,0) << std::endl;\n//  std::cout << T1*Eigen::Vector3f(0,1,0) << std::endl;\n//\n//  SE3f T2(SO3f::Rx(ToRad(10.)));\n\n//  std::cout << T-Tmu << std::endl;\n//  Eigen::Matrix<double,6,1> w = T-Tmu;\n//  std::cout << Tmu.Exp(w) << std::endl;\n//  std::cout << Tmu-T << std::endl;\n\n}\n\nTEST(SE3, transform) {\n\n  const float eps = 1e-5;\n  for (size_t i=0; i<10000; ++i) {\n    Eigen::Matrix<float,3,1> p0 = Eigen::Matrix<float,3,1>::Random();\n    SE3f T = SE3f::Random();\n    Eigen::Matrix4f Tmat = T.matrix();\n    Eigen::Matrix4f TmatInv = Tmat.inverse();\n\n    Eigen::Vector3f p1 = TmatInv.topLeftCorner(3,3)*p0 + TmatInv.topRightCorner(3,1);\n    Eigen::Vector3f p2 = T.Inverse()*p0;\n    ASSERT_TRUE(IsAppox(p1, p2, eps));\n\n    p1 = Tmat.topLeftCorner(3,3)*p0 + Tmat.topRightCorner(3,1);\n    p2 = T*p0;\n    ASSERT_TRUE(IsAppox(p1, p2, eps));\n\n  }\n}\n\nTEST(SE3, inverse) {\n\n  const float eps = 1e-5;\n  for (size_t i=0; i<10000; ++i) {\n    Eigen::Matrix<float,6,1> x0 = Eigen::Matrix<float,6,1>::Random();\n    SE3f T = SE3f::Exp_(x0);\n    Eigen::Matrix4f Tmat = T.matrix();\n    \n    Eigen::Matrix4f TmatInv = Tmat.inverse();\n    Eigen::Matrix4f Tinv = T.Inverse().matrix();\n    ASSERT_TRUE(IsAppox(TmatInv, Tinv, eps));\n\n    SE3f Tse3Inv = T.Inverse();\n    Eigen::Matrix4f Tinvinvmat = Tse3Inv.Inverse().matrix();\n    ASSERT_TRUE(IsAppox(Tinvinvmat, Tmat, eps));\n\n  }\n}\n\nTEST(SE3, expLog) {\n\n  const float eps = 1e-5;\n  for (size_t i=0; i<10000; ++i) {\n    Eigen::Matrix<float,6,1> x0 = Eigen::Matrix<float,6,1>::Random();\n    SE3f T = SE3f::Exp_(x0);\n    Eigen::Matrix<float,6,1> x1 = SE3f::Log_(T);\n    ASSERT_TRUE(IsAppox(x0, x1, eps));\n\n//    Eigen::Matrix4f Tmat = T.matrix();\n//    \n//    Eigen::Matrix4f TmatInv = Tmat.inverse();\n//    Eigen::Matrix4f Tinv = T.Inverse().matrix();\n//    ASSERT_TRUE(IsAppox(TmatInv, Tinv, eps));\n//\n//    SE3f Tse3Inv = T.Inverse();\n//    Eigen::Matrix4f Tinvinvmat = Tse3Inv.Inverse().matrix();\n//    ASSERT_TRUE(IsAppox(Tinvinvmat, Tmat, eps));\n\n  }\n}\n\nTEST(SE3, composition) {\n\n  const float eps = 1e-5;\n  for (size_t i=0; i<1000; ++i) {\n    SE3f Tw0 = SE3f::Random();\n    SE3f Tw1 = SE3f::Random();\n    Eigen::Matrix4f Tw0mat = Tw0.matrix();\n    Eigen::Matrix4f Tw1mat = Tw1.matrix();\n\n    SE3f T01 = Tw0.Inverse() * Tw1;\n    Eigen::Matrix4f T01mat = Tw0mat.inverse()*Tw1mat;\n\n    Eigen::Matrix4f T01_mat = T01.matrix();\n    ASSERT_TRUE(IsAppox(T01mat,T01_mat,eps));\n\n    SE3f Tw0w1 = Tw0 * Tw1;\n    Eigen::Matrix4f Tw0w1mat = Tw0mat*Tw1mat;\n    ASSERT_TRUE(Tw0w1mat.isApprox(Tw0w1.matrix(),eps));\n\n\n  }\n\n  SE3f Tw0;\n  Eigen::Matrix4f Tw0mat = Eigen::Matrix4f::Identity();\n  SE3f Tw1;\n  Eigen::Matrix4f Tw1mat = Eigen::Matrix4f::Identity();\n  for (size_t i=0; i<1000; ++i) {\n    Eigen::Matrix<float,6,1> x0 = 1e-3*Eigen::Matrix<float,6,1>::Random();\n    Tw0 = Tw0 * SE3f::Exp_(x0);\n    Tw0mat = Tw0mat * SE3f::Exp_(x0).matrix();\n    ASSERT_TRUE(Tw0mat.isApprox(Tw0.matrix(),eps));\n\n    Tw1 = SE3f::Exp_(x0) * Tw1;\n    Tw1mat = SE3f::Exp_(x0).matrix() * Tw1mat;\n    ASSERT_TRUE(Tw1mat.isApprox(Tw1.matrix(),eps));\n  }\n\n}\n\nTEST(SE3, exp) {\n\n  const float eps = 1e-5;\n\n  Eigen::Matrix<float,6,1> x0;\n  x0 << 0,0,ToRad(10.),0,0.1,0.1;\n  SE3f T0 = SE3f::Exp_(x0);\n  Eigen::Matrix<float,6,1> x1 = SE3f::Log_(T0);\n  std::cout << x0.transpose() << std::endl;\n  std::cout << x1.transpose() << std::endl;\n\n  ASSERT_NEAR(x0(0), x1(0), eps);\n  ASSERT_NEAR(x0(1), x1(1), eps);\n  ASSERT_NEAR(x0(2), x1(2), eps);\n  ASSERT_NEAR(x0(3), x1(3), eps);\n  ASSERT_NEAR(x0(4), x1(4), eps);\n  ASSERT_NEAR(x0(5), x1(5), eps);\n\n  x0 << 0,0,0.,0,0.1,0.1;\n  T0 = SE3f::Exp_(x0);\n  x1 = SE3f::Log_(T0);\n  std::cout << x0.transpose() << std::endl;\n  std::cout << x1.transpose() << std::endl;\n\n  ASSERT_NEAR(x0(0), x1(0), eps);\n  ASSERT_NEAR(x0(1), x1(1), eps);\n  ASSERT_NEAR(x0(2), x1(2), eps);\n  ASSERT_NEAR(x0(3), x1(3), eps);\n  ASSERT_NEAR(x0(4), x1(4), eps);\n  ASSERT_NEAR(x0(5), x1(5), eps);\n\n  for (size_t i=0; i<10000; ++i) {\n    x0 = Eigen::Matrix<float,6,1>::Random();\n    T0 = SE3f::Exp_(x0);\n    x1 = SE3f::Log_(T0);\n\n    ASSERT_NEAR(x0(0), x1(0), eps);\n    ASSERT_NEAR(x0(1), x1(1), eps);\n    ASSERT_NEAR(x0(2), x1(2), eps);\n    ASSERT_NEAR(x0(3), x1(3), eps);\n    ASSERT_NEAR(x0(4), x1(4), eps);\n    ASSERT_NEAR(x0(5), x1(5), eps);\n\n  }\n\n}\n\n#ifdef CUDA_FOUND\nTEST(SE3, gpu) {\n\n  const float eps = 1e-5;\n\n  for (size_t it=0; it<100; ++it) {\n    SE3f T = SE3f::Random();\n//    SO3f R (Eigen::Quaternion<float,Eigen::DontAlign>(T.rotation().vector()));\n    SO3f R (T.rotation());\n//    std::cout << T << std::endl;\n//    std::cout << T.rotation() << std::endl;\n//    std::cout << R << std::endl;\n\n    ManagedHostImage<Vector3fda> x(1000,1);\n    ManagedHostImage<Vector3fda> xBefore(1000,1);\n    ManagedHostImage<Vector3fda> xAfter(1000,1);\n    ManagedHostImage<Vector3fda> xAfterInv(1000,1);\n    ManagedHostImage<Vector3fda> xAfterInvRot(1000,1);\n    ManagedHostImage<Vector3fda> xAfterRot(1000,1);\n    xAfter.Fill(Vector3fda::Zero());\n    xAfterInv.Fill(Vector3fda::Zero());\n    xAfterInvRot.Fill(Vector3fda::Zero());\n    xAfterRot.Fill(Vector3fda::Zero());\n\n    ManagedDeviceImage<Vector3fda> cuX(1000,1);\n    ManagedDeviceImage<Vector3fda> cuXinv(1000,1);\n    ManagedDeviceImage<Vector3fda> cuXinvRot(1000,1);\n    ManagedDeviceImage<Vector3fda> cuXrot(1000,1);\n\n    cudaMemset(cuX.ptr_, 0, cuX.SizeBytes());\n    cudaMemset(cuXinv.ptr_, 0, cuXinv.SizeBytes());\n    cudaMemset(cuXinvRot.ptr_, 0, cuXinvRot.SizeBytes());\n    cudaMemset(cuXrot.ptr_, 0, cuXrot.SizeBytes());\n\n    for (size_t i=0; i<1000; ++i) {\n      x[i] = Vector3fda::Random();\n      xBefore[i] = x[i];\n      xAfter[i] = T*x[i];\n      xAfterInv[i] = T.Inverse()*x[i];\n      xAfterRot[i] = T.rotation()*x[i];\n      xAfterInvRot[i] = T.rotation().Inverse()*x[i];\n    }\n    cuX.CopyFrom(x, cudaMemcpyHostToDevice);\n    cuXinv.CopyFrom(x, cudaMemcpyHostToDevice);\n    cuXinvRot.CopyFrom(x, cudaMemcpyHostToDevice);\n    cuXrot.CopyFrom(x, cudaMemcpyHostToDevice);\n\n    TransformPc(T, cuX);\n    InverseTransformPc(T, cuXinv);\n    InverseTransformPc(R, cuXinvRot);\n    TransformPc(R, cuXrot);\n\n    x.CopyFrom(cuX, cudaMemcpyDeviceToHost);\n    for (size_t i=0; i<1000; ++i) {\n      ASSERT_TRUE(IsAppox(x[i],xAfter[i], eps));\n    }\n    x.CopyFrom(cuXrot, cudaMemcpyDeviceToHost);\n    for (size_t i=0; i<1000; ++i) {\n      ASSERT_TRUE(IsAppox(x[i],xAfterRot[i], eps));\n    }\n    x.CopyFrom(cuXinvRot, cudaMemcpyDeviceToHost);\n    for (size_t i=0; i<1000; ++i) {\n      ASSERT_TRUE(IsAppox(x[i],xAfterInvRot[i], eps));\n    }\n    x.CopyFrom(cuXinv, cudaMemcpyDeviceToHost);\n    for (size_t i=0; i<1000; ++i) {\n      if(!IsAppox(x[i],xAfterInv[i], eps)) {\n        std::cout << xBefore[i].transpose() << std::endl;    \n      }\n      ASSERT_TRUE(IsAppox(x[i],xAfterInv[i], eps));\n    }\n  }\n}\n#endif\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n\n", "meta": {"hexsha": "0ca27c18f210cc75a26af28df1c6ed649b98e18b", "size": 7730, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/SE3.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "test/SE3.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "test/SE3.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 28.0072463768, "max_line_length": 85, "alphanum_fraction": 0.6095730918, "num_tokens": 2894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7248702880639792, "lm_q1q2_score": 0.6175552620806963}}
{"text": "/**\n *  .file test/oglplus/math.cpp\n *  .brief Test case for math utilities.\n *\n *  .author Matus Chochlik\n *\n *  Copyright 2011-2015 Matus Chochlik. Distributed under the Boost\n *  Software License, Version 1.0. (See accompanying file\n *  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE OGLPLUS_math\n#include <boost/test/unit_test.hpp>\n\n#include <oglplus/gl.hpp>\n#include <oglplus/math/constants.hpp>\n\nBOOST_AUTO_TEST_SUITE(math)\n\nBOOST_AUTO_TEST_CASE(math_Pi)\n{\n\tBOOST_CHECK_CLOSE(oglplus::math::Pi(), 3.14159265, 0.0001);\n}\n\nBOOST_AUTO_TEST_CASE(math_2Pi_eq_TwoPi)\n{\n\tBOOST_CHECK(2*oglplus::math::Pi() == oglplus::math::TwoPi());\n}\n\nBOOST_AUTO_TEST_CASE(math_2HalfPi_eq_Pi)\n{\n\tBOOST_CHECK(2*oglplus::math::HalfPi() == oglplus::math::Pi());\n}\n\nBOOST_AUTO_TEST_CASE(math_4HalfPi_eq_TwoPi)\n{\n\tBOOST_CHECK(4*oglplus::math::HalfPi() == oglplus::math::TwoPi());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "c779ce71d55301f526eb4b4c72412aeb048b2401", "size": 965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/oglplus/math.cpp", "max_stars_repo_name": "Extrunder/oglplus", "max_stars_repo_head_hexsha": "c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 364.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T09:38:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:32:00.000Z", "max_issues_repo_path": "test/oglplus/math.cpp", "max_issues_repo_name": "Extrunder/oglplus", "max_issues_repo_head_hexsha": "c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 55.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T16:42:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-09T04:21:41.000Z", "max_forks_repo_path": "test/oglplus/math.cpp", "max_forks_repo_name": "Extrunder/oglplus", "max_forks_repo_head_hexsha": "c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 57.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T18:35:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T05:32:04.000Z", "avg_line_length": 23.5365853659, "max_line_length": 68, "alphanum_fraction": 0.7461139896, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.617555247275601}}
{"text": "/*\n(c) 2019 M. Werner - Part of the GIS++ tutorial \n- https://www.martinwerner.de/teaching/spatial-cpp\n- https://github.com/mwernerds/spatial-cpp\n\nProgram: R-Tree\nCompile: g++ -I $(BOOST_DIR) -Ofast -march=native  -Wall -std=c++11  -o 03_rtree 03_rtree.cpp\n*/\n\n#include<iostream>\n#include<fstream>\n#include <boost/geometry.hpp>\n#include <boost/algorithm/string.hpp>\n#include<chrono>\n\n#include<set>\n\n#include <boost/range/adaptor/indexed.hpp>\nusing  boost::adaptors::indexed;\n#include <boost/range/adaptor/transformed.hpp>\nusing  boost::adaptors::transformed;\n#include <boost/function_output_iterator.hpp>\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point;\ntypedef bg::model::box<point> box;\ntypedef bg::model::linestring<point> linestring;\ntypedef bg::model::polygon<point, false, false> polygon; // ccw, open polygon\ntypedef bg::model::multi_polygon<polygon> multi_polygon; // ccw, open polygon\ntypedef std::pair<box, size_t> value; // <- this is what the R-tree will hold\n\n\ntypedef bgi::rtree< value, bgi::rstar<16, 4> > rtree;\n\nstd::vector<std::pair<polygon, size_t>> dataset;\n\n\nstruct value_maker\n{\n    template<typename T>\n    inline value operator()(T const& v) const\n    {\n\tbox b;\n\tbg::envelope(v.value().first,b);\n        return value(b, v.index());\n    }\n};\n\nstd::ostream &operator<< (std::ostream &os, box &b)\n{\n    os << \"(\" << bg::get<0>(b.min_corner()) << \";\" << bg::get<1>(b.min_corner()) << \")\" << \"-->\"\n\t  << \"(\" << bg::get<0>(b.max_corner()) << \";\" << bg::get<1>(b.max_corner()) << \")\" ;\n    return os;\n}\n\npoint  operator + (const point &p, const point &b)\n{\n    return bg::make<point>(bg::get<0>(p)+bg::get<0>(b),bg::get<1>(p)+bg::get<1>(b));\n    \n}\npoint  operator - (const point &p, const point &b)\n{\n    return bg::make<point>(bg::get<0>(p)-bg::get<0>(b),bg::get<1>(p)-bg::get<1>(b));\n    \n}\n\n\npoint random_point_in_box(box b)\n{\n    double tau1 = static_cast<double> (std::rand()) / RAND_MAX;\n    double tau2 = static_cast<double> (std::rand()) / RAND_MAX;\n    return bg::make<point>(\n\tbg::get<0>(b.min_corner())+ tau1 * (bg::get<0>(b.max_corner())-bg::get<0>(b.min_corner())),\n\tbg::get<1>(b.min_corner())+ tau2 * (bg::get<1>(b.max_corner())-bg::get<1>(b.min_corner())));\n\n}\n\n\nint main(int argc, char **argv)\n{\n    std::srand(std::time(0)); //use current time as seed for random generator\n    \n// Load the OSM polygons and explode each multipolygon into polygons to be added to the index.\n    box roi(point(0,0),point(0,0));\n    { // scope for timing\n    auto start = std::chrono::high_resolution_clock::now();\n   \n    std::ifstream ifs(\"washington_dc_osm_buildings.wkt\");\n    std::string line;\n\n    \n    while(std::getline(ifs, line))\n    {\n\t// split at \";\"\n\tstd::vector<std::string> entries;\n\tboost::split(entries, line, [](char c){return c == ';';});\n\tsize_t osm_id = boost::lexical_cast<size_t>(entries[0]);\n\n\t// remove \"\n\t entries[1].erase(remove_if(entries[1].begin(), entries[1].end(), [](const char& c) {\n        return c=='\"';   }), entries[1].end());\n\tmulti_polygon mp;\n\tbg::read_wkt(entries[1],mp);\n\tfor (auto &p: mp) // each building part!\n\t{\n\t    bg::correct(p);\n\t    dataset.push_back(std::make_pair(p,osm_id));\n\t    if (bg::get<0>(roi.min_corner()) == 0){ // bad hack\n\t\tbg::envelope(p,roi);\n\t    }else{\n\t\tbox q;\n\t\tbg::envelope(p,q);\n\t\tbg::expand(roi,q);\n\t    }\n\t}\n    }\n    std::cout << \"Dataset contains \" << dataset.size() << \" polygons\" << std::endl;\n    std::cout << \"MBR of dataset: \" << roi << std::endl;\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> diff = end-start;\n    std::cout << \" Load CSV in \" << diff.count() << \"seconds\" << std::endl;\n    } // loading scope\n    // now load this into an R-tree: variant 1: sequential insert\n\n    { // sequential r-tree population\n    auto start = std::chrono::high_resolution_clock::now();\n    rtree rt;\n    \n    for (const auto &d:dataset |indexed())\n    {\n\tbox b;\n\tbg::envelope(d.value().first, b); // create MBR\n\trt.insert(value(b,d.index()));\n    }\n\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> diff = end-start;\n    std::cout << \" Sequential R-Tree in \" << diff.count() << \"seconds\" << std::endl;\n    }\n    rtree rt2; // just to have it later\n    // variant 2: bulk-load\n    { // bulk load scope\n    auto start = std::chrono::high_resolution_clock::now();\n    rt2 = rtree (dataset | indexed()\n                       | transformed(value_maker()));\n    auto end = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> diff = end-start;\n    std::cout << \" Bulk-Load R-Tree in \" << diff.count() << \"seconds\" << std::endl;\n    } // bulk load scope\n    \n    // Let us now do a kNN (k = 10) query for a single random point\n    std::vector<value> result;\n    auto p = random_point_in_box(roi);\n    // for reproducibilty:\n    p = bg::make<point>(-76.8117, 38.812);\n    std::cout << \"Anchor: \" << bg::wkt(p) << std::endl;\n    rt2.query(bgi::nearest(p, 10), std::back_inserter(result));\n    // two issues to be resolved: first, kNN is not ordered, second, r-tree knows bbox only\n    std::sort(result.begin(), result.end(), [p](const value & a, const value & b){\n\treturn bg::distance(dataset[a.second].first,p) < bg::distance(dataset[b.second].first,p );\n    });\n    \n    for (const auto &v:result | indexed())\n    {\n\tauto id = v.value().second;\n\tstd::cout << v.index() << \"\\t\" << dataset[id].second << \"\\t\" << bg::distance (p, dataset[id].first) << std::endl;\n    }\n\n    // and again something for QGIS:\n    // we will take a random point, then 10-nearest neighbors (BBOX), then double the distance for a range query.\n    // with all these results, we will write a single CSV containing classified buildings.\n    result.clear();\n    point anchor = bg::make<point> (-76.99017,38.88970);\n    std::cout << \"Anchor: \" << bg::wkt(anchor) << std::endl;\n    rt2.query(bgi::nearest(anchor, 200), std::back_inserter(result));\n    double radius = 0.03;\n\n    box range_query_box;\n    range_query_box.min_corner() = anchor - bg::make<point>(radius,radius);\n    range_query_box.max_corner() = anchor + bg::make<point>(radius,radius);\n\n    std::cout << \"Range Query Box:\" << range_query_box << std::endl;\n\n    // function_output_iterator is a nice tool as well:\n    std::set<size_t> knnids;\n    std::ofstream ofs(\"range_knn.csv\");\n    ofs <<  std::setprecision(std::numeric_limits<double>::digits10);\n    ofs << \"wkt;role\" << std::endl;\n    // first write all kNN with their ID\n    for (auto r:result)\n    {\n\tconst auto &item = dataset[r.second];\n\tofs << bg::wkt(item.first) <<\";\" << 1 << std::endl;\n\tknnids.insert(r.second);\n    }\n        \n    \n    rt2.query(bgi::within(range_query_box), boost::make_function_output_iterator([&](value const& v)\n    {\n\tconst auto &item = dataset[v.second];\n\tif (knnids.find(v.second) == knnids.end()){\n\t   ofs << bg::wkt(item.first) << \";\" << 2 << std::endl;\n\t}\n    }\n    ));\n    \n    return 0;\n}\n", "meta": {"hexsha": "50466bbee83e73ccc2ecc5096c1572de72ef2865", "size": 6998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "02_geo/03_rtree.cpp", "max_stars_repo_name": "mwernerds/spatial-cpp", "max_stars_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "02_geo/03_rtree.cpp", "max_issues_repo_name": "mwernerds/spatial-cpp", "max_issues_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02_geo/03_rtree.cpp", "max_forks_repo_name": "mwernerds/spatial-cpp", "max_forks_repo_head_hexsha": "a99921526c4818be66cdc0dc9458f5e4a9ac22fd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-08T23:57:30.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T23:57:30.000Z", "avg_line_length": 33.1658767773, "max_line_length": 114, "alphanum_fraction": 0.6217490712, "num_tokens": 2047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6175307779112831}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if !defined(LOGNORMAL_HPP)\n#define LOGNORMAL_HPP\n\n#if defined(_MSC_VER)\n#\tpragma warning(disable: 4267)\t// warning about loss of data when converting size_t to int\n#endif\n\n#include <cmath>\n//#include \"ncl/nxsdefs.h\"\n\n#include <boost/shared_ptr.hpp>\n//#include <boost/format.hpp>\n\n#include \"probability_distribution.hpp\"\n\nnamespace phycas\n{\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tThe Lognormal distribution with two parameters, the mean and standard deviation of the natural logarithm of the variable.\n*/\nclass LognormalDistribution : public ProbabilityDistribution\n\t{\n\tpublic:\n\t\t\t\t\tLognormalDistribution();\n\t\t\t\t\tLognormalDistribution(double mean, double stddev);\n\t\t\t\t\tLognormalDistribution(const LognormalDistribution & other);\n\t\t\t\t\t~LognormalDistribution();\n\n        LognormalDistribution * cloneAndSetLot(Lot * other) const;\n        LognormalDistribution * Clone() const;\n\t\tbool\t\tIsDiscrete() const;\n\t\tstd::string\tGetDistributionName() const;\n\t\tstd::string\tGetDistributionDescription() const;\n\t\tdouble\t\tGetMean() const;\n\t\tdouble\t\tGetVar() const;\n\t\tdouble\t\tGetStdDev() const;\n\t\tdouble\t\tGetCDF(double x) const;\n\t\tdouble\t\tSample() const;\n\t\tdouble\t\tGetLnPDF(double x) const;\n\t\tdouble\t\tGetRelativeLnPDF(double x) const;\n\t\tvoid\t\tSetMeanAndVariance(double mean, double var);\n\n\tprotected:\n\t\tvoid \t\t\tinitialize(double m, double s);\n\t\tvoid\t\t\tComputeLnConst();\n\n\tprotected:\n\t\tdouble\t\tlogmean;\t\t\t/**< the mean parameter of the lognormal distribution */\n\t\tdouble\t\tlogsd;\t\t\t\t/**< the standard deviation parameter of the lognormal distribution */\n\t\tdouble\t\tlogsd_squared;\t\t/**< the square of the logsd parameter (i.e. the variance of the log of this lognormal random variable) */\n\t\tdouble\t\tln_const;\t\t\t/**< the natural logarithm of the constant part of the density function */\n\t\tdouble\t\tpi_const;\t\t\t/**< precalculated (in constructor) value of pi */\n\t\tdouble\t\tsqrt2_const;\t\t/**< precalculated (in constructor) value of sqrt(2.0) */\n\n\t};\n\n} // namespace phycas\n\n#endif\n", "meta": {"hexsha": "dbf88a644f160d67b9f52f9dbb69baf8fe298cf7", "size": 3526, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/lognormal.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/lognormal.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/lognormal.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 44.075, "max_line_length": 164, "alphanum_fraction": 0.5791264889, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6175307750623009}}
{"text": "/**\n * @file performance_functions_test.cpp\n * @author Marcus Edel\n *\n *  Tests for the various performance functions.\n */\n#include <mlpack/core.hpp>\n\n#include <mlpack/methods/ann/performance_functions/mse_function.hpp>\n#include <mlpack/methods/ann/performance_functions/cee_function.hpp>\n#include <mlpack/methods/ann/performance_functions/sse_function.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"old_boost_test_definitions.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::ann;\n\nBOOST_AUTO_TEST_SUITE(PerformanceFunctionsTest);\n\n// Test the mean squared error performance function.\nBOOST_AUTO_TEST_CASE(MeanSquaredErrorTest)\n{\n  arma::colvec input(\"1.0 0.0 1.0 0.0 -1.0 0.0 -1.0 0.0\");\n  arma::colvec target = arma::zeros<arma::colvec>(8);\n\n  BOOST_REQUIRE_EQUAL(MeanSquaredErrorFunction::Error(input, target), 0.5);\n}\n\n// Test the cross entropy performance function.\nBOOST_AUTO_TEST_CASE(CrossEntropyErrorTest)\n{\n  arma::colvec input;\n  input << std::exp(-2.0) << std::exp(-1.0);\n  arma::colvec target = arma::ones<arma::colvec>(2);\n\n  BOOST_REQUIRE_EQUAL(CrossEntropyErrorFunction<>::Error(input, target), 3);\n}\n\n// Test the sum squared error performance function.\nBOOST_AUTO_TEST_CASE(SumSquaredErrorTest)\n{\n  arma::colvec input(\"1.0 0.0 1.0 0.0 -1.0 0.0 -1.0 0.0\");\n  arma::colvec target = arma::zeros<arma::colvec>(8);\n\n  BOOST_REQUIRE_EQUAL(SumSquaredErrorFunction::Error(input, target), 4);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "84839a13a7686886284906621023c94cd5f35fca", "size": 1443, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/performance_functions_test.cpp", "max_stars_repo_name": "vj-ug/Contribution-to-mlpack", "max_stars_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T11:59:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-17T11:59:20.000Z", "max_issues_repo_path": "src/mlpack/tests/performance_functions_test.cpp", "max_issues_repo_name": "vj-ug/Contribution-to-mlpack", "max_issues_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/performance_functions_test.cpp", "max_forks_repo_name": "vj-ug/Contribution-to-mlpack", "max_forks_repo_head_hexsha": "0ddb5ed463861f459ff2829712bdc59ba9d810b0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.86, "max_line_length": 76, "alphanum_fraction": 0.753984754, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.7122321903471562, "lm_q1q2_score": 0.6175307734191027}}
{"text": "#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/features2d.hpp>\n#include <iostream>\n#include <armadillo>\n#include \"highgui.h\"\n\nusing namespace std;\nusing namespace cv;\n\nvoid detect(cv::Mat &frame) {\n\tint h1 = 100;\n\tint h2 = 179;\n\tint s1 = 125;\n\tint s2 = 255;\n\tint v1 = 50;\n\tint v2 = 170;\n\tcv::Mat hsv;\n\tcv::cvtColor(frame, hsv, COLOR_BGR2HSV);\n\tcv::Mat hsv2mask, hsv2;\n\tcv::inRange(hsv, cv::Scalar(h1, s1, v1), cv::Scalar(h2, s2, v2), hsv2mask);\n\n\tarma::mat I;\n\tcvt_opencv2arma(hsv2mask, I);\n\tif (arma::accu(I) < 10.0) {\n\t\treturn;\n\t}\n\tarma::rowvec r = arma::sum(I, 0);\n\tarma::colvec c = arma::sum(I, 1);\n\tdouble midx = arma::sum(r * arma::cumsum(arma::ones<arma::vec>(r.n_elem))) / arma::sum(r);\n\tdouble midy = arma::sum(c % arma::cumsum(arma::ones<arma::vec>(c.n_elem))) / arma::sum(c);\n\n\tdouble covx = sqrt(arma::sum(r * arma::square(arma::cumsum(arma::ones<arma::vec>(r.n_elem)) - midx)) / arma::sum(r));\n\tdouble covy = sqrt(arma::sum(c % arma::square(arma::cumsum(arma::ones<arma::vec>(c.n_elem)) - midy)) / arma::sum(c));\n\tdouble estw = covx;\n\tdouble esth = estw;\n\testw *= 3; // strange constants\n\testh *= 3;\n\n\tarma::vec pos = arma::vec({ midx, midy });\n\tdouble width = covx * 3;\n\tcout << \"pos: \" << pos << endl;\n\tcout << \"width: \" << width << endl;\n}\n\nint main(int argc, char *argv[]) {\n\tif (argc != 8) {\n\t\tcout << \"usage: ./test img h1 h2 s1 s2 v1 v2\\n\";\n\t\treturn 1;\n\t}\n\tint h1 = atoi(argv[2]);\n\tint h2 = atoi(argv[3]);\n\tint s1 = atoi(argv[4]);\n\tint s2 = atoi(argv[5]);\n\tint v1 = atoi(argv[6]);\n\tint v2 = atoi(argv[7]);\n\n\t// convert to hsv\n\tVideoCapture cam(1);\n\n\tarma::vec xbuf(10, arma::fill::zeros);\n\tarma::vec ybuf(10, arma::fill::zeros);\n\tint xind = 0, yind = 0;\n\tbool stable = false;\n\n\twhile (1) {\n\t\tMat img;\n\t\tcam.read(img);\n\t\tMat hsv;\n\t\tcvtColor(img, hsv, COLOR_BGR2HSV);\n\n\t\t// in range masking\n\t\tMat hsv2mask, hsv2;\n\t\tinRange(hsv, Scalar(h1, s1, v1), Scalar(h2, s2, v2), hsv2mask);\n\t\t//hsv.copyTo(hsv2, hsv2mask);\n\n\t\tarma::mat I;\n\t\tcvt_opencv2arma(hsv2mask, I);\n\t\tarma::rowvec r = arma::sum(I, 0);\n\t\tarma::colvec c = arma::sum(I, 1);\n\t\tdouble midx = arma::sum(r * arma::cumsum(arma::ones<arma::vec>(r.n_elem))) / arma::sum(r);\n\t\tdouble midy = arma::sum(c % arma::cumsum(arma::ones<arma::vec>(c.n_elem))) / arma::sum(c);\n\t\tstable = true;\n\t\tif (midx < 1 || (midx > (int)I.n_cols - 1) || arma::sum(r) == 0) {\n\t\t\tmidx = 0;\n\t\t}\n\t\tif (midy < 1 || (midy > (int)I.n_rows - 1) || arma::sum(c) == 0) {\n\t\t\tmidy = 0;\n\t\t}\n\n\t\t// remove noise\n\t\tif (midx == 0 || midy == 0) {\n\t\t\tstable = false;\n\t\t}\n\t\txbuf[xind] = midx;\n\t\tybuf[yind] = midy;\n\t\txind = (xind + 1) % (int)xbuf.n_elem;\n\t\tyind = (yind + 1) % (int)ybuf.n_elem;\n\t\tmidx = arma::mean(xbuf);\n\t\tmidy = arma::mean(ybuf);\n\t\tif (sqrt(arma::var(xbuf) * arma::var(xbuf) + arma::var(ybuf) + arma::var(ybuf)) > 70.0) {\n\t\t\tstable = false;\n\t\t}\n\t\t\n\t\tVec3b color(255, 0, 0);\n\t\tcout << \"arma:: \" << midx << \", \" << midy << endl;\n\t\tcout << \"stable: \" << stable << endl;\n\t\tcircle(img, Point((int)midx, (int)midy), 4, color, 0);\n\n\t\tdouble covx = sqrt(arma::sum(r * arma::square(arma::cumsum(arma::ones<arma::vec>(r.n_elem)) - midx)) / arma::sum(r));\n\t\tdouble covy = sqrt(arma::sum(c % arma::square(arma::cumsum(arma::ones<arma::vec>(c.n_elem)) - midy)) / arma::sum(c));\n\t\tdouble estw = covx * 3;\n\t\tdouble esth = covy * 3;\n\n\t\trectangle(img, Rect(midx-estw/2,midy-esth/2,estw,esth), Scalar(0, 0, 255), 2);\n\n\t\t// use histogram binning to get the center\n\n\t\t// create blob params\n\t\t/*SimpleBlobDetector::Params params;\n\n\t\t// Change thresholds\n\t\tparams.minThreshold = 10;\n\t\tparams.maxThreshold = 200;\n\n\t\t// Filter by Area.\n\t\tparams.filterByArea = true;\n\t\tparams.minArea = 1500;\n\n\t\t// Filter by Circularity\n\t\tparams.filterByCircularity = true;\n\t\tparams.minCircularity = 0.1;\n\n\t\t// Filter by Convexity\n\t\tparams.filterByConvexity = true;\n\t\tparams.minConvexity = 0.87;\n\n\t\t// Filter by Inertia\n\t\tparams.filterByInertia = true;\n\t\tparams.minInertiaRatio = 0.01;\n\n\t\tPtr<SimpleBlobDetector> blob = SimpleBlobDetector::create(params);\n\t\tvector<KeyPoint> kp;\n\t\tMat des;\n\t\tMat hsvd = hsv2mask * -0.75 + 255;\n\t\tblob->detect(hsvd, kp);\n\n\t\tcout << \"found \" << kp.size() << \" matches\\n\";\n\n\t\tMat kpimg;\n\t\tdrawKeypoints(img, kp, kpimg, Scalar(0, 0, 255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);*/\n\n\t\timshow(\"oldhsv\", hsv);\n\t\timshow(\"newhsv\", hsv2mask);\n\t\timshow(\"img\", img);\n\t\tif (waitKey(30) & 0xff == 'Q') {\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn 1;\n}\n", "meta": {"hexsha": "6210d43974a53986725a74c2db88b3ec93dcf2ba", "size": 4437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_temp_/hsvcolorsegment/videotest.cpp", "max_stars_repo_name": "TimothyYong/Tachikoma-Project", "max_stars_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-02-02T23:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2016-02-02T23:13:54.000Z", "max_issues_repo_path": "_temp_/hsvcolorsegment/videotest.cpp", "max_issues_repo_name": "TimothyYong/Tachikoma-Project", "max_issues_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_temp_/hsvcolorsegment/videotest.cpp", "max_forks_repo_name": "TimothyYong/Tachikoma-Project", "max_forks_repo_head_hexsha": "c7af70f2c58fe43f25331fd03589845480ae0f16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2208588957, "max_line_length": 119, "alphanum_fraction": 0.61392833, "num_tokens": 1648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6175307681230667}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/mult.hpp>\n#include <boost/hana/one.hpp>\n\n#include \"matrix/comparable.hpp\"\n#include \"matrix/ring.hpp\"\nnamespace hana = boost::hana;\nusing namespace cppcon;\n\n\nint main() {\n    // mult\n    {\n        auto a = matrix(\n            row(1, 2, 3),\n            row(4, 5, 6)\n        );\n\n        auto b = matrix(\n            row(1, 2),\n            row(3, 4),\n            row(5, 6)\n        );\n\n        BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n            hana::mult(a, b),\n            matrix(\n                row(1*1 + 2*3 + 5*3, 1*2 + 2*4 + 3*6),\n                row(4*1 + 3*5 + 5*6, 4*2 + 5*4 + 6*6)\n            )\n        ));\n    }\n\n    // one\n    {\n        BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n            hana::one<Matrix<1, 1>>(),\n            matrix(\n                row(1)\n            )\n        ));\n\n        BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n            hana::one<Matrix<2, 2>>(),\n            matrix(\n                row(1, 0),\n                row(0, 1)\n            )\n        ));\n\n        BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n            hana::one<Matrix<3, 3>>(),\n            matrix(\n                row(1, 0, 0),\n                row(0, 1, 0),\n                row(0, 0, 1)\n            )\n        ));\n\n        BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n            hana::one<Matrix<4, 4>>(),\n            matrix(\n                row(1, 0, 0, 0),\n                row(0, 1, 0, 0),\n                row(0, 0, 1, 0),\n                row(0, 0, 0, 1)\n            )\n        ));\n\n        BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n            hana::one<Matrix<4, 5>>(),\n            matrix(\n                row(1, 0, 0, 0, 0),\n                row(0, 1, 0, 0, 0),\n                row(0, 0, 1, 0, 0),\n                row(0, 0, 0, 1, 0)\n            )\n        ));\n\n        BOOST_HANA_CONSTEXPR_CHECK(hana::equal(\n            hana::one<Matrix<5, 4>>(),\n            matrix(\n                row(1, 0, 0, 0),\n                row(0, 1, 0, 0),\n                row(0, 0, 1, 0),\n                row(0, 0, 0, 1),\n                row(0, 0, 0, 0)\n            )\n        ));\n    }\n}\n", "meta": {"hexsha": "a7f8094a61b90a50515302e9fe91a0a8ee452132", "size": 2313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cppcon_2014/ring.cpp", "max_stars_repo_name": "qicosmos/hana", "max_stars_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T05:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T21:48:27.000Z", "max_issues_repo_path": "example/cppcon_2014/ring.cpp", "max_issues_repo_name": "qicosmos/hana", "max_issues_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/cppcon_2014/ring.cpp", "max_forks_repo_name": "qicosmos/hana", "max_forks_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-06T10:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-06T10:50:17.000Z", "avg_line_length": 23.3636363636, "max_line_length": 78, "alphanum_fraction": 0.3990488543, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6175307677211389}}
{"text": "\n//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_SPECIAL_LEGENDRE_HPP\n#define BOOST_MATH_SPECIAL_LEGENDRE_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <utility>\n#include <vector>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/tools/config.hpp>\n\nnamespace boost{\nnamespace math{\n\n// Recurrance relation for legendre P and Q polynomials:\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type\n   legendre_next(unsigned l, T1 x, T2 Pl, T3 Plm1)\n{\n   typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n   return ((2 * l + 1) * result_type(x) * result_type(Pl) - l * result_type(Plm1)) / (l + 1);\n}\n\nnamespace detail{\n\n// Implement Legendre P and Q polynomials via recurrance:\ntemplate <class T, class Policy>\nT legendre_imp(unsigned l, T x, const Policy& pol, bool second = false)\n{\n   static const char* function = \"boost::math::legrendre_p<%1%>(unsigned, %1%)\";\n   // Error handling:\n   if((x < -1) || (x > 1))\n      return policies::raise_domain_error<T>(\n         function,\n         \"The Legendre Polynomial is defined for\"\n         \" -1 <= x <= 1, but got x = %1%.\", x, pol);\n\n   T p0, p1;\n   if(second)\n   {\n      // A solution of the second kind (Q):\n      p0 = (boost::math::log1p(x, pol) - boost::math::log1p(-x, pol)) / 2;\n      p1 = x * p0 - 1;\n   }\n   else\n   {\n      // A solution of the first kind (P):\n      p0 = 1;\n      p1 = x;\n   }\n   if(l == 0)\n      return p0;\n\n   unsigned n = 1;\n\n   while(n < l)\n   {\n      std::swap(p0, p1);\n      p1 = boost::math::legendre_next(n, x, p0, p1);\n      ++n;\n   }\n   return p1;\n}\n\ntemplate <class T, class Policy>\nT legendre_p_prime_imp(unsigned l, T x, const Policy& pol, T* Pn \n#ifdef BOOST_NO_CXX11_NULLPTR\n   = 0\n#else\n   = nullptr\n#endif\n)\n{\n   static const char* function = \"boost::math::legrendre_p_prime<%1%>(unsigned, %1%)\";\n   // Error handling:\n   if ((x < -1) || (x > 1))\n      return policies::raise_domain_error<T>(\n         function,\n         \"The Legendre Polynomial is defined for\"\n         \" -1 <= x <= 1, but got x = %1%.\", x, pol);\n   \n   if (l == 0)\n    {\n        if (Pn)\n        {\n           *Pn = 1;\n        }\n        return 0;\n    }\n    T p0 = 1;\n    T p1 = x;\n    T p_prime;\n    bool odd = l & 1;\n    // If the order is odd, we sum all the even polynomials:\n    if (odd)\n    {\n        p_prime = p0;\n    }\n    else // Otherwise we sum the odd polynomials * (2n+1)\n    {\n        p_prime = 3*p1;\n    }\n\n    unsigned n = 1;\n    while(n < l - 1)\n    {\n       std::swap(p0, p1);\n       p1 = boost::math::legendre_next(n, x, p0, p1);\n       ++n;\n       if (odd)\n       {\n          p_prime += (2*n+1)*p1;\n          odd = false;\n       }\n       else\n       {\n           odd = true;\n       }\n    }\n    // This allows us to evaluate the derivative and the function for the same cost.\n    if (Pn)\n    {\n        std::swap(p0, p1);\n        *Pn = boost::math::legendre_next(n, x, p0, p1);\n    }\n    return p_prime;\n}\n\ntemplate <class T, class Policy>\nstruct legendre_p_zero_func\n{\n   int n;\n   const Policy& pol;\n\n   legendre_p_zero_func(int n_, const Policy& p) : n(n_), pol(p) {}\n\n   std::pair<T, T> operator()(T x) const\n   { \n      T Pn;\n      T Pn_prime = detail::legendre_p_prime_imp(n, x, pol, &Pn);\n      return std::pair<T, T>(Pn, Pn_prime); \n   };\n};\n\ntemplate <class T, class Policy>\nstd::vector<T> legendre_p_zeros_imp(int n, const Policy& pol)\n{\n    using std::cos;\n    using std::sin;\n    using std::ceil;\n    using std::sqrt;\n    using boost::math::constants::pi;\n    using boost::math::constants::half;\n    using boost::math::tools::newton_raphson_iterate;\n\n    BOOST_ASSERT(n >= 0);\n    std::vector<T> zeros;\n    if (n == 0)\n    {\n        // There are no zeros of P_0(x) = 1.\n        return zeros;\n    }\n    int k;\n    if (n & 1)\n    {\n        zeros.resize((n-1)/2 + 1, std::numeric_limits<T>::quiet_NaN());\n        zeros[0] = 0;\n        k = 1;\n    }\n    else\n    {\n        zeros.resize(n/2, std::numeric_limits<T>::quiet_NaN());\n        k = 0;\n    }\n    T half_n = ceil(n*half<T>());\n\n    while (k < (int)zeros.size())\n    {\n        // Bracket the root: Szego:\n        // Gabriel Szego, Inequalities for the Zeros of Legendre Polynomials and Related Functions, Transactions of the American Mathematical Society, Vol. 39, No. 1 (1936)\n        T theta_nk =  ((half_n - half<T>()*half<T>() - static_cast<T>(k))*pi<T>())/(static_cast<T>(n)+half<T>());\n        T lower_bound = cos( (half_n - static_cast<T>(k))*pi<T>()/static_cast<T>(n + 1));\n        T cos_nk = cos(theta_nk);\n        T upper_bound = cos_nk;\n        // First guess follows from:\n        //  F. G. Tricomi, Sugli zeri dei polinomi sferici ed ultrasferici, Ann. Mat. Pura Appl., 31 (1950), pp. 93\u201397;\n        T inv_n_sq = 1/static_cast<T>(n*n);\n        T sin_nk = sin(theta_nk);\n        T x_nk_guess = (1 - inv_n_sq/static_cast<T>(8) + inv_n_sq /static_cast<T>(8*n) - (inv_n_sq*inv_n_sq/384)*(39  - 28 / (sin_nk*sin_nk) ) )*cos_nk;\n\n        boost::uintmax_t number_of_iterations = policies::get_max_root_iterations<Policy>();\n\n        legendre_p_zero_func<T, Policy> f(n, pol);\n\n        const T x_nk = newton_raphson_iterate(f, x_nk_guess,\n                                              lower_bound, upper_bound,\n                                              policies::digits<T, Policy>(),\n                                              number_of_iterations);\n\n        BOOST_ASSERT(lower_bound < x_nk);\n        BOOST_ASSERT(upper_bound > x_nk);\n        zeros[k] = x_nk;\n        ++k;\n    }\n    return zeros;\n}\n\n} // namespace detail\n\ntemplate <class T, class Policy>\ninline typename boost::enable_if_c<policies::is_policy<Policy>::value, typename tools::promote_args<T>::type>::type\n   legendre_p(int l, T x, const Policy& pol)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   static const char* function = \"boost::math::legendre_p<%1%>(unsigned, %1%)\";\n   if(l < 0)\n      return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_imp(-l-1, static_cast<value_type>(x), pol, false), function);\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_imp(l, static_cast<value_type>(x), pol, false), function);\n}\n\n\ntemplate <class T, class Policy>\ninline typename boost::enable_if_c<policies::is_policy<Policy>::value, typename tools::promote_args<T>::type>::type\n   legendre_p_prime(int l, T x, const Policy& pol)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   static const char* function = \"boost::math::legendre_p_prime<%1%>(unsigned, %1%)\";\n   if(l < 0)\n      return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_p_prime_imp(-l-1, static_cast<value_type>(x), pol), function);\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_p_prime_imp(l, static_cast<value_type>(x), pol), function);\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type\n   legendre_p(int l, T x)\n{\n   return boost::math::legendre_p(l, x, policies::policy<>());\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type\n   legendre_p_prime(int l, T x)\n{\n   return boost::math::legendre_p_prime(l, x, policies::policy<>());\n}\n\ntemplate <class T, class Policy>\ninline std::vector<T> legendre_p_zeros(int l, const Policy& pol)\n{\n    if(l < 0)\n        return detail::legendre_p_zeros_imp<T>(-l-1, pol);\n\n    return detail::legendre_p_zeros_imp<T>(l, pol);\n}\n\n\ntemplate <class T>\ninline std::vector<T> legendre_p_zeros(int l)\n{\n   return boost::math::legendre_p_zeros<T>(l, policies::policy<>());\n}\n\ntemplate <class T, class Policy>\ninline typename boost::enable_if_c<policies::is_policy<Policy>::value, typename tools::promote_args<T>::type>::type\n   legendre_q(unsigned l, T x, const Policy& pol)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_imp(l, static_cast<value_type>(x), pol, true), \"boost::math::legendre_q<%1%>(unsigned, %1%)\");\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type\n   legendre_q(unsigned l, T x)\n{\n   return boost::math::legendre_q(l, x, policies::policy<>());\n}\n\n// Recurrence for associated polynomials:\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type\n   legendre_next(unsigned l, unsigned m, T1 x, T2 Pl, T3 Plm1)\n{\n   typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n   return ((2 * l + 1) * result_type(x) * result_type(Pl) - (l + m) * result_type(Plm1)) / (l + 1 - m);\n}\n\nnamespace detail{\n// Legendre P associated polynomial:\ntemplate <class T, class Policy>\nT legendre_p_imp(int l, int m, T x, T sin_theta_power, const Policy& pol)\n{\n   // Error handling:\n   if((x < -1) || (x > 1))\n      return policies::raise_domain_error<T>(\n      \"boost::math::legendre_p<%1%>(int, int, %1%)\",\n         \"The associated Legendre Polynomial is defined for\"\n         \" -1 <= x <= 1, but got x = %1%.\", x, pol);\n   // Handle negative arguments first:\n   if(l < 0)\n      return legendre_p_imp(-l-1, m, x, sin_theta_power, pol);\n   if(m < 0)\n   {\n      int sign = (m&1) ? -1 : 1;\n      return sign * boost::math::tgamma_ratio(static_cast<T>(l+m+1), static_cast<T>(l+1-m), pol) * legendre_p_imp(l, -m, x, sin_theta_power, pol);\n   }\n   // Special cases:\n   if(m > l)\n      return 0;\n   if(m == 0)\n      return boost::math::legendre_p(l, x, pol);\n\n   T p0 = boost::math::double_factorial<T>(2 * m - 1, pol) * sin_theta_power;\n\n   if(m&1)\n      p0 *= -1;\n   if(m == l)\n      return p0;\n\n   T p1 = x * (2 * m + 1) * p0;\n\n   int n = m + 1;\n\n   while(n < l)\n   {\n      std::swap(p0, p1);\n      p1 = boost::math::legendre_next(n, m, x, p0, p1);\n      ++n;\n   }\n   return p1;\n}\n\ntemplate <class T, class Policy>\ninline T legendre_p_imp(int l, int m, T x, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n   // TODO: we really could use that mythical \"pow1p\" function here:\n   return legendre_p_imp(l, m, x, static_cast<T>(pow(1 - x*x, T(abs(m))/2)), pol);\n}\n\n}\n\ntemplate <class T, class Policy>\ninline typename tools::promote_args<T>::type\n   legendre_p(int l, int m, T x, const Policy& pol)\n{\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::legendre_p_imp(l, m, static_cast<value_type>(x), pol), \"bost::math::legendre_p<%1%>(int, int, %1%)\");\n}\n\ntemplate <class T>\ninline typename tools::promote_args<T>::type\n   legendre_p(int l, int m, T x)\n{\n   return boost::math::legendre_p(l, m, x, policies::policy<>());\n}\n\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_SPECIAL_LEGENDRE_HPP\n", "meta": {"hexsha": "6028b377d30db6d5325e902efd80343376a089df", "size": 11231, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CranApp/R-Portable/App/R-Portable/library/BH/include/boost/math/special_functions/legendre.hpp", "max_stars_repo_name": "singhmanish979/Trend-Analytics", "max_stars_repo_head_hexsha": "c6dacb4288884ba8086f1ebc0d2e6067486d165b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2018-10-19T01:56:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:30:19.000Z", "max_issues_repo_path": "CranApp/R-Portable/App/R-Portable/library/BH/include/boost/math/special_functions/legendre.hpp", "max_issues_repo_name": "singhmanish979/Trend-Analytics", "max_issues_repo_head_hexsha": "c6dacb4288884ba8086f1ebc0d2e6067486d165b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2018-03-28T15:16:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-05T09:42:02.000Z", "max_forks_repo_path": "CranApp/R-Portable/App/R-Portable/library/BH/include/boost/math/special_functions/legendre.hpp", "max_forks_repo_name": "singhmanish979/Trend-Analytics", "max_forks_repo_head_hexsha": "c6dacb4288884ba8086f1ebc0d2e6067486d165b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2018-08-07T00:47:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:30:23.000Z", "avg_line_length": 30.0294117647, "max_line_length": 175, "alphanum_fraction": 0.6234529427, "num_tokens": 3374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.6175307628270307}}
{"text": "#include \"prime.hpp\"\n\n// Miller-Rabin prime test algorithm.\n#include <boost/multiprecision/miller_rabin.hpp>\n#include <random>\n\nboost::multiprecision::cpp_int cryptb::prime::gen_random(const int num_bytes, random_engine& engine)\n{\n\tboost::multiprecision::cpp_int candidate;\n\tstd::mt19937_64 miller_rabin_engine(static_cast<std::mt19937_64::result_type>(engine.operator()(sizeof(std::mt19937_64::result_type))));\n\tdo\n\t{\n\t\tcandidate = engine.operator()(num_bytes);\n\t\tif (rand() % 2 == 0)\n\t\t\tcandidate += 1;\n\t\t// 64 Should be enough. The higher the number of trials, the lower the probability is for a false positive.\n\t\t// Note: making this number lower will significantly improve performance.\n\t} while (boost::multiprecision::miller_rabin_test(candidate, 64, miller_rabin_engine) == false);\n\treturn candidate;\n}\n", "meta": {"hexsha": "75cc326791c234ffb83694e52e9db7908e967336", "size": 810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rsa_cpp/prime.cpp", "max_stars_repo_name": "NatanFreeman/rsa_cpp", "max_stars_repo_head_hexsha": "c703be3860d172201eab150826427467e6d0ee7f", "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": "rsa_cpp/prime.cpp", "max_issues_repo_name": "NatanFreeman/rsa_cpp", "max_issues_repo_head_hexsha": "c703be3860d172201eab150826427467e6d0ee7f", "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": "rsa_cpp/prime.cpp", "max_forks_repo_name": "NatanFreeman/rsa_cpp", "max_forks_repo_head_hexsha": "c703be3860d172201eab150826427467e6d0ee7f", "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": 38.5714285714, "max_line_length": 137, "alphanum_fraction": 0.7567901235, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.6175233891584091}}
{"text": "#pragma once\n\n/* Multi-key search */\n\n#include \"pbc/pbc.h\"\n#include <NTL/ZZ.h>\n#include <string>\n#include \"main/ec.hh\"\n\n\nclass mksum {\npublic:\n\n    mksum();\n    ~mksum();\n    \n\tstd::vector<NTL::ZZ> keygen() const;\n\n    NTL::ZZ encrypt(const std::vector<NTL::ZZ> & pk, const NTL::ZZ & word);\n    NTL::ZZ add(const std::vector<NTL::ZZ> & pk, const NTL::ZZ & c1, const NTL::ZZ & c2);\n    NTL::ZZ decrypt(const std::vector<NTL::ZZ> & k, const NTL::ZZ & cipher);\n\n\tstd::vector<NTL::ZZ> from_bytes(const std::string & serial);\n    static std::string to_bytes(const std::vector<NTL::ZZ> & k);\n\n\tNTL::ZZ from_bytesN(const std::string & serial);\n    static std::string to_bytes(const NTL::ZZ & k);\n};\n\n\n", "meta": {"hexsha": "5cbdaf45ad3339bd672654ca24a5cf7e53398992", "size": 694, "ext": "hh", "lang": "C++", "max_stars_repo_path": "enc_modules/crypto_mk/main/multikey_sum.hh", "max_stars_repo_name": "Tofuseng/Mylar", "max_stars_repo_head_hexsha": "852bbeb27e077e36cdc561803d33bafa5dc795a9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 240.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T10:47:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T10:50:34.000Z", "max_issues_repo_path": "enc_modules/crypto_mk/main/multikey_sum.hh", "max_issues_repo_name": "eternaltyro/mylar", "max_issues_repo_head_hexsha": "18e9d0e6ef8fd836073c8bc47d79bb76c5405da5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-03-18T14:35:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-11T06:01:41.000Z", "max_forks_repo_path": "enc_modules/crypto_mk/main/multikey_sum.hh", "max_forks_repo_name": "eternaltyro/mylar", "max_forks_repo_head_hexsha": "18e9d0e6ef8fd836073c8bc47d79bb76c5405da5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 42.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T12:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T04:21:47.000Z", "avg_line_length": 22.3870967742, "max_line_length": 89, "alphanum_fraction": 0.6268011527, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.6175233891291603}}
{"text": "\ufeff#include <armadillo>\n#include <bitset>\n\nusing namespace arma;\nusing namespace std;\n\nmat crearTuplas(vec datos,\n                unsigned int longitudTupla)\n{\n    mat tuplas(datos.n_elem - longitudTupla + 1, longitudTupla);\n\n    for (unsigned int i = 0; i < tuplas.n_rows; ++i) {\n        rowvec tupla = datos(span(i, i + longitudTupla - 1)).t();\n        tuplas.row(i) = tupla;\n    }\n\n    return tuplas;\n}\n\nvec normalizar(vec serieOriginal, vec serieACambiar)\n{\n    const double minimo = min(serieOriginal);\n    const double rango = max(serieOriginal) - minimo;\n\n    vec result = (serieACambiar - minimo) / rango;\n\n    return result;\n}\n\nvec desnormalizar(vec serieOriginal, vec serieNormalizada)\n{\n    const double minimo = min(serieOriginal);\n    const double rango = max(serieOriginal) - minimo;\n\n    vec result = serieNormalizada * rango + minimo;\n\n    return result;\n}\n\nstruct VectorParticionado {\n    vec entrenamiento;\n    vec evaluacion;\n    vec prueba;\n};\n\nstruct ConjuntoDatos {\n    mat tuplasEntrada;\n    mat tuplasSalida;\n};\n\nstruct Particion {\n    ConjuntoDatos entrenamiento;\n    ConjuntoDatos evaluacion;\n    ConjuntoDatos prueba;\n};\n\n//mat agregarIndiceTemporal(const mat& tuplas)\n//{\n//    vec indice = linspace(1, tuplas.n_rows - 1, tuplas.n_rows);\n//    indice = normalizar(indice, indice);\n\n//    return join_horiz(indice, tuplas);\n//}\n\nConjuntoDatos\nagruparEntradasConSalidas(vector<vec> seriesEntrada,\n                          vec serieSalida,\n                          unsigned int retrasosEntrada,\n                          unsigned int nSalidas)\n{\n    mat tuplasEntrada;\n    for (vec& serie : seriesEntrada) {\n        // Se eliminan los ultimos nSalidas elementos de cada serie.\n        // Como se van a usar como salida deseada, no pueden formar\n        // parte de las entradas.\n        serie = serie.head(serie.n_elem - nSalidas);\n        mat tuplas = crearTuplas(serie, retrasosEntrada);\n\n        tuplasEntrada.insert_cols(tuplasEntrada.n_cols, tuplas);\n    }\n\n    // Los primeros retrasosEntrada elementos de serieSalida no pueden usarse como\n    // salida deseada, ya que no va a haber retrasosEntrada elementos anteriores\n    // para hacer la predicci\u00f3n.\n    serieSalida = serieSalida.tail(serieSalida.n_elem - retrasosEntrada);\n    const mat tuplasSalida = crearTuplas(serieSalida, nSalidas);\n\n    if (tuplasEntrada.n_rows != tuplasSalida.n_rows)\n        throw runtime_error(\"Esto no deber\u00eda pasar\");\n\n    return {tuplasEntrada, tuplasSalida};\n}\n\nParticion\narmarTuplas(vector<VectorParticionado> entradasParticionadas,\n            VectorParticionado salidaParticionada,\n            unsigned int retrasosEntrada,\n            unsigned int nSalidas)\n{\n    vector<vec> seriesEntradaEntrenamiento;\n    vector<vec> seriesEntradaEvaluacion;\n    vector<vec> seriesEntradaPrueba;\n    for (const VectorParticionado& vp : entradasParticionadas) {\n        seriesEntradaEntrenamiento.push_back(vp.entrenamiento);\n        seriesEntradaEvaluacion.push_back(vp.evaluacion);\n        seriesEntradaPrueba.push_back(vp.prueba);\n    }\n\n    Particion result;\n    result.entrenamiento = agruparEntradasConSalidas(seriesEntradaEntrenamiento,\n                                                     salidaParticionada.entrenamiento,\n                                                     retrasosEntrada,\n                                                     nSalidas);\n    result.evaluacion = agruparEntradasConSalidas(seriesEntradaEvaluacion,\n                                                  salidaParticionada.evaluacion,\n                                                  retrasosEntrada,\n                                                  nSalidas);\n    result.prueba = agruparEntradasConSalidas(seriesEntradaPrueba,\n                                              salidaParticionada.prueba,\n                                              retrasosEntrada,\n                                              nSalidas);\n\n    return result;\n}\n\npair<vector<VectorParticionado>, VectorParticionado>\nparticionar(vector<vec> seriesEntrada,\n            vec serieSalida)\n{\n    const int nDatos = serieSalida.n_elem;\n    const int nDatosPrueba = nDatos * 0.1;\n    const int nDatosEvaluacion = nDatos * 0.2;\n    const int nDatosEntrenamiento = nDatos - nDatosPrueba - nDatosEvaluacion;\n\n    vector<VectorParticionado> entradasParticionadas;\n    for (const vec& entrada : seriesEntrada) {\n        VectorParticionado entradaParticionada;\n        entradaParticionada.entrenamiento = entrada.head(nDatosEntrenamiento);\n        entradaParticionada.evaluacion = entrada(span(nDatosEntrenamiento,\n                                                      nDatosEntrenamiento + nDatosEvaluacion - 1));\n        entradaParticionada.prueba = entrada.tail(nDatosPrueba);\n\n        entradasParticionadas.push_back(entradaParticionada);\n    }\n\n    VectorParticionado salidaParticionada;\n    salidaParticionada.entrenamiento = serieSalida.head(nDatosEntrenamiento);\n    salidaParticionada.evaluacion = serieSalida(span(nDatosEntrenamiento,\n                                                     nDatosEntrenamiento + nDatosEvaluacion - 1));\n    salidaParticionada.prueba = serieSalida.tail(nDatosPrueba);\n\n    return make_pair(entradasParticionadas, salidaParticionada);\n}\n\nParticion\ncargarTuplas(const vector<string>& rutasSeriesEntrada,\n             const string& rutaSerieSalida,\n             unsigned int retrasosEntrada,\n             unsigned int nSalidas)\n{\n    vector<vec> seriesEntrada;\n    for (const string& ruta : rutasSeriesEntrada) {\n        seriesEntrada.push_back(vec{});\n        seriesEntrada.back().load(ruta);\n    }\n\n    vec serieSalida;\n    serieSalida.load(rutaSerieSalida);\n\n    for (const vec& serie : seriesEntrada)\n        if (serie.n_elem != serieSalida.n_elem)\n            throw runtime_error(\"Las series de datos deben tener la misma longitud\");\n\n    // Normalizar todas las series de datos\n    for (vec& v : seriesEntrada) {\n        v = normalizar(v, v);\n    }\n    serieSalida = normalizar(serieSalida, serieSalida);\n\n    //    if (agregarIndice) {\n    //        vec indice = linspace(1, serieSalida.n_elem - 1, serieSalida.n_elem);\n    //        indice = normalizar(indice, indice);\n\n    //        seriesEntrada.push_back(indice);\n    //    }\n\n    vector<VectorParticionado> entradasParticionadas;\n    VectorParticionado salidaParticionada;\n    tie(entradasParticionadas, salidaParticionada) = particionar(seriesEntrada, serieSalida);\n\n    if (salidaParticionada.prueba.n_elem < retrasosEntrada + nSalidas)\n        throw runtime_error(\"No alcanzan los datos de prueba para armar una tupla con la dimensi\u00f3n requerida\");\n\n    Particion particion = armarTuplas(entradasParticionadas,\n                                      salidaParticionada,\n                                      retrasosEntrada,\n                                      nSalidas);\n\n    return particion;\n}\n\ntemplate <unsigned int N>\nvector<vector<string>>\nsubconjuntos(const vector<string>& conjunto)\n{\n    const int nElemResult = pow(2, conjunto.size());\n    vector<vector<string>> result;\n\n    if (N != conjunto.size())\n        throw runtime_error(\"Pone bien los par\u00e1metros cacho\");\n\n    //    https://www.quora.com/How-do-I-generate-all-subsets-of-a-set-in-C++-iteratively\n    bitset<N> setDeBits{0};\n\n    for (int i = 0; i < nElemResult; ++i) {\n        vector<string> subconjunto;\n\n        for (unsigned int k = 0; k < conjunto.size(); k++) {\n            if (setDeBits.test(k)) {\n                subconjunto.push_back(conjunto.at(k));\n            }\n        }\n\n        result.push_back(subconjunto);\n        setDeBits = bitset<N>{setDeBits.to_ulong() + 1};\n    }\n\n    return result;\n}\n", "meta": {"hexsha": "152b62aa3b9614af71c763857d593620dfdef308", "size": 7642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TP_Final/Eleccion_de_modelo/construir_tuplas.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": "TP_Final/Eleccion_de_modelo/construir_tuplas.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": "TP_Final/Eleccion_de_modelo/construir_tuplas.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": 33.2260869565, "max_line_length": 111, "alphanum_fraction": 0.6370060194, "num_tokens": 1855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619963333289, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6174583931518725}}
{"text": "#include <Eigen/Geometry>\n#include <cmath>\n#include <limits>\n#include <sm/assert_macros.hpp>\n#include <sm/kinematics/quaternion_algebra.hpp>\n#include <sm/kinematics/rotations.hpp>\n\nnamespace sm {\nnamespace kinematics {\ntemplate <typename Scalar_ = double>\ninline bool isLessThenEpsilons4thRoot(Scalar_ x) {\n    static const Scalar_ epsilon4thRoot = pow(std::numeric_limits<Scalar_>::epsilon(), 1.0 / 4.0);\n    return x < epsilon4thRoot;\n}\n\n// quaternion rotation.\nEigen::Vector4d r2quat(Eigen::Matrix3d const& R) {\n    const double& c1 = R(0, 0);\n    const double& c2 = R(1, 0);\n    const double& c3 = R(2, 0);\n    const double& c4 = R(0, 1);\n    const double& c5 = R(1, 1);\n    const double& c6 = R(2, 1);\n    const double& c7 = R(0, 2);\n    const double& c8 = R(1, 2);\n    const double& c9 = R(2, 2);\n\n    Eigen::Vector4d dc(fabs(1.0 + c1 - c5 - c9), fabs(1.0 - c1 + c5 - c9), fabs(1.0 - c1 - c5 + c9),\n                       fabs(1.0 + c1 + c5 + c9));\n\n    unsigned maxq = 0;\n    double maxqval = dc(0);\n\n    for (unsigned i = 1; i < 4; i++) {\n        if (dc(i) > maxqval) {\n            maxq = i;\n            maxqval = dc(i);\n        }\n    }\n\n    double c;\n    Eigen::Vector4d q;\n    if (maxq == 0) {\n        q(0) = 0.5 * sqrt(dc(0));\n        c = 0.25 / q(0);\n        q(1) = c * (c4 + c2);\n        q(2) = c * (c7 + c3);\n        q(3) = c * (c8 - c6);\n    } else if (maxq == 1) {\n        q(1) = 0.5 * sqrt(dc(1));\n        c = 0.25 / q(1);\n        q(0) = c * (c4 + c2);\n        q(2) = c * (c6 + c8);\n        q(3) = c * (c3 - c7);\n    } else if (maxq == 2) {\n        q(2) = 0.5 * sqrt(dc(2));\n        c = 0.25 / q(2);\n        q(0) = c * (c3 + c7);\n        q(1) = c * (c6 + c8);\n        q(3) = c * (c4 - c2);\n    } else {\n        q(3) = 0.5 * sqrt(dc(3));\n        c = 0.25 / q(3);\n        q(0) = c * (c8 - c6);\n        q(1) = c * (c3 - c7);\n        q(2) = c * (c4 - c2);\n    }\n\n    if (q(3) < 0) q = -q;\n\n    return q;\n}\n\nEigen::Matrix3d quat2r(Eigen::Vector4d const& q) {\n    SM_ASSERT_NEAR_DBG(std::runtime_error, q.norm(), 1.f, 1e-4,\n                       \"The quaternion must be a unit vector to represent a rotation\");\n    // double n = q(3);\n    // Eigen::Vector3d e = makeV3(q(0),q(1),q(2));\n    // R = (n^2 - e'*e) * eye(3) + 2 * e * e' + 2 * n * crossMx(e);\n    // Eigen::Matrix3d R = (n*n - e.dot(e))*Eigen::Matrix3d::Identity() + 2 * e * e.transpose() + 2 * n * crossMx(e);\n\n    Eigen::Matrix3d R;\n\n    // [ q0^2 - q1^2 - q2^2 + q3^2,           2*q0*q1 + 2*q2*q3,           2*q0*q2 - 2*q1*q3]\n    // [         2*q0*q1 - 2*q2*q3, - q0^2 + q1^2 - q2^2 + q3^2,           2*q0*q3 + 2*q1*q2]\n    // [         2*q0*q2 + 2*q1*q3,           2*q1*q2 - 2*q0*q3, - q0^2 - q1^2 + q2^2 + q3^2]\n    R(0, 0) = q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3];\n    R(0, 1) = q[0] * q[1] * 2.0 + q[2] * q[3] * 2.0;\n    R(0, 2) = q[0] * q[2] * 2.0 - q[1] * q[3] * 2.0;\n    R(1, 0) = q[0] * q[1] * 2.0 - q[2] * q[3] * 2.0;\n    R(1, 1) = -q[0] * q[0] + q[1] * q[1] - q[2] * q[2] + q[3] * q[3];\n    R(1, 2) = q[0] * q[3] * 2.0 + q[1] * q[2] * 2.0;\n    R(2, 0) = q[0] * q[2] * 2.0 + q[1] * q[3] * 2.0;\n    R(2, 1) = q[0] * q[3] * (-2.0) + q[1] * q[2] * 2.0;\n    R(2, 2) = -q[0] * q[0] - q[1] * q[1] + q[2] * q[2] + q[3] * q[3];\n\n    return R;\n}\n\nEigen::Matrix4d quatPlus(Eigen::Vector4d const& q) {\n    // [  q3,  q2, -q1, q0]\n    // [ -q2,  q3,  q0, q1]\n    // [  q1, -q0,  q3, q2]\n    // [ -q0, -q1, -q2, q3]\n    Eigen::Matrix4d Q;\n    Q(0, 0) = q[3];\n    Q(0, 1) = q[2];\n    Q(0, 2) = -q[1];\n    Q(0, 3) = q[0];\n    Q(1, 0) = -q[2];\n    Q(1, 1) = q[3];\n    Q(1, 2) = q[0];\n    Q(1, 3) = q[1];\n    Q(2, 0) = q[1];\n    Q(2, 1) = -q[0];\n    Q(2, 2) = q[3];\n    Q(2, 3) = q[2];\n    Q(3, 0) = -q[0];\n    Q(3, 1) = -q[1];\n    Q(3, 2) = -q[2];\n    Q(3, 3) = q[3];\n\n    return Q;\n}\n\nEigen::Matrix4d quatOPlus(Eigen::Vector4d const& q) {\n    // [  q3, -q2,  q1, q0]\n    // [  q2,  q3, -q0, q1]\n    // [ -q1,  q0,  q3, q2]\n    // [ -q0, -q1, -q2, q3]\n\n    Eigen::Matrix4d Q;\n    Q(0, 0) = q[3];\n    Q(0, 1) = -q[2];\n    Q(0, 2) = q[1];\n    Q(0, 3) = q[0];\n    Q(1, 0) = q[2];\n    Q(1, 1) = q[3];\n    Q(1, 2) = -q[0];\n    Q(1, 3) = q[1];\n    Q(2, 0) = -q[1];\n    Q(2, 1) = q[0];\n    Q(2, 2) = q[3];\n    Q(2, 3) = q[2];\n    Q(3, 0) = -q[0];\n    Q(3, 1) = -q[1];\n    Q(3, 2) = -q[2];\n    Q(3, 3) = q[3];\n\n    return Q;\n}\n\nEigen::Vector4d qplus(Eigen::Vector4d const& q, Eigen::Vector4d const& p) {\n    Eigen::Vector4d qplus_p;\n    // p0*q3 + p1*q2 - p2*q1 + p3*q0\n    qplus_p[0] = p[0] * q[3] + p[1] * q[2] - p[2] * q[1] + p[3] * q[0];\n    // p2*q0 - p0*q2 + p1*q3 + p3*q1\n    qplus_p[1] = p[2] * q[0] - p[0] * q[2] + p[1] * q[3] + p[3] * q[1];\n    // p0*q1 - p1*q0 + p2*q3 + p3*q2\n    qplus_p[2] = p[0] * q[1] - p[1] * q[0] + p[2] * q[3] + p[3] * q[2];\n    // p3*q3 - p1*q1 - p2*q2 - p0*q0\n    qplus_p[3] = p[3] * q[3] - p[1] * q[1] - p[2] * q[2] - p[0] * q[0];\n\n    return qplus_p;\n}\n\nEigen::Vector4d qoplus(Eigen::Vector4d const& q, Eigen::Vector4d const& p) {\n    Eigen::Vector4d qoplus_p;\n    // p0*q3 - p1*q2 + p2*q1 + p3*q0\n    qoplus_p[0] = p[0] * q[3] - p[1] * q[2] + p[2] * q[1] + p[3] * q[0];\n    // p0*q2 - p2*q0 + p1*q3 + p3*q1\n    qoplus_p[1] = p[0] * q[2] - p[2] * q[0] + p[1] * q[3] + p[3] * q[1];\n    // p1*q0 - p0*q1 + p2*q3 + p3*q2\n    qoplus_p[2] = p[1] * q[0] - p[0] * q[1] + p[2] * q[3] + p[3] * q[2];\n    // p3*q3 - p1*q1 - p2*q2 - p0*q0\n    qoplus_p[3] = p[3] * q[3] - p[1] * q[1] - p[2] * q[2] - p[0] * q[0];\n\n    return qoplus_p;\n}\n\nEigen::Vector4d quatInv(Eigen::Vector4d const& q) {\n    Eigen::Vector4d qret = q;\n    invertQuat(qret);\n    return qret;\n}\n\nvoid invertQuat(Eigen::Vector4d& q) { q.head<3>() = -q.head<3>(); }\n\nEigen::Vector3d qeps(Eigen::Vector4d const& q) { return q.head<3>(); }\n\nEigen::Vector3f qeps(Eigen::Vector4f const& q) { return q.head<3>(); }\n\ndouble qeta(Eigen::Vector4d const& q) { return q[3]; }\n\nfloat qeta(Eigen::Vector4f const& q) { return q[3]; }\n\nEigen::Vector4d axisAngle2quat(Eigen::Vector3d const& a) {\n    // Method of implementing this function that is accurate to numerical precision from\n    // Grassia, F. S. (1998). Practical parameterization of rotations using the exponential map. journal of graphics,\n    // gpu, and game tools, 3(3):29\u201348.\n\n    double theta = a.norm();\n\n    // na is 1/theta sin(theta/2)\n    double na;\n    if (isLessThenEpsilons4thRoot(theta)) {\n        static const double one_over_48 = 1.0 / 48.0;\n        na = 0.5 + (theta * theta) * one_over_48;\n    } else {\n        na = sin(theta * 0.5) / theta;\n    }\n    Eigen::Vector3d axis = a * na;\n    double ct = cos(theta * 0.5);\n    return Eigen::Vector4d(axis[0], axis[1], axis[2], ct);\n}\n\n/**\n * calculate arcsin(x)/x\n * @param x\n * @return\n */\ntemplate <typename Scalar_>\ninline Scalar_ arcSinXOverX(Scalar_ x) {\n    if (isLessThenEpsilons4thRoot(fabs(x))) {\n        return Scalar_(1.0) + x * x * Scalar_(1 / 6);\n    }\n    return asin(x) / x;\n}\n\ntemplate <typename Scalar_>\nEigen::Matrix<Scalar_, 3, 1> quat2AxisAngle(Eigen::Matrix<Scalar_, 4, 1> const& q) {\n    SM_ASSERT_LT_DBG(std::runtime_error, fabs(q.norm() - 1), 8 * std::numeric_limits<Scalar_>::epsilon(),\n                     \"This function is inteded for unit quternions only.\");\n    const Eigen::Matrix<Scalar_, 3, 1> a = qeps(q);\n    const Scalar_ na = a.norm(), eta = qeta(q);\n    Scalar_ scale;\n    if (fabs(eta) < na) {  // use eta because it is more precise than na to calculate the scale. No singularities here.\n        scale = acos(eta) / na;\n    } else {\n        /*\n         * In this case more precision is in na than in eta so lets use na only to calculate the scale:\n         *\n         * assume first eta > 0 and 1 > na > 0.\n         *               u = asin (na) / na  (this implies u in [1, pi/2], because na i in [0, 1]\n         *    sin (u * na) = na\n         *  sin^2 (u * na) = na^2\n         *  cos^2 (u * na) = 1 - na^2\n         *                              (1 = ||q|| = eta^2 + na^2)\n         *    cos^2 (u * na) = eta^2\n         *                              (eta > 0,  u * na = asin(na) in [0, pi/2] => cos(u * na) >= 0 )\n         *      cos (u * na) = eta\n         *                              (u * na in [ 0, pi/2] )\n         *                 u = acos (eta) / na\n         *\n         * So the for eta > 0 it is acos(eta) / na == asin(na) / na.\n         * From some geometric considerations (mirror the setting at the hyper plane q==0) it follows for eta < 0 that\n         * (pi - asin(na)) / na = acos(eta) / na.\n         */\n        if (eta > 0) {\n            // For asin(na)/ na the singularity na == 0 can be removed. We can ask (e.g. Wolfram alpha) for its series\n            // expansion at na = 0. And that is done in the following function.\n            scale = arcSinXOverX(na);\n        } else {\n            // (pi - asin(na))/ na has a pole at na == 0. So we cannot remove this singularity.\n            // It is just the cut locus of the unit quaternion manifold at identity and thus the axis angle description\n            // becomes necessarily unstable there.\n            scale = (M_PI - asin(na)) / na;\n        }\n    }\n    return a * (Scalar_(2) * scale);\n}\ntemplate Eigen::Matrix<double, 3, 1> quat2AxisAngle(Eigen::Matrix<double, 4, 1> const& q);\ntemplate Eigen::Matrix<float, 3, 1> quat2AxisAngle(Eigen::Matrix<float, 4, 1> const& q);\n\nEigen::Matrix<double, 4, 3> quatJacobian(Eigen::Vector4d const& p) {\n    Eigen::Matrix<double, 4, 3> J;\n    // [  p3, -p2,  p1]\n    // [  p2,  p3, -p0]\n    // [ -p1,  p0,  p3]\n    // [ -p0, -p1, -p2]\n\n    J(0, 0) = p[3];\n    J(0, 1) = -p[2];\n    J(0, 2) = p[1];\n    J(1, 0) = p[2];\n    J(1, 1) = p[3];\n    J(1, 2) = -p[0];\n    J(2, 0) = -p[1];\n    J(2, 1) = p[0];\n    J(2, 2) = p[3];\n    J(3, 0) = -p[0];\n    J(3, 1) = -p[1];\n    J(3, 2) = -p[2];\n\n    return J * 0.5;\n}\n\nEigen::Vector4d updateQuat(Eigen::Vector4d const& q, Eigen::Vector3d const& dq) {\n    // the following code is an optimized version of:\n    // Eigen::Vector4d dq4 = axisAngle2quat(dq);\n    // Eigen::Vector4d retq = quatPlus(dq4)*q;\n    // return retq;\n\n    Eigen::Vector4d dq3 = axisAngle2quat(dq);\n    double ca = dq3[3];\n    Eigen::Vector4d retq;\n    retq[0] = q[0] * ca + dq3[0] * q[3] - dq3[1] * q[2] + dq3[2] * q[1];\n    retq[1] = q[1] * ca + dq3[0] * q[2] + dq3[1] * q[3] - dq3[2] * q[0];\n    retq[2] = q[2] * ca - dq3[0] * q[1] + dq3[1] * q[0] + dq3[2] * q[3];\n    retq[3] = q[3] * ca - dq3[0] * q[0] - dq3[1] * q[1] - dq3[2] * q[2];\n\n    return retq;\n}\n\nEigen::Vector3d quatRotate(Eigen::Vector4d const& q_a_b, Eigen::Vector3d const& v_b) {\n    return v_b + 2.0 * q_a_b.head<3>().cross(q_a_b.head<3>().cross(v_b) - q_a_b[3] * v_b);\n}\n\nEigen::Vector4d quatRandom() {\n    Eigen::Vector4d q_a_b;\n    q_a_b.setRandom();\n    q_a_b.array() -= 0.5;\n    q_a_b /= q_a_b.norm();\n    return q_a_b;\n}\n\nEigen::Vector4d quatIdentity() { return Eigen::Vector4d(0, 0, 0, 1); }\n\nEigen::Matrix<double, 3, 4> quatS(Eigen::Vector4d q) {\n    //   [  q3,  q2, -q1, -q0]\n    // 2 [ -q2,  q3,  q0, -q1]\n    //   [  q1, -q0,  q3, -q2]\n    q *= 2.0;\n\n    Eigen::Matrix<double, 3, 4> S;\n    S << q[3], q[2], -q[1], -q[0], -q[2], q[3], q[0], -q[1], q[1], -q[0], q[3], -q[2];\n\n    return S;\n}\n\nEigen::Matrix<double, 4, 3> quatInvS(Eigen::Vector4d q) {\n    q *= 0.5;\n\n    // 1 [  q3, -q2,  q1]\n    // - [  q2,  q3, -q0]\n    // 2 [ -q1,  q0,  q3]\n    //   [ -q0, -q1, -q2]\n\n    Eigen::Matrix<double, 4, 3> invS;\n    invS << q[3], -q[2], q[1], q[2], q[3], -q[0], -q[1], q[0], q[3], -q[0], -q[1], -q[2];\n    return invS;\n}\n\nEigen::Vector4d qslerp(const Eigen::Vector4d& q0, const Eigen::Vector4d& q1, double t) {\n    if (t <= 0.0) {\n        return q0;\n    } else if (t >= 1.0) {\n        return q1;\n    } else {\n        if ((q0 - q1).squaredNorm() > (q0 + q1).squaredNorm()) {\n            // The quaternions are far away from eachother on the sphere.\n            // Flip one around so that this works out.\n            return qplus(q0, qexp(t * qlog(qplus(quatInv(q0), -q1))));\n        } else {\n            return qplus(q0, qexp(t * qlog(qplus(quatInv(q0), q1))));\n        }\n    }\n}\n\n/// \\brief do linear interpolation between p0 and p1 for times t = [0.0,1.0]\nEigen::VectorXd lerp(const Eigen::VectorXd& p0, const Eigen::VectorXd& p1, double t) {\n    SM_ASSERT_EQ(std::runtime_error, p0.size(), p1.size(), \"The vectors must be the same size\");\n    if (t <= 0.0) {\n        return p0;\n    } else if (t >= 1.0) {\n        return p1;\n    } else {\n        return (1 - t) * p0 + t * p1;\n    }\n}\n\nEigen::Matrix<double, 3, 4> quatLogJacobian(const Eigen::Vector4d& p) {\n    //      [qx]\n    //      [qy]                -2*x\n    // p =  [qz],    g(x) = ----------------\n    //      [qw]               sqrt(1-qw\u00b2)\n    //\n    //\n    //      [2*acos(qw)      0            0            g(qx)]\n    // J =  [0            2*acos(qw)      0            g(qy)]\n    //      [0            0            2*acos(qw)      g(qz)]\n\n    Eigen::Matrix<double, 3, 4> J;\n    J.setZero();\n\n    double n = qeps(p).norm();\n\n    double de = n * n * n;                   // pow(n, 3);\n    double u12 = p(1) * p(1) + p(2) * p(2);  // pow(p(1), 2) + pow(p(2), 2);\n    double u02 = p(0) * p(0) + p(2) * p(2);  // pow(p(0), 2) + pow(p(2), 2);\n    double u01 = p(0) * p(0) + p(1) * p(1);  // pow(p(0), 2) + pow(p(1), 2);\n    double a = acos(p(3));\n    double uw = sqrt(-(p(3) * p(3) - 1) * n * n);\n\n    J(0, 0) = 2 * a * u12 / de;\n    J(0, 1) = -2 * a * p(1) * p(0) / de;\n    J(0, 2) = -2 * a * p(2) * p(0) / de;\n    J(0, 3) = -2 * p(0) / uw;\n    J(1, 0) = -2 * a * p(0) * p(1) / de;\n    J(1, 1) = 2 * a * u02 / de;\n    J(1, 2) = -2 * a * p(1) * p(2) / de;\n    J(1, 3) = -2 * p(1) / uw;\n    J(2, 0) = -2 * a * p(0) * p(2) / de;\n    J(2, 1) = -2 * a * p(1) * p(2) / de;\n    J(2, 2) = 2 * a * u01 / de;\n    J(2, 3) = -2 * p(2) / uw;\n\n    return J;\n}\n\ntemplate <typename Scalar_>\ninline const typename Eigen::Matrix<Scalar_, 4, 3>& quatV() {\n    static const Eigen::Matrix<Scalar_, 4, 3> V = 0.5 * Eigen::Matrix<Scalar_, 4, 3>::Identity();\n    return V;\n}\ntemplate const Eigen::Matrix<double, 4, 3>& quatV();\ntemplate const Eigen::Matrix<float, 4, 3>& quatV();\n\ntemplate <typename Scalar_>\nEigen::Matrix<Scalar_, 3, 3> expDiffMat(const Eigen::Matrix<Scalar_, 3, 1>& vec) {\n    Scalar_ phi = vec.norm();\n\n    if (phi == 0) {\n        return Eigen::Matrix<Scalar_, 3, 3>::Identity();\n    }\n\n    Eigen::Matrix<Scalar_, 3, 3> vecCross = crossMx(vec);\n\n    Scalar_ phiAbs = fabs(phi);\n    Scalar_ phiSquare = phi * phi;\n\n    Scalar_ a;\n    Scalar_ b;\n    if (!isLessThenEpsilons4thRoot(phiAbs)) {\n        Scalar_ siPhiHalf = sin(phi / 2);\n        a = (2 * siPhiHalf * siPhiHalf / phiSquare);\n        b = ((1 - sin(phi) / phi) / phiSquare);\n    } else {\n        a = (1.0 / 2) * (1 - (1.0 / (24 / 2)) * phiSquare);\n        b = (1.0 / 6) * (1 - (1.0 / (120 / 6)) * phiSquare);\n    }\n\n    return Eigen::Matrix<Scalar_, 3, 3>::Identity() - a * vecCross + b * vecCross * vecCross;\n}\ntemplate Eigen::Matrix<double, 3, 3> expDiffMat<double>(const Eigen::Matrix<double, 3, 1>&);\ntemplate Eigen::Matrix<float, 3, 3> expDiffMat<float>(const Eigen::Matrix<float, 3, 1>&);\n\ntemplate <typename Scalar_>\nEigen::Matrix<Scalar_, 4, 3> quatExpJacobian(const Eigen::Matrix<Scalar_, 3, 1>& vec) {\n    return quatOPlus(axisAngle2quat(vec.template cast<double>())).template cast<Scalar_>() * quatV<Scalar_>() *\n           expDiffMat(vec);\n}\ntemplate Eigen::Matrix<double, 4, 3> quatExpJacobian(const Eigen::Matrix<double, 3, 1>& vec);\ntemplate Eigen::Matrix<float, 4, 3> quatExpJacobian(const Eigen::Matrix<float, 3, 1>& vec);\n\ntemplate <typename Scalar_>\nEigen::Matrix<Scalar_, 3, 3> logDiffMat(const Eigen::Matrix<Scalar_, 3, 1>& vec) {\n    Scalar_ phi = vec.norm();\n    if (phi == 0) {\n        return Eigen::Matrix<Scalar_, 3, 3>::Identity();\n    }\n\n    Scalar_ phiAbs = fabs(phi);\n    Eigen::Matrix<Scalar_, 3, 3> vecCross = crossMx(vec);\n\n    Scalar_ a;\n    if (!isLessThenEpsilons4thRoot(phiAbs)) {\n        Scalar_ phiHalf = 0.5 * phi;\n        a = ((1 - phiHalf / tan(phiHalf)) / phi / phi);\n    } else {\n        a = 1.0 / 12 * (1 + 1.0 / 60 * phi * phi);\n    }\n    return Eigen::Matrix<Scalar_, 3, 3>::Identity() + 0.5 * vecCross + a * vecCross * vecCross;\n}\ntemplate Eigen::Matrix<double, 3, 3> logDiffMat<double>(const Eigen::Matrix<double, 3, 1>&);\ntemplate Eigen::Matrix<float, 3, 3> logDiffMat<float>(const Eigen::Matrix<float, 3, 1>&);\n\ntemplate <typename Scalar_>\nEigen::Matrix<Scalar_, 3, 4> quatLogJacobian2(const Eigen::Matrix<Scalar_, 4, 1>& p) {\n    return logDiffMat(quat2AxisAngle<>(p)) * (quatV<Scalar_>().transpose() * Scalar_(4.0)) *\n           quatOPlus(quatInv(p.template cast<double>())).template cast<Scalar_>();\n}\n\ntemplate Eigen::Matrix<double, 3, 4> quatLogJacobian2(const Eigen::Matrix<double, 4, 1>&);\ntemplate Eigen::Matrix<float, 3, 4> quatLogJacobian2(const Eigen::Matrix<float, 4, 1>&);\n}  // namespace kinematics\n}  // namespace sm\n", "meta": {"hexsha": "a2e3f1cfa2e3e66d73ba65e4359d06ddc74a594f", "size": 16807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/src/quaternion_algebra.cpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Schweizer-Messer/sm_kinematics/src/quaternion_algebra.cpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Schweizer-Messer/sm_kinematics/src/quaternion_algebra.cpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7489959839, "max_line_length": 119, "alphanum_fraction": 0.4940798477, "num_tokens": 6964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.6174026676275018}}
{"text": "/**\n * Created by sixdi on 1/11/2022.\n */\n#include <gtest/gtest.h>\n\n/**\n * DateTime:\n *      time points\n *      periods\n *      time of day\n *      calendar dates\n *\n\n *\n * Chrono and Timer:\n *      clocks to measure time\n *\n */\n\n\n/**\n * DateTime:\n *      used to process time data\n *      provides extensions to account for time zones\n *      supports formatted input and output of calendar dates and times\n *\n *      - Calender Dates\n *      - Location-independent Times\n *      - Location-dependent Times\n *      - Formatted Input and Output\n*/\n\n/**\n * Calendar Dates\n * https://theboostcpplibraries.com/boost.datetime-calendar\n *\n * https://www.boost.org/doc/libs/1_62_0/doc/html/date_time.html\n *\n * based on Gregorian Calendar\n * boost/date_time/gregorian/gregorian.hpp\n */\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <iostream>\n\n/**\n * creating a date\n */\nTEST(datetime, dates){\n    boost::gregorian::date d{2014, 1, 31};\n    std::cout << d.year() << std::endl;\n    std::cout << d.month() << std::endl;\n    std::cout << d.day() << std::endl;\n    std::cout << d.day_of_year() << std::endl;\n    std::cout << d.end_of_month() << std::endl;\n    std::cout << d.day_of_week() << std::endl;\n}\n/**\n * Getting a date from a clock or a string\n */\n using namespace boost::gregorian;\n using std::cout ;\n using std::cin;\n using std::endl;\nTEST(datetime, date_from_clock_or_string){\n    date d{day_clock::universal_day()};\n    cout << d.year() << \", \" << d.month() << endl;\n    d = date_from_iso_string(\"20140321\");\n    cout << d.year() << endl;\n}\n\n/**\n * date duration\n */\nTEST(datetime, date_duration){\n    date d1{2015, 1, 31};\n    date d2{2016, 3, 3};\n    date_duration dd = d2 - d1;\n    cout << dd.days() << endl;\n}\n\n/**\n * specialized duration\n */\nTEST(datetime, specialize_duration){\n    date_duration dd{4};\n    cout << dd.days() << endl;\n    weeks ws{4};\n    cout << ws.days() << endl;\n    months ms{4};\n    cout << ms.number_of_months() << endl;\n    years yrs{4};\n    cout << yrs.number_of_years() << endl;\n}\n\n/**\n * processing specialized durations\n */\nTEST(datetime, processing_specialized_duration){\n    date d{2014, 2, 4};\n    months ms{1};\n    date d2 = d + ms;\n    cout << d2 << endl;\n}\n\n/**\n * using date_period\n */\nTEST(datetime, using_date_period){\n    date d1{2014, 1, 1};\n    date d2{2014, 2,28};\n    date_period dp{d1, d2};\n    date_duration dd = dp.length();\n    cout << dd.days() << endl;\n}\n\n/**\n * whether a period contains dates\n */\nTEST(datetime, whether_a_period_contains_dates){\n    date d1{2014, 1, 1};\n    date d2{2014, 2, 28};\n    date_period dp{d1, d2};\n    cout.setf(std::ios::boolalpha);\n    cout << dp.contains(d1) << endl\n            << dp.contains(d2) << endl;\n\n}\n\n/**\n * iterating over dates\n */\nTEST(datetime, iterating_over_dates){\n    date d{2014, 4, 1};\n    day_iterator itr{d};\n    cout << itr->day_of_week() << endl;\n    cout << *++itr << endl;\n    cout << itr->day_of_week() << endl;\n    cout << boost::date_time::next_weekday(*itr, greg_weekday(boost::date_time::Friday)) << endl;\n}\n\n\n/**\n * outputs teh weekdays for next December 24 and following two public holidays.\n */\n\n#include <vector>\n#include <boost/smart_ptr.hpp>\n#include <boost/bind.hpp>\n\nvoid print_date(boost::shared_ptr<year_based_generator> d, int year){\n    std::cout << d.get()->get_date(year) << \"[\" << d.get()->get_date(year).day_of_week() << \"]\" << endl;\n}\n\nTEST(datetime, output_holiday){\n    std::vector<boost::shared_ptr<year_based_generator>>  holidays;\n    // Christmas' Eve\n    boost::shared_ptr<year_based_generator > h{new partial_date (24, boost::date_time::Dec)};\n    holidays.push_back(h);\n    //Christmas\n    h.reset(new partial_date(25, boost::date_time::Dec));\n    holidays.push_back(h);\n    // New Year's Day\n    h.reset(new partial_date(1, boost::date_time::Jan));\n    holidays.push_back(h);\n    std::for_each(holidays.begin(), holidays.end(), boost::bind(print_date, _1, 2022));\n}\n\n\n/**\n * calculate your age in days\n */\n\n#include <chrono>\n\nTEST(datetime, calculate_your_age){\n    date dob{1998, 3, 4};\n    date today{day_clock::local_day()};\n    date_duration d = today - dob;\n    std::cout << d << endl;\n}\n\n/**\n * uisng boost::posix_time::ptime\n * defines a location-independent time\n */\n#include <boost/date_time/posix_time/posix_time.hpp>\nusing namespace boost::posix_time;\nTEST(datetime, times){\n    ptime pt{date{2022, 1, 5}, time_duration{12, 0, 0}};\n    date d{pt.date()};\n    cout << d << endl;\n    time_duration td = pt.time_of_day();\n    cout << td << endl;\n}\n\n/**\n * create a time point with a clock or a string\n */\nTEST(datetime, time_point_with_clock_string){\n    ptime pt{second_clock::universal_time()};\n    cout << pt.date() << endl;\n    cout<< pt.time_of_day() << endl;\n\n    pt = from_iso_string(\"20220103T213440\");\n    cout << pt.date() << endl;\n    cout << pt.time_of_day() << endl;\n\n    pt = second_clock::local_time();\n    cout << pt.date() << endl;\n    cout << pt.time_of_day() << endl;\n}\n\n/**\n * time duration\n */\nTEST(datetime, timeduration){\n    time_duration td{16, 30, 9};\n    cout << td.hours() << endl;\n    cout << td.minutes() << endl;\n    cout << td.seconds() << endl;\n    cout << td.total_seconds() << endl;\n}\n\n/**\n * processing time_point\n */\n\nTEST(datetime, time_point){\n    ptime pt{date{2022, 2, 5}, time_duration{12, 3, 4}};\n    ptime pt2{date{2022, 3, 4}, time_duration{2, 4, 4}};\n    time_duration dt = pt2 - pt;\n    cout << dt << endl;\n    cout << dt.hours() << endl;\n    cout << dt.minutes() << endl;\n    cout << dt.seconds() << endl;\n    cout << dt.total_seconds() << endl;\n}\n\n/**\n * processing time durations\n */\nTEST(datetime, process_time_duration){\n    ptime pt{date{2022, 4, 5}, time_duration{23, 4, 5}};\n    time_duration td{2, 4, 6};\n    ptime pt2 = pt + td;\n    cout << pt2.date() << endl;\n    cout << pt2.time_of_day() << endl;\n}\n\n/**\n * using boost::posix_time::time_period\n */\nTEST(datetime, time_period){\n    ptime pt1{date{2022, 2, 3}, time_duration{3, 4, 5}};\n    ptime pt2{date{2022, 3, 4}, time_duration{13, 29, 3 }};\n    time_period tp{pt1, pt2};\n    cout << tp << endl;\n    cout.setf(std::ios::boolalpha);\n    cout << tp.contains(pt1) << endl;\n    cout << tp.contains(pt2) << endl;\n}\n\n/**\n * iterator over points in time\n */\nTEST(datetime, iterate_over_point_in_time){\n    ptime pt{date{2022, 5, 6}, time_duration{14, 34, 6}};\n    time_iterator itr{pt, time_duration{4, 30, 0}};\n    cout << *itr << endl;\n    cout << *++itr << endl;\n    cout << *++itr << endl;\n}\n\n/**\n * Location-dependent times\n * account for time zones\n */\n#include <boost/date_time/local_time/local_time.hpp>\nusing namespace boost::local_time;\nTEST(datetime, local_dependent_time){\n    time_zone_ptr tz{new posix_time_zone{\"CET+1\"}};\n    ptime pt{date{2022, 3, 4}, time_duration{3, 5, 6}};\n    local_date_time dt{pt, tz};\n    cout << dt.utc_time() << endl;\n    cout << dt.local_time() << endl;\n    cout << dt.zone_name() << endl;\n}\n\n/**\n * location-dependent points in time and different time zones\n *\n */\nTEST(datetime, diff_tz){\n    time_zone_ptr tz{new posix_time_zone {\"CET+1\"}};\n    ptime pt{date{2022, 3, 2}, time_duration{12, 0, 0}};\n    local_date_time dt{pt, tz};\n    cout << dt.local_time() << endl;\n\n    time_zone_ptr tz2{new posix_time_zone {\"EET+2\"}};\n    cout << dt.local_time_in(tz2).local_time() << endl;\n}\n/**\n *\n */\nTEST(datetime, local_time_period){\n   time_zone_ptr tz{new posix_time_zone {\"CET+0\"}};\n   ptime pt1{date{2022, 7, 9}, time_duration{13, 8, 0}};\n   local_date_time dt1{pt1, tz};\n\n   ptime pt2{date{2024, 7, 9}, time_duration{3, 0, 7}};\n   local_date_time dt2{pt2, tz};\n\n   local_time_period tp{dt2, dt1};\n   cout.setf(std::ios::boolalpha);\n   cout << tp.contains(dt1) << endl;\n   cout << tp.contains(dt2) << endl;\n}\n\n/**\n * user Defined format for a date\n */\n#include<memory>\n#include<locale>\nTEST(datetime, formatted_IO){\n    date d{2022, 2, 1};\n    std::unique_ptr<date_facet> df{new date_facet {\"%A, %d %B %Y\"}};\n    cout.imbue(std::locale{cout.getloc(), df.get()});\n    cout << d ;\n\n}\n/**\n * change names of weekdays and months\n */\nTEST(datetime, change_name){\n    std::locale::global(std::locale{\"German\"});\n    std::string months[12]{\"Januar\", \"Februar\", \"M\\xe4rz\", \"April\",\n                           \"Mai\", \"Juni\", \"Juli\", \"August\", \"September\", \"Oktober\",\n                           \"November\", \"Dezember\"};\n    std::string weekdays[7]{\"Sonntag\", \"Montag\", \"Dienstag\", \"Mittwoch\",\n                            \"Donnerstag\", \"Freitag\", \"Samstag\"};\n    date d{2022, 2, 4};\n    std::unique_ptr<date_facet> df{new date_facet {\"%A, %d. %B %Y\"}};\n    df->long_month_names(std::vector<std::string>{std::begin(months), std::end(months)});\n    df->long_weekday_names(std::vector<std::string>{weekdays, weekdays+7});\n\n    cout.imbue(std::locale{cout.getloc(), df.get()});\n    cout << d;\n\n}\nint main(int argc, char **argv){\n    ::testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}", "meta": {"hexsha": "9abe082eb13167bcec15dd30f23fe7b93b4b79fb", "size": 8902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BOOST/lib/boost_datetime.cpp", "max_stars_repo_name": "954gmo/STL_BOOST", "max_stars_repo_head_hexsha": "57128176d1a9799c50eecade558dd903b75bcb21", "max_stars_repo_licenses": ["MIT"], "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/lib/boost_datetime.cpp", "max_issues_repo_name": "954gmo/STL_BOOST", "max_issues_repo_head_hexsha": "57128176d1a9799c50eecade558dd903b75bcb21", "max_issues_repo_licenses": ["MIT"], "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/lib/boost_datetime.cpp", "max_forks_repo_name": "954gmo/STL_BOOST", "max_forks_repo_head_hexsha": "57128176d1a9799c50eecade558dd903b75bcb21", "max_forks_repo_licenses": ["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.1468926554, "max_line_length": 104, "alphanum_fraction": 0.6151426646, "num_tokens": 2610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6173508207819188}}
{"text": "// Copyright Paul A. Bristow 2016\n// Copyright John Z. Maddock 2016\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or\n//  copy at http ://www.boost.org/LICENSE_1_0.txt).\n\n/*! \\brief Graph showing use of Lambert W function to compute current\nthrough a diode-connected transistor with preset series resistance.\n\n\\details T. C. Banwell and A. Jayakumar,\nExact analytical solution of current flow through diode with series resistance,\nElectron Letters, 36(4):291-2 (2000).\nDOI:  doi.org/10.1049/el:20000301\n\nThe current through a diode connected NPN bipolar junction transistor (BJT)\ntype 2N2222 (See https://en.wikipedia.org/wiki/2N2222 and\nhttps://www.fairchildsemi.com/datasheets/PN/PN2222.pdf Datasheet)\nwas measured, for a voltage between 0.3 to 1 volt, see Fig 2 for a log plot, showing a knee visible at about 0.6 V.\n\nThe transistor parameter I sat was estimated to be 25 fA and the ideality factor = 1.0.\nThe intrinsic emitter resistance re was estimated from the rsat = 0 data to be 0.3 ohm.\n\nThe solid curves in Figure 2 are calculated using equation 5 with rsat included with re.\n\nhttp://www3.imperial.ac.uk/pls/portallive/docs/1/7292572.PDF\n\n*/\n\n#include <boost/math/special_functions/lambert_w.hpp>\nusing boost::math::lambert_w0;\n#include <boost/math/special_functions.hpp>\nusing boost::math::isfinite;\n#include <boost/svg_plot/svg_2d_plot.hpp>\nusing namespace boost::svg;\n\n#include <iostream>\n// using std::cout;\n// using std::endl;\n#include <exception>\n#include <stdexcept>\n#include <string>\n#include <array>\n#include <vector>\n#include <utility>\nusing std::pair;\n#include <map>\nusing std::map;\n#include <set>\nusing std::multiset;\n#include <limits>\nusing std::numeric_limits;\n#include <cmath> //\n\n/*!\nCompute thermal voltage as a function of temperature,\nabout 25 mV at room temperature.\nhttps://en.wikipedia.org/wiki/Boltzmann_constant#Role_in_semiconductor_physics:_the_thermal_voltage\n\n\\param temperature Temperature (degrees Celsius).\n*/\nconst double v_thermal(double temperature)\n{\n  BOOST_CONSTEXPR const double boltzmann_k = 1.38e-23; // joules/kelvin.\n  BOOST_CONSTEXPR double charge_q = 1.6021766208e-19; // Charge of an electron (columb).\n  double temp = +273; // Degrees C to K.\n  return boltzmann_k * temp / charge_q;\n} // v_thermal\n\n  /*!\n  Banwell & Jayakumar, equation 2, page 291.\n  */\ndouble i(double isat, double vd, double vt, double nu)\n{\n  double i = isat * (exp(vd / (nu * vt)) - 1);\n  return i;\n} //\n\n  /*!\n  Banwell & Jayakumar, Equation 4, page 291.\n  i current flow = isat\n  v voltage source.\n  isat reverse saturation current in equation 4.\n  (might implement equation 4 instead of simpler equation 5?).\n  vd voltage drop = v - i* rs  (equation 1).\n  vt  thermal voltage, 0.0257025 = 25 mV.\n  nu junction ideality factor (default = unity), also known as the emission coefficient.\n  re intrinsic emitter resistance, estimated to be 0.3 ohm from low current.\n  rsat reverse saturation current\n\n  \\param v Voltage V to compute current I(V).\n  \\param vt Thermal voltage, for example 0.0257025 = 25 mV, computed from boltzmann_k * temp / charge_q;\n  \\param rsat Resistance in series with the diode.\n  \\param re Intrinsic emitter resistance (estimated to be 0.3 ohm from the Rs = 0 data)\n  \\param isat Reverse saturation current (See equation 2).\n  \\param nu Ideality factor (default = unity).\n\n  \\returns I amp as function of V volt.\n  */\n\n//[lambert_w_diode_graph_2\ndouble iv(double v, double vt, double rsat, double re, double isat, double nu = 1.)\n{\n  // V thermal 0.0257025 = 25 mV\n  // was double i = (nu * vt/r) * lambert_w((i0 * r) / (nu * vt)); equ 5.\n\n  rsat = rsat + re;\n  double i = nu * vt / rsat;\n // std::cout << \"nu * vt / rsat = \" << i << std::endl; // 0.000103223\n\n  double x = isat * rsat / (nu * vt);\n//  std::cout << \"isat * rsat / (nu * vt) = \" << x << std::endl;\n\n  double eterm = (v + isat * rsat) / (nu * vt);\n // std::cout << \"(v + isat * rsat) / (nu * vt) = \" << eterm << std::endl;\n\n  double e = exp(eterm);\n//  std::cout << \"exp(eterm) = \" << e << std::endl;\n\n  double w0 = lambert_w0(x * e);\n//  std::cout << \"w0 = \" << w0 << std::endl;\n  return i * w0 - isat;\n} // double iv\n\n//] [\\lambert_w_diode_graph_2]\n\n\nstd::array<double, 5> rss = { 0., 2.18, 10., 51., 249 };  // series resistance (ohm).\nstd::array<double, 7> vds = { 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 };  // Diode voltage.\nstd::array<double, 7> lni = { -19.65, -15.75, -11.86, -7.97, -4.08, -0.0195, 3.6 }; // ln(current).\n\nint main()\n{\n  try\n  {\n    std::cout << \"Lambert W diode current example.\" << std::endl;\n\n//[lambert_w_diode_graph_1\n    double nu = 1.0; // Assumed ideal.\n    double vt = v_thermal(25); // v thermal, Shockley equation, expect about 25 mV at room temperature.\n    double boltzmann_k = 1.38e-23; // joules/kelvin\n    double temp = 273 + 25;\n    double charge_q = 1.6e-19; // column\n    vt = boltzmann_k * temp / charge_q;\n    std::cout << \"V thermal \" << vt << std::endl; // V thermal 0.0257025 = 25 mV\n    double rsat = 0.;\n    double isat = 25.e-15; //  25 fA;\n    std::cout << \"Isat = \" << isat << std::endl;\n    double re = 0.3;  // Estimated from slope of straight section of graph (equation 6).\n    double v = 0.9;\n    double icalc = iv(v, vt, 249., re, isat);\n    std::cout << \"voltage = \" << v << \", current = \" << icalc << \", \" << log(icalc) << std::endl; // voltage = 0.9, current = 0.00108485, -6.82631\n//] [/lambert_w_diode_graph_1]\n\n    // Plot a few measured data points.\n    std::map<const double, double> zero_data;  // Extrapolated from slope of measurements with no external resistor.\n    zero_data[0.3] = -19.65;\n    zero_data[0.4] = -15.75;\n    zero_data[0.5] = -11.86;\n    zero_data[0.6] = -7.97;\n    zero_data[0.7] = -4.08;\n    zero_data[0.8] = -0.0195;\n    zero_data[0.9] =  3.9;\n\n    std::map<const double, double>  measured_zero_data; // No external series resistor.\n    measured_zero_data[0.3] = -19.65;\n    measured_zero_data[0.4] = -15.75;\n    measured_zero_data[0.5] = -11.86;\n    measured_zero_data[0.6] = -7.97;\n    measured_zero_data[0.7] = -4.2;\n    measured_zero_data[0.72] = -3.5;\n    measured_zero_data[0.74] = -2.8;\n    measured_zero_data[0.76] = -2.3;\n    measured_zero_data[0.78] = -2.0;\n    // Measured from Fig 2 as raw data not available.\n\n    double step = 0.1;\n    for (int i = 0; i < vds.size(); i++)\n    {\n      zero_data[vds[i]] = lni[i];\n      std::cout << lni[i] << \"  \" << vds[i] << std::endl;\n    }\n    step = 0.01;\n\n    std::map<const double, double> data_2;\n    for (double v = 0.3; v < 1.; v += step)\n    {\n      double current = iv(v, vt, 2., re, isat);\n      data_2[v] = log(current);\n      // std::cout << \"v \" << v << \", current = \" << current << \" log current = \" << log(current) << std::endl;\n    }\n    std::map<const double, double> data_10;\n    for (double v = 0.3; v < 1.; v += step)\n    {\n      double current = iv(v, vt, 10., re, isat);\n      data_10[v] = log(current);\n    //  std::cout << \"v \" << v << \", current = \" << current << \" log current = \" << log(current) << std::endl;\n    }\n    std::map<const double, double> data_51;\n    for (double v = 0.3; v < 1.; v += step)\n    {\n      double current = iv(v, vt, 51., re, isat);\n      data_51[v] = log(current);\n     // std::cout << \"v \" << v << \", current = \" << current << \" log current = \" << log(current) << std::endl;\n    }\n    std::map<const double, double> data_249;\n    for (double v = 0.3; v < 1.; v += step)\n    {\n      double current = iv(v, vt, 249., re, isat);\n      data_249[v] = log(current);\n      // std::cout << \"v \" << v << \", current = \" << current << \" log current = \" << log(current) << std::endl;\n    }\n\n    svg_2d_plot data_plot;\n\n    data_plot.title(\"Diode current versus voltage\")\n      .x_size(400)\n      .y_size(300)\n      .legend_on(true)\n      .legend_lines(true)\n      .x_label(\"voltage (V)\")\n      .y_label(\"log(current) (A)\")\n      //.x_label_on(true)\n      //.y_label_on(true)\n      //.xy_values_on(false)\n      .x_range(0.25, 1.)\n      .y_range(-20., +4.)\n      .x_major_interval(0.1)\n      .y_major_interval(4)\n      .x_major_grid_on(true)\n      .y_major_grid_on(true)\n      //.x_values_on(true)\n      //.y_values_on(true)\n      .y_values_rotation(horizontal)\n      //.plot_window_on(true)\n      .x_values_precision(3)\n      .y_values_precision(3)\n      .coord_precision(4) // Needed to avoid stepping on curves.\n      .copyright_holder(\"Paul A. Bristow\")\n      .copyright_date(\"2016\")\n      //.background_border_color(black);\n      ;\n\n    // &#x2080; = subscript zero.\n    data_plot.plot(zero_data, \"I&#x2080;(V)\").fill_color(lightgray).shape(none).size(3).line_on(true).line_width(0.5);\n    data_plot.plot(measured_zero_data, \"Rs=0 &#x3A9;\").fill_color(lightgray).shape(square).size(3).line_on(true).line_width(0.5);\n    data_plot.plot(data_2, \"Rs=2 &#x3A9;\").line_color(blue).shape(none).line_on(true).bezier_on(false).line_width(1);\n    data_plot.plot(data_10, \"Rs=10 &#x3A9;\").line_color(purple).shape(none).line_on(true).bezier_on(false).line_width(1);\n    data_plot.plot(data_51, \"Rs=51 &#x3A9;\").line_color(green).shape(none).line_on(true).line_width(1);\n    data_plot.plot(data_249, \"Rs=249 &#x3A9;\").line_color(red).shape(none).line_on(true).line_width(1);\n    data_plot.write(\"./diode_iv_plot\");\n\n    // bezier_on(true);\n  }\n  catch (std::exception& ex)\n  {\n    std::cout << ex.what() << std::endl;\n  }\n\n\n}  // int main()\n\n   /*\n\n   //[lambert_w_output_1\n   Output:\n   Lambert W diode current example.\n   V thermal 0.0257025\n   Isat = 2.5e-14\n   voltage = 0.9, current = 0.00108485, -6.82631\n   -19.65  0.3\n   -15.75  0.4\n   -11.86  0.5\n   -7.97  0.6\n   -4.08  0.7\n   -0.0195  0.8\n   3.6  0.9\n\n   //] [/lambert_w_output_1]\n   */\n", "meta": {"hexsha": "d9a4bcda5e8da0c368ec998c0647a0e87c37ae2f", "size": 9693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/example/lambert_w_diode_graph.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/example/lambert_w_diode_graph.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/example/lambert_w_diode_graph.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 34.4946619217, "max_line_length": 146, "alphanum_fraction": 0.6316929743, "num_tokens": 3209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6173508207819187}}
{"text": "// Copyright John Maddock 2006.\n// Copyright Paul A. Bristow 2007, 2009\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n\n#include <boost/math/special_functions/gamma.hpp>\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n#include <boost/math/tools/stats.hpp>\n#include <boost/math/tools/test.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/array.hpp>\n#include \"libs/math/test/functor.hpp\"\n\n#include \"libs/math/test/handle_test_result.hpp\"\n#include \"../table_type.hpp\"\n\n#ifndef SC_\n#define SC_(x) static_cast<typename table_type<T>::type>(BOOST_JOIN(x, L))\n#endif\n\ntemplate<class Real, class T>\nvoid do_test_gamma(const T& data, const char* type_name, const char* test_name) {\n    typedef typename T::value_type row_type;\n    typedef Real value_type;\n\n    typedef value_type (*pg)(value_type);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n    pg funcp = boost::math::tgamma<value_type>;\n#else\n    pg funcp = boost::math::tgamma;\n#endif\n\n    boost::math::tools::test_result<value_type> result;\n\n    std::cout << \"Testing \" << test_name << \" with type \" << type_name\n              << \"\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n\n    //\n    // test tgamma against data:\n    //\n    result = boost::math::tools::test_hetero<Real>(data, bind_func<Real>(funcp, 0), extract_result<Real>(1));\n    handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::tgamma\", test_name);\n\n    //\n    // test lgamma against data:\n    //\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n    funcp = boost::math::lgamma<value_type>;\n#else\n    funcp = boost::math::lgamma;\n#endif\n    result = boost::math::tools::test_hetero<Real>(data, bind_func<Real>(funcp, 0), extract_result<Real>(2));\n    handle_test_result(result, data[result.worst()], result.worst(), type_name, \"boost::math::lgamma\", test_name);\n\n    std::cout << std::endl;\n}\n\ntemplate<class T>\nvoid test_gamma(T, const char* name) {\n#include \"gamma.ipp\"\n\n    do_test_gamma<T>(gamma, name, \"random values\");\n\n#include \"gamma_1_2.ipp\"\n\n    do_test_gamma<T>(gamma_1_2, name, \"Values near 1 and 2\");\n\n#include \"gamma_0.ipp\"\n\n    do_test_gamma<T>(gamma_0, name, \"Values near 0\");\n\n#include \"gamma_neg.ipp\"\n\n    do_test_gamma<T>(gamma_neg, name, \"Negative arguments\");\n}\n", "meta": {"hexsha": "d485263bcb79c37fa13c7a5fcecb78b0bd9d38e6", "size": 2609, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/multiprecision/test/math/high_prec/test_gamma.hpp", "max_stars_repo_name": "idealatom/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "libs/multiprecision/test/math/high_prec/test_gamma.hpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/multiprecision/test/math/high_prec/test_gamma.hpp", "max_forks_repo_name": "Curryrasul/knapsack-snark", "max_forks_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:53:21.000Z", "avg_line_length": 31.8170731707, "max_line_length": 114, "alphanum_fraction": 0.6968187045, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6173508179296145}}
{"text": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#include <simd_test.hpp>\n#include <boost/simd/function/asec.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/twopio_3.hpp>\n#include <boost/simd/constant/pio_3.hpp>\n#include <boost/simd/constant/two.hpp>\n\nnamespace bs = boost::simd;\n\ntemplate <typename T, std::size_t N, typename Env>\nvoid test(Env& $)\n{\n  using p_t = bs::pack<T, N>;\n\n  T a1[N], b[N], a2[N], c[N];\n  for(std::size_t i = 0; i < N; ++i)\n  {\n    a1[i] = i%2 ?N/T(i) : -(N/T(i));\n    a2[i] = T(i)/10000;\n    b[i] = bs::asec(a1[i]);\n    c[i] = bs::asec(a2[i]);\n  }\n\n  p_t aa1(&a1[0], &a1[0]+N);\n  p_t aa2(&a2[0], &a2[0]+N);\n  p_t bb (&b[0], &b[0]+N);\n  p_t cc (&c[0], &c[0]+N);\n  STF_ULP_EQUAL(bs::asec(aa1), bb, 4);\n  STF_ULP_EQUAL(bs::asec(aa2), cc, 2);\n}\n\nSTF_CASE_TPL(\"Check asec on pack\" , STF_IEEE_TYPES)\n{\n  static const std::size_t N = bs::pack<T>::static_size;\n\n  test<T, N>($);\n  test<T, N/2>($);\n  test<T, N*2>($);\n}\n\nSTF_CASE_TPL (\" asec\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::asec;\n  using p_t = bs::pack<T>;\n  using r_t = decltype(asec(p_t()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, p_t);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(asec(bs::Inf<p_t>()), bs::Pio_2<r_t>(), 0);\n  STF_ULP_EQUAL(asec(bs::Minf<p_t>()), bs::Pio_2<r_t>(), 0);\n  STF_ULP_EQUAL(asec(bs::Nan<p_t>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(asec(bs::Zero<p_t>()), bs::Nan<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(asec(-bs::Two<p_t>()), bs::Twopio_3<r_t>(), 0.5);\n  STF_ULP_EQUAL(asec(bs::Mone<p_t>()), bs::Pi<r_t>(), 0.5);\n  STF_ULP_EQUAL(asec(bs::One<p_t>()), bs::Zero<r_t>(), 0.5);\n  STF_ULP_EQUAL(asec(bs::Two<p_t>()), bs::Pio_3<r_t>(), 0.5);\n}\n", "meta": {"hexsha": "a378b4531dc9eabb5333f6ad216d10d114e7f06f", "size": 2489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/simd/asec.cpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "test/function/simd/asec.cpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/simd/asec.cpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 30.3536585366, "max_line_length": 100, "alphanum_fraction": 0.5897950984, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.617350816482075}}
{"text": "#include <mesh_array.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(MESH_ARRAY);\n\nBOOST_AUTO_TEST_CASE(positive_orientation_test)\n{\n  mesh_array::T4Mesh  M;\n\n  mesh_array::VertexAttribute<float, mesh_array::T4Mesh >  X;\n  mesh_array::VertexAttribute<float, mesh_array::T4Mesh >  Y;\n  mesh_array::VertexAttribute<float, mesh_array::T4Mesh >  Z;\n  \n  \n  M.set_capacity(4u,1u);\n  \n  mesh_array::Vertex const vi = M.push_vertex();\n  mesh_array::Vertex const vj = M.push_vertex();\n  mesh_array::Vertex const vk = M.push_vertex();\n  mesh_array::Vertex const vm = M.push_vertex();\n  \n  mesh_array::Tetrahedron const t = M.push_tetrahedron(vi,vj,vk,vm);\n  \n  X.bind(M);\n  Y.bind(M);\n  Z.bind(M);\n  \n  X(vi) = 0.0f;  Y(vi) = 0.0f;  Z(vi) = 0.0f;\n  X(vj) = 1.0f;  Y(vj) = 0.0f;  Z(vj) = 0.0f;\n  X(vk) = 0.0f;  Y(vk) = 1.0f;  Z(vk) = 0.0f;\n  X(vm) = 0.0f;  Y(vm) = 0.0f;  Z(vm) = 1.0f;\n  \n  bool const is_pos = mesh_array::is_positive_orientation( M, X, Y, Z);\n  \n  BOOST_CHECK( is_pos );\n  \n  \n}\n\nBOOST_AUTO_TEST_CASE(negative_orientation_test)\n{\n  mesh_array::T4Mesh  M;\n  \n  mesh_array::VertexAttribute<float, mesh_array::T4Mesh >  X;\n  mesh_array::VertexAttribute<float, mesh_array::T4Mesh >  Y;\n  mesh_array::VertexAttribute<float, mesh_array::T4Mesh >  Z;\n  \n  \n  M.set_capacity(4u,1u);\n  \n  mesh_array::Vertex const vi = M.push_vertex();\n  mesh_array::Vertex const vj = M.push_vertex();\n  mesh_array::Vertex const vk = M.push_vertex();\n  mesh_array::Vertex const vm = M.push_vertex();\n  \n  mesh_array::Tetrahedron const t = M.push_tetrahedron(vi,vj,vk,vm);\n  \n  X.bind(M);\n  Y.bind(M);\n  Z.bind(M);\n  \n  X(vi) = 0.0f;  Y(vi) = 0.0f;  Z(vi) = 0.0f;\n  X(vj) = 1.0f;  Y(vj) = 0.0f;  Z(vj) = 0.0f;\n  X(vk) = 0.0f;  Y(vk) = 1.0f;  Z(vk) = 0.0f;\n  X(vm) = 0.0f;  Y(vm) = 0.0f;  Z(vm) = -1.0f;\n  \n  bool const is_pos = mesh_array::is_positive_orientation( M, X, Y, Z);\n  \n  BOOST_CHECK( !is_pos );\n  \n  \n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "93efc2e01eab7b2845a19db0adaa07180afb8f47", "size": 2106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/MESH_ARRAY/unit_tests/mesh_array_orientation/mesh_array_orientation.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T09:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-13T00:24:21.000Z", "max_issues_repo_path": "PROX/FOUNDATION/MESH_ARRAY/unit_tests/mesh_array_orientation/mesh_array_orientation.cpp", "max_issues_repo_name": "erleben/matchstick", "max_issues_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/MESH_ARRAY/unit_tests/mesh_array_orientation/mesh_array_orientation.cpp", "max_forks_repo_name": "erleben/matchstick", "max_forks_repo_head_hexsha": "1cfdc32b95437bbb0063ded391c34c9ee9b9583b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.325, "max_line_length": 71, "alphanum_fraction": 0.6562203229, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6172997195717452}}
{"text": "// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick\n// Hart, Tobias Kessler\n//\n// This work is licensed under the terms of the MIT license.\n// For a copy, see <https://opensource.org/licenses/MIT>.\n\n#include <fstream>\n#include <iostream>\n\n#include <boost/make_shared.hpp>\n#include <boost/shared_ptr.hpp>\n#include \"gtest/gtest.h\"\n\n#include \"bark/commons/distribution/distributions_1d.hpp\"\n#include \"bark/commons/distribution/multivariate_normal.hpp\"\n#include \"bark/commons/params/setter_params.hpp\"\n\n// TODO(fortiss): fill our this test\nTEST(distribution_test, normal_dist_1d) {\n  auto params_ptr = std::make_shared<bark::commons::SetterParams>(true);\n  params_ptr->SetReal(\"Mean\", -3.0f);\n  params_ptr->SetReal(\"StdDev\", 2.0f);\n  params_ptr->SetInt(\"RandomSeed\", 1000.0f);\n\n  auto dist_normal = bark::commons::NormalDistribution1D(params_ptr);\n\n  size_t samples = 30000;\n  double mean = 0.0f;\n  for (size_t i = 0; i < samples; ++i) {\n    mean += dist_normal.Sample()[0];\n  }\n  mean /= samples;\n  EXPECT_NEAR(mean, -3.0f, 0.01);\n\n  double std_dev = 0.0f;\n  for (size_t i = 0; i < samples; ++i) {\n    auto sample = dist_normal.Sample()[0];\n    std_dev += abs(mean - sample) * abs(mean - sample);\n  }\n  EXPECT_NEAR(sqrt(std_dev / samples), 2.0f, 0.01);\n}\n\n// TODO(fortiss): fill our this test\nTEST(distribution_test, uniform_dist_1d) {\n  auto params_ptr = std::make_shared<bark::commons::SetterParams>(true);\n  const double lower_bound = -3.0f;\n  const double upper_bound = 10.0f;\n  params_ptr->SetReal(\"LowerBound\", -3.0f);\n  params_ptr->SetReal(\"UpperBound\", 10.0f);\n  params_ptr->SetInt(\"RandomSeed\", 1000.0f);\n\n  auto dist_uniform = bark::commons::UniformDistribution1D(params_ptr);\n\n  size_t samples = 10000;\n  double mean = 0.0f;\n  int num_buckets = 100;\n  double bucket_size = (upper_bound - lower_bound) / num_buckets;\n  std::vector<std::vector<double>> sample_container(num_buckets);\n  for (size_t i = 0; i < samples; ++i) {\n    auto sample = dist_uniform.Sample()[0];\n    EXPECT_TRUE(sample <= upper_bound);\n    EXPECT_TRUE(sample >= lower_bound);\n    sample_container[std::floor((sample - lower_bound) / bucket_size)]\n        .push_back(sample);\n    mean += sample;\n  }\n\n  auto uniform_prob = 1.0f / (upper_bound - lower_bound);\n  for (const auto& container : sample_container) {\n    auto bucket_prob =\n        static_cast<float>(container.size()) / static_cast<float>(samples);\n    EXPECT_NEAR(bucket_prob, bucket_size * uniform_prob, 0.01);\n  }\n\n  EXPECT_NEAR(mean / samples, (lower_bound + upper_bound) / 2.0f, 0.05);\n\n  EXPECT_NEAR(dist_uniform.Density({2.0f}), uniform_prob, 0.001f);\n  EXPECT_NEAR(dist_uniform.Density({3.0f}), uniform_prob, 0.001f);\n  EXPECT_NEAR(dist_uniform.Density({12.0f}), 0.0f, 0.001f);\n  EXPECT_NEAR(dist_uniform.Density({-4.0f}), 0.0f, 0.001f);\n\n  EXPECT_NEAR(dist_uniform.CDF({0.0f}), 3.0f * uniform_prob, 0.001f);\n}\n\nTEST(distribution_test, multivariate_distribution) {\n  // First test zero covariances\n  auto params_ptr = std::make_shared<bark::commons::SetterParams>(true);\n  const double lower_bound = -3.0f;\n  const double upper_bound = 10.0f;\n  params_ptr->SetListListFloat(\n      \"Covariance\", {{1.0, 0.2, 0.1}, {0.2, 3.0, -0.5}, {0.1, -0.5, 0.125553}});\n  params_ptr->SetListFloat(\"Mean\", {1.2f, 12.0f, 0.1234f});\n  params_ptr->SetInt(\"RandomSeed\", 1000.0f);\n\n  auto dist_multivariate = bark::commons::MultivariateDistribution(params_ptr);\n\n  size_t samples = 200000;\n  std::vector<double> mean(3, 0.0f);\n  for (size_t i = 0; i < samples; ++i) {\n    auto sample = dist_multivariate.Sample();\n    for (int j = 0; j < 3; ++j) {\n      mean[j] += sample[j];\n    }\n  }\n  for (int j = 0; j < 3; ++j) {\n    mean[j] /= samples;\n  }\n  auto mean_desired = params_ptr->GetListFloat(\"Mean\", \"\", {});\n  for (int j = 0; j < 3; ++j) {\n    EXPECT_NEAR(mean[j], mean_desired[j], 0.01);\n  }\n\n  std::vector<std::vector<double>> covar(3, std::vector<double>(3, 0.0f));\n  for (size_t i = 0; i < samples; ++i) {\n    auto sample = dist_multivariate.Sample();\n    for (int j = 0; j < 3; ++j) {\n      for (int z = 0; z < 3; ++z) {\n        covar[j][z] += (sample[j] - mean[j]) * (sample[z] - mean[z]);\n      }\n    }\n  }\n  for (int j = 0; j < 3; ++j) {\n    for (int z = 0; z < 3; ++z) {\n      covar[j][z] /= samples;\n    }\n  }\n  auto covar_desired = params_ptr->GetListListFloat(\"Covariance\", \"\", {{}});\n  for (int j = 0; j < 3; ++j) {\n    for (int z = 0; z < 3; ++z) {\n      EXPECT_NEAR(covar[j][z], covar_desired[j][z], 0.01);\n    }\n  }\n}\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "c0bdc089f5dadb37ee86ac19a5380a0a1c65320f", "size": 4593, "ext": "cc", "lang": "C++", "max_stars_repo_path": "bark/commons/tests/distribution_tests.cc", "max_stars_repo_name": "RdecKa/bark", "max_stars_repo_head_hexsha": "4aa4c901417e3a2c97050894ec61fcb57cc94e6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bark/commons/tests/distribution_tests.cc", "max_issues_repo_name": "RdecKa/bark", "max_issues_repo_head_hexsha": "4aa4c901417e3a2c97050894ec61fcb57cc94e6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bark/commons/tests/distribution_tests.cc", "max_forks_repo_name": "RdecKa/bark", "max_forks_repo_head_hexsha": "4aa4c901417e3a2c97050894ec61fcb57cc94e6e", "max_forks_repo_licenses": ["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.0431654676, "max_line_length": 80, "alphanum_fraction": 0.6505551927, "num_tokens": 1494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6172997151567567}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace inv_kinematics {\n\n/*!\n * Class containing the algorithmic part of the package.\n */\nclass AnalyticalIK\n{\n public:\n  /*!\n   * Constructor.\n   */\n  AnalyticalIK();\n\n  /*!\n   * Destructor.\n   */\n  virtual ~AnalyticalIK();\n\n  /*!\n   * Calculate joint angles from the given tool tip position\n   * @return the joint angles\n   */\n  Matrix<float, 6, 1> getJointAngles(MatrixXd H);\n\n  MatrixXd getR03(Matrix<float, 3, 1> theta_);\n\n  /*!\n   * Calculate the tranformation for 1 link\n   * @return the 4x4 Homogenous transformation matrix\n   */\n  MatrixXd MatrixTransformation(float theta, float d_, float a_, float alpha_);\n\n private:\n\n  //! Internal variable to test if Eigen works\n  Matrix2d testMatrix;\n\n  //! DH Parameters of a 6DOF Robot\n  Matrix<float, 6, 1> theta;\n  Matrix<float, 6, 1> d;\n  Matrix<float, 6, 1> a;\n  Matrix<float, 6, 1> alpha;\n};\n\n} /* namespace */\n", "meta": {"hexsha": "563f5926eef52185247a4b7295a1a7d2ff11cf95", "size": 972, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/inv_kinematics/include/inv_kinematics/AnalyticalIK.hpp", "max_stars_repo_name": "RBE501LaserRoboSurgery/LaserRoboSurgery", "max_stars_repo_head_hexsha": "7c5ba1657a86a49f903042953b74d8f2634721f6", "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/inv_kinematics/include/inv_kinematics/AnalyticalIK.hpp", "max_issues_repo_name": "RBE501LaserRoboSurgery/LaserRoboSurgery", "max_issues_repo_head_hexsha": "7c5ba1657a86a49f903042953b74d8f2634721f6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inv_kinematics/include/inv_kinematics/AnalyticalIK.hpp", "max_forks_repo_name": "RBE501LaserRoboSurgery/LaserRoboSurgery", "max_forks_repo_head_hexsha": "7c5ba1657a86a49f903042953b74d8f2634721f6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-05-01T20:03:55.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-01T20:03:55.000Z", "avg_line_length": 18.3396226415, "max_line_length": 79, "alphanum_fraction": 0.6697530864, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6172701359974859}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2014 Gael Guennebaud <gael.guennebaud@inria.fr>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include \"lapack_common.h\"\r\n#include <Eigen/SVD>\r\n\r\n// computes the singular values/vectors a general M-by-N matrix A using divide-and-conquer\r\nEIGEN_LAPACK_FUNC(gesdd,(char *jobz, int *m, int* n, Scalar* a, int *lda, RealScalar *s, Scalar *u, int *ldu, Scalar *vt, int *ldvt, Scalar* /*work*/, int* lwork,\r\n                         EIGEN_LAPACK_ARG_IF_COMPLEX(RealScalar */*rwork*/) int * /*iwork*/, int *info))\r\n{\r\n  // TODO exploit the work buffer\r\n  bool query_size = *lwork==-1;\r\n  int diag_size = (std::min)(*m,*n);\r\n  \r\n  *info = 0;\r\n        if(*jobz!='A' && *jobz!='S' && *jobz!='O' && *jobz!='N')  *info = -1;\r\n  else  if(*m<0)                                                  *info = -2;\r\n  else  if(*n<0)                                                  *info = -3;\r\n  else  if(*lda<std::max(1,*m))                                   *info = -5;\r\n  else  if(*lda<std::max(1,*m))                                   *info = -8;\r\n  else  if(*ldu <1 || (*jobz=='A' && *ldu <*m)\r\n                   || (*jobz=='O' && *m<*n && *ldu<*m))           *info = -8;\r\n  else  if(*ldvt<1 || (*jobz=='A' && *ldvt<*n)\r\n                   || (*jobz=='S' && *ldvt<diag_size)\r\n                   || (*jobz=='O' && *m>=*n && *ldvt<*n))         *info = -10;\r\n  \r\n  if(*info!=0)\r\n  {\r\n    int e = -*info;\r\n    return xerbla_(SCALAR_SUFFIX_UP\"GESDD \", &e, 6);\r\n  }\r\n  \r\n  if(query_size)\r\n  {\r\n    *lwork = 0;\r\n    return 0;\r\n  }\r\n  \r\n  if(*n==0 || *m==0)\r\n    return 0;\r\n  \r\n  PlainMatrixType mat(*m,*n);\r\n  mat = matrix(a,*m,*n,*lda);\r\n  \r\n  int option = *jobz=='A' ? ComputeFullU|ComputeFullV\r\n             : *jobz=='S' ? ComputeThinU|ComputeThinV\r\n             : *jobz=='O' ? ComputeThinU|ComputeThinV\r\n             : 0;\r\n\r\n  BDCSVD<PlainMatrixType> svd(mat,option);\r\n  \r\n  make_vector(s,diag_size) = svd.singularValues().head(diag_size);\r\n\r\n  if(*jobz=='A')\r\n  {\r\n    matrix(u,*m,*m,*ldu)   = svd.matrixU();\r\n    matrix(vt,*n,*n,*ldvt) = svd.matrixV().adjoint();\r\n  }\r\n  else if(*jobz=='S')\r\n  {\r\n    matrix(u,*m,diag_size,*ldu)   = svd.matrixU();\r\n    matrix(vt,diag_size,*n,*ldvt) = svd.matrixV().adjoint();\r\n  }\r\n  else if(*jobz=='O' && *m>=*n)\r\n  {\r\n    matrix(a,*m,*n,*lda)   = svd.matrixU();\r\n    matrix(vt,*n,*n,*ldvt) = svd.matrixV().adjoint();\r\n  }\r\n  else if(*jobz=='O')\r\n  {\r\n    matrix(u,*m,*m,*ldu)        = svd.matrixU();\r\n    matrix(a,diag_size,*n,*lda) = svd.matrixV().adjoint();\r\n  }\r\n    \r\n  return 0;\r\n}\r\n\r\n// computes the singular values/vectors a general M-by-N matrix A using two sided jacobi algorithm\r\nEIGEN_LAPACK_FUNC(gesvd,(char *jobu, char *jobv, int *m, int* n, Scalar* a, int *lda, RealScalar *s, Scalar *u, int *ldu, Scalar *vt, int *ldvt, Scalar* /*work*/, int* lwork,\r\n                         EIGEN_LAPACK_ARG_IF_COMPLEX(RealScalar */*rwork*/) int *info))\r\n{\r\n  // TODO exploit the work buffer\r\n  bool query_size = *lwork==-1;\r\n  int diag_size = (std::min)(*m,*n);\r\n  \r\n  *info = 0;\r\n        if( *jobu!='A' && *jobu!='S' && *jobu!='O' && *jobu!='N') *info = -1;\r\n  else  if((*jobv!='A' && *jobv!='S' && *jobv!='O' && *jobv!='N')\r\n           || (*jobu=='O' && *jobv=='O'))                         *info = -2;\r\n  else  if(*m<0)                                                  *info = -3;\r\n  else  if(*n<0)                                                  *info = -4;\r\n  else  if(*lda<std::max(1,*m))                                   *info = -6;\r\n  else  if(*ldu <1 || ((*jobu=='A' || *jobu=='S') && *ldu<*m))    *info = -9;\r\n  else  if(*ldvt<1 || (*jobv=='A' && *ldvt<*n)\r\n                   || (*jobv=='S' && *ldvt<diag_size))            *info = -11;\r\n  \r\n  if(*info!=0)\r\n  {\r\n    int e = -*info;\r\n    return xerbla_(SCALAR_SUFFIX_UP\"GESVD \", &e, 6);\r\n  }\r\n  \r\n  if(query_size)\r\n  {\r\n    *lwork = 0;\r\n    return 0;\r\n  }\r\n  \r\n  if(*n==0 || *m==0)\r\n    return 0;\r\n  \r\n  PlainMatrixType mat(*m,*n);\r\n  mat = matrix(a,*m,*n,*lda);\r\n  \r\n  int option = (*jobu=='A' ? ComputeFullU : *jobu=='S' || *jobu=='O' ? ComputeThinU : 0)\r\n             | (*jobv=='A' ? ComputeFullV : *jobv=='S' || *jobv=='O' ? ComputeThinV : 0);\r\n  \r\n  JacobiSVD<PlainMatrixType> svd(mat,option);\r\n  \r\n  make_vector(s,diag_size) = svd.singularValues().head(diag_size);\r\n  {\r\n        if(*jobu=='A') matrix(u,*m,*m,*ldu)           = svd.matrixU();\r\n  else  if(*jobu=='S') matrix(u,*m,diag_size,*ldu)    = svd.matrixU();\r\n  else  if(*jobu=='O') matrix(a,*m,diag_size,*lda)    = svd.matrixU();\r\n  }\r\n  {\r\n        if(*jobv=='A') matrix(vt,*n,*n,*ldvt)         = svd.matrixV().adjoint();\r\n  else  if(*jobv=='S') matrix(vt,diag_size,*n,*ldvt)  = svd.matrixV().adjoint();\r\n  else  if(*jobv=='O') matrix(a,diag_size,*n,*lda)    = svd.matrixV().adjoint();\r\n  }\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "07a0990fd675acd3e518409f2bac9e8933a12a06", "size": 5029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/lapack/svd.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/lapack/svd.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/lapack/svd.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": 36.1798561151, "max_line_length": 175, "alphanum_fraction": 0.4841916882, "num_tokens": 1695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6171992204509461}}
{"text": "/**\n * \\file Chebyshev2Filter.cpp\n */\n\n#include <boost/math/special_functions/asinh.hpp>\n\n#include \"Chebyshev2Filter.h\"\n#include \"helpers.h\"\n#include \"IIRFilter.h\"\n\nnamespace\n{\n  template<typename DataType>\n  void create_chebyshev2_analog_coefficients(int order, DataType ripple, std::vector<std::complex<DataType> >& z, std::vector<std::complex<DataType> >& p, DataType& k)\n  {\n    z.clear(); // no zeros for this filter type\n    p.clear();\n    \n    DataType de = static_cast<DataType>(1.0 / std::sqrt(std::pow(10, (0.1 * ripple)) - 1));\n    DataType mu = static_cast<DataType>(boost::math::asinh(1.0 / de) / order);\n    \n    for(int i = -order+1; i < order; i += 2)\n    {\n      std::complex<DataType> p1 = -std::complex<DataType>(std::cos(i * boost::math::constants::pi<DataType>() / (2 * order)), std::sin(i * boost::math::constants::pi<DataType>() / (2 * order)));\n      std::complex<DataType> p2 = std::complex<DataType>(std::sinh(mu) * p1.real(), std::cosh(mu) * p1.imag());\n      \n      p.push_back(std::complex<DataType>(1, 0) / p2);\n      \n      if(i == 0)\n      {\n        continue;\n      }\n      \n      z.push_back(std::complex<DataType>(0, 1 / std::sin(i * boost::math::constants::pi<DataType>() / (2 * order))));\n    }\n    \n    std::complex<DataType> f = 1;\n    for(int i = 0; i < p.size(); ++i)\n    {\n      f *= - p[i];\n    }\n    for(int i = 0; i < z.size(); ++i)\n    {\n      f /= - z[i];\n    }\n    k = f.real();\n  }\n  \n  template<typename DataType>\n  void create_default_chebyshev2_coeffs(size_t order, DataType ripple, DataType Wn, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)\n  {\n    std::vector<std::complex<DataType> > z;\n    std::vector<std::complex<DataType> > p;\n    DataType k;\n    \n    int fs = 2;\n    create_chebyshev2_analog_coefficients(static_cast<int>(order), ripple, z, p, k);\n    DataType warped = 2 * fs * std::tan(boost::math::constants::pi<DataType>() *  Wn / fs);\n    zpk_lp2lp(warped, z, p, k);\n    zpk_bilinear(fs, z, p, k);\n    \n    boost::math::tools::polynomial<DataType> b;\n    boost::math::tools::polynomial<DataType> a;\n    \n    zpk2ba(fs, z, p, k, b, a);\n    \n    for(size_t i = 0; i < std::min(order + 1, b.size()); ++i)\n    {\n      coefficients_in[i] = b[i];\n    }\n    for(size_t i = 0; i < std::min(order, a.size()-1); ++i)\n    {\n      coefficients_out[i] = -a[i];\n    }\n  }\n  \n  template<typename DataType>\n  void create_bp_chebyshev2_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)\n  {\n    std::vector<std::complex<DataType> > z;\n    std::vector<std::complex<DataType> > p;\n    DataType k;\n    \n    int fs = 2;\n    create_chebyshev2_analog_coefficients(static_cast<int>(order/2), ripple, z, p, k);\n    wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);\n    wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);\n    \n    zpk_lp2bp(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n    zpk_bilinear(fs, z, p, k);\n    \n    boost::math::tools::polynomial<DataType> b;\n    boost::math::tools::polynomial<DataType> a;\n    \n    zpk2ba(fs, z, p, k, b, a);\n    \n    for(size_t i = 0; i < std::min(order + 1, b.size()); ++i)\n    {\n      coefficients_in[i] = b[i];\n    }\n    for(size_t i = 0; i < std::min(order, a.size()-1); ++i)\n    {\n      coefficients_out[i] = -a[i];\n    }\n  }\n  \n  template<typename DataType>\n  void create_bs_chebyshev2_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)\n  {\n    std::vector<std::complex<DataType> > z;\n    std::vector<std::complex<DataType> > p;\n    DataType k;\n    \n    int fs = 2;\n    create_chebyshev2_analog_coefficients(static_cast<int>(order/2), ripple, z, p, k);\n    wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);\n    wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);\n    \n    zpk_lp2bs(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n    zpk_bilinear(fs, z, p, k);\n    \n    boost::math::tools::polynomial<DataType> b;\n    boost::math::tools::polynomial<DataType> a;\n    \n    zpk2ba(fs, z, p, k, b, a);\n    \n    for(size_t i = 0; i < std::min(order + 1, b.size()); ++i)\n    {\n      coefficients_in[i] = b[i];\n    }\n    for(size_t i = 0; i < std::min(order, a.size()-1); ++i)\n    {\n      coefficients_out[i] = -a[i];\n    }\n  }\n}\n\nnamespace ATK\n{\n  template <typename DataType>\n  Chebyshev2LowPassCoefficients<DataType>::Chebyshev2LowPassCoefficients(int nb_channels)\n  :Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2LowPassCoefficients<DataType_>::set_ripple(DataType_ ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev2LowPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2LowPassCoefficients<DataType_>::set_cut_frequency(DataType_ cut_frequency)\n  {\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev2LowPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n  \n  template <typename DataType>\n  void Chebyshev2LowPassCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  void Chebyshev2LowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_default_chebyshev2_coeffs(in_order, ripple, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n  \n  template <typename DataType>\n  Chebyshev2HighPassCoefficients<DataType>::Chebyshev2HighPassCoefficients(int nb_channels)\n  :Parent(nb_channels, nb_channels), cut_frequency(0), ripple(0), in_order(1), out_order(1)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2HighPassCoefficients<DataType_>::set_cut_frequency(DataType_ cut_frequency)\n  {\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev2HighPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2HighPassCoefficients<DataType_>::set_ripple(DataType_ ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev2HighPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n  \n  template <typename DataType>\n  void Chebyshev2HighPassCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  void Chebyshev2HighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_default_chebyshev2_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);\n    for(int i = in_order - 1; i >= 0; i -= 2)\n    {\n      coefficients_in[i] = - coefficients_in[i];\n      coefficients_out[i] = - coefficients_out[i];\n    }\n  }\n  \n  template <typename DataType>\n  Chebyshev2BandPassCoefficients<DataType>::Chebyshev2BandPassCoefficients(int nb_channels)\n  :Parent(nb_channels, nb_channels), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandPassCoefficients<DataType_>::set_cut_frequencies(std::pair<DataType_, DataType_> cut_frequencies)\n  {\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandPassCoefficients<DataType_>::set_cut_frequencies(DataType_ f0, DataType_ f1)\n  {\n    this->cut_frequencies = std::make_pair(f0, f1);\n    setup();\n  }\n  \n  template <typename DataType_>\n  std::pair<DataType_, DataType_> Chebyshev2BandPassCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandPassCoefficients<DataType_>::set_ripple(DataType_ ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev2BandPassCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n  \n  template <typename DataType>\n  void Chebyshev2BandPassCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = 2 * order;\n    setup();\n  }\n  \n  template <typename DataType>\n  void Chebyshev2BandPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_bp_chebyshev2_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n  \n  template <typename DataType>\n  Chebyshev2BandStopCoefficients<DataType>::Chebyshev2BandStopCoefficients(int nb_channels)\n  :Parent(nb_channels, nb_channels), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)\n  {\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandStopCoefficients<DataType_>::set_cut_frequencies(std::pair<DataType_, DataType_> cut_frequencies)\n  {\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandStopCoefficients<DataType_>::set_cut_frequencies(DataType_ f0, DataType_ f1)\n  {\n    this->cut_frequencies = std::make_pair(f0, f1);\n    setup();\n  }\n  \n  template <typename DataType_>\n  std::pair<DataType_, DataType_> Chebyshev2BandStopCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n  \n  template <typename DataType_>\n  void Chebyshev2BandStopCoefficients<DataType_>::set_ripple(DataType_ ripple)\n  {\n    this->ripple = ripple;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ Chebyshev2BandStopCoefficients<DataType_>::get_ripple() const\n  {\n    return ripple;\n  }\n  \n  template <typename DataType>\n  void Chebyshev2BandStopCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = 2 * order;\n    setup();\n  }\n  \n  template <typename DataType>\n  void Chebyshev2BandStopCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_bs_chebyshev2_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n  \n  template class Chebyshev2LowPassCoefficients<float>;\n  template class Chebyshev2LowPassCoefficients<double>;\n  template class Chebyshev2HighPassCoefficients<float>;\n  template class Chebyshev2HighPassCoefficients<double>;\n  template class Chebyshev2BandPassCoefficients<float>;\n  template class Chebyshev2BandPassCoefficients<double>;\n  template class Chebyshev2BandStopCoefficients<float>;\n  template class Chebyshev2BandStopCoefficients<double>;\n  \n  template class IIRFilter<Chebyshev2LowPassCoefficients<float> >;\n  template class IIRFilter<Chebyshev2LowPassCoefficients<double> >;\n  template class IIRFilter<Chebyshev2HighPassCoefficients<float> >;\n  template class IIRFilter<Chebyshev2HighPassCoefficients<double> >;\n  template class IIRFilter<Chebyshev2BandPassCoefficients<float> >;\n  template class IIRFilter<Chebyshev2BandPassCoefficients<double> >;\n  template class IIRFilter<Chebyshev2BandStopCoefficients<float> >;\n  template class IIRFilter<Chebyshev2BandStopCoefficients<double> >;\n  \n}\n", "meta": {"hexsha": "f5c04c2756a636379a3289ec9c1c886935422bb7", "size": 11720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/Chebyshev2Filter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "ATK/EQ/Chebyshev2Filter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ATK/EQ/Chebyshev2Filter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 31.3368983957, "max_line_length": 194, "alphanum_fraction": 0.6874573379, "num_tokens": 3392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954106, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.6170759844655419}}
{"text": "#include <iostream>\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n#include <Eigen/OrderingMethods>\n#include <yaml-cpp/yaml.h>\n#include \"NumpySaver.hpp\"\n\nconstexpr double alpha = 1 / 137.035399; // unitless;\nconstexpr double hbarc = 197.3269631;    // MeV*fm;\nconstexpr double c = 299792458;          // m/s\n\ntypedef std::complex<double> mattype;\nconstexpr std::complex<double> I(0, 1);\n\nYAML::Node\nget_config(int argc, char const *argv[])\n{\n    YAML::Node config;\n    switch (argc)\n    {\n    case 2:\n        config = YAML::LoadFile(argv[1]);\n        break;\n    default:\n        config = YAML::LoadFile(\"config.yaml\");\n        break;\n    }\n    return config;\n}\n\n/**\n * @brief Get the potential at each point in r.\n *\n * This is not yet a good implementation, since I am still learning eigen.\n * There is a lot of optimizing potential.\n *\n * @param r in fm\n * @param R0 in fm\n * @param V0 in MeV\n * @param Z1 number of protons\n * @param Z2 number of protons\n * @return potential in MeV\n */\nEigen::ArrayXd get_potential_middle(Eigen::ArrayXd &r, double V0, double Z1, double Z2)\n{\n    Eigen::ArrayXd pot(r.rows() + 1);\n\n    pot[0] = alpha * hbarc * Z1 * Z2 / r[0] + V0;\n\n    for (unsigned int i = 1; i < pot.rows() - 1; i++)\n    {\n        pot[i] = alpha * hbarc * Z1 * Z2 * 2 / (r[i - 1] + r[i]);\n    }\n    pot[pot.rows() - 1] = 0;\n\n    return pot;\n}\n\nEigen::ArrayXd get_potential_integral(Eigen::ArrayXd &r, double V0, double Z1, double Z2)\n{\n    Eigen::ArrayXd pot(r.rows() + 1);\n\n    pot[0] = alpha * hbarc * Z1 * Z2 / r[0] + V0;\n\n    for (unsigned int i = 1; i < pot.rows() - 1; i++)\n    {\n        pot[i] = alpha * hbarc * Z1 * Z2 * std::log(r[i] / r[i - 1]) / (r[i] - r[i - 1]);\n    }\n    pot[pot.rows() - 1] = 0;\n\n    return pot;\n}\n\nEigen::ArrayXd get_middle_points(Eigen::ArrayXd &r)\n{\n    Eigen::ArrayXd m(r.size() - 1);\n    for (int i = 0; i < m.size(); i++)\n        m[i] = (r[i] + r[i + 1]) / 2;\n    return m;\n}\n\nEigen::ArrayXd get_potential_realistic(Eigen::ArrayXd &r, double V0, double Z1, double Z2, double R0)\n{\n    Eigen::ArrayXd pot(r.rows() + 1);\n    auto mid = get_middle_points(r);\n\n    double a = 0.55;\n\n    for (unsigned int i = 0; i < pot.rows() - 2; i++)\n    {\n        pot[i] = V0 * (1 + std::cosh(R0 / a)) / (std::cosh(mid[i] / a) + std::cosh(R0 / a));\n        if (mid[i] >= R0)\n            pot[i] += alpha * hbarc * Z1 * Z2 / (mid[i]);\n        else\n            pot[i] += alpha * hbarc * Z1 * Z2 / (2 * R0) * (3 - std::pow(mid[i] / R0, 2));\n    }\n    pot[pot.rows() - 2] = 0;\n    pot[pot.rows() - 1] = 0;\n\n    return pot;\n}\n\nEigen::ArrayXd get_potential_left(Eigen::ArrayXd &r, double V0, double Z1, double Z2)\n{\n    Eigen::ArrayXd pot(r.rows() + 1);\n\n    pot[0] = alpha * hbarc * Z1 * Z2 / r[0] + V0;\n\n    for (unsigned int i = 1; i < pot.rows(); i++)\n    {\n        pot[i] = alpha * hbarc * Z1 * Z2 / r[i - 1];\n    }\n\n    return pot;\n}\n\nEigen::ArrayXd get_potential_right(Eigen::ArrayXd &r, double V0, double Z1, double Z2)\n{\n    Eigen::ArrayXd pot(r.rows() + 1);\n\n    pot[0] = alpha * hbarc * Z1 * Z2 / r[0] + V0;\n\n    for (unsigned int i = 1; i < pot.rows() - 1; i++)\n    {\n        pot[i] = alpha * hbarc * Z1 * Z2 / r[i];\n    }\n\n    pot[pot.rows() - 1] = 0;\n\n    return pot;\n}\n\nEigen::SparseMatrix<mattype> get_matrix(Eigen::ArrayXcd &k, Eigen::ArrayXd &r)\n{\n    int N = r.size() - 1;\n    auto matrix = Eigen::SparseMatrix<mattype>(2 * N + 3, 2 * N + 3);\n\n    // 2N+2 equations, 4 coefficients in each row, +1 A constraint -2 last boundary\n    matrix.reserve(4 * (2 * N + 2) + 1 - 2);\n\n    matrix.insert(0, 0) = 1;\n\n    for (int i = 0; i < N; i++)\n    {\n        auto j = 2 * i + 1;\n        matrix.insert(j, j - 1) = std::exp(I * k[i] * r[i]);\n        matrix.insert(j, j) = std::exp(-I * k[i] * r[i]);\n        matrix.insert(j, j + 1) = -std::exp(I * k[i + 1] * r[i]);\n        matrix.insert(j, j + 2) = -std::exp(-I * k[i + 1] * r[i]);\n\n        matrix.insert(j + 1, j - 1) = I * k[i] * std::exp(I * k[i] * r[i]);\n        matrix.insert(j + 1, j) = -I * k[i] * std::exp(-I * k[i] * r[i]);\n        matrix.insert(j + 1, j + 1) = -I * k[i + 1] * std::exp(I * k[i + 1] * r[i]);\n        matrix.insert(j + 1, j + 2) = I * k[i + 1] * std::exp(-I * k[i + 1] * r[i]);\n    }\n\n    matrix.insert(2 * N + 1, 2 * N) = std::exp(I * k[N] * r[N]);\n    matrix.insert(2 * N + 1, 2 * N + 1) = std::exp(-I * k[N] * r[N]);\n    matrix.insert(2 * N + 1, 2 * N + 2) = -std::exp(I * k[N + 1] * r[N]);\n\n    matrix.insert(2 * N + 2, 2 * N) = I * k[N] * std::exp(I * k[N] * r[N]);\n    matrix.insert(2 * N + 2, 2 * N + 1) = -I * k[N] * std::exp(-I * k[N] * r[N]);\n    matrix.insert(2 * N + 2, 2 * N + 2) = -I * k[N + 1] * std::exp(I * k[N + 1] * r[N]);\n\n    return matrix;\n}\n\nEigen::ArrayXd get_pdf(Eigen::VectorXcd &sol, Eigen::ArrayXcd &k, Eigen::ArrayXd &r, Eigen::ArrayXd &r_plot)\n{\n    Eigen::ArrayXd pdf(r_plot.size());\n    int i_k = 0;\n\n    auto this_k = k[0];\n    auto this_r = r[0];\n    auto this_A = sol[0];\n    auto this_B = sol[1];\n    for (int i = 0; i < pdf.size(); i++)\n    {\n        while (r_plot[i] > this_r)\n        {\n            i_k++;\n            this_k = k[i_k];\n            this_r = r[i_k];\n            this_A = sol[2 * i_k];\n            this_B = sol[2 * i_k + 1];\n        }\n        pdf[i] = std::norm(this_A * std::exp(I * this_k * r_plot[i]) + this_B * std::exp(-I * this_k * r_plot[i]));\n    }\n    return pdf;\n}\n\nEigen::VectorXcd get_rhs(int N)\n{\n    Eigen::VectorXcd vec = Eigen::VectorXcd::Zero(2 * N + 3);\n    vec[0] = 1;\n    return vec;\n}\n\nvoid run_simulation(YAML::Node &simulation_settings, YAML::Node &data)\n{\n    auto N = simulation_settings[\"N\"].as<int>();\n    auto R0 = simulation_settings[\"R0\"].as<double>();\n    auto R_last = simulation_settings[\"R_last\"].as<double>();\n    auto V0 = simulation_settings[\"V0\"].as<double>();\n    auto E_bind_alpha = simulation_settings[\"E_bind_alpha\"].as<double>();\n    auto pot_method = simulation_settings[\"pot_method\"].as<std::string>();\n\n    auto name = simulation_settings[\"Name\"].as<std::string>();\n\n    std::cout << \"Simulation Setting: \" << name << \"\\n\"\n              << std::endl;\n\n    for (std::size_t i = 0; i < data.size(); i++)\n    {\n        auto A_parent = data[i][\"A_parent\"].as<double>();\n        auto Z_parent = data[i][\"Z_parent\"].as<double>();\n        auto E_bind_p = data[i][\"E_bind_p\"].as<double>();\n        auto E_bind_d = data[i][\"E_bind_d\"].as<double>();\n        auto half_life_lit = data[i][\"half_life\"].as<double>();\n\n        auto symbol = data[i][\"Symbol\"].as<std::string>();\n\n        auto E_alpha = E_bind_p - E_bind_d - E_bind_alpha;\n\n        double A_daughter = A_parent - 4;\n        double Z_daughter = Z_parent - 2;\n        double m_alpha = 3727.379;\n\n        auto R0_this = R0 * std::pow(A_daughter, 1. / 3.);\n\n        // lets first construct the r array as it is constant for every nucleus\n        Eigen::ArrayXd r;\n        if (pot_method == \"realistic\")\n            r = Eigen::ArrayXd::LinSpaced(N + 1, 0, R_last);\n        else\n            r = Eigen::ArrayXd::LinSpaced(N + 1, R0_this, R_last);\n\n        Eigen::ArrayXcd pot;\n        if (pot_method == \"middle\")\n        {\n            pot = get_potential_middle(r, V0, Z_daughter, 2); // MeV\n        }\n        else if (pot_method == \"left\")\n        {\n            pot = get_potential_left(r, V0, Z_daughter, 2); // MeV\n        }\n        else if (pot_method == \"right\")\n        {\n            pot = get_potential_right(r, V0, Z_daughter, 2); // MeV\n        }\n        else if (pot_method == \"integrate\")\n        {\n            pot = get_potential_integral(r, V0, Z_daughter, 2); // MeV\n        }\n        else if (pot_method == \"realistic\")\n        {\n            pot = get_potential_realistic(r, V0, Z_daughter, 2, R0_this); // MeV\n        }\n        else\n        {\n            std::cerr << \"Warning! Unkown potential method: \" << pot_method << std::endl;\n            pot = get_potential_middle(r, V0, Z_daughter, 2); // MeV\n        }\n\n        Eigen::ArrayXcd k = (2 * m_alpha * (E_alpha - pot)).sqrt() / hbarc;\n\n        // Save potential to plot it!\n        Eigen::ArrayXd r_pot(r.size() + 1);\n        if (pot_method == \"realistic\")\n        {\n            r_pot << 0, get_middle_points(r), r(Eigen::last);\n        }\n        else\n        {\n            r_pot << 0, r;\n        }\n        NumpySaver(std::string(\"build/output/\" + name + \"-\" + symbol + \"-pot.npy\")) << r_pot << pot.real();\n\n        auto mat = get_matrix(k, r);\n        auto b = get_rhs(N);\n\n        Eigen::SparseLU<Eigen::SparseMatrix<mattype>, Eigen::COLAMDOrdering<int>> solver;\n        // Compute the ordering permutation vector from the structural pattern of A\n        solver.analyzePattern(mat);\n        // Compute the numerical factorization\n        solver.factorize(mat);\n        // Use the factors to solve the linear system\n        Eigen::VectorXcd x = solver.solve(b);\n\n        // R and T factor\n        double R = std::norm(x(1));\n        double T = std::norm(x(Eigen::last)) * std::abs(k(Eigen::last)) / std::abs(k[0]);\n        // check if R+T=1\n        if (std::abs(R + T - 1) > 1e-3)\n        {\n            std::cerr << \"Warning! R+T not equal to 1; R+T = \" << R + T << \"\\n\";\n        }\n\n        // plot pdf\n        Eigen::ArrayXd r_plot = Eigen::ArrayXd::LinSpaced(1000, 0, R_last);\n        auto pdf = get_pdf(x, k, r, r_plot);\n\n        NumpySaver pdf_saver(std::string(\"build/output/\" + name + \"-\" + symbol + \"-pdf.npy\")); // << r_plot << pdf;\n        pdf_saver.setPrecision(15);\n        pdf_saver << r_plot << pdf;\n\n        double v = std::sqrt(2 * E_alpha / m_alpha) * c;              // m/s\n        double half_life = std::log(2) * 2 * R0_this / T / v * 1e-15; // s\n\n        std::cerr << \"Lifetime of \" << symbol << \" \" << half_life << \"s (Difference to literature value of \"\n                  << (half_life / half_life_lit - 1) * 100 << \"%)\" << std::endl;\n    }\n}\n\nint main(int argc, char const *argv[])\n{\n    auto config = get_config(argc, argv);\n    auto data = config[\"data\"];\n\n    for (std::size_t i = 0; i < config[\"simulation_settings\"].size(); i++)\n    {\n        std::cout << \"##################################\\n\"\n                  << \"# Running Simulation \" << i + 1 << \"/\" << config[\"simulation_settings\"].size()\n                  << \"\\n##################################\\n\";\n        auto settings = config[\"simulation_settings\"][i];\n        run_simulation(settings, data);\n        std::cout << \"\\n\\n\";\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "85eb1e2939140fab4f0bfbf9cdf7dc3ae91e1e08", "size": 10356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project01-AlphaDecay/alpha.cpp", "max_stars_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_stars_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project01-AlphaDecay/alpha.cpp", "max_issues_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_issues_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project01-AlphaDecay/alpha.cpp", "max_forks_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_forks_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1927710843, "max_line_length": 115, "alphanum_fraction": 0.5204712244, "num_tokens": 3356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.6992544335934767, "lm_q1q2_score": 0.6170416022688673}}
{"text": "//    boost asinh.hpp header file\n\n//  (C) Copyright Eric Ford 2001 & Hubert Holin.\n//  (C) Copyright John Maddock 2008.\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n\n// See http://www.boost.org for updates, documentation, and revision history.\n\n#ifndef BOOST_ACOSH_HPP\n#define BOOST_ACOSH_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/config.hpp>\n#include <boost/config/no_tr1/cmath.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/special_functions/math_fwd.hpp>\n#include <boost/math/tools/precision.hpp>\n\n// This is the inverse of the hyperbolic cosine function.\n\nnamespace boost\n{\nnamespace math\n{\nnamespace detail\n{\ntemplate <typename T, typename Policy>\ninline T acosh_imp(const T x, const Policy& pol)\n{\n    BOOST_MATH_STD_USING\n\n    if ((x < 1) || (boost::math::isnan)(x))\n    {\n        return policies::raise_domain_error<T>(\n            \"boost::math::acosh<%1%>(%1%)\",\n            \"acosh requires x >= 1, but got x = %1%.\", x, pol);\n    }\n    else if ((x - 1) >= tools::root_epsilon<T>())\n    {\n        if (x > 1 / tools::root_epsilon<T>())\n        {\n            // http://functions.wolfram.com/ElementaryFunctions/ArcCosh/06/01/06/01/0001/\n            // approximation by laurent series in 1/x at 0+ order from -1 to 0\n            return log(x) + constants::ln_two<T>();\n        }\n        else if (x < 1.5f)\n        {\n            // This is just a rearrangement of the standard form below\n            // devised to minimse loss of precision when x ~ 1:\n            T y = x - 1;\n            return boost::math::log1p(y + sqrt(y * y + 2 * y), pol);\n        }\n        else\n        {\n            // http://functions.wolfram.com/ElementaryFunctions/ArcCosh/02/\n            return (log(x + sqrt(x * x - 1)));\n        }\n    }\n    else\n    {\n        // see\n        // http://functions.wolfram.com/ElementaryFunctions/ArcCosh/06/01/04/01/0001/\n        T y = x - 1;\n\n        // approximation by taylor series in y at 0 up to order 2\n        T result = sqrt(2 * y) * (1 - y / 12 + 3 * y * y / 160);\n        return result;\n    }\n}\n} // namespace detail\n\ntemplate <typename T, typename Policy>\ninline typename tools::promote_args<T>::type acosh(T x, const Policy&)\n{\n    typedef typename tools::promote_args<T>::type result_type;\n    typedef typename policies::evaluation<result_type, Policy>::type value_type;\n    typedef typename policies::normalise<\n        Policy, policies::promote_float<false>, policies::promote_double<false>,\n        policies::discrete_quantile<>, policies::assert_undefined<>>::type\n        forwarding_policy;\n    return policies::checked_narrowing_cast<result_type, forwarding_policy>(\n        detail::acosh_imp(static_cast<value_type>(x), forwarding_policy()),\n        \"boost::math::acosh<%1%>(%1%)\");\n}\ntemplate <typename T>\ninline typename tools::promote_args<T>::type acosh(T x)\n{\n    return boost::math::acosh(x, policies::policy<>());\n}\n\n} // namespace math\n} // namespace boost\n\n#endif /* BOOST_ACOSH_HPP */\n", "meta": {"hexsha": "29e220b1afacd5c29ace967c83a90b457be99b31", "size": 3189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/math/special_functions/acosh.hpp", "max_stars_repo_name": "sotaoverride/backup", "max_stars_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "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": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/math/special_functions/acosh.hpp", "max_issues_repo_name": "sotaoverride/backup", "max_issues_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/math/special_functions/acosh.hpp", "max_forks_repo_name": "sotaoverride/backup", "max_forks_repo_head_hexsha": "ca53a10b72295387ef4948a9289cb78ab70bc449", "max_forks_repo_licenses": ["Apache-2.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.2647058824, "max_line_length": 89, "alphanum_fraction": 0.636563186, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6170415770291263}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_POLYNOMIALS_FUNCTION_SCALAR_LAGUERRE_HPP_INCLUDED\n#define NT2_TOOLBOX_POLYNOMIALS_FUNCTION_SCALAR_LAGUERRE_HPP_INCLUDED\n#include <boost/math/special_functions.hpp>\n#include <nt2/sdk/constant/digits.hpp>\n#include <nt2/sdk/meta/adapted_traits.hpp>\n#include <nt2/include/functions/oneplus.hpp>\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A1 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::laguerre_, tag::cpu_,\n                          (A0)(A1),\n                          (integer_<A0>)(arithmetic_<A1>)\n                         )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::laguerre_(tag::integer_,tag::arithmetic_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n    struct result<This(A0,A1)> :\n      std::tr1::result_of<meta::floating(A0,A1)>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typedef typename NT2_RETURN_TYPE(2)::type type;\n      return nt2::laguerre(a0, type(a1));\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A1 is real_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::laguerre_, tag::cpu_,\n                          (A0)(A1),\n                          (integer_<A0>)(real_<A1>)\n                         )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::laguerre_(tag::integer_,tag::real_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n    struct result<This(A0,A1)> : meta::strip<A1>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      A1 p0 = One<A1>();\n      if(a0 == 0) return p0;\n      A1 p1 = p0-a1;\n      A0 c = 1;\n      while(c < a0)\n      {\n        std::swap(p0, p1);\n        p1 = laguerre_next(c, a1, p0, p1);\n        ++c;\n      }\n      return p1;\n    }\n  private:\n    template <class T, class T1, class T2>\n    static inline T\n    laguerre_next(const uint32_t& n, const T& x, const T1 &Ln, const T2& Lnm1)\n    {\n      const T np1 = oneplus(n);\n      return ((n + np1 - x) * Ln - n *Lnm1) / np1;\n    }\n  };\n} }\n\n#endif\n// modified by jt the 26/12/2010\n", "meta": {"hexsha": "bb0d6c8d2c4f79f1a615e9cf3e9115621bbf834f", "size": 2883, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/polynomials/include/nt2/toolbox/polynomials/function/scalar/laguerre.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/polynomials/include/nt2/toolbox/polynomials/function/scalar/laguerre.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/polynomials/include/nt2/toolbox/polynomials/function/scalar/laguerre.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.393258427, "max_line_length": 78, "alphanum_fraction": 0.5026014568, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6169461930594047}}
{"text": "/*\n\nCopyright (c) 2013  Ghassen Hamrouni\n\nAbstract:\n\nThis module provides some spectral graph algorithms\n\nAuthor:\n\nGhassen Hamrouni <ghamrouni.iptech@gmail.com> 23-07-2013\n\nRevision History:\n\n*/\n\n#ifndef R_1_PUBLIC_GRAPH_LAPLACIAN_SPECTRAL_H_\n#define R_1_PUBLIC_GRAPH_LAPLACIAN_SPECTRAL_H_\n\n#include <Eigen/Dense>\n#include \"SpectralGraph.hpp\"\n\nnamespace R1 {\n\tclass LaplacianSpectralGraph : public SpectralGraph {\n\tpublic:\n\t\tvirtual ~LaplacianSpectralGraph() {}\n\n\t\tLaplacianSpectralGraph(int NVertex) : SpectralGraph(NVertex) {\n\n\t\t}\n\n\t\t//////////////////////////////////////////////////////////////////////////\n\t\t//\t\t\t\t\t\t\t\tLaplacian\n\t\t//////////////////////////////////////////////////////////////////////////\n\n\t\tdouble laplacian(int u, int v) {\n\n\t\t\tdouble dv = degree(v);\n\n\t\t\tif (u == v && dv != 0) {\n\t\t\t\treturn 1 - adjacency_matrix(v, v) / dv;\n\t\t\t}\n\n\t\t\tif (adjacency_matrix(u, v) >= 1.0) {\n\n\t\t\t\tdouble du = degree(u);\n\n\t\t\t\treturn -adjacency_matrix(u, v) / sqrt(du * dv);\n\t\t\t}\n\n\t\t\treturn 0.0;\n\t\t}\n\n\t\tEigen::MatrixXd getLaplacianMatrix() {\n\t\t\tEigen::MatrixXd 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\t\t\t}\n\n\t\t\treturn laplacian_matrix;\n\t\t}\n\n\t\tEigen::VectorXd laplacianSpectrum() {\n\n\t\t\tEigen::MatrixXd L = getLaplacianMatrix();\n\n\t\t\tEigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eg1(L);\n\t\t\treturn eg1.eigenvalues();\n\t\t}\n\n\t\tstatic bool isospectralLaplacian(LaplacianSpectralGraph g1, LaplacianSpectralGraph g2, double epsilon) {\n\n\t\t\tEigen::VectorXd normalizedEg1 = g1.laplacianSpectrum().normalized();\n\t\t\tEigen::VectorXd 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(LaplacianSpectralGraph g1, LaplacianSpectralGraph g2) {\n\t\t\tEigen::VectorXd normalizedEg1 = g1.laplacianSpectrum().normalized();\n\t\t\tEigen::VectorXd 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": "977d1346799094063d66b5c62d72355a7dd4b298", "size": 2711, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/LaplacianSpectralGraph.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/LaplacianSpectralGraph.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/LaplacianSpectralGraph.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.0406504065, "max_line_length": 106, "alphanum_fraction": 0.6137956474, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6169367706118134}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation, \n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file   testVector.cpp\n * @brief  Unit tests for Vector class\n * @author Frank Dellaert\n **/\n\n#include <iostream>\n#include <CppUnitLite/TestHarness.h>\n#include <boost/tuple/tuple.hpp>\n#include <gtsam/base/Vector.h>\n\nusing namespace std;\nusing namespace gtsam;\n\n/* ************************************************************************* */\nTEST( TestVector, Vector_variants )\n{\n  Vector a = Vector_(2,10.0,20.0);\n  double data[] = {10,20};\n  Vector b = Vector_(2,data);\n  EXPECT(assert_equal(a, b));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, copy )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  double data[] = {10,20};\n  Vector b(2);\n  copy(data,data+2,b.data());\n  EXPECT(assert_equal(a, b));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, zero1 )\n{\n  Vector v = Vector::Zero(2);\n  EXPECT(zero(v));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, zero2 )\n{\n  Vector a = zero(2);\n  Vector b = Vector::Zero(2);\n  EXPECT(a==b);\n  EXPECT(assert_equal(a, b));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, scalar_multiply )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  Vector b(2); b(0) = 1; b(1) = 2;\n  EXPECT(assert_equal(a,b*10.0));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, scalar_divide )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  Vector b(2); b(0) = 1; b(1) = 2;\n  EXPECT(assert_equal(b,a/10.0));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, negate )\n{\n  Vector a(2); a(0) = 10; a(1) = 20;\n  Vector b(2); b(0) = -10; b(1) = -20;\n  EXPECT(assert_equal(b, -a));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, sub )\n{\n  Vector a(6);\n  a(0) = 10; a(1) = 20; a(2) = 3;\n  a(3) = 34; a(4) = 11; a(5) = 2;\n\n  Vector result(sub(a,2,5));\n\n  Vector b(3);\n  b(0) = 3; b(1) = 34; b(2) =11;\n\n  EXPECT(b==result);\n  EXPECT(assert_equal(b, result));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, subInsert )\n{\n\tVector big = zero(6),\n\t\t   small = ones(3);\n\n\tsize_t i = 2;\n\tsubInsert(big, small, i);\n\n\tVector expected = Vector_(6, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0);\n\n\tEXPECT(assert_equal(expected, big));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, householder )\n{\n  Vector x(4);\n  x(0) = 3; x(1) = 1; x(2) = 5; x(3) = 1;\n\n  Vector expected(4);\n  expected(0) = 1.0; expected(1) = -0.333333; expected(2) = -1.66667; expected(3) = -0.333333;\n\n  pair<double, Vector> result = house(x);\n\n  EXPECT(result.first==0.5);\n  EXPECT(equal_with_abs_tol(expected,result.second,1e-5));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, concatVectors)\n{\n  Vector A(2);\n  for(int i = 0; i < 2; i++)\n    A(i) = i;\n  Vector B(5);\n  for(int i = 0; i < 5; i++)\n    B(i) = i;\n\n  Vector C(7);\n  for(int i = 0; i < 2; i++) C(i) = A(i);\n  for(int i = 0; i < 5; i++) C(i+2) = B(i);\n\n  list<Vector> vs;\n  vs.push_back(A);\n  vs.push_back(B);\n  Vector AB1 = concatVectors(vs);\n  EXPECT(AB1 == C);\n\n  Vector AB2 = concatVectors(2, &A, &B);\n  EXPECT(AB2 == C);\n}\n\n/* ************************************************************************* */\nTEST( TestVector, weightedPseudoinverse )\n{\n\t// column from a matrix\n\tVector x(2);\n\tx(0) = 1.0; x(1) = 2.0;\n\n\t// create sigmas\n\tVector sigmas(2);\n\tsigmas(0) = 0.1; sigmas(1) = 0.2;\n\tVector weights = reciprocal(emul(sigmas,sigmas));\n\n\t// perform solve\n\tVector actual; double precision;\n\tboost::tie(actual, precision) = weightedPseudoinverse(x, weights);\n\n\t// construct expected\n\tVector expected(2);\n\texpected(0) = 0.5; expected(1) = 0.25;\n\tdouble expPrecision = 200.0;\n\n\t// verify\n\tEXPECT(assert_equal(expected,actual));\n\tEXPECT(fabs(expPrecision-precision) < 1e-5);\n}\n\n/* ************************************************************************* */\nTEST( TestVector, weightedPseudoinverse_constraint )\n{\n\t// column from a matrix\n\tVector x(2);\n\tx(0) = 1.0; x(1) = 2.0;\n\n\t// create sigmas\n\tVector sigmas(2);\n\tsigmas(0) = 0.0; sigmas(1) = 0.2;\n\tVector weights = reciprocal(emul(sigmas,sigmas));\n\n\t// perform solve\n\tVector actual; double precision;\n\tboost::tie(actual, precision) = weightedPseudoinverse(x, weights);\n\n\t// construct expected\n\tVector expected(2);\n\texpected(0) = 1.0; expected(1) = 0.0;\n\n\t// verify\n\tEXPECT(assert_equal(expected,actual));\n\tEXPECT(isinf(precision));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, weightedPseudoinverse_nan )\n{\n\tVector a = Vector_(4, 1., 0., 0., 0.);\n\tVector sigmas = Vector_(4, 0.1, 0.1, 0., 0.);\n\tVector weights = reciprocal(emul(sigmas,sigmas));\n\tVector pseudo; double precision;\n\tboost::tie(pseudo, precision) = weightedPseudoinverse(a, weights);\n\n\tVector expected = Vector_(4, 1., 0., 0.,0.);\n\tEXPECT(assert_equal(expected, pseudo));\n\tDOUBLES_EQUAL(100, precision, 1e-5);\n}\n\n/* ************************************************************************* */\nTEST( TestVector, ediv )\n{\n  Vector a = Vector_(3,10.,20.,30.);\n  Vector b = Vector_(3,2.0,5.0,6.0);\n  Vector actual(ediv(a,b));\n\n  Vector c = Vector_(3,5.0,4.0,5.0);\n  EXPECT(assert_equal(c,actual));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, dot )\n{\n  Vector a = Vector_(3,10.,20.,30.);\n  Vector b = Vector_(3,2.0,5.0,6.0);\n  DOUBLES_EQUAL(20+100+180,dot(a,b),1e-9);\n}\n\n/* ************************************************************************* */\nTEST( TestVector, axpy )\n{\n  Vector x = Vector_(3,10.,20.,30.);\n  Vector y0 = Vector_(3,2.0,5.0,6.0);\n  Vector y1 = y0, y2 = y0;\n  axpy(0.1,x,y1);\n  axpy(0.1,x,y2.head(3));\n  Vector expected = Vector_(3,3.0,7.0,9.0);\n  EXPECT(assert_equal(expected,y1));\n  EXPECT(assert_equal(expected,Vector(y2)));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, equals )\n{\n\tVector v1 = Vector_(1, 0.0/std::numeric_limits<double>::quiet_NaN()); //testing nan\n\tVector v2 = Vector_(1, 1.0);\n\tdouble tol = 1.;\n\tEXPECT(!equal_with_abs_tol(v1, v2, tol));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, greater_than )\n{\n\tVector v1 = Vector_(3, 1.0, 2.0, 3.0),\n\t\t   v2 = zero(3);\n\tEXPECT(greaterThanOrEqual(v1, v1)); // test basic greater than\n\tEXPECT(greaterThanOrEqual(v1, v2)); // test equals\n}\n\n/* ************************************************************************* */\nTEST( TestVector, reciprocal )\n{\n\tVector v = Vector_(3, 1.0, 2.0, 4.0);\n  EXPECT(assert_equal(Vector_(3, 1.0, 0.5, 0.25),reciprocal(v)));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, linear_dependent )\n{\n\tVector v1 = Vector_(3, 1.0, 2.0, 3.0);\n\tVector v2 = Vector_(3, -2.0, -4.0, -6.0);\n\tEXPECT(linear_dependent(v1, v2));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, linear_dependent2 )\n{\n\tVector v1 = Vector_(3, 0.0, 2.0, 0.0);\n\tVector v2 = Vector_(3, 0.0, -4.0, 0.0);\n\tEXPECT(linear_dependent(v1, v2));\n}\n\n/* ************************************************************************* */\nTEST( TestVector, linear_dependent3 )\n{\n\tVector v1 = Vector_(3, 0.0, 2.0, 0.0);\n\tVector v2 = Vector_(3, 0.1, -4.1, 0.0);\n\tEXPECT(!linear_dependent(v1, v2));\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "b8bb0333bda4503d110dbe8bd3b03e5864f28894", "size": 8159, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/base/tests/testVector.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "gtsam/base/tests/testVector.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/base/tests/testVector.cpp", "max_forks_repo_name": "sdmiller/gtsam_pcl", "max_forks_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T12:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:02:48.000Z", "avg_line_length": 26.9273927393, "max_line_length": 94, "alphanum_fraction": 0.4623115578, "num_tokens": 2303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.6169367500370877}}
{"text": "#ifndef LOGISTIC_H\n#define LOGISTIC_H\n#include <iostream>\n#include <stdlib.h>\n#include <cfloat>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include \"../utils/c_utils.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\n\nclass LogisticRegression\n{\n public:\n \tLogisticRegression();\n\tvoid init(bool _normalization = false, bool _standardization = false,bool _with_bias=false);\n\tvoid init(MatrixXd &_X,VectorXd &_Y,double lambda=1.0, bool _normalization = false, bool _standardization = true,bool _with_bias=true);\n \tdouble logPosterior();\n \tvoid setWeights(VectorXd &_W);\n    void setData(MatrixXd &_X,VectorXd &_Y);\n \tVectorXd getWeights();\n \tdouble getBias();\n \tvoid setBias(double bias);\n \tdouble getGradientBias();\n \t//MatrixXd computeHessian(MatrixXd &_X, VectorXd &_Y, VectorXd &_W);\n \tRowVectorXd featureMean,featureStd,featureMin,featureMax;\n \tbool initialized = false;\n \tvirtual double train(int n_iter,double alpha,double tol) = 0 ;\n \tvirtual VectorXd predict(MatrixXd &_X_test, bool prob=false, bool data_processing = true) = 0;\n\n protected:\n \tVectorXd weights;\n \tMatrixXd *X_train;\n \tVectorXd *Y_train;\n\tVectorXd eta,phi;\n\tVectorXd momemtum;\n \tint rows,dim;\n \tdouble lambda,bias,grad_bias;\n \tbool normalization, standardization, with_bias;\n \tVectorXd sigmoid(VectorXd &_eta);\n \t//VectorXd logSigmoid(VectorXd &_eta);\n \tdouble logPrior();\n \tdouble logLikelihood();\n \tMatrixXd Hessian;\n \tC_utils tools;\n\tvirtual void preCompute() = 0;\n \tvirtual VectorXd computeGradient() = 0;\n    //MVNGaussian posterior;\n};\n\n#endif\n", "meta": {"hexsha": "6bd00c5b0120ce566500b46f405daedd11b1538d", "size": 1606, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/likelihood/logistic_regression.hpp", "max_stars_repo_name": "fjorquerauribe/multitarget-tracking", "max_stars_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T13:55:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T20:49:10.000Z", "max_issues_repo_path": "src/likelihood/logistic_regression.hpp", "max_issues_repo_name": "fjorquerauribe/multitarget-tracking", "max_issues_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/likelihood/logistic_regression.hpp", "max_forks_repo_name": "fjorquerauribe/multitarget-tracking", "max_forks_repo_head_hexsha": "2ef5306f71bc1e197be0d9a7e379de1066fb815e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-06-01T07:00:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T05:21:04.000Z", "avg_line_length": 27.6896551724, "max_line_length": 136, "alphanum_fraction": 0.7484433375, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6169106357920578}}
{"text": "/**\n * ****************************************************************************\n * Copyright (c) 2015, Robert Lukierski.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n * ****************************************************************************\n * Simple Least-Squares Solver.\n * ****************************************************************************\n */\n\n#ifndef VISIONCORE_MATH_LEAST_SQUARES_HPP\n#define VISIONCORE_MATH_LEAST_SQUARES_HPP\n\n#include <VisionCore/Platform.hpp>\n#include <Eigen/Cholesky>\n\nnamespace vc\n{\n    \nnamespace math\n{\n\n// TODO eigenify\n    \ntemplate<typename T, int dim>\nclass LSQ\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    typedef T Scalar;\n    static constexpr int Dimension = dim;\n    typedef Eigen::Matrix<Scalar,Dimension,Dimension> MatrixType;\n    typedef Eigen::Matrix<Scalar,Dimension,1> VectorType;\n    typedef Eigen::AutoDiffScalar<Eigen::Matrix<Scalar,Dimension,1>> JetType;\n    \n    EIGEN_DEVICE_FUNC inline LSQ(const std::size_t nc = 0)\n    {\n        reset();\n        NumConstraints = nc;\n    }\n    \n    EIGEN_DEVICE_FUNC inline void reset()\n    {\n        A.setZero();\n        B.setZero();\n        Error = Scalar(0.0);\n        NumConstraints = 0;\n    }\n    \n    EIGEN_DEVICE_FUNC inline void update(const VectorType& J, const Scalar& res, const Scalar& weight = Scalar(1.0))\n    {\n        A.noalias() += J * J.transpose() * weight;\n        B.noalias() -= J * (res * weight);\n        Error += res * res * weight;\n        NumConstraints += 1;\n    }\n    \n    EIGEN_DEVICE_FUNC inline void update(const JetType& j, const Scalar& weight = Scalar(1.0))\n    {\n        update(j.deriviatives(), j.value(), weight);\n    }\n    \n    EIGEN_DEVICE_FUNC inline void finishAndDivide()\n    {\n        A /= (Scalar)NumConstraints;\n        B /= (Scalar)NumConstraints;\n        Error /= (Scalar)NumConstraints;\n    }\n    \n    EIGEN_DEVICE_FUNC inline VectorType solve()\n    {\n        return A.ldlt().solve(-B);\n    }\n    \n    MatrixType A;\n    VectorType B;\n    Scalar Error;\n    std::size_t NumConstraints;\n};\n\n}\n\n}\n\n#endif // VISIONCORE_MATH_LEAST_SQUARES_HPP\n", "meta": {"hexsha": "2ebf6a2084b88e67dc519faf8e8895773685e286", "size": 3576, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/VisionCore/Math/LeastSquares.hpp", "max_stars_repo_name": "lukier/vision_core", "max_stars_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2016-10-30T23:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T12:27:40.000Z", "max_issues_repo_path": "include/VisionCore/Math/LeastSquares.hpp", "max_issues_repo_name": "jczarnowski/vision_core", "max_issues_repo_head_hexsha": "924c53339b1d99ebb3b1e358edfaa1a4e8d3703b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T04:45:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T01:32:22.000Z", "max_forks_repo_path": "include/VisionCore/Math/LeastSquares.hpp", "max_forks_repo_name": "lukier/vision_core", "max_forks_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-14T00:46:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T08:55:11.000Z", "avg_line_length": 31.9285714286, "max_line_length": 116, "alphanum_fraction": 0.6515659955, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6169106303828069}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <algorithm>\n#include <chrono>\n#include <functional>\n#include <iostream>\n#include <ncurses.h>\n#include <thread>\n#include <vector>\n\n#define PI 3.14159265\n\nbool exitRequested = false;\n\nstd::thread timer_start(std::function<void(void)> func, unsigned int interval) {\n  return std::thread([func, interval]() {\n    while (!exitRequested) {\n      auto x = std::chrono::steady_clock::now() +\n               std::chrono::milliseconds(interval);\n      func();\n      std::this_thread::sleep_until(x);\n    }\n  });\n}\n\nusing Point2D = Eigen::Vector2i;\n\nstruct Item {\n  char label;\n  Point2D center;\n\n  Item(char label, Point2D center) : label(label), center(center){};\n};\n\nPoint2D rotatePoint(Point2D start, Point2D center, int degrees) {\n\n\n  float s = sin(degrees * PI / 180.0);\n  float c = cos(degrees * PI / 180.0);\n\n  float resultX = start(0) - center(0);\n  float resultY = start(1) - center(1);\n\n  // Rotation matrix is calculated here\n  float dx = resultX * c - resultY * s;\n  float dy = resultX * s + resultY * c;\n\n  return Point2D{int(center(0) + dx), int(center(1) + dy)};\n}\n\nvoid drawLine(Point2D start, Point2D end, WINDOW *window, char symbol) {\n  // Using Bresenham's line algorithm from\n  // https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm\n  Point2D current = start;\n  int dx = abs(end(0) - start(0));\n  int sx = start(0) < end(0) ? 1 : -1;\n\n  int dy = -abs(end(1) - start(1));\n  int sy = start(1) < end(1) ? 1 : -1;\n\n  int err = dx + dy;\n\n  while (true) {\n    mvwaddch(window, current(1), current(0), symbol);\n\n    if ((current(0) == end(0)) && (current(1) == end(1)))\n      break;\n\n    int e2 = 2 * err;\n\n    if (e2 >= dy) {\n      err += dy;\n      current(0) += sx;\n    }\n\n    if (e2 < dx) {\n      err += dx;\n      current(1) += sy;\n    }\n  }\n}\n\nstruct RotatingSquare {\n  char label;\n\n  Point2D center;\n  int size;\n  float rotationSpeed;\n\n  RotatingSquare(char label, Point2D center, int size = 1,\n                 float rotationSpeed = 0.0)\n      : label(label), center(center), size(size),\n        rotationSpeed(rotationSpeed){};\n};\n\ntemplate <typename T, class... Args> struct Aged {\n  int birthTime;\n  T item;\n  Aged(T item, int birthTime = 0)\n      : birthTime(birthTime), item(std::move(item)){};\n};\n\nint loop = 0;\n// We'll put game state here\nEigen::Vector2i userCursor;\n;\nint timeSpeed = 1;\n\ntemplate <class T> class AgedVector {\n  std::vector<Aged<T>> agedItems;\n  int age;\n  std::function<bool(const Aged<T> &, int)> filterFunction = nullptr;\n\npublic:\n  AgedVector<T>(\n      int age = 0,\n      std::function<bool(const Aged<T> &, int)> filterFunction = nullptr)\n      : age(age), filterFunction(filterFunction){};\n\n  void add(T item) { agedItems.push_back(Aged<T>(item, age)); };\n\n  void tick(int increment = 1) {\n    age += increment;\n    if (filterFunction != nullptr) {\n      auto i = std::begin(agedItems);\n      while (i != std::end(agedItems)) {\n        if (!filterFunction(*i, age)) {\n          i = agedItems.erase(i);\n        } else {\n          ++i;\n        }\n      }\n    }\n  }\n\n  auto begin() const { return agedItems.begin(); }\n  auto end() const { return agedItems.end(); }\n  int getAge() { return age; }\n};\n\nbool under100Ticks(const Aged<Item> &agedItem, int time) {\n  if ((time - agedItem.birthTime) > 100) {\n    return false;\n  }\n  return true;\n}\n\nAgedVector<Item> timeoutList(0, under100Ticks);\nAgedVector<RotatingSquare> squares;\n\nvoid addDecaying(WINDOW *window, Point2D center) {\n  timeoutList.add(Item('*', center));\n}\n\nvoid addSquare(WINDOW *window, Point2D center) {\n  squares.add(RotatingSquare('.', center, 2, 10.0));\n}\n\nvoid drawSquare(WINDOW *window, const RotatingSquare &square, int angle) {\n  int leftX = square.center(0) - square.size;\n  int rightX = square.center(0) + square.size;\n  int topY = square.center(1) - square.size;\n  int bottomY = square.center(1) + square.size;\n\n  // I don't like that the calculation of the rotation angle here has to use\n  // timeSpeed again, when we already passed it in to the squares via tick()\n\n  // Maybe we shouldn't bother with a AgedVector for boxes? Or augment it?\n\n  // Calculate rotated/translated\n  Point2D upperLeft = rotatePoint(Point2D{leftX, topY}, square.center, angle);\n  Point2D upperRight = rotatePoint(Point2D{rightX, topY}, square.center, angle);\n  Point2D lowerLeft =\n      rotatePoint(Point2D{leftX, bottomY}, square.center, angle);\n  Point2D lowerRight =\n      rotatePoint(Point2D{rightX, bottomY}, square.center, angle);\n\n  // Now draw 4 lines\n  drawLine(upperLeft, upperRight, window, square.label);\n  drawLine(upperLeft, lowerLeft, window, square.label);\n  drawLine(upperRight, lowerRight, window, square.label);\n  drawLine(lowerLeft, lowerRight, window, square.label);\n  mvwaddch(window, upperLeft(1), upperLeft(0), '+');\n  mvwaddch(window, upperRight(1), upperRight(0), '+');\n  mvwaddch(window, lowerLeft(1), lowerLeft(0), '+');\n  mvwaddch(window, lowerRight(1), lowerRight(0), '+');\n}\n\nvoid GameLoop(WINDOW *window) {\n  // Get input\n  int x = getch();\n\n  // Update the model\n  int minX = getbegx(window);\n  int minY = getbegy(window);\n  int maxX = getmaxx(window);\n  int maxY = getmaxy(window);\n\n  switch (x) {\n  case 'x':\n    exitRequested = true;\n    return;\n    break;\n  case KEY_LEFT:\n    userCursor(0) = std::max(userCursor(0) - 1, minX + 1);\n    break;\n  case KEY_RIGHT:\n    userCursor(0) = std::min(userCursor(0) + 1, maxX - 2);\n    break;\n  case KEY_UP:\n    userCursor(1) = std::max(userCursor(1) - 1, minY + 1);\n    break;\n  case KEY_DOWN:\n    userCursor(1) = std::min(userCursor(1) + 1, maxY - 2);\n    break;\n  case '+':\n    timeSpeed++;\n    if (timeSpeed > 100) {\n      timeSpeed = 100;\n    }\n    break;\n  case '-':\n    timeSpeed--;\n    if (timeSpeed < 1) {\n      timeSpeed = 1;\n    }\n    break;\n  case 's':\n    addSquare(window, userCursor);\n    break;\n  case ' ':\n    addDecaying(window, userCursor);\n    break;\n  }\n\n  // Draw the output\n  werase(window);\n  wborder(window, 0, 0, 0, 0, 0, 0, 0, 0);\n  mvprintw(10, 10, \"The iteration is %d\", loop++);\n  mvprintw(11, 10, \"The time multiplier is %d\", timeSpeed);\n\n  timeoutList.tick(timeSpeed);\n  squares.tick(timeSpeed);\n  for (const auto &item : timeoutList) {\n    mvwaddch(window, item.item.center(1), item.item.center(0),\n             item.item.label |\n                 COLOR_PAIR((timeoutList.getAge() - item.birthTime) / 10 + 50));\n  }\n\n  for (const auto &agedSquare : squares) {\n    const RotatingSquare &square = agedSquare.item;\n    int angle =\n        (square.rotationSpeed * timeSpeed * (loop - agedSquare.birthTime));\n    drawSquare(window, square, angle);\n  }\n\n  mvwaddch(window, userCursor(1), userCursor(0), 'X' | A_BOLD);\n  wrefresh(window); /* Print it on to the real screen */\n}\n\nint main() {\n  WINDOW *window = initscr(); /* Start curses mode \t\t  */\n  curs_set(0);\n  raw();\n  noecho();\n  cbreak();\n  nodelay(stdscr, TRUE);\n  keypad(stdscr, TRUE);\n  wresize(window, 300, 300);\n  userCursor << 10, 10;\n  start_color();\n  for (int i = 50; i < 60; i++) {\n    init_color(i, (200 - (i - 50) * 20), (1000 - (i - 50) * 100),\n               (100 - (i - 50) * 10));\n    init_pair(i, i, COLOR_BLACK);\n  }\n  timer_start(std::bind(GameLoop, window), 50).join();\n  endwin(); /* End curses mode\t\t  */\n  return 0;\n}\n", "meta": {"hexsha": "27647ee213f9cb7e95a3a27031cd4ca84a2c68ba", "size": 7252, "ext": "cc", "lang": "C++", "max_stars_repo_path": "first_game.cc", "max_stars_repo_name": "gwachob/first_game", "max_stars_repo_head_hexsha": "b8fa8842fde2646e2cbba990d1cf4aaf7ffd9a56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "first_game.cc", "max_issues_repo_name": "gwachob/first_game", "max_issues_repo_head_hexsha": "b8fa8842fde2646e2cbba990d1cf4aaf7ffd9a56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "first_game.cc", "max_forks_repo_name": "gwachob/first_game", "max_forks_repo_head_hexsha": "b8fa8842fde2646e2cbba990d1cf4aaf7ffd9a56", "max_forks_repo_licenses": ["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.8078291815, "max_line_length": 80, "alphanum_fraction": 0.6246552675, "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.7057850340255385, "lm_q1q2_score": 0.6169106242163749}}
{"text": "/*\r\n This program is free software; you can redistribute it and/or modify it under\r\n the terms of the European Union Public Licence - EUPL v.1.1 as published by\r\n the European Commission.\r\n\r\n This program is distributed in the hope that it will be useful, but WITHOUT\r\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r\n FOR A PARTICULAR PURPOSE. See the European Union Public Licence - EUPL v.1.1\r\n for more details.\r\n\r\n You should have received a copy of the European Union Public Licence - EUPL v.1.1\r\n along with this program.\r\n\r\n Further information about the European Union Public Licence - EUPL v.1.1 can\r\n also be found on the world wide web at http://ec.europa.eu/idabc/eupl\r\n\r\n*/\r\n\r\n/*\r\n ------ Copyright (C) 2010 STA Steering Board (space.trajectory.analysis AT gmail.com) ----\r\n*/\r\n\r\n\r\n/*\r\n------------------ Author:       Guillermo Ortega               -------------------\r\n------------------ Affiliation:  European Space Agency (ESA)    -------------------\r\n-----------------------------------------------------------------------------------\r\n Patched by Guillermo on July  11th 2009 to comply with STA statevector defintions and treat special cases\r\n when eccentricity is bigger than zero or when the true anomly or the argument of the perigee are not well\r\n defined. This routine needs to be converted into equinoctial elements for v2.0\r\n\r\n Added lines 227-230 by Tiziana Sabatini on July 2009 to avoid bugs with circular orbits\r\n */\r\n\r\n#include<float.h>\r\n#include<math.h>\r\n#include<stdio.h>\r\n#include<iostream>\r\n#include <Eigen/Core>\r\n#include <Eigen/Geometry>\r\n#include \"statevector.h\"\r\n\r\n#include <QTextStream>\r\n\r\n#define Pi 3.1415926535\r\n\r\n\r\nusing namespace sta;\r\n\r\n/* This function converts a state vector given in cartesian coordinates to an state vector given in\r\n   classical orbital elements. For a defintion about the orbital elements, please see \"statevector.h\"\r\n   /\r\n Description:\r\n      This function transforms spacecraft cartesian orbital elements in Keplerian\r\n      orbital elements\r\n\r\n Input:\r\n      mu standard gravitational parameter of the planet/moon\r\n      x  x-coordinate in ECI system (km)\r\n      y  y-coordinate in ECI system (km)\r\n      z  z-coordinate in ECI system (km)\r\n      xd vx-coordinate in ECI system (km/s)\r\n      yd vy-coordinate in ECI system (km/s)\r\n      zd vz-coordinate in ECI system (km/s)\r\n\r\n Output:\r\n      a  semi-major axis (km)\r\n      ec eccentricity (-)\r\n      i inclination (rad)\r\n      w0 argument of the perigee (rad)\r\n      o0  right ascention of the ascending node (rad)\r\n      m0 mean anomaly (rad)\r\n\r\n\r\n Date: July 2009\r\n Version: 2.0\r\n*/\r\n\r\n\r\n/*\r\n\r\nvoid cartesianTOorbital(double mu, double x, double y, double z, double xd, double yd, double zd,\r\n                double& a,double& e,double& i,double& argperi,double& longnode,double& meananom)\r\n\r\n{\r\n  Deprecated\r\n}\r\n\r\n*/\r\n\r\n\r\n#ifdef _MSC_VER\r\n\r\n\r\n// Inverse hyperbolic trig functions are missing from the MSVC math library\r\ndouble atanh(double x)\r\n{\r\n    return log((1.0 + x) / (1.0 - x)) / 2.0;\r\n}\r\n\r\n#endif\r\n\r\n\r\n/*\r\n   This function converts a state vector given in cartesian coordinates to an state vector given in\r\n   classical orbital elements. For a defintion about the orbital elements, please see \"statevector.h\"\r\n*/\r\n\r\nsta::KeplerianElements cartesianTOorbital(double mu, sta::StateVector cartesianStateVector)\r\n{\r\n\r\n      double h, r, v, rdotv, rdot, trueAnomaly;\r\n      double EccentricSINTrueAnomaly, EccentricCOSTrueAnomaly;\r\n      double SINofTheNode, COSofTheNode;\r\n      double ArgumentOfLatitudeSIN, ArgumentOfLatitudeCOS;\r\n      double pseudoTrueAnomaly, pseudoEccentricity;\r\n      double eccentricAnomaly;\r\n\r\n      Eigen::Vector3d OrbitalMomentum;\r\n\r\n      KeplerianElements foundKeplerianElements;\r\n\r\n      // First find the direction of angular momentum vector\r\n      // Compute orbital momentum vector, Eigen style\r\n      OrbitalMomentum = cartesianStateVector.position.cross(cartesianStateVector.velocity);\r\n\r\n      // Computing the vector norms\r\n      h = OrbitalMomentum.norm();\r\n      r = cartesianStateVector.position.norm();\r\n      v = cartesianStateVector.velocity.norm();\r\n\r\n      rdotv = cartesianStateVector.position.dot(cartesianStateVector.velocity);\r\n      rdot  = rdotv / r;\r\n\r\n\r\n      // Caculating INCLINATION\r\n      foundKeplerianElements.Inclination = acos(OrbitalMomentum(2) / h );\r\n\r\n\r\n      // Calculating the Ascending Node\r\n      if (OrbitalMomentum(0) != 0.0 || OrbitalMomentum(1) != 0.0)\r\n      {\r\n          foundKeplerianElements.AscendingNode = atan2( OrbitalMomentum(0), -OrbitalMomentum(1) );\r\n\r\n      }\r\n      else\r\n      {\r\n          foundKeplerianElements.AscendingNode = 0.0;\r\n      }\r\n\r\n\r\n      // Calculating the Semimajor Axis\r\n      foundKeplerianElements.SemimajorAxis = 1.0 / (2.0 / r - ( v * v) / mu);\r\n\r\n\r\n      // Calculating the Eccentricity\r\n      EccentricSINTrueAnomaly = rdot * h / mu;\r\n      EccentricCOSTrueAnomaly = (( h * h ) / ( mu * r )) - 1.0;\r\n\r\n      foundKeplerianElements.Eccentricity = sqrt( EccentricSINTrueAnomaly * EccentricSINTrueAnomaly + EccentricCOSTrueAnomaly * EccentricCOSTrueAnomaly );\r\n\r\n\r\n      // Calulating the Argument of the Periapsis\r\n      if (EccentricSINTrueAnomaly != 0.0 || EccentricCOSTrueAnomaly != 0.0)\r\n      {\r\n          trueAnomaly = atan2(EccentricSINTrueAnomaly, EccentricCOSTrueAnomaly);\r\n      }\r\n      else\r\n      {\r\n          trueAnomaly = 0.0;\r\n      }\r\n\r\n      SINofTheNode = sin(foundKeplerianElements.AscendingNode);\r\n      COSofTheNode = cos(foundKeplerianElements.AscendingNode);\r\n\r\n      ArgumentOfLatitudeSIN = (cartesianStateVector.position(1) * COSofTheNode - cartesianStateVector.position(0) * SINofTheNode ) / cos(foundKeplerianElements.Inclination);\r\n      ArgumentOfLatitudeCOS = cartesianStateVector.position(0) * COSofTheNode + cartesianStateVector.position(1) * SINofTheNode;\r\n\r\n      if (ArgumentOfLatitudeSIN != 0.0 || ArgumentOfLatitudeCOS != 0.0)\r\n      {\r\n          pseudoTrueAnomaly = atan2(ArgumentOfLatitudeSIN, ArgumentOfLatitudeCOS);\r\n      }\r\n      else\r\n      {\r\n          pseudoTrueAnomaly = 0.0;\r\n      }\r\n\r\n      foundKeplerianElements.ArgumentOfPeriapsis = pseudoTrueAnomaly - trueAnomaly;\r\n\r\n\r\n      if (foundKeplerianElements.ArgumentOfPeriapsis > M_PI)\r\n      {\r\n          foundKeplerianElements.ArgumentOfPeriapsis -= 2.0 * M_PI;\r\n      }\r\n\r\n      if (foundKeplerianElements.ArgumentOfPeriapsis < -M_PI)\r\n      {\r\n          foundKeplerianElements.ArgumentOfPeriapsis += 2.0 * M_PI;\r\n      }\r\n\r\n      if(foundKeplerianElements.Eccentricity<1e-15)\r\n            {\r\n          foundKeplerianElements.ArgumentOfPeriapsis=0; //patched by Ana to match STK results, and avoid undefinition in circular orbits\r\n      }\r\n      // Calculating now the Mean Anomaly\r\n      pseudoEccentricity = sqrt( fabs(1.0 - foundKeplerianElements.Eccentricity) / (1.0 + foundKeplerianElements.Eccentricity) );\r\n\r\n      if (foundKeplerianElements.Eccentricity < 1.0 )  // circular of elliptical case\r\n      {\r\n          eccentricAnomaly = 2.0 * atan (pseudoEccentricity * tan (trueAnomaly / 2.0 ) );\r\n          foundKeplerianElements.MeanAnomaly = eccentricAnomaly - foundKeplerianElements.Eccentricity * sin (eccentricAnomaly);\r\n          if (foundKeplerianElements.MeanAnomaly > M_PI) //Special case in which the mean anomly passed pi radians (elliptic orbit)\r\n          {\r\n              foundKeplerianElements.MeanAnomaly -= 2.0 * M_PI;\r\n          }\r\n          if (foundKeplerianElements.MeanAnomaly < - M_PI) //Special case in which the mean anomly passed -pi radians (elliptic orbit)\r\n          {\r\n              foundKeplerianElements.MeanAnomaly += 2.0 * M_PI;\r\n          }\r\n      }\r\n      else\r\n      {\r\n          eccentricAnomaly = 2.0 * atanh (pseudoEccentricity * tan (trueAnomaly / 2.0 ) );\r\n          foundKeplerianElements.MeanAnomaly = foundKeplerianElements.Eccentricity * sinh (eccentricAnomaly) - eccentricAnomaly;\r\n      }\r\n\r\n      foundKeplerianElements.TrueAnomaly = trueAnomaly;\r\n      if (foundKeplerianElements.Eccentricity < 1e-15)\r\n          foundKeplerianElements.TrueAnomaly = foundKeplerianElements.MeanAnomaly;\r\n      foundKeplerianElements.EccentricAnomaly = eccentricAnomaly;\r\n\r\n      // Finally putting all together and returning control\r\n      return foundKeplerianElements;\r\n\r\n}\r\nsta::DelaunayElements cartesianTOdelaunay(double mu, sta::StateVector cartesianStateVector)\r\n{\r\n    /*\r\n      function that calculates the Delaunay Elements- returns a structure with the 6 elements\r\n      mu- gravitational parameter\r\n      cartesian state vector- state vector for a specified time step\r\n      */\r\n    DelaunayElements CalcDelaunayElements;\r\n    KeplerianElements KeplerianElemList=cartesianTOorbital(mu,cartesianStateVector);\r\n    Eigen::Vector3d OrbitalMomentum;\r\n    OrbitalMomentum = cartesianStateVector.position.cross(cartesianStateVector.velocity);\r\n\r\n    CalcDelaunayElements.l=KeplerianElemList.MeanAnomaly;\r\n    CalcDelaunayElements.g=KeplerianElemList.ArgumentOfPeriapsis;\r\n    CalcDelaunayElements.h=KeplerianElemList.AscendingNode;\r\n    CalcDelaunayElements.L=sqrt(mu*(KeplerianElemList.SemimajorAxis));\r\n    CalcDelaunayElements.G=sqrt(mu*(KeplerianElemList.SemimajorAxis)*(1-(KeplerianElemList.Eccentricity*KeplerianElemList.Eccentricity)));\r\n    CalcDelaunayElements.H=sqrt(mu*(KeplerianElemList.SemimajorAxis)*(1-(KeplerianElemList.Eccentricity*KeplerianElemList.Eccentricity)))*cos((KeplerianElemList.Inclination));\r\n//CalcDelaunayElements.H=cartesianStateVector.position.x()*cartesianStateVector.velocity.y()-cartesianStateVector.position.y()*cartesianStateVector.velocity.x();\r\n    return CalcDelaunayElements;\r\n}\r\nsta::EquinoctialElements cartesianTOequinoctial(double mu,sta::StateVector cartesianStateVector)\r\n{\r\n    /*\r\n      function that calculates the Equinoctial Elements- returns a structure with the 6 elements\r\n      mu- gravitational parameter\r\n      cartesian state vector- state vector for a specified time step\r\n      */\r\n    EquinoctialElements CalcEquinoctialElements;\r\n    KeplerianElements KeplerianElemList=cartesianTOorbital(mu,cartesianStateVector);\r\n    Eigen::Vector3d OrbitalMomentum;\r\n    OrbitalMomentum = cartesianStateVector.position.cross(cartesianStateVector.velocity);\r\n\r\n    CalcEquinoctialElements.SemimajorAxis=KeplerianElemList.SemimajorAxis;\r\n    CalcEquinoctialElements.ecos=KeplerianElemList.Eccentricity*cos(KeplerianElemList.ArgumentOfPeriapsis+KeplerianElemList.AscendingNode);\r\n    CalcEquinoctialElements.esin=KeplerianElemList.Eccentricity*sin(KeplerianElemList.ArgumentOfPeriapsis+KeplerianElemList.AscendingNode);\r\n    CalcEquinoctialElements.tansin=tan(KeplerianElemList.Inclination/2)*sin(KeplerianElemList.AscendingNode);\r\n    CalcEquinoctialElements.tancos=tan(KeplerianElemList.Inclination/2)*cos(KeplerianElemList.AscendingNode);;\r\n    CalcEquinoctialElements.MeanLon=KeplerianElemList.AscendingNode+KeplerianElemList.ArgumentOfPeriapsis+KeplerianElemList.MeanAnomaly;\r\nreturn CalcEquinoctialElements;\r\n}\r\n", "meta": {"hexsha": "defce8f0b3c23ef585bc71c411fbb80865ff1426", "size": 10989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sta-src/Astro-Core/cartesianTOorbital.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "sta-src/Astro-Core/cartesianTOorbital.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "sta-src/Astro-Core/cartesianTOorbital.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 39.6714801444, "max_line_length": 176, "alphanum_fraction": 0.7034307034, "num_tokens": 2822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6169106164919874}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/inv.hpp\n *\n * \\brief Matrix inverse.\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_INV_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_INV_HPP\n\n\n#include <boost/numeric/ublas/exception.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/detail/debug.hpp>\n#include <boost/numeric/ublasx/operation/illcond.hpp>\n#include <boost/numeric/ublasx/operation/lu.hpp>\n#include <boost/numeric/ublasx/operation/num_columns.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n#include <limits>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace boost::numeric::ublas;\n\n/**\n * \\brief Matrix inversion of a square matrix.\n *\n * \\return \\c true if the given input matrix is invertible; \\c false is the\n *  input matrix is (nearly) singular.\n */\ntemplate <typename MatrixT>\nbool inv_inplace(MatrixT& A)\n{\n\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n\ttypedef typename matrix_traits<MatrixT>::size_type size_type;\n\n\t//pre: A is square\n\tBOOST_UBLAS_CHECK(\n\t\tnum_rows(A) == num_columns(A),\n\t\tbad_size()\n\t);\n\n\t// Compute the inverse X=A^{-1} as the solution of the linear system\n\t//  AX = I\n\n\tMatrixT X(identity_matrix<value_type>(num_rows(A)));\n\n\tsize_type sing;\n\tsing = lu_solve_inplace(A, X);\n\n\t// Check if matrix is singular\n\tif (sing)\n\t{\n\t\tBOOST_UBLASX_DEBUG_TRACE(\"Warning: Matrix is (nearly) singular: cannot compute its inverse.\");\n\n\t\t// Fill the matrix with Inf (like MATLAB does)\n\t\tA = scalar_matrix<value_type>(\n\t\t\t\tnum_rows(A),\n\t\t\t\tnum_columns(A),\n\t\t\t\t::std::numeric_limits<value_type>::infinity()\n\t\t\t);\n\n\t\treturn false;\n\t}\n\n\t// Check if matrix is ill-conditioned\n\tif (illcond(A))\n\t{\n\t\tBOOST_UBLASX_DEBUG_TRACE(\"Warning: Matrix is close to singular or badly scaled.  Results may be inaccurate.\");\n\t\t::std::clog << \"[Warning] Matrix is close to singular or badly scaled.  Results may be inaccurate.\" << ::std::endl;\n\t}\n\n\tA = X;\n\n\treturn true;\n}\n\n/**\n * \\brief Matrix inversion of a square matrix.\n */\ntemplate <typename MatrixExprT>\nmatrix<typename matrix_traits<MatrixExprT>::value_type> inv(matrix_expression<MatrixExprT> const& A)\n{\n\ttypedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\ttypedef matrix<value_type> out_matrix_type;\n\n\tout_matrix_type X(A);\n\n\tinv_inplace(X);\n\n\treturn X;\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_INV_HPP\n", "meta": {"hexsha": "fd65bd0ff5ca6084b7aeef4efa95e00a49fddcb4", "size": 2703, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/inv.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/inv.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/inv.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": 25.261682243, "max_line_length": 117, "alphanum_fraction": 0.7369589345, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6168419212593802}}
{"text": "/*\n * A very basic demo of libeigen3.\n *\n * USAGE:\n *    g++ -o transpose -I /PATH/TO/EIGEN/ transpose.cc\n * or\n *    g++ -o transpose $(pkg-config --cflags eigen3) transpose.cc\n */\n\n#include <cstdlib>\n#include <ctime>\n#include <iostream>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nint main()\n{\n    // Initialize the pseudo-random number generator (Eigen uses rand() internally).\n    srand(time(0));\n\n    MatrixXd a = MatrixXd::Random(3, 2);\n\n    std::cout << std::endl << \"Here is the matrix a\"   << std::endl << a             << std::endl;\n    std::cout << std::endl << \"Here is the matrix a^T\" << std::endl << a.transpose() << std::endl;\n    std::cout << std::endl;\n\n    /*\n     * !! WARNING !!\n     * As for basic arithmetic operators, transpose() and adjoint() simply\n     * return a proxy object without doing the actual transposition.\n     * If you do b = a.transpose(), then the transpose is evaluated at the same\n     * time as the result is written into b. However, there is a complication\n     * here.\n     * If you do a = a.transpose(), then Eigen starts writing the result into a\n     * before the evaluation of the transpose is finished. Therefore, the\n     * instruction a = a.transpose() does not replace a with its transpose, as\n     * one would expect:\n     */\n\n    //a = a.transpose(); // ERROR !!! do NOT do this, even with a square matrix !!!\n}\n", "meta": {"hexsha": "12f1f08297f3d5a8a0ba43d10842aa063c1c3f20", "size": 1372, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/eigen/eigen3/transpose/transpose.cc", "max_stars_repo_name": "jeremiedecock/snippets", "max_stars_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-06-08T13:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T08:20:04.000Z", "max_issues_repo_path": "cpp/eigen/eigen3/transpose/transpose.cc", "max_issues_repo_name": "jeremiedecock/snippets", "max_issues_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-22T02:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-22T02:36:10.000Z", "max_forks_repo_path": "cpp/eigen/eigen3/transpose/transpose.cc", "max_forks_repo_name": "jeremiedecock/snippets", "max_forks_repo_head_hexsha": "4bd4e7f459eee610d5cf19f845299ca942ff4b64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-10-31T09:48:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T15:59:45.000Z", "avg_line_length": 31.1818181818, "max_line_length": 98, "alphanum_fraction": 0.6253644315, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6168419182969885}}
{"text": "#include <blitz/array.h>\n\nusing namespace blitz;\n\nint main()\n{\n    Array<float,1> x(4), y(4);\n    Array<float,2> A(4,4);\n\n    x = 1, 2, 3, 4;\n    y = 1, 0, 0, 1;\n\n    firstIndex i;\n    secondIndex j;\n\n    A = x(i) * y(j);\n\n    cout << A << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "b85473166672627b9bd3915182b8560dedb91d1f", "size": 264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/doc/examples/outer.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/outer.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/outer.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": 11.4782608696, "max_line_length": 30, "alphanum_fraction": 0.4810606061, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6168419119257633}}
{"text": "#include \"MyFrameMain.hpp\"\n#include <wx/rawbmp.h>\n#include <wx/msgdlg.h>\n#include <sstream>\n#include <wx/dcclient.h> // For wxPaintDC\n#include <wx/dcbuffer.h> // For wxBufferedPaintDC\n#include <random>\n#include <algorithm>\n#include <array>\n#include <thread>\n#include <cmath>\n\n#include <functional> // For std::ref\n\n//#include <boost/multiprecision/cpp_complex.hpp>\n#include <complex>\n\nMyFrameMain::MyFrameMain(wxWindow* const parent, const wxWindowID id, const wxString& title) :\n\tFrameMain(parent, id, title, wxDefaultPosition, wxSize(1222, 512)), m_bitmap(1 /*Width*/, 1 /*Height*/, 24 /*Depth*/)\n{\n\t// To avoid flickering\n\tSetBackgroundStyle(wxBG_STYLE_PAINT);\n\twxNativePixelData data(this->m_bitmap);\n\tif (!data)\n\t{\n\t\twxMessageBox(\"Couldn\\'t get access to native pixel data\", \"Error drawing\");\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tconst int data_width = data.GetWidth();\n\t\tconst int data_height = data.GetHeight();\n\n\t\t// Zero out the buffer\n\t\t{\n\t\t\twxNativePixelData::Iterator pixel(data);\n\t\t\tfor (int column_index = 0; column_index < data_height; ++column_index, pixel.OffsetY(data, 1))\n\t\t\t{\n\t\t\t\tconst wxNativePixelData::Iterator row_start = pixel;\n\t\t\t\tfor (int row_index = 0; row_index < data_width; ++row_index, ++pixel)\n\t\t\t\t{\n\t\t\t\t\tpixel.Red() = 0;\n\t\t\t\t\tpixel.Green() = 0;\n\t\t\t\t\tpixel.Blue() = 0;\n\t\t\t\t}\n\t\t\t\tpixel = row_start;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid MyFrameMain::start_main_loop()\n{\n\t// Can't do this from the constructor in case the created thread needs to call a virtual function of this.\n\t// That's because accessing virtual functions before the object has finished constructing is undefined\n\t// behavior.\n\tthis->stop_now = false;\n\tthis->main_loop_thread = std::async(std::launch::async, this->main_loop, std::ref(*this));\n}\n\nvoid MyFrameMain::m_timerUpdateScreenOnTimer(wxTimerEvent& evnt)\n{\n\tif (this->in_on_timer)\n\t\treturn;\n\tthis->in_on_timer = true;\n\tthis->Refresh();\n\t//this->Update();\n\tthis->in_on_timer = false;\n}\n\nvoid MyFrameMain::FrameMainOnPaint(wxPaintEvent& evnt)\n{\n\tstd::lock_guard<std::mutex> lckr(this->drawing_lock);\n\tconst wxSize new_size = this->GetClientSize();\n\tif (new_size.x == 0 || new_size.y == 0)\n\t\treturn;\n\tif (this->m_bitmap.GetSize() != new_size)\n\t{\n\t\tthis->changed_dimensions = true;\n\t}\n\t//wxPaintDC dc(this);\n\t//wxBufferedPaintDC dc(this);\n\t// The difference between wxBufferedPaintDCand this class is that this class won't\n\t// double-buffer on platforms which have native double-buffering already,\n\t// avoiding any unnecessary buffering to avoid flicker.\n\twxAutoBufferedPaintDC dc(this);\n\tdc.DrawBitmap\n\t(\n\t\tthis->m_bitmap,\n\t\tdc.DeviceToLogicalX(0),\n\t\tdc.DeviceToLogicalY(0),\n\t\ttrue /* use mask */\n\t);\n\t{\n\t\tstd::ostringstream text_to_show;\n\t\ttext_to_show << \"Magnification: \" << this->m_magnification << \"X\";\n\t\twxPen pen(*wxWHITE);\n\t\tdc.SetPen(pen);\n\t\tdc.DrawRectangle(3, 5, 170, 17);\n\t\tdc.SetTextForeground(wxColour(0, 0, 0));\n\t\tdc.DrawText(text_to_show.str(), wxPoint(5, 5));\n\t}\n\tevnt.Skip();\n\t//wxPen pen(*wxRED, 1); // red pen of width 1\n\t//dc.SetPen(pen);\n\t//dc.DrawPoint(wxPoint(100, 100));\n\t//dc.SetPen(wxNullPen);\n}\n\n//static unsigned compute_mandel_pixel_color(const fl& x0, const fl& y0, const fl& len_x, const fl& len_y)\n//{\n//\tfl x2 = 0;\n//\tfl y2 = 0;\n//\tfl w = 0;\n//\tconst fl max = len_x * len_y;\n//\tunsigned iteration = 0;\n//\tconstexpr unsigned max_iteration = 10000;\n//\tfor (; x2 + y2 <= max && iteration < max_iteration; ++iteration)\n//\t{\n//\t\tconst fl x = x2 - y2 + x0;\n//\t\tconst fl y = w - x2 - y2 + y0;\n//\t\tx2 = x * x;\n//\t\ty2 = y * y;\n//\t\tw = (x + y) * (x + y);\n//\t}\n//\treturn static_cast<unsigned>(static_cast<fl>(iteration) * (static_cast<fl>(0xffffff) / static_cast<fl>(max_iteration)));\n//}\nconstexpr unsigned rgb(const unsigned r, const unsigned g, const unsigned b)\n{\n\treturn (r << 16) + (g << 8) + b;\n}\nconstexpr unsigned pallet[] = {\nrgb(66, 30, 15),// # brown 3\nrgb(25,7,26),// # dark violett\nrgb(9,1,47),// # darkest blue\nrgb(4,4,73),// # blue 5\nrgb(0   ,7,100),// # blue 4\nrgb(12 , 44 ,138),// # blue 3\nrgb(24 , 82, 177),// # blue 2\nrgb(57 ,125 ,209),// # blue 1\nrgb(134 ,181, 229),// # blue 0\nrgb(211 ,236, 248),// # lightest blue\nrgb(241, 233, 191),// # lightest yellow\nrgb(248, 201,  95),// # light yellow\nrgb(255, 170 , 0),// # dirty yellow\nrgb(204, 128  , 0),// # brown 0\nrgb(153,  87  , 0),// # brown 1\nrgb(106,  52  , 3),// # brown 2\n};\n//constexpr unsigned pallet[] = {\n//0x800000U,//maroon\n//0x8B0000U,//dark red\n//0xA52A2AU,//brown\n//0xB22222U,//firebrick\n//0xDC143CU,//crimson\n//0xFF0000U,//red\n//0xFF6347U,//tomato\n//0xFF7F50U,//coral\n//0xCD5C5CU,//indian red\n//0xF08080U,//light coral\n//0xE9967AU,//dark salmon\n//0xFA8072U,//salmon\n//0xFFA07AU,//light salmon\n//0xFF4500U,//orange red\n//0xFF8C00U,//dark orange\n//0xFFA500U,//orange\n//0xFFD700U,//gold\n//0xB8860BU,//dark golden rod\n//0xDAA520U,//golden rod\n//0xEEE8AAU,//pale golden rod\n//0xBDB76BU,//dark khaki\n//0xF0E68CU,//khaki\n//0x808000U,//olive\n//0xFFFF00U,//yellow\n//0x9ACD32U,//yellow green\n//0x556B2FU,//dark olive green\n//0x6B8E23U,//olive drab\n//0x7CFC00U,//lawn green\n//0x7FFF00U,//chart reuse\n//0xADFF2FU,//green yellow\n//0x006400U,//dark green\n//0x008000U,//green\n//0x228B22U,//forest green\n//0x00FF00U,//lime\n//0x32CD32U,//lime green\n//0x90EE90U,//light green\n//0x98FB98U,//pale green\n//0x8FBC8FU,//dark sea green\n//0x00FA9AU,//medium spring green\n//0x00FF7FU,//spring green\n//0x2E8B57U,//sea green\n//0x66CDAAU,//medium aqua marine\n//0x3CB371U,//medium sea green\n//0x20B2AAU,//light sea green\n//0x2F4F4FU,//dark slate gray\n//0x008080U,//teal\n//0x008B8BU,//dark cyan\n//0x00FFFFU,//aqua\n//0x00FFFFU,//cyan\n//0xE0FFFFU,//light cyan\n//0x00CED1U,//dark turquoise\n//0x40E0D0U,//turquoise\n//0x48D1CCU,//medium turquoise\n//0xAFEEEEU,//pale turquoise\n//0x7FFFD4U,//aqua marine\n//0xB0E0E6U,//powder blue\n//0x5F9EA0U,//cadet blue\n//0x4682B4U,//steel blue\n//0x6495EDU,//corn flower blue\n//0x00BFFFU,//deep sky blue\n//0x1E90FFU,//dodger blue\n//0xADD8E6U,//light blue\n//0x87CEEBU,//sky blue\n//0x87CEFAU,//light sky blue\n//0x191970U,//midnight blue\n//0x000080U,//navy\n//0x00008BU,//dark blue\n//0x0000CDU,//medium blue\n//0x0000FFU,//blue\n//0x4169E1U,//royal blue\n//0x8A2BE2U,//blue violet\n//0x4B0082U,//indigo\n//0x483D8BU,//dark slate blue\n//0x6A5ACDU,//slate blue\n//0x7B68EEU,//medium slate blue\n//0x9370DBU,//medium purple\n//0x8B008BU,//dark magenta\n//0x9400D3U,//dark violet\n//0x9932CCU,//dark orchid\n//0xBA55D3U,//medium orchid\n//0x800080U,//purple\n//0xD8BFD8U,//thistle\n//0xDDA0DDU,//plum\n//0xEE82EEU,//violet\n//0xFF00FFU,//magenta / fuchsia\n//0xDA70D6U,//orchid\n//0xC71585U,//medium violet red\n//0xDB7093U,//pale violet red\n//0xFF1493U,//deep pink\n//0xFF69B4U,//hot pink\n//0xFFB6C1U,//light pink\n//0xFFC0CBU,//pink\n//0xFAEBD7U,//antique white\n//0xF5F5DCU,//beige\n//0xFFE4C4U,//bisque\n//0xFFEBCDU,//blanched almond\n//0xF5DEB3U,//wheat\n//0xFFF8DCU,//corn silk\n//0xFFFACDU,//lemon chiffon\n//0xFAFAD2U,//light golden rod yellow\n//0xFFFFE0U,//light yellow\n//0x8B4513U,//saddle brown\n//0xA0522DU,//sienna\n//0xD2691EU,//chocolate\n//0xCD853FU,//peru\n//0xF4A460U,//sandy brown\n//0xDEB887U,//burly wood\n//0xD2B48CU,//tan\n//0xBC8F8FU,//rosy brown\n//0xFFE4B5U,//moccasin\n//0xFFDEADU,//navajo white\n//0xFFDAB9U,//peach puff\n//0xFFE4E1U,//misty rose\n//0xFFF0F5U,//lavender blush\n//0xFAF0E6U,//linen\n//0xFDF5E6U,//old lace\n//0xFFEFD5U,//papaya whip\n//0xFFF5EEU,//sea shell\n//0xF5FFFAU,//mint cream\n//0x708090U,//slate gray\n//0x778899U,//light slate gray\n//0xB0C4DEU,//light steel blue\n//0xE6E6FAU,//lavender\n//0xFFFAF0U,//floral white\n//0xF0F8FFU,//alice blue\n//0xF8F8FFU,//ghost white\n//0xF0FFF0U,//honeydew\n//0xFFFFF0U,//ivory\n//0xF0FFFFU,//azure\n//0xFFFAFAU,//snow\n//0x000000U,//black\n//0x696969U,//dim gray / dim grey\n//0x808080U,//gray / grey\n//0xA9A9A9U,//dark gray / dark grey\n//0xC0C0C0U,//silver\n//0xD3D3D3U,//light gray / light grey\n//0xDCDCDCU,//gainsboro\n//0xF5F5F5U,//white smoke\n//0xFFFFFFU//white\n//};\n//static unsigned compute_mandel_pixel_color(const fl& x0, const fl& y0)\n//{\n//\tfl x = 0;\n//\tfl y = 0;\n//\tunsigned iteration = 0;\n//\tconstexpr unsigned max_iteration = 2000;\n//\twhile (x * x + y * y <= 4 && iteration < max_iteration)\n//\t{\n//\t\tconst fl xtemp = x * x - y * y + x0;\n//\t\ty = 2 * x * y + y0;\n//\t\tx = xtemp;\n//\t\titeration = iteration + 1;\n//\t}\n//\treturn pallet[iteration % (sizeof(pallet) / sizeof(pallet[0]))];\n//}\nstatic unsigned compute_mandel_pixel_color(const fl& x0, const fl& y0)\n{\n\t// boost::multiprecision::cpp_complex_100\n\tstd::complex<double> c(static_cast<double>(x0), static_cast<double>(y0));\n\tstd::complex<double> z = 0;\n\tunsigned iteration = 0;\n\tconstexpr unsigned max_iteration = 2000;\n\t// boost::multiprecision::abs\n\tfor ( ; std::abs(z - c) < 2 && iteration < max_iteration; ++iteration)\n\t{\n\t\tz = z * z + c;\n\t}\n\treturn pallet[iteration % (sizeof(pallet) / sizeof(pallet[0]))];\n}\nvoid MyFrameMain::separate_thread_to_compute_rows(wxNativePixelData& data, wxNativePixelData::Iterator pixel, const unsigned y_start, const unsigned rows_to_compute, MyFrameMain& this_ref, wxSize frame_size)\n{\n\tconst int y_index_until_not_including = y_start + rows_to_compute;\n\tconst fl len_x_frame = frame_size.x;\n\tconst fl len_y_frame = frame_size.y;\n\tif (len_y_frame < y_index_until_not_including)\n\t{\n\t\tthrow std::invalid_argument(\"Trying to draw more rows than exist\");\n\t}\n\tauto frame_x_to_mandel = [len_x_frame, &this_ref](const fl& x_frame) -> fl\n\t{\n\t\treturn this_ref.m_start_x_mandel + this_ref.m_len_x_mandel * (x_frame / len_x_frame);\n\t};\n\tauto frame_y_to_mandel = [len_y_frame, &this_ref](const fl& y_frame) -> fl\n\t{\n\t\treturn this_ref.m_start_y_mandel + this_ref.m_len_y_mandel * (y_frame / len_y_frame);\n\t};\n\twhile (!this_ref.changed_dimensions)\n\t{\n\t\tconst wxNativePixelData::Iterator pixel_start = pixel;\n\t\tfor (int y = y_start; y < y_index_until_not_including && !this_ref.changed_dimensions; ++y, pixel.OffsetY(data, 1))\n\t\t{\n\t\t\tconst fl current_y_mandel = frame_y_to_mandel(frame_size.y - y);\n\t\t\tconst wxNativePixelData::Iterator row_start = pixel;\n\t\t\tfor (int x = 0; x < frame_size.x && !this_ref.changed_dimensions; ++x, ++pixel)\n\t\t\t{\n\t\t\t\tconst fl current_x_mandel = frame_x_to_mandel(x);\n\t\t\t\tconst unsigned pixel_color = compute_mandel_pixel_color(current_x_mandel, current_y_mandel);\n\t\t\t\t//pixel_color *= pixel_color;\n\t\t\t\t//pixel_color /= 2;\n\t\t\t\t//pixel_color = std::min(pixel_color, 0xffffffU);\n\t\t\t\tpixel.Red() = (pixel_color & 0xff0000) >> 16;\n\t\t\t\tpixel.Green() = (pixel_color & 0x00ff00) >> 8;\n\t\t\t\tpixel.Blue() = (pixel_color & 0x0000ff) >> 0;\n\t\t\t}\n\t\t\tpixel = row_start;\n\t\t}\n\t\tpixel = pixel_start;\n\t}\n}\nvoid MyFrameMain::main_loop(MyFrameMain& this_ref)\n{\n\tstd::random_device truly_random;\n\tstd::default_random_engine rand_algo(truly_random());\n\tstd::uniform_int_distribution<int> range(0, 255);\n\twhile (!this_ref.stop_now)\n\t{\n\t\twxSize frame_size;\n\t\t{\n\t\t\tstd::lock_guard<std::mutex> lckr(this_ref.drawing_lock);\n\t\t\tframe_size = this_ref.GetClientSize();\n\t\t\tif (this_ref.m_bitmap.GetSize() != frame_size && frame_size.x > 0 && frame_size.y > 0)\n\t\t\t{\n\t\t\t\tthis_ref.m_bitmap = wxBitmap(frame_size.x, frame_size.y, 24 /* Depth */);\n\t\t\t}\n\t\t\tthis_ref.changed_dimensions = false;\n\t\t}\n\t\twxNativePixelData data(this_ref.m_bitmap);\n\t\tif (!data)\n\t\t{\n\t\t\twxMessageBox(\"Couldn\\'t get access to native pixel data\", \"Error drawing\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst unsigned num_cores = std::max<unsigned>(std::thread::hardware_concurrency() / 2U, 1U);\n\t\t\tstd::vector<std::future<void>> threads;\n\t\t\tthreads.reserve(num_cores);\n\t\t\twxNativePixelData::Iterator pixel(data);\n\t\t\tconst unsigned num_rows_for_each_thread = frame_size.y / num_cores;\n\t\t\tconst unsigned num_rows_for_last_thread = frame_size.y - num_rows_for_each_thread * (num_cores - 1);\n\t\t\tfor (unsigned core_index = 0; core_index < num_cores; ++core_index)\n\t\t\t{\n\t\t\t\tconst unsigned num_rows_for_current_thread = ((core_index == num_cores - 1) ? num_rows_for_last_thread : num_rows_for_each_thread);\n\t\t\t\tthreads.push_back(std::async(std::launch::async, separate_thread_to_compute_rows, std::ref(data), pixel, core_index * num_rows_for_each_thread, num_rows_for_current_thread, std::ref(this_ref), frame_size));\n\t\t\t\tpixel.OffsetY(data, num_rows_for_current_thread);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid MyFrameMain::FrameMainOnLeftDClick(wxMouseEvent& evnt)\n{\n\twxPoint click_position;\n\twxSize window_size;\n\t{\n\t\tstd::lock_guard<std::mutex> lckr(this->drawing_lock);\n\t\tclick_position = evnt.GetPosition();\n\t\twindow_size = this->m_bitmap.GetSize();\n\t}\n\tconst fl ratio_x = static_cast<fl>(click_position.x) / static_cast<fl>(window_size.x);\n\tconst fl ratio_y = static_cast<fl>(window_size.y - click_position.y) / static_cast<fl>(window_size.y);\n\tconst fl new_center_x_mandle = this->m_start_x_mandel + this->m_len_x_mandel * ratio_x;\n\tconst fl new_center_y_mandle = this->m_start_y_mandel + this->m_len_y_mandel * ratio_y;\n\n\tthis->m_len_x_mandel *= this->m_zoom;\n\tthis->m_len_y_mandel *= this->m_zoom;\n\tthis->m_start_x_mandel = new_center_x_mandle - this->m_len_x_mandel / 2;\n\tthis->m_start_y_mandel = new_center_y_mandle - this->m_len_y_mandel / 2;\n\n\tthis->m_magnification /= static_cast<boost::multiprecision::cpp_bin_float_100>(this->m_zoom);\n}\n\nMyFrameMain::~MyFrameMain()\n{\n\tthis->stop_now = true;\n\tthis->changed_dimensions = true;\n\t// Will happen in any case\n\t//this->main_loop_thread.get();\n}\n", "meta": {"hexsha": "3809bdf5a10dc64cdd10d66e5b819f1568dacab7", "size": 13161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wxBitmap/MyFrameMain.cpp", "max_stars_repo_name": "BigBIueWhale/mandelbrot", "max_stars_repo_head_hexsha": "fb863f140a6570251d72ba99b35c6fe6f6c98fa9", "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": "wxBitmap/MyFrameMain.cpp", "max_issues_repo_name": "BigBIueWhale/mandelbrot", "max_issues_repo_head_hexsha": "fb863f140a6570251d72ba99b35c6fe6f6c98fa9", "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": "wxBitmap/MyFrameMain.cpp", "max_forks_repo_name": "BigBIueWhale/mandelbrot", "max_forks_repo_head_hexsha": "fb863f140a6570251d72ba99b35c6fe6f6c98fa9", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6783216783, "max_line_length": 210, "alphanum_fraction": 0.7032140415, "num_tokens": 4501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6168418991833123}}
{"text": "#include \"problemes.h\"\n#include \"chiffres.h\"\n#include \"polygonal.h\"\n#include \"permutation.h\"\n\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\ntypedef std::vector<vecteur> matrice;\n\nENREGISTRER_PROBLEME(98, \"Anagramic squares\") {\n    // By replacing each of the letters in the word CARE with 1, 2, 9, and 6 respectively, we form a square number:\n    // 1296 = 36\u00b2. What is remarkable is that, by using the same digital substitutions, the anagram, RACE, also forms a\n    // square number: 9216 = 96\u00b2. We shall call CARE (and RACE) a square anagram word pair and specify further that\n    // leading zeroes are not permitted, neither may a different letter have the same digital value as another letter.\n    //\n    // Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common\n    // English words, find all the square anagram word pairs (a palindromic word is NOT considered to be an anagram of\n    // itself).\n    // \n    // What is the largest square number formed by any member of such a pair?\n    // \n    // NOTE: All anagrams formed must be contained in the given text file.\n    std::map<nombre, std::set<vecteur>> anagrammes;\n    vecteur chiffres = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n    for (auto permutation: permutation::Permutation<vecteur>(chiffres)) {\n        if (permutation.front() != 0) {\n            for (unsigned short i = 1; i < 10; ++i) {\n                if (polygonal::est_carre(\n                        chiffres::conversion_nombre<nombre>(permutation.begin(), std::next(permutation.begin(), i))))\n                    anagrammes[i].emplace(permutation.begin(), std::next(permutation.begin(), i));\n            }\n            if (polygonal::est_carre(chiffres::conversion_nombre<nombre>(permutation.begin(), permutation.end())))\n                anagrammes[10].insert(permutation);\n        }\n    }\n\n    std::vector<std::string> mots;\n    std::ifstream ifs(\"data/p098_words.txt\");\n    std::string ligne;\n    while (ifs >> ligne) {\n        std::vector<std::string> v;\n        boost::split(v, ligne, boost::is_any_of(\",\\\"\"));\n        mots.insert(mots.end(), v.begin(), v.end());\n    }\n\n    nombre resultat = 0;\n    for (auto it1 = mots.begin(), en = mots.end(); it1 != en; ++it1) {\n        const auto &mot1 = *it1;\n        for (auto it2 = std::next(it1); it2 != en; ++it2) {\n            const auto &mot2 = *it2;\n            if (mot1.size() == mot2.size() && is_permutation(mot1.begin(), mot1.end(), mot2.begin())) {\n                for (const auto &anagramme: anagrammes[mot1.size()]) {\n                    std::map<char, nombre> decode;\n                    for (nombre n = 0; n < mot1.size(); ++n)\n                        decode[mot1.at(n)] = anagramme.at(n);\n\n                    vecteur v;\n                    for (char c: mot2)\n                        v.push_back(decode[c]);\n\n                    if (v.front() != 0) {\n                        auto n1 = chiffres::conversion_nombre<nombre>(anagramme.begin(), anagramme.end());\n                        auto n2 = chiffres::conversion_nombre<nombre>(v.begin(), v.end());\n                        if (polygonal::est_carre(n2)) {\n                            // std::cout << \"(\" << mot1 << \", \" << mot2 << \") ==>\" << n1 << \" \" <<  n2 << std::endl;\n                            resultat = std::max(n1, resultat);\n                            resultat = std::max(n2, resultat);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "a892e1a2ba27ca0035c1998ee068f76212a01874", "size": 3600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme098.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme098.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme0xx/probleme098.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": 45.0, "max_line_length": 120, "alphanum_fraction": 0.5558333333, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6167518282054086}}
{"text": "#include \"surface_manager.h\"\r\n\r\n#include <Eigen/Geometry>\r\n#include <iostream>\r\n\r\n\r\nSurface_Manager::Surface_Manager()\r\n{\r\n\tsurface_type = SURFACE;\r\n}\r\n\r\nSurface_Manager::~Surface_Manager()\r\n{\r\n\r\n}\r\n\r\nvoid Surface_Manager::frameAtPoint(Mesh::Point &pt, VFrame& frm)\r\n{\r\n\tOpenMesh::Vec3d n;\r\n\tassert(surface_type == SURFACE);\r\n\tNormAt(pt, n);\r\n\tfrm.e0 = pt;\r\n\tfrm.e1 = OpenMesh::cross(n,pt);\r\n\tfrm.n = n;\r\n}\r\n\r\nMesh::Point Surface_Manager::PointWithCoordinate(Mesh::Point &pt, VFrame &frm, const Eigen::Vector2d &x)\r\n{\r\n\tMesh::Point fin = pt + x(0) * frm.e0 + x(1) * frm.e1;\r\n\tMesh::Point close_p;\r\n\r\n\tassert(surface_type == SURFACE);\r\n\tCompressionProjiect(fin, close_p);\r\n\r\n\treturn close_p;\r\n}\r\n\r\nvoid Surface_Manager::PointProjection(Mesh::Point& pt, Mesh::Point& proj_p)\r\n{\r\n\tassert(surface_type == SURFACE);\r\n\tCompressionProjiect(pt, proj_p);\r\n}\r\n\r\nvoid Surface_Manager::CompressionProjiect(Mesh::Point& p, Mesh::Point& new_p)\r\n{\r\n\tdouble lambda = 0.76;\r\n\tdouble a = 1.618;\r\n\r\n\tdouble pr = p.norm();\r\n\tdouble prxy = sqrt(p[0] * p[0] + p[1] * p[1]);\r\n\tdouble sin_phi = p[2] / pr;\r\n\tdouble cos_phi = prxy / pr;\r\n\tdouble cos_theta = p[0] / prxy;\r\n\tdouble sin_theta = p[1] / prxy;\r\n\tif (prxy < 1e-8)\r\n\t{\r\n\t\tcos_phi = 0;\r\n\t\tcos_theta = 0;\r\n\t\tsin_theta = 0;\r\n\t}\r\n\r\n\tdouble r = (1 - lambda)* pow(cos_phi, a) + lambda;\r\n\tdouble new_x = r*cos_theta*cos_phi;\r\n\tdouble new_y = r*sin_theta*cos_phi;\r\n\tdouble new_z = r*sin_phi;\r\n\r\n\tnew_p = Mesh::Point(new_x, new_y, new_z);\r\n}\r\n\r\nvoid Surface_Manager::NormAt(Mesh::Point& p, OpenMesh::Vec3d& n)\r\n{\r\n\tdouble lambda = 0.76;\r\n\tdouble a = 1.618;\r\n\r\n\tdouble pr = p.norm();\r\n\tdouble prxy = sqrt(p[0] * p[0] + p[1] * p[1]);\r\n\tdouble sin_phi = p[2] / pr;\r\n\tdouble cos_phi = prxy / pr;\r\n\tdouble cos_theta = p[0] / prxy;\r\n\tdouble sin_theta = p[1] / prxy;\r\n\tif (prxy < 1e-8)\r\n\t{\r\n\t\tn = p;\r\n\t\tn.normalize();\r\n\t\tp = Mesh::Point(1, 0, 0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tdouble dr = (1 - lambda)*a* pow(cos_phi, a - 1)*sin_phi;\r\n\tn = p + dr * OpenMesh::Vec3d(cos_theta * sin_phi, sin_phi * sin_theta, -cos_phi);\r\n\tn.normalize();\r\n\tp = OpenMesh::Vec3d(-n[1], n[0], 0);\r\n\tp.normalize();\r\n\r\n\treturn;\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "8215abb9bbf687c986e4b2679bb6088bad84afcd", "size": 2120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PeelingArt/Mesh/surface_manager.cpp", "max_stars_repo_name": "565353780/peeling-art", "max_stars_repo_head_hexsha": "7427321c8cbf076361c8de2281a0f0cde7fd38bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PeelingArt/Mesh/surface_manager.cpp", "max_issues_repo_name": "565353780/peeling-art", "max_issues_repo_head_hexsha": "7427321c8cbf076361c8de2281a0f0cde7fd38bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PeelingArt/Mesh/surface_manager.cpp", "max_forks_repo_name": "565353780/peeling-art", "max_forks_repo_head_hexsha": "7427321c8cbf076361c8de2281a0f0cde7fd38bb", "max_forks_repo_licenses": ["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.2, "max_line_length": 105, "alphanum_fraction": 0.6183962264, "num_tokens": 681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026663679977, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6167316663634407}}
{"text": "/**\n * @addtogroup LinemodTraining\n * @{\n */\n\n#include <cmath>\n#include <Eigen/Geometry>\n#include <opencv2/core/eigen.hpp>\n#include \"LinemodTemplateGeneratorIteratorSinCos.hpp\"\n\nnamespace CDFF\n{\nnamespace Common\n{\nnamespace LinemodTraining\n{\n\nLinemodTemplateGeneratorIteratorSinCos::LinemodTemplateGeneratorIteratorSinCos(LinemodTemplateGenerator *px_renderer,\n                                                                               float f_lonMin, float f_lonMax, float f_lonStep,\n                                                                               float f_latMin, float f_latMax, float f_latStep,\n                                                                               float f_angleMin, float f_angleMax, float f_angleStep,\n                                                                               float f_radiusMin, float f_radiusMax, float f_radiusStep)\n    :\n      _px_renderer(px_renderer),\n\n      _f_lonMin(f_lonMin * static_cast<float>(CV_PI/180.0)),\n      _f_lonMax(f_lonMax * static_cast<float>(CV_PI/180.0)),\n      _f_lonStep(f_lonStep * static_cast<float>(CV_PI/180.0)),\n      _f_lon(f_lonMin * static_cast<float>(CV_PI/180.0)),\n\n      _f_latMin(f_latMin * static_cast<float>(CV_PI/180.0)),\n      _f_latMax(f_latMax * static_cast<float>(CV_PI/180.0)),\n      _f_latStep(f_latStep * static_cast<float>(CV_PI/180.0)),\n      _f_lat(f_latMin * static_cast<float>(CV_PI/180.0)),\n\n      _f_angleMin(f_angleMin * static_cast<float>(CV_PI/180.0)),\n      _f_angleMax(f_angleMax * static_cast<float>(CV_PI/180.0)),\n      _f_angleStep(f_angleStep * static_cast<float>(CV_PI/180.0)),\n      _f_angle(f_angleMin * static_cast<float>(CV_PI/180.0)),\n\n      _f_radiusMin(f_radiusMin),\n      _f_radiusMax(f_radiusMax),\n      _f_radiusStep(f_radiusStep),\n      _f_radius(f_radiusMin),\n      _mat4_currentPose(),\n      _i_size( static_cast<int>((std::floor((f_lonMax-f_lonMin)/f_lonStep)+1)\n               * (std::floor((f_latMax-f_latMin)/f_latStep)+1)\n               * (std::floor((f_angleMax-f_angleMin)/f_angleStep)+1)\n               * (std::floor((f_radiusMax-f_radiusMin)/f_radiusStep)+1))),\n      _b_isDone(false)\n{\n}\n\nLinemodTemplateGeneratorIteratorSinCos & LinemodTemplateGeneratorIteratorSinCos::operator++()\n{\n    _f_lon += _f_lonStep ;\n    if (_f_lon > _f_lonMax){\n        _f_lon = _f_lonMin;\n        _f_lat += _f_latStep;\n        if (_f_lat > _f_latMax){\n            _f_lat = _f_latMin;\n            _f_angle += _f_angleStep;\n            if (_f_angle > _f_angleMax)\n            {\n                _f_angle = _f_angleMin;\n                _f_radius += _f_radiusStep;\n                if (_f_radius > _f_radiusMax)\n                {\n                    _b_isDone = true;\n                }\n            }\n        }\n    }\n    return *this;\n}\n\nvoid LinemodTemplateGeneratorIteratorSinCos::render(std::vector<cv::Mat> &sources, cv::Mat &mask_out, int num_modalities)\n{\n    if (isDone())\n        return;\n\n    // North east down (NED) Frame\n    cv::Mat R_NED = (cv::Mat_<double>(3,3) <<\n                     -sin( static_cast<double>(_f_lat))*cos( static_cast<double>(_f_lon)),   -sin( static_cast<double>(_f_lon)),      -cos( static_cast<double>(_f_lat))*cos( static_cast<double>(_f_lon)),\n                     -sin( static_cast<double>(_f_lat))*sin( static_cast<double>(_f_lon)),    cos( static_cast<double>(_f_lon)),      -cos( static_cast<double>(_f_lat))*sin( static_cast<double>(_f_lon)),\n                     cos( static_cast<double>(_f_lat)),              0,                  -sin( static_cast<double>(_f_lat)));\n\n    // Rotation around Z\n    cv::Mat R_z = (cv::Mat_<double>(3,3) <<\n                   cos( static_cast<double>(_f_angle)),    -sin( static_cast<double>(_f_angle)),      0,\n                   sin( static_cast<double>(_f_angle)),    cos( static_cast<double>(_f_angle)),       0,\n                   0,               0,                  1);\n\n    cv::Mat Position = R_NED*R_z*cv::Mat(cv::Vec3d(0,0,- static_cast<double>(_f_radius)));\n    _mat4_currentPose = cv::Affine3d(R_NED*R_z, cv::Vec3d(Position));\n\n    _px_renderer->setPose(_mat4_currentPose);\n    _px_renderer->render(num_modalities);\n\n    sources.push_back(_px_renderer->_x_colorImage);\n    if(num_modalities == 2)\n        sources.push_back(_px_renderer->_x_depthImage);\n    mask_out = _px_renderer->_x_maskImage;\n}\n\n}\n}\n}\n/** @} */\n", "meta": {"hexsha": "af08c3b84e73de4550bce599047922f9bea56bb4", "size": 4333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Common/LinemodTraining/linemod-wrapper/LinemodTemplateGeneratorIteratorSinCos.cpp", "max_stars_repo_name": "H2020-InFuse/cdff", "max_stars_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T15:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T07:39:01.000Z", "max_issues_repo_path": "Common/LinemodTraining/linemod-wrapper/LinemodTemplateGeneratorIteratorSinCos.cpp", "max_issues_repo_name": "H2020-InFuse/cdff", "max_issues_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Common/LinemodTraining/linemod-wrapper/LinemodTemplateGeneratorIteratorSinCos.cpp", "max_forks_repo_name": "H2020-InFuse/cdff", "max_forks_repo_head_hexsha": "e55fd48f9a909d0c274c3dfa4fe2704bc5071542", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-06T12:09:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T12:09:05.000Z", "avg_line_length": 39.3909090909, "max_line_length": 203, "alphanum_fraction": 0.5875836603, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.6166553126348576}}
{"text": "\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n#include <iostream>\n\n#include \"../src/spherical_harmonics.hpp\"\n\nusing namespace fsph;\nusing namespace boost::math;\n\nint main(int argc, char **argv)\n{\n    unsigned int lmax(5);\n    float phi(0.25), theta(1.5*M_PI);\n\n    PointSPHEvaluator<float> eval(lmax);\n    eval.compute(phi, theta);\n    PointSPHEvaluator<float>::iterator iter(eval.begin(true));\n\n    double error(0);\n    unsigned int N(0);\n\n    for(unsigned int l(0); l <= lmax; ++l)\n    {\n        for(unsigned int m(0); m <= l; ++m)\n        {\n            std::complex<float> from_fsph(*iter);\n            // std::cout << iter.grad_phi(phi, theta) << ' ' << iter.grad_theta() << std::endl;\n            // boost names phi and theta using the opposite convention\n            std::complex<float> from_boost(spherical_harmonic(l, m, phi, theta));\n            from_boost *= pow(-1, m);\n            error += abs(from_fsph - from_boost);\n            if(abs(from_fsph - from_boost) > 1e-5)\n                std::cout << l << ' ' << m << ' ' << from_fsph << ' ' << from_boost << std::endl;\n            ++N;\n            ++iter;\n        }\n        for(unsigned int m(1); m <= l; ++m)\n        {\n            std::complex<float> from_fsph(*iter);\n            // std::cout << iter.grad_phi(phi, theta) << ' ' << iter.grad_theta() << std::endl;\n            // boost names phi and theta using the opposite convention\n            std::complex<float> from_boost(spherical_harmonic(l, -(int)m, phi, theta));\n            error += abs(from_fsph - from_boost);\n            if(abs(from_fsph - from_boost) > 1e-5)\n                std::cout << l << ' ' << m << ' ' << from_fsph << ' ' << from_boost << std::endl;\n            ++N;\n            ++iter;\n        }\n    }\n\n    const unsigned int start_l(2);\n    const unsigned int start_m(1);\n    PointSPHEvaluator<float>::iterator iter_l(eval.begin_l(start_l, start_m, false));\n\n    for(unsigned int l(start_l); l <= lmax; ++l)\n    {\n        for(unsigned int m(l == start_l? start_m: 0); m <= l; ++m)\n        {\n            std::complex<float> from_fsph(*iter_l);\n            // std::cout << iter_l.grad_phi(phi, theta) << ' ' << iter_l.grad_theta() << std::endl;\n            // boost names phi and theta using the opposite convention\n            std::complex<float> from_boost(spherical_harmonic(l, m, phi, theta));\n            from_boost *= pow(-1, m);\n            error += abs(from_fsph - from_boost);\n            if(abs(from_fsph - from_boost) > 1e-5)\n                std::cout << l << ' ' << m << ' ' << from_fsph << ' ' << from_boost << std::endl;\n            ++N;\n            ++iter_l;\n        }\n    }\n\n    return error/N > 1e-7;\n}\n", "meta": {"hexsha": "e3ca9f2f207b812ed0cf3ec3b199068998778a14", "size": 2673, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_boost.cpp", "max_stars_repo_name": "glotzerlab/fsph", "max_stars_repo_head_hexsha": "5896cffe2916763db57b801d2c9b092db232fc7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-09T12:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-30T15:49:49.000Z", "max_issues_repo_path": "tests/test_boost.cpp", "max_issues_repo_name": "glotzerlab/fsph", "max_issues_repo_head_hexsha": "5896cffe2916763db57b801d2c9b092db232fc7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-08-13T13:48:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T13:57:09.000Z", "max_forks_repo_path": "tests/test_boost.cpp", "max_forks_repo_name": "glotzerlab/fsph", "max_forks_repo_head_hexsha": "5896cffe2916763db57b801d2c9b092db232fc7a", "max_forks_repo_licenses": ["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.1216216216, "max_line_length": 99, "alphanum_fraction": 0.5331088664, "num_tokens": 709, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6166551700515557}}
{"text": "/*\n * Filename: inverse_condition_number.cpp\n *\n * Copyright 2020 Tecnalia\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include <manipulability_metrics/metrics/inverse_condition_number.h>\n\n#include <Eigen/SVD>\n\nnamespace manipulability_metrics\n{\ndouble inverseConditionNumber(const Chain& chain, const KDL::JntArray& joint_positions)\n{\n  return inverseConditionNumber(chain, KDL::Vector::Zero(), joint_positions);\n}\n\ndouble inverseConditionNumber(const Chain& chain, const KDL::Vector& tcp_offset, const KDL::JntArray& joint_positions)\n{\n  auto jac = KDL::Jacobian{ static_cast<unsigned int>(chain.n_joints) };\n  chain.jacobian(joint_positions, tcp_offset, jac);\n\n  auto jac_svd = Eigen::JacobiSVD<Eigen::Matrix<double, 6, Eigen::Dynamic>>{ jac.data };\n\n  return jac_svd.singularValues()(jac_svd.singularValues().rows() - 1) / jac_svd.singularValues()(0);\n}\n}  // namespace manipulability_metrics\n", "meta": {"hexsha": "d96cf79e68a25f276b7b58e25a590198032200d7", "size": 1416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "manipulability_metrics/src/inverse_condition_number.cpp", "max_stars_repo_name": "tecnalia-medical-robotics/manipulability_metrics", "max_stars_repo_head_hexsha": "0e1360376a49fdc623e761fc8ca769e99fa11ac9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-15T16:15:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T03:01:22.000Z", "max_issues_repo_path": "manipulability_metrics/src/inverse_condition_number.cpp", "max_issues_repo_name": "iLoveVenki/manipulability_metrics", "max_issues_repo_head_hexsha": "0e1360376a49fdc623e761fc8ca769e99fa11ac9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "manipulability_metrics/src/inverse_condition_number.cpp", "max_forks_repo_name": "iLoveVenki/manipulability_metrics", "max_forks_repo_head_hexsha": "0e1360376a49fdc623e761fc8ca769e99fa11ac9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-04-06T08:18:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-18T12:43:57.000Z", "avg_line_length": 35.4, "max_line_length": 118, "alphanum_fraction": 0.7584745763, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6166551640031179}}
{"text": "#ifndef FAST_GICP_SO3_HPP\n#define FAST_GICP_SO3_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace fast_gicp {\n\ninline Eigen::Matrix3f skew(const Eigen::Vector3f& x) {\n  Eigen::Matrix3f skew = Eigen::Matrix3f::Zero();\n  skew(0, 1) = -x[2];\n  skew(0, 2) = x[1];\n  skew(1, 0) = x[2];\n  skew(1, 2) = -x[0];\n  skew(2, 0) = -x[1];\n  skew(2, 1) = x[0];\n\n  return skew;\n}\n\ninline Eigen::Matrix3d skewd(const Eigen::Vector3d& x) {\n  Eigen::Matrix3d skew = Eigen::Matrix3d::Zero();\n  skew(0, 1) = -x[2];\n  skew(0, 2) = x[1];\n  skew(1, 0) = x[2];\n  skew(1, 2) = -x[0];\n  skew(2, 0) = -x[1];\n  skew(2, 1) = x[0];\n\n  return skew;\n}\n\n/*\n * SO3 expmap code taken from Sophus\n * https://github.com/strasdat/Sophus/blob/593db47500ea1a2de5f0e6579c86147991509c59/sophus/so3.hpp#L585\n *\n * Copyright 2011-2017 Hauke Strasdat\n *           2012-2017 Steven Lovegrove\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights  to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\ninline Eigen::Quaterniond so3_exp(const Eigen::Vector3d& omega) {\n  double theta_sq = omega.dot(omega);\n\n  double theta;\n  double imag_factor;\n  double real_factor;\n  if(theta_sq < 1e-10) {\n    theta = 0;\n    double theta_quad = theta_sq * theta_sq;\n    imag_factor = 0.5 - 1.0 / 48.0 * theta_sq + 1.0 / 3840.0 * theta_quad;\n    real_factor = 1.0 - 1.0 / 8.0 * theta_sq + 1.0 / 384.0 * theta_quad;\n  } else {\n    theta = std::sqrt(theta_sq);\n    double half_theta = 0.5 * theta;\n    imag_factor = std::sin(half_theta) / theta;\n    real_factor = std::cos(half_theta);\n  }\n\n  return Eigen::Quaterniond(real_factor, imag_factor * omega.x(), imag_factor * omega.y(), imag_factor * omega.z());\n}\n\n}  // namespace fast_gicp\n\n#endif", "meta": {"hexsha": "5d298aaff84e8d5e029d4b1e4c19db634f6e9723", "size": 2664, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fast_gicp/so3/so3.hpp", "max_stars_repo_name": "Gatsby23/fast_gicp", "max_stars_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "include/fast_gicp/so3/so3.hpp", "max_issues_repo_name": "Gatsby23/fast_gicp", "max_issues_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 131.0, "max_issues_repo_issues_event_min_datetime": "2019-02-18T10:56:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:07:00.000Z", "max_forks_repo_path": "include/fast_gicp/so3/so3.hpp", "max_forks_repo_name": "Gatsby23/fast_gicp", "max_forks_repo_head_hexsha": "2e9fd0b342b02b65e92142e9971f2e342f40a20a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 32.8888888889, "max_line_length": 116, "alphanum_fraction": 0.6895645646, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6166551547221627}}
{"text": "#include \"CRTP/Vectors/Euclidean3Vector.h\"\n\n#include <boost/test/unit_test.hpp>\n\nusing CRTP::Vectors::Euclidean3Vector;\n\nBOOST_AUTO_TEST_SUITE(CRTP)\nBOOST_AUTO_TEST_SUITE(Vectors)\n\nBOOST_AUTO_TEST_SUITE(Euclidean3Vectors_tests)\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(ConstructsFromInitializerList)\n{\n  Euclidean3Vector<double> x {30, 40, 50};\n\n  BOOST_TEST(true);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(AccessorsRetrieveData)\n{\n  Euclidean3Vector<double> x {30, 40, 50};\n\n  BOOST_TEST(x.x() == 30);\n  BOOST_TEST(x.y() == 40);\n  BOOST_TEST(x.z() == 50);\n}\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(DimensionRetrievesDimension)\n{\n  Euclidean3Vector<double> x;\n\n  BOOST_TEST(x.dimension() == 3);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // Euclidean3Vectors_tests\nBOOST_AUTO_TEST_SUITE_END() // Vectors\nBOOST_AUTO_TEST_SUITE_END() // CRTP", "meta": {"hexsha": "b3c37b0d1a57ff1295a2080324be97242cdd49e1", "size": 1259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Manifolds/Source/UnitTests/CRTP/Vectors/Euclidean3Vector_tests.cpp", "max_stars_repo_name": "ernestyalumni/mathphysics", "max_stars_repo_head_hexsha": "24ad9436bcb4860462cd10fe592e93ebd0ade0e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T14:24:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:19:23.000Z", "max_issues_repo_path": "Manifolds/Source/UnitTests/CRTP/Vectors/Euclidean3Vector_tests.cpp", "max_issues_repo_name": "ernestyalumni/mathphysics", "max_issues_repo_head_hexsha": "24ad9436bcb4860462cd10fe592e93ebd0ade0e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-09-29T09:29:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T03:12:29.000Z", "max_forks_repo_path": "Manifolds/Source/UnitTests/CRTP/Vectors/Euclidean3Vector_tests.cpp", "max_forks_repo_name": "ernestyalumni/mathphysics", "max_forks_repo_head_hexsha": "24ad9436bcb4860462cd10fe592e93ebd0ade0e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2018-01-21T05:33:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T20:15:13.000Z", "avg_line_length": 29.2790697674, "max_line_length": 80, "alphanum_fraction": 0.4733915806, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6166080319550351}}
{"text": "#ifndef TRIUMF_BNMR_SLR_SQ_EXP_HPP\n#define TRIUMF_BNMR_SLR_SQ_EXP_HPP\n\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n#include <triumf/bnmr/slr/common.hpp>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// \u03b2-detected nuclear magnetic resonance (\u03b2-NMR)\nnamespace bnmr {\n\n// spin-lattice relaxation (SLR)\nnamespace slr {\n\n/// pulsed square exponential integral (from 0 to time_p <= time)\ntemplate <typename T = double>\nT pulsed_sq_exp_integral(T time, T time_p, T nuclear_lifetime, T slr_rate) {\n  // make sure that\n  assert(time >= time_p);\n  // break up the expression into smaller chunks\n  T term_1 = (boost::math::constants::root_pi<T>() / (2.0 * slr_rate)) *\n             std::exp(1.0 / (4.0 * slr_rate * slr_rate * nuclear_lifetime *\n                             nuclear_lifetime));\n  T term_2 =\n      std::erf((2.0 * time * slr_rate * slr_rate * nuclear_lifetime + 1.0) /\n               (2.0 * slr_rate * nuclear_lifetime));\n  T term_3 = std::erf(\n      ((2.0 * (time - time_p)) * slr_rate * slr_rate * nuclear_lifetime + 1.0) /\n      (2.0 * slr_rate * nuclear_lifetime));\n  return term_1 * (term_2 - term_3);\n}\n\n/// pulsed square exponential\ntemplate <typename T = double>\nT pulsed_sq_exp(T time, T nuclear_lifetime, T pulse_length, T asymmetry,\n                T slr_rate) {\n  if (time == 0.0) {\n    return asymmetry;\n  } else if (time > 0.0 and time <= pulse_length) {\n    return asymmetry *\n           pulsed_sq_exp_integral(time, time, nuclear_lifetime, slr_rate) /\n           normalization(time, nuclear_lifetime);\n  } else if (time > pulse_length) {\n    return (asymmetry *\n            pulsed_sq_exp_integral(time, pulse_length, nuclear_lifetime,\n                                   slr_rate) /\n            normalization(pulse_length, nuclear_lifetime)) /\n           std::exp(-(time - pulse_length) / nuclear_lifetime);\n  } else {\n    return 0.0;\n  }\n}\n\n/// pulsed square exponential (ROOT)\ntemplate <typename T = double> T pulsed_sq_exp(const T *x, const T *par) {\n  return pulsed_sq_exp<T>(*x, par[0], par[1], par[2], par[3]);\n}\n\n} // namespace slr\n\n} // namespace bnmr\n\n} // namespace triumf\n\n#endif // TRIUMF_BNMR_SLR_SQ_EXP_HPP", "meta": {"hexsha": "c59469a40d9d96551b54eacf21b50d8d6aab15a7", "size": 2181, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/bnmr/slr/sq_exp.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/triumf/bnmr/slr/sq_exp.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/triumf/bnmr/slr/sq_exp.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.552238806, "max_line_length": 80, "alphanum_fraction": 0.648784961, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.6757645879592642, "lm_q1q2_score": 0.6165920411966467}}
{"text": "#include <boost/mpl/vector_c.hpp>\n#include <boost/mpl/integral_c.hpp>\n#include <boost/mpl/find.hpp>\n#include <boost/mpl/size.hpp>\n#include <boost/mpl/less.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/mpl/int.hpp>\n\nusing namespace boost::mpl;\n\ntemplate <typename Sequence, typename Value>\nstruct index_of\n{\n\tusing it = typename find<Sequence, Value>::type;\n\tusing index = typename it::pos;\n\tusing size = typename size<Sequence>::type;\n\tusing index_smaller_than_size = typename less<index, size>::type;\n\tusing type = typename if_<index_smaller_than_size, index, int_<-1>>::type;\n};\n\nint main()\n{\n\tusing v = vector_c<int, 5, 2, 3, 1, 4>;\n\n\tconstexpr int r1 = index_of<v, integral_c<int, 3>>::type::value;\n\tstatic_assert(r1 == 2);\n\n\tconstexpr int r2 = index_of<v, integral_c<int, 6>>::type::value;\n\tstatic_assert(r2 == -1);\n}\n", "meta": {"hexsha": "01be9b28e9a705b03aafdde306d142796baae348", "size": 826, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "05_mpl_with_values/main.cpp", "max_stars_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_stars_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "05_mpl_with_values/main.cpp", "max_issues_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_issues_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "05_mpl_with_values/main.cpp", "max_forks_repo_name": "BorisSchaeling/boost-meta-programming-2020", "max_forks_repo_head_hexsha": "1bb70e88070953daa4bc19f91f891b43583df06e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6451612903, "max_line_length": 75, "alphanum_fraction": 0.7130750605, "num_tokens": 231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6165700998110197}}
{"text": "#include \"ts.h\"\n#include <Eigen/Geometry>\n#include <cmath>\n\nusing namespace std;\n\nvector<double> ts_to_quat(vector<double> ts)\n{\n    Eigen::Quaterniond rTwist(Eigen::AngleAxisd(ts[1], Eigen::Vector3d::UnitY()));\n    Eigen::Vector3d swingVec(ts[0], 0, ts[2]);\n    Eigen::Quaterniond rSwing(Eigen::AngleAxisd(swingVec.norm(), swingVec.normalized()));\n    Eigen::Quaterniond r = rSwing * rTwist;\n    r.normalize();\n    if (r.w() < 0) { r.w() = -r.w(); r.x() = -r.x(); r.y() = -r.y(); r.z() = -r.z(); }\n    return { r.w(), r.x(), r.y(), r.z() };\n}\n\nvector<double> quat_to_ts(vector<double> quat)\n{\n    Eigen::Quaterniond r(quat[0], quat[1], quat[2], quat[3]);\n    \n    r.normalize();\n    if (r.w() < 0) { r.w() = -r.w(); r.x() = -r.x(); r.y() = -r.y(); r.z() = -r.z(); }\n\n    Eigen::Quaterniond rTwist(1, 0, 0, 0);\n    if (abs(r.y()) > 1e-6) rTwist = Eigen::Quaterniond(r.w(), 0, r.y(), 0);\n    \n    rTwist.normalize();\n\n    Eigen::Quaterniond rSwing = r * rTwist.conjugate();\n\n    Eigen::AngleAxisd axTwist(rTwist);\n    Eigen::AngleAxisd axSwing(rSwing);\n\n    return { \n        axSwing.angle() * axSwing.axis()[0],\n        axTwist.angle() * axTwist.axis()[1],\n        axSwing.angle() * axSwing.axis()[2]\n    };\n}\n", "meta": {"hexsha": "eeed9223e16d2b25e2b27f1957e53684c453b59b", "size": 1210, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kinematic/utils/ts.cpp", "max_stars_repo_name": "arpspoof/Jump", "max_stars_repo_head_hexsha": "1c9c1bd5c499e24bab25eb7decaa772b60798794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2021-04-25T03:36:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T00:23:59.000Z", "max_issues_repo_path": "Kinematic/utils/ts.cpp", "max_issues_repo_name": "squalidux/Jump", "max_issues_repo_head_hexsha": "1c9c1bd5c499e24bab25eb7decaa772b60798794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-05-25T10:04:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T01:54:00.000Z", "max_forks_repo_path": "Kinematic/utils/ts.cpp", "max_forks_repo_name": "squalidux/Jump", "max_forks_repo_head_hexsha": "1c9c1bd5c499e24bab25eb7decaa772b60798794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-04-25T03:05:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T19:58:01.000Z", "avg_line_length": 29.512195122, "max_line_length": 89, "alphanum_fraction": 0.5611570248, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6165648941101556}}
{"text": "\n//\n// Copyright (c) 2012 Ronaldo Carpio\n//\n// Permission to use, copy, modify, distribute and sell this software\n// and its documentation for any purpose is hereby granted without fee,\n// provided that the above copyright notice appear in all copies and\n// that both that copyright notice and this permission notice appear\n// in supporting documentation.  The authors make no representations\n// about the suitability of this software for any purpose.\n// It is provided \"as is\" without express or implied warranty.\n//\n\n/*\nThis is a C++ header-only library for N-dimensional linear interpolation on a rectangular grid. Implements two methods:\n* Multilinear: Interpolate using the N-dimensional hypercube containing the point. Interpolation step is O(2^N)\n* Simplicial: Interpolate using the N-dimensional simplex containing the point. Interpolation step is O(N log N), but less accurate.\nRequires boost/multi_array library.\n\nFor a description of the algorithms, see:\n* Weiser & Zarantonello (1988), \"A Note on Piecewise Linear and Multilinear Table Interpolation in Many Dimensions\", _Mathematics of Computation_ 50 (181), p. 189-196\n* Davies (1996), \"Multidimensional Triangulation and Interpolation for Reinforcement Learning\", _Proceedings of Neural Information Processing Systems 1996_\n*/\n\n// Orgiginal file from linterp library: github.com/rncarpio/linterp/blob/master/src/linterp.h\n// Modified by Sergey Poluyan\n// There are no significant changes. Everything except linear interpolation was removed. Some code simplification was done.\n\n// Usage:\n//    std::vector<double> f_values = {0.5, 1.0, 0.75};\n//    std::vector<std::vector<double>> grids = { {1, 2, 3} };\n//    boost::array<int, 1> grid_sizes = { 3 };\n//    auto grid_iter_list = linterp::get_begins_ends( grids.begin(), grids.end() );\n//    auto obj = linterp::InterpMultilinear<1, double>(grid_iter_list.first.begin(), grid_sizes.begin(), f_values.data(), f_values.data() + f_values.size() );\n//    boost::array<double, 1> args = { 1.25 };\n//    std::cout << obj.interp( args.begin() ) << std::endl;\n\n#ifndef linterp_hh\n#define linterp_hh\n\n#include <vector>\n#include <array>\n\n#include <boost/multi_array.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nnamespace linterp\n{\n\n\tstruct EmptyClass {};\n\n\ttemplate <int N, class T, bool CopyData = true, bool Continuous = true, class ArrayRefCountT = EmptyClass, class GridRefCountT = EmptyClass>\n\tclass NDInterpolator\n\t{\n\tpublic:\n\t\ttypedef T value_type;\n\t\ttypedef ArrayRefCountT array_ref_count_type;\n\t\ttypedef GridRefCountT grid_ref_count_type;\n\n\t\tNDInterpolator() {}\n\n\t\tstatic const int m_N = N;\n\t\tstatic const bool m_bCopyData = CopyData;\n\t\tstatic const bool m_bContinuous = Continuous;\n\n\t\ttypedef boost::numeric::ublas::array_adaptor<T> grid_type;\n\t\ttypedef boost::const_multi_array_ref<T, N> array_type;\n\t\ttypedef std::unique_ptr<array_type> array_type_ptr;\n\n\t\tarray_type_ptr m_pF;\n\t\tArrayRefCountT m_ref_F;\t\t\t\t\t// reference count for m_pF\n\t\tstd::vector<T> m_F_copy;\t\t\t\t\t\t// if CopyData == true, this holds the copy of F\n\n\t\tstd::vector<grid_type> m_grid_list;\n\t\tstd::vector<GridRefCountT> m_grid_ref_list;\t// reference counts for grids\n\t\tstd::vector<std::vector<T> > m_grid_copy_list;  \t// if CopyData == true, this holds the copies of the grids\n\n\t\t// constructors assume that [f_begin, f_end) is a contiguous array in C-order\n\t\t// non ref-counted constructor.\n\t\ttemplate <class IterT1, class IterT2, class IterT3>\n\t\tNDInterpolator(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin, IterT3 f_end)\n\t\t{\n\t\t\tinit(grids_begin, grids_len_begin, f_begin, f_end);\n\t\t}\n\n\t\t// ref-counted constructor\n\t\ttemplate <class IterT1, class IterT2, class IterT3, class RefCountIterT>\n\t\tNDInterpolator(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin, IterT3 f_end, ArrayRefCountT &refF, RefCountIterT grid_refs_begin)\n\t\t{\n\t\t\tinit_refcount(grids_begin, grids_len_begin, f_begin, f_end, refF, grid_refs_begin);\n\t\t}\n\n\t\ttemplate <class IterT1, class IterT2, class IterT3>\n\t\tvoid init(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin, IterT3 f_end)\n\t\t{\n\t\t\tset_grids(grids_begin, grids_len_begin, m_bCopyData);\n\t\t\tset_f_array(f_begin, f_end, m_bCopyData);\n\t\t}\n\t\ttemplate <class IterT1, class IterT2, class IterT3, class RefCountIterT>\n\t\tvoid init_refcount(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin, IterT3 f_end, ArrayRefCountT &refF, RefCountIterT grid_refs_begin)\n\t\t{\n\t\t\tset_grids(grids_begin, grids_len_begin, m_bCopyData);\n\t\t\tset_grids_refcount(grid_refs_begin, grid_refs_begin + N);\n\t\t\tset_f_array(f_begin, f_end, m_bCopyData);\n\t\t\tset_f_refcount(refF);\n\t\t}\n\n\t\ttemplate <class IterT1, class IterT2>\n\t\tvoid set_grids(IterT1 grids_begin, IterT2 grids_len_begin, bool bCopy)\n\t\t{\n\t\t\tm_grid_list.clear();\n\t\t\tm_grid_ref_list.clear();\n\t\t\tm_grid_copy_list.clear();\n\t\t\tfor(int i=0; i<N; i++)\n\t\t\t{\n\t\t\t\tint gridLength = grids_len_begin[i];\n\t\t\t\tif(bCopy == false)\n\t\t\t\t{\n\t\t\t\t\tT const *grid_ptr = &(*grids_begin[i]);\n\t\t\t\t\tm_grid_list.push_back(grid_type(gridLength, (T*) grid_ptr));\t  \t\t\t\t// use the given pointer\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_grid_copy_list.push_back(std::vector<T>(grids_begin[i], grids_begin[i] + grids_len_begin[i]));\t// make our own copy of the grid\n\t\t\t\t\tT *begin = &(m_grid_copy_list[i][0]);\n\t\t\t\t\tm_grid_list.push_back(grid_type(gridLength, begin));\t\t\t\t\t\t\t// use our copy\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttemplate <class IterT1, class RefCountIterT>\n\t\tvoid set_grids_refcount(RefCountIterT refs_begin, RefCountIterT refs_end)\n\t\t{\n\t\t\tassert(refs_end - refs_begin == N);\n\t\t\tm_grid_ref_list.assign(refs_begin, refs_begin + N);\n\t\t}\n\n\t\t// assumes that [f_begin, f_end) is a contiguous array in C-order\n\t\ttemplate <class IterT>\n\t\tvoid set_f_array(IterT f_begin, IterT f_end, bool bCopy)\n\t\t{\n\t\t\tunsigned int nGridPoints = 1;\n\t\t\tstd::array<int,N> sizes;\n\t\t\tfor(unsigned int i=0; i<m_grid_list.size(); i++)\n\t\t\t{\n\t\t\t\tsizes[i] = m_grid_list[i].size();\n\t\t\t\tnGridPoints *= sizes[i];\n\t\t\t}\n\n\t\t\tint f_len = f_end - f_begin;\n\t\t\tif((m_bContinuous && f_len != static_cast<int>(nGridPoints)) || (!m_bContinuous && f_len != 2 * static_cast<int>(nGridPoints)))\n\t\t\t{\n\t\t\t\tthrow std::invalid_argument(\"f has wrong size\");\n\t\t\t}\n\t\t\tfor(unsigned int i=0; i<m_grid_list.size(); i++)\n\t\t\t{\n\t\t\t\tif(!m_bContinuous)\n\t\t\t\t{\n\t\t\t\t\tsizes[i] *= 2;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm_F_copy.clear();\n\t\t\tif(bCopy == false)\n\t\t\t{\n\t\t\t\tm_pF.reset(new array_type(f_begin, sizes));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_F_copy = std::vector<T>(f_begin, f_end);\n\t\t\t\tm_pF.reset(new array_type(&m_F_copy[0], sizes));\n\t\t\t}\n\t\t}\n\t\tvoid set_f_refcount(ArrayRefCountT &refF)\n\t\t{\n\t\t\tm_ref_F = refF;\n\t\t}\n\n\t\t// -1 is before the first grid point\n\t\t// N-1 (where grid.size() == N) is after the last grid point\n\t\tint find_cell(int dim, T x) const\n\t\t{\n\t\t\tgrid_type const &grid(m_grid_list[dim]);\n\t\t\tif(x < *(grid.begin())) return -1;\n\t\t\telse if(x >= *(grid.end()-1)) return grid.size()-1;\n\t\t\telse\n\t\t\t{\n\t\t\t\tauto i_upper = std::upper_bound(grid.begin(), grid.end(), x);\n\t\t\t\treturn i_upper - grid.begin() - 1;\n\t\t\t}\n\t\t}\n\n\t\t// return the value of f at the given cell and vertex\n\t\tT get_f_val(std::array<int,N> const &cell_index, std::array<int,N> const &v_index) const\n\t\t{\n\t\t\tstd::array<int,N> f_index;\n\n\t\t\tif(m_bContinuous)\n\t\t\t{\n\t\t\t\tfor(int i=0; i<N; i++)\n\t\t\t\t{\n\t\t\t\t\tif(cell_index[i] < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tf_index[i] = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse if(cell_index[i] >= static_cast<int>(m_grid_list[i].size()-1))\n\t\t\t\t\t{\n\t\t\t\t\t\tf_index[i] = m_grid_list[i].size()-1;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tf_index[i] = cell_index[i] + v_index[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor(int i=0; i<N; i++)\n\t\t\t\t{\n\t\t\t\t\tif(cell_index[i] < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tf_index[i] = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse if(cell_index[i] >= static_cast<int>(m_grid_list[i].size()-1))\n\t\t\t\t\t{\n\t\t\t\t\t\tf_index[i] = (2*m_grid_list[i].size())-1;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tf_index[i] = 1 + (2*cell_index[i]) + v_index[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn (*m_pF)(f_index);\n\t\t}\n\n\t\tT get_f_val(std::array<int,N> const &cell_index, int v) const\n\t\t{\n\t\t\tstd::array<int,N> v_index;\n\t\t\tfor(int dim=0; dim<N; dim++)\n\t\t\t{\n\t\t\t\tv_index[dim] = (v >> (N-dim-1)) & 1;\t\t\t\t\t\t// test if the i-th bit is set\n\t\t\t}\n\t\t\treturn get_f_val(cell_index, v_index);\n\t\t}\n\t};\n\n\n\ttemplate <int N, class T, bool CopyData = true, bool Continuous = true, class ArrayRefCountT = EmptyClass, class GridRefCountT = EmptyClass>\n\tclass InterpMultilinear : public NDInterpolator<N,T,CopyData,Continuous,ArrayRefCountT,GridRefCountT>\n\t{\n\tpublic:\n\t\ttypedef NDInterpolator<N,T,CopyData,Continuous,ArrayRefCountT,GridRefCountT> super;\n\n\t\tInterpMultilinear() {}\n\n\t\ttemplate <class IterT1, class IterT2, class IterT3>\n\t\tInterpMultilinear(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin, IterT3 f_end)\n\t\t\t: super(grids_begin, grids_len_begin, f_begin, f_end)\n\t\t{}\n\t\ttemplate <class IterT1, class IterT2, class IterT3, class RefCountIterT>\n\t\tInterpMultilinear(IterT1 grids_begin, IterT2 grids_len_begin, IterT3 f_begin, IterT3 f_end, ArrayRefCountT &refF, RefCountIterT ref_begins)\n\t\t\t: super(grids_begin, grids_len_begin, f_begin, f_end, refF, ref_begins)\n\t\t{}\n\n\t\ttemplate <class IterT1, class IterT2>\n\t\tstatic T linterp_nd_unitcube(IterT1 f_begin, IterT1 f_end, IterT2 xi_begin, IterT2 xi_end)\n\t\t{\n\t\t\tint n = xi_end - xi_begin;\n\t\t\tint f_len = f_end - f_begin;\n\t\t\tassert(1 << n == f_len);\n\t\t\tT sub_lower, sub_upper;\n\t\t\tif(n == 1)\n\t\t\t{\n\t\t\t\tsub_lower = f_begin[0];\n\t\t\t\tsub_upper = f_begin[1];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsub_lower = linterp_nd_unitcube(f_begin, f_begin + (f_len/2), xi_begin + 1, xi_end);\n\t\t\t\tsub_upper = linterp_nd_unitcube(f_begin + (f_len/2), f_end, xi_begin + 1, xi_end);\n\t\t\t}\n\t\t\tT result = sub_lower + (*xi_begin)*(sub_upper - sub_lower);\n\t\t\treturn result;\n\t\t}\n\n\t\ttemplate <class IterT>\n\t\tT interp(IterT x_begin) const\n\t\t{\n\t\t\tstd::array<T,1> result;\n\t\t\tstd::array< std::array<T,1>, N > coord_iter;\n\t\t\tfor(int i=0; i<N; i++)\n\t\t\t{\n\t\t\t\tcoord_iter[i][0] = x_begin[i];\n\t\t\t}\n\t\t\tinterp_vec(1, coord_iter.begin(), coord_iter.end(), result.begin());\n\t\t\treturn result[0];\n\t\t}\n\n\t\ttemplate <class IterT1, class IterT2>\n\t\tvoid interp_vec(int n, IterT1 coord_iter_begin, IterT1 coord_iter_end, IterT2 i_result) const\n\t\t{\n\t\t\tassert(N == coord_iter_end - coord_iter_begin);\n\t\t\tstd::array<int,N> index;\n\t\t\tint c;\n\t\t\tT y;\n\t\t\tstd::vector<T> f(1 << N);\n\t\t\tstd::array<T,N> x;\n\n\t\t\tfor(int i=0; i<n; i++)  \t\t\t\t\t\t\t\t// loop over each point\n\t\t\t{\n\t\t\t\tfor(int dim=0; dim<N; dim++)  \t\t\t\t\t\t// loop over each dimension\n\t\t\t\t{\n\t\t\t\t\tauto const &grid(super::m_grid_list[dim]);\n\n\t\t\t\t\tc = this->find_cell(dim, coord_iter_begin[dim][i]);\n\t\t\t\t\tif(c == -1)  \t\t\t\t\t// before first grid point\n\t\t\t\t\t{\n\t\t\t\t\t\ty = 1.0;\n\t\t\t\t\t}\n\t\t\t\t\telse if(c == static_cast<int>(grid.size()-1))  \t// after last grid point\n\t\t\t\t\t{\n\t\t\t\t\t\ty = 0.0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\ty = (coord_iter_begin[dim][i] - grid[c]) / (grid[c + 1] - grid[c]);\n\t\t\t\t\t\tif(y < 0.0) y=0.0;\n\t\t\t\t\t\telse if(y > 1.0) y=1.0;\n\t\t\t\t\t}\n\t\t\t\t\tindex[dim] = c;\n\t\t\t\t\tx[dim] = y;\n\t\t\t\t}\n\t\t\t\t// copy f values at vertices\n\t\t\t\tfor(int v=0; v < (1 << N); v++)  \t\t\t\t\t// loop over each vertex of hypercube\n\t\t\t\t{\n\t\t\t\t\tf[v] = this->get_f_val(index, v);\n\t\t\t\t}\n\t\t\t\t*i_result++ = linterp_nd_unitcube(f.begin(), f.end(), x.begin(), x.end());\n\t\t\t}\n\t\t}\n\t};\n\n\ttemplate <class IterT>\n\tstd::pair<std::vector<typename IterT::value_type::const_iterator>, std::vector<typename IterT::value_type::const_iterator> > get_begins_ends(IterT iters_begin, IterT iters_end)\n\t{\n\t\ttypedef typename IterT::value_type T;\n\t\ttypedef std::vector<typename T::const_iterator> VecT;\n\t\tint N = iters_end - iters_begin;\n\t\tstd::pair<VecT, VecT> result;\n\t\tresult.first.resize(N);\n\t\tresult.second.resize(N);\n\t\tfor(int i=0; i<N; i++)\n\t\t{\n\t\t\tresult.first[i] = iters_begin[i].begin();\n\t\t\tresult.second[i] = iters_begin[i].end();\n\t\t}\n\t\treturn result;\n\t}\n\n}\n\n#endif //_linterp_h\n", "meta": {"hexsha": "8ad0a0e34d3e1a6a864cfd1c97fcf1d3a543f1ba", "size": 11662, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/linterp.hh", "max_stars_repo_name": "poluyan/PEPSGO", "max_stars_repo_head_hexsha": "d1039bf0362bddca6247ffadf7b2124e6cfb64cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-07T16:07:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-07T16:07:04.000Z", "max_issues_repo_path": "src/linterp.hh", "max_issues_repo_name": "poluyan/PEPSGO", "max_issues_repo_head_hexsha": "d1039bf0362bddca6247ffadf7b2124e6cfb64cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/linterp.hh", "max_forks_repo_name": "poluyan/PEPSGO", "max_forks_repo_head_hexsha": "d1039bf0362bddca6247ffadf7b2124e6cfb64cf", "max_forks_repo_licenses": ["Apache-2.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.1267217631, "max_line_length": 177, "alphanum_fraction": 0.6722689076, "num_tokens": 3571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6164913134278156}}
{"text": "//  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// Copyright Paul A. Bristow 2013\n// Copyright Christopher Kormanyos 2013.\n// Copyright John Maddock 2013.\n\n#ifdef _MSC_VER\n#  pragma warning (disable : 4512)\n#  pragma warning (disable : 4996)\n#endif\n\n#define BOOST_TEST_MAIN\n#define BOOST_LIB_DIAGNOSTIC \"on\"// Show library file details.\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp> // Extra test tool for FP comparison.\n\n#include <iostream>\n#include <limits>\n\n//[expression_template_1\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n/*`To define a 50 decimal digit type using `cpp_dec_float`,\nyou must pass two template parameters to `boost::multiprecision::number`.\n\nIt may be more legible to use a two-staged type definition such as this:\n\n``\ntypedef boost::multiprecision::cpp_dec_float<50> mp_backend;\ntypedef boost::multiprecision::number<mp_backend, boost::multiprecision::et_off> cpp_dec_float_50_noet;\n``\n\nHere, we first define `mp_backend` as `cpp_dec_float` with 50 digits.\nThe second step passes this backend to `boost::multiprecision::number`\nwith `boost::multiprecision::et_off`, an enumerated type.\n\n  typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<50>, boost::multiprecision::et_off>\n  cpp_dec_float_50_noet;\n\nYou can reduce typing with a `using` directive `using namespace boost::multiprecision;`\nif desired, as shown below.\n*/\n\nusing namespace boost::multiprecision;\n\n\n/*`Now `cpp_dec_float_50_noet` or `cpp_dec_float_50_et`\ncan be used as a direct replacement for built-in types like `double` etc.\n*/\n\nBOOST_AUTO_TEST_CASE(cpp_float_test_check_close_noet)\n{ // No expression templates/\n  typedef number<cpp_dec_float<50>, et_off> cpp_dec_float_50_noet;\n\n  std::cout.precision(std::numeric_limits<cpp_dec_float_50_noet>::digits10); // All significant digits.\n  std::cout << std::showpoint << std::endl; // Show trailing zeros.\n\n  cpp_dec_float_50_noet a (\"1.0\");\n  cpp_dec_float_50_noet b (\"1.0\");\n  b += std::numeric_limits<cpp_dec_float_50_noet>::epsilon(); // Increment least significant decimal digit.\n\n  cpp_dec_float_50_noet eps = std::numeric_limits<cpp_dec_float_50_noet>::epsilon();\n\n  std::cout <<\"a = \" << a << \",\\nb = \" << b << \",\\neps = \" << eps << std::endl;\n\n  BOOST_CHECK_CLOSE(a, b, eps * 100); // Expected to pass (because tolerance is as percent).\n  BOOST_CHECK_CLOSE_FRACTION(a, b, eps); // Expected to pass (because tolerance is as fraction).\n\n\n\n} // BOOST_AUTO_TEST_CASE(cpp_float_test_check_close)\n\nBOOST_AUTO_TEST_CASE(cpp_float_test_check_close_et)\n{ // Using expression templates.\n  typedef number<cpp_dec_float<50>, et_on> cpp_dec_float_50_et;\n\n  std::cout.precision(std::numeric_limits<cpp_dec_float_50_et>::digits10); // All significant digits.\n  std::cout << std::showpoint << std::endl; // Show trailing zeros.\n\n  cpp_dec_float_50_et a(\"1.0\");\n  cpp_dec_float_50_et b(\"1.0\");\n  b += std::numeric_limits<cpp_dec_float_50_et>::epsilon(); // Increment least significant decimal digit.\n\n  cpp_dec_float_50_et eps = std::numeric_limits<cpp_dec_float_50_et>::epsilon();\n\n  std::cout << \"a = \" << a << \",\\nb = \" << b << \",\\neps = \" << eps << std::endl;\n\n  BOOST_CHECK_CLOSE(a, b, eps * 100); // Expected to pass (because tolerance is as percent).\n  BOOST_CHECK_CLOSE_FRACTION(a, b, eps); // Expected to pass (because tolerance is as fraction).\n\n  /*`Using `cpp_dec_float_50` with the default expression template use switched on,\n  the compiler error message for `BOOST_CHECK_CLOSE_FRACTION(a, b, eps); would be:\n  */\n  // failure floating_point_comparison.hpp(59): error C2440: 'static_cast' :\n  // cannot convert from 'int' to 'boost::multiprecision::detail::expression<tag,Arg1,Arg2,Arg3,Arg4>'\n//] [/expression_template_1]\n\n} // BOOST_AUTO_TEST_CASE(cpp_float_test_check_close)\n\n/*\n\nOutput:\n\n  Description: Autorun \"J:\\Cpp\\big_number\\Debug\\test_cpp_float_close_fraction.exe\"\n  Running 1 test case...\n\n  a = 1.0000000000000000000000000000000000000000000000000,\n  b = 1.0000000000000000000000000000000000000000000000001,\n  eps = 1.0000000000000000000000000000000000000000000000000e-49\n\n  *** No errors detected\n\n\n*/\n\n", "meta": {"hexsha": "b4699fad87bd94ecee9671d3225e451fd00693aa", "size": 4285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/test_cpp_float_close_fraction.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/example/test_cpp_float_close_fraction.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/example/test_cpp_float_close_fraction.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": 35.7083333333, "max_line_length": 112, "alphanum_fraction": 0.7502917153, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789040926008, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6164912985841399}}
{"text": "//  Copyright 2006 John Maddock\r\n// Copyright Paul A. Bristow 2007.\r\n\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <pch.hpp>\r\n\r\n#include <boost/math/concepts/real_concept.hpp>\r\n#include <boost/test/test_exec_monitor.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n#include <boost/math/special_functions/ellint_rf.hpp>\r\n#include <boost/math/special_functions/ellint_rc.hpp>\r\n#include <boost/math/special_functions/ellint_rj.hpp>\r\n#include <boost/math/special_functions/ellint_rd.hpp>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/array.hpp>\r\n#include <boost/tr1/random.hpp>\r\n#include \"functor.hpp\"\r\n\r\n#include \"handle_test_result.hpp\"\r\n//\r\n// DESCRIPTION:\r\n// ~~~~~~~~~~~~\r\n//\r\n// This file tests the Carlson Elliptic Integrals.  \r\n// There are two sets of tests, spot\r\n// tests which compare our results with the published test values, \r\n// in Numerical Computation of Real or Complex Elliptic Integrals,\r\n// B. C. Carlson: http://arxiv.org/abs/math.CA/9409227\r\n// However, the bulk of the accuracy tests\r\n// use values generated with NTL::RR at 1000-bit precision\r\n// and our generic versions of these functions.\r\n//\r\n// Note that when this file is first run on a new platform many of\r\n// these tests will fail: the default accuracy is 1 epsilon which\r\n// is too tight for most platforms.  In this situation you will \r\n// need to cast a human eye over the error rates reported and make\r\n// a judgement as to whether they are acceptable.  Either way please\r\n// report the results to the Boost mailing list.  Acceptable rates of\r\n// error are marked up below as a series of regular expressions that\r\n// identify the compiler/stdlib/platform/data-type/test-data/test-function\r\n// along with the maximum expected peek and RMS mean errors for that\r\n// test.\r\n//\r\n\r\nvoid expected_results()\r\n{\r\n   //\r\n   // Define the max and mean errors expected for\r\n   // various compilers and platforms.\r\n   //\r\n   const char* largest_type;\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n   if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())\r\n   {\r\n      largest_type = \"(long\\\\s+)?double\";\r\n   }\r\n   else\r\n   {\r\n      largest_type = \"long double\";\r\n   }\r\n#else\r\n   largest_type = \"(long\\\\s+)?double\";\r\n#endif\r\n   //\r\n   // real long doubles:\r\n   //\r\n   if(boost::math::policies::digits<long double, boost::math::policies::policy<> >() > 53)\r\n   {\r\n      add_expected_result(\r\n         \".*\",                          // compiler\r\n         \".*\",                          // stdlib\r\n         BOOST_PLATFORM,                          // platform\r\n         largest_type,                  // test type(s)\r\n         \".*RJ.*\",      // test data group\r\n         \".*\", 1000, 50);  // test function\r\n      add_expected_result(\r\n         \".*\",                          // compiler\r\n         \".*\",                          // stdlib\r\n         BOOST_PLATFORM,                          // platform\r\n         \"real_concept\",                  // test type(s)\r\n         \".*RJ.*\",      // test data group\r\n         \".*\", 1000, 50);  // test function\r\n   }\r\n   //\r\n   // Catch all cases come last:\r\n   //\r\n   add_expected_result(\r\n      \".*\",                          // compiler\r\n      \".*\",                          // stdlib\r\n      \".*\",                          // platform\r\n      largest_type,                  // test type(s)\r\n      \".*RJ.*\",      // test data group\r\n      \".*\", 180, 50);  // test function\r\n   add_expected_result(\r\n      \".*\",                          // compiler\r\n      \".*\",                          // stdlib\r\n      \".*\",                          // platform\r\n      \"real_concept\",                  // test type(s)\r\n      \".*RJ.*\",      // test data group\r\n      \".*\", 180, 50);  // test function\r\n   add_expected_result(\r\n      \".*\",                          // compiler\r\n      \".*\",                          // stdlib\r\n      \".*\",                          // platform\r\n      largest_type,                  // test type(s)\r\n      \".*\",      // test data group\r\n      \".*\", 15, 8);  // test function\r\n   add_expected_result(\r\n      \".*\",                          // compiler\r\n      \".*\",                          // stdlib\r\n      \".*\",                          // platform\r\n      \"real_concept\",                  // test type(s)\r\n      \".*\",      // test data group\r\n      \".*\", 15, 8);  // test function\r\n   //\r\n   // Finish off by printing out the compiler/stdlib/platform names,\r\n   // we do this to make it easier to mark up expected error rates.\r\n   //\r\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \" \r\n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\r\n}\r\n\r\ntemplate <typename T>\r\nvoid do_test_ellint_rf(T& data, const char* type_name, const char* test)\r\n{\r\n   typedef typename T::value_type row_type;\r\n   typedef typename row_type::value_type value_type;\r\n\r\n   std::cout << \"Testing: \" << test << std::endl;\r\n\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n    value_type (*fp)(value_type, value_type, value_type) = boost::math::ellint_rf<value_type, value_type, value_type>;\r\n#else\r\n    value_type (*fp)(value_type, value_type, value_type) = boost::math::ellint_rf;\r\n#endif\r\n    boost::math::tools::test_result<value_type> result;\r\n \r\n    result = boost::math::tools::test(\r\n      data, \r\n      bind_func(fp, 0, 1, 2),\r\n      extract_result(3));\r\n   handle_test_result(result, data[result.worst()], result.worst(), \r\n      type_name, \"boost::math::ellint_rf\", test);\r\n\r\n   std::cout << std::endl;\r\n\r\n}\r\n\r\ntemplate <typename T>\r\nvoid do_test_ellint_rc(T& data, const char* type_name, const char* test)\r\n{\r\n   typedef typename T::value_type row_type;\r\n   typedef typename row_type::value_type value_type;\r\n\r\n   std::cout << \"Testing: \" << test << std::endl;\r\n\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n    value_type (*fp)(value_type, value_type) = boost::math::ellint_rc<value_type, value_type>;\r\n#else\r\n    value_type (*fp)(value_type, value_type) = boost::math::ellint_rc;\r\n#endif\r\n    boost::math::tools::test_result<value_type> result;\r\n \r\n    result = boost::math::tools::test(\r\n      data, \r\n      bind_func(fp, 0, 1),\r\n      extract_result(2));\r\n   handle_test_result(result, data[result.worst()], result.worst(), \r\n      type_name, \"boost::math::ellint_rc\", test);\r\n\r\n   std::cout << std::endl;\r\n\r\n}\r\n\r\ntemplate <typename T>\r\nvoid do_test_ellint_rj(T& data, const char* type_name, const char* test)\r\n{\r\n   typedef typename T::value_type row_type;\r\n   typedef typename row_type::value_type value_type;\r\n\r\n   std::cout << \"Testing: \" << test << std::endl;\r\n\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n    value_type (*fp)(value_type, value_type, value_type, value_type) = boost::math::ellint_rj<value_type, value_type, value_type, value_type>;\r\n#else\r\n    value_type (*fp)(value_type, value_type, value_type, value_type) = boost::math::ellint_rj;\r\n#endif\r\n    boost::math::tools::test_result<value_type> result;\r\n \r\n    result = boost::math::tools::test(\r\n      data, \r\n      bind_func(fp, 0, 1, 2, 3),\r\n      extract_result(4));\r\n   handle_test_result(result, data[result.worst()], result.worst(), \r\n      type_name, \"boost::math::ellint_rf\", test);\r\n\r\n   std::cout << std::endl;\r\n\r\n}\r\n\r\ntemplate <typename T>\r\nvoid do_test_ellint_rd(T& data, const char* type_name, const char* test)\r\n{\r\n   typedef typename T::value_type row_type;\r\n   typedef typename row_type::value_type value_type;\r\n\r\n   std::cout << \"Testing: \" << test << std::endl;\r\n\r\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\r\n    value_type (*fp)(value_type, value_type, value_type) = boost::math::ellint_rd<value_type, value_type, value_type>;\r\n#else\r\n    value_type (*fp)(value_type, value_type, value_type) = boost::math::ellint_rd;\r\n#endif\r\n    boost::math::tools::test_result<value_type> result;\r\n \r\n    result = boost::math::tools::test(\r\n      data, \r\n      bind_func(fp, 0, 1, 2),\r\n      extract_result(3));\r\n   handle_test_result(result, data[result.worst()], result.worst(), \r\n      type_name, \"boost::math::ellint_rd\", test);\r\n\r\n   std::cout << std::endl;\r\n\r\n}\r\n\r\ntemplate <typename T>\r\nvoid test_spots(T, const char* type_name)\r\n{\r\n   using namespace boost::math;\r\n   using namespace std;\r\n   // Spot values from Numerical Computation of Real or Complex \r\n   // Elliptic Integrals, B. C. Carlson: http://arxiv.org/abs/math.CA/9409227\r\n   // RF:\r\n   T tolerance = (std::max)(T(1e-13f), tools::epsilon<T>() * 5) * 100; // Note 5eps expressed as a persentage!!!\r\n   T eps2 = 2 * tools::epsilon<T>();\r\n   BOOST_CHECK_CLOSE(ellint_rf(T(1), T(2), T(0)), T(1.3110287771461), tolerance);\r\n   BOOST_CHECK_CLOSE(ellint_rf(T(0.5), T(1), T(0)), T(1.8540746773014), tolerance);\r\n   BOOST_CHECK_CLOSE(ellint_rf(T(2), T(3), T(4)), T(0.58408284167715), tolerance);\r\n   // RC:\r\n   BOOST_CHECK_CLOSE_FRACTION(ellint_rc(T(0), T(1)/4), boost::math::constants::pi<T>(), eps2);\r\n   BOOST_CHECK_CLOSE_FRACTION(ellint_rc(T(9)/4, T(2)), log(T(2)), eps2);\r\n   BOOST_CHECK_CLOSE_FRACTION(ellint_rc(T(1)/4, T(-2)), log(T(2))/3, eps2);\r\n   // RJ:\r\n   BOOST_CHECK_CLOSE(ellint_rj(T(0), T(1), T(2), T(3)), T(0.77688623778582), tolerance);\r\n   BOOST_CHECK_CLOSE(ellint_rj(T(2), T(3), T(4), T(5)), T(0.14297579667157), tolerance);\r\n   BOOST_CHECK_CLOSE(ellint_rj(T(2), T(3), T(4), T(-0.5)), T(0.24723819703052), tolerance);\r\n   BOOST_CHECK_CLOSE(ellint_rj(T(2), T(3), T(4), T(-5)), T(-0.12711230042964), tolerance);\r\n   // RD:\r\n   BOOST_CHECK_CLOSE(ellint_rd(T(0), T(2), T(1)), T(1.7972103521034), tolerance);\r\n   BOOST_CHECK_CLOSE(ellint_rd(T(2), T(3), T(4)), T(0.16510527294261), tolerance);\r\n\r\n   // Sanity/consistency checks from Numerical Computation of Real or Complex \r\n   // Elliptic Integrals, B. C. Carlson: http://arxiv.org/abs/math.CA/9409227\r\n   std::tr1::mt19937 ran;\r\n   std::tr1::uniform_real<float> ur(0, 1000);\r\n   T eps40 = 40 * tools::epsilon<T>();\r\n\r\n   for(unsigned i = 0; i < 1000; ++i)\r\n   {\r\n      T x = ur(ran);\r\n      T y = ur(ran);\r\n      T z = ur(ran);\r\n      T lambda = ur(ran);\r\n      T mu = x * y / lambda;\r\n      // RF, eq 49:\r\n      T s1 = ellint_rf(x+lambda, y+lambda, lambda) + \r\n         ellint_rf(x + mu, y + mu, mu);\r\n      T s2 = ellint_rf(x, y, T(0));\r\n      BOOST_CHECK_CLOSE_FRACTION(s1, s2, eps40);\r\n      // RC is degenerate case of RF:\r\n      s1 = ellint_rc(x, y);\r\n      s2 = ellint_rf(x, y, y);\r\n      BOOST_CHECK_CLOSE_FRACTION(s1, s2, eps40);\r\n      // RC, eq 50 (Note have to assume y = x):\r\n      T mu2 = x * x / lambda;\r\n      s1 = ellint_rc(lambda, x+lambda) \r\n         + ellint_rc(mu2, x + mu2);\r\n      s2 = ellint_rc(T(0), x);\r\n      BOOST_CHECK_CLOSE_FRACTION(s1, s2, eps40);\r\n      /*\r\n      T p = ????; // no closed form for a, b and p???\r\n      s1 = ellint_rj(x+lambda, y+lambda, lambda, p+lambda)\r\n         + ellint_rj(x+mu, y+mu, mu, p+mu);\r\n      s2 = ellint_rj(x, y, T(0), p)\r\n         - 3 * ellint_rc(a, b);\r\n      */\r\n      // RD, eq 53:\r\n      s1 = ellint_rd(lambda, x+lambda, y+lambda)\r\n         + ellint_rd(mu, x+mu, y+mu);\r\n      s2 = ellint_rd(T(0), x, y)\r\n         - 3 / (y * sqrt(x+y+lambda+mu));\r\n      BOOST_CHECK_CLOSE_FRACTION(s1, s2, eps40);\r\n      // RD is degenerate case of RJ:\r\n      s1 = ellint_rd(x, y, z);\r\n      s2 = ellint_rj(x, y, z, z);\r\n      BOOST_CHECK_CLOSE_FRACTION(s1, s2, eps40);\r\n   }\r\n\r\n   //\r\n   // Now random spot values:\r\n   //\r\n#include \"ellint_rf_data.ipp\"\r\n\r\n   do_test_ellint_rf(ellint_rf_data, type_name, \"RF: Random data\");\r\n\r\n#include \"ellint_rc_data.ipp\"\r\n\r\n   do_test_ellint_rc(ellint_rc_data, type_name, \"RC: Random data\");\r\n\r\n#include \"ellint_rj_data.ipp\"\r\n\r\n   do_test_ellint_rj(ellint_rj_data, type_name, \"RJ: Random data\");\r\n\r\n#include \"ellint_rd_data.ipp\"\r\n\r\n   do_test_ellint_rd(ellint_rd_data, type_name, \"RD: Random data\");\r\n}\r\n\r\nint test_main(int, char* [])\r\n{\r\n    expected_results();\r\n    BOOST_MATH_CONTROL_FP;\r\n\r\n    boost::math::ellint_rj(1.778e-31, 1.407e+18, 10.05, -4.83e-10);\r\n\r\n    test_spots(0.0F, \"float\");\r\n    test_spots(0.0, \"double\");\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n    test_spots(0.0L, \"long double\");\r\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\r\n    test_spots(boost::math::concepts::real_concept(0), \"real_concept\");\r\n#endif\r\n#else\r\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\r\n      \"either because the long double overloads of the usual math functions are \"\r\n      \"not available at all, or because they are too inaccurate for these tests \"\r\n      \"to pass.</note>\" << std::cout;\r\n#endif\r\n\r\n    return 0;\r\n}\r\n\r\n/*\r\n\r\ntest_carlson.cpp\r\nLinking...\r\nEmbedding manifest...\r\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_carlson.exe\"\r\nRunning 1 test case...\r\nTests run with Microsoft Visual C++ version 8.0, Dinkumware standard library version 405, Win32\r\nTesting: RF: Random data\r\nboost::math::ellint_rf<float> Max = 0 RMS Mean=0\r\nTesting: RC: Random data\r\nboost::math::ellint_rc<float> Max = 0 RMS Mean=0\r\nTesting: RJ: Random data\r\nboost::math::ellint_rf<float> Max = 0 RMS Mean=0\r\nTesting: RD: Random data\r\nboost::math::ellint_rd<float> Max = 0 RMS Mean=0\r\nTesting: RF: Random data\r\nboost::math::ellint_rf<double> Max = 2.949 RMS Mean=0.7498\r\n    worst case at row: 377\r\n    { 3.418e+025, 2.594e-005, 3.264e-012, 6.169e-012 }\r\nTesting: RC: Random data\r\nboost::math::ellint_rc<double> Max = 2.396 RMS Mean=0.6283\r\n    worst case at row: 10\r\n    { 1.97e-029, 3.224e-025, 2.753e+012 }\r\nTesting: RJ: Random data\r\nboost::math::ellint_rf<double> Max = 152.9 RMS Mean=11.15\r\n    worst case at row: 633\r\n    { 1.876e+016, 0.000278, 3.796e-006, -4.412e-005, -1.656e-005 }\r\nTesting: RD: Random data\r\nboost::math::ellint_rd<double> Max = 2.586 RMS Mean=0.8614\r\n    worst case at row: 45\r\n    { 2.111e-020, 8.757e-026, 1.923e-023, 1.004e+033 }\r\nTesting: RF: Random data\r\nboost::math::ellint_rf<long double> Max = 2.949 RMS Mean=0.7498\r\n    worst case at row: 377\r\n    { 3.418e+025, 2.594e-005, 3.264e-012, 6.169e-012 }\r\nTesting: RC: Random data\r\nboost::math::ellint_rc<long double> Max = 2.396 RMS Mean=0.6283\r\n    worst case at row: 10\r\n    { 1.97e-029, 3.224e-025, 2.753e+012 }\r\nTesting: RJ: Random data\r\nboost::math::ellint_rf<long double> Max = 152.9 RMS Mean=11.15\r\n    worst case at row: 633\r\n    { 1.876e+016, 0.000278, 3.796e-006, -4.412e-005, -1.656e-005 }\r\nTesting: RD: Random data\r\nboost::math::ellint_rd<long double> Max = 2.586 RMS Mean=0.8614\r\n    worst case at row: 45\r\n    { 2.111e-020, 8.757e-026, 1.923e-023, 1.004e+033 }\r\nTesting: RF: Random data\r\nboost::math::ellint_rf<real_concept> Max = 2.949 RMS Mean=0.7498\r\n    worst case at row: 377\r\n    { 3.418e+025, 2.594e-005, 3.264e-012, 6.169e-012 }\r\nTesting: RC: Random data\r\nboost::math::ellint_rc<real_concept> Max = 2.396 RMS Mean=0.6283\r\n    worst case at row: 10\r\n    { 1.97e-029, 3.224e-025, 2.753e+012 }\r\nTesting: RJ: Random data\r\nboost::math::ellint_rf<real_concept> Max = 152.9 RMS Mean=11.15\r\n    worst case at row: 633\r\n    { 1.876e+016, 0.000278, 3.796e-006, -4.412e-005, -1.656e-005 }\r\nTesting: RD: Random data\r\nboost::math::ellint_rd<real_concept> Max = 2.586 RMS Mean=0.8614\r\n    worst case at row: 45\r\n    { 2.111e-020, 8.757e-026, 1.923e-023, 1.004e+033 }\r\n*** No errors detected\r\n\r\n*/\r\n", "meta": {"hexsha": "67be9d5424fe1c172ab66860dc16571194f1dbeb", "size": 15392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_carlson.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/math/test/test_carlson.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/test/test_carlson.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 37.1787439614, "max_line_length": 163, "alphanum_fraction": 0.6111616424, "num_tokens": 4623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.6164912951020929}}
{"text": "\n#include \"EventShapes/EventShapes.h\"\n\n#include <Eigen/Dense>\n\n#include <iostream>\n#include <vector>\n\nusing namespace Eigen;\n\nint test_example_eigen() {\n    std::cout << \"Running Eigen example\" << std::endl;\n\n    // Test eigen\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    std::cout << std::endl;\n    return 0;\n}\n\nint test_example_eventshapes(unsigned int ndims = 2) {\n    std::cout << \"Running example Event Shapes tests\" << std::endl;\n\n    // Construct example input vectors\n    std::vector<std::vector<float>> vs;\n\n    EventShapes es;\n\n    if (ndims == 3) {\n        float epsilon = 0.05;\n        vs.push_back({1., epsilon, 0.});\n        vs.push_back({0., 1., epsilon});\n        vs.push_back({epsilon, 0., 1.});\n\n        es = EventShapes(vs, 3);\n\n    } else {\n        vs.push_back({0.5, 1.});\n        vs.push_back({1., -2.5});\n        vs.push_back({0., 1.5});\n        vs.push_back({-1., 2.});\n\n        es = EventShapes(vs, 2);\n\n    }\n\n    // Calculate\n    es.calc_all();\n    std::cout << \"Thrust: \" << es.get_thrust() << std::endl;\n    std::cout << \"Thrust major: \" << es.get_thrust_major() << std::endl;\n    std::cout << \"Thrust minor: \" << es.get_thrust_minor() << std::endl;\n    std::cout << \"Oblateness: \" << es.get_oblateness() << std::endl;\n    std::cout << \"Broadening: \" << es.get_broadening() << std::endl;\n    std::cout << \"S: \" << es.get_lin_spher_S() << std::endl;\n    std::cout << \"A: \" << es.get_lin_spher_A() << std::endl;\n    std::cout << \"C: \" << es.get_lin_spher_C() << std::endl;\n    std::cout << \"D: \" << es.get_lin_spher_D() << std::endl;\n\n\n    std::cout << std::endl;\n    return 0;\n}\n\nint main() {\n\n    std::cout << \"Hello, World!\" << std::endl;\n    std::cout << \"Running package event-shapes tests\" << std::endl;\n\n    test_example_eigen();\n\n    test_example_eventshapes(3);\n    test_example_eventshapes(2);\n\n    return 0;\n}\n", "meta": {"hexsha": "9023bede30705abf9c6734c51db62463415b3761", "size": 1950, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "tests/main.cxx", "max_stars_repo_name": "ynyrharris/event-shapes", "max_stars_repo_head_hexsha": "7d2095f2dfaa6663fe67756ab7fa4a83dc05df72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/main.cxx", "max_issues_repo_name": "ynyrharris/event-shapes", "max_issues_repo_head_hexsha": "7d2095f2dfaa6663fe67756ab7fa4a83dc05df72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/main.cxx", "max_forks_repo_name": "ynyrharris/event-shapes", "max_forks_repo_head_hexsha": "7d2095f2dfaa6663fe67756ab7fa4a83dc05df72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0740740741, "max_line_length": 72, "alphanum_fraction": 0.5487179487, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6164811539353791}}
{"text": "/**\n * @file\n * @brief Implementation of the GaussLegendre function to compute\n *        quadrature Weights and nodes\n * @author Raffael Casagrande\n * @date   2018-08-11 09:08:26\n * @copyright MIT License\n */\n\n#include \"gauss_quadrature.h\"\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\nnamespace lf::quad {\nstd::tuple<Eigen::VectorXd, Eigen::VectorXd> GaussLegendre(\n    unsigned num_points) {\n  LF_ASSERT_MSG(num_points > 0, \"num_points must be positive.\");\n\n  using scalar_t =\n      boost::multiprecision::number<boost::multiprecision::cpp_bin_float<\n          57, boost::multiprecision::digit_base_2>>;\n\n  static const scalar_t kPi = boost::math::constants::pi<scalar_t>();\n\n  Eigen::VectorXd points(num_points);\n  Eigen::VectorXd weights(num_points);\n\n  // the roots are symmetric in the interval, so we only have to find half of\n  // them\n  unsigned int m = (num_points + 1) / 2;\n\n  // approximation for the roots:\n  for (unsigned int i = 0; i < m; ++i) {\n    // initial guess for the i-th root:\n    scalar_t z = cos(kPi * (i + 0.75) / (num_points + 0.5));\n    scalar_t z1;\n    scalar_t pp;\n\n    // start of newton\n    do {\n      // calculate value of legendre polynomial at z using recurrence relation:\n      scalar_t p1 = 1.0;\n      scalar_t p2 = 0.0;\n      scalar_t p3;\n\n      for (unsigned int j = 0; j < num_points; ++j) {\n        p3 = p2;\n        p2 = p1;\n        p1 = ((2.0 * j + 1.) * z * p2 - j * p3) / (j + 1.);\n      }\n\n      // p1 is now the value of the legendre polynomial at z. Next we compute\n      // its derivative using a standard relation involving also p2, the\n      // polynomial of one lower order:\n      pp = num_points * (z * p1 - p2) / (z * z - 1.0);\n\n      z1 = z;\n      z = z1 - p1 / pp;\n    } while (abs(z - z1) > 1e-17);\n\n    points(i) = (0.5 * (1 - z)).convert_to<double>();\n    points(num_points - 1 - i) = (0.5 * (1 + z)).convert_to<double>();\n    weights(i) = (1. / ((1.0 - z * z) * pp * pp)).convert_to<double>();\n    weights(num_points - 1 - i) = weights(i);\n  }\n\n  return {std::move(points), std::move(weights)};\n}\n\nstd::tuple<Eigen::VectorXd, Eigen::VectorXd> GaussJacobi(\n    quadDegree_t num_points, double alpha, double beta) {\n  LF_ASSERT_MSG(num_points > 0, \"num_points must be positive.\");\n  LF_ASSERT_MSG(alpha > -1, \"alpha > -1 required\");\n  LF_ASSERT_MSG(beta > -1, \"beta > -1 required.\");\n\n  using boost::math::lgamma;\n  using scalar_t =\n      boost::multiprecision::number<boost::multiprecision::cpp_bin_float<\n          57, boost::multiprecision::digit_base_2>>;\n\n  int MAX_IT = 10;\n\n  scalar_t alfbet;\n  scalar_t an;\n  scalar_t bn;\n  scalar_t r1;\n  scalar_t r2;\n  scalar_t r3;\n  scalar_t a;\n  scalar_t b;\n  scalar_t c;\n  scalar_t p1;\n  scalar_t p2;\n  scalar_t p3;\n  scalar_t pp;\n  scalar_t temp;\n  scalar_t z;\n  scalar_t z1;\n\n  std::vector<scalar_t> points(num_points);\n  Eigen::VectorXd weights(num_points);\n\n  // Make an initial guess for the zeros:\n  for (quadDegree_t i = 0; i < num_points; ++i) {\n    if (i == 0) {\n      // initial guess for the largest root\n      an = alpha / num_points;\n      bn = beta / num_points;\n      r1 = (1.0 + alpha) *\n           (2.78 / (4.0 + num_points * num_points) + 0.768 * an / num_points);\n      r2 = 1.0 + 1.48 * an + 0.96 * bn + 0.452 * an * an + 0.83 * an * bn;\n      z = 1.0 - r1 / r2;\n    } else if (i == 1) {\n      // initial guess for the second largest root\n      r1 = (4.1 + alpha) / ((1.0 + alpha) * (1.0 + 0.156 * alpha));\n      r2 = 1.0 + 0.06 * (num_points - 8.0) * (1.0 + 0.12 * alpha) / num_points;\n      r3 = 1.0 + 0.012 * beta * (1.0 + 0.25 * std::abs(alpha)) / num_points;\n      z -= (1.0 - z) * r1 * r2 * r3;\n    } else if (i == 2) {\n      // initial guess for the third largest root\n      r1 = (1.67 + 0.28 * alpha) / (1.0 + 0.37 * alpha);\n      r2 = 1.0 + 0.22 * (num_points - 8.0) / num_points;\n      r3 = 1.0 + 8.0 * beta / ((6.28 + beta) * num_points * num_points);\n      z -= (points[0] - z) * r1 * r2 * r3;\n    } else if (i == num_points - 2) {\n      // initial guess for the second smallest root\n      r1 = (1.0 + 0.235 * beta) / (0.766 + 0.119 * beta);\n      r2 = 1.0 / (1.0 + 0.639 * (num_points - 4.0) /\n                            (1.0 + 0.71 * (num_points - 4.0)));\n      r3 = 1.0 /\n           (1.0 + 20.0 * alpha / ((7.5 + alpha) * num_points * num_points));\n      z += (z - points[num_points - 4]) * r1 * r2 * r3;\n    } else if (i == num_points - 1) {\n      // initial guess for the smallest root\n      r1 = (1.0 + 0.37 * beta) / (1.67 + 0.28 * beta);\n      r2 = 1.0 / (1.0 + 0.22 * (num_points - 8.0) / num_points);\n      r3 = 1.0 /\n           (1.0 + 8.0 * alpha / ((6.28 + alpha) * num_points * num_points));\n      z += (z - points[num_points - 3]) * r1 * r2 * r3;\n    } else {\n      // initial guess for the other points\n      z = 3.0 * points[i - 1] - 3.0 * points[i - 2] + points[i - 3];\n    }\n    alfbet = alpha + beta;\n    quadDegree_t its;\n    for (its = 1; its <= MAX_IT; ++its) {\n      // refinement by Newton's method\n      temp = 2.0 + alfbet;\n\n      // Start the recurrence with P_0 and P1 to avoid a division by zero when\n      // alpha * beta = 0 or -1\n      p1 = (alpha - beta + temp * z) / 2.0;\n      p2 = 1.0;\n      for (quadDegree_t j = 2; j <= num_points; ++j) {\n        p3 = p2;\n        p2 = p1;\n        temp = 2 * j + alfbet;\n        a = 2 * j * (j + alfbet) * (temp - 2.0);\n        b = (temp - 1.0) *\n            (alpha * alpha - beta * beta + temp * (temp - 2.0) * z);\n        c = 2.0 * (j - 1 + alpha) * (j - 1 + beta) * temp;\n        p1 = (b * p2 - c * p3) / a;\n      }\n      pp = (num_points * (alpha - beta - temp * z) * p1 +\n            2.0 * (num_points + alpha) * (num_points + beta) * p2) /\n           (temp * (1.0 - z * z));\n      // p1 is now the desired jacobia polynomial. We next compute pp, its\n      // derivative, by a standard relation involving p2, the polynomial of one\n      // lower order\n      z1 = z;\n      z = z1 - p1 / pp;  // Newtons Formula\n      if (abs(z - z1) <= 1e-17) {\n        break;\n      }\n    }\n    LF_VERIFY_MSG(its <= MAX_IT, \"too many iterations.\");\n\n    points[i] = z;\n    weights(i) = (exp(lgamma(alpha + num_points) + lgamma(beta + num_points) -\n                      lgamma(num_points + 1.) -\n                      lgamma(double(num_points) + alfbet + 1.0)) *\n                  temp * pow(2.0, alfbet) / (pp * p2))\n                     .convert_to<double>();\n  }\n\n  Eigen::VectorXd points_result(num_points);\n  for (quadDegree_t i = 0; i < num_points; ++i) {\n    points_result(i) = points[i].convert_to<double>();\n  }\n\n  return {points_result, weights};\n}\n}  // namespace lf::quad\n", "meta": {"hexsha": "c016445575b9399b66fb734b49935d5666e1597f", "size": 6634, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/lf/quad/gauss_quadrature.cc", "max_stars_repo_name": "isschoch/lehrfempp", "max_stars_repo_head_hexsha": "5083248a4b78227a0a331e384de3e6f546a54dcc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/lf/quad/gauss_quadrature.cc", "max_issues_repo_name": "isschoch/lehrfempp", "max_issues_repo_head_hexsha": "5083248a4b78227a0a331e384de3e6f546a54dcc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/lf/quad/gauss_quadrature.cc", "max_forks_repo_name": "isschoch/lehrfempp", "max_forks_repo_head_hexsha": "5083248a4b78227a0a331e384de3e6f546a54dcc", "max_forks_repo_licenses": ["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.1958762887, "max_line_length": 79, "alphanum_fraction": 0.5476334037, "num_tokens": 2245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6164811498438054}}
{"text": "/*\n\nchannel.cpp\n\nsolve for flow rates in a rectangular channel\n\n\nNx/Ny = number of nodes along a side\n\ng++ -I/usr/local/include/eigen3 ...\n\n*/\n\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <random>\n#include <vector>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace Eigen;\n\nclass TwoVect {\n\npublic:\n\n  double x;\n  double y;\n\n  TwoVect () {\n    x=0.0; y=0.0;\n  };\n  \n  TwoVect (double x0, double y0) {\n    x=x0; y=y0;\n  };\n\n  void setV(double x0, double y0) {\n    x=x0; y=y0;\n  }\n\n\n  double mag() {\n    return  sqrt(x*x + y*y);\n  }\n\n double operator*(const TwoVect & other);\n\n TwoVect operator+(const TwoVect & other);\n\n TwoVect operator-(const TwoVect & other);\n\n friend std::ostream &operator<<(std::ostream &out, TwoVect v0) {\n  out << v0.x << \" \" << v0.y;\n  return out;\n }\n\n}; // end of class TwoVect\n\nTwoVect TwoVect::operator-(const TwoVect & other) {\n  return TwoVect(x-other.x,y-other.y);\n}\n\nTwoVect TwoVect::operator+(const TwoVect & other) {\n  return TwoVect(x+other.x,y+other.y);\n}\n\ndouble TwoVect::operator*(const TwoVect & other) {\n  // dot product\n  return x*other.x + y*other.y;\n}\n\nTwoVect operator*(const double & lhs, const TwoVect & rhs) {\n  TwoVect v0 = TwoVect(lhs*rhs.x,lhs*rhs.y);\n  return v0;\n}\n\nTwoVect operator*(const TwoVect & lhs, const double & rhs) {\n  TwoVect v0 = TwoVect(rhs*lhs.x,rhs*lhs.y);\n  return v0;\n}\n\nTwoVect operator/(const TwoVect & lhs, const double & rhs) {\n  TwoVect v0 = TwoVect(lhs.x/rhs,lhs.y/rhs);\n  return v0;\n}\n\n// --------------------------------------------------------------------\n\ntypedef int node;\ntypedef int element;\nTwoVect *rNode = NULL;               // vector of node coordinates\ntypedef Matrix<int,Dynamic,3> eMat;  // custom Eigen matrix type\neMat nL;                             // track nodes associated with element 0,1,2 = CCW nodes\n\ndouble area(element e)  {\n  double a3 = rNode[nL(e,1)].x - rNode[nL(e,0)].x;\n  double a2 = rNode[nL(e,0)].x - rNode[nL(e,2)].x;\n  double b3 = rNode[nL(e,0)].y - rNode[nL(e,1)].y;\n  double b2 = rNode[nL(e,2)].y - rNode[nL(e,0)].y;\n  return 0.5*(a3*b2 - a2*b3);\n}\n\nTwoVect cm(element e) {\n  // center of mass of element e\n  return (rNode[nL(e,0)] + rNode[nL(e,1)] + rNode[nL(e,2)])/3.0;\n}\n\nint main(void) {\n  int verbose=0;\n  int Nx,Ny;\n  double hw,Pz,Vz;\n  ofstream ofs,ofs2,ofs3,ofs4;\n  ofs.open(\"channel.dat\");\n  ofs2.open(\"c2.dat\");\n  ofs3.open(\"c3.dat\");\n  ofs4.open(\"c4.dat\");\n  cout << \" input Nx, Ny, H/W [0.5], Pz/mu [-6], Vz [0] \" << endl;\n  cin >> Nx >> Ny >> hw >> Pz >> Vz;\n  cout << \" enter 1 for verbose mode \" << endl;\n  cin >> verbose;\n  int Nnodes = Nx*Ny;\n  int Nelements = (Nx-1)*(Ny-1)*2;\n  cout << \" number of nodes: \" << Nnodes << endl;\n  cout << \" number of elements: \" << Nelements << endl;\n\n  VectorXd f(Nnodes),w(Nnodes);\n  MatrixXd K(Nnodes,Nnodes);\n  nL = eMat(Nelements,3);\n\n  // define rectangle nodes\n  rNode = new TwoVect[Nnodes];\n  node nodeNumber = 0;\n  for (int iy=0;iy<Ny;iy++) {\n  for (int ix=0;ix<Nx;ix++) {\n     double x = (double) ix/(Nx-1);\n     double y = (double) iy/(Ny-1);\n     y *= hw;                        // scale to desired proportions\n     rNode[nodeNumber].setV(x,y);\n     nodeNumber++;\n  }}\n\n  //label elements and specify their nodes\n  if (verbose) cout << endl << \" element and associated nodes: \" << endl << endl;\n  for (int iy=0;iy<Ny-1;iy++) {\n  for (int ix=0;ix<Nx-1;ix++) {\n     node i = iy*(Nx-1)+ix;\n     element eNumber = 2*i;\n     node j = ix + Nx*iy;\n     nL(eNumber,0) = j;\n     nL(eNumber,1) = j+Nx+1;\n     nL(eNumber,2) = j+Nx;\n     if (verbose) cout << eNumber << \" \" << nL(eNumber,0) << \" \" << nL(eNumber,1) << \" \" << \n             nL(eNumber,2) << endl;\n     eNumber++;\n     nL(eNumber,0) = j;\n     nL(eNumber,1) = j+1;\n     nL(eNumber,2) = j+1+Nx;\n     if (verbose) cout << eNumber << \" \" << nL(eNumber,0) << \" \" << nL(eNumber,1) << \" \" << \n             nL(eNumber,2) << endl;\n  }}\n\n  if (verbose) {\n    cout << \" ----------- \" << endl;\n    // print mesh\n     for (element e=0;e<Nelements;e++) {\n        ofs << rNode[nL(e,0)] << \" \" << rNode[nL(e,1)] << endl;\n        ofs << rNode[nL(e,1)] << \" \" << rNode[nL(e,2)] << endl;\n        ofs << rNode[nL(e,2)] << \" \" << rNode[nL(e,0)] << endl;\n        ofs2 << e << \" \" << cm(e) << \" \" << area(e) << endl;\n     }\n  }\n\n  // assemble FEM stiffness matrix, K\n  for (element e=0;e<Nelements;e++) {\n     double beta[3],gamma[3];\n     for (int i=0;i<3;i++) {\n       int j = (i+1)%3;\n       int k = (i+2)%3;\n       beta[i]  = rNode[nL(e,j)].y - rNode[nL(e,k)].y;\n       gamma[i] = rNode[nL(e,k)].x - rNode[nL(e,j)].x;\n       if (verbose) cout << e << \" \" << i << \" \" << beta[i] << \" \" << gamma[i] << endl;\n     }\n     for (int i=0;i<3;i++) {\n     for (int j=0;j<3;j++) {\n        node I = nL(e,i);\n        node J = nL(e,j);\n        K(I,J) += (beta[i]*beta[j] + gamma[i]*gamma[j])/(4.0*area(e));\n     }}\n  }\n\n  if (verbose) {\n    cout << \" ----------- \" << endl;\n    cout << \"K \" << endl;\n    cout << \"det(K) = \" << K.determinant() << endl;\n    for (node i=0;i<Nnodes;i++) {\n    for (node j=0;j<Nnodes;j++) {\n      cout << i << \" \" << j << \" \" << K(i,j) << endl;\n    }}\n    cout << \" ----------- \" << endl;\n  }\n  \n\n  // assemble force vector  [pressure gradient/viscosity  = dp/dz / mu  == Pz]\n  for (element e=0;e<Nelements;e++) { \n     double ff = -Pz*area(e)/3.0;\n     f(nL(e,0)) += ff;  // sum force contribution to nodes\n     f(nL(e,1)) += ff;\n     f(nL(e,2)) += ff; \n  }\n  if (verbose) {\n    cout << \" f \" << endl;\n    for (node i=0;i<Nnodes;i++) cout << i << \" \" << f(i) << endl;\n    cout << \" ----------- \" << endl;\n  }\n\n  // boundary conditions    [trick to force w(...) = f(...) = 0]\n  // we need to identify the nodes on the boundary !\n\n  for (node n=0;n<Nx;n++) {\n     if (verbose) cout << \" boundary nodes: \" << n << \" \" << n + Nx*(Ny-1) << endl;\n     K(n,n) *= 1e12; \n     K(n+Nx*(Ny-1),n+Nx*(Ny-1)) *= 1e12;\n     f(n) = 0.0*K(n,n);                                 // bottom\n     f(n+Nx*(Ny-1)) = Vz*K(n+Nx*(Ny-1),n+Nx*(Ny-1));    // top  \n  }\n  for (node n=1;n<Ny-1;n++) {\n     if (verbose) cout << \" boundary nodes: \" << n*Nx << \" \" << n*Nx + Nx - 1 << endl;\n     K(n*Nx,n*Nx) *= 1e12;\n     K(n*Nx+Nx-1,n*Nx+Nx-1) *= 1e12;  \n     f(n*Nx) = 0.0*K(n*Nx,n*Nx);             // left\n     f(n*Nx+Nx-1) = 0.0;                     // right\n  }\n\n  int num=0;\n  for (node n=0;n<Nnodes;n++) {\n  for (node m=0;m<Nnodes;m++) {\n     if (K(n,m) != 0.0) num++;\n  }}\n  cout << --num << \" nonzero elements in K \" << endl;\n\n  // obtain solution\n  w = K.inverse()*f;\n\n  // store solution \n  int nx = 1;\n  for (node n=0;n<Nnodes;n++) {\n    ofs4 << rNode[n] << \" \" << w(n) << endl;\n    nx++;\n    if (nx > Nx) {\n       ofs4 << \"  \" << endl;\n       nx=1;\n    }\n  }\n\n  // integrate to obtain flow rate  [= int dx dy w(x,y)]\n  double in = 0.0;\n  for (element e=0;e<Nelements;e++) {\n     in +=area(e)*(w(nL(e,0)) + w(nL(e,1)) + w(nL(e,2)));\n  }\n  in /= 3.0;\n  cout << \" flow rate = \" << in << endl;\n\n  delete [] rNode;\n  ofs.close();\n  ofs2.close();\n  ofs3.close();\n  ofs4.close();\n  cout << \" mesh coords in channel.dat \" << endl;\n  cout << \" e cm(e) area(e) in c2.dat \" << endl;\n  cout << \" r_node w(r_node)  in c4.dat\" << endl;\n  return 0;\n}\n", "meta": {"hexsha": "51d81593a82dfd12f724018e95fd99ffeccd43d9", "size": 7172, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CH19/FEM/channel.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": "CH19/FEM/channel.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": "CH19/FEM/channel.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": 26.08, "max_line_length": 93, "alphanum_fraction": 0.5062744004, "num_tokens": 2531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938819, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6164651040736219}}
{"text": "\ufeff///////////////////////////////////////////////////////////////////\n//  Copyright Christopher Kormanyos 2018 - 2022.                 //\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// This Miller-Rabin primality test is loosely based on\n// an adaptation of some code from Boost.Multiprecision.\n// The Boost.Multiprecision code can be found here:\n// https://www.boost.org/doc/libs/1_78_0/libs/multiprecision/doc/html/boost_multiprecision/tut/primetest.html\n\n#include <ctime>\n#include <random>\n#include <sstream>\n#include <string>\n\n#include <boost/version.hpp>\n\n#if !defined(BOOST_VERSION)\n#error BOOST_VERSION is not defined. Ensure that <boost/version.hpp> is properly included.\n#endif\n\n#if ((BOOST_VERSION >= 107900) && !defined(BOOST_MP_STANDALONE))\n#define BOOST_MP_STANDALONE\n#endif\n\n#if (BOOST_VERSION < 108000)\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#endif\n\n#if (defined(__GNUC__) && !defined(__clang__) && (__GNUC__ >= 12))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wrestrict\"\n#endif\n\n#if (BOOST_VERSION < 108000)\n#if (defined(__clang__) && (__clang_major__ > 9)) && !defined(__APPLE__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-copy\"\n#endif\n#endif\n\n#include <boost/multiprecision/miller_rabin.hpp>\n#include <boost/multiprecision/uintwide_t_backend.hpp>\n\n#include <examples/example_uintwide_t.h>\n\nnamespace local_miller_rabin {\n\ntemplate<typename UnsignedIntegralType>\nauto lexical_cast(const UnsignedIntegralType& u) -> std::string\n{\n  std::stringstream ss;\n\n  ss << u;\n\n  return ss.str();\n}\n\n} // namespace local_miller_rabin\n\n#if defined(WIDE_INTEGER_NAMESPACE)\nauto WIDE_INTEGER_NAMESPACE::math::wide_integer::example008a_miller_rabin_prime() -> bool\n#else\nauto math::wide_integer::example008a_miller_rabin_prime() -> bool\n#endif\n{\n  #if defined(WIDE_INTEGER_NAMESPACE)\n  using boost_wide_integer_type =\n    boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<static_cast<WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t>(UINT32_C(512))>,\n                                  boost::multiprecision::et_off>;\n  #else\n  using boost_wide_integer_type =\n    boost::multiprecision::number<boost::multiprecision::uintwide_t_backend<static_cast<math::wide_integer::size_t>(UINT32_C(512))>,\n                                  boost::multiprecision::et_off>;\n  #endif\n\n  // This example uses wide_integer's uniform_int_distribution to select\n  // prime candidates. These prime candidates are subsequently converted\n  // (via string-streaming) to Boost.Multiprecision integers.\n\n  #if defined(WIDE_INTEGER_NAMESPACE)\n  using local_wide_integer_type = WIDE_INTEGER_NAMESPACE::math::wide_integer::uintwide_t              <static_cast<WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t>(std::numeric_limits<boost_wide_integer_type>::digits)>;\n  using local_distribution_type = WIDE_INTEGER_NAMESPACE::math::wide_integer::uniform_int_distribution<static_cast<WIDE_INTEGER_NAMESPACE::math::wide_integer::size_t>(std::numeric_limits<boost_wide_integer_type>::digits)>;\n  #else\n  using local_wide_integer_type = math::wide_integer::uintwide_t              <static_cast<math::wide_integer::size_t>(std::numeric_limits<boost_wide_integer_type>::digits)>;\n  using local_distribution_type = math::wide_integer::uniform_int_distribution<static_cast<math::wide_integer::size_t>(std::numeric_limits<boost_wide_integer_type>::digits)>;\n  #endif\n\n  using random_engine1_type = std::mt19937;\n  using random_engine2_type = std::linear_congruential_engine<std::uint32_t, UINT32_C(48271), UINT32_C(0), UINT32_C(2147483647)>; // NOLINT(cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers)\n\n  const auto seed_start = std::clock();\n\n  random_engine1_type gen1(static_cast<typename random_engine1_type::result_type>(seed_start));\n  random_engine2_type gen2(static_cast<typename random_engine2_type::result_type>(seed_start));\n\n  // Select prime candidates from a range of 10^150 ... max(uint512_t)-1.\n  WIDE_INTEGER_CONSTEXPR local_wide_integer_type\n    dist_min\n    (\n      \"1\"\n      \"00000000000000000000000000000000000000000000000000\"\n      \"00000000000000000000000000000000000000000000000000\"\n      \"00000000000000000000000000000000000000000000000000\"\n    );\n\n  WIDE_INTEGER_CONSTEXPR local_wide_integer_type\n    dist_max\n    (\n      (std::numeric_limits<local_wide_integer_type>::max)() - 1\n    );\n\n  local_distribution_type\n    dist\n    {\n      dist_min,\n      dist_max\n    };\n\n  boost_wide_integer_type p0;\n  boost_wide_integer_type p1;\n\n  auto dist_func =\n    [&dist, &gen1]() // NOLINT(modernize-use-trailing-return-type)\n    {\n      const auto n = dist(gen1);\n\n      return boost_wide_integer_type(local_miller_rabin::lexical_cast(n));\n    };\n\n  for(;;)\n  {\n    p0 = dist_func();\n\n    const auto p0_is_probably_prime = boost::multiprecision::miller_rabin_test(p0, 25U, gen2);\n\n    if(p0_is_probably_prime)\n    {\n      break;\n    }\n  }\n\n  auto seed_next = std::clock();\n\n  while(seed_next == seed_start)\n  {\n    seed_next = std::clock();\n  }\n\n  gen1.seed(static_cast<typename random_engine1_type::result_type>(seed_next));\n\n  for(;;)\n  {\n    p1 = dist_func();\n\n    const auto p1_is_probably_prime = boost::multiprecision::miller_rabin_test(p1, 25U, gen2);\n\n    if(p1_is_probably_prime)\n    {\n      break;\n    }\n  }\n\n  const boost_wide_integer_type gd = gcd(p0, p1);\n\n  const auto result_is_ok = (   (p0  > boost_wide_integer_type(local_miller_rabin::lexical_cast(dist_min)))\n                             && (p1  > boost_wide_integer_type(local_miller_rabin::lexical_cast(dist_min)))\n                             && (p0 != 0U)\n                             && (p1 != 0U)\n                             && (p0 != p1)\n                             && (gd == 1U));\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 defined(WIDE_INTEGER_STANDALONE_EXAMPLE008A_MILLER_RABIN_PRIME)\n\n#include <iomanip>\n#include <iostream>\n\nauto main() -> int // NOLINT(bugprone-exception-escape)\n{\n  #if defined(WIDE_INTEGER_NAMESPACE)\n  const auto result_is_ok = WIDE_INTEGER_NAMESPACE::math::wide_integer::example008a_miller_rabin_prime();\n  #else\n  const auto result_is_ok = math::wide_integer::example008a_miller_rabin_prime();\n  #endif\n\n  std::cout << \"result_is_ok: \" << std::boolalpha << result_is_ok << std::endl;\n\n  return (result_is_ok ? 0 : -1);\n}\n\n#endif\n\n#if (BOOST_VERSION < 108000)\n#if (defined(__clang__) && (__clang_major__ > 9)) && !defined(__APPLE__)\n#pragma GCC diagnostic pop\n#endif\n#endif\n\n#if (defined(__GNUC__) && !defined(__clang__) && (__GNUC__ >= 12))\n#pragma GCC diagnostic pop\n#endif\n\n#if (BOOST_VERSION < 108000)\n#if defined(__GNUC__)\n#pragma GCC diagnostic pop\n#pragma GCC diagnostic pop\n#pragma GCC diagnostic pop\n#endif\n#endif\n", "meta": {"hexsha": "c2d767d6fddefadb2a51164b724b36c121def218", "size": 7213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example008a_miller_rabin_prime.cpp", "max_stars_repo_name": "clayne/wide-integer", "max_stars_repo_head_hexsha": "a4e6828d28bda6313b206cd795b83ea6d1133f05", "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/example008a_miller_rabin_prime.cpp", "max_issues_repo_name": "clayne/wide-integer", "max_issues_repo_head_hexsha": "a4e6828d28bda6313b206cd795b83ea6d1133f05", "max_issues_repo_licenses": ["BSL-1.0"], "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/example008a_miller_rabin_prime.cpp", "max_forks_repo_name": "clayne/wide-integer", "max_forks_repo_head_hexsha": "a4e6828d28bda6313b206cd795b83ea6d1133f05", "max_forks_repo_licenses": ["BSL-1.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.3452914798, "max_line_length": 222, "alphanum_fraction": 0.7085817274, "num_tokens": 1793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6164650922959329}}
{"text": "#include \"geometry.h\"\n#include <Eigen/LU>\n\nusing namespace Eigen;\nnamespace marvel{\ndouble clo_surf_vol(const MatrixXd &nods, const MatrixXi &surf){\n  //TODO:check if the surface is closed and manifold\n  double volume = 0;\n  for(size_t i = 0; i < surf.cols(); ++i){\n    Matrix3d tet;\n    for(size_t j = 0; j < 3; ++j){\n      tet.row(j) = nods.col(surf(j, i));\n    }\n    //TODO:check\n    volume += tet.determinant();\n  }\n\n  return volume;\n  \n}\n\nint build_bdbox(const MatrixXd &nods, MatrixXd & bdbox){\n  //simple bounding box\n  //bounding box is a dimension * 2 matrix, whose first column is minimal value and second column is maximal value.\n  bdbox = nods.col(0)*MatrixXd::Ones(1, 2);\n  for(size_t i = 0; i < nods.cols(); ++i){\n    for(size_t j = 0; j < nods.rows(); ++j){\n      if(bdbox(j, 0) > nods(j, i))\n        bdbox(j, 0) = nods(j ,i);\n      if(bdbox(j, 1) < nods(j, i))\n        bdbox(j, 1) = nods(j ,i);      \n    }\n  }\n  return 0;\n}\n\n}//namespace : marvel\n", "meta": {"hexsha": "7551e5dfda5080687eec43105484c92af4994aec", "size": 964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry.cpp", "max_stars_repo_name": "Chongyao/Hierarchical-Z-Buffer", "max_stars_repo_head_hexsha": "61934510577c75a7de72b9f9a3a773d1e1ce46bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geometry.cpp", "max_issues_repo_name": "Chongyao/Hierarchical-Z-Buffer", "max_issues_repo_head_hexsha": "61934510577c75a7de72b9f9a3a773d1e1ce46bd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geometry.cpp", "max_forks_repo_name": "Chongyao/Hierarchical-Z-Buffer", "max_forks_repo_head_hexsha": "61934510577c75a7de72b9f9a3a773d1e1ce46bd", "max_forks_repo_licenses": ["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.3684210526, "max_line_length": 115, "alphanum_fraction": 0.5943983402, "num_tokens": 310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6163873452026604}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXf A = MatrixXf::Random(4,4);\nRealSchur<MatrixXf> schur(4);\nschur.compute(A, /* computeU = */ false);\ncout << \"The matrix T in the decomposition of A is:\" << endl << schur.matrixT() << endl;\nschur.compute(A.inverse(), /* computeU = */ false);\ncout << \"The matrix T in the decomposition of A^(-1) is:\" << endl << schur.matrixT() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "81d3b7903f720bef0ce4d1a7f82558e9d876d109", "size": 494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_RealSchur_compute.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_RealSchur_compute.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_RealSchur_compute.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0, "max_line_length": 93, "alphanum_fraction": 0.6578947368, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6163873399209461}}
{"text": "#include <NTL/mat_poly_ZZ.h>\r\n#include <NTL/mat_poly_ZZ_p.h>\r\n#include <NTL/mat_poly_lzz_p.h>\r\n\r\n#include <NTL/new.h>\r\n\r\nNTL_START_IMPL\r\n\r\nstatic\r\nlong CharPolyBound(const mat_ZZ& a)\r\n// This bound is computed via interpolation\r\n// through complex roots of unity.\r\n\r\n{\r\n   long n = a.NumRows();\r\n   long i;\r\n   ZZ res, t1, t2;\r\n\r\n   set(res);\r\n\r\n   for (i = 0; i < n; i++) {\r\n      InnerProduct(t1, a[i], a[i]);\r\n      abs(t2, a[i][i]);\r\n      mul(t2, t2, 2);\r\n      add(t2, t2, 1);\r\n      add(t1, t1, t2);\r\n      if (t1 > 1) {\r\n         SqrRoot(t1, t1);\r\n         add(t1, t1, 1);\r\n      }\r\n      mul(res, res, t1);\r\n   }\r\n\r\n   return NumBits(res);\r\n}\r\n\r\nvoid CharPoly(ZZX& gg, const mat_ZZ& a, long deterministic)\r\n{\r\n   long n = a.NumRows();\r\n   if (a.NumCols() != n)\r\n      LogicError(\"CharPoly: nonsquare matrix\");\r\n\r\n   if (n == 0) {\r\n      set(gg);\r\n      return;\r\n   }\r\n\r\n\r\n   if (n == 1) {\r\n      ZZ t;\r\n      SetX(gg);\r\n      negate(t, a(1, 1));\r\n      SetCoeff(gg, 0, t);\r\n      return;\r\n   }\r\n\r\n   long bound = 2 + CharPolyBound(a);\r\n\r\n   zz_pBak bak;\r\n   bak.save();\r\n\r\n   ZZ_pBak bak1;\r\n   bak1.save();\r\n\r\n   ZZX g;\r\n   ZZ prod;\r\n\r\n   clear(g);\r\n   set(prod);\r\n\r\n   long i;\r\n\r\n   long instable = 1;\r\n\r\n   long gp_cnt = 0;\r\n\r\n   for (i = 0; ; i++) {\r\n      if (NumBits(prod) > bound)\r\n         break;\r\n\r\n      if (!deterministic &&\r\n          !instable && bound > 1000 && NumBits(prod) < 0.25*bound) {\r\n         long plen = 90 + NumBits(max(bound, MaxBits(g)));\r\n\r\n         ZZ P;\r\n\r\n         GenPrime(P, plen, 90 + 2*NumBits(gp_cnt++));\r\n\r\n         ZZ_p::init(P);\r\n         mat_ZZ_p A;\r\n         ZZ_pX G;\r\n         conv(A, a);\r\n         CharPoly(G, A);\r\n\r\n         if (CRT(g, prod, G))\r\n            instable = 1;\r\n         else\r\n            break;\r\n      }\r\n\r\n      zz_p::FFTInit(i);\r\n\r\n      mat_zz_p A;\r\n      zz_pX G;\r\n      conv(A, a);\r\n      CharPoly(G, A);\r\n      instable = CRT(g, prod, G);\r\n   }\r\n\r\n   gg = g;\r\n\r\n   bak.restore();\r\n   bak1.restore();\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "0e233b97b9e77de37af56200b5249395e5e38af4", "size": 1991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/mat_poly_ZZ.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WinNTL-8_1_2/src/mat_poly_ZZ.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WinNTL-8_1_2/src/mat_poly_ZZ.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.0170940171, "max_line_length": 69, "alphanum_fraction": 0.4615770969, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6163651084518583}}
{"text": "\n#include <boost/test/unit_test.hpp>\n#include \"vec.h\"\n\nBOOST_AUTO_TEST_SUITE(vec)\n\nBOOST_AUTO_TEST_CASE(perpendiculars)\n{\n\tfor (int i = 0; i < 1000; i++)\n\t{\n\t\tmath::vec<3> v(math::scalar(rand() * 2) / RAND_MAX - 1, math::scalar(rand() * 2) / RAND_MAX - 1,\n\t\t\tmath::scalar(rand() * 2) / RAND_MAX - 1);\n\n\t\tmath::vec<3> xy = v.perpendicular_xy();\n\t\tmath::vec<3> yz = v.perpendicular_yz();\n\t\tmath::vec<3> xz = v.perpendicular_xz();\n\n\t\tBOOST_CHECK (math::abs(xy & v) < math::EPSILON);\n\t\tBOOST_CHECK (math::abs(yz & v) < math::EPSILON);\n\t\tBOOST_CHECK (math::abs(xz & v) < math::EPSILON);\n\t}\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "9d03639ad408f33c6fcb63446d46bb9a884021d1", "size": 616, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/math/test_vec.cc", "max_stars_repo_name": "mnvl/scratch", "max_stars_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T11:55:32.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-15T11:55:32.000Z", "max_issues_repo_path": "src/math/test_vec.cc", "max_issues_repo_name": "mnvl/scratch", "max_issues_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/test_vec.cc", "max_forks_repo_name": "mnvl/scratch", "max_forks_repo_head_hexsha": "7717772e0b9a85c8feb73fdc3562425f48b4a727", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.64, "max_line_length": 98, "alphanum_fraction": 0.6396103896, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6163651030838819}}
{"text": "\n#include \"FlexKalman/EigenQuatExponentialMap.h\"\n#include <Eigen/Eigen>\n#include <fstream>\n\n#include \"unifiedvideoinertial/CSV.h\"\n#include \"unifiedvideoinertial/CSVCellGroup.h\"\n\nusing namespace videotracker::util;\n\nint main() {\n    CSV csv;\n    for (int i = 0; i < 100; ++i) {\n\n        auto rotVec = Eigen::Vector3d{i / 2000., 0, 0};\n        auto full_exp = flexkalman::util::quat_exp(rotVec);\n        auto small_angle = flexkalman::util::small_angle_quat_exp(rotVec);\n        csv.row() << cellGroup(rotVec) << cellGroup(\"smallAngle.\", small_angle)\n                  << cellGroup(\"fullExp.\", full_exp);\n    }\n    std::ofstream os{\"data.csv\"};\n    csv.output(os);\n    return 0;\n}\n", "meta": {"hexsha": "3c955f9b5ea4b976636dc5495acd74a198a111bd", "size": 679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cplusplus/Kalman/ManualDump.cpp", "max_stars_repo_name": "rpavlik/UVBI-and-KalmanFramework-Standalone", "max_stars_repo_head_hexsha": "2276a2f921f91814a03dee6d9abe0305c6abf37a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-06-08T13:33:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T05:12:29.000Z", "max_issues_repo_path": "tests/cplusplus/Kalman/ManualDump.cpp", "max_issues_repo_name": "rpavlik/UVBI-and-KalmanFramework-Standalone", "max_issues_repo_head_hexsha": "2276a2f921f91814a03dee6d9abe0305c6abf37a", "max_issues_repo_licenses": ["Apache-2.0"], "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/cplusplus/Kalman/ManualDump.cpp", "max_forks_repo_name": "rpavlik/UVBI-and-KalmanFramework-Standalone", "max_forks_repo_head_hexsha": "2276a2f921f91814a03dee6d9abe0305c6abf37a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.16, "max_line_length": 79, "alphanum_fraction": 0.6435935199, "num_tokens": 195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6163625873287816}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n\nint main()\n{\n    using namespace boost::numeric::ublas;\n\n    int nSize;\n    std::cout << \"Enter matrix size (N): \";\n    std::cin >> nSize;\n\n    identity_matrix<int> oMatrix( nSize );\n\n    for ( unsigned int y = 0; y < oMatrix.size2(); y++ )\n    {\n        for ( unsigned int x = 0; x < oMatrix.size1(); x++ )\n        {\n            std::cout << oMatrix(x,y) << \" \";\n        }\n        std::cout << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "5a1c7c1016ccf6081cc8e63fc8459a2ef7c339e8", "size": 472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/identity-matrix-2.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-01-29T20:08:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:16:05.000Z", "max_issues_repo_path": "lang/C++/identity-matrix-2.cpp", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/C++/identity-matrix-2.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 19.6666666667, "max_line_length": 60, "alphanum_fraction": 0.5084745763, "num_tokens": 139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6163057386910782}}
{"text": "/*! \\file demo_2d_legend_lines_markers.cpp\n\\brief Demonstration of some simple 2D plot features.\n\\details Uses some simple math functions to generate curves.\nThis demonstrates plotting some simple math functions with most of the 2-D defaults,\njust changing a few details, from demo_2d_simple, \nto show use of legend for both markers and lines.\nThe detailed output shows the plot settings for each plot.\nSee default_2d_plot.cpp for using \\b all defaults.\nSee also demo_2d_plot.cpp for use of more of the very many options.\n*/\n\n// Copyright Jacob Voytko 2007\n// Copyright Paul A. Bristow 2007, 2008, 2012, 2018, 2020\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/svg_plot/svg_2d_plot.hpp>\nusing boost::svg::svg_2d_plot;\n\n//#include <boost/svg_plot/show_2d_settings.hpp>\n// Only needed for showing which settings in use.\n#include <boost/quan/unc_init.hpp>\n\n#include <iostream>\n// using std::cout;\n// using std::endl;\n// using std::boolalpha;\n#include <map>\nusing std::map;\n// #include <cmath>\n// using std::sqrt;\n#include <string>\n// using std::string;\n\n// using namespace boost::svg;\n// may be *very convenient* if using any SVG named colors,\n// to avoid writing\n//using boost::svg::red;\n//using boost::svg::yellow;\n//using boost::svg::orange;\n//using boost::svg::blue;\n//// and other enum options used:\n//using boost::svg::square;\n//// for every color used.\n\n// Three simple functions ued to generate some X and Y data-series.\n\ndouble e(double x)\n{\n  return x /2;\n}\n\ndouble f(double x)\n{\n  return std::sqrt(x);\n}\n\ndouble g(double x)\n{\n  return -2 + x*x;\n}\n\ndouble h(double x)\n{\n  return -1 + 2 * x;\n}\n\nint main()\n{\n  using namespace boost::svg; // Convenient so that all colors can be named.\n  try\n  {\n    // Some containers for (sorted) sample data.\n    std::map<double, double> data0;  // \n    std::map<double, double> data1;\n    std::map<double, double> data2;\n    std::map<double, double> data3;\n    std::map<double, double> data4;\n\n    const double n = 3.;\n\n    for(double i = -1; i <=n; i += 1.)\n    { // Compute several data points for each function.\n      data0[i] = i;\n      data1[i] = f(i);\n      data2[i] = g(i);\n      data3[i] = h(i);\n      data4[i] = e(i);\n     // List if desired:\n      // std::cout << i << ' '<< data1[i] << ' ' << data2[i] << ' ' << data3[i] << ' ' << data3[i] << std::endl;\n    }\n\n    svg_2d_plot my_plot;\n    // Uses most defaults, but some scale settings are usually sensible as defaults are -10 to +10.\n\n    my_plot.title(\"demo_2d_legend_lines_markers\");\n    std::cout << \" my_plot.title() \" << my_plot.title() << std::endl;\n    my_plot\n      .x_label(\"X-axis\") // Note chaining of setting functions.\n      .y_label(\"Y-axis\")\n      .y_range(-n, +n)\n      .x_range(-n, +n)\n      ///.x_autoscale(true) // hangs!\n      //.y_autoscale(true) // hangs!\n      .legend_on(true) // If you want to show legend and any lines and/or markers.\n      // https://www.w3schools.com/colors/colors_names.asp\n      .legend_background_color(lightyellow)\n      .legend_border_color(lightgrey)\n      .plot_background_color(whitesmoke)\n      .legend_title(\"Functions\")\n     ;\n\n    // You can check and show features and options.\n    std::cout << \"Plot title is \\\"\" <<  my_plot.title() << \"\\\".\" << std::endl;\n    std::cout << \"Legend header is \\\"\" <<  my_plot.legend_title() << \"\\\".\" << std::endl;\n\n    // Add the three data series to the plot in turn:\n    // Add any options to the data series.\n    // Plot color settings.  See https://www.w3schools.com/colors/colors_names.asp\n\n    my_plot.plot(data1, \"x\").stroke_color(black).fill_color(white); // Some are NaN because x < 0.\n\n   // my_plot.plot(data1, \"sqrt(x)\"); // But nicer to use Unicode symbol &#x221A; for square root.\n    my_plot.plot(data1, \"&#x221A;x\").stroke_color(red).fill_color(yellow); // Some are NaN because x < 0.\n\n    ////my_plot.plot(data2, \"-2 + x^2\").fill_color(orange).size(5); // but nicer to use Unicode symbol for superscript 2.\n    my_plot.plot(data2, \"-2 + x&#x00B2;\").stroke_color(magenta).fill_color(cyan).size(5);\n\n    my_plot.plot(data3, \"-1 + 2x\").stroke_color(red).fill_color(green).line_on(true).line_color(blue).shape(square); \n\n    my_plot.plot(data4, \"x / 2\").bezier_on(true).line_on(true).line_color(green).shape(none); \n\n    my_plot.write(\"./demo_2d_legend_lines_markers.svg\");\n\n    //show_2d_plot_settings(my_plot); // For diagnostic purposes only.\n  }\n  catch(const std::exception& e)\n  {\n    std::cout <<\n      \"\\n\"\"Message from thrown exception was:\\n  \" << e.what() << std::endl;\n  }\n  return 0;\n} // int main()\n\n\n  /*\n  my_plot.title() demo_2d_legend_lines_markers\n  Plot title is demo_2d_legend_lines_markers\n\n\n  SVG 2-D plot settings\n  axes_on true\n  background_border_width 2\n  background_border_color RGB(255,255,0)\n  background_color RGB(255,255,255)\n  image_border_margin() 3\n  image_border_width() 2\n  coord_precision 3\n  copyright_date\n  copyright_holder\n  description\n  document_title \"\"\n  x_size 500\n  image y_size 400\n  image_filename\n  legend_on true\n  legend_place 2\n  legend_top_left 367.3, 47.5, legend_bottom_right 497.5, 145.5\n  legend_background_color RGB(255,255,255)\n  legend_border_color RGB(255,255,0)\n  legend_color blank\n  legend_title \"\"\n  legend_title_font_size 14\n  legend_font_weight\n  legend_width 130.2\n  legend_lines true\n  limit points stroke color RGB(119,136,153)\n  limit points fill color RGB(250,235,215)\n  license_on false\n  license_reproduction permits\n  license_distribution permits\n  license_attribution requires\n  license_commercialuse permits\n  plot_background_color RGB(255,255,255)\n  plot_border_color RGB(119,136,153)\n  plot_border_width 2\n  plot_window_on true\n  plot_window_x 60.7, 353.3\n  plot_window_x_left 60.7\n  plot_window_x_right 353.3\n  plot_window_y 47.5, 346.5\n  plot_window_y_top 47.5\n  plot_window_y_bottom 346.5\n  title_on true\n  title \"\"\n  title_color blank\n  title_font_alignment 2\n  title_font_decoration\n  title_font_family Lucida Sans Unicode\n  title_font_rotation 0\n  title_font_size 18\n  title_font_stretch\n  title_font_style\n  title_font_weight\n  x_values_on false\n  x_values_font_size 12\n  x_values_font_family Lucida Sans Unicode\n  x_values_precision 3\n  x_values_ioflags 200 iosFormatFlags (0x200) dec.\n  y_values_precision 3\n  y_values_font_size() 3\n  y_values_ioflags 200 iosFormatFlags (0x200) dec.\n  y_values_color blank\n  y_values_font_family() Lucida Sans Unicode\n  y_values_font_size() 12\n  x_max 10\n  x_min -10\n  x_autoscale false\n  y_autoscale false\n  xy_autoscale false\n  x_autoscale_check_limits true\n  x_axis_on true\n  x_axis_color() RGB(0,0,0)\n  x_axis_label_color blank\n  x_values_color blank\n  x_axis_width 1\n  x_label_on true\n  x_label \"X-axis\"\n  x_label_color blank\n  x_label_font_family Lucida Sans Unicode\n  x_label_font_size 14\n  x_label_units\n  x_label_units_on false\n  x_major_labels_side left\n  x_major_label_rotation 0\n  x_major_grid_color RGB(200,220,255)\n  x_major_grid_on false\n  x_major_grid_width 1\n  x_major_interval 2\n  x_major_tick 2\n  x_major_tick_color RGB(0,0,0)\n  x_major_tick_length 5\n  x_major_tick_width 2\n  x_minor_interval 0\n  x_minor_tick_color RGB(0,0,0)\n  x_minor_tick_length 2\n  x_minor_tick_width 1\n  x_minor_grid_on false\n  x_minor_grid_color RGB(200,220,255)\n  x_minor_grid_width 0.5\n  x_range() -10, 10\n  x_num_minor_ticks 4\n  x_ticks_down_on true\n  x_ticks_up_on false\n  x_ticks_on_window_or_axis bottom\n  y_axis_position y_axis_position intersects X-axis (X range includes zero)\n  x_axis_position x_axis_position intersects Y axis (Y range includes zero)\n  x_plusminus_on false\n  x_plusminus_color blank\n  x_df_on false\n  x_df_color RGB(0,0,0)\n  x_prefix\n  x_separator\n  x_suffix\n  xy_values_on false\n  y_label_on \"true\"\n  y_label_axis Y-axis\n  y_axis_color RGB(0,0,0)\n  y_axis_label_color blank\n  y_axis_on true\n  axes_on true\n  y_axis_value_color RGB(0,0,0)\n  y_axis_width 1\n  y_label Y-axis\n  y_label_color blank\n  y_label_font_family Lucida Sans Unicode\n  y_label_font_size 14\n  y_label_on true\n  y_label_units\n  y_label_units_on false\n  y_label_width 0\n  y_major_grid_on false\n  y_major_grid_color RGB(200,220,255)\n  y_major_grid_width 1\n  y_major_interval 2\n  y_major_labels_side bottom\n  y_major_label_rotation 0\n  y_major_tick_color RGB(0,0,0)\n  y_major_tick_length  5\n  y_major_tick_width  2\n  y_minor_grid_on false\n  y_minor_grid_color  RGB(200,220,255)\n  y_minor_grid_width 0.5\n  y_minor_interval 0\n  y_minor_tick_color RGB(0,0,0)\n  y_minor_tick_length 2\n  y_minor_tick_width 1\n  y_range() -10, 10\n  y_num_minor_ticks\n  y_ticks_left_on true\n  y_ticks_right_on false\n  y_ticks_on_window_or_axis left\n  y_max 10\n  y_min -10\n  y_values_on false\n  y_plusminus_on false\n  y_plusminus_color blank\n  x_addlimits_on false\n  x_addlimits_color RGB(0,0,0)\n  y_df_on false\n  y_df_color RGB(0,0,0)\n  y_prefix \"\"\n  y_separator \"\"\n  y_suffix \"\"\n  confidence alpha 0.05\n  data lines width 2\n  Press any key to continue . . .\n  Output:\n\n\n\n  */\n\n", "meta": {"hexsha": "a4215e8af53255562b71df5fb3624b92e51874fc", "size": 9033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/demo_2d_legend_lines_markers.cpp", "max_stars_repo_name": "pabristow/svg_plot", "max_stars_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-03-09T03:23:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:02:07.000Z", "max_issues_repo_path": "example/demo_2d_legend_lines_markers.cpp", "max_issues_repo_name": "pabristow/svg_plot", "max_issues_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-03-05T14:39:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T09:00:33.000Z", "max_forks_repo_path": "example/demo_2d_legend_lines_markers.cpp", "max_forks_repo_name": "pabristow/svg_plot", "max_forks_repo_head_hexsha": "59e06b752acc252498e0ddff560b01fb951cb909", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-11-04T14:36:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:12:03.000Z", "avg_line_length": 27.623853211, "max_line_length": 121, "alphanum_fraction": 0.7212443264, "num_tokens": 2693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.616305730897006}}
{"text": "#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main () {\n    using namespace boost::numeric::ublas;\n    unsigned i;\n\n    vector<double> v (6);\n\n    // populando vetor\n    for (i = 0; i < v.size (); ++ i)\n        v (i) = i;\n\n    std::cout << \"v=\\n\" << v << std::endl;\n\n    // multiplicacao por escalar\n    vector<double> w = 3.0 * v;\n    std::cout << \"w=\\n\" << w << std::endl;\n\n    // soma de vetores\n    vector<double> x = v + w;\n    std::cout << \"x=\\n\" << x << std::endl;\n\n}", "meta": {"hexsha": "972a944b8ddd6d5b41222c4ec8a65d68693e5200", "size": 513, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ublas-vector/main.cpp", "max_stars_repo_name": "dayanyrec/study-boost", "max_stars_repo_head_hexsha": "8f5f9d1880c4e4601d8a468f77012be1f1a6ac9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ublas-vector/main.cpp", "max_issues_repo_name": "dayanyrec/study-boost", "max_issues_repo_head_hexsha": "8f5f9d1880c4e4601d8a468f77012be1f1a6ac9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ublas-vector/main.cpp", "max_forks_repo_name": "dayanyrec/study-boost", "max_forks_repo_head_hexsha": "8f5f9d1880c4e4601d8a468f77012be1f1a6ac9d", "max_forks_repo_licenses": ["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.375, "max_line_length": 42, "alphanum_fraction": 0.5263157895, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.616305723102934}}
{"text": "#include \"cellogram/point_source_detection.h\"\n\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <Eigen/Dense>\n#include <igl/list_to_matrix.h>\n#include <igl/Timer.h>\n\nbool load_img(const std::string & path, Eigen::MatrixXd &res)\n{\n\tstd::fstream file;\n\tfile.open(path.c_str());\n\n\tif (!file.good())\n\t{\n\t\tstd::cerr << \"Failed to open file : \" << path << std::endl;\n\t\tfile.close();\n\t\treturn false;\n\t}\n\n\n\tstd::string s;\n\tstd::vector<std::vector<double>> matrix;\n\n\twhile (getline(file, s))\n\t{\n\t\tstd::stringstream input(s);\n\t\tdouble temp;\n\t\tmatrix.emplace_back();\n\n\t\tstd::vector<double> &currentLine = matrix.back();\n\n\t\twhile (input >> temp)\n\t\t\tcurrentLine.push_back(temp);\n\t}\n\n\tif (!igl::list_to_matrix(matrix, res))\n\t{\n\t\tstd::cerr << \"list to matrix error\" << std::endl;\n\t\tfile.close();\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n\nint main(int argc, char** argv) {\n\tEigen::MatrixXd img;\n\tconst double sigma = 2;\n\tEigen::MatrixXd V;\n\tEigen::MatrixXd V_std;\n\tEigen::VectorXd pval_Ar;\n\n\tconst std::string root = DATA_DIR;\n\n\tload_img(root + \"1-1.txt\", img);\n\n\tdouble min = img.minCoeff();\n\tdouble max = img.maxCoeff();\n\n\tEigen::MatrixXd imgNorm;\n\n\timgNorm = (img.array() - min) / (max - min);\n\n\tcellogram::DetectionParams params;\n\n\tcellogram::point_source_detection(imgNorm, sigma, 0.5, V, params);\n\n\tstd::cout << V << std::endl;\n\tstd::cout << params.std_x << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "a739e0a35972575e6568a264ee8210b35c3851ae", "size": 1403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/pts_detection.cpp", "max_stars_repo_name": "cellogram/cellogram", "max_stars_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-09-25T15:04:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T08:17:44.000Z", "max_issues_repo_path": "misc/pts_detection.cpp", "max_issues_repo_name": "cellogram/cellogram", "max_issues_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/pts_detection.cpp", "max_forks_repo_name": "cellogram/cellogram", "max_forks_repo_head_hexsha": "d378e9b87e56b879b2fb352b08b0fed714481968", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-14T01:36:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-11T20:27:57.000Z", "avg_line_length": 18.4605263158, "max_line_length": 67, "alphanum_fraction": 0.6614397719, "num_tokens": 388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.616305717736465}}
{"text": "/* Tags: Delaunay Triangulation, Union-Find, Connected Components, Closest Neighbor \n\n  Key idea: Close relation to Golden Eye problem:\n            1:1 correspondence between points being connected (connected components in EMST)\n                <==>\n                we can move between the disks of the points\n                (for a radius >= 2 * minimal distance betw. them) \n            Can copy code from the EMST template, and adapt:\n            * two UF structures, one for given initial radius with s,\n              one for radius needed to get k\n            * for first problem (max bones):\n              for each component of tree, store the number of bones reachable\n              (i.e. 4 *distance to closest point <= s)\n              This can be done via a simple array, as UF comp. have index <= n\n              Upon merging, add together the numbers. At the end (when all edges <= s considerd)\n              look for max\n            * for second problem (min. radius b to get k):\n              Have additional edges from each bone to closest point with edge weight 4 * dist.\n              Sort as usual, then do same procedure as above (i.e. UF) until one comp has >= k bones\n              Then the latest edge considered has minimal radius needed\n\n              Why 4 * dist? ->\n              for correct b, need to consider radius over all edges, but for edges between trees\n              we have that dist = radius / 2. When we sort, we would thus mix up scale\n*/\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_2.h>\n#include <boost/pending/disjoint_sets.hpp>\n#include <vector>\n#include <tuple>\n#include <algorithm>\n#include <iostream>\n\n// Epic kernel is enough, no constructions needed, provided the squared distance\n// fits into a double (!)\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n// we want to store an index with each vertex\ntypedef std::size_t                                            Index;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<Index,K>   Vb;\ntypedef CGAL::Triangulation_face_base_2<K>                     Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb>            Tds;\ntypedef CGAL::Delaunay_triangulation_2<K,Tds>                  Delaunay;\n\n// As edges are not explicitly represented in the triangulation, we extract them\n// from the triangulation to be able to sort and process them. We store the\n// indices of the two endpoints, first the smaller, second the larger, and third\n// the squared length of the edge. The i-th entry, for i=0,... of a tuple t can\n// be accessed using std::get<i>(t).\ntypedef std::tuple<Index,Index,double> Edge;\ntypedef std::vector<Edge> EdgeV;\n\nstd::ostream& operator<<(std::ostream& o, const Edge& e) {\n  return o << std::get<0>(e) << \" \" << std::get<1>(e) << \" \" << std::get<2>(e);\n}\n\nvoid testcase() {\n  Index n, m, k;\n  long s;\n  std::cin >> n >> m >> s >> k;\n\n  // read points: first, we read all points and store them into a vector,\n  // together with their indices\n  typedef std::pair<K::Point_2,Index> IPoint;\n  std::vector<IPoint> oak_trees;\n  oak_trees.reserve(n);\n  for (Index i = 0; i < n; ++i) {\n    int x, y;\n    std::cin >> x >> y;\n    oak_trees.emplace_back(K::Point_2(x, y), i);\n  }\n  Delaunay t;\n  t.insert(oak_trees.begin(), oak_trees.end());\n\n  // store the number of bones that are in reach for each oak tree\n  std::vector<Index> bones_per_comp(n, 0);\n  std::vector<IPoint> points;\n  points.reserve(m);\n  EdgeV edges_ext;\n  edges_ext.reserve(m); // there can be no more in a planar graph\n\n  for (Index i = 0; i < m; ++i) {\n    int x, y;\n    std::cin >> x >> y;\n    auto p = K::Point_2(x, y);\n    auto v = t.nearest_vertex(p);\n    double dist = CGAL::squared_distance(p, v->point());\n    if(4 * K::FT(dist) <= s) {\n      bones_per_comp[v->info()] += 1;\n    }\n    points.emplace_back(p, i);\n    edges_ext.emplace_back(v->info(), n + i, 4 * dist);\n  }\n\n  // extract edges and sort by (squared) length\n  // This step takes O(n log n) time (for the sorting).\n  EdgeV edges;\n  edges.reserve(3*n + m); // there can be no more in a planar graph\n\n  for (auto e = t.finite_edges_begin(); e != t.finite_edges_end(); ++e) {\n    Index i1 = e->first->vertex((e->second+1)%3)->info();\n    Index i2 = e->first->vertex((e->second+2)%3)->info();\n    // ensure smaller index comes first\n    if (i1 > i2) std::swap(i1, i2);\n    edges.emplace_back(i1, i2, t.segment(e).squared_length());\n  }\n  std::sort(edges.begin(), edges.end(),\n        [](const Edge& e1, const Edge& e2) -> bool {\n          return std::get<2>(e1) < std::get<2>(e2);\n            });\n\n  boost::disjoint_sets_with_storage<> uf(n);\n  Index n_components = n;\n  // ... and process edges in order of increasing length\n  for (EdgeV::const_iterator e = edges.begin(); e != edges.end(); ++e) {\n    // determine components of endpoints\n    Index c1 = uf.find_set(std::get<0>(*e));\n    Index c2 = uf.find_set(std::get<1>(*e));\n    double squared_dist = std::get<2>(*e);\n    if(squared_dist <= s) {\n        if (c1 != c2) {\n            // this edge connects two different components => merge number of bones\n            auto b1 = bones_per_comp[c1];\n            auto b2 = bones_per_comp[c2];\n            bones_per_comp[c1] = 0;\n            bones_per_comp[c2] = 0;\n            uf.link(c1, c2);\n            Index c3 = uf.find_set(std::get<0>(*e));\n            bones_per_comp[c3] = b1 + b2;\n            if (--n_components == 1) break;\n        }\n    } else break;\n  }\n\n  std::cout << *std::max_element(bones_per_comp.begin(), bones_per_comp.end()) << \" \";\n  \n  // find minimal readius for k bones\n  // by considering edges to bones as well\n  // -- for code simplicity, redo whole union-find procedure\n  std::vector<Index> bones(n + m, 0);\n  for (Index i = 0; i < m; ++i) {\n    edges.push_back(edges_ext[i]);\n    bones[n + i] = 1;\n  }\n  std::sort(edges.begin(), edges.end(),\n        [](const Edge& e1, const Edge& e2) -> bool {\n          return std::get<2>(e1) < std::get<2>(e2);\n            });\n\n  boost::disjoint_sets_with_storage<> uf_ext(n + m);\n  K::FT b_squared = 0;\n  // ... and process edges in order of increasing length\n  for (EdgeV::const_iterator e = edges.begin(); e != edges.end(); ++e) {\n    // determine components of endpoints\n    Index i1 = std::get<0>(*e);\n    Index i2 = std::get<1>(*e);\n    Index c1 = uf_ext.find_set(i1);\n    Index c2 = uf_ext.find_set(i2);\n    double squared_dist = std::get<2>(*e);\n    if (c1 != c2) {\n        // this edge connects two different components => merge number of bones\n        auto b1 = bones[c1];\n        auto b2 = bones[c2];\n        bones[c1] = 0;\n        bones[c2] = 0;\n        uf_ext.link(c1, c2);\n        Index c3 = uf_ext.find_set(std::get<0>(*e));\n        bones[c3] = b1 + b2;\n        if (b1 + b2 >= k) {\n          b_squared = squared_dist;\n          break;\n        }\n    }\n  }\n  std::cout << b_squared << \"\\n\";\n}\n\nint main() \n{\n  std::ios_base::sync_with_stdio(false);\n  std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(0);\n  std::size_t t;\n  for (std::cin >> t; t > 0; --t) testcase();\n  return 0;\n}\n", "meta": {"hexsha": "af2421e119f0374e34bbd51dc027fad14e3a959b", "size": 7193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week11-idefix/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/week11-idefix/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/week11-idefix/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2606382979, "max_line_length": 100, "alphanum_fraction": 0.6071180314, "num_tokens": 2013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6163057123699959}}
{"text": "#include <iostream>\n#include <math.h>\n\n#include <boost/format.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/grid_graph.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/reverse_graph.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <LEDA/core/string.h>\n#include <LEDA/system/misc.h>\n//#include <LEDA/graph/max_flow.h>\n\n\n\n\nusing namespace boost;\nusing namespace std;\n\n\n//Type & Struct Definitions ___________________\n\n// Bundled properties for graph\nstruct bundleVertex {\n    int id;\n    int excess;\n    int distance;\n};\n\nstruct bundleEdge {\n    int residual;\n};\n\nstruct bundleGraph;\n\n\n// Define graph type\ntypedef adjacency_list<vecS, vecS, bidirectionalS, bundleVertex, bundleEdge, bundleGraph> Graph;\n\n//Define graph traits type\ntypedef graph_traits<Graph> Traits;\n\n//Define descriptor for vertices\ntypedef Traits::vertex_descriptor Vertex;\n//Define descriptor for edges\ntypedef Traits::edge_descriptor Edge;\n\n\nstruct bundleGraph {\n    Vertex source;\n    Vertex sink;\n};\n\n\n// Function Declarations ___________________\n\n// Create example graph used for visualising\nGraph createExampleGraph();\n// Print results to terminal\nvoid printResults(Graph &G);\n// Create graph visualisation dot language file\nvoid visualise(Graph &G);\n\n\n\n\n//Excess Scale functions -------\nvoid ExcessScaleMaxFlow(Graph &G, Vertex source, Vertex sink);\n\n// Handle preprocessing operations\nvoid preprocess(Graph &G, Vertex source, Vertex sink);\n// Calculate initial delta = 2 ^ log(maxCapacity)\nfloat calcInitialDelta(Graph &G);\n// Utility function for selecting node with smallest distance among nodes with large excess\nVertex selectNode(Graph &G, Vertex source, Vertex sink, float delta);\n// implements push of flow or relabel of distance of current node\nvoid pushRelabel(Graph &G, Vertex current, float delta);\n\n\n\n// Custom Property Writer for Graphviz\ntemplate <class IdMap, class ExcessMap, class DistanceMap>\nclass vertex_writer {\npublic:\n    vertex_writer(IdMap i, ExcessMap e, DistanceMap d) : im(i), em(e), dm(d) {}\n    template <class Vertex>\n    void operator()(ostream &out, const Vertex& v) const {\n        out << \"[label=\\\"ID:\" << im[v] << \"\\nExcess: \"<< em[v] <<\"\\nDistance: \"<< dm[v] << \"\\\"]\";\n    }\nprivate:\n    IdMap im;\n    ExcessMap em;\n    DistanceMap dm;\n};\n// Function for passing in the maps to custom property writer\ntemplate <class IdMap, class ExcessMap, class DistanceMap>\ninline vertex_writer<IdMap, ExcessMap, DistanceMap>\nmake_vertex_writer(IdMap i, ExcessMap e, DistanceMap d) {\n    return vertex_writer<IdMap, ExcessMap, DistanceMap>(i, e, d);\n}\n\n\n\n\n\nint main() {\n\n    Graph exampleG = createExampleGraph();\n\n    Vertex source = exampleG[graph_bundle].source;\n    Vertex sink = exampleG[graph_bundle].sink;\n\n\n\n\n\n    /*Algorithm exectution and timing*/\n\n    cout<<\"\\t\\tEXCESS SCALE MAX FLOW ALGORITHM\"<<endl;\n    cout << \"Case:\\tExample Graph\"<<endl;\n    float time = leda::used_time();\n    ExcessScaleMaxFlow(exampleG, source, sink);\n    cout << \"\\nImplementation Time: \" << leda::used_time(time) << endl;\n    //MAX_FLOW_T(const graph& G, node s, node t, const edge_array< NT> & cap)\n    //cout << \"BGL Time: \" << leda::used_time(time) << endl<<endl;\n\n\n\n    visualise(exampleG);  // dot -Tpng ./cmake-build-debug/graph.dot > exampleFinal.png\n\n\n    return 0;\n}\n\n\n\n// Function Definitions ___________________\nGraph createExampleGraph() {\n\n    // Graph instantiation\n    Graph G;\n\n    // Graph creation\n    Vertex v1 = add_vertex(bundleVertex{1, 0, 2}, G);\n    Vertex v2 = add_vertex(bundleVertex{2, 0, 1}, G);\n    Vertex v3 = add_vertex(bundleVertex{3, 0, 1}, G);\n    Vertex v4 = add_vertex(bundleVertex{4, 0, 0}, G);\n\n    add_edge(v1, v2, bundleEdge{2}, G);\n    add_edge(v1, v3, bundleEdge{4}, G);\n    add_edge(v2, v3, bundleEdge{3}, G);\n    add_edge(v2, v4, bundleEdge{1}, G);\n    add_edge(v3, v4, bundleEdge{5}, G);\n\n    G[graph_bundle].source = v1;\n    G[graph_bundle].sink = v4;\n\n\n    return G;\n}\n\nvoid printResults(Graph &G) {\n\n    print_graph(G, get(&bundleVertex::id, G));\n\n    Graph::vertex_iterator vertexIt, vertexEnd;\n    tie(vertexIt, vertexEnd) = vertices(G);\n    cout << endl << endl;\n    for (; vertexIt != vertexEnd; ++vertexIt) {\n        cout << \"excess of node \"<< G[*vertexIt].id << \" : \" << G[*vertexIt].excess << endl;\n    }\n\n    //TODO: MAX FLOW IS EXCESS VALUE AT SINK...handle that\n}\n\nvoid visualise(Graph &G) {\n    ofstream dot(\"graph.dot\");\n    write_graphviz(dot, G, make_vertex_writer(get(&bundleVertex::id, G),\n                                              get(&bundleVertex::excess, G),\n                                              get(&bundleVertex::distance, G)),\n                           make_label_writer(get(&bundleEdge::residual, G)));\n}\n\n\n\n\nvoid ExcessScaleMaxFlow(Graph &G, Vertex source, Vertex sink) {\n\n    // Preprocessing\n    preprocess(G, source, sink);\n\n    // Calculate initial delta = 2 ^ log(maxCapacity)\n    float delta = calcInitialDelta(G);\n\n    // Core update loop\n    while(delta >= 1) {\n\n        // select node with smallest distance among nodes with large excess\n        Vertex currentNode = selectNode(G, source, sink, delta);\n        while(currentNode != 0) {\n            // push flow or relabel distance of current node\n            pushRelabel(G, currentNode, delta);\n            // select another node from updated graph\n            currentNode = selectNode(G, source, sink, delta);\n        }\n        delta /= 2;  // update delta if no other selectable node\n    }\n\n}\n\nvoid preprocess(Graph &G, Vertex source, Vertex sink) {\n\n    // Store initial distances in this vector\n    std::vector<int> distances(num_vertices(G));\n\n    // Computation of exact distance labels via backward BFS from sink\n    reverse_graph<Graph> R = make_reverse_graph(G);\n    breadth_first_search(R,\n                         sink,\n                         visitor(make_bfs_visitor(record_distances(make_iterator_property_map(distances.begin(),\n                                                                                              get(vertex_index, G)),\n                                                                   on_tree_edge()))));\n    Graph::vertex_iterator vertexIt, vertexEnd;\n    tie(vertexIt, vertexEnd) = vertices(G);\n    for (; vertexIt != vertexEnd; ++vertexIt) {\n        G[*vertexIt].distance = distances[*vertexIt];\n    }\n\n    // Saturate source's adjacent edges\n    Graph::out_edge_iterator outedgeIt, outedgeEnd;\n    tie(outedgeIt, outedgeEnd) = out_edges(source, G);\n    for(; outedgeIt != outedgeEnd; ++outedgeIt) {\n        Vertex src = boost::source(*outedgeIt, G);\n        Vertex target = boost::target(*outedgeIt, G);\n        int saturation = G[*outedgeIt].residual;\n\n        add_edge(target, src, bundleEdge{saturation}, G);  // add reverse of saturated edge\n        remove_edge(*outedgeIt, G); // remove saturated edge\n\n        G[target].excess += saturation;  // update target node's excess property\n    }\n\n    // Update source node's distance label to num_vertices\n    G[source].distance = (int) num_vertices(G);\n}\n\nfloat calcInitialDelta(Graph &G) {\n\n    std::vector<int> capacities(num_edges(G));\n\n    Graph::edge_iterator edgeIt, edgeEnd;\n    tie(edgeIt, edgeEnd) = edges(G);\n    for (; edgeIt!= edgeEnd; ++edgeIt) {\n        capacities.push_back(G[*edgeIt].residual);\n    }\n    int maxCap = *max_element(capacities.begin(), capacities.end());\n    return (float) pow(2, ceil(log2(maxCap)));\n}\n\nVertex selectNode(Graph &G, Vertex source, Vertex sink, float delta) {\n\n    double min = std::numeric_limits<double>::infinity();\n    Vertex minNode = 0;\n\n    Graph::vertex_iterator vertexIt, vertexEnd;\n    tie(vertexIt, vertexEnd) = vertices(G);\n    for (; vertexIt != vertexEnd; ++vertexIt) {\n\n        // if node has large excess (cannot be source or sink)\n        if(G[*vertexIt].excess >= delta/2 && *vertexIt != source && *vertexIt != sink) {\n            if(G[*vertexIt].excess < min) {\n                min = G[*vertexIt].excess;\n                minNode = *vertexIt;\n            }\n        }\n    }\n    //return node with min excess amongst nodes with large excess\n    return minNode;\n}\n\nvoid pushRelabel(Graph &G, Vertex current, float delta) {\n\n    // stores candidate distances of adj nodes for raising current node's distance label to\n    std::vector<int> adjDist;\n\n    Graph::out_edge_iterator outedgeIt, outedgeEnd;\n    tie(outedgeIt, outedgeEnd) = out_edges(current, G);\n    for(; outedgeIt != outedgeEnd; ++outedgeIt) {\n        Vertex target = boost::target(*outedgeIt, G);\n\n        // if network contains an admissable arc\n        if(G[current].distance == G[target].distance + 1) {\n            int pushFlow = 0;\n            if(delta - G[target].excess > 0) {\n                pushFlow = std::min({G[current].excess, G[*outedgeIt].residual, (int) delta - G[target].excess});  // last arg ensures that excess doesnt exceed delta\n            } else {\n                pushFlow = std::min(G[current].excess, G[*outedgeIt].residual);\n            }\n\n            // implement Push\n            G[current].excess -= pushFlow;\n            G[target].excess += pushFlow;\n            G[*outedgeIt].residual -= pushFlow;\n            if(G[*outedgeIt].residual == 0)  // saturation\n                remove_edge(*outedgeIt, G); // remove saturated edge\n            bool found;\n            Edge reverse;\n            boost::tie(reverse, found) = edge(target, current, G);\n            if(found) {\n                G[reverse].residual += pushFlow;\n            } else {\n                add_edge(target, current, bundleEdge{pushFlow}, G);  // add reverse edge\n            }\n\n            return;\n        } else {\n            if(G[*outedgeIt].residual > 0)\n                adjDist.push_back(G[target].distance + 1);\n        }\n    }\n\n    // implement Relabel\n    int minDist = *min_element(adjDist.begin(), adjDist.end());\n    G[current].distance = minDist;\n\n    return;\n}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "010d8cff77575936b7323ac4799046e10ba91db7", "size": 9975, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Synaesthetic-Nemophilist/Max_Flow_Excess_Scaling_BGL", "max_stars_repo_head_hexsha": "358a1f5dedcdb580636502f2c01ab1172ff2afcb", "max_stars_repo_licenses": ["MIT"], "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": "Synaesthetic-Nemophilist/Max_Flow_Excess_Scaling_BGL", "max_issues_repo_head_hexsha": "358a1f5dedcdb580636502f2c01ab1172ff2afcb", "max_issues_repo_licenses": ["MIT"], "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": "Synaesthetic-Nemophilist/Max_Flow_Excess_Scaling_BGL", "max_forks_repo_head_hexsha": "358a1f5dedcdb580636502f2c01ab1172ff2afcb", "max_forks_repo_licenses": ["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.3382352941, "max_line_length": 166, "alphanum_fraction": 0.6318796992, "num_tokens": 2431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782012, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6162404428058685}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\ntypedef std::complex<double>      cdouble;\n\ntemplate <typename Matrix>\nvoid test(Matrix& A, const char* name)\n{\n    //using mtl::conj;\n    const unsigned                    xd= 2, yd= 5, n= xd * yd;\n    A.change_dim(n, n);\n    laplacian_setup(A, xd, yd); \n\n    A*= cdouble(1, -1);\n    std::cout << name << \"\\nconj(A) is\\n\" << with_format(mtl::conj(A), 7, 1) << \"\\n\";\n\n    mtl::dense_vector<cdouble> x(n),Ax(n);\n    x=cdouble(1,2);\n    \n    // Ax= mtl::mat::conj(A) * x;\n    Ax= mtl::conj(A) * x;\n    std::cout << \"conj(A) * x is \" << Ax << \"\\n\";\n    \n    Ax=trans(A) * x;\n    std::cout << \"trans(A) * x is \" << Ax << \"\\n\";\n\n    Ax=hermitian(A) * x;\n    std::cout << \"hermitian(A) * x is \" << Ax << \"\\n\";\n}\n\n\nint main(int, char**)\n{\n    mtl::compressed2D<cdouble>             crc;\n\n    test(crc, \"Compressed row major complex\");\n\n    return 0;\n}\n", "meta": {"hexsha": "2d8867aff826825c4688d2ad30501b69869fd72a", "size": 1347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/conj_mult_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/conj_mult_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/conj_mult_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 25.9038461538, "max_line_length": 94, "alphanum_fraction": 0.577579807, "num_tokens": 420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971190859164, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6161188569122963}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2010-2011 Gael Guennebaud <gael.guennebaud@inria.fr>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include \"lapack_common.h\"\r\n#include <Eigen/Cholesky>\r\n\r\n// POTRF computes the Cholesky factorization of a real symmetric positive definite matrix A.\r\nEIGEN_LAPACK_FUNC(potrf,(char* uplo, int *n, RealScalar *pa, int *lda, int *info))\r\n{\r\n  *info = 0;\r\n        if(UPLO(*uplo)==INVALID) *info = -1;\r\n  else  if(*n<0)                 *info = -2;\r\n  else  if(*lda<std::max(1,*n))  *info = -4;\r\n  if(*info!=0)\r\n  {\r\n    int e = -*info;\r\n    return xerbla_(SCALAR_SUFFIX_UP\"POTRF\", &e, 6);\r\n  }\r\n\r\n  Scalar* a = reinterpret_cast<Scalar*>(pa);\r\n  MatrixType A(a,*n,*n,*lda);\r\n  int ret;\r\n  if(UPLO(*uplo)==UP) ret = internal::llt_inplace<Scalar, Upper>::blocked(A);\r\n  else                ret = internal::llt_inplace<Scalar, Lower>::blocked(A);\r\n\r\n  if(ret>=0)\r\n    *info = ret+1;\r\n  \r\n  return 0;\r\n}\r\n\r\n// POTRS solves a system of linear equations A*X = B with a symmetric\r\n// positive definite matrix A using the Cholesky factorization\r\n// A = U**T*U or A = L*L**T computed by DPOTRF.\r\nEIGEN_LAPACK_FUNC(potrs,(char* uplo, int *n, int *nrhs, RealScalar *pa, int *lda, RealScalar *pb, int *ldb, int *info))\r\n{\r\n  *info = 0;\r\n        if(UPLO(*uplo)==INVALID) *info = -1;\r\n  else  if(*n<0)                 *info = -2;\r\n  else  if(*nrhs<0)              *info = -3;\r\n  else  if(*lda<std::max(1,*n))  *info = -5;\r\n  else  if(*ldb<std::max(1,*n))  *info = -7;\r\n  if(*info!=0)\r\n  {\r\n    int e = -*info;\r\n    return xerbla_(SCALAR_SUFFIX_UP\"POTRS\", &e, 6);\r\n  }\r\n\r\n  Scalar* a = reinterpret_cast<Scalar*>(pa);\r\n  Scalar* b = reinterpret_cast<Scalar*>(pb);\r\n  MatrixType A(a,*n,*n,*lda);\r\n  MatrixType B(b,*n,*nrhs,*ldb);\r\n\r\n  if(UPLO(*uplo)==UP)\r\n  {\r\n    A.triangularView<Upper>().adjoint().solveInPlace(B);\r\n    A.triangularView<Upper>().solveInPlace(B);\r\n  }\r\n  else\r\n  {\r\n    A.triangularView<Lower>().solveInPlace(B);\r\n    A.triangularView<Lower>().adjoint().solveInPlace(B);\r\n  }\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "741a09941dc55dd238c3c2cb8157eadabfce071b", "size": 2267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen/lapack/cholesky.cpp", "max_stars_repo_name": "subond/tools", "max_stars_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigen/lapack/cholesky.cpp", "max_issues_repo_name": "subond/tools", "max_issues_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen/lapack/cholesky.cpp", "max_forks_repo_name": "subond/tools", "max_forks_repo_head_hexsha": "05b93e6c78eab65ef6587e684303b12c686a3480", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-04T15:41:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-04T15:41:53.000Z", "avg_line_length": 31.0547945205, "max_line_length": 120, "alphanum_fraction": 0.5990295545, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6161188518604267}}
{"text": "/* =========== */\n/*  Libraries  */\n/* =========== */\n/* System Libraries */\n#include <iostream>\n#include <chrono>\n\n/* OpenCV Libraries */\n#include <opencv2/opencv.hpp>\n// #include <opencv2/core/core.hpp>\n// #include <opencv2/features2d/features2d.hpp>\n// #include <opencv2/highgui/highgui.hpp>\n// #include <opencv2/calib3d/calib3d.hpp>\n\n/* Sophus Libraries */\n#include <sophus/se3.hpp>\n\n/* Boost Libraries */\n#include <boost/format.hpp>\n\n/* Pangolin Libraries */\n#include <pangolin/pangolin.h>\n\n/* Custom Libraries */\n#include \"../../../common/libUtils_basic.h\"\n#include \"../../../common/libUtils_eigen.h\"\n#include \"../../../common/libUtils_opencv.h\"\n\nusing namespace std;\nusing namespace cv;\n\n/* Global Variables */\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\n\nstring left_file = \"../../images/left.png\"; // FIXME: I think this image is the 000000.png\nstring disparity_file = \"../../images/disparity.png\";\nboost::format fmt_others(\"../../images/%06d.png\"); // Other files\n\n// useful typedefs\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\ntypedef Eigen::Matrix<double, 2, 6> Matrix26d;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n// Camera Intrinsics\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\ndouble b = 0.573; // Baseline (Stereo Camera)\n\n/* =================== */\n/*  Class Declaration  */\n/* =================== */\n\n/**\n * @brief Class for accumulate Jacobians in parallel\n * \n */\nclass JacobianAccumulator {\npublic:\n    // Constructor\n    JacobianAccumulator(\n        const cv::Mat &img1_,\n        const cv::Mat &img2_,\n        const VecVector2d &px_ref_,\n        const vector<double> depth_ref_, //FIXME: Use &?\n        Sophus::SE3d &T21_) : img1(img1_), img2(img2_), px_ref(px_ref_), depth_ref(depth_ref_), T21(T21_)\n    {\n        p2_proj = VecVector2d(px_ref.size(), Eigen::Vector2d(0, 0));\n    }\n\n    /* Accumulate jacobians in a range */\n    void accumulate_jacobian(const cv::Range &range);\n\n    /* Get Hessian Matrix */\n    Matrix6d getHessian() const { return H; }\n\n    /* Get Bias Vector */\n    Vector6d getBias() const { return b; }\n\n    /* Get Total Cost */\n    double getTotalCost() const { return cost; }\n\n    /* Get Projected Points */\n    VecVector2d getProjectedPoints() const { return p2_proj; }\n\n    /* Reset H, b, and cost */\n    void reset() {\n        H = Matrix6d::Zero();\n        b = Vector6d::Zero();\n        cost = 0.0;\n    }\n\nprivate:\n    const cv::Mat &img1;\n    const cv::Mat &img2;\n    const VecVector2d &px_ref;\n    const vector<double> depth_ref; //FIXME: Use &?\n    Sophus::SE3d &T21;\n\n    VecVector2d p2_proj;            // Projected Points\n    std::mutex hessian_mutex;\n    Matrix6d H = Matrix6d::Zero();\n    Vector6d b = Vector6d::Zero();\n    double cost = 0.0;\n};\n\n/* ===================== */\n/*  Function Prototypes  */\n/* ===================== */\n/**\n * @brief Pose estimation using Direct Method (Multi-layer)\n * \n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationMultiLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref, //FIXME: Use &?\n    Sophus::SE3d &T21);\n\n/**\n * @brief Pose estimation using Direct Method (Single-layer)\n * \n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationSingleLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref, //FIXME: Use &?\n    Sophus::SE3d &T21);\n\n/** Bilinear Interpolation\n * @brief Get a grayscale value from reference image (bilinear interpolation)\n * \n * @param img input image\n * @param x x-coordinate of the center pixel\n * @param y y-coordinate of the center pixel\n * @return the interpolated value of this pixel\n */\ninline float GetPixelValue(const cv::Mat &img, float x, float y) {\n    /* Boundary check */\n    if (x < 0)\n        x = 0; // Avoid negative x-axis coordinates\n    if (y < 0)\n        y = 0; // Avoid negative y-axis coordinates\n    if (x >= img.cols)\n        x = img.cols - 1; // Avoid positive x-axis coordinates outside image width\n    if (y >= img.rows)\n        y = img.rows - 1; // Avoid positive y-axis coordinates outside image height\n\n    uchar *data = &img.data[int(y) * img.step + int(x)];\n\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n\n    return float(\n        (1 - xx) * (1 - yy) * data[0] +\n        xx * (1 - yy) * data[1] +\n        (1 - xx) * yy * data[img.step] +\n        xx * yy * data[img.step + 1]);\n}\n\n/* ====== */\n/*  Main  */\n/* ====== */\n/* This program demonstrates how to implement a sparse direct method of binocular cameras (i.e, vSLAM with Known Depth!). */\nint main(int argc, char **argv) {\n    cout << \"[direct_method] Hello!\" << endl << endl;\n\n    /* Load the images */\n    cv::Mat left_img = cv::imread(left_file, CV_LOAD_IMAGE_GRAYSCALE);\n    cv::Mat disparity_img = cv::imread(disparity_file, CV_LOAD_IMAGE_GRAYSCALE);\n\n    /* Initialization */\n    // Let's randomly pick pixels in the first image and generate some 3D points in the first image's frame\n    cv::RNG rng;\n    int nPoints = 2000;\n    int boarder = 20;\n    VecVector2d pixels_ref;\n    vector<double> depth_ref;\n\n    // Generate pixels in ref and load depth data\n    for (int i = 0; i < nPoints; i++) {\n        // Don't pick pixels close to the boarder\n        int x = rng.uniform(boarder, left_img.cols - boarder);\n        int y = rng.uniform(boarder, left_img.rows - boarder);\n\n        // Use the camera intrinsics parameters to get the depth from the disparity image.\n        // Note: Remember that in OpenCV, the coordinates axes for retriving the pixel value are inverted.\n        int disparity = disparity_img.at<uchar>(y, x); // Disp(x, y)\n        double depth = (fx * b) / disparity;           // D(x, y)\n\n        depth_ref.push_back(depth);           // {D(x, y)_i}\n        pixels_ref.push_back(Vector2d(x, y)); // {[x, y]_i}\n    }\n\n    // Estimates 01~05.png's pose using this information.\n    Sophus::SE3d T_cur_ref;\n\n    for (int i = 1; i < 6; i++) { // [1, 5]\n        cv::Mat img = cv::imread((fmt_others % i).str(), CV_LOAD_IMAGE_GRAYSCALE);\n\n        // Try single layer by uncommenting the following line\n        DirectPoseEstimationSingleLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);\n        // DirectPoseEstimationMultiLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);  //TODO\n    }\n\n    /* --------- */\n    /*  Results  */\n    /* --------  */\n    /* Display Images */\n    // imshow(\"image1\", image1);\n    // imshow(\"image2\", image2);\n    imshow(\"left\", left_img);\n    imshow(\"disparity\", disparity_img);\n    cout << \"\\nPress 'ESC' to exit the program...\" << endl;\n    waitKey(0);\n\n    cout << \"Done.\" << endl;\n\n    return 0;\n}\n\n/* ========================= */\n/*  Function Implementation  */\n/* ========================= */\nvoid DirectPoseEstimationSingleLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref, //FIXME: Use &?\n    Sophus::SE3d &T21){\n\n    /* Initialization */\n    const int iterations = 10;\n    double cost = 0.0, lastCost = 0.0;\n\n    Timer t1 = chrono::steady_clock::now();\n    JacobianAccumulator jaco_accu(img1, img2, px_ref, depth_ref, T21);\n\n    for (int iter = 0; iter < iterations; iter++)\n    {\n        jaco_accu.reset();\n        cv::parallel_for_(cv::Range(0, px_ref.size()), std::bind(&JacobianAccumulator::accumulate_jacobian, &jaco_accu, std::placeholders::_1));\n        Matrix6d H = jaco_accu.getHessian();\n        Vector6d b = jaco_accu.getBias();\n\n        /* ----- Solve! ----- */\n        // Solve the Linear System A*x=b, H(x)*\u2206x = g(x)\n        Vector6d update = H.ldlt().solve(b); // \u2206x = \u03b4\u03be (Lie Algebra)\n        cost = jaco_accu.getTotalCost();\n\n        // Check Solution\n        if (std::isnan(update[0]))\n        {\n            // sometimes occurred when we have a black or white patch and H is irreversible\n            cout << \"update is nan\" << endl;\n            break;\n        }\n\n        /* Stopping Criteria */\n        // If the cost increased, the update was not good, then break.\n        if (iter > 0 && cost > lastCost)\n        { // FIXME: I think the correct one is \"cost >= lastCost\"\n            cout << \"\\ncost: \" << cost << \" >= lastCost: \" << lastCost << \", break!\" << endl;\n            break;\n        }\n\n        /* ----- Update ----- */ // FIXME: Esta parte estava antes dos if acima, mas acredito que o correto seja fazer o update ap\u00f3s os ifs\n        // Left multiply T by a disturbance quantity exp(\u03b4\u03be)\n        T21 = Sophus::SE3d::exp(update) * T21; // Left perturbation\n\n        if (update.norm() < 1e-3)\n        { // Method converged!\n            break;\n        }\n\n        lastCost = cost;\n        cout << \"it: \" << iter << \",\\tcost: \" << std::setprecision(12) << cost << \",\\tupdate: \" << update.transpose() << endl;\n    }\n\n    printMatrix<Matrix4d>(\"T21: \", T21.matrix());\n    Timer t2 = chrono::steady_clock::now();\n\n    printElapsedTime(\"Direct method (Single-layer): \", t1, t2);\n\n    /* Plot the projected pixels */\n    Mat img2_show;\n    cv::cvtColor(img2, img2_show, CV_GRAY2BGR);\n    VecVector2d projection = jaco_accu.getProjectedPoints();\n\n    for (size_t i = 0; i < px_ref.size(); ++i)\n    {                               // FIXME: pq ++i, e n\u00e3o i++\n        auto p_ref = px_ref[i];     // p1_i\n        auto p_cur = projection[i]; // p2^_i\n\n        if (p_cur[0] > 0 && p_cur[1] > 0)\n        { // x, y\n            cv::circle(img2_show, cv::Point2f(p_cur[0], p_cur[1]), 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_show, cv::Point2f(p_ref[0], p_ref[1]), cv::Point2f(p_cur[0], p_cur[1]), cv::Scalar(0, 250, 0));\n        }\n    }\n    cv::imshow(\"Current\", img2_show);\n    cv::waitKey();\n}\n\nvoid JacobianAccumulator::accumulate_jacobian(const cv::Range &range) { // cv::Range(0, px_ref.size())\n    /* Parameters */\n    const int half_patch_size = 1;\n    int cnt_good = 0;\n    Matrix6d hessian = Matrix6d::Zero();\n    Vector6d bias = Vector6d::Zero();\n    double cost_tmp = 0;\n\n    for (size_t i = range.start; i < range.end; i++) {\n        /* Compute the projection in the second image */\n        Eigen::Vector3d x1_ref = Eigen::Vector3d((px_ref[i][0] - cx) / fx, (px_ref[i][1] - cy) / fy, 1);  // p1_i->x1_i, x1 = [X/Z, Y/Z, 1]\n        Eigen::Vector3d point_ref = depth_ref[i] * x1_ref;                                                // P1_i = [X, Y, Z]\n        Eigen::Vector3d point_cur = T21 * point_ref;                                                      // P2^_i = T21*.P1_i\n\n        if (point_cur[2] < 0) // invalid depth\n            continue;\n\n        float u = fx * point_cur[0] / point_cur[2] + cx; // u = fx*(X/Z)+cx\n        float v = fy * point_cur[1] / point_cur[2] + cy; // v = fy*(Y/Z)+cy\n\n        if (u < half_patch_size || u > img2.cols - half_patch_size ||\n            v < half_patch_size || v > img2.rows - half_patch_size)\n            continue;\n\n        p2_proj[i] = Eigen::Vector2d(u, v); // p2^ = [u, v]\n        double X = point_cur[0], Y = point_cur[1], Z = point_cur[2],\n               Z2 = Z * Z, Z_inv = 1.0 / Z, Z2_inv = Z_inv * Z_inv;\n\n        cnt_good++;\n\n        // and compute error and jacobian\n        for (int x = -half_patch_size; x <= half_patch_size; x++)\n            for (int y = -half_patch_size; y <= half_patch_size; y++)\n            {\n                double error =  GetPixelValue(img1, px_ref[i][0] + x, px_ref[i][1] + y) -\n                                GetPixelValue(img2, u + x, v + y);\n\n                Eigen::Vector2d J_img_pixel; // \u2202I2/\u2202u\n                Matrix26d J_pixel_xi;        // \u2202u/\u2202\u03b4\u03be\n\n                J_img_pixel = Eigen::Vector2d(\n                    0.5 * (GetPixelValue(img2, u + 1 + x, v + y) - GetPixelValue(img2, u - 1 + x, v + y)),\n                    0.5 * (GetPixelValue(img2, u + x, v + 1 + y) - GetPixelValue(img2, u + x, v - 1 + y)));\n\n                J_pixel_xi(0, 0) = fx * Z_inv;\n                J_pixel_xi(0, 1) = 0;\n                J_pixel_xi(0, 2) = -fx * X * Z2_inv;\n                J_pixel_xi(0, 3) = -fx * X * Y * Z2_inv;\n                J_pixel_xi(0, 4) = fx + fx * X * X * Z2_inv;\n                J_pixel_xi(0, 5) = -fx * Y * Z_inv;\n\n                J_pixel_xi(1, 0) = 0;\n                J_pixel_xi(1, 1) = fy * Z_inv;\n                J_pixel_xi(1, 2) = -fy * Y * Z2_inv;\n                J_pixel_xi(1, 3) = -fy - fy * Y * Y * Z2_inv;\n                J_pixel_xi(1, 4) = fy * X * Y * Z2_inv;\n                J_pixel_xi(1, 5) = fy * X * Z_inv;\n\n                // Total Jacobian, J = \u2212(\u2202I2/\u2202u)*(\u2202u/\u2202\u03b4\u03be)\n                Vector6d J = -1.0 * (J_img_pixel.transpose() * J_pixel_xi).transpose(); // 6x1\n\n                hessian += J * J.transpose();\n                bias += -error * J;\n                cost_tmp += error * error;\n            }\n    }\n\n    if (cnt_good)\n    {\n        // Set Hessian, bias and cost_tmp\n        unique_lock<mutex> lck(hessian_mutex);\n        H += hessian;\n        b += bias;\n        cost += cost_tmp / cnt_good;\n    }\n}", "meta": {"hexsha": "09d11f7c03a940c291eae3316c4fc67cbe83059b", "size": 13035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nicolas/ch8/optical_flow_book_examples/src/direct_method.cpp", "max_stars_repo_name": "nicolasrosa-forks/slambook2", "max_stars_repo_head_hexsha": "9cae572378fc5da758b6404e45d443b0bde71853", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nicolas/ch8/optical_flow_book_examples/src/direct_method.cpp", "max_issues_repo_name": "nicolasrosa-forks/slambook2", "max_issues_repo_head_hexsha": "9cae572378fc5da758b6404e45d443b0bde71853", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nicolas/ch8/optical_flow_book_examples/src/direct_method.cpp", "max_forks_repo_name": "nicolasrosa-forks/slambook2", "max_forks_repo_head_hexsha": "9cae572378fc5da758b6404e45d443b0bde71853", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-15T14:55:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T14:55:53.000Z", "avg_line_length": 33.4230769231, "max_line_length": 144, "alphanum_fraction": 0.5594936709, "num_tokens": 3800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6161188357893774}}
{"text": "/*\nCopyright 2012-2018 Tamas Bolner\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n  http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n#include <cinttypes>\n#include <iostream>\n#include <Eigen/Dense>\n#include \"SimplexSolver.h\"\n#include \"exception.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n    MatrixXd constraints(3, 3);\n    VectorXd objectiveFunction(2);\n    \n    try {\n        /*\n            Maximization problem\n        */\n        objectiveFunction <<    1,\n                                2;\n\n        constraints <<      2,    3,    34,\n                            1,    5,    45,\n                            1,    0,    15;\n\n        \n        SimplexSolver solver1(SIMPLEX_MAXIMIZE, objectiveFunction, constraints);\n\n        if (solver1.hasSolution()) {\n            cout << \"The maximum is: \" << solver1.getOptimum() << endl;\n            cout << \"The solution is: \" << solver1.getSolution().transpose() << endl;\n        } else {\n            cout << \"The linear problem has no solution.\" << endl;\n        }\n\n        cout << endl;\n        \n        /*\n            Minimization problem\n        */\n        objectiveFunction <<    3,\n                                4;\n\n        constraints <<      2,    1,    8,\n                            1,    2,    13,\n                            1,    5,    16;\n        \n        SimplexSolver solver2(SIMPLEX_MINIMIZE, objectiveFunction, constraints);\n\n        if (solver2.hasSolution()) {\n            cout << \"The minimum is: \" << solver2.getOptimum() << endl;\n            cout << \"The solution is: \" << solver2.getSolution().transpose() << endl;\n        } else {\n            cout << \"The linear problem has no solution.\" << endl;\n        }\n    } catch (const FException &ex) {\n        ex.Print();\n        return 1;\n    }\n    \n    return 0;\n}\n", "meta": {"hexsha": "7bcc12bf912cbca9cbbc89a0ac76f7fe9e912857", "size": 2228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "bolner/SimplexSolver", "max_stars_repo_head_hexsha": "a4fb1cdc71c312f76d0712fb5d24bdf137f55b04", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2017-09-09T14:29:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T01:38:20.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "bolner/SimplexSolver", "max_issues_repo_head_hexsha": "a4fb1cdc71c312f76d0712fb5d24bdf137f55b04", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-27T09:57:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-27T13:32:56.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "bolner/SimplexSolver", "max_forks_repo_head_hexsha": "a4fb1cdc71c312f76d0712fb5d24bdf137f55b04", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-02-17T07:05:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T08:36:06.000Z", "avg_line_length": 28.2025316456, "max_line_length": 85, "alphanum_fraction": 0.5453321364, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7981867801399695, "lm_q1q2_score": 0.6160752763121425}}
{"text": "/*\n* This program will read a .csv file containing the data of a polynomial\n* classification equation system to then exctact all its data. Its input\n* data will be saved into the matrix \"X\" and its output data into the\n* matrix \"Y\". Subsequently, a RBF Kernel support vector machine\n* classification method will be applied to obtain the best fitting\n* model for such data. Then, some evaluation metrics will be applied.\n* Next, a new .csv file will be created to save the results obtained\n* with the evaluation metrics. Finally, a plot of the predicted data by\n* the obtained model with respect to the actual data, will be plotted\n* and saved into a .png file. Both the .csv file and this .png file\n* will serve for further comparations and validation purposes.\n*\n* URL TO DOWNLOAD THE DLIB LIBRARY VERSION 19.22:\n* https://bit.ly/3DS3fBx\n*\n* DOCUMENTATION TO LEARN HOW TO COMPILE THE DLIB LIBRARY:\n* https://bit.ly/3xmF2k5\n* NOTE: I compiled on Linux From Command Line (see the makefile that is located under the same directory as this file).\n*\n* DOCUMENTATION TO LEARN ABOUT THE C FORMULATION OF A SUPPORT VECTOR MACHINE AS PROVIDED BY THE DLIB LIBRARY:\n* https://bit.ly/3xwDrYY\n*/\n\n// ------------------------------------------------- //\n// ----- DEFINE THE LIBRARIES THAT WE WILL USE ----- //\n// ------------------------------------------------- //\n#include <iostream>\n#include <dlib/svm.h> // Dlib library version 19.22\n#include <stdio.h>\n#include <stdlib.h>\n#include \"../../../../../../CenyML_library_skeleton/otherLibraries/time/mTime.h\" // library to count the time elapsed in Linux Ubuntu.\n//#include \"../../../../CenyML_library_skeleton/otherLibraries/time/mTimeTer.h\" // library to count the time elapsed in Cygwin terminal window.\n#include \"../../../../../../CenyML_library_skeleton/otherLibraries/csv/csvManager.h\" // library to open and create .csv files.\n#include \"../../../../../../CenyML_library_skeleton/otherLibraries/pbPlots/pbPlots.h\" // library to generate plots v0.1.9.0\n#include \"../../../../../../CenyML_library_skeleton/otherLibraries/pbPlots/supportLib.h\"  // library required for \"pbPlots.h\" v0.1.9.0\n#include \"../../../../../../CenyML_library_skeleton/CenyML_Library/cpuSequential/evaluationMetrics/CenyMLclassificationEvalMet.h\" // library to use the classification evaluation metrics of CenyML.\n\n\n// ---------------------------------------------- //\n// ----- DEFINE THE GLOBAL RESOURCES TO USE ----- //\n// ---------------------------------------------- //\nusing namespace std;\nusing namespace dlib;\n\n\n// --------------------------------------------------- //\n// ----- The code from the main file starts here ----- //\n// --------------------------------------------------- //\n\n\n\n// ----------------------------------------------- //\n// ----- DEFINE THE GENERAL FUNCTIONS TO USE ----- //\n// ----------------------------------------------- //\n/**\n* The \"linspace()\" function is inspired in the code made by\n* \"SamuraiMelon\" in the stackoverflow web site under the title of\n* \"Linearly Spaced Array in C\" (URL = https://bit.ly/3r5Dom6).\n* Nonetheless, as coded in this file, this function is used to\n* allocate some memory space whose pointer variable will be used\n* to create a linearly spaced array with respect to the specified\n* values in the argument variables of this function.\n*\n* @param double startFrom - This argument will be used as the\n*\t\t\t\t\t\t\tstarting value of the linearly spaced\n*\t\t\t\t\t\t\tarray to be created.\n*\n* @param double endHere - This argument will be used as the ending\n*\t\t\t\t\t\t  value of the linearly spaced array to be\n*\t\t\t\t\t\t  created.\n*\n* @param int n - This argument will represent the total number of\n*\t\t\t\t rows that the linearly spaced array to be created\n*\t\t\t\t will have.\n*\n*\n* @return double *vector - Pointer Variable with \"n\" rows and \"1\"\n*\t\t\t\t\t\t   columns that will be used as a linearly\n*\t\t\t\t\t\t   spaced array with \"n\" spaces and that\n*\t\t\t\t\t\t   will start with the value specified in\n*\t\t\t\t\t\t   the argument variable \"startFrom\" and\n*\t\t\t\t\t\t   that will end with the value specified\n*\t\t\t\t\t\t   in the argument variable \"endHere\".\n*\n* @author Miranda Meza Cesar\n* CREATION DATE: NOVEMBER 23, 2021\n* LAST UPDATE: N/A\n*/\ndouble *linspace(double startFrom, double endHere, int n) {\n\t// We allocate the required memory to create the pointer variable \"vector\" in which we will make a linearly spaced array.\n\tdouble *vector;\n\tdouble step = (endHere - startFrom) / (double) n;\n\tvector = (double *) malloc(n*sizeof(double));\n\t\n\t// We store the values of the pointer variable \"vector\".\n\tvector[0] = startFrom; // We store the initial value of the pointer variable \"vector\".\n\tfor (int currentRow=1; currentRow<n; currentRow++) { // We store the values of the pointer variable \"vector\" from row index \"1\" up to row index \"n-1\".\n\t vector[currentRow] = vector[currentRow - 1] + step;\n\t}\n\tvector[n-1] = endHere; // We store the last value of the pointer variable \"vector\".\n\t\n\t// We return the address of the allocated variable \"vector\".\n\treturn vector;\n}\n\n\n// ----------------------------------------- //\n// ----- THE MAIN FUNCTION STARTS HERE ----- //\n// ----------------------------------------- //\n/**\n* This is the main function of the program. Here we will read a .csv file and\n* then apply the RBF Kernel support vector machine classification on the input\n* and output data contained in it. In addition, some evaluation metrics will\n* be applied to evaluate the model. Finally, the results will be saved in a\n* new .csv file and in a .png file for further comparation and validation\n* purposes.\n*\n* @return 0\n*\n* @author Miranda Meza Cesar\n* CREATION DATE: NOVEMBER 27, 2021\n* LAST UPDATE: DECEMBER 06, 2021\n*/\nint main() {\n    // --- LOCAL VARIABLES VALUES TO BE DEFINED BY THE IMPLEMENTER --- //\n\tchar csv1Directory[] = \"database.csv\"; // Directory of the reference .csv file\n\tchar nameOfTheCsvFile2[] = \"Dlib_rbfSVM_evalMetrics.csv\"; // Name the .csv file that will store the resulting evaluation metrics for the ML model to be obtained.\n\tstruct csvManager csv1; // We create a csvManager structure variable to manage the desired .csv file (which is declared in \"csvManager.h\").\n\tcsv1.fileDirectory = csv1Directory; // We save the directory path of the desired .csv file into the csvManager structure variable.\n\tcsv1.maxRowChars = 150; // We define the expected maximum number of characters the can be present for any of the rows contained in the target .csv file.\n\tint m = 2; // This variable will contain the number of features (independent variables) that the input matrix is expected to have.\n\tint p = 1; // This variable will contain the number of outputs that the output matrix is expected to have.\n\tint columnIndexOfOutputDataInCsvFile = 2; // This variable will contain the index of the first column in which we will specify the location of the real output values (Y).\n\tint columnIndexOfInputDataInCsvFile = 3; // This variable will contain the index of the first column in which we will specify the location of the input values (X).\n\ttypedef matrix<double, 2, 1> sample_type; // DLIB COMMENT: This typedef declares a matrix with 2 rows and 1 column, where the rows represent the number of ML feautres and columns represents the current sample.\n\ttypedef radial_basis_kernel<sample_type> kernel_type; // DLIB COMMENT: This is a typedef for the type of kernel we are going to use in this example. \n\tstd::vector<sample_type> samples; // This will be used to store the samples to be managed by the machine learning models of the Dlib library.\n\tstd::vector<double> labels; //  This will be used to store the outputs for each of the samples managed by the machine learning models of the Dlib library.\n\tdouble gamma = 0.01; // We define the desired value for the hyperparameter \"gamma\".\n    \t\n\t\n\t// ---------------------- IMPORT DATA TO USE --------------------- //\n\tprintf(\"Initializing data extraction from .csv file containing the data to be used ...\\n\");\n\tdouble startingTime, elapsedTime; // Declaration of variables used to count time in seconds.\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to obtain the data from the reference .csv file.\n\t// Obtain the rows and columns dimensions of the data of the csv file (excluding headers)\n\tcsv1.rowsAndColumnsDimensions = (int *) malloc(2*sizeof(int)); // We initialize the variable that will store the rows & columns dimensions.\n\tgetCsvRowsAndColumnsDimensions(&csv1); // We input the memory location of the \"csv1\" into the argument of this function to get the rows & columns dimensions.\n\t// We save the rows and columns dimensions obtained in some variables that relate to the mathematical symbology according to the documentation of the method to be validated.\n\tint n = csv1.rowsAndColumnsDimensions[0]; // total number of rows of the input matrix (X)\n\tint databaseColumns1 = csv1.rowsAndColumnsDimensions[1]; // total number of columns of the database that was opened.\n\t// From the structure variable \"csv1\", we allocate the memory required for the variable (csv1.allData) so that we can store the data of the .csv file in it.\n\tcsv1.allData = (double *) malloc(n*databaseColumns1*sizeof(double));\n\t// We retrieve the data contained in the reference .csv file.\n\tgetCsvFileData(&csv1); // We input the memory location of the \"csv1\" into the argument of this function to get all the data contained in the .csv file.\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to obtain the data from the reference .csv file.\n\tprintf(\"Data extraction from .csv file containing %d samples for each of the %d columns (total samples = %d), elapsed %f seconds.\\n\\n\", n, databaseColumns1, (n*databaseColumns1), elapsedTime);\n\t\n\t\n\t\n\t// ------------------ PREPROCESSING OF THE DATA ------------------ //\n\tprintf(\"Initializing the output and input data with %d samples for each of the %d columns (total samples = %d) each...\\n\", n, m, n);\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to innitialize the input data to be used.\n\t// Allocate the memory required for the variable \"Y\" and \"Y_tilde\", which will contain the real output data of the system under study.\n\tdouble *Y = (double *) malloc(n*p*sizeof(double));\n\tdouble *Y_tilde = (double *) malloc(n*p*sizeof(double));\n\t// Store the data that must be contained in the output matrix \"Y\".\n\tfor (int currentRow=0; currentRow<n; currentRow++) {\n\t\tY[currentRow] = csv1.allData[columnIndexOfOutputDataInCsvFile + currentRow*databaseColumns1];\n\t\tif (Y[currentRow] == 0) {\n\t\t\tY_tilde[currentRow] = -1;\n\t\t} else {\n\t\t\tY_tilde[currentRow] = 1;\n\t\t}\n\t}\n\t// Allocate the memory required for the variable \"X\", which will contain the input data of the system under study.\n\tdouble *X = (double *) malloc(n*m*sizeof(double));\n\t// Store the data that must be contained in the input matrix \"X\".\n\tfor (int currentRow=0; currentRow<n; currentRow++) {\n\t\tfor (int currentColumn=0; currentColumn<m; currentColumn++) {\n\t\t\tX[currentColumn + currentRow*m] = csv1.allData[columnIndexOfInputDataInCsvFile + currentColumn + currentRow*databaseColumns1];\n\t\t}\n\t}\n\t// DLIB COMMENT: Pass the input data of the system under study to the Dlib svm trainer.\n\t//NOTE: In the Dlib library, it seems to me that all samples must be passed row per row, unlike most other libraries in which you can pass the entire matrix of rows and columns at once.\n\tfor (int currentRow=0; currentRow<n; currentRow++) {\n\t\t// IMPORTANT WARNING NOTE: I figured out that for some reason of\n\t\t// how the Dlib library has been programmed with respect to what\n\t\t// they call their \"sample_type\" object, it prevents me from\n\t\t// creating an instance with it (e.g. the one i crated as\n\t\t// \"DlibCurrentSample\") and use it inside a for-loop to\n\t\t// automatize the coulumns extraction from the input matrix \"X\".\n\t\t// Becaused of that, i had to remove such for-loop and do it\n\t\t// mannualy like how the Dlib example file \"smv_c_ex.cpp\" does\n\t\t// it.\n\t\tsample_type DlibCurrentSample;\n\t\tDlibCurrentSample(0) = X[currentRow*m];\n\t\tDlibCurrentSample(1) = X[1 + currentRow*m]; // We pass the current row of data from the input matrix \"X\" to the instance \"DlibCurrentSample\".\n\t\tsamples.push_back(DlibCurrentSample); // DLIB COMMENT: Save the current sample of the input matrix \"X\" so we can let the ML trainer learn from them below.\n\t\tlabels.push_back(Y_tilde[currentRow]); // DLIB COMMENT: Save the output of the current sample of the input matrix \"X\" so we can let the ML trainer learn from them below.\n\t}\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to innitialize the input data to be used.\n\tprintf(\"Output and input data innitialization elapsed %f seconds.\\n\\n\", elapsedTime);\n\t\n\t\n\t// ------------------------- DATA MODELING ----------------------- //\n\tprintf(\"Initializing Dlib RBF Kernel support vector machine classification algorithm ...\\n\");\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to apply the simple RBF Kernel machine classification with the input data (X).\t\n\tsvm_c_trainer<kernel_type> trainer; // DLIB COMMENT: Here we make an instance of the svm_c_trainer object that uses our kernel type.     \t\n\t// NOTE: If the function \"trainer.set_kernel(kernel_type(gamma))\" is not\n\t//\t \t used, then the Dlib library solves the model iteratively to\n\t//\t \t automatically find the best gamma value.\n\ttrainer.set_kernel(kernel_type(gamma)); // Define the \"gamma\" hyperparameter.\n    decision_function<kernel_type> KSVM_model = trainer.train(samples, labels); // We train the desired Kernel SVM model.\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to apply the simple RBF Kernel machine classification with the input data (X).\n\tprintf(\"Dlib RBF Kernel support vector machine classification algorithm elapsed %f seconds.\\n\\n\", elapsedTime);\n\t\n\t\n\t// ----------- PREDICTIONS AND EVALUATIONS OF THE MODEL --------- //\n\t// We predict the input values (X) with the machine learning model that was obtained.\n\tprintf(\"Initializing Dlib predictions with the model that was obtained ...\\n\");\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to apply the prediction with the model that was obtained.\n\t// Allocate the memory required for the variable \"Y_hat\", which will contain the predicted output data of the system under study.\n\tdouble *Y_hat = (double *) malloc(n*p*sizeof(double));\n\t// Pass the input data of the system under study to the trained model to make their corresponding predictions and store them.\n    //NOTE: In the Dlib library, all samples must be passed row per row, unlike most other libraries in which you can pass the entire matrix of rows and columns at once.\n\tsample_type sample; // We create and instance of the object \"sample_type\" to extract all the predicted data from the model that has just been trained.\n\tfor (int currentRow=0; currentRow<n; currentRow++) {\n\t\t// IMPORTANT WARNING NOTE: I figured out that for some reason of\n\t\t// how the Dlib library has been programmed with respect to what\n\t\t// they call their \"sample_type\" object, it prevents me from\n\t\t// creating an instance with it (e.g. the one i crated as\n\t\t// \"sample\") and use it inside a for-loop to automatize the\n\t\t// coulumns extraction from the input matrix \"X\". Becaused of\n\t\t// that, i had to remove such for-loop and do it mannualy like\n\t\t// how the Dlib example file \"smv_c_ex.cpp\" does it.\n\t\tsample(0) = X[currentRow*m];\n\t\tsample(1) = X[1 + currentRow*m]; // We pass the current row of data from the input matrix \"X\" to the instance \"DlibCurrentSample\".\n\t\tif (KSVM_model(sample) > 0) {\n\t\t\tY_hat[currentRow] = 1;\n\t\t} else {\n\t\t\tY_hat[currentRow] = 0; // Instead of storing a \"-1\" value, we will store a \"0\" instead so that we can use the predicted values in the CenyML evaluation metric funtions.\n\t\t}\n\t}\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to obtain the prediction wit hthe model that was obtained.\n\tprintf(\"The Dlib predictions with the model that was obtained elapsed %f seconds.\\n\\n\", elapsedTime);\n\t\n\t// We apply the cross entropy error metric.\n\tdouble NLLepsilon = 1.0E-15; // This variable will contain the user desired epsilon value to be summed to any zero value and substracted to any value of the output matrixes (Y and/or Y_hat). NOTE: It will be assigned the value to match the one used in scikit-learn.\n\tprintf(\"Initializing CenyML cross entropy error metric ...\\n\");\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to calculate the cross entropy error metric between \"Y\" and \"Y_hat\".\n\t// Allocate the memory required for the variable \"NLL\" (which will contain the results of the cross entropy error metric between \"Y\" and \"Y_hat\").\n\tdouble *NLL = (double *) calloc(1, sizeof(double));\n\t// We apply the cross entropy error metric between \"Y\" and \"Y_hat\".\n\tgetCrossEntropyError(Y, Y_hat, n, NLLepsilon, NLL);\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to calculate the cross entropy error metric between \"Y\" and \"Y_hat\".\n\tprintf(\"CenyML cross entropy error metric elapsed %f seconds.\\n\\n\", elapsedTime);\n\t\n\t// We apply the confusion matrix metric.\n\tprintf(\"Initializing CenyML confusion matrix metric ...\\n\");\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to calculate the confusion matrix metric between \"Y\" and \"Y_hat\".\n\t// Allocate the memory required for the variable \"confusionMatrix\" (which will contain the results of the confusion matrix metric between \"Y\" and \"Y_hat\").\n\tdouble *confusionMatrix = (double *) calloc(4, sizeof(double));\n\t// We apply the confusion matrix metric between \"Y\" and \"Y_hat\".\n\tgetConfusionMatrix(Y, Y_hat, n, confusionMatrix);\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to calculate the confusion matrix metric between \"Y\" and \"Y_hat\".\n\tprintf(\"CenyML confusion matrix metric elapsed %f seconds.\\n\\n\", elapsedTime);\n\t\n\t// We apply the accuracy metric.\n\tprintf(\"Initializing CenyML accuracy metric ...\\n\");\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to calculate the accuracy metric between \"Y\" and \"Y_hat\".\n\t// Allocate the memory required for the variable \"accuracy\" (which will contain the results of the accuracy metric between \"Y\" and \"Y_hat\").\n\tdouble *accuracy = (double *) calloc(1, sizeof(double));\n\t// We apply the accuracy metric between \"Y\" and \"Y_hat\".\n\tgetAccuracy(Y, Y_hat, n, accuracy);\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to calculate the accuracy metric between \"Y\" and \"Y_hat\".\n\tprintf(\"CenyML accuracy metric elapsed %f seconds.\\n\\n\", elapsedTime);\n\t\n\t// We apply the precision metric.\n\tprintf(\"Initializing CenyML precision metric ...\\n\");\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to calculate the precision metric between \"Y\" and \"Y_hat\".\n\t// Allocate the memory required for the variable \"precision\" (which will contain the results of the precision metric between \"Y\" and \"Y_hat\").\n\tdouble *precision = (double *) calloc(1, sizeof(double));\n\t// We apply the precision metric between \"Y\" and \"Y_hat\".\n\tgetPrecision(Y, Y_hat, n, precision);\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to calculate the precision metric between \"Y\" and \"Y_hat\".\n\tprintf(\"CenyML precision metric elapsed %f seconds.\\n\\n\", elapsedTime);\n\t\n\t// We apply the recall metric.\n\tprintf(\"Initializing CenyML recall metric ...\\n\");\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to calculate the recall metric between \"Y\" and \"Y_hat\".\n\t// Allocate the memory required for the variable \"recall\" (which will contain the results of the recall metric between \"Y\" and \"Y_hat\").\n\tdouble *recall = (double *) calloc(1, sizeof(double));\n\t// We apply the recall metric between \"Y\" and \"Y_hat\".\n\tgetRecall(Y, Y_hat, n, recall);\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to calculate the recall metric between \"Y\" and \"Y_hat\".\n\tprintf(\"CenyML recall metric elapsed %f seconds.\\n\\n\", elapsedTime);\n\t\n\t// We apply the F1 score metric.\n\tprintf(\"Initializing CenyML F1 score metric ...\\n\");\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to calculate the F1 score metric between \"Y\" and \"Y_hat\".\n\t// Allocate the memory required for the variable \"F1 score\" (which will contain the results of the F1 score metric between \"Y\" and \"Y_hat\").\n\tdouble *F1score = (double *) calloc(1, sizeof(double));\n\t// We apply the F1 score metric between \"Y\" and \"Y_hat\".\n\tgetF1score(Y, Y_hat, n, F1score);\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to calculate the F1 score metric between \"Y\" and \"Y_hat\".\n\tprintf(\"CenyML F1 score metric elapsed %f seconds.\\n\\n\", elapsedTime);\n\t\n\t// We create a single variable that contains within all the evaluation metrics that were tested.\n\tprintf(\"Initializing single variable that will store all the evaluation metrics done ...\\n\");\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to calculate the initialization of the single variable that will store all the evaluation metrics.\n\t// Allocate the memory required for the variable \"evaluationMetrics\" (which will contain all the results of the evaluation metrics that were obtained).\n\tdouble *evaluationMetrics = (double *) malloc(9*sizeof(double));\n\tevaluationMetrics[0] = NLL[0]; // We add the cross entropy error metric.\n\tevaluationMetrics[1] = confusionMatrix[0]; // We add the true positives from the confusion matrix.\n\tevaluationMetrics[2] = confusionMatrix[1]; // We add the false positives from the confusion matrix.\n\tevaluationMetrics[3] = confusionMatrix[2]; // We add the false negatives from the confusion matrix.\n\tevaluationMetrics[4] = confusionMatrix[3]; // We add the true negatives from the confusion matrix.\n\tevaluationMetrics[5] = accuracy[0]; // We add the accuracy metric.\n\tevaluationMetrics[6] = precision[0]; // We add the precision metric.\n\tevaluationMetrics[7] = recall[0]; // We add the recall metric.\n\tevaluationMetrics[8] = F1score[0]; // We add the F1 score metric.\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to calculate the initialization of the single variable that will store all the evaluation metrics.\n\tprintf(\"Innitialization of single variable to store all the evaluation metrics elapsed %f seconds.\\n\\n\", elapsedTime);\n\t\n\t// We store the resulting evaluation metrics that were obtained.\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to create the .csv file which will store the results of the evaluation metrics that were obtained.\n\t// Define the desired header names for the new .csv file to be create.\n    char csvHeaders2[strlen(\"NLL, TP, FP, FN, TN, accuracy, precision, recall, F1score\")+1]; // Variable where the following code will store the .csv headers.\n    csvHeaders2[0] = '\\0'; // Innitialize this char variable with a null value.\n\tstrcat(csvHeaders2, \"NLL, TP, FP, FN, TN, accuracy, precision, recall, F1score\"); // We add the headers into \"csvHeaders\".\n\t// Create a new .csv file and save the results obtained in it.\n\tchar is_nArray2 = 0; // Indicate through this flag variable that the variable that indicates the samples (1) is not an array because it has the same amount of samples per columns.\n\tchar isInsertId2 = 0; // Indicate through this flag variable that it is not desired that the file to be created automatically adds an \"id\" to each row.\n\tint csvFile_n2 = 1; // This variable is used to indicate the number of rows with data that will be printed in the .csv file to be created.\n\tcreateCsvFile(nameOfTheCsvFile2, csvHeaders2, evaluationMetrics, &csvFile_n2, is_nArray2, 9, isInsertId2); // We create the desired .csv file.\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to create the .csv file which will store the results calculated.\n\tprintf(\"Creation of the .csv file to store the evaluation metrics that were obtained, elapsed %f seconds.\\n\\n\", elapsedTime);\n\t\n\t\n\t\n\t// ----------------- VISUALIZATION OF THE MODEL ------------------ //\n\t// Plot a graph with the model that was obtained and saved it into a .png file.\n\tprintf(\"Initializing creation of .png image to store the plot of the predicted data and the actual data ...\\n\");\n\tstartingTime = seconds(); // We obtain the reference time to count the elapsed time to create the .png file that will store the results of the predicted and actual data.\n\t// Trying the \"pbPlots\" library (https://github.com/InductiveComputerScience/pbPlots)\n\t_Bool success;\n    StringReference *errorMessage;\n\tRGBABitmapImageReference *imageReference = CreateRGBABitmapImageReference();\n\t\n\t// In order to continue with the plotting process, identify the minimum and maximum values contained in each machine learning feature.\n\tdouble minX1 = X[0];\n\tdouble maxX1 = X[0];\n\tdouble minX2 = X[1];\n\tdouble maxX2 = X[1];\n\tfor (int currentRow=1; currentRow<n; currentRow++) {\n\t\tif (X[currentRow*m] < minX1) {\n\t\t\tminX1 = X[currentRow*m];\n\t\t}\n\t\tif (X[currentRow*m] > maxX1) {\n\t\t\tmaxX1 = X[currentRow*m];\n\t\t}\n\t\tif (X[1 + currentRow*m] < minX2) {\n\t\t\tminX2 = X[1 + currentRow*m];\n\t\t}\n\t\tif (X[1 + currentRow*m] > maxX2) {\n\t\t\tmaxX2 = X[1 + currentRow*m];\n\t\t}\n\t}\n\t// In order to continue with the plotting process, we increase by a 50% the ranges of the minimum and maximum detected.\n\tdouble rangeToBeAdded; // This variable will be used to store the range to be added/decreased for each max and min value detected.\n\trangeToBeAdded = (maxX1 - minX1) * 0.5;\n\tminX1 = minX1 - rangeToBeAdded;\n\tmaxX1 = maxX1 + rangeToBeAdded;\n\trangeToBeAdded = (maxX2 - minX2) * 0.5;\n\tminX2 = minX2 - rangeToBeAdded;\n\tmaxX2 = maxX2 + rangeToBeAdded;\n\t// In order to continue with the plotting process, we create some linearly spaced vectors of each independent feature with the min and max ranges that were obtained.\n\tint n_ofLinearlySpacedArray = 100;\n\tdouble *X1 = linspace(minX1, maxX1, n_ofLinearlySpacedArray);\n\tdouble *X2 = linspace(minX2, maxX2, n_ofLinearlySpacedArray);\n\t// In order to continue with the plotting process, we create a new input matrix that contains the data of the vectors that were created, which will be used to create the background of the plot to be created.\n\tdouble *bg_X = (double *) malloc((n_ofLinearlySpacedArray*n_ofLinearlySpacedArray)*m*sizeof(double)); // Allocate the memory required for the variable \"bg_X\".\n\tint currentRow_bg_X=0;\n\tfor (int currentRow1=0; currentRow1<n_ofLinearlySpacedArray; currentRow1++) { // Store the data that must be contained in the input matrix \"bg_X\".\n\t\tfor (int currentRow2=0; currentRow2<n_ofLinearlySpacedArray; currentRow2++) {\n\t\t\tbg_X[0 + currentRow_bg_X*m] = X1[currentRow1];\n\t\t\tbg_X[1 + currentRow_bg_X*m] = X2[currentRow2];\n\t\t\tcurrentRow_bg_X++;\n\t\t}\n\t}\n\t// In order to continue the plotting process, we obtain the output data that will be used to create the background of the plot to be created.\n\tdouble *bg_Y_hat = (double *) malloc((n_ofLinearlySpacedArray*n_ofLinearlySpacedArray)*p*sizeof(double));\n\t// Pass the input data of the system under study to the trained model to make their corresponding predictions and store them.\n    //NOTE: In the Dlib library, all samples must be passed row per row, unlike most other libraries in which you can pass the entire matrix of rows and columns at once.\n\tfor (int currentRow=0; currentRow<(n_ofLinearlySpacedArray*n_ofLinearlySpacedArray); currentRow++) {\n\t\t// IMPORTANT WARNING NOTE: I figured out that for some reason of\n\t\t// how the Dlib library has been programmed with respect to what\n\t\t// they call their \"sample_type\" object, it prevents me from\n\t\t// creating an instance with it (e.g. the one i crated as\n\t\t// \"sample\") and use it inside a for-loop to automatize the\n\t\t// coulumns extraction from the input matrix \"X\". Becaused of\n\t\t// that, i had to remove such for-loop and do it mannualy like\n\t\t// how the Dlib example file \"smv_c_ex.cpp\" does it.\n\t\tsample(0) = bg_X[currentRow*m];\n\t\tsample(1) = bg_X[1 + currentRow*m]; // We pass the current row of data from the input matrix \"X\" to the instance \"DlibCurrentSample\".\n\t\tif (KSVM_model(sample) > 0) {\n\t\t\tbg_Y_hat[currentRow] = 1;\n\t\t} else {\n\t\t\tbg_Y_hat[currentRow] = -1;\n\t\t}\n\t}\n\t// In order to continue the plotting process, we determine the number of 1s and 0s that were predicted for the background to be created.\n\tint n_of_bg1s = 0; // This variable will be used as a counter to determine the rows length of the pointer variables \"bg_X1_1s\" and \"bg_X2_1s\" to be created.\n\tint n_of_bg0s = 0; // This variable will be used as a counter to determine the rows length of the pointer variables \"bg_X1_0s\" and \"bg_X2_0s\" to be created.\n\tfor (int currentRow=0; currentRow<(n_ofLinearlySpacedArray*n_ofLinearlySpacedArray); currentRow++) {\n\t\tif (bg_Y_hat[currentRow] == 1) {\n\t\t\tn_of_bg1s++;\n\t\t} else {\n\t\t\tn_of_bg0s++;\n\t\t}\n\t}\n\t// In order to continue the plotting process, we seperate the input data that has an output value of \"1\" with respect to the ones that have an output of \"0\".\n\tdouble *bg_X1_1s = (double *) malloc(n_of_bg1s*1*sizeof(double)); // Allocate the memory required for the variable \"bg_X1_1s\".\n\tdouble *bg_X2_1s = (double *) malloc(n_of_bg1s*1*sizeof(double)); // Allocate the memory required for the variable \"bg_X2_1s\".\n\tdouble *bg_X1_0s = (double *) malloc(n_of_bg0s*1*sizeof(double)); // Allocate the memory required for the variable \"bg_X1_0s\".\n\tdouble *bg_X2_0s = (double *) malloc(n_of_bg0s*1*sizeof(double)); // Allocate the memory required for the variable \"bg_X2_0s\".\n\tint currentRow_bg_X_1s = 0; // This variable will be used as a counter for the output values of \"1\" that the pointer variables \"bg_X1_1s\" and \"bg_X2_1s\" have.\n\tint currentRow_bg_X_0s = 0; // This variable will be used as a counter for the output values of \"0\" that the pointer variables \"bg_X1_0s\" and \"bg_X2_0s\" have.\n\tfor (int currentRow=0; currentRow<(n_ofLinearlySpacedArray*n_ofLinearlySpacedArray); currentRow++) {\n\t\tif (bg_Y_hat[currentRow] == 1) {\n\t\t\tbg_X1_1s[currentRow_bg_X_1s] = bg_X[currentRow*m];\n\t\t\tbg_X2_1s[currentRow_bg_X_1s] = bg_X[1 + currentRow*m];\n\t\t\tcurrentRow_bg_X_1s++;\n\t\t} else {\n\t\t\tbg_X1_0s[currentRow_bg_X_0s] = bg_X[currentRow*m];\n\t\t\tbg_X2_0s[currentRow_bg_X_0s] = bg_X[1 + currentRow*m];\n\t\t\tcurrentRow_bg_X_0s++;\n\t\t}\n\t}\n\t\n\t// background with 1s\n\tScatterPlotSeries *series = GetDefaultScatterPlotSeriesSettings();\n\tseries->xs = bg_X1_1s;\n\tseries->xsLength = n_of_bg1s;\n\tseries->ys = bg_X2_1s;\n\tseries->ysLength = n_of_bg1s;\n\tseries->linearInterpolation = false;\n\tseries->pointType = L\"dots\";\n\tseries->pointTypeLength = wcslen(series->pointType);\n\tseries->color = CreateRGBAColor(0.808, 0.922, 0.804, 0.05);\n\t\n\t// background with 0s\n\t\n\tScatterPlotSeries *series2 = GetDefaultScatterPlotSeriesSettings();\n\tseries2->xs = bg_X1_0s;\n\tseries2->xsLength = n_of_bg0s;\n\tseries2->ys = bg_X2_0s;\n\tseries2->ysLength = n_of_bg0s;\n\tseries2->linearInterpolation = false;\n\tseries2->pointType = L\"dots\";\n\tseries2->pointTypeLength = wcslen(series2->pointType);\n\tseries2->color = CreateRGBAColor(0.902, 0.749, 0.749, 0.05);\n\t\n\t// In order to continue the plotting process, we determine the number of 1s and 0s that were predicted by the machine learning model that was created.\n\tint n_of_Y1s = 0; // This variable will be used as a counter to determine the rows length of the pointer variables \"real_X1_1s\" and \"real_X2_1s\" to be created.\n\tint n_of_Y0s = 0; // This variable will be used as a counter to determine the rows length of the pointer variables \"real_X1_0s\" and \"real_X2_0s\" to be created.\n\tfor (int currentRow=0; currentRow<n; currentRow++) {\n\t\tif (Y[currentRow] == 1) {\n\t\t\tn_of_Y1s++;\n\t\t} else {\n\t\t\tn_of_Y0s++;\n\t\t}\n\t}\n\t// In order to continue the plotting process, we seperate the input data that has an output value of \"1\" with respect to the ones that have an output of \"0\".\n\tdouble *real_X1_1s = (double *) malloc(n_of_Y1s*sizeof(double)); // Allocate the memory required for the variable \"real_X1_1s\".\n\tdouble *real_X2_1s = (double *) malloc(n_of_Y1s*sizeof(double)); // Allocate the memory required for the variable \"real_X2_1s\".\n\tdouble *real_X1_0s = (double *) malloc(n_of_Y0s*sizeof(double)); // Allocate the memory required for the variable \"real_X1_0s\".\n\tdouble *real_X2_0s = (double *) malloc(n_of_Y0s*sizeof(double)); // Allocate the memory required for the variable \"real_X2_0s\".\n\tint currentRow_predicted_X_1s = 0; // This variable will be used as a counter for the output values of \"1\" that the pointer variables \"real_X1_1s\" and \"real_X2_1s\" have.\n\tint currentRow_predicted_X_0s = 0; // This variable will be used as a counter for the output values of \"0\" that the pointer variables \"real_X1_0s\" and \"real_X2_0s\" have.\n\tfor (int currentRow=0; currentRow<n; currentRow++) {\n\t\tif (Y[currentRow] == 1) {\n\t\t\treal_X1_1s[currentRow_predicted_X_1s] = X[currentRow*m];\n\t\t\treal_X2_1s[currentRow_predicted_X_1s] = X[1 + currentRow*m];\n\t\t\tcurrentRow_predicted_X_1s++;\n\t\t} else {\n\t\t\treal_X1_0s[currentRow_predicted_X_0s] = X[currentRow*m];\n\t\t\treal_X2_0s[currentRow_predicted_X_0s] = X[1 + currentRow*m];\n\t\t\tcurrentRow_predicted_X_0s++;\n\t\t}\n\t}\n\t\n\t// real data with 1s\n\tScatterPlotSeries *series3 = GetDefaultScatterPlotSeriesSettings();\n\tseries3->xs = real_X1_1s;\n\tseries3->xsLength = n_of_Y1s;\n\tseries3->ys = real_X2_1s;\n\tseries3->ysLength = n_of_Y1s;\n\tseries3->linearInterpolation = false;\n\tseries3->pointType = L\"dots\";\n\tseries3->pointTypeLength = wcslen(series3->pointType);\n\tseries3->color = CreateRGBColor(0.325, 0.890, 0);\n\t// real data with 0s\n\tScatterPlotSeries *series4 = GetDefaultScatterPlotSeriesSettings();\n\tseries4->xs = real_X1_0s;\n\tseries4->xsLength = n_of_Y0s;\n\tseries4->ys = real_X2_0s;\n\tseries4->ysLength = n_of_Y0s;\n\tseries4->linearInterpolation = false;\n\tseries4->pointType = L\"filled triangles\";\n\tseries4->pointTypeLength = wcslen(series4->pointType);\n\tseries4->color = CreateRGBColor(0.929, 0.196, 0.216);\n\t\n\t// This next series will be created because, due to a bug, the pbPlots library assings automatically one last point at the end.\n\t// Therefore, we will plot a \"filled triangles\" scatter point on top of it with color black so that it does not make the user think of that point as an actual data of interest.\n\tdouble xs [] = {0};\n\tdouble ys [] = {0};\n\tScatterPlotSeries *series5 = GetDefaultScatterPlotSeriesSettings();\n\tseries5->xs = xs;\n\tseries5->xsLength = 1;\n\tseries5->ys = ys;\n\tseries5->ysLength = 1;\n\tseries5->linearInterpolation = false;\n\tseries5->pointType = L\"filled triangles\";\n\tseries5->pointTypeLength = wcslen(series5->pointType);\n\tseries5->color = GetBlack();\n\t\n\t// Create the .png image with the desired plot.\n\tScatterPlotSettings *settings = GetDefaultScatterPlotSettings();\n\tsettings->width = 600;\n\tsettings->height = 400;\n\tsettings->autoBoundaries = true;\n\tsettings->autoPadding = true;\n\tsettings->title = L\"\";\n\tsettings->titleLength = wcslen(settings->title);\n\tsettings->xLabel = L\"\";\n\tsettings->xLabelLength = wcslen(settings->xLabel);\n\tsettings->yLabel = L\"\";\n\tsettings->yLabelLength = wcslen(settings->yLabel);\n\tScatterPlotSeries *s [] = {series2, series, series3, series4, series5};\n\tsettings->scatterPlotSeries = s;\n\tsettings->scatterPlotSeriesLength = 5;\n\t\n\t// If there is an error during the .png file creation, show it on the terminal window.\n    errorMessage = (StringReference *)malloc(sizeof(StringReference));\n\tsuccess = DrawScatterPlotFromSettings(imageReference, settings, errorMessage);\n    if(success){\n        size_t length;\n        double *pngdata = ConvertToPNG(&length, imageReference->image);\n        WriteToFile(pngdata, length, \"plotOfMachineLearningModel (Dlib).png\");\n        DeleteImage(imageReference->image);\n\t}else{\n\t    fprintf(stderr, \"Error: \");\n        for(int i = 0; i < errorMessage->stringLength; i++){\n            fprintf(stderr, \"%c\", errorMessage->string[i]);\n        }\n        fprintf(stderr, \"\\n\");\n\t}\n\telapsedTime = seconds() - startingTime; // We obtain the elapsed time to create the .png file that will store the results of the predicted and actual data.\n\tprintf(\"Innitialization of the creation of the .png file elapsed %f seconds.\\n\", elapsedTime);\n\tprintf(\"NOTE: In regards to the .png image, the horizontal axis stands for the independent variable 1 and the vertical axis for the independent variable 2.\\n\");\n\tprintf(\"In addition, the color green stands for an output value of 1 and the color red for an output value of -1.\\n\");\n\tprintf(\"Finally, while the background color represents the predicted 1s and -1s that were made by the machine learning model that was just trained, the dots/triangles stand for the true behaviour of the system under study.\\n\\n\");\n\tprintf(\"The program has been successfully completed!\\n\");\n\t\n\t// Free the Heap memory used for the allocated variables since they will no longer be used and then terminate the program.\n\tfree(csv1.rowsAndColumnsDimensions);\n\tfree(csv1.allData);\n\tfree(Y);\n\tfree(X);\n\tfree(Y_hat);\n\tfree(NLL);\n\tfree(confusionMatrix);\n\tfree(accuracy);\n\tfree(precision);\n\tfree(recall);\n\tfree(F1score);\n\tfree(evaluationMetrics);\n\tfree(X1);\n\tfree(X2);\n\tfree(bg_X);\n\tfree(bg_Y_hat);\n\tfree(bg_X1_1s);\n\tfree(bg_X2_1s);\n\tfree(bg_X1_0s);\n\tfree(bg_X2_0s);\n\tfree(real_X1_1s);\n\tfree(real_X2_1s);\n\tfree(real_X1_0s);\n\tfree(real_X2_0s);\n\treturn (0); // end of program.\n}\n\n", "meta": {"hexsha": "6a16539a801f097e178a442d97e0bf2d0d5b86f7", "size": 37304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Validation_of_CenyML/cpuSequential/machineLearning/KernelMachineClassification/DlibCplusplus/radialBasisFunctionKSVM/main.cpp", "max_stars_repo_name": "Mortrack/CenyML", "max_stars_repo_head_hexsha": "b54080d01491c89b311dfde3b980434db04de4d2", "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": "Validation_of_CenyML/cpuSequential/machineLearning/KernelMachineClassification/DlibCplusplus/radialBasisFunctionKSVM/main.cpp", "max_issues_repo_name": "Mortrack/CenyML", "max_issues_repo_head_hexsha": "b54080d01491c89b311dfde3b980434db04de4d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Validation_of_CenyML/cpuSequential/machineLearning/KernelMachineClassification/DlibCplusplus/radialBasisFunctionKSVM/main.cpp", "max_forks_repo_name": "Mortrack/CenyML", "max_forks_repo_head_hexsha": "b54080d01491c89b311dfde3b980434db04de4d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.5906040268, "max_line_length": 266, "alphanum_fraction": 0.7237561656, "num_tokens": 9561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.6160752642286329}}
{"text": "#include \"cho_util/core/random_convex_polygon.hpp\"\n\n#include <cstdlib>\n#include <iostream>\n\n#include <fmt/printf.h>\n#include <boost/program_options.hpp>\n\n#include \"cho_util/core/random.hpp\"\n\nnamespace po = boost::program_options;\n\nstruct AppSettings {\n  int num_points{256};\n  int seed{0};\n};\n\nvoid Usage(const po::options_description& desc) {\n  // clang-format off\n  fmt::print(R\"(Usage:\n  test_generate_convex_polygon [options]\nDescription:\n  Test convex polygon generation.\nOptions:\n{}\n  )\",\n             desc);\n  // clang-format on\n}\n\nbool ParseArguments(int argc, char* argv[], AppSettings* const settings) {\n  po::options_description desc(\"\");\n\n  // clang-format off\n  desc.add_options()\n      (\"help,h\", \"help\")\n      (\"num_points,n\", po::value<int>(&settings->num_points)->default_value(256), \"Number of points in convex hull.\")\n      (\"seed,s\", po::value<int>(&settings->seed)->default_value(0), \"Random RNG seed.\")\n      ;\n  // clang-format on\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    Usage(desc);\n    return false;\n  }\n  return true;\n}\n\nint main(int argc, char* argv[]) {\n  AppSettings settings;\n  if (!ParseArguments(argc, argv, &settings)) {\n    return 1;\n  }\n  auto& rng = cho::core::RNG::GetInstance();\n  if (settings.seed >= 0) {\n    rng.SetSeed(settings.seed);\n  }\n  std::vector<Eigen::Vector2f> points;\n  cho::core::GenerateConvexPolygon(settings.num_points, &points, rng);\n\n  for (const auto& p : points) {\n    std::cout << p.transpose() << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "9830591087d01e55b676f761e13b01a6c88b6594", "size": 1580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cho_util/core/test/test_generate_convex_polygon.cpp", "max_stars_repo_name": "yycho0108/ChoUtils", "max_stars_repo_head_hexsha": "ce701d4c7bb21c6b17e218d584ad68bbb63fba0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cho_util/core/test/test_generate_convex_polygon.cpp", "max_issues_repo_name": "yycho0108/ChoUtils", "max_issues_repo_head_hexsha": "ce701d4c7bb21c6b17e218d584ad68bbb63fba0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cho_util/core/test/test_generate_convex_polygon.cpp", "max_forks_repo_name": "yycho0108/ChoUtils", "max_forks_repo_head_hexsha": "ce701d4c7bb21c6b17e218d584ad68bbb63fba0a", "max_forks_repo_licenses": ["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.8985507246, "max_line_length": 117, "alphanum_fraction": 0.6582278481, "num_tokens": 415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867585368343, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6160752554488417}}
{"text": "#include <blitz/vector.h>\n#include <blitz/tinyvec.h>\n\nBZ_USING_NAMESPACE(blitz)\n\n/*\n * Test a 12th order symmetric multistep method for solving the equations\n * of motion of a single planet circling the Sun.  The Sun is fixed in\n * space.\n *\n * Original F77 version written by John K. Prentice, Quetzal Computational\n * Associates, 21 Decmber 1992\n * \n * Blitz++ version by Todd Veldhuizen, 17 August 1997\n * The C++ version is a faithful translation of the Fortran 90 version,\n * so apologies for the \"C++Tran\" style.\n */\n\ninline double relativeError(double a, double b)\n{\n    if (b != 0.0)\n        return (a - b) / b;\n    else\n        return a;\n}\n\nint main()\n{\n    Vector<double> x_position_numerical(13), y_position_numerical(13),\n        alpha(13), beta(13), gamma(13), x_acceleration(13), y_acceleration(13);\n   \n    /*\n     * 12th order symmetric method coefficients\n     *\n     * Reference: \"Symmetric Multistep Methods for the Numerical\n     * Integration of Planetary Orbits\", G. D. Quinlan and\n     * S. Tremaine, The Astronomical Journal, 100 (1990), page 1695.\n     *\n     * Note!! The beta below are actually 53,222,400 times the\n     * real beta.  This common factor is divided out in the\n     * symmetric multistep calculation itself, in order to minimize\n     * round-off\n     */\n\n    const double beta_factor = 53222400.0;\n    alpha = 1.0, -2.0, 2.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 2.0, -2.0, 1.0;\n    beta  = 0.0, 90987349.0, -229596838.0, 812627169.0, -1628539944.0, \n            2714971338.0, -3041896548.0, 2714971338.0, -1628539944.0,\n            812627169.0, -229596838.0, 90987349.0, 0.0;\n\n    /*\n     * 12th order Cowell predictor coefficients\n     *\n     * Reference:  \"Astronomical Papers Prepared for the Use of the\n     * American Ephemeris and Nautical Almanac\", C. J. Cohen, E. C.\n     * Hubbard, and C. Oesterwinter, 22 (1973), page 20-21.\n     *\n     * Note!!  The gamma below are actually 1,743,565,824,000 times\n     * the real gamma.  This common factor is divided out in the\n     * Cowell predictor calculation itself, in order to minimize\n     * round-off\n     */\n\n    const double gamma_factor = 1743565824000.0;\n    gamma = 9072652009253.0, -39726106418680.0, 140544566352762.0, \n       -344579280210129.0, 613137294629235.0, -811345852376496.0,\n       807012356281740.0, -602852367932304.0, 333888089374395.0, \n       -133228219027160.0, 36262456774618.0, -6033724094760.0,\n       463483373517.0;\n\n    // Initialize variables\n\n    const double time_step = 0.25,\n                 stop_time = 365000.0,\n                 radius    = 1.0;\n    double time = - time_step;\n\n    cout << \" Position solution via 12th order symmetric multistep method\\n\"\n         << \" Velocity solution via 12th order Cowell predictor method\\n\"\n         << \"     radius = \" << radius << \", time step = \" << time_step\n         << endl;\n\n    // Define a constant which is needed later by the exact solution\n    const double gaussian_constant = 0.01720209895;\n    const double gravitational_constant = pow(gaussian_constant,2);\n    const double constant = sqrt(gravitational_constant/pow(radius,3));\n\n    // Initialize the first 12 numerical values using the exact values\n\n    double x_position_exact, y_position_exact;\n\n    for (int j=-1; j <= 11; ++j)\n    {\n        if (j >= 0)\n            time += time_step;\n\n        x_position_exact = radius * cos(constant * time);\n        y_position_exact = radius * sin(constant * time);\n\n        if (j >= 0)\n        {\n            x_position_numerical(j) = x_position_exact;\n            y_position_numerical(j) = y_position_exact;\n        }\n\n        x_acceleration(j+1) = -gravitational_constant/pow(radius,3) \n            * x_position_exact;\n        y_acceleration(j+1) = -gravitational_constant/pow(radius,3)\n            * y_position_exact;\n    }\n\n    /*\n     * Compute exact kinetic and potential energies, and the\n     * angular momentum.  These values are all divided by the mass\n     * of the object.  Since they are conserved, they will never change\n     * and hence do not have to be recalculated later.\n     */\n\n    double x_dot_exact = -radius * constant * sin(constant*time),\n         y_dot_exact =  radius * constant * cos(constant*time),\n         exact_velocity_squared = pow(x_dot_exact,2) + pow(y_dot_exact,2),\n         exact_kinetic_energy = 0.5 * exact_velocity_squared,\n         exact_potential_energy = -gravitational_constant / radius,\n         exact_total_energy = exact_potential_energy + exact_kinetic_energy,\n         exact_angular_momentum = x_position_exact * y_dot_exact\n             - y_position_exact * x_dot_exact;\n\n    double x_dot_numerical, y_dot_numerical;\n\n    // Perform loop over time\n\n    while (time <= stop_time)                           \n    {\n        // Advance time step (eek!)\n        time += time_step;        \n\n        // Calculate new acceleration of body at time=time-time_step\n        double numerical_radius_squared = pow(x_position_numerical(11),2)\n            + pow(y_position_numerical(11),2);\n        x_acceleration(12) = -gravitational_constant\n            / pow(numerical_radius_squared, 1.5) * x_position_numerical(11);\n        y_acceleration(12) = -gravitational_constant\n            / pow(numerical_radius_squared, 1.5) * y_position_numerical(11);\n\n        // Numerically solve for the new positions using a 12th order\n        // symmetric multistep method.\n\n        // First sum the first and second terms\n\n        double x_alpha_sum = dot(alpha(Range(0,11)), \n            x_position_numerical(Range(0,11)));\n        double y_alpha_sum = dot(alpha(Range(0,11)), \n            y_position_numerical(Range(0,11)));\n\n        double x_beta_sum = dot(beta(Range(0,11)), x_acceleration(Range(1,12)));\n        double y_beta_sum = dot(beta(Range(0,11)), y_acceleration(Range(1,12)));\n        x_position_numerical(12) = (-x_alpha_sum) + pow(time_step,2) \n            * (x_beta_sum / beta_factor);\n        y_position_numerical(12) = (-y_alpha_sum) + pow(time_step,2)\n            * (y_beta_sum / beta_factor);\n\n        // Numerically solve for the new velocities using a 12th order\n        // Cowell predictor method.\n\n        // First sum the gamma terms\n\n        double x_gamma_sum = dot(gamma, x_acceleration.reverse()),\n               y_gamma_sum = dot(gamma, y_acceleration.reverse());\n\n        x_dot_numerical = (x_position_numerical(11)\n            - x_position_numerical(10)) / time_step + time_step \n            * (x_gamma_sum / gamma_factor);\n        y_dot_numerical = (y_position_numerical(11)\n            - y_position_numerical(10)) / time_step + time_step\n            * (y_gamma_sum / gamma_factor);\n\n        // Push the stack down one\n\n        for (int j=0; j <= 11; ++j)\n        {\n            x_position_numerical(j) = x_position_numerical(j+1);\n            y_position_numerical(j) = y_position_numerical(j+1);\n            x_acceleration(j) = x_acceleration(j+1);\n            y_acceleration(j) = y_acceleration(j+1);\n        }\n    }\n\n    // Print results\n\n    // First compute energies and angular momenta (add divided by the mass\n    // of the object)\n\n    double numerical_velocity_squared = pow(x_dot_numerical,2) +\n               pow(y_dot_numerical,2),\n           numerical_radius = sqrt(pow(x_position_numerical(12),2)\n               + pow(y_position_numerical(12),2)),\n           numerical_kinetic_energy = 0.5 * numerical_velocity_squared,\n           numerical_potential_energy = -gravitational_constant \n               / numerical_radius,\n           numerical_total_energy = numerical_potential_energy\n               + numerical_kinetic_energy,\n           numerical_angular_momentum = x_position_numerical(12)\n               * y_dot_numerical - y_position_numerical(12) * x_dot_numerical;\n\n    // Compute exact results for comparison to the numerical results\n\n   x_position_exact = radius * cos(constant * time);\n   y_position_exact = radius * sin(constant * time);\n   x_dot_exact = -radius * constant * sin(constant * time);\n   y_dot_exact =  radius * constant * cos(constant * time);\n\n    // Next compute relative errors\n\n    double radius_error = relativeError(numerical_radius, radius),\n           x_error = relativeError(x_position_numerical(12), x_position_exact),\n           y_error = relativeError(y_position_numerical(12), y_position_exact),\n           x_dot_error = relativeError(x_dot_numerical, x_dot_exact),\n           y_dot_error = relativeError(y_dot_numerical, y_dot_exact);\n\n    double kinetic_energy_error = relativeError(numerical_kinetic_energy,\n               exact_kinetic_energy),\n           potential_energy_error = relativeError(numerical_potential_energy,\n               exact_potential_energy),\n           total_energy_error = relativeError(numerical_total_energy,\n               exact_total_energy),\n           angular_momentum_error = relativeError(numerical_angular_momentum,\n               exact_angular_momentum);\n\n    cout << \" Time = \" << time << endl\n         << \"    x rel error  = \" << x_error << \" y rel error  = \" << y_error\n         << endl\n         << \"    vx rel error = \" << x_dot_error << \" vy rel error = \" \n         << y_dot_error << endl\n         << \"    KE rel error = \" << kinetic_energy_error \n         << \" PE rel error = \" << potential_energy_error << endl\n         << \"    TE rel error = \" << total_energy_error << \" AM rel error = \"\n         << angular_momentum_error << endl\n         << \"    numerical radius = \" << numerical_radius \n         << \" radius rel error = \" << radius_error << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "f2f1ffb8bec2dc7136fe5c3351efc567498794e9", "size": 9496, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/kepler.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/kepler.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/kepler.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": 38.9180327869, "max_line_length": 80, "alphanum_fraction": 0.6373209773, "num_tokens": 2484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6160408144383005}}
{"text": "#pragma once\n\n#include \"./base.hpp\"\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <cassert>\n#include <string>\n\nnamespace tools {\n  namespace cpp_int_helper {\n    namespace mp = boost::multiprecision;\n\n    string to_string(mp::cpp_int a) {\n      string res = \"\";\n      if (a < 0) {\n        a *= -1;\n        res += \"-\";\n      }\n\n      while (a) {\n        res += static_cast<char>(a % 10 + '0');\n        a /= 10;\n      }\n      return res;\n    }\n\n    mp::cpp_int gcd(mp::cpp_int a, mp::cpp_int b) {\n      mp::cpp_int tmp;\n      while (b > 0) {\n        tmp = a;\n        a = b;\n        b = tmp % b;\n      }\n      return a;\n    }\n\n    mp::cpp_int lcm(mp::cpp_int a, mp::cpp_int b) { return a * b / gcd(a, b); }\n\n    namespace power_helper {\n\n      mp::cpp_int extgcd(mp::cpp_int a, mp::cpp_int b, mp::cpp_int &x, mp::cpp_int &y) {\n        if (b == 0) {\n          x = 1;\n          y = 0;\n          return a;\n        }\n        mp::cpp_int d = extgcd(b, a % b, y, x);\n        y = y - (a / b) * x;\n        return d;\n      }\n\n    } // namespace power_helper\n\n    mp::cpp_int power(mp::cpp_int a, mp::cpp_int e, mp::cpp_int p = -1) {\n      assert(p != 0);\n      assert(p >= -1);\n\n      if (e < 0) {\n        assert(p != -1 and gcd(a, p) == 1);\n        mp::cpp_int x, y;\n        power_helper::extgcd(a, p, x, y);\n        a = (x % p + p) % p;\n        e *= -1;\n      }\n\n      mp::cpp_int res = 1;\n      while (e > 0) {\n        if (e & 1) {\n          res *= a;\n          if (p != -1) res %= p;\n        }\n        a *= a;\n        if (p != -1) a %= p;\n        e >>= 1;\n      }\n      return res;\n    }\n\n  } // namespace cpp_int_helper\n  using namespace cpp_int_helper;\n  using cint = boost::multiprecision::cpp_int;\n} // namespace tools", "meta": {"hexsha": "ecdfb704adc1b0d4aff5d0e4432eafa8bc0f0558", "size": 1722, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tools/cppint.hpp", "max_stars_repo_name": "matumoto1234/library", "max_stars_repo_head_hexsha": "a2c80516a8afe5876696c139fe0e837d8a204f69", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T11:21:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T05:57:25.000Z", "max_issues_repo_path": "tools/cppint.hpp", "max_issues_repo_name": "matumoto1234/library", "max_issues_repo_head_hexsha": "a2c80516a8afe5876696c139fe0e837d8a204f69", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 102.0, "max_issues_repo_issues_event_min_datetime": "2021-10-30T21:30:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T18:39:47.000Z", "max_forks_repo_path": "tools/cppint.hpp", "max_forks_repo_name": "matumoto1234/library", "max_forks_repo_head_hexsha": "a2c80516a8afe5876696c139fe0e837d8a204f69", "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": 21.0, "max_line_length": 88, "alphanum_fraction": 0.4488966318, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6160408097230072}}
{"text": "//\n// Copyright 2020 Debabrata Mandal <mandaldebabrata123@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include <boost/gil.hpp>\n#include <boost/gil/extension/io/png.hpp>\n#include <boost/gil/extension/numeric/algorithm.hpp>\n#include <boost/gil/image_processing/adaptive_histogram_equalization.hpp>\n\nusing namespace boost::gil;\n\n// Demonstrates Adaptive Histogram Equalization (AHE)\n\n// See also:\n// histogram.cpp - General use of histograms in GIL\n// histogram_equalization.cpp - Regular Histogram Equalization\n// histogram_matching.cpp - Reference-based histogram computation\n\nint main()\n{\n    gray8_image_t img;\n    read_image(\"test_adaptive.png\", img, png_tag{});\n    gray8_image_t img_out(img.dimensions());\n\n    boost::gil::non_overlapping_interpolated_clahe(view(img), view(img_out));\n    write_view(\"out-adaptive.png\", view(img_out), png_tag{});\n    return 0;\n}\n", "meta": {"hexsha": "3a0e23edc6bb62f705761efa69465ca588f982cc", "size": 1029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/adaptive_he.cpp", "max_stars_repo_name": "DhruvaG2000/gil", "max_stars_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/adaptive_he.cpp", "max_issues_repo_name": "DhruvaG2000/gil", "max_issues_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/adaptive_he.cpp", "max_forks_repo_name": "DhruvaG2000/gil", "max_forks_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1818181818, "max_line_length": 80, "alphanum_fraction": 0.7551020408, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6160408097230072}}
{"text": "//  (C) Copyright 2006 Eric Niebler, Olivier Gygi.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Test case for weighted_tail_quantile.hpp\n\n#define BOOST_NUMERIC_FUNCTIONAL_STD_COMPLEX_SUPPORT\n#define BOOST_NUMERIC_FUNCTIONAL_STD_VALARRAY_SUPPORT\n#define BOOST_NUMERIC_FUNCTIONAL_STD_VECTOR_SUPPORT\n\n#include <boost/random.hpp>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <boost/accumulators/statistics/weighted_tail_quantile.hpp>\n\nusing namespace boost;\nusing namespace unit_test;\nusing namespace boost::accumulators;\n\n///////////////////////////////////////////////////////////////////////////////\n// test_stat\n//\nvoid test_stat()\n{\n    // tolerance in %\n    double epsilon = 1;\n\n    std::size_t n = 100000; // number of MC steps\n    std::size_t c =  20000; // cache size\n\n    double mu1 = 1.0;\n    double mu2 = -1.0;\n    boost::lagged_fibonacci607 rng;\n    boost::normal_distribution<> mean_sigma1(mu1,1);\n    boost::normal_distribution<> mean_sigma2(mu2,1);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal1(rng, mean_sigma1);\n    boost::variate_generator<boost::lagged_fibonacci607&, boost::normal_distribution<> > normal2(rng, mean_sigma2);\n\n    accumulator_set<double, stats<tag::weighted_tail_quantile<right> >, double>\n        acc1(right_tail_cache_size = c);\n\n    accumulator_set<double, stats<tag::weighted_tail_quantile<left> >, double>\n        acc2(left_tail_cache_size = c);\n\n    for (std::size_t i = 0; i < n; ++i)\n    {\n        double sample1 = normal1();\n        double sample2 = normal2();\n        acc1(sample1, weight = std::exp(-mu1 * (sample1 - 0.5 * mu1)));\n        acc2(sample2, weight = std::exp(-mu2 * (sample2 - 0.5 * mu2)));\n    }\n\n    // check standard normal distribution\n    BOOST_CHECK_CLOSE( quantile(acc1, quantile_probability = 0.975),  1.959963, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc1, quantile_probability = 0.999),  3.090232, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc2, quantile_probability  = 0.025), -1.959963, epsilon );\n    BOOST_CHECK_CLOSE( quantile(acc2, quantile_probability  = 0.001), -3.090232, epsilon );\n\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// init_unit_test_suite\n//\ntest_suite* init_unit_test_suite( int argc, char* argv[] )\n{\n    test_suite *test = BOOST_TEST_SUITE(\"weighted_tail_quantile test\");\n\n    test->add(BOOST_TEST_CASE(&test_stat));\n\n    return test;\n}\n\n", "meta": {"hexsha": "33936661710bcef51c9143b838574ca6dc3ba9ae", "size": 2717, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/accumulators/test/weighted_tail_quantile.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/accumulators/test/weighted_tail_quantile.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/accumulators/test/weighted_tail_quantile.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 35.75, "max_line_length": 115, "alphanum_fraction": 0.6794258373, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176259, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6160407955947671}}
{"text": "\r\n#include \"vector.hh\"\r\n#include \"linear_system.hh\"\r\n#include <Eigen/Dense>\r\n\r\n\r\nnamespace Geo {\r\n\r\n/*!Finds _u and _v such that ||_w - _u * _a - _v * _b||^2 is minimal.\r\n*/\r\ntemplate<typename ValT, size_t N>\r\nbool decompose(const std::array<ValT, N>& _w,\r\n  const std::array<ValT, N>& _a, const std::array<ValT, N>& _b,\r\n  ValT& _u, ValT& _v)\r\n{\r\n  Eigen::MatrixXd A(N, 2);\r\n  Eigen::VectorXd B(N);\r\n  for (auto i = 0; i < N; ++i)\r\n  {\r\n    A(i, 0) = _a[i];\r\n    A(i, 1) = _b[i];\r\n    B[i] = _w[i];\r\n  }\r\n  Eigen::VectorXd res = A.colPivHouseholderQr().solve(B);\r\n  _u = res[0];\r\n  _v = res[1];\r\n  return true;\r\n}\r\n\r\ntemplate bool decompose(const std::array<double, 3>& _w,\r\n  const std::array<double, 3>& _a, const std::array<double, 3>& _b,\r\n  double& _u, double& _v);\r\n\r\ntemplate bool decompose(const std::array<double, 2>& _w,\r\n  const std::array<double, 2>& _a, const std::array<double, 2>& _b,\r\n  double& _u, double& _v);\r\n\r\n}//namespace Geo\r\n", "meta": {"hexsha": "ec219b2b59e489bff8df35b9b1cac818ea286f39", "size": 950, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main/src/Geo/vector.cc", "max_stars_repo_name": "marcomanno/ploygon_triangulation", "max_stars_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/src/Geo/vector.cc", "max_issues_repo_name": "marcomanno/ploygon_triangulation", "max_issues_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/src/Geo/vector.cc", "max_forks_repo_name": "marcomanno/ploygon_triangulation", "max_forks_repo_head_hexsha": "c98b99e3f9598252ffc27eb202939f0183ac872b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.358974359, "max_line_length": 70, "alphanum_fraction": 0.5894736842, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6160148082976925}}
{"text": "// Copyright (C) 2019 David Harmon and Artificial Necessity\n// This code distributed under zlib, see LICENSE.txt for terms.\n\n#pragma once\n\n#include <iostream>\n#include <Eigen/StdVector>\n\n#include \"energy.hpp\"\n\nclass ConstrainedGaussSeidel {\npublic:\n    bool compute(const SparseMatrixd& A) {\n        if (A.rows() != A.cols()) {\n            std::cerr << \"Non-square matrix A!\" << std::endl;\n            return false;\n        }\n\n        S_.resize(A.rows() / 3, Eigen::Matrix3d::Identity());\n\n        return true;\n    }\n\n    void reset() {\n        for (Eigen::Matrix3d& M : S_) {\n            M.setIdentity();\n        }\n    }\n\n    void setFilter(int idx, const Eigen::Matrix3d& C) {\n        S_[idx] = C;\n    }\n\n    void filterInPlace(Eigen::VectorXd& v) {\n        #pragma omp parallel for\n        for (size_t i=0; i<S_.size(); i++) {\n            v.segment<3>(3*i) = S_[i] * v.segment<3>(3*i);\n        }\n    }\n\n    Eigen::VectorXd filter(const Eigen::VectorXd& v) {\n        Eigen::VectorXd out(v.size());\n        #pragma omp parallel for\n        for (size_t i=0; i<S_.size(); i++) {\n            out.segment<3>(3*i) = S_[i] * v.segment<3>(3*i);\n        }\n        return out;\n    }\n\n    void solve(const SparseMatrixd& A, const Eigen::VectorXd& b, Eigen::VectorXd& x) {\n\n        const int max_iters = 1000;\n        const double max_error = 1.e0-5;\n        double error = 1.0;\n        int iter = 0;\n        while (iter < max_iters && error > max_error) {\n            error = 0.0;\n            //#pragma omp parallel for\n            for (int i=0; i<A.rows()/3; i++) {\n                Eigen::Vector3d x_tmp;\n                for (int j=0; j<3; j++) {\n                    int idx = 3 * i + j;\n\n                    double omega = 0.0;\n                    double a_ii;\n\n                    for (SparseMatrixd::InnerIterator rit(A, idx) ; rit; ++rit) {\n                        if (rit.col() == idx) {\n                            a_ii = rit.value();\n                        } else {\n                            omega += rit.value() * x[rit.col()];\n                        }\n                    }\n\n                    x_tmp[j] = (b[idx] - omega) / a_ii;\n                    error += (x_tmp[j] - x[idx]) * (x_tmp[j] - x[idx]);\n                }\n\n                x.segment<3>(3*i) += S_[i] * (x_tmp - x.segment<3>(3*i));\n            }\n\n            error = (A*x - b).norm();\n            iter++;\n        }\n\n        std::cout << \"Finished in \" << iter << \" with error \" << error << std::endl;\n\n    }\n\n    const Eigen::Matrix3d& S(int idx) {\n        return S_[idx];\n    }\n\nprotected:\n    std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>> S_;\n};\n\n\n", "meta": {"hexsha": "fefef750119086ee128d78e25bc90be607d82100", "size": 2645, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gauss_seidel.hpp", "max_stars_repo_name": "liuwei792966953/stitch", "max_stars_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-23T05:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-23T05:20:09.000Z", "max_issues_repo_path": "include/gauss_seidel.hpp", "max_issues_repo_name": "liuwei792966953/stitch", "max_issues_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gauss_seidel.hpp", "max_forks_repo_name": "liuwei792966953/stitch", "max_forks_repo_head_hexsha": "108e3dbd3410331c741c7cb166f93bbffa11b369", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7171717172, "max_line_length": 86, "alphanum_fraction": 0.4612476371, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6160148040070496}}
{"text": "#include <bitset>\n#include <boost/dynamic_bitset.hpp>\n#include <chrono>\n\n#include <stdio.h>\n#include <string.h>\n\nbool verbose = true;\n\nvoid sieve(int n) \n{ \n  auto start = std::chrono::system_clock::now();\n  boost::dynamic_bitset<> notprime(n+1);\n  for (int p = 2; p*p <= n; p++) {\n    if (notprime[p] == 0) {\n      for (int i = p*2; i <= n; i += p)\n\tnotprime[i] = 1;\n    }\n  }\n  auto end = std::chrono::system_clock::now();\n  std::chrono::duration<double> elapsed_seconds = end-start;\n  printf(\"Computation took %f sec\\n\", elapsed_seconds.count());\n  \n  if (!verbose)\n    return;\n  printf(\"Primes <= %d\\n\", n);\n  for (int p = 2; p <= n; p++) \n    if (notprime[p] == 0) \n      printf(\"%d \", p);\n  printf(\"\\n\");\n} \n  \nint main(int argc, char* argv[]) { \n  if (argc < 2) {\n    printf(\"era [-quiet] <n>: computes primes <= n\\n\");\n    return -1;\n  }\n  if (!strcmp(argv[1], \"-quiet\")) {\n    verbose = false;\n  }\n  int n = std::stoi(argv[argc-1]);\n  sieve(n); \n  return 0; \n} \n", "meta": {"hexsha": "4afc9d81b0e69c09fea3473cc58b038af1bb820c", "size": 971, "ext": "cc", "lang": "C++", "max_stars_repo_path": "primes/era.cc", "max_stars_repo_name": "maxpoletto/primes", "max_stars_repo_head_hexsha": "956d0694bd4d0f7e592ac2e121d07d31f06b8930", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "primes/era.cc", "max_issues_repo_name": "maxpoletto/primes", "max_issues_repo_head_hexsha": "956d0694bd4d0f7e592ac2e121d07d31f06b8930", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "primes/era.cc", "max_forks_repo_name": "maxpoletto/primes", "max_forks_repo_head_hexsha": "956d0694bd4d0f7e592ac2e121d07d31f06b8930", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5777777778, "max_line_length": 63, "alphanum_fraction": 0.5561277034, "num_tokens": 318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6160148034813601}}
{"text": "// Copyright Paul A. Bristow 2007, 2009.\r\n// Copyright John Maddock 2006.\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// test_pareto.cpp\r\n\r\n// http://en.wikipedia.org/wiki/pareto_distribution\r\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3661.htm\r\n// Also:\r\n// Weisstein, Eric W. \"pareto Distribution.\"\r\n// From MathWorld--A Wolfram Web Resource.\r\n// http://mathworld.wolfram.com/paretoDistribution.html\r\n\r\n\r\n#ifdef _MSC_VER\r\n#  pragma warning(disable: 4127) // conditional expression is constant.\r\n# pragma warning (disable : 4996) // POSIX name for this item is deprecated\r\n# pragma warning (disable : 4224) // nonstandard extension used : formal parameter 'arg' was previously defined as a type\r\n# pragma warning (disable : 4180) // qualifier applied to function type has no meaning; ignored\r\n#  pragma warning(disable: 4100) // unreferenced formal parameter.\r\n#endif\r\n\r\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\r\n#include <boost/test/test_exec_monitor.hpp> // Boost.Test\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\n#include <boost/math/distributions/pareto.hpp>\r\n    using boost::math::pareto_distribution;\r\n#include <boost/math/tools/test.hpp>\r\n#include \"test_out_of_range.hpp\"\r\n\r\n#include <iostream>\r\n   using std::cout;\r\n   using std::endl;\r\n   using std::setprecision;\r\n#include <limits>\r\n  using std::numeric_limits;\r\n\r\n  template <class RealType>\r\n  void check_pareto(RealType scale, RealType shape, RealType x, RealType p, RealType q, RealType tol)\r\n  {\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n      ::boost::math::cdf(\r\n      pareto_distribution<RealType>(scale, shape),   // distribution.\r\n      x),                                            // random variable.\r\n      p,                                             // probability.\r\n      tol);                                          // tolerance eps.\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n      ::boost::math::cdf(\r\n      complement(\r\n      pareto_distribution<RealType>(scale, shape),   // distribution.\r\n      x)),                                           // random variable.\r\n      q,                                             // probability complement.\r\n      tol);                                          // tolerance eps.\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n      ::boost::math::quantile(\r\n      pareto_distribution<RealType>(scale, shape),   // distribution.\r\n      p),                                            // probability.\r\n      x,                                             // random variable.\r\n      tol);                                          // tolerance eps.\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n      ::boost::math::quantile(\r\n      complement(\r\n      pareto_distribution<RealType>(scale, shape),    // distribution.\r\n      q)),                                        // probability complement.\r\n      x,                                             // random variable.\r\n      tol);                                          // tolerance eps.\r\n  } // check_pareto\r\n\r\ntemplate <class RealType>\r\nvoid test_spots(RealType)\r\n{\r\n   // Basic sanity checks.\r\n   //\r\n   // Tolerance are based on units of epsilon, but capped at\r\n   // double precision, since that's the limit of our test data:\r\n   //\r\n   RealType tol = (std::max)((RealType)boost::math::tools::epsilon<double>(), boost::math::tools::epsilon<RealType>());\r\n   RealType tol5eps = tol * 5;\r\n   RealType tol10eps = tol * 10;\r\n   RealType tol100eps = tol * 100;\r\n   RealType tol1000eps = tol * 1000;\r\n\r\n   check_pareto(\r\n      static_cast<RealType>(1.1L), //\r\n      static_cast<RealType>(5.5L),\r\n      static_cast<RealType>(2.2L),\r\n      static_cast<RealType>(0.97790291308792L),\r\n      static_cast<RealType>(0.0220970869120796L),\r\n      tol10eps * 4);\r\n\r\n   check_pareto(\r\n      static_cast<RealType>(0.5L),\r\n      static_cast<RealType>(10.1L),\r\n      static_cast<RealType>(1.5L),\r\n      static_cast<RealType>(0.99998482686481L),\r\n      static_cast<RealType>(1.51731351900608e-005L),\r\n      tol100eps * 1000); // Much less accurate as p close to unity.\r\n\r\n   check_pareto(\r\n      static_cast<RealType>(0.1L),\r\n      static_cast<RealType>(2.3L),\r\n      static_cast<RealType>(1.5L),\r\n      static_cast<RealType>(0.99802762220697L),\r\n      static_cast<RealType>(0.00197237779302972L),\r\n      tol1000eps);\r\n\r\n   // Example from 23.3 page 259\r\n   check_pareto(\r\n      static_cast<RealType>(2.30444301457005L),\r\n      static_cast<RealType>(4),\r\n      static_cast<RealType>(2.4L),\r\n      static_cast<RealType>(0.15L),\r\n      static_cast<RealType>(0.85L),\r\n      tol100eps);\r\n\r\n   check_pareto(\r\n      static_cast<RealType>(2),\r\n      static_cast<RealType>(3),\r\n      static_cast<RealType>(3.4L),\r\n      static_cast<RealType>(0.796458375737838L),\r\n      static_cast<RealType>(0.203541624262162L),\r\n      tol10eps);\r\n\r\n   check_pareto( // Probability near 0.5\r\n      static_cast<RealType>(2),\r\n      static_cast<RealType>(2),\r\n      static_cast<RealType>(3),\r\n      static_cast<RealType>(0.5555555555555555555555555555555555555556L),\r\n      static_cast<RealType>(0.4444444444444444444444444444444444444444L),\r\n      tol5eps); // accurate.\r\n\r\n\r\n   // Tests for:\r\n\r\n   // pdf for shapes 1, 2 & 3 (exact)\r\n   BOOST_CHECK_CLOSE_FRACTION(\r\n      pdf(pareto_distribution<RealType>(1, 1), 1),\r\n      static_cast<RealType>(1), //\r\n      tol5eps);\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(   pdf(pareto_distribution<RealType>(1, 2), 1),\r\n      static_cast<RealType>(2), //\r\n      tol5eps);\r\n\r\n     BOOST_CHECK_CLOSE_FRACTION(   pdf(pareto_distribution<RealType>(1, 3), 1),\r\n      static_cast<RealType>(3), //\r\n      tol5eps);\r\n\r\n   // cdf\r\n   BOOST_CHECK_EQUAL( // x = scale\r\n      cdf(pareto_distribution<RealType>(1, 1), 1),\r\n      static_cast<RealType>(0) );\r\n\r\n   // Compare with values from StatCalc K. Krishnamoorthy,  ISBN 1-58488-635-8 eq 23.1.3\r\n   BOOST_CHECK_CLOSE_FRACTION( // small x\r\n      cdf(pareto_distribution<RealType>(2, 5), static_cast<RealType>(3.4)),\r\n      static_cast<RealType>(0.929570372227626L), tol5eps);\r\n\r\n   BOOST_CHECK_CLOSE_FRACTION( // small x\r\n      cdf(pareto_distribution<RealType>(2, 5), static_cast<RealType>(3.4)),\r\n      static_cast<RealType>(1 - 0.0704296277723743L), tol5eps);\r\n\r\n   BOOST_CHECK_CLOSE_FRACTION( // small x\r\n      cdf(complement(pareto_distribution<RealType>(2, 5), static_cast<RealType>(3.4))),\r\n      static_cast<RealType>(0.0704296277723743L), tol5eps);\r\n\r\n   // quantile\r\n   BOOST_CHECK_EQUAL( // x = scale\r\n      quantile(pareto_distribution<RealType>(1, 1), 0),\r\n      static_cast<RealType>(1) );\r\n\r\n   BOOST_CHECK_EQUAL( // x = scale\r\n      quantile(complement(pareto_distribution<RealType>(1, 1), 1)),\r\n      static_cast<RealType>(1) );\r\n\r\n   BOOST_CHECK_CLOSE_FRACTION( // small x\r\n      cdf(complement(pareto_distribution<RealType>(2, 5), static_cast<RealType>(3.4))),\r\n      static_cast<RealType>(0.0704296277723743L), tol5eps);\r\n\r\n    using namespace std; // ADL of std names.\r\n\r\n    pareto_distribution<RealType> pareto15(1, 5);\r\n    // Note: shape must be big enough (5) that all moments up to kurtosis are defined\r\n    // to allow all functions to be tested.\r\n\r\n    // mean:\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n       mean(pareto15), static_cast<RealType>(1.25), tol5eps); // 1.25 == 5/4\r\n    BOOST_CHECK_EQUAL(\r\n       mean(pareto15), static_cast<RealType>(1.25)); // 1.25 == 5/4 (expect exact so check equal)\r\n\r\n    pareto_distribution<RealType> p12(1, 2); //\r\n    BOOST_CHECK_EQUAL(\r\n       mean(p12), static_cast<RealType>(2)); // Exactly two.\r\n\r\n    // variance:\r\n   BOOST_CHECK_CLOSE_FRACTION(\r\n       variance(pareto15), static_cast<RealType>(0.10416666666666667L), tol5eps);\r\n    // std deviation:\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n       standard_deviation(pareto15), static_cast<RealType>(0.32274861218395140L), tol5eps);\r\n    // hazard:   No independent test values found yet.\r\n    //BOOST_CHECK_CLOSE_FRACTION(\r\n    //   hazard(pareto15, x), pdf(pareto15, x) / cdf(complement(pareto15, x)), tol5eps);\r\n    //// cumulative hazard:\r\n    //BOOST_CHECK_CLOSE_FRACTION(\r\n    //   chf(pareto15, x), -log(cdf(complement(pareto15, x))), tol5eps);\r\n    //// coefficient_of_variation:\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n       coefficient_of_variation(pareto15), static_cast<RealType>(0.25819888974716110L), tol5eps);\r\n    // mode:\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n       mode(pareto15), static_cast<RealType>(1), tol5eps);\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n       median(pareto15), static_cast<RealType>(1.1486983549970351L), tol5eps);\r\n\r\n    // skewness:\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n       skewness(pareto15), static_cast<RealType>(4.6475800154489004L), tol5eps);\r\n    // kertosis:\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n       kurtosis(pareto15), static_cast<RealType>(73.8L), tol5eps);\r\n    // kertosis excess:\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n       kurtosis_excess(pareto15), static_cast<RealType>(70.8L), tol5eps);\r\n    // Check difference between kurtosis and excess:\r\n    BOOST_CHECK_CLOSE_FRACTION(\r\n      kurtosis_excess(pareto15), kurtosis(pareto15) - static_cast<RealType>(3L), tol5eps);\r\n    // Check kurtosis excess = kurtosis - 3;\r\n\r\n    // Error condition checks:\r\n    check_out_of_range<pareto_distribution<RealType> >(1, 1);\r\n    BOOST_CHECK_THROW(pdf(pareto_distribution<RealType>(0, 1), 0), std::domain_error);\r\n    BOOST_CHECK_THROW(pdf(pareto_distribution<RealType>(1, 0), 0), std::domain_error);\r\n    BOOST_CHECK_THROW(pdf(pareto_distribution<RealType>(-1, 1), 0), std::domain_error);\r\n    BOOST_CHECK_THROW(pdf(pareto_distribution<RealType>(1, -1), 0), std::domain_error);\r\n\r\n    BOOST_CHECK_THROW(pdf(pareto_distribution<RealType>(1, 1), 0), std::domain_error);\r\n    BOOST_CHECK_THROW(cdf(pareto_distribution<RealType>(1, 1), 0), std::domain_error);\r\n\r\n    BOOST_CHECK_THROW(quantile(pareto_distribution<RealType>(1, 1), -1), std::domain_error);\r\n    BOOST_CHECK_THROW(quantile(pareto_distribution<RealType>(1, 1), 2), std::domain_error);\r\n} // template <class RealType>void test_spots(RealType)\r\n\r\nint test_main(int, char* [])\r\n{\r\n  // Check that can generate pareto distribution using the two convenience methods:\r\n   boost::math::pareto myp1(1., 1); // Using typedef\r\n   pareto_distribution<> myp2(1., 1); // Using default RealType double.\r\n  boost::math::pareto pareto11; // Use default values (scale = 1, shape = 1).\r\n  // Note NOT pareto11() as the compiler will interpret as a function!\r\n   // Basic sanity-check spot values.\r\n\r\n  BOOST_CHECK_EQUAL(pareto11.scale(), 1); // Check defaults again.\r\n  BOOST_CHECK_EQUAL(pareto11.shape(), 1);\r\n  BOOST_CHECK_EQUAL(myp1.scale(), 1);\r\n  BOOST_CHECK_EQUAL(myp1.shape(), 1);\r\n  BOOST_CHECK_EQUAL(myp2.scale(), 1);\r\n  BOOST_CHECK_EQUAL(myp2.shape(), 1);\r\n\r\n  // Test range and support using double only,\r\n  // because it supports numeric_limits max for pseudo-infinity.\r\n  BOOST_CHECK_EQUAL(range(myp2).first, 0); // range 0 to +infinity\r\n  BOOST_CHECK_EQUAL(range(myp2).second, (numeric_limits<double>::max)());\r\n  BOOST_CHECK_EQUAL(support(myp2).first, myp2.scale()); // support scale to + infinity.\r\n  BOOST_CHECK_EQUAL(support(myp2).second, (numeric_limits<double>::max)());\r\n\r\n  // Check some bad parameters to the distribution.\r\n   BOOST_CHECK_THROW(boost::math::pareto mypm1(-1, 1), std::domain_error); // Using typedef\r\n   BOOST_CHECK_THROW(boost::math::pareto myp0(0, 1), std::domain_error); // Using typedef\r\n   BOOST_CHECK_THROW(boost::math::pareto myp1m1(1, -1), std::domain_error); // Using typedef\r\n   BOOST_CHECK_THROW(boost::math::pareto myp10(1, 0), std::domain_error); // Using typedef\r\n\r\n  // Check some moments that should fail because shape not big enough.\r\n  BOOST_CHECK_THROW(variance(myp2), std::domain_error);\r\n  BOOST_CHECK_THROW(standard_deviation(myp2), std::domain_error);\r\n  BOOST_CHECK_THROW(skewness(myp2), std::domain_error);\r\n  BOOST_CHECK_THROW(kurtosis(myp2), std::domain_error);\r\n  BOOST_CHECK_THROW(kurtosis_excess(myp2), std::domain_error);\r\n\r\n  // Test on extreme values of distribution parameters,\r\n  // using just double because it has numeric_limit infinity etc.\r\n   BOOST_CHECK_THROW(boost::math::pareto mypinf1(+std::numeric_limits<double>::infinity(), 1), std::domain_error); // Using typedef\r\n   BOOST_CHECK_THROW(boost::math::pareto myp1inf(1, +std::numeric_limits<double>::infinity()), std::domain_error); // Using typedef\r\n   BOOST_CHECK_THROW(boost::math::pareto mypinf1(+std::numeric_limits<double>::infinity(), +std::numeric_limits<double>::infinity()), std::domain_error); // Using typedef\r\n\r\n  // Test on extreme values of random variate x, using just double because it has numeric_limit infinity etc..\r\n  // No longer allow x to be + or - infinity, then these tests should throw.\r\n  BOOST_CHECK_THROW(pdf(pareto11, +std::numeric_limits<double>::infinity()), std::domain_error); // x = + infinity\r\n  BOOST_CHECK_THROW(pdf(pareto11, -std::numeric_limits<double>::infinity()), std::domain_error); // x = - infinity\r\n  BOOST_CHECK_THROW(cdf(pareto11, +std::numeric_limits<double>::infinity()), std::domain_error); // x = + infinity\r\n  BOOST_CHECK_THROW(cdf(pareto11, -std::numeric_limits<double>::infinity()), std::domain_error); // x = - infinity\r\n\r\n  BOOST_CHECK_EQUAL(pdf(pareto11, 0.5), 0); // x < scale but > 0\r\n  BOOST_CHECK_EQUAL(pdf(pareto11, (std::numeric_limits<double>::min)()), 0); // x almost zero but > 0\r\n  BOOST_CHECK_EQUAL(pdf(pareto11, 1), 1); // x == scale, result == shape == 1\r\n  BOOST_CHECK_EQUAL(pdf(pareto11, +(std::numeric_limits<double>::max)()), 0); // x = +max, pdf has fallen to zero.\r\n\r\n  BOOST_CHECK_THROW(pdf(pareto11, 0), std::domain_error); // x == 0\r\n  BOOST_CHECK_THROW(pdf(pareto11, -1), std::domain_error); // x = -1\r\n  BOOST_CHECK_THROW(pdf(pareto11, -(std::numeric_limits<double>::max)()), std::domain_error); // x = - max\r\n  BOOST_CHECK_THROW(pdf(pareto11, -(std::numeric_limits<double>::min)()), std::domain_error); // x = - min\r\n\r\n  BOOST_CHECK_EQUAL(cdf(pareto11, 1), 0); // x == scale, cdf = zero.\r\n  BOOST_CHECK_EQUAL(cdf(pareto11, +(std::numeric_limits<double>::max)()), 1); // x = + max, cdf = unity.\r\n\r\n  BOOST_CHECK_THROW(cdf(pareto11, 0), std::domain_error); // x == 0\r\n  BOOST_CHECK_THROW(cdf(pareto11, -(std::numeric_limits<double>::min)()), std::domain_error); // x = - min,\r\n  BOOST_CHECK_THROW(cdf(pareto11, -(std::numeric_limits<double>::max)()), std::domain_error); // x = - max,\r\n\r\n   // (Parameter value, arbitrarily zero, only communicates the floating point type).\r\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tol5eps = 0.0001 %\r\n  test_spots(0.0); // Test double. OK at decdigits 7, tol5eps = 1e07 %\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n  test_spots(0.0L); // Test long double.\r\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x0582))\r\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\r\n#endif\r\n#else\r\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\r\n      \"either because the long double overloads of the usual math functions are \"\r\n      \"not available at all, or because they are too inaccurate for these tests \"\r\n      \"to pass.</note>\" << std::cout;\r\n#endif\r\n\r\n   return 0;\r\n} // int test_main(int, char* [])\r\n\r\n/*\r\n\r\nOutput:\r\n\r\nCompiling...\r\ntest_pareto.cpp\r\nLinking...\r\nEmbedding manifest...\r\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_pareto.exe\"\r\nRunning 1 test case...\r\n*** No errors detected\r\n\r\n\r\n\r\n*/\r\n\r\n\r\n", "meta": {"hexsha": "0e153d99e19a176458220a784f25c904209f0b5e", "size": 15516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_pareto.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/math/test/test_pareto.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/math/test/test_pareto.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 44.2051282051, "max_line_length": 171, "alphanum_fraction": 0.661446249, "num_tokens": 4206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6159862756260981}}
{"text": "#pragma once\n#include \"Chains.hpp\"\n#include <Eigen/Sparse>\n\n///@file\n///@brief Contains the classes \\ref mackey::AMT and \\ref mackey::EquivariantAMT\n\nnamespace mackey {\n\n\t///\t@brief\t Performs algebraic Morse theory reduction \n\t///\t@details Reduces given chain complex to a homotopy equivalent one but ideally smaller, using Algebraic Morse Theory\n\t///\t@warning The constructor performs the computation and modifies the chain complex in place to avoid copies. \n\t/// If you need the original chain complex please store it before passing it here.\n\ttemplate<typename diff_t>\n\tclass AMT {\n\tpublic:\n\n\t\t///Returns vector of \"change of basis\" matrices from the original to the reduced basis\n\t\tconst auto& original_to_reduced() const;\n\n\t\t///Returns vector of \"change of basis\" matrices from the reduced to the original basis\n\t\tconst auto& reduced_to_original() const;\n\n\t\t///Returns the average compression ratio as a double in [0,1]. Ideally as close to 0 as possible.\n\t\tdouble reduction_ratio() const;\n\n\t\t///Constructor that reduces\n\t\tAMT(std::vector<diff_t>& A, bool compute_original_to_reduced, bool compute_reduced_to_original);\n\n\tprotected:\n\n\t\t///Constructor that allows only to resize\n\t\tAMT(std::vector<diff_t>& A, bool compute_original_to_reduced, bool compute_reduced_to_original, bool onlyresize);\n\n\t\ttypedef typename diff_t::StorageIndex ind; ///<The storage type of the differential matrices (eg size_t)\n\t\ttypedef typename diff_t::Scalar scalar_t; ///<The scalar type of the differential matrices (eg int or Z2)\n\t\ttypedef Eigen::SparseMatrix<scalar_t, 1, ind> row_major_t; ///<The type of row major of the differential matrices (eg size_t)\n\n\t\tstd::vector<diff_t>& diff; ///<The reduced differential\n\t\tstd::vector<std::map<ind, ind>> morse; ///<The morse matching\n\t\tstd::vector<std::vector<ind>> critical; ///<The critical basis elements\n\n\t\t///Performs the reduction and sets the \"change of basis\" f,g.\n\t\tvoid reduce();\n\n\t\t///Sets the morse matchiing and normalizes diff if normalize=1 (this speeds up the AMT algorithm)\n\t\tvoid find_Morse_matching(int k, bool normalize);\n\n\t\t///Normalize diff if not done in find_Morse_matching\n\t\tvoid normalize(int k);\n\n\t\t///Erase the given morse matchings (eg if they are not equivariant).\n\t\tvoid erase_matchings(int k, const std::vector<std::pair<ind, ind>>& toremove);\n\n\tprivate:\n\t\tconst bool getf;\n\t\tconst bool getg;\n\n\t\tsize_t original_size; ///<Needed for the ratio\n\t\tstd::vector<diff_t> f; ///<The original to reduced \"change of basis\"\n\t\tstd::vector<diff_t> g; ///<The reduced to original \"change of basis\"\n\t\tstd::vector<std::map<ind, ind>> morse_inverse; ///<The inverse of the morse matching\n\t\tstd::vector<std::map<ind, scalar_t>> normalizing_coefficients; ///<The normalizing coefficients used in the computation\n\t\tsize_t compute_size() const;\n\t\tvoid resize();\n\t\tvoid set_critical();\n\t\tvoid kill_dead_paths();\n\t\tauto zig_zag_differential(int k, ind col) const;\n\t\tauto zig_zag_f(int k, ind col) const;\n\t\tauto zig_zag_g(int k, ind col) const;\n\t\tvoid set_f(int k);\n\t\tvoid set_g(int k);\n\t\tvoid reduce_diff(int k);\n\n\t};\n\n\t///\t@brief\t Performs algebraic Morse theory reduction preserving equivariance\n\t///\t@details Reduces given equivariant chain complex to a homotopy equivalent one but ideally smaller, using equivariant variant of \n\t///\t\t\t algebraic Morse theory\n\t///\t@warning The constructor performs the computation and modifies the chain complex in place to avoid copies. \n\t/// If you need the original chain complex please store it before passing it here.\n\ttemplate<typename rank_t, typename diff_t>\n\tclass EquivariantAMT : public AMT<diff_t> {\n\n\tpublic:\n\t\t///Constructor that performs the computation\n\t\tEquivariantAMT(Chains<rank_t, diff_t>& C, bool compute_original_to_reduced, bool compute_reduced_to_original);\n\n\tprivate:\n\n\t\tusing typename AMT<diff_t>::ind;\n\t\tusing typename AMT<diff_t>::scalar_t;\n\n\t\tChains<rank_t, diff_t>& C;\n\t\tstd::vector<std::vector<int64_t>> rank_sums;\n\t\tauto find_index(int k, ind element) const;\n\t\tauto find_orbit(int k, ind element) const;\n\t\tauto find_non_equivariant_matching(int k) const;\n\t\tvoid set_rank_sums();\n\t\tvoid compute_ranks();\n\t\tvoid compute();\n\t};\n}\n#include \"impl/Morse.ipp\"\n", "meta": {"hexsha": "a3e3f64ccfe708323e3a4002163249bee86f76d8", "size": 4163, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/Chain_Complexes/Morse.hpp", "max_stars_repo_name": "NickG-Math/Mackey", "max_stars_repo_head_hexsha": "0bd1e5b8aca16f3422c4ab9c5656990e1b501e54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Chain_Complexes/Morse.hpp", "max_issues_repo_name": "NickG-Math/Mackey", "max_issues_repo_head_hexsha": "0bd1e5b8aca16f3422c4ab9c5656990e1b501e54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Chain_Complexes/Morse.hpp", "max_forks_repo_name": "NickG-Math/Mackey", "max_forks_repo_head_hexsha": "0bd1e5b8aca16f3422c4ab9c5656990e1b501e54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6476190476, "max_line_length": 133, "alphanum_fraction": 0.746096565, "num_tokens": 1053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6159862711797305}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\n\ninline void write_quaternion_2_file(fstream &file, Eigen::Quaterniond &qua){\n    file << qua.w() << \" \" << qua.x() << \" \" << qua.y() << \" \" << qua.z() << endl;\n}\n\ninline void read_rotation_from_kitti_pose(fstream &file, Eigen::Matrix3d &rot){\n    double x, y, z, w;\n    for(int i=0; i<3; ++i){\n        file >> x >> y >> z >> w;\n        rot(i, 0) = x;\n        rot(i, 1) = y;\n        rot(i, 2) = z;\n    }\n}\n\nint main(){\n    string path_in = \"/home/chenchr/Dataset/kitti/poses/00.txt\";\n    string path_out = \"/home/chenchr/qua_eigen.txt\";\n    fstream file_in(path_in, ios::in);\n    fstream file_out(path_out, ios::out); \n    for(int i=0; i<100; ++i){\n        Eigen::Matrix3d temp;\n        read_rotation_from_kitti_pose(file_in, temp);\n        Eigen::Quaterniond qua(temp);\n        write_quaternion_2_file(file_out, qua);\n    }\n    return 0;\n}", "meta": {"hexsha": "4f115c29c3e0eadba3ecf5c975fd7e0afad5a143", "size": 950, "ext": "cc", "lang": "C++", "max_stars_repo_path": "misc_cxx/rotation2quaternion.cc", "max_stars_repo_name": "chenchr/PoseNet", "max_stars_repo_head_hexsha": "d8c0d1071db21652a7cb4b2715747ef346c8f706", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-09T03:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-10T00:13:56.000Z", "max_issues_repo_path": "misc_cxx/rotation2quaternion.cc", "max_issues_repo_name": "chenchr/PoseNet", "max_issues_repo_head_hexsha": "d8c0d1071db21652a7cb4b2715747ef346c8f706", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc_cxx/rotation2quaternion.cc", "max_forks_repo_name": "chenchr/PoseNet", "max_forks_repo_head_hexsha": "d8c0d1071db21652a7cb4b2715747ef346c8f706", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9411764706, "max_line_length": 82, "alphanum_fraction": 0.5915789474, "num_tokens": 290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041658, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6159862598626654}}
{"text": "/**\n * \\file ButterworthFilter.cpp\n */\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/polynomial.hpp>\n\n#include \"ButterworthFilter.h\"\n#include \"helpers.h\"\n#include \"IIRFilter.h\"\n\nnamespace\n{\n  template<typename DataType>\n  void create_butterworth_analog_coefficients(int order, std::vector<std::complex<DataType> >& z, std::vector<std::complex<DataType> >& p, DataType& k)\n  {\n    k = 1;\n    z.clear(); // no zeros for this filter type\n    p.clear();\n    for(int i = -order+1; i < order; i += 2)\n    {\n      p.push_back(std::complex<DataType>(-std::cos(boost::math::constants::pi<DataType>() * i / (2 * order)), -std::sin(boost::math::constants::pi<DataType>() * i / (2 * order))));\n    }\n  }\n  \n  template<typename DataType>\n  void create_default_coeffs(size_t order, DataType Wn, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)\n  {\n    std::vector<std::complex<DataType> > z;\n    std::vector<std::complex<DataType> > p;\n    DataType k;\n    \n    int fs = 2;\n    create_butterworth_analog_coefficients(static_cast<int>(order), z, p, k);\n    DataType warped = 2 * fs * std::tan(boost::math::constants::pi<DataType>() *  Wn / fs);\n    zpk_lp2lp(warped, z, p, k);\n    zpk_bilinear(fs, z, p, k);\n    \n    boost::math::tools::polynomial<DataType> b;\n    boost::math::tools::polynomial<DataType> a;\n    \n    zpk2ba(fs, z, p, k, b, a);\n    for(int i = 0; i < std::min(order + 1, b.size()); ++i)\n    {\n      coefficients_in[i] = b[i];\n    }\n    for(int i = 0; i < std::min(order, a.size()-1); ++i)\n    {\n      coefficients_out[i] = -a[i];\n    }\n  }\n\n  template<typename DataType>\n  void create_bp_coeffs(size_t order, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)\n  {\n    std::vector<std::complex<DataType> > z;\n    std::vector<std::complex<DataType> > p;\n    DataType k;\n    \n    int fs = 2;\n    create_butterworth_analog_coefficients(static_cast<int>(order/2), z, p, k);\n    wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);\n    wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);\n    \n    zpk_lp2bp(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n    zpk_bilinear(fs, z, p, k);\n    \n    boost::math::tools::polynomial<DataType> b;\n    boost::math::tools::polynomial<DataType> a;\n    \n    zpk2ba(fs, z, p, k, b, a);\n    \n    for(size_t i = 0; i < std::min(order + 1, b.size()); ++i)\n    {\n      coefficients_in[i] = b[i];\n    }\n    for(size_t i = 0; i < std::min(order, a.size()-1); ++i)\n    {\n      coefficients_out[i] = -a[i];\n    }\n  }\n  \n  template<typename DataType>\n  void create_bs_coeffs(size_t order, DataType wc1, DataType wc2, std::vector<DataType>& coefficients_in, std::vector<DataType>& coefficients_out)\n  {\n    std::vector<std::complex<DataType> > z;\n    std::vector<std::complex<DataType> > p;\n    DataType k;\n    \n    int fs = 2;\n    create_butterworth_analog_coefficients(static_cast<int>(order/2), z, p, k);\n    wc1 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc1 / fs);\n    wc2 = 2 * fs * std::tan(boost::math::constants::pi<DataType>() * wc2 / fs);\n    \n    zpk_lp2bs(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n    zpk_bilinear(fs, z, p, k);\n    \n    boost::math::tools::polynomial<DataType> b;\n    boost::math::tools::polynomial<DataType> a;\n    \n    zpk2ba(fs, z, p, k, b, a);\n    \n    for(size_t i = 0; i < std::min(order + 1, b.size()); ++i)\n    {\n      coefficients_in[i] = b[i];\n    }\n    for(size_t i = 0; i < std::min(order, a.size()-1); ++i)\n    {\n      coefficients_out[i] = -a[i];\n    }\n  }\n}\n\nnamespace ATK\n{\n  template <typename DataType>\n  ButterworthLowPassCoefficients<DataType>::ButterworthLowPassCoefficients(int nb_channels)\n  :Parent(nb_channels, nb_channels), cut_frequency(0), in_order(1), out_order(1)\n  {\n  }\n  \n  template <typename DataType_>\n  void ButterworthLowPassCoefficients<DataType_>::set_cut_frequency(DataType_ cut_frequency)\n  {\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ ButterworthLowPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n\n  template <typename DataType>\n  void ButterworthLowPassCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  void ButterworthLowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_default_coeffs(in_order, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n\n  template <typename DataType>\n  ButterworthHighPassCoefficients<DataType>::ButterworthHighPassCoefficients(int nb_channels)\n  :Parent(nb_channels, nb_channels), cut_frequency(0), in_order(1), out_order(1)\n  {\n  }\n  \n  template <typename DataType_>\n  void ButterworthHighPassCoefficients<DataType_>::set_cut_frequency(DataType_ cut_frequency)\n  {\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ ButterworthHighPassCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n  \n  template <typename DataType>\n  void ButterworthHighPassCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = order;\n    setup();\n  }\n  \n  template <typename DataType>\n  void ButterworthHighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_default_coeffs(in_order, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);\n    for(int i = in_order - 1; i >= 0; i -= 2)\n    {\n      coefficients_in[i] = - coefficients_in[i];\n      coefficients_out[i] = - coefficients_out[i];\n    }\n  }\n\n  template <typename DataType>\n  ButterworthBandPassCoefficients<DataType>::ButterworthBandPassCoefficients(int nb_channels)\n  :Parent(nb_channels, nb_channels), cut_frequencies(0, 0), in_order(1), out_order(1)\n  {\n  }\n\n  template <typename DataType_>\n  void ButterworthBandPassCoefficients<DataType_>::set_cut_frequencies(std::pair<DataType_, DataType_> cut_frequencies)\n  {\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n\n  template <typename DataType_>\n  void ButterworthBandPassCoefficients<DataType_>::set_cut_frequencies(DataType_ f0, DataType_ f1)\n  {\n    this->cut_frequencies = std::make_pair(f0, f1);\n    setup();\n  }\n\n  template <typename DataType_>\n  std::pair<DataType_, DataType_> ButterworthBandPassCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n\n  template <typename DataType>\n  void ButterworthBandPassCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = 2 * order;\n    setup();\n  }\n\n  template <typename DataType>\n  void ButterworthBandPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_bp_coeffs(in_order, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n\n  template <typename DataType>\n  ButterworthBandStopCoefficients<DataType>::ButterworthBandStopCoefficients(int nb_channels)\n  :Parent(nb_channels, nb_channels), cut_frequencies(0, 0), in_order(1), out_order(1)\n  {\n  }\n  \n  template <typename DataType_>\n  void ButterworthBandStopCoefficients<DataType_>::set_cut_frequencies(std::pair<DataType_, DataType_> cut_frequencies)\n  {\n    this->cut_frequencies = cut_frequencies;\n    setup();\n  }\n  \n  template <typename DataType_>\n  void ButterworthBandStopCoefficients<DataType_>::set_cut_frequencies(DataType_ f0, DataType_ f1)\n  {\n    this->cut_frequencies = std::make_pair(f0, f1);\n    setup();\n  }\n  \n  template <typename DataType_>\n  std::pair<DataType_, DataType_> ButterworthBandStopCoefficients<DataType_>::get_cut_frequencies() const\n  {\n    return cut_frequencies;\n  }\n  \n  template <typename DataType>\n  void ButterworthBandStopCoefficients<DataType>::set_order(int order)\n  {\n    in_order = out_order = 2 * order;\n    setup();\n  }\n  \n  template <typename DataType>\n  void ButterworthBandStopCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n    \n    create_bs_coeffs(in_order, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n  }\n\n  template class ButterworthLowPassCoefficients<float>;\n  template class ButterworthLowPassCoefficients<double>;\n  template class ButterworthHighPassCoefficients<float>;\n  template class ButterworthHighPassCoefficients<double>;\n  template class ButterworthBandPassCoefficients<float>;\n  template class ButterworthBandPassCoefficients<double>;\n  template class ButterworthBandStopCoefficients<float>;\n  template class ButterworthBandStopCoefficients<double>;\n  \n  template class IIRFilter<ButterworthLowPassCoefficients<float> >;\n  template class IIRFilter<ButterworthLowPassCoefficients<double> >;\n  template class IIRFilter<ButterworthHighPassCoefficients<float> >;\n  template class IIRFilter<ButterworthHighPassCoefficients<double> >;\n  template class IIRFilter<ButterworthBandPassCoefficients<float> >;\n  template class IIRFilter<ButterworthBandPassCoefficients<double> >;\n  template class IIRFilter<ButterworthBandStopCoefficients<float> >;\n  template class IIRFilter<ButterworthBandStopCoefficients<double> >;\n\n}\n", "meta": {"hexsha": "cd9f3a91459464018bc90c3e3da7499af317f6bc", "size": 9620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/ButterworthFilter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "ATK/EQ/ButterworthFilter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ATK/EQ/ButterworthFilter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 32.2818791946, "max_line_length": 180, "alphanum_fraction": 0.6997920998, "num_tokens": 2608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.6723316860482763, "lm_q1q2_score": 0.615929525729318}}
{"text": "/**\n * @file gradient_descent_test.cpp\n * @author Sumedh Ghaisas\n *\n * Test file for Gradient Descent optimizer.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/core/optimizers/gradient_descent/gradient_descent.hpp>\n#include <mlpack/core/optimizers/lbfgs/test_functions.hpp>\n#include <mlpack/core/optimizers/gradient_descent/test_function.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace std;\nusing namespace arma;\nusing namespace mlpack;\nusing namespace mlpack::optimization;\nusing namespace mlpack::optimization::test;\n\nBOOST_AUTO_TEST_SUITE(GradientDescentTest);\n\nBOOST_AUTO_TEST_CASE(SimpleGDTestFunction)\n{\n  GDTestFunction f;\n  GradientDescent<GDTestFunction> s(f, 0.01, 5000000, 1e-9);\n\n  arma::vec coordinates = f.GetInitialPoint();\n  double result = s.Optimize(coordinates);\n\n  BOOST_REQUIRE_SMALL(result, 1e-4);\n  BOOST_REQUIRE_SMALL(coordinates[0], 1e-2);\n  BOOST_REQUIRE_SMALL(coordinates[1], 1e-2);\n  BOOST_REQUIRE_SMALL(coordinates[2], 1e-2);\n}\n\nBOOST_AUTO_TEST_CASE(RosenbrockTest)\n{\n  // Create the Rosenbrock function.\n  RosenbrockFunction f;\n\n  GradientDescent<RosenbrockFunction> s(f, 0.001, 0, 1e-15);\n\n  arma::mat coordinates = f.GetInitialPoint();\n  double result = s.Optimize(coordinates);\n\n  BOOST_REQUIRE_SMALL(result, 1e-10);\n  for (size_t j = 0; j < 2; ++j)\n    BOOST_REQUIRE_CLOSE(coordinates[j], (double) 1.0, 1e-3);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "146054e0c0606afc9aaa40fceeb978c7462d2cb7", "size": 1703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/gradient_descent_test.cpp", "max_stars_repo_name": "NaxAlpha/mlpack-build", "max_stars_repo_head_hexsha": "1f0c1454d4b35eb97ff115669919c205cee5bd1c", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-21T11:08:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:52:14.000Z", "max_issues_repo_path": "src/mlpack/tests/gradient_descent_test.cpp", "max_issues_repo_name": "okmegy/Mlpack", "max_issues_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/gradient_descent_test.cpp", "max_forks_repo_name": "okmegy/Mlpack", "max_forks_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3620689655, "max_line_length": 78, "alphanum_fraction": 0.7592483852, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940927, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6159012651039574}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing Eigen::MatrixXd;\n\nusing namespace std;\n\nvoid TestEigenMatrix1();\nvoid TestEigenMatrix2();\n\nint main()\n{\n    //TestEigenMatrix1();\n    TestEigenMatrix2();\n    cout << \"Finished!\" << endl;\n    return 0;\n}\n\nvoid TestEigenMatrix2()\n{\n    int nodesPerLevel = 36;\n    char buf[255]={0,};\n    double radius = 10;\n    for (int n = 0; n < nodesPerLevel; n++)\n    {\n        Eigen::AngleAxisd rotz(-M_PI + 2*n*M_PI / nodesPerLevel, Eigen::Vector3d::UnitZ());\n        //Eigen::AngleAxisd roty(-0.5*M_PI + id*M_PI / (numLaps * nodesPerLevel), Eigen::Vector3d::UnitY());\n        Eigen::Matrix3d rot = rotz.toRotationMatrix();// (rotz * roty).toRotationMatrix();\n        Eigen::Isometry3d t;\n        t = rot;\n        t.translation() = t.linear() * Eigen::Vector3d(radius, 0, 0);\n        \n        Eigen::Transform<double, 3, 1, 0>::LinearPart l = t.linear();\n        \n        cout << \"#\" << n << endl;\n        \n        //row-wise\n        sprintf(buf, \"%f\\t%f\\t%f\\t%f\\n%f\\t%f\\t%f\\t%f\\n%f\\t%f\\t%f\\t%f\\n%f\\t%f\\t%f\\t%f\",\n                t(0,0), t(0,1),t(0,2), t(0,3),\n                t(1,0), t(1,1),t(1,2), t(1,3),\n                t(2,0), t(2,1),t(2,2), t(2,3),\n                t(3,0), t(3,1),t(3,2), t(3,3) );\n        cout << buf << endl<< endl;\n        \n        sprintf(buf, \"%f\\t%f\\t%f\\n%f\\t%f\\t%f\\n%f\\t%f\\t%f\",\n                rot(0,0), rot(0,1),rot(0,2),\n                rot(1,0), rot(1,1),rot(1,2),\n                rot(2,0), rot(2,1),rot(2,2));\n        cout << buf << endl;\n        //sprintf(buf, \"Linear part: %f\\t%f\\t%f\\n\", l(0,0), l(1,0), l(2,0));\n        cout << \"Linear part: \\n\"<< l << endl;\n        \n        // Quaternion<double> \n        Eigen::Quaterniond quat1 = (Eigen::Quaterniond) l;\n        Eigen::Quaterniond::Coefficients coeff1= quat1.coeffs();\n        // typedef Matrix<_Scalar,4,1,_Options> Coefficients;\n        \n        cout << \"Linear part(quaternion version): \\n\"<< coeff1(0,0)<< \" \" <<coeff1(1,0)<< \" \" <<coeff1(2,0)<< \" \" <<coeff1(3,0) << endl;\n        cout <<coeff1 << endl;\n        //cout << buf << endl<< endl;\n\n    }\n}\n\n// from https://eigen.tuxfamily.org/dox-devel/group__TutorialAdvancedInitialization.html\nvoid TestEigenMatrix1()\n{\n    Matrix3f m;\n    m << 1, 2, 3,\n         4, 5, 6,\n         7, 8, 9;\n    cout << m;\n    cout << \"\\n\\n\";\n\n    // typedef Matrix< double , Dynamic , Dynamic > Eigen::MatrixXd\n    MatrixXd m2(2,2);\n    m2(0,0) = 3;\n    m2(1,0) = 2.5;\n    m2(0,1) = -1;\n    m2(1,1) = m2(1,0) + m2(0,1);\n    std::cout << m2 ;\n    cout << \"\\n\\n\";\n\n    const int size = 6;\n    MatrixXd mat1(size, size);\n    mat1.topLeftCorner(size/2, size/2)     = MatrixXd::Zero(size/2, size/2);\n    mat1.topRightCorner(size/2, size/2)    = MatrixXd::Identity(size/2, size/2);\n    mat1.bottomLeftCorner(size/2, size/2)  = MatrixXd::Identity(size/2, size/2);\n    mat1.bottomRightCorner(size/2, size/2) = MatrixXd::Zero(size/2, size/2);\n    std::cout << mat1 << std::endl << std::endl;\n\n    // see https://github.com/RainerKuemmerle/g2o/blob/master/g2o/examples/data_fitting/curve_fit.cpp\n    cout << Eigen::Matrix<double, 1, 1>::Identity() << endl << endl;\n    \n    Eigen::Matrix3d transNoise = Eigen::Matrix3d::Zero();\n    cout << transNoise <<endl;\n}\n", "meta": {"hexsha": "2e7235e8d105e74e50859f24047e412bf6501e6a", "size": 3259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Eigen/TestEigen/main.cpp", "max_stars_repo_name": "dalek7/umbrella", "max_stars_repo_head_hexsha": "cabf0367940905ca5164d104d7aef6ff719ee166", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T09:12:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T09:12:02.000Z", "max_issues_repo_path": "Eigen/TestEigen/main.cpp", "max_issues_repo_name": "dalek7/umbrella", "max_issues_repo_head_hexsha": "cabf0367940905ca5164d104d7aef6ff719ee166", "max_issues_repo_licenses": ["MIT"], "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/TestEigen/main.cpp", "max_forks_repo_name": "dalek7/umbrella", "max_forks_repo_head_hexsha": "cabf0367940905ca5164d104d7aef6ff719ee166", "max_forks_repo_licenses": ["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.59, "max_line_length": 136, "alphanum_fraction": 0.5366676895, "num_tokens": 1108, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.6159012585399459}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_LOG_INV_LOGIT_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_LOG_INV_LOGIT_HPP\n\n#include <stan/math/prim/scal/fun/log1p.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Returns the natural logarithm of the inverse logit of the\n * specified argument.\n *\n   \\f[\n   \\mbox{log\\_inv\\_logit}(x) =\n   \\begin{cases}\n     \\ln\\left(\\frac{1}{1+\\exp(-x)}\\right)& \\mbox{if } -\\infty\\leq x \\leq \\infty\n \\\\[6pt] \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN} \\end{cases} \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{log\\_inv\\_logit}(x)}{\\partial x} =\n   \\begin{cases}\n     \\frac{1}{1+\\exp(x)} & \\mbox{if } -\\infty\\leq x\\leq \\infty \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n *\n * @param u argument\n * @return log of the inverse logit of argument\n */\ninline double log_inv_logit(double u) {\n  using std::exp;\n  if (u < 0.0)\n    return u - log1p(exp(u));  // prevent underflow\n  return -log1p(exp(-u));\n}\n\n/**\n * Returns the natural logarithm of the inverse logit of the\n * specified argument.\n *\n * @param u argument\n * @return log of the inverse logit of argument\n */\ninline double log_inv_logit(int u) {\n  return log_inv_logit(static_cast<double>(u));\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "e8fe5dff4665c9427fd9393718662238850379eb", "size": 1294, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/log_inv_logit.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/scal/fun/log_inv_logit.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/scal/fun/log_inv_logit.hpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.962962963, "max_line_length": 79, "alphanum_fraction": 0.6561051005, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940925, "lm_q2_score": 0.69925440852404, "lm_q1q2_score": 0.615901248543142}}
{"text": "// OpenTissue, A toolbox for physical based simulation and animation.\r\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\r\n//\r\n#include <OpenTissue/configuration.h>\r\n#include <OpenTissue/core/spline/spline.h>\r\n\r\n#define BOOST_AUTO_TEST_MAIN\r\n#include <boost/test/auto_unit_test.hpp>\r\n\r\n// Boost Test declaration and Checking macros\r\n#include <boost/test/unit_test_suite.hpp>\r\n#include <boost/test/test_tools.hpp>\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\ntypedef std::vector<double>                                                           knot_container;\r\n\r\nBOOST_AUTO_TEST_SUITE(opentissue_spline_compute_basis);  \r\n\r\nBOOST_AUTO_TEST_CASE(test_compute_basis)\r\n{\r\n  knot_container U;\r\n\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);\r\n  U.push_back(0.0);  //k = 3\r\n  U.push_back(0.2);\r\n  U.push_back(0.4);\r\n  U.push_back(0.6);\r\n  U.push_back(0.8);  // n = 6  => |P| = 7\r\n  U.push_back(1.0);\r\n  U.push_back(1.0);\r\n  U.push_back(1.0);  // m = 9  => |U| = 10\r\n\r\n  // Indices of basis functions belongs to the interval [0..n]\r\n\r\n  double const tolerance = 0.00001;\r\n\r\n  // Verify that zero other basis functions result in an error\r\n  {\r\n    BOOST_CHECK_THROW( OpenTissue::spline::detail::compute_basis(2, 0, 0.5, U), std::invalid_argument );\r\n  }\r\n\r\n  // Impossible basis function index\r\n  {\r\n    BOOST_CHECK_THROW( OpenTissue::spline::detail::compute_basis(7, 3, 0.5, U), std::invalid_argument );\r\n    BOOST_CHECK_THROW( OpenTissue::spline::detail::compute_basis(-1, 3, 0.5, U), std::invalid_argument );\r\n  }\r\n\r\n\r\n  // Verify that first order basis functions work as intended\r\n  {\r\n    double k1_1 = OpenTissue::spline::detail::compute_basis(0, 1,-0.5, U);\r\n    double k1_2 = OpenTissue::spline::detail::compute_basis(0, 1, 0.0, U);\r\n    double k1_3 = OpenTissue::spline::detail::compute_basis(2, 1,-0.5, U);\r\n    double k1_4 = OpenTissue::spline::detail::compute_basis(2, 1, 0.0, U);\r\n    double k1_5 = OpenTissue::spline::detail::compute_basis(2, 1, 0.1, U);\r\n    double k1_6 = OpenTissue::spline::detail::compute_basis(2, 1, 0.2, U);\r\n    double k1_7 = OpenTissue::spline::detail::compute_basis(2, 1, 0.3, U);\r\n    double k1_8 = OpenTissue::spline::detail::compute_basis(6, 1, 1.0, U); // special case for when hitting maximum U value in last basis interval\r\n    double k1_9 = OpenTissue::spline::detail::compute_basis(6, 1, 1.1, U); \r\n\r\n    BOOST_CHECK_CLOSE(k1_1, 0.0, tolerance);\r\n    BOOST_CHECK_CLOSE(k1_2, 0.0, tolerance);\r\n    BOOST_CHECK_CLOSE(k1_3, 0.0, tolerance);\r\n    BOOST_CHECK_CLOSE(k1_4, 1.0, tolerance);\r\n    BOOST_CHECK_CLOSE(k1_5, 1.0, tolerance);\r\n    BOOST_CHECK_CLOSE(k1_6, 0.0, tolerance);\r\n    BOOST_CHECK_CLOSE(k1_7, 0.0, tolerance);\r\n    BOOST_CHECK_CLOSE(k1_8, 1.0, tolerance);\r\n    BOOST_CHECK_CLOSE(k1_9, 0.0, tolerance);\r\n  }\r\n\r\n  // Verify higher order basis functions\r\n  {\r\n    double k3_1 = OpenTissue::spline::detail::compute_basis(2, 3, 0.5, U);\r\n    double k3_2 = OpenTissue::spline::detail::compute_basis(3, 3, 0.5, U);\r\n    double k3_3 = OpenTissue::spline::detail::compute_basis(4, 3, 0.5, U);\r\n\r\n    BOOST_CHECK_CLOSE(k3_1, 1.0/8.0, tolerance);\r\n    BOOST_CHECK_CLOSE(k3_2, 6.0/8.0, tolerance);\r\n    BOOST_CHECK_CLOSE(k3_3, 1.0/8.0, tolerance);\r\n  }\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END();\r\n", "meta": {"hexsha": "995e431098ea567494c5233ab1fe9092f0287176", "size": 3264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/spline/compute_basis/src/unit_compute_basis.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/spline/compute_basis/src/unit_compute_basis.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/spline/compute_basis/src/unit_compute_basis.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 37.9534883721, "max_line_length": 147, "alphanum_fraction": 0.6694240196, "num_tokens": 1046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6158913598304062}}
{"text": "/* \n// Copyright 2018 University of Liege\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n//     http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Authors:\n// - Adrien Crovato\n*/\n\n//// Ray casting and Point In Polygon test\n// Check that a given vector does not cross a given (body or wake) panel\n//\n// References:\n// http://geomalgorithms.com/a05-_intersect-1.html\n// http://demonstrations.wolfram.com/AnEfficientTestForAPointToBeInAConvexPolygon/\n// https://stackoverflow.com/questions/5188561/signed-angle-between-two-3d-vectors-with-same-origin-within-the-same-plane\n//\n// Inputs:\n// - u0, u1, u2: vector joining center of reference cell to center of adjacent cell\n// - w0, w1, w2: vector joining panel center to cell center\n// - f0, f1, f2: center of reference cell coordinates\n// - n0, n1, n2: panel unit normal\n// - v00, v01, v02: panel vertex 1 coordinates\n// - v10, v11, v12: panel vertex 2 coordinates\n// - v20, v21, v22: panel vertex 3 coordinates\n// - v30, v31, v32: panel vertex 4 coordinates\n//\n// Output:\n// - 0 (vector crosses the panel) OR 1 (vector does not cross the panel)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"cast_ray_pip.h\"\n\n#define TOL 1e-6\n\nusing namespace std;\nusing namespace Eigen;\n\nint cast_ray_pip(double u0, double u1, double u2, double w0, double w1, double w2,\n                 double f0, double f1, double f2, double n0, double n1, double n2,\n                 double v00, double v01, double v02, double v10, double v11, double v12,\n                 double v20, double v21, double v22, double v30, double v31, double v32) {\n\n    double D, N, sI;\n    Vector3d a, b, u, w, f, n, i, v0, v1, v2, v3;\n    u << u0, u1, u2; // vector joining center of reference cell to center of adjacent cell\n    w << w0, w1, w2; // vector joining panel center to cell center\n    f << f0, f1, f2; // center of reference cell coordinates\n    n << n0, n1, n2; // panel unit normal\n    v0 << v00, v01, v02; // panel vertex 1 coordinates\n    v1 << v10, v11, v12; // panel vertex 2 coordinates\n    v2 << v20, v21, v22; // panel vertex 3 coordinates\n    v3 << v30, v31, v32; // panel vertex 4 coordinates\n\n    //// Ray casting\n\n    D = n.dot(u);\n    N = -n.dot(w);\n\n    // A. Check if the vector is not parallel to the panel plane\n    if (abs(D) < TOL) {\n        return 1; // Vector is parallel to, or contained in, the panel plane\n    }\n\n    // B. Check if the vector is crossing the panel plane\n    sI = N/D; // parameter for intersection\n    if (sI < 0 || sI > 1) {\n        return 1; // Vector does not reach the panel plane\n    }\n    // C. Compute the intersection of the vector and the plane\n    else {\n        i = f + sI * u; // Compute intersection\n    }\n\n    //// Point in polygon\n\n    // D. Check that, for each pair of consecutive adjacent vertices, the angle between the lines joining the\n    // intersection the vertices is between 0 and PI, measured counterclockwise\n\n    // Vectors from intersection to vertices 1-4\n    a = v0 - i;\n    b = v3 - i;\n    // If (a X b) vector has not the same orientation as panel normal, then angle is between PI and 2PI\n    if ((a.cross(b)).dot(n) < -TOL)\n        return 1;\n    // Vectors from intersection to vertices 4-3\n    a = v3 - i;\n    b = v2 - i;\n    if ((a.cross(b)).dot(n) < -TOL)\n        return 1;\n    // Vectors from intersection to vertices 3-2\n    a = v2 - i;\n    b = v1 - i;\n    if ((a.cross(b)).dot(n) < -TOL)\n        return 1;\n    // Vectors from intersection to vertices 2-1\n    a = v1 - i;\n    b = v0 - i;\n    if ((a.cross(b)).dot(n) < -TOL)\n        return 1;\n\n    // If program ran till there, then derivative intersects the panel and must be prevented!\n    return 0;\n}", "meta": {"hexsha": "e510807567145660d407b02807987066e2ae4e2c", "size": 4117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cast_ray_pip.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/cast_ray_pip.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cast_ray_pip.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8, "max_line_length": 121, "alphanum_fraction": 0.648287588, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.615773600139341}}
{"text": "#include \"wave_filter.h\"\n\n// Standard libraries\n#include <cmath>\n#include <cstdlib>\n#include <iostream>\n#include <ctime>\n\n// Linear algebra math\n#include <Eigen/Dense>\n\nunsigned long long rdtsc(){\n  unsigned int lo,hi;\n  __asm__ __volatile__ (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n  return ((unsigned long long)hi << 32) | lo;\n}\n\nWaveFilter::WaveFilter() : initialized_(false),\n                           dT_(0.0) {};\n\nWaveFilter::WaveFilter(double sigma, double omega0, double lambda, double gain, double dT)\n{\n  this->initialize(sigma, omega0, lambda, gain, dT);\n}\n\nWaveFilter::~WaveFilter()\n{\n}\n\nvoid WaveFilter::initialize(double sigma, double omega0, double lambda, double gain, double dT)\n{\n  if (initialized_)\n    return;\n\n  A_ << 0, 1, -omega0*omega0, -2*lambda*omega0;\n  B_ << 0, 2*lambda*omega0*sigma;\n  x_ << 0,0;\n  gain_ = gain;\n  dT_ = dT;\n\n  srand48_r(rdtsc(), &randBuffer);\n\n  initialized_ = true;\n}\n\n\ndouble WaveFilter::updateFilter()\n{\n  if (!initialized_)\n    return 0.0;\n\n  x_ += (A_*x_ + B_*get_white_noise(&randBuffer))*dT_;\n\n  return gain_*x_[1];\n}\n\n\ndouble get_white_noise(struct drand48_data *buf)\n{\n  double result;\n  drand48_r(buf, &result);\n  return 2*(result - 0.5);\n}\n\n", "meta": {"hexsha": "39eb006b138fbaa80370eedc34c35de614206d9d", "size": 1193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/wave_filter.cpp", "max_stars_repo_name": "Lovestarni/asv_simulator", "max_stars_repo_head_hexsha": "824c832f071c51212367569a07f67e2dadfc1401", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T14:46:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T03:18:04.000Z", "max_issues_repo_path": "src/wave_filter.cpp", "max_issues_repo_name": "Lovestarni/asv_simulator", "max_issues_repo_head_hexsha": "824c832f071c51212367569a07f67e2dadfc1401", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-18T10:16:04.000Z", "max_issues_repo_issues_event_max_datetime": "2015-03-23T12:00:00.000Z", "max_forks_repo_path": "src/wave_filter.cpp", "max_forks_repo_name": "Lovestarni/asv_simulator", "max_forks_repo_head_hexsha": "824c832f071c51212367569a07f67e2dadfc1401", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-14T03:17:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T03:17:57.000Z", "avg_line_length": 18.3538461538, "max_line_length": 95, "alphanum_fraction": 0.6546521375, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6157735906211615}}
{"text": "#include <iostream>\n#include <fstream>\n#include <stdio.h>\n#include <math.h>\n#include <omp.h>\n\n#include <random>\n#include <map>\n#include <string>\n#include <iomanip>\n\n#include <unistd.h>\n#include <string>\n#include <algorithm>\n#include <random>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <boost/random.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/math/distributions/inverse_chi_squared.hpp>\n#include <boost/program_options.hpp>\n#include <iterator>\n\nusing namespace std;\nusing namespace Eigen;\nnamespace po = boost::program_options;\n\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::LLT;\nusing Eigen::Lower;\nusing Eigen::Map;\nusing Eigen::Upper;\ntypedef Map<MatrixXd> MapMatd;\n\nboost::random::mt19937 gen(time(0));\n\n//distributions\ndouble runif(double lower, double higher)\n{\n\tboost::random::uniform_real_distribution<> dist(lower, higher);\n\treturn dist(gen);\n}\n\ndouble rnorm(double mean, double sd)\n{\n\tboost::random::normal_distribution<> dist(mean, sd);\n\treturn dist(gen);\n}\n\n\ndouble rbeta(double alpha, double beta)\n{\n\n\tboost::math::beta_distribution<> dist(alpha, beta);\n\tdouble q = quantile(dist, runif(0,1));\n\n\treturn(q);\n}\n\ndouble rinvchisq(double df, double scale)\n{\n\n\tboost::math::inverse_chi_squared_distribution<> dist(df, scale);\n\tdouble q = quantile(dist, runif(0,1));\n\n\treturn(q);\n}\nint rbernoulli(double p)\n{\n\tstd::bernoulli_distribution dist(p);\n\treturn dist(gen);\n}\n\n//sampling functions\ndouble sample_mu(int N, double Sigma2_e,const VectorXd& Y,const MatrixXd& X,const VectorXd& beta)\n{\n\tdouble mean=((Y-X*beta).sum())/N;\n\tdouble sd=sqrt(Sigma2_e/N);\n\tdouble mu=rnorm(mean,sd);\n\treturn(mu);\n}\n\n//sample variance of beta\ndouble sample_sigma2_b(const VectorXd& beta,int NZ,double v0B,double s0B){\n\tdouble df=v0B+NZ;\n\tdouble scale=(beta.squaredNorm()*NZ+v0B*s0B)/(v0B+NZ);\n\t//cout<<NZ<<\"\\t\"<<beta.squaredNorm()<<\"\\t\"<<df<<\"\\t\"<<scale<<\"\\t\"<<endl;\n\tdouble psi2=rinvchisq(df, scale);\n\treturn(psi2);\n}\n\n//sample error variance of Y\ndouble sample_sigma2_e(int N,const VectorXd& epsilon,double v0E,double s0E){\n\tdouble sigma2=rinvchisq(v0E+N, (epsilon.squaredNorm()+v0E*s0E)/(v0E+N));\n\treturn(sigma2);\n}\n\n//sample mixture weight\ndouble sample_w(int M,int NZ){\n\tdouble w=rbeta(1+NZ,1+(M-NZ));\n\treturn(w);\n}\n\n\nvoid ReadFromFile(std::vector<double> &x, const std::string &file_name)\n{\n\tstd::ifstream read_file(file_name);\n\tassert(read_file.is_open());\n\n\tstd::copy(std::istream_iterator<double>(read_file), std::istream_iterator<double>(),\n\t\t\tstd::back_inserter(x));\n\n\tread_file.close();\n}\n\nint main(int argc, char *argv[])\n{\n\n\tpo::options_description desc(\"Options\");\n\tdesc.add_options()\n\t\t(\"M\", po::value<int>()->required(), \"No. of simulated markers\")\n\t\t(\"N\", po::value<int>()->required(), \"No. of simulated individuals\")\n\t\t(\"iter\", po::value<int>()->default_value(5000), \"No. of Gibbs iterations\")\n\t\t(\"pNZ\", po::value<double>()->default_value(0.5), \"Proportion nonzero\")\n\t\t(\"input\", po::value<std::string>()->default_value(\"none\"),\"Input filename\")\n\t\t(\"out\", po::value<std::string>()->default_value(\"BayesC_out\"),\"Output filename\")\n\t;\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc,argv,desc),vm);\n\tpo::notify(vm);\n\n\tint M=vm[\"M\"].as<int>();\n\tint N=vm[\"N\"].as<int>();\n\tint iter=vm[\"iter\"].as<int>();\n\tstring input=vm[\"input\"].as<string>();\n\tstring output=vm[\"out\"].as<string>();\n\n\tMatrixXd X(N,M);\n\tVectorXd Y(N);\n\n\t//beta coefficients\n\tVectorXd beta_true(M);\n\tbeta_true.setZero();\n\n\tint i,j,k,l,m=0;\n\n\t//Was an input matrix given?\n\n\tif (input!=\"none\"){ //Either read input tables for X and Y\n\t\tifstream f1(input+\".X\");\n\t\t//f1 >> m >> n;\n\t\tfor (int i = 0; i < N; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < M; j++)\n\t\t\t{\n\t\t\t\tf1 >> X(i,j);\n\t\t\t\t//cout<<X(i,j)<<endl;\n\t\t\t}\n\t\t}\n\t\tf1.close();\n\t\tcout<<\"finished reading matrix X!\"<<endl;\n\n\t\tstd::vector<double> Y_in;\n\t\tReadFromFile(Y_in, input+\".Y\");\n\t\tdouble* ptr_Y = &Y_in[0];\n\t\tEigen::Map<Eigen::VectorXd> Y1(ptr_Y, Y_in.size());\n\t\tcout<<\"finished reading vector Y!\"<<endl;\n\t\tif(Y_in.size()!=N){cout<<\"input Y vector size doesnt much the size indicated in the command line\"<<endl;return 0;}\n\t\tY=Y1;\n\t\tY_in.clear();\n\n\n\t}else //or simulate\n\t{\n\t\tdouble pNZ=vm[\"pNZ\"].as<double>();\n\t\tdouble sigmaY_true=1;\n\t\tdouble sigmab_true=1;\n\t\tint MT=pNZ*M;\n\n\t\t//Fill Genotype matrix\n\t\tfor (i=0;i<N;i++){\n\t\t\tfor (j=0;j<M;j++){\n\t\t\t\tX(i,j)=rnorm(0,1);\n\t\t\t}\n\t\t}\n\t\tfor (i=0;i<MT;i++){\n\t\t\tbeta_true[i]=rnorm(0,sigmab_true);\n\t\t}\n\n\t\t//error\n\t\tVectorXd error(N);\n\t\tfor (i=0;i<N;i++){\n\t\t\terror[i]=rnorm(0,sigmaY_true);\n\t\t}\n\n\t\t//construct phenotypes\n\t\tY=X*beta_true;\n\t\tY+=error;\n\t}\n\n\t//normalize\n\tRowVectorXd mean = X.colwise().mean();\n\tRowVectorXd sd = ((X.rowwise() - mean).array().square().colwise().sum() / (X.rows() - 1)).sqrt();\n\tX = (X.rowwise() - mean).array().rowwise() / sd.array();\n\n\n\tdouble Emu=0;\n\tVectorXd vEmu(N);\n\tvEmu.setOnes();\n\n\tVectorXd Ebeta(M);\n\tEbeta.setZero();\n\tVectorXd ny(M);\n\tny.setZero();\n\tdouble Ew=0.5;\n\t//residual error\n\tVectorXd epsilon(N);\n\n\tepsilon=Y-X*Ebeta-vEmu*Emu;\n\n\tstd::vector<int> markerI;\n\tfor (int i=0; i<M; ++i) {\n\t\tmarkerI.push_back(i);\n\t}\n\tint marker=0;\n\n\t//non-zero variable NZ\n\tint NZ=0;\n\n\tdouble Sigma2_e=epsilon.squaredNorm()/(N*0.5);\n\tdouble Sigma2_b=rbeta(1,1);\n\n\t//Standard parameterization of hyperpriors for variances\n\t//double v0E=0.001,s0E=0.001,v0B=0.001,s0B=0.001;\n\n\n\t// Alternative parameterization of hyperpriors for variances\n\tdouble v0E=4,v0B=4;\n\tdouble s0B=((v0B-2)/v0B)*Sigma2_b;\n\tdouble s0E=((v0E-2)/v0E)*Sigma2_e;\n\n\n\t//pre-computed elements for calculations\n\tVectorXd el1(M);\n\tfor (int i=0; i<M; ++i) {\n\t\tel1[i]=X.col(i).transpose()*X.col(i);\n\t}\n\n\tstd::ofstream ofs;\n\tofs.open(output+\"_estimates.txt\");\n\tfor (int i=0; i<M; ++i) {\n\t\tofs << \"beta_\" <<i<< ' ';\n\t}\n\tfor (int i=0; i<M; ++i) {\n\t\tofs << \"incl_\" <<i<< ' ';\n\t}\n\tofs << \"Ew\" << \" \";\n\tofs << \"Sigma2_b\" << \" \";\n\tofs << \"Sigma2_e\" << \" \";\n\tofs << \"\\n\";\n\tofs.close();\n\n\t//begin GIBBS sampling iterations\n\n\tofs.open (output+\"_estimates.txt\", std::ios_base::app);\n\tfor (i=0;i<iter;i++){\n\n\t\tEmu=sample_mu(N,Sigma2_e,Y,X,Ebeta);\n\n\t\t//sample effects and probabilities jointly\n\t\tstd::random_shuffle(markerI.begin(), markerI.end());\n\t\tfor (j=0;j<M;j++){\n\t\t\tmarker=markerI[j];\n\n\t\t\tepsilon=epsilon+X.col(marker)*Ebeta[marker];\n\n\t\t\tdouble Cj=el1[marker]+Sigma2_e/Sigma2_b; //adjusted variance\n\t\t\tdouble rj=X.col(marker).transpose()*epsilon; // mean\n\n\n\n\t\t\tdouble ratio=(((exp(-(pow(rj,2))/(2*Cj*Sigma2_e))*sqrt((Sigma2_b*Cj)/Sigma2_e))));\n\t\t\tratio=Ew/(Ew+ratio*(1-Ew));\n\t\t\tny[marker]=rbernoulli(ratio);\n\n\t\t\tif (ny[marker]==0){\n\t\t\t\tEbeta[marker]=0;\n\t\t\t}\n\t\t\telse if (ny[marker]==1){\n\t\t\t\tEbeta[marker]=rnorm(rj/Cj,Sigma2_e/Cj);\n\t\t\t}\n\n\t\t\tepsilon=epsilon-X.col(marker)*Ebeta[marker];\n\n\t\t}\n\t\tfor (j=0;j<M;j++){\n\t\t\tofs << Ebeta[j] << \" \";\n\t\t}\n\t\tfor (j=0;j<M;j++){\n\t\t\tofs << ny[j] << \" \";\n\t\t}\n\t\tNZ=ny.sum();\n\t\t//cout<<NZ<<endl;\n\n\t\tEw=sample_w(M,NZ);\n\t\tepsilon=Y-X*Ebeta-vEmu*Emu;\n\n\t\tSigma2_b=sample_sigma2_b(Ebeta,NZ,v0B,s0B);\n\t\tSigma2_e=sample_sigma2_e(N,epsilon,v0E,s0E);\n\n\t\tofs << Ew << \" \";\n\t\tofs << Sigma2_b << \" \";\n\t\tofs << Sigma2_e << \" \";\n\t\tofs << \"\\n\";\n\n\t}\n\tofs.close();\n\nif (input==\"none\"){\n\t//write to files\n\tofstream myfile1;\n\tmyfile1.open (output+\"_simulated_Y.txt\");\n\tfor (i=0;i<N;i++){\n\t\tmyfile1 << Y[i] << ' ';\n\t}\n\tmyfile1 << endl;\n\tmyfile1.close();\n\n\tofstream myfile2;\n\tmyfile2.open (output+\"_simulated_X.txt\");\n\tfor (i=0;i<N;i++){\n\t\tfor (j=0;j<M;j++){\n\t\t\tmyfile2<<X(i,j)<< ' ';\n\t\t}\n\t\tmyfile2<<endl;\n\t}\n\tmyfile2.close();\n\n\tofstream myfile3;\n\tmyfile3.open (output+\"_simulated_betatrue.txt\");\n\tmyfile3 << beta_true << ' ';\n\tmyfile3.close();\n}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "fd9780606c789ee1f931f682218b41d0c63439de", "size": 7564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "other/BayesC.cpp", "max_stars_repo_name": "jklopf/tensorbayes", "max_stars_repo_head_hexsha": "4b0cb3c565e9603a972135ddf7cfbe28a23b3a4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-12T16:58:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-12T16:58:32.000Z", "max_issues_repo_path": "other/BayesC.cpp", "max_issues_repo_name": "jklopf/tensorbayes", "max_issues_repo_head_hexsha": "4b0cb3c565e9603a972135ddf7cfbe28a23b3a4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "other/BayesC.cpp", "max_forks_repo_name": "jklopf/tensorbayes", "max_forks_repo_head_hexsha": "4b0cb3c565e9603a972135ddf7cfbe28a23b3a4a", "max_forks_repo_licenses": ["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.4886363636, "max_line_length": 116, "alphanum_fraction": 0.644235854, "num_tokens": 2436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.6157429872428852}}
{"text": "// Copyright (c) 2005-2009  INRIA Sophia-Antipolis (France).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org)\n//\n// $URL$\n// $Id$\n// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial\n//\n//\n// Author(s)     : Sebastien Loriot, Sylvain Pion\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/CGAL_Ipelet_base.h>\n#include <boost/format.hpp>\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n#include <CGAL/Delaunay_mesher_2.h>\n#include <CGAL/Delaunay_mesh_face_base_2.h>\n#include <CGAL/Delaunay_mesh_size_criteria_2.h>\n\nnamespace CGAL_mesh_2{\n  typedef CGAL::Exact_predicates_inexact_constructions_kernel       Kernel;\n  typedef CGAL::Triangulation_vertex_base_2<Kernel>                 Vb;\n  typedef CGAL::Delaunay_mesh_face_base_2<Kernel>                   Fb;\n  typedef CGAL::Triangulation_data_structure_2<Vb, Fb>              Tds;\n  typedef CGAL::Exact_predicates_tag                                     Itag;\n  typedef CGAL::Constrained_Delaunay_triangulation_2<Kernel,Tds,Itag>    CDT;\n  typedef CGAL::Delaunay_mesh_size_criteria_2<CDT>                  Criteria;\n  typedef CGAL::Delaunay_mesher_2<CDT, Criteria>                    Mesher;\n\nconst std::string sublabel[] ={\n  \"Mesh_2\", \"Help\"\n};\n\nconst std::string helpmsg[] = {\n  \"Mesh a polygon using CGAL::Mesh_2; Use circle centers for seeds\"\n};\n\nstruct IpeletMesh2\n  : CGAL::Ipelet_base<Kernel,2>\n{\n  IpeletMesh2()\n    : CGAL::Ipelet_base<Kernel,2>(\"Mesh_2\",sublabel, helpmsg) {}\n\n  void protected_run(int);\n};\n\n\nvoid IpeletMesh2::protected_run(int fn)\n{\n  if (fn==1) {\n    show_help();\n    return;\n  }\n\n  std::list<Point_2> list_of_seeds;\n\n  std::list<Point_2> pt_list;\n  std::list<Segment_2> sg_list;\n  std::list<Circle_2> cir_list;\n  std::list<Polygon_2> pol_list;\n\n  Iso_rectangle_2 bbox=\n    read_active_objects(\n      CGAL::dispatch_or_drop_output<Point_2,Polygon_2,Circle_2,Segment_2>(\n        std::back_inserter(pt_list),\n        std::back_inserter(pol_list),\n        std::back_inserter(cir_list),\n        std::back_inserter(sg_list)\n      )\n    );\n\n  if (pt_list.empty() && sg_list.empty() && pol_list.empty()) {\n    print_error_message(\"No mark selected\");\n    return;\n  }\n\n  CDT cdt;\n\n  for (std::list<Point_2>::iterator it=pt_list.begin();it!=pt_list.end();++it)\n    cdt.insert(*it);\n  for (std::list<Segment_2>::iterator it=sg_list.begin();it!=sg_list.end();++it)\n    cdt.insert_constraint(it->point(0),it->point(1));\n  for (std::list<Polygon_2>::iterator it=pol_list.begin();it!=pol_list.end();++it)\n    for(Polygon_2::Edge_const_iterator edge_it=it->edges_begin();edge_it!=it->edges_end();++edge_it)\n      cdt.insert_constraint(edge_it->point(0),edge_it->point(1));\n  for (std::list<Circle_2>::iterator it=cir_list.begin();it!=cir_list.end();++it)\n    list_of_seeds.push_back(it->center());\n\n\n  double alpha=0;\n\n  int x=static_cast<int>( floor((bbox.max)().x()-(bbox.min)().x()) );\n  int y=static_cast<int>( floor((bbox.max)().y()-(bbox.min)().y()) );\n\n  int ret_val;\n  boost::tie(ret_val,alpha)=request_value_from_user<double>((boost::format(\"Max edge length (BBox %1%x%2%)\") % x % y).str() );\n  if (ret_val == -1) return;\n\n  if(alpha<0){\n    print_error_message(\"Not a good value\");\n    return;\n  }\n\n  if (list_of_seeds.empty()){\n    Mesher mesher(cdt);\n    mesher.set_criteria(Criteria(0.125, alpha));\n    mesher.refine_mesh();\n  }\n  else\n    CGAL::refine_Delaunay_mesh_2(cdt,list_of_seeds.begin(), list_of_seeds.end(),\n      Criteria(0.125, alpha));\n\n\n  for (CDT::Finite_edges_iterator it=cdt.finite_edges_begin(); it!=cdt.finite_edges_end();++it)\n    if (it->first->is_in_domain() || it->first->neighbor(it->second)->is_in_domain())\n      draw_in_ipe(cdt.segment(*it));\n\n  group_selected_objects_();\n}\n\n}\n\nCGAL_IPELET(CGAL_mesh_2::IpeletMesh2)\n", "meta": {"hexsha": "a450cac2c7eb88fb4ca3e49c2f0d732a5b3c8f58", "size": 3796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/mesh_2.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/mesh_2.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "CGAL_ipelets/demo/CGAL_ipelets/mesh_2.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 30.368, "max_line_length": 126, "alphanum_fraction": 0.677028451, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.6157429796630772}}
{"text": "\n///////////////////////////////////////////////////////////////////////////////\n// Copyright Christopher Kormanyos 2013 - 2014.\n// Copyright John Maddock 2013.\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// This work is based on an earlier work:\n// \"Algorithm 910: A Portable C++ Multiple-Precision System for Special-Function Calculations\",\n// in ACM TOMS, {VOL 37, ISSUE 4, (February 2011)} (C) ACM, 2011. http://doi.acm.org/10.1145/1916461.1916469\n//\n\n#include <algorithm>\n#include <cstdint>\n#include <deque>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <vector>\n#include <boost/math/constants/constants.hpp>\n#include <boost/noncopyable.hpp>\n\n//#define USE_CPP_BIN_FLOAT\n#define USE_CPP_DEC_FLOAT\n//#define USE_MPFR\n\n#if !defined(DIGIT_COUNT)\n#define DIGIT_COUNT 100\n#endif\n\n#if !defined(BOOST_NO_CXX11_HDR_CHRONO)\n  #include <chrono>\n  #define STD_CHRONO std::chrono\n#else\n  #include <boost/chrono.hpp>\n  #define STD_CHRONO boost::chrono\n#endif\n\n#if defined(USE_CPP_BIN_FLOAT)\n  #include <boost/multiprecision/cpp_bin_float.hpp>\n  typedef boost::multiprecision::number<boost::multiprecision::cpp_bin_float<DIGIT_COUNT + 10> > mp_type;\n#elif defined(USE_CPP_DEC_FLOAT)\n  #include <boost/multiprecision/cpp_dec_float.hpp>\n  typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<DIGIT_COUNT + 10> > mp_type;\n#elif defined(USE_MPFR)\n  #include <boost/multiprecision/mpfr.hpp>\n  typedef boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<DIGIT_COUNT + 10> > mp_type;\n#else\n  #error no multiprecision floating type is defined\n#endif\n\ntemplate <class clock_type>\nstruct stopwatch\n{\npublic:\n  typedef typename clock_type::duration duration_type;\n\n  stopwatch() : m_start(clock_type::now()) { }\n\n  stopwatch(const stopwatch& other) : m_start(other.m_start) { }\n\n  stopwatch& operator=(const stopwatch& other)\n  {\n    m_start = other.m_start;\n    return *this;\n  }\n\n  ~stopwatch() { }\n\n  duration_type elapsed() const\n  {\n    return (clock_type::now() - m_start);\n  }\n\n  void reset()\n  {\n    m_start = clock_type::now();\n  }\n\nprivate:\n  typename clock_type::time_point m_start;\n};\n\nnamespace my_math\n{\n  template<class T> T chebyshev_t(const std::int32_t n, const T& x);\n\n  template<class T> T chebyshev_t(const std::uint32_t n, const T& x, std::vector<T>* vp);\n\n  template<class T> bool isneg(const T& x) { return (x < T(0)); }\n\n  template<class T> const T& zero() { static const T value_zero(0); return value_zero; }\n  template<class T> const T& one () { static const T value_one (1); return value_one; }\n  template<class T> const T& two () { static const T value_two (2); return value_two; }\n}\n\nnamespace orthogonal_polynomial_series\n{\n  template<typename T> static inline T orthogonal_polynomial_template(const T& x, const std::uint32_t n, std::vector<T>* const vp = static_cast<std::vector<T>*>(0u))\n  {\n    // Compute the value of an orthogonal chebyshev polinomial.\n    // Use stable upward recursion.\n\n    if(vp != nullptr)\n    {\n      vp->clear();\n      vp->reserve(static_cast<std::size_t>(n + 1u));\n    }\n\n    T y0 = my_math::one<T>();\n\n    if(vp != nullptr) { vp->push_back(y0); }\n\n    if(n == static_cast<std::uint32_t>(0u))\n    {\n      return y0;\n    }\n\n    T y1 = x;\n\n    if(vp != nullptr) { vp->push_back(y1); }\n\n    if(n == static_cast<std::uint32_t>(1u))\n    {\n      return y1;\n    }\n\n    T a = my_math::two <T>();\n    T b = my_math::zero<T>();\n    T c = my_math::one <T>();\n\n    T yk;\n\n    // Calculate higher orders using the recurrence relation.\n    // The direction of stability is upward recursion.\n    for(std::int32_t k = static_cast<std::int32_t>(2); k <= static_cast<std::int32_t>(n); ++k)\n    {\n      yk = (((a * x) + b) * y1) - (c * y0);\n\n      y0 = y1;\n      y1 = yk;\n\n      if(vp != nullptr) { vp->push_back(yk); }\n    }\n\n    return yk;\n  }\n}\n\ntemplate<class T> T my_math::chebyshev_t(const std::int32_t n, const T& x)\n{\n  if(my_math::isneg(x))\n  {\n    const bool b_negate = ((n % static_cast<std::int32_t>(2)) != static_cast<std::int32_t>(0));\n\n    const T y = chebyshev_t(n, -x);\n\n    return (!b_negate ? y : -y);\n  }\n\n  if(n < static_cast<std::int32_t>(0))\n  {\n    const std::int32_t nn = static_cast<std::int32_t>(-n);\n\n    return chebyshev_t(nn, x);\n  }\n  else\n  {\n    return orthogonal_polynomial_series::orthogonal_polynomial_template(x, static_cast<std::uint32_t>(n));\n  }\n}\n\ntemplate<class T> T my_math::chebyshev_t(const std::uint32_t n, const T& x, std::vector<T>* const vp) { return orthogonal_polynomial_series::orthogonal_polynomial_template(x, static_cast<std::int32_t>(n),  vp); }\n\nnamespace util\n{\n  template <class T> float digit_scale()\n  {\n    const int d = ((std::max)(std::numeric_limits<T>::digits10, 15));\n    return static_cast<float>(d) / 300.0F;\n  }\n}\n\nnamespace examples\n{\n  namespace nr_006\n  {\n    template<typename T> class hypergeometric_pfq_base : private boost::noncopyable\n    {\n    public:\n      virtual ~hypergeometric_pfq_base() { }\n\n      virtual void ccoef() const = 0;\n\n      virtual T series() const\n      {\n        using my_math::chebyshev_t;\n\n        // Compute the Chebyshev coefficients.\n        // Get the values of the shifted Chebyshev polynomials.\n        std::vector<T> chebyshev_t_shifted_values;\n        const T z_shifted = ((Z / W) * static_cast<std::int32_t>(2)) - static_cast<std::int32_t>(1);\n\n        chebyshev_t(static_cast<std::uint32_t>(C.size()),\n                    z_shifted,\n                    &chebyshev_t_shifted_values);\n\n        // Luke: C     ---------- COMPUTE SCALE FACTOR                       ----------\n        // Luke: C\n        // Luke: C     ---------- SCALE THE COEFFICIENTS                     ----------\n        // Luke: C\n\n        // The coefficient scaling is preformed after the Chebyshev summation,\n        // and it is carried out with a single division operation.\n        bool b_neg = false;\n\n        const T scale = std::accumulate(C.begin(),\n                                        C.end(),\n                                        T(0),\n                                        [&b_neg](T scale_sum, const T& ck) -> T\n                                        {\n                                          ((!b_neg) ? (scale_sum += ck) : (scale_sum -= ck));\n                                          b_neg = (!b_neg);\n                                          return scale_sum;\n                                        });\n\n        // Compute the result of the series expansion using unscaled coefficients.\n        const T sum = std::inner_product(C.begin(),\n                                         C.end(),\n                                         chebyshev_t_shifted_values.begin(),\n                                         T(0));\n\n        // Return the properly scaled result.\n        return sum / scale;\n      }\n\n    protected:\n      const   T             Z;\n      const   T             W;\n      mutable std::deque<T> C;\n\n      hypergeometric_pfq_base(const T& z,\n                              const T& w) : Z(z),\n                                            W(w),\n                                            C(0u) { }\n\n      virtual std::int32_t N() const { return static_cast<std::int32_t>(util::digit_scale<T>() * 500.0F); }\n    };\n\n    template<typename T> class ccoef4_hypergeometric_0f1 : public hypergeometric_pfq_base<T>\n    {\n    public:\n      ccoef4_hypergeometric_0f1(const T& c,\n                                const T& z,\n                                const T& w) : hypergeometric_pfq_base<T>(z, w),\n                                              CP(c) { }\n\n      virtual ~ccoef4_hypergeometric_0f1() { }\n\n      virtual void ccoef() const\n      {\n        // See Luke 1977 page 80.\n        const std::int32_t N1 = static_cast<std::int32_t>(this->N() + static_cast<std::int32_t>(1));\n        const std::int32_t N2 = static_cast<std::int32_t>(this->N() + static_cast<std::int32_t>(2));\n\n        // Luke: C     ---------- START COMPUTING COEFFICIENTS USING         ----------\n        // Luke: C     ---------- BACKWARD RECURRENCE SCHEME                 ----------\n        // Luke: C\n        T A3(0);\n        T A2(0);\n        T A1(boost::math::tools::root_epsilon<T>());\n\n        hypergeometric_pfq_base<T>::C.resize(1u, A1);\n\n        std::int32_t X1 = N2;\n\n        T C1 = T(1) - CP;\n\n        const T Z1 = T(4) / hypergeometric_pfq_base<T>::W;\n\n        for(std::int32_t k = static_cast<std::int32_t>(0); k < N1; ++k)\n        {\n          const T DIVFAC = T(1) / X1;\n\n          --X1;\n\n          // The terms have been slightly re-arranged resulting in lower complexity.\n          // Parentheses have been added to avoid reliance on operator precedence.\n          const T term =   (A2 - ((A3 * DIVFAC) * X1))\n                         + ((A2 * X1) * ((1 + (C1 + X1)) * Z1))\n                         + ((A1 * X1) * ((DIVFAC - (C1 * Z1)) + (X1 * Z1)));\n\n          hypergeometric_pfq_base<T>::C.push_front(term);\n\n          A3 = A2;\n          A2 = A1;\n          A1 = hypergeometric_pfq_base<T>::C.front();\n        }\n\n        hypergeometric_pfq_base<T>::C.front() /= static_cast<std::int32_t>(2);\n      }\n\n    private:\n      const T CP;\n    };\n\n    template<typename T> class ccoef1_hypergeometric_1f0 : public hypergeometric_pfq_base<T>\n    {\n    public:\n      ccoef1_hypergeometric_1f0(const T& a,\n                                const T& z,\n                                const T& w) : hypergeometric_pfq_base<T>(z, w),\n                                              AP(a) { }\n\n      virtual ~ccoef1_hypergeometric_1f0() { }\n\n      virtual void ccoef() const\n      {\n        // See Luke 1977 page 67.\n        const std::int32_t N1 = static_cast<std::int32_t>(N() + static_cast<std::int32_t>(1));\n        const std::int32_t N2 = static_cast<std::int32_t>(N() + static_cast<std::int32_t>(2));\n\n        // Luke: C     ---------- START COMPUTING COEFFICIENTS USING         ----------\n        // Luke: C     ---------- BACKWARD RECURRENCE SCHEME                 ----------\n        // Luke: C\n        T A2(0);\n        T A1(boost::math::tools::root_epsilon<T>());\n\n        hypergeometric_pfq_base<T>::C.resize(1u, A1);\n\n        std::int32_t X1 = N2;\n\n        T V1 = T(1) - AP;\n\n        // Here, we have corrected what appears to be an error in Luke's code.\n\n        // Luke's original code listing has:\n        //  AFAC = 2 + FOUR/W\n        // But it appears as though the correct form is:\n        //  AFAC = 2 - FOUR/W.\n\n        const T AFAC = 2 - (T(4) / hypergeometric_pfq_base<T>::W);\n\n        for(std::int32_t k = static_cast<std::int32_t>(0); k < N1; ++k)\n        {\n          --X1;\n\n          // The terms have been slightly re-arranged resulting in lower complexity.\n          // Parentheses have been added to avoid reliance on operator precedence.\n          const T term = -(((X1 * AFAC) * A1) + ((X1 + V1) * A2)) / (X1 - V1);\n\n          hypergeometric_pfq_base<T>::C.push_front(term);\n\n          A2 = A1;\n          A1 = hypergeometric_pfq_base<T>::C.front();\n        }\n\n        hypergeometric_pfq_base<T>::C.front() /= static_cast<std::int32_t>(2);\n      }\n\n    private:\n      const T AP;\n\n      virtual std::int32_t N() const { return static_cast<std::int32_t>(util::digit_scale<T>() * 1600.0F); }\n    };\n\n    template<typename T> class ccoef3_hypergeometric_1f1 : public hypergeometric_pfq_base<T>\n    {\n    public:\n      ccoef3_hypergeometric_1f1(const T& a,\n                                const T& c,\n                                const T& z,\n                                const T& w) : hypergeometric_pfq_base<T>(z, w),\n                                              AP(a),\n                                              CP(c) { }\n\n      virtual ~ccoef3_hypergeometric_1f1() { }\n\n      virtual void ccoef() const\n      {\n        // See Luke 1977 page 74.\n        const std::int32_t N1 = static_cast<std::int32_t>(this->N() + static_cast<std::int32_t>(1));\n        const std::int32_t N2 = static_cast<std::int32_t>(this->N() + static_cast<std::int32_t>(2));\n\n        // Luke: C     ---------- START COMPUTING COEFFICIENTS USING         ----------\n        // Luke: C     ---------- BACKWARD RECURRENCE SCHEME                 ----------\n        // Luke: C\n        T A3(0);\n        T A2(0);\n        T A1(boost::math::tools::root_epsilon<T>());\n\n        hypergeometric_pfq_base<T>::C.resize(1u, A1);\n\n        std::int32_t X  = N1;\n        std::int32_t X1 = N2;\n\n        T XA  =  X + AP;\n        T X3A = (X + 3) - AP;\n\n        const T Z1 = T(4) / hypergeometric_pfq_base<T>::W;\n\n        for(std::int32_t k = static_cast<std::int32_t>(0); k < N1; ++k)\n        {\n          --X;\n          --X1;\n          --XA;\n          --X3A;\n\n          const T X3A_over_X2 = X3A / static_cast<std::int32_t>(X + 2);\n\n          // The terms have been slightly re-arranged resulting in lower complexity.\n          // Parentheses have been added to avoid reliance on operator precedence.\n          const T PART1 =  A1 * (((X + CP) * Z1) - X3A_over_X2);\n          const T PART2 =  A2 * (Z1 * ((X + 3) - CP) + (XA / X1));\n          const T PART3 =  A3 * X3A_over_X2;\n\n          const T term = (((PART1 + PART2) + PART3) * X1) / XA;\n\n          hypergeometric_pfq_base<T>::C.push_front(term);\n\n          A3 = A2;\n          A2 = A1;\n          A1 = hypergeometric_pfq_base<T>::C.front();\n        }\n\n        hypergeometric_pfq_base<T>::C.front() /= static_cast<std::int32_t>(2);\n      }\n\n    private:\n      const T AP;\n      const T CP;\n    };\n\n    template<typename T> class ccoef6_hypergeometric_1f2 : public hypergeometric_pfq_base<T>\n    {\n    public:\n      ccoef6_hypergeometric_1f2(const T& a,\n                                const T& b,\n                                const T& c,\n                                const T& z,\n                                const T& w) : hypergeometric_pfq_base<T>(z, w),\n                                              AP(a),\n                                              BP(b),\n                                              CP(c) { }\n\n      virtual ~ccoef6_hypergeometric_1f2() { }\n\n      virtual void ccoef() const\n      {\n        // See Luke 1977 page 85.\n        const std::int32_t N1 = static_cast<std::int32_t>(this->N() + static_cast<std::int32_t>(1));\n\n        // Luke: C     ---------- START COMPUTING COEFFICIENTS USING         ----------\n        // Luke: C     ---------- BACKWARD RECURRENCE SCHEME                 ----------\n        // Luke: C\n        T A4(0);\n        T A3(0);\n        T A2(0);\n        T A1(boost::math::tools::root_epsilon<T>());\n\n        hypergeometric_pfq_base<T>::C.resize(1u, A1);\n\n        std::int32_t X  = N1;\n        T            PP = X + AP;\n\n        const T Z1 = T(4) / hypergeometric_pfq_base<T>::W;\n\n        for(std::int32_t k = static_cast<std::int32_t>(0); k < N1; ++k)\n        {\n          --X;\n          --PP;\n\n          const std::int32_t TWO_X    = static_cast<std::int32_t>(X * 2);\n          const std::int32_t X_PLUS_1 = static_cast<std::int32_t>(X + 1);\n          const std::int32_t X_PLUS_3 = static_cast<std::int32_t>(X + 3);\n          const std::int32_t X_PLUS_4 = static_cast<std::int32_t>(X + 4);\n\n          const T QQ = T(TWO_X + 3) / static_cast<std::int32_t>(TWO_X + static_cast<std::int32_t>(5));\n          const T SS = (X + BP) * (X + CP);\n\n          // The terms have been slightly re-arranged resulting in lower complexity.\n          // Parentheses have been added to avoid reliance on operator precedence.\n          const T PART1 =   A1 * (((PP - (QQ * (PP + 1))) * 2) + (SS * Z1));\n          const T PART2 =  (A2 * (X + 2)) * ((((TWO_X + 1) * PP) / X_PLUS_1) - ((QQ * 4) * (PP + 1)) + (((TWO_X + 3) * (PP + 2)) / X_PLUS_3) + ((Z1 * 2) * (SS - (QQ * (X_PLUS_1 + BP)) * (X_PLUS_1 + CP))));\n          const T PART3 =   A3 * ((((X_PLUS_3 - AP) - (QQ * (X_PLUS_4 - AP))) * 2) + (((QQ * Z1) * (X_PLUS_4 - BP)) * (X_PLUS_4 - CP)));\n          const T PART4 = ((A4 * QQ) * (X_PLUS_4 - AP)) / X_PLUS_3;\n\n          const T term = (((PART1 - PART2) + (PART3 - PART4)) * X_PLUS_1) / PP;\n\n          hypergeometric_pfq_base<T>::C.push_front(term);\n\n          A4 = A3;\n          A3 = A2;\n          A2 = A1;\n          A1 = hypergeometric_pfq_base<T>::C.front();\n        }\n\n        hypergeometric_pfq_base<T>::C.front() /= static_cast<std::int32_t>(2);\n      }\n\n    private:\n      const T AP;\n      const T BP;\n      const T CP;\n    };\n\n    template<typename T> class ccoef2_hypergeometric_2f1 : public hypergeometric_pfq_base<T>\n    {\n    public:\n      ccoef2_hypergeometric_2f1(const T& a,\n                                const T& b,\n                                const T& c,\n                                const T& z,\n                                const T& w) : hypergeometric_pfq_base<T>(z, w),\n                                              AP(a),\n                                              BP(b),\n                                              CP(c) { }\n\n      virtual ~ccoef2_hypergeometric_2f1() { }\n\n      virtual void ccoef() const\n      {\n        // See Luke 1977 page 59.\n        const std::int32_t N1 = static_cast<std::int32_t>(N() + static_cast<std::int32_t>(1));\n        const std::int32_t N2 = static_cast<std::int32_t>(N() + static_cast<std::int32_t>(2));\n\n        // Luke: C     ---------- START COMPUTING COEFFICIENTS USING         ----------\n        // Luke: C     ---------- BACKWARD RECURRENCE SCHEME                 ----------\n        // Luke: C\n        T A3(0);\n        T A2(0);\n        T A1(boost::math::tools::root_epsilon<T>());\n\n        hypergeometric_pfq_base<T>::C.resize(1u, A1);\n\n        std::int32_t X  = N1;\n        std::int32_t X1 = N2;\n        std::int32_t X3 = static_cast<std::int32_t>((X * 2) + 3);\n\n        T X3A = (X + 3) - AP;\n        T X3B = (X + 3) - BP;\n\n        const T Z1 = T(4) / hypergeometric_pfq_base<T>::W;\n\n        for(std::int32_t k = static_cast<std::int32_t>(0); k < N1; ++k)\n        {\n          --X;\n          --X1;\n          --X3A;\n          --X3B;\n          X3 -= 2;\n\n          const std::int32_t X_PLUS_2 = static_cast<std::int32_t>(X + 2);\n\n          const T XAB = T(1) / ((X + AP) * (X + BP));\n\n          // The terms have been slightly re-arranged resulting in lower complexity.\n          // Parentheses have been added to avoid reliance on operator precedence.\n          const T PART1 = (A1 * X1) * (2 - (((AP + X1) * (BP + X1)) * ((T(X3) / X_PLUS_2) * XAB)) + ((CP + X) * (XAB * Z1)));\n          const T PART2 = (A2 * XAB) * ((X3A * X3B) - (X3 * ((X3A + X3B) - 1)) + (((3 - CP) + X) * (X1 * Z1)));\n          const T PART3 = (A3 * X1) * (X3A / X_PLUS_2) * (X3B * XAB);\n\n          const T term = (PART1 + PART2) - PART3;\n\n          hypergeometric_pfq_base<T>::C.push_front(term);\n\n          A3 = A2;\n          A2 = A1;\n          A1 = hypergeometric_pfq_base<T>::C.front();\n        }\n\n        hypergeometric_pfq_base<T>::C.front() /= static_cast<std::int32_t>(2);\n      }\n\n    private:\n      const T AP;\n      const T BP;\n      const T CP;\n\n      virtual std::int32_t N() const { return static_cast<std::int32_t>(util::digit_scale<T>() * 1600.0F); }\n    };\n\n    template<class T> T luke_ccoef4_hypergeometric_0f1(const T& a, const T& x);\n    template<class T> T luke_ccoef1_hypergeometric_1f0(const T& a, const T& x);\n    template<class T> T luke_ccoef3_hypergeometric_1f1(const T& a, const T& b, const T& x);\n    template<class T> T luke_ccoef6_hypergeometric_1f2(const T& a, const T& b, const T& c, const T& x);\n    template<class T> T luke_ccoef2_hypergeometric_2f1(const T& a, const T& b, const T& c, const T& x);\n  }\n}\n\ntemplate<class T>\nT examples::nr_006::luke_ccoef4_hypergeometric_0f1(const T& a, const T& x)\n{\n  const ccoef4_hypergeometric_0f1<T> hypergeometric_0f1_object(a, x, T(-20));\n\n  hypergeometric_0f1_object.ccoef();\n\n  return hypergeometric_0f1_object.series();\n}\n\ntemplate<class T>\nT examples::nr_006::luke_ccoef1_hypergeometric_1f0(const T& a, const T& x)\n{\n  const ccoef1_hypergeometric_1f0<T> hypergeometric_1f0_object(a, x, T(-20));\n\n  hypergeometric_1f0_object.ccoef();\n\n  return hypergeometric_1f0_object.series();\n}\n\ntemplate<class T>\nT examples::nr_006::luke_ccoef3_hypergeometric_1f1(const T& a, const T& b, const T& x)\n{\n  const ccoef3_hypergeometric_1f1<T> hypergeometric_1f1_object(a, b, x, T(-20));\n\n  hypergeometric_1f1_object.ccoef();\n\n  return hypergeometric_1f1_object.series();\n}\n\ntemplate<class T>\nT examples::nr_006::luke_ccoef6_hypergeometric_1f2(const T& a, const T& b, const T& c, const T& x)\n{\n  const ccoef6_hypergeometric_1f2<T> hypergeometric_1f2_object(a, b, c, x, T(-20));\n\n  hypergeometric_1f2_object.ccoef();\n\n  return hypergeometric_1f2_object.series();\n}\n\ntemplate<class T>\nT examples::nr_006::luke_ccoef2_hypergeometric_2f1(const T& a, const T& b, const T& c, const T& x)\n{\n  const ccoef2_hypergeometric_2f1<T> hypergeometric_2f1_object(a, b, c, x, T(-20));\n\n  hypergeometric_2f1_object.ccoef();\n\n  return hypergeometric_2f1_object.series();\n}\n\nint main()\n{\n  stopwatch<STD_CHRONO::high_resolution_clock> my_stopwatch;\n  float total_time = 0.0F;\n\n  std::vector<mp_type> hypergeometric_0f1_results(20U);\n  std::vector<mp_type> hypergeometric_1f0_results(20U);\n  std::vector<mp_type> hypergeometric_1f1_results(20U);\n  std::vector<mp_type> hypergeometric_2f1_results(20U);\n  std::vector<mp_type> hypergeometric_1f2_results(20U);\n\n  const mp_type a(mp_type(3) / 7);\n  const mp_type b(mp_type(2) / 3);\n  const mp_type c(mp_type(1) / 4);\n\n  std::int_least16_t i;\n\n  std::cout << \"test hypergeometric_0f1.\" << std::endl;\n  i = 1U;\n  my_stopwatch.reset();\n\n  // Generate a table of values of Hypergeometric0F1.\n  // Compare with the Mathematica command:\n  // Table[N[HypergeometricPFQ[{}, {3/7}, -(i*EulerGamma)], 100], {i, 1, 20, 1}]\n  std::for_each(hypergeometric_0f1_results.begin(),\n                hypergeometric_0f1_results.end(),\n                [&i, &a](mp_type& new_value)\n                {\n                  const mp_type x(-(boost::math::constants::euler<mp_type>() * i));\n\n                  new_value = examples::nr_006::luke_ccoef4_hypergeometric_0f1(a, x);\n\n                  ++i;\n                });\n\n  total_time += STD_CHRONO::duration_cast<STD_CHRONO::duration<float> >(my_stopwatch.elapsed()).count();\n\n  // Print the values of Hypergeometric0F1.\n  std::for_each(hypergeometric_0f1_results.begin(),\n                hypergeometric_0f1_results.end(),\n                [](const mp_type& h)\n                {\n                  std::cout << std::setprecision(DIGIT_COUNT) << h << std::endl;\n                });\n\n  std::cout << \"test hypergeometric_1f0.\" << std::endl;\n  i = 1U;\n  my_stopwatch.reset();\n\n  // Generate a table of values of Hypergeometric1F0.\n  // Compare with the Mathematica command:\n  // Table[N[HypergeometricPFQ[{3/7}, {}, -(i*EulerGamma)], 100], {i, 1, 20, 1}]\n  std::for_each(hypergeometric_1f0_results.begin(),\n                hypergeometric_1f0_results.end(),\n                [&i, &a](mp_type& new_value)\n                {\n                  const mp_type x(-(boost::math::constants::euler<mp_type>() * i));\n\n                  new_value = examples::nr_006::luke_ccoef1_hypergeometric_1f0(a, x);\n\n                  ++i;\n                });\n\n  total_time += STD_CHRONO::duration_cast<STD_CHRONO::duration<float> >(my_stopwatch.elapsed()).count();\n\n  // Print the values of Hypergeometric1F0.\n  std::for_each(hypergeometric_1f0_results.begin(),\n                hypergeometric_1f0_results.end(),\n                [](const mp_type& h)\n                {\n                  std::cout << std::setprecision(DIGIT_COUNT) << h << std::endl;\n                });\n\n  std::cout << \"test hypergeometric_1f1.\" << std::endl;\n  i = 1U;\n  my_stopwatch.reset();\n\n  // Generate a table of values of Hypergeometric1F1.\n  // Compare with the Mathematica command:\n  // Table[N[HypergeometricPFQ[{3/7}, {2/3}, -(i*EulerGamma)], 100], {i, 1, 20, 1}]\n  std::for_each(hypergeometric_1f1_results.begin(),\n                hypergeometric_1f1_results.end(),\n                [&i, &a, &b](mp_type& new_value)\n                {\n                  const mp_type x(-(boost::math::constants::euler<mp_type>() * i));\n\n                  new_value = examples::nr_006::luke_ccoef3_hypergeometric_1f1(a, b, x);\n\n                  ++i;\n                });\n\n  total_time += STD_CHRONO::duration_cast<STD_CHRONO::duration<float> >(my_stopwatch.elapsed()).count();\n\n  // Print the values of Hypergeometric1F1.\n  std::for_each(hypergeometric_1f1_results.begin(),\n                hypergeometric_1f1_results.end(),\n                [](const mp_type& h)\n                {\n                  std::cout << std::setprecision(DIGIT_COUNT) << h << std::endl;\n                });\n\n  std::cout << \"test hypergeometric_1f2.\" << std::endl;\n  i = 1U;\n  my_stopwatch.reset();\n\n  // Generate a table of values of Hypergeometric1F2.\n  // Compare with the Mathematica command:\n  // Table[N[HypergeometricPFQ[{3/7}, {2/3, 1/4}, -(i*EulerGamma)], 100], {i, 1, 20, 1}]\n  std::for_each(hypergeometric_1f2_results.begin(),\n                hypergeometric_1f2_results.end(),\n                [&i, &a, &b, &c](mp_type& new_value)\n                {\n                  const mp_type x(-(boost::math::constants::euler<mp_type>() * i));\n\n                  new_value = examples::nr_006::luke_ccoef6_hypergeometric_1f2(a, b, c, x);\n\n                  ++i;\n                });\n\n  total_time += STD_CHRONO::duration_cast<STD_CHRONO::duration<float> >(my_stopwatch.elapsed()).count();\n\n  // Print the values of Hypergeometric1F2.\n  std::for_each(hypergeometric_1f2_results.begin(),\n                hypergeometric_1f2_results.end(),\n                [](const mp_type& h)\n                {\n                  std::cout << std::setprecision(DIGIT_COUNT) << h << std::endl;\n                });\n\n  std::cout << \"test hypergeometric_2f1.\" << std::endl;\n  i = 1U;\n  my_stopwatch.reset();\n\n  // Generate a table of values of Hypergeometric2F1.\n  // Compare with the Mathematica command:\n  // Table[N[HypergeometricPFQ[{3/7, 2/3}, {1/4}, -(i * EulerGamma)], 100], {i, 1, 20, 1}]\n  std::for_each(hypergeometric_2f1_results.begin(),\n                hypergeometric_2f1_results.end(),\n                [&i, &a, &b, &c](mp_type& new_value)\n                {\n                  const mp_type x(-(boost::math::constants::euler<mp_type>() * i));\n\n                  new_value = examples::nr_006::luke_ccoef2_hypergeometric_2f1(a, b, c, x);\n\n                  ++i;\n                });\n\n  total_time += STD_CHRONO::duration_cast<STD_CHRONO::duration<float> >(my_stopwatch.elapsed()).count();\n\n  // Print the values of Hypergeometric2F1.\n  std::for_each(hypergeometric_2f1_results.begin(),\n                hypergeometric_2f1_results.end(),\n                [](const mp_type& h)\n                {\n                  std::cout << std::setprecision(DIGIT_COUNT) << h << std::endl;\n                });\n\n  std::cout << \"Total execution time = \" << std::setprecision(3) << total_time << \"s\" << std::endl;\n}\n", "meta": {"hexsha": "4fb4e13bdf195071d2b832a7cfa4ed1433d97aeb", "size": 26915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/multiprecision/example/hypergeometric_luke_algorithms.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T15:15:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T15:15:28.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/multiprecision/example/hypergeometric_luke_algorithms.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T20:49:05.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/multiprecision/example/hypergeometric_luke_algorithms.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 33.5598503741, "max_line_length": 212, "alphanum_fraction": 0.5500650195, "num_tokens": 7716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6156897245755989}}
{"text": "#include <dynamic_reconfigure/server.h>\n#include <eigen_conversions/eigen_msg.h>\n#include <Eigen/Geometry>\n#include <deque>\n#include \"geometry_msgs/WrenchStamped.h\"\n#include \"nav_msgs/Odometry.h\"\n#include \"ros/ros.h\"\n#include \"sub8_controller/GainConfig.h\"\n#include \"sub8_msgs/Trajectory.h\"\n#include \"sub8_msgs/Waypoint.h\"\n\ntypedef std::deque<Eigen::Vector3d> ControllerDeque;\n\nclass PDController\n{\n  /*\n    [1] One day, all the land will be boxplus\n        http://arxiv.org/pdf/1107.1119.pdf\n    TODO: Make this an abstract class\n  */\npublic:\n  PDController();\n\nprivate:\n  // ROS Miscellanea\n  ros::NodeHandle nh;\n  ros::Subscriber waypoint_sub;\n  ros::Subscriber truth_sub;\n  ros::Publisher wrench_pub;\n  ros::Timer control_timer;\n  dynamic_reconfigure::Server<sub8_controller::GainConfig> server;\n  dynamic_reconfigure::Server<sub8_controller::GainConfig>::CallbackType reconfigure_callback;\n\n  bool ready = false;  // Wait until we're ready\n  bool got_state = false;\n  bool got_target = false;\n  double control_period = 0.02;\n\n  // Pose-trackings\n  struct PoseStruct\n  {\n    Eigen::Vector3d position;\n    Eigen::Matrix3d orientation;\n    Eigen::Vector3d linear_velocity;\n    Eigen::Vector3d angular_velocity;\n  };\n\n  sub8_msgs::Trajectory::ConstPtr current_trajectory;\n  PoseStruct target_state;\n  PoseStruct current_state;\n\n  // Control Parameters\n  unsigned int waypoint_index = 0;\n  unsigned int trans_history_length = 75;\n  unsigned int angle_history_length = 75;\n  ControllerDeque translation_error_history;\n  ControllerDeque orientation_error_history;\n\n  double waypoint_achievement_distance = 0.4;\n\n  double kp_trans = 30;\n  double kd_trans = 13;\n  double ki_trans = 25;\n\n  double kp_angle = 29;\n  double kd_angle = 14;\n  double ki_angle = 5;\n  double sub_mass = 25;  // kg\n\n  // Callbacks\n  void gain_callback(sub8_controller::GainConfig &config, uint32_t level);\n\n  void trajectory_callback(const sub8_msgs::Trajectory::ConstPtr &);\n  void truth_callback(const nav_msgs::Odometry::ConstPtr &);\n  geometry_msgs::WrenchStamped msg_from_wrench(Eigen::Vector3d &);\n  geometry_msgs::WrenchStamped msg_from_wrench(Eigen::Vector3d &, Eigen::Vector3d);\n\n  // Math\n  void append_to_history(ControllerDeque &history, Eigen::Vector3d &datum, unsigned int length);\n  Eigen::AngleAxis<double> rotation_difference(Eigen::Matrix3d &rotation_a, Eigen::Matrix3d &rotation_b);\n  Eigen::Vector3d estimate_derivative(ControllerDeque &);\n  Eigen::Vector3d estimate_integral(ControllerDeque &history);\n\n  // Control\n  void control_loop(const ros::TimerEvent &);\n  void set_target(unsigned int waypoint_index);\n};", "meta": {"hexsha": "afd1ec66ccb6e0690777ad4bb0fee0466d6a2085", "size": 2603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deprecated/gnc/sub8_controller/include/sub8_controller/pd_controller.hpp", "max_stars_repo_name": "ericgorday/SubjuGator", "max_stars_repo_head_hexsha": "f45ac790f06eb97efc0b0810a7b43d0a6e2facee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-02-17T21:54:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T17:49:23.000Z", "max_issues_repo_path": "deprecated/gnc/sub8_controller/include/sub8_controller/pd_controller.hpp", "max_issues_repo_name": "ericgorday/SubjuGator", "max_issues_repo_head_hexsha": "f45ac790f06eb97efc0b0810a7b43d0a6e2facee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 325.0, "max_issues_repo_issues_event_min_datetime": "2019-09-11T14:13:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T00:38:30.000Z", "max_forks_repo_path": "deprecated/gnc/sub8_controller/include/sub8_controller/pd_controller.hpp", "max_forks_repo_name": "ericgorday/SubjuGator", "max_forks_repo_head_hexsha": "f45ac790f06eb97efc0b0810a7b43d0a6e2facee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2019-09-16T00:29:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T10:56:38.000Z", "avg_line_length": 29.9195402299, "max_line_length": 105, "alphanum_fraction": 0.7575873992, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6156897114362118}}
{"text": "//\n// Created by leanne on 11/23/20.\n//\n\n#include \"utility.h\"\n#include \"VWAP.h\"\n#include <ctime>\n#include <cmath>\n#include <random>\n#include <algorithm>\n#include <cstdio>\n#include <boost/timer/timer.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/moment.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n\nusing std::vector;\nusing std::ofstream;\nusing namespace boost::accumulators;\nusing timer = boost::timer::auto_cpu_timer;\n\n\nvoid VWAPOption::computefirst2Moments(ofstream& file) {\n    timer t;\n    accumulator_set<double, stats<tag::moment<1>,tag::variance(immediate) > > moment1;\n    accumulator_set<double, stats<tag::moment<2>,tag::variance(immediate) > > moment2;\n\n    //compute estimate for 1st moment\n    for (int i = 0; i < NPaths_; ++i) {\n        double VWAP_T = simulateSinglePath();\n        moment1(VWAP_T);\n    }\n\n    //compute estimate for 2nd moment\n    for (int i = 0; i < NPaths_; ++i) {\n        double VWAP_T = simulateSinglePath();\n        moment2(VWAP_T);\n    }\n\n    cout << std::endl;\n    cout << \"computation time = \" << t.format(3) << std::endl;\n    cout << \"sigmaPrice = \" << sigmaPrice_ << std::endl;\n    cout << \"E(VWAP) = \" << moment<1>(moment1) << std::endl;\n    cout << \"E(VWAP^2) = \" << moment<2>(moment2) << std::endl;\n\n    file << sigmaPrice_\n         << \", \"\n         << moment<1>(moment1) //E(VWAP)\n         << \", \"\n         << sqrt(variance(moment1)) //StdErr(VWAP)\n         << \", \"\n         << moment<2>(moment2) //E(VWAP)\n         << \", \"\n         << sqrt(variance(moment2)) //StdErr(VWAP^2)\n         << std::endl;\n}\n\n\nvoid VWAPOption::computeMoment3(ofstream& file) {\n    timer t;\n    accumulator_set<double, stats<tag::moment<3> > > moment3;\n\n    //compute estimate for 3rd moment\n    for (int i = 0; i < NPaths_; ++i) {\n        double VWAP_T = simulateSinglePath();\n        moment3(VWAP_T);\n    }\n\n    cout << std::endl;\n    cout << \"computation time = \" << t.format(3) << std::endl;\n    cout << \"sigmaPrice = \" << sigmaPrice_ << std::endl;\n    cout << \"E(VWAP^3) = \" << moment<3>(moment3) << std::endl;\n\n    file << sigmaPrice_\n         << \", \"\n         << moment<3>(moment3) //E(VWAP^3)\n         << std::endl;\n}\n\nvoid VWAPOption::computePrice(ofstream& file) {\n    timer t;\n    accumulator_set<double, stats<tag::mean, tag::variance(immediate) > > price;\n\n    //compute estimate for VWAP price\n    for (int i = 0; i < NPaths_; ++i) {\n        double VWAP_T = simulateSinglePath();\n        if((VWAP_T - K_ ) > 0)\n        {\n            price(VWAP_T - K_);\n        }\n        else\n        {\n            price(0.0);\n        }\n    }\n    cout << std::endl;\n    cout << \"computation time = \" << t.format(3) << std::endl;\n    cout << \"sigmaPrice = \" << sigmaPrice_ << std::endl;\n    cout << \"price = \" << mean(price) << std::endl;\n    cout << \"stdDevPrice = \" << sqrt(variance(price)) << std::endl;\n\n    file << sigmaPrice_\n         << \", \"\n         << mean(price) //option price\n         << \", \"\n         << sqrt(variance(price)) << std::endl;\n\n}\nvoid VWAPOption::computeMoment3AndPrice(ofstream& file) {\n    timer t;\n    accumulator_set<double, stats<tag::moment<3> > > moment3;\n    accumulator_set<double, stats<tag::mean, tag::variance(immediate) > > price;\n\n\n    //compute estimate for 3rd moment\n    for (int i = 0; i < NPaths_; ++i) {\n        double VWAP_T = simulateSinglePath();\n        moment3(VWAP_T);\n    }\n\n    //compute estimate for VWAP price\n    for (int i = 0; i < NPaths_; ++i) {\n        double VWAP_T = simulateSinglePath();\n        if((VWAP_T - K_ ) > 0)\n            price(VWAP_T - K_);\n        else\n            price(0.0);\n    }\n\n    cout << std::endl;\n    cout << \"computation time = \" << t.format(2) << std::endl;\n    cout << \"sigmaPrice = \" << sigmaPrice_ << std::endl;\n    cout << \"E(VWAP^3) = \" << moment<3>(moment3) << std::endl;\n    cout << \"price = \" << mean(price) << std::endl;\n    cout << \"stdDevPrice = \" << sqrt(variance(price)) << std::endl;\n\n    file << sigmaPrice_\n         << \", \"\n         << moment<3>(moment3) //E(VWAP^3)\n         << \", \"\n         << mean(price) //option price\n         << \", \"\n         << sqrt(variance(price)) << std::endl;\n\n}\n\nvoid VWAPOption::computeParameters(ofstream& file) {\n    using std::cout;\n    timer t;\n    for (int i = 0; i < NPaths_; ++i) {\n\n        double VWAP_T = simulateSinglePath();\n\n        VWAPMoments_(VWAP_T);\n\n        if((VWAP_T - K_ ) > 0)\n            callOptionPayoffs_(VWAP_T - K_);\n        else\n            callOptionPayoffs_(0.0);\n    }\n\n    cout << std::endl;\n    cout << \"computation time = \" << t.format(3) << std::endl;\n    cout << \"sigmaPrice = \" << sigmaPrice_ << std::endl;\n    cout << \"Delta = \" << delta_ << std::endl;\n    cout << \"E(VWAP) = \" << moment<1>(VWAPMoments_) << std::endl;\n    cout << \"E(VWAP^2) = \" << moment<2>(VWAPMoments_) << std::endl;\n    cout << \"E(VWAP^3) = \" << moment<3>(VWAPMoments_) << std::endl;\n    cout << \"price = \" << mean(callOptionPayoffs_) << std::endl;\n    cout << \"stdDev = \" << sqrt(variance(callOptionPayoffs_)) << std::endl;\n\n\n    file << sigmaPrice_\n         << \", \"\n         << moment<1>(VWAPMoments_) //E(VWAP)\n         << \", \"\n         << moment<2>(VWAPMoments_) //E(VWAP^2)\n         << \", \"\n         << moment<3>(VWAPMoments_) //E(VWAP^3)\n         << \", \"\n         << mean(callOptionPayoffs_) //option price\n         << \", \"\n         << sqrt(variance(callOptionPayoffs_)) << std::endl;\n}\n\n\ndouble VWAPOption::GetNormDistrDouble(std::mt19937 &gen)\n{\n    double val = 1;\n    std::normal_distribution<> nd;\n    //   val = nd(gen);\n    do { val = nd(gen);}\n    while(val < 0.4 || val > 2.5);\n\n    return val;\n}\n\n//return a realisation of VWAP_T\ndouble VWAPOption::simulateSinglePath() {\n    int seed = -107;\n    std::mt19937 gen(seed);\n\n    double sumStUt = S0_*X0_*X0_;\n    double sumUt   = X0_*X0_;\n\n    double Sti = S0_;\n    double Xti = X0_;\n    double Uti = 0.0;\n    const double muX = a_*(1-exp(-lambda_ * delta_));\n    const double sigmaX2 = pow(sigmaVol_,2)/(2*lambda_)*(1-exp(-2*lambda_*delta_));\n\n    //simulate path over [0,T]\n    for (int i = 1; i <= numIncrements_; i++) {\n        Sti = Sti*exp((mu_-0.5*sigmaPrice_*sigmaPrice_)*delta_\n                      + sigmaPrice_*sqrt(delta_))*GetNormDistrDouble(gen);\n\n        Xti = exp(-lambda_*delta_)*Xti + muX + sqrt(sigmaX2)*GetNormDistrDouble(gen);\n        Uti = pow(Xti,2);\n\n        sumStUt+= Sti*Uti;\n        sumUt += Uti;\n    }\n\n    return (sumStUt/sumUt);\n}\n\n\n", "meta": {"hexsha": "31c2cfc3b53101fe6d50a3132ce947ac7d39b9e2", "size": 6548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "VWAP.cpp", "max_stars_repo_name": "leannejdong/VWAPOpt", "max_stars_repo_head_hexsha": "83d3e0492693ca81052b6388d3555074c678b617", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-16T07:43:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-02T16:48:36.000Z", "max_issues_repo_path": "VWAP.cpp", "max_issues_repo_name": "leannejdong/VWAPOpt", "max_issues_repo_head_hexsha": "83d3e0492693ca81052b6388d3555074c678b617", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VWAP.cpp", "max_forks_repo_name": "leannejdong/VWAPOpt", "max_forks_repo_head_hexsha": "83d3e0492693ca81052b6388d3555074c678b617", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T05:41:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T05:41:40.000Z", "avg_line_length": 28.4695652174, "max_line_length": 86, "alphanum_fraction": 0.5554367746, "num_tokens": 2008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206765295399, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6156273701463173}}
{"text": "#include <fstream>\n#include <iostream>\n#include <experimental/filesystem>\n#include <stdio.h>\n#include <random>\n#include <string>\n\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n#include \"../tasks.hh\"\n#include \"../classes/BinnedTypedMatrix.hh\"\n\nnamespace fs = std::experimental::filesystem;\n\nusing namespace EMC;\n\nusing namespace boost::numeric::ublas;\n\n/// from  https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c\nstd::string random_string(std::string::size_type length) {\n\tstatic auto& chrs = \"0123456789\"\n\t\t\t\"abcdefghijklmnopqrstuvwxyz\"\n\t\t\t\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n\tthread_local static std::mt19937 rg { std::random_device { }() };\n\tthread_local static std::uniform_int_distribution<std::string::size_type> pick(\n\t\t\t0, sizeof(chrs) - 2);\n\n\tstd::string s;\n\n\ts.reserve(length);\n\n\twhile (length--)\n\t\ts += chrs[pick(rg)];\n\n\treturn s;\n}\n\nunsigned int modeCount = 5;\n\nvoid shiftCenters(std::vector<double>& inputVec, unsigned int mode, double error) {\n\tswitch(mode) {\n\tcase 1: {\n\t\tfor (int i=0; i<inputVec.size(); i++) {\n\t\t\tinputVec.at(i) += error;\n\t\t}\n\t\tbreak;\n\t}\n\tcase 2: {\n\t\tfor (int i=0; i<inputVec.size(); i++) {\n\t\t\tinputVec.at(i) += error;\n\t\t\tif (inputVec.at(i) < 0) {\n\t\t\t\tinputVec.at(i) = 0;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tcase 3: {\n\t\tdouble half = inputVec.size() / 2.0;\n\t\tfor (int i=0; i<inputVec.size(); i++) {\n\t\t\tinputVec.at(i) += error * (i-half) / inputVec.size();\n\t\t\tif (inputVec.at(i) < 0) {\n\t\t\t\tinputVec.at(i) = 0;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tcase 4: {\n\t\tdouble half = inputVec.size() / 2.0;\n\t\tfor (int i=0; i<inputVec.size(); i++) {\n\t\t\tinputVec.at(i) -= error * (i-half) / inputVec.size();\n\t\t\tif (inputVec.at(i) < 0) {\n\t\t\t\tinputVec.at(i) = 0;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tcase 0: {\n\t\t/// do nothing, mode 0 does not modify bin centers\n\t\tbreak;\n\t}\n\tdefault:\n\t\tstd::cout << \"this should not happen!!\" << std::endl;\n\t\tbreak;\n\t}\n}\n\nint EMC::rebin_invert(bool forceOverwrite, std::string input, std::string output,\n\t\tint countRate, double minRow, double minCol, double minRowBin,\n\t\tdouble minColBin, double maxRow, double maxCol, double rowError, double colError) {\n\n\tif (!forceOverwrite && fs::exists(output)) {\n\t\tstd::cout << \"Output file already exists, use -f to force overwrite.\" << std::endl;\n\t\treturn 1;\n\t}\n\n    std::streambuf* orig_buf = std::cout.rdbuf();\n    std::cout.rdbuf(NULL);\n\n\tstd::string randRebinName = output + \"_\" + random_string(5) + \"_tmp.rebinned.mat\";\n\trebin(true, input, randRebinName, countRate, minRow, minCol, minRowBin, minColBin, maxRow, maxCol);\n\n\tstd::ifstream infile(randRebinName);\n\tBinnedTypedMatrix inputMatrix = BinnedTypedMatrix::readFromFile(infile);\n\tinfile.close();\n\n\tfs::remove(randRebinName);\n\n\tBinnedTypedMatrix newMat(inputMatrix.columnIndex, inputMatrix.rowIndex, inputMatrix.matType);\n\t{\n\t\ttypedef permutation_matrix<std::size_t> pmatrix;\n\t\t// create a working copy of the input\n\t\tmatrix<ValueError> A(inputMatrix.m);\n\t\t// create a permutation matrix for the LU-factorization\n\t\tpmatrix pm(A.size1());\n\t\t// perform LU-factorization\n\t\tint res = lu_factorize(A,pm);\n\t\tif( res != 0 )\n\t\t\treturn false;\n\t\t// create identity matrix of \"inverse\"\n\t\tnewMat.m.assign(identity_matrix<ValueError>(A.size1()));\n\t\t// backsubstitute to get the inverse\n\t\tlu_substitute(A, pm, newMat.m);\n\t}\n\n\tstd::vector<std::vector<std::vector<real>>> wiggleResults(newMat.rowCount, std::vector<std::vector<real>>(newMat.columnCount, std::vector<real>()));\n\n\tfor (unsigned int i=0; i<modeCount; i++) {\n\t\tfor (unsigned int j=0; j<modeCount; j++) {\n\t\t\tif (i==0 && j==0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t    std::cout.rdbuf(orig_buf);\n\t\t\tstd::cout << \"mode \" << i << \" \" << j << std::endl;\n\t\t\tstd::cout.flush();\n\t\t    std::cout.rdbuf(NULL);\n\n\t\t\tstd::string randKey = random_string(5);\n\n\t\t    std::cout.rdbuf(orig_buf);\n\t\t\tstd::cout << \"shift, \";\n\t\t\tstd::cout.flush();\n\t\t    std::cout.rdbuf(NULL);\n\t\t\tstd::string tmpShiftedMatrixName = output + \"_\" + randKey + \"_tmp.shifted.mat\";\n\t\t\t{ // shift matrix by mode\n\t\t\t\tstd::ifstream infile(input);\n\t\t\t\tBinnedTypedMatrix inputMat = BinnedTypedMatrix::readFromFile(infile);\n\n\t\t\t\tdouble mult = 0.7071067812;\n\n\t\t\t\tif (i==0 || j==0)\n\t\t\t\t\tmult=1;\n\n\t\t\t\tshiftCenters(inputMat.rowIndex, i, mult*rowError);\n\t\t\t\tshiftCenters(inputMat.columnIndex, j, mult*colError);\n\n\t\t\t\tstd::ofstream shiftedMatOutputName(tmpShiftedMatrixName);\n\t\t\t\tinputMat.writeToFile(shiftedMatOutputName);\n\t\t\t}\n\n\t\t    std::cout.rdbuf(orig_buf);\n\t\t\tstd::cout << \"rebin, \";\n\t\t\tstd::cout.flush();\n\t\t    std::cout.rdbuf(NULL);\n\t\t\tstd::string tmpRebinnedMatName = output + \"_\" + randKey + \"_tmp.rebin.mat\";\n\t\t\trebin(true, tmpShiftedMatrixName, tmpRebinnedMatName, countRate, minRow, minCol, minRowBin, minColBin, maxRow, maxCol);\n\n\t\t    std::cout.rdbuf(orig_buf);\n\t\t\tstd::cout << \"invert \";\n\t\t\tstd::cout.flush();\n\t\t    std::cout.rdbuf(NULL);\n\t\t\tstd::string tmpInvertedMatName = output + \"_\" + randKey + \"_tmp.inverted.mat\";\n\t\t\tinvert(true, tmpRebinnedMatName, tmpInvertedMatName);\n\n\t\t\tstd::ifstream infile(tmpInvertedMatName);\n\t\t\tBinnedTypedMatrix rebinnedInvertedMatrix = BinnedTypedMatrix::readFromFile(infile);\n\t\t\tinfile.close();\n\n\t\t\tfs::remove(tmpShiftedMatrixName);\n\t\t\tfs::remove(tmpRebinnedMatName);\n\t\t\tfs::remove(tmpInvertedMatName);\n\n\t\t    std::cout.rdbuf(orig_buf);\n\t\t\tstd::cout << \"and done!\" << std::endl;\n\t\t\tstd::cout.flush();\n\t\t    std::cout.rdbuf(NULL);\n\t\t\tfor (unsigned int rowPos = 0; rowPos < newMat.rowCount; rowPos++) {\n\t\t\t\tfor (unsigned int colPos = 0; colPos < newMat.columnCount; colPos++) {\n\t\t\t\t\twiggleResults.at(rowPos).at(colPos).push_back(rebinnedInvertedMatrix.m(rowPos, colPos).value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (unsigned int rowPos = 0; rowPos < newMat.rowCount; rowPos++) {\n\t\tfor (unsigned int colPos = 0; colPos < newMat.columnCount; colPos++) {\n\t\t\tnewMat.m(rowPos, colPos).err_sq = 0;\n\t\t\tfor (unsigned int i = 0; i<(modeCount*modeCount-1); i++) {\n\n\t\t\t\t// use this (quadratic mean)\n\t\t\t\tnewMat.m(rowPos, colPos).err_sq += pow(wiggleResults.at(rowPos).at(colPos).at(i)-newMat.m(rowPos, colPos).value, 2) / (modeCount*modeCount-1);\n\n\t\t\t\t// or this (linear mean)\n\t\t\t\t/*newMat.m(rowPos, colPos).err_sq += std::fabs(wiggleResults.at(rowPos).at(colPos).at(i)-newMat.m(rowPos, colPos).value) / (maxMode*maxMode);\n\t\t\t\tnewMat.m(rowPos, colPos).err_sq = newMat.m(rowPos, colPos).err_sq * newMat.m(rowPos, colPos).err_sq;*/\n\t\t\t}\n\t\t}\n\t}\n\n    std::ofstream outputF(output);\n    newMat.writeToFile(outputF);\n    outputF.close();\n\n    return 0;\n}\n", "meta": {"hexsha": "61e25c08417ffe0b0e419a79e64bd62ffe679cd0", "size": 6648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tasks/rebin_invert.cpp", "max_stars_repo_name": "pixel-toolbox/error-matrix-calculation", "max_stars_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tasks/rebin_invert.cpp", "max_issues_repo_name": "pixel-toolbox/error-matrix-calculation", "max_issues_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tasks/rebin_invert.cpp", "max_forks_repo_name": "pixel-toolbox/error-matrix-calculation", "max_forks_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6785714286, "max_line_length": 149, "alphanum_fraction": 0.6698255114, "num_tokens": 1987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6156273620975455}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\nnamespace fluid {\nnamespace algorithm {\nnamespace _impl {\n\nindex incrementalMeanVariance(const Eigen::Ref<Eigen::ArrayXXd> data,\n                              index                             lastSampleCount,\n                              Eigen::Ref<Eigen::ArrayXd>        mean,\n                              Eigen::Ref<Eigen::ArrayXd>        var)\n{\n\n  \n  Eigen::VectorXd rowSums = data.isNaN().select(0, data).colwise().sum();\n  index          newSampleCount = data.rows();\n  Eigen::ArrayXd lastSum = mean * lastSampleCount;\n  \n  if (mean.cols() > 0)\n  {\n    index updatedSampleCount = lastSampleCount + newSampleCount;\n    mean = ((mean * lastSampleCount) + rowSums.array()) / updatedSampleCount;\n\n    if (var.rows() > 0)\n    {\n    \n      Eigen::ArrayXXd tmp  = (data.transpose().colwise() - (rowSums.array() / newSampleCount)).transpose();\n      Eigen::ArrayXd correction = tmp.colwise().sum();\n      tmp = tmp.square();\n    \n      Eigen::ArrayXd newUnnormalisedVar = tmp.colwise().sum();\n      newUnnormalisedVar -= correction.square() / newSampleCount;\n    \n      Eigen::ArrayXd lastUnormalisedVar = var * lastSampleCount;\n  \n      \n      if(lastSampleCount > 0)\n      {\n          double lastCountOverNewCount = static_cast<double>(lastSampleCount) / newSampleCount;\n          var =(\n              lastUnormalisedVar\n              + newUnnormalisedVar\n              + lastCountOverNewCount\n                / updatedSampleCount\n                * (lastSum / lastCountOverNewCount - rowSums.array()).square()\n                );\n      }\n      var /= updatedSampleCount;\n    }\n    return updatedSampleCount;\n  }\n  return lastSampleCount;\n}\n\n} // namespace _impl\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "ede5a307406942f57095ef63aee049fe62de083e", "size": 1746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/IncrementalMeanVar.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/util/IncrementalMeanVar.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/util/IncrementalMeanVar.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.593220339, "max_line_length": 107, "alphanum_fraction": 0.5853379152, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6156273584985985}}
{"text": "\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <thread>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Dense>\n\n// #include <opencv2/core/core.hpp> // needed for verbosity >= 3, DISVISUAL\n// #include <opencv2/highgui/highgui.hpp> // needed for verbosity >= 3, DISVISUAL\n// #include <opencv2/imgproc/imgproc.hpp> // needed for verbosity >= 3, DISVISUAL\n\n#include <sys/time.h>    // timeof day\n#include <stdio.h>  \n\n#include \"oflow.h\"\n#include \"patchgrid.h\"\n#include \"refine_variational.h\"\n\n\nusing std::cout;\nusing std::endl;\nusing std::vector;\n\nnamespace OFC\n{\n\n  OFClass::OFClass(const float ** im_ao_in, const float ** im_ao_dx_in, const float ** im_ao_dy_in, // expects #sc_f_in pointers to float arrays for images and gradients. \n                                                                                       // E.g. im_ao[sc_f_in] will be used as coarsest coarsest, im_ao[sc_l_in] as finest scale\n                                                                                       // im_ao[  (sc_l_in-1) : 0 ] can be left as nullptr pointers\n                                                                                       // IMPORTANT assumption: mod(width,2^sc_f_in)==0  AND mod(height,2^sc_f_in)==0, \n                  const float ** im_bo_in, const float ** im_bo_dx_in, const float ** im_bo_dy_in,\n                  const int imgpadding_in,    \n                  float * outflow,\n                  const float * initflow,\n                  const int width_in, const int height_in, \n                  const int sc_f_in, const int sc_l_in,\n                  const int max_iter_in, const int min_iter_in,\n                  const float  dp_thresh_in,\n                  const float  dr_thresh_in,\n                  const float res_thresh_in,            \n                  const int p_samp_s_in,\n                  const float patove_in,\n                  const bool usefbcon_in, \n                  const int costfct_in,                   \n                  const int noc_in,\n                  const int patnorm_in, \n                  const bool usetvref_in,\n                  const float tv_alpha_in,\n                  const float tv_gamma_in,\n                  const float tv_delta_in,\n                  const int tv_innerit_in,\n                  const int tv_solverit_in,\n                  const float tv_sor_in,\n                  const int verbosity_in)\n  : im_ao(im_ao_in), im_ao_dx(im_ao_dx_in), im_ao_dy(im_ao_dy_in),  \n    im_bo(im_bo_in), im_bo_dx(im_bo_dx_in), im_bo_dy(im_bo_dy_in)\n{\n \n  \n  #ifdef WITH_OPENMP\n    if (verbosity_in>1)\n      cout <<  \"OPENMP is ON - used in pconst, pinit, potim\";\n    #ifdef USE_PARALLEL_ON_FLOWAGGR\n    if (verbosity_in>1)\n      cout << \", cflow \";\n    #endif                                                                  \n    if (verbosity_in>1) cout << endl;\n  #endif //DWITH_OPENMP  \n                                                                \n  // Parse optimization parameters\n  #if (SELECTMODE==1)\n  op.nop = 2;\n  #else\n  op.nop = 1;\n  #endif\n  op.p_samp_s = p_samp_s_in;  // patch has even border length, center pixel is at (p_samp_s/2, p_samp_s/2) (ZERO INDEXED!) \n  op.outlierthresh = (float)op.p_samp_s/2;     \n  op.patove = patove_in;\n  op.sc_f = sc_f_in;\n  op.sc_l = sc_l_in;\n  op.max_iter = max_iter_in;\n  op.min_iter = min_iter_in;\n  op.dp_thresh = dp_thresh_in*dp_thresh_in; // saves the square to compare with squared L2-norm (saves sqrt operation)\n  op.dr_thresh = dr_thresh_in;\n  op.res_thresh = res_thresh_in;\n  op.steps = std::max(1,  (int)floor(op.p_samp_s*(1-op.patove)));  \n  op.novals = noc_in * (p_samp_s_in)*(p_samp_s_in);\n  op.usefbcon = usefbcon_in;\n  op.costfct = costfct_in;\n  op.noc = noc_in;\n  op.patnorm = patnorm_in;\n  op.verbosity = verbosity_in;\n  op.noscales = op.sc_f-op.sc_l+1;\n  op.usetvref = usetvref_in;\n  op.tv_alpha = tv_alpha_in;\n  op.tv_gamma = tv_gamma_in;\n  op.tv_delta = tv_delta_in;\n  op.tv_innerit = tv_innerit_in;\n  op.tv_solverit = tv_solverit_in;\n  op.tv_sor = tv_sor_in;\n  op.normoutlier_tmpbsq = (v4sf) {op.normoutlier*op.normoutlier, op.normoutlier*op.normoutlier, op.normoutlier*op.normoutlier, op.normoutlier*op.normoutlier};\n  op.normoutlier_tmp2bsq = __builtin_ia32_mulps(op.normoutlier_tmpbsq, op.twos);\n  op.normoutlier_tmp4bsq = __builtin_ia32_mulps(op.normoutlier_tmpbsq, op.fours);\n\n  \n  // Variables for algorithm timings\n  struct timeval tv_start_all, tv_end_all, tv_start_all_global, tv_end_all_global;\n  if (op.verbosity>0)\n    gettimeofday(&tv_start_all_global, nullptr);\n  \n  // ... per each scale\n  double tt_patconstr[op.noscales], tt_patinit[op.noscales], tt_patoptim[op.noscales], tt_compflow[op.noscales], tt_tvopt[op.noscales], tt_all[op.noscales];\n  for (int sl=op.sc_f; sl>=op.sc_l; --sl) \n  {\n    tt_patconstr[sl-op.sc_l]=0;\n    tt_patinit[sl-op.sc_l]=0;\n    tt_patoptim[sl-op.sc_l]=0;\n    tt_compflow[sl-op.sc_l]=0;\n    tt_tvopt[sl-op.sc_l]=0;\n    tt_all[sl-op.sc_l]=0;\n  }\n\n  if (op.verbosity>1) gettimeofday(&tv_start_all, nullptr);\n \n  \n  // Create grids on each scale\n  vector<OFC::PatGridClass*> grid_fw(op.noscales);\n  vector<OFC::PatGridClass*> grid_bw(op.noscales); // grid for backward OF computation, only needed if 'usefbcon' is set to 1.\n  vector<float*> flow_fw(op.noscales);\n  vector<float*> flow_bw(op.noscales);\n  cpl.resize(op.noscales);\n  cpr.resize(op.noscales);\n  for (int sl=op.sc_f; sl>=op.sc_l; --sl) \n  {\n    int i = sl-op.sc_l;\n\n    float sc_fct = pow(2,-sl); // scaling factor at current scale\n    cpl[i].sc_fct = sc_fct;\n    cpl[i].height = height_in * sc_fct;\n    cpl[i].width = width_in * sc_fct;\n    cpl[i].imgpadding = imgpadding_in;\n    cpl[i].tmp_lb = -(float)op.p_samp_s/2; \n    cpl[i].tmp_ubw = (float) (cpl[i].width +op.p_samp_s/2-2);\n    cpl[i].tmp_ubh = (float) (cpl[i].height+op.p_samp_s/2-2);\n    cpl[i].tmp_w = cpl[i].width + 2*imgpadding_in;\n    cpl[i].tmp_h = cpl[i].height+ 2*imgpadding_in;\n    cpl[i].curr_lv = sl;\n    cpl[i].camlr = 0;\n\n    \n    cpr[i] = cpl[i];\n    cpr[i].camlr = 1;\n    \n    flow_fw[i]   = new float[op.nop * cpl[i].width * cpl[i].height]; \n    grid_fw[i]   = new OFC::PatGridClass(&(cpl[i]), &(cpr[i]), &op);\n   \n    if (op.usefbcon) // for merging forward and backward flow \n    {\n      flow_bw[i] = new float[op.nop * cpr[i].width * cpr[i].height];\n      grid_bw[i] = new OFC::PatGridClass(&(cpr[i]), &(cpl[i]), &op);\n      \n      // Make grids known to each other, necessary for AggregateFlowDense();\n      grid_fw[i]->SetComplGrid( grid_bw[i] );\n      grid_bw[i]->SetComplGrid( grid_fw[i] ); \n    }\n  }\n  \n  \n  // Timing, Grid memory allocation\n  if (op.verbosity>1)\n  {\n    gettimeofday(&tv_end_all, nullptr);\n    double tt_gridconst = (tv_end_all.tv_sec-tv_start_all.tv_sec)*1000.0f + (tv_end_all.tv_usec-tv_start_all.tv_usec)/1000.0f;\n    printf(\"TIME (Grid Memo. Alloc. ) (ms): %3g\\n\", tt_gridconst);          \n  }\n  \n\n  // *** Main loop; Operate over scales, coarse-to-fine\n  for (int sl=op.sc_f; sl>=op.sc_l; --sl)  \n  {\n    int ii = sl-op.sc_l;\n\n    if (op.verbosity>1) gettimeofday(&tv_start_all, nullptr);\n\n    // Initialize grid (Step 1 in Algorithm 1 of paper)\n    grid_fw[ii]->  InitializeGrid(im_ao[sl], im_ao_dx[sl], im_ao_dy[sl]);\n    grid_fw[ii]->  SetTargetImage(im_bo[sl], im_bo_dx[sl], im_bo_dy[sl]);\n    if (op.usefbcon)\n    {\n      grid_bw[ii]->InitializeGrid(im_bo[sl], im_bo_dx[sl], im_bo_dy[sl]);\n      grid_bw[ii]->SetTargetImage(im_ao[sl], im_ao_dx[sl], im_ao_dy[sl]);\n    }\n\n    // Timing, Grid construction\n    if (op.verbosity>1)\n    {\n      gettimeofday(&tv_end_all, nullptr);\n      tt_patconstr[ii] = (tv_end_all.tv_sec-tv_start_all.tv_sec)*1000.0f + (tv_end_all.tv_usec-tv_start_all.tv_usec)/1000.0f;\n      tt_all[ii] += tt_patconstr[ii];\n      gettimeofday(&tv_start_all, nullptr);\n    }\n    \n    // Initialization from previous scale, or to zero at first iteration. (Step 2 in Algorithm 1 of paper)                                          \n    if (sl < op.sc_f)\n    {\n      grid_fw[ii]->InitializeFromCoarserOF(flow_fw[ii+1]); // initialize from flow at previous coarser scale\n      \n      // Initialize backward flow\n      if (op.usefbcon)\n        grid_bw[ii]->InitializeFromCoarserOF(flow_bw[ii+1]);\n    } \n    else if (sl == op.sc_f && initflow != nullptr) // initialization given input flow\n    {\n      grid_fw[ii]->InitializeFromCoarserOF(initflow); // initialize from flow at coarser scale\n    }\n\n    // Timing, Grid initialization\n    if (op.verbosity>1)\n    {    \n      gettimeofday(&tv_end_all, nullptr);\n      tt_patinit[ii] = (tv_end_all.tv_sec-tv_start_all.tv_sec)*1000.0f + (tv_end_all.tv_usec-tv_start_all.tv_usec)/1000.0f;\n      tt_all[ii] += tt_patinit[ii];                                                                                                                                \n      gettimeofday(&tv_start_all, nullptr);\n    }      \n    \n    \n    // Dense Inverse Search. (Step 3 in Algorithm 1 of paper)                                          \n    grid_fw[ii]->Optimize();\n    if (op.usefbcon)\n      grid_bw[ii]->Optimize();\n      \n//     if (op.verbosity==4) // needed for verbosity >= 3, DISVISUAL\n//     {\n//       grid_fw[ii]->OptimizeAndVisualize(pow(2, sl));\n//       if (op.usefbcon)\n//         grid_bw[ii]->Optimize();\n//     }\n//     else\n//     {\n//       grid_fw[ii]->Optimize();\n//       if (op.usefbcon)\n//         grid_bw[ii]->Optimize();\n//     }\n\n    \n    // Timing, DIS\n    if (op.verbosity>1)\n    {    \n      gettimeofday(&tv_end_all, nullptr);\n      tt_patoptim[ii] = (tv_end_all.tv_sec-tv_start_all.tv_sec)*1000.0f + (tv_end_all.tv_usec-tv_start_all.tv_usec)/1000.0f;\n      tt_all[ii] += tt_patoptim[ii];                                                                                                                                                                                                          \n      \n      gettimeofday(&tv_start_all, nullptr);\n    }\n\n                                                              \n    // Densification. (Step 4 in Algorithm 1 of paper)                                                                    \n    float *tmp_ptr = flow_fw[ii];\n    if (sl == op.sc_l)\n      tmp_ptr = outflow;\n    \n    grid_fw[ii]->AggregateFlowDense(tmp_ptr);\n    \n    if (op.usefbcon && sl > op.sc_l )  // skip at last scale, backward flow no longer needed\n      grid_bw[ii]->AggregateFlowDense(flow_bw[ii]);\n      \n    \n    // Timing, Densification\n    if (op.verbosity>1)\n    {    \n      gettimeofday(&tv_end_all, nullptr);\n      tt_compflow[ii] = (tv_end_all.tv_sec-tv_start_all.tv_sec)*1000.0f + (tv_end_all.tv_usec-tv_start_all.tv_usec)/1000.0f;\n      tt_all[ii] += tt_compflow[ii];                                                                                                                                                                                                          \n      \n      gettimeofday(&tv_start_all, nullptr);\n    }    \n  \n  \n    // Variational refinement, (Step 5 in Algorithm 1 of paper)\n    if (op.usetvref)\n    {\n      OFC::VarRefClass varref_fw(im_ao[sl], im_ao_dx[sl], im_ao_dy[sl], \n                                im_bo[sl], im_bo_dx[sl], im_bo_dy[sl]\n                                ,&(cpl[ii]), &(cpr[ii]), &op, tmp_ptr);\n      \n      if (op.usefbcon  && sl > op.sc_l )    // skip at last scale, backward flow no longer needed\n          OFC::VarRefClass varref_bw(im_bo[sl], im_bo_dx[sl], im_bo_dy[sl], \n                                    im_ao[sl], im_ao_dx[sl], im_ao_dy[sl]\n                                    ,&(cpr[ii]), &(cpl[ii]), &op, flow_bw[ii]);\n    }\n    \n    // Timing, Variational Refinement\n    if (op.verbosity>1)\n    {        \n      gettimeofday(&tv_end_all, nullptr);\n      tt_tvopt[ii] = (tv_end_all.tv_sec-tv_start_all.tv_sec)*1000.0f + (tv_end_all.tv_usec-tv_start_all.tv_usec)/1000.0f;\n      tt_all[ii] += tt_tvopt[ii];                                                                                                                                                                                                                                                                     \n      printf(\"TIME (Sc: %i, #p:%6i, pconst, pinit, poptim, cflow, tvopt, total): %8.2f %8.2f %8.2f %8.2f %8.2f -> %8.2f ms.\\n\", sl, grid_fw[ii]->GetNoPatches(), tt_patconstr[ii], tt_patinit[ii], tt_patoptim[ii], tt_compflow[ii], tt_tvopt[ii], tt_all[ii]);\n    }\n                                                                \n\n//     if (op.verbosity==3) // Display displacement result of this scale // needed for verbosity >= 3, DISVISUAL\n//     {\n//       // Display Grid on current scale\n//       float sc_fct_tmp = pow(2, sl); // upscale factor\n// \n//       cv::Mat src(cpl[ii].height+2*cpl[ii].imgpadding, cpl[ii].width+2*cpl[ii].imgpadding, CV_32FC1, (void*) im_ao[sl]);  \n//       cv::Mat img_ao_mat = src(cv::Rect(cpl[ii].imgpadding, cpl[ii].imgpadding, cpl[ii].width, cpl[ii].height));\n// \n//       cv::Mat outimg;\n//       img_ao_mat.convertTo(outimg, CV_8UC1);\n//       cv::cvtColor(outimg, outimg, CV_GRAY2RGB);\n//       cv::resize(outimg, outimg, cv::Size(), sc_fct_tmp, sc_fct_tmp, cv::INTER_NEAREST);\n//       for (int i = 0; i < grid_fw[ii]->GetNoPatches() ; ++i)\n//         DisplayDrawPatchBoundary(outimg, grid_fw[ii]->GetRefPatchPos(i), sc_fct_tmp);\n//                           \n//       for (int i = 0; i < grid_fw[ii]->GetNoPatches(); ++i)\n//       {\n//         // Show displacement vector\n//         const Eigen::Vector2f pt_ref = grid_fw[ii]->GetRefPatchPos(i);\n//         const Eigen::Vector2f pt_ret = grid_fw[ii]->GetQuePatchPos(i);\n// \n//         Eigen::Vector2f pta, ptb;\n//         cv::line(outimg, cv::Point( (pt_ref[0]+.5)*sc_fct_tmp, (pt_ref[1]+.5)*sc_fct_tmp ), cv::Point( (pt_ret[0]+.5)*sc_fct_tmp, (pt_ret[1]+.5)*sc_fct_tmp ), cv::Scalar(0,255,0),  2);\n//       }\n//       cv::namedWindow( \"Img_ao\", cv::WINDOW_AUTOSIZE );\n//       cv::imshow( \"Img_ao\", outimg);\n//       \n//       cv::waitKey(0);\n//     }\n                                                              \n  }\n  \n  // Clean up\n  for (int sl=op.sc_f; sl>=op.sc_l; --sl) \n  {                                        \n\n    delete[] flow_fw[sl-op.sc_l];    \n    delete grid_fw[sl-op.sc_l];\n\n    if (op.usefbcon) \n    {\n      delete[] flow_bw[sl-op.sc_l];\n      delete grid_bw[sl-op.sc_l];\n    }\n  }\n  \n   \n  // Timing, total algorithm run-time\n  if (op.verbosity>0)\n  {       \n    gettimeofday(&tv_end_all_global, nullptr);\n    double tt = (tv_end_all_global.tv_sec-tv_start_all_global.tv_sec)*1000.0f + (tv_end_all_global.tv_usec-tv_start_all_global.tv_usec)/1000.0f;\n    printf(\"TIME (O.Flow Run-Time   ) (ms): %3g\\n\", tt);            \n  }\n\n  \n}\n\n// // needed for verbosity >= 3, DISVISUAL\n// void OFClass::DisplayDrawPatchBoundary(cv::Mat img, const Eigen::Vector2f pt, const float sc) \n// {\n//   cv::line(img, cv::Point( (pt[0]+.5)*sc, (pt[1]+.5)*sc ), cv::Point( (pt[0]+.5)*sc, (pt[1]+.5)*sc ), cv::Scalar(0,0,255),  4);\n//   \n//   float lb = -op.p_samp_s/2;\n//   float ub = op.p_samp_s/2-1;     \n//   \n//   cv::line(img, cv::Point( ((pt[0]+lb)+.5)*sc, ((pt[1]+lb)+.5)*sc ), cv::Point( ((pt[0]+ub)+.5)*sc, ((pt[1]+lb)+.5)*sc ), cv::Scalar(0,0,255),  1);\n//   cv::line(img, cv::Point( ((pt[0]+ub)+.5)*sc, ((pt[1]+lb)+.5)*sc ), cv::Point( ((pt[0]+ub)+.5)*sc, ((pt[1]+ub)+.5)*sc ), cv::Scalar(0,0,255),  1);\n//   cv::line(img, cv::Point( ((pt[0]+ub)+.5)*sc, ((pt[1]+ub)+.5)*sc ), cv::Point( ((pt[0]+lb)+.5)*sc, ((pt[1]+ub)+.5)*sc ), cv::Scalar(0,0,255),  1);\n//   cv::line(img, cv::Point( ((pt[0]+lb)+.5)*sc, ((pt[1]+ub)+.5)*sc ), cv::Point( ((pt[0]+lb)+.5)*sc, ((pt[1]+lb)+.5)*sc ), cv::Scalar(0,0,255),  1);\n// }\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "02056cf140fa433fa676dc2642ae2d2c9bec1e1b", "size": 15638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "of_dis/oflow.cpp", "max_stars_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_stars_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-01-31T13:32:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T16:35:29.000Z", "max_issues_repo_path": "of_dis/oflow.cpp", "max_issues_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_issues_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-09-14T11:02:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-29T23:28:48.000Z", "max_forks_repo_path": "of_dis/oflow.cpp", "max_forks_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_forks_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-01T12:20:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T03:42:54.000Z", "avg_line_length": 39.6903553299, "max_line_length": 294, "alphanum_fraction": 0.5462335337, "num_tokens": 4562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6156273548996513}}
{"text": "/**\n * @file mpc.cpp\n * @brief !Valgrind output\n *  Memcheck, a memory error detector\n *  Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.\n *  Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info\n *  Command: ./src/control_system/control_system_mpc_example\n *  \n *  HEAP SUMMARY:\n *      in use at exit: 0 bytes in 0 blocks\n *    total heap usage: 19,575 allocs, 19,575 frees, 866,248 bytes allocated\n *  \n *  All heap blocks were freed -- no leaks are possible\n *  \n *  For lists of detected and suppressed errors, rerun with: -s\n *  ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)\n */\n\n#include <mpc.hpp>\n#include <memory>\n#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n\nusing namespace controller;\n\nint main()\n{\n    unsigned int x = 3; // Number of states [position x, position y, theta].\n    unsigned int u = 2; // Input dimension [translation rate, rotation rate].\n    double dt = 0.025; // Timestamp.\n    double saturation = 10;\n\n    // Declare MAT for MPC computation.\n    Eigen::MatrixXd A(x, x); // System dynamics matrix.\n    Eigen::MatrixXd B(x, u); // Input matrix.\n    Eigen::MatrixXd Q(x, x); // Weight on the systems state.\n    Eigen::MatrixXd R(u, u); // Weight on control input.\n\n    A <<\n        cos(M_PI_4), -sin(M_PI_4), 0.0,\n        sin(M_PI_4), cos(M_PI_4), 0.0,\n        0.0, 0.0, 1.0;\n        \n    B <<\n        cos(M_PI_4) * dt, 0.0,\n        sin(M_PI_4) * dt, 0.0,\n        0.0, dt;\n\n    R <<\n        100.0, 0.0,\n        0.0, 100.0;\n\n    Q <<\n        1.0, 0.0, 0.0,\n        0.0, 1.0, 0.0,\n        0.0, 0.0, 1.0;\n\n    // Initialize MPC and assign the MAT.\n    auto ptr = std::unique_ptr<MPC>(new MPC(Q, R, saturation));\n\n    // Get state error.\n    Eigen::MatrixXd stateError(x, x);\n\n    stateError <<\n        0.0023, 0.0, 0.0,\n        0.0, 0.001, 0.0,\n        0.0, 0.0, 0.001;\n\n    // Get cmd_vel.\n    double numIteration = 100000;\n    double tolarance = 1.E-5;\n\n    Eigen::MatrixXd cmd_vel = ptr->computeDiscrete(A, B, stateError, numIteration, tolarance, dt);\n    std::cout << \"\\ncmd_vel.x\\tcmd_vel.orientation.z\\n\" << cmd_vel(0,0) << \"\\t\\t\" << cmd_vel(0,1) << std::endl;\n\n    /** !Output.\n     * @brief cmd_vel.x\t    cmd_vel.orientation.z\n     *        0.157304\t\t0.0800126\n     */\n\n    return EXIT_SUCCESS;\n}", "meta": {"hexsha": "ac32574cd9b59a5f17b2f682e50c07036ac58602", "size": 2291, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/control_system/example/mpc.cpp", "max_stars_repo_name": "duckstarr/controller", "max_stars_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-05-15T21:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T04:34:54.000Z", "max_issues_repo_path": "src/control_system/example/mpc.cpp", "max_issues_repo_name": "duckstarr/controller", "max_issues_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/control_system/example/mpc.cpp", "max_forks_repo_name": "duckstarr/controller", "max_forks_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6024096386, "max_line_length": 111, "alphanum_fraction": 0.5905718027, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.6155916419754328}}
{"text": "// (C) Copyright David Gleich 2007\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0 (See accompanying file\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\n\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/core_numbers.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <stdio.h>\n\nusing namespace boost;\n\nconst char* errstr = \"\";\n\nint test_1()\n{\n    // core numbers of sample graph\n    typedef adjacency_list< vecS, vecS, undirectedS > Graph;\n\n    Graph G(21);\n    add_edge(0, 1, G);\n    add_edge(1, 2, G);\n    add_edge(1, 3, G);\n    add_edge(2, 3, G);\n    add_edge(1, 4, G);\n    add_edge(3, 4, G);\n    add_edge(4, 5, G);\n    add_edge(4, 6, G);\n    add_edge(5, 6, G);\n    add_edge(4, 7, G);\n    add_edge(5, 7, G);\n    add_edge(6, 7, G);\n    add_edge(7, 8, G);\n    add_edge(3, 9, G);\n    add_edge(8, 9, G);\n    add_edge(8, 10, G);\n    add_edge(9, 10, G);\n    add_edge(10, 11, G);\n    add_edge(10, 12, G);\n    add_edge(3, 13, G);\n    add_edge(9, 13, G);\n    add_edge(3, 14, G);\n    add_edge(9, 14, G);\n    add_edge(13, 14, G);\n    add_edge(16, 17, G);\n    add_edge(16, 18, G);\n    add_edge(17, 19, G);\n    add_edge(18, 19, G);\n    add_edge(19, 20, G);\n\n    std::vector< int > core_nums(num_vertices(G));\n    core_numbers(\n        G, make_iterator_property_map(core_nums.begin(), get(vertex_index, G)));\n\n    for (size_t i = 0; i < num_vertices(G); ++i)\n    {\n        printf(\"vertex %3lu : %i\\n\", (unsigned long)i, core_nums[i]);\n    }\n\n    int correct[21]\n        = { 1, 2, 2, 3, 3, 3, 3, 3, 2, 3, 2, 1, 1, 3, 3, 0, 2, 2, 2, 2, 1 };\n    for (size_t i = 0; i < num_vertices(G); ++i)\n    {\n        if (core_nums[i] != correct[i])\n        {\n            return 1; // error!\n        }\n    }\n    return 0;\n}\n\nint test_2()\n{\n    // core numbers of sample graph\n    typedef adjacency_list< listS, vecS, undirectedS, no_property,\n        property< edge_weight_t, int > >\n        graph_t;\n    int num_nodes = 3;\n    typedef std::pair< int, int > Edge;\n\n    Edge edge_array[] = { Edge(0, 1), Edge(0, 2), Edge(1, 2) };\n    int weights[] = { -1, -2, -2 };\n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n    graph_t G(edge_array, edge_array + num_arcs, weights, num_nodes);\n\n    std::vector< int > core_nums(num_vertices(G));\n    weighted_core_numbers(\n        G, make_iterator_property_map(core_nums.begin(), get(vertex_index, G)));\n\n    for (size_t i = 0; i < num_vertices(G); ++i)\n    {\n        printf(\"vertex %3lu : %i\\n\", (unsigned long)i, core_nums[i]);\n    }\n\n    int correct[3] = { -1, -1, -4 };\n    for (size_t i = 0; i < num_vertices(G); ++i)\n    {\n        if (core_nums[i] != correct[i])\n        {\n            return 1; // error!\n        }\n    }\n    return 0;\n}\n\nint test_3()\n{\n    // core numbers of a directed graph, the core numbers of a directed\n    // cycle are always one\n    typedef adjacency_list< vecS, vecS, directedS > graph_t;\n    int num_nodes = 5;\n    typedef std::pair< int, int > Edge;\n\n    Edge edge_array[]\n        = { Edge(0, 1), Edge(1, 2), Edge(2, 3), Edge(3, 4), Edge(4, 0) };\n    int num_arcs = sizeof(edge_array) / sizeof(Edge);\n\n    graph_t G(edge_array, edge_array + num_arcs, num_nodes);\n\n    std::vector< int > core_nums(num_vertices(G));\n    core_numbers(\n        G, make_iterator_property_map(core_nums.begin(), get(vertex_index, G)));\n\n    for (size_t i = 0; i < num_vertices(G); ++i)\n    {\n        printf(\"vertex %3lu : %i\\n\", (unsigned long)i, core_nums[i]);\n    }\n\n    int correct[5] = { 1, 1, 1, 1, 1 };\n    for (size_t i = 0; i < num_vertices(G); ++i)\n    {\n        if (core_nums[i] != correct[i])\n        {\n            return 1; // error!\n        }\n    }\n    return 0;\n}\n\nint main(int, char**)\n{\n    int nfail = 0, ntotal = 0;\n    int rval;\n\n    const char* name;\n\n    name = \"core_numbers\";\n    rval = test_1();\n    ntotal++;\n    if (rval != 0)\n    {\n        nfail++;\n        printf(\"%20s  %50s\\n\", name, errstr);\n    }\n    else\n    {\n        printf(\"%20s  success\\n\", name);\n    }\n\n    name = \"weighted_core_numbers\";\n    rval = test_2();\n    ntotal++;\n    if (rval != 0)\n    {\n        nfail++;\n        printf(\"%20s  %50s\\n\", name, errstr);\n    }\n    else\n    {\n        printf(\"%20s  success\\n\", name);\n    }\n\n    name = \"directed_corenums\";\n    rval = test_3();\n    ntotal++;\n    if (rval != 0)\n    {\n        nfail++;\n        printf(\"%20s  %50s\\n\", name, errstr);\n    }\n    else\n    {\n        printf(\"%20s  success\\n\", name);\n    }\n\n    printf(\"\\n\");\n    printf(\"Total tests  : %3i\\n\", ntotal);\n    printf(\"Total failed : %3i\\n\", nfail);\n\n    return nfail != 0;\n}\n", "meta": {"hexsha": "24c4e11207852e811dc7620083c3414d8a49c80b", "size": 4611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/test/core_numbers_test.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/graph/test/core_numbers_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/test/core_numbers_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 23.6461538462, "max_line_length": 80, "alphanum_fraction": 0.544567339, "num_tokens": 1538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6154669859487416}}
{"text": "/*\n    Copyright (c) 2017 Mobile Robots Laboratory at Poznan University of Technology:\n    -Jan Wietrzykowski name.surname [at] put.poznan.pl\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 INCLUDE_MISC_HPP_\n#define INCLUDE_MISC_HPP_\n\n#include <ostream>\n#include <vector>\n\n#include <Eigen/Eigen>\n\n#include <pcl/common/common_headers.h>\n#include <pcl/impl/point_types.hpp>\n\n#include <opencv2/opencv.hpp>\n\n#include \"Types.hpp\"\n\nstatic constexpr float pi = 3.14159265359;\n\ntemplate<class T>\nstd::ostream& operator<<(std::ostream& out, const std::vector<T>& vec){\n\tout << \"[\";\n\tfor(int v = 0; v < (int)vec.size(); ++v){\n\t\tout << vec[v];\n\t\tif(v < vec.size() - 1){\n\t\t\tout << \", \";\n\t\t}\n\t}\n\tout << \"]\";\n\n\treturn out;\n}\n\nclass Misc{\npublic:\n\n\tstatic cv::Mat projectTo3D(cv::Mat depth, cv::Mat cameraParams);\n\n    static cv::Mat reprojectTo2D(pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr points, cv::Mat cameraParams);\n\n    static Eigen::Vector3d projectPointOnPlane(const Eigen::Vector3d &pt, const Eigen::Vector4d &plane);\n\n    static Eigen::Vector3d projectPointOnPlane(const Eigen::Vector2d &pt, const Eigen::Vector4d &plane, cv::Mat cameraMatrix);\n\n\tstatic bool projectImagePointsOntoPlane(const vectorVector2d &pts,\n\t\t\t\t\t\t\t\t\t\t   vectorVector3d &pts3d,\n\t\t\t\t\t\t\t\t\t\t   const cv::Mat &cameraMatrix,\n\t\t\t\t\t\t\t\t\t\t   const Eigen::Vector4d &planeEq);\n\t\n\tstatic bool nextChoice(std::vector<int>& choice, int N);\n\n\tstatic Eigen::Quaterniond planeEqToQuat(const Eigen::Vector4d &planeEq);\n\n\tstatic void normalizeAndUnify(Eigen::Quaterniond& q);\n\n\tstatic void normalizeAndUnify(Eigen::Vector4d& q);\n\n    static Eigen::Vector4d toNormalPlaneEquation(const Eigen::Vector4d &plane);\n\n\tstatic Eigen::Vector3d logMap(const Eigen::Quaterniond &quat);\n\n\tstatic Eigen::Quaterniond expMap(const Eigen::Vector3d &vec);\n\n\tstatic Eigen::Matrix4d matrixQ(const Eigen::Quaterniond &q);\n\n\tstatic Eigen::Matrix4d matrixW(const Eigen::Quaterniond &q);\n\n\tstatic Eigen::Matrix3d matrixK(const Eigen::Quaterniond &q);\n\n\tstatic bool checkIfAlignedWithNormals(const Eigen::Vector3d& testedNormal,\n                                            pcl::PointCloud<pcl::Normal>::ConstPtr normals,\n                                            bool& alignConsistent);\n\n\tstatic double transformLogDist(const Vector7d &trans1,\n\t\t\t\t\t\t\t\t   const Vector7d &trans2);\n\n    static double rotLogDist(const Eigen::Vector4d &rot1,\n\t\t\t\t\t\t\t const Eigen::Vector4d &rot2);\n\n    static cv::Mat colorIds(cv::Mat ids);\n\t\n\tstatic cv::Mat colorIdsWithLabels(cv::Mat ids);\n\t\n\tstatic Eigen::Vector3d closestPointOnLine(const Eigen::Vector3d &pt,\n\t\t\t\t\t\t\t\t\t   const Eigen::Vector3d &p,\n\t\t\t\t\t\t\t\t\t   const Eigen::Vector3d &n);\n    \n    template<typename MatrixTypeOut, typename MatrixTypeIn>\n    static MatrixTypeOut pseudoInverse(const MatrixTypeIn &a, double epsilon = std::numeric_limits<double>::epsilon())\n    {\n        Eigen::JacobiSVD< MatrixTypeIn > svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n        double tolerance = epsilon * std::max(a.cols(), a.rows()) * svd.singularValues().array().abs()(0);\n//        return svd.matrixV() *  (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(), 0).matrix().asDiagonal() * svd.matrixU().adjoint();\n        \n        typename Eigen::JacobiSVD< MatrixTypeIn >::SingularValuesType singularValues_inv = svd.singularValues();\n        for ( long i = 0; i < singularValues_inv.cols(); ++i) {\n            if ( fabs(svd.singularValues()(i)) > tolerance ) {\n                singularValues_inv(i) = 1.0 / svd.singularValues()(i);\n            }\n            else{\n                singularValues_inv(i)=0;\n            }\n        }\n        return (svd.matrixV() * singularValues_inv.asDiagonal());\n    }\n};\n\nstatic constexpr uint8_t colors[][3] = {\n\t\t{0xFF, 0x00, 0x00}, //Red\n\t\t{0xFF, 0xFF, 0xFF}, //White\n\t\t{0x00, 0xFF, 0xFF}, //Cyan\n\t\t{0xC0, 0xC0, 0xC0}, //Silver\n\t\t{0x00, 0x00, 0xFF}, //Blue\n\t\t{0x80, 0x80, 0x80}, //Gray\n\t\t{0x00, 0x00, 0xA0}, //DarkBlue\n\t\t{0x00, 0x00, 0x00}, //Black\n\t\t{0xAD, 0xD8, 0xE6}, //LightBlue\n\t\t{0xFF, 0xA5, 0x00}, //Orange\n\t\t{0x80, 0x00, 0x80}, //Purple\n\t\t{0xA5, 0x2A, 0x2A}, //Brown\n\t\t{0xFF, 0xFF, 0x00}, //Yellow\n\t\t{0x80, 0x00, 0x00}, //Maroon\n\t\t{0x00, 0xFF, 0x00}, //Lime\n\t\t{0x00, 0x80, 0x00}, //Green\n\t\t{0xFF, 0x00, 0xFF}, //Magenta\n\t\t{0x80, 0x80, 0x00} //Olive\n};\n\nclass Visualizer{\npublic:\n\n//\tstatic pcl::PointCloud<pcl::PointXYZRGBA>::Ptr makeColorPointcloud(pcl::PointCloud<pcl::PointXYZ>::Ptr\n};\n\n#endif /* INCLUDE_MISC_HPP_ */\n", "meta": {"hexsha": "f73b363b8f2b5df7e10b5410defe4ae61d11907f", "size": 5520, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Misc.hpp", "max_stars_repo_name": "richard5635/PlaneLoc", "max_stars_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2017-08-29T06:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T07:42:31.000Z", "max_issues_repo_path": "include/Misc.hpp", "max_issues_repo_name": "richard5635/PlaneLoc", "max_issues_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-26T06:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-26T01:59:41.000Z", "max_forks_repo_path": "include/Misc.hpp", "max_forks_repo_name": "richard5635/PlaneLoc", "max_forks_repo_head_hexsha": "aab6637124b1b99ad726a94e9f6762dddf3716b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2018-04-24T08:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T07:56:58.000Z", "avg_line_length": 35.1592356688, "max_line_length": 181, "alphanum_fraction": 0.678442029, "num_tokens": 1561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936537604179, "lm_q2_score": 0.8031737963569014, "lm_q1q2_score": 0.6154669830149558}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include \"math/interval.h\" // header to test\n\nusing namespace biosim;\n\nBOOST_AUTO_TEST_SUITE(suite_interval)\n\nBOOST_AUTO_TEST_CASE(int_interval) {\n  math::interval<int> iv;\n  BOOST_CHECK(iv.get_min() == -std::numeric_limits<int>::max());\n  BOOST_CHECK(iv.get_max() == std::numeric_limits<int>::max());\n\n  iv = math::interval<int>(-1, 1);\n  BOOST_CHECK(iv.get_min() == -1);\n  BOOST_CHECK(iv.get_max() == 1);\n  BOOST_CHECK(iv.get_length() == 2);\n\n  iv.set_min(3);\n  BOOST_CHECK(iv.get_min() == 3);\n  BOOST_CHECK(iv.get_max() == 3);\n\n  iv.set_max(2);\n  BOOST_CHECK(iv.get_min() == 2);\n  BOOST_CHECK(iv.get_max() == 2);\n\n  BOOST_CHECK(math::interval<int>::get_epsilon() == 1);\n}\n\nBOOST_AUTO_TEST_CASE(size_t_interval) {\n  math::interval<size_t> iv;\n  BOOST_CHECK(iv.get_min() == std::numeric_limits<size_t>::min());\n  BOOST_CHECK(iv.get_max() == std::numeric_limits<size_t>::max());\n\n  BOOST_CHECK(math::interval<size_t>::get_epsilon() == 1);\n}\n\nBOOST_AUTO_TEST_CASE(double_interval) {\n  math::interval<double> iv;\n  BOOST_CHECK(iv.get_min() == -std::numeric_limits<double>::max());\n  BOOST_CHECK(iv.get_max() == std::numeric_limits<double>::max());\n\n  iv = math::interval<double>(-1.0, 1.0);\n  BOOST_CHECK(iv.get_min() == -1.0);\n  BOOST_CHECK(iv.get_max() == 1.0);\n  BOOST_CHECK(iv.get_length() == 2.0);\n\n  iv.set_min(3.0);\n  BOOST_CHECK(iv.get_min() == 3.0);\n  BOOST_CHECK(iv.get_max() == 3.0);\n\n  iv.set_max(2.0);\n  BOOST_CHECK(iv.get_min() == 2.0);\n  BOOST_CHECK(iv.get_max() == 2.0);\n\n  BOOST_CHECK(math::interval<double>::get_epsilon() == std::numeric_limits<double>::epsilon());\n}\n\nBOOST_AUTO_TEST_CASE(interval_overlap) {\n  math::interval<int> iv1(1, 3), iv2(2, 5), iv3(3, 5), iv4(4, 5), iv5(5, 5), iv6(1, 5), iv7(0, 5);\n\n  BOOST_CHECK(iv1.is_continuous(iv2) == true);\n  BOOST_CHECK(iv2.is_continuous(iv1) == false);\n  BOOST_CHECK(iv1.overlaps(iv2) == true);\n  BOOST_CHECK(iv2.overlaps(iv1) == true);\n\n  BOOST_CHECK(iv1.is_continuous(iv3) == true);\n  BOOST_CHECK(iv3.is_continuous(iv1) == false);\n  BOOST_CHECK(iv1.overlaps(iv3) == true);\n  BOOST_CHECK(iv3.overlaps(iv1) == true);\n\n  BOOST_CHECK(iv1.is_continuous(iv4) == true);\n  BOOST_CHECK(iv4.is_continuous(iv1) == false);\n  BOOST_CHECK(iv1.overlaps(iv4) == false);\n  BOOST_CHECK(iv4.overlaps(iv1) == false);\n\n  BOOST_CHECK(iv1.is_continuous(iv5) == false);\n  BOOST_CHECK(iv5.is_continuous(iv1) == false);\n  BOOST_CHECK(iv1.overlaps(iv5) == false);\n  BOOST_CHECK(iv5.overlaps(iv1) == false);\n\n  BOOST_CHECK(iv1.is_continuous(iv6) == false);\n  BOOST_CHECK(iv6.is_continuous(iv1) == false);\n  BOOST_CHECK(iv1.overlaps(iv6) == true);\n  BOOST_CHECK(iv6.overlaps(iv1) == true);\n\n  BOOST_CHECK(iv1.is_continuous(iv7) == false);\n  BOOST_CHECK(iv7.is_continuous(iv1) == false);\n  BOOST_CHECK(iv1.overlaps(iv7) == true);\n  BOOST_CHECK(iv7.overlaps(iv1) == true);\n\n  math::interval<int> iv8(-1, 2), iv9(-1, 1), iv10(-1, 0), iv11(-1, -1), iv12(-1, 3);\n\n  BOOST_CHECK(iv8.is_continuous(iv1) == true);\n  BOOST_CHECK(iv1.is_continuous(iv8) == false);\n  BOOST_CHECK(iv1.overlaps(iv8) == true);\n  BOOST_CHECK(iv8.overlaps(iv1) == true);\n\n  BOOST_CHECK(iv9.is_continuous(iv1) == true);\n  BOOST_CHECK(iv1.is_continuous(iv9) == false);\n  BOOST_CHECK(iv1.overlaps(iv9) == true);\n  BOOST_CHECK(iv9.overlaps(iv1) == true);\n\n  BOOST_CHECK(iv10.is_continuous(iv1) == true);\n  BOOST_CHECK(iv1.is_continuous(iv10) == false);\n  BOOST_CHECK(iv1.overlaps(iv10) == false);\n  BOOST_CHECK(iv10.overlaps(iv1) == false);\n\n  BOOST_CHECK(iv11.is_continuous(iv1) == false);\n  BOOST_CHECK(iv1.is_continuous(iv11) == false);\n  BOOST_CHECK(iv1.overlaps(iv11) == false);\n  BOOST_CHECK(iv11.overlaps(iv1) == false);\n\n  BOOST_CHECK(iv12.is_continuous(iv1) == false);\n  BOOST_CHECK(iv1.is_continuous(iv12) == false);\n  BOOST_CHECK(iv1.overlaps(iv12) == true);\n  BOOST_CHECK(iv12.overlaps(iv1) == true);\n}\n\nBOOST_AUTO_TEST_CASE(interval_less_min_max) {\n  math::interval<int> iv1(1, 3), iv2(1, 4), iv3(2, 3);\n\n  BOOST_CHECK(less_min_max(iv1, iv1) == false);\n\n  BOOST_CHECK(less_min_max(iv1, iv2) == true);\n  BOOST_CHECK(less_min_max(iv2, iv1) == false);\n\n  BOOST_CHECK(less_min_max(iv1, iv3) == true);\n  BOOST_CHECK(less_min_max(iv3, iv1) == false);\n}\n\nBOOST_AUTO_TEST_CASE(interval_less_length) {\n  math::interval<int> iv1(1, 3), iv2(1, 4), iv3(2, 4);\n\n  BOOST_CHECK(less_length(iv1, iv1) == false);\n\n  BOOST_CHECK(less_length(iv1, iv2) == true);\n  BOOST_CHECK(less_length(iv2, iv1) == false);\n\n  BOOST_CHECK(less_length(iv1, iv3) == false);\n  BOOST_CHECK(less_length(iv3, iv1) == false);\n}\n\nBOOST_AUTO_TEST_CASE(interval_less_max) {\n  math::interval<int> iv1(1, 3), iv2(1, 4), iv3(2, 4);\n\n  BOOST_CHECK(less_max(iv1, iv1) == false);\n\n  BOOST_CHECK(less_max(iv1, iv2) == true);\n  BOOST_CHECK(less_max(iv2, iv1) == false);\n\n  BOOST_CHECK(less_max(iv2, iv3) == false);\n  BOOST_CHECK(less_max(iv3, iv2) == false);\n}\n\nBOOST_AUTO_TEST_CASE(interval_equal_min_max) {\n  math::interval<int> iv1(1, 3), iv2(1, 4), iv3(2, 4);\n  BOOST_CHECK(equal_min_max(iv1, iv1));\n  BOOST_CHECK(equal_min_max(iv1, iv2) == false);\n  BOOST_CHECK(equal_min_max(iv1, iv3) == false);\n}\n\nBOOST_AUTO_TEST_CASE(interval_equal_length) {\n  math::interval<int> iv1(1, 3), iv2(1, 4), iv3(2, 4);\n  BOOST_CHECK(equal_length(iv1, iv1));\n  BOOST_CHECK(equal_length(iv1, iv2) == false);\n  BOOST_CHECK(equal_length(iv1, iv3));\n}\n\nBOOST_AUTO_TEST_CASE(interval_merge) {\n  math::interval<int> iv1(5, 6), iv2(4, 7), iv3(4, 4), iv4(3, 3), iv5(6, 7), iv6(7, 7), iv7(8, 8);\n  BOOST_CHECK(math::interval<int>::merge(iv1, iv2).size() == 1);\n  BOOST_CHECK(math::interval<int>::merge(iv1, iv3).size() == 1);\n  BOOST_CHECK(math::interval<int>::merge(iv1, iv4).empty());\n  BOOST_CHECK(math::interval<int>::merge(iv1, iv5).size() == 1);\n  BOOST_CHECK(math::interval<int>::merge(iv1, iv6).size() == 1);\n  BOOST_CHECK(math::interval<int>::merge(iv1, iv7).empty());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6e6d2b3e789afa4f688d1a2d6776ed31ff18a7ec", "size": 5888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/interval.cpp", "max_stars_repo_name": "shze/biosim", "max_stars_repo_head_hexsha": "e9e6d97de0ccf8067e1db15980eb600389fff6ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/interval.cpp", "max_issues_repo_name": "shze/biosim", "max_issues_repo_head_hexsha": "e9e6d97de0ccf8067e1db15980eb600389fff6ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/interval.cpp", "max_forks_repo_name": "shze/biosim", "max_forks_repo_head_hexsha": "e9e6d97de0ccf8067e1db15980eb600389fff6ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5303867403, "max_line_length": 98, "alphanum_fraction": 0.6829144022, "num_tokens": 1862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6154669715077249}}
{"text": "// Copyright Paul A. Bristow 2015\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Comparison of finding roots using TOMS748, Newton-Raphson, Halley & Schroder algorithms.\n// root_n_finding_algorithms.cpp  Generalised for nth root version.\n\n// http://en.wikipedia.org/wiki/Cube_root\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// This program also writes files in Quickbook tables mark-up format.\n\n#include <boost/cstdlib.hpp>\n#include <boost/config.hpp>\n#include <boost/array.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/math/tools/roots.hpp>\n\n//using boost::math::policies::policy;\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//using boost::math::tools::halley_iterate; \n//using boost::math::tools::newton_raphson_iterate;\n//using boost::math::tools::schroder_iterate;\n\n#include <boost/math/special_functions/next.hpp> // For float_distance.\n#include <boost/math/special_functions/pow.hpp> // For pow<N>.\n#include <boost/math/tools/tuple.hpp> // for tuple and make_tuple.\n\n#include <boost/multiprecision/cpp_bin_float.hpp> // is binary.\nusing boost::multiprecision::cpp_bin_float_100;\nusing boost::multiprecision::cpp_bin_float_50;\n\n#include <boost/timer/timer.hpp>\n#include <boost/system/error_code.hpp>\n#include <boost/preprocessor/stringize.hpp>\n\n// STL\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <vector>\n#include <limits>\n#include <fstream> // std::ofstream\n#include <cmath>\n#include <typeinfo> // for type name using typid(thingy).name();\n\n#ifdef __FILE__\n  std::string sourcefilename = __FILE__;\n#else\n  std::string sourcefilename(\"\");\n#endif\n\n  std::string chop_last(std::string s)\n  {\n     std::string::size_type pos = s.find_last_of(\"\\\\/\");\n     if(pos != std::string::npos)\n        s.erase(pos);\n     else if(s.empty())\n        abort();\n     else\n        s.erase();\n     return s;\n  }\n\n  std::string make_root()\n  {\n     std::string result;\n     if(sourcefilename.find_first_of(\":\") != std::string::npos)\n     {\n        result = chop_last(sourcefilename); // lose filename part\n        result = chop_last(result);   // lose /example/\n        result = chop_last(result);   // lose /math/\n        result = chop_last(result);   // lose /libs/\n     }\n     else\n     {\n        result = chop_last(sourcefilename); // lose filename part\n        if(result.empty())\n           result = \".\";\n        result += \"/../../..\";\n     }\n     return result;\n  }\n\n  std::string short_file_name(std::string s)\n  {\n     std::string::size_type pos = s.find_last_of(\"\\\\/\");\n     if(pos != std::string::npos)\n        s.erase(0, pos + 1);\n     return s;\n  }\n\n  std::string boost_root = make_root();\n\n\nstd::string fp_hardware; // Any hardware features like SEE or AVX\n\nconst std::string roots_name = \"libs/math/doc/roots/\";\n\nconst std::string full_roots_name(boost_root + \"/libs/math/doc/roots/\");\n\nconst std::size_t nooftypes = 4;\nconst std::size_t noofalgos = 4;\n\ndouble digits_accuracy = 1.0; // 1 == maximum possible accuracy.\n\nstd::stringstream ss;\n\nstd::ofstream fout;\n\nstd::vector<std::string> algo_names =\n{\n  \"TOMS748\", \"Newton\", \"Halley\", \"Schr'''&#xf6;'''der\"\n};\n\nstd::vector<std::string> names =\n{\n  \"float\", \"double\", \"long double\", \"cpp_bin_float50\"\n};\n\nuintmax_t iters; // Global as value of iterations is not returned.\n\nstruct root_info\n{ // for a floating-point type, float, double ...\n  std::size_t max_digits10; // for type.\n  std::string full_typename; // for type from type_id.name().\n  std::string short_typename; // for type \"float\", \"double\", \"cpp_bin_float_50\" ....\n  std::size_t bin_digits;  // binary in floating-point type numeric_limits<T>::digits;  \n  int get_digits; // fraction of maximum possible accuracy required.\n  // = digits * digits_accuracy\n  // Vector of values (4) for each algorithm, TOMS748, Newton, Halley & Schroder.\n  //std::vector< boost::int_least64_t> times;  converted to int.\n  std::vector<int> times; // arbitrary units (ticks).\n  //boost::int_least64_t min_time = std::numeric_limits<boost::int_least64_t>::max(); // Used to normalize times (as int).\n  std::vector<double> normed_times;\n  int min_time = (std::numeric_limits<int>::max)(); // Used to normalize times.\n  std::vector<uintmax_t> iterations;\n  std::vector<long int> distances;\n  std::vector<cpp_bin_float_100> full_results;\n}; // struct root_info\n\nstd::vector<root_info> root_infos;  // One element for each floating-point type used.\n\ninline std::string build_test_name(const char* type_name, const char* test_name)\n{\n  std::string result(BOOST_COMPILER);\n  result += \"|\";\n  result += BOOST_STDLIB;\n  result += \"|\";\n  result += BOOST_PLATFORM;\n  result += \"|\";\n  result += type_name;\n  result += \"|\";\n  result += test_name;\n#if defined(_DEBUG) || !defined(NDEBUG)\n  result += \"|\";\n  result += \" debug\";\n#else\n  result += \"|\";\n  result += \" release\";\n#endif\n  result += \"|\";\n  return result;\n} // std::string build_test_name\n\n// Algorithms //////////////////////////////////////////////\n\n// No derivatives - using TOMS748 internally.\n\ntemplate <int N, typename T = double>\nstruct nth_root_functor_noderiv\n{ //  Nth root of x using only function - no derivatives.\n  nth_root_functor_noderiv(T const& to_find_root_of) : a(to_find_root_of)\n  { // Constructor just stores value a to find root of.\n  }\n  T operator()(T const& x)\n  {\n    using boost::math::pow;\n    T fx = pow<N>(x) -a; // Difference (estimate x^n - a).\n    return fx;\n  }\nprivate:\n  T a; // to be 'cube_rooted'.\n}; // template <int N, class T> struct nth_root_functor_noderiv\n\ntemplate <int N, class T = double>\nT nth_root_noderiv(T x)\n{ // return Nth root of x using bracket_and_solve (using NO derivatives).\n  using namespace std;  // Help ADL of std functions.\n  using namespace boost::math::tools; // For bracket_and_solve_root.\n\n  typedef double guess_type;\n\n  int exponent;\n  frexp(static_cast<guess_type>(x), &exponent); // Get exponent of z (ignore mantissa).\n  T guess = static_cast<T>(ldexp(static_cast<guess_type>(1.), exponent / N)); // Rough guess is to divide the exponent by n.\n  //T min = static_cast<T>(ldexp(static_cast<guess_type>(1.) / 2, exponent / N)); // Minimum possible value is half our guess.\n  //T max = static_cast<T>(ldexp(static_cast<guess_type>(2.), exponent / N)); // Maximum possible value is twice our guess.\n\n  T factor = 2; // How big steps to take when searching.\n\n  const boost::uintmax_t maxit = 50; // Limit to maximum iterations.\n  boost::uintmax_t it = maxit; // Initially our chosen max iterations, but updated with actual.\n  bool is_rising = true; // So if result if guess^3 is too low, then try increasing guess.\n  // Some fraction of digits is used to control how accurate to try to make the result.\n  int get_digits = std::numeric_limits<T>::digits - 2;\n  eps_tolerance<T> tol(get_digits); // Set the tolerance.\n  std::pair<T, T> r;\n  r =  bracket_and_solve_root(nth_root_functor_noderiv<N, T>(x), guess, factor, is_rising, tol, it);\n  iters = it;\n  T result = r.first + (r.second - r.first) / 2;  // Midway between brackets.\n  return result;\n} // template <class T> T nth_root_noderiv(T x)\n\n// Using 1st derivative only Newton-Raphson\n\ntemplate <int N, class T = double>\nstruct nth_root_functor_1deriv\n{ // Functor also returning 1st derivative.\n  BOOST_STATIC_ASSERT_MSG(boost::is_integral<T>::value == false, \"Only floating-point type types can be used!\");\n  BOOST_STATIC_ASSERT_MSG((N > 0) == true, \"root N must be > 0!\");\n\n  nth_root_functor_1deriv(T const& to_find_root_of) : a(to_find_root_of)\n  { // Constructor stores value a to find root of, for example:\n  }\n  std::pair<T, T> operator()(T const& x)\n  { // Return both f(x) and f'(x).\n    using boost::math::pow; // // Compile-time integral power.\n    T p = pow<N - 1>(x);\n    return std::make_pair(p * x - a, N * p); // 'return' both fx and dx.\n  }\n\nprivate:\n  T a; // to be 'nth_rooted'.\n}; // struct nthroot__functor_1deriv\n\ntemplate <int N, class T = double>\nT nth_root_1deriv(T x)\n{ // return nth root of x using 1st derivative and Newton_Raphson.\n  using namespace std;  // Help ADL of std functions.\n  using namespace boost::math::tools; // For newton_raphson_iterate.\n\n  BOOST_STATIC_ASSERT_MSG(boost::is_integral<T>::value == false, \"Only floating-point type types can be used!\");\n  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;\n\n  int exponent;\n  frexp(static_cast<guess_type>(x), &exponent); // Get exponent of z (ignore mantissa).\n  T guess = static_cast<T>(ldexp(static_cast<guess_type>(1.), exponent / N)); // Rough guess is to divide the exponent by n.\n  T min = static_cast<T>(ldexp(static_cast<guess_type>(1.) / 2, exponent / N)); // Minimum possible value is half our guess.\n  T max = static_cast<T>(ldexp(static_cast<guess_type>(2.), exponent / N)); // Maximum possible value is twice our guess.\n\n  int digits = std::numeric_limits<T>::digits; // Maximum possible binary digits accuracy for type T.\n  int get_digits = static_cast<int>(digits * 0.6);\n  const boost::uintmax_t maxit = 20;\n  boost::uintmax_t it = maxit;\n  T result = newton_raphson_iterate(nth_root_functor_1deriv<N, T>(x), guess, min, max, get_digits, it);\n  iters = it;\n  return result;\n} // T nth_root_1_deriv  Newton-Raphson\n\n// Using 1st and 2nd derivatives with Halley algorithm.\n\ntemplate <int N, class T = double>\nstruct nth_root_functor_2deriv\n{ // Functor returning both 1st and 2nd derivatives.\n  BOOST_STATIC_ASSERT_MSG(boost::is_integral<T>::value == false, \"Only floating-point type types can be used!\");\n  BOOST_STATIC_ASSERT_MSG((N > 0) == true, \"root N must be > 0!\");\n\n  nth_root_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\n  // using boost::math::tuple; // to return three values.\n  std::tuple<T, T, T> operator()(T const& x)\n  { // Return f(x), f'(x) and f''(x).\n    using boost::math::pow; // Compile-time integral power.\n    T p = pow<N - 2>(x);\n\n    return std::make_tuple(p * x * x - a, p * x * N, p * N * (N - 1)); // 'return' fx, dx and d2x.\n  }\nprivate:\n  T a; // to be 'nth_rooted'.\n};\n\ntemplate <int N, class T = double>\nT nth_root_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<T>::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;\n\n  int exponent;\n  frexp(static_cast<guess_type>(x), &exponent); // Get exponent of z (ignore mantissa).\n  T guess = static_cast<T>(ldexp(static_cast<guess_type>(1.), exponent / N)); // Rough guess is to divide the exponent by n.\n  T min = static_cast<T>(ldexp(static_cast<guess_type>(1.) / 2, exponent / N)); // Minimum possible value is half our guess.\n  T max = static_cast<T>(ldexp(static_cast<guess_type>(2.), exponent / N)); // Maximum possible value is twice our guess.\n\n  int digits = std::numeric_limits<T>::digits; // Maximum possible binary digits accuracy for type T.\n  int get_digits = static_cast<int>(digits * 0.4);\n  const boost::uintmax_t maxit = 20;\n  boost::uintmax_t it = maxit;\n  T result = halley_iterate(nth_root_functor_2deriv<N, T>(x), guess, min, max, get_digits, it);\n  iters = it;\n\n  return result;\n} // nth_2deriv Halley\n\ntemplate <int N, class T = double>\nT nth_root_2deriv_s(T x)\n{ // return nth root of x using 1st and 2nd derivatives and Schroder.\n\n  using namespace std;  // Help ADL of std functions.\n  using namespace boost::math::tools; // For schroder_iterate.\n\n  BOOST_STATIC_ASSERT_MSG(boost::is_integral<T>::value == false, \"Only floating-point type types can be used!\");\n  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;\n\n  int exponent;\n  frexp(static_cast<guess_type>(x), &exponent); // Get exponent of z (ignore mantissa).\n  T guess = static_cast<T>(ldexp(static_cast<guess_type>(1.), exponent / N)); // Rough guess is to divide the exponent by n.\n  T min = static_cast<T>(ldexp(static_cast<guess_type>(1.) / 2, exponent / N)); // Minimum possible value is half our guess.\n  T max = static_cast<T>(ldexp(static_cast<guess_type>(2.), exponent / N)); // Maximum possible value is twice our guess.\n\n  int get_digits = static_cast<int>(std::numeric_limits<T>::digits * 0.4);\n  const boost::uintmax_t maxit = 20;\n  boost::uintmax_t it = maxit;\n  T result = schroder_iterate(nth_root_functor_2deriv<N, T>(x), guess, min, max, get_digits, it);\n  iters = it;\n\n  return result;\n} // T nth_root_2deriv_s Schroder\n\n//////////////////////////////////////////////////////// end of algorithms - perhaps in a separate .hpp?\n\n//! Print 4 floating-point types info: max_digits10, digits and required accuracy digits as a Quickbook table.\nint table_type_info(double digits_accuracy)\n{\n  std::string qbk_name = full_roots_name; // Prefix by boost_root file.\n\n  qbk_name += \"type_info_table\";\n  std::stringstream ss;\n  ss.precision(3);\n  ss << \"_\" << digits_accuracy * 100;\n  qbk_name += ss.str();\n\n#ifdef _MSC_VER\n  qbk_name += \"_msvc.qbk\";\n#else // assume GCC\n  qbk_name += \"_gcc.qbk\";\n#endif\n\n  // Example: type_info_table_100_msvc.qbk\n  fout.open(qbk_name, std::ios_base::out);\n\n  if (fout.is_open())\n  {\n    std::cout << \"Output type table to \" << qbk_name << std::endl;\n  }\n  else\n  { // Failed to open.\n    std::cout << \" Open file \" << qbk_name << \" for output failed!\" << std::endl;\n    std::cout << \"errno \" << errno << std::endl;\n    return errno;\n  }\n\n  fout <<\n    \"[/\"\n    << qbk_name\n    << \"\\n\"\n    \"Copyright 2015 Paul A. Bristow.\"\"\\n\"\n    \"Copyright 2015 John Maddock.\"\"\\n\"\n    \"Distributed under the Boost Software License, Version 1.0.\"\"\\n\"\n    \"(See accompanying file LICENSE_1_0.txt or copy at\"\"\\n\"\n    \"http://www.boost.org/LICENSE_1_0.txt).\"\"\\n\"\n    \"]\"\"\\n\"\n    << std::endl;\n\n  fout << \"[h6 Fraction of maximum possible bits of accuracy required is \" << digits_accuracy << \".]\\n\" << std::endl;\n\n  std::string table_id(\"type_info\");\n  table_id += ss.str(); // Fraction digits accuracy.\n\n#ifdef _MSC_VER\n  table_id += \"_msvc\";\n#else // assume GCC\n  table_id += \"_gcc\";\n#endif\n\n  fout << \"[table:\" << table_id << \" Digits for float, double, long double and cpp_bin_float_50\\n\"\n    << \"[[type name] [max_digits10] [binary digits] [required digits]]\\n\";// header.\n\n  // For all fout types:\n\n  fout  << \"[[\" << \"float\" << \"]\"\n    << \"[\" << std::numeric_limits<float>::max_digits10 << \"]\"  // max_digits10\n    << \"[\" << std::numeric_limits<float>::digits << \"]\"// < \"Binary digits \n    << \"[\" << static_cast<int>(std::numeric_limits<float>::digits * digits_accuracy) << \"]]\\n\"; // Accuracy digits.\n\n  fout << \"[[\" << \"float\" << \"]\"\n    << \"[\" << std::numeric_limits<double>::max_digits10 << \"]\"  // max_digits10\n    << \"[\" << std::numeric_limits<double>::digits << \"]\"// < \"Binary digits \n    << \"[\" << static_cast<int>(std::numeric_limits<double>::digits * digits_accuracy) << \"]]\\n\"; // Accuracy digits.\n\n  fout << \"[[\" << \"long double\" << \"]\"\n    << \"[\" << std::numeric_limits<long double>::max_digits10 << \"]\"  // max_digits10\n    << \"[\" << std::numeric_limits<long double>::digits << \"]\"// < \"Binary digits \n    << \"[\" << static_cast<int>(std::numeric_limits<long double>::digits * digits_accuracy) << \"]]\\n\"; // Accuracy digits.\n\n  fout << \"[[\" << \"cpp_bin_float_50\" << \"]\"\n    << \"[\" << std::numeric_limits<cpp_bin_float_50>::max_digits10 << \"]\"  // max_digits10\n    << \"[\" << std::numeric_limits<cpp_bin_float_50>::digits << \"]\"// < \"Binary digits \n    << \"[\" << static_cast<int>(std::numeric_limits<cpp_bin_float_50>::digits * digits_accuracy) << \"]]\\n\"; // Accuracy digits.\n\n  fout << \"] [/table table_id_msvc] \\n\" << std::endl; // End of table.\n\n  fout.close();\n  return 0;\n} // type_table\n\n//! Evaluate root N timing for each algorithm, and for one floating-point type T. \ntemplate <int N, typename T>\nint test_root(cpp_bin_float_100 big_value, cpp_bin_float_100 answer, const char* type_name, std::size_t type_no)\n{\n  std::size_t max_digits = 2 + std::numeric_limits<T>::digits * 3010 / 10000;\n  // For new versions use max_digits10\n  // std::cout.precision(std::numeric_limits<T>::max_digits10);\n  std::cout.precision(max_digits);\n  std::cout << std::showpoint << std::endl; // Show trailing zeros too.\n\n  root_infos.push_back(root_info()); \n\n  root_infos[type_no].max_digits10 = max_digits;\n  root_infos[type_no].full_typename = typeid(T).name(); // Full typename.\n  root_infos[type_no].short_typename = type_name; // Short typename.\n  root_infos[type_no].bin_digits = std::numeric_limits<T>::digits;\n  root_infos[type_no].get_digits = static_cast<int>(std::numeric_limits<T>::digits * digits_accuracy);\n\n  T to_root = static_cast<T>(big_value);\n\n  T result; // root\n  T sum = 0;\n  T ans = static_cast<T>(answer);\n\n  using boost::timer::nanosecond_type;\n  using boost::timer::cpu_times;\n  using boost::timer::cpu_timer;\n\n  int eval_count = boost::is_floating_point<T>::value ? 10000000 : 100000; // To give a sufficiently stable timing for the fast built-in types,\n  //int eval_count = 1000000; // To give a sufficiently stable timing for the fast built-in types,\n  // This takes an inconveniently long time for multiprecision cpp_bin_float_50 etc  types.\n\n  cpu_times now; // Holds wall, user and system times.\n\n  { // Evaluate times etc for each algorithm.\n    //algorithm_names.push_back(\"TOMS748\"); // \n    cpu_timer ti; // Can start, pause, resume and stop, and read elapsed.\n    ti.start();\n    for (long i = 0; i < eval_count; ++i)\n    {\n      result = nth_root_noderiv<N, T>(to_root); // \n      sum += result;\n    }\n    now = ti.elapsed();\n    int time = static_cast<int>(now.user / eval_count);\n    root_infos[type_no].times.push_back(time); // CPU time taken.\n    if (time < root_infos[type_no].min_time)\n    {\n      root_infos[type_no].min_time = time;\n    }\n    ti.stop();\n    long int distance = static_cast<int>(boost::math::float_distance<T>(result, ans));\n    root_infos[type_no].distances.push_back(distance);\n    root_infos[type_no].iterations.push_back(iters); // \n    root_infos[type_no].full_results.push_back(result);\n  }\n  {\n    // algorithm_names.push_back(\"Newton\"); // algorithm\n    cpu_timer ti; // Can start, pause, resume and stop, and read elapsed.\n    ti.start();\n    for (long i = 0; i < eval_count; ++i)\n    {\n      result = nth_root_1deriv<N, T>(to_root); // \n      sum += result;\n    }\n    now = ti.elapsed();\n    int time = static_cast<int>(now.user / eval_count);\n    root_infos[type_no].times.push_back(time); // CPU time taken.\n    if (time < root_infos[type_no].min_time)\n    {\n      root_infos[type_no].min_time = time;\n    }\n\n    ti.stop();\n    long int distance = static_cast<int>(boost::math::float_distance<T>(result, ans));\n    root_infos[type_no].distances.push_back(distance);\n    root_infos[type_no].iterations.push_back(iters); //\n    root_infos[type_no].full_results.push_back(result);\n  }\n  {\n    //algorithm_names.push_back(\"Halley\"); // algorithm\n    cpu_timer ti; // Can start, pause, resume and stop, and read elapsed.\n    ti.start();\n    for (long i = 0; i < eval_count; ++i)\n    {\n      result = nth_root_2deriv<N>(to_root); // \n      sum += result;\n    }\n    now = ti.elapsed();\n    int time = static_cast<int>(now.user / eval_count);\n    root_infos[type_no].times.push_back(time); // CPU time taken.\n    ti.stop();\n    if (time < root_infos[type_no].min_time)\n    {\n      root_infos[type_no].min_time = time;\n    }\n    long int distance = static_cast<int>(boost::math::float_distance<T>(result, ans));\n    root_infos[type_no].distances.push_back(distance);\n    root_infos[type_no].iterations.push_back(iters); // \n    root_infos[type_no].full_results.push_back(result);\n  }\n  {\n    // algorithm_names.push_back(\"Schroder\"); // algorithm\n    cpu_timer ti; // Can start, pause, resume and stop, and read elapsed.\n    ti.start();\n    for (long i = 0; i < eval_count; ++i)\n    {\n      result = nth_root_2deriv_s<N>(to_root); // \n      sum += result;\n    }\n    now = ti.elapsed();\n    int time = static_cast<int>(now.user / eval_count);\n    root_infos[type_no].times.push_back(time); // CPU time taken.\n    if (time < root_infos[type_no].min_time)\n    {\n      root_infos[type_no].min_time = time;\n    }\n    ti.stop();\n    long int distance = static_cast<int>(boost::math::float_distance<T>(result, ans));\n    root_infos[type_no].distances.push_back(distance);\n    root_infos[type_no].iterations.push_back(iters); // \n    root_infos[type_no].full_results.push_back(result);\n  }\n  for (size_t i = 0; i != root_infos[type_no].times.size(); i++) // For each time.\n  { // Normalize times.\n    root_infos[type_no].normed_times.push_back(static_cast<double>(root_infos[type_no].times[i]) / root_infos[type_no].min_time);\n  }\n\n  std::cout << \"Accumulated result was: \" << sum << std::endl;\n\n  return 4;  // eval_count of how many algorithms used.\n} // test_root\n\n/*! Fill array of times, iterations, etc for Nth root for all 4 types,\n and write a table of results in Quickbook format.\n */\ntemplate <int N>\nvoid table_root_info(cpp_bin_float_100 full_value)\n{\n   using std::abs;\n  std::cout << nooftypes << \" floating-point types tested:\" << std::endl;\n#if defined(_DEBUG) || !defined(NDEBUG)\n  std::cout << \"Compiled in debug mode.\" << std::endl;\n#else\n  std::cout << \"Compiled in optimise mode.\" << std::endl;\n#endif\n  std::cout << \"FP hardware \" << fp_hardware << std::endl;\n  // Compute the 'right' answer for root N at 100 decimal digits.\n  cpp_bin_float_100 full_answer = nth_root_noderiv<N, cpp_bin_float_100>(full_value);\n\n  root_infos.clear(); // Erase any previous data.\n  // Fill the elements of the array for each floating-point type.\n\n  test_root<N, float>(full_value, full_answer, \"float\", 0);\n  test_root<N, double>(full_value, full_answer, \"double\", 1);\n  test_root<N, long double>(full_value, full_answer, \"long double\", 2);\n  test_root<N, cpp_bin_float_50>(full_value, full_answer, \"cpp_bin_float_50\", 3);\n\n  // Use info from 4 floating point types to\n\n  // Prepare Quickbook table for a single root\n  // with columns of times, iterations, distances repeated for various floating-point types,\n  // and 4 rows for each algorithm.\n\n  std::stringstream table_info;\n  table_info.precision(3);\n  table_info << \"[table:root_\" << N << \" \" << N << \"th root(\" << static_cast<float>(full_value) << \") for float, double, long double and cpp_bin_float_50 types\";\n  if (fp_hardware != \"\")\n  {\n    table_info << \", using \" << fp_hardware;\n  }\n  table_info << std::endl;\n\n  fout << table_info.str()\n    << \"[[][float][][][] [][double][][][] [][long d][][][] [][cpp50][][]]\\n\"\n    << \"[[Algo     ]\";\n  for (size_t tp = 0; tp != nooftypes; tp++)\n  { // For all types:\n    fout << \"[Its]\" << \"[Times]\" << \"[Norm]\" << \"[Dis]\" << \"[ ]\";\n  }\n  fout << \"]\" << std::endl;\n\n  // Row for all algorithms.\n  for (std::size_t algo = 0; algo != noofalgos; algo++)\n  {\n    fout << \"[[\" << std::left << std::setw(9) << algo_names[algo] << \"]\";\n    for (size_t tp = 0; tp != nooftypes; tp++)\n    { // For all types:\n      fout\n        << \"[\" << std::right << std::showpoint\n        << std::setw(3) << std::setprecision(2) << root_infos[tp].iterations[algo] << \"][\"\n        << std::setw(5) << std::setprecision(5) << root_infos[tp].times[algo] << \"][\";\n      fout << std::setw(3) << std::setprecision(3);\n        double normed_time = root_infos[tp].normed_times[algo];\n        if (abs(normed_time - 1.00) <= 0.05)\n        { // At or near the best time, so show as blue.\n          fout << \"[role blue \" << normed_time << \"]\";\n        }\n        else if (abs(normed_time) > 4.)\n        { // markedly poor so show as red.\n          fout << \"[role red \" << normed_time << \"]\";\n        }\n        else\n        { // Not the best, so normal black.\n          fout << normed_time;\n        }\n        fout << \"][\"\n        << std::setw(3) << std::setprecision(2) << root_infos[tp].distances[algo] << \"][ ]\";\n    } // tp\n    fout << \"]\" << std::endl;\n  } // for algo\n  fout << \"] [/end of table root]\\n\";\n} // void table_root_info\n\n/*! Output program header, table of type info, and tables for 4 algorithms and 4 floating-point types,\n for Nth root required digits_accuracy.\n */\n\nint roots_tables(cpp_bin_float_100 full_value, double digits_accuracy)\n{\n  ::digits_accuracy = digits_accuracy;\n  // Save globally so that it is available to root-finding algorithms. Ugly :-(\n\n#if defined(_DEBUG) || !defined(NDEBUG)\n  std::string debug_or_optimize(\"Compiled in debug mode.\");\n#else\n     std::string debug_or_optimize(\"Compiled in optimise mode.\");\n#endif\n\n  // Create filename for roots_table\n  std::string qbk_name = full_roots_name;\n  qbk_name += \"roots_table\";\n\n  std::stringstream ss;\n  ss.precision(3);\n  // ss << \"_\" << N // now put all the tables in one .qbk file?\n    ss << \"_\" << digits_accuracy * 100\n    << std::flush;\n  // Assume only save optimize mode runs, so don't add any  _DEBUG info.\n  qbk_name += ss.str();\n\n#ifdef _MSC_VER\n  qbk_name += \"_msvc\";\n#else // assume GCC\n  qbk_name += \"_gcc\";\n#endif \n  if (fp_hardware != \"\")\n  {\n    qbk_name += fp_hardware;\n  }\n  qbk_name += \".qbk\";\n\n  fout.open(qbk_name, std::ios_base::out);\n\n  if (fout.is_open())\n  {\n    std::cout << \"Output root table to \" << qbk_name << std::endl;\n  }\n  else\n  { // Failed to open.\n    std::cout << \" Open file \" << qbk_name << \" for output failed!\" << std::endl;\n    std::cout << \"errno \" << errno << std::endl;\n    return errno;\n  }\n\n  fout <<\n    \"[/\"\n    << qbk_name\n    << \"\\n\"\n    \"Copyright 2015 Paul A. Bristow.\"\"\\n\"\n    \"Copyright 2015 John Maddock.\"\"\\n\"\n    \"Distributed under the Boost Software License, Version 1.0.\"\"\\n\"\n    \"(See accompanying file LICENSE_1_0.txt or copy at\"\"\\n\"\n    \"http://www.boost.org/LICENSE_1_0.txt).\"\"\\n\"\n    \"]\"\"\\n\"\n    << std::endl;\n\n  // Print out the program/compiler/stdlib/platform names as a Quickbook comment:\n  fout << \"\\n[h6 Program \" << sourcefilename << \",\\n \"\n    << BOOST_COMPILER << \", \"\n    << BOOST_STDLIB << \", \"\n    << BOOST_PLATFORM << \"\\n\"\n    << debug_or_optimize \n    << ((fp_hardware != \"\") ? \", \" + fp_hardware : \"\")\n    << \"]\" // [h6 close].\n    << std::endl;\n\n  fout << \"Fraction of full accuracy \" << digits_accuracy << std::endl;\n\n  table_root_info<5>(full_value);\n  table_root_info<7>(full_value);\n  table_root_info<11>(full_value);\n\n  fout.close();\n\n  //   table_type_info(digits_accuracy);\n\n  return 0;\n} // roots_tables\n\n\nint main()\n{\n  using namespace boost::multiprecision;\n  using namespace boost::math;\n\n\n  try\n  {\n    std::cout << \"Tests run with \" << BOOST_COMPILER << \", \"\n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << \", \";\n\n// How to: Configure Visual C++ Projects to Target 64-Bit Platforms\n// https://msdn.microsoft.com/en-us/library/9yb4317s.aspx\n\n#ifdef _M_X64 // Defined for compilations that target x64 processors.\n    std::cout << \"X64 \" << std::endl;\n    fp_hardware += \"_X64\";\n#else\n#  ifdef _M_IX86\n     std::cout << \"X32 \" << std::endl;\n     fp_hardware += \"_X86\";\n#  endif\n#endif\n\n#ifdef _M_AMD64\n    std::cout << \"AMD64 \" << std::endl;\n //   fp_hardware += \"_AMD64\";\n#endif\n\n// https://msdn.microsoft.com/en-us/library/7t5yh4fd.aspx  \n// /arch (x86) options /arch:[IA32|SSE|SSE2|AVX|AVX2]\n// default is to use SSE and SSE2 instructions by default.\n// https://msdn.microsoft.com/en-us/library/jj620901.aspx\n// /arch (x64) options /arch:AVX and /arch:AVX2\n\n// MSVC doesn't bother to set these SSE macros!\n// http://stackoverflow.com/questions/18563978/sse-sse2-is-enabled-control-in-visual-studio\n// https://msdn.microsoft.com/en-us/library/b0084kay.aspx  predefined macros.\n\n// But some of these macros are *not* defined by MSVC, \n// unlike AVX (but *are* defined by GCC and Clang). \n// So the macro code above does define them.\n#if (defined(_M_AMD64) || defined (_M_X64))\n#ifndef _M_X64\n#  define _M_X64\n#endif\n#ifndef __SSE2__\n#  define __SSE2__\n#endif\n#else\n#  ifdef _M_IX86_FP // Expands to an integer literal value indicating which /arch compiler option was used:\n    std::cout << \"Floating-point _M_IX86_FP = \" << _M_IX86_FP << std::endl;\n#  if (_M_IX86_FP == 2) // 2 if /arch:SSE2, /arch:AVX or /arch:AVX2 \n#    define __SSE2__ // x32\n#  elif (_M_IX86_FP == 1) // 1 if /arch:SSE was used.\n#    define __SSE__ // x32\n#  elif (_M_IX86_FP == 0) // 0 if /arch:IA32 was used.\n#    define _X32 // No special FP instructions.\n#  endif\n# endif\n#endif\n// Set the fp_hardware that is used in the .qbk filename.\n#ifdef __AVX2__\n    std::cout << \"Floating-point AVX2 \" << std::endl;\n    fp_hardware += \"_AVX2\";\n#  else \n#    ifdef __AVX__\n    std::cout << \"Floating-point AVX \" << std::endl;\n    fp_hardware += \"_AVX\";\n#    else\n#      ifdef __SSE2__\n    std::cout << \"Floating-point SSE2 \" << std::endl;\n    fp_hardware += \"_SSE2\";\n#      else\n#        ifdef __SSE__\n    std::cout << \"Floating-point SSE \" << std::endl;\n    fp_hardware += \"_SSE\";\n#        endif\n#      endif\n#   endif\n# endif\n\n#ifdef _M_IX86\n    std::cout << \"Floating-point X86 _M_IX86 = \" << _M_IX86 << std::endl;\n    // https://msdn.microsoft.com/en-us/library/aa273918%28v=vs.60%29.aspx#_predir_table_1..3\n    // 600 = Pentium Pro\n#endif\n\n#ifdef _MSC_FULL_VER\n    std::cout << \"Floating-point _MSC_FULL_VER \" << _MSC_FULL_VER << std::endl;\n#endif\n\n#ifdef __MSVC_RUNTIME_CHECKS\n    std::cout << \"Runtime __MSVC_RUNTIME_CHECKS \" << std::endl;\n#endif\n\n    BOOST_MATH_CONTROL_FP;\n\n    cpp_bin_float_100 full_value(\"28.\");\n    // Compute full answer to more than precision of tests.\n    //T value = 28.; // integer (exactly representable as floating-point)\n    // whose cube root is *not* exactly representable.\n    // Wolfram Alpha command N[28 ^ (1 / 3), 100] computes cube root to 100 decimal digits.\n    // 3.036588971875662519420809578505669635581453977248111123242141654169177268411884961770250390838097895\n\n    std::cout.precision(100);\n    std::cout << \"value \" << full_value << std::endl;\n   // std::cout << \",\\n\"\"answer = \" << full_answer << std::endl;\n    std::cout.precision(6);\n   // cbrt cpp_bin_float_100 full_answer(\"3.036588971875662519420809578505669635581453977248111123242141654169177268411884961770250390838097895\");\n\n    // Output the table of types, maxdigits10 and digits and required digits for some accuracies.\n\n    // Output tables for some roots at full accuracy.\n    roots_tables(full_value, 1.);\n\n    // Output tables for some roots at less accuracy.\n    //roots_tables(full_value, 0.75);\n\n    return boost::exit_success;\n  }\n  catch (std::exception const& ex)\n  {\n    std::cout << \"exception thrown: \" << ex.what() << std::endl;\n    return boost::exit_failure;\n  }\n} // int main()\n\n/*\n\n*/\n", "meta": {"hexsha": "70f01792346fa3dd19be349cfc11303a701fa331", "size": 31233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/math/example/root_n_finding_algorithms.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-12T04:55:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T04:55:21.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/example/root_n_finding_algorithms.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/example/root_n_finding_algorithms.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 35.858783008, "max_line_length": 161, "alphanum_fraction": 0.65856626, "num_tokens": 8752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.8152324871074608, "lm_q1q2_score": 0.6154312312891381}}
{"text": "\r\n// g++ -I.. sparse_lu.cpp -O3 -g0 -I /usr/include/superlu/ -lsuperlu -lgfortran -DSIZE=1000 -DDENSITY=.05 && ./a.out\r\n\r\n#define EIGEN_SUPERLU_SUPPORT\r\n#define EIGEN_UMFPACK_SUPPORT\r\n#include <Eigen/Sparse>\r\n\r\n#define NOGMM\r\n#define NOMTL\r\n\r\n#ifndef SIZE\r\n#define SIZE 10\r\n#endif\r\n\r\n#ifndef DENSITY\r\n#define DENSITY 0.01\r\n#endif\r\n\r\n#ifndef REPEAT\r\n#define REPEAT 1\r\n#endif\r\n\r\n#include \"BenchSparseUtil.h\"\r\n\r\n#ifndef MINDENSITY\r\n#define MINDENSITY 0.0004\r\n#endif\r\n\r\n#ifndef NBTRIES\r\n#define NBTRIES 10\r\n#endif\r\n\r\n#define BENCH(X) \\\r\n  timer.reset(); \\\r\n  for (int _j=0; _j<NBTRIES; ++_j) { \\\r\n    timer.start(); \\\r\n    for (int _k=0; _k<REPEAT; ++_k) { \\\r\n        X  \\\r\n  } timer.stop(); }\r\n\r\ntypedef Matrix<Scalar,Dynamic,1> VectorX;\r\n\r\n#include <Eigen/LU>\r\n\r\ntemplate<int Backend>\r\nvoid doEigen(const char* name, const EigenSparseMatrix& sm1, const VectorX& b, VectorX& x, int flags = 0)\r\n{\r\n  std::cout << name << \"...\" << std::flush;\r\n  BenchTimer timer; timer.start();\r\n  SparseLU<EigenSparseMatrix,Backend> lu(sm1, flags);\r\n  timer.stop();\r\n  if (lu.succeeded())\r\n    std::cout << \":\\t\" << timer.value() << endl;\r\n  else\r\n  {\r\n    std::cout << \":\\t FAILED\" << endl;\r\n    return;\r\n  }\r\n\r\n  bool ok;\r\n  timer.reset(); timer.start();\r\n  ok = lu.solve(b,&x);\r\n  timer.stop();\r\n  if (ok)\r\n    std::cout << \"  solve:\\t\" << timer.value() << endl;\r\n  else\r\n    std::cout << \"  solve:\\t\" << \" FAILED\" << endl;\r\n\r\n  //std::cout << x.transpose() << \"\\n\";\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n  int rows = SIZE;\r\n  int cols = SIZE;\r\n  float density = DENSITY;\r\n  BenchTimer timer;\r\n\r\n  VectorX b = VectorX::Random(cols);\r\n  VectorX x = VectorX::Random(cols);\r\n\r\n  bool densedone = false;\r\n\r\n  //for (float density = DENSITY; density>=MINDENSITY; density*=0.5)\r\n//   float density = 0.5;\r\n  {\r\n    EigenSparseMatrix sm1(rows, cols);\r\n    fillMatrix(density, rows, cols, sm1);\r\n\r\n    // dense matrices\r\n    #ifdef DENSEMATRIX\r\n    if (!densedone)\r\n    {\r\n      densedone = true;\r\n      std::cout << \"Eigen Dense\\t\" << density*100 << \"%\\n\";\r\n      DenseMatrix m1(rows,cols);\r\n      eiToDense(sm1, m1);\r\n\r\n      BenchTimer timer;\r\n      timer.start();\r\n      FullPivLU<DenseMatrix> lu(m1);\r\n      timer.stop();\r\n      std::cout << \"Eigen/dense:\\t\" << timer.value() << endl;\r\n\r\n      timer.reset();\r\n      timer.start();\r\n      lu.solve(b,&x);\r\n      timer.stop();\r\n      std::cout << \"  solve:\\t\" << timer.value() << endl;\r\n//       std::cout << b.transpose() << \"\\n\";\r\n//       std::cout << x.transpose() << \"\\n\";\r\n    }\r\n    #endif\r\n\r\n    #ifdef EIGEN_UMFPACK_SUPPORT\r\n    x.setZero();\r\n    doEigen<Eigen::UmfPack>(\"Eigen/UmfPack (auto)\", sm1, b, x, 0);\r\n    #endif\r\n\r\n    #ifdef EIGEN_SUPERLU_SUPPORT\r\n    x.setZero();\r\n    doEigen<Eigen::SuperLU>(\"Eigen/SuperLU (nat)\", sm1, b, x, Eigen::NaturalOrdering);\r\n//     doEigen<Eigen::SuperLU>(\"Eigen/SuperLU (MD AT+A)\", sm1, b, x, Eigen::MinimumDegree_AT_PLUS_A);\r\n//     doEigen<Eigen::SuperLU>(\"Eigen/SuperLU (MD ATA)\", sm1, b, x, Eigen::MinimumDegree_ATA);\r\n    doEigen<Eigen::SuperLU>(\"Eigen/SuperLU (COLAMD)\", sm1, b, x, Eigen::ColApproxMinimumDegree);\r\n    #endif\r\n\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "24f88a304d23695c5075af60f475e17b4d883609", "size": 3143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/bench/sparse_lu.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/bench/sparse_lu.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/bench/sparse_lu.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": 23.6315789474, "max_line_length": 117, "alphanum_fraction": 0.5816099268, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301567, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6154312262758012}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Array<double,1,3> x(8,25,3),\n                  e(1./3.,0.5,2.);\ncout << \"[\" << x << \"]^[\" << e << \"] = \" << x.pow(e) << endl; // using ArrayBase::pow\ncout << \"[\" << x << \"]^[\" << e << \"] = \" << pow(x,e) << endl; // using Eigen::pow\n\n  return 0;\n}\n", "meta": {"hexsha": "9cb99f5838ac196617690c91458ca5378946f2d9", "size": 716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/snippets/compile_Cwise_array_power_array.cpp", "max_stars_repo_name": "mousepawmedia/libdeps", "max_stars_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-02-27T11:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T10:31:46.000Z", "max_issues_repo_path": "doc/snippets/compile_Cwise_array_power_array.cpp", "max_issues_repo_name": "mousepawmedia/libdeps", "max_issues_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-14T23:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-14T23:14:58.000Z", "max_forks_repo_path": "doc/snippets/compile_Cwise_array_power_array.cpp", "max_forks_repo_name": "mousepawmedia/libdeps", "max_forks_repo_head_hexsha": "b004d58d5b395ceaf9fdc993cfb00e91334a5d36", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-13T13:28:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T02:26:02.000Z", "avg_line_length": 28.64, "max_line_length": 224, "alphanum_fraction": 0.5824022346, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6154312082251381}}
{"text": "#include <opengv/optimization_tools/solver_tools/SolverTools.hpp>\n#include <opengv/optimization_tools/objective_function_tools/ObjectiveFunctionInfo.hpp>\n#include <Eigen/Dense>\n#include <opengv/types.hpp>\n\nclass SolverToolsNoncentralRelativePose : public SolverTools {\npublic:\n  Eigen::Matrix3d exp_R( Eigen::Matrix3d & X );\n\n  opengv::rotation_t rotation_solver(opengv::rotation_t & state_rotation, const opengv::translation_t & translation,\n                                     double &tol, ObjectiveFunctionInfo * info_function, int & k);\n\n  opengv::translation_t translation_solver(const opengv::rotation_t & rotation,\n                                           opengv::translation_t & translation, double &tol, ObjectiveFunctionInfo * info_function, double &step, int & k);\n\n};\n", "meta": {"hexsha": "3aeabbed072675e7210d95a526f08c036150b298", "size": 783, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/opengv/optimization_tools/solver_tools/SolverToolsNoncentralRelativePose.hpp", "max_stars_repo_name": "mateus03/2018AMMPoseSolver", "max_stars_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-05-15T12:41:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T10:42:52.000Z", "max_issues_repo_path": "include/opengv/optimization_tools/solver_tools/SolverToolsNoncentralRelativePose.hpp", "max_issues_repo_name": "mateus03/2018AMMPoseSolver", "max_issues_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/opengv/optimization_tools/solver_tools/SolverToolsNoncentralRelativePose.hpp", "max_forks_repo_name": "mateus03/2018AMMPoseSolver", "max_forks_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-27T18:11:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T18:11:14.000Z", "avg_line_length": 46.0588235294, "max_line_length": 155, "alphanum_fraction": 0.7190293742, "num_tokens": 175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6154238660666861}}
{"text": "#include <NTL/ZZ_pX.h>\n#include <NTL/ZZX.h>\n#include <NTL/BasicThreadPool.h>\n\nNTL_CLIENT\n\n\n#define ITER (500)\n\n\nvoid multest()\n{\n   cerr << \"mul\";\n   for (long iter = 0; iter < ITER; iter++) {\n      if (iter % 100 == 0) cerr << \".\";\n\n      long da = RandomBnd(5000) + 100;\n      long db = RandomBnd(5000) + 100;\n\n      ZZ_pX a, b, c1, c2;\n\n      random(a, da);\n      random(b, db);\n\n      if (deg(a) < 80 || deg(b) < 80) {\n         cerr << \"*\";\n         continue;\n      }\n\n      FFTMul(c1, a, b);\n\n      ZZX A, B, C;\n      conv(A, a);\n      conv(B, b);\n      mul(C, A, B);\n      conv(c2, C);\n\n      if (c1 != c2) {\n         cerr << \"******* oops\\n\";\n         break;\n      }\n   }\n\n   cerr << \"\\n\";\n}\n\n\nvoid sqrtest()\n{\n   cerr << \"sqr\";\n   for (long iter = 0; iter < ITER; iter++) {\n      if (iter % 100 == 0) cerr << \".\";\n\n      long da = RandomBnd(5000) + 100;\n      long db = RandomBnd(5000) + 100;\n\n      ZZ_pX a, b, c1, c2;\n\n      random(a, da);\n\n      if (deg(a) < 80) {\n         cerr << \"*\";\n         continue;\n      }\n\n      FFTSqr(c1, a);\n\n      ZZX A, B, C;\n      conv(A, a);\n      sqr(C, A);\n      conv(c2, C);\n\n      if (c1 != c2) {\n         cerr << \"******* oops\\n\";\n         break;\n      }\n   }\n\n   cerr << \"\\n\";\n}\n\n\n\n\nvoid mulmodtest()\n{\n   cerr << \"mulmod\";\n   for (long iter = 0; iter < ITER; iter++) {\n      if (iter % 100 == 0) cerr << \".\";\n\n      long n = RandomBnd(5000) + 300;\n      long da = RandomBnd(n)+1;\n      long db = RandomBnd(n)+1;\n\n      if (RandomBnd(2)) { da = n; db = n; }\n\n      ZZ_pX f;\n      random(f, n);\n      SetCoeff(f, n);\n      ZZ_pXModulus F(f);\n\n      ZZ_pX a, b, c1, c2;\n      random(a, da);\n      random(b, db);\n\n      MulMod(c1, a, b, F);\n\n      ZZX A, B, C;\n      conv(A, a);\n      conv(B, b);\n      mul(C, A, B);\n      conv(c2, C);\n      rem(c2, c2, F);\n\n      if (c1 != c2) {\n         cerr << \"******** oops\\n\";\n         break;\n      }\n   }\n\n   cerr << \"\\n\";\n}\n\n\nvoid sqrmodtest()\n{\n   cerr << \"sqrmod\";\n   for (long iter = 0; iter < ITER; iter++) {\n      if (iter % 100 == 0) cerr << \".\";\n\n      long n = RandomBnd(5000) + 300;\n      long da = RandomBnd(n)+1;\n      long db = RandomBnd(n)+1;\n\n      if (RandomBnd(2)) { da = n; db = n; }\n\n      ZZ_pX f;\n      random(f, n);\n      SetCoeff(f, n);\n      ZZ_pXModulus F(f);\n\n      ZZ_pX a, b, c1, c2;\n      random(a, da);\n      random(b, db);\n\n      SqrMod(c1, a, F);\n\n      ZZX A, B, C;\n      conv(A, a);\n      conv(B, b);\n      sqr(C, A);\n      conv(c2, C);\n      rem(c2, c2, F);\n\n      if (c1 != c2) {\n         cerr << \"******** oops\\n\";\n         break;\n      }\n   }\n\n   cerr << \"\\n\";\n}\n\n\n\nvoid mulmod1test()\n{\n   cerr << \"mulmod1\";\n   for (long iter = 0; iter < ITER; iter++) {\n      if (iter % 100 == 0) cerr << \".\";\n\n      long n = RandomBnd(5000) + 300;\n      long da = RandomBnd(n)+1;\n      long db = RandomBnd(n)+1;\n\n      if (RandomBnd(2)) { da = n; db = n; }\n\n      ZZ_pX f;\n      random(f, n);\n      SetCoeff(f, n);\n      ZZ_pXModulus F(f);\n\n      ZZ_pX a, b, c1, c2;\n      random(a, da);\n      random(b, db);\n\n      ZZ_pXMultiplier bb;\n      build(bb, b, F);\n\n      MulMod(c1, a, bb, F);\n\n      ZZX A, B, C;\n      conv(A, a);\n      conv(B, b);\n      mul(C, A, B);\n      conv(c2, C);\n      rem(c2, c2, F);\n\n      if (c1 != c2) {\n         cerr << \"******** oops\\n\";\n         break;\n      }\n   }\n\n   cerr << \"\\n\";\n}\n\n\nnamespace NTL {\n\nvoid CopyReverse(ZZ_pX& x, const ZZ_pX& a, long lo, long hi);\n\n}\n\n\n\nstruct ZZ_pXTransMultiplier {\n   ZZ_pX f0, fbi, b;\n   long shamt, shamt_fbi, shamt_b;\n};\n\n\n\n\nvoid build(ZZ_pXTransMultiplier& B, const ZZ_pX& b, const ZZ_pXModulus& F)\n{\n   long db = deg(b);\n\n   if (db >= F.n) LogicError(\"build TransMultiplier: bad args\");\n\n   ZZ_pX t;\n\n   LeftShift(t, b, F.n-1);\n   div(t, t, F);\n\n   // we optimize for low degree b\n\n   long d;\n\n   d = deg(t);\n   if (d < 0)\n      B.shamt_fbi = 0;\n   else\n      B.shamt_fbi = F.n-2 - d;\n\n   CopyReverse(B.fbi, t, 0, d);\n\n   // The following code optimizes the case when\n   // f = X^n + low degree poly\n\n   trunc(t, F.f, F.n);\n   d = deg(t);\n   if (d < 0)\n      B.shamt = 0;\n   else\n      B.shamt = d;\n\n   CopyReverse(B.f0, t, 0, d);\n\n   if (db < 0)\n      B.shamt_b = 0;\n   else\n      B.shamt_b = db;\n\n   CopyReverse(B.b, b, 0, db);\n}\n\n\n\nvoid TransMulMod(ZZ_pX& x, const ZZ_pX& a, const ZZ_pXTransMultiplier& B,\n               const ZZ_pXModulus& F)\n{\n   if (deg(a) >= F.n) LogicError(\"TransMulMod: bad args\");\n\n   ZZ_pX t1, t2;\n\n   mul(t1, a, B.b);\n   RightShift(t1, t1, B.shamt_b);\n\n   mul(t2, a, B.f0);\n   RightShift(t2, t2, B.shamt);\n   trunc(t2, t2, F.n-1);\n\n   mul(t2, t2, B.fbi);\n   if (B.shamt_fbi > 0) LeftShift(t2, t2, B.shamt_fbi);\n   trunc(t2, t2, F.n-1);\n   LeftShift(t2, t2, 1);\n\n   sub(x, t1, t2);\n}\n\n\n\nvoid UpdateMap(vec_ZZ_p& x, const vec_ZZ_p& a,\n         const ZZ_pXTransMultiplier& B, const ZZ_pXModulus& F)\n{\n   ZZ_pX xx;\n   TransMulMod(xx, to_ZZ_pX(a), B, F);\n   x = xx.rep;\n}\n\n\n\nvoid updatetest()\n{\n   cerr << \"update\";\n   for (long iter = 0; iter < ITER; iter++) {\n      if (iter % 100 == 0) cerr << \".\";\n\n      long n = RandomBnd(5000) + 300;\n      long da = RandomBnd(n)+1;\n      long db = RandomBnd(n)+1;\n\n      if (RandomBnd(2)) { da = n; db = n; }\n\n      ZZ_pX f;\n      random(f, n);\n      SetCoeff(f, n);\n      ZZ_pXModulus F(f);\n\n      ZZ_pX a, b;\n      random(a, da);\n      random(b, db);\n\n      ZZ_pXMultiplier bb1;\n      build(bb1, b, F);\n\n      ZZ_pXTransMultiplier bb2;\n      build(bb2, b, F);\n\n      Vec<ZZ_p> x1, x2;\n\n      UpdateMap(x1, a.rep, bb1, F);\n      UpdateMap(x2, a.rep, bb2, F);\n\n\n      if (x1 != x2) {\n         cerr << \"******** oops\\n\";\n         break;\n      }\n   }\n\n   cerr << \"\\n\";\n}\n\nvoid divremtest()\n{\n   cerr << \"divrem\";\n   for (long iter = 0; iter < ITER; iter++) {\n      if (iter % 100 == 0) cerr << \".\";\n\n      long n = RandomBnd(5000) + 300;\n      long dq = RandomBnd(n);\n\n\n      ZZ_pX f;\n      random(f, n);\n      SetCoeff(f, n);\n      ZZ_pXModulus F(f);\n\n      ZZ_pX a, q, r, q1, r1;\n\n      random(a, 2*n-1);\n\n      DivRem(q, r, a, F);\n      rem(r1, a, F);\n      div(q1, a, F);\n\n      if (deg(r) >= n || a != q*f + r || q != q1 || r != r1) {\n         cerr << \"******** oops\\n\";\n         break;\n      }\n   }\n\n   cerr << \"\\n\";\n}\n\n\nint main()\n{\n   ZZ p;\n   GenPrime(p, 100);\n\n   ZZ_p::init(p);\n\n   multest();\n   sqrtest();\n   mulmodtest();\n   sqrmodtest();\n   mulmod1test();\n   divremtest();\n   updatetest();\n\n#ifdef NTL_THREAD_BOOST\n\n   GenPrime(p, 500);\n   ZZ_p::init(p);\n\n   SetNumThreads(4);\n   cerr << \"numthreads=4\\n\";\n\n   multest();\n   sqrtest();\n   mulmodtest();\n   sqrmodtest();\n   mulmod1test();\n   divremtest();\n   updatetest();\n\n#endif\n\n}\n\n", "meta": {"hexsha": "4d9a5f0f655566bf87bf537d3ad59ff332b7f04a", "size": 6591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ZZ_pXTest.cpp", "max_stars_repo_name": "LittleNewton/Discrete_Logarithm", "max_stars_repo_head_hexsha": "28721af6db022e0e9f0b426fb3bf861d13de1592", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-16T13:49:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-16T13:49:01.000Z", "max_issues_repo_path": "tests/ZZ_pXTest.cpp", "max_issues_repo_name": "LittleNewton/Discrete_Logarithm", "max_issues_repo_head_hexsha": "28721af6db022e0e9f0b426fb3bf861d13de1592", "max_issues_repo_licenses": ["MIT"], "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/ZZ_pXTest.cpp", "max_forks_repo_name": "LittleNewton/Discrete_Logarithm", "max_forks_repo_head_hexsha": "28721af6db022e0e9f0b426fb3bf861d13de1592", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.9202898551, "max_line_length": 74, "alphanum_fraction": 0.4592626309, "num_tokens": 2366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256512199033, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6154238591024299}}
{"text": "#include <mpi.h> // has to be before plasma\n#ifdef USE_MKL\n#include <mkl.h>\n#include <mkl_cblas.h>\n#include <mkl_lapacke.h>\n#else\n#include <cblas.h>\n#include <lapacke.h>\n#endif\n#include <Eigen/Core> // after MKL\n#include <Eigen/Dense>\n#include <fstream>\n#include <array>\n#include <random>\n#include <mutex>\n#include <iostream>\n#include <map>\n#include <tuple>\n\n#include \"tasktorrent/tasktorrent.hpp\"\n#include \"util_shared.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace ttor;\n\n\nint VERB = 0;\nbool LOG = false;\nbool TEST = true;\nint n_threads_ = 2;\nint n_ = 2;\nint M_ = 4;\nint N_ = 2;\n\n// multi-threaded MKL dgeqp3 code -- test only on  a single node\nint mkl_dlaqps(int n_threads, int n, int M, int N)\n{\n    // MPI info\n    const int rank = comm_rank();\n    const int nranks = comm_size();\n    if(VERB) printf(\"[%d] Hello from %s\\n\", comm_rank(), processor_name().c_str());\n\n    assert(nranks==1);\n\n    int nb = min(32, n); // inner blocking size \n\n    // Warmup MKL\n    warmup_mkl(n_threads);\n\n    mkl_set_num_threads(n_threads);\n    \n    MatrixXd A = MatrixXd::Zero(0,0);\n    MatrixXd Acopy = MatrixXd::Zero(0,0);\n\n    auto val = [&](int i, int j) { return 1/(double)((i-j)*(i-j)+1); };\n    auto val_vec = [&](int i) {return 1/(double)(i*i+1);};\n\n    if (TEST) {\n        MatrixXd X =  MatrixXd::NullaryExpr(M*n,M*n,val);\n        VectorXd d = VectorXd::Zero(M*n);\n        d.head(N*n) = VectorXd::LinSpaced(N*n,1, N*n);\n        \n        DiagonalMatrix<double, Eigen::Dynamic> D(M*n);\n        D = d.asDiagonal();\n        A = X*D*X.inverse(); // A is square\n\n        Acopy = A;\n        if(rank == 0 && VERB) {\n            cout << A << endl;\n        }\n    } // X and D gets deleted here   \n    else {\n        A = MatrixXd::NullaryExpr(M*n,M*n,val);\n    }\n    // A is a square M*n x M*n matrix \n    VectorXd ht = VectorXd(min(M*n, M*n));\n    VectorXi jpvt = VectorXi::Zero(M*n);\n    int matrix_rank=0;\n\n    auto t0 = wctime();\n    laqps(&A, &jpvt, &ht, N*n, matrix_rank);\n    auto t1 = wctime();\n\n    if(matrix_rank != N*n) {\n        cout << matrix_rank << endl; \n        return -1;\n    }\n\n    if (rank == 0){\n        cout << \"Time taken: \" << elapsed(t0, t1) << endl;\n    }\n\n    if (rank == 0 && TEST){\n        MatrixXd v = A.leftCols(N*n);\n        VectorXd h = ht.topRows(N*n);\n        orgqr(&v, &h);\n\n        double error = (Acopy - v*(v.transpose()*Acopy)).norm();\n        cout << \"Error solve: \" << error << endl;\n        assert(error<=1e-8);\n    } \n    \n    \n    return 0;\n}\n\n\nint main(int argc, char **argv)\n{\n    int req = MPI_THREAD_FUNNELED;\n    int prov = -1;\n\n    MPI_Init_thread(NULL, NULL, req, &prov);\n\n    assert(prov == req);\n\n    if (argc >= 2)\n    {\n        n_threads_ = atoi(argv[1]);\n    }\n\n    if (argc >= 3)\n    {\n        n_ = atoi(argv[2]);\n    }\n\n    if (argc >= 4)\n    {\n        M_ = atoi(argv[3]);\n    }\n\n    if (argc >= 5)\n    {\n        N_ = atoi(argv[4]);\n    }\n\n    if (argc >= 6)\n    {\n        VERB = atoi(argv[5]);\n    }\n\n    if (argc >= 7)\n    {\n        LOG = atoi(argv[6]);\n    }\n\n    if (argc >= 8)\n    {\n        TEST = atoi(argv[7]);\n    }\n   \n    const int return_flag = mkl_dlaqps(n_threads_, n_, M_, N_);\n    MPI_Finalize();\n    return return_flag;\n}\n", "meta": {"hexsha": "bb399c2055a4b183338d825b6ad63bbdb8a730af", "size": 3201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "miniapp/rand_range/mkl_dlaqps.cpp", "max_stars_repo_name": "Abeynaya/tasktorrent", "max_stars_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "miniapp/rand_range/mkl_dlaqps.cpp", "max_issues_repo_name": "Abeynaya/tasktorrent", "max_issues_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "miniapp/rand_range/mkl_dlaqps.cpp", "max_forks_repo_name": "Abeynaya/tasktorrent", "max_forks_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_forks_repo_licenses": ["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.3885350318, "max_line_length": 83, "alphanum_fraction": 0.5379568885, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256313782277, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6154238544623443}}
{"text": "//#########################################################//\n//#                                                       #//\n//# gaussian_mixture_models  pca.cpp                      #//\n//# Roberto Capobianco  <capobianco@dis.uniroma1.it>      #//\n//#                                                       #//\n//#########################################################//\n\n#include <stdexcept>\n\n#include <Eigen/SVD>\n#include <iostream>\n\n#include <particle_filter/pca.h>\n\nnamespace gmms {\nEigen::MatrixXd\nPCA::pca(const Eigen::MatrixXd& dataset, double& retained_variance) {\n    if (num_components_ > dataset.cols()) {\n        throw std::runtime_error(\n                \"Number of components greater than dataset size\");\n    }\n\n    Eigen::MatrixXd centered = dataset.rowwise() - dataset.colwise().mean();\n\n    Eigen::RowVectorXd maxValues = centered.colwise().maxCoeff();\n    Eigen::RowVectorXd minValues = centered.colwise().minCoeff();\n    Eigen::MatrixXd normalized_dataset =\n            centered.array().rowwise() / (maxValues - minValues).array();\n\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(\n            normalized_dataset, Eigen::ComputeThinV);\n\n    Eigen::VectorXd S = svd.singularValues();\n    Eigen::MatrixXd W = svd.matrixV().leftCols(num_components_);\n\n    retained_variance = S.head(num_components_).sum() / S.sum();\n\n    Eigen::MatrixXd projected = normalized_dataset * W;\n\n    return projected;\n}\n}  // namespace gmms\n", "meta": {"hexsha": "57c6fca58aaa53ce1c722695ce726855528498f7", "size": 1430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/particle_filter/src/pca.cpp", "max_stars_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_stars_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-02-23T18:18:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T16:59:55.000Z", "max_issues_repo_path": "lib/particle_filter/src/pca.cpp", "max_issues_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_issues_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-16T22:05:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T14:21:53.000Z", "max_forks_repo_path": "lib/particle_filter/src/pca.cpp", "max_forks_repo_name": "MosHumanoid/bitbots_thmos_meta", "max_forks_repo_head_hexsha": "f45ccc362dc689b69027be5b0d000d2a08580de4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-29T10:20:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-20T16:36:47.000Z", "avg_line_length": 33.2558139535, "max_line_length": 76, "alphanum_fraction": 0.5517482517, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.6153289876741644}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\n#include <ipc/distance/point_point.hpp>\n\nnamespace ipc {\n\n/// @brief Compute the distance between a point and line in 2D or 3D.\n/// @note The distance is actually squared distance.\n/// @param p The point.\n/// @param e0 The first vertex of the edge defining the line.\n/// @param e1 The second vertex of the edge defining the line.\n/// @return The distance between the point and line.\ntemplate <typename DerivedP, typename DerivedE0, typename DerivedE1>\nauto point_line_distance(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedE0>& e0,\n    const Eigen::MatrixBase<DerivedE1>& e1)\n{\n    assert(p.size() == 2 || p.size() == 3);\n    assert(e0.size() == 2 || e0.size() == 3);\n    assert(e1.size() == 2 || e1.size() == 3);\n\n    if (p.size() == 2) {\n        auto e = e1 - e0;\n        auto numerator =\n            (e[1] * p[0] - e[0] * p[1] + e1[0] * e0[1] - e1[1] * e0[0]);\n        return numerator * numerator / e.squaredNorm();\n    } else {\n        return cross(e0 - p, e1 - p).squaredNorm() / (e1 - e0).squaredNorm();\n    }\n}\n\n// Symbolically generated derivatives;\nnamespace autogen {\n    void point_line_distance_gradient_2D(\n        double v01,\n        double v02,\n        double v11,\n        double v12,\n        double v21,\n        double v22,\n        double g[6]);\n\n    void point_line_distance_gradient_3D(\n        double v01,\n        double v02,\n        double v03,\n        double v11,\n        double v12,\n        double v13,\n        double v21,\n        double v22,\n        double v23,\n        double g[9]);\n\n    void point_line_distance_hessian_2D(\n        double v01,\n        double v02,\n        double v11,\n        double v12,\n        double v21,\n        double v22,\n        double H[36]);\n\n    void point_line_distance_hessian_3D(\n        double v01,\n        double v02,\n        double v03,\n        double v11,\n        double v12,\n        double v13,\n        double v21,\n        double v22,\n        double v23,\n        double H[81]);\n} // namespace autogen\n\n/// @brief Compute the gradient of the distance between a point and line.\n/// @note The distance is actually squared distance.\n/// @param[in] p The point.\n/// @param[in] e0 The first vertex of the edge defining the line.\n/// @param[in] e1 The second vertex of the edge defining the line.\n/// @param[out] grad The gradient of the distance wrt p, e0, and e1.\ntemplate <\n    typename DerivedP,\n    typename DerivedE0,\n    typename DerivedE1,\n    typename DerivedGrad>\nvoid point_line_distance_gradient(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedE0>& e0,\n    const Eigen::MatrixBase<DerivedE1>& e1,\n    Eigen::PlainObjectBase<DerivedGrad>& grad)\n{\n    assert(p.size() == 2 || p.size() == 3);\n    assert(e0.size() == 2 || e0.size() == 3);\n    assert(e1.size() == 2 || e1.size() == 3);\n\n    grad.resize(p.size() + e0.size() + e1.size());\n    if (p.size() == 2) {\n        autogen::point_line_distance_gradient_2D(\n            p[0], p[1], e0[0], e0[1], e1[0], e1[1], grad.data());\n    } else {\n        autogen::point_line_distance_gradient_3D(\n            p[0], p[1], p[2], e0[0], e0[1], e0[2], e1[0], e1[1], e1[2],\n            grad.data());\n    }\n}\n\n/// @brief Compute the hessian of the distance between a point and line.\n/// @note The distance is actually squared distance.\n/// @param[in] p The point.\n/// @param[in] e0 The first vertex of the edge defining the line.\n/// @param[in] e1 The second vertex of the edge defining the line.\n/// @param[out] hess The hessian of the distance wrt p, e0, and e1.\ntemplate <\n    typename DerivedP,\n    typename DerivedE0,\n    typename DerivedE1,\n    typename DerivedHess>\nvoid point_line_distance_hessian(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedE0>& e0,\n    const Eigen::MatrixBase<DerivedE1>& e1,\n    Eigen::PlainObjectBase<DerivedHess>& hess)\n{\n    assert(p.size() == 2 || p.size() == 3);\n    assert(e0.size() == 2 || e0.size() == 3);\n    assert(e1.size() == 2 || e1.size() == 3);\n\n    hess.resize(\n        p.size() + e0.size() + e1.size(), p.size() + e0.size() + e1.size());\n    if (p.size() == 2) {\n        autogen::point_line_distance_hessian_2D(\n            p[0], p[1], e0[0], e0[1], e1[0], e1[1], hess.data());\n    } else {\n        autogen::point_line_distance_hessian_3D(\n            p[0], p[1], p[2], e0[0], e0[1], e0[2], e1[0], e1[1], e1[2],\n            hess.data());\n    }\n}\n\n} // namespace ipc\n", "meta": {"hexsha": "1b9b8f2c0a385378599ad7c3fb2548f4208e43f0", "size": 4444, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/distance/point_line.hpp", "max_stars_repo_name": "ipc-sim/ipc-toolk", "max_stars_repo_head_hexsha": "81873d0288810e30166d871419da4104329860e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T21:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:24:31.000Z", "max_issues_repo_path": "src/distance/point_line.hpp", "max_issues_repo_name": "dbelgrod/ipc-toolkit", "max_issues_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T18:39:30.000Z", "max_forks_repo_path": "src/distance/point_line.hpp", "max_forks_repo_name": "dbelgrod/ipc-toolkit", "max_forks_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T12:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T04:55:49.000Z", "avg_line_length": 30.4383561644, "max_line_length": 77, "alphanum_fraction": 0.5927092709, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6152667000733923}}
{"text": "// restored from rdiff-backup: 2016-09-19T17:24:46+02:00\n\n#include <omp.h>\n#include <Eigen/Sparse>\n#include <algorithm>\n#include <boost/math/constants/constants.hpp>\n#include <boost/program_options.hpp>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <string>\n\n#include <base/eigen2hdf.hpp>\n#include <fft/ft_grid_helpers.hpp>\n#include <matrices/matrix_entries.hpp>\n#include <ridgelet/construction/ft.hpp>\n#include <ridgelet/construction/translation_grid.hpp>\n#include <ridgelet/lambda.hpp>\n#include <ridgelet/ridgelet_frame.hpp>\n#include \"base/init.hpp\"\n\nusing namespace std;\n\nconst double Lx = 1.0;\nconst double Ly = 1.0;\nconst double tol = 1e-10;\n\nconst double PI = boost::math::constants::pi<double>();\n\nint main(int argc, char* argv[])\n{\n  int J, rho;\n  SOURCE_INFO();\n\n  namespace po = boost::program_options;\n\n  po::options_description options(\"options\");\n  options.add_options()(\"help\", \"produce help message\")\n      (\"Jxy,J\", po::value<int>(&J)->default_value(3), \"J\")\n      (\"rho, r\", po::value<int>(&rho)->default_value(1), \"rho_x\")\n      (\"transport\", \"compute transport part too\");\n  po::variables_map vm;\n  try {\n    po::store(po::parse_command_line(argc, argv, options), vm);\n    po::notify(vm);\n    if (vm.count(\"help\")) {\n      std::cout << options << \"\\n\";\n      return 0;\n    }\n  } catch (std::exception& e) {\n    std::cout << e.what() << \"\\n\";\n  }\n\n  std::cout << \"J:   \" << J << \"\\n\"\n            << \"rho: \" << rho << \"\\n\";\n\n  RidgeletFrame frame(J, J, rho, rho);\n\n  std::string fname = std::string(\"mass_matrix_entries\") + std::to_string(J) + \".dat\";\n  // compute the translation grid sizes for reach lambda\n  // and\n  cout << \"Translation grid...\"\n       << \"\\n\";\n  std::vector<unsigned int> tgrid_size(frame.size());\n  std::vector<unsigned int> num_elements(frame.size() + 1, 0);\n  auto& lambdas = frame.lambdas();\n  for (unsigned int i = 0; i < frame.size(); ++i) {\n    auto T = tgrid_dim(lambdas[i], frame);\n    tgrid_size[i] = std::get<0>(T) * std::get<1>(T);\n  }\n  std::partial_sum(tgrid_size.begin(), tgrid_size.end(), num_elements.begin() + 1);\n  {\n    std::ofstream fout(std::string(\"num_elems\") + std::to_string(J) + \".dat\");\n    std::for_each(\n        num_elements.begin(), num_elements.end(), [&fout](unsigned int i) { fout << i << \"\\n\"; });\n    fout.close();\n  }\n\n  // Normalization ------------------------------\n  cout << \"Normalization...\"\n       << \"\\n\";\n  std::vector<double> ft_coeff_norms(frame.size());\n#pragma omp parallel for\n  for (unsigned int i = 0; i < frame.size(); ++i) {\n    auto lambda = frame.lambdas()[i];\n    if (lambda.t == rt_type::S) {\n      ft_coeff_norms[i] = std::sqrt(frame.get_dense(lambda).cwiseAbs2().sum());\n    } else {\n      ft_coeff_norms[i] = std::sqrt(frame.get_sparse(lambda).cwiseAbs2().sum());\n    }\n  }\n\n  /*\n   *  key = (l_i, l_j, t_d)\n   *  l_i, l_j, integer:\n   *  ------------------\n   *\n   *  hint: lambda_i = lambdas[l_i]\n   *\n   *  difference translation grid t_d:\n   *  -----------------\n   *  tuple t_d = {tx_i - tx_j, ty_i - ty_j}\n   */\n  typedef std::tuple<int, int> tgrid_diff_key; /*  type of t_d */\n  typedef std::tuple<int, int, tgrid_diff_key> key_type;\n  std::unordered_map<key_type, double> mass_matrix_entries;\n  std::unordered_map<key_type, double> transport_matrix_entries;\n\n  cout << \"Computing integrals...\"\n       << \"\\n\";\n#pragma omp parallel for schedule(dynamic, 1)\n  for (unsigned int i = 0; i < frame.size(); ++i) {\n    for (unsigned int j = 0; j <= i; ++j) {\n      // skip pairs that are known to evaluate to zero\n      if (std::abs(lambdas[i].j - lambdas[j].j) > 1) continue;\n      if ((lambdas[i].t == rt_type::X && lambdas[j].t == rt_type::Y) ||\n          (lambdas[i].t == rt_type::Y && lambdas[j].t == rt_type::X))\n        continue;\n      if ((lambdas[i].t == lambdas[j].t) && (lambdas[i].j == lambdas[j].j) &&\n          (std::abs(lambdas[i].k - lambdas[j].k) > 1))\n        continue;\n\n      auto& Psih_i = frame.get_sparse(lambdas[i]);\n      // Psih_i, Psih_j sparse\n      auto& Psih_j = frame.get_sparse(lambdas[j]);\n\n      auto T1 = tgrid_dim(lambdas[i], frame);\n      auto T2 = tgrid_dim(lambdas[j], frame);\n\n      int tx = std::max(std::get<0>(T1), std::get<0>(T2));\n      int ty = std::max(std::get<1>(T1), std::get<1>(T2));\n\n      // translation grid\n      auto vtx = Eigen::ArrayXd::LinSpaced(tx, 0, (1 - 1 / double(tx)) * Lx);\n      auto vty = Eigen::ArrayXd::LinSpaced(ty, 0, (1 - 1 / double(ty)) * Ly);\n\n      double fnorm = 1 / (ft_coeff_norms[i] * ft_coeff_norms[j]);\n      for (int idx_tx = 0; idx_tx < tx; ++idx_tx) {\n        for (int idx_ty = 0; idx_ty < ty; ++idx_ty) {\n          auto k = std::make_tuple(idx_tx, idx_ty);\n          auto key = std::make_tuple(i, j, k);\n          double v = compute_mass_entry(Psih_i, Psih_j, vtx[idx_tx], vty[idx_ty]);\n          v *= fnorm;\n          if (std::abs(v) > tol) {\n#pragma omp critical\n            mass_matrix_entries[key] = v;\n          }\n\n          if (vm.count(\"transport\")) {\n            double vxy = compute_tentry(\n                Psih_i, Psih_j, vtx[idx_tx], vty[idx_ty], derivative_t::dX, derivative_t::dY);\n            vxy *= fnorm;\n            double vxx = compute_tentry(\n                Psih_i, Psih_j, vtx[idx_tx], vty[idx_ty], derivative_t::dX, derivative_t::dX);\n            vxx *= fnorm;\n            double vyy = compute_tentry(\n                Psih_i, Psih_j, vtx[idx_tx], vty[idx_ty], derivative_t::dY, derivative_t::dY);\n            vyy *= fnorm;\n\n            double vt = 2 * vxy + vxx + vyy;\n\n            if (std::abs(vt) > tol) {\n#pragma omp critical\n              transport_matrix_entries[key] = vt;\n            }\n          }\n        }\n      }\n    }  // end for inner lambda\n  }    // end for outer lambda\n\n  std::cout << \"mass_matrix_entries.size: \" << mass_matrix_entries.size() << \"\\n\";\n  std::cout << \"writing results to \" << fname << \"\\n\";\n  // write to disk\n  std::ofstream fout(fname);\n  for (auto& elem : mass_matrix_entries) {\n    auto& key = elem.first;\n    auto val = elem.second;\n    int i = std::get<0>(key);\n    int j = std::get<1>(key);\n    int tx, ty;\n    std::tie(tx, ty) = std::get<2>(key);\n    fout << i << \"\\t\" << j << \"\\t\" << tx << \"\\t\" << ty << \"\\t\" << val << \"\\n\";\n  }\n  fout.close();\n  cout << \"\\tdone\"\n       << \"\\n\";\n\n  if (vm.count(\"transport\")) {\n    std::string fname = std::string(\"transport_matrix_\" + std::to_string(J) + \".dat\");\n    std::ofstream fout(fname);\n    for (auto& elem : transport_matrix_entries) {\n      auto& key = elem.first;\n      auto val = elem.second;\n      int i = std::get<0>(key);\n      int j = std::get<1>(key);\n      int tx, ty;\n      std::tie(tx, ty) = std::get<2>(key);\n      fout << i << \"\\t\" << j << \"\\t\" << tx << \"\\t\" << ty << \"\\t\" << val << \"\\n\";\n    }\n    fout.close();\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "b9439ac69c79aab93e57d54e9214dd08e0b4994b", "size": 6761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/matrices/main_mass_matrix.cpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "applications/matrices/main_mass_matrix.cpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/matrices/main_mass_matrix.cpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 32.8203883495, "max_line_length": 98, "alphanum_fraction": 0.566632155, "num_tokens": 2041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.6152666955181595}}
{"text": "// Copyright 2021 Apex.AI, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//  \u00a0 \u00a0http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Co-developed by Tier IV, Inc. and Apex.AI, Inc.\n\n#ifndef HELPER_FUNCTIONS__MAHALANOBIS_DISTANCE_HPP_\n#define HELPER_FUNCTIONS__MAHALANOBIS_DISTANCE_HPP_\n\n#include <Eigen/Cholesky>\n\nnamespace autoware\n{\nnamespace common\n{\nnamespace helper_functions\n{\n/// \\brief Calculate square of mahalanobis distance\n/// \\tparam T Type of elements in the matrix\n/// \\tparam kNumOfStates Number of states\n/// \\param sample Single column matrix containing sample whose distance needs to be computed\n/// \\param mean Single column matrix containing mean of samples received so far\n/// \\param covariance_factor Covariance matrix\n/// \\return Square of mahalanobis distance\ntemplate<typename T, std::int32_t kNumOfStates>\ntypes::float32_t calculate_squared_mahalanobis_distance(\n  const Eigen::Matrix<T, kNumOfStates, 1> & sample,\n  const Eigen::Matrix<T, kNumOfStates, 1> & mean,\n  const Eigen::Matrix<T, kNumOfStates, kNumOfStates> & covariance_factor)\n{\n  using Vector = Eigen::Matrix<T, kNumOfStates, 1>;\n  // This is equivalent to the squared Mahalanobis distance of the form: diff.T * C.inv() * diff\n  // Instead of the covariance matrix C we have its lower-triangular factor L, such that C = L * L.T\n  // squared_mahalanobis_distance = diff.T * C.inv() * diff\n  // = diff.T * (L * L.T).inv() * diff\n  // = diff.T * L.T.inv() * L.inv() * diff\n  // = (L.inv() * diff).T * (L.inv() * diff)\n  // this allows us to efficiently find the squared Mahalanobis distance using (L.inv() * diff),\n  // which can be found as a solution to: L * x = diff.\n  const Vector diff = sample - mean;\n  const Vector x = covariance_factor.ldlt().solve(diff);\n  return x.transpose() * x;\n}\n\n/// \\brief Calculate mahalanobis distance\n/// \\tparam T Type of elements in the matrix\n/// \\tparam kNumOfStates Number of states\n/// \\param sample Single column matrix containing sample whose distance needs to be computed\n/// \\param mean Single column matrix containing mean of samples received so far\n/// \\param covariance_factor Covariance matrix\n/// \\return Mahalanobis distance\ntemplate<typename T, std::int32_t kNumOfStates>\ntypes::float32_t calculate_mahalanobis_distance(\n  const Eigen::Matrix<T, kNumOfStates, 1> & sample,\n  const Eigen::Matrix<T, kNumOfStates, 1> & mean,\n  const Eigen::Matrix<T, kNumOfStates, kNumOfStates> & covariance_factor\n)\n{\n  return sqrtf(calculate_squared_mahalanobis_distance(sample, mean, covariance_factor));\n}\n}  // namespace helper_functions\n}  // namespace common\n}  // namespace autoware\n\n#endif  // HELPER_FUNCTIONS__MAHALANOBIS_DISTANCE_HPP_\n", "meta": {"hexsha": "fde5efca90a23917f1cb3c3dd66bea071cb02da8", "size": 3132, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/autoware_auto_common/include/helper_functions/mahalanobis_distance.hpp", "max_stars_repo_name": "ruvus/auto", "max_stars_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:14:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T10:03:08.000Z", "max_issues_repo_path": "src/common/autoware_auto_common/include/helper_functions/mahalanobis_distance.hpp", "max_issues_repo_name": "ruvus/auto", "max_issues_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2021-10-29T22:00:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T20:56:34.000Z", "max_forks_repo_path": "tmp_autoware_auto_dependencies/autoware_auto_common/include/helper_functions/mahalanobis_distance.hpp", "max_forks_repo_name": "taikitanaka3/AutowareArchitectureProposal.iv", "max_forks_repo_head_hexsha": "0d47ea532118c98458516a8c83fbdab3d27c6231", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-05-29T14:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:03:09.000Z", "avg_line_length": 41.2105263158, "max_line_length": 100, "alphanum_fraction": 0.7429757344, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.6152666955181595}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2016-2017 Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_FORMULAS_MAXIMUM_LONGITUDE_HPP\r\n#define BOOST_GEOMETRY_FORMULAS_MAXIMUM_LONGITUDE_HPP\r\n\r\n#include <boost/geometry/formulas/spherical.hpp>\r\n#include <boost/geometry/formulas/flattening.hpp>\r\n\r\n#include <boost/mpl/assert.hpp>\r\n\r\n#include <boost/math/special_functions/hypot.hpp>\r\n\r\nnamespace boost { namespace geometry { namespace formula\r\n{\r\n\r\n/*!\r\n\\brief Algorithm to compute the vertex longitude of a geodesic segment. Vertex is\r\na point on the geodesic that maximizes (or minimizes) the latitude. The algorithm\r\nis given the vertex latitude.\r\n*/\r\n\r\n//Classes for spesific CS\r\n\r\ntemplate <typename CT>\r\nclass vertex_longitude_on_sphere\r\n{\r\n\r\npublic:\r\n\r\n    template <typename T>\r\n    static inline CT apply(T const& lat1, //segment point 1\r\n                           T const& lat2, //segment point 2\r\n                           T const& lat3, //vertex latitude\r\n                           T const& sin_l12,\r\n                           T const& cos_l12) //lon1 -lon2\r\n    {\r\n        //https://en.wikipedia.org/wiki/Great-circle_navigation#Finding_way-points\r\n        CT const A = sin(lat1) * cos(lat2) * cos(lat3) * sin_l12;\r\n        CT const B = sin(lat1) * cos(lat2) * cos(lat3) * cos_l12\r\n                - cos(lat1) * sin(lat2) * cos(lat3);\r\n        CT lon = atan2(B, A);\r\n        return lon + math::pi<CT>();\r\n    }\r\n};\r\n\r\ntemplate <typename CT>\r\nclass vertex_longitude_on_spheroid\r\n{\r\n    template<typename T>\r\n    static inline void normalize(T& x, T& y)\r\n    {\r\n        T h = boost::math::hypot(x, y);\r\n        x /= h;\r\n        y /= h;\r\n    }\r\n\r\npublic:\r\n\r\n    template <typename T, typename Spheroid>\r\n    static inline CT apply(T const& lat1, //segment point 1\r\n                           T const& lat2, //segment point 2\r\n                           T const& lat3, //vertex latitude\r\n                           T& alp1,\r\n                           Spheroid const& spheroid)\r\n    {\r\n        // We assume that segment points lay on different side w.r.t.\r\n        // the vertex\r\n\r\n        // Constants\r\n        CT const c0 = 0;\r\n        CT const c2 = 2;\r\n        CT const half_pi = math::pi<CT>() / c2;\r\n        if (math::equals(lat1, half_pi)\r\n                || math::equals(lat2, half_pi)\r\n                || math::equals(lat1, -half_pi)\r\n                || math::equals(lat2, -half_pi))\r\n        {\r\n            // one segment point is the pole\r\n            return c0;\r\n        }\r\n\r\n        // More constants\r\n        CT const f = flattening<CT>(spheroid);\r\n        CT const pi = math::pi<CT>();\r\n        CT const c1 = 1;\r\n        CT const cminus1 = -1;\r\n\r\n        // First, compute longitude on auxiliary sphere\r\n\r\n        CT const one_minus_f = c1 - f;\r\n        CT const bet1 = atan(one_minus_f * tan(lat1));\r\n        CT const bet2 = atan(one_minus_f * tan(lat2));\r\n        CT const bet3 = atan(one_minus_f * tan(lat3));\r\n\r\n        CT cos_bet1 = cos(bet1);\r\n        CT cos_bet2 = cos(bet2);\r\n        CT const sin_bet1 = sin(bet1);\r\n        CT const sin_bet2 = sin(bet2);\r\n        CT const sin_bet3 = sin(bet3);\r\n\r\n        CT omg12 = 0;\r\n\r\n        if (bet1 < c0)\r\n        {\r\n            cos_bet1 *= cminus1;\r\n            omg12 += pi;\r\n        }\r\n        if (bet2 < c0)\r\n        {\r\n            cos_bet2 *= cminus1;\r\n            omg12 += pi;\r\n        }\r\n\r\n        CT const sin_alp1 = sin(alp1);\r\n        CT const cos_alp1 = math::sqrt(c1 - math::sqr(sin_alp1));\r\n\r\n        CT const norm = math::sqrt(math::sqr(cos_alp1) + math::sqr(sin_alp1 * sin_bet1));\r\n        CT const sin_alp0 = sin(atan2(sin_alp1 * cos_bet1, norm));\r\n\r\n        BOOST_ASSERT(cos_bet2 != c0);\r\n        CT const sin_alp2 = sin_alp1 * cos_bet1 / cos_bet2;\r\n\r\n        CT const cos_alp0 = math::sqrt(c1 - math::sqr(sin_alp0));\r\n        CT const cos_alp2 = math::sqrt(c1 - math::sqr(sin_alp2));\r\n\r\n        CT const sig1 = atan2(sin_bet1, cos_alp1 * cos_bet1);\r\n        CT const sig2 = atan2(sin_bet2, -cos_alp2 * cos_bet2); //lat3 is a vertex\r\n\r\n        CT const cos_sig1 = cos(sig1);\r\n        CT const sin_sig1 = math::sqrt(c1 - math::sqr(cos_sig1));\r\n\r\n        CT const cos_sig2 = cos(sig2);\r\n        CT const sin_sig2 = math::sqrt(c1 - math::sqr(cos_sig2));\r\n\r\n        CT const omg1 = atan2(sin_alp0 * sin_sig1, cos_sig1);\r\n        CT const omg2 = atan2(sin_alp0 * sin_sig2, cos_sig2);\r\n\r\n        omg12 += omg1 - omg2;\r\n\r\n        CT const sin_omg12 = sin(omg12);\r\n        CT const cos_omg12 = cos(omg12);\r\n\r\n        CT omg13 = geometry::formula::vertex_longitude_on_sphere<CT>\r\n                ::apply(bet1, bet2, bet3, sin_omg12, cos_omg12);\r\n\r\n        if (lat1 * lat2 < c0)//different hemispheres\r\n        {\r\n            if ((lat2 - lat1) * lat3  > c0)// ascending segment\r\n            {\r\n                omg13 = pi - omg13;\r\n            }\r\n        }\r\n\r\n        // Second, compute the ellipsoidal longitude\r\n\r\n        CT const e2 = f * (c2 - f);\r\n        CT const ep = math::sqrt(e2 / (c1 - e2));\r\n        CT const k2 = math::sqr(ep * cos_alp0);\r\n        CT const sqrt_k2_plus_one = math::sqrt(c1 + k2);\r\n        CT const eps = (sqrt_k2_plus_one - c1) / (sqrt_k2_plus_one + c1);\r\n        CT const eps2 = eps * eps;\r\n        CT const n = f / (c2 - f);\r\n\r\n        // sig3 is the length from equator to the vertex\r\n        CT sig3;\r\n        if(sin_bet3 > c0)\r\n        {\r\n            sig3 = half_pi;\r\n        } else {\r\n            sig3 = -half_pi;\r\n        }\r\n        CT const cos_sig3 = 0;\r\n        CT const sin_sig3 = 1;\r\n\r\n        CT sig13 = sig3 - sig1;\r\n        if (sig13 > pi)\r\n        {\r\n            sig13 -= 2 * pi;\r\n        }\r\n\r\n        // Order 2 approximation\r\n        CT const c1over2 = 0.5;\r\n        CT const c1over4 = 0.25;\r\n        CT const c1over8 = 0.125;\r\n        CT const c1over16 = 0.0625;\r\n        CT const c4 = 4;\r\n        CT const c8 = 8;\r\n\r\n        CT const A3 = 1 - (c1over2 - c1over2 * n) * eps - c1over4 * eps2;\r\n        CT const C31 = (c1over4 - c1over4 * n) * eps + c1over8 * eps2;\r\n        CT const C32 = c1over16 * eps2;\r\n\r\n        CT const sin2_sig3 = c2 * cos_sig3 * sin_sig3;\r\n        CT const sin4_sig3 = sin_sig3 * (-c4 * cos_sig3\r\n                                         + c8 * cos_sig3 * cos_sig3 * cos_sig3);\r\n        CT const sin2_sig1 = c2 * cos_sig1 * sin_sig1;\r\n        CT const sin4_sig1 = sin_sig1 * (-c4 * cos_sig1\r\n                                         + c8 * cos_sig1 * cos_sig1 * cos_sig1);\r\n        CT const I3 = A3 * (sig13\r\n                            + C31 * (sin2_sig3 - sin2_sig1)\r\n                            + C32 * (sin4_sig3 - sin4_sig1));\r\n\r\n        CT const sign = bet3 >= c0\r\n                      ? c1\r\n                      : cminus1;\r\n        \r\n        CT const dlon_max = omg13 - sign * f * sin_alp0 * I3;\r\n\r\n        return dlon_max;\r\n    }\r\n};\r\n\r\n//CS_tag dispatching\r\n\r\ntemplate <typename CT, typename CS_Tag>\r\nstruct compute_vertex_lon\r\n{\r\n    BOOST_MPL_ASSERT_MSG\r\n    (\r\n        false, NOT_IMPLEMENTED_FOR_THIS_COORDINATE_SYSTEM, (types<CS_Tag>)\r\n    );\r\n\r\n};\r\n\r\ntemplate <typename CT>\r\nstruct compute_vertex_lon<CT, spherical_equatorial_tag>\r\n{\r\n    template <typename Strategy>\r\n    static inline CT apply(CT const& lat1,\r\n                           CT const& lat2,\r\n                           CT const& vertex_lat,\r\n                           CT const& sin_l12,\r\n                           CT const& cos_l12,\r\n                           CT,\r\n                           Strategy)\r\n    {\r\n        return vertex_longitude_on_sphere<CT>\r\n                ::apply(lat1,\r\n                        lat2,\r\n                        vertex_lat,\r\n                        sin_l12,\r\n                        cos_l12);\r\n    }\r\n};\r\n\r\ntemplate <typename CT>\r\nstruct compute_vertex_lon<CT, geographic_tag>\r\n{\r\n    template <typename Strategy>\r\n    static inline CT apply(CT const& lat1,\r\n                           CT const& lat2,\r\n                           CT const& vertex_lat,\r\n                           CT,\r\n                           CT,\r\n                           CT& alp1,\r\n                           Strategy const& azimuth_strategy)\r\n    {\r\n        return vertex_longitude_on_spheroid<CT>\r\n                ::apply(lat1,\r\n                        lat2,\r\n                        vertex_lat,\r\n                        alp1,\r\n                        azimuth_strategy.model());\r\n    }\r\n};\r\n\r\n// Vertex longitude interface\r\n// Assume that lon1 < lon2 and vertex_lat is the latitude of the vertex\r\n\r\ntemplate <typename CT, typename CS_Tag>\r\nclass vertex_longitude\r\n{\r\npublic :\r\n    template <typename Strategy>\r\n    static inline CT apply(CT& lon1,\r\n                           CT& lat1,\r\n                           CT& lon2,\r\n                           CT& lat2,\r\n                           CT const& vertex_lat,\r\n                           CT& alp1,\r\n                           Strategy const& azimuth_strategy)\r\n    {\r\n        CT const c0 = 0;\r\n        CT pi = math::pi<CT>();\r\n\r\n        //Vertex is a segment's point\r\n        if (math::equals(vertex_lat, lat1))\r\n        {\r\n            return lon1;\r\n        }\r\n        if (math::equals(vertex_lat, lat2))\r\n        {\r\n            return lon2;\r\n        }\r\n\r\n        //Segment lay on meridian\r\n        if (math::equals(lon1, lon2))\r\n        {\r\n            return (std::max)(lat1, lat2);\r\n        }\r\n        BOOST_ASSERT(lon1 < lon2);\r\n\r\n        CT dlon = compute_vertex_lon<CT, CS_Tag>::apply(lat1, lat2,\r\n                                                        vertex_lat,\r\n                                                        sin(lon1 - lon2),\r\n                                                        cos(lon1 - lon2),\r\n                                                        alp1,\r\n                                                        azimuth_strategy);\r\n\r\n        CT vertex_lon = std::fmod(lon1 + dlon, 2 * pi);\r\n\r\n        if (vertex_lat < c0)\r\n        {\r\n            vertex_lon -= pi;\r\n        }\r\n\r\n        if (std::abs(lon1 - lon2) > pi)\r\n        {\r\n            vertex_lon -= pi;\r\n        }\r\n\r\n        return vertex_lon;\r\n    }\r\n};\r\n\r\n}}} // namespace boost::geometry::formula\r\n#endif // BOOST_GEOMETRY_FORMULAS_MAXIMUM_LONGITUDE_HPP\r\n\r\n", "meta": {"hexsha": "11ed592984eb17a6a1765c47366bcb6db5002f9f", "size": 10485, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/formulas/vertex_longitude.hpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/formulas/vertex_longitude.hpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/formulas/vertex_longitude.hpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0207100592, "max_line_length": 90, "alphanum_fraction": 0.4946113495, "num_tokens": 2618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.6152666832307896}}
{"text": "/*\n * random.cpp\n *\n */\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <random>\n\n#include <boost/assert.hpp>\n\n#include \"core/random.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace yann;\n\n\nnamespace yann {\n\ntypedef mt19937 DefaultGenerator;\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// yann::RandomGenerator_NormalDistribution implementation\n//\nclass RandomGenerator_NormalDistribution : public RandomGenerator {\n  friend class RandomGenerator;\n\npublic:\n  RandomGenerator_NormalDistribution(const Value & mean, const Value & stddev, optional<Value> seed) :\n    _gen(seed ? (unsigned)(*seed) : _rd()),\n    _dist(mean, stddev)\n  {\n  }\n\n  // RandomGenerator overwrites\n  Value next() { return _dist(_gen); }\n\nprivate:\n  RandomGenerator_NormalDistribution(const RandomGenerator_NormalDistribution &) = delete;\n  RandomGenerator_NormalDistribution& operator=(const RandomGenerator_NormalDistribution &) = delete;\n\nprivate:\n  random_device _rd;\n  DefaultGenerator _gen;\n  std::normal_distribution<Value> _dist;\n}; // class RandomGenerator_NormalDistribution\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// yann::RandomGenerator_UniformDistribution implementation\n//\nclass RandomGenerator_UniformDistribution : public RandomGenerator {\n  friend class RandomGenerator;\n\npublic:\n  RandomGenerator_UniformDistribution(const Value & aa, const Value & bb, optional<Value> seed) :\n    _gen(seed ? (unsigned)(*seed) : _rd()),\n    _dist(aa, bb)\n  {\n  }\n\n  // RandomGenerator overwrites\n  Value next() { return _dist(_gen); }\n\nprivate:\n  RandomGenerator_UniformDistribution(const RandomGenerator_UniformDistribution &) = delete;\n  RandomGenerator_UniformDistribution& operator=(const RandomGenerator_UniformDistribution &) = delete;\n\nprivate:\n  random_device _rd;\n  DefaultGenerator _gen;\n  uniform_real_distribution<Value> _dist;\n}; // class RandomGenerator_NormalDistribution\n\n\n}; // RandomGenerator\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// yann::RandomGenerator implementation\n//\nunique_ptr<RandomGenerator> yann::RandomGenerator::normal_distribution(\n    const Value & mean, const Value & stddev, optional<Value> seed)\n{\n  return make_unique<RandomGenerator_NormalDistribution>(mean, stddev, seed);\n}\n\nunique_ptr<RandomGenerator> yann::RandomGenerator::uniform_distribution(\n    const Value & aa, const Value & bb, optional<Value> seed)\n{\n  return make_unique<RandomGenerator_UniformDistribution>(aa, bb, seed);\n}\n\nvoid yann::RandomGenerator::generate(Value & val)\n{\n  val = next();\n}\n\nvoid yann::RandomGenerator::generate(RefMatrix mm)\n{\n  for(auto ii = 0; ii < mm.rows(); ++ii) {\n    for(auto jj = 0; jj < mm.cols(); ++jj) {\n      mm(ii, jj) = next();\n    }\n  }\n}\n\n", "meta": {"hexsha": "685d9469ffe49371044bf9b72013d0192abeadfb", "size": 2863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/random.cpp", "max_stars_repo_name": "lsh123/yann", "max_stars_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T10:25:07.000Z", "max_issues_repo_path": "src/core/random.cpp", "max_issues_repo_name": "lsh123/yann", "max_issues_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/random.cpp", "max_forks_repo_name": "lsh123/yann", "max_forks_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0272727273, "max_line_length": 103, "alphanum_fraction": 0.6699266504, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6152666745993645}}
{"text": "/*\n * ClusterRotate.cpp\n *\n *  Created on: 04-Mar-2009\n *      Author: sbutler\n */\n\n#define EIGEN2_SUPPORT\n\n#include \"ClusterRotate.h\"\n\n#include <map>\n#include <Eigen/Array>\n\nClusterRotate::ClusterRotate(int method) :\n\tmMethod(method),\n\tmMaxQuality(0)\n{\n\n}\n\nstd::vector<std::vector<int> > ClusterRotate::cluster(Eigen::MatrixXd& X) \n{\n\tmMaxQuality = 0;\n\tstd::vector<std::vector<int> > clusters;\n\tEigen::MatrixXd vecRot;\n\tEigen::MatrixXd vecIn = X.block(0, 0, X.rows(), 2);\n\tEvrot* e = NULL;\n\tfor (int g = 2; g <= X.cols(); g++) \n\t{\n\t\t// make it incremental (used already aligned vectors)\n\t\tif (g > 2)\n\t\t{\n\t\t\tvecIn.resize(X.rows(), g);\n\t\t\tvecIn.block(0, 0, vecIn.rows(), g - 1) = e->getRotatedEigenVectors();\n\t\t\tvecIn.block(0, g - 1, X.rows(), 1) = X.block(0, g - 1, X.rows(), 1);\n\t\t\tdelete e;\n\t\t}\n\t\t//perform the rotation for the current number of dimensions\n\t\te = new Evrot(vecIn, mMethod);\n\n\t\t//save max quality\n\t\tif (e->getQuality() > mMaxQuality) \n\t\t{\n\t\t\tmMaxQuality = e->getQuality();\n\t\t}\n\t\t//save cluster data for max cluster or if we're near the max cluster (so prefer more clusters)\n\t\tif ((e->getQuality() > mMaxQuality) || (mMaxQuality - e->getQuality() <= 0.001)) \n\t\t{\n\t\t\tclusters = e->getClusters();\n\t\t\tvecRot = e->getRotatedEigenVectors();\n\t\t}\n\t}\n\n\tEigen::MatrixXd clusterCentres = Eigen::MatrixXd::Zero(clusters.size(), vecRot.cols());\n\tfor (unsigned int i = 0; i < clusters.size(); i++) \n\t{\n\t\tfor (unsigned int j = 0; j < clusters[i].size(); j++) \n\t\t{\n\t\t\t//sum points within cluster\n\t\t\tclusterCentres.row(i) += vecRot.row(clusters[i][j]);\n\t\t}\n\t}\n\tfor (unsigned int i = 0; i < clusters.size(); i++)\n\t{\n\t\t//find average point within cluster\n\t\tclusterCentres.row(i) = clusterCentres.row(i) / clusters[i].size();\n\t}\n\n\t//order clustered points by (ascending) distance to cluster centre\n\tfor (unsigned int i = 0; i < clusters.size(); i++) \n\t{\n\t\tstd::multimap<double, int> clusterDistance;\n\t\tfor (unsigned int j = 0; j < clusters[i].size(); j++) \n\t\t{\n\t\t\tdouble d2 = (vecRot.row(clusters[i][j]) - clusterCentres.row(i)).squaredNorm();\n\t\t\tclusterDistance.insert(std::make_pair(d2, clusters[i][j]));\n\t\t}\n\t\t//the map will be sorted based on the key so just loop through it\n\t\t//to get set of data indices sorted on the distance to cluster\n\t\tclusters[i].clear();\n\t\tfor (std::multimap<double, int>::iterator it = clusterDistance.begin(); it != clusterDistance.end(); it++) \n\t\t{\n\t\t\tclusters[i].push_back(it->second);\n\t\t}\n\t}\n\n\treturn clusters;\n}\n\n", "meta": {"hexsha": "28ea0192dd17b7e9128864b1ea25a0f0d3e48af6", "size": 2445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SpectralClustering/ClusterRotate.cpp", "max_stars_repo_name": "gbull122/SpectralClustering", "max_stars_repo_head_hexsha": "76c1ab9e06a88a40807b5dad6f15bac9efb2da52", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-03T03:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-20T15:50:32.000Z", "max_issues_repo_path": "src/SpectralClustering/ClusterRotate.cpp", "max_issues_repo_name": "gbull122/SpectralClustering", "max_issues_repo_head_hexsha": "76c1ab9e06a88a40807b5dad6f15bac9efb2da52", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SpectralClustering/ClusterRotate.cpp", "max_forks_repo_name": "gbull122/SpectralClustering", "max_forks_repo_head_hexsha": "76c1ab9e06a88a40807b5dad6f15bac9efb2da52", "max_forks_repo_licenses": ["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.8681318681, "max_line_length": 109, "alphanum_fraction": 0.6429447853, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6152544977877458}}
{"text": "//==================================================================================================\n/*!\n  @file\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_ERFC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ERFC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n  @ingroup group-euler\n    Function object implementing erfc capabilities\n\n  Computes the complementary error function\n   \\f$\\displaystyle \\frac{2}{\\sqrt\\pi}\\int_{x}^{\\infty} e^{-t^2}\\mbox{d}t\\f$\n\n  @par Semantic:\n\n  For every parameter of floating type T\n\n  @code\n  T r = erfc(x);\n  @endcode\n\n  is similar to:\n\n  @code\n  T0 r = oneminus(erf(x));\n  @endcode\n\n  @par Decorators\n\n  std_ for floating entries provides access to @c std::erfc\n\n  @see erf, erfcx, oneminus\n\n  **/\n  Value erfc(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/erfc.hpp>\n#include <boost/simd/function/simd/erfc.hpp>\n\n#endif\n", "meta": {"hexsha": "2100ac8cd8deb7e2b47bcd7090425536e7271fdb", "size": 1169, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/erfc.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/erfc.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/erfc.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 22.0566037736, "max_line_length": 100, "alphanum_fraction": 0.5911035073, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6151907814033784}}
{"text": "// Copyright 2019 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_custom_accumulators_advanced\n\n#include <boost/format.hpp>\n#include <boost/histogram.hpp>\n#include <iostream>\n#include <sstream>\n\nint main() {\n  using namespace boost::histogram;\n\n  // Accumulator accepts two samples and an optional weight and computes the mean of each.\n  struct multi_mean {\n    accumulators::mean<> mx, my;\n\n    // called when no weight is passed\n    void operator()(double x, double y) {\n      mx(x);\n      my(y);\n    }\n\n    // called when a weight is passed\n    void operator()(weight_type<double> w, double x, double y) {\n      mx(w, x);\n      my(w, y);\n    }\n  };\n  // Note: The implementation can be made more efficient by sharing the sum of weights.\n\n  // Create a 1D histogram that uses the custom accumulator.\n  auto h = make_histogram_with(dense_storage<multi_mean>(), axis::integer<>(0, 2));\n  h(0, sample(1, 2));            // samples go to first cell\n  h(0, sample(3, 4));            // samples go to first cell\n  h(1, sample(5, 6), weight(2)); // samples go to second cell\n  h(1, sample(7, 8), weight(3)); // samples go to second cell\n\n  std::ostringstream os;\n  for (auto&& bin : indexed(h)) {\n    os << boost::format(\"index %i mean-x %.1f mean-y %.1f\\n\") % bin.index() %\n              bin->mx.value() % bin->my.value();\n  }\n  std::cout << os.str() << std::flush;\n  assert(os.str() == \"index 0 mean-x 2.0 mean-y 3.0\\n\"\n                     \"index 1 mean-x 6.2 mean-y 7.2\\n\");\n}\n\n//]\n", "meta": {"hexsha": "16ab559f2ab33a517b17c65a9ff1d6f7754d6c18", "size": 1618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/histogram/examples/guide_custom_accumulators_advanced.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 188.0, "max_stars_repo_stars_event_min_datetime": "2019-02-08T14:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T08:37:05.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/histogram/examples/guide_custom_accumulators_advanced.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 186.0, "max_issues_repo_issues_event_min_datetime": "2016-05-05T14:01:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-20T22:38:43.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/histogram/examples/guide_custom_accumulators_advanced.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 43.0, "max_forks_repo_forks_event_min_datetime": "2019-02-09T16:16:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T20:24:36.000Z", "avg_line_length": 30.5283018868, "max_line_length": 90, "alphanum_fraction": 0.6236093943, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6151907814033782}}
{"text": "\n#include \"distances.h\"\n#include \"EMD_wrapper.h\"\n\n#define EIGEN_NO_DEBUG\n#define EIGEN_DONT_PARALLELIZE\n#include <Eigen/Dense>\n\n#include <cmath> // for std::isnormal\n\nDistanceIndexPairs lp_distances(int Mp_i, const Options& opts, const Manifold& M, const Manifold& Mp,\n                                std::vector<int> inpInds)\n{\n  std::vector<int> inds;\n  std::vector<double> dists;\n\n  // Compare every observation in the M manifold to the\n  // Mp_i'th observation in the Mp manifold.\n  for (int i : inpInds) {\n    // Calculate the distance between M[i] and Mp[Mp_i]\n    double dist_i = 0.0;\n\n    // If we have panel data and the M[i] / Mp[Mp_j] observations come from different panels\n    // then add the user-supplied penalty/distance for the mismatch.\n    if (opts.panelMode && opts.idw > 0) {\n      dist_i += opts.idw * (M.panel(i) != Mp.panel(Mp_i));\n    }\n\n    for (int j = 0; j < M.E_actual(); j++) {\n      // Get the sub-distance between M[i,j] and Mp[Mp_i, j]\n      double dist_ij;\n\n      // If either of these values is missing, the distance from\n      // M[i,j] to Mp[Mp_i, j] is opts.missingdistance.\n      // However, if the user doesn't specify this, then the entire\n      // M[i] to Mp[Mp_i] distance is set as missing.\n      if ((M(i, j) == MISSING_SENTINEL) || (Mp(Mp_i, j) == MISSING_SENTINEL)) {\n        if (opts.missingdistance == 0) {\n          dist_i = MISSING_SENTINEL;\n          break;\n        } else {\n          dist_ij = opts.missingdistance;\n        }\n      } else { // Neither M[i,j] nor Mp[Mp_i, j] is missing.\n        // How do we compare them? Do we treat them like continuous values and subtract them,\n        // or treat them like unordered categorical variables and just check if they're the same?\n        if (opts.metrics[j] == Metric::Diff) {\n          dist_ij = M(i, j) - Mp(Mp_i, j);\n        } else { // Metric::CheckSame\n          dist_ij = (M(i, j) != Mp(Mp_i, j));\n        }\n      }\n\n      if (opts.distance == Distance::MeanAbsoluteError) {\n        dist_i += abs(dist_ij) / M.E_actual();\n      } else { // Distance::Euclidean\n        dist_i += dist_ij * dist_ij;\n      }\n    }\n\n    if (dist_i != 0 && dist_i != MISSING_SENTINEL) {\n      if (opts.distance == Distance::MeanAbsoluteError) {\n        dists.push_back(dist_i);\n      } else { // Distance::Euclidean\n        dists.push_back(sqrt(dist_i));\n      }\n      inds.push_back(i);\n    }\n  }\n\n  return { inds, dists };\n}\n\n// This function compares the M(i,.) multivariate time series to the Mp(j,.) multivariate time series.\n// The M(i,.) observation has data for E consecutive time points (e.g. time(i), time(i+1), ..., time(i+E-1)) and\n// the Mp(j,.) observation corresponds to E consecutive time points (e.g. time(j), time(j+1), ..., time(j+E-1)).\n// At each time instant we observe n >= 1 pieces of data.\n// These may either be continuous data or unordered categorical data.\n//\n// The Wasserstein distance (using the 'curve-matching' strategy) is equivalent to the (minimum) cost of turning\n// the first time series into the second time series. In a simple example, say E = 2 and n = 1, and\n//         M(i,.) = [ 1, 2 ] and Mp(j,.) = [ 2, 2 ].\n// To turn M(i,.) into Mp(j,.) the first element needs to be increased by 1, so the overall cost is\n//         Wasserstein( M(i,.), Mp(j,.) ) = 1.\n// The distance can also reorder the points, so for example say\n//         M(i,.) = [ 1, 100 ] and Mp(j,.) = [ 100, 1 ].\n// If we just change the 1 to 100 and the 100 to 1 then the cost of each is 99 + 99 = 198.\n// However, Wasserstein can instead reorder these points at a cost of\n//         Wasserstein( M(i,.), Mp(j,.) ) = 2 * gamma * (time(1)-time(2))\n// so if the observations occur on a regular grid so time(i) = i then the distance will just be 2 * gamma.\n//\n// The return value of this function is a matrix which shows the pairwise costs associated to each\n// potential Wasserstein solution. E.g. the (n,m) element of the returned matrix shows the cost\n// of turning the individual point M(i, n) into Mp(j, m).\n//\n// When there are missing values in one or other observation, we can either ignore this time period\n// and compute the Wasserstein for the mismatched regime where M(i,.) is of size len_i and Mp(j,.) is\n// of size len_j, where len_i != len_j is possible. Alternatively, we can fill in the affected elements\n// of the cost matrix with some user-supplied 'missingDistance' value and then len_i == len_j is upheld.\nstd::unique_ptr<double[]> wasserstein_cost_matrix(const Manifold& M, const Manifold& Mp, int i, int j,\n                                                  const Options& opts, int& len_i, int& len_j)\n{\n  // The M(i,.) observation will be stored as one flat vector of length M.E_actual():\n  // - the first M.E() observations will the lagged version of the main time series\n  // - the next M.E() observations will be the lagged 'dt' time series (if it is included, i.e., if M.E_dt() > 0)\n  // - the next n * M.E() observations will be the n lagged extra variables,\n  //   so in total that is M.E_lagged_extras() = n * M.E() observations\n  // - the remaining M.E_actual() - M.E() - M.E_dt() - M.E_lagged_extras() are the unlagged extras and the distance\n  //   between those two vectors forms a kind of minimum distance which is added to the time-series curve matching\n  //   Wasserstein distance.\n\n  bool skipMissing = (opts.missingdistance == 0);\n\n  auto M_i = M.laggedObsMap(i);\n  auto Mp_j = Mp.laggedObsMap(j);\n\n  auto M_i_missing = (M_i.array() == M.missing()).colwise().any();\n  auto Mp_j_missing = (Mp_j.array() == Mp.missing()).colwise().any();\n\n  if (skipMissing) {\n    // N.B. Can't .sum() a vector of bools to count them in Eigen.\n    len_i = M.E() - M_i_missing.count();\n    len_j = Mp.E() - Mp_j_missing.count();\n  } else {\n    len_i = M.E();\n    len_j = Mp.E();\n  }\n\n  double gamma = 1.0;\n  if (M.E_dt() > 0) {\n    // Imagine the M_i time series as a plot, and calculate the\n    // aspect ratio of this plot, so we can rescale the time variable\n    // to get the user-supplied aspect ratio.\n    double minData = std::numeric_limits<double>::max();\n    double maxData = std::numeric_limits<double>::min();\n    double maxTime = 0.0;\n    for (int t = 0; t < M_i.cols(); t++) {\n      if (M_i(0, t) != MISSING_SENTINEL) {\n        if (M_i(0, t) < minData) {\n          minData = M_i(0, t);\n        }\n        if (M_i(0, t) > maxData) {\n          maxData = M_i(0, t);\n        }\n      }\n      if (M_i(1, t) != MISSING_SENTINEL && M_i(1, t) > maxTime) {\n        maxTime = M_i(1, t);\n      }\n    }\n\n    double epsilon = 1e-6; // Some small number in case the following ratio gets wildly large/small\n    gamma = opts.aspectRatio * (maxData - minData + epsilon) / (maxTime + epsilon);\n  }\n\n  int timeSeriesDim = M_i.rows();\n\n  double unlaggedDist = 0.0;\n  int numUnlaggedExtras = M.E_extras() - M.E_lagged_extras();\n  for (int e = 0; e < numUnlaggedExtras; e++) {\n    double x = M.unlagged_extras(i, e), y = Mp.unlagged_extras(j, e);\n    bool eitherMissing = (x == M.missing()) || (y == M.missing());\n\n    if (eitherMissing) {\n      unlaggedDist += opts.missingdistance;\n    } else {\n      if (opts.metrics[timeSeriesDim + e] == Metric::Diff) {\n        unlaggedDist += abs(x - y);\n      } else {\n        unlaggedDist += x != y;\n      }\n    }\n  }\n\n  // If we have panel data and the M[i] / Mp[j] observations come from different panels\n  // then add the user-supplied penalty/distance for the mismatch.\n  if (opts.panelMode && opts.idw > 0) {\n    unlaggedDist += opts.idw * (M.panel(i) != Mp.panel(j));\n  }\n\n  auto flatCostMatrix = std::make_unique<double[]>(len_i * len_j);\n  std::fill_n(flatCostMatrix.get(), len_i * len_j, unlaggedDist);\n  Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> costMatrix(flatCostMatrix.get(),\n                                                                                                len_i, len_j);\n  for (int k = 0; k < timeSeriesDim; k++) {\n    int n = 0;\n    for (int nn = 0; nn < M_i.cols(); nn++) {\n      if (skipMissing && M_i_missing[nn]) {\n        continue;\n      }\n\n      int m = 0;\n\n      for (int mm = 0; mm < Mp_j.cols(); mm++) {\n        if (skipMissing && Mp_j_missing[mm]) {\n          continue;\n        }\n        double dist;\n        bool eitherMissing = M_i_missing[nn] || Mp_j_missing[mm];\n\n        if (eitherMissing) {\n          dist = opts.missingdistance;\n        } else {\n          if (opts.metrics[k] == Metric::Diff) {\n            dist = abs(M_i(k, nn) - Mp_j(k, mm));\n          } else {\n            dist = M_i(k, nn) != Mp_j(k, mm);\n          }\n        }\n\n        // For the time data, we add in the 'gamma' scaling factor calculated earlier\n        if ((M.E_dt() > 0) && (k == 1)) {\n          dist *= gamma;\n        }\n\n        costMatrix(n, m) += dist;\n\n        m += 1;\n      }\n\n      n += 1;\n    }\n  }\n  return flatCostMatrix;\n}\n\n// TODO: Subtract the D(x,x) and D(y,y) parts from this.\ndouble approx_wasserstein(double* C, int len_i, int len_j, double eps, double stopErr)\n{\n  Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> costMatrix(C, len_i, len_j);\n\n  double r = 1.0 / len_i;\n  double c = 1.0 / len_j;\n\n  Eigen::MatrixXd K = Eigen::exp(-costMatrix.array() / eps);\n  Eigen::MatrixXd Kp = len_i * K.array();\n\n  Eigen::VectorXd u = Eigen::VectorXd::Ones(len_i) / len_i;\n  Eigen::VectorXd v = Eigen::VectorXd::Ones(len_j) / len_j;\n\n  int maxIter = 10000;\n  for (int iter = 0; iter < maxIter; iter++) {\n\n    v = c / (K.transpose() * u).array();\n    u = 1.0 / (Kp * v).array();\n\n    if (iter % 10 == 0) {\n      // Compute right marginal (diag(u) K diag(v))^T1\n      Eigen::VectorXd tempColSums = (u.asDiagonal() * K * v.asDiagonal()).colwise().sum();\n      double LInfErr = (tempColSums.array() - c).abs().maxCoeff();\n      if (LInfErr < stopErr) {\n        break;\n      }\n    }\n  }\n\n  Eigen::MatrixXd transportPlan = u.asDiagonal() * K * v.asDiagonal();\n  double dist = (transportPlan.array() * costMatrix.array()).sum();\n  return dist;\n}\n\ndouble wasserstein(double* C, int len_i, int len_j)\n{\n  // Create vectors which are just 1/len_i and 1/len_j of length len_i and len_j.\n  auto w_1 = std::make_unique<double[]>(len_i);\n  std::fill_n(w_1.get(), len_i, 1.0 / len_i);\n  auto w_2 = std::make_unique<double[]>(len_j);\n  std::fill_n(w_2.get(), len_j, 1.0 / len_j);\n\n  int maxIter = 10000;\n  double cost;\n  EMD_wrap(len_i, len_j, w_1.get(), w_2.get(), C, &cost, maxIter);\n  return cost;\n}\n\nDistanceIndexPairs wasserstein_distances(int Mp_i, const Options& opts, const Manifold& M, const Manifold& Mp,\n                                         std::vector<int> inpInds)\n{\n  std::vector<int> inds;\n  std::vector<double> dists;\n\n  // Compare every observation in the M manifold to the\n  // Mp_i'th observation in the Mp manifold.\n  for (int i : inpInds) {\n    int len_i, len_j;\n    auto C = wasserstein_cost_matrix(M, Mp, i, Mp_i, opts, len_i, len_j);\n\n    if (len_i > 0 && len_j > 0) {\n      double dist_i = wasserstein(C.get(), len_i, len_j);\n\n      // Alternatively, the approximate version based on Sinkhorn's algorithm can be called with something like:\n      // double dist_i = approx_wasserstein(C.get(), len_i, len_j, 0.1, 0.1)\n      // In that case, the \"std::isnormal\" is really needed on the next line, as some\n      // instability gives us some 'nan' distances using that method.\n\n      if (dist_i != 0 && std::isnormal(dist_i)) {\n        dists.push_back(dist_i);\n        inds.push_back(i);\n      }\n    }\n  }\n\n  return { inds, dists };\n}", "meta": {"hexsha": "afb3640e7ca0e937f8337b1d5abcc64f525d325d", "size": 11489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/distances.cpp", "max_stars_repo_name": "9prady9/EDM", "max_stars_repo_head_hexsha": "db89a7fecf5a0f30b9db2b913a4d82f3c4ced33c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/distances.cpp", "max_issues_repo_name": "9prady9/EDM", "max_issues_repo_head_hexsha": "db89a7fecf5a0f30b9db2b913a4d82f3c4ced33c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distances.cpp", "max_forks_repo_name": "9prady9/EDM", "max_forks_repo_head_hexsha": "db89a7fecf5a0f30b9db2b913a4d82f3c4ced33c", "max_forks_repo_licenses": ["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.9174917492, "max_line_length": 117, "alphanum_fraction": 0.6049264514, "num_tokens": 3317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583167, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6151907752116932}}
{"text": "/* Enlarges source image trying to estimate missing pixels - Quadratic Model\n   (c) 2016, Eduardo Valle, blog.eduardovalle.com/\n*/\n#include <cassert>\n#include <iostream>\n#include <map>\n\n// #define SOLVER_SPARSE\n#include <Eigen/Core>\n#ifdef SOLVER_SPARSE\n    #include <Eigen/Sparse>\n    typedef Eigen::Triplet<double> Triplet;\n#else\n    #include <Eigen/Dense>\n#endif\n\n#include <gd.h>\n\n\nusing namespace std;\n\n/* Main function */\nint main(int argc, char *argv[]) {\n\n    // Check command-line and open source image\n    const int nParamsMin = 2;\n    const int nParamsMax = 8;\n    if ( argc <= nParamsMin || argc>(nParamsMax+1) ) {\n        cerr << \"Usage: \" << argv[0]\n             << \" <in.png> <out.png> [<dom>] [<asp>] [H up] [V up] [gweight] [toler]\" << endl\n             << endl\n             << \"   in.png    Input image in PNG format (mandatory)\" << endl\n             << \"   out.png   Output image in PNG format (mandatory)\" << endl\n             << \"   dom       Pixel connectedness domain: 4 or 8 (def: 4)\" << endl\n             << \"   asp       Pixel aspect ratio width/height (def: 1.0)\" << endl\n             << \"   H up      How much to upscale the image horizontally (def: 3)\" << endl\n             << \"   V up      How much to upscale the image vertically (def: 3)\" << endl\n             << \"   gweight   Relative importance of respecting data (def: 1.0 = neutral)\" << endl\n             << \"   toler     Graylevel difference for  equal pixels (def: 0, max: 255)\" << endl\n             << endl\n             << \"   Optional parameters must be entered in the right sequence\" << endl\n             << endl\n             #ifdef SOLVER_SPARSE\n                 << \"   Solver: Eigen::SparseQR\" << endl\n             #else\n                 << \"   Solver: Eigen::HouseholderQR\" << endl\n             #endif\n             << endl;\n        return 1;\n    }\n    FILE *infile = fopen(argv[1], \"r\");\n    if (infile == NULL) {\n        cerr << \"Error opening:\" << argv[1] << endl;\n        return 1;\n    }\n    gdImagePtr simage = gdImageCreateFromPng(infile);\n    fclose(infile);\n    if (simage == NULL) {\n        cerr << \"Error reading:\" << argv[1] << endl;\n        return 1;\n    }\n    const int w = simage->sx;\n    const int h = simage->sy;\n\n    // Are pixel and sample neighborhoods 4-connected or 8-connected ?\n    const int connectedness = (argc <= 3) ? 4 : atoi(argv[3]);\n    if (connectedness!=4 && connectedness!=8) {\n        cerr << \"Connectedness domain must be 4 or 8: \" << argv[3] << endl;\n        return 1;\n    }\n    const bool  four = (connectedness == 4);\n\n    // What is the relative importance of neighbors\n    const float aspect     = (argc <= 4) ? 1.0 : atof(argv[4]);\n    if (aspect <= 0.0f) {\n        cerr << \"Aspect ratio must be >= 0.0: \" << argv[4] << endl;\n        return 1;\n    }\n    const float weightV    = 1.0;\n    const float weightH    = pow(1.0/aspect, 2.0);\n    const float weightD    = 1.0/(1.0 + aspect*aspect);\n\n    // Horizontal, vertical, and surface ampliation\n    const int   upX        = (argc <= 5) ? 3 : atoi(argv[5]);\n    const int   upY        = (argc <= 6) ? 3 : atoi(argv[6]);\n    if (upX < 1) {\n        cerr << \"Horizontal upscaling must be 1 or greater: \" << argv[5] << endl;\n        return 1;\n    }\n    if (upY < 1) {\n        cerr << \"Vertical upscaling must be 1 or greater: \" << argv[6] << endl;\n        return 1;\n    }\n    const int   up2D       = upX*upY;\n\n    // Relative importance of attachment to graylevels\n    const float grayWeight = up2D * ((argc <= 7) ? 1.0 : atof(argv[7]));\n    if (grayWeight <= 0.0) {\n        cerr << \"Grayscale attachment weight must be > 0.0: \" << argv[7] << endl;\n        return 1;\n    }\n\n    // Tolerance for pixels be considered equal\n    const float tolerance = (argc <= 8) ? 1.0 : atof(argv[8]);\n    if (tolerance < 0.0) {\n        cerr << \"Pixel difference tolerance must be >= 0.0: \" << argv[8] << endl;\n        return 1;\n    }\n\n    // First pass : reads pixels matrix and count the number of needed variables\n    const int ws = w+2;\n    const int hs = h+2;\n    float samples[hs][ws],\n          lp = 0.0f;\n    int   hotEstimate = 0;\n    for (int y=0, ys=1; y<h; y++, ys++) {\n        for (int x=0, xs=1; x<w; x++, xs++) {\n            const int rgb = gdImageGetTrueColorPixel(simage, x, y);\n            const float r = rgb >> 16 & 0xff;\n            const float g = rgb >> 8  & 0xff;\n            const float b = rgb       & 0xff;\n            // Luminance coefficient for each color\n            const float rl = 0.21f;\n            const float gl = 0.72f;\n            const float bl = 0.07f;\n            const float l = r*rl + g*gl + b*bl;\n            // Destination pixels\n            samples[ys][xs] = l;\n            hotEstimate += (abs(l-lp)>tolerance) ? 1 : 0;\n        }\n    }\n    // ...correct borders (tries to create uniform border) to ease processing\n    for (int ys=0; ys<hs; ys++) {\n        samples[ys][0   ] = samples[   1][   1];\n        samples[ys][ws-1] = samples[hs-2][ws-2];\n    }\n    for (int xs=0; xs<ws; xs++) {\n        samples[   0][xs] = samples[   1][   1];\n        samples[hs-1][xs] = samples[hs-2][ws-2];\n    }\n\n    gdImageDestroy(simage);\n\n    cerr << \"Hot pixels estimate: \" << hotEstimate << endl;\n\n    // Second pass : assembles list of the hot pixels :\n    // those which are not equal to their neighbors\n    map<pair<int, int>, int> hotMap;\n    int hotCount = 0;\n    for (int ys=1; ys<hs-1; ys++) {\n        for (int xs=1; xs<ws-1; xs++) {\n            if ((abs(samples[ys][xs] - samples[ys+1][xs+1]) > tolerance) ||\n                (abs(samples[ys][xs] - samples[ys+1][xs  ]) > tolerance) ||\n                (abs(samples[ys][xs] - samples[ys+1][xs-1]) > tolerance) ||\n                (abs(samples[ys][xs] - samples[ys  ][xs+1]) > tolerance) ||\n                (abs(samples[ys][xs] - samples[ys  ][xs-1]) > tolerance) ||\n                (abs(samples[ys][xs] - samples[ys-1][xs+1]) > tolerance) ||\n                (abs(samples[ys][xs] - samples[ys-1][xs  ]) > tolerance) ||\n                (abs(samples[ys][xs] - samples[ys-1][xs-1]) > tolerance)) {\n                hotMap.insert(make_pair(make_pair(xs, ys), hotCount));\n                hotCount++;\n            }\n        }\n    }\n\n    cerr << \"Hot pixels count: \" << hotCount << endl;\n\n    // Assembles optimization matrix...\n\n    // The optimization we'll attempt tries to minimize the quadradic\n    // difference between neighboring subsamples, while constraining all\n    // subsamples inside a pixel to average to the given pixel. I.e.:\n    // If subsamples si,1 to si,n belong to pi, we are trying to minimize\n    // Sum_{for all neighboring subsample pairs s_1 s_2 } (s_1 - s_2)^2\n    // constrained to : For all pixels p_i :\n    // Avg_{for all subsamples s_i,j of pixel pi} si,j = pi\n\n    // The optimization above leads to an overdetermined linear system:\n    // 1) One equation per pixel for the averaging constraint\n    // 2) One equation per subsample for the quadratic minimization that\n    //    attains its mininimum when each subsample is the average of its\n    //    neighbors\n\n    const int vars    =  hotCount*up2D;\n    const int eqns    =  hotCount*up2D                 + hotCount;\n    const int nonzero = (hotCount*up2D)*(four ? 4 : 8) + (hotCount*up2D);\n    cerr << \"Optimizing : \" << vars\n             << \" variables and \" << eqns\n             << \" equations. \" << nonzero\n             << \" non-zero entries / \" << ( ((float)vars)*eqns )\n             << \" total (\" << ( ((float) nonzero)/vars/eqns*100.0 )\n             << \"%)\"  << endl;\n\n    #ifdef SOLVER_SPARSE\n        cerr << \"Using sparse matrices\" << endl;\n        std::vector<Triplet> triplets(nonzero);\n        Eigen::SparseMatrix<float> optimization(eqns, vars);\n    #else\n        cerr << \"Using dense matrices\" << endl;\n        Eigen::MatrixXf optimization(eqns, vars);\n        optimization.setZero();\n    #endif\n    Eigen::VectorXf targets(eqns);\n\n\n    // ...variable index for subsample at position (u,v) of the pixel (x,y)\n    auto varindex = [&](int i, int u, int v) -> int  {\n        assert(i>=0 && i<hotCount && u>=0 && u<upX && v>=0 && v<upY);\n        return i*up2D + v*upX+u;\n    };\n    auto findpix = [&](int x, int y) -> int {\n        assert(x>=0 && x<ws && y>=0 && y<hs);\n        try {\n            return hotMap.at(make_pair(x, y));\n        }\n        catch(out_of_range e) {\n            return -1;\n        }\n    };\n\n    // ...assemble the graylevel constraints\n    cerr << \"Assembling graylevel constraints... \" << endl;\n    for (auto pixel : hotMap) {\n        const int x = pixel.first.first;\n        const int y = pixel.first.second;\n        const int i = pixel.second;\n        // The constraint is for the average of the subsamples to\n        // be the graylevel of the pixel\n        for (int v=0; v<upY; v++) {\n            for (int u=0; u<upX; u++) {\n                const int var   = varindex(i, u, v);\n                const float val = (1.0f / up2D) * grayWeight;\n                #ifdef SOLVER_SPARSE\n                    triplets.push_back(Triplet(i, var, val));\n                #else\n                    optimization(i, var) = val;\n                #endif\n            }\n        }\n        targets(i) = samples[y][x] * grayWeight;\n    }\n    int eqn = hotCount;\n\n    // ...assemble the quadratic minimizations\n    cerr << \"Assembling quadratic minimizers... \" << endl;\n    for (auto pixel : hotMap) {\n        const int x = pixel.first.first;\n        const int y = pixel.first.second;\n        const int i = pixel.second;\n\n        // Finds neighboring pixels\n        const int iLU = four ? -1 : findpix(x-1, y-1);\n        const int iL  =             findpix(x-1, y  );\n        const int iLD = four ? -1 : findpix(x-1, y+1);\n        const int iU  =             findpix(x  , y-1);\n        const int iD  =             findpix(x  , y+1);\n        const int iRU = four ? -1 : findpix(x+1, y-1);\n        const int iR  =             findpix(x+1, y  );\n        const int iRD = four ? -1 : findpix(x+1, y+1);\n\n        // Finds variable corresponding to subsample at u+m,v+n\n        // n, m = {-1, 0, 1}\n        auto neighbor = [&](int u, int v, int m, int n) -> int {\n            assert(u>=0 && u<upX && v>=0 && v<upY && m>=-1 && m<=1 && n>=-1 && n<=1);\n            int nu = u+m, nv = v+n;\n            // Safe cases : neighbor is in same pixel\n            if (nu>=0 && nu<upX && nv>=0 && nv<upY) {\n                return varindex(i, nu, nv);\n            }\n            // Problematic cases : neighbor is accross pixels\n            int ni = -1;\n            if (nu < 0) {\n                if (nv <    0) { ni = iLU; nu = upX-1; nv = upY-1; } else\n                if (nv >= upY) { ni = iLD; nu = upX-1; nv =     0; } else\n                               { ni = iL ; nu = upX-1; }\n            }\n            else if (nu >= upX) {\n                if (nv <    0) { ni = iRU; nu =     0; nv = upY-1; } else\n                if (nv >= upY) { ni = iRD; nu =     0; nv =     0; } else\n                               { ni = iR ; nu =     0; }\n            }\n            else {\n                if (nv <    0) { ni = iU ; nv = upY-1; } else\n                if (nv >= upY) { ni = iD ; nv =     0; } else\n                               { assert(false); }\n            }\n            if (ni == -1) {\n                return -2;\n            }\n            const int si = varindex(ni, nu, nv);\n            assert(si != -1);\n            return si;\n        };\n\n        // Create constraint equations for all subsamples\n        for (int v=0; v<upY; v++) {\n            for (int u=0; u<upX; u++) {\n                // Finds neighboring subsamples\n                const int sLU = four ? -3 : neighbor(u, v, -1, -1);\n                const int sL  =             neighbor(u, v, -1,  0);\n                const int sLD = four ? -3 : neighbor(u, v, -1,  1);\n                const int sU  =             neighbor(u, v,  0, -1);\n                const int sD  =             neighbor(u, v,  0,  1);\n                const int sRU = four ? -3 : neighbor(u, v,  1, -1);\n                const int sR  =             neighbor(u, v,  1,  0);\n                const int sRD = four ? -3 : neighbor(u, v,  1,  1);\n                // Counts neighbors\n                const float norm =\n                    ( (sLU >= 0) ? weightD : 0.0f ) +\n                    ( (sL  >= 0) ? weightH : 0.0f ) +\n                    ( (sLD >= 0) ? weightD : 0.0f ) +\n                    ( (sU  >= 0) ? weightV : 0.0f ) +\n                    ( (sD  >= 0) ? weightV : 0.0f ) +\n                    ( (sRU >= 0) ? weightD : 0.0f ) +\n                    ( (sR  >= 0) ? weightH : 0.0f ) +\n                    ( (sRD >= 0) ? weightD : 0.0f );\n                // The constraint is for each subsample to be the average\n                // of the neighboring subsamples\n                #ifdef SOLVER_SPARSE\n                    triplets.push_back( Triplet(eqn, varindex(i, u, v), -1.0f) );\n                    if (sLU >= 0) { triplets.push_back( Triplet(eqn, sLU, weightD / norm) ); }\n                    if (sL  >= 0) { triplets.push_back( Triplet(eqn, sL , weightH / norm) ); }\n                    if (sLD >= 0) { triplets.push_back( Triplet(eqn, sLD, weightD / norm) ); }\n                    if (sU  >= 0) { triplets.push_back( Triplet(eqn, sU , weightV / norm) ); }\n                    if (sD  >= 0) { triplets.push_back( Triplet(eqn, sD , weightV / norm) ); }\n                    if (sRU >= 0) { triplets.push_back( Triplet(eqn, sRU, weightD / norm) ); }\n                    if (sR  >= 0) { triplets.push_back( Triplet(eqn, sR , weightH / norm) ); }\n                    if (sRD >= 0) { triplets.push_back( Triplet(eqn, sRD, weightD / norm) ); }\n                #else\n                    optimization(eqn, varindex(i, u, v)) = -1.0f;\n                    if (sLU >= 0) { optimization(eqn, sLU) = weightD / norm; }\n                    if (sL  >= 0) { optimization(eqn, sL ) = weightH / norm; }\n                    if (sLD >= 0) { optimization(eqn, sLD) = weightD / norm; }\n                    if (sU  >= 0) { optimization(eqn, sU ) = weightV / norm; }\n                    if (sD  >= 0) { optimization(eqn, sD ) = weightV / norm; }\n                    if (sRU >= 0) { optimization(eqn, sRU) = weightD / norm; }\n                    if (sR  >= 0) { optimization(eqn, sR ) = weightH / norm; }\n                    if (sRD >= 0) { optimization(eqn, sRD) = weightD / norm; }\n                #endif\n                targets(eqn) = 0.0f;\n                eqn++;\n            }\n        }\n    }\n\n    // ...showtime ! --- solve the humungous system\n    cerr << \"Showtime !\" << endl;\n    Eigen::VectorXf subsamples(vars);\n    #ifdef SOLVER_SPARSE\n        optimization.setFromTriplets(triplets.begin(), triplets.end());\n        optimization.makeCompressed(); // Requirement of SparseQR\n        Eigen::SparseQR<Eigen::SparseMatrix<float>, Eigen::COLAMDOrdering<int> > solver;\n        solver.compute(optimization);\n        if (solver.info() != Eigen::Success) {\n            cerr << \"Matrix decomposition failed\" << endl;\n            return 1;\n        }\n        subsamples = solver.solve(targets);\n        if(solver.info() != Eigen::Success) {\n            cerr << \"Solver failed\" << endl;\n            return 1;\n        }\n    #else\n        Eigen::HouseholderQR<Eigen::MatrixXf> solver;\n        solver.compute(optimization);\n        subsamples = solver.solve(targets);\n    #endif\n    // DEBUG :\n    // Eigen::JacobiSVD<Eigen::MatrixXf>\n    //    solver(optimization, Eigen::ComputeThinU | Eigen::ComputeThinV); // +precise, but ++slower\n    // cout << optimization << endl;\n    // cout << targets << endl;\n\n\n    // Prepares destination image\n    cerr << \"Preparing output...\" << endl;\n    const int wu = (int) (w * upX);\n    const int hu = (int) (h * upY);\n    gdImagePtr dimage = gdImageCreateTrueColor(wu, hu);\n    if (dimage == NULL) {\n        fprintf(stderr, \"Not enough memory.\\n\");\n        return 1;\n    }\n    int gray[256];\n    for (int l=0; l<256; l++) {\n        gray[l] = gdImageColorAllocate(dimage, l, l, l);\n    }\n\n    // DEBUG :\n    // int gray2[256];\n    // for (int l=0; l<256; l++) {\n    //     gray2[l] = gdImageColorAllocate(dimage, l, (int) (0.8f*l), l);\n    // }\n\n    // Second pass : resample image\n    for (int y=0, yu=0; y<h; y++, yu+=upY) {\n        for (int x=0, xu=0; x<w; x++, xu+=upX) {\n            int i = findpix(x+1, y+1);\n            for (int v=0; v<upY; v++) {\n                for (int u=0; u<upX; u++) {\n                    int l;\n                    if (i >= 0) {\n                        // Hot pixels were estimated by the optimizer\n                        l = subsamples( varindex(i, u, v) );\n                    }\n                    else {\n                        // Cold pixels come from flat areas and are copied from the samples\n                        l = samples[y+1][x+1];\n                    }\n                    l = (l < 0) ? 0 : ( (l>255) ? 255 : l );\n                    gdImageSetPixel(dimage, xu+u, yu+v, gray[l]);\n                    // gdImageSetPixel(dimage, xu+u, yu+v, i>=0 ? gray[l] : gray2[l]); // DEBUG\n                }\n            }\n        }\n    }\n\n    // Save results to output file\n    FILE *outfile = fopen(argv[2], \"w\");\n    if (outfile == NULL) {\n        cerr << \"Error opening: \" << argv[2] << endl;\n        return 1;\n    }\n    gdImagePng(dimage, outfile);\n    fclose(outfile);\n    gdImageDestroy(dimage);\n    return 0;\n}\n", "meta": {"hexsha": "075314bc31196cf2cca4a5462f382855b972212f", "size": 17304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pixel-estimate-quadratic.cpp", "max_stars_repo_name": "dreavjr/subpixel-zoom", "max_stars_repo_head_hexsha": "7358449ed2aa41974bf80309a454471511124c1c", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-27T21:18:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-14T15:52:36.000Z", "max_issues_repo_path": "pixel-estimate-quadratic.cpp", "max_issues_repo_name": "dreavjr/subpixel-zoom", "max_issues_repo_head_hexsha": "7358449ed2aa41974bf80309a454471511124c1c", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pixel-estimate-quadratic.cpp", "max_forks_repo_name": "dreavjr/subpixel-zoom", "max_forks_repo_head_hexsha": "7358449ed2aa41974bf80309a454471511124c1c", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3356643357, "max_line_length": 100, "alphanum_fraction": 0.4855524734, "num_tokens": 5044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931457, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6151907690200081}}
{"text": "/**\n * cubature_kalman_filter.hpp\n * @author wendao\n * 20/12/6\n **/\n#ifndef KKL_CUBATURE_KALMAN_FILTER_X_HPP\n#define KKL_CUBATURE_KALMAN_FILTER_X_HPP\n\n#include <random>\n#include <Eigen/Dense>\n#include <kalman/kalman_filter.hpp>\n\n/**\n * @brief Cubature Kalman Filter class\n * @param T        scaler type\n * @param System   system class to be estimated\n */\ntemplate<typename T, class System>\nclass CubatureKalmanFilterX : public KalmanFilter<T, System>\n{\n  typedef Eigen::Matrix<T, Eigen::Dynamic, 1> VectorXt;    //\u5217\u5411\u91cf\n  typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> MatrixXt;\n  using KalmanFilter<T, System>::state_dim;\n  using KalmanFilter<T, System>::N;\n  using KalmanFilter<T, System>::input_dim;\n  using KalmanFilter<T, System>::measurement_dim;\n  using KalmanFilter<T, System>::M;\n  using KalmanFilter<T, System>::mean;\n  using KalmanFilter<T, System>::cov;\n  using KalmanFilter<T, System>::system;\n  using KalmanFilter<T, System>::process_noise;\n  using KalmanFilter<T, System>::measurement_noise;\n  using KalmanFilter<T, System>::kalman_gain;\n\npublic:\n  /**\n   * @brief constructor\n   * @param system               system to be estimated\n   * @param state_dim            state vector dimension\n   * @param input_dim            input vector dimension\n   * @param measurement_dim      measurement vector dimension\n   * @param process_noise        process noise covariance (state_dim x state_dim)\n   * @param measurement_noise    measurement noise covariance (measurement_dim x measuremend_dim)\n   * @param mean                 initial mean\n   * @param cov                  initial covariance\n   */\n  CubatureKalmanFilterX(const System& _system, int _state_dim, int _input_dim, int _measurement_dim, \n                 const MatrixXt& _process_noise, const MatrixXt& _measurement_noise, \n                 const VectorXt& _mean, const MatrixXt& _cov):\n    KalmanFilter<T, System>(_system, _state_dim, _input_dim, _measurement_dim, _process_noise, _measurement_noise, _mean, _cov),\n    S(2 * _state_dim) //\u5bb9\u79ef\u70b9\u4e2a\u6570\n  {\n    \n    weights.resize(S, 1);\n    cubature_points.resize(S, N);\n    ext_weights.resize(2*(N+M), 1);\n    ext_cubature_points.resize(2*(N+M), N + M);\n    expected_measurements.resize(2*(N+M), M);\n\n    // initialize weights for cubature filter\n    for (int i = 0; i < S; i++)\n      weights[i] = 1.0 / S;\n\n    // weights for extended state space which includes error variances\n    for (int i = 0; i < 2*(N+M); i++)\n      ext_weights[i] = 1.0 / 2*(N+M);\n      \n  }\n\n  /**\n   * @brief predict  \u9884\u6d4b\u51fd\u6570\n   * @param control  input vector\n   */\n  virtual void predict(const VectorXt& control) override\n  {\n    // calculate cubature points\n    ensurePositiveFinite(cov);\n    computeCubaturePoints(mean, cov, cubature_points); //\u6839\u636e\u4e0a\u4e00\u65f6\u523b\u7684\u5747\u503c\u548c\u65b9\u5dee\u8ba1\u7b97cubature\u70b9\n    for (int i = 0; i < S; i++) {\n      cubature_points.row(i) = system.f(cubature_points.row(i), control); //\u6839\u636e\u7cfb\u7edf\u65b9\u7a0b\u4f20\u64adcubature\u70b9\n    }\n\n    const auto& Q = process_noise; //\u7cfb\u7edf\u566a\u58f0|\u8fc7\u7a0b\u566a\u58f0\n\n    // unscented transform\n    VectorXt mean_pred(mean.size());\n    MatrixXt cov_pred(cov.rows(), cov.cols());\n\n    mean_pred.setZero();\n    cov_pred.setZero();\n    for (int i = 0; i < S; i++) {\n      mean_pred += weights[i] * cubature_points.row(i);   //\u4f20\u64ad\u540e\u7684cubature\u70b9\u96c6\u5747\u503c\n    }\n    for (int i = 0; i < S; i++) \n      cov_pred += weights[i] * cubature_points.row(i).transpose() * cubature_points.row(i);\n    cov_pred -= mean_pred.transpose() * mean_pred; //\u4f20\u64ad\u540e\u7684cubature\u70b9\u96c6\u65b9\u5dee\n    cov_pred += Q;                                      //\u52a0\u4e0a\u8fc7\u7a0b\u566a\u58f0\n\n    //\u5f97\u5230\u9884\u6d4b\u503c\u548c\u9884\u6d4b\u534f\u65b9\u5dee\n    mean = mean_pred;\n    cov = cov_pred;\n  }\n\n  /**\n   * @brief correct      \u6821\u6b63\u51fd\u6570\n   * @param measurement  \u89c2\u6d4b\u503c\n   */\n  virtual void correct(const VectorXt& measurement) override\n  {\n    // create extended state space which includes error variances\n    VectorXt ext_mean_pred = VectorXt::Zero(N + M, 1);\n    MatrixXt ext_cov_pred = MatrixXt::Zero(N + M, N + M);\n    ext_mean_pred.topLeftCorner(N, 1) = VectorXt(mean);\n    ext_cov_pred.topLeftCorner(N, N) = MatrixXt(cov);\n    ext_cov_pred.bottomRightCorner(M, M) = measurement_noise;\n\n    ensurePositiveFinite(ext_cov_pred);\n    computeCubaturePoints(ext_mean_pred, ext_cov_pred, ext_cubature_points); //\u6839\u636e\u9884\u6d4b\u5747\u503c\u548c\u534f\u65b9\u5dee\u4ee5\u53ca\u6d4b\u91cf\u566a\u58f0\u8ba1\u7b97cubature\u70b9\n                                                                             //\u6b64\u65f6\u6d4b\u91cf\u8bef\u5dee\u5e76\u672a\u6dfb\u52a0\u5230cubature\u4e3b\u4f53,\u800c\u662f\u5b58\u653e\u4e8e\u62d3\u5c55\u90e8\u5206\n\n    // cubature transform\n    expected_measurements.setZero();\n    for (int i = 0; i < ext_cubature_points.rows(); i++) {\n      expected_measurements.row(i) = system.h(ext_cubature_points.row(i).transpose().topLeftCorner(N, 1));     //\u89c2\u6d4b\u65b9\u7a0b\u4f20\u64adcubature\u70b9\u96c6\n      expected_measurements.row(i) += VectorXt(ext_cubature_points.row(i).transpose().bottomRightCorner(M, 1));//\u6dfb\u52a0\u6d4b\u91cf\u566a\u58f0\n    }\n\n    VectorXt expected_measurement_mean = VectorXt::Zero(M);\n    for (int i = 0; i < ext_cubature_points.rows(); i++) {\n      expected_measurement_mean += ext_weights[i] * expected_measurements.row(i);  //\u4f20\u64ad\u540e\u7684cubature\u70b9\u96c6\u5747\u503c\n    }\n    MatrixXt expected_measurement_cov = MatrixXt::Zero(M, M);\n    for (int i = 0; i < ext_cubature_points.rows(); i++)\n      expected_measurement_cov += ext_weights[i] * expected_measurements.row(i).transpose() * expected_measurements.row(i);        \n\n    expected_measurement_cov -= expected_measurement_mean.transpose() * expected_measurement_mean; //\u4f20\u64ad\u540e\u7684cubature\u70b9\u96c6\u65b9\u5dee\n    expected_measurement_cov += measurement_noise;  //R = measurement_noise\n\n    // calculated transformed covariance\n    MatrixXt cross_cov = MatrixXt::Zero(N, M); //\u4e92\u534f\u65b9\u5dee\n    for(int i=0; i<S; ++i)\n      cross_cov += ext_weights[i] * ext_cubature_points.row(i).transpose() * expected_measurements.row(i);\n    cross_cov -= ext_mean_pred * expected_measurement_mean;\n\n    kalman_gain = cross_cov * cross_cov.inverse(); //\u5361\u5c14\u66fc\u589e\u76ca\n\n    VectorXt ext_mean = ext_mean_pred + kalman_gain * (measurement - expected_measurement_mean); //\u6700\u4f18\u4f30\u8ba1\n    MatrixXt ext_cov = ext_cov_pred - kalman_gain * expected_measurement_cov * kalman_gain.transpose();    //\u6700\u4f18\u4f30\u8ba1\u7684\u534f\u65b9\u5dee\n\n    mean = ext_mean.topLeftCorner(N, 1);\n    cov = ext_cov.topLeftCorner(N, N);\n  }\n\n  const MatrixXt& getSamplePoints() const { return cubature_points; }\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n  const int S;  //\u5bb9\u79ef\u70b9\u4e2a\u6570\n\npublic:\n  VectorXt weights;          //\u5bb9\u79ef\u70b9\u6743\u91cd,2N\u4e2a\u5bb9\u79ef\u70b9\uff0c\u6743\u91cd\u76f8\u540c\n  MatrixXt cubature_points;  //\u5bb9\u79ef\u70b9\n\n  VectorXt ext_weights;\n  MatrixXt ext_cubature_points;\n  MatrixXt expected_measurements;\n\nprivate:\n  /**\n   * @brief compute cubature points\n   * @param mean          mean\n   * @param cov           covariance\n   * @param cubature_points  calculated cubature points\n   */\n  void computeCubaturePoints(const VectorXt& mean, const MatrixXt& cov, MatrixXt& cubature_points) {\n    const int n = mean.size(); //\u72b6\u6001\u7ef4\u5ea6\n    assert(cov.rows() == n && cov.cols() == n);\n\n    Eigen::LLT<MatrixXt> llt(cov);\n    MatrixXt P_chol = llt.matrixL();\n    MatrixXt l = P_chol * sqrt(n);\n\n    for (int i = 0; i < n; i++) {\n      cubature_points.row(  i) = mean + l.col(i);\n      cubature_points.row(n+i) = mean - l.col(i);\n    }\n  }\n\n\n};\n\n\n#endif\n", "meta": {"hexsha": "9813eb64e0e3e65104b0844f948ad7d8fb94a5ce", "size": 6971, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kalman/cubature_kalman_filter.hpp", "max_stars_repo_name": "CastielLiu/hdl_localization", "max_stars_repo_head_hexsha": "c958f78b0dc2dd2eeb9a50aad9eff0f23e662ab2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/kalman/cubature_kalman_filter.hpp", "max_issues_repo_name": "CastielLiu/hdl_localization", "max_issues_repo_head_hexsha": "c958f78b0dc2dd2eeb9a50aad9eff0f23e662ab2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/kalman/cubature_kalman_filter.hpp", "max_forks_repo_name": "CastielLiu/hdl_localization", "max_forks_repo_head_hexsha": "c958f78b0dc2dd2eeb9a50aad9eff0f23e662ab2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9329896907, "max_line_length": 131, "alphanum_fraction": 0.6684837183, "num_tokens": 2093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.6723317123102956, "lm_q1q2_score": 0.6151169209846699}}
{"text": "#include <iostream>\n#include <stack>\n#include <vector>\n#include <list>\n\n#include <boost/range/algorithm_ext/erase.hpp>\n\ntemplate <class T>\nclass QStack : public std::stack<T>\n{\n  public:\n    T take() {\n        T v = this->top();\n        this->pop();\n        return v;\n    }\n\n    T takeBottom() {\n        T v = this->c.front();\n        this->c.pop_front();\n        return v;\n    }\n\n    void print() const\n    {\n        for (auto && v : this->c)\n            std::cout << v << \"\\t\";\n        std::cout << std::endl;\n    }\n};\n\n// Stack of Plates. Composite stack behaves as usual stack\nnamespace SoP\n{\n    template <class T>\n    class CompositeStack\n    {\n    public:\n        void push(T const& t)\n        {\n            if (m_stacks.empty() || m_stacks.back().size() == capacity())\n                m_stacks.emplace_back(QStack<T>());\n\n            m_stacks.back().push(t);\n        }\n\n        T take()\n        {\n            if (empty())\n                throw std::logic_error(\"The compoiste stack is empty.\");\n\n            auto &&back = m_stacks.back();\n            T v = back.take();\n            if (back.empty())\n                m_stacks.erase(--std::end(m_stacks));\n            return v;\n        }\n\n        T takeAt(std::size_t index)\n        {\n            if (index >= m_stacks.size())\n                throw std::logic_error(\"Cannot take from this stack.\");\n\n            return leftShift(index, true /*removeTop*/);\n        }\n\n        bool empty() const { return m_stacks.empty(); }\n\n        static std::size_t capacity() { return 3; }\n\n    private:\n        T leftShift(std::size_t index, bool removeTop)\n        {\n            auto &&stack = m_stacks.at(index);\n            T removedItem = removeTop ? stack.take() : stack.takeBottom();\n            if (stack.empty())\n                boost::range::remove_erase(m_stacks, stack);\n            else if (m_stacks.size() > index + 1)  {// not last element\n                T v = leftShift(index + 1, false /*remove top*/);\n                stack.push(v);\n            }\n\n            return removedItem;\n        }\n\n        std::vector<QStack<T>> m_stacks;\n    };\n\n    using IntCompositeStack = CompositeStack<int>;\n}\n\n// Implement Queue via two stacks\nnamespace tsq\n{\n    template <class T>\n    class Queue\n    {\n    public:\n        std::size_t size() const { return m_oldest.size() + m_newest.size(); }\n\n        void add(T const& e)\n        {\n            // Newest stack always has new element on top\n            m_newest.push(e);\n        }\n\n\n        T & peek() { return const_cast<T&>(const_cast<Queue<T> *>(this)->peek()); }\n        T const& peek() const\n        {\n            shiftStacks();\n            return m_oldest.top();\n        }\n\n        T take()\n        {\n            shiftStacks();\n            return m_oldest.take();\n        }\n\n    private:\n        /// Moves elements from newest stack to oldest\n        void shiftStacks() const\n        {\n            if (m_oldest.empty())\n                while (!m_newest.empty())\n                    m_oldest.push(m_newest.take());\n        }\n\n        mutable QStack<T> m_oldest;\n        mutable QStack<T> m_newest;\n    };\n\n    using IntQueue = Queue<int>;\n}\n\n// Implement sorted stack with using two stacks\nnamespace ss\n{\n    template <class T>\n    class SortedStack\n    {\n    public:\n        T const & peek() const { return m_stack.pop(); }\n        T  & peek() { return m_stack.top(); }\n\n        T take() { return m_stack.take(); }\n\n        void push(T const& v)\n        {\n            m_stack.push(v);\n            sort();\n        }\n\n        bool empty() const { return m_stack.empty(); }\n\n    private:\n        void sort()\n        {\n            QStack<T> tmpStask;\n            while (!m_stack.empty()) {\n\n                // Insert each element to the s in the sorted order\n                int tmpVal = m_stack.take();\n                while (!tmpStask.empty() && tmpStask.top() > tmpVal)\n                    m_stack.push(tmpStask.take());\n\n                tmpStask.push(tmpVal);\n\n                std::cout << \"stask: \";\n                m_stack.print();\n                std::cout << \"tmp: \";\n                tmpStask.print();\n            }\n\n            // Copy elements back\n            while (!tmpStask.empty())\n                m_stack.push(tmpStask.take());\n        }\n\n        QStack<T> m_stack;\n    };\n\n    using IntStack = SortedStack<int>;\n}\n\n// Animal shelter. Implement functions to \"adopt\" the oldest animal (in general) or perticulat animal\n// (i.e. dog or cat).\nnamespace as\n{\n    struct Animal\n    {\n        std::string name;\n\n        // Easy one, we don't have any behavioural difference between dogs and cats in this model\n        enum Type { Dog, Cat };\n        Type type;\n    };\n\n    class AnimalQueue\n    {\n    public:\n        void enqueue(Animal const& animal)\n        {\n            if (animal.type == Animal::Dog)\n                m_dogs.push_back({s_animalCounter++,animal});\n            else\n                m_cats.push_back({s_animalCounter++,animal});\n        }\n\n        Animal dequeueAny()\n        {\n            if (m_dogs.empty())\n                return dequeueCat();\n\n            if (m_cats.empty())\n                return dequeueDog();\n\n            OrderedAnimal dog = m_dogs.back();\n            OrderedAnimal cat = m_cats.back();\n            if (dog.first > cat.first) {\n                m_dogs.pop_back();\n                return dog.second;\n            } else {\n                m_cats.pop_back();\n                return cat.second;\n            }\n        }\n\n        Animal dequeueDog()\n        {\n            return dequeueImpl(m_dogs);\n        }\n\n        Animal dequeueCat()\n        {\n            return dequeueImpl(m_cats);\n        }\n\n    private:\n        using OrderedAnimal = std::pair<std::size_t, Animal>;\n        using AnimalsList = std::list<OrderedAnimal>;\n\n        Animal dequeueImpl(AnimalsList & animals)\n        {\n            if (animals.empty())\n                throw std::logic_error(\"No animals of this type or at all.\");\n\n            OrderedAnimal animal = animals.back();\n            animals.pop_back();\n            return animal.second;\n        }\n\n        static std::size_t s_animalCounter;\n\n        AnimalsList m_dogs;\n        AnimalsList m_cats;\n    };\n\n    std::size_t AnimalQueue::s_animalCounter = 0;\n\n    void print(Animal const& animal)\n    {\n        std::cout << animal.name\n                  << \"\\t\"\n                  << (animal.type == Animal::Dog ? \"dog\" : \"cat\") << std::endl;\n    }\n}\n\nint main(int /*argc*/, char */*argv*/[])\n{\n    // 1\n//    SoP::IntCompositeStack intStack;\n\n//    for (std::size_t i = 0; i < 10; ++i)\n//        intStack.push(i);\n\n//    std::cout << intStack.takeAt(3) << \"\\n\" << std::endl;\n\n//    while (!intStack.empty())\n//        std::cout << intStack.take() << std::endl;\n\n    // 2\n//    tsq::IntQueue queue;\n//    for (int i = 0; i < 10; ++i)\n//        queue.add(i);\n\n//    while (queue.size() != 0)\n//        std::cout << queue.take() << std::endl;\n\n    // 3\n//    ss::IntStack s;\n//    s.push(10);\n//    s.push(3);\n//    s.push(12);\n//    s.push(7);\n//    s.push(5);\n\n//    while (!s.empty())\n//        std::cout << s.take() << std::endl;\n\n    // 4\n    as::AnimalQueue queue;\n    queue.enqueue({\"a1\", as::Animal::Dog});\n    queue.enqueue({\"a2\", as::Animal::Cat});\n    queue.enqueue({\"a3\", as::Animal::Dog});\n    queue.enqueue({\"a4\", as::Animal::Dog});\n    queue.enqueue({\"a5\", as::Animal::Cat});\n\n    try {\n        as::print(queue.dequeueAny());\n        as::print(queue.dequeueDog());\n        as::print(queue.dequeueCat());\n        as::print(queue.dequeueCat());\n    } catch (std::exception const& e) {\n        std::cout << e.what() << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "444a10e645eba69baadbc62ea82d873d98dcda6d", "size": 7638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "stacks/main.cpp", "max_stars_repo_name": "vt4a2h/alg-review", "max_stars_repo_head_hexsha": "73cd4d497163dcc42350f7f33eea78fb64768264", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stacks/main.cpp", "max_issues_repo_name": "vt4a2h/alg-review", "max_issues_repo_head_hexsha": "73cd4d497163dcc42350f7f33eea78fb64768264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stacks/main.cpp", "max_forks_repo_name": "vt4a2h/alg-review", "max_forks_repo_head_hexsha": "73cd4d497163dcc42350f7f33eea78fb64768264", "max_forks_repo_licenses": ["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.7943925234, "max_line_length": 101, "alphanum_fraction": 0.4934537837, "num_tokens": 1830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.615087097229139}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/test/unit_test.hpp>\n#include \"Tudat/Mathematics/Interpolators/linearInterpolator.h\"\n\n#include <Eigen/Core>\n\n#include \"Tudat/Basics/testMacros.h\"\n#include \"Tudat/InputOutput/matrixTextFileReader.h\"\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_linear_interpolation )\n\n// Test implementation of linear interpolation function for data vectors.\nBOOST_AUTO_TEST_CASE( test_linearInterpolation_vector )\n{\n    // Set vectors of data.\n    const Eigen::Vector3d sortedIndependentVariables( 0.0, 1.0, 3.0 );\n    const Eigen::Vector3d associatedDependentVariables( -20.0, 20.0, 21.0 );\n\n    // Test 1: Test vector data with expected result of 0.0.\n    {\n        // Set target independent value in vector data.\n        const double targetIndependentVariableValue = 0.5;\n\n        // Compute interpolation.\n        const double interpolatedValue = interpolators::computeLinearInterpolation(\n                    sortedIndependentVariables, associatedDependentVariables,\n                    targetIndependentVariableValue );\n\n        // Verify that interpolated value corresponds to expected value (0.0).\n        BOOST_CHECK_SMALL( std::fabs( interpolatedValue - 0.0 ),\n                           std::numeric_limits< double >::min( ) );\n    }\n\n    // Test 2: Test vector data with expected result of 20.5.\n\n    // Set target independent value in vector data.\n    const double targetIndependentVariableValue = 2.0;\n\n    // Compute interpolation.\n    const double interpolatedValue = interpolators::computeLinearInterpolation(\n                sortedIndependentVariables, associatedDependentVariables,\n                targetIndependentVariableValue );\n\n    // Verify that interpolated value corresponds to expected value (20.5).\n    BOOST_CHECK_SMALL( std::fabs( interpolatedValue - 20.5 ),\n                       std::numeric_limits< double >::min( ) );\n}\n\n// Test linear interpolation with map of vectors with keys as independent variable.\nBOOST_AUTO_TEST_CASE( test_linearInterpolation_map )\n{\n    // Declare map of data and vectors for map value.\n    std::map < double, Eigen::VectorXd > sortedIndepedentAndDependentVariables;\n    const Eigen::Vector3d vectorOne( 10.0, -10.0, 70.0 );\n    const Eigen::Vector3d vectorTwo( 20.0, -5.0, 80.0 );\n    const Eigen::Vector3d vectorThree( 30.0, 60.0, 90.0 );\n\n    // Set map values in map using vector data.\n    sortedIndepedentAndDependentVariables[ 0.0 ] = vectorOne;\n    sortedIndepedentAndDependentVariables[ 1.0 ] = vectorTwo;\n    sortedIndepedentAndDependentVariables[ 2.0 ] = vectorThree;\n\n    // Set target independent variable value for interpolation.\n    const double targetIndependentVariableValue = 1.5;\n\n    // Compute interpolation.\n    Eigen::Vector3d interpolatedVector = interpolators::computeLinearInterpolation(\n                sortedIndepedentAndDependentVariables,\n                targetIndependentVariableValue );\n\n    // Check that interpolated values correspond to expected elements [25, 27.5, 85].\n    BOOST_CHECK_SMALL( std::fabs( interpolatedVector( 0 ) - 25.0 ),\n                       std::numeric_limits< double >::min( ) );\n\n    BOOST_CHECK_SMALL( std::fabs( interpolatedVector( 1 ) - 27.5 ),\n                       std::numeric_limits< double >::min( ) );\n\n    BOOST_CHECK_SMALL( std::fabs( interpolatedVector( 2 ) - 85.0 ),\n                       std::numeric_limits< double >::min( ) );\n}\n\n// Test linear interpolation from benchmark values generetd by Matlab, interpolating the\n// error function.\nBOOST_AUTO_TEST_CASE( test_linearInterpolation_matlab_compare )\n{\n    using namespace interpolators;\n\n    // Load input data used for generating matlab interpolation.\n    Eigen::MatrixXd inputData = input_output::readMatrixFromFile(\n                input_output::getTudatRootPath( ) +\n                \"Mathematics/Interpolators/UnitTests/interpolator_test_input_data.dat\",\",\" );\n\n    // Put data in STL vectors.\n    std::vector< double > independentVariableValues;\n    std::vector< double > dependentVariableValues;\n\n    for ( int i = 0; i < inputData.rows( ); i++ )\n    {\n        independentVariableValues.push_back( inputData( i, 0 ) );\n        dependentVariableValues.push_back( inputData( i, 1 ) );\n    }\n\n    // Create linear interpolator using hunting algorithm.\n    LinearInterpolatorDouble linearInterpolator(\n                independentVariableValues, dependentVariableValues, huntingAlgorithm );\n\n    // Load points at which interpolator is to be evaluated and data generated by Matlab.\n    Eigen::MatrixXd benchmarkData = input_output::readMatrixFromFile(\n                input_output::getTudatRootPath( ) +\n                \"Mathematics/Interpolators/UnitTests/linear_interpolator_test_output_data.dat\",\n                \",\" );\n\n    // Perform interpolation for required data points.\n    Eigen::VectorXd outputData = Eigen::VectorXd( benchmarkData.rows( ) );\n    for ( int i = 0; i < outputData.rows( ); i++ )\n    {\n        outputData[ i ] = linearInterpolator.interpolate( benchmarkData( i, 0 ) );\n    }\n\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( benchmarkData.block( 0, 1, benchmarkData.rows( ), 1 ),\n                                       outputData, 1.0E-13 );\n\n    // Create linear interpolator, now with nearest neighbvour search.\n    linearInterpolator = LinearInterpolatorDouble(\n                independentVariableValues, dependentVariableValues, binarySearch );\n\n    // Perform interpolation for required data points.\n    for ( int i = 0; i < outputData.rows( ); i++ )\n    {\n        outputData[ i ] = linearInterpolator.interpolate( benchmarkData( i, 0 ) );\n    }\n\n    TUDAT_CHECK_MATRIX_CLOSE_FRACTION( benchmarkData.block( 0, 1, benchmarkData.rows( ), 1 ),\n                                       outputData, 1.0E-13 );\n}\n\n// Test linear interpolation outside of independent variable range\nBOOST_AUTO_TEST_CASE( test_linearInterpolation_boundary_case )\n{\n    using namespace interpolators;\n\n    // Load input data used for generating matlab interpolation.\n    Eigen::MatrixXd inputData = input_output::readMatrixFromFile(\n                input_output::getTudatRootPath( ) +\n                \"Mathematics/Interpolators/UnitTests/interpolator_test_input_data.dat\",\",\" );\n\n    // Put data in STL vectors.\n    std::vector< double > independentVariableValues;\n    std::vector< double > dependentVariableValues;\n\n    for ( int i = 0; i < inputData.rows( ); i++ )\n    {\n        independentVariableValues.push_back( inputData( i, 0 ) );\n        dependentVariableValues.push_back( inputData( i, 1 ) );\n    }\n\n    // Create linear interpolator using hunting algorithm.\n    double valueOffset = 2.0;\n    double valueBelowMinimumValue = independentVariableValues[ 0 ] - valueOffset;\n    double valueAboveMaximumValue = independentVariableValues[ inputData.rows( ) - 1 ] + valueOffset;\n    double interpolatedValue = TUDAT_NAN, expectedValue = TUDAT_NAN;\n    bool exceptionIsCaught = false;\n\n    for( unsigned int i = 0; i < 7; i++ )\n    {\n        LinearInterpolatorDouble linearInterpolator(\n                    independentVariableValues, dependentVariableValues, huntingAlgorithm,\n                    static_cast< BoundaryInterpolationType >( i ) );\n\n        if( static_cast< BoundaryInterpolationType >( i ) == throw_exception_at_boundary )\n        {\n            try\n            {\n                linearInterpolator.interpolate( valueBelowMinimumValue );\n            }\n            catch( std::runtime_error )\n            {\n                exceptionIsCaught = true;\n            }\n            BOOST_CHECK_EQUAL( exceptionIsCaught, true );\n\n            exceptionIsCaught = false;\n            try\n            {\n                linearInterpolator.interpolate( valueAboveMaximumValue );\n            }\n            catch( std::runtime_error )\n            {\n                exceptionIsCaught = true;\n            }\n            BOOST_CHECK_EQUAL( exceptionIsCaught, true );\n        }\n        else if( ( static_cast< BoundaryInterpolationType >( i ) == use_boundary_value ) ||\n                 ( static_cast< BoundaryInterpolationType >( i ) == use_boundary_value_with_warning ) )\n        {\n            interpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, dependentVariableValues.at( 0 ), 1.0E-15 );\n\n            interpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, dependentVariableValues.at( inputData.rows( ) - 1 ), 1.0E-15 );\n\n        }\n        else if( ( static_cast< BoundaryInterpolationType >( i ) == extrapolate_at_boundary ) ||\n                 ( static_cast< BoundaryInterpolationType >( i ) == extrapolate_at_boundary_with_warning ) )\n        {\n            interpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            expectedValue = dependentVariableValues.at( 0 ) - valueOffset * (\n                        dependentVariableValues.at( 1 ) - dependentVariableValues.at( 0 ) ) / (\n                        independentVariableValues.at( 1 ) - independentVariableValues.at( 0 ) );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, expectedValue, 1.0E-15 );\n\n            interpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            expectedValue = dependentVariableValues.at( inputData.rows( ) - 1 ) + valueOffset * (\n                        dependentVariableValues.at( inputData.rows( ) - 1 ) - dependentVariableValues.at( inputData.rows( ) - 2 ) ) / (\n                        independentVariableValues.at( inputData.rows( ) - 1 ) - independentVariableValues.at( inputData.rows( ) - 2 ) );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, expectedValue, 1.0E-15 );\n        }\n        else if( ( static_cast< BoundaryInterpolationType >( i ) == use_default_value ) ||\n                 ( static_cast< BoundaryInterpolationType >( i ) == use_default_value_with_warning ) )\n        {\n            interpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, 0.0, 1.0E-15 );\n\n            interpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, 0.0, 1.0E-15 );\n        }\n    }\n}\n\n// Test linear interpolation outside of independent variable range with default extrapolation value\nBOOST_AUTO_TEST_CASE( test_linearInterpolation_boundary_case_extrapolation_default_value )\n{\n    using namespace interpolators;\n\n    // Load input data used for generating matlab interpolation.\n    Eigen::MatrixXd inputData = input_output::readMatrixFromFile(\n                input_output::getTudatRootPath( ) +\n                \"Mathematics/Interpolators/UnitTests/interpolator_test_input_data.dat\",\",\" );\n\n    // Put data in STL vectors.\n    std::vector< double > independentVariableValues;\n\n    for ( int i = 0; i < inputData.rows( ); i++ )\n    {\n        independentVariableValues.push_back( inputData( i, 0 ) );\n    }\n\n    // Create linear interpolator using hunting algorithm.\n    double valueOffset = 2.0;\n    double valueBelowMinimumValue = independentVariableValues[ 0 ] - valueOffset;\n    double valueAboveMaximumValue = independentVariableValues[ inputData.rows( ) - 1 ] + valueOffset;\n\n    // Test with long double\n    {\n        // Put data in STL vectors.\n        std::vector< long double > dependentVariableValues;\n        for ( int i = 0; i < inputData.rows( ); i++ )\n        {\n            dependentVariableValues.push_back( inputData( i, 1 ) );\n        }\n        long double interpolatedValue;\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            LinearInterpolator< double, long double > linearInterpolator(\n                        independentVariableValues, dependentVariableValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ) );\n\n            interpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, 0.0L, 1.0E-15 );\n\n            interpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, 0.0L, 1.0E-15 );\n        }\n    }\n\n    // Test with Eigen::Vector3d\n    {\n        // Put data in STL vectors.\n        std::vector< Eigen::Vector3d > dependentVariableValues;\n        Eigen::Vector3d tempData = Eigen::Vector3d::Zero( );\n        for ( int i = 0; i < inputData.rows( ); i++ )\n        {\n            tempData[ 0 ] = inputData( i, 1 );\n            dependentVariableValues.push_back( tempData );\n        }\n        Eigen::Vector3d interpolatedValue;\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            LinearInterpolator< double, Eigen::Vector3d > linearInterpolator(\n                        independentVariableValues, dependentVariableValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ) );\n\n            interpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Vector3d::Zero( ) ).norm( ), 1.0E-15 );\n\n            interpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Vector3d::Zero( ) ).norm( ), 1.0E-15 );\n        }\n    }\n\n    // Test with Eigen::Matrix3d\n    {\n        // Put data in STL vectors.\n        std::vector< Eigen::Matrix3d > dependentVariableValues;\n        Eigen::Matrix3d tempData = Eigen::Matrix3d::Zero( );\n        for ( int i = 0; i < inputData.rows( ); i++ )\n        {\n            tempData( 0, 2 ) = inputData( i, 1 );\n            dependentVariableValues.push_back( tempData );\n        }\n        Eigen::Matrix3d interpolatedValue;\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            LinearInterpolator< double, Eigen::Matrix3d > linearInterpolator(\n                        independentVariableValues, dependentVariableValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ) );\n\n            interpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Matrix3d::Zero( ) ).norm( ), 1.0E-15 );\n\n            interpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            BOOST_CHECK_SMALL( ( interpolatedValue - Eigen::Matrix3d::Zero( ) ).norm( ), 1.0E-15 );\n        }\n    }\n}\n\n// Test linear interpolation outside of independent variable range with extrapolation value given by user\nBOOST_AUTO_TEST_CASE( test_linearInterpolation_boundary_case_extrapolation_user_value )\n{\n    using namespace interpolators;\n\n    // Load input data used for generating matlab interpolation.\n    Eigen::MatrixXd inputData = input_output::readMatrixFromFile(\n                input_output::getTudatRootPath( ) +\n                \"Mathematics/Interpolators/UnitTests/interpolator_test_input_data.dat\",\",\" );\n\n    // Put data in STL vectors.\n    std::vector< double > independentVariableValues;\n\n    for ( int i = 0; i < inputData.rows( ); i++ )\n    {\n        independentVariableValues.push_back( inputData( i, 0 ) );\n    }\n\n    // Create linear interpolator using hunting algorithm.\n    double valueOffset = 2.0;\n    double valueBelowMinimumValue = independentVariableValues[ 0 ] - valueOffset;\n    double valueAboveMaximumValue = independentVariableValues[ inputData.rows( ) - 1 ] + valueOffset;\n\n    // Test with long double\n    {\n        // Put data in STL vectors.\n        std::vector< long double > dependentVariableValues;\n\n        for ( int i = 0; i < inputData.rows( ); i++ )\n        {\n            dependentVariableValues.push_back( inputData( i, 1 ) );\n        }\n        long double interpolatedValue;\n        long double extrapolationValue = 1.0L;\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            LinearInterpolator< double, long double > linearInterpolator(\n                        independentVariableValues, dependentVariableValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ), extrapolationValue );\n\n            interpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, extrapolationValue, 1.0E-15 );\n\n            interpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            BOOST_CHECK_CLOSE_FRACTION( interpolatedValue, extrapolationValue, 1.0E-15 );\n        }\n    }\n\n    // Test with Eigen::Vector3d\n    {\n        // Put data in STL vectors.\n        std::vector< Eigen::Vector3d > dependentVariableValues;\n        Eigen::Vector3d tempData = Eigen::Vector3d::Zero( );\n        for ( int i = 0; i < inputData.rows( ); i++ )\n        {\n            tempData[ 0 ] = inputData( i, 1 );\n            dependentVariableValues.push_back( tempData );\n        }\n        Eigen::Vector3d interpolatedValue;\n        Eigen::Vector3d extrapolationValue;\n        extrapolationValue[ 0 ] = 1.5;\n        extrapolationValue[ 1 ] = -3;\n        extrapolationValue[ 2 ] = 0;\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            LinearInterpolator< double, Eigen::Vector3d > linearInterpolator(\n                        independentVariableValues, dependentVariableValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ), extrapolationValue );\n\n            interpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );\n\n            interpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );\n        }\n    }\n\n    // Test with Eigen::Matrix3d\n    {\n        // Put data in STL vectors.\n        std::vector< Eigen::Matrix3d > dependentVariableValues;\n        Eigen::Matrix3d tempData = Eigen::Matrix3d::Zero( );\n        for ( int i = 0; i < inputData.rows( ); i++ )\n        {\n            tempData( 0, 2 ) = inputData( i, 1 );\n            dependentVariableValues.push_back( tempData );\n        }\n        Eigen::Matrix3d interpolatedValue;\n        Eigen::Matrix3d extrapolationValue = Eigen::Matrix3d::Random( );\n\n        for( unsigned int i = 5; i < 7; i++ )\n        {\n            LinearInterpolator< double, Eigen::Matrix3d > linearInterpolator(\n                        independentVariableValues, dependentVariableValues, huntingAlgorithm,\n                        static_cast< BoundaryInterpolationType >( i ), extrapolationValue );\n\n            interpolatedValue = linearInterpolator.interpolate( valueBelowMinimumValue );\n            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );\n\n            interpolatedValue = linearInterpolator.interpolate( valueAboveMaximumValue );\n            BOOST_CHECK_SMALL( ( interpolatedValue - extrapolationValue ).norm( ), 1.0E-15 );\n        }\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "9117fee95fd81a161a1a538d38887321fa6bb13c", "size": 19698, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/Interpolators/UnitTests/unitTestLinearInterpolator.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/Interpolators/UnitTests/unitTestLinearInterpolator.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/Interpolators/UnitTests/unitTestLinearInterpolator.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.8217391304, "max_line_length": 136, "alphanum_fraction": 0.6530104579, "num_tokens": 4361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143953, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6150870857676318}}
{"text": "#ifndef __SIMPLEX_HPP__\n#define __SIMPLEX_HPP__\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <iostream>\n#include <cmath>\n#include <vector>\n#include <unordered_set>\n#define INF 1e10\n#define EPSILON 1e-5\n\n\nclass Simplex{\npublic:\n    /// \u8f93\u5165\u76ee\u6807\u51fd\u6570\u5411\u91cf\uff08\u6309\u7167\u5355\u7eaf\u5f62\u8868\u9996\u884c\u683c\u5f0f\uff09\u4ee5\u53ca\u7ea6\u675f\u589e\u5e7f\u77e9\u9635\n    Simplex(Eigen::RowVectorXd _tar, Eigen::MatrixXd _cstrn):\n        target(_tar), constrain(_cstrn), _m(_cstrn.rows()), _n(_cstrn.cols() - 1), rhs(constrain.col(_n))\n    {\n        loop_cnt = 0;\n        artifacts = 0;\n        counter = new int[_m];\n        memset(counter, 0, _m * sizeof(int));\n    }\n\n    Simplex(Eigen::MatrixXd _cstrn):\n        constrain(_cstrn), _m(_cstrn.rows()), _n(_cstrn.cols() - 1), rhs(constrain.col(_n))\n    {\n        loop_cnt = 0;\n        artifacts = 0;\n        counter = new int[_m];\n        memset(counter, 0, _m * sizeof(int));\n    }\n\n    ~Simplex(){\n        delete[] counter;\n    }\npublic:\n    // \u53cc\u9636\u6bb5\u89e3\u6cd5\n    bool doubleStageSolve(const Eigen::RowVectorXd& tar);        \n    bool solve();\n    void showResults() const;\nprivate:\n    // \u8d77\u59cb\u60c5\u51b5\uff1a\u9996\u5148\u4ece\u589e\u5e7f\u77e9\u9635\u4e2d\u627e\u5230m\u4e2a\u7ebf\u6027\u65e0\u5173\u5411\u91cf\uff08\u4f7f\u7528\u9636\u68af\u5316\u7684\u65b9\u5f0f\uff09\n    // \u6b64\u540e\u53d6\u51fa\u8fd9\u4e9b\u5217\uff0c\u62fc\u5408\u77e9\u9635B\uff0c\u5f97\u5230(B^-1)\uff0c\u7ee7\u7eed\u4f7f\u7528\u5bf9\u89d2\u5316\uff1f\n    // \u5316\u4e3a\u5178\u5f0f\uff0c\u51fd\u6570\u9000\u51fa\n    void getCanonical();   \n    bool stageOneOptimize(std::unordered_set<int>& slct);        // \u9636\u6bb5\u4e00\u4f18\u5316\n\n    // \u9636\u68af\u5316\uff0cBinv\u4e3a\u9636\u68af\u5316\u7ed3\u679c\uff0c\u5f97\u5230\u77e9\u9635B\n    void ladderize(Eigen::MatrixXd& B);\n    bool findBiggestInspect(int& index) const;\n    bool isLooping() const;\nprivate:\n    Eigen::RowVectorXd target;\n    Eigen::MatrixXd constrain;\n    int artifacts;                  // \u4eba\u5de5\u53d8\u91cf\u4e2a\u6570\n    int _m;\n    int _n;                         // \u6b64\u5904_n\u7684\u5b9a\u4e49\u662f \u9664\u4e86RHS\u5217\u5916\u7684\u884c\u6570\uff08\u8f93\u5165\u7684constrain\u5305\u542bRHS\uff09\n    int* counter;\n    int loop_cnt;\n    std::vector<int> base_index;\n    const Eigen::Block<Eigen::MatrixXd, -1, 1, true>& rhs;\n};\n\n#endif  //__SIMPLEX_HPP__", "meta": {"hexsha": "b2f12f60029382ce427585524a9205812cd06531", "size": 1739, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/include/simplex.hpp", "max_stars_repo_name": "Enigmatisms/Operation", "max_stars_repo_head_hexsha": "c68f6246a448ba1be18597b2145eee882cb6478e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T12:04:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-13T03:15:44.000Z", "max_issues_repo_path": "cpp/include/simplex.hpp", "max_issues_repo_name": "Enigmatisms/Operation", "max_issues_repo_head_hexsha": "c68f6246a448ba1be18597b2145eee882cb6478e", "max_issues_repo_licenses": ["MIT"], "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/include/simplex.hpp", "max_forks_repo_name": "Enigmatisms/Operation", "max_forks_repo_head_hexsha": "c68f6246a448ba1be18597b2145eee882cb6478e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-13T01:30:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-13T01:30:18.000Z", "avg_line_length": 26.7538461538, "max_line_length": 105, "alphanum_fraction": 0.6152961472, "num_tokens": 624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6150240728477679}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/ext/std/ratio.hpp>\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <laws/group.hpp>\n#include <laws/monoid.hpp>\n\n#include <ratio>\nusing namespace boost::hana;\n\n\nint main() {\n    auto ratios = make<Tuple>(\n          std::ratio<0>{}\n        , std::ratio<1, 3>{}\n        , std::ratio<1, 2>{}\n        , std::ratio<2, 6>{}\n        , std::ratio<3, 1>{}\n        , std::ratio<7, 8>{}\n        , std::ratio<3, 5>{}\n        , std::ratio<2, 1>{}\n    );\n\n    //////////////////////////////////////////////////////////////////////////\n    // Monoid\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // plus\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                plus(std::ratio<3, 4>{}, std::ratio<5, 10>{}),\n                std::ratio<3*10 + 5*4, 4*10>{}\n            ));\n        }\n\n        // zero\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                zero<ext::std::Ratio>(),\n                std::ratio<0, 1>{}\n            ));\n\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                zero<ext::std::Ratio>(),\n                std::ratio<0, 2>{}\n            ));\n        }\n\n        // laws\n        test::TestMonoid<ext::std::Ratio>{ratios};\n    }\n\n    //////////////////////////////////////////////////////////////////////////\n    // Group\n    //////////////////////////////////////////////////////////////////////////\n    {\n        // minus\n        {\n            BOOST_HANA_CONSTANT_CHECK(equal(\n                minus(std::ratio<3, 4>{}, std::ratio<5, 10>{}),\n                std::ratio<3*10 - 5*4, 4*10>{}\n            ));\n        }\n\n        // laws\n        test::TestGroup<ext::std::Ratio>{ratios};\n    }\n}\n", "meta": {"hexsha": "77e1b27ed189687e265af352aaab424aff820709", "size": 1898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ext/std/ratio/group.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/ext/std/ratio/group.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/ext/std/ratio/group.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9736842105, "max_line_length": 78, "alphanum_fraction": 0.3888303477, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6150098508120695}}
{"text": "#ifndef MIN_JERK_CURVE_VEC_H\n#define MIN_JERK_CURVE_VEC_H\n\n#include <Eigen/Dense>\n#include <Utils/Math/minjerk_one_dim.hpp>\n\n// vector version of min jerk interpolation\n\nclass MinJerkCurveVec{\npublic:\n\tMinJerkCurveVec();\n\tMinJerkCurveVec(const Eigen::VectorXd & start_pos, const Eigen::VectorXd & start_vel, const Eigen::VectorXd & start_acc, \n\t\t\t  \t    const Eigen::VectorXd & end_pos, const Eigen::VectorXd & end_vel, const Eigen::VectorXd & end_acc,\n\t\t\t  \t    double duration);\n\t~MinJerkCurveVec();\n\tEigen::VectorXd evaluate(const double & t_in);\n\tEigen::VectorXd evaluateFirstDerivative(const double & t_in);\n\tEigen::VectorXd evaluateSecondDerivative(const double & t_in);\n\nprivate:\n\tdouble Ts; \n\t\n\tEigen::VectorXd p1;\n\tEigen::VectorXd v1;\n\tEigen::VectorXd a1;\n\t\n\tEigen::VectorXd p2;\n\tEigen::VectorXd v2;\n\tEigen::VectorXd a2;\n\n\tstd::vector<MinJerk_OneDimension> curves;\n \tEigen::VectorXd output;\n};\n\n#endif", "meta": {"hexsha": "0455fcf20890d8e029d5ddd097cae303e85e8c4d", "size": 910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Utils/Math/minjerk_vec.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/minjerk_vec.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/minjerk_vec.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": 26.0, "max_line_length": 122, "alphanum_fraction": 0.7494505495, "num_tokens": 240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672595, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6150098454016182}}
{"text": "#include \"graphing.h\"\n\n#include <boost/graph/connected_components.hpp>\n\nnamespace gaus::underground_modelling {\n\nGraph\nmake_graph(const arma::umat &adj_mat){\n\n  assert(adj_mat.is_symmetric());\n\n  Graph g;\n\n  const arma::uvec connections = arma::find(adj_mat == 1);\n\n  const auto [n_rows, n_cols] = arma::size(adj_mat);\n\n  assert(n_rows == n_cols);\n\n  for(const auto connection : connections){\n\n    const auto vertex_a = connection / n_rows;\n    const auto vertex_b = connection % n_rows;\n\n    add_edge(vertex_a, vertex_b, g);\n\n  }\n\n  return g;\n\n}\n\n\ndouble\ncheck_connectivity(const arma::umat &adjacency){\n\n  const auto graph = make_graph(adjacency);\n\n  std::vector<int> component(num_vertices(graph));\n\n  return connected_components(graph, &component[0]);\n\n}\n\n\narma::mat\nouter_difference(const arma::vec &vec){\n\n  const auto n_elem = vec.n_elem;\n\n  arma::mat mat = arma::zeros(arma::size(n_elem, n_elem));\n\n  for(int i = 0; i < n_elem; i++){\n    for(int j = 0; j < i; j++){\n\n      mat(i, j) = vec(i) - vec(j);\n      mat(j, i) = vec(j) - vec(i);\n\n    }\n  }\n\n  return mat;\n}\n\n\narma::mat\nfind_distances(const StationCoordinates &station_coord){\n\n  const auto x = outer_difference(station_coord.x);\n  const auto y = outer_difference(station_coord.y);\n\n  const auto distances = arma::sqrt(arma::square(x) + arma::square(y));\n\n  return distances;\n\n}\n\n\ndouble\ncalculate_cost(const arma::umat &adjacency,\n               const StationCoordinates &station_coord,\n               const CostParameters &cp){\n\n  const auto all_distances = find_distances(station_coord);\n\n  const auto built_distances = all_distances % adjacency;\n\n  //0.5 to stop double counting\n  return 0.5 * (arma::accu(built_distances * cp.cost_per_unit)\n                + arma::accu(adjacency) * cp.base_cost);\n}\n\n\ndouble\nfind_terminal_stations(const arma::umat &adjacency){\n\n  const auto n_connections = arma::sum(adjacency, 1);\n\n  return 1. + arma::find(n_connections <= 1).eval().n_elem;\n\n}\n\n}", "meta": {"hexsha": "8ece3f4dc29ba7565903cab490f974bc57f85076", "size": 1953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/underground_modelling/graphing.cpp", "max_stars_repo_name": "Oliver-Feighan/ga_underground_maps", "max_stars_repo_head_hexsha": "637a7f59e23b045ffb58e8baa8a336833eb3377c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/underground_modelling/graphing.cpp", "max_issues_repo_name": "Oliver-Feighan/ga_underground_maps", "max_issues_repo_head_hexsha": "637a7f59e23b045ffb58e8baa8a336833eb3377c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/underground_modelling/graphing.cpp", "max_forks_repo_name": "Oliver-Feighan/ga_underground_maps", "max_forks_repo_head_hexsha": "637a7f59e23b045ffb58e8baa8a336833eb3377c", "max_forks_repo_licenses": ["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.9611650485, "max_line_length": 71, "alphanum_fraction": 0.6758832565, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.6150098300545263}}
{"text": "#include <vector>\n#include \"Solvers.h\"\n#include \"math.h\"\n#include \"MatrixMath.h\"\n#include <iostream>\n#include \"CoolPropTools.h\"\n#include <Eigen/Dense>\n\nnamespace CoolProp{\n\n/** \\brief Calculate the Jacobian using numerical differentiation by column\n */\nstd::vector<std::vector<double> > FuncWrapperND::Jacobian(const std::vector<double> &x)\n{\n    double epsilon;\n    std::size_t N = x.size();\n    std::vector<double> r, xp;\n    std::vector<std::vector<double> > J(N, std::vector<double>(N, 0));\n    std::vector<double> r0 = call(x);\n    // Build the Jacobian by column\n    for (std::size_t i = 0; i < N; ++i)\n    {\n        xp = x;\n        epsilon = 0.001*x[i];\n        xp[i] += epsilon;\n        r = call(xp);\n        \n        for(std::size_t j = 0; j < N; ++j)\n        {\n            J[j][i] = (r[j]-r0[j])/epsilon;\n        }\n    }\n    return J;\n}\n\n/**\nIn this formulation of the Multi-Dimensional Newton-Raphson solver the Jacobian matrix is known.\nTherefore, the dx vector can be obtained from\n\nJ(x)dx=-f(x)\n\nfor a given value of x.  The pointer to the class FuncWrapperND that is passed in must implement the call() and Jacobian()\nfunctions, each of which take the vector x. The data is managed using std::vector<double> vectors\n\n@param f A pointer to an subclass of the FuncWrapperND class that implements the call() and Jacobian() functions\n@param x0 The initial guess value for the solution\n@param tol The root-sum-square of the errors from each of the components\n@param maxiter The maximum number of iterations\n@param errstring  A string with the returned error.  If the length of errstring is zero, no errors were found\n@returns If no errors are found, the solution.  Otherwise, _HUGE, the value for infinity\n*/\nstd::vector<double> NDNewtonRaphson_Jacobian(FuncWrapperND *f, const std::vector<double> &x, double tol, int maxiter)\n{\n    int iter=0;\n    f->errstring.clear();\n    std::vector<double> f0,v;\n    std::vector<std::vector<double> > JJ;\n    std::vector<double> x0 = x;\n    Eigen::VectorXd r(x0.size());\n    Eigen::MatrixXd J(x0.size(), x0.size());\n    double error = 999;\n    while (iter==0 || std::abs(error)>tol){\n        f0 = f->call(x0);\n        JJ = f->Jacobian(x0);\n        \n        for (std::size_t i = 0; i < x0.size(); ++i)\n        {\n            r(i) = f0[i];\n            for (std::size_t j = 0; j < x0.size(); ++j)\n            {\n                J(i,j) = JJ[i][j];\n            }\n        }\n\n        Eigen::VectorXd v = J.colPivHouseholderQr().solve(-r);\n\n        // Update the guess\n        double max_relchange = -1;\n        for (std::size_t i = 0; i<x0.size(); i++){\n            x0[i] += v(i);\n            double relchange = std::abs(v(i)/x0[i]);\n            if (std::abs(x0[i]) > 1e-16 && relchange > max_relchange ){\n                max_relchange = relchange;\n            }\n        }\n        \n        // Stop if the solution is not changing by more than numerical precision\n        double max_abschange = v.cwiseAbs().maxCoeff();\n        if (max_abschange < DBL_EPSILON*100){\n            return x0;\n        }\n        if (max_relchange < 1e-12){\n            return x0;\n        }\n        error = root_sum_square(f0);\n        if (iter>maxiter){\n            f->errstring = \"reached maximum number of iterations\";\n            x0[0] = _HUGE;\n        }\n        iter++;\n    }\n    return x0;\n}\n\n/**\nIn the newton function, a 1-D Newton-Raphson solver is implemented using exact solutions.  An initial guess for the solution is provided.\n\n@param f A pointer to an instance of the FuncWrapper1D class that implements the call() function\n@param x0 The initial guess for the solution\n@param ftol The absolute value of the tolerance accepted for the objective function\n@param maxiter Maximum number of iterations\n@returns If no errors are found, the solution, otherwise the value _HUGE, the value for infinity\n*/\ndouble Newton(FuncWrapper1DWithDeriv* f, double x0, double ftol, int maxiter)\n{\n    double x, dx, fval=999;\n    int iter=1;\n    f->errstring.clear();\n    x = x0;\n    while (iter < 2 || std::abs(fval) > ftol)\n    {\n        fval = f->call(x);\n        dx = -fval/f->deriv(x);\n\n        if (!ValidNumber(fval)){\n            throw ValueError(\"Residual function in newton returned invalid number\");\n        };\n\n        x += dx;\n\n        if (std::abs(dx/x) < 1e-11){\n            return x;\n        }\n\n        if (iter>maxiter)\n        {\n            f->errstring= \"reached maximum number of iterations\";\n            throw SolutionError(format(\"Newton reached maximum number of iterations\"));\n        }\n        iter=iter+1;\n    }\n    return x;\n}\n/**\nIn the Halley's method solver, two derivatives of the input variable are needed, it yields the following method:\n\n\\f[\nx_{n+1} = x_n - \\frac {2 f(x_n) f'(x_n)} {2 {[f'(x_n)]}^2 - f(x_n) f''(x_n)}\n\\f]\n\nhttp://en.wikipedia.org/wiki/Halley%27s_method\n\n@param f A pointer to an instance of the FuncWrapper1DWithTwoDerivs class that implements the call() and two derivatives\n@param x0 The initial guess for the solution\n@param ftol The absolute value of the tolerance accepted for the objective function\n@param maxiter Maximum number of iterations\n@param xtol_rel The minimum allowable (relative) step size\n@returns If no errors are found, the solution, otherwise the value _HUGE, the value for infinity\n*/\ndouble Halley(FuncWrapper1DWithTwoDerivs* f, double x0, double ftol, int maxiter, double xtol_rel)\n{\n    double x, dx, fval=999, dfdx, d2fdx2;\n    \n    // Initialize\n    f->iter=0;\n    f->errstring.clear();\n    x = x0;\n    \n    // The relaxation factor (less than 1 for smaller steps)\n    double omega = f->options.get_double(\"omega\", 1.0);\n    \n    while (f->iter < 2 || std::abs(fval) > ftol)\n    {\n        if (f->input_not_in_range(x)){\n            throw ValueError(format(\"Input [%g] is out of range\",x));\n        }\n        \n        fval = f->call(x);\n        dfdx = f->deriv(x);\n        d2fdx2 = f->second_deriv(x);\n        \n        if (!ValidNumber(fval)){\n            throw ValueError(\"Residual function in Halley returned invalid number\");\n        };\n        if (!ValidNumber(dfdx)){\n            throw ValueError(\"Derivative function in Halley returned invalid number\");\n        };\n        \n        dx = -omega*(2*fval*dfdx)/(2*POW2(dfdx)-fval*d2fdx2);\n\n        x += dx;\n\n        if (std::abs(dx/x) < xtol_rel){\n            return x;\n        }\n\n        if (f->iter>maxiter){\n            f->errstring= \"reached maximum number of iterations\";\n            throw SolutionError(format(\"Halley reached maximum number of iterations\"));\n        }\n        f->iter += 1;\n    }\n    return x;\n}\n    \n/**\n In the 4-th order Householder method, three derivatives of the input variable are needed, it yields the following method:\n \n \\f[\n x_{n+1} = x_n - f(x_n)\\left( \\frac {[f'(x_n)]^2 - f(x_n)f''(x_n)/2  } {[f'(x_n)]^3-f(x_n)f'(x_n)f''(x_n)+f'''(x_n)*[f(x_n)]^2/6 } \\right)\n \\f]\n \nhttp://numbers.computation.free.fr/Constants/Algorithms/newton.ps\n \n @param f A pointer to an instance of the FuncWrapper1DWithThreeDerivs class that implements the call() and three derivatives\n @param x0 The initial guess for the solution\n @param ftol The absolute value of the tolerance accepted for the objective function\n @param maxiter Maximum number of iterations\n @param xtol_rel The minimum allowable (relative) step size\n @returns If no errors are found, the solution, otherwise the value _HUGE, the value for infinity\n */\ndouble Householder4(FuncWrapper1DWithThreeDerivs* f, double x0, double ftol, int maxiter, double xtol_rel)\n{\n    double x, dx, fval=999, dfdx, d2fdx2, d3fdx3;\n    \n    // Initialization\n    f->iter=1;\n    f->errstring.clear();\n    x = x0;\n    \n    // The relaxation factor (less than 1 for smaller steps)\n    double omega = f->options.get_double(\"omega\", 1.0);\n    \n    while (f->iter < 2 || std::abs(fval) > ftol)\n    {\n        if (f->input_not_in_range(x)){\n            throw ValueError(format(\"Input [%g] is out of range\",x));\n        }\n        \n        fval = f->call(x);\n        dfdx = f->deriv(x);\n        d2fdx2 = f->second_deriv(x);\n        d3fdx3 = f->third_deriv(x);\n        \n        if (!ValidNumber(fval)){\n            throw ValueError(\"Residual function in Householder4 returned invalid number\");\n        };\n        if (!ValidNumber(dfdx)){\n            throw ValueError(\"Derivative function in Householder4 returned invalid number\");\n        };\n        if (!ValidNumber(d2fdx2)){\n            throw ValueError(\"Second derivative function in Householder4 returned invalid number\");\n        };\n        if (!ValidNumber(d3fdx3)){\n            throw ValueError(\"Third derivative function in Householder4 returned invalid number\");\n        };\n        \n        dx = -omega*fval*(POW2(dfdx)-fval*d2fdx2/2.0)/(POW3(dfdx)-fval*dfdx*d2fdx2+d3fdx3*POW2(fval)/6.0);\n        \n        x += dx;\n        \n        if (std::abs(dx/x) < xtol_rel){\n            return x;\n        }\n        \n        if (f->iter>maxiter){\n            f->errstring= \"reached maximum number of iterations\";\n            throw SolutionError(format(\"Householder4 reached maximum number of iterations\"));\n        }\n        f->iter += 1;\n    }\n    return x;\n}\n\n/**\nIn the secant function, a 1-D Newton-Raphson solver is implemented.  An initial guess for the solution is provided.\n\n@param f A pointer to an instance of the FuncWrapper1D class that implements the call() function\n@param x0 The initial guess for the solutionh\n@param dx The initial amount that is added to x in order to build the numerical derivative\n@param tol The absolute value of the tolerance accepted for the objective function\n@param maxiter Maximum number of iterations\n@returns If no errors are found, the solution, otherwise the value _HUGE, the value for infinity\n*/\ndouble Secant(FuncWrapper1D* f, double x0, double dx, double tol, int maxiter)\n{\n    #if defined(COOLPROP_DEEP_DEBUG)\n    static std::vector<double> xlog, flog;\n    xlog.clear(); flog.clear();\n    #endif\n\n    // Initialization\n    double x1=0,x2=0,x3=0,y1=0,y2=0,x,fval=999;\n    f->iter=1;\n    f->errstring.clear();\n    \n    // The relaxation factor (less than 1 for smaller steps)\n    double omega = f->options.get_double(\"omega\", 1.0);\n\n    if (std::abs(dx)==0){ f->errstring=\"dx cannot be zero\"; return _HUGE;}\n    while (f->iter<=2 || std::abs(fval)>tol)\n    {\n        if (f->iter==1){x1=x0; x=x1;}\n        if (f->iter==2){x2=x0+dx; x=x2;}\n        if (f->iter>2) {x=x2;}\n        \n            if (f->input_not_in_range(x)){\n                throw ValueError(format(\"Input [%g] is out of range\",x));\n            }\n\n            fval = f->call(x);\n\n            #if defined(COOLPROP_DEEP_DEBUG)\n                xlog.push_back(x);\n                flog.push_back(fval);\n            #endif\n\n            if (!ValidNumber(fval)){\n                throw ValueError(\"Residual function in secant returned invalid number\");\n            };\n        if (f->iter==1){y1=fval;}\n        if (f->iter>1)\n        {\n            double deltax = x2-x1;\n            if (std::abs(deltax)<1e-14){\n                return x;\n            }\n            y2=fval;\n            double deltay = y2-y1;\n            if (f->iter > 2 && std::abs(deltay)<1e-14){\n                return x;\n            }\n            x3=x2-omega*y2/(y2-y1)*(x2-x1);\n            y1=y2; x1=x2; x2=x3;\n\n        }\n        if (f->iter>maxiter)\n        {\n            f->errstring=std::string(\"reached maximum number of iterations\");\n            throw SolutionError(format(\"Secant reached maximum number of iterations\"));\n        }\n        f->iter += 1;\n    }\n    return x3;\n}\n\n/**\nIn the secant function, a 1-D Newton-Raphson solver is implemented.  An initial guess for the solution is provided.\n\n@param f A pointer to an instance of the FuncWrapper1D class that implements the call() function\n@param x0 The initial guess for the solution\n@param xmax The upper bound for the solution\n@param xmin The lower bound for the solution\n@param dx The initial amount that is added to x in order to build the numerical derivative\n@param tol The absolute value of the tolerance accepted for the objective function\n@param maxiter Maximum number of iterations\n@returns If no errors are found, the solution, otherwise the value _HUGE, the value for infinity\n*/\ndouble BoundedSecant(FuncWrapper1D* f, double x0, double xmin, double xmax, double dx, double tol, int maxiter)\n{\n    double x1=0,x2=0,x3=0,y1=0,y2=0,x,fval=999;\n    int iter=1;\n    f->errstring.clear();\n    if (std::abs(dx)==0){ f->errstring = \"dx cannot be zero\"; return _HUGE;}\n    while (iter<=3 || std::abs(fval)>tol)\n    {\n        if (iter==1){x1=x0; x=x1;}\n        else if (iter==2){x2=x0+dx; x=x2;}\n        else {x=x2;}\n            fval=f->call(x);\n        if (iter==1){y1=fval;}\n        else\n        {\n            y2=fval;\n            x3=x2-y2/(y2-y1)*(x2-x1);\n            // Check bounds, go half the way to the limit if limit is exceeded\n            if (x3 < xmin)\n            {\n                x3 = (xmin + x2)/2;\n            }\n            if (x3 > xmax)\n            {\n                x3 = (xmax + x2)/2;\n            }\n            y1=y2; x1=x2; x2=x3;\n\n        }\n        if (iter>maxiter){\n            f->errstring = \"reached maximum number of iterations\";\n            throw SolutionError(format(\"BoundedSecant reached maximum number of iterations\"));\n        }\n        iter=iter+1;\n    }\n    f->errcode = 0;\n    return x3;\n}\n\n/**\n\nThis function implements a 1-D bounded solver using the algorithm from Brent, R. P., Algorithms for Minimization Without Derivatives.\nEnglewood Cliffs, NJ: Prentice-Hall, 1973. Ch. 3-4.\n\na and b must bound the solution of interest and f(a) and f(b) must have opposite signs.  If the function is continuous, there must be\nat least one solution in the interval [a,b].\n\n@param f A pointer to an instance of the FuncWrapper1D class that must implement the class() function\n@param a The minimum bound for the solution of f=0\n@param b The maximum bound for the solution of f=0\n@param macheps The machine precision\n@param t Tolerance (absolute)\n@param maxiter Maximum number of steps allowed.  Will throw a SolutionError if the solution cannot be found\n*/\ndouble Brent(FuncWrapper1D* f, double a, double b, double macheps, double t, int maxiter)\n{\n    int iter;\n    f->errstring.clear();\n    double fa,fb,c,fc,m,tol,d,e,p,q,s,r;\n    fa = f->call(a);\n    fb = f->call(b);\n\n    // If one of the boundaries is to within tolerance, just stop\n    if (std::abs(fb) < t) { return b;}\n    if (!ValidNumber(fb)){\n        throw ValueError(format(\"Brent's method f(b) is NAN for b = %g, other input was a = %g\",b,a).c_str());\n    }\n    if (std::abs(fa) < t) { return a;}\n    if (!ValidNumber(fa)){\n        throw ValueError(format(\"Brent's method f(a) is NAN for a = %g, other input was b = %g\",a,b).c_str());\n    }\n    if (fa*fb>0){\n        throw ValueError(format(\"Inputs in Brent [%f,%f] do not bracket the root.  Function values are [%f,%f]\",a,b,fa,fb));\n    }\n\n    c=a;\n    fc=fa;\n    iter=1;\n    if (std::abs(fc)<std::abs(fb)){\n        // Goto ext: from Brent ALGOL code\n        a=b;\n        b=c;\n        c=a;\n        fa=fb;\n        fb=fc;\n        fc=fa;\n    }\n    d=b-a;\n    e=b-a;\n    m=0.5*(c-b);\n    tol=2*macheps*std::abs(b)+t;\n    while (std::abs(m)>tol && fb!=0){\n        // See if a bisection is forced\n        if (std::abs(e)<tol || std::abs(fa) <= std::abs(fb)){\n            m=0.5*(c-b);\n            d=e=m;\n        }\n        else{\n            s=fb/fa;\n            if (a==c){\n                //Linear interpolation\n                p=2*m*s;\n                q=1-s;\n            }\n            else{\n                //Inverse quadratic interpolation\n                q=fa/fc;\n                r=fb/fc;\n                m=0.5*(c-b);\n                p=s*(2*m*q*(q-r)-(b-a)*(r-1));\n                q=(q-1)*(r-1)*(s-1);\n            }\n            if (p>0){\n                q=-q;\n            }\n            else{\n                p=-p;\n            }\n            s=e;\n            e=d;\n            m=0.5*(c-b);\n            if (2*p<3*m*q-std::abs(tol*q) || p<std::abs(0.5*s*q)){\n                d=p/q;\n            }\n            else{\n                m=0.5*(c-b);\n                d=e=m;\n            }\n        }\n        a=b;\n        fa=fb;\n        if (std::abs(d)>tol){\n            b+=d;\n        }\n        else if (m>0){\n            b+=tol;\n        }\n        else{\n            b+=-tol;\n        }\n        fb=f->call(b);\n        if (!ValidNumber(fb)){\n            throw ValueError(format(\"Brent's method f(t) is NAN for t = %g\",b).c_str());\n        }\n        if (std::abs(fb) < macheps){\n            return b;\n        }\n        if (fb*fc>0){\n            // Goto int: from Brent ALGOL code\n            c=a;\n            fc=fa;\n            d=e=b-a;\n        }\n        if (std::abs(fc)<std::abs(fb)){\n            // Goto ext: from Brent ALGOL code\n            a=b;\n            b=c;\n            c=a;\n            fa=fb;\n            fb=fc;\n            fc=fa;\n        }\n        m=0.5*(c-b);\n        tol=2*macheps*std::abs(b)+t;\n        iter+=1;\n        if (!ValidNumber(a)){\n            throw ValueError(format(\"Brent's method a is NAN\").c_str());}\n        if (!ValidNumber(b)){\n            throw ValueError(format(\"Brent's method b is NAN\").c_str());}\n        if (!ValidNumber(c)){\n            throw ValueError(format(\"Brent's method c is NAN\").c_str());}\n        if (iter>maxiter){\n            throw SolutionError(format(\"Brent's method reached maximum number of steps of %d \", maxiter));}\n        if (std::abs(fb)< 2*macheps*std::abs(b)){\n            return b;\n        }\n    }\n    return b;\n}\n\n}; /* namespace CoolProp */\n", "meta": {"hexsha": "c289714b428a4d85c122236d1d9a7e74ddabc402", "size": 17498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Solvers.cpp", "max_stars_repo_name": "tarment10/CoolProp", "max_stars_repo_head_hexsha": "de465e1cf6755d23231f289c6f7c24fd58eca465", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Solvers.cpp", "max_issues_repo_name": "tarment10/CoolProp", "max_issues_repo_head_hexsha": "de465e1cf6755d23231f289c6f7c24fd58eca465", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Solvers.cpp", "max_forks_repo_name": "tarment10/CoolProp", "max_forks_repo_head_hexsha": "de465e1cf6755d23231f289c6f7c24fd58eca465", "max_forks_repo_licenses": ["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.4037037037, "max_line_length": 138, "alphanum_fraction": 0.5688650131, "num_tokens": 4780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511359371249, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6150098168442056}}
{"text": "#include \"../simplex.hpp\"\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <iostream>\n#include <vector>\n#define PROBLEM \"https://yukicoder.me/problems/no/1122\"\nusing namespace std;\n\nint main() {\n    using Float = boost::multiprecision::cpp_dec_float_50;\n    vector<Float> B(5);\n    for (auto &x : B) cin >> x;\n    vector<vector<Float>> A{{1, 1, 1, 0, 0}, {0, 1, 1, 1, 0}, {0, 0, 1, 1, 1}, {1, 0, 0, 1, 1}, {1, 1, 0, 0, 1}};\n    vector<Float> C(5, 1);\n    Simplex<Float, 30> simplex(A, B, C);\n    cout << llround(simplex.ans - 0.17) << '\\n'; // I haven't proved yet this always returns correct answer.\n}\n", "meta": {"hexsha": "8a315672a0f67d1f37e90a3ca9e2e4d1737e4a86", "size": 613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "combinatorial_opt/test/simplex.multiprecision.test.cpp", "max_stars_repo_name": "ankit6776/cplib-cpp", "max_stars_repo_head_hexsha": "b9f8927a6c7301374c470856828aa1f5667d967b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-06-21T00:18:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T17:45:44.000Z", "max_issues_repo_path": "combinatorial_opt/test/simplex.multiprecision.test.cpp", "max_issues_repo_name": "ankit6776/cplib-cpp", "max_issues_repo_head_hexsha": "b9f8927a6c7301374c470856828aa1f5667d967b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2021-06-03T14:42:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T14:15:30.000Z", "max_forks_repo_path": "combinatorial_opt/test/simplex.multiprecision.test.cpp", "max_forks_repo_name": "ankit6776/cplib-cpp", "max_forks_repo_head_hexsha": "b9f8927a6c7301374c470856828aa1f5667d967b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T04:47:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T06:39:57.000Z", "avg_line_length": 36.0588235294, "max_line_length": 113, "alphanum_fraction": 0.6150081566, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.6149623907240597}}
{"text": "/*\n    File Name:      main.cpp\n    ROS module:     simpl_ekf\n    Description:    Implements an extended Kalman Filter for attitude estimation.\n                    Only uses the accelerometer measurements with a simplified\n                    model to compute pitch and roll of the device.\n    Author:         Thomas Lew\n    Last update:    2017.03.13\n    Comments:       -Assumptions: - No movement (linear & angular) of the device\n                                  - The model is therefore overly simplified.\n                    -Known bug: The pitch value is always negative regardless of\n                      (solved)  the rotation around y-axis. The cause is a wrong\n                                z-value of vector \"y\" in update function.\n                                This problem is solved in publishOdometryResult()\n                                by using accel-x (ax) to determine the direction \n                                of the pitch angle.\n                                                                                */\n#include <ros/ros.h>\n#include <sensor_msgs/Imu.h>\n#include <nav_msgs/Odometry.h>\n\n//  Library for linear algebra\n#include <Eigen/Eigenvalues>\n#include <Eigen/Core>\n#include <math.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n//  Debugging boolean for printing EKF variables during execution\n#define EKF_DEBUG 1\n\n//  Number of IMU measurements used for calibration\n#define IMU_COUNT_CALIBRATION 30\n\n//  Euler angles values limits for debugging\n#define PITCH_MAX M_PI/2\n#define ROLL_MAX  M_PI/2\n#define YAW_MAX   M_PI/2\n\n/*  ------------------------------------------------------------\n    Parameters of the Extended Kalman Filter. Depends on the IMU\n    ------------------------------------------------------------                        */\n/*//  Python Script simulated IMU measurements:\n#define FREQ_HZ         50      // 50Hz for python Script\n#define PERIOD_SEC      0.02    // 1/50 for python Script\n#define SIGMA_SENSORS   0.1     // Variance of python script IMU data (imu_publisher)   */\n\n//  Nvdia Shield Tablet IMU (only accelerometer) measurements:\n#define FREQ_HZ       50        // 50Hz for Nvdia Shield Tablet\n#define PERIOD_SEC    0.02      // 1/50 for Nvdia Shield Tablet\n//  Computed with imu_variance.py : Variance_Accelerometer = 0.0004\n#define SIGMA_SENSORS 0.02      // Variance of Nvdia Shield Tablet IMU                  */\n\n/*  -----------------------------------------------------------------------------\n    ROS Topics used for publishing the results and receiving the IMU measurements\n    -----------------------------------------------------------------------------       */\nros::Publisher pub_odometry;\nros::Subscriber sub_imu;\n\nconst char imu_topic_name[] = \"/imu_3dm_gx4/imu\";\n//const char imu_topic_name[] = \"/python_IMU\";\n\n\n/*  ----------------------------------\n    State vector\n\n    Representation using Euler angles:\n\n                [ Yaw ]\n            x = [Pitch]\n                [Roll ]\n\n    ----------------------------------   */\nVectorXd x(VectorXd::Zero(3));\n\n//  Bias of sensors\nconst MatrixXd Q(PERIOD_SEC * PERIOD_SEC * MatrixXd::Identity(3,3));\n\n//  Noise of sensors. We assume same value for accelerometer and gyroscope\nconst MatrixXd R(SIGMA_SENSORS * MatrixXd::Identity(3,3));\n\n/*  --------------------\n    Prediction variables\n    --------------------    */\n\n/*  Transition matrix A\n    We assume a linear model with no motion, no rotation.   */\nMatrixXd A(MatrixXd::Identity(3,3));\n\n//  Covariance estimate matrix P\nMatrixXd P(MatrixXd::Zero(3,3));\n\n\n\n/*  --------------------\n    Update variables\n    --------------------    */\n\n/*  Form of the measurements z:\n    \n        [accel-x]\n    z = [accel-y]   with (-1 <= z <= 1)\n        [accel-z]\n    Note. These accelerometer measurements values are normalised.   */\n\n/*  Measurement prediction vector H(x). It depends on the current\n    Yaw, Pitch and Roll values of the state.                        */\nVectorXd H(VectorXd::Zero(3));\n/*  Jacobian matrix of H in regard of x                             */\nMatrixXd J(MatrixXd::Zero(3,3));\n\n/*  Accelerometer and gyroscope measurement for IMU calibration.\n    These values are not used in the EKF but can be useful for\n    further implementations.                                        */\ndouble gx = 0;\ndouble gy = 0;\ndouble gz = 0;  //9.81\n\ndouble bias_gyro_x = 0;\ndouble bias_gyro_y = 0;\ndouble bias_gyro_z = 0;\n\n/*  IMU variables set at the start of the execution of the program.\n    Used for calibration.                                           */\ndouble current_t = 0;\nbool is_time_init = false;\nbool is_imu_init = false;\nint imu_count = 0;\n\n/*  Initialisation of the State initialisation.                     */\nvoid state_init(){\n    x.segment<3>(0) = Vector3d(0,0,0);\n}\n\n/*  Jacobian matrix Initialisation                                  */\nvoid jacobian_init(){\n    // block use: Selects the .block(1st value location, size matrix)\n    /*J.block(0,3,3,3) = MatrixXd::Identity(3,3);\n    J.block(0,6,3,3) = MatrixXd::Identity(3,3);*/\n}\n\n/* Covariance matrix Q initialisation                               */\nvoid my_Q_covariance_matrix_init(){\n    /*//  Values for the Nvidia shield tablet\n    Q.block(0,0,3,3) = 0.032 * 0.032 * MatrixXd::Identity(3,3);\n    Q.block(3,3,3,3) = 0.1 * 0.032 * MatrixXd::Identity(3,3);\n    Q.block(6,6,3,3) = 0.03 * 0.032 * MatrixXd::Identity(3,3);  //  */\n    /*//  Values for the test python publisher\n    //  0.02 ) 1/50 with 50hz\n    /*double delta_t = 1 / double(FREQ_HZ);\n    Q = delta_t * delta_t * MatrixXd::Identity(3,3);*/\n    /*Q.block(3,3,3,3) = 0.1 * 0.02 * MatrixXd::Identity(3,3);\n    Q.block(6,6,3,3) = 0.03 * 0.02 * MatrixXd::Identity(3,3);   //  */\n}\n\n/*  Computes the original orientation and gyroscope bias.\n    These values are not used in the EKF but can be useful for\n    further implementations.                                        */\nvoid imu_init(double ax, double ay, double az, \n              double rx, double ry, double rz){\n    gx += ax;\n    gy += ay;\n    gz += az;\n\n    bias_gyro_x += rx;\n    bias_gyro_y += ry;\n    bias_gyro_z += rz;\n\n    if(imu_count == IMU_COUNT_CALIBRATION){\n        gx /= imu_count;\n        gy /= imu_count;\n        gz /= imu_count;\n\n        bias_gyro_x /= imu_count;\n        bias_gyro_y /= imu_count;\n        bias_gyro_z /= imu_count;\n\n        cout << \"calibrated gx: \" << gx << endl;\n        cout << \"calibrated gy: \" << gy << endl;\n        cout << \"calibrated gz: \" << gz << endl;\n\n        cout << \"bias_gyro_x: \" << bias_gyro_x << endl;\n        cout << \"bias_gyro_y: \" << bias_gyro_y << endl;\n        cout << \"bias_gyro_z: \" << bias_gyro_z << endl;\n    }\n}\n\n\nVector3d get_euler_angles()\n{\n    return x.segment<3>(0);\n}\n\nvoid publishOdometryResult(double time_imu, double ax)\n{\n    //  Get current state variables\n    Vector3d angles = get_euler_angles();\n    double yaw   = angles(0);\n    double pitch = angles(1);\n    double roll  = angles(2);\n\n    //  Odometry results are published\n    nav_msgs::Odometry odometry;\n    odometry.header.stamp = ros::Time::now();\n    odometry.header.frame_id = \"world\";\n    odometry.pose.pose.position.x = 0;\n    odometry.pose.pose.position.y = 0;\n    odometry.pose.pose.position.z = 0;\n    odometry.pose.pose.orientation.x = 0;\n    odometry.pose.pose.orientation.y = 0;\n    odometry.pose.pose.orientation.z = 0;\n    odometry.pose.pose.orientation.w = 1;\n    odometry.twist.twist.linear.x = 0;\n    odometry.twist.twist.linear.y = 0;\n    odometry.twist.twist.linear.y = 0;\n    odometry.twist.twist.angular.z = angles(0);\n    /*  Fix for the pitch angular being always negative */\n    if(ax >= 0)\n        odometry.twist.twist.angular.y = abs(angles(1));\n    else\n        odometry.twist.twist.angular.y = -abs(angles(1));\n    odometry.twist.twist.angular.x = angles(2);\n\n    //  Publish EKF Results\n    pub_odometry.publish(odometry);\n\n    /*  For Debugging purposes: \n        The pitch, roll and yaw values are displayed on the terminal                */\n    if(EKF_DEBUG){\n        cout << \"--------------------------------------------\" << endl;\n        cout << \"End of kalman filtering for this imu dataset\" << endl;\n        cout << \"--------------------------------------------\" << endl;\n        ROS_INFO(\"Odometry results published after IMU sample time: %lf\", time_imu);\n        cout << \"Yaw: \" <<      yaw     << endl;\n        cout << \"Pitch: \" <<    pitch   << endl;\n        cout << \"Roll: \" <<     roll    << endl;\n        cout << \"                     \" << endl;\n\n        //  We limit the pitch and roll values to stop a non converging Kalman Filter\n        if(pitch > PITCH_MAX || pitch < -PITCH_MAX || roll > ROLL_MAX || roll < -ROLL_MAX){\n            cout << \"pitch or roll value too high \" << endl;\n            abort();\n        }\n    }\n}\n\n/*  Extended Kalman Filter prediction function. */\nvoid predict(double dt){\n    if(EKF_DEBUG){\n        cout << \"                       \" << endl;\n        cout << \" --------------------- \" << endl;\n        cout << \"  NEW STATE PREDICTION \" << endl;\n        cout << \" --------------------- \" << endl;\n        cout << \"                       \" << endl;\n    }\n\n    /*  -----------------------------\n        Predict the prediction matrix\n        -----------------------------\n            Prediction matrix A\n                    {1 0 0}\n                A = {0 1 0}\n                    {0 0 1}         */\n\n    MatrixXd A(MatrixXd::Identity(3,3));\n\n    x = A * x;\n\n    /*  The Yaw cannot be computed with this model.\n        To avoid a drift of this angle, it is set to zero.              */\n    x[0] = 0;\n\n    //  Covariance matrix prediction\n    P = A * P * A.transpose() + Q;\n\n    Vector3d angles = get_euler_angles();\n    double yaw   = angles(0);\n    double pitch = angles(1);\n    double roll  = angles(2);\n\n    if(EKF_DEBUG){\n        cout << \"predicted pitch   yaw   roll \"         << endl;\n        cout << pitch << \";  \"  << yaw << \";  \" << roll << endl;\n        cout << \"                 \"                     << endl;\n\n        cout << \"Value of P after prediction\"   << endl;\n        cout << P                               << endl;\n        cout << \"                 \"             << endl;\n\n        cout << \"Value of Q : \"                 << endl;\n        cout << Q                               << endl;\n        cout << \"                 \"             << endl;\n    }\n}\n\n/*  For Debugging purposes: \n    the state vector, measurements and EKF matrices\n    are displayed on the terminal.                              */\nvoid debug_ekf_cout(double pitch, double yaw, double roll,\n                    VectorXd z, Vector3d H, Matrix<double, 3, 3> J,\n                    VectorXd y, Matrix<double, 3, 3> S, \n                    Matrix<double, 3, 3> K, MatrixXd P){\n    cout << \"Old value of Pitch, yaw and Roll \" << endl;\n    cout << pitch << \"  \" << yaw << \"  \" << roll << endl;\n    cout << \"                 \" << endl;\n    cout << \"Value of z (ax, ay, az) :\" << endl;\n    cout << z << endl;\n    cout << \"                 \" << endl;\n    cout << \"H vector updated: \" << endl;\n    cout << H             << endl;\n    cout << \"           \" << endl;\n    cout << \"J matix updated: \" << endl;\n    cout << J << endl;\n    cout << \"                 \" << endl;\n    cout << \"Value of y \" << endl;\n    cout << y << endl;\n    cout << \"                 \" << endl;\n    /*cout << \"S  updated: \"<< endl;\n    cout << S << endl;\n    cout << \"                 \" << endl;\n    cout << \"S inverse updated: \"<< endl;\n    cout << S.inverse() << endl;\n    cout << \"                 \" << endl;*/\n    cout << \"K updated: \" << endl;\n    cout << K << endl;\n    cout << \"                 \" << endl;\n    cout << \"K * y updated: \" << endl;\n    cout << K * y << endl;\n    cout << \"                 \" << endl;\n    /*cout << \"P updated: \"<< endl;\n    cout << P << endl;\n    cout << \"                 \" << endl;*/\n}\n\n/*  Extended Kalman Filter update function. */\nvoid update(double ax, double ay, double az, double rx, double ry, double rz, double dt)\n{\n    if(EKF_DEBUG){\n        cout << \"                 \" << endl;\n        cout << \"---------------- \" << endl;\n        cout << \" NEW UPDATE n. \"   << imu_count << endl;\n        cout << \"---------------- \" << endl;\n        cout << \"                 \" << endl;\n    }\n\n    Vector3d angles = get_euler_angles();\n    double yaw   = angles(0);\n    double pitch = angles(1);\n    double roll  = angles(2);\n\n    //  Measurement Vector\n    VectorXd z(3);\n    z << ax, ay, az;\n\n    /*  ---------------------------------------------------\n        -                Measurement Model                -\n        ---------------------------------------------------   */\n\n    /*          --------------------------\n                Measurement vector z model\n                --------------------------\n                               T  (0)            -1       T\n                z = H(x) = Rzyx * (0),  with Rzyx   = Rzyx\n                                  (1)   and Rzyx = Rz*Ry*Rx = R = ...\n\n    [cos(yaw) -sin(yaw) 0][cos(pitch) 0 sin(pitch)][1     0          0    ]\n    [sin(yaw) cos(yaw)  0][    0      1      0    ][0 cos(roll) -sin(roll)]\n    [   0         0     1][-sin(pitch)0 cos(pitch)][0 sin(roll)  cos(roll)]\n\n            --------------------------------------\n            Jacobian matrix from measurement model\n            -------------------------------------- \n                    J = d/dx (H(x))  \n                                                                        */\n\n    //  Theoretical Measurement from state estimate:\n    Vector3d H(3);\n    H <<    -sin(pitch),\n            cos(pitch)*sin(roll),\n            cos(pitch)*cos(roll);\n\n            /*cos(yaw)*sin(pitch)*cos(roll) + sin(yaw)*sin(roll),\n            sin(yaw)*sin(pitch)*sin(roll) - cos(yaw)*sin(roll),\n            cos(pitch)*cos(roll);*/\n\n    //  Jacobian matrix J computation\n    Matrix<double, 3, 3> J;\n    J <<    0,  -cos(pitch),            0,\n            0,  -sin(pitch)*sin(roll),  cos(pitch)*cos(roll),\n            0,  -sin(pitch)*cos(roll),  -cos(pitch)*sin(roll);\n\n    /*   \n    -sin(yaw)*sin(pitch)*cos(roll)+cos(yaw)*sin(roll), cos(yaw)*cos(pitch)*cos(roll), -cos(yaw)*sin(pitch)*sin(roll)+sin(yaw)*cos(roll),\n    cos(yaw)*sin(pitch)*cos(roll)+sin(yaw)*sin(roll),  sin(yaw)*cos(pitch)*cos(roll), -sin(yaw)*sin(pitch)*sin(roll)-cos(yaw)*cos(roll),\n    0,                                                 -sin(pitch)*cos(roll),         -cos(pitch)*sin(roll);*/\n\n    /*  -------------------------------------\n        Update step of Extended Kalman Filter\n        -------------------------------------  */\n\n    //  Innovation vector\n    VectorXd y(3);\n    y = z - H;\n\n    //  Innovation covariance\n    MatrixXd S(3,3);\n    S = J * P * J.transpose() + R;\n\n    //  Kalman gain\n    MatrixXd K(3,3);\n    K = P * J * S.inverse();\n\n    //  State estimate update\n    x = x + K * y;\n\n    //  Covariance estimate update\n    P = (MatrixXd::Identity(3, 3) - K * J) * P;\n\n    //  If Debug Mode: Print all variables computed by this update\n    if(EKF_DEBUG){\n        debug_ekf_cout(pitch, yaw, roll, z, H, J, y, S, K, P);\n    }\n}\n\n/*  Extended Kalman Filter global function.             */\nvoid kalman_filtering(double ax, double ay, double az, \n                      double rx, double ry, double rz, \n                      double dt){\n    predict(dt);\n    update(ax, ay, az, rx, ry, rz, dt);\n}\n\n\n/*  IMU callback function.\n    Uses the IMU measurements to compute the new state variables using an EKF. */\nvoid imu_callback(const sensor_msgs::Imu& imu_msg)\n{\n    ROS_INFO(\"Time of IMU sample: %lf\", imu_msg.header.stamp.toSec());\n\n    /*  Accelerometer and Gyroscope measurements.\n        This version doesn't use the angular velocity values */\n    double ax = imu_msg.linear_acceleration.x;\n    double ay = imu_msg.linear_acceleration.y;\n    double az = imu_msg.linear_acceleration.z;\n    double rx = imu_msg.angular_velocity.x;\n    double ry = imu_msg.angular_velocity.y;\n    double rz = imu_msg.angular_velocity.z;\n\n    /*  ----------------------------------------------------------------------\n        Calibrate Inertial Measurement Unit (IMU) at the start of the program.\n        Can be useful in case of an initial spatial frame which is moving.\n        Uses the IMU_COUNT_CALIBRATION first IMU values.\n        ----------------------------------------------------------------------  */\n    imu_count++;\n    if(!is_imu_init){\n        imu_init(ax,ay,az,rx,ry,rz);\n        if(imu_count == IMU_COUNT_CALIBRATION){\n            is_imu_init = true;\n            imu_count = 0;\n        }\n        return;\n    }\n\n    //  After imu calibration, set the IMU time\n    if(!is_time_init){\n        current_t = imu_msg.header.stamp.toSec();\n        is_time_init = true;\n        return;\n    }\n\n    /*  --------------------------------\n        Accelerometer data normalisation\n        --------------------------------  */\n    double norm_accel = sqrt(ax * ax + ay * ay + az * az);\n    ax = ax / norm_accel;\n    ay = ay / norm_accel;\n    az = az / norm_accel;\n\n    /*  ---------------\n        IMU Time update\n        ---------------  */\n    double new_time = imu_msg.header.stamp.toSec();\n    double dt = new_time - current_t;\n    current_t = new_time;\n\n\n    /*  --------------------------------------------------------------\n        Extended Kalman Filtering.\n\n        In this version, only the accelerometer measurements are used.\n        --------------------------------------------------------------  */\n    kalman_filtering(ax, ay, az, rx, ry, rz, dt);\n\n\n    /*  -------------------------------------------------\n        Results of the EKF are pusblished in a ROS topic.\n        -------------------------------------------------  */\n    publishOdometryResult(imu_msg.header.stamp.toSec(), ax);\n}\n\nvoid setupROS()\n{\n    ros::NodeHandle n(\"~\");\n    ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug);\n\n    //  Define ROS topics to publish the results\n    pub_odometry     = n.advertise<nav_msgs::Odometry>(\"odometry\", 1000);\n\n    //  Define IMU Measurements ROS topic.\n    sub_imu = n.subscribe(imu_topic_name, 1000, imu_callback);\n}\n\nint main(int argc, char **argv)\n{\n    state_init();\n    jacobian_init();\n    my_Q_covariance_matrix_init();\n\n    ros::init(argc, argv, \"simpl_ekf\");\n\n    setupROS();\n    ros::spin();\n\n    return 0;\n}", "meta": {"hexsha": "d9e25af94b50a7110a9a466a8628618e7dd04831", "size": 18307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simpl_ekf/src/main.cpp", "max_stars_repo_name": "ThomasJLew/simpl_ekf", "max_stars_repo_head_hexsha": "8654088704fedda1b8e0d0bed1b12a45768addee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-07-02T02:22:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-04T14:28:49.000Z", "max_issues_repo_path": "simpl_ekf/src/main.cpp", "max_issues_repo_name": "ThomasJLew/simpl_ekf", "max_issues_repo_head_hexsha": "8654088704fedda1b8e0d0bed1b12a45768addee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simpl_ekf/src/main.cpp", "max_forks_repo_name": "ThomasJLew/simpl_ekf", "max_forks_repo_head_hexsha": "8654088704fedda1b8e0d0bed1b12a45768addee", "max_forks_repo_licenses": ["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.8041825095, "max_line_length": 136, "alphanum_fraction": 0.4939640575, "num_tokens": 4535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.614935296965644}}
{"text": "// STL includes\n#include <iostream>\n#include <vector>\n\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/biconnected_components.hpp>\n\n\nusing namespace std;\n\nstruct topological {\n  bool operator() (const pair<int, int> t0, const pair<int, int> t1) {\n    return (t0.first < t1.first) || (t0.first == t1.first && t0.second < t1.second);\n  }\n};\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n  boost::no_property, boost::property<boost::edge_weight_t, int> >      graph;\ntypedef boost::property_map<graph, boost::edge_weight_t>::type edge_map;\ntypedef boost::graph_traits<graph>::edge_descriptor            edge_desc;\ntypedef boost::graph_traits<graph>::vertex_descriptor          vertex_desc;\ntypedef boost::graph_traits<graph>::edge_iterator                         edge_it;\n\nvoid important_bridges(graph &G) {\n  edge_map component = boost::get(boost::edge_weight, G);\n  int ncc = boost::biconnected_components(G, component); \n  \n  vector<pair<int, int>> imp_bridges(0); \n  edge_it ebeg, eend;\n  vector<int> size_ncc(ncc, 0);\n  for (boost::tie(ebeg, eend) = boost::edges(G); ebeg != eend; ++ebeg) {\n    size_ncc[component[*ebeg]]++;\n  }\n  \n  for (boost::tie(ebeg, eend) = boost::edges(G); ebeg != eend; ++ebeg) {\n    int u = boost::source(*ebeg, G), v = boost::target(*ebeg, G);\n    if (size_ncc[component[*ebeg]] == 1) imp_bridges.push_back({min(u,v),max(u,v)});\n  }\n  std::sort(imp_bridges.begin(), imp_bridges.end(), topological());\n  cout << imp_bridges.size() << endl;\n  for(auto e : imp_bridges)\n    cout << e.first <<  \" \" << e.second << endl;\n  \n}\n\nvoid testcase()\n{\n  int n; cin >> n;\n  int m; cin >> m;\n  graph G(n);\n  for(int i = 0; i < m; i++) {\n    int e1, e2; cin >> e1; cin >> e2;\n    boost::add_edge(e1, e2, G);\n  }\n  \n  important_bridges(G);\n}\n\nint main() {\n  std::ios_base::sync_with_stdio(false); // Always!\n  int t; cin >> t;\n  while(t--) testcase();\n}\n", "meta": {"hexsha": "6dd8682117bad10162095da0fdbbe02b25d0d681", "size": 1931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week04-important_bridges/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/week04-important_bridges/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/week04-important_bridges/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7076923077, "max_line_length": 84, "alphanum_fraction": 0.640600725, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6149352822109917}}
{"text": "/**\n * \\file\n * \\copyright\n * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n */\n\n#include \"MathTools.h\"\n\n#include <Eigen/Dense>\n#include <cmath>\n\n#include \"Point3d.h\"\n\nnamespace MathLib\n{\n\ndouble calcProjPntToLineAndDists(Point3d const& pp, Point3d const& pa,\n                                 Point3d const& pb, double& lambda, double& d0)\n{\n    auto const a = Eigen::Map<Eigen::Vector3d const>(pa.getCoords());\n    auto const b = Eigen::Map<Eigen::Vector3d const>(pb.getCoords());\n    auto const p = Eigen::Map<Eigen::Vector3d const>(pp.getCoords());\n\n    // g(lambda) = a + lambda v, v = b-a\n    Eigen::Vector3d const v = b - a;\n\n    // orthogonal projection: (p - g(lambda))^T * v = 0\n    // <=> (a-p - lambda (b-a))^T * (b-a) = 0\n    // <=> (a-p)^T * (b-a) = lambda (b-a)^T ) (b-a)\n    lambda = (((p - a).transpose() * v) / v.squaredNorm())(0, 0);\n\n    // compute projected point\n    Eigen::Vector3d const proj_pnt = a + lambda * v;\n\n    d0 = (proj_pnt - a).norm();\n\n    return (p - proj_pnt).norm();\n}\n\ndouble getAngle(Point3d const& p0, Point3d const& p1, Point3d const& p2)\n{\n    auto const a = Eigen::Map<Eigen::Vector3d const>(p0.getCoords());\n    auto const b = Eigen::Map<Eigen::Vector3d const>(p1.getCoords());\n    auto const c = Eigen::Map<Eigen::Vector3d const>(p2.getCoords());\n    Eigen::Vector3d const v0 = a - b;\n    Eigen::Vector3d const v1 = c - b;\n\n    // apply Cauchy Schwarz inequality\n    return std::acos(\n        (v0.transpose() * v1 / (v0.norm() * v1.norm()))(0, 0));\n}\n\ndouble scalarTriple(Eigen::Vector3d const& u, Eigen::Vector3d const& v,\n                    Eigen::Vector3d const& w)\n{\n    return u.cross(v).dot(w);\n}\n\n}  // namespace MathLib\n", "meta": {"hexsha": "5d7017408e0e27d0471fc812588c52c4f8b96509", "size": 1870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MathLib/MathTools.cpp", "max_stars_repo_name": "yezhigangzju/ogs", "max_stars_repo_head_hexsha": "074c5129680e87516477708b081afe79facabe87", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-24T02:38:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-24T02:38:44.000Z", "max_issues_repo_path": "MathLib/MathTools.cpp", "max_issues_repo_name": "yezhigangzju/ogs", "max_issues_repo_head_hexsha": "074c5129680e87516477708b081afe79facabe87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MathLib/MathTools.cpp", "max_forks_repo_name": "yezhigangzju/ogs", "max_forks_repo_head_hexsha": "074c5129680e87516477708b081afe79facabe87", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6825396825, "max_line_length": 79, "alphanum_fraction": 0.5983957219, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6149352816776529}}
{"text": "#include <queue>\n#include <limits>\n#include <cmath>\n#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <Eigen/Dense>\n#include <iostream>\n\nnamespace py = pybind11;\n\nconst float INF = std::numeric_limits<float>::infinity();\n\n// represents a single pixel\nclass Node {\n  public:\n    int idx; // index in the flattened grid\n    float cost; // cost of traversing this pixel\n    int path_length; // the length of the path to reach this node\n\n    Node(int i, float c, int path_length) : idx(i), cost(c), path_length(path_length) {}\n};\n\n// the top of the priority queue is the greatest element by default,\n// but we want the smallest, so flip the sign\nbool operator<(const Node &n1, const Node &n2) {\n  return n1.cost > n2.cost;\n}\n\n// See for various grid heuristics:\n// http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#S7\n// L_\\inf norm (diagonal distance)\ninline float linf_norm(int i0, int j0, int i1, int j1) {\n  return std::max(std::abs(i0 - i1), std::abs(j0 - j1));\n}\n\n// L_1 norm (manhattan distance)\ninline float l1_norm(int i0, int j0, int i1, int j1) {\n  return std::abs(i0 - i1) + std::abs(j0 - j1);\n}\n\ninline float euclidean_distance(int i0, int j0, int i1, int j1) {\n    float xd =(float)(i0 - i1);\n    float yd =(float)(j0 - j1);\n    float dist = std::sqrt(xd*xd+yd*yd);\n  return dist;\n}\n\n\n// weights:        flattened h x w grid of costs\n// h, w:           height and width of grid\n// start, goal:    index of start/goal in flattened grid\n// diag_ok:        if true, allows diagonal moves (8-conn.)\n// paths (output): for each node, stores previous node in path\nEigen::MatrixXi astar(Eigen::RowVectorXf op_map, int height, int width, int start, int goal, bool allow_diagonal) {\n  int h = height;\n  int w = width;\n  int diag_ok = int(allow_diagonal);\n\n  float* weights = op_map.data();\n  int* paths = new int[h * w];\n  int path_length = -1;\n\n  Node start_node(start, 0., 1);\n\n  float* costs = new float[h * w];\n  for (int i = 0; i < h * w; ++i)\n    costs[i] = INF;\n  costs[start] = 0.;\n\n  std::priority_queue<Node> nodes_to_visit;\n  nodes_to_visit.push(start_node);\n\n  int* nbrs = new int[8];\n\n  while (!nodes_to_visit.empty()) {\n    // .top() doesn't actually remove the node\n    Node cur = nodes_to_visit.top();\n\n    if (cur.idx == goal) {\n      path_length = cur.path_length;\n      break;\n    }\n\n    nodes_to_visit.pop();\n\n    int row = cur.idx / w;\n    int col = cur.idx % w;\n    // check bounds and find up to eight neighbors: top to bottom, left to right\n    nbrs[0] = (diag_ok && row > 0 && col > 0)          ? cur.idx - w - 1   : -1;\n    nbrs[1] = (row > 0)                                ? cur.idx - w       : -1;\n    nbrs[2] = (diag_ok && row > 0 && col + 1 < w)      ? cur.idx - w + 1   : -1;\n    nbrs[3] = (col > 0)                                ? cur.idx - 1       : -1;\n    nbrs[4] = (col + 1 < w)                            ? cur.idx + 1       : -1;\n    nbrs[5] = (diag_ok && row + 1 < h && col > 0)      ? cur.idx + w - 1   : -1;\n    nbrs[6] = (row + 1 < h)                            ? cur.idx + w       : -1;\n    nbrs[7] = (diag_ok && row + 1 < h && col + 1 < w ) ? cur.idx + w + 1   : -1;\n\n    float heuristic_cost;\n    for (int i = 0; i < 8; ++i) {\n      if (nbrs[i] >= 0) {\n        // the sum of the cost so far and the cost of this move\n        float new_cost = costs[cur.idx] + weights[nbrs[i]];\n        if (new_cost < costs[nbrs[i]]) {\n          // estimate the cost to the goal based on legal moves\n          heuristic_cost = euclidean_distance(nbrs[i] / w, nbrs[i] % w,\n                                       goal    / w, goal    % w);\n\n          // paths with lower expected cost are explored first\n          float priority = new_cost + heuristic_cost;\n          nodes_to_visit.push(Node(nbrs[i], priority, cur.path_length + 1));\n\n          costs[nbrs[i]] = new_cost;\n          paths[nbrs[i]] = cur.idx;\n        }\n      }\n    }\n  }\n\n  Eigen::MatrixXi path_return(2, path_length);\n\n  int idx = goal;\n  for (int i = path_length - 1; i >= 0; --i) {\n      int point_x = idx / w;\n      int point_y = idx % w;\n\n      path_return(0, i) = point_x;\n      path_return(1, i) = point_y;\n\n      idx = paths[idx];\n  }\n\n  delete[] costs;\n  delete[] nbrs;\n  delete[] paths;\n\n  return path_return;\n}\n\nPYBIND11_PLUGIN(astar) {\n  py::module m(\"astar\", \"astar\");\n  m.def(\"astar\", &astar, \"astar\");\n  return m.ptr();\n}", "meta": {"hexsha": "f0b4189f4ccbba9371a446f5831f0665d844812f", "size": 4364, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/astar.cpp", "max_stars_repo_name": "oiqbal95/RL-Self-Exploration-Mapping", "max_stars_repo_head_hexsha": "71350bdcf9d4429e23de5e62cf5e1a6e655026d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2020-07-25T11:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:17:43.000Z", "max_issues_repo_path": "src/astar.cpp", "max_issues_repo_name": "oiqbal95/RL-Self-Exploration-Mapping", "max_issues_repo_head_hexsha": "71350bdcf9d4429e23de5e62cf5e1a6e655026d3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-08T02:05:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T13:15:57.000Z", "max_forks_repo_path": "src/astar.cpp", "max_forks_repo_name": "oiqbal95/RL-Self-Exploration-Mapping", "max_forks_repo_head_hexsha": "71350bdcf9d4429e23de5e62cf5e1a6e655026d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-09-07T03:32:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T11:17:29.000Z", "avg_line_length": 30.5174825175, "max_line_length": 115, "alphanum_fraction": 0.5689734189, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.614913176076866}}
{"text": "/*******************************************************************************\n * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.\n * \n * Licensed under the MIT License (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://opensource.org/licenses/MIT\n * \n * Developers:\n *   Sebastian Niemann - Lead developer\n *   Daniel Kiechle - Unit testing\n ******************************************************************************/\n#include <Expected.hpp>\nusing armadilloJava::Expected;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <cmath>\nusing std::log;\nusing std::sqrt;\nusing std::pow;\n\n#include <fstream>\nusing std::ofstream;\n\n#include <streambuf>\nusing std::streambuf;\n\n#include <utility>\nusing std::pair;\n\n#include <armadillo>\nusing arma::Mat;\nusing arma::Col;\nusing arma::uword;\nusing arma::abs;\nusing arma::eps;\nusing arma::exp;\nusing arma::exp2;\nusing arma::exp10;\nusing arma::trunc_exp;\nusing arma::log;\nusing arma::log2;\nusing arma::log10;\nusing arma::trunc_log;\nusing arma::sqrt;\nusing arma::square;\nusing arma::floor;\nusing arma::ceil;\nusing arma::round;\nusing arma::sign;\nusing arma::sin;\nusing arma::asin;\nusing arma::sinh;\nusing arma::asinh;\nusing arma::cos;\nusing arma::acos;\nusing arma::cosh;\nusing arma::acosh;\nusing arma::tan;\nusing arma::atan;\nusing arma::tanh;\nusing arma::atanh;\nusing arma::cond;\nusing arma::rank;\nusing arma::diagvec;\nusing arma::min;\nusing arma::max;\nusing arma::prod;\nusing arma::mean;\nusing arma::median;\nusing arma::stddev;\nusing arma::var;\nusing arma::cor;\nusing arma::cov;\nusing arma::cumsum;\nusing arma::fliplr;\nusing arma::flipud;\nusing arma::hist;\nusing arma::sort;\nusing arma::trans;\nusing arma::unique;\nusing arma::vectorise;\nusing arma::lu;\nusing arma::pinv;\nusing arma::princomp;\nusing arma::qr;\nusing arma::qr_econ;\nusing arma::svd;\nusing arma::svd_econ;\nusing arma::accu;\n\n#include <InputClass.hpp>\nusing armadilloJava::InputClass;\n\n#include <Input.hpp>\nusing armadilloJava::Input;\n\nnamespace armadilloJava {\n  class ExpectedGenMat : public Expected {\n    public:\n      ExpectedGenMat() {\n        cout << \"Compute ExpectedGenMat(): \" << endl;\n\n          vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({\n            InputClass::GenMat\n          });\n\n          for (vector<pair<string, void*>> input : inputs) {\n            _fileSuffix = \"\";\n\n            int n = 0;\n            for (pair<string, void*> value : input) {\n              switch (n) {\n                case 0:\n                  _fileSuffix += value.first;\n                  _genMat = *static_cast<Mat<double>*>(value.second);\n                  break;\n              }\n              ++n;\n            }\n\n            cout << \"Using input: \" << _fileSuffix << endl;\n\n            expectedArmaAbs();\n            expectedArmaEps();\n            expectedArmaExp();\n            expectedArmaExp2();\n            expectedArmaExp10();\n            expectedArmaTrunc_exp();\n            expectedArmaLog();\n            expectedArmaLog2();\n            expectedArmaLog10();\n            expectedArmaTrunc_log();\n            expectedArmaSqrt();\n            expectedArmaSquare();\n            expectedArmaFloor();\n            expectedArmaCeil();\n            expectedArmaRound();\n            expectedArmaSign();\n            expectedArmaSin();\n            expectedArmaAsin();\n            expectedArmaSinh();\n            expectedArmaAsinh();\n            expectedArmaCos();\n            expectedArmaAcos();\n            expectedArmaCosh();\n            expectedArmaAcosh();\n            expectedArmaTan();\n            expectedArmaAtan();\n            expectedArmaTanh();\n            expectedArmaAtanh();\n            expectedArmaCond();\n            expectedArmaRank();\n            expectedArmaDiagvec();\n            expectedArmaMin();\n            expectedArmaMax();\n            expectedArmaProd();\n            expectedArmaMean();\n            expectedArmaMedian();\n            expectedArmaStddev();\n            expectedArmaVar();\n            expectedArmaCor();\n            expectedArmaCov();\n            expectedArmaCumsum();\n            expectedArmaFliplr();\n            expectedArmaFlipud();\n            expectedArmaHist();\n            expectedArmaSort();\n            expectedArmaTrans();\n            expectedArmaUnique();\n            expectedArmaVectorise();\n            expectedArmaLu();\n            expectedArmaPinv();\n            expectedArmaPrincomp();\n            expectedArmaQr();\n            expectedArmaQr_econ();\n            expectedArmaSvd();\n            expectedArmaSvd_econ();\n            expectedArmaNegate();\n            expectedArmaReciprocal();\n            expectedArmaAccu();\n            expectedMatMin();\n            expectedMatMax();\n            expectedMatSize();\n            expectedMatIs_finite();\n            expectedMatT();\n            expectedMatDiag();\n            expectedMatIs_square();\n            expectedMatIs_vec();\n            expectedMatIs_colvec();\n            expectedMatIs_rowvec();\n            expectedMatPrint();\n            expectedMatRaw_print();\n            expectedMat();\n          }\n\n          cout << \"done.\" << endl;\n        }\n\n    protected:\n      Mat<double> _genMat;\n\n      void expectedArmaAbs() {\n        cout << \"- Compute expectedArmaAbs() ... \";\n        save<double>(\"Arma.abs\", abs(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaEps() {\n        cout << \"- Compute expectedArmaAbs() ... \";\n        save<double>(\"Arma.eps\", eps(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaExp() {\n        cout << \"- Compute expectedArmaExp() ... \";\n        save<double>(\"Arma.exp\", exp(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaExp2() {\n        cout << \"- Compute expectedArmaExp2() ... \";\n        save<double>(\"Arma.exp2\", exp2(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaExp10() {\n        cout << \"- Compute expectedArmaExp10() ... \";\n        save<double>(\"Arma.exp10\", exp10(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrunc_exp() {\n        cout << \"- Compute expectedArmaTrunc_exp() ... \";\n        save<double>(\"Arma.trunc_exp\", trunc_exp(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaLog() {\n        cout << \"- Compute expectedArmaLog() ... \";\n        save<double>(\"Arma.log\", log(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaLog2() {\n        cout << \"- Compute expectedArmaLog2() ... \";\n        save<double>(\"Arma.log2\", log2(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaLog10() {\n        cout << \"- Compute expectedArmaLog10() ... \";\n        save<double>(\"Arma.log10\", log10(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrunc_log() {\n        cout << \"- Compute expectedArmaTrunc_log() ... \";\n        save<double>(\"Arma.trunc_log\", trunc_log(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSqrt() {\n        cout << \"- Compute expectedArmaSqrt() ... \";\n        save<double>(\"Arma.sqrt\", sqrt(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSquare() {\n        cout << \"- Compute expectedArmaSquare() ... \";\n        save<double>(\"Arma.square\", square(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaFloor() {\n        cout << \"- Compute expectedArmaFloor() ... \";\n        save<double>(\"Arma.floor\", floor(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCeil() {\n        cout << \"- Compute expectedArmaCeil() ... \";\n        save<double>(\"Arma.ceil\", ceil(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaRound() {\n        cout << \"- Compute expectedArmaRound() ... \";\n        save<double>(\"Arma.round\", round(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSign() {\n        cout << \"- Compute expectedArmaSign() ... \";\n        save<double>(\"Arma.sign\", sign(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSin() {\n        cout << \"- Compute expectedArmaSin() ... \";\n        save<double>(\"Arma.sin\", sin(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAsin() {\n        cout << \"- Compute expectedArmaAsin() ... \";\n        save<double>(\"Arma.asin\", asin(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSinh() {\n        cout << \"- Compute expectedArmaSinh() ... \";\n        save<double>(\"Arma.sinh\", sinh(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAsinh() {\n        cout << \"- Compute expectedArmaAsinh() ... \";\n        save<double>(\"Arma.asinh\", asinh(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCos() {\n        cout << \"- Compute expectedArmaCos() ... \";\n        save<double>(\"Arma.cos\", cos(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAcos() {\n        cout << \"- Compute expectedArmaAcos() ... \";\n        save<double>(\"Arma.acos\", acos(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCosh() {\n        cout << \"- Compute expectedArmaCosh() ... \";\n        save<double>(\"Arma.cosh\", cosh(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAcosh() {\n        cout << \"- Compute expectedArmaAcosh() ... \";\n\n        /*\n         * acosh behaves buggy on some systems, with acosh(inf) = nan instead of inf\n         */\n        //save<double>(\"Arma.acosh\", acosh(_genMat));\n\n        Mat<double> expected = _genMat;\n        expected.transform([](double value) {\n          return log(value + sqrt(pow(value, 2) - 1));\n        });\n        save<double>(\"Arma.acosh\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTan() {\n        cout << \"- Compute expectedArmaTan() ... \";\n        save<double>(\"Arma.tan\", tan(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAtan() {\n        cout << \"- Compute expectedArmaAtan() ... \";\n        save<double>(\"Arma.atan\", atan(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTanh() {\n        cout << \"- Compute expectedArmaTanh() ... \";\n        save<double>(\"Arma.tanh\", tanh(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAtanh() {\n        cout << \"- Compute expectedArmaAtanh() ... \";\n        save<double>(\"Arma.atanh\", atanh(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCond() {\n        cout << \"- Compute expectedArmaCond() ... \";\n        save<double>(\"Arma.cond\", Mat<double>({cond(_genMat)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaRank() {\n        cout << \"- Compute expectedArmaRank() ... \";\n        save<double>(\"Arma.rank\", Mat<double>({static_cast<double>(rank(_genMat))}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaDiagvec() {\n        cout << \"- Compute expectedArmaDiagvec() ... \";\n        save<double>(\"Arma.diagvec\", diagvec(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMin() {\n        cout << \"- Compute expectedArmaMin() ... \";\n        save<double>(\"Arma.min\", min(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMax() {\n        cout << \"- Compute expectedArmaMax() ... \";\n        save<double>(\"Arma.max\", max(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaProd() {\n        cout << \"- Compute expectedArmaProd() ... \";\n        save<double>(\"Arma.prod\", prod(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMean() {\n        cout << \"- Compute expectedArmaMean() ... \";\n        save<double>(\"Arma.mean\", mean(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMedian() {\n        cout << \"- Compute expectedArmaMedian() ... \";\n        save<double>(\"Arma.median\", median(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaStddev() {\n        cout << \"- Compute expectedArmaStddev() ... \";\n        save<double>(\"Arma.stddev\", stddev(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaVar() {\n        cout << \"- Compute expectedArmaVar() ... \";\n        save<double>(\"Arma.var\", var(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCor() {\n        cout << \"- Compute expectedArmaCor() ... \";\n        save<double>(\"Arma.cor\", cor(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCov() {\n        cout << \"- Compute expectedArmaCov() ... \";\n        save<double>(\"Arma.cov\", cov(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCumsum() {\n        cout << \"- Compute expectedArmaCumsum() ... \";\n        save<double>(\"Arma.cumsum\", cumsum(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaFliplr() {\n        cout << \"- Compute expectedArmaFliplr() ... \";\n        save<double>(\"Arma.fliplr\", fliplr(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaFlipud() {\n        cout << \"- Compute expectedArmaFlipud() ... \";\n        save<double>(\"Arma.flipud\", flipud(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaHist() {\n        cout << \"- Compute expectedArmaHist() ... \";\n        save<uword>(\"Arma.hist\", hist(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSort() {\n        if(!_genMat.is_finite()) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaSort() ... \";\n        save<double>(\"Arma.sort\", sort(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrans() {\n        cout << \"- Compute expectedArmaTrans() ... \";\n        save<double>(\"Arma.trans\", trans(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaUnique() {\n        cout << \"- Compute expectedArmaUnique() ... \";\n        save<double>(\"Arma.unique\", unique(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaVectorise() {\n        cout << \"- Compute expectedArmaVectorise() ... \";\n        save<double>(\"Arma.vectorise\", vectorise(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaLu() {\n        cout << \"- Compute expectedArmaLu() ... \";\n\n        Mat<double> L, U;\n\n        if(lu(L, U, _genMat)) {\n          save<double>(\"Arma.lu\", Mat<double>({1}));\n        } else {\n          save<double>(\"Arma.lu\", Mat<double>({0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaPinv() {\n        cout << \"- Compute expectedArmaPinv() ... \";\n        save<double>(\"Arma.pinv\", pinv(_genMat));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaPrincomp() {\n        cout << \"- Compute expectedArmaPrincomp() ... \";\n\n        Mat<double> coeff, score;\n        Col<double> latent, tsquared;\n\n        princomp(coeff, score, latent, tsquared, _genMat);\n\n        save<double>(\"Arma.princompLatent\", Mat<double>(latent));\n\n        cout << \"done.\" << endl;\n\n      }\n\n      void expectedArmaQr() {\n        cout << \"- Compute expectedArmaQr() ... \";\n\n        Mat<double> Q, R;\n\n        qr(Q, R, _genMat);\n\n        save<double>(\"Arma.qrQ\", Q);\n        save<double>(\"Arma.qrR\", R);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaQr_econ() {\n        cout << \"- Compute expectedArmaQr_econ() ... \";\n\n        Mat<double> Q, R;\n\n        qr_econ(Q, R, _genMat);\n\n        save<double>(\"Arma.qr_econQ\", Q);\n        save<double>(\"Arma.qr_econR\", R);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSvd() {\n        cout << \"- Compute expectedArmaSvd() ... \";\n\n        Mat<double> U, V;\n        Col<double> s;\n\n        svd(U, s, V, _genMat);\n        save<double>(\"Arma.svd\", Mat<double>(s));\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSvd_econ() {\n        cout << \"- Compute expectedArmaSvd_econ() ... \";\n\n        Mat<double> U, V;\n        Col<double> s;\n\n        svd_econ(U, s, V, _genMat);\n        save<double>(\"Arma.svd_econ\", Mat<double>(s));\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaNegate() {\n        cout << \"- Compute expectedArmaNegate() ... \";\n        save<double>(\"Arma.negate\", -_genMat);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaReciprocal() {\n        cout << \"- Compute expectedArmaReciprocal() ... \";\n        save<double>(\"Arma.reciprocal\", 1/_genMat);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAccu() {\n        cout << \"- Compute expectedArmaAccu() ... \";\n        save<double>(\"Arma.accu\", Mat<double>({accu(_genMat)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatMin() {\n        cout << \"- Compute expectedMatMinB() ... \";\n\n        double value;\n        uword row;\n        uword column;\n\n        value = _genMat.min(row, column);\n\n        save<double>(\"Mat.minValue\", Mat<double>({value}));\n        save<double>(\"Mat.minRow\", Mat<double>({static_cast<double>(row)}));\n        save<double>(\"Mat.minColumn\", Mat<double>({static_cast<double>(column)}));\n        save<double>(\"Mat.minIndex\", Mat<double>({static_cast<double>(row + column * _genMat.n_rows)}));\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatMax() {\n        cout << \"- Compute expectedMatMaxB() ... \";\n\n        double value;\n        uword row;\n        uword column;\n\n        value = _genMat.max(row, column);\n\n        save<double>(\"Mat.maxValue\", Mat<double>({value}));\n        save<double>(\"Mat.maxRow\", Mat<double>({static_cast<double>(row)}));\n        save<double>(\"Mat.maxColumn\", Mat<double>({static_cast<double>(column)}));\n        save<double>(\"Mat.maxIndex\", Mat<double>({static_cast<double>(row + column * _genMat.n_rows)}));\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatSize() {\n        cout << \"- Compute expectedMatSize() ... \";\n        save<double>(\"Mat.size\", Mat<double>({static_cast<double>(_genMat.size())}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatIs_finite() {\n        cout << \"- Compute expectedMatIs_finite() ... \";\n\n        if(_genMat.is_finite()) {\n          save<double>(\"Mat.is_finite\", Mat<double>({1}));\n        } else {\n          save<double>(\"Mat.is_finite\", Mat<double>({0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatT() {\n        cout << \"- Compute expectedMatT() ... \";\n        save<double>(\"Mat.t\", _genMat.t());\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatDiag() {\n        cout << \"- Compute expectedMatDiag() ... \";\n        save<double>(\"Mat.diag\", _genMat.diag());\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatIs_square() {\n        cout << \"- Compute expectedMatIs_square() ... \";\n\n        if(_genMat.is_square()) {\n          save<double>(\"Mat.is_square\", Mat<double>({1}));\n        } else {\n          save<double>(\"Mat.is_square\", Mat<double>({0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatIs_vec() {\n        cout << \"- Compute expectedMatIs_vec() ... \";\n\n        if(_genMat.is_vec()) {\n          save<double>(\"Mat.is_vec\", Mat<double>({1}));\n        } else {\n          save<double>(\"Mat.is_vec\", Mat<double>({0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatIs_colvec() {\n        cout << \"- Compute expectedMatIs_colvec() ... \";\n\n        if(_genMat.is_colvec()) {\n          save<double>(\"Mat.is_colvec\", Mat<double>({1}));\n        } else {\n          save<double>(\"Mat.is_colvec\", Mat<double>({0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatIs_rowvec() {\n        cout << \"- Compute expectedMatIs_rowvec() ... \";\n\n        if(_genMat.is_rowvec()) {\n          save<double>(\"Mat.is_rowvec\", Mat<double>({1}));\n        } else {\n          save<double>(\"Mat.is_rowvec\", Mat<double>({0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatPrint() {\n        cout << \"- Compute expectedMatPrint() ... \";\n\n        ofstream expected(_filepath + \"Mat.print(\" + _fileSuffix + \").txt\");\n        streambuf* previousBuffer = cout.rdbuf(expected.rdbuf());\n\n        _genMat.print();\n\n        cout.rdbuf(previousBuffer);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMatRaw_print() {\n        cout << \"- Compute expectedMatRaw_print() ... \";\n\n        ofstream expected(_filepath + \"Mat.raw_print(\" + _fileSuffix + \").txt\");\n        streambuf* previousBuffer = cout.rdbuf(expected.rdbuf());\n\n        _genMat.raw_print();\n\n        cout.rdbuf(previousBuffer);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMat() {\n        cout << \"- Compute expectedMat() ... \";\n        save<double>(\"Mat\", _genMat);\n        cout << \"done.\" << endl;\n      }\n  };\n}\n", "meta": {"hexsha": "8bfbde0b2f78efefc76e02f2a5cf9b8ec0781840", "size": 20818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/src/ExpectedGenMat.cpp", "max_stars_repo_name": "sebiniemann/ArmadilloJava", "max_stars_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-08-05T14:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T17:46:54.000Z", "max_issues_repo_path": "src/test/cpp/src/ExpectedGenMat.cpp", "max_issues_repo_name": "sebiniemann/ArmadilloJava", "max_issues_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-10-20T21:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T21:53:47.000Z", "max_forks_repo_path": "src/test/cpp/src/ExpectedGenMat.cpp", "max_forks_repo_name": "sebiniemann/ArmadilloJava", "max_forks_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T17:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:45:14.000Z", "avg_line_length": 27.500660502, "max_line_length": 104, "alphanum_fraction": 0.5207512729, "num_tokens": 5151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6149131741801336}}
{"text": "#include <boost/numeric/ublas/vector.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n\nnamespace ub = boost::numeric::ublas;\n\nstruct SimpleHarmonic {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x, T t){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(1);\n\t\ty(1) = - x(0);\n\n\t\treturn y;\n\t}\n\n\ttemplate <class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >&  x) {\n\t\tx.resize(2);\n\t\tx(0) = 0.;\n\t\tx(1) = 1.;\n\t}\n\n\ttemplate <class T>\n\tvoid start_time(kv::interval<T>& x) {\n\t\tx = 0.;\n\t}\n\n\ttemplate <class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\t\tx = 100.;\n\t}\n};\n\nstruct Lorenz {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x, T t){\n\t\tub::vector<T> y(3);\n\n\t\ty(0) = 10. * ( x(1) - x(0) );\n\t\ty(1) = 28. * x(0) - x(1) - x(0) * x(2);\n\t\ty(2) = (-8./3.) * x(2) + x(0) * x(1);\n\n\t\treturn y;\n\t}\n\n\ttemplate <class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >&  x) {\n\t\tx.resize(3);\n\t\tx(0) = 15.;\n\t\tx(1) = 15.;\n\t\tx(2) = 36.;\n\t}\n\n\ttemplate <class T>\n\tvoid start_time(kv::interval<T>& x) {\n\t\tx = 0.;\n\t}\n\n\ttemplate <class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\t\tx = 20.;\n\t}\n};\n\nstruct VdP {\n\tdouble mu;\n\n\tVdP(double mu = 0.25) : mu(mu) {}\n\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x, T t){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(1);\n\t\ty(1) = mu * (1. - x(0)*x(0))*x(1) - x(0);\n\n\t\treturn y;\n\t}\n\n\ttemplate <class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >&  x) {\n\t\tx.resize(2);\n\t\tx(0) = 1.;\n\t\tx(1) = 1.;\n\t}\n\n\ttemplate <class T>\n\tvoid start_time(kv::interval<T>& x) {\n\t\tx = 0.;\n\t}\n\n\ttemplate <class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\t\tx = 20.;\n\t}\n};\n\nstruct Nobi {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x, T t){\n\t\tub::vector<T> y(2);\n\n\t\ty(0) = x(1);\n\t\ty(1) = x(0) - x(0)*x(0)*x(0);\n\n\t\treturn y;\n\t}\n\n\ttemplate <class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >&  x) {\n\t\tx.resize(2);\n\t\tx(0) = 0.;\n\t\tx(1) = 4.;\n\t\t// x(0) = kv::interval<T>(-0.05, 0.05);\n\t\t// x(1) = kv::interval<T>(3.95, 4.05);\n\t}\n\n\ttemplate <class T>\n\tvoid start_time(kv::interval<T>& x) {\n\t\tx = 0.;\n\t}\n\n\ttemplate <class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\t\tx = \"3.3\";\n\t}\n};\n\nstruct QuadTest1 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x, T t){\n\t\tub::vector<T> y(1);\n\n\t\ty(0) = t * t;\n\n\t\treturn y;\n\t}\n\n\ttemplate <class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >&  x) {\n\t\tx.resize(1);\n\t\tx(0) = 0.;\n\t}\n\n\ttemplate <class T>\n\tvoid start_time(kv::interval<T>& x) {\n\t\tx = 0.;\n\t}\n\n\ttemplate <class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\t\tx = 20.;\n\t}\n};\n\nstruct QuadTest2 {\n\ttemplate <class T> ub::vector<T> operator() (const ub::vector<T>& x, T t){\n\t\tub::vector<T> y(1);\n\n\t\ty(0) = 0.;\n\n\t\treturn y;\n\t}\n\n\ttemplate <class T>\n\tvoid initial_value(ub::vector< kv::interval<T> >&  x) {\n\t\tx.resize(1);\n\t\tx(0) = 0.;\n\t}\n\n\ttemplate <class T>\n\tvoid start_time(kv::interval<T>& x) {\n\t\tx = 0.;\n\t}\n\n\ttemplate <class T>\n\tvoid stop_time(kv::interval<T>& x) {\n\t\tx = 20.;\n\t}\n};\n", "meta": {"hexsha": "540306acb01299509ee833c313c880116392ffa2", "size": 2967, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "example/ivp-example.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "example/ivp-example.hpp", "max_issues_repo_name": "soonho-tri/kv", "max_issues_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "example/ivp-example.hpp", "max_forks_repo_name": "soonho-tri/kv", "max_forks_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 16.6685393258, "max_line_length": 75, "alphanum_fraction": 0.5433097405, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6149131741801336}}
{"text": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_REFINE_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_REFINE_RSQRT_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/function/fnms.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/half.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD ( refine_rsqrt_\n                          , (typename T)\n                          , bd::cpu_\n                          , bd::scalar_<bd::floating_<T>>\n                          , bd::scalar_<bd::floating_<T>>\n                          )\n  {\n    BOOST_FORCEINLINE T operator()(T a0, T x) const BOOST_NOEXCEPT\n    {\n      // Newton-Raphson\n      return fma( fnms(a0, sqr(x), One<T>()), x*Half<T>(), x);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "15c867df28a3eb1516014b0c41d27fa02fd7898d", "size": 1339, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/refine_rsqrt.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/scalar/function/refine_rsqrt.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/scalar/function/refine_rsqrt.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 33.475, "max_line_length": 100, "alphanum_fraction": 0.5474234503, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.6148829422600407}}
{"text": "// All content Copyright (C) 2018 Genomics plc\n#define BOOST_TEST_DYN_LINK\n\n#include <boost/test/unit_test.hpp>\n\n#include \"utils/multinomialCoefficients.hpp\"\n\nBOOST_AUTO_TEST_CASE( factorial_0 ) { BOOST_CHECK_EQUAL( 1, factorial( 0 ) ); }\n\nBOOST_AUTO_TEST_CASE( factorial_1 ) { BOOST_CHECK_EQUAL( 1, factorial( 1 ) ); }\n\nBOOST_AUTO_TEST_CASE( factorial_2 ) { BOOST_CHECK_EQUAL( 2, factorial( 2 ) ); }\n\nBOOST_AUTO_TEST_CASE( factorial_3 ) { BOOST_CHECK_EQUAL( 6, factorial( 3 ) ); }\n", "meta": {"hexsha": "c6e453235cebbc18ae4ad15fe86da324012e09c7", "size": 482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/test/unittest/utils/testFactorial.cpp", "max_stars_repo_name": "dylex/wecall", "max_stars_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-08T15:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T07:13:05.000Z", "max_issues_repo_path": "cpp/test/unittest/utils/testFactorial.cpp", "max_issues_repo_name": "dylex/wecall", "max_issues_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-05T09:16:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-09T12:32:56.000Z", "max_forks_repo_path": "cpp/test/unittest/utils/testFactorial.cpp", "max_forks_repo_name": "dylex/wecall", "max_forks_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T07:28:33.000Z", "avg_line_length": 32.1333333333, "max_line_length": 79, "alphanum_fraction": 0.7510373444, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.7520125848754471, "lm_q1q2_score": 0.6148262951705717}}
{"text": "//            Copyright Daniel Trebbien 2010.\n// Distributed under the Boost Software License, Version 1.0.\n//   (See accompanying file LICENSE_1_0.txt or the copy at\n//         http://www.boost.org/LICENSE_1_0.txt)\n\n#include <cassert>\n#include <cstddef>\n#include <cstdlib>\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/one_bit_color_map.hpp>\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/typeof/typeof.hpp>\n\nstruct edge_t\n{\n    unsigned long first;\n    unsigned long second;\n};\n\n// A graphic of the min-cut is available at\n// <http://www.boost.org/doc/libs/release/libs/graph/doc/stoer_wagner_imgs/stoer_wagner.cpp.gif>\nint main()\n{\n    using namespace std;\n\n    typedef boost::adjacency_list< boost::vecS, boost::vecS, boost::undirectedS,\n        boost::no_property, boost::property< boost::edge_weight_t, int > >\n        undirected_graph;\n    typedef boost::property_map< undirected_graph, boost::edge_weight_t >::type\n        weight_map_type;\n    typedef boost::property_traits< weight_map_type >::value_type weight_type;\n\n    // define the 16 edges of the graph. {3, 4} means an undirected edge between\n    // vertices 3 and 4.\n    edge_t edges[] = { { 3, 4 }, { 3, 6 }, { 3, 5 }, { 0, 4 }, { 0, 1 },\n        { 0, 6 }, { 0, 7 }, { 0, 5 }, { 0, 2 }, { 4, 1 }, { 1, 6 }, { 1, 5 },\n        { 6, 7 }, { 7, 5 }, { 5, 2 }, { 3, 4 } };\n\n    // for each of the 16 edges, define the associated edge weight. ws[i] is the\n    // weight for the edge that is described by edges[i].\n    weight_type ws[] = { 0, 3, 1, 3, 1, 2, 6, 1, 8, 1, 1, 80, 2, 1, 1, 4 };\n\n    // construct the graph object. 8 is the number of vertices, which are\n    // numbered from 0 through 7, and 16 is the number of edges.\n    undirected_graph g(edges, edges + 16, ws, 8, 16);\n\n    // define a property map, `parities`, that will store a boolean value for\n    // each vertex. Vertices that have the same parity after\n    // `stoer_wagner_min_cut` runs are on the same side of the min-cut.\n    BOOST_AUTO(parities,\n        boost::make_one_bit_color_map(\n            num_vertices(g), get(boost::vertex_index, g)));\n\n    // run the Stoer-Wagner algorithm to obtain the min-cut weight. `parities`\n    // is also filled in.\n    int w = boost::stoer_wagner_min_cut(\n        g, get(boost::edge_weight, g), boost::parity_map(parities));\n\n    cout << \"The min-cut weight of G is \" << w << \".\\n\" << endl;\n    assert(w == 7);\n\n    cout << \"One set of vertices consists of:\" << endl;\n    size_t i;\n    for (i = 0; i < num_vertices(g); ++i)\n    {\n        if (get(parities, i))\n            cout << i << endl;\n    }\n    cout << endl;\n\n    cout << \"The other set of vertices consists of:\" << endl;\n    for (i = 0; i < num_vertices(g); ++i)\n    {\n        if (!get(parities, i))\n            cout << i << endl;\n    }\n    cout << endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "ce5b0e59ce7f8c7dbc49e1e463ea43931e557c0b", "size": 2954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/stoer_wagner.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/stoer_wagner.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/graph/example/stoer_wagner.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 35.1666666667, "max_line_length": 96, "alphanum_fraction": 0.6222071767, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6148262815387641}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2016 Oracle and/or its affiliates.\n// Contributed and/or modified by Vissarion Fisikopoulos, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <algorithms/test_perimeter.hpp>\n\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\ntemplate <typename P>\nvoid test_all()\n{\n    // Simple\n    test_geometry<bg::model::polygon<P> >(\"POLYGON((0 0,3 4,4 3,0 0))\",\n                                          5 + sqrt(2.0) + 5);\n    // Non-simple\n    test_geometry<bg::model::polygon<P> >(\"POLYGON((0 0,3 4,4 3,0 3,0 0))\",\n                                          5 + sqrt(2.0) + 4 + 3);\n    // With holes\n    test_geometry<bg::model::polygon<P> >(\"POLYGON((0 0,3 4,4 3,0 0),\\\n                                                   (2 2,3 4,3 3,2 2))\",\n                                          5 + sqrt(2.0) + 5 +\n                                          sqrt(5.0) + 1 + sqrt(2.0));\n    // Repeated points\n    test_geometry<bg::model::polygon<P> >(\"POLYGON((0 0,3 4,3 4,3 4,4 3,4 3,\\\n                                                    4 3,4 3,4 3,4 3,0 3,0 0))\",\n                                          5 + sqrt(2.0) + 4 + 3);\n    // Multipolygon\n    test_geometry<bg::model::multi_polygon<bg::model::polygon<P> > >\n    (\n        \"MULTIPOLYGON(((0 0,3 4,4 3,0 0)), ((0 0,3 4,4 3,0 3,0 0)))\",\n        5 + sqrt(2.0) + 5 + 5 + sqrt(2.0) + 4 + 3\n    );\n\n    // Geometries with perimeter zero\n    test_geometry<P>(\"POINT(0 0)\", 0);\n    test_geometry<bg::model::linestring<P> >(\"LINESTRING(0 0,3 4,4 3)\", 0);\n}\n\ntemplate <typename P>\nvoid test_empty_input()\n{\n    test_empty_input(bg::model::polygon<P>());\n    test_empty_input(bg::model::multi_polygon<bg::model::polygon<P> >());\n}\n\nint test_main(int, char* [])\n{\n    test_all<bg::model::d2::point_xy<int> >();\n    test_all<bg::model::d2::point_xy<float> >();\n    test_all<bg::model::d2::point_xy<double> >();\n\n    // test_empty_input<bg::model::d2::point_xy<int> >();\n\n    return 0;\n}\n", "meta": {"hexsha": "4045e6f97f8c4cbd4eb8b16e56fbdcf0cfb07219", "size": 2224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/algorithms/perimeter/perimeter.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": "test/algorithms/perimeter/perimeter.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": "test/algorithms/perimeter/perimeter.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 35.3015873016, "max_line_length": 79, "alphanum_fraction": 0.5382194245, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140004, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6148262681682489}}
{"text": "//  Copyright (c) 2014 Anton Bikineev\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n//  Computes test data for the derivatives of the\r\n//  various bessel functions. Results of derivatives\r\n//  are generated by the relations between the derivatives\r\n//  and Bessel functions, which actual implementation\r\n//  doesn't use. Results are printed to ~ 50 digits.\r\n//\r\n#include <fstream>\r\n\r\n#include <boost/multiprecision/mpfr.hpp>\r\n#include <boost/math/tools/test_data.hpp>\r\n#include <boost/test/included/prg_exec_monitor.hpp>\r\n\r\n#include <boost/math/special_functions/bessel.hpp>\r\n\r\nusing namespace boost::math::tools;\r\nusing namespace boost::math;\r\nusing namespace std;\r\nusing namespace boost::multiprecision;\r\n\r\ntemplate <class T>\r\nT bessel_j_derivative_bare(T v, T x)\r\n{\r\n   return (v / x) * boost::math::cyl_bessel_j(v, x) - boost::math::cyl_bessel_j(v+1, x);\r\n}\r\n\r\ntemplate <class T>\r\nT bessel_y_derivative_bare(T v, T x)\r\n{\r\n   return (v / x) * boost::math::cyl_neumann(v, x) - boost::math::cyl_neumann(v+1, x);\r\n}\r\n\r\ntemplate <class T>\r\nT bessel_i_derivative_bare(T v, T x)\r\n{\r\n   return (v / x) * boost::math::cyl_bessel_i(v, x) + boost::math::cyl_bessel_i(v+1, x);\r\n}\r\n\r\ntemplate <class T>\r\nT bessel_k_derivative_bare(T v, T x)\r\n{\r\n   return (v / x) * boost::math::cyl_bessel_k(v, x) - boost::math::cyl_bessel_k(v+1, x);\r\n}\r\n\r\ntemplate <class T>\r\nT sph_bessel_j_derivative_bare(T v, T x)\r\n{\r\n   if((v < 0) || (floor(v) != v))\r\n      throw std::domain_error(\"\");\r\n   if(v == 0)\r\n      return -boost::math::sph_bessel(1, x);\r\n   return boost::math::sph_bessel(itrunc(v-1), x) - ((v + 1) / x) * boost::math::sph_bessel(itrunc(v), x);\r\n}\r\n\r\ntemplate <class T>\r\nT sph_bessel_y_derivative_bare(T v, T x)\r\n{\r\n   if((v < 0) || (floor(v) != v))\r\n      throw std::domain_error(\"\");\r\n   if(v == 0)\r\n      return -boost::math::sph_neumann(1, x);\r\n   return boost::math::sph_neumann(itrunc(v-1), x) - ((v + 1) / x) * boost::math::sph_neumann(itrunc(v), x);\r\n}\r\n\r\nenum\r\n{\r\n   func_J = 0,\r\n   func_Y,\r\n   func_I,\r\n   func_K,\r\n   func_j,\r\n   func_y\r\n};\r\n\r\nint cpp_main(int argc, char*argv [])\r\n{\r\n   typedef number<mpfr_float_backend<200> > bignum;\r\n\r\n   parameter_info<bignum> arg1, arg2;\r\n   test_data<bignum> data;\r\n\r\n   int functype = 0;\r\n   std::string letter = \"J\";\r\n\r\n   if(argc == 2)\r\n   {\r\n      if(std::strcmp(argv[1], \"--Y\") == 0)\r\n      {\r\n         functype = func_Y;\r\n         letter = \"Y\";\r\n      }\r\n      else if(std::strcmp(argv[1], \"--I\") == 0)\r\n      {\r\n         functype = func_I;\r\n         letter = \"I\";\r\n      }\r\n      else if(std::strcmp(argv[1], \"--K\") == 0)\r\n      {\r\n         functype = func_K;\r\n         letter = \"K\";\r\n      }\r\n      else if(std::strcmp(argv[1], \"--j\") == 0)\r\n      {\r\n         functype = func_j;\r\n         letter = \"j\";\r\n      }\r\n      else if(std::strcmp(argv[1], \"--y\") == 0)\r\n      {\r\n         functype = func_y;\r\n         letter = \"y\";\r\n      }\r\n      else\r\n         assert(0);\r\n   }\r\n\r\n   bool cont;\r\n   std::string line;\r\n\r\n   std::cout << \"Welcome.\\n\"\r\n      \"This program will generate spot tests for the Bessel \" << letter << \" function derivative\\n\\n\";\r\n   do{\r\n      if(0 == get_user_parameter_info(arg1, \"a\"))\r\n         return 1;\r\n      if(0 == get_user_parameter_info(arg2, \"b\"))\r\n         return 1;\r\n\r\n      bignum (*fp)(bignum, bignum) = 0;\r\n      if(functype == func_J)\r\n         fp = bessel_j_derivative_bare;\r\n      else if(functype == func_I)\r\n         fp = bessel_i_derivative_bare;\r\n      else if(functype == func_K)\r\n         fp = bessel_k_derivative_bare;\r\n      else if(functype == func_Y)\r\n         fp = bessel_y_derivative_bare;\r\n      else if(functype == func_j)\r\n         fp = sph_bessel_j_derivative_bare;\r\n      else if(functype == func_y)\r\n         fp = sph_bessel_y_derivative_bare;\r\n      else\r\n         assert(0);\r\n\r\n      data.insert(fp, arg2, arg1);\r\n\r\n      std::cout << \"Any more data [y/n]?\";\r\n      std::getline(std::cin, line);\r\n      boost::algorithm::trim(line);\r\n      cont = (line == \"y\");\r\n   }while(cont);\r\n\r\n   std::cout << \"Enter name of test data file [default=bessel_j_derivative_data.ipp]\";\r\n   std::getline(std::cin, line);\r\n   boost::algorithm::trim(line);\r\n   if(line == \"\")\r\n      line = \"bessel_j_derivative_data.ipp\";\r\n   std::ofstream ofs(line.c_str());\r\n   line.erase(line.find('.'));\r\n   ofs << std::scientific << std::setprecision(50);\r\n   write_code(ofs, data, line.c_str());\r\n\r\n   return 0;\r\n}\r\n", "meta": {"hexsha": "223556297840d883109f12f82bc3374a05a25ebd", "size": 4544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/tools/bessel_derivative_data.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/math/tools/bessel_derivative_data.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/math/tools/bessel_derivative_data.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 27.2095808383, "max_line_length": 109, "alphanum_fraction": 0.5805457746, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6148262636243129}}
{"text": "#pragma once\n#include <Eigen/Dense>\nusing namespace Eigen;\n\nclass perceptron\n{\npublic:\n\tperceptron();\n\t~perceptron() {};\n\n\tvoid fit(MatrixXf& X_train, VectorXi& y_train);\n\tvoid predict(MatrixXf& X_test, VectorXi& y_test);\n\n\tint num_epochs; //number of iterations through the dataset\n\tfloat   theta0; //hyperplane offset\n\tVectorXf theta; //hyperplane coeffs\n\n};", "meta": {"hexsha": "f086336e495ff0d3eeadad4d2e611f812a470b4b", "size": 360, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "machine_learning/perceptron/perceptron.hpp", "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.hpp", "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.hpp", "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": 20.0, "max_line_length": 59, "alphanum_fraction": 0.7416666667, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.6147831371495934}}
{"text": "#include <iostream>\n\n#include <Eigen/Dense>\n\n#include \"polytope.hpp\"\n\nusing namespace integrator_chains;\n\n\nint main()\n{\n    Eigen::Vector4d bounds;\n    bounds << 0, 1,\n              0, 1;\n    LabeledPolytope *square = LabeledPolytope::box( bounds, \"square\" );\n\n    bounds << 0.5, 1.5,\n              0.2, 2;\n    Polytope *rect1 = Polytope::box( bounds );\n    Polytope rect2 = *rect1 & *square;\n\n    std::cout << *square << std::endl;\n    std::cout << *rect1 << std::endl;\n    std::cout << rect2 << std::endl;\n\n    Eigen::Vector2d X;\n    X << 0.3, 0.5;\n    do {\n        std::cout << \"The vector (\" << X(0) << \", \" << X(1) << \")\";\n        if (square->is_in( X )) {\n            std::cout << \" is in \";\n        } else {\n            std::cout << \" is not in \";\n        }\n        std::cout << \"[0,1]^2\" << std::endl;\n        X(0) += 0.4;\n    } while (X(0) < 1.5);\n\n    delete square;\n    return 0;\n}\n", "meta": {"hexsha": "3dab332746f11932e0e36d9d0aeedbd0572026c3", "size": 893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "domains/integrator_chains/dynamaestro/examples/standalone/hellopolytope.cpp", "max_stars_repo_name": "fmrchallenge/fmrbenchmark", "max_stars_repo_head_hexsha": "529520a2b254f7da366b681983182c9e25555b6c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-05-28T22:52:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T00:21:12.000Z", "max_issues_repo_path": "domains/integrator_chains/dynamaestro/examples/standalone/hellopolytope.cpp", "max_issues_repo_name": "fmrchallenge/fmrbenchmark", "max_issues_repo_head_hexsha": "529520a2b254f7da366b681983182c9e25555b6c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2016-02-07T20:57:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-30T23:42:06.000Z", "max_forks_repo_path": "domains/integrator_chains/dynamaestro/examples/standalone/hellopolytope.cpp", "max_forks_repo_name": "fmrchallenge/fmrbenchmark", "max_forks_repo_head_hexsha": "529520a2b254f7da366b681983182c9e25555b6c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-12-28T20:53:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-08T23:30:44.000Z", "avg_line_length": 21.2619047619, "max_line_length": 71, "alphanum_fraction": 0.477043673, "num_tokens": 300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6147472749604118}}
{"text": "/*\n * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT)\n *\n * This software may be modified and distributed under the terms of the\n * BSD 3-Clause license. See the accompanying LICENSE file for details.\n */\n\n#include <BayesFilters/WhiteNoiseAcceleration.h>\n\n#include <cmath>\n#include <utility>\n\n#include <Eigen/Cholesky>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration\n(\n    double T,\n    double tilde_q,\n    unsigned int seed\n) noexcept :\n    generator_(std::mt19937_64(seed)),\n    distribution_(std::normal_distribution<double>(0.0, 1.0)),\n    T_(T),\n    tilde_q_(tilde_q),\n    gauss_rnd_sample_([&] { return (distribution_)(generator_); })\n{\n    F_ << 1.0,  T_, 0.0, 0.0,\n          0.0, 1.0, 0.0, 0.0,\n          0.0, 0.0, 1.0,  T_,\n          0.0, 0.0, 0.0, 1.0;\n\n    double q11 = 1.0/3.0 * std::pow(T_, 3.0);\n    double q2  = 1.0/2.0 * std::pow(T_, 2.0);\n    Q_ << q11,  q2, 0.0, 0.0,\n           q2,  T_, 0.0, 0.0,\n          0.0, 0.0, q11,  q2,\n          0.0, 0.0,  q2,  T_;\n    Q_ *= tilde_q;\n\n    LDLT<Matrix4d> chol_ldlt(Q_);\n    sqrt_Q_ = (chol_ldlt.transpositionsP() * Matrix4d::Identity()).transpose() * chol_ldlt.matrixL() * chol_ldlt.vectorD().real().cwiseSqrt().asDiagonal();\n}\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(double T, double tilde_q) noexcept :\n    WhiteNoiseAcceleration(T, tilde_q, 1)\n{ }\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration() noexcept :\n    WhiteNoiseAcceleration(1.0, 1.0, 1)\n{ }\n\n\nWhiteNoiseAcceleration::~WhiteNoiseAcceleration() noexcept\n{ }\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(const WhiteNoiseAcceleration& wna) :\n    generator_(wna.generator_),\n    distribution_(wna.distribution_),\n    T_(wna.T_),\n    F_(wna.F_),\n    Q_(wna.Q_),\n    tilde_q_(wna.tilde_q_),\n    sqrt_Q_(wna.sqrt_Q_),\n    gauss_rnd_sample_(wna.gauss_rnd_sample_)\n{ }\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(WhiteNoiseAcceleration&& wna) noexcept :\n    generator_(std::move(wna.generator_)),\n    distribution_(std::move(wna.distribution_)),\n    T_(wna.T_),\n    F_(std::move(wna.F_)),\n    Q_(std::move(wna.Q_)),\n    tilde_q_(wna.tilde_q_),\n    sqrt_Q_(std::move(wna.sqrt_Q_)),\n    gauss_rnd_sample_(std::move(wna.gauss_rnd_sample_))\n{\n    wna.T_       = 0.0;\n    wna.tilde_q_ = 0.0;\n}\n\n\nWhiteNoiseAcceleration& WhiteNoiseAcceleration::operator=(const WhiteNoiseAcceleration& wna)\n{\n    WhiteNoiseAcceleration tmp(wna);\n    *this = std::move(tmp);\n\n    return *this;\n}\n\n\nWhiteNoiseAcceleration& WhiteNoiseAcceleration::operator=(WhiteNoiseAcceleration&& wna) noexcept\n{\n    T_       = wna.T_;\n    F_       = std::move(wna.F_);\n    Q_       = std::move(wna.Q_);\n    tilde_q_ = wna.tilde_q_;\n\n    sqrt_Q_           = std::move(wna.sqrt_Q_);\n    generator_        = std::move(wna.generator_);\n    distribution_     = std::move(wna.distribution_);\n    gauss_rnd_sample_ = std::move(wna.gauss_rnd_sample_);\n\n    wna.T_       = 0.0;\n    wna.tilde_q_ = 0.0;\n\n    return *this;\n}\n\n\nMatrixXd WhiteNoiseAcceleration::getNoiseSample(const std::size_t num)\n{\n    MatrixXd rand_vectors(4, num);\n    for (int i = 0; i < rand_vectors.size(); i++)\n        *(rand_vectors.data() + i) = gauss_rnd_sample_();\n\n    return sqrt_Q_ * rand_vectors;\n}\n\n\nMatrixXd WhiteNoiseAcceleration::getNoiseCovarianceMatrix()\n{\n    return Q_;\n}\n\n\nMatrixXd WhiteNoiseAcceleration::getStateTransitionMatrix()\n{\n    return F_;\n}\n\n\nVectorXd WhiteNoiseAcceleration::getTransitionProbability(const Ref<const MatrixXd>& prev_states, Ref<MatrixXd> cur_states)\n{\n    VectorXd probabilities(prev_states.cols());\n    MatrixXd differences = cur_states - prev_states;\n\n    std::size_t size = differences.rows();\n    for (std::size_t i = 0; i < prev_states.cols(); i++)\n    {\n        probabilities(i) = (-0.5 * static_cast<double>(size) * log(2.0 * M_PI) + -0.5 * log(Q_.determinant()) -0.5 * (differences.col(i).transpose() * Q_.inverse() * differences.col(i)).array()).exp().coeff(0);\n    }\n\n    return probabilities;\n}\n\n\nstd::pair<std::size_t, std::size_t> WhiteNoiseAcceleration::getOutputSize() const\n{\n    return std::make_pair(4, 0);\n}\n", "meta": {"hexsha": "3c4f7c8b7792ae05fad9332e63a09d12855ed6af", "size": 4090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_stars_repo_name": "vesor/bayes-filters-lib", "max_stars_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T02:52:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T07:06:39.000Z", "max_issues_repo_path": "src/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_issues_repo_name": "vesor/bayes-filters-lib", "max_issues_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_forks_repo_name": "vesor/bayes-filters-lib", "max_forks_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T08:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T08:20:28.000Z", "avg_line_length": 25.7232704403, "max_line_length": 210, "alphanum_fraction": 0.6628361858, "num_tokens": 1265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6147472628589052}}
{"text": "/* test_cauchy.cpp\n *\n * Copyright Steven Watanabe 2011\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id$\n *\n */\n\n#include <boost/random/cauchy_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/math/distributions/cauchy.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::cauchy_distribution<>\n#define BOOST_RANDOM_DISTRIBUTION_NAME cauchy\n#define BOOST_MATH_DISTRIBUTION boost::math::cauchy\n#define BOOST_RANDOM_ARG1_TYPE double\n#define BOOST_RANDOM_ARG1_NAME median\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(-n, n)\n#define BOOST_RANDOM_ARG2_TYPE double\n#define BOOST_RANDOM_ARG2_NAME sigma\n#define BOOST_RANDOM_ARG2_DEFAULT 1000.0\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(n) boost::uniform_real<>(0.001, n)\n\n#include \"test_real_distribution.ipp\"\n", "meta": {"hexsha": "14c27d9a65ea6ae1f13177d8a4aee098b012fb1c", "size": 954, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_cauchy.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/random/test/test_cauchy.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/random/test/test_cauchy.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 32.8965517241, "max_line_length": 73, "alphanum_fraction": 0.8102725367, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6147472617772551}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n#include <scitbx/math/basic_statistics.h>\n\n#include <boost/python/class.hpp>\n#include <vector>\n\nnamespace scitbx { namespace af { namespace boost_python {\n\n  template <typename FloatType>\n  struct median_functor_wrapper\n  {\n    typedef math::median_functor wt;\n\n    static\n    FloatType\n    call(\n      wt& O,\n      af::const_ref<FloatType> const& data)\n    {\n      std::vector<FloatType> buffer(data.begin(), data.end());\n      return O(af::make_ref(buffer));\n    }\n\n    static\n    math::median_statistics<FloatType>\n    dispersion(\n      wt& O,\n      af::const_ref<FloatType> const &data)\n    {\n      std::vector<FloatType> buffer(data.begin(), data.end());\n      return O.dispersion(af::make_ref(buffer));\n    }\n\n    static void wrap(char const *name) {\n      using namespace boost::python;\n      class_<wt>(name, no_init)\n        .def(init<>())\n        .def(init<wt::random_number_engine_t::result_type>(arg(\"seed\")))\n        .def(\"__call__\", call, arg(\"data\"))\n        .def(\"dispersion\", dispersion, arg(\"data\"))\n      ;\n    }\n  };\n\n\n  template <typename FloatType>\n  struct median_statistics_wrapper\n  {\n    typedef math::median_statistics<FloatType> wt;\n\n    static void wrap(char const *name) {\n      using namespace boost::python;\n      class_<wt>(name, no_init)\n        .def_readonly(\"median\", &wt::median)\n        .def_readonly(\"median_absolute_deviation\",\n                      &wt::median_absolute_deviation)\n      ;\n    }\n  };\n\n  void wrap_flex_median_statistics() {\n    median_statistics_wrapper<double>::wrap(\"median_statistics\");\n    median_functor_wrapper<double>::wrap(\"median_functor\");\n  }\n\n}}}\n", "meta": {"hexsha": "18b4be287e724ecdcd935f9fb0faac107246f46b", "size": 1671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/array_family/boost_python/flex_median.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/array_family/boost_python/flex_median.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/array_family/boost_python/flex_median.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 24.9402985075, "max_line_length": 72, "alphanum_fraction": 0.6433273489, "num_tokens": 403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759583, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6147472551348371}}
{"text": "#include <armadillo>\n\nusing namespace std;\n\nclass LinearRegression{\n    public:\n    int number_of_variables;\n    arma::mat weights;\n\n    LinearRegression(int num);\n\n    void train(arma::mat& X_train, arma::mat& y_train, float alpha, int epochs);\n\n    arma::mat predict(arma::mat& X_predict);\n};\n", "meta": {"hexsha": "5eb95cc325462f1ef86bd8c9a73021998768831a", "size": 295, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/methods/linear_regression/linear_regression.hpp", "max_stars_repo_name": "owais34/Mlplus", "max_stars_repo_head_hexsha": "3c208a44e543e6a0f1d9927139065c19fd7d57c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-16T13:36:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-16T13:36:16.000Z", "max_issues_repo_path": "src/methods/linear_regression/linear_regression.hpp", "max_issues_repo_name": "owais34/Mlplus", "max_issues_repo_head_hexsha": "3c208a44e543e6a0f1d9927139065c19fd7d57c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/methods/linear_regression/linear_regression.hpp", "max_forks_repo_name": "owais34/Mlplus", "max_forks_repo_head_hexsha": "3c208a44e543e6a0f1d9927139065c19fd7d57c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-28T19:29:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-28T19:29:28.000Z", "avg_line_length": 18.4375, "max_line_length": 80, "alphanum_fraction": 0.6915254237, "num_tokens": 73, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6147449385036055}}
{"text": "#include <iostream>\n\n#include <NTL/ZZ.h>\n\nusing namespace std;\nusing namespace NTL;\n\nvoid usage(char *progname) {\n\tcout << \"This program returns the factors p and q of \"\n\t\t\"n if p - q < n^(1/4).\"\n\t\t<< endl;\n\tcout << \"Usage: \" << progname << \" n\" << endl;\n}\n\nint main(int argc, char *argv[]) {\n\tif (argc != 2) { usage(argv[0]); return 3; }\n\n\tZZ n, a, b, p, q;\n\tn = conv<ZZ>(argv[1]);\n\n\t// p = floor(SqrRoot(n))\n\tSqrRoot(a, n);\n\t// q = p*p - n\n\tsqr(b, a);\n\tb -= n;\n\n\twhile(b < 0 || sqr(SqrRoot(b)) != b) {\n\t\ta++;\n\t\tsqr(b, a);\n\t\tb -= n;\n\t}\n\n\tp = a - SqrRoot(b);\n\tq = n / p;\n\n\tcout << p << endl << q << endl;\n}\n", "meta": {"hexsha": "5d16380c8237fe18c8996d2f5d640545ca457a5b", "size": 607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fermat_factor.cpp", "max_stars_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_stars_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fermat_factor.cpp", "max_issues_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_issues_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fermat_factor.cpp", "max_forks_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_forks_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.9736842105, "max_line_length": 55, "alphanum_fraction": 0.5090609555, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.6147303570396223}}
{"text": "#pragma once\n\n#include \"../../Primitives/SignalTraits.hpp\"\n#include \"../../Utility/Numbers.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/QR>\n\nnamespace dspbb::fir {\n\n\nnamespace impl {\n\n\ttemplate <class T>\n\tauto CoefficientMatrix(size_t filterLength, size_t gridSize) {\n\t\tEigen::Matrix<T, Eigen::Dynamic, 1> col;\n\t\tEigen::Matrix<T, 1, Eigen::Dynamic> row;\n\n\t\tcol.resize(gridSize);\n\t\trow.resize(filterLength);\n\n\t\tfor (size_t i = 0; i < gridSize; ++i) {\n\t\t\tcol(i) = T(i);\n\t\t}\n\t\tcol *= T(1) / T(gridSize - 1) * pi_v<T>;\n\n\t\tfor (size_t i = 0; i < filterLength; ++i) {\n\t\t\trow(i) = T(i);\n\t\t}\n\n\t\tEigen::MatrixX<T> coefficientMatrix = col * row;\n\n\t\tfor (size_t row = 0; row < gridSize; ++row) {\n\t\t\tcoefficientMatrix(row, 0) = T(1);\n\t\t\tfor (size_t col = 1; col < filterLength; ++col) {\n\t\t\t\tcoefficientMatrix(row, col) = 2 * std::cos(coefficientMatrix(row, col));\n\t\t\t}\n\t\t}\n\n\t\treturn coefficientMatrix;\n\t}\n\n\ttemplate <class T, class Func>\n\tauto WeightMatrix(size_t gridSize, const Func& weight) {\n\t\tEigen::DiagonalMatrix<T, Eigen::Dynamic> weightMatrix;\n\t\tweightMatrix.resize(gridSize);\n\t\tfor (size_t i = 0; i < gridSize; ++i) {\n\t\t\tweightMatrix.diagonal()(i) = weight(T(i) / T(gridSize - 1));\n\t\t}\n\t\treturn weightMatrix;\n\t}\n\n\ttemplate <class T, class Func>\n\tauto ResponseVector(size_t gridSize, const Func& response) {\n\t\tEigen::Matrix<T, Eigen::Dynamic, 1> responseVector;\n\t\tresponseVector.resize(gridSize);\n\t\tfor (size_t i = 0; i < gridSize; ++i) {\n\t\t\tresponseVector(i) = T(i);\n\t\t}\n\t\tresponseVector *= T(1) / T(gridSize - 1);\n\t\tfor (size_t i = 0; i < gridSize; ++i) {\n\t\t\tresponseVector(i) = response(responseVector(i));\n\t\t}\n\t\treturn responseVector;\n\t}\n\n} // namespace impl\n\n\ntemplate <class SignalR, class ResponseFunc, class WeightFunc, std::enable_if_t<is_mutable_signal_v<SignalR>, int> = 0>\nvoid KernelLeastSquares(SignalR&& coefficients, ResponseFunc responseFunc, WeightFunc weightFunc, size_t gridSize = 0) {\n\tusing R = typename std::decay_t<SignalR>::value_type;\n\tusing T = remove_complex_t<R>;\n\n\tconst size_t filterLength = (coefficients.Size() + 1) / 2;\n\tgridSize = gridSize == 0 ? 4 * filterLength : std::min(filterLength, gridSize);\n\n\tconst auto coefficientMatrix = impl::CoefficientMatrix<T>(filterLength, gridSize);\n\tconst auto weightMatrix = impl::WeightMatrix<T>(gridSize, weightFunc);\n\tconst auto responseVector = impl::ResponseVector<T>(gridSize, responseFunc);\n\n\tEigen::CompleteOrthogonalDecomposition<Eigen::MatrixX<T>> decomp{ weightMatrix * coefficientMatrix };\n\tconst Eigen::VectorX<T> halfFilter = decomp.solve(weightMatrix * responseVector);\n\tfor (size_t i = 0; i < filterLength; ++i) {\n\t\tcoefficients[i] = halfFilter(filterLength - i - 1);\n\t\tcoefficients[i + filterLength - 1] = halfFilter[i];\n\t}\n}\n\n} // namespace dspbb::fir", "meta": {"hexsha": "ecfbe76816e57fc2073b9f6c3c5520769e66b94d", "size": 2738, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dspbb/Filtering/FIR/LeastSquares.hpp", "max_stars_repo_name": "petiaccja/DSPBB", "max_stars_repo_head_hexsha": "405d43c4458adfc16ffad68dac4bcd7e1735407f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-11T13:34:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T20:25:20.000Z", "max_issues_repo_path": "include/dspbb/Filtering/FIR/LeastSquares.hpp", "max_issues_repo_name": "MoeSzyslak98/DSPBB", "max_issues_repo_head_hexsha": "405d43c4458adfc16ffad68dac4bcd7e1735407f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2021-08-14T11:02:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-25T15:41:31.000Z", "max_forks_repo_path": "include/dspbb/Filtering/FIR/LeastSquares.hpp", "max_forks_repo_name": "MoeSzyslak98/DSPBB", "max_forks_repo_head_hexsha": "405d43c4458adfc16ffad68dac4bcd7e1735407f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-29T14:32:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T20:25:15.000Z", "avg_line_length": 30.4222222222, "max_line_length": 120, "alphanum_fraction": 0.6859021183, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172688214138, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.6147069157264955}}
{"text": "#include <cmath>\n#include <iomanip>\n#include <iostream>\n\n#include <sodium/sodium.h>\n#include <boost/numeric/odeint.hpp>\n#include <catch/catch.hpp>\n\n#include \"../include/Plant.hpp\"\n#include \"../include/control-frp.hpp\"\n#include \"../include/pid.hpp\"\n#include \"../include/util/util-frp.hpp\"\n#include \"../include/util/util.hpp\"\n\n#include \"calculations/analytical_solutions.cpp\"\n\n#ifdef PLOT\n#include \"../include/plotting/gnuplot-iostream.h\"\n#include \"../include/plotting/plot-helpers.hpp\"\n#endif  // PLOT\n\nnamespace ode = boost::numeric::odeint;\nusing CState = PIDState<>;\nusing sim::PState;\n\nconstexpr double dt = 0.001;  // seconds.\nconstexpr auto dts = util::double_to_duration(dt);\nconst auto now = chrono::steady_clock::now();\n\nconstexpr double mass = 1.;\nconstexpr double damp = 10. / mass;\nconstexpr double spring = 20. / mass;\nconstexpr double staticForce = 1. / mass;\nconstexpr double simTime = 2;  // seconds\nconst sim::Plant plant(staticForce, damp, spring);\n\node::runge_kutta4<PState> stepper;\n\ninline SignalPt<double> to_error(const SignalPt<PState>& a, const PState& b) {\n  return {a.time, a.value[0] - b[0]};\n}\n\nTEST_CASE(\n    \"Given system and controller parameters, simulation should reproduce \"\n    \"analytically computed step responses to within a margin of error. See \"\n    \"src/calculations for details. Simulations performed using FRP.\") {\n  const CState u0 = {now, 0., 0., 0.};\n  // Setpoint to x = 1, for step response.\n  const sodium::cell<PState> setPoint({1., 0., 0.});\n\n  SECTION(\"Test A (Proportional Control) FRP.\") {\n    constexpr double Kp = 300.;\n    constexpr double Ki = 0.;\n    constexpr double Kd = 0.;\n\n    const sodium::stream_sink<SignalPt<PState>> sPlantState;\n\n    auto cControl = ctrl::control_frp(\n        pid_algebra(Kp, Ki, Kd), &to_error, setPoint,\n        static_cast<sodium::stream<SignalPt<PState>>>(sPlantState), u0);\n\n    auto [sPlantState_unlisten, plantRecord] = util::make_listener(sPlantState);\n    {\n      PState x = {0., 0., 0.};\n      sPlantState.send({now, x});\n      for (int k = 1; k < simTime / dt; ++k) {\n        x[2] = cControl.sample().ctrlVal;\n        stepper.do_step(plant, x, 0, dt);\n        sPlantState.send({now + k * dts, x});\n      }\n    }\n    sPlantState_unlisten();\n\n    {\n      constexpr double margin = 0.03;\n      auto simulatedPositions =\n          util::fmap([](auto x) { return x.value[0]; }, *plantRecord);\n      auto theoreticalPositions = util::fmap(\n          [](auto x) {\n            return analyt::test_A(util::unchrono_sec(x.time - now));\n          },\n          *plantRecord);\n\n#ifdef PLOT\n\n      const auto testData = util::fmap(\n          [](const auto& x) {\n            return std::make_pair(util::unchrono_sec(x.time - now), x.value[0]);\n          },\n          *plantRecord);\n\n      plot_with_tube(\"Test A, (Kp, Ki, Kd) = (300, 0, 0).\", testData,\n                     &analyt::test_A, margin);\n\n#endif  // PLOT\n\n      REQUIRE(util::compareVectors(simulatedPositions, theoreticalPositions,\n                                   margin));\n    }\n  }\n\n  SECTION(\"Test B (Proportional-Derivative Control) anamorphism.\") {\n    constexpr double Kp = 300.;\n    constexpr double Ki = 0.;\n    constexpr double Kd = 10.;\n\n    const sodium::stream_sink<SignalPt<PState>> sPlantState;\n\n    auto cControl = ctrl::control_frp(\n        pid_algebra(Kp, Ki, Kd), &to_error, setPoint,\n        static_cast<sodium::stream<SignalPt<PState>>>(sPlantState), u0);\n\n    auto [sPlantState_unlisten, plantRecord] = util::make_listener(sPlantState);\n    {\n      PState x = {0., 0., 0.};\n      sPlantState.send({now, x});\n      for (int k = 1; k < simTime / dt; ++k) {\n        x[2] = cControl.sample().ctrlVal;\n        stepper.do_step(plant, x, 0, dt);\n        sPlantState.send({now + k * dts, x});\n      }\n    }\n    sPlantState_unlisten();\n\n    {\n      constexpr double margin = 0.03;\n      auto simulatedPositions =\n          util::fmap([](auto x) { return x.value[0]; }, *plantRecord);\n      auto theoreticalPositions = util::fmap(\n          [](auto x) {\n            return analyt::test_B(util::unchrono_sec(x.time - now));\n          },\n          *plantRecord);\n\n#ifdef PLOT\n      const auto testData = util::fmap(\n          [](const auto& x) {\n            return std::make_pair(util::unchrono_sec(x.time - now), x.value[0]);\n          },\n          *plantRecord);\n\n      plot_with_tube(\"Test B, (Kp, Ki, Kd) = (300, 0, 10).\", testData,\n                     &analyt::test_B, margin);\n#endif  // PLOT\n\n      REQUIRE(util::compareVectors(simulatedPositions, theoreticalPositions,\n                                   margin));\n    }\n  }\n\n  SECTION(\"Test C (Proportional-Integral Control) anamorphism.\") {\n    constexpr double Kp = 30.;\n    constexpr double Ki = 70.;\n    constexpr double Kd = 0.;\n\n    // Setpoint to x = 1, for step response.\n    const sodium::cell<PState> setPoint({1., 0., 0.});\n    const sodium::stream_sink<SignalPt<PState>> sPlantState;\n\n    const CState u0 = {now - dts, 0., 0., 0.};\n    auto cControl = ctrl::control_frp(\n        pid_algebra(Kp, Ki, Kd), &to_error, setPoint,\n        static_cast<sodium::stream<SignalPt<PState>>>(sPlantState), u0);\n\n    auto [sPlantState_unlisten, plantRecord] = util::make_listener(sPlantState);\n    {\n      PState x = {0., 0., 0.};\n      sPlantState.send({now, x});\n      for (int k = 1; k < simTime / dt; ++k) {\n        x[2] = cControl.sample().ctrlVal;\n        stepper.do_step(plant, x, 0, dt);\n        sPlantState.send({now + k * dts, x});\n      }\n    }\n    sPlantState_unlisten();\n\n    {\n      constexpr double margin = 0.03;\n\n      auto simulatedPositions =\n          util::fmap([](auto x) { return x.value[0]; }, *plantRecord);\n      auto theoreticalPositions = util::fmap(\n          [](auto x) {\n            return analyt::test_C(util::unchrono_sec(x.time - now));\n          },\n          *plantRecord);\n\n#ifdef PLOT\n      const auto testData = util::fmap(\n          [](const auto& x) {\n            return std::make_pair(util::unchrono_sec(x.time - now), x.value[0]);\n          },\n          *plantRecord);\n\n      plot_with_tube(\"Test C, (Kp, Ki, Kd) = (30, 70, 0).\", testData,\n                     &analyt::test_C, margin);\n#endif  // PLOT\n\n      REQUIRE(util::compareVectors(simulatedPositions, theoreticalPositions,\n                                   margin));\n    }\n  }\n\n  SECTION(\"Test D (Proportional-Integral-Derivative Control) anamorphism.\") {\n    constexpr double Kp = 350.;\n    constexpr double Ki = 300.;\n    constexpr double Kd = 50.;\n\n    // Setpoint to x = 1, for step response.\n    const sodium::cell<PState> setPoint({1., 0., 0.});\n    const sodium::stream_sink<SignalPt<PState>> sPlantState;\n\n    const CState u0 = {now - dts, 0., 0., 0.};\n    auto cControl = ctrl::control_frp(\n        pid_algebra(Kp, Ki, Kd), &to_error, setPoint,\n        static_cast<sodium::stream<SignalPt<PState>>>(sPlantState), u0);\n\n    auto [sPlantState_unlisten, plantRecord] = util::make_listener(sPlantState);\n    {\n      PState x = {0., 0., 0.};\n      sPlantState.send({now, x});\n      for (int k = 1; k < simTime / dt; ++k) {\n        x[2] = cControl.sample().ctrlVal;\n        stepper.do_step(plant, x, 0, dt);\n        sPlantState.send({now + k * dts, x});\n      }\n    }\n    sPlantState_unlisten();\n\n    {\n      constexpr double margin = 0.07;\n\n      auto simulatedPositions =\n          util::fmap([](auto x) { return x.value[0]; }, *plantRecord);\n      auto theoreticalPositions = util::fmap(\n          [](auto x) {\n            return analyt::test_D(util::unchrono_sec(x.time - now));\n          },\n          *plantRecord);\n\n#ifdef PLOT\n      const auto testData = util::fmap(\n          [](const auto& x) {\n            return std::make_pair(util::unchrono_sec(x.time - now), x.value[0]);\n          },\n          *plantRecord);\n\n      plot_with_tube(\"Test B, (Kp, Ki, Kd) = (350, 300, 50).\", testData,\n                     &analyt::test_D, margin);\n#endif  // PLOT\n\n      REQUIRE(util::compareVectors(simulatedPositions, theoreticalPositions,\n                                   margin));\n    }\n  }\n}\n", "meta": {"hexsha": "d9d3fdde756e2eb740644d0272ae4d55443e1471", "size": 8013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pid-frp.cpp", "max_stars_repo_name": "timtro/pid-unfolding", "max_stars_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pid-frp.cpp", "max_issues_repo_name": "timtro/pid-unfolding", "max_issues_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pid-frp.cpp", "max_forks_repo_name": "timtro/pid-unfolding", "max_forks_repo_head_hexsha": "3e9aaa0c47785bb1fc7464235774de1c255a3b68", "max_forks_repo_licenses": ["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.1789883268, "max_line_length": 80, "alphanum_fraction": 0.5900411831, "num_tokens": 2234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.6146779961563121}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Siargey Kachanovich\n *\n *    Copyright (C) 2019 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"random_orthogonal_matrix_function\"\n#include <boost/test/unit_test.hpp>\n#include <gudhi/Unitary_tests_utils.h>\n\n#include <gudhi/Functions/random_orthogonal_matrix.h>\n\n#include <string>\n\n#include <random>\n#include <cstdlib>\n\nusing namespace Gudhi::coxeter_triangulation;\n\n// this test is separated as it requires CGAL\nBOOST_AUTO_TEST_CASE(random_orthogonal_matrix_function) {\n  // random orthogonal matrix\n  Eigen::MatrixXd matrix = random_orthogonal_matrix(5);\n  Eigen::MatrixXd id_matrix = matrix.transpose() * matrix;\n  for (std::size_t i = 0; i < 5; ++i)\n    for (std::size_t j = 0; j < 5; ++j)\n      if (i == j)\n        GUDHI_TEST_FLOAT_EQUALITY_CHECK(id_matrix(i, j), 1.0, 1e-10);\n      else\n        GUDHI_TEST_FLOAT_EQUALITY_CHECK(id_matrix(i, j), 0.0, 1e-10);\n}\n", "meta": {"hexsha": "84178741f00ff72a1082298c3918f028a8f14a55", "size": 1183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Coxeter_triangulation/test/random_orthogonal_matrix_function_test.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T05:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T05:45:06.000Z", "max_issues_repo_path": "src/Coxeter_triangulation/test/random_orthogonal_matrix_function_test.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Coxeter_triangulation/test/random_orthogonal_matrix_function_test.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.972972973, "max_line_length": 101, "alphanum_fraction": 0.707523246, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461006, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.614666644424307}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include \"typedefs.hpp\"\n\nnamespace yavque\n{\nEigen::SparseMatrix<double> pauli_x();\nEigen::SparseMatrix<cx_double> pauli_y();\nEigen::SparseMatrix<double> pauli_z();\nEigen::SparseMatrix<double> pauli_xx();\nEigen::SparseMatrix<double> pauli_yy();\nEigen::SparseMatrix<double> pauli_zz();\n} // namespace yavque\n", "meta": {"hexsha": "67d8bd62ed3b8a07f7be04634e503694498366ed", "size": 367, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/yavque/Utilities/pauli_operators.hpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/yavque/Utilities/pauli_operators.hpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/yavque/Utilities/pauli_operators.hpp", "max_forks_repo_name": "chaeyeunpark/Yavque", "max_forks_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9375, "max_line_length": 41, "alphanum_fraction": 0.7602179837, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6146666338143425}}
{"text": "#pragma once\n\n/* Classical constant propagation domain */\n\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/backward_assign_operations.hpp>\n#include <crab/domains/interval.hpp>\n#include <crab/domains/separate_domains.hpp>\n#include <crab/support/stats.hpp>\n\n#include <boost/optional.hpp>\n\nnamespace crab {\nnamespace domains {\n/**\n *  Each variable is mapped to an element in this lattice:\n *\n *            top\n *             |\n * ...,-3,-2,-1,0,1,2,3,...\n *             |\n *           bottom\n *\n * top means that it might not be a constant value\n **/\ntemplate <typename Number> class constant {\n  boost::optional<Number> m_constant;\n  bool m_is_bottom;\n  using constant_t = constant<Number>;\n  constant(bool is_bottom) : m_constant(boost::none), m_is_bottom(is_bottom) {}  \npublic:\n\n  constant(Number c) : m_constant(c), m_is_bottom(false) {}\n\n  static constant_t bottom() { return constant(true); }\n\n  static constant_t top() { return constant(false); }\n\n  static constant_t zero() { return constant(Number(0));}\n  \n  bool is_bottom() const { return m_is_bottom; }\n\n  bool is_top() const { return (!is_bottom() && !m_constant); }\n\n  bool is_constant() const { return m_constant != boost::none; }\n\n  Number get_constant() const {\n    assert(is_constant());\n    return *m_constant;\n  }\n\n  /** Begin Lattice Operations **/\n  bool operator<=(const constant_t &o) const {\n    if (is_bottom() || o.is_top()) {\n      return true;\n    } else if (o.is_bottom() || is_top()) {\n      return false;\n    } else {\n      assert(is_constant());\n      assert(o.is_constant());\n      return get_constant() == o.get_constant();\n    }\n  }\n\n  bool operator==(const constant_t &o) const {\n    return (m_is_bottom == o.m_is_bottom && m_constant == o.m_constant);\n  }\n\n  constant_t operator|(const constant_t &o) const {\n    if (is_bottom() || o.is_top())\n      return o;\n    else if (is_top() || o.is_bottom())\n      return *this;\n    else {\n      assert(is_constant());\n      assert(o.is_constant());\n      if (get_constant() == o.get_constant()) {\n        return *this;\n      } else {\n        return constant_t::top();\n      }\n    }\n  }\n\n  constant_t operator||(const constant_t &o) const { return *this | o; }\n\n  template <typename Thresholds>\n  constant_t widening_thresholds(const constant_t &o,\n                                 const Thresholds &ts /*unused*/) const {\n    return *this | o;\n  }\n\n  constant_t operator&(const constant_t &o) const {\n    if (is_bottom() || o.is_top())\n      return *this;\n    else if (is_top() || o.is_bottom()) {\n      return o;\n    } else {\n      assert(is_constant());\n      assert(o.is_constant());\n      if (get_constant() == o.get_constant()) {\n        return *this;\n      } else {\n        return constant_t::bottom();\n      }\n    }\n  }\n\n  constant_t operator&&(const constant_t &o) const { return *this & o; }\n  /** End  Lattice Operations **/\n  \n\n  /** Begin arithmetic operations **/\n  constant_t Add(const constant_t &o) const {\n    if (is_constant() && o.is_constant()) {\n      return constant_t(get_constant() + o.get_constant());\n    } else {\n      return constant_t::top();\n    }\n  }\n  constant_t Sub(const constant_t &o) const {\n    if (is_constant() && o.is_constant()) {\n      return constant_t(get_constant() - o.get_constant());\n    } else {\n      return constant_t::top();\n    }\n  }\n  constant_t Mul(const constant_t &o) const {\n    if (is_constant() && o.is_constant()) {\n      return constant_t(get_constant() * o.get_constant());\n    } else {\n      return constant_t::top();\n    }    \n  }\n  constant_t SDiv(const constant_t &o) const {\n    if (o.is_constant() && o.get_constant() == Number(0)) {\n      return constant_t::bottom();\n    }\n    if (is_constant() && o.is_constant()) {\n      return constant_t(get_constant() / o.get_constant());\n    } else {\n      return constant_t::top();\n    }    \n  }\n  constant_t SRem(const constant_t &o) const {\n    if (o.is_constant() && o.get_constant() == Number(0)) {\n      return constant_t::bottom();\n    }\n    if (is_constant() && o.is_constant()) {\n      return constant_t(get_constant() % o.get_constant());\n    } else {\n      return constant_t::top();\n    }    \n  }\n  constant_t UDiv(const constant_t &o) const {\n    if (o.is_constant() && o.get_constant() == Number(0)) {\n      return constant_t::bottom();\n    }\n    return constant_t::top();\n  }\n  constant_t URem(const constant_t &o) const {\n    if (o.is_constant() && o.get_constant() == Number(0)) {\n      return constant_t::bottom();\n    }\n    return constant_t::top();    \n  }\n  /** End arithmetic operations **/\n\n  /** Begin bitwise operations **/  \n  // These operations depend on the type of Number\n  constant_t BitwiseAnd(const constant_t &o) const;\n  constant_t BitwiseOr(const constant_t &o) const;\n  constant_t BitwiseXor(const constant_t &o) const;\n  constant_t BitwiseShl(const constant_t &o) const;\n  constant_t BitwiseLShr(const constant_t &o) const;\n  constant_t BitwiseAShr(const constant_t &o) const;\n  /** End bitwise operations **/\n  \n  void write(crab::crab_os &o) const {\n    if (is_bottom()) {\n      o << \"_|_\";\n    } else if (is_top()) {\n      o << \"top\";\n    } else {\n      assert(is_constant());\n      o << get_constant();\n    }\n  }\n\n  friend inline crab_os &operator<<(crab_os &o, const constant_t &c) {\n    c.write(o);\n    return o;\n  }\n  \n};\n\nnamespace constant_details {\nusing z_constant_t = constant<ikos::z_number>;\nusing q_constant_t = constant<ikos::q_number>;\n} // end namespace constant_details\n\ntemplate<> constant_details::z_constant_t\ninline constant_details::z_constant_t::BitwiseAnd(const constant_details::z_constant_t &o) const {\n  if (is_constant() && o.is_constant()) {\n    return constant_details::z_constant_t(get_constant() & o.get_constant());\n  } else {\n    return constant_details::z_constant_t::top();\n  } \n}\ntemplate<> constant_details::z_constant_t\ninline constant_details::z_constant_t::BitwiseOr(const constant_details::z_constant_t &o) const {\n  if (is_constant() && o.is_constant()) {\n    return constant_details::z_constant_t(get_constant() | o.get_constant());    \n  } else {\n    return constant_details::z_constant_t::top();\n  } \n}\ntemplate<> constant_details::z_constant_t\ninline constant_details::z_constant_t::BitwiseXor(const constant_details::z_constant_t &o) const {\n  if (is_constant() && o.is_constant()) {\n    return constant_details::z_constant_t(get_constant() ^ o.get_constant());        \n  } else {\n    return constant_details::z_constant_t::top();\n  } \n}\ntemplate<> constant_details::z_constant_t\ninline constant_details::z_constant_t::BitwiseShl(const constant_details::z_constant_t &o) const {\n  if (is_constant() && o.is_constant()) {\n    if (o.get_constant() >= ikos::z_number(0)) {\t    \n      return constant_details::z_constant_t(get_constant() << o.get_constant());\n    }\n  } \n  return constant_details::z_constant_t::top();\n}\ntemplate<> constant_details::z_constant_t\ninline constant_details::z_constant_t::BitwiseLShr(const constant_details::z_constant_t &o) const {\n  if (is_constant() && o.is_constant()) {\n    // if get_contant() is non-negative then LShr = AShr.\n    if (get_constant() >= ikos::z_number(0)) {\n      if (o.get_constant() >= ikos::z_number(0)) {\t        \n\treturn constant_details::z_constant_t(get_constant() >> o.get_constant());\n      }\n    }\n  } \n  return constant_details::z_constant_t::top();\n}\ntemplate<> constant_details::z_constant_t\ninline constant_details::z_constant_t::BitwiseAShr(const constant_details::z_constant_t &o) const {\n  if (is_constant() && o.is_constant()) {\n    if (o.get_constant() >= ikos::z_number(0)) {\t        \n      return constant_details::z_constant_t(get_constant() >> o.get_constant());\n    }\n  }\n  return constant_details::z_constant_t::top();\n}\n\n  \ntemplate<> constant_details::q_constant_t\ninline constant_details::q_constant_t::BitwiseAnd(const constant_details::q_constant_t &o) const {\n  return constant_details::q_constant_t::top();\n}\ntemplate<> constant_details::q_constant_t\ninline constant_details::q_constant_t::BitwiseOr(const constant_details::q_constant_t &o) const {\n  return constant_details::q_constant_t::top();\n}\ntemplate<> constant_details::q_constant_t\ninline constant_details::q_constant_t::BitwiseXor(const constant_details::q_constant_t &o) const {\n  return constant_details::q_constant_t::top();\n}\ntemplate<> constant_details::q_constant_t\ninline constant_details::q_constant_t::BitwiseShl(const constant_details::q_constant_t &o) const {\n  return constant_details::q_constant_t::top();\n}\ntemplate<> constant_details::q_constant_t\ninline constant_details::q_constant_t::BitwiseLShr(const constant_details::q_constant_t &o) const {\n  return constant_details::q_constant_t::top();\n}\ntemplate<> constant_details::q_constant_t\ninline constant_details::q_constant_t::BitwiseAShr(const constant_details::q_constant_t &o) const {\n  return constant_details::q_constant_t::top();\n}\n  \n\ntemplate <typename Number, typename VariableName>\nclass constant_domain final : public crab::domains::abstract_domain_api<\n                                  constant_domain<Number, VariableName>> {\npublic:\n  using constant_domain_t = constant_domain<Number, VariableName>;\n  using abstract_domain_t =\n      crab::domains::abstract_domain_api<constant_domain_t>;\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::interval_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::reference_constraint_t;\n  using typename abstract_domain_t::variable_or_constant_t;\n  using typename abstract_domain_t::variable_t;\n  using typename abstract_domain_t::variable_vector_t;\n  using typename abstract_domain_t::variable_or_constant_vector_t;\n  using constant_t = constant<Number>;\n  using number_t = Number;\n  using varname_t = VariableName;\n\nprivate:\n  using interval_domain_t = ikos::interval_domain<number_t, varname_t>;\n  using separate_domain_t = ikos::separate_domain<variable_t, constant_t>;\n\nprivate:\n  separate_domain_t m_env;\n\n  constant_domain(separate_domain_t &&env) : m_env(std::move(env)) {}\n\n  constant_t eval(const linear_expression_t &expr) const {\n    assert(!is_bottom());\n    constant_t r(expr.constant());\n    for (auto const&kv : expr) {\n      constant_t c(kv.first);\n      r  = r.Add(c.Mul(m_env[kv.second]));\n      if (r.is_top()) {\n\tbreak;\n      }\n    }\n    return r;\n  }\n  \n  constant_t compute_residual(const linear_constraint_t &cst, const variable_t &pivot) const {\n    constant_t residual(cst.constant());\n    for (auto const&kv: cst) {\n      constant_t c(kv.first);\n      const variable_t &v = kv.second;\n      if (!(v == pivot)) {\n\tresidual = residual.Sub(c.Mul(m_env[v]));\n\tif (residual.is_top()) {\n\t  break;\n\t}\n      }\n    }\n    return residual;\n  }\n  \n  void propagate(const linear_constraint_t &cst){\n    if (is_bottom()) {\n      return;\n    }\n    \n    if (cst.is_inequality() || cst.is_strict_inequality() || cst.is_disequation()) {\n      constant_t e = eval(cst.expression());\n      if (e.is_constant()) {\n\tif (cst.is_inequality()) {\n\t  if (!(e.get_constant() <= number_t(0))) {\n\t    set_to_bottom();\n\t    return;\n\t  }\n\t} else if (cst.is_disequation()) {\n\t  if (!(e.get_constant() != number_t(0))) {\n\t    set_to_bottom();\n\t    return;\n\t  }\n\t} else if (cst.is_strict_inequality()) {\n\t  if (!(e.get_constant() < number_t(0))) {\n\t    set_to_bottom();\n\t    return;\n\t  }\n\t} \n      }\n    } else if (cst.is_equality()) {\n      for (auto kv : cst) {\n\tnumber_t c = kv.first;\n\tconst variable_t &pivot = kv.second;\n\tconstant_t new_c = compute_residual(cst, pivot).SDiv(c);\n\tif (!new_c.is_top()) {\n\t  m_env.set(pivot, m_env[pivot] & new_c);\n\t}\n      }\n    }\n  }\n  \n  void solve_constraints(const linear_constraint_system_t &csts) {\n    for (auto const &c : csts) {\n      if (is_bottom()) {\n\treturn;\n      }\n      if (c.is_inequality() && c.is_unsigned()) {\n\t// we don't handle unsigned constraints\n\tcontinue;\n      }\n      if (c.is_tautology()) {\n\tcontinue;\n      }\n      if (c.is_contradiction()) {\n\tset_to_bottom();\n\treturn;\n      }\n      propagate(c);\n    }\n  }\n\npublic:\n  constant_domain_t make_top() const override {\n    return constant_domain_t(separate_domain_t::top());\n  }\n\n  constant_domain_t make_bottom() const override {\n    return constant_domain_t(separate_domain_t::bottom());\n  }\n\n  void set_to_top() override {\n    constant_domain abs(separate_domain_t::top());\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() override {\n    constant_domain abs(separate_domain_t::bottom());\n    std::swap(*this, abs);\n  }\n\n  constant_domain() : m_env(separate_domain_t::top()) {}\n\n  constant_domain(const constant_domain_t &e) : m_env(e.m_env) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n  }\n\n  constant_domain(constant_domain_t &&e) : m_env(std::move(e.m_env)) {}\n\n  constant_domain_t &operator=(const constant_domain_t &o) {\n    crab::CrabStats::count(domain_name() + \".count.copy\");\n    crab::ScopedCrabStats __st__(domain_name() + \".copy\");\n    if (this != &o) {\n      m_env = o.m_env;\n    }\n    return *this;\n  }\n\n  constant_domain_t &operator=(constant_domain_t &&o) {\n    if (this != &o) {\n      m_env = std::move(o.m_env);\n    }\n    return *this;\n  }\n\n  constant_t get_constant(const variable_t &v) const {\n    return m_env[v];\n  }\n\n  void set_constant(const variable_t &v, constant_t c) {\n    m_env.set(v, c);\n  }\n  \n  bool is_bottom() const override { return m_env.is_bottom(); }\n\n  bool is_top() const override { return m_env.is_top(); }\n\n  bool operator<=(const constant_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.leq\");\n    crab::ScopedCrabStats __st__(domain_name() + \".leq\");\n    return (m_env <= o.m_env);\n  }\n\n  void operator|=(const constant_domain_t &o) override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n    CRAB_LOG(\"constant-domain\",\n             crab::outs() << \"Join \" << m_env << \" and \" << o.m_env << \"\\n\";);\n    m_env = m_env | o.m_env;\n    CRAB_LOG(\"constant-domain\", crab::outs() << \"Res=\" << m_env << \"\\n\";);\n  }\n\n  constant_domain_t operator|(const constant_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.join\");\n    crab::ScopedCrabStats __st__(domain_name() + \".join\");\n    return (m_env | o.m_env);\n  }\n\n  constant_domain_t operator&(const constant_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.meet\");\n    crab::ScopedCrabStats __st__(domain_name() + \".meet\");\n    return (m_env & o.m_env);\n  }\n\n  constant_domain_t operator||(const constant_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.widening\");\n    crab::ScopedCrabStats __st__(domain_name() + \".widening\");\n    return (m_env || o.m_env);\n  }\n\n  constant_domain_t widening_thresholds(\n      const constant_domain_t &o,\n      const crab::iterators::thresholds<number_t> &ts) const override {\n    crab::CrabStats::count(domain_name() + \".count.widening\");\n    crab::ScopedCrabStats __st__(domain_name() + \".widening\");\n    return m_env.widening_thresholds(o.m_env, ts);\n  }\n\n  constant_domain_t operator&&(const constant_domain_t &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.narrowing\");\n    crab::ScopedCrabStats __st__(domain_name() + \".narrowing\");\n    return (m_env && o.m_env);\n  }\n\n  void operator-=(const variable_t &v) override {\n    crab::CrabStats::count(domain_name() + \".count.forget\");\n    crab::ScopedCrabStats __st__(domain_name() + \".forget\");\n    m_env -= v;\n  }\n\n  interval_t operator[](const variable_t &v) override {\n    constant_t c = m_env[v];\n    if (c.is_bottom()) {\n      return interval_t::bottom();\n    } else if (c.is_top()) {\n      return interval_t::top();\n    } else {\n      assert(c.is_constant());\n      return interval_t(c.get_constant());\n    }\n  }\n\n  void operator+=(const linear_constraint_system_t &csts) override {\n    crab::CrabStats::count(domain_name() + \".count.add_constraints\");\n    crab::ScopedCrabStats __st__(domain_name() + \".add_constraints\");\n    solve_constraints(csts);\n  }\n\n  void assign(const variable_t &x, const linear_expression_t &e) override {\n    crab::CrabStats::count(domain_name() + \".count.assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".assign\");\n    if (boost::optional<variable_t> v = e.get_variable()) {\n      m_env.set(x, m_env[(*v)]);\n    } else {\n      m_env.set(x, eval(e));\n    }\n  }\n\n  void apply(crab::domains::arith_operation_t op, const variable_t &x,\n             const variable_t &y, const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    if (!is_bottom()) {\n      constant_t yc = m_env[y];\n      constant_t zc = m_env[z];\n      constant_t xc = constant_t::top();\n      switch (op) {\n      case crab::domains::OP_ADDITION:\n\txc = yc.Add(zc);\n\tbreak;\n      case crab::domains::OP_SUBTRACTION:\n\txc = yc.Sub(zc);\n\tbreak;\n      case crab::domains::OP_MULTIPLICATION:\n\txc = yc.Mul(zc);\n\tbreak;\n      case crab::domains::OP_SDIV:\n\txc = yc.SDiv(zc);      \n\tbreak;\n      case crab::domains::OP_SREM:\n\txc = yc.SRem(zc);            \n\tbreak;\n      case crab::domains::OP_UDIV:\n\txc = yc.UDiv(zc);      \n\tbreak;\n      case crab::domains::OP_UREM:\n\txc = yc.URem(zc);            \n\tbreak;\n      default:\n\tCRAB_ERROR(\"Operation \", op, \" not supported\");\n      }\n      m_env.set(x, xc);\n    }\n  }\n  \n  void apply(crab::domains::arith_operation_t op, const variable_t &x,\n             const variable_t &y, number_t k) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    if (!is_bottom()) {\n      constant_t yc = m_env[y];\n      constant_t zc(k);\n      constant_t xc = constant_t::top();\n      switch (op) {\n      case crab::domains::OP_ADDITION:\n\txc = yc.Add(zc);\n\tbreak;\n      case crab::domains::OP_SUBTRACTION:\n\txc = yc.Sub(zc);\n\tbreak;\n      case crab::domains::OP_MULTIPLICATION:\n\txc = yc.Mul(zc);\n\tbreak;\n      case crab::domains::OP_SDIV:\n\txc = yc.SDiv(zc);      \n\tbreak;\n      case crab::domains::OP_SREM:\n\txc = yc.SRem(zc);            \n\tbreak;\n      case crab::domains::OP_UDIV:\n\txc = yc.UDiv(zc);      \n\tbreak;\n      case crab::domains::OP_UREM:\n\txc = yc.URem(zc);            \n\tbreak;\n      default:\n\tCRAB_ERROR(\"Operation \", op, \" not supported\");\n      }\n      m_env.set(x, xc);\n    }\n    \n  }\n\n  // intrinsics operations\n  void intrinsic(std::string name,\n\t\t const variable_or_constant_vector_t &inputs,\n                 const variable_vector_t &outputs) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", domain_name());\n  }\n\n  void backward_intrinsic(std::string name,\n\t\t\t  const variable_or_constant_vector_t &inputs,\n                          const variable_vector_t &outputs,\n                          const constant_domain_t &invariant) override {\n    CRAB_WARN(\"Intrinsics \", name, \" not implemented by \", domain_name());\n  }\n\n  // backward arithmetic operations\n  void backward_assign(const variable_t &x, const linear_expression_t &e,\n                       const constant_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_assign\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_assign\");\n    // TODO\n  }\n\n  void backward_apply(crab::domains::arith_operation_t op, const variable_t &x,\n                      const variable_t &y, number_t z,\n                      const constant_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_apply\");\n    // TODO\n  }\n\n  void backward_apply(crab::domains::arith_operation_t op, const variable_t &x,\n                      const variable_t &y, const variable_t &z,\n                      const constant_domain_t &inv) override {\n    crab::CrabStats::count(domain_name() + \".count.backward_apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".backward_apply\");\n    // TODO\n  }\n\n  // cast operations\n  void apply(crab::domains::int_conv_operation_t /*op*/, const variable_t &dst,\n             const variable_t &src) override {\n    // ignore the widths\n    assign(dst, src);\n  }\n\n  // bitwise operations\n  void apply(crab::domains::bitwise_operation_t op, const variable_t &x,\n             const variable_t &y, const variable_t &z) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    if (!is_bottom()) {\n      constant_t yc = m_env[y];\n      constant_t zc = m_env[z];\n      constant_t xc = constant_t::top();\n      switch (op) {\n      case crab::domains::OP_AND:\n\txc = yc.BitwiseAnd(zc);\n\tbreak;\n      case crab::domains::OP_OR:\n\txc = yc.BitwiseOr(zc);\n\tbreak;\n      case crab::domains::OP_XOR:\n\txc = yc.BitwiseXor(zc);\n\tbreak;\n      case crab::domains::OP_SHL:\n\txc = yc.BitwiseShl(zc);      \n\tbreak;\n      case crab::domains::OP_LSHR:\n\txc = yc.BitwiseLShr(zc);            \n\tbreak;\n      case crab::domains::OP_ASHR: {\n\txc = yc.BitwiseAShr(zc);                  \n\tbreak;\n      }\n      default:\n\tCRAB_ERROR(\"Operation \", op, \" not supported\");\n      }\n      m_env.set(x, xc);\n    }\n  }\n\n  void apply(crab::domains::bitwise_operation_t op, const variable_t &x,\n             const variable_t &y, number_t k) override {\n    crab::CrabStats::count(domain_name() + \".count.apply\");\n    crab::ScopedCrabStats __st__(domain_name() + \".apply\");\n\n    if (!is_bottom()) {\n      constant_t yc = m_env[y];\n      constant_t zc(k);\n      constant_t xc = constant_t::top();\n      switch (op) {\n      case crab::domains::OP_AND:\n\txc = yc.BitwiseAnd(zc);\n\tbreak;\n      case crab::domains::OP_OR:\n\txc = yc.BitwiseOr(zc);\n\tbreak;\n      case crab::domains::OP_XOR:\n\txc = yc.BitwiseXor(zc);\n\tbreak;\n      case crab::domains::OP_SHL:\n\txc = yc.BitwiseShl(zc);      \n\tbreak;\n      case crab::domains::OP_LSHR:\n\txc = yc.BitwiseLShr(zc);            \n\tbreak;\n      case crab::domains::OP_ASHR: {\n\txc = yc.BitwiseAShr(zc);                  \n\tbreak;\n      }\n      default:\n\tCRAB_ERROR(\"Operation \", op, \" not supported\");\n      }\n      m_env.set(x, xc);\n    }\n    \n  }\n\n  virtual void select(const variable_t &lhs, const linear_constraint_t &cond,\n                      const linear_expression_t &e1,\n                      const linear_expression_t &e2) override {\n    crab::CrabStats::count(domain_name() + \".count.select\");\n    crab::ScopedCrabStats __st__(domain_name() + \".select\");\n\n    if (!is_bottom()) {\n      constant_domain_t inv1(*this);\n      inv1 += cond;\n      if (inv1.is_bottom()) {\n        assign(lhs, e2);\n        return;\n      }\n      constant_domain_t inv2(*this);\n      inv2 += cond.negate();\n      if (inv2.is_bottom()) {\n        assign(lhs, e1);\n        return;\n      }\n      m_env.set(lhs, eval(e1) | eval(e2));\n    }\n  }\n\n  /// constant_domain implements only standard abstract operations of\n  /// a numerical domain so it is intended to be used as a leaf domain\n  /// in the hierarchy of domains.\n  BOOL_OPERATIONS_NOT_IMPLEMENTED(constant_domain_t)\n  ARRAY_OPERATIONS_NOT_IMPLEMENTED(constant_domain_t)\n  REGION_AND_REFERENCE_OPERATIONS_NOT_IMPLEMENTED(constant_domain_t)\n\n  void forget(const variable_vector_t &variables) override {\n    if (is_bottom() || is_top()) {\n      return;\n    }\n    for (auto const &var : variables) {\n      this->operator-=(var);\n    }\n  }\n\n  void project(const variable_vector_t &variables) override {\n    crab::CrabStats::count(domain_name() + \".count.project\");\n    crab::ScopedCrabStats __st__(domain_name() + \".project\");\n\n    m_env.project(variables);\n  }\n\n  void rename(const variable_vector_t &from,\n              const variable_vector_t &to) override {\n    crab::CrabStats::count(domain_name() + \".count.rename\");\n    crab::ScopedCrabStats __st__(domain_name() + \".rename\");\n\n    m_env.rename(from, to);\n  }\n\n  void expand(const variable_t &x, const variable_t &new_x) override {\n    crab::CrabStats::count(domain_name() + \".count.expand\");\n    crab::ScopedCrabStats __st__(domain_name() + \".expand\");\n\n    if (is_bottom() || is_top()) {\n      return;\n    }\n\n    m_env.set(new_x, m_env[x]);\n  }\n\n  void normalize() override {}\n\n  void minimize() override {}\n\n  void write(crab::crab_os &o) const override {\n    crab::CrabStats::count(domain_name() + \".count.write\");\n    crab::ScopedCrabStats __st__(domain_name() + \".write\");\n\n    m_env.write(o);\n  }\n\n  linear_constraint_system_t to_linear_constraint_system() const override {\n    crab::CrabStats::count(domain_name() +\n                           \".count.to_linear_constraint_system\");\n    crab::ScopedCrabStats __st__(domain_name() +\n                                 \".to_linear_constraint_system\");\n\n    linear_constraint_system_t csts;\n\n    if (this->is_bottom()) {\n      csts += linear_constraint_t::get_false();\n      return csts;\n    }\n\n    for (auto it = m_env.begin(); it != m_env.end(); ++it) {\n      const variable_t &v = it->first;\n      const constant_t &c = it->second;\n      if (c.is_constant()) {\n        csts += linear_constraint_t(v == c.get_constant());\n      }\n    }\n    return csts;\n  }\n\n  disjunctive_linear_constraint_system_t\n  to_disjunctive_linear_constraint_system() const override {\n    auto lin_csts = to_linear_constraint_system();\n    if (lin_csts.is_false()) {\n      return disjunctive_linear_constraint_system_t(true /*is_false*/);\n    } else if (lin_csts.is_true()) {\n      return disjunctive_linear_constraint_system_t(false /*is_false*/);\n    } else {\n      return disjunctive_linear_constraint_system_t(lin_csts);\n    }\n  }\n\n  std::string domain_name() const override { return \"ConstantDomain\"; }\n\n}; // class constant_domain\n} // namespace domains\n} // namespace crab\n\nnamespace crab {\nnamespace domains {\ntemplate <typename Number, typename VariableName>\nstruct abstract_domain_traits<constant_domain<Number, VariableName>> {\n  using number_t = Number;\n  using varname_t = VariableName;\n};\n\n} // namespace domains\n} // namespace crab\n", "meta": {"hexsha": "1f518fa552d4979a44eb2514f835016dbd382cd9", "size": 26186, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/constant_domain.hpp", "max_stars_repo_name": "LinerSu/crab", "max_stars_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 152.0, "max_stars_repo_stars_event_min_datetime": "2016-02-28T06:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:44:56.000Z", "max_issues_repo_path": "include/crab/domains/constant_domain.hpp", "max_issues_repo_name": "LinerSu/crab", "max_issues_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-07-03T06:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:09:32.000Z", "max_forks_repo_path": "include/crab/domains/constant_domain.hpp", "max_forks_repo_name": "LinerSu/crab", "max_forks_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-11-22T15:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T00:46:57.000Z", "avg_line_length": 30.4842840512, "max_line_length": 99, "alphanum_fraction": 0.6486290384, "num_tokens": 6715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6146666070244091}}
{"text": "// Compile with:\n// clang++ -o demoEllipsoids2D demoEllipsoids2D.cpp -L../build/ -I ../include/ -l diamonds -stdlib=libc++ -std=c++11 -Wno-deprecated-register\n//\n\n#include <ctime>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cassert>\n#include <unordered_set>\n#include <Eigen/Core>\n#include \"File.h\"\n#include \"EuclideanMetric.h\"\n#include \"KmeansClusterer.h\"\n#include \"Ellipsoid.h\"\n#include \"PrincipalComponentProjector.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\nint main()\n{\n    // ------ IDENTIFY CLUSTERS FROM INPUT SAMPLE ------\n    // Open the input file and read the data (synthetic sampling of a 2D parameter space)\n    \n    ifstream inputFile;\n    File::openInputFile(inputFile, \"kmeans_testsample2D.txt\");\n    unsigned long Nrows;\n    int Ncols;\n\n    File::sniffFile(inputFile, Nrows, Ncols);\n    ArrayXXd data = File::arrayXXdFromFile(inputFile, Nrows, Ncols);\n    ArrayXXd sample = data.transpose();\n    inputFile.close();\n\n\n    \n    \n    // Set up the clusterer using a Euclidean metric\n\n    EuclideanMetric myMetric;\n    int minNclusters = 2;\n    int maxNclusters = 10;\n    int Ntrials = 20;\n    double relTolerance = 0.01;\n\n    bool printNdimensions = false;\n    PrincipalComponentProjector projector(printNdimensions);\n    bool featureProjectionActivated = false;\n\n    KmeansClusterer clusterer(myMetric, projector, featureProjectionActivated, \n                           minNclusters, maxNclusters, Ntrials, relTolerance); \n\n\n    // Do the clustering, and get for each point the index of the cluster it belongs to\n\n    int optimalNclusters;\n    vector<int> clusterIndices(Nrows);\n    vector<int> clusterSizes;\n\n    optimalNclusters = clusterer.cluster(sample, clusterIndices, clusterSizes);\n    int Nclusters = optimalNclusters; \n   \n\n    // Output the results \n    \n    cerr << \"Input number of clusters: 5\" << endl; \n    cerr << \"Optimal number of clusters: \" << optimalNclusters << endl;\n    \n\n    // ------ Compute Ellipsoids ------\n    \n    int Ndimensions = Ncols;\n    assert(sample.cols() == clusterIndices.size());\n    assert(sample.cols() >= Ndimensions + 1);            // At least Ndimensions + 1 points are required.\n\n\n    // The enlargement fraction (it is the fraction by which each axis of an ellipsoid is enlarged)\n\n    double enlargementFraction = 3.0;  \n    \n    \n    // Compute \"sorted indices\" such that clusterIndices[sortedindices[k]] <= clusterIndices[sortedIndices[k+1]]\n\n    vector<int> sortedIndices = Functions::argsort(clusterIndices);\n\n\n    // beginIndex will take values such that the indices for one particular cluster (# n) will be in \n    // sortedIndex[beginIndex, ..., beginIndex + clusterSize[n] - 1]      \n\n    int beginIndex = 0;\n\n\n    // Clear whatever was in the ellipsoids collection\n\n    vector<Ellipsoid> ellipsoids;\n    ellipsoids.clear();\n\n\n    // Create an Ellipsoid for each cluster (provided it's large enough)\n\n    for (int i = 0; i < Nclusters; i++)\n    {   \n        // Skip cluster if number of points is not large enough\n\n        if (clusterSizes[i] < Ndimensions + 1) \n        {\n            // Move the beginIndex up to the next cluster\n\n            beginIndex += clusterSizes[i];\n\n\n            // Continue with the next cluster\n\n            continue;\n        }\n        else\n        {\n            // The cluster is indeed large enough to compute an Ellipsoid.\n\n            // Copy those points that belong to the current cluster in a separate Array\n            // This is because Ellipsoid needs a contiguous array of points.\n\n            ArrayXXd sampleOfOneCluster(Ndimensions, clusterSizes[i]);\n\n            for (int n = 0; n < clusterSizes[i]; ++n)\n            {\n                sampleOfOneCluster.col(n) = sample.col(sortedIndices[beginIndex+n]);\n            }\n\n\n            // Move the beginIndex up to the next cluster\n\n            beginIndex += clusterSizes[i];\n\n\n            // Add ellipsoid at the end of our vector\n\n            ellipsoids.push_back(Ellipsoid(sampleOfOneCluster, enlargementFraction));\n        }\n    }\n\n    int Nellipsoids = ellipsoids.size();\n    cerr << \"Nellispids: \" << Nellipsoids << endl;\n   \n    \n    // Find which ellipsoids are overlapping and which are not\n    \n    vector<unordered_set<int>> overlappingEllipsoidsIndices;\n\n\n    // Remove whatever was in the container before\n\n    overlappingEllipsoidsIndices.clear();\n   \n\n    // Make sure that the indices container has the right size\n\n    overlappingEllipsoidsIndices.resize(ellipsoids.size());\n\n\n    // If Ellipsoid i overlaps with ellipsoid j, than of course ellipsoid j also overlaps with i.\n    // The indices are kept in an unordered_set<> which automatically takes care\n    // that there are no duplicates.  \n    \n    bool ellipsoidMatrixDecompositionIsSuccessful;\n\n    for (int i = 0; i < Nellipsoids-1; ++i)\n    {\n        for (int j = i+1; j < Nellipsoids; ++j)\n        {\n            if (ellipsoids[i].overlapsWith(ellipsoids[j], ellipsoidMatrixDecompositionIsSuccessful))\n            {\n                overlappingEllipsoidsIndices[i].insert(j);\n                overlappingEllipsoidsIndices[j].insert(i);\n            }\n        }\n    }\n\n    mt19937 engine;\n    clock_t clockticks = clock();\n    engine.seed(clockticks);\n    uniform_real_distribution<> uniform(0.0, 1.0);  \n    \n\n    // Get the hyper-volume for each of the ellipsoids and normalize it \n    // to the sum of the hyper-volumes over all the ellipsoids\n\n    vector<double> normalizedHyperVolumes(Nellipsoids);\n    \n    for (int n=0; n < Nellipsoids; ++n)\n    {\n        normalizedHyperVolumes[n] = ellipsoids[n].getHyperVolume();\n    }\n\n    double sumOfHyperVolumes = accumulate(normalizedHyperVolumes.begin(), normalizedHyperVolumes.end(), 0.0, plus<double>());\n\n    ArrayXd centerCoordinate(2);\n   \n    cout << \"Nrmalized Hyper-Volumes\" << endl;\n    for (int n = 0; n < Nellipsoids; ++n)\n    {\n        normalizedHyperVolumes[n] /= sumOfHyperVolumes;\n        centerCoordinate = ellipsoids[n].getCenterCoordinates();\n        cerr << \"Ellipsoid #\" << n << \"   \" << normalizedHyperVolumes[n] << endl;\n        cerr << \"Center Coordinates: \" << centerCoordinate.transpose() << endl;\n        cerr << endl;\n    }\n\n\n    // Pick an ellipsoid with a probability according to its normalized hyper-volume\n    // First generate a uniform random number between 0 and 1\n\n    double uniformNumber = uniform(engine);\n\n\n    // Select the ellipsoid that makes the cumulative hyper-volume greater than this random\n    // number. Those ellipsoids with a larger hyper-volume will have a greater probability to \n    // be chosen.\n\n    double cumulativeHyperVolume = normalizedHyperVolumes[0];\n    int indexOfSelectedEllipsoid = 0;\n    \n    while (cumulativeHyperVolume < uniformNumber)\n    {\n        indexOfSelectedEllipsoid++;\n        cumulativeHyperVolume += normalizedHyperVolumes[indexOfSelectedEllipsoid];\n    }\n\n    cerr << \"Selected Ellipsoid #: \" << indexOfSelectedEllipsoid << endl;\n    centerCoordinate = ellipsoids[indexOfSelectedEllipsoid].getCenterCoordinates();\n    cerr << \"Center Coordinates: \" << centerCoordinate.transpose() << endl;\n    cerr << endl;\n   \n\n    // ------ Draw points from the Ellipsoid ------\n\n    int Npoints = 10000;    \n    ArrayXXd sampleOfDrawnPoints(Npoints,Ndimensions);\n    ArrayXd drawnPoint(Ndimensions);\n\n    for (int i=0; i < Npoints; ++i)\n    {\n        bool newPointIsFound = false;\n        \n        while (newPointIsFound == false)\n        {\n            // Draw a new point inside the ellipsoid\n            \n            ellipsoids[indexOfSelectedEllipsoid].drawPoint(drawnPoint);\n            \n            \n            // Check if the new point is also in other ellipsoids. If the point happens to be \n            // in N overlapping ellipsoids, then accept it only with a probability 1/N. If we\n            // wouldn't do this, the overlapping regions in the ellipsoids would be oversampled.\n\n            if (!overlappingEllipsoidsIndices[indexOfSelectedEllipsoid].empty())\n            {\n                // There are overlaps, so count the number of ellipsoids to which the new\n                // point belongs\n            \n                int NenclosingEllipsoids = 1;\n\n                for (auto index = overlappingEllipsoidsIndices[indexOfSelectedEllipsoid].begin();\n                          index != overlappingEllipsoidsIndices[indexOfSelectedEllipsoid].end();\n                        ++index)\n                {\n                    if (ellipsoids[*index].containsPoint(drawnPoint))  \n                    {\n                        NenclosingEllipsoids = static_cast<int>(DBL_MAX);\n                        //NenclosingEllipsoids++;\n                    }\n                }\n\n\n                // Only accept the new point with a probability = 1/NenclosingEllipsoids. \n                // If it's not accepted, go immediately back to the beginning of the while loop, \n                // and draw a new point inside the ellipsoid.\n\n                uniformNumber = uniform(engine);\n                newPointIsFound = (uniformNumber < 1./NenclosingEllipsoids);\n            }\n            else\n            {\n                // There are no ellipsoids overlapping with the selected one, so the point\n                // is automatically accepted\n\n                newPointIsFound = true;\n            }\n        }\n\n        sampleOfDrawnPoints.row(i) = drawnPoint.transpose();\n    }\n\n    ofstream outputFile;\n    File::openOutputFile(outputFile,\"ellipsoidSample2D.txt\");\n    File::arrayXXdToFile(outputFile, sampleOfDrawnPoints);\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "047a7a6d1b912717de0c1373e7b0b22f381f1f48", "size": 9543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/demoEllipsoids2D.cpp", "max_stars_repo_name": "vishalbelsare/DIAMONDS", "max_stars_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/demoEllipsoids2D.cpp", "max_issues_repo_name": "vishalbelsare/DIAMONDS", "max_issues_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/demoEllipsoids2D.cpp", "max_forks_repo_name": "vishalbelsare/DIAMONDS", "max_forks_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.495049505, "max_line_length": 141, "alphanum_fraction": 0.6314576129, "num_tokens": 2164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6146666070244091}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\n#include <ipc/utils/eigen_ext.hpp>\n\nnamespace ipc {\n\n/// @brief Compute the distance between two points.\n/// @note The distance is actually squared distance.\n/// @param[in] p0 The first point.\n/// @param[in] p1 The second point.\n/// @return The distance between p0 and p1.\ntemplate <typename DerivedP0, typename DerivedP1>\ninline auto point_point_distance(\n    const Eigen::MatrixBase<DerivedP0>& p0,\n    const Eigen::MatrixBase<DerivedP1>& p1)\n{\n    return (p1 - p0).squaredNorm();\n}\n\n/// @brief Compute the gradient of the distance between two points.\n/// @note The distance is actually squared distance.\n/// @param[in] p0 The first point.\n/// @param[in] p1 The second point.\n/// @param[out] grad The computed gradient.\ntemplate <typename DerivedP0, typename DerivedP1, typename DerivedGrad>\ninline void point_point_distance_gradient(\n    const Eigen::MatrixBase<DerivedP0>& p0,\n    const Eigen::MatrixBase<DerivedP1>& p1,\n    Eigen::PlainObjectBase<DerivedGrad>& grad)\n{\n    assert(p0.size() == p1.size());\n    grad.resize(p0.size() + p1.size());\n    grad.head(p0.size()) = 2.0 * (p0 - p1);\n    grad.tail(p1.size()) = -grad.head(p0.size());\n}\n\n/// @brief Compute the hessian of the distance between two points.\n/// @note The distance is actually squared distance.\n/// @param[in] p0 The first point.\n/// @param[in] p1 The second point.\n/// @param[out] hess The computed hessian.\ntemplate <typename DerivedP0, typename DerivedP1, typename DerivedHess>\ninline void point_point_distance_hessian(\n    const Eigen::MatrixBase<DerivedP0>& p0,\n    const Eigen::MatrixBase<DerivedP1>& p1,\n    Eigen::PlainObjectBase<DerivedHess>& hess)\n{\n    int dim = p0.size();\n    assert(p1.size() == dim);\n\n    hess.resize(2 * dim, 2 * dim);\n\n    hess.setZero();\n    hess.diagonal().setConstant(2.0);\n    for (int i = 0; i < dim; i++) {\n        hess(i, i + dim) = hess(i + dim, i) = -2;\n    }\n}\n\n} // namespace ipc\n", "meta": {"hexsha": "ab46706d92592973a79d47135fca688283d0c58b", "size": 1933, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/distance/point_point.hpp", "max_stars_repo_name": "ipc-sim/ipc-toolk", "max_stars_repo_head_hexsha": "81873d0288810e30166d871419da4104329860e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T21:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:24:31.000Z", "max_issues_repo_path": "src/distance/point_point.hpp", "max_issues_repo_name": "dbelgrod/ipc-toolkit", "max_issues_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T18:39:30.000Z", "max_forks_repo_path": "src/distance/point_point.hpp", "max_forks_repo_name": "dbelgrod/ipc-toolkit", "max_forks_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T12:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T04:55:49.000Z", "avg_line_length": 30.6825396825, "max_line_length": 71, "alphanum_fraction": 0.6802897051, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6146568577804766}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <typeinfo>\n#include <iostream>\n#include <cassert>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace std;\n    using mtl::lazy; using mtl::io::tout;\n    typedef mtl::dense_vector<double> vt;\n    \n    vt v(60);\n    iota(v);\n    tout << \"v is \" << v << endl;\n\n    mtl::mat::identity2D I(60);\n    vt w1(I * v);\n    tout << \"I * v is \" << w1 << endl;\n\n    if (one_norm(vt(w1 - v)) > 0.001) throw \"Wrong result with square identity\";\n\n    w1-= I * v;\n    tout << \"w1-= I * v is \" << w1 << endl;\n    if (one_norm(w1) > 0.001) throw \"Wrong result\";\n\n    w1+= I * v;\n    tout << \"w1+= I * v is \" << w1 << endl;\n    if (one_norm(vt(w1 - v)) > 0.001) throw \"Wrong result with square identity\"; \n\n    vt w2( w1 - I * v );\n    double alpha;\n    (lazy(w2)= I * v) || (lazy(alpha)= lazy_dot(w2, v));\n\n    vt w3(30), w4(90);\n    mtl::mat::identity2D I3(30, 60), I4(90, 60);\n    \n    w3= I3 * v;\n    tout << \"I3 * v is \" << w3 << endl;\n    if (one_norm(vt(w3 - v[mtl::irange(30)])) > 0.001) throw \"Wrong result with broad identity\";\n    \n    w4= I4 * v;\n    tout << \"I4 * v is \" << w4 << endl;\n    if (one_norm(vt(w4[mtl::irange(60)] - v)) > 0.001) throw \"Wrong result with long identity\";\n    if (one_norm(w4[mtl::irange(60, 90)]) > 0.001) throw \"Wrong result with long identity\";\n\n#if 0\n    mtl::dense2D<double> A(60,60);\n    A=2;\n    A+= A*I;\n    std::cout<< \"A=\\n\" << A << \"\\n\";\n#endif\n    return 0;\n}\n", "meta": {"hexsha": "61f7c754a10bd043d6b22356420821b6f911c0ed", "size": 1873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_identity_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/matrix_identity_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/matrix_identity_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 28.3787878788, "max_line_length": 96, "alphanum_fraction": 0.5728777363, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6146315527954284}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n#include <algorithm>\n#include <iostream>\n\n#include <boost/random/normal_distribution.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n\n#include <dpMM/distribution.hpp>\n#include <dpMM/sphere.hpp>\n\n#define LOG_2 0.69314718055994529\n#define LOG_PI 1.1447298858494002\n#define LOG_2PI 1.8378770664093453\n#define LOG_4PI 2.5310242469692907\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\nusing std::min;\n\ntemplate<typename T> \ninline T logBesselI(T nu, T x)\n{\n  // for large values of x besselI \\approx exp(x)/sqrt(2 PI x)\n  if(x>100.)  return x - 0.5*LOG_2PI -0.5*log(x);\n  return log(boost::math::cyl_bessel_i(nu,x));\n\n};\n\ntemplate<typename T> \ninline T logxOverSinhX(T x) {\n  if (fabs(x) < 1e-9) \n    return 0.;\n  else\n    return log(x)-log(sinh(x));\n}\ntemplate<typename T> \ninline T xOverSinhX(T x) {\n  if (fabs(x) < 1e-9) \n    return 1.;\n  else\n    return x/sinh(x);\n}\ntemplate<typename T> \ninline T xOverTanPiHalfX(T x) {\n  if (fabs(x) < 1e-9) \n    return 2./M_PI;\n  else\n    return x/tan(x*M_PI*0.5);\n}\n\ntemplate <typename T>\ninline T MLEstimateTau(const Eigen::Matrix<T,3,1>& xSum, const\n    Eigen::Matrix<T,3,1>& mu, T count) {\n  // Need double precision to achive convergence; single is not enough.\n  double tau = 1.0;\n  double prevTau = 0.;\n  double eps = 1e-8;\n  double R = xSum.norm()/count;\n  while (fabs(tau - prevTau) > eps) {\n//    std::cout << \"tau \" << tau << \" R \" << R << std::endl;\n    double inv_tanh_tau = 1./tanh(tau);\n    double inv_tau = 1./tau;\n    double f = -inv_tau + inv_tanh_tau - R;\n    double df = inv_tau*inv_tau - inv_tanh_tau*inv_tanh_tau + 1.;\n    prevTau = tau;\n    tau -= f/df;\n  }\n  return tau;\n};\n\n/* von-Mises-Fisher distribution in D=3 dimensions\n */\ntemplate<typename T>\nclass vMF : public Distribution<T>\n{\npublic:\n  uint32_t  D_;\n\n  vMF(const Matrix<T,Dynamic,1>& mu, T tau, boost::mt19937 *pRndGen);\n  vMF(const vMF<T>& vmf);\n  ~vMF();\n\n  T logPdf(const Matrix<T,Dynamic,1>& x) const;\n\n  Matrix<T,Dynamic,1> sample();\n\n  void print() const;\n\n  const Matrix<T,Dynamic,1>& mu() const {return mu_;};\n  void mu(const Matrix<T,Dynamic,1>& mu) const {mu_ = mu;};\n\n  T tau() const {return tau_;};\n  void tau(const T tau) {tau_ = tau;};\n\n  Matrix<T,Dynamic,1> mu_;\n  T tau_;\nprivate:\n  \n// Gaussian as a proposal distribution\n  boost::mt19937 *pRndGen_;\n  boost::uniform_01<> unif_;\n  boost::normal_distribution<> gauss_;\n};\n\ntypedef vMF<double> vMFd;\ntypedef vMF<float> vMFf;\n\ntemplate<typename T>\nvMF<T>::vMF(const Matrix<T,Dynamic,1>& mu, T tau, boost::mt19937 *pRndGen)\n  : Distribution<T>(pRndGen), D_(mu.rows()), mu_(mu), tau_(tau),\n  pRndGen_(pRndGen), gauss_(0,1)\n{};\n\ntemplate<typename T>\nvMF<T>::vMF(const vMF<T>& vmf)\n  : Distribution<T>(vmf.pRndGen_), D_(vmf.D_), mu_(vmf.mu()), tau_(vmf.tau()),\n    pRndGen_(vmf.pRndGen_), gauss_(0,1)\n{};\n\ntemplate<typename T>\nvMF<T>::~vMF()\n{};\n\ntemplate<typename T>\nT vMF<T>::logPdf(const Matrix<T,Dynamic,1>& x) const \n{\n  // modified bessel function of the first kind\n  // http://www.boost.org/doc/libs/1_35_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/bessel/mbessel.html\n  // \n  const T d = static_cast<T>(D_);\n  if (tau_ < 1e-9) {\n    // TODO insert general formula here (this currently works only\n    // for D=3\n    assert(D_==3);\n    return -LOG_4PI;\n  } else {\n    if (D_ == 3) {\n      return -LOG_2PI + log(tau_) + tau_*(mu_.dot(x)-1.) -\n        log(1.-exp(-2.*tau_));\n    }else {\n      return (d/2. -1.)*log(tau_) - (d/2.)*LOG_2PI \n        - logBesselI<T>(d/2. -1.,tau_) + tau_*mu_.dot(x);\n    }\n  }\n};\n\ntemplate<typename T>\nMatrix<T,Dynamic,1> vMF<T>::sample()\n{\n  assert(D_==3);\n  if (tau_ < 1e-10) {\n//    Eigen::VectorXf x;\n//    x << gauss_(*pRndGen_), gauss_(*pRndGen_), gauss_(*pRndGen_);\n//    return x.normalized();\n    return Eigen::Matrix<T,3,1>(gauss_(*pRndGen_), gauss_(*pRndGen_), gauss_(*pRndGen_)).normalized();\n  }\n  // https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf\n  // sample around (0,0,1)\n  Eigen::Matrix<T,2,1> v(gauss_(*pRndGen_), gauss_(*pRndGen_));\n  v.normalize();\n  const T u = unif_(*pRndGen_);\n  const T w = 1. + log(u+(1.-u)*exp(-2.*tau_))/tau_;\n  const T a = sqrtf(1.-w*w);\n  Eigen::Matrix<T,3,1> x(a*v(0), a*v(1), w);\n\n  // rotate to mu\n  Eigen::Matrix<T,3,1> axis = Eigen::Matrix<T,3,1>(0,0,1).cross(Eigen::Matrix<T,3,1>(mu_(0),mu_(1),mu_(2)));\n  T angle = acos(mu_[2]);\n\n  if (fabs(angle) <1e-9) \n    return x;\n\n  Eigen::Quaternion<T> q(cos(angle*0.5), \n      sin(angle*0.5)*axis(0)/axis.norm(),\n      sin(angle*0.5)*axis(1)/axis.norm(),\n      sin(angle*0.5)*axis(2)/axis.norm());\n  Eigen::Matrix<T,Eigen::Dynamic,1> xx = q._transformVector(x);\n  return xx;\n};\n\ntemplate<typename T>\nvoid vMF<T>::print() const\n{\n  cout<<\"mu = \"<<mu_.transpose()<<\"\\t tau = \"<<tau_<<endl;\n};\n", "meta": {"hexsha": "c04427192c7c727a7863cd9c2248ea0bbc1c1dba", "size": 4931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/vmf.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/dpMM/vmf.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dpMM/vmf.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 25.4175257732, "max_line_length": 113, "alphanum_fraction": 0.6369904685, "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6145151430412665}}
{"text": "#ifndef MLT_MODELS_LINEAR_MODEL_HPP\n#define MLT_MODELS_LINEAR_MODEL_HPP\n\n#include <Eigen/Core>\n\n#include \"base.hpp\"\n#include \"../utils/linear_algebra.hpp\"\n\nnamespace mlt {\nnamespace models {\n\tusing namespace utils::linear_algebra;\n\n\ttemplate <class BaseModelType>\n\tclass LinearModel : public BaseModelType {\n\tpublic:\n\t\tinline auto fit_intercept() const { return _fit_intercept; }\n\n\t\tinline const auto coefficients() const { assert(_fitted); return _fit_intercept ? _coefficients.leftCols(_coefficients.cols() - 1).eval() : _coefficients; }\n\n\t\tinline const auto intercepts() const { assert(_fitted && _fit_intercept); return _coefficients.rightCols<1>().eval(); }\n\n\t\tinline const auto all_coefficients() const { assert(_fitted); return _coefficients; }\n\n\tprotected:\n\t\tLinearModel(bool fit_intercept) : _fit_intercept(fit_intercept) {}\n\n\t\tinline void _set_coefficients(MatrixXdRef coefficients) {\n\t\t\t_coefficients = coefficients;\n\t\t\t_fitted = true;\n\t\t}\n\n\t\tinline auto _apply_linear_transformation(Features input) const {\n\t\t\tassert(_fitted);\n\n\t\t\tif (_fit_intercept) {\n\t\t\t\treturn linear_transformation(input, _coefficients.leftCols(_coefficients.cols() - 1), _coefficients.rightCols<1>());\n\t\t\t}\n\n\t\t\treturn linear_transformation(input, _coefficients);\n\t\t}\n\n\t\tinline auto _apply_linear_transformation(Features input, MatrixXdRef coeffs) const {\n\t\t\tif (_fit_intercept) {\n\t\t\t\treturn linear_transformation(input, coeffs.leftCols(coeffs.cols() - 1), coeffs.rightCols<1>());\n\t\t\t}\n\t\t\t\n\t\t\treturn linear_transformation(input, coeffs);\n\t\t}\n\n\t\tconst bool _fit_intercept;\n\n\tprivate:\n\t\tMatrixXd _coefficients;\n\t};\n}\n}\n\n#endif", "meta": {"hexsha": "3b0fbd4dc2ed39817de57053502e5064bd7af1f4", "size": 1607, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/models/linear_model.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/mlt/models/linear_model.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlt/models/linear_model.hpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7068965517, "max_line_length": 158, "alphanum_fraction": 0.7523335408, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.614454522706136}}
{"text": "#pragma once\n\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include <cmath>\n\nnamespace LRR\n{\n  namespace Math\n  {\n    using namespace Eigen;\n\n    template <typename T>\n    T ToRadians(T deg) { return deg * T(0.01745329251f); }\n\n    template <typename T>\n    T ToDegrees(T rad) { return rad * T(57.2957795131f); }\n\n    Matrix4f PerspectiveProjection(float fovy, float aspect, float zNear, float zFar);\n\n    Matrix4f RotationMatrix(AngleAxisf const &rotation);\n  }\n}", "meta": {"hexsha": "c7f4496893b8def6f9127be110dd1099b4cdf7cc", "size": 468, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math.hpp", "max_stars_repo_name": "Lisoph/LowResRenderer", "max_stars_repo_head_hexsha": "1f86aca8bca680e8e10ef8695977cd22e79a1f0b", "max_stars_repo_licenses": ["MIT"], "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": "Lisoph/LowResRenderer", "max_issues_repo_head_hexsha": "1f86aca8bca680e8e10ef8695977cd22e79a1f0b", "max_issues_repo_licenses": ["MIT"], "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": "Lisoph/LowResRenderer", "max_forks_repo_head_hexsha": "1f86aca8bca680e8e10ef8695977cd22e79a1f0b", "max_forks_repo_licenses": ["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.347826087, "max_line_length": 86, "alphanum_fraction": 0.6923076923, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.614454522706136}}
{"text": "#include <stdlib.h>     // srand, rand\n#include <unistd.h>\t// sleep\n#include <armadillo>\n#include <boost/math/special_functions/digamma.hpp>\n\n#include \"Sto_IHT.h\"\n#include \"Functions.h\"\n\nusing namespace arma;\nusing namespace std;\n\nvec expected_ln_beta_dist(const vec pos_count, const vec neg_count){\n// The logarithm of the geometric mean GX of a distribution with random variable X is the arithmetic mean of ln(X)\n//https://en.wikipedia.org/wiki/Beta_distribution#Geometric_mean\nvec ln_GX(pos_count.n_elem,fill::zeros);\nfor (unsigned int n = 0; n < ln_GX.n_elem; n++){\n\tln_GX(n) = boost::math::digamma(pos_count(n)) - boost::math::digamma(pos_count(n) + neg_count(n));\n\n}\nreturn ln_GX;  \n}\n\ndouble expected_ln_beta_dist(const double pos_count, const double neg_count){\n// The logarithm of the geometric mean GX of a distribution with random variable X is the arithmetic mean of ln(X)\n//https://en.wikipedia.org/wiki/Beta_distribution#Geometric_mean\ndouble ln_GX = boost::math::digamma(pos_count) - boost::math::digamma(pos_count + neg_count);\n\nreturn ln_GX;  \n}\n\nivec generate_support(const uvec &curr_supp,const uvec &prev_supp,const int sig_dim){\n\tivec supp_data(sig_dim,fill::ones);\n\tsupp_data *= -1;\n\n\tuvec mask_old(sig_dim,fill::zeros);\t// mask for the previous support\n\tmask_old(prev_supp) = ones<uvec>(prev_supp.n_elem);\n\t\n\tuvec mask_new(sig_dim,fill::zeros);\t// mask for the current support\n\tmask_new(curr_supp) = ones<uvec>(curr_supp.n_elem);\n\n\tconst uvec zero_indices = find(mask_old%(1 - mask_new));\n\tconst uvec one_indices  = find(mask_new%(1 - mask_old)) ;\n\tsupp_data.elem( zero_indices ).zeros(); \n\tsupp_data.elem( one_indices ).ones();\n\n\treturn supp_data;\n}\n\n\nvoid update_tally_bayesian(vec &pos_count, vec &neg_count, double &reliability_pos, \n\tdouble &reliability_neg, vec &expected_u, const ivec &support_data, \n\tconst ivec &prev_support_data, const double P_rand, const unsigned int global_iters, \n\tconst unsigned int local_iters){\n\t// initialization\n\tconst unsigned int sig_dim = pos_count.n_elem;\n\n\tuvec old_zero_indices = find(prev_support_data ==0);\t\n\tuvec old_one_indices = find(prev_support_data ==1);\t\n\tvec  old_expected_u  = expected_u;\n\n\tuvec zero_indices = find(support_data ==0);\t\n\tuvec one_indices = find(support_data ==1);\t\n\tconst uvec obs_indices = find(support_data !=-1);\n\n\n\t// #### Update U  #####\n\tmat Ln_Q(sig_dim,2,fill::zeros);\n\tuvec U(1);\n\t// evaluate update rules for U = 0\n\tU.zeros();  \n\t//prior term\n\tLn_Q(obs_indices,U).fill(expected_ln_beta_dist(reliability_neg,reliability_pos)) ; \n\n\t//liklihood term \t\n\tLn_Q(zero_indices,U) += expected_ln_beta_dist(pos_count(zero_indices),neg_count(zero_indices)); \t\n\tLn_Q(one_indices,U)  += expected_ln_beta_dist(neg_count(one_indices),pos_count(one_indices));  \n\n \n\t// evaluate update rules for U = 1\n\tU.ones();\n\t// prior term\n\tLn_Q(obs_indices,U).fill( expected_ln_beta_dist(reliability_pos,reliability_neg) );\n\t// liklihood term\n\tLn_Q(zero_indices,U) += expected_ln_beta_dist(neg_count(zero_indices),pos_count(zero_indices)); \n\tLn_Q(one_indices,U) += expected_ln_beta_dist(pos_count(one_indices),neg_count(one_indices)); \n\n\tmat Q = exp(Ln_Q);\t\t// posterior mass function (not normalized)\n\texpected_u(obs_indices) = Q(obs_indices,U)/sum(Q.rows(obs_indices),1);\n\n\t// #### Update R  #####\n\t// using coefficient reliability\n\t// prior term (XXX: comment tu use the prevoius value as prior)\n\treliability_pos = 1;\n\treliability_neg = 1; \n\t// liklihood term (coefficient reliability)\n\treliability_pos += sum(expected_u(obs_indices));\t\n\treliability_neg += sum(1 - expected_u(obs_indices));\n\t// liklihood term (number of iterations)\n\treliability_pos += local_iters;\n\treliability_neg += global_iters - local_iters;\n\n\t// #### Update Phi  #####\t\n\t#pragma omp critical\n\t{\n\tpos_count(one_indices) += expected_u(one_indices);\n\tneg_count(zero_indices) += expected_u(zero_indices);\n\tif (any(prev_support_data!=-1)){\n\t\tpos_count(old_one_indices) -= old_expected_u(old_one_indices);\n\t\tneg_count(old_zero_indices) -= old_expected_u(old_zero_indices);\n\t}\n\t}\n\t\n\n\treturn;\n}\n\n\n\n\nvec bayesian_Sto_IHT(const mat &A, const vec &y, const int sparsity, const vec prob_vec,\n\t\tconst unsigned int max_iter, const double gamma,const double tol, \n\t\tunsigned int &num_iters, const simulation_parameters simulation_params){\n\tuvec slow_cores;\n\tset_slow_cores(slow_cores, simulation_params);\n\n\tconst unsigned int sig_dim = A.n_cols;\n\t// initialization of variables that are SHARED among cores\n\tuvec updated_indices;\n\tvec pos_count(sig_dim,fill::ones);\t// positive count for tally score\n\tvec neg_count(sig_dim,fill::ones);\t// negative count for tally score\n\tvec x_hat_total(sig_dim,fill::zeros);\t// estimation of the signal\n\tbool done = false;\t\t\t// flag to check the convergence criteria\n\tunsigned int i = 0;\t\t\t// total number of iterations\n\tconst double P_rand = sparsity/sig_dim;\t//  probability of unreliable '1' measurement\n\t// parallel section of the code starts here\n\t#pragma omp parallel num_threads(simulation_params.num_cores)\n\t{\n\n\t// initializaiotn of variables that are LOCAL to each core\n\tuvec updated_indices;\n\tvec x_hat_local(sig_dim,fill::zeros);  \t// this is local to each core\n\tunsigned int iter_local = 0;\t\t// number of iteration for this core\n\tivec support_data(sig_dim,fill::zeros);\t// data on estimated support\n\tivec prev_support_data(sig_dim);\t// previous estimated support\n\tprev_support_data.fill(-1);\n\tdouble reliability_pos = 1;\t\t// positive count for core reliability\n\tdouble reliability_neg = 1;\t\t// negative count for core reliability\n\tvec expected_u(sig_dim);\t// expected coeffcient reliability (vote)\n\texpected_u.fill(1);\n\n\t// iterations to find the solutions\n\twhile(!done){\n\t\tvec tally= pos_count/ (pos_count + neg_count);\n\t\t// master thread uses the tally vector to check the convergence criteria\n\t\tif (omp_get_thread_num() == 0){\n\t\t\tconst uvec sorted_ind = sort_index(abs(tally),\"descend\");\n\t\t\tconst uvec est_supp = sorted_ind(span(0,sparsity - 1));\n\t\t\tconst mat A_supp = A.cols(est_supp);\n\t\t\tx_hat_local.zeros();\n\t\t\tx_hat_local(est_supp) = solve(A_supp,y);\n\t\t\tif (norm (y - A*x_hat_local) < tol || i >= max_iter){\n\t\t\t\tx_hat_total = x_hat_local;\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//slow cores sleep for  simulation_params.sleep_slow_cores microseconds\n\t\tif (any( slow_cores == omp_get_thread_num()) ){\n\t\t\tusleep(simulation_params.sleep_slow_cores);\n\t\t}\n\t\t\n\t\ti++;\n\t\titer_local++;\n\n\n\t\t// update the local estimate of the support\n\t\tuvec est_supp_local;\n        est_supp_local = Sto_IHT_async_iteration(x_hat_local, tally, A, y, \t\n            sparsity, prob_vec, gamma);\n\n\t\t// generate support data\n\t\tsupport_data.fill(-1);support_data.elem(est_supp_local).ones();\t\n\t\tupdate_tally_bayesian(pos_count, neg_count, reliability_pos, reliability_neg, expected_u, support_data, prev_support_data, P_rand, i , iter_local );\t\t\n\n\t\tprev_support_data = support_data;\n\t}\n\t}\n\t// parallel section of the code ends here\n\n\tnum_iters = i;\n\treturn x_hat_total;\n}\n\n", "meta": {"hexsha": "87e6b174de27264db50fdb8870f359babbff9caa", "size": 6918, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Bayes_Sto_IHT.cpp", "max_stars_repo_name": "LCWN-Lab/Parallel-Sparse-Recovery", "max_stars_repo_head_hexsha": "b5dd6b98977bcb437164f1c0109bc892f1d7141d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Bayes_Sto_IHT.cpp", "max_issues_repo_name": "LCWN-Lab/Parallel-Sparse-Recovery", "max_issues_repo_head_hexsha": "b5dd6b98977bcb437164f1c0109bc892f1d7141d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bayes_Sto_IHT.cpp", "max_forks_repo_name": "LCWN-Lab/Parallel-Sparse-Recovery", "max_forks_repo_head_hexsha": "b5dd6b98977bcb437164f1c0109bc892f1d7141d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-24T04:15:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T17:25:19.000Z", "avg_line_length": 35.6597938144, "max_line_length": 152, "alphanum_fraction": 0.7418328997, "num_tokens": 1804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6144545095610608}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2016 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file squarerootclvmodel.hpp\n    \\brief CLV model with a square root kernel process\n*/\n\n#ifndef quantlib_square_root_clv_model_hpp\n#define quantlib_square_root_clv_model_hpp\n\n#include <ql/time/date.hpp>\n#include <ql/patterns/lazyobject.hpp>\n#include <ql/math/interpolations/lagrangeinterpolation.hpp>\n#include <ql/math/matrix.hpp>\n#include <ql/experimental/math/gaussiannoncentralchisquaredpolynomial.hpp>\n\n#include <boost/function.hpp>\n#include <map>\n\nnamespace QuantLib {\n\n    class GBSMRNDCalculator;\n    class SquareRootProcess;\n    class GeneralizedBlackScholesProcess;\n\n    class SquareRootCLVModel : public LazyObject {\n      public:\n        SquareRootCLVModel(\n            const boost::shared_ptr<GeneralizedBlackScholesProcess>& bsProcess,\n            const boost::shared_ptr<SquareRootProcess>& sqrtProcess,\n            const std::vector<Date>& maturityDates,\n            Size lagrangeOrder,\n            Real pMax = Null<Real>(),\n            Real pMin = Null<Real>());\n\n        // cumulative distribution function of the BS process\n        Real cdf(const Date& d, Real x) const;\n\n        // inverse cumulative distribution function of the BS process\n        Real invCDF(const Date& d, Real q) const;\n\n        // collocation points of the square root process\n        Disposable<Array> collocationPointsX(const Date& d) const;\n\n        // collocation points for the underlying Y\n        Disposable<Array> collocationPointsY(const Date& d) const;\n\n        // CLV mapping function\n        boost::function<Real(Time, Real)> g() const;\n\n      protected:\n        void performCalculations() const;\n\n      private:\n        class MappingFunction : public std::binary_function<Time, Real, Real> {\n          public:\n            explicit MappingFunction(const SquareRootCLVModel& model);\n\n            Real operator()(Time t, Real x) const;\n\n          private:\n            const boost::shared_ptr<Matrix> s_, x_;\n            typedef std::map<Time, boost::shared_ptr<LagrangeInterpolation> >\n                interpl_type;\n\n            interpl_type interpl;\n        };\n\n        std::pair<Real, Real> nonCentralChiSquaredParams(const Date& d) const;\n\n        const Real pMax_, pMin_;\n        const boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess_;\n        const boost::shared_ptr<SquareRootProcess> sqrtProcess_;\n        const std::vector<Date> maturityDates_;\n        const Size lagrangeOrder_;\n        const boost::shared_ptr<GBSMRNDCalculator> rndCalculator_;\n\n        mutable boost::function<Real(Time, Real)> g_;\n    };\n}\n\n#endif\n", "meta": {"hexsha": "ba65a76bba58a7b35ea583aa3aede7f1d718bbbf", "size": 3346, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/squarerootclvmodel.hpp", "max_stars_repo_name": "sfondi/QuantLib", "max_stars_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-19T11:17:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-19T11:17:48.000Z", "max_issues_repo_path": "ql/experimental/models/squarerootclvmodel.hpp", "max_issues_repo_name": "sfondi/QuantLib", "max_issues_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T18:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T18:49:22.000Z", "max_forks_repo_path": "ql/experimental/models/squarerootclvmodel.hpp", "max_forks_repo_name": "sfondi/QuantLib", "max_forks_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.797979798, "max_line_length": 79, "alphanum_fraction": 0.6939629408, "num_tokens": 754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934408, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6144545018037006}}
{"text": "/**\n * @file Compute condition numbers of cell mass and stiffness matrices\n * for a bunch of finite element shape function sets.\n *\n * @note This file  is part of https://github.com/guidokanschat/benchmarks.git\n */\n\n#include <iostream>\n#include <fstream>\n\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_dgq.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_bernstein.h>\n#include <deal.II/lac/lapack_full_matrix.h>\n\nusing namespace dealii;\n\nenum class MatrixTypes\n{\n    mass,\n    stiffness\n};\n\ntemplate <int dim>\nvoid matrix (const FiniteElement<dim>& element,\n\t     const MatrixTypes type)\n{\n  Triangulation<dim> tr;\n  GridGenerator::hyper_cube (tr, 0., 1.);\n  DoFHandler<dim> dh (tr);\n  dh.distribute_dofs (element);\n  \n  const unsigned int degree = element.tensor_degree();\n  QGauss<dim> quadrature(degree+1);\n  LAPACKFullMatrix<double> M(element.dofs_per_cell);\n\n  FEValues<dim> fe(element, quadrature,\n\t\t   update_JxW_values | update_values | update_gradients);\n  fe.reinit(dh.begin_active());\n\n  for (unsigned int k=0;k<quadrature.size();++k)\n    for (unsigned int i=0;i<M.m();++i)\n      for (unsigned int j=0;j<M.n();++j)\n\tfor (unsigned int d=0;d<element.n_components();++d)\n\t  {\n\t    switch (type)\n\t      {\n\t    \tcase MatrixTypes::mass:\n\t\t      M(i,j) += fe.JxW(k)\n\t\t\t\t* fe.shape_value_component(j,k,d)\n\t\t\t\t* fe.shape_value_component(i,k,d);\n\t      \t      break;\n\t      \tcase MatrixTypes::stiffness:\n\t      \t      M(i,j) += fe.JxW(k)\n\t      \t\t\t* (fe.shape_grad_component(j,k,d)\n\t      \t\t\t   * fe.shape_grad_component(i,k,d));\n\t      \t      break;\n\t      }\n\t  }\n\n  M.compute_eigenvalues();\n  double lmin = 1.e30;\n  double lmax = -1.;\n  \n  for (unsigned int i=0;i<M.m();++i)\n    {  \n      const double lambda = M.eigenvalue(i).real();\nif (std::fabs(lambda) >= 1.e-9)\n\t{\n\t  if (lambda < lmin)\n\t    lmin = lambda;\n\t  if (lambda > lmax)\n\t    lmax = lambda;\n\t}\n    }\n  deallog << \"\\t[\" << lmin << \"\\t, \" << lmax\n\t  << \"]\\tcond \" << lmax/lmin;\n  deallog << std::endl;\n}\n\n\ntemplate<int dim>\nvoid doit ()\n{\n  typedef std::shared_ptr<const FiniteElement<dim> > FEPtr;\n  std::vector<FEPtr> elements;\n  elements.push_back(FEPtr(new FE_Q<dim>(1)));\n  elements.push_back(FEPtr(new FE_Q<dim>(2)));\n  elements.push_back(FEPtr(new FE_Q<dim>(3)));\n  elements.push_back(FEPtr(new FE_Q<dim>(4)));\n  elements.push_back(FEPtr(new FE_Q<dim>(5)));\n  elements.push_back(FEPtr(new FE_Q<dim>(6)));\n  elements.push_back(FEPtr(new FE_Q<dim>(7)));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGauss<1>(1))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGauss<1>(2))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGauss<1>(3))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGauss<1>(4))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGauss<1>(5))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGauss<1>(6))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGauss<1>(7))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGauss<1>(8))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGaussLobatto<1>(2))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGaussLobatto<1>(3))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGaussLobatto<1>(4))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGaussLobatto<1>(5))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGaussLobatto<1>(6))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGaussLobatto<1>(7))));\n  elements.push_back(FEPtr(new FE_DGQArbitraryNodes<dim>(QGaussLobatto<1>(8))));\n  elements.push_back(FEPtr(new FE_Bernstein<dim>(1)));\n  elements.push_back(FEPtr(new FE_Bernstein<dim>(2)));\n  elements.push_back(FEPtr(new FE_Bernstein<dim>(3)));\n  elements.push_back(FEPtr(new FE_Bernstein<dim>(4)));\n  elements.push_back(FEPtr(new FE_Bernstein<dim>(5)));\n  elements.push_back(FEPtr(new FE_Bernstein<dim>(6)));\n  elements.push_back(FEPtr(new FE_Bernstein<dim>(7)));\n\nfor (const FEPtr& fe : elements)\n  {\ndeallog << fe->get_name() << \"::mass \";\nmatrix(*fe, MatrixTypes::mass);\ndeallog << fe->get_name() << \"::stiff\";\nmatrix(*fe, MatrixTypes::stiffness);\n}\n\n}\n\n\nint main ()\n{\n  doit<2> ();\ndeallog << std::endl;\n  doit<3> ();\n}\n\n", "meta": {"hexsha": "e38a9ad744e48ba9141677ec5138975910035d62", "size": 4441, "ext": "cc", "lang": "C++", "max_stars_repo_path": "matrices/conditioning.cc", "max_stars_repo_name": "guidokanschat/benchmarks", "max_stars_repo_head_hexsha": "ceb961aa1cd7a084794e149f7f881005638f967c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matrices/conditioning.cc", "max_issues_repo_name": "guidokanschat/benchmarks", "max_issues_repo_head_hexsha": "ceb961aa1cd7a084794e149f7f881005638f967c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-10-28T07:16:39.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-28T07:16:39.000Z", "max_forks_repo_path": "matrices/conditioning.cc", "max_forks_repo_name": "guidokanschat/benchmarks", "max_forks_repo_head_hexsha": "ceb961aa1cd7a084794e149f7f881005638f967c", "max_forks_repo_licenses": ["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.4964539007, "max_line_length": 80, "alphanum_fraction": 0.6816032425, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.6144193795127446}}
{"text": "// Filename: umfpack_solve_example.cpp (part of MTL4)\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace std;  \n\nint main(int, char**)\n{\n#ifdef MTL_HAS_UMFPACK\n    typedef mtl::compressed2D<double> matrix_type;\n\n    matrix_type A(5, 5);\n    A= 2.,  3.,  0.,  0.,  0.,\n       3.,  0.,  4.,  0.,  6.,\n       0., -1., -3.,  2.,  0.,\n       0.,  0.,  1.,  0.,  0.,\n       0.,  4.,  2.,  0.,  1.;\n    crop(A);\n\n    mtl::dense_vector<double>   x(5), b(5);\n    b= 8., 45., -3., 3., 19.;\n    mtl::dense_vector<double>   b2(2 * b);\n    cout << \"A = \\n\" << A << \"b = \" << b << \"\\n\";\n\n    // Factorize and solve\n    umfpack_solve(A, x, b);\n    cout << \"\\nA \\\\ b using umfpack_solve = \" << x << \"\\n\";\n    \n    // Define a solver object by internally factorizing A\n    mtl::mat::umfpack::solver<matrix_type> solver(A);\n\n    // Solve A * x == b and b2 with the solver object\n    solver(x, b);\n    solver(x, b2);\n\n    // Change one or more matrix entries while keeping the sparsity pattern\n    A.lvalue(1, 2)= 5.0;\n\n    // Compute a new factorization (relying on unchanged sparsity)\n    solver.update_numeric();\n    \n    // If we change b accordingly we will get the same result\n    b[1]= 48;\n    solver(x, b);\n    cout << \"\\nA \\\\ b after numeric update = \" << x << \"\\n\";\n\n    // Change matrix's values and sparsity\n    {\n\tmtl::mat::inserter<matrix_type> ins(A);\n\tins[3][4] << 2.;\t\n    }\n    cout << \"\\nA is now = \\n\" << A << \"\\n\";\n\n    // Perform a completely new factorization\n    solver.update();\n\n    b[3]= 13.;\n    int status= solver(x, b);\n    cout << \"A \\\\ b after (complete) update = \" << x << \", status is \" << status << \"\\n\";\n\n#endif\n    return 0;\n}\n", "meta": {"hexsha": "3d6ecad1369d151508cfd510332fbb5c4476ffcd", "size": 1669, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/umfpack_solve_example.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/umfpack_solve_example.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/umfpack_solve_example.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 25.6769230769, "max_line_length": 89, "alphanum_fraction": 0.5380467346, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6143857734470608}}
{"text": "#include \"em_gmm.h\"\n\n#include <cassert>\n#include <iostream>\n#include <vector>\n#include <random>\n\n//< Uncomment the line below to utilize Math Kernel Library\n//#define EIGEN_USE_MKL_ALL\n#include <Eigen/Eigen>\n\nnamespace {\n    //< Constant for numerical stability\n    const float eps_covariance = 1e-10;\n    const float eps_zero = 1e-10;\n    const float eps_log_negative_inf = -1e30;\n    const float eps_convergence = 1e-4;\n    const float eps_regularize = 1e-30;\n}\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Matrix<float, Dynamic, Dynamic, RowMajor> RowMatrixXf;\n\ninline float log_sum(const float& log_a, const float& log_b) {\n    return log_a < log_b ?\n         (log_b + std::log (1.0 + std::exp (log_a - log_b)))\n         : (log_a + std::log (1.0 + std::exp (log_b - log_a)));\n}\n\nvoid calculate_log_prob_spherical(\n        const RowMatrixXf& mat_data, \n        const VectorXf& vec_nrm2_pts,\n        const RowVectorXf& vec_weights,\n        const RowMatrixXf& mat_means,\n        const RowMatrixXf& mat_diag_covs,\n        RowMatrixXf& mat_log_probs) {\n\n    const long num_modes = mat_means.rows();\n    const long num_pts = mat_data.rows();\n    const long dim = mat_data.cols();\n\n    assert( vec_nrm2_pts.rows() == num_pts &&\n            vec_weights.cols() == num_modes && \n            mat_means.cols() == dim &&\n            mat_diag_covs.rows() == num_modes &&\n            mat_diag_covs.cols() == dim &&\n            mat_log_probs.rows() == num_pts && \n            mat_log_probs.cols() == num_modes );\n\n    RowVectorXf vec_nrm2_centers(num_modes);\n    for (long c = 0; c < num_modes; c++) {\n        vec_nrm2_centers(c) = mat_means.row(c).squaredNorm();\n    }\n\n    mat_log_probs.noalias() = mat_data * mat_means.transpose();\n    mat_log_probs *= -2;\n    #pragma omp parallel for\n    for (long c = 0; c < num_modes; c++) {\n        mat_log_probs.col(c) += vec_nrm2_pts;\n    }\n    #pragma omp parallel for\n    for (long n = 0; n < num_pts; n++) {\n        mat_log_probs.row(n) += vec_nrm2_centers;\n    }\n\n    #pragma omp parallel for\n    for (long c = 0; c < num_modes; c++) {\n        const float cov = mat_diag_covs(c,0);\n        const float c1 = log(vec_weights(c) + eps_regularize) \n            - 0.5*dim*log(2*M_PI) - 0.5*dim*log(cov); \n        const float c2 = -0.5f/cov;\n        mat_log_probs.col(c) *= c2;\n        mat_log_probs.col(c) = (mat_log_probs.col(c).array() + c1).matrix();\n    } \n}\n\nvoid calculate_log_prob_diagonal(\n        const RowMatrixXf& mat_data, \n        const RowVectorXf& vec_weights,\n        const RowMatrixXf& mat_means,\n        const RowMatrixXf& mat_diag_covs,\n        RowMatrixXf& mat_log_probs) {\n\n    const long num_modes = mat_means.rows();\n    const long num_pts = mat_data.rows();\n    const long dim = mat_data.cols();\n\n    assert( vec_weights.cols() == num_modes && \n            mat_means.cols() == dim &&\n            mat_diag_covs.rows() == num_modes &&\n            mat_diag_covs.cols() == dim &&\n            mat_log_probs.rows() == num_pts && \n            mat_log_probs.cols() == num_modes);\n\n    const float c0(-0.5f*dim*log(2*M_PI));\n    RowVectorXf vec_c1_cov_prod(num_modes);\n    for (long c = 0; c < num_modes; c++) {\n        vec_c1_cov_prod(c) = -0.5f*(mat_diag_covs.row(c).array().log().sum());\n    }\n\n    #pragma omp parallel for\n    for (long n = 0; n < num_pts; n++) {\n        RowVectorXf vec_data = mat_data.row(n);\n        for (long c = 0; c < num_modes; c++) {\n            RowVectorXf delta = (vec_data - mat_means.row(c));\n            mat_log_probs(n,c) = -0.5f*(delta.array()*mat_diag_covs.row(c).array().cwiseInverse()).matrix().dot(delta)\n                + c0 + vec_c1_cov_prod(c);\n        }\n    }\n}\n\nvoid em_gmm(\n        const float *data, \n        const long num_pts, \n        const long dim,\n        const int num_modes,\n        float *means, \n        float *diag_covs,\n        float *weights,\n        bool should_fit_spherical_gaussian) {\n\n    using namespace std;\n\n    assert (num_modes < num_pts && \"Not enough data for em\");\n\n    RowVectorXf vec_eps_regularize(num_modes);\n    vec_eps_regularize.fill(eps_regularize);\n\n    //< K-means to initialize the EM\n    std::vector<int> labels(num_pts, -1);\n\n    Map<const RowMatrixXf> mat_data(data, num_pts, dim);\n    Map<RowMatrixXf> mat_means(means, num_modes, dim);\n    Map<RowMatrixXf> mat_diag_covs(diag_covs, num_modes, dim);\n    Map<RowVectorXf> vec_weights(weights, num_modes);\n\n    //< Random init\n    random_device rd;\n    default_random_engine gen(rd());\n    uniform_int_distribution<long> kmeans_seed_dist(0, num_pts-1);\n    vector<long> center_indices(num_modes);\n    generate(center_indices.begin(), center_indices.end(), [&]{ \n        return kmeans_seed_dist(gen);\n    });\n    #pragma omp parallel for\n    for (int c = 0; c < num_modes; c++) {\n        long n = center_indices[c];\n        mat_means.row(c) = mat_data.row(n);\n    }\n\n    //< kmeans convergence\n    const int max_kmeans_iterations = 20;\n    bool is_converged = false;\n    float eps(0.0f);\n\n    RowMatrixXf mat_distance(num_pts, num_modes);\n\n    VectorXf vec_nrm2_pts(num_pts);\n    #pragma omp parallel for\n    for (long r = 0; r < num_pts; r++) {\n        vec_nrm2_pts(r) = mat_data.row(r).squaredNorm();\n    }\n\n    RowVectorXf vec_nrm2_centers(num_modes);\n\n    //< K-means \n    RowMatrixXf mat_saved_means(num_modes, dim);\n    RowVectorXf assigned_counts(num_modes);\n\n    int iterations = 0;\n    while ((iterations++ < max_kmeans_iterations) && !is_converged) {\n\n        //< save previous centers\n        mat_saved_means = mat_means;\n\n        //< calculate point to center L2 distance\n        //< (X - C)^2 = X^2 + C^2 - 2*X*C\n        #pragma omp parallel for\n        for (int c = 0; c < num_modes; c++) {\n            vec_nrm2_centers(c) = mat_means.row(c).squaredNorm();\n        }\n        mat_distance.noalias() = mat_data * mat_means.transpose();\n        mat_distance *= -2;\n        #pragma omp parallel for\n        for (long c = 0; c < num_modes; c++) {\n            mat_distance.col(c) += vec_nrm2_pts;\n        }\n        \n        //< nearest centers along one column\n        #pragma omp parallel for\n        for (long n = 0; n < num_pts; n++) {\n            mat_distance.row(n) += vec_nrm2_centers;\n            mat_distance.row(n).minCoeff(&labels[n]);\n        }\n\n        assigned_counts.fill(0.0f);\n        for (long n = 0; n < num_pts; n++) {\n            long c = labels[n];\n            if (assigned_counts(c) < 1e-3) {\n                mat_means.row(c) = mat_data.row(n);\n            } else {\n                mat_means.row(c) += mat_data.row(n);\n            }\n            assigned_counts(c) += 1.0f;\n        }\n\n        #pragma omp parallel for\n        for (long c = 0; c < num_modes; c++) {\n            if (assigned_counts(c) > 1e-3) {\n                mat_means.row(c) /= assigned_counts(c);\n            } \n        }\n\n        //< evaluation\n        const float prev_eps = eps;\n        eps = (mat_saved_means - mat_means).norm();\n        is_converged = (eps < eps_convergence);\n        cout << \"kmeans \" << \"[\" << iterations << \"] \" << prev_eps << \" \" << eps << endl;\n    } \n\n    //< covariances and weights\n    vec_weights = assigned_counts / (float)num_pts;\n    mat_diag_covs.fill(0);\n    for (long n = 0; n < num_pts; n++) {\n        long c = labels[n];\n        mat_diag_covs.row(c) += mat_data.row(n).array().square().matrix();\n    }\n    for (long c = 0; c < num_modes; c++) {\n        if (assigned_counts(c) > 1e-3) {\n            mat_diag_covs.row(c) /= assigned_counts(c);\n            mat_diag_covs.row(c) -= mat_means.row(c).array().square().matrix();\n        } \n    }\n\n    if (should_fit_spherical_gaussian) {\n        for (int c = 0; c < num_modes; c++) {\n            const float spherical_val = std::max(mat_diag_covs.row(c).sum()/dim, eps_covariance);\n            mat_diag_covs.row(c).fill(spherical_val);\n        }\n    }\n\n    //< EM\n    RowMatrixXf& mat_log_probs = mat_distance;\n\n    const int max_em_iterations = 20;\n    is_converged = false; //< use weights as approximated indicator\n    float expectation(std::numeric_limits<float>::lowest());\n\n    RowVectorXf vec_evals(num_pts);\n    RowVectorXf vec_log_sum_probs(num_pts);\n    RowVectorXf vec_occup_eN(num_modes);\n    RowMatrixXf mat_occup_eX(num_modes, dim);\n    RowMatrixXf mat_occup_eX2(num_modes, dim);\n\n    iterations = 0;\n    while ((iterations++ < max_em_iterations) && !is_converged) {\n\n        //< calculate log probabilities\n        if (should_fit_spherical_gaussian) {\n            calculate_log_prob_spherical(mat_data, vec_nrm2_pts, vec_weights, mat_means, mat_diag_covs, mat_log_probs);\n        } else {\n            calculate_log_prob_diagonal(mat_data, vec_weights, mat_means, mat_diag_covs, mat_log_probs);\n        }\n\n        #pragma omp parallel for\n        for (long n = 0; n < num_pts; n++) {\n            vec_log_sum_probs(n) = mat_log_probs(n,0);\n            for (long c = 1; c < num_modes; c++) {\n                if (mat_log_probs(n,c) > eps_log_negative_inf) {\n                    vec_log_sum_probs(n) = log_sum(vec_log_sum_probs(n), mat_log_probs(n,c));\n                }\n            }\n        }\n\n        #pragma omp parallel for\n        for (long n = 0; n < num_pts; n++) {\n            RowVectorXf soft_count = (mat_log_probs.row(n).array() - vec_log_sum_probs(n)).exp().matrix();\n            vec_evals(n) = 0;\n            for (long c = 0; c < num_modes; c++) {\n                if (soft_count(c) > eps_zero) {\n                    vec_evals(n) += mat_log_probs(n,c)*soft_count(c);\n                }\n            }\n            mat_log_probs.row(n) = soft_count;\n        }\n\n        ////< Occupation counts\n        #pragma omp parallel for\n        for (long c = 0; c < num_modes; c++) {\n            vec_occup_eN(c) = mat_log_probs.col(c).sum();\n        }\n\n        mat_occup_eX = mat_log_probs.transpose() * mat_data;\n        //< M-Step: update means/diag_covs/weights\n        vec_weights = vec_occup_eN / vec_occup_eN.sum();\n        vec_occup_eN += vec_eps_regularize;\n        #pragma omp parallel for\n        for (int c = 0; c < num_modes; c++) {\n            if (vec_weights(c) > eps_zero) {\n                mat_means.row(c) = mat_occup_eX.row(c)/vec_occup_eN(c);\n            }\n        }\n\n        VectorXf vec_sum_occup_nrm2_pts = mat_log_probs.transpose() * vec_nrm2_pts;\n        if (should_fit_spherical_gaussian) {\n            for (int c = 0; c < num_modes; c++) {\n                const float spherical_val \n                    = (vec_sum_occup_nrm2_pts(c) - 2*mat_means.row(c).dot(mat_occup_eX.row(c)) + vec_nrm2_centers(c)*vec_occup_eN(c))\n                    / (dim*vec_occup_eN(c));\n                mat_diag_covs.row(c).fill(spherical_val);\n            }\n        } else {\n            mat_occup_eX2 = mat_log_probs.transpose() * mat_data.array().square().matrix();\n            for (long c = 0; c < num_modes; c++) {\n                mat_diag_covs.row(c) = ((mat_occup_eX2.row(c)/vec_occup_eN(c)).array() - mat_means.row(c).array().square()).max(eps_covariance).matrix();\n            }\n        }\n\n        const float prev_expectation = expectation;\n        expectation = vec_evals.sum();\n        const float scale = 1e5;\n        const float delta = exp((expectation - prev_expectation)/scale) - 1;\n        is_converged = (iterations > 0 && delta < eps_convergence);\n        cout << \"em \" << \"[\" << iterations << \"] \" << delta << \" \" << expectation << endl;\n    } //< em LOOP END\n    \n} //< function: fit_mixture_model\n\nvoid likelihood_gmm(\n        const float *data, \n        const long num_pts, \n        const long dim,\n        const int num_modes,\n        const float *means, \n        const float *diag_covs,\n        const float *weights,\n        float *log_probs, //< num_pts x num_modes\n        bool is_spherical_gaussian) {\n\n    Map<const RowMatrixXf> mat_data(data, num_pts, dim);\n    Map<const RowMatrixXf> mat_means(means, num_modes, dim);\n    Map<const RowMatrixXf> mat_diag_covs(diag_covs, num_modes, dim);\n    Map<const RowVectorXf> vec_weights(weights, num_modes);\n\n    VectorXf vec_nrm2_pts(num_pts);\n    #pragma omp parallel for\n    for (long r = 0; r < num_pts; r++) {\n        vec_nrm2_pts(r) = mat_data.row(r).squaredNorm();\n    }\n\n    RowVectorXf vec_nrm2_centers(num_modes);\n\n    RowMatrixXf mat_log_probs(num_pts, num_modes);\n\n    //< calculate log probabilities\n    if (is_spherical_gaussian) {\n        calculate_log_prob_spherical(mat_data, vec_nrm2_pts, vec_weights, mat_means, mat_diag_covs, mat_log_probs);\n    } else {\n        calculate_log_prob_diagonal(mat_data, vec_weights, mat_means, mat_diag_covs, mat_log_probs);\n    }\n\n    std::copy(mat_log_probs.data(), mat_log_probs.data() + num_pts*num_modes, log_probs);\n}\n", "meta": {"hexsha": "f031629554ecbf7d8005791f4b36fc9c6ea5f1d8", "size": 12622, "ext": "cc", "lang": "C++", "max_stars_repo_path": "em_gmm.cc", "max_stars_repo_name": "CVLearner/Mixture-of-Gaussians", "max_stars_repo_head_hexsha": "e274535188953708fd8f821e0154d788d49bee53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T18:42:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-11T11:51:38.000Z", "max_issues_repo_path": "em_gmm.cc", "max_issues_repo_name": "CVLearner/Mixture-of-Gaussians", "max_issues_repo_head_hexsha": "e274535188953708fd8f821e0154d788d49bee53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-03-13T19:28:54.000Z", "max_issues_repo_issues_event_max_datetime": "2015-03-17T04:03:02.000Z", "max_forks_repo_path": "em_gmm.cc", "max_forks_repo_name": "CVLearner/Mixture-of-Gaussians", "max_forks_repo_head_hexsha": "e274535188953708fd8f821e0154d788d49bee53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-01-22T07:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-19T06:23:05.000Z", "avg_line_length": 34.4863387978, "max_line_length": 153, "alphanum_fraction": 0.5942006021, "num_tokens": 3432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6143857623985791}}
{"text": "/*=============================================================================\r\n    Copyright (c) 2001-2003 Hartmut Kaiser\r\n    Copyright (c) 2002-2003 Joel de Guzman\r\n    http://spirit.sourceforge.net/\r\n\r\n    Use, modification and distribution is subject to the Boost Software\r\n    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n    http://www.boost.org/LICENSE_1_0.txt)\r\n=============================================================================*/\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  This sample shows, how to use Phoenix for implementing a\r\n//  simple (RPN style) calculator [ demonstrating phoenix ]\r\n//\r\n//  [ HKaiser 2001 ]\r\n//  [ JDG 6/29/2002 ]\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\n#include <boost/spirit/include/classic_core.hpp>\r\n#include <boost/spirit/include/classic_attribute.hpp>\r\n#include <boost/spirit/include/phoenix1_functions.hpp>\r\n#include <iostream>\r\n#include <string>\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\nusing namespace std;\r\nusing namespace BOOST_SPIRIT_CLASSIC_NS;\r\nusing namespace phoenix;\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Our RPN calculator grammar using phoenix to do the semantics\r\n//  The class 'RPNCalculator' implements a polish reverse notation\r\n//  calculator which is equivalent to the following YACC description.\r\n//\r\n//  exp:\r\n//        NUM           { $$ = $1;           }\r\n//      | exp exp '+'   { $$ = $1 + $2;      }\r\n//      | exp exp '-'   { $$ = $1 - $2;      }\r\n//      | exp exp '*'   { $$ = $1 * $2;      }\r\n//      | exp exp '/'   { $$ = $1 / $2;      }\r\n//      | exp exp '^'   { $$ = pow ($1, $2); }  /* Exponentiation */\r\n//      | exp 'n'       { $$ = -$1;          }  /* Unary minus */\r\n//      ;\r\n//\r\n//  The different notation results from the requirement of LL parsers not to\r\n//  allow left recursion in their grammar (would lead to endless recursion).\r\n//  Therefore the left recursion in the YACC script before is transformated\r\n//  into iteration. To some, this is less intuitive, but once you get used\r\n//  to it, it's very easy to follow.\r\n//\r\n//  Note:   The top rule propagates the expression result (value) upwards\r\n//          to the calculator grammar self.val closure member which is\r\n//          then visible outside the grammar (i.e. since self.val is the\r\n//          member1 of the closure, it becomes the attribute passed by\r\n//          the calculator to an attached semantic action. See the\r\n//          driver code that uses the calculator below).\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nstruct pow_\r\n{\r\n    template <typename X, typename Y>\r\n    struct result { typedef X type; };\r\n\r\n    template <typename X, typename Y>\r\n    X operator()(X x, Y y) const\r\n    {\r\n        using namespace std;\r\n        return pow(x, y);\r\n    }\r\n};\r\n\r\n//  Notice how power(x, y) is lazily implemented using Phoenix function.\r\nfunction<pow_> power;\r\n\r\nstruct calc_closure : BOOST_SPIRIT_CLASSIC_NS::closure<calc_closure, double, double>\r\n{\r\n    member1 x;\r\n    member2 y;\r\n};\r\n\r\nstruct calculator : public grammar<calculator, calc_closure::context_t>\r\n{\r\n    template <typename ScannerT>\r\n    struct definition {\r\n\r\n        definition(calculator const& self)\r\n        {\r\n            top = expr                      [self.x = arg1];\r\n            expr =\r\n                real_p                      [expr.x = arg1]\r\n                >> *(\r\n                        expr                [expr.y = arg1]\r\n                        >>  (\r\n                                ch_p('+')   [expr.x += expr.y]\r\n                            |   ch_p('-')   [expr.x -= expr.y]\r\n                            |   ch_p('*')   [expr.x *= expr.y]\r\n                            |   ch_p('/')   [expr.x /= expr.y]\r\n                            |   ch_p('^')   [expr.x = power(expr.x, expr.y)]\r\n                            )\r\n                    |   ch_p('n')           [expr.x = -expr.x]\r\n                    )\r\n                ;\r\n        }\r\n\r\n        typedef rule<ScannerT, calc_closure::context_t> rule_t;\r\n        rule_t expr;\r\n        rule<ScannerT> top;\r\n\r\n        rule<ScannerT> const&\r\n        start() const { return top; }\r\n    };\r\n};\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Main program\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\nint\r\nmain()\r\n{\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"\\t\\tExpression parser using Phoenix...\\n\\n\";\r\n    cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    cout << \"Type an expression...or [q or Q] to quit\\n\\n\";\r\n\r\n    calculator calc;    //  Our parser\r\n\r\n    string str;\r\n    while (getline(cin, str))\r\n    {\r\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\r\n            break;\r\n\r\n        double n = 0;\r\n        parse_info<> info = parse(str.c_str(), calc[var(n) = arg1], space_p);\r\n\r\n        //  calc[var(n) = arg1] invokes the calculator and extracts\r\n        //  the result of the computation. See calculator grammar\r\n        //  note above.\r\n\r\n        if (info.full)\r\n        {\r\n            cout << \"-------------------------\\n\";\r\n            cout << \"Parsing succeeded\\n\";\r\n            cout << \"result = \" << n << endl;\r\n            cout << \"-------------------------\\n\";\r\n        }\r\n        else\r\n        {\r\n            cout << \"-------------------------\\n\";\r\n            cout << \"Parsing failed\\n\";\r\n            cout << \"stopped at: \\\": \" << info.stop << \"\\\"\\n\";\r\n            cout << \"-------------------------\\n\";\r\n        }\r\n    }\r\n\r\n    cout << \"Bye... :-) \\n\\n\";\r\n    return 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "ca08a7ef905424c08a4f3d6217aca75427119a02", "size": 5836, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/spirit/classic/example/fundamental/more_calculators/rpn_calc.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/spirit/classic/example/fundamental/more_calculators/rpn_calc.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/spirit/classic/example/fundamental/more_calculators/rpn_calc.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 35.5853658537, "max_line_length": 85, "alphanum_fraction": 0.4239204935, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6143857608688822}}
{"text": "// M\u00e9todo da bisse\u00e7\u00e3o para obter raizes de equa\u00e7\u00f5es\n#include <iostream>\n#include <boost/math/tools/roots.hpp>\n\nusing namespace std;\nusing namespace boost::math::tools;\n\nstruct fn {\n    double operator() (double x) {\n        return 2 * x - 1;\n    }\n};\n\nstruct condition {\n    double m_limit;\n    condition(double limit) : m_limit(limit) { }\n    double operator() (double min, double max) {\n        return abs(min - max) <= m_limit;\n    }\n};\n\nint main() {\n    std::pair<double, double> result = bisect(fn(), -1.0, 1.0, condition(0.0001));\n\n    double root = (result.first + result.second) / 2;\n\n    cout << \"Raiz: \" << root << endl;\n\n    return 0;\n}", "meta": {"hexsha": "ab9d8c0a4eb44ce054db0d3b702a3e5e0c7267e8", "size": 647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bisect-roots/main.cpp", "max_stars_repo_name": "dayanyrec/study-boost", "max_stars_repo_head_hexsha": "8f5f9d1880c4e4601d8a468f77012be1f1a6ac9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bisect-roots/main.cpp", "max_issues_repo_name": "dayanyrec/study-boost", "max_issues_repo_head_hexsha": "8f5f9d1880c4e4601d8a468f77012be1f1a6ac9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bisect-roots/main.cpp", "max_forks_repo_name": "dayanyrec/study-boost", "max_forks_repo_head_hexsha": "8f5f9d1880c4e4601d8a468f77012be1f1a6ac9d", "max_forks_repo_licenses": ["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.5666666667, "max_line_length": 82, "alphanum_fraction": 0.6136012365, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6143349325243422}}
{"text": "#ifndef HAMILTONIANS_XXX_HPP\n#define HAMILTONIANS_XXX_HPP\n#include <Eigen/Eigen>\n\nclass XXX\n{\nprivate:\n\tint n_;\n\npublic:\n\n\tXXX(int n)\n\t\t: n_(n)\n\t{\n\t}\n\t\n\ttemplate<class State>\n\ttypename State::ValueType operator()(const State& smp) const\n\t{\n\t\ttypename State::ValueType s = 0.0;\n\t\t//Nearest-neighbor\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tdouble yysign = smp.sigmaAt(i)*smp.sigmaAt((i+1)%n_);\n\t\t\ts += yysign; //zz\n\t\t\ts += (1.0-yysign)*smp.ratio(i, (i+1)%n_); //xx+yy\n\t\t}\n\t\treturn s;\n\t}\n\n\tstd::map<uint32_t, double> operator()(uint32_t col) const\n\t{\n\t\tstd::map<uint32_t,double> res;\n\t\tfor(int i = 0; i < n_; i++)\n\t\t{\n\t\t\tint b1 = (col >> i) & 1;\n\t\t\tint b2 = (col >> ((i+1)%n_)) & 1;\n\t\t\tint sgn = (1-2*b1)*(1-2*b2);\n\t\t\tlong long int x = (1 << i) | (1 << ((i+1)%(n_)));\n\t\t\tres[col ^ x] += 1-sgn;\n\t\t\tres[col] += sgn;\n\t\t}\n\t\treturn res;\n\t}\n};\n#endif//HAMILTONIANS_XXX_HPP\n", "meta": {"hexsha": "691cd449ce34d402ff87bd8a6178255af410cbaa", "size": 861, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Hamiltonians/XXX.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Hamiltonians/XXX.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Hamiltonians/XXX.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.3191489362, "max_line_length": 61, "alphanum_fraction": 0.5702671312, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6143349103955724}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n  ArrayXXf  m(2,2);\n  \n  //assign some values coefficient by coefficient\n  m(0,0) = 1.0; m(0,1) = 2.0;\n  m(1,0) = 3.0; m(1,1) = 4.0;\n  \n  //print values to standard output\n  cout << m << endl << endl;\n \n  // using the comma-initializer is also allowed\n  m << 1.0,2.0,\n       3.0,4.0;\n     \n  //print values to standard output\n  cout << m << endl;\n}\n", "meta": {"hexsha": "812ba61a4989a1c2f64bde779534f2065bf77783", "size": 451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_ArrayClass_accessors.cpp", "max_stars_repo_name": "dailysoap/CSMM.104x", "max_stars_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_ArrayClass_accessors.cpp", "max_issues_repo_name": "dailysoap/CSMM.104x", "max_issues_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_ArrayClass_accessors.cpp", "max_forks_repo_name": "dailysoap/CSMM.104x", "max_forks_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 18.04, "max_line_length": 49, "alphanum_fraction": 0.5942350333, "num_tokens": 162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7931059585194573, "lm_q1q2_score": 0.6143266890973482}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n#include <functional>\n#include <iostream>\n#include <vector>\n\n#include <graphblas/graphblas.hpp>\n\nusing namespace grb;\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE algebra_semiring_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(arithmetic_semiring_test)\n{\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<double>().zero(), 0.0);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<double>().add(-2., 1.), -1.0);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<double>().mult(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<float>().zero(), 0.0f);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<float>().add(-2.f, 1.f), -1.0f);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<float>().mult(-2.f, 1.f), -2.0f);\n\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint64_t>().zero(), 0UL);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint64_t>().add(2UL, 1UL), 3UL);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint64_t>().mult(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint32_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint32_t>().add(2U, 1U), 3U);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint32_t>().mult(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint16_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint16_t>().add(2U, 1U), 3U);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint16_t>().mult(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint8_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint8_t>().add(2U, 1U), 3U);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<uint8_t>().mult(2U, 1U), 2U);\n\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int64_t>().zero(), 0L);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int64_t>().add(-2L, 1L), -1L);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int64_t>().mult(-2L, 1L), -2L);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int32_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int32_t>().add(-2, 1), -1);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int32_t>().mult(-2, 1), -2);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int16_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int16_t>().add(-2, 1), -1);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int16_t>().mult(-2, 1), -2);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int8_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int8_t>().add(-2, 1), -1);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<int8_t>().mult(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<bool>().zero(), false);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<bool>().add(false, false), false);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<bool>().add(false, true), true);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<bool>().mult(false, true), false);\n    BOOST_CHECK_EQUAL(ArithmeticSemiring<bool>().mult(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(min_plus_semiring_test)\n{\n    BOOST_CHECK_EQUAL(MinPlusSemiring<double>().zero(),\n                      std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MinPlusSemiring<double>().add(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<double>().add(2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<double>().mult(-2., 1.), -1.0);\n\n    BOOST_CHECK_EQUAL(MinPlusSemiring<float>().zero(),\n                      std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MinPlusSemiring<float>().add(-2.f, 1.f), -2.0f);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<float>().add(2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<float>().mult(-2.f, 1.f), -1.0f);\n\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint64_t>().zero(),\n                      std::numeric_limits<uint64_t>::max());\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint64_t>().add(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint64_t>().add(2UL, 3UL), 2UL);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint64_t>().mult(2UL, 1UL), 3UL);\n\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint32_t>().zero(),\n                      std::numeric_limits<uint32_t>::max());\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint32_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint32_t>().add(2U, 3U), 2U);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint32_t>().mult(2U, 1U), 3U);\n\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint16_t>().zero(),\n                      std::numeric_limits<uint16_t>::max());\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint16_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint16_t>().add(2U, 3U), 2U);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint16_t>().mult(2U, 1U), 3U);\n\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint8_t>().zero(),\n                      std::numeric_limits<uint8_t>::max());\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint8_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint8_t>().add(2U, 3U), 2U);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<uint8_t>().mult(2U, 1U), 3U);\n\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int64_t>().zero(),\n                      std::numeric_limits<int64_t>::max());\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int64_t>().add(-2L, 1L), -2L);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int64_t>().add(2L, -1L), -1L);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int64_t>().mult(-2L, 1L), -1L);\n\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int32_t>().zero(),\n                      std::numeric_limits<int32_t>::max());\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int32_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int32_t>().add(2, -1), -1);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int32_t>().mult(-2, 1), -1);\n\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int16_t>().zero(),\n                      std::numeric_limits<int16_t>::max());\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int16_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int16_t>().add(2, -1), -1);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int16_t>().mult(-2, 1), -1);\n\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int8_t>().zero(),\n                      std::numeric_limits<int8_t>::max());\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int8_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int8_t>().add(2, -1), -1);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<int8_t>().mult(-2, 1), -1);\n\n    BOOST_CHECK_EQUAL(MinPlusSemiring<bool>().zero(), true);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<bool>().add(false, true), false);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<bool>().add(true, true), true);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<bool>().mult(false, false), false);\n    BOOST_CHECK_EQUAL(MinPlusSemiring<bool>().mult(true, false), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(max_plus_semiring_test)\n{\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<double>().zero(),\n                      -std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<double>().add(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<double>().add(2., 1.), 2.0);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<double>().mult(-2., 1.), -1.0);\n\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<float>().zero(),\n                      -std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<float>().add(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<float>().add(2.f, 1.f), 2.0f);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<float>().mult(-2.f, 1.f), -1.0f);\n\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint64_t>().zero(),\n                      std::numeric_limits<uint64_t>::min());\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint64_t>().add(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint64_t>().add(2UL, 3UL), 3UL);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint64_t>().mult(2UL, 1UL), 3UL);\n\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint32_t>().zero(),\n                      std::numeric_limits<uint32_t>::min());\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint32_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint32_t>().add(2U, 3U), 3U);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint32_t>().mult(2U, 1U), 3U);\n\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint16_t>().zero(),\n                      std::numeric_limits<uint16_t>::min());\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint16_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint16_t>().add(2U, 3U), 3U);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint16_t>().mult(2U, 1U), 3U);\n\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint8_t>().zero(),\n                      std::numeric_limits<uint8_t>::min());\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint8_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint8_t>().add(2U, 3U), 3U);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<uint8_t>().mult(2U, 1U), 3U);\n\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int64_t>().zero(),\n                      std::numeric_limits<int64_t>::min());\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int64_t>().add(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int64_t>().add(2L, -1L), 2L);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int64_t>().mult(-2L, 1L), -1L);\n\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int32_t>().zero(),\n                      std::numeric_limits<int32_t>::min());\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int32_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int32_t>().add(2, -1), 2);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int32_t>().mult(-2, 1), -1);\n\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int16_t>().zero(),\n                      std::numeric_limits<int16_t>::min());\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int16_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int16_t>().add(2, -1), 2);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int16_t>().mult(-2, 1), -1);\n\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int8_t>().zero(),\n                      std::numeric_limits<int8_t>::min());\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int8_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int8_t>().add(2, -1), 2);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<int8_t>().mult(-2, 1), -1);\n\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<bool>().zero(), false);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<bool>().add(false, true), true);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<bool>().add(true, true), true);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<bool>().mult(false, false), false);\n    BOOST_CHECK_EQUAL(MaxPlusSemiring<bool>().mult(true, false), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(min_times_semiring_test)\n{\n    BOOST_CHECK_EQUAL(MinTimesSemiring<double>().zero(),\n                      std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MinTimesSemiring<double>().add(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<double>().mult(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<float>().zero(),\n                      std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MinTimesSemiring<float>().add(-2.f, 1.f), -2.0f);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<float>().mult(-2.f, 1.f), -2.0f);\n\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint64_t>().zero(),\n                      std::numeric_limits<uint64_t>::max());\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint64_t>().add(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint64_t>().mult(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint32_t>().zero(),\n                      std::numeric_limits<uint32_t>::max());\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint32_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint32_t>().mult(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint16_t>().zero(),\n                      std::numeric_limits<uint16_t>::max());\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint16_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint16_t>().mult(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint8_t>().zero(),\n                      std::numeric_limits<uint8_t>::max());\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint8_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<uint8_t>().mult(2U, 1U), 2U);\n\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int64_t>().zero(),\n                      std::numeric_limits<int64_t>::max());\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int64_t>().add(-2L, 1L), -2L);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int64_t>().mult(-2L, 1L), -2L);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int32_t>().zero(),\n                      std::numeric_limits<int32_t>::max());\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int32_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int32_t>().mult(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int16_t>().zero(),\n                      std::numeric_limits<int16_t>::max());\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int16_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int16_t>().mult(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int8_t>().zero(),\n                      std::numeric_limits<int8_t>::max());\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int8_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<int8_t>().mult(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(MinTimesSemiring<bool>().zero(), true);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<bool>().add(false, false), false);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<bool>().add(false, true), false);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<bool>().mult(false, true), false);\n    BOOST_CHECK_EQUAL(MinTimesSemiring<bool>().mult(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(max_times_semiring_test)\n{\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<double>().zero(),\n                      -std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<double>().add(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<double>().mult(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<float>().zero(),\n                      -std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<float>().add(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<float>().mult(-2.f, 1.f), -2.0f);\n\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint64_t>().zero(), 0UL);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint64_t>().add(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint64_t>().mult(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint32_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint32_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint32_t>().mult(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint16_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint16_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint16_t>().mult(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint8_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint8_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<uint8_t>().mult(2U, 1U), 2U);\n\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int64_t>().zero(),\n                      std::numeric_limits<int64_t>::min());\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int64_t>().add(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int64_t>().mult(-2L, 1L), -2L);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int32_t>().zero(),\n                      std::numeric_limits<int32_t>::min());\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int32_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int32_t>().mult(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int16_t>().zero(),\n                      std::numeric_limits<int16_t>::min());\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int16_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int16_t>().mult(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int8_t>().zero(),\n                      std::numeric_limits<int8_t>::min());\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int8_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<int8_t>().mult(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<bool>().zero(), false);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<bool>().add(false, false), false);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<bool>().add(false, true), true);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<bool>().mult(false, true), false);\n    BOOST_CHECK_EQUAL(MaxTimesSemiring<bool>().mult(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(min_max_semiring_test)\n{\n    BOOST_CHECK_EQUAL(MinMaxSemiring<double>().zero(),\n                      std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MinMaxSemiring<double>().add(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<double>().mult(-2., 1.),  1.0);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<float>().zero(),\n                      std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MinMaxSemiring<float>().add(-2.f, 1.f), -2.0f);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<float>().mult(-2.f, 1.f),  1.0f);\n\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint64_t>().zero(),\n                      std::numeric_limits<uint64_t>::max());\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint64_t>().add(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint64_t>().mult(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint32_t>().zero(),\n                      std::numeric_limits<uint32_t>::max());\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint32_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint32_t>().mult(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint16_t>().zero(),\n                      std::numeric_limits<uint16_t>::max());\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint16_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint16_t>().mult(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint8_t>().zero(),\n                      std::numeric_limits<uint8_t>::max());\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint8_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<uint8_t>().mult(2U, 1U), 2U);\n\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int64_t>().zero(),\n                      std::numeric_limits<int64_t>::max());\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int64_t>().add(-2L, 1L),-2L);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int64_t>().mult(-2L, 1L),  1L);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int32_t>().zero(),\n                      std::numeric_limits<int32_t>::max());\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int32_t>().add(-2, 1),-2);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int32_t>().mult(-2, 1),  1);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int16_t>().zero(),\n                      std::numeric_limits<int16_t>::max());\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int16_t>().add(-2, 1),-2);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int16_t>().mult(-2, 1),  1);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int8_t>().zero(),\n                      std::numeric_limits<int8_t>::max());\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int8_t>().add(-2, 1),-2);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<int8_t>().mult(-2, 1),  1);\n\n    BOOST_CHECK_EQUAL(MinMaxSemiring<bool>().zero(), true);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<bool>().add(false, false), false);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<bool>().add(false, true), false);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<bool>().mult(false, true), true);\n    BOOST_CHECK_EQUAL(MinMaxSemiring<bool>().mult(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(max_min_semiring_test)\n{\n    BOOST_CHECK_EQUAL(MaxMinSemiring<double>().zero(),\n                      -std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MaxMinSemiring<double>().add(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<double>().mult(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<float>().zero(),\n                      -std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MaxMinSemiring<float>().add(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<float>().mult(-2.f, 1.f), -2.0f);\n\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint64_t>().zero(), 0UL);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint64_t>().add(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint64_t>().mult(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint32_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint32_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint32_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint16_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint16_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint16_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint8_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint8_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<uint8_t>().mult(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int64_t>().zero(),\n                      std::numeric_limits<int64_t>::min());\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int64_t>().add(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int64_t>().mult(-2L, 1L), -2L);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int32_t>().zero(),\n                      std::numeric_limits<int32_t>::min());\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int32_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int32_t>().mult(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int16_t>().zero(),\n                      std::numeric_limits<int16_t>::min());\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int16_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int16_t>().mult(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int8_t>().zero(),\n                      std::numeric_limits<int8_t>::min());\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int8_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<int8_t>().mult(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(MaxMinSemiring<bool>().zero(), false);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<bool>().add(false, false), false);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<bool>().add(false, true), true);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<bool>().mult(false, true), false);\n    BOOST_CHECK_EQUAL(MaxMinSemiring<bool>().mult(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(plus_min_semiring_test)\n{\n    BOOST_CHECK_EQUAL(PlusMinSemiring<double>().zero(), 0.);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<double>().add(-2., 1.), -1.0);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<double>().add(2., 1.), 3.0);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<double>().mult(-2., 1.), -2.0);\n\n    BOOST_CHECK_EQUAL(PlusMinSemiring<float>().zero(), 0.f);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<float>().add(-2.f, 1.f), -1.0f);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<float>().add(2.f, 1.f), 3.0f);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<float>().mult(-2.f, 1.f), -2.0f);\n\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint64_t>().zero(), 0UL);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint64_t>().add(2UL, 1UL), 3UL);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint64_t>().add(2UL, 3UL), 5UL);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint64_t>().mult(2UL, 1UL), 1UL);\n\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint32_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint32_t>().add(2U, 1U), 3U);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint32_t>().add(2U, 3U), 5U);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint32_t>().mult(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint16_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint16_t>().add(2U, 1U), 3U);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint16_t>().add(2U, 3U), 5U);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint16_t>().mult(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint8_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint8_t>().add(2U, 1U), 3U);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint8_t>().add(2U, 3U), 5U);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<uint8_t>().mult(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int64_t>().zero(), 0L);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int64_t>().add(-2L, 1L), -1L);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int64_t>().add(2L, -1L), 1L);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int64_t>().mult(-2L, 1L), -2L);\n\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int32_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int32_t>().add(-2, 1), -1);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int32_t>().add(2, -1), 1);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int32_t>().mult(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int16_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int16_t>().add(-2, 1), -1);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int16_t>().add(2, -1), 1);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int16_t>().mult(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int8_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int8_t>().add(-2, 1), -1);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int8_t>().add(2, -1), 1);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<int8_t>().mult(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().zero(), false);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().add(false, true), true);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().add(true, true), true);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().mult(false, false), false);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().mult(true, false), false);\n    BOOST_CHECK_EQUAL(PlusMinSemiring<bool>().mult(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(logical_semiring_test)\n{\n    BOOST_CHECK_EQUAL(LogicalSemiring<double>().zero(), 0.0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<double>().add(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<double>().add(0., 1.), 1.0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<double>().add(-2., 0.), 1.0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<double>().add(0., 0.), 0.0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<double>().mult(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<double>().mult(0., 1.), 0.0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<double>().mult(-2., 0.), 0.0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<double>().mult(0., 0.), 0.0);\n\n    BOOST_CHECK_EQUAL(LogicalSemiring<float>().zero(), 0.0f);\n    BOOST_CHECK_EQUAL(LogicalSemiring<float>().add(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(LogicalSemiring<float>().add(0.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(LogicalSemiring<float>().add(-2.f, 0.f), 1.0f);\n    BOOST_CHECK_EQUAL(LogicalSemiring<float>().add(0.f, 0.f), 0.0f);\n    BOOST_CHECK_EQUAL(LogicalSemiring<float>().mult(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(LogicalSemiring<float>().mult(0.f, 1.f), 0.0f);\n    BOOST_CHECK_EQUAL(LogicalSemiring<float>().mult(-2.f, 0.f), 0.0f);\n    BOOST_CHECK_EQUAL(LogicalSemiring<float>().mult(0.f, 0.f), 0.0f);\n\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().zero(), 0UL);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().add(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().add(2UL, 0UL), 1UL);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().add(0UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().add(0UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().mult(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().mult(2UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().mult(0UL, 1UL), 0UL);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint64_t>().mult(0UL, 0UL), 0UL);\n\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().add(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().add(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().add(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().mult(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().mult(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint32_t>().mult(0U, 0U), 0U);\n\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().add(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().add(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().add(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().mult(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().mult(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint16_t>().mult(0U, 0U), 0U);\n\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().add(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().add(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().add(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().mult(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().mult(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(LogicalSemiring<uint8_t>().mult(0U, 0U), 0U);\n\n    BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().zero(), 0L);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().add(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().add(-2L, 0L), 1L);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().add(0L, 1L), 1L);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().add(0L, 0L), 0L);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().mult(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().mult(-2L, 0L), 0L);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().mult(0L, 1L), 0L);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int64_t>().mult(0L, 0L), 0L);\n\n    BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().add(-2, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().add(0, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().add(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().mult(-2, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().mult(0, 1), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int32_t>().mult(0, 0), 0);\n\n    BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().add(-2, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().add(0, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().add(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().mult(-2, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().mult(0, 1), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int16_t>().mult(0, 0), 0);\n\n    BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().add(-2, 0), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().add(0, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().add(0, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().mult(-2, 0), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().mult(0, 1), 0);\n    BOOST_CHECK_EQUAL(LogicalSemiring<int8_t>().mult(0, 0), 0);\n\n    BOOST_CHECK_EQUAL(LogicalSemiring<bool>().zero(), false);\n    BOOST_CHECK_EQUAL(LogicalSemiring<bool>().add(false, false), false);\n    BOOST_CHECK_EQUAL(LogicalSemiring<bool>().add(false, true), true);\n    BOOST_CHECK_EQUAL(LogicalSemiring<bool>().add(true, false), true);\n    BOOST_CHECK_EQUAL(LogicalSemiring<bool>().add(true, true), true);\n    BOOST_CHECK_EQUAL(LogicalSemiring<bool>().mult(false, false), false);\n    BOOST_CHECK_EQUAL(LogicalSemiring<bool>().mult(false, true), false);\n    BOOST_CHECK_EQUAL(LogicalSemiring<bool>().mult(true, false), false);\n    BOOST_CHECK_EQUAL(LogicalSemiring<bool>().mult(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(and_or_semiring_test)\n{\n    BOOST_CHECK_EQUAL(AndOrSemiring<double>().zero(), 1.0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<double>().mult(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<double>().mult(0., 1.), 1.0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<double>().mult(-2., 0.), 1.0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<double>().mult(0., 0.), 0.0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<double>().add(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<double>().add(0., 1.), 0.0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<double>().add(-2., 0.), 0.0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<double>().add(0., 0.), 0.0);\n\n    BOOST_CHECK_EQUAL(AndOrSemiring<float>().zero(), 1.0f);\n    BOOST_CHECK_EQUAL(AndOrSemiring<float>().mult(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(AndOrSemiring<float>().mult(0.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(AndOrSemiring<float>().mult(-2.f, 0.f), 1.0f);\n    BOOST_CHECK_EQUAL(AndOrSemiring<float>().mult(0.f, 0.f), 0.0f);\n    BOOST_CHECK_EQUAL(AndOrSemiring<float>().add(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(AndOrSemiring<float>().add(0.f, 1.f), 0.0f);\n    BOOST_CHECK_EQUAL(AndOrSemiring<float>().add(-2.f, 0.f), 0.0f);\n    BOOST_CHECK_EQUAL(AndOrSemiring<float>().add(0.f, 0.f), 0.0f);\n\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().zero(), 1UL);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().mult(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().mult(2UL, 0UL), 1UL);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().mult(0UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().mult(0UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().add(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().add(2UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().add(0UL, 1UL), 0UL);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint64_t>().add(0UL, 0UL), 0UL);\n\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().zero(), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().mult(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().mult(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().mult(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().add(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().add(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint32_t>().add(0U, 0U), 0U);\n\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().zero(), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().mult(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().mult(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().mult(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().add(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().add(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint16_t>().add(0U, 0U), 0U);\n\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().zero(), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().mult(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().mult(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().mult(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().add(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().add(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(AndOrSemiring<uint8_t>().add(0U, 0U), 0U);\n\n    BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().zero(), 1L);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().mult(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().mult(-2L, 0L), 1L);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().mult(0L, 1L), 1L);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().mult(0L, 0L), 0L);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().add(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().add(-2L, 0L), 0L);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().add(0L, 1L), 0L);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int64_t>().add(0L, 0L), 0L);\n\n    BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().zero(), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().mult(-2, 0), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().mult(0, 1), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().mult(0, 0), 0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().add(-2, 0), 0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().add(0, 1), 0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int32_t>().add(0, 0), 0);\n\n    BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().zero(), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().mult(-2, 0), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().mult(0, 1), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().mult(0, 0), 0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().add(-2, 0), 0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().add(0, 1), 0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int16_t>().add(0, 0), 0);\n\n    BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().zero(), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().mult(-2, 0), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().mult(0, 1), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().mult(0, 0), 0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().add(-2, 0), 0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().add(0, 1), 0);\n    BOOST_CHECK_EQUAL(AndOrSemiring<int8_t>().add(0, 0), 0);\n\n    BOOST_CHECK_EQUAL(AndOrSemiring<bool>().zero(), true);\n    BOOST_CHECK_EQUAL(AndOrSemiring<bool>().mult(false, false), false);\n    BOOST_CHECK_EQUAL(AndOrSemiring<bool>().mult(false, true), true);\n    BOOST_CHECK_EQUAL(AndOrSemiring<bool>().mult(true, false), true);\n    BOOST_CHECK_EQUAL(AndOrSemiring<bool>().mult(true, true), true);\n    BOOST_CHECK_EQUAL(AndOrSemiring<bool>().add(false, false), false);\n    BOOST_CHECK_EQUAL(AndOrSemiring<bool>().add(false, true), false);\n    BOOST_CHECK_EQUAL(AndOrSemiring<bool>().add(true, false), false);\n    BOOST_CHECK_EQUAL(AndOrSemiring<bool>().add(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(xor_and_semiring_test)\n{\n    BOOST_CHECK_EQUAL(XorAndSemiring<double>().zero(), 0.0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<double>().add(-2., 1.), 0.0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<double>().add(0., 1.), 1.0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<double>().add(-2., 0.), 1.0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<double>().add(0., 0.), 0.0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<double>().mult(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<double>().mult(0., 1.), 0.0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<double>().mult(-2., 0.), 0.0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<double>().mult(0., 0.), 0.0);\n\n    BOOST_CHECK_EQUAL(XorAndSemiring<float>().zero(), 0.0f);\n    BOOST_CHECK_EQUAL(XorAndSemiring<float>().add(-2.f, 1.f), 0.0f);\n    BOOST_CHECK_EQUAL(XorAndSemiring<float>().add(0.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(XorAndSemiring<float>().add(-2.f, 0.f), 1.0f);\n    BOOST_CHECK_EQUAL(XorAndSemiring<float>().add(0.f, 0.f), 0.0f);\n    BOOST_CHECK_EQUAL(XorAndSemiring<float>().mult(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(XorAndSemiring<float>().mult(0.f, 1.f), 0.0f);\n    BOOST_CHECK_EQUAL(XorAndSemiring<float>().mult(-2.f, 0.f), 0.0f);\n    BOOST_CHECK_EQUAL(XorAndSemiring<float>().mult(0.f, 0.f), 0.0f);\n\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().zero(), 0UL);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().add(2UL, 1UL), 0UL);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().add(2UL, 0UL), 1UL);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().add(0UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().add(0UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().mult(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().mult(2UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().mult(0UL, 1UL), 0UL);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint64_t>().mult(0UL, 0UL), 0UL);\n\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().add(2U, 1U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().add(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().add(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().add(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().mult(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().mult(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint32_t>().mult(0U, 0U), 0U);\n\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().add(2U, 1U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().add(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().add(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().add(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().mult(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().mult(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint16_t>().mult(0U, 0U), 0U);\n\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().add(2U, 1U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().add(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().add(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().add(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().mult(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().mult(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(XorAndSemiring<uint8_t>().mult(0U, 0U), 0U);\n\n    BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().zero(), 0L);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().add(-2L, 1L), 0L);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().add(-2L, 0L), 1L);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().add(0L, 1L), 1L);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().add(0L, 0L), 0L);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().mult(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().mult(-2L, 0L), 0L);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().mult(0L, 1L), 0L);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int64_t>().mult(0L, 0L), 0L);\n\n    BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().add(-2, 1), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().add(-2, 0), 1);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().add(0, 1), 1);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().add(0, 0), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().mult(-2, 0), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().mult(0, 1), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int32_t>().mult(0, 0), 0);\n\n    BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().add(-2, 1), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().add(-2, 0), 1);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().add(0, 1), 1);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().add(0, 0), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().mult(-2, 0), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().mult(0, 1), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int16_t>().mult(0, 0), 0);\n\n    BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().zero(), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().add(-2, 1), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().add(-2, 0), 1);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().add(0, 1), 1);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().add(0, 0), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().mult(-2, 0), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().mult(0, 1), 0);\n    BOOST_CHECK_EQUAL(XorAndSemiring<int8_t>().mult(0, 0), 0);\n\n    BOOST_CHECK_EQUAL(XorAndSemiring<bool>().zero(), false);\n    BOOST_CHECK_EQUAL(XorAndSemiring<bool>().add(false, false), false);\n    BOOST_CHECK_EQUAL(XorAndSemiring<bool>().add(false, true), true);\n    BOOST_CHECK_EQUAL(XorAndSemiring<bool>().add(true, false), true);\n    BOOST_CHECK_EQUAL(XorAndSemiring<bool>().add(true, true), false);\n    BOOST_CHECK_EQUAL(XorAndSemiring<bool>().mult(false, false), false);\n    BOOST_CHECK_EQUAL(XorAndSemiring<bool>().mult(false, true), false);\n    BOOST_CHECK_EQUAL(XorAndSemiring<bool>().mult(true, false), false);\n    BOOST_CHECK_EQUAL(XorAndSemiring<bool>().mult(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(xnor_or_semiring_test)\n{\n    BOOST_CHECK_EQUAL(XnorOrSemiring<double>().zero(), 1.0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<double>().mult(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<double>().mult(0., 1.), 1.0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<double>().mult(-2., 0.), 1.0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<double>().mult(0., 0.), 0.0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<double>().add(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<double>().add(0., 1.), 0.0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<double>().add(-2., 0.), 0.0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<double>().add(0., 0.), 1.0);\n\n    BOOST_CHECK_EQUAL(XnorOrSemiring<float>().zero(), 1.0f);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<float>().mult(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<float>().mult(0.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<float>().mult(-2.f, 0.f), 1.0f);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<float>().mult(0.f, 0.f), 0.0f);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<float>().add(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<float>().add(0.f, 1.f), 0.0f);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<float>().add(-2.f, 0.f), 0.0f);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<float>().add(0.f, 0.f), 1.0f);\n\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().zero(), 1UL);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().mult(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().mult(2UL, 0UL), 1UL);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().mult(0UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().mult(0UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().add(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().add(2UL, 0UL), 0UL);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().add(0UL, 1UL), 0UL);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint64_t>().add(0UL, 0UL), 1UL);\n\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().zero(), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().mult(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().mult(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().mult(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().add(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().add(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint32_t>().add(0U, 0U), 1U);\n\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().zero(), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().mult(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().mult(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().mult(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().add(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().add(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint16_t>().add(0U, 0U), 1U);\n\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().zero(), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().mult(2U, 0U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().mult(0U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().mult(0U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().add(2U, 0U), 0U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().add(0U, 1U), 0U);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<uint8_t>().add(0U, 0U), 1U);\n\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().zero(), 1L);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().mult(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().mult(-2L, 0L), 1L);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().mult(0L, 1L), 1L);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().mult(0L, 0L), 0L);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().add(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().add(-2L, 0L), 0L);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().add(0L, 1L), 0L);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int64_t>().add(0L, 0L), 1L);\n\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().zero(), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().mult(-2, 0), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().mult(0, 1), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().mult(0, 0), 0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().add(-2, 0), 0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().add(0, 1), 0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int32_t>().add(0, 0), 1);\n\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().zero(), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().mult(-2, 0), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().mult(0, 1), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().mult(0, 0), 0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().add(-2, 0), 0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().add(0, 1), 0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int16_t>().add(0, 0), 1);\n\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().zero(), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().mult(-2, 0), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().mult(0, 1), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().mult(0, 0), 0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().add(-2, 0), 0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().add(0, 1), 0);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<int8_t>().add(0, 0), 1);\n\n    BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().zero(), true);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().mult(false, false), false);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().mult(false, true), true);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().mult(true, false), true);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().mult(true, true), true);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().add(false, false), true);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().add(false, true), false);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().add(true, false), false);\n    BOOST_CHECK_EQUAL(XnorOrSemiring<bool>().add(true, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(min_first_test)\n{\n    BOOST_CHECK_EQUAL(MinFirstSemiring<double>().zero(),\n                      std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MinFirstSemiring<double>().add(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<double>().add(2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<double>().mult(-2., 1.), -2.0);\n\n    BOOST_CHECK_EQUAL(MinFirstSemiring<float>().zero(),\n                      std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MinFirstSemiring<float>().add(-2.f, 1.f), -2.0f);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<float>().add(2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<float>().mult(-2.f, 1.f), -2.0f);\n\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint64_t>().zero(),\n                      std::numeric_limits<uint64_t>::max());\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint64_t>().add(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint64_t>().add(2UL, 3UL), 2UL);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint64_t>().mult(2UL, 1UL), 2UL);\n\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint32_t>().zero(),\n                      std::numeric_limits<uint32_t>::max());\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint32_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint32_t>().add(2U, 3U), 2U);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint32_t>().mult(2U, 1U), 2U);\n\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint16_t>().zero(),\n                      std::numeric_limits<uint16_t>::max());\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint16_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint16_t>().add(2U, 3U), 2U);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint16_t>().mult(2U, 1U), 2U);\n\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint8_t>().zero(),\n                      std::numeric_limits<uint8_t>::max());\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint8_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint8_t>().add(2U, 3U), 2U);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<uint8_t>().mult(2U, 1U), 2U);\n\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int64_t>().zero(),\n                      std::numeric_limits<int64_t>::max());\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int64_t>().add(-2L, 1L), -2L);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int64_t>().add(2L, -1L), -1L);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int64_t>().mult(-2L, 1L), -2L);\n\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int32_t>().zero(),\n                      std::numeric_limits<int32_t>::max());\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int32_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int32_t>().add(2, -1), -1);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int32_t>().mult(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int16_t>().zero(),\n                      std::numeric_limits<int16_t>::max());\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int16_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int16_t>().add(2, -1), -1);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int16_t>().mult(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int8_t>().zero(),\n                      std::numeric_limits<int8_t>::max());\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int8_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int8_t>().add(2, -1), -1);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<int8_t>().mult(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(MinFirstSemiring<bool>().zero(), true);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<bool>().add(false, true), false);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<bool>().add(true, true), true);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<bool>().mult(true, false), true);\n    BOOST_CHECK_EQUAL(MinFirstSemiring<bool>().mult(false, true), false);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(min_second_test)\n{\n    BOOST_CHECK_EQUAL(MinSecondSemiring<double>().zero(),\n                      std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MinSecondSemiring<double>().add(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<double>().add(2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<double>().mult(-2., 1.), 1.0);\n\n    BOOST_CHECK_EQUAL(MinSecondSemiring<float>().zero(),\n                      std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MinSecondSemiring<float>().add(-2.f, 1.f), -2.0f);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<float>().add(2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<float>().mult(-2.f, 1.f), 1.0f);\n\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint64_t>().zero(),\n                      std::numeric_limits<uint64_t>::max());\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint64_t>().add(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint64_t>().add(2UL, 3UL), 2UL);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint64_t>().mult(2UL, 1UL), 1UL);\n\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint32_t>().zero(),\n                      std::numeric_limits<uint32_t>::max());\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint32_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint32_t>().add(2U, 3U), 2U);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint32_t>().mult(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint16_t>().zero(),\n                      std::numeric_limits<uint16_t>::max());\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint16_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint16_t>().add(2U, 3U), 2U);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint16_t>().mult(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint8_t>().zero(),\n                      std::numeric_limits<uint8_t>::max());\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint8_t>().add(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint8_t>().add(2U, 3U), 2U);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<uint8_t>().mult(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int64_t>().zero(),\n                      std::numeric_limits<int64_t>::max());\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int64_t>().add(-2L, 1L), -2L);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int64_t>().add(2L, -1L), -1L);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int64_t>().mult(-2L, 1L), 1L);\n\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int32_t>().zero(),\n                      std::numeric_limits<int32_t>::max());\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int32_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int32_t>().add(2, -1), -1);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int32_t>().mult(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int16_t>().zero(),\n                      std::numeric_limits<int16_t>::max());\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int16_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int16_t>().add(2, -1), -1);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int16_t>().mult(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int8_t>().zero(),\n                      std::numeric_limits<int8_t>::max());\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int8_t>().add(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int8_t>().add(2, -1), -1);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<int8_t>().mult(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(MinSecondSemiring<bool>().zero(), true);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<bool>().add(false, true), false);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<bool>().add(true, true), true);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<bool>().mult(true, false), false);\n    BOOST_CHECK_EQUAL(MinSecondSemiring<bool>().mult(false, true), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(max_first_test)\n{\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<double>().zero(),\n                      -std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<double>().add(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<double>().mult(-2., 1.), -2.0);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<float>().zero(),\n                      -std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<float>().add(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<float>().mult(-2.f, 1.f), -2.0f);\n\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint64_t>().zero(), 0UL);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint64_t>().add(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint64_t>().mult(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint32_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint32_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint32_t>().mult(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint16_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint16_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint16_t>().mult(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint8_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint8_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<uint8_t>().mult(2U, 1U), 2U);\n\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int64_t>().zero(),\n                      std::numeric_limits<int64_t>::min());\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int64_t>().add(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int64_t>().mult(-2L, 1L), -2L);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int32_t>().zero(),\n                      std::numeric_limits<int32_t>::min());\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int32_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int32_t>().mult(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int16_t>().zero(),\n                      std::numeric_limits<int16_t>::min());\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int16_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int16_t>().mult(-2, 1), -2);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int8_t>().zero(),\n                      std::numeric_limits<int8_t>::min());\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int8_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<int8_t>().mult(-2, 1), -2);\n\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<bool>().zero(), false);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<bool>().add(false, false), false);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<bool>().add(false, true), true);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<bool>().mult(false, true), false);\n    BOOST_CHECK_EQUAL(MaxFirstSemiring<bool>().mult(true, false), true);\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(max_second_test)\n{\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<double>().zero(),\n                      -std::numeric_limits<double>::infinity());\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<double>().add(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<double>().mult(-2., 1.), 1.0);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<float>().zero(),\n                      -std::numeric_limits<float>::infinity());\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<float>().add(-2.f, 1.f), 1.0f);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<float>().mult(-2.f, 1.f), 1.0f);\n\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint64_t>().zero(), 0UL);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint64_t>().add(2UL, 1UL), 2UL);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint64_t>().mult(2UL, 1UL), 1UL);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint32_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint32_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint32_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint16_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint16_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint16_t>().mult(2U, 1U), 1U);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint8_t>().zero(), 0U);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint8_t>().add(2U, 1U), 2U);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<uint8_t>().mult(2U, 1U), 1U);\n\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int64_t>().zero(),\n                      std::numeric_limits<int64_t>::min());\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int64_t>().add(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int64_t>().mult(-2L, 1L), 1L);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int32_t>().zero(),\n                      std::numeric_limits<int32_t>::min());\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int32_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int32_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int16_t>().zero(),\n                      std::numeric_limits<int16_t>::min());\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int16_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int16_t>().mult(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int8_t>().zero(),\n                      std::numeric_limits<int8_t>::min());\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int8_t>().add(-2, 1), 1);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<int8_t>().mult(-2, 1), 1);\n\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<bool>().zero(), false);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<bool>().add(false, false), false);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<bool>().add(false, true), true);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<bool>().mult(false, true), true);\n    BOOST_CHECK_EQUAL(MaxSecondSemiring<bool>().mult(true, false), false);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "43128856c2571e20dd32511587845a431b72cdd9", "size": 66711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_algebra_semiring.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_algebra_semiring.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_algebra_semiring.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 55.9186923722, "max_line_length": 80, "alphanum_fraction": 0.6806673562, "num_tokens": 20740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6142920275535022}}
{"text": "/***********************************************************************\nThis file is part of the librjmcmc project source files.\n\nCopyright : Institut Geographique National (2008-2012)\nContributors : Mathieu Br\u00e9dif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef UNIFORM_DISTRIBUTION_HPP\n#define UNIFORM_DISTRIBUTION_HPP\n\n#include <boost/random/uniform_smallint.hpp>\n// boost::math::uniform is not used as it is linked to real values rather than discrete integral values\n\nnamespace rjmcmc {\n\n    // 1_(n\\in[a,b])/(b-a+1)\n    class uniform_distribution {\n    public:\n        typedef double real_type;\n        typedef int    int_type;\n        typedef boost::uniform_smallint<int_type> rand_distribution_type;\n\n        uniform_distribution(int_type a, int_type b)\n            : m_rand(a,b)\n            , m_pdf(real_type(1)/(b-a+1)) {}\n\n        // new/old\n        real_type pdf_ratio(int_type n0, int_type n1) const\n        {\n            assert(pdf(n0)>0);\n            return (m_variate.distribution().min() <= n1 && n1 <= m_variate.distribution().max() );\n        }\n\n        real_type pdf(int_type n) const\n        {\n            return m_pdf * (m_variate.distribution().min() <= n && n <= m_variate.distribution().max() );\n        }\n\n        template<typename Engine>\n        inline int_type operator()(Engine& e) const { return m_rand(e); }\n\n    private:\n        mutable rand_distribution_type m_rand;\n        real_type m_pdf;\n    };\n\n}; // namespace rjmcmc\n\n#endif // UNIFORM_DISTRIBUTION_HPP\n", "meta": {"hexsha": "199fe3108194be6a5c3930ef9322e8b7c8bbc8e6", "size": 3040, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rjmcmc/rjmcmc/distribution/uniform_distribution.hpp", "max_stars_repo_name": "qc2105/librjmcmc", "max_stars_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-02-17T17:07:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T16:49:02.000Z", "max_issues_repo_path": "include/rjmcmc/rjmcmc/distribution/uniform_distribution.hpp", "max_issues_repo_name": "qc2105/librjmcmc", "max_issues_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T09:39:33.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-03T13:22:49.000Z", "max_forks_repo_path": "include/rjmcmc/rjmcmc/distribution/uniform_distribution.hpp", "max_forks_repo_name": "qc2105/librjmcmc", "max_forks_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T17:32:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T21:38:16.000Z", "avg_line_length": 38.4810126582, "max_line_length": 105, "alphanum_fraction": 0.6950657895, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6141763461605773}}
{"text": "\r\n#pragma once\r\n\r\n#include <Eigen/Core>\r\n#include <array>\r\n\r\nnamespace Discregrid\r\n{\r\n\r\n    enum class NearestEntity\r\n    {\r\n        VN0,\r\n        VN1,\r\n        VN2,\r\n        EN0,\r\n        EN1,\r\n        EN2,\r\n        FN\r\n    };\r\n\r\n    float point_triangle_sqdistance(Eigen::Vector3f const &point,\r\n                                    std::array<Eigen::Vector3f const *, 3> const &triangle,\r\n                                    Eigen::Vector3f *nearest_point = nullptr,\r\n                                    NearestEntity *ne = nullptr);\r\n\r\n}\r\n", "meta": {"hexsha": "b5d24cb0eef68b82278a9f67028d55c34d4de898", "size": 542, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "discregrid/src/geometry/point_triangle_distance.hpp", "max_stars_repo_name": "FeatherAntennae/Discregrid", "max_stars_repo_head_hexsha": "54ced899445d902470efe6b3d8df73c0fd9c23d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "discregrid/src/geometry/point_triangle_distance.hpp", "max_issues_repo_name": "FeatherAntennae/Discregrid", "max_issues_repo_head_hexsha": "54ced899445d902470efe6b3d8df73c0fd9c23d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "discregrid/src/geometry/point_triangle_distance.hpp", "max_forks_repo_name": "FeatherAntennae/Discregrid", "max_forks_repo_head_hexsha": "54ced899445d902470efe6b3d8df73c0fd9c23d1", "max_forks_repo_licenses": ["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": 92, "alphanum_fraction": 0.4557195572, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135362, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6141716232360929}}
{"text": "/**\n * @file upwindquadrature_main.cc\n * @brief Convergence study for 3 methods to solve CD BVP\n * @author Philippe Peter\n * @date July 2020\n * @copyright Developed at SAM, ETH Zurich\n */\n#include <lf/fe/fe.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/refinement/refinement.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <string>\n\n#include \"cd_tools.h\"\n#include \"standard_fem.h\"\n#include \"supg.h\"\n#include \"upwind.h\"\n\nint main() {\n  // parameter functions:\n  // velocity field\n  const Eigen::Vector2d v(2.0, 3.0);\n  const auto velocity = [&v](const Eigen::Vector2d& x) { return v; };\n  // diffusion coefficient\n  const double eps = 1.0;\n  const auto epsilon = [&eps](const Eigen::Vector2d& x) { return eps; };\n  // exact solution:\n  const auto u_exact = [&eps](const Eigen::Vector2d& x) {\n    return x(0) * x(1) * x(1) - x(1) * x(1) * std::exp(2 * (x(0) - 1) / eps) -\n           x(0) * std::exp(3 * (x(1) - 1) / eps) +\n           std::exp(2 * (x(0) - 1) / eps + 3 * (x(1) - 1) / eps);\n  };\n  // gradient of the exact solution\n  const auto u_grad_exact = [&eps](const Eigen::Vector2d& x) {\n    Eigen::Vector2d res;\n    res(0) = x(1) * x(1) -\n             x(1) * x(1) * 2.0 / eps * std::exp(2 * (x(0) - 1) / eps) -\n             std::exp(3 * (x(1) - 1) / eps) +\n             2.0 / eps * std::exp(2 * (x(0) - 1) / eps + 3 * (x(1) - 1) / eps);\n    res(1) = 2 * x(0) * x(1) - 2 * x(1) * std::exp(2 * (x(0) - 1) / eps) -\n             x(0) * 3.0 / eps * std::exp(3 * (x(1) - 1) / eps) +\n             3.0 / eps * std::exp(2 * (x(0) - 1) / eps + 3 * (x(1) - 1) / eps);\n    return res;\n  };\n  // Laplacian of the exact solution\n  const auto u_laplace_exact = [&eps](const Eigen::Vector2d& x) {\n    double uxx =\n        -4.0 / (eps * eps) * x(1) * x(1) * std::exp(2 * (x(0) - 1) / eps) +\n        4.0 / (eps * eps) *\n            std::exp(2 * (x(0) - 1) / eps + 3 * (x(1) - 1) / eps);\n    double uyy = 2.0 * x(0) - 2.0 * std::exp(2 * (x(0) - 1) / eps) -\n                 x(0) * 9.0 / (eps * eps) * std::exp(3 * (x(1) - 1) / eps) +\n                 9.0 / (eps * eps) *\n                     std::exp(2 * (x(0) - 1) / eps + 3 * (x(1) - 1) / eps);\n    return uxx + uyy;\n  };\n  // source function\n  const auto f = [&eps, &v, &u_grad_exact,\n                  &u_laplace_exact](const Eigen::Vector2d& x) {\n    return -eps * u_laplace_exact(x) + v.transpose() * u_grad_exact(x);\n  };\n\n  // boundary conditions\n  const auto g = [&u_exact](const Eigen::Vector2d& x) { return u_exact(x); };\n\n  // Construct mesh hierarchy:\n  std::unique_ptr<lf::mesh::MeshFactory> top_mesh_factory_ptr =\n      std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::mesh::utils::TPTriagMeshBuilder builder(std::move(top_mesh_factory_ptr));\n  builder.setBottomLeftCorner(Eigen::Vector2d{0.0, 0.0})\n      .setTopRightCorner(Eigen::Vector2d{1.0, 1.0})\n      .setNumXCells(2)\n      .setNumYCells(2);\n  std::shared_ptr<lf::mesh::Mesh> top_mesh = builder.Build();\n\n  std::shared_ptr<lf::refinement::MeshHierarchy> multi_mesh_p =\n      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(top_mesh, 6);\n  lf::refinement::MeshHierarchy& multi_mesh{*multi_mesh_p};\n  multi_mesh.PrintInfo(std::cout);\n\n  // get number of levels:\n  unsigned L = multi_mesh.NumLevels();\n\n  // Output file\n  std::string file_name = \"results_errors.txt\";\n  std::ofstream file;\n  file.open(file_name);\n  file << \"h, $L^2$-Error u (FEM), $L^2$-Error u (Upwind), $L^2$-Error u \"\n          \"(SUPG) \\n\";\n\n  // Perform computations on all levels and compute  L2-errors\n  for (unsigned l = 0; l < L; ++l) {\n    // extract mesh and construct FE space.\n    std::shared_ptr<const lf::mesh::Mesh> mesh_p{multi_mesh.getMesh(l)};\n    auto fe_space =\n        std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n\n    // compute solutions using Standard FE, Upwind, SUPG method\n    Eigen::VectorXd sol_standard = ConvectionDiffusion::SolveCDBVPStandardFem(\n        fe_space, epsilon, velocity, f, g);\n    lf::fe::MeshFunctionFE sol_standard_mf(fe_space, sol_standard);\n\n    Eigen::VectorXd sol_stable = ConvectionDiffusion::SolveCDBVPUpwind(\n        fe_space, epsilon, velocity, f, g);\n    lf::fe::MeshFunctionFE sol_upwind_mf(fe_space, sol_stable);\n\n    Eigen::VectorXd sol_supg =\n        ConvectionDiffusion::SolveCDBVPSupg(fe_space, epsilon, velocity, f, g);\n    lf::fe::MeshFunctionFE sol_supg_mf(fe_space, sol_supg);\n\n    // Wrap exact solution into mesh function for error computations\n    auto mf_solution = lf::mesh::utils::MeshFunctionGlobal(u_exact);\n\n    // Calculate L2 errors:\n    double L2err_standard = std::sqrt(lf::fe::IntegrateMeshFunction(\n        *mesh_p, lf::mesh::utils::squaredNorm(sol_standard_mf - mf_solution),\n        10));\n    double L2err_upwind = std::sqrt(lf::fe::IntegrateMeshFunction(\n        *mesh_p, lf::mesh::utils::squaredNorm(sol_upwind_mf - mf_solution),\n        10));\n    double L2err_supg = std::sqrt(lf::fe::IntegrateMeshFunction(\n        *mesh_p, lf::mesh::utils::squaredNorm(sol_supg_mf - mf_solution), 10));\n\n    // output\n    std::cout << \"Level \" << l\n              << \"(h= \" << ConvectionDiffusion::MeshWidth(mesh_p)\n              << \"): \" << L2err_standard << \", \" << L2err_upwind << \", \"\n              << L2err_supg << std::endl;\n    file << ConvectionDiffusion::MeshWidth(mesh_p) << \", \" << L2err_standard\n         << \", \" << L2err_upwind << \", \" << L2err_supg << std::endl;\n  }\n  file.close();\n\n  // Plot\n  std::system(\"python3 \" CURRENT_SOURCE_DIR\n              \"/plot_convergence.py \" CURRENT_BINARY_DIR);\n\n  return 0;\n}", "meta": {"hexsha": "2ee9e84de5651976ef5ec4192c1332cbaccae65e", "size": 5669, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lecturecodes/ConvectionDiffusion/convergence_main.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "lecturecodes/ConvectionDiffusion/convergence_main.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "lecturecodes/ConvectionDiffusion/convergence_main.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 38.5646258503, "max_line_length": 79, "alphanum_fraction": 0.599047451, "num_tokens": 1901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126791, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6141716061615397}}
{"text": "#include \"advent.hpp\"\n\n#include <fstream>\n#include <gsl/gsl_util>\n#include <iostream>\n#include <scn/scn.h>\n#include <Eigen/Dense>\n\n\nusing board = Eigen::Array<int, -1, -1>;\n\nauto day04(int argc, char** argv) -> int\n{\n    if (argc < 2) {\n        fmt::print(\"Please provide an input file.\\n\");\n        return 1;\n    }\n\n    std::ifstream infile(argv[1]); // NOLINT\n    std::string line;\n\n    // the first line represents the list of input numbers\n    std::getline(infile, line);\n    std::vector<int> numbers;\n    auto res = scn::scan_list(line, numbers, ',');\n    ENSURE(res);\n\n    // the remainder of the file contains the board configurations\n    int rows = 0;\n    std::vector<std::vector<int>> values;\n    std::vector<board> boards;\n\n    while(std::getline(infile, line)) {\n        if (line.empty()) {\n            if (rows > 0) {\n                boards.emplace_back(rows, values.front().size());\n                auto& b = boards.back();\n                for (size_t i = 0; i < values.size(); ++i) {\n                    EXPECT(values[i].size() == b.rows());\n                    b.row(gsl::narrow<Eigen::Index>(i)) = Eigen::Map<Eigen::Array<int, -1, 1>>(values[i].data(), values[i].size());\n                }\n                rows = 0;\n                values.clear();\n                //std::cout << b << \"\\n\\n\";\n            }\n            continue;\n        }\n        std::vector<int> vec;\n        auto res = scn::scan_list(line, vec, ' ');\n        ENSURE(res);\n        values.push_back(vec);\n        ++rows;\n    }\n\n    // part 1\n    std::vector<bool> bingoed(boards.size(), false);\n    for (auto n : numbers) {\n        size_t idx{0};\n        for (auto& b : boards) {\n            for (int i = 0; i < b.cols(); ++i) {\n                for (int j = 0; j < b.rows(); ++j) {\n                    if (bingoed[idx]) {\n                        continue;\n                    }\n\n                    if (n == b(i, j)) {\n                        b(i, j) = -1;\n                    }\n\n                    if (\n                            (i == j && (b.matrix().diagonal().array() < 0).all()) // bingo on the main diagonal\n                            || ((i == b.rows() - j - 1 || j == b.rows() - i - 1) && (b.matrix().transpose().diagonal().array() < 0).all()) // bingo on the other diagonal\n                            || (b.col(i) < 0).all() // column bingo\n                            || (b.row(j) < 0).all() // row bingo\n                       ) {\n                        auto sum = (b < 0).select(0, b).sum();\n                        auto score = sum * n;\n                        fmt::print(\"bingo at board {}! n: {}, sum: {}, score: {}\\n\", idx, n, sum, score);\n                        std::cout << b << \"\\n\\n\";\n                        bingoed[idx] = true;\n                    }\n                }\n            }\n            ++idx;\n        }\n    }\n    return 0;\n}\n", "meta": {"hexsha": "ace384abb9f3445e89855a9152ea577a5e0c189b", "size": 2844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/day04.cpp", "max_stars_repo_name": "foolnotion/aoc2021", "max_stars_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/day04.cpp", "max_issues_repo_name": "foolnotion/aoc2021", "max_issues_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/day04.cpp", "max_forks_repo_name": "foolnotion/aoc2021", "max_forks_repo_head_hexsha": "e2bbcd8cab2a1a7b9922694daff7d289a905c133", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-29T23:05:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T23:05:48.000Z", "avg_line_length": 31.9550561798, "max_line_length": 169, "alphanum_fraction": 0.4159634318, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6141330155967616}}
{"text": "\ufeff\n#include \"Srobotconfig.h\"\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nnamespace SRobot\n{\n    SCARA Scara(250,250);\n\t//\u521d\u59cb\u5316TransMatrix\n\tdouble mTransMatrix[16]={0};\n    double mangle[4]={0};\n    double mpose[6]={0};\n\n\t//\u53ea\u4f7f\u7528\u4e00\u79cd\u59ff\u6001\n\tbool mConfig = 1;\n\n    Matrix3d skew(Vector3d w)\n    {   \n        Matrix3d so3;\n        so3 << 0, -w(2), w(1),\n            w(2), 0, -w(0),\n            -w(1), w(0), 0;\n        return so3;\n    }\n\n    Matrix4d R2SE3(Vector3d v, Vector3d w, int i, double theta)\n    {\n        Matrix4d SE3 = Matrix4d::Identity();\n        if (i == 2)\n        {\n            SE3(2,3) = -theta;\n        }\n        else\n        {\n            theta = PI * theta / 180;\n            Matrix3d so3 = skew(w);\n            Matrix3d SO3 = Matrix3d::Identity() + so3 * sin(theta) + so3 * so3 * (1 - cos(theta));  //Rodrigues Formula\n            Vector3d p = (Matrix3d::Identity() - SO3) * skew(w) * v + w * w.transpose() * v * theta;\n            SE3.block<3,3>(0,0) = SO3;\n            SE3.block<3,1>(0,3) = p;\n        }\n        return SE3;\n    }\n\n    Matrix4d GetInverse(Matrix4d T)\n    {\n        Matrix4d T_inv = Matrix4d::Identity();\n        T_inv.block<3,3>(0,0) = T.block<3,3>(0,0).transpose();\n        T_inv.block<3,1>(0,3) = -T.block<3,3>(0,0).transpose() * T.block<3,1>(0,3);\n        return T_inv;\n    }\n\t\n    void Subproblem1 (Vector3d r, Vector3d p, Vector3d q, Vector3d w, double &theta)\n    {\n        Vector3d u,v,u_dot,v_dot;\n        u = p - r;\n        v = q - r;\n\n        u_dot = u - w * w.transpose() * u;\n        v_dot = v - w * w.transpose() * v;\n\n        theta = atan2(w.transpose()*(u_dot.cross(v_dot)),u_dot.transpose()*v_dot) * 180 / PI;\n    }\n\n//     //SCRAR\u6ca1\u6709\u7528 \u5199\u4e00\u4e0b\u5f53\u7ec3\u4e60\n    void Subproblem2 (Vector3d r, Vector3d p, Vector3d q, Vector3d w1, Vector3d w2, vector<double> &theta1, vector<double> &theta2 )\n    {\n        Vector3d u,v;\n        u = p - r;\n        v = q - r;\n\n        double w12 = w1.transpose()*w2;\n        double w2u = w2.transpose()*u;\n        double w1v = w1.transpose()*v;\n        double alpha = (w12*w2u - w1v) / (w12*w12 -1);\n        double beta = (w12*w1v-w2u) / (w12*w12 -1);\n\n        double u_norm_2 = u.transpose()*u;\n        Vector3d w1_cross_w2 = w1.cross(w2);\n        double Gamma_2 = (u_norm_2 - alpha*alpha -beta*beta -2*alpha*beta*w12) / (w1_cross_w2).dot(w1_cross_w2);\n\n        if(Gamma_2>=0){\n            double Gamma = sqrt(Gamma_2);\n            Vector3d z1 = alpha * w1 + beta * w2 + Gamma * w1_cross_w2;\n            Vector3d z2 = alpha * w1 + beta * w2 - Gamma * w1_cross_w2;\n            Vector3d c1 = z1 + r;\n            Vector3d c2 = z2 + r;\n\n            double theta1_temp, theta2_temp;\n            Subproblem1(r, q, c1, w1, theta1_temp);\n            theta1.push_back(-theta1_temp);\n            Subproblem1(r, q, c2, w1, theta1_temp);\n            theta1.push_back(-theta1_temp);\n\n            Subproblem1(r, p, c1, w2, theta2_temp);\n            theta2.push_back(theta2_temp);\n            Subproblem1(r, p, c2, w2, theta2_temp);\n            theta2.push_back(theta2_temp);\n        }\n    }\n   void Subproblem3 (Vector3d r, Vector3d p, Vector3d q, Vector3d w, double delta, vector<double> &theta)\n    {\n        Vector3d u,v,u_dot,v_dot;\n        u = p - r;\n        v = q - r;\n        u_dot = u - w * w.transpose() * u;\n        v_dot = v - w * w.transpose() * v;\n        double delta_dot_2 = delta*delta - (w.dot(p-q))*(w.dot(p-q));   //maybe bug\n\n        double theta0 = atan2(w.dot(u_dot.cross(v_dot)),u_dot.dot(v_dot));\n\n        double Phi = (u_dot.dot(u_dot) + v_dot.dot(v_dot) -delta_dot_2)/sqrt(4*u_dot.dot(u_dot)*v_dot.dot(v_dot));\n        if (abs(Phi) <= 1){\n            theta.push_back((theta0+acos(Phi))/PI*180);\n            theta.push_back((theta0-acos(Phi))/PI*180);\n        }\n    }\t\n\t\n\tvoid SetRobotEndPos(double x, double y, double z, double yaw, double pitch, double roll)\n\t{\n        mpose[0] = x;\n        mpose[1] = y;\n        mpose[2] = z;\n        mpose[3] = yaw/180*PI;\n        mpose[4] = pitch/180*PI;\n        mpose[5] = roll/180*PI;\n        \n        Eigen::AngleAxisd yawAngle(AngleAxisd(mpose[3],Vector3d::UnitZ()));\n        Eigen::AngleAxisd pitchAngle(AngleAxisd(mpose[4],Vector3d::UnitY()));\n        Eigen::AngleAxisd rollAngle(AngleAxisd(mpose[5],Vector3d::UnitZ()));\n        Matrix3d rotate;\n        rotate = yawAngle*pitchAngle*rollAngle;\n        Matrix4d T = Matrix4d::Identity();\n        T.block<3,3>(0,0) = rotate;\n        T(0,3) = x;\n        T(1,3) = y;\n        T(2,3) = z;\n\n        for (int i=0; i<4; i++){\n            for(int j=0; j<4; j++){\n                mTransMatrix[4*i+j] = T(i,j);\n            }\n        }\n\t}\n\n\tvoid GetJointAngles(double &angle1, double &angle2, double &angle3, double &angle4)\n\t{\n        robotBackward(mTransMatrix, mConfig, mangle);\n        angle1 = mangle[0];\n        angle2 = mangle[1];\n        angle3 = mangle[2];\n        angle4 = mangle[3];\n\t}\n\n\tvoid SetRobotJoint(double angle1, double angle2, double angle3, double angle4)\n\t{\n        mangle[0] = angle1;\n        mangle[1] = angle2;\n        mangle[2] = angle3;\n        mangle[3] = angle4;\n\t}\n\n\tvoid GetJointEndPos(double &x, double &y, double &z, double &yaw, double &pitch, double &roll)\n\t{\n        Matrix4d T;\n        Matrix3d R;\n        Vector3d Euler;\n        robotForward(mangle, mTransMatrix, mConfig);\n        for (int i=0; i<4; i++){\n            for(int j=0; j<4; j++){\n                T(i,j) = mTransMatrix[4*i+j];\n            }\n        }\n        x = T(0,3);\n        y = T(1,3);\n        z = T(2,3);\n        R = T.block<3,3>(0,0);\n        Euler = R.eulerAngles(2,1,2);\n        yaw = Euler(0)/PI*180;\n        pitch = Euler(1)/PI*180;\n        roll = Euler(2)/PI*180;\n\t}\n\n\n\t/********************************************************************\n\tABSTRACT:\t\u673a\u5668\u4eba\u9006\u8fd0\u52a8\u5b66\n\n\tINPUTS:\t\tT[16]:\t\u4f4d\u59ff\u77e9\u9635\uff0c\u5176\u4e2d\u957f\u5ea6\u8ddd\u79bb\u4e3a\u7c73\n\n\t\t\t\tconfig\uff1a\u59ff\u6001\uff0c\u516d\u8f74\u673a\u5668\u4eba\u5bf9\u5e94\u67098\u79cd\u59ff\u6001\uff08\u5373\u5bf9\u5e94\u7684\u9006\u8fd0\u52a8\u5b668\u4e2a\u89e3\uff09\uff0c\n\t\t\t\tScara\u673a\u5668\u4eba\u67092\u4e2a\u89e3\uff0cDelta\u673a\u5668\u4eba\u6709\u4e00\u4e2a\u89e3\uff0c\n\t\t\t\t\u4e3a\u4e86\u5b89\u5168\uff0c\u5b9e\u9a8c\u5ba4\u4e2d\u6211\u4eec\u53ea\u8ba1\u7b97\u4e00\u79cd\u5373\u53ef\u3002config\u7528\u6765\u4f5c\u4e3a\u9009\u89e3\u7684\u6807\u5fd7\u6570\u3002\n\n\tOUTPUTS:    theta[6] 6\u4e2a\u5173\u8282\u89d2, \u5355\u4f4d\u4e3a\u5f27\u5ea6\n\n\tRETURN:\t\t<none>\n\t***********************************************************************/\n\tvoid robotBackward(const double* TransVector, bool mconfig, double* theta)\n\t{\n        //get angle3\n\t\ttheta[2] = -TransVector[11];\n\n        Matrix4d G, T;\n        for (int i=0; i<4; i++){\n            for(int j=0; j<4; j++){\n                T(i,j) = TransVector[4*i+j];\n            }\n        }\n        G = T*GetInverse(Scara.G0);\n        //Subproblem3 to get angle 2\n        Matrix4d T3 = Matrix4d::Identity();\n        T3(2,3) = theta[2];\n        Vector4d q3(500,0,0,1);\n        Vector4d q1(0,0,0,1);\n\n        double delta = (G*q3).norm();\n        Vector4d p = T3*q3;\n        Vector4d q2(250,0,0,1);\n        vector<double> angle2;\n        Subproblem3(q2.head(3),p.head(3),q1.head(3),Scara.w.col(1),delta,angle2);\n        theta[1] = angle2[mconfig];\n        //Subproblem1 to get angle 1\n        Matrix4d T2 = R2SE3(Scara.v.col(1),Scara.w.col(1), 1, theta[1]);\n        Vector4d q = G*q3;\n        p =T2*T3*q3;\n        Subproblem1(q1.head(3),p.head(3),q.head(3),Scara.w.col(0),theta[0]);\n        //Subproblem1 to get angle 4\n        Matrix4d T1 = R2SE3(Scara.v.col(0),Scara.w.col(0), 0, theta[0]);\n        q = GetInverse(T3)*GetInverse(T2)*GetInverse(T1)*G*q1;\n        p = q1;\n        Subproblem1(q3.head(3),p.head(3),q.head(3),Scara.w.col(3),theta[3]);\n\t}\n\n\t/********************************************************************\n\tABSTRACT:\t\u673a\u5668\u4eba\u6b63\u8fd0\u52a8\u5b66\n\t\n\tINPUTS:\t\tq[6]: 6\u4e2a\u5173\u8282\u89d2, \u5355\u4f4d\u4e3a\u5f27\u5ea6\n\t\n\tOUTPUTS:\tconfig\u7528\u6765\u4f5c\u4e3a\u9009\u89e3\u7684\u6807\u5fd7\u6570\u3002\n\n\t\t\t\tTransVector[16] : \u521a\u4f53\u53d8\u6362\u77e9\u9635\uff0c\u4e5f\u5c31\u662f\u672b\u7aef\u7684\u4f4d\u59ff\u63cf\u8ff0\uff0c\u5176\u4e2d\u957f\u5ea6\u8ddd\u79bb\u4e3a\u7c73\n\t\n\tRETURN:\t\t<none>\n\t***********************************************************************/\n\tvoid robotForward(const double* q, double* TransVector, bool mconfig)\n\t{\t\n        Matrix4d T=Matrix4d::Identity();\n        cout<<endl;\n\t\tfor(int i=0;i<4;i++){\n            T = T * R2SE3(Scara.v.col(i),Scara.w.col(i),i,q[i]);\n        }\n        T = T*Scara.G0;\n        for (int i=0; i<4; i++){\n            for(int j=0; j<4; j++){\n                TransVector[4*i+j] = T(i,j);\n            }\n        }\n\t}\n}\n", "meta": {"hexsha": "f2fddb0a5f6b669eadd2365844cc77279c286ffd", "size": 7985, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SCARA/Srobotconfig.cpp", "max_stars_repo_name": "liuxiao916/Robotics_in_HIT", "max_stars_repo_head_hexsha": "20edb1ae457eb0bb91cc58a1247cf7d9cea7d70b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-28T10:40:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T10:40:17.000Z", "max_issues_repo_path": "SCARA/Srobotconfig.cpp", "max_issues_repo_name": "liuxiao916/Robotics_in_HIT", "max_issues_repo_head_hexsha": "20edb1ae457eb0bb91cc58a1247cf7d9cea7d70b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SCARA/Srobotconfig.cpp", "max_forks_repo_name": "liuxiao916/Robotics_in_HIT", "max_forks_repo_head_hexsha": "20edb1ae457eb0bb91cc58a1247cf7d9cea7d70b", "max_forks_repo_licenses": ["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.36121673, "max_line_length": 132, "alphanum_fraction": 0.5100814026, "num_tokens": 2753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6141330143357605}}
{"text": "#include <mex.h>\n#include \"armaMex.hpp\"\n#include <armadillo>\n#include <boost/math/special_functions/expint.hpp>\n#include <boost/math/special_functions/trigamma.hpp>\n#define POSITIVE_EPS 0.0001\n#define epsilon1 1e-30\n#define epsilon2 1e-7\n\ndouble Lentz_Algorithm(double const x)\n{\n    double f_prev = epsilon1, C_prev = epsilon1, D_prev = 0, delta = 2+epsilon2, D_curr, C_curr, f_curr;\n    double j = 1.0, tmp1, tmp2;\n    while (delta-1>=epsilon2 || 1-delta >= epsilon2)\n    {\n        j++;\n        tmp1 = x+2*j-1;\n        tmp2 = pow(j-1,2);\n        D_curr = 1/(tmp1-tmp2*D_prev);\n        C_curr = tmp1-tmp2/C_prev;\n        delta = C_curr*D_curr;\n        f_curr = f_prev*delta;\n        f_prev = f_curr;\n        C_prev = C_curr;\n        D_prev = D_curr;\n    }\n    return 1/(x+1+f_curr);\n}\n\n\nvoid mexFunction(int nlhs,mxArray *plhs[],int nrhs, const mxArray *prhs[])\n{\n    /* Input Interface*/\n    mat XDat = armaGetPr(prhs[0]);\n    uword maxIter, s, p = XDat.n_cols,n = XDat.n_rows;\n    double tol, eta, r;\n    \n    if (nrhs>1)\n    {\n        eta = armaGetDouble(prhs[1]);\n        eta = eta/(p+eta);\n    }\n    else eta = 300.0/(p+300.0);//0.05; //4*sqrt(double(p)/(p^2-1));\n    \n    if (nrhs>2) maxIter = (uword)armaGetDouble(prhs[2]);\n    else maxIter = 10000;\n    if (nrhs>3) tol = armaGetDouble(prhs[3]);\n    else tol = 0.01;\n    \n    if (nrhs>4) r = armaGetDouble(prhs[4]);\n    else\n    {\n        r = 0.5; //(1-400.0/double(p))/(1+400.0/double(p));\n        //if(r<0.05) r = 0.05;\n    }\n    if (nrhs>5) s = (uword)armaGetDouble(prhs[5]);\n    else s = round((double)p/(1e-3*(p-1)+1)); //(pow((double)p,1.5)/(5e-2*(p-1)+sqrt(double(p))));\n\n    \n    \n    \n\tmat nS = XDat.t()*XDat;\n\n    /* Initialization */\n    auto t_start = std::chrono::high_resolution_clock::now();\n\tvec dnS = nS.diag();\n    uword pe = p*(p-1)/2;\n\n    uvec idl(pe);\n    uvec idu(pe);\n    uvec idr(pe);\n    uvec idc(pe);\n    uword k = 0, i, j, jp, kappa;\n    for (j = 0,jp = 0;j<p;j++,jp+=p)\n    {\n        for (i=j+1;i<p;i++)\n        {\n            idl(k) = jp+i;\n            idu(k) = i*p+j;\n            idr(k) = i;\n            idc(k) = j;\n            k++;\n        }\n\n    }\n\n    double psr = (double)p/s;\n    uvec idp(p), id0(s), idd;\n    vec nd2pp = (double)n/2+linspace<vec>(p,1,p);\n\n    mat ML(p,p,fill::eye);\n    mat ML2(p,p,fill::eye);\n    mat ML2pVL(p,p,fill::eye);\n    mat VL(p,p,fill::zeros);\n    mat LAMBDA(p,p,fill::zeros);\n\n    vec h(pe,fill::zeros),zeta(pe),mL(pe,fill::zeros);\n    zeta.fill(10.0);\n\n    vec alpha(p,fill::ones);\n    vec beta(p,fill::ones);\n\n    double a = (double)pe/2, b = a/50;\n\n    vec mLold = h/zeta;\n    vec lambdaold(pe,fill::ones);\n\n    mat VL2(p,p,fill::zeros);\n    for (i=1;i<p;i++)\n    {\n        VL2(span(i,p-1),i) += i;\n        VL2(i,span(i,p-1)) += i;\n    }\n\tVL2 *= 0.01;\n\n\tvec d(pe,1);\n\td.fill(0.5);\n\n    vec mD, mD2, mD2pvD, vD, vL, lambda(pe), gmL, gvL, gmD, gvD, c5(p), c6, mLnew, lambdanew, alphatmp, betatmp, dtmp;//mL,\n    mat c1, c2, c3, c4, LDL, c2pc3, K_tmp1, K_tmp2;\n    double omega, difmL, diflambda, difmax;\n    vec d1h(pe,fill::zeros), d1zeta(pe,fill::zeros), d1alpha(p,fill::zeros), d1beta(p,fill::zeros), d1d(pe,fill::zeros);\n    double d2h = 0, d2zeta = 0, d2alpha = 0, d2beta = 0, d2d = 0, d1b = 0, d2b = 0;\n    double tau = 6e2; //, tauzeta = tauh, taualpha = tauh, taubeta = tauh, taub = tauh, taud = tauh;\n    double rho, gb, btmp;//1/eta;rho_ub, c7=(5*eta>0.25)?0.25:5*eta, \n    vec gh, gzeta, galpha, gbeta, gd;\n    arma_rng::set_seed(0);\n\n    /* KL proximal variational inference */\n    mexPrintf(\"Start Running BISN ...\\n\");\n    for (kappa=1;kappa<=maxIter;kappa++)\n    {\n        mD = alpha/beta;\n        mD2 = square(mD);\n        vD = mD/beta;\n        mD2pvD = mD2+vD;\n\n        vL = 1/zeta;\n        VL.elem(idl) = vL;\n        mL =  h%vL;\n        ML.elem(idl) = mL;\n        ML2.elem(idl) = square(mL);\n        ML2pVL.elem(idl) = ML2.elem(idl)+vL;\n\n        omega = a/b;\n        lambda = d;\n        lambda.transform([](double val){return (val > 10) ? Lentz_Algorithm(val) : (- boost::math::expint(-val) * exp(val));});\n        lambda = 1/(d%lambda)-1;\n        LAMBDA.elem(idl) = omega*lambda;\n        LAMBDA.elem(idu) = LAMBDA.elem(idl);\n\n\n        if (kappa==1)\n        {\n            c1 = nS;\n            c2 = -VL;\n            c2.each_row() += sum(VL);\n            c2 *= LAMBDA(1); \n            //c2 = LAMBDA(1)*(repmat(sum(VL),p,1)-VL);\n            c3 = LAMBDA;\n            c4 = (VL+VL2)*mD2pvD(0);\n\t\t\tVL2.clear();\n        }\n        else\n        {\n            K_tmp1 = ML.rows(id0);\n            K_tmp1.each_row() %= mD.t();\n            LDL = K_tmp1*ML.t();\n            c1 *= r;\n            c1.rows(id0) += psr*(nS.rows(id0)+LDL%LAMBDA.rows(id0))*ML;\n\n            c2 *= r;\n            c2.rows(id0) += psr*LAMBDA.rows(id0)*VL;\n\n            c3 *= r;\n            c3.rows(id0) += psr*LAMBDA.rows(id0)*ML2;\n\n            K_tmp1 = ML2pVL.rows(id0);\n            K_tmp1.each_row() %= mD2pvD.t();\n            K_tmp2 = ML2.rows(id0);\n            K_tmp2.each_row() %= mD2.t();\n            c4 *=r;\n            c4.rows(id0) += psr*(K_tmp1*ML2pVL.t()-K_tmp2*ML2.t()+square(LDL));\n        }\n\n        c2pc3 = c2+c3;\n        gmL = -c1.elem(idl)%mD.elem(idc)-ML.elem(idl)%(mD2pvD.elem(idc)%c2.elem(idl)+vD.elem(idc)%c3.elem(idl));\n        gvL = dnS.elem(idr)%mD.elem(idc)+c2pc3.elem(idl)%mD2pvD.elem(idc);\n        gh = gmL+mL%gvL - h;\n        gvL.elem(find(gvL<0)).zeros();\n        gzeta = gvL - zeta;\n        d1h = (1-1/tau)*d1h+gh/tau;\n        d2h = (1-1/tau)*d2h+mean(square(gh))/tau;\n        d1zeta = (1-1/tau)*d1zeta + gzeta/tau;\n        d2zeta = (1-1/tau)*d2zeta + mean(square(gzeta))/tau;\n\n        gmD = (VL.t()*dnS+trans(sum(ML%c1))+trans(sum(VL%(c2pc3+c3)))%mD)/2;\n        gvD = trans(sum(ML2pVL%c2pc3))/4;;\n        c5 = alpha;\n        c5.transform([](double val) { return boost::math::trigamma(val); });\n        c6 = mD/(alpha%c5-1);\n        alphatmp = nd2pp+c6/beta%gvD;\n        alphatmp.elem(find(alphatmp<0)).zeros();\n        betatmp = gmD+(1/beta+c5%c6)%gvD;\n        betatmp.elem(find(betatmp<0)).zeros();\n        galpha = alphatmp - alpha;\n        gbeta = betatmp - beta;\n        d1alpha = (1-1/tau)*d1alpha + galpha/tau;\n        d2alpha = (1-1/tau)*d2alpha + mean(square(galpha))/tau;\n        d1beta = (1-1/tau)*d1beta + gbeta/tau;\n        d2beta = (1-1/tau)*d2beta + mean(square(gbeta))/tau;\n\n        dtmp = omega/2*c4.elem(idl);\n        dtmp.elem(find(dtmp<0)).zeros();\n        gd = dtmp - d;\n        d1d = (1-1/tau)*d1d + gd/tau;\n        d2d = (1-1/tau)*d2d + mean(square(gd))/tau;\n\n        btmp = sum(lambda%c4.elem(idl))/2;\n        if (btmp<0) btmp = 0;\n        gb = btmp - b;\n        d1b = (1-1/tau)*d1b + gb/tau;\n        d2b = (1-1/tau)*d2b + pow(gb,2)/tau;\n\n        rho = (mean(square(d1h))+mean(square(d1zeta))+p/pe*(mean(square(d1alpha))+mean(square(d1beta)))+mean(square(d1d))+pow(d1b,2)/pe)/(d2h+d2zeta+p/pe*(d2alpha+d2beta)+d2d+d2b/pe);\n        if (rho>eta) rho = eta;\n\n        tau = (1-rho)*tau + 1;\n        h += rho*gh;\n        zeta += rho*gzeta;\n        alpha += rho*galpha;\n        beta += rho*gbeta;\n        d += rho*gd;\n        b += rho*gb;\n\n\n\n        if (kappa%100 == 0)\n        {\n            mLnew = h/zeta;\n            lambdanew = lambda;\n            difmL = sqrt(mean(square(mLnew-mLold))/mean(square(mLold)));\n            diflambda = max(abs(lambdanew-lambdaold));\n            difmax = max(abs(mLnew-mLold));\n            mexPrintf(\"#no. of iterations = %d, difmL = %f, difmax = %f, diflambda = %f\\n\",kappa,difmL,difmax,diflambda);\n            mexEvalString(\"drawnow;\");\n            if (difmL<tol)\n                break;\n            else\n            {\n                mLold = mLnew;\n                lambdaold = lambdanew;\n            }\n        }\n        \n        id0 = randperm(p, s);\n\n\n        K_tmp1 = ML.rows(id0);\n        K_tmp1.each_row() %= mD.t();\n        LDL = K_tmp1*ML.t();\n        c1.rows(id0) -= psr*(nS.rows(id0)+LDL%LAMBDA.rows(id0))*ML;\n        c2.rows(id0) -= psr*LAMBDA.rows(id0)*VL;\n        c3.rows(id0) -= psr*LAMBDA.rows(id0)*ML2;\n        \n        K_tmp1 = ML2pVL.rows(id0);\n        K_tmp1.each_row() %= mD2pvD.t();\n        K_tmp2 = ML2.rows(id0);\n        K_tmp2.each_row() %= mD2.t();\n        c4.rows(id0) -= psr*(K_tmp1*ML2pVL.t()-K_tmp2*ML2.t()+square(LDL));\n    }\n\n\n\n\n    ML.elem(idl) = h/zeta;\n    VL.elem(idl) = 1/zeta;\n    mD = alpha/beta;\n    vD = mD/beta;\n    auto t_end = std::chrono::high_resolution_clock::now();\n    double ElapsedTime = std::chrono::duration<double, std::milli>(t_end-t_start).count() / 1e3;\n    if (kappa < maxIter && difmL<tol) mexPrintf(\"BISN converges, elapsed time is %e seconds.\\n\",ElapsedTime);\n    else mexPrintf(\"BISN reaches the maximum number of iterations, elapsed time is %e seconds.\\n\",ElapsedTime);\n\n    /* Output Interface */\n    if (nlhs>3)\n    {\n        plhs[0] = armaCreateMxMatrix(p,p,mxDOUBLE_CLASS,mxREAL);\n        armaSetPr(plhs[0],ML);\n        plhs[1] = armaCreateMxMatrix(p,p,mxDOUBLE_CLASS,mxREAL);\n        armaSetPr(plhs[1],VL);\n        plhs[2] = armaCreateMxMatrix(p,1,mxDOUBLE_CLASS,mxREAL);\n        armaSetPr(plhs[2],mD);\n        plhs[3] = armaCreateMxMatrix(p,1,mxDOUBLE_CLASS,mxREAL);\n        armaSetPr(plhs[3],vD);\n        if (nlhs>4)\n        {\n            omega = a/b;\n            plhs[4] = mxCreateDoubleScalar(omega);\n        }\n        if (nlhs>5)\n        {\n            lambda = d;\n            lambda.transform([](double val){return (val > 10) ? Lentz_Algorithm(val) : (- boost::math::expint(-val) * exp(val));});\n            lambda = 1/(d%lambda)-1;\n            plhs[5] = armaCreateMxMatrix(pe,1,mxDOUBLE_CLASS,mxREAL);\n            armaSetPr(plhs[5],lambda);\n        }\n        if (nlhs>6) plhs[6] = mxCreateDoubleScalar(ElapsedTime);\n    }\n    else\n    {\n        mexErrMsgIdAndTxt(\"BINS:output\",\"Expected at least four output arguments\");\n    }\n\n}\n", "meta": {"hexsha": "ad34409b8c88fab185987dcec263e59c22a2c3ed", "size": 9784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BISN.cpp", "max_stars_repo_name": "fhlyhv/BISN_matlab_wrapper", "max_stars_repo_head_hexsha": "81037c0a8dcfab3058e22dec428ded24f76eaccc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BISN.cpp", "max_issues_repo_name": "fhlyhv/BISN_matlab_wrapper", "max_issues_repo_head_hexsha": "81037c0a8dcfab3058e22dec428ded24f76eaccc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-21T01:00:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-21T01:00:25.000Z", "max_forks_repo_path": "BISN.cpp", "max_forks_repo_name": "fhlyhv/BISN_matlab_wrapper", "max_forks_repo_head_hexsha": "81037c0a8dcfab3058e22dec428ded24f76eaccc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8643533123, "max_line_length": 183, "alphanum_fraction": 0.5212591987, "num_tokens": 3518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6140655402410079}}
{"text": "// Copyright (c) 2015-2019 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#include \"genotype.hpp\"\n\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\n#include \"utils/maths.hpp\"\n\nnamespace octopus {\n\n// non-member methods\n\nGenotype<Haplotype> remap(const Genotype<Haplotype>& genotype, const GenomicRegion& region)\n{\n    Genotype<Haplotype> result {genotype.ploidy()};\n    for (const auto& haplotype : genotype) result.emplace(remap(haplotype, region));\n    return result;\n}\n\nstd::size_t num_genotypes(const unsigned num_elements, const unsigned ploidy)\n{\n    return boost::math::binomial_coefficient<double>(num_elements + ploidy - 1, num_elements - 1);\n}\n\nboost::optional<std::size_t> num_genotypes_noexcept(const unsigned num_elements, const unsigned ploidy) noexcept\n{\n    boost::optional<std::size_t> result {};\n    try {\n        result = num_genotypes(num_elements, ploidy);\n    } catch (...) {}\n    return result;\n}\n\nstd::size_t max_num_elements(const std::size_t num_genotypes, const unsigned ploidy)\n{\n    if (num_genotypes == 0 || ploidy == 0) return 0;\n    auto y = maths::factorial<std::size_t>(ploidy);\n    if (y >= num_genotypes) return 1;\n    const auto t = num_genotypes * y;\n    unsigned j {1};\n    for (; j < num_genotypes; ++j) {\n        y /= j;\n        y *= j + ploidy;\n        if (y >= t) break;\n    }\n    return j + 1;\n}\n\nstd::size_t element_cardinality_in_genotypes(const unsigned num_elements, const unsigned ploidy)\n{\n    return ploidy * (num_genotypes(num_elements, ploidy) / num_elements);\n}\n\nstd::size_t num_max_zygosity_genotypes(const unsigned num_elements, const unsigned ploidy)\n{\n    namespace bmp = boost::math::policies;\n    using policy = bmp::policy<bmp::overflow_error<bmp::throw_on_error>>;\n    try {\n        return boost::numeric_cast<std::size_t>(boost::math::binomial_coefficient<double>(num_elements, ploidy, policy {}));\n    } catch (const boost::numeric::positive_overflow& e) {\n        throw std::overflow_error {e.what()};\n    }\n}\n\nboost::optional<std::size_t> num_max_zygosity_genotypes_noexcept(unsigned num_elements, unsigned ploidy) noexcept\n{\n    assert(num_elements >= ploidy);\n    boost::optional<std::size_t> result {};\n    try {\n        result = num_max_zygosity_genotypes(num_elements, ploidy);\n    } catch (...) {}\n    return result;\n}\n\n} // namespace octopus\n", "meta": {"hexsha": "6ae6c8925b3c011aadaff1c140c6b917d2ab6391", "size": 2429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/types/genotype.cpp", "max_stars_repo_name": "gunjanbaid/octopus", "max_stars_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_stars_repo_licenses": ["MIT"], "max_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/types/genotype.cpp", "max_issues_repo_name": "gunjanbaid/octopus", "max_issues_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/types/genotype.cpp", "max_forks_repo_name": "gunjanbaid/octopus", "max_forks_repo_head_hexsha": "b19e825d10c16bc14565338aadf4aee63c8fe816", "max_forks_repo_licenses": ["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.141025641, "max_line_length": 124, "alphanum_fraction": 0.6986414162, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.6140655255792977}}
{"text": "#include \"NelderMead.hpp\"\n\n#include <iostream>\n#include <Eigen/Dense>\n\nclass Example : public NelderMead<Eigen::VectorXd, double> {\n    double f(const Eigen::VectorXd& ys){\n        double res = 0.0;\n        double m = 1.0;\n        for(int i=0; i<ys.size(); i++){\n            res += m*std::abs(ys[i]);\n            m*=10000.0;\n        }\n        return res;\n    }\n};\n\n\nint main(){\n    std::vector<Eigen::VectorXd> xs;\n        \n    xs.push_back(Eigen::Vector2d(1, 101));\n    xs.push_back(Eigen::Vector2d(2, 100));\n    xs.push_back(Eigen::Vector2d(3, 101));\n\n    Example q;\n    q.setSimplex(xs);\n    for(int i=0; i<200; i++){\n        q.iterate();\n        std::cout<<q.current().first<<\"\\n\";\n    }\n}\n", "meta": {"hexsha": "9ed796b26f34e0cc541699fbd26470db8dc59031", "size": 694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example.cpp", "max_stars_repo_name": "waterlaz/NelderMead", "max_stars_repo_head_hexsha": "bd9418c3cc0fa4c687e42be7743d0b27cd4c48c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example.cpp", "max_issues_repo_name": "waterlaz/NelderMead", "max_issues_repo_head_hexsha": "bd9418c3cc0fa4c687e42be7743d0b27cd4c48c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example.cpp", "max_forks_repo_name": "waterlaz/NelderMead", "max_forks_repo_head_hexsha": "bd9418c3cc0fa4c687e42be7743d0b27cd4c48c0", "max_forks_repo_licenses": ["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.0303030303, "max_line_length": 60, "alphanum_fraction": 0.5317002882, "num_tokens": 212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.614011829154728}}
{"text": "#include <armadillo>\n#include <cstring>\n#include <ctime>\n#include \"gyro_rocket6g.hh\"\n#include \"matrix_tool.hh\"\n#include \"stochastic.hh\"\n\n\n\nGyroRocket6G::GyroRocket6G()\n{\n    snprintf(name, sizeof(name), \"Rocket6G Gyro Sensor Model\");\n    srand(static_cast<unsigned int>(time(NULL)));\n}\n\nvoid GyroRocket6G::algorithm(LaunchVehicle *VehicleIn)\n{\n    arma::vec3 WBIB = VehicleIn->DM->WBIB;\n\n    //-------------------------------------------------------------------------\n    // ARW RRW\n    double sig(1.0);\n    double RRW(0.0130848811);  // 0.4422689813  7.6072577e-3\n    double ARW(0.2828427125);  // 0.07071067812  7.90569415e-3\n    double Freq(200.0);\n\n    for (int i = 0; i < 3; i++) {\n        VehicleIn->Sensor->ITA2_G(i) =\n            gauss(0, 1.0) * RRW * RAD;  // distribution(generator) * RRW * RAD;\n        VehicleIn->Sensor->BETA_G(i) = 0.9999 * VehicleIn->Sensor->BETA_G(i) +\n                                       VehicleIn->Sensor->ITA2_G(i) * VehicleIn->dt;\n        VehicleIn->Sensor->ITA1_G(i) = gauss(0, 1.0) *\n                                       (ARW * sqrt(Freq) / 60. * (1 / sig)) *\n                                       RAD;  // distribution(generator) * (ARW *\n                                             // sqrt(Freq) / 60 * (1 / sig)) * RAD;\n    }\n\n    // combining all uncertainties\n    VehicleIn->Sensor->EWBIB = VehicleIn->Sensor->ITA1_G +\n                               VehicleIn->Sensor->BETA_G;  // EMSBG + EUG + EWG;\n\n    VehicleIn->Sensor->WBICB = WBIB + VehicleIn->Sensor->EWBIB;\n\n    return;\n}\n", "meta": {"hexsha": "f17b342566b2aaf52eceed798cde4ebcd18c1a60", "size": 1530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/sensor_dm/gyro/gyro_rocket6g.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/sensor_dm/gyro/gyro_rocket6g.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/sensor_dm/gyro/gyro_rocket6g.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": 33.2608695652, "max_line_length": 84, "alphanum_fraction": 0.5169934641, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.6140118224659318}}
{"text": "// Copyright (C) 2018-2020 Chris Richardson (chris@bpi.cam.ac.uk)\n// SPDX-License-Identifier:    MIT\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <chrono>\n#include <iostream>\n#include <memory>\n#include <mpi.h>\n\n#include \"CreateA.h\"\n#include <spmv/L2GMap.h>\n#include <spmv/read_petsc.h>\n\nvoid restrict_main()\n{\n  int mpi_rank;\n  MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);\n  int mpi_size;\n  MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);\n\n  // Keep list of timings\n  std::map<std::string, std::chrono::duration<double>> timings;\n\n  auto timer_start = std::chrono::system_clock::now();\n  // Read in a PETSc binary format matrix\n  auto R = spmv::read_petsc_binary_matrix(MPI_COMM_WORLD, \"R4.dat\");\n  auto q = spmv::read_petsc_binary_vector(MPI_COMM_WORLD, \"b4.dat\");\n\n  // Get local and global sizes\n  std::int64_t M = R.rows();\n  auto l2g = R.col_map();\n  std::int64_t N = l2g->global_size();\n\n  std::cout << \"Vector = \" << q.size() << \" \" << M << \"\\n\";\n\n  auto timer_end = std::chrono::system_clock::now();\n  timings[\"0.PetscRead\"] += (timer_end - timer_start);\n\n  timer_start = std::chrono::system_clock::now();\n\n  if (mpi_rank == 0)\n    std::cout << \"Creating vector of size \" << N << \"\\n\";\n\n  // Vector in \"column space\" with extra space for ghosts at end\n  Eigen::VectorXd psp(l2g->local_size() + l2g->num_ghosts());\n\n  timer_end = std::chrono::system_clock::now();\n  timings[\"1.VecCreate\"] += (timer_end - timer_start);\n\n  // Apply matrix\n  if (mpi_rank == 0)\n    std::cout << \"Applying matrix\\n\";\n\n  double pnorm_sum, qnorm_sum;\n  for (int i = 0; i < 10; ++i) {\n    // Restrict\n    timer_start = std::chrono::system_clock::now();\n    psp = R.transpmult(q);\n\n    timer_end = std::chrono::system_clock::now();\n    timings[\"3.SpMV\"] += (timer_end - timer_start);\n\n    timer_start = std::chrono::system_clock::now();\n    l2g->reverse_update(psp.data());\n    timer_end = std::chrono::system_clock::now();\n    timings[\"2.SparseUpdate\"] += (timer_end - timer_start);\n\n    Eigen::Map<Eigen::VectorXd> p(psp.data(), l2g->local_size());\n    double pnorm = p.squaredNorm();\n    MPI_Allreduce(&pnorm, &pnorm_sum, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n\n    // Prolongate\n    timer_start = std::chrono::system_clock::now();\n    l2g->update(psp.data());\n    timer_end = std::chrono::system_clock::now();\n    timings[\"2.SparseUpdate\"] += (timer_end - timer_start);\n\n    timer_start = std::chrono::system_clock::now();\n    q = R.mult(psp);\n\n    timer_end = std::chrono::system_clock::now();\n    timings[\"3.SpMV\"] += (timer_end - timer_start);\n\n    double qnorm = q.squaredNorm();\n    MPI_Allreduce(&qnorm, &qnorm_sum, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n  }\n\n  if (mpi_rank == 0)\n    std::cout << \"\\nTimings (\" << mpi_size\n              << \")\\n----------------------------\\n\";\n\n  std::chrono::duration<double> total_time\n      = std::chrono::duration<double>::zero();\n  for (auto q : timings)\n    total_time += q.second;\n  timings[\"Total\"] = total_time;\n\n  for (auto q : timings) {\n    double q_local = q.second.count(), q_max, q_min;\n    MPI_Reduce(&q_local, &q_max, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);\n    MPI_Reduce(&q_local, &q_min, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD);\n\n    if (mpi_rank == 0) {\n      std::string pad(16 - q.first.size(), ' ');\n      std::cout << \"[\" << q.first << \"]\" << pad << q_min << '\\t' << q_max\n                << \"\\n\";\n    }\n  }\n\n  if (mpi_rank == 0) {\n    std::cout << \"----------------------------\\n\";\n    std::cout << \"norm q = \" << qnorm_sum << \"\\n\";\n    std::cout << \"norm p = \" << pnorm_sum << \"\\n\";\n  }\n}\n//-----------------------------------------------------------------------------\nint main(int argc, char** argv)\n{\n#ifdef _OPENMP\n  int provided;\n  MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided);\n  if (provided < MPI_THREAD_FUNNELED) {\n    std::cout << \"The threading support level is lesser than required\"\n              << std::endl;\n    MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE);\n  }\n#else\n  MPI_Init(&argc, &argv);\n#endif\n\n  restrict_main();\n\n  MPI_Finalize();\n  return 0;\n}\n", "meta": {"hexsha": "4d04d3bf226b08b72ecb218b67a5ffdb7db58104", "size": 4047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/restrictmain.cpp", "max_stars_repo_name": "Excalibur-SLE/spmv", "max_stars_repo_head_hexsha": "7bd7aa05c5c7018c807160e1d1d70b11a8143eca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/restrictmain.cpp", "max_issues_repo_name": "Excalibur-SLE/spmv", "max_issues_repo_head_hexsha": "7bd7aa05c5c7018c807160e1d1d70b11a8143eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-04T15:55:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T15:56:02.000Z", "max_forks_repo_path": "demos/restrictmain.cpp", "max_forks_repo_name": "Excalibur-SLE/spmv", "max_forks_repo_head_hexsha": "7bd7aa05c5c7018c807160e1d1d70b11a8143eca", "max_forks_repo_licenses": ["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.5401459854, "max_line_length": 79, "alphanum_fraction": 0.6073634791, "num_tokens": 1174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6138947365389215}}
{"text": "/**\n * @author      Mahdi Maghrebi <mahdi.maghrebi@nih.gov>\n * October 2019\n * This is the Implementation of K-NN Algorithm in Distributed Systems as developed \n * in \"PANDA: Extreme Scale Parallel K-Nearest Neighbor on Distributed Architectures\", Patwary et a., 2016\n */\n\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <mpi.h>\n#include <math.h>\n#include <vector>\n#include <stack>\n#include <boost/iostreams/device/mapped_file.hpp> \n#include <boost/iostreams/stream.hpp>             \n#include <set>\n#include <omp.h>\n#include <iomanip>\n\nusing namespace std;\n/**\n * Read the output of linux command execution \n * @param  cmd  is the inux command to be executed\n * @return the output from the execution of the linux command\n */\nstd::string exec(const char* cmd) {\n\tstd::array<char, 128> buffer;\n\tstd::string result;\n\tstd::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, \"r\"), pclose);\n\tif (!pipe) {\n\t\tthrow std::runtime_error(\"popen() failed!\");\n\t}\n\twhile (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {\n\t\tresult += buffer.data();\n\t}\n\treturn result;\n}\n/**\n * Defining the criteria for Sorting the data in a pair container from the biggest value to the smallest\n */\nbool sortinrev(const pair<double,int> &a,const pair<double,int> &b) { \n\treturn (a.first > b.first); \n} \n/**\n * Compute the variance of a sampled data over data dimensions and Sort dimensions according to their variability\n * @param   DataCounts  Number of total data from which we take the samples\n * @param   nodeData0 Dataset containing the data available for sampling\n * @param   featureCounts Number of features in dataset (equal to number of columns in the input csv file)\n * @param   world_size  Total number of MPI processors\n * @param\tglobalKdTreeSamples Number of Samples from dataset for computation here \t \n * @return  VectorGlobalSqrtSum A sorted pair containig the index of the dimensions with the highest variability \n */\nauto findMaxVarDims(int DataCounts,double **nodeData0, int featureCounts, int world_size, int globalKdTreeSamples) {\n\tdouble samplingData[globalKdTreeSamples][featureCounts];\n\tdouble localSum[featureCounts], globalSum[featureCounts];\n\tdouble localSqrtSum[featureCounts], globalSqrtSum[featureCounts];\t\n\n\tfor (int j=0; j<featureCounts; ++j){\n\t\tlocalSum[j]=0;\n\t\tlocalSqrtSum[j]=0;\n\t}\n\n\tfor (int i=0; i< globalKdTreeSamples; ++i){\n\t\tint randomIndex=rand()%DataCounts;\n\t\tfor (int j=0; j<featureCounts; ++j){\n\t\t\tsamplingData[i][j]=nodeData0[randomIndex][j];\n\t\t\tlocalSum[j]+=samplingData[i][j];\t\n\t\t}\n\t}\t\n\n\tMPI_Allreduce(localSum,globalSum,featureCounts,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);\t\t\n\n\tfor (int i=0; i< globalKdTreeSamples; ++i){\n\t\tfor (int j=0; j<featureCounts; ++j){\n\t\t\tlocalSqrtSum[j]+=pow((samplingData[i][j]-(globalSum[j]/world_size/globalKdTreeSamples)),2) ;\n\t\t}\n\t}\n\n\tMPI_Allreduce(localSqrtSum,globalSqrtSum,featureCounts,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);\n\n\tvector<pair<double,int>> VectorGlobalSqrtSum;\n\n\tfor (int j=0; j<featureCounts; ++j){\n\t\tVectorGlobalSqrtSum.push_back(make_pair(globalSqrtSum[j],j));\n\t}\n\tsort(VectorGlobalSqrtSum.begin(), VectorGlobalSqrtSum.end(),sortinrev);\n\treturn VectorGlobalSqrtSum;\t\t\t\n}\n/**\n * Compute the distance between 2 data points within the same bucket\n * @param  index Index of the first data point\n * @param  index2 Index of the second data point\n * @param  mappedData2 2D array containing dataset\towned by each processor\t \n * @param  featureCounts Number of features in dataset (equal to number of columns in the input csv file)\n * @return sqrt(dist) The distance between 2 data points within the same bucket\n */\ndouble computeDistance (int index,int index2, double** mappedData2, int featureCounts){\t\t\n\tdouble dist=0;\n\tfor (int i=0; i<featureCounts; ++i){\n\t\tdouble differences=mappedData2[index][i]-mappedData2[index2][i];\n\t\tdist+=differences*differences;\n\t}\n\treturn sqrt(dist);\t\n}\n/**\n * Compute the distance between 2 data points during querying\n * @param   index Index of the first data point\n * @param   i Index of the processor that has sent query\n * @param   jj Beginning index of the desired data point in the received data from the querying processor\n * @param   mappedData2 2D array containing dataset\towned by the current processor\t \t \n * @param   receivingPointCoordinates 2D array containing data received from the querying processors\t \n * @param   featureCounts Number of features in dataset (equal to number of columns in the input csv file)\n * @return sqrt(dist) The distance between 2 data points \n */\t\ndouble computeDistance2 (int index, int i, int jj, double** mappedData2, double** receivingPointCoordinates,int featureCounts ){\t\n\tdouble dist=0;\n\tfor (int k=0; k<featureCounts; ++k){\n\t\tdouble differences= mappedData2[index][k]-receivingPointCoordinates[i][jj+k];\n\t\tdist+=differences*differences;\n\t}\n\treturn sqrt(dist);\t\n}\n/**\n * Compute the median of data at a dividing node of the global Kd Tree\n * @param  maxVarDimension Index of the chosen dimension for computing median\n * @param  nodeDataIndex0 Vector containing the indices of data available at the dividing node\n * @param   globalKdTreeSamplesMedian Number of data sampled by each processor to collaboratively compute the median at the dividing node of the global Kd tree\n * @param   Epsilon The acceptable buffer in estimating the median\t \n * @param   world_size Total number of MPI processors\n * @param   world_rank Rank of each MPI processor\n * @param\tdata 2D array containing the datapoint coordinates owned by each processor\n * @return  MedianCandidate The estimated value of median at the dividing node \n */\t\t\ndouble globalFindMedian (int maxVarDimension, vector<int> nodeDataIndex0, int globalKdTreeSamplesMedian, double Epsilon, int world_size, int world_rank, double** data) {\t\n\tint randomIndex;\t\n\tvector <double> sampledDataValues, leftSampledDataValues, rightSampledDataValues;\n\tsampledDataValues.reserve(globalKdTreeSamplesMedian);\n\tleftSampledDataValues.reserve(globalKdTreeSamplesMedian);\n\trightSampledDataValues.reserve(globalKdTreeSamplesMedian);\n\n\tfor (int i=0; i< globalKdTreeSamplesMedian; ++i){\n\t\trandomIndex=rand()%nodeDataIndex0.size();\n\t\tint index=nodeDataIndex0[randomIndex];  \n\t\tsampledDataValues.push_back(data[index][maxVarDimension]);\n\t}\n\n\tint randomRank;\n\tdouble MedianCandidate;\n\tint totalCountsData=world_size*globalKdTreeSamplesMedian;\n\tint accumulatedLeftCounts=0;\n\tbool whileFlag=true;\n\tint whileCount=0;\n\n\twhile(whileFlag){\n\t\tif (world_rank==0) {randomRank=rand()%world_size;}\n\t\tMPI_Bcast(&randomRank,1,MPI_INT,0,MPI_COMM_WORLD);       \n\n\t\tif (world_rank==randomRank) {\n\t\t\trandomIndex=rand()%sampledDataValues.size();\n\t\t\tMedianCandidate=sampledDataValues[randomIndex];\n\t\t}\n\t\tMPI_Bcast(&MedianCandidate,1,MPI_DOUBLE,randomRank,MPI_COMM_WORLD);\n\n\t\tint leftCounts=0; int rightCounts=0;int globalleftCounts=0;\n\t\tleftSampledDataValues.clear();\n\t\trightSampledDataValues.clear();\n\n\t\tfor (int i=0; i<sampledDataValues.size() ; ++i){\n\t\t\tif (sampledDataValues[i] < MedianCandidate) {\n\t\t\t\tleftSampledDataValues.push_back(sampledDataValues[i]);\n\t\t\t\t++leftCounts;\n\t\t\t}\n\t\t\telse{ \n\t\t\t\trightSampledDataValues.push_back(sampledDataValues[i]);\n\t\t\t\t++rightCounts;        \n\t\t\t}\n\t\t}\n\n\t\tMPI_Allreduce(&leftCounts,&globalleftCounts,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);\n\t\tgloballeftCounts+=accumulatedLeftCounts;\n\t\tdouble ratio= double(globalleftCounts)/totalCountsData;\n\n\t\tif ( ratio < 0.5+Epsilon && ratio > 0.5-Epsilon ) {\n\t\t\twhileFlag=false;\n\t\t\treturn MedianCandidate ;}\n\t\telse if (ratio < 0.5-Epsilon){\n\t\t\taccumulatedLeftCounts=globalleftCounts;\n\t\t\tsampledDataValues.clear();\n\t\t\tsampledDataValues=rightSampledDataValues;    \n\t\t}\n\n\t\t++whileCount;\n\t\t// For diagnosis, the following error hints at the difficulty of finding the median \t\n\t\tMPI_File logfile;\n\t\tchar line[1024];\n\t\tif (whileCount % 10000 == 0) {\n\t\t\tprintf(\"Too Many Trials for Global KD Tree Median, Processor = %d \\n\",world_rank);\n\t\t\tsprintf(line,\"Too Many Trials for Global KD Tree Median, Processor = %d \\n\",world_rank);\n\t\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\n\t\t}\n\t}\n}\n/**\n * Compute the median of data at a dividing node of the local Kd Tree\n * @param  localKdTreeSamplesMedian Number of samples used to compute the median\n * @paramn  sampledDataValues The coordinates of the sampled data\n * @param   Epsilon The acceptable buffer in estimating the median\t \n * @param   world_rank Rank of each MPI processor\n * @return  MedianCandidate The estimated value of median at the dividing node \n */\t\t\ndouble localFindMedian (int localKdTreeSamplesMedian,vector<double> sampledDataValues, double Epsilon, int world_rank) {\t\n\tvector <double> leftSampledDataValues, rightSampledDataValues;\n\tleftSampledDataValues.reserve(localKdTreeSamplesMedian);\n\trightSampledDataValues.reserve(localKdTreeSamplesMedian);\n\n\tint accumulatedLeftCounts=0;\n\tbool whileFlag=true;\n\tint whileCount=0;\n\n\twhile(whileFlag){    \n\t\tint randomIndex=rand()%sampledDataValues.size();\n\t\tdouble MedianCandidate=sampledDataValues[randomIndex];\t\n\t\tint leftCounts=0;\n\t\tint rightCounts=0;\n\t\tleftSampledDataValues.clear();\n\t\trightSampledDataValues.clear();\n\n\t\tfor (int i=0; i<sampledDataValues.size() ; ++i){\n\t\t\tif (sampledDataValues[i] < MedianCandidate) {\n\t\t\t\tleftSampledDataValues.push_back(sampledDataValues[i]);\n\t\t\t\t++leftCounts;\n\t\t\t}\n\t\t\telse{ \n\t\t\t\trightSampledDataValues.push_back(sampledDataValues[i]);\n\t\t\t\t++rightCounts;        \n\t\t\t}\n\t\t}\n\t\tleftCounts+=accumulatedLeftCounts;\n\t\tdouble ratio= double(leftCounts)/localKdTreeSamplesMedian;\n\n\t\tif ( ratio < 0.5+Epsilon && ratio > 0.5-Epsilon ) {\n\t\t\twhileFlag=false;\t\n\t\t\treturn MedianCandidate;\n\t\t}\n\t\telse if (ratio < 0.5-Epsilon){\n\t\t\taccumulatedLeftCounts=leftCounts;\n\t\t\tsampledDataValues.clear();\n\t\t\tsampledDataValues=rightSampledDataValues;    \n\t\t\twhileFlag=true;\n\t\t}\n\t\telse if (ratio > 0.5+Epsilon){\n\t\t\twhileFlag=true;\n\t\t}\n\t\t++whileCount;\n\n\t\tif (whileCount % 10000 == 0) {\n\t\t\tif (Epsilon<0.25) Epsilon*=2; \n\t\t\telse return MedianCandidate;\n\t\t}\n\t}\n}\n/**\n * Sort the max-heap data structure for a new data inserted at its index i \n * @param  ID The ID of the point data\n * @paramn  i Index of the inserted data in the Heap \n * @param   KNNDistanceinBuckets The values of distances for selected K-NNs    \t \n * @param   KNNIDsinBuckets The IDs of the selected K-NNs\n * @param   KNNCounts  Desired count of K-NNs to be computed in this program\t  \n */\t\t\t\nvoid Max_Heapify(int ID, int i, double ** KNNDistanceinBuckets, int ** KNNIDsinBuckets,int KNNCounts) {\n\tint largest = 0;\n\tint l = 2*i + 1; \n\tint r = 2*i + 2;\n\n\tif ((l < KNNCounts) && (KNNDistanceinBuckets[ID][l] > KNNDistanceinBuckets[ID][i])) {\n\t\tlargest = l;\n\t}\n\telse {\n\t\tlargest = i;\n\t}\n\n\tif ((r < KNNCounts) && (KNNDistanceinBuckets[ID][r] > KNNDistanceinBuckets[ID][largest])) {\n\t\tlargest = r;\n\t}\n\n\tif (largest != i) {\n\t\tstd::swap(KNNDistanceinBuckets[ID][i], KNNDistanceinBuckets[ID][largest]);\n\t\tstd::swap(KNNIDsinBuckets[ID][i], KNNIDsinBuckets[ID][largest]);\n\t\tMax_Heapify(ID, largest, KNNDistanceinBuckets, KNNIDsinBuckets,KNNCounts);\n\t}\n}\n/**\n * Build Max-Heap datat structure for the first time\n * @param  ID The ID of the point data\n * @param   KNNCounts  Desired count of K-NNs to be computed in this program\n * @param   KNNDistanceinBuckets The values of distances for selected K-NNs    \t \n * @param   KNNIDsinBuckets The IDs of the selected K-NNs\t  \n */\t\nvoid Build_Max_Heap(int ID,int KNNCounts, double** KNNDistanceinBuckets, int** KNNIDsinBuckets) {\n\tfor (int i = floor((KNNCounts - 1) / 2); i >= 0; i--) {\n\t\tMax_Heapify(ID, i,KNNDistanceinBuckets, KNNIDsinBuckets,KNNCounts);\n\t}\n}\n/**\n * Sort the max-heap data structure for a newly inserted data\n * @param   k The index of the inserted point data\n * @param   receivingHeapArrayDistances2DCopy The values of distances for selected K-NNs    \t \n * @param   receivingHeapArray2DCopy The IDs of the selected K-NNs\n * @param   KNNCounts  Desired count of K-NNs to be computed in this program\t  \n */\t\t\nvoid Max_Heapify2 (int k, double * receivingHeapArrayDistances2DCopy, int * receivingHeapArray2DCopy,int KNNCounts) {\n\tint largest = 0;\n\tint l = 2*k + 1; \n\tint r = 2*k + 2;\n\n\tif ((l < KNNCounts) && (receivingHeapArrayDistances2DCopy[l] > receivingHeapArrayDistances2DCopy[k])) {\n\t\tlargest = l;\n\t}\n\telse {\n\t\tlargest = k;\n\t}\n\n\tif ((r < KNNCounts) && (receivingHeapArrayDistances2DCopy[r] > receivingHeapArrayDistances2DCopy[largest])) {\n\t\tlargest = r;\n\t}\n\n\tif (largest != k) {\n\t\tstd::swap(receivingHeapArrayDistances2DCopy[k], receivingHeapArrayDistances2DCopy[largest]);\n\t\tstd::swap(receivingHeapArray2DCopy[k], receivingHeapArray2DCopy[largest]);\n\t\tMax_Heapify2(largest,receivingHeapArrayDistances2DCopy,receivingHeapArray2DCopy,KNNCounts);\n\t}\n}\n/**\n * Build Max-Heap datat structure for the first time\n * @param   KNNCounts  Desired count of K-NNs to be computed in this program\n * @param   receivingHeapArrayDistances2DCopy The values of distances for selected K-NNs    \t \n * @param   receivingHeapArray2DCopy The IDs of the selected K-NNs\t  \n */\t\nvoid Build_Max_Heap2(int KNNCounts, double* receivingHeapArrayDistances2DCopy, int* receivingHeapArray2DCopy) {\n\tfor (int ii = floor((KNNCounts - 1) / 2); ii >= 0; ii--) {\n\t\tMax_Heapify2(ii,receivingHeapArrayDistances2DCopy,receivingHeapArray2DCopy,KNNCounts);\n\t}\n}\n\n\n/**\n * Main Function of the Code\n */\t\t\t\nint main(int argc, char * const argv[]) {\n\t/**\t\n\t * MPI Parallel Logfile\n\t */\t\t\n\tMPI_File logfile;\n\tchar line[1024];\n\t/**\t\n\t * Beginning MPI communications\n\t */\t\t\t\n\tMPI_Init(NULL, NULL);\n\t/**\t\n\t * world_size is defined here as total number of MPI processors\n\t */\t\n\tint world_size;\n\tMPI_Comm_size(MPI_COMM_WORLD, &world_size);\n\t/**\t\n\t * world_rank is defined here as the rank of MPI processors\n\t */\t\n\tint world_rank;\n\tMPI_Comm_rank(MPI_COMM_WORLD, &world_rank);\n\t/**\n\t * The errors and informational messages are outputted to the log file \n\t */\t\n\tMPI_File_open(MPI_COMM_WORLD, \"Setting.txt\", MPI_MODE_WRONLY | MPI_MODE_CREATE,MPI_INFO_NULL, &logfile);\t\t\n\t/**\n\t * The following arguments are passed to the code (in order) from the command line:\n\t * fileName is the full path to the input csv dataset\n\t * KNNCounts is the desired number of K-NNs for each data point to be computed in this code\n\t * featureCounts is the number of columns in the input csv datastet (number of data dimensions)\n\t */\t\n\tstring fileName = argv[1]; \t\n\tconst int KNNCounts = atoi(argv[2]); \t\t\n\n\tint featureCounts, colIndex1, colIndex2;\n\tif (argc == 3) {\n\t\tstring cmd0=\"head -n 1 \"+ fileName + \" |tr '\\\\,' '\\\\n' |wc -l \";\n\t\tfeatureCounts = stoi(exec(cmd0.c_str())); \n\t} else if (argc == 5) {\n\t\tstring cmd0=\"head -n 1 \"+ fileName + \" |tr '\\\\,' '\\\\n' |wc -l \";\n\t\tfeatureCounts = stoi(exec(cmd0.c_str())); \n\t\tcolIndex1 = atoi(argv[3]); \n\t\tcolIndex2 = atoi(argv[4]); \n\t} else \t{\n\t\tprintf(\"Wrong Input Arguments\\n\");\n\t\tsprintf(line,\"Wrong Input Arguments\\n\");\n\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE); \n\t\treturn -1;\n\t}\n\t/**\t\n\t * The following important parameters are used in the design of algorithm. Their values are\n\t * initialized according to the suggested values in the referencing paper.\n\t * globalKdTreeSamples is the number of data sampled by each processor to collaboratively compute dimensions with the highest variability.\n\t * globalKdTreeSamplesMedian is the number of data sampled by each processor to collaboratively compute the median of the chosen dimension for each splitting node within the global Kd Tree.\n\t * localKdTreeSamplesMedian is the number of data sampled by each processor separately to compute the median of the chosen dimension for each splitting node within the local Kd Tree.\n\t * Epsilon is a buffer in accepting the Median value\n\t * Parallel_IO is a flag that defines if the input csv file can be read in parallel by all the processors\n\t * bucketSize is the size of a bucket (or a leaf) in the local Kd Tree\n\t * estimatedExtraLayers: To limit the growing size of the local Kd Trees, the growth of the tree is limited by a number of layers defined here from the initial guess of the required buckets\n\t */\t\t\n\tconst int globalKdTreeSamples=256;\t\n\tconst int globalKdTreeSamplesMedian=256;\n\tint localKdTreeSamplesMedian=1024;\n\tdouble Epsilon=0.01; \n\tconst int Parallel_IO = 1; \n\tconst int bucketSize=32;\n\tconst int estimatedExtraLayers=1;\n\t/**\t\n\t * Seed for random number generation\n\t */\t\n\tsrand(17);\n\t/**\t\n\t * total number of MPI processors should be a power of 2 due to algorithm design for global Kd Tree.\n\t * Otherwise, output an error and exit the program\n\t */\t\n\tbool powerOfTwo = !(world_size == 0) && !(world_size & (world_size - 1));\n\tif (powerOfTwo!=true) {\n\t\tif (world_rank==0) {\n\t\t\tprintf(\"Number of Processors should be a power of 2\\n\");\n\t\t\tsprintf(line,\"Number of Processors should be a power of 2\\n\");\n\t\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\n\t\t}\n\t\tMPI_Finalize();\n\t\treturn 0;\n\t}\t\n\tint numericWidth=floor(log10(world_size) + 1);\t\t\n\t/**\t\n\t * The master processor splits the input csv file as each processor could have its own non-overlapping set of input data\n\t */\n\tif (world_rank==0) {\n\t\tstring cmd=string(\"split -n l/\")+to_string(world_size)+\" \"+ fileName+\" -a \"+to_string(numericWidth)+\" -d tmpFile --additional-suffix=.csv\"; \n\t\tint returnValue=system(cmd.c_str());\n\t}\n\t/**\t\n\t * All procesors neeed to stop here until master processor returns\n\t */\n\tMPI_Barrier(MPI_COMM_WORLD);\n\t/**\t\n\t * Each processor reads its own set of data from a unique csv file (localFileName)\n\t */\t\n\tint worldRankWidth=floor(log10(world_rank) + 1);\n\tstd::stringstream ss;\n\tss << std::setw(numericWidth-worldRankWidth) << std::setfill('0') << world_rank;\n\tstd::string s = ss.str();\n\tstring localFileName=\"tmpFile\"+s+\".csv\";\n\n\tifstream infile;   \n\tinfile.open(localFileName); \n\t/**\t\n\t * Output error in case the localFileName was not opened for reading\n\t */\t\n\tif(infile.fail()) { \n\t\tprintf(\"error in opening the input file\\n\");\n\t\tsprintf(line,\"error in opening the input file\\n\");\n\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\n\t\treturn 1; \n\t} \n\t/**\t\n\t * Each processor finds out about the number of records in its localFileName\n\t */\t\n\tstring cmd3=\"wc -l \"+localFileName;\n\tstring outputCmd3 = exec(cmd3.c_str());\n\tint tmpFileLineCounts=stoi(outputCmd3.substr(0, outputCmd3.find(\" \")));\n\t/**\t\n\t * The master node needs to subtract 1 record which is for header information\n\t */\t\n\tif (world_rank==0) {\n\t\tstring dummyLine;\n\t\tgetline(infile, dummyLine);\n\t\t--tmpFileLineCounts;\n\t} \n\t/**\t\n\t * MPI communication between the processors as they all need to know how many data the other processors have\n\t */\n\tint tmpFileLineCountsArray[world_size], tmpFileLineCountsArrayCum[world_size] ;\n\tint sendBuffer0[0];\n\tsendBuffer0[0]=tmpFileLineCounts;\n\tMPI_Allgather(sendBuffer0,1,MPI_INT,tmpFileLineCountsArray,1,MPI_INT,MPI_COMM_WORLD);\n\t/**\t\n\t * All Processors make an array tmpFileLineCountsArrayCum that cummulatively stores the number of data in the other processors \n\t */\n\tfor (int i=0; i<world_size; ++i) {\n\t\ttmpFileLineCountsArrayCum[i]=0;\n\t}\n\n\tfor (int i=0; i<world_size; ++i) {\t\n\t\tfor (int j=0; j<i+1; ++j) {\n\t\t\ttmpFileLineCountsArrayCum[i]+=tmpFileLineCountsArray[j];\n\t\t}\n\t}\t\n\tif (world_rank==0) {\n\t\tprintf(\"The input csv file contains %d rows of raw data (w/o header) with %d columns\\n\",tmpFileLineCountsArrayCum[world_size-1],featureCounts);\n\t\tsprintf(line,\"The input csv file contains %d rows of raw data (w/o header) with %d columns\\n\",tmpFileLineCountsArrayCum[world_size-1],featureCounts);\n\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\t\t\n\t}\t\t\n\t/**\t\n\t * Parse data from csv file and store them in a 2D array\n\t */\n\tdouble ** inputdata= new double*[tmpFileLineCounts];;\n\tfor (int i=0; i<tmpFileLineCounts; ++i) { inputdata[i] = new double[featureCounts]; }\n\n\tif (argc==3){\n\t\tfor (int i=0; i<tmpFileLineCounts; ++i) {\n\t\t\tstring temp, temp2;\n\t\t\tgetline(infile, temp);\t\n\t\t\tfor (int j=0; j<featureCounts; ++j){\n\t\t\t\ttemp2 =temp.substr(0, temp.find(\",\"));\n\t\t\t\tinputdata[i][j]=atof(temp2.c_str());\n\t\t\t\ttemp.erase(0, temp.find(\",\") + 1);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor (int i=0; i<tmpFileLineCounts; ++i) {\n\t\t\tstring temp, temp2;\n\t\t\tgetline(infile, temp);\t\n\t\t\tfor (int j=0; j<featureCounts; ++j){\n\t\t\t\ttemp2 =temp.substr(0, temp.find(\",\"));\n\t\t\t\tif (j >= colIndex1-1 && j < colIndex2) inputdata[i][j] = atof(temp2.c_str());\n\t\t\t\ttemp.erase(0, temp.find(\",\") + 1);\n\t\t\t}\n\t\t}\t\n\t}\n\tif (argc == 5) featureCounts=colIndex2-colIndex1+1;\n\t/**\t\n\t * Remove the local input files as their data has been already parsed and read\n\t */\n\tinfile.close();\n\tstring cmd2= string(\"rm \")+localFileName;\n\tint returnValue=system(cmd2.c_str());\n\t/**\n\t * Query about the number of available OpenMP processors and set it for OpenMP\n\t */\t\n\tint nProcessors = omp_get_num_procs();\n    omp_set_num_threads(nProcessors-1);\n\tcout <<\"Total Number of OpenMP Processes in the Parallel Region = \"<< nProcessors-1 <<endl;\n\t\n\t/**\t\n\t * Compute dimensions with the highest variance\n\t */\t\n\tvector<pair<double,int>> VectorGlobalSqrtSum;\n\tvector <int> nodeDataIndex[world_size];\n\tnodeDataIndex[0].reserve(tmpFileLineCounts);\n\tfor (int i=0; i<tmpFileLineCounts; ++i){nodeDataIndex[0].push_back(i);}\t\t\n\tVectorGlobalSqrtSum=findMaxVarDims(nodeDataIndex[0].size(), inputdata, featureCounts, world_size, globalKdTreeSamples);\t\n\t/**\t\n\t * Constructing the global Kd Tree collaboratively by all the processors\n\t */\t\t\n\tvector<double> globalMedianValuesforNodes;\n\tvector <int> nextLayerNodeDataIndex[world_size];\n\tint nodeCounts=1, nodesLayer=0;\t\n\tdouble medianNodeData;\n\n\twhile (nodeCounts!= world_size){ \n\t\tif (world_rank ==0) {\n\t\t\tprintf(\"Constructing Global Kd Tree: Layer = %d \\n\",nodesLayer);\n\t\t\tsprintf(line,\"Constructing Global Kd Tree: Layer = %d \\n\",nodesLayer);\n\t\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\n\t\t}\n\t\tint indexMaxVarDim=VectorGlobalSqrtSum[nodesLayer].second; \n\n\t\tfor (int i=0; i<nodeCounts; ++i){\n\t\t\tint countLeft=0, countRight=0;\n\t\t\tmedianNodeData=globalFindMedian(indexMaxVarDim,nodeDataIndex[i], globalKdTreeSamplesMedian,Epsilon, world_size,world_rank, inputdata);\t\t\t\t\t\t\n\t\t\tglobalMedianValuesforNodes.push_back(medianNodeData); \n\n\t\t\tfor (int j=0; j< nodeDataIndex[i].size(); ++j){ \n\t\t\t\tint index=nodeDataIndex[i][j]; \n\t\t\t\tif (inputdata[index][indexMaxVarDim] < medianNodeData){ \n\t\t\t\t\tnextLayerNodeDataIndex[i*2].push_back(index);\n\t\t\t\t\t++countLeft;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tnextLayerNodeDataIndex[i*2+1].push_back(index);\n\t\t\t\t\t++countRight;\n\t\t\t\t}   \n\t\t\t}\n\t\t}\n\t\tnodeCounts*=2;\n\t\t++nodesLayer;\n\n\t\tfor (int i=0; i<nodeCounts; ++i){\n\t\t\tnodeDataIndex[i].clear();\n\t\t\tnodeDataIndex[i]=nextLayerNodeDataIndex[i];\t\n\t\t\tnextLayerNodeDataIndex[i].clear();\t\n\t\t}\n\t}\t\n\t\n\tint indexMaxVarDim=VectorGlobalSqrtSum[nodesLayer].second; \n\tfor (int i=0; i<nodeCounts; ++i){\n\t\tint countLeft=0, countRight=0;\n\t\tmedianNodeData=globalFindMedian(indexMaxVarDim,nodeDataIndex[i], globalKdTreeSamplesMedian,Epsilon, world_size,world_rank, inputdata);\t\t\t\t\t\t\n\t\tglobalMedianValuesforNodes.push_back(medianNodeData); \t\t\t\n\t}\n\t\n\t/**\t\n\t * Once the number of dividing nodes in the global Kd Tree became equal to the number of MPI processors\n\t * each processor will be responsible for the data of one dividing node\n\t * Index of data for each processor is stored at ProcessorLocalDataIndex\n\t */\t\n\tint *ProcessorLocalDataIndex;\n\tint cnts; \n\n\tfor (int i=0; i<nodeCounts; ++i){\n\t\tint rcount[world_size];\n\t\tint send_buffer[0];\n\t\tint displs[nodeCounts];\n\t\tdispls[0]=0;\t\n\t\tint myDATA[nodeDataIndex[i].size()];\n\n\t\tfor (int j=0; j< nodeDataIndex[i].size(); ++j){ \n\t\t\tif (world_rank>0) myDATA[j]= nodeDataIndex[i][j]+tmpFileLineCountsArrayCum[world_rank-1];\n\t\t\telse if(world_rank==0) myDATA[j]= nodeDataIndex[i][j];\n\t\t}  \n\n\t\tint Totalcounts=(int)nodeDataIndex[i].size();\t\t\t            \t\t\t  \n\t\tsend_buffer[0]=nodeDataIndex[i].size();\t\t\t\t\t\t\t\t\n\t\tMPI_Gather(send_buffer,1, MPI_INT,rcount,1, MPI_INT,i,MPI_COMM_WORLD);\n\n\t\tif (world_rank==i){\t\n\t\t\tcnts=0;\n\t\t\tfor (int k=0; k<nodeCounts; ++k){cnts+=rcount[k];}\t\t\t\n\t\t\tfor (int k=1; k<nodeCounts; ++k){displs[k]=displs[k-1]+rcount[k-1];}\n\t\t\tProcessorLocalDataIndex = new int[cnts]; \n\t\t}\t\n\t\tMPI_Gatherv(myDATA,Totalcounts,MPI_INT,ProcessorLocalDataIndex,rcount,displs,MPI_INT,i,MPI_COMM_WORLD);     \t\t \n\t}\n\t/**\t\n\t * Now, each processor only reads its own data from the input csv file according to the indices of ProcessorLocalDataIndex\n\t * If parallel I/O is not available (Parallel_IO=0), each processor reads the file at a time\n\t * the main output of this section is mappedData which is a 2D array storing dataset\n\t */\n\tint rankOfProcess=0;\n\tdouble mappedData[cnts][featureCounts];  \n\tint indexLookupArray[tmpFileLineCountsArrayCum[world_size-1]];\n\n\tif (Parallel_IO){\n\t\tusing boost::iostreams::mapped_file_source;\n\t\tusing boost::iostreams::stream;\n\t\tmapped_file_source mmap(fileName);\n\t\tstream<mapped_file_source> is(mmap, std::ios::binary);\n\t\tstring tempString,tempString2;\n\t\tint m_numLines = 0;\n\t\tstring dummyLine;\n\t\tgetline(is, dummyLine);    \n\n\t\tfor (int i=0; i<cnts; ++i){      \n\t\t\tint lineIndex=ProcessorLocalDataIndex[i];\n\t\t\tbool flag=true;\n\n\t\t\twhile (flag==true){\n\t\t\t\tif (m_numLines==lineIndex) {  \n\t\t\t\t\tindexLookupArray[lineIndex]=i; \n\t\t\t\t\tgetline(is, tempString);      \n\t\t\t\t\tfor (int j=0;j<featureCounts;++j){\n\t\t\t\t\t\ttempString2 =tempString.substr(0, tempString.find(\",\"));\n\t\t\t\t\t\tmappedData[i][j]=atof(tempString2.c_str());\n\t\t\t\t\t\ttempString.erase(0, tempString.find(\",\") + 1);\n\t\t\t\t\t}\n\t\t\t\t\tm_numLines++;\n\t\t\t\t\tflag=false;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tgetline(is, dummyLine);  \n\t\t\t\t\tm_numLines++;\n\t\t\t\t\tflag=true;\n\t\t\t\t\tif(!is) {flag=false; break;}\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tmmap.close();\n\t}\n\telse{\n\t\twhile (rankOfProcess < world_size){\n\t\t\tif (world_rank==rankOfProcess){\n\t\t\t\tusing boost::iostreams::mapped_file_source;\n\t\t\t\tusing boost::iostreams::stream;\n\t\t\t\tmapped_file_source mmap(fileName);\n\t\t\t\tstream<mapped_file_source> is(mmap, std::ios::binary);\n\t\t\t\tstring tempString,tempString2;\n\t\t\t\tint m_numLines = 0;\n\t\t\t\tstring dummyLine;\n\t\t\t\tgetline(is, dummyLine);    \n\n\t\t\t\tfor (int i=0; i<cnts; ++i){      \n\t\t\t\t\tint lineIndex=ProcessorLocalDataIndex[i];\n\t\t\t\t\tbool flag=true;\n\n\t\t\t\t\twhile (flag==true){\n\t\t\t\t\t\tif (m_numLines==lineIndex) {  \n\t\t\t\t\t\t\tindexLookupArray[lineIndex]=i; \n\t\t\t\t\t\t\tgetline(is, tempString);      \n\t\t\t\t\t\t\tfor (int j=0;j<featureCounts;++j){\n\t\t\t\t\t\t\t\ttempString2 =tempString.substr(0, tempString.find(\",\"));\n\t\t\t\t\t\t\t\tmappedData[i][j]=atof(tempString2.c_str());\n\t\t\t\t\t\t\t\ttempString.erase(0, tempString.find(\",\") + 1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tm_numLines++;\n\t\t\t\t\t\t\tflag=false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tgetline(is, dummyLine);  \n\t\t\t\t\t\t\tm_numLines++;\n\t\t\t\t\t\t\tflag=true;\n\t\t\t\t\t\t\tif(!is) {flag=false; break;}\n\t\t\t\t\t\t}\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmmap.close();\n\t\t\t}\n\t\t\t++rankOfProcess;\n\t\t\tMPI_Barrier(MPI_COMM_WORLD);\n\t\t}  \n\t}\n\t/**\t\n\t * Now, it is the time to construct the local Kd Tree by each processor separately\n\t * Tree construction continues until all data is stored in the buckets of size bucketSize\n\t * or maxAllowedLayers is reached \n\t */\n\tif (world_rank==0) {\n\t\tprintf(\"Constructing the Local Kd Tree\\n\");\n\t\tsprintf(line,\"Constructing the Local Kd Tree\\n\");\n\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\n\t}\n\n\tint layerNodeCounts=1;  \n\tint localNodesLayer=0;\n\tvector < vector<int> > localNodeDataIndex;\n\tvector <int> tmpvector;\n\tvector <double> localMedianNodeData;\n\tvector <int> isBucket;\n\tbool localFlag=true;\n\tint numberofNodeSofar;\n\tint nodeIndexofaPoint[cnts];      \n\ttmpvector.reserve(cnts);\n\n\tfor (int i=0; i<cnts; ++i){\n\t\ttmpvector.push_back(ProcessorLocalDataIndex[i]); \n\t\tnodeIndexofaPoint[i]=-1;\n\t}\n\tlocalNodeDataIndex.push_back(tmpvector);\t\t\n\n\tisBucket.reserve(localNodeDataIndex[0].size()/bucketSize);\n\tlocalMedianNodeData.reserve(localNodeDataIndex[0].size()/bucketSize);\n\t/**\t\n\t * Ideally we need estimatedLayers number of layers in the local Kd tree\n\t */\n\tint estimatedLayers=int(log2(localNodeDataIndex[0].size()/bucketSize))+1;  \n\tint maxAllowedLayers=estimatedLayers+estimatedExtraLayers;\n\tif (maxAllowedLayers+nodesLayer > featureCounts){\n\t\tprintf(\"Error in Exceeding Dimensions, increase BucketSize\\n\");\n\t\tsprintf(line,\"Error in Exceeding Dimensions, increase BucketSize\\n\");\n\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\n\t}\n\n\tif (localNodeDataIndex[0].size() <= bucketSize+1) {isBucket.push_back(1); localFlag=false;}  \n\telse {isBucket.push_back(0);}\t\n\n\twhile (localFlag){\n\t\tint indexMaxVarDim=VectorGlobalSqrtSum[localNodesLayer+nodesLayer].second; \n\t\tif (localNodesLayer==0) {numberofNodeSofar=0;}\n\t\telse {numberofNodeSofar=pow(2,localNodesLayer)-1;}\n\n\t\tfor (int i=0; i<layerNodeCounts; ++i){\n\t\t\tint globalID=numberofNodeSofar +i;\n\t\t\tint countLeft=0, countRight=0;\n\t\t\tint leftNodeGlobalIndex=numberofNodeSofar+layerNodeCounts+(i*2);\n\t\t\tint rightNodeGlobalIndex=numberofNodeSofar+layerNodeCounts+(i*2)+1;\n\t\t\tlocalNodeDataIndex.push_back(std::vector<int>());\n\t\t\tlocalNodeDataIndex.push_back(std::vector<int>());\n\n\t\t\tif (isBucket[globalID]==1) {isBucket.push_back(0); isBucket.push_back(0); localMedianNodeData.push_back(0); continue;}\n\t\t\tif (localNodeDataIndex[globalID].size()==0) {isBucket.push_back(0); isBucket.push_back(0); localMedianNodeData.push_back(0); continue;}\t\t\n\t\t\tif (localKdTreeSamplesMedian > localNodeDataIndex[globalID].size()/2) localKdTreeSamplesMedian=localNodeDataIndex[globalID].size()/2;\t\t\t\n\t\t\tvector <double> sampledDataValues;\t\n\t\t\tfor (int i=0; i< localKdTreeSamplesMedian; ++i){\n\t\t\t\tint randomIndex=rand()%localNodeDataIndex[globalID].size();\n\t\t\t\tint index=localNodeDataIndex[globalID][randomIndex];\t\t\t\n\t\t\t\tint index1=indexLookupArray[index];\t         \n\t\t\t\tsampledDataValues.push_back(mappedData[index1][indexMaxVarDim]);\n\t\t\t}\n\n\t\t\tdouble temp=localFindMedian(localKdTreeSamplesMedian,sampledDataValues,Epsilon,world_rank);\n\t\t\tlocalMedianNodeData.push_back(temp);\n\n\t\t\tfor (int j=0; j< localNodeDataIndex[globalID].size(); ++j){ \n\t\t\t\tint index0=localNodeDataIndex[globalID][j];\n\t\t\t\tint index=indexLookupArray[index0];\n\t\t\t\tif (mappedData[index][indexMaxVarDim] < localMedianNodeData[globalID]){ \n\t\t\t\t\tlocalNodeDataIndex[leftNodeGlobalIndex].push_back(index0);\n\t\t\t\t\t++countLeft;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tlocalNodeDataIndex[rightNodeGlobalIndex].push_back(index0);\n\t\t\t\t\t++countRight;\n\t\t\t\t} \n\t\t\t}\n\n\t\t\tif (countLeft ==1) {\n\t\t\t\tlocalNodeDataIndex[rightNodeGlobalIndex].push_back(localNodeDataIndex[leftNodeGlobalIndex][0]);\n\t\t\t\tlocalNodeDataIndex[leftNodeGlobalIndex].pop_back();\n\t\t\t\t--countLeft;\n\t\t\t}\n\n\t\t\tif (countRight ==1) {\n\t\t\t\tlocalNodeDataIndex[leftNodeGlobalIndex].push_back(localNodeDataIndex[rightNodeGlobalIndex][0]);\n\t\t\t\tlocalNodeDataIndex[rightNodeGlobalIndex].pop_back();\n\t\t\t\t--countRight;\n\t\t\t}\n\n\n\t\t\tif ((countLeft <= bucketSize+1 && countLeft >0)|| ((localNodesLayer == maxAllowedLayers-1) && countLeft >0) ) {  \n\t\t\t\tisBucket.push_back(1);\t\t\t\n\n\t\t\t\tfor (int j=0; j< localNodeDataIndex[leftNodeGlobalIndex].size(); ++j){ \n\t\t\t\t\tint index0=localNodeDataIndex[leftNodeGlobalIndex][j];\n\t\t\t\t\tint index=indexLookupArray[index0];\n\t\t\t\t\tnodeIndexofaPoint[index]=leftNodeGlobalIndex;\t\t\t\t\t\t\t\n\t\t\t\t} \n\t\t\t}\n\t\t\telse {isBucket.push_back(0);}\n\n\t\t\tif ((countRight <= bucketSize+1 && countRight >0) || ((localNodesLayer == maxAllowedLayers-1) && countRight >0) ) {  \n\t\t\t\tisBucket.push_back(1);\n\n\t\t\t\tfor (int j=0; j< localNodeDataIndex[rightNodeGlobalIndex].size(); ++j){ \n\t\t\t\t\tint index0=localNodeDataIndex[rightNodeGlobalIndex][j];\n\t\t\t\t\tint index=indexLookupArray[index0];              \n\t\t\t\t\tnodeIndexofaPoint[index]=rightNodeGlobalIndex;\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {isBucket.push_back(0);}\t\t\n\t\t}\n\n\t\tlocalFlag=false;\n\t\tfor (int i=0; i<layerNodeCounts; ++i){\n\t\t\tint globalID=numberofNodeSofar + i;\t   \n\t\t\tif (isBucket[globalID]==0 && localNodeDataIndex[globalID].size()>0 ) {localFlag=true; break;\n\t\t\t}\n\t\t}\n\t\tlayerNodeCounts*=2;\n\t\t++localNodesLayer;\t\n\t}\n\t/**\t\n\t * For performance, it is better to refer to local Kd tree later\n\t * from the ID of the first dividing node which has been converted to a bucket\n\t */\n\tint FirstBucket;\n\tfor (int i=0; i< localNodeDataIndex.size(); ++i){ \n\t\tif (isBucket[i] == 1) {FirstBucket=i;break;}\n\t}\n\t/**\t\n\t * Now, it is the time to start computing K-NNs from the data points within each bucket in the local Kd Tree\n\t * and store them in KNNIDsinBuckets and KNNDistanceinBuckets\n\t * To improve the performance, the data locality was considered for main arrays of localNodeDataIndex2 and mappedData2 \n\t * and the data within the same bucket arranged close to each other in the new arrays\n\t */\n\tif (world_rank==0) {\n\t\tprintf(\"Computing K-NNs for the points within the Same Bucket\\n\");\n\t\tsprintf(line,\"Computing K-NNs for the points within the Same Bucket\\n\");\n\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\n\t}\n\tint KNNIDsinBucketsFilledCounts[cnts];\n\tint localIndexConvertor[cnts];\n\tint counter=0;\n\tvector<vector<int>> localNodeDataIndex2;  \n\n\tint **KNNIDsinBuckets = new int*[cnts];\n\tfor (int i=0; i<cnts; ++i) { KNNIDsinBuckets[i] = new int[KNNCounts]; }\t\n\n\tdouble ** KNNDistanceinBuckets = new double*[cnts];\n\tfor (int i=0; i<cnts; ++i) { KNNDistanceinBuckets[i] = new double[KNNCounts]; }\t\n\n\tfor (int i=0; i< localNodeDataIndex.size(); ++i){ \n\t\tlocalNodeDataIndex2.push_back(std::vector<int>());\t\n\t\tif (isBucket[i] == 0) {continue;}\n\n\t\tfor (int j=0; j< localNodeDataIndex[i].size(); ++j){ \n\t\t\tlocalIndexConvertor[counter]=localNodeDataIndex[i][j];\n\t\t\tlocalNodeDataIndex2[i].push_back(counter); \n\t\t\t++counter;\n\t\t}\n\t}\n\n\tdouble** mappedData2=new double*[cnts];\n\tfor (int i=0; i<cnts; ++i) { mappedData2[i] = new double[featureCounts]; }\n\n\tint nodeIndexofaPoint2[cnts];\n\n\tfor (int i=0; i< cnts; ++i){ \n\t\tint pointID=localIndexConvertor[i];\n\t\tint index=indexLookupArray[pointID]; \n\t\tnodeIndexofaPoint2[i]=nodeIndexofaPoint[index];\n\t\tfor (int j=0; j<featureCounts; ++j){\n\t\t\tmappedData2[i][j]=mappedData[index][j];\n\t\t}\n\t}\n\n\tfor (int i=0; i< cnts; ++i){ \n\t\tfor (int j=0; j< KNNCounts; ++j){ \n\t\t\tKNNIDsinBuckets[i][j]=-1;\n\t\t}\n\t}\n\n\tfor (int i=0; i< cnts; ++i){ \n\t\tKNNIDsinBucketsFilledCounts[i]=0;\n\t}\n\n\tfor (int i=FirstBucket; i< localNodeDataIndex2.size(); ++i){ \n\t\tif (isBucket[i] == 0) {continue;}\t\t\n\t\tfor (int j=0; j< localNodeDataIndex2[i].size()-1; ++j){ \n\t\t\tint index=localNodeDataIndex2[i][j];\t\t\n\t\t\tfor (int k=j+1; k<localNodeDataIndex2[i].size(); ++k){ \n\t\t\t\tint index2=localNodeDataIndex2[i][k];\t\t\n\t\t\t\tint emptyIndex = KNNIDsinBucketsFilledCounts[index];\n\t\t\t\tdouble dist=computeDistance(index,index2,mappedData2,featureCounts); \n\t\t\t\t\n\t\t\t\tif  (emptyIndex < KNNCounts) {\n\t\t\t\t\tKNNIDsinBuckets[index][emptyIndex]=localIndexConvertor[index2];                    \n\t\t\t\t\t++KNNIDsinBucketsFilledCounts[index];                      \n\t\t\t\t\tKNNDistanceinBuckets[index][emptyIndex]=dist;          \n\t\t\t\t\tif (emptyIndex==(KNNCounts-1)) Build_Max_Heap(index,KNNCounts,KNNDistanceinBuckets,KNNIDsinBuckets);\n\t\t\t\t}\n\t\t\t\telse { \n\t\t\t\t\tif (dist < KNNDistanceinBuckets[index][0]) {         \n\t\t\t\t\t\tKNNIDsinBuckets[index][0]=localIndexConvertor[index2];                                         \n\t\t\t\t\t\tKNNDistanceinBuckets[index][0]=dist;     \n\t\t\t\t\t\tMax_Heapify(index, 0, KNNDistanceinBuckets, KNNIDsinBuckets,KNNCounts);\n\t\t\t\t\t}    \n\t\t\t\t}\n\n\t\t\t\tint emptyIndex2 = KNNIDsinBucketsFilledCounts[index2];\n\t\t\t\tif  (emptyIndex2 < KNNCounts) {\n\t\t\t\t\tKNNIDsinBuckets[index2][emptyIndex2]=localIndexConvertor[index];\t                     \n\t\t\t\t\t++KNNIDsinBucketsFilledCounts[index2];                      \n\t\t\t\t\tKNNDistanceinBuckets[index2][emptyIndex2]=dist;       \n\t\t\t\t\tif (emptyIndex2==(KNNCounts-1)) Build_Max_Heap(index2,KNNCounts,KNNDistanceinBuckets,KNNIDsinBuckets);                        \n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (dist < KNNDistanceinBuckets[index2][0]) {  \n\t\t\t\t\t\tKNNIDsinBuckets[index2][0]=localIndexConvertor[index];                                         \n\t\t\t\t\t\tKNNDistanceinBuckets[index2][0]=dist;\n\t\t\t\t\t\tMax_Heapify(index2, 0, KNNDistanceinBuckets, KNNIDsinBuckets, KNNCounts);}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t/**\t\n\t * Now, it is the time to find the IDs of processors that contain the neighboring sub-spaces \n\t * A neighboring processor is selected if its distance from the given point is less than \n\t * the maximum distance in the heap of that point (first entry of heap)\n\t */\n\tif (world_rank==0) {\n\t\tprintf(\"Finding the Spatial Neighboring Processors\\n\");\n\t\tsprintf(line,\"Finding the Spatial Neighboring Processors\\n\");\n\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\n\t}\n\n\tvector<int> ScatterVlocalNodeDataIndex[world_size];\n\tvector<int> ScatterVKNNIDsinBucketsFilledCounts[world_size];\n\n\tint globalLayerID = int(log2(world_size));\n\tint lowestNodeID=pow(2,globalLayerID)-1; \n\tint highestNodeID=lowestNodeID+world_size-1;\n\tint NeighboringNodes[cnts][world_size-1];\n\n\tif (world_size != 1){ \n\t\tfor (int i=0; i<cnts; ++i){\n\t\t\tfor (int j=0; j<world_size-1; ++j){\n\t\t\t\tNeighboringNodes[i][j]=-1;\n\t\t\t}\n\t\t}\n\n\t\tfor (int i=FirstBucket; i< localNodeDataIndex2.size(); ++i){ \n\t\t\tif (isBucket[i] == 0) {continue;}\n\t\t\tfor (int j=0; j< localNodeDataIndex2[i].size(); ++j){ \n\t\t\t\tint index1= localNodeDataIndex2[i][j];\n\n\t\t\t\tdouble rPrime=KNNDistanceinBuckets[index1][0];\n\t\t\t\tstack<pair<int,double>> globalStack;  \n\t\t\t\tglobalStack.push(make_pair(0,0));\n\t\t\t\t/**\t \n\t\t\t\t * C1NodeID is the closer child, and C2NodeID is the other child\n\t\t\t\t */\n\t\t\t\tint C1NodeID,C2NodeID;\n\t\t\t\tint jcounts=0;\n\n\t\t\t\twhile (!globalStack.empty()){\n\t\t\t\t\tpair<int,double> topPairinStack=globalStack.top();\n\t\t\t\t\tint nodeID=topPairinStack.first;\n\t\t\t\t\tdouble dValue=topPairinStack.second;\n\t\t\t\t\tglobalStack.pop();\n\t\t\t\t\tint nodesLayer0=int(log2(nodeID+1));\n\t\t\t\t\tint indexMaxVarDim=VectorGlobalSqrtSum[nodesLayer0].second;\n\n\t\t\t\t\tif (dValue < rPrime){\t\t\n\t\t\t\t\t\tdouble dPrime= mappedData2[index1][indexMaxVarDim] - globalMedianValuesforNodes[nodeID];\n\t\t\t\t\t\tif (dPrime < 0) { \n\t\t\t\t\t\t\tC1NodeID=2*nodeID+1; \n\t\t\t\t\t\t\tC2NodeID=2*nodeID+2; \n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tC1NodeID=2*nodeID+2; \n\t\t\t\t\t\t\tC2NodeID=2*nodeID+1; \n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdPrime=sqrt(dValue*dValue+dPrime*dPrime);\n\t\t\t\t\t\tif (dPrime<rPrime) { \n\t\t\t\t\t\t\tif (C2NodeID <= highestNodeID) {\n\t\t\t\t\t\t\t\tglobalStack.push(make_pair(C2NodeID,dPrime));\n\t\t\t\t\t\t\t\tif (C2NodeID >= lowestNodeID && (C2NodeID-lowestNodeID)!=world_rank) {\n\t\t\t\t\t\t\t\t\tNeighboringNodes[index1][jcounts]=C2NodeID-lowestNodeID;\n\t\t\t\t\t\t\t\t\tScatterVlocalNodeDataIndex[C2NodeID-lowestNodeID].push_back(index1);\n\t\t\t\t\t\t\t\t\tScatterVKNNIDsinBucketsFilledCounts[C2NodeID-lowestNodeID].push_back(KNNIDsinBucketsFilledCounts[index1]);\n\t\t\t\t\t\t\t\t\t++jcounts;\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\n\t\t\t\t\t\tif (C1NodeID <= highestNodeID) {\n\t\t\t\t\t\t\tglobalStack.push(make_pair(C1NodeID,dValue));\n\t\t\t\t\t\t\tif (C1NodeID >= lowestNodeID && (C1NodeID-lowestNodeID)!=world_rank) {\n\t\t\t\t\t\t\t\tNeighboringNodes[index1][jcounts]=C1NodeID-lowestNodeID;\n\t\t\t\t\t\t\t\tScatterVlocalNodeDataIndex[C1NodeID-lowestNodeID].push_back(index1);\n\t\t\t\t\t\t\t\tScatterVKNNIDsinBucketsFilledCounts[C1NodeID-lowestNodeID].push_back(KNNIDsinBucketsFilledCounts[index1]);\n\t\t\t\t\t\t\t\t++jcounts;\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\t}\t\n\t/**\t\n\t * Now, send the data of the given point to the neighboring processors identified above \n\t * for further computation of possible K-NNs in those processors\n\t */\n\tint displ[world_size],displ2[world_size],displ3[world_size];\n\tint bufferCounts[world_size],bufferCounts2[world_size],bufferCounts3[world_size];\n\tbufferCounts[world_rank]=0;\n\tbufferCounts2[world_rank]=0;  \n\tbufferCounts3[world_rank]=0;\n\n\tif (world_size != 1){\t\n\t\tfor (int i=0; i<cnts; ++i){      \n\t\t\tScatterVlocalNodeDataIndex[world_rank].push_back(i);      \n\t\t\tScatterVKNNIDsinBucketsFilledCounts[world_rank].push_back(KNNIDsinBucketsFilledCounts[i]);\t\t\t\t\t\n\t\t}\n\n\t\tfor (int i=0; i<world_size; ++i){ \n\t\t\tbufferCounts[i]=ScatterVlocalNodeDataIndex[i].size(); \n\t\t\tbufferCounts2[i]=ScatterVlocalNodeDataIndex[i].size()*KNNCounts;\n\t\t\tbufferCounts3[i]=ScatterVlocalNodeDataIndex[i].size()*featureCounts;\n\t\t}\n\n\t\tdispl[0]=0;\n\t\tdispl2[0]=0;\n\t\tdispl3[0]=0;\n\t\tfor (int i=1; i<world_size; ++i){\n\t\t\tdispl[i]= displ[i-1]+bufferCounts[i-1];\n\t\t\tdispl2[i]= displ2[i-1]+bufferCounts2[i-1];\n\t\t\tdispl3[i]= displ3[i-1]+bufferCounts3[i-1];\n\t\t}\n\t}\n\n\tconst int ArraySizeScatterV=displ[world_size-1]+bufferCounts[world_size-1];\n\tint sendbuffer[ArraySizeScatterV];\n\tint sendbuffer2[ArraySizeScatterV];\n\tint sendbuffer4[ArraySizeScatterV*KNNCounts];\n\tdouble sendbuffer5[ArraySizeScatterV*featureCounts];\n\tdouble sendbuffer6[ArraySizeScatterV*KNNCounts];\n\n\tif (world_size != 1){\t\t\n\t\tfor (int i=0; i<world_size; ++i){\n\t\t\tint KIndex=displ[i];\t\n\t\t\tfor (int j=0; j<ScatterVlocalNodeDataIndex[i].size(); ++j){\n\t\t\t\tsendbuffer[KIndex+j]=ScatterVlocalNodeDataIndex[i][j]; \n\t\t\t\tsendbuffer2[KIndex+j]=ScatterVKNNIDsinBucketsFilledCounts[i][j];\n\t\t\t\tfor (int kk=0; kk<KNNCounts; ++kk){\n\t\t\t\t\tsendbuffer4[(KIndex+j)*KNNCounts+kk]= KNNIDsinBuckets[ScatterVlocalNodeDataIndex[i][j]][kk];\n\t\t\t\t\tsendbuffer6[(KIndex+j)*KNNCounts+kk]= KNNDistanceinBuckets[ScatterVlocalNodeDataIndex[i][j]][kk];\n\t\t\t\t}\n\t\t\t\tfor (int ll=0; ll<featureCounts; ++ll){\n\t\t\t\t\tsendbuffer5[(KIndex+j)*featureCounts+ll]= mappedData2[ScatterVlocalNodeDataIndex[i][j]][ll];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tint receivingCountsMatrix[world_size];\n\tint receiveCounts,TotalReceiveCounts=0;\n\tint *receivingIndices[world_size];\n\tint *receivingHeapSize[world_size];\n\tint *receivingHeapArray[world_size];\n\tdouble *receivingHeapArrayDistances[world_size];\n\tdouble *receivingPointCoordinates[world_size];\n\n\tif (world_size != 1){\t\n\t\tfor (int i=0; i<world_size; ++i){\n\t\t\tMPI_Scatter (bufferCounts,1,MPI_INT,&receiveCounts,1 ,MPI_INT,i,MPI_COMM_WORLD); \n\t\t\treceivingIndices[i]=new int[receiveCounts];  \n\t\t\treceivingHeapSize[i]=new int[receiveCounts];  \n\t\t\treceivingHeapArray[i]=new int[receiveCounts*KNNCounts];\n\t\t\treceivingHeapArrayDistances[i]=new double[receiveCounts*KNNCounts];\n\t\t\treceivingPointCoordinates[i]=new double[receiveCounts*featureCounts];\n\t\t\treceivingCountsMatrix[i]=receiveCounts;\n\t\t\tTotalReceiveCounts+=receiveCounts; \n\n\t\t\tMPI_Scatterv (&sendbuffer ,bufferCounts, displ, MPI_INT,&receivingIndices[i][0],receiveCounts,MPI_INT,i,MPI_COMM_WORLD); \n\t\t\tMPI_Scatterv (&sendbuffer2,bufferCounts, displ, MPI_INT,&receivingHeapSize[i][0],receiveCounts,MPI_INT,i,MPI_COMM_WORLD); \n\t\t\tMPI_Scatterv (&sendbuffer4,bufferCounts2,displ2,MPI_INT,&receivingHeapArray[i][0],receiveCounts*KNNCounts,MPI_INT,i,MPI_COMM_WORLD); \n\t\t\tMPI_Scatterv (&sendbuffer5,bufferCounts3,displ3,MPI_DOUBLE,&receivingPointCoordinates[i][0],receiveCounts*featureCounts,MPI_DOUBLE,i,MPI_COMM_WORLD); \n\t\t\tMPI_Scatterv (&sendbuffer6,bufferCounts2,displ2,MPI_DOUBLE,&receivingHeapArrayDistances[i][0],receiveCounts*KNNCounts,MPI_DOUBLE,i,MPI_COMM_WORLD); \n\t\t}\n\t}\n\telse{\n\t\treceivingIndices[0]=new int[cnts]; \n\t\treceivingHeapArray[0]=new int[cnts*KNNCounts];\t\n\t\treceivingHeapArrayDistances[0]=new double[cnts*KNNCounts];\t\n\t\treceivingPointCoordinates[0]=new double[cnts*featureCounts];\n\t\treceivingCountsMatrix[0]=cnts;\n\t\treceivingHeapSize[0]=new int[cnts];\n\n\t\tfor (int i=0; i<cnts; ++i){      \n\t\t\treceivingIndices[0][i]=i;\n\t\t\treceivingHeapSize[0][i]=KNNIDsinBucketsFilledCounts[i];\n\n\t\t\tfor (int j=0; j<KNNCounts; ++j){ \n\t\t\t\treceivingHeapArrayDistances[0][i*KNNCounts+j]=KNNDistanceinBuckets[i][j];\n\t\t\t\treceivingHeapArray[0][i*KNNCounts+j]=KNNIDsinBuckets[i][j];\n\t\t\t}\n\n\t\t\tfor (int j=0; j<featureCounts; ++j){    \n\t\t\t\treceivingPointCoordinates[0][i*featureCounts+j]=mappedData2[i][j];\n\t\t\t}\n\t\t}\n\t}\n\tdelete[] ProcessorLocalDataIndex;\n\t/**\t\n\t * Now, follow querying to compute possible K-NNs for each given point\n\t * For each point, querying is performed on the local Kd Tree of its hosting processor as well as \n\t * the local Kd Tree of the neighboring processors identified above\n\t * This section is the implementation of Algorithm 1 in the referencing paper and is computationally the most expensive part of the code\n\t */\n\tif (world_rank==0) {\n\t\tprintf(\"Computing K-NNs for Queries\\n\");\n\t\tsprintf(line,\"Computing K-NNs for Queries\\n\");\n\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\n\t}\n\t/**\t \n\t * C1NodeID is the closer child, and C2NodeID is the other child\n\t */\n\tint C1NodeID,C2NodeID;\n\n\tfor (int i=0; i<world_size; ++i){\n\t\t/**\t\n\t\t * To improve the performance, multi-threading using OpenMP is implemented here\n\t\t */\n        #pragma omp parallel for private(C1NodeID,C2NodeID)\n\t\tfor (int j=0; j<receivingCountsMatrix[i]; ++j){\n\n\t\t\tint tmpReceivingHeapSize=receivingHeapSize[i][j];\n\t\t\tdouble rPrimeValue=receivingHeapArrayDistances[i][j*KNNCounts];\n\n\t\t\tdouble * receivingHeapArrayDistances2DCopy=new double[KNNCounts];\n\t\t\tint * receivingHeapArray2DCopy=new int[KNNCounts];\n\t\t\t/**\t\n\t\t\t * To improve the performance, 1D arrays receivingHeapArray2DCopy and receivingHeapArrayDistances2DCopy are used here\n\t\t\t */\n\t\t\tfor (int k=0; k<KNNCounts; ++k){\n\t\t\t\treceivingHeapArray2DCopy[k]=receivingHeapArray[i][j*KNNCounts+k];\n\t\t\t\treceivingHeapArrayDistances2DCopy[k]=receivingHeapArrayDistances[i][j*KNNCounts+k];\n\t\t\t}\n\n\t\t\tint tmpIsHeapChanged=0;\n\t\t\tstack<pair<int,double>> globalStack; \n\t\t\tglobalStack.push(make_pair(0,0)); \n\n\t\t\twhile (!globalStack.empty()){\n\t\t\t\tpair<int,double> topPairinStack=globalStack.top();\n\t\t\t\tint nodeID=topPairinStack.first;\n\t\t\t\tdouble dValue=topPairinStack.second;\n\t\t\t\tglobalStack.pop();\n\t\t\t\tint nodesLayer0=int(log2(nodeID+1));\n\t\t\t\tint indexMaxVarDim=VectorGlobalSqrtSum[nodesLayer0+nodesLayer].second;\n\n\t\t\t\tif (isBucket[nodeID] == 1) {\n\t\t\t\t\tfor (int kk=0; kk<localNodeDataIndex2[nodeID].size(); ++kk){ \t\t\t\t\t\n\n\t\t\t\t\t\tif (i==world_rank) {\n\t\t\t\t\t\t\tint index=receivingIndices[i][j];\n\t\t\t\t\t\t\tif (nodeIndexofaPoint2[index]==nodeID) break;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tint index= localNodeDataIndex2[nodeID][kk];\n\t\t\t\t\t\tdouble distance=computeDistance2(index,i,j*featureCounts,mappedData2,receivingPointCoordinates,featureCounts);\n\n\t\t\t\t\t\tif (distance < rPrimeValue){\n\t\t\t\t\t\t\tif (tmpReceivingHeapSize < KNNCounts){\n\t\t\t\t\t\t\t\treceivingHeapArray2DCopy[tmpReceivingHeapSize]=localIndexConvertor[index];\n\t\t\t\t\t\t\t\treceivingHeapArrayDistances2DCopy[tmpReceivingHeapSize]=distance;\n\t\t\t\t\t\t\t\t++tmpReceivingHeapSize;\n\t\t\t\t\t\t\t\ttmpIsHeapChanged=1;     \n\t\t\t\t\t\t\t\tif(tmpReceivingHeapSize==KNNCounts) {\n\t\t\t\t\t\t\t\t\tBuild_Max_Heap2(KNNCounts,receivingHeapArrayDistances2DCopy,receivingHeapArray2DCopy);\n\t\t\t\t\t\t\t\t\trPrimeValue=receivingHeapArrayDistances2DCopy[0];\n\t\t\t\t\t\t\t\t}     \n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (distance < receivingHeapArrayDistances2DCopy[0]){\n\t\t\t\t\t\t\t\treceivingHeapArrayDistances2DCopy[0]=distance;\n\t\t\t\t\t\t\t\treceivingHeapArray2DCopy[0]=localIndexConvertor[index];\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tMax_Heapify2(0,receivingHeapArrayDistances2DCopy,receivingHeapArray2DCopy,KNNCounts);\n\t\t\t\t\t\t\t\ttmpIsHeapChanged=1;\n\t\t\t\t\t\t\t\trPrimeValue=receivingHeapArrayDistances2DCopy[0];\n\t\t\t\t\t\t\t}                \n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (dValue < rPrimeValue){\n\t\t\t\t\t\tdouble dPrime= receivingPointCoordinates[i][j*featureCounts+indexMaxVarDim] - localMedianNodeData[nodeID];\n\t\t\t\t\t\tif (dPrime < 0) { \n\t\t\t\t\t\t\tC1NodeID=2*nodeID+1; \n\t\t\t\t\t\t\tC2NodeID=2*nodeID+2;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tC1NodeID=2*nodeID+2; \n\t\t\t\t\t\t\tC2NodeID=2*nodeID+1; \n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdPrime=sqrt(dValue*dValue+dPrime*dPrime);\n\t\t\t\t\t\tif (dPrime < rPrimeValue) { \n\t\t\t\t\t\t\tif (C2NodeID <= localNodeDataIndex2.size()) {\n\t\t\t\t\t\t\t\tglobalStack.push(make_pair(C2NodeID,dPrime));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (C1NodeID <= localNodeDataIndex2.size()) {\n\t\t\t\t\t\t\tglobalStack.push(make_pair(C1NodeID,dValue));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (tmpIsHeapChanged==1) {\n\t\t\t\tfor (int k=0; k<KNNCounts; ++k){\n\t\t\t\t\treceivingHeapArray[i][j*KNNCounts+k]=receivingHeapArray2DCopy[k];\n\t\t\t\t\treceivingHeapArrayDistances[i][j*KNNCounts+k]=receivingHeapArrayDistances2DCopy[k];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t/**\t\n\t * Now, Send the newly computed K-NNs from the above (Algorithm 1) to the original processor contained it\n\t */\n\tif (world_rank==0) {\n\t\tprintf(\"Sending the Outputs of Query Computations Back to the Original Node\\n\");\n\t\tsprintf(line,\"Sending the Outputs of Query Computations Back to the Original Node\\n\");\n\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\n\t}\n\tint sendbuffer4return[TotalReceiveCounts*KNNCounts];\n\tdouble sendbuffer6return[TotalReceiveCounts*KNNCounts];\n\n\tif (world_size != 1){\t\n\t\tint indexreturn=0;\n\t\tfor (int i=0; i<world_size; ++i){\n\t\t\tfor (int j=0; j<receivingCountsMatrix[i]; ++j){\n\t\t\t\tfor (int k=0; k<KNNCounts; ++k){\n\t\t\t\t\tsendbuffer4return[indexreturn]=receivingHeapArray[i][j*KNNCounts+k];\n\t\t\t\t\tsendbuffer6return[indexreturn]=receivingHeapArrayDistances[i][j*KNNCounts+k];\n\t\t\t\t\t++indexreturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tint displreturn[world_size];\n\tdisplreturn[0]=0;\n\tfor (int i=1; i<world_size; ++i){displreturn[i]= displreturn[i-1]+receivingCountsMatrix[i-1]*KNNCounts;}\n\tint sendCounts[world_size];\n\tfor (int i=0; i<world_size; ++i){sendCounts[i]= receivingCountsMatrix[i]*KNNCounts;}\n\tint *originalNodereceivingHeapArray[world_size];\n\tdouble *originalNodereceivingHeapArrayDistances[world_size];\n\n\tif (world_size != 1){\n\t\tfor (int i=0; i<world_size; ++i){\n\t\t\toriginalNodereceivingHeapArray[i]=new int[bufferCounts2[i]];\n\t\t\toriginalNodereceivingHeapArrayDistances[i]=new double[bufferCounts2[i]];\n\t\t\tMPI_Scatterv (&sendbuffer4return,sendCounts,displreturn,MPI_INT,&originalNodereceivingHeapArray[i][0],bufferCounts2[i],MPI_INT,i,MPI_COMM_WORLD); \n\t\t\tMPI_Scatterv (&sendbuffer6return,sendCounts,displreturn,MPI_DOUBLE,&originalNodereceivingHeapArrayDistances[i][0],bufferCounts2[i],MPI_DOUBLE,i,MPI_COMM_WORLD); \n\t\t}\n\t}\n\telse {\n\t\toriginalNodereceivingHeapArray[0]=new int[cnts*KNNCounts];\n\t\toriginalNodereceivingHeapArrayDistances[0]=new double[cnts*KNNCounts];\n\n\t\tfor (int i=0; i<cnts*KNNCounts; ++i){\n\t\t\toriginalNodereceivingHeapArray[0][i]=receivingHeapArray[0][i];\n\t\t\toriginalNodereceivingHeapArrayDistances[0][i]=receivingHeapArrayDistances[0][i];\n\t\t}\n\t}\n\t/**\t\n\t * Now, organize and sort the K-NNs for each given point either \n\t * received from the neighboring processors or was initially computed from the points within the same bucket\n\t * after sorting, choose only the desired number (KNNCounts) of K-NNs with the shortest distance \n\t */\n\tif (world_rank==0) {\n\t\tprintf(\"Preparing the Final Outputs\\n\");\n\t\tsprintf(line,\"Preparing the Final Outputs\\n\");\n\t\tMPI_File_write(logfile, line, strlen(line), MPI_CHAR, MPI_STATUS_IGNORE);\n\t}\n\n\tofstream outputFileIndex,outputFileDistance;\n\tstring filename1= \"KNN_Indices_\"+to_string(world_rank)+\".csv\";\n\toutputFileIndex.open(filename1);\t\n\tstring filename2= \"KNN_Distances_\"+to_string(world_rank)+\".csv\";\n\toutputFileDistance.open(filename2);\n\n\tfor (int i=0; i<cnts; ++i){\n\t\t/**\t\n\t\t * Set container removes the duplicates and sort data accroding to their distance\n\t\t */\n\t\tset <pair<double,int>> setContainer;\n\t\tint pointID=localIndexConvertor[i];\n\t\t/**\t\n\t\t * Insert into Set container the K-NNs initially computed from the points within the same bucket\n\t\t */\n\t\tfor (int j=0; j<KNNCounts; ++j){\n\t\t\tif (KNNIDsinBuckets[i][j] != -1) setContainer.insert(make_pair(KNNDistanceinBuckets[i][j],KNNIDsinBuckets[i][j]));\n\t\t}\n\t\t/**\t\n\t\t * Insert into Set container the K-NNs computed from the querying in the same processor\n\t\t */\n\t\tfor (int k=0; k<KNNCounts; ++k){\n\t\t\tsetContainer.insert(make_pair(originalNodereceivingHeapArrayDistances[world_rank][i*KNNCounts+k],originalNodereceivingHeapArray[world_rank][i*KNNCounts+k]));\n\t\t} \n\t\t/**\t\n\t\t * Insert into Set container the K-NNs computed from the querying of the other neighboring processors\n\t\t */\n\t\tfor (int j=0; j<world_size-1; ++j){\n\t\t\tint neighborID=NeighboringNodes[i][j];\n\t\t\tif (neighborID == -1) continue;\n\n\t\t\tvector<int>::iterator it = std::find(ScatterVlocalNodeDataIndex[neighborID].begin(), ScatterVlocalNodeDataIndex[neighborID].end(), i);\t\t\t\n\t\t\tint index = std::distance(ScatterVlocalNodeDataIndex[neighborID].begin(), it);  \t\t\n\n\t\t\tfor (int k=0; k<KNNCounts; ++k){\n\t\t\t\tsetContainer.insert(make_pair(originalNodereceivingHeapArrayDistances[neighborID][index*KNNCounts+k],originalNodereceivingHeapArray[neighborID][index*KNNCounts+k]));  \n\t\t\t} \n\t\t}\n\t\t/**\t\n\t\t * Output the results as sorted in the Set container\n\t\t */\n\t\tset <pair<double,int>>::iterator pairIt;\n\t\tpairIt=setContainer.begin();\n\t\tint outputCounter=0;\n\t\tfor (int ii=0; ii<KNNCounts*2; ++ii){\n\t\t\tif (outputCounter==KNNCounts) break;\n\n\t\t\tif ((*pairIt).second==-1) {pairIt++; continue;}\n\t\t\tif (outputCounter == 0) outputFileIndex<<pointID<<\",\";\n\n\t\t\tif (outputCounter != KNNCounts-1) { outputFileIndex<<(*pairIt).second<<\",\";\n\t\t\t} else {outputFileIndex<<(*pairIt).second<<endl;}\n\n\t\t\tif (outputCounter == 0) outputFileDistance<<pointID<<\",\";\n\n\t\t\tif (outputCounter != KNNCounts-1) { outputFileDistance<<(*pairIt).first<<\",\";\n\t\t\t} else {outputFileDistance<<(*pairIt).first<<endl;}\t\t\n\t\t\tpairIt++;\n\t\t\toutputCounter++;\t\t\t\n\t\t}\n\t} //loop cnts\n\n\tdelete[] receivingHeapArray[world_size];\n\tdelete[] receivingHeapArrayDistances[world_size];\n\n\toutputFileIndex.close();\n\toutputFileDistance.close();\t\n\t/**\t\n\t * All procesors neeed to stop here until master processor returns\n\t */\n\tMPI_Barrier(MPI_COMM_WORLD);\n\t/**\t\n\t * Concatenate the Outputs from various processors into a single file and remove the extra output files\n\t */\t\n\t\n\tif (world_rank==0) {\n\t\tstring cmd4= string(\"cat KNN_Indices_*.csv > KNN_Indices.csv\");\n\t\tint returnValue=system(cmd4.c_str());\t\n\t\tstring cmd5= string(\"cat KNN_Distances_*.csv > KNN_Distances.csv\");\n\t\treturnValue=system(cmd5.c_str());\n\n\t\tstring cmd6= string(\"rm KNN_Indices_*\");\n\t\treturnValue=system(cmd6.c_str());\n\t\tstring cmd7= string(\"rm KNN_Distances_*\");\n\t\treturnValue=system(cmd7.c_str());\n\t}\n\n\tMPI_File_close(&logfile);\n\tMPI_Finalize();\t\t\n\treturn 0;\t\t\t\n}\n\n", "meta": {"hexsha": "336f9c56a91b7411839d524e914819f384eddf02", "size": 53220, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "clustering/K-NN/Distributed-Memory/KNN_Distributed_code-OpenMP.cpp", "max_stars_repo_name": "mmvih/polus-plugins", "max_stars_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clustering/K-NN/Distributed-Memory/KNN_Distributed_code-OpenMP.cpp", "max_issues_repo_name": "mmvih/polus-plugins", "max_issues_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clustering/K-NN/Distributed-Memory/KNN_Distributed_code-OpenMP.cpp", "max_forks_repo_name": "mmvih/polus-plugins", "max_forks_repo_head_hexsha": "c424938e3f35900758f7d74f3dfec2adfb3228fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-26T19:23:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T19:23:57.000Z", "avg_line_length": 37.6912181303, "max_line_length": 190, "alphanum_fraction": 0.7105975197, "num_tokens": 15407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6138947306746309}}
{"text": "#include \"asymmetric_normal.hpp\"\n#include \"normal.hpp\"\n\n#include <gtest/gtest.h>\n\n#include <boost/random/mersenne_twister.hpp>\n\nusing namespace MultidimensionalArray;\nusing namespace ProbabilityDistributions;\n\nTEST(AsymmetricNormalTest, Likelihood) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  AsymmetricNormal<double> dist1(0.25, 0, 1);\n  Normal<double> dist2(0, 1);\n  Array<double> samples;\n  dist1.sample(samples, n_samples, rng);\n\n  auto indexes = Distribution<double>::sort_data(samples);\n\n  double likelihood11 = dist1.log_likelihood(samples);\n  double likelihood12 = dist2.log_likelihood(samples);\n\n  EXPECT_GE(likelihood11, likelihood12);\n\n  dist1.MLE(samples, indexes);\n  dist2.MLE(samples, indexes);\n\n  double likelihood21 = dist1.log_likelihood(samples);\n  double likelihood22 = dist2.log_likelihood(samples);\n\n  EXPECT_GE(likelihood22, likelihood12);\n  EXPECT_GE(likelihood21, likelihood11);\n  EXPECT_GT(likelihood21, likelihood22);\n\n  EXPECT_LT(0, dist1.get_sigma());\n  EXPECT_LT(0, dist1.get_p());\n  EXPECT_GT(1, dist1.get_p());\n}\n\nTEST(AsymmetricNormalTest, LikelihoodConsistency) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  AsymmetricNormal<double> dist1(0.5, 0, 1);\n  dist1.fix_p(true);\n  Normal<double> dist2(0, 1);\n  Array<double> samples;\n  dist1.sample(samples, n_samples, rng);\n\n  auto indexes = Distribution<double>::sort_data(samples);\n\n  double likelihood11 = dist1.log_likelihood(samples);\n  double likelihood12 = dist2.log_likelihood(samples);\n\n  EXPECT_DOUBLE_EQ(likelihood12, likelihood11);\n\n  dist1.MLE(samples, indexes);\n  dist2.MLE(samples, indexes);\n\n  double likelihood21 = dist1.log_likelihood(samples);\n  double likelihood22 = dist2.log_likelihood(samples);\n\n  EXPECT_DOUBLE_EQ(likelihood22, likelihood21);\n\n  EXPECT_NEAR(dist1.get_mu(), dist2.get_mu(), 1e-8);\n  EXPECT_DOUBLE_EQ(dist1.get_sigma(), dist2.get_sigma());\n}\n\nTEST(AsymmetricNormalTest, MLE) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  AsymmetricNormal<double> dist(0.5, 0, 1);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n  auto indexes = Distribution<double>::sort_data(samples);\n  dist.MLE(samples, indexes);\n\n  double p = dist.get_p(), mu = dist.get_mu(), sigma = dist.get_sigma();\n  double eps = 1e-4;\n  double ll = dist.log_likelihood(samples);\n\n  dist.set_p(p + eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_p(p - eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_p(p);\n\n  dist.set_mu(mu + eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_mu(mu - eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_mu(mu);\n\n  dist.set_sigma(sigma + eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_sigma(sigma - eps);\n  EXPECT_GE(ll, dist.log_likelihood(samples));\n  dist.set_sigma(sigma);\n}\n\nTEST(AsymmetricNormalTest, Samples) {\n  boost::random::mt19937 rng;\n  const unsigned int n_samples = 100;\n  AsymmetricNormal<double> dist(0.5, 0, 1);\n  Array<double> samples;\n  dist.sample(samples, n_samples, rng);\n  for (size_t i = 0; i < n_samples; i++) {\n    EXPECT_LT(-5, samples(i,0));\n    EXPECT_GT(5, samples(i,0));\n  }\n}\n", "meta": {"hexsha": "ed9c493fb9f5f6e9beb4119bf0e5d52b6056e5c0", "size": 3188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/asymmetric_normal.cpp", "max_stars_repo_name": "mirandaconrado/probability-distributions", "max_stars_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/asymmetric_normal.cpp", "max_issues_repo_name": "mirandaconrado/probability-distributions", "max_issues_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/asymmetric_normal.cpp", "max_forks_repo_name": "mirandaconrado/probability-distributions", "max_forks_repo_head_hexsha": "6b7d86e181237eb134e6df6da60200beed66922f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4642857143, "max_line_length": 72, "alphanum_fraction": 0.7296110414, "num_tokens": 842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505966, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6138947198899255}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation, \n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file    Rot3Q.cpp\n * @brief   Rotation (internal: quaternion representation*)\n * @author  Richard Roberts\n */\n\n#include <gtsam/config.h> // Get GTSAM_USE_QUATERNIONS macro\n\n#ifdef GTSAM_USE_QUATERNIONS\n\n#include <boost/math/constants/constants.hpp>\n#include <gtsam/geometry/Rot3.h>\n\nusing namespace std;\n\nnamespace gtsam {\n\n  static const Matrix I3 = eye(3);\n\n  /* ************************************************************************* */\n  Rot3::Rot3() : quaternion_(Quaternion::Identity()) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const Point3& col1, const Point3& col2, const Point3& col3) :\n      quaternion_((Eigen::Matrix3d() <<\n          col1.x(), col2.x(), col3.x(),\n          col1.y(), col2.y(), col3.y(),\n          col1.z(), col2.z(), col3.z()).finished()) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(double R11, double R12, double R13,\n      double R21, double R22, double R23,\n      double R31, double R32, double R33) :\n        quaternion_((Eigen::Matrix3d() <<\n            R11, R12, R13,\n            R21, R22, R23,\n            R31, R32, R33).finished()) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const Matrix3& R) :\n      quaternion_(R) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const Matrix& R) :\n      quaternion_(Matrix3(R)) {}\n\n//  /* ************************************************************************* */\n//   Rot3::Rot3(const Matrix3& R) :\n//       quaternion_(R) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const Quaternion& q) : quaternion_(q) {}\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Rx(double t) { return Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitX())); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Ry(double t) { return Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitY())); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Rz(double t) { return Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitZ())); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::RzRyRx(double x, double y, double z) { return Rot3(\n      Quaternion(Eigen::AngleAxisd(z, Eigen::Vector3d::UnitZ())) *\n      Quaternion(Eigen::AngleAxisd(y, Eigen::Vector3d::UnitY())) *\n      Quaternion(Eigen::AngleAxisd(x, Eigen::Vector3d::UnitX())));\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::rodriguez(const Vector& w, double theta) {\n    return Quaternion(Eigen::AngleAxisd(theta, w)); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::compose(const Rot3& R2,\n  boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n    if (H1) *H1 = R2.transpose();\n    if (H2) *H2 = I3;\n    return Rot3(quaternion_ * R2.quaternion_);\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::operator*(const Rot3& R2) const {\n    return Rot3(quaternion_ * R2.quaternion_);\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::inverse(boost::optional<Matrix&> H1) const {\n    if (H1) *H1 = -matrix();\n    return Rot3(quaternion_.inverse());\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::between(const Rot3& R2,\n  boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n    if (H1) *H1 = -(R2.transpose()*matrix());\n    if (H2) *H2 = I3;\n    return between_default(*this, R2);\n  }\n\n  /* ************************************************************************* */\n  Point3 Rot3::rotate(const Point3& p,\n        boost::optional<Matrix&> H1,  boost::optional<Matrix&> H2) const {\n    Matrix R = matrix();\n    if (H1) *H1 = R * skewSymmetric(-p.x(), -p.y(), -p.z());\n    if (H2) *H2 = R;\n    Eigen::Vector3d r = R * p.vector();\n    return Point3(r.x(), r.y(), r.z());\n  }\n\n  /* ************************************************************************* */\n  // Log map at identity - return the canonical coordinates of this rotation\n  Vector3 Rot3::Logmap(const Rot3& R) {\n    Eigen::AngleAxisd angleAxis(R.quaternion_);\n    if(angleAxis.angle() > M_PI)      // Important:  use the smallest possible\n      angleAxis.angle() -= 2.0*M_PI;  // angle, e.g. no more than PI, to keep\n    if(angleAxis.angle() < -M_PI)     // error continuous.\n      angleAxis.angle() += 2.0*M_PI;\n    return angleAxis.axis() * angleAxis.angle();\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::retract(const Vector& omega, Rot3::CoordinatesMode mode) const {\n    return compose(Expmap(omega));\n  }\n\n  /* ************************************************************************* */\n  Vector3 Rot3::localCoordinates(const Rot3& t2, Rot3::CoordinatesMode mode) const {\n    return Logmap(between(t2));\n  }\n\n  /* ************************************************************************* */\n  Matrix3 Rot3::matrix() const {return quaternion_.toRotationMatrix();}\n\n  /* ************************************************************************* */\n  Matrix3 Rot3::transpose() const {return quaternion_.toRotationMatrix().transpose();}\n\n  /* ************************************************************************* */\n  Point3 Rot3::r1() const { return Point3(quaternion_.toRotationMatrix().col(0)); }\n\n  /* ************************************************************************* */\n  Point3 Rot3::r2() const { return Point3(quaternion_.toRotationMatrix().col(1)); }\n\n  /* ************************************************************************* */\n  Point3 Rot3::r3() const { return Point3(quaternion_.toRotationMatrix().col(2)); }\n\n  /* ************************************************************************* */\n  Quaternion Rot3::toQuaternion() const { return quaternion_; }\n\n /* ************************************************************************* */\n\n} // namespace gtsam\n\n#endif\n", "meta": {"hexsha": "c5990153a713ff241664d78caf667b38e33c355c", "size": 6670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Rot3Q.cpp", "max_stars_repo_name": "Ellon/gtsam-3.1.0", "max_stars_repo_head_hexsha": "7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-13T21:19:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T12:14:04.000Z", "max_issues_repo_path": "gtsam/geometry/Rot3Q.cpp", "max_issues_repo_name": "Ellon/gtsam-3.1.0", "max_issues_repo_head_hexsha": "7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/geometry/Rot3Q.cpp", "max_forks_repo_name": "Ellon/gtsam-3.1.0", "max_forks_repo_head_hexsha": "7968c07cf79ff39ffce05dd7c1aadcd97d7c3c21", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1807228916, "max_line_length": 96, "alphanum_fraction": 0.4151424288, "num_tokens": 1459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6138947189460489}}
{"text": "#include <opencv2/opencv.hpp>\n#include <string>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace cv;\n\n// this program shows how to use optical flow\n\nstring file_1 = \"../1.png\";  // first image\nstring file_2 = \"../2.png\";  // second image\n\n// TODO implement this funciton\n/**\n * single level optical flow\n * @param [in] img1 the first image\n * @param [in] img2 the second image\n * @param [in] kp1 keypoints in img1\n * @param [in|out] kp2 keypoints in img2, if empty, use initial guess in kp1\n * @param [out] success true if a keypoint is tracked successfully\n * @param [in] inverse use inverse formulation?\n */\nvoid OpticalFlowSingleLevel(\n        const Mat &img1,\n        const Mat &img2,\n        const vector<KeyPoint> &kp1,\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse = false\n);\n\n// TODO implement this funciton\n/**\n * multi level optical flow, scale of pyramid is set to 2 by default\n * the image pyramid will be create inside the function\n * @param [in] img1 the first pyramid\n * @param [in] img2 the second pyramid\n * @param [in] kp1 keypoints in img1\n * @param [out] kp2 keypoints in img2\n * @param [out] success true if a keypoint is tracked successfully\n * @param [in] inverse set true to enable inverse formulation\n */\nvoid OpticalFlowMultiLevel(\n        const Mat &img1,\n        const Mat &img2,\n        const vector<KeyPoint> &kp1,\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse = false\n);\n\n/**\n * get a gray scale value from reference image (bi-linear interpolated)\n * @param img\n * @param x\n * @param y\n * @return\n */\ninline float GetPixelValue(const cv::Mat &img, float x, float y)\n{\n    uchar *data = &img.data[int(y) * img.step + int(x)];\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n    return float(\n            (1 - xx) * (1 - yy) * data[0] +\n            xx * (1 - yy) * data[1] +\n            (1 - xx) * yy * data[img.step] +\n            xx * yy * data[img.step + 1]\n    );\n}\n\n\nint main(int argc, char **argv)\n{\n\n    // images, note they are CV_8UC1, not CV_8UC3\n    Mat img1 = imread(file_1, 0);\n    if(img1.data == NULL )\n    {\n        perror(\"please check your path\");\n        return 0;\n    }\n    Mat img2 = imread(file_2, 0);\n    if(img2.data == NULL )\n    {\n        perror(\"please check your path\");\n        return 0;\n    }\n\n    // key points, using GFTT here.\n    vector<KeyPoint> kp1;\n    Ptr<GFTTDetector> detector = GFTTDetector::create(500, 0.01, 20); // maximum 500 keypoints\n    detector->detect(img1, kp1); //\u5339\u914d\u70b9\n\n    // now lets track these key points in the second image\n    // first use single level LK in the validation picture\n    vector<KeyPoint> kp2_single;\n    vector<bool> success_single;\n    OpticalFlowSingleLevel(img1, img2, kp1, kp2_single, success_single);\n\n    // then test multi-level LK\n    vector<KeyPoint> kp2_multi;\n    vector<bool> success_multi;\n    OpticalFlowMultiLevel(img1, img2, kp1, kp2_multi, success_multi);\n\n    // use opencv's flow for validation\n    vector<Point2f> pt1, pt2;\n    for (auto &kp: kp1) pt1.push_back(kp.pt);\n    vector<uchar> status;\n    vector<float> error;\n    cv::calcOpticalFlowPyrLK(img1, img2, pt1, pt2, status, error, cv::Size(8, 8));\n\n    // plot the differences of those functions\n    Mat img2_single;\n    cv::cvtColor(img2, img2_single, CV_GRAY2BGR);\n    for (int i = 0; i < kp2_single.size(); i++)\n    {\n        if (success_single[i])\n        {\n            cv::circle(img2_single, kp2_single[i].pt, 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_single, kp1[i].pt, kp2_single[i].pt, cv::Scalar(0, 250, 0));\n        }\n    }\n\n    Mat img2_multi;\n    cv::cvtColor(img2, img2_multi, CV_GRAY2BGR);\n    for (int i = 0; i < kp2_multi.size(); i++)\n    {\n        if (success_multi[i])\n        {\n            cv::circle(img2_multi, kp2_multi[i].pt, 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_multi, kp1[i].pt, kp2_multi[i].pt, cv::Scalar(0, 250, 0));\n        }\n    }\n\n    Mat img2_CV;\n    cv::cvtColor(img2, img2_CV, CV_GRAY2BGR);\n    for (int i = 0; i < pt2.size(); i++)\n    {\n        if (status[i])\n        {\n            cv::circle(img2_CV, pt2[i], 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_CV, pt1[i], pt2[i], cv::Scalar(0, 250, 0));\n        }\n    }\n\n    cv::imshow(\"tracked single level\", img2_single);\n    cv::imshow(\"tracked multi level\", img2_multi);\n    cv::imshow(\"tracked by opencv\", img2_CV);\n    cv::waitKey(0);\n\n    return 0;\n}\n\nvoid OpticalFlowSingleLevel(\n        const Mat &img1,\n        const Mat &img2,\n        const vector<KeyPoint> &kp1, //\u7279\u5f81\u70b9\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse)\n{\n\n    // parameters\n    int half_patch_size = 4;\n    int iterations = 10;\n    bool have_initial = !kp2.empty();\n\n    for (size_t i = 0; i < kp1.size(); i++) //\u53d6\u7279\u5f81\u70b9\n    {\n        auto kp = kp1[i];\n        double dx = 0, dy = 0; // dx,dy need to be estimated\n        if (have_initial)\n        {\n            dx = kp2[i].pt.x - kp.pt.x;\n            dy = kp2[i].pt.y - kp.pt.y;\n        }\n\n        double cost = 0, lastCost = 0;\n        bool succ = true; // indicate if this point succeeded\n\n        // Gauss-Newton iterations\n        for (int iter = 0; iter < iterations; iter++)\n        {\n            Eigen::Matrix2d H = Eigen::Matrix2d::Zero();\n            Eigen::Vector2d b = Eigen::Vector2d::Zero();\n            cost = 0;\n\n            if (kp.pt.x + dx <= half_patch_size || kp.pt.x + dx >= img1.cols - half_patch_size ||\n                kp.pt.y + dy <= half_patch_size || kp.pt.y + dy >= img1.rows - half_patch_size)\n            {   // go outside\n                succ = false;\n                break;\n            }\n\n            // compute cost and jacobian\n            for (int x = -half_patch_size; x < half_patch_size; x++)// \u904d\u5386\u56fe\u50cf\u5757\n            {\n                for (int y = -half_patch_size; y < half_patch_size; y++)// \u904d\u5386\u56fe\u50cf\u5757\n                {\n\n                    // TODO START YOUR CODE HERE (~8 lines)\n                    double X = kp.pt.x +x;\n                    double Y = kp.pt.y +y;\n                    bool have_computed_J = false;\n                    error =   -(GetPixelValue(img1,X,Y) - GetPixelValue(img2,X+dx,Y+dy)) ;\n//                    error = GetPixelValue(img1,X,Y) - GetPixelValue(img2,X+dx,Y+dy);\n                    Eigen::Vector2d J;  // Jacobian\n                    if (inverse == false)\n                    {\n                        // Forward Jacobian\n                        J[0] = ( GetPixelValue(img2,X+dx+1,Y+dy) - GetPixelValue(img2,X+dx-1,Y+dy) )/2;\n                        J[1] = ( GetPixelValue(img2,X+dx,Y+dy+1) - GetPixelValue(img2,X+dx,Y+dy-1) )/2;\n\n                    }\n                    else\n                    {\n                        // Inverse Jacobian\n                        // NOTE this J does not change when dx, dy is updated, so we can store it and only compute error\n\n                        if(have_computed_J == false)\n                        {\n                            J[0] = (GetPixelValue(img1, X + 1, Y) - GetPixelValue(img1, X - 1, Y)) / 2;\n                            J[1] = (GetPixelValue(img1, X, Y + 1) - GetPixelValue(img1, X, Y - 1)) / 2;\n                            have_computed_J = true;\n                        }\n\n                    // compute H, b and set cost;\n                    H;\n\n                    b;\n\n                    cost;\n\n                    // TODO END YOUR CODE HERE\n\n                }\n\n            }\n\n\n            // compute update\n            // TODO START YOUR CODE HERE (~1 lines)\n            Eigen::Vector2d update;\n\n\n\n            // TODO END YOUR CODE HERE\n\n            if (isnan(update[0]))\n            {\n                // sometimes occurred when we have a black or white patch and H is irreversible\n                cout << \"update is nan\" << endl;\n                succ = false;\n                break;\n            }\n            if (iter > 0 && cost > lastCost)\n            {\n                cout << \"cost increased: \" << cost << \", \" << lastCost << endl;\n                break;\n            }\n\n            // update dx, dy\n            dx += update[0];\n            dy += update[1];\n            lastCost = cost;\n            succ = true;\n        }\n\n        success.push_back(succ);\n\n        // set kp2\n        if (have_initial)\n        {\n            kp2[i].pt = kp.pt + Point2f(dx, dy);\n        } else\n        {\n            KeyPoint tracked = kp;\n            tracked.pt += cv::Point2f(dx, dy);\n            kp2.push_back(tracked);\n        6\n    }\n}\n\nvoid OpticalFlowMultiLevel(\n        const Mat &img1,\n        const Mat &img2,\n        const vector<KeyPoint> &kp1,\n        vector<KeyPoint> &kp2,\n        vector<bool> &success,\n        bool inverse)\n{\n\n    // parameters\n    int pyramids = 4;\n    double pyramid_scale = 0.5;\n    double scales[] = {1.0, 0.5, 0.25, 0.125};\n\n    // create pyramids\n    vector<Mat> pyr1, pyr2; // image pyramids\n    // TODO START YOUR CODE HERE (~8 lines)\n    for (int i = 0; i < pyramids; i++)\n    {\n\n    }\n    // TODO END YOUR CODE HERE\n\n    // coarse-to-fine LK tracking in pyramids\n    // TODO START YOUR CODE HERE\n\n    // TODO END YOUR CODE HERE\n    // don't forget to set the results into kp2\n}\n", "meta": {"hexsha": "c858529f00e951ed79a6fe7d0f97c63befc79a49", "size": 9214, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homework/homework_L6/my_optical_flow.cpp", "max_stars_repo_name": "MrCocoaCat/slambook", "max_stars_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-02-13T05:39:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-15T17:35:25.000Z", "max_issues_repo_path": "homework/homework_L6/my_optical_flow.cpp", "max_issues_repo_name": "MrCocoaCat/slambook", "max_issues_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homework/homework_L6/my_optical_flow.cpp", "max_forks_repo_name": "MrCocoaCat/slambook", "max_forks_repo_head_hexsha": "1eb2c3b081c6f668f342ae8d3fa536748bedc77d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-21T13:59:20.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-21T13:59:20.000Z", "avg_line_length": 29.2507936508, "max_line_length": 120, "alphanum_fraction": 0.5239852399, "num_tokens": 2564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6138696762507084}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[simplify_inserter\r\n//` Simplify a linestring using an output iterator\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n\r\nint main()\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<double> P;\r\n    typedef boost::geometry::model::linestring<P> L;\r\n\r\n    L line;\r\n    boost::geometry::read_wkt(\"linestring(1.1 1.1, 2.5 2.1, 3.1 3.1, 4.9 1.1, 3.1 1.9)\", line);\r\n\r\n    typedef boost::geometry::strategy::distance::projected_point<P, P> DS;\r\n    typedef boost::geometry::strategy::simplify::douglas_peucker<P, DS> simplification;\r\n\r\n    L simplified;\r\n    boost::geometry::simplify_inserter(line, std::back_inserter(simplified), 0.5, simplification()); //std::ostream_iterator<P>(std::cout, \"\\n\"), 0.5);//);\r\n    //std::cout << simplified[0];\r\n    //boost::geometry::simplify_inserter(line, std::ostream_iterator<P>(std::cout, \"\\n\"), 0.5);//, simplification());\r\n\r\n    std::ostream_iterator<P> out(std::cout, \"\\n\");\r\n    std::copy(simplified.begin(), simplified.end(), out);\r\n\r\n    std::cout\r\n        << \"  original: \" << boost::geometry::dsv(line) << std::endl\r\n        << \"simplified: \" << boost::geometry::dsv(simplified) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[simplify_inserter_output\r\n/*`\r\nOutput:\r\n[pre\r\nsimplify_inserter: 16\r\nsimplify_inserter: 0.339837\r\n]\r\n*/\r\n//]\r\n/*\r\nOUTPUT\r\nPOINT(1.1 1.1)  original: ((1.1, 1.1), (2.5, 2.1), (3.1, 3.1), (4.9, 1.1), (3.1, 1.9))\r\nsimplified: ((1.1, 1.1), (3.1, 3.1), (4.9, 1.1), (3.1, 1.9))\r\n*/\r\n/*\r\nOUTPUT\r\nPOINT(1.1 1.1)  original: ((1.1, 1.1), (2.5, 2.1), (3.1, 3.1), (4.9, 1.1), (3.1, 1.9))\r\nsimplified: ((1.1, 1.1), (3.1, 3.1), (4.9, 1.1), (3.1, 1.9))\r\n*/\r\n/*\r\nOUTPUT\r\nPOINT(1.1 1.1)  original: ((1.1, 1.1), (2.5, 2.1), (3.1, 3.1), (4.9, 1.1), (3.1, 1.9))\r\nsimplified: ((1.1, 1.1), (3.1, 3.1), (4.9, 1.1), (3.1, 1.9))\r\n*/\r\n", "meta": {"hexsha": "8b1ee1c7738b0a0ad72e06bf721682effc712fac", "size": 2241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/geometry/doc/src/examples/algorithms/simplify_insert_with_strategy.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "libs/boost/libs/geometry/doc/src/examples/algorithms/simplify_insert_with_strategy.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/geometry/doc/src/examples/algorithms/simplify_insert_with_strategy.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 31.125, "max_line_length": 156, "alphanum_fraction": 0.6064257028, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.613869672026091}}
{"text": "// -----------------------------------------------------------------------\r\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\r\n//\r\n// Copyright (c) German Cancer Research Center (DKFZ),\r\n// Software development for Integrated Diagnostics and Therapy (SIDT).\r\n// ALL RIGHTS RESERVED.\r\n// See rttbCopyright.txt or\r\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html\r\n//\r\n// This software is distributed WITHOUT ANY WARRANTY; without even\r\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n// PURPOSE.  See the above copyright notices for more information.\r\n//\r\n//------------------------------------------------------------------------\r\n\r\n#include <ctime>\r\n\r\n#include <boost/random.hpp>\r\n#include <boost/random/normal_distribution.hpp>\r\n\r\n#include \"rttbBioModel.h\"\r\n#include \"rttbBioModelScatterPlots.h\"\r\n#include \"rttbInvalidParameterException.h\"\r\n\r\nnamespace rttb\r\n{\r\n\tnamespace models\r\n\t{\r\n\r\n\t\t/* Initiate Random Number generator with current time */\r\n\t\tboost::random::mt19937 rng(static_cast<unsigned>(time(nullptr)));\r\n\t\t/* Generate random number between 0 and 1 */\r\n\t\tboost::random::uniform_01<boost::mt19937> uniDist(rng);\r\n\r\n\t\tScatterPlotType getScatterPlotVary1Parameter(BioModel& aModel, int aParamId,\r\n\t\t        BioModelParamType aMean, BioModelParamType aVariance, DoseTypeGy aNormalisationDose,\r\n\t\t        int numberOfPoints,\r\n\t\t        DoseTypeGy aMinDose, DoseTypeGy aMaxDose)\r\n\t\t{\r\n\t\t\tScatterPlotType scatterPlotData;\r\n\r\n\t\t\tif (aVariance == 0)\r\n\t\t\t{\r\n\t\t\t\t//set to small positive value to avoid negative infinity!\r\n\t\t\t\taVariance = 1e-30;\r\n\t\t\t}\r\n\r\n\t\t\tif (aMaxDose <= aMinDose)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: aMaxDose must be > aMinDose!\");\r\n\t\t\t}\r\n\r\n\t\t\tif (aNormalisationDose <= 0)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: aNormalisationDose must be > 0!\");\r\n\t\t\t}\r\n\r\n\t\t\t/* Choose Normal Distribution */\r\n\t\t\tboost::random::normal_distribution<double> gaussian_dist(0, aVariance);\r\n\r\n\t\t\t/* Create a Gaussian Random Number generator\r\n\t\t\t*  by binding with previously defined\r\n\t\t\t*  normal distribution object\r\n\t\t\t*/\r\n\t\t\tboost::random::variate_generator<boost::mt19937&, boost::normal_distribution<double> > generator(\r\n\t\t\t    rng, gaussian_dist);\r\n\r\n\t\t\tint i = 0;\r\n\r\n\t\t\twhile (i < numberOfPoints)\r\n\t\t\t{\r\n\t\t\t\tdouble paramValue, probability;\r\n\t\t\t\tdouble randomValue = generator();\r\n\t\t\t\tparamValue = randomValue + aMean;\r\n\t\t\t\tprobability = normal_pdf(randomValue, aVariance);\r\n\r\n\t\t\t\tif (probability > 1)\r\n\t\t\t\t{\r\n\t\t\t\t\tprobability = 1;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//randomly select a dose between aMinDose and aMaxDose\r\n\t\t\t\tdouble dose = uniDist() * (aMaxDose - aMinDose) + aMinDose;\r\n\r\n\t\t\t\tif (probability > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\taModel.setParameterByID(aParamId, paramValue);\r\n\t\t\t\t\t\taModel.init(dose / aNormalisationDose);\r\n\t\t\t\t\t\tdouble value = aModel.getValue();\r\n\t\t\t\t\t\tstd::pair<double, double> modelProbPair = std::make_pair(value, probability);\r\n\t\t\t\t\t\tscatterPlotData.insert(std::pair<double, std::pair<double, double> >(dose, modelProbPair));\r\n\t\t\t\t\t\ti++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (core::InvalidParameterException& /*e*/)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t//repeat evaluation to guarantee the correct number of scatter values\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn scatterPlotData;\r\n\t\t}\r\n\r\n\t\tdouble normal_pdf(double aValue, double aVariance)\r\n\t\t{\r\n\t\t\tstatic const double inv_sqrt_2pi = 0.3989422804014327;\r\n\t\t\tdouble a = (aValue) / aVariance;\r\n\r\n\t\t\treturn inv_sqrt_2pi / aVariance * std::exp(-0.5f * a * a);\r\n\t\t}\r\n\r\n\t\tScatterPlotType getScatterPlotVaryParameters(BioModel& aModel,\r\n\t\t        std::vector<int> aParamIdVec, BioModel::ParamVectorType aMeanVec,\r\n\t\t        BioModel::ParamVectorType aVarianceVec,\r\n\t\t        DoseTypeGy aNormalisationDose, int numberOfPoints, DoseTypeGy aMinDose, DoseTypeGy aMaxDose)\r\n\t\t{\r\n\r\n\t\t\tScatterPlotType scatterPlotData;\r\n\r\n\t\t\tif (aMaxDose <= aMinDose)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: aMaxDose must be > aMinDose!\");\r\n\t\t\t}\r\n\r\n\t\t\tif (aNormalisationDose <= 0)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: aNormalisationDose must be > 0!\");\r\n\t\t\t}\r\n\r\n\t\t\t//all input vectors need to have the same size\r\n\t\t\tif (((aVarianceVec.size() != aMeanVec.size()) || (aVarianceVec.size() != aParamIdVec.size())))\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidParameterException(\"Parameter vectors have different sizes!\");\r\n\t\t\t}\r\n\r\n\t\t\tfor (double & v : aVarianceVec)\r\n\t\t\t{\r\n\t\t\t\t//set to small positive value to avoid negative infinity!\r\n\t\t\t\tif (v == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tv = 1e-30;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tdouble paramValue;\r\n\r\n\r\n\t\t\t// vary all parameters for each scattered point\r\n\t\t\tint i = 0;\r\n\r\n\t\t\twhile (i < numberOfPoints)\r\n\t\t\t{\r\n\t\t\t\tdouble probability = 1;\r\n\r\n\t\t\t\tfor (GridIndexType j = 0; j < aParamIdVec.size(); j++)\r\n\t\t\t\t{\r\n\t\t\t\t\t/* Choose Normal Distribution */\r\n\t\t\t\t\tboost::random::normal_distribution<double> gaussian_dist(0, aVarianceVec.at(j));\r\n\r\n\t\t\t\t\t/* Create a Gaussian Random Number generator\r\n\t\t\t\t\t*  by binding with previously defined\r\n\t\t\t\t\t*  normal distribution object\r\n\t\t\t\t\t*/\r\n\t\t\t\t\tboost::random::variate_generator<boost::mt19937&, boost::normal_distribution<double> > generator(\r\n\t\t\t\t\t    rng, gaussian_dist);\r\n\r\n\t\t\t\t\tdouble randomValue = generator();\r\n\t\t\t\t\tparamValue = randomValue + aMeanVec.at(j);\r\n\r\n\t\t\t\t\tif (aVarianceVec.at(j) != 0)\r\n\t\t\t\t\t{\r\n\r\n\t\t\t\t\t\t/* calculate combined probability */\r\n\t\t\t\t\t\tprobability = probability * normal_pdf(randomValue, aVarianceVec.at(j));\r\n\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: Variance should not be 0!\");\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\taModel.setParameterByID(aParamIdVec.at(j), paramValue);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//randomly select a dose between aMinDose and aMaxDose\r\n\t\t\t\tdouble dose = uniDist() * (aMaxDose - aMinDose) + aMinDose;\r\n\r\n\r\n\t\t\t\tif (probability > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\taModel.init(dose / aNormalisationDose);\r\n\t\t\t\t\t\tdouble value = aModel.getValue();\r\n\t\t\t\t\t\tstd::pair<double, double> modelProbPair = std::make_pair(value, probability);\r\n\t\t\t\t\t\tscatterPlotData.insert(std::pair<double, std::pair<double, double> >(dose, modelProbPair));\r\n\t\t\t\t\t\ti++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (core::InvalidParameterException& /*e*/)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t//repeat evaluation to guarantee the correct number of scatter values\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn scatterPlotData;\r\n\t\t}\r\n\r\n\t}//end namespace models\r\n}//end namespace rttb\r\n", "meta": {"hexsha": "67565ef729201cfc8a7d04df161519fb109c63df", "size": 6398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/models/rttbBioModelScatterPlots.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "code/models/rttbBioModelScatterPlots.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/models/rttbBioModelScatterPlots.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 29.7581395349, "max_line_length": 103, "alphanum_fraction": 0.6411378556, "num_tokens": 1652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789452074398, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.6137803369975124}}
{"text": "#define CATCH_CONFIG_MAIN\r\n#include \"catch2/catch.hpp\"\r\n#include <Eigen/Dense>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <cassert>\r\n#include \"Network.h\"\r\n\r\n\r\n\r\nusing Eigen::MatrixXd;\r\n \r\nbool test_vs(){\r\n\tMatrixXd expected_result (5,1) ;\r\n\texpected_result << 24, -8, 20, -4, 1;\r\n\tstd::ifstream net_file (\"./test_net.txt\");\r\n    assert(net_file.is_open());\r\n    Network net = Network();\r\n    net.preprocess_netlist(net_file);\r\n    net.parse_netlist(net_file);\r\n    net.calculate();\r\n    net_file.close();\r\n    return expected_result.isApprox(net.get_result_matrix());\r\n}\r\n\r\nbool test_cs(){\r\n\tMatrixXd expected_result (3,1) ;\r\n\texpected_result << 8, -24, -11;\r\n\tstd::ifstream net_file2 (\"./test_net2.txt\");\r\n    assert(net_file2.is_open());\r\n    Network net = Network();\r\n    net.preprocess_netlist(net_file2);\r\n    net.parse_netlist(net_file2);\r\n    net.calculate();\r\n    net_file2.close();\r\n    return expected_result.isApprox(net.get_result_matrix());\r\n}\r\n\r\n\r\nTEST_CASE( \"Circuit test\" ) {\r\n\tREQUIRE(test_vs() == true);\r\n\tREQUIRE(test_cs() == true);\r\n}\r\n", "meta": {"hexsha": "cb8677944e2d59710d2d888f75d4d6cf082dcdbf", "size": 1064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_main.cpp", "max_stars_repo_name": "appiad/spice", "max_stars_repo_head_hexsha": "b82709d9334efa3264f37b7e8eb55130f9e494c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/test_main.cpp", "max_issues_repo_name": "appiad/spice", "max_issues_repo_head_hexsha": "b82709d9334efa3264f37b7e8eb55130f9e494c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_main.cpp", "max_forks_repo_name": "appiad/spice", "max_forks_repo_head_hexsha": "b82709d9334efa3264f37b7e8eb55130f9e494c3", "max_forks_repo_licenses": ["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.1818181818, "max_line_length": 62, "alphanum_fraction": 0.6607142857, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.6137166477846651}}
{"text": "#include <blitz/array.h>\n#include <fstream>\n\nusing namespace blitz;\n\nvoid makeLogo();\n\nint main()\n{\n    makeLogo();\n    return 0;\n}\n\nvoid setInitialConditions(Array<float,2>& c, Array<float,2>& P1, \n    Array<float,2>& P2, Array<float,2>& P3, int N, int M);\n\nvoid snapshot(const Array<float,2>& P, const Array<float,2>& c);\n\nvoid makeLogo()\n{\n    const int N = 300, M = 900;\n    int niters = 3000;\n\n    Array<float,2> P1, P2, P3, c;\n    allocateArrays(shape(N,M), P1, P2, P3, c);\n    Range I(1,N-2), J(1,M-2);\n\n    setInitialConditions(c, P1, P2, P3, N, M);\n\n    for (int iter=0; iter < niters; ++iter)\n    {\n        P3(I,J) = (2-4*c(I,J)) * P2(I,J)\n          + c(I,J)*(P2(I-1,J) + P2(I+1,J) + P2(I,J-1) + P2(I,J+1))\n          - P1(I,J);\n\n        cycleArrays(P1,P2,P3);\n\n        snapshot(P2, c);\n    }\n\n}\n\nvoid setInitialConditions(Array<float,2>& c, Array<float,2>& P1,\n    Array<float,2>& P2, Array<float,2>& P3, int N, int M)\n{\n    // Set the velocity field\n    c = 0.3;\n\n    ifstream ifs(\"blitz3.pgm\");\n    char tmpBuf[128];\n    int pixel;\n    ifs.getline(tmpBuf, 128);\n    ifs.getline(tmpBuf, 128);\n    ifs.getline(tmpBuf, 128);\n\n    for (int pi=0; pi < 199; ++pi)\n    {\n        for (int pj=0; pj < 798; ++pj)\n        {\n            ifs >> pixel;\n            if (pixel)\n                c(pi+50,pj+56) = 0.02;\n        }\n    }\n\n    // Initial pressure distribution: gaussian pulse\n    using namespace blitz::tensor;\n    int cr = N/6-1;\n//    int cc = 7.0*M/8.0-1;\n    float s2 = 64.0 * 9.0 / pow2(N/2.0);\n    P1 = 0.0;\n//    P2 = exp(-(pow2(i-cr)+pow2(j-cc)) * s2);\n    P2 = exp(-(pow2(i-cr)) * s2);\n    \n    P3 = 0.0;\n}\n\n\nvoid snapshot(const Array<float,2>& P, const Array<float,2>& c)\n{\n    static int count = 0, snapshotNum = 0;\n    if (++count < 50)\n        return;\n\n    count = 0;\n    ++snapshotNum;\n    char filename[128];\n    sprintf(filename, \"logo%03d.m\", snapshotNum);\n\n    ofstream ofs(filename);\n    int N = P.length(firstDim);\n    int M = P.length(secondDim);\n\n    float Pmin = -0.6;\n    float PScale = 1.0/1.2;\n    float VScale = 1.0;\n\n    ofs << \"P\" << snapshotNum << \" = [ \";\n    for (int i=0; i < N; ++i)\n    {\n        for (int j=0; j < M; ++j)\n        {\n            float value1 = (P(i,j)-Pmin)*PScale;\n            float value2 = c(i,j)*VScale;\n            int r1 = value1 * 4096;\n            int r2 = value2 * 4096;\n            ofs << r1 << \" \" << r2 << \"    \";\n        }\n        if (i < N-1)\n            ofs << \";\" << endl;\n    }\n    ofs << \"];\" << endl;\n}\n\n", "meta": {"hexsha": "73f9f87c36e82d36982fe15f907f472ec8def97f", "size": 2480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/makelogo.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/makelogo.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/makelogo.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5652173913, "max_line_length": 66, "alphanum_fraction": 0.4967741935, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6136678903301186}}
{"text": "#include \"linalg.h\"\n#include <cstring>\n\n// this files requires Eigen.\n// Linux:\n//   sudo apt install libeigen3-dev\n// Windows:\n//   download it from http://eigen.tuxfamily.org/\n//   unzip it in ./gmsh-api/eigen\n//   be sure to load the environment\n//   (the eigen folder should be added to INCLUDE)\n\n#include <Eigen/Dense>\n\n// print a vector<double> as \"[v1, v2, v3, ...]\"\n\nstd::ostream &operator<<(std::ostream &s, std::vector<double> const &v)\n{\n    s << '[';\n    for (int i = 0; i < v.size(); ++i)\n    {\n        if (std::abs(v[i]) < 1e-10)\n            s << \"0\";\n        else\n            s << v[i];\n        if (i != v.size() - 1)\n            s << \", \";\n    }\n    s << ']';\n    return s;\n}\n\n// create and return a random matrix of dimension \"dim\"\n\nstd::vector<double> randomMatrix(int dim)\n{\n    // create a dim x dim mrandom matrix using Eigen\n    Eigen::MatrixXd mat = Eigen::MatrixXd::Random(dim, dim);\n    // copy its values into a std::vector\n    std::vector<double> v(dim * dim);\n    std::memcpy(&(v[0]), mat.data(), dim * dim * sizeof(double));\n    return v;\n}\n\n// compute the inverse of a square matrix of size (dim,dim) given as a std::vector<double>\n// return the inverse as a std::vector<double>\n\nstd::vector<double> inverse(std::vector<double> &M, int dim)\n{\n    Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>> mapA(&(M[0]), dim, dim);\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> B = mapA.inverse();\n    std::vector<double> invM(dim * dim);\n    std::memcpy(&(invM[0]), B.data(), dim * dim * sizeof(double));\n    return invM;\n}\n\n// multiply 2 matrices given as std::vector<double>\n// return the result as a std::vector<double>\n\nstd::vector<double> matmult(std::vector<double> &A, std::vector<double> &B, int dim)\n{\n    assert(A.size() == dim * dim);\n    assert(B.size() == dim * dim);\n\n    std::vector<double> C(dim * dim);\n    for (int i = 0; i < dim; ++i)\n        for (int j = 0; j < dim; ++j)\n        {\n            double v = 0;\n            for (int k = 0; k < dim; ++k)\n                v += A[i * dim + k] * B[k * dim + j];\n            C[i * dim + j] = v;\n        }\n    return C;\n}\n", "meta": {"hexsha": "dc3c8a953d372ee269928f002033ec025a372cef", "size": 2165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "classes/gpu/samples/invert_matrix/linalg.cpp", "max_stars_repo_name": "rboman/progs", "max_stars_repo_head_hexsha": "c60b4e0487d01ccd007bcba79d1548ebe1685655", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-12T13:26:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T16:14:53.000Z", "max_issues_repo_path": "classes/gpu/samples/invert_matrix/linalg.cpp", "max_issues_repo_name": "rboman/progs", "max_issues_repo_head_hexsha": "c60b4e0487d01ccd007bcba79d1548ebe1685655", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-01T07:08:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-28T07:32:42.000Z", "max_forks_repo_path": "classes/gpu/samples/invert_matrix/linalg.cpp", "max_forks_repo_name": "rboman/progs", "max_forks_repo_head_hexsha": "c60b4e0487d01ccd007bcba79d1548ebe1685655", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T13:13:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-13T20:08:15.000Z", "avg_line_length": 28.4868421053, "max_line_length": 111, "alphanum_fraction": 0.5635103926, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.613667879921052}}
{"text": "#ifndef NOBODY_CAMERA_H_\n#define NOBODY_CAMERA_H_\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <nobody/orthonormal_frame.hpp>\n\nnamespace nobody {\n\nclass Camera {\n  using Vector3f = Eigen::Vector3f;\n\n public:\n  Camera() = default;\n  Camera(int width, int height, float fov)\n      : screen_width_(width), screen_height_(height), field_of_view_(fov) {}\n\n  const Vector3f& position() const { return frame_.origin(); }\n  Vector3f direction() const { return -frame_.back(); }\n  const Orthonormal_frame& frame() const { return frame_; }\n  float field_of_view() const { return field_of_view_; }\n  float vertical_field_of_view() const;\n  float horizontal_field_of_view() const;\n  float opengl_field_of_view() const;\n  int screen_width() const { return screen_width_; }\n  int screen_height() const { return screen_height_; }\n  float pixel_size() const { return pixel_size_; }\n  float aspect_ratio() const { return aspect_ratio_; }\n\n  void look_at(const Vector3f& eye, const Vector3f& center, const Vector3f& up);\n  void set_screen_resolution(int width, int height);\n  void set_field_of_view(float fov);\n  void set_vertical_field_of_view(float fov) { set_field_of_view(fov); }\n  void set_horizontal_field_of_view(float fov);\n\n private:\n  void compute_pixel_size();\n  void compute_aspect_ratio();\n\n private:\n  Orthonormal_frame frame_;\n\n  float field_of_view_;\n  int screen_height_;\n  int screen_width_;\n  float pixel_size_;\n  float aspect_ratio_;\n};\n\n}  // namespace nobody\n\n#endif  // NOBODY_CAMERA_H_", "meta": {"hexsha": "4d6037bce5d36f0630cd501857011dcb3459f1a7", "size": 1496, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nobody/camera.hpp", "max_stars_repo_name": "lyrahgames/nobody", "max_stars_repo_head_hexsha": "868b1a6c872f051f76c6ee852a977053e1ac35d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-05T08:48:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-05T08:48:05.000Z", "max_issues_repo_path": "nobody/camera.hpp", "max_issues_repo_name": "lyrahgames/nobody", "max_issues_repo_head_hexsha": "868b1a6c872f051f76c6ee852a977053e1ac35d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T14:48:22.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-14T23:32:50.000Z", "max_forks_repo_path": "nobody/camera.hpp", "max_forks_repo_name": "lyrahgames/nobody", "max_forks_repo_head_hexsha": "868b1a6c872f051f76c6ee852a977053e1ac35d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7692307692, "max_line_length": 80, "alphanum_fraction": 0.7493315508, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6136457297775246}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file NaiveSE3Tests.cpp\n/// \\brief Unit tests for the naive implementation of the SE3 Lie Group math.\n/// \\details Unit tests for the various Lie Group functions will test both\n/// special cases,\n///          and randomly generated cases.\n///\n/// \\author Sean Anderson\n//////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <gtest/gtest.h>\n\n#include <math.h>\n#include <iomanip>\n#include <ios>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <lgmath/CommonMath.hpp>\n#include <lgmath/se3/Operations.hpp>\n#include <lgmath/so3/Operations.hpp>\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n///\n/// UNIT TESTS OF SE(3) MATH\n///\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of SE(3) hat function\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, Test4x4HatFunction) {\n  // Number of random tests\n  const unsigned numTests = 20;\n\n  // Add vectors to be tested - random\n  std::vector<Eigen::Matrix<double, 6, 1> > trueVecs;\n  for (unsigned i = 0; i < numTests; i++) {\n    trueVecs.push_back(Eigen::Matrix<double, 6, 1>::Random());\n  }\n\n  // Setup truth matrices\n  std::vector<Eigen::Matrix<double, 4, 4> > trueMats;\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double, 4, 4> mat;\n    mat << 0.0, -trueVecs.at(i)[5], trueVecs.at(i)[4], trueVecs.at(i)[0],\n        trueVecs.at(i)[5], 0.0, -trueVecs.at(i)[3], trueVecs.at(i)[1],\n        -trueVecs.at(i)[4], trueVecs.at(i)[3], 0.0, trueVecs.at(i)[2], 0.0, 0.0,\n        0.0, 0.0;\n    trueMats.push_back(mat);\n  }\n\n  // Test the function\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double, 4, 4> testMat = lgmath::se3::hat(trueVecs.at(i));\n    std::cout << \"true: \" << trueMats.at(i) << std::endl;\n    std::cout << \"func: \" << testMat << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(trueMats.at(i), testMat, 1e-6));\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of SE(3) curlyhat function\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, TestCurlyHatFunction) {\n  // Number of random tests\n  const unsigned numTests = 20;\n\n  // Add vectors to be tested - random\n  std::vector<Eigen::Matrix<double, 6, 1> > trueVecs;\n  for (unsigned i = 0; i < numTests; i++) {\n    trueVecs.push_back(Eigen::Matrix<double, 6, 1>::Random());\n  }\n\n  // Setup truth matrices\n  std::vector<Eigen::Matrix<double, 6, 6> > trueMats;\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double, 6, 6> mat;\n    mat << 0.0, -trueVecs.at(i)[5], trueVecs.at(i)[4], 0.0, -trueVecs.at(i)[2],\n        trueVecs.at(i)[1], trueVecs.at(i)[5], 0.0, -trueVecs.at(i)[3],\n        trueVecs.at(i)[2], 0.0, -trueVecs.at(i)[0], -trueVecs.at(i)[4],\n        trueVecs.at(i)[3], 0.0, -trueVecs.at(i)[1], trueVecs.at(i)[0], 0.0, 0.0,\n        0.0, 0.0, 0.0, -trueVecs.at(i)[5], trueVecs.at(i)[4], 0.0, 0.0, 0.0,\n        trueVecs.at(i)[5], 0.0, -trueVecs.at(i)[3], 0.0, 0.0, 0.0,\n        -trueVecs.at(i)[4], trueVecs.at(i)[3], 0.0;\n    trueMats.push_back(mat);\n  }\n\n  // Test the function\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double, 6, 6> testMat = lgmath::se3::curlyhat(trueVecs.at(i));\n    std::cout << \"true: \" << trueMats.at(i) << std::endl;\n    std::cout << \"func: \" << testMat << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(trueMats.at(i), testMat, 1e-6));\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of homogeneous point to 4x6 matrix function\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, TestPointTo4x6MatrixFunction) {\n  // Number of random tests\n  const unsigned numTests = 20;\n\n  // Add vectors to be tested - random\n  std::vector<Eigen::Matrix<double, 4, 1> > trueVecs;\n  for (unsigned i = 0; i < numTests; i++) {\n    trueVecs.push_back(Eigen::Matrix<double, 4, 1>::Random());\n  }\n\n  // Setup truth matrices\n  std::vector<Eigen::Matrix<double, 4, 6> > trueMats;\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double, 4, 6> mat;\n    mat << trueVecs.at(i)[3], 0.0, 0.0, 0.0, trueVecs.at(i)[2],\n        -trueVecs.at(i)[1], 0.0, trueVecs.at(i)[3], 0.0, -trueVecs.at(i)[2],\n        0.0, trueVecs.at(i)[0], 0.0, 0.0, trueVecs.at(i)[3], trueVecs.at(i)[1],\n        -trueVecs.at(i)[0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n    trueMats.push_back(mat);\n  }\n\n  // Test the 3x1 function with scaling param\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double, 4, 6> testMat =\n        lgmath::se3::point2fs(trueVecs.at(i).head<3>(), trueVecs.at(i)[3]);\n    std::cout << \"true: \" << trueMats.at(i) << std::endl;\n    std::cout << \"func: \" << testMat << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(trueMats.at(i), testMat, 1e-6));\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of homogeneous point to 6x4 matrix function\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, TestPointTo6x4MatrixFunction) {\n  // Number of random tests\n  const unsigned numTests = 20;\n\n  // Add vectors to be tested - random\n  std::vector<Eigen::Matrix<double, 4, 1> > trueVecs;\n  for (unsigned i = 0; i < numTests; i++) {\n    trueVecs.push_back(Eigen::Matrix<double, 4, 1>::Random());\n  }\n\n  // Setup truth matrices\n  std::vector<Eigen::Matrix<double, 6, 4> > trueMats;\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double, 6, 4> mat;\n    mat << 0.0, 0.0, 0.0, trueVecs.at(i)[0], 0.0, 0.0, 0.0, trueVecs.at(i)[1],\n        0.0, 0.0, 0.0, trueVecs.at(i)[2], 0.0, trueVecs.at(i)[2],\n        -trueVecs.at(i)[1], 0.0, -trueVecs.at(i)[2], 0.0, trueVecs.at(i)[0],\n        0.0, trueVecs.at(i)[1], -trueVecs.at(i)[0], 0.0, 0.0;\n    trueMats.push_back(mat);\n  }\n\n  // Test the 3x1 function with scaling param\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double, 6, 4> testMat =\n        lgmath::se3::point2sf(trueVecs.at(i).head<3>(), trueVecs.at(i)[3]);\n    std::cout << \"true: \" << trueMats.at(i) << std::endl;\n    std::cout << \"func: \" << testMat << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(trueMats.at(i), testMat, 1e-6));\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of exponential functions: vec2tran and tran2vec\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, CompareAnalyticalAndNumericVec2Tran) {\n  // Add vectors to be tested\n  std::vector<Eigen::Matrix<double, 6, 1> > trueVecs;\n  Eigen::Matrix<double, 6, 1> temp;\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 1.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 1.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 1.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, -lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, -lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, -lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  const unsigned numRand = 20;\n  for (unsigned i = 0; i < numRand; i++) {\n    trueVecs.push_back(Eigen::Matrix<double, 6, 1>::Random());\n  }\n\n  // Get number of tests\n  const unsigned numTests = trueVecs.size();\n\n  // Calc matrices\n  std::vector<Eigen::Matrix<double, 4, 4> > analyticTrans;\n  for (unsigned i = 0; i < numTests; i++) {\n    analyticTrans.push_back(lgmath::se3::vec2tran(trueVecs.at(i)));\n  }\n\n  // Compare analytical and numeric result\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      Eigen::Matrix<double, 4, 4> numericTran =\n          lgmath::se3::vec2tran(trueVecs.at(i), 20);\n      std::cout << \"ana: \" << analyticTrans.at(i) << std::endl;\n      std::cout << \"num: \" << numericTran << std::endl;\n      EXPECT_TRUE(\n          lgmath::common::nearEqual(analyticTrans.at(i), numericTran, 1e-6));\n    }\n  }\n\n  // Test rot2vec\n  {\n    for (unsigned i = 0; i < numTests; i++) {\n      Eigen::Matrix<double, 6, 1> testVec =\n          lgmath::se3::tran2vec(analyticTrans.at(i));\n      std::cout << \"true: \" << trueVecs.at(i) << std::endl;\n      std::cout << \"func: \" << testVec << std::endl;\n      EXPECT_TRUE(\n          lgmath::common::nearEqualLieAlg(trueVecs.at(i), testVec, 1e-6));\n    }\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of exponential jacobians: vec2jac and vec2jacinv\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, CompareAnalyticalJacobInvAndNumericCounterpartsInSE3) {\n  // Add vectors to be tested\n  std::vector<Eigen::Matrix<double, 6, 1> > trueVecs;\n  Eigen::Matrix<double, 6, 1> temp;\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 1.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 1.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 1.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, -lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, -lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, -lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  const unsigned numRand = 20;\n  for (unsigned i = 0; i < numRand; i++) {\n    trueVecs.push_back(Eigen::Matrix<double, 6, 1>::Random());\n  }\n\n  // Get number of tests\n  const unsigned numTests = trueVecs.size();\n\n  // Calc analytical matrices\n  std::vector<Eigen::Matrix<double, 6, 6> > analyticJacs;\n  std::vector<Eigen::Matrix<double, 6, 6> > analyticJacInvs;\n  for (unsigned i = 0; i < numTests; i++) {\n    analyticJacs.push_back(lgmath::se3::vec2jac(trueVecs.at(i)));\n    analyticJacInvs.push_back(lgmath::se3::vec2jacinv(trueVecs.at(i)));\n  }\n\n  // Compare inversed analytical and analytical inverse\n  for (unsigned i = 0; i < numTests; i++) {\n    std::cout << \"ana: \" << analyticJacs.at(i) << std::endl;\n    std::cout << \"num: \" << analyticJacInvs.at(i) << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(analyticJacs.at(i).inverse(),\n                                          analyticJacInvs.at(i), 1e-6));\n  }\n\n  // Compare analytical and 'numerical' jacobian\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double, 6, 6> numericJac =\n        lgmath::se3::vec2jac(trueVecs.at(i), 20);\n    std::cout << \"ana: \" << analyticJacs.at(i) << std::endl;\n    std::cout << \"num: \" << numericJac << std::endl;\n    EXPECT_TRUE(\n        lgmath::common::nearEqual(analyticJacs.at(i), numericJac, 1e-6));\n  }\n\n  // Compare analytical and 'numerical' jacobian inverses\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double, 6, 6> numericJac =\n        lgmath::se3::vec2jacinv(trueVecs.at(i), 20);\n    std::cout << \"ana: \" << analyticJacInvs.at(i) << std::endl;\n    std::cout << \"num: \" << numericJac << std::endl;\n    EXPECT_TRUE(\n        lgmath::common::nearEqual(analyticJacInvs.at(i), numericJac, 1e-6));\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief General test of adjoint tranformation identity, Ad(T(v)) = I +\n/// curlyhat(v)*J(v)\n/////////////////////////////////////////////////////////////////////////////////////////////\nTEST(LGMath, TestIdentityAdTvEqualIPlusCurlyHatvTimesJv) {\n  // Add vectors to be tested\n  std::vector<Eigen::Matrix<double, 6, 1> > trueVecs;\n  Eigen::Matrix<double, 6, 1> temp;\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 1.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 1.0, 0.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 1.0, 0.0, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, -lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, -lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, -lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI, 0.0, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI, 0.0;\n  trueVecs.push_back(temp);\n  temp << 0.0, 0.0, 0.0, 0.0, 0.0, 0.5 * lgmath::constants::PI;\n  trueVecs.push_back(temp);\n  const unsigned numRand = 20;\n  for (unsigned i = 0; i < numRand; i++) {\n    trueVecs.push_back(Eigen::Matrix<double, 6, 1>::Random());\n  }\n\n  // Get number of tests\n  const unsigned numTests = trueVecs.size();\n\n  // Test Identity\n  for (unsigned i = 0; i < numTests; i++) {\n    Eigen::Matrix<double, 6, 6> lhs =\n        lgmath::se3::tranAd(lgmath::se3::vec2tran(trueVecs.at(i)));\n    Eigen::Matrix<double, 6, 6> rhs = Eigen::Matrix<double, 6, 6>::Identity() +\n                                      lgmath::se3::curlyhat(trueVecs.at(i)) *\n                                          lgmath::se3::vec2jac(trueVecs.at(i));\n    std::cout << \"lhs: \" << lhs << std::endl;\n    std::cout << \"rhs: \" << rhs << std::endl;\n    EXPECT_TRUE(lgmath::common::nearEqual(lhs, rhs, 1e-6));\n  }\n}\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "e6909dfd2518dc0c30b93af24abeec626c03cb19", "size": 15076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/SE3Tests.cpp", "max_stars_repo_name": "utiasASRL/lgmath", "max_stars_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T11:56:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:55:11.000Z", "max_issues_repo_path": "tests/SE3Tests.cpp", "max_issues_repo_name": "utiasASRL/lgmath", "max_issues_repo_head_hexsha": "d767997cc183f13f5d77ef3056f0c78af37547ae", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-06T21:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T15:23:38.000Z", "max_forks_repo_path": "tests/SE3Tests.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": 40.2026666667, "max_line_length": 94, "alphanum_fraction": 0.535088883, "num_tokens": 5293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6136457274150662}}
{"text": "//\r\n// Copyright (c) 2016 - 2017 Mesh Consultants Inc.\r\n// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n// of this software and associated documentation files (the \"Software\"), to deal\r\n// in the Software without restriction, including without limitation the rights\r\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n// copies of the Software, and to permit persons to whom the Software is\r\n// furnished to do so, subject to the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be included in\r\n// all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n// THE SOFTWARE.\r\n//\r\n\r\n\r\n#include \"Geomlib_TriMeshMeanCurvatureFlow.h\"\n\n#pragma warning(push, 0)\n#include <igl/is_vertex_manifold.h>\n#include <igl/is_edge_manifold.h>\n#include <igl/cotmatrix.h>\n#include <igl/massmatrix.h>\n#include <igl/doublearea.h>\n#include <igl/barycenter.h>\n#pragma warning(pop)\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include \"TriMesh.h\"\n#include \"ConversionUtilities.h\"\n\nnamespace {\n\nbool IglMeanCurvatureStep(\n\tconst Eigen::MatrixXf& V,\n\tconst Eigen::MatrixXi& F,\n\tEigen::MatrixXf& NV,\n\tEigen::MatrixXi& NF\n)\n{\n\tEigen::MatrixXf U = V;\n\n\tEigen::SparseMatrix<float> L;\n\tigl::cotmatrix(V, F, L);\n\n\tEigen::SparseMatrix<float> M;\n\tigl::massmatrix(U, F, igl::MASSMATRIX_TYPE_BARYCENTRIC, M);\n\n\tconst auto & S = (M - 0.001f * L);\n\tEigen::SimplicialLLT<Eigen::SparseMatrix<float> > solver(S);\n\tif (solver.info() != Eigen::Success) {\n\t\treturn false;\n\t}\n\tU = solver.solve(M * U).eval();\n\n\t// Compute centroid and subtract (also important for numerics)\n\tEigen::VectorXf doubleArea;\n\tigl::doublearea(U, F, doubleArea);\n\tfloat area = 0.5f * doubleArea.sum();\n\tif (!(area > 0.0f)) { // we divide by it later\n\t\treturn false;\n\t}\n\n\tEigen::MatrixXf BC;\n\tigl::barycenter(U, F, doubleArea);\n\tEigen::RowVector3f centroid(0, 0, 0);\n\tfor (int i = 0; i < BC.rows(); ++i) {\n\t\tcentroid += (0.5f * doubleArea(i) / area) * BC.row(i);\n\t}\n\tU.rowwise() -= centroid;\n\n\t// Normalize to unit surface area (important for numerics)\n\tif (!(sqrt(area) > 0.0f)) { // do you get 0.0f if you sqrt a really small float?\n\t\treturn false;\n\t}\n\tU.array() /= sqrt(area);\n\n\tNV = U;\n\tNF = F;\n\n\treturn true;\n}\n\n} //\n\nusing Urho3D::Variant;\n\nUrho3D::Variant Geomlib::TriMesh_MeanCurvatureFlowStep(\n\tconst Urho3D::Variant& tri_mesh\n)\n{\n\tif (!TriMesh_Verify(tri_mesh)) {\n\t\treturn Variant();\n\t}\n\n\tEigen::MatrixXf V;\n\tEigen::MatrixXi F;\n\tIglMeshToMatrices(tri_mesh, V, F);\n\n\t/*\n\tif (!igl::is_edge_manifold(V, F)) {\n\t\treturn Variant();\n\t}\n\tEigen::VectorXi B;\n\tif (!igl::is_vertex_manifold(F, B)) {\n\t\treturn Variant();\n\t}\n\t*/\n\n\t// V, F are ok\n\tEigen::MatrixXf NV;\n\tEigen::MatrixXi NF;\n\tbool success = IglMeanCurvatureStep(V, F, NV, NF);\n\tif (!success) {\n\t\treturn Variant();\n\t}\n\n\treturn TriMesh_Make(NV, NF);\n}\n\nbool Geomlib::TriMesh_MeanCurvatureFlow(\n\tconst Urho3D::Variant& tri_mesh,\n\tint num_steps,\n\tUrho3D::Variant& tri_mesh_out\n)\n{\n\tif (!TriMesh_Verify(tri_mesh)) {\n\t\treturn false;\n\t}\n\tif (num_steps <= 0) {\n\t\treturn false;\n\t}\n\n\tEigen::MatrixXf V;\n\tEigen::MatrixXi F;\n\tIglMeshToMatrices(tri_mesh, V, F);\n\n\t// V, F are ok here\n\n\tfor (int i = 0; i < num_steps; ++i) {\n\n\t\tEigen::MatrixXf VV;\n\t\tEigen::MatrixXi FF;\n\t\tbool success = IglMeanCurvatureStep(V, F, VV, FF);\n\t\tif (!success) {\n\t\t\treturn false;\n\t\t}\n\t\tV.setZero(VV.rows(), VV.cols());\n\t\tV = VV;\n\t\tF.setZero(FF.rows(), FF.cols());\n\t\tF = FF;\n\t}\n\n\ttri_mesh_out = TriMesh_Make(V, F);\n\tif (!TriMesh_Verify(tri_mesh_out)) {\n\t\treturn false;\n\t}\n\treturn true;\n}", "meta": {"hexsha": "04e53c15cb5f80a70df4d3615ff0f342eb0c2715", "size": 4035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry/Geomlib_TriMeshMeanCurvatureFlow.cpp", "max_stars_repo_name": "elix22/IogramSource", "max_stars_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-03-01T04:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T13:33:50.000Z", "max_issues_repo_path": "Geometry/Geomlib_TriMeshMeanCurvatureFlow.cpp", "max_issues_repo_name": "elix22/IogramSource", "max_issues_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-09T05:22:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T18:38:05.000Z", "max_forks_repo_path": "Geometry/Geomlib_TriMeshMeanCurvatureFlow.cpp", "max_forks_repo_name": "elix22/IogramSource", "max_forks_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-03-01T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:36:54.000Z", "avg_line_length": 24.0178571429, "max_line_length": 81, "alphanum_fraction": 0.688228005, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6136152510349792}}
{"text": "/**\n * Copyright (c) 2018, The Akatsuki(Jacob.lsx). All rights reserved.\n */\n\n\n#include <iostream>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n\n#include <chrono>\n\nusing namespace std;\nusing namespace cv;\n\n/* find the two photo feature matches points */\nvoid find_feature_matches(const cv::Mat&, const cv::Mat&, std::vector<cv::KeyPoint>&, std::vector<cv::KeyPoint>&, std::vector<cv::DMatch>&);\n\n/* Converts the pixel coordinate system to the normalized imaging plane coordinate system */\ncv::Point2d pixel2cam(const cv::Point2d&, const cv::Mat&);\n\nvoid bundleAdjustment( const std::vector<cv::Point3f>, const std::vector<cv::Point2f>, const cv::Mat&, cv::Mat&, cv::Mat&);\n\nint main(int argc, char** argv)\n{\n    google::InitGoogleLogging(argv[0]);\n    if (argc != 5) {\n        cout << \"usage: pose_estimation_3d2d img1 img2 depth1 depth2.\" << endl;\n        return 1;\n    }\n    \n    //-- 1st, read photo\n    cv::Mat img_1 = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);\n    cv::Mat img_2 = cv::imread(argv[2], CV_LOAD_IMAGE_COLOR);\n    \n    if (img_1.empty() || img_2.empty()) {\n        cout << \"img1 or img2 is no find.\" << endl;\n        return 1;\n    }\n    \n    //-- 2nd, find the two photo feature matches points\n    std::vector<cv::KeyPoint> keypoints_1, keypoints_2;\n    std::vector<cv::DMatch> matches;\n    find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n    cout << \"feature matches points total is \" << matches.size() << endl;\n    \n    //-- 3rd, create 3 dimensions point correspondences\n    cv::Mat d1 = cv::imread(argv[3], CV_LOAD_IMAGE_UNCHANGED);      // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n    cv::Mat K = (cv::Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n    std::vector<cv::Point3f> pts_3d;\n    std::vector<cv::Point2f> pts_2d;\n    for (cv::DMatch m:matches) {\n        ushort d = d1.ptr<unsigned short>(int (keypoints_1[m.queryIdx].pt.y))[int (keypoints_1[m.queryIdx].pt.x)];\n        \n        if (d == 0) {   /* bad depth */\n            continue;\n        }\n        float dd = d/5000.0;\n        cv::Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n        pts_3d.push_back(cv::Point3d (p1.x*dd, p1.y*dd, dd));\n        pts_2d.push_back(keypoints_2[m.trainIdx].pt);\n    }\n    cout << \"3d-2d pairs: \" << pts_3d.size() << endl;\n    \n    //-- 4th, use PnP or bundle adjustment compute camera pose.\n    cv::Mat r, t;\n    cv::solvePnP(pts_3d, pts_2d, K, cv::Mat(), r, t, false);    // \u8c03\u7528OpenCV \u7684 PnP \u6c42\u89e3\uff0c\u53ef\u9009\u62e9EPNP\uff0cDLS\u7b49\u65b9\u6cd5\n    cv::Mat R;\n    cv::Rodrigues(r, R);    // r\u4e3a\u65cb\u8f6c\u5411\u91cf\u5f62\u5f0f\uff0c\u7528Rodrigues\u516c\u5f0f\u8f6c\u6362\u4e3a\u77e9\u9635\n    \n    cout << \"R = \" << endl << R << endl;\n    cout << \"t = \" << endl << t << endl;\n    \n    cout << \"\\r\\ncalling bundle adjustment\" << endl;\n    \n    bundleAdjustment(pts_3d, pts_2d, K, r, t);\n    \n    return 0;\n}\n\n/**\n * find the two photo feature matches points\n */\nvoid find_feature_matches(const cv::Mat& img_1, const cv::Mat& img_2, std::vector<cv::KeyPoint>& keypoints_1, std::vector<cv::KeyPoint>& keypoints_2, std::vector<cv::DMatch>& matches)\n{\n    //-- Initialize\n    cv::Mat descriptors_1, descriptors_2;\n    cv::Ptr<cv::FeatureDetector> detector = cv::ORB::create();\n    cv::Ptr<cv::DescriptorExtractor> descriptor = cv::ORB::create();\n    cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n    \n    //-- 1st: detect Oriented FAST KeyPoint \n    detector->detect(img_1, keypoints_1);\n    detector->detect(img_2, keypoints_2);\n    \n    //-- 2nd: Calculates BRIEF descriptors with KeyPoint's coordinate\n    descriptor->compute(img_1, keypoints_1, descriptors_1);\n    descriptor->compute(img_2, keypoints_2, descriptors_2);\n    \n    //-- 3rd: \u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n    std::vector<cv::DMatch> match;\n    matcher->match(descriptors_1, descriptors_2, match);\n    \n    //-- 4th: \u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n    double min_dist = 10000, max_dist = 0;\n    \n    /* \u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb */\n    for (int i = 0; i < descriptors_1.rows; i++) {\n        double dist = match[i].distance;\n        if (dist < min_dist) {\n            min_dist = dist;\n        }\n        if (dist > max_dist) {\n            max_dist = dist;\n        }\n    }\n    \n    printf(\"-- Max distance : %f \\r\\n\", max_dist);\n    printf(\"-- Min distance : %f \\r\\n\", min_dist);\n    \n    // \u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n    for (int i = 0; i < descriptors_2.rows; i ++) {\n        if (match[i].distance <= max(2*min_dist, 30.0)) {\n            matches.push_back(match[i]);\n        }\n    }\n}\n\n/**\n * Converts the pixel coordinate system to the normalized imaging plane coordinate system\n */\ncv::Point2d pixel2cam(const cv::Point2d& p, const cv::Mat& K)\n{\n    return cv::Point2d\n        (\n            (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n            (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n        );\n}\n\nclass ReprojectionError\n{\npublic:\n    ReprojectionError(const cv::Point2f p_2d, const cv::Point3f p_3d) : p_2d_(p_2d), p_3d_(p_3d) {}\n    \n    template<typename T>\n    bool operator()(const T* const T_, const T* const point_3d_,  T* residual_) const;\n    \n    // Factory to hide the construction of the CostFunction object from the client code.\n    static ceres::CostFunction* create(const cv::Point2f &p_2d, const cv::Point3f &p_3d);\n    \nprivate:\n    template<typename T>\n    static inline void camProjectionWithoutDistortion(const T* const r, const T* const t, const T* const pt_3d, T* predicted);\n    \n    cv::Point2f p_2d_;\n    cv::Point3f p_3d_;\n    static float fx_, fy_, cx_, cy_;\n};\n\nfloat ReprojectionError::fx_ = 520.9; \nfloat ReprojectionError::fy_ = 521.0;\nfloat ReprojectionError::cx_ = 325.1;\nfloat ReprojectionError::cy_ = 249.7;\n\ntemplate<typename T>\nbool ReprojectionError::operator()(const T* const r_, const T* const t_,  T* residual_) const\n{\n    T p[3] = {(T)p_3d_.x, (T)p_3d_.y, (T)p_3d_.z};\n    T predicted[2];\n    \n    // T_[0, 1, 2] are the angle-axis rotation\n    // T_[3, 4, 5] are the translation\n    camProjectionWithoutDistortion(r_, t_, p, predicted);\n    \n    // The error is the difference between the predicted and observed position\n    residual_[0] = predicted[0] - T(p_2d_.x);\n    residual_[1] = predicted[1] - T(p_2d_.y);\n    \n//     cout << residual_[1] << \", \" << residual_[2] << endl;\n}\n\ntemplate<typename T>\ninline void ReprojectionError::camProjectionWithoutDistortion(const T* const r, const T* const t, const T* const pt_3d, T* predicted)\n{\n    T p[3];\n    ceres::AngleAxisRotatePoint(r, pt_3d, p);\n    \n    p[0] += t[0];\n    p[1] += t[1];\n    p[2] += t[2];\n    \n    T px_normalized = p[0] / p[2];\n    T py_normalized = p[1] / p[2];\n    \n    predicted[0] = (T)fx_ * px_normalized + (T)cx_;\n    predicted[1] = (T)fy_ * py_normalized + (T)cy_;\n}\n\nceres::CostFunction* ReprojectionError::create(const cv::Point2f &p_2d, const cv::Point3f &p_3d)\n{\n    return (new ceres::AutoDiffCostFunction<ReprojectionError, 2, 3, 3>(\n                new ReprojectionError(p_2d, p_3d)));\n}\n\nvoid bundleAdjustment(\n    const std::vector<cv::Point3f> points_3d,\n    const std::vector<cv::Point2f> points_2d,\n    const cv::Mat& K,\n    cv::Mat& r,\n    cv::Mat& t )\n{\n    double rotation[3];\n    double translation[3];\n    for (int i = 0; i < 3; i++) {\n        rotation[i] = r.at<double>(i, 0);\n        translation[i] = t.at<double>(i, 0);\n    }\n    \n    ceres::Problem problem;\n    for (int i = 0; i < points_2d.size(); i ++) {\n        ceres::CostFunction* cost_function = ReprojectionError::create(points_2d[i], points_3d[i]);\n        problem.AddResidualBlock(cost_function, nullptr, rotation, translation);\n    }\n    \n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_SCHUR;\n    options.minimizer_progress_to_stdout = true;\n    \n    ceres::Solver::Summary summary;\n    \n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    \n    ceres::Solve(options, &problem, &summary);\n    \n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << endl;\n    \n    cout << summary.BriefReport() << endl;\n    \n    cout << endl << \"after optimization: \" << endl;\n    \n    cv::Mat r_vec = (cv::Mat_<double>(3, 1) << rotation[0], rotation[1], rotation[2]);\n    cv::Mat R;\n    cv::Rodrigues(r_vec, R);\n    \n    cout << \"R = \\r\\n\" << R << endl;\n    cout << \"t = \\r\\n\" << translation[0] << \", \" << translation[1] << \", \" << translation[2] << endl;\n    \n//     cout << \"T = \" << endl << Eigen::Isometry3d(pose->estimate()).matrix() << endl;\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "018c66c01ac22ff0fc73dff998a31fcfd05f1411", "size": 8752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_estimation_3d2d/src/pose_estimation_3d2d_ceres.cpp", "max_stars_repo_name": "LSXiang/slam_learning_journey", "max_stars_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-22T00:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T05:23:27.000Z", "max_issues_repo_path": "pose_estimation_3d2d/src/pose_estimation_3d2d_ceres.cpp", "max_issues_repo_name": "LSXiang/slam_learning_journey", "max_issues_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pose_estimation_3d2d/src/pose_estimation_3d2d_ceres.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": 32.9022556391, "max_line_length": 183, "alphanum_fraction": 0.6200868373, "num_tokens": 2857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6136152381763049}}
{"text": "/*\n    This file is part of Mitsuba, a physically based rendering system.\n\n    Copyright (c) 2007-2014 by Wenzel Jakob and others.\n\n    Mitsuba is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License Version 3\n    as published by the Free Software Foundation.\n\n    Mitsuba is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <mitsuba/core/vmf.h>\n#include <mitsuba/core/warp.h>\n#include <mitsuba/core/brent.h>\n#include <boost/bind.hpp>\n\nMTS_NAMESPACE_BEGIN\n\nFloat VonMisesFisherDistr::eval(Float cosTheta) const {\n\tif (m_kappa == 0.0f)\n\t\treturn INV_FOURPI;\n#if 0\n\treturn math::fastexp(cosTheta * m_kappa)\n\t\t* m_kappa / (4 * M_PI * std::sinh(m_kappa));\n#else\n\t/* Numerically stable version */\n\treturn math::fastexp(m_kappa * std::min((Float)0, cosTheta - 1))\n\t\t* m_kappa / (2 * M_PI * (1-math::fastexp(-2*m_kappa)));\n#endif\n}\n\nVector VonMisesFisherDistr::sample(const Point2 &sample) const {\n\tif (m_kappa == 0)\n\t\treturn warp::squareToUniformSphere(sample);\n\n#if 0\n\tFloat cosTheta = math::fastlog(math::fastexp(-m_kappa) + 2 *\n\t\t\t\t\t\tsample.x * std::sinh(m_kappa)) / m_kappa;\n#else\n\t/* Numerically stable version */\n\tFloat cosTheta = 1 + (math::fastlog(sample.x +\n\t\tmath::fastexp(-2 * m_kappa) * (1 - sample.x))) / m_kappa;\n#endif\n\n\tFloat sinTheta = math::safe_sqrt(1-cosTheta*cosTheta),\n\t      sinPhi, cosPhi;\n\n\tmath::sincos(2*M_PI * sample.y, &sinPhi, &cosPhi);\n\n\treturn Vector(cosPhi * sinTheta,\n\t\tsinPhi * sinTheta, cosTheta);\n}\n\nFloat VonMisesFisherDistr::getMeanCosine() const {\n\tif (m_kappa == 0)\n\t\treturn 0;\n\tFloat coth = m_kappa > 6 ? 1 : ((std::exp(2*m_kappa)+1)/(std::exp(2*m_kappa)-1));\n\treturn coth-1/m_kappa;\n}\n\nstatic Float A3(Float kappa) {\n\treturn 1/ std::tanh(kappa) - 1 / kappa;\n}\n\nstd::string VonMisesFisherDistr::toString() const {\n\tstd::ostringstream oss;\n\toss << \"VonMisesFisherDistr[kappa=\" << m_kappa << \"]\";\n\treturn oss.str();\n}\n\nstatic Float dA3(Float kappa) {\n\tFloat csch = 2.0f /\n\t\t(math::fastexp(kappa)-math::fastexp(-kappa));\n\treturn 1/(kappa*kappa) - csch*csch;\n}\n\nstatic Float A3inv(Float y, Float guess) {\n\tFloat x = guess;\n\tint it = 1;\n\n\twhile (true) {\n\t\tFloat residual = A3(x)-y,\n\t\t\t  deriv = dA3(x);\n\t\tx -= residual/deriv;\n\n\t\tif (++it > 20) {\n\t\t\tSLog(EWarn, \"VanMisesFisherDistr::convolve(): Newton's method \"\n\t\t\t\t\" did not converge!\");\n\t\t\treturn guess;\n\t\t}\n\n\t\tif (std::abs(residual) < 1e-5f)\n\t\t\tbreak;\n\t}\n\treturn x;\n}\n\nFloat VonMisesFisherDistr::convolve(Float kappa1, Float kappa2) {\n\treturn A3inv(A3(kappa1) * A3(kappa2), std::min(kappa1, kappa2));\n}\n\nFloat VonMisesFisherDistr::forPeakValue(Float x) {\n\tif (x < INV_FOURPI) {\n\t\treturn 0.0f;\n\t} else if (x > 0.795) {\n\t\treturn 2 * M_PI * x;\n\t} else {\n\t\treturn std::max((Float) 0.0f,\n\t\t\t(168.479f * x * x + 16.4585f * x - 2.39942f) /\n\t\t\t(-1.12718f * x * x + 29.1433f * x + 1.0f));\n\t}\n}\n\nstatic Float meanCosineFunctor(Float kappa, Float g) {\n\treturn VonMisesFisherDistr(kappa).getMeanCosine()-g;\n}\n\nFloat VonMisesFisherDistr::forMeanLength(Float l) {\n\treturn (3*l - l*l*l) / (1-l*l);\n}\n\nFloat VonMisesFisherDistr::forMeanCosine(Float g) {\n\tif (g == 0)\n\t\treturn 0;\n\telse if (g < 0)\n\t\tSLog(EError, \"Error: vMF distribution cannot be created for g<0.\");\n\n\tBrentSolver brentSolver(100, 1e-6f);\n\tBrentSolver::Result result = brentSolver.solve(\n\t\tboost::bind(&meanCosineFunctor, _1, g), 0, 1000);\n\tSAssert(result.success);\n\treturn result.x;\n}\n\nMTS_NAMESPACE_END\n", "meta": {"hexsha": "aae1fc47d43c494a401461a1dd4054e02519ecf7", "size": 3733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mitsuba-af602c6fd98a/src/libcore/vmf.cpp", "max_stars_repo_name": "NTForked-ML/pbrs", "max_stars_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 139.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T00:22:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T20:33:10.000Z", "max_issues_repo_path": "mitsuba-af602c6fd98a/src/libcore/vmf.cpp", "max_issues_repo_name": "NTForked-ML/pbrs", "max_issues_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-08-15T18:22:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-01T05:44:41.000Z", "max_forks_repo_path": "mitsuba-af602c6fd98a/src/libcore/vmf.cpp", "max_forks_repo_name": "NTForked-ML/pbrs", "max_forks_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2017-07-21T03:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T06:55:34.000Z", "avg_line_length": 26.1048951049, "max_line_length": 82, "alphanum_fraction": 0.678274846, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.613615230580086}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cassert>\n//#include <NTL/mat_ZZ_p.h>\n#include <NTL/mat_ZZ.h>\n//#include <NTL/ZZ_p.h>\n#include <NTL/ZZ.h>\n//#include <NTL/vec_ZZ_p.h>\n#include <NTL/vec_ZZ.h>\n#include <cmath>\n#include <stack>\n\nusing namespace std;\nusing namespace NTL;\n\nconst ZZ w(1ll << 40ll);\nZZ aBound(1000), tBound(aBound), eBound(1000);\nint l = 100;\n\nconst mat_ZZ hCat(const mat_ZZ& A, const mat_ZZ& B);\nconst mat_ZZ vCat(const mat_ZZ& A, const mat_ZZ& B);\n\nconst vec_ZZ decrypt(const mat_ZZ& S, const vec_ZZ& c);\n\n// returns c*\nconst vec_ZZ getBitVector(const vec_ZZ& c);\n\n// returns S*\nconst mat_ZZ getBitMatrix(const mat_ZZ& S);\n\n// returns S\nconst mat_ZZ getSecretKey(const mat_ZZ& T);\n\n// returns M\nconst mat_ZZ keySwitchMatrix(const mat_ZZ& S, const mat_ZZ& T);\n\n// finds c* then returns Mc*\nconst vec_ZZ keySwitch(const mat_ZZ& M, const vec_ZZ& c);\n\n// as described, treating I as the secret key and wx as ciphertext\nconst vec_ZZ encrypt(const mat_ZZ& T, const vec_ZZ& x);\n\nconst mat_ZZ getRandomMatrix(long row, long col, const ZZ& bound);\n\n// server side addition with same secret key\nconst vec_ZZ addn(const vec_ZZ& c1, const vec_ZZ& c2);\n\n// server side linear transformation,\n// returns S(Gx) given c=Sx and M (key switch matrix from GS to S)\nconst vec_ZZ linearTransform(const mat_ZZ& M, const vec_ZZ& c);\n\n// returns M, the key switch matrix from GS to S,\n// to be sent to server\nconst mat_ZZ linearTransformClient(const mat_ZZ& T, const mat_ZZ& G);\n\n// computes an inner product, given two ciphertexts and the keyswitch matrix\nconst vec_ZZ innerProd(const vec_ZZ& c1, const vec_ZZ& c2, const mat_ZZ& M);\n\n// returns M, the key switch matrix from vec(S^t S) to S,\n// to be sent to the server\nconst mat_ZZ innerProdClient(const mat_ZZ& T);\n\n// returns a column vector\nconst mat_ZZ vectorize(const mat_ZZ& M);\n\nconst mat_ZZ copyRows(const mat_ZZ& row, long numrows);\n\n\n\n\n// finds c* then returns Mc*\nconst vec_ZZ keySwitch(const mat_ZZ& M, const vec_ZZ& c) {\n\tvec_ZZ cstar = getBitVector(c);\n\treturn M * cstar;\n}\n\n\nconst mat_ZZ getRandomMatrix(long row, long col, const ZZ& bound){\n\tmat_ZZ A;\n\tA.SetDims(row, col);\n\tfor (int i=0; i<row; ++i){\n\t\tfor (int j=0; j<col; ++j){\n\t\t\tA[i][j] = RandomBnd(bound);\n\t\t}\n\t}\n\treturn A;\n}\n\n\n\n\n// returns S*\nconst mat_ZZ getBitMatrix(const mat_ZZ& S) {\n\tmat_ZZ result;\n\tint rows = S.NumRows(), cols = S.NumCols();\n\tresult.SetDims(rows, l * cols);\n\n\tvec_ZZ powers;\n\tpowers.SetLength(l);\n\tpowers[0] = 1;\n\tfor(int i = 0; i < l - 1; ++i) {\n\t\tpowers[i+1] = powers[i]*2;\n\t}\n\n\tfor(int i = 0; i < rows; ++i) {\n\t\tfor(int j = 0; j < cols; ++j) {\n\t\t\tfor(int k = 0; k < l; ++k) {\n\t\t\t\tresult[i][j*l + k] = S[i][j] * powers[k];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\n\n// returns c*\nconst vec_ZZ getBitVector(const vec_ZZ& c) {\n\tvec_ZZ result;\n\tint length = c.length();\n\tresult.SetLength(length * l);\n\tfor(int i = 0; i < length; ++i) {\n\t\tZZ sign = (c[i] < ZZ(0)) ? ZZ(-1) : ZZ(1);\n\t\tZZ value = c[i] * sign;\n\t\tfor(int j = 0; j < l; ++j) {\n\t\t\tresult[i * l + j] = sign*bit(value, j);\n\t\t}\n\t}\n\treturn result;\n}\n\n\n\n// returns S\nconst mat_ZZ getSecretKey(const mat_ZZ& T) {\n\tmat_ZZ I;\n\tident(I, T.NumRows());\n\treturn hCat(I, T);\n}\n\n\nconst mat_ZZ hCat(const mat_ZZ& A, const mat_ZZ& B) {\n\tassert(A.NumRows() == B.NumRows());\n\n\tint rows = A.NumRows(), colsA = A.NumCols(), colsB = B.NumCols();\n\tmat_ZZ result;\n\tresult.SetDims(rows, colsA + colsB);\n\n\t// Copy A\n\tfor(int i = 0; i < rows; ++i) {\n\t\tfor(int j = 0; j < colsA; ++j) {\n\t\t\tresult[i][j] = A[i][j];\n\t\t}\n\t}\n\n\t// Copy B\n\tfor(int i = 0; i < rows; ++i) {\n\t\tfor(int j = 0; j < colsB; ++j) {\n\t\t\tresult[i][colsA + j] = B[i][j];\n\t\t}\n\t}\n\n\treturn result;\n}\n\nconst mat_ZZ vCat(const mat_ZZ& A, const mat_ZZ& B) {\n\tassert(A.NumCols() == B.NumCols());\n\n\tint cols = A.NumCols(), rowsA = A.NumRows(), rowsB = B.NumRows();\n\tmat_ZZ result;\n\tresult.SetDims(rowsA + rowsB, cols);\n\n\t// Copy A\n\tfor(int i = 0; i < rowsA; ++i) {\n\t\tfor(int j = 0; j < cols; ++j) {\n\t\t\tresult[i][j] = A[i][j];\n\t\t}\n\t}\n\n\t// Copy B\n\tfor(int i = 0; i < rowsB; ++i) {\n\t\tfor(int j = 0; j < cols; ++j) {\n\t\t\tresult[i + rowsA][j] = B[i][j];\n\t\t}\n\t}\n\n\treturn result;\n}\n\ninline const ZZ nearestInteger(const ZZ& x, const ZZ& w) {\n\treturn (x + (w+1)/2) / w;\n}\n\nconst vec_ZZ decrypt(const mat_ZZ& S, const vec_ZZ& c) {\n\tvec_ZZ Sc = S*c;\n\tvec_ZZ output;\n\toutput.SetLength(Sc.length());\n\tfor (int i=0; i<Sc.length(); i++) {\n\t\toutput[i] = nearestInteger(Sc[i], w);\n\t}\n\treturn output;\n}\n\nconst mat_ZZ keySwitchMatrix(const mat_ZZ& S, const mat_ZZ& T) {\n\tmat_ZZ Sstar = getBitMatrix(S);\n\tmat_ZZ A = getRandomMatrix(T.NumCols(),Sstar.NumCols(),aBound);\n\tmat_ZZ E = getRandomMatrix(Sstar.NumRows(),Sstar.NumCols(),eBound);\n\treturn vCat(Sstar + E - T*A, A);\n}\n\nconst vec_ZZ encrypt(const mat_ZZ& T, const vec_ZZ& x) {\n\tmat_ZZ I;\n\tident(I, x.length());\n\treturn keySwitch(keySwitchMatrix(I, T), w * x);\n}\n\n\n\n\nconst vec_ZZ addVectors(const vec_ZZ& c1, const vec_ZZ& c2){\n\treturn c1 + c2;\n}\n\nconst vec_ZZ linearTransform(const mat_ZZ& M, const vec_ZZ& c){\n\treturn M * getBitVector(c);\n}\n\nconst mat_ZZ linearTransformClient(const mat_ZZ& G, const mat_ZZ& S, const mat_ZZ& T){\n\treturn keySwitchMatrix(G * S, T);\n}\n\n\nconst vec_ZZ innerProd(const vec_ZZ& c1, const vec_ZZ& c2, const mat_ZZ& M){\n\tmat_ZZ cc1;\n\tmat_ZZ cc2;\n\tmat_ZZ cc;\n\n\tcc1.SetDims(c1.length(), 1);\n\tfor (int i=0; i<c1.length(); ++i){\n\t\tcc1[i][0] = c1[i];\n\t}\n\tcc2.SetDims(1, c2.length());\n\tfor (int i=0; i<c2.length(); ++i){\n\t\tcc2[0][i] = c2[i];\n\t}\n\tcc = vectorize(cc1 * cc2);\n\n\tvec_ZZ output;\n\toutput.SetLength(cc.NumRows());\n\tfor (int i=0; i<cc.NumRows(); i++) {\n\t\toutput[i] = nearestInteger(cc[i][0], w);\n\t}\n\treturn M * getBitVector(output);\n}\n\nconst mat_ZZ innerProdClient(const mat_ZZ& T){\n\tmat_ZZ S = getSecretKey(T);\n\tmat_ZZ tvsts = transpose(vectorize(transpose(S) * S));\n\tmat_ZZ mvsts = copyRows(tvsts, T.NumRows());\n\treturn keySwitchMatrix(mvsts, T);\n}\n\n\n\n\nconst mat_ZZ copyRows(const mat_ZZ& row, long numrows){\n\tmat_ZZ ans;\n\tans.SetDims(numrows, row.NumCols());\n\tfor (int i=0; i<ans.NumRows(); ++i){\n\t\tfor (int j=0; j<ans.NumCols(); ++j){\n\t\t\tans[i][j] = row[0][j];\n\t\t}\n\t}\n\treturn ans;\n}\n\nconst mat_ZZ vectorize(const mat_ZZ& M){\n\tmat_ZZ ans;\n\tans.SetDims(M.NumRows() * M.NumCols(), 1);\n\tfor (int i=0; i<M.NumRows(); ++i){\n\t\tfor (int j=0; j<M.NumCols(); ++j){\n\t\t\tans[i*M.NumCols() + j][0] = M[i][j];\n\t\t}\n\t}\n\treturn ans;\n}\n\n\n\nint main() {\n\tifstream cin(\"vhe.in\");\n\n\tcin.tie(NULL);\n\tios_base::sync_with_stdio(false);\n\n\tstack<vec_ZZ*> vectors;\n\tstack<mat_ZZ*> matrices;\n\n\tstring operation;\n\twhile (cin >> operation) {\n\t\t//cerr << \"Operation: \" << operation << endl;\n\n\t\tif (operation == \"vector\") {\n\t\t\tvec_ZZ* v = new vec_ZZ();\n\t\t\tcin >> (*v);\n\t\t\t//cerr << \"Vector (\" << v.length() << \")\" << endl;\n\t\t\tvectors.push(v);\n\n\t\t} else if (operation == \"matrix\") {\n\t\t\tmat_ZZ* m = new mat_ZZ();\n\t\t\tcin >> (*m);\n\t\t\t//cerr << \"Matrix (\" << m.NumRows() << \", \" << m.NumCols() << \")\" << endl;\n\t\t\tmatrices.push(m);\n\n\t\t} else if (operation == \"duplicate-vector\") {\n\t\t\tvectors.push(vectors.top());\n\n\t\t} else if (operation == \"duplicate-matrix\") {\n\t\t\tmatrices.push(matrices.top());\n\n\t\t} else if (operation == \"add\") {\n\t\t\tvec_ZZ& v1 = *vectors.top(); vectors.pop();\n\t\t\tvec_ZZ& v2 = *vectors.top(); vectors.pop();\n\t\t\tvec_ZZ* v = new vec_ZZ();\n\t\t\t(*v) = addVectors(v1, v2);\n\t\t\tvectors.push(v);\n\n\t\t} else if (operation == \"scalar-multiply\") {\n\t\t\tZZ x;\n\t\t\tcin >> x;\n\t\t\tvec_ZZ& v = *vectors.top(); vectors.pop();\n\t\t\tvec_ZZ* v2 = new vec_ZZ();\n\t\t\t(*v2) = v * x;\n\t\t\tvectors.push(v2);\n\n\t\t} else if (operation == \"linear-transform\") {\n\t\t\tvec_ZZ& v = *vectors.top(); vectors.pop();\n\t\t\tmat_ZZ& m = *matrices.top(); matrices.pop();\n\t\t\tvec_ZZ* r = new vec_ZZ();\n\t\t\t(*r) = linearTransform(m, v);\n\t\t\tvectors.push(r);\n\n\t\t} else if (operation == \"linear-transform-key-switch\") {\n\t\t\tmat_ZZ& T = *matrices.top(); matrices.pop();\n\t\t\tmat_ZZ& S = *matrices.top(); matrices.pop();\n\t\t\tmat_ZZ& G = *matrices.top(); matrices.pop();\n\t\t\tmat_ZZ* m = new mat_ZZ();\n\t\t\t(*m) = linearTransformClient(G, S, T);\n\t\t\tmatrices.push(m);\n\n\t\t} else if (operation == \"inner-product\") {\n\t\t\tvec_ZZ& v1 = *vectors.top(); vectors.pop();\n\t\t\tvec_ZZ& v2 = *vectors.top(); vectors.pop();\n\t\t\tmat_ZZ& m = *matrices.top(); matrices.pop();\n\t\t\tvec_ZZ *v = new vec_ZZ();\n\t\t\t(*v) = innerProd(v1, v2, m);\n\t\t\tvectors.push(v);\n\n\t\t} else if (operation == \"inner-product-key-switch\") {\n\t\t\tmat_ZZ& T = *matrices.top(); matrices.pop();\n\t\t\tmat_ZZ *m = new mat_ZZ();\n\t\t\t(*m) = innerProdClient(T);\n\t\t\tmatrices.push(m);\n\n\t\t} else if (operation == \"key-switch\") {\n\t\t\tvec_ZZ& v = *vectors.top(); vectors.pop();\n\t\t\tmat_ZZ& m = *matrices.top(); matrices.pop();\n\t\t\tvec_ZZ *v2 = new vec_ZZ();\n\t\t\t(*v2) = keySwitch(m, v);\n\t\t\tvectors.push(v2);\n\n\t\t} else if (operation == \"random-matrix\") {\n\t\t\tint rows, cols;\n\t\t\tcin >> rows >> cols;\n\t\t\tmat_ZZ *m = new mat_ZZ();\n\t\t\t(*m) = getRandomMatrix(rows, cols, tBound);\n\t\t\tmatrices.push(m);\n\n\t\t} else if (operation == \"identity\") {\n\t\t\tint rows;\n\t\t\tcin >> rows;\n\t\t\tmat_ZZ *I = new mat_ZZ();\n\t\t\tident(*I, rows);\n\t\t\tmatrices.push(I);\n\n\t\t} else if (operation == \"key-switch-matrix\") {\n\t\t\tmat_ZZ& T = *matrices.top(); matrices.pop();\n\t\t\tmat_ZZ& S = *matrices.top(); matrices.pop();\n\t\t\tmat_ZZ *m = new mat_ZZ();\n\t\t\t(*m) = keySwitchMatrix(S, T);\n\t\t\tmatrices.push(m);\n\n\t\t} else if (operation == \"get-secret-key\") {\n\t\t\tmat_ZZ &T = *matrices.top(); matrices.pop();\n\t\t\tmat_ZZ *s = new mat_ZZ();\n\t\t\t(*s) = getSecretKey(T);\n\t\t\tmatrices.push(s);\n\n\t\t} else if (operation == \"encrypt\") {\n\t\t\tmat_ZZ& T = *matrices.top(); matrices.pop();\n\t\t\tvec_ZZ& x = *vectors.top(); vectors.pop();\n\t\t\tvec_ZZ *v = new vec_ZZ();\n\t\t\t(*v) = encrypt(T, x);\n\t\t\tvectors.push(v);\n\n\t\t} else if (operation == \"decrypt\") {\n\t\t\tmat_ZZ& S = *matrices.top(); matrices.pop();\n\t\t\tvec_ZZ& c = *vectors.top(); vectors.pop();\n\t\t\tvec_ZZ *x = new vec_ZZ();\n\t\t\t(*x) = decrypt(S, c);\n\t\t\tvectors.push(x);\n\n\t\t} else {\n\t\t\tcerr << \"Unknown command: \" << operation << endl;\n\t\t}\n\n\t}\n\n\tstack<vec_ZZ> vectors2;\n\twhile (vectors.size()) {\n\t\tvectors2.push(*vectors.top()); vectors.pop();\n\t}\n\twhile (vectors2.size()) {\n\t\tcout << vectors2.top() << endl; vectors2.pop();\n\t}\n\n\tstack<mat_ZZ> matrices2;\n\twhile (matrices.size()) {\n\t\tmatrices2.push(*matrices.top()); matrices.pop();\n\t}\n\twhile (matrices2.size()) {\n\t\tcout << matrices2.top() << endl; matrices2.pop();\n\t}\n\n\n\t// // Testing for the 3 fundamental operations:\n\t// const int N = 10;\n\t// vec_ZZ x1;\n\t// vec_ZZ x2;\n\t// x1.SetLength(N);\n\t// x2.SetLength(N);\n\t// for(int i = 0; i < N; ++i) {\n\t// \tx1[i] = RandomBnd(10000);\n\t// \tx2[i] = RandomBnd(10000);\n\t// }\n\t// cout << x1 << endl;\n\t// cout << x2 << endl;\n\t// mat_ZZ T = getRandomMatrix(N, N, tBound);\n\t// mat_ZZ S = getSecretKey(T);\n\t// vec_ZZ c1 = encrypt(T, x1);\n\t// vec_ZZ c2 = encrypt(T, x2);\n\n\n\n\t// // Testing for inner product no switch\n\t// vec_ZZ cc = innerProdNoSwitch(x1, c2);\n\t// vec_ZZ dxx = innerProdNoSwitchDecrypt(cc, S);\n\t// ZZ xx;\n\t// InnerProduct(xx, x1, x2);\n\n\t// cout << xx << endl;\n\t// cout << dxx[0] << endl;\n\t// cout << xx - dxx[0] << endl;\n\n\n\t// // Testing for inner product\n\t// mat_ZZ M;\n\t// vec_ZZ cc;\n\t// vec_ZZ dxx;\n\t// ZZ xx;\n\n\t// M = innerProdClient(T);\n\t// cc = innerProd(c1, c2, M);\n\t// dxx = decrypt(getSecretKey(T), cc);\n\t// InnerProduct(xx, x1, x2);\n\n\n\t// cout << xx << endl;\n\t// cout << dxx[0] << endl;\n\t// cout << xx - dxx[0] << endl;\n\n\n\t// // Testing for linear transform\n\t// mat_ZZ G;\n\t// mat_ZZ M;\n\t// vec_ZZ cc;\n\t// vec_ZZ dxx;\n\t// vec_ZZ xx;\n\n\t// G = getRandomMatrix(N, N, aBound);\n\t// M = linearTransformClient(T, G);\n\t// cc = linearTransform(M, c1);\n\t// dxx = decrypt(getSecretKey(T), cc);\n\t// xx = G * x1;\n\n\t// cout << G << endl;\n\t// cout << xx << endl;\n\t// cout << dxx << endl;\n\t// cout << xx - dxx << endl;\n\n\n\n\t// // Testing for addition:\n\t// vec_ZZ cplus;\n\t// vec_ZZ dxplus;\n\t// vec_ZZ xplus;\n\n\t// cplus = addn(c1, c2);\n\t// dxplus = decrypt(getSecretKey(T), cplus);\n\t// xplus = x1 + x2;\n\n\t// cout << xplus << endl;\n\t// cout << dxplus << endl;\n\t// cout << xplus - dxplus << endl;\n\n\n}\n\n", "meta": {"hexsha": "2f3d6417e3b196a7b3a5434783f208be2822fb0b", "size": 11918, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vhe.cpp", "max_stars_repo_name": "mukira/vector-homomorphic-encryption", "max_stars_repo_head_hexsha": "daec930f358ce65a73afd99d5cab92b7ac37c020", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2015-11-27T11:06:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T05:35:04.000Z", "max_issues_repo_path": "vhe.cpp", "max_issues_repo_name": "mukira/vector-homomorphic-encryption", "max_issues_repo_head_hexsha": "daec930f358ce65a73afd99d5cab92b7ac37c020", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-11-27T11:07:44.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-27T15:39:00.000Z", "max_forks_repo_path": "vhe.cpp", "max_forks_repo_name": "mukira/vector-homomorphic-encryption", "max_forks_repo_head_hexsha": "daec930f358ce65a73afd99d5cab92b7ac37c020", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2016-03-14T14:22:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-01T22:21:23.000Z", "avg_line_length": 22.9192307692, "max_line_length": 86, "alphanum_fraction": 0.6048833697, "num_tokens": 4095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6135795108022383}}
{"text": "#define _USE_MATH_DEFINES\n\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#include <climits>\n#include <cfloat>\n#include <cmath>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"externals.h\"\n#include \"typedValue.h\"\n#include \"stack.h\"\n#include \"word.h\"\n#include \"context.h\"\n#include \"mathMacro.h\"\n\nconst BigInt kBigInt_FLT_MAX(FLT_MAX);\nconst BigInt kBigInt_Minus_FLT_MAX(-FLT_MAX);\nconst BigInt kBigInt_DBL_MAX(DBL_MAX);\nconst BigInt kBigInt_Minus_DBL_MAX(-DBL_MAX);\n\nstatic double deg2rad(double inTheta) { return inTheta/180.0*M_PI; }\nstatic BigFloat deg2rad(BigFloat inTheta) { return inTheta/180.0*M_PI; }\nstatic double rad2deg(double inTheta) { return inTheta/M_PI*180.0; }\nstatic BigFloat rad2deg(BigFloat inTheta) { return inTheta/M_PI*180.0; }\n\nstatic int    maxOp(int     inA,int inB)     { return std::max(inA,inB); }\nstatic long   maxOp(long    inA,long inB)    { return std::max(inA,inB); }\nstatic float  maxOp(float   inA,float inB)   { return std::max(inA,inB); }\nstatic double maxOp(double  inA,double inB)  { return std::max(inA,inB); }\nstatic BigInt maxOp(BigInt inA,BigInt inB) {\n\treturn inA>inB ? inA : inB;\n}\nstatic BigFloat maxOp(BigFloat inA,BigFloat inB) {\n\treturn inA>inB ? inA : inB;\n}\n\nstatic int    minOp(int     inA,int inB)     { return std::min(inA,inB); }\nstatic long   minOp(long    inA,long inB)    { return std::min(inA,inB); }\nstatic float  minOp(float   inA,float inB)   { return std::min(inA,inB); }\nstatic double minOp(double  inA,double inB)  { return std::min(inA,inB); }\nstatic BigInt minOp(BigInt inA,BigInt inB) {\n\treturn inA<inB ? inA : inB;\n}\nstatic BigFloat minOp(BigFloat inA,BigFloat inB) {\n\treturn inA<inB ? inA : inB;\n}\n\nvoid InitDict_Math() {\n\tInstall(new Word(\"true\",WORD_FUNC {\n\t\tinContext.DS.emplace_back(true);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"false\",WORD_FUNC {\n\t\tinContext.DS.emplace_back(false);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"+\",WORD_FUNC { TwoOp(+); },LVOP::LVOpSupported2args| LVOP::ADD));\n\tInstall(new Word(\"-\",WORD_FUNC { TwoOp(-); },LVOP::LVOpSupported2args| LVOP::SUB));\n\tInstall(new Word(\"*\",WORD_FUNC { TwoOp(*); },LVOP::LVOpSupported2args| LVOP::MUL));\n\tInstall(new Word(\"/\",WORD_FUNC { TwoOp(/); },LVOP::LVOpSupported2args| LVOP::DIV));\n\tInstall(new Word(\"%\",WORD_FUNC {\n\t\tif(inContext.DS.size()<2) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2);\n\t\t}\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tCheckIntegerAndNonZero(tos);\n\t\tTypedValue& second=ReadTOS(inContext.DS);\n\t\tModAssign(second,tos); \t// second %= tos;\n\t\tNEXT;\n\t}));\n\n\n\tInstall(new Word(\"2*\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\t\ttos.intValue\t   *= 2;\tbreak;\n\t\t\tcase DataType::kTypeLong:\t\ttos.longValue\t   *= 2L;\tbreak;\n\t\t\tcase DataType::kTypeBigInt:\t\t*(tos.bigIntPtr)   *= 2;\tbreak;\n\t\t\tcase DataType::kTypeFloat:\t\ttos.floatValue\t   *= 2.0f;\tbreak;\n\t\t\tcase DataType::kTypeDouble:\t\ttos.doubleValue\t   *= 2.0;\tbreak;\n\t\t\tcase DataType::kTypeBigFloat:\t*(tos.bigFloatPtr) *= 2;\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t},LVOP::LVOpSupported1args | LVOP::TWC));\n\n\tInstall(new Word(\"@+\",WORD_FUNC { RefTwoOp(inContext.DS,+); }));\n\tInstall(new Word(\"@-\",WORD_FUNC { RefTwoOp(inContext.DS,-); }));\n\tInstall(new Word(\"@*\",WORD_FUNC { RefTwoOp(inContext.DS,*); }));\n\tInstall(new Word(\"@/\",WORD_FUNC { RefTwoOp(inContext.DS,/); }));\n\tInstall(new Word(\"@%\",WORD_FUNC {\n\t\tif(inContext.DS.size()<2) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tTypedValue& second=ReadSecond(inContext.DS);\n\t\tCheckIntegerAndNonZero(tos);\n\t\tRefMod(inContext.DS,second,tos);\n\t\tNEXT;\n\t}));\n\n\n\tInstall(new Word(\"+@\",WORD_FUNC { TwoOpAssignTOS(+); }));\n\tInstall(new Word(\"-@\",WORD_FUNC { TwoOpAssignTOS(-); }));\n\tInstall(new Word(\"*@\",WORD_FUNC { TwoOpAssignTOS(*); }));\n\tInstall(new Word(\"/@\",WORD_FUNC { TwoOpAssignTOS(/); }));\n\tInstall(new Word(\"%@\",WORD_FUNC {\n\t\tif(inContext.DS.size()<2) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tTypedValue& second=ReadSecond(inContext.DS);\n\t\tCheckIntegerAndNonZero(tos);\n\t\tModAssignTOS(inContext,second,tos);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"&\",WORD_FUNC { BitOp(&); }));\n\tInstall(new Word(\"|\",WORD_FUNC { BitOp(|); }));\n\tInstall(new Word(\"^\",WORD_FUNC { BitOp(^); }));\n\tInstall(new Word(\">>\",WORD_FUNC { BitShiftOp(>>); }));\n\tInstall(new Word(\"<<\",WORD_FUNC { BitShiftOp(<<); }));\n\n\tInstall(new Word(\"@&\",WORD_FUNC { RefBitOp(&); }));\n\tInstall(new Word(\"@|\",WORD_FUNC { RefBitOp(|); }));\n\tInstall(new Word(\"@^\",WORD_FUNC { RefBitOp(^); }));\n\tInstall(new Word(\"@>>\",WORD_FUNC { RefBitShiftOp(>>); }));\n\tInstall(new Word(\"@<<\",WORD_FUNC { RefBitShiftOp(<<); }));\n\n\t// bitwise NOT.\n\tInstall(new Word(\"~\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt: \ttos.intValue=~tos.intValue;\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\ttos.longValue=~tos.longValue;\tbreak;\n\t\t\tcase DataType::kTypeBigInt:\t*tos.bigIntPtr=~*tos.bigIntPtr;\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_INT_OR_LONG_OR_BIGINT,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"@~\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\n\t\t\t\tinContext.DS.emplace_back(~tos.intValue);\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\n\t\t\t\tinContext.DS.emplace_back(~tos.longValue);\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigInt:\n\t\t\t\tinContext.DS.emplace_back(~*tos.bigIntPtr);\t\n\t\t\t\tbreak;\n\t\t\tdefault: \n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_INT_OR_LONG_OR_BIGINT,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">\",WORD_FUNC { CmpOp(>); }));\n\tInstall(new Word(\"<\",WORD_FUNC { CmpOp(<); }));\n\tInstall(new Word(\">=\",WORD_FUNC { CmpOp(>=); }));\n\tInstall(new Word(\"<=\",WORD_FUNC { CmpOp(<=); }));\n\tInstall(new Word(\"==\",WORD_FUNC { CmpOp(==); }));\n\tInstall(new Word(\"!=\",WORD_FUNC { CmpOp(!=); }));\n\n\tInstall(new Word(\"@>\",WORD_FUNC { RefCmpOp(>); }));\n\tInstall(new Word(\"@<\",WORD_FUNC { RefCmpOp(<); }));\n\tInstall(new Word(\"@>=\",WORD_FUNC { RefCmpOp(>=); }));\n\tInstall(new Word(\"@<=\",WORD_FUNC { RefCmpOp(<=); }));\n\tInstall(new Word(\"@==\",WORD_FUNC { RefCmpOp(==); }));\n\tInstall(new Word(\"@!=\",WORD_FUNC { RefCmpOp(!=); }));\n\n\tInstall(new Word(\"&&\",WORD_FUNC { BoolOp(&&); }));\n\tInstall(new Word(\"||\",WORD_FUNC { BoolOp(||); }));\n\tInstall(new Word(\"xor\",WORD_FUNC { BoolOp(!=); }));\n\tInstall(new Word(\"not\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tif(tos.dataType!=DataType::kTypeBool) {\n\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_BOOL,tos);\n\t\t}\n\t\ttos.boolValue = tos.boolValue != true;\n\t\tNEXT;\n\t}));\n\tInstall(new Word(\"not-true?\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tinContext.DS.emplace_back(!(tos.dataType==DataType::kTypeBool\n\t\t\t\t\t\t\t\t\t&& tos.boolValue==true));\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"sqrt\",WORD_FUNC { OneArgFloatingFunc(sqrt); }));\n\n\tInstall(new Word(\"square\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\n\t\t\t\ttos.intValue*=tos.intValue;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\n\t\t\t\ttos.longValue*=tos.longValue;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigInt:\n\t\t\t\t*(tos.bigIntPtr) *= *(tos.bigIntPtr);\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeFloat:\n\t\t\t\ttos.floatValue*=tos.floatValue;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeDouble:\n\t\t\t\ttos.doubleValue*=tos.doubleValue;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigFloat:\n\t\t\t\t*(tos.bigFloatPtr) *= *(tos.bigFloatPtr);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"exp\", WORD_FUNC { OneParamFunc(exp);  }));\n\tInstall(new Word(\"log\", WORD_FUNC { OneParamFunc(log);  }));\n\tInstall(new Word(\"log10\", WORD_FUNC { OneParamFunc(log10);  }));\n\n\tInstall(new Word(\"sin\",WORD_FUNC { OneParamFunc(sin); }));\n\tInstall(new Word(\"cos\",WORD_FUNC { OneParamFunc(cos); }));\n\tInstall(new Word(\"tan\",WORD_FUNC { OneParamFunc(tan); }));\n\n\tInstall(new Word(\"asin\",WORD_FUNC { OneParamFunc(asin); }));\n\tInstall(new Word(\"acos\",WORD_FUNC { OneParamFunc(acos); }));\n\tInstall(new Word(\"atan\",WORD_FUNC { OneParamFunc(atan); }));\n\n\tInstall(new Word(\"abs\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\n\t\t\t\tinContext.DS.emplace_back(abs(tos.intValue));\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\n\t\t\t\tinContext.DS.emplace_back(abs(tos.longValue));\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigInt:\n\t\t\t\tinContext.DS.emplace_back(abs(*(tos.bigIntPtr)));\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeFloat:\n\t\t\t\tinContext.DS.emplace_back(abs(tos.floatValue));\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeDouble:\n\t\t\t\tinContext.DS.emplace_back(abs(tos.doubleValue));\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigFloat:\n\t\t\t\tinContext.DS.emplace_back(abs(*(tos.bigIntPtr)));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"floor\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tFloorOrCeil(floor,tos);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"ceil\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tFloorOrCeil(ceil,tos);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"deg-to-rad\",WORD_FUNC { OneParamFunc(deg2rad); }));\n\tInstall(new Word(\"rad-to-deg\",WORD_FUNC { OneParamFunc(rad2deg); }));\n\n\tInstall(new Word(\"pow\",WORD_FUNC { \n\t\tusing namespace boost::multiprecision;\n\n\t\tif(inContext.DS.size()<2) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2);\n\t\t}\n\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tTypedValue& second=ReadTOS(inContext.DS);\n\t\tif(second.dataType==DataType::kTypeDouble) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase DataType::kTypeInt: /* double x int -> double */\n\t\t\t\t\tsecond.doubleValue=pow(second.doubleValue,(double)tos.intValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeLong: /* double x long -> double */\n\t\t\t\t\tsecond.doubleValue=pow(second.doubleValue,(double)tos.longValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeFloat: /* double x float -> double */\n\t\t\t\t\tsecond.doubleValue=pow(second.doubleValue,(double)tos.floatValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeDouble: /* double x double -> dobule */\n\t\t\t\t\tsecond.doubleValue=pow(second.doubleValue,tos.doubleValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeBigInt: { /* double x bigInt -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.doubleValue),\n\t\t\t\t\t\t\t\t\t  BigFloat(*tos.bigIntPtr)); \n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=DataType::kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeBigFloat: { /* double x bigFloat -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.doubleValue),*tos.bigFloatPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=DataType::kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else if(second.dataType==DataType::kTypeBigInt) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase DataType::kTypeInt:\t/* bigInt x int -> bigInt */\n\t\t\t\t\t*second.bigIntPtr=pow(*second.bigIntPtr,tos.intValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeLong:\t/* bigInt x long -> bigInt */\n\t\t\t\t\t*second.bigIntPtr=pow(*second.bigIntPtr,tos.longValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeFloat: {\t/* bigInt x float -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(*second.bigIntPtr),\n\t\t\t\t\t\t\t\t\t  BigFloat(tos.floatValue));\n\t\t\t\t\t\tdelete(second.bigIntPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=DataType::kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeDouble: {\t/* bigInt x double -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(*second.bigIntPtr),\n\t\t\t\t\t\t\t\t\t  BigFloat(tos.doubleValue));\n\t\t\t\t\t\tdelete(second.bigIntPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=DataType::kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeBigInt: /* bigInt x bigInt -> bigInt */\n\t\t\t\t\treturn inContext.Error(InvalidTypeTosSecondErrorID::E_OUT_OF_SUPPORT_TOS_SECOND,tos,second);\n\t\t\t\tcase DataType::kTypeBigFloat: { /* bigInt x bigFloat -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(*second.bigIntPtr),*tos.bigFloatPtr);\n\t\t\t\t\t\tdelete(second.bigIntPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=DataType::kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else if(second.dataType==DataType::kTypeBigFloat) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase DataType::kTypeInt: /* bigFloat x int -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,\n\t\t\t\t\t\t\t\t\t\t\tBigFloat(tos.intValue));\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeLong: /* bigFloat x long -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,\n\t\t\t\t\t\t\t\t\t\t\t BigFloat(tos.longValue));\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeFloat: /* bigFloat x float -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,\n\t\t\t\t\t\t\t\t\t\t\tBigFloat(tos.floatValue));\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeDouble: /* bigFloat x double -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,\n\t\t\t\t\t\t\t\t\t\t\tBigFloat(tos.doubleValue));\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeBigInt: /* bigFloat x bigInt -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,\n\t\t\t\t\t\t\t\t\t\t\tBigFloat(*tos.bigIntPtr));\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeBigFloat: /* bigFloat x bigFloat -> bigFloat */\n\t\t\t\t\t*second.bigFloatPtr=pow(*second.bigFloatPtr,*tos.bigFloatPtr);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else if(second.dataType==DataType::kTypeInt) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase DataType::kTypeInt:\t/* int x int -> int */\n\t\t\t\t\tsecond.intValue=(int)pow(second.intValue,tos.intValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeLong:\t/* int x long -> long */\n\t\t\t\t\tsecond.longValue=(long)pow((long)second.intValue,tos.longValue);\n\t\t\t\t\tsecond.dataType=DataType::kTypeLong;\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeFloat: /* int x float -> float */\n\t\t\t\t\tsecond.floatValue=(float)pow((float)second.intValue,\n\t\t\t\t\t\t\t\t\t\t\t\t tos.floatValue);\n\t\t\t\t\tsecond.dataType=DataType::kTypeFloat;\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeDouble: /* int x double -> double */\n\t\t\t\t\tsecond.doubleValue=(double)pow((double)second.intValue,\n\t\t\t\t\t\t\t\t\t\t\t\t   tos.doubleValue);\n\t\t\t\t\tsecond.dataType=DataType::kTypeDouble;\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeBigInt: /* int x bigInt -> OutOfSupport */\n\t\t\t\t\treturn inContext.Error(InvalidTypeTosSecondErrorID::E_OUT_OF_SUPPORT_TOS_SECOND,tos,second);\n\t\t\t\tcase DataType::kTypeBigFloat: { /* int x bigFloat -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.intValue),*tos.bigFloatPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=DataType::kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\t\t\t\t\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else if(second.dataType==DataType::kTypeLong) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase DataType::kTypeInt:\t/* long x int -> long */\n\t\t\t\t\tsecond.longValue=(long)pow(second.longValue,(long)tos.intValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeLong:\t/* long x long -> long */\n\t\t\t\t\tsecond.longValue=(long)pow(second.longValue,tos.longValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeFloat:\t/* long x float -> float */\n\t\t\t\t\tsecond.floatValue=(float)pow((float)second.longValue,\n\t\t\t\t\t\t\t\t\t\t\t\t tos.floatValue);\n\t\t\t\t\tsecond.dataType=DataType::kTypeFloat;\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeDouble:\t/* long x double -> double */\n\t\t\t\t\tsecond.doubleValue=(double)pow((double)second.longValue,\n\t\t\t\t\t\t\t\t\t\t\t\t   tos.doubleValue);\n\t\t\t\t\tsecond.dataType=DataType::kTypeDouble;\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeBigInt: /* long x bigInt -> OutOfSupport */\n\t\t\t\t\treturn inContext.Error(InvalidTypeTosSecondErrorID::E_OUT_OF_SUPPORT_TOS_SECOND,tos,second);\n\t\t\t\tcase DataType::kTypeBigFloat: { /* long x bigFloat -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.longValue),*tos.bigFloatPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=DataType::kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else if(second.dataType==DataType::kTypeFloat) {\n\t\t\tswitch(tos.dataType) {\n\t\t\t\tcase DataType::kTypeInt: /* float x int -> float */\n\t\t\t\t\tsecond.floatValue=(float)pow((double)second.floatValue,\n\t\t\t\t\t\t\t\t\t\t\t\t (double)tos.intValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeLong: /* float x long -> float*/\n\t\t\t\t\tsecond.floatValue=(float)pow((double)second.floatValue,\n\t\t\t\t\t\t\t\t\t\t\t\t (double)tos.longValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeFloat: /* float x float -> float */\n\t\t\t\t\tsecond.floatValue=(float)pow((double)second.floatValue,\n\t\t\t\t\t\t\t\t\t\t\t\t (double)tos.floatValue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeDouble: /* float x double -> dobule */\n\t\t\t\t\tsecond.doubleValue=pow((double)second.floatValue,tos.doubleValue);\n\t\t\t\t\tsecond.dataType=DataType::kTypeDouble;\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeBigInt: { /* float x bigInt -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.floatValue),\n\t\t\t\t\t\t\t\t\t  BigFloat(*tos.bigIntPtr));\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=DataType::kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeBigFloat: { /* float x bigFloat -> bigFloat */\n\t\t\t\t\t\tBigFloat *bigFloat=new BigFloat();\n\t\t\t\t\t\t*bigFloat=pow(BigFloat(second.floatValue),*tos.bigFloatPtr);\n\t\t\t\t\t\tsecond.bigFloatPtr=bigFloat;\n\t\t\t\t\t\tsecond.dataType=DataType::kTypeBigFloat;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: goto onError;\n\t\t\t}\n\t\t} else { \nonError: \n\t\t\treturn inContext.Error(InvalidTypeTosSecondErrorID::E_INVALID_DATA_TYPE_TOS_SECOND,tos,second);\n\t\t} \n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"max\",WORD_FUNC {\n\t\tif(inContext.DS.size()<2) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2);\n\t\t}\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tTypedValue second=Pop(inContext.DS);\n\t\tPushFuncResult(inContext.DS,maxOp,second,tos);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"min\",WORD_FUNC {\n\t\tif(inContext.DS.size()<2) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2);\n\t\t}\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tTypedValue second=Pop(inContext.DS);\n\t\tPushFuncResult(inContext.DS,minOp,second,tos);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"0?\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\n\t\t\t\ttos.dataType=DataType::kTypeBool;\n\t\t\t\ttos.boolValue=tos.intValue==0;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\n\t\t\t\ttos.dataType=DataType::kTypeBool;\n\t\t\t\ttos.boolValue=tos.longValue==0;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigInt: {\n\t\t\t\t\tBigInt *biPtr=tos.bigIntPtr;\n\t\t\t\t\ttos.dataType=DataType::kTypeBool;\n\t\t\t\t\ttos.boolValue=*biPtr==0;\n\t\t\t\t\tdelete(biPtr);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeFloat:\n\t\t\t\ttos.dataType=DataType::kTypeBool;\n\t\t\t\ttos.boolValue=tos.floatValue==0;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeDouble:\n\t\t\t\ttos.dataType=DataType::kTypeBool;\n\t\t\t\ttos.boolValue=tos.doubleValue==0;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigFloat: {\n\t\t\t\t\tBigFloat *bfPtr=tos.bigFloatPtr;\n\t\t\t\t\ttos.dataType=DataType::kTypeBool;\n\t\t\t\t\ttos.boolValue=*bfPtr==0;\n\t\t\t\t\tdelete(bfPtr);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\t// equivalent to '1 +'.\n\tInstall(new Word(\"1+\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\t\ttos.intValue+=1;\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\t\ttos.longValue+=1;\t\tbreak;\n\t\t\tcase DataType::kTypeFloat:\t\ttos.floatValue+=1;\t\tbreak;\n\t\t\tcase DataType::kTypeDouble:\t\ttos.doubleValue+=1;\t\tbreak;\n\t\t\tcase DataType::kTypeBigInt:\t\t*tos.bigIntPtr+=1;\t\tbreak;\n\t\t\tcase DataType::kTypeBigFloat:\t*tos.bigFloatPtr+=1;\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t},LVOP::LVOpSupported1args | LVOP::INC));\n\n\t// equivalent to '1 -'.\n\tInstall(new Word(\"1-\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\t\ttos.intValue-=1;\tbreak;\n\t\t\tcase DataType::kTypeLong:\t\ttos.longValue-=1;\tbreak;\n\t\t\tcase DataType::kTypeFloat:\t\ttos.floatValue-=1;\tbreak;\n\t\t\tcase DataType::kTypeDouble:\t\ttos.doubleValue-=1;\tbreak;\n\t\t\tcase DataType::kTypeBigInt:\t\t*tos.bigIntPtr-=1;\tbreak;\n\t\t\tcase DataType::kTypeBigFloat:\t*tos.bigFloatPtr-=1;break;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t},LVOP::LVOpSupported1args | LVOP::DEC));\n\n\tInstall(new Word(\"2/\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\t\ttos.intValue/=2;\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\t\ttos.longValue/=2;\t\tbreak;\n\t\t\tcase DataType::kTypeFloat:\t\ttos.floatValue/=2.0f;\tbreak;\n\t\t\tcase DataType::kTypeDouble:\t\ttos.doubleValue/=2.0;\tbreak;\n\t\t\tcase DataType::kTypeBigInt:\t\t*tos.bigIntPtr/=2;\t\tbreak;\n\t\t\tcase DataType::kTypeBigFloat:\t*tos.bigFloatPtr/=2.0;\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"even?\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\n\t\t\t\ttos.boolValue = (tos.intValue & 0x01)==0;\n\t\t\t\ttos.dataType=DataType::kTypeBool;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\n\t\t\t\ttos.boolValue = (tos.longValue & 0x01)==0;\n\t\t\t\ttos.dataType=DataType::kTypeBool;\n\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeBigInt: {\n\t\t\t\t\tbool result=(*tos.bigIntPtr & 0x01)==0;\n\t\t\t\t\tdelete tos.bigIntPtr;\n\t\t\t\t\ttos.dataType=DataType::kTypeBool;\n\t\t\t\t\ttos.boolValue=result;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_INT_OR_LONG_OR_BIGINT,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"@even?\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tbool result=false;\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt: \t\tresult = (tos.intValue & 0x01)==0; \tbreak;\n\t\t\tcase DataType::kTypeLong:\t\tresult = (tos.longValue & 0x01)==0; break;\n\t\t\tcase DataType::kTypeBigInt: \tresult = (*tos.bigIntPtr & 0x01)==0;break;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_INT_OR_LONG_OR_BIGINT,tos);\n\t\t}\n\t\tinContext.DS.emplace_back(result);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"rand-max\",WORD_FUNC {\n\t\tinContext.DS.emplace_back(RAND_MAX);\n\t\tNEXT;\n\t}));\n\n\t// I ---\n\tInstall(new Word(\"set-random-seed\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tif(tos.dataType!=DataType::kTypeInt) {\n\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_INT,tos);\n\t\t}\n\t\tsrand((unsigned int)tos.intValue);\n\t\tNEXT;\n\t}));\n\t\n\t// [0,RAND_MAX]\n\tInstall(new Word(\"rand\",WORD_FUNC {\n\t\tinContext.DS.emplace_back(rand());\n\t\tNEXT;\n\t}));\n\n\t// [0,1]\n\tInstall(new Word(\"random\",WORD_FUNC {\n\t\tinContext.DS.emplace_back((float)rand()/(float)RAND_MAX);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"randomize\",WORD_FUNC {\n\t\tsrand((unsigned int)time(NULL));\n\t\tNEXT;\n\t}));\n\n\t// n1 --- n2 \n\t// s.t. n2 is an integer where n2 in [0,n1).\n\tInstall(new Word(\"rand-to\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tif(tos.dataType!=DataType::kTypeInt) {\n\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_INT,tos);\n\t\t}\n\n\t\tconst int n=tos.intValue;\n\t\tif(n<0 || RAND_MAX<n) {\n\t\t\treturn inContext.Error(ErrorIdWithInt::E_TOS_POSITIVE_INT,n);\n\t\t}\n\t\tint t=(int)(rand()/((float)RAND_MAX+1)*n);\n\t\tinContext.DS.emplace_back(t);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\"pi\",WORD_FUNC {\n\t\tinContext.DS.emplace_back(M_PI);\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">int\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tif(tos.dataType==DataType::kTypeFloat) {\n\t\t\tif(tos.floatValue<INT_MIN || INT_MAX<tos.floatValue) {\n\t\t\t\treturn inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.intValue=(int)tos.floatValue;\n\t\t} else if(tos.dataType==DataType::kTypeDouble) {\n\t\t\tif(tos.doubleValue<INT_MIN || INT_MAX<tos.doubleValue) {\n\t\t\t\treturn inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.intValue=(int)tos.doubleValue;\n\t\t} else if(tos.dataType==DataType::kTypeLong) {\n\t\t\tif(tos.longValue<(long)INT_MIN || (long)INT_MAX<tos.longValue) {\n\t\t\t\treturn inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.intValue=(int)tos.longValue;\n\t\t} else if(tos.dataType==DataType::kTypeBigInt) {\n\t\t\tif(*tos.bigIntPtr<INT_MIN || INT_MAX<*tos.bigIntPtr) {\n\t\t\t\treturn inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.intValue=static_cast<int>(*tos.bigIntPtr);\n\t\t} else if(tos.dataType==DataType::kTypeAddress) {\n\t\t\ttos.dataType=DataType::kTypeInt;\n\t\t} else if(tos.dataType!=DataType::kTypeInt) {\n\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos);\n\t\t}\n\t\ttos.dataType=DataType::kTypeInt;\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">long\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tif(tos.dataType==DataType::kTypeFloat) {\n\t\t\tif(tos.floatValue<LONG_MIN || LONG_MAX<tos.floatValue) {\n\t\t\t\treturn inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_LONG_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.longValue=(long)tos.floatValue;\n\t\t} else if(tos.dataType==DataType::kTypeDouble) {\n\t\t\tif(tos.doubleValue<LONG_MIN || LONG_MAX<tos.doubleValue) {\n\t\t\t\treturn inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_LONG_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.longValue=(long)tos.doubleValue;\n\t\t} else if(tos.dataType==DataType::kTypeInt) {\n\t\t\ttos.longValue=(long)tos.intValue;\n\t\t} else if(tos.dataType==DataType::kTypeBigInt) {\n\t\t\tif(*tos.bigIntPtr<LONG_MIN || LONG_MAX<*tos.bigIntPtr) {\n\t\t\t\treturn inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_LONG_DUE_TO_OVERFLOW);\n\t\t\t}\n\t\t\ttos.longValue=static_cast<long>(*tos.bigIntPtr);\n\t\t} else if(tos.dataType!=DataType::kTypeLong) {\n\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos);\n\t\t}\n\t\ttos.dataType=DataType::kTypeLong;\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">INT\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tBigInt bigInt;\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\n\t\t\t\tbigInt=tos.intValue;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\n\t\t\t\tbigInt=tos.longValue;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeFloat:\n\t\t\t\tbigInt=static_cast<BigInt>(tos.floatValue);\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeDouble:\n\t\t\t\tbigInt=static_cast<BigInt>(tos.doubleValue);\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeString:\n\t\t\t\tbigInt=BigInt(*tos.stringPtr);\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigInt:\n\t\t\t\t// do nothing\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigFloat:\n\t\t\t\tbigInt=static_cast<BigInt>(*tos.bigFloatPtr);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER_OR_STRING,tos);\n\t\t}\n\t\tif(tos.dataType!=DataType::kTypeBigInt) {\n\t\t\tinContext.DS.emplace_back(bigInt);\n\t\t} else {\n\t\t\tinContext.DS.emplace_back(*tos.bigIntPtr);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">float\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\n\t\t\t\ttos.floatValue=(float)tos.intValue;\n\t\t\t\ttos.dataType=DataType::kTypeFloat;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\n\t\t\t\ttos.floatValue=(float)tos.longValue;\n\t\t\t\ttos.dataType=DataType::kTypeFloat;\n\t\t\t\tbreak;\n\t\t\t\tcase DataType::kTypeBigInt: {\n\t\t\t\t\tif(*tos.bigIntPtr>kBigInt_FLT_MAX\n\t\t\t\t\t  || *tos.bigIntPtr<kBigInt_Minus_FLT_MAX) {\n\t\t\t\t\t\treturn inContext.Error(\n\t\t\t\t\t\t\t\tNoParamErrorID::E_CAN_NOT_CONVERT_TO_FLOAT_DUE_TO_OVERFLOW);\n\t\t\t\t\t}\n\t\t\t\t\tfloat f=tos.ToFloat(inContext);\n\t\t\t\t\tdelete tos.bigIntPtr;\n\t\t\t\t\ttos.floatValue=f;\n\t\t\t\t\ttos.dataType=DataType::kTypeFloat;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeFloat:\n\t\t\t\t// do nothing\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeDouble:\n\t\t\t\tif(tos.doubleValue>FLT_MAX || tos.doubleValue<-FLT_MAX) {\n\t\t\t\t\treturn inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_FLOAT_DUE_TO_OVERFLOW);\n\t\t\t\t}\n\t\t\t\ttos.floatValue=(float)tos.doubleValue;\n\t\t\t\ttos.dataType=DataType::kTypeFloat;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigFloat: {\n\t\t\t\t\tif(*tos.bigFloatPtr>FLT_MAX || *tos.bigFloatPtr<-FLT_MAX) {\n\t\t\t\t\t\treturn inContext.Error(\n\t\t\t\t\t\t\t\tNoParamErrorID::E_CAN_NOT_CONVERT_TO_FLOAT_DUE_TO_OVERFLOW);\n\t\t\t\t\t}\n\t\t\t\t\tfloat f=tos.ToFloat(inContext);\n\t\t\t\t\tdelete tos.bigFloatPtr;\n\t\t\t\t\ttos.floatValue=f;\n\t\t\t\t\ttos.dataType=DataType::kTypeFloat;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">double\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\n\t\t\t\ttos.doubleValue=(double)tos.intValue;\n\t\t\t\ttos.dataType=DataType::kTypeDouble;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\n\t\t\t\ttos.doubleValue=(double)tos.longValue;\n\t\t\t\ttos.dataType=DataType::kTypeDouble;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigInt: {\n\t\t\t\t\tif(*tos.bigIntPtr>kBigInt_DBL_MAX\n\t\t\t\t\t  || *tos.bigIntPtr<kBigInt_Minus_DBL_MAX) {\n\t\t\t\t\t\treturn inContext.Error(\n\t\t\t\t\t\t\t\tNoParamErrorID::E_CAN_NOT_CONVERT_TO_DOUBLE_DUE_TO_OVERFLOW);\n\t\t\t\t\t}\n\t\t\t\t\tdouble t=tos.ToDouble(inContext);\n\t\t\t\t\tdelete tos.bigIntPtr;\n\t\t\t\t\ttos.doubleValue=t;\n\t\t\t\t\ttos.dataType=DataType::kTypeDouble;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeFloat:\n\t\t\t\ttos.doubleValue=(double)tos.floatValue;\n\t\t\t\ttos.dataType=DataType::kTypeDouble;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeDouble:\n\t\t\t\t// do nothing\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigFloat: {\n\t\t\t\t\tif(*tos.bigFloatPtr>DBL_MAX || *tos.bigFloatPtr<-DBL_MAX) {\n\t\t\t\t\t\treturn inContext.Error(\n\t\t\t\t\t\t\t\tNoParamErrorID::E_CAN_NOT_CONVERT_TO_DOUBLE_DUE_TO_OVERFLOW);\n\t\t\t\t\t}\n\t\t\t\t\tdouble t=tos.ToDouble(inContext);\n\t\t\t\t\tdelete tos.bigFloatPtr;\n\t\t\t\t\ttos.doubleValue=t;\n\t\t\t\t\ttos.dataType=DataType::kTypeDouble;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">FLOAT\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue tos=Pop(inContext.DS);\n\t\tBigFloat bigFloat;\n\t\tswitch(tos.dataType) {\n\t\t\tcase DataType::kTypeInt:\n\t\t\t\tbigFloat=tos.intValue;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeLong:\n\t\t\t\tbigFloat=tos.longValue;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeFloat:  \n\t\t\t\tbigFloat=tos.floatValue;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeDouble:\n\t\t\t\tbigFloat=tos.doubleValue;\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeString:\n\t\t\t\tbigFloat=BigFloat(*tos.stringPtr);\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigInt:\n\t\t\t\tbigFloat=static_cast<BigFloat>(*tos.bigIntPtr);\n\t\t\t\tbreak;\n\t\t\tcase DataType::kTypeBigFloat:\n\t\t\t   \t/* do nothing */\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t  \t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER_OR_STRING,tos);\n\t\t}\n\t\tif(tos.dataType!=DataType::kTypeBigFloat) {\n\t\t\tinContext.DS.emplace_back(bigFloat);\n\t\t} else {\n\t\t\tinContext.DS.emplace_back(*tos.bigFloatPtr);\n\t\t}\n\t\tNEXT;\n\t}));\n\n\tInstall(new Word(\">address\",WORD_FUNC {\n\t\tif(inContext.DS.size()<1) {\n\t\t\treturn inContext.Error(NoParamErrorID::E_DS_IS_EMPTY);\n\t\t}\n\t\tTypedValue& tos=ReadTOS(inContext.DS);\n\t\tif(tos.dataType!=DataType::kTypeInt && tos.dataType!=DataType::kTypeAddress) {\n\t\t\treturn inContext.Error(InvalidTypeErrorID::E_TOS_INT,tos);\n\t\t}\n\t\ttos.dataType=DataType::kTypeAddress;\n\t\tNEXT;\n\t}));\n}\n\n", "meta": {"hexsha": "1660ea4910680a585d96ef2419cc861733bb6e65", "size": 32708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dict/dictMath.cpp", "max_stars_repo_name": "0918nobita/Paraphrase", "max_stars_repo_head_hexsha": "1c2a74d664ebd6f6ab663bbc41c4e72bed288c1a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2019-01-10T00:41:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T07:10:22.000Z", "max_issues_repo_path": "src/dict/dictMath.cpp", "max_issues_repo_name": "0918nobita/Paraphrase", "max_issues_repo_head_hexsha": "1c2a74d664ebd6f6ab663bbc41c4e72bed288c1a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-02-18T04:08:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-24T10:00:39.000Z", "max_forks_repo_path": "src/dict/dictMath.cpp", "max_forks_repo_name": "0918nobita/Paraphrase", "max_forks_repo_head_hexsha": "1c2a74d664ebd6f6ab663bbc41c4e72bed288c1a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-03T08:55:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-18T17:31:17.000Z", "avg_line_length": 32.708, "max_line_length": 98, "alphanum_fraction": 0.6845114345, "num_tokens": 9806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857204, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.6135656357279653}}
{"text": "// test computeCost\n#include <cassert>\n#include <armadillo>\n#include \"../../ex1/computeCost.hpp\"\n#include \"../../ex1/util.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n    fmat X;\n    fvec y, theta;\n\n    parse_mat(&X, \"[ 2, 1, 3; 7, 1, 9; 1, 8, 1; 3, 7, 4 ]\");\n    parse_mat(&y, \"[2 ; 5 ; 5 ; 6]\");\n    parse_mat(&theta, \"[0.4 ; 0.6 ; 0.8]\");\n\n    auto J = computeCost(X, y, theta);\n    cout << \"J = \" << J << endl;\n    assert(J >= 5.2950f && J < 5.29501f);\n\n    return 0;\n}\n", "meta": {"hexsha": "def466d6a53f6b3bbef9604ca6cbaf06c9c585f2", "size": 492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ex1/computeCostMulti_main.cpp", "max_stars_repo_name": "kolbma/coursera-ml", "max_stars_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T21:08:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T21:08:21.000Z", "max_issues_repo_path": "tests/ex1/computeCostMulti_main.cpp", "max_issues_repo_name": "kolbma/coursera-ml", "max_issues_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "max_issues_repo_licenses": ["Apache-2.0"], "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/ex1/computeCostMulti_main.cpp", "max_forks_repo_name": "kolbma/coursera-ml", "max_forks_repo_head_hexsha": "a8473829138804cf6a46cc60e076d9851b55ae25", "max_forks_repo_licenses": ["Apache-2.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.68, "max_line_length": 60, "alphanum_fraction": 0.5284552846, "num_tokens": 189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959543, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6135651955493764}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_PROJECTION_HPP\n#define MCL_PROJECTION_HPP 1\n\n#include <Eigen/Core>\n\nnamespace mcl\n{\n\n\n// Projection on Triangle\ntemplate <typename T>\nstatic inline Eigen::Matrix<T,3,1> point_on_triangle(const Eigen::Matrix<T,3,1> &point, const Eigen::Matrix<T,3,1> &p1, const Eigen::Matrix<T,3,1> &p2, const Eigen::Matrix<T,3,1> &p3);\n\n// Projection on Sphere\ntemplate <typename T>\nstatic inline Eigen::Matrix<T,3,1> point_on_sphere(const Eigen::Matrix<T,3,1> &point, const Eigen::Matrix<T,3,1> &center, const T &rad);\n\n// Projection on a Box\ntemplate <typename T>\nstatic inline Eigen::Matrix<T,3,1> point_on_box(const Eigen::Matrix<T,3,1> &point, const Eigen::Matrix<T,3,1> &bmin, const Eigen::Matrix<T,3,1> &bmax);\n\n// Project a point on to a plane\ntemplate <typename T>\nstatic inline Eigen::Matrix<T,3,1> point_on_plane(const Eigen::Matrix<T,3,1> &point, const Eigen::Matrix<T,3,1> &plane_norm, const Eigen::Matrix<T,3,1> &plane_pt);\n\n// Projection on an edge\ntemplate <typename T> \nstatic inline Eigen::Matrix<T,2,1> point_on_edge(const Eigen::Matrix<T,2,1> &point, const Eigen::Matrix<T,2,1> &p1, const Eigen::Matrix<T,2,1> &p2);\n\n// Projection on an edge (3D)\ntemplate <typename T>\nstatic inline Eigen::Matrix<T,3,1> point_on_edge(const Eigen::Matrix<T,3,1> &point, const Eigen::Matrix<T,3,1> &p1, const Eigen::Matrix<T,3,1> &p2);\n\n// Computes the shortest vector from p toward q, as well as\n// the barycentric coordinates of the closest points.\n// The distance between the segments is the norm of this vector.\n// Source: https://github.com/evouga/collisiondetection, license: public domain.\ntemplate <typename T>\nstatic inline Eigen::Matrix<T,3,1> edge_to_edge(\n\tconst Eigen::Matrix<T,3,1> &p0,\n\tconst Eigen::Matrix<T,3,1> &p1,\n\tconst Eigen::Matrix<T,3,1> &q0,\n\tconst Eigen::Matrix<T,3,1> &q1,\n\tEigen::Matrix<T,4,1> &bary);\n\n\n//\n//\tImplementation\n//\n\n// I do not know the source of the function.\n// If anyone knows, please tell me!\ntemplate <typename T>\nEigen::Matrix<T,3,1> point_on_triangle(const Eigen::Matrix<T,3,1> &point, const Eigen::Matrix<T,3,1> &p1, const Eigen::Matrix<T,3,1> &p2, const Eigen::Matrix<T,3,1> &p3)\n{\n\tauto clamp_zero_one = [](const T &val){ return val < 0 ? 0 : (val > 1 ? 1 : val); };\n\n\tEigen::Matrix<T,3,1> edge0 = p2 - p1;\n\tEigen::Matrix<T,3,1> edge1 = p3 - p1;\n\tEigen::Matrix<T,3,1> v0 = p1 - point;\n\n\tT a = edge0.dot(edge0);\n\tT b = edge0.dot(edge1);\n\tT c = edge1.dot(edge1);\n\tT d = edge0.dot(v0);\n\tT e = edge1.dot(v0);\n\tT det = a*c - b*b;\n\tT s = b*e - c*d;\n\tT t = b*d - a*e;\n\n\tconst T zero(0);\n\tconst T one(1);\n\n\tif ( s + t < det ) {\n\t\tif ( s < zero ) {\n\t\t    if ( t < zero ) {\n\t\t\tif ( d < zero ) {\n\t\t\t    s = clamp_zero_one( -d/a );\n\t\t\t    t = zero;\n\t\t\t}\n\t\t\telse {\n\t\t\t    s = zero;\n\t\t\t    t = clamp_zero_one( -e/c );\n\t\t\t}\n\t\t    }\n\t\t    else {\n\t\t\ts = zero;\n\t\t\tt = clamp_zero_one( -e/c );\n\t\t    }\n\t\t}\n\t\telse if ( t < zero ) {\n\t\t    s = clamp_zero_one( -d/a );\n\t\t    t = zero;\n\t\t}\n\t\telse {\n\t\t    T invDet = one / det;\n\t\t    s *= invDet;\n\t\t    t *= invDet;\n\t\t}\n\t}\n\telse {\n\t\tif ( s < zero ) {\n\t\t    T tmp0 = b+d;\n\t\t    T tmp1 = c+e;\n\t\t    if ( tmp1 > tmp0 ) {\n\t\t\tT numer = tmp1 - tmp0;\n\t\t\tT denom = a-T(2)*b+c;\n\t\t\ts = clamp_zero_one( numer/denom );\n\t\t\tt = one-s;\n\t\t    }\n\t\t    else {\n\t\t\tt = clamp_zero_one( -e/c );\n\t\t\ts = zero;\n\t\t    }\n\t\t}\n\t\telse if ( t < zero ) {\n\t\t    if ( a+d > b+e ) {\n\t\t\tT numer = c+e-b-d;\n\t\t\tT denom = a-T(2)*b+c;\n\t\t\ts = clamp_zero_one( numer/denom );\n\t\t\tt = one-s;\n\t\t    }\n\t\t    else {\n\t\t\ts = clamp_zero_one( -e/c );\n\t\t\tt = zero;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    T numer = c+e-b-d;\n\t\t    T denom = a-T(2)*b+c;\n\t\t    s = clamp_zero_one( numer/denom );\n\t\t    t = one - s;\n\t\t}\n\t}\n\n\treturn (p1 + edge0*s + edge1*t);\n\n} // end project triangle\n\n\ntemplate <typename T>\nEigen::Matrix<T,3,1> point_on_sphere(const Eigen::Matrix<T,3,1> &point, const Eigen::Matrix<T,3,1> &center, const T &rad)\n{\n\tEigen::Matrix<T,3,1> dir = point-center;\n\tdir.normalize();\n\treturn (center + dir*rad);\n} // end project sphere\n\n\ntemplate <typename T>\nEigen::Matrix<T,3,1> point_on_box(const Eigen::Matrix<T,3,1> &point, const Eigen::Matrix<T,3,1> &bmin, const Eigen::Matrix<T,3,1> &bmax)\n{\n\t// Loops through axes and moves point to nearest surface\n\tEigen::Matrix<T,3,1> x = point;\n\tT dx = std::numeric_limits<T>::max();\n\tfor (int i=0; i<3; ++i)\n\t{\n\t\tT dx_max = std::abs(bmax[i]-point[i]);\n\t\tT dx_min = std::abs(bmin[i]-point[i]);\n\t\tif(dx_max < dx)\n\t\t{\n\t\t\tx = point;\n\t\t\tx[i] = bmax[i];\n\t\t\tdx = dx_max;\n\t\t}\n\t\tif (dx_min < dx)\n\t\t{\n\t\t\tx = point;\n\t\t\tx[i] = bmin[i];\n\t\t\tdx = dx_min;\n\t\t}\n\t}\n\treturn x;\n} // end project box\n\n\ntemplate <typename T>\nEigen::Matrix<T,3,1> point_on_plane(const Eigen::Matrix<T,3,1> &point, const Eigen::Matrix<T,3,1> &plane_norm, const Eigen::Matrix<T,3,1> &plane_pt)\n{\n    T d = -1 * plane_norm.dot(point-plane_pt);\n    Eigen::Matrix<T,3,1> t_vec = plane_norm * d;\n    return point + t_vec;\n}\n\n\ntemplate <typename T>\nstatic Eigen::Matrix<T,2,1> point_on_edge(const Eigen::Matrix<T,2,1> &p, const Eigen::Matrix<T,2,1> &e0, const Eigen::Matrix<T,2,1> &e1)\n{\n\tEigen::Matrix<T,2,1> e = (e1-e0);\n\tT e_len2 = e.dot(e);\n\tif(e_len2 <= 0.0) { return e0; } // zero length edge\n\tEigen::Matrix<T,2,1> pe0 = (p-e0);\n\tT t = pe0.dot(e)/e_len2;\n\tif (t < 0.0){ return e0; }\n\telse if (t > 1.0) { return e1; }\n\treturn e0 + t * e;\n}\n\n\n// Ericson, Real-Time Collision Detection\ntemplate <typename T>\nstatic Eigen::Matrix<T,3,1> point_on_edge(const Eigen::Matrix<T,3,1> &point, const Eigen::Matrix<T,3,1> &p1, const Eigen::Matrix<T,3,1> &p2)\n{\n\tEigen::Matrix<T,3,1> ab = p2-p1;\n\tT t = ab.dot(point-p1);\n\tEigen::Matrix<T,3,1> d = point; // result\n\n\t// c projects outside the [a,b] interval, on the a side; clamp to a\n\tif (t <= 0)\n\t{\n\t\tt = 0;\n\t\td = p1;\n\t}\n\telse\n\t{\n\t\tT denom = ab.dot(ab); // Always nonnegative since denom = ||ab|| \u2227 2\n\t\t// c projects outside the [a,b] interval, on the b side; clamp to b\n\t\tif (t >= denom)\n\t\t{\n\t\t\tt = 1;\n\t\t\td = p2;\n\t\t}\n\t\t// c projects inside the [a,b] interval; must do deferred divide now\n\t\telse\n\t\t{\n\t\t\tt = t/denom;\n\t\t\td = p1+t*ab;\n\t\t}\n\t}\n\treturn d;\n}\n\n\ntemplate <typename T>\nstatic Eigen::Matrix<T,3,1> edge_to_edge(\n    const Eigen::Matrix<T,3,1> &p0,\n    const Eigen::Matrix<T,3,1> &p1,\n    const Eigen::Matrix<T,3,1> &q0,\n    const Eigen::Matrix<T,3,1> &q1,\n    Eigen::Matrix<T,4,1> &bary)\n{\n\ttypedef Eigen::Matrix<T,3,1> eteVec3;\n\tauto clamp01 = [](T x)\n\t{\n\t\treturn std::min(T(1), std::max(x, T(0)));\n\t};\n\n\teteVec3 d1 = p1-p0;\n\teteVec3 d2 = q1-q0;\n\teteVec3 r = p0-q0;\n\tT a = d1.squaredNorm();\n\tT e = d2.squaredNorm();\n\tT f = d2.dot(r);\n\tT s = 0;\n\tT t = 0;\n\tT c = d1.dot(r);\n\tT b = d1.dot(d2);\n\tT denom = a*e-b*b;\n\tif (denom != T(0)) {\n\t\ts = clamp01((b*f-c*e)/denom);\n\t}\n\telse { // Parallel/degenerate edges\n\t\ts = 0;\n\t}\n\tT tnom = b*s + f;\n\tif(tnom < 0 || e == 0)\n\t{\n\t\tt = 0;\n\t\tif(a == 0) {\n\t\t\ts = 0;\n\t\t} else {\n\t\t\ts = clamp01(-c/a);\n\t\t}\n\t}\n\telse if(tnom > e)\n\t{\n\t\tt = 1.0;\n\t\tif(a == 0) {\n\t\t\ts = 0;\n\t\t} else {\n\t\t\ts = clamp01((b-c)/a);\n\t\t}\n\t}\n\telse {\n\t\tt = tnom/e;\n\t}\n\n\teteVec3 c1 = p0 + s*d1;\n\teteVec3 c2 = q0 + t*d2;\n\tbary[0] = 1-s;\n\tbary[1] = s;\n\tbary[2] = 1-t;\n\tbary[3] = t;\n\treturn c2-c1;\n}\n\n} // end namespace mcl\n\n#endif", "meta": {"hexsha": "d7435d2694ace3ea91735acde5f575574723f4d9", "size": 7152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/Projection.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/Projection.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/Projection.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6821192053, "max_line_length": 184, "alphanum_fraction": 0.5922818792, "num_tokens": 2623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695208, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6135592568648888}}
{"text": "#ifndef EXPSUM_KERNEL_FUNCTIONS_SPH_BESSEL_KERNEL_HPP\n#define EXPSUM_KERNEL_FUNCTIONS_SPH_BESSEL_KERNEL_HPP\n\n#include <armadillo>\n\n#include \"expsum/constants.hpp\"\n#include \"expsum/kernel_functions/gamma.hpp\"\n\nnamespace expsum\n{\n\ntemplate <typename T>\nstruct sph_bessel_kernel\n{\npublic:\n    using size_type    = arma::uword;\n    using real_type    = T;\n    using complex_type = std::complex<T>;\n\n    using vector_type = arma::Col<complex_type>;\n    using matrix_type = arma::Mat<complex_type>;\n\nprivate:\n    vector_type exponent_;\n    vector_type weight_;\n\npublic:\n    void compute(size_type n, real_type band_limit, real_type eps);\n\n    size_type size() const\n    {\n        return exponent_.size();\n    }\n\n    const vector_type& exponents() const\n    {\n        return exponent_;\n    }\n\n    const vector_type& weights() const\n    {\n        return weight_;\n    }\n};\n\ntemplate <typename T>\nvoid sph_bessel_kernel<T>::compute(size_type n, real_type band_limit,\n                                   real_type eps)\n{\n    constexpr const real_type one  = real_type(1);\n    constexpr const real_type zero = real_type();\n    // i^{n % 4}\n    constexpr const complex_type phase_p[4] = {\n        complex_type(one, zero), complex_type(zero, one),\n        complex_type(-one, zero), complex_type(zero, -one)};\n    // (-i)^{n % 4}\n    constexpr const complex_type phase_m[4] = {\n        complex_type(one, zero), complex_type(zero, -one),\n        complex_type(-one, zero), complex_type(zero, one)};\n\n    // k mod 4 = k & mask_mod4\n    constexpr const size_type mask_mod4 = 3; // 0b11\n\n    // static const auto huge = std::sqrt(std::numeric_limits<T>::max());\n    // static const auto huge = std::numeric_limits<T>::max() / 10;\n\n    const auto delta = 1 / band_limit;\n\n    real_type coeff = real_type(1);\n    real_type t_lower, t_upper, h = real_type(1);\n\n    for (size_type k = 0; k <= n; ++k)\n    {\n        const auto beta    = static_cast<real_type>(k + 1);\n        const auto log_eps = std::log(eps / coeff);\n        // Lower bound\n        t_lower = std::min((log_eps + std::lgamma(beta + 1)) / beta, t_lower);\n        t_upper = std::max(t_upper, -std::log(delta) + std::log(-log_eps) +\n                                        std::log(beta) + real_type(0.5));\n        h = std::min(h, 2 * constant<T>::pi /\n                            (std::log(T(3)) - beta * std::log(std::cos(T(1))) -\n                             log_eps));\n        std::cout << \"  (\" << n << ',' << k << \"):\\n\"\n                  << \"    t_lower = \" << t_lower << '\\n'\n                  << \"    t_upper = \" << t_upper << '\\n'\n                  << \"    a(n, k) = \" << coeff << '\\n'\n                  << \"    h       = \" << h << std::endl;\n        coeff *= static_cast<real_type>((n - k) * (n + k + 1)) / (2 * k + 2);\n    }\n\n    const auto N = static_cast<size_type>(std::floor((t_upper - t_lower) / h));\n\n    vector_type a(2 * N);\n    vector_type w(2 * N);\n\n    for (size_type i = 0; i < N; ++i)\n    {\n        const auto ai = std::exp(t_lower + i * h);\n        a(2 * i + 0)  = complex_type(ai, real_type(-1));\n        a(2 * i + 1)  = complex_type(ai, real_type(1));\n    }\n    // a(2 * N) = huge;\n\n    for (size_type i = 0; i < N; ++i)\n    {\n        const auto ti = t_lower + i * h;\n        coeff         = real_type(0.5);\n        auto w0       = complex_type();\n        auto w1       = complex_type();\n        for (size_type k = 0; k <= n; ++k)\n        {\n            auto base_w = coeff * h * std::exp((k + 1) * ti);\n            w0 += base_w * phase_m[(n - k + 1) & mask_mod4];\n            w1 += base_w * phase_p[(n - k + 1) & mask_mod4];\n            coeff *= static_cast<real_type>((n - k) * (n + k + 1)) /\n                     (2 * (k + 1) * (k + 1));\n        }\n        w(2 * i + 0) = w0;\n        w(2 * i + 1) = w1;\n    }\n    // w(2 * N) = -arma::sum(w.head(2 * N)) + (n == 0 ? one : zero);\n\n    exponent_.swap(a);\n    weight_.swap(w);\n    return;\n}\n\n} // namespace: expsum\n\n#endif /* EXPSUM_KERNEL_FUNCTIONS_SPH_BESSEL_KERNEL_HPP */\n", "meta": {"hexsha": "ce312ffa1a8559838da523a761cc9693a7540456", "size": 3989, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/kernel_functions/sph_bessel_kernel.hpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/expsum/kernel_functions/sph_bessel_kernel.hpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/expsum/kernel_functions/sph_bessel_kernel.hpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4503816794, "max_line_length": 79, "alphanum_fraction": 0.5266984207, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6134981766478809}}
{"text": "//\n// Copyright 2019 Mateusz Loskot <mateusz at loskot dot net>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#define BOOST_TEST_MODULE gil/test/extension/numeric/channel_numeric_operations\n#include \"unit_test.hpp\"\n\n#include <boost/gil.hpp>\n#include <boost/gil/extension/numeric/channel_numeric_operations.hpp>\n\n#include <tuple>\n#include <type_traits>\n\n#include \"core/channel/test_fixture.hpp\"\n\nnamespace gil = boost::gil;\nnamespace fixture = boost::gil::test::fixture;\n\nBOOST_AUTO_TEST_SUITE(channel_plus_t)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(plus_integer_same_types, channel_t, fixture::channel_integer_types)\n{\n    gil::channel_plus_t<channel_t, channel_t, channel_t> f;\n    BOOST_TEST(f(0, 0) == channel_t(0));\n    BOOST_TEST(f(100, 27) == channel_t(127));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(plus_integer_mixed_types, channel_t, fixture::channel_integer_types)\n{\n    {\n        using channel1_t = channel_t;\n        using channel2_t = std::uint8_t; // duplicates only one of fixture::channel_integer_types\n        gil::channel_plus_t<channel1_t, channel2_t, channel1_t> f;\n        BOOST_TEST(f(0, 0) == channel1_t(0));\n        BOOST_TEST(f(100, 27) == channel_t(127));\n    }\n    {\n        using channel1_t = std::uint8_t; // duplicates only one of fixture::channel_integer_types\n        using channel2_t = channel_t;\n        gil::channel_plus_t<channel1_t, channel2_t, channel2_t> f;\n        BOOST_TEST(f(0, 0) == channel2_t(0));\n        BOOST_TEST(f(100, 27) == channel_t(127));\n    }\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(plus_integer_signed_types_with_overflow, channel_t, fixture::channel_integer_signed_types)\n{\n    // Signed integer overflow is UB, so just check addition does not yield mathematically\n    // expected value but is constrained by the range of representable values for given type.\n\n    auto const max_value = gil::channel_traits<channel_t>::max_value();\n    gil::channel_plus_t<channel_t, channel_t, channel_t> f;\n    BOOST_TEST(f(max_value, 1) != std::int64_t(max_value) + 1);\n    BOOST_TEST(f(max_value, max_value) != std::int64_t(max_value) + max_value);\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(plus_integer_unsigned_types_with_wraparound, channel_t, fixture::channel_integer_unsigned_types)\n{\n    // The C Standard, 6.2.5, paragraph 9 [ISO/IEC 9899:2011], states:\n    // A computation involving unsigned operands can never overflow, because a result that\n    // cannot be represented by the resulting unsigned integer type is reduced modulo the number\n    // that is one greater than the largest value that can be represented by the resulting type.\n\n    auto const max_value = gil::channel_traits<channel_t>::max_value();\n    auto const min_value = gil::channel_traits<channel_t>::min_value();\n    gil::channel_plus_t<channel_t, channel_t, channel_t> f;\n    BOOST_TEST(f(max_value, 1) == min_value);\n    BOOST_TEST(f(max_value, max_value) == max_value - 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END() // channel_plus_t\n\nBOOST_AUTO_TEST_SUITE(channel_minus_t)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(minus_integer_same_types, channel_t, fixture::channel_integer_types)\n{\n    gil::channel_minus_t<channel_t, channel_t, channel_t> f;\n    BOOST_TEST(f(0, 0) == channel_t(0));\n    BOOST_TEST(f(100, 27) == channel_t(73));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(minus_integer_mixed_types, channel_t, fixture::channel_integer_types)\n{\n    {\n        using channel1_t = channel_t;\n        using channel2_t = std::uint8_t; // duplicates only one of fixture::channel_integer_types\n        gil::channel_minus_t<channel1_t, channel2_t, channel1_t> f;\n        BOOST_TEST(f(0, 0) == channel1_t(0));\n        BOOST_TEST(f(100, 27) == channel_t(73));\n    }\n    {\n        using channel1_t = std::uint8_t; // duplicates only one of fixture::channel_integer_types\n        using channel2_t = channel_t;\n        gil::channel_minus_t<channel1_t, channel2_t, channel2_t> f;\n        BOOST_TEST(f(0, 0) == channel2_t(0));\n        BOOST_TEST(f(100, 27) == channel_t(73));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // channel_minus_t\n\nBOOST_AUTO_TEST_SUITE(channel_multiplies_t)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(multiplies_integer_same_types, channel_t, fixture::channel_integer_types)\n{\n    gil::channel_multiplies_t<channel_t, channel_t, channel_t> f;\n    BOOST_TEST(f(0, 0) == channel_t(0));\n    BOOST_TEST(f(1, 1) == channel_t(1));\n    BOOST_TEST(f(4, 2) == channel_t(8));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(multiplies_integer_mixed_types, channel_t, fixture::channel_integer_types)\n{\n    {\n        using channel1_t = channel_t;\n        using channel2_t = std::uint8_t; // duplicates only one of fixture::channel_integer_types\n        gil::channel_multiplies_t<channel1_t, channel2_t, channel1_t> f;\n        BOOST_TEST(f(0, 0) == channel1_t(0));\n        BOOST_TEST(f(4, 2) == channel_t(8));\n    }\n    {\n        using channel1_t = std::uint8_t; // duplicates only one of fixture::channel_integer_types\n        using channel2_t = channel_t;\n        gil::channel_multiplies_t<channel1_t, channel2_t, channel2_t> f;\n        BOOST_TEST(f(0, 0) == channel2_t(0));\n        BOOST_TEST(f(4, 2) == channel_t(8));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // channel_multiplies_t\n\nBOOST_AUTO_TEST_SUITE(channel_divides_t)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(divides_integer_same_types, channel_t, fixture::channel_integer_types)\n{\n    gil::channel_divides_t<channel_t, channel_t, channel_t> f;\n    BOOST_TEST(f(0, 1) == channel_t(0));\n    BOOST_TEST(f(1, 1) == channel_t(1));\n    BOOST_TEST(f(4, 2) == channel_t(2));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(divides_integer_mixed_types, channel_t, fixture::channel_integer_types)\n{\n    {\n        using channel1_t = channel_t;\n        using channel2_t = std::uint8_t; // duplicates only one of fixture::channel_integer_types\n        gil::channel_divides_t<channel1_t, channel2_t, channel1_t> f;\n        BOOST_TEST(f(0, 1) == channel1_t(0));\n        BOOST_TEST(f(4, 2) == channel_t(2));\n    }\n    {\n        using channel1_t = std::uint8_t; // duplicates only one of fixture::channel_integer_types\n        using channel2_t = channel_t;\n        gil::channel_divides_t<channel1_t, channel2_t, channel2_t> f;\n        BOOST_TEST(f(0, 1) == channel2_t(0));\n        BOOST_TEST(f(4, 2) == channel_t(2));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // channel_divides_t\n\nBOOST_AUTO_TEST_SUITE(channel_plus_scalar_t)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(plus_scalar_integer_same_types, channel_t, fixture::channel_integer_types)\n{\n    gil::channel_plus_scalar_t<channel_t, int, channel_t> f;\n    BOOST_TEST(f(0, 0) == channel_t(0));\n    BOOST_TEST(f(100, 27) == channel_t(127));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(plus_scalar_integer_mixed_types, channel_t, fixture::channel_integer_types)\n{\n    using channel_result_t = std::uint8_t;\n    gil::channel_plus_scalar_t<channel_t, int, channel_result_t> f;\n    BOOST_TEST(f(0, 0) == channel_result_t(0));\n    BOOST_TEST(f(100, 27) == channel_result_t(127));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // channel_plus_scalar_t\n\nBOOST_AUTO_TEST_SUITE(channel_minus_scalar_t)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(minus_scalar_integer_same_types, channel_t, fixture::channel_integer_types)\n{\n    gil::channel_minus_scalar_t<channel_t, int, channel_t> f;\n    BOOST_TEST(f(0, 0) == channel_t(0));\n    BOOST_TEST(f(100, 27) == channel_t(73));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(minus_scalar_integer_mixed_types, channel_t, fixture::channel_integer_types)\n{\n    using channel_result_t = std::uint8_t;\n    gil::channel_minus_scalar_t<channel_t, int, std::uint8_t> f;\n    BOOST_TEST(f(0, 0) == channel_result_t(0));\n    BOOST_TEST(f(100, 27) == channel_result_t(73));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // channel_minus_scalar_t\n\nBOOST_AUTO_TEST_SUITE(channel_multiplies_scalar_t)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(multiplies_scalar_integer_same_types, channel_t, fixture::channel_integer_types)\n{\n    gil::channel_multiplies_scalar_t<channel_t, channel_t, channel_t> f;\n    BOOST_TEST(f(0, 0) == channel_t(0));\n    BOOST_TEST(f(1, 1) == channel_t(1));\n    BOOST_TEST(f(4, 2) == channel_t(8));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(multiplies_scalar_integer_mixed_types, channel_t, fixture::channel_integer_types)\n{\n    using channel_result_t = std::uint8_t;\n    gil::channel_multiplies_scalar_t<channel_t, int, channel_result_t> f;\n    BOOST_TEST(f(0, 0) == channel_result_t(0));\n    BOOST_TEST(f(4, 2) == channel_result_t(8));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // channel_multiplies_scalar_t\n\nBOOST_AUTO_TEST_SUITE(channel_divides_scalar_t)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(divides_scalar_integer_same_types, channel_t, fixture::channel_integer_types)\n{\n    gil::channel_divides_scalar_t<channel_t, channel_t, channel_t> f;\n    BOOST_TEST(f(0, 1) == channel_t(0));\n    BOOST_TEST(f(1, 1) == channel_t(1));\n    BOOST_TEST(f(4, 2) == channel_t(2));\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(divides_scalar_integer_mixed_types, channel_t, fixture::channel_integer_types)\n{\n    using channel_result_t = std::uint8_t; // duplicates only one of fixture::channel_integer_types\n    gil::channel_divides_scalar_t<channel_t, int, channel_result_t> f;\n    BOOST_TEST(f(0, 1) == channel_t(0));\n    BOOST_TEST(f(4, 2) == channel_t(2));\n}\n\nBOOST_AUTO_TEST_SUITE_END() // channel_divides_scalar_t\n\nBOOST_AUTO_TEST_SUITE(channel_halves_t)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(halves_integer_same_types, channel_t, fixture::channel_integer_types)\n{\n    gil::channel_halves_t<channel_t> f;\n    {\n        channel_t c(0);\n        f(c);\n        BOOST_TEST(c == channel_t(0));\n    }\n    {\n        channel_t c(2);\n        f(c);\n        BOOST_TEST(c == channel_t(1));\n    }\n    {\n        channel_t c(4);\n        f(c);\n        BOOST_TEST(c == channel_t(2));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // channel_halves_t\n\nBOOST_AUTO_TEST_SUITE(channel_zeros_t)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(zeros_integer_same_types, channel_t, fixture::channel_integer_types)\n{\n    gil::channel_zeros_t<channel_t> f;\n    {\n        channel_t c(0);\n        f(c);\n        BOOST_TEST(c == channel_t(0));\n    }\n    {\n        channel_t c(2);\n        f(c);\n        BOOST_TEST(c == channel_t(0));\n    }\n    {\n        channel_t c(4);\n        f(c);\n        BOOST_TEST(c == channel_t(0));\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END() // channel_zeros_t\n\nBOOST_AUTO_TEST_SUITE(channel_assigns_t)\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(assigns_integer_same_types, channel_t, fixture::channel_integer_types)\n{\n    gil::channel_assigns_t<channel_t, channel_t> f;\n    {\n        channel_t c1(10);\n        channel_t c2(20);\n        f(c1, c2);\n        BOOST_TEST(c2 == c1);\n    }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END() // channel_assigns_t\n", "meta": {"hexsha": "95100c0d3aa0c3222ffda0f2e47094919e0b5ce1", "size": 10594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/extension/numeric/channel_numeric_operations.cpp", "max_stars_repo_name": "NEDJIMAbelgacem/gil", "max_stars_repo_head_hexsha": "8ea3644825d4b2dcabda6d4ce6281d4882f45c61", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-07T18:50:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T18:50:07.000Z", "max_issues_repo_path": "test/extension/numeric/channel_numeric_operations.cpp", "max_issues_repo_name": "NEDJIMAbelgacem/gil", "max_issues_repo_head_hexsha": "8ea3644825d4b2dcabda6d4ce6281d4882f45c61", "max_issues_repo_licenses": ["BSL-1.0"], "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/extension/numeric/channel_numeric_operations.cpp", "max_forks_repo_name": "NEDJIMAbelgacem/gil", "max_forks_repo_head_hexsha": "8ea3644825d4b2dcabda6d4ce6281d4882f45c61", "max_forks_repo_licenses": ["BSL-1.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.6209150327, "max_line_length": 126, "alphanum_fraction": 0.7206909571, "num_tokens": 2866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6134673634267326}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[intersects_linestring\r\n//` Check if two linestrings intersect each other\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/io/wkt/wkt.hpp>\r\n\r\nint main()\r\n{\r\n    // Calculate the intersects of a cartesian polygon\r\n    typedef boost::geometry::model::d2::point_xy<double> P;\r\n    boost::geometry::model::linestring<P> line1, line2;\r\n\r\n    boost::geometry::read_wkt(\"linestring(1 1,2 2,3 3)\", line1);\r\n    boost::geometry::read_wkt(\"linestring(2 1,1 2,4 0)\", line2);\r\n\r\n    bool b = boost::geometry::intersects(line1, line2);\r\n\r\n    std::cout << \"Intersects: \" << (b ? \"YES\" : \"NO\") << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[intersects_linestring_output\r\n/*`\r\nOutput:\r\n[pre\r\nIntersects: YES\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "0955c34109bb06c298d4015b68bc23d62e846baa", "size": 1192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/intersects_linestring.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/intersects_linestring.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/intersects_linestring.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 25.3617021277, "max_line_length": 80, "alphanum_fraction": 0.6753355705, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650247, "lm_q2_score": 0.7461389817407017, "lm_q1q2_score": 0.6134673573950489}}
{"text": "\n#pragma once\n\n#include \"perceive/foundation.hpp\"\n#include \"perceive/utils/sdbm-hash.hpp\"\n#include \"vector-2.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace perceive\n{\n// --------------------------------------------------------------------- Vector3\n\n#pragma pack(push, 1)\ntemplate<typename T> class Vector3T\n{\n public:\n   using value_type = T;\n\n   T x, y, z;\n\n   constexpr Vector3T()\n       : x(T(0.0))\n       , y(T(0.0))\n       , z(T(0.0))\n   {}\n   constexpr Vector3T(T x_, T y_, T z_)\n       : x(x_)\n       , y(y_)\n       , z(z_)\n   {}\n   constexpr Vector3T(const float p[3])\n   {\n      x = p[0];\n      y = p[1];\n      z = p[2];\n   }\n   constexpr Vector3T(const double p[3])\n   {\n      x = p[0];\n      y = p[1];\n      z = p[2];\n   }\n   constexpr Vector3T(const Vector2T<T>& p, double z_ = 0.0)\n       : x(p.x)\n       , y(p.y)\n       , z(z_)\n   {}\n   // explicit Vector3T(const Eigen::Vector3f& v) : x(v(0)), y(v(1)), z(v(2)) {}\n   // explicit Vector3T(const Eigen::Vector3d& v) : x(v(0)), y(v(1)), z(v(2)) {}\n\n   static Vector3T nan() { return Vector3T(T(NAN), T(NAN), T(NAN)); }\n\n   Vector3T& operator=(const Vector3T& v) = default;\n\n   Vector3T& operator=(const Eigen::Vector3d& v)\n   {\n      for(int i = 0; i < 3; ++i) this->operator[](i) = v(i);\n      return *this;\n   }\n\n   unsigned size() const { return 3; }\n\n   Vector3T& normalise(T epsilon = T(1e-9))\n   {\n      // Don't normalize if we don't have to\n      T mag2 = quadrance();\n      if(std::fabs(mag2 - T(1.0)) > epsilon) {\n         T mag_inv = T(1.0) / std::sqrt(mag2);\n         x *= mag_inv;\n         y *= mag_inv;\n         z *= mag_inv;\n      }\n      return *this;\n   }\n\n   Vector3T& normalise_line(T epsilon = T(1e-9))\n   {\n      T mag2 = x * x + y * y;\n      if(std::fabs(mag2 - T(1.0)) > epsilon and (mag2 > T(1e-20)))\n         *this *= T(1.0) / std::sqrt(mag2);\n      return *this;\n   }\n\n   Vector3T& normalise_point(T epsilon = T(1e-9))\n   {\n      if(std::fabs(z - T(1.0)) > epsilon) *this *= T(1.0) / z;\n      return *this;\n   }\n\n   Vector3T normalised(T epsilon = T(1e-9)) const\n   {\n      Vector3T res = *this;\n      res.normalise(epsilon);\n      return res;\n   }\n   Vector3T normalised_line(T epsilon = T(1e-9)) const\n   {\n      Vector3T res = *this;\n      res.normalise_line(epsilon);\n      return res;\n   }\n   Vector3T normalised_point(T epsilon = T(1e-9)) const\n   {\n      Vector3T res = *this;\n      res.normalise_point(epsilon);\n      return res;\n   }\n\n   Vector3T& normalize(T ep = T(1e-9)) { return normalise(ep); }\n   Vector3T& normalize_line(T ep = T(1e-9)) { return normalise_line(ep); }\n   Vector3T& normalize_point(T ep = T(1e-9)) { return normalise_point(ep); }\n\n   Vector3T normalized(T epsilon = T(1e-9)) const\n   {\n      return normalised(epsilon);\n   }\n   Vector3T normalized_line(T ep = T(1e-9)) const\n   {\n      return normalised_line(ep);\n   }\n   Vector3T normalized_point(T ep = T(1e-9)) const\n   {\n      return normalised_point(ep);\n   }\n\n   T quadrance() const { return x * x + y * y + z * z; }\n   inline T norm() const;\n   T dot(const Vector3T& o) const { return x * o.x + y * o.y + z * o.z; }\n   T distance(const Vector3T& rhs) const { return (*this - rhs).norm(); }\n   Vector3T cross(const Vector3T& v) const\n   {\n      Vector3T o;\n      o.x = y * v.z - z * v.y;\n      o.y = z * v.x - x * v.z;\n      o.z = x * v.y - y * v.x;\n      return o;\n   }\n   Vector3T left_cross(const Vector3T& rhs) const { return rhs.cross(*this); }\n\n   Vector3T& set_to(const T& a, const T& b, const T& c)\n   {\n      x = a;\n      y = b;\n      z = c;\n      return *this;\n   }\n   Vector3T& set_to(T a[3])\n   {\n      set_to(a[0], a[1], a[2]);\n      return *this;\n   }\n\n   T* copy_to(T a[3]) const\n   {\n      a[0] = x;\n      a[1] = y;\n      a[2] = z;\n      return a;\n   }\n\n   T* ptr()\n   {\n      assert(&x == reinterpret_cast<const T*>(this) + 0);\n      assert(&y == reinterpret_cast<const T*>(this) + 1);\n      assert(&z == reinterpret_cast<const T*>(this) + 2);\n      return &x;\n   }\n   const T* ptr() const { return const_cast<Vector3T<T>*>(this)->ptr(); }\n   T& operator[](int idx)\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 3);\n#endif\n      return ptr()[idx];\n   }\n\n   const T& operator[](int idx) const\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 3);\n#endif\n      return ptr()[idx];\n   }\n\n   T& operator()(int idx)\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 3);\n#endif\n      return ptr()[idx];\n   }\n\n   const T& operator()(int idx) const\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 3);\n#endif\n      return ptr()[idx];\n   }\n\n   Vector3T round() const\n   {\n      return Vector3T(\n          floor(x + T(0.499)), floor(y + T(0.499)), floor(z + T(0.499)));\n   }\n\n   Vector3T& operator*=(T scalar)\n   {\n      x *= scalar;\n      y *= scalar;\n      z *= scalar;\n      return *this;\n   }\n   Vector3T& operator/=(T scalar)\n   {\n      x /= scalar;\n      y /= scalar;\n      z /= scalar;\n      return *this;\n   }\n   Vector3T operator*(T scalar) const\n   {\n      Vector3T res(*this);\n      res *= scalar;\n      return res;\n   }\n   Vector3T operator/(T scalar) const\n   {\n      Vector3T res(*this);\n      res /= scalar;\n      return res;\n   }\n\n   Vector3T& operator+=(const Vector3T& rhs)\n   {\n      x += rhs.x;\n      y += rhs.y;\n      z += rhs.z;\n      return *this;\n   }\n   Vector3T& operator-=(const Vector3T& rhs)\n   {\n      x -= rhs.x;\n      y -= rhs.y;\n      z -= rhs.z;\n      return *this;\n   }\n   Vector3T operator+(const Vector3T& rhs) const\n   {\n      Vector3T res(*this);\n      res += rhs;\n      return res;\n   }\n   Vector3T operator-(const Vector3T& rhs) const\n   {\n      Vector3T res(*this);\n      res -= rhs;\n      return res;\n   }\n   Vector3T operator-() const { return Vector3T(-x, -y, -z); }\n\n   bool operator==(const Vector3T& rhs) const\n   {\n      return x == rhs.x && y == rhs.y && z == rhs.z;\n   }\n   bool operator!=(const Vector3T& rhs) const { return !(*this == rhs); }\n\n   bool operator<(const Vector3T& o) const noexcept\n   {\n      return (x != o.x) ? (x < o.x) : (y != o.y) ? (y < o.y) : (z < o.z);\n   }\n\n   bool operator>(const Vector3T& o) const noexcept\n   {\n      return !(*this == o) and !(*this < o);\n   }\n\n   bool operator<=(const Vector3T& o) const noexcept\n   {\n      return (*this == o) or (*this < o);\n   }\n\n   bool operator>=(const Vector3T& o) const noexcept { return !(*this < o); }\n\n   bool has_nan() const { return x != x || y != y || z != z; }\n   bool is_nan() const\n   {\n      return std::isnan(x) || std::isnan(y) || std::isnan(z);\n   }\n   bool is_finite() const\n   {\n      return std::isfinite(x) && std::isfinite(y) && std::isfinite(z);\n   }\n   bool is_unit_vector(T epsilon = T(1e-9)) const\n   {\n      return is_finite() && fabs(quadrance() - 1.0) < epsilon;\n   }\n\n   inline friend bool isfinite(const Vector3T& o) noexcept\n   {\n      return o.is_finite();\n   }\n\n   std::string to_string(const char* fmt = nullptr) const\n   {\n      if(fmt == nullptr) {\n         if constexpr(std::is_floating_point<T>::value) {\n            fmt = \"[{:7.5f}, {:7.5f}, {:7.5f}]\";\n         } else {\n            fmt = \"[{}, {}, {}]\";\n         }\n      }\n      return format(fmt, x, y, z);\n   }\n   std::string to_str() const { return format(\"[{}, {}, {}]\", x, y, z); }\n\n   void print(const char* msg = NULL, bool newline = true) const\n   {\n      printf(\"%s%s%s%s\",\n             (msg == NULL ? \"\" : msg),\n             (msg == NULL ? \"\" : \" \"),\n             to_string().c_str(),\n             (newline ? \"\\n\" : \"\"));\n      fflush(stdout);\n   }\n\n   // Treat as spherical\n   T& inclination() { return x; }\n   T& azimuth() { return y; }\n   T& r() { return z; }\n   const T& inclination() const { return x; }\n   const T& azimuth() const { return y; }\n   const T& r() const { return z; }\n\n   // Homogenous point\n   bool pt_at_infinity(T epsilon = T(1e-9)) const { return fabs(z) < epsilon; }\n\n   size_t hash() const { return sdbm_hash(ptr(), sizeof(T) * size()); }\n\n   friend std::string str(const Vector3T<T>& o) noexcept\n   {\n      return o.to_string();\n   }\n};\n#pragma pack(pop)\n\ntemplate<typename T> Vector3T<T> operator*(float a, const Vector3T<T>& v)\n{\n   return v * a;\n}\ntemplate<typename T> Vector3T<T> operator/(float a, const Vector3T<T>& v)\n{\n   return v / a;\n}\ntemplate<typename T> Vector3T<T> operator*(double a, const Vector3T<T>& v)\n{\n   return v * a;\n}\ntemplate<typename T> Vector3T<T> operator/(double a, const Vector3T<T>& v)\n{\n   return v / a;\n}\n\n// String shim\ntemplate<typename T> std::string str(const Vector3T<T>& v)\n{\n   return v.to_string();\n}\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& out, const Vector3T<T>& v)\n{\n   out << v.to_string();\n   return out;\n}\n\ntemplate<> inline float Vector3T<float>::norm() const\n{\n   return sqrtf(quadrance());\n}\ntemplate<> inline double Vector3T<double>::norm() const\n{\n   return sqrt(quadrance());\n}\n} // namespace perceive\n", "meta": {"hexsha": "6ed5fd7a81012c8d94cea83d9523f3ae1d3ca8fb", "size": 8834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector-3.hpp", "max_stars_repo_name": "prcvlabs/multiview", "max_stars_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T23:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:43:32.000Z", "max_issues_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector-3.hpp", "max_issues_repo_name": "prcvlabs/multiview", "max_issues_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:33:02.000Z", "max_forks_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector-3.hpp", "max_forks_repo_name": "prcvlabs/multiview", "max_forks_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-26T03:14:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T06:42:52.000Z", "avg_line_length": 22.8860103627, "max_line_length": 80, "alphanum_fraction": 0.530110935, "num_tokens": 2775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6134609427257737}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2012 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file richardsonextrapolation.hpp\n*/\n\n#ifndef quantlib_richardson_extrapolation_hpp\n#define quantlib_richardson_extrapolation_hpp\n\n#include <ql/types.hpp>\n#include <ql/utilities/null.hpp>\n#include <boost/function.hpp>\n\nnamespace QuantLib {\n\n    //! Richardson Extrapolation\n    /*! Richardson Extrapolation is a sequence acceleration technique for\n      \\f[\n          f(\\Delta h) = f_0 + \\alpha\\cdot (\\Delta h)^n + O((\\Delta h)^{n+1})\n      \\f]\n     */\n\n    /*! References:\n        http://en.wikipedia.org/wiki/Richardson_extrapolation\n     */\n\n    class RichardsonExtrapolation {\n      public:\n        /*! Richardon Extrapolation\n           \\param f function to be extrapolated to delta_h -> 0\n           \\param delta_h step size\n           \\param n if known, n is the order of convergence\n         */\n        RichardsonExtrapolation(const boost::function<Real (Real)>& f,\n                                Real delta_h, Real n = Null<Real>());\n\n\n        /*! Extrapolation for known order of convergence\n            \\param t scaling factor for the step size\n        */\n        Real operator()(Real t=2.0) const;\n\n        /*! Extrapolation for unknown order of convergence\n            \\param t first scaling factor for the step size\n            \\param s second scaling factor for the step size\n        */\n        Real operator()(Real t, Real s) const;\n\n      private:\n        const Real delta_h_;\n        const Real fdelta_h_;\n        const Real n_;\n        const boost::function<Real (Real)> f_;\n    };\n}\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2012 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file richardsonextrapolation.cpp\n*/\n\n#include <ql/errors.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n\n#include <cmath>\n\nnamespace QuantLib {\n    namespace {\n        class RichardsonEqn {\n          public:\n            RichardsonEqn(Real fh, Real ft, Real fs, Real t, Real s)\n            : fdelta_h_(fh), ft_(ft), fs_(fs), t_(t), s_(s) { }\n\n            Real operator()(Real k) const {\n                return      ft_ + (ft_-fdelta_h_)/(std::pow(t_, k)-1.0)\n                        - ( fs_ + (fs_-fdelta_h_)/(std::pow(s_, k)-1.0));\n            }\n          private:\n            const Real fdelta_h_, ft_, fs_, t_, s_;\n        };\n\n    }\n\n    inline RichardsonExtrapolation::RichardsonExtrapolation(\n        const boost::function<Real (Real)>& f, Real delta_h, Real n)\n    : delta_h_(delta_h),\n      fdelta_h_(f(delta_h)),\n      n_(n),\n      f_(f) {\n    }\n\n\n    inline Real RichardsonExtrapolation::operator()(Real t) const {\n\n        QL_REQUIRE(t > 1, \"scaling factor must be greater than 1\");\n        QL_REQUIRE(n_ != Null<Real>(), \"order of convergence must be known\");\n\n        const Real tk = std::pow(t, n_);\n\n        return (tk*f_(delta_h_/t)-fdelta_h_)/(tk-1.0);\n    }\n\n    inline Real RichardsonExtrapolation::operator()(Real t, Real s)\n    const {\n        QL_REQUIRE(t > 1 && s > 1, \"scaling factors must be greater than 1\");\n        QL_REQUIRE(t > s, \"t must be greater than s\");\n\n        const Real ft = f_(delta_h_/t);\n        const Real fs = f_(delta_h_/s);\n\n        const Real k = Brent().solve(RichardsonEqn(fdelta_h_, ft, fs, t, s),\n                                     1e-8, 0.05, 10);\n\n        const Real ts = std::pow(s, k);\n\n        return (ts*fs-fdelta_h_)/(ts-1.0);\n    }\n}\n\n\n#endif", "meta": {"hexsha": "7fbfcb440ba373f22cc62614243c1199af163dbc", "size": 4817, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/richardsonextrapolation.hpp", "max_stars_repo_name": "markxio/Quantuccia", "max_stars_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T14:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:00:52.000Z", "max_issues_repo_path": "ql/math/richardsonextrapolation.hpp", "max_issues_repo_name": "markxio/Quantuccia", "max_issues_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-04-02T14:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T05:31:12.000Z", "max_forks_repo_path": "ql/math/richardsonextrapolation.hpp", "max_forks_repo_name": "markxio/Quantuccia", "max_forks_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T05:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:30:20.000Z", "avg_line_length": 31.2792207792, "max_line_length": 79, "alphanum_fraction": 0.6352501557, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6134609274640338}}
{"text": "#pragma once\n\n// #include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include \"SU2meshparser.hpp\"\n\nnamespace heatdiff\n{\nclass HeatDiffusion2d\n{\npublic:\n    HeatDiffusion2d();\n    ~HeatDiffusion2d();\n\n    void SetMeshConfiguration(std::string meshfilename);\n    void GenerateGrid();\n    void SetFlowConfig(double volumetric_source, double thermal_cond,\n                       double thickness);\n    void SetBoundaryConditions(std::string tag, std::string bc_type,\n                               double temperature);\n    void SetInitialConditions(double init_temperature);\n    void Solve();\n    void WriteResultsToVtk(std::string vtkfilename);\n\n    // For debug\n    void PrintDebug();\n\nprivate:\n    std::string meshfilename_;\n    std::vector<CellQuad4> cells_;\n    std::vector<Node2d> nodes_;\n\n    // Calculate initial cell values\n    void CalcInitialValues();\n    // Cinstruct matrices\n    void ConstructMatrices();\n    void UpdateFaceValues();\n    void CalcNodalValues();\n\n    double thickness_;\n\n    // For Simultaneous Linear Equation\n    //! Coefficient matrix\n    Eigen::SparseMatrix<double> A;\n    //! Temperature vector\n    Eigen::VectorXd T;\n    //! Source vector\n    Eigen::VectorXd B;\n};\n}  // namespace heatdiff", "meta": {"hexsha": "883229826552a8ad491c6ca48806a2b97e2b5dcc", "size": 1216, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "03_heatDiffuion2d/heatdiffusion2d/inc/HeatDiffusion2d.hpp", "max_stars_repo_name": "nishiys/CFDbasics", "max_stars_repo_head_hexsha": "638372956e31f8392f20b0d2027762cc4f9ef10b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-19T10:17:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-19T10:17:17.000Z", "max_issues_repo_path": "03_heatDiffuion2d/heatdiffusion2d/inc/HeatDiffusion2d.hpp", "max_issues_repo_name": "nishiys/CFDbasics", "max_issues_repo_head_hexsha": "638372956e31f8392f20b0d2027762cc4f9ef10b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "03_heatDiffuion2d/heatdiffusion2d/inc/HeatDiffusion2d.hpp", "max_forks_repo_name": "nishiys/CFDbasics", "max_forks_repo_head_hexsha": "638372956e31f8392f20b0d2027762cc4f9ef10b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-19T10:22:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-19T10:22:36.000Z", "avg_line_length": 23.8431372549, "max_line_length": 69, "alphanum_fraction": 0.6743421053, "num_tokens": 268, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7217432062975978, "lm_q1q2_score": 0.6134609270654587}}
{"text": "//\n// Created by mmath on 7/7/17.\n//\n\n#include <cmath>\n#include <deque>\n#include <algorithm>\n#include <functional>\n#include <tuple>\n#include <iostream>\n\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n#include \"Utilities.hpp\"\n#include \"FunctionApprox.hpp\"\n\nnamespace pyscan {\n\n    std::ostream& operator<<(std::ostream& object, Vec3 const& v1) {\n        object << \"(\" << v1[0] << \", \" << v1[1] << \", \" << v1[2] << \")\";\n        return object;\n    }\n\n\n    bool almostEqualRelative(double A, double B, double maxRelDiff) {\n        // Calculate the difference.\n        double diff = fabs(A - B);\n        A = fabs(A);\n        B = fabs(B);\n        // Find the largest\n        double largest = (B > A) ? B : A;\n        return diff <= largest * maxRelDiff;\n    }\n\n    bool lineIntersection(Vec2 const& dir1, double d1, Vec2 const& dir2, double d2, Vec2& v_ext) {\n        /*\n         * Need to test two cases.\n         *\n         */\n        if (almostEqualRelative(dir1[0] * dir2[1], dir1[1] * dir2[0], 8 * std::numeric_limits<double>::epsilon())) {\n            return false;\n        }\n\n        double denom = 1 / (dir1[0] * dir2[1] - dir1[1] * dir2[0]);\n\n        v_ext[0] = (dir2[1] * d1 - dir1[1] * d2) * denom;\n        v_ext[1] = (dir1[0] * d2 - dir2[0] * d1) * denom;\n        return true;\n    }\n\n\n    double det3(Vec3 const& dir1, Vec3 const& dir2, Vec3 const& dir3) {\n        return dir1[0] * util::det2(dir2[1], dir3[1], dir2[2], dir3[2])\n               - dir1[1] * util::det2(dir2[0], dir3[0], dir2[2], dir3[2])\n               + dir1[2] * util::det2(dir2[0], dir3[0], dir2[1], dir3[1]);\n    }\n\n    using namespace boost::numeric::ublas;\n\n    matrix<double> inverse3x3(matrix<double> const& m) {\n        double det = m(0, 0) * (m(1, 1) * m(2, 2) - m(2, 1) * m(1, 2)) -\n                     m(0, 1) * (m(1, 0) * m(2, 2) - m(1, 2) * m(2, 0)) +\n                     m(0, 2) * (m(1, 0) * m(2, 1) - m(1, 1) * m(2, 0));\n\n        double invdet = 1 / det;\n\n        matrix<double> minv(3, 3);\n        minv(0, 0) = (m(1, 1) * m(2, 2) - m(2, 1) * m(1, 2)) * invdet;\n        minv(0, 1) = (m(0, 2) * m(2, 1) - m(0, 1) * m(2, 2)) * invdet;\n        minv(0, 2) = (m(0, 1) * m(1, 2) - m(0, 2) * m(1, 1)) * invdet;\n        minv(1, 0) = (m(1, 2) * m(2, 0) - m(1, 0) * m(2, 2)) * invdet;\n        minv(1, 1) = (m(0, 0) * m(2, 2) - m(0, 2) * m(2, 0)) * invdet;\n        minv(1, 2) = (m(1, 0) * m(0, 2) - m(0, 0) * m(1, 2)) * invdet;\n        minv(2, 0) = (m(1, 0) * m(2, 1) - m(2, 0) * m(1, 1)) * invdet;\n        minv(2, 1) = (m(2, 0) * m(0, 1) - m(0, 0) * m(2, 1)) * invdet;\n        minv(2, 2) = (m(0, 0) * m(1, 1) - m(1, 0) * m(0, 1)) * invdet;\n\n        return minv;\n    }\n\n    bool lineIntersection(Vec3 const& dir1, Vec3 const& p1,\n                          Vec3 const& dir2, Vec3 const& p2,\n                          Vec3 const& dir3, Vec3 const& p3,\n                          Vec3& v_ext) {\n\n        double d1 = dot(dir1, p1);\n        double d2 = dot(dir2, p2);\n        double d3 = dot(dir3, p3);\n        //equation will be of the form.\n        // a1 x + b1 y + c1 z = d1\n        // a2 x + b2 y + c2 z = d2\n        // a3 x + b3 y + c3 z = d3\n\n        // Compute the rank of the system and see if it is singular\n        double dval = det3(dir1, dir2, dir3);\n        if (util::aeq(fabs(dval), 0)) {\n            return false;\n        }\n\n        matrix<double> A(3, 3);\n\n        A(0, 0) = dir1[0], A(0, 1) = dir1[1], A(0, 2) = dir1[2],\n        A(1, 0) = dir2[0], A(1, 1) = dir2[1], A(1, 2) = dir2[2],\n        A(2, 0) = dir3[0], A(2, 1) = dir3[1], A(2, 2) = dir3[2];\n\n\n        vector<double> v(3);\n        v[0] = d1, v[1] = d2, v[2] = d3;\n        auto m = inverse3x3(A);\n\n        v_ext[0] = m(0, 0) * v[0] + m(0, 1) * v[1] + m(0, 2) * v[2];\n        v_ext[1] = m(1, 0) * v[0] + m(1, 1) * v[1] + m(1, 2) * v[2];\n        v_ext[2] = m(2, 0) * v[0] + m(2, 1) * v[1] + m(2, 2) * v[2];\n        return true;\n    }\n\n\n    bool inside(Vec2 const& pos, double alpha, double rho) {\n      return (alpha <= pos[0]) && (pos[0] <= 1 - alpha) &&\n        (rho <= pos[1]) && (pos[1] <= 1 - rho);\n    }\n\n    bool inRange(double a, double b) {\n      return (b <= a) && (a <= 1 - b);\n    }\n\n    void lineIntersectionI(Vec2 const& dir1, double d1, Vec2 const& dir2, double d2, Vec2& v_ext) {\n      /*\n        If there is numerical instability then we project to infinity.\n      */\n      if (!lineIntersection(dir1, d1, dir2, d2, v_ext)) {\n        v_ext[0] = std::numeric_limits<double>::infinity();\n        v_ext[1] = std::numeric_limits<double>::infinity();\n      }\n    }\n\n\n\n    Vec2 projectToBoundary(Vec2 const& pos, Vec2 const& dir, double alpha, double rho) {\n      /*\n        Takes the pos and projects it to the rectangle defined by\n        [rho, 1 rho] x [alpha, 1 - alpha]\n      */\n      if (inside(pos, alpha, rho))\n        return pos;\n\n      Vec2 rho_b, rho_t, alpha_l, alpha_r;\n      double d1 = dot(pos, dir);\n      lineIntersectionI(dir, d1, Vec2{0.0, 1.0}, rho, rho_b);\n      lineIntersectionI(dir, d1, Vec2{0.0, 1.0}, 1 - rho, rho_t);\n      lineIntersectionI(dir, d1, Vec2{1.0, 0.0}, alpha, alpha_l);\n      lineIntersectionI(dir, d1, Vec2{1.0, 0.0}, 1 - alpha, alpha_r);\n      if (pos[1] < rho && inRange(rho_b[0], alpha))\n          return rho_b;\n      else if (1 - rho < pos[1] && inRange(rho_t[0], alpha))\n        return rho_t;\n      else if (pos[0] < alpha && inRange(alpha_l[1], rho))\n        return alpha_l;\n      else if (1 - alpha < pos[0] && inRange(alpha_r[1], rho))\n        return alpha_r;\n      // lives in the corner and no good projections\n      else if (pos[0] < alpha) {\n        if (pos[1] < rho)\n          return {alpha, rho};\n        else\n          return {alpha, 1 - rho};\n      } else {\n        if (pos[1] < rho)\n          return {1 - alpha, rho};\n        else\n          return {1 - alpha, 1 - rho};\n      }\n    }\n\n\n\n    double approximateHull(double eps,\n                           Vec2 const& cc, Vec2 const& cl,\n                           std::function<double(Vec2)> phi, //function to maximize\n                           std::function<Vec2(Vec2)> lineMaxExt) {\n\n\n        auto lineMaxF = [&] (Vec2 v1) {\n          auto pt = lineMaxExt(v1);\n          //std::cout << \"line_max = \" << pt << std::endl;\n          return pt; // projectToBoundary(pt, v1, alpha, rho);\n        };\n\n        auto avg = [&] (Vec2 const& v1, Vec2 const& v2) {\n            Vec2 v_out = v1 + v2;\n            Vec2 tmp;\n            double norm = 1.0 / sqrt(v_out[0] * v_out[0] + v_out[1] * v_out[1]);\n            tmp[0] = v_out[0] * norm;\n            tmp[1] = v_out[1] * norm;\n            return tmp;\n        };\n\n        struct Frame {\n            Vec2 d_cc, d_cl, p_cc, p_cl;\n            Frame(Vec2 const& di, Vec2 const& dj, Vec2 const& cc, Vec2 const& cl) :\n                    d_cc(di), d_cl(dj), p_cc(cc), p_cl(cl) {}\n        };\n        double maxRValue = 0;\n\n        std::deque<Frame> frameStack;\n        // TODO double check debug to see if there is an issue with an infinite singularity here. Might need to change start.\n        //This start needs to be fixed. Compute the mi, bi, and everything explicitly\n        frameStack.emplace_back(cc, cl, lineMaxF(cc), lineMaxF(cl));\n\n//#ifndef NDEBUG\n//        size_t iter_count = 0;\n//#endif\n        while(!frameStack.empty()) {\n            Frame lf = frameStack.front();\n\n//#ifndef NDEBUG\n//            std::cout << \"considering triangle\" << std::endl;\n//            std::cout << lf.d_cc << \" \" << lf.p_cc << \" \" << lf.d_cl << \" \" << lf.p_cl << std::endl;\n//#endif\n            frameStack.pop_front();\n            double di = dot(lf.d_cc, lf.p_cc);\n            double dj = dot(lf.d_cl, lf.p_cl);\n            double vi = phi(lf.p_cc);\n            double vj = phi(lf.p_cl);\n            maxRValue = std::max({vi, vj, maxRValue});\n            Vec2 p_ext;\n\n            if (lineIntersection(lf.d_cc, di, lf.d_cl, dj, p_ext)) {\n                double vw = phi(p_ext);\n//#ifndef NDEBUG\n//                std::cout << lf.p_cc << \" \" << vi << std::endl;\n//                std::cout << p_ext << \" \" << vw << std::endl;\n//                std::cout << lf.p_cl << \" \" << vj << std::endl;\n//#endif\n                //dist(lf)\n                if (vw - maxRValue > eps) {\n\n                    //This triangle is worth evaluating\n//#ifndef NDEBUG\n//                    std::cout << \"evaluating triangle\" << std::endl;\n//#endif\n                    Vec2 m_vec = avg(lf.d_cc, lf.d_cl);\n                    auto line_max = lineMaxF(m_vec);\n\n                    frameStack.emplace_back(lf.d_cc, m_vec, lf.p_cc, line_max);\n                    frameStack.emplace_back(m_vec, lf.d_cl, line_max, lf.p_cl);\n                }\n            }\n//#ifndef NDEBUG\n//            iter_count += 1;\n//            std::cout << std::endl;\n//#endif\n        }\n//#ifndef NDEBUG\n//        std::cout << \"maxRValue = \" << maxRValue << std::endl;\n//        std::cout << iter_count << std::endl;\n//#endif\n        return maxRValue;\n    }\n\n    double approximateHull(double eps,\n                           std::function<double(Vec2)> phi, //function to maximize\n                           std::function<Vec2(Vec2)> lineMaxF) {\n        return std::max(approximateHull(eps, Vec2{1, 0}, Vec2{0, -1}, phi, lineMaxF),\n                        approximateHull(eps, Vec2{-1, 0}, Vec2{0, 1}, phi, lineMaxF));\n    }\n\n    /*\n     * Computes the height of a triangle that has corner points p1, p2, and pt where pt is the top corner.\n     * p1, p2 -- corners of the base of the triangle\n     * pt -- top corner of the triangle\n     * return -- the height of the triangle as a double.\n     */\n    double height(Vec2 const& p1, Vec2 const& p2, Vec2 const& pt) {\n        double a = sqrt((p1[0] - p2[0]) *(p1[0] - p2[0]) + (p1[1] - p2[1]) *(p1[1] - p2[1]));\n        double b = sqrt((p1[0] - pt[0]) *(p1[0] - pt[0]) + (p1[1] - pt[1]) *(p1[1] - pt[1]));\n        double c = sqrt((p2[0] - pt[0]) *(p2[0] - pt[0]) + (p2[1] - pt[1]) *(p2[1] - pt[1]));\n        double s = (a + b + c)/ 2;\n        return 2 * sqrt(s * (s - a) * (s - b) * (s - c)) / a;\n    }\n\n    std::vector<Vec2> eps_core_set(double eps,\n                                   Vec2 const& cc, Vec2 const& cl,\n                                   std::function<Vec2(Vec2)> lineMaxF) {\n\n            auto avg = [&] (Vec2 const& v1, Vec2 const& v2) {\n                Vec2 v_out = v1 + v2;\n                Vec2 tmp;\n                double norm = 1.0 / sqrt(v_out[0] * v_out[0] + v_out[1] * v_out[1]);\n                tmp[0] = v_out[0] * norm;\n                tmp[1] = v_out[1] * norm;\n                return tmp;\n            };\n\n            struct Frame {\n                Vec2 d_cc, d_cl, p_cc, p_cl;\n                Frame(Vec2 const& di, Vec2 const& dj, Vec2 const& cc, Vec2 const& cl) :\n                        d_cc(di), d_cl(dj), p_cc(cc), p_cl(cl) {}\n            };\n            auto pcc = lineMaxF(cc), pcl = lineMaxF(cl);\n            std::vector<Vec2> pts{ pcc, pcl };\n            std::deque<Frame> frameStack;\n            frameStack.emplace_back(cc, cl, pcc, pcl);\n            while(!frameStack.empty()) {\n                Frame lf = frameStack.front();\n                frameStack.pop_front();\n                double di = dot(lf.d_cc, lf.p_cc);\n                double dj = dot(lf.d_cl, lf.p_cl);\n\n                Vec2 p_ext;\n\n                if (lineIntersection(lf.d_cc, di, lf.d_cl, dj, p_ext)) {\n                    if (height(lf.p_cc, lf.p_cl, p_ext) > eps) {\n\n                        Vec2 m_vec = avg(lf.d_cc, lf.d_cl);\n                        auto line_max = lineMaxF(m_vec);\n                        pts.push_back(line_max);\n                        frameStack.emplace_back(lf.d_cc, m_vec, lf.p_cc, line_max);\n                        frameStack.emplace_back(m_vec, lf.d_cl, line_max, lf.p_cl);\n                    }\n                }\n            }\n            return pts;\n    }\n\n    std::vector<Vec2> eps_core_set(double eps,\n                        std::function<Vec2(Vec2)> lineMaxF) {\n        auto core_set1 = eps_core_set(eps, Vec2{1, 0}, Vec2{0, -1},  lineMaxF)\n            ,core_set2 = eps_core_set(eps, Vec2{0, 1}, Vec2{1, 0}, lineMaxF)\n            ,core_set3 = eps_core_set(eps, Vec2{-1, 0}, Vec2{0, 1}, lineMaxF)\n            ,core_set4 = eps_core_set(eps, Vec2{0, -1}, Vec2{-1, 0}, lineMaxF);\n        core_set1.insert(core_set1.end(), core_set2.begin(), core_set2.end());\n        core_set1.insert(core_set1.end(), core_set3.begin(), core_set3.end());\n        core_set1.insert(core_set1.end(), core_set4.begin(), core_set4.end());\n        return core_set1;\n    }\n\n\n    point_list_t approx_hull(point_list_t const &pts, double eps) {\n        auto max_f = [&] (Vec2 direction) {\n            double max_dir = -std::numeric_limits<double>::infinity();\n            pt2_t curr_pt(0.0, 0.0, 0.0);\n            for (auto& pt : pts) {\n                double curr_dir = direction[0] * pt(0) + direction[1] * pt(1);\n                if (max_dir < curr_dir) {\n                    max_dir = curr_dir;\n                    curr_pt = pt;\n                }\n            }\n            return Vec2{curr_pt(0), curr_pt(1)};\n        };\n        std::vector<pyscan::Point<>> core_set_pts;\n        {\n            auto vecs = eps_core_set(eps, max_f);\n            for (auto &v :vecs) {\n                core_set_pts.emplace_back(v[0], v[1], 1.0);\n            }\n        }\n        remove_duplicates(core_set_pts);\n        return core_set_pts;\n    }\n\n  }\n", "meta": {"hexsha": "c49672a5a2b4d1486edc6b4176c36f94e4537173", "size": 13401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/FunctionApprox.cpp", "max_stars_repo_name": "michaelmathen/pyscan", "max_stars_repo_head_hexsha": "f0eb78d3e9a6a2048a5c8166f3be5f453b2bea22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-22T20:50:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T21:13:50.000Z", "max_issues_repo_path": "src/FunctionApprox.cpp", "max_issues_repo_name": "AprilXiaoyanLiu/pyscan", "max_issues_repo_head_hexsha": "f0eb78d3e9a6a2048a5c8166f3be5f453b2bea22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FunctionApprox.cpp", "max_forks_repo_name": "AprilXiaoyanLiu/pyscan", "max_forks_repo_head_hexsha": "f0eb78d3e9a6a2048a5c8166f3be5f453b2bea22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-06-26T21:13:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-26T22:03:46.000Z", "avg_line_length": 36.6147540984, "max_line_length": 125, "alphanum_fraction": 0.4827997911, "num_tokens": 4375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6134609192353012}}
{"text": "#include \"TrICP.h\"\n\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\nusing namespace navtypes;\n\nstruct PointPair // NOLINT(cppcoreguidelines-pro-type-member-init)\n{\n\tpoint_t mapPoint;\n\tpoint_t samplePoint;\n\tdouble dist;\n};\n\nvoid heapify(PointPair arr[], int len, int i) {\n\tint smallest = i;\n\tint l = 2 * i + 1;\n\tint r = 2 * i + 2;\n\tif (l < len && arr[l].dist < arr[smallest].dist) {\n\t\tsmallest = l;\n\t}\n\tif (r < len && arr[r].dist < arr[smallest].dist) {\n\t\tsmallest = r;\n\t}\n\n\tif (smallest != i) {\n\t\tstd::swap(arr[i], arr[smallest]);\n\t\theapify(arr, len, smallest);\n\t}\n}\n\n// get some of the point pairs with the least distance using heapsort\nstd::vector<PointPair> getMinN(PointPair* arr, int len, int minNum) {\n\tfor (int i = len / 2 - 1; i >= 0; i--) {\n\t\theapify(arr, len, i);\n\t}\n\n\tstd::vector<PointPair> ret;\n\tfor (int i = len - 1; i > len - 1 - minNum; i--) {\n\t\tret.push_back(arr[0]);\n\t\tstd::swap(arr[0], arr[i]);\n\t\theapify(arr, i, 0);\n\t}\n\n\treturn ret;\n}\n\ntransform_t computeTransformation(const std::vector<PointPair>& pairs) {\n\t/*\n\t * We need to find a rigid transformation that maps points in the sample to points in\n\t * the map. This transformation is not a regular affine, as only rotations and translations\n\t * are permitted.\n\t *\n\t * We can do this with the Kabsch algorithm.\n\t * https://en.wikipedia.org/wiki/Kabsch_algorithm\n\t */\n\tEigen::Vector2d mapCentroid = Eigen::Vector2d::Zero();\n\tEigen::Vector2d sampleCentroid = Eigen::Vector2d::Zero();\n\n\tfor (const PointPair& pair : pairs) {\n\t\tmapCentroid += pair.mapPoint.topRows<2>();\n\t\tsampleCentroid += pair.samplePoint.topRows<2>();\n\t}\n\n\tmapCentroid /= pairs.size();\n\tsampleCentroid /= pairs.size();\n\n\tint size = pairs.size();\n\tEigen::Matrix<double, Eigen::Dynamic, 2> P(size, 2);\n\tEigen::Matrix<double, Eigen::Dynamic, 2> Q(size, 2);\n\tfor (int i = 0; i < size; i++) {\n\t\tP.row(i) = pairs[i].samplePoint.topRows<2>() - sampleCentroid;\n\t\tQ.row(i) = pairs[i].mapPoint.topRows<2>() - mapCentroid;\n\t}\n\n\tEigen::Matrix2d H = P.transpose() * Q;\n\n\t// computing SVD for square matrices, so no QR preconditioner needed\n\tEigen::JacobiSVD<Eigen::Matrix2d, Eigen::NoQRPreconditioner> svd;\n\tsvd.compute(H, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n\tEigen::Matrix2d U = svd.matrixU();\n\tEigen::Matrix2d V = svd.matrixV();\n\tdouble d = (V * U.transpose()).determinant() > 0 ? 1 : -1;\n\tEigen::Matrix2d D = Eigen::Matrix2d::Identity();\n\tD.bottomRightCorner<1, 1>()(0, 0) = d;\n\tEigen::Matrix2d R = V * D * U.transpose();\n\n\tEigen::Vector2d translation = mapCentroid - R * sampleCentroid;\n\n\ttransform_t trf = transform_t::Identity();\n\ttrf.topLeftCorner<2, 2>() = R;\n\ttrf.topRightCorner<2, 1>() = translation;\n\treturn trf;\n}\n\nTrICP::TrICP(int maxIter, double relErrChangeThresh,\n\t\t\t std::function<point_t(const point_t&)> getClosest)\n\t: maxIter(maxIter), relErrChangeThresh(relErrChangeThresh),\n\t  getClosest(std::move(getClosest)) {\n}\n\ntransform_t TrICP::correct(const points_t& sample, double overlap) {\n\tif (sample.empty() || overlap == 0) {\n\t\treturn transform_t::Identity();\n\t}\n\tint i = 0;\n\tdouble mse = 1e9;\n\tdouble oldMSE;\n\tpoints_t points = sample;\n\ttransform_t trf = transform_t::Identity();\n\tint N = static_cast<int>(overlap * sample.size());\n\tdo {\n\t\ti++;\n\t\toldMSE = mse;\n\t\ttransform_t t = iterate(points, N, mse);\n\t\ttrf = t * trf;\n\t} while (!isDone(i, mse, oldMSE));\n\n\treturn trf;\n}\n\nbool TrICP::isDone(int numIter, double mse, double oldMSE) const {\n\tif (mse <= 1e-9) {\n\t\treturn true;\n\t}\n\tdouble relErrChange = fabs(mse - oldMSE) / mse;\n\treturn numIter >= maxIter || relErrChange <= relErrChangeThresh;\n}\n\ntransform_t TrICP::iterate(points_t& sample, int N, double& mse) const {\n\tPointPair pairs[sample.size()];\n\tfor (size_t i = 0; i < sample.size(); i++) {\n\t\tconst point_t& point = sample[i];\n\t\tpoint_t closestPoint = getClosest(point);\n\t\tdouble dist = (point - closestPoint).norm();\n\t\tPointPair pair{closestPoint, point, dist};\n\t\tpairs[i] = pair;\n\t}\n\n\tstd::vector<PointPair> closestPairs = getMinN(pairs, sample.size(), N);\n\n\tdouble newS = 0;\n\tfor (const PointPair& pair : closestPairs) {\n\t\tnewS += pair.dist * pair.dist;\n\t}\n\tmse = newS / N;\n\n\ttransform_t trf = computeTransformation(closestPairs);\n\n\tfor (point_t& point : sample) {\n\t\tpoint = trf * point;\n\t}\n\treturn trf;\n}\n", "meta": {"hexsha": "04d046fef742144d36e251ddc1d23dbc6363d56e", "size": 4214, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/worldmap/TrICP.cpp", "max_stars_repo_name": "huskyroboticsteam/Resurgence", "max_stars_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-23T23:31:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:17:41.000Z", "max_issues_repo_path": "src/worldmap/TrICP.cpp", "max_issues_repo_name": "huskyroboticsteam/Resurgence", "max_issues_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-22T05:33:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T07:01:47.000Z", "max_forks_repo_path": "src/worldmap/TrICP.cpp", "max_forks_repo_name": "huskyroboticsteam/Resurgence", "max_forks_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0128205128, "max_line_length": 92, "alphanum_fraction": 0.6682486948, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6134609110065682}}
{"text": "\n#pragma once\n\n/// @file\n\n#include \"numeric/dense_matrix.hpp\"\n#include <Eigen/SVD>\n\nnamespace neon\n{\n/// svd computes the singular value decomposition of an input matrix and\n/// provides access to the left and right singular vectors and the singular\n/// values.\nclass svd\n{\npublic:\n    svd() = default;\n\n    virtual ~svd() = default;\n\n    /// compute thin SVD decomposition of a matrix A\n    virtual void compute(col_matrix const& A) = 0;\n\n    /// Compute thin SVD decomposition\n    /// \\param A Input matrix\n    /// \\param n Maximum number of singular vectors\n    virtual void compute(col_matrix const& A, std::int64_t const n) = 0;\n\n    /// compute thin SVD decomposition of a matrix A with a tolerance on the singular values\n    /// A singular value will be considered nonzero if its value is strictly greater than\n    /// \\f$ \\vert singular value \\vert \\leqslant threshold \\times \\vert max singular value \\vert \\f$.\n    virtual void compute(col_matrix const& A, double const tolerance) = 0;\n\n    /// \\return left singular vectors (columns of the thin U matrix)\n    virtual col_matrix const& left() const noexcept = 0;\n\n    /// \\return right singular vectors (columns of the thin V matrix)\n    virtual col_matrix const& right() const noexcept = 0;\n\n    /// \\return singular values\n    virtual vector const& values() const noexcept = 0;\n\n    /// A least-squares solution of A*x = b\n    /// linear compination of columns of A\n    virtual void solve(vector& x, vector const& b) const noexcept = 0;\n\nprotected:\n    col_matrix left_vectors;\n    col_matrix right_vectors;\n    vector singular_values;\n};\n\n/// bdc_svd first reduces the input matrix to bi-diagonal form and then performs a\n/// divide-and-conquer diagonalization. Small blocks are diagonalized using class\n/// JacobiSVD. Default switching size is 16.\nclass bdc_svd : public svd\n{\npublic:\n    bdc_svd() = default;\n\n    bdc_svd(col_matrix const& A);\n\n    void compute(col_matrix const& A) override;\n\n    void compute(col_matrix const& A, std::int64_t const n) override;\n\n    void compute(col_matrix const& A, double const tolerance) override;\n\n    col_matrix const& left() const noexcept override;\n\n    col_matrix const& right() const noexcept override;\n\n    vector const& values() const noexcept override;\n\n    void solve(vector& x, vector const& b) const noexcept override;\n\nprivate:\n    Eigen::BDCSVD<col_matrix> decomposition;\n};\n\n/// Implementation of the truncated Singular Value Decomposition, using\n/// randomized algorithms as described in 'finding structure with randomness'\n/// @cite halko2011finding.\nclass randomised_svd : public svd\n{\npublic:\n    randomised_svd() = default;\n\n    randomised_svd(col_matrix const& A);\n\n    void compute(col_matrix const& A) override;\n\n    void compute(col_matrix const& A, std::int64_t const n) override;\n\n    void compute(col_matrix const& A, double const tolerance) override;\n\n    col_matrix const& left() const noexcept override;\n\n    col_matrix const& right() const noexcept override;\n\n    vector const& values() const noexcept override;\n\n    void solve(vector& x, vector const& b) const noexcept override;\n\nprivate:\n    Eigen::BDCSVD<col_matrix> decomposition;\n};\n}\n", "meta": {"hexsha": "d32e6a106cf00289db40d38d22c0b17733371a81", "size": 3175, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/svd/svd.hpp", "max_stars_repo_name": "dbeurle/neon", "max_stars_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T17:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T23:13:26.000Z", "max_issues_repo_path": "src/solver/svd/svd.hpp", "max_issues_repo_name": "dbeurle/neon", "max_issues_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T07:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-10T19:38:12.000Z", "max_forks_repo_path": "src/solver/svd/svd.hpp", "max_forks_repo_name": "dbeurle/neon", "max_forks_repo_head_hexsha": "63cd2929a6eaaa0e1654c729cd35a9a52a706962", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-10-08T16:51:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T08:08:04.000Z", "avg_line_length": 29.128440367, "max_line_length": 101, "alphanum_fraction": 0.7155905512, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6134609055207458}}
{"text": "#ifndef EXPSUM_PARTIAL_LANCZOS_BIDIAGONALIZATION_HPP\n#define EXPSUM_PARTIAL_LANCZOS_BIDIAGONALIZATION_HPP\n\n#include <armadillo>\n\nnamespace expsum\n{\n///\n/// Partial Lanczos bidiagonalization with full reorthogonalization\n///\n/// @param matvec  compute `y = a * A) * x + b * y` with matrix-free form\n/// @param matvec_trans compute `y = a * A.t() * x + b * y` with matrix-free\n///   form\n/// @param[out] alpha  real vector of size `n` that stores diagonal part of B.\n/// @param[out] beta   real vector of size `n - 1` that stores superdiagonal\n///   part of B.\n/// @param[out] P  on exit matrix P\n/// @param[out] Q  on exit matrix Q\n/// @param[out] rank  on exit rank of matrix A\n/// @param[inout] tol_error on entry tolerance of residuals, and on exit an\n///   esitmation of residual.\n/// @param[inout] work workspace\n///\ntemplate <typename MatVec, typename MatVecTrans, typename T>\nvoid partial_lanczos_bidiagonalization(\n    MatVec matvec, MatVecTrans matvec_trans,\n    arma::Col<typename arma::Col<T>::pod_type>& alpha,\n    arma::Col<typename arma::Col<T>::pod_type>& beta, arma::Mat<T>& P,\n    arma::Mat<T>& Q, arma::uword& rank,\n    typename arma::Col<T>::pod_type& tol_error, arma::Col<T>& work)\n{\n    using value_type = T;\n    using real_type  = typename arma::Col<T>::pod_type;\n\n    // constexpr static const value_type zero = value_type();\n    // constexpr static const value_type one  = value_type(1);\n\n    arma::uword m        = P.n_rows;\n    arma::uword n        = Q.n_rows;\n    arma::uword k        = P.n_cols;\n    arma::uword max_rank = std::min({m, n, k});\n\n    assert(Q.n_cols == k);\n    assert(work.size() >= max_rank);\n    assert(real_type() < tol_error && tol_error < real_type(1));\n\n    auto q0 = Q.col(0);\n    q0.randn();\n    q0 /= arma::norm(q0);\n    auto p0 = P.col(0);\n    // p0 <-- A * q0\n    matvec(q0, value_type(), p0);\n    auto a1 = arma::norm(p0);\n    if (a1 > real_type())\n    {\n        p0 *= real_type(1) / a1;\n    }\n    alpha(0) = a1;\n\n    const real_type tol2 = tol_error * tol_error;\n    // Estimation of the Frobenius norm of A\n    real_type fnormA = a1 * a1;\n    // Estimation of relative error\n    real_type error = real_type();\n\n    rank = 0;\n\n    while (++rank < max_rank)\n    {\n        auto p1 = P.col(rank - 1);\n        auto p2 = P.col(rank);\n        auto q1 = Q.col(rank - 1);\n        auto q2 = Q.col(rank);\n        //\n        // --- Recursion for right Lanczos vector\n        //\n        // q2 <-- A.t() * p1 - a1 * q1\n        matvec_trans(p1, value_type(), q2);\n        q2 -= a1 * q1;\n        // Reorthogonalization\n        auto tmp   = work.head(rank);\n        auto viewQ = Q.head_cols(rank);\n        tmp        = viewQ.t() * q2;\n        q2 -= viewQ * tmp;\n\n        auto b1 = arma::norm(q2);\n        if (b1 > real_type())\n        {\n            q2 *= real_type(1) / b1;\n        }\n        beta(rank - 1) = b1;\n        //\n        // --- Recursion for left Lanczos vector\n        //\n        // p2 <-- A * p2 - b1 * p1\n        matvec(q2, value_type(), p2);\n        p2 -= b1 * p1;\n        // Reorthogonalization\n        auto viewP = P.head_cols(rank);\n        tmp        = viewP.t() * p2;\n        p2 -= viewP * tmp;\n\n        const auto a2 = arma::norm(p2);\n        if (a2 > real_type())\n        {\n            p2 *= real_type(1) / a2;\n        }\n        alpha(rank) = a2;\n\n        const auto t = a2 * a2 + b1 * b1;\n        //\n        // Estimation of the Frobenius norm of A\n        //\n        // \\|A\\|_{F}^{2}= \\sum_{K=1}^{rank(A)-1}\n        //              (\\alpha_{K}^{2} + \\beta_{K}^{2}) + \\alpha_{rank(A)}}\n        //\n        fnormA += t;\n        error = t;\n        if (t <= tol2 * fnormA)\n        {\n            // Converged\n            break;\n        }\n\n        a1 = a2;\n    }\n\n    tol_error = sqrt(error);\n    return;\n}\n\n} // namespace: expsum\n\n#endif /* NUMERIC_PARTIAL_LANCZOS_BIDIAGONALIZATION_HPP */\n", "meta": {"hexsha": "3707a842d9d4be4ae6f976e67c3993f34170e984", "size": 3847, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/fitting/partial_lanczos_bidiagonalization.hpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/expsum/fitting/partial_lanczos_bidiagonalization.hpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/expsum/fitting/partial_lanczos_bidiagonalization.hpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4962962963, "max_line_length": 78, "alphanum_fraction": 0.542240707, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6134604316310465}}
{"text": "//####### Test module for unit conversion ####################################\n\n//Define Module name\n #define BOOST_TEST_MODULE \"phys/unit_conversion\"\n\n//Include Boost unit tests library & library for floating point comparison\n#include <boost/test/unit_test.hpp>\n#include <boost/test/tools/floating_point_comparison.hpp>\n\n#include <picsar_qed/math/math_constants.h>\n#include <picsar_qed/physics/phys_constants.h>\n#include <picsar_qed/physics/unit_conversion.hpp>\n\n#include <array>\n#include <algorithm>\n#include <functional>\n\nusing namespace picsar::multi_physics::phys;\nusing namespace picsar::multi_physics::math;\n\n//Tolerance for double precision calculations\nconst double double_tolerance = 1.0e-12;\n\n//Tolerance for single precision calculations\nconst float float_tolerance = 1.0e-4;\n\n//Templated tolerance\ntemplate <typename T>\nT constexpr tolerance()\n{\n    if(std::is_same<T,float>::value)\n        return float_tolerance;\n    else\n        return double_tolerance;\n}\n\n//Auxiliary functions for tests\ntemplate<typename RealType>\nstruct val_pack{\n    RealType SI;\n    RealType omega;\n    RealType lambda;\n    RealType hl;\n};\n\ntemplate<typename RealType, quantity Quantity>\nconstexpr void test_to_SI(val_pack<RealType> vals,\n    RealType reference_omega = -1.0,\n    RealType reference_length = -1.0)\n{\n    const auto fact_SI =\n        conv<Quantity, unit_system::SI,\n            unit_system::SI, RealType>::fact();\n    const auto fact_omega =\n        conv<Quantity, unit_system::norm_omega,\n            unit_system::SI, RealType>::fact(reference_omega);\n    const auto fact_lambda =\n        conv<Quantity, unit_system::norm_lambda,\n            unit_system::SI, RealType>::fact(reference_length);\n    const auto fact_hl =\n        conv<Quantity, unit_system::heaviside_lorentz,\n            unit_system::SI, RealType>::fact();\n\n    const auto res_SI2SI = vals.SI*fact_SI;\n    const auto res_omega2SI = vals.omega*fact_omega;\n    const auto res_lambda2SI = vals.lambda*fact_lambda;\n    const auto res_hl2SI = vals.hl*fact_hl;\n    const auto all_res = std::array<RealType,4>{\n        res_SI2SI, res_omega2SI, res_lambda2SI, res_hl2SI};\n    for (const auto& res : all_res)\n        BOOST_CHECK_SMALL((res-vals.SI)/vals.SI, tolerance<RealType>());\n}\n\ntemplate<typename RealType, quantity Quantity>\nconstexpr void test_from_to(\n    val_pack<RealType> vals,\n    RealType reference_omega = -1.0,\n    RealType reference_length = -1.0)\n\n{\n    const auto from_SI_to_all = std::array<RealType,4>\n    {\n        vals.SI*conv<Quantity, unit_system::SI,\n            unit_system::SI, RealType>::fact(),\n        vals.SI*conv<Quantity, unit_system::SI,\n            unit_system::norm_omega, RealType>::fact(1.0,reference_omega),\n        vals.SI*conv<Quantity, unit_system::SI,\n            unit_system::norm_lambda, RealType>::fact(1.0,reference_length),\n        vals.SI*conv<Quantity, unit_system::SI,\n            unit_system::heaviside_lorentz, RealType>::fact(),\n    };\n\n    const auto from_omega_to_all = std::array<RealType,4>\n    {\n        vals.omega*conv<Quantity, unit_system::norm_omega,\n            unit_system::SI, RealType>::fact(reference_omega),\n        vals.omega*conv<Quantity, unit_system::norm_omega,\n            unit_system::norm_omega, RealType>::fact(reference_omega, reference_omega),\n        vals.omega*conv<Quantity, unit_system::norm_omega,\n            unit_system::norm_lambda, RealType>::fact(reference_omega, reference_length),\n        vals.omega*conv<Quantity, unit_system::norm_omega,\n            unit_system::heaviside_lorentz, RealType>::fact(reference_omega),\n    };\n\n    const auto from_lambda_to_all = std::array<RealType,4>\n    {\n        vals.lambda*conv<Quantity, unit_system::norm_lambda,\n            unit_system::SI, RealType>::fact(reference_length),\n        vals.lambda*conv<Quantity, unit_system::norm_lambda,\n            unit_system::norm_omega, RealType>::fact(reference_length, reference_omega),\n        vals.lambda*conv<Quantity, unit_system::norm_lambda,\n            unit_system::norm_lambda, RealType>::fact(reference_length, reference_length),\n        vals.lambda*conv<Quantity, unit_system::norm_lambda,\n            unit_system::heaviside_lorentz, RealType>::fact(reference_length, 1.0),\n    };\n\n    const auto from_hl_to_all = std::array<RealType,4>\n    {\n        vals.hl*conv<Quantity, unit_system::heaviside_lorentz,\n            unit_system::SI, RealType>::fact(),\n        vals.hl*conv<Quantity, unit_system::heaviside_lorentz,\n            unit_system::norm_omega, RealType>::fact(1.0,reference_omega),\n        vals.hl*conv<Quantity, unit_system::heaviside_lorentz,\n            unit_system::norm_lambda, RealType>::fact(1.0,reference_length),\n        vals.hl*conv<Quantity, unit_system::heaviside_lorentz,\n            unit_system::heaviside_lorentz, RealType>::fact(),\n    };\n\n    const auto fact_SI = conv<Quantity, unit_system::SI,\n        unit_system::SI, RealType>::fact();\n    const auto fact_omega = conv<Quantity, unit_system::norm_omega,\n        unit_system::SI, RealType>::fact(reference_omega);\n    const auto fact_lambda = conv<Quantity, unit_system::norm_lambda,\n        unit_system::SI, RealType>::fact(reference_length);\n    const auto fact_hl = conv<Quantity, unit_system::heaviside_lorentz,\n        unit_system::SI, RealType>::fact();\n\n    const auto all_facts = std::array<RealType, 4>{\n        fact_SI, fact_omega, fact_lambda, fact_hl};\n\n    const auto all_data = std::array<std::array<RealType, 4>, 4>{\n        from_SI_to_all,\n        from_omega_to_all,\n        from_lambda_to_all,\n        from_hl_to_all\n    };\n\n    for (auto data: all_data)\n    {\n        std::transform( data.begin(), data.end(),\n            all_facts.begin(), data.begin(),\n            std::multiplies<RealType>());\n\n        for (const auto& res : data){\n            BOOST_CHECK_SMALL((res-vals.SI)/vals.SI, tolerance<RealType>());\n        }\n    }\n}\n\n// ------------- Tests --------------\n\n// ***Test energy reference for Heaviside Lorentz units\ntemplate<typename RealType>\nvoid test_case_hl_reference_energy()\n{\n    BOOST_CHECK_SMALL(\n        (heaviside_lorentz_reference_energy<RealType>-MeV<RealType>)/MeV<RealType>,\n        tolerance<RealType>());\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_heaviside_lorentz_ref_energy )\n{\n    test_case_hl_reference_energy<double>();\n    test_case_hl_reference_energy<float>();\n}\n\n// ***Test electron rest energy in Heaviside Lorentz units\ntemplate<typename RealType>\nvoid test_case_hl_electron_rest_energy()\n{\n    constexpr auto exp = static_cast<RealType>(\n        electron_mass<double>*light_speed<double>*light_speed<double>/\n        MeV<double>);\n    constexpr auto res = heaviside_lorentz_electron_rest_energy<RealType>;\n    BOOST_CHECK_SMALL((res-exp)/exp, tolerance<RealType>());\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_heaviside_lorentz_electron_rest_energy )\n{\n    test_case_hl_electron_rest_energy<double>();\n    test_case_hl_electron_rest_energy<float>();\n}\n\n// ***Test Schwinger field in Heaviside Lorentz units\ntemplate<typename RealType>\nvoid test_case_hl_schwinger_field()\n{\n    constexpr auto exp = static_cast<RealType>(\n        schwinger_field<double>*conv<quantity::E,\n            unit_system::SI, unit_system::heaviside_lorentz, double>::fact());\n    constexpr auto res = heaviside_lorentz_schwinger_field<RealType>;\n    BOOST_CHECK_SMALL((res-exp)/exp, tolerance<RealType>());\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_heaviside_lorentz_schwinger_field )\n{\n    test_case_hl_schwinger_field<double>();\n    test_case_hl_schwinger_field<float>();\n}\n\n// ***Test elementary charge in Heaviside Lorentz units\ntemplate<typename RealType>\nvoid test_case_hl_elementary_charge()\n{\n    constexpr auto exp = static_cast<RealType>(\n        elementary_charge<double>*conv<quantity::charge,\n            unit_system::SI, unit_system::heaviside_lorentz, double>::fact());\n    constexpr auto res = heaviside_lorentz_elementary_charge<RealType>;\n    BOOST_CHECK_SMALL((res-exp)/exp, tolerance<RealType>());\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_heaviside_lorentz_elementary_charge )\n{\n    test_case_hl_elementary_charge<double>();\n    test_case_hl_elementary_charge<float>();\n}\n\n// ***Test mass conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_mass()\n{\n    constexpr auto mass_SI = electron_mass<RealType>;\n    constexpr auto mass_omega = static_cast<RealType>(1.0);\n    constexpr auto mass_lambda = static_cast<RealType>(1.0);\n    constexpr auto mass_hl = electron_mass<RealType>*light_speed<RealType>*\n        light_speed<RealType>/heaviside_lorentz_reference_energy<RealType>;\n    constexpr auto all_masses = val_pack<RealType>{mass_SI, mass_omega, mass_lambda, mass_hl};\n\n    test_to_SI<RealType, quantity::mass>(all_masses);\n    test_from_to<RealType, quantity::mass>(all_masses);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_mass )\n{\n    test_case_mass<double>();\n    test_case_mass<float>();\n}\n\n// ***Test charge conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_charge()\n{\n    constexpr auto charge_SI = elementary_charge<RealType>;\n    constexpr auto charge_omega = static_cast<RealType>(1.0);\n    constexpr auto charge_lambda = static_cast<RealType>(1.0);\n    constexpr auto charge_hl = sqrt_4_pi_fine_structure<RealType>;\n    constexpr auto all_charges = val_pack<RealType>{charge_SI, charge_omega, charge_lambda, charge_hl};\n\n    test_to_SI<RealType, quantity::charge>(all_charges);\n    test_from_to<RealType, quantity::charge>(all_charges);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_charge )\n{\n    test_case_charge<double>();\n    test_case_charge<float>();\n}\n\n// ***Test velocity conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_velocity()\n{\n    constexpr auto velocity_SI = light_speed<RealType>;\n    constexpr auto velocity_omega = static_cast<RealType>(1.0);\n    constexpr auto velocity_lambda = static_cast<RealType>(1.0);\n    constexpr auto velocity_hl = static_cast<RealType>(1.0);\n    constexpr auto all_velocities = val_pack<RealType>{velocity_SI, velocity_omega, velocity_lambda, velocity_hl};\n\n    test_to_SI<RealType, quantity::velocity>(all_velocities);\n    test_from_to<RealType, quantity::velocity>(all_velocities);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_velocity )\n{\n    test_case_velocity<double>();\n    test_case_velocity<float>();\n}\n\n// ***Test momentum conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_momentum()\n{\n    constexpr auto momentum_SI = electron_mass<RealType>*light_speed<RealType>;\n    constexpr auto momentum_omega = static_cast<RealType>(1.0);\n    constexpr auto momentum_lambda = static_cast<RealType>(1.0);\n    constexpr auto momentum_hl = static_cast<RealType>(\n        electron_mass<double>*light_speed<double>*light_speed<double>/\n        heaviside_lorentz_reference_energy<double>);\n    constexpr auto all_momenta = val_pack<RealType>{momentum_SI, momentum_omega, momentum_lambda, momentum_hl};\n\n    test_to_SI<RealType, quantity::momentum>(all_momenta);\n    test_from_to<RealType, quantity::momentum>(all_momenta);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_momentum )\n{\n    test_case_momentum<double>();\n    test_case_momentum<float>();\n}\n\n// ***Test energy conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_energy()\n{\n    constexpr auto energy_SI = GeV<RealType>;\n    constexpr auto energy_omega = static_cast<RealType>(\n        GeV<double>/electron_mass<double>/light_speed<double>/light_speed<double>);\n    constexpr auto energy_lambda = static_cast<RealType>(\n        GeV<double>/electron_mass<double>/light_speed<double>/light_speed<double>);\n    constexpr auto energy_hl = static_cast<RealType>(\n        GeV<double>/heaviside_lorentz_reference_energy<double>);\n    constexpr auto all_energies = val_pack<RealType>{energy_SI, energy_omega, energy_lambda, energy_hl};\n\n    test_to_SI<RealType, quantity::energy>(all_energies);\n    test_from_to<RealType, quantity::energy>(all_energies);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_energy )\n{\n    test_case_energy<double>();\n    test_case_energy<float>();\n}\n\n\n// ***Test length conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_length()\n{\n    constexpr auto reference_length = static_cast<RealType>(800.0e-9);\n    constexpr auto reference_omega = static_cast<RealType>(\n        2.0*pi<double>*light_speed<double>/reference_length);\n\n    constexpr auto length_SI = reference_length;\n    constexpr auto length_omega = static_cast<RealType>(2.0* pi<double>);\n    constexpr auto length_lambda = static_cast<RealType>(1.0);\n    constexpr auto length_hl = static_cast<RealType>(\n        heaviside_lorentz_reference_energy<double>*reference_length/\n        reduced_plank<double>/light_speed<double>);\n\n    constexpr auto all_lenghts = val_pack<RealType>{length_SI, length_omega, length_lambda, length_hl};\n\n    test_to_SI<RealType, quantity::length>(\n        all_lenghts, reference_omega, reference_length);\n    test_from_to<RealType, quantity::length>(\n        all_lenghts, reference_omega, reference_length);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_length)\n{\n    test_case_length<double>();\n    test_case_length<float>();\n}\n\n// ***Test area conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_area_to_SI()\n{\n    constexpr auto reference_length = static_cast<RealType>(800.0e-9);\n    constexpr auto reference_omega = static_cast<RealType>(\n        2.0*pi<double>*light_speed<double>/reference_length);\n\n    constexpr auto area_SI = reference_length*reference_length;\n    constexpr auto area_omega = static_cast<RealType>(4.0* pi<double>*pi<double>);\n    constexpr auto area_lambda = static_cast<RealType>(1.0);\n    constexpr auto area_hl = static_cast<RealType>(\n        heaviside_lorentz_reference_energy<double>*\n        heaviside_lorentz_reference_energy<double>*\n        reference_length*reference_length/\n        reduced_plank<double>/reduced_plank<double>/\n        light_speed<double>/light_speed<double>);\n\n    constexpr auto all_areas = val_pack<RealType>{area_SI, area_omega, area_lambda, area_hl};\n\n    test_to_SI<RealType, quantity::area>(\n        all_areas, reference_omega, reference_length);\n    test_from_to<RealType, quantity::area>(\n        all_areas, reference_omega, reference_length);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_area_to_SI )\n{\n    test_case_area_to_SI<double>();\n    test_case_area_to_SI<float>();\n}\n\n// ***Test volume conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_volume_to_SI()\n{\n    constexpr auto reference_length = static_cast<RealType>(800.0e-9);\n    constexpr auto reference_omega = static_cast<RealType>(\n        2.0*pi<double>*light_speed<double>/reference_length);\n\n    constexpr auto volume_SI = reference_length*reference_length*reference_length;\n    constexpr auto volume_omega = static_cast<RealType>(8.0*\n        pi<double>*pi<double>*pi<double>);\n    constexpr auto volume_lambda = static_cast<RealType>(1.0);\n    constexpr auto volume_hl = static_cast<RealType>(\n        heaviside_lorentz_reference_energy<double>*\n        heaviside_lorentz_reference_energy<double>*\n        heaviside_lorentz_reference_energy<double>*\n        reference_length*reference_length*reference_length/\n        reduced_plank<double>/reduced_plank<double>/reduced_plank<double>/\n        light_speed<double>/light_speed<double>/light_speed<double>);\n\n    constexpr auto all_volumes = val_pack<RealType>{volume_SI, volume_omega, volume_lambda, volume_hl};\n\n    test_to_SI<RealType, quantity::volume>(\n        all_volumes, reference_omega, reference_length);\n    test_from_to<RealType, quantity::volume>(\n        all_volumes, reference_omega, reference_length);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_volume_to_SI )\n{\n    test_case_volume_to_SI<double>();\n    test_case_volume_to_SI<float>();\n}\n\n// ***Test time conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_time_to_SI()\n{\n    constexpr auto reference_length = static_cast<RealType>(800.0e-9);\n    constexpr auto reference_omega = static_cast<RealType>(\n        2.0*pi<double>*light_speed<double>/reference_length);\n\n    constexpr auto time_SI = static_cast<RealType>(reference_length/light_speed<double>);\n    constexpr auto time_omega = static_cast<RealType>(2.0*pi<double>);\n    constexpr auto time_lambda = static_cast<RealType>(1.0);\n    constexpr auto time_hl = static_cast<RealType>(\n        (reference_length/light_speed<double>)*\n        heaviside_lorentz_reference_energy<double>/\n        reduced_plank<double>);\n\n    constexpr auto all_times = val_pack<RealType>{time_SI, time_omega, time_lambda, time_hl};\n\n    test_to_SI<RealType, quantity::time>(\n        all_times, reference_omega, reference_length);\n    test_from_to<RealType, quantity::time>(\n        all_times, reference_omega, reference_length);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_time_to_SI )\n{\n    test_case_time_to_SI<double>();\n    test_case_time_to_SI<float>();\n}\n\n// ***Test rate conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_rate_to_SI()\n{\n    constexpr auto reference_length = static_cast<RealType>(800.0e-9);\n    constexpr auto reference_omega = static_cast<RealType>(\n        2.0*pi<double>*light_speed<double>/reference_length);\n\n    constexpr auto rate_SI = static_cast<RealType>(light_speed<double>/reference_length);\n    constexpr auto rate_omega = static_cast<RealType>(1/(2.0*pi<double>));\n    constexpr auto rate_lambda = static_cast<RealType>(1.0);\n    constexpr auto rate_hl = static_cast<RealType>(\n        (light_speed<double>/reference_length)*\n        reduced_plank<double>/\n        heaviside_lorentz_reference_energy<double>);\n\n    constexpr auto all_rates = val_pack<RealType>{rate_SI, rate_omega, rate_lambda, rate_hl};\n\n    test_to_SI<RealType, quantity::rate>(\n        all_rates, reference_omega, reference_length);\n    test_from_to<RealType, quantity::rate>(\n        all_rates, reference_omega, reference_length);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_rate_to_SI )\n{\n    test_case_rate_to_SI<double>();\n    test_case_rate_to_SI<float>();\n}\n\n// ***Test E conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_E_to_SI()\n{\n    constexpr auto reference_length = static_cast<RealType>(800.0e-9);\n    constexpr auto reference_omega = static_cast<RealType>(\n        2.0*pi<double>*light_speed<double>/reference_length);\n\n    constexpr double ref_field_omega = reference_omega*\n        (electron_mass<double>*light_speed<double>/elementary_charge<double>);\n    constexpr double ref_field_length = electron_mass<double>*\n        light_speed<double>*light_speed<double>/elementary_charge<double>/reference_length;\n    constexpr double ref_field_hl =\n        heaviside_lorentz_reference_energy<double>*\n        heaviside_lorentz_reference_energy<double>*\n        sqrt_4_pi_fine_structure<double>/\n        elementary_charge<double>/reduced_plank<double>/light_speed<double>;\n\n    constexpr auto E_SI = schwinger_field<RealType>;\n    constexpr auto E_omega = static_cast<RealType>(\n        schwinger_field<double>/ref_field_omega);\n    constexpr auto E_lambda = static_cast<RealType>(schwinger_field<double>/\n        ref_field_length);\n    constexpr auto E_hl = static_cast<RealType>(schwinger_field<double>/\n        ref_field_hl);\n\n    constexpr auto all_E = val_pack<RealType>{E_SI, E_omega, E_lambda, E_hl};\n\n    test_to_SI<RealType, quantity::E>(\n        all_E, reference_omega, reference_length);\n    test_from_to<RealType, quantity::E>(\n        all_E, reference_omega, reference_length);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_E_to_SI )\n{\n    test_case_E_to_SI<double>();\n    test_case_E_to_SI<float>();\n}\n\n// ***Test B conversion to SI and all to all\ntemplate<typename RealType>\nvoid test_case_B_to_SI()\n{\n    constexpr auto reference_length = static_cast<RealType>(800.0e-9);\n    constexpr auto reference_omega = static_cast<RealType>(\n        2.0*pi<double>*light_speed<double>/reference_length);\n\n    constexpr double ref_field_omega = reference_omega*\n        (electron_mass<double>/elementary_charge<double>);\n    constexpr double ref_field_length = electron_mass<double>*\n        light_speed<double>/elementary_charge<double>/reference_length;\n    constexpr double ref_field_hl =\n        heaviside_lorentz_reference_energy<double>*\n        heaviside_lorentz_reference_energy<double>*\n        sqrt_4_pi_fine_structure<double>/\n        elementary_charge<double>/reduced_plank<double>/\n        light_speed<double>/light_speed<double>;\n\n    constexpr double mag_schwinger = schwinger_field<double>/light_speed<double>;\n\n    constexpr auto B_SI = static_cast<RealType>(mag_schwinger);\n    constexpr auto B_omega = static_cast<RealType>(\n        mag_schwinger/ref_field_omega);\n    constexpr auto B_lambda = static_cast<RealType>(mag_schwinger/\n        ref_field_length);\n    constexpr auto B_hl = static_cast<RealType>(mag_schwinger/\n        ref_field_hl);\n\n    constexpr auto all_B = val_pack<RealType>{B_SI, B_omega, B_lambda, B_hl};\n\n    test_to_SI<RealType, quantity::B>(\n        all_B, reference_omega, reference_length);\n    test_from_to<RealType, quantity::B>(\n        all_B, reference_omega, reference_length);\n}\n\nBOOST_AUTO_TEST_CASE( picsar_unit_conv_B_to_SI )\n{\n    test_case_B_to_SI<double>();\n    test_case_B_to_SI<float>();\n}\n", "meta": {"hexsha": "a02529e21962a7e9614319e4e1baf94c687ed01c", "size": 21277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multi_physics/QED/QED_tests/test_picsar_units.cpp", "max_stars_repo_name": "ax3l/picsar", "max_stars_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T17:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T17:20:30.000Z", "max_issues_repo_path": "multi_physics/QED/QED_tests/test_picsar_units.cpp", "max_issues_repo_name": "ax3l/picsar", "max_issues_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-11-03T10:55:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T17:00:36.000Z", "max_forks_repo_path": "multi_physics/QED/QED_tests/test_picsar_units.cpp", "max_forks_repo_name": "ax3l/picsar", "max_forks_repo_head_hexsha": "7ce1b321d9e047a238e56ee95507d36520a95b5b", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-06-23T13:54:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T21:51:38.000Z", "avg_line_length": 37.1975524476, "max_line_length": 114, "alphanum_fraction": 0.731682098, "num_tokens": 5050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6134604299505543}}
{"text": "// simple Boost usage example for gdb\n\n#include <iostream>\n#include <boost/math/common_factor_rt.hpp>\n\nint main()\n{\n    using namespace boost::math;\n    int result = gcd_evaluator<int>()(50, 125);\n    std::cout << \"GCD of 50 and 125 is \" << result << \"\\n\";\n}\n", "meta": {"hexsha": "7d7c9f32c4e00e130efd8a79aff25faba4c6381d", "size": 259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/simple_boost.cpp", "max_stars_repo_name": "MarioQuillas/gdb_python_api", "max_stars_repo_head_hexsha": "e2573f38e765e0bd2f41122ed2de481b015c0ef6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T10:08:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:41:28.000Z", "max_issues_repo_path": "examples/simple_boost.cpp", "max_issues_repo_name": "MarioQuillas/gdb_python_api", "max_issues_repo_head_hexsha": "e2573f38e765e0bd2f41122ed2de481b015c0ef6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-06-11T10:16:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-17T17:13:04.000Z", "max_forks_repo_path": "examples/simple_boost.cpp", "max_forks_repo_name": "MarioQuillas/gdb_python_api", "max_forks_repo_head_hexsha": "e2573f38e765e0bd2f41122ed2de481b015c0ef6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-05-01T14:30:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-21T20:32:54.000Z", "avg_line_length": 21.5833333333, "max_line_length": 59, "alphanum_fraction": 0.6486486486, "num_tokens": 70, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6134604287752219}}
{"text": "#include \"rand_state.cpp\"\n#include \"entropy.cpp\"\n#include <armadillo>\n#include <iostream>\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n  int n_q = 10;\n  int k = 3;\n  for (int d=1; d<100; d++)\n    {\n      cx_dvec psi = scrambled_1d(n_q, d);\n      cout << \"depth=\" << d << endl;\n      cout << \"von Neumann entropy=\" << vNentropy(k, psi) << endl;\n      cout << \"diagonal entropy=\" << diagentropy(k, psi) << endl;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "d6365b1abf06e9984aee06bbab3143e79a14866a", "size": 444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/test_scramble.cpp", "max_stars_repo_name": "ikim-quantum/DecodeInterior", "max_stars_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/test_scramble.cpp", "max_issues_repo_name": "ikim-quantum/DecodeInterior", "max_issues_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/test_scramble.cpp", "max_forks_repo_name": "ikim-quantum/DecodeInterior", "max_forks_repo_head_hexsha": "c07649e8728c784dc1bd2a25602fec14a344a234", "max_forks_repo_licenses": ["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.3043478261, "max_line_length": 66, "alphanum_fraction": 0.5833333333, "num_tokens": 137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.6134597509643094}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n#include <complex>\n#include <cmath>\n\nusing Eigen::MatrixXcd;\nusing Eigen::VectorXd;\nusing Eigen::VectorXcd;\n\n#define AU_L 5.2917721067e-11 // m\n#define AU_T 2.41888432651e-17 // s\n#define AU_E 4.35974465e-18 // J\n#define EV 1.6021766208e-19 // J\n#define AU2ANG (AU_L / 1e-10)\n#define AU2EV (AU_E / EV)\n#define PI 3.141592653589793238462643383279502884L\n\ndouble simps(VectorXcd f, int size, double dx)\n{\n    double so = 0.0, se = 0.0;\n    for (int i = 1; i < size - 2; i++)\n    {\n        if(i % 2 == 1)\n        {\n            so = so + ((double)real(f[i]));\n        }\n        else\n        {\n            se = se + ((double)real(f[i]));\n        }\n    }\n    return dx / 3 * (((double)real(f[0])) + ((double)real(f[size-1])) + 4 * so + 2 * se);\n}\n\nint main()\n{\n    // constantes do problema\n    const double E0 = 150.0; // eV\n    const double delta_x = 1.0; // angstron\n    const double x0 = -20.0; // angstron\n\n    // otimizando\n    double L = 100.0; // angstron\n    int N = 256;\n    double dt = 1e-19; // s\n\n    double L_au = L / AU2ANG;\n    double dt_au = dt / AU_T;\n    double E0_au = E0 / AU2EV;\n    double delta_x_au = delta_x / AU2ANG;\n    double x0_au = x0 / AU2ANG;\n    double k0_au = sqrt(2.0 * E0_au);\n\n    double dx = L / ((double)(N-1));\n    double dx_au = L_au / ((double)(N-1));\n    VectorXd x_au(N), x_aux(N);\n    for (int i = 0; i < N; i++)\n    {\n        x_au[i] = -L_au / 2.0 + dx_au * ((double)i);\n    }\n\n    // crank-nicolson\n    MatrixXcd B(N,N);\n    MatrixXcd C(N,N);\n    MatrixXcd D(N,N);\n\n    std::complex<double> alpha = - dt_au * (1i / (2.0 * dx_au * dx_au)) / 2.0;\n    std::complex<double> beta = 1.0 - dt_au * (- 1i / (dx_au * dx_au)) / 2.0;\n    std::complex<double> gamma = 1.0 + dt_au * (- 1i / (dx_au * dx_au)) / 2.0;\n    for (int i = 0; i < N; i++)\n    {\n        if (i > 0)\n        {\n            B(i,i-1) = alpha;\n            C(i,i-1) = -alpha;\n        }\n        if (i < N - 1) {\n\n            B(i,i+1) = alpha;\n            C(i,i+1) = -alpha;\n        }\n        B(i,i) = beta;\n        C(i,i) = gamma;\n    }\n    D = B.inverse() * C;\n\n    // pacote de onda\n    double d2 = pow(delta_x_au, 2);\n    double PN = 1.0 / pow(2.0 * PI * d2, 1.0 / 4.0);\n    VectorXcd psi(N), psi_aux(N), psi_s(N);\n    for (int i = 0; i < N; i++)\n    {\n        psi[i] = 1i * k0_au * x_au[i] - pow(x_au[i] - x0_au, 2) / (4.0 * d2);\n        psi[i] = PN * exp(psi[i]);\n    }\n    psi_s = psi.conjugate();\n\n    double A0 = simps(psi_s.cwiseProduct(psi), N, dx_au);\n    double A = 0.0;\n    double xm = x0_au, xm2, xm3;\n    double var_norma = 0.0;\n    int contador = 0;\n\n    while (xm < -x0_au)\n    {\n        contador++;\n        psi = D * psi;\n        psi_s = psi.conjugate();\n        A = simps(psi_s.cwiseProduct(psi), N, dx_au);\n        xm = simps(psi_s.cwiseProduct(x_au.cwiseProduct(psi)), N, dx_au) / A;\n        //std::cout << \"x0=\" << x0_au * AU2ANG << \" & A/A0=\" << (100.0 * A / A0) << \" & X=\" << xm * AU2ANG << \" & C=\" << contador << \"\\n\";\n    }\n\n    var_norma = 100.0 * A / A0;\n    x_aux = x_au.cwiseProduct(x_au);\n    xm2 = simps(psi_s.cwiseProduct(x_aux.cwiseProduct(psi)), N, dx_au) / A;\n    x_aux = x_au.cwiseProduct(x_aux);\n    xm3 = simps(psi_s.cwiseProduct(x_aux.cwiseProduct(psi)), N, dx_au) / A;\n    double desvpad = sqrt(abs(xm2 - pow(xm, 2)));\n    double skewness = (xm3 - 3.0 * xm * pow(desvpad, 2) - pow(xm, 3)) / pow(desvpad, 3);\n\n    std::cout << \"L=\" << L << \" & N=\" << N << \" & dt=\" << dt << \" & A/A0=\" << var_norma << \" & X=\" << xm * AU2ANG << \" & S=\" << desvpad * AU2ANG << \" & G=\" << skewness << \" & C=\" << contador << \" & T=\" << (((double)contador) * dt) << \"\\n\";\n}\n", "meta": {"hexsha": "b1153cfccf1d107bb7677f72aa10e44f0c7685c1", "size": 3647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/my_program.cpp", "max_stars_repo_name": "thiagolcmelo/benchmark", "max_stars_repo_head_hexsha": "bc6697cde65700858ef948e05f8b1517bc33b045", "max_stars_repo_licenses": ["MIT"], "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/my_program.cpp", "max_issues_repo_name": "thiagolcmelo/benchmark", "max_issues_repo_head_hexsha": "bc6697cde65700858ef948e05f8b1517bc33b045", "max_issues_repo_licenses": ["MIT"], "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/my_program.cpp", "max_forks_repo_name": "thiagolcmelo/benchmark", "max_forks_repo_head_hexsha": "bc6697cde65700858ef948e05f8b1517bc33b045", "max_forks_repo_licenses": ["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.176, "max_line_length": 239, "alphanum_fraction": 0.5037016726, "num_tokens": 1411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193597, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.6134565312036258}}
{"text": "/*  _______________________________________________________________________\n\n    DAKOTA: Design Analysis Kit for Optimization and Terascale Applications\n    Copyright 2014 Sandia Corporation.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Dakota directory.\n    _______________________________________________________________________ */\n\n//- Class:\t NonDWASABIBayesCalibration\n//- Description: Derived class for WASABI-based Bayesian inference\n//- Owner:       Tim Wildey\n//- Checked by:\n//- Version:\n\n#ifndef NOND_WASABI_BAYES_CALIBRATION_H\n#define NOND_WASABI_BAYES_CALIBRATION_H\n\n#include \"NonDBayesCalibration.hpp\"\n#include \"GaussianKDE.hpp\"\n// for uniform PDF\n#include <boost/math/distributions/uniform.hpp>\n#include <boost/math/distributions/normal.hpp>\n// for uniform samples (uniform_real is deprecated)\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real.hpp>\n\nnamespace Dakota {\n\n\n/// WASABI - Weighted Adaptive Surrogate Approximations for Bayesian Inference \n\n/** This class performs Bayesian calibration using the WASABI approach\n    */\n\nclass NonDWASABIBayesCalibration: public NonDBayesCalibration\n{\npublic:\n\n  //\n  //- Heading: Constructors and destructor\n  //\n\n  /// standard constructor\n  NonDWASABIBayesCalibration(ProblemDescDB& problem_db, Model& model);\n  /// destructor\n  ~NonDWASABIBayesCalibration();\n\n  //\n  //- Heading: Static callback functions required by WASABI\n  //\n\n  /// initializer for problem size characteristics in WASABI\n  static void \n  problem_size (int &chain_num, int &cr_num, int &gen_num, int &pair_num, \n\t\tint &par_num);\n\n  /// Filename and data initializer for WASABI\n  static void \n  problem_value (std::string *chain_filename, std::string *gr_filename,\n\t\t double &gr_threshold, int &jumpstep, double limits[], \n\t\t int par_num, int &printstep, std::string *restart_read_filename, \n\t\t std::string *restart_write_filename);\n\n  /// Compute the prior density at specified point zp\n  static double prior_density (int par_num, double zp[]);\n\n  // NOTE: Memory is freed inside the dream core\n  /// Sample the prior and return an array of parameter values\n  //static double* prior_sample (int par_num);\n\n  void prior_sample ( RealVector & sample);\n         \n  void compute_responses(RealMatrix & samples, RealMatrix & responses);\n\nprotected:\n\n  //\n  //- Heading: Virtual function redefinitions\n  //\n\n  /// redefined from DakotaNonD\n  void quantify_uncertainty();\n  // redefined from DakotaNonD\n  void print_results(std::ostream& s);\n\n  /// Extract a subset of samples for posterior eval according to the\n  /// indices in points_to_keep\n  void extract_selected_posterior_samples(const std::vector<int> &points_to_keep,\n\t\t\t\t   const RealMatrix &samples_for_posterior_eval,\n\t\t\t\t   const RealVector &posterior_density,\n\t\t\t\t   RealMatrix &posterior_data ) const;\n\n  /// Export posterior_data to file\n  void export_posterior_samples_to_file( const std::string filename, \n\t\t\t\t\t const RealMatrix &posterior_data) const;\n  \n\n  //\n  //- Heading: Data\n\n  /// The mean of the multivariate Gaussian distribution of the obs. data\n  RealVector dataDistMeans;\n  /// The covariance of the multivariate Gaussian distribution of the obs. data\n  RealVector dataDistCovariance;\n  /// The filename of the file containing the data that with density estimator\n  /// defines the distribution of the obs. data\n  std::string dataDistFilename;\n  /// The type of covariance data provided (\"diagonal\",\"matrix\")\n  std::string dataDistCovType;\n  /// The filename of the import file containing samples at which the \n  /// posterior will be evaluated\n  std::string posteriorSamplesImportFile;\n  /// Format of imported posterior samples file\n  unsigned short posteriorSamplesImportFormat;\n  /// The filename of the export file containing an arbitrary set of samples and \n  /// their corresponding density values\n  std::string exportPosteriorDensityFile;\n  /// The filename of the export file containing samples from the posterior and \n  /// their corresponding density values\n  std::string exportPosteriorSamplesFile;\n  /// Format of imported posterior samples and values file\n  unsigned short exportFileFormat;\n  /// Flag specifying whether to generate random samples from the posterior\n  bool generateRandomPosteriorSamples;\n  /// Flag specifying whether to evaluate the posterior density at a \n  /// set of samples\n  bool evaluatePosteriorDensity;\n\n  /// lower bounds on calibrated parameters\n  RealVector paramMins;\n  /// upper bounds on calibrated parameters\n  RealVector paramMaxs;\n\n  /// uniform prior PDFs for each variable\n  std::vector<boost::math::uniform> priorDistributions;\n  /// random number engine for sampling the prior\n  boost::mt19937 rnumGenerator;\n  /// samplers for the uniform prior PDFs for each variable\n  std::vector<boost::uniform_real<double> > priorSamplers;\n\nprivate:\n\n  //\n  // - Heading: Data\n  // \n\n  /// Pointer to current class instance for use in static callback functions\n  static NonDWASABIBayesCalibration* NonDWASABIInstance;\n  \n};\n\n} // namespace Dakota\n\n#endif\n", "meta": {"hexsha": "a1c24a6b7ab8debaae45e95a2fa3548514b1a893", "size": 5124, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dakota-6.3.0.Windows.x86/include/NonDWASABIBayesCalibration.hpp", "max_stars_repo_name": "seakers/ExtUtils", "max_stars_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dakota-6.3.0.Windows.x86/include/NonDWASABIBayesCalibration.hpp", "max_issues_repo_name": "seakers/ExtUtils", "max_issues_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dakota-6.3.0.Windows.x86/include/NonDWASABIBayesCalibration.hpp", "max_forks_repo_name": "seakers/ExtUtils", "max_forks_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-18T14:13:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T14:13:14.000Z", "avg_line_length": 33.0580645161, "max_line_length": 81, "alphanum_fraction": 0.7576112412, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.6134565261067031}}
{"text": "#include \"TalibMeanReversion.h\"\n#include <profitview_util.h>\n#include <SIOClient.h>\n#include <Poco/Logger.h>\n#include <Poco/JSON/Parser.h>\n#include <boost/json.hpp>\n#include <Poco/Any.h>\n#include <ta_libc.h>\n#include <numeric>\n#include <string>\n#include <vector>\n#include <memory>\n#include <ctime>\n\nTalibMeanReversion::TalibMeanReversion(\n\tExchange& exchange, \n\tint lookback,\n\tdouble reversion_level,\n\tint base_quantity)\n: lookback_        {lookback       }\n, reversion_level_ {reversion_level}\n, base_quantity_   {base_quantity  }\n, exchange_        {exchange       }\n{\n    TA_Initialize();\n}\n\nTalibMeanReversion::~TalibMeanReversion() \n{\n    TA_Shutdown();\n}\n\ntemplate<typename Sequence>\ndouble TalibMeanReversion::stdev(const Sequence& sequence) const \n{\n    std::vector<double> prices{ sequence.begin(), sequence.end()};\n\n    // See: https://www.ta-lib.org/d_api/d_api.html#Output%20Size\n    std::unique_ptr <TA_Real []> out{ new TA_Real[lookback_ - TA_STDDEV_Lookback(TA_INTEGER_DEFAULT, TA_REAL_DEFAULT)]};\n\n    TA_Integer outBeg;\n    TA_Integer outNbElement;\n    auto code{ TA_STDDEV(0, lookback_ - 1, prices.data(), TA_INTEGER_DEFAULT, TA_REAL_DEFAULT, &outBeg, &outNbElement, &out[0])};\n    return out[0];\n}\n\nvoid TalibMeanReversion::onTrade(const void *p, Array::Ptr &market_data)\n{\n\tauto& logger{ Poco::Logger::get(\"example\")};\n\tauto result{ market_data->getElement<std::string>(0)};\n\n\tPoco::JSON::Parser parser;\n\tPoco::Dynamic::Var result_json{ parser.parse(result)};\n\n\tauto result_object{ result_json.extract<Poco::JSON::Object::Ptr>()};\n\tauto price{ result_object->get(\"price\").convert<double>()};\n\n    auto symbol{ result_object->get(\"sym\").toString()};\n\n    profitview::util::log_trade(logger, result_object);\n\n\ttime_t date_time{ result_object->get(\"time\").convert<time_t>()};\n\tlogger.information(\"Time: \" + std::string{std::asctime(std::localtime(&date_time))});\n\n    auto& [elements, prices] { counted_prices_[symbol]};\n\n    prices.emplace_back(price);\n\n    if(elements + 1 < lookback_) {\n        ++elements; // Accumulate up to lookback_ prices\n    } else {\n        // These could be done on the fly but the complexity would distract\n        auto mean { std::accumulate(prices.begin(), prices.end(), 0.0)/lookback_};\n        double std_reversion { reversion_level_*stdev(prices)};\n\n        prices.pop_front(); // Now we have lookback_ prices already, remove the oldest\n\n\t\tlogger.information(\"Mean: \" + std::to_string(mean));\n\t\tlogger.information(\"Standard reversion: \" + std::to_string(std_reversion));\n\n        if(boost::json::value* headers{ result_.if_contains(\"headers\")};\n           result_.empty() || // Before the first trade, result_ will be empty and therefore...\n           (headers &&        // ... headers will be nullptr\n            // If there are headers to check, check that rate-limit hasn't been hit\n            std::stol(headers->as_object()[\"x-ratelimit-reset\"].as_string().c_str()) < std::time(nullptr))) \n        {\n            if(price > mean + std_reversion) { // Well greater than the normal volatility\n                // so sell, expecting a reversion to the mean\n                result_ = exchange_.new_order(symbol, Side::sell, base_quantity_, OrderType::market);\n            }\n            else if(price < mean - std_reversion) { // Well less than the normal volatility\n                // so buy, expecting a reversion to the mean\n                result_ = exchange_.new_order(symbol, Side::buy, base_quantity_, OrderType::market);\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "f956bebed9c57f4b66497b9cce9818a474b4a3ba", "size": 3510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TalibMeanReversion.cpp", "max_stars_repo_name": "profitviews/cpp_crypto_algos", "max_stars_repo_head_hexsha": "59eacb2fadce226a90f33bfb91b23a0bf337b444", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "TalibMeanReversion.cpp", "max_issues_repo_name": "profitviews/cpp_crypto_algos", "max_issues_repo_head_hexsha": "59eacb2fadce226a90f33bfb91b23a0bf337b444", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TalibMeanReversion.cpp", "max_forks_repo_name": "profitviews/cpp_crypto_algos", "max_forks_repo_head_hexsha": "59eacb2fadce226a90f33bfb91b23a0bf337b444", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T08:42:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T14:12:06.000Z", "avg_line_length": 35.8163265306, "max_line_length": 129, "alphanum_fraction": 0.6709401709, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.6134255374773486}}
{"text": "#include \"benchmark_functions.hpp\"\n\n#include <boost/python.hpp>\n#include <cmath>\n#include <numeric>\n\nnamespace optimization\n{\n\nnamespace\n{\ntemplate <typename Type>\nstd::vector<Type> list_to_vector(const boost::python::list &l)\n{\n    std::vector<Type> out(len(l));\n    for (auto i = 0u; i < len(l); ++i)\n        out.emplace_back(boost::python::extract<Type>(l[i]));\n\n    return out;\n}\n}\n\ndouble bent_cigar(const std::vector<double> &x)\n{\n    return std::pow(x[0], 2) +\n           std::pow(10, 6) * std::accumulate(std::next(x.begin()), x.end(), 0., [](double acc, double el) {\n               return acc + std::pow(el, 2);\n           });\n}\n\ndouble bent_cigar_pywrapper(const boost::python::list &x)\n{\n    return bent_cigar(list_to_vector<double>(x));\n}\n\ndouble rosenbrock(const std::vector<double> &x)\n{\n    double result = 0;\n\n    for (auto i = 0u; i < x.size() - 1; ++i)\n        result += 100 * std::pow(std::pow(x[i], 2) - std::pow(x[i + 1], 2), 2) + std::pow(x[i] - 1, 2);\n\n    return result;\n}\n\ndouble rosenbrock_pywrapper(const boost::python::list &x)\n{\n    return rosenbrock(list_to_vector<double>(x));\n}\n\ndouble rastrigin(const std::vector<double> &x)\n{\n    return std::accumulate(x.begin(), x.end(), 0., [](double acc, double el) {\n        return acc + std::pow(el, 2) - 10. * std::cos(2 * std::acos(-1) * el) + 10.;\n    });\n}\n\ndouble rastrigin_pywrapper(const boost::python::list &x)\n{\n    return rastrigin(list_to_vector<double>(x));\n}\n\ndouble zakharov(const std::vector<double> &x)\n{\n    const double by_half = std::accumulate(x.begin(), x.end(), 0., [](double acc, double el) {\n        return el * 0.5;\n    });\n\n    return std::accumulate(x.begin(), x.end(), 0., [](double acc, double el) {\n               return acc + std::pow(el, 2);\n           }) +\n           std::pow(by_half, 2.) + std::pow(by_half, 4.);\n}\n\ndouble zakharov_pywrapper(const boost::python::list &x)\n{\n    return zakharov(list_to_vector<double>(x));\n}\n\ndouble objective_function(function f, const std::vector<double> &x)\n{\n    switch (f)\n    {\n    case function::bent_cigar:\n        return bent_cigar(x);\n    case function::rosenbrock:\n        return rosenbrock(x);\n    case function::rastrigin:\n        return rastrigin(x);\n    case function::zakharov:\n        return zakharov(x);\n    }\n\n    throw std::runtime_error(\"Wrong enum value for function\");\n}\n\n} // optimization\n", "meta": {"hexsha": "2c3feef915f435026b55d31e81370a5ea9ac79ba", "size": 2353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "optimization/benchmark_functions.cpp", "max_stars_repo_name": "czeslavo/gwo", "max_stars_repo_head_hexsha": "709488a90840c0a2ed43635143c007adb91b47d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-06-04T02:09:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-25T12:48:11.000Z", "max_issues_repo_path": "optimization/benchmark_functions.cpp", "max_issues_repo_name": "czeslavo/gwo", "max_issues_repo_head_hexsha": "709488a90840c0a2ed43635143c007adb91b47d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-14T22:37:39.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-15T08:54:06.000Z", "max_forks_repo_path": "optimization/benchmark_functions.cpp", "max_forks_repo_name": "czeslavo/gwo", "max_forks_repo_head_hexsha": "709488a90840c0a2ed43635143c007adb91b47d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-03-07T07:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-03T08:31:30.000Z", "avg_line_length": 24.0102040816, "max_line_length": 107, "alphanum_fraction": 0.6068848279, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6133447741312111}}
{"text": "/*!\n  @author Shin'ichiro Nakaoka\n*/\n\n#include \"LuaUtil.h\"\n#include \"../EigenUtil.h\"\n#include <boost/format.hpp>\n\nusing namespace std;\nusing boost::format;\nusing namespace cnoid;\n\nnamespace cnoid {\n\nvoid exportLuaEigenTypes(sol::table& module)\n{\n    module.new_usertype<Vector3>(\n        \"Vector3\",\n        \"new\", sol::factories(\n            []() { return make_shared_aligned<Vector3>(); },\n            [](double x, double y, double z) { return make_shared_aligned<Vector3>(x, y, z); }),\n        sol::call_constructor, sol::factories(\n            [](sol::table self){ return make_shared_aligned<Vector3>(); },\n            [](sol::table self, double x, double y, double z){ return make_shared_aligned<Vector3>(x, y, z); }),\n        sol::meta_function::index, [](Vector3& self, int index) { return self[index]; },\n        sol::meta_function::new_index, [](Vector3& self, int index, double value) { self[index] = value; },\n        sol::meta_function::unary_minus, [](Vector3& self) { return make_shared_aligned<Vector3>(-self); },\n        sol::meta_function::addition, [](Vector3& self, Vector3& other) { return make_shared_aligned<Vector3>(self + other); },\n        sol::meta_function::subtraction, [](Vector3& self, Vector3& other) { return make_shared_aligned<Vector3>(self - other); },\n        sol::meta_function::multiplication, [](Vector3& self, Vector3& other) { return self.dot(other); },\n        \"dot\", [](Vector3& self, Vector3& other) { return self.dot(other); },\n        \"cross\", [](Vector3& self, Vector3& other) { return make_shared_aligned<Vector3>(self.cross(other)); },\n        \"toString\", [](Vector3& self) { return (format(\"{ %1%, %2%, %3% }\") % self[0] % self[1] % self[2]).str(); }\n        );\n}\n\n}\n", "meta": {"hexsha": "1407564c1e872b4d005ec067a408f039bdbe95aa", "size": 1716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Util/lua/LuaEigenTypes.cpp", "max_stars_repo_name": "jun0/choreonoid", "max_stars_repo_head_hexsha": "37167e52bfa054088272e1924d2062604104ac08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:57:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T21:42:22.000Z", "max_issues_repo_path": "src/Util/lua/LuaEigenTypes.cpp", "max_issues_repo_name": "jun0/choreonoid", "max_issues_repo_head_hexsha": "37167e52bfa054088272e1924d2062604104ac08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Util/lua/LuaEigenTypes.cpp", "max_forks_repo_name": "jun0/choreonoid", "max_forks_repo_head_hexsha": "37167e52bfa054088272e1924d2062604104ac08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-11T06:42:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-11T06:42:16.000Z", "avg_line_length": 45.1578947368, "max_line_length": 130, "alphanum_fraction": 0.6264568765, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6132101485084013}}
{"text": "// chebyshev.cpp: evaulation of Chebyshev polynomials for filter design\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 <boost/multiprecision/cpp_bin_float.hpp>\n#include <hprblas>\n\n// define a true 256-bit IEEE floating point type\nconstexpr size_t bits_in_octand = 113 + 128;\nusing cpp_bin_float_octand = boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<bits_in_octand, boost::multiprecision::backends::digit_base_2, void, boost::int16_t, -16382, 16383>, boost::multiprecision::expression_template_option::et_off>;\n// define the floating point types (single, double, quad, octand)\nusing sp = boost::multiprecision::cpp_bin_float_single;\nusing dp = boost::multiprecision::cpp_bin_float_double;\nusing qp = boost::multiprecision::cpp_bin_float_quad;\nusing op = cpp_bin_float_octand;\n\n// generate the Chebyshev nodes in the interval (-1, 1)\ntemplate<typename Vector>\nvoid chebyshev_nodes(Vector& args, Vector& v) {\n\ttypedef typename Vector::value_type value_type;\n\tsize_t nrOfNodes = size(args);\n\tif (size(v) != size(args)) { \n\t\tstd::cerr << \"chebyshev_nodes: vectors must be the same size\\n\"; \n\t\treturn;\n\t}\n\tvalue_type pi = value_type(3.14159265358979323846);  // TODO: this is limited to native type accuracy\n\tfor (size_t k = 1; k <= nrOfNodes; ++k) {\n\t\tvalue_type numerator = (2 * k - 1) * pi;\n\t\tvalue_type denominator = 2 * nrOfNodes;\n\t\tvalue_type arg = numerator / denominator; // better would be to use cospi arguments, so we side step radian round-off\n\t\targs[k] =arg;\n\t\tv[k] = cos(arg);\n\t}\n}\n\ntemplate<typename Vector>\nvoid dumpPair(const Vector& args, const Vector& nodes) {\n\tfor (size_t i = 0; i < size(args) && i < size(nodes); ++i) {\n\t\tstd::cout << args[i] << \" : \" << nodes[i] << std::endl;\n\t}\n}\n\ntemplate<typename Scalar>\nstd::ostream& operator<<(std::ostream& ostr, const std::vector<Scalar>& vec) {\n\tostr << \"[ \";\n\tfor (auto v : vec) {\n\t\tostr << v << \" \";\n\t}\n\tostr << \"]\";\n\treturn ostr;\n}\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace sw::universal;\n\n\tusing Real = double; // qp;\n\tmtl::vec::dense_vector<Real> args(10), nodes(10);\n\tchebyshev_nodes(args, nodes);\n\tstd::cout << std::setprecision(std::numeric_limits<Real>::digits10);\n\tdumpPair(args, nodes);\n\n\tmtl::vec::cos(args);\n\n\tstd::cout << nodes << std::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\n\n/* \n BOOST implementation of operator<<() for cpp_bin_float backend\n\n class number {\n ...\n   //\n   // String conversion functions:\n   //\n   std::string str(std::streamsize digits = 0, std::ios_base::fmtflags f = std::ios_base::fmtflags(0))const\n   {\n\t  return m_backend.str(digits, f);\n   }\n   template<class Archive>\n   void serialize(Archive & ar, const unsigned int version)\n   {\n   ar & m_backend;\n   }\n...\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates>\ninline std::ostream& operator << (std::ostream& os, const number<Backend, ExpressionTemplates>& r)\n{\n\tstd::streamsize d = os.precision();\n\tstd::string s = r.str(d, os.flags());\n\tstd::streamsize ss = os.width();\n\tif (ss > static_cast<std::streamsize>(s.size()))\n\t{\n\t\tchar fill = os.fill();\n\t\tif ((os.flags() & std::ios_base::left) == std::ios_base::left)\n\t\t\ts.append(static_cast<std::string::size_type>(ss - s.size()), fill);\n\t\telse\n\t\t\ts.insert(static_cast<std::string::size_type>(0), static_cast<std::string::size_type>(ss - s.size()), fill);\n\t}\n\treturn os << s;\n}\n\n template <unsigned Digits, digit_base_type DigitBase, class Allocator, class Exponent, Exponent MinE, Exponent MaxE>\nstd::string cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::str(std::streamsize dig, std::ios_base::fmtflags f) const\n{\n   if(dig == 0)\n\t  dig = std::numeric_limits<number<cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE> > >::max_digits10;\n\n   bool scientific = (f & std::ios_base::scientific) == std::ios_base::scientific;\n   bool fixed = !scientific && (f & std::ios_base::fixed);\n\n   std::string s;\n\n   if(exponent() <= cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::max_exponent)\n   {\n\t  // How far to left-shift in order to demormalise the mantissa:\n\t  boost::intmax_t shift = (int)cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::bit_count - exponent() - 1;\n\t  boost::intmax_t digits_wanted = static_cast<int>(dig);\n\t  boost::intmax_t base10_exp = exponent() >= 0 ? static_cast<boost::intmax_t>(std::floor(0.30103 * exponent())) : static_cast<boost::intmax_t>(std::ceil(0.30103 * exponent()));\n\t  //\n\t  // For fixed formatting we want /dig/ digits after the decimal point,\n\t  // so if the exponent is zero, allowing for the one digit before the\n\t  // decimal point, we want 1 + dig digits etc.\n\t  //\n\t  if(fixed)\n\t\t digits_wanted += 1 + base10_exp;\n\t  if(scientific)\n\t\t digits_wanted += 1;\n\t  if(digits_wanted < -1)\n\t  {\n\t\t // Fixed precision, no significant digits, and nothing to round!\n\t\t s = \"0\";\n\t\t if(sign())\n\t\t\ts.insert(static_cast<std::string::size_type>(0), 1, '-');\n\t\t boost::multiprecision::detail::format_float_string(s, base10_exp, dig, f, true);\n\t\t return s;\n\t  }\n\t  //\n\t  // power10 is the base10 exponent we need to multiply/divide by in order\n\t  // to convert our denormalised number to an integer with the right number of digits:\n\t  //\n\t  boost::intmax_t power10 = digits_wanted - base10_exp - 1;\n\t  //\n\t  // If we calculate 5^power10 rather than 10^power10 we need to move\n\t  // 2^power10 into /shift/\n\t  //\n\t  shift -= power10;\n\t  cpp_int i;\n\t  int roundup = 0; // 0=no rounding, 1=tie, 2=up\n\t  static const unsigned limb_bits = sizeof(limb_type) * CHAR_BIT;\n\t  //\n\t  // Set our working precision - this is heuristic based, we want\n\t  // a value as small as possible > cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::bit_count to avoid large computations\n\t  // and excessive memory usage, but we also want to avoid having to\n\t  // up the computation and start again at a higher precision.\n\t  // So we round cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::bit_count up to the nearest whole number of limbs, and add\n\t  // one limb for good measure.  This works very well for small exponents,\n\t  // but for larger exponents we add a few extra limbs to max_bits:\n\t  //\n#ifdef BOOST_MP_STRESS_IO\n\t  boost::intmax_t max_bits = cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::bit_count + 32;\n#else\n\t  boost::intmax_t max_bits = cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::bit_count + ((cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::bit_count % limb_bits) ? (limb_bits - cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::bit_count % limb_bits) : 0) + limb_bits;\n\t  if(power10)\n\t\t max_bits += (msb(boost::multiprecision::detail::abs(power10)) / 8) * limb_bits;\n#endif\n\t  do\n\t  {\n\t\t boost::int64_t error = 0;\n\t\t boost::intmax_t calc_exp = 0;\n\t\t //\n\t\t // Our integer result is: bits() * 2^-shift * 5^power10\n\t\t //\n\t\t i = bits();\n\t\t if(shift < 0)\n\t\t {\n\t\t\tif(power10 >= 0)\n\t\t\t{\n\t\t\t   // We go straight to the answer with all integer arithmetic,\n\t\t\t   // the result is always exact and never needs rounding:\n\t\t\t   BOOST_ASSERT(power10 <= (boost::intmax_t)INT_MAX);\n\t\t\t   i <<= -shift;\n\t\t\t   if(power10)\n\t\t\t\t  i *= pow(cpp_int(5), static_cast<unsigned>(power10));\n\t\t\t}\n\t\t\telse if(power10 < 0)\n\t\t\t{\n\t\t\t   cpp_int d;\n\t\t\t   calc_exp = boost::multiprecision::cpp_bf_io_detail::restricted_pow(d, cpp_int(5), -power10, max_bits, error);\n\t\t\t   shift += calc_exp;\n\t\t\t   BOOST_ASSERT(shift < 0); // Must still be true!\n\t\t\t   i <<= -shift;\n\t\t\t   cpp_int r;\n\t\t\t   divide_qr(i, d, i, r);\n\t\t\t   roundup = boost::multiprecision::cpp_bf_io_detail::get_round_mode(r, d, error, i);\n\t\t\t   if(roundup < 0)\n\t\t\t   {\n#ifdef BOOST_MP_STRESS_IO\n\t\t\t\t  max_bits += 32;\n#else\n\t\t\t\t  max_bits *= 2;\n#endif\n\t\t\t\t  shift = (int)cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::bit_count - exponent() - 1 - power10;\n\t\t\t\t  continue;\n\t\t\t   }\n\t\t\t}\n\t\t }\n\t\t else\n\t\t {\n\t\t\t//\n\t\t\t// Our integer is bits() * 2^-shift * 10^power10\n\t\t\t//\n\t\t\tif(power10 > 0)\n\t\t\t{\n\t\t\t   if(power10)\n\t\t\t   {\n\t\t\t\t  cpp_int t;\n\t\t\t\t  calc_exp = boost::multiprecision::cpp_bf_io_detail::restricted_pow(t, cpp_int(5), power10, max_bits, error);\n\t\t\t\t  calc_exp += boost::multiprecision::cpp_bf_io_detail::restricted_multiply(i, i, t, max_bits, error);\n\t\t\t\t  shift -= calc_exp;\n\t\t\t   }\n\t\t\t   if((shift < 0) || ((shift == 0) && error))\n\t\t\t   {\n\t\t\t\t  // We only get here if we were asked for a crazy number of decimal digits -\n\t\t\t\t  // more than are present in a 2^max_bits number.\n#ifdef BOOST_MP_STRESS_IO\n\t\t\t\t  max_bits += 32;\n#else\n\t\t\t\t  max_bits *= 2;\n#endif\n\t\t\t\t  shift = (int)cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::bit_count - exponent() - 1 - power10;\n\t\t\t\t  continue;\n\t\t\t   }\n\t\t\t   if(shift)\n\t\t\t   {\n\t\t\t\t  roundup = boost::multiprecision::cpp_bf_io_detail::get_round_mode(i, shift - 1, error);\n\t\t\t\t  if(roundup < 0)\n\t\t\t\t  {\n#ifdef BOOST_MP_STRESS_IO\n\t\t\t\t\t max_bits += 32;\n#else\n\t\t\t\t\t max_bits *= 2;\n#endif\n\t\t\t\t\t shift = (int)cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::bit_count - exponent() - 1 - power10;\n\t\t\t\t\t continue;\n\t\t\t\t  }\n\t\t\t\t  i >>= shift;\n\t\t\t   }\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t   // We're right shifting, *and* dividing by 5^-power10,\n\t\t\t   // so 5^-power10 can never be that large or we'd simply\n\t\t\t   // get zero as a result, and that case is already handled above:\n\t\t\t   cpp_int r;\n\t\t\t   BOOST_ASSERT(-power10 < INT_MAX);\n\t\t\t   cpp_int d = pow(cpp_int(5), static_cast<unsigned>(-power10));\n\t\t\t   d <<= shift;\n\t\t\t   divide_qr(i, d, i, r);\n\t\t\t   r <<= 1;\n\t\t\t   int c = r.compare(d);\n\t\t\t   roundup = c < 0 ? 0 : c == 0 ? 1 : 2;\n\t\t\t}\n\t\t }\n\t\t s = i.str(0, std::ios_base::fmtflags(0));\n\t\t //\n\t\t // Check if we got the right number of digits, this\n\t\t // is really a test of whether we calculated the\n\t\t // decimal exponent correctly:\n\t\t //\n\t\t boost::intmax_t digits_got = i ? static_cast<boost::intmax_t>(s.size()) : 0;\n\t\t if(digits_got != digits_wanted)\n\t\t {\n\t\t\tbase10_exp += digits_got - digits_wanted;\n\t\t\tif(fixed)\n\t\t\t   digits_wanted = digits_got;  // strange but true.\n\t\t\tpower10 = digits_wanted - base10_exp - 1;\n\t\t\tshift = (int)cpp_bin_float<Digits, DigitBase, Allocator, Exponent, MinE, MaxE>::bit_count - exponent() - 1 - power10;\n\t\t\tif(fixed)\n\t\t\t   break;\n\t\t\troundup = 0;\n\t\t }\n\t\t else\n\t\t\tbreak;\n\t  }\n\t  while(true);\n\t  //\n\t  // Check whether we need to round up: note that we could equally round up\n\t  // the integer /i/ above, but since we need to perform the rounding *after*\n\t  // the conversion to a string and the digit count check, we might as well\n\t  // do it here:\n\t  //\n\t  if((roundup == 2) || ((roundup == 1) && ((s[s.size() - 1] - '0') & 1)))\n\t  {\n\t\t boost::multiprecision::detail::round_string_up_at(s, static_cast<int>(s.size() - 1), base10_exp);\n\t  }\n\n\t  if(sign())\n\t\t s.insert(static_cast<std::string::size_type>(0), 1, '-');\n\n\t  boost::multiprecision::detail::format_float_string(s, base10_exp, dig, f, false);\n   }\n   else\n   {\n\t  switch(exponent())\n\t  {\n\t  case exponent_zero:\n\t\t s = sign() ? \"-0\" : f & std::ios_base::showpos ? \"+0\" : \"0\";\n\t\t boost::multiprecision::detail::format_float_string(s, 0, dig, f, true);\n\t\t break;\n\t  case exponent_nan:\n\t\t s = \"nan\";\n\t\t break;\n\t  case exponent_infinity:\n\t\t s = sign() ? \"-inf\" : f & std::ios_base::showpos ? \"+inf\" : \"inf\";\n\t\t break;\n\t  }\n   }\n   return s;\n}\n */", "meta": {"hexsha": "eb47452b63c5a18bd00f4865da046faf6fb86f43", "size": 12187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/polynomial/chebyshev.cpp", "max_stars_repo_name": "stillwater-sc/hpr-blas", "max_stars_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-13T10:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T20:30:58.000Z", "max_issues_repo_path": "applications/polynomial/chebyshev.cpp", "max_issues_repo_name": "stillwater-sc/hpr-blas", "max_issues_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T11:19:32.000Z", "max_forks_repo_path": "applications/polynomial/chebyshev.cpp", "max_forks_repo_name": "stillwater-sc/hpr-blas", "max_forks_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:35:35.000Z", "avg_line_length": 34.7207977208, "max_line_length": 323, "alphanum_fraction": 0.6582423894, "num_tokens": 3497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6132101485084012}}
{"text": "#pragma once\n#include <array>\n#include <cassert>\n#include <type_traits>\n\n#include <Eigen/Core>\n\n#include \"control_points_container.hpp\"\n#include \"fixed_size_container_type_trait.hpp\"\n#include \"fixed_size_container_type_trait_eigen.hpp\"\n#include \"multi_array.hpp\"\n#include \"value_type_trait.hpp\"\n#include \"internal/base_matrix.hpp\"\n#include \"internal/gtest_friend.hpp\"\n#include \"internal/no_discard.hpp\"\n#include \"internal/uniform_bspline_eval.hpp\"\n\nnamespace ubs {\n\n/**\n * @brief A uniform B-spline.\n *\n * An implementation of a uniform B-spline from @f$ \\mathbb{R}^n \\rightarrow \\mathbb{R}^m @f$. Uniform means, that the\n * knot vector of the B-spline is equally distributed. Using such a knot vector makes the computation much more\n * efficient, as the basis can be precomputed.\n *\n * For an introduction to B-splines see <https://en.wikipedia.org/wiki/B-spline>.\n *\n * The input and output dimensions of the spline is defined by the input and output type.\n *\n * @tparam ValueType_ The value type.\n * @tparam Degree_ The spline degree.\n * @tparam InputType_ The input type. A FixedSizeContainerTypeTrait must be available for that type.\n * @tparam OutputType_ The output type. A FixedSizeContainerTypeTrait must be available for that type.\n * @tparam ControlPointsType_ The control points type. A ControlPointsTrait must be available for that\n *                            type.\n */\ntemplate <typename ValueType_,\n          int Degree_,\n          typename InputType_,\n          typename OutputType_,\n          typename ControlPointsType_ = ubs::MultiArray<OutputType_,\n                                                        FixedSizeContainerTypeTrait<InputType_>::Size,\n                                                        typename FixedSizeContainerTypeTrait<OutputType_>::Allocator>>\nclass UniformBSpline {\n    // Friends for classes, which need to be partial specialized. (These classes cannot be functions as in class\n    // partial specialization is not allowed.)\n    template <typename Spline_, int InputDims_, int CurDim_>\n    friend struct internal::EvaluateBSpline;\n    template <int TotalDerivative_, int PartialDerivativeIdx_, int InputDims_, int CurDim_>\n    friend class internal::EvaluateBSplineSmoothness;\n\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n    /** @brief The spline degree. */\n    static constexpr int Degree = Degree_;\n    /** @brief The spline order. */\n    static constexpr int Order = Degree_ + 1;\n    /** @brief The number of input dimensions. */\n    static constexpr int InputDims = FixedSizeContainerTypeTrait<InputType_>::Size;\n    /** @brief The number of output dimensions. */\n    static constexpr int OutputDims = FixedSizeContainerTypeTrait<OutputType_>::Size;\n\n    static_assert(InputDims > 0, \"The number of input dimensions must be positive.\");\n    static_assert(OutputDims > 0, \"The number of output dimensions must be positive.\");\n\n    // If one would like to use a higher degree spline, the basis matrices needs to be generated. The code generation\n    // is written in a Mathematica script located at scripts/generate_bspline_basis_cpp_files.\n    static_assert(Degree >= 1 && Degree <= 5, \"Unsupported degree specified.\");\n\n    /** @brief The value type. */\n    using ValueType = ValueType_;\n\n    /** @brief The input type. */\n    using InputType = InputType_;\n    /** @brief The output type. */\n    using OutputType = OutputType_;\n\n    /** @brief The B-spline basis type. */\n    using BasisType = Eigen::Matrix<ValueType, Order, 1>;\n    /** @brief The control points type. */\n    using ControlPointsType = ControlPointsType_;\n    /** @brief The control points container type. */\n    using ControlPointsContainerType =\n        ControlPointsContainer<ValueType, Degree, InputType, OutputType, ControlPointsType>;\n\n    /**\n     * @brief Default constructor.\n     *\n     * Creates a uniform B-spline for which all control points are initialized with zero.\n     * The number of control points in each dimension is the lowest number possible, which is Order.\n     * The lower bound is set to zero and the upper bound is set to one in each dimension.\n     */\n    UniformBSpline() = default;\n\n    /**\n     * @brief Constructs a uniform B-spline using the specified control points.\n     *\n     * The number of control points for each dimension must be at least the order of the spline.\n     * The lower bound is set to zero and the upper bound is set to one in each dimension.\n     *\n     * @param[in] controlPoints The control points.\n     */\n    explicit UniformBSpline(const ControlPointsType& controlPoints) : controlPoints_(controlPoints) {\n    }\n\n    /**\n     * @brief Constructs a uniform B-spline using the specified lower bound and upper bound.\n     *\n     * All the control points are zero initialized. The number of control points in each dimension is the lowest\n     * number possible, which is Order.\n     *\n     * @param[in] lowerBound The lower bound.\n     * @param[in] upperBound The upper bound.\n     */\n    UniformBSpline(const InputType& lowerBound, const InputType& upperBound) : controlPoints_(lowerBound, upperBound) {\n    }\n\n    /**\n     * @brief Constructs a uniform B-spline using the specified control points, lower bound and upper bound.\n     *\n     * @note The number of control points for each dimension must be at least the order of the spline.\n     * @param[in] controlPoints The control points.\n     * @param[in] lowerBound The lower bound.\n     * @param[in] upperBound The upper bound.\n     */\n    UniformBSpline(const InputType& lowerBound, const InputType& upperBound, const ControlPointsType& controlPoints)\n            : controlPoints_(lowerBound, upperBound, controlPoints) {\n    }\n\n    /**\n     * @brief Construct a new Uniform B Spline object using a control points container.\n     *\n     * @param[in] controlPointsContainer The control points container.\n     */\n    explicit UniformBSpline(const ControlPointsContainerType& controlPointsContainer)\n            : controlPoints_(controlPointsContainer) {\n    }\n\n    /** @copydoc UniformBSpline(const ControlPointsContainerType& controlPointsContainer) */\n    explicit UniformBSpline(ControlPointsContainerType&& controlPointsContainer)\n            : controlPoints_(std::move(controlPointsContainer)) {\n    }\n\n    /**\n     * @brief Set new control points.\n     * @param[in] controlPoints The new control points.\n     */\n    void setControlPoints(const ControlPointsType& controlPoints) {\n        controlPoints_.set(controlPoints);\n    }\n\n    /** @copydoc setControlPoints() */\n    void setControlPoints(ControlPointsType&& controlPoints) {\n        controlPoints_.set(std::move(controlPoints));\n    }\n\n    /**\n     * @brief Set new bounds.\n     * @note lowerBound < upperBound for each dimensions.\n     * @param[in] lowerBound The lower range of the input type.\n     * @param[in] upperBound The upper range of the input type.\n     */\n    void setBounds(const InputType& lowerBound, const InputType& upperBound) {\n        controlPoints_.setBounds(lowerBound, upperBound);\n    }\n\n    /**\n     * @brief Checks, whether the specified position is between lower and upper bound.\n     * @param[in] pos The position.\n     * @return True, if this point can be used to evaluate the B-spline, otherwise false.\n     */\n    UBS_NO_DISCARD bool inRange(const InputType& pos) const {\n        using ContainerTrait = FixedSizeContainerTypeTrait<InputType>;\n        for (int dim = 0; dim < InputDims; ++dim) {\n            const auto& val = ContainerTrait::get(pos, dim);\n            if (val < getLowerBound(dim) || val > getUpperBound(dim)) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    /**\n     * @return The lower bound in each dimension.\n     */\n    UBS_NO_DISCARD const InputType& getLowerBound() const {\n        return controlPoints_.getLowerBound();\n    }\n\n    /**\n     * @return The upper bound in each dimension.\n     */\n    UBS_NO_DISCARD const InputType& getUpperBound() const {\n        return controlPoints_.getUpperBound();\n    }\n\n    /**\n     * @brief Return the lower bound for the specified dimension.\n     * @param[in] dim The dimension.\n     * @return The lower bound.\n     */\n    UBS_NO_DISCARD ValueType getLowerBound(int dim) const {\n        return controlPoints_.getLowerBound(dim);\n    }\n\n    /**\n     * @brief Return the upper bound for the specified dimension.\n     * @param[in] dim The dimension.\n     * @return The upper bound.\n     */\n    UBS_NO_DISCARD ValueType getUpperBound(int dim) const {\n        return controlPoints_.getUpperBound(dim);\n    }\n\n    /**\n     * @brief Returns the number of control points of the specified dimension.\n     * @param[in] dim The dimension.\n     * @return The number of control points.\n     */\n    UBS_NO_DISCARD int getNumControlPoints(int dim) const {\n        return int(controlPoints_.getSize(dim));\n    }\n\n    /**\n     * @return The constant control points.\n     */\n    UBS_NO_DISCARD const ControlPointsType& getControlPoints() const {\n        return controlPoints_.get();\n    }\n\n    /**\n     * @brief Returns the control points.\n     * @return The control points.\n     */\n    UBS_NO_DISCARD const ControlPointsContainerType& getControlPointsContainer() const {\n        return controlPoints_;\n    }\n\n    /** @copydoc getControlPointsContainer() const */\n    UBS_NO_DISCARD ControlPointsContainerType& getControlPointsContainer() {\n        return controlPoints_;\n    }\n\n    /**\n     * @brief Returns the scale of the B-spline.\n     *\n     * The scales are depending on the number of control points and the lower and upper bounds.\n     *\n     * @param[in] dim The dimension.\n     * @return The scale in the specified dimension.\n     */\n    UBS_NO_DISCARD ValueType getScale(int dim) const {\n        return controlPoints_.getScale(dim);\n    }\n\n    /**\n     * @brief Set extrapolation.\n     *\n     * If set to true, the spline can be queried outside of the bounds. As an extrapolation the closest spline segment\n     * is used.\n     *\n     * @param[in] v True, if extrapolating should be enabled, otherwise false.\n     */\n    void setExtrapolate(bool v) {\n        extrapolate_ = v;\n    }\n\n    /**\n     * @sa setExtrapolate(bool v)\n     * @return True, if extrapolation is enabled, otherwise false.\n     */\n    UBS_NO_DISCARD bool isExtrapolating() const {\n        return extrapolate_;\n    }\n\n    /**\n     * @brief Determine the span and value in the specified dimension at the specified value.\n     *\n     * The span is the start position, which needs to be used together with the basis to evaluate the spline at val.\n     * The span value is the value which is needed to get the basis function at the correct position. This means,\n     * one can calculate the spline value as follows (1D -> 1D):\n     *\n     * @code\n     * double pos = 0.1;\n     * const std::pair<int, double> spanVal = getSpanAndValue(0, pos);\n     * auto basis = basisFunctions(spanVal.second);\n     *\n     * double ret = 0.0;\n     * int idx = 0;\n     * for (int i = spanVal.first; i < spanVal.first + Order; ++i, ++idx) {\n     *      ret += basis[idx] * controlPoint[i];\n     * }\n     * @endcode\n     *\n     * @param[in] dim The dimension.\n     * @param[in] val The position (0 <= x <= 1).\n     * @return A pair, where first is the span index and second is the span value.\n     */\n    UBS_NO_DISCARD std::pair<int, ValueType> getSpanIndexAndValue(int dim, ValueType val) const {\n        assert(controlPoints_.getScale(dim) > ValueType(0.0));\n\n        if (!extrapolate_) {\n            assert(val >= getLowerBound(dim) - ValueType(1e-5) && val <= getUpperBound(dim) + ValueType(1e-5));\n        }\n\n        const ValueType baseX = (val - controlPoints_.getLowerBound(dim)) * controlPoints_.getScale(dim);\n\n        // Use trait to convert to int. For 'normal' types this is just a static cast, but e.g. for a ceres::Jet type\n        // the value part is used and cast to int.\n        const int xii = ValueTypeTrait<ValueType>::toInt(baseX);\n        const auto xi = std::max(0, std::min(xii, getNumControlPoints(dim) - Order));\n        const ValueType xv = baseX - ValueType(xi);\n\n        return std::make_pair(xi, xv);\n    }\n\n    /**\n     * @brief Return the start index and values.\n     *\n     * These information can be used to evaluate the B-spline and its derivatives.\n     * The returned data is only valid as long as the shape of the control points and the lower and upper bound is not\n     * changed.\n     *\n     * @sa getSpanIndexAndValue(int dim, ValueType val) const\n     * @param[in] pos The position to evaluate the start index and values in each dimension.\n     * @return std::pair<int, InputType>\n     */\n    UBS_NO_DISCARD std::pair<int, InputType> getStartIndexAndValues(const InputType& pos) const {\n        std::pair<int, InputType> data{};\n\n        const auto& strides = controlPoints_.getStrides();\n        for (int dim = 0; dim < InputDims; ++dim) {\n            const ValueType val = FixedSizeContainerTypeTrait<InputType>::get(pos, dim);\n            const auto sv = getSpanIndexAndValue(dim, val);\n\n            data.first += strides[dim] * sv.first;\n            FixedSizeContainerTypeTrait<InputType>::get(data.second, dim) = sv.second;\n        }\n\n        return data;\n    }\n\n    /**\n     * @sa getSpanIndexAndValue\n     * @return The span index.\n     */\n    UBS_NO_DISCARD int getSpanIndex(int dim, ValueType point) const {\n        return getSpanIndexAndValue(dim, point).first;\n    }\n\n    /**\n     * @brief Evaluates the span indices.\n     * @sa getSpanIndex(int dim, ValueType point) const\n     * @param[in] pos The position to evaluate the spline indices.\n     * @return The span indices in each dimension.\n     */\n    UBS_NO_DISCARD std::array<int, InputDims> getSpanIndices(const InputType& pos) const {\n        std::array<int, InputDims> indices{};\n        for (int dim = 0; dim < InputDims; ++dim) {\n            indices[dim] = getSpanIndex(dim, FixedSizeContainerTypeTrait<InputType>::get(pos, dim));\n        }\n        return indices;\n    }\n\n    /**\n     * @sa getSpanIndexAndValue\n     * @return The span value.\n     */\n    UBS_NO_DISCARD ValueType getSpanValue(int dim, ValueType point) const {\n        return getSpanIndexAndValue(dim, point).second;\n    }\n\n    /**\n     * @brief Determine the basis at the span value.\n     * @sa getSpanIndexAndValue\n     * @param[in] spanValue The span value.\n     * @return The basis.\n     */\n    UBS_NO_DISCARD BasisType basisFunctions(ValueType spanValue) const {\n        BasisType basis{basis_.col(0)};\n        for (int i = 1; i < Order; ++i) {\n            basis = spanValue * basis + basis_.col(i);\n        }\n        return basis;\n    }\n\n    /**\n     * @brief Determine the basis derivative at the span value.\n     * @sa getSpanIndexAndValue\n     * @param[in] dim The dimension.\n     * @param[in] derivative The derivative.\n     * @param[in] spanValue The span value.\n     * @return The derivative basis.\n     */\n    UBS_NO_DISCARD BasisType basisFunctionDerivatives(int dim, int derivative, ValueType spanValue) const {\n        if (derivative > Degree) {\n            return BasisType::Zero();\n        }\n        if (derivative == 0) {\n            return basisFunctions(spanValue);\n        }\n\n        using ValueTypeTrait = ValueTypeTrait<ValueType>;\n        const ValueType scale{ValueTypeTrait::pow(controlPoints_.getScale(dim), derivative)};\n\n        BasisType basis = basis_.col(0) * (derivativeFactors_(0, derivative - 1) * scale);\n        for (int i = 1; i < Order - derivative; ++i) {\n            basis = spanValue * basis + basis_.col(i) * (derivativeFactors_(i, derivative - 1) * scale);\n        }\n        return basis;\n    }\n\n    /**\n     * @brief Evaluates the spline at the specified position.\n     * @param[in] pos The position. Each value must be between lower bound and upper bound.\n     * @return The spline value.\n     */\n    UBS_NO_DISCARD OutputType evaluate(const InputType& pos) const {\n        return evaluate(pos, [this](int /*dim*/, ValueType pos) { return basisFunctions(pos); });\n    }\n\n    /**\n     * @brief Evaluates the derivative of the spline at the specified position.\n     * @param[in] pos The position. Each value must be between lower bound and upper bound.\n     * @param[in] d The derivative in the first dimension.\n     * @param[in] derivatives The derivative in the second, third, ... dimension.\n     * @return The derivative value.\n     */\n    template <typename... Ts>\n    UBS_NO_DISCARD OutputType derivative(const InputType& pos, int d, Ts... derivatives) const {\n        static_assert(1 + sizeof...(Ts) == InputDims, \"Invalid number of inputs specified.\");\n        const std::array<int, InputDims> derivs{d, derivatives...};\n        return derivative(pos, derivs);\n    }\n\n    /**\n     * @brief Evaluates the derivative of the spline at the specified position.\n     * @param[in] pos The position. Each value must be between lower bound and upper bound.\n     * @param[in] derivatives The partial derivatives.\n     * @return The derivative value.\n     */\n    UBS_NO_DISCARD OutputType derivative(const InputType& pos, const std::array<int, InputDims>& derivatives) const {\n        return evaluate(pos, [this, &derivatives](int dim, ValueType pos) {\n            const int derivative = derivatives[dim];\n            if (derivative == 0) {\n                return basisFunctions(pos);\n            }\n\n            return basisFunctionDerivatives(dim, derivative, pos);\n        });\n    }\n\n    /**\n     * @brief Evaluates the smoothness value.\n     *\n     * The smoothness value is defined as:\n     * @f[\n     * s_i = \\int_0^1 \\lVert f_i^{(n)}(\\mathbf{x}) \\rVert^2 \\mathbf{dx}\n     * @f]\n     *\n     * @tparam TotalDerivative The total derivative.\n     * @return The smoothness value in each dimension.\n     */\n    template <int TotalDerivative>\n    UBS_NO_DISCARD OutputType smoothness() const {\n        static_assert(TotalDerivative >= 0 && TotalDerivative <= 3, \"Unsupported derivative specified.\");\n        constexpr int MaxTotal = internal::TotalDerivative<InputDims, TotalDerivative>::NumPartialDerivatives;\n\n        OutputType res = FixedSizeContainerTypeTrait<OutputType>::zero();\n        internal::ComputeSmoothness<InputDims, TotalDerivative, MaxTotal, 0>::apply(\n            *this, controlPoints_.getStrides(), res);\n        return res;\n    }\n\n    /**\n     * @brief Evaluates the B-spline by calculating the basis and passes it to the evalFunction.\n     *\n     * This function iterates over the sums, which are needed to compute a B-spline. It calculates the basis value and\n     * for each calculated basis value it calls the eval function. The signature must be void(int idx, ValueType\n     * basisVal), where idx is the control point index and basisVal value which need to be multiplied with the control\n     * point.\n     *\n     * This function is mainly used if one would like to get the basis values and control points indices and defer the\n     * evaluation. This is usually the case during optimization.\n     *\n     * @param[in] pos The position. Each value must be between lower bound and upper bound.\n     * @param[in] basisFunction The basis function.\n     * @param[in] evalFunction The evaluation function.\n     */\n    template <typename BasisFunction, typename EvalFunction>\n    void evaluate(const InputType& pos, BasisFunction basisFunction, EvalFunction evalFunction) const {\n        const std::pair<int, InputType> startIndexValues = getStartIndexAndValues(pos);\n        evaluate(startIndexValues.first, startIndexValues.second, basisFunction, evalFunction);\n    }\n\n    /**\n     * @copybrief evaluate(const InputType& pos, BasisFunction basisFunction, EvalFunction evalFunction) const\n     *\n     * For more information see\n     * evaluate(const InputType& pos, BasisFunction basisFunction, EvalFunction evalFunction) const.\n     *\n     * @param[in] startIdx The start index returned by getStartIndexAndValues().\n     * @param[in] values The values returned by getStartIndexAndValues().\n     * @param[in] basisFunction The basis function.\n     * @param[in] evalFunction The evaluation function.\n     */\n    template <typename BasisFunction, typename EvalFunction>\n    void evaluate(int startIdx, const InputType& values, BasisFunction basisFunction, EvalFunction evalFunction) const {\n        const auto& strides = controlPoints_.getStrides();\n\n        std::array<BasisType, InputDims> fullBasis{};\n        for (int dim = 0; dim < InputDims; ++dim) {\n            fullBasis[dim] = basisFunction(dim, FixedSizeContainerTypeTrait<InputType>::get(values, dim));\n        }\n\n        using SplineType = UniformBSpline<ValueType_, Degree_, InputType_, OutputType_, ControlPointsType>;\n        internal::EvaluateBSpline<SplineType, InputDims, 0>::apply(\n            fullBasis, strides, startIdx, ValueType(1.0), evalFunction);\n    }\n\n    /**\n     * @brief Casts this spline to the spline specified in the template parameter SplineOut.\n     *\n     * The cast function copies the control points, the lower and upper bounds. The value type of the source and\n     * destination types must be convertible.\n     *\n     * @tparam SplineOut The spline to which this spline is casted to.\n     * @return The casted spline.\n     */\n    template <typename SplineOut,\n              typename = std::enable_if_t<\n                  std::is_same<UniformBSpline<ValueType_, Degree_, InputType_, OutputType_, ControlPointsType>,\n                               SplineOut>::value>>\n    UBS_NO_DISCARD const SplineOut& cast() {\n        return *this;\n    }\n\n    /** \\copydoc const SplineOut& cast() */\n    template <typename SplineOut,\n              typename = std::enable_if_t<\n                  !std::is_same<UniformBSpline<ValueType_, Degree_, InputType_, OutputType_, ControlPointsType>,\n                                SplineOut>::value>>\n    UBS_NO_DISCARD SplineOut cast() const {\n        using T = typename SplineOut::ValueType;\n        using OptSpline = SplineOut;\n        using OptInputType = typename OptSpline::InputType;\n        using OptOutputType = typename OptSpline::OutputType;\n        using OptControlPointsType = typename OptSpline::ControlPointsType;\n        using OptControlPointsContainerType = typename OptSpline::ControlPointsContainerType;\n        using OptInputContainerTrait = ubs::FixedSizeContainerTypeTrait<OptInputType>;\n        using OptOutputContainerTrait = ubs::FixedSizeContainerTypeTrait<OptOutputType>;\n\n        // Convert bounds.\n        OptInputType lowerBound{};\n        OptInputType upperBound{};\n        for (int i = 0; i < OptInputContainerTrait::Size; ++i) {\n            OptInputContainerTrait::get(lowerBound, i) = T(getLowerBound(i));\n            OptInputContainerTrait::get(upperBound, i) = T(getUpperBound(i));\n        }\n\n        OptControlPointsType controlPoints{};\n        ubs::ControlPointsTrait<OptControlPointsType>::resize(controlPoints, controlPoints_.getShape());\n        OptControlPointsContainerType controlPointsContainer(lowerBound, upperBound, std::move(controlPoints));\n\n        // Copy control points.\n        controlPoints_.transform(controlPointsContainer, [](const auto& p) {\n            OptOutputType v{};\n            for (int i = 0; i < OptOutputContainerTrait::Size; ++i) {\n                OptOutputContainerTrait::get(v, i) = T(ubs::FixedSizeContainerTypeTrait<OutputType>::get(p, i));\n            }\n            return v;\n        });\n\n        SplineOut splineOut(std::move(controlPointsContainer));\n        splineOut.setExtrapolate(extrapolate_);\n        return splineOut;\n    }\n\nprivate:\n    // Used for unit test of derivative factors.\n    FRIEND_TEST(UniformBSpline, DerivativeFactors);\n\n    /**\n     * @brief Evaluate the B-spline given a basis function.\n     *\n     * The evaluation of the function itself and the derivatives is similar, the basis function selects, which basis\n     * is used.\n     *\n     * @param[in] pos The position, at which the B-spline will be evaluated.\n     * @param[in] basisFunction The basis function. The signature must be @code BasisType(int dim, ValueType pos)\n     * @endcode\n     * @return The evaluated basis value.\n     */\n    template <typename BasisFunction>\n    UBS_NO_DISCARD OutputType evaluate(const InputType& pos, BasisFunction basisFunction) const {\n        OutputType res = FixedSizeContainerTypeTrait<OutputType>::zero();\n        evaluate(pos, basisFunction, [this, &res](int idx, ValueType basisVal) {\n            res += controlPoints_.at(idx) * basisVal;\n        });\n        return res;\n    }\n\n    /**\n     * @brief Determines the derivative factors.\n     *\n     * The derivative factors are the factor from deriving the vector\n     * @f[\n     * \\mathbf{x}(t) = \\begin{pmatrix} \\vdots  \\\\ t^2 \\\\ t \\\\ 1 \\end{pmatrix}\n     * @f]\n     * n times.\n     * As an example, the derivative factors for order 4 are:\n     * @f[\n     * \\begin{blockarray}{cccc}\n     * x^{(1)} & x^{(2)} & x^{(3)} & x^{(4)} \\\\\n     * \\begin{block}{(cccc)}\n     * 4 & 12 & 24 & 24 \\\\\n     * 3 &  6 &  6 &  0 \\\\\n     * 2 &  2 &  0 &  0 \\\\\n     * 1 &  0 &  0 &  0 \\\\\n     * \\end{block}\n     * \\end{blockarray}\n     * @f]\n     *\n     * @return The derivative factors.\n     */\n    UBS_NO_DISCARD Eigen::Matrix<ValueType, Degree, Degree> getDerivativeFactors() const {\n        Eigen::Matrix<int, Degree, Degree> derivativeFactors = Eigen::Matrix<int, Degree, Degree>::Zero();\n\n        for (int i = 0; i < Degree; ++i) {\n            derivativeFactors(i, 0) = Order - 1 - i;\n        }\n\n        for (int c = 1; c < Degree; ++c) {\n            for (int r = 0; r < Degree - c; ++r) {\n                derivativeFactors(r, c) = derivativeFactors(r, c - 1) * (Degree - r - c);\n            }\n        }\n\n        return derivativeFactors.template cast<ValueType>();\n    }\n\n    /** @brief The control points. */\n    ControlPointsContainerType controlPoints_;\n\n    /** @brief The uniform B-spline basis. */\n    Eigen::Matrix<ValueType, Order, Order> basis_{\n        internal::UniformBSplineBasis<Order>::matrix().template cast<ValueType>()};\n    /** @brief The derivative factors. */\n    Eigen::Matrix<ValueType, Degree, Degree> derivativeFactors_{getDerivativeFactors()};\n    /** @brief Flag, if spline extrapolation is enabled. If true, the spline can be evaluated outside of the bounds. */\n    bool extrapolate_{false};\n};\n} // namespace ubs\n\n#include \"internal/uniform_bspline_impl.hpp\"\n\nnamespace ubs {\n\n/**\n * @brief Using declaration for a spline @f$ \\mathbb{R} \\rightarrow \\mathbb{R} @f$.\n * @tparam ValueType_ The value type.\n * @tparam Degree_ The spline degree.\n */\ntemplate <typename ValueType, int Degree>\nusing UniformBSpline11 =\n    UniformBSpline<ValueType,\n                   Degree,\n                   ValueType,\n                   ValueType,\n                   std::vector<ValueType, typename FixedSizeContainerTypeTrait<ValueType>::Allocator>>;\n\n/**\n * @copybrief UniformBSpline11\n *\n * The value type is float.\n * @tparam Degree_ The spline degree.\n */\ntemplate <int Degree>\nusing UniformBSpline11f = UniformBSpline11<float, Degree>;\n\n/**\n * @copybrief UniformBSpline11\n *\n * The value type is double.\n * @tparam Degree_ The spline degree.\n */\ntemplate <int Degree>\nusing UniformBSpline11d = UniformBSpline11<double, Degree>;\n\n/**\n * @brief Using declaration for an Eigen spline @f$ \\mathbb{R}^n \\rightarrow \\mathbb{R}^m @f$.\n * @tparam ValueType_ The value type.\n * @tparam Degree_ The spline degree.\n * @tparam InputDims_ The input dimensions.\n * @tparam OutputDims_ The output dimensions.\n */\ntemplate <typename ValueType, int Degree, int InputDims, int OutputDims>\nusing EigenUniformBSpline =\n    UniformBSpline<ValueType, Degree, Eigen::Matrix<ValueType, InputDims, 1>, Eigen::Matrix<ValueType, OutputDims, 1>>;\n\n} // namespace ubs\n", "meta": {"hexsha": "0e33fd2f4c1ff18196b27a4be2c7d68569d3b3b8", "size": 27619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/uniform_bspline/uniform_bspline.hpp", "max_stars_repo_name": "KIT-MRT/uniform_bspline", "max_stars_repo_head_hexsha": "158f026f72849088351dc7b31f33ff5b6684965d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T00:13:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T09:22:33.000Z", "max_issues_repo_path": "include/uniform_bspline/uniform_bspline.hpp", "max_issues_repo_name": "KIT-MRT/uniform_bspline", "max_issues_repo_head_hexsha": "158f026f72849088351dc7b31f33ff5b6684965d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/uniform_bspline/uniform_bspline.hpp", "max_forks_repo_name": "KIT-MRT/uniform_bspline", "max_forks_repo_head_hexsha": "158f026f72849088351dc7b31f33ff5b6684965d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-16T15:17:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T09:22:34.000Z", "avg_line_length": 39.1758865248, "max_line_length": 120, "alphanum_fraction": 0.6581338933, "num_tokens": 6500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7057850340255385, "lm_q1q2_score": 0.6132049310352025}}
{"text": "#ifndef _SPHERE_MESH_GEN_IMPL_H_\n#define _SPHERE_MESH_GEN_IMPL_H_\n\n#include \"mtao/types.hpp\"\n#include <tuple>\n#include <array>\n#include <map>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <Eigen/Dense>\n\nnamespace mtao::geometry::mesh::shapes {\n    namespace detail {\n        template <typename Scalar_>\n            class SphereMeshFactory{\n                typedef std::array<unsigned int, 3> Face;\n                typedef std::array<unsigned int, 2> Edge;\n                public:\n                typedef Scalar_ Scalar;\n                typedef typename mtao::Vector<Scalar,3> Vector;\n                SphereMeshFactory(int depth=3);\n                void triforce(const Face & f, int depth);\n                unsigned int add_edge(Edge e);\n                void write(const std::string & filename);\n                void write(std::ostream & outstream);\n                const std::vector<Face> faces() const {return m_faces;}\n                const std::vector<Vector> vertices() const {return m_vertices;}\n\n            mtao::ColVectors<Scalar,3> V() const ;\n            mtao::ColVectors<int,3> F() const ;\n                private:\n                const int m_depth = 0;\n                mtao::vector<Vector> m_vertices;\n                mtao::vector<Face> m_faces;\n                std::map<Edge, unsigned int> m_edges;\n\n            };\n\n\n\n        template <typename T>\n            SphereMeshFactory<T>::SphereMeshFactory(int depth): m_depth(depth) {\n                //Create icosahedron base\n\n                Scalar gr = .5 * (1 + std::sqrt(Scalar(5)));\n                m_vertices.resize(12);\n\n                m_vertices[ 0] = Vector(     0,    - 1,     gr);\n                m_vertices[ 1] = Vector(    gr,      0,      1);\n                m_vertices[ 2] = Vector(    gr,      0,    - 1);\n                m_vertices[ 3] = Vector(   -gr,      0,    - 1);\n                m_vertices[ 4] = Vector(   -gr,      0,      1);\n                m_vertices[ 5] = Vector(   - 1,     gr,      0);\n                m_vertices[ 6] = Vector(     1,     gr,      0);\n                m_vertices[ 7] = Vector(     1,    -gr,      0);\n                m_vertices[ 8] = Vector(   - 1,    -gr,      0);\n                m_vertices[ 9] = Vector(     0,    - 1,    -gr);\n                m_vertices[10] = Vector(     0,      1,    -gr);\n                m_vertices[11] = Vector(     0,      1,     gr);\n                for(auto&& v: m_vertices) {\n                    v.normalize();\n                }\n\n                triforce({{ 1 ,  2 ,  6}},depth); \n                triforce({{ 1 ,  7 ,  2}},depth); \n                triforce({{ 3 ,  4 ,  5}},depth); \n                triforce({{ 4 ,  3 ,  8}},depth); \n                triforce({{ 6 ,  5 , 11}},depth); \n                triforce({{ 5 ,  6 , 10}},depth); \n                triforce({{ 9 , 10 ,  2}},depth); \n                triforce({{10 ,  9 ,  3}},depth); \n                triforce({{ 7 ,  8 ,  9}},depth); \n                triforce({{ 8 ,  7 ,  0}},depth); \n                triforce({{11 ,  0 ,  1}},depth); \n                triforce({{ 0 , 11 ,  4}},depth); \n                triforce({{ 6 ,  2 , 10}},depth); \n                triforce({{ 1 ,  6 , 11}},depth); \n                triforce({{ 3 ,  5 , 10}},depth); \n                triforce({{ 5 ,  4 , 11}},depth); \n                triforce({{ 2 ,  7 ,  9}},depth); \n                triforce({{ 7 ,  1 ,  0}},depth); \n                triforce({{ 3 ,  9 ,  8}},depth); \n                triforce({{ 4 ,  8 ,  0}},depth); \n\n\n\n            }\n        template <typename T>\n            void SphereMeshFactory<T>::triforce(const Face & f, int depth) {\n                if(depth <= 0) {\n                    m_faces.push_back(f);\n                } else {\n                    unsigned int e01 = add_edge({{f[0],f[1]}});\n                    unsigned int e12 = add_edge({{f[1],f[2]}});\n                    unsigned int e02 = add_edge({{f[0],f[2]}});\n                    triforce({{f[0],e01,e02}},depth-1);\n                    triforce({{f[1],e12,e01}},depth-1);\n                    triforce({{f[2],e02,e12}},depth-1);\n                    triforce({{e01 ,e12,e02}},depth-1);\n                }\n\n            }\n\n        template <typename T>\n            unsigned int SphereMeshFactory<T>::add_edge(Edge e) {\n                if(e[0] > e[1]) {\n                    unsigned int tmp = e[0];\n                    e[0] = e[1];\n                    e[1] = tmp;\n                }\n                auto it = m_edges.find(e);\n                if(it != m_edges.end()) {\n                    return it->second;\n                } else {\n                    m_edges[e] = m_vertices.size();\n                    m_vertices.push_back(\n                            (m_vertices[e[0]] + m_vertices[e[1]]).normalized()\n                            );\n                    return m_vertices.size()-1;\n                }\n\n\n            }\n\n        template <typename T>\n            mtao::ColVectors<T,3> SphereMeshFactory<T>::V() const {\n            mtao::ColVectors<T,3> v(3,m_vertices.size());\n                for(size_t i = 0; i < m_vertices.size(); ++i) {\n                    v.col(i) = m_vertices[i];\n                }\n                return v;\n            }\n\n        template <typename T>\n            mtao::ColVectors<int,3> SphereMeshFactory<T>::F() const {\n                mtao::ColVectors<int,3> f(3,m_faces.size());\n                for(size_t i = 0; i < m_faces.size(); ++i) {\n                    f.col(i) = Eigen::Map<const mtao::Vector<unsigned int,3>>(m_faces[i].data()).cast<int>();\n                }\n                return f;\n            }\n\n    }\n\n}\n#endif\n", "meta": {"hexsha": "b71cc4d51c47c21690fe2f79cf70b6eb3630d2b1", "size": 5602, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/mesh/shapes/sphere_ipl.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/geometry/mesh/shapes/sphere_ipl.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/mesh/shapes/sphere_ipl.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": 37.8513513514, "max_line_length": 109, "alphanum_fraction": 0.4164584077, "num_tokens": 1501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6132049286380209}}
{"text": "// Author: Tucker Haydon\n\n#include <iostream>\n#include <cstdlib>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <osqp.h>\n\n#include \"polynomial_solver.h\"\n#include \"common.h\"\n\nnamespace p4 {\n  namespace {\n    // Helper structure that contains pre-computed constants\n    struct Constants {   \n      size_t num_dimensions;\n      size_t polynomial_order;\n      size_t derivative_order;\n      size_t continuity_order;\n      size_t num_intermediate_points;\n      size_t num_nodes;\n      size_t num_segments;\n      size_t num_params_per_node_per_dim;\n      size_t num_params_per_segment_per_dim;\n      size_t num_params_per_node;\n      size_t num_params_per_segment;\n      size_t total_num_params;\n      size_t num_constraints;\n    };\n\n    // Generates a square matrix that is the integrated form of d^n/dt^n [p(x)'p(x)].\n    // The derivative of this matrix can be easily calculated by computing the\n    // zeroth derivative of the matrix, padding the first n rows and columns\n    // with zeros, and shifting the matrix down and to the right by n\n    // rows/columns.\n    //\n    // See the theory documentation for further details.\n    Eigen::MatrixXd QuadraticMatrix(\n        const size_t polynomial_order,\n        const size_t derivative_order,\n        const double dt) {\n      Eigen::MatrixXd base_integrated_quadratic_matrix;\n      base_integrated_quadratic_matrix.resize(polynomial_order + 1, polynomial_order + 1);\n      base_integrated_quadratic_matrix.fill(0);\n      for(size_t row = 0; row < polynomial_order + 1; ++row) {\n        for(size_t col = 0; col < polynomial_order + 1; ++col) {\n          base_integrated_quadratic_matrix(row, col) = \n            std::pow(dt, row + col + 1) \n            / Factorial(row) \n            / Factorial(col) \n            / (row + col + 1);\n        }\n      }\n    \n      // Vector of ones\n      Eigen::MatrixXd ones_vec;\n      ones_vec.resize(polynomial_order + 1 - derivative_order, 1);\n      ones_vec.fill(1);\n    \n      // Shift the matrix down rows\n      Eigen::MatrixXd row_shift_mat;\n      row_shift_mat.resize(polynomial_order + 1, polynomial_order + 1);\n      row_shift_mat.fill(0);\n      row_shift_mat.diagonal(-1*derivative_order) = ones_vec;\n    \n      // Shift the matrix right cols\n      Eigen::MatrixXd col_shift_mat;\n      col_shift_mat.resize(polynomial_order + 1, polynomial_order + 1);\n      col_shift_mat.fill(0);\n      col_shift_mat.diagonal(+1*derivative_order) = ones_vec;\n    \n      Eigen::MatrixXd integrated_quadratic_matrix;\n      integrated_quadratic_matrix.resize(polynomial_order + 1, polynomial_order + 1);\n      integrated_quadratic_matrix = row_shift_mat * base_integrated_quadratic_matrix * col_shift_mat;\n    \n      return integrated_quadratic_matrix;\n    }\n\n    // Sets the upper and lower bound vectors for the equality and continuity\n    // constraints.\n    void SetConstraints(\n        const Constants& constants,\n        const std::vector<double>& times,\n        const std::vector<NodeEqualityBound>& explicit_node_equality_bounds, \n        const std::vector<NodeInequalityBound>& explicit_node_inequality_bounds,\n        const std::vector<SegmentInequalityBound>& explicit_segment_inequality_bounds,\n        Eigen::MatrixXd& lower_bound_vec, \n        Eigen::MatrixXd& upper_bound_vec,\n        std::vector<Eigen::Triplet<double>>& constraint_triplets\n        ) {\n      size_t constraint_idx = 0;\n      for(size_t dimension_idx = 0; dimension_idx < constants.num_dimensions; ++dimension_idx) { \n        for(size_t node_idx = 0; node_idx < constants.num_nodes; ++node_idx) {\n          for(size_t derivative_idx = 0; derivative_idx < constants.num_params_per_segment_per_dim; ++derivative_idx) {\n\n            // Equality Constraints\n            for(const NodeEqualityBound& bound: explicit_node_equality_bounds) {\n              if(\n                  false == (bound.node_idx == node_idx) ||\n                  false == (bound.dimension_idx == dimension_idx) || \n                  false == (bound.derivative_idx == derivative_idx)) {\n                continue;\n              }\n              else {\n                const double alpha = node_idx+1 < constants.num_nodes ? (times[node_idx + 1] - times[node_idx]) : 1;\n\n                // Bounds. Scaled by alpha. See documentation.\n                lower_bound_vec(constraint_idx,0) = bound.value * std::pow(alpha, derivative_idx);\n                upper_bound_vec(constraint_idx,0) = bound.value * std::pow(alpha, derivative_idx);\n\n                // Constraints\n                size_t parameter_idx = 0 \n                  + derivative_idx \n                  + constants.num_params_per_node_per_dim * node_idx\n                  + constants.num_params_per_node_per_dim * constants.num_nodes * dimension_idx;\n                constraint_triplets.emplace_back(constraint_idx, parameter_idx, 1);\n\n                constraint_idx++;\n              }\n            }\n\n            // Node inequality bound constraints\n            for(const NodeInequalityBound& bound: explicit_node_inequality_bounds) {\n              if(\n                  false == (bound.node_idx == node_idx) ||\n                  false == (bound.dimension_idx == dimension_idx) || \n                  false == (bound.derivative_idx == derivative_idx)) {\n                continue;\n              }\n              else {\n                const double alpha = node_idx+1 < constants.num_nodes ? (times[node_idx + 1] - times[node_idx]) : 1;\n\n                // Bounds. Scaled by alpha. See documentation.\n                lower_bound_vec(constraint_idx,0) = bound.lower * std::pow(alpha, derivative_idx);\n                upper_bound_vec(constraint_idx,0) = bound.upper * std::pow(alpha, derivative_idx);\n\n                // Constraints\n                size_t parameter_idx = 0 \n                  + derivative_idx \n                  + constants.num_params_per_node_per_dim * node_idx\n                  + constants.num_params_per_node_per_dim * constants.num_nodes * dimension_idx;\n                constraint_triplets.emplace_back(constraint_idx, parameter_idx, 1);\n\n                constraint_idx++;\n              }\n            }\n          }\n\n          // Continuity constraints\n          if(node_idx < constants.num_segments) {\n            const size_t num_continuity_constraints = constants.continuity_order + 1;\n            constexpr double delta_t = 1.0;\n            const double alpha_k = times[node_idx + 1] - times[node_idx];\n            const double alpha_kp1 = node_idx + 2 < constants.num_nodes ? times[node_idx + 2] - times[node_idx + 1] : 1.0;\n\n\n            for(size_t continuity_idx = 0; continuity_idx < num_continuity_constraints; ++continuity_idx) {\n              // Bounds\n              lower_bound_vec(constraint_idx,0) = 0;\n              upper_bound_vec(constraint_idx,0) = 0;\n\n              // Constraints. Scaled by alpha. See documentation.\n              // Propagate the current node\n              Eigen::MatrixXd segment_propagation_coefficients;\n              segment_propagation_coefficients.resize(1, constants.num_params_per_segment_per_dim);\n              segment_propagation_coefficients.fill(0);\n              segment_propagation_coefficients \n                = TimeVector(constants.polynomial_order, continuity_idx, delta_t).transpose()\n                / std::pow(alpha_k, continuity_idx);\n\n              // Minus the next node\n              Eigen::MatrixXd segment_terminal_coefficients;\n              segment_terminal_coefficients.resize(1, constants.num_params_per_segment_per_dim);\n              segment_terminal_coefficients.fill(0);\n              segment_terminal_coefficients(0,continuity_idx) = -1 / std::pow(alpha_kp1, continuity_idx);\n\n              size_t current_segment_idx = 0 \n                // Get to the right dimension\n                + constants.num_params_per_node_per_dim * constants.num_nodes * dimension_idx\n                // Get to the right node\n                + constants.num_params_per_node_per_dim * node_idx;\n              size_t next_segment_idx = 0\n                // Get to the right dimension\n                + constants.num_params_per_node_per_dim * constants.num_nodes * dimension_idx\n                // Get to the right node\n                + constants.num_params_per_node_per_dim * (node_idx + 1);\n\n              for(size_t param_idx = 0; param_idx < constants.num_params_per_segment_per_dim; ++param_idx) {\n                constraint_triplets.emplace_back(\n                    constraint_idx, \n                    current_segment_idx + param_idx, \n                    segment_propagation_coefficients(0, param_idx));\n                // TODO: Just insert one terminal constraint\n                constraint_triplets.emplace_back(\n                    constraint_idx, \n                    next_segment_idx + param_idx, \n                    segment_terminal_coefficients(0, param_idx));\n              }\n\n              constraint_idx++;\n            }\n          }\n        }\n      }\n\n      // Include start- and end-points in segment constraints. When constraining\n      // a segment, also constrain the endpoints of the segment to the same\n      // value. If this were not the case, the following situation could occur:\n      // the start endpoint is constrained to -2, but the following segment is\n      // constrained above zero. Clearly, there is no smooth solution that\n      // permits this. \n      // \n      // Add two to account for the endpoints and then remove one to convert\n      // from the number of points the the number of segments. Divide the\n      // segment length (1) by the number of segments to get the length of each\n      // intermediate segment.\n      const double dt = 1.0 / (constants.num_intermediate_points + 2 - 1);\n\n      // Segment lower bound constraints\n      for(const SegmentInequalityBound& bound: explicit_segment_inequality_bounds) {\n        const double alpha = times[bound.segment_idx+1] - times[bound.segment_idx];\n\n        // point_idx == intermediate_point_idx\n        // Add 2 for start and end points\n        for(size_t point_idx = 0; point_idx < constants.num_intermediate_points+2; ++point_idx)  {\n          // Bounds\n          lower_bound_vec(constraint_idx,0) = -SegmentInequalityBound::INFTY;\n          upper_bound_vec(constraint_idx,0) = bound.value * std::pow(alpha, bound.derivative_idx);\n\n          // Time at a specific point\n          double time = point_idx * dt;\n\n          Eigen::MatrixXd segment_propagation_coefficients;\n          segment_propagation_coefficients.resize(1, constants.num_params_per_segment_per_dim);\n          segment_propagation_coefficients.fill(0);\n          segment_propagation_coefficients \n            = TimeVector(constants.polynomial_order, bound.derivative_idx, time).transpose();\n\n          for(size_t dimension_idx = 0; dimension_idx < constants.num_dimensions; ++dimension_idx) {\n            Eigen::MatrixXd transform_coefficients;\n            transform_coefficients.resize(1, constants.num_params_per_segment_per_dim);\n            transform_coefficients.fill(0);\n            transform_coefficients = bound.mapping(dimension_idx, 0) \n              * segment_propagation_coefficients;\n\n            size_t current_segment_idx = 0 \n              // Get to the right dimension\n              + constants.num_params_per_node_per_dim * constants.num_nodes * dimension_idx\n              // Get to the right node\n              + constants.num_params_per_segment_per_dim * bound.segment_idx;\n\n            for(size_t param_idx = 0; param_idx < constants.num_params_per_segment_per_dim; ++param_idx) {\n              constraint_triplets.emplace_back(\n                  constraint_idx, \n                  current_segment_idx + param_idx, \n                  transform_coefficients(0, param_idx));\n            }\n          }\n\n          constraint_idx++;\n        }\n      }\n    }\n\n    void SetQuadraticCost(\n        const Constants& constants,\n        std::vector<Eigen::Triplet<double>>& quadratic_triplets) {\n      const double delta_t = 1.0;\n      const Eigen::MatrixXd quadratic_matrix = QuadraticMatrix(constants.polynomial_order, constants.derivative_order, delta_t);\n\n      for(size_t dimension_idx = 0; dimension_idx < constants.num_dimensions; ++dimension_idx) {\n        // No cost for final node\n        for(size_t node_idx = 0; node_idx < constants.num_nodes - 1; ++node_idx) {\n          const size_t parameter_idx = 0\n            // Get to the right dimension\n            + constants.num_params_per_node_per_dim * constants.num_nodes * dimension_idx\n            // Get to the right node\n            + constants.num_params_per_node_per_dim * node_idx;\n          for(size_t row = 0; row < constants.num_params_per_node_per_dim; ++row) {\n            for(size_t col = 0; col < constants.num_params_per_node_per_dim; ++col) { \n              quadratic_triplets.emplace_back(\n                  row + parameter_idx, \n                  col + parameter_idx, \n                  quadratic_matrix(row,col)\n                  );\n            }\n          }\n        }\n      }\n    }\n\n    // Converts an en eigen sparse matrix into an OSQP sparse matrix\n    // Reference: https://github.com/robotology/osqp-eigen\n    void Eigen2OSQP(\n        const Eigen::SparseMatrix<double> eigen_sparse_mat,\n        csc*& osqp_mat) {\n\n      // get number of row, columns and nonZeros from Eigen SparseMatrix\n      c_int rows   = eigen_sparse_mat.rows();\n      c_int cols   = eigen_sparse_mat.cols();\n      c_int num_nz = eigen_sparse_mat.nonZeros();\n    \n      // get inner and outer index\n      const int* innerIndexPtr    = eigen_sparse_mat.innerIndexPtr();\n      const int* outerIndexPtr    = eigen_sparse_mat.outerIndexPtr();\n      const int* innerNonZerosPtr = eigen_sparse_mat.innerNonZeroPtr();\n    \n      // get nonzero values\n      const double* valuePtr = eigen_sparse_mat.valuePtr();\n    \n      // Allocate memory for csc matrix\n      if(osqp_mat != nullptr){\n        std::cerr << \"osqp_mat pointer is not a null pointer! \" << std::endl;\n        std::exit(EXIT_FAILURE);\n      }\n    \n      osqp_mat = csc_spalloc(rows, cols, num_nz, 1, 0);\n    \n      int innerOsqpPosition = 0;\n      for(int k = 0; k < cols; ++k) {\n          if (eigen_sparse_mat.isCompressed()) {\n              osqp_mat->p[k] = static_cast<c_int>(outerIndexPtr[k]);\n          } else {\n              if (k == 0) {\n                  osqp_mat->p[k] = 0;\n              } else {\n                  osqp_mat->p[k] = osqp_mat->p[k-1] + innerNonZerosPtr[k-1];\n              }\n          }\n          for (typename Eigen::SparseMatrix<double>::InnerIterator it(eigen_sparse_mat,k); it; ++it) {\n              osqp_mat->i[innerOsqpPosition] = static_cast<c_int>(it.row());\n              osqp_mat->x[innerOsqpPosition] = static_cast<c_float>(it.value());\n              innerOsqpPosition++;\n          }\n      }\n      osqp_mat->p[static_cast<int>(cols)] = static_cast<c_int>(innerOsqpPosition);\n    }\n  }\n\n\n  PolynomialSolver::Solution PolynomialSolver::Run(\n      const std::vector<double>& times,\n      const std::vector<NodeEqualityBound>& explicit_node_equality_bounds,\n      const std::vector<NodeInequalityBound>& explicit_node_inequality_bounds,\n      const std::vector<SegmentInequalityBound>& explicit_segment_inequality_bounds) {\n\n    this->options_.Check();\n\n    if(times.size() < 2) {\n      std::cerr << \"PolynomialSolver::Run -- Time vector must have a size greater than one.\" << std::endl;\n      std::exit(EXIT_FAILURE);\n    }\n\n    Constants constants;\n    constants.num_dimensions = this->options_.num_dimensions;\n    constants.polynomial_order = this->options_.polynomial_order;\n    constants.derivative_order = this->options_.derivative_order;\n    constants.continuity_order = this->options_.continuity_order;\n    constants.num_intermediate_points = this->options_.num_intermediate_points;\n    constants.num_nodes = times.size();\n    constants.num_segments = constants.num_nodes - 1;\n    constants.num_params_per_node_per_dim = constants.polynomial_order + 1;\n    constants.num_params_per_segment_per_dim = constants.polynomial_order + 1;\n    constants.num_params_per_node = constants.num_dimensions * constants.num_params_per_node_per_dim;\n    constants.num_params_per_segment = constants.num_dimensions * constants.num_params_per_segment_per_dim;\n    constants.total_num_params = constants.num_params_per_node * constants.num_nodes;\n\n    // Explicit constraints are provided\n    const size_t num_explicit_constraints = 0\n      + explicit_node_equality_bounds.size() \n      + explicit_node_inequality_bounds.size() \n      + explicit_segment_inequality_bounds.size() * (constants.num_intermediate_points+2);\n\n    // Implicit constraints are continuity constraints\n    const size_t num_implicit_constraints = constants.num_segments*(constants.continuity_order+1)*constants.num_dimensions;\n\n    constants.num_constraints = num_explicit_constraints + num_implicit_constraints;\n\n    /*\n     * CONSTRAINTS\n     */\n    Eigen::MatrixXd lower_bound_vec, upper_bound_vec;\n    lower_bound_vec.resize(constants.num_constraints, 1);\n    upper_bound_vec.resize(constants.num_constraints, 1);\n\n    std::vector<Eigen::Triplet<double>> constraint_triplets;\n    SetConstraints(\n        constants, \n        times,\n        explicit_node_equality_bounds,\n        explicit_node_inequality_bounds,\n        explicit_segment_inequality_bounds,\n        lower_bound_vec, \n        upper_bound_vec, \n        constraint_triplets);\n\n    // Triplets to sparse mat\n    Eigen::SparseMatrix<double> sparse_constraint_mat(\n        constants.num_constraints, \n        constants.total_num_params);\n    sparse_constraint_mat.setFromTriplets(\n        constraint_triplets.begin(), \n        constraint_triplets.end());\n\n    /*\n     * QUADRATIC MATRIX\n     */\n    std::vector<Eigen::Triplet<double>> quadratic_triplets;\n    SetQuadraticCost(constants, quadratic_triplets);\n\n    // Triplets to sparse mat\n    Eigen::SparseMatrix<double> sparse_quadratic_mat(\n        constants.total_num_params, \n        constants.total_num_params);\n    sparse_quadratic_mat.setFromTriplets(\n        quadratic_triplets.begin(), \n        quadratic_triplets.end());\n\n    /*\n     * CONVERT EIGEN TO OSQP\n     */\n    csc* P = nullptr;\n    csc* A = nullptr;\n\n    Eigen2OSQP(sparse_quadratic_mat, P);\n    Eigen2OSQP(sparse_constraint_mat, A);\n\n    c_float q[constants.total_num_params];\n    for(size_t param_idx = 0; param_idx < constants.total_num_params; ++param_idx) {\n      q[param_idx] = 0;\n    }\n\n    c_float l[constants.num_constraints], u[constants.num_constraints];\n    for(size_t row_idx = 0; row_idx < constants.num_constraints; ++row_idx) {\n      l[row_idx] = lower_bound_vec(row_idx, 0);\n      u[row_idx] = upper_bound_vec(row_idx, 0);\n    }\n\n    /*\n     * RUN THE SOLVER\n     */\n    // Allocate and populate data\n    std::shared_ptr<OSQPData> data = std::shared_ptr<OSQPData>(\n        (OSQPData *)c_malloc(sizeof(OSQPData)),\n        [](OSQPData* data) {\n          c_free(data->A);\n          c_free(data->P);\n        });\n    data->n = constants.total_num_params;\n    data->m = constants.num_constraints;\n    data->P = P;\n    data->q = q;\n    data->A = A;\n    data->l = l;\n    data->u = u;\n\n    // Allocate and prepare workspace\n    // Workspace shared pointer requires custom destructor\n    PolynomialSolver::Solution solution;\n    solution.num_dimensions   = constants.num_dimensions;\n    solution.polynomial_order = constants.polynomial_order;\n    solution.num_nodes        = constants.num_nodes;\n    solution.workspace =  std::shared_ptr<OSQPWorkspace>(\n        osqp_setup(data.get(), &this->options_.osqp_settings),\n        [](OSQPWorkspace* workspace) { \n          osqp_cleanup(workspace);\n        });\n\n    // Solve\n    osqp_solve(solution.workspace.get());\n\n    // Return the solution\n    return solution;\n  }\n\n  void PolynomialSolver::Options::Check() {\n    if(this->num_dimensions < 1) {\n      std::cerr << \"PolynomialSolver::Options::Check -- Number of dimensions must be greater than zero.\" << std::endl;\n      std::exit(EXIT_FAILURE);\n    }\n  }\n\n  std::vector<std::vector<Eigen::VectorXd>> PolynomialSolver::Solution::Coefficients() const {\n    const size_t num_segments                   = this->num_nodes - 1;\n    const size_t num_params_per_node_per_dim    = this->polynomial_order + 1;\n    const size_t num_params_per_segment_per_dim = this->polynomial_order + 1;\n    const size_t num_params_per_node            = this->num_dimensions * num_params_per_node_per_dim;\n    const size_t num_params_per_segment         = this->num_dimensions * num_params_per_segment_per_dim;\n    const size_t total_num_params               = this->num_nodes * num_params_per_node;\n\n    std::vector<std::vector<Eigen::VectorXd>> coefficients;\n\n    coefficients.resize(this->num_dimensions);\n    for(size_t dimension_idx = 0; dimension_idx < this->num_dimensions; ++dimension_idx) {\n      coefficients[dimension_idx].resize(this->num_nodes);\n      for(size_t node_idx = 0; node_idx < this->num_nodes; ++node_idx) {\n        coefficients[dimension_idx][node_idx].resize(num_params_per_node_per_dim);\n        for(size_t coefficient_idx = 0; coefficient_idx < num_params_per_node_per_dim; ++coefficient_idx) {\n          const size_t parameter_idx = 0\n            // Get to the right dimension\n            + num_params_per_node_per_dim * this->num_nodes * dimension_idx\n            // Get to the right node\n            + num_params_per_node_per_dim * node_idx\n            // Get to the right parameter idx\n            + coefficient_idx;\n\n          coefficients[dimension_idx][node_idx](coefficient_idx)\n            = this->workspace->solution->x[parameter_idx];\n        }\n      }\n    }\n    return coefficients;\n  }\n\n  Eigen::VectorXd PolynomialSolver::Solution::Coefficients(\n      const size_t dimension_idx, \n      const size_t node_idx) const {\n    const size_t num_segments                   = this->num_nodes - 1;\n    const size_t num_params_per_node_per_dim    = this->polynomial_order + 1;\n    const size_t num_params_per_segment_per_dim = this->polynomial_order + 1;\n    const size_t num_params_per_node            = this->num_dimensions * num_params_per_node_per_dim;\n    const size_t num_params_per_segment         = this->num_dimensions * num_params_per_segment_per_dim;\n    const size_t total_num_params               = this->num_nodes * num_params_per_node;\n\n    Eigen::VectorXd coefficients;\n    coefficients.resize(num_params_per_node_per_dim);\n    for(size_t coefficient_idx = 0; coefficient_idx < num_params_per_node_per_dim; ++coefficient_idx) {\n      const size_t parameter_idx = 0\n        // Get to the right dimension\n        + num_params_per_node_per_dim * this->num_nodes * dimension_idx\n        // Get to the right node\n        + num_params_per_node_per_dim * node_idx\n        // Get to the right parameter idx\n        + coefficient_idx;\n\n      coefficients(coefficient_idx)\n        = this->workspace->solution->x[parameter_idx];\n    }\n\n    return coefficients;\n  }\n}\n\n", "meta": {"hexsha": "d75085e339ff3b4924a8c8f11673e50f4adf694f", "size": 22910, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/polynomial_solver.cc", "max_stars_repo_name": "TuckerHaydon/MinimumSnap", "max_stars_repo_head_hexsha": "474ec8edfec45adb4291f945736772c335dc9cc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T07:14:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T03:37:48.000Z", "max_issues_repo_path": "src/polynomial_solver.cc", "max_issues_repo_name": "TuckerHaydon/MinimumSnap", "max_issues_repo_head_hexsha": "474ec8edfec45adb4291f945736772c335dc9cc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T23:00:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T18:37:04.000Z", "max_forks_repo_path": "src/polynomial_solver.cc", "max_forks_repo_name": "TuckerHaydon/MinimumSnap", "max_forks_repo_head_hexsha": "474ec8edfec45adb4291f945736772c335dc9cc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-04-18T21:44:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-05T09:55:09.000Z", "avg_line_length": 41.9597069597, "max_line_length": 128, "alphanum_fraction": 0.6501091227, "num_tokens": 5034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6132049250760493}}
{"text": "/* Copyright (C) 2017 Nikolai Pakhtusov - All Rights Reserved\n * You may use, distribute and modify this code under the\n * terms of the MIT license.\n *\n * You should have received a copy of the MIT license with\n * this file. If not, please write to: chesterlanduk@gmail.com\n */\n\n#include <vector>\n// TODO: actually it is not an experimental/optional;\n// TODO: In c++17 it is just <optional> but it is not working\n#include <experimental/optional>\n\n#include <cv.h>\n#include <opencv2/imgcodecs.hpp>\n\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include \"help_funcs.cpp\"\n\n\nusing std::experimental::optional;\nusing std::pair;\nusing std::numeric_limits;\n\nusing cv::Mat;\nusing cv::Point;\n\nusing namespace boost::numeric::ublas;\n\nusing Real = float;\n\n\n#define ASSUMED_DEGREE 30\n\n#define MINIMAL_TRIANGLE_AREA 1000\n\n//#define DEBUG_MODE\n\n#define TEST_MODE\n\nenum Side {\n    Right,\n    Left\n};\n\n\ntemplate<typename T1, typename T2>\noptional<T2> operator>>(optional<T1> a, std::function< optional<T2>(T1)> f) {\n    if(a) return f(*a);\n    return optional<T2>{};\n}\n\n\nstd::pair<Real, Real> findEquiationCoeffs(cv::Vec4i points){\n\n    int x1, y1, x2, y2;\n\n    x1 = points[0];\n    y1 = points[1];\n    x2 = points[2];\n    y2 = points[3];\n\n    Real k = ((Real) (y2 - y1)) /\n             ((Real) (x2 - x1));\n    Real b = - ((Real) (x1 * (y2 - y1)) /\n                (Real) (x2 - x1))\n             + y1;\n\n    return std::make_pair(k, b);\n};\n\n\n// \u0442\u043e\u0447\u043a\u0438 \u0441\u0445\u043e\u0434\u0430\n// birds eye view\n\noptional<pair<Real, Real>>\nfindIntersectionPoint(const std::vector<cv::Vec4i>& lines){\n\n    if (lines.size() < 2){\n        return std::experimental::nullopt;\n    }\n\n    // TODO: get special lines (instead of two first)\n    auto [k1, b1] = findEquiationCoeffs(lines[0]);\n    auto [k2, b2] = findEquiationCoeffs(lines[1]);\n\n    // TODO: use special library for it (for example LAPACK)\n    //    matrix<Real> A = identity_matrix<Real>(2);\n    //    A(0, 0) = k1; A(0, 1) = b1;\n    //    A(0, 0) = k1; A(0, 1) = b1;\n    Real x = (b2 - b1) / (k1 - k2);\n    Real y = k1 * x + b1;\n\n    return std::make_pair(x, y);\n}\n\n\nvoid filterBadLines(std::vector<cv::Vec4i>& lines){\n    auto isBadLine = [](const cv::Vec4i& line) -> bool{\n        // We think it is bad when it is more then ASSUMED_DEGREE - 1\n        auto [k, b] = findEquiationCoeffs(line);\n//        cout << \"k: \" << k << \" b: \" << b << endl;\n        double tangent = tan(M_PI * (Real)(ASSUMED_DEGREE + 1)/180);\n        if (k < 0){\n            if (k > -tangent){\n                return true;\n            }\n        }\n        if (k > 0){\n            if (k > tangent){\n                return true;\n            }\n        }\n        return false;\n//        int x1 = line[0];\n//        int y1 = line[1];\n//        int x2 = line[2];\n//        int y2 = line[3];\n//\n//        int catheter1 = abs(x1 - x2);\n//        int catheter2 = abs(y1 - y2);\n//\n//        if (catheter2 == 0){\n//            return false;\n//        }\n////        cout << (1/sqrt(3)) << endl;\n////        cout << catheter1/catheter2 << endl;\n//        if ((Real)catheter2/(Real)catheter1 < (1/sqrt(3))){\n//            cout << (Real)catheter1/(Real)catheter2 << endl;\n//            return true;\n//        }\n//\n//        return false;\n\n    };\n\n    std::remove_if(lines.begin(), lines.end(), isBadLine);\n\n    auto isOnOneLine = [](const cv::Vec4i& line1, const cv::Vec4i& line2){\n        int Ax = line1[0];\n        int Ay = line1[1];\n        int Bx = line1[2];\n        int By = line1[3];\n\n        int Cx1 = line2[0];\n        int Cy1 = line2[1];\n\n        int Cx2 = line2[2];\n        int Cy2 = line2[3];\n        // Are of triangle is: [ Ax * (By - Cy) + Bx * (Cy - Ay) + Cx * (Ay - By) ] / 2\n        float area1 = (Ax * (By - Cy1) + Bx * (Cy1 - Ay) + Cx1 * (Ay - By)) / 2;\n        float area2 = (Ax * (By - Cy2) + Bx * (Cy2 - Ay) + Cx2 * (Ay - By)) / 2;\n\n        if (area1 < MINIMAL_TRIANGLE_AREA && area2 < MINIMAL_TRIANGLE_AREA){\n            return true;\n        }\n        return false;\n    };\n\n\n    if (lines.size() < 2){\n        throw std::exception();\n    }\n\n    auto iter = std::begin(lines) + 1;\n    for(; iter != std::end(lines);) {\n        if(isOnOneLine(lines[0], *iter)){\n            lines.erase(iter);\n        } else {\n            ++iter;\n            break;\n        }\n    }\n}\n\n\nMat prepareBeforeLinesFinding(const Mat& image){\n    Mat tempImg, destImg;\n    cv::cvtColor(image, tempImg, cv::COLOR_BGR2BGRA);\n    cv::Canny(tempImg, destImg, 1000, 10, 3);\n    return destImg;\n}\n\n\nstd::vector<cv::Vec4i> findLines(Mat& image){\n\n    int minLineLength = 200;\n    int maxLineGap = 25;\n\n    std::vector<cv::Vec4i> lines;\n\n    cv::HoughLinesP(image, lines, 1, M_PI/180, 100, minLineLength, maxLineGap);\n\n    return lines;\n}\n\n\nMat generateMatrix(const Mat& source, int beta_){\n    int alpha_=90;\n    int f_ = 500, dist_ = 500;\n\n    Real f, dist;\n    Real alpha, beta, gamma;\n    beta = ((Real)beta_ - 90)*M_PI/180;\n    f = (Real) f_;\n    dist = (Real) dist_;\n\n    cv::Size taille = source.size();\n    Real w = (Real)taille.width, h = (Real)taille.height;\n\n    // Projection 2D -> 3D matrix\n    Mat A1 = (cv::Mat_<Real>(4,3) <<\n            1, 0, -w/2,\n            0, 1, -h/2,\n            0, 0,    0,\n            0, 0,    1);\n\n    // Rotation matrices around the Y axe\n    Mat R = (cv::Mat_<Real>(4, 4) <<\n            cos(beta), 0, -sin(beta), 0,\n            0,         1,          0, 0,\n            sin(beta), 0,  cos(beta), 0,\n            0,         0,          0, 1);\n\n    // Translation matrix on the Z axis change dist will change the height\n    Mat T = (cv::Mat_<Real>(4, 4) <<\n            1, 0, 0,    0,\n            0, 1, 0,    0,\n            0, 0, 1, dist,\n            0, 0, 0,    1);       // Camera Intrisecs matrix 3D -> 2D\n    // 500 was f; f was from 1 to 2000 (magic-magic amm)\n    Mat A2 = (cv::Mat_<Real>(3,4) <<\n            500, 0, w/2, 0,\n            0, 500, h/2, 0,\n            0, 0,   1, 0);\n\n    Mat transfo = A2 * (T * (R * A1));\n\n    return transfo;\n}\n\n\nMat transformation(const Mat& source, int beta_){\n\n    auto transfo = generateMatrix(source, beta_);\n\n    Mat destination;\n\n    cv::warpPerspective(source, destination, transfo, source.size(), cv::INTER_CUBIC);\n\n    return destination;\n}\n\n\nvoid fixImage(const Mat& image, std::function<void (Mat&, int)> callback){\n\n    auto specialImg = prepareBeforeLinesFinding(image);\n#ifdef DEBUG_MODE\n    draw(specialImg);\n#endif\n\n    int defaultBeta = 90;\n    int beta;\n\n    auto lines = findLines(specialImg);\n#ifdef DEBUG_MODE\n    auto tempImg = image;\n    for(auto&l : lines){\n        line( tempImg, Point(l[0], l[1]),\n              Point(l[2], l[3]), cv::Scalar(0, 255, 0), 2, 8 );\n    }\n    draw(tempImg);\n#endif\n    assert(lines.size() > 1);\n    filterBadLines(lines);\n#ifdef DEBUG_MODE\n    for(auto&l : lines){\n        line( tempImg, Point(l[0], l[1]),\n              Point(l[2], l[3]), cv::Scalar(0, 255, 255), 2, 8 );\n    }\n    draw(tempImg);\n#endif\n\n    auto findSide = [](cv::Vec4i line, int x) -> Side {\n        if(line[0] > x && line[2] > x){\n            return Side::Left;\n        }\n        return Side::Right;\n    };\n\n    auto [x, y] = findIntersectionPoint(lines)\n            .value_or(std::make_pair(0, 0));\n\n    Side prevSide = findSide(lines[0], x);\n\n    for (int stepUpDown = -1; stepUpDown < 2; stepUpDown += 2) {\n        beta = defaultBeta;\n\n        for (unsigned i = 0; i < ASSUMED_DEGREE; ++i) {\n\n            beta += stepUpDown;\n\n            std::vector<cv::Vec4i> transformedLines(lines.size());\n\n            std::transform(std::begin(lines), std::end(lines),\n                           std::begin(transformedLines),\n                           [=](cv::Vec4i& line) -> cv::Vec4i {\n                               std::vector<cv::Point2f> points;\n                               points.emplace_back(cv::Point2f(line[0], line[1]));\n                               points.emplace_back(cv::Point2f(line[2], line[3]));\n\n                               auto m = generateMatrix(specialImg, beta); // In each iteration ??\n\n                               std::vector<cv::Point2f> newPoints;\n\n                               cv::perspectiveTransform(points, newPoints, m);\n                               return cv::Vec4i(\n                                       {\n                                               int(newPoints[0].x),\n                                               int(newPoints[0].y),\n                                               int(newPoints[1].x),\n                                               int(newPoints[1].y)\n                                       }\n                               );\n                           }\n            );\n            filterBadLines(transformedLines); // TODO: ????\n            auto [x, y] = findIntersectionPoint(transformedLines)\n                    .value_or(std::make_pair(0, 0));\n\n#ifdef DEBUG_MODE\n            auto destination = transformation(image, beta);\n            line( destination, Point(transformedLines[0][0], transformedLines[0][1]),\n                  Point(transformedLines[0][2], transformedLines[0][3]), cv::Scalar(0, 255, 0), 2, 8 );\n            line( destination, Point(transformedLines[1][0], transformedLines[1][1]),\n                  Point(transformedLines[1][2], transformedLines[1][3]), cv::Scalar(0, 255, 0), 2, 8 );\n            line( destination, Point(transformedLines[1][0], transformedLines[1][1]),\n                  Point(x, y), cv::Scalar(255, 255, 0), 2, 8 );\n            line( destination, Point(transformedLines[0][0], transformedLines[0][1]),\n                  Point(x, y), cv::Scalar(255, 255, 0), 2, 8 );\n            draw(destination);\n            cout << \"Current: \" << x << \", beta: \" << beta << endl;\n#endif // DEBUG_MODE\n\n            Side currSide = findSide(transformedLines[0], x);\n\n            if (currSide != prevSide){\n                goto RESULT;\n            }\n\n            prevSide = currSide;\n        }\n    }\n\n    RESULT:\n\n    auto destination = transformation(image, beta);\n    callback(destination, beta);\n\n}\n\n\nint main(int argc, char** argv) {\n\n#ifdef DEBUG_MODE\n//    std::string imgName(\"../tested_data/image0.JPG\");\n//    std::string imgName(\"../data/IMG_0048.JPG\");\n    std::string imgName(\"../tested_data/IMG_0047.JPG\");\n    cout << \"DEBUG MODE ON!\" << endl;\n#else\n#ifdef TEST_MODE\n//    std::string imgName(\"../tested_data/imageedit_6_2688227020.jpg\");\n//    std::string imgName(\"../data/image0.JPG\");\n    assert(argc == 3);\n\n    if (strcmp(argv[1], \"--data\") != 0){\n        cout << strcmp(argv[0], \"--data\") << endl;\n        std::abort();\n    }\n\n    std::string imgName(argv[2]);\n#else\n    assert(argc == 3);\n\n    if (strcmp(argv[1], \"--data\") != 0){\n        cout << strcmp(argv[0], \"--data\") << endl;\n        std::abort();\n    }\n\n    std::string imgName(argv[2]);\n#endif // TEST_MODE\n#endif // DEBUG_MODE\n#ifdef TEST_MODE\n    Mat image = getImage(imgName);\n\n    auto printWrapped = [](Mat& , int beta) -> void {\n        std::cout << beta << std::endl;\n    };\n    fixImage(image, printWrapped);\n\n#else\n    cout << imgName << endl;\n\n    Mat image = getImage(imgName);\n\n    auto drawWrapped = [](Mat& image, int i = 0) -> void {\n        draw(image);\n    };\n\n    draw(image);\n\n    fixImage(image, drawWrapped);\n\n\n    return EXIT_SUCCESS;\n#endif\n}", "meta": {"hexsha": "5d12d6c620a3e7140f8df06f24a578195bec89ca", "size": 11217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "NickolayStorm/CurseComputerVision", "max_stars_repo_head_hexsha": "b1807b2b9527044161e6b43e417a5bf6d29b6551", "max_stars_repo_licenses": ["MIT"], "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": "NickolayStorm/CurseComputerVision", "max_issues_repo_head_hexsha": "b1807b2b9527044161e6b43e417a5bf6d29b6551", "max_issues_repo_licenses": ["MIT"], "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": "NickolayStorm/CurseComputerVision", "max_forks_repo_head_hexsha": "b1807b2b9527044161e6b43e417a5bf6d29b6551", "max_forks_repo_licenses": ["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.7708830549, "max_line_length": 103, "alphanum_fraction": 0.515289293, "num_tokens": 3252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6131985394229665}}
{"text": "#include <deal.II/base/point.h>\n\n#include <gtest/gtest.h>\n\nusing namespace dealii;\n\n\nTEST(Pythagoras, Norm)\n{\n  Point<2> x(3, 4);\n  ASSERT_EQ(x.norm(), 5);\n}\n\n\nTEST(Pythagoras, Distance)\n{\n  Point<2> x(4, 5);\n  Point<2> y(1, 1);\n  ASSERT_EQ(x.distance(y), 5);\n}\n\n\nTEST(Pythagoras, ScalarProduct)\n{\n  Point<2> x(3, 4);\n  ASSERT_EQ(x * x, 25);\n}\n\n\nint\nmain(int argc, char *argv[])\n{\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "10d7acd2226f39a162192ea36a998c90ab865aea", "size": 449, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pythagoras.cc", "max_stars_repo_name": "matteosecli/lab-01", "max_stars_repo_head_hexsha": "ff72fd162ce445d16dec5704c14bd93723e6093c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pythagoras.cc", "max_issues_repo_name": "matteosecli/lab-01", "max_issues_repo_head_hexsha": "ff72fd162ce445d16dec5704c14bd93723e6093c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pythagoras.cc", "max_forks_repo_name": "matteosecli/lab-01", "max_forks_repo_head_hexsha": "ff72fd162ce445d16dec5704c14bd93723e6093c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-06T13:55:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-10T13:54:02.000Z", "avg_line_length": 12.4722222222, "max_line_length": 39, "alphanum_fraction": 0.6280623608, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6130650938128104}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_SloanRadauQuadrature.hpp\n//! \\author Luke Kersting\n//! \\brief  Sloan implementation of Gauss-Radau quadrature\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_SLOAN_RADAU_QUADRATURE_HPP\n#define UTILITY_SLOAN_RADAU_QUADRATURE_HPP\n\n// Boost Includes\n#include <boost/multiprecision/cpp_dec_float.hpp>\n\n// Std Lib Includes\n#include <vector>\n\nnamespace Utility{\n\n// use extended precision to make sure moments are preserved accurately\ntypedef boost::multiprecision::cpp_dec_float_50 long_float;\n\n//! The Sloan implementation of Gauss-Radau quadrature\nclass SloanRadauQuadrature\n{\n\npublic:\n\n  //! Constructor\n  SloanRadauQuadrature(\n            const std::vector<long_float>& legendre_expansion_moments );\n\n  //! Destructor\n  ~SloanRadauQuadrature()\n  { /* ... */ }\n\n  //! Find the nodes for the Radau quadrature\n  void getRadauNodesAndWeights( std::vector<long_float>& nodes,\n                                std::vector<long_float>& weights,\n                                const int number_of_angles_wanted = 1 ) const;\n\n  //! Find the nodes for the Radau quadrature\n  void getRadauNodesAndWeights( std::vector<long double>& nodes,\n                                std::vector<long double>& weights,\n                                const int number_of_angles_wanted = 1 ) const;\n\n  //! Find the nodes for the Radau quadrature\n  void getRadauNodesAndWeights( std::vector<double>& nodes,\n                                std::vector<double>& weights,\n                                const int number_of_angles_wanted = 1 ) const;\n\n//protected:\n\n  // Return the Radau moments of the legendre expansion of a function, f(x)\n  void getRadauMoments( std::vector<long_float>& radau_moments ) const;\n\n  // Return the Radau moments of the legendre expansion of a function, f(x)\n  void getLongRadauMoments( std::vector<long_float>& radau_moments ) const;\n\n  // Evaluate the normalization ratio for the orthogonal polynomials, Q and x*Q\n  void evaluateOrthogonalNormalizationRatio(\n        std::vector<long_float>& normalization_ratios,\n        const std::vector<std::vector<long_float> >& orthogonal_coefficients,\n        const std::vector<long_float>& normalization_factors_N,\n        const std::vector<long_float>& radau_moments,\n        const int i ) const;\n\n  // Evaluate the ith mean coefficients for orthogonal polynomial recursion relation\n  long_float evaluateMeanCoefficient(\n                     const std::vector<long_float>& normalization_ratios,\n                     const int i ) const;\n\n  // Evaluate the ith row of coefficients of the orthogonal polynomial Q\n  void evaluateOrthogonalCoefficients(\n        std::vector<std::vector<long_float> >& orthogonal_coefficients,\n        const std::vector<long_float>& variances,\n        const std::vector<long_float>& mean_coefficients,\n        const int i ) const;\n\n  // Evaluate the normalization factors, N_i for the orthogonal polynomial, Q\n  void evaluateOrthogonalNormalizationFactor(\n        std::vector<long_float>& normalization_factors_N,\n        const std::vector<std::vector<long_float> >& orthogonal_coefficients,\n        const std::vector<long_float>& radau_moments,\n        const int i ) const;\n\n  // Evaluate the variance of the moments of the orthogonal polynomial, Q_i\n  long_float evaluateVariance(\n        const std::vector<long_float>& normalization_factors_N,\n        const int i ) const;\n\n  // Evaluate the nth orthogonal polynomial at x, Q_n(x)\n  long_float evaluateOrthogonalPolynomial(\n        const std::vector<long_float>& variances,\n        const std::vector<long_float>& mean_coefficients,\n        const long_float x,\n        const int i ) const;\n\n  // Evaluate the roots of the nth orthogonal polynomial using the roots of the (n-1)th\n  bool evaluateOrthogonalRoots(\n        std::vector<std::vector<long_float> >& roots,\n        const std::vector<long_float>& variances,\n        const std::vector<long_float>& mean_coefficients,\n        const int i ) const;\n\n  // Estimate an extra (i+1)th mean coefficient for the ith orthogonal polynomial\n  void estimateExtraMeanCoefficient(\n        std::vector<long_float>& mean_coefficients,\n        const std::vector<long_float>& variances,\n        const std::vector<long_float>& normalization_factors_N,\n        const std::vector<long_float>& radau_moments,\n        const int i ) const;\n\nprivate:\n\n  // Shape a two-d array\n  static void shapeTwoDArray( std::vector<std::vector<long_float> >& two_d_array,\n                              const size_t num_rows,\n                              const size_t num_cols,\n                              const long_float fill_value = 0.0 );\n\n  // Moments of the Legendre expansion of weighting function f(x)\n  std::vector<long_float> d_legendre_expansion_moments;\n\n};\n\n} // end Utility namespace\n\n#endif // end UTILITY_GAUSS_RADAU_QUADRATURE_KERNEL_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_SloanRadauQuadrature.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "7884e29701bea1695710164d2c33ebefc2777697", "size": 5158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/integrator/src/Utility_SloanRadauQuadrature.hpp", "max_stars_repo_name": "bam241/FRENSIE", "max_stars_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-14T19:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T17:44:09.000Z", "max_issues_repo_path": "packages/utility/integrator/src/Utility_SloanRadauQuadrature.hpp", "max_issues_repo_name": "bam241/FRENSIE", "max_issues_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T19:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T03:36:08.000Z", "max_forks_repo_path": "packages/utility/integrator/src/Utility_SloanRadauQuadrature.hpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 38.4925373134, "max_line_length": 87, "alphanum_fraction": 0.6465684374, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6129980578847605}}
{"text": "/* \n * File:   mJohnsonGE.cpp\n * Author: andrasjoo\n *\n * Created on May 28, 2012, 3:43 PM\n */\n\n#include \"mJohnsonGE.h\"\n#include \"mGenome.h\"\n#include <armadillo/armadillo>\n#include \"mGCubeAdapter.h\"\n\nnamespace mmga {\n\n    float mJohnsonGE(GAGenome & gen) {\n        int sigma = ((mGenome&) gen).numberOfMultiplications();\n        int delta = ((mGenome&) gen).matrixSize();\n        float s1, s2;\n        float err = 0;\n\n        arma::cube a, b, c;\n        mGCubeAdapter()((mGenome&) gen, a, b, c);\n\n        for (int i = 0; i < delta; ++i) {\n            for (int j = 0; j < delta; ++j) {\n                for (int k = 0; k < delta; ++k) {\n                    for (int l = 0; l < delta; ++l) {\n                        for (int m = 0; m < delta; ++m) {\n                            for (int n = 0; n < delta; ++n) {\n                                s1 = (n == i) * (j == k) * (l == m);\n                                s2 = 0;\n\n                                for (int r = 0; r < sigma; ++r) {\n                                    s2 += a(i, j, r) * b(k, l, r) * c(m, n, r);\n                                }\n\n                                err += (s2 - s1) * (s2 - s1);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        return 1.0f / (1.0f + err);\n    }\n\n}\n", "meta": {"hexsha": "18c5cf4e27db69fb972f9ab5f310843e50aeea9a", "size": 1327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mJohnsonGE.cpp", "max_stars_repo_name": "Radigeco/mmga", "max_stars_repo_head_hexsha": "ae7d3ebb43e0198710c04552da837d654d5b0349", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mJohnsonGE.cpp", "max_issues_repo_name": "Radigeco/mmga", "max_issues_repo_head_hexsha": "ae7d3ebb43e0198710c04552da837d654d5b0349", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mJohnsonGE.cpp", "max_forks_repo_name": "Radigeco/mmga", "max_forks_repo_head_hexsha": "ae7d3ebb43e0198710c04552da837d654d5b0349", "max_forks_repo_licenses": ["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.0816326531, "max_line_length": 79, "alphanum_fraction": 0.3413715147, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6128502504311277}}
{"text": "#include \"widgetpreview.hpp\"\n#include \"core.hpp\"\n#include \"mainwindow.hpp\"\n#include <Eigen/Core>\n#include <QPaintEvent>\n#include <QPainter>\n#include <nlopt-util.hpp>\n#include <sequential-line-search/sequential-line-search.hpp>\n#include <tinycolormap.hpp>\n\nusing Eigen::Vector3d;\nusing Eigen::VectorXd;\n\nnamespace\n{\n    Core& core = Core::getInstance();\n}\n\nWidgetPreview::WidgetPreview(QWidget* parent) : QWidget(parent)\n{\n    this->setFixedSize(320, 320);\n\n    // Search for the maximum and minimum values\n    const auto upper  = Eigen::Vector2d::Ones();\n    const auto lower  = Eigen::Vector2d::Zero();\n    const auto x_init = 0.5 * (upper + lower);\n    const auto x_max  = nloptutil::unconstrained::derivative_free::bounded::solve(\n        x_init,\n        upper,\n        lower,\n        [&](const Eigen::VectorXd& x) { return core.evaluateObjectiveFunction(x); },\n        nlopt::GN_DIRECT,\n        true,\n        1000);\n    const auto x_min = nloptutil::unconstrained::derivative_free::bounded::solve(\n        x_init,\n        upper,\n        lower,\n        [&](const Eigen::VectorXd& x) { return core.evaluateObjectiveFunction(x); },\n        nlopt::GN_DIRECT,\n        false,\n        1000);\n\n    m_f_min = core.evaluateObjectiveFunction(x_min);\n    m_f_max = core.evaluateObjectiveFunction(x_max);\n}\n\nvoid WidgetPreview::paintEvent(QPaintEvent* event)\n{\n    QPainter     painter(this);\n    const QRect& rect = event->rect();\n\n    const VectorXd x = core.optimizer->CalcPointFromSliderPosition(core.mainWindow->obtainSliderPosition());\n    const double   f = core.evaluateObjectiveFunction(x);\n    const auto     c = tinycolormap::GetJetColor((f - m_f_min) / (m_f_max - m_f_min)).ConvertToQColor();\n\n    const QBrush backgroundBrush = QBrush(c);\n    painter.setRenderHint(QPainter::Antialiasing);\n    painter.fillRect(rect, backgroundBrush);\n}\n", "meta": {"hexsha": "360c183f8c6e31e2422bef9aea8c37d251e06f43", "size": 1841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/sequential_line_search_2d_gui/widgetpreview.cpp", "max_stars_repo_name": "yuki-koyama/sequential-line-search", "max_stars_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2018-03-12T13:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T20:28:04.000Z", "max_issues_repo_path": "demos/sequential_line_search_2d_gui/widgetpreview.cpp", "max_issues_repo_name": "yuki-koyama/sequential-line-search", "max_issues_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2018-04-05T23:42:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-13T03:52:42.000Z", "max_forks_repo_path": "demos/sequential_line_search_2d_gui/widgetpreview.cpp", "max_forks_repo_name": "yuki-koyama/sequential-line-search", "max_forks_repo_head_hexsha": "7f68ce6f3ccb63eee4e921b867bd1014e3f947ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-06-12T17:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T11:13:03.000Z", "avg_line_length": 30.1803278689, "max_line_length": 108, "alphanum_fraction": 0.6789788159, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6128284150139268}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n\nint round_to_int(double x) {\n  return static_cast<int>(x < 0 ? x - 0.5 : x + 0.5);\n}\n\nint finite_choose_test(int N, int n) {\n  using std::exp;\n  return round_to_int(exp(lgamma(N + 1) - lgamma(n + 1) - lgamma(N - n + 1)));\n}\n\nvoid test_choose_finite(int N, int n) {\n  using stan::math::choose;\n  if (n > N)\n    EXPECT_EQ(0, choose(N, n));\n  else\n    EXPECT_EQ(finite_choose_test(N, n), choose(N, n));\n}\n\nTEST(MathFunctions, choose) {\n  for (int N = 0; N <= 32; ++N)\n    for (int n = 0; n <= 32; ++n)\n      test_choose_finite(N, n);\n}\n\nTEST(MathFunctions, chooseThrow) {\n  using stan::math::choose;\n  EXPECT_THROW(choose(36, 18), std::domain_error);\n  EXPECT_THROW(choose(-2, 1), std::domain_error);\n  EXPECT_THROW(choose(2, -1), std::domain_error);\n}\n\nTEST(MathFunctions, choose_nan) {\n  using stan::math::choose;\n  int nan = std::numeric_limits<int>::quiet_NaN() - 1;\n  // quiet_NaN() returns 0 which would otherwise be valid\n  EXPECT_THROW(choose(2, nan), std::domain_error);\n  EXPECT_THROW(choose(nan, 2), std::domain_error);\n  EXPECT_THROW(choose(nan, nan), std::domain_error);\n}\n", "meta": {"hexsha": "058f45e8dde4479a27bb929bbb854f9732ef7cf5", "size": 1270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/math/prim/scal/fun/choose_test.cpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "test/unit/math/prim/scal/fun/choose_test.cpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "test/unit/math/prim/scal/fun/choose_test.cpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2222222222, "max_line_length": 78, "alphanum_fraction": 0.6724409449, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6128284042680489}}
{"text": "#include \"squarelattice.hpp\"\n#include \"wanglandau.h\"\n#include <boost/random.hpp>\n#include <ctime>\n#include <boost/program_options.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH\n\nint main(int argc, char **argv)\n{\n  using namespace boost;\n  using namespace boost::program_options;\n  options_description opt(\"options\");\n  opt.add_options()\n    (\"help,h\", \"show this message\")\n    (\"q,q\", value<int>()->default_value(2), \"number of state of a spin\")\n    (\"L,L\", value<int>()->default_value(10), \"length of lattice\")\n    (\"flatness,f\", value<double>()->default_value(0.8), \"target flatness of histogram\")\n    (\"final,F\", value<double>()->default_value(1.0e-8), \"minimum updating factor\")\n    (\"interval,i\", value<int>()->default_value(32), \"interval between checks for flatness\")\n    (\"verbose,v\",  \"show histogram verbose info\");\n\n  variables_map vm;\n  store(parse_command_line(argc, argv, opt), vm);\n  notify(vm);\n\n  if( vm.count(\"help\") ){\n    std::cout << opt << std::endl;\n    return 0;\n  }\n\n  const int q = vm[\"q\"].as<int>();\n  const int L = vm[\"L\"].as<int>();\n  const double flatness = vm[\"flatness\"].as<double>();\n  const double final_factor = vm[\"final\"].as<double>();\n  const int check_interval = vm[\"interval\"].as<int>();\n  const bool verbose = vm.count(\"verbose\");\n\n  boost::variate_generator<boost::mt19937, boost::uniform_real<> >\n    rnd(boost::mt19937(static_cast<uint32_t>(std::time(0))), boost::uniform_real<>(0.0, 1.0));\n\n  wanglandau::SquareLattice lattice(L);\n\n  const int nsites = lattice.num_sites();\n  const int nbonds = lattice.num_bonds();\n\n  wanglandau::WangLandau wl(nbonds+1, flatness, final_factor, (q==2?0.4:0.8)*(nbonds+1),\n                            std::log(q), nbonds);\n\n  std::vector<int> spins(nsites, 0);\n  int npara = nbonds;\n\n  while( !wl.finished()){\n    for(int i=0; i<check_interval; ++i){\n      for(int s=0; s<nsites; ++s){\n        const int site = nsites*rnd();\n        const int pspin = spins[site]; // present\n        const int cspin = q*rnd();     // candidate\n        int cpara = npara;\n        foreach(int neighbor, lattice.neighbors(site)){\n          cpara -= spins[neighbor] == pspin ? 1 : 0;\n          cpara += spins[neighbor] == cspin ? 1 : 0;\n        }\n        if(rnd() < wl.prob(npara, cpara)){\n          spins[site] = cspin;\n          npara = cpara;\n        }\n        wl.visit(npara);\n      }\n    }\n    wl.update(verbose);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "0881276258038b8359f1343d469733f1f69cd789", "size": 2446, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/potts.cpp", "max_stars_repo_name": "yomichi/Potts-WL", "max_stars_repo_head_hexsha": "89af40b81191172d0603b8ae28b10599c6637f74", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/potts.cpp", "max_issues_repo_name": "yomichi/Potts-WL", "max_issues_repo_head_hexsha": "89af40b81191172d0603b8ae28b10599c6637f74", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/potts.cpp", "max_forks_repo_name": "yomichi/Potts-WL", "max_forks_repo_head_hexsha": "89af40b81191172d0603b8ae28b10599c6637f74", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7662337662, "max_line_length": 94, "alphanum_fraction": 0.6185609158, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.612828398490348}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <complex>\n#include \"../../JeanBaptiste/include/AlgorithmFactory.h\"\n#include \"../include/AlgorithmFixture.h\"\n#include <string>\n\nnamespace ut = boost::unit_test;\nnamespace jb = jeanbaptiste;\nnamespace jbo = jeanbaptiste::options;\n\nclass RadixSplit24Fixture\n    : public AlgorithmFixture\n{\nprotected:\n    bool initialized_;\n\npublic:\n    RadixSplit24Fixture()\n        : AlgorithmFixture()\n    {\n        BOOST_TEST_MESSAGE(\"Setup fixture: square pulse of 64 samples.\");\n        BOOST_TEST((initialized_ = algorithmResult_.initialize(\"../../test cases/square pulse (n=64).xml\", \"fft.in\", workingSet_, expectedOutIFFT_, \"fft.out\", expectedOutFFT_)), \"Loading test data failed.\");\n    }\n\n    ~RadixSplit24Fixture()\n    {}\n};\n\n\nBOOST_FIXTURE_TEST_SUITE(RadixSplit24TestSuite, RadixSplit24Fixture)\n\n    BOOST_AUTO_TEST_CASE(fft_radix_split_2_4_dif)\n    {\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Running split radix 2-4 DIF FFT and IFFT.\");\n\n        // Create Split-Radix-2-4 DIF FFT algorithms for sample counts 2 ... 256.\n        jb::AlgorithmFactory<1, 8, jbo::Radix_Split_2_4, jbo::Decimation_In_Frequency, jbo::Direction_Forward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> fftFactory;\n\n        // Create Split-Radix-2-4 DIF IFFT algorithms for sample counts 2 ... 256.\n        jb::AlgorithmFactory<1, 8, jbo::Radix_Split_2_4, jbo::Decimation_In_Frequency, jbo::Direction_Backward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> ifftFactory;\n\n        runAlgorithms(fftFactory.getAlgorithm(6), ifftFactory.getAlgorithm(6));\n    }\n\n    BOOST_AUTO_TEST_CASE(fft_radix_split_2_4_dit)\n    {\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Running split radix 2-4 DIT FFT and IFFT.\");\n\n        // Create Split-Radix-2-4 DIT FFT algorithms for sample counts 2 ... 256.\n        jb::AlgorithmFactory<1, 8, jbo::Radix_Split_2_4, jbo::Decimation_In_Time, jbo::Direction_Forward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> fftFactory;\n\n        // Create Split-Radix-2-4 DIT IFFT algorithms for sample counts 2 ... 256.\n        jb::AlgorithmFactory<1, 8, jbo::Radix_Split_2_4, jbo::Decimation_In_Time, jbo::Direction_Backward, jbo::Window_None,\n            jbo::Normalization_Square_Root, std::complex<double>> ifftFactory;\n\n        runAlgorithms(fftFactory.getAlgorithm(6), ifftFactory.getAlgorithm(6));\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "28de231e8860150d22ac96343e8c618106959129", "size": 2547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "JeanBaptiste.Test/src/FixtureRadixSplit24.cpp", "max_stars_repo_name": "JoergWarthemann/jeanbaptiste", "max_stars_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JeanBaptiste.Test/src/FixtureRadixSplit24.cpp", "max_issues_repo_name": "JoergWarthemann/jeanbaptiste", "max_issues_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JeanBaptiste.Test/src/FixtureRadixSplit24.cpp", "max_forks_repo_name": "JoergWarthemann/jeanbaptiste", "max_forks_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4558823529, "max_line_length": 207, "alphanum_fraction": 0.7027875932, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812554, "lm_q2_score": 0.7606506581031359, "lm_q1q2_score": 0.6128046547376619}}
{"text": "/**\n * ravess_example.cpp\n *\n * 2021 Gabriel Moreira\n *\n * https://github.com/gabmoreira/maks\n *\n * This software and the related documents  are provided as  is,  with no express\n * or implied  warranties,  other  than those  that are  expressly stated  in the\n * License.\n *\n * Copyright \u00a9 2021 Gabriel Moreira. All rights reserved.\n */\n\n#include <iostream>\n#include <string>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include \"io.hpp\"\n#include \"ravg.hpp\"\n#include \"linalg.hpp\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXi;\n\ntypedef Eigen::SparseMatrix<double> Sparse;\n\nint main(int argc, char *argv[]) {\n    \n    int MAX_EDGES = 25000;\n    \n    std::string path(argv[1]);\n    \n    int num_nodes;\n    int num_edges;\n    \n    VectorXi edge_i(MAX_EDGES);\n    VectorXi edge_j(MAX_EDGES);\n    \n    // Rotation data allocation in contiguous row matrix blocks\n    MatrixXd edge_r(3, 3 * MAX_EDGES);\n\n    // Read edge rotations from .g2o file\n    readG2O(path.c_str(), edge_i, edge_j, edge_r, num_edges);\n    \n    // Convert edges ids to matrix indices in place\n    alg::convertToIdx(edge_i.topRows(num_edges), edge_j.topRows(num_edges), num_nodes);\n        \n    printf(\"Read %d nodes and %d edges from %s\\n\", num_nodes, num_edges, path.c_str());\n    \n    Sparse A(num_nodes, num_nodes);\n    alg::adjacency(edge_i, edge_j, num_edges, true, A);\n    \n    Sparse Rtilde(num_nodes * 3, num_nodes * 3);\n    alg::sparseBlocks(edge_i, edge_j, edge_r, 3, 3, num_edges, true, Rtilde);\n        \n    // Placeholder for the solution\n    MatrixXd R(3 * num_nodes, 3);\n    double dual = 0.0f;\n    \n    // Primal-dual method for rotation averaging\n    primalDualSO3(Rtilde, A, R, num_nodes, 50, dual, 5e-14, -1e-6);\n     \n};\n    \n", "meta": {"hexsha": "294fcdf37636828019b7ae6f38fe7281ba228a84", "size": 1717, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ravess_example.cpp", "max_stars_repo_name": "rjanvier/maks", "max_stars_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2020-12-15T10:15:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:19:07.000Z", "max_issues_repo_path": "src/ravess_example.cpp", "max_issues_repo_name": "rjanvier/maks", "max_issues_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T12:24:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:47:43.000Z", "max_forks_repo_path": "src/ravess_example.cpp", "max_forks_repo_name": "rjanvier/maks", "max_forks_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-06T07:22:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T09:31:30.000Z", "avg_line_length": 25.25, "max_line_length": 87, "alphanum_fraction": 0.6604542807, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6127651098685377}}
{"text": "\ufeff//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"RefNormalizationFloat32Workload.hpp\"\n\n#include \"RefWorkloadUtils.hpp\"\n#include \"TensorBufferArrayView.hpp\"\n\n#include \"Profiling.hpp\"\n\n#include <armnn/Tensor.hpp>\n\n#include <boost/log/trivial.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n\nusing namespace armnnUtils;\n\nnamespace armnn\n{\n\n// Helper function to compute \"Within\" normalization using Krichevsky 2012: Local Brightness Normalization.\nstatic void NormalizeWithinUingLbr(const float*       inputData,\n                                   float*             outputData,\n                                   const TensorShape& tensorShape,\n                                   uint32_t           norm_size,\n                                   float              alpha,\n                                   float              beta,\n                                   float              kappa)\n{\n    const unsigned int batchSize = tensorShape[0];\n    const unsigned int depth = tensorShape[1];\n    const unsigned int rows = tensorShape[2];\n    const unsigned int cols = tensorShape[3];\n\n    int radius = boost::numeric_cast<int>(norm_size / 2u); /* Strong Assumption on rounding Mode */\n\n    for (unsigned int n = 0; n < batchSize; n++)\n    {\n        for (unsigned int c = 0; c < depth; c++)\n        {\n            for (unsigned int h = 0; h < rows; h++)\n            {\n                for (unsigned int w = 0; w < cols; w++)\n                {\n                    float accumulated_scale = 0.0;\n                    for (int y = -radius; y <= radius; y++)\n                    {\n                        for (int x = -radius; x <= radius; x++)\n                        {\n                            int i = boost::numeric_cast<int>(w) + x;\n                            int j = boost::numeric_cast<int>(h) + y;\n\n                            if ((i < 0) || (i >= boost::numeric_cast<int>(cols)))\n                            {\n                                continue;\n                            }\n\n                            if ((j < 0) || (j >= boost::numeric_cast<int>(rows)))\n                            {\n                                continue;\n                            }\n\n                            float inval = inputData[n * cols * rows * depth +\n                                                    c * cols * rows +\n                                                    boost::numeric_cast<unsigned int>(j) * cols +\n                                                    boost::numeric_cast<unsigned int>(i)];\n\n                            accumulated_scale += inval*inval;\n                        }\n                    }\n                    outputData[n * cols * rows * depth +\n                               c * cols * rows +\n                               h * cols +\n                               w] = inputData[n * cols * rows * depth +\n                                              c * cols * rows +\n                                              h * cols +\n                                              w] / (powf((kappa + (accumulated_scale * alpha)), beta));\n                }\n            }\n        }\n    }\n}\n\n// Helper function to compute \"Across\" normalization using Krichevsky 2012: Local Brightness Normalization.\nvoid NormalizeAcrossUingLbr(const float*       inputData,\n                            float*             outputData,\n                            const TensorShape& tensorShape,\n                            uint32_t           norm_size,\n                            float              alpha,\n                            float              beta,\n                            float              kappa,\n                            DataLayout         dataLayout)\n{\n    TensorBufferArrayView<const float> input(tensorShape,\n                                             inputData,\n                                             dataLayout);\n    TensorBufferArrayView<float> output(tensorShape,\n                                        outputData,\n                                        dataLayout);\n\n    DataLayoutIndexed dataLayoutIndexed(dataLayout);\n\n    const unsigned int batchSize = tensorShape[0];\n    const unsigned int depth     = tensorShape[dataLayoutIndexed.GetChannelsIndex()];\n    const unsigned int rows      = tensorShape[dataLayoutIndexed.GetHeightIndex()];\n    const unsigned int cols      = tensorShape[dataLayoutIndexed.GetWidthIndex()];\n\n    int radius = boost::numeric_cast<int>(norm_size / 2u); /* Strong Assumption on rounding Mode */\n\n    for (unsigned int n = 0; n < batchSize; n++)\n    {\n        for (unsigned int c = 0; c < depth; c++)\n        {\n            for (unsigned int h = 0; h < rows; h++)\n            {\n                for (unsigned int w = 0; w < cols; w++)\n                {\n                    float accumulated_scale = 0.0;\n                    for (int z = -radius; z <= radius; z++)\n                    {\n                        int k = boost::numeric_cast<int>(c) + z;\n\n                        if ((k < 0) || (k >= boost::numeric_cast<int>(depth)))\n                        {\n                            continue;\n                        }\n\n                        float inval = input.Get(n, boost::numeric_cast<unsigned int>(k), h, w);\n\n                        accumulated_scale += inval * inval;\n                    }\n\n                    float scale = kappa + (accumulated_scale * alpha);\n                    scale = powf(scale, -beta);\n\n                    output.Get(n, c, h, w) = scale * input.Get(n, c, h, w);\n                }\n            }\n        }\n    }\n}\n\nvoid RefNormalizationFloat32Workload::Execute() const\n{\n    ARMNN_SCOPED_PROFILING_EVENT(Compute::CpuRef, \"RefNormalizationFloat32Workload_Execute\");\n\n    const TensorInfo& inputInfo = GetTensorInfo(m_Data.m_Inputs[0]);\n\n    float*       outputData = GetOutputTensorDataFloat(0, m_Data);\n    const float* inputData = GetInputTensorDataFloat(0, m_Data);\n\n    if (NormalizationAlgorithmMethod::LocalBrightness == m_Data.m_Parameters.m_NormMethodType)\n    {\n        if (NormalizationAlgorithmChannel::Within == m_Data.m_Parameters.m_NormChannelType)\n        {\n            NormalizeWithinUingLbr(inputData,\n                                   outputData,\n                                   inputInfo.GetShape(),\n                                   m_Data.m_Parameters.m_NormSize,\n                                   m_Data.m_Parameters.m_Alpha,\n                                   m_Data.m_Parameters.m_Beta,\n                                   m_Data.m_Parameters.m_K);\n        }\n        else if (NormalizationAlgorithmChannel::Across == m_Data.m_Parameters.m_NormChannelType)\n        {\n            NormalizeAcrossUingLbr(inputData,\n                                   outputData,\n                                   inputInfo.GetShape(),\n                                   m_Data.m_Parameters.m_NormSize,\n                                   m_Data.m_Parameters.m_Alpha,\n                                   m_Data.m_Parameters.m_Beta,\n                                   m_Data.m_Parameters.m_K,\n                                   m_Data.m_Parameters.m_DataLayout);\n        }\n        else\n        {\n            BOOST_LOG_TRIVIAL(warning) << \"Illegal NORMALIZATION mode in normalization_f32\";\n            return;\n        }\n    }\n    else\n    {\n        BOOST_LOG_TRIVIAL(warning) << \"Lcr method (Jarret 2009: Local Contrast Normalization) not supported yet.\";\n        return;\n    }\n}\n\n} //namespace armnn\n", "meta": {"hexsha": "3a2f2b965853871bc66d902f2aad8b14a5544af8", "size": 7463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/reference/workloads/RefNormalizationFloat32Workload.cpp", "max_stars_repo_name": "jnorwood/armnn", "max_stars_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-26T23:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T23:00:46.000Z", "max_issues_repo_path": "src/backends/reference/workloads/RefNormalizationFloat32Workload.cpp", "max_issues_repo_name": "jnorwood/armnn", "max_issues_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/backends/reference/workloads/RefNormalizationFloat32Workload.cpp", "max_forks_repo_name": "jnorwood/armnn", "max_forks_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0732984293, "max_line_length": 114, "alphanum_fraction": 0.4503550851, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.6127650945015372}}
{"text": "#include \"geometrycentral/quad_cover.h\"\n#include <Eigen/SparseCholesky>\n\n// ONLY WORKS FOR MESHES WITHOUT BOUNDARY\nQuadCover::QuadCover(HalfedgeMesh* m, Geometry<Euclidean>* g) : mesh(m), geom(g), phi(m), r(m), field(m), \n                                                                singularities(m), branchCover(m) {\n    assert(mesh->nBoundaryLoops() == 0);\n}\n\nvoid QuadCover::setup() {\n    VertexData<double> s(mesh);\n    // Compute s_i at each vertex\n    for (VertexPtr v : mesh->vertices()) {\n        if (v.isBoundary()) {\n            s[v] = 1.0;\n        } else {\n            double sum = 0;\n            for (HalfedgePtr he : v.outgoingHalfedges()) {\n                sum += geom->angle(he.next());\n            }\n            s[v] = 2*M_PI / sum;\n        }\n    }\n    \n    // Compute transport at edges r_ij <- e^ip_ij\n    for (VertexPtr v : mesh->vertices()) {\n        HalfedgePtr he = v.halfedge();\n        double angle = 0;\n        double s_i = s[v];\n        do {\n            phi[he] = angle;\n            angle += s_i * geom->angle(he.next());\n            he = he.next().next().twin();\n        } while (he != v.halfedge());\n    }\n\n    // Compute r_ij\n    std::complex<double> i(0, 1);\n    for (VertexPtr v : mesh->vertices()) {\n        for (HalfedgePtr he : v.outgoingHalfedges()) {\n            double theta_ij = phi[he];\n            double theta_ji = phi[he.twin()] + M_PI;\n            double rho_ij = theta_ij - theta_ji;\n            r[he] = std::exp(i * n * rho_ij);\n        }\n    }   \n}\n\nEigen::SparseMatrix<std::complex<double>> QuadCover::assembleM() {\n    size_t n = mesh->nVertices();\n    Eigen::SparseMatrix<std::complex<double>> M(n,n);\n    std::vector<Eigen::Triplet<std::complex<double>>> triplets;\n\n    VertexData<size_t> vertexIndices = mesh->getVertexIndices();\n    for (FacePtr f : mesh->faces()) {\n        HalfedgePtr he_ij = f.halfedge();\n        size_t i = vertexIndices[he_ij.vertex()];\n        size_t j = vertexIndices[he_ij.next().vertex()];\n        size_t k = vertexIndices[he_ij.prev().vertex()];\n\n        double area = geom->area(f);\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(i, i, area/3.));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(j, j, area/3.));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(k, k, area/3.));\n    }\n    M.setFromTriplets(triplets.begin(),triplets.end());\n    return M;\n}\n\nEigen::SparseMatrix<std::complex<double>> QuadCover::assembleA() {\n    size_t n = mesh->nVertices();\n    Eigen::SparseMatrix<std::complex<double>> A(n,n);\n    std::vector<Eigen::Triplet<std::complex<double>>> triplets;\n\n    VertexData<size_t> vertexIndices = mesh->getVertexIndices();\n    for (FacePtr f : mesh->faces()) {\n        HalfedgePtr he_ij = f.halfedge();\n        HalfedgePtr he_jk = f.halfedge().next();\n        HalfedgePtr he_ki = f.halfedge().prev();\n\n        size_t i = vertexIndices[he_ij.vertex()];\n        size_t j = vertexIndices[he_jk.vertex()];\n        size_t k = vertexIndices[he_ki.vertex()];\n\n        double a = geom->cotan(he_jk);\n        double b = geom->cotan(he_ki);\n        double c = geom->cotan(he_ij);\n\n        std::complex<double> r_ij = r[he_ij];\n        std::complex<double> r_ji = r[he_ij.twin()];\n        std::complex<double> r_jk = r[he_jk];\n        std::complex<double> r_kj = r[he_jk.twin()];\n        std::complex<double> r_ki = r[he_ki];\n        std::complex<double> r_ik = r[he_ki.twin()];\n\n        // row i\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(i,i,b + c));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(i,j,-c * r_ij));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(i,k,-b * r_ik));\n\n        // row j\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(j,i,-c * r_ji));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(j,j,c + a));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(j,k,-a * r_jk));\n\n        // row k\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(k,i,-b * r_ki));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(k,j,-a * r_kj));\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(k,k,a + b));\n    }\n    A.setFromTriplets(triplets.begin(),triplets.end());\n    return A;\n}\n\nvoid QuadCover::computeSmoothestField(Eigen::SparseMatrix<std::complex<double>> M, Eigen::SparseMatrix<std::complex<double>> A) {\n    // LL^T <- Cholesky(A)\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<std::complex<double>>> solver;\n    solver.compute(A);\n\n    // u <- UniformRand(-1,1)\n    Eigen::MatrixXcd u = Eigen::MatrixXcd::Random(mesh->nVertices(),1);\n    Eigen::MatrixXcd x;\n\n    // inverse power iteration to find eigenvector belonging to the smallest eigenvalue\n    for (int i = 0; i < nPowerIterations; i++) {\n        x = solver.solve(M * u);\n        std::complex<double> norm2 = (x.transpose() * M * x)(0,0);\n        u = x / sqrt(norm2);\n    }\n\n    // map resulting vector to VertexData\n    VertexData<size_t> vertexIndices = mesh->getVertexIndices();\n    for (VertexPtr v : mesh->vertices()) {\n        std::complex<double> c = u(vertexIndices[v],0);\n        if (std::abs(c) == 0) {\n            field[v] = 0;\n        } else {\n            field[v] = c / std::abs(c);   \n        }\n    }\n} \n\nVertexData<std::complex<double>> QuadCover::computeCrossField() {\n    std::cout << \"Computing Cross Field!\" << std::endl;\n    // Algorithm 1 : Setup\n    setup();\n\n    // Algorithm 2 : Smoothest Field\n    Eigen::SparseMatrix<std::complex<double>> M = assembleM();\n    Eigen::SparseMatrix<std::complex<double>> A = assembleA();\n    A = A + eps * M;\n    computeSmoothestField(M,A);\n\n    std::cout << \"Done computing smoothest field!\" << std::endl;\n    return field;\n}\n\nFaceData<int> QuadCover::computeSingularities() {\n    std::cout << \"Computing Singularities!\" << std::endl;\n    // first, compute Omega_ijk <- arg(r_ij r_jk r_ki)\n    FaceData<double> Omega(mesh);\n    for (FacePtr f : mesh->faces()) {\n        std::complex<double> r_ij = r[f.halfedge()];\n        std::complex<double> r_jk = r[f.halfedge().next()];\n        std::complex<double> r_ki = r[f.halfedge().prev()];\n        Omega[f] = std::arg(r_ij * r_jk * r_ki);\n    }\n\n    // next, compute w_ij for each e_ij, such that u_j = e^iw_ij * r_ij * u_i \n    // w_ij = arg(u_j / (r_ij * u_i))\n    HalfedgeData<double> w(mesh);\n    for (HalfedgePtr he : mesh->allHalfedges()) {\n        std::complex<double> u_i = field[he.vertex()];\n        std::complex<double> u_j = field[he.twin().vertex()];        \n        std::complex<double> r_ij = r[he];\n        w[he] = std::arg(u_j * r_ij / u_i);\n    }\n\n    // finally, compute index for each triangle t\n    // (1/2pi) * (w_ij + w_jk + w_ki + Omega_ijk)\n    for (FacePtr f : mesh->faces()) {\n        double w_ij = w[f.halfedge()];\n        double w_jk = w[f.halfedge().next()];\n        double w_ki = w[f.halfedge().prev()];\n        double Omega_ijk = Omega[f];\n        double phi = (w_ij + w_jk + w_ki - Omega_ijk) / (2.0 * M_PI);\n        singularities[f] = std::round(phi);\n    }\n    return singularities;\n}\n\nvoid QuadCover::computeBranchCover() {\n    std::cout<< \"Computing Branch Cover!\" << std::endl;\n    std::complex<double> i(0, 1);\n    for (FacePtr f : mesh->faces()) {\n        int total = 0;\n        for (HalfedgePtr he_ij : f.adjacentHalfedges()) {\n            HalfedgePtr he_ji = he_ij.twin();\n\n            std::complex<double> f_ij = std::pow(field[he_ij.vertex()], 1.0 / n);\n            std::complex<double> f_ji = std::pow(field[he_ji.vertex()], 1.0 / n);\n            \n            // we need to recompute r_ij here without raising to the nth power, \n            // as raising to the nth power and then taking the nth root is not always an identity operation\n            double theta_ij = phi[he_ij];\n            double theta_ji = phi[he_ij.twin()] + M_PI;\n            double rho_ij = theta_ji - theta_ij;\n            std::complex<double> r_ij = std::exp(i * rho_ij);\n            std::complex<double> s_ij = f_ji / (f_ij * r_ij); \n            double ang = std::arg(s_ij);\n            \n            if (ang >= -M_PI_4 && ang < M_PI_4) {\n                branchCover[he_ij] = 0;\n            } else if (ang >= M_PI_4 && ang < 3.0 * M_PI_4) {\n                branchCover[he_ij] = 1;\n                total = (total + 1) % 4;\n            } else if ((ang >= 3.0 * M_PI_4 && ang <= PI) || \n                       (ang < -3.0 * M_PI_4 && ang >= -PI)) {\n                branchCover[he_ij] = 2;\n                total = (total + 2) % 4;\n            } else {\n                assert(ang >= -3.0 * M_PI_4 && ang < -M_PI_4);\n                branchCover[he_ij] = 3;\n                total = (total + 3) % 4;\n            }\n            /*          \n            if ( ang >= -M_PI_2 && ang < M_PI_2 ) {\n                branchCover[he_ij.edge()] = 0;\n            } else {\n                branchCover[he_ij.edge()] = 1;\n                total = (total + 1) % 2;\n            }*/\n        }   \n        \n        if (singularities[f] != 0 && total == 0) {\n            std::cout << \"difference at singularity: \" << total << std::endl;\n        } else if (singularities[f] == 0 && total != 0) {\n            std::cout << \"difference at non-singularity: \" << total << std::endl; \n        }\n    }\n}\n\nEigen::SparseMatrix<std::complex<double>> QuadCover::buildLaplacian() {\n    size_t n = mesh->nVertices();\n    Eigen::SparseMatrix<std::complex<double>> L(n,n);\n    std::vector<Eigen::Triplet<std::complex<double>>> triplets;\n    \n    VertexData<size_t> vertexIndices = mesh->getVertexIndices();\n    for (VertexPtr v1 : mesh->vertices()) {\n        int index1 = vertexIndices[v1];\n        double sum = __DBL_EPSILON__;\n\n        // add neighbor weights\n        for (HalfedgePtr heOut : v1.outgoingHalfedges()) {\n            VertexPtr v2 = heOut.twin().vertex();\n            int index2 = vertexIndices[v2];\n            double weight = (geom->cotan(heOut) + geom->cotan(heOut.twin())) / 2;\n            sum += weight;\n\n            if (branchCover[heOut] == 1) {\n                weight *= -1;\n            }\n            triplets.push_back(Eigen::Triplet<std::complex<double>>(index1, index2, std::complex<double>(-weight,0)));\n        }\n\n        // add diagonal weight\n        triplets.push_back(Eigen::Triplet<std::complex<double>>(index1, index1, std::complex<double>(sum,0)));  \n    }\n    L.setFromTriplets(triplets.begin(), triplets.end());\n    return L;\n}\n\nVertexData<double> QuadCover::computeOffset() {\n    std::cout << \"Computing Offset!\" << std::endl;\n    \n    Eigen::SparseMatrix<std::complex<double>> L = buildLaplacian();\n    Eigen::SparseMatrix<std::complex<double>> M = assembleM();\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<std::complex<double>>> solver;\n    solver.compute(L);\n\n    // u <- UniformRand(-1,1)\n    Eigen::MatrixXcd u = Eigen::MatrixXcd::Random(mesh->nVertices(),1);\n    Eigen::MatrixXcd x;\n\n    // inverse power iteration to find eigenvector belonging to the smallest eigenvalue\n    for (int i = 0; i < nPowerIterations; i++) {\n        x = solver.solve(M * u);\n        std::complex<double> norm2 = (x.transpose() * M * x)(0,0);\n        u = x / sqrt(norm2);\n    }\n\n    // store into VertexData\n    VertexData<double> offset(mesh);\n    VertexData<size_t> vertexIndices = mesh->getVertexIndices();\n    for (VertexPtr v : mesh->vertices()) {\n        size_t index = vertexIndices[v];\n        offset[v] = x(index,0).real();\n    }\n\n    emitTriangles(offset);\n    return offset;\n}\n\nvoid QuadCover::emitTriangles(VertexData<double> offsets) {\n    std::cout << \"Emitting Triangles!\" << std::endl;\n    \n    std::ofstream outfile (\"branchcover.obj\");\n    // write vertices\n    for (VertexPtr v : mesh->vertices()) {\n        Vector3 pos = geom->position(v) + offsets[v] * geom->normal(v);\n        Vector3 neg = geom->position(v) - offsets[v] * geom->normal(v);\n\n        outfile << \"v \" << pos.x << \" \" << pos.y << \" \" << pos.z << std::endl;\n        outfile << \"v \" << neg.x << \" \" << neg.y << \" \" << neg.z << std::endl;\n    }\n\n    // write face indices\n    VertexData<size_t> vertexIndices = mesh->getVertexIndices();\n    for (FacePtr f : mesh->faces()) {\n        HalfedgePtr he = f.halfedge();\n\n       for (int currSheet = 0; currSheet < 2; currSheet++) {\n           outfile << \"f \";\n           do {\n               size_t index = vertexIndices[he.vertex()];\n               if (currSheet == 0) {\n                   outfile << (2*index)+1 << \" \";\n               } else {\n                   outfile << (2*index+1)+1 << \" \";\n               }\n               currSheet = (currSheet + branchCover[he]) % 2;\n               he = he.next();\n           } while (he != f.halfedge());\n           outfile << std::endl;\n       }\n    }\n\n    outfile.close();\n    std::cout << \"Done!\" << std::endl;\n}", "meta": {"hexsha": "9849052f1a697a3b7528c4682331a70e0f5e5384", "size": 12734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/quad_cover.cpp", "max_stars_repo_name": "connorzl/geometry-central", "max_stars_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/quad_cover.cpp", "max_issues_repo_name": "connorzl/geometry-central", "max_issues_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/quad_cover.cpp", "max_forks_repo_name": "connorzl/geometry-central", "max_forks_repo_head_hexsha": "99114ffaf3efb58c912f94402dd0426cbb17d3f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4529411765, "max_line_length": 129, "alphanum_fraction": 0.553950055, "num_tokens": 3550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6127432299582416}}
{"text": "#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <complex>\n#include <iomanip>\n#include <Eigen/Dense>\n#include \"GaussLegendreEigen.cpp\"\n\n/*\n\nsingle channel non-rel T-matrix solver\n\ng++ -I/usr/local/include/eigen3 ...\n\n*/\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef std::complex<double> Complex;\nstatic const Complex I(0.0,1.0);\ndouble V0,r0,mu;\n\ndouble deltaExact(double k) {\n  // S-wave square well phase shift\n  // should be a pos del for attractive potl\n  double kp = sqrt(k*k+abs(V0)*2.0*mu);\n  return (-k*r0+atan(k*tan(kp*r0)/kp))*180.0/M_PI;\n}\n\n\nComplex SqWell(double k, double p, int ell) {\n  // V = V0*theta(r-r0) S-wave only\n  double SqReal;\n  if (k != p) {\n    SqReal = -2.0*M_PI*V0/(k*p)*(sin((k+p)*r0)/(k+p) - \n                             sin((k-p)*r0)/(k-p));\n  } else {\n    SqReal = -2.0*M_PI*V0/(k*k)*(sin(2.0*k*r0)/(2.0*k)-r0);\n  }\n  return Complex(SqReal,0.0);\n}\n\nint main () {\n  ofstream ofs;\n  ofs.open(\"T.dat\");\n  double m1,m2;\n  int Ngrid,ell;\n  Complex D;\n\n  cout << \" enter m1, m2, ell \" << endl;\n  cin >> m1 >> m2 >> ell;\n  cout << \" enter V0 (<0 for attractive), r0 \" << endl;\n  cin >> V0 >> r0;\n  cout << \" enter Ngrid \" << endl;\n  cin >> Ngrid;\n  \n  mu = m1*m2/(m1+m2);\n  VectorXd k(Ngrid+1),w(Ngrid);\n  VectorXcd V(Ngrid+1),T(Ngrid+1);\n  MatrixXcd M(Ngrid+1,Ngrid+1);\n\n  GaussLegendreEigen(k,w,Ngrid,0.0,M_PI_2);   // create GL grid & weights\n  for (int i=0;i<Ngrid;i++) {                                 // map grid\n    w(i) = w(i)/pow(cos(k(i)),2);\n    k(i) = tan(k(i));\n  }\n  //  test this\n  double s=0.0;\n  for (int i=0;i<Ngrid;i++) {\n   s += w(i)*k(i)*k(i)*exp(-k(i)*k(i));\n  }\n  s *= 4/sqrt(M_PI);\n  cout << \" test integral \" << setprecision(20) << s << endl;\n\n  for (int ik=1;ik<50;ik++) {            // loop in scattering momentum\n    double k0 = ik*0.04;\n    k(Ngrid) = k0;                       // add  k0 to the grid\n    for (int a=0;a<=Ngrid;a++) {\n       V(a) = SqWell(k(a),k0,ell);\n    }\n    for (int a=0;a<=Ngrid;a++) {\n    for (int b=0;b<=Ngrid;b++) {\n      if (b == Ngrid) {\n        double Dr = 0.0;\n        for (int i=0;i<Ngrid;i++)\n          Dr -= w(i)*k0*k0/(k0*k0-k(i)*k(i)); \n          D = Complex(Dr,-M_PI*k0/2.0); \n      } else {\n          D = Complex(w(b)*k(b)*k(b)/(k0*k0-k(b)*k(b)),0.0); \n      }\n      M(a,b) = -mu/(M_PI*M_PI)*SqWell(k(a),k(b),ell)*D;\n      if (a == b) M(a,b) = Complex(1.0,0.0) + M(a,b);\n    }} // end of a/b loops\n    T = M.inverse()*V;                        // invert to obtain  T(k,k0)\n    Complex Tonshell = T(Ngrid);\n    double delta1 = atan(Tonshell.imag()/Tonshell.real())*180.0/M_PI;\n    double delta2 = asin(-mu*k0*Tonshell.real()/M_PI)*90.0/M_PI;\n    ofs << k0 << \" \" << delta1 << \" \" << delta2 << \" \" << deltaExact(k0) << endl;\n  } // end of k0 loop \n  cout << \" k, delta1 , delta2, delta_exact in T.dat \" << endl;\n  ofs.close();\n  return 0;\n}\n", "meta": {"hexsha": "b4f2c82b0f9e68acff6fd38bda7da37d513b18bb", "size": 2856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CH21/TMATRIX/T.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": "CH21/TMATRIX/T.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": "CH21/TMATRIX/T.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": 27.2, "max_line_length": 81, "alphanum_fraction": 0.525210084, "num_tokens": 1029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6127432241616664}}
{"text": "/*\n * Copyright (c) 2013-2018 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef DKA_HPP\n#define DKA_HPP\n\n#include <limits>\n#include <cmath>\n#include <boost/numeric/ublas/vector.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/complex.hpp>\n#include <kv/constants.hpp>\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\ntemplate <class T>\nstatic T inline eval_polynomial (const ub::vector<T>& p, const T& x)\n{\n\tint i;\n\tT r;\n\tint s = p.size();\n\n\tr = p(s-1);\n\tfor (i=s-2; i>=0; i--) {\n\t\tr = r * x + p(i);\n\t}\n\n\treturn r;\n}\n\n// Durand Kerner Aberth algorithm\n\ntemplate <class T>\nbool dka(const ub::vector< kv::complex<T> >& p, ub::vector< kv::complex<T> >& x, T epsilon = std::numeric_limits<T>::epsilon())\n{\n\tint i, j;\n\tint s = p.size();\n\tint n = s - 1;\n\tub::vector< kv::complex<T> > a(s);\n\tkv::complex<T> c;\n\tub::vector<T> b;\n\tT r, tmp, norm1, norm2, norm3;\n\tub::vector<T> db;\n\tub::vector< kv::complex<T> > dx(n);\n\tT pi = kv::constants<T>::pi();\n\tkv::complex<T> f, df;\n\n\tusing std::abs;\n\tusing std::pow;\n\n\tif (p(n).real() * p(n).real() + p(n).imag() * p(n).imag() == 0.) {\n\t\treturn false;\n\t}\n\n\t// make equation b(r) = 0\n\n\tfor (i=0; i<s; i++) a(i) = p(i);\n\n\tc = -a(n-1) / (a(n) * n);\n\tfor (i=1; i<=n; i++) {\n\t\tfor (j = n; j >= i; j--) {\n\t\t\ta(j-1) += a(j) * c;\n\t\t}\n\t}\n\n\tb.resize(s);\n\tfor (i=0; i<n-1; i++) b(i) = -abs(a(i));\n\tb(n-1) = 0.;\n\tb(n) = abs(a(n));\n\t// prepare for the case where b(0)...b(n-2) are 0.\n\tb(0) = std::min(b(0), -std::numeric_limits<T>::epsilon());\n\n\t// initial guess for b(r) = 0\n\tr = 0.;\n\tfor (i=0; i<n-1; i++) {\n\t\ttmp = pow(n * abs(b[i]/b[n]), 1.0/(n-i));\n\t\tif (tmp > r) r = tmp;\n\t}\n\n\t// db(r) = b'(r)\n\tdb.resize(n);\n\tfor (i=1; i<s; i++) db(i-1) = b(i) * i;\n\n\t// calculate radius by Newton's method for equation b(r) = 0\n\twhile (true) {\n\t\ttmp = eval_polynomial(b, r) / eval_polynomial(db, r);\n\t\tr -= tmp;\n\t\tif (abs(tmp) < n * abs(r) * epsilon) break;\n\t}\n\n\t// set Aberth's initial values\n\n\tx.resize(n);\n\tfor (i=0; i<n; i++) {\n\t\tx(i) = c + r * exp((2. * i * pi / n + pi / (2. * n)) * kv::complex<T>::i());\n\t}\n\n\t// max(|pi|)\n\tnorm3 = 0.;\n\tfor (i=0; i<s; i++) {\n\t\tnorm3 = std::max(norm3, abs(p(i)));\n\t}\n\n\t// Durand Kerner algorithm\n\n\twhile (true) {\n\t\tfor (i=0; i<n; i++) {\n\t\t\tf = eval_polynomial(p, x(i));\n\t\t\tdf = p(n);\n\t\t\tfor (j=0; j<n; j++) {\n\t\t\t\tif (j == i) continue;\n\t\t\t\tdf *= x(i) - x(j);\n\t\t\t}\n\t\t\tif (df.real() * df.real() + df.imag() * df.imag() == 0.) {\n\t\t\t\tdx(i) = 0.;\n\t\t\t} else {\n\t\t\t\tdx(i) = f / df;\n\t\t\t}\n\t\t}\n\n\t\tx -= dx;\n\n\t\tnorm1 = 1.;\n\t\tnorm2 = 0.;\n\t\tfor (i=0; i<n; i++) {\n\t\t\tnorm1 = std::max(norm1, abs(x(i)));\n\t\t\tnorm2 = std::max(norm2, abs(dx(i)));\n\t\t}\n\t\tif (norm2 <= n * norm1 * epsilon) break;\n\t\tif (abs(f) <= n * norm3 * epsilon) break;\n\t}\n\n\treturn true;\n}\n\n// error estimation using Smith's theorem\n\ntemplate <class T>\nub::vector< kv::complex< interval<T> > > smith_error(const ub::vector< kv::complex< interval<T> > >& p, const ub::vector< kv::complex<T> >& x)\n{\n\tint i, j;\n\tint s = p.size();\n\tint n = s - 1;\n\tub::vector< kv::complex< interval<T> > > x2, x3(n);\n\tkv::complex< interval<T> > f, df;\n\tT err;\n\tub::vector<int> unified(n);\n\tbool flag;\n\n\tx2 = x;\n\n\tfor (i=0; i<n; i++) {\n\t\tf = eval_polynomial(p, x2(i));\n\t\tdf = p(n);\n\t\tfor (j=0; j<n; j++) {\n\t\t\tif (j == i) continue;\n\t\t\tdf *= x2(i) - x2(j);\n\t\t}\n\t\tif (zero_in(df.real() * df.real() + df.imag() * df.imag())) {\n\t\t\terr = std::numeric_limits<T>::infinity();\n\t\t} else {\n\t\t\terr = abs(n * f / df).upper();\n\t\t}\n\t\tx3(i).real() = x2(i).real() + err * interval<T>(-1., 1.);\n\t\tx3(i).imag() = x2(i).imag() + err * interval<T>(-1., 1.);\n\t}\n\n\t/* unify overlapping solutions */\n\n\tfor (i=0; i<n; i++) unified(i) = -1; /* not unified */\n\n\twhile (true) {\n\t\tflag = true;\n\t\tfor (i=0; i<n-1; i++) {\n\t\t\tif (unified(i) != -1) continue;\n\t\t\tfor (j=i; j<n; j++) {\n\t\t\t\tif (unified(j) != -1) continue;\n\t\t\t\tif (overlap(x3(i).real(), x3(j).real()) && overlap(x3(i).imag(), x3(j).imag())) {\n\t\t\t\t\tx3(i).real() = interval<T>::hull(x3(i).real(), x3(j).real());\n\t\t\t\t\tx3(i).imag() = interval<T>::hull(x3(i).imag(), x3(j).imag());\n\t\t\t\t\tunified(j) = i; /* x3(j) is unified to x3(i) */\n\t\t\t\t\tflag = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (flag) break;\n\t}\n\n\tfor (i=0; i<n; i++) {\n\t\tif (unified(i) != -1) x3(i) = x3(unified(i));\n\t}\n\n\treturn x3;\n}\n\n// verified Durand Kerner Aberth\n\ntemplate <class T>\nbool vdka(const ub::vector< kv::complex< interval<T> > >& p, ub::vector< kv::complex< interval<T> > >& result, T epsilon = std::numeric_limits<T>::epsilon())\n{\n\tint i;\n\tint s = p.size();\n\tint n = s - 1;\n\tub::vector< kv::complex< T > > p2(s), x2;\n\n\tif (zero_in(p(n).real() * p(n).real() + p(n).imag() * p(n).imag())) {\n\t\treturn false;\n\t}\n\n\tfor (i=0; i<s; i++) {\n\t\tp2(i).real() = mid(p(i).real());\n\t\tp2(i).imag() = mid(p(i).imag());\n\t}\n\n\tdka(p2, x2, epsilon);\n\n\tresult = smith_error(p, x2);\n\treturn true;\n}\n\n} // namespace kv\n\n#endif // DKA_HPP\n", "meta": {"hexsha": "7090f47d9a2b57c3440e5f27acaa4b373fccf64c", "size": 4806, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/dka.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T07:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T07:11:09.000Z", "max_issues_repo_path": "src/interval/kv/dka.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interval/kv/dka.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.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.0789473684, "max_line_length": 157, "alphanum_fraction": 0.5214315439, "num_tokens": 1823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6127137297230117}}
{"text": "//Trevor Hickey\n//Homework 1: GCD\n//Sept. 11\n\n//STD\n#include <iostream>\n#include <string>\n#include <cmath>\n#include <functional>\n\n//Boost\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n//My Sources\n#include \"globals.hpp\"         // types & constants\n#include \"gcd_algorithms.hpp\"  // namespace\n#include \"algorithm.hpp\"       // class\n#include \"test_suite.hpp\"      // namespace\n\n//Function Decelerations\nvoid Validate_Algorithm_Correctness(void);\nvoid Test_Algorithm_Speed(void);\nvoid Output_Title_Of_Table(std::vector<Algorithm<>> const& algorithms);\nvoid Perform_Bit_Test(boost::random::mt19937 & gen, int i, std::vector<Algorithm<>> algorithms);\nvoid Output_Results(int i, std::vector<Algorithm<>> const& algorithms);\ntemplate <typename IntegerType> void Run_GCD_Performance_Test(Algorithm<IntegerType> & alg, IntegerType a, IntegerType b);\n\nint main(){\n\n\t//test that the algorithms work\n\tValidate_Algorithm_Correctness();\n\n\t//output speed performance data for each algorithm\n\tTest_Algorithm_Speed();\n\n\treturn EXIT_SUCCESS;\n}\n\n//Function Definitions\nvoid Validate_Algorithm_Correctness(void){\n\n\t//we generate some random numbers of different bit lengths and check edge cases to\n\t//make sure that the algorithms all produce the desired results.\n\t//If there is an issue, the function will report a message through std::cerr\n\tTest_Suite::Check_Algorithm_Validity ( GCD::Euclid_Recursive    );\n\tTest_Suite::Check_Algorithm_Validity ( GCD::Euclid_Iterative    );\n\tTest_Suite::Check_Algorithm_Validity ( GCD::Euclid_Unrolled     );\n\tTest_Suite::Check_Algorithm_Validity ( GCD::Euclid_Bit          );\n\tTest_Suite::Check_Algorithm_Validity ( GCD::Binary_Recursive    );\n\tTest_Suite::Check_Algorithm_Validity ( GCD::Binary_Iterative    );\n\tTest_Suite::Check_Algorithm_Validity ( GCD::Binary_Iterative_V2 );\n\tTest_Suite::Check_Algorithm_Validity ( GCD::CTZ                 );\n\tTest_Suite::Check_Algorithm_Validity ( GCD::Boost               );\n\n\t//I'm leaving these algorithms out, because they are slow\n\t//Test_Suite::Check_Algorithm_Validity (GCD::Brute_Force);\n\t//Test_Suite::Check_Algorithm_Validity (GCD::Factor);\n\n\treturn;\n}\nvoid Test_Algorithm_Speed(void){\n\n\t//a vector containing all of the different algorithms we will be testing\n\tstd::vector<Algorithm<>> algorithms;\n\talgorithms.push_back(Algorithm<>( \"Euclid_Recursive\"    ,GCD::Euclid_Recursive    ));\n\talgorithms.push_back(Algorithm<>( \"Euclid_Iterative\"    ,GCD::Euclid_Iterative    ));\n\talgorithms.push_back(Algorithm<>( \"Euclid_Unrolled\"     ,GCD::Euclid_Unrolled     ));\n\talgorithms.push_back(Algorithm<>( \"Euclid_Bit\"          ,GCD::Euclid_Bit          ));\n\talgorithms.push_back(Algorithm<>( \"Binary_Recursive\"    ,GCD::Binary_Recursive    ));\n\talgorithms.push_back(Algorithm<>( \"Binary_Iterative\"    ,GCD::Binary_Iterative    ));\n\talgorithms.push_back(Algorithm<>( \"Binary_Iterative_V2\" ,GCD::Binary_Iterative_V2 ));\n\talgorithms.push_back(Algorithm<>( \"CTZ\"                 ,GCD::CTZ                 ));\n\talgorithms.push_back(Algorithm<>( \"Boost\"               ,GCD::Boost               ));\n\n\n\t//build a generator and test the algorithm across a range of bit lengths\n\tboost::random::mt19937 gen(std::time(0));\n\tOutput_Title_Of_Table(algorithms);\n\tfor (auto i = constant::min_bit_length; i < constant::max_bit_length; ++i){\n\t\tPerform_Bit_Test(gen,i,algorithms);\n\t}\n\n\treturn;\n}\nvoid Output_Title_Of_Table(std::vector<Algorithm<>> const& algorithms){\n\n\tstd::cout << \"testing the speed of GCD algorithms in milliseconds (\" << constant::num_of_trials << \" trials for each bit length)\\n\";\n\t//print out a terrible title just so we know what algorithm is in each column\n\tfor (auto const& it: algorithms){std::cout << \"|\" << it.name << \"|\";}\n\tstd::cout << '\\n';\n\t\n\treturn;\n}\nvoid Perform_Bit_Test(boost::random::mt19937 & gen, int i, std::vector<Algorithm<>> algorithms){\n\n\t//loop through each algorithm and test its speed against random numbers of a particular bit length\n\tTestType a,b;\n\tauto dist = Test_Suite::Get_Specified_Bit_Length_Distribution(i);\n\tfor (int i = 0; i < constant::num_of_trials; ++i){\n\t\ta = dist(gen);\n\t\tb = dist(gen);\n\t\tfor (auto & it: algorithms){\n\t\t\tRun_GCD_Performance_Test(it,a,b);\n\t\t}\n\t}\n\n\t//once data is collected for each algorithm in regards to\n\t//specific bit length numbers, output the results.\n\t//NOTE: this data will be lost after the function returns.\n\t//This is because the algorithm classes will be re-used on different bit lengths.\n\tOutput_Results(i,algorithms);\n\n\treturn;\n}\nvoid Output_Results(int i, std::vector<Algorithm<>> const& algorithms){\n\n\t//output the total time it took to run the number of trials\n\t//*You know what, I'm just going to calculate the average in whatever graph software I use\n\tstd::cout << \"bit-length \" << i << \">\";\n\tfor (auto it: algorithms){\n\t\tstd::cout << \" \" << \"(\" << (it.total_time) << \")\";\n\t}\n\tstd::cout << '\\n';\n\n\treturn;\n}\ntemplate <typename IntegerType> void Run_GCD_Performance_Test(Algorithm<IntegerType> & alg, IntegerType a, IntegerType b){\n\n\tboost::posix_time::ptime startTime, endTime;\n\n\t//time the execution of the algorithm\n\tstartTime = boost::posix_time::microsec_clock::local_time();\n\talg.fun(a,b);\n\tendTime = boost::posix_time::microsec_clock::local_time();\n\n\talg.total_time += (endTime-startTime);\n\t++alg.trials;\n\n\treturn;\n}\n\n", "meta": {"hexsha": "8f45cd2c93ecfc66d5ca0493c3c63e4742aa0cd2", "size": 5371, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/GCD-Test-Suite/src/code/driver.cpp", "max_stars_repo_name": "luxe/CodeLang-compiler", "max_stars_repo_head_hexsha": "78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T07:43:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T13:12:32.000Z", "max_issues_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/GCD-Test-Suite/src/code/driver.cpp", "max_issues_repo_name": "luxe/CodeLang-compiler", "max_issues_repo_head_hexsha": "78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 371.0, "max_issues_repo_issues_event_min_datetime": "2019-05-16T15:23:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-04T15:45:27.000Z", "max_forks_repo_path": "source/code/scratch/old_repos/edinboro/CSCI-385/GCD-Test-Suite/src/code/driver.cpp", "max_forks_repo_name": "UniLang/compiler", "max_forks_repo_head_hexsha": "c338ee92994600af801033a37dfb2f1a0c9ca897", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-08-22T17:37:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-07T07:15:32.000Z", "avg_line_length": 37.2986111111, "max_line_length": 133, "alphanum_fraction": 0.7231428039, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619306896955, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6127137218278079}}
{"text": "//\n// Created by egrzrbr on 2019-04-26.\n//\n\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <stdio.h>\n/*****************\n * Main function *\n *****************/\n\n#include <unistd.h>\n#include <time.h>\n#include <iostream>\n\n#define EIGEN_STACK_ALLOCATION_LIMIT 0\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n/**********************************\n * Pseudo-random number generator *\n **********************************/\n\n#define EIGEN_COUT(mat) {std::cout << #mat << \" = {\\n\" << mat << \"}\" << std::endl;}\n\nstatic uint64_t mat_rng[2] = {11ULL, 1181783497276652981ULL};\n\nstatic inline uint64_t xorshift128plus(uint64_t s[2]) {\n\n\tuint64_t x, y;\n\tx = s[0], y = s[1];\n\ts[0] = y;\n\tx ^= x << 23;\n\ts[1] = x ^ y ^ (x >> 17) ^ (y >> 26);\n\ty += s[1];\n\treturn y;\n}\n\ndouble mat_drand(void) {\n\n\treturn (xorshift128plus(mat_rng) >> 11) * (1.0 / 9007199254740992.0);\n}\n\ntemplate<class Matrix_t>\nvoid mat_gen_random_ublas(Matrix_t &m) {\n\n\tssize_t i, j;\n\tfor (i = 0; i < m.rows(); ++i)\n\t\tfor (j = 0; j < m.cols(); ++j)\n\t\t\tm(i, j) = mat_drand();\n}\n\ntemplate<class Matrix_t>\nvoid mat_arange(Matrix_t &m) {\n\n\tconst ssize_t N = m.rows();\n\tconst ssize_t M = m.cols();\n\tssize_t i, j;\n\tfor (i = 0; i < N; ++i)\n\t\tfor (j = 0; j < M; ++j)\n\t\t\tm(i, j) = j * N + i;\n}\n\ntemplate<typename T, size_t N, size_t TRIALS>\nvoid test_trials(const char opt = 'r') {\n\n\n\tint c;\n\tclock_t t;\n\n\t{\n\n\t\tMatrixXf a(N, N), b(N, N), m(N, N);\n\n\t\tif (opt == 'r') {\n\t\t\tmat_gen_random_ublas(a);\n\t\t\tmat_gen_random_ublas(b);\n\t\t} else {\n\t\t\tmat_arange(a);\n\t\t\tmat_arange(b);\n\t\t}\n\n\t\tt = clock();\n\t\tfor (int i = 0; i < TRIALS; i++)\n\t\t\tm = a * b;\n\t\tfprintf(stderr, \"CPU time: %g\\n\", (double) (clock() - t) / CLOCKS_PER_SEC);\n\n\t\tif (N > 10) return;\n\t\tEIGEN_COUT(a)\n\t\tEIGEN_COUT(b)\n\t\tEIGEN_COUT(c)\n\t}\n\n\t{\n\n\t\tMatrix<float, N, N> a, b, c;\n\n\t\tif (opt == 'r') {\n\t\t\tmat_gen_random_ublas(a);\n\t\t\tmat_gen_random_ublas(b);\n\t\t} else {\n\t\t\tmat_arange(a);\n\t\t\tmat_arange(b);\n\t\t}\n\n\n\t\tt = clock();\n\n\t\tfor (int i = 0; i < TRIALS; i++)\n\t\t\tc = a * b;\n\t\tfprintf(stderr, \"CPU time: %g\\n\", (double) (clock() - t) / CLOCKS_PER_SEC);\n\t\tif (N > 10) return;\n\t\tEIGEN_COUT(a)\n\t\tEIGEN_COUT(b)\n\t\tEIGEN_COUT(c)\n\t}\n\n}\n\ntemplate<typename T, size_t N>\nvoid matNN_mul_matNN(const char opt = 'r') {\n\n\tstd::cout << \"matNN_mul_matNN\" << std::endl;\n\n\tclock_t t;\n\tMatrix<T, N, N> a;\n\tMatrix<T, N, N> b;\n\tMatrix<T, N, N> c;\n\n\tif (opt == 'r') {\n\t\tmat_gen_random_ublas(a);\n\t\tmat_gen_random_ublas(b);\n\t} else {\n\t\tmat_arange(a);\n\t\tmat_arange(b);\n\t}\n\n\tt = clock();\n\n\tc = a * b;\n\n\tstd::cout << c.size() << std::endl;\n\tfprintf(stderr, \"CPU time: %g\\n\", (double) (clock() - t) / CLOCKS_PER_SEC);\n\tif (N > 10) return;\n\tEIGEN_COUT(a)\n\tEIGEN_COUT(b)\n\tEIGEN_COUT(c)\n}\n\ntemplate<typename T, size_t N>\nvoid vecN1_mul_vec1N(const char opt = 'r') {\n\n\tclock_t t;\n\tMatrix<T, N, 1> a;\n\tMatrix<T, 1, N> b;\n\tMatrix<T, N, N> c;\n\n\tif (opt == 'r') {\n\t\tmat_gen_random_ublas(a);\n\t\tmat_gen_random_ublas(b);\n\t} else {\n\t\tmat_arange(a);\n\t\tmat_arange(b);\n\t}\n\tt = clock();\n\n\tc = a * b;\n\n\tstd::cout << c.size() << std::endl;\n\tfprintf(stderr, \"CPU time: %g\\n\", (double) (clock() - t) / CLOCKS_PER_SEC);\n\tif (N > 10) return;\n\tEIGEN_COUT(a)\n\tEIGEN_COUT(b)\n\tEIGEN_COUT(c)\n}\n\n\ntemplate<typename T, size_t N, size_t M>\nvoid matNM_mul_vecM1(const char opt = 'r') {\n\n\tclock_t t;\n\tMatrix<T, N, M> a;\n\tMatrix<T, M, 1> b;\n\tMatrix<T, N, 1> c;\n\n\tif (opt == 'r') {\n\t\tmat_gen_random_ublas(a);\n\t\tmat_gen_random_ublas(b);\n\t} else {\n\t\tmat_arange(a);\n\t\tmat_arange(b);\n\t}\n\n\tt = clock();\n\n\tc = a * b;\n\n\tstd::cout << c.size() << std::endl;\n\tfprintf(stderr, \"CPU time: %g\\n\", (double) (clock() - t) / CLOCKS_PER_SEC);\n\tif (N > 10) return;\n\tEIGEN_COUT(a)\n\tEIGEN_COUT(b)\n\tEIGEN_COUT(c)\n}\n\n\ntemplate<typename T, size_t N>\nvoid vec1N_mul_vecN1(const char opt = 'r') {\n\n\tclock_t t;\n\tMatrix<T, 1, N> a;\n\tMatrix<T, N, 1> b;\n\tMatrix<T, 1, 1> c;\n\n\tif (opt == 'r') {\n\t\tmat_gen_random_ublas(a);\n\t\tmat_gen_random_ublas(b);\n\t} else {\n\t\tmat_arange(a);\n\t\tmat_arange(b);\n\t}\n\n\tt = clock();\n\n\tc = a * b;\n\n\tstd::cout << c.size() << std::endl;\n\tfprintf(stderr, \"CPU time: %g\\n\", (double) (clock() - t) / CLOCKS_PER_SEC);\n\tif (N > 10) return;\n\tEIGEN_COUT(a)\n\tEIGEN_COUT(b)\n\tEIGEN_COUT(c)\n}\n\n\nint main(int argc, char *argv[]) {\n\n\tconstexpr int N = 500;\n\tconstexpr int M = 400;\n\tconstexpr int K = 10;\n\tclock_t t;\n\n\tmatNN_mul_matNN<float, N>();\n\tmatNM_mul_vecM1<float, N, M>();\n\tvecN1_mul_vec1N<float, N>();\n\tvec1N_mul_vecN1<float, N>();\n\n\n\tmatNN_mul_matNN<float, 5>(0);\n\tmatNM_mul_vecM1<float, 5, 4>(0);\n\tvecN1_mul_vec1N<float, 5>(0);\n\tvec1N_mul_vecN1<float, 5>(0);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "e8368e8efac113a2ed40f164bba700305dc1adf6", "size": 4512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen/matmul_eigen.cpp", "max_stars_repo_name": "robgrzel/Eigen_Boost_OpenMPI_GoogleTests_Examples", "max_stars_repo_head_hexsha": "40e5eb9385ae216529d39b314925106c5766a674", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eigen/matmul_eigen.cpp", "max_issues_repo_name": "robgrzel/Eigen_Boost_OpenMPI_GoogleTests_Examples", "max_issues_repo_head_hexsha": "40e5eb9385ae216529d39b314925106c5766a674", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigen/matmul_eigen.cpp", "max_forks_repo_name": "robgrzel/Eigen_Boost_OpenMPI_GoogleTests_Examples", "max_forks_repo_head_hexsha": "40e5eb9385ae216529d39b314925106c5766a674", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.4208494208, "max_line_length": 83, "alphanum_fraction": 0.5815602837, "num_tokens": 1625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6127137169015058}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef METRO_LOG_SUM_EXP_HPP\n#define METRO_LOG_SUM_EXP_HPP\n\n#include <vector>\n#include <Eigen/Core>\n\nnamespace metro {\n\t// Compute the log of a sum of exponentials via an algorithm that \n\ttemplate< typename Matrix, typename Nonmissingness >\n\tdouble log_sum_exp( Matrix const& data, Nonmissingness const& nonmissingness ) {\n\t\tassert( data.rows() == nonmissingness.rows() ) ;\n\t\tassert( data.cols() == nonmissingness.cols() ) ;\n\t\tif( data.size() == 0 || nonmissingness.sum() == 0 ) {\n\t\t\treturn 0.0 ;\n\t\t}\n\t\tdouble max_value = ( data.array() * nonmissingness.array() ).maxCoeff() ;\n\t\tif( max_value == -std::numeric_limits< double >::infinity() ) {\n\t\t\treturn max_value ;\n\t\t}\n\t\tEigen::MatrixXd const exponential = ( data - Eigen::MatrixXd::Constant( data.rows(), data.cols(), max_value ) ).array().exp() ;\n\t\treturn max_value + std::log( ( exponential.array() * nonmissingness.array() ).sum() ) ;\n\t}\n\n\t// Ditto but assuming all values are present.\n\ttemplate< typename Matrix >\n\tdouble log_sum_exp( Matrix const& data ) {\n\t\tif( data.size() == 0 ) {\n\t\t\treturn 0.0 ;\n\t\t}\n\t\tdouble max_value = data.array().maxCoeff() ;\n\t\tif( max_value == -std::numeric_limits< double >::infinity() ) {\n\t\t\treturn max_value ;\n\t\t}\n\t\tEigen::MatrixXd const exponential = ( data - Eigen::MatrixXd::Constant( data.rows(), data.cols(), max_value ) ).array().exp() ;\n\t\treturn max_value + std::log( exponential.array().sum() ) ;\n\t}\n\n\t// Ditto but assuming all values are present.\n\ttemplate<>\n\tdouble log_sum_exp( std::vector< double > const& data ) ;\n\n\tvoid rowwise_log_sum_exp( Eigen::MatrixXd const&, Eigen::VectorXd* result ) ;\n\tvoid rowwise_log_sum_exp( Eigen::MatrixXd const&, Eigen::MatrixXd const& nonmissingness, Eigen::VectorXd* result ) ;\n}\n\n#endif\n", "meta": {"hexsha": "403f50e18e725c5cd364c13962da43e102f1ab8f", "size": 1937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "metro/include/metro/log_sum_exp.hpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "metro/include/metro/log_sum_exp.hpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "metro/include/metro/log_sum_exp.hpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5471698113, "max_line_length": 129, "alphanum_fraction": 0.6819824471, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.6126264477909602}}
{"text": "/***************************************************************************************\n    File: perceptron.cpp\n\n    Description:\n      Runs an arbitrary-precision rational valued perceptron algorithm.\n      This program will infinite loop if the dataset is not linearly separable.\n      Reads input from stdin and outputs to stdout.\n\n    Input: a training set\n    Example:\n\n    2     // number of training vectors\n    2     // number of features per vector\n    1     // label 1\n    1/2   // vector 1, feature 1\n    1.2   // vector 1, feature 2\n    0     // label 2\n    0     // vector 2, feature 1\n    1%3   // vector 2, feature 2\n\n    resulting in the following vectors:\n      <1 % 1, 1 % 2, 6 % 5> and <-1 % 1, 0 % 1, 1 % 3>\n      // both % & / can be used as fraction.\n      // labels are transformed from {0, 1} to {-1, 1} and appended to front of vectors.\n\n    Output:\n      This program will either infinite loop or termintate after outputing a weight\n      vector representing the hyperplane sperating the data (1 feature per line).\n\n    Example output (for the above example input).\n    -1 % 1\n    1 % 1\n    7 % 5\n\n    which represents the following 2D line.\n    y = -7/5x - 1/||<1 % 1, 7 % 5>||\n ***************************************************************************************/\n#include <iostream>\n#include <string>\n#include <vector>\n#include <limits>\n\n#include <boost/rational.hpp>\n#include <boost/multiprecision/gmp.hpp>\n\ntypedef boost::multiprecision::mpz_int Z;\ntypedef boost::rational<Z> Q;\ntypedef std::vector<Q> Qvec;\n\nstd::istream& operator >> (std::istream& ins, Q& q);\nstd::ostream& operator << (std::ostream& outs, const Q& q);\n\n// Vector Operations\nQ dot (const Qvec& x, const Qvec& y);\nQvec add (const Qvec& x, const Qvec& y);\nQvec mult (const Qvec& x, const Q q);\ninline int sign(Q q) { return (0 < q) - (0 > q); } // 1 or -1\n\nQvec perceptron(const std::vector<Qvec>& features, const std::vector<int>& labels);\n\nint main(int argc, char ** argv){\n  std::size_t nvecs, nfeats;\n  std::cin >> nvecs >> nfeats;\n\n  std::vector<Qvec> vecs;\n  std::vector<int>  lbls;\n\n  for (std::size_t i = 0; i < nvecs; ++i){\n    int lbl;\n    std::cin >> lbl;\n    lbls.push_back(lbl*2-1); //{0,1} => {-1, 1}\n\n    std::cin.ignore(std::numeric_limits<int>::max(),'\\n'); //ignore until new line\n\n    Qvec vec(1, Q(1, 1));\n    for (std::size_t j = 0; j < nfeats; ++j){\n      Q q;\n      std::cin >> q;\n      vec.push_back(q);\n    }\n    vecs.push_back(vec);\n  }\n\n  Qvec w = perceptron(vecs, lbls);\n\n  if (argc != 1){ // pretty print\n    std::cout << \"<\";\n    for (std::size_t i = 0; i < w.size(); ++i){\n      std::cout << w[i];\n      if (i != w.size() - 1){\n        std::cout << \", \";\n      }\n    }\n    std::cout << \">\" << std::endl;\n  } else {\n    for (std::size_t i = 0; i < w.size(); ++i){\n      std::cout << w[i] << std::endl;\n    }\n  }\n  return 0;\n}\n\n// for now, we assume each number is on it's own line\nstd::istream& operator >> (std::istream& ins, Q& q){\n  Z n, d;\n  char c;\n\n  std::string num;\n\n  getline(ins, num);\n\n  std::size_t pos;\n  if ((pos = num.find('%')) != std::string::npos ||\n      (pos = num.find('/')) != std::string::npos){  // fractional\n    n = Z(num.substr(0, pos));\n    d = Z(num.substr(pos+1));\n  } else if ((pos = num.find('.')) != std::string::npos){ // floating point\n    std::string N, D;\n    N = num.substr(0, pos);\n    D = num.substr(pos+1);\n    d = 1;\n    for (std::size_t i = 0; i < D.length(); ++i){ // pow doesn't work (it has limited precision)\n      d *= 10;\n    }\n    while (D[0] == '0'){\n      D = D.substr(1);\n    }\n    n = Z(N)*d + Z(D);\n  } else { // integral\n    n = Z(num);\n    d = 1;\n  }\n\n  q = Q(n, d);\n\n  return ins;\n}\n\nstd::ostream& operator << (std::ostream& outs, const Q& q){\n  return outs << q.numerator() << \" % \" << q.denominator();\n}\n\nQ dot (const Qvec& x, const Qvec& y){\n  Q res(0, 1);\n  for (std::size_t i = 0; i < x.size(); ++i){\n    res += x[i] * y[i];\n  }\n  return res;\n}\n\nQvec add (const Qvec& x, const Qvec& y){\n  Qvec res(x.size());\n  for (std::size_t i = 0; i < x.size(); ++i){\n    res[i] = x[i] + y[i];\n  }\n  return res;\n}\n\nQvec mult (const Qvec& x, const Q q){\n  Qvec res(x.size());\n  for (std::size_t i = 0; i < x.size(); ++i){\n    res[i] = x[i] * q;\n  }\n  return res;\n}\n\nQvec perceptron(const std::vector<Qvec>& features, const std::vector<int>& labels){\n  Qvec weights(features[0].size(), Q(0, 1));\n\n  size_t fuel = 0;\n  bool converged;\n  do {\n    ++fuel;\n    converged = true;\n\n    for (std::size_t i = 0; i < features.size(); ++i){\n      Q res = dot(weights, features[i]);\n\n      if (sign(res) != labels[i] || res == Q(0,1)) { // wrong sign or res = 0.\n        weights = add(weights, mult(features[i], Q(labels[i], 1)));\n        converged = false;\n      }\n    }\n  } while (!converged);\n  std::cerr << \"Fuel: \" << fuel << std::endl;\n  return weights;\n}\n", "meta": {"hexsha": "7e63f34c176013232c49eb3cb2276079ca6c657e", "size": 4832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Benchmarks/cpp/perceptron.cpp", "max_stars_repo_name": "billy-price/CoqPerceptron", "max_stars_repo_head_hexsha": "e21936d4f405de495594183d5ee51efed5214dcf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-03-07T20:47:44.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-04T18:18:07.000Z", "max_issues_repo_path": "Benchmarks/cpp/perceptron.cpp", "max_issues_repo_name": "billy-price/CoqPerceptron", "max_issues_repo_head_hexsha": "e21936d4f405de495594183d5ee51efed5214dcf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Benchmarks/cpp/perceptron.cpp", "max_forks_repo_name": "billy-price/CoqPerceptron", "max_forks_repo_head_hexsha": "e21936d4f405de495594183d5ee51efed5214dcf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-15T13:32:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-15T13:32:33.000Z", "avg_line_length": 25.7021276596, "max_line_length": 96, "alphanum_fraction": 0.5314569536, "num_tokens": 1543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.6126264421183983}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <complex>\n#include \"../include/WindowingAnalysis.h\"\n#include \"../../JeanBaptiste/include/tools/RealComplexConversion.h\"\n#include \"../../JeanBaptiste/include/windowing/BartlettWindow.h\"\n#include \"../../JeanBaptiste/include/windowing/BlackmanWindow.h\"\n#include \"../../JeanBaptiste/include/windowing/BlackmanHarrisWindow.h\"\n#include \"../../JeanBaptiste/include/windowing/CosineWindow.h\"\n#include \"../../JeanBaptiste/include/windowing/FlatTopWindow.h\"\n#include \"../../JeanBaptiste/include/windowing/HammingWindow.h\"\n#include \"../../JeanBaptiste/include/windowing/VonHannWindow.h\"\n#include \"../../JeanBaptiste/include/windowing/WelchWindow.h\"\n#include <string>\n\nnamespace ut = boost::unit_test;\nnamespace jb = jeanbaptiste;\nnamespace jt = jeanbaptiste::tools;\nnamespace jw = jeanbaptiste::windowing;\n\nclass WindowCalculationFixture\n{\nprotected:\n    std::vector<double> workingSet_;\n    std::vector<double> expectedOut_;\n    static const unsigned kSampleCnt_ = 128;\n    Utilities::WindowingAnalysis<double> analysis_;\n    jt::Real2Complex<std::complex<double>> real2ComplexConverter_;\n    jt::Complex2Real<std::complex<double>> complex2RealConverter_;\n    bool initialized_;\n\npublic:\n    WindowCalculationFixture()\n    {\n        workingSet_.clear();\n        expectedOut_.clear();\n    }\n\n    ~WindowCalculationFixture()\n    {}\n};\n\n\nBOOST_FIXTURE_TEST_SUITE(WindowCalculationTestSuite, WindowCalculationFixture)\n\n    BOOST_AUTO_TEST_CASE(bartlett)\n    {\n        BOOST_TEST((initialized_ = analysis_.initialize(\"../../test cases/WinBartlettTest.xml\", \"win.in\", workingSet_, \"win.out\", expectedOut_)), \"Loading test data failed.\");\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Checking Bartlett window samples.\");\n\n        jw::BartlettWindow<std::integral_constant<int, kSampleCnt_>, std::complex<double>> bartlett;\n\n        auto complexData = real2ComplexConverter_(workingSet_);\n        bartlett(&complexData[0]);\n        auto realData = complex2RealConverter_(complexData);\n\n        analysis_.checkOutput(realData, expectedOut_);\n    }\n\n    BOOST_AUTO_TEST_CASE(blackman_harris)\n    {\n        BOOST_TEST((initialized_ = analysis_.initialize(\"../../test cases/WinBlackmanHarrisTest.xml\", \"win.in\", workingSet_, \"win.out\", expectedOut_)), \"Loading test data failed.\");\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Checking Blackman Harris window samples.\");\n\n        jw::BlackmanHarrisWindow<std::integral_constant<int, kSampleCnt_>, std::complex<double>> blackmanHarris;\n\n        auto complexData = real2ComplexConverter_(workingSet_);\n        blackmanHarris(&complexData[0]);\n        auto realData = complex2RealConverter_(complexData);\n\n        analysis_.checkOutput(realData, expectedOut_);\n    }\n\n    BOOST_AUTO_TEST_CASE(blackman)\n    {\n        BOOST_TEST((initialized_ = analysis_.initialize(\"../../test cases/WinBlackmanTest.xml\", \"win.in\", workingSet_, \"win.out\", expectedOut_)), \"Loading test data failed.\");\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Checking Blackman window samples.\");\n\n        jw::BlackmanWindow<std::integral_constant<int, kSampleCnt_>, std::complex<double>> blackman;\n\n        auto complexData = real2ComplexConverter_(workingSet_);\n        blackman(&complexData[0]);\n        auto realData = complex2RealConverter_(complexData);\n\n        analysis_.checkOutput(realData, expectedOut_);\n    }\n\n    BOOST_AUTO_TEST_CASE(cosine)\n    {\n        BOOST_TEST((initialized_ = analysis_.initialize(\"../../test cases/WinCosineTest.xml\", \"win.in\", workingSet_, \"win.out\", expectedOut_)), \"Loading test data failed.\");\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Checking Cosine window samples.\");\n\n        jw::CosineWindow<std::integral_constant<int, kSampleCnt_>, std::complex<double>> cosineWin;\n\n        auto complexData = real2ComplexConverter_(workingSet_);\n        cosineWin(&complexData[0]);\n        auto realData = complex2RealConverter_(complexData);\n\n        analysis_.checkOutput(realData, expectedOut_);\n    }\n\n    BOOST_AUTO_TEST_CASE(flat_top)\n    {\n        BOOST_TEST((initialized_ = analysis_.initialize(\"../../test cases/WinFlatTopTest.xml\", \"win.in\", workingSet_, \"win.out\", expectedOut_)), \"Loading test data failed.\");\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Checking Flat Top window samples.\");\n\n        jw::FlatTopWindow<std::integral_constant<int, kSampleCnt_>, std::complex<double>> flatTopWin;\n\n        auto complexData = real2ComplexConverter_(workingSet_);\n        flatTopWin(&complexData[0]);\n        auto realData = complex2RealConverter_(complexData);\n\n        analysis_.checkOutput(realData, expectedOut_);\n    }\n\n    BOOST_AUTO_TEST_CASE(hamming)\n    {\n        BOOST_TEST((initialized_ = analysis_.initialize(\"../../test cases/WinHammingTest.xml\", \"win.in\", workingSet_, \"win.out\", expectedOut_)), \"Loading test data failed.\");\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Checking Hamming window samples.\");\n\n        jw::HammingWindow<std::integral_constant<int, kSampleCnt_>, std::complex<double>> hammingWin;\n\n        auto complexData = real2ComplexConverter_(workingSet_);\n        hammingWin(&complexData[0]);\n        auto realData = complex2RealConverter_(complexData);\n\n        analysis_.checkOutput(realData, expectedOut_);\n    }\n\n    BOOST_AUTO_TEST_CASE(von_hann)\n    {\n        BOOST_TEST((initialized_ = analysis_.initialize(\"../../test cases/WinvonHannTest.xml\", \"win.in\", workingSet_, \"win.out\", expectedOut_)), \"Loading test data failed.\");\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Checking von Hann window samples.\");\n\n        jw::VonHannWindow<std::integral_constant<int, kSampleCnt_>, std::complex<double>> vonHannWin;\n\n        auto complexData = real2ComplexConverter_(workingSet_);\n        vonHannWin(&complexData[0]);\n        auto realData = complex2RealConverter_(complexData);\n\n        analysis_.checkOutput(realData, expectedOut_);\n    }\n\n    BOOST_AUTO_TEST_CASE(welch)\n    {\n        BOOST_TEST((initialized_ = analysis_.initialize(\"../../test cases/WinWelchTest.xml\", \"win.in\", workingSet_, \"win.out\", expectedOut_)), \"Loading test data failed.\");\n        if (!initialized_)\n            return;\n\n        BOOST_TEST_MESSAGE(\"Checking Welch window samples.\");\n\n        jw::WelchWindow<std::integral_constant<int, kSampleCnt_>, std::complex<double>> welchWin;\n\n        auto complexData = real2ComplexConverter_(workingSet_);\n        welchWin(&complexData[0]);\n        auto realData = complex2RealConverter_(complexData);\n\n        analysis_.checkOutput(realData, expectedOut_);\n    }\n\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "8fb9434ebe4f8a0ff9bdcc302d44b798e428c11a", "size": 6749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "JeanBaptiste.Test/src/FixtureWindowCalculation.cpp", "max_stars_repo_name": "JoergWarthemann/jeanbaptiste", "max_stars_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "JeanBaptiste.Test/src/FixtureWindowCalculation.cpp", "max_issues_repo_name": "JoergWarthemann/jeanbaptiste", "max_issues_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JeanBaptiste.Test/src/FixtureWindowCalculation.cpp", "max_forks_repo_name": "JoergWarthemann/jeanbaptiste", "max_forks_repo_head_hexsha": "cda9f5e80c126fa8612ce1515b2f904056c09fda", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2872928177, "max_line_length": 181, "alphanum_fraction": 0.6961031264, "num_tokens": 1526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6126264400873911}}
{"text": "#include <bits/stdc++.h>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\ntypedef long long ll;\ntypedef vector <int> vi;\n\nint main(){\n    ios_base::sync_with_stdio(false);\n    cin.tie(nullptr);\n    freopen(\"in.txt\", \"r\", stdin);\n    freopen(\"out.txt\", \"w\", stdout);\n    int tc; cin >> tc;\n    cpp_int n, ans;\n    while(tc--){\n        cin >> n;\n        ans = 24 + n * (-18 + n * (23 + n * (-6 + n)));\n        ans /= 24;\n        cout << ans << \"\\n\";\n    }\n    return 0;\n}", "meta": {"hexsha": "28e26ba6c2e43837f4fa777fb265e7da490fb040", "size": 524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/How Many Pieces of Land?.cpp", "max_stars_repo_name": "satvik007/uva", "max_stars_repo_head_hexsha": "72a763f7ed46a34abfcf23891300d68581adeb44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-08-12T06:09:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-16T02:31:27.000Z", "max_issues_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/How Many Pieces of Land?.cpp", "max_issues_repo_name": "satvik007/uva", "max_issues_repo_head_hexsha": "72a763f7ed46a34abfcf23891300d68581adeb44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/How Many Pieces of Land?.cpp", "max_forks_repo_name": "satvik007/uva", "max_forks_repo_head_hexsha": "72a763f7ed46a34abfcf23891300d68581adeb44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8181818182, "max_line_length": 55, "alphanum_fraction": 0.5515267176, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843131, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.6125653046826298}}
{"text": "// Copyright (c) 2021 Graphcore Ltd. All rights reserved.\n\n#ifndef poplibs_support_log_arithmetic_hpp\n#define poplibs_support_log_arithmetic_hpp\n\n#ifndef INCLUDE_IN_ASSEMBLER\n// Conditionally avoid including functions that use multi_array\n#ifndef __POPC__\n#include <boost/multi_array.hpp>\n#endif\n\nnamespace poplibs_support {\nnamespace log {\n\ninline constexpr auto probabilityOne = 0;\ninline constexpr auto probabilityZero = -65504; // Min HALF\n\n// Given log values, perform an equivalent `linear add` operation\ntemplate <typename FPType> FPType add(const FPType a_, const FPType b_) {\n  FPType a = a_ < b_ ? b_ : a_;\n  FPType b = a_ < b_ ? a_ : b_;\n  return a + std::log(1 + std::exp(b - a));\n}\n\n// Given log values, perform an equivalent `linear sub` operation\ntemplate <typename FPType> FPType sub(const FPType a_, const FPType b_) {\n  FPType a = a_ < b_ ? b_ : a_;\n  FPType b = a_ < b_ ? a_ : b_;\n  return a + std::log(1 - std::exp(b - a));\n}\n\n// Given log values, perform an equivalent `linear mul` operation\ntemplate <typename FPType> FPType mul(const FPType a, const FPType b) {\n  return a + b;\n}\n// Given log values, perform an equivalent `linear divide` operation\ntemplate <typename FPType> FPType div(const FPType a, const FPType b) {\n  return a - b;\n}\n\n#ifndef __POPC__\n\n// TODO Move out of log namespace, or do log(softmax(x)) - this is just\n// softmax(x)\n// Simply to save having to carefully enter values, use a softmax to\n// convert them into probabilities\ntemplate <typename FPType>\nboost::multi_array<FPType, 2> softMax(const boost::multi_array<FPType, 2> &in) {\n  boost::multi_array<FPType, 2> out(boost::extents[in.size()][in[0].size()]);\n  for (unsigned i = 0; i < in[0].size(); i++) {\n    FPType sum = 0;\n    for (unsigned j = 0; j < in.size(); j++) {\n      sum += std::exp(in[j][i]);\n    }\n    for (unsigned j = 0; j < in.size(); j++) {\n      out[j][i] = std::exp(in[j][i]) / sum;\n    }\n  }\n  return out;\n}\n\n// Converted each individual element to natural log.\n// Add a small constant to prevent numeric errors\ntemplate <typename FPType>\nboost::multi_array<FPType, 2> log(const boost::multi_array<FPType, 2> &in) {\n  boost::multi_array<FPType, 2> out(boost::extents[in.size()][in[0].size()]);\n  for (unsigned i = 0; i < in.size(); i++) {\n    for (unsigned j = 0; j < in[i].size(); j++) {\n      out[i][j] = std::log(in[i][j] + 1e-50);\n    }\n  }\n  return out;\n}\n// Find exp of each individual element\ntemplate <typename FPType>\nboost::multi_array<FPType, 2> exp(const boost::multi_array<FPType, 2> &in) {\n  boost::multi_array<FPType, 2> out(boost::extents[in.size()][in[0].size()]);\n  for (unsigned i = 0; i < in.size(); i++) {\n    for (unsigned j = 0; j < in[i].size(); j++) {\n      out[i][j] = std::exp(in[i][j]);\n    }\n  }\n  return out;\n}\n\n#endif // ifndef __POPC__\n} // namespace log\n} // namespace poplibs_support\n#endif // ifndef INCLUDE_IN_ASSEMBLER\n\n#define LOG_PROBABILITY_ZERO_FLOAT 0xC77FE000\n\n#endif // poplibs_support_log_arithmetic_hpp\n", "meta": {"hexsha": "8a64eaa0df5ab99b11162f688c5a6891d99c68f2", "size": 2969, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/poplibs_support/LogArithmetic.hpp", "max_stars_repo_name": "graphcore/poplibs", "max_stars_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:28.000Z", "max_issues_repo_path": "include/poplibs_support/LogArithmetic.hpp", "max_issues_repo_name": "graphcore/poplibs", "max_issues_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/poplibs_support/LogArithmetic.hpp", "max_forks_repo_name": "graphcore/poplibs", "max_forks_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:32:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T14:58:45.000Z", "avg_line_length": 31.585106383, "max_line_length": 80, "alphanum_fraction": 0.6699225328, "num_tokens": 887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465080392795, "lm_q2_score": 0.6548947357776796, "lm_q1q2_score": 0.6125535042429593}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <chrono>\n\n#include \"mesh_reader_eigen.hpp\"\n#include \"constants_dense.hpp\"\n#include \"newton_raphson_dense.hpp\"\n\nusing Eigen::MatrixXd;\ntypedef Matrix<double, Dynamic, 1> VectorXd;\n\n// Compile command:\n// g++ -std=c++14 eigen_dense.cpp -O3 -o dense.o -I/usr/local/include/eigen3\n// Run command:\n// ./dense.o filename T(in C) eta_u(in %) eta_v(in %)\n\n// u = Cu = concentration O2, v = Cv = concentration CO2\n\n\nclass F\n{\n  /* Returns tuple containing two functors, one for the original expression and one for the Jacobian. */\n\n  private:\n    MatrixXd& Au_;\n    MatrixXd& Av_;\n    MatrixXd& B_;\n    MatrixXd& C_;\n    VectorXd& D_;\n\n  public:\n    F(MatrixXd& Au, MatrixXd& Av,MatrixXd& B,MatrixXd& C,VectorXd& D)\n    :Au_(Au), Av_(Av),B_(B), C_(C),D_(D)\n    {\n    }\n\n    VectorXd operator()(VectorXd& x)\n    {\n      int n = Au_.rows();\n      VectorXd u = x.head(n);\n      VectorXd v = x.tail(n);\n      VectorXd func(2*n);\n      func << Au_*u + B_*Ru(u,v) + hu*(C_*u - D_*uamb),Av_*v - B_*Rv(u,v) + hv*(C_*v - D_*vamb);\n      return func;\n    }\n};\n\n\nclass J\n{\n  /* Returns tuple containing two functors, one for the original expression and one for the Jacobian. */\n\n  private:\n    MatrixXd& Au_;\n    MatrixXd& Av_;\n    MatrixXd& B_;\n    MatrixXd& C_;\n    VectorXd& D_;\n\n  public:\n    J(MatrixXd& Au, MatrixXd& Av,MatrixXd& B,MatrixXd& C,VectorXd& D)\n    :Au_(Au), Av_(Av),B_(B), C_(C),D_(D)\n    {\n    }\n\n    MatrixXd operator()(VectorXd& x)\n    {\n      int n = Au_.rows();\n      VectorXd u = x.head(n);\n      VectorXd v = x.tail(n);\n      MatrixXd func(2*n,2*n);\n      func << Au_ + B_*dRudu(u,v) + hu*C_,B_*dRudv(u,v),-B_*dRvdu(u,v),Av_ - (B_*dRvdv(u,v)) + hv*C_;\n      return func;\n    }\n};\n\n\nint main(int argc, char *argv[])\n{\n  std::cout << std::endl;\n  std::cout << \"Setting constants ...\" << std::endl;\n  setConstants(atof(argv[2])+273.15,atof(argv[3])/100,atof(argv[4])/100);\n\n  auto t1 = std::chrono::high_resolution_clock::now();\n  std::string file_name = argv[1];\n  std::string location = \"../triangle/\"+ file_name +\".1\";\n  MatrixXd vertices = mesh::read_vertices(location+\".node\");\n  MatrixXd triangles = mesh::read_triangles(vertices,location+\".ele\");\n  MatrixXi boundaries = mesh::read_boundaries(vertices,location+\".poly\");\n  auto t2 = std::chrono::high_resolution_clock::now();\n\n  std::cout << std::endl;\n  std::cout << \"Input data successfully read:\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n  std::cout << \"Number of vertices :\" << vertices.rows() << std::endl;\n  std::cout << \"Number of triangles:\" << triangles.rows() <<std::endl;\n  t1 = std::chrono::high_resolution_clock::now();\n\n  /* Calculate coefficient matrix B related to the respiration kinetics,\n  part of right hand side in system of nonlinear equations */\n\n  MatrixXd B = MatrixXd::Zero(vertices.rows(), vertices.rows());\n  for (unsigned t = 0; t < triangles.rows(); ++t)\n  {\n    int a = triangles(t, 0);\n    int b = triangles(t, 1);\n    int c = triangles(t, 2);\n    double area = triangles(t, 3);\n    B(a, a) += area*(6.*vertices(a, 0) + 2.*vertices(b, 0) + 2.*vertices(c, 0));\n    B(b, a) += area*(2.*vertices(a, 0) + 2.*vertices(b, 0) + vertices(c, 0));\n    B(a,b) += area*(2.*vertices(a, 0) + 2.*vertices(b, 0) + vertices(c, 0));\n    B(c, a) += area*(2.*vertices(a, 0) + vertices(b, 0) + 2.*vertices(c, 0));\n    B(a,c) += area*(2.*vertices(a, 0) + vertices(b, 0) + 2.*vertices(c, 0));\n    B(b, b) += area*(2.*vertices(a, 0) + 6.*vertices(b, 0) + 2.*vertices(c, 0));\n    B(b, c) += area*(vertices(a, 0) + 2.*vertices(b, 0) + 2.*vertices(c, 0));\n    B(c,b) += area*(vertices(a, 0) + 2.*vertices(b, 0) + 2.*vertices(c, 0));\n    B(c, c) += area*(2.*vertices(a, 0) + 2.*vertices(b, 0) + 6.*vertices(c, 0));\n  }\n  B *= (1./60.);\n\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << std::endl;\n  std::cout << \"B matrix successfully assembled\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Calculate the first part of the stiffness matrix in the lefthand\n  side of the the nonlinear system, A */\n\n  t1 = std::chrono::high_resolution_clock::now();\n  MatrixXd A_U = MatrixXd::Zero(vertices.rows(), vertices.rows());\n  MatrixXd A_V = MatrixXd::Zero(vertices.rows(), vertices.rows());\n  Eigen::Matrix<double,3,2> G;\n  Eigen::Matrix<double,3,3> GGT_U;\n  Eigen::Matrix<double,3,3> GGT_V;\n  Eigen::Matrix<double,2,2> I_U;\n  Eigen::Matrix<double,2,2> I_V;\n  I_U(0,0) = DU_R;\n  I_U(1,0) = 0;\n  I_U(0,1) = 0;\n  I_U(1,1) = DU_Z;\n  I_V(0,0) = DV_R;\n  I_V(1,1) = DV_Z;\n  I_V(1,0) = 0;\n  I_V(0,1) = 0;\n  for (unsigned t = 0; t < triangles.rows(); ++t)\n  {\n    int a = triangles(t, 0);\n    int b = triangles(t, 1);\n    int c = triangles(t, 2);\n    double area = triangles(t, 3);\n    G(0, 0) = (vertices(b, 1) - vertices(c, 1));\n    G(1, 0) = (vertices(c, 1) - vertices(a, 1));\n    G(2, 0) = (vertices(a, 1) - vertices(b, 1));\n    G(0, 1) = (vertices(c, 0) - vertices(b, 0));\n    G(1, 1) = (vertices(a, 0) - vertices(c, 0));\n    G(2, 1) = (vertices(b, 0) - vertices(a, 0));\n    GGT_U = (1/(2*area))*((vertices(a, 0)+vertices(b, 0)+vertices(c, 0))/6)*(G*I_U*G.transpose());\n    GGT_V = (1/(2*area))*((vertices(a, 0)+vertices(b, 0)+vertices(c, 0))/6)*(G*I_V*G.transpose());\n    #ifdef DEBUG\n    std::cout<<\"GGT_U\" << std::endl << GGT_U << std::endl;\n    std::cout<<\"GGT_V\" << std::endl << GGT_V << std::endl;\n    #endif\n    A_U(a, a) += GGT_U(0, 0);\n    A_U(b, a) += GGT_U(1, 0);\n    A_U(a, b) += GGT_U(1, 0);\n    A_U(c, a) += GGT_U(2, 0);\n    A_U(a, c) += GGT_U(2, 0);\n    A_U(b, b) += GGT_U(1, 1);\n    A_U(b, c) += GGT_U(1, 2);\n    A_U(c, b) += GGT_U(1, 2);\n    A_U(c, c) += GGT_U(2, 2);\n    A_V(a, a) += GGT_V(0, 0);\n    A_V(b, a) += GGT_V(1, 0);\n    A_V(a, b) += GGT_V(1, 0);\n    A_V(c, a) += GGT_V(2, 0);\n    A_V(a, c) += GGT_V(2, 0);\n    A_V(b, b) += GGT_V(1, 1);\n    A_V(b, c) += GGT_V(1, 2);\n    A_V(c, b) += GGT_V(1, 2);\n    A_V(c, c) += GGT_V(2, 2);\n  }\n\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << std::endl;\n  std::cout << \"A matrices assembled.\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Calculate the second part of the stiffness matrix (C) and the\n  second part of the righthand side (D) */\n\n  MatrixXd C = MatrixXd::Zero(vertices.rows(), vertices.rows());\n  VectorXd D = VectorXd::Zero(vertices.rows());\n  for (unsigned b = 0; b < boundaries.rows(); ++b)\n  {\n    double len = sqrt(pow(vertices(boundaries(b, 0), 0) - vertices(boundaries(b, 1), 0), 2) +\n      pow(vertices(boundaries(b, 0), 1) - vertices(boundaries(b, 1), 1), 2));\n    C(boundaries(b, 0), boundaries(b, 0)) += len*(vertices(boundaries(b, 0), 0)/4 + vertices(boundaries(b, 1), 0)/12);\n    C(boundaries(b, 0), boundaries(b, 1)) += len*(vertices(boundaries(b, 0), 0)/12 + vertices(boundaries(b, 1), 0)/12);\n    C(boundaries(b, 1), boundaries(b, 0)) += len*(vertices(boundaries(b, 0), 0)/12 + vertices(boundaries(b, 1), 0)/12);\n    C(boundaries(b, 1), boundaries(b, 1)) += len*(vertices(boundaries(b, 0), 0)/12 + vertices(boundaries(b, 1), 0)/4);\n    D(boundaries(b,0)) += len*(vertices(boundaries(b,0),0)/3.+vertices(boundaries(b,1),0)/6.);\n    D(boundaries(b,1)) += len*(vertices(boundaries(b,0),0)/6.+vertices(boundaries(b,1),0)/3.);\n  }\n\n  t2 = std::chrono::high_resolution_clock::now();\n\n  std::cout << std::endl;\n  std::cout << \"C matrix and D vector assembled.\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Solve linearized problem with ambient concentrations as input_field\n  to obtain starting concentration values, then solve the nonlinear\n  system with Newton-Raphson */\n\n  t1 = std::chrono::high_resolution_clock::now();\n\n  t1 = std::chrono::high_resolution_clock::now();\n  F F_funct(A_U, A_V, B, C, D);\n  J J_funct(A_U, A_V, B, C, D);\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << std::endl;\n  std::cout << \"Functors are created\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n  t1 = std::chrono::high_resolution_clock::now();\n\n  VectorXd guess(vertices.rows()*2);\n  VectorXd u_0 = (A_U+(Vmu/Kmu)*B+hu*C).colPivHouseholderQr().solve(hu*D*uamb);\n  VectorXd v_0 = (A_V+hv*C).colPivHouseholderQr().solve(rq*(Vmu/Kmu)*B*u_0+hv*vamb*D);\n\n  guess << u_0,v_0;\n  t2 = std::chrono::high_resolution_clock::now();\n  std::cout << std::endl;\n  std::cout<< \"Initial guess calculated\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  #ifdef DEBUG\n  std::cout << \"A_U =\" << std::endl;\n  std::cout << A_U << std::endl;\n  std::cout << \"A_V =\" << std::endl;\n  std::cout << A_V << std::endl;\n  std::cout << \"B =\" << std::endl;\n  std::cout << B << std::endl;\n  std::cout << \"C =\" << std::endl;\n  std::cout << C << std::endl;\n  std::cout << \"D =\" << std::endl;\n  std::cout << D << std::endl;\n  std::cout << \"u_0\" << std::endl;\n  std::cout << u_0 << std::endl;\n  std::cout << \"v_0\" << std::endl;\n  std::cout << v_0 <<std::endl;\n  std::cout << \"Initial function value = \" << std::endl;\n  std::cout << F_funct(guess) <<std::endl;\n  std::cout << \"Initial Jacobian = \" << std::endl;\n  std::cout << J_funct(guess);\n  #endif\n\n  std::cout << std::endl;\n  std::cout<< \"Calculating nonlinear system solution ...\" << std::endl;\n  t1 = std::chrono::high_resolution_clock::now();\n  newton_raphson(F_funct,J_funct,guess,pow(10,-17));\n  t2 = std::chrono::high_resolution_clock::now();\n\n  std::cout<< \"Numerical solution nonlinear system calculated\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n\n  /* Write out the result for python matplotlib code */\n\n  t1 = std::chrono::high_resolution_clock::now();\n  int n = vertices.rows();\n  VectorXd u = guess.head(n);\n  VectorXd v = guess.tail(n);\n  mesh::write_result(u,v);\n  t2 = std::chrono::high_resolution_clock::now();\n\n  std::cout << std::endl;\n  std::cout<< \"Results for u and v written out\" << std::endl;\n  std::cout << \"This took: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n            << \" milliseconds\" << std::endl;\n  std::cout << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "41207ebcde780a6ae9787a4652fc1d4216bfcca8", "size": 10774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/eigen_dense.cpp", "max_stars_repo_name": "PieterAppeltans/ProjectWIT", "max_stars_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/eigen_dense.cpp", "max_issues_repo_name": "PieterAppeltans/ProjectWIT", "max_issues_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/eigen_dense.cpp", "max_forks_repo_name": "PieterAppeltans/ProjectWIT", "max_forks_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1543624161, "max_line_length": 119, "alphanum_fraction": 0.5874327084, "num_tokens": 3680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.6125535026640155}}
{"text": "/*\n * Copyright Nick Thompson, 2017\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n#define BOOST_TEST_MODULE naive_monte_carlo_test\n#define BOOST_NAIVE_MONTE_CARLO_DEBUG_FAILURES\n#include <cmath>\n#include <ostream>\n#include <boost/lexical_cast.hpp>\n#include <boost/type_index.hpp>\n#include <boost/test/included/unit_test.hpp>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/quadrature/naive_monte_carlo.hpp>\n\nusing std::abs;\nusing std::vector;\nusing std::pair;\nusing boost::math::constants::pi;\nusing boost::math::quadrature::naive_monte_carlo;\n\n\ntemplate<class Real>\nvoid test_pi_multithreaded()\n{\n    std::cout << \"Testing pi is calculated correctly (multithreaded) using Monte-Carlo on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [](std::vector<Real> const & x)->Real {\n        Real r = x[0]*x[0]+x[1]*x[1];\n        if (r <= 1) {\n          return 4;\n        }\n        return 0;\n    };\n\n    std::vector<std::pair<Real, Real>> bounds{{Real(0), Real(1)}, {Real(0), Real(1)}};\n    Real error_goal = 0.0002;\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, error_goal,\n                                          /*singular =*/ false,/* threads = */ 2, /* seed = */ 18012);\n    auto task = mc.integrate();\n    Real pi_estimated = task.get();\n    if (abs(pi_estimated - pi<Real>())/pi<Real>() > 0.005) {\n        std::cout << \"Error in estimation of pi too high, function calls: \" << mc.calls() << \"\\n\";\n        std::cout << \"Final error estimate : \" << mc.current_error_estimate() << \"\\n\";\n        std::cout << \"Error goal           : \" << error_goal << \"\\n\";\n        BOOST_CHECK_CLOSE_FRACTION(pi_estimated, pi<Real>(), 0.005);\n    }\n}\n\ntemplate<class Real>\nvoid test_pi()\n{\n    std::cout << \"Testing pi is calculated correctly using Monte-Carlo on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [](std::vector<Real> const & x)->Real\n    {\n        Real r = x[0]*x[0]+x[1]*x[1];\n        if (r <= 1)\n        {\n            return 4;\n        }\n        return 0;\n    };\n\n    std::vector<std::pair<Real, Real>> bounds{{Real(0), Real(1)}, {Real(0), Real(1)}};\n    Real error_goal = (Real) 0.0002;\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, error_goal,\n                                            /*singular =*/ false,/* threads = */ 1, /* seed = */ 128402);\n    auto task = mc.integrate();\n    Real pi_estimated = task.get();\n    if (abs(pi_estimated - pi<Real>())/pi<Real>() > 0.005)\n    {\n        std::cout << \"Error in estimation of pi too high, function calls: \" << mc.calls() << \"\\n\";\n        std::cout << \"Final error estimate : \" << mc.current_error_estimate() << \"\\n\";\n        std::cout << \"Error goal           : \" << error_goal << \"\\n\";\n        BOOST_CHECK_CLOSE_FRACTION(pi_estimated, pi<Real>(), 0.005);\n    }\n\n}\n\ntemplate<class Real>\nvoid test_constant()\n{\n    std::cout << \"Testing constants are integrated correctly using Monte-Carlo on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [](std::vector<Real> const &)->Real\n    {\n      return 1;\n    };\n\n    std::vector<std::pair<Real, Real>> bounds{{Real(0), Real(1)}, { Real(0), Real(1)}};\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, (Real) 0.0001,\n                                            /* singular = */ false, /* threads = */ 1, /* seed = */ 87);\n\n    auto task = mc.integrate();\n    Real one = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(one, 1, 0.001);\n    BOOST_CHECK_SMALL(mc.current_error_estimate(), std::numeric_limits<Real>::epsilon());\n    BOOST_CHECK(mc.calls() > 1000);\n}\n\n\ntemplate<class Real>\nvoid test_exception_from_integrand()\n{\n    std::cout << \"Testing that a reasonable action is performed by the Monte-Carlo integrator when the integrand throws an exception on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [](std::vector<Real> const & x)->Real\n    {\n        if (x[0] > 0.5 && x[0] < 0.5001)\n        {\n            throw std::domain_error(\"You have done something wrong.\\n\");\n        }\n        return (Real) 1;\n    };\n\n    std::vector<std::pair<Real, Real>> bounds{{ Real(0), Real(1)}, { Real(0), Real(1)}};\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, (Real) 0.0001);\n\n    auto task = mc.integrate();\n    bool caught_exception = false;\n    try\n    {\n      Real result = task.get();\n      // Get rid of unused variable warning:\n      std::ostream cnull(0);\n      cnull << result;\n    }\n    catch(std::exception const &)\n    {\n        caught_exception = true;\n    }\n    BOOST_CHECK(caught_exception);\n}\n\n\ntemplate<class Real>\nvoid test_cancel_and_restart()\n{\n    std::cout << \"Testing that cancellation and restarting works on naive Monte-Carlo integration on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real exact = boost::lexical_cast<Real>(\"1.3932039296856768591842462603255\");\n    BOOST_CONSTEXPR const Real A = 1.0 / (pi<Real>() * pi<Real>() * pi<Real>());\n    auto g = [&](std::vector<Real> const & x)->Real\n    {\n        return A / (1.0 - cos(x[0])*cos(x[1])*cos(x[2]));\n    };\n    vector<pair<Real, Real>> bounds{{ Real(0), pi<Real>()}, { Real(0), pi<Real>()}, { Real(0), pi<Real>()}};\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, (Real) 0.05, true, 1, 888889);\n\n    auto task = mc.integrate();\n    mc.cancel();\n    double y = task.get();\n    // Super low tolerance; because it got canceled so fast:\n    BOOST_CHECK_CLOSE_FRACTION(y, exact, 1.0);\n\n    mc.update_target_error((Real) 0.01);\n    task = mc.integrate();\n    y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, exact, 0.1);\n}\n\ntemplate<class Real>\nvoid test_finite_singular_boundary()\n{\n    std::cout << \"Testing that finite singular boundaries work on naive Monte-Carlo integration on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    using std::pow;\n    using std::log;\n    auto g = [](std::vector<Real> const & x)->Real\n    {\n        // The first term is singular at x = 0.\n        // The second at x = 1:\n        return pow(log(1.0/x[0]), 2) + log1p(-x[0]);\n    };\n    vector<pair<Real, Real>> bounds{{Real(0), Real(1)}};\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, (Real) 0.01, true, 1, 1922);\n\n    auto task = mc.integrate();\n\n    double y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, 1.0, 0.1);\n}\n\ntemplate<class Real>\nvoid test_multithreaded_variance()\n{\n    std::cout << \"Testing that variance computed by naive Monte-Carlo integration converges to integral formula on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real exact_variance = (Real) 1/(Real) 12;\n    auto g = [&](std::vector<Real> const & x)->Real\n    {\n        return x[0];\n    };\n    vector<pair<Real, Real>> bounds{{ Real(0), Real(1)}};\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, (Real) 0.001, false, 2, 12341);\n\n    auto task = mc.integrate();\n    Real y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, 0.5, 0.01);\n    BOOST_CHECK_CLOSE_FRACTION(mc.variance(), exact_variance, 0.05);\n}\n\ntemplate<class Real>\nvoid test_variance()\n{\n    std::cout << \"Testing that variance computed by naive Monte-Carlo integration converges to integral formula on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    Real exact_variance = (Real) 1/(Real) 12;\n    auto g = [&](std::vector<Real> const & x)->Real\n    {\n        return x[0];\n    };\n    vector<pair<Real, Real>> bounds{{ Real(0), Real(1)}};\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, (Real) 0.001, false, 1, 12341);\n\n    auto task = mc.integrate();\n    Real y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, 0.5, 0.01);\n    BOOST_CHECK_CLOSE_FRACTION(mc.variance(), exact_variance, 0.05);\n}\n\ntemplate<class Real, uint64_t dimension>\nvoid test_product()\n{\n    std::cout << \"Testing that product functions are integrated correctly by naive Monte-Carlo on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [&](std::vector<Real> const & x)->Real\n    {\n        double y = 1;\n        for (uint64_t i = 0; i < x.size(); ++i)\n        {\n            y *= 2*x[i];\n        }\n        return y;\n    };\n\n    vector<pair<Real, Real>> bounds(dimension);\n    for (uint64_t i = 0; i < dimension; ++i)\n    {\n        bounds[i] = std::make_pair<Real, Real>(0, 1);\n    }\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, (Real) 0.001, false, 1, 13999);\n\n    auto task = mc.integrate();\n    Real y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, 1, 0.01);\n    using std::pow;\n    Real exact_variance = pow(4.0/3.0, dimension) - 1;\n    BOOST_CHECK_CLOSE_FRACTION(mc.variance(), exact_variance, 0.1);\n}\n\ntemplate<class Real, uint64_t dimension>\nvoid test_alternative_rng_1()\n{\n    std::cout << \"Testing that alternative RNGs work correctly using naive Monte-Carlo on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [&](std::vector<Real> const & x)->Real\n    {\n        double y = 1;\n        for (uint64_t i = 0; i < x.size(); ++i)\n        {\n            y *= 2*x[i];\n        }\n        return y;\n    };\n\n    vector<pair<Real, Real>> bounds(dimension);\n    for (uint64_t i = 0; i < dimension; ++i)\n    {\n        bounds[i] = std::make_pair<Real, Real>(0, 1);\n    }\n    std::cout << \"Testing std::mt19937\" << std::endl;\n\n    naive_monte_carlo<Real, decltype(g), std::mt19937> mc1(g, bounds, (Real) 0.001, false, 1, 1882);\n\n    auto task = mc1.integrate();\n    Real y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, 1, 0.01);\n    using std::pow;\n    Real exact_variance = pow(4.0/3.0, dimension) - 1;\n    BOOST_CHECK_CLOSE_FRACTION(mc1.variance(), exact_variance, 0.05);\n\n    std::cout << \"Testing std::knuth_b\" << std::endl;\n    naive_monte_carlo<Real, decltype(g), std::knuth_b> mc2(g, bounds, (Real) 0.001, false, 1, 1883);\n    task = mc2.integrate();\n    y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, 1, 0.01);\n\n    std::cout << \"Testing std::ranlux48\" << std::endl;\n    naive_monte_carlo<Real, decltype(g), std::ranlux48> mc3(g, bounds, (Real) 0.001, false, 1, 1884);\n    task = mc3.integrate();\n    y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, 1, 0.01);\n}\n\ntemplate<class Real, uint64_t dimension>\nvoid test_alternative_rng_2()\n{\n    std::cout << \"Testing that alternative RNGs work correctly using naive Monte-Carlo on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [&](std::vector<Real> const & x)->Real\n    {\n        double y = 1;\n        for (uint64_t i = 0; i < x.size(); ++i)\n        {\n            y *= 2*x[i];\n        }\n        return y;\n    };\n\n    vector<pair<Real, Real>> bounds(dimension);\n    for (uint64_t i = 0; i < dimension; ++i)\n    {\n        bounds[i] = std::make_pair<Real, Real>(0, 1);\n    }\n\n    std::cout << \"Testing std::default_random_engine\" << std::endl;\n    naive_monte_carlo<Real, decltype(g), std::default_random_engine> mc4(g, bounds, (Real) 0.001, false, 1, 1884);\n    auto task = mc4.integrate();\n    Real y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, 1, 0.01);\n\n    std::cout << \"Testing std::minstd_rand\" << std::endl;\n    naive_monte_carlo<Real, decltype(g), std::minstd_rand> mc5(g, bounds, (Real) 0.001, false, 1, 1887);\n    task = mc5.integrate();\n    y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, 1, 0.01);\n\n    std::cout << \"Testing std::minstd_rand0\" << std::endl;\n    naive_monte_carlo<Real, decltype(g), std::minstd_rand0> mc6(g, bounds, (Real) 0.001, false, 1, 1889);\n    task = mc6.integrate();\n    y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, 1, 0.01);\n\n}\n\ntemplate<class Real>\nvoid test_upper_bound_infinite()\n{\n    std::cout << \"Testing that infinite upper bounds are integrated correctly by naive Monte-Carlo on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [](std::vector<Real> const & x)->Real\n    {\n        return 1.0/(x[0]*x[0] + 1.0);\n    };\n\n    vector<pair<Real, Real>> bounds(1);\n    for (uint64_t i = 0; i < bounds.size(); ++i)\n    {\n        bounds[i] = std::make_pair<Real, Real>(0, std::numeric_limits<Real>::infinity());\n    }\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, (Real) 0.001, true, 1, 8765);\n    auto task = mc.integrate();\n    Real y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, boost::math::constants::half_pi<Real>(), 0.01);\n}\n\ntemplate<class Real>\nvoid test_lower_bound_infinite()\n{\n    std::cout << \"Testing that infinite lower bounds are integrated correctly by naive Monte-Carlo on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [](std::vector<Real> const & x)->Real\n    {\n        return 1.0/(x[0]*x[0] + 1.0);\n    };\n\n    vector<pair<Real, Real>> bounds(1);\n    for (uint64_t i = 0; i < bounds.size(); ++i)\n    {\n        bounds[i] = std::make_pair<Real, Real>(-std::numeric_limits<Real>::infinity(), 0);\n    }\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, (Real) 0.001, true, 1, 1208);\n\n    auto task = mc.integrate();\n    Real y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, boost::math::constants::half_pi<Real>(), 0.01);\n}\n\ntemplate<class Real>\nvoid test_lower_bound_infinite2()\n{\n    std::cout << \"Testing that infinite lower bounds (2) are integrated correctly by naive Monte-Carlo on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [](std::vector<Real> const & x)->Real\n    {\n        // If x[0] = inf, this should blow up:\n        return (x[0]*x[0])/(x[0]*x[0]*x[0]*x[0] + 1.0);\n    };\n\n    vector<pair<Real, Real>> bounds(1);\n    for (uint64_t i = 0; i < bounds.size(); ++i)\n    {\n        bounds[i] = std::make_pair<Real, Real>(-std::numeric_limits<Real>::infinity(), 0);\n    }\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, (Real) 0.001, true, 1, 1208);\n    auto task = mc.integrate();\n    Real y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, boost::math::constants::half_pi<Real>()/boost::math::constants::root_two<Real>(), 0.01);\n}\n\ntemplate<class Real>\nvoid test_double_infinite()\n{\n    std::cout << \"Testing that double infinite bounds are integrated correctly by naive Monte-Carlo on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [](std::vector<Real> const & x)->Real\n    {\n        return 1.0/(x[0]*x[0] + 1.0);\n    };\n\n    vector<pair<Real, Real>> bounds(1);\n    for (uint64_t i = 0; i < bounds.size(); ++i)\n    {\n        bounds[i] = std::make_pair<Real, Real>(-std::numeric_limits<Real>::infinity(), std::numeric_limits<Real>::infinity());\n    }\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, (Real) 0.001, true, 1, 1776);\n\n    auto task = mc.integrate();\n    Real y = task.get();\n    BOOST_CHECK_CLOSE_FRACTION(y, boost::math::constants::pi<Real>(), 0.01);\n}\n\ntemplate<class Real, uint64_t dimension>\nvoid test_radovic()\n{\n    // See: Generalized Halton Sequences in 2008: A Comparative Study, function g1:\n    std::cout << \"Testing that the Radovic function is integrated correctly by naive Monte-Carlo on type \" << boost::typeindex::type_id<Real>().pretty_name() << \"\\n\";\n    auto g = [](std::vector<Real> const & x)->Real\n    {\n        using std::abs;\n        Real alpha = (Real)0.01;\n        Real z = 1;\n        for (uint64_t i = 0; i < dimension; ++i)\n        {\n            z *= (abs(4*x[i]-2) + alpha)/(1+alpha);\n        }\n        return z;\n    };\n\n    vector<pair<Real, Real>> bounds(dimension);\n    for (uint64_t i = 0; i < bounds.size(); ++i)\n    {\n        bounds[i] = std::make_pair<Real, Real>(0, 1);\n    }\n    Real error_goal = (Real) 0.001;\n    naive_monte_carlo<Real, decltype(g)> mc(g, bounds, error_goal, false, 1, 1982);\n\n    auto task = mc.integrate();\n    Real y = task.get();\n    if (abs(y - 1) > 0.01)\n    {\n        std::cout << \"Error in estimation of Radovic integral too high, function calls: \" << mc.calls() << \"\\n\";\n        std::cout << \"Final error estimate: \" << mc.current_error_estimate() << std::endl;\n        std::cout << \"Error goal          : \" << error_goal << std::endl;\n        std::cout << \"Variance estimate   : \" << mc.variance() << std::endl;\n        BOOST_CHECK_CLOSE_FRACTION(y, 1, 0.01);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(naive_monte_carlo_test)\n{\n   std::cout << \"Default hardware concurrency = \" << std::thread::hardware_concurrency() << std::endl;\n#if !defined(TEST) || TEST == 1\n    test_finite_singular_boundary<double>();\n    test_finite_singular_boundary<float>();\n#endif\n#if !defined(TEST) || TEST == 2\n    test_pi<float>();\n    test_pi<double>();\n#endif\n#if !defined(TEST) || TEST == 3\n    test_pi_multithreaded<float>();\n    test_constant<float>();\n#endif\n    //test_pi<long double>();\n#if !defined(TEST) || TEST == 4\n    test_constant<double>();\n    //test_constant<long double>();\n    test_cancel_and_restart<float>();\n#endif\n#if !defined(TEST) || TEST == 5\n    test_exception_from_integrand<float>();\n    test_variance<float>();\n#endif\n#if !defined(TEST) || TEST == 6\n    test_variance<double>();\n    test_multithreaded_variance<double>();\n#endif\n#if !defined(TEST) || TEST == 7\n    test_product<float, 1>();\n    test_product<float, 2>();\n#endif\n#if !defined(TEST) || TEST == 8\n    test_product<float, 3>();\n    test_product<float, 4>();\n    test_product<float, 5>();\n#endif\n#if !defined(TEST) || TEST == 9\n    test_product<float, 6>();\n    test_product<double, 1>();\n#endif\n#if !defined(TEST) || TEST == 10\n    test_product<double, 2>();\n#endif\n#if !defined(TEST) || TEST == 11\n    test_product<double, 3>();\n    test_product<double, 4>();\n#endif\n#if !defined(TEST) || TEST == 12\n    test_upper_bound_infinite<float>();\n    test_upper_bound_infinite<double>();\n#endif\n#if !defined(TEST) || TEST == 13\n    test_lower_bound_infinite<float>();\n    test_lower_bound_infinite<double>();\n#endif\n#if !defined(TEST) || TEST == 14\n    test_lower_bound_infinite2<float>();\n#endif\n#if !defined(TEST) || TEST == 15\n    test_double_infinite<float>();\n    test_double_infinite<double>();\n#endif\n#if !defined(TEST) || TEST == 16\n    test_radovic<float, 1>();\n    test_radovic<float, 2>();\n#endif\n#if !defined(TEST) || TEST == 17\n    test_radovic<float, 3>();\n    test_radovic<double, 1>();\n#endif\n#if !defined(TEST) || TEST == 18\n    test_radovic<double, 2>();\n    test_radovic<double, 3>();\n#endif\n#if !defined(TEST) || TEST == 19\n    test_radovic<double, 4>();\n    test_radovic<double, 5>();\n#endif\n#if !defined(TEST) || TEST == 20\n    test_alternative_rng_1<float, 3>();\n#endif\n#if !defined(TEST) || TEST == 21\n    test_alternative_rng_1<double, 3>();\n#endif\n#if !defined(TEST) || TEST == 22\n    test_alternative_rng_2<float, 3>();\n#endif\n#if !defined(TEST) || TEST == 23\n    test_alternative_rng_2<double, 3>();\n#endif\n\n}\n", "meta": {"hexsha": "7096afb514e3dbc662babe01d1e6d5cd21838928", "size": 18723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/test/naive_monte_carlo_test.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/test/naive_monte_carlo_test.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/test/naive_monte_carlo_test.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 34.3541284404, "max_line_length": 202, "alphanum_fraction": 0.6091438338, "num_tokens": 5453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6125351176010793}}
{"text": "/**\n * @file advectionfv2d_main.cc\n * @brief NPDE homework AdvectionFV2D code\n * @author Philipp Egg\n * @date 21.06.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <array>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <functional>\n#include <iostream>\n#include <memory>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/geometry/geometry.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/refinement/refinement.h>\n\n#include \"advectionfv2d.h\"\n\nint main() {\n#if SOLUTION\n  // Define velocity field beta\n  // Note that the problem description requires ||B|| <= 1\n  auto beta = [](Eigen::Vector2d x) -> Eigen::Vector2d {\n    return Eigen::Vector2d(-x[1], x[0]) / std::sqrt(2.0);\n  };\n\n  // Functor for initial bump\n  Eigen::Vector2d x0(0.8, 0.2);\n  double d = 0.2;\n  auto u0 = [x0, d](Eigen::Vector2d x) -> double {\n    double dist = (x - x0).norm();\n    if (dist < d) {\n      return std::pow(std::cos(M_PI / (2.0 * d) * dist), 2);\n    } else {\n      return 0.0;\n    }\n  };\n\n  // Task 8-8.o\n  // Generate a mesh hierarchy\n  double T = 1.0;\n\n  // TODO inconsistancy: g vs. G\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(0, 1. / 3.);\n\n  auto mesh_seq_p{\n      lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(mesh_p, 5)};\n\n  std::vector<int> vector_num_cells;\n  std::vector<double> vector_l2error;\n\n  // Iterate over mesh levels starting from thrid refinement\n  int num_meshes = mesh_seq_p->NumLevels();\n  for (int level = 3; level < num_meshes; level++) {\n    std::cout << \"Computing L2Error for level: \" << level << std::endl;\n\n    // Get the current mesh\n    auto cur_mesh = mesh_seq_p->getMesh(level);\n\n    // Create a DOF Hander for the current mesh\n    const lf::assemble::UniformFEDofHandler cur_dofh(\n        cur_mesh, {{lf::base::RefEl::kPoint(), 0},\n                   {lf::base::RefEl::kSegment(), 0},\n                   {lf::base::RefEl::kTria(), 1},\n                   {lf::base::RefEl::kQuad(), 1}});\n\n    // Compute cell normals\n    std::shared_ptr<lf::mesh::utils::CodimMeshDataSet<\n        Eigen::Matrix<double, 2, Eigen::Dynamic>>>\n        normal_vectors = AdvectionFV2D::computeCellNormals(cur_dofh.Mesh());\n\n    // Compute adjecent cells\n    std::shared_ptr<lf::mesh::utils::CodimMeshDataSet<\n        std::array<const lf::mesh::Entity *, 4>>>\n        adjacentCells = AdvectionFV2D::getAdjacentCellPointers(cur_dofh.Mesh());\n\n    // Get result from simulation\n    Eigen::VectorXd result = AdvectionFV2D::simulateAdvection(\n        cur_dofh, beta, u0, adjacentCells, normal_vectors, T);\n\n    // Get exact result at barycenters of cells\n    Eigen::VectorXd ref_solution = AdvectionFV2D::refSolution(cur_dofh, u0, T);\n\n    // Compute L2 error in barycenter\n    double l2_error = 0;\n    for (const lf::mesh::Entity *cell : cur_mesh->Entities(0)) {\n      const lf::geometry::Geometry *geo_p = cell->Geometry();\n      double area = lf::geometry::Volume(*geo_p);\n      int idx = cur_dofh.GlobalDofIndices(*cell)[0];\n      l2_error += std::pow((result[idx] - ref_solution[idx]), 2) * area;\n    }\n    l2_error = std::sqrt(l2_error);\n    vector_num_cells.push_back(cur_dofh.NumDofs());\n    vector_l2error.push_back(l2_error);\n    std::cout << \"L2Error at level \" << level << \": \" << l2_error << std::endl;\n\n    // Writing vtk files (optional part)\n    std::string sol = \"sol\";\n    std::string ref = \"ref\";\n    std::string f_end = \".vtk\";\n    std::ostringstream sol_st;\n    std::ostringstream ref_st;\n    std::ostringstream sol_st_file;\n    std::ostringstream ref_st_file;\n    sol_st << sol << level;\n    ref_st << ref << level;\n    sol_st_file << sol << level << f_end;\n    ref_st_file << ref << level << f_end;\n\n    lf::io::VtkWriter vtk_writer1(cur_dofh.Mesh(), sol_st_file.str());\n    auto cell_data_ref =\n        lf::mesh::utils::make_CodimMeshDataSet<double>(cur_dofh.Mesh(), 0);\n    for (const lf::mesh::Entity *cell : cur_dofh.Mesh()->Entities(0)) {\n      int row = cur_dofh.GlobalDofIndices(*cell)[0];\n      cell_data_ref->operator()(*cell) = result[row];\n    }\n    vtk_writer1.WriteCellData(sol_st.str(), *cell_data_ref);\n\n    lf::io::VtkWriter vtk_writer2(cur_dofh.Mesh(), ref_st_file.str());\n    auto cell_data_sol =\n        lf::mesh::utils::make_CodimMeshDataSet<double>(cur_dofh.Mesh(), 0);\n    for (const lf::mesh::Entity *cell : cur_dofh.Mesh()->Entities(0)) {\n      int row = cur_dofh.GlobalDofIndices(*cell)[0];\n      cell_data_sol->operator()(*cell) = ref_solution[row];\n    }\n    vtk_writer2.WriteCellData(ref_st.str(), *cell_data_sol);\n  }\n\n  // Task 8-8.q\n  // Compute threshold for fourth refinement level\n  int level = 4;\n  auto cur_mesh = mesh_seq_p->getMesh(level);\n\n  // Create a DOF Hander for the current mesh\n  const lf::assemble::UniformFEDofHandler cur_dofh(\n      cur_mesh, {{lf::base::RefEl::kPoint(), 0},\n                 {lf::base::RefEl::kSegment(), 0},\n                 {lf::base::RefEl::kTria(), 1},\n                 {lf::base::RefEl::kQuad(), 1}});\n\n  int threshold = AdvectionFV2D::findCFLthreshold(cur_dofh, beta, T);\n  int cfl_thres = int((T / AdvectionFV2D::computeHmin(cur_mesh) + 1));\n  std::cout << \"Threshold for level: \" << level << \" is: \" << threshold\n            << \" | Threshold from CFL is: \" << cfl_thres << std::endl;\n\n  // Write Output file of Task 8-8.o and 8-8.q\n  std::ofstream csv_file;\n  csv_file.open(\"advectionfv2d.csv\");\n  for (int i = 0; i < vector_num_cells.size(); i++) {\n    std::cout << \"Cells: \" << vector_num_cells.at(i)\n              << \" | L2Error: \" << vector_l2error.at(i) << std::endl;\n    csv_file << vector_num_cells.at(i) << \",\" << vector_l2error.at(i) << \"\\n\";\n  }\n  csv_file.close();\n\n  // Print convergence rates\n  for (int i = 1; i < vector_num_cells.size(); i++) {\n    double conv_rate =\n        (std::log(vector_l2error[i - 1]) - std::log(vector_l2error[i])) /\n        (std::log(vector_num_cells[i]) - std::log(vector_num_cells[i - 1]));\n    std::cout << \"Conv. Rate \" << i << \"-\" << i + 1 << \"  is: \" << conv_rate\n              << std::endl;\n  }\n\n  // Plot results from 8-8.o\n  std::system(\"python3 \" CURRENT_SOURCE_DIR\n              \"/advectionfv2d.py \" CURRENT_BINARY_DIR\n              \"/advectionfv2d.csv \" CURRENT_BINARY_DIR \"/solution.eps\");\n\n  return 0;\n#else\n  //====================\n  // Your code goes here\n  //====================\n  return 0;\n#endif\n}\n", "meta": {"hexsha": "368acfe3bdf02567111aaaca4a0969585b2d0b1d", "size": 6608, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/AdvectionFV2D/mastersolution/advectionfv2d_main.cc", "max_stars_repo_name": "hanyao8/NPDECODES", "max_stars_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "developers/AdvectionFV2D/mastersolution/advectionfv2d_main.cc", "max_issues_repo_name": "hanyao8/NPDECODES", "max_issues_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "developers/AdvectionFV2D/mastersolution/advectionfv2d_main.cc", "max_forks_repo_name": "hanyao8/NPDECODES", "max_forks_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7142857143, "max_line_length": 80, "alphanum_fraction": 0.6274213075, "num_tokens": 1970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6125351135848563}}
{"text": "/**\n * @file Unit tests for FBstabDense\n * which is designed to solve QPs of the form:\n *\n * min  0.5 z'Hz + f'z\n * s.t. Az <= b\n *\n */\n#include <cmath>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include \"drake/solvers/fbstab/fbstab_dense.h\"\n\nnamespace drake {\nnamespace solvers {\nnamespace fbstab {\nnamespace test {\n\nusing MatrixXd = Eigen::MatrixXd;\nusing VectorXd = Eigen::VectorXd;\n\n/**\n * Tests FBstab with\n *\n * H = [3 1]  f = [10]\n *     [1 1]      [5 ]\n *\n * A = [-1 0] b = [0]\n *     [0  1]     [0]\n *\n * This QP can be solved analytically\n * and has the unique primal(z) - dual(v) solution\n * z = [0 -5],  v = [5 0]\n */\nGTEST_TEST(FBstabDense, FeasibleQP) {\n  MatrixXd H(2, 2);\n  MatrixXd A(2, 2);\n  VectorXd f(2);\n  VectorXd b(2);\n\n  H << 3, 1, 1, 1;\n  f << 10, 5;\n  A << -1, 0, 0, 1;\n  b << 0, 0;\n\n  int n = f.size();\n  int q = b.size();\n\n  FBstabDense::QPData data;\n  data.H = &H;\n  data.f = &f;\n  data.A = &A;\n  data.b = &b;\n\n  VectorXd z0 = Eigen::VectorXd::Zero(n);\n  VectorXd v0 = Eigen::VectorXd::Zero(q);\n  VectorXd y0 = Eigen::VectorXd::Zero(q);\n\n  FBstabDense::QPVariable x0;\n  x0.z = &z0;\n  x0.v = &v0;\n  x0.y = &y0;\n\n  FBstabDense solver(n, q);\n  solver.UpdateOption(\"abs_tol\", 1e-8);\n  solver.SetDisplayLevel(FBstabAlgoDense::Display::OFF);\n  SolverOut out = solver.Solve(data, &x0);\n\n  ASSERT_EQ(out.eflag, ExitFlag::SUCCESS);\n\n  VectorXd zopt(2);\n  VectorXd vopt(2);\n  zopt << 0, -5;\n  vopt << 5, 0;\n  for (int i = 0; i < n; i++) {\n    EXPECT_NEAR(z0(i), zopt(i), 1e-8);\n  }\n\n  for (int i = 0; i < q; i++) {\n    EXPECT_NEAR(v0(i), vopt(i), 1e-8);\n  }\n}\n\n/**\n * Tests FBstab with\n *\n * H = [1 0]  f = [1]\n *     [0 0]      [0]\n *\n * A = [0  0] b = [0 ]\n *     [1  0]     [3 ]\n *     [0  1]     [3 ]\n *     [-1 0]     [-1]\n *     [0 -1]     [-1]\n *\n * This QP is degenerate with a primal solution set\n * [1] x [1,3]\n */\nGTEST_TEST(FBstabDense, DegenerateQP) {\n  MatrixXd H(2, 2);\n  MatrixXd A(5, 2);\n  VectorXd f(2);\n  VectorXd b(5);\n\n  H << 1, 0, 0, 0;\n  f << 1, 0;\n\n  A << 0, 0, 1, 0, 0, 1, -1, 0, 0, -1;\n\n  b << 0, 3, 3, -1, -1;\n\n  int n = f.size();\n  int q = b.size();\n\n  FBstabDense::QPData data;\n  data.H = &H;\n  data.f = &f;\n  data.A = &A;\n  data.b = &b;\n\n  VectorXd z0 = Eigen::VectorXd::Zero(n);\n  VectorXd v0 = Eigen::VectorXd::Zero(q);\n  VectorXd y0 = Eigen::VectorXd::Zero(q);\n\n  FBstabDense::QPVariable x0;\n  x0.z = &z0;\n  x0.v = &v0;\n  x0.y = &y0;\n\n  FBstabDense solver(n, q);\n  solver.UpdateOption(\"abs_tol\", 1e-8);\n  solver.SetDisplayLevel(FBstabAlgoDense::Display::OFF);\n  SolverOut out = solver.Solve(data, &x0);\n\n  ASSERT_EQ(out.eflag, ExitFlag::SUCCESS);\n  EXPECT_NEAR(z0(0), 1, 1e-8);\n  EXPECT_TRUE((z0(1) >= 1) && (z0(1) <= 3));\n\n  // Check satisfaction of KKT conditions.\n  VectorXd r1 = H * z0 + f + A.transpose() * v0;\n  VectorXd r2 = y0.cwiseMin(v0);\n\n  ASSERT_NEAR(r1.norm() + r2.norm(), 0, 1e-6);\n}\n\n/**\n * Tests FBstab with\n *\n * H = [1 0]  f = [1 ]\n *     [0 0]      [-1]\n *\n * A = [1  1] b = [0 ]\n *     [1  0]     [3 ]\n *     [0  1]     [3 ]\n *     [-1 0]     [-1]\n *     [0 -1]     [-1]\n *\n * This QP is infeasible, i.e.,\n * there is no z satisfying Az <= b\n */\nGTEST_TEST(FBstabDense, InfeasibleQP) {\n  MatrixXd H(2, 2);\n  MatrixXd A(5, 2);\n  VectorXd f(2);\n  VectorXd b(5);\n\n  H << 1, 0, 0, 0;\n  f << 1, -1;\n\n  A << 1, 1, 1, 0, 0, 1, -1, 0, 0, -1;\n\n  b << 0, 3, 3, -1, -1;\n\n  int n = f.size();\n  int q = b.size();\n\n  FBstabDense::QPData data;\n  data.H = &H;\n  data.f = &f;\n  data.A = &A;\n  data.b = &b;\n\n  VectorXd z0 = Eigen::VectorXd::Zero(n);\n  VectorXd v0 = Eigen::VectorXd::Zero(q);\n  VectorXd y0 = Eigen::VectorXd::Zero(q);\n\n  FBstabDense::QPVariable x0;\n  x0.z = &z0;\n  x0.v = &v0;\n  x0.y = &y0;\n\n  FBstabDense solver(n, q);\n  solver.UpdateOption(\"abs_tol\", 1e-8);\n  solver.SetDisplayLevel(FBstabAlgoDense::Display::OFF);\n  SolverOut out = solver.Solve(data, &x0);\n\n  ASSERT_EQ(out.eflag, ExitFlag::PRIMAL_INFEASIBLE);\n}\n\n/**\n * Tests FBstab with\n *\n * H = [1 0]  f = [1 ]\n *     [0 0]      [-1]\n *\n * A = [0  0] b = [0 ]\n *     [1  0]     [3 ]\n *     [-1 0]     [-1]\n *     [0 -1]     [-1]\n *\n * This QP is unbounded below, i.e.,\n * its optimal value is -infinity\n */\nGTEST_TEST(FBstabDense, UnboundedQP) {\n  MatrixXd H(2, 2);\n  MatrixXd A(4, 2);\n  VectorXd f(2);\n  VectorXd b(4);\n\n  H << 1, 0, 0, 0;\n  f << 1, -1;\n\n  A << 0, 0, 1, 0, -1, 0, 0, -1;\n\n  b << 0, 3, -1, -1;\n\n  int n = f.size();\n  int q = b.size();\n\n  FBstabDense::QPData data;\n  data.H = &H;\n  data.f = &f;\n  data.A = &A;\n  data.b = &b;\n\n  VectorXd z0 = Eigen::VectorXd::Zero(n);\n  VectorXd v0 = Eigen::VectorXd::Zero(q);\n  VectorXd y0 = Eigen::VectorXd::Zero(q);\n\n  FBstabDense::QPVariable x0;\n  x0.z = &z0;\n  x0.v = &v0;\n  x0.y = &y0;\n\n  FBstabDense solver(n, q);\n  solver.UpdateOption(\"abs_tol\", 1e-8);\n  solver.SetDisplayLevel(FBstabAlgoDense::Display::OFF);\n  SolverOut out = solver.Solve(data, &x0);\n\n  ASSERT_EQ(out.eflag, ExitFlag::DUAL_INFEASIBLE);\n}\n\n}  // namespace test\n}  // namespace fbstab\n}  // namespace solvers\n}  // namespace drake\n", "meta": {"hexsha": "6ed0433d458af327f1fa79c64b8d61a7d8bd5b4f", "size": 4990, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/fbstab/test/fbstab_dense_unit_tests.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "solvers/fbstab/test/fbstab_dense_unit_tests.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/fbstab/test/fbstab_dense_unit_tests.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 19.2664092664, "max_line_length": 56, "alphanum_fraction": 0.5394789579, "num_tokens": 2051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6124346083634389}}
{"text": "// Petter Strandmark 2014\n// petter.strandmark@gmail.com\n//\n// [1] Chambolle, A., & Pock, T. (2011). A first-order primal-dual algorithm for convex\n//     problems with applications to imaging. Journal of Mathematical Imaging and Vision,\n//     40(1), 120-145.\n//\n// [2] Pock, T., & Chambolle, A. (2011, November). Diagonal preconditioning for first\n//     order primal-dual algorithms in convex optimization. In Computer Vision (ICCV),\n//     2011 IEEE International Conference on (pp. 1762-1769). IEEE.\n//\n\n#include <cstdio>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <string>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <first_order_solver.h>\n\ndouble get_feasibility_error(const Eigen::VectorXd& x,\n                             Eigen::VectorXd* temp_storage,\n                             const Eigen::VectorXd& lb,\n                             const Eigen::VectorXd& ub,\n                             const Eigen::SparseMatrix<double>& A,\n                             const Eigen::VectorXd& b,\n                             const std::vector<LinearConstraintType>& constraint_types)\n{\n\tusing namespace std;\n\tconst auto m = A.rows();\n\tconst auto n = A.cols();\n\tattest(lb.rows() == n);\n\tattest(ub.rows() == n);\n\tattest(x.rows() == n);\n\tattest(b.rows() == m);\n\tattest(constraint_types.size() == m);\n\n\tdouble feasibility_error = 0;\n\t*temp_storage = A*x - b;\n\n\tfor (ptrdiff_t i = 0; i < m; ++i) {\n\t\tif (constraint_types[i] == LinearConstraintType::Equality) {\n\t\t\tfeasibility_error = max(feasibility_error, abs((*temp_storage)(i)));\n\t\t}\n\t\telse if (constraint_types[i] == LinearConstraintType::LessThan) {\n\t\t\tfeasibility_error = max(feasibility_error, (*temp_storage)(i));\n\t\t}\n\t\telse if (constraint_types[i] == LinearConstraintType::GreaterThan) {\n\t\t\tfeasibility_error = max(feasibility_error, -(*temp_storage)(i));\n\t\t}\n\t}\n\n\tfor (ptrdiff_t j = 0; j < n; ++j) {\n\t\tfeasibility_error = max(feasibility_error, lb(j) - x(j));\n\t\tfeasibility_error = max(feasibility_error, x(j) - ub(j));\n\t}\n\n\tdouble denominator = max(x.maxCoeff(), -x.minCoeff());\n\tif (denominator <= 1e-10) {\n\t\tdenominator = 1;\n\t}\n\n\treturn feasibility_error / denominator;\n}\n\n// Will use x_prev as a temporary storage after\n// examining it.\nbool check_convergence_and_log(std::ptrdiff_t iteration,\n                               const Eigen::VectorXd& x,\n                               Eigen::VectorXd* x_prev,\n                               const Eigen::VectorXd& y,\n                               const Eigen::VectorXd& y_prev,\n                               const Eigen::VectorXd& c,\n                               const Eigen::VectorXd& lb,\n                               const Eigen::VectorXd& ub,\n                               const Eigen::SparseMatrix<double>& A,\n                               const Eigen::VectorXd& b,\n                               const std::vector<LinearConstraintType>& constraint_types,\n                               const FirstOrderOptions& options)\n{\n\tusing namespace Eigen;\n\tusing namespace std;\n\n\tconst auto n = x.size();\n\tconst auto m = y.size();\n\n\tbool is_converged = false;\n\n\t//cerr << \"x      = \" << (*x).transpose() << endl;\n\t//cerr << \"Ax     = \" << (A*(*x)).transpose() << endl;\n\t//cerr << \"Ax - b = \" << (A*(*x) - b).transpose() << endl;\n\n\tauto get_relative_change = [iteration](const Eigen::VectorXd& x, const Eigen::VectorXd& x_prev) -> double\n\t{\n\t\tdouble relative_change;\n\t\tif (iteration <= 0) {\n\t\t\trelative_change = std::numeric_limits<double>::quiet_NaN();\n\t\t}\n\t\telse {\n\t\t\trelative_change = (x - x_prev).norm() / (x.norm() + x_prev.norm());\n\t\t\tif (relative_change != relative_change) {\n\t\t\t\t// Both x and x_prev were null vectors.\n\t\t\t\trelative_change = 0;\n\t\t\t}\n\t\t}\n\t\treturn relative_change;\n\t};\n\n\tdouble relative_change_x = get_relative_change(x, *x_prev);\n\tdouble relative_change_y = get_relative_change(y, y_prev);\n\tdouble feasibility_error = get_feasibility_error(x, x_prev, lb, ub, A, b, constraint_types);\n\n\tif (relative_change_x < options.tolerance && relative_change_y < options.tolerance) {\n\t\tis_converged = true;\n\t}\n\n\tif (options.log_function) {\n\t\tostringstream message;\n\t\tmessage << setw(9);\n\t\tif (iteration == -1) {\n\t\t\tmessage << \"end\";\n\t\t}\n\t\telse {\n\t\t\tmessage << iteration;\n\t\t}\n\t\tmessage << \"   \"\n\t\t\t\t<< setw(15) << setprecision(6) << scientific << c.dot(x) << \" \"\n\t\t\t\t<< setw(12) << setprecision(3) << scientific << relative_change_x << \" \"\n\t\t\t\t<< setw(12) << setprecision(3) << scientific << relative_change_y << \" \"\n\t\t\t\t<< setw(15) << setprecision(6) << scientific << feasibility_error;\n\t\toptions.log_function(message.str());\n\t}\n\n\treturn is_converged;\n}\n\n\ntemplate<typename Int>\nstd::string to_string_with_separator(Int input)\n{\n\tattest(input >= 0);\n\tstd::string s;\n\tauto num = std::to_string(input);\n\tstd::reverse(begin(num), end(num));\n\tfor (std::size_t i = 0; i < num.size(); ++i) {\n\t\ts += num[i];\n\t\tif (i % 3 == 2 && i < num.size() - 1) {\n\t\t\ts += ',';\n\t\t}\n\t}\n\tstd::reverse(begin(s), end(s));\n\treturn s;\n}\n\n\n/// Solves the linear program\n///\n///   minimize c\u00b7x\n///   such that Ax = b,\n///             l \u2264 x \u2264 u.\nbool first_order_primal_dual_solve(Eigen::VectorXd* x_ptr,    /// Primal variables (in/out).\n                                   Eigen::VectorXd* y_ptr,    /// Dual variables (in/out).\n                                   const Eigen::VectorXd& c,  /// Objective function.\n                                   const Eigen::VectorXd& lb, /// Lower bound on x.\n                                   const Eigen::VectorXd& ub, /// Upper bound on x.\n                                   const Eigen::SparseMatrix<double>& A,   /// Equality constraint matrix.\n                                   const Eigen::VectorXd& b,  /// Right-hand side of constraints.\n                                   const std::vector<LinearConstraintType>& constraint_types,\n                                   const FirstOrderOptions& options)\n{\n\tusing namespace Eigen;\n\tusing namespace std;\n\n\tVectorXd& x = *x_ptr;\n\tVectorXd& y = *y_ptr;\n\n\tconst auto n = x.size();\n\tconst auto m = y.size();\n\tattest(c.size() == n);\n\tattest(A.rows() == m);\n\tattest(A.cols() == n);\n\tattest(constraint_types.size() == m);\n\n\tVectorXd x_prev(n);\n\tVectorXd y_prev(m);\n\n\t//cerr << \"m=\" << m << \", n=\" << n << endl;\n\t//cerr << \"A = \\n\" << A << endl;\n\t//cerr << \"b = \\n\" << b  << endl;\n\t//cerr << \"lb = \\n\" << lb.transpose() << endl;\n\t//cerr << \"ub = \\n\" << ub.transpose() << endl;\n\n\tconst SparseMatrix<double> AT = A.transpose();\n\n\tif (options.log_function) {\n\t\toptions.log_function(\"Problem size: \" + to_string_with_separator(A.rows())\n\t\t                              + \" x \" + to_string_with_separator(A.cols())\n\t\t                              + \" (\"  + to_string_with_separator(A.nonZeros()) + \" non-zeros)\");\n\t\toptions.log_function(\"   Iter         Objective     Rel. ch. x   Rel. ch. y   Infeasibility \");\n\t\toptions.log_function(\"----------------------------------------------------------------------\");\n\t\tx_prev.setConstant(std::numeric_limits<double>::quiet_NaN());\n\t\ty_prev.setConstant(std::numeric_limits<double>::quiet_NaN());\n\t\tcheck_convergence_and_log(0, x, &x_prev, y, y_prev, c, lb, ub, A, b, constraint_types, options);\n\t}\n\n\t// Compute preconditioners as in eq. (10) from [2], with alpha = 1.\n\tVectorXd Tvec(n);\n\tVectorXd Svec(m);\n\tTvec.setZero();\n\tSvec.setZero();\n\tfor (int k = 0; k < A.outerSize(); ++k) {\n\t\tfor (SparseMatrix<double>::InnerIterator it(A, k); it; ++it) {\n\t\t\tauto i = it.row();\n\t\t\tauto j = it.col();\n\t\t\tauto value = abs(it.value());\n\t\t\tTvec(j) += value;\n\t\t\tSvec(i) += value;\n\t\t}\n\t}\n\n\tfor (ptrdiff_t j = 0; j < n; ++j) {\n\t\tTvec(j) = 1.0 / Tvec(j);\n\t}\n\n\tfor (ptrdiff_t i = 0; i < m; ++i) {\n\t\tSvec(i) = 1.0 / Svec(i);\n\t}\n\n\tsize_t iteration;\n\tfor (iteration = 1; iteration <= options.maximum_iterations; ++iteration) {\n\t\tbool should_check_convergence = options.print_interval <= 1 || iteration % options.print_interval == 1;\n\n\t\tx_prev = x;\n\t\tif (should_check_convergence) {\n\t\t\ty_prev = y;\n\t\t}\n\n\t\t// See eq. (18) from [2].\n\n\t\tx = x - Tvec.asDiagonal() * ( AT*y + c);\n\n\t\tfor (ptrdiff_t j = 0; j < n; ++j) {\n\t\t\tx(j) = max(lb(j), min(ub(j), x(j)));\n\t\t}\n\t\t\n\t\ty = y + Svec.asDiagonal() * (A*(2 * x - x_prev) - b);\n\n\t\tfor (size_t i = 0; i < m; ++i) {\n\t\t\tif (constraint_types[i] == LinearConstraintType::LessThan) {\n\t\t\t\ty(i) = max(y(i), 0.0);\n\t\t\t}\n\t\t\telse if (constraint_types[i] == LinearConstraintType::GreaterThan) {\n\t\t\t\ty(i) = min(y(i), 0.0);\n\t\t\t}\n\t\t}\n\n\t\tif (should_check_convergence) {\n\t\t\tif (check_convergence_and_log(iteration, x, &x_prev, y, y_prev, c, lb, ub, A, b, constraint_types, options)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tcheck_convergence_and_log(-1, x, &x_prev, y, y_prev, c, lb, ub, A, b, constraint_types, options);\n\n\tdouble feasibility_error = get_feasibility_error(x, &x_prev, lb, ub, A, b, constraint_types);\n\treturn feasibility_error < 100*options.tolerance;\n}\n\n\nbool EASY_IP_API first_order_admm_solve(Eigen::VectorXd* x_ptr,\n                                        const Eigen::VectorXd& c,\n                                        const Eigen::VectorXd& lb,\n                                        const Eigen::VectorXd& ub,\n                                        const Eigen::SparseMatrix<double>& A,\n                                        const Eigen::VectorXd& b,\n                                        const FirstOrderOptions& options)\n{\n\tusing namespace Eigen;\n\tusing namespace std;\n\n\tVectorXd& x = *x_ptr;\n\n\tconst auto n = x.size();\n\tconst auto m = A.rows();\n\tattest(c.size() == n);\n\tattest(A.cols() == n);\n\n\tVectorXd z(n);\n\tz.setZero();\n\tVectorXd u(n);\n\tu.setZero();\n\n\tconst double rho = options.rho;\n\n\tstd::vector<LinearConstraintType> constraint_types(m, LinearConstraintType::Equality);\n\t\n\tvector<Triplet<double>> triplets;\n\n\tfor (auto j = decltype(n)(0); j < n; ++j) {\n\t\ttriplets.emplace_back(j, j, rho);\n\t}\n\n\tfor (int k = 0; k < A.outerSize(); ++k) {\n\t\tfor (SparseMatrix<double>::InnerIterator it(A, k); it; ++it) {\n\t\t\tauto i = it.row();\n\t\t\tauto j = it.col();\n\t\t\tauto value = it.value();\n\t\t\t\n\t\t\ttriplets.emplace_back(j    , i + n, value);\n\t\t\ttriplets.emplace_back(n + i, j    , value);\n\t\t}\n\t}\n\n\ttypedef SparseMatrix<double>::Index index;\n\tSparseMatrix<double, ColMajor> System(index(n + m), index(n + m));\n\tSystem.setFromTriplets(triplets.begin(), triplets.end());\n\tSystem.makeCompressed();\n\n\t/*cerr << \"System = \" << endl << System.toDense() << endl << endl;*/\n\n\tSparseLU<SparseMatrix<double, ColMajor>, COLAMDOrdering<SparseMatrix<double, ColMajor>::Index> >  solver;\n\tsolver.analyzePattern(System);\n\tsolver.factorize(System);\n\tauto computation_info = solver.info();\n\tif (computation_info != Success) {\n\t\tif (computation_info == NumericalIssue) {\n\t\t\tthrow runtime_error(\"Eigen::NumericalIssue\");\n\t\t}\n\t\telse if (computation_info == NoConvergence) {\n\t\t\tthrow runtime_error(\"Eigen::NoConvergence \");\n\t\t}\n\t\telse if (computation_info == InvalidInput) {\n\t\t\tthrow runtime_error(\"Eigen::InvalidInput \");\n\t\t}\n\t\telse {\n\t\t\tthrow runtime_error(\"Unknown Eigen error.\");\n\t\t}\n\t}\n\n\tVectorXd x_prev(n);\n\tVectorXd z_prev(m);\n\n\tVectorXd lhs(m + n);\n\tVectorXd xv(m + n);\n\n\tif (options.log_function) {\n\t\toptions.log_function(\"   Iter         Objective     Rel. ch. x   Rel. ch. z   ||Ax - b||_inf\");\n\t\toptions.log_function(\"----------------------------------------------------------------------\");\n\t\tx_prev.setConstant(std::numeric_limits<double>::quiet_NaN());\n\t\tz_prev.setConstant(std::numeric_limits<double>::quiet_NaN());\n\t\tcheck_convergence_and_log(0, x, &x_prev, z, z_prev, c, lb, ub, A, b, constraint_types, options);\n\t}\n\n\tsize_t iteration;\n\tfor (iteration = 1; iteration <= options.maximum_iterations; ++iteration) {\n\t\tbool should_check_convergence = options.print_interval <= 1 || iteration % options.print_interval == 1;\n\n\t\tif (should_check_convergence) {\n\t\t\tx_prev = x;\n\t\t\tz_prev = z;\n\t\t}\n\n\t\tlhs.block(0, 0, n, 1) = -c + rho*(z - u);\n\t\tlhs.block(n, 0, m, 1) = b;\n\t\txv = solver.solve(lhs);\n\t\tx = xv.block(0, 0, n, 1);\n\n\t\tz = x + u;\n\t\tfor (ptrdiff_t i = 0; i < n; ++i) {\n\t\t\tz(i) = max(lb(i), min(ub(i), z(i)));\n\t\t}\n\n\t\tu = u + x - z;\n\n\t\tif (should_check_convergence) {\n\t\t\tif (check_convergence_and_log(iteration, x, &x_prev, z, z_prev, c, lb, ub, A, b, constraint_types, options)) {\n\t\t\t\t// TODO\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tdouble feasibility_error = get_feasibility_error(x, &x_prev, lb, ub, A, b, constraint_types);\n\treturn feasibility_error < 100 * options.tolerance;\n}\n\n\nvoid FirstOrderProblem::check_invariants() const\n{\n\tauto n = get_cost().size();\n\tattest(get_var_lb().size() == n);\n\tattest(get_var_ub().size() == n);\n\n\tattest(get_rows().size() == get_values().size());\n\tattest(get_cols().size() == get_values().size());\n\n\tauto m = get_rhs_lower().size();\n\tattest(get_rhs_upper().size() == m);\n\n\tattest(get_integer_variables().empty());\n}\n\n\nvoid FirstOrderProblem::convert_into_equality_constrained_problem()\n{\n\tauto m = get_rhs_lower().size();\n\n\tsize_t constraints_added = 0;\n\tfor (size_t i = 0; i < m; ++i) {\n\t\tauto& lb = get_rhs_lower()[i];\n\t\tauto& ub = get_rhs_upper()[i];\n\t\tif (lb != ub) {\n\t\t\tauto slack = add_variable(IP::Real);\n\t\t\tset_bounds(0.0, slack, std::numeric_limits<double>::infinity());\n\t\t\tget_rows().push_back(int(i));\n\t\t\tget_cols().push_back(int(get_variable_index(slack)));\n\n\t\t\tif (ub < 1e100) {\n\t\t\t\tattest(lb <= -1e100); // Cannot convert if both lb and ub exists.\n\t\t\t\tlb = ub;\n\t\t\t\tget_values().push_back(1.0);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tattest(lb > -1e100);\n\t\t\t\tub = lb;\n\t\t\t\tget_values().push_back(-1.0);\n\t\t\t}\n\t\t\tconstraints_added++;\n\t\t}\n\t}\n\n\tcheck_invariants();\n}\n\nvoid FirstOrderProblem::get_system_matrix(Eigen::SparseMatrix<double>* A,\n                                          const FirstOrderOptions& options)\n{\n\tusing namespace Eigen;\n\tusing namespace std;\n\n\tauto n = get_cost().size();\n\tauto m = get_rhs_lower().size();\n\tcheck_invariants();\n\n\ttypedef unsigned int index;\n\tvector<Triplet<double, index>> sparse_indices;\n\tfor (size_t ind = 0; ind < get_rows().size(); ++ind) {\n\t\tsize_t i = get_rows()[ind];\n\t\tsize_t j = get_cols()[ind];\n\t\tauto value = get_values()[ind];\n\t\tattest(i < m);\n\t\tattest(j < n);\n\t\tsparse_indices.emplace_back(index(i), index(j), value);\n\t}\n\n\tA->resize(static_cast<int>(m), static_cast<int>(n));\n\tA->setFromTriplets(sparse_indices.begin(), sparse_indices.end());\n\n\tcheck_invariants();\n}\n\nbool FirstOrderProblem::solve_first_order(const FirstOrderOptions& options)\n{\n\tusing namespace Eigen;\n\tusing namespace std;\n\n\tSparseMatrix<double> A;\n\tget_system_matrix(&A, options);\n\n\tauto n = get_cost().size();\n\tauto m = get_rhs_lower().size();\n\n\tMap<const VectorXd> lb(get_var_lb().data(), n);\n\tMap<const VectorXd> ub(get_var_ub().data(), n);\n\tVectorXd            b(m);\n\tMap<const VectorXd> c(get_cost().data(), n);\n\tVectorXd x(n); x.setZero();\n\tVectorXd y(m); y.setZero();\n\n\tstd::vector<LinearConstraintType> constraint_types;\n\tfor (size_t i = 0; i < m; ++i) {\n\t\tauto& lb = get_rhs_lower()[i];\n\t\tauto& ub = get_rhs_upper()[i];\n\t\tif (lb == ub) {\n\t\t\tb[i] = lb;\n\t\t\tconstraint_types.push_back(LinearConstraintType::Equality);\n\t\t}\n\t\telse if (ub < 1e100) {\n\t\t\tattest(lb <= -1e100); // Cannot convert if both lb and ub exists.\n\t\t\tb[i] = ub;\n\t\t\tconstraint_types.push_back(LinearConstraintType::LessThan);\n\t\t}\n\t\telse {\n\t\t\tattest(lb > -1e100);\n\t\t\tb[i] = lb;\n\t\t\tconstraint_types.push_back(LinearConstraintType::GreaterThan);\n\t\t}\n\t}\n\n\tbool feasible = first_order_primal_dual_solve(&x, &y, c, lb, ub, A, b, constraint_types, options);\n\n\tget_solution().resize(n);\n\tfor (size_t j = 0; j < n; ++j) {\n\t\tget_solution()[j] = x(j);\n\t}\n\n\treturn feasible;\n}\n\n\nbool FirstOrderProblem::solve_admm(const FirstOrderOptions& options)\n{\n\tusing namespace Eigen;\n\tusing namespace std;\n\n\tauto n = get_cost().size();\n\tauto m = get_rhs_lower().size();\n\n\t// First, convert all inequality constraints to\n\t// equality constraints.\n\tconvert_into_equality_constrained_problem();\n\tsize_t constraints_added = get_cost().size() - n;\n\tn = get_cost().size();\n\tif (options.log_function && constraints_added > 0) {\n\t\tostringstream sout;\n\t\tsout << constraints_added << \" inequality constraints converted.\";\n\t\toptions.log_function(sout.str());\n\t}\n\n\tSparseMatrix<double> A;\n\tget_system_matrix(&A, options);\n\n\tMap<const VectorXd> lb(get_var_lb().data(), n);\n\tMap<const VectorXd> ub(get_var_ub().data(), n);\n\tMap<const VectorXd> b(get_rhs_upper().data(), m);\n\tMap<const VectorXd> c(get_cost().data(), n);\n\tVectorXd x(n); x.setZero();\n\n\tbool feasible = first_order_admm_solve(&x, c, lb, ub, A, b, options);\n\n\tget_solution().resize(n);\n\tfor (size_t j = 0; j < n; ++j) {\n\t\tget_solution()[j] = x(j);\n\t}\n\n\treturn feasible;\n}\n", "meta": {"hexsha": "dc89aa6a96b1a1da5b5deffe7bd357b22b467037", "size": 16485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/first_order_solver.cpp", "max_stars_repo_name": "PetterS/easy-IP", "max_stars_repo_head_hexsha": "d57607333b9844a32723db5e1d748b9eeb4fb2a2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-12-04T05:59:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-01T00:33:30.000Z", "max_issues_repo_path": "source/first_order_solver.cpp", "max_issues_repo_name": "PetterS/easy-IP", "max_issues_repo_head_hexsha": "d57607333b9844a32723db5e1d748b9eeb4fb2a2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-04T19:41:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-04T19:41:26.000Z", "max_forks_repo_path": "source/first_order_solver.cpp", "max_forks_repo_name": "PetterS/easy-IP", "max_forks_repo_head_hexsha": "d57607333b9844a32723db5e1d748b9eeb4fb2a2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-04-10T20:31:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-04T06:13:27.000Z", "avg_line_length": 29.8101265823, "max_line_length": 113, "alphanum_fraction": 0.6033363664, "num_tokens": 4464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936438, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6124345904652831}}
{"text": "#include <hpx/hpx_init.hpp>\n#include <hpx/runtime/threads/topology.hpp>\n#include <boost/format.hpp>\n\n#include <sys/time.h>\n\n#include \"matrix_block.h\"\n\nusing hpx::lcos::shared_future;\nusing hpx::lcos::future;\nusing std::vector;\nusing std::cout;\nusing std::endl;\nusing std::chrono::high_resolution_clock;\nusing time_point = std::chrono::system_clock::time_point;\n\n\nint blocksize;\n\nvoid print(block A) {\n    for(int i = 0; i < A.height; i++) {\n        for(int j = 0; j < A.width; j++) {\n            cout << A[i][j] << \" \";\n        }\n        cout << endl;\n    }\n    cout << endl;\n}\n\nblock rec_mult(block A, block B, block C);\n\nblock serial_mult(block A, block B, block C) {\n    for (int i = 0; i < C.height; i++) {\n        for (int j = 0; j < C.width; j++) {\n            for (int k = 0; k < A.width;k++) {\n                C[i][j] += A[i][k] * B[k][j];\n            }\n        }\n    }\n    return C;\n}\n\nblock add_blocks(block A, block B, block result) {\n    for(int i = 0; i < A.height; i++){\n        for(int j = 0; j < A.width; j++) {\n            result[i][j] = A[i][j] + B[i][j];\n        }\n    }\n    return result;\n}\n\nblock calc_c11(block A, block B, block C) {\n    block tempC = C.block11();//scratch space\n    tempC.add_scratch();\n    block A11B11 = rec_mult(A.block11(), B.block11(), C.block11());\n    block A12B21 = rec_mult(A.block12(), B.block21(), tempC);\n    return add_blocks(A11B11, A12B21, C.block11());\n}\n\nblock calc_c12(block A, block B, block C) {\n    block tempC = C.block12();\n    tempC.add_scratch();\n    block A11B12 = rec_mult(A.block11(), B.block12(), C.block12());\n    block A12B22 = rec_mult(A.block12(), B.block22(), tempC);\n    return add_blocks(A11B12, A12B22, C.block12());\n}\n\nblock calc_c21(block A, block B, block C) {\n    block tempC = C.block21();\n    tempC.add_scratch();\n    block A21B11 = rec_mult(A.block21(), B.block11(), C.block21());\n    block A22B21 = rec_mult(A.block22(), B.block21(), tempC);\n    return add_blocks(A21B11, A22B21, C.block21());\n}\n\nblock calc_c22(block A, block B, block C) {\n    block tempC = C.block22();\n    tempC.add_scratch();\n    block A21B12 = rec_mult(A.block21(), B.block12(), C.block22());\n    block A22B22 = rec_mult(A.block22(), B.block22(), tempC);\n    return add_blocks(A21B12, A22B22, C.block22());\n}\n\nblock rec_mult(block A, block B, block C) {\n    if(C.width <= blocksize || C.height <= blocksize ) {\n        return serial_mult(A, B, C);\n    } \n    block C11 = calc_c11(A, B, C);\n    block C12 = calc_c12(A, B, C);\n    block C21 = calc_c21(A, B, C);\n    block C22 = calc_c22(A, B, C);\n\n    return C;\n}\n\nint hpx_main(int argc, char **argv) {\n    blocksize = 100;\n    int niter = 1, N = 1000;\n    time_point time1, time2;\n    srand(1);\n    if(argc > 1)\n        N = atoi(argv[1]);\n    if(argc > 2)\n        blocksize = atoi(argv[2]);\n    if(argc > 3)\n        niter = atoi(argv[3]);\n     cout << \"Recursive matrix multiplication\" << endl;\n     cout << \"size \" << N << endl;\n     cout << \"block size \" << blocksize << endl;\n     cout << \"Number of iterations \" << niter << endl;\n\n    block a(N);\n    block b(N);\n    block c(new double[N*N], N);\n\n    time1 = high_resolution_clock::now();\n    rec_mult(a, b, c);\n    time2 = high_resolution_clock::now();\n\n     auto time = std::chrono::duration_cast<std::chrono::microseconds>(time2 - time1).count();\n     cout << \"time \"<< time << \" microseconds\" << endl;\n    return hpx::finalize();\n}\n\nint main(int argc, char ** argv) {\n\n    hpx::init(argc, argv);\n\n    return 0;\n}\n", "meta": {"hexsha": "299b4cc1aaa5ef1bfbf958a23b55c87fd7120daa", "size": 3477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/hpx/bench/mmult-serial.cpp", "max_stars_repo_name": "tianyi93/hpxMP_mirror", "max_stars_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-07-16T14:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T11:25:09.000Z", "max_issues_repo_path": "examples/hpx/bench/mmult-serial.cpp", "max_issues_repo_name": "tianyi93/hpxMP_mirror", "max_issues_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-06-18T14:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-16T20:43:57.000Z", "max_forks_repo_path": "examples/hpx/bench/mmult-serial.cpp", "max_forks_repo_name": "tianyi93/hpxMP_mirror", "max_forks_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T18:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T11:17:28.000Z", "avg_line_length": 26.5419847328, "max_line_length": 94, "alphanum_fraction": 0.5760713259, "num_tokens": 1067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6124345767263227}}
{"text": "//  (C) Copyright Matt Borland 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <cmath>\n#include <cfloat>\n#include <cstdint>\n#include <limits>\n#include <type_traits>\n#include <boost/math/ccmath/frexp.hpp>\n#include <boost/math/ccmath/isnan.hpp>\n#include <boost/math/ccmath/isinf.hpp>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\ntemplate <typename T>\ninline constexpr T base_helper(const T val)\n{\n    int i = 0;\n    const T ans = boost::math::ccmath::frexp(val, &i);\n\n    return ans;\n}\n\ntemplate <typename T>\ninline constexpr int exp_helper(const T val)\n{\n    int i = 0;\n    boost::math::ccmath::frexp(val, &i);\n\n    return i;\n}\n\ntemplate <typename T>\nconstexpr void test()\n{\n    if constexpr (std::numeric_limits<T>::has_quiet_NaN)\n    {\n        static_assert(boost::math::ccmath::isnan(base_helper(std::numeric_limits<T>::quiet_NaN())), \"If the arg is NaN, NaN is returned\");\n    }\n\n    static_assert(!base_helper(T(0)), \"If the arg is +- 0 the value is returned\");\n    static_assert(!base_helper(T(-0)), \"If the arg is +- 0 the value is returned\");\n    static_assert(boost::math::ccmath::isinf(base_helper(std::numeric_limits<T>::infinity())), \"If the arg is +- inf the value is returned\");\n    static_assert(boost::math::ccmath::isinf(base_helper(-std::numeric_limits<T>::infinity())), \"If the arg is +- inf the value is returned\");\n\n    // N[125/32, 30]\n    // 3.90625000000000000000000000000\n    // 0.976562500000000000000000000000 * 2^2\n    constexpr T test_base = base_helper(T(125.0/32));\n    static_assert(test_base == T(0.9765625));\n    constexpr int test_exp = exp_helper(T(125.0/32));\n    static_assert(test_exp == 2);\n}\n\n#if !defined(BOOST_MATH_NO_CONSTEXPR_DETECTION) && !defined(BOOST_MATH_USING_BUILTIN_CONSTANT_P)\nint main()\n{\n    test<float>();\n    test<double>();\n\n    #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n    test<long double>();\n    #endif\n    \n    #ifdef BOOST_HAS_FLOAT128\n    test<boost::multiprecision::float128>();\n    #endif\n\n    return 0;\n}\n#else\nint main()\n{\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "75a11b26a547d11ef3756f96de208aeb802a456a", "size": 2216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ccmath_frexp_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "test/ccmath_frexp_test.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "test/ccmath_frexp_test.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 27.3580246914, "max_line_length": 142, "alphanum_fraction": 0.6908844765, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.612349276587951}}
{"text": "#include <vector>\n#include <list>\n#include <string>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <algorithm>\n#include <iterator>\n\n#include <boost/cstdlib.hpp>\n\ndouble distance(const std::vector<std::size_t> &lhs, const std::vector<std::size_t> &rhs, const std::vector<std::vector<double>> &distances)\n{\n  double sum_d = 0.0;\n  std::size_t n = 0;\n  for(std::size_t x : lhs) {\n    for(std::size_t y : rhs) {\n      //std::cerr << \"distances[\" << x << \"][\" << y << \"]=\" << distances.at(x).at(y) << std::endl;\n      sum_d += distances.at(x).at(y);\n      ++n;\n    }\n  }\n  //std::cerr << \"sum_d=\" << sum_d << std::endl;\n  return sum_d / n;\n}\n\nint main()\n{\n  std::cerr.precision(3);\n  //std::cerr << std::fixed;\n\n  std::size_t n;\n  std::cin >> n;\n  //std::cerr << \"n=\" << n << std::endl;\n\n  std::vector<std::vector<double>> distances(n, std::vector<double>(n, 0.0));\n  std::string line;\n  std::getline(std::cin, line);\n  std::size_t l = 0;\n  while(true) {\n    std::getline(std::cin, line);\n    if(!std::cin) {\n      break;\n    }\n\n    std::istringstream linestream(line);\n    for(std::size_t i = 0; i < n; ++i) {\n      double x;\n      linestream >> x;\n      distances.at(l).at(i) = x;\n    }\n    ++l;\n  }\n\n  //std::cerr << \"distances=[\" << std::endl;\n  //for(const std::vector<double> &row : distances) {\n    //std::cerr << \"  [ \";\n    //std::copy(row.begin(), row.end(), std::ostream_iterator<double>(std::cerr, \" \"));\n    //std::cerr << \"]\" << std::endl;\n  //}\n  //std::cerr << \"]\" << std::endl;\n\n  std::list<std::vector<std::size_t>> clusters;\n  typedef std::list<std::vector<std::size_t>>::iterator clusters_iterator;\n  for(std::size_t i = 0; i < n; ++i) {\n    clusters.push_back(std::vector<std::size_t>(1, i));\n  }\n\n  //for(const auto &cluster: clusters) {\n    //std::cerr << \"cluster=[ \";\n    //std::copy(cluster.begin(), cluster.end(), std::ostream_iterator<std::size_t>(std::cerr, \" \"));\n    //std::cerr << \"]\" << std::endl;\n  //}\n\n  while(clusters.size() > 1) {\n    const clusters_iterator c_end = clusters.end();\n    double min_d = std::numeric_limits<double>::max(); // minimum distance\n    std::pair<clusters_iterator, clusters_iterator> min_c = std::make_pair(c_end, c_end); // indices of two clusters with minimum distance\n    for(clusters_iterator c_i = clusters.begin(); c_i != c_end; ++c_i) {\n      for(clusters_iterator c_j = c_i; c_j != c_end; ++c_j) {\n        if(c_i == c_j) {\n          continue;\n        }\n        double d = distance(*c_i, *c_j, distances);\n        if(d <= min_d) {\n          min_d = d;\n          min_c = std::make_pair(c_i, c_j);\n        }\n      }\n    }\n    //std::cerr << \"min_d=\" << min_d << std::endl;\n\n    //std::cerr << \"min_c.first=[ \";\n    //std::copy(min_c.first->begin(), min_c.first->end(), std::ostream_iterator<std::size_t>(std::cerr, \" \"));\n    //std::cerr << \"]\" << std::endl;\n    //std::cerr << \"min_c.second=[ \";\n    //std::copy(min_c.second->begin(), min_c.second->end(), std::ostream_iterator<std::size_t>(std::cerr, \" \"));\n    //std::cerr << \"]\" << std::endl;\n\n    std::copy(min_c.second->begin(), min_c.second->end(), std::back_inserter(*min_c.first));\n    //std::sort(min_c.first->begin(), min_c.first->end());\n\n    //std::cerr << \"min_c.first=[ \";\n    //std::copy(min_c.first->begin(), min_c.first->end(), std::ostream_iterator<std::size_t>(std::cerr, \" \"));\n    //std::cerr << \"]\" << std::endl;\n    //std::cerr << \"min_c.second=[ \";\n    //std::copy(min_c.second->begin(), min_c.second->end(), std::ostream_iterator<std::size_t>(std::cerr, \" \"));\n    //std::cerr << \"]\" << std::endl;\n\n    clusters.erase(min_c.second);\n\n    //for(const auto &cluster: clusters) {\n      //std::cerr << \"cluster=[ \";\n      //std::copy(cluster.begin(), cluster.end(), std::ostream_iterator<std::size_t>(std::cerr, \" \"));\n      //std::cerr << \"]\" << std::endl;\n    //}\n    for(std::size_t i: *min_c.first) {\n      std::cout << (i + 1) << \" \";\n    }\n    std::cout << std::endl;\n    //std::cout << std::endl;\n  }\n\n  return boost::exit_success;\n}\n\n\n// vim: set ts=2 sw=2 et:\n\n\n", "meta": {"hexsha": "102394476ac1b2323d20e69bd9a88ac56a9bc188", "size": 4027, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "meetups/04-HierarchicalClustering/data/14_05_07.tar/14_05_07/prog.cpp", "max_stars_repo_name": "it-depends/CPSG-ML", "max_stars_repo_head_hexsha": "4051e72d9d44d2c3c79c3062c8e647f529b76faf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "meetups/04-HierarchicalClustering/data/14_05_07.tar/14_05_07/prog.cpp", "max_issues_repo_name": "it-depends/CPSG-ML", "max_issues_repo_head_hexsha": "4051e72d9d44d2c3c79c3062c8e647f529b76faf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "meetups/04-HierarchicalClustering/data/14_05_07.tar/14_05_07/prog.cpp", "max_forks_repo_name": "it-depends/CPSG-ML", "max_forks_repo_head_hexsha": "4051e72d9d44d2c3c79c3062c8e647f529b76faf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-15T21:48:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-15T21:48:01.000Z", "avg_line_length": 30.7404580153, "max_line_length": 140, "alphanum_fraction": 0.557486963, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6123492716799231}}
{"text": "\n#pragma once\n\n#include \"perceive/foundation.hpp\"\n#include \"perceive/utils/sdbm-hash.hpp\"\n#include <Eigen/Core>\n#include <cmath>\n\nnamespace perceive\n{\n// --------------------------------------------------------------------- Vector2\n#pragma pack(push, 1)\ntemplate<typename T> class Vector2T\n{\n public:\n   using value_type = T;\n\n   T x, y;\n\n   Vector2T()\n       : x(T(0.0))\n       , y(T(0.0))\n   {}\n   Vector2T(T x_, T y_)\n       : x(x_)\n       , y(y_)\n   {}\n   Vector2T(const float p[2])\n   {\n      x = p[0];\n      y = p[1];\n   }\n   Vector2T(const double p[2])\n   {\n      x = p[0];\n      y = p[1];\n   }\n\n   Vector2T& operator=(const Vector2T& v) = default;\n\n   Vector2T& operator=(const Eigen::Vector2f& v)\n   {\n      for(int i = 0; i < 2; ++i) this->operator[](i) = v(i);\n      return *this;\n   }\n\n   static Vector2T nan() { return Vector2T(T(NAN), T(NAN)); }\n   static Vector2T range()\n   {\n      auto mmax = std::numeric_limits<T>::max();\n      auto mmin = std::numeric_limits<T>::lowest();\n      return Vector2T(mmax, mmin);\n   }\n\n   void union_value(T v)\n   {\n      if(v < this->x) this->x = v;\n      if(v > this->y) this->y = v;\n   }\n\n   unsigned size() const { return 2; }\n\n   Vector2T& normalise(T epsilon = 1e-9)\n   {\n      // Don't normalize if we don't have to\n      T mag2 = x * x + y * y;\n      if(std::fabs(mag2 - T(1.0)) > epsilon) {\n         T mag_inv = T(1.0) / std::sqrt(mag2);\n         x *= mag_inv;\n         y *= mag_inv;\n      }\n      return *this;\n   }\n   Vector2T normalised(T epsilon = T(1e-9)) const\n   {\n      Vector2T res = *this;\n      res.normalise(epsilon);\n      return res;\n   }\n   Vector2T& normalize(T epsilon = T(1e-9)) { return normalise(epsilon); }\n   Vector2T normalized(T epsilon = T(1e-9)) const\n   {\n      return normalised(epsilon);\n   }\n   T quadrance() const { return x * x + y * y; }\n   T norm() const { return T(std::sqrt(quadrance())); }\n   T dot(const Vector2T& rhs) const { return x * rhs.x + y * rhs.y; }\n   T perp_dot(const Vector2T& rhs) const { return x * rhs.y - y * rhs.x; }\n   T quadrance(const Vector2T& rhs) const\n   {\n      return (x - rhs.x) * (x - rhs.x) + (y - rhs.y) * (y - rhs.y);\n   }\n   T distance(const Vector2T& rhs) const { return (*this - rhs).norm(); }\n\n   // As polar co-ordinates\n   T& mag() { return x; }\n   const T& mag() const { return x; }\n   T& theta() { return y; }\n   const T& theta() const { return y; }\n\n   // As format\n   T& width() { return x; }\n   const T& width() const { return x; }\n   T& height() { return y; }\n   const T& height() const { return y; }\n\n   Vector2T& set_to(const T& a, const T& b)\n   {\n      x = a;\n      y = b;\n      return *this;\n   }\n   Vector2T& set_to(T a[2])\n   {\n      set_to(a[0], a[1]);\n      return *this;\n   }\n\n   T* copy_to(T a[2]) const\n   {\n      a[0] = x;\n      a[1] = y;\n      return a;\n   }\n\n   T* ptr()\n   {\n#ifdef DEBUG_BUILD\n      assert(&x == reinterpret_cast<const T*>(this) + 0);\n      assert(&y == reinterpret_cast<const T*>(this) + 1);\n#endif\n      return &x;\n   }\n   const T* ptr() const { return const_cast<Vector2T<T>*>(this)->ptr(); }\n\n   T& operator[](int idx)\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 2);\n#endif\n      return ptr()[idx];\n   }\n   const T& operator[](int idx) const\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 2);\n#endif\n      return ptr()[idx];\n   }\n\n   T& operator()(int idx)\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 2);\n#endif\n      return ptr()[idx];\n   }\n\n   const T& operator()(int idx) const\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 2);\n#endif\n      return ptr()[idx];\n   }\n\n   Vector2T flip_x() const { return Vector2T(-x, y); }\n   Vector2T flip_y() const { return Vector2T(x, -y); }\n   Vector2T clockwise_90() const { return Vector2T(y, -x); }\n   Vector2T counter_clockwise_90() const { return Vector2T(-y, x); }\n   Vector2T rotate(T theta) const\n   {\n      auto sin_t = std::sin(theta);\n      auto cos_t = std::cos(theta);\n      return Vector2T<T>(x * cos_t - y * sin_t, x * sin_t + y * cos_t);\n   }\n\n   Vector2T round() const { return Vector2T(std::round(x), std::round(y)); }\n\n   Vector2T& operator*=(T scalar)\n   {\n      x *= scalar;\n      y *= scalar;\n      return *this;\n   }\n\n   Vector2T& operator/=(T scalar)\n   {\n      x /= scalar;\n      y /= scalar;\n      return *this;\n   }\n   Vector2T operator*(T scalar) const\n   {\n      Vector2T res(*this);\n      res *= scalar;\n      return res;\n   }\n\n   Vector2T operator/(T scalar) const\n   {\n      Vector2T res(*this);\n      res /= scalar;\n      return res;\n   }\n\n   Vector2T& operator+=(const Vector2T& rhs)\n   {\n      x += rhs.x;\n      y += rhs.y;\n      return *this;\n   }\n\n   Vector2T& operator-=(const Vector2T& rhs)\n   {\n      x -= rhs.x;\n      y -= rhs.y;\n      return *this;\n   }\n\n   Vector2T operator+(const Vector2T& rhs) const\n   {\n      Vector2T res(*this);\n      res += rhs;\n      return res;\n   }\n   Vector2T operator-(const Vector2T& rhs) const\n   {\n      Vector2T res(*this);\n      res -= rhs;\n      return res;\n   }\n\n   Vector2T operator-() const { return Vector2T<T>(-x, -y); }\n\n   bool operator==(const Vector2T& rhs) const\n   {\n      return x == rhs.x && y == rhs.y;\n   }\n   bool operator!=(const Vector2T& rhs) const { return !(*this == rhs); }\n\n   bool operator<(const Vector2T& rhs) const\n   {\n      return x == rhs.x ? y < rhs.y : x < rhs.x;\n   }\n   bool operator<=(const Vector2T& rhs) const\n   {\n      return x == rhs.x ? y <= rhs.y : x <= rhs.x;\n   }\n   bool operator>(const Vector2T& rhs) const { return !(*this <= rhs); }\n   bool operator>=(const Vector2T& rhs) const { return !(*this < rhs); }\n\n   bool has_nan() const { return x != x || y != y; }\n   bool is_nan() const { return std::isnan(x) || std::isnan(y); }\n   bool is_finite() const { return std::isfinite(x) && std::isfinite(y); }\n   bool is_unit_vector(T epsilon = 1e-9) const\n   {\n      return is_finite() && fabs(quadrance() - 1.0) < epsilon;\n   }\n\n   inline friend bool isfinite(const Vector2T& o) noexcept\n   {\n      return o.is_finite();\n   }\n\n   std::string to_string(const char* fmt = nullptr) const\n   {\n      if(fmt == nullptr) {\n         if constexpr(std::is_floating_point<T>::value) {\n            fmt = \"[{:7.5f}, {:7.5f}]\";\n         } else {\n            fmt = \"[{}, {}]\";\n         }\n      }\n      return format(fmt, x, y);\n   }\n   std::string to_str() const { return format(\"[{}, {}]\", x, y); }\n\n   void print(const char* msg = NULL, bool newline = true) const\n   {\n      printf(\"%s%s%s%s\",\n             msg,\n             (msg == NULL ? \"\" : \" \"),\n             to_string().c_str(),\n             (newline ? \"\\n\" : \"\"));\n      fflush(stdout);\n   }\n\n   size_t hash() const { return sdbm_hash(ptr(), sizeof(T) * size()); }\n\n   friend std::string str(const Vector2T<T>& o) noexcept\n   {\n      return o.to_string();\n   }\n};\n#pragma pack(pop)\n\n// Scalar multiplication\ntemplate<typename T> Vector2T<T> operator*(float a, const Vector2T<T>& v)\n{\n   return v * T(a);\n}\ntemplate<typename T> Vector2T<T> operator/(float a, const Vector2T<T>& v)\n{\n   return v / T(a);\n}\ntemplate<typename T> Vector2T<T> operator*(double a, const Vector2T<T>& v)\n{\n   return v * T(a);\n}\ntemplate<typename T> Vector2T<T> operator/(double a, const Vector2T<T>& v)\n{\n   return v / T(a);\n}\n\n// String shim\ntemplate<typename T> std::string str(const Vector2T<T>& v)\n{\n   return v.to_string();\n}\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& out, const Vector2T<T>& v)\n{\n   out << v.to_string();\n   return out;\n}\n\ntemplate<typename T> inline T perp_dot(T x1, T y1, T x2, T y2)\n{\n   return x1 * y2 - x2 * y1;\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "a6a17427f6e4efba6099e1b75926e4127a6d6219", "size": 7575, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector-2.hpp", "max_stars_repo_name": "prcvlabs/multiview", "max_stars_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T23:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:43:32.000Z", "max_issues_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector-2.hpp", "max_issues_repo_name": "prcvlabs/multiview", "max_issues_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:33:02.000Z", "max_forks_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector-2.hpp", "max_forks_repo_name": "prcvlabs/multiview", "max_forks_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-26T03:14:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T06:42:52.000Z", "avg_line_length": 22.6796407186, "max_line_length": 80, "alphanum_fraction": 0.5392739274, "num_tokens": 2334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.612349270661265}}
{"text": "//\n// Copyright (c) 2015-2016,2018 CNRS\n//\n\n/* --- Unitary test symmetric.cpp This code tests and compares two ways of\n * expressing symmetric matrices. In addition to the unitary validation (test\n * of the basic operations), the code is validating the computation\n * performances of each methods.\n *\n * The three methods are:\n * - Eigen SelfAdjoint (a mask atop of a classical dense matrix) ==> the least efficient.\n * - Pinocchio rewritting of Metapod code with LTI factor as well and minor improvement.\n *\n * IMPORTANT: the following timings seems outdated.\n * Expected time scores on a I7 2.1GHz:\n * - Eigen: 2.5us\n * - Pinocchio: 6us\n */\n\n#include \"pinocchio/spatial/fwd.hpp\"\n#include \"pinocchio/spatial/skew.hpp\"\n#include \"pinocchio/utils/timer.hpp\"\n\n#include <boost/random.hpp>\n# include <eigen3/Eigen/Geometry>\n\n#include \"pinocchio/spatial/symmetric3.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\n\n# include <eigen3/Eigen/StdVector>\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::Matrix3d)\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(pinocchio::Symmetric3)\n\nvoid timeSym3(const pinocchio::Symmetric3 & S,\n        const pinocchio::Symmetric3::Matrix3 & R,\n        pinocchio::Symmetric3 & res)\n{\n  res = S.rotate(R);\n}\n\n#ifdef WITH_METAPOD\n\n#include <metapod/tools/spatial/lti.hh>\n#include <metapod/tools/spatial/rm-general.hh>\n\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::ltI<double>)\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::RotationMatrixTpl<double>)\n\nvoid timeLTI(const metapod::Spatial::ltI<double>& S,\n       const metapod::Spatial::RotationMatrixTpl<double>& R, \n       metapod::Spatial::ltI<double> & res)\n{\n  res = R.rotTSymmetricMatrix(S);\n}\n\n#endif\n\nvoid timeSelfAdj( const Eigen::Matrix3d & A,\n      const Eigen::Matrix3d & Sdense,\n      Eigen::Matrix3d & ASA )\n{\n  typedef Eigen::SelfAdjointView<const Eigen::Matrix3d,Eigen::Upper> Sym3;\n  Sym3 S(Sdense);\n  ASA.triangularView<Eigen::Upper>()\n    = A * S * A.transpose();\n}\n\nBOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )\n\n/* --- PINOCCHIO ------------------------------------------------------------ */\n/* --- PINOCCHIO ------------------------------------------------------------ */\n/* --- PINOCCHIO ------------------------------------------------------------ */\nBOOST_AUTO_TEST_CASE ( test_pinocchio_Sym3 )\n{\n  using namespace pinocchio;\n  typedef Symmetric3::Matrix3 Matrix3;\n  typedef Symmetric3::Vector3 Vector3;\n  \n  { \n    // op(Matrix3)\n    {\n      Matrix3 M = Matrix3::Random(); M = M*M.transpose();\n      Symmetric3 S(M);\n      BOOST_CHECK(S.matrix().isApprox(M, 1e-12));\n    }\n    \n    // S += S\n    {\n      Symmetric3\n      S = Symmetric3::Random(),\n      S2 = Symmetric3::Random();\n      Symmetric3 Scopy = S;\n      S+=S2;\n      BOOST_CHECK(S.matrix().isApprox(S2.matrix()+Scopy.matrix(), 1e-12));\n    }\n\n    // S + M\n    {\n      Symmetric3 S = Symmetric3::Random();\n      Matrix3 M = Matrix3::Random(); M = M*M.transpose();\n\n      Symmetric3 S2 = S + M;\n      BOOST_CHECK(S2.matrix().isApprox(S.matrix()+M, 1e-12));\n\n      S2 = S - M;\n      BOOST_CHECK(S2.matrix().isApprox(S.matrix()-M, 1e-12));\n    }\n\n    // S*v\n    {\n      Symmetric3 S = Symmetric3::Random();\n      Vector3 v = Vector3::Random(); \n      Vector3 Sv = S*v;\n      BOOST_CHECK(Sv.isApprox(S.matrix()*v, 1e-12));\n    }\n\n    // Random\n    for(int i=0;i<100;++i )\n    {\n      Matrix3 M = Matrix3::Random(); M = M*M.transpose();\n      Symmetric3 S = Symmetric3::RandomPositive();\n      Vector3 v = Vector3::Random();\n      BOOST_CHECK_GT( (v.transpose()*(S*v))[0] , 0);\n    }\n\n    // Identity\n    { \n      BOOST_CHECK(Symmetric3::Identity().matrix().isApprox(Matrix3::Identity(), 1e-12));\n    }\n\n    // Skew2\n    {\n      Vector3 v = Vector3::Random();\n      Symmetric3 vxvx = Symmetric3::SkewSquare(v);\n\n      Vector3 p = Vector3::UnitX();\n      BOOST_CHECK((vxvx*p).isApprox(v.cross(v.cross(p)), 1e-12));\n\n      p = Vector3::UnitY();\n      BOOST_CHECK((vxvx*p).isApprox(v.cross(v.cross(p)), 1e-12));\n\n      p = Vector3::UnitZ();\n      BOOST_CHECK((vxvx*p).isApprox(v.cross(v.cross(p)), 1e-12));\n\n      Matrix3 vx = skew(v);\n      Matrix3 vxvx2 = (vx*vx).eval();\n      BOOST_CHECK(vxvx.matrix().isApprox(vxvx2, 1e-12));\n\n      Symmetric3 S = Symmetric3::RandomPositive();\n      BOOST_CHECK((S-Symmetric3::SkewSquare(v)).matrix()\n                                        .isApprox(S.matrix()-vxvx2, 1e-12));\n\n      double m = Eigen::internal::random<double>()+1;\n      BOOST_CHECK((S-m*Symmetric3::SkewSquare(v)).matrix()\n                                        .isApprox(S.matrix()-m*vxvx2, 1e-12));\n\n\n      Symmetric3 S2 = S;\n      S -= Symmetric3::SkewSquare(v);\n      BOOST_CHECK(S.matrix().isApprox(S2.matrix()-vxvx2, 1e-12));\n\n      S = S2; S -= m*Symmetric3::SkewSquare(v);\n      BOOST_CHECK(S.matrix().isApprox(S2.matrix()-m*vxvx2, 1e-12));\n\n    }\n\n    // (i,j)\n    {\n      Matrix3 M = Matrix3::Random(); M = M*M.transpose();\n      Symmetric3 S(M);\n      for(int i=0;i<3;++i)\n        for(int j=0;j<3;++j)\n          BOOST_CHECK_SMALL(S(i,j) - M(i,j), Eigen::NumTraits<double>::dummy_precision());\n      }\n    }\n\n    // SRS\n    {\n      Symmetric3 S = Symmetric3::RandomPositive();\n      Matrix3 R = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();\n      \n      Symmetric3 RSRt = S.rotate(R);\n      BOOST_CHECK(RSRt.matrix().isApprox(R*S.matrix()*R.transpose(), 1e-12));\n\n      Symmetric3 RtSR = S.rotate(R.transpose());\n      BOOST_CHECK(RtSR.matrix().isApprox(R.transpose()*S.matrix()*R, 1e-12));\n    }\n  \n  // Test operator vtiv\n  {\n    Symmetric3 S = Symmetric3::RandomPositive();\n    Vector3 v = Vector3::Random();\n    double kinetic_ref = v.transpose() * S.matrix() * v;\n    double kinetic = S.vtiv(v);\n    BOOST_CHECK_SMALL(kinetic_ref - kinetic, 1e-12);\n  }\n  \n  // Test v x S3\n  {\n    Symmetric3 S = Symmetric3::RandomPositive();\n    Vector3 v = Vector3::Random();\n    Matrix3 Vcross = skew(v);\n    Matrix3 M_ref(Vcross * S.matrix());\n    \n    Matrix3 M_res;\n    Symmetric3::vxs(v,S,M_res);\n    BOOST_CHECK(M_res.isApprox(M_ref));\n    \n    BOOST_CHECK(S.vxs(v).isApprox(M_ref));\n  }\n  \n  // Test S3 vx\n  {\n    Symmetric3 S = Symmetric3::RandomPositive();\n    Vector3 v = Vector3::Random();\n    Matrix3 Vcross = skew(v);\n    Matrix3 M_ref(S.matrix() * Vcross);\n    \n    Matrix3 M_res;\n    Symmetric3::svx(v,S,M_res);\n    BOOST_CHECK(M_res.isApprox(M_ref));\n    \n    BOOST_CHECK(S.svx(v).isApprox(M_ref));\n  }\n  \n  // Test isZero\n  {\n    Symmetric3 S_not_zero = Symmetric3::Identity();\n    BOOST_CHECK(!S_not_zero.isZero());\n    \n    Symmetric3 S_zero = Symmetric3::Zero();\n    BOOST_CHECK(S_zero.isZero());\n  }\n  \n  // Test isApprox\n  {\n    Symmetric3 S1 = Symmetric3::RandomPositive();\n    Symmetric3 S2 = S1;\n    \n    BOOST_CHECK(S1.isApprox(S2));\n    \n    Symmetric3 S3 = S1;\n    S3 += S3;\n    BOOST_CHECK(!S1.isApprox(S3));\n  }\n\n    // Time test\n    {\n      const size_t NBT = 100000;\n      Symmetric3 S = Symmetric3::RandomPositive();\n\n      std::vector<Symmetric3> Sres (NBT);\n      std::vector<Matrix3> Rs (NBT);\n      for(size_t i=0;i<NBT;++i) \n        Rs[i] = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();\n\n      std::cout << \"Pinocchio: \";\n      PinocchioTicToc timer(PinocchioTicToc::US); timer.tic();\n      SMOOTH(NBT)\n      {\n        timeSym3(S,Rs[_smooth],Sres[_smooth]);\n      }\n      timer.toc(std::cout,NBT);\n    }\n}\n\n/* --- EIGEN SYMMETRIC ------------------------------------------------------ */\n/* --- EIGEN SYMMETRIC ------------------------------------------------------ */\n/* --- EIGEN SYMMETRIC ------------------------------------------------------ */\n\nBOOST_AUTO_TEST_CASE ( test_eigen_SelfAdj )\n{\n  using namespace pinocchio;\n  typedef Eigen::Matrix3d Matrix3;\n  typedef Eigen::SelfAdjointView<Matrix3,Eigen::Upper> Sym3;\n\n  Matrix3 M = Matrix3::Random();\n  Sym3 S(M);\n  {\n    Matrix3 Scp = S;\n    BOOST_CHECK((Scp-Scp.transpose()).isApprox(Matrix3::Zero(), 1e-16));\n  }\n\n  Matrix3 M2 = Matrix3::Random();\n  M.triangularView<Eigen::Upper>() = M2;\n\n  Matrix3 A = Matrix3::Random(), ASA1, ASA2;\n  ASA1.triangularView<Eigen::Upper>() = A * S * A.transpose();\n  timeSelfAdj(A,M,ASA2);\n\n  {\n    Matrix3 Masa1 = ASA1.selfadjointView<Eigen::Upper>();\n    Matrix3 Masa2 = ASA2.selfadjointView<Eigen::Upper>();\n    BOOST_CHECK(Masa1.isApprox(Masa2, 1e-16));\n  }\n\n  const size_t NBT = 100000;\n  std::vector<Eigen::Matrix3d> Sres (NBT);\n  std::vector<Eigen::Matrix3d> Rs (NBT);\n  for(size_t i=0;i<NBT;++i) \n    Rs[i] = (Eigen::Quaterniond(Eigen::Matrix<double,4,1>::Random())).normalized().matrix();\n\n  std::cout << \"Eigen: \";\n  PinocchioTicToc timer(PinocchioTicToc::US); timer.tic();\n  SMOOTH(NBT)\n  {\n    timeSelfAdj(Rs[_smooth],M,Sres[_smooth]);\n  }\n  timer.toc(std::cout,NBT);\n}\n\nBOOST_AUTO_TEST_CASE(comparison)\n{\n  using namespace pinocchio;\n  Symmetric3 sym1(Symmetric3::Random());\n  \n  Symmetric3 sym2(sym1);\n  sym2.data() *= 2;\n  \n  BOOST_CHECK(sym2 != sym1);\n  BOOST_CHECK(sym1 == sym1);\n}\n\nBOOST_AUTO_TEST_CASE(cast)\n{\n  using namespace pinocchio;\n  Symmetric3 sym(Symmetric3::Random());\n  \n  BOOST_CHECK(sym.cast<double>() == sym);\n  BOOST_CHECK(sym.cast<long double>().cast<double>() == sym);\n  \n}\nBOOST_AUTO_TEST_SUITE_END ()\n\n", "meta": {"hexsha": "06109dd10de3105cb7c2fd57681dbf55c2d20695", "size": 9238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/symmetric.cpp", "max_stars_repo_name": "shubhamsingh91/Pinocchio_ss", "max_stars_repo_head_hexsha": "683f6d1ea445cf65e74056f2b18eb65a4151ff0f", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-30T18:01:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-30T21:49:06.000Z", "max_issues_repo_path": "unittest/symmetric.cpp", "max_issues_repo_name": "shubhamsingh91/Pinocchio_ss", "max_issues_repo_head_hexsha": "683f6d1ea445cf65e74056f2b18eb65a4151ff0f", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/symmetric.cpp", "max_forks_repo_name": "shubhamsingh91/Pinocchio_ss", "max_forks_repo_head_hexsha": "683f6d1ea445cf65e74056f2b18eb65a4151ff0f", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3313609467, "max_line_length": 98, "alphanum_fraction": 0.6025113661, "num_tokens": 2706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6123492637159199}}
{"text": "//============================================================================\r\n// Name        : autodiff.cpp\r\n// Author      : \r\n// Version     :\r\n// Copyright   : Your copyright notice\r\n// Description : Hello World in C++, Ansi-style\r\n//============================================================================\r\n\r\n#include <iostream>\r\n#include <sstream>\r\n#include <numeric>\r\n#include <boost/foreach.hpp>\r\n#include \"autodiff.h\"\r\n#include \"Stack.h\"\r\n#include \"Tape.h\"\r\n#include \"BinaryOPNode.h\"\r\n#include \"UaryOPNode.h\"\r\n\r\nusing namespace std;\r\n\r\nnamespace AutoDiff\r\n{\r\n\r\n#if FORWARD_ENABLED\r\n\r\nunsigned int num_var = 0;\r\n\r\nvoid hess_forward(Node* root, unsigned int nvar, double** hess_mat)\r\n{\r\n\tassert(nvar == num_var);\r\n\tunsigned int len = (nvar+3)*nvar/2;\r\n\troot->hess_forward(len,hess_mat);\r\n}\r\n\r\n#endif\r\n\r\n\r\nPNode* create_param_node(double value){\r\n\treturn new PNode(value);\r\n}\r\nVNode* create_var_node(double v)\r\n{\r\n\treturn new VNode(v);\r\n}\r\nOPNode* create_binary_op_node(OPCODE code, Node* left, Node* right)\r\n{\r\n\treturn BinaryOPNode::createBinaryOpNode(code,left,right);\r\n}\r\nOPNode* create_uary_op_node(OPCODE code, Node* left)\r\n{\r\n\treturn UaryOPNode::createUnaryOpNode(code,left);\r\n}\r\ndouble eval_function(Node* root)\r\n{\r\n\tassert(SD->size()==0);\r\n\tassert(SV->size()==0);\r\n\troot->eval_function();\r\n\tassert(SV->size()==1);\r\n\tdouble val = SV->pop_back();\r\n\treturn val;\r\n}\r\n\r\ndouble grad_reverse(Node* root,vector<Node*>& vnodes, vector<double>& grad)\r\n{\r\n\tgrad.clear();\r\n\tBOOST_FOREACH(Node* node, vnodes)\r\n\t{\r\n\t\tassert(node->getType()==VNode_Type);\r\n\t\tstatic_cast<VNode*>(node)->adj = NaN_Double;\r\n\t}\r\n\r\n\tassert(SD->size()==0);\r\n\troot->grad_reverse_0();\r\n\tassert(SV->size()==1);\r\n\troot->grad_reverse_1_init_adj();\t\r\n\troot->grad_reverse_1();\r\n\tassert(SD->size()==0);\r\n\tdouble val = SV->pop_back();\r\n\tassert(SV->size()==0);\r\n\t//int i=0;\r\n\tBOOST_FOREACH(Node* node, vnodes)\r\n\t{\r\n\t\tassert(node->getType()==VNode_Type);\r\n\t\tgrad.push_back(static_cast<VNode*>(node)->adj);\r\n\t\tstatic_cast<VNode*>(node)->adj = NaN_Double;\r\n\t}\r\n\tassert(grad.size()==vnodes.size());\r\n\t//all nodes are VNode and adj == NaN_Double -- this reset adj for this expression tree by root\r\n\treturn val;\r\n}\r\n\r\ndouble grad_reverse(Node* root, vector<Node*>& vnodes, col_compress_matrix_row& rgrad)\r\n{\r\n\tBOOST_FOREACH(Node* node, vnodes)\r\n\t{\r\n\t\tassert(node->getType()==VNode_Type);\r\n\t\tstatic_cast<VNode*>(node)->adj = NaN_Double;\r\n\t}\r\n\tassert(SD->size()==0);\r\n\troot->grad_reverse_0();\r\n\tassert(SV->size()==1);\r\n\troot->grad_reverse_1_init_adj();\r\n\troot->grad_reverse_1();\r\n\tassert(SD->size()==0);\r\n\tdouble val = SV->pop_back();\r\n\tassert(SV->size()==0);\r\n\tunsigned int i =0;\r\n\tBOOST_FOREACH(Node* node, vnodes)\r\n\t{\r\n\t\tassert((node)->getType()==VNode_Type);\r\n\t\tdouble diff = static_cast<VNode*>(node)->adj;\r\n\t\tif(!isnan(diff)){\r\n\t\t\trgrad(i) = diff;\r\n\t\t\tstatic_cast<VNode*>(node)->adj = NaN_Double;\r\n\t\t}\r\n\t\ti++;\r\n\t}\r\n\t//all nodes are VNode and adj == NaN_Double -- this reset adj for this expression tree by root\r\n\tassert(i==vnodes.size());\r\n\treturn val;\r\n}\r\n\r\ndouble hess_reverse(Node* root,vector<Node*>& vnodes,vector<double>& dhess)\r\n{\r\n\tTT->clear();\r\n\tII->clear();\r\n\tassert(TT->empty());\r\n\tassert(II->empty());\r\n\tassert(TT->index==0);\r\n\tassert(II->index==0);\r\n\tdhess.clear();\r\n\r\n//\tfor(vector<Node*>::iterator it=nodes.begin();it!=nodes.end();it++)\r\n//\t{\r\n//\t\tassert((*it)->getType()==VNode_Type);\r\n//\t\t(*it)->index = 0;\r\n//\t} //this work complete in hess-reverse_0_init_index\r\n\r\n\tassert(root->n_in_arcs == 0);\r\n\troot->hess_reverse_0_init_n_in_arcs();\r\n\tassert(root->n_in_arcs == 1);\r\n\troot->hess_reverse_0();\r\n\tdouble val = NaN_Double;\r\n\troot->hess_reverse_get_x(TT->index,val);\r\n//\tcout<<TT->toString();\r\n//\tcout<<endl;\r\n//\tcout<<II->toString();\r\n//\tcout<<\"======================================= hess_reverse_0\"<<endl;\r\n\troot->hess_reverse_1_init_x_bar(TT->index);\r\n\tassert(root->n_in_arcs == 1);\r\n\troot->hess_reverse_1(TT->index);\r\n\tassert(root->n_in_arcs == 0);\r\n\tassert(II->index==0);\r\n//\tcout<<TT->toString();\r\n//\tcout<<endl;\r\n//\tcout<<II->toString();\r\n//\tcout<<\"======================================= hess_reverse_1\"<<endl;\r\n\r\n\tfor(vector<Node*>::iterator it=vnodes.begin();it!=vnodes.end();it++)\r\n\t{\r\n\t\tassert((*it)->getType()==VNode_Type);\r\n\t\tdhess.push_back(TT->get((*it)->index-1));\r\n\t}\r\n\r\n\tTT->clear();\r\n\tII->clear();\r\n\troot->hess_reverse_1_clear_index();\r\n\treturn val;\r\n}\r\n\r\ndouble hess_reverse(Node* root,vector<Node*>& vnodes,col_compress_matrix_col& chess)\r\n{\r\n\tTT->clear();\r\n\tII->clear();\r\n\tassert(TT->empty());\r\n\tassert(II->empty());\r\n\tassert(TT->index==0);\r\n\tassert(II->index==0);\r\n\r\n//\tfor(vector<Node*>::iterator it=nodes.begin();it!=nodes.end();it++)\r\n//\t{\r\n//\t\tassert((*it)->getType()==VNode_Type);\r\n//\t\t(*it)->index = 0;\r\n//\t} //this work complete in hess-reverse_0_init_index\r\n\r\n\tassert(root->n_in_arcs == 0);\r\n\t//reset node index and n_in_arcs - for the Tape location\r\n\troot->hess_reverse_0_init_n_in_arcs();\r\n\tassert(root->n_in_arcs == 1);\r\n\troot->hess_reverse_0();\r\n\tdouble val = NaN_Double;\r\n\troot->hess_reverse_get_x(TT->index,val);\r\n//\tcout<<TT->toString();\r\n//\tcout<<endl;\r\n//\tcout<<II->toString();\r\n//\tcout<<\"======================================= hess_reverse_0\"<<endl;\r\n\troot->hess_reverse_1_init_x_bar(TT->index);\r\n\tassert(root->n_in_arcs == 1);\r\n\troot->hess_reverse_1(TT->index);\r\n\tassert(root->n_in_arcs == 0);\r\n\tassert(II->index==0);\r\n//\tcout<<TT->toString();\r\n//\tcout<<endl;\r\n//\tcout<<II->toString();\r\n//\tcout<<\"======================================= hess_reverse_1\"<<endl;\r\n\r\n\tunsigned int i =0;\r\n\tBOOST_FOREACH(Node* node, vnodes)\r\n\t{\r\n\t\tassert(node->getType() == VNode_Type);\r\n\t\t//node->index = 0 means this VNode is not in the tree\r\n\t\tif(node->index!=0)\r\n\t\t{\r\n\t\t\tdouble hess = TT->get(node->index -1);\r\n\t\t\tif(!isnan(hess))\r\n\t\t\t{\r\n\t\t\t\tchess(i) = chess(i) + hess;\r\n\t\t\t}\r\n\t\t}\r\n\t\ti++;\r\n\t}\r\n\tassert(i==vnodes.size());\r\n\troot->hess_reverse_1_clear_index();\r\n\tTT->clear();\r\n\tII->clear();\r\n\treturn val;\r\n}\r\n\r\nunsigned int nzGrad(Node* root)\r\n{\r\n\tunsigned int nzgrad,total = 0;\r\n\tboost::unordered_set<Node*> nodes;\r\n\troot->collect_vnodes(nodes,total);\r\n\tnzgrad = nodes.size();\r\n\treturn nzgrad;\r\n}\r\n\r\n/*\r\n * number of non-zero gradient in constraint tree root that also belong to vSet\r\n */\r\nunsigned int nzGrad(Node* root, boost::unordered_set<Node*>& vSet)\r\n{\r\n\tunsigned int nzgrad=0, total=0;\r\n\tboost::unordered_set<Node*> vnodes;\r\n\troot->collect_vnodes(vnodes,total);\r\n\t//cout<<\"nzGrad - vnodes size[\"<<vnodes.size()<<\"] -- total node[\"<<total<<\"]\"<<endl;\r\n\tfor(boost::unordered_set<Node*>::iterator it=vnodes.begin();it!=vnodes.end();it++)\r\n\t{\r\n\t\tNode* n = *it;\r\n\t\tif(vSet.find(n) != vSet.end())\r\n\t\t{\r\n\t\t\tnzgrad++;\r\n\t\t}\r\n\t}\r\n\treturn nzgrad;\r\n}\r\n\r\nvoid nonlinearEdges(Node* root, EdgeSet& edges)\r\n{\r\n\troot->nonlinearEdges(edges);\r\n}\r\n\r\nunsigned int nzHess(EdgeSet& eSet,boost::unordered_set<Node*>& set1, boost::unordered_set<Node*>& set2)\r\n{\r\n\tlist<Edge>::iterator i = eSet.edges.begin();\r\n\tfor(;i!=eSet.edges.end();)\r\n\t{\r\n\t\tEdge e =*i;\r\n\t\tNode* a = e.a;\r\n\t\tNode* b = e.b;\r\n\t\tif((set1.find(a)!=set1.end() && set2.find(b)!=set2.end())\r\n\t\t\t||\r\n\t\t\t(set1.find(b)!=set1.end() && set2.find(a)!=set2.end()))\r\n\t\t{\r\n\t\t\t//e is connected between set1 and set2\r\n\t\t\ti++;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ti = eSet.edges.erase(i);\r\n\t\t}\r\n\t}\r\n\tunsigned int diag=eSet.numSelfEdges();\r\n\tunsigned int nzHess = (eSet.size())*2 - diag;\r\n\treturn nzHess;\r\n}\r\n\r\nunsigned int nzHess(EdgeSet& edges)\r\n{\r\n\tunsigned int diag=edges.numSelfEdges();\r\n\tunsigned int nzHess = (edges.size())*2 - diag;\r\n\treturn nzHess;\r\n}\r\n\r\nunsigned int numTotalNodes(Node* root)\r\n{\r\n\tunsigned int total = 0;\r\n\tboost::unordered_set<Node*> nodes;\r\n\troot->collect_vnodes(nodes,total);\r\n\treturn total;\r\n}\r\n\r\nstring tree_expr(Node* root)\r\n{\r\n\tostringstream oss;\r\n\toss<<\"visiting tree == \"<<endl;\r\n\tint level = 0;\r\n\troot->inorder_visit(level,oss);\r\n\treturn oss.str();\r\n}\r\n\r\nvoid print_tree(Node* root)\r\n{\r\n\tcout<<\"visiting tree == \"<<endl;\r\n\tint level = 0;\r\n\troot->inorder_visit(level,cout);\r\n}\r\n\r\nvoid autodiff_setup()\r\n{\r\n\tStack::diff = new Stack();\r\n\tStack::vals = new Stack();\r\n\tTape<unsigned int>::indexTape = new Tape<unsigned int>();\r\n\tTape<double>::valueTape = new Tape<double>();\r\n}\r\n\r\nvoid autodiff_cleanup()\r\n{\r\n\tdelete Stack::diff;\r\n\tdelete Stack::vals;\r\n\tdelete Tape<unsigned int>::indexTape;\r\n\tdelete Tape<double>::valueTape;\r\n}\r\n\r\n} //AutoDiff namespace end\r\n", "meta": {"hexsha": "b70d05c614c65b1212929b5fa58388260d6e7f72", "size": 8321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/yap/example/autodiff_library/autodiff.cpp", "max_stars_repo_name": "Talustus/boost_src", "max_stars_repo_head_hexsha": "ffe074de008f6e8c46ae1f431399cf932164287f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/yap/example/autodiff_library/autodiff.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/yap/example/autodiff_library/autodiff.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": 24.7648809524, "max_line_length": 104, "alphanum_fraction": 0.6135079918, "num_tokens": 2264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6123492549185234}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\n *    All rights reserved.\n *\n *    Redistribution and use in source and binary forms, with or without modification, are\n *    permitted provided that the following conditions are met:\n *      - Redistributions of source code must retain the above copyright notice, this list of\n *        conditions and the following disclaimer.\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\n *        conditions and the following disclaimer in the documentation and/or other materials\n *        provided with the distribution.\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\n *        may be used to endorse or promote products derived from this software without specific\n *        prior written permission.\n *\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *    Changelog\n *      YYMMDD    Author            Comment\n *      100910    J. Melman         First creation of code.\n *      110111    J. Melman         Adapted to the offical Tudat standards.\n *      110124    J. Melman         Further adapted to the offical Tudat standards.\n *      110201    J. Melman         Made the tests for obliquity and astronomical unit more\n *                                  accurate.\n *      120127    D. Dirkx          Moved to Tudat core.\n *      120127    K. Kumar          Transferred unit tests over to Boost unit test framework.\n *      120128    K. Kumar          Changed BOOST_CHECK to BOOST_CHECK_CLOSE_FRACTION for unit test\n *                                  comparisons.\n *      121205    K. Kumar          Updated license in file header.\n *      150417    D. Dirkx          Added tests for floating ints.\n *\n *    References\n *\n *    Notes\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <iostream>\n#include <iomanip>\n#include <limits>\n\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n// Define Boost test suite.\nBOOST_AUTO_TEST_SUITE( test_mathematical_constants )\n\n//! Check correct pi using PI = circumference / diameter:\nBOOST_AUTO_TEST_CASE( test_PI )\n{    \n    const double radius = 5.0;\n\n    // Circumference circle with radius 5, 32 digits precision, see\n    // http://www.wolframalpha.com/input/?i=Circumference+of+a+circle+with+radius+5\n    // http://www.wolframalpha.com/input/?i=N[10*PI,66]\n    double circumference = 31.4159265358979323846264338327950288419716939937510582097494459230; \n    BOOST_CHECK_CLOSE(  mathematical_constants::PI,\n                        circumference / ( 2.0 * radius ) ,\n                        std::numeric_limits< double >::epsilon( ) );\n}\n\n//! Check correct E using E Wolfram alpha as reference\nBOOST_AUTO_TEST_CASE( test_E )\n{    \n    // Numerical value from:\n    // http://www.wolframalpha.com/input/?i=e+72+digits\n    BOOST_CHECK_CLOSE( mathematical_constants::E,\n        2.71828182845904523536028747135266249775724709369995957496696762772407663, \n        std::numeric_limits< double >::epsilon( ) );\n}\n\n//! Check correct GOLDEN_RATIO using GOLDEN_RATIO Wolfram alpha as reference\nBOOST_AUTO_TEST_CASE( test_GOLDEN_RATIO )\n{    \n    // Numerical value from:\n    // http://www.wolframalpha.com/input/?i=golden+ratio+72+digits\n    BOOST_CHECK_CLOSE(  mathematical_constants::GOLDEN_RATIO,\n        1.618033988749894848204586834365638117720309179805762862135448622705260463, \n        std::numeric_limits< double >::epsilon( ) );\n}\n\n//! Check correct NAN using boost Floating Point Classification (fpclassify)\nBOOST_AUTO_TEST_CASE( test_NAN )\n{    \n    // Numerical value from:\n    // http://www.wolframalpha.com/input/?i=golden+ratio+72+digits\n    BOOST_CHECK( boost::math::isnan( TUDAT_NAN ) );\n}\n\nBOOST_AUTO_TEST_CASE( test_TemplatedValues )\n{\n    double one = 1.0;\n    long double longOne = 1.00000000000000000000L;\n\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingInteger< double >( 1 ),\n                        one, std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingInteger< long double >( 1 ),\n                        longOne, std::numeric_limits< long  double >::epsilon( ) );\n\n    BOOST_CHECK_SMALL(  mathematical_constants::getFloatingInteger< double >( 0 ),\n                        std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_SMALL(  mathematical_constants::getFloatingInteger< long double >( 0 ),\n                        std::numeric_limits< long  double >::epsilon( ) );\n\n    double two = 2.0;\n    long double longTwo = 2.00000000000000000000L;\n\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingInteger< double >( 2 ),\n                        two, std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingInteger< long double >( 2 ),\n                        longTwo, std::numeric_limits< long  double >::epsilon( ) );\n\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingFraction< double >( 1, 2 ),\n                        mathematical_constants::getFloatingInteger< double >( 1 ) /\n                        mathematical_constants::getFloatingInteger< double >( 2 ),\n                        std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE(  mathematical_constants::getFloatingFraction< long double >( 1, 2 ),\n                        mathematical_constants::getFloatingInteger< long double >( 1 ) /\n                        mathematical_constants::getFloatingInteger< long double >( 2 )\n                        , std::numeric_limits< long double >::epsilon( ) );\n\n\n    BOOST_CHECK_CLOSE(  mathematical_constants::getPi< double >( ),\n                        mathematical_constants::PI, std::numeric_limits< double >::epsilon( ) );\n    BOOST_CHECK_CLOSE(  mathematical_constants::getPi< long double >( ),\n                        mathematical_constants::LONG_PI, std::numeric_limits< long  double >::epsilon( ) );\n\n}\n\n// Close Boost test suite.\nBOOST_AUTO_TEST_SUITE_END( ) // End test_mathematical_constants\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "7b0b9518f125c98f79b78afa8f17981e6630d4cf", "size": 6994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/UnitTests/unitTestMathematicalConstants.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/BasicMathematics/UnitTests/unitTestMathematicalConstants.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/BasicMathematics/UnitTests/unitTestMathematicalConstants.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 46.0131578947, "max_line_length": 107, "alphanum_fraction": 0.6757220475, "num_tokens": 1582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6123488044726227}}
{"text": "/*\n   Copyright (C) 2015-2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n// Critical temperature of hexagonal lattice Ising model\n\n#include <iomanip>\n#include <iostream>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include \"ising/mp_wrapper.hpp\"\n#include \"options.hpp\"\n#include \"hexagonal.hpp\"\n\ntemplate<class T>\nvoid calc(const std::string& Ja_in, const std::string& Jb_in, const std::string& Jc_in) {\n  typedef T real_t;\n  real_t Ja = convert<real_t>(Ja_in);\n  real_t Jb = convert<real_t>(Jb_in);\n  real_t Jc = convert<real_t>(Jc_in);\n  auto tc = ising::tc::hexagonal(Ja, Jb, Jc);\n  std::cout << std::scientific << std::setprecision(std::numeric_limits<real_t>::digits10)\n            << \"# lattice: hexagonal\\n\"\n            << \"# precision: \" << std::numeric_limits<real_t>::digits10 << std::endl\n            << \"# Ja Jb Jc Tc 1/Tc\" << std::endl\n            << Ja << ' ' << Jb << ' ' << Jc << ' ' << tc << ' ' << (1 / tc) << std::endl;\n}\n\nint main(int argc, char **argv) {\n  namespace mp = boost::multiprecision;\n  options3 opt(argc, argv);\n  if (!opt.valid) return 127;\n  if (opt.prec <= std::numeric_limits<float>::digits10) {\n    calc<float>(opt.Ja, opt.Jb, opt.Jc);\n  } else if (opt.prec <= std::numeric_limits<double>::digits10) {\n    calc<double>(opt.Ja, opt.Jb, opt.Jc);\n  } else if (opt.prec <= std::numeric_limits<mp_wrapper<mp::cpp_dec_float_50>>::digits10) {\n    calc<mp_wrapper<mp::cpp_dec_float_50>>(opt.Ja, opt.Jb, opt.Jc);\n  } else if (opt.prec <= std::numeric_limits<mp_wrapper<mp::cpp_dec_float_100>>::digits10) {\n    calc<mp_wrapper<mp::cpp_dec_float_100>>(opt.Ja, opt.Jb, opt.Jc);\n  } else {\n    std::cerr << \"Error: Required precision is too high\\n\"; return 127;\n  }\n}\n", "meta": {"hexsha": "febcde0398364c0578dc84067d06da0c739c287c", "size": 2254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ising/tc/hexagonal.cpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "ising/tc/hexagonal.cpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "ising/tc/hexagonal.cpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.25, "max_line_length": 92, "alphanum_fraction": 0.6716947649, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7577943767446201, "lm_q1q2_score": 0.6123487974673004}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include <gtest/gtest.h>\n#include <mrpt/math/CMatrixDynamic.h>\n#include <Eigen/Dense>\n\nTEST(CMatrixDynamic, GetSetEigen)\n{\n\t{\n\t\tauto M = mrpt::math::CMatrixDynamic<double>::Identity(3);\n\t\tauto em = M.asEigen();\n\t\tem.setIdentity();\n\t\tfor (int i = 0; i < 3; i++) EXPECT_EQ(M(i, i), 1.0);\n\t}\n\t{\n\t\tmrpt::math::CMatrixDynamic<double> M(3, 3);\n\t\tauto em = M.asEigen();\n\t\tfor (int i = 0; i < 3; i++)\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tconst auto n = ((i + 1) * 3) + (j * 1001);\n\t\t\t\tem(i, j) = n;\n\t\t\t\tEXPECT_NEAR(M(i, j), em(i, j), 1e-9)\n\t\t\t\t\t<< \"(i,j)=(\" << i << \",\" << j << \")\\n\";\n\t\t\t}\n\t}\n}\nTEST(CMatrixDynamic, asString)\n{\n\tauto M = mrpt::math::CMatrixDynamic<double>::Identity(2);\n\tM.setIdentity();\n\tEXPECT_EQ(std::string(\"1 0\\n0 1\"), M.asString());\n}\n\nTEST(CMatrixDynamic, CtorFromArray)\n{\n\tconst double dat_R[] = {1., 2., 3., 4., 5., 6., 7., 8., 9.};\n\tmrpt::math::CMatrixDouble R(3, 3, dat_R);\n\tfor (int r = 0; r < 3; r++)\n\t{\n\t\tfor (int c = 0; c < 3; c++)\n\t\t{\n\t\t\tEXPECT_EQ(dat_R[c + r * 3], R(r, c))\n\t\t\t\t<< \"(r,c)=(\" << r << \",\" << c << \")\\n\";\n\t\t}\n\t}\n}\n\n// Added to run with valgrind to error checking.\nTEST(CMatrixDynamic, Resizes)\n{\n\tusing mrpt::math::CMatrixDouble;\n\t{\n\t\tCMatrixDouble M(0, 0);\n\t\tM.resize(0, 0);\n\t\tM.resize(1, 1);\n\t\tM.resize(10, 10);\n\t\tM.resize(15, 10);\n\t\tM.resize(15, 12);\n\t\tM.resize(5, 12);\n\t\tM.resize(3, 2);\n\t}\n\t{\n\t\tCMatrixDouble M(40, 50);\n\t\tM.resize(3, 3);\n\t}\n}\n", "meta": {"hexsha": "ed759b1350a3c6e61546e7dfd5fd8d4c413c78f6", "size": 2017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/src/CMatrixDynamic_unittest.cpp", "max_stars_repo_name": "gao-ouyang/mrpt", "max_stars_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-05T05:20:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-05T05:20:51.000Z", "max_issues_repo_path": "libs/math/src/CMatrixDynamic_unittest.cpp", "max_issues_repo_name": "gao-ouyang/mrpt", "max_issues_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/src/CMatrixDynamic_unittest.cpp", "max_forks_repo_name": "gao-ouyang/mrpt", "max_forks_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_forks_repo_licenses": ["BSD-3-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.8933333333, "max_line_length": 80, "alphanum_fraction": 0.4665344571, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6123487904619781}}
{"text": "//\r\n// $Id: Parabola.cpp 2051 2010-06-15 18:39:13Z chambm $\r\n//\r\n//\r\n// Original author: Darren Kessner <darren@proteowizard.org>\r\n//\r\n// Copyright 2006 Louis Warschaw Prostate Cancer Center\r\n//   Cedars Sinai Medical Center, Los Angeles, California  90048\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \r\n// you may not use this file except in compliance with the License. \r\n// You may obtain a copy of the License at \r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software \r\n// distributed under the License is distributed on an \"AS IS\" BASIS, \r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \r\n// See the License for the specific language governing permissions and \r\n// limitations under the License.\r\n//\r\n\r\n\r\n#define PWIZ_SOURCE\r\n\r\n#include \"Parabola.hpp\"\r\n#include \"pwiz/utility/misc/Std.hpp\"\r\n\r\n\r\n#ifndef NDEBUG\r\n#define NDEBUG\r\n#endif // NDEBUG\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <boost/numeric/ublas/lu.hpp>\r\n#include <boost/numeric/ublas/triangular.hpp>\r\n#include <boost/numeric/ublas/vector_proxy.hpp>\r\nnamespace ublas = boost::numeric::ublas;\r\n\r\n\r\n#if BOOST_UBLAS_TYPE_CHECK\r\ngoo; // need -DNDEBUG in makefile!\r\n#endif\r\n\r\n\r\nnamespace pwiz {\r\nnamespace math {\r\n\r\n\r\nPWIZ_API_DECL Parabola::Parabola(double a, double b, double c)\r\n:   a_(3)\r\n{\r\n    a_[0] = a;\r\n    a_[1] = b;\r\n    a_[2] = c;\r\n}\r\n\r\n\r\nPWIZ_API_DECL Parabola::Parabola(vector<double> a)\r\n:   a_(a)\r\n{\r\n    if (a_.size() != 3)\r\n        throw logic_error(\"[Parabola::Parabola()] 3 coefficients required.\");\r\n}\r\n\r\n\r\nnamespace {\r\n\r\n\r\nvoid solve(ublas::matrix<double>& A, ublas::vector<double>& a)\r\n{\r\n    ublas::permutation_matrix<size_t> pm(3);\r\n    int singular = lu_factorize(A, pm);\r\n    if (singular)\r\n        throw runtime_error(\"[Parabola.cpp::solve()] Matrix is singular.\");\r\n\r\n    lu_substitute(A, pm, a); // may cause assertion without NDEBUG defined for ublas, probably due to roundoff errors\r\n}\r\n\r\n\r\nvoid fitExact(const vector< pair<double,double> >& samples, vector<double>& coefficients)\r\n{\r\n    if (samples.size() != 3)\r\n        throw logic_error(\"[Parabola.cpp::fitExact()] Exactly 3 samples required.\\n\");\r\n\r\n    // fit parabola to the 3 samples (xi,yi):\r\n    //\r\n    //   ( x1^2  x1  1 )( a[0] )   ( y1 )\r\n    //   ( x2^2  x2  1 )( a[1] ) = ( y2 )\r\n    //   ( x3^2  x3  1 )( a[2] )   ( y3 )\r\n\r\n    ublas::matrix<double> A(3,3);\r\n    ublas::vector<double> a(3);\r\n\r\n    for (int i=0; i<3; i++)\r\n    {\r\n        double x = samples[i].first;\r\n        double y = samples[i].second;\r\n        A(i,0) = x*x;\r\n        A(i,1) = x;\r\n        A(i,2) = 1;\r\n        a(i) = y;\r\n    }\r\n\r\n    solve(A, a);\r\n    copy(a.begin(), a.end(), coefficients.begin());\r\n}\r\n\r\n\r\nvoid fitWeightedLeastSquares(const vector< pair<double,double> >& samples,\r\n                             const vector<double>& weights,\r\n                             vector<double>& coefficients)\r\n{\r\n    if (samples.size() != weights.size())\r\n        throw logic_error(\"[Parabola.cpp::fitWeightedLeastSquares] Wrong weight count.\");\r\n\r\n    // given samples {(xi,yi)} and weights {wi}\r\n    // minimize e(a) = sum[wi(p(a,xi)-yi)^2],\r\n    // where p(a,xi) = a[0](xi)^2 + a[1](xi) + a[0]c\r\n    //\r\n    // de/da == 0 =>\r\n    //   ( sum_wx4  sum_wx3  sum_wx2 )( a[0] )   ( sum_wyx2 )\r\n    //   ( sum_wx3  sum_wx2  sum_wx1 )( a[1] ) = ( sum_wyx1 )\r\n    //   ( sum_wx2  sum_wx1  sum_wx0 )( a[2] )   ( sum_wyx0 )\r\n    //\r\n    // where:\r\n    //   sum_wxn means sum[wi*(xi)^n]\r\n    //   sum_wyxn means sum[wi*yi*(xi)^n]\r\n\r\n    double sum_wx4 = 0;\r\n    double sum_wx3 = 0;\r\n    double sum_wx2 = 0;\r\n    double sum_wx1 = 0;\r\n    double sum_wx0 = 0;\r\n    double sum_wyx2 = 0;\r\n    double sum_wyx1 = 0;\r\n    double sum_wyx0 = 0;\r\n\r\n    for (unsigned int i=0; i<samples.size(); i++)\r\n    {\r\n        double x = samples[i].first;\r\n        double y = samples[i].second;\r\n        double w = weights[i];\r\n\r\n        sum_wx4 += w*pow(x,4);\r\n        sum_wx3 += w*pow(x,3);\r\n        sum_wx2 += w*x*x;\r\n        sum_wx1 += w*x;\r\n        sum_wx0 += w;\r\n        sum_wyx2 += w*y*x*x;\r\n        sum_wyx1 += w*y*x;\r\n        sum_wyx0 += w*y;\r\n    }\r\n\r\n    ublas::matrix<double> A(3,3);\r\n    ublas::vector<double> a(3);\r\n\r\n    A(0,0) = sum_wx4;\r\n    A(1,0) = A(0,1) = sum_wx3;\r\n    A(2,0) = A(1,1) = A(0,2) = sum_wx2;\r\n    A(1,2) = A(2,1) = sum_wx1;\r\n    A(2,2) = sum_wx0;\r\n\r\n    a(0) = sum_wyx2;\r\n    a(1) = sum_wyx1;\r\n    a(2) = sum_wyx0;\r\n\r\n    solve(A, a);\r\n    copy(a.begin(), a.end(), coefficients.begin());\r\n}\r\n\r\n} // namespace\r\n\r\n\r\nPWIZ_API_DECL Parabola::Parabola(const vector< pair<double,double> >& samples)\r\n:   a_(3)\r\n{\r\n    if (samples.size() < 3)\r\n        throw logic_error(\"[Parabola::Parabola()] At least 3 samples required.\");\r\n\r\n    if (samples.size() == 3)\r\n        fitExact(samples, a_);\r\n    else\r\n        fitWeightedLeastSquares(samples, vector<double>(samples.size(),1), a_);\r\n}\r\n\r\n\r\n// construct by weighted least squares\r\nPWIZ_API_DECL\r\nParabola::Parabola(const std::vector< std::pair<double,double> >& samples,\r\n                   const std::vector<double>& weights)\r\n:   a_(3)\r\n{\r\n    fitWeightedLeastSquares(samples, weights, a_);\r\n}\r\n\r\n\r\nPWIZ_API_DECL ostream& operator<<(ostream& os, const Parabola& p)\r\n{\r\n    vector<double> a = p.coefficients();\r\n    os << \"[Parabola (\" << a[0] << \", \" << a[1] << \", \" << a[2] << \")]\";\r\n    return os;\r\n}\r\n\r\n\r\n} // namespace math \r\n} // namespace pwiz\r\n\r\n", "meta": {"hexsha": "178cd91ee748068b88aea2bcec2596010930dbee", "size": 5547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/math/Parabola.cpp", "max_stars_repo_name": "edyp-lab/pwiz-mzdb", "max_stars_repo_head_hexsha": "d13ce17f4061596c7e3daf9cf5671167b5996831", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T08:33:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T06:14:54.000Z", "max_issues_repo_path": "pwiz/utility/math/Parabola.cpp", "max_issues_repo_name": "shze/pwizard-deb", "max_issues_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "pwiz/utility/math/Parabola.cpp", "max_forks_repo_name": "shze/pwizard-deb", "max_forks_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-02-03T09:41:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T18:42:36.000Z", "avg_line_length": 26.4142857143, "max_line_length": 118, "alphanum_fraction": 0.5743645214, "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6123487816217555}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nArrayXXi A = ArrayXXi::Random(4,4).abs();\ncout << \"Here is the initial matrix A:\\n\" << A << \"\\n\";\nfor(auto row : A.rowwise())\n  std::sort(row.begin(), row.end());\ncout << \"Here is the sorted matrix A:\\n\" << A << \"\\n\";\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "4f676ec71a9cab135adc3d38d06021b31dd35c8e", "size": 751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_Tutorial_std_sort_rows_cxx11.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_Tutorial_std_sort_rows_cxx11.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_Tutorial_std_sort_rows_cxx11.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8965517241, "max_line_length": 224, "alphanum_fraction": 0.6631158455, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.6123316437862434}}
{"text": "#include \"../Galerkin.hpp\"\n#include <iostream>\n\nusing namespace Galerkin;\nusing namespace Elements;\nusing namespace Rationals;\nusing namespace Polynomials;\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n\nconstexpr std::array<double, 5> scalings = {0.5, 1, 0.5, 0.25, 0.25};\n\nconstexpr std::array<double, 5> offsets = { 0.5, 2, 3.5, 4.25, 4.75 };\n\nconstexpr std::array<C1IntervalElement<double>, 5> elements = {\n    C1IntervalElement(scalings[0], offsets[0]), C1IntervalElement(scalings[1], offsets[1]),\n    C1IntervalElement(scalings[2], offsets[2]), C1IntervalElement(scalings[3], offsets[3]),\n    C1IntervalElement(scalings[4], offsets[4])};\n\nconstexpr std::array<std::array<int, 4>, 5> dof_numbers = {\n    std::array{0, 1, 2, 3}, std::array{3, 2, 4, 5}, std::array{5, 4, 6, 7}, std::array{7, 6, 8, 9},\n    std::array{9, 8, 10, 11}};\n\nconstexpr std::size_t num_dofs = 12;\n\nconstexpr auto el_stiffness(const C1IntervalElement<double> &el)\n{\n    auto form = [&](auto f, auto g) { return el.template partial<0>(f) * el.template partial<0>(g); };\n\n    return el.form_matrix(form);\n}\n\nEigen::MatrixXd stiffness_matrix()\n{\n    Eigen::MatrixXd K = Eigen::MatrixXd::Zero(num_dofs, num_dofs);\n    for (int i = 0; i < 5; ++i)\n    {\n        auto Ke = el_stiffness(elements[i]);\n        for (int j = 0; j < 4; ++j)\n        {\n            for (int k = 0; k < 4; ++k)\n            {\n                K(dof_numbers[i][j], dof_numbers[i][k]) += Ke(j, k);\n            }\n        }\n    }\n    return K;\n}\n\nstatic_assert(elements[0].coordinate_map()(std::tuple(-1))[0] == 0);\nstatic_assert(elements[0].coordinate_map()(std::tuple(1))[0] == 1);\n\nconstexpr auto u = make_poly(\n    std::tuple(rational<3, 8>, rational<-47, 12>, rational<97, 8>, -rational<115, 12>),\n    PowersList<Powers<4>, Powers<3>, Powers<2>, Powers<1>>{});\n\nconstexpr auto f = u.template partial<0>().template partial<0>();\n\nEigen::VectorXd forcing_vector()\n{\n    Eigen::VectorXd F = Eigen::VectorXd::Zero(num_dofs);\n    for (int i = 0; i < 5; ++i)\n    {\n        const auto &el = elements[i];\n        for (int j = 0; j < 4; ++j)\n        {\n            auto rule = el.coordinate_map().template quadrature_rule<6>();\n            double detj = el.coordinate_map().detJ()();\n            auto g = [&](auto xi) {\n                return detj * f(el.coordinate_map()(std::tuple(xi))) * el.basis()[j](xi);\n            };\n            F[dof_numbers[i][j]] -= Quadrature::integrate(g, rule);\n        }\n    }\n\n    return F;\n}\n\nvoid print_polynomial(const Polynomial<double, Powers<0>, Powers<1>, Powers<2>, Powers<3>> &p)\n{\n    printf(\"%f * x^3 + %f * x^2 + %f * x + %f\", p.coeffs()[3], p.coeffs()[2], p.coeffs()[1], p.coeffs()[0]);\n}\n\nvoid eliminate_dirichlet_bc(Eigen::MatrixXd &K, Eigen::VectorXd &F, int which)\n{\n    for (int i = 0; i < K.rows(); ++i)\n    {\n        K(i, which) = 0;\n        K(which, i) = 0;\n    }\n    K(which, which) = 1.0;\n    F(which) = 0.0;\n}\n\nint main()\n{\n    auto K = stiffness_matrix();\n    auto F = forcing_vector();\n    eliminate_dirichlet_bc(K, F, 1);\n    eliminate_dirichlet_bc(K, F, num_dofs - 2);\n    std::cout << \"K = \" << K << '\\n';\n    std::cout << \"F = \" << F << '\\n';\n    Eigen::VectorXd U = K.ldlt().solve(F);\n\n    for (int i = 0; i < 5; ++i)\n    {\n        const auto &el = elements[i];\n        printf(\"Solution on element %d: \", i);\n        auto p = 0.0 * el.basis()[0];\n        for (int j = 0; j < 4; ++j)\n        {\n            p += el.basis()[j] * U[dof_numbers[i][j]];\n        }\n        print_polynomial(p);\n        printf(\"\\n\");\n    }\n\n    return 0;\n}", "meta": {"hexsha": "3e0399c6ea971febe379d6e3ac9f835b519f176d", "size": 3530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/c1_interval_example.cpp", "max_stars_repo_name": "slmcbane/Galerkin", "max_stars_repo_head_hexsha": "76d47c9822f2930d8126eb5784f411a7852d6ed4", "max_stars_repo_licenses": ["MIT"], "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/c1_interval_example.cpp", "max_issues_repo_name": "slmcbane/Galerkin", "max_issues_repo_head_hexsha": "76d47c9822f2930d8126eb5784f411a7852d6ed4", "max_issues_repo_licenses": ["MIT"], "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/c1_interval_example.cpp", "max_forks_repo_name": "slmcbane/Galerkin", "max_forks_repo_head_hexsha": "76d47c9822f2930d8126eb5784f411a7852d6ed4", "max_forks_repo_licenses": ["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.4166666667, "max_line_length": 108, "alphanum_fraction": 0.5586402266, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6123227311186963}}
{"text": "//////////////////////////////////////////////////////////////////////////////////\n// statistics::survival::model::models::exponential::detail::log_likelihood.hpp //\n//                                                                              //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                   //\n//  Software License, Version 1.0. (See accompanying file                       //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)            //\n//////////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_SURVIVAL_MODEL_MODELS_EXPONENTIAL_DETAIL_LOG_LIKELIHOOD_HPP_ER_2009\n#define BOOST_STATISTICS_SURVIVAL_MODEL_MODELS_EXPONENTIAL_DETAIL_LOG_LIKELIHOOD_HPP_ER_2009\n#include <cmath>\n#include <stdexcept>\n#include <boost/format.hpp>\n#include <boost/statistics/survival/data/data/event.hpp>\n\nnamespace boost{\nnamespace statistics{\n\nnamespace survival{\nnamespace model{\nnamespace exponential{\nnamespace detail{                \n                \n    template<typename T>\n    T\n    log_likelihood(\n        const T& log_rate,\n        const data::event<T>& e\n    ){\n        static const char* msg = \n            \"survival::model::exponential::log_unnromalized_pdf(%1%,%2%)\";\n        typedef T value_type;\n        value_type result = exp(log_rate);\n        result *= (- e.time());\n        try{\n            if( boost::math::isinf(result) ){\n                throw std::runtime_error(\"isinf(result)\");\n            }\n            if( boost::math::isnan(result) ){\n                throw std::runtime_error(\"isnan(result)\");\n            }\n        }catch(std::exception ex){\n            std::string str = msg;\n            str += ex.what();\n            format f(str); f % log_rate % e;\n            throw std::runtime_error(\n                f.str()\n            );\n        }\n        if(e.failure()){\n            result += log_rate;\n        }\n        return result;\n    }\n            \n}// detail\n}// exponential\n}// model\n}// survival\n}// statistics\n}// boost\n\n#endif ", "meta": {"hexsha": "734ac08de4fac0092ee561a37f9f5119ec1806e3", "size": 2048, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "survival_model copy/boost/statistics/survival/model/models/exponential/detail/log_likelihood.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "survival_model copy/boost/statistics/survival/model/models/exponential/detail/log_likelihood.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "survival_model copy/boost/statistics/survival/model/models/exponential/detail/log_likelihood.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0322580645, "max_line_length": 92, "alphanum_fraction": 0.5112304688, "num_tokens": 412, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6123227241332154}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n  {\n  mat A(4, 5, fill::randu);\n  mat B(4, 5, fill::randu);\n  \n  cout << A*B.t() << endl;\n  \n  return 0;\n  }\n", "meta": {"hexsha": "1d0e789b02ba4296bdea421bf5c2a361ace9cd5a", "size": 206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "robotica/prg5.cpp", "max_stars_repo_name": "Jacobprojects/UACJ-Robotica", "max_stars_repo_head_hexsha": "62ef2adf02e615b8b1733045148401c98e28a663", "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": "robotica/prg5.cpp", "max_issues_repo_name": "Jacobprojects/UACJ-Robotica", "max_issues_repo_head_hexsha": "62ef2adf02e615b8b1733045148401c98e28a663", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "robotica/prg5.cpp", "max_forks_repo_name": "Jacobprojects/UACJ-Robotica", "max_forks_repo_head_hexsha": "62ef2adf02e615b8b1733045148401c98e28a663", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 12.875, "max_line_length": 27, "alphanum_fraction": 0.5873786408, "num_tokens": 70, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.612322710059849}}
{"text": "#pragma once\n#include <cmath>\n#include <iostream>\n#include <exception>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\nusing Eigen::ArrayXd;\nusing Eigen::MatrixXcd;\nusing Eigen::MatrixXd;\nusing Eigen::Vector3d;\n\nnamespace CPU\n{\n    struct closest_matrix_params\n    {\n        unsigned int dim;\n        unsigned int np;\n        unsigned int nm;\n        const MatrixXd &p;\n        const MatrixXd &m;\n    };\n\n    struct err_compute_params\n    {\n        unsigned int np;\n        MatrixXd &p;\n        double s;\n        const MatrixXd &r;\n        const MatrixXd &t;\n        const MatrixXd &Y;\n    };\n\n    struct err_compute_alignment_params\n    {\n        unsigned int np;\n        const MatrixXd &p;\n        double s;\n        const MatrixXd &r;\n        const MatrixXd &t;\n        const MatrixXd &y;\n    };\n\n    class ICP\n    {\n    public:\n        ICP(MatrixXd m_, MatrixXd p_, int max_iter_)\n            : m{m_},\n              p{p_},\n              new_p{p_},\n              np{(unsigned int)p_.cols()},\n              nm{(unsigned int)m_.cols()},\n              dim{3},\n              max_iter{max_iter_}\n        {\n            this->s = 1.;\n            this->r = MatrixXd::Identity(m_.rows(), m_.rows());\n            this->t = MatrixXd::Zero(m_.rows(), 1);\n        }\n\n        ~ICP()\n        {\n        }\n\n        struct closest_matrix_params get_closest_matrix_params()\n        {\n            struct closest_matrix_params cmp\n                {\n                    dim, np, nm, new_p, m\n                };\n            return cmp;\n        }\n\n        struct err_compute_params get_err_compute_params(Eigen::MatrixXd &Y)\n        {\n            struct err_compute_params ecp\n                {\n                    np, new_p, s, r, t, Y\n                };\n            return ecp;\n        }\n\n        struct err_compute_alignment_params get_err_compute_alignment_params(Eigen::MatrixXd &Y)\n        {\n            struct err_compute_alignment_params ecap\n                {\n                    np, new_p, s, r, t, Y\n                };\n            return ecap;\n        }\n\n        void find_corresponding();\n        void alignement_check();\n        double find_alignment(MatrixXd y);\n\n    public:\n        MatrixXd new_p;\n\n    private:\n        double s;\n        MatrixXd t;\n        MatrixXd r;\n\n        MatrixXd m;\n        MatrixXd p;\n\n        unsigned int np;\n        unsigned int nm;\n        unsigned int dim;\n\n        int max_iter;\n        const double threshold = 1e-5;\n    };\n\n    MatrixXd closest_matrix(struct closest_matrix_params pa);\n    double err_compute(struct err_compute_params pa);\n    double err_compute_alignment(struct err_compute_alignment_params pa);\n    int max_element_index(Eigen::EigenSolver<Eigen::MatrixXd>::EigenvalueType &eigen_value);\n\n} // namespace CPU\n", "meta": {"hexsha": "1b4ee85070437fad52c378c9b5b6628779721db3", "size": 2760, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/cpu.hh", "max_stars_repo_name": "yassram/iterative-closest-point", "max_stars_repo_head_hexsha": "11ed48b5a3885c20ea99f4265c9c8bae2752ef86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-04T08:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T16:36:13.000Z", "max_issues_repo_path": "src/cpu.hh", "max_issues_repo_name": "yassram/iterative-closest-point", "max_issues_repo_head_hexsha": "11ed48b5a3885c20ea99f4265c9c8bae2752ef86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpu.hh", "max_forks_repo_name": "yassram/iterative-closest-point", "max_forks_repo_head_hexsha": "11ed48b5a3885c20ea99f4265c9c8bae2752ef86", "max_forks_repo_licenses": ["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.6229508197, "max_line_length": 96, "alphanum_fraction": 0.5326086957, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138366, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6122964420983702}}
{"text": "//\n// Created by erik on 10/28/16.\n//\n\n#include \"physics/units.h\"\n#include <boost/test/unit_test.hpp>\n#include <type_traits>\n#include <sstream>\n\nusing namespace spatacs;\nnamespace dim = physics::dimensions;\n\n// check dimension multiplication\nstatic_assert( std::is_same<dim::mul_t<dim::dimless_t, dim::length_t>, dim::length_t>::value,  \"multiplication of dimensionless and length must yield length\");\nstatic_assert( std::is_same<dim::mul_t<dim::dimless_t, dim::energy_t>, dim::energy_t>::value,  \"multiplication of dimensionless and energy must yield energy\");\n\n\nstatic_assert( std::is_same<dim::mul_t<dim::acceleration_t, dim::mass_t>, dim::force_t>::value,  \"error in unit multiplication\");\nstatic_assert( std::is_same<dim::mul_t<dim::force_t, dim::length_t>, dim::energy_t>::value,  \"error in unit multiplication\");\nstatic_assert( std::is_same<dim::div_t<dim::length_t, dim::time_t>, dim::velocity_t>::value,  \"error in unit division\");\nstatic_assert( std::is_same<dim::div_t<dim::velocity_t, dim::time_t>, dim::acceleration_t>::value,  \"error in unit division\");\nstatic_assert( std::is_same<dim::pow_t<dim::area_t, 1, 2>, dim::length_t>::value,  \"error in unit division\");\n\nstatic_assert( std::ratio_equal<dim::energy_t::length, std::ratio<2, 1>>(), \"unexpected meters in energy\");\nstatic_assert( std::ratio_equal<dim::energy_t::time,   std::ratio<-2, 1>>(), \"unexpected meters in energy\");\nstatic_assert( std::ratio_equal<dim::energy_t::mass, std::ratio<1, 1>>(), \"unexpected meters in energy\");\n\nstatic_assert( dim::dimensions_equal<dim::acceleration_t, dim::acceleration_t>(), \"equality comparison is broken\" );\n\n#define STREAM_OUT_TEST(value, result)  \\\n{                                   \\\n    std::stringstream stream;       \\\n    stream << value;                \\\n    BOOST_CHECK_EQUAL(stream.str(), result); \\\n}\n\n#define STREAM_IN_TEST(value, input)  \\\n{                                   \\\n    std::stringstream stream;       \\\n    stream << input;                \\\n    decltype(value) tmp;            \\\n    stream >> tmp;                  \\\n    BOOST_CHECK(!stream.fail());     \\\n    BOOST_CHECK_EQUAL(tmp, value);  \\\n}\n\nBOOST_AUTO_TEST_SUITE(Units)\n    BOOST_AUTO_TEST_CASE(ratio_stream)\n    {\n        STREAM_OUT_TEST((std::ratio<1, 3>{}), \"1/3\");\n        STREAM_OUT_TEST((std::ratio<3, 1>{}), \"3\");\n    }\n\n    BOOST_AUTO_TEST_CASE(dimension_stream)\n    {\n        STREAM_OUT_TEST(dim::length_t{}, \"m\");\n        STREAM_OUT_TEST(dim::area_t{},   \"m^2\");\n        STREAM_OUT_TEST(dim::energy_t{}, \"kgm^2s^-2\");\n    }\n\n    BOOST_AUTO_TEST_CASE(units_stream)\n    {\n        STREAM_OUT_TEST(500.0_m, \"500m\");\n        STREAM_OUT_TEST(150.0_kg, \"150kg\");\n        STREAM_OUT_TEST(500.0_kJ, \"500kJ\");\n        STREAM_OUT_TEST(3000.0_kg, \"3t\");\n        STREAM_OUT_TEST(kilonewtons(5.5), \"5.5kN\");\n        STREAM_OUT_TEST(5.0_km*5.0_km, \"25km^2\");\n    }\n    \n    BOOST_AUTO_TEST_CASE(units_input)\n    {\n        STREAM_IN_TEST(500.0_m, \"500m\");\n        STREAM_IN_TEST(150.0_kg, \"150kg\");\n        STREAM_IN_TEST(500.0_kJ, \"500kJ\");\n        STREAM_IN_TEST(3000.0_kg, \"3t\");\n        STREAM_IN_TEST(kilonewtons(5.5), \"5.5kN\");\n        STREAM_IN_TEST(5.0_km*5.0_km, \"25km^2\");\n    }\nBOOST_AUTO_TEST_SUITE_END()", "meta": {"hexsha": "6da0c1e9edd05092fbc836f74ef49a732caa4769", "size": 3206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units_test.cpp", "max_stars_repo_name": "ngc92/SpaTacS", "max_stars_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units_test.cpp", "max_issues_repo_name": "ngc92/SpaTacS", "max_issues_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units_test.cpp", "max_forks_repo_name": "ngc92/SpaTacS", "max_forks_repo_head_hexsha": "c8689b4262171f7169c5600c5251c307915a961c", "max_forks_repo_licenses": ["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.075, "max_line_length": 159, "alphanum_fraction": 0.6459762944, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6122802062307998}}
{"text": "#include \"cmath\"\n#include \"softmax.h\"\n#include <ctime>\n#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <fstream>\n\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::VectorXi;\nusing Eigen::MatrixXi;\nusing Eigen::ArrayXXd;\n\nnamespace lrprox {\n\n  SOFTMAX::SOFTMAX(int num_dims, int num_classes)\n    : num_dims_(num_dims), num_classes_(num_classes) {\n    initWeight_();\n  }\n\n  double SOFTMAX::cost(const MatrixXd &X, const MatrixXi &Y) {\n    // X: n * num_dims, y: n * num_classes\n    // minimize negative log prob\n    ArrayXXd term1 = (X * weight_).array();\n    // do not take average\n    return ((logsumexp(term1.matrix()).replicate(1, term1.cols()).array() - term1) * Y.cast<double>().array()).sum();\n  }\n\n  MatrixXd SOFTMAX::grad(const MatrixXd &X, const MatrixXi &Y) {\n    MatrixXd term1 = (X * weight_).array().exp().matrix();\n    ArrayXXd P = term1.array() / term1.rowwise().sum().replicate(1, term1.cols()).array();\n\n    return X.transpose() * (P - Y.cast<double>().array()).matrix();\n//    return weight_;\n  }\n//\n//  VectorXi predict(const MatrixXd &X);\n//\n  const MatrixXd& SOFTMAX::getWeight() {\n    return weight_;\n  }\n  void SOFTMAX::updateWeight(const std::vector<double>& weight) {\n    for (int i = 0; i < weight_.cols(); i++) {\n      weight_.col(i) = VectorXd::Map(&weight[i*weight_.rows()], weight_.rows());\n    }\n  }\n  void SOFTMAX::updateWeight(const MatrixXd& weight) {\n    weight_ = weight;\n  }\n\n  void SOFTMAX::outputWeight(std::vector<double>& weight) {\n    weight.resize(weight_.rows() * weight_.cols());\n    for (int i = 0; i < weight_.cols(); i++) {\n       VectorXd::Map(&weight[i*weight_.rows()], weight_.rows()) = weight_.col(i);\n    }\n  }\n\n  MatrixXi SOFTMAX::onehot_encoder(const VectorXi &y) {\n    std::vector<int> labels;\n    std::map<int, int> label_to_idx;\n    for (int i = 0; i < y.size(); i++) {\n      if (label_to_idx.count(y(i)) == 0) {\n        label_to_idx[y(i)] = 1;\n        labels.push_back(y(i));\n      }\n    }\n    std::sort(labels.begin(), labels.end());\n    for (int i = 0; i < labels.size(); i++) {\n      label_to_idx[labels[i]] = i;\n    }\n    MatrixXi Y = MatrixXi::Zero(y.size(), labels.size());\n    for (int i = 0; i < y.size(); i++) {\n      Y(i, label_to_idx[y(i)]) = 1;\n    }\n    return Y;\n  }\n\n//\n//  bool saveModel(std::string &filename);\n\n  void SOFTMAX::initWeight_() {\n//    weight_ = MatrixXd::Random(num_dims_, num_classes_);\n    weight_ = MatrixXd::Ones(num_dims_, num_classes_);\n  }\n\n  MatrixXd SOFTMAX::logsumexp(const MatrixXd &X) {\n    MatrixXd max_X = X.rowwise().maxCoeff();\n    return max_X + (X - max_X.replicate(1, X.cols())).array().exp().matrix().rowwise().sum().array().log().matrix();\n  }\n\n\n//bool LR::SaveModel(std::string& filename) {\n//  std::ofstream fout(filename.c_str());\n//  fout << num_feature_dim_ << std::endl;\n//  for (int i = 0; i < num_feature_dim_; ++i) {\n//    fout << weight_[i] << ' ';\n//  }\n//  fout << std::endl;\n//  fout.close();\n//  return true;\n//}\n\n//std::string LR::DebugInfo() {\n//  std::ostringstream out;\n//  for (size_t i = 0; i < weight_.size(); ++i) {\n//    out << weight_[i] << \" \";\n//  }\n//  return out.str();\n//}\n\n//  float LR::Sigmoid_(std::vector<float> feature) {\n//    float z = 0;\n//    for (size_t j = 0; j < weight_.size(); ++j) {\n//      z += weight_[j] * feature[j];\n//    }\n//    return 1. / (1. + exp(-z));\n//  }\n\n} // namespace lrprox\n", "meta": {"hexsha": "2b4612682f0a4e1885def2b51605fbc1bdd4ba75", "size": 3415, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/LR_proximal/src/softmax.cc", "max_stars_repo_name": "xcgoner/ps-lite-new", "max_stars_repo_head_hexsha": "39754e97b4b23dc6f90ab6fc22b3e1a918f48093", "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/LR_proximal/src/softmax.cc", "max_issues_repo_name": "xcgoner/ps-lite-new", "max_issues_repo_head_hexsha": "39754e97b4b23dc6f90ab6fc22b3e1a918f48093", "max_issues_repo_licenses": ["Apache-2.0"], "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/LR_proximal/src/softmax.cc", "max_forks_repo_name": "xcgoner/ps-lite-new", "max_forks_repo_head_hexsha": "39754e97b4b23dc6f90ab6fc22b3e1a918f48093", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5403225806, "max_line_length": 117, "alphanum_fraction": 0.5956076135, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6122801959877293}}
{"text": "#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include <vector>\n#include <algorithm>\n#include <list>\n#include \"../../../iterators.hpp\"\n#include \"../../../math/root.hpp\"\n#include \"../../../math/axis.hpp\"\n#include \"../../../math/multiaxis.hpp\"\n#include \"../../../math/combinatorics.hpp\"\n#include <boost/math/distributions/normal.hpp>\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace hmLib {\n\tTEST_CLASS(test_math_root) {\n\tpublic:\n\t\tTEST_METHOD(root_finding_toms748) {\n\t\tauto f = [](double x) {return (x - 0.3)*(x - 0.4549)*(x - 0.8991); };\n\n\t\tstd::vector<double> Ans;\n\t\thmLib::math::stable_root_toms748(f, 0.0, 1.0, 0.001, 1e-5, hmLib::back_inserter(Ans));\n\n\t\tAssert::AreEqual(1u, Ans.size(), L\"Ans Num Error\");\n//\t\tAssert::AreEqual(0.3, Ans.at(0), 1e-5, L\"Ans Num Error\");\n\t\tAssert::AreEqual(0.4549, Ans.at(0), 1e-5, L\"Ans Num Error\");\n//\t\tAssert::AreEqual(0.8991, Ans.at(2), 1e-5, L\"Ans Num Error\");\n\t\t}\n\t\tTEST_METHOD(root_finding_bisect) {\n\t\tauto f = [](double x) {return (x - 0.3)*(x - 0.4549)*(x - 0.8991); };\n\n\t\tstd::vector<double> Ans;\n\t\thmLib::math::bisect_root_stepper<double> Stepper(0.001, 1e-5);\n\t\thmLib::math::stable_root(Stepper, f, 0.0, 1.0, hmLib::back_inserter(Ans));\n\n\t\tAssert::AreEqual(1u, Ans.size(), L\"Ans Num Error\");\n//\t\tAssert::AreEqual(0.3, Ans.at(0), 1e-5, L\"Ans Num Error\");\n\t\tAssert::AreEqual(0.4549, Ans.at(0), 1e-5, L\"Ans Num Error\");\n//\t\tAssert::AreEqual(0.8991, Ans.at(2), 1e-5, L\"Ans Num Error\");\n\t\t}\n\t};\n\tTEST_CLASS(test_math_axis) {\n\t\tTEST_METHOD(make_range_axis_with_borders) {\n\t\t\tauto Axis1 = make_range_axis(0.0, 10.0, 11);\n\t\t\tAssert::AreEqual(11u, Axis1.size());\n\t\t\tAssert::AreEqual( 0.0, Axis1.lower());\n\t\t\tAssert::AreEqual(10.0, Axis1.upper());\n\n\t\t\tauto Axis2 = make_range_axis(0.0, 10.0, 11, math::range_axis_option::none);\n\t\t\tAssert::AreEqual(11u, Axis2.size());\n\t\t\tAssert::AreEqual(0.0, Axis2.lower());\n\t\t\tAssert::AreEqual(10.0, Axis2.upper());\n\n\t\t\tauto Axis3 = make_range_axis(0.0, 10.0, 9, math::range_axis_option::exclude_boundary);\n\t\t\tAssert::AreEqual(9u, Axis3.size());\n\t\t\tAssert::AreEqual(1.0, Axis3.lower());\n\t\t\tAssert::AreEqual(9.0, Axis3.upper());\n\n\t\t\tauto Axis4 = make_range_axis(0.0, 10.0, 10, math::range_axis_option::exclude_lower_boundary);\n\t\t\tAssert::AreEqual(10u, Axis4.size());\n\t\t\tAssert::AreEqual(1.0, Axis4.lower());\n\t\t\tAssert::AreEqual(10.0, Axis4.upper());\n\n\t\t\tauto Axis5 = make_range_axis(0.0, 10.0, 10, math::range_axis_option::exclude_upper_boundary);\n\t\t\tAssert::AreEqual(10u, Axis5.size());\n\t\t\tAssert::AreEqual(0.0, Axis5.lower());\n\t\t\tAssert::AreEqual(9.0, Axis5.upper());\n\t\t}\n\t\tTEST_METHOD(axis_grid_index) {\n\t\t\t{\n\t\t\t\tauto Axis = make_range_axis(0.0, 1.0, 11);\n\t\t\t\tAssert::AreEqual(0.1, Axis.interval());\n\t\t\t\tfor(unsigned int i = 0; i<Axis.size(); ++i) {\n\t\t\t\t\tAssert::AreEqual<int>(i, Axis.index(0.1*i-0.04));\n\t\t\t\t\tAssert::AreEqual<int>(i, Axis.index(0.1*i+0.04));\n\t\t\t\t}\n\t\t\t}\n\t\t\t{\n\t\t\t\tauto Axis = make_range_axis(0.0, 1.0, 11, math::grid_adjuster<math::grid_policy::floor_grid_tag,-8>());\n\t\t\t\tAssert::AreEqual(0.1, Axis.interval());\n\t\t\t\tfor(unsigned int i = 0; i<Axis.size(); ++i) {\n\t\t\t\t\tAssert::AreEqual<int>(i, Axis.index(0.1*i+0.04));\n\t\t\t\t\tAssert::AreEqual<int>(i, Axis.index(0.1*i+0.08));\n\t\t\t\t}\n\t\t\t}\n\t\t\t{\n\t\t\t\tauto Axis = make_range_axis(0.0, 1.0, 11, math::ceil_grid_adjuster<-8>());\n\t\t\t\tAssert::AreEqual(0.1, Axis.interval());\n\t\t\t\tfor(unsigned int i = 0; i<Axis.size(); ++i) {\n\t\t\t\t\tAssert::AreEqual<int>(i, Axis.index(0.1*i-0.04));\n\t\t\t\t\tAssert::AreEqual<int>(i, Axis.index(0.1*i-0.08));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tTEST_METHOD(axis_flort_index) {\n\t\t\t{\n\t\t\t\tauto Axis = make_range_axis(0.0, 1.0, 11);\n\n\t\t\t\tAssert::AreEqual(0.0, Axis.float_index(0.00), 1e-5);\n\t\t\t\tAssert::AreEqual(0.2, Axis.float_index(0.02), 1e-5);\n\t\t\t\tAssert::AreEqual(4.6, Axis.float_index(0.46), 1e-5);\n\t\t\t\tAssert::AreEqual(8.3, Axis.float_index(0.83), 1e-5);\n\t\t\t}\n\t\t}\n\t\tTEST_METHOD(axis_grid_round_range) {\n\t\t\tauto Axis = make_range_axis(0.0, 1.0, 11);\n\n\t\t\tAssert::AreEqual(0.1, Axis.interval());\n\n\t\t\t{\n\t\t\t\tauto Ans = Axis.weighted_index(0.30-0.04, 0.30+0.04);\n\t\t\t\tAssert::AreEqual(1u, Ans.size());\n\t\t\t\tAssert::AreEqual(0.8, Ans.volume(),1e-5);\n\t\t\t\tAssert::AreEqual(3, Ans.at(0).first);\n\t\t\t\tAssert::AreEqual(1.0, Ans.at(0).second, 1e-5);\n\n\t\t\t\tauto Itr = Ans.begin();\n\t\t\t\tauto End = Ans.end();\n\t\t\t\tAssert::IsFalse(Itr==End);\n\t\t\t\tAssert::AreEqual(3, (*Itr).first);\n\t\t\t\tAssert::AreEqual(1.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::IsTrue(Itr==End);\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tauto Ans = Axis.weighted_index(0.30-0.04, 0.30+0.06);\n\t\t\t\tAssert::AreEqual(2u, Ans.size());\n\t\t\t\tAssert::AreEqual(1.0, Ans.volume(),1e-5);\n\t\t\t\tAssert::AreEqual(3, Ans.at(0).first);\n\t\t\t\tAssert::AreEqual(0.9 , Ans.at(0).second, 1e-5);\n\t\t\t\tAssert::AreEqual(4, Ans.at(1).first);\n\t\t\t\tAssert::AreEqual(0.1, Ans.at(1).second, 1e-5);\n\n\t\t\t\tauto Itr = Ans.begin();\n\t\t\t\tauto End = Ans.end();\n\t\t\t\tAssert::IsFalse(Itr==End);\n\t\t\t\tAssert::AreEqual(3, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.9, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(4, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.1, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::IsTrue(Itr==End);\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tauto Ans = Axis.weighted_index(0.30-0.04, 0.30+0.26);\n\t\t\t\tAssert::AreEqual(4u, Ans.size());\n\t\t\t\tAssert::AreEqual(3.0, Ans.volume(), 1e-5);\n\t\t\t\tAssert::AreEqual(3, Ans.at(0).first);\n\t\t\t\tAssert::AreEqual(0.9/3.0, Ans.at(0).second, 1e-5);\n\t\t\t\tAssert::AreEqual(4, Ans.at(1).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, Ans.at(1).second, 1e-5);\n\t\t\t\tAssert::AreEqual(5, Ans.at(2).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, Ans.at(2).second, 1e-5);\n\t\t\t\tAssert::AreEqual(6, Ans.at(3).first);\n\t\t\t\tAssert::AreEqual(0.1/3.0, Ans.at(3).second, 1e-5);\n\n\t\t\t\tauto Itr = Ans.begin();\n\t\t\t\tauto End = Ans.end();\n\t\t\t\tAssert::IsFalse(Itr==End);\n\t\t\t\tAssert::AreEqual(3, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.9/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(4, (*Itr).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(5, (*Itr).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(6, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.1/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::IsTrue(Itr==End);\n\t\t\t}\n\t\t}\n\t\tTEST_METHOD(axis_grid_floor_range) {\n\t\t\tauto Axis = make_range_axis(0.0, 1.0, 11,math::floor_grid_adjuster<-8>());\n\n\t\t\tAssert::AreEqual(0.1, Axis.interval());\n\n\t\t\t{\n\t\t\t\tauto Ans = Axis.weighted_index(0.30+0.04, 0.30+0.08);\n\t\t\t\tAssert::AreEqual(1u, Ans.size());\n\t\t\t\tAssert::AreEqual(3, Ans.at(0).first);\n\t\t\t\tAssert::AreEqual(1.0, Ans.at(0).second, 1e-5);\n\n\t\t\t\tauto Itr = Ans.begin();\n\t\t\t\tauto End = Ans.end();\n\t\t\t\tAssert::IsFalse(Itr==End);\n\t\t\t\tAssert::AreEqual(3, (*Itr).first);\n\t\t\t\tAssert::AreEqual(1.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::IsTrue(Itr==End);\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tauto Ans = Axis.weighted_index(0.30+0.01, 0.30+0.11);\n\t\t\t\tAssert::AreEqual(2u, Ans.size());\n\t\t\t\tAssert::AreEqual(1.0, Ans.volume(), 1e-5);\n\t\t\t\tAssert::AreEqual(3, Ans.at(0).first);\n\t\t\t\tAssert::AreEqual(0.9, Ans.at(0).second, 1e-5);\n\t\t\t\tAssert::AreEqual(4, Ans.at(1).first);\n\t\t\t\tAssert::AreEqual(0.1, Ans.at(1).second, 1e-5);\n\n\t\t\t\tauto Itr = Ans.begin();\n\t\t\t\tauto End = Ans.end();\n\t\t\t\tAssert::IsFalse(Itr==End);\n\t\t\t\tAssert::AreEqual(3, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.9, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(4, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.1, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::IsTrue(Itr==End);\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tauto Ans = Axis.weighted_index(0.30+0.01, 0.30+0.31);\n\t\t\t\tAssert::AreEqual(4u, Ans.size());\n\t\t\t\tAssert::AreEqual(3.0, Ans.volume(), 1e-5);\n\t\t\t\tAssert::AreEqual(3, Ans.at(0).first);\n\t\t\t\tAssert::AreEqual(0.9/3.0, Ans.at(0).second, 1e-5);\n\t\t\t\tAssert::AreEqual(4, Ans.at(1).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, Ans.at(1).second, 1e-5);\n\t\t\t\tAssert::AreEqual(5, Ans.at(2).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, Ans.at(2).second, 1e-5);\n\t\t\t\tAssert::AreEqual(6, Ans.at(3).first);\n\t\t\t\tAssert::AreEqual(0.1/3.0, Ans.at(3).second, 1e-5);\n\n\t\t\t\tauto Itr = Ans.begin();\n\t\t\t\tauto End = Ans.end();\n\t\t\t\tAssert::IsFalse(Itr==End);\n\t\t\t\tAssert::AreEqual(3, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.9/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(4, (*Itr).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(5, (*Itr).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(6, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.1/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::IsTrue(Itr==End);\n\t\t\t}\n\t\t}\n\t\tTEST_METHOD(axis_grid_ceil_range) {\n\t\t\tauto Axis = make_range_axis(0.0, 1.0, 11, math::ceil_grid_adjuster<-8>());\n\n\t\t\tAssert::AreEqual(0.1, Axis.interval());\n\n\t\t\t{\n\t\t\t\tauto Ans = Axis.weighted_index(0.20+0.04, 0.20+0.08);\n\t\t\t\tAssert::AreEqual(1u, Ans.size());\n\t\t\t\tAssert::AreEqual(3, Ans.at(0).first);\n\t\t\t\tAssert::AreEqual(1.0, Ans.at(0).second, 1e-5);\n\n\t\t\t\tauto Itr = Ans.begin();\n\t\t\t\tauto End = Ans.end();\n\t\t\t\tAssert::IsFalse(Itr==End);\n\t\t\t\tAssert::AreEqual(3, (*Itr).first);\n\t\t\t\tAssert::AreEqual(1.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::IsTrue(Itr==End);\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tauto Ans = Axis.weighted_index(0.20+0.01, 0.20+0.11);\n\t\t\t\tAssert::AreEqual(2u, Ans.size());\n\t\t\t\tAssert::AreEqual(3, Ans.at(0).first);\n\t\t\t\tAssert::AreEqual(0.9, Ans.at(0).second, 1e-5);\n\t\t\t\tAssert::AreEqual(4, Ans.at(1).first);\n\t\t\t\tAssert::AreEqual(0.1, Ans.at(1).second, 1e-5);\n\n\t\t\t\tauto Itr = Ans.begin();\n\t\t\t\tauto End = Ans.end();\n\t\t\t\tAssert::IsFalse(Itr==End);\n\t\t\t\tAssert::AreEqual(3, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.9, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(4, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.1, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::IsTrue(Itr==End);\n\t\t\t}\n\n\t\t\t{\n\t\t\t\tauto Ans = Axis.weighted_index(0.20+0.01, 0.20+0.31);\n\t\t\t\tAssert::AreEqual(4u, Ans.size());\n\t\t\t\tAssert::AreEqual(3.0, Ans.volume(), 1e-5);\n\t\t\t\tAssert::AreEqual(3, Ans.at(0).first);\n\t\t\t\tAssert::AreEqual(0.9/3.0, Ans.at(0).second, 1e-5);\n\t\t\t\tAssert::AreEqual(4, Ans.at(1).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, Ans.at(1).second, 1e-5);\n\t\t\t\tAssert::AreEqual(5, Ans.at(2).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, Ans.at(2).second, 1e-5);\n\t\t\t\tAssert::AreEqual(6, Ans.at(3).first);\n\t\t\t\tAssert::AreEqual(0.1/3.0, Ans.at(3).second, 1e-5);\n\n\t\t\t\tauto Itr = Ans.begin();\n\t\t\t\tauto End = Ans.end();\n\t\t\t\tAssert::IsFalse(Itr==End);\n\t\t\t\tAssert::AreEqual(3, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.9/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(4, (*Itr).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(5, (*Itr).first);\n\t\t\t\tAssert::AreEqual(1.0/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::AreEqual(6, (*Itr).first);\n\t\t\t\tAssert::AreEqual(0.1/3.0, (*Itr).second, 1e-5);\n\t\t\t\t++Itr;\n\t\t\t\tAssert::IsTrue(Itr==End);\n\t\t\t}\n\t\t}\n\t\tTEST_METHOD(axis_mapping_floor_floor) {\n\t\t\tauto Axis1 = make_range_axis(0.2, 0.89, 4, math::floor_grid_adjuster<-8>());\t//[0.2, 0.43, 0.66, 0.89]\n\t\t\tauto Axis2 = make_range_axis(0.02, 0.74, 7, math::floor_grid_adjuster<-8>());\t//[0.02, 0.14, 0.26, 0.38, 0.50, 0.62, 0.74]\n\n\n\t\t\tauto Mapper = hmLib::map_axis(Axis1, Axis2);\n\t\t\t//lower & upper\n\t\t\tAssert::AreEqual(0, Mapper.lower());\n\t\t\tAssert::AreEqual(1, Mapper.upper());\n\n\t\t\t//inside\n\t\t\tAssert::IsTrue(Mapper.inside(0));\n\t\t\tAssert::IsTrue(Mapper.inside(1));\n\t\t\tAssert::IsFalse(Mapper.inside(2));\n\t\t\tAssert::IsFalse(Mapper.inside(3));\n\n\t\t\tauto WI = Mapper.weighted_index(0);\n\t\t\tAssert::AreEqual(3u, WI.size());\n\t\t\tAssert::AreEqual(1, WI.at(0).first);\n\t\t\tAssert::AreEqual((0.26-0.20)/0.23, WI.at(0).second, 1e-5);\n\t\t\tAssert::AreEqual(2, WI.at(1).first);\n\t\t\tAssert::AreEqual((0.38-0.26)/0.23, WI.at(1).second, 1e-5);\n\t\t\tAssert::AreEqual(3, WI.at(2).first);\n\t\t\tAssert::AreEqual((0.43-0.38)/0.23, WI.at(2).second, 1e-5);\n\t\t}\n\t\tTEST_METHOD(axis_mapping_round_round) {\n\t\t\tauto Axis1 = make_range_axis(0.2+0.23/2, 0.89+0.23/2, 4, math::round_grid_adjuster<-8>());\t//[0.2, 0.43, 0.66, 0.89]\n\t\t\tauto Axis2 = make_range_axis(0.02+0.12/2, 0.74+0.12/2, 7, math::round_grid_adjuster<-8>());\t//[0.02, 0.14, 0.26, 0.38, 0.50, 0.62, 0.74]\n\n\n\t\t\tauto Mapper = hmLib::map_axis(Axis1, Axis2);\n\t\t\t//lower & upper\n\t\t\tAssert::AreEqual(0, Mapper.lower());\n\t\t\tAssert::AreEqual(1, Mapper.upper());\n\n\t\t\t//inside\n\t\t\tAssert::IsTrue(Mapper.inside(0));\n\t\t\tAssert::IsTrue(Mapper.inside(1));\n\t\t\tAssert::IsFalse(Mapper.inside(2));\n\t\t\tAssert::IsFalse(Mapper.inside(3));\n\n\t\t\tauto WI = Mapper.weighted_index(0);\n\t\t\tAssert::AreEqual(3u, WI.size());\n\t\t\tAssert::AreEqual(1, WI.at(0).first);\n\t\t\tAssert::AreEqual((0.26-0.20)/0.23, WI.at(0).second, 1e-5);\n\t\t\tAssert::AreEqual(2, WI.at(1).first);\n\t\t\tAssert::AreEqual((0.38-0.26)/0.23, WI.at(1).second, 1e-5);\n\t\t\tAssert::AreEqual(3, WI.at(2).first);\n\t\t\tAssert::AreEqual((0.43-0.38)/0.23, WI.at(2).second, 1e-5);\n\t\t}\n\t\tTEST_METHOD(axis_mapping_ceil_round) {\n\t\t\tauto Axis1 = make_range_axis(0.2+0.23, 0.89+0.23, 4, math::ceil_grid_adjuster<-8>());\t//[0.2, 0.43, 0.66, 0.89]\n\t\t\tauto Axis2 = make_range_axis(0.02+0.12/2, 0.74+0.12/2, 7, math::round_grid_adjuster<-8>());\t//[0.02, 0.14, 0.26, 0.38, 0.50, 0.62, 0.74]\n\n\n\t\t\tauto Mapper = hmLib::map_axis(Axis1, Axis2);\n\t\t\t//lower & upper\n\t\t\tAssert::AreEqual(0, Mapper.lower());\n\t\t\tAssert::AreEqual(1, Mapper.upper());\n\n\t\t\t//inside\n\t\t\tAssert::IsTrue(Mapper.inside(0));\n\t\t\tAssert::IsTrue(Mapper.inside(1));\n\t\t\tAssert::IsFalse(Mapper.inside(2));\n\t\t\tAssert::IsFalse(Mapper.inside(3));\n\n\t\t\tauto WI = Mapper.weighted_index(0);\n\t\t\tAssert::AreEqual(3u, WI.size());\n\t\t\tAssert::AreEqual(1, WI.at(0).first);\n\t\t\tAssert::AreEqual((0.26-0.20)/0.23, WI.at(0).second, 1e-5);\n\t\t\tAssert::AreEqual(2, WI.at(1).first);\n\t\t\tAssert::AreEqual((0.38-0.26)/0.23, WI.at(1).second, 1e-5);\n\t\t\tAssert::AreEqual(3, WI.at(2).first);\n\t\t\tAssert::AreEqual((0.43-0.38)/0.23, WI.at(2).second, 1e-5);\n\t\t}\n\t\tTEST_METHOD(axis_mapping_round_ceil) {\n\t\t\tauto Axis1 = make_range_axis(0.2+0.23/2, 0.89+0.23/2, 4, math::round_grid_adjuster<-8>());\t//[0.2, 0.43, 0.66, 0.89]\n\t\t\tauto Axis2 = make_range_axis(0.02+0.12, 0.74+0.12, 7, math::ceil_grid_adjuster<-8>());\t//[0.02, 0.14, 0.26, 0.38, 0.50, 0.62, 0.74]\n\n\n\t\t\tauto Mapper = hmLib::map_axis(Axis1, Axis2);\n\t\t\t//lower & upper\n\t\t\tAssert::AreEqual(0, Mapper.lower());\n\t\t\tAssert::AreEqual(1, Mapper.upper());\n\n\t\t\t//inside\n\t\t\tAssert::IsTrue(Mapper.inside(0));\n\t\t\tAssert::IsTrue(Mapper.inside(1));\n\t\t\tAssert::IsFalse(Mapper.inside(2));\n\t\t\tAssert::IsFalse(Mapper.inside(3));\n\n\t\t\tauto WI = Mapper.weighted_index(0);\n\t\t\tAssert::AreEqual(3u, WI.size());\n\t\t\tAssert::AreEqual(1, WI.at(0).first);\n\t\t\tAssert::AreEqual((0.26-0.20)/0.23, WI.at(0).second, 1e-5);\n\t\t\tAssert::AreEqual(2, WI.at(1).first);\n\t\t\tAssert::AreEqual((0.38-0.26)/0.23, WI.at(1).second, 1e-5);\n\t\t\tAssert::AreEqual(3, WI.at(2).first);\n\t\t\tAssert::AreEqual((0.43-0.38)/0.23, WI.at(2).second, 1e-5);\n\t\t}\n\t\tTEST_METHOD(axis_mapping_norm) {\n\t\t\tauto Axis1 = hmLib::make_range_axis(1.0, 2.0, 101);\n\t\t\tauto Axis2 = hmLib::make_range_axis(0.5, 2.5, 101);\n\n\t\t\tauto Dist = boost::math::normal_distribution<double>(1.5, 0.1);\n\n\t\t\tstd::vector<double> Vec1(Axis1.size(), 0.);\n\n\n\t\t\tfor(unsigned int i = 0; i<Axis1.size(); ++i) {\n\t\t\t\tVec1[i] = boost::math::pdf(Dist, Axis1[i])*Axis1.interval();\n\t\t\t}\n\t\t\tauto Mapper = Axis1.map_to(Axis2);\n\n\t\t\tstd::vector<double> Vec2(Axis2.size(), 0.);\n\t\t\tfor(unsigned int i = 0; i<Vec1.size(); ++i) {\n\t\t\t\tauto wi = Mapper.weighted_index(i);\n\t\t\t\tfor(auto p:wi) {\n\t\t\t\t\tVec2[p.first] += p.second*Vec1[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauto Sum1 = std::accumulate(Vec1.begin(), Vec1.end(), 0.0);\n\t\t\tauto Sum2 = std::accumulate(Vec2.begin(), Vec2.end(), 0.0);\n\n\t\t\tAssert::AreEqual(1.0, Sum1, 1e-3);\n\t\t\tAssert::AreEqual(Sum1, Sum2, 1e-4);\n\t\t}\n\t};\n\tTEST_CLASS(test_math_multiaxis) {\n\t\tTEST_METHOD(test_map) {\n\t\t\tlattice_axis<double, 2> Axes1;\n\t\t\tAxes1.axis(0).assign(4.95, 5.05, 101);\n\t\t\tAxes1.axis(1).assign(0.80, 0.90, 101);\n\n\t\t\tlattice_axis<double, 2> Axes2;\n\t\t\tAxes2.axis(0).assign(4.90, 5.10, 101);\n\t\t\tAxes2.axis(1).assign(0.80, 0.90, 101);\n\n\t\t\tauto Dist1 = boost::math::normal_distribution<double>(5.00, 0.01);\n\t\t\tauto Dist2 = boost::math::normal_distribution<double>(0.85, 0.01);\n\t\t\tlattices::indexer<2> Indexer(lattices::extent_type<2>{101, 101});\n\t\t\tstd::vector<double> Vec1(101*101, 0.0);\n\t\t\tfor(unsigned int i = 0; i<Axes1.axis(0).size(); ++i) {\n\t\t\t\tfor(unsigned int j = 0; j<Axes1.axis(1).size(); ++j) {\n\t\t\t\t\tVec1[Indexer.index(lattices::point_type<2>{static_cast<int>(i), static_cast<int>(j)})] = boost::math::pdf(Dist1, Axes1.axis(0)[i])*Axes1.axis(0).interval()\n\t\t\t\t\t\t* boost::math::pdf(Dist2, Axes1.axis(1)[j])*Axes1.axis(1).interval();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauto Mapper = Axes1.map_to(Axes2);\n\t\t\tstd::vector<double> Vec2(Vec1.size(), 0.);\n\t\t\tfor(unsigned int i = 0; i<Axes1.axis(0).size(); ++i) {\n\t\t\t\tfor(unsigned int j = 0; j<Axes1.axis(1).size(); ++j) {\n\t\t\t\t\tauto wi = Mapper.weighted_point(lattices::point_type<2>{static_cast<int>(i), static_cast<int>(j)});\n\t\t\t\t\tfor(auto p:wi) {\n\t\t\t\t\t\tVec2[Indexer.index(p.first)] += p.second*Vec1[Indexer.index(lattices::point_type<2>{static_cast<int>(i), static_cast<int>(j)})];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauto Sum1 = std::accumulate(Vec1.begin(), Vec1.end(), 0.0);\n\t\t\tauto Sum2 = std::accumulate(Vec2.begin(), Vec2.end(), 0.0);\n\n\t\t\tAssert::AreEqual(1.0, Sum1, 1e-3);\n\t\t\tAssert::AreEqual(Sum1, Sum2, 1e-4);\n\n\t\t}\n\t};\n\tTEST_CLASS(test_math_combi) {\n\t\tTEST_METHOD(test_combination) {\n\t\t\tunsigned int N = 5;\n\t\t\tunsigned int R = 3;\n\t\t\tcombination_indexer<> Indexer(N, R);\n\t\t\tAssert::AreEqual<unsigned long long>(10, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_combination_at) {\n\t\t\tunsigned int N = 5;\n\t\t\tunsigned int R = 3;\n\t\t\tcombination_indexer<> Indexer(N, R);\n\t\t\tAssert::AreEqual<unsigned long long>(10, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(std::size_t i = 0; i<Indexer.size(); ++i) {\n\t\t\t\t\tAssert::IsTrue(Indexer[i]<N);\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += Indexer.at(i);\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_combination_excp1_at) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,4,6 };\n\t\t\tcombination_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(10, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(std::size_t i = 0; i<Indexer.size(); ++i) {\n\t\t\t\t\tAssert::IsTrue(Indexer[i]<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), Indexer[i])==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += Indexer.at(i);\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_combination_excp1) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,4,6 };\n\t\t\tcombination_indexer<> Indexer(N, R,Excp.begin(),Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(10, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_combination_excp2) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,3,4,6,3,4,0,0,0,6 };\n\t\t\tcombination_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(10, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_combination_excp3) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 5,6,7,8,9 };\n\t\t\tcombination_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(10, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multicombination) {\n\t\t\tunsigned int N = 5;\n\t\t\tunsigned int R = 3;\n\t\t\tmulticombination_indexer<> Indexer(N, R);\n\t\t\tAssert::AreEqual<unsigned long long>(nHr(5,3), Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multicombination_at) {\n\t\t\tunsigned int N = 5;\n\t\t\tunsigned int R = 3;\n\t\t\tmulticombination_indexer<> Indexer(N, R);\n\t\t\tAssert::AreEqual<unsigned long long>(nHr(5,3), Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(std::size_t i = 0; i<Indexer.size(); ++i) {\n\t\t\t\t\tAssert::IsTrue(Indexer[i]<N);\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += Indexer.at(i);\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multicombination_excp1_at) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,4,6 };\n\t\t\tmulticombination_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(nHr(5, 3), Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(std::size_t i = 0; i<Indexer.size(); ++i) {\n\t\t\t\t\tAssert::IsTrue(Indexer[i]<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), Indexer[i])==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += Indexer.at(i);\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multicombination_excp) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,4,6 };\n\t\t\tmulticombination_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(nHr(N-Excp.size(),R), Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multicombination_excp2) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,3,4,6,3,4,0,0,0,6 };\n\t\t\tmulticombination_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(nHr(5,3), Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multicombination_excp3) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 5,6,7,8,9 };\n\t\t\tmulticombination_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(nHr(5,3), Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_permutation) {\n\t\t\tunsigned int N = 5;\n\t\t\tunsigned int R = 3;\n\t\t\tpermutation_indexer<> Indexer(N, R);\n\t\t\tAssert::AreEqual<unsigned long long>(60, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_permutation_at) {\n\t\t\tunsigned int N = 5;\n\t\t\tunsigned int R = 3;\n\t\t\tpermutation_indexer<> Indexer(N, R);\n\t\t\tAssert::AreEqual<unsigned long long>(60, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(std::size_t i = 0; i<Indexer.size(); ++i) {\n\t\t\t\t\tAssert::IsTrue(Indexer[i]<N);\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += Indexer.at(i);\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_permutation_excp1_at) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,4,6 };\n\t\t\tpermutation_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(60, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(std::size_t i = 0; i<Indexer.size(); ++i) {\n\t\t\t\t\tAssert::IsTrue(Indexer[i]<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), Indexer[i])==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += Indexer.at(i);\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_permutation_excp1) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,4,6 };\n\t\t\tpermutation_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(60, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_permutation_excp2) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,3,4,6,3,4,0,0,0,6 };\n\t\t\tpermutation_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(60, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_permutation_excp3) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 5,6,7,8,9 };\n\t\t\tpermutation_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(60, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multipermutation) {\n\t\t\tunsigned int N = 5;\n\t\t\tunsigned int R = 3;\n\t\t\tmultipermutation_indexer<> Indexer(N, R);\n\t\t\tAssert::AreEqual<unsigned long long>(125, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multipermutation_at) {\n\t\t\tunsigned int N = 5;\n\t\t\tunsigned int R = 3;\n\t\t\tmultipermutation_indexer<> Indexer(N, R);\n\t\t\tAssert::AreEqual<unsigned long long>(125, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(std::size_t i = 0; i<Indexer.size(); ++i) {\n\t\t\t\t\tAssert::IsTrue(Indexer[i]<N);\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += Indexer.at(i);\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multipermutation_excp1_at) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,4,6 };\n\t\t\tmultipermutation_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(125, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(std::size_t i = 0; i<Indexer.size(); ++i) {\n\t\t\t\t\tAssert::IsTrue(Indexer[i]<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), Indexer[i])==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += Indexer.at(i);\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multipermutation_excp) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,4,6 };\n\t\t\tmultipermutation_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(125, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multipermutation_excp2) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 0,3,3,4,6,3,4,0,0,0,6 };\n\t\t\tmultipermutation_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(125, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\t\tTEST_METHOD(test_multipermutation_excp3) {\n\t\t\tunsigned int N = 9;\n\t\t\tunsigned int R = 3;\n\t\t\tstd::vector<unsigned int> Excp{ 5,6,7,8,9 };\n\t\t\tmultipermutation_indexer<> Indexer(N, R, Excp.begin(), Excp.end());\n\t\t\tAssert::AreEqual<unsigned long long>(125, Indexer.total_casenum());\n\n\t\t\tstd::vector<unsigned long long> Vec;\n\t\t\tfor(; Indexer.valid(); Indexer.next()) {\n\t\t\t\tunsigned long long Val = 0;\n\t\t\t\tfor(auto Itr = Indexer.begin(); Itr!=Indexer.end(); ++Itr) {\n\t\t\t\t\tAssert::IsTrue(*Itr<N);\n\t\t\t\t\tAssert::IsTrue(std::find(Excp.begin(), Excp.end(), *Itr)==Excp.end());\n\t\t\t\t\tVal *= 10;\n\t\t\t\t\tVal += *Itr;\n\t\t\t\t}\n\t\t\t\tVec.push_back(Val);\n\t\t\t}\n\t\t\tAssert::AreEqual<unsigned long long>(Indexer.total_casenum(), Vec.size());\n\t\t\tAssert::IsTrue(std::unique(Vec.begin(), Vec.end())==Vec.end());\n\t\t}\n\n\t};\n}\n", "meta": {"hexsha": "5f7acf09f5e594f281cd42a417ff5b3fd7ead5ac", "size": 34752, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vc/hmLib/test_hmLib/test_math.cpp", "max_stars_repo_name": "hmito/hmLib", "max_stars_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vc/hmLib/test_hmLib/test_math.cpp", "max_issues_repo_name": "hmito/hmLib", "max_issues_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vc/hmLib/test_hmLib/test_math.cpp", "max_forks_repo_name": "hmito/hmLib", "max_forks_repo_head_hexsha": "0f2515ba9c99c06d02e2fa633eeae73bcd793983", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-09-22T03:32:11.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-22T03:32:11.000Z", "avg_line_length": 35.4250764526, "max_line_length": 160, "alphanum_fraction": 0.6178061694, "num_tokens": 12148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6122801856151876}}
{"text": "/*++\n    BDcpp -- Simple Bjontegaard Delta metric implementation for C++.\n\n    MIT License\n\n    Copyright (c) 2022 Tim Bruylants\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n--*/\n\n#include \"bdcpp.h\"\n\n#include <Eigen/Dense>\n#include <cmath>\n\nnamespace bdcpp\n{\nnamespace details\n{\n// Fit a polynomial of given order on the curve (minimizing squared distance).\nstd::vector<value_type> polyFit(const curve_data_type& curve, const size_t order)\n{\n    const size_t numCoefficients = order + 1;\n    const size_t nCount = curve.size();\n\n    Eigen::MatrixX<value_type> X(nCount, numCoefficients);\n    Eigen::MatrixX<value_type> Y(nCount, 1);\n\n    // fill X and Y matrices (X is a Vandermonde matrix)\n    for (size_t row = 0; row < nCount; ++row)\n    {\n        Y(row, 0) = curve[row].second;\n        value_type v = (value_type)1;\n        for (size_t col = 0; col < numCoefficients; ++col)\n        {\n            X(row, col) = v;\n            v *= curve[row].first;\n        }\n    }\n\n    // Solve for the polynomial coefficients (one column) and return.\n    const Eigen::VectorX<value_type> coefficients = X.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(Y);\n    return std::vector<value_type>(coefficients.data(), coefficients.data() + numCoefficients);\n}\n\n// Calculates Y(x), where the polynomial coefficients are given.\nvalue_type polyVal(const std::vector<value_type>& coefficients, const value_type x)\n{\n    assert(!coefficients.empty());\n    size_t c = coefficients.size();\n    value_type r = coefficients[--c];\n    while (c != 0)\n    {\n        r *= x;\n        r += coefficients[--c];\n    }\n    return r;\n}\n\nstd::vector<value_type> polyIntegrate(const std::vector<value_type>& coefficients, const value_type constant = 0)\n{\n    const size_t numCoefficients = coefficients.size();\n    std::vector<value_type> ic(numCoefficients + 1);\n    ic[0] = constant;\n    for (size_t c = 0; c < numCoefficients; ++c)\n    {\n        ic[c + 1] = coefficients[c] / (c + 1);\n    }\n    return ic;\n}\n\n// The main Bjontegaard calculation to get the area surface difference between two curves.\nvalue_type bdDiff(const curve_data_type& curveA, const curve_data_type& curveB, const int polyOrder)\n{\n    assert(polyOrder >= 3);\n    // Take lowest and highest X values (assumes sorted curves and relevant range overlap).\n    const auto lowX = std::max(curveA.front().first, curveB.front().first);\n    const auto highX = std::min(curveA.back().first, curveB.back().first);\n\n    // Fit curves as polynomials and integrate them.\n    const auto iCoefficientsA = polyIntegrate(polyFit(curveA, (size_t)polyOrder));\n    const auto iCoefficientsB = polyIntegrate(polyFit(curveB, (size_t)polyOrder));\n\n    // Calculate the definite integrals.\n    const auto intA = polyVal(iCoefficientsA, highX) - polyVal(iCoefficientsA, lowX);\n    const auto intB = polyVal(iCoefficientsB, highX) - polyVal(iCoefficientsB, lowX);\n\n    // Return the BD diff (as the area over range).\n    return (intB - intA) / (highX - lowX);\n}\n\n// Prepare curve points for BD calculations.\ntemplate<bool TRANSPOSE>\ncurve_data_type prepareCurve(const curve_data_type& curve)\n{\n    assert(curve.size() >= 4);\n    auto newCurve(curve);\n    std::sort(newCurve.begin(), newCurve.end(), [](const curve_data_point_type& vA, const curve_data_point_type& vB)\n        {\n            return vA.first < vB.first;\n        });\n    std::for_each(newCurve.begin(), newCurve.end(), [](curve_data_point_type& v)\n        {\n            v.first = std::log(v.first);\n            if constexpr (TRANSPOSE)\n            {\n                std::swap(v.first, v.second);\n            }\n        });\n    return newCurve;\n}\n}\n\n// Calculate the BD-SNR for the two given curves (returns a distortion improvement in dB).\nvalue_type bdsnr(const curve_data_type& curveA, const curve_data_type& curveB, const int polyOrder)\n{\n    return details::bdDiff(details::prepareCurve<false>(curveA), details::prepareCurve<false>(curveB), polyOrder);\n}\n\n// Calculate the BD-BR for the two given curves (returns a rate improvement in %).\nvalue_type bdbr(const curve_data_type& curveA, const curve_data_type& curveB, const int polyOrder)\n{\n    return (std::exp(details::bdDiff(details::prepareCurve<true>(curveA), details::prepareCurve<true>(curveB), polyOrder)) - 1) * 100;\n}\n}\n", "meta": {"hexsha": "dba67f1114390e57ae37931f331e903acb2035fe", "size": 5301, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bdcpp/bdcpp.cpp", "max_stars_repo_name": "tbr/bjontegaard_cpp", "max_stars_repo_head_hexsha": "d06302497d8af0734d69ce93590acab9a4998817", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bdcpp/bdcpp.cpp", "max_issues_repo_name": "tbr/bjontegaard_cpp", "max_issues_repo_head_hexsha": "d06302497d8af0734d69ce93590acab9a4998817", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bdcpp/bdcpp.cpp", "max_forks_repo_name": "tbr/bjontegaard_cpp", "max_forks_repo_head_hexsha": "d06302497d8af0734d69ce93590acab9a4998817", "max_forks_repo_licenses": ["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.3309859155, "max_line_length": 134, "alphanum_fraction": 0.6891152613, "num_tokens": 1323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6122801854857168}}
{"text": "/*\n * main.cpp\n *\n *  Created on: 3 Aug 2018\n *      Author: scsjd\n */\n\n#include <chrono>\n#include <iostream>\n#include <random>\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n#include <NTL/vec_ZZ.h>\n#include <NTL/vec_ZZ_p.h>\n#include \"DETEncrypter.h\"\n#include \"DETDecrypter.h\"\n#include \"SSEEncrypter.h\"\n#include \"SSEDecrypter.h\"\n#include \"GACDEncrypter.h\"\n#include \"GACDDecrypter.h\"\n#include \"PolyACDEncrypter.h\"\n#include \"PolyACDDecrypter.h\"\n#include \"HE1Encrypter.h\"\n#include \"HE1Decrypter.h\"\n#include \"HE1NEncrypter.h\"\n#include \"HE1NDecrypter.h\"\n#include \"HE2Encrypter.h\"\n#include \"HE2Decrypter.h\"\n#include \"HE2NEncrypter.h\"\n#include \"HE2NDecrypter.h\"\n#include \"HE2Ciphertext.h\"\n#include \"PolyCiphertext.h\"\n#include \"SSECiphertext.h\"\n\nNTL::ZZX createRandomPoly(std::mt19937& rng, int mu, int n) {\n\tNTL::ZZX p;\n\t//Generate random int for degree of poly\n\tunsigned int rnd = (rng() % n) + 1;\n\t//Generate random coefficients for poly\n\tp.SetLength(rnd+1);\n\tfor (unsigned int i = 0; i < rnd + 1; i++) {\n\t\tNTL::ZZ tmp;\n\t\tRandomBits(tmp, mu);\n\t\tp[i] = tmp;\n\t}\n\treturn p;\n}\n\nint main(){\n\tstd::cout << \"======= SSE Tests =======\" << std::endl;\n\n\tstd::string test = \"this is a test\";\n\n\tstd::cout << \"DET consistency test: \";\n\tDETEncrypter DETenc;\n\tstd::string DETsecrets = DETenc.writeSecretsToJSON();\n\tstd::string DETencrypted = DETenc.encryptToHex(test);\n\n\tDETDecrypter DETdec;\n\tDETdec.readSecretsFromJSON(DETsecrets);\n\tstd::string DETdecrypted = DETdec.decryptFromHex(DETencrypted);\n\tif(test==DETdecrypted) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"DET equality test: \";\n\tstd::string encrypted1 = DETenc.encryptToHex(test);\n\tstd::string encrypted2 = DETenc.encryptToHex(test);\n\tif(encrypted1==encrypted2) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"SSE consistency test: \";\n\tSSEEncrypter SSEenc;\n\tstd::string SSEsecrets = SSEenc.writeSecretsToJSON();\n\tstd::string SSEencrypted = SSEenc.encrypt(test);\n\n\tSSEDecrypter SSEdec;\n\tSSEdec.readSecretsFromJSON(SSEsecrets);\n\tstd::string SSEdecrypted = SSEdec.decrypt(SSEencrypted);\n\tif(test==SSEdecrypted) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"SSE match test 1: \";\n\tstd::string searchKey = SSEenc.createHexEncodedSearchKey(test);\n\tSSECiphertext ssec(SSEencrypted);\n\tif(ssec.match(searchKey)) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"SSE match test 2: \";\n\tstd::string test2 = \"The quick brown fox jumped over the lazy dog\";\n\tstd::string SSEencrypted2 = SSEenc.encrypt(test2);\n\tstd::string searchKey2 = SSEenc.createHexEncodedSearchKey(test2);\n\tSSECiphertext ssec2(SSEencrypted2);\n\tif(ssec2.match(searchKey2)) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"======= OPE Tests =======\" << std::endl;\n\t//Data for GACD test\n\tint bits = 32;\n\tNTL::ZZ ope_m1 = NTL::RandomBits_ZZ(bits);\n\tNTL::ZZ ope_m2 = NTL::RandomBits_ZZ(bits);\n\n\tstd::cout << \"GACD consistency test: \";\n\tGACDEncrypter GACDenc(GACDEncrypter::getMinimumKeyLength(bits));\n\tstd::string GACDsecrets = GACDenc.writeSecretsToJSON();\n\tNTL::ZZ GACDencrypted1 = GACDenc.encrypt(ope_m1);\n\n\tGACDDecrypter GACDdec;\n\tGACDdec.readSecretsFromJSON(GACDsecrets);\n\tNTL::ZZ GACDdecrypted = GACDdec.decrypt(GACDencrypted1);\n\tif(ope_m1==GACDdecrypted) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"GACD order-preserving test: \";\n\tNTL::ZZ GACDencrypted2 = GACDenc.encrypt(ope_m2);\n\tif(ope_m1 < ope_m2){\n\t\tif(GACDencrypted1<GACDencrypted2) std::cout << \"PASSED\" << std::endl;\n\t\telse std::cout << \"FAILED\" << std::endl;\n\t}\n\telse{\n\t\tif (ope_m1>ope_m2){\n\t\t\tif(GACDencrypted1>GACDencrypted2) std::cout << \"PASSED\" << std::endl;\n\t\t\telse std::cout << \"FAILED\" << std::endl;\n\t\t}\n\t\telse{\n\t\t\t//random order\n\t\t\tstd::cout << \"PASSED\" << std::endl;\n\t\t}\n\t}\n\n\t//Data for PolyACD tests\n\tint lambda = 80;\n\tint mu = 32;\n\tint cdegree = 10;\n\tint pdegree = 5;\n\tstd::mt19937 rng;\n\tunsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n\trng.seed(seed);\n\tNTL::ZZX ope_p1 = createRandomPoly(rng,mu,pdegree);\n\tPolyCiphertext polyp1(ope_p1);\n\tNTL::ZZX ope_p2 = createRandomPoly(rng,mu,pdegree);\n\tPolyCiphertext polyp2(ope_p2);\n\n\tstd::cout << \"PolyACD consistency test: \";\n\tPolyACDEncrypter PolyACDenc(lambda,mu,cdegree);\n\tstd::string PolyACDsecrets = PolyACDenc.writeSecretsToJSON();\n\tNTL::ZZX PolyACDencrypted1 = PolyACDenc.encrypt(ope_p1);\n\n\tPolyACDDecrypter PolyACDdec;\n\tPolyACDdec.readSecretsFromJSON(PolyACDsecrets);\n\tNTL::ZZX PolyACDdecrypted = PolyACDdec.decrypt(PolyACDencrypted1);\n\tif(ope_p1==PolyACDdecrypted) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"PolyACD order-preserving test: \";\n\tNTL::ZZX PolyACDencrypted2 = PolyACDenc.encrypt(ope_p2);\n\tPolyCiphertext polyc1(PolyACDencrypted1);\n\tPolyCiphertext polyc2(PolyACDencrypted2);\n\tif(polyp1 < polyp2){\n\t\tif(polyc1<polyc2) std::cout << \"PASSED\" << std::endl;\n\t\telse std::cout << \"FAILED\" << std::endl;\n\t}\n\telse{\n\t\tif (polyp1>polyp2){\n\t\t\tif(polyc1>polyc2) std::cout << \"PASSED\" << std::endl;\n\t\t\telse std::cout << \"FAILED\" << std::endl;\n\t\t}\n\t\telse{\n\t\t\t//random order\n\t\t\tstd::cout << \"PASSED\" << std::endl;\n\t\t}\n\t}\n\n\tstd::cout << \"======= Integer HE Tests =======\" << std::endl;\n\t//Data for HEx tests\n\tint n = 1000;\n\tint d = 2;\n\tint rho1=8;\n\tint rho2=32;\n\tint rhoprime=32;\n\n\tNTL::ZZ he_rho1_m1 = NTL::RandomBits_ZZ(rho1);\n\tNTL::ZZ he_rho1_m2 = NTL::RandomBits_ZZ(rho1);\n\tNTL::ZZ he_rho2_m1 = NTL::RandomBits_ZZ(rho2);\n\tNTL::ZZ he_rho2_m2 = NTL::RandomBits_ZZ(rho2);\n\tNTL::ZZ rho1_sum = he_rho1_m1+he_rho1_m2;\n\tNTL::ZZ rho1_product = he_rho1_m1*he_rho1_m2;\n\tNTL::ZZ rho2_sum = he_rho2_m1+he_rho2_m2;\n\tNTL::ZZ rho2_product = he_rho2_m1*he_rho2_m2;\n\n\tstd::cout << \"HE1 consistency test: \";\n\tHE1Encrypter he1enc(n,d,rho2);\n\the1enc.init();\n\t//NTL::ZZ he1key = he1enc.getKey();\n\tstd::string he1secrets = he1enc.writeSecretsToJSON();\n\tNTL::ZZ_p he1_c1 = he1enc.encrypt(he_rho2_m1);\n\n\tHE1Decrypter he1dec;\n\t//he1dec.setKey(he1key);\n\the1dec.readSecretsFromJSON(he1secrets);\n\the1dec.init();\n\tNTL::ZZ he1_m1 = he1dec.decrypt(he1_c1);\n\tif(he1_m1==he_rho2_m1) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"HE1 homomorphic tests:\" << std::endl;\n\tNTL::ZZ_p he1_c2 = he1enc.encrypt(he_rho2_m2);\n\tNTL::ZZ_p he1_sum = he1_c1+he1_c2;\n\tNTL::ZZ_p he1_product = he1_c1*he1_c2;\n\tNTL::ZZ he1_sum_dec = he1dec.decrypt(he1_sum);\n\tNTL::ZZ he1_product_dec = he1dec.decrypt(he1_product);\n\tstd::cout << \"\\t Sum: \";\n\tif(he1_sum_dec==rho2_sum) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\tstd::cout << \"\\t Product: \";\n\tif(he1_product_dec==rho2_product) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"HE1N consistency test: \";\n\tHE1NEncrypter he1nenc(n,d,rho1,rhoprime);\n\the1nenc.init();\n\t//NTL::vec_ZZ he1nkey = he1nenc.getKey();\n\tstd::string he1nsecrets = he1nenc.writeSecretsToJSON();\n\tNTL::ZZ_p he1n_c1 = he1nenc.encrypt(he_rho1_m1);\n\n\tHE1NDecrypter he1ndec;\n\t//he1ndec.setKey(he1nkey);\n\the1ndec.readSecretsFromJSON(he1nsecrets);\n\tNTL::ZZ he1n_m1 = he1ndec.decrypt(he1n_c1);\n\tif(he1n_m1==he_rho1_m1) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"HE1N homomorphic tests:\" << std::endl;\n\tNTL::ZZ_p he1n_c2 = he1nenc.encrypt(he_rho1_m2);\n\tNTL::ZZ_p he1n_sum = he1n_c1+he1n_c2;\n\tNTL::ZZ_p he1n_product = he1n_c1*he1n_c2;\n\tNTL::ZZ he1n_sum_dec = he1ndec.decrypt(he1n_sum);\n\tNTL::ZZ he1n_product_dec = he1ndec.decrypt(he1n_product);\n\tstd::cout << \"\\t Sum: \";\n\tif(he1n_sum_dec==rho1_sum) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\tstd::cout << \"\\t Product: \";\n\tif(he1n_product_dec==rho1_product) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"HE2 consistency test: \";\n\tHE2Encrypter he2enc(n,d,rho2);\n\the2enc.init();\n\tstd::string he2secrets = he2enc.writeSecretsToJSON();\n\tstd::string he2params = he2enc.writeParametersToJSON();\n\tNTL::vec_ZZ_p he2_c1 = he2enc.encrypt(he_rho2_m1);\n\n\tHE2Decrypter he2dec;\n\the2dec.readSecretsFromJSON(he2secrets);\n\tNTL::ZZ he2_m1 = he2dec.decrypt(he2_c1);\n\tif(he2_m1==he_rho2_m1) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"HE2 homomorphic tests:\" << std::endl;\n\tNTL::vec_ZZ_p he2_c2 = he2enc.encrypt(he_rho2_m2);\n\tHE2Ciphertext::setParameters(he2params);\n\tHE2Ciphertext he2c1(he2_c1);\n\tHE2Ciphertext he2c2(he2_c2);\n\tNTL::vec_ZZ_p he2_sum = (he2c1+he2c2).get_ciphertext();\n\tNTL::vec_ZZ_p he2_product = (he2c1*he2c2).get_ciphertext();\n\tNTL::ZZ he2_sum_dec = he2dec.decrypt(he2_sum);\n\tNTL::ZZ he2_product_dec = he2dec.decrypt(he2_product);\n\tstd::cout << \"\\t Sum: \";\n\tif(he2_sum_dec==rho2_sum) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\tstd::cout << \"\\t Product: \";\n\tif(he2_product_dec==rho2_product) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"HE2N consistency test: \";\n\tHE2NEncrypter he2nenc(n,d,rho1,rhoprime);\n\the2nenc.init();\n\tstd::string he2nsecrets = he2nenc.writeSecretsToJSON();\n\tstd::string he2nparams = he2nenc.writeParametersToJSON();\n\tNTL::vec_ZZ_p he2n_c1 = he2nenc.encrypt(he_rho1_m1);\n\n\tHE2NDecrypter he2ndec;\n\the2ndec.readSecretsFromJSON(he2nsecrets);\n\tNTL::ZZ he2n_m1 = he2ndec.decrypt(he2n_c1);\n\tif(he2n_m1==he_rho1_m1) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\n\tstd::cout << \"HE2N homomorphic tests:\" << std::endl;\n\tNTL::vec_ZZ_p he2n_c2 = he2nenc.encrypt(he_rho1_m2);\n\t//Fails in setParameters when initialising R\n\tHE2Ciphertext::setParameters(he2nparams);\n\tHE2Ciphertext he2nc1(he2n_c1);\n\tHE2Ciphertext he2nc2(he2n_c2);\n\tHE2Ciphertext he2ncsum = he2nc1+he2nc2;\n\tHE2Ciphertext he2ncproduct = he2nc1*he2nc2;\n\tNTL::vec_ZZ_p he2n_sum = he2ncsum.get_ciphertext();\n\tNTL::vec_ZZ_p he2n_product = (he2nc1*he2nc2).get_ciphertext();\n\tNTL::ZZ he2n_sum_dec = he2ndec.decrypt(he2n_sum);\n\tNTL::ZZ he2n_product_dec = he2ndec.decrypt(he2n_product);\n\tstd::cout << \"\\t Sum: \";\n\tif(he2n_sum_dec==rho1_sum) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n\tstd::cout << \"\\t Product: \";\n\tif(he2n_product_dec==rho1_product) std::cout << \"PASSED\" << std::endl;\n\telse std::cout << \"FAILED\" << std::endl;\n}\n\n", "meta": {"hexsha": "ea05e3e08206cb4d8b5766415f054aa68a30a232", "size": 10435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/main.cpp", "max_stars_repo_name": "TANGO-Project/cryptsdc", "max_stars_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/main.cpp", "max_issues_repo_name": "TANGO-Project/cryptsdc", "max_issues_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/main.cpp", "max_forks_repo_name": "TANGO-Project/cryptsdc", "max_forks_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.990228013, "max_line_length": 77, "alphanum_fraction": 0.6970771442, "num_tokens": 3785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.6122358579001271}}
{"text": "#include <dlib/matrix.h>\n#include <dlib/svm_threaded.h>\n#include <plot.h>\n\n#include <experimental/filesystem>\n#include <iostream>\n#include <map>\n\nusing namespace dlib;\nnamespace fs = std::experimental::filesystem;\n\nconst std::vector<std::string> data_names{\"dataset0.csv\", \"dataset1.csv\",\n                                          \"dataset2.csv\", \"dataset3.csv\",\n                                          \"dataset4.csv\"};\n\nconst std::vector<std::string> colors{\"red\", \"green\", \"blue\", \"cyan\", \"black\"};\n\nusing DataType = double;\nusing Coords = std::vector<DataType>;\nusing PointCoords = std::pair<Coords, Coords>;\nusing Classes = std::map<size_t, PointCoords>;\n\nusing SampleType = matrix<DataType, 2, 1>;\nusing Samples = std::vector<SampleType>;\nusing Labels = std::vector<DataType>;\n\nvoid PlotClasses(const Classes& classes,\n                 const std::string& name,\n                 const std::string& file_name) {\n  plotcpp::Plot plt(true);\n  // plt.SetTerminal(\"qt\");\n  plt.SetTerminal(\"png\");\n  plt.SetOutput(file_name);\n  plt.SetTitle(name);\n  plt.SetXLabel(\"x\");\n  plt.SetYLabel(\"y\");\n  plt.SetAutoscale();\n  plt.GnuplotCommand(\"set grid\");\n\n  auto draw_state = plt.StartDraw2D<Coords::const_iterator>();\n  for (auto& cls : classes) {\n    std::stringstream params;\n    params << \"lc rgb '\" << colors[cls.first] << \"' pt 7\";\n    plt.AddDrawing(\n        draw_state,\n        plotcpp::Points(cls.second.first.begin(), cls.second.first.end(),\n                        cls.second.second.begin(),\n                        std::to_string(cls.first) + \" cls\", params.str()));\n  }\n\n  plt.EndDraw2D(draw_state);\n  plt.Flush();\n}\n\nvoid KRRClassification(const Samples& samples,\n                       const Labels& labels,\n                       const Samples& test_samples,\n                       const Labels& test_labels,\n                       const std::string& name) {\n  using OVOtrainer = one_vs_one_trainer<any_trainer<SampleType>>;\n  using KernelType = radial_basis_kernel<SampleType>;\n\n  krr_trainer<KernelType> krr_trainer;\n  krr_trainer.set_kernel(KernelType(0.1));\n\n  OVOtrainer trainer;\n  trainer.set_trainer(krr_trainer);\n\n  one_vs_one_decision_function<OVOtrainer> df = trainer.train(samples, labels);\n\n  Classes classes;\n  DataType accuracy = 0;\n  for (size_t i = 0; i != test_samples.size(); i++) {\n    auto vec = test_samples[i];\n    auto class_idx = static_cast<size_t>(df(vec));\n    if (static_cast<size_t>(test_labels[i]) == class_idx)\n      ++accuracy;\n    classes[class_idx].first.push_back(vec(0, 0));\n    classes[class_idx].second.push_back(vec(1, 0));\n  }\n\n  accuracy /= test_samples.size();\n\n  PlotClasses(classes, \"Kernel Ridge Regression \" + std::to_string(accuracy),\n              name + \"-krr-dlib.png\");\n}\n\nvoid SVMClassification(const Samples& samples,\n                       const Labels& labels,\n                       const Samples& test_samples,\n                       const Labels& test_labels,\n                       const std::string& name) {\n  using OVOtrainer = one_vs_one_trainer<any_trainer<SampleType>>;\n  using KernelType = radial_basis_kernel<SampleType>;\n\n  svm_nu_trainer<KernelType> svm_trainer;\n  svm_trainer.set_kernel(KernelType(0.1));\n\n  OVOtrainer trainer;\n  trainer.set_trainer(svm_trainer);\n\n  one_vs_one_decision_function<OVOtrainer> df = trainer.train(samples, labels);\n\n  Classes classes;\n  DataType accuracy = 0;\n  for (size_t i = 0; i != test_samples.size(); i++) {\n    auto vec = test_samples[i];\n    auto class_idx = static_cast<size_t>(df(vec));\n    if (static_cast<size_t>(test_labels[i]) == class_idx)\n      ++accuracy;\n    classes[class_idx].first.push_back(vec(0, 0));\n    classes[class_idx].second.push_back(vec(1, 0));\n  }\n\n  accuracy /= test_samples.size();\n\n  PlotClasses(classes, \"SVM \" + std::to_string(accuracy),\n              name + \"-svm-dlib.png\");\n}\n\nint main(int argc, char** argv) {\n  if (argc > 1) {\n    auto base_dir = fs::path(argv[1]);\n    for (auto& dataset : data_names) {\n      auto dataset_name = base_dir / dataset;\n      if (fs::exists(dataset_name)) {\n        std::ifstream file(dataset_name);\n        matrix<DataType> data;\n        file >> data;\n\n        auto inputs = dlib::subm(data, 0, 1, data.nr(), 2);\n        auto outputs = dlib::subm(data, 0, 3, data.nr(), 1);\n\n        auto num_samples = inputs.nr();\n        auto num_features = inputs.nc();\n        std::size_t num_clusters =\n            std::set<double>(outputs.begin(), outputs.end()).size();\n\n        std::cout << dataset << \"\\n\"\n                  << \"Num samples: \" << num_samples\n                  << \" num features: \" << num_features\n                  << \" num clusters: \" << num_clusters << std::endl;\n\n        // split data set to the train and test parts\n        long test_num = 300;\n        Samples test_samples;\n        Labels test_labels;\n        {\n          for (long row = 0; row < test_num; ++row) {\n            test_samples.emplace_back(dlib::reshape_to_column_vector(\n                dlib::subm_clipped(inputs, row, 0, 1, data.nc())));\n\n            test_labels.emplace_back(outputs(row, 0));\n          }\n        }\n\n        std::vector<SampleType> samples;\n        Labels labels;\n        {\n          for (long row = test_num; row < inputs.nr(); ++row) {\n            samples.emplace_back(dlib::reshape_to_column_vector(\n                dlib::subm_clipped(inputs, row, 0, 1, data.nc())));\n            labels.emplace_back(outputs(row, 0));\n          }\n        }\n\n        // SVMClassification(samples, labels, test_samples, test_labels,\n        // dataset);\n        KRRClassification(samples, labels, test_samples, test_labels, dataset);\n      } else {\n        std::cerr << \"Dataset file \" << dataset_name << \" missed\\n\";\n      }\n    }\n  } else {\n    std::cerr << \"Please provider path to the datasets folder\\n\";\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "ba62bacb2ec75037d72a6575248b99ddca00dbff", "size": 5791, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter07/dlib/dlib-classify.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter07/dlib/dlib-classify.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter07/dlib/dlib-classify.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 32.1722222222, "max_line_length": 79, "alphanum_fraction": 0.6050768434, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6122085170340804}}
{"text": "/*\n * GridTools\n *\n * Copyright (c) 2014-2019, ETH Zurich\n * All rights reserved.\n *\n * Please, refer to the LICENSE file in the root directory.\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n#include <boost/mpl/arithmetic.hpp>\n#include <boost/mpl/comparison.hpp>\n#include <gridtools/common/defs.hpp>\n#include <gridtools/common/generic_metafunctions/mpl_tags.hpp>\n#include <gtest/gtest.h>\n\nTEST(integralconstant, comparison) {\n    GT_STATIC_ASSERT(\n        (boost::mpl::greater<std::integral_constant<int, 5>, std::integral_constant<int, 4>>::type::value), \"\");\n\n    GT_STATIC_ASSERT(\n        (boost::mpl::less<std::integral_constant<int, 4>, std::integral_constant<int, 5>>::type::value), \"\");\n\n    GT_STATIC_ASSERT(\n        (boost::mpl::greater_equal<std::integral_constant<int, 5>, std::integral_constant<int, 4>>::type::value), \"\");\n\n    GT_STATIC_ASSERT(\n        (boost::mpl::less_equal<std::integral_constant<int, 4>, std::integral_constant<int, 5>>::type::value), \"\");\n}\n\nTEST(integralconstant, arithmetic) {\n    GT_STATIC_ASSERT(\n        (boost::mpl::plus<std::integral_constant<int, 5>, std::integral_constant<int, 4>>::type::value == 9), \"\");\n    GT_STATIC_ASSERT(\n        (boost::mpl::minus<std::integral_constant<int, 5>, std::integral_constant<int, 4>>::type::value == 1), \"\");\n}\n", "meta": {"hexsha": "e8059801baf3cbd6fd41d2a99a080cd894dbf96e", "size": 1292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/common/generic_metafunctions/test_mpl_tags.cpp", "max_stars_repo_name": "mbianco/gridtools", "max_stars_repo_head_hexsha": "1abef09881a31495a3d02a15d3fe21620c6dde98", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/common/generic_metafunctions/test_mpl_tags.cpp", "max_issues_repo_name": "mbianco/gridtools", "max_issues_repo_head_hexsha": "1abef09881a31495a3d02a15d3fe21620c6dde98", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/common/generic_metafunctions/test_mpl_tags.cpp", "max_forks_repo_name": "mbianco/gridtools", "max_forks_repo_head_hexsha": "1abef09881a31495a3d02a15d3fe21620c6dde98", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T10:35:50.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-14T10:35:50.000Z", "avg_line_length": 34.9189189189, "max_line_length": 118, "alphanum_fraction": 0.6787925697, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.61220851649808}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <math/prim/mat/prob/vector_rng_test_helper.hpp>\n#include <math/prim/mat/prob/VectorIntRNGTestRig.hpp>\n#include <limits>\n#include <vector>\n\nclass BernoulliLogitTestRig : public VectorIntRNGTestRig {\n public:\n  BernoulliLogitTestRig()\n      : VectorIntRNGTestRig(10000, 10, {0, 1},\n                            {-5.7, -1.0, 0.0, 0.2, 1.0, 10.0}, {-3, -2, 0, 1},\n                            {}, {}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& t, const T2&, const T3&, T_rng& rng) const {\n    return stan::math::bernoulli_logit_rng(t, rng);\n  }\n\n  template <typename T1>\n  double pmf(int y, T1 t, double, double) const {\n    return std::exp(stan::math::bernoulli_logit_lpmf(y, t));\n  }\n};\n\nTEST(ProbDistributionsBernoulliLogit, errorCheck) {\n  check_dist_throws_all_types(BernoulliLogitTestRig());\n}\n\nTEST(ProbDistributionsBernoulliLogit, distributionCheck) {\n  check_counts_real(BernoulliLogitTestRig());\n}\n", "meta": {"hexsha": "db4e1641f479cd59b111cc54a15e17fe0eb421b8", "size": 1117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/mat/prob/bernoulli_logit_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/prim/mat/prob/bernoulli_logit_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/prim/mat/prob/bernoulli_logit_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9142857143, "max_line_length": 78, "alphanum_fraction": 0.6902417189, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.6122085113637686}}
{"text": "#include <opencv2/opencv.hpp>\n#include <sophus/se3.hpp>\n#include <boost/format.hpp>\n#include <ceres/ceres.h>\n#include <chrono>\n\nusing namespace std;\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\n\n// Camera intrinsics\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n\n// baseline\ndouble baseline = 0.573;\n// paths\nstring left_file = \"../left.png\";\nstring disparity_file = \"../disparity.png\";\nboost::format fmt_others(\"../%06d.png\");    // other files\n\n// useful typedefs\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\ntypedef Eigen::Matrix<double, 2, 6> Matrix26d;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n\n// bilinear interpolation\ninline float get(const cv::Mat &img, float x, float y) {\n    // boundary check\n    if (x < 0) x = 0;\n    if (y < 0) y = 0;\n    if (x >= img.cols) x = img.cols - 1;\n    if (y >= img.rows) y = img.rows - 1;\n    uchar *data = &img.data[int(y) * img.step + int(x)];\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n    return float(\n        (1 - xx) * (1 - yy) * data[0] +\n        xx * (1 - yy) * data[1] +\n        (1 - xx) * yy * data[img.step] +\n        xx * yy * data[img.step + 1]\n    );\n}\n\nEigen::Vector3d get_3D_point_from_depth(const Eigen::Vector2d& p, double depth)\n{\n    return Eigen::Vector3d(depth * (p.x() - cx) / fx,\n                           depth * (p.y() - cy) / fy,\n                           depth);\n}\n\n\nusing namespace Sophus;\n// Local parameterization needed to handle SE3 from Sophus (from Sophus/test/ceres/)\nclass LocalParameterizationSE3 : public ceres::LocalParameterization {\n public:\n  virtual ~LocalParameterizationSE3() {}\n\n  // SE3 plus operation for Ceres\n  //\n  //  T * exp(x)\n  //\n  virtual bool Plus(double const* T_raw, double const* delta_raw,\n                    double* T_plus_delta_raw) const {\n    Eigen::Map<SE3d const> const T(T_raw);\n    Eigen::Map<Vector6d const> const delta(delta_raw);\n    Eigen::Map<SE3d> T_plus_delta(T_plus_delta_raw);\n    T_plus_delta = T * SE3d::exp(delta); ///// check if good left or righ multiply ??????????????????\n    // std::cout << (SE3d::exp(delta) * T).matrix() << \"\\n\";\n    // std::cout << (T * SE3d::exp(delta)).matrix() << \"\\n\\n\";\n    return true;\n  }\n\n  // Jacobian of SE3 plus operation for Ceres\n  //\n  // Dx T * exp(x)  with  x=0\n  //\n  virtual bool ComputeJacobian(double const* T_raw,\n                               double* jacobian_raw) const {\n    Eigen::Map<SE3d const> T(T_raw);\n    Eigen::Map<Eigen::Matrix<double, 7, 6, Eigen::RowMajor>> jacobian(\n        jacobian_raw);\n    jacobian = T.Dx_this_mul_exp_x_at_0();\n    return true;\n  }\n\n  virtual int GlobalSize() const { return SE3d::num_parameters; }\n\n  virtual int LocalSize() const { return SE3d::DoF; }\n};\n\nstruct PhotometricError: public ceres::SizedCostFunction<1, 7>\n{\n    PhotometricError(const cv::Mat& img1, const cv::Mat& img2, const Eigen::Vector2d& p1, const Eigen::Vector3d& P1, const Eigen::Matrix3d& K)\n    : _img1(img1), _img2(img2), _p1(p1), _P1(P1), _K(K) {}\n\n    virtual bool Evaluate(double const* const *params,\n                          double *residuals,\n                          double **jacobians) const {\n        const Eigen::Map<const Sophus::SE3d> Rt(params[0]);\n\n        Eigen::Vector3d P2 = Rt * _P1;\n        Eigen::Vector3d p2 = _K * P2;\n        p2 /= p2.z();\n\n        double v1 = get(_img1, _p1.x(), _p1.y());\n        double v2 = get(_img2, p2.x(), p2.y());\n        double err = v1 - v2;\n        residuals[0] = err;\n\n        if (!jacobians) return true;\n        if (!jacobians[0]) return true;\n\n        double fx = _K(0, 0);\n        double fy = _K(1, 1);\n        double cx = _K(0, 2);\n        double cy = _K(1, 2);\n        double X2 = std::pow(P2.x(), 2);\n        double Y2 = std::pow(P2.y(), 2);\n        double Z2 = std::pow(P2.z(), 2);\n\n\n        int xx = 0, yy = 0;\n        double dx = 0.5 * (get(_img2, p2.x() + xx + 1, p2.y() + yy) - get(_img2, p2.x() + xx - 1, p2.y() + yy));\n        double dy = 0.5 * (get(_img2, p2.x() + xx, p2.y() + yy + 1) - get(_img2, p2.x() + xx, p2.y() + yy - 1));\n        Eigen::Vector2d dIdu(dx, dy);\n        Eigen::Matrix<double, 2, 6> dudRt;\n        dudRt << fx/P2.z(), 0.0, -fx*P2.x() / Z2,-fx * P2.x() * P2.y() / Z2, fx + fx * X2 / Z2, -fx * P2.y() / P2.z(),\n                 0.0, fy / P2.z(), -fy*P2.y()/Z2, -fy-fy * Y2 / Z2, fy * P2.x() * P2.y() / Z2, fy * P2.x() / P2.z();\n        Eigen::Matrix<double, 6, 1> J = -(dIdu.transpose() * dudRt).transpose();\n        jacobians[0][0] = J(0, 0);\n        jacobians[0][1] = J(1, 0);\n        jacobians[0][2] = J(2, 0);\n        jacobians[0][3] = J(3, 0);\n        jacobians[0][4] = J(4, 0);\n        jacobians[0][5] = J(5, 0);\n        jacobians[0][6] = 0.0;\n\n        return true;\n    }\n\n    private:\n        cv::Mat _img1, _img2;\n        Eigen::Vector2d _p1;\n        Eigen::Vector3d _P1;\n        Eigen::Matrix3d _K;\n};\n\n\n/**\n * pose estimation using direct method\n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationSingleLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,\n    const Eigen::Matrix3d& K,\n    Sophus::SE3d &Rt // points from cam1 reference frame to cam2\n)\n{\n    int nb_iters = 10;\n    int half_w_size = 2;\n    double prev_cost = 0.0;\n\n    ceres::Problem problem;\n\n    problem.AddParameterBlock(Rt.data(), 7, new LocalParameterizationSE3());\nstd::cout << \"AFTER add parameters bloxk\" << std::endl;\n    for (int i = 0; i < px_ref.size(); ++i)\n    {\n        const auto& p1 = px_ref[i];\n        Eigen::Vector3d P1 = get_3D_point_from_depth(p1, depth_ref[i]);\n        problem.AddResidualBlock(\n            new PhotometricError(img1, img2, p1, P1, K),\n            nullptr,\n            Rt.data()\n        );\n    }\nstd::cout << \"AFTER ad dresiduals block\" << std::endl;\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\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    ceres::Solve(options, &problem, &summary);\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double >>(t2 - t1);\n    cout << \"optimization with ceres costs time: \" << time_used.count() << \" seconds.\" << endl;\n    \n\n    std::cout << \"translation: \" << Rt.translation().transpose() << \"\\n\";\n    std::cout << \"rotation: \" << Rt.so3().unit_quaternion().toRotationMatrix() << \"\\n\";\n\n}\n\n\nvoid DirectPoseEstimationPyramidal(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,\n    const Eigen::Matrix3d& K,\n    Sophus::SE3d &Rt)\n{\n    int nb_levels = 1;\n    double factor = 2.0;\n    double scale = 1.0 / std::pow(factor, nb_levels-1);\n\n\n    for (int l = 0; l < nb_levels; ++l)\n    {\n        cv::Mat img1_r, img2_r;\n        cv::resize(img1, img1_r, cv::Size(), scale, scale);\n        cv::resize(img2, img2_r, cv::Size(), scale, scale);\n\n        Eigen::Matrix3d K_r = K;\n        K_r(0, 0) *= scale;\n        K_r(1, 1) *= scale;\n        K_r(0, 2) *= scale;\n        K_r(1, 2) *= scale;\n        auto p_r = px_ref;\n        for (auto& p : p_r)\n        {\n            p *= scale;\n        }\n\n        DirectPoseEstimationSingleLayer(img1_r, img2_r, p_r, depth_ref, K_r, Rt);\n\n        scale *= factor;\n    }\n}\n\n\nint main(int argc, char **argv) {\n\n    cv::Mat left_img = cv::imread(left_file, 0);\n    cv::Mat disparity_img = cv::imread(disparity_file, 0);\n\n    // let's randomly pick pixels in the first image and generate some 3d points in the first image's frame\n    cv::RNG rng(1994);\n    int nPoints = 2000;\n    int boarder = 20;\n    VecVector2d pixels_ref;\n    vector<double> depth_ref;\n\n\n    // generate pixels in ref and load depth data\n    for (int i = 0; i < nPoints; i++) {\n        int x = rng.uniform(boarder, left_img.cols - boarder);  // don't pick pixels close to boarder\n        int y = rng.uniform(boarder, left_img.rows - boarder);  // don't pick pixels close to boarder\n        int disparity = disparity_img.at<uchar>(y, x);\n        double depth = fx * baseline / disparity; // you know this is disparity to depth\n        depth_ref.push_back(depth);\n        pixels_ref.push_back(Eigen::Vector2d(x, y));\n    }\n\n    // estimates 01~05.png's pose using this information\n    Sophus::SE3d Rt;\n    Eigen::Matrix3d K;\n    K << fx, 0.0, cx,\n         0.0, fy, cy,\n         0.0, 0.0, 1.0;\n\n    for (int i = 1; i < 2; i++) {  // 1~10\n        cv::Mat img = cv::imread((fmt_others % i).str(), 0);\n        // try single layer by uncomment this line\n        DirectPoseEstimationSingleLayer(left_img, img, pixels_ref, depth_ref, K, Rt);\n        // DirectPoseEstimationPyramidal(left_img, img, pixels_ref, depth_ref, K, Rt);\n\n\n        // plot the projected pixels here\n        cv::Mat img2_show;\n        cv::cvtColor(img, img2_show, CV_GRAY2BGR);\n        std::vector<Eigen::Vector2d> projections(pixels_ref.size());\n        for (int i = 0; i < pixels_ref.size(); ++i)\n        {\n            Eigen::Vector3d P_ref = get_3D_point_from_depth(pixels_ref[i], depth_ref[i]);\n            Eigen::Vector3d uv = K * (Rt * P_ref);\n            projections[i] = uv.hnormalized();\n        }\n\n        for (size_t i = 0; i < pixels_ref.size(); ++i) {\n            auto p_ref = pixels_ref[i];\n            auto p_cur = projections[i];\n            if (p_cur[0] > 0 && p_cur[1] > 0) {\n                cv::circle(img2_show, cv::Point2f(p_cur[0], p_cur[1]), 2, cv::Scalar(0, 250, 0), 2);\n                cv::line(img2_show, cv::Point2f(p_ref[0], p_ref[1]), cv::Point2f(p_cur[0], p_cur[1]),\n                        cv::Scalar(0, 250, 0));\n            }\n        }\n        cv::imshow(\"current\", img2_show);\n        cv::waitKey();\n        // cv::imwrite(\"img_\"+std::to_string(i) + \".png\", img2_show);\n\n    }\n    return 0;\n}\n", "meta": {"hexsha": "3e5a8ce8bcb239e535ccaa3f5f5bda8ebd61a12d", "size": 9964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch8/direct_method_ceres copy.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch8/direct_method_ceres copy.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch8/direct_method_ceres copy.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4560260586, "max_line_length": 142, "alphanum_fraction": 0.570754717, "num_tokens": 3181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.612208506229457}}
{"text": "//rego: Automatic time series forecasting and missing value imputation.\n//\n//Copyright (C) Davide Altomare and David Loris <https://channelattribution.io>\n//\n//This source code is licensed under the MIT license found in the\n//LICENSE file in the root directory of this source tree. \n\n#define language_cpp \n//#define language_python\n//#define language_R\n\n#include <iostream>\n#include <vector>\n#include <set>\n#include <math.h>\n#include <time.h>\n#include <stdio.h>\n#include <sstream>\n#include <list>\n#include <string>\n#include <random>\n#include <numeric>\n#include <time.h> \n#include <thread>\n#include <map>\n#include <algorithm>\n#include <list>\n#include <limits> \n#include <functional>\n#include <ctime>\n\n\n#define OPTIM_ENABLE_ARMA_WRAPPERS\n#ifdef language_py\n  #ifdef _WIN32\n    #define ARMA_DONT_USE_LAPACK\n    #define ARMA_DONT_USE_BLAS\n  #endif\n#endif\n#define ARMA_USE_CXX11\n#define ARMA_64BIT_WORD\n#define ARMA_DONT_PRINT_ERRORS\n\n#include <armadillo>\n#include <optim.hpp>\n\n#ifdef language_R\n #define __GXX_EXPERIMENTAL_CXX0X__ 1\n\n #include <Rcpp.h>\n //#include <RcppArmadillo.h>\n //#define USE_RCPP_ARMADILLO\n \n #ifndef BEGIN_RCPP\n #define BEGIN_RCPP\n #endif\n  \n #ifndef END_RCPP\n #define END_RCPP\n #endif\n \n using namespace Rcpp;\n#endif\n\n\n#ifdef language_py\n #include <Python.h>\n#endif\n\n\nusing namespace std;\nusing namespace arma;\n\n\n#define uli unsigned long int\nusing svec1=vector<double>;\nusing svec2=vector< vector <double> >;\nusing svec3=vector < vector< vector <double> > >;\nusing svec4=vector < vector < vector< vector <double> > > >;\n\n\n//------------------------------------------------------------------------------------------------------------------------\n//GENERAL FUNCTIONS\n//------------------------------------------------------------------------------------------------------------------------\n\n\ndouble lfactorial(uli n)\n{\n  \n double x;\n\n x=lgamma(n+1);\n\n return(x);\n\n} //end function\n\n\ndouble lchoose(uli n, uli k)\n{\n  \n  double x;\n  \n  x=lgamma(n+1)-lgamma(k+1)-lgamma(n-k+1);\n\n  return(x);\n\n} //end function\n\n\nmat sub_mat(mat* M, vec vr, vec vc)\n{\n  uli r, c, lvr, lvc;\n  lvr=vr.n_elem;\n  lvc=vc.n_elem;\n  mat Q(lvr,lvc);\n\n  for(c=0; c<lvc; c++){\n   for(r=0; r<lvr; r++){ \n    Q(r,c)=(*M)(vr(r),vc(c)); \n   }\n  }\n\n  return Q;\n\n} //end function\n\n\nmat pow_vec(vec* v, vec* w)\n{\n\n   uli k, lv; \n   vec vv;\n\n   lv=(*v).n_elem;\n   vv=zeros<vec>(lv);\n\n   for(k=0; k<lv; k++){\n    vv(k)=pow((*v)(k),(*w)(k));\n   }\n\n return vv;\n\n}\n\nmat Cholesky(mat* M)\n{\n    double n=(*M).n_rows;\n    mat lower(n,n);\n \n    // Decomposing a matrix into Lower Triangular\n    for (uli i = 0; i < n; i++) {\n        for (uli j = 0; j <= i; j++) {\n            uli sum = 0;\n \n            if (j == i) // summation for diagonals\n            {\n                for (uli k = 0; k < j; k++){\n                    sum += pow(lower(j,k), 2);\n                    lower(j,j) = sqrt((*M)(j,j) - sum);\n                }\n            } else {\n \n                // Evaluating L(i, j) using L(j, j)\n                for (uli k = 0; k < j; k++){\n                    sum += (lower(i,k) * lower(j,k));\n                    lower(i,j) = ((*M)(i,j) - sum) / lower(j,j);\n                }\n            }\n        }\n    }\n\n    return(lower);\n \n}\n\n\nvec forward_sub(mat* L, vec* b)\n{\n    /*x = forward_sub(L, b) is the solution to L x = b\n       L must be a lower-triangular matrix\n       b must be a vector of the same leading dimension as L\n    */\n    \n    double n = (*L).n_cols;\n    vec x = zeros<vec>(n);\n    double tmp;\n    for(double i=0; i<n; ++i){\n        tmp = (*b)(i);\n         for(double j=0; j<i; ++j){\n          tmp -= (*L)(i,j) * x(j);\n         }\n\n        x(i) = tmp / (*L)(i,i);\n    }\n    return(x);\n}\n\nvec back_sub(mat* U, vec* b)\n{\n    /*x = back_sub(U, b) is the solution to U x = b\n       U must be an upper-triangular matrix\n       b must be a vector of the same leading dimension as U\n    */\n    \n    double n = (*U).n_cols; //it must be double\n    vec x = zeros<vec>(n);\n    double tmp;\n    for(double i=n-1; i>=0; i--){\n      tmp = (*b)(i);\n       for(uli j=i; j<n; ++j){\n        tmp -= (*U)(i,j) * x(j);\n        x(i) = tmp / (*U)(i,i);\n       }\n    }\n\n    return(x);\n\n}\n\nvec solve0(mat* A, vec* b){\n \n  mat L=Cholesky(A);\n  mat Lt=trans(L);\n\n  vec vy=forward_sub(&L,b);\n  vec vx=back_sub(&Lt, &vy);\n  \n  return(vx);\n\n}\n\nvec solve_linear(mat* A, vec* b){\n  \n #ifdef ARMA_DONT_USE_LAPACK\n  return(solve0(A,b));\n #else\n  return(solve(*A,*b));\n #endif\n \n\n}\n\n\n//------------------------------------------------------------------------------------------------------------------------\n//FUNCTIONS FOR STORING MODELS IN A BINARY TREE\n//------------------------------------------------------------------------------------------------------------------------\n\n//this function add a model \"M\" to \"tree\"\n\nfield<mat> add_to_tree(vec* M, double lM, uli nM, mat* tree, double ltree)\n{\n\n uli j,k;\n\n field<mat> Res(2,1);\n\n if(nM==0){\n    \n  for(j=0; j<=lM; j++){\n \n   if((*M)(j)==1){(*tree)(j,0)=j+1;}\n   else{(*tree)(j,1)=j+1;}\n \n  }\n \n  ltree=lM; \n  (*tree).row(ltree)=(*tree).row(ltree)*0+nM;\n\n }\n\n uli z,h,iM=0;\n\n if(nM>0){ //if1\n   \n  z=0;\n  h=ltree+1;\n  \n  for(j=0; j<=lM; j++){ //for1  \n  \n   iM=1-(*M)(j);\n      \n   if(!is_finite((*tree)(z,iM)) && (j<=lM) ){ //if2\n     \n    (*tree)(z,iM)=h;\n     \n    for(k=(j+1); k<=lM; k++){ //for2\n  \n      if((*M)(k)==1){(*tree)(h,0)=h+1;} else{(*tree)(h,1)=h+1;}\n      \n      h=h+1;\n    \n    } //end for2    \n\n    iM=1-(*M)(lM);\n    ltree=h-1;\n    break;\n   \n   } //end if2\n \n   if(j==lM){(*tree)(z,iM)=nM; ltree=ltree+1; break;}\n  \n   if((*tree)(z,iM)>=0){z=(*tree)(z,iM);}\n  \n  } //end for1\n  \n\n  (*tree)(ltree,iM)=(*tree)(ltree,iM)*0+nM;\n\n } //end if1\n\n\n Res(0,0)=(*tree);\n Res(1,0)=ltree;\n\n return Res;\n\n} //end function\n\n\n//this function returns the possible movements from a model \"M\", given all the previous models visited and stored in \"tree\"\n\nvec mov_tree(mat* tree, vec* M, uli lM, vec* vlM, uli max_lM)\n{\n\n uli q, k, z, h, iM2;\n double sumM;\n vec mov(lM+1); \n uvec imov, umov; \n vec mov2, M2;\n \n \n mov.fill(-1);\n sumM=sum(*M);\n q=0;\n\n for(k=0; k<=lM; k++){ //for1\n  \n  M2=(*M); \n  M2(k)=1-(*M)(k);\n  z=0;\n  \n  for(h=0; h<=lM; h++){ //for2\n    \n   iM2=1-M2(h);\n   if(!is_finite((*tree)(z,iM2))){mov(q)=k; q=q+1; break;} else{z=(*tree)(z,iM2);}\n   \n    } //end for2\n  \n \n } //end for1\n\n imov=find(mov>-1);\n \n if(!imov.is_empty()){\n \n  mov=mov.elem(imov);\n  umov=conv_to<uvec>::from(mov);\n\n  if(sumM>=max_lM){\n  \n   mov2=zeros<vec>(lM+1);\n   mov2.elem(umov)=ones<vec>(mov.n_elem);\n   mov=(mov2%(*M))%(*vlM);\n   imov=find(mov>0);\n   if(!imov.is_empty()){mov=mov.elem(imov); mov=mov-1;} else{mov=datum::nan;}\n  }\n\n } else {mov=datum::nan;}\n \n\n return mov;\n\n} //end function\n\n\n\n//------------------------------------------------------------------------------------------------------------------------\n//FUNCTIONS FOR BAYESIAN STOCHASTIC SEARCH\n//------------------------------------------------------------------------------------------------------------------------\n\n\ndouble log_H_h_i(double mu, double sigma, double h, double i)\n{\n\n double x;\n\n x=lfactorial(2*h)+i*log(sigma)-lfactorial(i)+(2*h-2*i)*log(abs(mu))-lfactorial(2*h-2*i);\n\n return x;\n\n} //end function\n\n\n\ndouble log_FBF_Ga_Gb(vec* G_a, vec* G_b, uli edge, mat* edges, mat* YtY, uli add, double n, double h)\n{\n  \n  uli e1, e2, iwi;\n  double i, p, b, S2, mu, sigma, logS2, ilogS2, logHhi, ilog4, log_num1, log_den1, log_w_1, log_num0i0, log_den0i0, log_w_0, log_FBF_unpasso;\n  vec V1, V2, G1, V11, pa1, pa0, betah, vv(1), z1;\n  uvec iw, ipa1;\n  mat e, yty, XtX, invXtX;   \n  vec Xty;\n  \n  e=(*edges).row(edge);\n  e1=e(0);\n  e2=e(1);\n\n  V1=(*edges).col(0);\n  V2=(*edges).col(1);\n    \n  if(add==1){G1=(*G_a);}else{G1=(*G_b);}\n\n  V11=(V1+1)%G1;\n  iw=find(V2==e2); pa1=V11.elem(iw);\n  iw=find(pa1>0); pa1=pa1.elem(iw); pa1=pa1-1;\n \n  iw=find(pa1!=e1); if(!iw.is_empty()){pa0=pa1.elem(iw);}else{pa0=datum::nan;}\n \n  p=pa1.n_elem;\n  b=(p+2*h+1)/n;\n\n  yty=(*YtY)(e2,e2);\n    \n  // //calcolo w1\n   \n  vv(0)=e2; Xty=conv_to<vec>::from(sub_mat(YtY,pa1,vv));\n  XtX=sub_mat(YtY,pa1,pa1);\n  betah=solve_linear(&XtX,&Xty);\n\n  S2=conv_to<double>::from(yty-(trans(Xty)*betah));\n  \n  iw=find(pa1==e1); mu=conv_to<double>::from(betah.elem(iw));\n  iwi=conv_to<uli>::from(iw); \n  z1=zeros<vec>(pa1.n_elem);\n  z1(iwi)=1;\n  z1=solve_linear(&XtX,&z1);\n  \n  sigma=conv_to<double>::from(z1.elem(iw));\n  \n  if(S2>0){\n   log_w_1=(-n*(1-b)/2)*log(datum::pi*b*S2);\n   logS2=log(S2);\n   log_num1=-datum::inf;\n   log_den1=-datum::inf;\n\n   for(i=0; i<=h; i++){\n   \n    ilogS2=i*logS2;\n    logHhi=log_H_h_i(mu,sigma,h,i);\n    ilog4=-i*log(4);\n      \n    log_num1=log_add(log_num1, (ilog4+logHhi+lgamma((n-p-2*i)/2)+ilogS2));\n    log_den1=log_add(log_den1, (ilog4+logHhi+lgamma((n*b-p-2*i)/2)+ilogS2));\n\n   }\n    \n   log_w_1=log_w_1+log_num1-log_den1;\n  }else{\n   log_w_1=datum::inf;\n  }\n     \n  //calcolo w0\n\n  if(!pa0.is_finite()){p=0;}else{p=pa0.n_elem;}\n\n  log_num0i0=lgamma((n-p)/2);\n  log_den0i0=lgamma((n*b-p)/2);\n\n  if(p==0){S2=conv_to<double>::from(yty);}\n  else{\n   vv(0)=e2; Xty=conv_to<vec>::from(sub_mat(YtY,pa0,vv));\n   XtX=sub_mat(YtY,pa0,pa0);\n   betah=solve_linear(&XtX,&Xty); \n\n   S2=conv_to<double>::from(yty-(trans(Xty)*betah));\n  }\n\n  if(S2>0){\n   log_w_0=(-(n*(1-b)/2))*log(datum::pi*b*S2)+log_num0i0-log_den0i0;\n  }else{\n   log_w_0=datum::inf;\n  }\n  \n  //calcolo FBF\n\n  if(add==1){log_FBF_unpasso=log_w_1-log_w_0;}\n  else{log_FBF_unpasso=log_w_0-log_w_1;} \n  \n  if(!is_finite(log_FBF_unpasso)){\n   log_FBF_unpasso=0;\n  }\n\n  return log_FBF_unpasso;\n\n} // end function\n\n\n\n\nfield<mat> FBF_heart(double nt, mat* YtY, vec* vG_base, double lcv, vec* vlcv, mat* edges, double n_tot_mod, double C, double maxne, double h, bool univariate)\n{\n    \n   uli t, add, edge, imq, limodR, s;\n   double ltree, lM, sum_log_FBF, log_FBF_G, log_pi_G, log_num_MP_G, sum_log_RSMP, n_mod_r, log_FBF_t, log_FBF1;\n   vec M_log_FBF, log_num_MP, log_sume, G, imod_R, M_log_RSMP, pRSMP, mov, vlM, qh, G_t, M_q, M_P;\n   uvec iw;\n   mat tree, SM, M_G; \n   field<mat> treeRes, Res(4,1);\n   uword i_n_mod_r, imaxe;\n \n   M_G=zeros<mat>(lcv,n_tot_mod);  \n   M_P=zeros<vec>(n_tot_mod); \n   M_log_FBF=zeros<vec>(n_tot_mod); \n   log_num_MP=zeros<vec>(n_tot_mod); \n   M_q=zeros<vec>(lcv); \n   tree=zeros<mat>(n_tot_mod*lcv,2); tree.fill(datum::nan);\n   ltree=datum::nan;\n   lM=lcv-1; \n \n   sum_log_FBF=-datum::inf; \n   log_sume=zeros<vec>(lcv); log_sume.fill(-datum::inf);\n  \n   M_log_RSMP=zeros<vec>(n_tot_mod);\n   sum_log_RSMP=-datum::inf;\n   imod_R=zeros<vec>(n_tot_mod);\n\n   lM=lcv-1;\n\n   Col<uli> vexit(1);\n\n   for(t=0; t<lcv; t++){ //for1\n       \n    G=(*vG_base);\n    G(t)=1-(*vG_base)(t);\n    add=G(t);\n    edge=t;\n\n    log_FBF_G=log_FBF_Ga_Gb(&G,vG_base,edge,edges,YtY,add,nt,h);\n    \n    M_G.col(t)=G;\n    \n    treeRes=add_to_tree(&G,lM,t,&tree,ltree);\n    tree=treeRes(0,0);\n    ltree=conv_to<double>::from(treeRes(1,0));\n        \n    M_log_FBF(t)=log_FBF_G;\n    log_pi_G=-log(lcv+1)-lchoose(lcv,sum(G));\n    log_num_MP_G=log_FBF_G+log_pi_G;\n    log_num_MP(t)=log_num_MP_G;\n\n    sum_log_FBF=log_add(sum_log_FBF, log_num_MP_G);\n  \n    for(imq=0; imq<lcv; imq++){\n     if(G(imq)==1){log_sume(imq)=log_add(log_sume(imq), log_num_MP_G);}\n    }\n    \n    M_q=exp(log_sume-sum_log_FBF);\n   \n    M_log_RSMP(t)=log_num_MP_G;\n    sum_log_RSMP=log_add(sum_log_RSMP, log_num_MP_G);\n   \n    imod_R(t)=t;\n \n   } //end for1\n\n   vec vtmp1,vtmp2;\n\n   if(univariate==0){\n   \n    limodR=t-1; \n    s=lcv;\n\n    \n    while(t<n_tot_mod){ //while1\n\n     pRSMP=exp(M_log_RSMP.subvec(0,limodR)-sum_log_RSMP);\n\t   pRSMP.max(i_n_mod_r);\n     \n     n_mod_r=imod_R(i_n_mod_r);\n         \n     G=M_G.col(n_mod_r);\n     G_t=G;\n     log_FBF_t=M_log_FBF(n_mod_r);\n     \n     \n     vlM=(*vlcv)+1;\n     mov=mov_tree(&tree,&G,lM,&vlM,maxne);\n   \n     if(!is_finite(mov)){ //if1\n      \n      imod_R(i_n_mod_r)=-1;\n      iw=find(imod_R>-1); imod_R=imod_R.elem(iw);\n      M_log_RSMP=M_log_RSMP.elem(iw);\n          \n      limodR=limodR-1;\n      t=t-1;\n        \n     } else{\n        \n       vtmp1=(M_q+C)/(1-M_q+C);\n       vtmp2=(2*(1-G))-1;\n       qh=pow_vec(&vtmp1, &vtmp2);\n       qh=qh.elem(conv_to<uvec>::from(mov));\n    \n        \n       if(mov.n_elem==1){ //if2\n           \n        imod_R(i_n_mod_r)=-1;\n        iw=find(imod_R>-1); imod_R=imod_R.elem(iw);\n        M_log_RSMP=M_log_RSMP.elem(iw);\n      \n         limodR=limodR-1;  \n         edge=mov(0);\n         \n        } else{\n           \n           qh.max(imaxe);\n           edge=mov(imaxe);\n          \n        } // end if2\n    \n        \n        G(edge)=1-G(edge);\n        add=G(edge);   \n       \n        \n        log_FBF1=log_FBF_Ga_Gb(&G,&G_t,edge,edges,YtY,add,nt,h);\n        log_FBF_G=log_FBF1+log_FBF_t;\n      \n        M_G.col(t)=G;\n        \n        treeRes=add_to_tree(&G,lM,t,&tree,ltree);\n        tree=treeRes(0,0);\n        ltree=conv_to<double>::from(treeRes(1,0));\n      \n        M_log_FBF(t)=log_FBF_G;\n        log_pi_G=-log(lcv+1)-lchoose(lcv,sum(G));\n        log_num_MP_G=log_FBF_G+log_pi_G;\n        log_num_MP(t)=log_num_MP_G;\n    \n        sum_log_FBF=log_add(sum_log_FBF, log_num_MP_G);\n        \n        for(imq=0; imq<lcv; imq++){\n         if(G(imq)==1){log_sume(imq)=log_add(log_sume(imq), log_num_MP_G);}\n        }\n        M_q=exp(log_sume-sum_log_FBF);\n\t    \n        limodR=limodR+1;\n        imod_R(limodR)=t;\n        M_log_RSMP(limodR)=log_num_MP_G; \n         \n     } //end if1\n    \n     t=t+1;\n     s=s+1;\n    \n    } //end while1 \n\n  }// end if univariate \n\n  t=t-1; \n  s=s-1;\n  \n  M_P.subvec(0,t)=exp(log_num_MP.subvec(0,t)-sum_log_FBF);\n  if(max(M_P.subvec(0,t))>0){\n   M_P.subvec(0,t)=M_P.subvec(0,t)/sum(M_P.subvec(0,t));\n  }else{\n   M_P.subvec(0,t)=zeros<vec>(t+1);\t  \t  \n  }\n  \n  M_G=M_G.submat(0,0,lcv-1,t);\n  \n  Res(0,0)=M_q;\n  Res(1,0)=M_G;\n  Res(2,0)=M_P;\n  Res(3,0)=M_log_FBF.subvec(0,t);\n\n  return Res;\n   \n\n} // end function\n\n\n\nfield<mat> FBF_RS(Mat<double>* Corr_c, double nobs_c, Col<double>* G_base_c, double h_c, double C_c, double n_tot_mod_c, double n_hpp_c, bool univariate)\n{\n\n uli neq, rr; \n double maxne, Mlogbin_sum, lcv, rrmax, q;\n vec V1, V2, vlcv, vG_base, M_q, M_P, iM_P, M_P2;\n mat edges, G_fin, M_G, M_G2;\n mat YtY;\n field<mat> heartRes;\n \n q=(*Corr_c).n_cols; \n\n maxne=nobs_c-2*h_c-2;\n\n neq=1;\n\n V1=linspace<vec>(1,q-1,q-1);\n V2=zeros<vec>(q-neq);\n\n edges=join_rows(V1,V2); \n   \n lcv=V1.n_elem;\n vlcv=linspace<vec>(0,lcv-1,lcv); \n  \n vG_base=flipud(*G_base_c);\n   \n rrmax=std::min(maxne,lcv); \n Mlogbin_sum=0;\n   \n for(rr=1; rr<=rrmax; rr++){\n  Mlogbin_sum=log_add(Mlogbin_sum,lchoose(lcv,rr));   \n }\n \n n_tot_mod_c=std::min(Mlogbin_sum,log(n_tot_mod_c));\n n_tot_mod_c=round(exp(n_tot_mod_c)); \n\n YtY=(*Corr_c)*nobs_c;\n heartRes=FBF_heart(nobs_c, &YtY, &vG_base, lcv, &vlcv, &edges, n_tot_mod_c, C_c, maxne, h_c, univariate);\n \n return(heartRes);\n\n} // end function\n\n\nvoid printA(string msg)\n{\n\n #ifdef language_cpp\n  cout << msg << endl;\n #endif\n \n #ifdef language_py\n  msg=\"print('\" + msg + \"')\";\n  PyRun_SimpleString(msg.c_str());\n #endif\n\n #ifdef language_R\t\n  Rcout << msg << endl;\n #endif \n\t\n}\n\n\nvoid xit(){\n  vector<int> v;\n  printA(\"execution intentionally interrupted\");\n  printA(to_string(v[0]));\n}\n\ntemplate <typename T>\nvoid printV(vector<T> vec,string name){\n  printA(name+\": \");\n  for (auto i: vec){\n    printA(to_string(i));\n  }\n  printA(\"\");\n}\n\ntemplate<typename T>\nstring vec_to_string (T v, uli len){\n    \n    // string type0=typeid(v(0)).name();\n    // bool flg_string=0;\n    // if(type0.find(\"string\")!=string::npos){\n    //   flg_string=1;\n    // }\n    \n    string res;\n    if(len>0){\n     res=to_string(v(0));\n     for(uli t=1; t<len; ++t){\n       res=res+\",\"+to_string(v(t));\n     }\n    }else{\n     res=\"empty\";\n    }\n    return(res);\n}\n\n\ntemplate <typename T>\nstring NumberToString ( T Number )\n{\n   ostringstream ss;\n   ss << Number;\n   return ss.str();\n}\n\nvector<long int> split_string(const string &s, uli order) {\n    \n\tchar delim=' ';\n\tvector<long int> result(order,-1);\n    stringstream ss (s);\n    string item;\n\n\tuli h=0;\n    while (getline (ss, item, delim)) {\n\t\tresult[h]=stoi(item);\n\t\th=h+1;\n    }\n\t\t\n    return result;\n}\n\ntemplate<typename T>\nuli find_consecutive_finite(T* x, uli col){\n   \n   uli max_num=0;\n   uli num=0;\n   for(uli j=0; j<(*x).n_rows; ++j){\n    if(isfinite((*x)(j,col))==1){\n     num=num+1;\n     if(num>max_num){\n       max_num=num;\n     }\n    }else{\n     num=0; \n    } \n   }\n\n  return(max_num);\n\n}\n\ntemplate<typename T>\nuli find_consecutive_nan(T* x, uli col){\n   \n   uli max_num=0;\n   uli num=0;\n   for(uli j=0; j<(*x).n_rows; ++j){\n    if(isfinite((*x)(j,col))==0){\n     num=num+1;\n     if(num>max_num){\n       max_num=num;\n     }\n    }else{\n     num=0; \n    } \n   }\n\n  return(max_num);\n\n}\n\n\n// template<typename T>\n// void save_mat(T* obj,string dir, string name, string type){\n//   struct timeval time_now{};\n//   gettimeofday(&time_now, nullptr); \n//   time_t msecs_time = (time_now.tv_sec * 1000) + (time_now.tv_usec / 1000);\n//   (*obj).save(dir + name + \"_\" + to_string(msecs_time) + \".\" + type, csv_ascii);\n// }\n\n\nstring f_print_perc(double num){ \n \n string res;\n if(num>=1){\n  res=to_string((double)(floor(num*10000)/100)).substr(0,6);    \n }else if(num>=0.1){ \n  res=to_string((double)(floor(num*10000)/100)).substr(0,5); \n }else{\n  res=to_string((double)(floor(num*10000)/100)).substr(0,4);    \t   \n } \n return(res);\n}\n\n\nvector<string> subvector(vector<string> v, Col<uli> idx){\n vector<string> sub_v;\n for(uli j=0; j<idx.n_rows; ++j){\n  sub_v.push_back(v[idx(j)]);\n }\n return(sub_v);\n}\n\n\nint rand11(){\n std::random_device rd; \n std::mt19937 gen(rd()); \n std::uniform_int_distribution<> distrib(0,  RAND_MAX);\n return(distrib(gen));\n}\n\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//FUNCTIONS FOR VARIABLE SELECTION AND PREDICTIONS\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nstruct str_input\n{\n\n  mat MY0;\n  mat MY;\n  mat corY;\n  uli corY_nr;\n  uli corY_nc;\n\n  // mat* prt_MY0(){\n  //  return(&MY0);\n  // }\n  \n  // mat* prt_MY(){\n  //  return(&MY);\n  // }\n\n};\n\n\nstr_input data_preparation(mat* Y, Col<uli> vretard)\n{\n\n  //varibile target in differenze ritardata\n  \n  mat MY;\n  if(vretard.n_rows>0){\n    MY.resize((*Y).n_rows,vretard.n_rows);\n      \n    for(uli k=0; k<vretard.n_rows; ++k){\n     MY.col(k)=shift((*Y).col(0),vretard(k));\n     if(vretard(k)>0){\n       MY.submat(0,k,vretard(k)-1,k)+=datum::nan;\n     }\n    }\n    //join\n    MY=join_rows((*Y),MY);\n  }else{\n   MY=(*Y);\n  }\n\n  //output\n\n  str_input tab_input;\n  \n  tab_input.MY0=MY;\n\n  MY=MY.rows(find_finite(sum(MY,1)));\n\n  tab_input.MY=MY;\n\n  mat corY=cor(MY);\n\n  tab_input.corY=corY;\n  tab_input.corY_nr=MY.n_rows;\n  tab_input.corY_nc=MY.n_cols;\n\n\n  return(tab_input);\n\n}\n\n\n\nstruct str_output_reg\n{\n    Col<double> vactual;\n    Col<double> vfitted0;\n    Col<double> vresid0;\n    Col<double> vfitted;\n    Col<double> vresid;\n    Col<double> vbeta;\n    double TSS;\n    double RSS;\n    double L;\n    double L_adj;\n};\n\ndouble f_loss_function(const vec& vals_inp, vec* grad_out, void* opt_data)\n{\n      \n  str_input* data = reinterpret_cast<str_input*>(opt_data);\n  mat MY=data->MY;\n\n  double err=0;\n  double fit=0;\n\n  uli n=MY.n_rows;\n\n  for(uli t=0; t<n; ++t){\n    fit=0;\n    for(uli k=0; k<vals_inp.n_rows; ++k){\n      fit=fit+vals_inp(k)*MY(t,k+1);\n    }\n    err=err+(abs(MY(t,0)-fit)/n);\n  }\n\n  return err;\n\n}\n\nstr_output_reg reg(str_input* tab_input, string loss_function)\n{\n     \n    vec vbeta;\n\n    mat X=(*tab_input).MY.cols(1,(*tab_input).MY.n_cols-1);\n    vec Y=(*tab_input).MY.col(0);\n    mat XtX=trans(X)*X;\n    vec Xty=trans(X)*Y;\n    vbeta=solve_linear(&XtX,&Xty); \n\n    if(loss_function==\"MAE\"){\n     optim::de(vbeta,f_loss_function,tab_input);\n    }\n    //vec vbeta=inv_sympd(XtX)*Xty;\n\t    \n    vec vactual=Y;\n    vec vfitted=X*vbeta;\n    vec vresid=vactual-vfitted;\n\t\n    vec vactual0=(*tab_input).MY0.col(0);\n    vec vfitted0=(*tab_input).MY0.cols(1,(*tab_input).MY0.n_cols-1)*vbeta;\n    vec vresid0=vactual0-vfitted0;\n     \n    str_output_reg Res;\n\n    Res.vbeta=vbeta;\n    Res.vactual=Y;\n    Res.vfitted0=vfitted0;\n    Res.vresid0=vresid0;\n    Res.vfitted=vfitted;\n    Res.vresid=vresid;\n\n    return(Res);\n}\n\n\nstruct str_out_uni_select\n{\n Col<uli> vars_x_idx;\n Col<uli> vars_ar_idx; \n vec logs_FBF_x;\n vec logs_FBF_ar;\n uli odiff;\n \n};\n\nstr_out_uni_select model_univariate_selection(mat* Y, double from_lag, double max_lag, bool flg_diff){\n\n  str_out_uni_select str_out;\n  Col<uli> vretard;\n  uli odiff=0;\n  \n  if((max_lag!=0) || (((*Y).n_cols-1)>0)){\n    \n    double cons_rows;\n    uli max_lag0;\n\n    cons_rows=(double) find_consecutive_finite(Y,0);\n\n    // if(log(cons_rows/10)>0){\n    //  max_lag0=(uli) min(((cons_rows/2)+1),cons_rows/log(cons_rows/10));\n    // }else{\n    //  max_lag0=1; \n    // }\n    if((cons_rows-8)>0){\n     max_lag0=cons_rows-8;\n    }else{\n     max_lag0=1; \n    }\n\n    if(max_lag==-1){\n     max_lag=(double) max_lag0;\n    }else if(max_lag>0){\n     max_lag=(double) min(max_lag,(double)max_lag0);\n    }\n  \n    Col<uli> ids_vars_x;\n    vec log_FBF_x;\n    Col<uli> ids_vars_ar;\n    vec log_FBF_ar;\n    \n    if(from_lag<=max_lag){\n    \n      if(max_lag>0){\n       vretard=linspace<Col<uli>>((uli)from_lag,(uli)max_lag,(uli)(max_lag-from_lag+1));\n      }\n  \n      double nx=(*Y).n_cols-1;\n      double nretard=vretard.n_rows;\n      double nvars=nx+nretard;\n      \n      double h_c=1; \n      if(nvars>50){\n       h_c=2; \n      } \n      double n_tot_mod_c=nvars*100;\n      double C_c=0.01;\n      double threshold; \n      \n      str_input tab_input;\n      field<mat> res;\n    \n      uli nr,nc,nvar_max;\n      Col<double> G_base_c;\n      bool univariate=1;\n      Col<double> M_q;\n      \n      vec v_log_FBF;\n      mat M_log_FBF(1,3),M_log_FBF_x,M_log_FBF_ar;\n  \n      uvec idfinite=find_finite((*Y).col(0));\n      nr=idfinite.n_rows;\n      \n      double qt;\n      if(nvars<10){\n        qt=0.90;\n      }else{\n        qt=0.99;\n      }\n  \n  \n      vec x;\n      vec G_a(1);G_a(0)=1;\n      vec G_b(1);G_b(0)=0;\n      uli edge=0;\n      mat edges(1,2);edges(0,0)=0;edges(0,1)=1;\n      uli add=1;\n      double log_FBF;\n    \n      //estimate threshold\n      \n      uli nv1=(uli)((double)nx);\n      uli nv=std::max((uli)200,nv1);\n      \n      vec y=(*Y).col(0);\n      y=y.elem(idfinite);\n  \n      mat YtY(2,2);YtY(0,0)=1;YtY(1,1)=1;\n      v_log_FBF.set_size(nv);\n      \n      //arma_rng::set_seed(1234567); \n      mt19937 gen(1234567);\n      normal_distribution<double> distribution(0.0,1.0);\n      x.resize(nr);\n      \n      for(uli j=0; j<nv; ++j){\n        \n        //x = randu<vec>(nr,1);\n        for(uli k=0; k<nr; ++k){\n          x(k)=distribution(gen);\n        }\n        \n        YtY(1,0)=as_scalar(cor(y,x));\n        YtY(0,1)=YtY(1,0);\n        \n        v_log_FBF(j)=log_FBF_Ga_Gb(&G_a, &G_b, edge, &edges, &YtY, add, nr, h_c);\n        \n      }\n      \n      uli nth=(uli) (qt*v_log_FBF.size());\n      v_log_FBF=sort(v_log_FBF);\n      threshold=v_log_FBF(nth);\n      \n      mat MY((*Y).col(0).n_rows,2);\n      MY.col(0)=(*Y).col(0);\n      mat MY1;\n      \n\n      //select X variables\n      \n      if(nx>0){\n      \n        M_log_FBF_x.set_size(nx,3);\n        \n        for(uli j=0; j<nx; ++j){\n          \n          MY.col(1)=(*Y).col(j+1);\n          MY1=MY.rows(find_finite(sum(MY,1)));\n          nr=MY1.n_rows;\n          YtY=cor(MY1);\n          \n          M_log_FBF_x(j,0)=0;\n          M_log_FBF_x(j,1)=j+1;\n          M_log_FBF_x(j,2)=log_FBF_Ga_Gb(&G_a, &G_b, edge, &edges, &YtY, add, nr, h_c);\n          \n        }\n        \n        \n        M_log_FBF=join_cols(M_log_FBF,M_log_FBF_x);\n      \n      }else{\n        \n        //differentiation\n      \n        if(flg_diff==1){\n        \n          double fbf=datum::inf;\n          mat Y0;\n          \n          while(((fbf-threshold)>0) & (odiff<2)){\n            MY.col(0)=(*Y).col(0);\n            MY.col(1)=linspace<vec>(1,(*Y).n_rows,(*Y).n_rows);\n            MY1=MY.rows(find_finite(sum(MY,1)));\n            nr=MY1.n_rows;\n            YtY=cor(MY1);\n            fbf=log_FBF_Ga_Gb(&G_a, &G_b, edge, &edges, &YtY, add, nr, h_c);\n\n            if((fbf-threshold)>0){\n              Y0=(*Y);\n              (*Y).col(0)=shift((*Y).col(0),1);\n              (*Y).submat(0,0,0,0)+=datum::nan;\n              for(uli j=0; j<(*Y).n_rows; ++j){\n               (*Y)(j,0)=Y0(j,0)-(*Y)(j,0);\n              }\n              odiff=odiff+1;\n            }else{\n              break;\n            }\n          \n          }\n          \n        }\n        \n      \n      }\n      \n      //select retard\n      \n      if(nretard>0){\n        \n        M_log_FBF_ar.set_size(nretard,3);\n        \n        for(uli j=0; j<nretard; ++j){\n          \n          MY.col(1)=shift((*Y).col(0),vretard(j));\n          if(vretard(j)>0){\n            MY.submat(0,1,vretard(j)-1,1)+=datum::nan;\n          }\n          \n          MY1=MY.rows(find_finite(sum(MY,1)));\n          nr=MY1.n_rows;\n          YtY=cor(MY1);\n          \n          M_log_FBF_ar(j,0)=1;\n          M_log_FBF_ar(j,1)=vretard(j);\n          M_log_FBF_ar(j,2)=log_FBF_Ga_Gb(&G_a, &G_b, edge, &edges, &YtY, add, nr, h_c);\n        \n        }\n        \n        M_log_FBF=join_cols(M_log_FBF,M_log_FBF_ar);\n        \n      }\n      \n      M_log_FBF.shed_row(0);\n      \n      uvec ids=find(M_log_FBF.col(2)<=threshold);\n      M_log_FBF.shed_rows(ids);\n      \n      \n      if(M_log_FBF.n_rows>0){\n      \n        nvar_max=(uli)2*std::pow(idfinite.n_rows,0.25); //nb: only non missing target is considered\n        \n        if(M_log_FBF.n_rows>nvar_max){\n          ids = sort_index(M_log_FBF.col(2),\"descend\");\n          ids=ids.rows(0,nvar_max-1);\n          ids=sort(ids);\n          M_log_FBF=M_log_FBF.rows(ids);\n        }\n      \n        uvec ids_x=find(M_log_FBF.col(0)==0);\n  \n        if(ids_x.size()>0){\n          ids_vars_x=conv_to< Col<uli> >::from(M_log_FBF.col(1));\n          ids_vars_x=ids_vars_x.elem(ids_x);\n          log_FBF_x=M_log_FBF.col(2);\n          log_FBF_x=log_FBF_x.elem(ids_x);\n        }\n      \n        uvec ids_ar=find(M_log_FBF.col(0)==1);\n      \n        if(ids_ar.size()>0){\n          ids_vars_ar=conv_to< Col<uli> >::from(M_log_FBF.col(1));\n          ids_vars_ar=ids_vars_ar.elem(ids_ar);\n          log_FBF_ar=M_log_FBF.col(2);\n          log_FBF_ar=log_FBF_ar.elem(ids_ar);\n        }\n      \n      }\n    \n    }\n    \n    str_out.vars_x_idx=ids_vars_x; //nb. first regressor has id=1\n    str_out.vars_ar_idx=ids_vars_ar;\n    str_out.logs_FBF_x=log_FBF_x;\n    str_out.logs_FBF_ar=log_FBF_ar;\n    str_out.odiff=odiff;\n  \n  } \n   \n  \n  return(str_out);\n\n}\n\n\nfield<vec> model_multivariate_selection(mat* Y, Col<uli>* ids_vars_x_uni, Col<uli>* ids_vars_ar_uni, string loss_function, bool flg_const, bool flg_arx){\n        \n    Col<uli> ids_vars_x,v_ar;\n    vec vbeta_arx;\n    vec vresid((*Y).n_rows,1);\n\n    double nvars=(*Y).n_cols-1+(*ids_vars_ar_uni).n_rows; \n    \n    if(nvars>0){\n\n      double threshold=0.5;\n      double h_c=1; \n      if(nvars>50){\n       h_c=2; \n      } \n      double n_tot_mod_c=nvars*100;\n      double C_c=0.01;\n      double n_hpp_c=1;\n       \n      mat Y0;\n      uvec u_ids_vars_x;\n      if((*ids_vars_x_uni).n_rows>0){\n       u_ids_vars_x=join_cols(zeros<uvec>(1),conv_to< uvec >::from(*ids_vars_x_uni));\n       Y0=(*Y).cols(u_ids_vars_x);\n      }else{\n       Y0=(*Y).cols(0,0);\n      }\n    \n      str_input tab_input=data_preparation(&Y0,(*ids_vars_ar_uni));\n    \n      uli nvar_max=(uli)std::pow(tab_input.MY.n_rows,0.25);\n      \n      uli nr,nc;\n      Col<double> G_base_c;\n      bool univariate=0;\n      vec M_q;\n      field<mat> res;\n      uvec ids;\n      vec rvals;\n  \n      uli len_ar=(*ids_vars_ar_uni).n_rows;\n      vec ids_vars;\n  \n      mat M_G;\n      vec M_P;\n    \n      if((len_ar>0) || (Y0.n_cols>1)){\n    \t\n\t      nr=tab_input.corY_nr;\n        nc=tab_input.corY_nc;\n  \n        h_c=1; \n        if((nc-1)>50){\n         h_c=2; \n        } \n    \n        G_base_c=zeros<vec>(nc-1);\n        \n        res=FBF_RS(&tab_input.corY,nr,&G_base_c,h_c,C_c,n_tot_mod_c,n_hpp_c,univariate);\n      \n                \n        M_q=res(0,0);\n  \n\t      ids=find(M_q>=threshold);\n\t      if(ids.n_rows>nvar_max){\n          ids = sort_index(M_q,\"descend\");\n          ids=ids.rows(0,nvar_max-1);\n          ids=sort(ids);\n        }\n    \n        rvals=linspace<vec>(0,M_q.n_rows-1, M_q.n_rows).elem(ids);\n      \n        ids_vars=rvals-(Y0.n_cols-1);\n        vec ids_vars_ar=ids_vars(find(ids_vars>=0));\n        uvec fd_ids_vars=find(ids_vars<0);\n        if(fd_ids_vars.n_cols>0){\n         ids_vars_x=conv_to< Col<uli> >::from(rvals(fd_ids_vars));\n        }\n    \n\t      if(ids_vars.n_rows>0){\n          if(len_ar>0){\n            uvec u_ids_vars_ar=conv_to< uvec >::from(ids_vars_ar);\n            v_ar=(*ids_vars_ar_uni).rows(u_ids_vars_ar);\n          }\n          \n          uvec urvals=join_cols(zeros<uvec>(1),conv_to< uvec >::from(rvals+1));\n          tab_input.MY0=tab_input.MY0.cols(urvals);\n          tab_input.MY=tab_input.MY.cols(urvals);\n        \n          if((flg_const==1) & (flg_arx==1)){\n           tab_input.MY0.resize(tab_input.MY0.n_rows,tab_input.MY0.n_cols+1);\n           tab_input.MY0.col(tab_input.MY0.n_cols-1)=zeros<vec>(tab_input.MY0.n_rows)+1;\n\n           tab_input.MY.resize(tab_input.MY.n_rows,tab_input.MY.n_cols+1);\n           tab_input.MY.col(tab_input.MY.n_cols-1)=zeros<vec>(tab_input.MY.n_rows)+1;\n          }\n          \n          str_output_reg tab_out_reg=reg(&tab_input, loss_function);\n          vbeta_arx=tab_out_reg.vbeta;\n          vresid=tab_out_reg.vresid0;\n        }else{\n\t    \t  vresid=Y0.col(0);\n          double m0=as_scalar(mean(vresid.rows(find_finite(vresid))));\n          for(uli t=0; t<vresid.n_rows; ++t){\n            vresid(t)=vresid(t)-m0;\n\t        }\n        }\n      }else{\n    \n        vresid=Y0.col(0);\n        double m0=as_scalar(mean(vresid.rows(find_finite(vresid))));\n        for(uli t=0; t<vresid.n_rows; ++t){\n         vresid(t)=vresid(t)-m0;\n        }\n      \n      }\n\n      if(ids_vars_x.size()>0){ \n       u_ids_vars_x=conv_to< uvec >::from(ids_vars_x);\n       ids_vars_x=(*ids_vars_x_uni).elem(u_ids_vars_x);\n      }\n      \n    }else{\n\n     vresid=(*Y).col(0);\n\n    }\n\n    \n    uli nmodels=1;\n    \n    field<vec> str_out;\n    str_out.set_size(nmodels,4);\n    str_out(0,0)=conv_to< vec >::from(ids_vars_x);\n    str_out(0,1)=conv_to< vec >::from(v_ar);\n    str_out(0,2)=vbeta_arx;\n    str_out(0,3)=vresid;\n    \n    return(str_out);\n\n}\n\n\n\nmap<string,double> performances(vec vactual, vec vfitted, uli nvars){\n\n  vec vresid=vactual-vfitted;\n  uvec non_missing=find_finite(vresid);\n  vresid=vresid.elem(non_missing);   \n  //double RSS_=as_scalar(sum(pow(vresid,2)));\n  \n  vactual=vactual.elem(non_missing);\n  double m0=mean(vactual);\n  // Col<double> vTSS=vactual;\n  // for(uli i=0; i<vTSS.n_rows; ++i){\n  //  vTSS(i)=vTSS(i)-m0;\n  // }\n  // vTSS=pow(vTSS,2);\n  // double TSS=sum(vTSS);\n\n  // double R2 = 1 - (RSS/TSS);\n  // double R2_adj = 1 - (((double)vactual.n_rows-1)/((double)vactual.n_rows-(double)nvars-1))*(RSS/TSS); \n \n  //abs dist\n\n\n  double L1=as_scalar(sum(abs(vresid)));\n\n  double L0=0;\n  for(uli i=0; i<vactual.n_rows; ++i){\n   L0=L0+abs(vactual(i)-m0);\n  }  \n\n  double L=1-(L1/L0);\n\n  double L_adj=1 - (((double)vactual.n_rows-1)/((double)vactual.n_rows-(double)nvars-1))*(L1/L0);\n\n  map<string,double> res;\n  res[\"L\"]=L;\n  res[\"L_adj\"]=L_adj;\n\n  return(res);\n    \n}\n\n\nstruct str_pred_out\n{\n\n mat predictions;\n mat fitted;\n double L;\n double L_adj;\n \n};\n\n\nstr_pred_out sarimax_pred(mat* Y, bool flg_sim, mat Mfitted, vec probs, uli nsim, string loss_function, bool pred_only, bool flg_const, field<vec> models)\n{\n  \n  Col<uli> ids_vars_x=conv_to< Col<uli> >::from(models(0,0));\n  Col<uli> ids_vars_ar=conv_to< Col<uli> >::from(models(0,1));\n  vec vbeta_arx=models(0,2);\n  ///\n  double const0=0;\n  if(flg_const==1){\n   if(vbeta_arx.n_rows>0){\n    const0=vbeta_arx(vbeta_arx.n_rows-1);\n    vbeta_arx.shed_row(vbeta_arx.n_rows-1);\n   }\n  }\n  ///\n  \n  Col<uli> ids_vars_ma=conv_to< Col<uli> >::from(models(0,3));\n  vec vbeta_ma=models(0,4);\n  \n  str_pred_out str_out;\n  vec vresid; \n\n  uli p=ids_vars_ar.n_rows;\n  uli q=ids_vars_ma.n_rows;\n  uli k=vbeta_arx.n_rows-p; //number of regressors\n\n  uli maxpq=0;\n  if((p==0) && (q!=0)){\n    maxpq=ids_vars_ma.max();\n  }else if((p!=0) && (q==0)){\n    maxpq=ids_vars_ar.max();\n  }else if((p!=0) && (q!=0)){\n    maxpq=max(ids_vars_ar.max(),ids_vars_ma.max());\n  }\n  \n  uli npred;\n  if(flg_sim==0){\n    uli npred1=find_consecutive_nan(Y,0);\n    uli npred2=find_consecutive_finite(Y,0)-maxpq-k;\n\n    npred=min(npred1,npred2);\n    if(npred==0){\n      npred=1;\n    }\n  }else{\n    npred=Mfitted.n_cols;\n  }\n  \n  uli ri;\n  double rd;\n  // //random_device rdv; \n  mt19937 gen(1234567);\n  // default_random_engine gen;\n  uniform_real_distribution<double> distrib(0.0,1.0);\n\n  // mt19937 engine(1234567);\n  // uniform_real_distribution<double> distrib(0.0,1.0);\n  // auto gen = bind(ref(distrib), ref(engine));\n\n  field<vec> Fresid(npred,1);\n  vec resid_size(npred);\n\n  if(flg_sim==1){ \n     for(uli kpred=0; kpred<npred; ++kpred){\n       vresid=(*Y).col(0)-Mfitted.col(kpred);\n       vresid=vresid(find_finite(vresid));\n       Fresid(kpred,0)=vresid;\n       resid_size(kpred)=(double) vresid.size();\n     }\n  }else{\n    nsim=1;\n  }\n\n  vec vbeta_x;\n  vec vbeta_ar;\n\n  if(k>0){\n   vbeta_x=vbeta_arx.rows(0,k-1);\n  }\n  if(p>0){\n   vbeta_ar=vbeta_arx.rows(k,vbeta_arx.n_rows-1);\n  }\n  double tar;\n  double tma;\n  \n  mat My_pred((*Y).n_rows, npred);\n  vec veps((*Y).n_rows);\n  field<mat> Fout(npred,1);\n  mat Mout;\n  \n  if(flg_sim==1){\n    for(uli kpred=0; kpred<npred; ++kpred){\n     Fout(kpred,0).resize(nsim,(*Y).n_rows);\n     Fout(kpred,0).fill(datum::nan);\n    }\n    }else{  \n     for(uli kpred=0; kpred<npred; ++kpred){\n      Fout(kpred,0).resize((*Y).n_rows,2);\n    }\n  }\n  \n  double pred_x=0;\n  double pred_ar=0;\n  double pred_ma=0;\n  double pred_err;\n  \n  uvec ut(1);\n  uvec uids_vars_x=conv_to<uvec>::from(ids_vars_x);\n\n  double eps_tma;\n\n  bool is_na_pred_ar=0;\n  \n  uli t0, tk, last_kpred;\n\n  for(uli s=0; s<nsim; ++s){\n\n    My_pred.fill(datum::nan);\n    veps.fill(datum::nan);\n\n    if(maxpq>0){\n     t0=(maxpq+1);\n    }else{\n     t0=0; \n    }\n      \n\n    for(uli t=t0; t<(*Y).n_rows; ++t){\n      \n      last_kpred=std::min(npred,(uli)(*Y).n_rows-t);\n      \n      for(uli kpred=0; kpred<last_kpred; ++kpred){ \n\n        tk=t+kpred;\n\n        ut(0)=tk;\n   \n        //X\n        \n        if(k>0){\n         pred_x=as_scalar((*Y).submat(ut,uids_vars_x)*vbeta_x);\n        }else{\n         pred_x=0;\n        }\n        \n        //AR\n\n        pred_ar=const0;\n    \n        if(p>0){\n        \n          for(uli p0=0; p0<p; ++p0){\n           \n           tar=(double)tk-(double)ids_vars_ar(p0);\n           \n           if(tar>0){\n            if((tar<t) && (isfinite((*Y)(tar,0)))){ \n             pred_ar=pred_ar+(*Y)(tar,0)*vbeta_ar(p0);\n            }else{ \n             is_na_pred_ar=1;\n             for(uli z=0; z<=kpred; ++z){ \n              if(isfinite(My_pred(tar,z))){ \n               pred_ar=pred_ar+My_pred(tar,z)*vbeta_ar(p0);\n               is_na_pred_ar=0;\n               break;\n              }\n             }\n             if(is_na_pred_ar==1){\n               pred_ar=datum::nan;\n             }\n            }\n           }else{\n            pred_ar=datum::nan;\n            break; \n           }\n      \n          }\n        \n        }//end if p\n    \n        pred_ma=0;\n\n        if(isfinite(pred_ar)){\n        \n          //MA\n      \n          if(q>0){\n              \n            for(uli q0=0; q0<q; ++q0){\n        \n             tma=(double)tk-(double)ids_vars_ma(q0);\n        \n             if(tma>0){\n              eps_tma=veps(tma);\n              if((tma<t) && (isfinite(eps_tma))){\n                pred_ma=pred_ma+eps_tma*vbeta_ma(q0);\n              }else{\n                pred_ma=pred_ma+0;\n              }\n             }else{\n              pred_ma=pred_ma+0;\n             }\n        \n            }\n            \n          }//end if q\n\n    \n        }\n            \n        if(isfinite(pred_ar)){\n         My_pred(tk,kpred)=pred_x+pred_ar+pred_ma; \n        }else{\n         My_pred(tk,kpred)=datum::nan; \n        }\n            \n        if(flg_sim==1){\n                    \n          rd=distrib(gen);\n          ri=(uli)floor(resid_size(kpred)*rd);\n\n          pred_err=Fresid(kpred,0)(ri);\n\n          if(kpred==0){\n            if(isfinite((*Y)(t,0))){\n              veps(t)=(*Y)(t,0)-pred_x-pred_ar;\n            }else{\n              veps(t)=0+pred_err;\n            }\n          }\n          \n          if(isfinite(pred_ar)){\n           My_pred(tk,kpred)=pred_x+pred_ar+pred_ma+pred_err; \n          }else{\n           My_pred(tk,kpred)=datum::nan; \n          }\n\n          Fout(kpred,0)(s,tk)=My_pred(tk,kpred);\n\n        }else{ \n\n          if(kpred==0){\n           if(isfinite((*Y)(t,0))){\n            veps(t)=(*Y)(t,0)-pred_x-pred_ar;\n           }else{\n            veps(t)=0;\n           }\n          }\n        \n        }\n        \n        // if(kpred==0){\n        //  cout << \"--------\" << endl;\n        //  cout << \"tk:\" << tk << endl;\n        //  cout << \"pred_ma:\" << pred_ma << endl;\n        //  cout << \"pred_ar:\" << pred_ar << endl;\n        //  cout << \"eps-1:\" << veps(tk-1) << endl;\n        //  cout << \"eps:\" << veps(tk) << endl;\n        //  cout << \"target-1:\" << (*Y)(tk-1,0) << endl;\n        //  cout << \"target:\" << (*Y)(tk,0) << endl;\n        //  cout << \"pred:\" << My_pred(tk,0) << endl;\n        // }\n      \n      }//end kpred \n      \n    }//end t\n  \n  }//end s\n  \n  if(flg_sim==1){\n   \n   for(uli kpred=0; kpred<npred; ++kpred){ \n     Fout(kpred,0)=quantile(Fout(kpred,0),probs);\n     Fout(kpred,0)=join_rows(Mfitted.col(kpred),Fout(kpred,0).t());\n     Fout(kpred,0)=join_rows((*Y).col(0),Fout(kpred,0));\n   }\n\n   if(npred>1){\n      \n     //prediction interval correction\n\n     uli kpred=0;\n     uli h_low=0, h_up=0;\n   \n     mat M_low((*Y).n_rows,3); M_low.fill(datum::nan);\n     mat M_up((*Y).n_rows,3); M_up.fill(datum::nan);\n\n     mat M0_low((*Y).n_rows,3); M0_low.fill(datum::nan);\n     M0_low.col(1)=Fout(0,0).col(2);\n     M0_low.col(2).fill(1);\n     mat M0_up((*Y).n_rows,3); M0_up.fill(datum::nan);\n     M0_up.col(1)=Fout(0,0).col(4);\n     M0_up.col(2).fill(1);\n\n     for(uli j=0; j<(*Y).n_rows; ++j){\n       if(isfinite((*Y)(j,0))==0){\n         if((kpred>0) && (kpred<npred)){\n           M_low(h_low,0)=Fout(kpred,0)(j,2);\n           M_low(h_low,1)=Fout(0,0)(j,2);\n           M_low(h_low,2)=1;\n           M0_low(j,0)=Fout(kpred,0)(j,2);\n           h_low=h_low+1;\n  \n           M_up(h_up,0)=Fout(kpred,0)(j,4);\n           M_up(h_up,1)=Fout(0,0)(j,4);\n           M_up(h_up,2)=1;\n           M0_up(j,0)=Fout(kpred,0)(j,4);\n           h_up=h_up+1;\n         }\n         kpred=kpred+1;  \n       }else{\n        kpred=0; \n       }  \n     }\n\n     str_input tab_input_ci;\n     str_output_reg reg_ci; \n     vec vlower_bound, vupper_bound;\n     vec vquantiles_ci;\n\n     tab_input_ci.MY0=M0_low;\n     tab_input_ci.MY=M_low.rows(0,h_low-1);\n     reg_ci=reg(&tab_input_ci, loss_function);\n     vquantiles_ci=quantile(reg_ci.vresid,probs);\n     vlower_bound=reg_ci.vfitted0;\n     for(uli j=0; j<vlower_bound.n_rows; ++j){\n      vlower_bound(j)=vlower_bound(j)+vquantiles_ci(0);\n     }\n\n     tab_input_ci.MY0=M0_up;\n     tab_input_ci.MY=M_up.rows(0,h_low-1);\n     reg_ci=reg(&tab_input_ci, loss_function);\n     vquantiles_ci=quantile(reg_ci.vresid,probs);\n     vupper_bound=reg_ci.vfitted0;\n     for(uli j=0; j<vupper_bound.n_rows; ++j){\n      vupper_bound(j)=vupper_bound(j)+vquantiles_ci(2);\n     }  \n\n     Mout=Fout(0,0);\n\n     kpred=0;\n     for(uli j=0; j<(*Y).n_rows; ++j){\n       if(isfinite((*Y)(j,0))==0){\n         if((kpred>0) && (kpred<npred)){\n           if((isfinite(vlower_bound(j))) && isfinite(vupper_bound(j))){\n            Mout(j,2)=vlower_bound(j);\n            Mout(j,4)=vupper_bound(j);\n           }\n         }\n         kpred=kpred+1;  \n       }else{\n        kpred=0; \n       }  \n     }\n\n   }else{\n\n    Mout=Fout(0,0);\n\n   }//end if(npred>1)\n\n  }else{\n  \n   uvec nonmiss;\n\n   for(uli kpred=0; kpred<npred; ++kpred){\n     nonmiss=find_finite((*Y).col(0)-My_pred.col(kpred));\n     npred=kpred+1;\n     if(nonmiss.n_rows<20){ //20 is the number of observations over that the forecasting horizon can be considered significative\n       break;\n     }\n   }\n  \n  }\n     \n  map<string,double> mp_idx_perf;\n\n  double L, L_adj;\n  if(pred_only==0){\n   mp_idx_perf=performances((*Y).col(0), My_pred.col(0), (uli)(ids_vars_x.n_rows+ids_vars_ar.n_rows+ids_vars_ma.n_rows));\n   L=mp_idx_perf[\"L\"];\n   L_adj=mp_idx_perf[\"L_adj\"];\n  }\n  \n  str_out.predictions=Mout;\n  if(flg_sim==0){\n   str_out.fitted=My_pred.cols(0,npred-1);\n  }else{\n   str_out.fitted=My_pred; \n  }\n  str_out.L=L;\n  str_out.L_adj=L_adj;\n\n  return(str_out);\n\n}\n\n\nstruct str_model_out\n{\n  Col<uli> ids_vars_x;\n  Col<uli> ids_vars_ar;\n  Col<double> vbeta_arx;\n  Col<uli> ids_vars_ma;\n  Col<double> vbeta_ma;\n};  \n\n\nstruct str_model_selection\n{\n \n field<vec> models;\n mat predictions;\n\n};\n\n\nstr_model_selection model_selection_prediction(mat* Y, double from_lag, double max_lag, vec probs, uli nsim, string loss_function, bool pred_only, bool flg_const, bool flg_diff, field<vec> models)\n{\n\n  str_pred_out out_pred_i;\n\n  str_out_uni_select out_uni_select_arx;\n  field<vec> out_multi_select_arx;\n\n  str_out_uni_select out_uni_select_ma;\n  field<vec> out_multi_select_ma;\n  \n  vec vresid;\n  mat Mfitted, Mfitted_empty;\n  Col<uli> vretard_empty;\n\n  bool flg_x_only=0;\n  if(max_lag==0){\n   flg_x_only=1; \n  }\n  \n  str_model_selection res_out;\n  \n  res_out.models.set_size(1,6);\n  \n  //SARIX\n  \n  uli ndiff=0;\n  vec old_target=(*Y).col(0);\n  \n  if(pred_only==0){\n    \n    out_uni_select_arx=model_univariate_selection(Y, from_lag, max_lag, flg_diff);\n    \n    res_out.models(0,5)=out_uni_select_arx.odiff;\n    ndiff=(uli)out_uni_select_arx.odiff;\n    \n  }else{\n    \n    ndiff=(uli)as_scalar(models(0,5));\n    mat Y0;\n    for(uli k=0; k<ndiff; ++k){\n      Y0=(*Y);\n      (*Y).col(0)=shift((*Y).col(0),1);\n      (*Y).submat(0,0,0,0)+=datum::nan;\n      for(uli j=0; j<(*Y).n_rows; ++j){\n       (*Y)(j,0)=Y0(j,0)-(*Y)(j,0);\n      }\n    }\n    \n  }\n  \n  if(((flg_x_only==0) && (out_uni_select_arx.vars_ar_idx.n_rows>0) && (pred_only==0)) || ((flg_x_only==0) && (pred_only==1))){ //if it is a sarimax\n    \n    \n    if(pred_only==0){\n      \n      \n      out_multi_select_arx=model_multivariate_selection(Y, &out_uni_select_arx.vars_x_idx, &out_uni_select_arx.vars_ar_idx, loss_function, flg_const, 1);\n      \n      \n      res_out.models(0,0)=out_multi_select_arx(0,0);\n      res_out.models(0,1)=out_multi_select_arx(0,1);\n      res_out.models(0,2)=out_multi_select_arx(0,2);\n      \n      //MA\n\n      vresid=out_multi_select_arx(0,3);\n\n      out_uni_select_ma=model_univariate_selection(&vresid, from_lag, max_lag, 0);\n      \n      out_multi_select_ma=model_multivariate_selection(&vresid, &out_uni_select_ma.vars_x_idx, &out_uni_select_ma.vars_ar_idx, loss_function, flg_const, 0);\n      \n      res_out.models(0,3)=out_multi_select_ma(0,1);\n      res_out.models(0,4)=out_multi_select_ma(0,2);\n      \n      models=res_out.models;\n    \n    }\n    \n    out_pred_i=sarimax_pred(Y, 0, Mfitted_empty, probs, nsim, loss_function, pred_only, flg_const, models);\n    Mfitted=out_pred_i.fitted;\n\n    out_pred_i=sarimax_pred(Y, 1, Mfitted, probs, nsim, loss_function, pred_only, flg_const, models);\n    \n    res_out.predictions=out_pred_i.predictions;\n    \n  }else{\n    \n    flg_x_only=1;\n  \n  }\n  \n\n  if(flg_x_only==1){\n     \n    if(pred_only==0){\n    \n      out_multi_select_arx=model_multivariate_selection(Y, &out_uni_select_arx.vars_x_idx, &vretard_empty, loss_function, flg_const, 1);\n\n      res_out.models(0,0)=out_multi_select_arx(0,0);\n      res_out.models(0,1)=out_multi_select_arx(0,1);\n      res_out.models(0,2)=out_multi_select_arx(0,2);\n      \n      models=res_out.models;\n      \n    }\n    \n    out_pred_i=sarimax_pred(Y, 0, Mfitted_empty, probs, nsim, loss_function, pred_only, flg_const, models);\n    Mfitted=out_pred_i.fitted;\n    \n    out_pred_i=sarimax_pred(Y, 1, Mfitted, probs, nsim, loss_function, pred_only, flg_const, models);\n    \n    res_out.predictions=out_pred_i.predictions;\n\n  }\n  \n  if(ndiff>0){\n   \n      double y_t1,y_t2;\n      out_pred_i.predictions.col(0)=old_target;\n      \n      for(uli j=0; j<ndiff; ++j){\n        for(uli k=1; k<5; ++k){\n          out_pred_i.predictions(j,k)=datum::nan;\n        }\n      }\n      \n      for(uli j=ndiff; j<out_pred_i.predictions.n_rows; ++j){\n        for(uli k=1; k<5; ++k){\n          if(isfinite(out_pred_i.predictions(j,k))==1){\n            y_t1=out_pred_i.predictions(j-1,0);\n            if(isfinite(y_t1)==0){\n             y_t1=out_pred_i.predictions(j-1,k);\n            }\n            if(ndiff==1){\n             out_pred_i.predictions(j,k)=out_pred_i.predictions(j,k)+y_t1;\n            }\n            if(ndiff==2){\n             y_t2=out_pred_i.predictions(j-2,0);\n             if(isfinite(y_t2)==0){\n              y_t2=out_pred_i.predictions(j-2,k);\n             }\n             out_pred_i.predictions(j,k)=out_pred_i.predictions(j,k)+2*y_t1-y_t2;\n            }\n          }\n        }\n      }\n      \n      res_out.predictions=out_pred_i.predictions;\n    \n  }\n  \n  (*Y).col(0)=old_target;\n  \n  return(res_out);\n\n}\n\n\nstruct str_output\n{\n\n mat predictions;\n vec performances;\n \n mat fw_predictions;\n field<vec> fw_models;\n vec fw_performances;\n \n mat bw_predictions;\n field<vec> bw_models;\n vec bw_performances;\n\n};\n\n\n\nstr_output regpred_cpp(mat* Y, double from_lag, double max_lag, double alpha, uli nsim, bool flg_print, string direction, string loss_function, bool pred_only, bool flg_const, bool flg_diff, vector < field<vec> > vmodels)\n{\n  \n  str_model_out tab_model;\n  str_pred_out tab_pred;\n  str_output str_out;\n   \n  double pinf=(alpha/2);\n  double psup=1-(alpha/2);\n\n  vec probs={pinf, 0.5, psup};\n\n  vec vresid_empty;\n  vec vresid;\n  vec vfitted;\n\n  Col<uli> vtmp_uli;\n  map<string,double> mp_idx_perf;\n\n  uli nrows=(*Y).n_rows;\n  \n  mat Yr;\n  if((direction==\"<->\") || (direction==\"<-\")){ //do not move below\n   Yr=reverse((*Y),0);\n  }\n\n  uli bw_k=0, fw_k=0;\n\n  mat predictions, predictions_rev;\n\n  str_model_selection out_sel_pred;\n  \n  field<vec> models0;\n  field<vec> models;\n  \n  double L,L_adj;\n  \n  if((direction==\"<->\") || (direction==\"->\")){ \n    \n    //model selection\n    if(flg_print==1){\n     printA(\"Forward prediction: model selection and prediction...\");\n    }\n    \n    if(pred_only==1){\n     models0=vmodels[0];\n    }\n    \n    out_sel_pred=model_selection_prediction(Y, from_lag, max_lag, probs, nsim, loss_function,pred_only,flg_const,flg_diff,models0);\n  \n    predictions=out_sel_pred.predictions;\n\n    str_out.fw_predictions=predictions;\n    \n    models=out_sel_pred.models;\n    str_out.fw_models=models;\n    \n    L=datum::nan;\n    L_adj=datum::nan;\n    if(pred_only==0){\n      fw_k=(uli) (models(0,0).size() + models(0,1).size() + models(0,3).size());\n      mp_idx_perf=performances(predictions.col(0), predictions.col(3), fw_k);\n      L=mp_idx_perf[\"L\"];\n      L_adj=mp_idx_perf[\"L_adj\"];\n    }\n    \n    str_out.fw_performances.set_size(2);\n    str_out.fw_performances(0)=L;\n    str_out.fw_performances(1)=L_adj;\n    \n    \n  }\n \n  if((direction==\"<->\") || (direction==\"<-\")){ \n                    \n    //model selection\n    if(flg_print==1){\n     printA(\"Backward prediction: model selection and prediction...\");\n    }\n    \n    if(pred_only==1){\n     models0=vmodels[1];\n    }\n    \n    out_sel_pred=model_selection_prediction(&Yr, from_lag, max_lag, probs, nsim, loss_function,pred_only,flg_const,flg_diff,models0);\n\n    predictions_rev=reverse(out_sel_pred.predictions);\n    \n    str_out.bw_predictions=predictions_rev;\n    \n    models=out_sel_pred.models;\n    str_out.bw_models=models;\n\n    L=datum::nan;\n    L_adj=datum::nan;\n    if(pred_only==0){\n      bw_k=(uli) (models(0,0).size() + models(0,1).size() + models(0,3).size());\n      mp_idx_perf=performances(predictions_rev.col(0), predictions_rev.col(3), bw_k);\n      L=mp_idx_perf[\"L\"];\n      L_adj=mp_idx_perf[\"L_adj\"];\n    }\n    \n    str_out.bw_performances.set_size(2);\n    str_out.bw_performances(0)=L;\n    str_out.bw_performances(1)=L_adj;\n\n  }\n\n  //collapse\n  \n  if(direction==\"<-\"){\n    predictions=predictions_rev;\n  }\n\n  \n  if(direction==\"<->\"){\n\n   for(uli t=0; t<nrows; ++t){\n    for(uli k=1; k<4; ++k){\n     if(isfinite(predictions(t,1)) && isfinite(predictions_rev(t,1))){\n      predictions(t,1)=(predictions(t,1)+predictions_rev(t,1))/2;\n     }else if(isfinite(predictions_rev(t,1))){\n      predictions(t,1)=predictions_rev(t,1);\n     } \n    }\n   }\n\n  }\n\n  str_out.predictions=predictions;\n         \n  L=datum::nan;\n  L_adj=datum::nan;\n  if(pred_only==0){\n    mp_idx_perf=performances(predictions.col(0), predictions.col(3), max(bw_k,fw_k));\n    L=mp_idx_perf[\"L\"];\n    L_adj=mp_idx_perf[\"L_adj\"];\n  }\n  \n  str_out.performances.set_size(2);\n  str_out.performances(0)=L;\n  str_out.performances(1)=L_adj;\n  \n  if(flg_print==1){ \n   printA(\"Process ended successfully!\");\n  }\n  \n  return(str_out);\n\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//FUNCTION FOR PASSING RESULTS TO PYTHON AND R \n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nmat  std_vec2_to_arma_mat(svec2* A) {\n\n    uli nrows=(*A).size();\n    uli ncols=(*A)[0].size();\n    \n    mat V(nrows,ncols);\n    \n    for (uli j = 0; j < nrows; ++j) {\n     for (uli i = 0; i < ncols; ++i) {\n       V(j,i)=(*A)[j][i];\n     }\n    }\n   \n    return V;\n\n}\n\nsvec2  arma_mat_to_std_vec2(mat* A) {\n    \n    svec2  V((*A).n_rows);\n    for (size_t i = 0; i < (*A).n_rows; ++i) {\n        V[i] = conv_to< svec1 >::from((*A).row(i));\n    };\n    \n    return V;\n}\n\n\nfield<vec> std_vec3_to_arma_fie_vec(svec3* A){\n  \n    uli nrows=(*A).size(); //number of models\n    uli ncols=(*A)[0].size();; //number of parameter vectors\n    \n    field<vec> V(nrows,ncols);\n    \n    for (uli j = 0; j < nrows; ++j) {\n     for (uli i = 0; i < ncols; ++i) {\n       V(j,i)=(*A)[j][i];\n     }\n    }\n   \n    return V;\n  \n}\n\n\nsvec3 arma_fie_vec_to_std_vec3(field<vec>* A){\n  \n    uli nrows=(*A).n_rows; //number of models\n    uli ncols=(*A).n_cols; //number of parameter vectors\n    \n    svec3 V(nrows, vector< vector<double> >(ncols , vector<double>()));\n    // svec3 V;\n    // svec3.resize(nrows);\n    \n    for (uli j = 0; j < nrows; ++j) {\n     //V[j].resize(ncols);\n     for (uli i = 0; i < ncols; ++i) {\n       //V[j][i].push_back(conv_to< svec1 >::from((*A)(j,i)));\n       V[j][i]=conv_to< svec1 >::from((*A)(j,i));\n     }\n    }\n   \n    return V;\n  \n}\n\n#ifdef language_py\n\n\npair < svec3, pair < svec2, svec4 > > \nregpred_py(svec2& Y, double from_lag, double max_lag, double alpha, uli nsim, bool flg_print, string direction, string loss_function, bool pred_only, bool flg_const, bool flg_diff, svec4& vmodels){\n  \n  mat Y0=std_vec2_to_arma_mat(&Y);\n  \n  vector < field<vec> > vmodels0(2);\n  if(pred_only==1){\n   if((direction==\"->\") || (direction==\"<->\")){\n    vmodels0[0]=std_vec3_to_arma_fie_vec(&vmodels[0]);\n   }\n   if((direction==\"<-\") || (direction==\"<->\")){\n    vmodels0[1]=std_vec3_to_arma_fie_vec(&vmodels[1]);\n   }\n  }\n    \n  str_output str_out=regpred_cpp(&Y0, from_lag, max_lag, alpha, nsim, flg_print, direction, loss_function, pred_only, flg_const, flg_diff, vmodels0);\n\n  //store predictions\n    \n  svec3 vpredictions(3);\n  \n  svec2 predictions=arma_mat_to_std_vec2(&str_out.predictions);\n  svec2 fw_predictions=arma_mat_to_std_vec2(&str_out.fw_predictions);\n  svec2 bw_predictions=arma_mat_to_std_vec2(&str_out.bw_predictions);\n  \n  vpredictions[0]=predictions;\n  vpredictions[1]=fw_predictions;\n  vpredictions[2]=bw_predictions;\n  \n  //store performances\n  \n  svec2 vperformances(3);\n  \n  svec1 performances=conv_to< svec1 >::from(str_out.performances);\n  svec1 fw_performances=conv_to< svec1 >::from(str_out.fw_performances);\n  svec1 bw_performances=conv_to< svec1 >::from(str_out.bw_performances);\n  \n  vperformances[0]=performances;\n  vperformances[1]=fw_performances;\n  vperformances[2]=bw_performances;\n  \n  //store models\n  \n  svec4 vmodels1(2);\n  if(pred_only==0){\n     vmodels1[0]=arma_fie_vec_to_std_vec3(&str_out.fw_models);\n     vmodels1[1]=arma_fie_vec_to_std_vec3(&str_out.bw_models);\n  }\n  \n  //final store\n  \n  pair < svec3, pair < svec2, svec4 > > res;\n  res.first=vpredictions;\n  res.second.first=vperformances;\n  res.second.second=vmodels1;\n  \n  return(res);\n\n}\n\n#endif\n\n#ifdef language_R\n\ntemplate <typename T>\nNumericVector arma_vec_to_R_vec(const T* x) {\n    return NumericVector((*x).begin(), (*x).end());\n}\n\nvec R_vec_to_arma_vec(NumericVector* V) {\n    \n    uli nr=(uli) (*V).size();\n    \n    vec O(nr);\n    \n    for (size_t j = 0; j < nr; ++j) {\n      O(j)=(*V)(j);\n    }\n    \n    return(O);\n    \n}\n\nNumericMatrix  arma_mat_to_R_mat(mat* A) {\n    \n  NumericMatrix  V((*A).n_rows,(*A).n_cols);\n    \n\tfor (size_t j = 0; j < (*A).n_rows; ++j) {\n     for (size_t i = 0; i < (*A).n_cols; ++i) {\n        V(j,i) =(*A)(j,i);\n     }\n\t}\n    \n  return V;\n}\n\n\nfield<vec> R_List2_vec_to_arma_fie_vec(List L0){\n  \n  uli nrows=L0.size();\n  List L1=L0[0];\n  uli ncols=L1.size();\n  \n  NumericVector v;\n  field<vec> O(nrows,ncols);\n  \n  for (uli i0 = 0; i0 < nrows; ++i0){\n    L1=L0[i0];\n    for (uli i1 = 0; i1 < ncols; ++i1){\n      v=L1[i1];\n      O(i0,i1)=R_vec_to_arma_vec(&v);\n    }\n  }\n  \n  return(O);\n\n}\n\n\nList arma_fie_vec_to_R_List2_vec(field<vec>* F){\n  \n  uli nrows=(*F).n_rows;\n  uli ncols=(*F).n_cols;\n  \n  vec v;\n  List R0(nrows); \n  \n  for (uli i0 = 0; i0 < nrows; ++i0){\n    List R1(ncols);\n    for (uli i1 = 0; i1 < ncols; ++i1){\n      v=(*F)(i0,i1);\n      R1[i1]=arma_vec_to_R_vec(&v);\n    }\n    R0[i0]=R1;\n  }\n  \n  return(R0);\n  \n}\n\nRcppExport SEXP regpred_R(SEXP Y_p, SEXP from_lag_p, SEXP max_lag_p, SEXP alpha_p, SEXP nsim_p, SEXP flg_print_p, SEXP direction_p, SEXP loss_function_p, SEXP pred_only_p, SEXP flg_const_p, SEXP flg_diff_p, SEXP vmodels_p)\n{\n\n  NumericMatrix Y_0(Y_p); \n  mat Y(Y_0.begin(), Y_0.nrow(), Y_0.ncol(), false);\n  \n  NumericVector from_lag_0(from_lag_p); \n  double from_lag = Rcpp::as<double>(from_lag_0);\n  \n  NumericVector max_lag_0(max_lag_p); \n  double max_lag = Rcpp::as<double>(max_lag_0);\n  \n  NumericVector alpha_0(alpha_p); \n  double alpha = Rcpp::as<double>(alpha_0);\n  \n  NumericVector nsim_0(nsim_p); \n  uli nsim = Rcpp::as<uli>(nsim_0);\n  \n  NumericVector flg_print_0(flg_print_p); \n  bool flg_print = Rcpp::as<bool>(flg_print_0);\n\n  CharacterVector direction_0(direction_p); \n  string direction = Rcpp::as<string>(direction_0);\n\n  CharacterVector loss_function_0(loss_function_p); \n  string loss_function = Rcpp::as<string>(loss_function_0);\n  \n  NumericVector pred_only_0(pred_only_p); \n  bool pred_only = Rcpp::as<bool>(pred_only_0);\n  \n  NumericVector flg_const_0(flg_const_p);\n  bool flg_const = Rcpp::as<bool>(flg_const_0);\n  \n  NumericVector flg_diff_0(flg_diff_p);\n  bool flg_diff = Rcpp::as<bool>(flg_diff_0);\n  \n  List vmodels(vmodels_p);\n  \n  vector < field<vec> > vmodels0(2);\n  List fw_models;\n  List bw_models;\n  if(pred_only==1){\n   vmodels0[0]=R_List2_vec_to_arma_fie_vec(vmodels[0]);\n   vmodels0[1]=R_List2_vec_to_arma_fie_vec(vmodels[1]);\n   fw_models=vmodels[0];\n   bw_models=vmodels[1];\n  }\n\n  str_output str_out=regpred_cpp(&Y, from_lag, max_lag, alpha, nsim, flg_print, direction, loss_function, pred_only, flg_const, flg_diff, vmodels0);\n  \n  //store predictions\n  \n  NumericMatrix predictions=arma_mat_to_R_mat(&str_out.predictions);\n  NumericMatrix fw_predictions=arma_mat_to_R_mat(&str_out.fw_predictions);\n  NumericMatrix bw_predictions=arma_mat_to_R_mat(&str_out.bw_predictions);\n  \n  //store performances\n  \n  NumericVector performances=arma_vec_to_R_vec(&str_out.performances);\n  NumericVector fw_performances=arma_vec_to_R_vec(&str_out.fw_performances);\n  NumericVector bw_performances=arma_vec_to_R_vec(&str_out.bw_performances);\n  \n  //store models\n  \n  if(pred_only==0){\n     fw_models=arma_fie_vec_to_R_List2_vec(&str_out.fw_models);\n     bw_models=arma_fie_vec_to_R_List2_vec(&str_out.bw_models);\n  }\n  \n  /*maximum 20 elements admitted for each level*/\n  List res=List::create(\n    Named(\"prediction\")=List::create(\n      Named(\"final\") = predictions,\n      Named(\"forward\") = fw_predictions,\n      Named(\"backward\") = bw_predictions\n    ),\n    Named(\"performance\")=List::create(\n      Named(\"final\") = performances,\n      Named(\"forward\") = fw_performances, \n      Named(\"backward\") = bw_performances\n    ),\n    Named(\"model\")=List::create( \n      Named(\"forward\") = fw_models, \n      Named(\"backward\") = bw_models \n    )\n  );\n\n  return(res);\n\n}\n\n#endif\n \n", "meta": {"hexsha": "d68d74069adc76401a352e66cd88ddcb5d158ecc", "size": 56668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/functions.cpp", "max_stars_repo_name": "DavideAltomare/rego", "max_stars_repo_head_hexsha": "9caac57e20f408d1925ad244a755f596d4dc5641", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2022-01-05T21:53:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T11:40:44.000Z", "max_issues_repo_path": "c++/functions.cpp", "max_issues_repo_name": "DavideAltomare/rego", "max_issues_repo_head_hexsha": "9caac57e20f408d1925ad244a755f596d4dc5641", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-05T10:08:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T08:17:34.000Z", "max_forks_repo_path": "c++/functions.cpp", "max_forks_repo_name": "DavideAltomare/rego", "max_forks_repo_head_hexsha": "9caac57e20f408d1925ad244a755f596d4dc5641", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-06T10:33:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T21:35:40.000Z", "avg_line_length": 22.196631414, "max_line_length": 222, "alphanum_fraction": 0.5604397544, "num_tokens": 18878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325346, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6122085056934554}}
{"text": "// Copyright Louis Dionne 2013-2016\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\r\n\r\n#include <boost/hana/equal.hpp>\r\n#include <boost/hana/filter.hpp>\r\n#include <boost/hana/integral_constant.hpp>\r\n#include <boost/hana/mod.hpp>\r\n#include <boost/hana/tuple.hpp>\r\n\r\n\r\nstruct is_even {\r\n    template <typename N>\r\n    constexpr auto operator()(N n) const {\r\n        return n % boost::hana::int_c<2> == boost::hana::int_c<0>;\r\n    }\r\n};\r\n\r\nint main() {\r\n    constexpr auto tuple = boost::hana::make_tuple(\r\n        <%= (1..input_size).map { |n| \"boost::hana::int_c<#{n}>\" }.join(', ') %>\r\n    );\r\n    constexpr auto result = boost::hana::filter(tuple, is_even{});\r\n    (void)result;\r\n}\r\n", "meta": {"hexsha": "6f52ba15fe62cbe211e7969206554249c19e9b88", "size": 782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/hana/benchmark/filter/compile.hana.tuple.erb.cpp", "max_stars_repo_name": "snichols/boost_1_61_0", "max_stars_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-06T09:03:52.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-06T09:03:52.000Z", "max_issues_repo_path": "libs/hana/benchmark/filter/compile.hana.tuple.erb.cpp", "max_issues_repo_name": "snichols/boost_1_61_0", "max_issues_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "max_issues_repo_licenses": ["BSL-1.0"], "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/hana/benchmark/filter/compile.hana.tuple.erb.cpp", "max_forks_repo_name": "snichols/boost_1_61_0", "max_forks_repo_head_hexsha": "10142fe2415a0c4ddb72207b5f235cce20f72649", "max_forks_repo_licenses": ["BSL-1.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.0769230769, "max_line_length": 82, "alphanum_fraction": 0.6368286445, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6121611667604924}}
{"text": "//  Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// Basic sanity check that header <boost/math/special_functions/gamma.hpp>\n// #includes all the files that it needs to.\n//\n#include <boost/math/special_functions/gamma.hpp>\n//\n// Note this header includes no other headers, this is\n// important if this test is to be meaningful:\n//\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n   check_result<float>(boost::math::tgamma<float>(f));\n   check_result<double>(boost::math::tgamma<double>(d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::tgamma<long double>(l));\n#endif\n\n   check_result<float>(boost::math::lgamma<float>(f));\n   check_result<double>(boost::math::lgamma<double>(d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::lgamma<long double>(l));\n#endif\n\n   check_result<float>(boost::math::gamma_p<float>(f, f));\n   check_result<double>(boost::math::gamma_p<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::gamma_p<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::gamma_q<float>(f, f));\n   check_result<double>(boost::math::gamma_q<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::gamma_q<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::gamma_p_inv<float>(f, f));\n   check_result<double>(boost::math::gamma_p_inv<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::gamma_p_inv<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::gamma_q_inv<float>(f, f));\n   check_result<double>(boost::math::gamma_q_inv<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::gamma_q_inv<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::gamma_p_inva<float>(f, f));\n   check_result<double>(boost::math::gamma_p_inva<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::gamma_p_inva<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::gamma_q_inva<float>(f, f));\n   check_result<double>(boost::math::gamma_q_inva<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::gamma_q_inva<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::gamma_p_derivative<float>(f, f));\n   check_result<double>(boost::math::gamma_p_derivative<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::gamma_p_derivative<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::tgamma_ratio<float>(f, f));\n   check_result<double>(boost::math::tgamma_ratio<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::tgamma_ratio<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::tgamma_delta_ratio<float>(f, f));\n   check_result<double>(boost::math::tgamma_delta_ratio<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::tgamma_delta_ratio<long double>(l, l));\n#endif\n}\n", "meta": {"hexsha": "f7ad18e9c1ca20d711885d0e6a85ce3a2603ce6e", "size": 3415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/test/compile_test/sf_gamma_incl_test.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/test/compile_test/sf_gamma_incl_test.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/test/compile_test/sf_gamma_incl_test.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 40.6547619048, "max_line_length": 81, "alphanum_fraction": 0.7519765739, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6121611664364078}}
{"text": "// Copyright (c) 2013, Manuel Blum\n// All rights reserved.\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <cstdio>\n\n#include \"nn.h\"\n\nint main (int argc, const char* argv[]) {\n\n  // input dimensionality\n  int n_input = 2;\n  // output dimensionality\n  int n_output = 1;\n  // number of training samples\n  int m = 4;\n  // number of layers\n  int k = 3;\n  // number of optimization steps\n  int max_steps = 50;\n  // regularization parameter\n  double lambda = 0.000001;\n\n  // training inputs\n  matrix_t X(m, n_input);\n  matrix_t Y(m, n_output);\n\n  // XOR problem\n  X << 0, 0, 0, 1, 1, 0, 1, 1;\n  Y << 0, 1, 1, 0;\n  std::cout << \"training input: \" << std::endl << X << std::endl;\n  std::cout << \"training output: \" << std::endl << Y << std::endl;\n\n  // specify network topology\n  Eigen::VectorXi topo(k);\n  topo << n_input, 6, n_output;\n  std::cout << \"topology: \" << std::endl << topo << std::endl;\n\n  // initialize a neural network with given topology\n  NeuralNet nn(topo);\n\n  nn.autoscale(X,Y);\n  \n  // train the network\n  std::cout << \"starting training\" << std::endl;\n  double err;\n  for (int i = 0; i < max_steps; ++i) {\n    err = nn.loss(X, Y, lambda);\n    nn.rprop();\n    printf(\"%3i   %4.4f\\n\", i, err);\n  }\n\n  // write model to disk\n  nn.write(\"example.nn\");\n\n  // read model from disk\n  NeuralNet nn2(\"example.nn\");\n\n  // testing \n  nn2.forward_pass(X);\n  matrix_t Y_test = nn2.get_activation();\n\n  std::cout << \"test input:\" << std::endl << X << std::endl;\n  std::cout << \"test output:\" << std::endl << Y_test << std::endl;\n\n  return 0;\n}\n\n", "meta": {"hexsha": "301bde4d19088e88a2852c889fe4b85888f79ce0", "size": 1549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tutorial.cpp", "max_stars_repo_name": "mblum/nn", "max_stars_repo_head_hexsha": "f5fbba4ad93ce72798828d03b9b7d34dfb48a10f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-05-27T11:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-12T14:57:31.000Z", "max_issues_repo_path": "tutorial.cpp", "max_issues_repo_name": "mblum/nn", "max_issues_repo_head_hexsha": "f5fbba4ad93ce72798828d03b9b7d34dfb48a10f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial.cpp", "max_forks_repo_name": "mblum/nn", "max_forks_repo_head_hexsha": "f5fbba4ad93ce72798828d03b9b7d34dfb48a10f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-08-25T11:04:43.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-15T04:36:25.000Z", "avg_line_length": 22.1285714286, "max_line_length": 66, "alphanum_fraction": 0.6010329245, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6121611661123232}}
{"text": "#include <iostream>\n#include <complex>\n#include <cmath>\n#include <string>\n#include <fstream>\n#include <Eigen/Eigen>\n#include \"Component.h\"\n\nusing namespace Eigen;\nusing namespace std;\n\n\nconst double PI = 3.141592;\ndouble w;\nint VS_num = 0, CS_num = 0, R_num = 0, L_num = 0, C_num = 0, nodes_num = 0;\nifstream input;\nofstream output;\nvector<Component> components;\n\n\n// Read The input from external file\nbool read()\n{\n    string s;\n    cout << \"Enter INPUT file name: \";\n    cin >> s;\n    input.open(s + \".txt\");\n    if (input.is_open())\n    {\n        input >> s;\n        w = stoi(s);\n\n        while (!input.eof())\n        {\n            input >> s;\n            if (s == \"Vs\")\n            {\n                string n1, n2, mag, phase;\n                Component VScource;\n                VScource.name = s;\n                input >> n1 >> n2 >> mag >> phase;\n        \n\t\t\t\tVScource.node1 = stoi(n1);\n                VScource.node2 = stoi(n2);\n                \n\t\t\t\tdouble magn = stod(mag);\n                double ph = stod(phase);\n                \n\t\t\t\tVScource.voltage = complex<double>(magn * cos(ph * PI / 180),\n                    magn * sin(ph * PI / 180));\n\n                components.push_back(VScource);\n                VS_num++;\n            }\n            else if (s == \"Cs\")\n            {\n                string n1, n2, mag, phase;\n                Component SScource;\n                SScource.name = s;\n                \n\t\t\t\tinput >> n1 >> n2 >> mag >> phase;\n                \n\t\t\t\tSScource.node1 = stoi(n1);\n                SScource.node2 = stoi(n2);\n                \n\t\t\t\tdouble magn = stod(mag);\n                double ph = stod(phase);\n                \n\t\t\t\tSScource.current = complex<double>(magn * cos(ph * PI / 180),\n                    magn * sin(ph * PI / 180));\n                components.push_back(SScource);\n\n                CS_num++;\n            }\n\n            else if (s[0] == 'R')\n            {\n                string n1, n2, mag;\n                Component R;\n                R.name = s;\n                input >> n1 >> n2 >> mag;\n                R.node1 = stoi(n1);\n                R.node2 = stoi(n2);\n\n                float magn = stof(mag);\n                R.Z = complex<double>(magn, 0);\n                \n\t\t\t\tR.Y = pow(R.Z, -1);\n                R.factor = 0;\n                components.push_back(R);\n                R_num++;\n            }\n            else if (s[0] == 'C')\n            {\n                string n1, n2, factor;\n                Component C;\n                C.name = s;\n                \n\t\t\t\tinput >> n1 >> n2 >> factor;\n                \n\t\t\t\tC.node1 = stoi(n1);\n                C.node2 = stoi(n2);\n                double magn = stod(factor);\n                \n\t\t\t\tC.Z = complex<double>(0, -1 / (w * magn));\n                C.Y = pow(C.Z, -1);\n                \n\t\t\t\tC.factor = magn;\n                components.push_back(C);\n                C_num++;\n            }\n            else if (s[0] == 'L')\n            {\n                string n1, n2, factor;\n                Component L;\n                L.name = s;\n                \n\t\t\t\tinput >> n1 >> n2 >> factor;\n                \n\t\t\t\tL.node1 = stoi(n1);\n                L.node2 = stoi(n2);\n                \n\t\t\t\tdouble magn = stod(factor);\n                \n\t\t\t\tL.Z = complex<double>(0, w * magn);\n                L.Y = pow(L.Z, -1); //(0, -1/(w*magn));\n                L.factor = magn;\n                \n\t\t\t\tcomponents.push_back(L);\n                L_num++;\n            }\n        }\n    }\n    else\n    {\n        cout << \"Wrong name, Enter a valid name\\n\";\n        return false;\n    }\n    return true;\n}\n\nint main()\n{\n    if (read())\n        ;\n    else\n    {\n        while (true)\n        {\n            cout << \"Please Enter a valid name\\n\";\n            if (read())\n                break;\n        }\n    }\n\n    for (int i = 0; i < components.size(); ++i)\n    {\n        if (components[i].node1 > nodes_num)\n            nodes_num = components[i].node1;\n        if (components[i].node2 > nodes_num)\n            nodes_num = components[i].node2;\n    }\n\n    int Eqs = nodes_num;\n    for (int i = 0; i < components.size(); ++i)\n    {\n        if (components[i].name == \"Vs\")\n        {\n            Eqs++;\n            components[i].VS_num = Eqs;\n        }\n    }\n\n    Eigen::MatrixXcd Ys(Eqs, Eqs);\n    Eigen::MatrixXcd VS(Eqs, 1);\n    Eigen::MatrixXcd IS(Eqs, 1);\n\n    for (int i = 0; i < Eqs; ++i)\n        for (int j = 0; j < Eqs; ++j)\n            Ys(i, j).imag(0), Ys(i, j).real(0);\n\n\tfor (int i = 0; i < Eqs; ++i)\n    {\n        VS(i, 0).imag(0);\n        VS(i, 0).real(0);\n\n        IS(i, 0).imag(0);\n        IS(i, 0).real(0);\n    }\n    \n\tvector<complex<double> > Vnodes(nodes_num);\n    for (int i = 0; i < components.size(); ++i)\n    {\n        // first of all, if we have a voltage source\n        if (components[i].node1 == 0 && components[i].name == \"Vs\")\n        {\n            // Vnodes[components[i].node2] = components[i].voltage;\n            Ys(components[i].node2 - 1, components[i].VS_num - 1) += complex<double>(-1, 0);\n            Ys(components[i].VS_num - 1, components[i].node2 - 1) += complex<double>(-1, 0);\n            VS(components[i].VS_num - 1, 0) += components[i].voltage;\n        }\n        else if (components[i].node2 == 0 && components[i].name == \"Vs\")\n        {\n            Ys(components[i].node1 - 1, components[i].VS_num - 1) += complex<double>(1, 0);\n            Ys(components[i].VS_num - 1, components[i].node1 - 1) += complex<double>(1, 0);\n            VS(components[i].VS_num - 1, 0) += components[i].voltage;\n        }\n        else if (components[i].node1 != 0 && components[i].node2 != 0\n            && components[i].name == \"Vs\") // same as previus but we have two additional equations\n        {\n            Ys(components[i].node1 - 1, components[i].VS_num - 1) += complex<double>(1, 0);\n            Ys(components[i].node2 - 1, components[i].VS_num - 1) += complex<double>(-1, 0);\n            Ys(components[i].VS_num - 1, components[i].node1 - 1) += complex<double>(1, 0);\n            Ys(components[i].VS_num - 1, components[i].node2 - 1) += complex<double>(-1, 0);\n            VS(components[i].VS_num - 1, 0) += components[i].voltage;\n        }\n\n        // If we have current sources\n        else if (components[i].name == \"Cs\" && components[i].node1 == 0)\n        {\n            VS(components[i].node2 - 1, 0) -= components[i].current;\n        }\n        else if (components[i].name == \"Cs\" && components[i].node2 == 0)\n        {\n            VS(components[i].node1 - 1, 0) += components[i].current;\n        }\n        else if (components[i].name == \"Cs\" && components[i].node1 != 0 && components[i].node2 != 0)\n        {\n            VS(components[i].node2 - 1, 0) -= components[i].current;\n            VS(components[i].node1 - 1, 0) += components[i].current;\n        }\n\n        // Now if we have passive components\n        else if (components[i].name[0] == 'R' || components[i].name[0] == 'C'\n            || components[i].name[0] == 'L')\n        {\n            if (components[i].node1 == 0)\n            {\n                Ys(components[i].node2 - 1, components[i].node2 - 1) += components[i].Y;\n            }\n            else if (components[i].node2 == 0)\n            {\n                Ys(components[i].node1 - 1, components[i].node1 - 1) += components[i].Y;\n            }\n            else if (components[i].node1 != 0 && components[i].node2 != 0)\n            {\n                Ys(components[i].node1 - 1, components[i].node1 - 1) += components[i].Y;\n                Ys(components[i].node2 - 1, components[i].node1 - 1) -= components[i].Y;\n                Ys(components[i].node2 - 1, components[i].node2 - 1) += components[i].Y;\n                Ys(components[i].node1 - 1, components[i].node2 - 1) += components[i].Y;\n            }\n        }\n    }\n\n    IS += Ys.jacobiSvd(ComputeThinU | ComputeThinV).solve(VS);\n    cout << \"\\n\";\n\n    cout << Ys << \"\\n\\n\\n\";\n    cout << VS << \"\\n\\n\\n\";\n    cout << IS;\n    cout << \"\\n\";\n\n\n    for (int i = 0; i < Eqs; i++)\n    {\n\n        IS(i, 0).real(int(IS(i, 0).real() * 1000) / 1000.0);\n        IS(i, 0).imag(int(IS(i, 0).imag() * 1000) / 1000.0);\n    }\n    int i = 0;\n    for (; i < nodes_num; i++)\n    {\n        cout << \"V(\" << i + 1 << \")\"\n             << \" \" << abs(IS(i, 0)) << \" \" << (arg(IS(i, 0)) * (180 / 3.141592654));\n        cout << endl;\n    }\n    for (int j = 0; j < nodes_num; j++)\n    {\n        if (components[j].name == \"Vs\")\n        {\n            cout << \"I(\" << components[j].node1 << \" \" << components[j].node2 << \")\"\n                 << \" \" << abs(IS(i, 0)) << \" \" << (arg(IS(i, 0)) * (180 / 3.141592654));\n            i++;\n            cout << endl;\n        }\n        if (components[j].name == \"Is\")\n        {\n            cout << \"I(\" << components[j].node2 << \" \" << components[j].node1 << \")\"\n                 << \" \" << abs(components[j].current) << \" \"\n                 << (arg(components[j].current) * (180 / 3.141592654));\n            cout << endl;\n        }\n        if (components[j].name[0] == 'R' || components[j].name[0] == 'L'\n            || components[j].name[0] == 'C')\n        {\n            if (components[j].node1 != 0 && components[j].node1 != 0)\n            {\n                complex<double> I\n                    = ((IS(components[j].node1 - 1, 0) - IS(components[j].node2 - 1, 0))\n                        / components[j].Z);\n                cout << \"I(\" << components[j].node1 << \" \" << components[j].node2 << \")\"\n                     << \" \" << abs(I) << \" \" << (arg(I) * (180 / 3.141592654));\n                cout << endl;\n            }\n            else\n            {\n                if (components[j].node1 == 0)\n                {\n                    complex<double> I = ((complex<double>(0, 0) - IS(components[j].node2 - 1, 0))\n                        / components[j].Z);\n                    cout << \"I(\" << components[j].node1 << \" \" << components[j].node2 << \")\"\n                         << \" \" << abs(I) << \" \" << (arg(I) * (180 / 3.141592654));\n                    cout << endl;\n                }\n                else if (components[j].node2 == 0)\n                {\n                    complex<double> I = ((IS(components[j].node1 - 1, 0)) / components[j].Z);\n                    cout << \"I(\" << components[j].node1 << \" \" << components[j].node2 << \")\"\n                         << \" \" << abs(I) << \" \" << (arg(I) * (180 / 3.141592654));\n                    cout << endl;\n                }\n            }\n        }\n    }\n    system(\"PAUSE\");\n    return 0;\n}", "meta": {"hexsha": "d702c9f88e13522e7ee94878b1f76800cd336c38", "size": 10420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/Circuits/Solver.cpp", "max_stars_repo_name": "AbdallahHemdan/Circuits-Solver", "max_stars_repo_head_hexsha": "5706d82220d80e52f306aa8bfceee39a31ab5b3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-03-18T17:42:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T22:01:15.000Z", "max_issues_repo_path": "Src/Circuits/Solver.cpp", "max_issues_repo_name": "AbdallahHemdan/Circuits-Solver", "max_issues_repo_head_hexsha": "5706d82220d80e52f306aa8bfceee39a31ab5b3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/Circuits/Solver.cpp", "max_forks_repo_name": "AbdallahHemdan/Circuits-Solver", "max_forks_repo_head_hexsha": "5706d82220d80e52f306aa8bfceee39a31ab5b3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-13T09:01:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-13T09:01:43.000Z", "avg_line_length": 31.8654434251, "max_line_length": 100, "alphanum_fraction": 0.4215930902, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6121611611278039}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  MatrixXcf a = MatrixXcf::Random(2,2);\ncout << \"Here is the matrix a\\n\" << a << endl;\n\ncout << \"Here is the matrix a^T\\n\" << a.transpose() << endl;\n\n\ncout << \"Here is the conjugate of a\\n\" << a.conjugate() << endl;\n\n\ncout << \"Here is the matrix a^*\\n\" << a.adjoint() << endl;\n\n\n\n  return 0;\n}\n", "meta": {"hexsha": "1ff54f4602f51e5dde646e9abeff9d43a639752c", "size": 428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_tut_arithmetic_transpose_conjugate.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_tut_arithmetic_transpose_conjugate.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_tut_arithmetic_transpose_conjugate.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": 17.12, "max_line_length": 64, "alphanum_fraction": 0.6191588785, "num_tokens": 129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7931059536292271, "lm_q1q2_score": 0.6121536734061777}}
{"text": "https://www.boost.org/doc/libs/1_72_0/libs/multiprecision/doc/html/boost_multiprecision/tut/ints/egs/factorials.html\n\n#include <iostream>\n#include <cassert>\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::cpp_int;\n\nusing namespace std;\n\ncpp_int factorial(int n)\n{\n    assert(n >= 0);\n    if (n <= 1)\n        return 1;\n    else\n        return n * factorial(n - 1);\n}\n\nint main()\n{\n    for (int i = 0; i < 10; i++)\n        cout << i << \"!=\" << factorial(i) << endl;\n}\n\n/*\n\n*/", "meta": {"hexsha": "79fb5783fec2f3ccabbb8e4bc5339caa96555498", "size": 499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "various/boost_examples/factorial.cpp", "max_stars_repo_name": "chgogos/oop", "max_stars_repo_head_hexsha": "3b0e6bbd29a76f863611e18d082913f080b1b571", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-04-23T13:45:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T18:26:47.000Z", "max_issues_repo_path": "various/boost_examples/factorial.cpp", "max_issues_repo_name": "chgogos/oop", "max_issues_repo_head_hexsha": "3b0e6bbd29a76f863611e18d082913f080b1b571", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "various/boost_examples/factorial.cpp", "max_forks_repo_name": "chgogos/oop", "max_forks_repo_head_hexsha": "3b0e6bbd29a76f863611e18d082913f080b1b571", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-09-01T15:17:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T20:31:36.000Z", "avg_line_length": 17.8214285714, "max_line_length": 116, "alphanum_fraction": 0.621242485, "num_tokens": 144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6121536673565352}}
{"text": "/** \\file oaranktest.cpp\n\nC++ program: oaranktest\n\noaranktest: tool for testing speed of rank calculations\n\nAuthor: Pieter Eendebak <pieter.eendebak@gmail.com>, (C) 2016\n\nCopyright: See LICENSE.txt file that comes with this distribution\n*/\n\n#include <algorithm>\n#include <iostream>\n#include <map>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"anyoption.h\"\n#include \"arrayproperties.h\"\n#include \"arraytools.h\"\n#include \"tools.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\n#include \"Deff.h\"\n#include \"arraytools.h\"\n#include \"strength.h\"\n\nusing namespace Eigen;\n\nint main (int argc, char *argv[]) {\n        AnyOption opt;\n        /* parse command line options */\n        opt.setFlag (\"help\", 'h'); \n        opt.setOption (\"output\", 'o');\n        opt.setOption (\"input\", 'I');\n        opt.setOption (\"rand\", 'r');\n        opt.setOption (\"niter\", 'n');\n        opt.setOption (\"verbose\", 'v');\n        opt.setOption (\"ii\", 'i');\n\n        opt.addUsage (\"Orthonal Array: oaranktest: testing platform\");\n        opt.addUsage (\"Usage: oatest [OPTIONS] [FILE]\");\n        opt.addUsage (\"\");\n        opt.addUsage (\" -h --help  \t\t\tPrints this help \");\n        opt.processCommandArgs (argc, argv);\n\n        double t0 = get_time_ms (), dt = 0;\n        int randvalseed = opt.getIntValue ('r', 1);\n        int xx = opt.getIntValue ('x', 0);\n        int niter = opt.getIntValue (\"niter\", 2);\n        int verbose = opt.getIntValue (\"verbose\", 1);\n\n        const char *input = opt.getValue ('I');\n        if (input == 0)\n                input = \"test.oa\";\n\n        srand (randvalseed);\n        if (randvalseed == -1) {\n                randvalseed = time (NULL);\n                printf (\"random seed %d\\n\", randvalseed);\n                srand (randvalseed);\n        }\n\n        print_copyright ();\n\n        /* parse options */\n        if (opt.getFlag (\"help\") || opt.getFlag ('h') || opt.getArgc () < 0) {\n                opt.printUsage ();\n                exit (0);\n        }\n\n        /* read data from file */\n\n        double t00 = get_time_ms ();\n        t0 = get_time_ms ();\n        arraylist_t ll = readarrayfile (input);\n        std::sort (ll.begin (), ll.end ());\n        dt = get_time_ms () - t0;\n\n        int s = ll.size ();\n        for (int j = 0; j < niter; j++) {\n                for (int i = 0; i < s; i++) {\n                        ll.push_back (ll[i]);\n                }\n        }\n\n        if (verbose)\n                printf (\"oaranktest: %ld arrays (reading %.3f [s])\\n\", ll.size (), dt);\n\n        const long nn = ll.size ();\n        std::vector< int > rr (nn);\n        t0 = get_time_ms ();\n        for (size_t i = 0; i < ll.size (); i++) {\n                array_link A = ll[i];\n                array_link B = array2xf (A);\n                int r1 = arrayrankColPivQR (B);\n                rr[i] = r1;\n\n                if (verbose >= 3) {\n                        B.show ();\n                        int rank_lu = arrayrankFullPivLU (B);\n                        int rank_svd = arrayrankSVD (B);\n\t\t\t\t\t\tmyprintf(\"arrayrankFullPivLU: %d, arrayrankSVD %d\", rank_lu, rank_svd);\n\n                }\n        }\n        const array_link al0 = ll[0];\n        printf (\"warm-up complete\\n\");\n\n        t0 = get_time_ms ();\n        for (size_t i = 0; i < ll.size (); i++) {\n                array_link A = ll[i];\n                array_link B = array2secondorder (A);\n        }\n        dt = get_time_ms () - t0;\n        printf (\"oaranktest: conversion to second order (%.3f [s], %.3f Marrays/s)\\n\", dt, nn / dt);\n\n        if (1) {\n                t0 = get_time_ms ();\n                for (size_t i = 0; i < ll.size (); i++) {\n                        array_link A = ll[i];\n                        array_link B = array2xf (A);\n                        int r = arrayrankSVD (B);\n                        if (r != rr[i]) {\n                                printfd (\"error: i %d, r %d rr[i] %d\\n\", i, r, rr[i]);\n                        }\n                        myassert (r == rr[i], \"arrayrankSVD\");\n                }\n                dt = get_time_ms () - t0;\n                printf (\"oaranktest: rank SVD (%.3f [s], %.3f Marrays/s)\\n\", dt, nn / dt);\n        }\n\n        if (1) {\n\n                t0 = get_time_ms ();\n                for (size_t i = 0; i < ll.size (); i++) {\n                        array_link A = ll[i];\n                        array_link B = array2xf (A);\n                        int r = arrayrankFullPivLU (B);\n\n                        if (r != rr[i]) {\n                                printfd (\"error: i %d, r %d rr[i] %d\\n\", i, r, rr[i]);\n                        }\n                        myassert (r == rr[i], \"FullPivLU\");\n                }\n                dt = get_time_ms () - t0;\n                printf (\"oaranktest: rank FullPivLU (%.3f [s], %.3f Marrays/s)\\n\", dt, nn / dt);\n        }\n\n        if (verbose >= 2) {\n                array2xf (al0).showarray ();\n        }\n        if (1) {\n                t0 = get_time_ms ();\n                for (size_t i = 0; i < ll.size (); i++) {\n                        array_link A = ll[i];\n                        array_link B = array2xf (A);\n                        int r = arrayrankColPivQR (B);\n                        if (r != rr[i]) {\n                                printfd (\"error: i %d, r %d rr[i] %d\\n\", i, r, rr[i]);\n                        }\n                        myassert (r == rr[i], \"arrayrankColPivQR\");\n                }\n                dt = get_time_ms () - t0;\n                printf (\"oaranktest: rank ColPiv (%.3f [s], %.3f Marrays/s)\\n\", dt, nn / dt);\n        }\n\n        for (int nsub = 2; nsub < 5; nsub++) {\n                rankStructure rank_calculator (al0.selectFirstColumns (al0.n_columns - nsub), nsub, 0);\n                if (verbose >= 2) {\n                        rank_calculator.alsub.show ();\n                        printf (\"subrank: %d\\n\", arrayrankFullPivLU (array2xf (rank_calculator.alsub)));\n                        printf (\"---\\n\\n\");\n                }\n                t0 = get_time_ms ();\n                for (size_t i = 0; i < ll.size (); i++) {\n                        array_link A = ll[i];\n                        int r = rank_calculator.rankxf (A);\n                        if (r != rr[i]) {\n                                printfd (\"  i %d, r %d rr[i] %d\\n\", i, r, rr[i]);\n                        }\n                        assert (r == rr[i]);\n                }\n                dt = get_time_ms () - t0;\n                printf (\"oaranktest: rank ColPivHouseholderQR-cache (nsub %d, %.3f [s], %.3f Marrays/s)\\n\", nsub, dt,\n                        nn / dt);\n        }\n\n        return 0;\n}\n\n", "meta": {"hexsha": "ae768ca393025bbd8ba4f78ae1f4ff106af133ff", "size": 6615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/oaranktest.cpp", "max_stars_repo_name": "ABohynDOE/oapackage", "max_stars_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-11-06T07:24:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T22:02:19.000Z", "max_issues_repo_path": "utils/oaranktest.cpp", "max_issues_repo_name": "ABohynDOE/oapackage", "max_issues_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2015-11-06T07:25:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T01:33:47.000Z", "max_forks_repo_path": "utils/oaranktest.cpp", "max_forks_repo_name": "ABohynDOE/oapackage", "max_forks_repo_head_hexsha": "d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-08-16T15:09:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T11:48:55.000Z", "avg_line_length": 33.75, "max_line_length": 117, "alphanum_fraction": 0.4296296296, "num_tokens": 1714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6120149849358025}}
{"text": "// unit test file atanh.hpp for the special functions test suite\r\n\r\n//  (C) Copyright Hubert Holin 2003.\r\n//  Distributed under the Boost Software License, Version 1.0. (See\r\n//  accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n#include <functional>\r\n#include <iomanip>\r\n//#include <iostream>\r\n\r\n\r\n#include <boost/math/special_functions/atanh.hpp>\r\n\r\n\r\n#include <boost/test/unit_test.hpp>\r\n#include <boost/test/test_case_template.hpp>\r\n\r\ntemplate<typename T>\r\nT    atanh_error_evaluator(T x)\r\n{\r\n    using    ::std::abs;\r\n    using    ::std::tanh;\r\n    using    ::std::cosh;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::atanh;\r\n    \r\n    \r\n    static T const   epsilon = numeric_limits<float>::epsilon();\r\n    \r\n    T                y = tanh(x);\r\n    T                z = atanh(y);\r\n    \r\n    T                absolute_error = abs(z-x);\r\n    T                relative_error = absolute_error/(cosh(x)*cosh(x));\r\n    T                scaled_error = relative_error/epsilon;\r\n    \r\n    return(scaled_error);\r\n}\r\n\r\n\r\nBOOST_TEST_CASE_TEMPLATE_FUNCTION(atanh_test, T)\r\n{\r\n    using    ::std::abs;\r\n    using    ::std::tanh;\r\n    using    ::std::log;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    using    ::boost::math::atanh;\r\n    \r\n    \r\n    BOOST_MESSAGE(\"Testing atanh in the real domain for \"\r\n        << string_type_name<T>::_() << \".\");\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(),\r\n        (abs(atanh<T>(static_cast<T>(0))))\r\n        (numeric_limits<T>::epsilon()));\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(),\r\n        (abs(atanh<T>(static_cast<T>(3)/5) - log(static_cast<T>(2))))\r\n        (numeric_limits<T>::epsilon()));\r\n    \r\n    BOOST_CHECK_PREDICATE(::std::less_equal<T>(),\r\n        (abs(atanh<T>(static_cast<T>(-3)/5) + log(static_cast<T>(2))))\r\n        (numeric_limits<T>::epsilon()));\r\n    \r\n    for    (int i = 0; i <= 100; i++)\r\n    {\r\n        T    x = static_cast<T>(i-50)/static_cast<T>(5);\r\n        T    y = tanh(x);\r\n        \r\n        if    (\r\n                (abs(y-static_cast<T>(1)) >= numeric_limits<T>::epsilon())&&\r\n                (abs(y+static_cast<T>(1)) >= numeric_limits<T>::epsilon())\r\n            )\r\n        {\r\n            BOOST_CHECK_PREDICATE(::std::less_equal<T>(),\r\n                (atanh_error_evaluator(x))\r\n                (static_cast<T>(4)));\r\n        }\r\n    }\r\n}\r\n\r\n\r\nvoid    atanh_manual_check()\r\n{\r\n    using    ::std::abs;\r\n    using    ::std::tanh;\r\n        \r\n    using    ::std::numeric_limits;\r\n    \r\n    \r\n    BOOST_MESSAGE(\" \");\r\n    BOOST_MESSAGE(\"atanh\");\r\n    \r\n    for    (int i = 0; i <= 100; i++)\r\n    {\r\n        float        xf = static_cast<float>(i-50)/static_cast<float>(5);\r\n        double       xd = static_cast<double>(i-50)/static_cast<double>(5);\r\n        long double  xl =\r\n                static_cast<long double>(i-50)/static_cast<long double>(5);\r\n        \r\n        float        yf = tanh(xf);\r\n        double       yd = tanh(xd);\r\n        (void) &yd;        // avoid \"unused variable\" warning\r\n        long double  yl = tanh(xl);\r\n        (void) &yl;        // avoid \"unused variable\" warning\r\n        \r\n        if    (\r\n                std::numeric_limits<float>::has_infinity &&\r\n                std::numeric_limits<double>::has_infinity &&\r\n                std::numeric_limits<long double>::has_infinity\r\n            )\r\n        {\r\n            BOOST_MESSAGE( ::std::setw(15)\r\n                        << atanh_error_evaluator(xf)\r\n                        << ::std::setw(15)\r\n                        << atanh_error_evaluator(xd)\r\n                        << ::std::setw(15)\r\n                        << atanh_error_evaluator(xl));\r\n        }\r\n        else\r\n        {\r\n            if    (\r\n                    (abs(yf-static_cast<float>(1)) <\r\n                        numeric_limits<float>::epsilon())||\r\n                    (abs(yf+static_cast<float>(1)) <\r\n                        numeric_limits<float>::epsilon())||\r\n                    (abs(yf-static_cast<double>(1)) <\r\n                        numeric_limits<double>::epsilon())||\r\n                    (abs(yf+static_cast<double>(1)) <\r\n                        numeric_limits<double>::epsilon())||\r\n                    (abs(yf-static_cast<long double>(1)) <\r\n                        numeric_limits<long double>::epsilon())||\r\n                    (abs(yf+static_cast<long double>(1)) <\r\n                        numeric_limits<long double>::epsilon())\r\n                )\r\n            {\r\n                BOOST_MESSAGE(\"Platform's numerics may lack precision.\");\r\n            }\r\n            else\r\n            {\r\n                BOOST_MESSAGE( ::std::setw(15)\r\n                            << atanh_error_evaluator(xf)\r\n                            << ::std::setw(15)\r\n                            << atanh_error_evaluator(xd)\r\n                            << ::std::setw(15)\r\n                            << atanh_error_evaluator(xl));\r\n            }\r\n        }\r\n    }\r\n    \r\n    BOOST_MESSAGE(\" \");\r\n}\r\n\r\n", "meta": {"hexsha": "2938fc7b43de2d526c9441feebbfb0ece03d4d8c", "size": 5035, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/math/special_functions/atanh_test.hpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/math/special_functions/atanh_test.hpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/special_functions/atanh_test.hpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 31.46875, "max_line_length": 77, "alphanum_fraction": 0.468917577, "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6120149738438545}}
{"text": "/*\nTest RS code over binary extension field\n*/\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <boost/program_options.hpp>\n#include \"../include/PFE.hpp\"\n#include \"../include/EFE.hpp\"\n#include \"../include/DFT.hpp\"\n#include \"../include/helpers.hpp\"\n#include \"../include/GF2M.hpp\"\n//#include \"../include/encodedecode.hpp\"\n#include \"../include/ReedSolomon.hpp\"\n#include <string>\n#include <fstream>\n#include <streambuf>\n#include <random>\n#include <chrono>\n\n\n\n\nusing namespace std;\n\n\n// define static variables \n\ntypedef GF2 pfe;\ntemplate<> polynomial<pfe> EFE<pfe>::prim_poly = polynomial<pfe>();\ntemplate<> unsigned EFE<pfe>::m = 30;\n\n\n\n\n\n\n\n\nint main(int ac, char* av[])\n{\n\n// randomness\nrandom_device r;\ndefault_random_engine gen(r());\nuniform_int_distribution<int> randbit(0, 1);\nuniform_int_distribution<int> randint(0, 16383);\n\n\n\n// parameters\nconst unsigned M = 50000;\n//const unsigned Q = 127;\n//const unsigned P = 129;\nconst unsigned Q = 127;\nconst unsigned P = 337;\nconst unsigned n = P*Q; // 2^14 - 1\n//const unsigned k = 13926; // k = 0.85*n\nconst unsigned k = 36379; // k = 0.85*n\n\n\n\n///// GF2M definitions\n/*\nconst unsigned prim_poly = 16553;\nconst unsigned m = 14;\ntypedef GF2M<unsigned,m,prim_poly> gf;\n// efe a = efe(34); // 32 + 2 = 100010 = x + x^5\ngf fa = gf(66,0); // 64 + 2 = 1000010 = x + x^5\n*/\n\nconst uint_least64_t prim_poly = 4399239010919;\nconst unsigned m = 42;\ntypedef GF2M<uint_least64_t,m,prim_poly> gf;\n// efe a = efe(34); // 32 + 2 = 100010 = x + x^5\ngf fa = gf(1935755,0); // 64 + 2 = 1000010 = x + x^5\n\n\ncout << \"primitive polynomial: \" << bitset<64>(prim_poly) << endl;\ncout << \"                      \" << bitset<64>( ((uint_least64_t)1 << m) ) << endl; \ncout << \"order of a: \" << fa.order() << endl;\n\n\n\nDFT_FFT<gf> dftgf(n,fa,P,Q); // Fourier transform for the outer code \n// Does the DFT work? \nvector<gf> ct_ = vector<gf>(n);\nfor(gf& el:ct_) \n\tel = gf(randint(gen),0); // random vector\nct_[3] = gf(0);\nvector<gf> C_, hatc_;\ncout << ct_.size() << \" \" << ct_[0] << endl;\ndftgf.dft(ct_,C_);\ndftgf.idft(hatc_,C_);\nif(hatc_ == ct_)\n\tcout << \"DFT works!\" << endl;\nelse\n\tcout << \"DFT failed.\" << endl;\n\n\nRScode<gf,DFT_FFT<gf>> outercode(n,k,fa,dftgf);\n\n\n///// EFE version\n\n/*\ntypedef EFE<pfe> gf;\ntypedef EFE<pfe> efe;\nEFE<pfe>::m = 14;\n// initialize the primitive polynomial\n// x^14 + x^7 + x^5 + x^3 + 1\npfe ppvv[m+1] = {1,0,0,1,0,1,0,1,0,0,0,0,0,0,1}; // for m=14\nvector<pfe> ppv(ppvv, ppvv+m+1);\nEFE<pfe>::prim_poly = polynomial<pfe>(ppv);\n// initialize the element of order n, the Fourier kernel  \npfe aa[m] = {0,1,0,0,0,0,1,0,0,0,0,0,0,0}; // element of order 2^14-1\nvector<pfe> avv(aa, aa+m); // \nefe a = efe(avv); // this is an element of order n\nDFT_FFT<gf> dftefe(n,a,P,Q); // Fourier transform for the outer code \n\n\n\nRScode<gf,DFT_FFT<efe>> outercode(n,k,a,dftefe);\n*/\n\n\n\n///// test the outer code\n\n// generate information\n\nvector<gf> infvec(outercode.k); // information vector; \nfor(gf& el: infvec)\n\tel = gf(randbit(gen));\n\n// encode\n\nvector<gf> c; // outer codeword \noutercode.RSencode(infvec,c);\n\n// disturb\n\nfloat errorprob = 0.01;\nfloat erasureprob = 0.1;\nbernoulli_distribution bern(errorprob);\nbernoulli_distribution eras(erasureprob);\n\nint errctr = 0;\nint eractr = 0;\nfor(gf& s : c){\n\tif( bern(gen) ){\t\n\t\t// generated random efe\n\t\t//vector<pfe> rsymbol(m);\n\t\t//for(pfe& el : rsymbol)\n\t\t//\tel = pfe( randbit(gen) );\n\t\t//s = efe(rsymbol);\n\t\ts = gf(randint(gen));\n\t\t//cout << rsymbol << endl;\n\t\terrctr++;\n\t} else if( eras(gen) ){\n\t\ts = gf();\n\t\teractr++;\n\t}\n}\n\ncout << \"inserted \" << errctr << \" errors and \" << eractr << \" erasures\" << endl;\ncout << \"should be able to correct \" << (n - k) / 2 << \" errors\" << endl;\n\n// decoding\n\nauto t1 = chrono::high_resolution_clock::now();\nvector<gf> infvecrec;\npair<unsigned,unsigned> erctroc = outercode.RS_decode_spec(infvecrec,c);\nauto t2 = chrono::high_resolution_clock::now();\ncout << \"decoding took \"\n     << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()\n     << \" milliseconds\\n\";\n\ncout << \"outer code: \" << erctroc.first << \" errasures, \" << erctroc.second << \" errors corrected\"<< endl;\n\n\nif( infvec ==  infvecrec)\n\tcout << \"I did correct all errors!\" << endl; \nelse\t\n\tcout << \"I couldn't correct all errors!\" << endl; \n\n\n}\n", "meta": {"hexsha": "b802a46ee1934839e6aacd2dfbfbdad1100030cd", "size": 4257, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testRS.cpp", "max_stars_repo_name": "libingzheren/dna_rs_coding", "max_stars_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-12-01T11:55:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T01:57:11.000Z", "max_issues_repo_path": "tests/testRS.cpp", "max_issues_repo_name": "libingzheren/dna_rs_coding", "max_issues_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-26T09:13:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-26T15:19:01.000Z", "max_forks_repo_path": "tests/testRS.cpp", "max_forks_repo_name": "libingzheren/dna_rs_coding", "max_forks_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-05T06:14:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T09:10:36.000Z", "avg_line_length": 22.4052631579, "max_line_length": 106, "alphanum_fraction": 0.6375381724, "num_tokens": 1430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.6119598314599644}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <complex>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"vlasovpp/field.h\"\n#include \"vlasovpp/weno.h\"\n#include \"vlasovpp/fft.h\"\n#include \"vlasovpp/array_view.h\"\n#include \"vlasovpp/poisson.h\"\n\nnamespace math = boost::math::constants;\nconst std::complex<double> & I = std::complex<double>(0.,1.);\n\n#define SQ(X) ((X)*(X))\n#define Xi(i) (i*f0.step.dx+f0.range.x_min)\n#define Vk(k) (k*f0.step.dv+f0.range.v_min)\n\nint main(int,char**)\n{\n  const std::size_t NumDimV = 1;\n\tconst int Nx = 64, Nv = 128, Nb_iter=100;\n\n\tfield<double,NumDimV> f0( boost::extents[Nv][Nx] );\n\n\tf0.range.v_min = -10.; f0.range.v_max = 10.;\n\tf0.step.dv = (f0.range.v_max-f0.range.v_min)/Nv;\n\tf0.range.x_min = -10.; f0.range.x_max = 10.;\n\tf0.step.dx = (f0.range.x_max-f0.range.x_min)/Nx;\n\n  double Tf = 2.*math::pi<double>();\n\n\tublas::vector<double> v (Nv);\n  ublas::vector<double> E (Nx);\n  for ( std::size_t k=0 ; k<Nv ; ++k ) { v[k] = Vk(k); }\n  for ( std::size_t i=0 ; i<Nx ; ++i ) { E[i] = -Xi(i); }\n\n\tconst double lx = f0.range.x_max-f0.range.x_min;\n  const double lv = f0.range.v_max-f0.range.v_min;\n\tublas::vector<double> kx(Nx),kv(Nv);\n  for ( int i=0  ; i<Nx/2 ; ++i ) { kx[i]    = 2.*math::pi<double>()*i/lx; }\n  for ( int i=-Nx/2 ; i<0 ; ++i ) { kx[Nx+i] = 2.*math::pi<double>()*i/lx; }\n\n  for ( int k=0  ; k<Nv/2 ; ++k ) { kv[k]    = 2.*math::pi<double>()*k/lv; }\n  for ( int k=-Nv/2 ; k<0 ; ++k ) { kv[Nv+k] = 2.*math::pi<double>()*k/lv; }\n\t\n  for (field<double,NumDimV>::size_type k=0 ; k<f0.size(0) ; ++k ) {\n    for (field<double,NumDimV>::size_type i=0 ; i<f0.size(1) ; ++i ) {\n      //f[k][i] = std::cos(Xi(i)*0.2)*std::cos(math::pi<double>()*2.*Vk(k)/20);\n      f0[k][i] = std::exp( -SQ(Xi(i)-1.)/2. )*std::exp( -Vk(k)*Vk(k)/1.);\n      //f[k][i] = ( std::exp(-0.5*SQ(Vk(k)))*np/std::sqrt(2.*math::pi<double>()) )*(1.+0.04*std::cos(0.3*Xi(i)));\n    }\n  }\n  f0.write(\"init.dat\");\n\n\n  fft::spectrum_ hxf(Nx);\n  fft::spectrum_ hvf(Nv);\n\n\n  for ( int nb_iter=10 ; nb_iter<100 ; nb_iter+=10 ){\n    double dt = Tf/nb_iter;\n\n    int i_t=0;\n    field<double,1> f=f0;\n    while ( i_t*dt < Tf ) {\n      //std::cout<<\" \\r\"<<i_t<<\" \"<<std::flush;\n\n      field<double,1> f1 = f;\n      field<double,1> f2 = f;\n  \t  \n  \t  for ( std::size_t k=0 ; k<Nv ; ++k ) {\n  \t  \thxf.fft(&(f[k][0]));\n  \t  \tfor ( std::size_t i=0 ; i<Nx ; ++i ) { hxf[i] = std::exp( -I*v(k)*kx[i]*0.5*dt )*hxf[i]; }\n  \t  \thxf.ifft(&(f1[k][0]));\n  \t  }\n\n      for ( std::size_t i=0 ; i<Nx ; ++i ) {\n        std::valarray<double> fi(Nv); for ( std::size_t k=0 ; k<Nv ; ++k ) { fi[k] = f1[k][i]; }\n        hvf.fft(&(fi[0]));\n        for ( std::size_t k=0 ; k<Nv ; ++k ) { hvf[k] = std::exp( -I*E(i)*kv[k]*dt )*hvf[k]; }\n        hvf.ifft(&(fi[0]));\n        for ( std::size_t k=0 ; k<Nv ; ++k ) { f2[k][i] = fi[k]; }\n      }\n\n  \t  for ( auto k=0 ; k<f.size(0) ; ++k ) {\n  \t  \thxf.fft(&(f2[k][0]));\n  \t  \tfor ( auto i=0 ; i<Nx ; ++i ) { hxf[i] = std::exp( -I*v(k)*kx[i]*0.5*dt )*hxf[i]; }\n  \t  \thxf.ifft(&(f[k][0]));\n  \t  }\n\n      ++i_t;\n  \t}\n    //std::cout << \" \\r\" << nb_iter << \" : \" << i_t << std::endl;\n    field<double,1> diff=f;\n    for ( std::size_t k=0 ; k<Nv ; ++k ) {\n      for ( std::size_t i=0 ; i<Nx ; ++i ) {\n        diff[k][i] -= f0[k][i];\n      }\n    }\n    double e_1  = std::accumulate( diff.origin() , diff.origin()+diff.num_elements() , 0. , [&](double a,double b){return a+std::abs(b)*f0.step.dx*f0.step.dv;} );\n    double e_oo = std::abs(*std::max_element( diff.origin() , diff.origin()+diff.num_elements() , [](double a,double b){return (std::abs(a) < std::abs(b));} ));\n    std::cout << dt << \" \" << e_1 << \" \" << e_oo << std::endl;\n  }\n\n\treturn 0;\n}\n", "meta": {"hexsha": "49ab14ac90fe2fc3655a630e9b0d4f26e1c66c0d", "size": 3827, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/order_strang.cc", "max_stars_repo_name": "kivvix/vlasovpp", "max_stars_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/order_strang.cc", "max_issues_repo_name": "kivvix/vlasovpp", "max_issues_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/order_strang.cc", "max_forks_repo_name": "kivvix/vlasovpp", "max_forks_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2782608696, "max_line_length": 162, "alphanum_fraction": 0.5286124902, "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357632379241, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6119408602925626}}
{"text": "\n#pragma once\n\n#include <Eigen/Dense>\n\n#include \"aabb.hpp\"\n#include \"euclidean-transform.hpp\"\n#include \"ordered-pair.hpp\"\n#include \"perceive/utils/math.hpp\"\n#include \"quaternion.hpp\"\n#include \"vector-2.hpp\"\n#include \"vector-3.hpp\"\n#include \"vector-4.hpp\"\n\nnamespace perceive\n{\n// --------------------------------------------------------------------- Lp-norm\n\nenum class Lp_norm_t : int { L_INF = 0, L1 = 1, L2 = 2, L3 = 3, L4 = 4 };\n\ninline const char* str(Lp_norm_t method)\n{\n   switch(method) {\n   case Lp_norm_t::L_INF: return \"L-inf\";\n   case Lp_norm_t::L1: return \"L1\";\n   case Lp_norm_t::L2: return \"L2\";\n   case Lp_norm_t::L3: return \"L3\";\n   case Lp_norm_t::L4: return \"L4\";\n   }\n   return \"<error>\";\n}\n\n// --------------------------------------------------------------------- Vectors\n\ntypedef Vector2T<float> Vector2f;\ntypedef Vector3T<float> Vector3f;\ntypedef Vector4T<float> Vector4f;\ntypedef Vector4T<float> Plane4f;\ntypedef QuaternionT<float> QuaternionF;\n\ntypedef Vector2T<real> Vector2;\ntypedef Vector3T<real> Vector3;\ntypedef Vector4T<real> Vector4;\ntypedef Vector4T<real> Plane;\ntypedef QuaternionT<real> Quaternion;\ntypedef AABBT<real> AABB;\n\ntypedef Vector2T<int> Point2;\ntypedef Vector3T<int> Point3;\ntypedef Vector4T<int> Point4;\ntypedef AABBT<int> AABBi;\ntypedef OrderedPairT<int> OrderedPair;\n\ntypedef EuclideanTransformT<float> EuclideanTransformF;\ntypedef EuclideanTransformT<real> EuclideanTransform;\n\nusing RealRange = std::pair<real, real>;\n\n// #define EIGEN_ALIGN Eigen::DontAlign\n#define EIGEN_ALIGN Eigen::AutoAlign\n\ntemplate<typename T> using EigenVector4T = Eigen::Matrix<T, 4, 1, EIGEN_ALIGN>;\n\nusing Vector2r = Eigen::Vector2d;\nusing Vector3r = Eigen::Vector3d;\nusing Vector4r = Eigen::Vector4d;\nusing Vector6r = Eigen::Matrix<real, 6, 1, EIGEN_ALIGN>;\nusing VectorXr = Eigen::Matrix<real, Eigen::Dynamic, 1, EIGEN_ALIGN>;\n\ntemplate<typename T> using Matrix4T = Eigen::Matrix<T, 4, 4, EIGEN_ALIGN>;\n\nusing Matrix3r  = Eigen::Matrix<real, 3, 3, EIGEN_ALIGN>;\nusing Matrix4r  = Eigen::Matrix<real, 4, 4, EIGEN_ALIGN>;\nusing Matrix34r = Eigen::Matrix<real, 3, 4, EIGEN_ALIGN>;\nusing MatrixXr  = Eigen::Matrix<real, Eigen::Dynamic, Eigen::Dynamic>;\n\nusing Matrix3f  = Eigen::Matrix<float, 3, 3, EIGEN_ALIGN>;\nusing Matrix4f  = Eigen::Matrix<float, 4, 4, EIGEN_ALIGN>;\nusing Matrix34f = Eigen::Matrix<float, 3, 4, EIGEN_ALIGN>;\nusing MatrixXf  = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>;\n\nusing MatrixXi = Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic>;\n\n// ----------------------------------------------------------------------- Round\n\n// template<> inline Vector2 round<Vector2>(const Vector2& v) noexcept\n// {\n//    return v.round();\n// }\n// template<> inline Vector3 round<Vector3>(const Vector3& v) noexcept\n// {\n//    return v.round();\n// }\n// template<> inline Vector4 round<Vector4>(const Vector4& v) noexcept\n// {\n//    return v.round();\n// }\n\n// ------------------------------------------------------------------ Conversion\n\ninline Vector2 to_vec2(const Point2& v) noexcept { return Vector2(v(0), v(1)); }\ninline Vector2 to_vec2(const Vector2& v) noexcept\n{\n   return Vector2(v(0), v(1));\n}\ninline Vector2 to_vec2(const Vector2r& v) noexcept\n{\n   return Vector2(v(0), v(1));\n}\ninline Vector2 to_vec2(const Vector2f& v) noexcept\n{\n   return Vector2(real(v(0)), real(v(1)));\n}\ninline Vector2r to_vec2r(const Point2& v) noexcept\n{\n   return Vector2r(v(0), v(1));\n}\ninline Vector2r to_vec2r(const Vector2& v) noexcept\n{\n   return Vector2r(v(0), v(1));\n}\ninline Vector2r to_vec2r(const Vector2r& v) noexcept\n{\n   return Vector2r(v(0), v(1));\n}\ninline Vector2r to_vec2r(const Vector2f& v) noexcept\n{\n   return Vector2r(v(0), v(1));\n}\ninline Vector2f to_vec2f(const Point2& v) noexcept\n{\n   return Vector2f(float(v(0)), float(v(1)));\n}\ninline Vector2f to_vec2f(const Vector2& v) noexcept\n{\n   return Vector2f(float(v(0)), float(v(1)));\n}\ninline Vector2f to_vec2f(const Vector2r& v) noexcept\n{\n   return Vector2f(float(v(0)), float(v(1)));\n}\ninline Vector2f to_vec2f(const Vector2f& v) noexcept\n{\n   return Vector2f(v(0), v(1));\n}\n\ninline Vector3 to_vec3(const Point3& v) noexcept\n{\n   return Vector3(v(0), v(1), v(2));\n}\ninline Vector3 to_vec3(const Vector3& v) noexcept\n{\n   return Vector3(v(0), v(1), v(2));\n}\ninline Vector3 to_vec3(const Vector3r& v) noexcept\n{\n   return Vector3(v(0), v(1), v(2));\n}\ninline Vector3 to_vec3(const Vector3f& v) noexcept\n{\n   return Vector3(real(v(0)), real(v(1)), real(v(2)));\n}\ninline Vector3r to_vec3r(const Point3& v) noexcept\n{\n   return Vector3r(v(0), v(1), v(2));\n}\ninline Vector3r to_vec3r(const Vector3& v) noexcept\n{\n   return Vector3r(v(0), v(1), v(2));\n}\ninline Vector3r to_vec3r(const Vector3r& v) noexcept\n{\n   return Vector3r(v(0), v(1), v(2));\n}\ninline Vector3r to_vec3r(const Vector3f& v) noexcept\n{\n   return Vector3r(real(v(0)), real(v(1)), real(v(2)));\n}\ninline Vector3f to_vec3f(const Point3& v) noexcept\n{\n   return Vector3f(float(v(0)), float(v(1)), float(v(2)));\n}\ninline Vector3f to_vec3f(const Vector3& v) noexcept\n{\n   return Vector3f(float(v(0)), float(v(1)), float(v(2)));\n}\ninline Vector3f to_vec3f(const Vector3r& v) noexcept\n{\n   return Vector3f(float(v(0)), float(v(1)), float(v(2)));\n}\ninline Vector3f to_vec3f(const Vector3f& v) noexcept\n{\n   return Vector3f(v(0), v(1), v(2));\n}\n\ninline Vector4 to_vec4(const Point4& v) noexcept\n{\n   return Vector4(v(0), v(1), v(2), v(3));\n}\ninline Vector4 to_vec4(const Vector4& v) noexcept\n{\n   return Vector4(v(0), v(1), v(2), v(3));\n}\ninline Vector4 to_vec4(const Vector4r& v) noexcept\n{\n   return Vector4(v(0), v(1), v(2), v(3));\n}\ninline Vector4 to_vec4(const Vector4f& v) noexcept\n{\n   return Vector4(real(v(0)), real(v(1)), real(v(2)), real(v(3)));\n}\ninline Vector4r to_vec4r(const Point4& v) noexcept\n{\n   return Vector4r(v(0), v(1), v(2), v(3));\n}\ninline Vector4r to_vec4r(const Vector4& v) noexcept\n{\n   return Vector4r(v(0), v(1), v(2), v(3));\n}\ninline Vector4r to_vec4r(const Vector4r& v) noexcept\n{\n   return Vector4r(v(0), v(1), v(2), v(3));\n}\ninline Vector4r to_vec4r(const Vector4f& v) noexcept\n{\n   return Vector4r(real(v(0)), real(v(1)), real(v(2)), real(v(3)));\n}\ninline Vector4f to_vec4f(const Point4& v) noexcept\n{\n   return Vector4f(float(v(0)), float(v(1)), float(v(2)), float(v(3)));\n}\ninline Vector4f to_vec4f(const Vector4& v) noexcept\n{\n   return Vector4f(float(v(0)), float(v(1)), float(v(2)), float(v(3)));\n}\ninline Vector4f to_vec4f(const Vector4r& v) noexcept\n{\n   return Vector4f(float(v(0)), float(v(1)), float(v(2)), float(v(3)));\n}\ninline Vector4f to_vec4f(const Vector4f& v) noexcept\n{\n   return Vector4f(float(v(0)), float(v(1)), float(v(2)), float(v(3)));\n}\n\ninline Point2 to_pt2(const std::pair<int, int>& v) noexcept\n{\n   return Point2(v.first, v.second);\n}\ninline Point2 to_pt2(const Vector2& v) noexcept\n{\n   return Point2(int(v.x), int(v.y));\n}\ninline Point2 to_pt2(const Vector2f& v) noexcept\n{\n   return Point2(int(v.x), int(v.y));\n}\ninline Point3 to_pt3(const Vector3& v) noexcept\n{\n   return Point3(int(v.x), int(v.y), int(v.z));\n}\ninline Point3 to_pt3(const Vector3f& v) noexcept\n{\n   return Point3(int(v.x), int(v.y), int(v.z));\n}\ninline Point4 to_pt4(const Vector4& v) noexcept\n{\n   return Point4(int(v.x), int(v.y), int(v.z), int(v.w));\n}\ninline Point4 to_pt4(const Vector4f& v) noexcept\n{\n   return Point4(int(v.x), int(v.y), int(v.z), int(v.w));\n}\n\ninline Quaternion to_quaternion(const QuaternionF& q) noexcept\n{\n   return Quaternion(real(q.x), real(q.y), real(q.z), real(q.w));\n}\n\ninline QuaternionF to_quaternionf(const Quaternion& q) noexcept\n{\n   return QuaternionF(float(q.x), float(q.y), float(q.z), float(q.w));\n}\n\ntemplate<typename T> inline Vector2T<T> clip_to_xy(const Vector3T<T>& X)\n{\n   return Vector2T<T>(X.x, X.y);\n}\n\n// ------------------------------------------------------------------- is-finite\n\ninline bool is_finite(const Vector2& x) noexcept { return x.is_finite(); }\ninline bool is_finite(const Vector3& x) noexcept { return x.is_finite(); }\ninline bool is_finite(const Vector4& x) noexcept { return x.is_finite(); }\ninline bool is_finite(const Vector2f& x) noexcept { return x.is_finite(); }\ninline bool is_finite(const Vector3f& x) noexcept { return x.is_finite(); }\ninline bool is_finite(const Vector4f& x) noexcept { return x.is_finite(); }\ninline bool is_finite(float x) noexcept { return std::isfinite(x); }\ninline bool is_finite(double x) noexcept { return std::isfinite(x); }\n\n// --------------------------------------------------------- matrix-mult-helpers\n// P3\ninline Vector4r mult_homgen(const Matrix4r& M, const Vector4r& X) noexcept\n{\n   Vector4r Y = M * Vector4r(X(0), X(1), X(2), X(3));\n   if(fabs(Y(3)) < 1e-9) Y /= Y(3);\n   return Y;\n}\n\ninline Vector4 mult_homgen(const Matrix4r& M, const Vector4& X) noexcept\n{\n   return to_vec4(mult_homgen(M, to_vec4r(X)));\n}\n\ninline Vector3r mult_homgen(const Matrix4r& M, const Vector3r& X) noexcept\n{\n   auto Y = mult_homgen(M, Vector4r(X(0), X(1), X(2), 1.0));\n   return Vector3r(Y(0), Y(1), Y(2));\n}\n\ninline Vector3 mult_homgen(const Matrix4r& M, const Vector3& X) noexcept\n{\n   return to_vec3(mult_homgen(M, to_vec3r(X)));\n}\n\n// P2\ninline Vector3r mult_homgen(const Matrix3r& M, const Vector3r& X) noexcept\n{\n   Vector3r Y = M * X;\n   if(fabs(Y(2)) < 1e-9) Y /= Y(2);\n   return Y;\n}\n\ninline Vector3 mult_homgen(const Matrix3r& M, const Vector3& X) noexcept\n{\n   return to_vec3(mult_homgen(M, to_vec3r(X)));\n}\n\ninline Vector2r mult_homgen(const Matrix3r& M, const Vector2r& X) noexcept\n{\n   auto Y = mult_homgen(M, Vector3r(X(0), X(1), 1.0));\n   return Vector2r(Y(0), Y(1));\n}\n\ninline Vector2 mult_homgen(const Matrix3r& M, const Vector2& X) noexcept\n{\n   return to_vec2(mult_homgen(M, to_vec2r(X)));\n}\n\n// --------------------------------------------------------------- AABB => AABBi\n\ninline AABBi aabb_to_aabbi(const AABB& aabb)\n{\n   return AABBi(int(floor(aabb.left)),\n                int(floor(aabb.top)),\n                int(ceil(aabb.right)),\n                int(ceil(aabb.bottom)));\n}\n\n// -------------------------------------------------------- Matrix3r => Matrix3d\n\ntemplate<typename U, typename V> void matrixU_to_V(const U& S, V& D) noexcept\n{\n   using T               = typename V::Scalar;\n   const unsigned n_rows = unsigned(S.rows());\n   const unsigned n_cols = unsigned(S.cols());\n   if(D.rows() != S.rows() || D.cols() != S.cols())\n      D = V::Zero(S.rows(), S.cols());\n   assert(D.rows() == n_rows && D.cols() == n_cols);\n   for(unsigned row = 0; row < n_rows; ++row)\n      for(unsigned col = 0; col < n_cols; ++col) D(row, col) = T(S(row, col));\n}\n\n// static void matrix3r_to_3d(const Matrix3r& S, Matrix3d& D) {matrixU_to_V(S,\n// D);} static void matrix3d_to_3r(const Matrix3d& S, Matrix3r& D)\n// {matrixU_to_V(S, D);} static void matrixXr_to_Xd(const MatrixXr& S, MatrixXd&\n// D) {matrixU_to_V(S, D);} static void matrixXd_to_Xr(const MatrixXd& S,\n// MatrixXr& D) {matrixU_to_V(S, D);}\n\n// --------------------------------------------------------------------- Generic\n\ntemplate<typename T> typename T::value_type quadrance(const T& v) noexcept\n{\n   return v.quadrance();\n}\ntemplate<typename T> typename T::value_type norm(const T& v) noexcept\n{\n   return v.norm();\n}\ntemplate<typename T> typename T::value_type dot(const T& u, const T& v) noexcept\n{\n   return u.dot(v);\n}\ntemplate<typename T>\ntypename T::value_type distance(const T& u, const T& v) noexcept\n{\n   return u.distance(v);\n}\n\ntemplate<typename T>\ninline Vector3T<T> cross(const Vector3T<T>& u, const Vector3T<T>& v)\n{\n   return u.cross(v);\n}\n\ninline Matrix3r make_skew_symmetric(const Vector3& t) noexcept\n{\n   Matrix3r Tx = Matrix3r::Zero();\n   Tx(0, 1)    = -t(2);\n   Tx(0, 2)    = t(1);\n   Tx(1, 2)    = -t(0);\n   Tx(1, 0)    = t(2);\n   Tx(2, 0)    = -t(1);\n   Tx(2, 1)    = t(0);\n   return Tx;\n}\n\n// --------------------------------------------------------------------- Vector2\n\ninline Vector2 cartesian_to_polar(const Vector2& x) noexcept\n{\n   Vector2 ret;\n   if(fabs(x.quadrance() - real(1.0)) < real(1e-9)) {\n      ret.mag()   = real(1.0);\n      ret.theta() = acos(x.y >= real(0.0) ? x.x : -x.x);\n   } else {\n      ret.mag()   = x.norm();\n      ret.theta() = acos((x.y >= real(0.0) ? x.x : -x.x) / ret.mag());\n   }\n   return ret;\n}\n\ninline Vector2 angle_to_cartesian(const real theta) noexcept\n{\n   return Vector2(cos(theta), sin(theta));\n}\n\ninline Vector2 polar_to_cartesian(const Vector2& x) noexcept\n{\n   return angle_to_cartesian(x.theta()) * x.mag();\n}\n\n// ------------------------------------------------------------------- Spherical\n\ninline Vector3f\nspherical_to_cartesian(float inc, float azi, float dist) noexcept\n{\n   const float sinx = std::sin(inc);\n   const float cosx = std::cos(inc);\n   const float siny = std::sin(azi);\n   const float cosy = std::cos(azi);\n   //\n   return Vector3f(sinx * cosy, sinx * siny, cosx) * dist;\n}\n\ninline Vector3 spherical_to_cartesian(real inc, real azi, real dist) noexcept\n{\n   const Vector3::value_type sinx = sin(inc);\n   const Vector3::value_type cosx = cos(inc);\n   const Vector3::value_type siny = sin(azi);\n   const Vector3::value_type cosy = cos(azi);\n   //\n   return Vector3(sinx * cosy, sinx * siny, cosx) * dist;\n}\n\ninline Vector3 spherical_to_cartesian(const Vector3& s) noexcept\n{\n   return spherical_to_cartesian(s.x, s.y, s.z);\n}\n\ninline Vector3f spherical_to_cartesian(const Vector3f& s) noexcept\n{\n   return spherical_to_cartesian(s.x, s.y, s.z);\n}\n\ninline Vector3 cartesian_to_spherical(real x, real y, real z) noexcept\n{\n   auto r           = sqrt(x * x + y * y + z * z);\n   auto inclination = acos(z / r);\n   auto azimuth     = atan2(y, x);\n   return Vector3(inclination, azimuth, r);\n}\n\ninline Vector3 cartesian_to_spherical(const Vector3& n) noexcept\n{\n   return cartesian_to_spherical(n.x, n.y, n.z);\n}\n\ninline Vector3f cartesian_to_spherical(const Vector3f& n) noexcept\n{\n   return to_vec3f(cartesian_to_spherical(real(n.x), real(n.y), real(n.z)));\n}\n\n// ----------------------------------------------------------------- Homogeneous\n\ninline Vector3r normalized_P2(const Vector3r& x) noexcept\n{\n   Vector3r v = x;\n   v /= v(2);\n   if((fabs(v(0)) > 1e20) || (fabs(v(1)) > 1e20))\n      return x; // tending towards an ideal point\n   return v;\n}\n\ntemplate<typename T>\ninline Vector2T<T> homgen_P2_to_R2(const Vector3T<T>& x) noexcept\n{\n   if(std::fabs(x.z) < T(1e-20)) {\n      T sign = (x.z < T(0.0)) ? -T(1.0) : T(1.0);\n      return Vector2T<T>(sign * x.x / T(1e-20), sign * x.y / T(1e-20));\n   }\n   auto inv = T(1.0) / x.z;\n   return Vector2T<T>(x.x * inv, x.y * inv);\n}\n\ntemplate<typename T>\ninline Vector3T<T> homgen_R2_to_P2(const Vector2T<T>& x) noexcept\n{\n   return Vector3T<T>(x.x, x.y, T(1.0));\n}\n\ntemplate<typename T>\ninline Vector2T<T> line_line_isect(const Vector3T<T>& u,\n                                   const Vector3T<T>& v) noexcept\n{\n   return homgen_P2_to_R2(cross(u, v));\n}\n\ntemplate<typename T>\ninline Vector3T<T> to_homgen_line(const Vector2T<T>& u,\n                                  const Vector2T<T>& v) noexcept\n{\n   Vector3T<T> ret(u.y - v.y, v.x - u.x, u.x * v.y - u.y * v.x);\n   ret.normalise_line();\n   return ret;\n}\n\ntemplate<typename T>\ninline Vector3T<T> to_homgen_line(const Vector3T<T>& u,\n                                  const Vector3T<T>& v) noexcept\n{\n   Vector3T<T> ret = cross(u, v);\n   ret.normalise_line();\n   return ret;\n}\n\ninline Vector3r to_homgen_line(const Vector3r& u, const Vector3r& v) noexcept\n{\n   return to_vec3r(to_homgen_line(to_vec3(u), to_vec3(v)));\n}\n\ntemplate<typename T>\ninline T dot_line_point(const Vector3T<T>& line,\n                        const Vector3T<T>& point) noexcept\n{\n   return dot(line, point);\n}\n\ntemplate<typename T>\ninline T dot_line_point(const Vector3T<T>& line,\n                        const Vector2T<T>& point) noexcept\n{\n   return line.x * point.x + line.y * point.y + line.z;\n}\n\n// Project 'point' onto 'line'\ntemplate<typename T>\ninline Vector2T<T> project_point_line(const Vector3T<T>& line,\n                                      const Vector2T<T>& point) noexcept\n{\n   return point - dot_line_point(line, point) * Vector2T<T>(line.x, line.y);\n}\n\ninline bool is_orthogonal(const Vector3& a, const Vector3& b) noexcept\n{\n   return fabs(dot(a, b)) < 1e-9;\n}\n\ntemplate<typename T>\ninline typename T::value_type uv_cos_theta(const T& u, const T& v)\n{\n   using V = typename T::value_type;\n   return std::clamp<V>(u.normalised().dot(v.normalised()), V(-1.0), V(1.0));\n}\n\n// ---------------------------------------------------------- Lifted Coordinates\n\ninline Vector6r lift_xy(real x, real y) noexcept\n{\n   Vector6r X;\n   X(0) = square(x);\n   X(1) = x * y;\n   X(2) = square(y);\n   X(3) = x;\n   X(4) = y;\n   X(5) = 1.0;\n   return X;\n}\n\ninline Vector6r lift_xy(const Vector2& x) noexcept { return lift_xy(x.x, x.y); }\ninline Vector6r lift_xy(const Vector2r& x) noexcept\n{\n   return lift_xy(x(0), x(1));\n}\ninline Vector6r lift_xy(const Vector3& x) noexcept\n{\n   return lift_xy(homgen_P2_to_R2(x));\n}\ninline Vector6r lift_xy(const Vector3r& x) noexcept\n{\n   return lift_xy(homgen_P2_to_R2(to_vec3(x)));\n}\n\n// ------------------------------------------------------------------------ Rays\n\ninline Vector3 to_ray(const MatrixXr& A, real x, real y) noexcept\n{\n   return to_vec3(A * lift_xy(x, y)).normalized();\n}\n\ninline Vector3 to_ray(const MatrixXr& A, const Vector2& x) noexcept\n{\n   return to_ray(A, x.x, x.y);\n}\ninline Vector3 to_ray(const MatrixXr& A, const Vector2r& x) noexcept\n{\n   return to_ray(A, x(0), x(1));\n}\ninline Vector3 to_ray(const MatrixXr& A, const Vector3r& x) noexcept\n{\n   return to_ray(A, homgen_P2_to_R2(to_vec3(x)));\n}\n\n// ---------------------------------------------------------------- 2D Iteration\n\nstatic constexpr array<std::pair<int, int>, 4> four_connected\n    = {{{-1, 0}, {0, -1}, {0, 1}, {1, 0}}};\n\nstatic constexpr array<std::pair<int, int>, 8> eight_connected\n    = {{{-1, 0}, {0, -1}, {0, 1}, {1, 0}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}};\n\nstatic constexpr array<std::pair<int, int>, 20> twenty_connected\n    = {{{-2, -1}, {-2, 0}, {-2, 1}, {-1, -2}, {-1, -1}, {-1, 0}, {-1, 1},\n        {-1, 2},  {0, -2}, {0, -1}, {0, 1},   {0, 2},   {1, -2}, {1, -1},\n        {1, 0},   {1, 1},  {1, 2},  {2, -1},  {2, 0},   {2, 1}}};\n\nstatic constexpr array<std::pair<int, int>, 21> twentyone_connected\n    = {{{-2, -1}, {-2, 0}, {-2, 1}, {-1, -2}, {-1, -1}, {-1, 0}, {-1, 1},\n        {-1, 2},  {0, -2}, {0, -1}, {0, 1},   {0, 0},   {0, 2},  {1, -2},\n        {1, -1},  {1, 0},  {1, 1},  {1, 2},   {2, -1},  {2, 0},  {2, 1}}};\n\nstatic constexpr array<std::pair<int, int>, 24> twentyfour_connected\n    = {{{-2, -2}, {-2, -1}, {-2, 0}, {-2, 1}, {-2, 2}, {-1, -2},\n        {-1, -1}, {-1, 0},  {-1, 1}, {-1, 2}, {0, -2}, {0, -1},\n        {0, 1},   {0, 2},   {1, -2}, {1, -1}, {1, 0},  {1, 1},\n        {1, 2},   {2, -2},  {2, -1}, {2, 0},  {2, 1},  {2, 2}}};\n\n// -------------------------------------------------------------------- feedback\n\ntemplate<typename T>\ninline string vec_feedback(const Vector2T<T>& u, const Vector2T<T>& v) noexcept\n{\n   return format(\"|{} - {}| = {}\", str(u), str(v), (u - v).norm());\n}\n\ntemplate<typename T>\ninline string vec_feedback(const Vector3T<T>& u, const Vector3T<T>& v) noexcept\n{\n   return format(\"|{} - {}| = {}\", str(u), str(v), (u - v).norm());\n}\n\ntemplate<typename T>\ninline string vec_feedback(const Vector4T<T>& u, const Vector4T<T>& v) noexcept\n{\n   return format(\"|{} - {}| = {}\", str(u), str(v), (u - v).norm());\n}\n\n// ----------------------------------------------------------- Quantize Funciton\nstd::array<std::pair<Point2, float>, 4> quantize(const Vector2& X) noexcept;\n\n} // namespace perceive\n\nnamespace std\n{\n// OrderedPair\ntemplate<> struct hash<perceive::OrderedPair>\n{\n   size_t operator()(const perceive::OrderedPair& v) const { return v.hash(); }\n};\n\n// ---------------------------------------------------------------------- Vector\n\n// Vector2\ntemplate<> struct hash<perceive::Vector2>\n{\n   size_t operator()(const perceive::Vector2& v) const { return v.hash(); }\n};\n\n// Vector3\ntemplate<> struct hash<perceive::Vector3>\n{\n   size_t operator()(const perceive::Vector3& v) const { return v.hash(); }\n};\n\n// Vector4\ntemplate<> struct hash<perceive::Vector4>\n{\n   size_t operator()(const perceive::Vector4& v) const { return v.hash(); }\n};\n\n// ----------------------------------------------------------------------- Point\n\n// Point2\ntemplate<> struct hash<perceive::Point2>\n{\n   size_t operator()(const perceive::Point2& v) const { return v.hash(); }\n};\n\n// Point3\ntemplate<> struct hash<perceive::Point3>\n{\n   size_t operator()(const perceive::Point3& v) const { return v.hash(); }\n};\n\n// Point4\ntemplate<> struct hash<perceive::Point4>\n{\n   size_t operator()(const perceive::Point4& v) const { return v.hash(); }\n};\n\n} // namespace std\n", "meta": {"hexsha": "cb7e79db532c06f1dd4919c8a6b86776bc989885", "size": 20732, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector.hpp", "max_stars_repo_name": "prcvlabs/multiview", "max_stars_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T23:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:43:32.000Z", "max_issues_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector.hpp", "max_issues_repo_name": "prcvlabs/multiview", "max_issues_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:33:02.000Z", "max_forks_repo_path": "multiview/multiview_cpp/src/perceive/geometry/vector.hpp", "max_forks_repo_name": "prcvlabs/multiview", "max_forks_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-26T03:14:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T06:42:52.000Z", "avg_line_length": 28.3611491108, "max_line_length": 80, "alphanum_fraction": 0.6076596566, "num_tokens": 6468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.6119408422865034}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n//[ guide_make_static_histogram\n\n#include <boost/histogram.hpp>\n#include <cassert>\n\nint main() {\n  using namespace boost::histogram;\n\n  // create a 1d-histogram in default configuration which\n  // covers the real line from -1 to 1 in 100 bins\n  auto h = make_histogram(axis::regular<>(100, -1.0, 1.0));\n\n  // rank is the number of axes\n  assert(h.rank() == 1);\n}\n\n//]\n", "meta": {"hexsha": "55eb4b6892ec12ec63f9695be9371df20ab3ed0e", "size": 566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/histogram/examples/guide_make_static_histogram.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/histogram/examples/guide_make_static_histogram.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/histogram/examples/guide_make_static_histogram.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 23.5833333333, "max_line_length": 61, "alphanum_fraction": 0.7014134276, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6119249286462831}}
{"text": "// test_differentiate.cpp\n// (c) Tivole\n\n#include <boost/test/unit_test.hpp>\n#include \"../src/numerary.hpp\"\n\nnamespace numerary\n{\n    \n    BOOST_AUTO_TEST_SUITE(TestDifferentiate)\n    \n    BOOST_AUTO_TEST_CASE(test_differentiate_order_1_h)\n    {\n        const double h = 0.00001;\n        const short int order = 1;\n        double x;\n        double expected_result;\n        double result;\n\n        // Testing sin\n        x = M_PI;\n        expected_result = -1;\n        result = Numerary::differentiate(sin, 1, x, \"h\", h);\n        BOOST_CHECK(fabs(result - expected_result) <= 1.e-4);\n\n\n        // Testing cos\n        x = M_PI_2;\n        expected_result = -1;\n        result = Numerary::differentiate(cos, 1, x, \"h\", h);\n        BOOST_CHECK(fabs(result - expected_result) <= 1.e-4);\n\n        // Testing exp\n        x = 1;\n        expected_result = 2.718281828;\n        result = Numerary::differentiate(exp, 1, x, \"h\", h);\n        BOOST_CHECK(fabs(result - expected_result) <= 1.e-4);\n    }\n\n\n    BOOST_AUTO_TEST_CASE(test_differentiate_order_1_2h)\n    {\n        const double h = 0.00001;\n        const short int order = 1;\n        double x;\n        double expected_result;\n        double result;\n\n        // Testing sin\n        x = M_PI;\n        expected_result = -1;\n        result = Numerary::differentiate(sin, 1, x, \"2h\", h);\n        BOOST_CHECK(fabs(result - expected_result) <= 1.e-4);\n\n\n        // Testing cos\n        x = M_PI_2;\n        expected_result = -1;\n        result = Numerary::differentiate(cos, 1, x, \"2h\", h);\n        BOOST_CHECK(fabs(result - expected_result) <= 1.e-4);\n\n        // Testing exp\n        x = 1;\n        expected_result = 2.718281828;\n        result = Numerary::differentiate(exp, 1, x, \"2h\", h);\n        BOOST_CHECK(fabs(result - expected_result) <= 1.e-4);\n    }\n\n    BOOST_AUTO_TEST_SUITE_END()\n}\n\n", "meta": {"hexsha": "022c137ea07221791c44297f6bda4b5b3bb5178e", "size": 1833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_differentiate.cpp", "max_stars_repo_name": "tivole/Numerary", "max_stars_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2020-02-21T06:09:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T10:00:06.000Z", "max_issues_repo_path": "test/test_differentiate.cpp", "max_issues_repo_name": "tivole/Ti_Numerary", "max_issues_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_differentiate.cpp", "max_forks_repo_name": "tivole/Ti_Numerary", "max_forks_repo_head_hexsha": "2034cd0fbd5d68cd2120baf2c613da54b10a738b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-12T11:12:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-12T11:12:27.000Z", "avg_line_length": 25.4583333333, "max_line_length": 61, "alphanum_fraction": 0.5733769776, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6118495084341498}}
{"text": "//==============================================================================\n//         Copyright 2015 J.T.Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EULER_FUNCTIONS_SIMD_COMMON_BETALN_HPP_INCLUDED\n#define NT2_EULER_FUNCTIONS_SIMD_COMMON_BETALN_HPP_INCLUDED\n\n#include <nt2/euler/functions/betaln.hpp>\n#include <nt2/include/functions/simd/gammaln.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/plus.hpp>\n#include <nt2/include/functions/simd/all.hpp>\n#include <nt2/include/functions/simd/logical_and.hpp>\n#include <nt2/include/functions/simd/is_nltz.hpp>\n#include <boost/assert.hpp>\n#include <boost/simd/operator/functions/details/assert_utils.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( betaln_, tag::cpu_\n                            , (A0)\n                            , ((generic_<floating_<A0>>))\n                              ((generic_<floating_<A0>>))\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      BOOST_ASSERT_MSG(boost::simd::assert_all(logical_and(is_nltz(a0),is_nltz(a1))), \"inputs must be positive\");\n      return(gammaln(a0)+gammaln(a1)-gammaln(a0+a1));\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "26b5f4c4657132a6c5f6edded1bc57904b447e5b", "size": 1476, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/betaln.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/betaln.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/betaln.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 36.0, "max_line_length": 113, "alphanum_fraction": 0.5860433604, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6118495062304471}}
{"text": "//\n// Copyright (c) 2012 Juan Palacios juan.palacios.puyana@gmail.com\n// This file is part of minimathlibs.\n// Subject to the BSD 2-Clause License \n// - see < http://opensource.org/licenses/BSD-2-Clause>\n//\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE TestMatrix\n#include <boost/test/unit_test.hpp>\n\n#include <cmath>\n#include <cstdlib>\n#include <iostream>\n#include <limits>\n#include \"minimath/matrix.hpp\"\n#include \"minimath/matrix_ops.hpp\"\n#include \"minimath/numeric_utils.hpp\"\n\nnamespace \n{\n// test if all elements of a matrix have a particular value\ntemplate <typename M>\nbool valueEquality(const M& m, \n                   typename M::value_type v, \n                   typename M::value_type tol = std::numeric_limits<typename M::value_type>::epsilon()) {\n\n  for (unsigned int r = 0; r < m.rows(); ++r)\n  {\n    for (unsigned int c = 0; c < m.cols(); ++c)\n    {\n      if ( std::abs(m(r,c) - v) > tol) {\n        std::cout << \"\\nm(\" << r << \", \" << c << \") = \" << m(r,c) << \"\\n\";\n        std::cout << \"\\n\" << m << \"\\n\";\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\n// test if two elements are within epsilon of each other\ntemplate <typename T>\nbool valueEquality(const T& lhs, const T& rhs)\n{\n  return std::abs(rhs-lhs) < std::numeric_limits<T>::epsilon();\n}\n\n// test if a matrix is an identity matrix\ntemplate <typename M>\nbool isIdentity(const M& m, \n                typename M::value_type tol = std::numeric_limits<typename M::value_type>::epsilon()) {\n\n  if (m.rows() != m.cols()) return false;\n  for (unsigned int r = 0; r < m.rows(); ++r)\n  {\n    for (unsigned int c = 0; c < m.cols(); ++c)\n    {\n      if (r==c)\n      {\n        if ( std::abs(m(r,c) - 1) > tol) return false;\n      } else {\n        if ( std::abs(m(r,c)) > tol) {\n          std::cout << \"\\nm(\" << r << \", \" << c << \") = \" << m(r,c) << \"\\n\";\n          std::cout << \"\\n\" << m << \"\\n\";\n          return false;\n        }\n      }\n    }\n  }\n  return true;\n}\n\nstruct setup\n{\n    setup() { std::srand(42); }\n};\n\n} // anonymous namespace\n\n\ntypedef minimath::matrix<double, 2> M2x2;\ntypedef minimath::matrix<double, 3> M3x3;\ntypedef minimath::matrix<double, 4> M4x4;\ntypedef minimath::matrix<double, 5> M5x5;\n\ntypedef minimath::matrix<double, 2,1> M2x1;\ntypedef minimath::matrix<double, 3,2> M3x2;\ntypedef minimath::matrix<double, 4,3> M4x3;\ntypedef minimath::matrix<double, 5,4> M5x4;\n\ntypedef minimath::matrix<double, 3,4> M3x4;\ntypedef minimath::matrix<double, 4,5> M4x5;\n\nBOOST_FIXTURE_TEST_SUITE(TestMatrix, setup)\n\n\nBOOST_AUTO_TEST_CASE(testDefaultConstruction)\n{\n  M2x2 a;\n  M2x2 b;\n  M2x2 c;\n  BOOST_CHECK(valueEquality(a, 0.));\n  BOOST_CHECK(valueEquality(b, 0.));\n  BOOST_CHECK(valueEquality(c, 0.));\n  BOOST_CHECK(2==a.rows());\n  BOOST_CHECK(2==a.cols());\n  BOOST_CHECK(4==a.size());\n  BOOST_CHECK(a==b);\n  BOOST_CHECK(a==c);\n  BOOST_CHECK(b==c);\n\n  M5x4 d, e, f;\n  BOOST_CHECK(valueEquality(d, 0));\n  BOOST_CHECK(valueEquality(e, 0));\n  BOOST_CHECK(valueEquality(f, 0));\n  BOOST_CHECK(5==e.rows());\n  BOOST_CHECK(4==e.cols());\n  BOOST_CHECK(20==e.size());\n  BOOST_CHECK(d==e);\n  BOOST_CHECK(d==f);\n  BOOST_CHECK(e==f);\n\n}\n\nBOOST_AUTO_TEST_CASE(testZeroMatrixConstruction)\n{\n  M4x3 m = minimath::zero_matrix();\n  BOOST_CHECK(valueEquality(m, 0));\n}\n\nBOOST_AUTO_TEST_CASE(testZeroMatrixAssignment)\n{\n  M4x3 m;\n  m = minimath::zero_matrix();\n  BOOST_CHECK(valueEquality(m, 0));\n}\n\n\nBOOST_AUTO_TEST_CASE(testIdentityMatrixConstruction)\n{\n  M4x4 m4 = minimath::identity_matrix();\n  BOOST_CHECK(isIdentity(m4));\n  M5x5 m5 = minimath::identity_matrix();\n  BOOST_CHECK(isIdentity(m5));\n\n}\n\nBOOST_AUTO_TEST_CASE(testIdentityMatrixAssignment)\n{\n  M4x4 m;\n  m = minimath::identity_matrix();\n  BOOST_CHECK(isIdentity(m));\n}\n\n\nBOOST_AUTO_TEST_CASE(testScalarConstruction)\n{\n  for (int  i = -20; i < 21; ++i) {\n    M5x5 m(i);\n    BOOST_CHECK(valueEquality(m, i));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testCopyConstruction)\n{\n  M4x3 m;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    m[i] = i;\n  }\n  M4x3 m2(m);\n  BOOST_CHECK(m2==m);\n}\n\nBOOST_AUTO_TEST_CASE(testAssignment)\n{\n  M4x3 m;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    m[i] = i;\n  }\n  M4x3 m2;\n  m2 = m;\n  BOOST_CHECK(m2==m);\n\n}\n\nBOOST_AUTO_TEST_CASE(testEquality)\n{\n  M4x3 m1, m2;\n  for (unsigned int i = 0; i< m1.size(); ++i) {\n    m1[i] = i;\n    m2[i] = i;\n  }\n  BOOST_CHECK(m2==m1);\n\n}\n\nBOOST_AUTO_TEST_CASE(testInequality)\n{\n  M4x3 m;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    m[i] = i;\n  }\n  M4x3 m2;\n  BOOST_CHECK(m2!=m);\n}\n\n\nBOOST_AUTO_TEST_CASE(testPlusEqualsScalar)\n{\n  M4x3 m;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    m[i] = i;\n  }\n  m += 100;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    BOOST_CHECK(valueEquality(m[i], M4x3::value_type(i) + 100));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testMinusEqualsScalar)\n{\n  M4x3 m;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    m[i] = i;\n  }\n  m -= 100;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    BOOST_CHECK(valueEquality(m[i], M4x3::value_type(i) - 100.));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testPlusEquals)\n{\n  M3x3 m1;\n  for (unsigned int i = 0; i< m1.size(); ++i) {\n    m1[i] = i;\n  }\n  M3x3 m2(10);\n  m1 += m2;\n  for (unsigned int i = 0; i< m1.size(); ++i) {\n    BOOST_CHECK(valueEquality(m1[i], M3x3::value_type(i) + 10));\n  }\n\n}\n\nBOOST_AUTO_TEST_CASE(testMinusEquals)\n{\n  M3x3 m1;\n  for (unsigned int i = 0; i< m1.size(); ++i) {\n    m1[i] = 10*i;\n  }\n  M3x3 m2(10);\n  m1 -= m2;\n  for (unsigned int i = 0; i< m1.size(); ++i) {\n    BOOST_CHECK(valueEquality(m1[i], M3x3::value_type(10)*(int(i) -1) ));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testTimesEqualsScalar)\n{\n  M4x3 m;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    m[i] = i;\n  }\n  m *= 100;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    BOOST_CHECK(valueEquality(m[i], M4x3::value_type(i) * 100));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testDivideEqualsScalar)\n{\n  M4x3 m;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    m[i] = i*1000;\n  }\n  m /= 100;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    BOOST_CHECK(valueEquality(m[i], M4x4::value_type(i) * 10));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testMatrixPlusScalar)\n{\n  M4x3 m(11);\n  M4x3 m2 = m + 100;\n  for (unsigned int i = 0; i< m2.size(); ++i) {\n    BOOST_CHECK(valueEquality(m2, 111));    \n  }\n}\n\nBOOST_AUTO_TEST_CASE(testMatrixMinusScalar)\n{\n  M4x3 m(111);\n  M4x3 m2 = m - 101;\n  for (unsigned int i = 0; i< m2.size(); ++i) {\n    BOOST_CHECK(valueEquality(m2, 10));    \n  }\n}\n\nBOOST_AUTO_TEST_CASE(testScalarPlusMatrix)\n{\n  M4x3 m(11);\n  M4x3 m2 = 100 + m;\n  for (unsigned int i = 0; i< m2.size(); ++i) {\n    BOOST_CHECK(valueEquality(m2, 111));    \n  }\n}\n\nBOOST_AUTO_TEST_CASE(testScalarMinusMatrix)\n{\n  M4x3 m(101);\n  M4x3 m2 = 111 - m;\n  for (unsigned int i = 0; i< m2.size(); ++i) {\n    BOOST_CHECK(valueEquality(m2, 10));    \n  }\n}\n\n\nBOOST_AUTO_TEST_CASE(testMatrixTimesScalar)\n{\n  M4x3 m(11);\n  M4x3 m2 = m * 100;\n  for (unsigned int i = 0; i< m2.size(); ++i) {\n    BOOST_CHECK(valueEquality(m2, 1100));    \n  }\n}\n\nBOOST_AUTO_TEST_CASE(testTranspose)\n{\n  M4x3 m;\n  for (unsigned int i = 0; i< m.size(); ++i) {\n    m[i] = i;\n  }\n  M3x4 mT = m.transpose();\n  for (unsigned int r = 0; r < m.rows(); ++r)\n  {\n    for (unsigned int c = 0; c < m.cols(); ++c)\n    {\n      BOOST_CHECK(valueEquality(m(r,c), mT(c,r)));\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testLeftInverse)\n{\n  for (unsigned int attempt = 0; attempt <5; ++attempt)\n  {\n    M4x3 m;\n    for (unsigned int i = 0; i< m.size(); ++i) {\n      m[i] = std::rand()%m.size();\n    }\n    bool success = true;\n    M3x4 mInv = minimath::left_inverse(m, success);\n    BOOST_CHECK(success);\n    BOOST_CHECK(minimath::equal(mInv*m, M3x3(minimath::identity_matrix()), 128));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testInverse)\n{\n  for (unsigned int attempt = 0; attempt <5; ++attempt)\n  {\n    M3x3 m;\n    for (unsigned int i = 0; i< m.size(); ++i) {\n      m[i] = std::rand()%m.size();\n    }\n    bool success = true;\n    M3x3 mInv = m.inverse(success);\n    BOOST_CHECK(success);\n    BOOST_CHECK(minimath::equal(mInv*m, M3x3(minimath::identity_matrix()), 128));\n  }\n}\n\nBOOST_AUTO_TEST_CASE(testInvert)\n{\n  for (unsigned int attempt = 0; attempt <5; ++attempt)\n  {\n    M3x3 m;\n    for (unsigned int i = 0; i< m.size(); ++i) {\n      m[i] = std::rand()%m.size();\n    }\n    bool success = true;\n    M3x3 mInv = m;\n    mInv.invert(success);\n    BOOST_CHECK(success);\n    BOOST_CHECK(minimath::equal(mInv*m, M3x3(minimath::identity_matrix()), 16));\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "0cb551d63f6bbd5efeb102b123f63bf76cc85bdc", "size": 8430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/TestMatrix.cpp", "max_stars_repo_name": "XPsoud/minimathlibs", "max_stars_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-20T13:54:46.000Z", "max_issues_repo_path": "tests/TestMatrix.cpp", "max_issues_repo_name": "XPsoud/minimathlibs", "max_issues_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/TestMatrix.cpp", "max_forks_repo_name": "XPsoud/minimathlibs", "max_forks_repo_head_hexsha": "be4ece76e90fd95a247a8d7ab47cc8f84c9cb750", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T15:04:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:04:57.000Z", "avg_line_length": 21.4503816794, "max_line_length": 105, "alphanum_fraction": 0.6043890866, "num_tokens": 2842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.8104789109591832, "lm_q1q2_score": 0.6118426764232415}}
{"text": "#include <boost/lexical_cast.hpp>\n#include <iostream>\n#include <vector>\n\nclass hamiltonian {\npublic:\n  // z[0]: position, z[1]: momentum\n  double energy(double t, std::vector<double> const& z) const {\n    return potential_energy(t, z) + kinetic_energy(t, z);\n  }\n  double potential_energy(double /* t */, std::vector<double> const& z) const {\n    //return -std::cos(2*M_PI*z[0]);\n    return -std::cos(z[0]);\n  }\n  double kinetic_energy(double /* t */, std::vector<double> const& z) const {\n    return 0.5 * z[1] * z[1];\n  }\n  // \"force\" calculation\n  void operator()(double /* t */, std::vector<double> const& z, std::vector<double>& force) const {\n    force[0] = z[1];\n    //force[1] = -2*M_PI*std::sin(2*M_PI*z[0]);\n    force[1] = -std::sin(z[0]);\n  }\n};\n\nint main(int argc, char **argv) {\n  double t_init = 0;\n  double t_final = 10;\n  double dt = 0.001;\n  if (argc >= 2) t_final = boost::lexical_cast<double>(argv[1]);\n  if (argc >= 3) dt = boost::lexical_cast<double>(argv[2]);\n  std::cout << \"# \" << integrator_t::name() << std::endl\n            << \"# t_init  = \" << t_init << std::endl\n            << \"# t_final = \" << t_final << std::endl\n            << \"# dt      = \" << dt << std::endl;\n  \n  std::vector<double> z(2);\n  z[0] = M_PI*0.5;\n  z[1] = 0;\n\n  hamiltonian ham;\n\n  integrator_t integrator(2);\n  for (double t = t_init; t <= t_final; t += dt) {\n    std::cout <<  t << ' ' << z[0] << ' ' << z[1] << ' ' << ham.energy(t,z) << ' ' << ham.kinetic_energy(t,z) << ' ' << ham.potential_energy(t,z) << std::endl;\n    integrator.step(t, dt, z, ham);\n  }\n}\n", "meta": {"hexsha": "2d91a2ff0e80db7d121b205b15e007a7e16be6b6", "size": 1562, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "basic-examples/integrator/1spin_main.hpp", "max_stars_repo_name": "FIshikawa/ClassicalStatPhys", "max_stars_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "basic-examples/integrator/1spin_main.hpp", "max_issues_repo_name": "FIshikawa/ClassicalStatPhys", "max_issues_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T08:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T09:29:10.000Z", "max_forks_repo_path": "basic-examples/integrator/1spin_main.hpp", "max_forks_repo_name": "FIshikawa/ClassicalStatPhys", "max_forks_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-18T03:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-21T22:58:27.000Z", "avg_line_length": 31.8775510204, "max_line_length": 159, "alphanum_fraction": 0.5550576184, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.754914975839675, "lm_q1q2_score": 0.6118426657574226}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2018 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE at \n * the top level of the deal.II distribution. \n * \n * --------------------------------------------------------------------- \n * \n * Author: Wolfgang Bangerth, Colorado State University \n *         Yong-Yong Cai, Beijing Computational Science Research Center \n */ \n\n\n// @sect3{Include files}  \u7a0b\u5e8f\u4ee5\u901a\u5e38\u7684\u5305\u542b\u6587\u4ef6\u5f00\u59cb\uff0c\u6240\u6709\u8fd9\u4e9b\u6587\u4ef6\u4f60\u73b0\u5728\u5e94\u8be5\u90fd\u89c1\u8fc7\u4e86\u3002\n\n#include <deal.II/base/logstream.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/sparse_matrix.h> \n#include <deal.II/lac/block_sparse_matrix.h> \n#include <deal.II/lac/block_vector.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/sparse_direct.h> \n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/error_estimator.h> \n#include <deal.II/numerics/matrix_tools.h> \n\n#include <fstream> \n#include <iostream> \n\n// \u7136\u540e\u6309\u7167\u60ef\u4f8b\u5c06\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u6240\u6709\u5185\u5bb9\u653e\u5165\u4e00\u4e2a\u547d\u540d\u7a7a\u95f4\uff0c\u5e76\u5c06deal.II\u547d\u540d\u7a7a\u95f4\u5bfc\u5165\u5230\u6211\u4eec\u5c06\u8981\u5de5\u4f5c\u7684\u547d\u540d\u7a7a\u95f4\u4e2d\u3002\n\nnamespace Step58 \n{ \n  using namespace dealii; \n// @sect3{The <code>NonlinearSchroedingerEquation</code> class}  \n\n// \u7136\u540e\u662f\u4e3b\u7c7b\u3002\u5b83\u770b\u8d77\u6765\u975e\u5e38\u50cf  step-4  \u6216  step-6  \u4e2d\u7684\u76f8\u5e94\u7c7b\uff0c\u552f\u4e00\u7684\u4f8b\u5916\u662f\uff0c\u77e9\u9635\u548c\u5411\u91cf\u4ee5\u53ca\u5176\u4ed6\u6240\u6709\u4e0e\u7ebf\u6027\u7cfb\u7edf\u76f8\u5173\u7684\u5143\u7d20\u73b0\u5728\u90fd\u5b58\u50a8\u4e3a  `std::complex<double>`  \u7c7b\u578b\uff0c\u800c\u4e0d\u4ec5\u4ec5\u662f `double`\u3002\n\n  template <int dim> \n  class NonlinearSchroedingerEquation \n  { \n  public: \n    NonlinearSchroedingerEquation(); \n    void run(); \n\n  private: \n    void setup_system(); \n    void assemble_matrices(); \n    void do_half_phase_step(); \n    void do_full_spatial_step(); \n    void output_results() const; \n\n    Triangulation<dim> triangulation; \n    FE_Q<dim>          fe; \n    DoFHandler<dim>    dof_handler; \n\n    AffineConstraints<std::complex<double>> constraints; \n\n    SparsityPattern                    sparsity_pattern; \n    SparseMatrix<std::complex<double>> system_matrix; \n    SparseMatrix<std::complex<double>> rhs_matrix; \n\n    Vector<std::complex<double>> solution; \n    Vector<std::complex<double>> system_rhs; \n\n    double       time; \n    double       time_step; \n    unsigned int timestep_number; \n\n    double kappa; \n  }; \n\n//  @sect3{Equation data}  \n\n// \u5728\u6211\u4eec\u7ee7\u7eed\u586b\u5199\u4e3b\u7c7b\u7684\u7ec6\u8282\u4e4b\u524d\uff0c\u8ba9\u6211\u4eec\u5b9a\u4e49\u4e0e\u95ee\u9898\u76f8\u5bf9\u5e94\u7684\u65b9\u7a0b\u6570\u636e\uff0c\u5373\u521d\u59cb\u503c\uff0c\u4ee5\u53ca\u4e00\u4e2a\u53f3\u624b\u7c7b\u3002\u6211\u4eec\u5c06\u628a\u521d\u59cb\u6761\u4ef6\u4e5f\u7528\u4e8e\u8fb9\u754c\u503c\uff0c\u6211\u4eec\u53ea\u662f\u4fdd\u6301\u8fb9\u754c\u503c\u4e0d\u53d8\uff09\u3002\u6211\u4eec\u4f7f\u7528\u6d3e\u751f\u81eaFunction\u7c7b\u6a21\u677f\u7684\u7c7b\u6765\u505a\u8fd9\u4ef6\u4e8b\uff0c\u8fd9\u4e2a\u6a21\u677f\u4e4b\u524d\u5df2\u7ecf\u7528\u8fc7\u5f88\u591a\u6b21\u4e86\uff0c\u6240\u4ee5\u4e0b\u9762\u7684\u5185\u5bb9\u770b\u8d77\u6765\u5e76\u4e0d\u4ee4\u4eba\u60ca\u8bb6\u3002\u552f\u4e00\u503c\u5f97\u6ce8\u610f\u7684\u662f\uff0c\u6211\u4eec\u8fd9\u91cc\u6709\u4e00\u4e2a\u590d\u503c\u95ee\u9898\uff0c\u6240\u4ee5\u6211\u4eec\u5fc5\u987b\u63d0\u4f9bFunction\u7c7b\u7684\u7b2c\u4e8c\u4e2a\u6a21\u677f\u53c2\u6570\uff08\u5426\u5219\u4f1a\u9ed8\u8ba4\u4e3a`double`\uff09\u3002\u6b64\u5916\uff0c`value()`\u51fd\u6570\u7684\u8fd4\u56de\u7c7b\u578b\u5f53\u7136\u4e5f\u662f\u590d\u6570\u3002\n\n// \u8fd9\u4e9b\u51fd\u6570\u7cbe\u786e\u5730\u8fd4\u56de\u4ec0\u4e48\uff0c\u5728\u4ecb\u7ecd\u90e8\u5206\u7684\u6700\u540e\u5df2\u7ecf\u8ba8\u8bba\u8fc7\u4e86\u3002\n\n  template <int dim> \n  class InitialValues : public Function<dim, std::complex<double>> \n  { \n  public: \n    InitialValues() \n      : Function<dim, std::complex<double>>(1) \n    {} \n\n    virtual std::complex<double> \n    value(const Point<dim> &p, const unsigned int component = 0) const override; \n  }; \n\n  template <int dim> \n  std::complex<double> \n  InitialValues<dim>::value(const Point<dim> & p, \n                            const unsigned int component) const \n  { \n    static_assert(dim == 2, \"This initial condition only works in 2d.\"); \n\n    (void)component; \n    Assert(component == 0, ExcIndexRange(component, 0, 1)); \n\n    const std::vector<Point<dim>> vortex_centers = {{0, -0.3}, \n                                                    {0, +0.3}, \n                                                    {+0.3, 0}, \n                                                    {-0.3, 0}}; \n\n    const double R = 0.1; \n    const double alpha = \n      1. / (std::pow(R, dim) * std::pow(numbers::PI, dim / 2.)); \n\n    double sum = 0; \n    for (const auto &vortex_center : vortex_centers) \n      { \n        const Tensor<1, dim> distance = p - vortex_center; \n        const double         r        = distance.norm(); \n\n        sum += alpha * std::exp(-(r * r) / (R * R)); \n      } \n\n    return {std::sqrt(sum), 0.}; \n  } \n\n  template <int dim> \n  class Potential : public Function<dim> \n  { \n  public: \n    Potential() = default; \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n  }; \n\n  template <int dim> \n  double Potential<dim>::value(const Point<dim> & p, \n                               const unsigned int component) const \n  { \n    (void)component; \n    Assert(component == 0, ExcIndexRange(component, 0, 1)); \n\n    return (Point<dim>().distance(p) > 0.7 ? 1000 : 0); \n  } \n\n//  @sect3{Implementation of the <code>NonlinearSchroedingerEquation</code> class}  \n\n// \u6211\u4eec\u9996\u5148\u6307\u5b9a\u4e86\u7c7b\u7684\u6784\u9020\u51fd\u6570\u7684\u5b9e\u73b0\u3002\n\n  template <int dim> \n  NonlinearSchroedingerEquation<dim>::NonlinearSchroedingerEquation() \n    : fe(2) \n    , dof_handler(triangulation) \n    , time(0) \n    , time_step(1. / 128) \n    , timestep_number(0) \n    , kappa(1) \n  {} \n// @sect4{Setting up data structures and assembling matrices}  \n\n// \u4e0b\u4e00\u4e2a\u51fd\u6570\u662f\u5728\u7a0b\u5e8f\u5f00\u59cb\u65f6\uff0c\u4e5f\u5c31\u662f\u5728\u7b2c\u4e00\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e4b\u524d\uff0c\u8bbe\u7f6e\u7f51\u683c\u3001DoFHandler\u4ee5\u53ca\u77e9\u9635\u548c\u5411\u91cf\u3002\u5982\u679c\u4f60\u5df2\u7ecf\u9605\u8bfb\u4e86\u81f3\u5c11\u5230 step-6 \u4e3a\u6b62\u7684\u6559\u7a0b\u7a0b\u5e8f\uff0c\u90a3\u4e48\u524d\u51e0\u884c\u662f\u76f8\u5f53\u6807\u51c6\u7684\u3002\n\n  template <int dim> \n  void NonlinearSchroedingerEquation<dim>::setup_system() \n  { \n    GridGenerator::hyper_cube(triangulation, -1, 1); \n    triangulation.refine_global(6); \n\n    std::cout << \"Number of active cells: \" << triangulation.n_active_cells() \n              << std::endl; \n\n    dof_handler.distribute_dofs(fe); \n\n    std::cout << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << std::endl \n              << std::endl; \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp); \n    sparsity_pattern.copy_from(dsp); \n\n    system_matrix.reinit(sparsity_pattern); \n    rhs_matrix.reinit(sparsity_pattern); \n\n    solution.reinit(dof_handler.n_dofs()); \n    system_rhs.reinit(dof_handler.n_dofs()); \n\n    constraints.close(); \n  } \n\n// \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u7ec4\u88c5\u76f8\u5173\u7684\u77e9\u9635\u3002\u6309\u7167\u6211\u4eec\u5bf9\u65af\u7279\u6717\u5206\u88c2\u7684\u7a7a\u95f4\u6b65\u9aa4\uff08\u5373\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u4e09\u4e2a\u90e8\u5206\u6b65\u9aa4\u4e2d\u7684\u7b2c\u4e8c\u4e2a\u6b65\u9aa4\uff09\u7684Crank-Nicolson\u79bb\u6563\u5316\u7684\u5199\u6cd5\uff0c\u6211\u4eec\u88ab\u5f15\u5bfc\u5230\u7ebf\u6027\u7cfb\u7edf  \n// $\\left[ -iM  +  \\frac 14 k_{n+1} A + \\frac 12 k_{n+1} W \\right]\n//    \\Psi^{(n,2)}\n//   =\n//   \\left[ -iM  -  \\frac 14 k_{n+1} A - \\frac 12 k_{n+1} W \\right]\n//    \\Psi^{(n,1)}$ \n   \n//     \u6362\u53e5\u8bdd\u8bf4\uff0c\u8fd9\u91cc\u6709\u4e24\u4e2a\u77e9\u9635\u5728\u8d77\u4f5c\u7528--\u4e00\u4e2a\u7528\u4e8e\u5de6\u624b\u8fb9\uff0c\u4e00\u4e2a\u7528\u4e8e\u53f3\u624b\u8fb9\u3002\u6211\u4eec\u5206\u522b\u5efa\u7acb\u8fd9\u4e9b\u77e9\u9635\u3002\u6211\u4eec\u53ef\u4ee5\u907f\u514d\u5efa\u7acb\u53f3\u624b\u8fb9\u7684\u77e9\u9635\uff0c\u800c\u53ea\u662f\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e2d\u5f62\u6210\u77e9\u9635\u7684*\u4f5c\u7528* $\\Psi^{(n,1)}$ \u3002\u8fd9\u53ef\u80fd\u66f4\u6709\u6548\uff0c\u4e5f\u53ef\u80fd\u4e0d\u6709\u6548\uff0c\u4f46\u662f\u5bf9\u4e8e\u8fd9\u4e2a\u7a0b\u5e8f\u6765\u8bf4\uff0c\u6548\u7387\u5e76\u4e0d\u662f\u6700\u91cd\u8981\u7684\uff09\u3002)\n\n  template <int dim> \n  void NonlinearSchroedingerEquation<dim>::assemble_matrices() \n  { \n    const QGauss<dim> quadrature_formula(fe.degree + 1); \n\n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<std::complex<double>> cell_matrix_lhs(dofs_per_cell, \n                                                     dofs_per_cell); \n    FullMatrix<std::complex<double>> cell_matrix_rhs(dofs_per_cell, \n                                                     dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n    std::vector<double>                  potential_values(n_q_points); \n    const Potential<dim>                 potential; \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        cell_matrix_lhs = std::complex<double>(0.); \n        cell_matrix_rhs = std::complex<double>(0.); \n\n        fe_values.reinit(cell); \n\n        potential.value_list(fe_values.get_quadrature_points(), \n                             potential_values); \n\n        for (unsigned int q_index = 0; q_index < n_q_points; ++q_index) \n          { \n            for (unsigned int k = 0; k < dofs_per_cell; ++k) \n              { \n                for (unsigned int l = 0; l < dofs_per_cell; ++l) \n                  { \n                    const std::complex<double> i = {0, 1}; \n\n                    cell_matrix_lhs(k, l) += \n                      (-i * fe_values.shape_value(k, q_index) * \n                         fe_values.shape_value(l, q_index) + \n                       time_step / 4 * fe_values.shape_grad(k, q_index) * \n                         fe_values.shape_grad(l, q_index) + \n                       time_step / 2 * potential_values[q_index] * \n                         fe_values.shape_value(k, q_index) * \n                         fe_values.shape_value(l, q_index)) * \n                      fe_values.JxW(q_index); \n\n                    cell_matrix_rhs(k, l) += \n                      (-i * fe_values.shape_value(k, q_index) * \n                         fe_values.shape_value(l, q_index) - \n                       time_step / 4 * fe_values.shape_grad(k, q_index) * \n                         fe_values.shape_grad(l, q_index) - \n                       time_step / 2 * potential_values[q_index] * \n                         fe_values.shape_value(k, q_index) * \n                         fe_values.shape_value(l, q_index)) * \n                      fe_values.JxW(q_index); \n                  } \n              } \n          } \n\n        cell->get_dof_indices(local_dof_indices); \n        constraints.distribute_local_to_global(cell_matrix_lhs, \n                                               local_dof_indices, \n                                               system_matrix); \n        constraints.distribute_local_to_global(cell_matrix_rhs, \n                                               local_dof_indices, \n                                               rhs_matrix); \n      } \n  } \n// @sect4{Implementing the Strang splitting steps}  \n\n// \u5728\u5efa\u7acb\u4e86\u4e0a\u8ff0\u6240\u6709\u6570\u636e\u7ed3\u6784\u540e\uff0c\u6211\u4eec\u73b0\u5728\u53ef\u4ee5\u5b9e\u73b0\u6784\u6210\u65af\u7279\u6717\u5206\u88c2\u65b9\u6848\u7684\u90e8\u5206\u6b65\u9aa4\u3002\u6211\u4eec\u4ece\u63a8\u8fdb\u9636\u6bb5\u7684\u534a\u6b65\u5f00\u59cb\uff0c\u8fd9\u88ab\u7528\u4f5c\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7684\u7b2c\u4e00\u548c\u6700\u540e\u90e8\u5206\u3002\n\n// \u4e3a\u6b64\uff0c\u56de\u987e\u4e00\u4e0b\uff0c\u5bf9\u4e8e\u7b2c\u4e00\u4e2a\u534a\u6b65\uff0c\u6211\u4eec\u9700\u8981\u8ba1\u7b97  $\\psi^{(n,1)} = e^{-i\\kappa|\\psi^{(n,0)}|^2 \\tfrac 12\\Delta t} \\; \\psi^{(n,0)}$  \u3002\u8fd9\u91cc\uff0c $\\psi^{(n,0)}=\\psi^{(n)}$ \u548c $\\psi^{(n,1)}$ \u662f\u7a7a\u95f4\u7684\u51fd\u6570\uff0c\u5206\u522b\u5bf9\u5e94\u4e8e\u524d\u4e00\u4e2a\u5b8c\u6574\u65f6\u95f4\u6b65\u9aa4\u7684\u8f93\u51fa\u548c\u4e09\u4e2a\u90e8\u5206\u6b65\u9aa4\u4e2d\u7b2c\u4e00\u4e2a\u6b65\u9aa4\u7684\u7ed3\u679c\u3002\u5fc5\u987b\u4e3a\u7b2c\u4e09\u4e2a\u90e8\u5206\u6b65\u9aa4\u8ba1\u7b97\u76f8\u5e94\u7684\u89e3\u51b3\u65b9\u6848\uff0c\u5373  $\\psi^{(n,3)} = e^{-i\\kappa|\\psi^{(n,2)}|^2 \\tfrac 12\\Delta t} \\; \\psi^{(n,2)}$  \uff0c\u5176\u4e2d  $\\psi^{(n,3)}=\\psi^{(n+1)}$  \u662f\u6574\u4e2a\u65f6\u95f4\u6b65\u9aa4\u7684\u7ed3\u679c\uff0c\u5176\u8f93\u5165  $\\psi^{(n,2)}$  \u662f\u65af\u7279\u6717\u5206\u5272\u7684\u7a7a\u95f4\u6b65\u9aa4\u7684\u7ed3\u679c\u3002\n\n// \u4e00\u4e2a\u91cd\u8981\u7684\u8ba4\u8bc6\u662f\uff0c\u867d\u7136 $\\psi^{(n,0)}(\\mathbf x)$ \u53ef\u80fd\u662f\u4e00\u4e2a\u6709\u9650\u5143\u51fd\u6570\uff08\u5373\uff0c\u662f\u7247\u72b6\u591a\u9879\u5f0f\uff09\uff0c\u4f46\u5bf9\u4e8e\u6211\u4eec\u4f7f\u7528\u6307\u6570\u56e0\u5b50\u66f4\u65b0\u76f8\u4f4d\u7684 \"\u65cb\u8f6c \"\u51fd\u6570\u6765\u8bf4\uff0c\u4e0d\u4e00\u5b9a\u662f\u8fd9\u6837\u7684\uff08\u56de\u987e\u4e00\u4e0b\uff0c\u8be5\u51fd\u6570\u7684\u632f\u5e45\u5728\u8be5\u6b65\u9aa4\u4e2d\u4fdd\u6301\u4e0d\u53d8\uff09\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u6211\u4eec\u53ef\u4ee5\u5728\u6bcf\u4e00\u4e2a\u70b9 $\\psi^{(n,1)}(\\mathbf x)$ *\u8ba1\u7b97 $\\mathbf x\\in\\Omega$ \uff0c\u4f46\u6211\u4eec\u4e0d\u80fd\u5728\u7f51\u683c\u4e0a\u8868\u793a\u5b83\uff0c\u56e0\u4e3a\u5b83\u4e0d\u662f\u4e00\u4e2a\u7247\u72b6\u591a\u9879\u5f0f\u51fd\u6570\u3002\u5728\u4e00\u4e2a\u79bb\u6563\u7684\u73af\u5883\u4e2d\uff0c\u6211\u4eec\u80fd\u505a\u7684\u6700\u597d\u7684\u4e8b\u60c5\u5c31\u662f\u8ba1\u7b97\u4e00\u4e2a\u6295\u5f71\u6216\u5185\u63d2\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u6211\u4eec\u53ef\u4ee5\u8ba1\u7b97 $\\psi_h^{(n,1)}(\\mathbf x) = \\Pi_h \\left(e^{-i\\kappa|\\psi_h^{(n,0)}(\\mathbf x)|^2 \\tfrac 12\\Delta t} \\; \\psi_h^{(n,0)}(\\mathbf x) \\right)$ \uff0c\u5176\u4e2d $\\Pi_h$ \u662f\u4e00\u4e2a\u6295\u5f71\u6216\u5185\u63d2\u7b97\u5b50\u3002\u5982\u679c\u6211\u4eec\u9009\u62e9\u63d2\u503c\uff0c\u60c5\u51b5\u5c31\u7279\u522b\u7b80\u5355\u3002\u90a3\u4e48\uff0c\u6211\u4eec\u9700\u8981\u8ba1\u7b97\u7684\u5c31\u662f*\u5728\u8282\u70b9\u70b9\u4e0a\u7684\u53f3\u624b\u8fb9\u7684\u503c\uff0c\u5e76\u5c06\u8fd9\u4e9b\u4f5c\u4e3a\u81ea\u7531\u5ea6\u5411\u91cf $\\Psi^{(n,1)}$ \u7684\u8282\u70b9\u503c\u3002\u8fd9\u5f88\u5bb9\u6613\u505a\u5230\uff0c\u56e0\u4e3a\u5728\u8fd9\u91cc\u4f7f\u7528\u7684\u62c9\u683c\u6717\u65e5\u6709\u9650\u5143\u7684\u8282\u70b9\u70b9\u4e0a\u8bc4\u4f30\u53f3\u624b\u8fb9\uff0c\u9700\u8981\u6211\u4eec\u53ea\u770b\u8282\u70b9\u5411\u91cf\u7684\u4e00\u4e2a\uff08\u590d\u503c\uff09\u6761\u76ee\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u6211\u4eec\u9700\u8981\u505a\u7684\u662f\u8ba1\u7b97 $\\Psi^{(n,1)}_j = e^{-i\\kappa|\\Psi^{(n,0)}_j|^2 \\tfrac 12\\Delta t} \\; \\Psi^{(n,0)}_j$ \uff0c\u5176\u4e2d $j$ \u5728\u6211\u4eec\u7684\u89e3\u5411\u91cf\u7684\u6240\u6709\u6761\u76ee\u4e0a\u5faa\u73af\u3002\u8fd9\u5c31\u662f\u4e0b\u9762\u7684\u51fd\u6570\u6240\u505a\u7684--\u4e8b\u5b9e\u4e0a\uff0c\u5b83\u751a\u81f3\u6ca1\u6709\u4e3a $\\Psi^{(n,0)}$ \u548c $\\Psi^{(n,1)}$ \u4f7f\u7528\u5355\u72ec\u7684\u5411\u91cf\uff0c\u800c\u53ea\u662f\u9002\u5f53\u5730\u66f4\u65b0\u540c\u4e00\u4e2a\u5411\u91cf\u3002\n\n  template <int dim> \n  void NonlinearSchroedingerEquation<dim>::do_half_phase_step() \n  { \n    for (auto &value : solution) \n      { \n        const std::complex<double> i         = {0, 1}; \n        const double               magnitude = std::abs(value); \n\n        value = std::exp(-i * kappa * magnitude * magnitude * (time_step / 2)) * \n                value; \n      } \n  } \n\n// \u4e0b\u4e00\u6b65\u662f\u6c42\u89e3\u6bcf\u4e2a\u65f6\u95f4\u6b65\u9aa4\u4e2d\u7684\u7ebf\u6027\u7cfb\u7edf\uff0c\u5373\u6211\u4eec\u4f7f\u7528\u7684Strang\u5206\u5272\u7684\u540e\u534a\u6b65\u3002\u8bb0\u5f97\u5b83\u7684\u5f62\u5f0f\u662f $C\\Psi^{(n,2)} = R\\Psi^{(n,1)}$ \uff0c\u5176\u4e2d $C$ \u548c $R$ \u662f\u6211\u4eec\u4e4b\u524d\u7ec4\u88c5\u7684\u77e9\u9635\u3002\n\n// \u6211\u4eec\u5728\u8fd9\u91cc\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u7684\u65b9\u6cd5\u662f\u4f7f\u7528\u76f4\u63a5\u6c42\u89e3\u5668\u3002\u6211\u4eec\u9996\u5148\u4f7f\u7528 $r=R\\Psi^{(n,1)}$ \u51fd\u6570\u5f62\u6210\u53f3\u8fb9\u7684 SparseMatrix::vmult() \uff0c\u5e76\u5c06\u7ed3\u679c\u653e\u5165`system_rhs`\u53d8\u91cf\u3002\u7136\u540e\u6211\u4eec\u8c03\u7528 SparseDirectUMFPACK::solver() \uff0c\u8be5\u51fd\u6570\u4ee5\u77e9\u9635 $C$ \u548c\u53f3\u624b\u8fb9\u7684\u5411\u91cf\u4e3a\u53c2\u6570\uff0c\u5e76\u5728\u540c\u4e00\u5411\u91cf`system_rhs`\u4e2d\u8fd4\u56de\u89e3\u3002\u6700\u540e\u4e00\u6b65\u662f\u5c06\u8ba1\u7b97\u51fa\u7684\u89e3\u653e\u56de`solution`\u53d8\u91cf\u4e2d\u3002\n\n  template <int dim> \n  void NonlinearSchroedingerEquation<dim>::do_full_spatial_step() \n  { \n    rhs_matrix.vmult(system_rhs, solution); \n\n    SparseDirectUMFPACK direct_solver; \n    direct_solver.solve(system_matrix, system_rhs); \n\n    solution = system_rhs; \n  } \n\n//  @sect4{Creating graphical output}  \n\n// \u6211\u4eec\u5e94\u8be5\u8ba8\u8bba\u7684\u6700\u540e\u4e00\u4e2a\u8f85\u52a9\u51fd\u6570\u548c\u7c7b\u662f\u90a3\u4e9b\u521b\u5efa\u56fe\u5f62\u8f93\u51fa\u7684\u51fd\u6570\u3002\u5bf9\u65af\u7279\u6717\u5206\u88c2\u7684\u5c40\u90e8\u548c\u7a7a\u95f4\u90e8\u5206\u8fd0\u884c\u534a\u6b65\u548c\u5168\u6b65\u7684\u7ed3\u679c\u662f\uff0c\u6211\u4eec\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u6570\u7ed3\u675f\u65f6\u5c06`solution`\u5411\u91cf $\\Psi^n$ \u66f4\u65b0\u4e3a\u6b63\u786e\u7684\u503c\u3002\u5b83\u7684\u6761\u76ee\u5305\u542b\u6709\u9650\u5143\u7f51\u683c\u8282\u70b9\u4e0a\u7684\u89e3\u7684\u590d\u6570\u3002\n\n// \u590d\u6570\u4e0d\u5bb9\u6613\u88ab\u89c6\u89c9\u5316\u3002\u6211\u4eec\u53ef\u4ee5\u8f93\u51fa\u5b83\u4eec\u7684\u5b9e\u90e8\u548c\u865a\u90e8\uff0c\u5373\u5b57\u6bb5 $\\text{Re}(\\psi_h^{(n)}(\\mathbf x))$ \u548c $\\text{Im}(\\psi_h^{(n)}(\\mathbf x))$ \uff0c\u8fd9\u6b63\u662fDataOut\u7c7b\u5728\u901a\u8fc7 DataOut::add_data_vector() \u9644\u52a0\u590d\u6570\u5411\u91cf\uff0c\u7136\u540e\u8c03\u7528 DataOut::build_patches(). \u65f6\u6240\u505a\u7684\u4e8b\u60c5\uff0c\u8fd9\u786e\u5b9e\u662f\u6211\u4eec\u4e0b\u9762\u8981\u505a\u7684\u3002\n\n// \u4f46\u5f88\u591a\u65f6\u5019\uff0c\u6211\u4eec\u5bf9\u89e3\u5411\u91cf\u7684\u5b9e\u90e8\u548c\u865a\u90e8\u5e76\u4e0d\u7279\u522b\u611f\u5174\u8da3\uff0c\u800c\u662f\u5bf9\u89e3\u7684\u5e45\u5ea6 $|\\psi|$ \u548c\u76f8\u4f4d\u89d2 $\\text{arg}(\\psi)$ \u7b49\u884d\u751f\u91cf\u611f\u5174\u8da3\u3002\u5728\u8fd9\u91cc\u8fd9\u6837\u7684\u91cf\u5b50\u7cfb\u7edf\u7684\u80cc\u666f\u4e0b\uff0c\u5e45\u5ea6\u672c\u8eab\u5e76\u4e0d\u90a3\u4e48\u6709\u8da3\uff0c\u76f8\u53cd\uff0c\"\u632f\u5e45\"\uff0c $|\\psi|^2$ \u624d\u662f\u4e00\u4e2a\u7269\u7406\u5c5e\u6027\uff1a\u5b83\u5bf9\u5e94\u4e8e\u5728\u4e00\u4e2a\u7279\u5b9a\u7684\u72b6\u6001\u573a\u6240\u627e\u5230\u4e00\u4e2a\u7c92\u5b50\u7684\u6982\u7387\u5bc6\u5ea6\u3002\u5c06\u8ba1\u7b97\u51fa\u7684\u91cf\u653e\u5165\u8f93\u51fa\u6587\u4ef6\u4ee5\u5b9e\u73b0\u53ef\u89c6\u5316\u7684\u65b9\u6cd5--\u6b63\u5982\u5728\u4ee5\u524d\u7684\u8bb8\u591a\u6559\u7a0b\u7a0b\u5e8f\u4e2d\u4f7f\u7528\u7684\u90a3\u6837--\u662f\u4f7f\u7528\u6570\u636e\u540e\u5904\u7406\u7a0b\u5e8f\u548c\u6d3e\u751f\u7c7b\u7684\u8bbe\u65bd\u3002\u5177\u4f53\u6765\u8bf4\uff0c\u4e00\u4e2a\u590d\u6570\u7684\u632f\u5e45\u548c\u5b83\u7684\u76f8\u4f4d\u89d2\u90fd\u662f\u6807\u91cf\uff0c\u56e0\u6b64DataPostprocessorScalar\u7c7b\u662f\u6211\u4eec\u8981\u505a\u7684\u6b63\u786e\u5de5\u5177\u3002\n\n// \u56e0\u6b64\uff0c\u6211\u4eec\u5728\u8fd9\u91cc\u8981\u505a\u7684\u662f\u5b9e\u73b0\u4e24\u4e2a\u7c7b`ComplexAmplitude`\u548c`ComplexPhase`\uff0c\u4e3aDataOut\u51b3\u5b9a\u751f\u6210\u8f93\u51fa\u7684\u6bcf\u4e2a\u70b9\u8ba1\u7b97\u89e3\u51b3\u65b9\u6848\u7684\u632f\u5e45 $|\\psi_h|^2$ \u548c\u76f8\u4f4d $\\text{arg}(\\psi_h)$ \uff0c\u4ee5\u4fbf\u8fdb\u884c\u53ef\u89c6\u5316\u3002\u4e0b\u9762\u6709\u5927\u91cf\u7684\u6a21\u677f\u4ee3\u7801\uff0c\u8fd9\u4e24\u4e2a\u7c7b\u4e2d\u7684\u7b2c\u4e00\u4e2a\u552f\u4e00\u6709\u8da3\u7684\u90e8\u5206\u662f\u5b83\u7684`evaluate_vector_field()`\u51fd\u6570\u5982\u4f55\u8ba1\u7b97`computed_quantities`\u5bf9\u8c61\u3002\n\n//\uff08\u8fd8\u6709\u4e00\u4e2a\u76f8\u5f53\u5c34\u5c2c\u7684\u4e8b\u5b9e\u662f\uff0c<a\n//  href=\"https:en.cppreference.com/w/cpp/numeric/complex/norm\">std::norm()</a>\u51fd\u6570\u5e76\u6ca1\u6709\u8ba1\u7b97\u4eba\u4eec\u5929\u771f\u7684\u60f3\u8c61\uff0c\u5373 $|\\psi|$  \uff0c\u800c\u662f\u8fd4\u56de $|\\psi|^2$ \u3002\u4e00\u4e2a\u6807\u51c6\u51fd\u6570\u4ee5\u8fd9\u6837\u7684\u65b9\u5f0f\u88ab\u9519\u8bef\u5730\u547d\u540d\uff0c\u8fd9\u5f53\u7136\u662f\u76f8\u5f53\u4ee4\u4eba\u56f0\u60d1\u7684......)\n\n  namespace DataPostprocessors \n  { \n    template <int dim> \n    class ComplexAmplitude : public DataPostprocessorScalar<dim> \n    { \n    public: \n      ComplexAmplitude(); \n\n      virtual void evaluate_vector_field( \n        const DataPostprocessorInputs::Vector<dim> &inputs, \n        std::vector<Vector<double>> &computed_quantities) const override; \n    }; \n\n    template <int dim> \n    ComplexAmplitude<dim>::ComplexAmplitude() \n      : DataPostprocessorScalar<dim>(\"Amplitude\", update_values) \n    {} \n\n    template <int dim> \n    void ComplexAmplitude<dim>::evaluate_vector_field( \n      const DataPostprocessorInputs::Vector<dim> &inputs, \n      std::vector<Vector<double>> &               computed_quantities) const \n    { \n      Assert(computed_quantities.size() == inputs.solution_values.size(), \n             ExcDimensionMismatch(computed_quantities.size(), \n                                  inputs.solution_values.size())); \n\n      for (unsigned int q = 0; q < computed_quantities.size(); ++q) \n        { \n          Assert(computed_quantities[q].size() == 1, \n                 ExcDimensionMismatch(computed_quantities[q].size(), 1)); \n          Assert(inputs.solution_values[q].size() == 2, \n                 ExcDimensionMismatch(inputs.solution_values[q].size(), 2)); \n\n          const std::complex<double> psi(inputs.solution_values[q](0), \n                                         inputs.solution_values[q](1)); \n          computed_quantities[q](0) = std::norm(psi); \n        } \n    } \n\n// \u8fd9\u4e9b\u540e\u5904\u7406\u7a0b\u5e8f\u7c7b\u4e2d\u7684\u7b2c\u4e8c\u4e2a\u662f\u8ba1\u7b97\u6bcf\u4e00\u4e2a\u70b9\u7684\u590d\u503c\u89e3\u51b3\u65b9\u6848\u7684\u76f8\u4f4d\u89d2\u3002\u6362\u53e5\u8bdd\u8bf4\uff0c\u5982\u679c\u6211\u4eec\u8868\u793a  $\\psi(\\mathbf x,t)=r(\\mathbf x,t) e^{i\\varphi(\\mathbf x,t)}$  \uff0c\u90a3\u4e48\u8fd9\u4e2a\u7c7b\u5c31\u4f1a\u8ba1\u7b97  $\\varphi(\\mathbf x,t)$  \u3002\u51fd\u6570 <a href=\"https:en.cppreference.com/w/cpp/numeric/complex/arg\">std::arg</a> \u4e3a\u6211\u4eec\u505a\u8fd9\u4e2a\uff0c\u5e76\u5c06\u89d2\u5ea6\u4f5c\u4e3a\u5b9e\u6570\u8fd4\u56de  $-\\pi$  \u548c  $+\\pi$  \u4e4b\u95f4\u3002\n\n// \u7531\u4e8e\u6211\u4eec\u5c06\u5728\u7ed3\u679c\u90e8\u5206\u8be6\u7ec6\u89e3\u91ca\u7684\u539f\u56e0\uff0c\u6211\u4eec\u5b9e\u9645\u4e0a\u6ca1\u6709\u5728\u4ea7\u751f\u8f93\u51fa\u7684\u6bcf\u4e2a\u4f4d\u7f6e\u8f93\u51fa\u8fd9\u4e2a\u503c\u3002\u76f8\u53cd\uff0c\u6211\u4eec\u53d6\u76f8\u4f4d\u6240\u6709\u8bc4\u4f30\u70b9\u7684\u6700\u5927\u503c\uff0c\u7136\u540e\u7528\u8fd9\u4e2a\u6700\u5927\u503c\u586b\u5145\u6bcf\u4e2a\u8bc4\u4f30\u70b9\u7684\u8f93\u51fa\u5b57\u6bb5--\u5b9e\u8d28\u4e0a\uff0c\u6211\u4eec\u5c06\u76f8\u4f4d\u89d2\u4f5c\u4e3a\u4e00\u4e2a\u7247\u72b6\u5e38\u6570\u5b57\u6bb5\u8f93\u51fa\uff0c\u5176\u4e2d\u6bcf\u4e2a\u5355\u5143\u90fd\u6709\u81ea\u5df1\u7684\u5e38\u6570\u503c\u3002\u4e00\u65e6\u4f60\u8bfb\u5b8c\u4e0b\u9762\u7684\u8ba8\u8bba\u5c31\u4f1a\u660e\u767d\u5176\u4e2d\u7684\u539f\u56e0\u3002\n\n    template <int dim> \n    class ComplexPhase : public DataPostprocessorScalar<dim> \n    { \n    public: \n      ComplexPhase(); \n\n      virtual void evaluate_vector_field( \n        const DataPostprocessorInputs::Vector<dim> &inputs, \n        std::vector<Vector<double>> &computed_quantities) const override; \n    }; \n\n    template <int dim> \n    ComplexPhase<dim>::ComplexPhase() \n      : DataPostprocessorScalar<dim>(\"Phase\", update_values) \n    {} \n\n    template <int dim> \n    void ComplexPhase<dim>::evaluate_vector_field( \n      const DataPostprocessorInputs::Vector<dim> &inputs, \n      std::vector<Vector<double>> &               computed_quantities) const \n    { \n      Assert(computed_quantities.size() == inputs.solution_values.size(), \n             ExcDimensionMismatch(computed_quantities.size(), \n                                  inputs.solution_values.size())); \n\n      double max_phase = -numbers::PI; \n      for (unsigned int q = 0; q < computed_quantities.size(); ++q) \n        { \n          Assert(computed_quantities[q].size() == 1, \n                 ExcDimensionMismatch(computed_quantities[q].size(), 1)); \n          Assert(inputs.solution_values[q].size() == 2, \n                 ExcDimensionMismatch(inputs.solution_values[q].size(), 2)); \n\n          max_phase = \n            std::max(max_phase, \n                     std::arg( \n                       std::complex<double>(inputs.solution_values[q](0), \n                                            inputs.solution_values[q](1)))); \n        } \n\n      for (auto &output : computed_quantities) \n        output(0) = max_phase; \n    } \n\n  } // namespace DataPostprocessors \n\n// \u5728\u8fd9\u6837\u5b9e\u73b0\u4e86\u8fd9\u4e9b\u540e\u5904\u7406\u7a0b\u5e8f\u540e\uff0c\u6211\u4eec\u50cf\u5f80\u5e38\u4e00\u6837\u521b\u5efa\u8f93\u51fa\u3002\u4e0e\u5176\u4ed6\u8bb8\u591a\u65f6\u95f4\u76f8\u5173\u7684\u6559\u7a0b\u7a0b\u5e8f\u4e00\u6837\uff0c\u6211\u4eec\u7ed9DataOut\u9644\u52a0\u6807\u5fd7\uff0c\u8868\u793a\u65f6\u95f4\u6b65\u6570\u548c\u5f53\u524d\u6a21\u62df\u65f6\u95f4\u3002\n\n  template <int dim> \n  void NonlinearSchroedingerEquation<dim>::output_results() const \n  { \n    const DataPostprocessors::ComplexAmplitude<dim> complex_magnitude; \n    const DataPostprocessors::ComplexPhase<dim>     complex_phase; \n\n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \"Psi\"); \n    data_out.add_data_vector(solution, complex_magnitude); \n    data_out.add_data_vector(solution, complex_phase); \n    data_out.build_patches(); \n\n    data_out.set_flags(DataOutBase::VtkFlags(time, timestep_number)); \n\n    const std::string filename = \n      \"solution-\" + Utilities::int_to_string(timestep_number, 3) + \".vtu\"; \n    std::ofstream output(filename); \n    data_out.write_vtu(output); \n  } \n\n//  @sect4{Running the simulation}  \n\n// \u5269\u4e0b\u7684\u6b65\u9aa4\u662f\u6211\u4eec\u5982\u4f55\u8bbe\u7f6e\u8fd9\u4e2a\u7a0b\u5e8f\u7684\u6574\u4f53\u903b\u8f91\u3002\u8fd9\u5176\u5b9e\u662f\u6bd4\u8f83\u7b80\u5355\u7684\u3002\u8bbe\u7f6e\u6570\u636e\u7ed3\u6784\uff1b\u5c06\u521d\u59cb\u6761\u4ef6\u63d2\u503c\u5230\u6709\u9650\u5143\u7a7a\u95f4\uff1b\u7136\u540e\u8fed\u4ee3\u6240\u6709\u65f6\u95f4\u6b65\u957f\uff0c\u5728\u6bcf\u4e2a\u65f6\u95f4\u6b65\u957f\u4e0a\u6267\u884c\u65af\u7279\u6717\u5206\u5272\u6cd5\u7684\u4e09\u4e2a\u90e8\u5206\u3002\u6bcf\u969410\u4e2a\u65f6\u95f4\u6b65\u957f\uff0c\u6211\u4eec\u5c31\u751f\u6210\u56fe\u5f62\u8f93\u51fa\u3002\u8fd9\u5c31\u662f\u4e86\u3002\n\n  template <int dim> \n  void NonlinearSchroedingerEquation<dim>::run() \n  { \n    setup_system(); \n    assemble_matrices(); \n\n    time = 0; \n    VectorTools::interpolate(dof_handler, InitialValues<dim>(), solution); \n    output_results(); \n\n    const double end_time = 1; \n    for (; time <= end_time; time += time_step) \n      { \n        ++timestep_number; \n\n        std::cout << \"Time step \" << timestep_number << \" at t=\" << time \n                  << std::endl; \n\n        do_half_phase_step(); \n        do_full_spatial_step(); \n        do_half_phase_step(); \n\n        if (timestep_number % 1 == 0) \n          output_results(); \n      } \n  } \n} // namespace Step58 \n\n//  @sect4{The main() function}  \n\n// \u5176\u4f59\u7684\u53c8\u662f\u9505\u7089\u677f\uff0c\u548c\u4ee5\u524d\u51e0\u4e4e\u6240\u6709\u7684\u6559\u7a0b\u7a0b\u5e8f\u5b8c\u5168\u4e00\u6837\u3002\n\nint main() \n{ \n  try \n    { \n      using namespace Step58; \n\n      NonlinearSchroedingerEquation<2> nse; \n      nse.run(); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n  return 0; \n} \n\n", "meta": {"hexsha": "f17032defbce5d7f8c59d3da2b90dc6dc60e58ef", "size": 19601, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-58/step-58.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-58/step-58.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-58/step-58.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5498084291, "max_line_length": 750, "alphanum_fraction": 0.5988980154, "num_tokens": 6881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245994514084, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6117598655510491}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\nusing Eigen::Ref;\nusing Eigen::RowVectorXd;\n\nclass Scaler {\npublic:\n    MatrixXd fit_transform(const Ref<const MatrixXd> input);\n\n    MatrixXd transform(const Ref<const MatrixXd> input) const;\n\nprivate:\n    RowVectorXd std;\n    RowVectorXd mean;\n};\n", "meta": {"hexsha": "f771fad40eb2a01c0c930b39fb958fff10fa73ae", "size": 310, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gradient_descent/scaler.hpp", "max_stars_repo_name": "ShkarupaDC/parallel-gradient-descent", "max_stars_repo_head_hexsha": "269c0e0fcb2272a25f69a4656e2b0d369f7b7b63", "max_stars_repo_licenses": ["MIT"], "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/gradient_descent/scaler.hpp", "max_issues_repo_name": "ShkarupaDC/parallel-gradient-descent", "max_issues_repo_head_hexsha": "269c0e0fcb2272a25f69a4656e2b0d369f7b7b63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gradient_descent/scaler.hpp", "max_forks_repo_name": "ShkarupaDC/parallel-gradient-descent", "max_forks_repo_head_hexsha": "269c0e0fcb2272a25f69a4656e2b0d369f7b7b63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.3157894737, "max_line_length": 62, "alphanum_fraction": 0.7322580645, "num_tokens": 71, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6117598564346389}}
{"text": "\n#include \"../linfereactdiff.h\"\n\n#include <gtest/gtest.h>\n#include <lf/assemble/assemble.h>\n#include <lf/base/base.h>\n#include <lf/fe/fe.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n#include <memory>\n#include <utility>\n\nnamespace LinFeReactDiff::test {\n\nconstexpr char mesh_file[] = CURRENT_SOURCE_DIR \"/../../meshes/square.msh\";\n\nTEST(LinFeReactDiff, TestSolveFe) {\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader(std::move(mesh_factory), mesh_file);\n  auto mesh = reader.mesh();\n  Eigen::VectorXd mu = solveFE(mesh);\n  ASSERT_NEAR(mu(mu.size() - 1), 0.00254543, 0.00001);\n  ASSERT_NEAR(mu(mu.size() - 2), 0.00145535, 0.00001);\n}\n\nTEST(LinFeReactDiff, TestEnergy) {\n  auto mesh_factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::io::GmshReader reader(std::move(mesh_factory), mesh_file);\n  auto mesh = reader.mesh();\n\n  // Implementation from solution to not depend on the first task\n  auto zero = [](Eigen::Vector2d x) -> double { return 0.; };\n  lf::mesh::utils::MeshFunctionGlobal mf_zero{zero};\n  auto identity = [](Eigen::Vector2d x) -> double { return 1.; };\n  lf::mesh::utils::MeshFunctionGlobal mf_identity{identity};\n  auto c = [](Eigen::Vector2d x) -> double { return x[0] * x[1]; };\n  lf::mesh::utils::MeshFunctionGlobal mf_c{c};\n\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh);\n  const lf::mesh::Mesh &mesh_p{*(fe_space->Mesh())};\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n\n  const lf::base::size_type N_dofs(dofh.NumDofs());\n  lf::assemble::COOMatrix<double> A(N_dofs, N_dofs);\n  lf::uscalfe::ReactionDiffusionElementMatrixProvider<\n      double, decltype(mf_identity), decltype(mf_zero)>\n      elmat_builder(fe_space, mf_identity, mf_zero);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elmat_builder, A);\n  Eigen::Matrix<double, Eigen::Dynamic, 1> phi(N_dofs);\n  phi.setZero();\n\n  lf::uscalfe::ScalarLoadElementVectorProvider<double, decltype(mf_c)>\n      elvec_builder(fe_space, mf_c);\n\n  AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n  const lf::fe::ScalarReferenceFiniteElement<double> *rsf_edge_p =\n      fe_space->ShapeFunctionLayout(lf::base::RefEl::kSegment());\n  LF_ASSERT_MSG(rsf_edge_p != nullptr, \"FE specification for edges missing\");\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(fe_space->Mesh(), 1)};\n  auto ess_bdc_flags_values_findest{lf::fe::InitEssentialConditionFromFunction(\n      *fe_space,\n      [&bd_flags](const lf::mesh::Entity &edge) -> bool {\n        return bd_flags(edge);\n      },\n      mf_zero)};\n\n  lf::assemble::FixFlaggedSolutionComponents<double>(\n      [&ess_bdc_flags_values_findest](lf::assemble::glb_idx_t gdof_idx) {\n        return ess_bdc_flags_values_findest[gdof_idx];\n      },\n      A, phi);\n\n  Eigen::VectorXd mu;\n  Eigen::SparseMatrix<double> A_crs = A.makeSparse();\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(A_crs);\n  mu = solver.solve(phi);\n\n  // compute energy\n  double energy = computeEnergy(mesh, mu);\n  ASSERT_NEAR(energy, 0.0105153, 0.00001);\n}\n\n}  // namespace LinFeReactDiff::test\n", "meta": {"hexsha": "c48888696e19ebbf2e9a4b823068b7efbc98cb68", "size": 3330, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/LinFeReactDiff/templates/test/linfereactdiff_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/LinFeReactDiff/templates/test/linfereactdiff_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/LinFeReactDiff/templates/test/linfereactdiff_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 35.4255319149, "max_line_length": 79, "alphanum_fraction": 0.7072072072, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6117598358145415}}
{"text": "/*\n   Based on https://github.com/jackjack-jj/jeeq, GPLv3.\n   Specifically designed to use Smileycoin key pairs for encoding/decoding so\n   this is not as general as jeeq.py\n   All the math here is explained pretty well on this wikipedia page:\n   https://en.wikipedia.org/wiki/ElGamal_encryption\n */\n#include <string.h>\n#include <stdbool.h>\n#include <boost/endian/conversion.hpp>\n\n#include <vector>\n#include <stdexcept>\n\n#include <openssl/ec.h>\n#include <openssl/bn.h>\n#include <openssl/obj_mac.h>\n#include <openssl/crypto.h>\n#include <openssl/rand.h>\n#include <openssl/sha.h>\n#include <openssl/err.h>\n\n#include \"key.h\"\n#include \"util.h\"\n#include \"jeeq.h\"\n\n#define PRIVHEADER_LEN          9\n#define PUBHEADER_LEN           7\n#define PRIVKEY_LEN             32\n#define COMPR_PUBKEY_LEN        33\n#define UNCOMPR_PUBKEY_LEN      65\n#define CHUNK_SIZE              32\n#define VERSION                 0x00\n#define GX_HEX                  \"79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798\"\n#define GY_HEX                  \"483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8\"\n#define GORDER_HEX              \"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141\"\n#define GCOFACTOR_HEX           \"01\"\n\nusing namespace boost::endian;\n\n/* return:  secp256k1 curve with the bitcoin generator, order and cofactor\n * in:      ctx, bignum context\n */\nstatic EC_GROUP *init_curve(BN_CTX *ctx)\n{\n    EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_secp256k1);\n\n    EC_POINT *generator = EC_POINT_new(group);\n\n    BIGNUM *Gx = BN_new();\n    BIGNUM *Gy = BN_new();\n    BIGNUM *order = BN_new();\n    BIGNUM *cofactor = BN_new();\n\n    BN_hex2bn(&Gx, GX_HEX);\n    BN_hex2bn(&Gy, GY_HEX);\n\n    BN_hex2bn(&order, GORDER_HEX);\n    BN_hex2bn(&cofactor, GCOFACTOR_HEX);\n\n    EC_POINT_set_affine_coordinates_GFp(group, generator, Gx, Gy, ctx);\n    EC_GROUP_set_generator(group, generator, order, cofactor);\n\n    BN_free(Gx);\n    BN_free(Gy);\n    BN_free(cofactor);\n    BN_free(order);\n\n    EC_POINT_free(generator);\n\n    return group;\n}\n\n/* return: 1\n * out: m, pointer to message that will be prefaced with the private header\n * in:  nmsg, pointer to the message\n *      msg_length, length of the message\n */\nstatic int write_private_header(uint8_t *m, const uint8_t *nmsg, const uint32_t msg_length)\n{\n    uint8_t hash[SHA256_DIGEST_LENGTH];\n    SHA256(nmsg, msg_length, hash);\n\n    m[0] = VERSION;\n    m[1] = 0x00;\n    m[2] = 0x06;\n    *(uint32_t*)&m[3] = native_to_big(msg_length);\n    m[7] = hash[0];\n    m[8] = hash[1];\n\n    return 1;\n}\n\n/* return: 1\n * out:     enc, the encrypted string to preface the public header with\n * in:      pub, pointer to raw pubkey,\n *          is_compressed, whether the pubkey is compressed NEEDED\n */\nstatic int write_public_header(uint8_t *enc, const uint8_t *pub)\n{\n    uint8_t hash[SHA256_DIGEST_LENGTH];\n    size_t pubkey_length = (pub[0] == 0x04) ? UNCOMPR_PUBKEY_LEN : COMPR_PUBKEY_LEN;\n\n    SHA256(pub, pubkey_length, hash);\n\n    enc[0] = 0x6a;\n    enc[1] = 0x6a;\n    enc[2] = VERSION;\n    enc[3] = 0x00;\n    enc[4] = 0x02;\n    enc[5] = hash[0];\n    enc[6] = hash[1];\n\n    return 1;\n}\n\n/* return:  1 on success, 0 otherwise\n * out:     message_length, read message length\n * in:      dec, decrypted string\n */\nstatic int read_private_header(size_t *message_length, const uint8_t *dec)\n{\n    if (dec[0] != VERSION) return 0;\n    if (dec[1] != 0x00) return 0;\n    if (dec[2] != 0x06) return 0;\n\n    uint32_t msg_len = big_to_native(*(uint32_t*)&dec[3]);\n\n    /* com_mh stands for computed message hash */\n    uint8_t com_mh[SHA256_DIGEST_LENGTH];\n    SHA256(&dec[PRIVHEADER_LEN], msg_len, com_mh);\n\n    /* check that our computed hash matches the one in the header */\n    if (dec[7] != com_mh[0] || dec[8] != com_mh[1]) return 0;\n    *message_length = msg_len;\n\n    return 1;\n}\n\n/* return: 1 on success, 0 otherwise\n * in:  group, bitcoin curve\n *      enc, encryted string\n *      bn_privkey, our privkey as a bignum\n *      is_compressed??,  RETHINK\n *      ctx, bignum context\n */\nstatic int read_public_header(const EC_GROUP *group, const uint8_t *enc,\n        const uint8_t* our_pubkey, BN_CTX *ctx)\n{\n    if (enc[0] != 0x6a)     return 0;\n    if (enc[1] != 0x6a)     return 0;\n    if (enc[2] != VERSION)  return 0;\n    if (enc[3] != 0x00)     return 0;\n    if (enc[4] != 0x02)     return 0;\n\n    /* computed public key hash = com_pkh */\n    uint8_t com_pkh[SHA256_DIGEST_LENGTH];\n    SHA256(our_pubkey, (our_pubkey[0]==0x04 ? UNCOMPR_PUBKEY_LEN : COMPR_PUBKEY_LEN), com_pkh);\n\n    if (enc[5] != com_pkh[0] || enc[6] != com_pkh[1])\n        return 0;\n\n    return 1;\n}\n\n/* return: 1 on success, 0 otherwise\n * out: y, the y value corresponding to x+offset, if it is found\n *      offset, the offset needed to the x value to give a y\n * in:  group, bitcoin curve\n *      x,   our x\n *      odd, whether we want the y value to be odd or even,\n *      ctx, bignum context\n */\nstatic int y_from_x(const EC_GROUP *group, BIGNUM *y, size_t *offset, const BIGNUM *x, const bool odd, BN_CTX *ctx)\n{\n    EC_POINT *M = EC_POINT_new(group);\n\n    /* try to find y the easy way */\n    if (EC_POINT_set_compressed_coordinates_GFp(group, M, x, odd, ctx) == 1)\n    {\n        EC_POINT_get_affine_coordinates_GFp(group, M, NULL, y, ctx);\n        *offset = 0;\n        EC_POINT_free(M);\n        return 1;\n    }\n\n    int ret = 0;\n    BN_CTX_start(ctx);\n\n    BIGNUM *p = BN_CTX_get(ctx);\n    BIGNUM *a = BN_CTX_get(ctx);\n    BIGNUM *b = BN_CTX_get(ctx);\n\n    EC_GROUP_get_curve_GFp(group, p, a, b, ctx);\n\n    BIGNUM *Mx = BN_CTX_get(ctx);\n    BN_copy(Mx, x);\n    BIGNUM *My = BN_CTX_get(ctx);\n    BIGNUM *My2 = BN_CTX_get(ctx);\n    BIGNUM *aMx2 = BN_CTX_get(ctx);\n\n    BIGNUM *half = BN_CTX_get(ctx);\n    BN_copy(half, p);\n    BN_add_word(half, 1);\n    BN_div_word(half, 4);\n\n    /* xoffset can be in the range 1-127 since we have 7 bits free,\n       we only need 1 bit to discern odd from even points\n    */\n    for (int i = 1; i < 128; i++)\n    {\n        BN_add_word(Mx, 1);\n\n        /* My2 = (Mx^2 * Mx mod p) */\n        BN_sqr(My2, Mx, ctx);\n        BN_mod_mul(My2, My2, Mx, p, ctx);\n\n        BN_mod_sqr(aMx2, Mx, p, ctx);\n        BN_mul(aMx2, aMx2, a, ctx);\n\n        BN_mod(b, b, p, ctx);\n\n        BN_add(My2, My2, aMx2);\n        BN_add(My2, My2, b);\n\n        BN_mod_exp(My, My2, half, p, ctx);\n\n        /* this function will return 1 on success (point on curve), else 0 */\n        if (EC_POINT_set_affine_coordinates_GFp(group, M, Mx, My, ctx) == 1)\n        {\n            if (odd == BN_is_bit_set(My, 0))\n            {\n                BN_copy(y, My);\n                *offset = i;\n            }\n            else\n            {\n                BN_sub(y, p, My);\n                *offset = i;\n            }\n\n            ret = 1;\n            break;\n        }\n    }\n\n    /* some errors here are expected since set_affine_coordinates logs an error\n     * when we try to set an invalid x,y combination when trying offsets\n     */\n    if (ERR_peek_error())\n    {\n        unsigned long e = 0;\n        while ((e = ERR_get_error()))\n            LogPrintf(\"y_from_x %s: %s\", ERR_func_error_string(e), ERR_reason_error_string(e));\n    }\n\n    BN_CTX_end(ctx);\n    EC_POINT_free(M);\n\n    return ret;\n}\n\n/* return:  a malloc pointer to the encrypted string,\n * out:     enc_len, size of the encrypted string in bytes\n * in:      pubkey, pointer to raw pubkey\n *          msg, pointer to the message to be encrypted\n *          msg_len, length of the message to be encrypted\n */\nstatic uint8_t *encrypt_message(size_t *enc_len, const uint8_t *pubkey,\n        const uint8_t *msg, const size_t msg_len)\n{\n    BN_CTX *ctx = BN_CTX_new();\n    /* our secp256k1 curve and bitcoin generator\n     * these must be thread local as openssl does not support shared\n     * use of its data structures\n     */\n    EC_GROUP *group = init_curve(ctx);\n\n    uint8_t *ret = NULL;\n\n    EC_POINT *pk = EC_POINT_new(group);\n\n    // get so many blocks of 32B blocks that msg will fit\n    int chunk_count = (PRIVHEADER_LEN + msg_len)/CHUNK_SIZE + 1;\n\n    uint8_t *m = (uint8_t*)OPENSSL_zalloc(chunk_count * CHUNK_SIZE);\n\n    write_private_header(m, msg, msg_len);\n    memcpy(&m[PRIVHEADER_LEN], msg, msg_len);\n\n    BIGNUM *bn_pubkey = BN_new();\n    BN_bin2bn(&pubkey[1], 32, bn_pubkey);\n\n    // pubkey is compressed\n    if (pubkey[0] == 0x02 || pubkey[0] == 0x03)\n    {\n        EC_POINT_set_compressed_coordinates_GFp(group, pk, bn_pubkey, pubkey[0]==0x03, ctx);\n    }\n    else\n    {\n        BIGNUM *bn_pubkey_extra = BN_new();\n\n        BN_bin2bn(&pubkey[1+32], 32, bn_pubkey_extra);\n        EC_POINT_set_affine_coordinates_GFp(group, pk, bn_pubkey, bn_pubkey_extra, ctx);\n\n        BN_free(bn_pubkey_extra);\n    }\n\n    BIGNUM *rand = BN_new();\n    BIGNUM *rand_range = BN_new();\n    BIGNUM *Mx = BN_new();\n    BIGNUM *My = BN_new();\n    EC_POINT *M = EC_POINT_new(group);\n    EC_POINT *T = EC_POINT_new(group);\n    EC_POINT *U = EC_POINT_new(group);\n    EC_GROUP_get_order(group, rand_range, ctx);\n    BN_sub_word(rand_range, 1);\n\n    uint8_t *enc = (uint8_t*)malloc(PUBHEADER_LEN + chunk_count * 2*COMPR_PUBKEY_LEN);\n    write_public_header(enc, pubkey);\n    int enc_loc = PUBHEADER_LEN;\n    int m_loc = 0;\n    size_t xoffset = 0;\n\n    for (int i = 0; i < chunk_count; i++)\n    {\n        /* since rand must be in [1,...,q-1] */\n        BN_rand_range(rand, rand_range);\n        BN_add_word(rand, 1);\n\n        if (!BN_bin2bn(&m[m_loc], CHUNK_SIZE, Mx))\n            goto err;\n\n        if (!y_from_x(group, My, &xoffset, Mx, true, ctx))\n            goto err;\n\n        /* adding our xoffset that we get from y_from_x() */\n        BN_add_word(Mx, xoffset);\n\n        EC_POINT_set_affine_coordinates_GFp(group, M, Mx, My, ctx);\n\n        /* see wiki */\n        EC_POINT_mul(group, T, rand, NULL, NULL, ctx);\n        EC_POINT_mul(group, U, NULL, pk, rand, ctx);\n        EC_POINT_add(group, U, U, M, ctx);\n\n        EC_POINT_point2oct(group, T, POINT_CONVERSION_COMPRESSED,\n                &enc[enc_loc], COMPR_PUBKEY_LEN, ctx);\n        EC_POINT_point2oct(group, U, POINT_CONVERSION_COMPRESSED,\n                &enc[enc_loc+COMPR_PUBKEY_LEN], COMPR_PUBKEY_LEN, ctx);\n\n        /* encoding our offset within the odd/even byte (02/03), the first bit represets\n         * evenness and other 7 represent the offset */\n        enc[enc_loc] = enc[enc_loc] - 2 + (xoffset << 1);\n\n        enc_loc += 2*COMPR_PUBKEY_LEN;\n        m_loc += CHUNK_SIZE;\n    }\n\n    /* success */\n    *enc_len = enc_loc;\n    ret = enc;\n\nerr:\n    if (ERR_peek_error())\n    {\n        unsigned long e = 0;\n        while ((e = ERR_get_error()))\n            LogPrintf(\"encrypt_message %s: %s\", ERR_func_error_string(e), ERR_reason_error_string(e));\n    }\n\n    OPENSSL_clear_free(m, chunk_count * CHUNK_SIZE);\n    BN_free(rand);\n    BN_free(rand_range);\n    BN_free(Mx);\n    BN_free(My);\n    BN_free(bn_pubkey);\n    EC_POINT_free(M);\n    EC_POINT_free(T);\n    EC_POINT_free(U);\n    EC_POINT_free(pk);\n\n    EC_GROUP_free(group);\n    BN_CTX_free(ctx);\n\n    return ret;\n}\n\n/* return:  malloc pointer to the decrypted message\n * out:     dec_len, length of the decrypted message\n * in:      privkey, pointer to raw private key\n *          pubkey, pointer to the raw public key matching privkey\n *          enc, pointer to the encrypted message\n *          enc_len, length of the encrypted message\n */\nstatic uint8_t *decrypt_message(size_t *dec_len, const uint8_t *privkey, const uint8_t *pubkey,\n                                const uint8_t *enc, const size_t enc_len)\n{\n    BN_CTX *ctx = BN_CTX_new();\n    EC_GROUP *group = init_curve(ctx);\n\n    /* check that the public header is valid and matches our priv/pubkey pair */\n    if (!read_public_header(group, enc, pubkey, ctx))\n        return NULL;\n\n    int chunk_count = (enc_len - PUBHEADER_LEN) / (2*COMPR_PUBKEY_LEN);\n\n    uint8_t *r = (uint8_t*)OPENSSL_malloc(PRIVHEADER_LEN + chunk_count * CHUNK_SIZE);\n\n    uint8_t *Tser = (uint8_t*)OPENSSL_malloc(COMPR_PUBKEY_LEN);\n    uint8_t *User = (uint8_t*)OPENSSL_malloc(COMPR_PUBKEY_LEN);\n    int xoffset = 0;\n\n    EC_POINT *T = EC_POINT_new(group);\n    EC_POINT *U = EC_POINT_new(group);\n    EC_POINT *M = EC_POINT_new(group);\n    EC_POINT *V = EC_POINT_new(group);\n\n    BIGNUM *Mx = BN_new();\n\n    BIGNUM *bn_privkey = BN_new();\n    BN_bin2bn(privkey, PRIVKEY_LEN, bn_privkey);\n\n    int enc_loc = PUBHEADER_LEN;\n    int r_loc = 0;\n    for (int i = 0; i < chunk_count; i++)\n    {\n        memcpy(Tser, &enc[enc_loc], COMPR_PUBKEY_LEN);\n        memcpy(User, &enc[enc_loc+COMPR_PUBKEY_LEN], COMPR_PUBKEY_LEN);\n\n        /* decode the offset and evenness from the first byte */\n        xoffset = Tser[0] >> 1;\n        Tser[0] = 2 + (Tser[0]&1);\n\n        EC_POINT_oct2point(group, T, Tser, COMPR_PUBKEY_LEN, ctx);\n        EC_POINT_oct2point(group, U, User, COMPR_PUBKEY_LEN, ctx);\n\n        EC_POINT_mul(group, V, NULL, T, bn_privkey, ctx);\n        EC_POINT_invert(group, V, ctx);\n        EC_POINT_add(group, M, U, V, ctx);\n\n        EC_POINT_get_affine_coordinates_GFp(group, M, Mx, NULL, ctx);\n\n        /* substract our offset so that we get the original Mx */\n        BN_sub_word(Mx, xoffset);\n\n        BN_bn2binpad(Mx, &r[r_loc], CHUNK_SIZE);\n\n        r_loc += CHUNK_SIZE;\n        enc_loc += 2*COMPR_PUBKEY_LEN;\n    }\n\n    uint8_t *ret = NULL;\n\n    size_t size = 0;\n    if (!read_private_header(&size, r))\n        goto err;\n\n    /* success */\n    ret = (uint8_t*)malloc(size);\n    memcpy(ret, &r[PRIVHEADER_LEN], size);\n    *dec_len = size;\n\nerr:\n    if (ERR_peek_error())\n    {\n        unsigned long e = 0;\n        while ((e = ERR_get_error()))\n            LogPrintf(\"decrypt_message %s: %s\", ERR_func_error_string(e), ERR_reason_error_string(e));\n    }\n\n    OPENSSL_free(Tser);\n    OPENSSL_free(User);\n\n    EC_POINT_clear_free(V);\n    EC_POINT_clear_free(U);\n    EC_POINT_clear_free(M);\n    EC_POINT_clear_free(T);\n\n    BN_free(Mx);\n    BN_clear_free(bn_privkey);\n\n    OPENSSL_clear_free(r, r_loc);\n\n    EC_GROUP_free(group);\n    BN_CTX_free(ctx);\n\n    return ret;\n}\n\n/* wrappers for the C functions\n */\nusing namespace std;\n\nnamespace Jeeq {\n\nvector<uint8_t> EncryptMessage(const CPubKey pubkey, const string msg)\n{\n    // check pubkey\n    if (!pubkey.IsValid())\n        throw runtime_error(\"Jeeq::EncryptMessage(): called with an invalid public key\");\n    //  ensure that msg is not empty\n    if (msg.size() == 0) throw runtime_error(\"Jeeq::EncryptMessage(): no message to encrypt\");\n\n    size_t enc_len = 0;\n    uint8_t *benc = encrypt_message(&enc_len, pubkey.begin(), (uint8_t*)&msg[0], msg.size());\n    if (benc == NULL || enc_len == 0)\n        return vector<uint8_t>{};\n\n    vector<uint8_t> enc(benc, benc+enc_len);\n    return enc;\n}\n\nstring DecryptMessage(const CKey privkey, const vector<uint8_t> enc)\n{\n    // check privkey\n    if (!privkey.IsValid())\n        throw runtime_error(\"Jeeq::DecryptMessage(): called with an invalid private key\");\n    // ensure that enc is not empty\n    if (enc.size() == 0)\n        throw runtime_error(\"Jeeq::DecryptMessage(): no encoded message to decrypt\");\n\n    size_t dec_len = 0;\n    CPubKey pubkey = privkey.GetPubKey();\n    uint8_t *bdec = decrypt_message(&dec_len, privkey.begin(), pubkey.begin(),\n                      enc.data(), enc.size());\n    if (bdec == NULL || dec_len == 0)\n        return string();\n\n    string dec(bdec, bdec+dec_len);\n    free(bdec);\n    return dec;\n}\n\n}\n\n// if we don't do this bignum.h ducks everything up\n#include \"base58.h\"\n#include \"net.h\"\n#include \"netbase.h\"\n#include \"util.h\"\n#include \"wallet.h\"\n#include \"walletdb.h\"\n\n// auxillary function for EncryptMessage\nnamespace Jeeq {\nCPubKey SearchForPubKey(CBitcoinAddress addr)\n{\n    CScript spk;\n    spk.SetDestination(addr.Get());\n\n    CBlock block;\n    uint256 blockhash;\n    CTransaction txout;\n\n    // beginning at the blockchain tip going back\n    for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)\n    {\n        if (!ReadBlockFromDisk(block, pindex))\n            return CPubKey();\n\n        // skip coinbase (vtx[0])\n        for (unsigned int i = 1; i < block.vtx.size(); i++)\n        {\n            for (unsigned int j = 0; j < block.vtx[i].vin.size(); j++)\n            {\n                // get tx from txid and blockhash and store it in txout\n                GetTransaction(block.vtx[i].vin[j].prevout.hash, txout, blockhash);\n                int n = block.vtx[i].vin[j].prevout.n;\n\n                if (txout.vout[n].scriptPubKey == spk)\n                {\n                    CScript ssig = block.vtx[i].vin[j].scriptSig;\n\n                    opcodetype opcode;\n                    std::vector<unsigned char> pkdata;\n                    auto pc = ssig.begin();\n\n                    // we do it twice since the pubkey is the second item\n                    ssig.GetOp(pc, opcode, pkdata);\n                    ssig.GetOp(pc, opcode, pkdata);\n\n                    return CPubKey(pkdata.begin(), pkdata.end());\n                }\n            }\n        }\n    }\n\n    return CPubKey();\n}\n} // Namespace Jeeq\n", "meta": {"hexsha": "b1d1712b45cb891b6f9e36b4fd22bf62d415ecd3", "size": 17030, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/jeeq.cpp", "max_stars_repo_name": "frokenfreyja/smileyCoin", "max_stars_repo_head_hexsha": "d57952bcee45508616802150afee804dffc9ffa2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/jeeq.cpp", "max_issues_repo_name": "frokenfreyja/smileyCoin", "max_issues_repo_head_hexsha": "d57952bcee45508616802150afee804dffc9ffa2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/jeeq.cpp", "max_forks_repo_name": "frokenfreyja/smileyCoin", "max_forks_repo_head_hexsha": "d57952bcee45508616802150afee804dffc9ffa2", "max_forks_repo_licenses": ["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.7668918919, "max_line_length": 115, "alphanum_fraction": 0.6179682913, "num_tokens": 4990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.6117593370552572}}
{"text": "/**\n * @file   test.cpp\n * @author Chengyu Liu \n * @date   Tue 08 June 2021\n *\n * @brief  \u8fd9\u662f\u4e2a\u629b\u7269\u578b\u65b9\u7a0b\u7684\u4f8b\u5b50\uff0c\u975e\u5e38\u7b80\u5355\uff0c\u4e2d\u95f4\u5c31\u6ca1\u6709\u89e3\u91ca\u592a\u591a\u4e86\n *\n */\n\n#include <iostream>\n#include <vector>\n#include <iterator>\n#include <algorithm>\n\n#include <base/exceptions.h>\n#include <lac/full_matrix.h>\n#include <lac/sparsity_pattern.h>\n#include <lac/sparse_matrix.h>\n\n\n#include <AFEPack/EasyMesh.h>\n#include <AFEPack/TemplateElement.h>\n#include <AFEPack/FEMSpace.h>\n#include <AFEPack/BilinearOperator.h>\n#include <AFEPack/Operator.h>\n#include <AFEPack/Geometry.h>\n#include <AFEPack/BoundaryCondition.h>\n\n//#include <trace/mintrace.h>\n#include <CG/CGSolver.h>\n#include <EigenSolver/Miscellaneous.h>\n#include <EigenSolver/EigenSolver.h>\n#define DIM 2\n#define PI (4.0*atan(1.0)) \n\n/// \u521d\u503c\u548c\u8fb9\u503c\u7684\u8868\u8fbe\u5f0f\ndouble _u_(const double * p)\n{\n  return sin(PI*p[0]) * sin(PI*p[1]);\n  //return sin(PI*p[0]) * sin(2*PI*p[1]);\n  //return p[0]*exp(p[1]);\n}\n\n/// \u53f3\u7aef\u9879 In fact, right hand side vector will not be used in Laplacian eigenvalue problems.\ndouble _f_(const double * p)\n{\n  return 10+5*PI*PI*_u_(p);\n  //return p[0]*p[1] + sin(p[1]);\n}\n\ndouble f(const double * p)\n{\n  return 0;\n}\n\n/// Construct the Stiff matrix in the left hand side.\nclass Stiff_Matrix : public L2InnerProduct<DIM,double>\n{\npublic:\n  Stiff_Matrix(FEMSpace<double,DIM>& sp) :\n    L2InnerProduct<DIM,double>(sp, sp) {}\n  virtual void getElementMatrix(const Element<double,DIM>& e0,\n                                const Element<double,DIM>& e1,\n                                const ActiveElementPairIterator< DIM >::State s)\n  {\n    double vol = e0.templateElement().volume();\n    u_int acc = algebricAccuracy();\n    const QuadratureInfo<DIM>& qi = e0.findQuadratureInfo(acc);\n    u_int n_q_pnt = qi.n_quadraturePoint();\n    std::vector<double> jac = e0.local_to_global_jacobian(qi.quadraturePoint());\n    //AFEPack::Point<DIM> test1;\n    //std::vector<AFEPack::Point<DIM>> test2;\n    // \n    // Here always get an error! vector<Point<DIM> >;\n    // Reason: Because there is a same name class in deal.ii: Point class. While\n    // using Point, it might use the dealii.Point defaultly!!!! So you just add \n    // the namespace to control the class will solve the problem;\n    std::vector<AFEPack::Point<DIM>> q_pnt = e0.local_to_global(qi.quadraturePoint());\n    //std::cout<<\"ATTENTION!This is a test flag!!!\"<<std::endl;\n    std::vector<std::vector<double> > bas_val = e0.basis_function_value(q_pnt);\n    std::vector<std::vector<std::vector<double> > > bas_grad = e0.basis_function_gradient(q_pnt);\n    u_int n_ele_dof = e0.dof().size();\n    for (u_int l = 0;l < n_q_pnt;++ l) {\n      double Jxw = vol*qi.weight(l)*jac[l];\n      for (u_int i = 0;i < n_ele_dof;++ i) {\n        for (u_int j = 0;j < n_ele_dof;++ j) {\n          //elementMatrix(i,j) += Jxw*(bas_val[i][l]*bas_val[j][l]/_dt +\n\t  //                         innerProduct(bas_grad[i][l], bas_grad[j][l]));\n\t  elementMatrix(i,j) += Jxw*(innerProduct(bas_grad[i][l], bas_grad[j][l]));\n        }\n      }\n    }\n  }\n};\n\n// Construct the Mass matrix in the right hand side,\nclass Mass_Matrix : public L2InnerProduct<DIM,double>\n{\npublic:\n  Mass_Matrix(FEMSpace<double,DIM>& sp) :\n    L2InnerProduct<DIM,double>(sp, sp){}\n  virtual void getElementMatrix(const Element<double,DIM>& e0,\n                                const Element<double,DIM>& e1,\n                                const ActiveElementPairIterator< DIM >::State s)\n  {\n    double vol = e0.templateElement().volume();\n    u_int acc = algebricAccuracy();\n    const QuadratureInfo<DIM>& qi = e0.findQuadratureInfo(acc);\n    u_int n_q_pnt = qi.n_quadraturePoint();\n    std::vector<double> jac = e0.local_to_global_jacobian(qi.quadraturePoint());\n    //AFEPack::Point<DIM> test1;\n    //std::vector<AFEPack::Point<DIM>> test2;\n    // \n    // Here always get an error! vector<Point<DIM> >;\n    // Reason: Because there is a same name class in deal.ii: Point class. While\n    // using Point, it might use the dealii.Point defaultly!!!! So you just add \n    // the namespace to control the class will solve the problem;\n    std::vector<AFEPack::Point<DIM>> q_pnt = e0.local_to_global(qi.quadraturePoint());\n    //std::cout<<\"ATTENTION!This is a test flag!!!\"<<std::endl;\n    std::vector<std::vector<double> > bas_val = e0.basis_function_value(q_pnt);\n    std::vector<std::vector<std::vector<double> > > bas_grad = e0.basis_function_gradient(q_pnt);\n    u_int n_ele_dof = e0.dof().size();\n    for (u_int l = 0;l < n_q_pnt;++ l) {\n      double Jxw = vol*qi.weight(l)*jac[l];\n      for (u_int i = 0;i < n_ele_dof;++ i) {\n        for (u_int j = 0;j < n_ele_dof;++ j) {\n          /*elementMatrix(i,j) += Jxw*(bas_val[i][l]*bas_val[j][l]/_dt +\n\t    innerProduct(bas_grad[i][l], bas_grad[j][l]));*/\n\t  elementMatrix(i,j) += Jxw*(bas_val[i][l]*bas_val[j][l]);\n        }\n      }\n    }\n  }\n};\n\nvoid boundary_condition_apply(const FEMSpace<double, DIM>& sp, \n\t\tSparseMatrix<double>& A, \n\t\tBoundaryConditionAdmin<double,DIM> boundary,\n\t\tbool preserve_symmetry = true)\n{\n  u_int n_dof = sp.n_dof();\n  const SparsityPattern& spA = A.get_sparsity_pattern();\n  const std::size_t * rowstart = spA.get_rowstart_indices();\n  const u_int * colnum = spA.get_column_numbers();\n  \n  for(u_int i=0; i< n_dof; ++ i)\n  {\n\t  int bm = sp.dofInfo(i).boundary_mark;\n\t  std::cout<<\"The \"<<i<<\"-th dof corresponding boundary mark is:\"<<bm<<std::endl;\n  }\n \n  int numOfbm = 0; \n  for (u_int i = 0; i < n_dof; ++ i){\n    int bm = sp.dofInfo(i).boundary_mark;\n    if (bm == 0) continue;\n    // For this case only 1 for Drichlet boundary condition.\n    if (bm != 1) continue; // Attention, For this case specially.\n\n    numOfbm += 1;\n\n    for (u_int j = rowstart[i]+1; j < rowstart[i+1]; ++ j){\n\t    A.global_entry(j) -= A.global_entry(j);\n    }\n    if (preserve_symmetry) {\n      for (u_int j = rowstart[i] + 1;j < rowstart[i + 1];++ j) {\n        u_int k = colnum[j];\n        const u_int * p = std::find(&colnum[rowstart[k] + 1],\n                                    &colnum[rowstart[k + 1]], i);\n        if (p != &colnum[rowstart[k+1]]) {\n          u_int l = p - &colnum[rowstart[0]];\n          A.global_entry(l) -= A.global_entry(l);\n        }\n      }\n    }\n  }\n  \n  std::cout<<\"!@@@@@@@@@@The number of Dirchlet is :\"<<numOfbm<<std::endl;    \n    \n}\n\nint main(int argc, char * argv[])\n{\n  /// \u51c6\u5907\u7f51\u683c\n  EasyMesh mesh;\n  mesh.readData(argv[1]);\n\n  /// \u51c6\u5907\u53c2\u8003\u5355\u5143\n  TemplateGeometry<DIM> tmp_geo;\n  tmp_geo.readData(\"triangle.tmp_geo\");\n  CoordTransform<DIM,DIM> crd_trs;\n  crd_trs.readData(\"triangle.crd_trs\");\n  TemplateDOF<DIM> tmp_dof(tmp_geo);\n  tmp_dof.readData(\"triangle.2.tmp_dof\");\n  BasisFunctionAdmin<double,DIM,DIM> bas_fun(tmp_dof);\n  bas_fun.readData(\"triangle.2.bas_fun\");\n\n  std::vector<TemplateElement<double,DIM> > tmp_ele(1);\n  tmp_ele[0].reinit(tmp_geo, tmp_dof, crd_trs, bas_fun);\n\n  /// \u5b9a\u5236\u6709\u9650\u5143\u7a7a\u95f4\n  FEMSpace<double,DIM> fem_space(mesh, tmp_ele);\n  u_int n_ele = mesh.n_geometry(DIM);\n  fem_space.element().resize(n_ele);\n  for (u_int i = 0;i < n_ele;++ i) {\n    fem_space.element(i).reinit(fem_space, i, 0);\n  }\n  fem_space.buildElement();\n  fem_space.buildDof();\n  fem_space.buildDofBoundaryMark();\n\n  /// \u51c6\u5907\u521d\u503c\n  FEMFunction<double,DIM> u_h(fem_space);\n  Operator::L2Interpolate(&_u_, u_h);\n\n  /// \u51c6\u5907\u8fb9\u754c\u6761\u4ef6\n  Vector<double> rhs;\n  Operator::L2Discretize(&f, fem_space, rhs, 4);\n\n  BoundaryFunction<double,DIM> boundary(BoundaryConditionInfo::DIRICHLET,\n                                        1,\n                                        &_u_);\n  BoundaryConditionAdmin<double,DIM> boundary_admin(fem_space);\n  boundary_admin.add(boundary);\n\n  // double t;//\n\n\n  // double dt = 0.01; /// \u7b80\u5355\u8d77\u89c1\uff0c\u968f\u624b\u53d6\u4e2a\u65f6\u95f4\u6b65\u957f\u7b97\u4e86\n\n  /// \u51c6\u5907\u7ebf\u6027\u7cfb\u7edf\u7684\u77e9\u9635\n  /*\n  Matrix mat(fem_space, dt);\n  mat.algebricAccuracy() = 3;\n  mat.build();*/\n\n\n  StiffMatrix<2,double> stiff_matrix(fem_space);\n  stiff_matrix.algebricAccuracy() = 4;\n  stiff_matrix.build();\n  boundary_condition_apply(fem_space, stiff_matrix, boundary_admin);\n\n  MassMatrix<2,double> mass_matrix(fem_space);\n  mass_matrix.algebricAccuracy() = 4;\n  mass_matrix.build();\n  boundary_condition_apply(fem_space, mass_matrix, boundary_admin);\n\n  \n  /*\n  /// \u51c6\u5907\u53f3\u7aef\u9879\n  Vector<double> rhs(fem_space.n_dof());\n  FEMSpace<double,DIM>::ElementIterator the_ele = fem_space.beginElement();\n  FEMSpace<double,DIM>::ElementIterator end_ele = fem_space.endElement();\n  for (;the_ele != end_ele;++ the_ele) {\n    double vol = the_ele->templateElement().volume();\n    const QuadratureInfo<DIM>& qi = the_ele->findQuadratureInfo(3);\n    u_int n_q_pnt = qi.n_quadraturePoint();\n    std::vector<double> jac = the_ele->local_to_global_jacobian(qi.quadraturePoint());\n    std::vector<AFEPack::Point<DIM>> q_pnt = the_ele->local_to_global(qi.quadraturePoint());\n    std::vector<std::vector<double> > bas_val = the_ele->basis_function_value(q_pnt);\n\n    /// \u5f53\u57fa\u51fd\u6570\u7684\u503c\u5df2\u77e5\u60c5\u51b5\u4e0b\uff0c\u53ef\u4ee5\u4f7f\u7528\u4e0b\u9762\u7684\u51fd\u6570\u6765\u52a0\u901f\n    std::vector<double> u_h_val = u_h.value(bas_val, *the_ele);\n    std::vector<std::vector<double> > u_h_grad = u_h.gradient(q_pnt, *the_ele);\n    const std::vector<int>& ele_dof = the_ele->dof();\n    u_int n_ele_dof = ele_dof.size();\n    for (u_int l = 0;l < n_q_pnt;++ l) {\n      double Jxw = vol*qi.weight(l)*jac[l];\n      double f_val = _f_(q_pnt[l]);\n      for (u_int i = 0;i < n_ele_dof;++ i)\n\t{\n\t  rhs(ele_dof[i]) += Jxw*bas_val[i][l]*(u_h_val[l]/dt + f_val);\n        }\n    }\n    }*/\n\n  /// \u5e94\u7528\u8fb9\u754c\u6761\u4ef6\n  //  boundary_admin.apply(mat, u_h, rhs);\n\n  /// \u6c42\u89e3\u7ebf\u6027\u7cfb\u7edf\n  /*\n  AMGSolver solver;\n  solver.lazyReinit(mat);\n  solver.solve(u_h, rhs, 1.0e-08, 50);*/\n  //TraceSolver soll(stiff_matrix, mass_matrix);\n  CGSolver AAAA;\n  EigenSolver solver(stiff_matrix, mass_matrix);\n  /*\n  std::vector<double>rhs(stiff_matrix.m(),0),x(12,0);\n  rhs[0]=-0.107343;\n  rhs[1]=-0.107920;\n  rhs[2]=0.296721;\n  rhs[3]=0.136396;\n  rhs[4]=-1.038010;\n  rhs[5]=-0.456170;\n  rhs[6]=0.694243;\n  rhs[7]=1.047650;\n  rhs[8]=0.488934;\n  rhs[9]=0.065605;\n  rhs[10]=-0.113350;\n  rhs[11]=-0.309275;\n  std::vector<double> temp(6,0);\n  std::vector<std::vector<double>> tempX(12,temp);\n  solver.X=tempX;\n  for(int i=0;i<12;i++)\n    {\n      for(int j=0;j<6;j++)\n\t{\n\t  std::cin>>solver.X[i][j];\n\t}\n    }\n  solver.get_MX();\n  solver.solve(x, rhs, 1.0e-3, 200);\n  std::cout<<\"The rhs vector before CG is :\\n\";\n  for(int i=0;i<rhs.size();i++)\n    {\n      std::cout<<rhs[i]<<\" \";\n    }\n  std::cout<<std::endl;\n  std::cout<<\"The solution of CG\\n\";\n  for(int i=0;i<x.size();i++)\n    {\n      std::cout<<x[i]<<\" \";\n    }\n  std::cout<<std::endl;\n  */\n  \n  /////////////////////////////\n  \n  //solver.mintrace(10, 1.0e-3, 200);\n  std::vector<double> x(stiff_matrix.m(),1);\n  double lambda;\n  solver.PowerSolve(x, lambda);\n  /*\n  std::cout<<\"This is the maximal eigenvalues of AX=lambda Mx;\\n\";\n  for (int i=0;i < x.size();i++)\n  {\n    std::cout<<x[i]<<\" \";\n  }\n  std::cout<<\"\\n\";\n*/\n  std::vector<double> x2(stiff_matrix.m(),1);\n  solver.IPowerSolve(x2, lambda, 100, 1.e-3);\n\n  int eig_num=5;\n  std::vector<double> tempxx(eig_num,0), lam_3(eig_num,0);\n  std::vector<std::vector<double>> x3(stiff_matrix.m(),tempxx);\n  /*\n  for(int k=0;k<eig_num;k++)\n  {\n    x3[k][k]=1;\n  }*/\n\n  for (int i=0;i<x3.size();i++)\n  {\n    for(int j=0;j<x3[0].size();j++)\n    {\n      x3[i][j] = ((double) rand() / (RAND_MAX));\n    }\n  }\n\n  solver.BIPowerSolve(x3, lam_3, eig_num, 1000, 1.e-3);\n  std::cout<<\"The \"<<eig_num<<\" smallest eigenvalues are:\\n\";\n\n  for (int k=0;k<eig_num;k++)\n  {\n    std::cout<<lam_3[k]<<\" \";\n  }\n  std::cout<<\"\\n\";\n\n  std::cout<<\"The matrix are:\\n\";\n  show_matrix(x3);\n\n\n//  std::cout<<\"This is the minimal eigenvalues of AX=lambda Mx;\\n\";\n  /*\n  for (int i=0;i < x2.size();i++)\n  {\n    std::cout<<x2[i]<<\" \";\n  }\n  std::cout<<\"\\n\";\n  */\n  /*for (int i=0;i<solver.lambda.size();i++)\n    {\n      std::cout<<solver.lambda[i]<<std::endl;\n    }\n  std::cout<<\"\\n\";\n*/\n  /*\n  std::vector<double> exact_eigen={2.0*PI*PI,PI*PI,PI*PI,0.0};\n  std::cout<<\" The exact eigens are:\\n\";\n  for (int i=0;i<solver.lambda.size();i++)\n    {\n      std::cout<<fabs(solver.lambda[i]-exact_eigen[i])<<std::endl;\n      // std::cout<<exact_eigen[i]<<std::endl;\n    }\n  std::cout<<\"\\n\";\n  \n  std::cout<<\"This is the matrix V after the whole process\\n\";\n  for(int i=0;i<solver.X.size();i++)\n    {\n      for(int j=0;j<solver.X[0].size();j++)\n\t{\n\t  std::cout<<solver.X[i][j]<<\" \";\n\t}\n      std::cout<<std::endl;\n      }*/\n  \n  \n  /*\n  std::cout<<\"Output the solution matrix X!\\n\";\n  for(int i=0;i<solver.X.size();i++)\n    {\n      for(int j=0;j<solver.X[0].size();j++)\n\t{\n\t  std::cout<<solver.X[i][j]<<\" \";\n\t}\n      std::cout<<std::endl;\n    }\n  std::cout<<std::endl;\n  */\n\n  /// \u8f93\u51fa\u6570\u636e\u753b\u56fe\n  /* u_h.writeOpenDXData(\"u_h.dx\");*/\n  // std::cout << \"Press ENTER to continue or CTRL+C to stop ...\" << std::flush;\n  // getchar();\n\n  // t += dt; /// \u66f4\u65b0\u65f6\u95f4\n    \n  //std::cout << \"\\n\\tt = \" <<  t << std::endl;\n\n  // Print the stiffness matrix in to .txt and .gnuplot form.\n // std::ofstream sparsematrix2 (\"stiff_matrix.1\");\n // stiff_matrix.print(sparsematrix2);\n\n  std::filebuf fb;\n  fb.open (\"stiff_matrix.txt\",std::ios::out);\n  std::ostream os(&fb);\n  stiff_matrix.print_formatted(os, 3, true, 0, \"0.0\", 1);\n  fb.close();\n\n\n // Print the mass matrix into .txt and .gnuplot form. \n//  std::ofstream sparsematrix  (\"mass_matrix.1\");\n // mass_matrix.print(sparsematrix);\n\n  std::filebuf fb2;\n  fb2.open (\"mass_matrix.txt\",std::ios::out);\n  std::ostream os2(&fb2);\n  mass_matrix.print_formatted(os2, 3, true, 0, \"0.0\", 1);\n  fb2.close();\n\n\n /* \n  std::cout<<\"Attention! This is print out the columns of the matrix A and M\\n\";\n  std::vector<double> tempx(stiff_matrix.n(),0), tempAx, tempMx;\n\n  for(int i=0;i<solver.A->m();i++)\n    {\n      tempx[i]=1;\n      \n      tempAx=multiply(solver.A, tempx);\n      for(int j=0;j<tempAx.size();j++)\n\t{\n\t  std::cout<<tempAx[j]<<\" \";\n\t}\n\tstd::cout<<std::endl;\n      \n      tempMx=multiply(solver.M, tempx);\n      for(int j=0;j<tempMx.size();j++)\n\t{\n\t  std::cout<<tempMx[j]<<\" \";\n\t}\n      std::cout<<std::endl;\n      tempx[i]=0;\n    }\n    */\n  \n  return 0;\n}\n\n/**\n * end of file\n *\n */\n", "meta": {"hexsha": "6f3e8310da27d350968f28045c069be93f0008f8", "size": 13912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EigenSolver/example/laplacian/test.cpp", "max_stars_repo_name": "CauchYLIU3551/EigenSolver", "max_stars_repo_head_hexsha": "cd901cbbea2cc5bfe8cb9325ba5c266b3627e169", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EigenSolver/example/laplacian/test.cpp", "max_issues_repo_name": "CauchYLIU3551/EigenSolver", "max_issues_repo_head_hexsha": "cd901cbbea2cc5bfe8cb9325ba5c266b3627e169", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EigenSolver/example/laplacian/test.cpp", "max_forks_repo_name": "CauchYLIU3551/EigenSolver", "max_forks_repo_head_hexsha": "cd901cbbea2cc5bfe8cb9325ba5c266b3627e169", "max_forks_repo_licenses": ["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.6845360825, "max_line_length": 97, "alphanum_fraction": 0.6107676826, "num_tokens": 4530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6117593261535729}}
{"text": "#include \"creapairmatrix.h\"\n#include <iostream> // for cout\n#include <fstream>  // for ifstream\n#include <armadillo>\n#include <algorithm>    // std::sort\n\nusing namespace arma;\n\n// https://stackoverflow.com/questions/11964552/finding-quartiles?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qac++\ntemplate <typename T1, typename T2> typename T1::value_type quant(const T1 &x, T2 q)\n{\n    //assert(q >= 0.0 && q <= 1.0);\n\n    const auto n  = x.size();\n    const auto id = (n - 1) * q;\n    const auto lo = floor(id);\n    const auto hi = ceil(id);\n    const auto qs = x[lo];\n    const auto h  = (id - lo);\n\n    return (1.0 - h) * qs + h * x[hi];\n}\n\nCReadPairMatrix::CReadPairMatrix()\n{\n    m_alpha = 1.0;\n}\n\nint CReadPairMatrix::ReadTSV(const char* filename)\n{\n    this->matrixValue.empty();\n    this->filterdMatrixValue.empty();\n    this->nullMatrixValue.empty();\n    this->IS2MatrixValue.empty();\n\n    this->vecColName.empty();\n    this->vecRowName.empty();\n\n\n    ifstream infile(filename);\n    if (!infile) {\n        cout << \"unable to load file\" << endl;\n    }\n    string str;\n\n    vector<vector<string>> vvStr;\n\n    vector<string> vecTitle;\n    int pos1, pos2;\n\n    // title\n\n    getline(infile, str);\n    pos1 = 0;\n    pos2 = str.find('\\t',pos1);\n    pos1 = ++pos2;\n    while((pos2 = str.find('\\t',pos1))!= string::npos)\n    {\n        this->vecColName.push_back(str.substr(pos1, pos2-pos1));\n        pos1 = ++pos2;\n    }\n    this->vecColName.push_back(str.substr(pos1, string::npos));   // the last name\n\n    // values\n    //int nRowIndex = 0;\n    while (getline(infile, str))\n    {\n        pos1 = 0;\n        vector<float> vFloat;\n        pos2 = str.find('\\t',pos1);\n        this->vecRowName.push_back( str.substr(pos1, pos2-pos1) );\n        pos1 = ++pos2;\n        while((pos2 = str.find('\\t',pos1))!= string::npos)\n        {\n            vFloat.push_back(stof(str.substr(pos1, pos2-pos1)));\n            pos1 = ++pos2;\n        }\n        vFloat.push_back(stof(str.substr(pos1, string::npos)));     // the last value\n        //std::sort(vFloat.begin(),vFloat.end());\n        //std::cout << nRowIndex << \"\\t\" << quant(vFloat, 0.75) << std::endl;\n        //nRowIndex++;\n        this->matrixValue.push_back(vFloat);\n\n    }\n\n    float sum = 0;\n    for(vector<float> x : this->matrixValue)\n        for(float i : x)\n            sum += i;\n\n    cout << \"Read pair sum = \" << sum << endl;\n\n    return 1;\n}\n\nint CReadPairMatrix::Nullmatrix()\n{\n\n\n    float TotalSum = 0;\n    int nCols = this->vecColName.size();\n    int nRows = this->vecRowName.size();\n\n\n    // total sums\n    for(vector<float> x : this->matrixValue)\n        for(float i : x)\n            TotalSum += i;\n\n    TotalSum += ( nCols * nRows );\n\n\n    vector<float> colSums;\n    // col sums\n    for(int i = 0; i < nCols; i++ ){\n        float sum = 0;\n        for(vector<float> x : this->matrixValue){\n            sum += x[i];\n            sum += m_alpha;\n        }\n        colSums.push_back( sum / TotalSum );\n    }\n\n\n    vector<float> rowSums;\n    // row sums\n    for(vector<float> x : this->matrixValue){\n        float sum = 0;\n        for(int i = 0; i < nRows; i++ ){\n            sum += x[i];\n            sum += m_alpha;\n        }\n        rowSums.push_back( sum / TotalSum );\n    }\n\n    nullMatrixValue.empty();\n    for(int i = 0; i < nRows; i++ ){\n        vector<float> x;\n        for(int j = 0; j < nCols; j++ ){\n            float nullValue = rowSums[i] * colSums[j];\n            x.push_back( nullValue * TotalSum );   //x.push_back( int(nullValue * TotalSum) );\n        }\n        nullMatrixValue.push_back(x);\n    }\n}\n\nint CReadPairMatrix::GMM_Fit()\n{\n    int N = this->vecColName.size() * this->vecRowName.size();\n\n    // create synthetic data containing\n    // 2 clusters with normal distribution\n    int d = 1; // dimensionality\n    //uword N = 10000; // number of samples (vectors)\n    mat data(d, N, fill::zeros);\n\n    float sum = 0;\n    int i = 0;\n    for(vector<float> values : this->matrixValue)\n        for(float value : values)\n        {\n            data.col(i) = value;\n            i++;\n        }\n\n    // model the data as a diagonal GMM with 2 Gaussians\n    gmm_diag model;\n    bool status = model.learn(data, 2, maha_dist, random_subset,10, 5, 1e-10, true);\n    if(status == false) { cout << \"learning failed\" << endl; }\n\n    double overall_likelihood = model.avg_log_p(data);\n\n    rowvec set_likelihood = model.log_p( data.cols(0,9) );\n    double scalar_likelihood = model.log_p( data.col(0) );\n\n    uword gaus_id = model.assign( data.col(0), eucl_dist );\n    urowvec gaus_ids = model.assign( data.cols(0,9), prob_dist );\n\n\n    filterdMatrixValue.empty();\n    // Add filtered values\n    i = 0;\n    int filtered_cnt = 0;\n    int filtered_non_zero_cnt = 0;\n    for(vector<float> x : this->matrixValue){\n        vector<float> filteredValues;\n        for(float value : x){\n            uword gaus_id1 = model.assign( data.col(i), eucl_dist ); //prob_dist );\n            if ( gaus_id1 == 0) {\n                filteredValues.push_back(value);\n                cout << \"## pos\\t\" << value << endl;\n            }\n            else{\n                filteredValues.push_back(0.0);\n                cout << \"## filtered\\t\" << value << endl;\n                filtered_cnt ++;\n                if ( value != 0 ) filtered_non_zero_cnt ++;\n            }\n            i++;\n        }\n        filterdMatrixValue.push_back(filteredValues);\n    }\n\n    urowvec histogram1 = model.raw_hist (data, prob_dist);\n    rowvec histogram2 = model.norm_hist(data, eucl_dist);\n\n    model.means.print(\"means:\");\n\n    cout << \"filtered_cnt\\t\" << filtered_cnt << endl;\n    cout << \"filtered_non_zero_cnt\\t\" << filtered_non_zero_cnt << endl;\n    cout << \"histogram1\\t\" << histogram1[0] << \"\\t\" << histogram1[1] << endl;\n    cout << \"histogram2\\t\" << histogram2[0] << \"\\t\" << histogram2[1] << endl;\n\n    model.save(\"/Users/jyang/my_model.gmm\");\n\n    mat modified_dcovs = 2 * model.dcovs;\n\n    model.set_dcovs(modified_dcovs);\n\n    return 0;\n}\n\nint CReadPairMatrix::InteractionScore2(vector<vector<float>>& nullMat, vector<vector<float>>& filterdMat)\n{\n    IS2MatrixValue.empty();\n\n    int nCols = this->vecColName.size();\n    int nRows = this->vecRowName.size();\n\n\n    for(int i = 0; i < nRows; i++ ){\n        vector<float> x;\n        vector<float> t;\n        for(int j = 0; j < nCols; j++ ){\n            float nullValue = nullMat[i][j];\n            float filteredValue = filterdMat[i][j];\n            float IS2 = filteredValue / nullValue;\n            x.push_back( IS2 );\n            t.push_back( IS2 );\n        }\n\n        // Remove the 75th percentile signal\n        std::sort(t.begin(),t.end());\n        //std::cout << nRowIndex << \"\\t\" << quant(vFloat, 0.75) << std::endl;\n        float quantile = quant(t, 0.75);\n        if ( quantile == 0.0 ){\n            IS2MatrixValue.push_back( x );\n        }\n        else{\n            for(int j = 0; j < nCols; j++ ){\n                x[j] -= quantile;\n                if ( x[j] < 0.0 ) x[j] = 0.0;\n            }\n            IS2MatrixValue.push_back( x );\n        }\n\n\n        //std::cout << quant(x, 0.75) << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "d6314a15ae15d40f7f74c6f1f84ad73073f8048c", "size": 7132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/creapairmatrix.cpp", "max_stars_repo_name": "lionking0000/recYnH_Qt", "max_stars_repo_head_hexsha": "04651b500055a330b911db4f0af0d82a387393be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/creapairmatrix.cpp", "max_issues_repo_name": "lionking0000/recYnH_Qt", "max_issues_repo_head_hexsha": "04651b500055a330b911db4f0af0d82a387393be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/creapairmatrix.cpp", "max_forks_repo_name": "lionking0000/recYnH_Qt", "max_forks_repo_head_hexsha": "04651b500055a330b911db4f0af0d82a387393be", "max_forks_repo_licenses": ["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.2213740458, "max_line_length": 141, "alphanum_fraction": 0.5511777902, "num_tokens": 2006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.611754383422831}}
{"text": "\n// Copyright 2010-2014, D. E. Shaw Research.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt )\n\n#ifndef BOOST_RANDOM_DETAIL_MULHILO_HPP\n#define BOOST_RANDOM_DETAIL_MULHILO_HPP\n\n#include <limits>\n#include <boost/cstdint.hpp>\n#include <boost/integer.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/static_assert.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace detail{\n\n// First, we implement hilo multiplication with \"half words\".  This is\n// the \"reference implementation\" which should be correct for any\n// binary unsigned integral UINT with an even number of bits.  In\n// practice, we try to avoid this implementation because it is so slow\n// (4 multiplies plus about a dozen xor, or, +, shift, mask and\n// compare operations.\ntemplate <typename Uint>\ninline Uint \nmulhilo_halfword(Uint a, Uint b, Uint& hip){ \n    BOOST_STATIC_ASSERT(std::numeric_limits<Uint>::is_specialized &&\n                        std::numeric_limits<Uint>::is_integer &&\n                        !std::numeric_limits<Uint>::is_signed &&\n                        std::numeric_limits<Uint>::radix == 2 &&\n                        std::numeric_limits<Uint>::digits%2 == 0);\n    const unsigned WHALF = std::numeric_limits<Uint>::digits/2;\n    const Uint LOMASK = ((Uint)(~(Uint)0)) >> WHALF;\n    Uint lo = a*b;\n    Uint ahi = a>>WHALF;\n    Uint alo = a& LOMASK;\n    Uint bhi = b>>WHALF;\n    Uint blo = b& LOMASK;\n                                                                   \n    Uint ahbl = ahi*blo;\n    Uint albh = alo*bhi;\n                                                                   \n    Uint ahbl_albh = ((ahbl&LOMASK) + (albh&LOMASK));\n    Uint hi = (ahi*bhi) + (ahbl>>WHALF) +  (albh>>WHALF);\n    hi += ahbl_albh >> WHALF;\n    /* carry from the sum with alo*blo */                               \n    hi += ((lo >> WHALF) < (ahbl_albh&LOMASK));\n    hip = hi;\n    return lo;\n}\n\n// We can formulate a much faster implementation if we can use\n// integers of twice the width of Uint (e.g., DblUint).  Such types\n// are not always available (e.g., when Uint is uintmax_t), but when\n// they are, we find that modern compilers (gcc, MSVC, Intel) pattern\n// match the structure of the mulhilo below and turn it into an\n// optimized instruction sequence, e.g., mulw or mull.\n//\n// However, the alternative implementation, which we want to use\n// when there *is* a DblUint would be ambiguoous without some enable_if\n// hackery.  To support that, we need a has_double_width type trait.\n//\n// N.B.  It should be possible to do this with some SFINAE wrapped\n// around an instantiation of uint_t<2*W>::least.  My attempts to do\n// so ran into the problem described in\n// https://svn.boost.org/trac/boost/ticket/6169 from Nov 23, 2011\n// (still open in April 2014).  So instead just check that twice the\n// number of digits in Uint is less than or equal to the number of\n// digits in uintmax_t.  FWIW, there is currently (as of 1.53)\n// a BOOST_STATIC_ASSERT in integer.hpp that insists on a very\n// similar condition:  Bits <= sizeof(boost::uintmax_t)*CHAR_BIT.\n\ntemplate <typename Uint>\nclass has_double_width{\npublic:\n    static const bool value = std::numeric_limits<Uint>::is_specialized &&\n        std::numeric_limits<Uint>::is_integer &&\n        !std::numeric_limits<Uint>::is_signed &&\n        std::numeric_limits<Uint>::radix == 2 &&\n        2*std::numeric_limits<Uint>::digits <= std::numeric_limits< boost::uintmax_t >::digits;\n};\n\n// mulhilo using double-width DblUint\ntemplate <typename Uint>\ninline typename boost::enable_if_c<has_double_width<Uint>::value, Uint>::type\nmulhilo(Uint a, Uint b, Uint& hip){\n    typedef typename uint_t<2*std::numeric_limits<Uint>::digits>::least DblUint;\n    DblUint product = ((DblUint)a)*((DblUint)b);\n    hip = product>>std::numeric_limits<Uint>::digits;\n    return (Uint)product;\n}\n\n// When there is no DblUint and there are no specializations that use\n// machine-specific intrinsics (below), fall back to mulhilo_halfword.\ntemplate <typename Uint>\ninline typename boost::enable_if_c<!has_double_width<Uint>::value, Uint>::type \nmulhilo(Uint a, Uint b, Uint& hip){\n    return mulhilo_halfword(a, b, hip);\n}\n\n// Every ISA I know (x86, ppc, arm, CUDA) has an instruction that\n// gives the hi word of the product of two uintmax_t's FAR more\n// quickly and succinctly than a call to mulhilo_halfword.  Without\n// them, philox<N, uintmax_t> would be impractically slow.\n// Unfortunately, they require compiler-and-hardware-specific\n// intrinsics or asm statements.\n//\n// FIXME - add more special cases here, e.g., MSVC intrinsics and\n// asm for PowerPC and ARM.\n#if defined(__GNUC__) && defined(__x86_64__)\ntemplate <>\ninline uint64_t \nmulhilo(uint64_t ax, uint64_t b, uint64_t& hip){\n    uint64_t dx;\n    __asm__(\"\\n\\t\"\n        \"mulq %2\\n\\t\"\n        : \"=a\"(ax), \"=d\"(dx)\n        : \"r\"(b), \"0\"(ax)\n        );\n    hip = dx;\n    return ax;\n}\n#endif\n\n} // namespace detail\n} // namespace random\n} // namespace boost\n\n#endif // BOOST_RANDOM_DETAIL_MULHILO_HPP\n", "meta": {"hexsha": "ebee0dbe9182d5ad263200409fa4c8a7a70e9962", "size": 5094, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/random/detail/mulhilo.hpp", "max_stars_repo_name": "DEShawResearch/Random123-Boost", "max_stars_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-04-08T18:40:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T00:08:25.000Z", "max_issues_repo_path": "boost/random/detail/mulhilo.hpp", "max_issues_repo_name": "DEShawResearch/Random123-Boost", "max_issues_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "max_issues_repo_licenses": ["BSL-1.0"], "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/random/detail/mulhilo.hpp", "max_forks_repo_name": "DEShawResearch/Random123-Boost", "max_forks_repo_head_hexsha": "65e3d874b67aa7b3e02d5ad8306462f52d2079c0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T13:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T11:13:12.000Z", "avg_line_length": 38.5909090909, "max_line_length": 95, "alphanum_fraction": 0.6674519042, "num_tokens": 1362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6117144738830975}}
{"text": "/******************************************************************************\n * Copyright (C) 2013 by Jerome Maye                                          *\n * jerome.maye@gmail.com                                                      *\n ******************************************************************************/\n\n#include \"aslam/calibration/functions/IncompleteGammaPFunction.h\"\n\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace aslam {\n  namespace calibration {\n\n/******************************************************************************/\n/* Constructors and Destructor                                                */\n/******************************************************************************/\n\n    IncompleteGammaPFunction::IncompleteGammaPFunction(double alpha) :\n        mAlpha(alpha) {\n    }\n\n    IncompleteGammaPFunction::IncompleteGammaPFunction(const\n        IncompleteGammaPFunction& other) :\n        mAlpha(other.mAlpha) {\n    }\n\n    IncompleteGammaPFunction& IncompleteGammaPFunction::operator = (const\n        IncompleteGammaPFunction& other) {\n      if (this != &other) {\n        mAlpha = other.mAlpha;\n      }\n      return *this;\n    }\n\n    IncompleteGammaPFunction::~IncompleteGammaPFunction() {\n    }\n\n/******************************************************************************/\n/* Stream operations                                                          */\n/******************************************************************************/\n\n    void IncompleteGammaPFunction::read(std::istream& stream) {\n    }\n\n    void IncompleteGammaPFunction::write(std::ostream& stream) const {\n      stream << \"alpha: \" << mAlpha;\n    }\n\n    void IncompleteGammaPFunction::read(std::ifstream& stream) {\n    }\n\n    void IncompleteGammaPFunction::write(std::ofstream& stream) const {\n    }\n\n/******************************************************************************/\n/* Accessors                                                                  */\n/******************************************************************************/\n\n    double IncompleteGammaPFunction::getValue(const VariableType& argument)\n        const {\n      return boost::math::gamma_p(mAlpha, argument);\n    }\n\n    double IncompleteGammaPFunction::getAlpha() const {\n      return mAlpha;\n    }\n\n    void IncompleteGammaPFunction::setAlpha(double alpha) {\n      mAlpha = alpha;\n    }\n\n  }\n}\n", "meta": {"hexsha": "1f375281490a62e2178427b3d4be79df4445e65b", "size": 2407, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental_calibration/src/functions/IncompleteGammaPFunction.cpp", "max_stars_repo_name": "ethz-asl/aslam_incremental_calibration", "max_stars_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-08-23T06:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T16:56:29.000Z", "max_issues_repo_path": "incremental_calibration/src/functions/IncompleteGammaPFunction.cpp", "max_issues_repo_name": "ethz-asl/aslam_incremental_calibration", "max_issues_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:02:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-14T16:02:18.000Z", "max_forks_repo_path": "incremental_calibration/src/functions/IncompleteGammaPFunction.cpp", "max_forks_repo_name": "ethz-asl/aslam_incremental_calibration", "max_forks_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2017-01-23T09:01:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T05:13:23.000Z", "avg_line_length": 32.9726027397, "max_line_length": 80, "alphanum_fraction": 0.4200249273, "num_tokens": 371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545427, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6117144710372254}}
{"text": "// Bring in my package's API, which is what I'm testing\n\n#include <Eigen/Core>\n// Bring in gtest\n#include <gtest/gtest.h>\n#include <boost/cstdint.hpp>\n#include <sm/eigen/gtest.hpp>\n\n#include <sm/eigen/matrix_sqrt.hpp>\n\nTEST(EigenMatrixSqrtTest, testMatrixSqrt) {\n    for (int i = 0; i < 100; ++i) {\n        Eigen::MatrixXd R = sm::eigen::randomCovariance<3>();\n        Eigen::MatrixXd sqrtR;\n        sm::eigen::computeMatrixSqrt(R, sqrtR);\n        Eigen::MatrixXd reconstructedR = sqrtR * sqrtR.transpose();\n        ASSERT_DOUBLE_MX_EQ(R, reconstructedR, 1e-9,\n                            \"Reconstructing the matrix from the square root in iteration \" << i);\n    }\n}\n", "meta": {"hexsha": "d66e76c26b2e257fae26e18877b0c073216d1d8e", "size": 667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_eigen/test/MatrixSqrtTest.cpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Schweizer-Messer/sm_eigen/test/MatrixSqrtTest.cpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Schweizer-Messer/sm_eigen/test/MatrixSqrtTest.cpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7619047619, "max_line_length": 97, "alphanum_fraction": 0.6431784108, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6117144710372254}}
{"text": "/*****************************************************************************\n*   ExploringSfMWithOpenCV\n******************************************************************************\n*   by Roy Shilkrot, 5th Dec 2012\n*   http://www.morethantechnical.com/\n******************************************************************************\n*   Ch4 of the book \"Mastering OpenCV with Practical Computer Vision Projects\"\n*   Copyright Packt Publishing 2012.\n*   http://www.packtpub.com/cool-projects-with-opencv/book\n*****************************************************************************/\n\n#include \"FindCameraMatrices.h\"\n#include \"Triangulation.h\"\n\n#include <vector>\n#include <iostream>\n\n#include <opencv2/calib3d/calib3d.hpp>\n\nusing namespace cv;\nusing namespace std;\n\n#ifdef USE_EIGEN\n#include <Eigen/Eigen>\n#endif\n\n#define DECOMPOSE_SVD\n\n#ifndef CV_PCA_DATA_AS_ROW\n#define CV_PCA_DATA_AS_ROW 0\n#endif\n\nvoid DecomposeEssentialUsingHorn90(double _E[9], double _R1[9], double _R2[9], double _t1[3], double _t2[3]) {\n\t//from : http://people.csail.mit.edu/bkph/articles/Essential.pdf\n#ifdef USE_EIGEN\n\tusing namespace Eigen;\n\n\tMatrix3d E = Map<Matrix<double,3,3,RowMajor> >(_E);\n\tMatrix3d EEt = E * E.transpose();\n\tVector3d e0e1 = E.col(0).cross(E.col(1)),e1e2 = E.col(1).cross(E.col(2)),e2e0 = E.col(2).cross(E.col(2));\n\tVector3d b1,b2;\n\n#if 1\n\t//Method 1\n\tMatrix3d bbt = 0.5 * EEt.trace() * Matrix3d::Identity() - EEt; //Horn90 (12)\n\tVector3d bbt_diag = bbt.diagonal();\n\tif (bbt_diag(0) > bbt_diag(1) && bbt_diag(0) > bbt_diag(2)) {\n\t\tb1 = bbt.row(0) / sqrt(bbt_diag(0));\n\t\tb2 = -b1;\n\t} else if (bbt_diag(1) > bbt_diag(0) && bbt_diag(1) > bbt_diag(2)) {\n\t\tb1 = bbt.row(1) / sqrt(bbt_diag(1));\n\t\tb2 = -b1;\n\t} else {\n\t\tb1 = bbt.row(2) / sqrt(bbt_diag(2));\n\t\tb2 = -b1;\n\t}\n#else\n\t//Method 2\n\tif (e0e1.norm() > e1e2.norm() && e0e1.norm() > e2e0.norm()) {\n\t\tb1 = e0e1.normalized() * sqrt(0.5 * EEt.trace()); //Horn90 (18)\n\t\tb2 = -b1;\n\t} else if (e1e2.norm() > e0e1.norm() && e1e2.norm() > e2e0.norm()) {\n\t\tb1 = e1e2.normalized() * sqrt(0.5 * EEt.trace()); //Horn90 (18)\n\t\tb2 = -b1;\n\t} else {\n\t\tb1 = e2e0.normalized() * sqrt(0.5 * EEt.trace()); //Horn90 (18)\n\t\tb2 = -b1;\n\t}\n#endif\n\t\n\t//Horn90 (19)\n\tMatrix3d cofactors; cofactors.col(0) = e1e2; cofactors.col(1) = e2e0; cofactors.col(2) = e0e1;\n\tcofactors.transposeInPlace();\n\t\n\t//B = [b]_x , see Horn90 (6) and http://en.wikipedia.org/wiki/Cross_product#Conversion_to_matrix_multiplication\n\tMatrix3d B1; B1 <<\t0,-b1(2),b1(1),\n\t\t\t\t\t\tb1(2),0,-b1(0),\n\t\t\t\t\t\t-b1(1),b1(0),0;\n\tMatrix3d B2; B2 <<\t0,-b2(2),b2(1),\n\t\t\t\t\t\tb2(2),0,-b2(0),\n\t\t\t\t\t\t-b2(1),b2(0),0;\n\n\tMap<Matrix<double,3,3,RowMajor> > R1(_R1),R2(_R2);\n\n\t//Horn90 (24)\n\tR1 = (cofactors.transpose() - B1*E) / b1.dot(b1);\n\tR2 = (cofactors.transpose() - B2*E) / b2.dot(b2);\n\tMap<Vector3d> t1(_t1),t2(_t2); \n\tt1 = b1; t2 = b2;\n\t\n\tcout << \"Horn90 provided \" << endl << R1 << endl << \"and\" << endl << R2 << endl;\n#endif\n}\n\nbool CheckCoherentRotation(cv::Mat_<double>& R) {\n\n\t\n\tif(fabsf(determinant(R))-1.0 > 1e-07) {\n\t\tcerr << \"det(R) != +-1.0, this is not a rotation matrix\" << endl;\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nMat GetFundamentalMat(const vector<KeyPoint>& imgpts1,\n\t\t\t\t\t   const vector<KeyPoint>& imgpts2,\n\t\t\t\t\t   vector<KeyPoint>& imgpts1_good,\n\t\t\t\t\t   vector<KeyPoint>& imgpts2_good,\n\t\t\t\t\t   vector<DMatch>& matches\n#ifdef __SFM__DEBUG__\n\t\t\t\t\t  ,const Mat& img_1,\n\t\t\t\t\t  const Mat& img_2\n#endif\n\t\t\t\t\t  ) \n{\n\t//Try to eliminate keypoints based on the fundamental matrix\n\t//(although this is not the proper way to do this)\n\tvector<uchar> status(imgpts1.size());\n\t\n#ifdef __SFM__DEBUG__\n\tstd::vector< DMatch > good_matches_;\n\tstd::vector<KeyPoint> keypoints_1, keypoints_2;\n#endif\t\t\n\t//\tundistortPoints(imgpts1, imgpts1, cam_matrix, distortion_coeff);\n\t//\tundistortPoints(imgpts2, imgpts2, cam_matrix, distortion_coeff);\n\t//\n\timgpts1_good.clear(); imgpts2_good.clear();\n\t\n\tvector<KeyPoint> imgpts1_tmp;\n\tvector<KeyPoint> imgpts2_tmp;\n\tif (matches.size() <= 0) { \n\t\t//points already aligned...\n\t\timgpts1_tmp = imgpts1;\n\t\timgpts2_tmp = imgpts2;\n\t} else {\n\t\tGetAlignedPointsFromMatch(imgpts1, imgpts2, matches, imgpts1_tmp, imgpts2_tmp);\n\t}\n\t\n\tMat F;\n\t{\n\t\tvector<Point2f> pts1,pts2;\n\t\tKeyPointsToPoints(imgpts1_tmp, pts1);\n\t\tKeyPointsToPoints(imgpts2_tmp, pts2);\n#ifdef __SFM__DEBUG__\n\t\tcout << \"pts1 \" << pts1.size() << \" (orig pts \" << imgpts1_tmp.size() << \")\" << endl;\n\t\tcout << \"pts2 \" << pts2.size() << \" (orig pts \" << imgpts2_tmp.size() << \")\" << endl;\n#endif\n\t\tdouble minVal,maxVal;\n\t\tcv::minMaxIdx(pts1,&minVal,&maxVal);\n\t\tF = findFundamentalMat(pts1, pts2, FM_RANSAC, 0.006 * maxVal, 0.99, status); //threshold from [Snavely07 4.1]\n\t}\n\t\n\tvector<DMatch> new_matches;\n\tcout << \"F keeping \" << countNonZero(status) << \" / \" << status.size() << endl;\t\n\tfor (unsigned int i=0; i<status.size(); i++) {\n\t\tif (status[i]) \n\t\t{\n\t\t\timgpts1_good.push_back(imgpts1_tmp[i]);\n\t\t\timgpts2_good.push_back(imgpts2_tmp[i]);\n\n\t\t\tif (matches.size() <= 0) { //points already aligned...\n\t\t\t\tnew_matches.push_back(DMatch(matches[i].queryIdx,matches[i].trainIdx,matches[i].distance));\n\t\t\t} else {\n\t\t\t\tnew_matches.push_back(matches[i]);\n\t\t\t}\n\n#ifdef __SFM__DEBUG__\n\t\t\tgood_matches_.push_back(DMatch(imgpts1_good.size()-1,imgpts1_good.size()-1,1.0));\n\t\t\tkeypoints_1.push_back(imgpts1_tmp[i]);\n\t\t\tkeypoints_2.push_back(imgpts2_tmp[i]);\n#endif\n\t\t}\n\t}\t\n\t\n\tcout << matches.size() << \" matches before, \" << new_matches.size() << \" new matches after Fundamental Matrix\\n\";\n\tmatches = new_matches; //keep only those points who survived the fundamental matrix\n\t\n#if 0\n\t//-- Draw only \"good\" matches\n#ifdef __SFM__DEBUG__\n\tif(!img_1.empty() && !img_2.empty()) {\t\t\n\t\tvector<Point2f> i_pts,j_pts;\n\t\tMat img_orig_matches;\n\t\t{ //draw original features in red\n\t\t\tvector<uchar> vstatus(imgpts1_tmp.size(),1);\n\t\t\tvector<float> verror(imgpts1_tmp.size(),1.0);\n\t\t\timg_1.copyTo(img_orig_matches);\n\t\t\tKeyPointsToPoints(imgpts1_tmp, i_pts);\n\t\t\tKeyPointsToPoints(imgpts2_tmp, j_pts);\n\t\t\tdrawArrows(img_orig_matches, i_pts, j_pts, vstatus, verror, Scalar(0,0,255));\n\t\t}\n\t\t{ //superimpose filtered features in green\n\t\t\tvector<uchar> vstatus(imgpts1_good.size(),1);\n\t\t\tvector<float> verror(imgpts1_good.size(),1.0);\n\t\t\ti_pts.resize(imgpts1_good.size());\n\t\t\tj_pts.resize(imgpts2_good.size());\n\t\t\tKeyPointsToPoints(imgpts1_good, i_pts);\n\t\t\tKeyPointsToPoints(imgpts2_good, j_pts);\n\t\t\tdrawArrows(img_orig_matches, i_pts, j_pts, vstatus, verror, Scalar(0,255,0));\n\t\t\timshow( \"Filtered Matches\", img_orig_matches );\n\t\t}\n\t\tint c = waitKey(0);\n\t\tif (c=='s') {\n\t\t\timwrite(\"fundamental_mat_matches.png\", img_orig_matches);\n\t\t}\n\t\tdestroyWindow(\"Filtered Matches\");\n\t}\n#endif\t\t\n#endif\n\t\n\treturn F;\n}\n\nvoid TakeSVDOfE(Mat_<double>& E, Mat& svd_u, Mat& svd_vt, Mat& svd_w) {\n#if 1\n\t//Using OpenCV's SVD\n\tSVD svd(E,SVD::MODIFY_A);\n\tsvd_u = svd.u;\n\tsvd_vt = svd.vt;\n\tsvd_w = svd.w;\n#else\n\t//Using Eigen's SVD\n\tcout << \"Eigen3 SVD..\\n\";\n\tEigen::Matrix3f  e = Eigen::Map<Eigen::Matrix<double,3,3,Eigen::RowMajor> >((double*)E.data).cast<float>();\n\tEigen::JacobiSVD<Eigen::MatrixXf> svd(e, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\tEigen::MatrixXf Esvd_u = svd.matrixU();\n\tEigen::MatrixXf Esvd_v = svd.matrixV();\n\tsvd_u = (Mat_<double>(3,3) << Esvd_u(0,0), Esvd_u(0,1), Esvd_u(0,2),\n\t\t\t\t\t\t  Esvd_u(1,0), Esvd_u(1,1), Esvd_u(1,2), \n\t\t\t\t\t\t  Esvd_u(2,0), Esvd_u(2,1), Esvd_u(2,2)); \n\tMat_<double> svd_v = (Mat_<double>(3,3) << Esvd_v(0,0), Esvd_v(0,1), Esvd_v(0,2),\n\t\t\t\t\t\t  Esvd_v(1,0), Esvd_v(1,1), Esvd_v(1,2), \n\t\t\t\t\t\t  Esvd_v(2,0), Esvd_v(2,1), Esvd_v(2,2));\n\tsvd_vt = svd_v.t();\n\tsvd_w = (Mat_<double>(1,3) << svd.singularValues()[0] , svd.singularValues()[1] , svd.singularValues()[2]);\n#endif\n\t\n\tcout << \"----------------------- SVD ------------------------\\n\";\n\tcout << \"U:\\n\"<<svd_u<<\"\\nW:\\n\"<<svd_w<<\"\\nVt:\\n\"<<svd_vt<<endl;\n\tcout << \"----------------------------------------------------\\n\";\n}\n\nbool TestTriangulation(const vector<CloudPoint>& pcloud, const Matx34d& P, vector<uchar>& status) {\n\tvector<Point3d> pcloud_pt3d = CloudPointsToPoints(pcloud);\n\tvector<Point3d> pcloud_pt3d_projected(pcloud_pt3d.size());\n\t\n\tMatx44d P4x4 = Matx44d::eye(); \n\tfor(int i=0;i<12;i++) P4x4.val[i] = P.val[i];\n\t\n\tperspectiveTransform(pcloud_pt3d, pcloud_pt3d_projected, P4x4);\n\t\n\tstatus.resize(pcloud.size(),0);\n\tfor (int i=0; i<pcloud.size(); i++) {\n\t\tstatus[i] = (pcloud_pt3d_projected[i].z > 0) ? 1 : 0;\n\t}\n\tint count = countNonZero(status);\n\n\tdouble percentage = ((double)count / (double)pcloud.size());\n\tcout << count << \"/\" << pcloud.size() << \" = \" << percentage*100.0 << \"% are in front of camera\" << endl;\n\tif(percentage < 0.75)\n\t\treturn false; //less than 75% of the points are in front of the camera\n\n\t//check for coplanarity of points\n\tif(false) //not\n\t{\n\t\tcv::Mat_<double> cldm(pcloud.size(),3);\n\t\tfor(unsigned int i=0;i<pcloud.size();i++) {\n\t\t\tcldm.row(i)(0) = pcloud[i].pt.x;\n\t\t\tcldm.row(i)(1) = pcloud[i].pt.y;\n\t\t\tcldm.row(i)(2) = pcloud[i].pt.z;\n\t\t}\n\t\tcv::Mat_<double> mean;\n\t\tcv::PCA pca(cldm,mean,CV_PCA_DATA_AS_ROW);\n\n\t\tint num_inliers = 0;\n\t\tcv::Vec3d nrm = pca.eigenvectors.row(2); nrm = nrm / norm(nrm);\n\t\tcv::Vec3d x0 = pca.mean;\n\t\tdouble p_to_plane_thresh = sqrt(pca.eigenvalues.at<double>(2));\n\n\t\tfor (int i=0; i<pcloud.size(); i++) {\n\t\t\tVec3d w = Vec3d(pcloud[i].pt) - x0;\n\t\t\tdouble D = fabs(nrm.dot(w));\n\t\t\tif(D < p_to_plane_thresh) num_inliers++;\n\t\t}\n\n\t\tcout << num_inliers << \"/\" << pcloud.size() << \" are coplanar\" << endl;\n\t\tif((double)num_inliers / (double)(pcloud.size()) > 0.85)\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool DecomposeEtoRandT(\n\tMat_<double>& E,\n\tMat_<double>& R1,\n\tMat_<double>& R2,\n\tMat_<double>& t1,\n\tMat_<double>& t2) \n{\n#ifdef DECOMPOSE_SVD\n\t//Using HZ E decomposition\n\tMat svd_u, svd_vt, svd_w;\n\tTakeSVDOfE(E,svd_u,svd_vt,svd_w);\n\n\t//check if first and second singular values are the same (as they should be)\n\tdouble singular_values_ratio = fabsf(svd_w.at<double>(0) / svd_w.at<double>(1));\n\tif(singular_values_ratio>1.0) singular_values_ratio = 1.0/singular_values_ratio; // flip ratio to keep it [0,1]\n\tif (singular_values_ratio < 0.7) {\n\t\tcout << \"singular values are too far apart\\n\";\n\t\treturn false;\n\t}\n\n\tMatx33d W(0,-1,0,\t//HZ 9.13\n\t\t1,0,0,\n\t\t0,0,1);\n\tMatx33d Wt(0,1,0,\n\t\t-1,0,0,\n\t\t0,0,1);\n\tR1 = svd_u * Mat(W) * svd_vt; //HZ 9.19\n\tR2 = svd_u * Mat(Wt) * svd_vt; //HZ 9.19\n\tt1 = svd_u.col(2); //u3\n\tt2 = -svd_u.col(2); //u3\n#else\n\t//Using Horn E decomposition\n\tDecomposeEssentialUsingHorn90(E[0],R1[0],R2[0],t1[0],t2[0]);\n#endif\n\treturn true;\n}\n\nbool FindCameraMatrices(const Mat& K, \n\t\t\t\t\t\tconst Mat& Kinv, \n\t\t\t\t\t\tconst Mat& distcoeff,\n\t\t\t\t\t\tconst vector<KeyPoint>& imgpts1,\n\t\t\t\t\t\tconst vector<KeyPoint>& imgpts2,\n\t\t\t\t\t\tvector<KeyPoint>& imgpts1_good,\n\t\t\t\t\t\tvector<KeyPoint>& imgpts2_good,\n\t\t\t\t\t\tMatx34d& P,\n\t\t\t\t\t\tMatx34d& P1,\n\t\t\t\t\t\tvector<DMatch>& matches,\n\t\t\t\t\t\tvector<CloudPoint>& outCloud\n#ifdef __SFM__DEBUG__\n\t\t\t\t\t\t,const Mat& img_1,\n\t\t\t\t\t\tconst Mat& img_2\n#endif\n\t\t\t\t\t\t) \n{\n\t//Find camera matrices\n\t{\n\t\tcout << \"Find camera matrices...\";\n\t\tdouble t = getTickCount();\n\t\t\n\t\tMat F = GetFundamentalMat(imgpts1,imgpts2,imgpts1_good,imgpts2_good,matches\n#ifdef __SFM__DEBUG__\n\t\t\t\t\t\t\t\t  ,img_1,img_2\n#endif\n\t\t\t\t\t\t\t\t  );\n\t\tif(matches.size() < 100) { // || ((double)imgpts1_good.size() / (double)imgpts1.size()) < 0.25\n\t\t\tcerr << \"not enough inliers after F matrix\" << endl;\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t//Essential matrix: compute then extract cameras [R|t]\n\t\tMat_<double> E = K.t() * F * K; //according to HZ (9.12)\n\n\t\t//according to http://en.wikipedia.org/wiki/Essential_matrix#Properties_of_the_essential_matrix\n\t\tif(fabsf(determinant(E)) > 1e-07) {\n\t\t\tcout << \"det(E) != 0 : \" << determinant(E) << \"\\n\";\n\t\t\tP1 = 0;\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tMat_<double> R1(3,3);\n\t\tMat_<double> R2(3,3);\n\t\tMat_<double> t1(1,3);\n\t\tMat_<double> t2(1,3);\n\n\t\t//decompose E to P' , HZ (9.19)\n\t\t{\t\t\t\n\t\t\tif (!DecomposeEtoRandT(E,R1,R2,t1,t2)) return false;\n\n\t\t\tif(determinant(R1)+1.0 < 1e-09) {\n\t\t\t\t//according to http://en.wikipedia.org/wiki/Essential_matrix#Showing_that_it_is_valid\n\t\t\t\tcout << \"det(R) == -1 [\"<<determinant(R1)<<\"]: flip E's sign\" << endl;\n\t\t\t\tE = -E;\n\t\t\t\tDecomposeEtoRandT(E,R1,R2,t1,t2);\n\t\t\t}\n\t\t\tif (!CheckCoherentRotation(R1)) {\n\t\t\t\tcout << \"resulting rotation is not coherent\\n\";\n\t\t\t\tP1 = 0;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tP1 = Matx34d(R1(0,0),\tR1(0,1),\tR1(0,2),\tt1(0),\n\t\t\t\t\t\t R1(1,0),\tR1(1,1),\tR1(1,2),\tt1(1),\n\t\t\t\t\t\t R1(2,0),\tR1(2,1),\tR1(2,2),\tt1(2));\n\t\t\tcout << \"Testing P1 \" << endl << Mat(P1) << endl;\n\t\t\t\n\t\t\tvector<CloudPoint> pcloud,pcloud1; vector<KeyPoint> corresp;\n\t\t\tdouble reproj_error1 = TriangulatePoints(imgpts1_good, imgpts2_good, K, Kinv, distcoeff, P, P1, pcloud, corresp);\n\t\t\tdouble reproj_error2 = TriangulatePoints(imgpts2_good, imgpts1_good, K, Kinv, distcoeff, P1, P, pcloud1, corresp);\n\t\t\tvector<uchar> tmp_status;\n\t\t\t//check if pointa are triangulated --in front-- of cameras for all 4 ambiguations\n\t\t\tif (!TestTriangulation(pcloud,P1,tmp_status) || !TestTriangulation(pcloud1,P,tmp_status) || reproj_error1 > 100.0 || reproj_error2 > 100.0) {\n\t\t\t\tP1 = Matx34d(R1(0,0),\tR1(0,1),\tR1(0,2),\tt2(0),\n\t\t\t\t\t\t\t R1(1,0),\tR1(1,1),\tR1(1,2),\tt2(1),\n\t\t\t\t\t\t\t R1(2,0),\tR1(2,1),\tR1(2,2),\tt2(2));\n\t\t\t\tcout << \"Testing P1 \"<< endl << Mat(P1) << endl;\n\n\t\t\t\tpcloud.clear(); pcloud1.clear(); corresp.clear();\n\t\t\t\treproj_error1 = TriangulatePoints(imgpts1_good, imgpts2_good, K, Kinv, distcoeff, P, P1, pcloud, corresp);\n\t\t\t\treproj_error2 = TriangulatePoints(imgpts2_good, imgpts1_good, K, Kinv, distcoeff, P1, P, pcloud1, corresp);\n\t\t\t\t\n\t\t\t\tif (!TestTriangulation(pcloud,P1,tmp_status) || !TestTriangulation(pcloud1,P,tmp_status) || reproj_error1 > 100.0 || reproj_error2 > 100.0) {\n\t\t\t\t\tif (!CheckCoherentRotation(R2)) {\n\t\t\t\t\t\tcout << \"resulting rotation is not coherent\\n\";\n\t\t\t\t\t\tP1 = 0;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tP1 = Matx34d(R2(0,0),\tR2(0,1),\tR2(0,2),\tt1(0),\n\t\t\t\t\t\t\t\t R2(1,0),\tR2(1,1),\tR2(1,2),\tt1(1),\n\t\t\t\t\t\t\t\t R2(2,0),\tR2(2,1),\tR2(2,2),\tt1(2));\n\t\t\t\t\tcout << \"Testing P1 \"<< endl << Mat(P1) << endl;\n\n\t\t\t\t\tpcloud.clear(); pcloud1.clear(); corresp.clear();\n\t\t\t\t\treproj_error1 = TriangulatePoints(imgpts1_good, imgpts2_good, K, Kinv, distcoeff, P, P1, pcloud, corresp);\n\t\t\t\t\treproj_error2 = TriangulatePoints(imgpts2_good, imgpts1_good, K, Kinv, distcoeff, P1, P, pcloud1, corresp);\n\t\t\t\t\t\n\t\t\t\t\tif (!TestTriangulation(pcloud,P1,tmp_status) || !TestTriangulation(pcloud1,P,tmp_status) || reproj_error1 > 100.0 || reproj_error2 > 100.0) {\n\t\t\t\t\t\tP1 = Matx34d(R2(0,0),\tR2(0,1),\tR2(0,2),\tt2(0),\n\t\t\t\t\t\t\t\t\t R2(1,0),\tR2(1,1),\tR2(1,2),\tt2(1),\n\t\t\t\t\t\t\t\t\t R2(2,0),\tR2(2,1),\tR2(2,2),\tt2(2));\n\t\t\t\t\t\tcout << \"Testing P1 \"<< endl << Mat(P1) << endl;\n\n\t\t\t\t\t\tpcloud.clear(); pcloud1.clear(); corresp.clear();\n\t\t\t\t\t\treproj_error1 = TriangulatePoints(imgpts1_good, imgpts2_good, K, Kinv, distcoeff, P, P1, pcloud, corresp);\n\t\t\t\t\t\treproj_error2 = TriangulatePoints(imgpts2_good, imgpts1_good, K, Kinv, distcoeff, P1, P, pcloud1, corresp);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!TestTriangulation(pcloud,P1,tmp_status) || !TestTriangulation(pcloud1,P,tmp_status) || reproj_error1 > 100.0 || reproj_error2 > 100.0) {\n\t\t\t\t\t\t\tcout << \"Shit.\" << endl; \n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\t\t\t\n\t\t\t}\n\t\t\tfor (unsigned int i=0; i<pcloud.size(); i++) {\n\t\t\t\toutCloud.push_back(pcloud[i]);\n\t\t\t}\n\t\t}\t\t\n\t\t\n\t\tt = ((double)getTickCount() - t)/getTickFrequency();\n\t\tcout << \"Done. (\" << t <<\"s)\"<< endl;\n\t}\n\treturn true;\n}\n", "meta": {"hexsha": "2e60c06e324f7a84c30b06799f588333ba82dca5", "size": 15282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Chapter4_StructureFromMotion/FindCameraMatrices.cpp", "max_stars_repo_name": "nic-c-cc-txt/code-master", "max_stars_repo_head_hexsha": "97f4f1da5f27b2af4d2faee51436ecdaef662a24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2017-05-16T02:28:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T14:03:53.000Z", "max_issues_repo_path": "Chapter4_StructureFromMotion/FindCameraMatrices.cpp", "max_issues_repo_name": "nic-c-cc-txt/code-master", "max_issues_repo_head_hexsha": "97f4f1da5f27b2af4d2faee51436ecdaef662a24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-05-18T19:11:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-05T08:59:25.000Z", "max_forks_repo_path": "Chapter02/FindCameraMatrices.cpp", "max_forks_repo_name": "Pandinosaurus/Mastering-OpenCV3-Second-Edition", "max_forks_repo_head_hexsha": "3347366025d7551f42eb55940aac629629000d42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2017-05-21T17:59:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-22T22:20:22.000Z", "avg_line_length": 33.3668122271, "max_line_length": 147, "alphanum_fraction": 0.6253762597, "num_tokens": 5445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6117144653454809}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// distribution::toolkit::example::location_scale.cpp                        //\n//                                                                          //\n//  (C) Copyright 2009 Erwann Rogard                                        //\n//  Use, modification and distribution are subject to the                   //\n//  Boost Software License, Version 1.0. (See accompanying file             //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)        //\n//////////////////////////////////////////////////////////////////////////////\n#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <numeric>\n#include <cmath>\n#include <string>\n#include <stdexcept>\n#include <limits>\n\n#include <boost/mpl/apply.hpp>\n#include <boost/bind.hpp>\n#include <boost/function.hpp>\n#include <boost/range.hpp>\n\n#include <boost/math/tools/precision.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\n#include <boost/statistics/detail/distribution_common/functor/log_unnormalized_pdf.hpp>\n#include <boost/statistics/detail/distribution_common/distributions/reference/wrapper.hpp>\n\n#include <boost/statistics/detail/distribution_toolkit/meta/include.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/students_t/include.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/location_scale/include.hpp>\n#include <boost/statistics/detail/distribution_toolkit/map_pdf/include.hpp>\n\n#include <libs/statistics/detail/distribution_toolkit/example/distribution_function.h>\n\nvoid example_distribution_function(std::ostream& out){\n\n        out << \"-> example_distribution_function\" << std::endl;\n\n        using namespace boost;\n        using namespace math;\n        using namespace statistics::detail;\n        namespace dist = distribution;\n\n        // Types\n        typedef double                                          \tval_;\n        typedef boost::mt19937                                  \turng_;\n        typedef boost::normal_distribution<val_>                \trnd_;\n        typedef math::students_t_distribution<val_>             \tstud_;\n        typedef dist::toolkit::location_scale_distribution<stud_>   ls_stud_;\n        typedef boost::variate_generator<urng_&,rnd_>           \tvg_;\n        typedef boost::numeric::bounds<val_> \t\t\t\t\t\tbounds_;\n\n        // Constants\n        const unsigned df   = 10;\n        const val_ mu       = 10;\n        const val_ sigma    = 2;\n        const val_ x        = 2.132;\n\n        // Initialization\n        urng_ urng;\n        \n        stud_ stud(df);\n        ls_stud_ ls_stud(mu, sigma, stud);\n\n\t\tout << \"testing error handling : \" << std::endl;\n\n        try{   \n        \tstatic const val_ inf = std::numeric_limits<val_>::infinity();\n\t\t\tls_stud_ ls_stud(inf,sigma,stud);\n        }catch(std::exception& e){\n        \tout << e.what() << std::endl;\n\t\t}\n\n\t\ttry{\n\t\t\tls_stud_(mu,-1.0,stud);\n        }catch(std::exception& e){\n        \tout << e.what() << std::endl;\n        }\n\n        struct float_{\n            \n            static bool equal(const val_& a, const val_& b){\n                static val_ e = boost::math::tools::epsilon<val_>();;\n                return fabs(a-b)< e;\n            }\n        \n        };\n        {   // product_pdf\n            typedef dist::toolkit::product_pdf<stud_,ls_stud_>     prod_dist_;\n            prod_dist_ prod_dist(stud,ls_stud);\n            prod_dist_ prod_dist2(stud,ls_stud);\n            prod_dist = prod_dist2; // check assignment\n            BOOST_ASSERT(\n                float_::equal(\n                    log_unnormalized_pdf(prod_dist,x),\n                    log_unnormalized_pdf(prod_dist2,x)\n                )\n            );\n            BOOST_ASSERT(\n                float_::equal(\n                    log_unnormalized_pdf(prod_dist.first(),x)\n                     + log_unnormalized_pdf(prod_dist.second(),x),\n                    log_unnormalized_pdf(prod_dist,x)\n                )\n            );\n\n        }\n        {   // inverse_pdf\n            typedef dist::toolkit::inverse_pdf<stud_> inv_dist_;\n            inv_dist_ inv_dist(stud);\n            BOOST_ASSERT(\n                float_::equal(\n                    -log_unnormalized_pdf(inv_dist.distribution(),x),\n                    log_unnormalized_pdf(inv_dist,x)\n                )\n            );\n        }\n        {   // ratio_pdf + fun_wrap\n            typedef dist::toolkit::meta_ratio_pdf<stud_,ls_stud_>  \tmf_;\n            typedef mf_::type ratio_dist_;\n            ratio_dist_ ratio_dist = mf_::call(stud,ls_stud);\n            BOOST_ASSERT(\n                float_::equal(\n                    // + sign because inherits from inverse\n                    log_unnormalized_pdf(ratio_dist.first(),x)\n                        + log_unnormalized_pdf(ratio_dist.second(),x),\n                    log_unnormalized_pdf(ratio_dist,x)\n                )\n            );\n        }\n    out << \"<-\" << std::endl;\n}\n", "meta": {"hexsha": "18e1030701a9b0cab4d24e7db35188e062cd0818", "size": 5056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "distribution_toolkit/libs/statistics/detail/distribution_toolkit/example/distribution_function.cpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distribution_toolkit/libs/statistics/detail/distribution_toolkit/example/distribution_function.cpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distribution_toolkit/libs/statistics/detail/distribution_toolkit/example/distribution_function.cpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1764705882, "max_line_length": 96, "alphanum_fraction": 0.5476661392, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764119, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6117144624996086}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <boost/config.hpp>\n#include <iostream>\n#include <vector>\n#include <utility>\n\n#include <boost/graph/adjacency_list.hpp>\n\n/*\n  Sample Output\n\n  0 <--\n  1 <-- 0\n  2 <-- 1\n  3 <-- 1\n  4 <-- 2  3\n\n */\n\nint main(int , char* [])\n{\n  using namespace boost;\n  using namespace std;\n  using namespace boost;\n\n  typedef adjacency_list<listS,vecS,bidirectionalS> Graph;\n  const int num_vertices = 5;\n  Graph g(num_vertices);\n\n  add_edge(0, 1, g);\n  add_edge(1, 2, g);\n  add_edge(1, 3, g);\n  add_edge(2, 4, g);\n  add_edge(3, 4, g);\n\n  boost::graph_traits<Graph>::vertex_iterator i, end;\n  boost::graph_traits<Graph>::in_edge_iterator ei, edge_end;\n\n  for(boost::tie(i,end) = vertices(g); i != end; ++i) {\n    cout << *i << \" <-- \";\n    for (boost::tie(ei,edge_end) = in_edges(*i, g); ei != edge_end; ++ei)\n      cout << source(*ei, g) << \"  \";\n    cout << endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "a06de4207183132091ea6c6b15a22d43ec1546d7", "size": 1303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/in_edges.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/in_edges.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/in_edges.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": 24.1296296296, "max_line_length": 73, "alphanum_fraction": 0.5617805065, "num_tokens": 384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6116454568745181}}
{"text": "/*\n * Bayes++ the Bayesian Filtering Library\n * Copyright (c) 2002 Michael Stevens\n * See accompanying Bayes++.htm for terms and conditions of use.\n *\n * $Id$\n */\n\n/*\n * Implement a NON-LINEAR range angle observer for many filter schemes\n * The model parameters allow model sizes and the non-linearity.\n * This provides an excellent vehicle to test each scheme. Use for regression testing\n */\n\n#include \"BayesFilter/allFilters.hpp\"\n#include \"BayesFilter/schemeFlt.hpp\"\n#include \"Test/random.hpp\"\n#include \"angle.hpp\"\n#include <cmath>\n#include <iostream>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/format.hpp>\n#include <boost/limits.hpp>\n\n\nusing namespace Bayesian_filter;\nusing namespace Bayesian_filter_matrix;\nusing namespace angleArith;\n\n\nconst std::size_t NX = 2+1;\t\t\t// State dimension (x,y) and some more to show noise coupling or singular X\nconst std::size_t NQ = 2;\t\t\t// State dimension of noise\nconst std::size_t NZ = 2+2;\t\t\t// Observation dimension (r,a) and some empty dummies\nconst std::size_t NS = 1000;\t\t\t// Number of samples for a sampled representation\n\nconst bool RA_MODEL = true;\t\t// Use Range angle NON-linear model (requires normalising angle)\nconst bool NOISE_MODEL = true;\t\t// Add noise to truth model\nconst bool TRUTH_STATIONARY = false;// Truth model setup\nconst Float INIT_XY[2] = {1.,-0.2};\t// XY initial position\nconst Float TARGET[2] = {-11.,0.};\t// XY position of target\n\nconst Float RANGE_NOISE = NOISE_MODEL ? Float(0.1) : Float(1e-6);\nconst Float ANGLE_NOISE = NOISE_MODEL ? Float(5. * angle<Float>::Deg2Rad) : Float(1e-6);\nconst Float Z_CORRELATION = Float(0e-1);\t// (Un)Correlated observation model\n\nconst Float X_NOISE = Float(0.05);\t\t// predict model\nconst Float Y_NOISE = Float(0.09);\nconst Float XY_NOISE_COUPLING = Float(0.05);\nconst Float Q_NOISE = Float(1.0);\t\t// Noise in addition Q terms\nconst Float G_COUPLING = Float(1.0);\t// Coupling in addition G terms\n\nconst Float INIT_X_NOISE = Float(0.07);\nconst Float INIT_Y_NOISE = Float(0.10);\nconst Float INIT_XY_NOISE_CORRELATION = Float(0.4);\nconst Float INIT_2_NOISE = Float(0.09);\t// Use zero for singular X\t\nconst Float INIT_2_NOISE_CORRELATION = Float(0.5);\n\n\n// Square \ntemplate <class scalar>\ninline scalar sqr(scalar x)\n{\n\treturn x*x;\n}\n\nclass Rtheta_random : public Bayesian_filter_test::Boost_random, public SIR_random\n/*\n * Random numbers for filters from Boost\n */\n{\npublic:\n\tFloat normal (const Float mean, const Float sigma)\n\t{\n\t\tFloat f = Boost_random::normal (mean, sigma);\n\t\treturn f;\n\t}\n\tvoid normal (DenseVec& v)\n\t{\n\t\tBoost_random::normal (v);\n\t}\n\tvoid uniform_01 (DenseVec& v)\n\t{\n\t\tBoost_random::uniform_01 (v);\n\t}\n} Random, Random2;\n\n\n/*\n * Linear predict model\n *  x static and y tending to x\n *  Correlated additive noise\n */\nclass pred_model : public Sampled_LiInAd_predict_model\n{\npublic:\n\tpred_model();\n};\n\n\npred_model::pred_model () :\n\tSampled_LiInAd_predict_model(NX,NQ, Random2)\n// Construct constant model\n{\n\t// Build Fx, Identity all except active partition\n\tFM::identity (Fx);\n\tFx(0,0) = Float(1);\n\tFx(0,1) = Float(0);\n\tFx(1,0) = Float(0.1);\n\tFx(1,1) = Float(0.9);\n\n\t// Build q,G, Test addition parts using coupled noise\n\tq = ublas::scalar_vector<Float>(NQ, Q_NOISE);\n\tq[0] = sqr(X_NOISE);\n\tq[1] = sqr(Y_NOISE);\n\tG = ublas::scalar_matrix<Float>(NX,NQ, G_COUPLING);\n\tG(0,0) = 1;\n\tG(0,1) = XY_NOISE_COUPLING;\n\tG(1,0) = XY_NOISE_COUPLING;\n\tG(1,1) = 1;\n\n\t// Build inverse Fx, Identity all except active partition\n\tDenseColMatrix denseinvFx (Fx.size1(), Fx.size2());\n\tInformation_root_scheme::inverse_Fx (denseinvFx, Fx);\n\tinv.Fx = denseinvFx;\n}\n\n\n/*\n * Observation model: gradient linearised versions\n *  Linearisation state must be set before use\n *  Both uncorrelated and correlated representation\n *  Correlated representation is just the uncorrelated adapted so the\n *  correlation term are added.\n */\n#ifndef MODEL_LINEAR\n\ttypedef General_LzUnAd_observe_model Observe_un_special;\n\ttypedef General_LzCoAd_observe_model Observe_co_special;\n#else\n\ttypedef General_LiUnAd_observe_model Observe_un_special;\n\ttypedef General_LiCoAd_observe_model Observe_co_special;\n#endif\n\nclass uobs_model : public Observe_un_special\n{\npublic:\n\tuobs_model();\n\tconst Vec& h(const Vec& x) const;\n\tvoid normalise (Vec& z_denorm, const Vec& z_from) const;\n\tvoid state (const Vec& x);\nprivate:\n\tmutable Vec z_pred;\n};\n\nclass cobs_model : public Observe_co_special\n{\npublic:\n\tcobs_model(uobs_model& u);\n\tconst Vec& h(const Vec& x) const;\n\tvoid normalise (Vec& z_denorm, const Vec& z_from) const;\n\tvoid state (const Vec& x);\nprivate:\n\tuobs_model& uobs;\n};\n\nuobs_model::uobs_model() :\n\tObserve_un_special(NX,NZ),\n\tz_pred(NZ)\n{\n\t// Observation covariance uncorrelated\n\tZv = ublas::scalar_vector<Float>(Zv.size(), Float(1));\n\tZv[0] = sqr(RANGE_NOISE);\n\tZv[1] = (RA_MODEL ? sqr(ANGLE_NOISE): sqr(RANGE_NOISE));\n}\n\ncobs_model::cobs_model(uobs_model& u) :\n\tObserve_co_special(NX,NZ),\n\tuobs(u)\n{\n\tFM::identity (Z);\n\t// Create the correlation in Z\n\tZ(0,0) = Float(uobs.Zv[0]); Z(1,1) = Float(uobs.Zv[1]);\t// ISSUE mixed type proxy assignment\n\tZ(1,0) = Float(Z(0,1) = sqrt(Z(0,0))*sqrt(Z(1,1))*Z_CORRELATION);\n}\n\nvoid uobs_model::state (const Vec& x)\n{\n\tFloat dx = TARGET[0] - x[0];\n\tFloat dy = TARGET[1] - x[1];\n\n\tHx.clear();\n\tif (RA_MODEL) {\n\t\tFloat distSq = dx*dx + dy*dy;\n\t\tFloat dist = sqrt (distSq);\n\t\tHx(0,0) = -dx / dist;\n\t\tHx(0,1) = -dy / dist;\n\t\tHx(1,0) = +dy / distSq;\n\t\tHx(1,1) = -dx / distSq;\n\t}\n\telse {\n\t\tHx(0,0) = -1;\n\t\tHx(0,1) = 0;\n\t\tHx(1,0) = 0;\n\t\tHx(1,1) = -1;\n\t}\n}\n\nvoid cobs_model::state (const FM::Vec& x)\n{\n\tuobs.state (x);\n\tHx = uobs.Hx;\n}\n\nconst Vec& uobs_model::h (const Vec& x) const\n{\n\tFloat dx = TARGET[0] - x[0];\n\tFloat dy = TARGET[1] - x[1];\n\n\tz_pred.clear();\n\tif (RA_MODEL) {\n\t\tFloat distSq = dx*dx + dy*dy;\n\t\tFloat dist = sqrt (distSq);\n\n\t\tz_pred[0] = dist;\n\t\tz_pred[1] = std::atan2 (dy, dx);\n\t}\n\telse {\n\t\tz_pred[0] = dx;\n\t\tz_pred[1] = dy;\n\t}\n\treturn z_pred;\n}\n\nconst Vec& cobs_model::h (const Vec& x) const\n{\n\treturn uobs.h(x);\n}\n\nvoid uobs_model::normalise (Vec& z_denorm, const Vec& z_from) const\n{\n\tif (RA_MODEL) {\n\t\tz_denorm[1] = angle<Float>(z_denorm[1]).from (z_from[1]);\n\t}\n}\n\nvoid cobs_model::normalise (Vec& z_denorm, const Vec& z_from) const\n{\n\tuobs.normalise(z_denorm, z_from);\n}\n\n/*\n * A dynamic system with noise, or a fixed additive noise\n */\nclass walk : private pred_model\n{\npublic:\n\twalk (const Vec start, const bool fixed = false);\n\tvoid predict ();\n\tVec x, x_pred, rootq;\nprivate:\n\tbool m_fixed;\n\tVec m_base;\n};\n\nwalk::walk (const Vec start, const bool fixed) : x(NX), x_pred(NX), rootq(NQ), m_base(NX)\n{\n\tm_fixed = fixed;\n\tm_base = start;\n\tx = m_base;\n\tfor (Vec::const_iterator qi = q.begin(); qi != q.end(); ++qi) {\n\t\trootq[qi.index()] = std::sqrt(*qi);\n\t}\n}\n\nvoid walk::predict ()\n{\n\t\t\t\t\t\t// Correlated additive random noise\n\tDenseVec n(rootq.size()), nc(x.size());\n\t::Random.normal (n);\t\t// independant zero mean normal\n\t\t\t\t\t\t\t\t// multiply elements by std dev\n\tfor (DenseVec::iterator ni = n.begin(); ni != n.end(); ++ni) {\n\t\t*ni *= rootq[ni.index()];\n\t}\n\tnc = prod(G,n);\t\t\t\t// correlate\n\n\tif (m_fixed) {\t\t\t\t// Randomize based on assumed noise\n\t\tx = m_base + nc;\n\t}\n\telse {\n\t\tx_pred = f(x);\n\t\tx = x_pred;\n\t\tnoalias(x) += nc;\n\t}\n}\n\n\n// Special for Information scheme using Linrz predict\nclass Information_linrz_scheme : public Information_scheme\n{\npublic:\n\tInformation_linrz_scheme (std::size_t x_size, std::size_t z_initialsize = 0) :\n\t\tKalman_state_filter (x_size),\n\t\tInformation_state_filter (x_size),\n\t\tInformation_scheme (x_size, z_initialsize)\n\t{}\n\tFloat predict (Linrz_predict_model& f)\n\t// Enforce use of Linrz predict\n\t{\n\t\treturn Information_scheme::predict (f);\n\t}\n};\n\n// Filter_scheme Information_linrz_scheme specialisation\nnamespace Bayesian_filter {\ntemplate <>\nFilter_scheme<Information_linrz_scheme>::Filter_scheme(std::size_t x_size, std::size_t q_maxsize, std::size_t z_initialsize) :\n\tKalman_state_filter (x_size),\n\tInformation_state_filter (x_size),\n\tInformation_linrz_scheme (x_size, z_initialsize)\n{}\n}\n\n/*\n * Filter under test. Initialised for state and covariance\n */\ntemplate <class TestScheme>\nclass Filter\n{\npublic:\n\tFilter (const Vec& x_init, const SymMatrix& X_init);\n\tFilter_scheme<TestScheme> ts;\n\ttemplate <class P>\n\tvoid predict (P& pmodel)\n\t{\n\t\tts.predict (pmodel);\n\t}\n\ttemplate <class O>\n\tvoid observe (O& omodel, const Vec& z)\n\t{\n\t\tts.observe (omodel, z);\n\t}\n\tvoid update ()\n\t{\n\t\tts.update ();\n\t}\n\tconst Vec& x()\n\t{\treturn ts.x;\n\t}\n\tconst SymMatrix& X()\n\t{\treturn ts.X;\n\t}\n\tvoid dump_state()\n\t{\t// output any additional state variables\n\t}\n};\n\ntemplate <class TestScheme>\nFilter<TestScheme>::Filter (const Vec& x_init, const SymMatrix& X_init) :\n\tts (x_init.size(), NQ, NZ)\n{\n\tts.init_kalman (x_init, X_init);\n}\n\n// Specialise for SIR_kalman\ntemplate <>\nFilter<SIR_kalman_scheme>::Filter (const Vec& x_init, const SymMatrix& X_init) :\n\tts (x_init.size(), NS, ::Random2)\n{\n\tts.init_kalman (x_init, X_init);\n}\n\n// dump_state specialisations\ntemplate <>\nvoid Filter<Information_root_scheme>::dump_state()\n{\t// output any additional state variables\n\tstd::cout << ts.r << ts.R << std::endl;\n}\n\ntemplate <>\nvoid Filter<Unscented_scheme>::dump_state()\n{\t// output any additional state variables\n\tstd::cout << ts.XX << std::endl;\n}\n\n/*\n * Compare Two filters\n */\n\ntemplate<class Tf1, class Tf2>\nclass CCompare\n{\npublic:\n\tCCompare (const Vec x_init, const SymMatrix X_init, unsigned nIterations);\nprivate:\n\tvoid doIt (unsigned nIterations);\n\t// Attributes\n\tTf1 f1;\n\tTf2 f2;\n\twalk truth;\n\tpred_model f;\n\tuobs_model uh;\n\tcobs_model ch;\n\n\t// Implementation\n\tvoid dumpCompare ();\n\n\tVec ztrue, z;\n\n\tDenseVec f1_xpred, f2_xpred;\n\tDenseSymMatrix f1_Xpred;\n\tDenseSymMatrix f2_Xpred;\n};\n\ntemplate<class Tf1, class Tf2>\nCCompare<Tf1,Tf2>::CCompare (const Vec x_init, const SymMatrix X_init, unsigned nIterations) :\n\tf1(x_init, X_init),\n\tf2(x_init, X_init),\n\ttruth (x_init, TRUTH_STATIONARY),\n\tuh(),\n\tch(uh),\n\tztrue(NZ), z(NZ),\n\tf1_xpred (NX),\n\tf2_xpred (NX),\n\tf1_Xpred (NX, NX),\n\tf2_Xpred (NX, NX)\n{\n\t// Initialises test variables\n\tz.clear();\n\n\tf1_xpred.clear();\n\tf2_xpred.clear();\n\tf1_Xpred.clear();\n\tf2_Xpred.clear();\n\n\tdoIt (nIterations);\n}\n\ntemplate<class Tf1, class Tf2>\nvoid CCompare<Tf1, Tf2>::dumpCompare ()\n{\n\t// Additional Scheme state\n\t//f1.dump_state(); f2.dump_state();\n\n\tFloat zx, zy;\n\tif (RA_MODEL) {\n\t\tzx = truth.x[0] + z[0] * cos (z[1]);\n\t\tzy = truth.x[1] + z[0] * sin (z[1]);\n\t}\n\telse {\n\t\tzx = truth.x[0] + z[0];\n\t\tzy = truth.x[1] + z[1];\n\t}\n\n\t// Comparison\n\t{\n\t\tusing std::cout; using std::endl;\n\t\tusing boost::format;\n\t\tconst Vec& f1x = f1.x(); const SymMatrix& f1X = f1.X();\n\t\tconst Vec& f2x = f2.x(); const SymMatrix& f2X = f2.X();\n\n\t\t// Comparison and truth line\n\t\t//\tx(0)diff, x(1)diff, truth.x(0), truth.x(1), zx, zy)\n\t\tcout << format(\"*%11.4g %11.4g * %10.3f %10.3f  %10.3f %10.3f\")\n\t\t\t \t% (f1x[0]-f2x[0]) % (f1x[1]-f2x[1])\n\t\t\t \t% Float(truth.x[0]) % Float(truth.x[1]) % zx % zy << endl;\t// ISSUE mixed type proxy assignment\n\n\t\tformat state(\" %11.4g %11.4g * %10.3f %10.3f\");\n\t\tformat covariance(\" %12.4e %12.4e %12.4e\");\n\n\t\t// Filter f1 performance\n\t\t//\t\tx[0]err, x[1]err, x[0], x[1],  Xpred*3, X*3\n\t\tcout << state % (f1x[0]-truth.x[0]) % (f1x[1]-truth.x[1])\n\t\t\t\t% f1x[0] % f1x[1] << endl;\n\t\tcout << covariance % f1_Xpred(0,0) % f1_Xpred(1,1) % f1_Xpred(1,0);\n\t\tcout << covariance % f1X(0,0) % f1X(1,1) % f1X(1,0) << endl;\n\t\t// Filter f2 performance\n\t\t//\t\tx[0]err, x[1]err, x[0], x[1], x[01]dist,  Xpred*3, X*3\n\t\tcout << state % (f2x[0]-truth.x[0]) % (f2x[1]-truth.x[1])\n\t\t\t\t% f2x[0] % f2x[1] << endl;\n\t\tcout << covariance % f2_Xpred(0,0) % f2_Xpred(1,1) % f2_Xpred(1,0);\n\t\tcout << covariance % f2X(0,0) % f2X(1,1) % f2X(1,0) << endl;\n\t}\n}\n\ntemplate<class Tf1, class Tf2>\nvoid CCompare<Tf1, Tf2>::doIt (unsigned nIterations)\n{\n\t// Update the filter x,X representation\n\tf1.update (); f2.update ();\n\tz = ztrue = uh.h(truth.x);\n\tdumpCompare();\n\n\tfor (unsigned i = 0; i < nIterations; i++ ) {\n\t\ttruth.predict ();\t\t// Predict truth model\n\t\tf1.predict (f);\t\t\t// Predict filters\n\t\tf2.predict (f);\n\n\t\t// Update the filter\n\t\tf1.update (); f2.update ();\n\n\t\tf1_xpred = f1.x(); f2_xpred = f2.x();\n\t\tf1_Xpred = f1.X(); f2_Xpred = f2.X();\n\n\t\t// Observation, true and Randomize based on an uncorrelated noise model\n\t\tztrue = uh.h(truth.x);\n\t\tif (NOISE_MODEL) {\n\t\t\tz[0] = Random.normal (ztrue[0], sqrt(uh.Zv[0]) );\n\t\t\tz[1] = Random.normal (ztrue[1], sqrt(uh.Zv[1]) );\n\t\t}\n\t\telse\n\t\t\tz = ztrue;\n\n\t\t// Observe using model linearised about filter state estimate\n\t\tif (Z_CORRELATION == 0)\n\t\t{\n\t\t\tuh.state(f1.x()); f1.observe (uh, z);\n\t\t\tuh.state(f2.x()); f2.observe (uh, z);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tch.state(f1.x()); f1.observe (ch, z);\n\t\t\tch.state(f2.x()); f2.observe (ch, z);\n\t\t}\n\n\t\t// Update the filter\n\t\tf1.update (); f2.update ();\n\n\t\tdumpCompare();\n\t\t// DEBUG char c;std::cin>>c;\n\t}\n}\n\n\nint main()\n{\n\t// Other things I might want to test\n\textern void other_tests();\n\tother_tests();\n\n\t// Use a know sequence for comparisons between systems\n\tRandom.seed();\n\tRandom2.seed();\n\t\n\t// Setup the test filters\n\t\t// Cartesian start position (in meters)\n\tVec x_init (NX);\n\tx_init.clear();\n \tx_init[0] = INIT_XY[0];\n\tx_init[1] = INIT_XY[1];\n\t\t// Initial state covariance, correlated\n\tSymMatrix X_init (NX, NX);\n\tFM::identity (X_init);\n\tX_init(0,0) = sqr(INIT_X_NOISE);\n\tX_init(1,1) = sqr(INIT_Y_NOISE);\n\tX_init(1,0) = X_init(0,1) = INIT_X_NOISE*INIT_Y_NOISE*INIT_XY_NOISE_CORRELATION;\n\t// Additional state correlation is useful for testing\n\t\tX_init(2,2) = sqr(INIT_2_NOISE);\n\tX_init(2,0) = X_init(0,2) = INIT_X_NOISE*INIT_2_NOISE*INIT_2_NOISE_CORRELATION;\n\tX_init(2,1) = X_init(1,2) = INIT_Y_NOISE*INIT_2_NOISE*INIT_2_NOISE_CORRELATION;\n\n\t// Initialise and do the comparison\n\tstd::cout << \"udfilter, ufilter \" << \"RA_MODEL:\" << RA_MODEL << \" NOISE_MODEL:\" << NOISE_MODEL << \" TRUTH_STATIONARY:\" << TRUTH_STATIONARY << std::endl;\n\tRandom.seed();\n\tCCompare<Filter<UD_scheme>, Filter<Unscented_scheme> > test1(x_init, X_init, 4);\n\tstd::cout << std::endl;\n\n\tstd::cout << \"cfilter, ifilter \" << \"RA_MODEL:\" << RA_MODEL << \" NOISE_MODEL:\" << NOISE_MODEL << \" TRUTH_STATIONARY:\" << TRUTH_STATIONARY << std::endl;\n\tRandom.seed();\n\tCCompare<Filter<Covariance_scheme>, Filter<Information_linrz_scheme> > test2(x_init, X_init, 4);\n\tstd::cout << std::endl;\n\n\tstd::cout << \"irfilter, ilfilter \" << \"RA_MODEL:\" << RA_MODEL << \" NOISE_MODEL:\" << NOISE_MODEL << \" TRUTH_STATIONARY:\" << TRUTH_STATIONARY << std::endl;\n\tRandom.seed();\n\tCCompare<Filter<Information_root_scheme>, Filter<Information_scheme> > test3(x_init, X_init, 4);\n\tstd::cout << std::endl;\n\n\tstd::cout << \"sfilter, itfilter \" << \"RA_MODEL:\" << RA_MODEL << \" NOISE_MODEL:\" << NOISE_MODEL << \" TRUTH_STATIONARY:\" << TRUTH_STATIONARY << std::endl;\n\tRandom.seed();\n\tCCompare<Filter<SIR_kalman_scheme>, Filter<Iterated_covariance_scheme> > test4(x_init, X_init, 4);\n\tstd::cout << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "57f36f4746fe8c421cf57da24579ea9dbf34203e", "size": 14810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rtheta/rtheta.cpp", "max_stars_repo_name": "Exadios/Bayes-", "max_stars_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T21:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-19T01:59:02.000Z", "max_issues_repo_path": "rtheta/rtheta.cpp", "max_issues_repo_name": "Exadios/Bayes-", "max_issues_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rtheta/rtheta.cpp", "max_forks_repo_name": "Exadios/Bayes-", "max_forks_repo_head_hexsha": "a1cd9efe2e840506d887bec9b246fd936f2b71e5", "max_forks_repo_licenses": ["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.4030874786, "max_line_length": 154, "alphanum_fraction": 0.6748818366, "num_tokens": 4878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6116454537771375}}
{"text": "// File: compressed2D.cpp\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl;\n\n    // CRS matrix\n    compressed2D<double>   A(12, 12);\n\n    // Laplace operator discretized on a 3x4 grid\n    mat::laplacian_setup(A, 3, 4);\n    std::cout << \"A is \\n\" << A;\n    \n    // Element access is allowed for reading\n    std::cout << \"A[3][2] is \" << A[3][2] << \"\\n\\n\";\n    \n    // CCS matrix\n    compressed2D<float, mat::parameters<tag::col_major> > B(10, 10);\n\n    // Assign the identity matrix times 3 to B\n    B= 3;\n    std::cout << \"B is \\n\" << B << \"\\n\";\n\n    return 0;\n}\n\n", "meta": {"hexsha": "596c4ff597335f6850084a15334c14ae79f40a88", "size": 622, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/compressed2D.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/compressed2D.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/compressed2D.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 20.7333333333, "max_line_length": 68, "alphanum_fraction": 0.5675241158, "num_tokens": 207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6116207536604679}}
{"text": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Molassembler/Temple/Optimization/SO3NelderMead.h\"\n\n#include <iostream>\n\nusing namespace Scine::Molassembler;\n\nBOOST_AUTO_TEST_CASE(SO3NelderMead, *boost::unit_test::label(\"Temple\")) {\n  struct EigenValueDecomposition {\n    static inline double square(double x) noexcept {\n      return x * x;\n    }\n\n    double operator() (const Eigen::Matrix3d& rotation) const {\n      Eigen::Matrix3d X;\n      X <<  5,  2,  1,\n            2,  7,  3,\n            1,  3, 10;\n      Eigen::Matrix3d partiallyDiagonal = rotation * X * rotation.transpose();\n      double offDiagonalSquares = 0;\n      for(unsigned i = 0; i < 2; ++i) {\n        for(unsigned j = i + 1; j < 3; ++j) {\n          offDiagonalSquares += square(partiallyDiagonal(i, j)) + square(partiallyDiagonal(j, i));\n        }\n      }\n      return offDiagonalSquares;\n    }\n  };\n\n  struct NelderMeadChecker {\n    bool shouldContinue(unsigned iteration, double lowestValue, double stddev) {\n      //std::cout << \"Iteration \" << iteration << \": \" << lowestValue << \" +- \" << stddev << \"\\n\";\n      return iteration < 1000 && lowestValue >= 1e-5 && stddev > 1e-7;\n    }\n  };\n\n  using OptimizerType = Temple::SO3NelderMead<>;\n\n  { /* Squared distance commutative */\n    const auto A = OptimizerType::Manifold::randomRotation();\n    const auto B = OptimizerType::Manifold::randomRotation();\n    BOOST_CHECK_MESSAGE(\n      std::fabs(OptimizerType::Manifold::distanceSquared(A, B) - OptimizerType::Manifold::distanceSquared(B, A)) < 1e-10,\n      \"Squared distance calculation is not commutative\"\n    );\n  }\n\n  { /* Geodesic interpolation works */\n    const Eigen::Matrix3d zPi = Eigen::AngleAxisd(M_PI, Eigen::Vector3d::UnitZ()).toRotationMatrix();\n    const Eigen::Matrix3d zPiHalf = Eigen::AngleAxisd(M_PI / 2, Eigen::Vector3d::UnitZ()).toRotationMatrix();\n    BOOST_CHECK_MESSAGE(\n      OptimizerType::Manifold::geodesic(zPi, zPiHalf, 0).isApprox(zPiHalf, 1e-4),\n      \"geodesicExtrapolation(a, b, 0) != b\"\n    );\n    BOOST_CHECK_MESSAGE(\n      OptimizerType::Manifold::geodesic(zPi, zPiHalf, 1).isApprox(zPi, 1e-4),\n      \"geodesicExtrapolation(a, b, 1) != a\"\n    );\n\n    const Eigen::AngleAxisd interpolation {OptimizerType::Manifold::geodesic(zPiHalf, zPi, 0.5)};\n    BOOST_CHECK_MESSAGE(\n      interpolation.axis().isApprox(Eigen::Vector3d::UnitZ(), 1e-4),\n      \"Axis of interpolated rotation is no longer z, but: \" << interpolation.axis().transpose()\n    );\n    BOOST_CHECK_MESSAGE(\n      std::fabs(interpolation.angle() - 3 * M_PI / 4) < 1e-4,\n      \"Angle of interpolated rotation is not 3 pi / 4 (\" << (3 * M_PI / 4) << \"), but \" << interpolation.angle()\n    );\n  }\n\n  bool pass = false;\n  OptimizerType::OptimizationReturnType result;\n  const unsigned maxAttempts = 10;\n  for(unsigned i = 0; i < maxAttempts; ++i) {\n    auto simplexVertices = OptimizerType::randomParameters();\n    result = Temple::SO3NelderMead<>::minimize(\n      simplexVertices,\n      EigenValueDecomposition {},\n      NelderMeadChecker {}\n    );\n    if(std::fabs(result.value) < 1e-2) {\n      pass = true;\n      break;\n    }\n\n    std::cout << \"Attempt \" << i << \" lowest SO(3) minim. value = \" << result.value << \"\\n\";\n  }\n\n  BOOST_CHECK_MESSAGE(\n    pass,\n    \"SO(3) Nelder-Mead does not find minimization of EigenValueDecomposition problem in three attempts, value is \"\n    << result.value << \" after \" << result.iterations\n    << \" iterations.\"\n  );\n}\n", "meta": {"hexsha": "76c8e3aa577879c10536382f4cd644501b391e1b", "size": 3610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Temple/Optimization/SO3NelderMead.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "test/Temple/Optimization/SO3NelderMead.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Temple/Optimization/SO3NelderMead.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 35.0485436893, "max_line_length": 121, "alphanum_fraction": 0.643767313, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6116207482382694}}
{"text": "#include \"ode45.hpp\"\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nusing namespace Eigen;\nusing namespace std;\n\n// Compute the maps Phi and W at time T, for initial data given by u0 and v0.\npair<Vector2d,Matrix2d> PhiAndW(double u0, double v0, double T) {\n    auto f = [] (const VectorXd & w) {\n        \n        // TODO: the right hand side of the system of ODEs related to Phi and W.\n        \n    };\n    \n    ode45<Eigen::VectorXd> O(f);\n    O.options.rtol = 1e-14;\n    O.options.atol = 1e-12;\n\n    // TODO\n    \n}\n\n// Apply the Newton method to find initial data giving solutions with period equal to 5.\nint main(){\n    \n    // TODO\n    \n}", "meta": {"hexsha": "854388516f38b837cc6bf8c8de8709bd576ef595", "size": 662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS13/templates_ps13/LV_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/LV_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/LV_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": 22.0666666667, "max_line_length": 88, "alphanum_fraction": 0.6283987915, "num_tokens": 182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6116207404573543}}
{"text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <fstream>\n\n#include <boost/timer.hpp>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <sophus/se3.h>\n\n/* parameters */\nconst int boarder = 20;         // boundary\nconst int width = 640;\nconst int height = 480;\n\nconst double fx = 481.2f;\nconst double fy = -480.0f;\nconst double cx = 319.5f;\nconst double cy = 239.5f;\n\nconst int ncc_window_size = 2;  // NCC window width half size\nconst int ncc_area = (2*ncc_window_size + 1) * (2*ncc_window_size + 1);     // NCC window area size\n\nconst double min_cov = 0.1f;    // convergence condition: minimum variance\nconst double max_cov = 10.f;    // divergence  condition: maximum variance\n\n/* functions declaration */\nbool readDatasetFiles(\n    const std::string& path, \n    std::vector<std::string>& color_image_files, \n    std::vector<Sophus::SE3>& poses\n);\n\nbool update(\n    const cv::Mat& ref, \n    const cv::Mat& curr, \n    const Sophus::SE3& T_c_r, \n    cv::Mat& depth, \n    cv::Mat& depth_cov\n);\n\nbool epipolarSearch(\n    const cv::Mat& ref, \n    const cv::Mat& curr, \n    const Sophus::SE3& T_c_r, \n    const Eigen::Vector2d& pt_ref, \n    const double& depth_mu, \n    const double& depth_cov, \n    Eigen::Vector2d& pt_curr\n);\n\nbool updateDepthFilter(\n    const Eigen::Vector2d& pt_ref,\n    const Eigen::Vector2d& pt_curr,\n    const Sophus::SE3& T_c_r,\n    cv::Mat& depth,\n    cv::Mat& depth_cov\n);\n\ndouble computeNCC(\n    const cv::Mat& ref,\n    const cv::Mat& curr,\n    const Eigen::Vector2d& pt_ref,\n    const Eigen::Vector2d& pt_curr\n);\n\ninline double getBilinearInterpolatedValue(const cv::Mat& image, const Eigen::Vector2d& pt)\n{\n    uchar* d = & image.data[int(pt.y()) * image.step + int(pt.x())];\n    \n    double xx = pt.x() - floor(pt.x());\n    double yy = pt.y() - floor(pt.y());\n    \n    return ( (1.f-xx) * (1.f-yy) * double(d[0]) + \n                xx    * (1.f-yy) * double(d[1]) +\n             (1.f-xx) *    yy    * double(d[image.step]) +\n                xx    *    yy    * double(d[image.step + 1]) ) / 255.0;\n}\n\n/* some tools functions */\nvoid plotDepth(const cv::Mat& depth);\n\ninline Eigen::Vector3d px2cam(const Eigen::Vector2d px)\n{\n    return Eigen::Vector3d(\n        (px.x() - cx) / fx,\n        (px.y() - cy) / fy,\n        1.0\n    );\n}\n\ninline Eigen::Vector2d cam2px(const Eigen::Vector3d p_cam)\n{\n    return Eigen::Vector2d(\n        p_cam.x() * fx / p_cam.z() + cx,\n        p_cam.y() * fy / p_cam.z() + cy\n    );\n}\n\ninline bool inside(const Eigen::Vector2d& pt)\n{\n    return (pt.x() >= boarder && pt.y() >= boarder\n        &&  pt.x() + boarder <= width && pt.y() + boarder <= height); \n}\n\nvoid showEpipolarMatch(\n    const cv::Mat& ref, \n    const cv::Mat& curr, \n    const Eigen::Vector2d& px_ref, \n    const Eigen::Vector2d& px_curr\n);\n\nvoid showEpipolarLine(\n    const cv::Mat& ref,\n    const cv::Mat& curr,\n    const Eigen::Vector2d& px_ref,\n    const Eigen::Vector2d& px_mincurr,\n    const Eigen::Vector2d& px_maxcurr\n);\n\nint main(int argc, char** argv)\n{\n    if (argc != 2) {\n        std::cout << \"Usage: dense_mapping_monocular <path_to_test_dataset>\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n    \n    // read the data form the dataset\n    std::vector<std::string> color_image_files;\n    std::vector<Sophus::SE3> poses_T_w_c;\n    bool ret = readDatasetFiles(argv[1], color_image_files, poses_T_w_c);\n    if (ret == false) {\n        std::cout << \"Reading files failed\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n    \n    std::cout << \"read total \" << color_image_files.size() << \" files.\" << std::endl;\n    \n    // first image\n    cv::Mat ref = cv::imread(color_image_files[0], 0);      // garg-scale image\n    Sophus::SE3 pose_ref_Twc = poses_T_w_c[0];\n    double init_depth = 3.0;\n    double init_cov2 = 3.0;\n    cv::Mat depth(height, width, CV_64F, init_depth);\n    cv::Mat depth_cov(height, width, CV_64F, init_cov2);\n    \n    for (int index = 1; index < color_image_files.size(); index ++) {\n        std::cout << \"*** loop \" << index << \" ***\" << std::endl;\n        cv::Mat curr = cv::imread(color_image_files[index], 0);\n        if (curr.data == nullptr) continue;\n        Sophus::SE3 pose_curr_Twc = poses_T_w_c[index];\n        Sophus::SE3 pose_curr_ref = pose_curr_Twc.inverse() * pose_ref_Twc;\n        update(ref, curr, pose_curr_ref, depth, depth_cov);\n        plotDepth(depth);\n        cv::imshow(\"image\", curr);\n        cv::waitKey(1);\n    }\n    \n    std::cout << \"estimation returens, saving depth map ...\" << std::endl;\n    cv::imwrite(\"depth.png\", depth);\n    std::cout << \"done.\" << std::endl;\n    \n    return 0u;\n}\n\nbool readDatasetFiles(const std::string& path, std::vector<std::string>& color_image_files, std::vector<Sophus::SE3>& poses)\n{\n    std::ifstream fin(path + \"/first_200_frames_traj_over_table_input_sequence.txt\");\n    if (!fin) return false;\n    \n    while(!fin.eof()) {\n        /* the form of dataset : image's name, tx, ty, tz, qx, qy, qz, qw. NOTE: the transformation matrix is camera to world */\n        std::string image_name;\n        fin >> image_name;\n        \n        double data[7];\n        for (double& d : data) fin >> d;\n        \n        color_image_files.push_back(path + std::string(\"/images/\") + image_name);\n        poses.push_back(\n            Sophus::SE3(Sophus::Quaterniond(data[6], data[3], data[4], data[5]),\n                        Sophus::Vector3d(data[0], data[1], data[2]))\n        );\n        \n        if (!fin.good()) break;\n    }\n    \n    return true;\n}\n\n/* update the global depth map */\nbool update(const cv::Mat& ref, const cv::Mat& curr, const Sophus::SE3& T_c_r, cv::Mat& depth, cv::Mat& depth_cov)\n{\n#pragma omp parallel for\n    for (int x = boarder; x < width - boarder; x++) {\n#pragma omp parallel for \n        for (int y = boarder; y < height - boarder; y++) {\n            // Traversing every pixel\n            if (depth_cov.ptr<double>(y)[x] < min_cov || depth_cov.ptr<double>(y)[x] > max_cov)     // the depth was convergence / divergence\n                continue;\n            \n            // match the pixel in the epipolar between the reference and the current\n            Eigen::Vector2d pt_curr;\n            bool ret = epipolarSearch(\n                ref,\n                curr,\n                T_c_r,\n                Eigen::Vector2d(x, y),\n                depth.ptr<double>(y)[x],\n                sqrt(depth_cov.ptr<double>(y)[x]),\n                pt_curr\n            );\n            \n            if (ret == false)   // match false\n                continue;\n            \n            // \u53d6\u6d88\u8be5\u6ce8\u91ca\u4ee5\u663e\u793a\u5339\u914d\n//             showEpipolarMatch(ref, curr, Eigen::Vector2d(x, y), pt_curr);\n            \n            // update the depth map\n            updateDepthFilter(Eigen::Vector2d(x, y), pt_curr, T_c_r, depth, depth_cov);\n        }\n    }\n    return true;\n}\n\nbool epipolarSearch(const cv::Mat& ref, const cv::Mat& curr, const Sophus::SE3& T_c_r, const Eigen::Vector2d& pt_ref, const double& depth_mu, const double& depth_cov, Eigen::Vector2d& pt_curr)\n{\n    Eigen::Vector3d f_ref = px2cam(pt_ref);\n    f_ref.normalize();\n    Eigen::Vector3d p_ref = f_ref*depth_mu;\n    \n    Eigen::Vector2d px_mean_curr = cam2px(T_c_r * p_ref);           // \u6309\u6df1\u5ea6\u5747\u503c\u6295\u5f71\u7684\u50cf\u7d20\n    double d_min = depth_mu - 3*depth_cov, d_max = depth_mu + 3*depth_cov;\n    if (d_min < 0.1) d_min = 0.1;\n    Eigen::Vector2d px_min_curr = cam2px(T_c_r * (f_ref * d_min));  // \u6309\u6700\u5c0f\u6df1\u5ea6\u6295\u5f71\u7684\u50cf\u7d20\n    Eigen::Vector2d px_max_curr = cam2px(T_c_r * (f_ref * d_max));  // \u6309\u6700\u5927\u6df1\u5ea6\u6295\u5f71\u7684\u50cf\u7d20\n    \n    Eigen::Vector2d epipolar_line = px_max_curr - px_min_curr;      // \u6781\u7ebf\uff08\u7ebf\u6bb5\u5f62\u5f0f\uff09\n    Eigen::Vector2d epipolar_direction = epipolar_line;             // \u6781\u7ebf\u65b9\u5411 \n    epipolar_direction.normalize();\n    double half_length = 0.5 * epipolar_line.norm();                // \u6781\u7ebf\u7ebf\u6bb5\u7684\u534a\u957f\u5ea6\n    if (half_length > 100) half_length = 100;                       // \u6211\u4eec\u4e0d\u5e0c\u671b\u641c\u7d22\u592a\u591a\u4e1c\u897f \n    \n    // if the epipolar line length <= 1.5 pixel, we regard that the mean point is the matching point\n    if (half_length <= 1.5) {\n        pt_curr = px_mean_curr;\n        if (!inside(pt_curr))\n            return false;\n        return true;\n    } \n    \n    // \u53d6\u6d88\u6b64\u53e5\u6ce8\u91ca\u4ee5\u663e\u793a\u6781\u7ebf\uff08\u7ebf\u6bb5\uff09\n//     showEpipolarLine(ref, curr, pt_ref, px_min_curr, px_max_curr);\n    \n    // \u5728\u6781\u7ebf\u4e0a\u641c\u7d22\uff0c\u4ee5\u6df1\u5ea6\u5747\u503c\u70b9\u4e3a\u4e2d\u5fc3\uff0c\u5de6\u53f3\u5404\u53d6\u534a\u957f\u5ea6\n    double best_ncc = -1.0;\n    Eigen::Vector2d best_px_curr;\n    for (double l = -half_length; l <= half_length; l += 0.7){      // l += sqrt(2)\n        Eigen::Vector2d px_curr = px_mean_curr + l * epipolar_direction;    // \u5f85\u5339\u914d\u70b9\n        if (!inside(px_curr))\n            continue;\n        // \u8ba1\u7b97\u5f85\u5339\u914d\u70b9\u4e0e\u53c2\u8003\u5e27\u7684 NCC\n        double ncc = computeNCC(ref, curr, pt_ref, px_curr);\n        if (ncc > best_ncc) {\n            best_ncc = ncc;\n            best_px_curr = px_curr;\n        }\n    }\n    if (best_ncc < 0.85f)       // \u53ea\u76f8\u4fe1 NCC \u5f88\u9ad8\u7684\u5339\u914d\n        return false;\n    \n    pt_curr = best_px_curr;\n    \n    return true;\n}\n\ndouble computeNCC(const cv::Mat& ref, const cv::Mat& curr, const Eigen::Vector2d& pt_ref, const Eigen::Vector2d& pt_curr)\n{\n    // \u96f6\u5747\u503c-\u5f52\u4e00\u5316\u4e92\u76f8\u5173\n    // \u5148\u7b97\u5747\u503c\n    double mean_ref = 0, mean_curr = 0;\n    std::vector<double> values_ref, values_curr;    // \u53c2\u8003\u5e27\u548c\u5f53\u524d\u5e27\u7684\u5747\u503c\n    for (int x = -ncc_window_size; x <= ncc_window_size; x ++) {\n        for (int y = -ncc_window_size; y <= ncc_window_size; y ++) {\n            double value_ref = double(ref.ptr<uchar>(int(y + pt_ref.y()))[int(x + pt_ref.x())]) / 255.0;\n            mean_ref += value_ref;\n            \n//             double value_curr = double(curr.ptr<uchar>(int(y + pt_curr.y()))[int(x + pt_curr.x())]) / 255.0;\n            double value_curr = getBilinearInterpolatedValue(curr, pt_curr + Eigen::Vector2d(x, y));\n            mean_curr += value_curr;\n            \n            values_ref.push_back(value_ref);\n            values_curr.push_back(value_curr);\n        }\n    }\n    \n    mean_ref /= ncc_area;\n    mean_curr /= ncc_area;\n    \n    // compute Zero mean NCC \n    double numerator = 0, denominator1 = 0, denominator2 = 0;\n    for (int i = 0; i < values_ref.size(); i++) {\n        double n = (values_ref[i] - mean_ref) * (values_curr[i] - mean_curr);\n        numerator += n;\n        denominator1 += (values_ref[i] - mean_ref) * (values_ref[i] - mean_ref);\n        denominator2 += (values_curr[i] - mean_curr) * (values_curr[i] - mean_curr);\n    }\n    return numerator / sqrt(denominator1 * denominator2 + 1e-10);   // \u9632\u6b62\u5206\u6bcd\u51fa\u73b0\u96f6\n}\n\nbool updateDepthFilter(const Eigen::Vector2d& pt_ref, const Eigen::Vector2d& pt_curr, const Sophus::SE3& T_c_r, cv::Mat& depth, cv::Mat& depth_cov)\n{\n    // \u7528\u4e09\u89d2\u5316\u8ba1\u7b97\u6df1\u5ea6\n    Sophus::SE3 T_r_c = T_c_r.inverse();\n    Eigen::Vector3d f_ref = px2cam(pt_ref);\n    f_ref.normalize();\n    Eigen::Vector3d f_curr = px2cam(pt_curr);\n    f_curr.normalize();\n    \n    /**\n     * function:\n     * d_ref * f_ref = d_cur * (R_r_c * f_cur) + t_r_c\n     * => [f_ref^T f_ref, -f_ref^T f_cur] [d_ref] = [f_ref^T t]\n     *    [f_cur^T f_ref, -f_cur^T f_cur] [d_cur] = [f_cur^T t]\n     * \u4e8c\u9636\u65b9\u7a0b\u7528\u514b\u83b1\u9ed8\u6cd5\u5219\u6c42\u89e3\u5e76\u89e3\u4e4b\n     */\n    Eigen::Vector3d t = T_r_c.translation();\n    Eigen::Vector3d f2 = T_r_c.rotation_matrix() * f_curr;\n    Eigen::Vector2d b = Eigen::Vector2d(t.dot(f_ref), t.dot(f2));\n    \n    double A[4];\n    A[0] = f_ref.dot(f_ref);\n    A[2] = f_ref.dot(f2);\n    A[1] = -A[2];\n    A[3] = -f2.dot(f2);\n    \n    double d = A[0]*A[3] - A[1]*A[2];\n    Eigen::Vector2d lambda_vec = Eigen::Vector2d(\n        A[3]*b(0, 0) - A[1]*b(1, 0),\n        A[0]*b(1, 0) - A[2]*b(0, 0)) / d;\n    \n    Eigen::Vector3d xm = lambda_vec(0, 0) * f_ref;\n    Eigen::Vector3d xn = lambda_vec(1, 0) * f2 + t;\n    Eigen::Vector3d d_esti = (xm + xn) / 2.0;       // \u4e09\u89d2\u5316\u7b97\u5f97\u7684\u6df1\u5ea6\u5411\u91cf\n    double depth_estimation = d_esti.norm();        // \u6df1\u5ea6\u503c\n    \n    // \u8ba1\u7b97\u4e0d\u786e\u5b9a\u6027\uff08\u4ee5\u4e00\u4e2a\u50cf\u7d20\u4e3a\u8bef\u5dee\uff09\n    Eigen::Vector3d p = f_ref*depth_estimation;\n    Eigen::Vector3d a = p - t;\n    double t_norm = t.norm();\n    double a_norm = a.norm();\n    double alpha = acos(f_ref.dot(t) / t_norm);\n    double beta = acos(a.dot(-t) / a_norm / t_norm);\n    double beta_prime = beta + atan(1.0 / fx / 2.0) * 2.0;\n    double gamma = M_PI - alpha - beta_prime;\n    double p_prime = t_norm * sin(beta_prime) / sin(gamma);\n    double d_cov = p_prime - depth_estimation;\n    double d_cov2 = d_cov * d_cov;\n    \n    // \u9ad8\u65af\u878d\u5408\n    double mu = depth.ptr<double>(int(pt_ref.y()))[int(pt_ref.x())];\n    double sigma2 = depth_cov.ptr<double>(int(pt_ref.y()))[int(pt_ref.x())];\n    \n    double mu_fuse = (d_cov2*mu + sigma2*depth_estimation) / (d_cov2 + sigma2);\n    double sigma2_fuse = (d_cov2*sigma2) / (d_cov2 + sigma2);\n    \n    depth.ptr<double>(int(pt_ref.y()))[int(pt_ref.x())] = mu_fuse;\n    depth_cov.ptr<double>(int(pt_ref.y()))[int(pt_ref.x())] = sigma2_fuse;\n    \n    return true;\n}\n\nvoid plotDepth(const cv::Mat& depth)\n{\n    cv::imshow(\"depth\", depth * 0.4);\n    cv::waitKey(1);\n}\n\nvoid showEpipolarMatch(const cv::Mat& ref, const cv::Mat& curr, const Eigen::Vector2d& px_ref, const Eigen::Vector2d& px_curr)\n{\n    cv::Mat ref_show, curr_show;\n    cv::cvtColor(ref, ref_show, CV_GRAY2BGR);\n    cv::cvtColor(curr, curr_show, CV_GRAY2BGR);\n    \n    cv::circle(ref_show, cv::Point2f(px_ref.x(), px_ref.y()), 5, cv::Scalar(0, 0, 250), 2);\n    cv::circle(curr_show, cv::Point2f(px_curr.x(), px_curr.y()), 5, cv::Scalar(0, 0, 250), 2);\n    \n    cv::imshow(\"ref\", ref_show);\n    cv::imshow(\"curr\", curr_show);\n    cv::waitKey(1);\n}\n\nvoid showEpipolarLine(const cv::Mat& ref, const cv::Mat& curr, const Eigen::Vector2d& px_ref, const Eigen::Vector2d& px_mincurr, const Eigen::Vector2d& px_maxcurr)\n{\n    cv::Mat ref_show, curr_show;\n    cv::cvtColor(ref, ref_show, CV_GRAY2BGR);\n    cv::cvtColor(curr, curr_show, CV_GRAY2BGR);\n    \n    cv::circle(ref_show, cv::Point2f(px_ref.x(), px_ref.y()), 5, cv::Scalar(0, 250, 0), 2);\n    cv::circle(curr_show, cv::Point2f(px_mincurr.x(), px_mincurr.y()), 5, cv::Scalar(0, 250, 2), 2);\n    cv::circle(curr_show, cv::Point2f(px_maxcurr.x(), px_maxcurr.y()), 5, cv::Scalar(0, 250, 2), 2);\n    cv::line(curr_show, cv::Point2f(px_mincurr.x(), px_mincurr.y()), cv::Point2f(px_maxcurr.x(), px_maxcurr.y()), cv::Scalar(0, 250, 0), 1);\n    \n    cv::imshow(\"ref\", ref_show);\n    cv::imshow(\"curr\", curr_show);\n    cv::waitKey(1);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "707677ab5d3c7d741df4ca5acad26fb45db7e4ad", "size": 14191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dense_mapping_monocular/src/dense_mapping_monocular.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": "dense_mapping_monocular/src/dense_mapping_monocular.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": "dense_mapping_monocular/src/dense_mapping_monocular.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": 31.3267108168, "max_line_length": 192, "alphanum_fraction": 0.5905855824, "num_tokens": 4536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785201, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.611620739508168}}
{"text": "//\n//  Copyright (c) 2013 Vladimir Chalupecky\n//\n//  Permission is hereby granted, free of charge, to any person obtaining a copy\n//  of this software and associated documentation files (the \"Software\"), to\n//  deal in the Software without restriction, including without limitation the\n//  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n//  sell copies of the Software, and to permit persons to whom the Software is\n//  furnished to do so, subject to the following conditions:\n//\n//  The above copyright notice and this permission notice shall be included in\n//  all copies or substantial portions of the Software.\n//\n//  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n//  IN THE SOFTWARE.\n\n#ifndef TPS_TPS_HPP\n#define TPS_TPS_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Cholesky>\n\n#include <boost/assert.hpp>\n#include <boost/type_traits/conditional.hpp>\n\n#include <cmath>\n#include <stdexcept>\n#include <vector>\n#include <iostream>\n\nnamespace tps { \nnamespace detail {\n\ntemplate< int k >\nstruct Polyharmonic_spline_kernel_odd\n{\n    double operator()(double r)\n    {\n        return std::pow(r, k);\n    }\n};\n\ntemplate< int k >\nstruct Polyharmonic_spline_kernel_even\n{\n    double operator()(double r)\n    {\n        if (r < 1.0)\n        {\n            return std::pow(r, k - 1) * std::log(std::pow(r, r));\n        }\n\n        return std::pow(r, k) * std::log(r);\n    }\n};\n\n} // namespace detail\n\ntemplate< int k >\nstruct Polyharmonic_spline_kernel : public boost::conditional < k % 2,\n        detail::Polyharmonic_spline_kernel_odd<k>,\n        detail::Polyharmonic_spline_kernel_even<k> >::type\n{};\n\n\ntemplate< int Domain_dim, int Range_dim, typename Kernel_function >\nclass Polyharmonic_spline_transformation\n{\npublic:\n    typedef Eigen::Matrix< double, Domain_dim, 1 > Domain_point;\n    typedef Eigen::Matrix< double, Range_dim, 1 >  Range_point;\n\nprivate:\n    typedef std::vector< Domain_point > Domain_points_container;\n    typedef std::vector< Range_point> Range_points_container;\n    typedef Eigen::MatrixXd Matrix;\n\npublic:\n    template< typename Forward_iterator_1, typename Forward_iterator_2 >\n    Polyharmonic_spline_transformation(\n            Forward_iterator_1 domain_points_begin,\n            Forward_iterator_1 domain_points_end,\n            Forward_iterator_2 range_points_begin,\n            Forward_iterator_2 range_points_end,\n            double max_relative_error = 1.0e-8\n    )\n        : domain_points_(domain_points_begin, domain_points_end)\n        , bending_norm_(0.0)\n        , max_relative_error_(max_relative_error)\n    {\n        if (domain_points_.size() < Domain_dim + 1)\n        {\n            throw\n                std::runtime_error(\n                    \"Polyharmonic_spline_transformation(): \"\n                    \"Insufficient number of corresponding pairs given\"\n                );\n        }\n\n        assemble_L_matrix();\n        set_range_points(range_points_begin, range_points_end);\n    }\n\n    Range_point transform(Domain_point p)\n    {\n        std::size_t N = domain_points_.size();\n        std::size_t M = N + 1 + Domain_dim;\n\n        Range_point result = Wa_.block<1, Range_dim>(N, 0).transpose();\n\n        for (std::size_t i = 0; i < Domain_dim; ++i)\n        {\n            result += p(i) * Wa_.block<1, Range_dim>(N + 1 + i, 0).transpose();\n        }\n\n        for (std::size_t i = 0; i < N; ++i)\n        {\n            if (p != domain_points_[i])\n            {\n                result += kernel_((domain_points_[i] - p).norm())\n                    * Wa_.block<1, Range_dim>(i, 0).transpose();\n            }\n        }\n\n        return result;\n    }\n\n    template < typename Forward_iterator >\n    void set_range_points(Forward_iterator begin, Forward_iterator end)\n    {\n        if (domain_points_.size() != std::distance(begin, end))\n        {\n            throw\n                std::runtime_error(\n                    \"Polyharmonic_spline_transformation::set_range_points(): \"\n                    \"The number of domain and range points must be the \"\n                    \"same.\"\n                );\n        }\n\n        assemble_Vt_matrix(begin, end);\n        update_Wa_matrix();\n    }\n\n    double integral_bending_norm() const\n    {\n        return bending_norm_;\n    }\n\nprivate:\n    template < typename Forward_iterator >\n    void assemble_Vt_matrix(Forward_iterator begin, Forward_iterator end)\n    {\n        std::size_t N = domain_points_.size();\n        std::size_t M = N + 1 + Domain_dim;\n\n        Vt_.resize(M, Range_dim);\n        std::size_t i = 0;\n\n        for (Forward_iterator it = begin; it != end; ++it, ++i)\n        {\n            Vt_.block<1, Range_dim>(i, 0) = *it;\n        }\n\n        Vt_.bottomLeftCorner < Domain_dim + 1, Range_dim > ().setZero();\n    }\n\n\n    void assemble_L_matrix()\n    {\n        std::size_t N = domain_points_.size();\n        std::size_t M = N + 1 + Domain_dim;\n\n        L_.resize(M, M);\n\n        for (std::size_t i = 0; i < N; ++i)\n        {\n            L_(i, i) = 0.0;\n\n            for (std::size_t j = i + 1; j < N; ++j)\n            {\n                if (domain_points_[i] == domain_points_[j])\n                {\n                    throw std::runtime_error(\n                        \"Polyharmonic_spline_transformation::assemble_L_matrix(): \"\n                        \"Degenerate input points\");\n                }\n\n                double d = (domain_points_[i] - domain_points_[j]).norm();\n\n\t\t\t\tstatic double const minimum_distance_ = 1.0e-6;\n                if (d < minimum_distance_)\n                {\n                    std::cerr <<\n                        \"Warning: Polyharmonic_spline_transformation::assemble_L_matrix(): \"\n                        \"Input points \" << i << \" and \" << j <<\n                        \" are too close (dist(i,j) < \" << minimum_distance_\n                        << ')' << std::endl;\n                }\n\n                L_(i, j) = L_(j, i) = kernel_(d);\n            }\n        }\n\n        for (std::size_t i = 0; i < N; ++i)\n        {\n            L_.block<1, Domain_dim>(i, N + 1) = domain_points_[i].transpose();\n            L_.block<Domain_dim, 1>(N + 1, i) = domain_points_[i];\n        }\n\n        L_.col(N).setOnes();\n        L_.row(N).setOnes();\n        L_.bottomRightCorner < Domain_dim + 1, Domain_dim + 1 > ().setZero();\n    }\n\n    void update_Wa_matrix()\n    {\n        std::size_t N = domain_points_.size();\n        std::size_t M = N + 1 + Domain_dim;\n\n        Wa_.resize(M, Range_dim);\n        Wa_ = L_.fullPivLu().solve(Vt_);\n        double relative_error = (L_ * Wa_ - Vt_).norm() / Vt_.norm();\n\n        if (std::isnan(relative_error))\n        {\n            throw\n                std::runtime_error(\n                    \"Polyharmonic_spline_transformation::update_Wa_matrix(): \"\n                    \"Cannot define transformation (probably degenerate input \"\n                    \"points)\"\n                );\n        }\n\n        if (relative_error > max_relative_error_)\n        {\n            throw\n                std::runtime_error(\n                    \"Polyharmonic_spline_transformation::update_Wa_matrix(): \"\n                    \"Relative error too large\"\n                );\n        }\n\n        Matrix bending_norm = Matrix::Zero(1, 1);\n\n        for (std::size_t i = 0; i < Range_dim; ++i)\n        {\n            bending_norm += Wa_.block(0, i, N, 1).transpose()\n                * L_.block(0, 0, N, N) \n                * Wa_.block(0, i, N, 1);\n        }\n\n        bending_norm_ = bending_norm(0, 0);\n    }\n\n    Domain_points_container domain_points_;\n    Kernel_function         kernel_;\n    Matrix                  L_, Vt_, Wa_;\n    double                  bending_norm_, max_relative_error_;\n};\n\ntemplate < int Domain_dim, int Range_dim >\nclass Thin_plate_spline_transformation : public Polyharmonic_spline_transformation<\n                                            Domain_dim,\n                                            Range_dim,\n                                            Polyharmonic_spline_kernel< 2 > >\n{\n    typedef Polyharmonic_spline_transformation<\n        Domain_dim,\n        Range_dim,\n        Polyharmonic_spline_kernel< 2 > > Base;\n\npublic:\n    template< typename Forward_iterator_1, typename Forward_iterator_2 >\n    Thin_plate_spline_transformation(\n            Forward_iterator_1 domain_points_begin,\n            Forward_iterator_1 domain_points_end,\n            Forward_iterator_2 range_points_begin,\n            Forward_iterator_2 range_points_end,\n            double max_relative_error = 1.0e-8\n    )\n        : Base(domain_points_begin, domain_points_end, range_points_begin,\n                range_points_end, max_relative_error)\n    {}\n};\n\n} // namespace tps\n\n#endif // TPS_TPS_HPP\n", "meta": {"hexsha": "0c4e040887f707712719be100be3d0c984729511", "size": 9084, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wbs/src/Geomatic/tps.hpp", "max_stars_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_stars_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-05-26T21:19:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T14:17:29.000Z", "max_issues_repo_path": "wbs/src/Geomatic/tps.hpp", "max_issues_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_issues_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-02-18T12:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-13T12:57:45.000Z", "max_forks_repo_path": "wbs/src/Geomatic/tps.hpp", "max_forks_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_forks_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-16T02:49:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-16T02:49:20.000Z", "avg_line_length": 30.6891891892, "max_line_length": 92, "alphanum_fraction": 0.5773888155, "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.6115551076312691}}
{"text": "#ifndef MANIFOLDS_FUNCTIONS_TRIG_SIMPLIFICATIONS_HH\n#define MANIFOLDS_FUNCTIONS_TRIG_SIMPLIFICATIONS_HH\n\n#include \"multiplication.hh\"\n#include \"integral_polynomial.hh\"\n#include \"addition.hh\"\n#include \"division.hh\"\n#include <boost/mpl/map.hpp>\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/size.hpp>\n#include <boost/mpl/insert.hpp>\n#include <boost/mpl/contains.hpp>\n\nnamespace manifolds {\n\ntemplate <>\nstruct Simplification<Composition<IntegralPolynomial<0, 0, 1>, Cos>,\n                      /*mult_cos_cos*/ 0> {\n  static auto Combine(Composition<IntegralPolynomial<0, 0, 1>, Cos>) {\n    SIMPLIFY_INFO(\"Simplifying cos**2\\n\");\n    return ComposeRaw(IP<1, 0, -1>(), sin_);\n  }\n};\n\ntypedef boost::mpl::map<\n    boost::mpl::pair<Cos, ACos>, boost::mpl::pair<Sin, ASin>,\n    boost::mpl::pair<Tan, ATan>, boost::mpl::pair<Cosh, ACosh>,\n    boost::mpl::pair<Sinh, ASinh>, boost::mpl::pair<Tanh, ATanh> > RawInverses;\n\nstruct AddReverse {\n  template <class Map, class Elem> struct apply {\n    typedef typename boost::mpl::insert<\n        Map, boost::mpl::pair<typename Elem::second,\n                              typename Elem::first> >::type type;\n  };\n};\n\ntypedef boost::mpl::fold<RawInverses, RawInverses, AddReverse>::type Inverses;\n\nstatic_assert(boost::mpl::size<Inverses>::type::value == 12, \"\");\nstatic_assert(\n    boost::is_same<boost::mpl::at<Inverses, ATanh>::type, Tanh>::value, \"\");\nstatic_assert(\n    boost::mpl::contains<Inverses, boost::mpl::pair<Sin, ASin> >::value, \"\");\n\ntemplate <class F1, class F2>\nstruct Simplification<\n    Composition<F1, F2>, /*com_f_f_inv*/ 0,\n    typename std::enable_if<boost::mpl::contains<\n        Inverses, boost::mpl::pair<F1, F2> >::type::value>::type> {\n  static auto Combine(Composition<F1, F2>) { return IP<0, 1>(); }\n};\n\ntemplate <> struct Simplification<Composition<Sin, ACos>, 0> {\n  static auto Combine(Composition<Sin, ACos>) {\n    SIMPLIFY_INFO(\"Simplifying Sin(ACos)\\n\");\n    return sqrt_(IP<1, 0, -1>());\n  }\n};\n\ntemplate <> struct Simplification<Composition<Sin, ATan>, 0> {\n  static auto Combine(Composition<Sin, ATan>) {\n    SIMPLIFY_INFO(\"Simplifying Sin(ATan)\\n\");\n    auto hypo = sqrt_(IP<1, 0, 1>());\n    return DivideRaw(IP<0, 1>(), hypo);\n  }\n};\n\ntemplate <> struct Simplification<Composition<Cos, ASin>, 0> {\n  static auto Combine(Composition<Cos, ASin>) {\n    SIMPLIFY_INFO(\"Simplifying Cos(ASin)\\n\");\n    return sqrt_(IP<1, 0, -1>());\n  }\n};\n\ntemplate <> struct Simplification<Composition<Cos, ATan>, 0> {\n  static auto Combine(Composition<Cos, ATan>) {\n    SIMPLIFY_INFO(\"Simplifying Cos(ATan)\\n\");\n    auto hypo = sqrt_(IP<1, 0, 1>());\n    return DivideRaw(IP<1>(), hypo);\n  }\n};\n\ntemplate <> struct Simplification<Composition<Tan, ASin>, 0> {\n  static auto Combine(Composition<Tan, ASin>) {\n    SIMPLIFY_INFO(\"Simplifying Tan(ASin)\\n\");\n    return DivideRaw(IP<0, 1>(), IP<1, 0, -1>());\n  }\n};\n\ntemplate <> struct Simplification<Composition<Tan, ACos>, 0> {\n  static auto Combine(Composition<Tan, ACos>) {\n    SIMPLIFY_INFO(\"Simplifying Tan(ACos)\\n\");\n    return DivideRaw(IP<1>(), IP<1, 0, -1>());\n  }\n};\n\ntemplate <IPInt_t i, IPInt_t... cs> struct is_all_but_last_0 {\n  static const bool value = i == 0 && is_all_but_last_0<cs...>::value;\n  typedef bool_<value> type;\n};\n\ntemplate <IPInt_t i> struct is_all_but_last_0<i> {\n  static const bool value = true;\n  typedef bool_<value> type;\n};\n\ntemplate <IPInt_t i> using ic = std::integral_constant<IPInt_t, i>;\n\ntemplate <IPInt_t... coeffs>\nstruct Simplification<\n    Composition<Sin, IntegralPolynomial<coeffs...> >, 0,\n    typename std::enable_if<is_all_but_last_0<coeffs...>::value &&(\n        last<ic<coeffs>...>::type::value < 0)>::type> {\n\n  static auto Combine(Composition<Sin, IntegralPolynomial<coeffs...> >) {\n    SIMPLIFY_INFO(\"Simplifying Sin(-n*x^m)\\n\");\n    return Negative(sin_(Negative(IntegralPolynomial<coeffs...>())));\n  }\n};\n\ntemplate <IPInt_t... coeffs>\nstruct Simplification<\n    Composition<Sin, IntegralPolynomial<coeffs...> >, 0,\n    typename std::enable_if<\n        is_all_but_last_0<coeffs...>::value &&(sizeof...(coeffs) > 1) &&\n        (last<ic<coeffs>...>::type::value > 1)>::type> {\n  static const IPInt_t c = last<ic<coeffs>...>::type::value;\n  static const IPInt_t left = c / 2;\n  static const IPInt_t right = c - left;\n\n  template <std::size_t... indices>\n  static auto Combine(std::integer_sequence<std::size_t, indices...>) {\n    SIMPLIFY_INFO(\"Simplifying Sin(n*x^m)\\n\");\n    return std::make_pair(IP<(indices * 0)..., left>(),\n                          IP<(indices * 0)..., right>());\n  }\n\n  static auto Combine(Composition<Sin, IntegralPolynomial<coeffs...> >) {\n    SIMPLIFY_INFO(\"Simplifying Sin(n*x^m)\\n\");\n    auto subs = Combine(std::make_index_sequence<sizeof...(coeffs) - 1>());\n    auto left = subs.first;\n    auto right = subs.second;\n    return AddRaw(MultiplyRaw(sin_(left), cos_(right)),\n                  MultiplyRaw(cos_(left), sin_(right)));\n  }\n};\n\ntemplate <IPInt_t... coeffs>\nstruct Simplification<\n    Composition<Cos, IntegralPolynomial<coeffs...> >, 0,\n    typename std::enable_if<is_all_but_last_0<coeffs...>::value &&(\n        last<ic<coeffs>...>::type::value < 0)>::type> {\n\n  static auto Combine(Composition<Cos, IntegralPolynomial<coeffs...> >) {\n    SIMPLIFY_INFO(\"Simplifying Cos(-n*x^m)\\n\");\n    return cos_(Negative(IntegralPolynomial<coeffs...>()));\n  }\n};\n\ntemplate <IPInt_t... coeffs>\nstruct Simplification<\n    Composition<Cos, IntegralPolynomial<coeffs...> >, 0,\n    typename std::enable_if<\n        is_all_but_last_0<coeffs...>::value &&(sizeof...(coeffs) > 1) &&\n        (last<ic<coeffs>...>::type::value > 1)>::type> {\n  static const IPInt_t c = last<ic<coeffs>...>::type::value;\n  static const IPInt_t left = c / 2;\n  static const IPInt_t right = c - left;\n\n  template <std::size_t... indices>\n  static auto Combine(std::integer_sequence<std::size_t, indices...>) {\n    return std::make_pair(IP<(indices * 0)..., left>(),\n                          IP<(indices * 0)..., right>());\n  }\n\n  static auto Combine(Composition<Cos, IntegralPolynomial<coeffs...> >) {\n    SIMPLIFY_INFO(\"Simplifying Cos(n*x^m)\\n\");\n    auto subs = Combine(std::make_index_sequence<sizeof...(coeffs) - 1>());\n    auto left = subs.first;\n    auto right = subs.second;\n    return SubRaw(MultiplyRaw(cos_(left), cos_(right)),\n                  MultiplyRaw(sin_(left), sin_(right)));\n  }\n};\n\ntemplate <IPInt_t... coeffs> struct SplitPoly {\n  template <int i>\n  using ith = typename nth<i, std::integral_constant<IPInt_t, coeffs>...>::type;\n\n  template <int i, int DUMMY = 0> struct NonZero {\n    static const int index = sizeof...(coeffs) - 1 - i;\n    static const int value =\n        ith<index>::value == 0 ? NonZero<i - 1, 0>::value : i;\n  };\n\n  template <int DUMMY> struct NonZero<-1, DUMMY> {\n    static const int value = -1;\n  };\n\n  static const int first = NonZero<sizeof...(coeffs) - 1>::value;\n  static_assert(first != -1, \"\");\n\n  template <class> struct LeftPoly;\n\n  template <std::size_t... indices>\n  struct LeftPoly<std::integer_sequence<std::size_t, indices...> > {\n    typedef IntegralPolynomial<ith<indices>::value...> type;\n  };\n\n  template <class> struct RightPoly;\n\n  template <std::size_t... indices>\n  struct RightPoly<std::integer_sequence<std::size_t, indices...> > {\n    typedef std::tuple<std::integral_constant<IPInt_t, coeffs>...> tup;\n    typedef std::integral_constant<IPInt_t, 0> zero;\n    typedef decltype(replace_element<first>(tup(), zero())) tup_z;\n    typedef IntegralPolynomial<\n        std::tuple_element<indices, tup_z>::type::value...> type;\n  };\n\n  typedef boost::mpl::pair<\n      typename LeftPoly<std::make_index_sequence<first + 1> >::type,\n      typename RightPoly<std::make_index_sequence<sizeof...(coeffs)> >::type>\n  type;\n};\n\ntemplate <IPInt_t... coeffs>\nstruct Simplification<\n    Composition<Sin, IntegralPolynomial<coeffs...> >, 0,\n    typename std::enable_if<!is_all_but_last_0<coeffs...>::value>::type> {\n  typedef typename SplitPoly<coeffs...>::type Splits;\n  typedef typename Splits::first Left;\n  typedef typename Splits::second Right;\n\n  static auto Combine(Composition<Sin, IntegralPolynomial<coeffs...> >) {\n    SIMPLIFY_INFO(\"Simplifying Sin(poly + poly)\\n\");\n    return AddRaw(MultiplyRaw(Sin {}(Left{}), Cos {}(Right{})),\n                  MultiplyRaw(Cos {}(Left{}), Sin {}(Right{})));\n  }\n};\n\ntemplate <IPInt_t... coeffs>\nstruct Simplification<\n    Composition<Cos, IntegralPolynomial<coeffs...> >, 0,\n    typename std::enable_if<!is_all_but_last_0<coeffs...>::value>::type> {\n  typedef typename SplitPoly<coeffs...>::type Splits;\n  typedef typename Splits::first Left;\n  typedef typename Splits::second Right;\n\n  static auto Combine(Composition<Cos, IntegralPolynomial<coeffs...> >) {\n    SIMPLIFY_INFO(\"Simplifying Cos(poly + poly)\\n\");\n    return SubRaw(MultiplyRaw(Cos {}(Left{}), Cos {}(Right{})),\n                  MultiplyRaw(Sin {}(Left{}), Sin {}(Right{})));\n  }\n};\n\ntemplate <IPInt_t... coeffs>\nstruct Simplification<\n    Composition<Tan, IntegralPolynomial<coeffs...> >, 0,\n    typename std::enable_if<is_all_but_last_0<coeffs...>::value &&(\n        last<ic<coeffs>...>::type::value < 0)>::type> {\n  static auto Combine(Composition<Tan, IntegralPolynomial<coeffs...> >) {\n    return Negative(tan_(Negative(IP<coeffs...>())));\n  }\n};\n\ntemplate <IPInt_t... coeffs>\nstruct Simplification<\n    Composition<Tan, IntegralPolynomial<coeffs...> >, 1,\n    typename std::enable_if<is_all_but_last_0<coeffs...>::value &&(\n        last<ic<coeffs>...>::type::value > 1)>::type> {\n  template <class T, std::size_t... indices>\n  static auto Process(T, std::integer_sequence<std::size_t, indices...>) {\n    return IP<std::tuple_element<indices, T>::type::value...>();\n  }\n  static auto Combine(Composition<Tan, IntegralPolynomial<coeffs...> >) {\n    static const IPInt_t last_c = last<ic<coeffs>...>::type::value;\n    static const int last_i = sizeof...(coeffs) - 1;\n    static const IPInt_t left = last_c / 2;\n    static const IPInt_t right = last_c - left;\n    typedef std::tuple<std::integral_constant<IPInt_t, coeffs>...> tup;\n    typedef std::integral_constant<IPInt_t, left> Left;\n    typedef std::integral_constant<IPInt_t, right> Right;\n    std::make_index_sequence<sizeof...(coeffs)> indices;\n    auto left_p = Process(replace_element<last_i>(tup(), Left()), indices);\n    auto right_p = Process(replace_element<last_i>(tup(), Right()), indices);\n    return DivideRaw(AddRaw(tan_(left_p), tan_(right_p)),\n                     IP<1, 1>()(MultiplyRaw(tan_(left_p), tan_(right_p))));\n  }\n};\n\ntemplate <IPInt_t... coeffs>\nstruct Simplification<\n    Composition<Tan, IntegralPolynomial<coeffs...> >, 0,\n    typename std::enable_if<!is_all_but_last_0<coeffs...>::value>::type> {\n  static auto Combine(Composition<Tan, IntegralPolynomial<coeffs...> >) {\n    typedef typename SplitPoly<coeffs...>::type Pair;\n    typename Pair::first left;\n    typename Pair::second right;\n    return DivideRaw(AddRaw(tan_(left), tan_(right)),\n                     IP<1, 1>()(MultiplyRaw(tan_(left), tan_(right))));\n  }\n};\n\ntemplate <IPInt_t... coeffs>\nstruct Simplification<Composition<IntegralPolynomial<coeffs...>, Sqrt>, 0,\n                      typename std::enable_if<(sizeof...(coeffs) > 2)>::type> {\n  template <int i>\n  using ith = typename nth<i, std::integral_constant<IPInt_t, coeffs>...>::type;\n\n  template <int, class, class> struct Process;\n\n  template <int i, IPInt_t... evens, IPInt_t... odds>\n  struct Process<i, std::integer_sequence<IPInt_t, evens...>,\n                 std::integer_sequence<IPInt_t, odds...> > {\n    typedef typename std::conditional<\n        i % 2 == 0, std::integer_sequence<IPInt_t, ith<i>::value, evens...>,\n        std::integer_sequence<IPInt_t, evens...> >::type nes;\n\n    typedef typename std::conditional<\n        i % 2 == 1, std::integer_sequence<IPInt_t, ith<i>::value, odds...>,\n        std::integer_sequence<IPInt_t, odds...> >::type nos;\n\n    typedef typename Process<i - 1, nes, nos>::type type;\n  };\n\n  template <IPInt_t... evens, IPInt_t... odds>\n  struct Process<-1, std::integer_sequence<IPInt_t, evens...>,\n                 std::integer_sequence<IPInt_t, odds...> > {\n    typedef boost::mpl::pair<IntegralPolynomial<evens...>,\n                             IntegralPolynomial<odds...> > type;\n  };\n\n  static auto Combine(Composition<IntegralPolynomial<coeffs...>, Sqrt>) {\n    typedef typename Process<sizeof...(coeffs) - 1,\n                             std::integer_sequence<IPInt_t>,\n                             std::integer_sequence<IPInt_t> >::type Pair;\n    typedef typename Pair::first Evens;\n    typedef typename Pair::second Odds;\n    return AddRaw(Evens(), MultiplyRaw(Odds(), sqrt_));\n  }\n};\n}\n\n#endif\n", "meta": {"hexsha": "002031737f71efcf5a50cb1b10bc1695af6aaa32", "size": 12681, "ext": "hh", "lang": "C++", "max_stars_repo_path": "functions/std_functions_simplifications.hh", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/std_functions_simplifications.hh", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/std_functions_simplifications.hh", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["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.5446685879, "max_line_length": 80, "alphanum_fraction": 0.6515259049, "num_tokens": 3625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.6113308232030196}}
{"text": "#include <math.h>\n#include <iostream>\n#include <armadillo>\n#include <vector>\n#include <complex>\n#include <fftw3.h>\n#include \"mkl.h\"\n\n#include \"tensor.h\"\nusing namespace std;\n\n#include \"time.h\"\ndouble gettime(){\n    struct timeval tv;\n    gettimeofday(&tv,NULL);\n    return tv.tv_sec*1000+tv.tv_usec/1000.0; //time:s\n};\n\nusing namespace std;\nusing namespace arma;\n\nint main() {\n    double t0,t1;\n    int I=100;\n    int R=0.2*I;\n    Tensor<float> a(I,I,I);\n    for (int i = 0; i < a.n1; ++i) {\n        for (int j = 0; j < a.n2; ++j) {\n            for(int k=0; k<a.n3; ++k) {\n                a(i,j,k) = randu();\n            }\n        }\n    }\n    cout << sizeof(a(1,1,1)) << endl;\n//    Tensor<double> g(1,1,1);\n//    mat u1(2,1);\n//    mat u2(2,1);\n//    mat u3(2,1);\n//    tuckercore<double> A{g,u1,u2,u3};\n//\n    cout << \"time:\" <<endl;\n    t0=gettime();\n        HOSVD(a,R,R,R);\n//    cp_als(a,R);\n    t1=gettime();\n\n    cout << \"time:\" <<t1-t0 <<endl;\n//    Tensor<double> b(2,3,5),d(5,5,5), z(2,3,4),t(5,5,5);\n//    cout<<z(0,1,2)<<endl;\n//\n//    z=z.zeros(2,3,4);\n//    cout<<z(0,1,2)+123<<endl;\n//\n//    int *c=getsize(b);\n//    cout<<c[0]<<endl; //tensor\u5927\u5c0f\n//    cout<<sizeof(a)<<endl;\n//    cout<<norm(a)<<endl;\n//\n//    cout << \"Hello, World!\" << endl;\n//    cout<<t(1,2,3)<<endl;\n//    cout<<norm(a)<<endl;\n\n\n//    mat m1 = ten2mat(a,1);\n//    cout << m1 << endl;\n//\n//    mat m2 = ten2mat(a,2);\n//    cout << m2 << endl;\n//\n//    mat m3 = ten2mat(a,3);\n//    cout << m3 << endl;\n\n//    cout<<slice(a,0,2)<<endl;\n//slice\n//    cout<<fiber(a,1,2,2)<<endl;\n    return 0;\n\n}", "meta": {"hexsha": "b2e22b86f3fedf9ce8e3d953226408e2ea28b0c9", "size": 1578, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "float/main.cpp", "max_stars_repo_name": "Forsworns/Transform-based-Tensor-Model", "max_stars_repo_head_hexsha": "d86dd5f6b115068b80b16ead0d1d48371f4669ed", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "float/main.cpp", "max_issues_repo_name": "Forsworns/Transform-based-Tensor-Model", "max_issues_repo_head_hexsha": "d86dd5f6b115068b80b16ead0d1d48371f4669ed", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "float/main.cpp", "max_forks_repo_name": "Forsworns/Transform-based-Tensor-Model", "max_forks_repo_head_hexsha": "d86dd5f6b115068b80b16ead0d1d48371f4669ed", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.2307692308, "max_line_length": 58, "alphanum_fraction": 0.4904942966, "num_tokens": 592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.6113308207701081}}
{"text": "#include \"DarkART/Radial_Integrator.hpp\"\n\n#include <cmath>\n#include <functional>\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n\n#include \"libphysica/Integration.hpp\"\n#include \"libphysica/Natural_Units.hpp\"\n#include \"libphysica/Utilities.hpp\"\n\n#include \"DarkART/Special_Functions.hpp\"\n\nnamespace DarkART\n{\n\nusing namespace libphysica::natural_units;\n\ndouble Radial_Integrator::Radial_Integral_Adaptive(unsigned int integral_index, double k_final, double q, int l_final, int L)\n{\n\tstd::function<double(double)> integrand = [this, integral_index, L, q, k_final, l_final](double r) {\n\t\tswitch(integral_index)\n\t\t{\n\t\t\tcase 1:\n\t\t\t\treturn r * r * initial_state.Radial_Wavefunction(r) * final_state->Radial_Wavefunction(r, k_final, l_final) * Spherical_Bessel_jL(L, q * r);\n\t\t\tcase 2:\n\t\t\t\treturn r * r * initial_state.Radial_Wavefunction_Derivative(r) * final_state->Radial_Wavefunction(r, k_final, l_final) * Spherical_Bessel_jL(L, q * r);\n\t\t\tcase 3:\n\t\t\t\treturn r * initial_state.Radial_Wavefunction(r) * final_state->Radial_Wavefunction(r, k_final, l_final) * Spherical_Bessel_jL(L, q * r);\n\t\t\tdefault:\n\t\t\t\tstd::cerr << \"Radial_Integrator::Radial_Integral_Adaptive(): Integral I_\" << integral_index << \" not defined.\" << std::endl;\n\t\t\t\tstd::exit(EXIT_FAILURE);\n\t\t}\n\t};\n\t// Integrate stepwise\n\tdouble stepsize\t = 0.5 * Bohr_Radius;\n\tdouble integral\t = 0.0;\n\tdouble epsilon_1 = 1.0, epsilon_2 = 1.0;\n\tdouble tolerance = 1.0e-6;\n\tunsigned int i;\n\tfor(i = 0; epsilon_1 > tolerance || epsilon_2 > tolerance; i++)\n\t{\n\t\tepsilon_2\t\t\t\t= epsilon_1;\n\t\tdouble new_contribution = boost::math::quadrature::gauss_kronrod<double, 41>::integrate(integrand, i * stepsize, (i + 1) * stepsize, 5, 1e-9);\n\n\t\tintegral += new_contribution;\n\t\tepsilon_1 = std::fabs(new_contribution / integral);\n\t}\n\treturn integral;\n}\n\nvoid Radial_Integrator::Tabulate_Initial_Wavefunction()\n{\n\tfor(unsigned int ri = 0; ri < r_points; ri++)\n\t{\n\t\tinitial_radial_wavefunction_list[ri]\t\t\t= initial_state.Radial_Wavefunction(r_values_and_weights[ri][0]);\n\t\tinitial_radial_wavefunction_derivative_list[ri] = initial_state.Radial_Wavefunction_Derivative(r_values_and_weights[ri][0]);\n\t}\n}\n\nvoid Radial_Integrator::Tabulate_Final_Wavefunction(int l_final, int ki)\n{\n\tif(l_final >= l_final_max_max)\n\t{\n\t\tstd::cerr << \"Error in Radial_Integrator::Tabulate_Final_Wavefunction(): l_final_max_max = \" << l_final_max_max << \" exceeded.\" << std::endl;\n\t\tstd::exit(EXIT_FAILURE);\n\t}\n\tfor(int li = l_final_max[ki] + 1; li <= l_final; li++)\n\t\tfor(unsigned int ri = 0; ri < r_points; ri++)\n\t\t\tfinal_radial_wavefunction_list[ki][li][ri] = final_state->Radial_Wavefunction(r_values_and_weights[ri][0], k_grid[ki], li);\n\tl_final_max[ki] = l_final;\n}\n\nvoid Radial_Integrator::Tabulate_Bessel_Function(int Lmax, int qi)\n{\n\tif(Lmax >= l_final_max_max + 2)\n\t{\n\t\tstd::cerr << \"Error in Radial_Integrator::Tabulate_Bessel_Function(): L_max_max = \" << l_final_max_max + 2 << \" exceeded.\" << std::endl;\n\t\tstd::exit(EXIT_FAILURE);\n\t}\n\tfor(int L = L_max[qi] + 1; L <= Lmax; L++)\n\t\tfor(unsigned int ri = 0; ri < r_points; ri++)\n\t\t\tbessel_function_list[qi][L][ri] = Spherical_Bessel_jL(L, q_grid[qi] * r_values_and_weights[ri][0]);\n\tL_max[qi] = Lmax;\n}\n\ndouble Radial_Integrator::Radial_Integral_Table(unsigned int integral_index, double k_final, double q, int l_final, int L)\n{\n\t// Identify ki and qi\n\tint ki = libphysica::Locate_Closest_Location(k_grid, k_final);\n\tint qi = libphysica::Locate_Closest_Location(q_grid, q);\n\n\t// Check if the tables have been computed for l_final and L\n\tif(l_final > l_final_max[ki])\n\t\tTabulate_Final_Wavefunction(l_final, ki);\n\tif(L > L_max[qi])\n\t\tTabulate_Bessel_Function(L, qi);\n\n\t// Sum up the integral\n\tdouble integral = 0.0;\n\tfor(unsigned int ri = 0; ri < r_values_and_weights.size(); ri++)\n\t{\n\t\tdouble r\t  = r_values_and_weights[ri][0];\n\t\tdouble weight = r_values_and_weights[ri][1];\n\n\t\tif(integral_index == 1)\n\t\t\tintegral += weight * r * r * initial_radial_wavefunction_list[ri] * final_radial_wavefunction_list[ki][l_final][ri] * bessel_function_list[qi][L][ri];\n\t\telse if(integral_index == 2)\n\t\t\tintegral += weight * r * r * initial_radial_wavefunction_derivative_list[ri] * final_radial_wavefunction_list[ki][l_final][ri] * bessel_function_list[qi][L][ri];\n\t\telse if(integral_index == 3)\n\t\t\tintegral += weight * r * initial_radial_wavefunction_list[ri] * final_radial_wavefunction_list[ki][l_final][ri] * bessel_function_list[qi][L][ri];\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"Radial_Integrator::Radial_Integral_Table(): Integral I_\" << integral_index << \" not defined.\" << std::endl;\n\t\t\tstd::exit(EXIT_FAILURE);\n\t\t}\n\t}\n\treturn integral;\n}\n\nRadial_Integrator::Radial_Integrator()\n: using_function_tabulation(false), initial_state()\n{\n}\n\nRadial_Integrator::Radial_Integrator(const Initial_Electron_State& ini_state, const Final_Electron_State& fin_state)\n: using_function_tabulation(false), initial_state(ini_state)\n{\n\tfinal_state = fin_state.Clone();\n}\n\ndouble Radial_Integrator::Radial_Integral(int integral_index, double k_final, double q, int l_final, int L)\n{\n\tif(using_function_tabulation)\n\t\treturn Radial_Integral_Table(integral_index, k_final, q, l_final, L);\n\telse\n\t\treturn Radial_Integral_Adaptive(integral_index, k_final, q, l_final, L);\n}\n\nvoid Radial_Integrator::Use_Tabulated_Functions(unsigned int rpoints, const std::vector<double>& k_list, const std::vector<double>& q_list)\n{\n\tusing_function_tabulation = true;\n\tk_grid\t\t\t\t\t  = k_list;\n\tq_grid\t\t\t\t\t  = q_list;\n\tl_final_max\t\t\t\t  = std::vector<int>(k_grid.size(), -1);\n\tL_max\t\t\t\t\t  = std::vector<int>(q_grid.size(), -1);\n\n\tr_points\t\t\t = rpoints;\n\tr_max\t\t\t\t = 50.0 * Bohr_Radius;\n\tr_values_and_weights = libphysica::Compute_Gauss_Legendre_Roots_and_Weights(r_points, 0.0, r_max);\n\n\tinitial_radial_wavefunction_list\t\t\t= std::vector<double>(r_points, 0.0);\n\tinitial_radial_wavefunction_derivative_list = std::vector<double>(r_points, 0.0);\n\tTabulate_Initial_Wavefunction();\n\n\t// 2. Initiate final radial wavefunctions and Bessel function list\n\tfinal_radial_wavefunction_list = std::vector<std::vector<std::vector<double>>>(k_grid.size(), std::vector<std::vector<double>>(l_final_max_max, std::vector<double>(r_points, 0.0)));\n\tbessel_function_list\t\t   = std::vector<std::vector<std::vector<double>>>(q_grid.size(), std::vector<std::vector<double>>(l_final_max_max + 2, std::vector<double>(r_points, 0.0)));\n}\n\nvoid Radial_Integrator::Set_New_States(const Initial_Electron_State& new_initial_state, const Final_Electron_State& new_final_state)\n{\n\t// New states\n\tinitial_state = new_initial_state;\n\tfinal_state\t  = new_final_state.Clone();\n\n\tif(using_function_tabulation)\n\t{\n\t\t// 1. Tabulate initial radial wavefunction\n\t\tTabulate_Initial_Wavefunction();\n\n\t\t// 2. Reset the final state wavefunction lists\n\t\tl_final_max\t\t\t\t\t   = std::vector<int>(k_grid.size(), -1);\n\t\tfinal_radial_wavefunction_list = std::vector<std::vector<std::vector<double>>>(k_grid.size(), std::vector<std::vector<double>>(l_final_max_max, std::vector<double>(r_points, 0.0)));\n\t}\n}\n\n}\t// namespace DarkART", "meta": {"hexsha": "bcb99646ce59483ea0048128aa65648d42b7ba1d", "size": 6994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Radial_Integrator.cpp", "max_stars_repo_name": "temken/DarkART", "max_stars_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-15T13:58:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T13:58:28.000Z", "max_issues_repo_path": "src/Radial_Integrator.cpp", "max_issues_repo_name": "temken/DarkART", "max_issues_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Radial_Integrator.cpp", "max_forks_repo_name": "temken/DarkART", "max_forks_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2921348315, "max_line_length": 183, "alphanum_fraction": 0.7380611953, "num_tokens": 2013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.6113308103470323}}
{"text": "#include <Core/Core.h>\n\n#include <Eigen/Eigen.h>\n#include <Surface/Surface.h>\n#include <Geom/Geom.h>\n#include <Functions4U/Functions4U.h>\n#include <numeric> \n\nnamespace Upp {\nusing namespace Eigen;\n\nPoint3D GetCentroid(const Point3D &a, const Point3D &b) {\n\treturn Point3D(avg(a.x, b.x), avg(a.y, b.y), avg(a.z, b.z));\t\n}\n\nPoint3D GetCentroid(const Point3D &a, const Point3D &b, const Point3D &c) {\n\treturn Point3D(avg(a.x, b.x,c.x), avg(a.y, b.y, c.y), avg(a.z, b.z, c.z));\t\n}\n\nVector3D GetNormal(const Point3D &a, const Point3D &b, const Point3D &c) {\n\treturn Vector3D((a - b) % (b - c)).Normalize();\n}\n\nPoint3D Intersection(const Vector3D &lineVector, const Point3D &linePoint, const Point3D &planePoint, const Vector3D &planeNormal) {\n\tVector3D diff = planePoint - linePoint;\n\tdouble prod1 = diff.dot(planeNormal);\n\tdouble prod2 = lineVector.dot(planeNormal);\n\tif (abs(prod2) < EPS_XYZ)\n\t\treturn Null;\n\tdouble factor = prod1/prod2;\n\treturn linePoint + lineVector*factor;\t\n}\n\nvoid Point3D::Translate(double dx, double dy, double dz) {\n\tx += dx;\n\ty += dy;\n\tz += dz;\n}\n\nvoid Point3D::Rotate(double da_x, double da_y, double da_z, double c_x, double c_y, double c_z) {\n\tAffine3d aff;\n\tGetTransform(aff, da_x, da_y, da_z, c_x, c_y, c_z);\n\tRotate(aff);\n}\n\nvoid Point3D::Rotate(const Affine3d &quat) {\n\tVector3d pnt0(x, y, z);\t\n\tVector3d pnt = quat * pnt0;\n\n\tx = pnt[0];\n\ty = pnt[1];\n\tz = pnt[2];\n}\n\nvoid GetTransform(Affine3d &aff, double a_x, double a_y, double a_z, double c_x, double c_y, double c_z) {\n\tVector3d c(c_x, c_y, c_z);\t\n\taff =\tTranslation3d(c) *\n\t\t\tAngleAxisd(a_x*M_PI/180, Vector3d::UnitX()) *\n\t\t \tAngleAxisd(a_y*M_PI/180, Vector3d::UnitY()) *\n\t\t \tAngleAxisd(a_z*M_PI/180, Vector3d::UnitZ()) *\n\t\t \tTranslation3d(-c);\n}\n\nPoint3D Segment3D::IntersectionPlaneX(double x) {\n\tif (from.x >= x && to.x >= x)\n\t\treturn Point3D(true);\n\tif (from.x <= x && to.x <= x)\n\t\treturn Point3D(false);\n\t\n\tdouble factor = (x - from.x)/(to.x - from.x);\n\treturn Point3D(x, from.y + (to.y - from.y)*factor, from.z + (to.z - from.z)*factor);\n}\n\nPoint3D Segment3D::IntersectionPlaneY(double y) {\n\tif (from.y >= y && to.y >= y)\n\t\treturn Point3D(true);\n\tif (from.y <= y && to.y <= y)\n\t\treturn Point3D(false);\n\t\n\tdouble factor = (y - from.y)/(to.y - from.y);\n\treturn Point3D(from.x + (to.x - from.x)*factor, y, from.z + (to.z - from.z)*factor);\n}\n\nPoint3D Segment3D::IntersectionPlaneZ(double z) {\n\tif (from.z >= z && to.z >= z)\n\t\treturn Point3D(true);\n\tif (from.z <= z && to.z <= z)\n\t\treturn Point3D(false);\n\t\n\tdouble factor = (z - from.z)/(to.z - from.z);\n\treturn Point3D(from.x + (to.x - from.x)*factor, from.y + (to.y - from.y)*factor, z);\n}\n\nPoint3D Segment3D::Intersection(const Point3D &planePoint, const Vector3D &planeNormal) {\n\tVector3D vector = Vector();\n\tVector3D diff = planePoint - from;\n\tdouble prod1 = diff.dot(planeNormal);\n\tdouble prod2 = vector.dot(planeNormal);\n\tif (abs(prod2) < EPS_XYZ)\n\t\treturn Null;\n\tdouble factor = prod1/prod2;\n\tif (factor >= 1)\n\t\treturn Point3D(true);\n\tif (factor <= 0)\n\t\treturn Point3D(false);\n\treturn from + vector*factor;\t\n}\n\nbool Segment3D::PointIn(const Point3D &p) const {\n\treturn PointInSegment(p, *this);\n}\n\nbool Segment3D::SegmentIn(const Segment3D &in) const {\n\treturn SegmentInSegment(in, *this);\n}\n\nbool Segment3D::SegmentIn(const Segment3D &in, double in_len) const {\n\treturn SegmentInSegment(in, in_len, *this);\n}\n\n\nbool PointInSegment(const Point3D &p, const Segment3D &seg) {\n\tdouble dpa = p.Distance(seg.from);\n\tdouble dpb = p.Distance(seg.to);\n\tdouble dab = seg.Length();\n\t\n\treturn abs(dpa + dpb - dab) < EPS_XYZ;\n}\n\nbool SegmentInSegment(const Segment3D &in, double in_len, const Segment3D &seg) {\n\tdouble seg_len = seg.Length();\n\t\n\tdouble seg_from_in_from = seg.from.Distance(in.from);\n\tdouble in_to_seg_to = in.to.Distance(seg.to);\n\tif (abs(seg_from_in_from + in_len + in_to_seg_to - seg_len) < EPS_XYZ)\n\t\treturn true;\n\n\tdouble seg_from_in_to = seg.from.Distance(in.to);\n\tdouble in_from_seg_to = in.from.Distance(seg.to);\n\tif (abs(seg_from_in_to + in_len + in_from_seg_to - seg_len) < EPS_XYZ)\n\t\treturn true;\n\t\n\treturn false;\n}\n\nbool SegmentInSegment(const Segment3D &in, const Segment3D &seg) {\n\treturn SegmentInSegment(in, in.Length(), seg);\n}\n\nvoid Surface::Clear() {\n\tnodes.Clear();\n\tpanels.Clear();\n\tskewed.Clear();\n\tsegWaterlevel.Clear();\n\tsegTo1panel.Clear();\n\tsegTo3panel.Clear();\n\tsegments.Clear();\n\tselPanels.Clear();\n\tselNodes.Clear();\n}\n\nSurface::Surface(const Surface &orig, int) {\n\thealing = orig.healing;\n\tnumTriangles = orig.numTriangles;\n\tnumBiQuads = orig.numBiQuads;\n\tnumMonoQuads = orig.numMonoQuads;\n\t\n\tpanels = clone(orig.panels);\n\tnodes = clone(orig.nodes);\n\tskewed = clone(orig.skewed);\n\tsegWaterlevel = clone(orig.segWaterlevel);\n\tsegTo1panel = clone(orig.segTo1panel);\n\tsegTo3panel = clone(orig.segTo3panel);\n\tsegments = clone(orig.segments);\n\t\n\tenv = clone(orig.env);\n\t\n\tsurface = orig.surface;\n\tvolume = orig.volume;\n\tvolumex = orig.volumex;\n\tvolumey = orig.volumey;\n\tvolumez = orig.volumez;\n}\n\nbool Surface::IsEmpty() {\n\treturn nodes.IsEmpty();\n}\n\nbool Surface::FixSkewed(int ipanel) {\n\tPanel &pan = panels[ipanel];\n\t\n\tint &id0 = pan.id[0];\n\tint &id1 = pan.id[1];\n\tint &id2 = pan.id[2];\n\tint &id3 = pan.id[3];\n\tPoint3D &p0 = nodes[id0];\n\tPoint3D &p1 = nodes[id1];\n\tPoint3D &p2 = nodes[id2];\n\tPoint3D &p3 = nodes[id3];\n\tif (id0 != id3) {\t\t// Is not triangular \n\t\tVector3D normal301 = GetNormal(p3, p0, p1);\n\t\tVector3D normal012 = GetNormal(p0, p1, p2);\n\t\tVector3D normal123 = GetNormal(p1, p2, p3);\n\t\tVector3D normal230 = GetNormal(p2, p3, p0);\n\t\tdouble d0  = normal301.Manhattan();\n\t\tdouble d01 = normal301.Manhattan(normal012);\n\t\tdouble d02 = normal301.Manhattan(normal123);\n\t\tdouble d03 = normal301.Manhattan(normal230);\n\t\t\n\t\tint numg = 0;\n\t\tif (d0 < d01)\n\t\t\tnumg++;\n\t\tif (d0 < d02)\n\t\t\tnumg++;\n\t\tif (d0 < d03)\n\t\t\tnumg++;\t \n\t\tif (numg > 1) {\n\t\t\tskewed << Segment3D(p0, p1) << Segment3D(p1, p2) << Segment3D(p2, p3) << Segment3D(p3, p0);\n\t\t\t\n\t\t\tif (d0 < d01)\n\t\t\t\tSwap(pan.id[1], pan.id[2]);\n\t\t\telse if (d0 < d02)\n\t\t\t\tSwap(pan.id[2], pan.id[3]);\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nint Surface::FixSkewed() {\t\n\tint num = 0;\n\tfor (int i = 0; i < panels.GetCount(); ++i) \n\t\tif (FixSkewed(i))\n\t\t\tnum++;\n\treturn num;\n}\n\nvoid Surface::DetectTriBiP(Vector<Panel> &panels, int &numTri, int &numBi, int &numP) {\n\tnumTri = numBi = numP = 0;\n\tfor (int i = panels.GetCount()-1; i >= 0; --i) {\n\t\tPanel &panel = panels[i];\n\t\tUpp::Index<int> ids;\n\t\tids.FindAdd(panel.id[0]);\n\t\tids.FindAdd(panel.id[1]);\n\t\tids.FindAdd(panel.id[2]);\n\t\tids.FindAdd(panel.id[3]);\n\t\tif (ids.GetCount() == 4)\n\t\t\t;\n\t\telse if (ids.GetCount() == 3) {\n\t\t\tnumTri++;\n\t\t\tpanel.id[0] = ids[0];\n\t\t\tpanel.id[1] = ids[1];\n\t\t\tpanel.id[2] = ids[2];\t\n\t\t\tpanel.id[3] = ids[0];\t\n\t\t} else if (ids.GetCount() == 2) {\n\t\t\tnumBi++;\n\t\t\tpanels.Remove(i, 1);\n\t\t} else {\n\t\t\tnumP++;\n\t\t\tpanels.Remove(i, 1);\n\t\t}\n\t}\n}\n\nvoid Surface::TriangleToQuad(Panel &pan) {\n\tpanels << pan;\n\tTriangleToQuad(panels.GetCount() - 1);\n}\n\nvoid Surface::TriangleToQuad(int ipanel) {\n\tPanel &pan00 = panels[ipanel];\n\tint id0 = pan00.id[0];\n\tint id1 = pan00.id[1];\n\tint id2 = pan00.id[2];\n\tPoint3D &p0 = nodes[id0];\n\tPoint3D &p1 = nodes[id1];\n\tPoint3D &p2 = nodes[id2];\n\t\t\n\tPoint3D p012= GetCentroid(p0, p1, p2);\tnodes.Add(p012);\tint id012= nodes.GetCount()-1;\n\tPoint3D p01 = GetCentroid(p0, p1);\t\tnodes.Add(p01);\t\tint id01 = nodes.GetCount()-1;\n\tPoint3D p12 = GetCentroid(p1, p2);\t\tnodes.Add(p12);\t\tint id12 = nodes.GetCount()-1;\n\tPoint3D p20 = GetCentroid(p2, p0);\t\tnodes.Add(p20);\t\tint id20 = nodes.GetCount()-1;\n\t\n\tpanels.Remove(ipanel, 1);\n\tPanel &pan0 = panels.Add();\tpan0.id[0] = id0;\tpan0.id[1] = id01;\tpan0.id[2] = id012;\tpan0.id[3] = id20;\n\tPanel &pan1 = panels.Add();\tpan1.id[0] = id01;\tpan1.id[1] = id1;\tpan1.id[2] = id12;\tpan1.id[3] = id012;\n\tPanel &pan2 = panels.Add();\tpan2.id[0] = id012;\tpan2.id[1] = id12;\tpan2.id[2] = id2;\tpan2.id[3] = id20;\n}\n\nint Surface::RemoveDuplicatedPanels(Vector<Panel> &_panels) {\t\t\n\tint num = 0;\n\tfor (int i = 0; i < _panels.GetCount()-1; ++i) {\n\t\tPanel &panel = _panels[i];\n\t\tfor (int j = _panels.GetCount()-1; j >= i+1; --j) {\n\t\t\tif (panel == _panels[j]) {\n\t\t\t\tnum++;\n\t\t\t\t_panels.Remove(j, 1);\n\t\t\t}\n\t\t}\n\t}\n\treturn num;\n}\n\nint Surface::RemoveTinyPanels(Vector<Panel> &_panels) {\t\t\n\tint num = 0;\n\tdouble avgsurface = 0;\n\tfor (int i = 0; i < _panels.GetCount(); ++i) \n\t\tavgsurface += _panels[i].surface0 + _panels[i].surface1;\n\tavgsurface /= _panels.GetCount();\n\tdouble tiny = avgsurface/1000000;\n\t\t\t\n\tfor (int i = _panels.GetCount()-1; i >= 0; --i) {\n\t\tdouble surface = _panels[i].surface0 + _panels[i].surface1;\n\t\tif (surface < tiny) {\n\t\t\tnum++;\n\t\t\t_panels.Remove(i, 1);\n\t\t}\n\t}\n\treturn num;\n}\n\nint Surface::RemoveDuplicatedPointsAndRenumber(Vector<Panel> &_panels, Vector<Point3D> &_nodes) {\n\tint num = 0;\n\t\n\t// Detect duplicated points in nodes\n\tdouble similThres = EPS_XYZ;\n\tUpp::Index<int> duplic, goods;\n\tfor (int i = 0; i < _nodes.GetCount()-1; ++i) {\n\t\tif (duplic.Find(i) >= 0)\n\t\t\tcontinue;\n\t\tfor (int j = i+1; j < _nodes.GetCount(); ++j) {\n\t\t\tif (_nodes[i].IsSimilar(_nodes[j], similThres)) {\n\t\t\t\tduplic << j;\n\t\t\t\tgoods << i;\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Replace duplicated points with good ones in panels\n\tfor (int i = 0; i < _panels.GetCount(); ++i) {\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tint &id = _panels[i].id[j];\n\t\t\tint pos = duplic.Find(id);\n\t\t\tif (pos >= 0)\n\t\t\t\tid = goods[pos];\n\t\t}\n\t}\n\t\n\t// Find unused nodes\n\tVector<int> newId;\n\tnewId.SetCount(_nodes.GetCount());\n\tint avId = 0;\n\tfor (int i = 0; i < _nodes.GetCount(); ++i) {\n\t\tbool found = false;\n\t\tfor (int ip = 0; ip < _panels.GetCount() && !found; ++ip) {\n\t\t\tint numP = PanelGetNumNodes(_panels, ip);\n\t\t\tfor (int j = 0; j < numP; ++j) {\n\t\t\t\tif (_panels[ip].id[j] == i) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!found)\n\t\t\tnewId[i] = Null;\t// Remove unused nodes\n\t\telse if (duplic.Find(i) >= 0)\n\t\t\tnewId[i] = Null;\t\n \t\telse {\t\n\t\t\tnewId[i] = avId;\n\t\t\tavId++;\n\t\t} \n\t}\n\t\n\t// Remove duplicated nodes\n\tfor (int i = _nodes.GetCount()-1; i >= 0; --i) {\n\t\tif (IsNull(newId[i]))\n\t\t\t_nodes.Remove(i, 1);\n\t}\n\t\n\t// Renumber panels\n\tfor (int i = 0; i < _panels.GetCount(); ++i) {\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tint& id = _panels[i].id[j];\n\t\t\tid = newId[id];\n\t\t}\n\t}\n\treturn num;\n}\n\t\nvoid Surface::AddSegment(int inode0, int inode1, int ipanel) {\n\tASSERT(!IsNull(inode0));\n\tASSERT(!IsNull(inode1));\n\tfor (int i = 0; i < segments.GetCount(); ++i) {\n\t\tif ((segments[i].inode0 == inode0 && segments[i].inode1 == inode1) ||\n\t\t\t(segments[i].inode1 == inode0 && segments[i].inode0 == inode1)) {\n\t\t\tsegments[i].panels << ipanel;\n\t\t\treturn;\n\t\t}\n\t}\n\tSegment &sg = segments.Add();\n\tsg.inode0 = inode0;\n\tsg.inode1 = inode1;\n\tsg.panels << ipanel;\n}\n\nint Surface::SegmentInSegments(int iseg) const {\n\tSegment3D seg(nodes[segments[iseg].inode0], nodes[segments[iseg].inode1]);\n\tdouble lenSeg = seg.Length();\n\t\t\t\n\tfor (int i = 0; i < segments.GetCount(); ++i) {\n\t\tif (i != iseg) {\n\t\t\tconst Segment &segment = segments[i];\n\t\t\tSegment3D is(nodes[segment.inode0], nodes[segment.inode1]);\n\t\t\tif (is.SegmentIn(seg, lenSeg))\t\t\n\t\t\t\treturn i;\n\t\t\tif (seg.SegmentIn(is))\n\t\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}\n\nvoid Surface::GetSegments() {\n\tsegments.Clear();\n\t\t\n\tfor (int i = 0; i < panels.GetCount(); ++i) {\n\t\tint id0 = panels[i].id[0];\n\t\tint id1 = panels[i].id[1];\n\t\tint id2 = panels[i].id[2];\n\t\tint id3 = panels[i].id[3];\n\t\tAddSegment(id0, id1, i);\n\t\tAddSegment(id1, id2, i);\n\t\tif (IsPanelTriangle(i)) \n\t\t\tAddSegment(id2, id0, i);\n\t\telse {\n\t\t\tAddSegment(id2, id3, i);\n\t\t\tAddSegment(id3, id0, i);\n\t\t}\n\t}\n\tavgLenSegment = 0;\n\tfor (const auto &s : segments)\n\t\tavgLenSegment += nodes[s.inode0].Distance(nodes[s.inode1]);\n\tavgLenSegment /= segments.GetCount();\n}\n\t\nvoid Surface::AnalyseSegments(double zTolerance) {\n\tGetSegments();\n\t\n\tfor (int i = 0; i < segments.GetCount(); ++i) {\n\t\tint inode0 = segments[i].inode0;\n\t\tint inode1 = segments[i].inode1;\n\t\t\n\t\tif (inode0 >= nodes.GetCount())\n\t\t\tthrow Exc(Format(t_(\"Node %d is pointing out of scope\"), inode0+1));\t\n\t\tif (inode1 >= nodes.GetCount())\n\t\t\tthrow Exc(Format(t_(\"Node %d is pointing out of scope\"), inode1+1));\n\t\t\n\t\tint num = segments[i].panels.GetCount();\n\t\t\t\t\n\t\tif (num == 1) {\n\t\t\tif (nodes[inode0].z >= zTolerance && nodes[inode1].z >= zTolerance)\n\t\t\t\tsegWaterlevel << Segment3D(nodes[inode0], nodes[inode1]);\n\t\t\telse {\n\t\t\t\tif (SegmentInSegments(i) < 0)\t\n\t\t\t\t\tsegTo1panel << Segment3D(nodes[inode0], nodes[inode1]);\n\t\t\t}\n\t\t} else if (num > 2)\n\t\t\tsegTo3panel << Segment3D(nodes[inode0], nodes[inode1]);\n\t}\n}\n\nbool Surface::GetLowest(int &iLowSeg, int &iLowPanel) {\t// Get the lowest panel with normal non horizontal\n\tiLowSeg = iLowPanel = Null;\n\tdouble zLowSeg = DBL_MAX;\n\tfor (int i = 0; i < segments.GetCount(); ++i) {\n\t\tconst Segment &seg = segments[i];\n\t\tif (seg.panels.GetCount() == 2) {\n\t\t\tfor (int ip = 0; ip < seg.panels.GetCount(); ++ip) {\n\t\t\t\tif (panels[seg.panels[ip]].normal0.z != 0) {\n\t\t\t\t\tdouble zz = max(nodes[seg.inode0].z, nodes[seg.inode1].z);\n\t\t\t\t\tif (zz < zLowSeg) {\n\t\t\t\t\t\tzLowSeg = zz;\n\t\t\t\t\t\tiLowSeg = i;\n\t\t\t\t\t\tiLowPanel = ip;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif (!IsNull(iLowSeg))\n\t\treturn true;\n\tfor (int i = 0; i < segments.GetCount(); ++i) {\n\t\tconst Segment &seg = segments[i];\n\t\tif (seg.panels.GetCount() == 2) {\n\t\t\tfor (int ip = 0; ip < seg.panels.GetCount(); ++ip) {\n\t\t\t\tdouble zz = min(nodes[seg.inode0].z, nodes[seg.inode1].z);\n\t\t\t\tif (zz < zLowSeg) {\n\t\t\t\t\tzLowSeg = zz;\n\t\t\t\t\tiLowSeg = i;\n\t\t\t\t\tiLowPanel = ip;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn !IsNull(iLowSeg);\n}\n\t\nbool Surface::ReorientPanels0(bool _side) {\n\tnumUnprocessed = -1;\n\t\n\tint iLowSeg, iLowPanel;\n\tif (!GetLowest(iLowSeg, iLowPanel))\n\t\treturn false;\n\t\n\t// Reorient lowest panel downwards to be the seed\n\tint ip = segments[iLowSeg].panels[iLowPanel];\n\tif (panels[ip].normal0.z != 0) {\n\t\tif (_side && panels[ip].normal0.z > 0 || !_side && panels[ip].normal0.z < 0)\n\t\t\tReorientPanel(ip);\n\t} else if (panels[ip].normal0.x != 0) {\n\t\tif (_side && panels[ip].normal0.x > 0 || !_side && panels[ip].normal0.x < 0)\n\t\t\tReorientPanel(ip);\n\t} else {\n\t\tif (_side && panels[ip].normal0.y > 0 || !_side && panels[ip].normal0.y < 0)\n\t\t\tReorientPanel(ip);\n\t}\n\t\n\tVector<int> panelStack;\n\tUpp::Index<int> panelProcessed;\n\t\n\tpanelStack << ip;\n\twhile (!panelStack.IsEmpty()) {\n\t\tint id = panelStack.GetCount() - 1;\n\t\tint ipp = panelStack[id];\n\t\tpanelStack.Remove(id, 1);\n\t\tpanelProcessed << ipp;\n\t\t\n\t\tfor (int is = 0; is < segments.GetCount(); ++is) {\n\t\t\tconst Upp::Index<int> &segPanels = segments[is].panels;\n\t\t\tif (segPanels.Find(ipp) >= 0) {\n\t\t\t\tfor (int i = 0; i < segPanels.GetCount(); ++i) {\n\t\t\t\t\tint ipadyac = segPanels[i];\n\t\t\t\t\tif (ipadyac != ipp && panelProcessed.Find(ipadyac) < 0) {\n\t\t\t\t\t\tpanelStack << ipadyac;\n\t\t\t\t\t\tif (!SameOrderPanel(ipp, ipadyac, segments[is].inode0, segments[is].inode1))\n\t\t\t\t\t\t\tReorientPanel(ipadyac);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tnumUnprocessed = panels.GetCount() - panelProcessed.GetCount();\n\n\treturn true;\n}\n\nVector<Vector<int>> Surface::GetPanelSets(Function <void(String, int pos)> Status) {\n\tVector<Vector<int>> ret;\n\t\n\tdouble zTolerance = -0.1;\n\tAnalyseSegments(zTolerance);\t\n\t\n\tIndex<int> allPanels;\n\tfor (int i = 0; i < panels.GetCount(); ++i)\n\t\tallPanels << i;\n\t\n\twhile (allPanels.GetCount() > 0) {\n\t\tVector<int> panelStack;\n\t\tUpp::Index<int> panelProcessed;\n\t\n\t\tpanelStack << allPanels[0];\n\t\twhile (!panelStack.IsEmpty()) {\n\t\t\tint id = panelStack.GetCount() - 1;\n\t\t\tint ipp = panelStack[id];\n\t\t\tpanelStack.Remove(id, 1);\n\t\t\tint iall = allPanels.Find(ipp);\n\t\t\tif (iall < 0)\n\t\t\t\tcontinue;\n\t\t\tallPanels.Remove(iall);\n\t\t\tpanelProcessed << ipp;\n\t\t\t\n\t\t\tfor (int is = 0; is < segments.GetCount(); ++is) {\n\t\t\t\tconst Upp::Index<int> &segPanels = segments[is].panels;\n\t\t\t\tif (segPanels.Find(ipp) >= 0) {\n\t\t\t\t\tfor (int i = 0; i < segPanels.GetCount(); ++i) {\n\t\t\t\t\t\tint ipadyac = segPanels[i];\n\t\t\t\t\t\tif (ipadyac != ipp && panelProcessed.Find(ipadyac) < 0) \n\t\t\t\t\t\t\tpanelStack << ipadyac;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tret << panelProcessed.PickKeys();\n\t\tpanelProcessed.Clear();\n\t\tStatus(Format(t_(\"Split mesh #%d\"), ret.GetCount()), 0);\n\t}\n\treturn ret;\n}\n\nvoid Surface::ReorientPanel(int ip) {\n\tpanels[ip].Swap();\n\tpanels[ip].normal0.Mirror();\n\tif (panels[ip].IsTriangle()) \n\t\tpanels[ip].normal1.Mirror();\n}\n\nbool Panel::FirstNodeIs0(int in0, int in1) const {\n\tif (IsTriangle()) {\n\t\tif ((id[0] == in0 && id[1] == in1) ||\n\t\t\t(id[1] == in0 && id[2] == in1) ||\n\t\t\t(id[2] == in0 && id[0] == in1))\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t} else {\n\t\tif ((id[0] == in0 && id[1] == in1) ||\n\t\t\t(id[1] == in0 && id[2] == in1) ||\n\t\t\t(id[2] == in0 && id[3] == in1) ||\n\t\t\t(id[3] == in0 && id[0] == in1))\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n}\n\nvoid Panel::RedirectTriangles() {\n\tint shift = 0;\n\tif (id[0] == id[1])\n\t\tshift = -1;\n\telse if (id[1] == id[2])\n\t\tshift = -2;\n\telse if (id[2] == id[3])\n\t\tshift = 1;\n\telse\n\t\treturn;\n\tShiftNodes(shift);\n}\n\nvoid Panel::ShiftNodes(int shift) {\n\tint id_0 = id[0];\n\tint id_1 = id[1];\n\tint id_2 = id[2];\n\tint id_3 = id[3];\n\tif (shift == 1) {\n\t\tid[1] = id_0;\n\t\tid[2] = id_1;\n\t\tid[3] = id_2;\n\t\tid[0] = id_3;\n\t} else if (shift == -1) { \n\t\tid[0] = id_1;\n\t\tid[1] = id_2;\n\t\tid[2] = id_3;\n\t\tid[3] = id_0;\n\t} else if (shift == -2) { \n\t\tid[0] = id_2;\n\t\tid[1] = id_3;\n\t\tid[2] = id_0;\n\t\tid[3] = id_1;\n\t} else\n\t\tthrow t_(\"ShiftNodes value not implemented\");\n}\n\ndouble Panel::GetSurface(const Point3D &p0, const Point3D &p1, const Point3D &p2) {\n\tdouble l01 = p0.Distance(p1);\n\tdouble l12 = p1.Distance(p2);\n\tdouble l02 = p0.Distance(p2);\n\n\tdouble s = (l01 + l12 + l02)/2;\n\treturn sqrt(max(s*(s - l01)*(s - l12)*(s - l02), 0.)); \n}\n\nbool Surface::SameOrderPanel(int ip0, int ip1, int in0, int in1) {\n\tbool first0in0 = panels[ip0].FirstNodeIs0(in0, in1);\n\tbool first1in0 = panels[ip1].FirstNodeIs0(in0, in1);\n\t\n\treturn first0in0 != first1in0;\n}\n\nString Surface::Heal(bool basic, Function <void(String, int pos)> Status) {\n\tString ret;\n\t\n\tif (basic) {\n\t\tStatus(t_(\"Removing duplicated panels (pass 1)\"), 25);\n\t\tnumDupPan = RemoveDuplicatedPanels(panels);\n\t\t\n\t\tStatus(t_(\"Removing duplicated points\"), 50);\n\t\tnumDupP = RemoveDuplicatedPointsAndRenumber(panels, nodes);\n\t\tif (numDupP > 0) \n\t\t\tret << \"\\n\" << Format(t_(\"Removed %d duplicated points\"), numDupP);\t\n\t\n\t\tStatus(t_(\"Removing duplicated panels (pass 2)\"), 75);\n\t\tnumDupPan += RemoveDuplicatedPanels(panels);\t// Second time after duplicated points\n\t\tif (numDupPan > 0) \n\t\t\tret << \"\\n\" << Format(t_(\"Removed %d duplicated panels\"), numDupPan);\n\t} else {\t\n\t\tStatus(t_(\"Detecting triangles and wrong panels\"), 40);\n\t\tDetectTriBiP(panels, numTriangles, numBiQuads, numMonoQuads);\n\t\tif (numTriangles > 0)\n\t\t\tret << \"\\n\" << Format(t_(\"Fixed %d triangles\"), numTriangles);\n\t\tif (numBiQuads > 0)\n\t\t\tret << \"\\n\" << Format(t_(\"Removed %d 2 points quads\"), numBiQuads);\n\t\tif (numMonoQuads > 0)\n\t\t\tret << \"\\n\" << Format(t_(\"Removed %d 1 points quads\"), numMonoQuads);\n\t\t\n\t\tStatus(t_(\"Removing tiny panels\"), 45);\n\t\tRemoveTinyPanels(panels);\n\t\t\n\t\tStatus(t_(\"Removing duplicated panels (pass 1)\"), 55);\n\t\tnumDupPan = RemoveDuplicatedPanels(panels);\n\t\t\n\t\tStatus(t_(\"Fixing skewed panels\"), 60);\n\t\tnumSkewed = FixSkewed();\n\t\tif (numSkewed > 0) \n\t\t\tret << \"\\n\" << Format(t_(\"Fixed %d skewed panels\"), numSkewed);\n\t\n\t\tStatus(t_(\"Removing duplicated points\"), 65);\n\t\tnumDupP = RemoveDuplicatedPointsAndRenumber(panels, nodes);\n\t\tif (numDupP > 0) \n\t\t\tret << \"\\n\" << Format(t_(\"Removed %d duplicated points\"), numDupP);\t\n\t\n\t\tStatus(t_(\"Removing duplicated panels (pass 2)\"), 70);\n\t\tnumDupPan += RemoveDuplicatedPanels(panels);\t// Second time after duplicated points\n\t\tif (numDupPan > 0) \n\t\t\tret << \"\\n\" << Format(t_(\"Removed %d duplicated panels\"), numDupPan);\n\t\n\t\tStatus(t_(\"Analysing water tightness\"), 75);\n\t\tdouble zTolerance = -0.1;\n\t\tAnalyseSegments(zTolerance);\n\t\tret << \"\\n\" << Format(t_(\"%d segments, %d water level, %d water leak and %d multipanel\"), \n\t\t\t\t\t\t\t\t\tsegments.GetCount(), segWaterlevel.GetCount(), \n\t\t\t\t\t\t\t\t\tsegTo1panel.GetCount(), segTo3panel.GetCount());\n/*\t\t\n\t\tStatus(t_(\"Reorienting panels water side\"), 80);\n\t\tif (!ReorientPanels0(true))\n\t\t\tret << \"\\n\" << t_(\"Failed to reorient panels to water side\");\n\t\telse if (numUnprocessed > 0)\n\t\t\tret << \"\\n\" << Format(t_(\"%d panels not reoriented. Body contains separated surfaces\"), numUnprocessed);\n*/\t\t\n\t\thealing = true;\n\t}\n\treturn ret;\n}\n\nvoid Surface::Orient() {\n\tGetSegments();\n\tReorientPanels0(side);\n\tside = !side;\n}\t\t\n\t\t\nvoid Surface::Image(int axis) {\n\tfor (int i = 0; i < nodes.GetCount(); ++i) {\n\t\tPoint3D &node = nodes[i];\n\t\tif (axis == 0)\n\t\t\tnode.x = -node.x;\n\t\telse if (axis == 1)\n\t\t\tnode.y = -node.y;\n\t\telse\n\t\t\tnode.z = -node.z;\n\t}\n\tfor (int i = 0; i < panels.GetCount(); ++i) \n\t\tReorientPanel(i);\n}\n\t\nvoid Surface::GetLimits() {\n\tenv.maxX = env.maxY = env.maxZ = -DBL_MAX; \n\tenv.minX = env.minY = env.minZ = DBL_MAX;\n\tfor (int i = 0; i < nodes.GetCount(); ++i) {\n\t\tenv.maxX = max(env.maxX, nodes[i].x);\n\t\tenv.minX = min(env.minX, nodes[i].x);\n\t\tenv.maxY = max(env.maxY, nodes[i].y);\n\t\tenv.minY = min(env.minY, nodes[i].y);\n\t\tenv.maxZ = max(env.maxZ, nodes[i].z);\n\t\tenv.minZ = min(env.minZ, nodes[i].z);\n\t}\n}\n\nvoid Surface::JointTriangularPanels(int ip0, int ip1, int inode0, int inode1) {\n\tPanel &pan = panels[ip0];\n\tint iip0 = -1, iip1 = -1;\n\tfor (int i = 0; i < 4; ++i) {\n\t\tif (pan.id[i] == inode0 || pan.id[i] == inode1)\n\t\t\t;\n\t\telse {\n\t\t\tiip0 = pan.id[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (iip0 < 0)\n\t\treturn;\t\t// Error?\n\tPanel &pan1 = panels[ip1];\n\tfor (int i = 0; i < 4; ++i) {\n\t\tif (pan1.id[i] == inode0 || pan1.id[i] == inode1)\n\t\t\t;\n\t\telse {\n\t\t\tiip1 = pan.id[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (iip1 < 0)\n\t\treturn;\t\t// Error?\n\tpan.id[0] = iip0;\n\tpan.id[1] = inode0;\n\tpan.id[2] = iip1;\n\tpan.id[3] = inode1;\n\tFixSkewed(ip0);\n\tGetPanelParams(pan);\n\tif (pan.normal0.Angle(pan1.normal0) > 0.1*M_PI) {\n\t\tpan.Swap();\n\t\tGetPanelParams(pan);\t\n\t}\n\tpanels.Remove(ip1);\n}\n\nvoid Surface::GetPanelParams(Panel &panel) const {\n\tpanel.RedirectTriangles();\n\t\n\tconst Point3D &p0 = nodes[panel.id[0]];\n\tconst Point3D &p1 = nodes[panel.id[1]];\n\tconst Point3D &p2 = nodes[panel.id[2]];\n\tconst Point3D &p3 = nodes[panel.id[3]];\n\t\n\tpanel.surface0 = panel.GetSurface(p0, p1, p2);\n\tpanel.centroid0 = GetCentroid(p0, p1, p2);\n\tpanel.normal0 = GetNormal(p0, p1, p2);\n\tif (!panel.IsTriangle()) {\n\t\tpanel.surface1 = panel.GetSurface(p2, p3, p0);\n\t\tpanel.centroid1 = GetCentroid(p2, p3, p0);\n\t\tpanel.normal1 = GetNormal(p2, p3, p0);\n\t\tdouble surf = panel.surface0 + panel.surface1;\n\t\tpanel.centroidPaint.x = (panel.centroid0.x*panel.surface0 + panel.centroid1.x*panel.surface1)/surf;\n\t\tpanel.centroidPaint.y = (panel.centroid0.y*panel.surface0 + panel.centroid1.y*panel.surface1)/surf;\n\t\tpanel.centroidPaint.z = (panel.centroid0.z*panel.surface0 + panel.centroid1.z*panel.surface1)/surf;\n\t\tpanel.normalPaint.x = (panel.normal0.x*panel.surface0 + panel.normal1.x*panel.surface1)/surf;\n\t\tpanel.normalPaint.y = (panel.normal0.y*panel.surface0 + panel.normal1.y*panel.surface1)/surf;\n\t\tpanel.normalPaint.z = (panel.normal0.z*panel.surface0 + panel.normal1.z*panel.surface1)/surf;\n\t\tpanel.normalPaint.Normalize();\n\t} else {\n\t\tpanel.surface1 = 0;\n\t\tpanel.centroidPaint = panel.centroid1 = panel.centroid0;\n\t\tpanel.normalPaint = panel.normal1 = panel.normal0;\n\t}\n}\n\nString Surface::CheckErrors() const {\n\tfor (int ip = 0; ip < panels.GetCount(); ++ip) {\n\t\tconst Panel &panel = panels[ip];\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tif (panel.id[i] >= nodes.GetCount())\n\t\t\t\treturn Format(t_(\"Node %d in panel %d [%d] does not exist\"), panel.id[i]+1, ip+1, i+1);\n\t\t}\n\t}\n\treturn Null;\n}\n\t\t\nvoid Surface::GetPanelParams() {\n\tfor (int ip = 0; ip < panels.GetCount(); ++ip) {\n\t\tPanel &panel = panels[ip];\n\t\tGetPanelParams(panel);\n\t}\t\n}\n\nvoid Surface::GetSurface() {\n\tsurface = 0;\n\tfor (int ip = 0; ip < panels.GetCount(); ++ip) \n\t\tsurface += panels[ip].surface0 + panels[ip].surface1;\n\tavgFacetSideLen  = sqrt(surface/panels.GetCount());\n}\n\ndouble Surface::GetWaterPlaneArea() const {\n\tdouble area = 0;\n\t\n\tfor (int ip = 0; ip < panels.GetCount(); ++ip) {\n\t\tconst Panel &panel = panels[ip];\n\t\tarea += -(panel.surface0*panel.normal0.z + panel.surface1*panel.normal1.z);\n\t}\n\treturn area;\n}\n\nvoid Surface::GetVolume() {\n\tvolumex = volumey = volumez = 0;\n\t\n\tfor (int ip = 0; ip < panels.GetCount(); ++ip) {\n\t\tconst Panel &panel = panels[ip];\n\t\t\n\t\tvolumex += panel.surface0*panel.normal0.x*panel.centroid0.x;\n\t\tvolumey += panel.surface0*panel.normal0.y*panel.centroid0.y;\n\t\tvolumez += panel.surface0*panel.normal0.z*panel.centroid0.z;\n\t\t\n\t\tif (!panel.IsTriangle()) {\n\t\t\tvolumex += panel.surface1*panel.normal1.x*panel.centroid1.x;\n\t\t\tvolumey += panel.surface1*panel.normal1.y*panel.centroid1.y;\n\t\t\tvolumez += panel.surface1*panel.normal1.z*panel.centroid1.z;\n\t\t}\n\t}\n\tvolume = avg(volumex, volumey, volumez);\n}\n\t\nPoint3D Surface::GetCenterOfBuoyancy() const {\n\tdouble xb = 0, yb = 0, zb = 0;\n\t\n\tfor (int ip = 0; ip < panels.GetCount(); ++ip) {\n\t\tconst Panel &panel = panels[ip];\n\t\t\n\t\txb += panel.surface0*panel.normal0.x*sqr(panel.centroid0.x);\n\t\tyb += panel.surface0*panel.normal0.y*sqr(panel.centroid0.y);\n\t\tzb += panel.surface0*panel.normal0.z*sqr(panel.centroid0.z);\n\t\t\n\t\tif (!panel.IsTriangle()) {\n\t\t\txb += panel.surface1*panel.normal1.x*sqr(panel.centroid1.x);\n\t\t\tyb += panel.surface1*panel.normal1.y*sqr(panel.centroid1.y);\n\t\t\tzb += panel.surface1*panel.normal1.z*sqr(panel.centroid1.z);\n\t\t}\n\t}\n\t\n\txb /= 2*volumex;\n\tyb /= 2*volumey;\n\tzb /= 2*volumez;\n\t\n\treturn Point3D(xb, yb, zb);\n}\n\nvoid Surface::GetHydrostaticStiffness(MatrixXd &c, const Point3D &cb, double rho, \n\t\t\t\t\tconst Point3D &cg, double mass, double g) {\n\tc.setConstant(6, 6, 0);\n\t\n\tif (volume < EPS_XYZ)\n\t\treturn;\n\t\n\tif (IsNull(mass))\n\t\tmass = rho*volume;\n\t\t\n\tfor (int ip = 0; ip < panels.GetCount(); ++ip) {\t\n\t\tconst Panel &panel = panels[ip];\n\n\t\tdouble momentz0 = panel.normal0.z*panel.surface0;\n\t\tdouble momentz1 = panel.normal1.z*panel.surface1;\n\t\tdouble x0 = panel.centroid0.x;\n\t\tdouble y0 = panel.centroid0.y;\n\t\tdouble x1 = panel.centroid1.x;\n\t\tdouble y1 = panel.centroid1.y;\n\t\tc(2, 2) -= (momentz0 + momentz1);\n        c(2, 3) -= (y0*momentz0 + y1*momentz1);\n        c(2, 4) += (x0*momentz0 + x1*momentz1);\n        c(3, 3) -= (y0*y0*momentz0 + y1*y1*momentz1);\n        c(3, 4) += (x0*y0*momentz0 + x1*y1*momentz1);\n        c(4, 4) -= (x0*x0*momentz0 + x1*x1*momentz1);\n\t}\n\tdouble rho_g = rho*g;\n\t\n\tc(2, 2) = c(2, 2)*rho_g;\t\t\t\t\t\t\t\t\t\n\tc(2, 3) = c(2, 3)*rho_g;\n\tc(2, 4) = c(2, 4)*rho_g;\n\tc(3, 4) = c(3, 4)*rho_g;\n\t\n\tc(3, 3) = (c(3, 3) + volumez*cb.z)*rho_g - mass*g*cg.z;\n\tc(4, 4) = (c(4, 4) + volumez*cb.z)*rho_g - mass*g*cg.z;\n\t\n\tif (abs(cb.x) > EPS_XYZ)\n\t\tc(3, 5) -= rho_g*volume*cb.x;\n\tif (abs(cg.x) > EPS_XYZ)\n\t\tc(3, 5) += mass*g*cg.x;\n\t\n\tif (abs(cb.x) > EPS_XYZ)\n\t\tc(4, 5) -= rho_g*volume*cb.y;\n\tif (abs(cg.x) > EPS_XYZ)\n\t\tc(4, 5) += mass*g*cg.y;\n\t\t\t\n\tc(3, 2) = c(2, 3);\n\tc(4, 2) = c(2, 4);\n\tc(4, 3) = c(3, 4);\n}\n\ninline static void CheckAddSegZero(Vector<Segment3D> &seg, const Point3D &p0, const Point3D &p1, \n\t\t\tconst Point3D &p2, const Point3D &p3) {\n\tif (p0 != p1 && Between(p0.z, EPS_XYZ) && Between(p1.z, EPS_XYZ))\n\t\tseg << Segment3D(p0, p1);\n\tif (p1 != p2 && Between(p1.z, EPS_XYZ) && Between(p2.z, EPS_XYZ))\n\t\tseg << Segment3D(p1, p2);\n\tif (p2 != p3 && Between(p2.z, EPS_XYZ) && Between(p3.z, EPS_XYZ))\n\t\tseg << Segment3D(p2, p3);\n\tif (p3 != p0 && Between(p3.z, EPS_XYZ) && Between(p0.z, EPS_XYZ))\n\t\tseg << Segment3D(p3, p0);\n}\n\nvoid Surface::CutZ(const Surface &orig, int factor) {\n\tnodes = clone(orig.nodes);\n\tpanels.Clear();\n\t\n\tsegWaterlevel.Clear();\n\tfactor *= -1;\n\t\n\tfor (int ip = 0; ip < orig.panels.GetCount(); ++ip) {\n\t\tconst int &id0 = orig.panels[ip].id[0];\n\t\tconst int &id1 = orig.panels[ip].id[1];\n\t\tconst int &id2 = orig.panels[ip].id[2];\n\t\tconst int &id3 = orig.panels[ip].id[3];\n\t\tconst Point3D &p0 = nodes[id0];\n\t\tconst Point3D &p1 = nodes[id1];\n\t\tconst Point3D &p2 = nodes[id2];\n\t\tconst Point3D &p3 = nodes[id3];\t\n\t\t\n\t\tCheckAddSegZero(segWaterlevel, p0, p1, p2, p3);\n\t\t\n\t\tif ((p0.z)*factor >= -EPS_XYZ && (p1.z)*factor >= -EPS_XYZ && \n\t\t\t(p2.z)*factor >= -EPS_XYZ && (p3.z)*factor >= -EPS_XYZ) \n\t\t\t;\n\t\telse if ((p0.z)*factor <= EPS_XYZ && (p1.z)*factor <= EPS_XYZ && \n\t\t\t\t (p2.z)*factor <= EPS_XYZ && (p3.z)*factor <= EPS_XYZ) {\n\t\t\tpanels << Panel(orig.panels[ip]);\n\t\t} else {\n\t\t\tconst int *origPanelid = orig.panels[ip].id;\n\t\t\tVector<int> nodeFrom, nodeTo;\n\t\t\tSegment3D segWL;\n\t\t\tsegWL.from = segWL.to = Null;\n\t\t\tconst int ids[] = {0, 1, 2, 3, 0};\n\t\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\t\tif (origPanelid[ids[i]] == origPanelid[ids[i+1]])\n\t\t\t\t\t;\n\t\t\t\telse {\n\t\t\t\t\tconst Point3D &from = nodes[origPanelid[ids[i]]];\n\t\t\t\t\tconst Point3D &to   = nodes[origPanelid[ids[i+1]]];\n\t\t\t\t\tif (abs(from.z) <= EPS_XYZ && abs(to.z) <= EPS_XYZ) {\n\t\t\t\t\t\t//nodeFrom << origPanelid[ids[i]];\n\t\t\t\t\t\t//nodeTo << origPanelid[ids[i+1]];\n\t\t\t\t\t\tsegWL.from = from;\n\t\t\t\t\t\tsegWL.to = to;\t\n\t\t\t\t\t} else if ((from.z)*factor <= 0 && (to.z)*factor <= 0) {\n\t\t\t\t\t\tnodeFrom << origPanelid[ids[i]];\n\t\t\t\t\t\tnodeTo << origPanelid[ids[i+1]];\n\t\t\t\t\t} else if ((from.z)*factor >= 0 && (to.z)*factor >= 0) \n\t\t\t\t\t\t;\n\t\t\t\t\telse {\n\t\t\t\t\t\tSegment3D seg(from, to);\n\t\t\t\t\t\tPoint3D inter = seg.IntersectionPlaneZ(0);\n\t\t\t\t\t\tif (!IsNull(inter)) {\n\t\t\t\t\t\t\tif ((from.z)*factor < 0) {\n\t\t\t\t\t\t\t\tnodeFrom << origPanelid[ids[i]];\n\t\t\t\t\t\t\t\tnodes << inter;\n\t\t\t\t\t\t\t\tnodeTo << nodes.GetCount() - 1;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tnodeTo << origPanelid[ids[i+1]];\n\t\t\t\t\t\t\t\tnodes << inter;\n\t\t\t\t\t\t\t\tnodeFrom << nodes.GetCount() - 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (IsNull(segWL.from))\n\t\t\t\t\t\t\tsegWL.from = inter;\n\t\t\t\t\t\telse if (IsNull(segWL.to))\n\t\t\t\t\t\t\tsegWL.to = inter;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!IsNull(segWL))\n\t\t\t\tsegWaterlevel << segWL;\n\t\t\t\n\t\t\tint pos = -1, nFrom, nTo;\n\t\t\tfor (int i = 0; i < nodeFrom.GetCount(); ++i) {\n\t\t\t\tint i_1 = i + 1;\n\t\t\t\tif (i_1 >= nodeFrom.GetCount())\n\t\t\t\t\ti_1 = 0;\n\t\t\t\tif (nodeTo[i] != nodeFrom[i_1]) {\n\t\t\t\t\tpos = i+1;\n\t\t\t\t\tnFrom = nodeTo[i];\n\t\t\t\t\tnTo = nodeFrom[i_1];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (pos == nodeTo.GetCount()) {\n\t\t\t\tnodeFrom << nFrom;\n\t\t\t\tnodeTo << nTo;\n\t\t\t} else if (pos >= 0) {\n\t\t\t\tnodeFrom.Insert(pos, nFrom);\t\t\n\t\t\t\tnodeTo.Insert(pos, nTo);\n\t\t\t}\n\t\t\t\n\t\t\tPanel panel;\n\t\t\tif (nodeFrom.GetCount() == 3) {\n\t\t\t\tpanel.id[0] = nodeFrom[0];\n\t\t\t\tpanel.id[1] = nodeFrom[1];\n\t\t\t\tpanel.id[2] = nodeFrom[2];\n\t\t\t\tpanel.id[3] = nodeFrom[2];\n\t\t\t} else if (nodeFrom.GetCount() == 4) {\n\t\t\t\tpanel.id[0] = nodeFrom[0];\n\t\t\t\tpanel.id[1] = nodeFrom[1];\n\t\t\t\tpanel.id[2] = nodeFrom[2];\n\t\t\t\tpanel.id[3] = nodeFrom[3];\n\t\t\t} else if (nodeFrom.GetCount() == 5) {\n\t\t\t\tpanel.id[0] = nodeFrom[0];\n\t\t\t\tpanel.id[1] = nodeFrom[1];\n\t\t\t\tpanel.id[2] = nodeFrom[2];\n\t\t\t\tpanel.id[3] = nodeFrom[3];\n\t\t\t\tPanel panel2;\n\t\t\t\tpanel2.id[0] = nodeFrom[0];\n\t\t\t\tpanel2.id[1] = nodeFrom[3];\n\t\t\t\tpanel2.id[2] = nodeFrom[4];\n\t\t\t\tpanel2.id[3] = nodeFrom[4];\n\t\t\t\t//TriangleToQuad(panel2); \n\t\t\t\tpanels << panel2;\n\t\t\t}\n\t\t\t//TriangleToQuad(panel);\n\t\t\tpanels << panel;\n\t\t}\n\t}\n\tDeleteVoidSegments(segWaterlevel);\n\tDeleteDuplicatedSegments(segWaterlevel);\n}\n\nvoid Surface::CutX(const Surface &orig, int factor) {\n\tnodes = clone(orig.nodes);\n\tpanels.Clear();\n\t\n\tfactor *= -1;\n\t\n\tfor (int ip = 0; ip < orig.panels.GetCount(); ++ip) {\n\t\tconst int &id0 = orig.panels[ip].id[0];\n\t\tconst int &id1 = orig.panels[ip].id[1];\n\t\tconst int &id2 = orig.panels[ip].id[2];\n\t\tconst int &id3 = orig.panels[ip].id[3];\n\t\tconst Point3D &p0 = nodes[id0];\n\t\tconst Point3D &p1 = nodes[id1];\n\t\tconst Point3D &p2 = nodes[id2];\n\t\tconst Point3D &p3 = nodes[id3];\t\n\t\t\n\t\tif ((p0.x)*factor >= 0 && (p1.x)*factor >= 0 && (p2.x)*factor >= 0 && (p3.x)*factor >= 0) \n\t\t\t;\n\t\telse if ((p0.x)*factor <= 0 && (p1.x)*factor <= 0 && (p2.x)*factor <= 0 && (p3.x)*factor <= 0) \n\t\t\tpanels << Panel(orig.panels[ip]);\n\t\telse {\n\t\t\tconst int *origPanelid = orig.panels[ip].id;\n\t\t\tVector<int> nodeFrom, nodeTo;\n\n\t\t\tconst int ids[] = {0, 1, 2, 3, 0};\n\t\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\t\tif (origPanelid[ids[i]] == origPanelid[ids[i+1]])\n\t\t\t\t\t;\n\t\t\t\telse {\n\t\t\t\t\tconst Point3D &from = nodes[origPanelid[ids[i]]];\n\t\t\t\t\tconst Point3D &to   = nodes[origPanelid[ids[i+1]]];\n\t\t\t\t\tSegment3D seg(from, to);\n\t\t\t\t\tif (abs(from.x) <= EPS_XYZ && abs(to.x) <= EPS_XYZ) {\n\t\t\t\t\t\tnodeFrom << origPanelid[ids[i]];\n\t\t\t\t\t\tnodeTo << origPanelid[ids[i+1]];\n\t\t\t\t\t} else if ((from.x)*factor <= 0 && (to.x)*factor <= 0) {\n\t\t\t\t\t\tnodeFrom << origPanelid[ids[i]];\n\t\t\t\t\t\tnodeTo << origPanelid[ids[i+1]];\n\t\t\t\t\t} else if ((from.x)*factor >= 0 && (to.x)*factor >= 0) \n\t\t\t\t\t\t;\n\t\t\t\t\telse {\n\t\t\t\t\t\tPoint3D inter = seg.IntersectionPlaneX(0);\n\t\t\t\t\t\tif (!IsNull(inter)) {\n\t\t\t\t\t\t\tif ((from.x)*factor < 0) {\n\t\t\t\t\t\t\t\tnodeFrom << origPanelid[ids[i]];\n\t\t\t\t\t\t\t\tnodes << inter;\n\t\t\t\t\t\t\t\tnodeTo << nodes.GetCount() - 1;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tnodeTo << origPanelid[ids[i+1]];\n\t\t\t\t\t\t\t\tnodes << inter;\n\t\t\t\t\t\t\t\tnodeFrom << nodes.GetCount() - 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tint pos = -1, nFrom, nTo;\n\t\t\tfor (int i = 0; i < nodeFrom.GetCount(); ++i) {\n\t\t\t\tint i_1 = i + 1;\n\t\t\t\tif (i_1 >= nodeFrom.GetCount())\n\t\t\t\t\ti_1 = 0;\n\t\t\t\tif (nodeTo[i] != nodeFrom[i_1]) {\n\t\t\t\t\tpos = i+1;\n\t\t\t\t\tnFrom = nodeTo[i];\n\t\t\t\t\tnTo = nodeFrom[i_1];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (pos == nodeTo.GetCount()) {\n\t\t\t\tnodeFrom << nFrom;\n\t\t\t\tnodeTo << nTo;\n\t\t\t} else if (pos >= 0) {\n\t\t\t\tnodeFrom.Insert(pos, nFrom);\t\t\n\t\t\t\tnodeTo.Insert(pos, nTo);\n\t\t\t}\n\t\t\t\n\t\t\tPanel panel;\n\t\t\tif (nodeFrom.GetCount() == 3) {\n\t\t\t\tpanel.id[0] = nodeFrom[0];\n\t\t\t\tpanel.id[1] = nodeFrom[1];\n\t\t\t\tpanel.id[2] = nodeFrom[2];\n\t\t\t\tpanel.id[3] = nodeFrom[2];\n\t\t\t} else if (nodeFrom.GetCount() == 4) {\n\t\t\t\tpanel.id[0] = nodeFrom[0];\n\t\t\t\tpanel.id[1] = nodeFrom[1];\n\t\t\t\tpanel.id[2] = nodeFrom[2];\n\t\t\t\tpanel.id[3] = nodeFrom[3];\n\t\t\t} else if (nodeFrom.GetCount() == 5) {\n\t\t\t\tpanel.id[0] = nodeFrom[0];\n\t\t\t\tpanel.id[1] = nodeFrom[1];\n\t\t\t\tpanel.id[2] = nodeFrom[2];\n\t\t\t\tpanel.id[3] = nodeFrom[3];\n\t\t\t\tPanel panel2;\n\t\t\t\tpanel2.id[0] = nodeFrom[0];\n\t\t\t\tpanel2.id[1] = nodeFrom[3];\n\t\t\t\tpanel2.id[2] = nodeFrom[4];\n\t\t\t\tpanel2.id[3] = nodeFrom[4];\n\t\t\t\t//TriangleToQuad(panel2); \n\t\t\t\tpanels << panel2;\n\t\t\t}\n\t\t\t//TriangleToQuad(panel);\n\t\t\tpanels << panel;\n\t\t}\n\t}\n}\n\nvoid Surface::CutY(const Surface &orig, int factor) {\n\tnodes = clone(orig.nodes);\n\tpanels.Clear();\n\t\n\tfactor *= -1;\n\t\n\tfor (int ip = 0; ip < orig.panels.GetCount(); ++ip) {\n\t\tconst int &id0 = orig.panels[ip].id[0];\n\t\tconst int &id1 = orig.panels[ip].id[1];\n\t\tconst int &id2 = orig.panels[ip].id[2];\n\t\tconst int &id3 = orig.panels[ip].id[3];\n\t\tconst Point3D &p0 = nodes[id0];\n\t\tconst Point3D &p1 = nodes[id1];\n\t\tconst Point3D &p2 = nodes[id2];\n\t\tconst Point3D &p3 = nodes[id3];\t\n\t\t\n\t\tif ((p0.y)*factor >= 0 && (p1.y)*factor >= 0 && (p2.y)*factor >= 0 && (p3.y)*factor >= 0) \n\t\t\t;\n\t\telse if ((p0.y)*factor <= 0 && (p1.y)*factor <= 0 && (p2.y)*factor <= 0 && (p3.y)*factor <= 0) \n\t\t\tpanels << Panel(orig.panels[ip]);\n\t\telse {\n\t\t\tconst int *origPanelid = orig.panels[ip].id;\n\t\t\tVector<int> nodeFrom, nodeTo;\n\n\t\t\tconst int ids[] = {0, 1, 2, 3, 0};\n\t\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\t\tif (origPanelid[ids[i]] == origPanelid[ids[i+1]])\n\t\t\t\t\t;\n\t\t\t\telse {\n\t\t\t\t\tconst Point3D &from = nodes[origPanelid[ids[i]]];\n\t\t\t\t\tconst Point3D &to   = nodes[origPanelid[ids[i+1]]];\n\t\t\t\t\tif ((from.y)*factor <= 0 && (to.y)*factor <= 0) {\n\t\t\t\t\t\tnodeFrom << origPanelid[ids[i]];\n\t\t\t\t\t\tnodeTo << origPanelid[ids[i+1]];\n\t\t\t\t\t} else if ((from.y)*factor >= 0 && (to.y)*factor >= 0) \n\t\t\t\t\t\t;\n\t\t\t\t\telse {\n\t\t\t\t\t\tSegment3D seg(from, to);\n\t\t\t\t\t\tPoint3D inter = seg.IntersectionPlaneY(0);\n\t\t\t\t\t\tif (!IsNull(inter)) {\n\t\t\t\t\t\t\tif ((from.y)*factor < 0) {\n\t\t\t\t\t\t\t\tnodeFrom << origPanelid[ids[i]];\n\t\t\t\t\t\t\t\tnodes << inter;\n\t\t\t\t\t\t\t\tnodeTo << nodes.GetCount() - 1;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tnodeTo << origPanelid[ids[i+1]];\n\t\t\t\t\t\t\t\tnodes << inter;\n\t\t\t\t\t\t\t\tnodeFrom << nodes.GetCount() - 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tint pos = -1, nFrom, nTo;\n\t\t\tfor (int i = 0; i < nodeFrom.GetCount(); ++i) {\n\t\t\t\tint i_1 = i + 1;\n\t\t\t\tif (i_1 >= nodeFrom.GetCount())\n\t\t\t\t\ti_1 = 0;\n\t\t\t\tif (nodeTo[i] != nodeFrom[i_1]) {\n\t\t\t\t\tpos = i+1;\n\t\t\t\t\tnFrom = nodeTo[i];\n\t\t\t\t\tnTo = nodeFrom[i_1];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (pos == nodeTo.GetCount()) {\n\t\t\t\tnodeFrom << nFrom;\n\t\t\t\tnodeTo << nTo;\n\t\t\t} else if (pos >= 0) {\n\t\t\t\tnodeFrom.Insert(pos, nFrom);\t\t\n\t\t\t\tnodeTo.Insert(pos, nTo);\n\t\t\t}\n\t\t\t\n\t\t\tPanel panel;\n\t\t\tif (nodeFrom.GetCount() == 3) {\n\t\t\t\tpanel.id[0] = nodeFrom[0];\n\t\t\t\tpanel.id[1] = nodeFrom[1];\n\t\t\t\tpanel.id[2] = nodeFrom[2];\n\t\t\t\tpanel.id[3] = nodeFrom[2];\n\t\t\t} else if (nodeFrom.GetCount() == 4) {\n\t\t\t\tpanel.id[0] = nodeFrom[0];\n\t\t\t\tpanel.id[1] = nodeFrom[1];\n\t\t\t\tpanel.id[2] = nodeFrom[2];\n\t\t\t\tpanel.id[3] = nodeFrom[3];\n\t\t\t} else if (nodeFrom.GetCount() == 5) {\n\t\t\t\tpanel.id[0] = nodeFrom[0];\n\t\t\t\tpanel.id[1] = nodeFrom[1];\n\t\t\t\tpanel.id[2] = nodeFrom[2];\n\t\t\t\tpanel.id[3] = nodeFrom[3];\n\t\t\t\tPanel panel2;\n\t\t\t\tpanel2.id[0] = nodeFrom[0];\n\t\t\t\tpanel2.id[1] = nodeFrom[3];\n\t\t\t\tpanel2.id[2] = nodeFrom[4];\n\t\t\t\tpanel2.id[3] = nodeFrom[4];\n\t\t\t\t//TriangleToQuad(panel2); \n\t\t\t\tpanels << panel2;\n\t\t\t}\n\t\t\t//TriangleToQuad(panel);\n\t\t\tpanels << panel;\n\t\t}\n\t}\n}\n\nvoid Surface::Join(const Surface &orig) {\n\tint num = nodes.GetCount();\n\tint numOrig = orig.nodes.GetCount();\n\tnodes.SetCount(num + numOrig);\n\tfor (int i = 0; i < numOrig; ++i)\n\t\tnodes[num+i] = orig.nodes[i];\n\t\n\tint numPan = panels.GetCount();\n\tint numPanOrig = orig.panels.GetCount();\n\tpanels.SetCount(numPan + numPanOrig);\n\tfor (int i = 0; i < numPanOrig; ++i) {\n\t\tPanel &pan = panels[numPan+i];\n\t\tconst Panel &panOrig = orig.panels[i];\n\t\t\n\t\tfor (int ii = 0; ii < 4; ++ii)\n\t\t\tpan.id[ii] = panOrig.id[ii] + num;\n\t\t\n\t\tGetPanelParams(pan);\n\t}\n\t\n\tSurface::RemoveDuplicatedPanels(panels);\n\tSurface::RemoveDuplicatedPointsAndRenumber(panels, nodes);\n\tSurface::RemoveDuplicatedPanels(panels);\n}\n\t\nvoid Surface::Translate(double x, double y, double z) {\n\tfor (int i = 0; i < nodes.GetCount(); ++i) \n\t\tnodes[i].Translate(x, y, z); \n\t\n\tfor (int i = 0; i < skewed.GetCount(); ++i) \n\t\tskewed[i].Translate(x, y, z);\n\t\n\tfor (int i = 0; i < segTo1panel.GetCount(); ++i) \n\t\tsegTo1panel[i].Translate(x, y, z);\n\tfor (int i = 0; i < segTo3panel.GetCount(); ++i) \n\t\tsegTo3panel[i].Translate(x, y, z);\n}\n\nvoid Surface::Rotate(double a_x, double a_y, double a_z, double c_x, double c_y, double c_z) {\n\tAffine3d quat;\n\tGetTransform(quat, a_x, a_y, a_z, c_x, c_y, c_z);\n\t\n\tfor (int i = 0; i < nodes.GetCount(); ++i) \n\t\tnodes[i].Rotate(quat);\n\n\tfor (int i = 0; i < skewed.GetCount(); ++i) \n\t\tskewed[i].Rotate(quat);\n\t\n\tfor (int i = 0; i < segTo1panel.GetCount(); ++i) \n\t\tsegTo1panel[i].Rotate(quat);\n\tfor (int i = 0; i < segTo3panel.GetCount(); ++i) \n\t\tsegTo3panel[i].Rotate(quat);\n}\n\nvoid Surface::DeployXSymmetry() {\n\tint nnodes = nodes.GetCount();\n\tfor (int i = 0; i < nnodes; ++i) {\n\t\tPoint3D \t  &dest = nodes.Add();\n\t\tconst Point3D &orig = nodes[i];\n\t\tdest.x = -orig.x;\n\t\tdest.y =  orig.y;\n\t\tdest.z =  orig.z;\n\t}\n\tint npanels = panels.GetCount();\n\tfor (int i = 0; i < npanels; ++i) {\n\t\tPanel \t\t&dest = panels.Add();\n\t\tconst Panel &orig = panels[i];\n\t\tdest.id[0] = orig.id[3] + nnodes;\n\t\tdest.id[1] = orig.id[2] + nnodes;\n\t\tdest.id[2] = orig.id[1] + nnodes;\n\t\tdest.id[3] = orig.id[0] + nnodes;\n\t}\n}\n\nvoid Surface::DeployYSymmetry() {\n\tint nnodes = nodes.GetCount();\n\tfor (int i = 0; i < nnodes; ++i) {\n\t\tPoint3D \t  &dest = nodes.Add();\n\t\tconst Point3D &orig = nodes[i];\n\t\tdest.x =  orig.x;\n\t\tdest.y = -orig.y;\n\t\tdest.z =  orig.z;\n\t}\n\tint npanels = panels.GetCount();\n\tfor (int i = 0; i < npanels; ++i) {\n\t\tPanel \t\t&dest = panels.Add();\n\t\tconst Panel &orig = panels[i];\n\t\tdest.id[0] = orig.id[3] + nnodes;\n\t\tdest.id[1] = orig.id[2] + nnodes;\n\t\tdest.id[2] = orig.id[1] + nnodes;\n\t\tdest.id[3] = orig.id[0] + nnodes;\n\t}\n}\n\nvoid VolumeEnvelope::MixEnvelope(VolumeEnvelope &env) {\n\tmaxX = maxNotNull(env.maxX, maxX);\n\tminX = minNotNull(env.minX, minX);\n\tmaxY = maxNotNull(env.maxY, maxY);\n\tminY = minNotNull(env.minY, minY);\n\tmaxZ = maxNotNull(env.maxZ, maxZ);\n\tminZ = minNotNull(env.minZ, minZ);\n}\n\nvoid Surface::AddNode(Point3D &p) {\n\tdouble similThres = EPS_XYZ;\n\tfor (int i = 0; i < nodes.GetCount(); ++i) {\n\t\tif (nodes[i].IsSimilar(p, similThres))\n\t\t\treturn;\n\t}\n\tnodes << p;\n}\n\nint Surface::FindNode(Point3D &p) {\n\tfor (int i = 0; i < nodes.GetCount(); ++i) {\n\t\tif (nodes[i] == p)\n\t\t\treturn i;\n\t}\n\treturn -1;\n}\n\t\nvoid Surface::AddFlatPanel(double lenX, double lenY, double panelWidth) {\n\tint numX = int(round(lenX/panelWidth));\n\tASSERT(numX > 0);\n\tdouble widthX = lenX/numX;\t\n\t\n\tint numY = int(round(lenY/panelWidth));\n\tASSERT(numY > 0);\n\tdouble widthY = lenY/numY;\t\n\t\n\tArray<PanelPoints> pans;\n\tpans.SetCount(numX*numY);\n\tint n = 0;\n\tfor (int i = 0; i < numX; ++i) {\n\t\tfor (int j = 0; j < numY; ++j) {\n\t\t\tpans[n].data[0].x = widthX*i;\t\tpans[n].data[0].y = widthY*j;\t\tpans[n].data[0].z = 0; \n\t\t\tpans[n].data[1].x = widthX*(i+1);\tpans[n].data[1].y = widthY*j;\t\tpans[n].data[1].z = 0;\n\t\t\tpans[n].data[2].x = widthX*(i+1);\tpans[n].data[2].y = widthY*(j+1);\tpans[n].data[2].z = 0;\n\t\t\tpans[n].data[3].x = widthX*i;\t\tpans[n].data[3].y = widthY*(j+1);\tpans[n].data[3].z = 0;\n\t\t\tn++;\n\t\t}\n\t}\n\tSetPanelPoints(pans);\n}\n\nvoid Surface::AddRevolution(Vector<Pointf> &points, double panelWidth) {\n\tif (points.GetCount() < 2)\n\t\tthrow Exc(t_(\"Point nimver has to be higher than 2\"));\n\t\n\tfor (int i = points.GetCount()-2; i >= 0; --i) {\n\t\tdouble len = sqrt(sqr(points[i].x-points[i+1].x) + sqr(points[i].y-points[i+1].y)); \n\t\tint num = int(round(len/panelWidth));\n\t\tif (num > 1) {\n\t\t\tdouble x0 = points[i].x;\n\t\t\tdouble lenx = points[i+1].x - points[i].x;\n\t\t\tdouble y0 = points[i].y;\n\t\t\tdouble leny = points[i+1].y - points[i].y;\n\t\t\tfor (int in = num-1; in >= 1; --in) {\n\t\t\t\tPointf p(x0 + lenx*in/num, y0 + leny*in/num);\n\t\t\t\tpoints.Insert(i+1, p);\n\t\t\t}\n\t\t}\n\t}\n\n\tdouble maxx = 0;\n\tfor (Pointf &p : points)\n\t\tmaxx = max(maxx, p.x);\n\t\n\tint numSlices = int(round(2*M_PI*maxx/panelWidth));\n\tif (Odd(numSlices))\n\t\tnumSlices++;\n\t\n\tif (numSlices < 3)\n\t\tthrow Exc(t_(\"Panel width too large\"));\n\t\t\n\tArray<PanelPoints> pans;\n\tpans.SetCount(numSlices*(points.GetCount()-1));\n\tint n = 0;\n\tfor (int i = 0; i < points.GetCount()-1; ++i) {\n\t\tif (points[i].x == 0) {\n\t\t\tfor (int j = 0; j < numSlices; j += 2) {\n\t\t\t\tpans[n].data[0].x = 0;\t\n\t\t\t\tpans[n].data[0].y = 0;\n\t\t\t\tpans[n].data[0].z = points[i].y;\n\n\t\t\t\tpans[n].data[1].x = points[i+1].x*cos((2*M_PI*j)/numSlices);\t\n\t\t\t\tpans[n].data[1].y = points[i+1].x*sin((2*M_PI*j)/numSlices);\n\t\t\t\tpans[n].data[1].z = points[i+1].y;\n\t\n\t\t\t\tpans[n].data[2].x = points[i+1].x*cos((2*M_PI*(j+1))/numSlices);\t\n\t\t\t\tpans[n].data[2].y = points[i+1].x*sin((2*M_PI*(j+1))/numSlices);\n\t\t\t\tpans[n].data[2].z = points[i+1].y;\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tpans[n].data[3].x = points[i+1].x*cos((2*M_PI*(j+2))/numSlices);\t\n\t\t\t\tpans[n].data[3].y = points[i+1].x*sin((2*M_PI*(j+2))/numSlices);\n\t\t\t\tpans[n].data[3].z = points[i+1].y;\n\t\t\t\t\n\t\t\t\tn++;\n\t\t\t}\n\t\t} else if (points[i+1].x == 0) {\n\t\t\tfor (int j = 0; j < numSlices; j += 2) {\n\t\t\t\tpans[n].data[0].x = points[i].x*cos((2*M_PI*j)/numSlices);\t\n\t\t\t\tpans[n].data[0].y = points[i].x*sin((2*M_PI*j)/numSlices);\n\t\t\t\tpans[n].data[0].z = points[i].y;\n\t\n\t\t\t\tpans[n].data[1].x = points[i].x*cos((2*M_PI*(j+1))/numSlices);\t\n\t\t\t\tpans[n].data[1].y = points[i].x*sin((2*M_PI*(j+1))/numSlices);\n\t\t\t\tpans[n].data[1].z = points[i].y;\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tpans[n].data[2].x = points[i].x*cos((2*M_PI*(j+2))/numSlices);\t\n\t\t\t\tpans[n].data[2].y = points[i].x*sin((2*M_PI*(j+2))/numSlices);\n\t\t\t\tpans[n].data[2].z = points[i].y;\n\n\t\t\t\tpans[n].data[3].x = 0;\t\n\t\t\t\tpans[n].data[3].y = 0;\n\t\t\t\tpans[n].data[3].z = points[i+1].y;\n\t\t\t\t\t\t\t\t\n\t\t\t\tn++;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (int j = 0; j < numSlices; ++j) {\n\t\t\t\tpans[n].data[0].x = points[i].x*cos((2*M_PI*j)/numSlices);\t\n\t\t\t\tpans[n].data[0].y = points[i].x*sin((2*M_PI*j)/numSlices);\n\t\t\t\tpans[n].data[0].z = points[i].y;\n\t\t\t\t\n\t\t\t\tpans[n].data[1].x = points[i].x*cos((2*M_PI*(j+1))/numSlices);\t\n\t\t\t\tpans[n].data[1].y = points[i].x*sin((2*M_PI*(j+1))/numSlices);\n\t\t\t\tpans[n].data[1].z = points[i].y;\n\t\n\t\t\t\tpans[n].data[2].x = points[i+1].x*cos((2*M_PI*(j+1))/numSlices);\t\n\t\t\t\tpans[n].data[2].y = points[i+1].x*sin((2*M_PI*(j+1))/numSlices);\n\t\t\t\tpans[n].data[2].z = points[i+1].y;\n\t\n\t\t\t\tpans[n].data[3].x = points[i+1].x*cos((2*M_PI*j)/numSlices);\t\n\t\t\t\tpans[n].data[3].y = points[i+1].x*sin((2*M_PI*j)/numSlices);\n\t\t\t\tpans[n].data[3].z = points[i+1].y;\n\t\t\t\t\n\t\t\t\tn++;\n\t\t\t}\n\t\t}\n\t}\n\tpans.SetCount(n);\n\tSetPanelPoints(pans);\n}\n\nvoid Surface::SetPanelPoints(Array<PanelPoints> &pans) {\n\tfor (int i = 0; i < pans.GetCount(); ++i) {\n\t\tPanelPoints &pan = pans[i];\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tPoint3D p(pan.data[j].x, pan.data[j].y, pan.data[j].z);\n\t\t\tAddNode(p);\n\t\t}\n\t}\n\tfor (int i = 0; i < pans.GetCount(); ++i) {\n\t\tPanelPoints &pan = pans[i];\n\t\tPanel &panel = panels.Add();\n\t\tfor (int j = 0; j < 4; ++j) {\n\t\t\tPoint3D p(pan.data[j].x, pan.data[j].y, pan.data[j].z);\n\t\t\tint id = FindNode(p);\n\t\t\tif (id < 0)\n\t\t\t\tthrow Exc(\"Node not found in SetPanelPoints()\");\n\t\t\tpanel.id[j] = id;\n\t\t}\n\t}\n}\n\nbool Surface::FindMatchingPanels(const Array<PanelPoints> &pans, double x, double y, \n\t\t\t\t\t\t\t\t double width, int &idpan1, int &idpan2) {\n\tidpan1 = idpan2 = -1;\n\tVector<Point3D> pt;\n\tpt << Point3D(x, \t\t y, \t\t0);\n\tpt << Point3D(x, \t\t y + width, 0);\n\tpt << Point3D(x + width, y + width, 0);\n\tpt << Point3D(x + width, y, 0);\n\tfor (int ip = 0; ip < pans.GetCount(); ++ip) {\t\n\t\tint numMatchingPoints = 0;\n\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\tfor (int ipt = 0; ipt < 4; ++ipt) \n\t\t\t\tif (pans[ip].data[i] == pt[ipt])\n\t\t\t\t\tnumMatchingPoints++;\n\t\t}\n\t\tif (numMatchingPoints == 3) {\n\t\t\tif (idpan1 < 0)\n\t\t\t\tidpan1 = ip;\n\t\t\telse {\n\t\t\t\tidpan2 = ip;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\n\nVector<double> GetPolyAngles(const Array<Pointf> &bound) {\n\tVector<double> angles(bound.size());\n\tint i;\n\tfor (i = 0; i < angles.size()-1; ++i) \n\t\tangles[i] = ToDeg(Angle(bound[i], bound[i+1]));\n\tangles[i] = ToDeg(Angle(bound[i], bound[0]));\n\treturn angles;\n}\n\nvoid Surface::AddPolygonalPanel2(Array<Pointf> &bound, double width, bool adjustSize) {\n\tASSERT(bound.GetCount() >= 2);\n\t\n\tif (bound[0] != bound[bound.size()-1])\n\t\tbound << bound[0];\n\t\n\tArray<Pointf> points = clone(bound);\n\t\n\tif (adjustSize) {\n\t\tfor (int i = points.GetCount()-2; i >= 0; --i) {\n\t\t\tdouble len = sqrt(sqr(points[i].x-points[i+1].x) + sqr(points[i].y-points[i+1].y)); \n\t\t\tint num = int(len/width);\n\t\t\tif (num > 1) {\n\t\t\t\tdouble x0 = points[i].x;\n\t\t\t\tdouble lenx = points[i+1].x - points[i].x;\n\t\t\t\tdouble y0 = points[i].y;\n\t\t\t\tdouble leny = points[i+1].y - points[i].y;\n\t\t\t\tfor (int in = num-1; in >= 1; --in) {\n\t\t\t\t\tPointf p(x0 + lenx*in/num, y0 + leny*in/num);\n\t\t\t\t\tpoints.Insert(i+1, p);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tdouble minX = std::numeric_limits<double>::max(), minY = std::numeric_limits<double>::max(), \n\t\t   maxX = std::numeric_limits<double>::lowest(), maxY = std::numeric_limits<double>::lowest();\n\tfor (const auto &p : points) {\n\t\tif (p.x < minX)\n\t\t\tminX = p.x;\n\t\tif (p.y < minY)\n\t\t\tminY = p.y;\n\t\tif (p.x > maxX)\n\t\t\tmaxX = p.x;\n\t\tif (p.y > maxY)\n\t\t\tmaxY = p.y;\n\t}\n\tArray<Pointf> poly;\n\tfor (double x = minX; x < maxX; x += width) {\n\t\tfor (double y = minY; y < maxY; y += width) {\t\n\t\t\tPointf pt(x, y);\n\t\t\tbool addPoint = true;\n\t\t\tfor (int i = 0; i < points.size(); ++i)\n\t\t\t\tif (Distance(points[i], pt) < 0.8*width) {\n\t\t\t\t\taddPoint = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tif (addPoint && ContainsPoint(points, pt) != CMP_OUT)\n\t\t\t\tpoly << pt;\n\t\t}\n\t}\n\tfor (const auto &p : points) \n\t\tpoly << p;\n\n\tDelaunay del;\n\tdel.Build(poly);\n\n\tArray<PanelPoints> pans;\n\tfor (int i = 0; i < del.GetCount(); ++i) {\n\t\tconst Delaunay::Triangle &tri = del[i];\n\t\tif (tri[0] < 0 || tri[1] < 0 || tri[2] < 0)  \n\t\t\tcontinue;\n\n\t\tconst Pointf &p0 = poly[tri[0]];\n\t\tconst Pointf &p1 = poly[tri[1]];\n\t\tconst Pointf &p2 = poly[tri[2]];\n\n\t\tint idp0 = Find(bound, p0);\n\t\tint idp1 = Find(bound, p1);\n\t\tint idp2 = Find(bound, p2);\n\t\t\n\t\tbool t01 = idp0 >= 0 && idp1 >= 0 && abs(idp0 - idp1) == 1;\t// In the bound and adjacent\n\t\tif (!t01)\n\t\t\tt01 = ContainsPoint(bound, Middle(p0, p1)) != CMP_OUT;\n\n\t\tbool t12 = idp1 >= 0 && idp2 >= 0 && abs(idp1 - idp2) == 1;\n\t\tif (!t12)\n\t\t\tt12 = ContainsPoint(bound, Middle(p1, p2)) != CMP_OUT;\n\t\t\t\n\t\tbool t20 = idp2 >= 0 && idp0 >= 0 && abs(idp2 - idp0) == 1;\n\t\tif (!t20)\n\t\t\tt20 = ContainsPoint(bound, Middle(p2, p0)) != CMP_OUT;\t\t\n\t\t\n\t\tif (t01 && t12 && t20) {\n\t\t\tPanelPoints &pan = pans.Add();\n\t\t\tpan.data[0].x = poly[tri[0]].x;\t\tpan.data[0].y = poly[tri[0]].y;\t\tpan.data[0].z = 0;\n\t\t\tpan.data[1].x = poly[tri[1]].x;\t\tpan.data[1].y = poly[tri[1]].y;\t\tpan.data[1].z = 0;\n\t\t\tpan.data[2].x = poly[tri[2]].x;\t\tpan.data[2].y = poly[tri[2]].y;\t\tpan.data[2].z = 0;\n\t\t\tpan.data[3].x = poly[tri[2]].x;\t\tpan.data[3].y = poly[tri[2]].y;\t\tpan.data[3].z = 0;\n\t\t}\n\t}\n\t// Convert triangles to quads. To be improved\n\tfor (double x = minX; x < maxX; x += width) {\n\t\tfor (double y = minY; y < maxY; y += width) {\t\n\t\t\tint idpan1, idpan2;\n\t\t\tif (FindMatchingPanels(pans, x, y, width, idpan1, idpan2)) {\n\t\t\t\tpans[idpan1].data[0] = Point3D(x, \t\t  y, \t\t 0);\n\t\t\t\tpans[idpan1].data[1] = Point3D(x + width, y, \t\t 0);\n\t\t\t\tpans[idpan1].data[2] = Point3D(x + width, y + width, 0);\n\t\t\t\tpans[idpan1].data[3] = Point3D(x, y + width, 0);\n\t\t\t\tpans.Remove(idpan2);\n\t\t\t}\n\t\t}\n\t}\n\tSetPanelPoints(pans);\n}\n\nvoid Surface::AddPolygonalPanel(Vector<Pointf> &bound, double panelWidth, bool adjustSize) {\n\tASSERT(bound.GetCount() >= 2);\n\t\n\tif (bound[0] != bound[bound.size()-1])\n\t\tbound << bound[0];\n\t\n\tif (adjustSize) {\n\t\tfor (int i = bound.GetCount()-2; i >= 0; --i) {\n\t\t\tdouble len = sqrt(sqr(bound[i].x-bound[i+1].x) + sqr(bound[i].y-bound[i+1].y)); \n\t\t\tint num = int(round(len/panelWidth));\n\t\t\tif (num > 1) {\n\t\t\t\tdouble x0 = bound[i].x;\n\t\t\t\tdouble lenx = bound[i+1].x - bound[i].x;\n\t\t\t\tdouble y0 = bound[i].y;\n\t\t\t\tdouble leny = bound[i+1].y - bound[i].y;\n\t\t\t\tfor (int in = num-1; in >= 1; --in) {\n\t\t\t\t\tPointf p(x0 + lenx*in/num, y0 + leny*in/num);\n\t\t\t\t\tbound.Insert(i+1, p);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tbound.Remove(bound.size()-1);\n\t\n\tdouble avgx = 0, avgy = 0;\n\tfor (Pointf &p : bound) {\n\t\tavgx += p.x;\n\t\tavgy += p.y;\n\t}\n\tPointf avgp(avgx/bound.GetCount(), avgy/bound.GetCount());\n\n\tUpp::Array<Pointf> delp;\n\tdelp.SetCount(bound.GetCount());\n\tfor (int i = 0; i < bound.GetCount(); ++i) \n\t\tdelp[i] = bound[i]; \n\tdelp << avgp;\n\t\n\tDelaunay del;\n\t\n\tint maxnum = -1;\n\twhile (true) {\n\t\tdel.Build(delp);\n\t\tdouble avglen = 0, maxlen = 0;\n\t\tint maxid, maxid3, num = 0;\n\t\tfor (int i = 0; i < del.GetCount(); ++i) {\n\t\t\tconst Delaunay::Triangle &tri = del[i];\n\t\t\tif (tri[0] < 0 || tri[1] < 0 || tri[2] < 0)  \n\t\t\t\tcontinue;\n\n\t\t\tdouble len;\n\t\t\tlen = sqrt(sqr(delp[tri[0]].x - delp[tri[1]].x) + sqr(delp[tri[0]].y - delp[tri[1]].y));\n\t\t\tavglen += len;\tnum++;\n\t\t\tif (maxlen < len) {\n\t\t\t\tmaxlen = len;\tmaxid = i;\tmaxid3 = 0;\n\t\t\t}\n\t\t\tlen = sqrt(sqr(delp[tri[1]].x - delp[tri[2]].x) + sqr(delp[tri[1]].y - delp[tri[2]].y));\n\t\t\tavglen += len;\tnum++;\n\t\t\tif (maxlen < len) {\n\t\t\t\tmaxlen = len;\tmaxid = i;\tmaxid3 = 1;\n\t\t\t}\t\t\t\n\t\t\tlen = sqrt(sqr(delp[tri[2]].x - delp[tri[0]].x) + sqr(delp[tri[2]].y - delp[tri[0]].y));\n\t\t\tavglen += len;\tnum++;\n\t\t\tif (maxlen < len) {\n\t\t\t\tmaxlen = len;\tmaxid = i;\tmaxid3 = 2;\n\t\t\t}\n\t\t}\n\t\tif (num == maxnum)\n\t\t\tbreak;\n\t\tmaxnum = num;\n\t\tavglen /= num;\n\t\tif (avglen < panelWidth) \n\t\t\tbreak;\n\t\t\n\t\tint maxid33 = maxid3 == 2 ? 0 : maxid3+1;\n\t\t\n\t\tdelp << Pointf(Avg(delp[del[maxid][maxid3]].x, delp[del[maxid][maxid33]].x), Avg(delp[del[maxid][maxid3]].y, delp[del[maxid][maxid33]].y));\t\n\t}\n\t\n\tArray<PanelPoints> pans;\n\tfor (int i = 0; i < del.GetCount(); ++i) {\n\t\tconst Delaunay::Triangle &tri = del[i];\n\t\tif (tri[0] < 0 || tri[1] < 0 || tri[2] < 0)  \n\t\t\tcontinue;\n\n\t\tPanelPoints &pan = pans.Add();\n\t\tpan.data[0].x = delp[tri[0]].x;\t\tpan.data[0].y = delp[tri[0]].y;\t\tpan.data[0].z = 0;\n\t\tpan.data[1].x = delp[tri[1]].x;\t\tpan.data[1].y = delp[tri[1]].y;\t\tpan.data[1].z = 0;\n\t\tpan.data[2].x = delp[tri[2]].x;\t\tpan.data[2].y = delp[tri[2]].y;\t\tpan.data[2].z = 0;\n\t\tpan.data[3].x = delp[tri[2]].x;\t\tpan.data[3].y = delp[tri[2]].y;\t\tpan.data[3].z = 0;\n\t}\n\tSetPanelPoints(pans);\n}\n\nVector<Point3D> Surface::GetClosedPolygons(Vector<Segment3D> &segs) {\n\tVector<Point3D> ret;\n\t\n\tif (segs.IsEmpty())\n\t\treturn ret;\n\t\n\tret << segs[0].from;\n\tret << segs[0].to;\n\tsegs.Remove(0);\n\twhile (true) {\n\t\tconst Point3D &last = ret[ret.size()-1];\n\t\tbool found = false;\n\t\tfor (int i = 0; i < segs.size(); ++i) {\n\t\t\tif (segs[i].from == last) {\n\t\t\t\tret << segs[i].to;\n\t\t\t\tsegs.Remove(i);\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t} else if (segs[i].to == last) {\n\t\t\t\tret << segs[i].from;\n\t\t\t\tsegs.Remove(i);\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!found) \n\t\t\treturn ret;\n\t\tif (ret[0] == ret[ret.size()-1])\n\t\t\treturn ret;\t\t// Polygon closed\n\t\tif (segs.IsEmpty()) {\n\t\t\tret.Clear();\t// Polygon unclosed\n\t\t\treturn ret;\n\t\t}\n\t}\n}\n\t\t\nArray<Pointf> Surface::Point3dto2D(const Vector<Point3D> &bound) {\n\tArray<Pointf> ret;\n\tfor (const auto &d: bound)\n\t\tret << Pointf(d.x, d.y);\n\treturn ret;\n}\n\nint Find(Vector<Segment3D> &segs, const Point3D &from, const Point3D &to) {\n\tfor (int is = 0; is < segs.size(); ++is) {\n\t\tif (segs[is].from == from && segs[is].to == to)\n\t\t\treturn is;\n\t\tif (segs[is].from == to && segs[is].to == from)\n\t\t\treturn is;\n\t}\n\treturn -1;\n}\n\nvoid DeleteVoidSegments(Vector<Segment3D> &segs) {\n\tfor (int i = segs.size()-1; i >= 0; --i) {\n\t\tconst Segment3D &seg = segs[i];\n\t\tif (seg.from == seg.to)\n\t\t\tsegs.Remove(i);\n\t}\n}\t\n\nvoid DeleteDuplicatedSegments(Vector<Segment3D> &segs) {\n\tfor (int i = 0; i < segs.size(); ++i) {\n\t\tconst Segment3D &seg0 = segs[i];\n\t\tfor (int j = segs.size()-1; j > i; --j) {\n\t\t\tconst Segment3D &seg = segs[j];\t\n\t\t\tif (seg0.from == seg.from && seg0.to == seg.to)\n\t\t\t\tsegs.Remove(j);\n\t\t\telse if (seg0.from == seg.to && seg0.to == seg.from)\n\t\t\t\tsegs.Remove(j);\n\t\t}\n\t}\n}\n\nbool Surface::GetDryPanels(const Surface &orig) {\n\tnodes = clone(orig.nodes);\n\tpanels.Clear();\n\t\n\tfor (const auto &pan : orig.panels) {\n\t\tconst int &id0 = pan.id[0];\n\t\tconst int &id1 = pan.id[1];\n\t\tconst int &id2 = pan.id[2];\n\t\tconst int &id3 = pan.id[3];\n\t\tconst Point3D &p0 = nodes[id0];\n\t\tconst Point3D &p1 = nodes[id1];\n\t\tconst Point3D &p2 = nodes[id2];\n\t\tconst Point3D &p3 = nodes[id3];\t\n\t\t\n\t\tif (p0.z >= -EPS_XYZ && p1.z >= -EPS_XYZ && p2.z >= -EPS_XYZ && p3.z >= -EPS_XYZ) \n\t\t\tpanels << clone(pan);\n\t}\n\treturn !panels.IsEmpty();\n}\n\nVector<Segment3D> Surface::GetWaterLineSegments(const Surface &orig) {\n\tVector<Segment3D> ret;\n\n\tfor (const auto &pan : orig.panels) {\n\t\tconst int &id0 = pan.id[0];\n\t\tconst int &id1 = pan.id[1];\n\t\tconst int &id2 = pan.id[2];\n\t\tconst int &id3 = pan.id[3];\n\t\tconst Point3D &p0 = orig.nodes[id0];\n\t\tconst Point3D &p1 = orig.nodes[id1];\n\t\tconst Point3D &p2 = orig.nodes[id2];\n\t\tconst Point3D &p3 = orig.nodes[id3];\t\n\t\t\n\t\tif (p0 != p1 && p0.z >= -EPS_XYZ && p1.z >= -EPS_XYZ && Find(ret, p0, p1) < 0)\n\t\t\tret << Segment3D(p0, p1);\n\t\tif (p1 != p2 && p1.z >= -EPS_XYZ && p2.z >= -EPS_XYZ && Find(ret, p1, p2) < 0)\n\t\t\tret << Segment3D(p1, p2);\n\t\tif (p2 != p3 && p2.z >= -EPS_XYZ && p3.z >= -EPS_XYZ && Find(ret, p2, p3) < 0)\n\t\t\tret << Segment3D(p2, p3);\n\t\tif (p3 != p0 && p3.z >= -EPS_XYZ && p0.z >= -EPS_XYZ && Find(ret, p3, p0) < 0)\n\t\t\tret << Segment3D(p3, p0);\n\t}\n\treturn ret;\n}\n\nvoid Surface::AddWaterSurface(Surface &surf, const Surface &under, char c) {\n\tif (c == 'f') {\t\t\t\t// Takes the underwater limit from under and fills inside it\n\t\tif (surf.surface == 0)\n\t\t\treturn;\n\n\t\tVector<Segment3D> segs = GetWaterLineSegments(under);\n\t\tif (segs.IsEmpty())\n\t\t\tthrow Exc(t_(\"There is no water piercing in this mesh\"));\n\t\t\n\t\tsurf.GetSegments();\n\t\tdouble panelWidth = surf.GetAvgLenSegment();\n\t\t\n\t\twhile (!segs.IsEmpty()) {\n\t\t\tVector<Point3D> bound = GetClosedPolygons(segs);\n\t\t\tif (bound.IsEmpty())\n\t\t\t\tbreak;\n\t\t\tArray<Pointf> bound2D = Point3dto2D(bound);\n\t\t\tif (bound2D.size() > 2)\n\t\t\t\tAddPolygonalPanel2(bound2D, panelWidth*1.2, false);\n\t\t}\n\t} else if (c == 'r') {\t\t// Copies only the underwater side\n\t\tif (under.panels.IsEmpty())\n\t\t\tthrow Exc(t_(\"There is no submerged mesh\"));\n\t\tpanels = clone(under.panels);\n\t\tnodes = clone(under.nodes);\n\t} else if (c == 'e') \t\t// Copies only the dry and waterline side\n\t\tif (!GetDryPanels(surf))\n\t\t\tthrow Exc(t_(\"There is no mesh in and above the water surface\"));\t\t\n}\n\nchar Surface::IsWaterPlaneMesh() const {\n\tbool waterplane = false, outwaterplane = false;\n\tfor (const auto &pan : panels) {\n\t\tconst int &id0 = pan.id[0];\n\t\tconst int &id1 = pan.id[1];\n\t\tconst int &id2 = pan.id[2];\n\t\tconst int &id3 = pan.id[3];\n\t\tconst Point3D &p0 = nodes[id0];\n\t\tconst Point3D &p1 = nodes[id1];\n\t\tconst Point3D &p2 = nodes[id2];\n\t\tconst Point3D &p3 = nodes[id3];\t\n\t\t\n\t\tint numwaterplane = 0, num = 0;\n\t\tif (p0 != p1) {\n\t\t\tnum++;\n\t\t\tif (p0.z >= -EPS_XYZ && p1.z >= -EPS_XYZ && p0.z <= EPS_XYZ && p1.z <= EPS_XYZ)\n\t\t\t\tnumwaterplane++;\n\t\t}\n\t\tif (p1 != p2) {\n\t\t\tnum++;\n\t\t\tif (p1.z >= -EPS_XYZ && p2.z >= -EPS_XYZ && p1.z <= EPS_XYZ && p2.z <= EPS_XYZ)\n\t\t\t\tnumwaterplane++;\n\t\t}\n\t\tif (p2 != p3) {\n\t\t\tnum++;\n\t\t\tif (p2.z >= -EPS_XYZ && p3.z >= -EPS_XYZ && p2.z <= EPS_XYZ && p3.z <= EPS_XYZ)\n\t\t\t\tnumwaterplane++;\n\t\t}\n\t\tif (p3 != p0) {\n\t\t\tnum++;\n\t\t\tif (p3.z >= -EPS_XYZ && p0.z >= -EPS_XYZ && p3.z <= EPS_XYZ && p0.z <= EPS_XYZ)\n\t\t\t\tnumwaterplane++;\n\t\t}\n\t\tif (num == numwaterplane)\n\t\t\twaterplane = true;\n\t\telse\n\t\t\toutwaterplane = true;\n\t}\t\n\tif (waterplane && !outwaterplane)\n\t\treturn 'y';\n\telse if (!waterplane && outwaterplane)\n\t\treturn 'n';\n\telse\n\t\treturn 'x';\t\n}\n\n}", "meta": {"hexsha": "1835f4e0bad0553fe7ce2896c609862e994ea77f", "size": 56793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface/Surface.cpp", "max_stars_repo_name": "Libraries4U/Surface", "max_stars_repo_head_hexsha": "8857ea652fa716d9bef8f2dffc465199283e643b", "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": "Surface/Surface.cpp", "max_issues_repo_name": "Libraries4U/Surface", "max_issues_repo_head_hexsha": "8857ea652fa716d9bef8f2dffc465199283e643b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Surface/Surface.cpp", "max_forks_repo_name": "Libraries4U/Surface", "max_forks_repo_head_hexsha": "8857ea652fa716d9bef8f2dffc465199283e643b", "max_forks_repo_licenses": ["Apache-2.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.1432111001, "max_line_length": 142, "alphanum_fraction": 0.5929780079, "num_tokens": 20624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505966, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6113057161499028}}
{"text": "/********************************************************************************\n * Copyright 2017 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_GEOMETRY_ANALYTIC_QUADRATICS_QUADRATICSURFACE_HPP_\n#define RW_GEOMETRY_ANALYTIC_QUADRATICS_QUADRATICSURFACE_HPP_\n\n/**\n * @file QuadraticSurface.hpp\n *\n * \\copydoc rw::geometry::QuadraticSurface\n */\n#if !defined(SWIG)\n#include \"QuadraticCurve.hpp\"\n\n#include <rw/geometry/PlainTriMesh.hpp>\n#include <rw/geometry/analytic/ImplicitSurface.hpp>\n#include <rw/math/Transform3D.hpp>\n#include <rw/math/Vector3D.hpp>\n\n#include <Eigen/Core>\n#include <vector>\n#endif\nnamespace rw { namespace geometry {\n    class TriMesh;\n\n    //! @addtogroup geometry\n#if !defined(SWIG)\n    //! @{\n#endif\n    /**\n     * @brief A quadratic surface.\n     *\n     * The general quadratic surface is described as an implicit surface of the form:\n     *\n     * \\f$ x^T A x + 2 a^T x + u = 0\\f$\n     *\n     * where\n     *\n     * A is a symmetric matrix, \\f$ A \\in \\mathbb{R}^{3\\times3} \\f$ , and \\f$ a \\in \\mathbb{R}^3, u\n     * \\in \\mathbb{R}\\f$\n     */\n\n    #if !defined(SWIGJAVA)\n    class QuadraticSurface : public ImplicitSurface\n    #else \n    class QuadraticSurface\n    #endif \n    {\n      public:\n        //! @brief Smart pointer type for QuadraticSurface\n        typedef rw::core::Ptr< QuadraticSurface > Ptr;\n\n        //! @brief Smart pointer type for const QuadraticSurface\n        typedef rw::core::Ptr< const QuadraticSurface > CPtr;\n\n        /**\n         * @brief A trimming region is defined using an ImplicitSurface.\n         *\n         * A point is only considered part of this surface, if all trimming conditions evaluate to a\n         * negative value.\n         */\n        typedef rw::geometry::ImplicitSurface::CPtr TrimmingRegion;\n\n        /**\n         * @brief Construct new quadratic surface of the implicit form \\f$ x^T A x + 2 a^T x + u =\n         * 0\\f$ when A is diagonal.\n         *\n         * Some functions, such as #getTriMesh and #extremums, work on a diagonalized surface.\n         * When this constructor is used, some effort is saved as the surface is already known to be\n         * diagonalized.\n         *\n         * For a diagonalized surface, all scaled, cloned and translated surfaces will also be\n         * diagonalized surfaces.\n         *\n         * @param A [in] the diagonal of the A matrix.\n         * @param a [in] the vector \\f$ a \\in \\mathbb{R}^3\\f$ .\n         * @param u [in] the scalar offset \\f$ u \\in \\mathbb{R} \\f$ .\n         * @param conditions [in] (optional) list of trimming conditions.\n         */\n        QuadraticSurface (\n            const Eigen::Diagonal< Eigen::Matrix3d >& A, const Eigen::Vector3d& a, double u,\n            const std::vector< TrimmingRegion >& conditions = std::vector< TrimmingRegion > ());\n\n        //! @copydoc QuadraticSurface(const Eigen::Diagonal<Eigen::Matrix3d>&, const\n        //! Eigen::Vector3d&, double, const std::vector<TrimmingRegion>&)\n        QuadraticSurface (\n            const Eigen::DiagonalMatrix< double, 3, 3 >& A, const Eigen::Vector3d& a, double u,\n            const std::vector< TrimmingRegion >& conditions = std::vector< TrimmingRegion > ());\n\n        /**\n         * @brief Construct new quadratic surface of the implicit form \\f$ x^T A x + 2 a^T x + u =\n         * 0\\f$ when A is non-diagonal.\n         * @param A [in] a view of the upper part of the symmetric matrix \\f$ A \\in\n         * \\mathbb{R}^{3\\times3} \\f$ . Use the Eigen function A.selfadjointView<Eigen::Upper>() to\n         * extract the upper part.\n         * @param a [in] the vector \\f$ a \\in \\mathbb{R}^3\\f$ .\n         * @param u [in] the scalar offset \\f$ u \\in \\mathbb{R} \\f$ .\n         * @param conditions [in] (optional) list of trimming conditions.\n         */\n        QuadraticSurface (\n            const Eigen::SelfAdjointView< const Eigen::Matrix3d, Eigen::Upper >& A,\n            const Eigen::Vector3d& a, double u,\n            const std::vector< TrimmingRegion >& conditions = std::vector< TrimmingRegion > ());\n\n        //! @copydoc QuadraticSurface(const Eigen::SelfAdjointView<const Eigen::Matrix3d,\n        //! Eigen::Upper>&, const Eigen::Vector3d&, double, const std::vector<TrimmingRegion>&)\n        QuadraticSurface (\n            const Eigen::SelfAdjointView< Eigen::Matrix3d, Eigen::Upper >& A,\n            const Eigen::Vector3d& a, double u,\n            const std::vector< TrimmingRegion >& conditions = std::vector< TrimmingRegion > ());\n\n        /**\n         * @brief Construct new quadratic surface of the implicit form \\f$ x^T A x + 2 a^T x + u =\n         * 0\\f$ when A is non-diagonal.\n         * @param A [in] a view of the lower part of the symmetric matrix \\f$ A \\in\n         * \\mathbb{R}^{3\\times3} \\f$ . Use the Eigen function A.selfadjointView<Eigen::Lower>() to\n         * extract the lower part.\n         * @param a [in] the vector \\f$ a \\in \\mathbb{R}^3\\f$ .\n         * @param u [in] the scalar offset \\f$ u \\in \\mathbb{R} \\f$ .\n         * @param conditions [in] (optional) list of trimming conditions.\n         */\n        QuadraticSurface (\n            const Eigen::SelfAdjointView< const Eigen::Matrix3d, Eigen::Lower >& A,\n            const Eigen::Vector3d& a, double u,\n            const std::vector< TrimmingRegion >& conditions = std::vector< TrimmingRegion > ());\n\n        //! @copydoc QuadraticSurface(const Eigen::SelfAdjointView<const Eigen::Matrix3d,\n        //! Eigen::Lower>&, const Eigen::Vector3d&, double, const std::vector<TrimmingRegion>&)\n        QuadraticSurface (\n            const Eigen::SelfAdjointView< Eigen::Matrix3d, Eigen::Lower >& A,\n            const Eigen::Vector3d& a, double u,\n            const std::vector< TrimmingRegion >& conditions = std::vector< TrimmingRegion > ());\n\n        //! @brief Destructor.\n        virtual ~QuadraticSurface ();\n\n        // From ImplicitSurface\n        //! @copydoc ImplicitSurface::transform(const rw::math::Transform3D<>&) const\n        QuadraticSurface::Ptr transform (const rw::math::Transform3D<>& T) const;\n\n        //! @copydoc ImplicitSurface::transform(const rw::math::Vector3D<double>&) const\n        QuadraticSurface::Ptr transform (const rw::math::Vector3D<double>& P) const;\n\n        //! @copydoc ImplicitSurface::scale\n        QuadraticSurface::Ptr scale (double factor) const;\n\n        //! @copydoc ImplicitSurface::clone\n        QuadraticSurface::Ptr clone () const;\n\n        //! @copydoc ImplicitSurface::extremums\n        virtual std::pair< double, double > extremums (const rw::math::Vector3D<double>& direction) const;\n\n        //! @copydoc ImplicitSurface::getTriMesh\n        virtual rw::core::Ptr< TriMesh >\n        getTriMesh (const std::vector< rw::math::Vector3D<double> >& border =\n                        std::vector< rw::math::Vector3D<double> > ()) const;\n\n        //! @copydoc ImplicitSurface::setDiscretizationResolution\n        virtual void setDiscretizationResolution (double resolution)\n        {\n            _stepsPerRevolution = resolution;\n        }\n\n        //! @copydoc ImplicitSurface::equals\n        virtual bool equals (const Surface& surface, double threshold) const;\n\n#if !defined(SWIG)\n        //! @copydoc ImplicitSurface::operator()(const rw::math::Vector3D<double>&) const\n        virtual double operator() (const rw::math::Vector3D<double>& x) const;\n#else \n        CALLOPERATOR(double,const rw::math::Vector3D<double>& );\n#endif \n\n        //! @copydoc ImplicitSurface::insideTrimmingRegion\n        virtual bool insideTrimmingRegion (const rw::math::Vector3D<double>& P) const;\n\n        //! @copydoc ImplicitSurface::normal\n        virtual rw::math::Vector3D<double> normal (const rw::math::Vector3D<double>& x) const;\n\n        //! @copydoc ImplicitSurface::gradient\n        virtual rw::math::Vector3D<double> gradient (const rw::math::Vector3D<double>& x) const;\n\n        //! @copydoc ImplicitSurface::reuseTrimmingRegions\n        virtual void reuseTrimmingRegions (rw::geometry::ImplicitSurface::Ptr surface) const;\n\n        //! @brief Get the 3 x 3 symmetric matrix for the second order term in the implicit\n        //! formulation.\n        const Eigen::Matrix3d& A () const { return _A; }\n\n        //! @brief Get the 3d vector for the first order term in the implicit formulation.\n        const Eigen::Vector3d& a () const { return _a; }\n\n        //! @brief Get the scalar for the zero order term in the implicit formulation.\n        double u () const { return _u; }\n\n        /**\n         * @brief Get the determinant of the \\f$ \\mathbf{A} \\f$ matrix.\n         * @return the determinant.\n         */\n        double determinantA () const { return _determinantA; }\n\n        /**\n         * @brief Normalize the implicit expression such that the largest coefficient becomes one.\n         *\n         * For a quadratic surface, a scaling of \\f$ \\mathbf{A}, \\mathbf{a} \\f$ and u with a common\n         * factor, will give the exact same surface. This means that the numerical values can get\n         * arbitrarily big or small. This functions scales the expression such that the largest\n         * element becomes 1.\n         *\n         * @return a mathematically identical surface, where the coefficients of the defining\n         * equation is normalized.\n         */\n        QuadraticSurface::Ptr normalize () const;\n\n        /**\n         * @brief Get the trimming conditions for the surface.\n         * @return ImplicitSurface vector specifying the boundary of the surface. If surface is\n         * unbounded, the length of the vector is zero.\n         */\n        const std::vector< TrimmingRegion >& getTrimmingConditions () const { return _conditions; }\n\n        /**\n         * @brief Set the trimming conditions of this surface.\n         * @param conditions [in] a vector of conditions.\n         */\n        void setTrimmingConditions (const std::vector< TrimmingRegion >& conditions)\n        {\n            _conditions = conditions;\n        }\n\n        /**\n         * @brief Add a trimming condition to this surface.\n         * @param condition [in] the condition to add.\n         */\n        void addTrimmingCondition (const TrimmingRegion& condition)\n        {\n            _conditions.push_back (condition);\n        }\n\n        /**\n         * @brief Get a diagonalization of the surface.\n         * @return the diagonalized surface, and the rotation transforming this surface into the\n         * diagonalized surface.\n         */\n        std::pair< QuadraticSurface, rw::math::Rotation3D<> > diagonalize () const;\n\n        /**\n         * @brief Check if this surface is diagonalized.\n         * @return true if A is digaonalized, false otherwise.\n         */\n        bool diagonalized () const { return _diagonal; }\n\n/** @name Normal forms of Quadratic Surfaces\n * Functions for creation of standard Quadratic Surfaces.\n */\n#if !defined(SWIG)\n///@{\n#endif\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create an ellipsoid with radii \\b a, \\b b, and \\b c respectively.\n         *\n         * \\image html geometry/quadrics_ellipsoid.gif \"Normal form of Quadratic Surface:\n         * Ellipsoid.\"\n         *\n         * @param a [in] radius in the \\f$ x_1 \\f$ direction.\n         * @param b [in] radius in the \\f$ x_2 \\f$ direction.\n         * @param c [in] radius in the \\f$ x_3 \\f$ direction.\n         * @return a QuadraticSurface representation of an ellipsoid.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeEllipsoid (double a, double b, double c);\n\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create a spheroid (special case of the ellipsoid).\n         *\n         * \\image html geometry/quadrics_spheroid.gif \"Normal form of Quadratic Surface: Spheroid\n         * (special case of ellipsoid).\"\n         *\n         * @param a [in] radius in the \\f$ x_1 \\f$ and \\f$ x_2 \\f$ directions.\n         * @param b [in] radius in the \\f$ x_3 \\f$ direction.\n         * @return a QuadraticSurface representation of a spheroid.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeSpheroid (double a, double b);\n\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create a sphere (special case of the ellipsoid and spheroid).\n         *\n         * \\image html geometry/quadrics_sphere.gif \"Normal form of Quadratic Surface: Sphere\n         * (special case of ellipsoid and spheroid).\"\n         *\n         * @param radius [in] radius of the sphere.\n         * @return a QuadraticSurface representation of a sphere.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeSphere (double radius);\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create an elliptic paraboloid.\n         *\n         * \\image html geometry/quadrics_elliptic_paraboloid.gif \"Normal form of Quadratic Surface:\n         * Elliptic Paraboloid.\"\n         *\n         * @param a [in] radius of the ellipse in the \\f$ x_1\\f$ direction when \\f$ x_3=1\\f$ .\n         * @param b [in] radius of the ellipse in the \\f$ x_2\\f$ direction when \\f$ x_3=1\\f$ .\n         * @return a QuadraticSurface representation of an elliptic paraboloid.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeEllipticParaboloid (double a, double b);\n\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create a circular paraboloid (special case of elliptic paraboloid).\n         *\n         * \\image html geometry/quadrics_circular_paraboloid.gif \"Normal form of Quadratic Surface:\n         * Circular Paraboloid (special case of elliptic paraboloid).\"\n         *\n         * @param a [in] radius of the circle when \\f$ x_3=1\\f$ .\n         * @return a QuadraticSurface representation of a circular paraboloid.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeCircularParaboloid (double a);\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create a hyperbolic paraboloid.\n         *\n         * \\image html geometry/quadrics_hyperbolic_paraboloid.gif \"Normal form of Quadratic\n         * Surface: Hyperbolic Paraboloid.\"\n         *\n         * @param a [in] width in the \\f$ x_1\\f$ direction when \\f$ x_3=1\\f$ .\n         * @param b [in] width in the \\f$ x_2\\f$ direction when \\f$ x_3=-1\\f$ .\n         * @return a QuadraticSurface representation of a hyperbolic paraboloid.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeHyperbolicParaboloid (double a, double b);\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create an elliptic hyperboloid of one sheet.\n         *\n         * \\image html geometry/quadrics_elliptic_hyperboloid_onesheet.gif \"Normal form of Quadratic\n         * Surface: Elliptic Hyperboloid of One Sheet.\"\n         *\n         * @param a [in] radius of the ellipse in the \\f$ x_1\\f$ direction when \\f$ x_3=0\\f$ .\n         * @param b [in] radius of the ellipse in the \\f$ x_2\\f$ direction when \\f$ x_3=0\\f$ .\n         * @param c [in] radius is scaled with the factor \\f$ \\frac{1}{c}\\sqrt{x_3^2+c^2}\\f$ .\n         * @return a QuadraticSurface representation of an elliptic hyperboloid of one sheet.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeEllipticHyperboloidOneSheet (double a, double b, double c);\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create a circular hyperboloid of one sheet (special case of the elliptic\n         * hyperboloid of one sheet).\n         *\n         * \\image html geometry/quadrics_circular_hyperboloid_onesheet.gif \"Normal form of Quadratic\n         * Surface: Circular Hyperboloid of One Sheet (special case of elliptic hyperboloid of one\n         * sheet).\"\n         *\n         * @param a [in] radius of the circle in the \\f$ x_1\\f$ and \\f$ x_2\\f$ directions when\n         * \\f$ x_3=0\\f$ .\n         * @param b [in] radius is scaled along \\f$ x_3\\f$ , to \\f$ \\frac{a}{c}\\sqrt{x_3^2+c^2}\\f$ .\n         * @return a QuadraticSurface representation of a circular hyperboloid of one sheet.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeCircularHyperboloidOneSheet (double a, double b);\n\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create an elliptic hyperboloid of two sheets.\n         *\n         * \\image html geometry/quadrics_elliptic_hyperboloid_twosheets.gif \"Normal form of\n         * Quadratic Surface: Elliptic Hyperboloid of Two Sheets.\"\n         *\n         * @param a [in] radius of the ellipse in the \\f$ x_1\\f$ direction when\n         * \\f$ x_3=\\pm\\sqrt{2}c\\f$ .\n         * @param b [in] radius of the ellipse in the \\f$ x_2\\f$ direction when\n         * \\f$ x_3=\\pm\\sqrt{2}c\\f$ .\n         * @param c [in] distance from origo to each of the the two sheets.\n         * @return a QuadraticSurface representation of an elliptic hyperboloid of two sheets.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeEllipticHyperboloidTwoSheets (double a, double b,\n                                                                       double c);\n\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create a circular hyperboloid of two sheets (special case of the elliptic\n         * hyperboloid of two sheets).\n         *\n         * \\image html geometry/quadrics_circular_hyperboloid_twosheets.gif \"Normal form of\n         * Quadratic Surface: Circular Hyperboloid of Two Sheets (special case of elliptic\n         * hyperboloid of two sheets).\"\n         *\n         * @param a [in] radius of the circle in the \\f$ x_1\\f$ and \\f$ x_2\\f$ directions when\n         * \\f$ x_3=\\pm\\sqrt{2}b\\f$ .\n         * @param b [in] distance from origo to each of the the two sheets.\n         * @return a QuadraticSurface representation of a circular hyperboloid of two sheets.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeCircularHyperboloidTwoSheets (double a, double b);\n\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create an elliptic cone.\n         *\n         * The cone is a singular (or degenerate) surface as it has a point where the gradient\n         * vanishes. In the origo the gradient will always be zero, and no normal can be determined.\n         *\n         * \\image html geometry/quadrics_elliptic_cone.gif \"Normal form of Quadratic Surface:\n         * Elliptic Cone.\"\n         *\n         * @param a [in] radius of the ellipse in the \\f$ x_1\\f$ direction when \\f$ x_3=c\\f$ .\n         * @param b [in] radius of the ellipse in the \\f$ x_2\\f$ direction when \\f$ x_3=c\\f$ .\n         * @param c [in] rate of change for the radius.\n         * @return a QuadraticSurface representation of an elliptic cone.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeEllipticCone (double a, double b, double c);\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create a circular cone (special case of the elliptic cone).\n         *\n         * \\image html geometry/quadrics_circular_cone.gif \"Normal form of Quadratic Surface:\n         * Circular Cone (special case of elliptic cone).\"\n         *\n         * @param a [in] radius of the circle in the \\f$ x_1\\f$ and \\f$ x_2\\f$ directions when\n         * \\f$ x_3=c\\f$ .\n         * @param b [in] rate of change for the radius.\n         * @return a QuadraticSurface representation of a circular cone.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeCircularCone (double a, double b);\n\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create an elliptic cylinder.\n         *\n         * \\image html geometry/quadrics_elliptic_cylinder.gif \"Normal form of Quadratic Surface:\n         * Elliptic Cylinder.\"\n         *\n         * @param a [in] radius in the \\f$ x_1\\f$ direction.\n         * @param b [in] radius in the \\f$ x_2\\f$ direction.\n         * @return a QuadraticSurface representation of an elliptic cylinder.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeEllipticCylinder (double a, double b);\n\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create a circular cylinder (special case of the elliptic cylinder).\n         *\n         * \\image html geometry/quadrics_circular_cylinder.gif \"Normal form of Quadratic Surface:\n         * Circular Cylinder (special case of elliptic cylinder).\"\n         *\n         * @param radius [in] radius in the \\f$ x_1\\f$ and \\f$ x_2\\f$ directions.\n         * @param outward [in] (optional) set to false to create inner surface of cylinder, with\n         * normals pointing inwards.\n         * @return a QuadraticSurface representation of a circular cylinder.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeCircularCylinder (double radius, bool outward = true);\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create a hyperbolic cylinder.\n         *\n         * \\image html geometry/quadrics_hyperbolic_cylinder.gif \"Normal form of Quadratic Surface:\n         * Hyperbolic Cylinder.\"\n         *\n         * @param a [in] width in the \\f$ x_1\\f$ direction at \\f$ x_2=0\\f$ .\n         * @param b [in] controls the rate of change in the \\f$ x_1\\f$ direction.\n         * @return a QuadraticSurface representation of a hyperbolic cylinder.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeHyperbolicCylinder (double a, double b);\n\n#if !defined(SWIGJAVA)\n        /**\n         * @brief Create a parabolic cylinder.\n         *\n         * \\image html geometry/quadrics_parabolic_cylinder.gif \"Normal form of Quadratic Surface:\n         * Parabolic Cylinder.\"\n         *\n         * @param a [in] controls the focal length of the parabola.\n         * @return a QuadraticSurface representation of a parabolic cylinder.\n         */\n\n         #endif \n        static QuadraticSurface::Ptr makeParabolicCylinder (double a);\n#if !defined(SWIG)\n///@}\n#endif\n\n        /**\n         * @brief Represent a plane as a QuadraticSurface.\n         *\n         * A plane is a particularly simple type of quadratic surface, where\n         * \\f$ \\mathbf{A}=\\mathbf{0}\\f$ .\n         *\n         * Even though a plane is not strictly a quadratic surface, is is often convenient to be\n         * able to treat it like a quadratic surface.\n         *\n         * @param n [in] the normal of the plane.\n         * @param d [in] the distance from the plane to the origo.\n         * @return a QuadraticSurface representing a plane.\n         */\n        static QuadraticSurface::Ptr makePlane (const rw::math::Vector3D<double>& n, double d);\n\n      private:\n        QuadraticSurface (const Eigen::Matrix3d& A, bool diagonal, double determinantA,\n                          const Eigen::Vector3d& a, double u,\n                          const std::vector< TrimmingRegion >& conditions,\n                          double stepsPerRevolution);\n        #if !defined(SWIGJAVA)\n        // From ImplicitSurface\n        inline rw::geometry::ImplicitSurface::Ptr\n        doTransformImplicitSurface (const rw::math::Transform3D<>& T) const\n        {\n            return transform (T);\n        }\n        inline rw::geometry::ImplicitSurface::Ptr doTransformImplicitSurface (const rw::math::Vector3D<double>& P) const\n        {\n            return transform (P);\n        }\n        inline rw::geometry::ImplicitSurface::Ptr doScaleImplicitSurface (double factor) const\n        {\n            return scale (factor);\n        }\n        inline rw::geometry::ImplicitSurface::Ptr doCloneImplicitSurface () const { return clone (); }\n        #endif \n        rw::core::Ptr< TriMesh > getTriMeshDiagonal (\n            const std::vector< rw::math::Vector3D<double> >& border,\n            const rw::math::Rotation3D<>& R = rw::math::Rotation3D<>::identity ()) const;\n        std::pair< double, double > extremumsDiagonal (const rw::math::Vector3D<double>& dir) const;\n        std::vector< rw::geometry::QuadraticCurve > findSilhouette (std::size_t u, std::size_t v, std::size_t e,\n                                                      double eSplit) const;\n        typedef enum Place { FRONT, BACK, BOTH } Place;\n        void makeSurface (const std::vector< rw::math::Vector3D<double> > fullPolygon, std::size_t u,\n                          std::size_t v, std::size_t e, double eSplit, Place place,\n                          const rw::math::Rotation3D<>& R,\n                          rw::geometry::PlainTriMeshN1D::Ptr mesh) const;\n\n        const Eigen::Matrix3d _A;\n        const Eigen::Vector3d _a;\n        const double _u;\n        const double _determinantA;\n        const bool _diagonal;\n        std::vector< TrimmingRegion > _conditions;\n\n        double _stepsPerRevolution;\n    };\n#if !defined(SWIG)\n//! @}\n#endif\n}}    // namespace rw::geometry\n\n#endif /* RW_GEOMETRY_ANALYTIC_QUADRATICS_QUADRATICSURFACE_HPP_ */\n", "meta": {"hexsha": "53aca0c8f1012a42564d8e1d5d7adbeb297102a3", "size": 25161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/geometry/analytic/quadratics/QuadraticSurface.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/geometry/analytic/quadratics/QuadraticSurface.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/geometry/analytic/quadratics/QuadraticSurface.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6572847682, "max_line_length": 120, "alphanum_fraction": 0.6089980525, "num_tokens": 6304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6113057120777959}}
{"text": "/// Copyright (c) 2018-2021, Parker Owan.  All rights reserved.\n/// Licensed under BSD-3 Clause, https://opensource.org/licenses/BSD-3-Clause\n\n#include \"sia/math/math.h\"\n\n#include <glog/logging.h>\n#include <Eigen/SVD>\n\nnamespace sia {\n\nconst Eigen::VectorXd slice(const Eigen::VectorXd& x,\n                            const std::vector<std::size_t>& indices) {\n  Eigen::VectorXd y = Eigen::VectorXd::Zero(indices.size());\n  for (std::size_t i = 0; i < indices.size(); ++i) {\n    y(i) = x(indices.at(i));\n  }\n  return y;\n}\n\nconst Eigen::MatrixXd slice(const Eigen::MatrixXd& X,\n                            const std::vector<std::size_t>& rows,\n                            const std::vector<std::size_t>& cols) {\n  Eigen::MatrixXd Y = Eigen::MatrixXd::Zero(rows.size(), cols.size());\n  for (std::size_t i = 0; i < rows.size(); ++i) {\n    for (std::size_t j = 0; j < cols.size(); ++j) {\n      Y(i, j) = X(rows.at(i), cols.at(j));\n    }\n  }\n  return Y;\n}\n\nbool llt(const Eigen::MatrixXd& A, Eigen::MatrixXd& L) {\n  Eigen::LLT<Eigen::MatrixXd> llt(A);\n  L = llt.matrixL();\n  if (llt.info() != Eigen::ComputationInfo::Success) {\n    LOG(WARNING) << \"LLT decomposition of matrix A = \" << A << \" failed with \"\n                 << llt.info();\n    return false;\n  }\n  return true;\n}\n\nbool ldltSqrt(const Eigen::MatrixXd& A, Eigen::MatrixXd& M) {\n  Eigen::LDLT<Eigen::MatrixXd> ldlt(A);\n  const Eigen::MatrixXd I = Eigen::MatrixXd::Identity(A.rows(), A.cols());\n  const Eigen::MatrixXd P = ldlt.transpositionsP() * I;\n  const Eigen::MatrixXd L = ldlt.matrixL();\n  const Eigen::VectorXd D = ldlt.vectorD();\n  M = P.transpose() * L * D.array().sqrt().matrix().asDiagonal();\n  if (ldlt.info() != Eigen::ComputationInfo::Success) {\n    LOG(WARNING) << \"LDLT decomposition of matrix A = \" << A << \" failed with \"\n                 << ldlt.info();\n    return false;\n  }\n  return true;\n}\n\nbool svd(const Eigen::MatrixXd& A,\n         Eigen::MatrixXd& U,\n         Eigen::VectorXd& S,\n         Eigen::MatrixXd& V,\n         double tolerance) {\n  bool result = true;\n\n  // Compute the SVD of A\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(\n      A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  const Eigen::VectorXd& singular_values = svd.singularValues();\n\n  // Check for singular condition\n  for (int i = 0; i < singular_values.size(); ++i) {\n    if (singular_values(i) <= tolerance) {\n      LOG(WARNING) << \"Singular value is less than tolerance\";\n      result = false;\n    }\n  }\n\n  // Return SVD matrices\n  U = svd.matrixU();\n  S = singular_values.array();\n  V = svd.matrixV();\n  return result;\n}\n\nconst Eigen::MatrixXd svdInverse(const Eigen::MatrixXd& U,\n                                 const Eigen::VectorXd& S,\n                                 const Eigen::MatrixXd& V) {\n  return V * S.array().inverse().matrix().asDiagonal() * U.transpose();\n}\n\nbool svdInverse(const Eigen::MatrixXd& A,\n                Eigen::MatrixXd& Ainv,\n                double tolerance) {\n  Eigen::MatrixXd U, V;\n  Eigen::VectorXd S;\n  bool result = svd(A, U, S, V, tolerance);\n\n  // Compute the generalized inverse using SVD\n  Ainv = svdInverse(U, S, V);\n  return result;\n}\n\nconst Eigen::MatrixXd lltSqrt(const Eigen::MatrixXd& A) {\n  Eigen::LLT<Eigen::MatrixXd> llt(A);\n  return llt.matrixL();\n}\n\nconst Eigen::VectorXd rk4(\n    std::function<Eigen::VectorXd(const Eigen::VectorXd&,\n                                  const Eigen::VectorXd&)> dynamical_system,\n    const Eigen::VectorXd& x,\n    const Eigen::VectorXd& u,\n    double dt) {\n  Eigen::VectorXd f1 = dynamical_system(x, u);\n  Eigen::VectorXd f2 = dynamical_system(x + dt * f1 / 2, u);\n  Eigen::VectorXd f3 = dynamical_system(x + dt * f2 / 2, u);\n  Eigen::VectorXd f4 = dynamical_system(x + dt * f3, u);\n  return x + dt / 6 * (f1 + 2 * f2 + 2 * f3 + f4);\n}\n\nconst Eigen::VectorXd dfdx(std::function<double(const Eigen::VectorXd&)> f,\n                           const Eigen::VectorXd& x) {\n  std::size_t n = x.size();\n  Eigen::VectorXd df = Eigen::VectorXd::Zero(n);\n  for (std::size_t i = 0; i < n; ++i) {\n    Eigen::VectorXd dx = Eigen::VectorXd::Zero(n);\n    dx(i) = NUMERICAL_DERIVATIVE_STEP;\n    double fp = f(x + dx);\n    double fn = f(x - dx);\n    df(i) = (fp - fn) / 2 / NUMERICAL_DERIVATIVE_STEP;\n  }\n  return df;\n}\n\nconst Eigen::VectorXd dfdx(\n    std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&)> f,\n    const Eigen::VectorXd& x,\n    const Eigen::VectorXd& u) {\n  std::size_t n = x.size();\n  Eigen::VectorXd df = Eigen::VectorXd::Zero(n);\n  for (std::size_t i = 0; i < n; ++i) {\n    Eigen::VectorXd dx = Eigen::VectorXd::Zero(n);\n    dx(i) = NUMERICAL_DERIVATIVE_STEP;\n    double fp = f(x + dx, u);\n    double fn = f(x - dx, u);\n    df(i) = (fp - fn) / 2 / NUMERICAL_DERIVATIVE_STEP;\n  }\n  return df;\n}\n\nconst Eigen::MatrixXd dfdx(\n    std::function<Eigen::VectorXd(const Eigen::VectorXd&,\n                                  const Eigen::VectorXd&)> f,\n    const Eigen::VectorXd& x,\n    const Eigen::VectorXd& u) {\n  std::size_t n = x.size();\n  Eigen::MatrixXd Df;\n  for (std::size_t i = 0; i < n; ++i) {\n    Eigen::VectorXd dx = Eigen::VectorXd::Zero(n);\n    dx(i) = NUMERICAL_DERIVATIVE_STEP;\n    Eigen::VectorXd fp = f(x + dx, u);\n    Eigen::VectorXd fn = f(x - dx, u);\n    if (i == 0) {\n      Df = Eigen::MatrixXd::Zero(fp.size(), n);\n    }\n    Df.col(i) = (fp - fn) / 2 / NUMERICAL_DERIVATIVE_STEP;\n  }\n  return Df;\n}\n\nconst Eigen::VectorXd dfdu(\n    std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&)> f,\n    const Eigen::VectorXd& x,\n    const Eigen::VectorXd& u) {\n  std::size_t n = u.size();\n  Eigen::VectorXd df = Eigen::VectorXd::Zero(n);\n  for (std::size_t i = 0; i < n; ++i) {\n    Eigen::VectorXd du = Eigen::VectorXd::Zero(n);\n    du(i) = NUMERICAL_DERIVATIVE_STEP;\n    double fp = f(x, u + du);\n    double fn = f(x, u - du);\n    df(i) = (fp - fn) / 2 / NUMERICAL_DERIVATIVE_STEP;\n  }\n  return df;\n}\n\nconst Eigen::MatrixXd dfdu(\n    std::function<Eigen::VectorXd(const Eigen::VectorXd&,\n                                  const Eigen::VectorXd&)> f,\n    const Eigen::VectorXd& x,\n    const Eigen::VectorXd& u) {\n  std::size_t n = u.size();\n  Eigen::MatrixXd Df;\n  for (std::size_t i = 0; i < n; ++i) {\n    Eigen::VectorXd du = Eigen::VectorXd::Zero(n);\n    du(i) = NUMERICAL_DERIVATIVE_STEP;\n    Eigen::VectorXd fp = f(x, u + du);\n    Eigen::VectorXd fn = f(x, u - du);\n    if (i == 0) {\n      Df = Eigen::MatrixXd::Zero(fp.size(), n);\n    }\n    Df.col(i) = (fp - fn) / 2 / NUMERICAL_DERIVATIVE_STEP;\n  }\n  return Df;\n}\n\nconst Eigen::MatrixXd d2fdxx(std::function<double(const Eigen::VectorXd&)> f,\n                             const Eigen::VectorXd& x) {\n  std::size_t n = x.size();\n  Eigen::MatrixXd H = Eigen::MatrixXd::Zero(n, n);\n  for (std::size_t i = 0; i < n; ++i) {\n    Eigen::VectorXd dx = Eigen::VectorXd::Zero(n);\n    dx(i) = NUMERICAL_DERIVATIVE_STEP;\n    Eigen::VectorXd fp = dfdx(f, x + dx);\n    Eigen::VectorXd fn = dfdx(f, x - dx);\n    H.col(i) = (fp - fn) / 2 / NUMERICAL_DERIVATIVE_STEP;\n  }\n  // Ensure that the Hessian is necessarily symmetric\n  return (H + H.transpose()) / 2.0;\n}\n\nconst Eigen::MatrixXd d2fdxx(\n    std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&)> f,\n    const Eigen::VectorXd& x,\n    const Eigen::VectorXd& u) {\n  std::size_t n = x.size();\n  Eigen::MatrixXd H = Eigen::MatrixXd::Zero(n, n);\n  for (std::size_t i = 0; i < n; ++i) {\n    Eigen::VectorXd dx = Eigen::VectorXd::Zero(n);\n    dx(i) = NUMERICAL_DERIVATIVE_STEP;\n    Eigen::VectorXd fp = dfdx(f, x + dx, u);\n    Eigen::VectorXd fn = dfdx(f, x - dx, u);\n    H.col(i) = (fp - fn) / 2 / NUMERICAL_DERIVATIVE_STEP;\n  }\n  // Ensure that the Hessian is necessarily symmetric\n  return (H + H.transpose()) / 2.0;\n}\n\nconst Eigen::MatrixXd d2fduu(\n    std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&)> f,\n    const Eigen::VectorXd& x,\n    const Eigen::VectorXd& u) {\n  std::size_t n = u.size();\n  Eigen::MatrixXd H = Eigen::MatrixXd::Zero(n, n);\n  for (std::size_t i = 0; i < n; ++i) {\n    Eigen::VectorXd du = Eigen::VectorXd::Zero(n);\n    du(i) = NUMERICAL_DERIVATIVE_STEP;\n    Eigen::VectorXd fp = dfdu(f, x, u + du);\n    Eigen::VectorXd fn = dfdu(f, x, u - du);\n    H.col(i) = (fp - fn) / 2 / NUMERICAL_DERIVATIVE_STEP;\n  }\n  // Ensure that the Hessian is necessarily symmetric\n  return (H + H.transpose()) / 2.0;\n}\n\nconst Eigen::MatrixXd d2fdux(\n    std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&)> f,\n    const Eigen::VectorXd& x,\n    const Eigen::VectorXd& u) {\n  std::size_t m = x.size();\n  std::size_t n = u.size();\n  Eigen::MatrixXd H = Eigen::MatrixXd::Zero(m, n);\n  for (std::size_t i = 0; i < n; ++i) {\n    Eigen::VectorXd du = Eigen::VectorXd::Zero(n);\n    du(i) = NUMERICAL_DERIVATIVE_STEP;\n    Eigen::VectorXd fp = dfdx(f, x, u + du);\n    Eigen::VectorXd fn = dfdx(f, x, u - du);\n    H.col(i) = (fp - fn) / 2 / NUMERICAL_DERIVATIVE_STEP;\n  }\n  // Ensure that the Hessian is necessarily symmetric\n  // return (H + H.transpose()) / 2.0;\n  return H;\n}\n\ndouble frobNormSquared(const Eigen::MatrixXd& A) {\n  assert(A.rows() == A.cols());\n  double p = double(A.rows());\n  return (A * A.transpose()).trace() / p;\n}\n\nconst Eigen::MatrixXd estimateCovariance(const Eigen::MatrixXd& samples) {\n  // See: \"A Well-Conditioned Estimator for Large-dimensional Covariance\n  // Matrices\", 2004.\n  std::size_t n = samples.cols();\n  std::size_t d = samples.rows();\n  double p = double(d);\n  const Eigen::MatrixXd cov = samples * samples.transpose() / double(n);\n  double mu = cov.trace() / p;\n  const Eigen::MatrixXd muI = mu * Eigen::MatrixXd::Identity(d, d);\n  double d2 = frobNormSquared(cov - muI);\n  double b2 = 0;\n  for (std::size_t i = 0; i < n; ++i) {\n    const Eigen::VectorXd& x = samples.col(i);\n    b2 += frobNormSquared(x * x.transpose() - cov);\n  }\n  b2 /= pow(double(n), 2);\n  b2 = std::min(d2, b2);\n  double shrinkage = b2 / d2;\n  return (1 - shrinkage) * cov + shrinkage * muI;\n}\n\n}  // namespace sia\n", "meta": {"hexsha": "301b72772ef7092df493e616abc7be9137676d16", "size": 9942, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sia/math/math.cpp", "max_stars_repo_name": "parkerowan/libsia", "max_stars_repo_head_hexsha": "84e0054f5fc1ee1ec61a7de74208a6620d437859", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sia/math/math.cpp", "max_issues_repo_name": "parkerowan/libsia", "max_issues_repo_head_hexsha": "84e0054f5fc1ee1ec61a7de74208a6620d437859", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sia/math/math.cpp", "max_forks_repo_name": "parkerowan/libsia", "max_forks_repo_head_hexsha": "84e0054f5fc1ee1ec61a7de74208a6620d437859", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8118811881, "max_line_length": 79, "alphanum_fraction": 0.5977670489, "num_tokens": 2979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.727975443004307, "lm_q1q2_score": 0.6113057071219629}}
{"text": "/*\nthis file should cover the following functions in hmm.h\n- hmm_vec2 HMM_MultiplyVec2(hmm_vec2 Left, hmm_vec2 Right);\n- hmm_vec2 HMM_MultiplyVec2f(hmm_vec2 Left, float Right);\n- hmm_vec3 HMM_MultiplyVec3(hmm_vec3 Left, hmm_vec3 Right);\n- hmm_vec3 HMM_MultiplyVec3f(hmm_vec3 Left, float Right);\n- hmm_vec4 HMM_MultiplyVec4(hmm_vec4 Left, hmm_vec4 Right);\n- hmm_vec4 HMM_MultiplyVec4f(hmm_vec4 Left, float Right);\n- hmm_mat4 HMM_MultiplyMat4(hmm_mat4 Left, hmm_mat4 Right);\n- hmm_mat4 HMM_MultiplyMat4f(hmm_mat4 Matrix, float Scalar);\n- hmm_vec4 HMM_MultiplyMat4ByVec4(hmm_mat4 Matrix, hmm_vec4 Vector);\n\ntake care of operator overloading also for these functions:\n- hmm_vec2 operator*(hmm_vec2 Left, hmm_vec2 Right);\n- hmm_vec3 operator*(hmm_vec3 Left, hmm_vec3 Right);\n- hmm_vec4 operator*(hmm_vec4 Left, hmm_vec4 Right);\n- hmm_mat4 operator*(hmm_mat4 Left, hmm_mat4 Right);\n- hmm_vec2 operator*(hmm_vec2 Left, float Right);\n- hmm_vec3 operator*(hmm_vec3 Left, float Right);\n- hmm_vec4 operator*(hmm_vec4 Left, float Right);\n- hmm_mat4 operator*(hmm_mat4 Left, float Right);\n- hmm_vec2 operator*(float Left, hmm_vec2 Right);\n- hmm_vec3 operator*(float Left, hmm_vec3 Right);\n- hmm_vec4 operator*(float Left, hmm_vec4 Right);\n- hmm_mat4 operator*(float Left, hmm_mat4 Right);\n- hmm_vec4 operator*(hmm_mat4 Matrix, hmm_vec4 Vector);\n- hmm_vec2 &operator*=(hmm_vec2 &Left, hmm_vec2 Right);\n- hmm_vec3 &operator*=(hmm_vec3 &Left, hmm_vec3 Right);\n- hmm_vec4 &operator*=(hmm_vec4 &Left, hmm_vec4 Right);\n- hmm_vec2 &operator*=(hmm_vec2 &Left, float Right);\n- hmm_vec3 &operator*=(hmm_vec3 &Left, float Right);\n- hmm_vec4 &operator*=(hmm_vec4 &Left, float Right);\n- hmm_mat4 &operator*=(hmm_mat4 &Left, float Right);\n*/\n#define BOOST_TEST_MAIN\n#include <boost/test/unit_test.hpp>\n#include \"HMM.h\"\n#include \"test_helpers.h\"\nnamespace utf = boost::unit_test;\nnamespace tt = boost::test_tools;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(multiplication_test_suite)\n\nBOOST_AUTO_TEST_SUITE(multiplication_vec2_by_int, *utf::label(\"trivial\"))\n\nBOOST_AUTO_TEST_CASE(test_HMM_MultiplyVec2_int_BothVecsZeros, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto zeros = HMM_Vec2i(0, 0);\n    //Act\n    auto res = HMM_MultiplyVec2(zeros, zeros);\n    //Assert\n    float expectedRes[2] = {0, 0};\n    BOOST_TEST(res.Elements == expectedRes);\n}\n\nBOOST_AUTO_TEST_CASE(test_HMM_MultiplyVec2_int_V1_zeros, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto zeros = HMM_Vec2i(0, 0);\n    auto right = HMM_Vec2i(5, -10);\n    //Act\n    auto res = HMM_MultiplyVec2(zeros, right);\n    //Assert\n    float expectedRes[2] = {0, 0};\n    BOOST_TEST(res.Elements == expectedRes);\n}\n\nBOOST_AUTO_TEST_CASE(test_HMM_MultiplyVec2_int_postives, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2i(1, 5);\n    auto right = HMM_Vec2i(3, 4);\n    //Act\n    auto res = HMM_MultiplyVec2(left, right);\n    //Assert\n    float expectedRes[2] = {left.Elements[0] * right.Elements[0], left.Elements[1] * right.Elements[1]};\n    BOOST_TEST(res.Elements == expectedRes);\n}\n\nBOOST_AUTO_TEST_CASE(test_HMM_MultiplyVec2_int_pos_neg, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2i(1, 5);\n    auto right = HMM_Vec2i(-3, -4);\n    //Act\n    auto res = HMM_MultiplyVec2(left, right);\n    //Assert\n    float expectedRes[2] = {left.Elements[0] * right.Elements[0], left.Elements[1] * right.Elements[1]};\n    BOOST_TEST(vector<float>(res.Elements, res.Elements + 2) == vector<float>({left.Elements[0] * right.Elements[0], left.Elements[1] * right.Elements[1]}));\n}\n\nBOOST_AUTO_TEST_CASE(test_HMM_MultiplyVec2_float_pos_neg, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(.5, .2);\n    auto right = HMM_Vec2(-2, -10.);\n    //Act\n    auto res = HMM_MultiplyVec2(left, right);\n    //Assert\n    float expectedRes[2] = {left.Elements[0] * right.Elements[0], left.Elements[1] * right.Elements[1]};\n    BOOST_TEST(res.Elements == expectedRes);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n//--------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(multiplication_vec2_by_float)\n\nBOOST_AUTO_TEST_CASE(test_HMM_MultiplyVec2f_vec_x_posfloat, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(.5, .2);\n    float right = 10.;\n    //Act\n    auto res = HMM_MultiplyVec2f(left, right);\n    //Assert\n    float expectedRes[2] = {left.Elements[0] * right, left.Elements[1] * right};\n    BOOST_TEST(res.Elements == expectedRes);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n//--------------------------------------------------------------\nBOOST_AUTO_TEST_SUITE(mul_vec2_using_operators)\n\nBOOST_AUTO_TEST_CASE(test_mul_vec2_by_vec2_using_mul_operator, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(10., 1.);\n    auto right = HMM_Vec2(-2, -5.);\n    //Act\n    auto res = left * right;\n    //Assert\n    float expectedRes[2] = {left.Elements[0] * right.Elements[0], left.Elements[1] * right.Elements[1]};\n    BOOST_TEST(res.Elements == expectedRes);\n}\n\nBOOST_AUTO_TEST_CASE(test_mul_vec2_by_float_using_mul_operator, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(.5, .2);\n    float right = 10.;\n    //Act\n    auto res = left * right;\n    //Assert\n    BOOST_TEST(vector<float>(res.Elements, res.Elements + 2) == vector<float>({left.Elements[0] * right, left.Elements[1] * right}));\n}\n\nBOOST_AUTO_TEST_CASE(test_mul_vec2_by_vec2_using_mul_equal_operator, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(.5, .2);\n    auto right = HMM_Vec2(-2, -5.);\n    //Act\n    auto res = left;\n    res *= right;\n    //Assert\n    BOOST_TEST(vector<float>(res.Elements, res.Elements + 2) == vector<float>({left.Elements[0] * right.Elements[0], left.Elements[1] * right.Elements[1]}));\n}\n\nBOOST_AUTO_TEST_CASE(test_mul_vec2_by_float_using_mul_equal_operator, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = HMM_Vec2(.5, .2);\n    float right = 10.;\n    //Act\n    auto res = left;\n    res *= right;\n    //Assert\n    BOOST_TEST(vector<float>(res.Elements, res.Elements + 2) == vector<float>({left.Elements[0] * right, left.Elements[1] * right}));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//--------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(multiplication_mat4_by_mat4)\n\nBOOST_AUTO_TEST_CASE(test_HMM_MultiplyMat4, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = hmm_mat4();\n    float arr[4][4] = {{1, 2, 3, 4},\n                       {5, -6, 7, 8},\n                       {9, 10, 11, 12},\n                       {0, 15, 0, 0}};\n    copy(&arr[0][0], &arr[0][0] + 4 * 4, &left.Elements[0][0]);\n\n    //Act\n    hmm_mat4 res = HMM_MultiplyMat4(left, left);\n\n    //Assert\n    float expMat[4][4] = {{38, 80, 50, 56},\n                          {38, 236, 50, 56},\n                          {158, 248, 218, 248},\n                          {75, -90, 105, 120}};\n\n    BOOST_TEST(res.Elements == expMat);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//--------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(multiplication_mat4_by_floatscalar)\n\nBOOST_AUTO_TEST_CASE(test_HMM_MultiplyMat4f, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = hmm_mat4();\n    float arr[4][4] = {{1, 2, 3, 4},\n                       {5, -6, 7, 8},\n                       {9, 10, 11, 12},\n                       {0, 15, 0, 0}};\n    copy(&arr[0][0], &arr[0][0] + 4 * 4, &left.Elements[0][0]);\n\n    float right = .5;\n    //Act\n    hmm_mat4 res = HMM_MultiplyMat4f(left, right);\n\n    //Assert\n    float expMat[4][4] = {{arr[0][0] * right, arr[0][1] * right, arr[0][2] * right, arr[0][3] * right},\n                          {arr[1][0] * right, arr[1][1] * right, arr[1][2] * right, arr[1][3] * right},\n                          {arr[2][0] * right, arr[2][1] * right, arr[2][2] * right, arr[2][3] * right},\n                          {arr[3][0] * right, arr[3][1] * right, arr[3][2] * right, arr[3][3] * right}};\n\n    BOOST_TEST(res.Elements == expMat);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n//--------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(multiplication_mat4_by_vec4)\n\nBOOST_AUTO_TEST_CASE(test_HMM_MultiplyMat4ByVec4, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = hmm_mat4();\n    float arr[4][4] = {{1, 2, 3, 4},\n                       {5, -6, 7, 8},\n                       {9, 10, 11, 12},\n                       {0, 15, 0, 0}};\n    copy(&arr[0][0], &arr[0][0] + 4 * 4, &left.Elements[0][0]);\n\n    hmm_vec4 right = HMM_Vec4(.5, 1., 0., -3.);\n    //Act\n    hmm_vec4 res = HMM_MultiplyMat4ByVec4(left, right);\n    //Assert\n    float expRes[] = {5.5, -50, 8.5, 10};\n    BOOST_TEST(res.Elements == expRes);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n//--------------------------------------------------------------\n\nBOOST_AUTO_TEST_SUITE(multiplication_using_operators)\n\nBOOST_AUTO_TEST_CASE(test_mul_mat4_by_mat4_using_mul_operator, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = hmm_mat4();\n    float arr[4][4] = {{1, 2, 3, 4},\n                       {5, -6, 7, 8},\n                       {9, 10, 11, 12},\n                       {0, 15, 0, 0}};\n    copy(&arr[0][0], &arr[0][0] + 4 * 4, &left.Elements[0][0]);\n\n    //Act\n    hmm_mat4 res = left * left;\n\n    //Assert\n    float expMat[4][4] = {{38, 80, 50, 56},\n                          {38, 236, 50, 56},\n                          {158, 248, 218, 248},\n                          {75, -90, 105, 120}};\n\n    BOOST_TEST(res.Elements == expMat);\n}\n\nBOOST_AUTO_TEST_CASE(test_mul_mat4_by_floatscalar_using_mul_operator, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = hmm_mat4();\n    float arr[4][4] = {{1, 2, 3, 4},\n                       {5, -6, 7, 8},\n                       {9, 10, 11, 12},\n                       {0, 15, 0, 0}};\n    copy(&arr[0][0], &arr[0][0] + 4 * 4, &left.Elements[0][0]);\n\n    float right = .5;\n    //Act\n    hmm_mat4 res = left * right;\n    //Assert\n    float expMat[4][4] = {{arr[0][0] * right, arr[0][1] * right, arr[0][2] * right, arr[0][3] * right},\n                          {arr[1][0] * right, arr[1][1] * right, arr[1][2] * right, arr[1][3] * right},\n                          {arr[2][0] * right, arr[2][1] * right, arr[2][2] * right, arr[2][3] * right},\n                          {arr[3][0] * right, arr[3][1] * right, arr[3][2] * right, arr[3][3] * right}};\n\n    BOOST_TEST(res.Elements == expMat);\n}\n\nBOOST_AUTO_TEST_CASE(test_mul_mat4_by_vec4_using_mul_operator, *utf::tolerance(0.00001)) {\n    //Arrange\n    auto left = hmm_mat4();\n    float arr[4][4] = {{1, 2, 3, 4},\n                       {5, -6, 7, 8},\n                       {9, 10, 11, 12},\n                       {0, 15, 0, 0}};\n    copy(&arr[0][0], &arr[0][0] + 4 * 4, &left.Elements[0][0]);\n\n    hmm_vec4 right = HMM_Vec4(.5, 1., 0., -3.);\n    //Act\n    hmm_vec4 res = left * right;\n    //Assert\n    float epxRes[] = {5.5, -50, 8.5, 10};\n    BOOST_TEST(res.Elements == epxRes);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "366c5c08b277124ee93d76ba98cbcdb611cc0aae", "size": 10889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Test-HMM/tests/tests_mul.cpp", "max_stars_repo_name": "AmmarRabie/Test-HMM", "max_stars_repo_head_hexsha": "2fb6dac9b6144030b585200e89e516a53bc97e66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Test-HMM/tests/tests_mul.cpp", "max_issues_repo_name": "AmmarRabie/Test-HMM", "max_issues_repo_head_hexsha": "2fb6dac9b6144030b585200e89e516a53bc97e66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Test-HMM/tests/tests_mul.cpp", "max_forks_repo_name": "AmmarRabie/Test-HMM", "max_forks_repo_head_hexsha": "2fb6dac9b6144030b585200e89e516a53bc97e66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2394822006, "max_line_length": 157, "alphanum_fraction": 0.5926164019, "num_tokens": 3478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.611286425657932}}
{"text": "/** \\file student_t_distribution.hpp \n    \\brief Student's t probability distribution */\n/*\n-------------------------------------------------------------------------\n   This file is part of BayesOpt, an efficient C++ library for \n   Bayesian optimization.\n\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   BayesOpt is free software: you can redistribute it and/or modify it \n   under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   BayesOpt is distributed in the hope that it will be useful, but \n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.\n------------------------------------------------------------------------\n*/\n\n\n#ifndef __STUDENT_T_DISTRIBUTION_HPP__\n#define __STUDENT_T_DISTRIBUTION_HPP__\n\n// for student t distribution\n#include <boost/math/distributions/students_t.hpp> \n#include \"prob_distribution.hpp\"\n\nnamespace bayesopt\n{\n\n  class StudentTDistribution: public ProbabilityDistribution\n  {\n  public:\n    StudentTDistribution(randEngine& eng);\n    virtual ~StudentTDistribution();\n\n    /** \n     * \\brief Sets the mean and std of the distribution\n     */\n    void setMeanAndStd(double mean, double std)\n    { mean_ = mean; std_ = std; };\n\n    /** \n     * \\brief Sets the degrees of freedom (dof) the distribution\n     */\n    void setDof(size_t dof)\n    { \n      dof_ = dof; \n      boost::math::students_t new_d(dof);\n      d_ = new_d;\n    };\n\n    /** \n     * \\brief Probability density function\n     * @param x query point\n     * @return probability\n     */\n    double pdf(double x) \n    {\n      x = (x - mean_) / std_;\n      return boost::math::pdf(d_,x); \n    };\n\n    /** \n     * \\brief Expected Improvement algorithm for minimization\n     * @param min  minimum value found\n     * @param g exponent (used for annealing)\n     *\n     * @return negative value of the expected improvement\n     */\n    double negativeExpectedImprovement(double min, size_t g);\n\n    /** \n     * \\brief Lower confindence bound. Can be seen as the inverse of the Upper \n     * confidence bound\n     * @param beta std coefficient (used for annealing)\n     * @return value of the lower confidence bound\n     */\n    double lowerConfidenceBound(double beta);\n\n    /** \n     * Probability of improvement algorithm for minimization\n     * @param min  minimum value found\n     * @param epsilon minimum improvement margin\n     * \n     * @return negative value of the probability of improvement\n     */\n    double negativeProbabilityOfImprovement(double min,\n\t\t\t\t\t    double epsilon);\n\n    /** \n     * Sample outcome acording to the marginal distribution at the query point.\n     * @return outcome\n     */\n    double sample_query();\n\n    double getMean() { return mean_; };\n    double getStd()  { return std_; };\n\n  private:\n    boost::math::students_t d_;\n    double mean_;\n    double std_;\n    size_t dof_;\n  };\n\n} //namespace bayesopt\n\n#endif\n", "meta": {"hexsha": "c5605a2c18dc9efd44ee7dd1bd6b40e93d58f275", "size": 3265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/include/student_t_distribution.hpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/include/student_t_distribution.hpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/include/student_t_distribution.hpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 28.3913043478, "max_line_length": 79, "alphanum_fraction": 0.6444104135, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6112065887097933}}
{"text": "#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <iostream>\n\nusing namespace boost::geometry;\nusing namespace std;\n\nint main()\n{\n\ttypedef model::d2::point_xy<double> pointtype;\n\tpointtype point1(3, 3);\n\tpointtype point2(2, 12.1);\n\n\tmodel::polygon<pointtype> poly;\n\tpointtype points[] = {pointtype(0, 0), pointtype(0, 10), pointtype(5, 15),\n\t\t\t\t\t\t  pointtype(10, 10), pointtype(10, 0), pointtype(0, 0)};\n\tappend(poly, points);\n\n\tcout << wkt(point1) << \" is \"\n\t\t << (within(point1, poly) ? \"inside\" : \"outside of\") << \" the \"\n\t\t << wkt(poly) << endl;\n\tcout << wkt(point2) << \" is \"\n\t\t << (within(point2, poly) ? \"inside\" : \"outside of\") << \" the \"\n\t\t << wkt(poly) << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "f43ddd1082e13989456860323804bdb9b3c7d3ec", "size": 773, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Cpp SOURCE CODE/Boost/Geometry/pointinpoly.cxx", "max_stars_repo_name": "DevJeffersonL/OPEN-SOURCE-", "max_stars_repo_head_hexsha": "8e650337ebab7608a4bdb5106df74e17b0e0e995", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-30T06:19:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:19:22.000Z", "max_issues_repo_path": "Cpp SOURCE CODE/Boost/Geometry/pointinpoly.cxx", "max_issues_repo_name": "DevJeffersonL/OPEN-SOURCE-CODE", "max_issues_repo_head_hexsha": "8e650337ebab7608a4bdb5106df74e17b0e0e995", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cpp SOURCE CODE/Boost/Geometry/pointinpoly.cxx", "max_forks_repo_name": "DevJeffersonL/OPEN-SOURCE-CODE", "max_forks_repo_head_hexsha": "8e650337ebab7608a4bdb5106df74e17b0e0e995", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6071428571, "max_line_length": 75, "alphanum_fraction": 0.6429495472, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6112023747325521}}
{"text": "#include <catch2/catch.hpp>\n\n#include <Eigen/Geometry>\n#include <finitediff.hpp>\n#include <igl/PI.h>\n\n#include <ipc/distance/edge_edge.hpp>\n\n#include <autodiff/autodiff_types.hpp>\n#include <geometry/distance.hpp>\n#include <logger.hpp>\n#include <utils/not_implemented_error.hpp>\n\nusing namespace ipc::rigid;\n\n//-----------------------------------------------------------------------------\n// Unsigned Distances\n//-----------------------------------------------------------------------------\n\nTEST_CASE(\"Edge-edge distance gradient\", \"[distance][gradient]\")\n{\n    using namespace ipc::rigid;\n    typedef AutodiffType<12> Diff;\n    Diff::activate();\n\n    // Generate a geometric space of\n    double angle = 0;\n    SECTION(\"Almost parallel\")\n    {\n        double exponent = GENERATE(range(-6, 3));\n        angle = pow(10, exponent) * igl::PI / 180.0;\n    }\n    // SECTION(\"Parallel\") { angle = 0; }\n\n    Diff::D2Vector3d ea0 = Diff::d2vars(0, Eigen::Vector3d(-1.0, 0, 0));\n    Diff::D2Vector3d ea1 = Diff::d2vars(3, Eigen::Vector3d(+1.0, 0, 0));\n    Diff::D2Vector3d eb0 =\n        Diff::d2vars(6, Eigen::Vector3d(cos(angle), 1, sin(angle)));\n    Diff::D2Vector3d eb1 = Diff::d2vars(\n        9, Eigen::Vector3d(cos(angle + igl::PI), 1, sin(angle + igl::PI)));\n\n    Diff::DDouble2 distance = ipc::edge_edge_distance(ea0, ea1, eb0, eb1);\n\n    // Compute the gradient using finite differences\n    Eigen::VectorXd x(12);\n    x.segment<3>(0) = Diff::get_value(ea0);\n    x.segment<3>(3) = Diff::get_value(ea1);\n    x.segment<3>(6) = Diff::get_value(eb0);\n    x.segment<3>(9) = Diff::get_value(eb1);\n    auto f = [](const Eigen::VectorXd& x) {\n        return ipc::edge_edge_distance(\n            Eigen::Vector3d(x.segment<3>(0)), Eigen::Vector3d(x.segment<3>(3)),\n            Eigen::Vector3d(x.segment<3>(6)), Eigen::Vector3d(x.segment<3>(9)));\n    };\n    Eigen::VectorXd fgrad;\n    fd::finite_gradient(x, f, fgrad);\n\n    CAPTURE(angle, distance.getGradient().transpose(), fgrad.transpose());\n    CHECK(distance.getValue() == Approx(1.0));\n    CHECK(fd::compare_gradient(distance.getGradient(), fgrad));\n    CHECK(distance.getHessian().squaredNorm() != 0.0);\n}\n\n//-----------------------------------------------------------------------------\n// Signed Distances\n//-----------------------------------------------------------------------------\n\ntemplate <typename T> int sign(T val) { return (T(0) < val) - (val < T(0)); }\n\nTEST_CASE(\"Point-line signed distance\", \"[distance]\")\n{\n    double expected_distance = GENERATE(-10, -1, -1e-4, 0, 1e-4, 1, 10);\n    Eigen::Vector2d p = Eigen::Vector2d::Random();\n    p.y() = expected_distance;\n    Eigen::Vector2d s0(-10, 0);\n    Eigen::Vector2d s1(-9, 0);\n\n    double distance = point_line_signed_distance(p, s0, s1);\n    CAPTURE(distance, expected_distance);\n    CHECK(sign(distance) == sign(expected_distance));\n}\n\nTEST_CASE(\"Line-line signed distance\", \"[distance]\")\n{\n    double expected_distance = GENERATE(-10, -1, -1e-4, 0, 1e-4, 1, 10);\n    Eigen::Vector3d line0_point0(-9.9, expected_distance, 0);\n    Eigen::Vector3d line0_point1(-10, expected_distance, 0);\n    Eigen::Vector3d line1_point0(0, 0, -10);\n    Eigen::Vector3d line1_point1(0, 0, -9.9);\n\n    double distance = line_line_signed_distance(\n        line0_point0, line0_point1, line1_point0, line1_point1);\n    CAPTURE(distance, expected_distance);\n    CHECK(sign(distance) == sign(expected_distance));\n}\n\nTEST_CASE(\"Point-plane signed distance\", \"[distance]\")\n{\n    double expected_distance = GENERATE(-10, -1, -1e-4, 0, 1e-4, 1, 10);\n    Eigen::Vector3d p = Eigen::Vector3d::Random();\n    p.y() = expected_distance;\n    Eigen::Vector3d p0 = Eigen::Vector3d::Random();\n    Eigen::Vector3d p1 = Eigen::Vector3d::Random();\n    Eigen::Vector3d p2 = Eigen::Vector3d::Random();\n    p0.y() = p1.y() = p2.y() = 0;\n    if (Eigen::Vector3d::UnitY().dot((p1 - p0).cross(p2 - p0)) < 0) {\n        std::swap(p1, p2);\n    }\n\n    double distance = point_plane_signed_distance(p, p0, p1, p2);\n    CAPTURE(distance, expected_distance);\n    CHECK(sign(distance) == sign(expected_distance));\n}\n", "meta": {"hexsha": "c7036afc783d74589e6b6e357ee23749bc591604", "size": 4071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/geometry/test_distance.cpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "tests/geometry/test_distance.cpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "tests/geometry/test_distance.cpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 35.7105263158, "max_line_length": 80, "alphanum_fraction": 0.595431098, "num_tokens": 1173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450968, "lm_q2_score": 0.6992544147913994, "lm_q1q2_score": 0.6112023678514086}}
{"text": "#include <itp/core>\n#include <fstream>\n#include <Eigen/Dense>\n\ndouble safe_acos(double value)\n{\n\tif (value <= -1.0)\n\t{\n\t\treturn itp::pi;\n\t}\n\telse if (value >= 1.0)\n\t{\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\treturn std::acos(value);\n\t}\n}\n\ndouble calcVolume(double RMOF, double R, double L)\n{\n\tdouble ret = 0;\n\tif (R <= RMOF - L)\n\t{\n\t\tret = 4 * itp::pi * R * R * R / 3;\n\t}\n\telse if (R > RMOF + L)\n\t{\n\t\tdouble hmax = std::sqrt(R * R - (RMOF - L) * (RMOF - L));\n\t\tdouble hmin = std::sqrt(R * R - (RMOF + L) * (RMOF + L));\n\t\tdouble dh = 1e-5;\n\t\tdouble r, alpha, belta, cosAlpha, cosBelta;\n\t\tfor (double h = hmin; h <= hmax; h += dh)\n\t\t{\n\t\t\tr = std::sqrt(R * R - h * h);\n\t\t\tcosAlpha = (r * r + L * L - RMOF * RMOF) / (2.0 * r * L);\n\t\t\tcosBelta = (L * L + RMOF * RMOF - r * r) / (2.0 * L * RMOF);\n\t\t\talpha = safe_acos(cosAlpha);\n\t\t\tbelta = safe_acos(cosBelta);\n\t\t\tret += dh * (alpha * r * r + belta * RMOF * RMOF - L * RMOF * std::sin(belta));\n\t\t}\n\t\tret += itp::pi / 3 * (3 * R - (R - hmax)) * (R - hmax) * (R - hmax);\n\t\tret += hmin * itp::pi * RMOF * RMOF;\n\t\tret *= 2;\n\t}\n\telse\n\t{\n\t\tdouble hmax = std::sqrt(R * R - (RMOF - L) * (RMOF - L));\n\t\tdouble dh = 1e-5;\n\t\tdouble r, alpha, belta, cosAlpha, cosBelta;\n\t\tfor (double h = 0; h <= hmax; h += dh)\n\t\t{\n\t\t\tr = std::sqrt(R * R - h * h);\n\t\t\tcosAlpha = (r * r + L * L - RMOF * RMOF) / (2.0 * r * L);\n\t\t\tcosBelta = (L * L + RMOF * RMOF - r * r) / (2.0 * L * RMOF);\n\t\t\talpha = safe_acos(cosAlpha);\n\n\t\t\tbelta = safe_acos(cosBelta);\n\n\t\t\tret += dh * (alpha * r * r + belta * RMOF * RMOF - L * RMOF * std::sin(belta));\n\t\t}\n\t\tret += itp::pi / 3 * (3 * R - (R - hmax)) * (R - hmax) * (R - hmax);\n\t\tret *= 2;\n\t}\n\treturn ret;\n}\n\n\nint main()\n{\n\tdouble upPos = 32.927;\n\tdouble lowPos = 27.073;\n\n\tdouble RMOF = 0.655;\n\tdouble L = 0.4;\n\tdouble dL = 0.001;\n\n\tint Lbin = RMOF / dL;\n\tdouble LMOF = upPos - lowPos;\n\tdouble Rmax = LMOF / 2;\n\tdouble dR = 0.002; // nm\n\tint Rbin = Rmax / dR;\n\n\tEigen::ArrayXXd totVolume(Lbin, Rbin);\n\ttotVolume.fill(0);\n\tfmt::print(\"{}\\n\", calcVolume(RMOF, 0.656, 0.001));\n\t\n\n}", "meta": {"hexsha": "0841c071726a75f1b32069e0f5d1b727fd5de425", "size": 2015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/analysis/testRDF.cpp", "max_stars_repo_name": "TING2938/Gmx2020PostAnalysis", "max_stars_repo_head_hexsha": "0859383946c05c7424adb1ffa72fd2f8066ce850", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-23T15:02:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T16:32:09.000Z", "max_issues_repo_path": "src/analysis/testRDF.cpp", "max_issues_repo_name": "jianghuili/Gmx2020PostAnalysis", "max_issues_repo_head_hexsha": "0859383946c05c7424adb1ffa72fd2f8066ce850", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/analysis/testRDF.cpp", "max_forks_repo_name": "jianghuili/Gmx2020PostAnalysis", "max_forks_repo_head_hexsha": "0859383946c05c7424adb1ffa72fd2f8066ce850", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-23T15:01:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T15:01:49.000Z", "avg_line_length": 22.3888888889, "max_line_length": 82, "alphanum_fraction": 0.5196029777, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.6688802603710085, "lm_q1q2_score": 0.6111401940203407}}
{"text": "/*\n * CubicInterpolation.hpp\n *\n *  Created on: Jan 21, 2020\n *      Author: Edo Jelavic\n *      Institute: ETH Zurich, Robotic Systems Lab\n */\n\n#pragma once\n\n#include <Eigen/Core>\n#include <vector>\n#include <map>\n#include \"grid_map_core/TypeDefs.hpp\"\n\n/*\n * For difference between bicubic convolution interpolation (piecewise cubic)\n * and bicubic interpolation see:\n *\n * https://en.wikipedia.org/wiki/Bicubic_interpolation\n *\n * R. Keys (1981). \"Cubic convolution interpolation for digital image processing\".\n * IEEE Transactions on Acoustics, Speech, and Signal Processing. 29 (6): 1153\u20131160.\n *\n*   https://web.archive.org/web/20051024202307/\n*   http://www.geovista.psu.edu/sites/geocomp99/Gc99/082/gc_082.htm\n */\n\nnamespace grid_map {\n\nclass GridMap;\n\n/*\n * Data structure (matrix) that contains data\n * necessary for interpolation. These are either 16\n * function values in the case of bicubic convolution interpolation\n * or function values and their derivatives for the case\n * of standard bicubic inteprolation.\n */\nusing FunctionValueMatrix = Eigen::Matrix4d;\n\n/*!\n * Takes the id requested, performs checks and returns\n * an id that it is within the specified bounds.\n * @param[in] idReq - input index .\n * @param[in] nElem - number of elements in the container\n * @return index that is within [0, nElem-1].\n */\nunsigned int bindIndexToRange(unsigned int idReq, unsigned int nElem);\n\n\n/*!\n * Extract the value of the specific layer at the\n * row and column requested. If row and column are out\n * of bounds they will be bound to range.\n * @param[in] layerMat - matrix of the layer from where\n *                       the data is extracted\n * @param[in] rowReq - row requested\n * @param[in] colReq - column requested\n * @return - value of the layer at rowReq and colReq\n */\ndouble getLayerValue(const Matrix &layerMat, int rowReq, int colReq);\n\nnamespace bicubic_conv {\n\n/*!\n * Matrix for cubic interpolation via convolution. Taken from:\n * https://en.wikipedia.org/wiki/Bicubic_interpolation\n */\nstatic const Eigen::Matrix4d cubicInterpolationConvolutionMatrix {\n    (Eigen::Matrix4d() << 0.0,  2.0,  0.0,  0.0,\n                         -1.0,  0.0,  1.0,  0.0,\n                          2.0, -5.0,  4.0, -1.0,\n                         -1.0,  3.0, -3.0,  1.0).finished() };\n\n/*\n * Index of the middle knot for bicubic inteprolation. This is\n * the function value with subscripts (0,0), i.e. f00 in\n * https://en.wikipedia.org/wiki/Bicubic_interpolation\n * In the grid map it corresponds to the grid map point closest to the\n * queried point (in terms of Euclidean distance). Queried point has\n * coordinates (x,y) for at which the interpolation is requested.\n * @param[in]  gridMap - grid map with the data\n * @param[in]  queriedPosition - position for which the interpolated data is requested\n * @param[out] index - indices of the middle knot for the interpolation\n * @return - true if success\n */\nbool getIndicesOfMiddleKnot(const GridMap &gridMap, const Position &queriedPosition, Index *index);\n\n/*\n * Coordinates used for interpolation need to be shifted and scaled,\n * since the original algorithm operates around the origin and with unit\n * resolution\n * @param[in]  gridMap - grid map with the data\n * @param[in]  queriedPosition - position for which the interpolation is requested\n * @param[out] position - normalized coordinates of the point for which the interpolation is requested\n * @return - true if success\n */\nbool getNormalizedCoordinates(const GridMap &gridMap, const Position &queriedPosition,\n                              Position *position);\n\n/*\n * Queries the grid map for function values at the coordiantes which are neccesary for\n * performing the interpolation. The right function values are then assembled\n * in a matrix.\n * @param[in]  gridMap - grid map with the data\n * @param[in]  layer - name of the layer that we are interpolating\n * @param[in]  queriedPosition - position for which the interpolation is requested\n * @param[out] data - 4x4 matrix with 16 function values used for interpolation, see\n *           R. Keys (1981). \"Cubic convolution interpolation for digital image processing\".\n *           IEEE Transactions on Acoustics, Speech, and Signal Processing. 29 (6): 1153\u20131160.\n *           for the details.\n * @return - true if success\n */\nbool assembleFunctionValueMatrix(const GridMap &gridMap, const std::string &layer,\n                                 const Position &queriedPosition, FunctionValueMatrix *data);\n\n/*\n * Performs convolution in 1D. the function requires 4 function values\n * to compute the convolution. The result is interpolated data in 1D.\n * @param[in]  t - normalized coordinate (x or y)\n * @param[in]  functionValues - vector of 4 function values neccessary to perform\n *                            interpolation in 1 dimension.\n * @return - interpolated value at normalized coordinate t\n */\ndouble convolve1D(double t, const Eigen::Vector4d &functionValues);\n\n/*\n * Performs convolution in 1D. the function requires 4 function values\n * to compute the convolution. The result is interpolated data in 1D.\n * @param[in]  gridMap - grid map with discrete function values\n * @param[in]  layer - name of the layer for which we want to perform interpolation\n * @param[in]  queriedPosition - position for which the interpolation is requested\n * @param[out] interpolatedValue - interpolated value at queried point\n * @return - true if success\n */\nbool evaluateBicubicConvolutionInterpolation(const GridMap &gridMap, const std::string &layer,\n                                             const Position &queriedPosition,\n                                             double *interpolatedValue);\n\n} /* namespace bicubic_conv */\n\nnamespace bicubic {\n\n/*\n * Enum for the derivatives direction\n * to perform interpolation one needs\n * derivatives w.r.t. to x and y dimension.\n */\nenum class Dim2D: int {\n    X,\n    Y\n};\n\n/*!\n * Matrix for cubic interpolation. Taken from:\n * https://en.wikipedia.org/wiki/Bicubic_interpolation\n */\nstatic const Eigen::Matrix4d bicubicInterpolationMatrix {\n    (Eigen::Matrix4d() << 1.0,  0.0,  0.0,  0.0,\n                          0.0,  0.0,  1.0,  0.0,\n                         -3.0,  3.0, -2.0, -1.0,\n                          2.0, -2.0,  1.0,  1.0).finished() };\n\n/*\n * Data matrix that can hold function values\n * these can be either function values at requested\n * positions or their derivatives.\n */\nstruct DataMatrix\n{\n  double topLeft_ = 0.0;\n  double topRight_ = 0.0;\n  double bottomLeft_ = 0.0;\n  double bottomRight_ = 0.0;\n};\n\n/*\n * Interpolation is performed on a unit square.\n * Hence we need to compute 4 corners of that unit square,\n * and find their indices in the grid map. IndicesMatrix\n * is a container that stores those indices. Each index\n * contains two numbers (row number, column number) in the\n * grid map.\n */\nstruct IndicesMatrix\n{\n  Index topLeft_ { 0, 0 };\n  Index topRight_ { 0, 0 };\n  Index bottomLeft_ { 0, 0 };\n  Index bottomRight_ { 0, 0 };\n};\n\n/*\n * Makes sure that all indices in side the\n * data structure IndicesMatrix are within the\n * range of the grid map.\n * @param[in] gridMap - input grid map with discrete function values\n * @param[in/out] indices - indices that are bound to range, i.e.\n *                          rows and columns are with ranges\n */\nvoid bindIndicesToRange(const GridMap &gridMap, IndicesMatrix *indices);\n\n/*\n * Performs bicubic interpolation at requested position.\n * @param[in]  gridMap - grid map with discrete function values\n * @param[in]  layer - name of the layer for which we want to perform interpolation\n * @param[in]  queriedPosition - position for which the interpolation is requested\n * @param[out] interpolatedValue - interpolated value at queried point\n * @return - true if success\n */\nbool evaluateBicubicInterpolation(const GridMap &gridMap, const std::string &layer,\n                                  const Position &queriedPosition, double *interpolatedValue);\n\n/*\n * Deduces which points in the grid map close a unit square around the\n * queried point and returns their indices (row and column number)\n * @param[in]  gridMap - grid map with discrete function values\n * @param[in]  queriedPosition - position for which the interpolation is requested\n * @param[out] indicesMatrix - data structure with indices forming a unit square\n *                            around the queried point\n * @return - true if success\n */\nbool getUnitSquareCornerIndices(const GridMap &gridMap, const Position &queriedPosition,\n                                IndicesMatrix *indicesMatrix);\n\n/*\n * Get index (row and column number) of a point in grid map, which\n * is closest to the queried position.\n * @param[in]  gridMap - grid map with discrete function values\n * @param[in]  queriedPosition - position for which the interpolation is requested\n * @param[out] index - indices of the closest point in grid_map\n * @return - true if success\n */\nbool getClosestPointIndices(const GridMap &gridMap, const Position &queriedPosition, Index *index);\n\n/*\n * Retrieve function values from the grid map at requested indices.\n * @param[in]  layerData - layer of a grid map with function values\n * @param[in]  indices - indices (row and column numbers) for which function values are requested\n * @param[out] data - requested function values\n * @return - true if success\n */\nbool getFunctionValues(const Matrix &layerData, const IndicesMatrix &indices, DataMatrix *data);\n\n/*\n * Retrieve function derivative values from the grid map at requested indices. Function\n * derivatives are approximated using central difference.\n * @param[in]  layerData - layer of a grid map with function values\n * @param[in]  indices - indices (row and column numbers) for which function derivative\n *                       values are requested\n * @param[in]  dim - dimension along which we want to evaluate partial derivatives (X or Y)\n * @param[in]  resolution - resolution of the grid map\n * @param[out] derivatives - values of derivatives at requested indices\n * @return - true if success\n */\nbool getFirstOrderDerivatives(const Matrix &layerData, const IndicesMatrix &indices, Dim2D dim,\n                              double resolution, DataMatrix *derivatives);\n\n/*\n * Retrieve second order function derivative values from the grid map at requested indices.\n * Function derivatives are approximated using central difference. We compute partial derivative\n * w.r.t to one coordinate and then the other. Note that the order of differentiation\n * does not matter.\n * @param[in]  layerData - layer of a grid map with function values\n * @param[in]  indices - indices (row and column numbers) for which function derivative\n *                       values are requested\n * @param[in]  resolution - resolution of the grid map\n * @param[out] derivatives - values of second order mixed derivatives at requested indices\n * @return - true if success\n */\nbool getMixedSecondOrderDerivatives(const Matrix &layerData, const IndicesMatrix &indices,\n                                    double resolution, DataMatrix *derivatives);\n\n/*\n * First order derivative for a specific point determined by index.\n * Approximated by central difference.\n * See https://www.mathematik.uni-dortmund.de/~kuzmin/cfdintro/lecture4.pdf\n * for details\n * @param[in]  layerData - layer of a grid map with function values\n * @param[in]  index - index (row and column number) for which function derivative\n *                       value is requested\n * @param[in]  dim - dimension along which we want to evaluate partial derivative (X or Y)\n * @param[in]  resolution - resolution of the grid map\n * @return - value of the derivative at requested index\n */\ndouble firstOrderDerivativeAt(const Matrix &layerData, const Index &index, Dim2D dim,\n                              double resolution);\n\n/*\n * Second order mixed derivative for a specific point determined by index.\n * See https://www.mathematik.uni-dortmund.de/~kuzmin/cfdintro/lecture4.pdf\n * for details\n * @param[in]  layerData - layer of a grid map with function values\n * @param[in]  index - index (row and column number) for which function derivative\n *                       value is requested\n * @param[in]  resolution - resolution of the grid map\n * @return - value of the second order mixed derivative at requested index\n */\ndouble mixedSecondOrderDerivativeAt(const Matrix &layerData, const Index &index, double resolution);\n\n/*\n * Evaluate polynomial at requested coordinates. the function will compute the polynomial\n * coefficients and then evaluate it. See\n * https://en.wikipedia.org/wiki/Bicubic_interpolation\n * for details.\n * @param[in]  functionValues - function values and derivatives required to\n *                              compute polynomial coefficients\n * @param[in]  tx - normalized x coordinate for which the interpolation should be computed\n * @param[in]  ty - normalized y coordinate for which the interpolation should be computed\n * @return - interpolated value at requested normalized coordinates.\n */\ndouble evaluatePolynomial(const FunctionValueMatrix &functionValues, double tx, double ty);\n\n/*\n * Assemble function value matrix from small submatrices containing function values\n * or derivative values at the corners of the unit square.\n * See https://en.wikipedia.org/wiki/Bicubic_interpolation for details.\n *\n * @param[in]  f - Function values at the corners of the unit square\n * @param[in]  dfx - Partial derivative w.r.t to x at the corners of the unit square\n * @param[in]  dfy - Partial derivative w.r.t to y at the corners of the unit square\n * @param[in]  ddfxy - Second order partial derivative w.r.t to x and y at the corners of the unit square\n * @param[out]  functionValues - function values and derivatives required to\n *                              compute polynomial coefficients\n */\nvoid assembleFunctionValueMatrix(const DataMatrix &f, const DataMatrix &dfx, const DataMatrix &dfy,\n                                 const DataMatrix &ddfxy, FunctionValueMatrix *functionValues);\n\n/*\n * Coordinates used for interpolation need to be shifter and scaled,\n * since the original algorithm operates on a unit square around the origin.\n * @param[in]  gridMap - grid map with the data\n * @param[in]  originIndex - index of a bottom left corner if the unit square in the grid map\n *                            this corner is the origin for the normalized coordinates.\n * @param[in]  queriedPosition - position for which the interpolation is requested\n * @param[out] position - normalized coordinates of the point for which the interpolation is requested\n * @return - true if success\n */\nbool computeNormalizedCoordinates(const GridMap &gridMap, const Index &originIndex,\n                                  const Position &queriedPosition, Position *normalizedCoordinates);\n\n} /* namespace bicubic */\n\n} /* namespace grid_map*/\n", "meta": {"hexsha": "3b50088746f21c9e0df7b84cc06ab4a10a2653fc", "size": 14833, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/include/grid_map_core/CubicInterpolation.hpp", "max_stars_repo_name": "ethz-asl/grid_map", "max_stars_repo_head_hexsha": "b7293f5d379719d2d0b9f1ce047d00f32601487a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 358.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T12:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-04T14:04:53.000Z", "max_issues_repo_path": "grid_map_core/include/grid_map_core/CubicInterpolation.hpp", "max_issues_repo_name": "ethz-asl/grid_map", "max_issues_repo_head_hexsha": "b7293f5d379719d2d0b9f1ce047d00f32601487a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T11:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-30T14:53:48.000Z", "max_forks_repo_path": "grid_map_core/include/grid_map_core/CubicInterpolation.hpp", "max_forks_repo_name": "ethz-asl/grid_map", "max_forks_repo_head_hexsha": "b7293f5d379719d2d0b9f1ce047d00f32601487a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 218.0, "max_forks_repo_forks_event_min_datetime": "2015-03-19T04:41:02.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-06T02:36:16.000Z", "avg_line_length": 42.8699421965, "max_line_length": 105, "alphanum_fraction": 0.7039034585, "num_tokens": 3433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6110590136604318}}
{"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_ATAN2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATAN2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the quadrant aware `atan2` function.\n\n\n\n    @par Header <boost/simd/function/atan2.hpp>\n\n    @par Notes\n\n    - For any real arguments @c x and @c y not both equal to zero, <tt>atan2(y, x)</tt>\n    (be aware of the parameter order) is the angle in radians between the positive\n    x-axis of a plane and the point  given by the coordinates  <tt>(x, y)</tt>.\n\n    - It is also the angle in \\f$[-\\pi,\\pi[\\f$ for which\n    \\f$x/\\sqrt{x^2+y^2}\\f$ and \\f$y/\\sqrt{x^2+y^2}\\f$\n    are respectively the sine and the cosine.\n\n    - Following IEEE norms,  we should have:\n     -  If y is \\f$\\pm0\\f$ and x is negative or -0,\\f$\\pm\\pi\\f$ is returned\n     -  If y is \\f$\\pm0\\f$ and x is positive or +0, \\f$\\pm0\\f$ is returned\n     -  If y is \\f$\\pm\\infty\\f$ and x is finite, \\f$\\pm\\pi/2\\f$ is returned\n     -  If y is \\f$\\pm\\infty\\f$ and x is \\f$-\\infty\\f$,\\f$\\pm3\\pi/4\\f$ is returned\n     -  If y is \\f$\\pm\\infty\\f$ and x is \\f$+\\infty\\f$, \\f$\\pm\\pi/4\\f$ is returned\n     -  If x is \\f$\\pm0\\f$ and y is negative, \\f$-\\pi/2\\f$ is returned\n     -  If x is \\f$\\pm0\\f$ and y is positive, \\f$+\\pi/2\\f$  is returned\n     -  If x is \\f$-\\infty\\f$ and y is finite and positive, \\f$+\\pi\\f$ is returned\n     -  If x is \\f$-\\infty\\f$ and y is finite and negative, \\f$-\\pi\\f$ is returned\n     -  If x is \\f$+\\infty\\f$ and y is finite and positive, +0 is returned\n     -  If x is \\f$+\\infty\\f$ and y is finite and negative, -0 is returned\n     -  If either x is Nan or y is Nan, Nan is returned\n\n     The pedantic_ decorator ensures all these conditions, but the regular version\n     (no decorator) will return a NaN if x and y are both either null or infinite,\n     result which in fact is not more absurd than the IEEE choices.\n     It will be conforming in all other cases.\n\n    @par Decorators\n\n    - std_  provides access to std::atan2\n\n    - pedantic_ ensures the respect of all IEEE limits\n\n    @see atan, atand, atanpi\n\n\n    @par Example:\n\n      @snippet atan2.cpp atan2\n\n    @par Possible output:\n\n      @snippet atan2.txt atan2\n\n  **/\n  IEEEValue atan2(IEEEValue const& y, IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/atan2.hpp>\n#include <boost/simd/function/simd/atan2.hpp>\n\n#endif\n", "meta": {"hexsha": "394f40b1022e6ceec2afc9abcb5dceb0ea98f452", "size": 2814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/atan2.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/atan2.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/atan2.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 34.7407407407, "max_line_length": 100, "alphanum_fraction": 0.6069651741, "num_tokens": 833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6110590088738251}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_PERSPECTIVETRANSFORM2D_HPP\n#define RW_MATH_PERSPECTIVETRANSFORM2D_HPP\n\n#if !defined(SWIG)\n#include \"Vector2D.hpp\"\n#include \"Vector3D.hpp\"\n\n#include <rw/common/Serializable.hpp>\n#include <rw/core/macros.hpp>\n\n#include <Eigen/Core>\n#endif\n\nnamespace rw { namespace math {\n\n    /**\n     * @brief The PerspectiveTransform2D is a perspective transform in 2D.\n     *\n     * The homographic transform can be used to map one arbitrary 2D\n     * quadrilateral into another.\n     */\n    template< class T = double > class PerspectiveTransform2D\n    {\n      private:\n        //! Eigen 3x3 matrix used as internal data structure.\n        typedef Eigen::Matrix< T, 3, 3 > EigenMatrix3x3;\n\n      public:\n        /**\n         * @brief constructor\n         */\n        PerspectiveTransform2D ()    //: _matrix(3,3)\n        {\n            _matrix (0, 0) = 1;\n            _matrix (0, 1) = 0;\n            _matrix (0, 2) = 0;\n            _matrix (1, 0) = 0;\n            _matrix (1, 1) = 1;\n            _matrix (1, 2) = 0;\n            _matrix (2, 0) = 0;\n            _matrix (2, 1) = 0;\n            _matrix (2, 2) = 1;\n        }\n\n        /**\n         * @brief constructor\n         */\n        PerspectiveTransform2D (T r11, T r12, T r13, T r21, T r22, T r23, T r31, T r32,\n                                T r33)    //: _matrix(3,3)\n        {\n            _matrix (0, 0) = r11;\n            _matrix (0, 1) = r12;\n            _matrix (0, 2) = r13;\n            _matrix (1, 0) = r21;\n            _matrix (1, 1) = r22;\n            _matrix (1, 2) = r23;\n            _matrix (2, 0) = r31;\n            _matrix (2, 1) = r32;\n            _matrix (2, 2) = r33;\n        }\n\n        /**\n         * @brief constructor\n         * @param r\n         * @return\n         */\n        template< class R > explicit PerspectiveTransform2D (const Eigen::Matrix< R, 3, 3 >& r)\n        //: _matrix(r)\n        {\n            for (size_t i = 0; i < 3; i++)\n                for (size_t j = 0; j < 3; j++)\n                    _matrix (i, j) = r (i, j);\n        }\n\n        /**\n         * @brief constructor\n         * @param r\n         * @return\n         */\n        template< class R > explicit PerspectiveTransform2D (const Eigen::MatrixBase< R >& r)\n        //: _matrix(r)\n        {\n            RW_ASSERT (r.rows () == 3);\n            RW_ASSERT (r.cols () == 3);\n            for (size_t i = 0; i < 3; i++)\n                for (size_t j = 0; j < 3; j++)\n                    _matrix (i, j) = r.row (i) (j);\n        }\n\n        /**\n         * @brief calculates a PerspectiveTransform2D that maps points from point\n         * set pts1 to point set pts2\n         * @param pts1 [in] point set one\n         * @param pts2 [in] point set two\n         */\n        static PerspectiveTransform2D< T >\n        calcTransform (std::vector< rw::math::Vector2D< T > > pts1,\n                       std::vector< rw::math::Vector2D< T > > pts2);\n\n        /**\n         * @brief Returns the inverse of the PerspectiveTransform\n         */\n        PerspectiveTransform2D< T > inverse () const\n        {\n            return PerspectiveTransform2D< T > (_matrix.transpose ());\n        }\n#if !defined(SWIG)\n        /**\n         * @brief Returns matrix element reference\n         * @param row [in] row, row must be @f$ < 3 @f$\n         * @param col [in] col, col must be @f$ < 3 @f$\n         * @return reference to matrix element\n         */\n        T& operator() (std::size_t row, std::size_t col)\n        {\n            assert (row < 3);\n            assert (col < 3);\n            return _matrix (row, col);\n        }\n\n        /**\n         * @brief Returns const matrix element reference\n         * @param row [in] row, row must be @f$ < 3 @f$\n         * @param col [in] col, col must be @f$ < 3 @f$\n         * @return const reference to matrix element\n         */\n        const T& operator() (std::size_t row, std::size_t col) const\n        {\n            assert (row < 3);\n            assert (col < 3);\n            return _matrix (row, col);\n        }\n#else\n        MATRIXOPERATOR (T);\n#endif\n\n        /**\n         * @brief transform a point using this perspective transform\n         */\n        rw::math::Vector2D< T > operator* (const rw::math::Vector2D< T >& v) const\n        {\n            const T x = v (0);\n            const T y = v (1);\n\n            const T g      = (*this) (2, 0);\n            const T h      = (*this) (2, 1);\n            const T one    = static_cast< T > (1);\n            const T lenInv = one / (g * x + h * y + one);\n\n            const T a = (*this) (0, 0);\n            const T b = (*this) (0, 1);\n            const T c = (*this) (0, 2);\n\n            const T d = (*this) (1, 0);\n            const T e = (*this) (1, 1);\n            const T f = (*this) (1, 2);\n\n            return rw::math::Vector2D< T > ((a * x + b * y + c) * lenInv,\n                                            (d * x + e * y + f) * lenInv);\n        }\n\n        /**\n         * @brief transform a 2d point into a 3d point with this\n         * perspective transform\n         * @param hT\n         * @param v\n         * @return\n         */\n        rw::math::Vector3D< T > calc3dVec (const PerspectiveTransform2D< T >& hT,\n                                           const rw::math::Vector2D< T >& v)\n        {\n            const T x = v (0);\n            const T y = v (1);\n\n            const T g   = hT (2, 0);\n            const T h   = hT (2, 1);\n            const T one = static_cast< T > (1);\n            // const T lenInv = one / (g * x + h * y + one);\n            const T len = (g * x + h * y + one);\n\n            const T a = hT (0, 0);\n            const T b = hT (0, 1);\n            const T c = hT (0, 2);\n\n            const T d = hT (1, 0);\n            const T e = hT (1, 1);\n            const T f = hT (1, 2);\n\n            return rw::math::Vector3D< T > ((a * x + b * y + c), (d * x + e * y + f), len);\n        }\n\n        /**\n         * @brief Returns reference to the 3x3 matrix @f$ \\mathbf{M}\\in SO(3)\n         * @f$ that represents this rotation\n         *\n         * @return @f$ \\mathbf{M}\\in SO(3) @f$\n         */\n        const Eigen::Matrix< T, 3, 3 >& e () const { return _matrix; }\n\n        /**\n         * @brief Returns reference to the 3x3 matrix @f$ \\mathbf{M}\\in SO(3)\n         * @f$ that represents this rotation\n         *\n         * @return @f$ \\mathbf{M}\\in SO(3) @f$\n         */\n        Eigen::Matrix< T, 3, 3 >& e () { return _matrix; }\n\n      private:\n        EigenMatrix3x3 _matrix;\n    };\n\n    /**\n     * @brief Take the inverse of a PerspectiveTransform2D.\n     * @param aRb [in] a PerspectiveTransform2D.\n     * @return the inverse of \\b aRb .\n     * @relates rw::math::PerspectiveTransform2D\n     */\n    template< class T > PerspectiveTransform2D< T > inverse (const PerspectiveTransform2D< T >& aRb)\n    {\n        return aRb.inverse ();\n        // return PerspectiveTransform2D<T>(trans(aRb.m()));\n    }\n#if !defined(SWIG)\n    extern template class rw::math::PerspectiveTransform2D< double >;\n    extern template class rw::math::PerspectiveTransform2D< float >;\n#else\n    SWIG_DECLARE_TEMPLATE (PerspectiveTransform2Dd, rw::math::PerspectiveTransform2D< double >);\n    SWIG_DECLARE_TEMPLATE (PerspectiveTransform2Df, rw::math::PerspectiveTransform2D< float >);\n#endif\n\n    using PerspectiveTransform2Dd = PerspectiveTransform2D< double >;\n    using PerspectiveTransform2Df = PerspectiveTransform2D< float >;\n\n}}    // namespace rw::math\n\nnamespace rw { namespace common {\n    class OutputArchive;\n    class InputArchive;\n    namespace serialization {\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::PerspectiveTransform2D\n         */\n        template<>\n        void write (const rw::math::PerspectiveTransform2D< double >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::PerspectiveTransform2D\n         */\n        template<>\n        void write (const rw::math::PerspectiveTransform2D< float >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::PerspectiveTransform2D\n         */\n        template<>\n        void read (rw::math::PerspectiveTransform2D< double >& sobject,\n                   rw::common::InputArchive& iarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::PerspectiveTransform2D\n         */\n        template<>\n        void read (rw::math::PerspectiveTransform2D< float >& sobject,\n                   rw::common::InputArchive& iarchive, const std::string& id);\n    }    // namespace serialization\n}}       // namespace rw::common\n\n#endif    // end include guard\n", "meta": {"hexsha": "e81e311b91e3b8f2346c2a2f3627942f566779c6", "size": 9691, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/PerspectiveTransform2D.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/PerspectiveTransform2D.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/PerspectiveTransform2D.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1883561644, "max_line_length": 100, "alphanum_fraction": 0.5059333402, "num_tokens": 2633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387956435734, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6110589899550366}}
{"text": "/*\n * Copyright 2017 Maeve Automation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\n#include <cmath>\n#include <tuple>\n\n#include \"open_maeve/maeve_geometry/tau.h\"\n\nnamespace open_maeve {\nnamespace {\nconstexpr auto EPS = 1e-4;\nconstexpr auto INF = std::numeric_limits<double>::infinity();\n\n//------------------------------------------------------------------------------\n\ndouble extent(const double Z, const Eigen::Vector2d& p1,\n              const Eigen::Vector2d& p2) {\n  const auto d = (p1 - p2).norm();\n  return d / Z;\n}\n\n//------------------------------------------------------------------------------\n\n}  // namespace\n\n//------------------------------------------------------------------------------\n\nTEST(Tau, tau1) {\n  {\n    const auto range = 0.0;\n    const auto relative_speed = 0.0;\n    const auto expected_tau = 0.0;\n    const auto computed_tau = tau(range, relative_speed, EPS);\n    EXPECT_EQ(computed_tau, expected_tau);\n  }\n\n  {\n    const auto range = 1.0;\n    const auto relative_speed = 1.0;\n    const auto expected_tau = 1.0;\n    const auto computed_tau = tau(range, relative_speed, EPS);\n    EXPECT_EQ(computed_tau, expected_tau);\n  }\n\n  {\n    const auto range = 1.0;\n    const auto relative_speed = -1.0;\n    const auto expected_tau = -1.0;\n    const auto computed_tau = tau(range, relative_speed, EPS);\n    EXPECT_EQ(computed_tau, expected_tau);\n  }\n\n  {\n    const auto range = 1.0;\n    const auto relative_speed = 0.0;\n    const auto expected_tau = INF;\n    const auto computed_tau = tau(range, relative_speed, EPS);\n    EXPECT_EQ(computed_tau, expected_tau);\n  }\n\n  {\n    const auto range = 1.0;\n    const auto relative_speed = (0.5 * EPS);\n    const auto expected_tau = INF;\n    const auto computed_tau = tau(range, relative_speed, EPS);\n    EXPECT_EQ(computed_tau, expected_tau);\n  }\n\n  {\n    const auto range = 1.0;\n    const auto relative_speed = (2.0 * EPS);\n    const auto computed_tau = tau(range, relative_speed, EPS);\n    EXPECT_TRUE(std::isfinite(computed_tau));\n  }\n}\n\n//------------------------------------------------------------------------------\n\nTEST(Tau, verifyScaling) {\n  const auto Z = 17.0;\n  const auto Z_dot = -1.2;\n  const Eigen::Vector2d P1(2.3, 3.13);\n  const Eigen::Vector2d P2(5.67, -1.32);\n\n  auto t_delta = 10.37;\n  auto tau = -(Z + Z_dot * t_delta) / Z_dot;\n  const auto e1 = extent(Z, P1, P2);\n  const auto e2 = extent(Z + Z_dot * t_delta, P1, P2);\n  const auto e_dot = (e2 - e1) / t_delta;\n  const auto tau_estimated = tauFromDiscreteScaleDt(e2, e_dot, t_delta, EPS);\n  EXPECT_NEAR(tau_estimated, tau, 0.0001)\n      << \"e1: \" << e1 << \", e2: \" << e2 << \", e_dot: \" << e_dot;\n}\n\n//------------------------------------------------------------------------------\n\n}  // namespace open_maeve\n", "meta": {"hexsha": "5b1182ffe2460f025c1cc337dff9e310e091bcd0", "size": 3823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "maeve_geometry/test/test_tau.cpp", "max_stars_repo_name": "togaen/open_maeve", "max_stars_repo_head_hexsha": "5a5916a8519f4184f5b73c74e5a229df45a02af5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "maeve_geometry/test/test_tau.cpp", "max_issues_repo_name": "togaen/open_maeve", "max_issues_repo_head_hexsha": "5a5916a8519f4184f5b73c74e5a229df45a02af5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maeve_geometry/test/test_tau.cpp", "max_forks_repo_name": "togaen/open_maeve", "max_forks_repo_head_hexsha": "5a5916a8519f4184f5b73c74e5a229df45a02af5", "max_forks_repo_licenses": ["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.8583333333, "max_line_length": 80, "alphanum_fraction": 0.6136541983, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6110246717845356}}
{"text": "#include \"Math.h\"\r\n#include \"../utils/GapsAssert.h\"\r\n\r\n#include <boost/math/distributions/exponential.hpp>\r\n#include <boost/math/distributions/gamma.hpp>\r\n#include <boost/math/distributions/normal.hpp>\r\n\r\n#define GAPS_SQ(x) ((x) * (x))\r\n\r\n#define Q_GAMMA_THRESHOLD 0.000001f\r\n#define Q_GAMMA_MIN_VALUE 0.f\r\n\r\nfloat gaps::min(float a, float b)\r\n{\r\n    return a < b ? a : b;\r\n}\r\n\r\nunsigned gaps::min(unsigned a, unsigned b)\r\n{\r\n    return a < b ? a : b;\r\n}\r\n\r\nuint64_t gaps::min(uint64_t a, uint64_t b)\r\n{\r\n    return a < b ? a : b;\r\n}\r\n\r\nfloat gaps::max(float a, float b)\r\n{\r\n    return a < b ? b : a;\r\n}\r\n\r\nunsigned gaps::max(unsigned a, unsigned b)\r\n{\r\n    return a < b ? b : a;\r\n}\r\n\r\nuint64_t gaps::max(uint64_t a, uint64_t b)\r\n{\r\n    return a < b ? b : a;\r\n}\r\n\r\nfloat gaps::d_gamma(float d, float shape, float scale)\r\n{\r\n    boost::math::gamma_distribution<> gam(shape, scale);\r\n    return pdf(gam, d);\r\n}\r\n\r\nfloat gaps::p_gamma(float p, float shape, float scale)\r\n{\r\n    boost::math::gamma_distribution<> gam(shape, scale);\r\n    return cdf(gam, p);\r\n}\r\n\r\nfloat gaps::q_gamma(float q, float shape, float scale)\r\n{\r\n    if (q < Q_GAMMA_THRESHOLD)\r\n    {\r\n        return Q_GAMMA_MIN_VALUE;\r\n    }\r\n    boost::math::gamma_distribution<> gam(shape, scale);\r\n    return quantile(gam, q);\r\n}\r\n\r\nfloat gaps::d_norm(float d, float mean, float sd)\r\n{\r\n    boost::math::normal_distribution<> norm(mean, sd);\r\n    return pdf(norm, d);\r\n}\r\n\r\nfloat gaps::q_norm(float q, float mean, float sd)\r\n{\r\n    boost::math::normal_distribution<> norm(mean, sd);\r\n    return quantile(norm, q);\r\n}\r\n\r\nfloat gaps::p_norm(float p, float mean, float sd)\r\n{\r\n    boost::math::normal_distribution<> norm(mean, sd);\r\n    return cdf(norm, p);\r\n}\r\n\r\ndouble gaps::lgamma(double x)\r\n{\r\n    return boost::math::lgamma(x); // NOLINT\r\n}\r\n", "meta": {"hexsha": "6a204492f0c0742853426a24c25cd2d4505fad1e", "size": 1803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/math/Math.cpp", "max_stars_repo_name": "FertigLab/CoGAPS", "max_stars_repo_head_hexsha": "206bac9630b0cf234b4367d041597af98ca92a13", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2017-01-24T14:48:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T22:11:43.000Z", "max_issues_repo_path": "src/math/Math.cpp", "max_issues_repo_name": "FertigLab/CoGAPS", "max_issues_repo_head_hexsha": "206bac9630b0cf234b4367d041597af98ca92a13", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:09:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T01:35:29.000Z", "max_forks_repo_path": "src/math/Math.cpp", "max_forks_repo_name": "FertigLab/CoGAPS", "max_forks_repo_head_hexsha": "206bac9630b0cf234b4367d041597af98ca92a13", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-10-19T12:19:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-18T15:50:39.000Z", "avg_line_length": 20.724137931, "max_line_length": 57, "alphanum_fraction": 0.6217415419, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6110246552349109}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[point_order\n//` Examine the expected point order of a polygon type\n\n#include <iostream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n\nint main()\n{\n    typedef boost::geometry::model::d2::point_xy<double> point_type;\n    typedef boost::geometry::model::polygon<point_type, false> polygon_type;\n\n    boost::geometry::order_selector order = boost::geometry::point_order<polygon_type>::value;\n    \n    std::cout << \"order: \" << order << std::endl\n        << \"(clockwise = \" << boost::geometry::clockwise\n        << \", counterclockwise = \" << boost::geometry::counterclockwise\n        << \") \"<< std::endl;\n\n    return 0;\n}\n\n//]\n\n\n//[point_order_output\n/*`\nOutput:\n[pre\norder: 2\n(clockwise = 1, counterclockwise = 2)\n]\n*/\n//]\n", "meta": {"hexsha": "ff09223540b6ed90a50c1b7dad9531724d55bac4", "size": 1139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/core/point_order.cpp", "max_stars_repo_name": "olegshnitko/libboost", "max_stars_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T00:40:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T00:40:22.000Z", "max_issues_repo_path": "libs/geometry/doc/src/examples/core/point_order.cpp", "max_issues_repo_name": "olegshnitko/libboost", "max_issues_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/geometry/doc/src/examples/core/point_order.cpp", "max_forks_repo_name": "olegshnitko/libboost", "max_forks_repo_head_hexsha": "548eb6365af3724d8f4b47ebbabf7eb3ad8e66a8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7608695652, "max_line_length": 94, "alphanum_fraction": 0.6900790167, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.610934679579509}}
{"text": "#define BOOST_TEST_MODULE \"test_LUDecomposition\"\n\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost/test/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include \"test_Defs.hpp\"\nusing ax::test::tolerance;\nusing ax::test::seed;\n\n#include <random>\n\n#include \"../src/LUDecomposition.hpp\"\n\nBOOST_AUTO_TEST_CASE(LUDecomposition)\n{\n    ax::Matrix<double, 4,4> mat;\n\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> randreal(0e0, 1e0);\n\n    std::array<std::array<double, 4>, 4> rand1;\n    for(std::size_t i=0; i<4; ++i)\n        for(std::size_t j=0; j<4; ++j)\n            mat(i,j) = rand1[i][j] = randreal(mt);\n\n    const auto LUpair = ax::LUdecompose<ax::Doolittle>(mat);\n\n    const ax::Matrix<double, 4,4> L = LUpair.first;\n    const ax::Matrix<double, 4,4> U = LUpair.second;\n    const ax::Matrix<double, 4,4> A = L * U;\n\n    // ============= test for L ============= \n    for(std::size_t i = 0; i<4; ++i)\n        BOOST_CHECK_EQUAL(L(i,i), 1e0);\n\n    for(std::size_t i = 0; i<4; ++i)\n        for(std::size_t j = i+1; j<4; ++j)\n        {\n            BOOST_CHECK_EQUAL(L(i,j), 0e0);\n        }\n\n    // ============= test for U ============= \n    for(std::size_t i = 0; i<4; ++i)\n        for(std::size_t j = 0; j<i; ++j)\n        {\n            BOOST_CHECK_EQUAL(U(i,j), 0e0);\n        }\n\n    for(std::size_t i=0; i<4; ++i)\n        for(std::size_t j=0; j<4; ++j)\n            BOOST_CHECK_CLOSE(A(i,j), mat(i,j), tolerance);\n}\n", "meta": {"hexsha": "9042a57f85edf276bdfa674f563888299968b68c", "size": 1492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_LUDecomposition.cpp", "max_stars_repo_name": "ToruNiina/AX", "max_stars_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-16T13:56:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-16T13:56:31.000Z", "max_issues_repo_path": "test/test_LUDecomposition.cpp", "max_issues_repo_name": "ToruNiina/AX", "max_issues_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_LUDecomposition.cpp", "max_forks_repo_name": "ToruNiina/AX", "max_forks_repo_head_hexsha": "c99ddaa683dc94c7ec856a7cf1e10c0a6189951a", "max_forks_repo_licenses": ["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.1754385965, "max_line_length": 62, "alphanum_fraction": 0.5670241287, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6109346696027347}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <limits>\n#include <stdexcept>\n#include <cmath>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n\nTEST(MathFunctions, cbrt) {\n  using stan::math::cbrt;\n  EXPECT_FLOAT_EQ(-2.0, cbrt(-8.0));\n  EXPECT_FLOAT_EQ(-1.392476650083834, cbrt(-2.7));\n  EXPECT_FLOAT_EQ(0, cbrt(0));\n  EXPECT_FLOAT_EQ(2.0, cbrt(8.0));\n\n}\n\nTEST(MathFunctions, cbrt_inf_return) {\n  EXPECT_EQ(-std::numeric_limits<double>::infinity(),\n            stan::math::cbrt(-std::numeric_limits<double>::infinity()));\n  EXPECT_EQ(std::numeric_limits<double>::infinity(),\n            stan::math::cbrt(std::numeric_limits<double>::infinity()));\n}\n\nTEST(MathFunctions, cbrt_nan) {\n  using stan::math::cbrt;\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::cbrt(std::numeric_limits<double>::quiet_NaN()));\n}\n", "meta": {"hexsha": "f16e81c434e8fd08127ef7ef272f9b588a4f8d91", "size": 857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/cbrt_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/cbrt_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/cbrt_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5517241379, "max_line_length": 75, "alphanum_fraction": 0.6872812135, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173777511623, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6109346537196005}}
{"text": "//\n// Created by Yohsuke Murase on 2020/06/04.\n//\n\n#include <iostream>\n#include <vector>\n#include <array>\n#include <map>\n#include <random>\n#include <cassert>\n#include <fstream>\n#include <Eigen/Dense>\n#include \"StrategyN2M3.hpp\"\n\n// memory-1 species in strategy space discretized with `D`\n// memory-1 strategy is characterized by tuple (p_{cc}, p_{cd}, p_{dc}, p_{dd}),\n// where each of which denotes cooperation probability conditioned by the last Alice's action and the other players' defectors.\n// Each of which can take discrete values [0,1/D,2/D,...,D/D].\n// ID of a species is given by an integer with base-(D+1).\n// ID can take values [0, (D+1)^4-1]\n// ID=0 : AllD, ID=ID_MAX-1 : AllC\nclass Cprobs {\n public:\n  Cprobs(size_t id, size_t DIS) {\n    double dinv = 1.0 / DIS;\n    const size_t B = DIS+1;\n    cc = (id % B) * dinv;\n    cd = ((id/B) % B) * dinv; // A: c, B: d\n    dc = ((id/B/B) % B) * dinv; // A: d, B: c\n    dd = ((id/B/B/B) % B) * dinv;\n  }\n  double cc, cd, dc, dd;\n};\n\nclass Mem1Species {\n public:\n  static size_t N_M1_Species(size_t DIS) { return (DIS+1)*(DIS+1)*(DIS+1)*(DIS+1); }\n  Mem1Species(size_t _id, size_t _DIS) : id(_id), DIS(_DIS), prob(_id, _DIS) {\n    assert(id <= N_M1_Species(DIS));\n  }\n  size_t id;\n  size_t DIS;\n  Cprobs prob;\n\n  std::string ToString() const {\n    const size_t B = DIS+1;\n    size_t cc = (id % B);\n    size_t cd = ((id/B) % B);\n    size_t dc = ((id/B/B) % B);\n    size_t dd = ((id/B/B/B) % B);\n    std::ostringstream oss;\n    oss << cc << '-' << cd << '-' << dc << '-' << dd << '/' << DIS;\n    if (IsDefensible()) { oss << \"_D\"; }\n    if (IsEfficient()) { oss << \"_E\"; }\n    return oss.str();\n  }\n\n  std::vector<double> StationaryState(const Mem1Species& Bstr, double error = 0.0) const {\n    Eigen::Matrix<double,4,4> A;\n\n    // state 0: cc, state 1: cd (lower bit is A's history), ... 3: dd\n    // calculate transition probability from j to i\n\n    for (size_t j = 0; j < 4; j++) {\n      Action last_a = (j & 1ul) ? D : C;\n      Action last_b = ((j>>1ul) & 1ul) ? D : C;\n\n      auto cooperation_prob = [](Action a, Action b, const Mem1Species& str) -> double {\n        if (a == C) {\n          if (b == C) { return str.prob.cc; }\n          else { return str.prob.cd; }\n        }\n        else {\n          if (b == C) { return str.prob.dc; }\n          else { return str.prob.dd; }\n        }\n      };\n      double c_A = cooperation_prob(last_a, last_b, *this);\n      double c_B = cooperation_prob(last_b, last_a, Bstr);\n\n      c_A = (1.0 - error) * c_A + error * (1.0 - c_A);\n      c_B = (1.0 - error) * c_B + error * (1.0 - c_B);\n      A(0,j) = c_A * c_B;\n      A(1,j) = (1.0-c_A) * c_B;\n      A(2,j) = c_A * (1.0-c_B);\n      A(3,j) = (1.0-c_A) * (1.0-c_B);\n    }\n\n    for(int i=0; i<4; i++) {\n      A(i,i) -= 1.0;\n    }\n    for(int i=0; i<4; i++) {\n      A(4-1,i) += 1.0;  // normalization condition\n    }\n    Eigen::VectorXd b(4);\n    for(int i=0; i<4; i++) { b(i) = 0.0;}\n    b(4-1) = 1.0;\n    Eigen::VectorXd x = A.colPivHouseholderQr().solve(b);\n    std::vector<double> ans(4, 0.0);\n    for(int i=0; i<ans.size(); i++) {\n      ans[i] = x(i);\n    }\n\n    return ans;\n  }\n\n  double CooperationProb(StateN2M3 s) const {\n    if (s.a_1 == C) {\n      if (s.b_1 == C) { return prob.cc; }\n      else { return prob.cd; }\n    }\n    else {\n      if (s.b_1 == C) { return prob.dc; }\n      else { return prob.dd; }\n    }\n  }\n\n  // returns false for mixed strategy\n  bool IsDefensible() const {\n    double tolerance = 1.0e-8;\n    if (prob.cc > tolerance && prob.cc < 1.0 - tolerance) { return false; }\n    if (prob.cd > tolerance && prob.cd < 1.0 - tolerance) { return false; }\n    if (prob.dc > tolerance && prob.dc < 1.0 - tolerance) { return false; }\n    if (prob.dd > tolerance && prob.dd < 1.0 - tolerance) { return false; }\n\n    // N = 2^{2}\n    const size_t N = 4;\n    typedef std::array<std::array<int, N>, N> d_matrix_t;\n    d_matrix_t d;\n\n    // construct adjacency matrix\n    const int INF = N; // N is large enough since the path length is between -N/4 to N/4.\n    for (size_t i = 0; i < N; i++) {\n      for (size_t j = 0; j < N; j++) {\n        d[i][j] = INF;\n      }\n    }\n\n    for (size_t i = 0; i < N; i++) {\n      Action a0 = (i & 1) ? D : C; // current state\n      Action b0 = (i & 2) ? D : C;\n      Action act_a = C;\n      if (a0 == C) {\n        if (b0 == C) { act_a = (prob.cc > 0.5 ? C : D); }\n        else { act_a = (prob.cd > 0.5 ? C : D); }\n      }\n      else {\n        if (b0 == C) { act_a = (prob.dc > 0.5 ? C : D); }\n        else { act_a = (prob.dd > 0.5 ? C : D); }\n      }\n\n      // Get possible next states\n      std::array<Action, 2> act_bs = {C, D};\n      for (auto act_b: act_bs) {\n        size_t j = 0;\n        if (act_a == D) { j += 1; }\n        if (act_b == D) { j += 2; }\n        if (j == 0 || j == 3) d[i][j] = 0;\n        else if (j == 1) d[i][j] = 1;\n        else if (j == 2) d[i][j] = -1;\n      }\n      if (d[i][i] < 0) { return false; }\n    }\n\n    for (size_t k = 0; k < N; k++) {\n      for (size_t i = 0; i < N; i++) {\n        for (size_t j = 0; j < N; j++) {\n          d[i][j] = std::min(d[i][j], d[i][k] + d[k][j]);\n        }\n        if (d[i][i] < 0) { return false; }\n      }\n    }\n    return true;\n  }\n\n  bool IsEfficient() const {\n    auto ss = StationaryState(*this, 0.0001);\n    return (ss[0] > 0.99);\n  }\n};\n\n\nclass Species { // either Mem1Species or StrategyN3M5\n public:\n  Species(size_t ID, size_t DIS) : m1(Mem1Species(0, DIS)), m5(0ull){\n    const size_t N_M1 = Mem1Species::N_M1_Species(DIS);\n    if (ID < N_M1) {\n      is_m1 = true;\n      m1 = Mem1Species(ID, DIS);\n      m5 = StrategyN2M3(0ull);\n      name = m1.ToString();\n    }\n    else if (ID == N_M1) {\n      is_m1 = false;\n      m1 = Mem1Species(0, DIS);\n      m5 = StrategyN2M3::CAPRI2();\n      name = \"CAPRI2\";\n    }\n    else if (ID == N_M1 + 1) {\n      is_m1 = false;\n      m1 = Mem1Species(0, DIS);\n      m5 = StrategyN2M3::CAPRI();\n      name = \"CAPRI\";\n    }\n    else if (ID == N_M1 + 2) {\n      is_m1 = false;\n      m1 = Mem1Species(0, DIS);\n      m5 = StrategyN2M3::TFT_ATFT();\n      name = \"TFT_ATFT\";\n    }\n    else if (ID == N_M1 + 3) {\n      is_m1 = false;\n      m1 = Mem1Species(0, DIS);\n      m5 = StrategyN2M3::AON(2);\n      name = \"AON2\";\n    }\n    else if (ID == N_M1 + 4) {\n      is_m1 = false;\n      m1 = Mem1Species(0, DIS);\n      m5 = StrategyN2M3::AON(3);\n      name = \"AON3\";\n    }\n    else {\n      throw std::runtime_error(\"must not happen\");\n    }\n  };\n  bool is_m1;\n  Mem1Species m1;\n  StrategyN2M3 m5;\n  std::string name;\n  std::string ToString() const { return name; }\n  std::vector<double> StationaryState(const Species &sb, double error) const {\n    if (is_m1 && sb.is_m1) {\n      return m1.StationaryState(sb.m1, error);\n    }\n    std::cerr << \"calculating stationary state: \" << name << ' ' << sb.name << std::endl;\n\n    typedef Eigen::Triplet<double> T;\n    std::vector<T> tripletVec;\n\n    for (size_t j = 0; j < 64; j++) {\n      // calculate transition probability from j to i\n      const StateN2M3 sj(j);\n      double c_a = _CooperationProb(sj);\n      double c_b = sb._CooperationProb(sj.SwapAB());\n      // cooperation probability taking noise into account\n      c_a = (1.0 - error) * c_a + error * (1.0 - c_a);\n      c_b = (1.0 - error) * c_b + error * (1.0 - c_b);\n\n      for (size_t t = 0; t < 4; t++) {\n        Action act_a = (t & 1ul) ? D : C;\n        Action act_b = (t & 2ul) ? D : C;\n        size_t i = sj.NextState(act_a, act_b).ID();\n        double p_a = (act_a == C) ? c_a : (1.0-c_a);\n        double p_b = (act_b == C) ? c_b : (1.0-c_b);\n        tripletVec.emplace_back(i, j, p_a * p_b);\n      }\n    }\n\n    const size_t S = 64;\n    Eigen::SparseMatrix<double> A(S, S);\n    A.setFromTriplets(tripletVec.cbegin(), tripletVec.cend());\n\n    // subtract unit matrix & normalization condition\n    std::vector<T> iVec;\n    for (int i = 0; i < S-1; i++) { iVec.emplace_back(i, i, -1.0); }\n    for (int i = 0; i < S-1; i++) { iVec.emplace_back(S-1, i, 1.0); }\n    Eigen::SparseMatrix<double> I(S, S);\n    I.setFromTriplets(iVec.cbegin(), iVec.cend());\n    A = A + I;\n    // std::cerr << \"  transition matrix has been created\" << std::endl;\n\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(S);\n    b(S-1) = 1.0;\n\n    Eigen::BiCGSTAB<Eigen::SparseMatrix<double>, Eigen::IncompleteLUT<double> > solver;\n    solver.compute(A);\n    Eigen::VectorXd x = solver.solve(b);\n\n    // std::cerr << \"#iterations:     \" << solver.iterations() << std::endl;\n    // std::cerr << \"estimated error: \" << solver.error() << std::endl;\n\n    std::vector<double> ans(S, 0.0);\n    for (int i = 0; i < S; i++) { ans[i] = x[i]; }\n    return ans;\n  }\n private:\n  double _CooperationProb(const StateN2M3 &s) const {\n    if (is_m1) { return m1.CooperationProb(s); }\n    else { return m5.ActionAt(s) == C ? 1.0 : 0.0; }\n  }\n\n public:\n  static std::vector<Species> Memory1Species(size_t discrete_level) {\n    std::vector<Species> ans;\n    size_t n = Mem1Species::N_M1_Species(discrete_level);\n    for (size_t i = 0; i < n; i++) {\n      ans.emplace_back(i, discrete_level);\n    }\n    return std::move(ans);\n  }\n  static std::vector<Species> ReactiveMem1Species(size_t discrete_level) {\n    std::vector<Species> ans;\n    size_t B = discrete_level + 1;\n    size_t n = Mem1Species::N_M1_Species(discrete_level);\n    size_t B2 = B * B;\n    for (size_t i = 0; i < n/B2; i++) {\n      size_t id = i * B2 + i;\n      ans.emplace_back(id, discrete_level);\n    }\n    return std::move(ans);\n  }\n};\n\n\nclass Ecosystem {\n public:\n  Ecosystem(const std::vector<Species> &species_pool, double error) :pool(species_pool), N_SPECIES(species_pool.size()), e(error) {\n    CalculateSSCache();\n  };\n  size_t N_SPECIES;\n  std::vector<Species> pool;\n  const double e;\n  typedef std::vector<double> ss_cache_t;\n  std::vector<std::vector<ss_cache_t> > ss_cache;\n  // ss_cache[i][i] stores the stationary state when PG game is played by (i,i)\n  // ss_cache[i][j] stores the stationary state when PG game is played by (i,j)\n\n  void CalculateSSCache() {\n    ss_cache.resize(N_SPECIES);\n    for (size_t i = 0; i < N_SPECIES; i++) {\n      ss_cache[i].resize(N_SPECIES);\n    }\n\n#pragma omp parallel for schedule(dynamic,1)\n    for (size_t I=0; I < N_SPECIES * N_SPECIES; I++) {\n      size_t i = I / N_SPECIES;\n      size_t j = I % N_SPECIES;\n      ss_cache[i][j] = pool[i].StationaryState(pool[j], e);\n    }\n  }\n\n  // payoff of species i and j when the game is played by (i,j)\n  std::array<double,2> PayoffVersus(size_t i, size_t j, double benefit, double cost) const {\n    return Payoffs(ss_cache[i][j], benefit, cost);\n  }\n\n  std::array<double,2> Payoffs(const ss_cache_t &ss, double benefit, double cost) const {\n    std::array<double, 2> ans = {0.0, 0.0};\n    if (ss.size() == 4) {\n      for (size_t i = 0; i < 4; i++) {\n        double pa = 0.0, pb = 0.0;\n        if ((i & 1ul) == 0) {\n          pa -= cost;\n          pb += benefit;\n        }\n        if ((i & 2ul) == 0) {\n          pb -= cost;\n          pa += benefit;\n        }\n        ans[0] += ss[i] * pa;\n        ans[1] += ss[i] * pb;\n      }\n    }\n    else {\n      assert(ss.size() == 64);\n      for (size_t i = 0; i < 64; i++) {\n        StateN2M3 s(i);\n        double pa = 0.0, pb = 0.0;\n        if (s.a_1 == C) {\n          pa -= cost;\n          pb += benefit;\n        }\n        if (s.b_1 == C) {\n          pb -= cost;\n          pa += benefit;\n        }\n        ans[0] += ss[i] * pa;\n        ans[1] += ss[i] * pb;\n      }\n    }\n    return ans;\n  }\n\n  // calculate the equilibrium distribution exactly by linear algebra\n  std::vector<double> CalculateEquilibrium(double benefit, double cost, uint64_t N, double sigma) const {\n    Eigen::MatrixXd A(N_SPECIES, N_SPECIES);\n    #pragma omp parallel for\n    for (size_t ii = 0; ii < N_SPECIES * N_SPECIES; ii++) {\n      size_t i = ii / N_SPECIES;\n      size_t j = ii % N_SPECIES;\n      if (i == j) { A(i, j) = 0.0; continue; }\n      double p = FixationProb(benefit, cost, N, sigma, i, j);\n      // std::cerr << \"Fixation prob of mutant (mutant,resident): \" << p << \" (\" << pool[i].ToString() << \", \" << pool[j].ToString() << \")\" << std::endl;\n      A(i, j) = p * (1.0 / N_SPECIES);\n    }\n\n    for (size_t j = 0; j < N_SPECIES; j++) {\n      double p_sum = 0.0;\n      for (size_t i = 0; i < N_SPECIES; i++) {\n        p_sum += A(i, j);\n      }\n      assert(p_sum <= 1.0);\n      A(j, j) = 1.0 - p_sum; // probability that the state doesn't change\n    }\n\n    size_t n_row = A.rows();\n\n    // subtract Ax = x => (A-I)x = 0\n    for (size_t i = 0; i < A.rows(); i++) {\n      A(i, i) -= 1.0;\n    }\n    // normalization condition\n    for (size_t i = 0; i < A.rows(); i++) {\n      A(A.rows()-1, i) += 1.0;\n    }\n\n    Eigen::VectorXd b(A.rows());\n    for(int i=0; i<A.rows()-1; i++) { b(i) = 0.0;}\n    b(A.rows()-1) = 1.0;\n    Eigen::VectorXd x = A.householderQr().solve(b);\n    std::vector<double> ans(A.rows());\n    double prob_total = 0.0;\n    for(int i=0; i<ans.size(); i++) {\n      ans[i] = x(i);\n      prob_total += x(i);\n      assert(x(i) > -0.000001);\n    }\n    assert(std::abs(prob_total - 1.0) < 0.00001);\n    return ans;\n  }\n\n  double FixationProb(double benefit, double cost, uint64_t N, double sigma, size_t mutant_idx, size_t resident_idx) const {\n    // \\frac{1}{\\rho} = \\sum_{i=0}^{N-1} \\exp\\left( \\sigma \\sum_{j=1}^{i} \\left[(N-j-1)s_{yy} + js_{yx} - (N-j)s_{xy} - (j-1)s_{xx} \\right] \\right) \\\\\n    //                = \\sum_{i=0}^{N-1} \\exp\\left( \\frac{\\sigma i}{2} \\left[(-i+2N-3)s_{yy} + (i+1)s_{yx} - (-i+2N-1)s_{xy} - (i-1)s_{xx} \\right] \\right)\n\n    double s_xx = PayoffVersus(mutant_idx, mutant_idx, benefit, cost)[0];\n    double s_yy = PayoffVersus(resident_idx, resident_idx, benefit, cost)[0];\n    auto xy = PayoffVersus(mutant_idx, resident_idx, benefit, cost);\n    double s_xy = xy[0];\n    double s_yx = xy[1];\n\n    double num_games = (N-1);\n    s_xx /= num_games;\n    s_yy /= num_games;\n    s_xy /= num_games;\n    s_yx /= num_games;\n    double rho_inv = 0.0;\n    for (int i=0; i < N; i++) {\n      double x = sigma * i * 0.5 * (\n          (2*N-3-i) * s_yy\n          + (i+1) * s_yx\n          - (2*N-1-i) * s_xy\n          - (i-1) * s_xx\n      );\n      rho_inv += std::exp(x);\n    }\n    return 1.0 / rho_inv;\n  }\n\n  std::vector<std::string> SpeciesNames() const {\n    std::vector<std::string> ans;\n    for(auto s: pool) {\n      ans.emplace_back( s.ToString() );\n    }\n    return std::move(ans);\n  }\n  double CooperationLevelSpecies(size_t i) const {\n    const ss_cache_t &ss = ss_cache[i][i];\n    if (ss.size() == 4) {\n      double level = 0.0;\n      for (size_t s = 0; s < 4; s++) {\n        size_t num_c = 2 - std::bitset<2>(s).count();\n        level += ss[s] * (num_c / 2.0);\n      };\n      return level;\n    }\n    else {\n      double level = 0.0;\n      for (size_t s = 0; s < 64; s++) {\n        StateN2M3 state(s);\n        size_t num_c = 2ul;\n        if (state.a_1 == D) num_c -= 1;\n        if (state.b_1 == D) num_c -= 1;\n        level += ss[s] * (num_c / 2.0);\n      }\n      return level;\n    }\n  }\n  double CooperationLevel(const std::vector<double> &eq_rate) const {\n    assert(eq_rate.size() == N_SPECIES);\n    double ans = 0.0;\n    for (size_t i = 0; i < N_SPECIES; i++) {\n      double c_lev = CooperationLevelSpecies(i);\n      ans += eq_rate[i] * c_lev;\n    }\n    return ans;\n  }\n};\n\n\nint main(int argc, char *argv[]) {\n  Eigen::initParallel();\n  if( argc != 11 ) {\n    std::cerr << \"Error : invalid argument\" << std::endl;\n    std::cerr << \"  Usage : \" << argv[0] << \" <Nmax> <sigma> <error rate> <discrete_level> <0:reactive/1:full memory1> <1:capri2> <1:capri> <1:aon2> <1:aon3> <1:tft_atft>\" << std::endl;\n    return 1;\n  }\n\n  if (false)  // debugging\n  {\n    Species wsls(0b1001, 1);\n    Species cccd(0b0111, 1);\n    Species capri2(0b10000, 1);\n    std::cerr << wsls.ToString() << std::endl;\n    std::cerr << capri2.ToString() << std::endl;\n    auto x = capri2.StationaryState(wsls, 0.0001);\n    std::cerr << x[0] << std::endl;\n    // std::vector<Species> pool = Species::Memory1Species(1);\n    std::vector<Species> pool;\n    pool.push_back(wsls);\n    pool.push_back(capri2);\n    pool.push_back(cccd);\n    Ecosystem eco(pool, 0.0001);\n    double p01 = eco.FixationProb(4.0, 1.0, 64, 1.0, 0, 1);\n    double p10 = eco.FixationProb(4.0, 1.0, 64, 1.0, 1, 0);\n    double p02 = eco.FixationProb(4.0, 1.0, 64, 1.0, 0, 2);\n    double p20 = eco.FixationProb(4.0, 1.0, 64, 1.0, 2, 0);\n    double p12 = eco.FixationProb(4.0, 1.0, 64, 1.0, 1, 2);\n    double p21 = eco.FixationProb(4.0, 1.0, 64, 1.0, 2, 1);\n    auto eq = eco.CalculateEquilibrium(4.0, 1.0, 64, 1.0);\n    std::cerr << cccd.ToString() << std::endl;\n    std::cerr << ' ' << p02 << std::endl;\n  }\n\n  double cost = 1.0;\n  uint64_t Nmax = std::strtoull(argv[1], nullptr,0);\n  double sigma = std::strtod(argv[2], nullptr);\n  double e = std::strtod(argv[3], nullptr);\n  uint64_t discrete_level = std::strtoull(argv[4], nullptr,0);\n\n  unsigned long full_or_reactive = std::strtoul(argv[5], nullptr, 0);\n  unsigned long add_capri2 = std::strtoul(argv[6], nullptr, 0);\n  unsigned long add_capri = std::strtoul(argv[7], nullptr, 0);\n  unsigned long add_aon2 = std::strtoul(argv[8], nullptr, 0);\n  unsigned long add_aon3 = std::strtoul(argv[9], nullptr, 0);\n  unsigned long add_tftatft = std::strtoul(argv[10], nullptr, 0);\n\n  std::vector<Species> pool = (full_or_reactive == 1 ? Species::Memory1Species(discrete_level) : Species::ReactiveMem1Species(discrete_level));\n  size_t N_M1 = Mem1Species::N_M1_Species(discrete_level);\n  if (add_capri2) {\n    pool.emplace_back(N_M1+0, discrete_level);\n  }\n  if (add_capri) {\n    pool.emplace_back(N_M1+1, discrete_level);\n  }\n  if (add_aon2) {\n    pool.emplace_back(N_M1+3, discrete_level);\n  }\n  if (add_aon3) {\n    pool.emplace_back(N_M1+4, discrete_level);\n  }\n  if (add_tftatft) {\n    pool.emplace_back(N_M1+2, discrete_level);\n  }\n  Ecosystem eco(pool, e);\n\n  {\n    std::ofstream namout(\"species.txt\");\n    for(auto name: eco.SpeciesNames()) {\n      namout << name << std::endl;\n    }\n    namout << std::endl;\n  }\n\n  auto SweepOverBeta = [&eco,cost,sigma](size_t N)->std::vector<std::pair<double,double>> {\n    char fname1[100];\n    sprintf(fname1, \"abundance_%zu.dat\", N);\n    std::ofstream eqout(fname1);\n    std::vector<std::pair<double,double>> c_levels;\n    for (int i = 5; i <= 300; i+=5) {\n      double benefit = 1.0 + i / 100.0;\n      auto eq = eco.CalculateEquilibrium(benefit, cost, N, sigma);\n      eqout << benefit << ' ';\n      for (double x: eq) { eqout << x << ' '; }\n      eqout << std::endl;\n      double c_lev = eco.CooperationLevel(eq);\n      c_levels.push_back(std::make_pair(benefit, c_lev));\n    }\n    return c_levels;\n  };\n\n  std::vector<std::vector<std::pair<double,double>>> ans;\n  for (int N = 2; N <= Nmax; N++) {\n    auto a = SweepOverBeta(N);\n    ans.push_back(a);\n  }\n\n  std::ofstream fout(\"cooperation_level.dat\");\n  for (size_t i = 0; i < ans[0].size(); i++) {\n    fout << ans[0][i].first;\n    for (size_t j = 0; j < ans.size(); j++) {\n      fout << ' ' << ans[j][i].second;\n    }\n    fout << \"\\n\";\n  }\n  fout.close();\n\n  return 0;\n}\n", "meta": {"hexsha": "4c78abf36d7e128e9bedb4ab0e82763608c2cc35", "size": 19015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/main_evo_n2.cpp", "max_stars_repo_name": "yohm/sim_CAPRI_nplayers", "max_stars_repo_head_hexsha": "d58906d7ec654e1d583090741f27a7bc03954053", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/main_evo_n2.cpp", "max_issues_repo_name": "yohm/sim_CAPRI_nplayers", "max_issues_repo_head_hexsha": "d58906d7ec654e1d583090741f27a7bc03954053", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/main_evo_n2.cpp", "max_forks_repo_name": "yohm/sim_CAPRI_nplayers", "max_forks_repo_head_hexsha": "d58906d7ec654e1d583090741f27a7bc03954053", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1211129296, "max_line_length": 185, "alphanum_fraction": 0.545253747, "num_tokens": 6581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6109300587565093}}
{"text": "/*\n * Copyright 2019 GridGain Systems, Inc. and Contributors.\n *\n * Licensed under the GridGain Community Edition License (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#define _USE_MATH_DEFINES\n\n#ifdef _WIN32\n#   include <windows.h>\n#endif\n\n#include <sql.h>\n#include <sqlext.h>\n\n#include <cmath>\n\n#include <vector>\n#include <string>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"ignite/ignite.h\"\n#include \"ignite/ignition.h\"\n#include \"ignite/impl/binary/binary_utils.h\"\n\n#include \"test_type.h\"\n#include \"test_utils.h\"\n#include \"sql_test_suite_fixture.h\"\n\nusing namespace ignite;\nusing namespace ignite::cache;\nusing namespace ignite::cache::query;\nusing namespace ignite::common;\nusing namespace ignite_test;\n\nusing namespace boost::unit_test;\n\nusing ignite::impl::binary::BinaryUtils;\n\nBOOST_FIXTURE_TEST_SUITE(SqlNumericFunctionTestSuite, ignite::SqlTestSuiteFixture)\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionAbs)\n{\n    TestType in;\n\n    in.i32Field = -42;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<SQLINTEGER>(\"SELECT {fn ABS(i32Field)} FROM TestType\", std::abs(in.i32Field));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionAcos)\n{\n    TestType in;\n\n    in.doubleField = 0.32;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn ACOS(doubleField)} FROM TestType\", std::acos(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionAsin)\n{\n    TestType in;\n\n    in.doubleField = 0.12;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn ASIN(doubleField)} FROM TestType\", std::asin(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionAtan)\n{\n    TestType in;\n\n    in.doubleField = 0.14;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn ATAN(doubleField)} FROM TestType\", std::atan(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionAtan2)\n{\n    TestType in;\n\n    in.doubleField = 0.24;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn ATAN2(doubleField, 0.2)} FROM TestType\", std::atan2(in.doubleField, 0.2));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionCeiling)\n{\n    TestType in;\n\n    in.doubleField = 7.31;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn CEILING(doubleField)} FROM TestType\", std::ceil(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionCos)\n{\n    TestType in;\n\n    in.doubleField = 2.31;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn COS(doubleField)} FROM TestType\", std::cos(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionCot)\n{\n    TestType in;\n\n    in.doubleField = 2.31;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn COT(doubleField)} FROM TestType\", 1 / std::tan(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionDegrees)\n{\n    TestType in;\n\n    in.doubleField = 2.31;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn DEGREES(doubleField)} FROM TestType\", in.doubleField * M_1_PI * 180);\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionExp)\n{\n    TestType in;\n\n    in.doubleField = 1.23;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn EXP(doubleField)} FROM TestType\", std::exp(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionFloor)\n{\n    TestType in;\n\n    in.doubleField = 5.29;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn FLOOR(doubleField)} FROM TestType\", std::floor(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionLog)\n{\n    TestType in;\n\n    in.doubleField = 15.3;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn LOG(doubleField)} FROM TestType\", std::log(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionLog10)\n{\n    TestType in;\n\n    in.doubleField = 15.3;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn LOG10(doubleField)} FROM TestType\", std::log10(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionMod)\n{\n    TestType in;\n\n    in.i64Field = 26;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<SQLBIGINT>(\"SELECT {fn MOD(i64Field, 3)} FROM TestType\", in.i64Field % 3);\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionPi)\n{\n    CheckSingleResult<double>(\"SELECT {fn PI()}\", M_PI);\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionPower)\n{\n    TestType in;\n\n    in.doubleField = 1.81;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn POWER(doubleField, 2.5)} FROM TestType\", std::pow(in.doubleField, 2.5));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionRadians)\n{\n    TestType in;\n\n    in.doubleField = 161;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn RADIANS(doubleField)} FROM TestType\", in.doubleField * M_PI / 180.0);\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionRand)\n{\n    CheckSingleResult<double>(\"SELECT {fn RAND()} * 0\", 0);\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionRound)\n{\n    TestType in;\n\n    in.doubleField = 5.29;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn ROUND(doubleField)} FROM TestType\", std::floor(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionSign)\n{\n    TestType in;\n\n    in.doubleField = -1.39;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn SIGN(doubleField)} FROM TestType\", in.doubleField < 0 ? -1 : in.doubleField == 0 ? 0 : 1);\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionSin)\n{\n    TestType in;\n\n    in.doubleField = 1.01;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn SIN(doubleField)} FROM TestType\", std::sin(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionSqrt)\n{\n    TestType in;\n\n    in.doubleField = 2.56;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn SQRT(doubleField)} FROM TestType\", std::sqrt(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionTan)\n{\n    TestType in;\n\n    in.doubleField = 0.56;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn TAN(doubleField)} FROM TestType\", std::tan(in.doubleField));\n}\n\nBOOST_AUTO_TEST_CASE(TestNumericFunctionTruncate)\n{\n    TestType in;\n\n    in.doubleField = 4.17133;\n\n    testCache.Put(1, in);\n\n    CheckSingleResult<double>(\"SELECT {fn TRUNCATE(doubleField, 3)} FROM TestType\", 4.171);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6df69c8fa6ea0c1b16bf1df6f096c00c1d8a9f56", "size": 6717, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/platforms/cpp/odbc-test/src/sql_numeric_functions_test.cpp", "max_stars_repo_name": "FedorUporov/gridgain", "max_stars_repo_head_hexsha": "883125f943743fa8198d88be98dfe61bde86ad96", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 218.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T13:20:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T05:28:55.000Z", "max_issues_repo_path": "modules/platforms/cpp/odbc-test/src/sql_numeric_functions_test.cpp", "max_issues_repo_name": "FedorUporov/gridgain", "max_issues_repo_head_hexsha": "883125f943743fa8198d88be98dfe61bde86ad96", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 175.0, "max_issues_repo_issues_event_min_datetime": "2015-02-04T23:16:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T18:34:24.000Z", "max_forks_repo_path": "modules/platforms/cpp/odbc-test/src/sql_numeric_functions_test.cpp", "max_forks_repo_name": "FedorUporov/gridgain", "max_forks_repo_head_hexsha": "883125f943743fa8198d88be98dfe61bde86ad96", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 93.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T20:54:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:09:00.000Z", "avg_line_length": 21.9509803922, "max_line_length": 132, "alphanum_fraction": 0.7184755099, "num_tokens": 1750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6109300561668741}}
{"text": "//  Copyright John Maddock 2008.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/bindings/rr.hpp>\n#include <boost/test/included/test_exec_monitor.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/test.hpp>\n#include <fstream>\n\n#include <boost/math/tools/test_data.hpp>\n\nusing namespace boost::math::tools;\nusing namespace std;\n\nstruct asinh_data_generator\n{\n   boost::math::ntl::RR operator()(boost::math::ntl::RR z)\n   {\n      std::cout << z << \" \";\n      boost::math::ntl::RR result = log(z + sqrt(z * z + 1));\n      std::cout << result << std::endl;\n      return result;\n   }\n};\n\nstruct acosh_data_generator\n{\n   boost::math::ntl::RR operator()(boost::math::ntl::RR z)\n   {\n      std::cout << z << \" \";\n      boost::math::ntl::RR result = log(z + sqrt(z * z - 1));\n      std::cout << result << std::endl;\n      return result;\n   }\n};\n\nstruct atanh_data_generator\n{\n   boost::math::ntl::RR operator()(boost::math::ntl::RR z)\n   {\n      std::cout << z << \" \";\n      boost::math::ntl::RR result = log((z + 1) / (1 - z)) / 2;\n      std::cout << result << std::endl;\n      return result;\n   }\n};\n\nint test_main(int argc, char*argv [])\n{\n   boost::math::ntl::RR::SetPrecision(500);\n   boost::math::ntl::RR::SetOutputPrecision(40);\n\n   parameter_info<boost::math::ntl::RR> arg1;\n   test_data<boost::math::ntl::RR> data;\n   std::ofstream ofs;\n\n   bool cont;\n   std::string line;\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for the inverse hyperbolic sin function:\\n\";\n\n   do{\n      if(0 == get_user_parameter_info(arg1, \"z\"))\n         return 1;\n      data.insert(asinh_data_generator(), arg1);\n\n      std::cout << \"Any more data [y/n]?\";\n      std::getline(std::cin, line);\n      boost::algorithm::trim(line);\n      cont = (line == \"y\");\n   }while(cont);\n\n   std::cout << \"Enter name of test data file [default=asinh_data.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"asinh_data.ipp\";\n   ofs.open(line.c_str());\n   write_code(ofs, data, \"asinh_data\");\n   data.clear();\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for the inverse hyperbolic cos function:\\n\";\n\n   do{\n      if(0 == get_user_parameter_info(arg1, \"z\"))\n         return 1;\n      data.insert(acosh_data_generator(), arg1);\n\n      std::cout << \"Any more data [y/n]?\";\n      std::getline(std::cin, line);\n      boost::algorithm::trim(line);\n      cont = (line == \"y\");\n   }while(cont);\n\n   std::cout << \"Enter name of test data file [default=acosh_data.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"acosh_data.ipp\";\n   ofs.close();\n   ofs.open(line.c_str());\n   write_code(ofs, data, \"acosh_data\");\n   data.clear();\n\n   std::cout << \"Welcome.\\n\"\n      \"This program will generate spot tests for the inverse hyperbolic tan function:\\n\";\n\n   do{\n      if(0 == get_user_parameter_info(arg1, \"z\"))\n         return 1;\n      data.insert(atanh_data_generator(), arg1);\n\n      std::cout << \"Any more data [y/n]?\";\n      std::getline(std::cin, line);\n      boost::algorithm::trim(line);\n      cont = (line == \"y\");\n   }while(cont);\n\n   std::cout << \"Enter name of test data file [default=atanh_data.ipp]\";\n   std::getline(std::cin, line);\n   boost::algorithm::trim(line);\n   if(line == \"\")\n      line = \"atanh_data.ipp\";\n   ofs.close();\n   ofs.open(line.c_str());\n   write_code(ofs, data, \"atanh_data\");\n   \n   return 0;\n}\n\n", "meta": {"hexsha": "b18396722d285d76ff0dbbcfddef9e8a381c70ae", "size": 3641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/math/tools/inv_hyp_data.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/math/tools/inv_hyp_data.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "boost/libs/math/tools/inv_hyp_data.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 26.9703703704, "max_line_length": 89, "alphanum_fraction": 0.6053282065, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619885, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.610930050927447}}
{"text": "/*=============================================================================\n\n  NifTK: A software platform for medical image computing.\n\n  Copyright (c) University College London (UCL). All rights reserved.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n\n  See LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include <math.h>\n#include <float.h>\n#include <iomanip>\n\n#include <niftkConversionUtils.h>\n#include <niftkCommandLineParser.h>\n#include <itkCommandLineHelper.h>\n\n#include <itkImageRegionIterator.h>\n#include <itkImageRegionConstIterator.h>\n#include <itkBasicImageFeaturesImageFilter.h>\n#include <itkImageFileReader.h>\n#include <itkImageFileWriter.h>\n#include <itkNifTKImageIOFactory.h>\n#include <itkRescaleIntensityImageFilter.h>\n#include <itkImage.h>\n#include <itkUnaryFunctorImageFilter.h>\n#include <itkScalarToRGBBIFPixelFunctor.h>\n#include <itkScalarToRGBOBIFPixelFunctor.h>\n#include <itkMaskImageFilter.h>\n#include <itkResampleImageFilter.h>\n#include <itkLinearInterpolateImageFunction.h>\n#include <itkIdentityTransform.h>\n\n#include <boost/filesystem/path.hpp>\n\nstruct niftk::CommandLineArgumentDescription clArgList[] = {\n  {OPT_SWITCH, \"dbg\", 0, \"Output debugging information.\"},\n  {OPT_SWITCH, \"v\", 0,   \"Verbose output during execution.\"},\n\n  {OPT_SWITCH, \"st\", NULL, \"Perform single threaded execution [multi-threaded].\"},\n  {OPT_SWITCH, \"resample\", NULL, \"Speed up the execution by resampling the image.\"},\n\n  {OPT_SWITCH, \"orientate\", NULL, \"Calculate orientated BIFs [no].\"},\n  {OPT_SWITCH, \"n72\", NULL, \"Calculate orientations in one degree increments [45degs].\"},\n\n  {OPT_SWITCH, \"vflip\", NULL, \"Flip the orientation vertically (e.g. for PA vs AP views).\"},\n  {OPT_SWITCH, \"hflip\", NULL, \"Flip the orientation horizontally (e.g. for ML vs LM views).\"},\n\n  {OPT_SWITCH, \"noSlope\", NULL, \"Ignore slopes, i.e. only classify as 2nd order.\"},\n\n  {OPT_DOUBLEx2, \"origin\", \"ox,oy\", \"Orientate relative to this origin in mm (0,0 = corner of the image).\"},\n\n  {OPT_FLOAT, \"sigma\", \"value\", \"The Guassian std. dev. in mm at which to compute the BIFs [1.0].\"},\n  {OPT_INT,   \"nscales\", \"n\",   \"The number of scales to process [1].\"},\n  {OPT_FLOAT, \"fscales\", \"value\", \"The multiplicative factor between scales [2.0].\"},\n\n  {OPT_FLOAT, \"e\", \"epsilon\", \"The noise suppression parameter [1e-05].\"},\n\n  {OPT_STRING, \"u2D\", \"filename\", \"Local reference orientation in 'x'.\"},\n  {OPT_STRING, \"v2D\", \"filename\", \"Local reference orientation in 'y'.\"},\n\n  {OPT_STRING, \"mask\", \"filename\", \"Only compute BIFs where the mask image is non-zero.\"},\n\n  {OPT_FLOAT, \"t\",    \"threshold\", \"Only compute BIFs where the input image is greater than <threshold>.\"},\n  {OPT_STRING, \"om\", \"filename\", \"Write the computed mask image to a file.\"},\n\n  {OPT_STRING, \"oS00\", \"filename\", \"Save the zero order smoothed image to a file.\"},\n  {OPT_STRING, \"oS10\", \"filename\", \"Save the first derivative in 'x' to a file.\"},\n  {OPT_STRING, \"oS01\", \"filename\", \"Save the first derivative in 'y' to a file.\"},\n  {OPT_STRING, \"oS11\", \"filename\", \"Save the second derivative in 'xy' to a file.\"},\n  {OPT_STRING, \"oS20\", \"filename\", \"Save the second derivative in 'xx' to a file.\"},\n  {OPT_STRING, \"oS02\", \"filename\", \"Save the second derivative in 'yy' to a file.\"},\n\n  {OPT_STRING, \"oFlat\", \"filename\", \"Save the flatness response to a file.\"},\n  {OPT_STRING, \"oSlope\", \"filename\", \"Save the slope-like response to a file.\"},\n  {OPT_STRING, \"oDarkBlob\", \"filename\", \"Save the dark blob response to a file.\"},\n  {OPT_STRING, \"oLightBlob\", \"filename\", \"Save the light blob response to a file.\"},\n  {OPT_STRING, \"oDarkLine\", \"filename\", \"Save the dark line response to a file.\"},\n  {OPT_STRING, \"oLightLine\", \"filename\", \"Save the light line response to a file.\"},\n  {OPT_STRING, \"oSaddle\", \"filename\", \"Save the saddlelike response to a file.\"},\n\n  {OPT_STRING, \"oOrient\", \"filename\", \"Save the continuous orientation image to a file.\"},\n  {OPT_STRING, \"oVar\", \"filename\", \"Save the BIF response variance image to a file.\"},\n\n  {OPT_STRING, \"oh\",   \"filename\", \"Write the histogram of BIFs to a file..\"},\n  {OPT_STRING, \"opng\", \"filename\", \"Write the label image as a colour PNG file for display purposes.\"},\n  {OPT_STRING, \"o\",    \"filename\", \"The output label image.\"},\n\n  {OPT_STRING|OPT_LONELY|OPT_REQ, NULL, \"filename\", \"The input image.\"},\n  \n  {OPT_DONE, NULL, NULL, \n   \"Program to compute basic image features for a 2D image.\\n\"\n  }\n};\n\n\nenum {\n  O_DEBUG = 0,\n  O_VERBOSE,\n\n  O_SINGLE_THREADED,\n  O_RESAMPLE_IMAGES,\n\n  O_ORIENTATE,\n  O_72_ORIENTATIONS,\n\n  O_FLIP_VERTICALLY,\n  O_FLIP_HORIZONTALLY,\n  \n  O_SECOND_ORDER_ONLY,\n\n  O_ORIGIN,\n\n  O_SIGMA_IN_MM,\n  O_NUMBER_OF_SCALES,\n  O_SCALE_FACTOR,\n\n  O_EPSILON,\n\n  O_ORIENTATION_INX,\n  O_ORIENTATION_INY,\n\n  O_MASK,\n\n  O_THRESHOLD,\n  O_OUTPUT_MASK,\n\n  O_OUTPUT_S00,\n  O_OUTPUT_S10,\n  O_OUTPUT_S01,\n  O_OUTPUT_S11,\n  O_OUTPUT_S20,\n  O_OUTPUT_S02,\n\n  O_OUTPUT_FLAT,\n  O_OUTPUT_SLOPE,\n  O_OUTPUT_DARK_BLOB,\n  O_OUTPUT_LIGHT_BLOB,\n  O_OUTPUT_DARK_LINE,\n  O_OUTPUT_LIGHT_LINE,\n  O_OUTPUT_SADDLE,    \n\n  O_OUTPUT_ORIENTATION,\n  O_OUTPUT_VARIANCE,\n\n  O_OUTPUT_HISTOGRAM,\n  O_OUTPUT_COLOUR_IMAGE,\n  O_OUTPUT_IMAGE,\n\n  O_INPUT_IMAGE\n};\n\n\nstd::string AddScaleSuffix( std::string filename, float scale, int nScales ) \n{\n  if ( nScales > 1 ) {\n\n    char strScale[128];\n\n    boost::filesystem::path pathname( filename );\n    boost::filesystem::path ofilename;\n\n    std::string extension = pathname.extension().string();\n    std::string stem = pathname.stem().string();\n\n    if ( extension == std::string( \".gz\" ) ) {\n\n      extension = pathname.stem().extension().string() + extension;\n      stem = pathname.stem().stem().string();\n    }\n\n    sprintf(strScale, \"_%03gmm\", scale);\n\n    ofilename = pathname.parent_path() /\n      boost::filesystem::path( stem + std::string( strScale ) + extension );\n    \n    return ofilename.string();\n  }\n  else \n    return filename;\n}\n\n\nstd::string AddSuffix( std::string filename, std::string suffix ) \n{\n  boost::filesystem::path pathname( filename );\n  boost::filesystem::path ofilename;\n\n  std::string extension = pathname.extension().string();\n  std::string stem = pathname.stem().string();\n\n  if ( extension == std::string( \".gz\" ) ) {\n    \n    extension = pathname.stem().extension().string() + extension;\n    stem = pathname.stem().stem().string();\n  }\n\n  ofilename = pathname.parent_path() /\n    boost::filesystem::path( stem + suffix + extension );\n    \n  return ofilename.string();\n}\n\n\nint main( int argc, char *argv[] )\n{\n  itk::NifTKImageIOFactory::Initialize();\n\n  bool flgVerbose;\n  bool flgDebug;\n\n  bool flgSingleThreaded;\n  bool flgOrientate;\n  bool flgResampleImages;\n\n  bool flgFlipVertically;\n  bool flgFlipHorizontally;\n\n  bool flgN72;\n\n  bool flgSecondOrderOnly;\n\n  unsigned int iDim;\n\n  int iScale;\n  int nScales = 1;\n\n  float sigmaInMM = 1;\n  float scaleFactor = 2.;\n  float scaleFactorRelativeToInput = 1.;\n\n  float epsilon = 1.0e-05;\n\n  float threshold = 0.;\n\n  double *origin = 0;\n\n  std::string fileOrientationInX;\n  std::string fileOrientationInY;\n\n  std::string fileMask; \n  std::string fileOutputMask;\n\n  std::string fileOutputS00;\n  std::string fileOutputS10;\n  std::string fileOutputS01;\n  std::string fileOutputS11;\n  std::string fileOutputS20;\n  std::string fileOutputS02;\n\n  std::string fileOutputFlat;\n  std::string fileOutputSlope;\n  std::string fileOutputDarkBlob;\n  std::string fileOutputLightBlob;\n  std::string fileOutputDarkLine;\n  std::string fileOutputLightLine;\n  std::string fileOutputSaddle;   \n\n  std::string fileOutputOrientation;\n  std::string fileOutputVariance;\n\n  std::string fileOutputHistogram;\n  std::string fileOutputImage;\n  std::string fileOutputColourImage;\n\n  std::string fileInputImage;\n  \n  // Create the command line parser, passing the\n  // 'CommandLineArgumentDescription' structure. The final boolean\n  // parameter indicates whether the command line options should be\n  // printed out as they are parsed.\n\n  niftk::CommandLineParser CommandLineOptions(argc, argv, clArgList, false);\n\n  CommandLineOptions.GetArgument( O_DEBUG, flgDebug );\n  CommandLineOptions.GetArgument( O_VERBOSE, flgVerbose );\n\n  CommandLineOptions.GetArgument( O_SINGLE_THREADED, flgSingleThreaded );\n  CommandLineOptions.GetArgument( O_RESAMPLE_IMAGES, flgResampleImages );\n\n  CommandLineOptions.GetArgument( O_ORIENTATE, flgOrientate );\n\n  CommandLineOptions.GetArgument( O_72_ORIENTATIONS, flgN72 );\n\n  CommandLineOptions.GetArgument( O_FLIP_VERTICALLY,   flgFlipVertically );\n  CommandLineOptions.GetArgument( O_FLIP_HORIZONTALLY, flgFlipHorizontally );\n\n  CommandLineOptions.GetArgument( O_SECOND_ORDER_ONLY, flgSecondOrderOnly);\n\n  CommandLineOptions.GetArgument( O_ORIGIN, origin );\n\n  CommandLineOptions.GetArgument( O_SIGMA_IN_MM, sigmaInMM );\n  CommandLineOptions.GetArgument( O_NUMBER_OF_SCALES, nScales );\n  CommandLineOptions.GetArgument( O_SCALE_FACTOR, scaleFactor );\n\n  CommandLineOptions.GetArgument( O_EPSILON, epsilon );\n\n  CommandLineOptions.GetArgument( O_ORIENTATION_INX, fileOrientationInX );\n  CommandLineOptions.GetArgument( O_ORIENTATION_INY, fileOrientationInY );\n\n  if ( (fileOrientationInX.length() || fileOrientationInY.length()) && origin) {\n\n    std::cerr <<\"Command line options: -u2D and -v2D cannot be used with -origin\";\n    return EXIT_FAILURE;\n  }                \n    \n  if ( (fileOrientationInX.length() || fileOrientationInY.length()) \n       && ! (fileOrientationInX.length() && fileOrientationInY.length()) ) {\n\n    std::cerr <<\"Both command line options: -u2D and -v2D are required\";\n    return EXIT_FAILURE;\n  }                \n    \n  CommandLineOptions.GetArgument( O_MASK, fileMask );\n\n  CommandLineOptions.GetArgument( O_THRESHOLD, threshold );\n  CommandLineOptions.GetArgument( O_OUTPUT_MASK, fileOutputMask );\n\n  CommandLineOptions.GetArgument( O_OUTPUT_S00, fileOutputS00 );\n  CommandLineOptions.GetArgument( O_OUTPUT_S10, fileOutputS10 );\n  CommandLineOptions.GetArgument( O_OUTPUT_S01, fileOutputS01 );\n  CommandLineOptions.GetArgument( O_OUTPUT_S11, fileOutputS11 );\n  CommandLineOptions.GetArgument( O_OUTPUT_S20, fileOutputS20 );\n  CommandLineOptions.GetArgument( O_OUTPUT_S02, fileOutputS02 );\n\n  CommandLineOptions.GetArgument( O_OUTPUT_FLAT,       fileOutputFlat );\n  CommandLineOptions.GetArgument( O_OUTPUT_SLOPE,      fileOutputSlope );\n  CommandLineOptions.GetArgument( O_OUTPUT_DARK_BLOB,  fileOutputDarkBlob );\n  CommandLineOptions.GetArgument( O_OUTPUT_LIGHT_BLOB, fileOutputLightBlob );\n  CommandLineOptions.GetArgument( O_OUTPUT_DARK_LINE,  fileOutputDarkLine );\n  CommandLineOptions.GetArgument( O_OUTPUT_LIGHT_LINE, fileOutputLightLine );\n  CommandLineOptions.GetArgument( O_OUTPUT_SADDLE,     fileOutputSaddle );\n\n  CommandLineOptions.GetArgument( O_OUTPUT_ORIENTATION, fileOutputOrientation );\n  CommandLineOptions.GetArgument( O_OUTPUT_VARIANCE, fileOutputVariance );\n\n  CommandLineOptions.GetArgument( O_OUTPUT_HISTOGRAM, fileOutputHistogram );\n  CommandLineOptions.GetArgument( O_OUTPUT_COLOUR_IMAGE, fileOutputColourImage );\n  CommandLineOptions.GetArgument( O_OUTPUT_IMAGE, fileOutputImage );\n\n  CommandLineOptions.GetArgument( O_INPUT_IMAGE, fileInputImage );\n\n\n  // Read the input image\n  // ~~~~~~~~~~~~~~~~~~~~\n\n  int dims = itk::PeekAtImageDimension(fileInputImage);\n  // Define the dimension of the images\n  const unsigned int ImageDimension = 2;\n\n  if (dims != ImageDimension)\n  {\n    std::cerr << \"Unsupported image dimension.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  typedef float InputPixelType;\n  typedef itk::Image<InputPixelType, ImageDimension> InputImageType;\n\n  typedef itk::ImageFileReader< InputImageType > FileReaderType;\n\n  typedef float OutputPixelType;\n  typedef itk::Image<OutputPixelType, ImageDimension> OutputImageType;\n\n  typedef itk::BasicImageFeaturesImageFilter< InputImageType, OutputImageType > BasicImageFeaturesFilterType;\n\n  typedef BasicImageFeaturesFilterType::MaskImageType MaskImageType;\n\n  typedef itk::ImageFileReader< MaskImageType > MaskReaderType;\n\n\n\n  FileReaderType::Pointer imageReader = FileReaderType::New();\n\n  imageReader->SetFileName(fileInputImage);\n\n  try\n  { \n    std::cout << \"Reading the input image\" << std::endl;\n    imageReader->Update();\n  }\n  catch (itk::ExceptionObject &ex)\n  { \n    std::cout << ex << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  InputImageType::SizeType    nPixelsInput;\n  InputImageType::SpacingType resnInput;\n  InputImageType::PointType   originInput;\n\n  nPixelsInput = imageReader->GetOutput()->GetLargestPossibleRegion().GetSize();\n  resnInput    = imageReader->GetOutput()->GetSpacing();\n  originInput  = imageReader->GetOutput()->GetOrigin();\n\n\n  // Set up the image resampler\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  InputImageType::SizeType    nPixelsResampled;\n  InputImageType::SpacingType resnResampled;\n  InputImageType::PointType   originResampled;\n\n  InputImageType::Pointer pInputImage;\n  \n  typedef itk::ResampleImageFilter< InputImageType, InputImageType > ResampleFilterType;\n  ResampleFilterType::Pointer resampleInputFilter = 0;\n\n  typedef itk::IdentityTransform< double, ImageDimension > IdentityTransformType;\n  IdentityTransformType::Pointer resampleIdentityTransform = 0;\n\n  typedef itk::LinearInterpolateImageFunction< InputImageType, double > ResampleInterpolatorType;\n  ResampleInterpolatorType::Pointer resampleInterpolator = 0;\n\n  if ( flgResampleImages ) {\n\n    for ( iDim=0; iDim<ImageDimension; iDim++) {\n      \n      nPixelsResampled[iDim] = nPixelsInput[iDim];\n      resnResampled[iDim]    = resnInput[iDim];\n      originResampled[iDim]  = originInput[iDim];\n    }\n\n    resampleInputFilter = ResampleFilterType::New();\n\n    resampleIdentityTransform = IdentityTransformType::New();\n    resampleInterpolator      = ResampleInterpolatorType::New();\n\n    resampleInputFilter->SetInput( imageReader->GetOutput() );\n    resampleInputFilter->SetOutputSpacing( resnResampled );\n    resampleInputFilter->SetOutputOrigin( originResampled );\n    resampleInputFilter->SetSize( nPixelsResampled );\n\n    resampleInputFilter->SetTransform( resampleIdentityTransform );\n    resampleInputFilter->SetInterpolator( resampleInterpolator );\n\n    resampleInputFilter->SetDefaultPixelValue( 0 );\n\n    InputImageType::DirectionType direction;\n    direction.SetIdentity();\n    resampleInputFilter->SetOutputDirection( direction );\n\n    try\n      { \n\tstd::cout << \"Resampling the input image\" << std::endl;\n\tresampleInputFilter->Update();\n      }\n    catch (itk::ExceptionObject &ex)\n      { \n\tstd::cout << ex << std::endl;\n\treturn EXIT_FAILURE;\n      }\n\n    pInputImage = resampleInputFilter->GetOutput();\n\n  }\n  else \n    pInputImage = imageReader->GetOutput();\n\n\n  // Read the local orientation images\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  FileReaderType::Pointer xOrientReader, yOrientReader;\n\n  if ( (fileOrientationInX.length() > 0) && (fileOrientationInY.length() > 0) ) {\n\n    flgOrientate = true; \n\n    xOrientReader = FileReaderType::New();\n\n    xOrientReader->SetFileName( fileOrientationInX );\n\n    try\n      { \n\tstd::cout << \"Reading the local orientation in 'x'\" << std::endl;\n\txOrientReader->Update();\n      }\n    catch (itk::ExceptionObject &ex)\n      { \n\tstd::cout << ex << std::endl;\n\treturn EXIT_FAILURE;\n      }\n\n    yOrientReader = FileReaderType::New();\n\n    yOrientReader->SetFileName( fileOrientationInY );\n\n    try\n      { \n\tstd::cout << \"Reading the local orientation in 'y'\" << std::endl;\n\tyOrientReader->Update();\n      }\n    catch (itk::ExceptionObject &ex)\n      { \n\tstd::cout << ex << std::endl;\n\treturn EXIT_FAILURE;\n      }\n  }\n\n\n  // Read the mask\n  // ~~~~~~~~~~~~~\n\n  MaskImageType::Pointer pMaskImage = 0;\n  MaskReaderType::Pointer maskReader = 0;\n\n  if ( fileMask.length() > 0 ) {\n\n    maskReader = MaskReaderType::New();\n\n    maskReader->SetFileName(fileMask);\n\n    try\n      { \n\tstd::cout << \"Reading the mask image\" << std::endl;\n\tmaskReader->Update();\n      }\n    catch (itk::ExceptionObject &ex)\n      { \n\tstd::cout << ex << std::endl;\n\treturn EXIT_FAILURE;\n      }\n\n    pMaskImage = maskReader->GetOutput();\n  }\n\n  // Or create it by thresholding the input image\n\n  if ( threshold ) {\n\n    if ( ! pMaskImage ) {\n\n      pMaskImage = MaskImageType::New();\n\n      pMaskImage->SetRegions( pInputImage->GetLargestPossibleRegion() );\n      pMaskImage->SetSpacing( pInputImage->GetSpacing() );\n      pMaskImage->SetOrigin( pInputImage->GetOrigin() );\n\n      pMaskImage->Allocate( );\n      pMaskImage->FillBuffer( 1 );\n    }\n\n    typedef itk::ImageRegionConstIterator< InputImageType > InputIteratorType;\n  \n    InputIteratorType itInput( pInputImage, pInputImage->GetLargestPossibleRegion() );\n    \n    InputImageType::IndexType index;\n\n    itInput.GoToBegin();\n\n    while (! itInput.IsAtEnd() ) {\n      \n      index = itInput.GetIndex();\t\n\n      if ( itInput.Get() < threshold )\n\n\tpMaskImage->SetPixel( index, 0);\n\n      ++itInput;\n    }\n  }\n\n  if ( pMaskImage && ( fileOutputMask.length() > 0 ) ) {\n\n    typedef itk::ImageFileWriter< MaskImageType > FileWriterType;\n\n    FileWriterType::Pointer writer = FileWriterType::New();\n\n    writer->SetFileName( fileOutputMask.c_str() );\n    writer->SetInput( pMaskImage );\n\n    try\n    {\n      std::cout << \"Writing: \" << fileOutputMask.c_str() << std::endl;\n      writer->Update();\n    }\n    catch (itk::ExceptionObject &e)\n    {\n      std::cerr << e << std::endl;\n    }\n  }\n\n\n  // Create the basic image features filter\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  BasicImageFeaturesFilterType::Pointer BIFsFilter = BasicImageFeaturesFilterType::New();\n\n  if ( flgDebug )\n    BIFsFilter->DebugOn();\n\n  if ( flgVerbose )\n    BIFsFilter->VerboseOn();\n\n  if (flgSingleThreaded)\n    BIFsFilter->SetSingleThreadedExecution();\n\n  BIFsFilter->SetEpsilon( epsilon );\n\n  if (flgOrientate) {\n    BIFsFilter->CalculateOrientatedBIFs();\n\n    if ( flgN72 )\n      BIFsFilter->SetNumberOfOrientations( 72 );\n  }\n\n  if ( flgFlipVertically )   BIFsFilter->SetFlipVertically();\n  if ( flgFlipHorizontally ) BIFsFilter->SetFlipHorizontally();\n\n  if ( flgSecondOrderOnly ) BIFsFilter->SecondOrderOnly();\n\n  if (origin) {\n    BasicImageFeaturesFilterType::OriginType bifOrigin;\n\n    bifOrigin[0] = origin[0];\n    bifOrigin[1] = origin[1];\n\n    BIFsFilter->SetOrigin( bifOrigin );\n  }\n\n  if ( (fileOrientationInX.length() > 0) && (fileOrientationInY.length() > 0) )\n    BIFsFilter->SetLocalOrientation( xOrientReader->GetOutput(), \n\t\t\t\t     yOrientReader->GetOutput() );\n\n  if ( pMaskImage ) \n    BIFsFilter->SetMask( pMaskImage );\n\n  BIFsFilter->SetInput( pInputImage );\n  \n\n  // Run the filter at each scale\n  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n  for (iScale=0; iScale<nScales; iScale++) {\n    \n    BIFsFilter->SetSigma( sigmaInMM );\n\n\n    try\n      {\n\tstd::cout << \"Computing basic image features\" << std::endl;\n\tBIFsFilter->Update();\n      }\n    catch (itk::ExceptionObject &e)\n      {\n\tstd::cerr << e << std::endl;\n      }\n  \n  \n    // Compute a histogram of the BIFs\n    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    if ( fileOutputHistogram.length() > 0 ) {\n\n      unsigned int iBin;\n      unsigned int nBins;\n\n      float nPixels = 0;\n      float *histogram;\n\n      OutputPixelType pixel;\n\n      OutputImageType::Pointer bifs = BIFsFilter->GetOutput();\n\n      if (flgOrientate) {\n\tif ( flgN72 )\n\t  nBins = 183;\n\telse\n\t  nBins = 23;\n      }\n      else\n\tnBins = 7;\n\n      histogram = new float[nBins];\n\n      for (iBin=0; iBin<nBins; iBin++) \n\thistogram[ iBin ] = 0.;\n  \n      if ( pMaskImage ) {\n\n\ttypedef itk::ImageRegionConstIterator< MaskImageType > MaskIteratorType;\n  \n\tMaskImageType::Pointer mask = pMaskImage;\n\n\tMaskIteratorType itMask( pMaskImage, pMaskImage->GetLargestPossibleRegion() );\n    \n\tMaskImageType::IndexType index;\n\n\titMask.GoToBegin();\n\n\twhile (! itMask.IsAtEnd() ) {\n      \n\t  index = itMask.GetIndex();\t\n\n\t  if ( itMask.Get() > 0 ) {\t// if inside the mask\n\n\t    pixel = bifs->GetPixel( index );\n\n\t    if ( (pixel < 0) || (pixel >= nBins) )\n\t      std::cerr << \"BIF value (\"\n\t\t\t<< niftk::ConvertToString(pixel)\n\t\t\t<< \") exceeds histogram range (0 to \"\n\t\t\t<< niftk::ConvertToString(nBins - 1) << \".\";\n\n\t    else {\n\t      nPixels++;\n\t      histogram[ (unsigned int) pixel ]++;\n\t    }\n\t  }\n\n\t  ++itMask;\n\t}\n      }\n      else {\n\ttypedef itk::ImageRegionConstIterator< OutputImageType > IteratorType;\n  \n\tIteratorType itBIFs( bifs, bifs->GetLargestPossibleRegion() );\n    \n\titBIFs.GoToBegin();\n\n\twhile (! itBIFs.IsAtEnd() ) {\n      \n\t  pixel = itBIFs.Get();\n\n\t  if ( (pixel < 0) || (pixel >= nBins) )\n\t    std::cerr <<std::string(\"BIF value (\")\n\t\t      << niftk::ConvertToString(pixel)\n\t\t      << \") exceeds histogram range (0 to \"\n\t\t      << niftk::ConvertToString(nBins - 1) + \".\";\n      \n\t  else {\n\t    nPixels++;\n\t    histogram[ (unsigned int) pixel ]++;\n\t  }\n\n\t  ++itBIFs;\n\t}\n\n      }\n\n      std::fstream fout;\n      fout.open( AddScaleSuffix( fileOutputHistogram, sigmaInMM, nScales ).c_str(), std::ios::out );\n\n      if ((! fout) || fout.bad()) {\n\tstd::cerr << \"Failed to open file: \"\n\t\t  << AddScaleSuffix( fileOutputHistogram, sigmaInMM, nScales ) << std::endl;\n\texit(1);\n      }\n  \n      std::cout << \"Writing: \" \n\t\t<< AddScaleSuffix( fileOutputHistogram, sigmaInMM, nScales ) << std::endl;\n      \n      for (iBin=0; iBin<nBins; iBin++) \n\n\tfout << std::setw(6) << iBin << \" \"\n\t     << histogram[ iBin ]/nPixels << std::endl;\n  \n      delete histogram;\n      fout.close();    \n    }\n\t\n\n    // Write the derivatives?\n    // ~~~~~~~~~~~~~~~~~~~~~~\n\n    if ( fileOutputS00.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 0, AddScaleSuffix( fileOutputS00, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n    if ( fileOutputS10.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 1, AddScaleSuffix( fileOutputS10, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n    if ( fileOutputS01.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 2, AddScaleSuffix( fileOutputS01, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n    if ( fileOutputS11.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 3, AddScaleSuffix( fileOutputS11, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n    if ( fileOutputS20.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 4, AddScaleSuffix( fileOutputS20, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n    if ( fileOutputS02.length() != 0 ) \n      BIFsFilter->WriteDerivativeToFile( 5, AddScaleSuffix( fileOutputS02, \n\t\t\t\t\t\t\t    sigmaInMM, nScales ) );\n\n\n    // Write the filter responses?\n    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    if ( fileOutputFlat.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 0, AddScaleSuffix( fileOutputFlat, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputSlope.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 1, AddScaleSuffix( fileOutputSlope, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputDarkBlob.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 2, AddScaleSuffix( fileOutputDarkBlob, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputLightBlob.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 3, AddScaleSuffix( fileOutputLightBlob, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputLightLine.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 4, AddScaleSuffix( fileOutputLightLine, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputDarkLine.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 5, AddScaleSuffix( fileOutputDarkLine, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n    if ( fileOutputSaddle.length() != 0 ) \n      BIFsFilter->WriteFilterResponseToFile( 6, AddScaleSuffix( fileOutputSaddle, \n\t\t\t\t\t\t\t\tsigmaInMM, nScales ) );\n\n\n    // Write the BIF image?\n    // ~~~~~~~~~~~~~~~~~~~~\n\n    if (fileOutputImage.length() != 0) {\n\n      typedef itk::ImageFileWriter< OutputImageType > FileWriterType;\n\n      FileWriterType::Pointer writer = FileWriterType::New();\n\n      writer->SetFileName( AddScaleSuffix( fileOutputImage, sigmaInMM, nScales ) );\n      writer->SetInput( BIFsFilter->GetOutput() );\n\n      try\n\t{\n\t  std::cout << \"Writing: \"\n\t\t    << AddScaleSuffix( fileOutputImage, sigmaInMM, nScales ) << std::endl;\n\t  writer->Update();\n\t}\n      catch (itk::ExceptionObject &e)\n\t{\n\t  std::cerr << e << std::endl;\n\t}\n    }\n\n    if (fileOutputColourImage.length() != 0) {\n\n      typedef itk::RGBPixel<unsigned char> RGBPixelType;\n      typedef itk::Image<RGBPixelType, 2> RGBImageType;\n\n      typedef itk::ImageFileWriter< RGBImageType > FileWriterType;\n\n      FileWriterType::Pointer writer = FileWriterType::New();\n      writer->SetFileName( AddScaleSuffix( fileOutputColourImage, sigmaInMM, nScales ) );\n\n      if (flgOrientate) {\n\tif ( flgN72 ) {\n\t  typedef itk::Functor::ScalarToRGBOBIFPixelFunctor<OutputPixelType, 72> ColorMapFunctorType;\n\t  typedef itk::UnaryFunctorImageFilter<OutputImageType, RGBImageType, ColorMapFunctorType> ColorMapFilterType;\n      \n\t  ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();\n\t  colormapper->SetInput(BIFsFilter->GetOutput());\n\t  colormapper->UpdateLargestPossibleRegion();\n\t  \n\t  writer->SetInput(colormapper->GetOutput());\n\t}\n\telse {\n\t  typedef itk::Functor::ScalarToRGBOBIFPixelFunctor<OutputPixelType, 8> ColorMapFunctorType;\n\t  typedef itk::UnaryFunctorImageFilter<OutputImageType, RGBImageType, ColorMapFunctorType> ColorMapFilterType;\n\t\n\t  ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();\n\t  colormapper->SetInput(BIFsFilter->GetOutput());\n\t  colormapper->UpdateLargestPossibleRegion();\n\t  \n\t  writer->SetInput(colormapper->GetOutput());\n\t}\n      }\n      else {\n\ttypedef itk::Functor::ScalarToRGBBIFPixelFunctor<OutputPixelType> ColorMapFunctorType;\n\ttypedef itk::UnaryFunctorImageFilter<OutputImageType, RGBImageType, ColorMapFunctorType> ColorMapFilterType;\n      \n\tColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();\n\tcolormapper->SetInput(BIFsFilter->GetOutput());\n\tcolormapper->UpdateLargestPossibleRegion();\n\n\twriter->SetInput(colormapper->GetOutput());\n      }\n\n      try\n\t{\n\t  std::cout << \"Writing: \" \n\t\t    << AddScaleSuffix( fileOutputColourImage, sigmaInMM, nScales ) << std::endl;\n\t  writer->Update();\n\t}\n      catch (itk::ExceptionObject &e)\n\t{\n\t  std::cerr << e << std::endl;\n\t}\n    }\n\n\n    // Output the orientation image\n    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n    \n    if ( fileOutputOrientation.length() > 0 ) {\n      \n      typedef itk::ImageFileWriter< OutputImageType > FileWriterType;\n      \n      FileWriterType::Pointer writer = FileWriterType::New();\n      writer->SetFileName( AddScaleSuffix( fileOutputOrientation, sigmaInMM, nScales ) );\n\n      typedef itk::MaskImageFilter< OutputImageType, MaskImageType, OutputImageType > \n\tMaskFilterType;\n\n\n      if ( pMaskImage ) {\n\tMaskFilterType::Pointer maskFilter = MaskFilterType::New();\n\n\tmaskFilter->SetInput1( BIFsFilter->GetOrientation() );\n\tmaskFilter->SetInput2( pMaskImage );\n\n\tmaskFilter->Update();\n\n\twriter->SetInput( maskFilter->GetOutput() );\n      }\n      else\n\twriter->SetInput( BIFsFilter->GetOrientation() );\n      \n      try\n\t{\n\t  std::cout << \"Writing: \"\n\t\t    << AddScaleSuffix( fileOutputOrientation, sigmaInMM, nScales ) << std::endl;\n\t  writer->Update();\n\t}\n      catch (itk::ExceptionObject &e)\n\t{\n\t  std::cerr << e << std::endl;\n\t}\n    }\n\n  \n    // Calculate the BIF response variance image\n    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    if ( fileOutputVariance.length() > 0 ) {\n\n      float mean, variance, S00;\n      float rFlat, rSlope, rDarkBlob, rLightBlob, rDarkLine, rLightLine, rSaddle;\n\n      OutputImageType::Pointer imVariance = OutputImageType::New();\n      OutputImageType::RegionType region = pInputImage->GetLargestPossibleRegion();\n\n      imVariance->SetRegions( region );\n      imVariance->SetSpacing( pInputImage->GetSpacing() );\n      imVariance->SetOrigin( pInputImage->GetOrigin() );\n\n      imVariance->Allocate( );\n      imVariance->FillBuffer( 0. );\n\n      if ( pMaskImage ) {\n\n\ttypedef itk::ImageRegionConstIterator< MaskImageType > MaskIteratorType;\n  \n\tMaskIteratorType itMask( pMaskImage, pMaskImage->GetLargestPossibleRegion() );\n    \n\tMaskImageType::IndexType index;\n\n\titMask.GoToBegin();\n\n\twhile (! itMask.IsAtEnd() ) {\n      \n\t  index = itMask.GetIndex();\t\n\n\t  if ( itMask.Get() > 0 ) {\t// if inside the mask\n\n\t    S00 = BIFsFilter->GetS00()->GetPixel( index );\n\n\t    rFlat      = BIFsFilter->GetResponseFlat(     )->GetPixel( index );\n\t    rSlope     = BIFsFilter->GetResponseSlope(    )->GetPixel( index );\n\t    rDarkBlob  = BIFsFilter->GetResponseDarkBlob( )->GetPixel( index );\n\t    rLightBlob = BIFsFilter->GetResponseLightBlob()->GetPixel( index );\n\t    rDarkLine  = BIFsFilter->GetResponseDarkLine( )->GetPixel( index );\n\t    rLightLine = BIFsFilter->GetResponseLightLine()->GetPixel( index );\n\t    rSaddle    = BIFsFilter->GetResponseSaddle(   )->GetPixel( index );\n\n\t    mean = ( rFlat + rSlope + rDarkBlob + rLightBlob + rDarkLine + rLightLine + rSaddle )/7.;\n\n\t    variance = ( (rFlat      - mean)*(rFlat      - mean) + \n\t\t\t (rSlope     - mean)*(rSlope     - mean) + \n\t\t\t (rDarkBlob  - mean)*(rDarkBlob  - mean) + \n\t\t\t (rLightBlob - mean)*(rLightBlob - mean) + \n\t\t\t (rDarkLine  - mean)*(rDarkLine  - mean) + \n\t\t\t (rLightLine - mean)*(rLightLine - mean) + \n\t\t\t (rSaddle    - mean)*(rSaddle    - mean) )/7.;\n\n\t    if ( S00 )\n\t      imVariance->SetPixel( index, variance/S00 );\n\t    else\n\t      imVariance->SetPixel( index, 0.);\n\t  }\n\n\t  ++itMask;\n\t}\n      }\n      else {\n\ttypedef itk::ImageRegionConstIterator< OutputImageType > IteratorType;\n  \n\tIteratorType itVar( imVariance, imVariance->GetLargestPossibleRegion() );\n\n\tOutputImageType::IndexType index;\n    \n\titVar.GoToBegin();\n      \n\twhile (! itVar.IsAtEnd() ) {\n\t\n\t  index = itVar.GetIndex();\t\n\n\t  S00 = BIFsFilter->GetS00()->GetPixel( index );\n\n\t  rFlat      = BIFsFilter->GetResponseFlat(     )->GetPixel( index );\n\t  rSlope     = BIFsFilter->GetResponseSlope(    )->GetPixel( index );\n\t  rDarkBlob  = BIFsFilter->GetResponseDarkBlob( )->GetPixel( index );\n\t  rLightBlob = BIFsFilter->GetResponseLightBlob()->GetPixel( index );\n\t  rDarkLine  = BIFsFilter->GetResponseDarkLine( )->GetPixel( index );\n\t  rLightLine = BIFsFilter->GetResponseLightLine()->GetPixel( index );\n\t  rSaddle    = BIFsFilter->GetResponseSaddle(   )->GetPixel( index );\n\n\t  mean = ( rFlat + rSlope + rDarkBlob + rLightBlob + rDarkLine + rLightLine + rSaddle )/7.;\n\n\t  variance = ( (rFlat      - mean)*(rFlat      - mean) + \n\t\t       (rSlope     - mean)*(rSlope     - mean) + \n\t\t       (rDarkBlob  - mean)*(rDarkBlob  - mean) + \n\t\t       (rLightBlob - mean)*(rLightBlob - mean) + \n\t\t       (rDarkLine  - mean)*(rDarkLine  - mean) + \n\t\t       (rLightLine - mean)*(rLightLine - mean) + \n\t\t       (rSaddle    - mean)*(rSaddle    - mean) )/7.;\n\t\n\t  if ( S00 )\n\t    imVariance->SetPixel( index, variance/S00 );\n\t  else\n\t    imVariance->SetPixel( index, 0.);\n\t\n\t  ++itVar;\n\t}\n      }\n\n      typedef itk::ImageFileWriter< OutputImageType > FileWriterType;\n\n      FileWriterType::Pointer writer = FileWriterType::New();\n\n      writer->SetFileName( AddScaleSuffix( fileOutputVariance, sigmaInMM, nScales ) );\n      writer->SetInput( imVariance );\n\n      try\n\t{\n\t  std::cout << \"Writing: \" \n\t\t    << AddScaleSuffix( fileOutputVariance, sigmaInMM, nScales ) << std::endl;\n\t  writer->Update();\n\t}\n      catch (itk::ExceptionObject &e)\n\t{\n\t  std::cerr << e << std::endl;\n\t}\n    }\n\n    // Increase the scale used\n    // ~~~~~~~~~~~~~~~~~~~~~~~\n\n    sigmaInMM *= scaleFactor;    \n    scaleFactorRelativeToInput *= scaleFactor;  \n\n    \n    // Update the resampling?\n    // ~~~~~~~~~~~~~~~~~~~~~~\n\n    if ( flgResampleImages ) {\n      float actualSamplingFactor;\n\n      for ( iDim=0; iDim<ImageDimension; iDim++) {\n\t\n\tnPixelsResampled[iDim] = static_cast<InputImageType::SizeValueType>( ceil( ((float) nPixelsInput[iDim])\n\t\t\t\t\t\t\t\t\t      / scaleFactorRelativeToInput ) );\n\n\tactualSamplingFactor = ((float) nPixelsInput[iDim]) / ((float) nPixelsResampled[iDim] );\n\n\tresnResampled[iDim]    = resnInput[iDim] * actualSamplingFactor;\n\n\toriginResampled[iDim]  = originInput[iDim] + resnResampled[iDim]/2. - resnInput[iDim]/2.;\n      }\n\n      resampleInputFilter->SetOutputSpacing( resnResampled );\n      resampleInputFilter->SetOutputOrigin( originResampled );\n      resampleInputFilter->SetSize( nPixelsResampled );\n\n      resampleInputFilter->SetInput( BIFsFilter->GetS00() );\n\n      try\n\t{ \n\t  std::cout << \"Resampling the input image by: \" << actualSamplingFactor << std::endl;\n\t  resampleInputFilter->UpdateLargestPossibleRegion();\n\t}\n      catch (itk::ExceptionObject &ex)\n\t{ \n\t  std::cout << ex << std::endl;\n\t  return EXIT_FAILURE;\n\t}\n    }    \n    \n  }\n}\n", "meta": {"hexsha": "537982ba8229c71d38f7f1235e7344888bd28799", "size": 32682, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Applications/BasicImageFeatures/niftkBasicImageFeatures.cxx", "max_stars_repo_name": "NifTK/NifTK", "max_stars_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T13:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T19:17:39.000Z", "max_issues_repo_path": "Applications/BasicImageFeatures/niftkBasicImageFeatures.cxx", "max_issues_repo_name": "NifTK/NifTK", "max_issues_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/BasicImageFeatures/niftkBasicImageFeatures.cxx", "max_forks_repo_name": "NifTK/NifTK", "max_forks_repo_head_hexsha": "2358b333c89ff1bba1c232eecbbcdc8003305dfe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-08-20T07:06:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T07:55:27.000Z", "avg_line_length": 29.3638814016, "max_line_length": 111, "alphanum_fraction": 0.6701854232, "num_tokens": 8926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6109300482776544}}
{"text": "// Compile with:\n// clang++ -o demoPrincipalComponentProjector5D demoPrincipalComponentProjector5D.cpp -L../build/ -I ../include/ -l diamonds -stdlib=libc++ -std=c++11 -Wno-deprecated-register\n//\n\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <Eigen/Core>\n#include \"File.h\"\n#include \"PrincipalComponentProjector.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\nint main()\n{\n    // Open the input file and read the data (synthetic sampling of a 5D parameter space)\n    \n    ifstream inputFile;\n    File::openInputFile(inputFile, \"kmeans_testsample5D.txt\");\n    \n    unsigned long Nrows;\n    int Ncols;\n\n    File::sniffFile(inputFile, Nrows, Ncols);\n    ArrayXXd data = File::arrayXXdFromFile(inputFile, Nrows, Ncols);\n    ArrayXXd sample = data.transpose();\n    inputFile.close();\n\n    \n    // Set up the Principal Component Projector and apply this to the input sample\n\n    bool printNdimensions = true;\n    PrincipalComponentProjector projector(printNdimensions);\n    \n    ArrayXXd optimizedSample;\n    optimizedSample = projector.projection(sample);\n    ArrayXXd finalSample = optimizedSample.transpose();\n\n\n    // Print the reduced-dimensionality sample into an output ASCII file\n\n    ofstream outputFile;\n    File::openOutputFile(outputFile, \"principalComponentProjection5D.txt\");\n    outputFile << scientific << setprecision(4);\n    File::arrayXXdToFile(outputFile, finalSample);\n    outputFile.close();\n\n\n\n    // That's it!\n \n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "b605f4de5955f3e9f05616d8d0fbd0f5842f2edd", "size": 1499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/demoPrincipalComponentProjector5D.cpp", "max_stars_repo_name": "vishalbelsare/DIAMONDS", "max_stars_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/demoPrincipalComponentProjector5D.cpp", "max_issues_repo_name": "vishalbelsare/DIAMONDS", "max_issues_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/demoPrincipalComponentProjector5D.cpp", "max_forks_repo_name": "vishalbelsare/DIAMONDS", "max_forks_repo_head_hexsha": "76409b22c9da782436b52e454a8b36bc78fca6f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.298245614, "max_line_length": 175, "alphanum_fraction": 0.7204803202, "num_tokens": 347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182187, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6109300353294788}}
{"text": "#include \"hash_filter_utils.h\"\n#include \"ps-plus/common/initializer/none_initializer.h\"\n#include <Eigen/Dense>\n\nnamespace ps {\nnamespace server {\nnamespace udf {\n\nvoid l2_norm_op(std::shared_ptr<std::vector<HashMapItem>>& indexes, Tensor* input, std::shared_ptr<Tensor>& output) {\n  const auto& shape = input->Shape();\n  assert(shape.Size() == 2);\n  output.reset(new Tensor(input->Type(), TensorShape({shape[0]}), new initializer::NoneInitializer));\n  Eigen::MatrixXf m(indexes->size(), shape[1]);\n  m.setZero();\n\n  CASES(input->Type(), {\n    T* data_ptr = input->Raw<T>();\n    T* data;\n    for (size_t i = 0; i < indexes->size(); i++) {\n\n      T* data = data_ptr + (*indexes)[i].id * shape[1];\n      for (size_t j = 0; j < shape[1]; j++) {\n        m(i, j) = *data;\n        ++data;\n      }      \n    }\n  });\n\n  //auto& res = m.rowwise().squaredNorm();\n  auto& res = m.rowwise().norm();\n  \n  CASES(output->Type(), {\n    T* data_ptr = output->Raw<T>();\n    T* data;\n    for (size_t i = 0; i < indexes->size(); i++) {\n      data = data_ptr + (*indexes)[i].id;\n      *data = res(i);\n      ++data;\n    }\n  });\n  \n  printf(\"l2_norm_op indexes size: %ld, l2 norm output range(%f, %f) \\n\", \n         indexes->size(), res.minCoeff(), res.maxCoeff());\n};\n}\n}\n}\n", "meta": {"hexsha": "39a3f64e15ee45e2fb122c65d2078b69666acec3", "size": 1251, "ext": "cc", "lang": "C++", "max_stars_repo_path": "xdl/ps-plus/ps-plus/server/udf/hash_filter_utils.cc", "max_stars_repo_name": "bigo-sg/x-deeplearning", "max_stars_repo_head_hexsha": "d7c006d316f50a8d0c38478101d0ef8be4b9c886", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-28T10:11:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T10:11:26.000Z", "max_issues_repo_path": "xdl/ps-plus/ps-plus/server/udf/hash_filter_utils.cc", "max_issues_repo_name": "bigo-sg/x-deeplearning", "max_issues_repo_head_hexsha": "d7c006d316f50a8d0c38478101d0ef8be4b9c886", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xdl/ps-plus/ps-plus/server/udf/hash_filter_utils.cc", "max_forks_repo_name": "bigo-sg/x-deeplearning", "max_forks_repo_head_hexsha": "d7c006d316f50a8d0c38478101d0ef8be4b9c886", "max_forks_repo_licenses": ["Apache-2.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.0625, "max_line_length": 117, "alphanum_fraction": 0.5715427658, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6109096736288319}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n#include \"quadrature/qmaxwell.hpp\"\n#include \"spectral/lagrange_polynomial.hpp\"\n\n\nnamespace boltzmann {\nnamespace impl_lsq {\n\nclass LSQ_BC_Base\n{\n public:\n  LSQ_BC_Base(int K);\n\n  virtual void apply(Eigen::DenseBase<DERIVED>& dst, const Eigen::DenseBase<DERIVED>& src) const;\n\n protected:\n  Eigen::MatrixXd L_;\n};\n\nLSQ_BC_Base::LSQ_BC_Base(int K)\n{\n  L_.resize(K, K);\n\n  QMaxwell y_quad(1.0, K);\n  QHermiteW qherm(1.0, K);\n\n  Eigen::VectorXd y(K);\n  for (int i = 0; i < K; ++i) {\n    y(i) = -y_quad.pts(i);\n  }\n\n  lagrange_poly_simple lagpoly(qherm.pts().data(), qherm.pts().size());\n\n  for (int i2 = 0; i2 < K; ++i2) {\n    for (int j = 0; j < K; ++j) {\n      double val = 0;\n      for (int q = 0; q < K; ++q) {\n        val += lagpoly.eval(j, y(q)) * lagpoly.eval(i2, y(q)) * y_quad.wts(q);\n      }\n      L_(i2, j) = val;\n    }\n  }\n}\n\nvoid\nLSQ_BC_Base::apply(Eigen::DenseBase& dst, const Eigen::DenseBase& src) const\n{\n  dst = L_ * src;\n}\n\n}  // impl_lsq\n}  // boltzmann\n", "meta": {"hexsha": "0a7f942a6cc9703a91ffa433bb56ffe420455be3", "size": 1008, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix/bc/impl/lsq/lsq_bc_base.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrix/bc/impl/lsq/lsq_bc_base.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix/bc/impl/lsq/lsq_bc_base.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.0, "max_line_length": 97, "alphanum_fraction": 0.6011904762, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517044, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6109096685860336}}
{"text": "#define BOOST_TEST_NO_LIB\n#include <boost/test/auto_unit_test.hpp>\n\n#include \"coconut/pulp/math/Plane.hpp\"\n\nusing namespace coconut;\nusing namespace coconut::pulp;\nusing namespace coconut::pulp::math;\n\nnamespace /* anonymous */ {\n\nBOOST_AUTO_TEST_SUITE(PulpTestSuite);\nBOOST_AUTO_TEST_SUITE(PulpMathTestSuite);\nBOOST_AUTO_TEST_SUITE(PulpMathPlaneTestSuite);\n\nBOOST_AUTO_TEST_CASE(PlaneIsConstructibleFromPointAndNormal) {\n\tconst auto p = Plane({ 0.0f, 1.0f, 0.0f }, { 2.0f, 2.0f, 2.0f });\n\n\tBOOST_CHECK_EQUAL(p.normal(), Vec3(0.0f, 1.0f, 0.0f).normalised());\n\tBOOST_CHECK_CLOSE(p.signedDistanceToOrigin(), -2.0f, 0.01f);\n}\n\nBOOST_AUTO_TEST_CASE(PlaneIsConstructibleFromNormalAndDistanceFromOrigin) {\n\tconst auto p = Plane({ 2.0f, 1.0f, 3.0f }, 3.0f);\n\n\tBOOST_CHECK_EQUAL(p.normal(), Vec3(2.0f, 1.0f, 3.0f).normalised());\n\tBOOST_CHECK_CLOSE(p.signedDistanceToOrigin(), 3.0f, 0.01f);\n}\n\nBOOST_AUTO_TEST_CASE(CanTestPointPositionWithRespectToPlane) {\n\tconst auto p = Plane({ 1.0f, 1.0f, 0.1f }, { -1.0f, -1.0f, 1.0f });\n\n\tBOOST_CHECK_CLOSE_FRACTION(p.signedDistanceToPoint({ 1.0f, 0.0f, 1.0f }), 2.116036f, 0.01f);\n\tBOOST_CHECK_CLOSE(p.signedDistanceToPoint({ -1.0f, -1.0f, 1.0f }), 0.0f, 0.01f);\n\tBOOST_CHECK_CLOSE(p.signedDistanceToPoint({ -2.0f, -0.5f, 3.0f }), -0.211603f, 0.01f);\n}\n\nBOOST_AUTO_TEST_SUITE_END(/* PulpMathPlaneTestSuite */);\nBOOST_AUTO_TEST_SUITE_END(/* PulpMathTestSuite */);\nBOOST_AUTO_TEST_SUITE_END(/* PulpTestSuite */);\n\n} // anonymous namespace\n", "meta": {"hexsha": "ab3ba11f058d71b2b2d3e58fde143be0eff6356d", "size": 1468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "coconut-pulp-math/src/test/c++/coconut/pulp/math/Plane.cpp", "max_stars_repo_name": "mikosz/coconut", "max_stars_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T12:01:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T12:01:54.000Z", "max_issues_repo_path": "coconut-pulp-math/src/test/c++/coconut/pulp/math/Plane.cpp", "max_issues_repo_name": "mikosz/coconut", "max_issues_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coconut-pulp-math/src/test/c++/coconut/pulp/math/Plane.cpp", "max_forks_repo_name": "mikosz/coconut", "max_forks_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1395348837, "max_line_length": 93, "alphanum_fraction": 0.7431880109, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6109096579470673}}
{"text": "#include \"Align.h\"\n\n#include <iostream>\n\n#include <Eigen/SVD>\n#include <cmath>\n\n\nint flag = 0;\nusing namespace Eigen;\nusing namespace std;\n\n\n\nEigen::Matrix3d exp(Eigen::Matrix3d x) {\n\t//return x.exp();\n\tdouble theta = sqrt(x(0, 1)*x(0, 1) + x(0, 2)*x(0, 2) + x(1, 2)*x(1, 2));\n\tif (abs(theta) == 0) return Eigen::Matrix3d::Identity();\n\tx /= theta;\n\treturn Eigen::Matrix3d::Identity() +\n\t\tx * sin(theta) +\n\t\tx * x * (1 - cos(theta));\n}\n\n\n\nEigen::Matrix3d log(Eigen::Matrix3d x) {\n\t//return x.log();\n\tdouble theta = (x.trace() - 1) / 2;\n\ttheta = acos(max(-1.0, min(1.0, theta)));\n\tif (abs(theta) == 0) return Eigen::Matrix3d::Zero();\n\treturn (theta / (2 * sin(theta))) * (x - x.transpose());\n}\n\ndouble polarDec(const Eigen::Matrix3d &a, Eigen::Matrix3d &r, Eigen::Matrix3d &s) {\n\tJacobiSVD<Eigen::MatrixXd> svd(a, ComputeThinU | ComputeThinV);\n\tr = svd.matrixU() * svd.matrixV().transpose();\n\ts = svd.matrixV() * svd.singularValues().asDiagonal() * svd.matrixV().transpose();\n\n\tif (r.determinant() < 0) {\n\t\tVector3d sv = svd.singularValues();\n\t\tint minsv = 0;\n\t\tr = svd.matrixU();\n\t\tif (sv(1) < sv(minsv)) minsv = 1;\n\t\tif (sv(2) < sv(minsv)) minsv = 2;\n\t\tif (sv(minsv) < -Eps) {\n\t\t\tcerr << \"polar dec Error, min singular values <= 0 :\" << endl;\n\t\t\tcerr << a << endl;\n\t\t}\n\t\t//cout << \"Min SV \" << sv(minsv) << \" \" << minsv << endl;\n\t\tr.col(minsv) *= -1;\n\t\tsv(minsv) *= -1;\n\t\t//cout << \"R :\\n\" << r << endl;\n\t\tr = r * svd.matrixV().transpose();\n\t\ts = svd.matrixV() * sv.asDiagonal() * svd.matrixV().transpose();\n\t\treturn sv.sum();\n\t}\n\treturn svd.singularValues().sum();\n}\n\n\n\nAffineAlign::AffineAlign(std::vector<Eigen::Vector3d> &v) : p(v), AtA(Matrix3d::Zero()) {\n\t//if (flag) fout << p.size() << endl;\n\tfor (int i = 0; i < p.size(); i++) {\n\t\t//assert(p[i] == p[i]);\n\t\tAtA += p[i] * p[i].transpose();\n\t\t//if (flag) fout << p[i] << endl << endl;\n\t}\n\tif (flag) {\n\t\t//fout << \"AtA\" << endl;\n\t\t//fout << AtA << endl;\n\t\t//fout << AtA.determinant() << endl;\n\t}\n\tAtA = AtA.inverse().eval();\n}\n\nMatrix3d AffineAlign::calc(const std::vector<Vector3d> &v) {\n\tif (v.size() != p.size()) {\n\t\tcout << \"!!Error v.size() != p.size()\" << endl;\n\t\t//fout << \"!!Error v.size() != p.size()\" << endl;\n\t}\n\tVector3d vx(Vector3d::Zero()), vy(Vector3d::Zero()), vz(Vector3d::Zero());\n\tfor (int i = 0; i < p.size(); i++) {\n\t\tvx += p[i] * v[i](0);\n\t\tvy += p[i] * v[i](1);\n\t\tvz += p[i] * v[i](2);\n\t}\n\t//assert(vx == vx);\n\tvx = AtA * vx;\n\tvy = AtA * vy;\n\tvz = AtA * vz;\n\tMatrix3d res;\n\tres << vx, vy, vz;\n\treturn res.transpose();\n}\n\ndouble AffineAlign::residualwithoutnormal(Eigen::Matrix3d m, std::vector<Eigen::Vector3d> v) {\n\tdouble rs = 0;\n\tfor (int i = 0; i < v.size() - 1; i++)\n\t\trs += (v[i] - m*p[i]).squaredNorm();\n\treturn rs;\n}\n\n\nOpenMesh::Vec3d EtoO(const Eigen::Vector3d &v) {\n\treturn OpenMesh::Vec3d(v(0), v(1), v(2));\n}\n\nEigen::Vector3d OtoE(const OpenMesh::Vec3d &v) {\n\treturn Eigen::Vector3d(v[0], v[1], v[2]);\n}\n\nvoid Rot::ToLogR()\n{\n\tdouble the = circlek * 2 * M_PI + theta;\n\t//the = theta;\n\tlogr = Eigen::Matrix3d::Zero();\n\tlogr(0, 1) = -axis(2);\n\tlogr(0, 2) = axis(1);\n\tlogr(1, 2) = -axis(0);\n\tEigen::Matrix3d logr1 = logr.transpose();\n\tlogr = the*(logr - logr1);\n}\n\ndouble Rot::ToAngle()\n{\n\tdouble the = circlek * 2 * M_PI + theta;\n\treturn the;\n}\n\n\nRot logrot(Eigen::Matrix3d jrotation)\n{\n\tRot jrot;\n\tdouble theta = (jrotation.trace() - 1) / 2;\n\ttheta = acos(max(-1.0, min(1.0, theta)));\n\tif (abs(theta) <= 1e-6)\n\t{\n\t\tjrot.circlek = 0;\n\t\tjrot.theta = 0;\n\t\tjrot.axis = Eigen::Vector3d::Zero();\n\t}\n\telse\n\t{\n\t\tjrot.theta = theta;\n\t\tEigen::Matrix3d tmp = (1 / (2 * sin(theta))) * (jrotation - jrotation.transpose());\n\t\tEigen::Vector3d jaxis;\n\t\tjaxis(0) = tmp(2, 1);\n\t\tjaxis(1) = tmp(0, 2);\n\t\tjaxis(2) = tmp(1, 0);\n\t\tjrot.axis = jaxis / jaxis.norm();\n\t}\n\tjrot.ToLogR();\n\treturn jrot;\n}\n\nvoid logrot(Rot & jrot ,Eigen::Matrix3d & jrotation)\n{\n\tdouble theta = (jrotation.trace() - 1) / 2;\n\ttheta = acos(max(-1.0, min(1.0, theta)));\n\tif (abs(theta) <= 1e-6)\n\t{\n\t\tjrot.circlek = 0;\n\t\tjrot.theta = 0;\n\t\tjrot.axis = Eigen::Vector3d::Zero();\n\t}\n\telse\n\t{\n\t\tjrot.theta = theta;\n\t\tEigen::Matrix3d tmp = (1 / (2 * sin(theta))) * (jrotation - jrotation.transpose());\n\t\tEigen::Vector3d jaxis;\n\t\tjaxis(0) = tmp(2, 1);\n\t\tjaxis(1) = tmp(0, 2);\n\t\tjaxis(2) = tmp(1, 0);\n\t\tjrot.axis = jaxis / jaxis.norm();\n\t}\n\t//jrot.ToLogR();\t\n}\n\n\nRot logrot(Eigen::Matrix3d jrotation, Rot irot)\n{\n\n\tRot jrot;\n\tdouble theta = (jrotation.trace() - 1) / 2;\n\ttheta = acos(max(-1.0, min(1.0, theta)));\n\tif (abs(theta) <=1e-6)\n\t//if (abs(sin(theta))<0.0001||abs(theta) <= 0.15)// cylinder \u05e8\ufffd\ufffd\n\t{\n\t\tjrot = irot;\n\t\tjrot.theta = 0;\n\t}\n\telse\n\t{\n\t\tEigen::Vector3d jaxis;\n\t\tEigen::Matrix3d tmp = Eigen::Matrix3d::Zero();\n\t\tif (abs(theta - M_PI) <= 1e-6)\n\t\t{\n\t\t\tjaxis = irot.axis;\n\t\t\t//jrot.theta = M_PI;\n\t\t\ttmp(0, 1) = -jaxis(2);\n\t\t\ttmp(0, 2) = jaxis(1);\n\t\t\ttmp(1, 2) = -jaxis(0);\n\t\t\tEigen::Matrix3d tmp2 = tmp.transpose();\n\t\t\ttmp = (tmp - tmp2);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttmp = (1 / (2 * sin(theta))) * (jrotation - jrotation.transpose());\n\n\t\t\tjaxis(0) = tmp(2, 1);\n\t\t\tjaxis(1) = tmp(0, 2);\n\t\t\tjaxis(2) = tmp(1, 0);\n\t\t}\n\n\t\t//debug\n\t\tEigen::Matrix3d logr = Eigen::Matrix3d::Zero();\n\t\tlogr(0, 1) = -jaxis(2);\n\t\tlogr(0, 2) = jaxis(1);\n\t\tlogr(1, 2) = -jaxis(0);\n\t\tEigen::Matrix3d tmp1 = logr.transpose();\n\t\tlogr = (logr - tmp1);\n\t\tdouble _norm1 = (tmp - logr).squaredNorm();\n\t\tif (_norm1 >= 0.0001)\n\t\t{\n\t\t\t//cout<<\"error\"<<endl;\n\t\t}\n\t\ttmp = theta*tmp;\n\t\tdouble _norm2 = (tmp - log(jrotation)).squaredNorm();\n\t\tif (_norm2 > 0.00001)\n\t\t{\n\t\t\tlog(jrotation);\n\t\t}\n\t\tdouble _norm = jaxis.norm();\n\t\tif (_norm < 1)\n\t\t{\n\t\t\t//cout<<_norm<<endl;\n\t\t}\n\t\tdouble _sign = jaxis.dot(irot.axis);\n\t\tif (_sign < 0)\n\t\t{\n\t\t\tjaxis = -jaxis;\n\t\t\ttheta = 2 * PI - theta;\n\t\t}\n\t\tjrot.axis = jaxis / jaxis.norm();//\n\t\t//jrot.axis = jaxis;\n\t\tjrot.theta = theta;\n\t\tjrot.circlek = irot.circlek;\n\t}\n\n\n\tif (abs(theta - irot.theta) > M_PI)\n\t{\n\t\tif (irot.theta < M_PI)\n\t\t{\n\t\t\t//[0,2*PI)\n\t\t\tjrot.circlek = jrot.circlek - 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (jrot.circlek >= 0)\n\t\t\t{\n\t\t\t\t// cout<<\"test\"<<endl;\n\t\t\t}\n\t\t\tjrot.circlek = jrot.circlek + 1;\n\t\t}\n\t}\n\tjrot.ToLogR();\n\tEigen::Matrix3d tmp = log(jrotation);\n\tdouble _norm1 = (jrot.logr - tmp).squaredNorm();\n\tif (_norm1 >= 0.0001)\n\t{\n\t\t//cout<<\"error\"<<endl;\n\t}\n\n\treturn jrot;\n}", "meta": {"hexsha": "7ce9b9adcb07f17f90bf26dfbb5932fb38d4e9db", "size": 6209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ACAP_linux/src/Align.cpp", "max_stars_repo_name": "shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer", "max_stars_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 216.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T11:53:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:41:35.000Z", "max_issues_repo_path": "ACAP_linux/src/Align.cpp", "max_issues_repo_name": "gaolinorange/Automatic-Unpaired-Shape-Deformation-Transfer", "max_issues_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-23T08:29:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T06:45:34.000Z", "max_forks_repo_path": "ACAP_linux/src/Align.cpp", "max_forks_repo_name": "shubhMaheshwari/Automatic-Unpaired-Shape-Deformation-Transfer", "max_forks_repo_head_hexsha": "8c9afe017769f9554706bcd267b6861c4c144999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2018-09-13T08:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T00:33:54.000Z", "avg_line_length": 22.3345323741, "max_line_length": 94, "alphanum_fraction": 0.5651473667, "num_tokens": 2425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.85391273808085, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6109096527659267}}
{"text": "// Portfolio VaR through MC simulation\n// from test_ptf_mc_var.cpp\n\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"CVaR.h\"\n\n#include \"compute_returns_eigen.h\"\n#include \"compute_var.h\"\n#include \"path.h\"\n#include \"mc_engine.h\"\n#include \"rng.h\"\n#include \"pca.h\"\n#include \"portfolio.h\"\n#include \"ptf_var.h\"\n\n#include <boost/math/special_functions/erf.hpp>\nusing boost::math::erfc_inv;\n\nnamespace RiskJS {\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\ndouble CVaRHistorical(priceData rawPrices, weightData weights, double alphatest) {\n    // Remove lines with missing values\n    size_t n(rawPrices.size() - 1);\n    size_t m(rawPrices[0].size() - 1);\n\n    Mat _prices;\n    _prices.resize(m,Vec(n));\n\n    for(size_t i = 1;i < n+1;++i){\n        for(size_t j = 1;j < rawPrices[i].size();++j){\n            string tmp = rawPrices[i][j];\n            if(tmp.empty()){\n                _prices[j-1][i-1] = 99999.;\n            }\n            else{\n                _prices[j-1][i-1] = stod(tmp);\n            }\n        }\n    }\n\n    vector<string> indexNames(rawPrices[0].size() - 1);\n\n    for(size_t i = 1;i < rawPrices[0].size();++i){\n        indexNames[i-1] = rawPrices[0][i];\n    }\n\n\t\t// Remove missing values to compute trailling returns\n    Mat prices;\n    prices.resize(m,Vec(0));\n\n    bool goodrow = true;\n    for(size_t j = 0;j < _prices[0].size();++j){\n        for(size_t i = 0;i < _prices.size();++i){\n            if((_prices[i][j] == 99999) || (_prices[i][j] == 0))\n                goodrow = false;\n        }\n        if (goodrow)\n            for(size_t i = 0;i < _prices.size();++i){\n                prices[i].push_back(_prices[i][j]);\n            }\n            goodrow = true;\n        }\n    unsigned int windowsize = prices[0].size()-2;\n    std::shared_ptr<ComputeReturn> cr(new ComputeReturn(prices,1,windowsize,true));\n\n    // create portfolio\n  \tPtf _ptf;\n  \tfor(size_t i = 0;i < m;++i){\n        shared_ptr<Instrument> instrument(new DeltaOne());\n        auto p = std::make_pair(i,instrument);\n\t\t    _ptf.push_back(p);\n    }\n\t  shared_ptr<Portfolio> ptf(new Portfolio(_ptf, weights, cr, false, 1.e+07));\n\n    HistoricalVaR model;\n\n    // CVaRhistorical\n    model.setAlpha(1.0-alphatest);\n    double CVaRHistorical = model(0,ptf->getReturns());\n\n    return CVaRHistorical;\n}\n\n}\n", "meta": {"hexsha": "4008b720e561c4b88dc2c0374e1fb6614680bce2", "size": 2299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CVaRHistorical.cpp", "max_stars_repo_name": "vigor-ish/riskjs", "max_stars_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CVaRHistorical.cpp", "max_issues_repo_name": "vigor-ish/riskjs", "max_issues_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-02T02:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T02:33:13.000Z", "max_forks_repo_path": "src/CVaRHistorical.cpp", "max_forks_repo_name": "vigor-ish/riskjs", "max_forks_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-30T18:36:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-30T18:36:40.000Z", "avg_line_length": 24.4574468085, "max_line_length": 83, "alphanum_fraction": 0.5854719443, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6108470747176449}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\n// for linear algebra.\n//\n// Copyright (C) 2012 Desire Nuentsa <desire.nuentsa_wakam@inria.fr>\n// Copyright (C) 2012 Gael Guennebaud <gael.guennebaud@inria.fr>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n\n\n\n#include \"main.h\"\n#include <Eigen/LevenbergMarquardt>\n\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <typename Scalar>\nstruct sparseGaussianTest : SparseFunctor<Scalar, int>\n{\n  typedef Matrix<Scalar,Dynamic,1> VectorType;\n  typedef SparseFunctor<Scalar,int> Base;\n  typedef typename Base::JacobianType JacobianType;\n  sparseGaussianTest(int inputs, int values) : SparseFunctor<Scalar,int>(inputs,values)\n  { }\n  \n  VectorType model(const VectorType& uv, VectorType& x)\n  {\n    VectorType y; //Change this to use expression template\n    int m = Base::values(); \n    int n = Base::inputs();\n    eigen_assert(uv.size()%2 == 0);\n    eigen_assert(uv.size() == n);\n    eigen_assert(x.size() == m);\n    y.setZero(m);\n    int half = n/2;\n    VectorBlock<const VectorType> u(uv, 0, half);\n    VectorBlock<const VectorType> v(uv, half, half);\n    Scalar coeff;\n    for (int j = 0; j < m; j++)\n    {\n      for (int i = 0; i < half; i++) \n      {\n        coeff = (x(j)-i)/v(i);\n        coeff *= coeff;\n        if (coeff < 1. && coeff > 0.)\n          y(j) += u(i)*std::pow((1-coeff), 2);\n      }\n    }\n    return y;\n  }\n  void initPoints(VectorType& uv_ref, VectorType& x)\n  {\n    m_x = x;\n    m_y = this->model(uv_ref,x);\n  }\n  int operator()(const VectorType& uv, VectorType& fvec)\n  {\n    int m = Base::values(); \n    int n = Base::inputs();\n    eigen_assert(uv.size()%2 == 0);\n    eigen_assert(uv.size() == n);\n    int half = n/2;\n    VectorBlock<const VectorType> u(uv, 0, half);\n    VectorBlock<const VectorType> v(uv, half, half);\n    fvec = m_y;\n    Scalar coeff;\n    for (int j = 0; j < m; j++)\n    {\n      for (int i = 0; i < half; i++)\n      {\n        coeff = (m_x(j)-i)/v(i);\n        coeff *= coeff;\n        if (coeff < 1. && coeff > 0.)\n          fvec(j) -= u(i)*std::pow((1-coeff), 2);\n      }\n    }\n    return 0;\n  }\n  \n  int df(const VectorType& uv, JacobianType& fjac)\n  {\n    int m = Base::values(); \n    int n = Base::inputs();\n    eigen_assert(n == uv.size());\n    eigen_assert(fjac.rows() == m);\n    eigen_assert(fjac.cols() == n);\n    int half = n/2;\n    VectorBlock<const VectorType> u(uv, 0, half);\n    VectorBlock<const VectorType> v(uv, half, half);\n    Scalar coeff;\n    \n    //Derivatives with respect to u\n    for (int col = 0; col < half; col++)\n    {\n      for (int row = 0; row < m; row++)\n      {\n        coeff = (m_x(row)-col)/v(col);\n          coeff = coeff*coeff;\n        if(coeff < 1. && coeff > 0.)\n        {\n          fjac.coeffRef(row,col) = -(1-coeff)*(1-coeff);\n        }\n      }\n    }\n    //Derivatives with respect to v\n    for (int col = 0; col < half; col++)\n    {\n      for (int row = 0; row < m; row++)\n      {\n        coeff = (m_x(row)-col)/v(col);\n        coeff = coeff*coeff;\n        if(coeff < 1. && coeff > 0.)\n        {\n          fjac.coeffRef(row,col+half) = -4 * (u(col)/v(col))*coeff*(1-coeff);\n        }\n      }\n    }\n    return 0;\n  }\n  \n  VectorType m_x, m_y; //Data points\n};\n\n\ntemplate<typename T>\nvoid test_sparseLM_T()\n{\n  typedef Matrix<T,Dynamic,1> VectorType;\n  \n  int inputs = 10;\n  int values = 2000;\n  sparseGaussianTest<T> sparse_gaussian(inputs, values);\n  VectorType uv(inputs),uv_ref(inputs);\n  VectorType x(values);\n  // Generate the reference solution \n  uv_ref << -2, 1, 4 ,8, 6, 1.8, 1.2, 1.1, 1.9 , 3;\n  //Generate the reference data points\n  x.setRandom();\n  x = 10*x;\n  x.array() += 10;\n  sparse_gaussian.initPoints(uv_ref, x);\n  \n  \n  // Generate the initial parameters \n  VectorBlock<VectorType> u(uv, 0, inputs/2); \n  VectorBlock<VectorType> v(uv, inputs/2, inputs/2);\n  v.setOnes();\n  //Generate u or Solve for u from v\n  u.setOnes();\n  \n  // Solve the optimization problem\n  LevenbergMarquardt<sparseGaussianTest<T> > lm(sparse_gaussian);\n  int info;\n//   info = lm.minimize(uv);\n  \n  VERIFY_IS_EQUAL(info,1);\n    // Do a step by step solution and save the residual \n  int maxiter = 200;\n  int iter = 0;\n  MatrixXd Err(values, maxiter);\n  MatrixXd Mod(values, maxiter);\n  LevenbergMarquardtSpace::Status status; \n  status = lm.minimizeInit(uv);\n  if (status==LevenbergMarquardtSpace::ImproperInputParameters)\n      return ;\n\n}\nvoid test_sparseLM()\n{\n  CALL_SUBTEST_1(test_sparseLM_T<double>());\n  \n  // CALL_SUBTEST_2(test_sparseLM_T<std::complex<double>());\n}\n", "meta": {"hexsha": "43318ac01b9d2b62ac161522ae60262fc1ee677a", "size": 4677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "External/eigen-3.3.7/test/sparseLM.cpp", "max_stars_repo_name": "RokKos/eol-cloth", "max_stars_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "External/eigen-3.3.7/test/sparseLM.cpp", "max_issues_repo_name": "RokKos/eol-cloth", "max_issues_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "External/eigen-3.3.7/test/sparseLM.cpp", "max_forks_repo_name": "RokKos/eol-cloth", "max_forks_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4237288136, "max_line_length": 87, "alphanum_fraction": 0.5982467394, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6108470701881605}}
{"text": "/* -------------------------------------------------------------------------\n *   A Modular Optimization framework for Localization and mApping  (MOLA)\n * Copyright (C) 2018-2021 University of Almeria\n * See LICENSE for license information.\n * ------------------------------------------------------------------------- */\n\n/**\n * @file   test-mp2p_error_terms_jacobians.cpp\n * @brief  Unit tests for Jacobians of error terms\n * @author Francisco Jose Ma\u00f1as Alvarez, Jose Luis Blanco Claraco\n * @date   Apr 10, 2020\n */\n\n#include <mp2p_icp/errorTerms.h>\n#include <mrpt/core/exceptions.h>\n#include <mrpt/math/num_jacobian.h>  // finite difference method\n#include <mrpt/poses/CPose3D.h>\n#include <mrpt/poses/Lie/SE.h>\n#include <mrpt/random.h>\n#include <Eigen/Dense>\n#include <iostream>  // cerr\n\nusing namespace mrpt;  // for the \"_deg\" suffix\nusing namespace mrpt::math;\nusing namespace mrpt::poses;\n\nauto& rnd = mrpt::random::getRandomGenerator();\n\nstatic double normald(const double sigma)\n{\n    return rnd.drawGaussian1D_normalized() * sigma;\n}\nstatic float normalf(const float sigma)\n{\n    return rnd.drawGaussian1D_normalized() * sigma;\n}\n\n// ===========================================================================\n//  Test: error_point2point\n// ===========================================================================\n\nvoid test_Jacob_error_point2point()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        normald(10), normald(10), normald(10),\n        // Yaw pitch roll\n        rnd.drawUniform(-M_PI, M_PI), rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5),\n        rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5));\n\n    mrpt::tfest::TMatchingPair pair;\n\n    pair.this_x  = normalf(20);\n    pair.this_y  = normalf(20);\n    pair.this_z  = normalf(20);\n    pair.other_x = normalf(10);\n    pair.other_y = normalf(10);\n    pair.other_z = normalf(10);\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 3, 12> J1;\n    // const mrpt::math::CVectorFixed<double, 3> error = // (Ignored here)\n    mp2p_icp::error_point2point(pair, p, J1);\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 3, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-6);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<3>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<3>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_point2point(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n\n    if ((numJacob.asEigen() - jacob.asEigen()).array().abs().maxCoeff() > 1e-5)\n    {\n        std::cerr << \"numJacob:\\n\"\n                  << numJacob.asEigen() << \"\\njacob:\\n\"\n                  << jacob.asEigen() << \"\\nDiff:\\n\"\n                  << (numJacob - jacob) << \"\\nJ1:\\n\"\n                  << J1.asEigen() << \"\\n\";\n        THROW_EXCEPTION(\"Jacobian mismatch, see above.\");\n    }\n}\n\n// ===========================================================================\n//  Test: error_point2line\n// ===========================================================================\n\nvoid test_Jacob_error_point2line()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        normald(10), normald(10), normald(10),\n        // Yaw pitch roll\n        rnd.drawUniform(-M_PI, M_PI), rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5),\n        rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5));\n\n    mp2p_icp::point_line_pair_t pair;\n\n    pair.ln_this.pBase.x = normalf(20);\n    pair.ln_this.pBase.y = normalf(20);\n    pair.ln_this.pBase.z = normalf(20);\n    pair.ln_this.director[0] = normald(20);\n    pair.ln_this.director[1] = normald(20);\n    pair.ln_this.director[2] = normald(20);\n\n    pair.pt_other.x = normalf(10);\n    pair.pt_other.y = normalf(10);\n    pair.pt_other.z = normalf(10);\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 1, 12> J1;\n\n    mp2p_icp::error_point2line(pair, p, J1);\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 1, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-6);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<1>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<1>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_point2line(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n\n    if ((numJacob.asEigen() - jacob.asEigen()).array().abs().maxCoeff() > 1e-5)\n    {\n        std::cerr << \"numJacob:\\n\"\n                  << numJacob.asEigen() << \"\\njacob:\\n\"\n                  << jacob.asEigen() << \"\\nDiff:\\n\"\n                  << (numJacob - jacob) << \"\\nJ1:\\n\"\n                  << J1.asEigen() << \"\\n\";\n        THROW_EXCEPTION(\"Jacobian mismatch, see above.\");\n    }\n}\n\n// ===========================================================================\n//  Test: error_point2plane\n// ===========================================================================\n\nvoid test_Jacob_error_point2plane()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        normald(10), normald(10), normald(10),\n        // Yaw pitch roll\n        rnd.drawUniform(-M_PI, M_PI), rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5),\n        rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5));\n\n    mp2p_icp::point_plane_pair_t pair;\n\n    pair.pl_this.centroid.x = normalf(20);\n    pair.pl_this.centroid.y = normalf(20);\n    pair.pl_this.centroid.z = normalf(20);\n    pair.pl_this.plane.coefs[0] = normald(20);\n    pair.pl_this.plane.coefs[1] = normald(20);\n    pair.pl_this.plane.coefs[2] = normald(20);\n\n    pair.pt_other.x = normalf(10);\n    pair.pt_other.y = normalf(10);\n    pair.pt_other.z = normalf(10);\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 1, 12> J1;\n\n    mp2p_icp::error_point2plane(pair, p, J1);\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 1, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-6);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<1>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<1>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_point2plane(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n\n    if ((numJacob.asEigen() - jacob.asEigen()).array().abs().maxCoeff() > 1e-5)\n    {\n        std::cerr << \"numJacob:\\n\"\n                  << numJacob.asEigen() << \"\\njacob:\\n\"\n                  << jacob.asEigen() << \"\\nDiff:\\n\"\n                  << (numJacob - jacob) << \"\\nJ1:\\n\"\n                  << J1.asEigen() << \"\\n\";\n        THROW_EXCEPTION(\"Jacobian mismatch, see above.\");\n    }\n}\n\n// ===========================================================================\n//  Test: error_line2line\n// ===========================================================================\n\nvoid test_Jacob_error_line2line()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        normald(10), normald(10), normald(10),\n        // Yaw pitch roll\n        rnd.drawUniform(-M_PI, M_PI), rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5),\n        rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5));\n\n    mp2p_icp::matched_line_t pair;\n\n    pair.ln_this.pBase.x = normalf(10);\n    pair.ln_this.pBase.y = normalf(10);\n    pair.ln_this.pBase.z = normalf(10);\n    pair.ln_this.director[0] = normald(10);\n    pair.ln_this.director[1] = normald(10);\n    pair.ln_this.director[2] = normald(10);\n\n    pair.ln_other.pBase.x = normalf(10);\n    pair.ln_other.pBase.y = normalf(10);\n    pair.ln_other.pBase.z = normalf(10);\n    pair.ln_other.director[0] = normald(10);\n    pair.ln_other.director[1] = normald(10);\n    pair.ln_other.director[2] = normald(10);\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 4, 12> J1;\n\n    mp2p_icp::error_line2line(pair, p, J1);\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 4, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-6);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<4>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<4>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_line2line(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n\n    if ((numJacob.asEigen() - jacob.asEigen()).array().abs().maxCoeff() > 1e-5)\n    {\n        std::cerr << \"numJacob:\\n\"\n                  << numJacob.asEigen() << \"\\njacob:\\n\"\n                  << jacob.asEigen() << \"\\nDiff:\\n\"\n                  << (numJacob - jacob) << \"\\nJ1:\\n\"\n                  << J1.asEigen() << \"\\n\";\n        THROW_EXCEPTION(\"Jacobian mismatch, see above.\");\n    }\n}\n\n// ===========================================================================\n//  Test: error_plane2plane\n// ===========================================================================\n\nvoid test_Jacob_error_plane2plane()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        normald(10), normald(10), normald(10),\n        // Yaw pitch roll\n        rnd.drawUniform(-M_PI, M_PI), rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5),\n        rnd.drawUniform(-M_PI * 0.5, M_PI * 0.5));\n\n    mp2p_icp::matched_plane_t pair;\n\n    pair.p_this.centroid.x = normalf(20);\n    pair.p_this.centroid.y = normalf(20);\n    pair.p_this.centroid.z = normalf(20);\n    pair.p_this.plane.coefs[0] = normald(20);\n    pair.p_this.plane.coefs[1] = normald(20);\n    pair.p_this.plane.coefs[2] = normald(20);\n\n    pair.p_other.centroid.x = normalf(10);\n    pair.p_other.centroid.y = normalf(10);\n    pair.p_other.centroid.z = normalf(10);\n    pair.p_other.plane.coefs[0] = normald(10);\n    pair.p_other.plane.coefs[1] = normald(10);\n    pair.p_other.plane.coefs[2] = normald(10);\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 3, 12> J1;\n\n    mp2p_icp::error_plane2plane(pair, p, J1);\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 3, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-6);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<3>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<3>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_plane2plane(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n\n    if ((numJacob.asEigen() - jacob.asEigen()).array().abs().maxCoeff() > 1e-5)\n    {\n        std::cerr << \"numJacob:\\n\"\n                  << numJacob.asEigen() << \"\\njacob:\\n\"\n                  << jacob.asEigen() << \"\\nDiff:\\n\"\n                  << (numJacob - jacob) << \"\\nJ1:\\n\"\n                  << J1.asEigen() << \"\\n\";\n        THROW_EXCEPTION(\"Jacobian mismatch, see above.\");\n    }\n}\n\n// ===========================================================================\n//  Test: error_line2line\n// ===========================================================================\n\nvoid test_error_line2line()\n{\n    const CPose3D p = CPose3D(\n        // x y z\n        1, 0.5, 0.1,\n        // Yaw pitch roll\n        0, 0, 0);\n\n    mp2p_icp::matched_line_t pair;\n\n    pair.ln_this.pBase.x = 0;\n    pair.ln_this.pBase.y = 1;\n    pair.ln_this.pBase.z = -4;\n    pair.ln_this.director[0] =  0.4364;\n    pair.ln_this.director[1] =  0.8729;\n    pair.ln_this.director[2] = -0.2182;\n\n    pair.ln_other.pBase.x = 2;\n    pair.ln_other.pBase.y = 1;\n    pair.ln_other.pBase.z = -0.5;\n    pair.ln_other.director[0] = 0.2357;\n    pair.ln_other.director[1] = 0.2357;\n    pair.ln_other.director[2] = 0.9428;\n\n    // Implemented values:\n    mrpt::math::CMatrixFixed<double, 4, 12> J1;\n\n    mrpt::math::CVectorFixedDouble<4> error = mp2p_icp::error_line2line(pair, p, J1);\n\n    mrpt::math::CVectorFixedDouble<4> ref_error;\n    ref_error[0] = 0.0517;\n    ref_error[1] = 0.2007;\n    ref_error[2] = 0.6372;\n    ref_error[3] = -1.1610;\n\n    std::cout << \"\\nResultado: \\n\"\n              << error <<  \"\\nRecta A:\\n\"\n              <<  pair.ln_this << \"\\nRecta B:\\n\"\n              << pair.ln_other << \"\\n\";\n\n    // (12x6 Jacobian)\n    const auto dDexpe_de = mrpt::poses::Lie::SE<3>::jacob_dDexpe_de(p);\n\n    const mrpt::math::CMatrixFixed<double, 4, 6> jacob(J1 * dDexpe_de);\n\n    // Numerical Jacobian:\n    CMatrixDouble numJacob;\n    {\n        CVectorFixedDouble<6> x_mean;\n        x_mean.setZero();\n\n        CVectorFixedDouble<6> x_incrs;\n        x_incrs.fill(1e-6);\n        mrpt::math::estimateJacobian(\n            x_mean,\n            /* Error function to evaluate */\n            std::function<void(\n                const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                CVectorFixedDouble<4>& err)>(\n                /* Lambda, capturing the pair data */\n                [pair](\n                    const CVectorFixedDouble<6>& eps, const CPose3D& D,\n                    CVectorFixedDouble<4>& err) {\n                    // SE(3) pose increment on the manifold:\n                    const CPose3D incr         = Lie::SE<3>::exp(eps);\n                    const CPose3D D_expEpsilon = D + incr;\n                    err = mp2p_icp::error_line2line(pair, D_expEpsilon);\n                }),\n            x_incrs, p, numJacob);\n    }\n        std::cout << \"numJacob:\\n\"\n                  << numJacob.asEigen() << \"\\njacob:\\n\"\n                  << jacob.asEigen() << \"\\nDiff:\\n\"\n                  << (numJacob - jacob) << \"\\nJ1:\\n\"\n                  << J1.asEigen() << \"\\ndDexp_de:\\n\"\n                  << dDexpe_de.asEigen() << \"\\n\";\n\n}\n\nint main([[maybe_unused]] int argc, [[maybe_unused]] char** argv)\n{\n    try\n    {\n        rnd.randomize(1234);  // for reproducible tests\n\n        test_Jacob_error_point2point();\n        test_Jacob_error_point2line();\n        test_Jacob_error_point2plane();\n        // test_Jacob_error_line2line();\n        test_Jacob_error_plane2plane();\n        test_error_line2line();\n    }\n    catch (std::exception& e)\n    {\n        std::cerr << mrpt::exception_to_str(e) << \"\\n\";\n        return 1;\n    }\n}\n", "meta": {"hexsha": "09de911e3528e6d9aecbd2cc724bb2cb4eb72e3c", "size": 17248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test-mp2p_error_terms_jacobians.cpp", "max_stars_repo_name": "mfkiwl/mp2p_icp", "max_stars_repo_head_hexsha": "1cdbf6c1cf8372a2d916271ebfcb344538100e28", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 82.0, "max_stars_repo_stars_event_min_datetime": "2019-06-09T15:33:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:04:09.000Z", "max_issues_repo_path": "tests/test-mp2p_error_terms_jacobians.cpp", "max_issues_repo_name": "mfkiwl/mp2p_icp", "max_issues_repo_head_hexsha": "1cdbf6c1cf8372a2d916271ebfcb344538100e28", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test-mp2p_error_terms_jacobians.cpp", "max_forks_repo_name": "mfkiwl/mp2p_icp", "max_forks_repo_head_hexsha": "1cdbf6c1cf8372a2d916271ebfcb344538100e28", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2019-06-19T10:05:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-28T08:37:34.000Z", "avg_line_length": 34.0197238659, "max_line_length": 85, "alphanum_fraction": 0.5214517625, "num_tokens": 4891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.610847069932253}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n\n// This file was modified by Oracle on 2016.\n// Modifications copyright (c) 2016, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ARITHMETIC_CROSS_PRODUCT_HPP\n#define BOOST_GEOMETRY_ARITHMETIC_CROSS_PRODUCT_HPP\n\n\n#include <cstddef>\n\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/size_t.hpp>\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <std::size_t Dimension>\nstruct cross_product\n{\n    // We define cross product only for 2d (see Wolfram) and 3d.\n    // In Math, it is also well-defined for 7-dimension.\n    // Generalisation of cross product to n-dimension is defined as\n    // wedge product but it is not direct analogue to binary cross product.\n    BOOST_MPL_ASSERT_MSG((false),\n                         NOT_IMPLEMENTED_FOR_THIS_DIMENSION,\n                         (mpl::size_t<Dimension>));\n};\n\ntemplate <>\nstruct cross_product<2>\n{\n    template <typename P1, typename P2, typename ResultP>\n    static inline void apply(P1 const& p1, P2 const& p2, ResultP& result)\n    {\n        assert_dimension<P1, 2>();\n        assert_dimension<P2, 2>();\n        assert_dimension<ResultP, 2>();\n\n        // For 2-dimensions, analog of the cross product U(x,y) and V(x,y) is\n        // Ux * Vy - Uy * Vx\n        // which is returned as 0-component (or X) of 2d vector, 1-component is undefined.\n        set<0>(result, get<0>(p1) * get<1>(p2) - get<1>(p1) * get<0>(p2));\n    }\n};\n\ntemplate <>\nstruct cross_product<3>\n{\n    template <typename P1, typename P2, typename ResultP>\n    static inline void apply(P1 const& p1, P2 const& p2, ResultP& result)\n    {\n        assert_dimension<P1, 3>();\n        assert_dimension<P2, 3>();\n        assert_dimension<ResultP, 3>();\n\n        set<0>(result, get<1>(p1) * get<2>(p2) - get<2>(p1) * get<1>(p2));\n        set<1>(result, get<2>(p1) * get<0>(p2) - get<0>(p1) * get<2>(p2));\n        set<2>(result, get<0>(p1) * get<1>(p2) - get<1>(p1) * get<0>(p2));\n    }\n};\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\n/*!\n\\brief Computes the cross product of two vectors.\n\\details All vectors should have the same dimension, 3 or 2.\n\\ingroup arithmetic\n\\param p1 first vector\n\\param p2 second vector\n\\return the cross product vector\n\n*/\ntemplate <typename ResultP, typename P1, typename P2>\ninline ResultP cross_product(P1 const& p1, P2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<ResultP>) );\n    BOOST_CONCEPT_ASSERT( (concepts::ConstPoint<P1>) );\n    BOOST_CONCEPT_ASSERT( (concepts::ConstPoint<P2>) );\n\n    ResultP result;\n    detail::cross_product<dimension<ResultP>::value>::apply(p1, p2, result);\n    return result;\n}\n\n/*!\n\\brief Computes the cross product of two vectors.\n\\details All vectors should have the same dimension, 3 or 2.\n\\ingroup arithmetic\n\\param p1 first vector\n\\param p2 second vector\n\\return the cross product vector\n\n\\qbk{[heading Examples]}\n\\qbk{[cross_product] [cross_product_output]}\n*/\ntemplate <typename P>\ninline P cross_product(P const& p1, P const& p2)\n{\n    BOOST_CONCEPT_ASSERT((concepts::Point<P>));\n    BOOST_CONCEPT_ASSERT((concepts::ConstPoint<P>));\n\n    P result;\n    detail::cross_product<dimension<P>::value>::apply(p1, p2, result);\n    return result;\n}\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ARITHMETIC_CROSS_PRODUCT_HPP\n", "meta": {"hexsha": "1df1147ef2aba71068b8566799e6cbac06be80a7", "size": 3949, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/geometry/arithmetic/cross_product.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": "3rdparty/boost_1_73_0/boost/geometry/arithmetic/cross_product.hpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": "3rdparty/boost_1_73_0/boost/geometry/arithmetic/cross_product.hpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T04:03:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T18:53:47.000Z", "avg_line_length": 29.6917293233, "max_line_length": 90, "alphanum_fraction": 0.6920739428, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143776, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6107874030150945}}
{"text": "/*\n * simulated_telemetry_server.cpp\n *\n *  Created on: Dec 5, 2018\n *      Author: ttw2xk\n */\n\n\n\n#include \"f1_datalogger/car_data/car_data.h\"\n#include <boost/program_options.hpp>\n#include <iostream>\n#include <boost/asio.hpp>\n#include <memory>\n#include <thread>\n#include <math.h> \n#include <boost/math/constants/constants.hpp>\nnamespace po = boost::program_options;\nvoid exit_with_help(po::options_description& desc)\n{\n        std::stringstream ss;\n        ss << \"F1 Simulated Telemetry Server. Command line arguments are as follows:\" << std::endl;\n        desc.print(ss);\n        std::printf(\"%s\", ss.str().c_str());\n        exit(0); // @suppress(\"Invalid arguments\")\n}\nint main(int argc, char** argv) {\n\tusing boost::asio::ip::udp;\n\tusing namespace deepf1;\n        unsigned int BUFLEN = 1289;\n        unsigned int UDP_BUFLEN = BUFLEN;\n        unsigned int sleep_time;\n        unsigned int packet_size = sizeof(UDPPacket);\n\n        std::string address, port;\n        po::options_description desc(\"Allowed Options\");\n\t\n        try{\n                desc.add_options()\n                (\"help,h\", \"Displays options and exits\")\n                (\"address,a\", po::value<std::string>(&address)->default_value(\"127.0.0.1\"), \"IPv4 Address to send data to\")\n                (\"port_number,p\", po::value<std::string>(&port)->default_value(\"20777\"), \"Port number to send data to\")\n                (\"sleep_time,s\", po::value<unsigned int>(&sleep_time)->default_value(100), \"Number of milliseconds to sleep between simulated packets\")\n                ;\n\t        po::variables_map vm;\n                po::store(po::parse_command_line(argc, argv, desc), vm);\n                po::notify(vm);\n                if (vm.find(\"help\") != vm.end()) {\n                        exit_with_help(desc);\n                }\n        }catch(boost::exception& e){\n                exit_with_help(desc);\n        }\n        boost::asio::io_service io_service;\n        udp::resolver resolver(io_service);\n        udp::resolver::query query(udp::v4(), address, port);\n        udp::endpoint receiver_endpoint = *resolver.resolve(query);\n        udp::socket socket(io_service);\n        socket.open(udp::v4());\n\n\n        std::shared_ptr<UDPPacket> data(new UDPPacket);\n        float fake_time = 0;\n        float dt = 1E-3*((float)sleep_time);\n        float period = 5.0;\n        float freq=1/period;\n\tfloat pi = boost::math::constants::pi<float>();\n        while (true) {\n                data->m_time = fake_time;\n                data->m_steer = sin(2*pi*freq*fake_time);\n                data->m_throttle = sin(2*pi*freq*fake_time + pi /3.0);\n                data->m_brake = sin(2*pi*freq*fake_time + 2.0*pi /3.0);\n                std::cout<<\"Sending fake UDP data\"<<std::endl;\n                // std::cout<<\"fake_time: \"<<fake_time<<std::endl;\n                // std::cout<<\"Steering: \"<<data->m_steer<<std::endl;\n                // std::cout<<\"Throttle: \"<<data->m_throttle<<std::endl;\n                // std::cout<<\"B:rake \"<<data->m_brake<<std::endl;\n                socket.send_to(boost::asio::buffer(boost::asio::buffer(data.get(), packet_size)), receiver_endpoint);\n                fake_time += dt;\n                std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time));\n        }\n        return 0;\n\t\t/* */\n}\n", "meta": {"hexsha": "80e8fb002fdd1b2444661b8bf419c9075961e0dd", "size": 3281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data-logger/src/udp_logging/simulated_telemetry_server.cpp", "max_stars_repo_name": "dummyaccount123457/deepracing", "max_stars_repo_head_hexsha": "cd70a0252b5cbfd1c45afc13f2eb774fa0aad1fe", "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": "data-logger/src/udp_logging/simulated_telemetry_server.cpp", "max_issues_repo_name": "dummyaccount123457/deepracing", "max_issues_repo_head_hexsha": "cd70a0252b5cbfd1c45afc13f2eb774fa0aad1fe", "max_issues_repo_licenses": ["Apache-2.0"], "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-logger/src/udp_logging/simulated_telemetry_server.cpp", "max_forks_repo_name": "dummyaccount123457/deepracing", "max_forks_repo_head_hexsha": "cd70a0252b5cbfd1c45afc13f2eb774fa0aad1fe", "max_forks_repo_licenses": ["Apache-2.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.6, "max_line_length": 151, "alphanum_fraction": 0.5733008229, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6107874011142596}}
{"text": "#include \"simulate.h\"\n\n#include <algorithm>\n#include <exception>\n#include <climits>\n#include <cmath>\n#include <utility>\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/hypergeometric.hpp>\n#include <boost/math/distributions/students_t.hpp>\n\nusing namespace std;\n\nconst boost::math::normal STANDARD_NORMAL(0, 1);\n\ndouble testBalance(const arma::Col<double> &z, const arma::Col<double> &t) {\n  if (z.n_rows != t.n_rows) throw length_error(\"Column vectors must be the same length.\");\n  int N = t.n_rows;             // population size\n  int n = 0;                    // draws\n  int K = 0;                    // \"success\" events\n  int k = 0;                    // observed successes\n  for (int i = 0; i < N; ++i) {\n    if (!(t(i) == 0 || t(i) == 1)) throw logic_error(\"Treatment must be a vector of 0s and 1s.\");\n    if (!(z(i) == 0 || z(i) == 1)) throw logic_error(\"Covariate must be a vector of 0s and 1s.\");\n    if (t(i) == 1) ++n;         // assigning to treatment is draw\n    if (z(i) == 1) ++K;         // number of possible success events\n    if (t(i) == 1 && z(i) == 1) ++k; // observed successes\n  }    \n  boost::math::hypergeometric_distribution<> X(K, n, N);\n  // find Prob(|X - K/N*n| >= |k - K/N*n|) = Prob(X <= K/N*n - |k - K/N*n|) + Prob(X >= K/N*n + |k - K/N*n|)\n  double p = ((double) K)/N;  \n  double mean = p*n;\n  double delta = abs(k - p*n);\n  double pValue = 0;  \n  int L = mean - delta;\n  int U = mean + delta - 1; // complement is not inclusive\n  return U < L ? 1 : boost::math::cdf(X, L) + boost::math::cdf(boost::math::complement(X, U));\n}\n\ndouble calculateVariance(int N, double alpha, double power) {\n  double z = boost::math::quantile(boost::math::complement(STANDARD_NORMAL, alpha/2)); // critical value\n  double lower = 1;\n  double upper = 100000000;\n  double mid = (upper + lower)/2;\n  while (upper - lower > 0.00000001) {\n    double val = boost::math::cdf(STANDARD_NORMAL, -z + sqrt(N)/sqrt(mid)) + boost::math::cdf(STANDARD_NORMAL, -z - sqrt(N)/sqrt(mid));\n    if (val > power) {\n      lower = mid;\n    } else {\n      upper = mid;\n    }\n    mid = (upper + lower)/2;\n  }\n  return mid;\n}\n\npair<double, double> calculateBetaPValue(const arma::mat &Z, const arma::Col<double> &Y, \n                                         double sigma, bool varianceKnown) {\n  arma::mat ZZ = Z.t()*Z;\n  arma::mat beta = arma::solve(ZZ, Z.t()*Y);\n  arma::Col<double> e(ZZ.n_rows, arma::fill::zeros); e(0) = 1;\n  arma::mat inverseFirstColumn = arma::solve(ZZ, e);\n  if (varianceKnown) {\n    double standardDeviation = sigma*sqrt(inverseFirstColumn(0));\n    double t = abs(beta(0))/standardDeviation;  \n    return make_pair(2*cdf(STANDARD_NORMAL, -t), beta(0));\n  } else {    \n    int df = Y.n_rows - beta.n_rows;            // degrees of freedom\n    double s = arma::norm(Y - Z*beta)/sqrt(df); // sample standard deviation\n    double standardDeviation = s*sqrt(inverseFirstColumn(0));\n    double t = abs(beta(0))/standardDeviation;  \n    boost::math::students_t tDist(df);\n    return make_pair(2*cdf(tDist, -t), beta(0));\n  }\n}\n\ntuple<double, double, int, int, double, double> simulate(const arma::Col<double> &Y, const vector<int> X, \n                                                         double sigma, bool varianceKnown,\n                                                         arma::mat &Z, mt19937_64 &rng,\n                                                         bool interceptTerm) {\n  bernoulli_distribution bernoulli(0.5);\n  int N = X.size();\n  Z.fill(0);\n  // bestColumns[k] keeps track of the k + 1 or k + 2 columns that produce the smallest p-value depending on interceptTerm\n  vector<arma::uvec> bestColumns; bestColumns.reserve(N - 1); \n  if (interceptTerm) { // make intercept term last column of Z\n    fill(Z.begin_col(N - 1), Z.end_col(N - 1), 1);\n    copy(X.begin(), X.end(), Z.begin_col(0));\n    bestColumns.push_back(arma::uvec{0, (unsigned long long) N - 1ULL}); \n  } else {\n    copy(X.begin(), X.end(), Z.begin_col(0));\n    bestColumns.push_back(arma::uvec{0});     \n  }  \n  // bestPValues[k] corresponds to p-value if the columns bestColumns[k] are used\n  vector<pair<double, double>> bestPValues; bestPValues.reserve(N - 1);\n  bestPValues.push_back(calculateBetaPValue(Z.cols(bestColumns.front()), Y, sigma, varianceKnown));\n  if (bestPValues.front().first <= 0.05) {\n    return make_tuple(bestPValues.front().first, bestPValues.front().second, 0, 0, -1, bestPValues.front().first);\n  } else {                    // need more covariates\n    bool done = false;\n    int smallestSubsetSize = INT_MAX;\n    /* add covariates one-by-one, we always include the treatment\n     * if we're using the intercept two covariates are included by default\n     */\n    for (int j = 1; j < N - 2 || (j == N - 2 && !interceptTerm); ++j) { \n      for (int k = 0; k < N; ++k) Z(k, j) = bernoulli(rng);\n      if (!interceptTerm) {\n        while (arma::rank(Z) <= j) {\n          for (int k = 0; k < N; ++k) Z(k, j) = bernoulli(rng);\n        }        \n      } else { // offset rank by 1 for intercept term\n        while (arma::rank(Z) <= j + 1) {\n          for (int k = 0; k < N; ++k) Z(k, j) = bernoulli(rng);\n        }        \n      }\n      for (int k = j; k >= 1; --k) { // loop through subset sizes, k is the number of additional covariates\n        pair<double, double> newPValue;\n        if (k == j) {           // use all available covariates\n          bestColumns.emplace_back(bestColumns.back().n_rows + 1); // add one more to biggest subset\n          for (int l = 0; l < bestColumns.back().n_rows - 1; ++l) { \n            bestColumns.back()(l) = bestColumns[j - 1](l); // copy over from original subset\n          }\n          bestColumns.back()(bestColumns.back().n_rows - 1) = j; // add new covariate\n          newPValue = calculateBetaPValue(Z.cols(bestColumns.back()), Y, sigma, varianceKnown);\n          bestPValues.push_back(newPValue);\n        } else {                // make a new subset of same size with new covariate\n          arma::uvec columnSubset(bestColumns[k].n_rows); \n          for (int l = 0; l < columnSubset.n_rows - 1; ++l) \n            columnSubset(l) = bestColumns[k - 1](l); // copy over from smaller subset\n          columnSubset(columnSubset.n_rows - 1) = j; // add new covariate\n          newPValue = calculateBetaPValue(Z.cols(columnSubset), Y, sigma, varianceKnown);\n          if (bestPValues[k].first > newPValue.first) { // if better subset replace\n            bestPValues[k] = newPValue;\n            bestColumns[k] = columnSubset;\n          }\n        }\n        if (newPValue.first <= 0.05) { // stop when we reach significance\n          done = true;\n          smallestSubsetSize = k;\n        }\n      }\n      if (done) {\n        // compute balance p value in special case that only 1 covariate was needed\n        double balancePValue = -1;\n        if (smallestSubsetSize == 1 && !interceptTerm) {\n          balancePValue = testBalance(Z.col(bestColumns[1](1)), Z.col(0));\n        } else if (smallestSubsetSize == 1 && interceptTerm) {\n          balancePValue = testBalance(Z.col(bestColumns[1](2)), Z.col(0));\n        }\n        return make_tuple(bestPValues.front().first, bestPValues[smallestSubsetSize].second, \n                          j, smallestSubsetSize, balancePValue, bestPValues[smallestSubsetSize].first); \n      }\n    }    \n  }  \n  return make_tuple(bestPValues.front().first, bestPValues.front().second, -1, -1, -1, bestPValues.front().first);\n}\n", "meta": {"hexsha": "0c967f0b2bf14c484eb66c0c4a4258eff8437375", "size": 7442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulate.cpp", "max_stars_repo_name": "ppham27/cheating-linear-models-simulations", "max_stars_repo_head_hexsha": "ea71915c37ebd2b7c3e4e45e1cfacfba848277bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulate.cpp", "max_issues_repo_name": "ppham27/cheating-linear-models-simulations", "max_issues_repo_head_hexsha": "ea71915c37ebd2b7c3e4e45e1cfacfba848277bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulate.cpp", "max_forks_repo_name": "ppham27/cheating-linear-models-simulations", "max_forks_repo_head_hexsha": "ea71915c37ebd2b7c3e4e45e1cfacfba848277bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.1012658228, "max_line_length": 135, "alphanum_fraction": 0.5872077399, "num_tokens": 2120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6107845367205373}}
{"text": "#include <gtest/gtest.h>\n#include <boost/math/distributions.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <stan/math/prim/mat.hpp>\n#include <math/prim/mat/prob/vector_rng_test_helper.hpp>\n#include <limits>\n#include <vector>\n\nclass ScaledInvChiSquareTestRig : public VectorRealRNGTestRig {\n public:\n  ScaledInvChiSquareTestRig()\n      : VectorRealRNGTestRig(10000, 10, {0.5, 1.3, 2.0, 5.8}, {1, 2, 3, 6},\n                             {-2.5, -1.7, -0.1, 0.0}, {-3, -2, -1, 0},\n                             {0.1, 1.0, 2.5, 4.0}, {1, 2, 3, 4},\n                             {-2.7, -1.5, -0.5, 0.0}, {-3, -2, -1, 0}) {}\n\n  template <typename T1, typename T2, typename T3, typename T_rng>\n  auto generate_samples(const T1& nu, const T2& sigma, const T3&,\n                        T_rng& rng) const {\n    return stan::math::scaled_inv_chi_square_rng(nu, sigma, rng);\n  }\n\n  std::vector<double> generate_quantiles(double nu, double sigma,\n                                         double) const {\n    std::vector<double> quantiles;\n    double K = stan::math::round(2 * std::pow(N_, 0.4));\n    boost::math::inverse_chi_squared_distribution<> dist(nu);\n\n    for (int i = 1; i < K; ++i) {\n      double frac = i / K;\n      quantiles.push_back(quantile(dist, frac) * (nu * sigma * sigma));\n    }\n    quantiles.push_back(std::numeric_limits<double>::max());\n\n    return quantiles;\n  }\n};\n\nTEST(ProbDistributionsScaledInvChiSquare, errorCheck) {\n  check_dist_throws_all_types(ScaledInvChiSquareTestRig());\n}\n\nTEST(ProbDistributionsScaledInvChiSquare, distributionTest) {\n  check_quantiles_real_real(ScaledInvChiSquareTestRig());\n}\n", "meta": {"hexsha": "4b1cdfcbb4362e93ad9069f3eedb1c129f43c839", "size": 1626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/prim/mat/prob/scaled_inv_chi_square_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/prim/mat/prob/scaled_inv_chi_square_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/prim/mat/prob/scaled_inv_chi_square_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.347826087, "max_line_length": 75, "alphanum_fraction": 0.6193111931, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6107845309191298}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <vector>\n#include <numeric>\n#include <limits>\n#include <list>\n#include <set>\n#include <queue>\n#include <map>\n#include <stack>\n#include <math.h>\n\nusing namespace std;\n\n\n__int64 CollatzProblem()\n{\n    map<__int64,__int64> seq;\n    map<__int64,__int64>::iterator I;\n    seq[2] = 1;\n\n    for( int i=3; i< (int)1e6; ++i )\n    {\n        stack<__int64> series;\n        __int64 v = i;\n\n        for( ;; )\n        {\n            I = seq.find( v );\n            if( I == seq.end() ) \n            {\n                series.push( v );\n                v = ( v%2 == 0 ) ? ( v/2 ) : ( 3*v+1 );\n                if ( v < 0 ) \n                {\n                    break;\n                }\n            }\n            else\n            {\n                __int64 c = I->second + 1;\n                while( series.size() > 0 ) \n                {   \n                    seq[ series.top() ] = c;\n                    series.pop();\n                    c++;\n                }\n\n                break;\n            }\n        }\n    }\n\n    struct CountComp {\n        bool operator()( const pair<__int64,__int64>& l, const pair<__int64,__int64>& r) { return l.second<r.second; }\n    };\n\n    I = max_element( seq.begin(), seq.end(), CountComp() );\n    return I->first;\n}\n\n__int64 CollatzProblem_UsingLinearAddress( int N )\n{\n    int* seq = new int[ N ];\n    memset( seq, 0, sizeof(int)*N );\n    seq[2] = 1;\n\n    for( int i=3; i< N; ++i )\n    {\n        stack<__int64> series;\n        __int64 v = i;\n\n        for( ;; )\n        {\n            if( v>=N || (v<N && seq[ (int)v ] == 0) )\n            {\n                series.push( v );\n                v = ( v%2 == 0 ) ? ( v/2 ) : ( 3*v+1 );\n                if ( v < 0 ) \n                {\n                    break;\n                }\n            }\n            else\n            {\n                int c = seq[ (int)v ] + 1;\n                while( series.size() > 0 ) \n                {   \n                    if ( series.top() < N ) {\n                        seq[ (int)series.top() ] = c;\n                    }\n                    series.pop();\n                    c++;\n                }\n\n                break;\n            }\n        }\n    }\n\n    struct CountComp {\n        bool operator()( const int& l, const int& r) { return l<r; }\n    };\n\n    int ret = max_element( seq, seq+N, CountComp() ) - seq;\n    delete seq;\n\n    return ret;\n}\n\nBOOST_AUTO_TEST_CASE( TestEulerProject14 )\n{\n    //BOOST_CHECK_EQUAL( 837799, CollatzProblem() );\n    //BOOST_CHECK_EQUAL( 837799, CollatzProblem_UsingLinearAddress( 1000000) );\n}\n\n\nvoid PathInGrid( int r, int d, __int64 &count )\n{\n    if ( r == 0 || d == 0 ) \n    {\n        count++;\n        return;\n    }\n\n    PathInGrid( r-1, d, count );\n    PathInGrid( r, d-1, count );\n}\n\n__int64 PathInGrid_Fast( int d )\n{\n    vector<__int64> P, C;\n    \n    P.assign( 3, 0 );\n    P[2]=6; P[1]=3;\n\n    for( int n = 3; n <= d; ++n )\n    {\n        C.assign( n+1, 0 );\n\n        C[1] = n + 1;\n        C[n] = 1 + P[1];\n        for( int i=2; i<n; ++i) \n        {\n            C[i] = P[i] + C[i-1];\n            C[n] += P[i];\n        }\n        C[n] *= 2;\n\n        P.swap( C );\n    }\n\n    return P[ d ];\n}\n\n\nBOOST_AUTO_TEST_CASE( TestEulerProject15 )\n{\n    {\n        __int64 count = 0;\n        PathInGrid( 3, 3, count );\n        BOOST_CHECK_EQUAL( 20, count );\n    }\n\n    {\n        BOOST_CHECK_EQUAL( 20, PathInGrid_Fast( 3) );\n        //BOOST_CHECK_EQUAL( 137846528820, PathInGrid_Fast( 20 ) );\n    }\n}\n\n\n__int64 DigitSumOfTwoSquare( int power )\n{\n\tclass Number\n\t{\n\tpublic:\n        Number( const Number& r ) : _V( r._V ) {}\n\n        Number( const char *str )\n\t\t{\n\t\t\tconst char *l = str + strlen( str );\n\t\t\twhile ( l != str ) \n\t\t\t{\n\t\t\t\t_V.push_back( *(--l) - '0' );\n\t\t\t}\n\t\t}\n\n\t\tvoid Add( const Number& r )\n\t\t{\n\t\t\tchar v = 0;\n\t\t\tsize_t i=0;\n\t\t\tfor( ; i<r._V.size(); ++i )\n\t\t\t{\n\t\t\t\tif( i >= _V.size() ) \n\t\t\t\t{\n\t\t\t\t\t_V.push_back( r._V[i] );\n\t\t\t\t}\n\n\t\t\t\tv += r._V[i] + _V[i]; \n\t\t\t\t_V[i] = v%10;\n\t\t\t\tv /=  10;\n\t\t\t}\n\n\t\t\twhile( v != 0 )\n\t\t\t{\n\t\t\t\tif( i >= _V.size() ) {\n\t\t\t\t\t_V.push_back( v );\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tv += _V[i]; \n\t\t\t\t\t_V[i] = v % 10;\n\t\t\t\t\tv /=  10;\n\t\t\t\t}\n\t\t\t\t++i;\n\t\t\t}\n\t\t}\n\n\t\tstring AsString() const \n\t\t{\n\t\t\tstring r;\n\t\t\tfor( int i=_V.size()-1; i>=0; --i)\n\t\t\t{\n\t\t\t\tr.push_back( _V[i] + '0' );\n\t\t\t}\n\n\t\t\treturn r;\n\t\t}\n\n\tprivate:\n\t\tvector<char> _V;\n\t};\n\n\tif( power == 0 ) \n\t\treturn 1;\n\n\tNumber v( \"2\" );\n\tfor( int i = 2; i<=power; ++i ) \n\t{\n\t\tNumber a( v );\n\t\tv.Add( a );\n\t}\n\n    struct IntCharAdd {\n        __int64 operator() ( __int64 s, const char& v ) { return s + ( v - '0' ); }\n    };\n\n    string vs( v.AsString() );\n    return accumulate( vs.begin(), vs.end(), (__int64)0, IntCharAdd() );\n}\n\nBOOST_AUTO_TEST_CASE( TestEulerProject16 )\n{\n    BOOST_CHECK_EQUAL( 26, DigitSumOfTwoSquare( 15 ) );\n//    BOOST_CHECK_EQUAL( 1366, DigitSumOfTwoSquare( 1000 ) );\n}\n\nint LetterCountSumFrom0neTo( int n )\n{\n    class NumericWord\n    {\n    public:\n        static int Count( int v )\n        {\n            static int letters_0_19[] = \n            { \n                0,\n                strlen(\"one\"),\n                strlen(\"two\"),\n                strlen(\"three\"),\n                strlen(\"four\"),\n                strlen(\"five\"),\n                strlen(\"six\"),\n                strlen(\"seven\"),\n                strlen(\"eight\"),\n                strlen(\"nine\"),\n                strlen(\"ten\"),\n                strlen(\"eleven\"),\n                strlen(\"twelve\"),\n                strlen(\"thirteen\"),\n                strlen(\"fourteen\"),\n                strlen(\"fifteen\"),\n                strlen(\"sixteen\"),\n                strlen(\"seventeen\"),\n                strlen(\"eighteen\"),\n                strlen(\"nineteen\"),\n            };\n\n            static int letters_0_90[] = \n            {\n                0,\n                0,\n                strlen(\"twenty\"),\n                strlen(\"thirty\"),\n                strlen(\"forty\"),\n                strlen(\"fifty\"),\n                strlen(\"sixty\"),\n                strlen(\"seventy\"),\n                strlen(\"eighty\"),\n                strlen(\"ninety\"),\n            };\n\n            int c1 = v / 20;\n            if ( c1 == 0 )\n            {\n                return letters_0_19[ v % 20 ];\n            }\n            else if ( v < 100 )\n            {\n                return letters_0_90[ v / 10 ] + letters_0_19[ v % 10 ];\n            }\n            else if ( v < 1000 ) \n            {\n                static int hundred = 7;\n                static int and = 3;\n\n                if( v%100 == 0 )\n                {\n                    return letters_0_19[ v / 100 ] + hundred;\n                }\n                \n                return letters_0_19[ v / 100 ] + hundred + and + Count( v % 100 );\n            }\n            else if ( v == 1000 )\n            {\n                return 11;\n            }\n\n            return -1;\n        }\n\n        static int SummationOfCount( int s, int e )\n        {\n            int sum = 0;\n            for( int i = s; i<=e; ++i ) { sum += Count(i); }\n            return sum;\n        }\n\n        static int SummationOfCount( int n ) // FIX ME : This method is not working!\n        {\n            if( n <= 19 ) \n            {\n                return SummationOfCount( 1, n );\n            }\n            else if ( n < 100 )\n            {\n                int sum = SummationOfCount( 1, 19 );\n                int s_9 = SummationOfCount( 0, 9 );\n\n                int i = 20;\n                for( ; i< (n/10)*10; i+= 10 )\n                {\n                    sum += Count(i) * 10;\n                    sum += s_9;\n                }\n\n                sum += Count(i) * ((n%10)+1);\n                sum += SummationOfCount( 1, n % 10 );\n                return sum;\n            }\n            else if ( n < 1000 )\n            {\n                static int hundred = 7;\n                static int and = 3;\n                int s99 = SummationOfCount( 99 );\n                int i = 100, sum = 0;\n                for( ; i < (n/100)*100; i+=100 )\n                {\n                    sum += hundred;\n                    sum += ( Count( i / 100 ) + + hundred + and ) * 100;\n                    sum += s99;\n                }\n                \n                sum += hundred;\n                sum += ( Count( i / 100 ) + hundred + and ) * ( n % 100 );\n                sum += SummationOfCount( 1, n%100 );\n                return sum;\n            }\n            else if ( n == 1000 ) \n            {\n                static int one_thousand = 11;\n                int s999 = SummationOfCount( 999 );\n                return s999 + one_thousand;\n            }\n\n            return -1;\n        }\n    };\n\n    return NumericWord::SummationOfCount( 1, n );\n}\n\nBOOST_AUTO_TEST_CASE( TestEulerProject17 )\n{\n    BOOST_CHECK_EQUAL( 19, LetterCountSumFrom0neTo( 5 ) );\n//    BOOST_CHECK_EQUAL( 21124, LetterCountSumFrom0neTo( 1000 ) );\n}\n\nstruct Place {\n    int Row, Col;\n    int Sum, UpperBound;\n    Place() {};\n    Place( int row, int col, int sum ) : Row(row), Col(col), Sum(sum)\n    {\n        UpperBound = sum + (s_RowCount - row - 1)*s_MaxValue;\n    }\n\n    bool operator() ( const Place& l, const Place& r ) \n    {\n        if( l.UpperBound == r.UpperBound ) {\n            if( l.Sum == r.Sum ) {\n                if( l.Row == r.Row ) \n                    return l.Col > r.Col;\n                return l.Row > r.Row;\n            }\n            return l.Sum > r.Sum;\n        }\n        return l.UpperBound > r.UpperBound;\n    }\n\n    static void Dump( const Place & p )\n    {\n        printf( \"r=%d,c=%d,s=%d,u=%d\\n\", p.Row, p.Col, p.Sum, p.UpperBound );\n    }\n\n    static void SetUpperBoundVariable( int rowCount, int maxValue )\n    {\n        s_RowCount = rowCount;\n        s_MaxValue = maxValue;\n    }\n\n    static int s_RowCount, s_MaxValue;\n};\n\nint Place::s_RowCount = 0;\nint Place::s_MaxValue = 0;\n\nint FindMaxTopToBottom( const vector< vector<int> >& triangle, int maxValue )\n{\n    typedef priority_queue< Place, vector<Place>, Place > PlaceQueue;\n\n    int n = triangle.size();\n    Place::SetUpperBoundVariable( n, maxValue );\n\n    PlaceQueue q;\n    q.push( Place( 0,0, triangle[0][0] ));\n    int max = 0, iter = 0;\n\n    while( q.size() > 0 ) \n    {\n        Place t( q.top() );\n        q.pop();\n        Place::Dump( t );\n\n        if( t.Row < n-1 )\n        {\n            if( t.UpperBound < max ) \n                continue;\n\n            q.push( Place( t.Row+1, t.Col, t.Sum + triangle[t.Row+1][t.Col] ) );\n            q.push( Place( t.Row+1, t.Col+1, t.Sum + triangle[t.Row+1][t.Col+1] ) );\n        }\n        else\n        {\n            if( t.Sum > max ) \n            {\n                max = t.Sum;\n            }   \n        }\n\n        iter++;\n    }\n       \n    printf( \"max = %d, iter count = %d\\n\", max, iter );\n    return max;\n}\n\nvector<int> ParseAsVector( const char *numbers )\n{\n    vector<int> v;\n    const char *s = numbers;\n    char *e = const_cast<char *>(numbers);\n    while( *e != NULL ) \n    {\n        int i = strtol( s, &e, 10  );\n        if( i == 0 )\n            break;\n\n        v.push_back( i );\n        s = e;\n    }\n    return v;\n}\n\nint FindMaxTopToBottomFromBottomToTop( vector< vector<int> >& t )\n{\n    for( size_t i=t.size()-1; i>0; --i )\n    {\n        for( size_t j=0; j<t[i].size()-1; ++j )\n        {\n            t[i-1][j] += max( t[i][j], t[i][j+1] );\n        }\n    }\n       \n    return t[0][0];\n}\n\n\nBOOST_AUTO_TEST_CASE( TestEulerProject18 )\n{\n    {\n        vector< vector<int> > triangle;\n        triangle.assign( 4, vector<int>() );\n        triangle[0].swap( ParseAsVector( \"3\" ) );\n        triangle[1].swap( ParseAsVector( \"7 4\" ) );\n        triangle[2].swap( ParseAsVector( \"2 4 6\" ) );\n        triangle[3].swap( ParseAsVector( \"8 5 9 3\" ) );\n\n        int ret = FindMaxTopToBottom( triangle, 9 );\n        BOOST_CHECK_EQUAL( 23, ret );\n    }\n\n    {\n        vector< vector<int> > triangle;\n        triangle.assign( 15, vector<int>() );\n        triangle[0].swap( ParseAsVector( \"75\" ) );\n        triangle[1].swap( ParseAsVector( \"95 64\" ) );\n        triangle[2].swap( ParseAsVector( \"17 47 82\" ) );\n        triangle[3].swap( ParseAsVector( \"18 35 87 10\" ) );\n        triangle[4].swap( ParseAsVector( \"20 04 82 47 65\" ) );\n        triangle[5].swap( ParseAsVector( \"19 01 23 75 03 34\" ) );\n        triangle[6].swap( ParseAsVector( \"88 02 77 73 07 63 67\" ) );\n        triangle[7].swap( ParseAsVector( \"99 65 04 28 06 16 70 92\" ) );\n        triangle[8].swap( ParseAsVector( \"41 41 26 56 83 40 80 70 33\" ) );\n        triangle[9].swap( ParseAsVector( \"41 48 72 33 47 32 37 16 94 29\" ) );\n        triangle[10].swap( ParseAsVector( \"53 71 44 65 25 43 91 52 97 51 14\" ) );\n        triangle[11].swap( ParseAsVector( \"70 11 33 28 77 73 17 78 39 68 17 57\" ) );\n        triangle[12].swap( ParseAsVector( \"91 71 52 38 17 14 91 43 58 50 27 29 48\" ) );\n        triangle[13].swap( ParseAsVector( \"63 66 04 68 89 53 67 30 73 16 69 87 40 31\" ) );\n        triangle[14].swap( ParseAsVector( \"04 62 98 27 23 09 70 98 73 93 38 53 60 04 23\" ) );\n\n//        BOOST_CHECK_EQUAL( 1074, FindMaxTopToBottom( triangle, 99 ) );\n    }\n}\n\nBOOST_AUTO_TEST_CASE( TestEulerProject67 )\n{\n#if 0\n    {\n        vector< vector<int> > triangle;\n        triangle.clear();\n\n        {\n            FILE *fp = fopen( \"triangle.txt\", \"rt\" );\n    \n            while( !feof( fp ) ) {\n                char buf[1024];\n                if( fgets( buf, 1024, fp ) == NULL )\n                    break;\n\n                triangle.push_back( ParseAsVector( buf ) );\n            }\n\n            fclose( fp );\n        }\n\n        int ret = FindMaxTopToBottomFromBottomToTop( triangle);\n        BOOST_CHECK_EQUAL( 7273, ret );\n    }\n#endif\n}\n", "meta": {"hexsha": "77112110a6ccb512ecb28d3a627c1591697ce3e8", "size": 13586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CodingSkill/CPPCoding/TestProjectEulerTo25.cpp", "max_stars_repo_name": "SungwooNam/ProgrammingStudy", "max_stars_repo_head_hexsha": "3c2fe6096fea29547f05ff29bbde14a48c4afa9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-22T04:58:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-22T04:58:15.000Z", "max_issues_repo_path": "src/CodingSkill/CPPCoding/TestProjectEulerTo25.cpp", "max_issues_repo_name": "SungwooNam/ProgrammingStudy", "max_issues_repo_head_hexsha": "3c2fe6096fea29547f05ff29bbde14a48c4afa9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-21T16:02:41.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-21T16:02:41.000Z", "max_forks_repo_path": "src/CodingSkill/CPPCoding/TestProjectEulerTo25.cpp", "max_forks_repo_name": "SungwooNam/ProgrammingStudy", "max_forks_repo_head_hexsha": "3c2fe6096fea29547f05ff29bbde14a48c4afa9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7517482517, "max_line_length": 118, "alphanum_fraction": 0.431179155, "num_tokens": 3965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7185943985973773, "lm_q1q2_score": 0.6107845203348721}}
{"text": "#define BOOST_TEST_MODULE variables\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"exprtest.hpp\"\n\ndouble const x = 1;\ndouble const y = 2;\n\nstd::map<std::string, double> const symtab = {\n    std::make_pair(\"x\",  x),\n    std::make_pair(\"y\",  y),\n    std::make_pair(\"e\", -1),\n};\n\nSYMEXPRTEST(var1, \"x+y\" , symtab, x+y)\nSYMEXPRTEST(var2, \"x-y\" , symtab, x-y)\nSYMEXPRTEST(var3, \"x*y\" , symtab, x*y)\nSYMEXPRTEST(var4, \"x/y\" , symtab, x/y);\nSYMEXPRTEST(var5, \"x%y\" , symtab, std::fmod(x,y));\nSYMEXPRTEST(var6, \"x**y\", symtab, std::pow(x,y));\n\n// Constants have higher priority than variables of the same name\nSYMEXPRTEST(var7, \"e\", symtab, boost::math::constants::e<double>())\n", "meta": {"hexsha": "74095fb8955d00b4fa5a26e7aacdfe3946e7b6ea", "size": 697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/variables.cpp", "max_stars_repo_name": "fweik/boost_matheval", "max_stars_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/variables.cpp", "max_issues_repo_name": "fweik/boost_matheval", "max_issues_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/variables.cpp", "max_forks_repo_name": "fweik/boost_matheval", "max_forks_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0416666667, "max_line_length": 67, "alphanum_fraction": 0.668579627, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.6107598027761427}}
{"text": "#include <Eigen/Dense>\n\n#include \"benchmark.hpp\"\n\n#include <iostream>\n\nint main() {\n  for (size_t k = 10; k <= 1000; k+=10) {\n    size_t m = k;\n    double *A = create_random_sq_matrix(m);\n\n    sleep(0.1);\n    Eigen::MatrixXd A_;\n    A_.resize(m, m);\n    size_t index = 0;\n    for (size_t i = 0; i < m; i++) {\n      for (size_t j = 0; j < m; j++) {\n        A_(i, j) = A[index];\n      }\n    }\n\n    struct timespec t = tic();\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(A_, Eigen::ComputeFullV | Eigen::ComputeFullU);\n    Eigen::MatrixXd U = svd.matrixU();\n    Eigen::VectorXd d = svd.singularValues();\n    Eigen::MatrixXd S = d.asDiagonal();\n    Eigen::MatrixXd V = svd.matrixV();\n    printf(\"matrix_size: %ld\\tEigen SVD: %fs\\n\", A_.rows(), toc(&t));\n\n    bool retval = A_.isApprox(U * S * V.transpose());\n    if (retval == false) {\n      exit(-1);\n    }\n\n    free(A);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "00e3ea72f3b38bb9fd562ac06d825356b2cda727", "size": 884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "proto/lib/benchmarks/bench_svd-eigen.cpp", "max_stars_repo_name": "daoran/proto", "max_stars_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-08-27T21:37:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T12:25:04.000Z", "max_issues_repo_path": "proto/lib/benchmarks/bench_svd-eigen.cpp", "max_issues_repo_name": "daoran/proto", "max_issues_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-21T01:08:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-21T01:10:10.000Z", "max_forks_repo_path": "proto/lib/benchmarks/bench_svd-eigen.cpp", "max_forks_repo_name": "daoran/proto", "max_forks_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T05:10:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-22T03:19:44.000Z", "avg_line_length": 22.1, "max_line_length": 89, "alphanum_fraction": 0.5542986425, "num_tokens": 283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6107597989133792}}
{"text": "/**\n * eigen_boost.cpp\n *\n * Tests the cooperation of Eigen and boost::multiprecision.\n * Based on Eigen's test/boostmultiprec.cpp, Copyright (C) 2016 Gael Guennebaud\n */\n\n#include <iostream>\n\n#include <boost/chrono.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/QR>\n\n#undef min\n#undef max\n#undef isnan\n#undef isinf\n#undef isfinite\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/number.hpp>\n#include <boost/math/special_functions.hpp>\n\n\nnamespace mp = boost::multiprecision;\ntypedef mp::number<mp::cpp_dec_float<100>, mp::et_on> Real;\ntypedef Eigen::Matrix<Real, Eigen::Dynamic, Eigen::Dynamic> MatrixType;\n\nint main(int argc, char **argv)\n{\n\tEigen::MatrixXd abc;\n\tconst int matrixDimension = 50;\n\tMatrixType a = MatrixType::Random(matrixDimension, matrixDimension);\n\n\tEigen::ColPivHouseholderQR<MatrixType> qrOfA(a);\n\n\tstd::cout << \"QR decomposition \" << (qrOfA.info() == Eigen::Success ? \"succeeded\" : \"failed\") << std::endl;\n\tstd::cout << \"Matrix is invertible: \" << (qrOfA.isInvertible() ? \"true\" : \"false\") << std::endl;\n\tstd::cout << \"Rank = \" << qrOfA.rank() << \", abs(determinant) = \" << qrOfA.absDeterminant() << std::endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "0c57a2d7b67842f16692d3b12a50f5c6b51d5891", "size": 1179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/eigen_boost/src/eigen_boost.cpp", "max_stars_repo_name": "rhiestan/build-scripts", "max_stars_repo_head_hexsha": "c7db736b83db19cb67db3af56a88f2e416db74cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T09:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-22T20:03:42.000Z", "max_issues_repo_path": "test/eigen_boost/src/eigen_boost.cpp", "max_issues_repo_name": "rhiestan/build-scripts", "max_issues_repo_head_hexsha": "c7db736b83db19cb67db3af56a88f2e416db74cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-10-12T08:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T09:30:15.000Z", "max_forks_repo_path": "test/eigen_boost/src/eigen_boost.cpp", "max_forks_repo_name": "rhiestan/build-scripts", "max_forks_repo_head_hexsha": "c7db736b83db19cb67db3af56a88f2e416db74cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-02-23T01:03:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T12:59:20.000Z", "avg_line_length": 27.4186046512, "max_line_length": 108, "alphanum_fraction": 0.7065309584, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6106968449211242}}
{"text": "/*\n Kathpalia, A. and Nagaraj, N., 2019. Data-based intervention approach for Complexity-Causality measure. PeerJ Computer Science, 5, p.e196.\n */\n\n#include \"ETC.hpp\"\n#include <thread>\n#include <future>\n#include <Eigen/Dense>\n \n\n\n\nstruct CCC {\n    \n    enum threading {MULTITHREAD, SINGLETHREAD};\n\n    //DC(dx|xpast) = ETC(xpast + dx) - ETC(xpast)\n    //equation 5 in the paper\n    static double dynamicCC(const ArrayXL &seq, size_t dx, size_t xpast, size_t step, threading threadType=CCC::MULTITHREAD) {\n        size_t len = seq.size() -dx - xpast;\n        auto calcCall = [&seq, dx, xpast, step, len]()  {\n            double valCall=0;\n            for(size_t i=0; i < len; i += step) {\n                auto window = seq(Eigen::seq(i, i+ xpast + dx - 1));\n                //                cout << \"all: \\n\" << window.t() << endl;\n                valCall += ETC::calc(window);\n            }\n            return valCall;\n        };\n        auto calcCpast = [&seq, xpast, step, len]() {\n            double valCpast=0;\n            for(size_t i=0; i < len; i += step) {\n                ArrayXL window = seq(Eigen::seq(i, i+xpast-1));\n                //                cout << \"past: \\n\" << window.t() << endl;\n                valCpast += ETC::calc(window);\n            }\n            return valCpast;\n        };\n        double Call=0;\n        double Cpast=0;\n        if (threadType == CCC::MULTITHREAD) {\n            auto CallThread = std::async(std::launch::async, [&calcCall]() {\n                return calcCall();\n            });\n            auto CpastThread = std::async(std::launch::async, [&calcCpast]() {\n                return calcCpast();\n            });\n            Call = CallThread.get();\n            Cpast = CpastThread.get();\n        }else{\n            Call = calcCall();\n            Cpast = calcCpast();\n        }\n        int k = ceil(len/(double)step);\n        double val = Call - Cpast;\n        val = val / k;\n        return val;\n    }\n\n    //equation 6 in the paper\n    static double dynamicCCJoint(const ArrayXL &X, const ArrayXL &Y, size_t dx, size_t past, size_t step) {\n        size_t len = X.size() -dx - past;\n        int k=1;\n        double val=0;\n        for(size_t i=0; i < len; i += step) {\n            auto CallThread = std::async(std::launch::async, [&X, &Y, dx, past, i]() {\n                ArrayXL window1 = X(Eigen::seq(i, i+ past + dx - 1));\n                ArrayXL window2 = X(Eigen::seq(i, i+ past + dx - 1));\n                window2(Eigen::seq(0,past-1)) = Y(Eigen::seq(i,i+past-1));\n//                auto window = seq1.subvec(i, i+ past + dx - 1);\n//                cout << \"all: \\n\" << window.t() << endl;\n                return ETC::calcJoint(window1, window2);\n            });\n            auto CpastThread = std::async(std::launch::async, [&X, &Y, past, i]() {\n                ArrayXL window1 = X(Eigen::seq(i, i+past-1));\n                ArrayXL window2 = Y(Eigen::seq(i, i+past-1));\n//                cout << \"past: \\n\" << window.t() << endl;\n                return ETC::calcJoint(window1, window2);\n            });\n            double Call = CallThread.get();\n            double Cpast = CpastThread.get();\n//            cout << Call << \",\" << Cpast << endl;\n//            cout << \"intCC: \" << Call << \", \" << Cpast << \", \" << (Call - Cpast) <<endl;\n            val += Call - Cpast;\n            k++;\n        }\n        val = val / (k-1);\n        return val;\n\n    }\n\n    //equation 8 in the paper\n    static std::tuple<double, unsigned int> CCCausality(const ArrayXL &effectSeq, const ArrayXL &causeSeq, size_t dx, size_t past, size_t step) {\n        auto dynCCSeq1Thread = std::async(std::launch::async, [&effectSeq, past, dx, step]() {\n            return CCC::dynamicCC(effectSeq, dx, past, step);\n        });\n\n        auto dynCCSeqJointThread = std::async(std::launch::async, [&effectSeq, &causeSeq, past, dx, step]() {\n            return CCC::dynamicCCJoint(effectSeq, causeSeq, dx, past, step);\n        });\n        auto dynCCResult = dynCCSeq1Thread.get();\n        double dynCC = dynCCResult;\n        double dynCCJoint = dynCCSeqJointThread.get();\n        double CCC = dynCC - dynCCJoint;\n//        cout << \"CCC: \" << dynCC << \", \" << dynCCJoint << endl;\n        //CCC mode - see table S1, related to polarity of the terms, and relative magnitude\n        unsigned int CCCMode;\n        if (dynCC < 0) {\n            if (dynCCJoint < 0) {\n                if (CCC < 0) {\n                    CCCMode = 0;\n                }else{\n                    CCCMode = 1;\n                }\n                \n            }else{\n                CCCMode = 2;\n            }\n        }else{\n            if (dynCCJoint < 0) {\n                CCCMode = 3;\n            }else{\n                if (CCC < 0) {\n                    CCCMode = 4;\n                }else{\n                    CCCMode = 5;\n                }\n            }\n        }\n\n        return std::make_tuple(CCC, CCCMode);;\n    }\n};\n", "meta": {"hexsha": "97be340e31631edb41cbf26452e1360ce8c24e61", "size": 4910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CCC.hpp", "max_stars_repo_name": "chriskiefer/libcccrt", "max_stars_repo_head_hexsha": "e05edc8ed65cecc5515ccb5469e4c73fc4549231", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-03-19T23:16:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T03:20:15.000Z", "max_issues_repo_path": "CCC.hpp", "max_issues_repo_name": "chriskiefer/libcccrt", "max_issues_repo_head_hexsha": "e05edc8ed65cecc5515ccb5469e4c73fc4549231", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CCC.hpp", "max_forks_repo_name": "chriskiefer/libcccrt", "max_forks_repo_head_hexsha": "e05edc8ed65cecc5515ccb5469e4c73fc4549231", "max_forks_repo_licenses": ["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.6417910448, "max_line_length": 145, "alphanum_fraction": 0.4767820774, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220294, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.6106968392053467}}
{"text": "/*UJ - Uncle Jack\n#math #big-numbers\n\nDear Uncle Jack is willing to give away some of his collectable CDs to his nephews. Among the titles you can find very rare albums of Hard Rock, Classical Music, Reggae and much more; each title is considered to be unique. Last week he was listening to one of his favorite songs, Nobody\u2019s fool, and realized that it would be prudent to be aware of the many ways he can give away the CDs among some of his nephews.\n\n\nSo far he has not made up his mind about the total amount of CDs and the number of nephews. Indeed, a given nephew may receive no CDs at all.\n\n\nPlease help dear Uncle Jack, given the total number of CDs and the number of nephews, to calculate the number of different ways to distribute the CDs among the nephews.\n\n\nInput\n\nThe input consists of several test cases. Each test case is given in a single line of the input by, space separated, integers N (1 <= N <= 1000) and D (0 <= D <= 2500), corresponding to the number of nephews and the number of CDs respectively. The end of the test cases is indicated with N = D = 0.\n\n\nOutput\n\nThe output consists of several lines, one per test case, following the order given by the input. Each line has the number of all possible ways to distribute D CDs among N nephews.\nExample\n\nInput:\n1 20\n3 10\n0 0\n\nOutput:\n1\n59049\n\n*/\n\n#include <iostream>\n#include <boost/multiprecision/cpp_int.hpp>\n\nint main()\n{\n    using namespace boost::multiprecision;\n    \n    cpp_int n;\n    int d;\n    \n    while (true)\n    {\n        std::cin >> n >> d;\n        if (n == 0) break;\n        \n        std::cout << pow(n, d) << std::endl;\n    }\n    \n    return 0;\n}\n", "meta": {"hexsha": "06256d766f1ff5fb8cb8f82c9f52d81604a1d2bd", "size": 1633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SPOJ/UJ - Uncle Jack.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/UJ - Uncle Jack.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/UJ - Uncle Jack.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": 30.2407407407, "max_line_length": 413, "alphanum_fraction": 0.7066748316, "num_tokens": 406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.6106968334895686}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed\n * under the MIT license. See the license file LICENSE.\n */\n#pragma once \n\n#include <stdint.h>\n#include <iostream>\n#include <algorithm>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/QR>\n#include <unsupported/Eigen/MatrixFunctions>\n\nusing namespace Eigen;\nusing std::min;\nusing std::max;\n\nnamespace mmf{\n\n//TODO: use the other sphere class\nclass SphereSimple\n{\n  public:\n  SphereSimple()\n  {}\n  ~SphereSimple()\n  {}\n\n  /* normal in tangent space around p rotate to the north pole\n   * -> the third dimension will always be 0\n   * -> return only first 2 dims\n   */\n  MatrixXf Log_p_2D(const Matrix<float,3,1>& p, const MatrixXf& q)\n  {\n    return rotate_p2north(p,Log_p(p,q));\n  }\n\n  /* rotate points x in tangent plane around north pole down to p\n   */\n  MatrixXf rotate_north2p(const Matrix<float,3,1>& p, const MatrixXf& xNorth)\n  {\n    Matrix3f northR = this->north_R_TpS2(p);\n    //cout<<\"northR\"<<endl<<northR<<endl;\n    if(xNorth.cols() == 2)\n    {\n      MatrixXf x(xNorth.rows(),3);\n      x = xNorth * northR.transpose().topRows<2>();\n      return x;\n    }else if (xNorth.rows() == 2){\n      MatrixXf x(3,xNorth.cols());\n      x = northR.leftCols<2>() * xNorth;\n      return x;\n    }else{\n      assert(false);\n      return p;\n    }\n  }\n\n  /* rotate points x in tangent plane around p to north pole and \n   * return 2D coordinates\n   */\n  MatrixXf rotate_p2north(const Matrix<float,3,1>& p, const MatrixXf& x)\n  {\n    Matrix3f northR = this->north_R_TpS2(p);\n    if(x.cols() == 3)\n    {\n      //MatrixXf xNorth(x.rows(),2);\n      assert((x.row(0)*northR.transpose())(2) < 1e-6);\n      return (x * northR.transpose()).leftCols<2>();\n    }else if (x.rows() == 3){\n//#ifndef NDEBUG\n//      cout<< (northR * x.col(0)).transpose()<<endl;\n//#endif \n      assert((northR * x.col(0))(2) < 1e-3);\n      return (northR * x).topRows<2>();\n    }else{\n      assert(false);\n      return Matrix<float,Dynamic,1>::Zero(2);\n    }\n  }\n\n  /* compute rotation from TpS^2 to north pole on sphere\n   */\n  Matrix3f north_R_TpS2(const Matrix<float,3,1>& p)\n  {\n    Matrix<float,3,1> north;\n    north << 0.f,0.f,1.f;\n    Eigen::Quaternion<float> northQ_TpS2;\n    northQ_TpS2.setFromTwoVectors(p,north);\n    return northQ_TpS2.toRotationMatrix().cast<float>();\n  }\n\n  MatrixXf Log_p(const Matrix<float,3,1>& p, const MatrixXf& q)\n  {\n    MatrixXf x(q.rows(),q.cols());\n    if(q.cols() == 3)\n    {\n      for (uint32_t i=0; i<q.rows(); ++i)\n      {\n        float dot = max(-1.0f,min(1.0f,q.row(i).dot(p)));\n        float theta = acos(dot);\n        float sinc;\n        if(theta < 1.e-8)\n          sinc = 1.0f;\n        else\n          sinc = theta/sin(theta);\n        x.row(i) = (q.row(i)-p.transpose()*dot)*sinc;\n      }\n    }else if (q.rows() == 3)\n    {\n      for (uint32_t i=0; i<q.cols(); ++i)\n      {\n        float dot = max(-1.0f,min(1.0f,p.dot(q.col(i))));\n        float theta = acos(dot);\n        float sinc;\n        if(theta < 1.e-8)\n          sinc = 1.0f;\n        else\n          sinc = theta/sin(theta);\n        x.col(i) = (q.col(i)-p*dot)*sinc;\n      }\n    }else{\n      assert(false);\n    }\n    return x;\n  }\n\n  MatrixXf Exp_p(const Matrix<float,3,1>& p, const MatrixXf& x)\n  {\n//    assert(p.cols ==1);\n    MatrixXf q(x.rows(),x.cols());\n     \n    for (uint32_t i=0; i<x.cols(); ++i){\n      float theta_i = x.col(i).norm();\n      //cout<<\"theta \"<<theta_i<<endl;\n      if (theta_i < 1e-10)\n        q.col(i) = p + x.col(i);\n      else\n        q.col(i) = p*cos(theta_i) + x.col(i)/theta_i *sin(theta_i);\n      //cout<<q.col(i).transpose()<<endl;\n    }\n    return q;\n  }\n\n  protected:\n};\n\n\n}\n", "meta": {"hexsha": "c51c064835d5c6b64df67cc10ad82ef5b4c93619", "size": 3661, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mmf/sphereSimple.hpp", "max_stars_repo_name": "jstraub/mmf", "max_stars_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-06-02T04:17:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T05:44:53.000Z", "max_issues_repo_path": "include/mmf/sphereSimple.hpp", "max_issues_repo_name": "jstraub/mmf", "max_issues_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mmf/sphereSimple.hpp", "max_forks_repo_name": "jstraub/mmf", "max_forks_repo_head_hexsha": "45a5adea57ba96c08161e61312b2d743d822ebaf", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-06T04:34:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-28T06:35:00.000Z", "avg_line_length": 24.4066666667, "max_line_length": 77, "alphanum_fraction": 0.5678776291, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6106872874948547}}
{"text": "#include \"tet.h\"\n\n#include \"args.hxx\"\n\n#include \"cuda/cg.cuh\"\n\n#include <ctime>\n\n#include <Eigen/SparseCholesky>\n#include <Eigen/SparseCore>\n\nusing namespace CompArch;\n\n// == Geometry data\nTetMesh* mesh;\n\nfloat diffusionTime = 0.001;\n\nvoid testSolver(size_t startIndex, double t, bool useCSR = false) {\n    std::vector<double> distances;\n    distances.reserve(mesh->vertices.size());\n\n    std::vector<double> start(mesh->vertices.size(), 0.0);\n    start[startIndex] = 1;\n    if (t < 0) t = mesh->meanEdgeLength();\n\n    Eigen::VectorXd u0 = Eigen::VectorXd::Map(start.data(), start.size());\n\n    Eigen::VectorXd u(mesh->vertices.size());\n    Eigen::VectorXd phi(mesh->vertices.size());\n    Eigen::VectorXd divX = Eigen::VectorXd::Random(mesh->vertices.size());\n    Eigen::VectorXd ones = Eigen::VectorXd::Ones(divX.size());\n    divX -= divX.dot(ones) * ones;\n\n\n    if (useCSR) {\n        cgSolveCSR(u, u0, *mesh, 1e-8, t);\n        cgSolveCSR(phi, divX, *mesh, 1e-8, -1);\n    } else {\n        cgSolve(u, u0, *mesh, 1e-8, t);\n        cgSolve(phi, divX, *mesh, 1e-8, -1);\n    }\n\n    Eigen::SparseMatrix<double> L    = mesh->weakLaplacian();\n    Eigen::SparseMatrix<double> M    = mesh->massMatrix();\n\n    Eigen::SparseMatrix<double> flow = M + t * L;\n    cout << \"Residual: \" << (flow * u  - u0).norm();\n    cout << \"\\tResidual 2: \" << (L * phi - divX).norm() << endl;\n}\n\nstd::vector<double> computeDistances(size_t startIndex, double t, bool useCUDA, bool useCSR=false) {\n    std::vector<double> distances;\n    distances.reserve(mesh->vertices.size());\n\n    std::vector<double> start(mesh->vertices.size(), 0.0);\n    start[startIndex] = 1;\n    if (t < 0) t = mesh->meanEdgeLength();\n\n    Eigen::VectorXd u0 = Eigen::VectorXd::Map(start.data(), start.size());\n    Eigen::SparseMatrix<double> L    = mesh->weakLaplacian();\n    Eigen::SparseMatrix<double> M    = mesh->massMatrix();\n\n    Eigen::VectorXd u(mesh->vertices.size());\n    Eigen::SparseMatrix<double> flow = M + t * L;\n    if (useCUDA) {\n        if (useCSR) {\n            cgSolveCSR(u, u0, *mesh, 1e-8, t);\n        } else {\n            cgSolve(u, u0, *mesh, 1e-8, t);\n        }\n        double residual = (flow * u - u0).norm();\n        if (residual > 1e-5)\n            cout << \"Residual 1: \" << residual << endl;\n    } else {\n        Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n        solver.compute(flow);\n        u = solver.solve(u0);\n    }\n\n    Eigen::VectorXd divX = Eigen::VectorXd::Zero(u.size());\n\n    std::vector<Vector3> tetXs;\n    for (Tet t : mesh->tets) {\n        std::array<Vector3, 4> vertexPositions = mesh->layOutIntrinsicTet(t);\n\n        std::array<double, 4> tetU{u[t.verts[0]], u[t.verts[1]], u[t.verts[2]],\n                                   u[t.verts[3]]};\n        Vector3 tetGradU = grad(tetU, vertexPositions);\n        Vector3 X = tetGradU.normalize();\n\n        tetXs.emplace_back(Vector3{X.x, X.y, X.z});\n\n        std::array<double, 4> tetDivX = div(X, vertexPositions);\n        for (size_t i = 0; i < 4; ++i) {\n            divX[t.verts[i]] += tetDivX[i];\n        }\n    }\n\n    Eigen::VectorXd ones = Eigen::VectorXd::Ones(divX.size());\n    divX -= divX.dot(ones) * ones;\n\n    Eigen::VectorXd phi(mesh->vertices.size());\n    if (useCUDA) {\n        if (useCSR) {\n            cgSolveCSR(phi, divX, *mesh, 1e-8, -1);\n        } else {\n            cgSolve(phi, divX, *mesh, 1e-8, -1);\n        }\n        double residual = (L * phi - divX).norm();\n        if (residual > 1e-5)\n            cout << \"Residual 2: \" << residual << endl;\n    } else {\n        Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver;\n        solver.compute(L);\n        phi = solver.solve(divX);\n    }\n\n    for (int i = 0; i < phi.size(); ++i) {\n        distances[i] = phi[i];\n    }\n\n    double minDist = distances[0];\n    for (size_t i = 1; i < distances.size(); ++i) {\n        minDist = fmin(minDist, distances[i]);\n    }\n    for (size_t i = 0; i < distances.size(); ++i) {\n        distances[i] -= minDist;\n        assert(distances[i] >= 0);\n    }\n\n    return distances;\n}\n\nint main(int argc, char** argv) {\n\n    // Configure the argument parser\n    args::ArgumentParser parser(\"Geometry program\");\n    args::Positional<std::string> inputFilename(\n        parser, \"mesh\", \"Tet mesh (ele file) to be processed.\");\n    args::Positional<std::string> niceName(\n        parser, \"name\", \"Nice name for printed output.\");\n\n    // Parse args\n    try {\n        parser.ParseCLI(argc, argv);\n    } catch (args::Help) {\n        std::cout << parser;\n        return 0;\n    } catch (args::ParseError e) {\n        std::cerr << e.what() << std::endl;\n        std::cerr << parser;\n        return 1;\n    }\n\n    std::string filename = \"../../meshes/TetMeshes/bunny_small.1.ele\";\n    // Make sure a mesh name was given\n    if (inputFilename) {\n        filename = args::get(inputFilename);\n    }\n\n    std::string descriptionName = filename;\n    if (niceName) {\n        descriptionName = args::get(niceName);\n    }\n\n    mesh = TetMesh::loadFromFile(filename);\n    std::cout << descriptionName << \"\\t\" << mesh->tets.size();\n\n    std::cout << endl;\n    std::cout << \"CSR test: \" ;\n    testSolver(0, -1, true);\n    std::cout << \"non CSR test: \";\n    testSolver(0, -1, false);\n    std::cout << \"Done testing \" << endl;\n\n    std::clock_t start;\n    double duration;\n\n    start = std::clock();\n    computeDistances(0, -1, false);\n    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC * 1000;\n    std::cout<< \"\\t\" << duration;\n\n    start = std::clock();\n    computeDistances(0, -1, true, true);\n    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC * 1000;\n    std::cout<< \"\\tCSR: \" << duration;\n\n    start = std::clock();\n    computeDistances(0, -1, true, false);\n    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC * 1000;\n    std::cout<< \"\\tmine: \" << duration;\n\n    std::cout << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "c85a1332d2f6d9938d2fadd66cd5ce8cf4a94528", "size": 5896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "MarkGillespie/TetGeodesicsInHeat", "max_stars_repo_head_hexsha": "8787b00511734179ba20fab0258fc41a8d07229d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-13T00:27:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-13T00:27:16.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "MarkGillespie/TetGeodesicsInHeat", "max_issues_repo_head_hexsha": "8787b00511734179ba20fab0258fc41a8d07229d", "max_issues_repo_licenses": ["MIT"], "max_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": "MarkGillespie/TetGeodesicsInHeat", "max_forks_repo_head_hexsha": "8787b00511734179ba20fab0258fc41a8d07229d", "max_forks_repo_licenses": ["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.6281407035, "max_line_length": 100, "alphanum_fraction": 0.5681818182, "num_tokens": 1730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476800298183, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6106872841912367}}
{"text": "#include \"catch.hpp\"\n#include \"functions.hpp\"\n#include \"mwtrans_complex.hpp\"\n#include \"timer.hpp\"\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n#include <cmath>\n#include <complex>\n#include <fmt/format.h>\n\nusing complex_d = std::complex<double>;\nusing namespace std::literals::complex_literals;\nusing namespace boost::math::quadrature;\n\nbool is_equal(complex_d c1, complex_d c2, double eps = 1.0e-8) {\n  return std::abs(c1 - c2) < eps;\n}\n\nTEST_CASE(\"Case simple\", \"[test_complex]\") {\n  double error;\n  double a{0};\n  double b{1};\n  unsigned int max_depth = 0;\n  double tolerance = 0;\n  complex_d ret = gauss_kronrod<double, 61>::integrate(\n      func_simple, a, b, max_depth, tolerance, &error);\n  complex_d exact{0.5, 0.25};\n  REQUIRE(is_equal(ret, exact));\n}\n\nTEST_CASE(\"Case 1c\", \"[test_complex]\") {\n  double abserr = 1.0e-9;\n  double referr = 1.0e-7;\n  MWtransIntComplex mwt(0, 0, abserr, referr);\n  complex_d ret = mwt.perform(func_1c);\n  complex_d exact = -1.0 + 1.0i;\n  std::cout << ret << std::endl;\n  REQUIRE(is_equal(ret, exact));\n}\n", "meta": {"hexsha": "18da45c92cbd9ee70eadd7e812f0b2b14012ca37", "size": 1048, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test_complex.cc", "max_stars_repo_name": "pan3rock/mWOI", "max_stars_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_complex.cc", "max_issues_repo_name": "pan3rock/mWOI", "max_issues_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_complex.cc", "max_forks_repo_name": "pan3rock/mWOI", "max_forks_repo_head_hexsha": "47f544cd29020616d2dfb4ce01e09da27ccf84c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2, "max_line_length": 64, "alphanum_fraction": 0.6917938931, "num_tokens": 326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.6106872808051246}}
{"text": "//  ExoticBSEngineReverse.cpp\n\n//On the tractability of the Brownian Bridge algorithm, 2003, Leobacher, Scheicher\n//p.8 - 11\n\n\n#include <cmath>\n#include <algorithm>\n\n#include <boost\\numeric\\ublas\\matrix.hpp>\n//#include <boost\\numeric\\ublas\\lu.hpp>\n//#include <boost\\numeric\\ublas\\io.hpp>\n\n#include <ExoticBSEngineReverse.h>\n#include <stochastic_term.h>\n\nusing namespace std;\nusing namespace boost::numeric::ublas;\n\nvoid ExoticBSEngineReverse::GetOnePath(MJArray& LogSpotValues)\n{\n    TheGenerator->GetGaussians(Variates);\n    MJArray tmp = StochasticTerm(A, Variates);\n\n    double CurrentLogSpot = LogSpot;\n\n    for (unsigned long j=0; j < NumberOfTimes; j++){\n        CurrentLogSpot += Drifts[j];\n        CurrentLogSpot += StandardDeviations[j] * tmp[j];\n\t\t    LogSpotValues[j] = CurrentLogSpot;\n    }\n}\n\nExoticBSEngineReverse::ExoticBSEngineReverse(const Wrapper<PathDependent>& TheProduct_,\n                                    const Parameters& R_,\n                                    const Parameters& D_,\n                                    const Parameters& Vol_,\n                                    const Wrapper<RandomBase>& TheGenerator_,\n                                    double Spot_,\n\t\t\t\t\t\t\t\t\tbool speed_up_)\n                                    :\n                                    ExoticEngine(TheProduct_,R_,speed_up_),\n                                    TheGenerator(TheGenerator_)\n{\n    MJArray Times(TheProduct_->GetLookAtTimes());\n\n    NumberOfTimes = Times.size();\n\t  if (speed_up == true)\n\t\t  NumberOfTimes -= 1;\n\n    TheGenerator->ResetDimensionality(NumberOfTimes);\n\n    Drifts.resize(NumberOfTimes);\n    StandardDeviations.resize(NumberOfTimes);\n    A.resize(NumberOfTimes, NumberOfTimes);\n\n    //double Variance = Vol_.IntegralSquare(0,1);\n\n    Drifts[0] = R_.Integral(0.0,Times[0]) - D_.Integral(0.0,Times[0]) - 0.5 * Vol_.IntegralSquare(0.0,Times[0]);\n\tStandardDeviations[0] = sqrt(Vol_.IntegralSquare(0.0, 1.0));\n\n    for (unsigned long j=1; j < NumberOfTimes; ++j)\n    {\n        //double thisVariance = Vol_.IntegralSquare(0,1);\n        Drifts[j] = R_.Integral(Times[j-1],Times[j]) - D_.Integral(Times[j-1],Times[j])\n                    - 0.5 * Vol_.IntegralSquare(Times[j-1],Times[j]);\n\t\tStandardDeviations[j] = sqrt(Vol_.IntegralSquare(0.0, 1.0));\n    }\n\n    LogSpot = std::log(Spot_);\n    Variates.resize(NumberOfTimes);\n    method_ = logscale;\n\n    //--------------------------------------------------------------------------------\n\n    Matrix C(NumberOfTimes, NumberOfTimes);\n\n\t/*\n    for (size_t i(0); i < NumberOfTimes; ++i)\n      for (size_t j(0); j < NumberOfTimes; ++j)\n        C[i][j] = max(Times[i],Times[j]);\n\t*/\n\n\tfor (size_t i(0); i < NumberOfTimes; ++i){\n\t\tfor (size_t j(0); j < NumberOfTimes; ++j)\n\t\t\tC[i][j] = TheProduct_->GetLookAtTimes()[j];\n\t}\n\n\tfor (size_t j(1); j <NumberOfTimes; ++j){\n\t\tfor (size_t i(0); i < j; ++i)\n\t\t\tC[i][j] = TheProduct_->GetLookAtTimes()[i];\n\t}\n\n\n\t//std::cout << C << endl;\n\n    //Permutation matrix - reverse row order last row becoming the first one\n    Matrix P(NumberOfTimes, NumberOfTimes);\n\n\tfor (size_t i(0); i < NumberOfTimes; ++i)\n\t\tfor (size_t j(0); j < NumberOfTimes; ++j)\n\t\t\tP[i][j] = 0.0;\n\n\tfor (size_t i(0);i < NumberOfTimes;++i)\n\t\tP[NumberOfTimes - 1 - i][i] = 1.0;\n\n\t//std::cout << P << endl;\n\n\t//Matrix Pinv = inverse(P);\n\n\t//Inverse of permutation matrix Pinv = P\n\n\t//std::cout << Pinv << endl;\n\n    Matrix D = P * C * P;\n\n\t//std::cout << D << endl;\n\n\tMatrix E = CholeskyDecomposition(D);\n\n\tMatrix F = P * E;\n\n\t/*\n\t//Implement via LU decomposition. Resulting matrix not symmetric\n\n\tstd::copy(D.begin(), D.end(), A.begin2());\n\n\tpermutation_matrix<Size> pert(A.size1());\n\n\tconst Size singular = lu_factorize(A, pert); //overwrite A. Final A contains both L and U triangle\n\tQL_REQUIRE(singular == 0, \"singular matrix given\");\n\n\tfor (size_t i(0); i < NumberOfTimes; ++i)\n\t\tfor (size_t j(0); j < NumberOfTimes; ++j)\n\t\t\tA(i, j) = P[i][j] * A(i, j);\n\t*/\n    \n\tstd::copy(F.begin(), F.end(), A.begin2());\n\n\t//std::cout << A << endl;\n\n}\n", "meta": {"hexsha": "fd01d81b14198fa7ff5777f8440715ba54c3810e", "size": 4023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "library/source/ExoticBSEngineReverse.cpp", "max_stars_repo_name": "calvin456/intro_derivative_pricing", "max_stars_repo_head_hexsha": "0841fbc0344bee00044d67977faccfd2098b5887", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-12-28T16:07:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:55:57.000Z", "max_issues_repo_path": "library/source/ExoticBSEngineReverse.cpp", "max_issues_repo_name": "calvin456/intro_derivative_pricing", "max_issues_repo_head_hexsha": "0841fbc0344bee00044d67977faccfd2098b5887", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "library/source/ExoticBSEngineReverse.cpp", "max_forks_repo_name": "calvin456/intro_derivative_pricing", "max_forks_repo_head_hexsha": "0841fbc0344bee00044d67977faccfd2098b5887", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-06-04T04:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T17:41:16.000Z", "avg_line_length": 28.1328671329, "max_line_length": 112, "alphanum_fraction": 0.591349739, "num_tokens": 1132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6106872808051245}}
{"text": "// Std includes\n#include <cmath>\n#include <iostream>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"fl0w/simple_shear.h\"\n\nconst unsigned int DIM = 3;\n\nusing TypeScalar = double;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\nusing TypeMatrix = Eigen::Matrix<TypeScalar, DIM, DIM>;\ntemplate<typename... Args>\nusing TypeRef = Eigen::Ref<Args...>;\nusing TypeFlow = fl0w::SimpleShear<TypeVector, TypeMatrix, TypeRef>;\n\nvoid test(const TypeFlow& flow, const TypeVector& x, const TypeScalar& t) {\n    // Expected values\n    TypeVector xW;\n    xW << 0.0,\n          0.0,\n         -0.5;\n    TypeMatrix xS;\n    xS << 0.0, 0.5, 0.0,\n          0.5, 0.0, 0.0,\n          0.0, 0.0, 0.0;\n    // Output\n    TypeVector w = flow.getVorticity(x, t);\n    TypeMatrix S = flow.getStrain(x, t);\n    std::cout << std::endl;\n    std::cout << \"flow.getVorticity(\" << x.transpose() << \", \" << t << \") = \" << std::endl; \n    std::cout << w << std::endl;\n    std::cout << \"flow.getStrain(\" << x.transpose() << \", \" << t << \") = \" << std::endl; \n    std::cout << S << std::endl;\n    // Test Output\n    std::cout << std::endl;\n    std::cout << \"Test vorticity succeeded : \" << (w == xW) << std::endl; \n    std::cout << \"Test strain succeeded : \" << (S == xS) << std::endl; \n    std::cout << std::endl;\n    // Small temporary additional computations\n    std::cout << \"flow.getJacobian(\" << x.transpose() << \", \" << t << \") = \" << std::endl; \n    std::cout << flow.getJacobian(x, t) << std::endl;\n    TypeVector dir;\n    dir << 1.0,\n           0.0,\n           0.0;\n    std::cout << \"flow.getJacobian(\" << x.transpose() << \", \" << t << \") * \" << dir.transpose() << \" = \" << std::endl; \n    std::cout << flow.getJacobian(x, t).transpose() * dir  << std::endl;\n}\n\n\nvoid print(const TypeFlow& flow, const TypeVector& x, const TypeScalar& t) {\n    std::cout << std::endl;\n    std::cout << \"flow.getVelocity(\" << x.transpose() << \", \" << t << \") -> \" << flow.getVelocity(x, t).transpose() << std::endl;\n    std::cout << \"flow.getVorticity(\" << x.transpose() << \", \" << t << \") -> \" << flow.getVorticity(x, t).transpose() << std::endl;\n    std::cout << \"flow.getAcceleration(\" << x.transpose() << \", \" << t << \") -> \" << flow.getAcceleration(x, t).transpose() << std::endl;\n    std::cout << std::endl;\n}\n\nint main () { \n    TypeFlow flow;\n    flow.create(1.0);\n    TypeVector x;\n    double t;\n    // Init\n    x << 0.0, 0.0, 0.0;\n    t = 0.0;\n    test(flow, x, t);\n}\n", "meta": {"hexsha": "d9e3ae719575398ead0923f7ae4b2960b8c84459", "size": 2459, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/simple_shear/main.cpp", "max_stars_repo_name": "C0PEP0D/fl0w", "max_stars_repo_head_hexsha": "7e6b1ea0577d73ab98bfa10ae35e827d653cd1f1", "max_stars_repo_licenses": ["MIT"], "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/simple_shear/main.cpp", "max_issues_repo_name": "C0PEP0D/fl0w", "max_issues_repo_head_hexsha": "7e6b1ea0577d73ab98bfa10ae35e827d653cd1f1", "max_issues_repo_licenses": ["MIT"], "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/simple_shear/main.cpp", "max_forks_repo_name": "C0PEP0D/fl0w", "max_forks_repo_head_hexsha": "7e6b1ea0577d73ab98bfa10ae35e827d653cd1f1", "max_forks_repo_licenses": ["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.6338028169, "max_line_length": 137, "alphanum_fraction": 0.5461569744, "num_tokens": 789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6106872708117764}}
{"text": "//\n// Copyright (c) 2018 Stefan Seefeld\n// All rights reserved.\n//\n// This file is part of Boost.uBLAS. It is made available under the\n// Boost Software License, Version 1.0.\n// (Consult LICENSE or http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/program_options.hpp>\n#include \"../init.hpp\"\n#include \"../benchmark.hpp\"\n#include <complex>\n#include <string>\n\nnamespace po = boost::program_options;\nnamespace ublas = boost::numeric::ublas;\nnamespace boost { namespace numeric { namespace ublas { namespace benchmark {\n\ntemplate <typename T>\nclass prod : public benchmark\n{\npublic:\n  prod(std::string const &name) : benchmark(name) {}\n  virtual void setup(long l)\n  {\n    init(a, l, 200);\n    init(b, l, 200);\n  }\n  virtual void operation(long l)\n  {\n    for (int i = 0; i < l; ++i)\n      for (int j = 0; j < l; ++j)\n      {\n\tc(i,j) = 0;\n\tfor (int k = 0; k < l; ++k)\n\t  c(i,j) += a(i,k) * b(k,j);\n      }\n  }\nprivate:\n  ublas::matrix<T> a;\n  ublas::matrix<T> b;\n  ublas::matrix<T> c;\n};\n\n}}}}\n\nnamespace bm = boost::numeric::ublas::benchmark;\n\ntemplate <typename T>\nvoid benchmark(std::string const &type)\n{\n  //  using matrix = ublas::matrix<T, ublas::basic_row_major<>>;\n  bm::prod<T> p(\"ref::prod(matrix<\" + type + \">)\");\n  p.run(std::vector<long>({1, 2, 4, 8, 16, 32, 64, 128, 256, 512}));//, 1024}));\n}\n\nint main(int argc, char **argv)\n{\n  po::variables_map vm;\n  try\n  {\n    po::options_description desc(\"Matrix product (reference implementation)\\n\"\n                                 \"Allowed options\");\n    desc.add_options()(\"help,h\", \"produce help message\");\n    desc.add_options()(\"type,t\", po::value<std::string>(), \"select value-type (float, double, fcomplex, dcomplex)\");\n\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\"))\n    {\n      std::cout << desc << std::endl;\n      return 0;\n    }\n  }\n  catch(std::exception &e)\n  {\n    std::cerr << \"error: \" << e.what() << std::endl;\n    return 1;\n  }\n  std::string type = vm.count(\"type\") ? vm[\"type\"].as<std::string>() : \"float\";\n  if (type == \"float\")\n    benchmark<float>(\"float\");\n  else if (type == \"double\")\n    benchmark<double>(\"double\");\n  else if (type == \"fcomplex\")\n    benchmark<std::complex<float>>(\"std::complex<float>\");\n  else if (type == \"dcomplex\")\n    benchmark<std::complex<double>>(\"std::complex<double>\");\n  else\n    std::cerr << \"unsupported value-type \\\"\" << vm[\"type\"].as<std::string>() << '\\\"' << std::endl;\n}\n", "meta": {"hexsha": "4b436316795f0cb5f50b91f6db184499e8b716f3", "size": 2495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/benchmarks/reference/mm_prod.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/ublas/benchmarks/reference/mm_prod.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/ublas/benchmarks/reference/mm_prod.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 26.5425531915, "max_line_length": 116, "alphanum_fraction": 0.6024048096, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6106802380558062}}
{"text": "/*\n * randomNumberGenerator.hpp\n *\n *  Created on: Apr 29, 2016\n *      Author: jhwangbo\n */\n\n#ifndef RANDOMNUMBERGENERATOR_HPP_\n#define RANDOMNUMBERGENERATOR_HPP_\n\n// for random sampling\n#include <boost/random.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/math/distributions.hpp>\n#include <cstdlib>\n#include <mutex>\n#include <Eigen/Core>\n\nnamespace rai {\n\ntemplate<typename Dtype>\nclass RandomNumberGenerator {\n\n public:\n\n  RandomNumberGenerator() {\n//    distributionNormal = new boost::random::normal_distribution<Dtype>(0.0, 1.0);\n//    distributionUni = new boost::uniform_real<Dtype>(-1, 1);\n//    distributionUni01 = new boost::uniform_real<Dtype>(0, 1);\n  }\n\n  ~RandomNumberGenerator() {\n//    delete distributionNormal;\n//    delete distributionUni;\n//    delete distributionUni01;\n  }\n\n  /* mean =0, std = 1*/\n  Dtype sampleNormal() {\n    std::lock_guard<std::mutex> lockModel(rndMutex_);\n    auto dist = boost::random::normal_distribution<Dtype>(0.0, 1.0);\n    return dist(rngGenerator);\n  }\n\n  /* from -1 to 1*/\n  Dtype sampleUniform() {\n    auto dist = boost::uniform_real<Dtype>(-1, 1);\n    std::lock_guard<std::mutex> lockModel(rndMutex_);\n    return dist(rngGenerator);\n  }\n\n  /* from 0 to 1*/\n  Dtype sampleUniform01() {\n    auto dist = boost::uniform_real<Dtype>(0, 1);\n    std::lock_guard<std::mutex> lockModel(rndMutex_);\n    return dist(rngGenerator);\n  }\n\n  bool forXPercent(float epsilon) {\n    auto dist = boost::uniform_real<Dtype>(0, 1);\n    std::lock_guard<std::mutex> lockModel(rndMutex_);\n    return dist(rngGenerator) < epsilon;\n  }\n\n  int intRand(const int &min, const int &max) {\n    {\n      std::lock_guard<std::mutex> lockModel(rndMutex_);\n      std::uniform_int_distribution<int> distribution(min, max);\n      return distribution(rngGenerator);\n    }\n  }\n\n  /* weighted random sampling where the weights are given by 1, r, r^2, ... */\n  int intWeightedRand (const int &max, Dtype weightDecayFtr) {\n    Dtype sum = (Dtype(1) - std::pow(weightDecayFtr, max+1)) / (Dtype(1)-weightDecayFtr);\n    return std::ceil(log(Dtype(1) - sampleUniform01() * sum * (Dtype(1) - weightDecayFtr)) / log(weightDecayFtr)) - 1;\n  }\n\n  template<int dim>\n  void sampleVectorInNormalUniform(Dtype *vector) {\n    std::lock_guard<std::mutex> lockModel(rndMutex_);\n    auto dist = boost::uniform_real<Dtype>(-1, 1);\n    for (int i = 0; i < dim; i++)\n      vector[i] = dist(rngGenerator);\n  }\n\n  template<int dim>\n  void sampleInUnitSphere(Dtype *vector) {\n    sampleVectorInNormalUniform<dim>(vector);\n    Dtype sum = 0.0f;\n\n    for (int i = 0; i < dim; i++)\n      sum += vector[i] * vector[i];\n\n    Dtype amplitudeOverSum = pow(std::abs(sampleUniform()), Dtype(1.0) / Dtype(dim)) / sqrtf(sum);\n\n    for (int i = 0; i < dim; i++)\n      vector[i] = vector[i] * amplitudeOverSum;\n  }\n\n  template<int dim>\n  void sampleOnUnitSphere(Dtype *vector) {\n    sampleVectorInNormalUniform<dim>(vector);\n    Dtype sum = 0.0f;\n\n    for (int i = 0; i < dim; i++)\n      sum += vector[i] * vector[i];\n\n    for (int i = 0; i < dim; i++)\n      vector[i] = vector[i] / sqrtf(sum);\n  }\n\n  template<typename Derived>\n  void shuffleSTDVector(std::vector<Derived> &order) {\n    boost::variate_generator<boost::mt19937 &, boost::uniform_int<> >\n        random_number_shuffler(rngGenerator, boost::uniform_int<>());\n    std::random_shuffle(order.begin(), order.end(), random_number_shuffler);\n  }\n\n  /* this method is opitmized for memory use. The column should be dynamic size */\n  template<typename Derived, int Rows, int Cols>\n  void shuffleColumns(Eigen::Matrix<Derived, Rows, Cols> &matrix) {\n    int colSize = int(matrix.cols());\n\n    /// sampling the order\n    std::vector<int> order;\n    std::vector<bool> needSuffling(colSize, true);\n\n    order.resize(colSize);\n    for (int i = 0; i < colSize; i++) order[i] = i;\n    shuffleSTDVector(order);\n    Eigen::Matrix<Derived, Rows, 1> memoryCol(matrix.rows());\n\n    int colID;\n\n    for (int colStartID = 0; colStartID < colSize; colStartID++) {\n      if (order[colStartID] == colStartID || !needSuffling[colStartID]) continue;\n\n      colID = colStartID;\n      memoryCol = matrix.col(colID);\n      do {\n        matrix.col(colID) = matrix.col(order[colID]);\n        needSuffling[colID] = false;\n        colID = order[colID];\n      } while (colStartID != order[colID]);\n      matrix.col(colID) = memoryCol;\n      needSuffling[colID] = false;\n    }\n  }\n\n  std::vector<unsigned> getNrandomSubsetIdx (unsigned nOfElem, unsigned nOfSubElem) {\n    std::vector<unsigned> memoryIdx(nOfSubElem);\n    ///// randomly sampling memory indeces\n    for (unsigned i = 0; i < nOfSubElem; i++) {\n      memoryIdx[i] = intRand(0, nOfElem - 1);\n      for (unsigned j = 0; j < i; j++) {\n        if (memoryIdx[i] == memoryIdx[j]) {\n          i--;\n          break;\n        }\n      }\n    }\n    return memoryIdx;\n  }\n\n  /* this method is opitmized for memory use. The column should be dynamic size */\n  template<typename Derived1, int Rows1, int Cols1, typename Derived2, int Rows2, int Cols2>\n  void shuffleColumnsOfTwoMatrices(Eigen::Matrix<Derived1, Rows1, Cols1> &matrix1,\n                                   Eigen::Matrix<Derived2, Rows2, Cols2> &matrix2) {\n//    LOG_IF(FATAL, matrix1.cols() != matrix2.cols()) << \"two matrices have different number of columns\";\n\n    int colSize = int(matrix1.cols());\n\n    /// sampling the order\n    std::vector<int> order;\n    std::vector<bool> needSuffling(colSize, true);\n\n    order.resize(colSize);\n    for (int i = 0; i < colSize; i++) order[i] = i;\n    shuffleSTDVector(order);\n    Eigen::Matrix<Derived1, Rows1, 1> memoryCol1(matrix1.rows());\n    Eigen::Matrix<Derived2, Rows2, 1> memoryCol2(matrix2.rows());\n\n    int colID;\n\n    for (int colStartID = 0; colStartID < colSize; colStartID++) {\n      if (order[colStartID] == colStartID || !needSuffling[colStartID]) continue;\n\n      colID = colStartID;\n      memoryCol1 = matrix1.col(colID);\n      memoryCol2 = matrix2.col(colID);\n\n      do {\n        matrix1.col(colID) = matrix1.col(order[colID]);\n        matrix2.col(colID) = matrix2.col(order[colID]);\n\n        needSuffling[colID] = false;\n        colID = order[colID];\n      } while (colStartID != order[colID]);\n      matrix1.col(colID) = memoryCol1;\n      matrix2.col(colID) = memoryCol2;\n      needSuffling[colID] = false;\n    }\n  }\n\n  /* this method is opitmized for memory use. The column should be dynamic size */\n  template<typename Derived1, int Rows1, int Cols1, typename Derived2, int Rows2, int Cols2, typename Derived3, int Rows3, int Cols3>\n  void shuffleColumnsOfThreeMatrices(Eigen::Matrix<Derived1, Rows1, Cols1> &matrix1,\n                                     Eigen::Matrix<Derived2, Rows2, Cols2> &matrix2,\n                                     Eigen::Matrix<Derived3, Rows3, Cols3> &matrix3) {\n\n    int colSize = int(matrix1.cols());\n\n    /// sampling the order\n    std::vector<int> order;\n    std::vector<bool> needSuffling(colSize, true);\n\n    order.resize(colSize);\n    for (int i = 0; i < colSize; i++) order[i] = i;\n    shuffleSTDVector(order);\n\n    Eigen::Matrix<Derived1, Rows1, 1> memoryCol1(matrix1.rows());\n    Eigen::Matrix<Derived2, Rows2, 1> memoryCol2(matrix2.rows());\n    Eigen::Matrix<Derived3, Rows3, 1> memoryCol3(matrix3.rows());\n\n    int colID;\n\n    for (int colStartID = 0; colStartID < colSize; colStartID++) {\n      if (order[colStartID] == colStartID || !needSuffling[colStartID]) continue;\n\n      colID = colStartID;\n      memoryCol1 = matrix1.col(colID);\n      memoryCol2 = matrix2.col(colID);\n      memoryCol3 = matrix3.col(colID);\n      do {\n        matrix1.col(colID) = matrix1.col(order[colID]);\n        matrix2.col(colID) = matrix2.col(order[colID]);\n        matrix3.col(colID) = matrix3.col(order[colID]);\n        needSuffling[colID] = false;\n        colID = order[colID];\n      } while (colStartID != order[colID]);\n      matrix1.col(colID) = memoryCol1;\n      matrix2.col(colID) = memoryCol2;\n      matrix3.col(colID) = memoryCol3;\n      needSuffling[colID] = false;\n    }\n  }\n\n  /* this method is opitmized for memory use. The column should be dynamic size */\n  template<typename Derived1, int Rows1, int Cols1, typename Derived2, int Rows2, int Cols2, typename Derived3, int Rows3, int Cols3>\n  void shuffleColumnsOfFourMatrices(Eigen::Matrix<Derived1, Rows1, Cols1> &matrix1,\n                                     Eigen::Matrix<Derived2, Rows2, Cols2> &matrix2,\n                                     Eigen::Matrix<Derived3, Rows3, Cols3> &matrix3,\n                                     Eigen::Matrix<Derived3, Rows3, Cols3> &matrix4) {\n\n    int colSize = int(matrix1.cols());\n\n    /// sampling the order\n    std::vector<int> order;\n    std::vector<bool> needSuffling(colSize, true);\n\n    order.resize(colSize);\n    for (int i = 0; i < colSize; i++) order[i] = i;\n    shuffleSTDVector(order);\n\n    Eigen::Matrix<Derived1, Rows1, 1> memoryCol1(matrix1.rows());\n    Eigen::Matrix<Derived2, Rows2, 1> memoryCol2(matrix2.rows());\n    Eigen::Matrix<Derived3, Rows3, 1> memoryCol3(matrix3.rows());\n    Eigen::Matrix<Derived3, Rows3, 1> memoryCol4(matrix4.rows());\n\n    int colID;\n\n    for (int colStartID = 0; colStartID < colSize; colStartID++) {\n      if (order[colStartID] == colStartID || !needSuffling[colStartID]) continue;\n\n      colID = colStartID;\n      memoryCol1 = matrix1.col(colID);\n      memoryCol2 = matrix2.col(colID);\n      memoryCol3 = matrix3.col(colID);\n      memoryCol4 = matrix4.col(colID);\n\n      do {\n        matrix1.col(colID) = matrix1.col(order[colID]);\n        matrix2.col(colID) = matrix2.col(order[colID]);\n        matrix3.col(colID) = matrix3.col(order[colID]);\n        matrix4.col(colID) = matrix4.col(order[colID]);\n\n        needSuffling[colID] = false;\n        colID = order[colID];\n      } while (colStartID != order[colID]);\n      matrix1.col(colID) = memoryCol1;\n      matrix2.col(colID) = memoryCol2;\n      matrix3.col(colID) = memoryCol3;\n      matrix4.col(colID) = memoryCol4;\n\n      needSuffling[colID] = false;\n    }\n  }\n\n  /*you can use this method to make the random samples the same*/\n  static void seed(uint32_t seed) {\n    rngGenerator.seed(seed);\n  }\n\n private:\n  static boost::random::mt19937 rngGenerator;\n  static std::mutex rndMutex_;\n//  boost::random::normal_distribution<Dtype> *distributionNormal;\n//  boost::uniform_real<Dtype> *distributionUni, *distributionUni01;\n\n};\n\n}\n// Initialize the random number generator with a time-based seed instead of the default one.\ntemplate<typename Dtype>\nboost::random::mt19937 rai::RandomNumberGenerator<Dtype>::rngGenerator(time(NULL));\ntemplate<typename Dtype>\nstd::mutex rai::RandomNumberGenerator<Dtype>::rndMutex_;\n\n#endif /* RANDOMNUMBERGENERATOR_HPP_ */\n", "meta": {"hexsha": "c7515331380b530b66b56efb7392f0f859621d61", "size": 10680, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/raiCommon/utils/RandomNumberGenerator.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/utils/RandomNumberGenerator.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/utils/RandomNumberGenerator.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": 33.2710280374, "max_line_length": 133, "alphanum_fraction": 0.6452247191, "num_tokens": 2984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6106802313303834}}
{"text": "#include \"MishMesh/geodesics.h\"\n\n#include <MishMesh/laplace.h>\n#include <MishMesh/utils.h>\n#include <MishMesh/macros.h>\n\n#include <Eigen/Eigen>\n\n#include <vector>\n#include <cassert>\n\n/**\n * Compute geodesic distances on a mesh using the heat method by Crane, Wischedel and Wardetzky.\n * [Crane, K., Weischedel, C., and Wardetzky, M. (2013). Geodesics in Heat. ACM Trans. Graph. 32, 1-11.]\n * https://dl.acm.org/citation.cfm?id=2516977\n *\n * @param[inout] mesh The mesh.\n * @param[in] start_vh A valid vertex in the mesh, that will be used as start vertex.\n * @param[in] geodesicGeodesicDistanceProperty A mesh property to store the geodesic distances. The method assumes, that the property is already added to the mesh\n * @param[in] t The timestep for the heat diffusion step in the algorithm.\n */\nvoid MishMesh::compute_heat_geodesics(TriMesh &mesh, const TriMesh::VertexHandle start_vh, GeodesicDistanceProperty geodesicGeodesicDistanceProperty, double t) {\n\treturn compute_heat_geodesics(mesh, std::vector<TriMesh::VertexHandle>{start_vh}, geodesicGeodesicDistanceProperty, t);\n}\n\n/**\n * Compute geodesic distances on a mesh using the heat method by Crane, Wischedel and Wardetzky.\n * [Crane, K., Weischedel, C., and Wardetzky, M. (2013). Geodesics in Heat. ACM Trans. Graph. 32, 1-11.]\n * https://dl.acm.org/citation.cfm?id=2516977\n *\n * @param[inout] mesh The mesh.\n * @param[in] start_vhs A list of valid vertices in the mesh, that will be used as start vertices.\n * @param[in] geodesicGeodesicDistanceProperty A mesh property to store the geodesic distances. The method assumes, that the property is already added to the mesh\n * @param[in] t The timestep for the heat diffusion step in the algorithm.\n */\nvoid MishMesh::compute_heat_geodesics(TriMesh &mesh, const std::vector<TriMesh::VertexHandle> start_vhs, GeodesicDistanceProperty geodesicGeodesicDistanceProperty, double t) {\n\tif(start_vhs.empty()) return;\n\n\tmesh.request_face_normals();\n\tmesh.update_face_normals();\n\n\t// Lc is the laplacian without area weighting\n\tEigen::SparseMatrix<double> Lc = MishMesh::laplace_matrix(mesh, false, false);\n\n\t// Set the initial heat distribution\n\tEigen::VectorXd u0 = Eigen::VectorXd::Zero(mesh.n_vertices());\n\tfor(auto start_vh : start_vhs) {\n\t\tu0[start_vh.idx()] = 1.0;\n\t}\n\n\t// Calculate the vertex areas as 1/3 of the triangles around a vertex\n\tEigen::VectorXd vertex_areas(mesh.n_vertices());\n\tvertex_areas.setZero();\n\tfor(auto vh : mesh.vertices()) {\n\t\tFOR_CVF(f_it, vh) {\n\t\t\tvertex_areas[vh.idx()] += MishMesh::compute_area(mesh, *f_it);\n\t\t}\n\t\tvertex_areas[vh.idx()] /= 3.0;\n\t}\n\n\t// Calculate A - t*L_c\n\tEigen::SparseMatrix<double> A_tLc = -t * Lc;\n\tassert(A_tLc.rows() == A_tLc.cols());\n\tfor(int i = 0; i < A_tLc.rows(); i++){\n\t\tA_tLc.coeffRef(i, i) += vertex_areas[i];\n\t};\n\tassert(A_tLc.isCompressed());\n\n\t// Compute one heat diffusion timestep\n\tEigen::SparseLU<Eigen::SparseMatrix<double>> luSolver;\n\tluSolver.compute(A_tLc);\n\tEigen::VectorXd u = luSolver.solve(u0);\n\n\t// Calculate the gradients on the faces\n\tstd::vector<OpenMesh::Vec3d> face_grad_u(mesh.n_faces(), OpenMesh::Vec3d(0,0,0));\n\tfor(auto fh : mesh.faces()) {\n\t\tOpenMesh::Vec3d &x = face_grad_u[fh.idx()];\n\t\tconst OpenMesh::Vec3d &N = mesh.normal(fh);\n\t\tFOR_CFV(v_it, fh) {\n\t\t\tauto vh = *v_it;\n\t\t\tauto heh = MishMesh::opposite_halfedge(mesh, fh, vh);\n\t\t\tOpenMesh::Vec3d ei = mesh.point(mesh.to_vertex_handle(heh)) - mesh.point(mesh.from_vertex_handle(heh));\n\t\t\tx += u[v_it->idx()] * (N % ei);\n\t\t}\n\t\tx /= 2 * MishMesh::compute_area(mesh, fh);\n\t}\n\n\t// Calculate the divergence at the vertices\n\tEigen::VectorXd vertex_div_u = Eigen::VectorXd::Zero(mesh.n_vertices());\n\tfor(auto vh : mesh.vertices()) {\n\t\tauto pi = mesh.point(vh);\n\t\tdouble &div = vertex_div_u[vh.idx()];\n\t\tFOR_CVOH(h_it, vh) {\n\t\t\t// The edge and the next edge belong to a common face,\n\t\t\t// except when the current edge is a boundary edge. In that case\n\t\t\t// we skip it, as it will be the next_heh of another halfedge later.\n\t\t\tauto heh = *h_it;\n\t\t\tif(mesh.is_boundary(heh)) continue;\n\t\t\tauto next_h_it = h_it;\n\t\t\tnext_h_it++;\n\t\t\tauto next_heh = *next_h_it;\n\n\t\t\tassert(mesh.face_handle(heh) == mesh.face_handle(mesh.opposite_halfedge_handle(next_heh)));\n\t\t\tauto fh = mesh.face_handle(heh);\n\n\t\t\tauto p1 = mesh.point(mesh.to_vertex_handle(heh));\n\t\t\tauto p2 = mesh.point(mesh.to_vertex_handle(next_heh));\n\t\t\tOpenMesh::Vec3d e1 = (p1 - pi);\n\t\t\tOpenMesh::Vec3d e2 = (p2 - pi);\n\t\t\tOpenMesh::Vec3d e3 = (p2 - p1);\n\t\t\tOpenMesh::Vec3d X_face = -face_grad_u[fh.idx()] / face_grad_u[fh.idx()].norm();\n\n\t\t\tdouble angle1 = acos((-e3.normalized()) | (-e2.normalized()));\n\t\t\tdouble angle2 = acos(e3.normalized() | (-e1.normalized()));\n\n\t\t\tdiv += (1.0 / tan(angle1)) * (e1 | X_face) + (1.0 / tan(angle2)) * (e2 | X_face);\n\t\t}\n\t\tdiv /= 2.0;\n\t}\n\n\t// The distance of the source vertex is always 0, so we can use it as boundary condition\n\t// to get an unique solution of the poisson equation.\n\tstd::vector<std::pair<Eigen::Index, double>> bc{std::make_pair(start_vhs[0].idx(), 0.0)};\n\tMishMesh::apply_boundary_conditions(Lc, vertex_div_u, bc);\n\tluSolver.compute(Lc);\n\tEigen::VectorXd phi = luSolver.solve(vertex_div_u);\n\tfor(auto vh : mesh.vertices()) {\n\t\tmesh.property(geodesicGeodesicDistanceProperty, vh) = phi[vh.idx()];\n\t}\n\n\tmesh.release_face_normals();\n}\n", "meta": {"hexsha": "97f8692a8db7e339dafc4d58411055cde805839b", "size": 5276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/heatGeodesics.cpp", "max_stars_repo_name": "aschier/MishMesh", "max_stars_repo_head_hexsha": "6128e33501935b57c80c7e0816aa1b2229907990", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-15T11:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T02:30:47.000Z", "max_issues_repo_path": "src/heatGeodesics.cpp", "max_issues_repo_name": "aschier/MishMesh", "max_issues_repo_head_hexsha": "6128e33501935b57c80c7e0816aa1b2229907990", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/heatGeodesics.cpp", "max_forks_repo_name": "aschier/MishMesh", "max_forks_repo_head_hexsha": "6128e33501935b57c80c7e0816aa1b2229907990", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-26T13:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-26T13:25:28.000Z", "avg_line_length": 39.6691729323, "max_line_length": 175, "alphanum_fraction": 0.7075435936, "num_tokens": 1569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6106640815762944}}
{"text": "// Copyright (c) Dietmar Wolz.\r\n//\r\n// This source code is licensed under the MIT license found in the\r\n// LICENSE file in the root directory.\r\n\r\n// Eigen based implementation of the Harris hawks optimization, see\r\n// Harris hawks optimization: Algorithm and applications\r\n// Ali Asghar Heidari, Seyedali Mirjalili, Hossam Faris, Ibrahim Aljarah, Majdi Mafarja, Huiling Chen\r\n// Future Generation Computer Systems, \r\n// DOI: https://doi.org/10.1016/j.future.2019.02.028\r\n\r\n// derived from https://github.com/7ossam81/EvoloPy/blob/master/optimizers/HHO.py\r\n\r\n#include <Eigen/Core>\r\n#include <iostream>\r\n#include <float.h>\r\n#include <math.h>\r\n#include <ctime>\r\n#include <random>\r\n#include \"pcg_random.hpp\"\r\n\r\nusing namespace std;\r\n\r\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> vec;\r\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat;\r\n\r\ntypedef double (*callback_type)(int, double[]);\r\n\r\nnamespace harris_hawks {\r\n\r\nstatic uniform_real_distribution<> distr_01 = std::uniform_real_distribution<>(0, 1);\r\nstatic normal_distribution<> gauss_01 = std::normal_distribution<>(0, 1);\r\n\r\nstatic vec zeros(int n) {\r\n\treturn  Eigen::MatrixXd::Zero(n, 1);\r\n}\r\n\r\nstatic Eigen::MatrixXd uniform(int dx, int dy, pcg64& rs) {\r\n\treturn Eigen::MatrixXd::NullaryExpr( dx, dy, [&](){return distr_01(rs);});\r\n}\r\n\r\nstatic Eigen::MatrixXd normalVec(int dim, pcg64& rs) {\r\n\treturn Eigen::MatrixXd::NullaryExpr( dim, 1, [&](){return gauss_01(rs);});\r\n}\r\n\r\n// wrapper around the fittness function, scales according to boundaries\r\n\r\nclass Fittness {\r\n\r\npublic:\r\n\r\n    Fittness(callback_type pfunc, const vec& lower_limit,\r\n            const vec& upper_limit) {\r\n        func = pfunc;\r\n        lower = lower_limit;\r\n        upper = upper_limit;\r\n        evaluationCounter = 0;\r\n        if (lower.size() > 0) // bounds defined\r\n            scale = (upper - lower);\r\n    }\r\n\r\n    vec getClosestFeasible(const vec& X) const {\r\n        if (lower.size() > 0) {\r\n        \treturn X.cwiseMin(1.0).cwiseMax(0.0);\r\n        }\r\n        return X;\r\n    }\r\n\r\n    double eval(const vec& X) {\r\n        int n = X.size();\r\n        double parg[n];\r\n        for (int i = 0; i < n; i++)\r\n            parg[i] = X(i);\r\n        double res = func(n, parg);\r\n        evaluationCounter++;\r\n        return res;\r\n    }\r\n\r\n    double value(const vec& X) {\r\n        if (lower.size() > 0)\r\n            return eval(decode(X));\r\n        else\r\n            return eval(X);\r\n    }\r\n\r\n\tvec decode(const vec& X) const {\r\n\t\tif (lower.size() > 0)\r\n\t\t\treturn (X.array() * scale.array()).matrix() + lower;\r\n\t\telse\r\n\t\t\treturn X;\r\n\t}\r\n\r\n    vec encode(const vec& X) const {\r\n        if (lower.size() > 0)\r\n        \treturn (X - lower).array() / scale.array();\r\n        else\r\n            return X;\r\n    }\r\n\r\n    int getEvaluations() {\r\n        return evaluationCounter;\r\n    }\r\n\r\nprivate:\r\n   callback_type func;\r\n   vec lower;\r\n   vec upper;\r\n   long evaluationCounter;\r\n   vec scale;\r\n};\r\n\r\nclass HHOptimizer {\r\n\r\npublic:\r\n\r\n    HHOptimizer(long runid_, Fittness* fitfun_, int dim_, int seed_, int popsize_, \r\n            int maxEvaluations_, double stopfitness_) {\r\n        // runid used to identify a specific run\r\n        runid = runid_;\r\n        // fitness function to minimize\r\n        fitfun = fitfun_;\r\n        // Number of objective variables/problem dimension\r\n        dim = dim_;\r\n        // Population size\r\n        if (popsize_ > 0)\r\n            popsize = popsize_;\r\n        else\r\n            popsize = 31;\r\n        // termination criteria\r\n        // maximal number of evaluations allowed.\r\n        maxEvaluations = maxEvaluations_;\r\n        // Limit for fitness value.\r\n        stopfitness = stopfitness_;\r\n        // Number of iterations already performed.\r\n        iterations = 0;\r\n         // stop criteria\r\n        stop = 0;\r\n        //std::random_device rd;\r\n        rs = new pcg64(seed_);\r\n        init();\r\n    }\r\n\r\n    ~HHOptimizer() {\r\n    \tdelete rs;\r\n    }\r\n\r\n    double rnd01() {\r\n        return distr_01(*rs);\r\n    }\r\n \r\n    vec levy(int dim) {\r\n        double beta = 1.5;\r\n        double sigma = pow ((tgamma(1+beta)*sin(M_PI*beta/2)/(tgamma((1+beta)/2) * beta * pow(2,((beta-1)/2))) ), (1/beta));\r\n        vec u = 0.01*normalVec(dim, *rs)*sigma;\r\n        vec v = normalVec(dim, *rs).cwiseAbs();\r\n        vec zz = v.array().pow( vec::Constant(dim, 1.0/beta).array());\r\n        vec step = u.cwiseProduct(zz.cwiseInverse());\r\n        return step;\r\n    }\r\n\r\n    void doOptimize() {\r\n    \r\n        // -------------------- Generation Loop --------------------------------\r\n\r\n        for (iterations = 1; fitfun->getEvaluations() < maxEvaluations; iterations++) {\r\n\r\n            // fitness of locations\r\n            for (int i = 0; i < popsize; i++) {\r\n                popX.col(i) = fitfun->getClosestFeasible(popX.col(i));\r\n                double y = fitfun->value(popX.col(i)); // compute fitness\r\n                if (!isfinite(y)) {\r\n                    stop = -1;\r\n                    return;\r\n                }\r\n                if (y < bestY) {\r\n                    // update the location of Rabbit\r\n                    bestY = y;\r\n                    bestX = popX.col(i);\r\n                }\r\n            }\r\n            double e1 = 2*(1-((iterations-1)/maxIter)); // factor to decrease the energy of the rabbit\r\n            \r\n            // Update the location of the harris hawks \r\n           for (int i = 0; i < popsize; i++) {\r\n                double e0 = 2*rnd01()-1;  // -1<e0<1\r\n                vec xi = popX.col(i);\r\n                double escapingEnergy = e1*e0; // escaping energy of rabbit Eq. (3) in the paper\r\n\r\n                // -------- Exploration phase Eq. (1) in paper -------------------\r\n\r\n                if (abs(escapingEnergy) >= 1) {\r\n                    // harris hawks perch randomly based on 2 strategy:\r\n                    double q = rnd01();\r\n                    int randHawkIndex = (int)(popsize*rnd01());\r\n                    vec xr = popX.col(randHawkIndex);\r\n                    if (q < 0.5)\r\n                        // perch based on other family members\r\n                    \tpopX.col(i) = xr - rnd01() * (xr - 2*rnd01()*xi).cwiseAbs();\r\n\r\n                    else {\r\n                        // perch on a random tall tree (random site inside group's home range)\r\n                        vec xmean = popX.rowwise().mean();\r\n                        vec rvec = vec::Constant(dim, rnd01());\r\n                        popX.col(i) = (bestX - xmean) - rnd01()*rvec;\r\n                    }\r\n                }\r\n                // -------- Exploitation phase -------------------\r\n                else {\r\n                    //Attacking the rabbit using 4 strategies regarding the behavior of the rabbit\r\n\r\n                    //phase 1: ----- surprise pounce (seven kills) ----------\r\n                    // multiple, short rapid dives by different hawks\r\n\r\n                    double r = rnd01(); // probability of each event\r\n                    \r\n                    if (r >= 0.5 && abs(escapingEnergy) < 0.5)  // Hard besiege Eq. (6) in paper\r\n                        popX.col(i) = bestX - escapingEnergy*(bestX - xi).cwiseAbs();\r\n\r\n                    if (r >= 0.5 && abs(escapingEnergy) >= 0.5) {  // Soft besiege Eq. (4) in paper\r\n                        double jumpStrength = 2*(1- rnd01()); // random jump strength of the rabbit\r\n                        popX.col(i) = (bestX-popX.col(i)) - escapingEnergy*(jumpStrength*bestX-xi).cwiseAbs();\r\n                    }\r\n                    // phase 2: --------performing team rapid dives (leapfrog movements)----------\r\n\r\n                    if (r < 0.5 && abs(escapingEnergy) >= 0.5) { // Soft besiege Eq. (10) in paper\r\n                        // rabbit try to escape by many zigzag deceptive motions\r\n                        double jumpStrength = 2 * (1-rnd01());\r\n                        vec x1 = fitfun->getClosestFeasible(\r\n                        \t\tbestX-escapingEnergy*(jumpStrength*bestX-xi).cwiseAbs());\r\n                        double y1 = fitfun->value(x1);\r\n                        if (y1 < bestY) // improved move?\r\n                            popX.col(i) = x1;\r\n                        else { // hawks perform levy-based short rapid dives around the rabbit\r\n                            vec x2 = fitfun->getClosestFeasible(\r\n                            \t\tbestX-escapingEnergy*(jumpStrength*bestX-xi).cwiseAbs() +\r\n                            \t\tnormalVec(dim, *rs).cwiseProduct(levy(dim)));\r\n                            double y2 = fitfun->value(x2);\r\n                            if ( y2 < bestY )\r\n                                popX.col(i) = x2;\r\n                        }\r\n                    }\r\n                    if (r < 0.5 && abs(escapingEnergy) < 0.5) {  // Hard besiege Eq. (11) in paper\r\n                         double jumpStrength = 2 * (1-rnd01());\r\n                         vec xmean = popX.rowwise().mean();\r\n                         vec x1 = fitfun->getClosestFeasible(\r\n                        \t\t bestX - escapingEnergy * (jumpStrength * bestX-xmean).cwiseAbs());\r\n                         \r\n                         if (fitfun->value(x1) < bestY) // improved move?\r\n                            popX.col(i) = x1;\r\n                         else { // Perform levy-based short rapid dives around the rabbit\r\n                             vec x2 = fitfun->getClosestFeasible(\r\n                            \t\t bestX - escapingEnergy * (jumpStrength*bestX - xmean).cwiseAbs() +\r\n                            \t\t normalVec(dim, *rs).cwiseProduct(levy(dim)));\r\n                            double y2 = fitfun->value(x2);\r\n                            if ( y2 < bestY )\r\n                                popX.col(i) = x2; \r\n                         }\r\n                    } \r\n                }\r\n                if (isfinite(stopfitness) && bestY < stopfitness) {\r\n                    stop = 1;\r\n                    return;\r\n                }\r\n            }             \r\n        }\r\n    }\r\n \r\n    void init() {\r\n        // initialize the locations of the harris hawks\r\n        popX = uniform(dim, popsize, *rs);\r\n        // initialize the location and energy of the rabbit\r\n        bestX = zeros(popsize);\r\n        bestY = DBL_MAX;\r\n        maxIter = maxEvaluations / popsize;\r\n    }\r\n    \r\n    vec getBestX() {\r\n        return bestX;\r\n    }\r\n\r\n    double getBestValue() {\r\n        return bestY;\r\n    }\r\n\r\n    double getIterations() {\r\n        return iterations;\r\n    }\r\n\r\n    double getStop() {\r\n        return stop;\r\n    }\r\n\r\nprivate:\r\n      long runid;\r\n      Fittness* fitfun;\r\n      int popsize; // population size\r\n      int dim;\r\n      int maxEvaluations;\r\n      int maxIter;\r\n      double stopfitness;\r\n      int iterations;\r\n      double guessValue;\r\n      vec guess;\r\n      double bestY;\r\n      vec bestX;\r\n      int stop;\r\n      pcg64* rs;\r\n      mat popX;\r\n      vec popY;\r\n};\r\n\r\n}\r\n\r\nusing namespace harris_hawks;\r\n\r\nextern \"C\" {\r\n    double* optimizeHH_C(long runid, callback_type func, int dim, int seed,\r\n            double *lower, double *upper, int maxEvals, \r\n            double stopfitness, int popsize) {\r\n        int n = dim;\r\n        double *res = new double[n + 4];\r\n        vec lower_limit(n), upper_limit(n);\r\n        bool useLimit = false;\r\n        for (int i = 0; i < n; i++) {\r\n            lower_limit[i] = lower[i];\r\n            upper_limit[i] = upper[i];\r\n            useLimit |= (lower[i] != 0);\r\n            useLimit |= (upper[i] != 0);\r\n        }\r\n        if (useLimit == false) {\r\n            lower_limit.resize(0);\r\n            upper_limit.resize(0);\r\n        } \r\n        Fittness fitfun(func, lower_limit, upper_limit);\r\n        HHOptimizer opt(\r\n            runid,\r\n            &fitfun,\r\n            dim,\r\n            seed,\r\n            popsize,\r\n            maxEvals,\r\n            stopfitness\r\n            );\r\n        try {\r\n            opt.doOptimize();\r\n            vec bestX = fitfun.decode(opt.getBestX());\r\n            double bestY = opt.getBestValue();\r\n            for (int i = 0; i < n; i++)\r\n                res[i] = bestX[i];\r\n            res[n] = bestY;\r\n            res[n+1] = fitfun.getEvaluations();\r\n            res[n+2] = opt.getIterations();\r\n            res[n+3] = opt.getStop();\r\n            return res;\r\n        } catch (std::exception& e) {\r\n            cout << e.what() << endl;\r\n            return res;\r\n        }\r\n    }\r\n}\r\n", "meta": {"hexsha": "33828b2cd052ba47cc6376c07aeb9b332e15b730", "size": 12354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_fcmaescpp/hawksoptimizer.cpp", "max_stars_repo_name": "MingchengZuo/fast-cma-es", "max_stars_repo_head_hexsha": "ada34f50b93d52493d768ad67addaf915f9e0d2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-07T08:43:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-07T08:43:49.000Z", "max_issues_repo_path": "_fcmaescpp/hawksoptimizer.cpp", "max_issues_repo_name": "MingchengZuo/fast-cma-es", "max_issues_repo_head_hexsha": "ada34f50b93d52493d768ad67addaf915f9e0d2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_fcmaescpp/hawksoptimizer.cpp", "max_forks_repo_name": "MingchengZuo/fast-cma-es", "max_forks_repo_head_hexsha": "ada34f50b93d52493d768ad67addaf915f9e0d2f", "max_forks_repo_licenses": ["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.2216066482, "max_line_length": 125, "alphanum_fraction": 0.4803302574, "num_tokens": 2907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.610662203655739}}
{"text": "#pragma once\n\n#include \"base.hpp\"\n\n#include <Eigen/Geometry>\n#include <cmath>\n#include <limits>\n\ntemplate <typename Scalar>\nclass QuaternionElement final\n    : public ManifoldElement<QuaternionElement<Scalar>, Scalar, 3>\n{\n public:\n  using Base = ManifoldElement<QuaternionElement<Scalar>, Scalar, 3>;\n  using TangentVec = typename Base::TangentVec;\n\n  using Quat = Eigen::Quaternion<Scalar>;\n  using ElementType = Quat;\n\n  QuaternionElement(const Quat &q = Quat::Identity()) : quat_{q} {}\n\n  Quat const &getValue() const { return quat_; }\n  void setValue(const Quat &q) { quat_ = q; }\n\n  QuaternionElement operator+(const TangentVec &diff) const override\n  {\n    return QuaternionElement(quat_ * vec_to_quat(diff));\n  }\n\n  TangentVec operator-(const QuaternionElement &q) const override\n  {\n    return quat_to_vec(q.getValue().conjugate() * quat_);\n  }\n\n  static TangentVec angle_axis_to_vec(const Scalar &angle,\n                                      const Eigen::Matrix<Scalar, 3, 1> &axis)\n  {\n    return axis * angle;\n  }\n\n  friend std::ostream &operator<<(std::ostream &stream,\n                                  const QuaternionElement &element)\n  {\n    stream << element.quat_.coeffs().transpose();\n    return stream;\n  }\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n private:\n  static TangentVec quat_to_vec(const Quat &q)\n  {\n    const auto q_vec_norm = q.vec().norm();\n    if(q_vec_norm < 10 * std::numeric_limits<Scalar>::epsilon())\n      return TangentVec::Zero();\n    else\n    {\n      const Scalar sign = (q.w() >= 0) ? 1 : -1;\n      return 2 * std::atan2(q_vec_norm, sign * q.w()) * sign * q.vec() /\n             q_vec_norm;\n    }\n  }\n\n  static Quat vec_to_quat(const TangentVec &vec)\n  {\n    const auto v_norm = vec.norm();\n    if(v_norm < 10 * std::numeric_limits<Scalar>::epsilon())\n      return Quat::Identity();\n\n    Quat q;\n    q.w() = std::cos(v_norm / 2);\n    q.vec() = std::sin(v_norm / 2) * vec / v_norm;\n    return q;\n  }\n\n  Quat quat_;\n};\n", "meta": {"hexsha": "723bea18ef601f58509206e274f6a5f8464d2cda", "size": 1955, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/manifold_cdkf/element_types/quaternion.hpp", "max_stars_repo_name": "kartikmohta/manifold_cdkf", "max_stars_repo_head_hexsha": "e000ca7ab24721f300ab2d0737e2a2d9cc0db912", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-03-04T03:29:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T12:58:20.000Z", "max_issues_repo_path": "include/manifold_cdkf/element_types/quaternion.hpp", "max_issues_repo_name": "kartikmohta/manifold_cdkf", "max_issues_repo_head_hexsha": "e000ca7ab24721f300ab2d0737e2a2d9cc0db912", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/manifold_cdkf/element_types/quaternion.hpp", "max_forks_repo_name": "kartikmohta/manifold_cdkf", "max_forks_repo_head_hexsha": "e000ca7ab24721f300ab2d0737e2a2d9cc0db912", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-11-12T13:04:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T23:04:34.000Z", "avg_line_length": 25.0641025641, "max_line_length": 78, "alphanum_fraction": 0.6352941176, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.610553212652685}}
{"text": "#ifndef ALM_PSEUDOINVERSE\n#define ALM_PSEUDOINVERSE\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <vector>\n\nnamespace math_utils{ \n  void pseudoInverse(const Eigen::MatrixXd & A,\n                     Eigen::MatrixXd & Apinv,\n                     double tolerance,\n                     unsigned int computationOptions = Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n  void pseudoInverse(const Eigen::MatrixXd & A,\n                     Eigen::MatrixXd & Apinv,\n                     std::vector<double> & singular_values,\n                     double tolerance,\n                     unsigned int computationOptions = Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n  void pseudoInverse(const Eigen::MatrixXd & A,\n                     Eigen::JacobiSVD<Eigen::MatrixXd>& svdDecomposition,\n                     Eigen::MatrixXd & Apinv,\n                     double tolerance,\n                     unsigned int computationOptions = Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n  void weightedPseudoInverse(const Eigen::MatrixXd & J, const Eigen::MatrixXd & Winv,\n                             Eigen::MatrixXd & Jinv, double tolerance);\n  \n  void weightedPseudoInverse(const Eigen::MatrixXd & J, const Eigen::MatrixXd & Winv,\n                          Eigen::JacobiSVD<Eigen::MatrixXd> & svdDecomposition,\n                          Eigen::MatrixXd & Jinv, \n                          double tolerance);\n\n}\n#endif\n", "meta": {"hexsha": "06dcd009826fb82c622f0febb6a5be4122016706", "size": 1405, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/avatar_locomanipulation/helpers/pseudo_inverse.hpp", "max_stars_repo_name": "stevenjj/icra2020locomanipulation", "max_stars_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-01-06T11:43:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T22:59:09.000Z", "max_issues_repo_path": "include/avatar_locomanipulation/helpers/pseudo_inverse.hpp", "max_issues_repo_name": "stevenjj/icra2020locomanipulation", "max_issues_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/avatar_locomanipulation/helpers/pseudo_inverse.hpp", "max_forks_repo_name": "stevenjj/icra2020locomanipulation", "max_forks_repo_head_hexsha": "414085b68cc1b3b24f7b920b543bba9d95350c16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T16:08:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T11:13:49.000Z", "avg_line_length": 39.0277777778, "max_line_length": 98, "alphanum_fraction": 0.5857651246, "num_tokens": 279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6105532126526849}}
{"text": "#include \"solver/constrained_l1_solver.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <glog/logging.h>\n\n#include <algorithm>\n#include <string>\n\n#include \"math/sparse_cholesky_llt.h\"\n#include \"util/stringprintf.h\"\n\nnamespace GraphSfM {\n\nConstrainedL1Solver::ConstrainedL1Solver(\n    const Options& options,\n    const Eigen::SparseMatrix<double>& A,\n    const Eigen::VectorXd& b,\n    const Eigen::SparseMatrix<double>& geq_mat,\n    const Eigen::VectorXd& geq_vec)\n    : options_(options),\n      num_l1_residuals_(b.size()),\n      num_inequality_constraints_(geq_vec.size()) {\n  CHECK_EQ(A.cols(), geq_mat.cols());\n  CHECK_EQ(A.rows(), b.rows());\n  CHECK_EQ(geq_mat.rows(), geq_vec.rows());\n\n  // Allocate matrix A.\n  A_.resize(A.rows() + geq_mat.rows(), A.cols());\n\n  // Iterate over the input mat and geq_mat and store the entries in A.\n  std::vector<Eigen::Triplet<double> > triplets;\n  triplets.reserve(A.nonZeros() + geq_mat.nonZeros());\n  for (int i = 0; i < A.outerSize(); i++) {\n    for (Eigen::SparseMatrix<double>::InnerIterator it(A, i); it; ++it) {\n      triplets.emplace_back(it.row(), it.col(), it.value());\n    }\n  }\n  // Store the Geq mat below matrix A.\n  for (int i = 0; i < geq_mat.outerSize(); i++) {\n    // Iterate over inside\n    for (Eigen::SparseMatrix<double>::InnerIterator it(geq_mat, i); it; ++it) {\n      triplets.emplace_back(A.rows() + it.row(), it.col(), it.value());\n    }\n  }\n  A_.setFromTriplets(triplets.begin(), triplets.end());\n\n  Eigen::SparseMatrix<double> spd_mat(A.cols(), A.cols());\n  spd_mat.selfadjointView<Eigen::Upper>().rankUpdate(A_.transpose());\n\n  linear_solver_.Compute(spd_mat);\n  CHECK_EQ(linear_solver_.Info(), Eigen::Success);\n\n  // Set the modified b vector.\n  b_.resize(b.size() + geq_vec.size());\n  b_.head(b.size()) = b;\n  b_.tail(geq_vec.size()) = geq_vec;\n}\n\n// We create a modified L1 solver such that ||Bx - b|| is minimized under L1\n// norm subject to the constraint geq_mat * x > geq_vec. We conveniently\n// create this constraint in ADMM terms as:\n//\n//    minimize f(x) + g(z_1) + h(z_2)\n//    s.t. Bx - b - z_1 = 0\n//         Cx - c - z_2 = 0\n//\n// Where f(x) = 0, g(z_1) = |z_1| and h(z_2) is an indicate function for our\n// inequality constraint. This can be transformed into the standard ADMM\n// formulation as:\n//\n//    minimize f(x) + g(z)\n//    s.t. A * x - d - z = 0\n//\n// where A = [B;C] and d=[b;c] (where ; is the \"stack\" operation like matlab)\n// This can now be solved in the same form as the L1 minimization, with a\n// slightly different z update.\nvoid ConstrainedL1Solver::Solve(Eigen::VectorXd* solution) {\n  CHECK_NOTNULL(solution)->resize(A_.cols());\n  Eigen::VectorXd& x = *solution;\n  Eigen::VectorXd z(A_.rows()), u(A_.rows());\n  z.setZero();\n  u.setZero();\n\n  Eigen::VectorXd a_times_x(A_.rows()), z_old(z.size()), ax_hat(A_.rows());\n  // Precompute some convergence terms.\n  const double rhs_norm = b_.norm();\n  const double primal_abs_tolerance_eps =\n      std::sqrt(A_.rows()) * options_.absolute_tolerance;\n  const double dual_abs_tolerance_eps =\n      std::sqrt(A_.cols()) * options_.absolute_tolerance;\n  VLOG(2) << \"Iteration   R norm          S norm          Primal eps      \"\n             \"Dual eps\";\n  const std::string row_format =\n      \"  % 4d     % 4.4e     % 4.4e     % 4.4e     % 4.4e\";\n\n  // qp_options.max_num_iterations = 100;\n  for (int i = 0; i < options_.max_num_iterations; i++) {\n    x.noalias() = linear_solver_.Solve(A_.transpose() * (b_ + z - u));\n\n    if (linear_solver_.Info() != Eigen::Success) {\n      LOG(ERROR) << \"L1 Minimization failed. Could not solve the sparse \"\n                    \"linear system with Cholesky Decomposition\";\n      return;\n    }\n\n    a_times_x.noalias() = A_ * x;\n    ax_hat.noalias() = options_.alpha * a_times_x;\n    ax_hat.noalias() += (1.0 - options_.alpha) * (z + b_);\n\n    // Update z and set z_old.\n    std::swap(z, z_old);\n    z.noalias() = ModifiedShrinkage(ax_hat - b_ + u, 1.0 / options_.rho);\n\n    // Update u.\n    u.noalias() += ax_hat - z - b_;\n\n    // Compute the convergence terms.\n    const double r_norm = (a_times_x - z - b_).norm();\n    const double s_norm = (-options_.rho * A_.transpose() * (z - z_old)).norm();\n    const double max_norm = std::max({a_times_x.norm(), z.norm(), rhs_norm});\n    const double primal_eps =\n        primal_abs_tolerance_eps + options_.relative_tolerance * max_norm;\n    const double dual_eps = dual_abs_tolerance_eps +\n                            options_.relative_tolerance *\n                                (options_.rho * A_.transpose() * u).norm();\n\n    // Log the result to the screen.\n    VLOG(2) << GraphSfM::StringPrintf(\n        row_format.c_str(), i, r_norm, s_norm, primal_eps, dual_eps);\n    // Determine if the minimizer has converged.\n    if (r_norm < primal_eps && s_norm < dual_eps) {\n      break;\n    }\n  }\n}\n\nEigen::VectorXd ConstrainedL1Solver::ModifiedShrinkage(\n    const Eigen::VectorXd& vec, const double kappa) {\n  Eigen::VectorXd output(num_l1_residuals_ + num_inequality_constraints_);\n\n  // Get an array for the subset of l1 terms in the input vec.\n  Eigen::Map<const Eigen::ArrayXd> l1_array(vec.data(), num_l1_residuals_);\n  Eigen::Map<const Eigen::ArrayXd> inequality_array(\n      vec.data() + num_l1_residuals_, num_inequality_constraints_);\n\n  // Compute the L1 proximal operator on the L1 terms.\n  output.head(num_l1_residuals_).array() =\n      (l1_array - kappa).max(0.0) - (-l1_array - kappa).max(0.0);\n  // Project the inequality constraints such that geq_mat * x - geq_vec > 0\n  output.tail(num_inequality_constraints_).array() = inequality_array.max(0.0);\n  return output;\n}\n\n}  // namespace GraphSfM\n", "meta": {"hexsha": "172bd03dbcf3a9b955b0d41f4cd147a1627ccf9f", "size": 5650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solver/constrained_l1_solver.cpp", "max_stars_repo_name": "LumanYang/GraphSfM", "max_stars_repo_head_hexsha": "c04a63578ce63065eb76278f358812c099d4eeef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T06:18:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T06:18:43.000Z", "max_issues_repo_path": "src/solver/constrained_l1_solver.cpp", "max_issues_repo_name": "longchao343/GraphSfM", "max_issues_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver/constrained_l1_solver.cpp", "max_forks_repo_name": "longchao343/GraphSfM", "max_forks_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2179487179, "max_line_length": 80, "alphanum_fraction": 0.6476106195, "num_tokens": 1608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.610553207046252}}
{"text": "/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <random>\n#include <cmath>\n#include <boost/core/demangle.hpp>\n#include <boost/math/special_functions/rsqrt.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing boost::math::rsqrt;\n\ntemplate<typename Real>\nvoid test_rsqrt()\n{\n    std::cout << \"Testing rsqrt on type \" << boost::core::demangle(typeid(Real).name()) << \"\\n\";\n    using std::sqrt;\n    Real x = std::numeric_limits<Real>::min();\n    while (x < 10000*std::numeric_limits<Real>::epsilon()) {\n        Real expected = 1/sqrt(x);\n        Real computed = rsqrt(x);\n        if(!CHECK_ULP_CLOSE(expected, computed, 2)) {\n            std::cerr << \"  1/sqrt(\" << x << \") is computed incorrectly.\\n\";\n        }\n        x += std::numeric_limits<Real>::epsilon();\n    }\n\n    // x ~ 1:\n    x = 1;\n    while (x < 1 + 1000*std::numeric_limits<Real>::epsilon()) {\n        Real expected = 1/sqrt(x);\n        Real computed = rsqrt(x);\n        if(!CHECK_ULP_CLOSE(expected, computed, 2)) {\n            std::cerr << \"  1/sqrt(\" << x << \") is computed incorrectly.\\n\";\n        }\n        x += std::numeric_limits<Real>::epsilon();\n    }\n\n    // x ~ 1000:\n    x = 1000;\n    while (x < 1000 + 1000*1000*std::numeric_limits<Real>::epsilon()) {\n        Real expected = 1/sqrt(x);\n        Real computed = rsqrt(x);\n        if(!CHECK_ULP_CLOSE(expected, computed, 2)) {\n            std::cerr << \"  1/sqrt(\" << x << \") is computed incorrectly.\\n\";\n        }\n        x += 1000*std::numeric_limits<Real>::epsilon();\n    }\n\n    x = std::numeric_limits<Real>::infinity();\n    Real expected = 1/sqrt(x);\n    Real computed = rsqrt(x);\n    if (!CHECK_ULP_CLOSE(expected, computed, 0)) {\n        std::cerr << \"Reciprocal square root of infinity not correctly computed.\\n\";\n    }\n\n    x = std::numeric_limits<Real>::max();\n    expected = 1/sqrt(x);\n    computed = rsqrt(x);\n    if (!CHECK_EQUAL(expected, computed)) {\n        std::cerr << \"Reciprocal square root of std::numeric_limits<Real>::max() not correctly computed.\\n\";\n    }\n\n    if (!CHECK_NAN(rsqrt(std::numeric_limits<Real>::quiet_NaN()))) {\n        std::cerr << \"Reciprocal square root of std::numeric_limits<Real>::quiet_NaN() is not a NaN.\\n\";\n    }\n}\n\n\nint main()\n{\n    test_rsqrt<float>();\n    test_rsqrt<double>();\n    test_rsqrt<long double>();\n    test_rsqrt<boost::multiprecision::cpp_bin_float_50>();\n    test_rsqrt<boost::multiprecision::cpp_bin_float_100>();\n\n    #ifdef BOOST_HAS_FLOAT128\n    test_rsqrt<float128>();\n    #endif\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "9874f17d27cb6fb29e674952e313a91d53ec19a3", "size": 2904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/rsqrt_test.cpp", "max_stars_repo_name": "anarthal/boost-unix-mirror", "max_stars_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-28T15:15:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-28T15:15:28.000Z", "max_issues_repo_path": "libs/math/test/rsqrt_test.cpp", "max_issues_repo_name": "anarthal/boost-unix-mirror", "max_issues_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/test/rsqrt_test.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 31.2258064516, "max_line_length": 108, "alphanum_fraction": 0.6212121212, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6105531969199843}}
{"text": "#define BOOST_TEST_MODULE matrix\n\n#include <boost/test/unit_test.hpp>\n#include <boost/test/test_case_template.hpp>\n#include <boost/mpl/list.hpp>\n\n\n#include <mla/matrix/all.h++>\n#include <mla/vector/all.h++>\n#include <mla/matrix/convert.h++>\n\n#include <mla/solvers/CG.h++>\n\n\ntypedef boost::mpl::list<\n\tmla::matrix::DenseRowMajor<float>,\n\tmla::matrix::DenseRowMajor<double>,\n\tmla::matrix::SparseCRS<float>,\n\tmla::matrix::SparseCRS<double>\n> matrix_type_list;\n\n\nBOOST_AUTO_TEST_SUITE(test_solvers)\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( solve_unit_1, MatrixType, matrix_type_list )\n{\n\tsize_t matrix_size = 6;\n\n\ttypedef typename MatrixType::scalar_type Scalar;\n\n\tMatrixType A(matrix_size, matrix_size);\n\tA.setEye();\n\n\tmla::vector::Dense<Scalar> x(matrix_size), b(matrix_size);\n\n\tScalar value = 1.0f;\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tb.setValue( i, value);\n\t}\n\n\n\n\tmla::cg(A, x, b, 0.01f, 6);\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tBOOST_CHECK_CLOSE( x.getValue(i), 1.0f/b.getValue(i), 0.001f);\n\t}\n}\n\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( solve_unit_2, MatrixType, matrix_type_list )\n{\n\tsize_t matrix_size = 6;\n\n\ttypedef typename MatrixType::scalar_type Scalar;\n\n\tMatrixType A(matrix_size, matrix_size);\n\tA.setEye();\n\n\tmla::vector::Dense<Scalar> x(matrix_size), b(matrix_size);\n\n\tScalar value = 2.0f;\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tb.setValue( i, value);\n\t}\n\n\n\tmla::cg(A, x, b, 0.01f, 6);\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tBOOST_CHECK_CLOSE( x.getValue(i), b.getValue(i), 0.001f);\n\t}\n}\n\n\nBOOST_AUTO_TEST_CASE_TEMPLATE( solve_unit_3, MatrixType, matrix_type_list )\n{\n\tsize_t matrix_size = 6;\n\n\ttypedef typename MatrixType::scalar_type Scalar;\n\n\tmla::matrix::DenseRowMajor<Scalar> from(matrix_size, matrix_size);\n\tmla::vector::Dense<Scalar> x(matrix_size), b(matrix_size);\n\n\tScalar value = 2.0f;\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tfrom.setValue( i, i, value);\n\t\tb.setValue( i, (Scalar)1.0f);\n\t}\n\n\tMatrixType A(matrix_size, matrix_size);\n\tmla::matrix::convert(from, A);\n\n\tmla::cg(A, x, b, 0.01f, 6);\n\n\tfor(unsigned int i = 0; i < matrix_size; i++)\n\t{\n\t\tBOOST_CHECK_CLOSE( x.getValue(i), 1.0f/value, 0.001f);\n\t}\n}\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "29cb8560d26fe28e914949cce5a06095da7bbd70", "size": 2218, "ext": "c++", "lang": "C++", "max_stars_repo_path": "unit_tests/test_solvers_cg.c++", "max_stars_repo_name": "ruimaciel/mla", "max_stars_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_tests/test_solvers_cg.c++", "max_issues_repo_name": "ruimaciel/mla", "max_issues_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_tests/test_solvers_cg.c++", "max_forks_repo_name": "ruimaciel/mla", "max_forks_repo_head_hexsha": "b05f5913067af31a345cd2187de25871dbe31856", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1206896552, "max_line_length": 75, "alphanum_fraction": 0.6970243463, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6105531913135511}}
{"text": "#include <vector>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nnamespace ic {\nusing Particion = pair<uvec, uvec>;\n\n// Particionamiento con reposici\u00f3n\nvector<Particion> particionar(const mat& datos, int nParticiones, double porcentajeEnt)\n{\n\tvector<Particion> particiones;\n\tconst int nPatronesEnt = datos.n_rows * porcentajeEnt / 100;\n\n    // Creo el vector de \u00edndices.\n    // Va desde 0 hasta la cantidad de patrones menos 1.\n\tuvec indices = linspace<uvec>(0, datos.n_rows - 1, datos.n_rows);\n\n\tfor (int i = 0; i < nParticiones; ++i) {\n\t\tindices = shuffle(indices);\n        particiones.push_back({indices.head(nPatronesEnt),\n                               indices.tail(indices.n_rows - nPatronesEnt)});\n\t}\n\n\treturn particiones;\n}\n\n// Particionamiento sin reposici\u00f3n\nvector<Particion> leaveKOut(const mat& datos, int k)\n{\n\tvector<Particion> particiones;\n    const int nParticiones = datos.n_rows / k;\n\tconst uvec indices = shuffle(linspace<uvec>(0, datos.n_rows - 1, datos.n_rows));\n\n\tfor (int i = 0; i < nParticiones; ++i) {\n        uvec indicesPrueba = indices.rows(span(k * i, (i + 1) * k - 1)); // De 0 a k-1, de k a 2k-1, ...\n\t\tuvec indicesEnt;\n\n\t\tif (k * i - 1 >= 0)\n\t\t\tindicesEnt.insert_rows(0, indices.rows(span(0, k * i - 1)));\n\n        if ((i + 1) * k <= int(indices.n_elem - 1)) {\n            // Si es la \u00faltima partici\u00f3n, vamos a meter los elementos del final del bloque de datos\n            // en la partici\u00f3n de prueba\n            if (i == nParticiones - 1)\n                indicesPrueba.insert_rows(indicesPrueba.n_elem, indices.rows(span((i + 1) * k, indices.n_elem - 1)));\n            else\n                indicesEnt.insert_rows(indicesEnt.n_elem, indices.rows(span((i + 1) * k, indices.n_elem - 1)));\n        }\n\n\t\tparticiones.push_back({indicesEnt, indicesPrueba});\n\t}\n\n\treturn particiones;\n}\n\nvoid guardarParticiones(const vector<Particion>& particiones, string rutaCarpeta)\n{\n\tfor (unsigned int i = 0; i < particiones.size(); ++i) {\n\t\tparticiones[i].first.save(rutaCarpeta + \"particionEnt\" + to_string(i), arma_ascii);\n\t\tparticiones[i].second.save(rutaCarpeta + \"particionPrueba\" + to_string(i), arma_ascii);\n\t}\n}\n\nvector<Particion> cargarParticiones(string rutaCarpeta, int nParticiones)\n{\n\tvector<Particion> particiones;\n\tparticiones.resize(nParticiones);\n\n\tfor (int i = 0; i < nParticiones; ++i) {\n\t\tparticiones[i].first.load(rutaCarpeta + \"particionEnt\" + to_string(i));\n\t\tparticiones[i].second.load(rutaCarpeta + \"particionPrueba\" + to_string(i));\n\t}\n\n\treturn particiones;\n}\n}\n", "meta": {"hexsha": "32cf32fb0665a1a3dc49ffea782bd99b6e218c30", "size": 2522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia1/particionar.cpp", "max_stars_repo_name": "junrrein/ic2017", "max_stars_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "guia1/particionar.cpp", "max_issues_repo_name": "junrrein/ic2017", "max_issues_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "guia1/particionar.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": 31.9240506329, "max_line_length": 117, "alphanum_fraction": 0.6673275178, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.8056321936479701, "lm_q1q2_score": 0.6105035416640731}}
{"text": "/* Copyright (C) 2012-2019 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n\n#include <NTL/ZZ.h>\n#include <helib/polyEval.h>\n#include <helib/EncryptedArray.h>\n#include <helib/debugging.h>\n\n#include \"gtest/gtest.h\"\n#include \"test_common.h\"\n\n#ifdef DEBUG_PRINTOUT\nextern helib::SecKey* dbgKey;\nextern helib::EncryptedArray* dbgEa;\n#endif\n\nnamespace {\nstruct Parameters {\n    Parameters(long p, long r, long m, long d, long k, long max_d, long L, bool isMonic) :\n        p(p),\n        r(r),\n        m(m),\n        d(d),\n        k(k),\n        max_d(max_d),\n        L(L),\n        isMonic(isMonic)\n    {};\n\n  const long p;       //   p is the plaintext base\n  const long r;       //   r is the lifting\n  const long m;       //   m is a specific cyclotomic ring\n  const long d;       //   d is the polynomial degree\n  const long k;       //   k is the baby-step parameter\n  const long max_d;\n  const long L;\n  const bool isMonic;\n\n    friend std::ostream& operator<<(std::ostream& os, const Parameters& params)\n    {\n        return os << \"{\"\n            << \"p=\" << params.p << \",\"\n            << \"r=\" << params.r << \",\"\n            << \"m=\" << params.m << \",\"\n            << \"d=\" << params.d << \",\"\n            << \"k=\" << params.k << \",\"\n            << \"max_d=\" << params.max_d << \",\"\n            << \"L=\" << params.L << \",\"\n            << \"isMonic=\" << params.isMonic\n            << \"}\";\n    };\n};\n\nclass GTestPolyEval : public ::testing::TestWithParam<Parameters>\n{\n    protected:\n        long p;\n        long r;\n        long d;\n        long max_d;\n        long L;\n        bool isMonic;\n        long m;\n        long k;\n        helib::Context context;\n        long p2r;\n        helib::EncryptedArray ea;\n        helib::SecKey secretKey;\n        const helib::PubKey &publicKey;\n\n        GTestPolyEval() :\n            p(GetParam().p),\n            r(GetParam().r),\n            d(GetParam().d),\n            max_d(GetParam().max_d),\n            L(GetParam().L),\n            isMonic(GetParam().isMonic),\n            m(GetParam().m),\n            k(GetParam().k),\n            context((helib::setDryRun(helib_test::dry), m), p, r),\n            p2r(context.alMod.getPPowR()),\n            ea((helib::buildModChain(context, L, /*c=*/3), context)),\n            secretKey(context),\n            publicKey((secretKey.GenSecKey(), secretKey))\n            //  addSome1DMatrices(secretKey); // compute key-switching matrices\n    {};\n\n    virtual void SetUp() override {\n#ifdef DEBUG_PRINTOUT\n        helib::dbgEa = &ea;        // for debugging purposes\n        helib::dbgKey = &secretKey;\n#endif\n        if (!helib_test::noPrint) std::cout << (helib::isDryRun()? \"* dry run, \" : \"* \")\n        << \"degree-\"<<d<<\", m=\"<<m<<\", L=\"<<L<<\", p^r=\"<<p2r<<std::endl;\n    };\n\n    virtual void TearDown() override\n    {\n      helib::cleanupGlobals();\n    }\n};\n\n\nTEST_P(GTestPolyEval, encryptedPolynomialsEvaluateAtEncryptedPointCorrectly)\n{\n  NTL::zz_pBak bak; bak.save(); NTL::zz_p::init(p);\n  NTL::zz_pXModulus phimX = NTL::conv<NTL::zz_pX>(ea.getPAlgebra().getPhimX());\n\n  // Choose random plaintext polynomials\n  NTL::zz_pX pX = NTL::random_zz_pX(deg(phimX)-1);\n  NTL::Vec<NTL::zz_pX> ppoly(NTL::INIT_SIZE, d);\n  for (long i=0; i<ppoly.length(); i++) random(ppoly[i], deg(phimX)-1);\n\n  // Evaluate the non-encrypted polynomial\n  NTL::zz_pX pres = (ppoly.length()>0)? ppoly[ppoly.length()-1] : NTL::zz_pX::zero();\n  for (long i=ppoly.length()-2; i>=0; i--) {\n    MulMod(pres, pres, pX, phimX);\n    pres += ppoly[i];\n  }\n\n  // Encrypt the random polynomials\n  helib::Ctxt cX(publicKey);\n  NTL::Vec<helib::Ctxt> cpoly(NTL::INIT_SIZE, d, cX);\n\n  secretKey.Encrypt(cX, NTL::conv<NTL::ZZX>(pX));\n\n  for (long i=0; i<ppoly.length(); i++)\n    secretKey.Encrypt(cpoly[i], NTL::conv<NTL::ZZX>(ppoly[i]));\n\n  // Evaluate the encrypted polynomial\n  helib::polyEval(cX, cpoly, cX);\n\n  // Compare the results\n  NTL::ZZX ret;\n  secretKey.Decrypt(ret, cX);\n  NTL::zz_pX cres = NTL::conv<NTL::zz_pX>(ret);\n  EXPECT_EQ(cres, pres) << \"encrypted poly MISMATCH\";\n};\n\nTEST_P(GTestPolyEval, evaluatePolynomialOnCiphertext)\n{\n  // evaluate at random points (at least one co-prime with p)\n    std::vector<long> x;\n  ea.random(x);\n  while (NTL::GCD(x[0],p)!=1) { x[0] = NTL::RandomBnd(p2r); }\n  helib::Ctxt inCtxt(publicKey), outCtxt(publicKey);\n  ea.encrypt(inCtxt, publicKey, x);\n\n  NTL::ZZX poly;\n  for (long i=d; i>=0; i--)\n    SetCoeff(poly, i, NTL::RandomBnd(p2r)); // coefficients are random\n  if (isMonic) SetCoeff(poly, d);    // set top coefficient to 1\n\n  // Evaluate poly on the ciphertext\n  helib::polyEval(outCtxt, poly, inCtxt, k);\n\n  // Check the result\n  std::vector<long> y;\n  ea.decrypt(outCtxt, secretKey, y);\n  for (long i=0; i<ea.size(); i++) {\n    EXPECT_EQ(helib::polyEvalMod(poly, x[i], p2r), y[i])\n        << \"plaintext poly MISMATCH\\n\";\n  }\n};\n\nstd::vector<Parameters> getParameters()\n{\n    std::vector<Parameters> allParams;\n    \n    //SLOW\n    const long p = 7;\n    const long r = 2;\n          long m = 0;\n    const long k = 0;\n    long d = 34;\n    \n    //FAST\n    //const long p = 3;\n    //const long r = 2;\n    //      long m = 91;\n    //const long k = 0;\n    //long d = -1;\n\n    const long max_d = (d<=0)? 35 : d;\n    const long L = (7+NTL::NextPowerOfTwo(max_d))*30;\n\n    if(m < 2) {\n        m = helib::FindM(/*secprm=*/80, L, /*c=*/3, p, 1, 0, m, !helib_test::noPrint);\n    }\n\n    // Test both monic and non-monic polynomials of this degree\n    if(d >= 0) {\n        allParams.push_back(Parameters{p, r, m, d, k, max_d, L, false});\n        allParams.push_back(Parameters{p, r, m, d, k, max_d, L,  true});\n    } else {\n      // Test degrees 1 to 3 and 25 through 35\n      for(d = 1; d <= 3; d += 2)\n        allParams.push_back(Parameters{p, r, m, d, k, max_d, L, true});\n      for(d = 25; d <= 33; d += 2)\n        allParams.push_back(Parameters{p, r, m, d, k, max_d, L, true});\n    }\n    return allParams;\n};\n\nINSTANTIATE_TEST_SUITE_P(manyDegrees, GTestPolyEval, ::testing::ValuesIn(getParameters()));\n\n} // namespace\n", "meta": {"hexsha": "69a1ae840228dcd4dfdb4b1461b2e0c9ed0e9d48", "size": 6549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/GTestPolyEval.cpp", "max_stars_repo_name": "lparth/homeenc-HElib", "max_stars_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-06T09:26:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T09:26:23.000Z", "max_issues_repo_path": "tests/GTestPolyEval.cpp", "max_issues_repo_name": "lparth/homeenc-HElib", "max_issues_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_issues_repo_licenses": ["Apache-2.0"], "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/GTestPolyEval.cpp", "max_forks_repo_name": "lparth/homeenc-HElib", "max_forks_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_forks_repo_licenses": ["Apache-2.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.1797235023, "max_line_length": 91, "alphanum_fraction": 0.581920904, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146849, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6105035407936914}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n//\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <geometry_test_common.hpp>\n\n\n#include <boost/geometry/algorithms/correct.hpp>\n#include <boost/geometry/algorithms/within.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/geometry/geometries/ring.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/multi/algorithms/within.hpp>\n#include <boost/geometry/multi/core/point_type.hpp>\n#include <boost/geometry/multi/geometries/multi_geometries.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n#include <boost/geometry/extensions/nsphere/nsphere.hpp>\n\nint test_main( int , char* [] )\n{\n    typedef bg::model::d2::point_xy<double> gl_point;\n    typedef bg::model::nsphere<gl_point, double> gl_circle;\n    typedef bg::model::ring<gl_point> gl_ring;\n    typedef bg::model::polygon<gl_point> gl_polygon;\n    typedef bg::model::multi_polygon<gl_polygon> gl_multi_polygon;\n\n    gl_circle circle(gl_point(1, 1), 2.5);\n\n    gl_ring ring;\n    ring.push_back(gl_point(0,0));\n    ring.push_back(gl_point(1,0));\n    ring.push_back(gl_point(1,1));\n    ring.push_back(gl_point(0,1));\n    bg::correct(ring);\n\n    gl_polygon pol;\n    pol.outer() = ring;\n    gl_multi_polygon multi_polygon;\n    multi_polygon.push_back(pol);\n\n    // Multipolygon in circle\n    BOOST_CHECK_EQUAL(bg::within(multi_polygon, circle), true);\n\n    multi_polygon.front().outer().insert(multi_polygon.front().outer().begin() + 1, gl_point(10, 10));\n    BOOST_CHECK_EQUAL(bg::within(multi_polygon, circle), false);\n\n    return 0;\n}\n", "meta": {"hexsha": "c1d398d751c40a07b8c1e391757793dd50315106", "size": 2047, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/nsphere/nsphere-multi_within.cpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "extensions/test/nsphere/nsphere-multi_within.cpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "extensions/test/nsphere/nsphere-multi_within.cpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 35.9122807018, "max_line_length": 102, "alphanum_fraction": 0.745481192, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6105035354616338}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://kylelutz.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#include <iostream>\n#include <iterator>\n\n#include <boost/compute/algorithm/max_element.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/functional/geometry.hpp>\n#include <boost/compute/iterator/transform_iterator.hpp>\n#include <boost/compute/types/fundamental.hpp>\n\nnamespace compute = boost::compute;\n\n// this example shows how to use the max_element() algorithm along with\n// a transform_iterator and the length() function to find the longest\n// 4-component vector in an array of vectors\nint main()\n{\n    using compute::float4_;\n\n    // vectors data\n    float data[] = { 1.0f, 2.0f, 3.0f, 0.0f,\n                     4.0f, 5.0f, 6.0f, 0.0f,\n                     7.0f, 8.0f, 9.0f, 0.0f,\n                     0.0f, 0.0f, 0.0f, 0.0f };\n\n    // create device vector with the vector data\n    compute::vector<float4_> vector(\n        reinterpret_cast<float4_ *>(data),\n        reinterpret_cast<float4_ *>(data) + 4\n    );\n\n    // find the longest vector\n    compute::vector<float4_>::const_iterator iter =\n        compute::max_element(\n            compute::make_transform_iterator(\n                vector.begin(), compute::length<float4_>()\n            ),\n            compute::make_transform_iterator(\n                vector.end(), compute::length<float4_>()\n            )\n        ).base();\n\n    // print the index of the longest vector\n    std::cout << \"longest vector index: \"\n              << std::distance(vector.begin(), iter)\n              << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "9c3953ff90e326e7c9c54b13181149b047618268", "size": 1938, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/longest_vector.cpp", "max_stars_repo_name": "skozilla/compute", "max_stars_repo_head_hexsha": "861a75ae9f05f5bbd25d13120788133a1c9dc886", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-03-18T01:14:13.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-18T01:14:13.000Z", "max_issues_repo_path": "example/longest_vector.cpp", "max_issues_repo_name": "junmuz/compute", "max_issues_repo_head_hexsha": "b979ff527d3f1cb6e073da29b167bf02b3218c9a", "max_issues_repo_licenses": ["BSL-1.0"], "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/longest_vector.cpp", "max_forks_repo_name": "junmuz/compute", "max_forks_repo_head_hexsha": "b979ff527d3f1cb6e073da29b167bf02b3218c9a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8474576271, "max_line_length": 79, "alphanum_fraction": 0.5779153767, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321703143955, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6105035195752299}}
{"text": "/* $Id: step-1.cc 23709 2011-05-17 04:34:08Z bangerth $\n *\n * Copyright (C) 1999, 2000, 2001, 2002, 2003, 2005, 2006, 2007, 2009, 2011 by the deal.II authors\n *\n * This file is subject to QPL and may not be  distributed\n * without copyright and license information. Please refer\n * to the file deal.II/doc/license.html for the  text  and\n * further information on this license.\n */\n\n/* \n * This is a modified version for the exercises of the lecture \n * finite elements at University of Hamburg in Summer 2014\n * \n */\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/grid/grid_out.h>\n#include <fstream>\n#include <cmath>\n\nusing namespace dealii;\nvoid first_grid ()\n\n{\n  Triangulation<2> triangulation;\n  GridGenerator::hyper_cube (triangulation);\n  triangulation.refine_global (4);\n  std::ofstream out (\"grid-1.eps\");\n  GridOut grid_out;\n  grid_out.write_eps (triangulation, out);\n}\n\nvoid second_grid ()\n{\n  Triangulation<2> triangulation;\n  const Point<2> center (1,0);\n  const double inner_radius = 0.5,\n               outer_radius = 1.0;\n  GridGenerator::hyper_shell (triangulation,\n                              center, inner_radius, outer_radius,\n\t\t\t      10);\n  const HyperShellBoundary<2> boundary_description(center);\n  triangulation.set_boundary (0, boundary_description);\n  \n  for (unsigned int step=0; step<5; ++step)\n    {\n      Triangulation<2>::active_cell_iterator\n\tcell = triangulation.begin_active(),\n\tendc = triangulation.end();\n      for (; cell!=endc; ++cell)\n\tfor (unsigned int v=0;\n             v < GeometryInfo<2>::vertices_per_cell;\n             ++v)\n\t{\n\t  const double distance_from_center\n\t    = center.distance (cell->vertex(v));\n\t  \n\t  if (std::fabs(distance_from_center - inner_radius) < 1e-10)\n\t  {\n\t    cell->set_refine_flag ();\n\t    break;\n\t  }\n\t}\n      triangulation.execute_coarsening_and_refinement ();\n    }\n  std::ofstream out (\"grid-2.eps\");\n  GridOut grid_out;\n  grid_out.write_eps (triangulation, out);\n\n  triangulation.set_boundary (0);\n}\n\n\nint main ()\n{\n  first_grid ();\n  second_grid ();\n}\n\n", "meta": {"hexsha": "294d51fcd06c9f6469723a01b68123fd57096ca4", "size": 2199, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MathMods/FiniteElement/Ex-0-4/exercise-0-4.cc", "max_stars_repo_name": "homdx/edu", "max_stars_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MathMods/FiniteElement/Ex-0-4/exercise-0-4.cc", "max_issues_repo_name": "homdx/edu", "max_issues_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MathMods/FiniteElement/Ex-0-4/exercise-0-4.cc", "max_forks_repo_name": "homdx/edu", "max_forks_repo_head_hexsha": "a32c9f1777f80a54c3d4a3fc8389748fe27739c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-09-15T21:30:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-15T21:30:43.000Z", "avg_line_length": 25.8705882353, "max_line_length": 98, "alphanum_fraction": 0.6807639836, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.610471176975708}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <complex>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"miMaS/field.h\"\n#include \"miMaS/weno.h\"\n#include \"miMaS/fft.h\"\n#include \"miMaS/array_view.h\"\n#include \"miMaS/poisson.h\"\n\nnamespace math = boost::math::constants;\nconst std::complex<double> & I = std::complex<double>(0.,1.);\n\n#define SQ(X) ((X)*(X))\n#define Xi(i) (i*f.step.dx+f.range.x_min)\n#define Vk(k) (k*f.step.dv+f.range.v_min)\n\nint main(int,char**)\n{\n  const std::size_t NumDimV = 1;\n\tconst int Nx = 64, Nv = 128, Nb_iter=100;\n\n\tfield<double,NumDimV> f( boost::extents[Nv][Nx] );\n\n\tf.range.v_min = -10.; f.range.v_max = 10;\n\tf.step.dv = (f.range.v_max-f.range.v_min)/Nv;\n\tf.range.x_min = 0.; f.range.x_max = 20.*math::pi<double>();\n\tf.step.dx = (f.range.x_max-f.range.x_min)/Nx;\n\n\tconst double dt = 1.606*f.step.dv/0.6; //0.5*6.*math::pi<double>()/(Nv*f.range.v_max);\n\n\tublas::vector<double> v (Nv,1.);\n  ublas::vector<double> E (Nx,1.),rho(Nx);\n  for ( std::size_t k=0 ; k<Nv ; ++k ) { v[k] = Vk(k); }\n  //for ( std::size_t i=0 ; i<Nx ; ++i ) { E[i] = -Xi(i); }\n\n\tconst double lx = f.range.x_max-f.range.x_min;\n  const double lv = f.range.v_max-f.range.v_min;\n\tublas::vector<double> kx(Nx),kv(Nv);\n  for ( int i=0  ; i<Nx/2 ; ++i ) { kx[i]    = 2.*math::pi<double>()*i/lx; }\n  for ( int i=-Nx/2 ; i<0 ; ++i ) { kx[Nx+i] = 2.*math::pi<double>()*i/lx; }\n\n  for ( int k=0  ; k<Nv/2 ; ++k ) { kv[k]    = 2.*math::pi<double>()*k/lv; }\n  for ( int k=-Nv/2 ; k<0 ; ++k ) { kv[Nv+k] = 2.*math::pi<double>()*k/lv; }\n\t\n  double np = 0.9 , nb = 0.2 , ui = 4.5;\n  for (field<double,NumDimV>::size_type k=0 ; k<f.size(0) ; ++k ) {\n    for (field<double,NumDimV>::size_type i=0 ; i<f.size(1) ; ++i ) {\n      f[k][i] = ( std::exp(-0.5*SQ(Vk(k)))*np/std::sqrt(2.*math::pi<double>()) + nb/std::sqrt(2.*math::pi<double>())*std::exp(-0.5*SQ(Vk(k)-ui)/0.25) )*(1.+0.04*std::cos(0.3*Xi(i)));\n      //f[k][i] = std::cos(Xi(i)*0.2)*std::cos(math::pi<double>()*2.*Vk(k)/20);\n      //f[k][i] = std::exp( -SQ(Xi(i)-1.)/2. )*std::exp( -Vk(k)*Vk(k)/1.);\n      //f[k][i] = ( std::exp(-0.5*SQ(Vk(k)))*np/std::sqrt(2.*math::pi<double>()) )*(1.+0.04*std::cos(0.3*Xi(i)));\n    }\n  }\n  f.write(\"init.dat\");\n\n  poisson<double> poisson_solver(Nx,lx);\n\n  double Tf = 60.;//2*math::pi<double>();\n  int i_t=0;\n\n  std::cout << f.size(0) << \"x\" << f.size(1) << std::endl;\n  std::cout << \"dt \" << dt << std::endl;\n  std::cout << \"dx \" << f.step.dx << std::endl;\n  std::cout << \"dv \" << f.step.dv << std::endl;\n  std::cout << \"Tf \" << Tf << std::endl;\n\n  ublas::vector<double> ee(int(Tf/dt)+1.);\n  ublas::vector<double> Emax(int(Tf/dt)+1.);\n  ublas::vector<double> H(int(Tf/dt)+1.);\n\n  while ( i_t*dt < Tf ) {\n    std::cout<<\" \\r\"<<i_t<<\" \"<<std::flush;\n\n    field<double,1> f1 = f;\n    field<double,1> f2 = f;\n\t  \n    fft::spectrum_ hxf(Nx);\n\t  for ( std::size_t k=0 ; k<Nv ; ++k ) {\n\t  \thxf.fft(&(f[k][0]));\n\n\t  \tfor ( std::size_t i=0 ; i<Nx ; ++i ) {\n        hxf[i] = std::exp( -I*v(k)*kx[i]*0.5*dt )*hxf[i];\n\t  \t}\n\n\t  \thxf.ifft(&(f1[k][0]));\n\t  }\n\n    fft::spectrum_ hvf(Nv);\n    rho = f1.density();\n    E = poisson_solver(rho);\n    for ( std::size_t i=0 ; i<Nx ; ++i ) {\n      std::valarray<double> fi(Nv); for ( std::size_t k=0 ; k<Nv ; ++k ) { fi[k] = f1[k][i]; }\n      hvf.fft(&(fi[0]));\n\n      for ( std::size_t k=0 ; k<Nv ; ++k ) {\n        hvf[k] = std::exp( -I*E(i)*kv[k]*dt )*hvf[k];\n      }\n\n      hvf.ifft(&(fi[0]));\n      for ( std::size_t k=0 ; k<Nv ; ++k ) { f2[k][i] = fi[k]; }\n    }\n\n\t  for ( auto k=0 ; k<f.size(0) ; ++k ) {\n\t  \thxf.fft(&(f2[k][0]));\n\n\t  \tfor ( auto i=0 ; i<Nx ; ++i ) {\n        hxf[i] = std::exp( -I*v(k)*kx[i]*0.5*dt )*hxf[i];\n\t  \t}\n\n\t  \thxf.ifft(&(f[k][0]));\n\t  }\n\n\n\n    rho = f.density();\n    E = poisson_solver(rho);\n    ee(i_t) = 0.;\n    for ( auto i=0 ; i<Nx ; ++i ) {\n      ee(i_t) += SQ(E(i))*f.step.dx;\n    }\n    H(i_t) = energy(f,E);\n    ++i_t;\n\t}\n\n  std::cout << \" \\r\" << i_t << std::endl;\n\n\n  f.write(\"vp.dat\");\n\n  std::ofstream of;\n  std::size_t count = 0;\n  auto dt_y = [&,count=0](auto const& y) mutable { std::stringstream ss; ss<<count*dt<<\" \"<<y; return ss.str(); };\n  of.open(\"ee.dat\");\n  for ( auto i=0; i<ee.size() ; ++i ) {\n    of << i*dt <<\" \" << ee[i] << \"\\n\";\n  }\n  of.close();\n  of.open(\"H.dat\");\n  for ( auto i=0; i<H.size() ; ++i ) {\n    of << i*dt <<\" \" << (H[i]-H[0])/std::abs(H[0]) << \"\\n\";\n  }\n  of.close();\n  of.open(\"Emax.dat\");\n  std::transform( ee.begin() , ee.end() , std::ostream_iterator<std::string>(of,\"\\n\") , dt_y );\n  of.close();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "cc400569164d4724c9104e744668baea7d1cceef", "size": 4662, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/strang.cc", "max_stars_repo_name": "kivvix/vlasovpp", "max_stars_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-03T22:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-29T06:12:07.000Z", "max_issues_repo_path": "code/strang.cc", "max_issues_repo_name": "kivvix/vlasovpp", "max_issues_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/strang.cc", "max_forks_repo_name": "kivvix/vlasovpp", "max_forks_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-29T06:17:16.000Z", "avg_line_length": 29.5063291139, "max_line_length": 182, "alphanum_fraction": 0.5186615187, "num_tokens": 1824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.6893056295505784, "lm_q1q2_score": 0.6104707522870214}}
{"text": "#define _USE_MATH_DEFINES\n\n#include \"fastDonut.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n\n\n\nstd::vector<std::vector<fast::calPoint>> fast::fastDonut(int center_x, int center_y, int radius, double start_ratio, double end_ratio, double step_angle) {\n\n\tif (radius == 0) {\n\t\tHVERROR(error, \"Invalid box roi range\");\n\t}\n\n\tif (step_angle <= 0) {\n\t\tHVERROR(error, \"Invalid step angle\");\n\t}\n\n\tif (start_ratio <= 0 && end_ratio <= 0) {\n\t\tHVERROR(error, \"Invalid ratio\");\n\t}\n\n\n\n\tint start_radius = (int)((double)radius * start_ratio);\n\tint end_radius = (int)((double)radius * end_ratio);\n\n\tint distance_radius = (int)fabs(start_radius - end_radius);\n\tif (distance_radius == 0) {\n\t\tHVERROR(error, \"Invalid start ratio and end ratio\");\n\t}\n\n\tint aligned_distance_radius = distance_radius + (distance_radius % 4);\n\tint min_radius = start_radius > end_radius ? end_radius : start_radius;\n\tint max_radius = start_radius > end_radius ? start_radius : end_radius;\n\n\n\t/// Radius SIMD \n\tstd::vector<double> vector_radius; // Radius vector\n\tvector_radius.resize(aligned_distance_radius * 2);\n\n\n\tint sign = 1;\n\tif (start_radius > end_radius)\n\t\tsign = -1;\n\n\tint current_radius = start_radius;\n\tfor (int radius = 0; radius < distance_radius * 2;) {\n\t\tvector_radius[radius] = current_radius;\n\t\tvector_radius[radius + 1] = current_radius;\n\t\tradius += 2;\n\t\tcurrent_radius += sign;\n\t}\n\n\t/// Coordinate SIMD \n\tstd::vector<double> vector_cordinate_table = { (double)center_x , (double)center_y, (double)center_x , (double)center_y }; // cordinate vector\n\tconst __m256d simd_coordinate = _mm256_load_pd(vector_cordinate_table.data()); // cordinate simd\n\n\n\n\tstd::vector<std::vector<fast::calPoint>> combine_vertical_xy;\n\tint doubleDistance = distance_radius * 2;\n\tint chunk_size = sizeof(double) * 4;\n\n\tfor (double angle = 0; angle < 360;) {\n\n\t\t/// trigonometric SIMD \n\t\tdouble x_cos = sin(angle * M_PI / 180);\n\t\tdouble y_sine = cos(angle * M_PI / 180);\n\t\tstd::vector<double> vector_trigonometric_table = { x_cos ,y_sine, x_cos ,y_sine }; // trigonometric vector\n\t\tconst __m256d simd_trigonometric = _mm256_load_pd(vector_trigonometric_table.data()); // trigonometric simd\n\n\n\t\tstd::vector<fast::calPoint> vertical_xy;\n\t\tvertical_xy.resize(aligned_distance_radius);\n\t\tvoid* vertical_xy_ptr = vertical_xy.data();\n\t\tfor (int simd_skip = 0; simd_skip < doubleDistance;) {\n\n\t\t\tconst __m256d simd_radius = _mm256_load_pd(vector_radius.data() + simd_skip); // radius simd\n\t\t\t__m256d chunk_mul = _mm256_mul_pd(simd_radius, simd_trigonometric);\n\t\t\t__m256d start_result = _mm256_add_pd(chunk_mul, simd_coordinate);\n\t\t\tmemcpy((((double*)vertical_xy_ptr) + simd_skip), &start_result, chunk_size);\n\t\t\tsimd_skip += 4;\n\t\t}\n\t\tvertical_xy.resize(distance_radius);\n\t\tcombine_vertical_xy.push_back(vertical_xy);\n\n\t\tangle += step_angle;\n\t}\n\n\treturn combine_vertical_xy;\n}\n", "meta": {"hexsha": "5b9ecb558050bb382a4e1bd50d906b4353b4a4c8", "size": 2828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FastROI/fastROI/fastDonut.cpp", "max_stars_repo_name": "gellston/FastROI", "max_stars_repo_head_hexsha": "983e939127d8b4d629db355f6614fc0a8f2a4e39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2022-01-19T02:21:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T22:53:19.000Z", "max_issues_repo_path": "FastROI/fastROI/fastDonut.cpp", "max_issues_repo_name": "gellston/FastROI", "max_issues_repo_head_hexsha": "983e939127d8b4d629db355f6614fc0a8f2a4e39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FastROI/fastROI/fastDonut.cpp", "max_forks_repo_name": "gellston/FastROI", "max_forks_repo_head_hexsha": "983e939127d8b4d629db355f6614fc0a8f2a4e39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-21T02:31:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T16:07:04.000Z", "avg_line_length": 29.7684210526, "max_line_length": 155, "alphanum_fraction": 0.724893918, "num_tokens": 763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314707995588, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.6104707415714901}}
{"text": "// Effectively recursive lambda in C++, std::function technique\n//\n// Copyright (c) 2020 Eliah Kagan\n//\n// Permission to use, copy, modify, and/or distribute this software for any\n// purpose with or without fee is hereby granted.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n#include <cstddef>\n#include <functional>\n#include <iostream>\n#include <iterator>\n#include <tuple>\n#include <unordered_map>\n#include <boost/multiprecision/cpp_int.hpp>\n\nint main()\n{\n    using boost::multiprecision::cpp_int;\n    using Key = std::tuple<cpp_int, unsigned>;\n\n    constexpr auto hash = [](const Key& key) {\n        constexpr std::size_t seed {127}, multiplier {131'071};\n        const auto& [base, exponent] = key;\n\n        auto code = seed;\n        code = code * multiplier + std::hash<cpp_int>{}(base);\n        code = code * multiplier + exponent;\n        return code;\n    };\n\n    std::unordered_map<Key, cpp_int, decltype(hash)> memo;\n\n    std::function<cpp_int(cpp_int, unsigned)>\n    my_pow = [&memo, &my_pow](const cpp_int& base, unsigned exponent) {\n        if (exponent == 0) return cpp_int{1};\n\n        auto p = memo.find({base, exponent});\n        if (p != end(memo)) return p->second;\n\n        auto result = my_pow(base, exponent / 2);\n        result *= result;\n        if (exponent % 2 != 0) result *= base;\n\n        memo[{base, exponent}] = result;\n        return result;\n    };\n\n    cpp_int ans = my_pow(7, 1013);\n    std::cout << \"Computed value: \" << ans << '\\n';\n\n    cpp_int known = pow(cpp_int{7}, 1013);\n    std::cout << \"Accepted value: \" << known << '\\n';\n\n    std::cout << \"Correct?  \" << std::boolalpha << (ans == known) << '\\n';\n}\n", "meta": {"hexsha": "54756c511ad5d01195d9dfa5d7ffa4bd46663e3a", "size": 2108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lambda-stdfunction.cpp", "max_stars_repo_name": "EliahKagan/recursive-lambda", "max_stars_repo_head_hexsha": "fec089ea5ed6573a39267ea100bd4f71146a60cb", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lambda-stdfunction.cpp", "max_issues_repo_name": "EliahKagan/recursive-lambda", "max_issues_repo_head_hexsha": "fec089ea5ed6573a39267ea100bd4f71146a60cb", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lambda-stdfunction.cpp", "max_forks_repo_name": "EliahKagan/recursive-lambda", "max_forks_repo_head_hexsha": "fec089ea5ed6573a39267ea100bd4f71146a60cb", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9375, "max_line_length": 79, "alphanum_fraction": 0.6484819734, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6104202509033482}}
{"text": "#include <math.h>\n#include <iostream>\n#include <armadillo>\n#include <vector>\n#include <complex>\n#include <fftw3.h>\n#include \"mkl.h\"\n\n\n//#include <omp.h>\n\n#include \"tensor.h\"\n#include \"tensor.cpp\"\n#include \"cp_als.cpp\"\n#include \"tucker_hosvd.cpp\"\n\nusing namespace std;\n\n#include \"time.h\"\ndouble gettime(){\n    struct timeval tv;\n    gettimeofday(&tv,NULL);\n    return tv.tv_sec*1000+tv.tv_usec/1000.0; //time:s\n};\n\nusing namespace std;\nusing namespace arma;\n\nint main() {\n    double t0,t1;\n    int I=3;\n    int R=0.2*I;\n    R=1;\n    //    arma_rng::set_seed(1);\n\n    t0=gettime();\n    Tensor<float> a(I,I,I);\n    t1=gettime();\n    cout << \"time:\" <<t1-t0 <<endl;\n\n    for (int i = 0; i < a.n1; ++i) {\n        for (int j = 0; j < a.n2; ++j) {\n            for(int k=0; k< a.n3; ++k) {\n                a(i,j,k) = randu<float>();\n            }\n        }\n    }\n//    arma_rng::set_seed(1);\n//    Tensor<float> b(I,I,I);\n//    for (int i = 0; i < b.n1; ++i) {\n//        for (int j = 0; j < b.n2; ++j) {\n//            for(int k=0; k<b.n3; ++k) {\n//                b(i,j,k) = randu<float>();\n////                cout << a(i,j,k) - b(i,j,k) << endl;\n//            }\n//        }\n//    }\n\n    Tensor<double> b(I,I,I);\n\n//    t0=gettime();\n//    tucker_core<float> result;\n//    result = hosvd(a,R,R,R);\n//    t1=gettime();\n//    cout << \"time:\" <<t1-t0 <<endl;\n\n    t0=gettime();\n    cp_mats<float> result;\n    result = cp_als(a,R);\n    t1=gettime();\n    cout << \"time:\" <<t1-t0 <<endl;\n\n//    t0=gettime();\n//        HOSVD(a,R,R,R);\n//        hosvd(a,R,R,R);\n//        cp_als(a,R);\n//        cpals(a,R);\n//    t1=gettime();\n//    cout << \"time:\" <<t1-t0 <<endl;\n\n//    Tensor<double> b(2,3,5),d(5,5,5), z(2,3,4),t(5,5,5);\n//    cout<<z(0,1,2)<<endl;\n//    z=z.zeros(2,3,4);\n//    cout<<z(0,1,2)+123<<endl;\n//\n//    int *c=getsize(b);\n//    cout<<c[0]<<endl; //tensor\u5927\u5c0f\n//    cout<<sizeof(a)<<endl;\n//    cout<<norm(a)<<endl;\n//    cout<<t(1,2,3)<<endl;\n\n//    mat m1 = ten2mat(a,1);\n//    cout << m1 << endl;\n//    mat m2 = ten2mat(a,2);\n//    cout << m2 << endl;\n//    mat m3 = ten2mat(a,3);,\n//    cout << m3 << endl;\n\n//    cout<<slice(a,0,2)<<endl;\n//slice\n//    cout<<fiber(a,1,2,2)<<endl;\n\n    return 0;\n\n}\n", "meta": {"hexsha": "feb3659f825674787468c485b3f2325fac5a6002", "size": 2202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "FreshHillyer/TensorLet_in_C_PlusPlus", "max_stars_repo_head_hexsha": "b27d4561d0335331bc28f1c6ea9bec7704664a66", "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": "FreshHillyer/TensorLet_in_C_PlusPlus", "max_issues_repo_head_hexsha": "b27d4561d0335331bc28f1c6ea9bec7704664a66", "max_issues_repo_licenses": ["Apache-2.0"], "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": "FreshHillyer/TensorLet_in_C_PlusPlus", "max_forks_repo_head_hexsha": "b27d4561d0335331bc28f1c6ea9bec7704664a66", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7735849057, "max_line_length": 58, "alphanum_fraction": 0.4736603088, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6104142562330583}}
{"text": "\r\n#include <random>\r\n#include <math.h>\r\n\r\n#include <boost/filesystem.hpp>\r\n#include <boost/format.hpp>\r\n\r\n#include <cml/cml.h>\r\n\r\n#include <framework/misc.h>\r\n#include <framework/vector.h>\r\n\r\nnamespace fs = boost::filesystem;\r\n\r\n// Our global random number generator.\r\nstatic std::mt19937 rng;\r\n\r\nnamespace fw {\r\n\r\nfloat distance_between_line_and_point(vector const &start,\r\n    vector const &direction, vector const &point) {\r\n  // see: http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/\r\n  vector end = start + direction;\r\n  float u = (point[0] - start[0]) * (end[0] - start[0])\r\n      + (point[1] - start[1]) * (end[1] - start[1])\r\n      + (point[2] - start[2]) * (end[2] - start[2]);\r\n\r\n  // this is the point on the line closest to 'point'\r\n  vector point_on_line = start + (direction * u);\r\n\r\n  // therefore, the distance is just the length of the (point - point_line_to) vector.\r\n  vector vector_to_point = point - point_on_line;\r\n  return vector_to_point.length();\r\n}\r\n\r\n// Gets the distance between the given line segment and point. This is different to\r\n// distance_between_line_and_point, which looks at an infinite line, where as this one only looks\r\n// at the given line *segment*.\r\nfloat distance_between_line_segment_and_point(vector const &start,\r\n    vector const &end, vector const &point) {\r\n  // see: http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/\r\n  float u = (point[0] - start[0]) * (end[0] - start[0])\r\n      + (point[1] - start[1]) * (end[1] - start[1])\r\n      + (point[2] - start[2]) * (end[2] - start[2]);\r\n\r\n  if (u < 0.0f)\r\n    u = 0.0f;\r\n  if (u > 1.0f)\r\n    u = 1.0f;\r\n\r\n  // this is the point on the line closest to 'point'\r\n  vector point_on_line = start + ((end - start) * u);\r\n\r\n  // therefore, the distance is just the length of the (point - point_line_to) vector.\r\n  vector vector_to_point = point - point_on_line;\r\n  return vector_to_point.length();\r\n}\r\n\r\n// Returns the angle, in radians, between a and b\r\nfloat angle_between(vector const &a, vector const &b) {\r\n  vector lhs = a;\r\n  vector rhs = b;\r\n\r\n  float cosangle = cml::dot(lhs.normalize(), rhs.normalize());\r\n  return acos(cosangle);\r\n}\r\n\r\nfw::vector point_plane_intersect(vector const &plane_pt,\r\n    vector const &plane_normal, vector const &p_start, vector const &p_dir) {\r\n  // see: http://local.wasp.uwa.edu.au/~pbourke/geometry/planeline/\r\n  vector end = p_start + p_dir;\r\n\r\n  float numerator = cml::dot(plane_normal, plane_pt - p_start);\r\n  float denominator = cml::dot(plane_normal, end - p_start);\r\n  float u = numerator / denominator;\r\n  return p_start + (p_dir * u);\r\n}\r\n\r\nfloat random() {\r\n  return static_cast<float>(rng()) / static_cast<float>(rng.max());\r\n}\r\n\r\nvoid random_initialize() {\r\n  std::random_device rd;\r\n  rng.seed(rd());\r\n}\r\n\r\nfw::vector get_direction_to(fw::vector const &from, fw::vector const &to,\r\n    float wrap_x, float wrap_z) {\r\n  fw::vector dir = to - from;\r\n\r\n  // if we're not wrapping, the direction is just the \"simple\" direction\r\n  if (wrap_x == 0 && wrap_z == 0)\r\n    return dir;\r\n\r\n  // otherwise, we'll also try in the various other directions and return the shortest one\r\n  for (int z = -1; z <= 1; z++) {\r\n    for (int x = -1; x <= 1; x++) {\r\n      fw::vector another_to(to[0] + (x * wrap_x), to[1], to[2] + (z * wrap_z));\r\n      fw::vector another_dir = another_to - from;\r\n\r\n      if (another_dir.length_squared() < dir.length_squared())\r\n        dir = another_dir;\r\n    }\r\n  }\r\n\r\n  return dir;\r\n}\r\n\r\n// Calculates the distance between 'from' and 'to', taking into consideration the fact that\r\n// the world wraps at (wrap_x, wrap_z).\r\nfloat calculate_distance(fw::vector const &from, fw::vector const &to,\r\n    float wrap_x, float wrap_z) {\r\n  return (get_direction_to(from, to, wrap_x, wrap_z).length());\r\n}\r\n\r\n}\r\n", "meta": {"hexsha": "c1e5447043f0b3f50c426ed6001840b3f1627de5", "size": 3777, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/framework/misc.cc", "max_stars_repo_name": "codeka/ravaged-planets", "max_stars_repo_head_hexsha": "ab20247b3829414e71b58c9a6e926bddf41f1da5", "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/framework/misc.cc", "max_issues_repo_name": "codeka/ravaged-planets", "max_issues_repo_head_hexsha": "ab20247b3829414e71b58c9a6e926bddf41f1da5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/framework/misc.cc", "max_forks_repo_name": "codeka/ravaged-planets", "max_forks_repo_head_hexsha": "ab20247b3829414e71b58c9a6e926bddf41f1da5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-17T22:24:17.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-15T18:37:15.000Z", "avg_line_length": 32.0084745763, "max_line_length": 98, "alphanum_fraction": 0.6476039185, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.6104142550944768}}
{"text": "#include <Eigen/Dense>\n#include <fmt/core.h>\n#include <fmt/ostream.h>\n#include <iostream>\n\n#include \"HittableList.hh\"\n#include \"Sphere.hh\"\n#include \"color.hh\"\n#include \"ray.hh\"\n\nauto main(int /*argc*/, char** /*argv*/) -> int\n{\n    // Image\n    constexpr auto aspect_ratio = 16.0 / 9.0;\n    constexpr int image_width = 400;\n    constexpr int image_height = static_cast<int>(image_width / aspect_ratio);\n\n    // Camera\n    constexpr auto viewport_height = 2.0;\n    constexpr auto viewport_width = aspect_ratio * viewport_height;\n    constexpr auto focal_length = 1.0;\n\n    Eigen::Vector3d origin{0, 0, 0};\n    Eigen::Vector3d horizontal{viewport_width, 0, 0};\n    Eigen::Vector3d vertical{0, viewport_height, 0};\n    Eigen::Vector3d lower_left_corner = origin - horizontal / 2 - vertical / 2 -\n                                        Eigen::Vector3d{0, 0, focal_length};\n\n    // World\n    hittable::HittableList world;\n    world.add(\n        std::make_shared<hittable::Sphere>(Eigen::Vector3d{0, 0, -1}, 0.5));\n    world.add(std::make_shared<hittable::Sphere>(Eigen::Vector3d{0, -100.5, -1},\n                                                 100));\n\n    fmt::print(\"P3{} {}\\n255\\n\", image_width, image_height);\n\n    for (int j = image_height - 1; j >= 0; j--)\n    {\n        fmt::print(std::cerr, \"\\rScanlines remaining: {} \", j);\n        for (int i = 0; i < image_width; i++)\n        {\n            auto u = double(i) / (image_width - 1);\n            auto v = double(j) / (image_height - 1);\n            ray::Ray r{origin, lower_left_corner + u * horizontal +\n                                   v * vertical - origin};\n            color::Color pixColor = ray::ray_color(r, world);\n            color::write_color(std::cout, ray::ray_color(r));\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "aafcb45cd023e57134aac083b0818a92d90c3119", "size": 1773, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/main.cc", "max_stars_repo_name": "AlexanderDavid/inOneWeekend", "max_stars_repo_head_hexsha": "244bf38a94b7f90be9e85d0c10e737a15de03b98", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cc", "max_issues_repo_name": "AlexanderDavid/inOneWeekend", "max_issues_repo_head_hexsha": "244bf38a94b7f90be9e85d0c10e737a15de03b98", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cc", "max_forks_repo_name": "AlexanderDavid/inOneWeekend", "max_forks_repo_head_hexsha": "244bf38a94b7f90be9e85d0c10e737a15de03b98", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8333333333, "max_line_length": 80, "alphanum_fraction": 0.5736040609, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.6757645879592641, "lm_q1q2_score": 0.6104142338807391}}
{"text": "#include \"gradient_sh.hpp\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <complex>\n#include <fmt/format.h>\n#include <fmt/ostream.h>\n#include <fstream>\n#include <memory>\n#include <utility>\n\nusing namespace Eigen;\nusing namespace std::complex_literals;\n\nusing std::exp;\nusing std::pow;\nusing std::sqrt;\nusing complex_d = std::complex<double>;\n\nconst double PI = 3.14159265358979323846;\n\nnamespace grad_sh {\n\nGRTCoeff::GRTCoeff(const Ref<const ArrayXXd> model, const double freq,\n                   const double c)\n    : z_(model.col(1)), rho_(model.col(2)), beta_(model.col(3)),\n      alpha_(model.col(4)), mu_(rho_ * beta_.pow(2)), nl_(model.rows()),\n      angfreq_(2.0 * PI * freq), c_(c), nv_(VectorXcd::Zero(nl_)),\n      e_(nl_, Matrix2cd::Zero()), t_d_(VectorXcd::Zero(nl_)),\n      r_ud_(VectorXcd::Zero(nl_)), r_du_(VectorXcd::Zero(nl_)),\n      t_u_(VectorXcd::Zero(nl_)), gt_d_(VectorXcd::Zero(nl_)),\n      gr_ud_(VectorXcd::Zero(nl_)), gr_du_(VectorXcd::Zero(nl_ + 1)),\n      gt_u_(VectorXcd::Zero(nl_)), cd_(VectorXcd::Zero(nl_)),\n      cu_(VectorXcd::Zero(nl_)) {\n\n  initialize_nv();\n  initialize_E();\n\n  compute_rtc();\n  compute_grtc();\n  compute_CdCu();\n}\n\nvoid GRTCoeff::initialize_E() {\n  for (int i = 0; i < nl_; ++i) {\n    complex_d e21 = -mu_(i) * nv_(i);\n    e_[i] << 1.0, 1.0, e21, -e21;\n  }\n}\n\nvoid GRTCoeff::initialize_nv() {\n  for (int i = 0; i < nl_; ++i) {\n    complex_d val =\n        std::sqrt(pow(angfreq_ / c_, 2) - pow(angfreq_ / beta_(i), 2));\n    if (val.real() < 0) {\n      val = -val;\n    }\n    nv_(i) = val;\n  }\n}\n\ncomplex_d GRTCoeff::get_Ad(const double z, const int ind_layer) const {\n  return exp(-nv_(ind_layer) * (z - z_(ind_layer)));\n}\n\ncomplex_d GRTCoeff::get_Au(const double z, const int ind_layer) const {\n  return exp(-nv_(ind_layer) * (z_(ind_layer + 1) - z));\n}\n\ncomplex_d GRTCoeff::get_Ad_der(const double z, const int ind_layer) const {\n  return -nv_(ind_layer) * exp(-nv_(ind_layer) * (z - z_(ind_layer)));\n}\n\ncomplex_d GRTCoeff::get_Au_der(const double z, const int ind_layer) const {\n  if (ind_layer == nl_ - 1) {\n    return 0.0;\n  }\n\n  return nv_(ind_layer) * exp(-nv_(ind_layer) * (z_(ind_layer + 1) - z));\n}\n\nvoid GRTCoeff::compute_rtc() {\n  for (int i = 1; i < nl_ - 1; ++i) {\n    auto &e0 = e_[i - 1];\n    auto &e1 = e_[i];\n\n    Matrix2cd mat1;\n    mat1 << e1(0, 0), -e0(0, 1), e1(1, 0), -e0(1, 1);\n\n    // complex_d ad = exp(-nv_(i - 1) * (z_(i) - z_(i - 1)));\n    // complex_d au = exp(-nv_(i) * (z_(i + 1) - z_(i)));\n    complex_d ad = get_Ad(z_(i), i - 1);\n    complex_d au = get_Au(z_(i), i);\n    Matrix2cd mat2;\n    mat2 << e0(0, 0) * ad, -e1(0, 1) * au, e0(1, 0) * ad, -e1(1, 1) * au;\n\n    Matrix2cd result = mat1.inverse() * mat2;\n    t_d_(i) = result(0, 0);\n    r_ud_(i) = result(0, 1);\n    r_du_(i) = result(1, 0);\n    t_u_(i) = result(1, 1);\n  }\n\n  int i = nl_ - 1;\n  auto &e0 = e_[i - 1];\n  auto &e1 = e_[i];\n  Matrix2cd mat1;\n  mat1 << e1(0, 0), -e0(0, 1), e1(1, 0), -e0(1, 1);\n  // complex_d ad = exp(-nv_(i - 1) * (z_(i) - z_(i - 1)));\n  complex_d ad = get_Ad(z_(nl_ - 1), nl_ - 2);\n  Matrix<complex_d, 2, 1> mat2;\n  mat2 << e0(0, 0) * ad, e0(1, 0) * ad;\n\n  Matrix<complex_d, 2, 1> result = mat1.inverse() * mat2;\n  t_d_(i) = result(0, 0);\n  r_du_(i) = result(1, 0);\n}\n\nvoid GRTCoeff::compute_grtc() {\n  for (int i = nl_ - 1; i >= 1; --i) {\n    gt_d_(i) = 1.0 / (1.0 - r_ud_(i) * gr_du_(i + 1)) * t_d_(i);\n    gr_du_(i) = r_du_(i) + t_u_(i) * gr_du_(i + 1) * gt_d_(i);\n  }\n  auto &e0 = e_[0];\n  // complex_d au = exp(-nv_(0) * (z_(1) - z_(0)));\n  complex_d au = get_Au(z_(0), 0);\n  gr_ud_(0) = -1.0 / e0(1, 0) * e0(1, 1) * au;\n  for (int i = 1; i < nl_; ++i) {\n    gt_u_(i) = 1.0 / (1.0 - r_du_(i) * gr_ud_(i - 1)) * t_u_(i);\n    gr_ud_(i) = r_ud_(i) + t_d_(i) * gr_ud_(i - 1) * gt_u_(i);\n  }\n}\n\nvoid GRTCoeff::compute_CdCu() {\n  cd_(0) = 1.0;\n  cu_(0) = gr_du_(1) * cd_(0);\n  for (int i = 1; i < nl_ - 1; ++i) {\n    cd_(i) = gt_d_(i) * cd_(i - 1);\n    cu_(i) = gr_du_(i + 1) * cd_(i);\n  }\n  cd_(nl_ - 1) = gt_d_(nl_ - 1) * cd_(nl_ - 2);\n}\n\nIntegralLayer::IntegralLayer(const Ref<const ArrayXXd> model, const double freq,\n                             const double c)\n    : grtc_(std::make_unique<GRTCoeff>(model, freq, c)), nl_(model.rows()),\n      k_(2.0 * PI * freq / c), pvel_(c), z_(model.col(1)), beta_(model.col(3)),\n      rho_(model.col(2)), mu_(rho_ * beta_ * beta_), nv_(grtc_->nv_),\n      thickness_(nl_ - 1), cd_(grtc_->cd_), cu_(grtc_->cu_),\n      matP_u_u_(nl_, Array22cd::Zero()), matP_uc_u_(nl_, Array22cd::Zero()),\n      matP_uc_uc_(nl_, Array22cd::Zero()), matP_du_du_(nl_, Array22cd::Zero()),\n      matP_duc_du_(nl_, Array22cd::Zero()),\n      matP_duc_duc_(nl_, Array22cd::Zero()),\n      sigma_x_sigma_top_(nl_, Array22cd::Zero()),\n      sigmac_x_sigma_top_(nl_, Array22cd::Zero()),\n      sigma_x_sigmac_top_(nl_, Array22cd::Zero()),\n      sigmac_x_sigmac_top_(nl_, Array22cd::Zero()),\n      sigma_x_sigma_bottom_(nl_, Array22cd::Zero()),\n      sigmac_x_sigma_bottom_(nl_, Array22cd::Zero()),\n      sigma_x_sigmac_bottom_(nl_, Array22cd::Zero()),\n      sigmac_x_sigmac_bottom_(nl_, Array22cd::Zero()),\n      int_ut2_(ArrayXd::Zero(nl_)), int_dut2_(ArrayXd::Zero(nl_)) {\n  for (int i = 0; i < nl_ - 1; ++i) {\n    thickness_(i) = z_(i + 1) - z_(i);\n  }\n\n  initialize_P();\n  initialize_sigma();\n\n  integrate_ut2();\n  integrate_dut2();\n}\n\nvoid IntegralLayer::initialize_P() {\n  for (auto i = 0; i < nl_; ++i) {\n    const complex_d nv = nv_(i);\n    const complex_d nvc = std::conj(nv_(i));\n\n    matP_u_u_[i] << 1.0 / (-nv - nv), 1.0, 1.0, 1.0 / (nv + nv);\n    matP_uc_u_[i] << 1.0 / (-nvc - nv), 1.0 / (-nvc + nv), 1.0 / (nvc - nv),\n        1.0 / (nvc + nv);\n    matP_uc_uc_[i] << 1.0 / (-nvc - nvc), 1.0, 1.0, 1.0 / (nvc + nvc);\n    matP_du_du_[i] << nv / (-2.0), -nv * nv, -nv * nv, nv / 2.0;\n    matP_duc_du_[i] << nvc * nv / (-nvc - nv), -nvc * nv / (-nvc + nv),\n        -nvc * nv / (nvc - nv), nvc * nv / (nvc + nv);\n    matP_duc_duc_[i] << nvc / (-2.0), -nvc * nvc, -nvc * nvc, nvc / 2.0;\n\n    if (pvel_ > beta_(i)) {\n      matP_uc_u_[i](0, 0) = 1.0;\n      matP_uc_u_[i](1, 1) = 1.0;\n      matP_duc_du_[i](0, 0) = nvc * nv;\n      matP_duc_du_[i](1, 1) = nvc * nv;\n    } else {\n      matP_uc_u_[i](0, 1) = 1.0;\n      matP_uc_u_[i](1, 0) = 1.0;\n      matP_duc_du_[i](0, 1) = -nvc * nv;\n      matP_duc_du_[i](1, 0) = -nvc * nv;\n    }\n  }\n}\n\nvoid IntegralLayer::initialize_sigma() {\n  MatrixXcd sigma_bottom = MatrixXcd::Zero(2, nl_);\n  MatrixXcd sigma_top = MatrixXcd::Zero(2, nl_);\n  for (auto i = 0; i < nl_ - 1; ++i) {\n    sigma_bottom.col(i) << cd_(i), cu_(i) * exp(-nv_(i) * thickness_(i));\n    sigma_top.col(i) << cd_(i) * exp(-nv_(i) * thickness_(i)), cu_(i);\n  }\n  sigma_bottom.col(nl_ - 1) << cd_(nl_ - 1), 0;\n  sigma_top.col(nl_ - 1).fill(0);\n\n  for (auto id_layer = 0; id_layer < nl_; ++id_layer) {\n    for (auto i = 0; i < 2; ++i) {\n      for (auto j = 0; j < 2; ++j) {\n        sigma_x_sigma_top_[id_layer](i, j) =\n            sigma_top(i, id_layer) * sigma_top(j, id_layer);\n        sigmac_x_sigma_top_[id_layer](i, j) =\n            conj(sigma_top(i, id_layer)) * sigma_top(j, id_layer);\n        sigma_x_sigmac_top_[id_layer](i, j) =\n            sigma_top(i, id_layer) * conj(sigma_top(j, id_layer));\n        sigmac_x_sigmac_top_[id_layer](i, j) =\n            conj(sigma_top(i, id_layer)) * conj(sigma_top(j, id_layer));\n\n        sigma_x_sigma_bottom_[id_layer](i, j) =\n            sigma_bottom(i, id_layer) * sigma_bottom(j, id_layer);\n        sigmac_x_sigma_bottom_[id_layer](i, j) =\n            conj(sigma_bottom(i, id_layer)) * sigma_bottom(j, id_layer);\n        sigma_x_sigmac_bottom_[id_layer](i, j) =\n            sigma_bottom(i, id_layer) * conj(sigma_bottom(j, id_layer));\n        sigmac_x_sigmac_bottom_[id_layer](i, j) =\n            conj(sigma_bottom(i, id_layer)) * conj(sigma_bottom(j, id_layer));\n      }\n    }\n    if (id_layer != nl_ - 1) {\n      sigma_x_sigma_top_[id_layer](0, 1) *= thickness_(id_layer);\n      sigma_x_sigma_top_[id_layer](1, 0) *= thickness_(id_layer);\n      sigmac_x_sigmac_top_[id_layer](0, 1) *= thickness_(id_layer);\n      sigmac_x_sigmac_top_[id_layer](1, 0) *= thickness_(id_layer);\n      if (pvel_ > beta_(id_layer)) {\n        sigmac_x_sigma_top_[id_layer](0, 0) =\n            conj(cd_(id_layer)) * cd_(id_layer) * thickness_(id_layer);\n        sigmac_x_sigma_top_[id_layer](1, 1) =\n            conj(cu_(id_layer)) * cu_(id_layer) * thickness_(id_layer);\n        sigma_x_sigmac_top_[id_layer](0, 0) =\n            cd_(id_layer) * conj(cd_(id_layer)) * thickness_(id_layer);\n        sigmac_x_sigma_top_[id_layer](1, 1) =\n            cu_(id_layer) * conj(cu_(id_layer)) * thickness_(id_layer);\n      } else {\n        sigmac_x_sigma_top_[id_layer](0, 1) *= thickness_(id_layer);\n        sigmac_x_sigma_top_[id_layer](1, 0) *= thickness_(id_layer);\n        sigma_x_sigmac_top_[id_layer](0, 1) *= thickness_(id_layer);\n        sigma_x_sigmac_top_[id_layer](1, 0) *= thickness_(id_layer);\n      }\n      sigma_x_sigma_bottom_[id_layer](0, 1) = 0.;\n      sigma_x_sigma_bottom_[id_layer](1, 0) = 0.;\n      sigmac_x_sigmac_bottom_[id_layer](0, 1) = 0.;\n      sigmac_x_sigmac_bottom_[id_layer](1, 0) = 0.;\n\n      if (pvel_ > beta_(id_layer)) {\n        sigmac_x_sigma_bottom_[id_layer](0, 0) = 0.;\n        sigmac_x_sigma_bottom_[id_layer](1, 1) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](0, 0) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](1, 1) = 0.;\n      } else {\n        sigmac_x_sigma_bottom_[id_layer](0, 1) = 0.;\n        sigmac_x_sigma_bottom_[id_layer](1, 0) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](0, 1) = 0.;\n        sigma_x_sigmac_bottom_[id_layer](1, 0) = 0.;\n      }\n    }\n  }\n}\n\ndouble IntegralLayer::intker_ut2_top(int id_layer) {\n  Array22cd auu = matP_u_u_[id_layer] * sigma_x_sigma_top_[id_layer];\n  Array22cd aucu = matP_uc_u_[id_layer] * sigmac_x_sigma_top_[id_layer];\n  Array22cd aucuc = matP_uc_uc_[id_layer] * sigmac_x_sigmac_top_[id_layer];\n  complex_d result = auu.sum() + 2.0 * aucu.sum() + aucuc.sum();\n  return result.real() / 4.0;\n}\n\ndouble IntegralLayer::intker_ut2_bottom(int id_layer) {\n  Array22cd auu = matP_u_u_[id_layer] * sigma_x_sigma_bottom_[id_layer];\n  Array22cd aucu = matP_uc_u_[id_layer] * sigmac_x_sigma_bottom_[id_layer];\n  Array22cd aucuc = matP_uc_uc_[id_layer] * sigmac_x_sigmac_bottom_[id_layer];\n  complex_d result = auu.sum() + 2.0 * aucu.sum() + aucuc.sum();\n  return result.real() / 4.0;\n}\n\ndouble IntegralLayer::intker_dut2_top(int id_layer) {\n  Array22cd auu = matP_du_du_[id_layer] * sigma_x_sigma_top_[id_layer];\n  Array22cd aucu = matP_duc_du_[id_layer] * sigmac_x_sigma_top_[id_layer];\n  Array22cd aucuc = matP_duc_duc_[id_layer] * sigmac_x_sigmac_top_[id_layer];\n  complex_d result = auu.sum() + 2.0 * aucu.sum() + aucuc.sum();\n  return result.real() / 4.0;\n}\n\ndouble IntegralLayer::intker_dut2_bottom(int id_layer) {\n  Array22cd auu = matP_du_du_[id_layer] * sigma_x_sigma_bottom_[id_layer];\n  Array22cd aucu = matP_duc_du_[id_layer] * sigmac_x_sigma_bottom_[id_layer];\n  Array22cd aucuc = matP_duc_duc_[id_layer] * sigmac_x_sigmac_bottom_[id_layer];\n  complex_d result = auu.sum() + 2.0 * aucu.sum() + aucuc.sum();\n  return result.real() / 4.0;\n}\n\nvoid IntegralLayer::integrate_ut2() {\n  for (int id_layer = 0; id_layer < nl_; ++id_layer) {\n    int_ut2_(id_layer) = intker_ut2_top(id_layer) - intker_ut2_bottom(id_layer);\n  }\n}\n\nvoid IntegralLayer::integrate_dut2() {\n  for (int id_layer = 0; id_layer < nl_; ++id_layer) {\n    int_dut2_(id_layer) =\n        intker_dut2_top(id_layer) - intker_dut2_bottom(id_layer);\n  }\n}\n\ndouble IntegralLayer::compute_I1() {\n  ArrayXd ker = rho_ * int_ut2_;\n  double i2 = 0.5 * ker.sum();\n  return i2;\n}\n\ndouble IntegralLayer::compute_I2() {\n  ArrayXd ker = mu_ * int_ut2_;\n  double i2 = 0.5 * ker.sum();\n  return i2;\n}\n\ndouble IntegralLayer::compute_I3() {\n  ArrayXd ker = mu_ * int_dut2_;\n  double i2 = 0.5 * ker.sum();\n  return i2;\n}\n\nArrayXd IntegralLayer::compute_kvs() {\n  ArrayXd kvs(nl_);\n  for (int i = 0; i < nl_; ++i) {\n    kvs(i) =\n        0.5 * rho_(i) * beta_(i) * (int_ut2_(i) + int_dut2_(i) / pow(k_, 2));\n  }\n  return kvs;\n}\n\nGradientSH::~GradientSH() = default;\n\nArrayXd GradientSH::compute(const double freq, const double c) const {\n  IntegralLayer intl(model_, freq, c);\n  double I2 = intl.compute_I2();\n  ArrayXd kvs = intl.compute_kvs();\n\n  kvs *= c / I2;\n\n  return kvs;\n}\n\n} // namespace grad_sh", "meta": {"hexsha": "78646388c6712e9a55c24f9caa08fb824264b551", "size": 12356, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/gradient_sh.cc", "max_stars_repo_name": "pan3rock/DisbaTomo", "max_stars_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-07-30T03:27:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T14:05:47.000Z", "max_issues_repo_path": "src/gradient_sh.cc", "max_issues_repo_name": "pan3rock/DisbaTomo", "max_issues_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gradient_sh.cc", "max_forks_repo_name": "pan3rock/DisbaTomo", "max_forks_repo_head_hexsha": "b1e6ffa3afd911f1934cd6274854b5fa4161a9cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2021-07-31T12:38:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T15:07:53.000Z", "avg_line_length": 34.5139664804, "max_line_length": 80, "alphanum_fraction": 0.6062641632, "num_tokens": 4578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.6103828737505397}}
{"text": "//\r\n// Copyright 2014 Mitsubishi Electric Research Laboratories All\r\n// Rights Reserved.\r\n//\r\n// Permission to use, copy and modify this software and its\r\n// documentation without fee for educational, research and non-profit\r\n// purposes, is hereby granted, provided that the above copyright\r\n// notice, this paragraph, and the following three paragraphs appear\r\n// in all copies.\r\n//\r\n// To request permission to incorporate this software into commercial\r\n// products contact: Director; Mitsubishi Electric Research\r\n// Laboratories (MERL); 201 Broadway; Cambridge, MA 02139.\r\n//\r\n// IN NO EVENT SHALL MERL BE LIABLE TO ANY PARTY FOR DIRECT,\r\n// INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING\r\n// LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS\r\n// DOCUMENTATION, EVEN IF MERL HAS BEEN ADVISED OF THE POSSIBILITY OF\r\n// SUCH DAMAGES.\r\n//\r\n// MERL SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT\r\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\r\n// FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN\r\n// \"AS IS\" BASIS, AND MERL HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE,\r\n// SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\r\n//\r\n#pragma once\r\n//\r\n// Note:\r\n// If you use dsyevh3 library [http://www.mpi-hd.mpg.de/personalhomes/globes/3x3/],\r\n// this function can be accelerated by uncommenting the following line\r\n//#define USE_DSYEVH3\r\n//\r\n#ifdef USE_DSYEVH3\r\n\t#include \"dsyevh3/dsyevh3.h\"\r\n#else\r\n\t#include <Eigen/Core>\r\n\t#include <Eigen/Dense>\r\n#endif\r\n\r\n#include <cmath>\r\n#include <limits>\r\n\r\nnamespace LA {\r\n\t//s[0]<=s[1]<=s[2], V[:][i] correspond to s[i]\r\n\tinline static bool eig33sym(double K[3][3], double s[3], double V[3][3])\r\n\t{\r\n#ifdef USE_DSYEVH3\r\n\t\tdouble tmpV[3][3];\r\n\t\tif(dsyevh3(K, tmpV, s)!=0) return false;\r\n\r\n\t\tint order[]={0,1,2};\r\n\t\tfor(int i=0; i<3; ++i) {\r\n\t\t\tfor(int j=i+1; j<3; ++j) {\r\n\t\t\t\tif(s[i]>s[j]) {\r\n\t\t\t\t\tdouble tmp=s[i];\r\n\t\t\t\t\ts[i]=s[j];\r\n\t\t\t\t\ts[j]=tmp;\r\n\t\t\t\t\tint tmpor=order[i];\r\n\t\t\t\t\torder[i]=order[j];\r\n\t\t\t\t\torder[j]=tmpor;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tV[0][0]=tmpV[0][order[0]]; V[0][1]=tmpV[0][order[1]]; V[0][2]=tmpV[0][order[2]];\r\n\t\tV[1][0]=tmpV[1][order[0]]; V[1][1]=tmpV[1][order[1]]; V[1][2]=tmpV[1][order[2]];\r\n\t\tV[2][0]=tmpV[2][order[0]]; V[2][1]=tmpV[2][order[1]]; V[2][2]=tmpV[2][order[2]];\r\n#else\r\n\t\t//below we did not specify row major since it does not matter, K==K'\r\n\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es(\r\n\t\t\tEigen::Map<Eigen::Matrix3d>(K[0], 3, 3) );\r\n\t\tEigen::Map<Eigen::Vector3d>(s,3,1)=es.eigenvalues();\r\n\t\t//below we need to specify row major since V!=V'\r\n\t\tEigen::Map<Eigen::Matrix<double,3,3,Eigen::RowMajor>>(V[0],3,3)=es.eigenvectors();\r\n#endif\r\n\t\treturn true;\r\n\t}\r\n}//end of namespace LA", "meta": {"hexsha": "fc90b0215847de4c5bf4bf8c6d5e8c1d654ab700", "size": 2738, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/peac/eig33sym.hpp", "max_stars_repo_name": "symao/PEAC", "max_stars_repo_head_hexsha": "c4fddbdd7aafaf9af7a29602b4427009bc6f360b", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2018-05-02T07:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T04:05:05.000Z", "max_issues_repo_path": "include/peac/eig33sym.hpp", "max_issues_repo_name": "symao/PEAC", "max_issues_repo_head_hexsha": "c4fddbdd7aafaf9af7a29602b4427009bc6f360b", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-05T11:22:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T08:43:36.000Z", "max_forks_repo_path": "include/peac/eig33sym.hpp", "max_forks_repo_name": "symao/PEAC", "max_forks_repo_head_hexsha": "c4fddbdd7aafaf9af7a29602b4427009bc6f360b", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2017-11-07T07:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T03:36:04.000Z", "avg_line_length": 35.1025641026, "max_line_length": 85, "alphanum_fraction": 0.6610664719, "num_tokens": 850, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6103769249771028}}
{"text": "/*****************************************************************************\n*\n* Copyright (C) 2015-2017 by Synge Todo <wistaria@phy.s.u-tokyo.ac.jp>\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n// Calculating free energy density of square lattice Ising model by the transfer matrix method\n\n#include <cmath>\n#include <vector>\n#include <boost/array.hpp>\n#include <lattice/square.hpp>\n#include <lse/exp_number.hpp>\n\n#ifndef ISING_SQUARE_TRANSFER_MATRIX_HPP\n#define ISING_SQUARE_TRANSFER_MATRIX_HPP\n\nnamespace ising {\nnamespace square {\n\nstruct transfer_matrix {\npublic:\n  typedef lse::exp_double exp_double;\n  template<typename VEC>\n  static exp_double product_D(double beta, std::vector<double> const& inter_x,\n                                   std::vector<double> const& field, VEC& v) {\n    int width = inter_x.size();\n    int dim = 1 << width;\n    exp_double normal = 1;\n    std::vector<boost::array<double, 2> > weight(width);\n    for (int b = 0; b < width; ++b) {\n      double offset = std::abs(beta * inter_x[b]);\n      normal *= lse::exp_value(offset);\n      weight[b][0] = std::exp(beta * inter_x[b] - offset);\n      weight[b][1] = std::exp(-beta * inter_x[b] - offset);\n    }\n    for (int c = 0; c < dim; ++c) {\n      double elem = v[c];\n      for (int b = 0; b < width; ++b) {\n        int s0 = b;\n        int s1 = (b+1) % width;\n        elem *= weight[b][((c >> s0) & 1) ^ ((c >> s1) & 1)];\n      }\n      v[c] = elem;\n    }\n    if (field.size()) {\n      for (int s = 0; s < width; ++s) {\n        double offset = std::abs(beta * field[s]);\n        normal *= lse::exp_value(offset);\n        weight[s][0] = std::exp(beta * field[s] - offset);\n        weight[s][1] = std::exp(-beta * field[s] - offset);\n      }\n      for (int c = 0; c < dim; ++c) {\n        double elem = v[c];\n        for (int s = 0; s < width; ++s) elem *= weight[s][((c >> s) & 1)];\n        v[c] = elem;\n      }\n    }\n    return normal;\n  }\n\n  template<typename VEC>\n  static exp_double product_D(double beta, std::vector<double> const& inter_x, VEC& v) {\n    std::vector<double> field(0);\n    return product_D(beta, inter_x, field, v);\n  }\n\n  template<typename VEC>\n  static exp_double product_U(double beta, std::vector<double> const& inter_y, VEC& v) {\n    int width = inter_y.size();\n    int dim = 1 << width;\n    exp_double normal = 1;\n    boost::array<double, 2> weight;\n    for (int s = 0; s < width; ++s) {\n      double offset = std::abs(beta * inter_y[s]);\n      normal *= lse::exp_value(offset);\n      weight[0] = std::exp(beta * inter_y[s] - offset);\n      weight[1] = std::exp(-beta * inter_y[s] - offset);\n      for (int c0 = 0; c0 < dim; ++c0) {\n        if (((c0 >> s) & 1) == 0) {\n          int c1 = c0 ^ (1 << s);\n          double v0 = v[c0];\n          double v1 = v[c1];\n          v[c0] = weight[0] * v0 + weight[1] * v1;\n          v[c1] = weight[0] * v1 + weight[1] * v0;\n        }\n      }\n    }\n    return normal;\n  }\n\n  static double free_energy(double beta, lattice::square const& lat,\n                            std::vector<double> const& inter,\n                            std::vector<double> const& field = std::vector<double>(0)) {\n    int Lx = lat.get_length_x();\n    int Ly = lat.get_length_y();\n    std::vector<double> inter_x(Lx), inter_y(Lx), field_x(field.size() > 0 ? Lx : 0);\n    int dim = 1 << Lx;\n    std::vector<double> v(dim);\n    exp_double sum = 0;\n    for (int i = 0; i < dim; ++i) {\n      exp_double weight = 1;\n      for (int j = 0; j < dim; ++j) v[j] = 0;\n      v[i] = 1;\n      for (int y = 0; y < Ly; ++y) {\n        for (int x = 0; x < Lx; ++x) {\n          inter_x[x] = inter[2 * (Lx * y + x)];\n          inter_y[x] = inter[2 * (Lx * y + x) + 1];\n        }\n        if (field_x.size()) {\n          for (int x = 0; x < Lx; ++x) {\n            field_x[x] = field[Lx * y + x];\n          }\n        }\n        weight *= ising::square::transfer_matrix::product_D(beta, inter_x, field_x, v);\n        weight *= ising::square::transfer_matrix::product_U(beta, inter_y, v);\n      }\n      weight *= v[i];\n      sum += weight;\n    }\n    return -log(sum) / beta;\n  }\n\n  static double free_energy(double beta, lattice::square const& lat, double J, double H = 0.0) {\n    std::vector<double> inter(lat.num_bonds(), J);\n    std::vector<double> field((H != 0.0) ? lat.num_sites() : 0, H);\n    return free_energy(beta, lat, inter, field);\n  }\n\n  static double free_energy_density(double beta, lattice::square const& lat,\n                                    std::vector<double> const& inter,\n                                    std::vector<double> const& field = std::vector<double>(0)) {\n    return free_energy(beta, lat, inter, field) / lat.num_sites();\n  }\n\n  static double free_energy_density(double beta, lattice::square const& lat, double J,\n                                    double H = 0.0) {\n    return free_energy(beta, lat, J, H) / lat.num_sites();\n  }\n};\n\n} // end namespace square\n} // end namespace ising\n\n#endif // ISING_SQUARE_TRANSFER_MATRIX_HPP\n", "meta": {"hexsha": "47c9c3b1faecb9562a932c31533931a6937262da", "size": 5154, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ising/square/transfer_matrix.hpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "ising/square/transfer_matrix.hpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "ising/square/transfer_matrix.hpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5906040268, "max_line_length": 96, "alphanum_fraction": 0.5322079938, "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.6103105245464835}}
{"text": "//\n//  dt_util.h\n//  Classifer_RF\n//\n//  Created by jimmy on 2017-02-16.\n//  Copyright (c) 2017 Nowhere Planet. All rights reserved.\n//\n\n#ifndef __Classifer_RF__dt_util__\n#define __Classifer_RF__dt_util__\n\n// decision tree util\n#include <stdio.h>\n#include <vector>\n#include <Eigen/Dense>\n#include <unordered_map>\n#include <string>\n\nusing std::vector;\nusing std::string;\nusing Eigen::VectorXf;\nusing Eigen::VectorXd;\nusing std::vector;\n\nclass DTUtil\n{\npublic:\n    // spatial variance objective\n    template <class T>\n    static double spatialVariance(const vector<T> & labels, const vector<unsigned int> & indices);\n    \n    \n    // mean and standard deviation\n    template <class T>\n    static void meanStddev(const vector<T> & labels, const vector<unsigned int> & indices, T & mean, T & sigma);\n    \n    // mean value of data\n    // mask: index of data\n    template <class T>\n    static T mean(const vector<T> & data,\n                  const vector<unsigned int> & mask);\n    \n    // mean value of data\n    template <class T>\n    static T mean(const vector<T> & data);\n    \n    // mean value and median value of errors\n    // median value: each dimension is independently computed\n    template <class T>\n    static void meanMedianError(const vector<T> & errors, T & mean, T & median);\n    \n    // balance objective\n    static double balanceLoss(const int leftNodeSize, const int rightNodeSize);\n    \n    // [start, step, end)\n    template <class T>\n    static vector<T> range(int start, int end, int step)\n    {\n        assert((end - start) * step >= 0);\n        vector<T> ret;\n        for (int i = start; i < end; i += step) {\n            ret.push_back((T)i);\n        }\n        return ret;\n    }\n\n    \n};\n\n#endif /* defined(__Classifer_RF__dt_util__) */\n", "meta": {"hexsha": "14143c4b6b04d0ba696ace34e748fcbe9b8d8ca7", "size": 1756, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dt_common/dt_util.hpp", "max_stars_repo_name": "LiliMeng/btrf", "max_stars_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T15:24:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T13:51:05.000Z", "max_issues_repo_path": "src/dt_common/dt_util.hpp", "max_issues_repo_name": "LiliMeng/btrf", "max_issues_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dt_common/dt_util.hpp", "max_forks_repo_name": "LiliMeng/btrf", "max_forks_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-11-08T16:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-21T03:40:02.000Z", "avg_line_length": 24.7323943662, "max_line_length": 112, "alphanum_fraction": 0.6378132118, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7401743735019594, "lm_q1q2_score": 0.6102455898319967}}
{"text": "\n#include <test_common.h>\n#include <igl/per_face_normals.h>\n#include <Eigen/Geometry>\n\nTEST_CASE(\"per_face_normals: dot\", \"[igl]\")\n{\n  const auto test_case = [](const std::string &param)\n  {\n\t  Eigen::MatrixXd V,N;\n\t  Eigen::MatrixXi F;\n\t  // Load example mesh: GetParam() will be name of mesh file\n\t  test_common::load_mesh(param, V, F);\n\t  igl::per_face_normals(V,F,N);\n\t  REQUIRE (N.rows() == F.rows());\n\t  for(int f = 0;f<N.rows();f++)\n\t  {\n\t    for(int c = 0;c<3;c++)\n\t    {\n\t      // Every half-edge dot the normal should be 0\n\t      REQUIRE(std::abs((V.row(F(f,c))-V.row(F(f,(c+1)%3))).dot(N.row(f))) < 1e-12);\n\t    }\n\t  }\n\t  // REQUIRE (b == a);\n\t  // REQUIRE (a==b);\n\t  // ASSERT_NEAR(a,b,1e-15)\n\t  // REQUIRE (1e-12 > a);\n  };\n\n  test_common::run_test_cases(test_common::all_meshes(), test_case);\n}\n", "meta": {"hexsha": "8406c3905c76633ac190103a3c55ec67ddefcca1", "size": 809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "External/libigl-2.1.0/tests/include/igl/per_face_normals.cpp", "max_stars_repo_name": "RokKos/eol-cloth", "max_stars_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "External/libigl-2.1.0/tests/include/igl/per_face_normals.cpp", "max_issues_repo_name": "RokKos/eol-cloth", "max_issues_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "External/libigl-2.1.0/tests/include/igl/per_face_normals.cpp", "max_forks_repo_name": "RokKos/eol-cloth", "max_forks_repo_head_hexsha": "b9c6f55f25ba17f33532ea5eefa41fedd29c5206", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.28125, "max_line_length": 84, "alphanum_fraction": 0.587144623, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6102455851066166}}
{"text": "/*\r\n * bulirsch_stoer.cpp\r\n *\r\n * Copyright 2011-2013 Mario Mulansky\r\n * Copyright 2011-2012 Karsten Ahnert\r\n *\r\n * Distributed under the Boost Software License, Version 1.0.\r\n * (See accompanying file LICENSE_1_0.txt or\r\n * copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#define _USE_MATH_DEFINES\r\n#include <cmath>\r\n\r\n#include <boost/array.hpp>\r\n#include <boost/ref.hpp>\r\n\r\n#include <boost/numeric/odeint/config.hpp>\r\n\r\n#include <boost/numeric/odeint.hpp>\r\n#include <boost/numeric/odeint/stepper/bulirsch_stoer.hpp>\r\n#include <boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\ntypedef boost::array< double , 1 > state_type;\r\n\r\n/*\r\n * x' = ( - x*sin t  + 2 tan x ) y\r\n * with x( pi/6 ) = 2/sqrt(3) the analytic solution is 1/cos t\r\n */\r\n\r\nvoid rhs( const state_type &x , state_type &dxdt , const double t )\r\n{\r\n    dxdt[0] = ( - x[0] * sin( t ) + 2.0 * tan( t ) ) * x[0];\r\n}\r\n\r\nvoid rhs2( const state_type &x , state_type &dxdt , const double t )\r\n{\r\n    dxdt[0] = sin(t);\r\n}\r\n\r\n\r\nofstream out;\r\n\r\nvoid write_out( const state_type &x , const double t )\r\n{\r\n    out << t << '\\t' << x[0] << endl;\r\n}\r\n\r\nint main()\r\n{\r\n    bulirsch_stoer_dense_out< state_type > stepper( 1E-8 , 0.0 , 0.0 , 0.0 );\r\n    bulirsch_stoer< state_type > stepper2( 1E-8 , 0.0 , 0.0 , 0.0 );\r\n\r\n    state_type x = {{ 2.0 / sqrt(3.0) }};\r\n\r\n    double t = M_PI/6.0;\r\n    //double t = 0.0;\r\n    double dt = 0.01;\r\n    double t_end = M_PI/2.0 - 0.1;\r\n    //double t_end = 100.0;\r\n\r\n    out.open( \"bs.dat\" );\r\n    out.precision(16);\r\n    integrate_const( stepper , rhs , x , t , t_end , dt , write_out );\r\n    out.close();\r\n\r\n    x[0] = 2.0 / sqrt(3.0);\r\n\r\n    out.open( \"bs2.dat\" );\r\n    out.precision(16);\r\n    integrate_adaptive( stepper , rhs , x , t , t_end , dt , write_out );\r\n    out.close();\r\n\r\n    x[0] = 2.0 / sqrt(3.0);\r\n\r\n    out.open( \"bs3.dat\" );\r\n    out.precision(16);\r\n    integrate_adaptive( stepper2 , rhs , x , t , t_end , dt , write_out );\r\n    out.close();\r\n\r\n\r\n    typedef runge_kutta_dopri5< state_type > dopri5_type;\r\n    typedef controlled_runge_kutta< dopri5_type > controlled_dopri5_type;\r\n    typedef dense_output_runge_kutta< controlled_dopri5_type > dense_output_dopri5_type;\r\n\r\n    dense_output_dopri5_type dopri5 = make_dense_output( 1E-9 , 1E-9 , dopri5_type() );\r\n\r\n    x[0] = 2.0 / sqrt(3.0);\r\n\r\n    out.open( \"bs4.dat\" );\r\n    out.precision(16);\r\n    integrate_adaptive( dopri5 , rhs , x , t , t_end , dt , write_out );\r\n    out.close();\r\n\r\n}\r\n", "meta": {"hexsha": "a998fe85bc9708adaaf487d91d3ea7e1c053b244", "size": 2575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/bulirsch_stoer.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/bulirsch_stoer.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/bulirsch_stoer.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 25.495049505, "max_line_length": 89, "alphanum_fraction": 0.6116504854, "num_tokens": 831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6102455787216875}}
{"text": "/**\n * Copyright (c) 2020 Neka-Nat\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n**/\n#include \"cupoch/visualization/utility/gl_helper.h\"\n\n#include <Eigen/Dense>\n#include <cmath>\n\nnamespace cupoch {\nnamespace visualization {\nnamespace gl_helper {\n\nGLMatrix4f LookAt(const Eigen::Vector3f &eye,\n                  const Eigen::Vector3f &lookat,\n                  const Eigen::Vector3f &up) {\n    Eigen::Vector3f front_dir = (eye - lookat).normalized();\n    Eigen::Vector3f up_dir = up.normalized();\n    Eigen::Vector3f right_dir = up_dir.cross(front_dir).normalized();\n    up_dir = front_dir.cross(right_dir).normalized();\n\n    Eigen::Matrix4f mat = Eigen::Matrix4f::Zero();\n    mat.block<1, 3>(0, 0) = right_dir.transpose();\n    mat.block<1, 3>(1, 0) = up_dir.transpose();\n    mat.block<1, 3>(2, 0) = front_dir.transpose();\n    mat(0, 3) = -right_dir.dot(eye);\n    mat(1, 3) = -up_dir.dot(eye);\n    mat(2, 3) = -front_dir.dot(eye);\n    mat(3, 3) = 1.0;\n    return mat.cast<GLfloat>();\n}\n\nGLMatrix4f Perspective(float field_of_view_,\n                       float aspect,\n                       float z_near,\n                       float z_far) {\n    Eigen::Matrix4f mat = Eigen::Matrix4f::Zero();\n    float fov_rad = field_of_view_ / 180.0 * M_PI;\n    float tan_half_fov = std::tan(fov_rad / 2.0);\n    mat(0, 0) = 1.0 / aspect / tan_half_fov;\n    mat(1, 1) = 1.0 / tan_half_fov;\n    mat(2, 2) = -(z_far + z_near) / (z_far - z_near);\n    mat(3, 2) = -1.0;\n    mat(2, 3) = -2.0 * z_far * z_near / (z_far - z_near);\n    return mat.cast<GLfloat>();\n}\n\nGLMatrix4f Ortho(float left,\n                 float right,\n                 float bottom,\n                 float top,\n                 float z_near,\n                 float z_far) {\n    Eigen::Matrix4f mat = Eigen::Matrix4f::Zero();\n    mat(0, 0) = 2.0 / (right - left);\n    mat(1, 1) = 2.0 / (top - bottom);\n    mat(2, 2) = -2.0 / (z_far - z_near);\n    mat(0, 3) = -(right + left) / (right - left);\n    mat(1, 3) = -(top + bottom) / (top - bottom);\n    mat(2, 3) = -(z_far + z_near) / (z_far - z_near);\n    mat(3, 3) = 1.0;\n    return mat.cast<GLfloat>();\n}\n\nEigen::Vector3f Project(const Eigen::Vector3f &point,\n                        const GLMatrix4f &mvp_matrix,\n                        const int width,\n                        const int height) {\n    Eigen::Vector4f pos = mvp_matrix.cast<float>() *\n                          Eigen::Vector4f(point(0), point(1), point(2), 1.0);\n    if (pos(3) == 0.0) {\n        return Eigen::Vector3f::Zero();\n    }\n    pos /= pos(3);\n    return Eigen::Vector3f((pos(0) * 0.5 + 0.5) * (float)width,\n                           (pos(1) * 0.5 + 0.5) * (float)height,\n                           (1.0 + pos(2)) * 0.5);\n}\n\nEigen::Vector3f Unproject(const Eigen::Vector3f &screen_point,\n                          const GLMatrix4f &mvp_matrix,\n                          const int width,\n                          const int height) {\n    Eigen::Vector4f point =\n            mvp_matrix.cast<float>().inverse() *\n            Eigen::Vector4f(screen_point(0) / (float)width * 2.0 - 1.0,\n                            screen_point(1) / (float)height * 2.0 - 1.0,\n                            screen_point(2) * 2.0 - 1.0, 1.0);\n    if (point(3) == 0.0) {\n        return Eigen::Vector3f::Zero();\n    }\n    point /= point(3);\n    return point.block<3, 1>(0, 0);\n}\n\nint ColorCodeToPickIndex(const Eigen::Vector4i &color) {\n    if (color(0) == 255) {\n        return -1;\n    } else {\n        return ((color(0) * 256 + color(1)) * 256 + color(2)) * 256 + color(3);\n    }\n}\n\n}  // namespace gl_helper\n}  // namespace visualization\n}  // namespace cupoch", "meta": {"hexsha": "5aa10b98fea632c3774d8ab6b771b82a39d75c56", "size": 4639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cupoch/visualization/utility/gl_helper.cpp", "max_stars_repo_name": "collector-m/cupoch", "max_stars_repo_head_hexsha": "1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 522.0, "max_stars_repo_stars_event_min_datetime": "2020-01-19T05:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T04:36:52.000Z", "max_issues_repo_path": "src/cupoch/visualization/utility/gl_helper.cpp", "max_issues_repo_name": "collector-m/cupoch", "max_issues_repo_head_hexsha": "1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 87.0, "max_issues_repo_issues_event_min_datetime": "2020-02-23T09:56:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T13:35:15.000Z", "max_forks_repo_path": "src/cupoch/visualization/utility/gl_helper.cpp", "max_forks_repo_name": "collector-m/cupoch", "max_forks_repo_head_hexsha": "1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 74.0, "max_forks_repo_forks_event_min_datetime": "2020-01-27T15:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T11:58:22.000Z", "avg_line_length": 38.0245901639, "max_line_length": 80, "alphanum_fraction": 0.5826686786, "num_tokens": 1335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.610245577315405}}
{"text": "#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\ncpp_int Combination(int n, int r) {\n    cpp_int u = 1, d = 1;\n    for (int i = 2; i <= n; i++) {\n        u *= i;\n        if (i <= n - r) d *= i;\n    }\n    for (int i = 2; i <= r; i++) d *= i;\n    return u / d;\n}\nint main() {\n    int l; cin >> l;\n    cpp_int ans = Combination(l - 1, 11);\n    cout << ans << endl;\n}\n", "meta": {"hexsha": "bfee14df82f4940964c41c20657eca2b8131f473", "size": 495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/abc185/c/main.cpp", "max_stars_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_stars_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AtCoder/abc185/c/main.cpp", "max_issues_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_issues_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-10-19T08:47:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T05:23:56.000Z", "max_forks_repo_path": "AtCoder/abc185/c/main.cpp", "max_forks_repo_name": "H-Tatsuhiro/Com_Pro-Cpp", "max_forks_repo_head_hexsha": "fd79f7821a76b11f4a6f83bbb26a034db577a877", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5, "max_line_length": 43, "alphanum_fraction": 0.5474747475, "num_tokens": 156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.6102411465562506}}
{"text": "#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n\n#include <opencv2/opencv.hpp>\n#include <pcl/common/common_headers.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/common/transforms.h>\n\n#include \"imgProc.hpp\"\n#include \"sfm.hpp\"\n#include \"tapl/pte/ptEngine.hpp\"\n\ninline double deg2rad(double deg) { return deg * M_PI / 180.0; }\ninline double rad2deg(double rad) { return rad * 180.0 / M_PI; }\n\n/**\n * Estimate four possible R and T from the Essential Matrix\n */\nstd::vector<Eigen::MatrixXd> computeInitialRTfromE(const Eigen::MatrixXd &E) {\n   \n    // SVD decomposition\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(E, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n    // build 'Z' and 'W'\n    Eigen::MatrixXd Z(3,3);\n    Z << 0, 1, 0, \n        -1, 0, 0, \n         0, 0, 0;\n    Eigen::MatrixXd W(3,3);\n    W << 0, -1, 0, \n         1,  0, 0, \n         0,  0, 1;\n\n    // E can be re-written as E=MQ; where M=U.Z.U^T and Q=U.W.V^T or Q=U.W^T.V^T\n    Eigen::MatrixXd M = svd.matrixU() * Z * svd.matrixU().transpose();\n    Eigen::MatrixXd Q1 = svd.matrixU() * W * svd.matrixV().transpose();\n    Eigen::MatrixXd Q2 = svd.matrixU() * W.transpose() * svd.matrixV().transpose();\n\n    // R can be computed as R=(det Q)Q\n    Eigen::MatrixXd R1 = Q1.determinant() * Q1;\n    Eigen::MatrixXd R2 = Q2.determinant() * Q2;\n\n    // E = U\u03a3V^T, T is simply either u3 or \u2212u3, where u3 is the third column vector of U\n    Eigen::MatrixXd T1 = svd.matrixU().col(2);\n    Eigen::MatrixXd T2 = -svd.matrixU().col(2);\n\n    // compose four possible RT\n    std::vector<Eigen::MatrixXd> RT;\n    // R1 and T1\n    Eigen::MatrixXd R1T1(3,4);\n    R1T1.block<3,3>(0,0) = R1;\n    R1T1.block<3,1>(0,3) = T1;\n    RT.push_back(R1T1);\n    // R1 and T2\n    Eigen::MatrixXd R1T2(3,4);\n    R1T2.block<3,3>(0,0) = R1;\n    R1T2.block<3,1>(0,3) = T2;\n    RT.push_back(R1T2);\n    // R2 and T1\n    Eigen::MatrixXd R2T1(3,4);\n    R2T1.block<3,3>(0,0) = R2;\n    R2T1.block<3,1>(0,3) = T1;\n    RT.push_back(R2T1);\n    // R2 and T2\n    Eigen::MatrixXd R2T2(3,4);\n    R2T2.block<3,3>(0,0) = R2;\n    R2T2.block<3,1>(0,3) = T2;\n    RT.push_back(R2T2);\n\n    // return\n    return RT;\n}\n\n/**\n * Linear estimate of the 3d point\n */\ntapl::Point3d tapl::cve::StructureFromMotion::linearEstimate3dPt( \n                    const std::vector<tapl::Point2d> &point2d,                                         \n                    const std::vector<Eigen::MatrixXd> &projectionMatrices ) {\n    // We can re-write [p x MP = 0] in the form [AP = 0] and solve for P \n    // by decomposing A using SVD\n    // let's formulate the A matrix\n    Eigen::MatrixXd A(point2d.size()*2, 4);\n    for (auto i=0; i<point2d.size(); ++i) {\n        A.row(i*2) << (point2d.at(i).x * projectionMatrices.at(i).row(2)) - \n                                    projectionMatrices.at(i).row(0);\n        A.row((i*2)+1) << (point2d.at(i).y * projectionMatrices.at(i).row(2)) - \n                                    projectionMatrices.at(i).row(1);\n    }\n    // SVD decomposition\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    // P can be obtained as the last column of v or last row of v_transpose\n    Eigen::MatrixXd pt3d_homogeneous = svd.matrixV().col(3);\n    // homogeneous to cartesian coordinate conversion\n    tapl::Point3d pt3d( pt3d_homogeneous(0,0) / pt3d_homogeneous(3,0), \n                        pt3d_homogeneous(1,0) / pt3d_homogeneous(3,0), \n                        pt3d_homogeneous(2,0) / pt3d_homogeneous(3,0) );\n    return pt3d;\n}\n\n/**\n * Non-linear estimate of the 3d point\n */\ntapl::Point3d tapl::cve::StructureFromMotion::nonLinearEstimate3dPt( \n                    const std::vector<tapl::Point2d> &point2d,                                         \n                    const std::vector<Eigen::MatrixXd> &projectionMatrices,\n                    std::pair<std::vector<float>,std::vector<float>> &reprojectionErrors,\n                    const uint16_t nIterations,\n                    const float reprErrorThresh ) {\n    // compute linear estimate of the 3d point\n    tapl::Point3d pt3d_initial = linearEstimate3dPt(point2d, projectionMatrices);\n    // perform non-linear least squares optimization\n    tapl::Point3d pt3d_optimize;\n    reprojectionErrors = \\\n        gnOptim.optimize(pt3d_initial, point2d, projectionMatrices, nIterations, reprErrorThresh, pt3d_optimize);\n    return pt3d_optimize;\n}\n\n/**\n * Estimate R, T, and triengulated points\n */\nstd::pair<Eigen::MatrixXd, std::vector<tapl::Point3d>> \n    tapl::cve::StructureFromMotion::computeSFM( \n                    const Eigen::MatrixXd &E, \n                    const std::vector<std::vector<tapl::Point2d>> &points2d, \n                    const Eigen::MatrixXd &projectionMat1,\n                    const float &maxReprojectionErr ) {\n    // compute four possible RT\n    std::vector<Eigen::MatrixXd> RT = computeInitialRTfromE(E);\n    // projection matrices\n    std::vector<Eigen::MatrixXd> projectionMatrices(2);\n    projectionMatrices.at(0) = projectionMat1;\n    // set of triangulated 3d points\n    std::vector<std::vector<tapl::Point3d>> pointsTriangulatedRef(4, std::vector<tapl::Point3d>(points2d.size()));\n    std::vector<std::vector<tapl::Point3d>> pointsTriangulated(4, std::vector<tapl::Point3d>(points2d.size()));\n    // reprojection errors\n    std::vector<std::vector<std::pair<std::vector<float>,std::vector<float>>>> \n        reprojectionErrors(4, std::vector<std::pair<std::vector<float>,std::vector<float>>>(points2d.size()));\n    // iterate over 4 possible R & T\n    for (auto it1=RT.begin(); it1!= RT.end(); ++it1) {\n        auto rtIdx = std::distance(RT.begin(), it1);\n        // build projection matrix\n        Eigen::MatrixXd projectionMat2 = projectionMat1 * (*it1);\n        // TODO: Update the implementation so that we have 1 projection matrix per camera\n        projectionMatrices.at(1) = projectionMat2;\n        // go through each point and triangulate it through multiple-views\n        for (auto it2=points2d.begin(); it2!=points2d.end(); ++it2) {\n            auto ptIdx = std::distance(points2d.begin(), it2);\n            // triangulate 3d point\n            std::pair<std::vector<float>,std::vector<float>> reprojectionError;\n            auto pt3d = this->nonLinearEstimate3dPt(*it2, projectionMatrices, reprojectionError);\n            reprojectionErrors[rtIdx][ptIdx] = reprojectionError;\n            pointsTriangulatedRef[rtIdx][ptIdx] = pt3d;\n\n            // convert to homogeneous coordinate system\n            Eigen::MatrixXd point3dHomogeneous(4,1);\n            point3dHomogeneous << pt3d.x, pt3d.y, pt3d.z, 1.0;\n            auto ptsTransformed = (*it1) * point3dHomogeneous;\n            pointsTriangulated[rtIdx][ptIdx] = *(new tapl::Point3d(ptsTransformed(0), ptsTransformed(1), ptsTransformed(2)));\n        }\n    }\n\n    // for each RT, count number of points that fall in front of all cameras.\n    // the one with maximum number of points will correspond to the correct RT\n    size_t correctIdx = 0;\n    uint16_t maxCount = 0;\n    for (auto i=0; i<RT.size(); ++i) {\n        uint16_t count = 0;\n        for (auto j=0; j<points2d.size(); ++j) {\n            if ((pointsTriangulatedRef[i][j].z > 0.0) && \n                (pointsTriangulated[i][j].z > 0.0)) {\n                   count ++;\n               }\n        }\n        if (count > maxCount) {\n            maxCount = count;\n            correctIdx = i;\n        }\n    }\n\n    Eigen::MatrixXd correctRT = RT[correctIdx];\n    std::vector<tapl::Point3d> correctTriangulatedPtsRef = pointsTriangulatedRef[correctIdx];\n    std::vector<tapl::Point3d> correctTriangulatedPts = pointsTriangulated[correctIdx];\n\n    // use PnP to get refined pose\n    // get pose using ransac\n    cv::Mat rvec = cv::Mat::zeros(3, 1, CV_64FC1);\n    cv::Mat tvec = cv::Mat::zeros(3, 1, CV_64FC1);    \n    const int iterationsCount = 500;       // number of Ransac iterations. default 100\n    const float reprojectionError = 1.0;    // maximum allowed distance to consider it an inlier. default 8.0\n    const float confidence = 0.99;          // RANSAC successful confidence. default 0.99\n    const bool useExtrinsicGuess = true;   // default false\n    const int flags = cv::SOLVEPNP_ITERATIVE;\n    cv::Mat inliers;\n    std::vector<cv::Point2f> kpts2d_;\n    std::vector<cv::Point3f> kpts3d_;\n    std::vector<uint16_t> idxRemove;\n    for (auto i=0; i<points2d.size(); ++i) {\n        // filter out the points outside of region-of-interest and the points with high reprojection error\n        if ((correctTriangulatedPts[i].z > 0.0) && (correctTriangulatedPtsRef[i].z > 0.0) &&\n            (correctTriangulatedPtsRef[i].z > this->minXYZ.at(2)) && (correctTriangulatedPtsRef[i].z < this->maxXYZ.at(2)) &&\n            (fabs(correctTriangulatedPtsRef[i].x) > this->minXYZ.at(0)) && (fabs(correctTriangulatedPtsRef[i].x) < this->maxXYZ.at(0)) &&\n            (fabs(correctTriangulatedPtsRef[i].y) > this->minXYZ.at(1)) && (fabs(correctTriangulatedPtsRef[i].y) < this->maxXYZ.at(1)) &&\n            reprojectionErrors[correctIdx][i].second.at(0) < maxReprojectionErr ) { // post-optimization reprojection error in the first camera frame\n            \n            // compute epipolar lines\n            Eigen::MatrixXf pt2(3,1);\n            pt2 << points2d[i][1].x, points2d[i][1].y, 1.0;\n            Eigen::MatrixXf epipolarLine1 = (E.transpose().cast <float> ()) * pt2.cast <float> ();\n            epipolarLine1 = epipolarLine1 / epipolarLine1(2,0); // normalize\n            // compute distance between epipolar line to the point in the other image\n            auto dist2ep = fabs(static_cast<float>(epipolarLine1(0,0)) * points2d[i][0].x + \n                                static_cast<float>(epipolarLine1(1,0)) * points2d[i][0].y + \n                                static_cast<float>(epipolarLine1(2,0))) / \n                            sqrt(pow(static_cast<float>(epipolarLine1(0,0)), 2) + \n                                 pow(static_cast<float>(epipolarLine1(1,0)), 2));\n            // if (dist2ep < 50.0) { \n            // points in the camera plane for which the pose needs to be computed\n            kpts2d_.push_back(cv::Point2f(points2d[i][1].x, points2d[i][1].y));\n            // 3d points in the coordinate of reference camera frame\n            kpts3d_.push_back(cv::Point3f(correctTriangulatedPtsRef[i].x, correctTriangulatedPtsRef[i].y, correctTriangulatedPtsRef[i].z));\n            // }\n            // else idxRemove.push_back(i);\n        }\n        else idxRemove.push_back(i);\n    }\n    // remove outliers\n    for (auto it_idx=idxRemove.end()-1; it_idx!=idxRemove.begin()-1; --it_idx) {\n        correctTriangulatedPtsRef.erase(correctTriangulatedPtsRef.begin()+(*it_idx));\n    } \n    if(kpts3d_.size() >= 6) {\n        cv::solvePnPRansac(kpts3d_, kpts2d_, this->K, this->dist_coeff, rvec, tvec,\n                            useExtrinsicGuess, iterationsCount, reprojectionError, confidence,\n                            inliers, flags );\n        float inliers_ratio = static_cast<float>(inliers.size().height) / static_cast<float>(kpts3d_.size());\n        // TLOG_DEBUG << \"Inliers ratio [\" << kpts3d_.size() << \"/\" << inliers.size().height << \"] = [\" << inliers_ratio << \"]\";\n\n        // get global pose in world reference frame\n        // check for NaNs\n        rvec.convertTo(rvec, CV_32F);\n        tvec.convertTo(tvec, CV_32F);\n        cv::patchNaNs(rvec, 0.0); // replace NaN with 0.0\n        cv::patchNaNs(tvec, 0.0); // replace NaN with 0.0\n        // rotation matrix\n        cv::Mat R;\n        cv::Rodrigues(rvec, R);\n        // translation matrix\n        cv::Mat t = cv::Mat::eye(4,4, CV_32FC1);\n        tvec.copyTo(t(cv::Rect(3,0,1,3)));\n        // build an RT matrix\n        Eigen::MatrixXd R_eigen(3,3);\n        cv2eigen(R, R_eigen);\n        Eigen::MatrixXd RT_pnp(3,4);\n        RT_pnp.block<3,3>(0,0) << R_eigen;\n        RT_pnp.block<3,1>(0,3) << tvec.at<float>(0,0), tvec.at<float>(0,1), tvec.at<float>(0,2);\n\n        return std::pair<Eigen::MatrixXd, std::vector<tapl::Point3d>>(RT_pnp, correctTriangulatedPtsRef);\n    }\n    else {\n        TLOG_WARN << \"PnP failed\";\n        return std::pair<Eigen::MatrixXd, std::vector<tapl::Point3d>>(correctRT, correctTriangulatedPtsRef);\n    }\n}\n\n/**\n * Structure-from-Motion constructor\n */\ntapl::cve::StructureFromMotion::StructureFromMotion( \n                                     const std::vector<cv::Mat> &images, \n                                     const cv::Mat &K,\n                                     const std::vector<float> &minXYZ,\n                                     const std::vector<float> &maxXYZ,\n                                     const bool verbose) {\n    // copy inputs to private variable\n    this->images = images;\n    this->K = K;\n    this->minXYZ = minXYZ;\n    this->maxXYZ = maxXYZ;\n    this->verbose = verbose;\n    // make bundles of 'm' images\n}\n\n/**\n * Structure-from-Motion implementation\n */\ntapl::ResultCode tapl::cve::StructureFromMotion::process(\n                                std::vector<tapl::Point3dColor> &points,\n                                std::vector<tapl::Pose6dof> &poses,\n                                std::vector<tapl::CameraPairs> &framePairs) {\n\n    // global pose\n    Eigen::Matrix4f globalPose = Eigen::Matrix4f::Identity();\n    // Go through each camera frame\n    for (auto it=this->images.begin()+1; it!=this->images.end(); ++it) {\n        if (this->verbose) TLOG_INFO << \"processing frames [\" << \n                                        std::distance(images.begin(), it) <<\n                                        \"] and [\" << \n                                        std::distance(images.begin(), it+1) << \"]\";\n\n        tapl::CameraPairs camPairs(*(it-1), *it, this->K);\n\n        // compute fundamental matrix\n        if (tapl::cve::computeFundamentalMatrix(camPairs) != tapl::SUCCESS) {\n            TLOG_ERROR << \"could not compute fundamental matrix\";\n            return tapl::FAILURE;\n        }\n\n        // retrieve fundamental matrix\n        cv::Mat F;\n        if (camPairs.getFundamentalMatrix(F) !=  tapl::SUCCESS) {\n            TLOG_ERROR << \"could not retrieve fundamental matrix\";\n            return tapl::FAILURE;\n        }\n\n        // compute essential matrix\n        cv::Mat E = this->K.t() * F * this->K;\n\n        // get keypoints\n        std::vector<cv::KeyPoint> kpts1;\n        if (camPairs.first->getKeypoints(kpts1) !=  tapl::SUCCESS) {\n            TLOG_ERROR << \"could not retrieve keypoints\";\n            return tapl::FAILURE;\n        }\n        std::vector<cv::KeyPoint> kpts2;\n        if (camPairs.second->getKeypoints(kpts2) !=  tapl::SUCCESS) {\n            TLOG_ERROR << \"could not retrieve keypoints\";\n            return tapl::FAILURE;\n        }\n\n        // get keypoints matches\n        std::vector<cv::DMatch> kptMatches;\n        if (camPairs.getKptsMatches(kptMatches) !=  tapl::SUCCESS) {\n            TLOG_ERROR << \"could not retrieve keypoints matches\";\n            return tapl::FAILURE;\n        }\n\n        // build vector of 'n' points in 'm' camera frames (n x m - Point2d)\n        std::vector<std::vector<tapl::Point2d>> kptSet;\n        std::vector<tapl::Point2d> trackedKpts;\n        for (auto it_match=kptMatches.begin(); it_match!=kptMatches.end(); ++it_match) {\n            if (it_match->distance < 100.0) {\n                tapl::Point2d pt1 = tapl::Point2d( kpts1.at((*it_match).queryIdx).pt.x, \n                                                   kpts1.at((*it_match).queryIdx).pt.y );\n                tapl::Point2d pt2 = tapl::Point2d( kpts2.at((*it_match).trainIdx).pt.x, \n                                                   kpts2.at((*it_match).trainIdx).pt.y );\n                trackedKpts.push_back(pt1);\n                // TODO: compute corresponding lines, find and reject outliers\n\n                // this point in all cameras\n                std::vector<tapl::Point2d> ptCameras = {pt1, pt2};\n                kptSet.push_back(ptCameras);\n            }\n        }\n\n        // draw the matches \n        cv::Mat matchImg;\n        cv::drawMatches(*(it-1), kpts1, *(it), kpts2,\n                        kptMatches, matchImg,\n                        cv::Scalar::all(-1), cv::Scalar::all(-1),\n                        std::vector<char>(), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);\n\n        // convert E to eigen format\n        Eigen::MatrixXd eigenE(3,3); \n        cv2eigen(E, eigenE);\n        // convert K to eigen format\n        Eigen::MatrixXd eigenK(3,3); \n        Eigen::MatrixXd projectionMat1(3,4); \n        cv2eigen(this->K, eigenK);\n        projectionMat1.block<3,3>(0,0) = eigenK;\n        projectionMat1(3,3) = 1.0;\n        auto sfm = computeSFM(eigenE, kptSet, projectionMat1);\n        Eigen::MatrixXd RT = sfm.first;\n        std::vector<tapl::Point3d> triangulatedPts = sfm.second;\n        // Get point color\n        std::vector<tapl::Point3dColor> triangulatedPtsColor;\n        cv::Mat imgProj = cv::Mat::zeros((it-1)->rows, (it-1)->cols, CV_8UC3);\n        for ( auto &pt3d : triangulatedPts) {\n            Eigen::MatrixXd eigenPt3d(3,1);\n            eigenPt3d << pt3d.x, pt3d.y, pt3d.z;\n            auto eigenPt2dHomogeneous = eigenK * eigenPt3d;\n            float pxX, pxY;\n            pxX = eigenPt2dHomogeneous(0,0) / eigenPt2dHomogeneous(2,0);\n            pxY = eigenPt2dHomogeneous(1,0) / eigenPt2dHomogeneous(2,0);\n            // check if the coordinate is within limits\n            cv::Vec3b rgb;\n            if ((pxX >= 0) && (pxX < (it-1)->cols) &&\n                (pxY >= 0) && (pxY < (it-1)->rows)) {\n                rgb = (it-1)->at<cv::Vec3b>(static_cast<int>(pxY),static_cast<int>(pxX));\n                imgProj.at<cv::Vec3b>(static_cast<int>(pxY),static_cast<int>(pxX)) = rgb;\n            }\n            else rgb = cv::Vec3b(0, 0, 0);\n            tapl::Point3dColor pt3dColor( pt3d.x, pt3d.y, pt3d.z, static_cast<uint8_t>(rgb[0]), \n                                          static_cast<uint8_t>(rgb[1]), static_cast<uint8_t>(rgb[2]));\n            triangulatedPtsColor.push_back(pt3dColor);\n        }\n\n        // plot\n        Eigen::Matrix4f P = Eigen::Matrix4f::Identity();\n        P.block<3,4>(0,0) = RT.cast<float>();\n        Eigen::Matrix4f Pi = Eigen::Matrix4f::Identity();\n        Pi.block<3,3>(0,0) = P.block<3,3>(0,0).transpose();\n        Pi.block<3,1>(0,3) = -P.block<3,3>(0,0).transpose() * P.block<3,1>(0,3);\n        globalPose = globalPose * Pi;\n\n        // compute pose \n        cv::Mat cvPose;\n        eigen2cv(globalPose, cvPose);\n        tapl::Pose6dof pose(cvPose);\n        // add to camera \n        camPairs.pushPose(pose);\n        camPairs.pushTrackedKpts(trackedKpts);\n        camPairs.pushTriangulatedPts(triangulatedPtsColor);\n        // push to the output vector\n        poses.push_back(pose);\n        for (auto &point : triangulatedPtsColor) points.push_back(point);\n        // push camera pairs\n        framePairs.push_back(camPairs);\n    }\n\n    // return success\n    return tapl::SUCCESS;\n}", "meta": {"hexsha": "3267d5aec6b7b49d7467447425bbf5f2caf9737e", "size": 19022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tapl/cve/sfm.cpp", "max_stars_repo_name": "towardsautonomy/TAPL", "max_stars_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T12:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T12:53:17.000Z", "max_issues_repo_path": "tapl/cve/sfm.cpp", "max_issues_repo_name": "towardsautonomy/TAPL", "max_issues_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tapl/cve/sfm.cpp", "max_forks_repo_name": "towardsautonomy/TAPL", "max_forks_repo_head_hexsha": "4d065b2250483bf2ea118bafa312ca893a25ca87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5480093677, "max_line_length": 149, "alphanum_fraction": 0.5799600463, "num_tokens": 5499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.6619228691808012, "lm_q1q2_score": 0.6102411418277528}}
{"text": "#define BOOST_TEST_MODULE \"Test Chebyshev Normalization class\"\n\n#include <boost/test/unit_test.hpp>\n\n#include \"distance/Chebyshev.hpp\"\n\nusing namespace genex;\n\n#define TOLERANCE 1e-9\n\nstruct MockData\n{\n  data_t dat_1[5] = {1, 2, 3, 4, 5};\n  data_t dat_2[5] = {11, 2, 3, 4, 5};\n};\n\nBOOST_AUTO_TEST_CASE( time_series_length, *boost::unit_test::tolerance(TOLERANCE)  )\n{\n  MockData data;\n  TimeSeries ts_1(data.dat_1, 0, 0, 5);\n  TimeSeries ts_2(data.dat_2, 0, 0, 5);\n  Chebyshev dist;\n\n  data_t total = dist.init();\n\n  for (int i = 0; i < ts_1.getLength(); i++) {\n    total = dist.reduce(total, total, ts_1[i], ts_2[i]);\n  }\n\n  BOOST_TEST( dist.norm(total, ts_1, ts_2), 10.0 );\n\n  dist.clean(total);\n}\n", "meta": {"hexsha": "7109eadbfaa7504783e3e538d57438a52e60af69", "size": 700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/distance/ChebyshevNormTest.cpp", "max_stars_repo_name": "mihinsumaria/genex", "max_stars_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-28T07:36:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T07:49:24.000Z", "max_issues_repo_path": "test/distance/ChebyshevNormTest.cpp", "max_issues_repo_name": "mihinsumaria/genex", "max_issues_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/distance/ChebyshevNormTest.cpp", "max_forks_repo_name": "mihinsumaria/genex", "max_forks_repo_head_hexsha": "34786b0cf5d573348b82e5d164dbc05e0411d6a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-01T20:25:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T20:25:42.000Z", "avg_line_length": 20.5882352941, "max_line_length": 84, "alphanum_fraction": 0.6671428571, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6102143944194344}}
{"text": "/*\nLICENSE: see isogeometric_application/LICENSE.txt\n*/\n\n//\n//   Project Name:        Kratos\n//   Last modified by:    $Author: hbui $\n//   Date:                $Date: Nov 11, 2017 $\n//   Revision:            $Revision: 1.1 $\n//\n//\n\n\n// System includes\n#include <string>\n\n// External includes\n#include <boost/foreach.hpp>\n#include <boost/python.hpp>\n#include <boost/python/stl_iterator.hpp>\n#include <boost/python/operators.hpp>\n\n// Project includes\n#include \"includes/define.h\"\n#include \"containers/array_1d.h\"\n#include \"includes/ublas_interface.h\"\n#include \"custom_utilities/trans/transformation.h\"\n#include \"custom_utilities/trans/translation.h\"\n#include \"custom_utilities/trans/rotation.h\"\n#include \"custom_utilities/trans/mirror.h\"\n#include \"custom_utilities/trans/transformation_utility.h\"\n#include \"custom_python/add_transformation_to_python.h\"\n\n\nnamespace Kratos\n{\n\nnamespace Python\n{\n\nusing namespace boost::python;\n\n//////////////////////////////////////////////////\n\ntemplate<typename TDataType>\nTransformation<TDataType> TransformationUtility_CreateAlignTransformation(TransformationUtility<TDataType>& rDummy,\n    const typename Transformation<TDataType>::VectorType& a, const typename Transformation<TDataType>::VectorType& b)\n{\n    Transformation<TDataType> T;\n    T = rDummy.CreateAlignTransformation(a, b);\n    return T;\n}\n\ntemplate<typename TDataType>\nvoid Transformation_SetValue(Transformation<TDataType>& rDummy, const int& i, const int& j, const TDataType& v)\n{\n    rDummy(i, j) = v;\n}\n\ntemplate<typename TDataType>\nTDataType Transformation_GetValue(Transformation<TDataType>& rDummy, const int& i, const int& j)\n{\n    return rDummy(i, j);\n}\n\ntemplate<typename TDataType, typename TVectorType>\nTVectorType Transformation_Apply(Transformation<TDataType>& rDummy, const TVectorType& v)\n{\n    TVectorType newv = v;\n    rDummy.template ApplyTransformation<TVectorType>(newv);\n    return newv;\n}\n\ntemplate<typename TDataType>\nboost::python::list Transformation_Apply2(Transformation<TDataType>& rDummy, boost::python::list v)\n{\n    std::vector<TDataType> newv;\n    typedef boost::python::stl_input_iterator<TDataType> iterator_value_type;\n    BOOST_FOREACH(const typename iterator_value_type::value_type& d, std::make_pair(iterator_value_type(v), iterator_value_type() ) )\n        newv.push_back(d);\n\n    rDummy.template ApplyTransformation<std::vector<TDataType> >(newv);\n\n    boost::python::list res;\n    for (std::size_t i = 0; i < newv.size(); ++i)\n        res.append(newv[i]);\n\n    return res;\n}\n\ntemplate<typename TDataType>\narray_1d<TDataType, 3> Transformation_P(Transformation<TDataType>& rDummy)\n{\n    return rDummy.P();\n}\n\ntemplate<typename TDataType>\narray_1d<TDataType, 3> Transformation_V1(Transformation<TDataType>& rDummy)\n{\n    return rDummy.V1();\n}\n\ntemplate<typename TDataType>\narray_1d<TDataType, 3> Transformation_V2(Transformation<TDataType>& rDummy)\n{\n    return rDummy.V2();\n}\n\ntemplate<typename TDataType>\narray_1d<TDataType, 3> Transformation_V3(Transformation<TDataType>& rDummy)\n{\n    return rDummy.V3();\n}\n\n//////////////////////////////////////////////////\n\nvoid IsogeometricApplication_AddTransformationToPython()\n{\n    typedef Transformation<double>::VectorType VectorType;\n\n    class_<Transformation<double>, Transformation<double>::Pointer>\n    (\"Transformation\", init<>())\n    .def(init<const VectorType&, const VectorType&, const VectorType&>())\n    .def(init<const array_1d<double, 3>&, const array_1d<double, 3>&, const array_1d<double, 3>&>())\n    .def(init<const VectorType&, const VectorType&, const VectorType&, const VectorType&>())\n    .def(init<const array_1d<double, 3>&, const array_1d<double, 3>&, const array_1d<double, 3>&, const array_1d<double, 3>&>())\n    .def(\"AppendTransformation\", &Transformation<double>::AppendTransformation)\n    .def(\"PrependTransformation\", &Transformation<double>::PrependTransformation)\n    .def(\"Inverse\", &Transformation<double>::Inverse)\n    // .def(boost::python::operators<boost::python::op_mul>());\n    .def(\"P\", &Transformation_P<double>)\n    .def(\"V1\", &Transformation_V1<double>)\n    .def(\"V2\", &Transformation_V2<double>)\n    .def(\"V3\", &Transformation_V3<double>)\n    .def(\"SetValue\", &Transformation_SetValue<double>)\n    .def(\"GetValue\", &Transformation_GetValue<double>)\n    .def(\"Apply\", &Transformation_Apply<double, Vector>)\n    .def(\"Apply\", &Transformation_Apply<double, array_1d<double, 3> >)\n    .def(\"Apply\", &Transformation_Apply2<double>)\n    .def(self_ns::str(self))\n    ;\n\n    class_<Translation<double>, Translation<double>::Pointer, bases<Transformation<double> >, boost::noncopyable>\n    (\"Translation\", init<const double&, const double&, const double&>())\n    .def(self_ns::str(self))\n    ;\n\n    class_<Rotation<0, double>, Rotation<0, double>::Pointer, bases<Transformation<double> >, boost::noncopyable>\n    (\"RotationX\", init<const double&>())\n    .def(self_ns::str(self))\n    ;\n\n    class_<Rotation<1, double>, Rotation<1, double>::Pointer, bases<Transformation<double> >, boost::noncopyable>\n    (\"RotationY\", init<const double&>())\n    .def(self_ns::str(self))\n    ;\n\n    class_<Rotation<2, double>, Rotation<2, double>::Pointer, bases<Transformation<double> >, boost::noncopyable>\n    (\"RotationZ\", init<const double&>())\n    .def(self_ns::str(self))\n    ;\n\n    class_<Mirror<0, double>, Mirror<0, double>::Pointer, bases<Transformation<double> >, boost::noncopyable>\n    (\"MirrorX\", init<>())\n    .def(self_ns::str(self))\n    ;\n\n    class_<Mirror<1, double>, Mirror<1, double>::Pointer, bases<Transformation<double> >, boost::noncopyable>\n    (\"MirrorY\", init<>())\n    .def(self_ns::str(self))\n    ;\n\n    class_<Mirror<2, double>, Mirror<2, double>::Pointer, bases<Transformation<double> >, boost::noncopyable>\n    (\"MirrorZ\", init<>())\n    .def(self_ns::str(self))\n    ;\n\n    class_<TransformationUtility<double>, TransformationUtility<double>::Pointer, boost::noncopyable>\n    (\"TransformationUtility\", init<>())\n    .def(\"CreateAlignTransformation\", &TransformationUtility_CreateAlignTransformation<double>)\n    ;\n\n}\n\n}  // namespace Python.\n\n} // Namespace Kratos\n\n", "meta": {"hexsha": "9f0910a2c0eca93b8951887a4f1b9795811bbfa3", "size": 6104, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "custom_python/add_transformation_to_python.cpp", "max_stars_repo_name": "ForeverDavid/isogeometric_application", "max_stars_repo_head_hexsha": "4bc23241010a82aa38e845e0d3403e1cab28bc14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "custom_python/add_transformation_to_python.cpp", "max_issues_repo_name": "ForeverDavid/isogeometric_application", "max_issues_repo_head_hexsha": "4bc23241010a82aa38e845e0d3403e1cab28bc14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "custom_python/add_transformation_to_python.cpp", "max_forks_repo_name": "ForeverDavid/isogeometric_application", "max_forks_repo_head_hexsha": "4bc23241010a82aa38e845e0d3403e1cab28bc14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-25T08:31:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T08:31:06.000Z", "avg_line_length": 32.2962962963, "max_line_length": 133, "alphanum_fraction": 0.7033093054, "num_tokens": 1478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.6102143894159786}}
{"text": "/**\n * \\file dcs/math/stats/distribution/pareto.hpp\n *\n * \\brief The Pareto probability distribution.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_STATS_DISTRIBUTION_PARETO_HPP\n#define DCS_MATH_STATS_DISTRIBUTION_PARETO_HPP\n\n\n#include <dcs/detail/config/boost.hpp>\n\n#if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(103500) // 1.35\n# \terror \"Required Boost library version >= 1.35\"\n#endif\n\n#include <boost/math/distributions/pareto.hpp>\n#include <cmath>\n#include <cstddef>\n#include <dcs/math/policies/policy.hpp>\n#include <dcs/math/random/uniform_01_adaptor.hpp>\n#include <iostream>\n#include <vector>\n\n\nnamespace dcs { namespace math { namespace stats {\n\n/**\n * \\brief The Pareto distribution with shape parameter \\f$\\alpha\\f$ and scale\n *  parameter \\f$\\beta\\f$.\n *\n * \\tparam RealT The type used for real numbers.\n * \\tparam PolicyT The policy type.\n *\n * The probability density function (pdf):\n * \\f[\n *   \\Pr(x|\\lambda) = \\frac{\\alpha\\,\\beta^\\alpha}{x^{\\alpha+1}}, \\quad\n *                    \\text{ for }x>\\beta\n * \\f]\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate < typename RealT=double, typename PolicyT=::dcs::math::policies::policy<> >\nclass pareto_distribution\n{\n\tpublic: typedef RealT support_type;\n\tpublic: typedef RealT value_type;\n\tpublic: typedef PolicyT policy_type;\n\n\tpublic: explicit pareto_distribution(support_type shape=1, support_type scale=1)\n\t\t: dist_(shape, scale)\n\t{\n\t\t// empty\n\t}\n\n\n\t// compiler-generated copy ctor and assignment operator are fine\n\n\n\t/**\n\t * \\brief Generate a random number distributed according to this\n\t * pareto distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\return A random number distributed according to this pareto\n\t * distribution.\n\t *\n\t * A \\c pareto random number distribution produces random numbers\n\t * \\f$x > 0\\f$ distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|\\alpha) = \\frac{\\alpha\\,k^\\alpha}{x^{\\alpha+1}}, \\quad\n\t *                   \\text{ for }x>k\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\tsupport_type rand(UniformRandomGeneratorT& rng) const\n\t{\n\t\t::dcs::math::random::uniform_01_adaptor<UniformRandomGeneratorT&, support_type> eng(rng);\n\n\t\t// Use the inversion method:\n    \t//    x=\\frac{k}{(1-p)^{1/\\alpha}}\n    \t// => x=k(1-p)^{-1/\\alpha}\n    \t// => x=ku^{-1/\\alpha}, where u is a uniform random number in [0,1)\n\n#if DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(104000)\n\t\treturn dist_.scale()*::std::pow(value_type(1)-eng(), -value_type(1)/dist_.shape());\n//\t\treturn dist_.scale()*::std::pow(eng(), -value_type(1)/dist_.shape());\n#else\n\t\treturn dist_.location()*::std::pow(value_type(1)-eng(), -value_type(1)/dist_.shape());\n//\t\treturn dist_.location()*::std::pow(eng(), -value_type(1)/dist_.shape());\n#endif // DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION\n\t}\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * pareto distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A vector of random numbers distributed according to this\n\t * pareto distribution.\n\t *\n\t * A \\c pareto random number distribution produces random numbers\n\t * \\f$x > 0\\f$ distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|\\lambda) = \\frac{\\alpha\\,\\beta^\\alpha}{x^{\\alpha+1}}, \\quad\n\t *                    \\text{ for }x>\\beta\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\t::std::vector<support_type> rand(UniformRandomGeneratorT& rng, ::std::size_t n)\n\t{\n\t\t::std::vector<support_type> rnds(n);\n\n        for ( ; n > 0; --n)\n\t\t{\n\t\t\trnds.push_back(rand());\n\t\t}\n\n\t\treturn rnds;\n\t}\n\n\n\tpublic: support_type shape() const\n\t{\n\t\treturn dist_.shape();\n\t}\n\n\n\tpublic: support_type scale() const\n\t{\n#if DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(104000)\n\t\treturn dist_.scale();\n#else\n\t\treturn dist_.location();\n#endif // DCS_DETAIL_CONFIG_BOOST_VERSION\n\t}\n\n\n\tpublic: support_type quantile(value_type p) const\n\t{\n\t\treturn ::boost::math::quantile(dist_, p);\n\t}\n\n\n\tpublic: value_type mean() const\n\t{\n#if DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(104000)\n\t\treturn dist_.scale()*dist_.shape()/(dist_.shape()-1);\n#else\n\t\treturn dist_.location()*dist_.shape()/(dist_.shape()-1);\n#endif // DCS_DETAIL_CONFIG_BOOST_VERSION\n\t}\n\n\n\tpublic: value_type variance() const\n\t{\n#if DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(104000)\n\t\treturn dist_.scale()*dist_.scale()*dist_.shape()/((dist_.shape()-1)*(dist_.shape()-2));\n#else\n\t\treturn dist_.location()*dist_.location()*dist_.shape()/((dist_.shape()-1)*(dist_.shape()-2));\n#endif // DCS_DETAIL_CONFIG_BOOST_VERSION\n\t}\n\n\n\tprivate: ::boost::math::pareto_distribution<value_type,policy_type> dist_;\n};\n\n\ntemplate <\n\ttypename CharT,\n\ttypename CharTraitsT,\n\ttypename RealT,\n\ttypename PolicyT\n>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, pareto_distribution<RealT,PolicyT> const& dist)\n{\n\treturn os << \"Pareto(\"\n\t\t\t  << \"shape=\" <<  dist.shape()\n\t\t\t  << \", scale=\" <<  dist.scale()\n\t\t\t  << \")\";\n}\n\n}}} // Namespace dcs::math::stats\n\n#endif // DCS_MATH_STATS_DISTRIBUTION_PARETO_HPP\n", "meta": {"hexsha": "4c8a79c8ffcc8c8052738849f6cc4a30c12debe9", "size": 5794, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/pareto.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/stats/distribution/pareto.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/stats/distribution/pareto.hpp", "max_forks_repo_name": "sguazt/dcsxx-commons", "max_forks_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1262135922, "max_line_length": 144, "alphanum_fraction": 0.6955471177, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256432832333, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6102143815359947}}
{"text": "#include <stan/math/prim/scal.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <gtest/gtest.h>\n#include <limits>\n#include <stdexcept>\n\nTEST(MathFunctions, erf) {\n  using stan::math::erf;\n  EXPECT_FLOAT_EQ(-0.3286267594591274, erf(-0.3));\n  EXPECT_FLOAT_EQ(0, erf(0));\n  EXPECT_FLOAT_EQ(0.9999939742388482, erf(3.2));\n}\n\nTEST(MathFunctions, erfOverflow) {\n  EXPECT_FLOAT_EQ(-1, erf(-100));\n  EXPECT_FLOAT_EQ(1, erf(100));\n}\n\nTEST(MathFunctions, erfNan) {\n  double nan = std::numeric_limits<double>::quiet_NaN();\n  EXPECT_PRED1(boost::math::isnan<double>,\n               stan::math::erf(nan));\n}\n", "meta": {"hexsha": "287ecf7e9164123ce66769843821ae28a415b619", "size": 614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/erf_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/erf_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/prim/scal/fun/erf_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5833333333, "max_line_length": 56, "alphanum_fraction": 0.7019543974, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6102143786594666}}
{"text": "/**\n * @file    LossFunction.cpp\n * @brief   Gaussian loss function with mahalanobis distance, and robust loss\n * @author  Jing Dong\n * @date    Oct 14, 2017\n */\n\n#include <minisam/core/LossFunction.h>\n\n#include <Eigen/Dense>\n\nnamespace minisam {\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> GaussianLoss::SqrtInformation(\n    const Eigen::MatrixXd& R) {\n  assert(R.rows() == R.cols() &&\n         \"[GaussianLoss::SqrtInformation] non-square sqrt-root matrix\");\n  return std::shared_ptr<LossFunction>(new GaussianLoss(R));\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> GaussianLoss::Information(\n    const Eigen::MatrixXd& I) {\n  assert(I.rows() == I.cols() &&\n         \"[GaussianLoss::Information] non-square information matrix\");\n  Eigen::LLT<Eigen::MatrixXd> llt(I.selfadjointView<Eigen::Upper>());\n  return std::shared_ptr<LossFunction>(new GaussianLoss(llt.matrixU()));\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> GaussianLoss::Covariance(\n    const Eigen::MatrixXd& Sigma) {\n  assert(Sigma.rows() == Sigma.cols() &&\n         \"[GaussianLoss::Covariance] non-square covariance matrix\");\n  return Information(Sigma.inverse());\n}\n\n/* ************************************************************************** */\nvoid GaussianLoss::print(std::ostream& out) const {\n  out << \"Gaussian loss function : R =\" << std::endl << sqrt_info_ << std::endl;\n}\n\n/* ************************************************************************** */\nvoid GaussianLoss::weightInPlace(Eigen::VectorXd& b) const {\n  assert(sqrt_info_.cols() == b.size() &&\n         \"[GaussianLoss::weightInPlace] error size wrong\");\n  b = sqrt_info_ * b;\n}\n\n/* ************************************************************************** */\nvoid GaussianLoss::weightInPlace(std::vector<Eigen::MatrixXd>& As,\n                                 Eigen::VectorXd& b) const {\n  assert(sqrt_info_.cols() == b.size() &&\n         \"[GaussianLoss::weightInPlace] error size wrong\");\n  b = sqrt_info_ * b;\n  for (auto& A : As) {\n    assert(sqrt_info_.cols() == A.rows() &&\n           \"[GaussianLoss::weightInPlace] jacobian size wrong\");\n    A = sqrt_info_ * A;\n  }\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> DiagonalLoss::Precisions(\n    const Eigen::VectorXd& I_diag) {\n  return std::shared_ptr<LossFunction>(new DiagonalLoss(I_diag.cwiseSqrt()));\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> DiagonalLoss::Sigmas(\n    const Eigen::VectorXd& S_diag) {\n  return std::shared_ptr<LossFunction>(new DiagonalLoss(S_diag.cwiseInverse()));\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> DiagonalLoss::Variances(\n    const Eigen::VectorXd& V_diag) {\n  return std::shared_ptr<LossFunction>(\n      new DiagonalLoss((V_diag.cwiseInverse()).cwiseSqrt()));\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> DiagonalLoss::Scales(const Eigen::VectorXd& s) {\n  return std::shared_ptr<LossFunction>(new DiagonalLoss(s));\n}\n\n/* ************************************************************************** */\nvoid DiagonalLoss::print(std::ostream& out) const {\n  out << \"Diagonal loss function : R_diag = [\" << sqrt_info_diag_.transpose()\n      << \"]'\" << std::endl;\n}\n\n/* ************************************************************************** */\nvoid DiagonalLoss::weightInPlace(Eigen::VectorXd& b) const {\n  assert(sqrt_info_diag_.size() == b.size() &&\n         \"[DiagonalLoss::weightInPlace] error size wrong\");\n  b = b.cwiseProduct(sqrt_info_diag_);\n}\n\n/* ************************************************************************** */\nvoid DiagonalLoss::weightInPlace(std::vector<Eigen::MatrixXd>& As,\n                                 Eigen::VectorXd& b) const {\n  assert(sqrt_info_diag_.size() == b.size() &&\n         \"[DiagonalLoss::weightInPlace] error size wrong\");\n  b = b.cwiseProduct(sqrt_info_diag_);\n  for (auto& A : As) {\n    assert(sqrt_info_diag_.size() == A.rows() &&\n           \"[DiagonalLoss::weightInPlace] jacobian size wrong\");\n    for (int i = 0; i < A.rows(); i++) {\n      A.row(i) *= sqrt_info_diag_(i);\n    }\n  }\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> ScaleLoss::Precision(double prec) {\n  return std::shared_ptr<LossFunction>(new ScaleLoss(std::sqrt(prec)));\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> ScaleLoss::Sigma(double sigma) {\n  return std::shared_ptr<LossFunction>(new ScaleLoss(1.0 / sigma));\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> ScaleLoss::Variance(double var) {\n  return std::shared_ptr<LossFunction>(new ScaleLoss(1.0 / std::sqrt(var)));\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> ScaleLoss::Scale(double s) {\n  return std::shared_ptr<LossFunction>(new ScaleLoss(s));\n}\n\n/* ************************************************************************** */\nvoid ScaleLoss::print(std::ostream& out) const {\n  out << \"Scale loss function : inv_sigma = \" << inv_sigma_ << std::endl;\n}\n\n/* ************************************************************************** */\nvoid ScaleLoss::weightInPlace(Eigen::VectorXd& b) const { b *= inv_sigma_; }\n\n/* ************************************************************************** */\nvoid ScaleLoss::weightInPlace(std::vector<Eigen::MatrixXd>& As,\n                              Eigen::VectorXd& b) const {\n  b *= inv_sigma_;\n  for (auto& A : As) {\n    A *= inv_sigma_;\n  }\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> CauchyLoss::Cauchy(double k) {\n  return std::shared_ptr<LossFunction>(new CauchyLoss(k));\n}\n\n/* ************************************************************************** */\nvoid CauchyLoss::print(std::ostream& out) const {\n  out << \"Cauchy loss function : k = \" << k_ << std::endl;\n}\n\n/* ************************************************************************** */\nvoid CauchyLoss::weightInPlace(Eigen::VectorXd& b) const {\n  double sqrtw = std::sqrt(weight(b.norm()));\n  b *= sqrtw;\n}\n\n/* ************************************************************************** */\nvoid CauchyLoss::weightInPlace(std::vector<Eigen::MatrixXd>& As,\n                               Eigen::VectorXd& b) const {\n  const double sqrtw = std::sqrt(weight(b.norm()));\n  b *= sqrtw;\n  for (auto& A : As) {\n    A *= sqrtw;\n  }\n}\n\n/* ************************************************************************** */\nstd::shared_ptr<LossFunction> HuberLoss::Huber(double k) {\n  return std::shared_ptr<LossFunction>(new HuberLoss(k));\n}\n\n/* ************************************************************************** */\nvoid HuberLoss::print(std::ostream& out) const {\n  out << \"Huber loss function : k = \" << k_ << std::endl;\n}\n\n/* ************************************************************************** */\nvoid HuberLoss::weightInPlace(Eigen::VectorXd& b) const {\n  double sqrtw = std::sqrt(weight(b.norm()));\n  b *= sqrtw;\n}\n\n/* ************************************************************************** */\nvoid HuberLoss::weightInPlace(std::vector<Eigen::MatrixXd>& As,\n                              Eigen::VectorXd& b) const {\n  const double sqrtw = std::sqrt(weight(b.norm()));\n  b *= sqrtw;\n  for (auto& A : As) {\n    A *= sqrtw;\n  }\n}\n\n/* ************************************************************************** */\nvoid ComposedLoss::print(std::ostream& out) const {\n  out << \"Composed loss function : \" << std::endl << \"Loss 1 : \";\n  l1_->print(out);\n  out << \"Loss 2 : \";\n  l2_->print(out);\n}\n\n/* ************************************************************************** */\nvoid ComposedLoss::weightInPlace(Eigen::VectorXd& b) const {\n  l1_->weightInPlace(b);\n  l2_->weightInPlace(b);\n}\n\n/* ************************************************************************** */\nvoid ComposedLoss::weightInPlace(std::vector<Eigen::MatrixXd>& As,\n                                 Eigen::VectorXd& b) const {\n  l1_->weightInPlace(As, b);\n  l2_->weightInPlace(As, b);\n}\n}  // namespace minisam\n", "meta": {"hexsha": "6ce5695acc15789ba5b4d3a6426bffbd6d4d741e", "size": 8525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "minisam/core/LossFunction.cpp", "max_stars_repo_name": "versatran01/minisam", "max_stars_repo_head_hexsha": "b3840d2629551fdfa287df8aac2e7956873d2b0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 338.0, "max_stars_repo_stars_event_min_datetime": "2019-09-03T10:44:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:12:08.000Z", "max_issues_repo_path": "minisam/core/LossFunction.cpp", "max_issues_repo_name": "bhsphd/minisam", "max_issues_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T09:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T06:04:02.000Z", "max_forks_repo_path": "minisam/core/LossFunction.cpp", "max_forks_repo_name": "bhsphd/minisam", "max_forks_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 87.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T05:17:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T09:47:23.000Z", "avg_line_length": 37.7212389381, "max_line_length": 80, "alphanum_fraction": 0.4624046921, "num_tokens": 1752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6100770360835497}}
{"text": "#ifndef YANNQ_HYPERCUBECONVLAYER_HH\n#define YANNQ_HYPERCUBECONVLAYER_HH\n\n#include <time.h>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <complex>\n#include <fstream>\n#include <memory>\n#include <random>\n#include <vector>\n\n#include \"AbstractLayer.hpp\"\n\n#include <Utilities/Utility.hpp>\n#include <Utilities/Exceptions.hpp>\n\nnamespace yannq {\n\ntemplate<typename T>\nclass Conv1D : public AbstractLayer<T> {\n\tstatic_assert(!AbstractLayer<T>::Matrix::IsRowMajor, \"Matrix must be column-major\");\n\npublic:\n\tusing Scalar = T;\n\tusing RealScalar = remove_complex_t<T>;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\nprivate:\n\tconst bool useBias_;  // boolean to turn or off bias\n\n\tconst uint32_t inChannels_;   // number of input channels\n\tconst uint32_t outChannels_;  // number of output channels\n\n\tconst uint32_t kernelSize_;\n\tconst uint32_t stride_;         // convolution stride\n\t\n\tconst uint32_t npar_;          // number of parameters in layer\n\n\tMatrix kernel_;  // Weight parameters, W((inChannels_ * kernelSize)x(outChannels))\n\tVector bias_;     // Bias parameters, b(outChannels)\n\n\tstatic uint32_t numParams(bool useBias, const uint32_t inChannels,\n\t\t\tconst uint32_t outChannels, const uint32_t kernelSize)\n\t{\n\t\tuint32_t np = inChannels * outChannels * kernelSize;\n\t\tif(useBias)\n\t\t\tnp += outChannels;\n\t\treturn np;\n\t}\n\npublic:\n\t/// Constructor\n\tConv1D(\tconst uint32_t inChannels, const uint32_t outChannels,\n\t\t\tconst uint32_t kernelSize, const uint32_t stride = 1,\n\t\t\tconst bool useBias = false)\n\t\t: useBias_(useBias), inChannels_(inChannels), outChannels_(outChannels),\n\t\tkernelSize_(kernelSize), stride_(stride),\n\t\tnpar_(numParams(useBias, inChannels, outChannels, kernelSize)),\n\t\tkernel_(inChannels*kernelSize, outChannels), bias_(outChannels)\n\t{\n\t}\n\n\tConv1D(const Conv1D& rhs) = default;\n\tConv1D(Conv1D&& rhs) = default;\n\n\tConv1D& operator=(const Conv1D& rhs) = default;\n\tConv1D& operator=(Conv1D&& rhs) = default;\n\n\tbool operator==(const Conv1D& rhs) const\n\t{\n\t\tif(useBias_ != rhs.useBias_)\n\t\t\treturn false;\n\n\t\tbool res = (inChannels_ == rhs.inChannels_) && \n\t\t\t\t(outChannels_ == rhs.outChannels_) &&\n\t\t\t\t(kernelSize_ == rhs.kernelSize_) &&\n\t\t\t\t(stride_ == rhs.stride_) &&\n\t\t\t\t(kernel_ == rhs.kernel_);\n\n\t\tif(!useBias_)\n\t\t\treturn res;\n\t\telse\n\t\t\treturn res && (bias_ == rhs.bias_);\n\t}\n\n\tbool operator!=(const Conv1D& rhs) const\n\t{\n\t\treturn !(*this == rhs);\n\t}\n\n\tstd::string name() const override { return \"Convolutional 1D Layer\"; }\n\n\ttemplate<class RandomEngine>\n\tvoid randomizeParams(RandomEngine&& re, RealScalar sigma)\n\t{\n\t\tsetParams(randomVector<T>(std::forward<RandomEngine>(re), sigma, npar_));\n\t}\n\n\tuint32_t paramDim() const override { return npar_; }\n\tuint32_t outputDim(uint32_t inputDim) const override {\n\t\treturn (inputDim / stride_ / inChannels_) * outChannels_; \n\t}\n\n\tVector getParams() const override \n\t{\n\t\tVector pars(npar_);\n\t\tpars.head(kernel_.size()) = Eigen::Map<const Vector>(kernel_.data(), kernel_.size());\n\t\tif(useBias_)\n\t\t{\n\t\t\tpars.tail(outChannels_) = bias_;\n\t\t}\n\t\treturn pars;\n\t}\n\n\tvoid setParams(VectorConstRef pars) override \n\t{\n\t\tassert(pars.size() == npar_);\n\t\tEigen::Map<Vector>(kernel_.data(), kernel_.size()) = pars.head(kernel_.size());\n\t\tif(useBias_)\n\t\t{\n\t\t\tbias_ = pars.tail(outChannels_);\n\t\t}\n\t}\n\n\tvoid updateParams(VectorConstRef ups) override\n\t{\n\t\tassert(ups.size() == npar_);\n\t\tEigen::Map<Vector>(kernel_.data(), kernel_.size()) += ups.head(kernel_.size());\n\t\tif(useBias_)\n\t\t{\n\t\t\tbias_ += ups.tail(outChannels_);\n\t\t}\n\t}\n\n\t/**\n\t * Feedforward\n\t * @input: inChannels*size\n\t * @output: outChannels*size\n\t */\n\tvoid forward(const VectorConstRef& input, VectorRef output) override \n\t{\n\t\tassert(input.size() % inChannels_ == 0);\n\t\tuint32_t inSize = input.size() / inChannels_;\n\t\tuint32_t outSize = inSize / stride_;\n\n\t\toutput.setZero();\n\n\t\t// y = Wx+b\n\t\tfor (uint32_t oc = 0; oc < outChannels_; oc++)\n\t\tfor (uint32_t r = 0; r < outSize; r ++) \n\t\t{\n\t\t\tfor (uint32_t ic = 0; ic < inChannels_; ic++)\n\t\t\tfor (uint32_t ki = 0; ki < kernelSize_; ki++)\n\t\t\t{\n\t\t\t\toutput(r + oc*outSize) += kernel_(ki + ic*kernelSize_, oc)\n\t\t\t\t\t*input(((r*stride_+ki-kernelSize_/2+inSize)%inSize) + ic*inSize);\n\t\t\t}\n\t\t}\n\n\t\tif (useBias_) {\n\t\t\tfor (uint32_t oc = 0; oc < outChannels_; ++oc) {\n\t\t\t\tfor (uint32_t i = 0; i < outSize; ++i) {\n\t\t\t\t\toutput(i + oc*outSize) += bias_(oc);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid backprop(const VectorConstRef& prev_layer_output,\n\t\t\tconst VectorConstRef& /*this_layer_output*/,\n\t\t\tconst VectorConstRef& dout, \n\t\t\tVectorRef din,\n\t\t\tVectorRef der) override\n\t{\n\t\tassert(prev_layer_output.size() % inChannels_ == 0);\n\t\tuint32_t inSize = prev_layer_output.size() / inChannels_;\n\t\tuint32_t outSize = inSize / stride_;\n\n\t\tdin.resize(inSize*inChannels_);\n\t\tdin.setZero();\n\t\tder.setZero();\n\n\t\t// propagate delta to prev-layer\n\t\tfor (uint32_t oc = 0; oc < outChannels_; oc++)\n\t\tfor (uint32_t r = 0; r < outSize; r ++) \n\t\tfor (uint32_t ic = 0; ic < inChannels_; ic++)\n\t\tfor (uint32_t ki = 0; ki < kernelSize_; ki++)\n\t\t{\n\t\t\tdin(((r*stride_+ki-kernelSize_/2+inSize)%inSize) + ic*inSize) \n\t\t\t\t+= kernel_(ki + ic*kernelSize_, oc)*dout[r + oc*outSize];\n\t\t}\n\n\t\t// weight der\n\t\tMatrix dw(inChannels_*kernelSize_, outChannels_);\n\t\tdw.setZero();\n\n\t\t// accumulate weight difference\n\t\tfor (uint32_t oc = 0; oc < outChannels_; oc++)\n\t\tfor (uint32_t r = 0; r < outSize; r ++) \n\t\t{\n\t\t\tfor (uint32_t ic = 0; ic < inChannels_; ic++)\n\t\t\tfor (uint32_t ki = 0; ki < kernelSize_; ki++)\n\t\t\t{\n\t\t\t\tdw(ki + ic*kernelSize_, oc) += \n\t\t\t\t\tprev_layer_output(((r*stride_+ki-kernelSize_/2+inSize)%inSize) + ic*inSize)*\n\t\t\t\t\tdout[r + oc*outSize];\n\t\t\t}\n\t\t}\n\t\tdw.resize(dw.rows()*dw.cols(),1);\n\t\tder.head(kernel_.size()) = std::move(dw);\n\t\t\n\t\tuint32_t k = kernel_.size();\n\t\tif(useBias_)// accumulate bias difference\n\t\t{\n\t\t\tfor (uint32_t oc = 0; oc < outChannels_; oc++)\n\t\t\tfor (uint32_t r = 0; r < outSize; r ++) \n\t\t\t{\n\t\t\t\tder(oc + k) += dout(r + oc*outSize);\n\t\t\t}\n\t\t}\n\t}\n\n\tuint32_t fanIn() override\n\t{\n\t\treturn inChannels_*kernelSize_;\n\t}\n\tuint32_t fanOut() override\n\t{\n\t\treturn outChannels_*kernelSize_;\n\t}\n\n\tnlohmann::json desc() const override {\n\t\tnlohmann::json layerpar;\n\t\tlayerpar[\"name\"] = name();\n\t\tlayerpar[\"use_bias\"] = useBias_;\n\t\tlayerpar[\"input_channels\"] = inChannels_;\n\t\tlayerpar[\"output_channels\"] = outChannels_;\n\t\tlayerpar[\"kernel_size\"] = kernelSize_;\n\t\tlayerpar[\"stride\"] = stride_;\n\t\treturn layerpar;\n\t}\n};\n}// namespace yannq\n\n#endif\n", "meta": {"hexsha": "9899c369a334dfce3e8f4de7898ca94a8038aba5", "size": 6514, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Machines/layers/Conv1D.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Machines/layers/Conv1D.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Machines/layers/Conv1D.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.056, "max_line_length": 87, "alphanum_fraction": 0.6734725207, "num_tokens": 1965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6100770348298813}}
{"text": "//\n// Environment that supports circle obstacles.\n//\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <array>\n#include <vector>\n\nnamespace circle_world \n{\n\nconstexpr int OBSTACLE_DIM = 2;\n\nclass Circle\n{\npublic:\n    Circle(const double radius, const double x, double y);\n    Circle(const double radius, const Eigen::Vector2d &position);\n\n    // Returns TRUE if the other circle intersects with this circle. \n    // The Euclidean distance between the edges of the circles is returned in distance. \n    // The distance will be negative if they intersect.\n    bool distance(const Circle &other, double &distance) const;\n\n    // Returns the Euclidean distance between the centroids of this circle and the other.\n    double centroid_distance(const Circle &other) const;\n\n    double radius() const { return radius_; }\n    double& radius() { return radius_; }\n\n    Eigen::Vector2d& position() { return position_; };\n    const Eigen::Vector2d& position() const { return position_; };\n\nprivate:\n    double radius_ = 0;\n    Eigen::Vector2d position_ = Eigen::Vector2d::Zero();\n};\n\nclass CircleWorld\n{\npublic:\n    // Set the world boundary constraints to the default.\n    CircleWorld() = default;\n\n    // Set the world boundary constraints.\n    CircleWorld(double min_x, double max_x, double min_y, double max_y); \n    // Same order as above, [min_x, max_x, min_y, max_y].\n    CircleWorld(const std::array<double, 4> &world_dims);\n\n    void add_obstacle(const double radius, double x, double y);\n    void add_obstacle(const double radius, const Eigen::Vector2d& position);\n    void add_obstacle(const Circle &obstacle);\n\n    // Returns TRUE if circle intersects with any obstacle. \n    // The Euclidean distance from circle's edge to all the obstacles \n    // is returned in distance. \n    // The distance will be negative if they intersect.\n    bool distances(const Circle& circle, std::vector<double> &distances) const;\n\n    const std::vector<Circle> &obstacles() const { return obstacles_; }\n    std::vector<Circle> &obstacles() { return obstacles_; }\n    \n    std::array<double, 4> dimensions() const { return {{min_x_, max_x_, min_y_, max_y_}}; }\n\nprivate:\n    std::vector<Circle> obstacles_;\n\n    double min_x_ = -20;\n    double max_x_ = 20;\n    double min_y_ = -20;\n    double max_y_ = 20;\n};\n\nstd::ostream& operator<<(std::ostream& os, const Circle& o);\n\n// First line is the dimensions of the world.\n// Following lines are posx posy radius) for each Circle obstacle.\n// Everything is set at 13 character width for each entry.\nstd::ostream& operator<<(std::ostream& os, const CircleWorld& world);\n\n} // namespace circle_world \n\n", "meta": {"hexsha": "24aae0b785f71ad46994c94ff62ec163e62182c4", "size": 2624, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/experiments/simulators/circle_world.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/experiments/simulators/circle_world.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/experiments/simulators/circle_world.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": 30.511627907, "max_line_length": 91, "alphanum_fraction": 0.7019817073, "num_tokens": 628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6100220588186723}}
{"text": "#pragma once\r\n\r\n#include <Eigen/Eigen>\r\n#include <glm/glm.hpp>\r\n\r\nnamespace gfx\r\n{\r\ntemplate <glm::length_t C, typename T, glm::qualifier Q> struct eigenresults\r\n{\r\n    glm::mat<C, C, T, Q> eigenvectors;\r\n    glm::vec<C, T, Q>    eigenvalues;\r\n};\r\n\r\ntemplate <glm::length_t C, typename T, glm::qualifier Q> eigenresults<C, T, Q> eig(const glm::mat<C, C, T, Q>& matrix)\r\n{\r\n    static Eigen::EigenSolver<Eigen::Matrix<T, C, C>> solver;\r\n    Eigen::Matrix3d                            matrix_eigen = reinterpret_cast<const Eigen::Matrix3d&>(matrix);\r\n    solver.compute(matrix_eigen);\r\n\r\n    eigenresults<C, T, Q> results;\r\n    Eigen::Matrix3d vectors = solver.eigenvectors().real();\r\n    Eigen::Vector3d values  = solver.eigenvalues().real();\r\n    results.eigenvalues     = reinterpret_cast<const glm::dvec3&>(values);\r\n    results.eigenvectors    = reinterpret_cast<const glm::dmat3&>(vectors);\r\n    return results;\r\n}\r\n}", "meta": {"hexsha": "e590d5b5ca6df2ec8de82a90971b9c23955fc228", "size": 921, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gfx/math/math.hpp", "max_stars_repo_name": "johannes-braun/graphics_utilities", "max_stars_repo_head_hexsha": "191772a3ff1c14eea74b9b5614b6226cf1f8abb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gfx/math/math.hpp", "max_issues_repo_name": "johannes-braun/graphics_utilities", "max_issues_repo_head_hexsha": "191772a3ff1c14eea74b9b5614b6226cf1f8abb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gfx/math/math.hpp", "max_forks_repo_name": "johannes-braun/graphics_utilities", "max_forks_repo_head_hexsha": "191772a3ff1c14eea74b9b5614b6226cf1f8abb7", "max_forks_repo_licenses": ["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.1111111111, "max_line_length": 119, "alphanum_fraction": 0.6460369164, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.6548947223065754, "lm_q1q2_score": 0.6100098798398013}}
{"text": "/*\n   Copyright (C) 2015-2021 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n// Free energy, energy, and specific heat of square lattice Ising model\n\n#pragma once\n\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n\nnamespace tfi {\nnamespace energy {\nnamespace chain {\n\nnamespace {\n\ntemplate<typename T>\nstruct functor {\n  typedef T real_t;\n  functor(real_t J, real_t Gamma) : J_(J), Gamma_(Gamma) {}\n  real_t operator()(real_t k) const {\n    using std::abs; using std::cos; using std::sin; using std::sqrt; using std::pow;\n    return 2 * abs(J_) * sqrt(pow(cos(k) - (Gamma_ / J_), 2) + pow(sin(k), 2));\n  }\n  real_t J_, Gamma_;\n};\n\ntemplate<typename T>\nfunctor<T> func(T J, T Gamma) { return functor<T>(J, Gamma); }\n\n}\n  \ntemplate<typename T>\ninline T infinite(T J, T Gamma) {\n  using std::abs;\n  typedef T real_t;\n  if (abs(J)> 0) {\n    auto pi = boost::math::constants::pi<real_t>();\n    boost::math::quadrature::tanh_sinh<real_t> integrator;\n    return -integrator.integrate(func(J, Gamma), 0, pi) / (2 * pi);\n  } else {\n    return -abs(Gamma);\n  }\n}\n\n} // end namespace chain\n} // end namespace energy\n} // end namespace tfi\n", "meta": {"hexsha": "2ee618f42a4771e7737d6dbe61fc52d1761e80d4", "size": 1742, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tfi/energy/chain.hpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "tfi/energy/chain.hpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "tfi/energy/chain.hpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6507936508, "max_line_length": 84, "alphanum_fraction": 0.6911595867, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6099927647361221}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\r\n/*\r\n\r\n    This is an example illustrating the use of the support vector machine\r\n    utilities from the dlib C++ Library.  \r\n\r\n    This example creates a simple set of data to train on and then shows\r\n    you how to use the cross validation and svm training functions\r\n    to find a good decision function that can classify examples in our\r\n    data set.\r\n\r\n\r\n    The data used in this example will be 2 dimensional data and will\r\n    come from a distribution where points with a distance less than 10\r\n    from the origin are labeled +1 and all other points are labeled\r\n    as -1.\r\n        \r\n*/\r\n\r\n\r\n#include <iostream>\r\n#include <dlib/svm.h>\r\n\r\nusing namespace std;\r\nusing namespace dlib;\r\n\r\n\r\nint main()\r\n{\r\n    // The svm functions use column vectors to contain a lot of the data on which they\r\n    // operate. So the first thing we do here is declare a convenient typedef.  \r\n\r\n    // This typedef declares a matrix with 2 rows and 1 column.  It will be the object that\r\n    // contains each of our 2 dimensional samples.   (Note that if you wanted more than 2\r\n    // features in this vector you can simply change the 2 to something else.  Or if you\r\n    // don't know how many features you want until runtime then you can put a 0 here and\r\n    // use the matrix.set_size() member function)\r\n    typedef matrix<double, 2, 1> sample_type;\r\n\r\n    // This is a typedef for the type of kernel we are going to use in this example.  In\r\n    // this case I have selected the radial basis kernel that can operate on our 2D\r\n    // sample_type objects\r\n    typedef radial_basis_kernel<sample_type> kernel_type;\r\n\r\n\r\n    // Now we make objects to contain our samples and their respective labels.\r\n    std::vector<sample_type> samples;\r\n    std::vector<double> labels;\r\n\r\n    // Now let's put some data into our samples and labels objects.  We do this by looping\r\n    // over a bunch of points and labeling them according to their distance from the\r\n    // origin.\r\n    for (int r = -20; r <= 20; ++r)\r\n    {\r\n        for (int c = -20; c <= 20; ++c)\r\n        {\r\n            sample_type samp;\r\n            samp(0) = r;\r\n            samp(1) = c;\r\n            samples.push_back(samp);\r\n\r\n            // if this point is less than 10 from the origin\r\n            if (sqrt((double)r*r + c*c) <= 10)\r\n                labels.push_back(+1);\r\n            else\r\n                labels.push_back(-1);\r\n\r\n        }\r\n    }\r\n\r\n\r\n    // Here we normalize all the samples by subtracting their mean and dividing by their\r\n    // standard deviation.  This is generally a good idea since it often heads off\r\n    // numerical stability problems and also prevents one large feature from smothering\r\n    // others.  Doing this doesn't matter much in this example so I'm just doing this here\r\n    // so you can see an easy way to accomplish this with the library.  \r\n    vector_normalizer<sample_type> normalizer;\r\n    // let the normalizer learn the mean and standard deviation of the samples\r\n    normalizer.train(samples);\r\n    // now normalize each sample\r\n    for (unsigned long i = 0; i < samples.size(); ++i)\r\n        samples[i] = normalizer(samples[i]); \r\n\r\n\r\n    // Now that we have some data we want to train on it.  However, there are two\r\n    // parameters to the training.  These are the nu and gamma parameters.  Our choice for\r\n    // these parameters will influence how good the resulting decision function is.  To\r\n    // test how good a particular choice of these parameters is we can use the\r\n    // cross_validate_trainer() function to perform n-fold cross validation on our training\r\n    // data.  However, there is a problem with the way we have sampled our distribution\r\n    // above.  The problem is that there is a definite ordering to the samples.  That is,\r\n    // the first half of the samples look like they are from a different distribution than\r\n    // the second half.  This would screw up the cross validation process but we can fix it\r\n    // by randomizing the order of the samples with the following function call.\r\n    randomize_samples(samples, labels);\r\n\r\n\r\n    // The nu parameter has a maximum value that is dependent on the ratio of the +1 to -1\r\n    // labels in the training data.  This function finds that value.\r\n    const double max_nu = maximum_nu(labels);\r\n\r\n    // here we make an instance of the svm_nu_trainer object that uses our kernel type.\r\n    svm_nu_trainer<kernel_type> trainer;\r\n\r\n    // Now we loop over some different nu and gamma values to see how good they are.  Note\r\n    // that this is a very simple way to try out a few possible parameter choices.  You\r\n    // should look at the model_selection_ex.cpp program for examples of more sophisticated\r\n    // strategies for determining good parameter choices.\r\n    cout << \"doing cross validation\" << endl;\r\n    for (double gamma = 0.00001; gamma <= 1; gamma *= 5)\r\n    {\r\n        for (double nu = 0.00001; nu < max_nu; nu *= 5)\r\n        {\r\n            // tell the trainer the parameters we want to use\r\n            trainer.set_kernel(kernel_type(gamma));\r\n            trainer.set_nu(nu);\r\n\r\n            cout << \"gamma: \" << gamma << \"    nu: \" << nu;\r\n            // Print out the cross validation accuracy for 3-fold cross validation using\r\n            // the current gamma and nu.  cross_validate_trainer() returns a row vector.\r\n            // The first element of the vector is the fraction of +1 training examples\r\n            // correctly classified and the second number is the fraction of -1 training\r\n            // examples correctly classified.\r\n            cout << \"     cross validation accuracy: \" << cross_validate_trainer(trainer, samples, labels, 3);\r\n        }\r\n    }\r\n\r\n\r\n    // From looking at the output of the above loop it turns out that a good value for nu\r\n    // and gamma for this problem is 0.15625 for both.  So that is what we will use.\r\n\r\n    // Now we train on the full set of data and obtain the resulting decision function.  We\r\n    // use the value of 0.15625 for nu and gamma.  The decision function will return values\r\n    // >= 0 for samples it predicts are in the +1 class and numbers < 0 for samples it\r\n    // predicts to be in the -1 class.\r\n    trainer.set_kernel(kernel_type(0.15625));\r\n    trainer.set_nu(0.15625);\r\n    typedef decision_function<kernel_type> dec_funct_type;\r\n    typedef normalized_function<dec_funct_type> funct_type;\r\n\r\n    // Here we are making an instance of the normalized_function object.  This object\r\n    // provides a convenient way to store the vector normalization information along with\r\n    // the decision function we are going to learn.  \r\n    funct_type learned_function;\r\n    learned_function.normalizer = normalizer;  // save normalization information\r\n    learned_function.function = trainer.train(samples, labels); // perform the actual SVM training and save the results\r\n\r\n    // print out the number of support vectors in the resulting decision function\r\n    cout << \"\\nnumber of support vectors in our learned_function is \" \r\n         << learned_function.function.basis_vectors.size() << endl;\r\n\r\n    // Now let's try this decision_function on some samples we haven't seen before.\r\n    sample_type sample;\r\n\r\n    sample(0) = 3.123;\r\n    sample(1) = 2;\r\n    cout << \"This is a +1 class example, the classifier output is \" << learned_function(sample) << endl;\r\n\r\n    sample(0) = 3.123;\r\n    sample(1) = 9.3545;\r\n    cout << \"This is a +1 class example, the classifier output is \" << learned_function(sample) << endl;\r\n\r\n    sample(0) = 13.123;\r\n    sample(1) = 9.3545;\r\n    cout << \"This is a -1 class example, the classifier output is \" << learned_function(sample) << endl;\r\n\r\n    sample(0) = 13.123;\r\n    sample(1) = 0;\r\n    cout << \"This is a -1 class example, the classifier output is \" << learned_function(sample) << endl;\r\n\r\n\r\n    // We can also train a decision function that reports a well conditioned probability\r\n    // instead of just a number > 0 for the +1 class and < 0 for the -1 class.  An example\r\n    // of doing that follows:\r\n    typedef probabilistic_decision_function<kernel_type> probabilistic_funct_type;  \r\n    typedef normalized_function<probabilistic_funct_type> pfunct_type;\r\n\r\n    pfunct_type learned_pfunct; \r\n    learned_pfunct.normalizer = normalizer;\r\n    learned_pfunct.function = train_probabilistic_decision_function(trainer, samples, labels, 3);\r\n    // Now we have a function that returns the probability that a given sample is of the +1 class.  \r\n\r\n    // print out the number of support vectors in the resulting decision function.  \r\n    // (it should be the same as in the one above)\r\n    cout << \"\\nnumber of support vectors in our learned_pfunct is \" \r\n         << learned_pfunct.function.decision_funct.basis_vectors.size() << endl;\r\n\r\n    sample(0) = 3.123;\r\n    sample(1) = 2;\r\n    cout << \"This +1 class example should have high probability.  Its probability is: \" \r\n         << learned_pfunct(sample) << endl;\r\n\r\n    sample(0) = 3.123;\r\n    sample(1) = 9.3545;\r\n    cout << \"This +1 class example should have high probability.  Its probability is: \" \r\n         << learned_pfunct(sample) << endl;\r\n\r\n    sample(0) = 13.123;\r\n    sample(1) = 9.3545;\r\n    cout << \"This -1 class example should have low probability.  Its probability is: \" \r\n         << learned_pfunct(sample) << endl;\r\n\r\n    sample(0) = 13.123;\r\n    sample(1) = 0;\r\n    cout << \"This -1 class example should have low probability.  Its probability is: \" \r\n         << learned_pfunct(sample) << endl;\r\n\r\n\r\n\r\n    // Another thing that is worth knowing is that just about everything in dlib is\r\n    // serializable.  So for example, you can save the learned_pfunct object to disk and\r\n    // recall it later like so:\r\n    serialize(\"saved_function.dat\") << learned_pfunct;\r\n\r\n    // Now let's open that file back up and load the function object it contains.\r\n    deserialize(\"saved_function.dat\") >> learned_pfunct;\r\n\r\n    // Note that there is also an example program that comes with dlib called the\r\n    // file_to_code_ex.cpp example.  It is a simple program that takes a file and outputs a\r\n    // piece of C++ code that is able to fully reproduce the file's contents in the form of\r\n    // a std::string object.  So you can use that along with the std::istringstream to save\r\n    // learned decision functions inside your actual C++ code files if you want.  \r\n\r\n\r\n\r\n\r\n    // Lastly, note that the decision functions we trained above involved well over 200\r\n    // basis vectors.  Support vector machines in general tend to find decision functions\r\n    // that involve a lot of basis vectors.  This is significant because the more basis\r\n    // vectors in a decision function, the longer it takes to classify new examples.  So\r\n    // dlib provides the ability to find an approximation to the normal output of a trainer\r\n    // using fewer basis vectors.  \r\n\r\n    // Here we determine the cross validation accuracy when we approximate the output using\r\n    // only 10 basis vectors.  To do this we use the reduced2() function.  It takes a\r\n    // trainer object and the number of basis vectors to use and returns a new trainer\r\n    // object that applies the necessary post processing during the creation of decision\r\n    // function objects.\r\n    cout << \"\\ncross validation accuracy with only 10 support vectors: \" \r\n         << cross_validate_trainer(reduced2(trainer,10), samples, labels, 3);\r\n\r\n    // Let's print out the original cross validation score too for comparison.\r\n    cout << \"cross validation accuracy with all the original support vectors: \" \r\n         << cross_validate_trainer(trainer, samples, labels, 3);\r\n\r\n    // When you run this program you should see that, for this problem, you can reduce the\r\n    // number of basis vectors down to 10 without hurting the cross validation accuracy. \r\n\r\n\r\n    // To get the reduced decision function out we would just do this:\r\n    learned_function.function = reduced2(trainer,10).train(samples, labels);\r\n    // And similarly for the probabilistic_decision_function: \r\n    learned_pfunct.function = train_probabilistic_decision_function(reduced2(trainer,10), samples, labels, 3);\r\n}\r\n\r\n", "meta": {"hexsha": "3cbb7ca83679d5e275dfdd8cd5c38ad0b69a4c73", "size": 12223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/svm_ex.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/svm_ex.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "examples/svm_ex.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.74609375, "max_line_length": 120, "alphanum_fraction": 0.6766751207, "num_tokens": 2831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6099621213543337}}
{"text": "//\n//  main.cpp\n//  LR-x\n//\n//  Created by zhuangqh on 2017/6/16.\n//  Copyright \u00a9 2017\u5e74 zhuangqh. All rights reserved.\n//\n\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <omp.h>\n#include \"io.h\"\n#include \"LR.hpp\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nvoid timer_wrapper(std::function<void()> func) {\n  double startTime = omp_get_wtime();\n  func();\n  double stopTime = omp_get_wtime();\n\n  std::cout << stopTime - startTime << std::endl;\n}\n\nvoid save_res(const char *filename, VectorXd &res) {\n  std::ofstream f(filename);\n  f << res;\n  f.close();\n}\n\nint main() {\n\n//  auto mat = LR::IO::load_txt(\"./train.txt\", 1866819, 201);\n\n  auto train = LR::IO::load_csv(\"../spamtrain.csv\", 2760, 57);\n\n  auto test = LR::IO::load_csv(\"../spamtest.csv\", 1841, 57);\n\n  LR::LogisticRegression lr(1e-5, 1000, 0);\n\n  VectorXd res;\n\n  timer_wrapper([&]() {\n    lr.fit_naive(train);\n  });\n  res = lr.predict(test.first);\n  save_res(\"naive.txt\", res);\n\n  timer_wrapper([&]() {\n    lr.fit_vec(train);\n  });\n  res = lr.predict(test.first);\n  save_res(\"vectorization.txt\", res);\n\n  timer_wrapper([&]() {\n    lr.fit_parallel(train);\n  });\n  res = lr.predict(test.first);\n  save_res(\"parallel.txt\", res);\n\n  return 0;\n}\n", "meta": {"hexsha": "95d224f9c4e3d11fd503c78f052e7b82a5cf1894", "size": 1227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "zhuangqh/LR-x", "max_stars_repo_head_hexsha": "c33fb552d786ab7dc5a2afa00acf4d0760d8e3b3", "max_stars_repo_licenses": ["MIT"], "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": "zhuangqh/LR-x", "max_issues_repo_head_hexsha": "c33fb552d786ab7dc5a2afa00acf4d0760d8e3b3", "max_issues_repo_licenses": ["MIT"], "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": "zhuangqh/LR-x", "max_forks_repo_head_hexsha": "c33fb552d786ab7dc5a2afa00acf4d0760d8e3b3", "max_forks_repo_licenses": ["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.8769230769, "max_line_length": 62, "alphanum_fraction": 0.62999185, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6099621120853891}}
{"text": "#define BOOST_TEST_MODULE \"test_matrix\"\n\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost/test/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mill/math/Matrix.hpp>\n\n#include <random>\nconstexpr static unsigned int seed = 32479327;\nconstexpr static std::size_t N = 10000;\n\nBOOST_AUTO_TEST_CASE(construct_matrix_3x3)\n{\n    {\n        mill::Matrix<double, 3, 3> mat;\n        BOOST_CHECK_EQUAL((mat(0, 0)), 0);\n        BOOST_CHECK_EQUAL((mat(0, 1)), 0);\n        BOOST_CHECK_EQUAL((mat(0, 2)), 0);\n        BOOST_CHECK_EQUAL((mat(1, 0)), 0);\n        BOOST_CHECK_EQUAL((mat(1, 1)), 0);\n        BOOST_CHECK_EQUAL((mat(1, 2)), 0);\n        BOOST_CHECK_EQUAL((mat(2, 0)), 0);\n        BOOST_CHECK_EQUAL((mat(2, 1)), 0);\n        BOOST_CHECK_EQUAL((mat(2, 2)), 0);\n    }\n\n    {\n        mill::Matrix<double, 3, 3> mat(1, 2, 3, 4, 5, 6, 7, 8, 9);\n        BOOST_CHECK_EQUAL((mat(0, 0)), 1);\n        BOOST_CHECK_EQUAL((mat(0, 1)), 2);\n        BOOST_CHECK_EQUAL((mat(0, 2)), 3);\n        BOOST_CHECK_EQUAL((mat(1, 0)), 4);\n        BOOST_CHECK_EQUAL((mat(1, 1)), 5);\n        BOOST_CHECK_EQUAL((mat(1, 2)), 6);\n        BOOST_CHECK_EQUAL((mat(2, 0)), 7);\n        BOOST_CHECK_EQUAL((mat(2, 1)), 8);\n        BOOST_CHECK_EQUAL((mat(2, 2)), 9);\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(add_matrix_3x3)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(-1.0, 1.0);\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        mill::Matrix<double, 3, 3> lhs;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<3; ++j)\n                lhs(i, j) = uni(mt);\n\n        mill::Matrix<double, 3, 3> rhs;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<3; ++j)\n                rhs(i, j) = uni(mt);\n\n        mill::Matrix<double, 3, 3> mat = lhs + rhs;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<3; ++j)\n                BOOST_CHECK_EQUAL((mat(i, j)), (lhs(i, j) + rhs(i, j)));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(sub_matrix_3x3)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(-1.0, 1.0);\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        mill::Matrix<double, 3, 3> lhs;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<3; ++j)\n                lhs(i, j) = uni(mt);\n\n        mill::Matrix<double, 3, 3> rhs;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<3; ++j)\n                rhs(i, j) = uni(mt);\n\n        mill::Matrix<double, 3, 3> mat = lhs - rhs;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<3; ++j)\n                BOOST_CHECK_EQUAL((mat(i, j)), (lhs(i, j) - rhs(i, j)));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(scalar_mul_matrix_3x3)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(-1.0, 1.0);\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        mill::Matrix<double, 3, 3> lhs;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<3; ++j)\n                lhs(i, j) = uni(mt);\n        const double scl = uni(mt);\n\n        {\n        mill::Matrix<double, 3, 3> mat = lhs * scl;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<3; ++j)\n                BOOST_CHECK_EQUAL((mat(i, j)), (lhs(i, j) * scl));\n        }\n\n        {\n        mill::Matrix<double, 3, 3> mat = scl * lhs;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<3; ++j)\n                BOOST_CHECK_EQUAL((mat(i, j)), (scl * lhs(i, j)));\n        }\n\n    }\n}\n\nBOOST_AUTO_TEST_CASE(scalar_div_matrix_3x3)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(-1.0, 1.0);\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        mill::Matrix<double, 3, 3> lhs;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<3; ++j)\n                lhs(i, j) = uni(mt);\n        const double scl = uni(mt);\n\n        mill::Matrix<double, 3, 3> mat = lhs / scl;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<3; ++j)\n                BOOST_CHECK_EQUAL((mat(i, j)), (lhs(i, j) / scl));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(multi_matrix_2x2_2x2)\n{\n    mill::Matrix<int, 2, 2> lhs;\n    lhs(0,0) = 5;\n    lhs(0,1) = 6;\n    lhs(1,0) = 7;\n    lhs(1,1) = 8;\n    mill::Matrix<int, 2, 2> rhs;\n    rhs(0,0) = 1;\n    rhs(0,1) = 2;\n    rhs(1,0) = 3;\n    rhs(1,1) = 4;\n    mill::Matrix<int, 2, 2> mat = lhs * rhs;\n    BOOST_CHECK_EQUAL((mat(0,0)), 23);\n    BOOST_CHECK_EQUAL((mat(0,1)), 34);\n    BOOST_CHECK_EQUAL((mat(1,0)), 31);\n    BOOST_CHECK_EQUAL((mat(1,1)), 46);\n}\n\nBOOST_AUTO_TEST_CASE(multi_matrix_3x4_4x2)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(-1.0, 1.0);\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        mill::Matrix<double, 3, 4> lhs;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<4; ++j)\n                lhs(i, j) = uni(mt);\n\n        mill::Matrix<double, 4, 2> rhs;\n        for(std::size_t i=0; i<4; ++i)\n            for(std::size_t j=0; j<2; ++j)\n                rhs(i, j) = uni(mt);\n\n        mill::Matrix<double, 3, 2> mat = lhs * rhs;\n        for(std::size_t i=0; i<3; ++i)\n            for(std::size_t j=0; j<2; ++j)\n            {\n                double sum = 0.;\n                for(std::size_t k=0; k<4; ++k)\n                    sum += lhs(i, k) * rhs(k, j);\n                BOOST_CHECK_EQUAL((mat(i, j)), sum);\n            }\n    }\n}\n\nBOOST_AUTO_TEST_CASE(multi_matrix_dynamic)\n{\n    std::mt19937 mt(seed);\n    std::uniform_real_distribution<double> uni(-1.0, 1.0);\n\n    for(std::size_t test_times=0; test_times<N; ++test_times)\n    {\n        mill::Matrix<double, mill::DYNAMIC, mill::DYNAMIC> lhs({10u, 10u});\n        mill::Matrix<double, mill::DYNAMIC, mill::DYNAMIC> rhs({10u, 10u});\n\n        for(std::size_t i=0; i<lhs.len(); ++i)\n        {\n            lhs[i] = uni(mt);\n            rhs[i] = uni(mt);\n        }\n\n        mill::Matrix<double, mill::DYNAMIC, mill::DYNAMIC> sum = lhs + rhs;\n        BOOST_TEST(sum.row() == 10u);\n        BOOST_TEST(sum.col() == 10u);\n        for(std::size_t i=0; i<lhs.len(); ++i)\n        {\n            BOOST_CHECK_EQUAL(sum[i], lhs[i] + rhs[i]);\n        }\n\n        mill::Matrix<double, mill::DYNAMIC, mill::DYNAMIC> mul = lhs * rhs;\n        BOOST_TEST(mul.row() == 10u);\n        BOOST_TEST(mul.col() == 10u);\n        for(std::size_t i=0; i<lhs.row(); ++i)\n        {\n            for(std::size_t j=0; j<rhs.col(); ++j)\n            {\n                double s=0;\n                for(std::size_t k=0; k<lhs.col(); ++k)\n                {\n                    s += lhs(i, k) * rhs(k, j);\n                }\n                BOOST_TEST(mul(i, j) == s, boost::test_tools::tolerance(1e-8));\n            }\n        }\n    }\n}\n\n", "meta": {"hexsha": "8ead2d58c4dbdcae673e3e07ce1604804d7d25e4", "size": 6852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math/test_matrix.cpp", "max_stars_repo_name": "ToruNiina/Coffee-mill", "max_stars_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-12-11T07:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-01T07:33:37.000Z", "max_issues_repo_path": "tests/math/test_matrix.cpp", "max_issues_repo_name": "ToruNiina/Coffee-mill", "max_issues_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/math/test_matrix.cpp", "max_forks_repo_name": "ToruNiina/Coffee-mill", "max_forks_repo_head_hexsha": "343a6b89f7bc4645d596809aac9009db1c5ec0d8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9213973799, "max_line_length": 79, "alphanum_fraction": 0.5083187391, "num_tokens": 2305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402813, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6097667796652078}}
{"text": "#pragma once\n#include <Eigen/Dense>\nusing namespace Eigen;\n\nclass lrsgd\n{\npublic:\n\tlrsgd();\n\t~lrsgd() {};\n\n\tVectorXf sigmoid(VectorXf& a);\n\tvoid lr_objective(float& cost, VectorXf& grad, VectorXf& theta);\n\tvoid fit(void);\n\tvoid generate_data(MatrixXf& X, VectorXi& y);\n\n\tint num_iter;       //max number of iterations\n\tVectorXf theta;     //logistic regression weights\n\tfloat lambda;       //regularization parameter\n\tfloat cost;         //LR objective\n\tVectorXf grad;      //gradient of LR objective\n\n\tint tau0;           //learning rate parameter\n\tint kappa;          //learning rate parameter\n\tVectorXf eta;       //learning rate schedule\t\n\n\tMatrixXf X;         //input data n x d\n\tVectorXi y;         //input labels n x 1\n};\n", "meta": {"hexsha": "ebcbe36e769fac34b1da05d76f0c1f9ee2553b53", "size": 729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "machine_learning/logreg/logreg.hpp", "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/logreg/logreg.hpp", "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/logreg/logreg.hpp", "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": 25.1379310345, "max_line_length": 65, "alphanum_fraction": 0.6598079561, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6097667570167764}}
{"text": "\n#include \"obj.h\"\n#include \"assignment.h\"\n#include \"HungarianAlg.h\"\n\n#include <math.h>\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <ctime>\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include <iostream>\n\ntemplate<typename LeftClass, typename RightClass>\ndouble function_t(LeftClass& lc, RightClass& rc) {\n\treturn std::sqrt((lc.x - rc.x)*(lc.x -\trc.x) + (lc.y - rc.y)*(lc.y -\trc.y)); \n}\n\n#define RANGE 100.0\n\nint main (int argc, char** argv) {\n#ifdef (WIN32 || WIN64)\n\tsrand((unsigned)time(NULL));\n#else\n\tsrandom((unsigned)time(NULL));\n#endif\n\tint M = 10;\n\tint N = 15;\n\tdouble dist_thresh = 10.0;\n\tstd::vector<ele::LeftObj> left_obj(M);\n\tstd::vector<ele::RightObj> right_obj(N);\n\n\tEigen::MatrixXd l_value = (Eigen::MatrixXd::Random(M, 2)).array().abs() * 100.0;\n\tfor (int i=0; i<l_value.rows(); i++) {\n\t\tleft_obj[i].x = l_value(i, 0);\n\t\tleft_obj[i].x = l_value(i, 1);\n\t}\n\tEigen::MatrixXd r_value = (Eigen::MatrixXd::Random(N, 2)).array().abs() * 100.0;\n\tfor (int i=0; i<r_value.rows(); i++) {\n\t\tright_obj[i].x = r_value(i, 0);\n\t\tright_obj[i].x = r_value(i, 1);\n\t}\n\n\tstd::cout << \"create Assingment\" << std::endl;\n\tele::Assignment<ele::LeftObj, ele::RightObj> assign_engine(&left_obj, \n\t\t\t&right_obj,  function_t<ele::LeftObj, ele::RightObj>, dist_thresh);\n\n\tstd::cout << \"start Solve...\" << std::endl;\n\tassign_engine.Solve();\n\n\tstd::cout << \"Solved and get result\" << std::endl;\n\tstd::vector<int> result = assign_engine.Assign(); \n\n\tfor (size_t i=0; i<result.size(); i++) {\n\t\tif (result[i] < 0)\n\t\t\tstd::cout << \"Left: \" << i << \" --> null\" << std::endl;\n\t\telse\n\t\t\tstd::cout << \"Left: \" << i << \" --> Right: \" << result[i] << std::endl;\n\t}\n\n  return 0;\n}", "meta": {"hexsha": "0300cffa2262ecc385d7352e54b9dddaef81f560", "size": 1671, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/main.cc", "max_stars_repo_name": "peihy2012/BKM", "max_stars_repo_head_hexsha": "72637a967aff087883ed631d04d322168e726f09", "max_stars_repo_licenses": ["MIT"], "max_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.cc", "max_issues_repo_name": "peihy2012/BKM", "max_issues_repo_head_hexsha": "72637a967aff087883ed631d04d322168e726f09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cc", "max_forks_repo_name": "peihy2012/BKM", "max_forks_repo_head_hexsha": "72637a967aff087883ed631d04d322168e726f09", "max_forks_repo_licenses": ["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.7076923077, "max_line_length": 81, "alphanum_fraction": 0.6241771394, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6097667520734197}}
{"text": "#define BOOST_TEST_MODULE functions\n#define BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#include \"exprtest.hpp\"\n\nEXPRTEST(func_abs   , \"abs   (-1.0)\", std::abs   (-1.0))\nEXPRTEST(func_acos  , \"acos  ( 1.0)\", std::acos  ( 1.0))\nEXPRTEST(func_acosh , \"acosh ( 1.0)\", std::acosh ( 1.0))\nEXPRTEST(func_asin  , \"asin  ( 1.0)\", std::asin  ( 1.0))\nEXPRTEST(func_asinh , \"asinh ( 1.0)\", std::asinh ( 1.0))\nEXPRTEST(func_atan  , \"atan  ( 1.0)\", std::atan  ( 1.0))\nEXPRTEST(func_atanh , \"atanh ( 0.0)\", std::atanh ( 0.0))\nEXPRTEST(func_cbrt  , \"cbrt  ( 1.0)\", std::cbrt  ( 1.0))\nEXPRTEST(func_ceil  , \"ceil  ( 0.5)\", std::ceil  ( 0.5))\nEXPRTEST(func_cos   , \"cos   ( 1.0)\", std::cos   ( 1.0))\nEXPRTEST(func_cosh  , \"cosh  ( 1.0)\", std::cosh  ( 1.0))\nEXPRTEST(func_erf   , \"erf   ( 1.0)\", std::erf   ( 1.0))\nEXPRTEST(func_erfc  , \"erfc  ( 1.0)\", std::erfc  ( 1.0))\nEXPRTEST(func_exp   , \"exp   ( 1.0)\", std::exp   ( 1.0))\nEXPRTEST(func_exp2  , \"exp2  ( 1.0)\", std::exp2  ( 1.0))\nEXPRTEST(func_floor , \"floor ( 0.5)\", std::floor ( 0.5))\nEXPRTEST(func_log   , \"log   ( 1.0)\", std::log   ( 1.0))\nEXPRTEST(func_log2  , \"log2  ( 1.0)\", std::log2  ( 1.0))\nEXPRTEST(func_log10 , \"log10 ( 1.0)\", std::log10 ( 1.0))\nEXPRTEST(func_round , \"round ( 0.5)\", std::round ( 0.5))\nEXPRTEST(func_sgn   , \"sgn   (-1.0)\",             -1.0 )\nEXPRTEST(func_sin   , \"sin   ( 1.0)\", std::sin   ( 1.0))\nEXPRTEST(func_sinh  , \"sinh  ( 1.0)\", std::sinh  ( 1.0))\nEXPRTEST(func_sqrt  , \"sqrt  ( 1.0)\", std::sqrt  ( 1.0))\nEXPRTEST(func_tan   , \"tan   ( 1.0)\", std::tan   ( 1.0))\nEXPRTEST(func_tanh  , \"tanh  ( 1.0)\", std::tanh  ( 1.0))\nEXPRTEST(func_tgamma, \"tgamma( 4.0)\", std::tgamma( 4.0))\n\nEXPRTEST(func_atan2, \"atan2(2.0, 3.0)\", std::atan2(2.0,3.0))\nEXPRTEST(func_max,   \"max  (2.0, 3.0)\", std::fmax(2.0,3.0))\nEXPRTEST(func_min,   \"min  (2.0, 3.0)\", std::fmin(2.0,3.0))\nEXPRTEST(func_pow,   \"pow  (2.0, 3.0)\", std::pow(2.0,3.0))\n", "meta": {"hexsha": "8af6b50ae8a752f988eeeb208e396f5147a9e318", "size": 1905, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/functions.cpp", "max_stars_repo_name": "fweik/boost_matheval", "max_stars_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/functions.cpp", "max_issues_repo_name": "fweik/boost_matheval", "max_issues_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/functions.cpp", "max_forks_repo_name": "fweik/boost_matheval", "max_forks_repo_head_hexsha": "6e77515ec71ce95fe24b8ced6170fa146e9912ac", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.1315789474, "max_line_length": 60, "alphanum_fraction": 0.5779527559, "num_tokens": 851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6097495469219797}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <pch.hpp> \n\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/test/test_exec_monitor.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/trunc.hpp>\n#include <boost/math/tools/test.hpp>\n#include \"functor.hpp\"\n#include <boost/array.hpp>\n\n#include \"handle_test_result.hpp\"\n\n//\n// DESCRIPTION:\n// ~~~~~~~~~~~~\n//\n// This file tests the function binomial_coefficient<T>.  \n// The accuracy tests\n// use values generated with NTL::RR at 1000-bit precision\n// and our generic versions of these function.\n//\n// Note that when this file is first run on a new platform many of\n// these tests will fail: the default accuracy is 1 epsilon which\n// is too tight for most platforms.  In this situation you will \n// need to cast a human eye over the error rates reported and make\n// a judgement as to whether they are acceptable.  Either way please\n// report the results to the Boost mailing list.  Acceptable rates of\n// error are marked up below as a series of regular expressions that\n// identify the compiler/stdlib/platform/data-type/test-data/test-function\n// along with the maximum expected peek and RMS mean errors for that\n// test.\n//\n\nvoid expected_results()\n{\n   //\n   // Define the max and mean errors expected for\n   // various compilers and platforms.\n   //\n   const char* largest_type;\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())\n   {\n      largest_type = \"(long\\\\s+)?double\";\n   }\n   else\n   {\n      largest_type = \"long double\";\n   }\n#else\n   largest_type = \"(long\\\\s+)?double\";\n#endif\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      largest_type,                  // test type(s)\n      \".*large.*\",                   // test data group\n      \".*\", 100, 20);                 // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \".*large.*\",                   // test data group\n      \".*\", 250, 100);               // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \"real_concept\",                // test type(s)\n      \".*\",                          // test data group\n      \".*\", 150, 30);                 // test function\n   add_expected_result(\n      \".*\",                          // compiler\n      \".*\",                          // stdlib\n      \".*\",                          // platform\n      \".*\",                          // test type(s)\n      \".*\",                          // test data group\n      \".*\", 2, 1);                   // test function\n\n   //\n   // Finish off by printing out the compiler/stdlib/platform names,\n   // we do this to make it easier to mark up expected error rates.\n   //\n   std::cout << \"Tests run with \" << BOOST_COMPILER << \", \" \n      << BOOST_STDLIB << \", \" << BOOST_PLATFORM << std::endl;\n}\n\ntemplate <class T>\nT binomial_wrapper(T n, T k)\n{\n   return boost::math::binomial_coefficient<T>(\n      boost::math::itrunc(n),\n      boost::math::itrunc(k));\n}\n\ntemplate <class T>\nvoid test_binomial(T, const char* type_name)\n{\n   using namespace std;\n\n   typedef T (*func_t)(T, T);\n#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)\n   func_t f = &binomial_wrapper<T>;\n#else\n   func_t f = &binomial_wrapper;\n#endif\n\n#include \"binomial_data.ipp\"\n\n   boost::math::tools::test_result<T> result = boost::math::tools::test(\n      binomial_data, \n      bind_func(f, 0, 1), \n      extract_result(2));\n\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\"\n      \"Test results for small arguments and type \" << type_name << std::endl << std::endl;\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n   handle_test_result(result, binomial_data[result.worst()], result.worst(), type_name, \"binomial_coefficient\", \"Binomials: small arguments\");\n   std::cout << std::endl;\n\n#include \"binomial_large_data.ipp\"\n\n   result = boost::math::tools::test(\n      binomial_large_data, \n      bind_func(f, 0, 1), \n      extract_result(2));\n\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\"\n      \"Test results for large arguments and type \" << type_name << std::endl << std::endl;\n   std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\";\n   handle_test_result(result, binomial_large_data[result.worst()], result.worst(), type_name, \"binomial_coefficient\", \"Binomials: large arguments\");\n   std::cout << std::endl;\n}\n\ntemplate <class T>\nvoid test_spots(T, const char* name)\n{\n   T tolerance = boost::math::tools::epsilon<T>() * 50 * 100;  // 50 eps as a percentage\n   if(!std::numeric_limits<T>::is_specialized)\n      tolerance *= 10;  // beta function not so accurate without lanczos support\n\n   std::cout << \"Testing spot checks for type \" << name << \" with tolerance \" << tolerance << \"%\\n\";\n\n   BOOST_CHECK_EQUAL(boost::math::binomial_coefficient<T>(20, 0), static_cast<T>(1));\n   BOOST_CHECK_EQUAL(boost::math::binomial_coefficient<T>(20, 1), static_cast<T>(20));\n   BOOST_CHECK_EQUAL(boost::math::binomial_coefficient<T>(20, 2), static_cast<T>(190));\n   BOOST_CHECK_EQUAL(boost::math::binomial_coefficient<T>(20, 3), static_cast<T>(1140));\n   BOOST_CHECK_EQUAL(boost::math::binomial_coefficient<T>(20, 20), static_cast<T>(1));\n   BOOST_CHECK_EQUAL(boost::math::binomial_coefficient<T>(20, 19), static_cast<T>(20));\n   BOOST_CHECK_EQUAL(boost::math::binomial_coefficient<T>(20, 18), static_cast<T>(190));\n   BOOST_CHECK_EQUAL(boost::math::binomial_coefficient<T>(20, 17), static_cast<T>(1140));\n   BOOST_CHECK_EQUAL(boost::math::binomial_coefficient<T>(20, 10), static_cast<T>(184756L));\n\n   BOOST_CHECK_CLOSE(boost::math::binomial_coefficient<T>(100, 5), static_cast<T>(7.528752e7L), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::binomial_coefficient<T>(100, 81), static_cast<T>(1.323415729392122674e20L), tolerance);\n\n   BOOST_CHECK_CLOSE(boost::math::binomial_coefficient<T>(300, 3), static_cast<T>(4.45510e6L), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::binomial_coefficient<T>(300, 7), static_cast<T>(4.043855956140000e13L), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::binomial_coefficient<T>(300, 290), static_cast<T>(1.3983202332417017700000000e18L), tolerance);\n   BOOST_CHECK_CLOSE(boost::math::binomial_coefficient<T>(300, 275), static_cast<T>(1.953265141442868389822364184842211512000000e36L), tolerance);\n}\n\nint test_main(int, char* [])\n{\n   expected_results();\n   BOOST_MATH_CONTROL_FP;\n\n   test_spots(1.0F, \"float\");\n   test_spots(1.0, \"double\");\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_spots(1.0L, \"long double\");\n   test_spots(boost::math::concepts::real_concept(), \"real_concept\");\n#endif\n\n   test_binomial(1.0F, \"float\");\n   test_binomial(1.0, \"double\");\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   test_binomial(1.0L, \"long double\");\n#ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS\n   test_binomial(boost::math::concepts::real_concept(), \"real_concept\");\n#endif\n#else\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\n      \"either because the long double overloads of the usual math functions are \"\n      \"not available at all, or because they are too inaccurate for these tests \"\n      \"to pass.</note>\" << std::cout;\n#endif\n   return 0;\n}\n\n\n\n", "meta": {"hexsha": "b946f8039b6eb94c5f09587ad3ff13a82c7b9c37", "size": 7973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/test_binomial_coeff.cpp", "max_stars_repo_name": "oudream/boost_1_42_0", "max_stars_repo_head_hexsha": "e92227bf374e478030e89876ec353de6eecaeac0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/math/test/test_binomial_coeff.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-17T10:11:43.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-17T10:11:43.000Z", "max_forks_repo_path": "libs/math/test/test_binomial_coeff.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 39.6666666667, "max_line_length": 162, "alphanum_fraction": 0.6198419666, "num_tokens": 2016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.6097077282289545}}
{"text": "#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nint main(int argc, char **argv) \n{\n  // exploit namespaces to shorten code\n  using namespace boost::numeric::ublas;\n  using std::cout; \n  using std::endl;\n\n  // declare three 3x3 matrices of complex<long double> elements\n  matrix<std::complex<long double> > m(11, 11);\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        int a = r -5;\n        int b = c - 5;\n      m(r,c) =  a + b * 1i;\n\n    }\n  }\n\n  // print to screen as demonstration\n  cout << \"m:\" << endl;\n  cout << m << endl;\n\n    /*\n  cout << endl << \"n:\" << endl;\n  cout << n << endl;\n  cout << endl << \"o:\" << endl;\n  cout << o << 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}\n", "meta": {"hexsha": "1801dca895a81c14d08893bdb0573a95c86fdd64", "size": 969, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/blas/new_matrix.cc", "max_stars_repo_name": "chapman-cs510-2016f/cw-13-datacats", "max_stars_repo_head_hexsha": "882a9942f8311fa10998065010086e4ee1d9a747", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/blas/new_matrix.cc", "max_issues_repo_name": "chapman-cs510-2016f/cw-13-datacats", "max_issues_repo_head_hexsha": "882a9942f8311fa10998065010086e4ee1d9a747", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/blas/new_matrix.cc", "max_forks_repo_name": "chapman-cs510-2016f/cw-13-datacats", "max_forks_repo_head_hexsha": "882a9942f8311fa10998065010086e4ee1d9a747", "max_forks_repo_licenses": ["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.6341463415, "max_line_length": 64, "alphanum_fraction": 0.5407636739, "num_tokens": 309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.6096436295262042}}
{"text": "#include <Eigen/Eigen>\n#include <gtest/gtest.h>\n#include <torch/Torch.h>\n\nusing namespace torch;\n\nconst float epsilon = 1E-4;\n\nEigen::Matrix4f GetRotationMatrix(const Vector& rotation)\n{\n  const Eigen::Quaternionf quaternion =\n      Eigen::AngleAxisf(rotation.x, Eigen::Vector3f::UnitX()) *\n      Eigen::AngleAxisf(rotation.y, Eigen::Vector3f::UnitY()) *\n      Eigen::AngleAxisf(rotation.z, Eigen::Vector3f::UnitZ());\n\n  Eigen::Matrix4f result(Eigen::Matrix4f::Identity());\n  result.block<3, 3>(0, 0) = Eigen::Matrix3f(quaternion);\n  return result;\n}\n\nconst Eigen::Matrix4f GetRotationMatrix(const optix::Matrix4x4& rotation)\n{\n  typedef Eigen::Matrix<float, 4, 4, Eigen::RowMajor> RowMatrix;\n  return Eigen::Map<const RowMatrix>(rotation.getData());\n}\n\nTEST(Transform, Translation)\n{\n  Transform transform;\n  Vector expected;\n  Vector found;\n\n  expected = Vector(0, 0, 0);\n  found = transform.GetTranslation();\n  ASSERT_NEAR(expected.x, found.x, epsilon);\n  ASSERT_NEAR(expected.y, found.y, epsilon);\n  ASSERT_NEAR(expected.z, found.z, epsilon);\n\n  expected = Vector(1, 2, 3);\n  transform.SetTranslation(expected);\n  found = transform.GetTranslation();\n  ASSERT_NEAR(expected.x, found.x, epsilon);\n  ASSERT_NEAR(expected.y, found.y, epsilon);\n  ASSERT_NEAR(expected.z, found.z, epsilon);\n\n  expected = Vector(0, -1, 2);\n  transform.SetTranslation(expected);\n  found = transform.GetTranslation();\n  ASSERT_NEAR(expected.x, found.x, epsilon);\n  ASSERT_NEAR(expected.y, found.y, epsilon);\n  ASSERT_NEAR(expected.z, found.z, epsilon);\n\n  expected = Vector(0, 0, 0);\n  transform.SetTranslation(expected);\n  found = transform.GetTranslation();\n  ASSERT_NEAR(expected.x, found.x, epsilon);\n  ASSERT_NEAR(expected.y, found.y, epsilon);\n  ASSERT_NEAR(expected.z, found.z, epsilon);\n}\n\nTEST(Transform, Rotation)\n{\n  Transform transform;\n  Eigen::Matrix4f expected;\n  Eigen::Matrix4f found;\n  Vector rotation;\n\n  rotation = Vector(0, 0, 0);\n  expected = GetRotationMatrix(rotation);\n  found = GetRotationMatrix(transform.GetRotationMatrix());\n\n  for (unsigned int i = 0; i < 16; ++i)\n  {\n    ASSERT_NEAR(expected.data()[i], found.data()[i], epsilon);\n  }\n\n  rotation = Vector(0.5, 0, 0);\n  transform.SetRotation(rotation);\n  expected = GetRotationMatrix(rotation);\n  found = GetRotationMatrix(transform.GetRotationMatrix());\n\n  for (unsigned int i = 0; i < 16; ++i)\n  {\n    ASSERT_NEAR(expected.data()[i], found.data()[i], epsilon);\n  }\n\n  rotation = Vector(0, 0.5, 0);\n  transform.SetRotation(rotation);\n  expected = GetRotationMatrix(rotation);\n  found = GetRotationMatrix(transform.GetRotationMatrix());\n\n  for (unsigned int i = 0; i < 16; ++i)\n  {\n    ASSERT_NEAR(expected.data()[i], found.data()[i], epsilon);\n  }\n\n  rotation = Vector(0, 0, 0.5);\n  transform.SetRotation(rotation);\n  expected = GetRotationMatrix(rotation);\n  found = GetRotationMatrix(transform.GetRotationMatrix());\n\n  for (unsigned int i = 0; i < 16; ++i)\n  {\n    ASSERT_NEAR(expected.data()[i], found.data()[i], epsilon);\n  }\n\n  rotation = Vector(0.1, 0.2, 0.3);\n  transform.SetRotation(rotation);\n  expected = GetRotationMatrix(rotation);\n  found = GetRotationMatrix(transform.GetRotationMatrix());\n\n  for (unsigned int i = 0; i < 16; ++i)\n  {\n    ASSERT_NEAR(expected.data()[i], found.data()[i], epsilon);\n  }\n\n  rotation = Vector(1, 2, 3);\n  transform.SetRotation(rotation);\n  expected = GetRotationMatrix(rotation);\n  found = GetRotationMatrix(transform.GetRotationMatrix());\n\n  for (unsigned int i = 0; i < 16; ++i)\n  {\n    ASSERT_NEAR(expected.data()[i], found.data()[i], epsilon);\n  }\n\n  rotation = Vector(-1, 2, -3);\n  transform.SetRotation(rotation);\n  expected = GetRotationMatrix(rotation);\n  found = GetRotationMatrix(transform.GetRotationMatrix());\n\n  for (unsigned int i = 0; i < 16; ++i)\n  {\n    ASSERT_NEAR(expected.data()[i], found.data()[i], epsilon);\n  }\n\n  rotation = Vector(0.1, 0.2, 0.3);\n  transform.SetScale(1, 2, 3);\n  transform.SetRotation(rotation);\n  expected = GetRotationMatrix(rotation);\n  found = GetRotationMatrix(transform.GetRotationMatrix());\n\n  for (unsigned int i = 0; i < 16; ++i)\n  {\n    ASSERT_NEAR(expected.data()[i], found.data()[i], epsilon);\n  }\n\n  rotation = Vector(-1, 2, -3);\n  transform.SetScale(0.1, 0.2, 0.3);\n  transform.SetRotation(rotation);\n  expected = GetRotationMatrix(rotation);\n  found = GetRotationMatrix(transform.GetRotationMatrix());\n\n  for (unsigned int i = 0; i < 16; ++i)\n  {\n    ASSERT_NEAR(expected.data()[i], found.data()[i], epsilon);\n  }\n}\n\nTEST(Transform, Scale)\n{\n  Transform transform;\n  Vector expected;\n  Vector found;\n\n  expected = Vector(1, 1, 1);\n  found = transform.GetScale();\n  ASSERT_NEAR(expected.x, found.x, epsilon);\n  ASSERT_NEAR(expected.y, found.y, epsilon);\n  ASSERT_NEAR(expected.z, found.z, epsilon);\n\n  expected = Vector(1, 2, 3);\n  transform.SetScale(expected);\n  found = transform.GetScale();\n  ASSERT_NEAR(expected.x, found.x, epsilon);\n  ASSERT_NEAR(expected.y, found.y, epsilon);\n  ASSERT_NEAR(expected.z, found.z, epsilon);\n\n  expected = Vector(2, 2, 2);\n  transform.SetScale(expected);\n  found = transform.GetScale();\n  ASSERT_NEAR(expected.x, found.x, epsilon);\n  ASSERT_NEAR(expected.y, found.y, epsilon);\n  ASSERT_NEAR(expected.z, found.z, epsilon);\n\n  expected = Vector(0.1, 0.2, 0.3);\n  transform.SetScale(expected);\n  found = transform.GetScale();\n  ASSERT_NEAR(expected.x, found.x, epsilon);\n  ASSERT_NEAR(expected.y, found.y, epsilon);\n  ASSERT_NEAR(expected.z, found.z, epsilon);\n\n  transform.SetRotation(0.1, 0.2, 0.3);\n  expected = Vector(0.1, 0.2, 0.3);\n  transform.SetScale(expected);\n  found = transform.GetScale();\n  ASSERT_NEAR(expected.x, found.x, epsilon);\n  ASSERT_NEAR(expected.y, found.y, epsilon);\n  ASSERT_NEAR(expected.z, found.z, epsilon);\n\n  transform.SetRotation(0.3, 0.2, 0.1);\n  expected = Vector(1, 2, 3);\n  transform.SetScale(expected);\n  found = transform.GetScale();\n  ASSERT_NEAR(expected.x, found.x, epsilon);\n  ASSERT_NEAR(expected.y, found.y, epsilon);\n  ASSERT_NEAR(expected.z, found.z, epsilon);\n}", "meta": {"hexsha": "3fa12f3fac6c0540897ed2167d02a03b03bc24db", "size": 6002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Transform.cpp", "max_stars_repo_name": "arpg/torch", "max_stars_repo_head_hexsha": "601ec64854008d97e39d2ca86ef4a93f79930967", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-05-29T03:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-29T03:08:54.000Z", "max_issues_repo_path": "tests/Transform.cpp", "max_issues_repo_name": "arpg/torch", "max_issues_repo_head_hexsha": "601ec64854008d97e39d2ca86ef4a93f79930967", "max_issues_repo_licenses": ["Apache-2.0"], "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/Transform.cpp", "max_forks_repo_name": "arpg/torch", "max_forks_repo_head_hexsha": "601ec64854008d97e39d2ca86ef4a93f79930967", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-07-24T11:58:52.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-24T11:58:52.000Z", "avg_line_length": 28.8557692308, "max_line_length": 73, "alphanum_fraction": 0.6909363545, "num_tokens": 1626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.6096436181143641}}
{"text": "#include \"stdafx.h\"\n#include \"Calibration.h\"\n#include \"Configuration.h\"\n#include \"IPCClient.h\"\n\n#include <string>\n#include <vector>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n\nstatic IPCClient Driver;\nCalibrationContext CalCtx;\nCalibrationState LastState = CalibrationState::None;\nEigen::Vector3d ReferenceTranslation;\nEigen::Vector3d ReferenceRotation;\n\nvoid InitCalibrator()\n{\n\tDriver.Connect();\n}\n\nstruct Pose\n{\n\tEigen::Matrix3d rot;\n\tEigen::Vector3d trans;\n\n\tPose() { }\n\tPose(vr::HmdMatrix34_t hmdMatrix)\n\t{\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tfor (int j = 0; j < 3; j++) {\n\t\t\t\trot(i,j) = hmdMatrix.m[i][j];\n\t\t\t}\n\t\t}\n\t\ttrans = Eigen::Vector3d(hmdMatrix.m[0][3], hmdMatrix.m[1][3], hmdMatrix.m[2][3]);\n\t}\n\tPose(double x, double y, double z) : trans(Eigen::Vector3d(x,y,z)) { }\n};\n\nPose ReferencePose;\n\nstruct Sample\n{\n\tPose ref, target;\n\tbool valid;\n\tSample() : valid(false) { }\n\tSample(Pose ref, Pose target) : valid(true), ref(ref), target(target) { }\n};\n\nstruct DSample\n{\n\tbool valid;\n\tEigen::Vector3d ref, target;\n};\n\nbool StartsWith(const std::string &str, const std::string &prefix)\n{\n\tif (str.length() < prefix.length())\n\t\treturn false;\n\n\treturn str.compare(0, prefix.length(), prefix) == 0;\n}\n\nbool EndsWith(const std::string &str, const std::string &suffix)\n{\n\tif (str.length() < suffix.length())\n\t\treturn false;\n\n\treturn str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;\n}\n\nEigen::Vector3d AxisFromRotationMatrix3(Eigen::Matrix3d rot)\n{\n\treturn Eigen::Vector3d(rot(2,1) - rot(1,2), rot(0,2) - rot(2,0), rot(1,0) - rot(0,1));\n}\n\ndouble AngleFromRotationMatrix3(Eigen::Matrix3d rot)\n{\n\treturn acos((rot(0,0) + rot(1,1) + rot(2,2) - 1.0) / 2.0);\n}\n\nDSample DeltaRotationSamples(Sample s1, Sample s2)\n{\n\t// Difference in rotation between samples.\n\tauto dref = s1.ref.rot * s2.ref.rot.transpose();\n\tauto dtarget = s1.target.rot * s2.target.rot.transpose();\n\n\t// When stuck together, the two tracked objects rotate as a pair,\n\t// therefore their axes of rotation must be equal between any given pair of samples.\n\tDSample ds;\n\tds.ref = AxisFromRotationMatrix3(dref);\n\tds.target = AxisFromRotationMatrix3(dtarget);\n\n\t// Reject samples that were too close to each other.\n\tauto refA = AngleFromRotationMatrix3(dref);\n\tauto targetA = AngleFromRotationMatrix3(dtarget);\n\tds.valid = refA > 0.4 && targetA > 0.4 && ds.ref.norm() > 0.01 && ds.target.norm() > 0.01;\n\n\tds.ref.normalize();\n\tds.target.normalize();\n\treturn ds;\n}\n\nEigen::Vector3d CalibrateRotation(const std::vector<Sample> &samples)\n{\n\tstd::vector<DSample> deltas;\n\n\tfor (size_t i = 0; i < samples.size(); i++)\n\t{\n\t\tfor (size_t j = 0; j < i; j++)\n\t\t{\n\t\t\tauto delta = DeltaRotationSamples(samples[i], samples[j]);\n\t\t\tif (delta.valid)\n\t\t\t\tdeltas.push_back(delta);\n\t\t}\n\t}\n\tchar buf[256];\n\tsnprintf(buf, sizeof buf, \"Got %zd samples with %zd delta samples\\n\", samples.size(), deltas.size());\n\tCalCtx.Log(buf);\n\n\t// Kabsch algorithm\n\n\tEigen::MatrixXd refPoints(deltas.size(), 3), targetPoints(deltas.size(), 3);\n\tEigen::Vector3d refCentroid(0,0,0), targetCentroid(0,0,0);\n\n\tfor (size_t i = 0; i < deltas.size(); i++)\n\t{\n\t\trefPoints.row(i) = deltas[i].ref;\n\t\trefCentroid += deltas[i].ref;\n\n\t\ttargetPoints.row(i) = deltas[i].target;\n\t\ttargetCentroid += deltas[i].target;\n\t}\n\n\trefCentroid /= (double) deltas.size();\n\ttargetCentroid /= (double) deltas.size();\n\n\tfor (size_t i = 0; i < deltas.size(); i++)\n\t{\n\t\trefPoints.row(i) -= refCentroid;\n\t\ttargetPoints.row(i) -= targetCentroid;\n\t}\n\n\tauto crossCV = refPoints.transpose() * targetPoints;\n\n\tEigen::BDCSVD<Eigen::MatrixXd> bdcsvd;\n\tauto svd = bdcsvd.compute(crossCV, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n\tEigen::Matrix3d i = Eigen::Matrix3d::Identity();\n\tif ((svd.matrixU() * svd.matrixV().transpose()).determinant() < 0)\n\t{\n\t\ti(2,2) = -1;\n\t}\n\n\tEigen::Matrix3d rot = svd.matrixV() * i * svd.matrixU().transpose();\n\trot.transposeInPlace();\n\n\tEigen::Vector3d euler = rot.eulerAngles(2, 1, 0) * 180.0 / EIGEN_PI;\n\n\tsnprintf(buf, sizeof buf, \"Calibrated rotation: yaw=%.2f pitch=%.2f roll=%.2f\\n\", euler[1], euler[2], euler[0]);\n\tCalCtx.Log(buf);\n\treturn euler;\n}\n\nEigen::Vector3d CalibrateTranslation(const std::vector<Sample> &samples)\n{\n\tstd::vector<std::pair<Eigen::Vector3d, Eigen::Matrix3d>> deltas;\n\n\tfor (size_t i = 0; i < samples.size(); i++)\n\t{\n\t\tfor (size_t j = 0; j < i; j++)\n\t\t{\n\t\t\tauto QAi = samples[i].ref.rot.transpose();\n\t\t\tauto QAj = samples[j].ref.rot.transpose();\n\t\t\tauto dQA = QAj - QAi;\n\t\t\tauto CA = QAj * (samples[j].ref.trans - samples[j].target.trans) - QAi * (samples[i].ref.trans - samples[i].target.trans);\n\t\t\tdeltas.push_back(std::make_pair(CA, dQA));\n\n\t\t\tauto QBi = samples[i].target.rot.transpose();\n\t\t\tauto QBj = samples[j].target.rot.transpose();\n\t\t\tauto dQB = QBj - QBi;\n\t\t\tauto CB = QBj * (samples[j].ref.trans - samples[j].target.trans) - QBi * (samples[i].ref.trans - samples[i].target.trans);\n\t\t\tdeltas.push_back(std::make_pair(CB, dQB));\n\t\t}\n\t}\n\n\tEigen::VectorXd constants(deltas.size() * 3);\n\tEigen::MatrixXd coefficients(deltas.size() * 3, 3);\n\n\tfor (size_t i = 0; i < deltas.size(); i++)\n\t{\n\t\tfor (int axis = 0; axis < 3; axis++)\n\t\t{\n\t\t\tconstants(i * 3 + axis) = deltas[i].first(axis);\n\t\t\tcoefficients.row(i * 3 + axis) = deltas[i].second.row(axis);\n\t\t}\n\t}\n\n\tEigen::Vector3d trans = coefficients.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(constants);\n\tauto transcm = trans * 100.0;\n\n\tchar buf[256];\n\tsnprintf(buf, sizeof buf, \"Calibrated translation x=%.2f y=%.2f z=%.2f\\n\", transcm[0], transcm[1], transcm[2]);\n\tCalCtx.Log(buf);\n\treturn transcm;\n}\n\nSample CollectSample(const CalibrationContext &ctx)\n{\n\tvr::TrackedDevicePose_t reference, target;\n\treference.bPoseIsValid = false;\n\ttarget.bPoseIsValid = false;\n\n\treference = ctx.devicePoses[ctx.referenceID];\n\ttarget = ctx.devicePoses[ctx.targetID];\n\n\tbool ok = true;\n\tif (!reference.bPoseIsValid)\n\t{\n\t\tCalCtx.Log(\"Reference device is not tracking\\n\"); ok = false;\n\t}\n\tif (!target.bPoseIsValid)\n\t{\n\t\tCalCtx.Log(\"Target device is not tracking\\n\"); ok = false;\n\t}\n\tif (!ok)\n\t{\n\t\tCalCtx.Log(\"Aborting calibration!\\n\");\n\t\tCalCtx.state = CalibrationState::None;\n\t\treturn Sample();\n\t}\n\n\treturn Sample(\n\t\tPose(reference.mDeviceToAbsoluteTracking),\n\t\tPose(target.mDeviceToAbsoluteTracking)\n\t);\n}\n\nvr::HmdQuaternion_t VRRotationQuat(Eigen::Vector3d eulerdeg)\n{\n\tauto euler = eulerdeg * EIGEN_PI / 180.0;\n\n\tEigen::Quaterniond rotQuat =\n\t\tEigen::AngleAxisd(euler(0), Eigen::Vector3d::UnitZ()) *\n\t\tEigen::AngleAxisd(euler(1), Eigen::Vector3d::UnitY()) *\n\t\tEigen::AngleAxisd(euler(2), Eigen::Vector3d::UnitX());\n\n\tvr::HmdQuaternion_t vrRotQuat;\n\tvrRotQuat.x = rotQuat.coeffs()[0];\n\tvrRotQuat.y = rotQuat.coeffs()[1];\n\tvrRotQuat.z = rotQuat.coeffs()[2];\n\tvrRotQuat.w = rotQuat.coeffs()[3];\n\treturn vrRotQuat;\n}\n\nvr::HmdVector3d_t VRTranslationVec(Eigen::Vector3d transcm)\n{\n\tauto trans = transcm * 0.01;\n\tvr::HmdVector3d_t vrTrans;\n\tvrTrans.v[0] = trans[0];\n\tvrTrans.v[1] = trans[1];\n\tvrTrans.v[2] = trans[2];\n\treturn vrTrans;\n}\n\nvoid ResetAndDisableOffsets(uint32_t id)\n{\n\tvr::HmdVector3d_t zeroV;\n\tzeroV.v[0] = zeroV.v[1] = zeroV.v[2] = 0;\n\n\tvr::HmdQuaternion_t zeroQ;\n\tzeroQ.x = 0; zeroQ.y = 0; zeroQ.z = 0; zeroQ.w = 1;\n\n\tprotocol::Request req(protocol::RequestSetDeviceTransform);\n\treq.setDeviceTransform = { id, false, zeroV, zeroQ };\n\tDriver.SendBlocking(req);\n}\n\nstatic_assert(vr::k_unTrackedDeviceIndex_Hmd == 0, \"HMD index expected to be 0\");\n\nvoid ScanAndApplyProfile(CalibrationContext &ctx)\n{\n\tchar buffer[vr::k_unMaxPropertyStringSize];\n\tctx.enabled = ctx.validProfile;\n\n\tfor (uint32_t id = 0; id < vr::k_unMaxTrackedDeviceCount; ++id)\n\t{\n\t\tauto deviceClass = vr::VRSystem()->GetTrackedDeviceClass(id);\n\t\tif (deviceClass == vr::TrackedDeviceClass_Invalid)\n\t\t\tcontinue;\n\n\t\t/*if (deviceClass == vr::TrackedDeviceClass_HMD) // for debugging unexpected universe switches\n\t\t{\n\t\t\tvr::ETrackedPropertyError err = vr::TrackedProp_Success;\n\t\t\tauto universeId = vr::VRSystem()->GetUint64TrackedDeviceProperty(id, vr::Prop_CurrentUniverseId_Uint64, &err);\n\t\t\tprintf(\"uid %d err %d\\n\", universeId, err);\n\t\t\tResetAndDisableOffsets(id);\n\t\t\tcontinue;\n\t\t}*/\n\n\t\tif (!ctx.enabled)\n\t\t{\n\t\t\tResetAndDisableOffsets(id);\n\t\t\tcontinue;\n\t\t}\n\n\t\tvr::ETrackedPropertyError err = vr::TrackedProp_Success;\n\t\tvr::VRSystem()->GetStringTrackedDeviceProperty(id, vr::Prop_TrackingSystemName_String, buffer, vr::k_unMaxPropertyStringSize, &err);\n\n\t\tif (err != vr::TrackedProp_Success)\n\t\t{\n\t\t\tResetAndDisableOffsets(id);\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::string trackingSystem(buffer);\n\n\t\tif (id == vr::k_unTrackedDeviceIndex_Hmd)\n\t\t{\n\t\t\t//auto p = ctx.devicePoses[id].mDeviceToAbsoluteTracking.m;\n\t\t\t//printf(\"HMD %d: %f %f %f\\n\", id, p[0][3], p[1][3], p[2][3]);\n\n\t\t\tif (trackingSystem != ctx.referenceTrackingSystem)\n\t\t\t{\n\t\t\t\t// Currently using an HMD with a different tracking system than the calibration.\n\t\t\t\tctx.enabled = false;\n\t\t\t}\n\n\t\t\tResetAndDisableOffsets(id);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (trackingSystem != ctx.targetTrackingSystem)\n\t\t{\n\t\t\tResetAndDisableOffsets(id);\n\t\t\tcontinue;\n\t\t}\n\n\t\tprotocol::Request req(protocol::RequestSetDeviceTransform);\n\t\treq.setDeviceTransform = {\n\t\t\tid,\n\t\t\ttrue,\n\t\t\tVRTranslationVec(ctx.calibratedTranslation),\n\t\t\tVRRotationQuat(ctx.calibratedRotation)\n\t\t};\n\t\tDriver.SendBlocking(req);\n\t}\n\n\tif (ctx.enabled && ctx.chaperone.valid && ctx.chaperone.autoApply)\n\t{\n\t\tuint32_t quadCount = 0;\n\t\tvr::VRChaperoneSetup()->GetLiveCollisionBoundsInfo(nullptr, &quadCount);\n\n\t\t// Heuristic: when SteamVR resets to a blank-ish chaperone, it uses empty geometry,\n\t\t// but manual adjustments (e.g. via a play space mover) will not touch geometry.\n\t\tif (quadCount != ctx.chaperone.geometry.size())\n\t\t{\n\t\t\tApplyChaperoneBounds();\n\t\t}\n\t}\n}\n\nvoid StartCalibration()\n{\n\tCalCtx.state = CalibrationState::Begin;\n\tCalCtx.wantedUpdateInterval = 0.0;\n\tCalCtx.messages.clear();\n}\n\nvoid SetReferenceOffset() {\n\tauto &ctx = CalCtx;\n\tPose pose(ctx.devicePoses[ctx.referenceID].mDeviceToAbsoluteTracking);\n\tReferencePose = pose;\n\tReferenceTranslation = ctx.calibratedTranslation;\n\tReferenceRotation = ctx.calibratedRotation;\n}\n\nvoid CalibrationTick(double time)\n{\n\tif (!vr::VRSystem())\n\t\treturn;\n\n\tauto &ctx = CalCtx;\n\tif ((time - ctx.timeLastTick) < 0.05)\n\t\treturn;\n\n\tctx.timeLastTick = time;\n\tvr::VRSystem()->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseRawAndUncalibrated, 0.0f, ctx.devicePoses, vr::k_unMaxTrackedDeviceCount);\n\n\tif (ctx.state == CalibrationState::None)\n\t{\n\t\tctx.wantedUpdateInterval = 1.0;\n\n\t\tif ((time - ctx.timeLastScan) >= 1.0)\n\t\t{\n\t\t\tScanAndApplyProfile(ctx);\n\t\t\tctx.timeLastScan = time;\n\t\t}\n\t\treturn;\n\t}\n\n\tif (ctx.state == CalibrationState::Editing)\n\t{\n\t\tctx.wantedUpdateInterval = 0.1;\n\n\t\tif ((time - ctx.timeLastScan) >= 0.1)\n\t\t{\n\t\t\tScanAndApplyProfile(ctx);\n\t\t\tctx.timeLastScan = time;\n\t\t}\n\t\treturn;\n\t}\n\n\tif (ctx.state == CalibrationState::Referencing)\n\t{\n\t\tPose pose(ctx.devicePoses[ctx.referenceID].mDeviceToAbsoluteTracking);\n\t\tEigen::Vector3d deltaTrans = pose.trans - ReferencePose.trans;\n\t\tctx.calibratedTranslation = (ReferenceTranslation + (deltaTrans * 100));\n\n\t\t// Attempt # 1, getting teh euler delta and adding it to the original reference rotation - does not work.\n\t\t//auto rotation = pose.rot.eulerAngles(2, 1, 0) * 180.0 / EIGEN_PI;\n\t\t/*ctx.calibratedRotation[0] = ReferenceRotation(0) + rotation(0);\n\t\tctx.calibratedRotation[1] = ReferenceRotation(1) + rotation(1);\n\t\tctx.calibratedRotation[2] = ReferenceRotation(2) + rotation(2);*/\n\t\t//ctx.calibratedRotation[0] = rotation(0);\n\t\t//ctx.calibratedRotation[1] = rotation(1);\n\t\t//ctx.calibratedRotation[2] = rotation(2);\n\n\n\t\t// Attempt #2, convert it all to quaternions ?? didnt get far with this one.\n\t\t/*Eigen::Quaterniond currentQuat =\n\t\t\tEigen::AngleAxisd(ctx.calibratedRotation(0), Eigen::Vector3d::UnitZ()) *\n\t\t\tEigen::AngleAxisd(ctx.calibratedRotation(1), Eigen::Vector3d::UnitY()) *\n\t\t\tEigen::AngleAxisd(ctx.calibratedRotation(2), Eigen::Vector3d::UnitX());\n\t\tEigen::Matrix3d deltaRot = pose.rot - ReferencePose.rot;\n\t\tEigen::Quaternionf delta(deltaRot);\n\t\tvr::HmdQuaternion_t deltaQuat;\n\t\tdeltaQuat.x = delta.coeffs()[0];\n\t\tdeltaQuat.y = delta.coeffs()[1];\n\t\tdeltaQuat.z = delta.coeffs()[2];\n\t\tdeltaQuat.w = delta.coeffs()[3];*/\n\t\t//currentQuat.normalize();\n\t\t// Eigen::Matrix3d updatedRot = currentQuat.toRotationMatrix() + deltaRot;\n\n\n\t\tctx.wantedUpdateInterval = 0.025;\n\n\t\tif ((time - ctx.timeLastScan) >= 0.025)\n\t\t{\n\t\t\tScanAndApplyProfile(ctx);\n\t\t\tctx.timeLastScan = time;\n\t\t}\n\t\treturn;\n\t}\n\tLastState = ctx.state;\n\n\tif (ctx.state == CalibrationState::Begin)\n\t{\n\t\tbool ok = true;\n\n\t\tchar referenceSerial[256], targetSerial[256];\n\t\tvr::VRSystem()->GetStringTrackedDeviceProperty(ctx.referenceID, vr::Prop_SerialNumber_String, referenceSerial, 256);\n\t\tvr::VRSystem()->GetStringTrackedDeviceProperty(ctx.targetID, vr::Prop_SerialNumber_String, targetSerial, 256);\n\n\t\tchar buf[256];\n\t\tsnprintf(buf, sizeof buf, \"Reference device ID: %d, serial: %s\\n\", ctx.referenceID, referenceSerial);\n\t\tCalCtx.Log(buf);\n\t\tsnprintf(buf, sizeof buf, \"Target device ID: %d, serial %s\\n\", ctx.targetID, targetSerial);\n\t\tCalCtx.Log(buf);\n\n\t\tif (ctx.referenceID == -1)\n\t\t{\n\t\t\tCalCtx.Log(\"Missing reference device\\n\"); ok = false;\n\t\t}\n\t\telse if (!ctx.devicePoses[ctx.referenceID].bPoseIsValid)\n\t\t{\n\t\t\tCalCtx.Log(\"Reference device is not tracking\\n\"); ok = false;\n\t\t}\n\n\t\tif (ctx.targetID == -1)\n\t\t{\n\t\t\tCalCtx.Log(\"Missing target device\\n\"); ok = false;\n\t\t}\n\t\telse if (!ctx.devicePoses[ctx.targetID].bPoseIsValid)\n\t\t{\n\t\t\tCalCtx.Log(\"Target device is not tracking\\n\"); ok = false;\n\t\t}\n\n\t\tif (!ok)\n\t\t{\n\t\t\tctx.state = CalibrationState::None;\n\t\t\tCalCtx.Log(\"Aborting calibration!\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tResetAndDisableOffsets(ctx.targetID);\n\t\tctx.state = CalibrationState::Rotation;\n\t\tctx.wantedUpdateInterval = 0.0;\n\n\t\tCalCtx.Log(\"Starting calibration...\\n\");\n\t\treturn;\n\t}\n\n\tauto sample = CollectSample(ctx);\n\tif (!sample.valid)\n\t{\n\t\treturn;\n\t}\n\n\tstatic std::vector<Sample> samples;\n\tsamples.push_back(sample);\n\n\tCalCtx.Progress(samples.size(), CalCtx.SampleCount());\n\n\tif (samples.size() == CalCtx.SampleCount())\n\t{\n\t\tCalCtx.Log(\"\\n\");\n\t\tif (ctx.state == CalibrationState::Rotation)\n\t\t{\n\t\t\tctx.calibratedRotation = CalibrateRotation(samples);\n\n\t\t\tauto vrRotQuat = VRRotationQuat(ctx.calibratedRotation);\n\n\t\t\tprotocol::Request req(protocol::RequestSetDeviceTransform);\n\t\t\treq.setDeviceTransform = { ctx.targetID, true, vrRotQuat };\n\t\t\tDriver.SendBlocking(req);\n\n\t\t\tctx.state = CalibrationState::Translation;\n\t\t}\n\t\telse if (ctx.state == CalibrationState::Translation)\n\t\t{\n\t\t\tctx.calibratedTranslation = CalibrateTranslation(samples);\n\n\t\t\tauto vrTrans = VRTranslationVec(ctx.calibratedTranslation);\n\n\t\t\tprotocol::Request req(protocol::RequestSetDeviceTransform);\n\t\t\treq.setDeviceTransform = { ctx.targetID, true, vrTrans };\n\t\t\tDriver.SendBlocking(req);\n\n\t\t\tctx.validProfile = true;\n\t\t\tSaveProfile(ctx);\n\t\t\tCalCtx.Log(\"Finished calibration, profile saved\\n\");\n\n\t\t\tctx.state = CalibrationState::None;\n\t\t}\n\n\t\tsamples.clear();\n\t}\n}\n\nvoid LoadChaperoneBounds()\n{\n\tvr::VRChaperoneSetup()->RevertWorkingCopy();\n\n\tuint32_t quadCount = 0;\n\tvr::VRChaperoneSetup()->GetLiveCollisionBoundsInfo(nullptr, &quadCount);\n\n\tCalCtx.chaperone.geometry.resize(quadCount);\n\tvr::VRChaperoneSetup()->GetLiveCollisionBoundsInfo(&CalCtx.chaperone.geometry[0], &quadCount);\n\tvr::VRChaperoneSetup()->GetWorkingStandingZeroPoseToRawTrackingPose(&CalCtx.chaperone.standingCenter);\n\tvr::VRChaperoneSetup()->GetWorkingPlayAreaSize(&CalCtx.chaperone.playSpaceSize.v[0], &CalCtx.chaperone.playSpaceSize.v[1]);\n\tCalCtx.chaperone.valid = true;\n}\n\nvoid ApplyChaperoneBounds()\n{\n\tvr::VRChaperoneSetup()->RevertWorkingCopy();\n\tvr::VRChaperoneSetup()->SetWorkingCollisionBoundsInfo(&CalCtx.chaperone.geometry[0], CalCtx.chaperone.geometry.size());\n\tvr::VRChaperoneSetup()->SetWorkingStandingZeroPoseToRawTrackingPose(&CalCtx.chaperone.standingCenter);\n\tvr::VRChaperoneSetup()->SetWorkingPlayAreaSize(CalCtx.chaperone.playSpaceSize.v[0], CalCtx.chaperone.playSpaceSize.v[1]);\n\tvr::VRChaperoneSetup()->CommitWorkingCopy(vr::EChaperoneConfigFile_Live);\n}\n", "meta": {"hexsha": "c8e017ca122aa94a7e0b72f0da26c2b29bf07a81", "size": 15991, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OpenVR-SpaceCalibrator/Calibration.cpp", "max_stars_repo_name": "sidequestlegend/OpenVR-SpaceCalibrator", "max_stars_repo_head_hexsha": "439aff9a5a21a679df0bbb36ed2ee2e4dd3b236e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "OpenVR-SpaceCalibrator/Calibration.cpp", "max_issues_repo_name": "sidequestlegend/OpenVR-SpaceCalibrator", "max_issues_repo_head_hexsha": "439aff9a5a21a679df0bbb36ed2ee2e4dd3b236e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OpenVR-SpaceCalibrator/Calibration.cpp", "max_forks_repo_name": "sidequestlegend/OpenVR-SpaceCalibrator", "max_forks_repo_head_hexsha": "439aff9a5a21a679df0bbb36ed2ee2e4dd3b236e", "max_forks_repo_licenses": ["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.8104347826, "max_line_length": 143, "alphanum_fraction": 0.7009567882, "num_tokens": 4791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.609643614072127}}
{"text": "#pragma once\n#include <functional>\n#include <random>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n\nnamespace filter_bay\n{\n/*!\nSimplifies drawing from a multivariant normal distribution.\n*/\nclass NormalSampler\n{\n  // Drawing from multivariate normal distribution:\n  // https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Drawing_values_from_the_distribution\n  // Sample by projecting standard normal distributed values with L, where\n  // L L^T = covarianc\npublic:\n  // typedef Eigen::Matrix<double, dim, dim> MatrixDim;\n  // typedef Eigen::Matrix<double, dim, 1> VectorDim;\n\n  /*!\n  Create the sampler using a random_device to create the seed.\n  */\n  NormalSampler()\n  {\n    std::random_device random_device;\n    uniform_generator = std::mt19937(random_device());\n  }\n\n  /*!\n  Create the sampler via a seed. For testing it should always be the same seed.\n  In real world use the random_device class to generate the seed.\n  */\n  NormalSampler(unsigned int seed) : uniform_generator(seed) {}\n\n  /*!\n  Samples a random vector from a normal distribution using a robust \n  decomposition algorithm.\n  \\param mean the mean of the distribution\n  \\param covariance the covariance of the distribution\n  */\n  template <typename scalar, int dim>\n  auto sample_robust(const Eigen::Matrix<scalar, dim, 1> &mean,\n                     const Eigen::Matrix<scalar, dim, dim> &covariance)\n      -> Eigen::Matrix<scalar, dim, 1>\n  {\n    // Use LDLT decomposition which works with semi definite covariances:\n    auto ldlt = covariance.ldlt();\n    // L = P^T L sqrt(D), where D is a diagonal matrix.\n    // https://stats.stackexchange.com/questions/48749/how-to-sample-from-a-multivariate-normal-given-the-pt-ldlt-p-decomposition-o\n    auto P_T = ldlt.transpositionsP().transpose();\n    auto L = ldlt.matrixL().toDenseMatrix();\n    // Root for diagonal matrix can be calculated element wise\n    auto sqrt_D = ldlt.vectorD().cwiseSqrt().asDiagonal();\n    auto decomposed = P_T * L * sqrt_D;\n    return sample<scalar, dim>(mean, decomposed);\n  }\n\n  /*!\n  Samples a random vector from a normal distribution using the Cholesky\n  decomposition. It might fail, if the covariance is not positive definite.\n  \\param mean the mean of the distribution\n  \\param covariance the covariance of the distribution\n  */\n  template <typename scalar, int dim>\n  auto sample_cholesky(const Eigen::Matrix<scalar, dim, 1> &mean,\n                       const Eigen::Matrix<scalar, dim, dim> &covariance)\n      -> Eigen::Matrix<scalar, dim, 1>\n  {\n    auto decomposed = covariance.llt().matrixL();\n    return sample<scalar, dim>(mean, decomposed);\n  }\n\n  /*!\n  Draws random values from a normal distribution parametrized by the mean and\n  standard deviation (NOT variance as in the covariance matrix version).\n  */\n  template <typename scalar>\n  scalar draw_normal(scalar mean, scalar standard_deviation)\n  {\n    std::normal_distribution<scalar> normal_dist;\n    return normal_dist(uniform_generator) * standard_deviation + mean;\n  }\n\nprivate:\n  // Algorithm that provides uniform distributed pseudo-random numbers.\n  // Real randomness is imposed via a random seed.\n  std::mt19937 uniform_generator;\n\n  /*!\n  Samples with the given mean and decomposed covariance matrix.\n  */\n  template <typename scalar, int dim>\n  auto sample(const Eigen::Matrix<scalar, dim, 1> &mean,\n              const Eigen::Matrix<scalar, dim, dim> &decomposed)\n      -> Eigen::Matrix<scalar, dim, 1>\n  {\n    auto norm_dist = create_normal_dist_vector<scalar, dim>();\n    return mean + decomposed * norm_dist;\n  }\n\n  /*!\n  Creates a vector with all elements drawn randlomly from a standard normal\n  distribution.\n  */\n  template <typename scalar, int dim>\n  Eigen::Matrix<scalar, dim, 1> create_normal_dist_vector()\n  {\n    std::normal_distribution<scalar> normal_dist;\n    Eigen::Matrix<scalar, dim, 1> result;\n    for (int i = 0; i < dim; i++)\n    {\n      result(i) = normal_dist(uniform_generator);\n    }\n    return result;\n  }\n};\n} // namespace filter_bay", "meta": {"hexsha": "3a3bac2f43e21840dff3c6ae810cdb358824f3f2", "size": 4023, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/filter_bay/utility/normal_sampler.hpp", "max_stars_repo_name": "Tuebel/filter_bay", "max_stars_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/filter_bay/utility/normal_sampler.hpp", "max_issues_repo_name": "Tuebel/filter_bay", "max_issues_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-10T14:36:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-21T10:10:08.000Z", "max_forks_repo_path": "include/filter_bay/utility/normal_sampler.hpp", "max_forks_repo_name": "Tuebel/filter_bay", "max_forks_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.525, "max_line_length": 131, "alphanum_fraction": 0.7066865523, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.6096436100298896}}
{"text": "#include <kv/Heine.hpp>\n#include <kv/qAiry.hpp>\n#include <kv/qBessel.hpp>\n#include <cmath>\n#include <iostream>\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/interval.hpp>\n\n// define rounding operations for double\n// if \"rdouble.hpp\" is not included, result of computation is not \"verified\" \n#include <kv/rdouble.hpp>\ntypedef kv::interval<double> itv;\ntypedef kv::complex< kv::interval<double> > cp;\nusing namespace std;\nnamespace ub = boost::numeric::ublas;\n\nint main()\n{\n  cout.precision(17);\n  ub::vector< itv > x(30);\n  int n=20;\n  itv y,nu,q,xx;\n  q=\"0.7\";\n  nu=1.5;\n  y=20.;\n \n  x(0)=y;\n  \n  for(int i=1;i<=n;i++){\n    xx=mid(x(i-1));\n    x(i)=xx-kv::HEratio(itv(xx),itv(nu),itv(q))*(1-q)*x(i-1)\n      /(kv::HEratio(itv(x(i-1)),itv(nu),itv(q))-kv::HEratio(itv(q*x(i-1)),itv(nu),itv(q)));\n    cout<<x(i)<<endl;\n    //cout<<i<<endl;\n    cout<<\"value of HE inf\"<<kv::Hahn_Exton(itv(x(i).lower()),itv(nu),itv(q))<<endl;\n    cout<<\"value of HE sup\"<<kv::Hahn_Exton(itv(x(i).upper()),itv(nu),itv(q))<<endl;\n    cout<<\"value of HE mid\"<<kv::Hahn_Exton(itv(mid(x(i))),itv(nu),itv(q))<<endl;\n  }\n }\n  // to be updated\n\n", "meta": {"hexsha": "b44d584b52e1245491e2e3cfb76a2b5799127c00", "size": 1183, "ext": "cc", "lang": "C++", "max_stars_repo_path": "qNewton/ratio/HEratio-QintNewton.cc", "max_stars_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_stars_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T20:55:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T12:26:00.000Z", "max_issues_repo_path": "qNewton/ratio/HEratio-QintNewton.cc", "max_issues_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_issues_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-03-07T04:32:20.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-05T01:48:57.000Z", "max_forks_repo_path": "qNewton/ratio/HEratio-QintNewton.cc", "max_forks_repo_name": "Daisuke-Kanaizumi/q-special-functions", "max_forks_repo_head_hexsha": "91aafafe125d864931e640cbe6993d9d61a32126", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8863636364, "max_line_length": 91, "alphanum_fraction": 0.6229923922, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6096436076513344}}
{"text": "\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <algorithm>\n\n#include \"aux/eigen2hdf.hpp\"\n#include \"quadrature/qhermite.hpp\"\n#include \"spectral/basis/spectral_basis_factory_hermite.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n#include \"spectral/h2n_1d.hpp\"\n#include \"spectral/hermite_to_nodal.hpp\"\n#include \"spectral/polar_to_hermite.hpp\"\n\n//#include <deal.II/base/exceptions.h>\n\nusing namespace std;\nusing namespace boltzmann;\n\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[])\n{\n  typedef Eigen::VectorXd vec_t;\n\n  int K = atoi(argv[1]);\n\n  // create basis files\n  typedef typename SpectralBasisFactoryHN::basis_type hermite_basis_t;\n  hermite_basis_t hermite_basis;\n  SpectralBasisFactoryHN::create(hermite_basis, K, 2);\n  cout << \"Hermite basis size: \" << hermite_basis.n_dofs() << endl;\n\n  // hermite to nodal\n  typedef Eigen::MatrixXd mat_t;\n  Hermite2Nodal<hermite_basis_t> h2n(\n      hermite_basis, K, [K](mat_t& m1, mat_t& m2) { H2N_1d<>::create(m1, m2, K); });\n  Hermite2Nodal<hermite_basis_t> h2ng(\n      hermite_basis, K, [K](mat_t& m1, mat_t& m2) { H2NG_1d::create(m1, m2, K, 1.0); });\n\n  auto& M = h2n.get_h2n();\n\n  auto& M2 = h2ng.get_h2n();\n\n  auto diff = M - M2;\n  diff = diff.select(abs(diff) < 1e-15, Eigen::MatrixXd::Zero(diff.rows(), diff.cols()), diff);\n\n  cout << \"difference matrix\\n\";\n  cout << diff << endl;\n  // cout << \"M := H2N-matrix\\n\";\n  // cout << \"M.T * M\\n\";\n  // cout << M.transpose()* M  << endl;\n\n  // fname = \"coefficients.h5\";\n  // if(!boost::filesystem::exists(fname)) {\n  //   cout << endl << fname << \" does not exist. Abort!\\n\";\n  //   return 1;\n  // }\n  // vec_t cp(N); // polar coefficients\n  // hid_t h5_init = H5Fopen(fname.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n  // eigen2hdf::load(h5_init, \"coeffs\", cp);\n  // H5Fclose(h5_init);\n\n  // AssertDimension(polar_basis.n_dofs(), cp.size());\n\n  hid_t h5f = H5Fcreate(\"test.h5\", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  eigen2hdf::save(h5f, \"M\", M);\n  eigen2hdf::save(h5f, \"Mg\", M2);\n  // eigen2hdf::save(h5f, \"coeffs_nodal\", cn);\n  // eigen2hdf::save(h5f, \"coeffs_hermite\", ch);\n  // eigen2hdf::save(h5f, \"coeffs\", cp2);\n  H5Fclose(h5f);\n\n  return 0;\n}\n", "meta": {"hexsha": "71adb332a516af8da4330ee76062047be912931a", "size": 2317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/H2N/main2.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/H2N/main2.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/H2N/main2.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3291139241, "max_line_length": 95, "alphanum_fraction": 0.6750107898, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6095180479202376}}
{"text": "///\n/// \\file hankel_gemv.hpp\n///\n#ifndef MXPFIT_HANKEL_MATRIX_HPP\n#define MXPFIT_HANKEL_MATRIX_HPP\n\n#include <Eigen/Core>\n\n#include <fftw3/shared_plan.hpp>\n\nnamespace mxpfit\n{\n\n///\n/// ### HankelMatrix\n///\n/// \\brief Expression of a generalized Hankel matrix.\n///\n/// \\tparam T  Scalar type of matrix elements\n///\n/// For the given vector \\f$ \\boldsymbol{h} = [h_0,h_1,...,h_{n+m-1}]^{T},\\f$ a\n/// \\f$ m \\times n \\f$ Hankel matrix, \\f$ A, \\f$ is defined as\n///\n/// \\f[\n///   A = \\left[ \\begin{array}{cccccc}\n///     h_0    & h_1    & h_2    & h_3   & \\cdots & h_{n-1} \\\\\n///     h_1    & h_2    & h_3    & h_4   & \\cdots & h_{n}   \\\\\n///     h_2    & h_3    & h_4    & h_5   & \\cdots & h_{n+1} \\\\\n///     h_3    & h_4    & h_5    & h_6   & \\cdots & h_{n+2} \\\\\n///     \\vdots & \\vdots & \\vdots &\\vdots & \\ddots & \\vdots \\\\\n///     h_{m-1} & h_{m} & h_{m+1} & h_{m+2} & \\cdots & h_{m+n-1}\n///   \\end{array} \\right]\n/// \\f]\n///\n/// This class represents a Hankel matrix expression from the given number of\n/// rows, \\f$ m, \\f$ the number of columns \\f$n,\\f$ and a vector expression for\n/// the coefficients, \\f$ \\boldsymbol{h}. \\f$ If the given vector expression is\n/// l-value, this class wraps the existing vector expression, otherwise storage\n/// for coefficients are allocated and stored.\n///\n/// This class also provides the interface for matrix-vector multiplication\n/// compatible to `MatrixFreeGEMV`. This operation can be performed efficiently\n/// using the fast Fourier transform (FFT) in \\f$O((m+n)\\log(m+n).\\f$\n///\n/// For this purpose, the class also allocate internal vectors as working space.\n/// The FFT plans are automatically generated whenever matrix size is updated.\n/// This operation is done in thread-safe manner, using mutex-lock.\n///\ntemplate <typename T>\nclass HankelMatrix\n{\npublic:\n    using Scalar              = T;\n    using RealScalar          = typename Eigen::NumTraits<T>::Real;\n    using ComplexScalar       = std::complex<RealScalar>;\n    using StorageIndex        = Eigen::Index;\n    using Index               = Eigen::Index;\n    using CoeffsVector        = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using CoeffsVectorRef     = Eigen::Ref<const CoeffsVector>;\n    using ComplexCoeffsVector = Eigen::Matrix<ComplexScalar, Eigen::Dynamic, 1>;\n    using PlainObject = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n\nprivate:\n    using FFT  = fftw3::FFT<RealScalar>;\n    using IFFT = fftw3::IFFT<RealScalar>;\n\n    typename FFT::PlanPointer m_fft_plan;\n    typename IFFT::PlanPointer m_ifft_plan;\n\n    Index m_rows;\n    Index m_cols;\n\n    mutable CoeffsVector m_work;\n    CoeffsVectorRef m_coeffs;\n    ComplexCoeffsVector m_caux;\n    mutable ComplexCoeffsVector m_xaux;\n\npublic:\n    enum\n    {\n        /// `Scalar` is complex number?\n        IsComplex = Eigen::NumTraits<Scalar>::IsComplex\n    };\n\n    /// Default constructor: create an empty matrix\n    HankelMatrix()\n        : m_fft_plan(),\n          m_ifft_plan(),\n          m_rows(),\n          m_cols(),\n          m_work(),\n          m_coeffs(m_work), // need to initialize Eigen::Ref object\n          m_caux(),\n          m_xaux()\n    {\n    }\n\n    /// Copy constructor\n    HankelMatrix(const HankelMatrix &other)\n        : m_fft_plan(other.m_fft_plan),\n          m_ifft_plan(other.m_ifft_plan),\n          m_rows(other.m_rows),\n          m_cols(other.m_cols),\n          m_work(other.m_work),\n          m_coeffs(other.m_coeffs),\n          m_caux(other.m_caux),\n          m_xaux(other.m_xaux)\n    {\n    }\n\n    ///\n    /// Construct a Hankel matrix with memory allocation\n    ///\n    /// \\param[in] nrows the number of rows\n    /// \\param[in] ncols the number of columns\n    /// \\param[in] prescribed_fft_size the FFT length (optional)\n    ///\n    /// \\pre  `nrows >= 0 && ncols >= 0` is required\n    ///\n    HankelMatrix(Index nrows, Index ncols, Index prescribed_fft_size = 0)\n        : m_fft_plan(),\n          m_ifft_plan(),\n          m_rows(nrows),\n          m_cols(ncols),\n          m_work(get_fft_length(nrows, ncols, prescribed_fft_size)),\n          m_coeffs(m_work), // need to initialize Eigen::Ref\n          m_caux(IsComplex ? m_work.size() : m_work.size() / 2 + 1),\n          m_xaux(m_caux.size())\n    {\n        assert(nrows >= Index() && \"nrows must be a non-negative integer\");\n        assert(ncols >= Index() && \"ncols must be a non-negative integer\");\n        set_fft_plans();\n    }\n\n    /// Default destructor\n    ~HankelMatrix()\n    {\n    }\n\n    /// Assignment operator is deleted as a consequence that Eigen::Ref is\n    /// non-assignable\n    HankelMatrix &operator=(const HankelMatrix &other) = delete;\n\n    /// \\return the number of rows\n    Index rows() const\n    {\n        return m_rows;\n    }\n\n    /// \\return the number of columns\n    Index cols() const\n    {\n        return m_cols;\n    }\n\n    /// \\return size of vector that defines current Hankel matrix\n    Index size() const\n    {\n        // Return 0 if the matrix is empty\n        return std::max(Index(), rows() + cols() - 1);\n    }\n\n    /// \\return  A const reference of the coefficient vector\n    const CoeffsVectorRef &coeffs() const\n    {\n        return m_coeffs;\n    }\n\n    ///\n    /// Resize internal Hankel matrix and update FFT plan for matrix-vector\n    /// multiplication if necessary.\n    ///\n    void resize(Index nrows, Index ncols, Index prescribed_fft_size = 0)\n    {\n        assert(nrows >= Index() && \"nrows must be a non-negative integer\");\n        assert(ncols >= Index() && \"ncols must be a non-negative integer\");\n\n        m_rows = nrows;\n        m_cols = ncols;\n\n        const Index n1 = m_work.size();\n        const Index n2 = get_fft_length(nrows, ncols, prescribed_fft_size);\n\n        if (n1 != n2)\n        {\n            m_work.resize(n2);\n            m_caux.resize(IsComplex ? m_work.size() : m_work.size() / 2 + 1);\n            m_xaux.resize(m_caux.size());\n            set_fft_plans();\n\n            if (coeffs().size() != size())\n            {\n                // Eigen::Ref to dummy object\n                m_coeffs.~CoeffsVectorRef();\n                ::new (&m_coeffs) CoeffsVectorRef(m_work);\n            }\n        }\n    }\n\n    ///\n    /// Set a Hankel matrix from the number of rows, columns and vector\n    /// expression of matrix coefficients.\n    ///\n    /// \\param[in] coeffs   the vector expression of matrix coefficients\n    ///\n    /// \\pre `coeffs.size() ==  size()` is required\n    ///\n    template <typename Derived>\n    void setCoeffs(const Eigen::EigenBase<Derived> &coeffs)\n    {\n        assert(coeffs.size() == size() &&\n               \"Invalid size for the vector of coefficients\");\n        if (rows() == Index() || cols() == Index())\n        {\n            // Matrix is empty. Nothing to do.\n            return;\n        }\n\n        m_coeffs.~CoeffsVectorRef();\n        ::new (&m_coeffs) CoeffsVectorRef(coeffs.derived());\n\n        compute_aux_vector();\n    }\n\n    void setCoeffs(const CoeffsVectorRef &coeffs)\n    {\n        assert(coeffs.size() == size() &&\n               \"Invalid size for the vector of coefficients\");\n        if (rows() == Index() || cols() == Index())\n        {\n            // Matrix is empty. Nothing to do.\n            return;\n        }\n\n        if (&(coeffs.derived()) != &m_coeffs)\n        {\n            m_coeffs.~CoeffsVectorRef();\n            ::new (&m_coeffs) CoeffsVectorRef(coeffs);\n            compute_aux_vector();\n        }\n    }\n\n    /// \\return The same Hankel matrix in dense form.\n    PlainObject toDenseMatrix() const\n    {\n        PlainObject ret(rows(), cols());\n        for (Index j = 0; j < cols(); ++j)\n        {\n            for (Index i = 0; i < rows(); ++i)\n            {\n                ret(i, j) = coeffs()(i + j);\n            }\n        }\n        return ret;\n    }\n\n    /// Compute `dst += alpha * A * rhs`\n    template <typename Dest, typename RHS>\n    void apply(Dest &dst, const Eigen::MatrixBase<RHS> &rhs, Scalar alpha) const\n    {\n        apply_impl<false>(dst, rhs, alpha);\n    }\n\n    /// Compute `dst += alpha * A.conjugate() * rhs`\n    template <typename Dest, typename RHS>\n    void applyConjugate(Dest &dst, const Eigen::MatrixBase<RHS> &rhs,\n                        Scalar alpha) const\n    {\n        apply_impl<(IsComplex != 0)>(dst, rhs, alpha);\n    }\n\n    /// Compute `dst += alpha * A.transpose() * rhs`\n    template <typename Dest, typename RHS>\n    void applyTranspose(Dest &dst, const Eigen::MatrixBase<RHS> &rhs,\n                        Scalar alpha) const\n    {\n        apply_transpose_impl<false>(dst, rhs, alpha);\n    }\n\n    /// Compute `dst += alpha * A.transpose() * rhs`\n    template <typename Dest, typename RHS>\n    void applyAdjoint(Dest &dst, const Eigen::MatrixBase<RHS> &rhs,\n                      Scalar alpha) const\n    {\n        apply_transpose_impl<(IsComplex != 0)>(dst, rhs, alpha);\n    }\n\nprivate:\n    static Index get_fft_length(Index nrows, Index ncols,\n                                Index prescribed_fft_size)\n    {\n        // Enforce fft_size becomes even\n        const Index n = (nrows + ncols) / 2;\n        return std::max({prescribed_fft_size, 2 * n});\n    }\n\n    void set_fft_plans()\n    {\n        const int n       = static_cast<int>(m_work.size());\n        const int howmany = 1;\n        m_fft_plan  = FFT::make_plan(n, howmany, m_work.data(), m_xaux.data());\n        m_ifft_plan = IFFT::make_plan(n, howmany, m_xaux.data(), m_work.data());\n    }\n\n    // Pre-compute auxiliary vector for matrix-vector multiplication operation\n    void compute_aux_vector()\n    {\n        // Set first column of circulant matrix C. Then compute the discrete\n        // Fourier transform this vector and store the result into \\c caux.\n        const auto nhead    = rows();\n        const auto ntail    = cols() - 1;\n        const auto npadding = m_work.size() - nhead - ntail;\n\n        m_work.head(nhead) = coeffs().tail(nhead);\n        if (npadding > Index())\n        {\n            m_work.segment(nhead, npadding).setZero();\n        }\n        m_work.tail(ntail) = coeffs().head(ntail);\n\n        // m_caux <-- FFT[m_work]\n        FFT::run(m_fft_plan, m_work.data(), m_caux.data());\n        m_caux *= RealScalar(1) / m_work.size();\n    }\n\n    template <bool ComplexConjugate, typename Dest, typename RHS>\n    void apply_impl(Dest &dst, const Eigen::MatrixBase<RHS> &rhs,\n                    Scalar alpha) const\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(Dest);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(RHS);\n\n        assert(dst.size() == rows());\n        assert(rhs.size() == cols());\n\n        if (alpha == Scalar(/*zero*/))\n        {\n            return;\n        }\n        //\n        // Form new vector x' = [x(n-1),x(n-2),...,x(0),0....0] of\n        // length n + m - 1, and compute FFT.\n        //\n        if (ComplexConjugate)\n        {\n            m_work.head(cols()) = rhs.reverse().conjugate();\n        }\n        else\n        {\n            m_work.head(cols()) = rhs.reverse();\n        }\n\n        m_work.tail(m_work.size() - cols()).setZero();\n\n        // m_xaux <-- FFT[m_work]\n        FFT::run(m_fft_plan, m_work.data(), m_xaux.data());\n        //\n        // y[0:nrows] = IFFT(FFT(c') * FFT(x'))[0:nrows]\n        //\n        m_xaux = m_xaux.cwiseProduct(m_caux);\n        IFFT::run(m_ifft_plan, m_xaux.data(), m_work.data());\n\n        if (ComplexConjugate)\n        {\n            dst += alpha * m_work.head(rows()).conjugate();\n        }\n        else\n        {\n            dst += alpha * m_work.head(rows());\n        }\n    }\n\n    // Compute `dst += alpha * A^T * rhs`\n    template <bool ComplexConjugate, typename Dest, typename RHS>\n    void apply_transpose_impl(Dest &dst, const Eigen::MatrixBase<RHS> &rhs,\n                              Scalar alpha) const\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(Dest);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(RHS);\n\n        assert(dst.size() == cols());\n        assert(rhs.size() == rows());\n\n        if (alpha == Scalar(/*zero*/))\n        {\n            return;\n        }\n        //\n        // Form new vector x' = [0,0,...,0,x(m-1),x(m-2),...,x(0)] of\n        // length n + m - 1, and compute FFT.\n        //\n        m_work.head(m_work.size() - rows()).setZero();\n        if (ComplexConjugate)\n        {\n            m_work.tail(rows()) = rhs.reverse().conjugate();\n        }\n        else\n        {\n            m_work.tail(rows()) = rhs.reverse();\n        }\n\n        // m_xaux <-- FFT[m_work]\n        FFT::run(m_fft_plan, m_work.data(), m_xaux.data());\n        //\n        // y[0:ncols-1] = IFFT(FFT(c') * FFT(x'))[nrows:size - 1]\n        //\n        m_xaux = m_xaux.cwiseProduct(m_caux);\n        IFFT::run(m_ifft_plan, m_xaux.data(), m_work.data());\n\n        if (ComplexConjugate)\n        {\n            dst += alpha * m_work.tail(cols()).conjugate();\n        }\n        else\n        {\n            dst += alpha * m_work.tail(cols());\n        }\n    }\n};\n\n} // namespace mxpfit\n\n#endif /* MXPFIT_HANKEL_MATRIX_HPP */\n", "meta": {"hexsha": "156bafcf7adc708e3952c74234b39f6a2ef47575", "size": 12854, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/hankel_matrix.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/hankel_matrix.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/hankel_matrix.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3160377358, "max_line_length": 80, "alphanum_fraction": 0.5548467403, "num_tokens": 3348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.6095180424473028}}
{"text": "/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*/\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n#include <boost/version.hpp>\n\n#include \"mitkFormulaParser.h\"\n#include \"mitkFresnel.h\"\n\nnamespace qi = boost::spirit::qi;\nnamespace ascii = boost::spirit::ascii;\nnamespace phx = boost::phoenix;\n\ntypedef std::string::const_iterator Iter;\ntypedef ascii::space_type Skipper;\n\nnamespace qi = boost::spirit::qi;\n\nnamespace mitk\n{\n  /*!\n   *\t@brief\t\t\tTransforms the given number from degrees to radians and returns it.\n   *\t@tparam T\t\tThe scalar type that represents a value (e.g. double).\n   *\t@param[in] deg\tA scalar value in degrees.\n   *\t@return\t\t\tThe given value in radians.\n   */\n  template<typename T>\n  inline T deg2rad(const T deg)\n  {\n    return deg * boost::math::constants::pi<T>() / static_cast<T>(180);\n  }\n\n  /*!\n   *\t@brief\t\t\tReturns the cosine of the given degree scalar.\n   *\t@tparam T\t\tThe scalar type that represents a value (e.g. double).\n   *\t@param[in] t\tA scalar value in degrees whose cosine should be returned.\n   *\t@return\t\t\tThe cosine of the given degree scalar.\n   */\n  template<typename T>\n  inline T cosd(const T t)\n  {\n    return std::cos(deg2rad(t));\n  }\n\n  /*!\n   *\t@brief\t\t\tReturns the sine of the given degree scalar.\n   *\t@tparam T\t\tThe scalar type that represents a value (e.g. double).\n   *\t@param[in] t\tA scalar value in degrees whose sine should be returned.\n   *\t@return\t\t\tThe sine of the given degree scalar.\n   */\n  template<typename T>\n  inline T sind(const T t)\n  {\n    return std::sin(deg2rad(t));\n  }\n\n  /*!\n   *\t@brief\t\t\tReturns the tangent of the given degree scalar.\n   *\t@tparam T\t\tThe scalar type that represents a value (e.g. double).\n   *\t@param[in] t\tA scalar value in degrees whose tangent should be returned.\n   *\t@return\t\t\tThe tangent of the given degree scalar.\n   */\n  template<typename T>\n  inline T tand(const T t)\n  {\n    return std::tan(deg2rad(t));\n  }\n\n  /*!\n   *\t@brief\t\t\tReturns the fresnel integral sine at the given x-coordinate.\n   *\t@details\t\tCode for \"fresnel_s()\" (fresnel.cpp and fresnel.h) taken as-is from the GNU\n   *\t\t\t\t\tScientific Library (http://www.gnu.org/software/gsl/), specifically from\n   *\t\t\t\t\thttp://www.network-theory.co.uk/download/gslextras/Fresnel/.\n   *\t@tparam T\t\tThe scalar type that represents a value (e.g. double).\n   *\t@param[in] t\tThe x-coordinate at which the fresnel integral sine should be returned.\n   *\t@return\t\t\tThe fresnel integral sine at the given x-coordinate.\n   */\n  template<typename T>\n  T fresnelS(const T t)\n  {\n    T x = t / boost::math::constants::root_half_pi<T>();\n    return static_cast<T>(fresnel_s(x) / boost::math::constants::root_two_div_pi<T>());\n  }\n\n  /*!\n   *\t@brief\t\t\tReturns the fresnel integral cosine at the given x-coordinate.\n   *\t@details\t\tCode for \"fresnel_c()\" (fresnel.cpp and fresnel.h) taken as-is from the GNU\n   *\t\t\t\t\tScientific Library (http://www.gnu.org/software/gsl/), specifically from\n   *\t\t\t\t\thttp://www.network-theory.co.uk/download/gslextras/Fresnel/.\n   *\t@tparam T\t\tThe scalar type that represents a value (e.g. double).\n   *\t@param[in] t\tThe x-coordinate at which the fresnel integral cosine should be returned.\n   *\t@return\t\t\tThe fresnel integral cosine at the given x-coordinate.\n   */\n  template<typename T>\n  T fresnelC(const T t)\n  {\n    T x = t / boost::math::constants::root_half_pi<T>();\n    return static_cast<T>(fresnel_c(x) / boost::math::constants::root_two_div_pi<T>());\n  }\n\n  /*!\n   *\t@brief\t\tThe grammar that defines the language (i.e. what is allowed) for the parser.\n   */\n  class Grammar : public qi::grammar<Iter, FormulaParser::ValueType(), Skipper>\n  {\n    /*!\n     *\t@brief\tHelper structure that makes it easier to dynamically call any\n     *\t\t\tone-parameter-function by overloading the @c () operator.\n     */\n    struct func1_\n    {\n      // Required for Phoenix 3+\n      template<typename Sig>\n      struct result;\n\n      /*!\n       *\t@brief\t\t\t\tHelper structure that is needed for compatibility with\n       *\t\t\t\t\t\t@c boost::phoenix.\n       *\t@tparam Functor\t\tType of the functor (this struct).\n       *\t@tparam Function\tType of the function that should be called.\n       *\t@tparam Arg1\t\tType of the argument the function should be called with.\n       *\n       */\n      template<typename Functor, typename Function, typename Arg1>\n      struct result<Functor(Function, Arg1&)>\n      {\n        /*! @brief The result structure always needs this typedef */\n        typedef Arg1 type;\n      };\n\n      /*!\n       *\t@brief\t\t\t\tCalls the function @b f with the argument @b a1 and returns the\n       *\t\t\t\t\t\tresult.\n       *\t\t\t\t\t\tThe result always has the same type as the argument.\n       *\t@tparam Function\tType of the function that should be called.\n       *\t@tparam Arg1\t\t\tType of the argument the function should be called with.\n       *\t@param[in] f\t\tThe function that should be called.\n       *\t@param[in] a1\t\tThe argument the function should be called with.\n       *\t@return\t\t\t\tThe result of the called function.\n       */\n      template<typename Function, typename Arg1>\n      Arg1 operator()(const Function f, const Arg1 a1) const\n      {\n        return f(a1);\n      }\n    };\n\n    /*!\n     *\t@brief\tHelper structure that maps strings to function calls so that parsing e.g.\n     *\t\t\t@c \"cos(0)\" actually calls the @c std::cos function with parameter @c 1 so it\n     *\t\t\treturns @c 0.\n     */\n    class unaryFunction_ :\n      public qi::symbols<typename std::iterator_traits<Iter>::value_type, FormulaParser::ValueType(*)(FormulaParser::ValueType)>\n    {\n    public:\n      /*!\n       *\t@brief Constructs the structure, this is where the mapping takes place.\n       */\n      unaryFunction_()\n      {\n        this->add\n        (\"abs\", static_cast<FormulaParser::ValueType(*)(FormulaParser::ValueType)>(&std::abs))\n          (\"exp\", static_cast<FormulaParser::ValueType(*)(FormulaParser::ValueType)>(&std::exp)) // @TODO: exp ignores division by zero\n          (\"sin\", static_cast<FormulaParser::ValueType(*)(FormulaParser::ValueType)>(&std::sin))\n          (\"cos\", static_cast<FormulaParser::ValueType(*)(FormulaParser::ValueType)>(&std::cos))\n          (\"tan\", static_cast<FormulaParser::ValueType(*)(FormulaParser::ValueType)>(&std::tan))\n          (\"sind\", &sind)\n          (\"cosd\", &cosd)\n          (\"tand\", &tand)\n          (\"fresnelS\", &fresnelS)\n          (\"fresnelC\", &fresnelC);\n      }\n    } unaryFunction;\n\n  public:\n    /*!\n     *\t@brief\t\t\t\t\t\t\tConstructs the grammar with the given formula parser.\n     *\t@param[in, out] formulaParser\tThe formula parser this grammar is for - so it can\n     *\t\t\t\t\t\t\t\t\taccess its variable map.\n     */\n    Grammar(FormulaParser& formulaParser) : Grammar::base_type(start)\n    {\n      using qi::_val;\n      using qi::_1;\n      using qi::_2;\n      using qi::char_;\n      using qi::alpha;\n      using qi::alnum;\n      using qi::double_;\n      using qi::as_string;\n\n      phx::function<func1_> func1;\n\n      start = expression > qi::eoi;\n\n      expression = term[_val = _1]\n        >> *(('+' >> term[_val += _1])\n          | ('-' >> term[_val -= _1]));\n\n      term = factor[_val = _1]\n        >> *(('*' >> factor[_val *= _1])\n          | ('/' >> factor[_val /= _1]));\n\n      factor = primary[_val = _1];\n      /*!\t@TODO:\tRepair exponentiation */\n      //>> *('^' >> factor[phx::bind<FormulaParser::ValueType, FormulaParser::ValueType, FormulaParser::ValueType>(std::pow, _val, _1)]);\n\n      variable = as_string[alpha >> *(alnum | char_('_'))]\n        [_val = phx::bind(&FormulaParser::lookupVariable, &formulaParser, _1)];\n\n      primary = double_[_val = _1]\n        | '(' >> expression[_val = _1] >> ')'\n        | ('-' >> primary[_val = -_1])\n        | ('+' >> primary[_val = _1])\n        | (unaryFunction >> '(' >> expression >> ')')[_val = func1(_1, _2)]\n        | variable[_val = _1];\n    }\n\n    /*! the rules of the grammar. */\n    qi::rule<Iter, FormulaParser::ValueType(), Skipper> start;\n    qi::rule<Iter, FormulaParser::ValueType(), Skipper> expression;\n    qi::rule<Iter, FormulaParser::ValueType(), Skipper> term;\n    qi::rule<Iter, FormulaParser::ValueType(), Skipper> factor;\n    qi::rule<Iter, FormulaParser::ValueType(), Skipper> variable;\n    qi::rule<Iter, FormulaParser::ValueType(), Skipper> primary;\n  };\n\n\n  FormulaParser::FormulaParser(const VariableMapType* variables) : m_Variables(variables)\n  {}\n\n  FormulaParser::ValueType FormulaParser::parse(const std::string& input)\n  {\n    std::string::const_iterator iter = input.begin();\n    std::string::const_iterator end = input.end();\n    FormulaParser::ValueType result = static_cast<FormulaParser::ValueType>(0);\n\n    try\n    {\n      if (!qi::phrase_parse(iter, end, Grammar(*this), ascii::space, result))\n      {\n        mitkThrowException(FormulaParserException) << \"Could not parse '\" << input <<\n          \"': Grammar could not be applied to the input \" << \"at all.\";\n      }\n    }\n    catch (qi::expectation_failure<Iter>& e)\n    {\n      std::string parsed = \"\";\n\n      for (Iter i = input.begin(); i != e.first; i++)\n      {\n        parsed += *i;\n      }\n      mitkThrowException(FormulaParserException) << \"Error while parsing '\" << input <<\n        \"': Unexpected character '\" << *e.first << \"' after '\" << parsed << \"'\";\n    }\n\n    return result;\n  };\n\n  FormulaParser::ValueType FormulaParser::lookupVariable(const std::string var)\n  {\n    if (m_Variables == nullptr)\n    {\n      mitkThrowException(FormulaParserException) << \"Map of variables is empty\";\n    }\n\n    try\n    {\n      return m_Variables->at(var);\n    }\n    catch (std::out_of_range&)\n    {\n      mitkThrowException(FormulaParserException) << \"No variable '\" << var << \"' defined in lookup\";\n    }\n  };\n\n}\n", "meta": {"hexsha": "eda29c8517ed23b5dd003a892b0cb1766e2c5da0", "size": 10077, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/ModelFit/src/Common/mitkFormulaParser.cpp", "max_stars_repo_name": "zhaomengxiao/MITK", "max_stars_repo_head_hexsha": "a09fd849a4328276806008bfa92487f83a9e2437", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-03T12:03:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T12:03:32.000Z", "max_issues_repo_path": "Modules/ModelFit/src/Common/mitkFormulaParser.cpp", "max_issues_repo_name": "zhaomengxiao/MITK", "max_issues_repo_head_hexsha": "a09fd849a4328276806008bfa92487f83a9e2437", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-22T10:19:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-22T10:19:02.000Z", "max_forks_repo_path": "Modules/ModelFit/src/Common/mitkFormulaParser.cpp", "max_forks_repo_name": "zhaomengxiao/MITK_lancet", "max_forks_repo_head_hexsha": "a09fd849a4328276806008bfa92487f83a9e2437", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-27T09:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-27T09:41:18.000Z", "avg_line_length": 34.6288659794, "max_line_length": 137, "alphanum_fraction": 0.6181403195, "num_tokens": 2542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6095112523060126}}
{"text": "// osqp-eigen\n#include \"OsqpEigen/OsqpEigen.h\"\n\n// eigen\n#include <Eigen/Dense>\n#include <iostream>\n\nint main()\n{\n    // allocate QP problem matrices and vectores\n    Eigen::SparseMatrix<double> hessian(2, 2);      //P: n*n\u6b63\u5b9a\u77e9\u9635,\u5fc5\u987b\u4e3a\u7a00\u758f\u77e9\u9635SparseMatrix\n    Eigen::VectorXd gradient(2);                    //Q: n*1\u5411\u91cf\n    Eigen::SparseMatrix<double> linearMatrix(2, 2); //A: m*n\u77e9\u9635,\u5fc5\u987b\u4e3a\u7a00\u758f\u77e9\u9635SparseMatrix\n    Eigen::VectorXd lowerBound(2);                  //L: m*1\u4e0b\u9650\u5411\u91cf\n    Eigen::VectorXd upperBound(2);                  //U: m*1\u4e0a\u9650\u5411\u91cf\n\n    hessian.insert(0, 0) = 2.0; //\u6ce8\u610f\u7a00\u758f\u77e9\u9635\u7684\u521d\u59cb\u5316\u65b9\u5f0f,\u65e0\u6cd5\u4f7f\u7528<<\u521d\u59cb\u5316\n    hessian.insert(1, 1) = 2.0;\n    // std::cout << \"hessian:\" << std::endl\n    //           << hessian << std::endl;\n    gradient << -2, -2;\n    linearMatrix.insert(0, 0) = 1.0; //\u6ce8\u610f\u7a00\u758f\u77e9\u9635\u7684\u521d\u59cb\u5316\u65b9\u5f0f,\u65e0\u6cd5\u4f7f\u7528<<\u521d\u59cb\u5316\n    linearMatrix.insert(1, 1) = 1.0;\n    // std::cout << \"linearMatrix:\" << std::endl\n    //           << linearMatrix << std::endl;\n    lowerBound << 1, 1;\n    upperBound << 1.5, 1.5;\n\n    // instantiate the solver\n    OsqpEigen::Solver solver;\n\n    // settings\n    solver.settings()->setVerbosity(false);\n    solver.settings()->setWarmStart(true);\n\n    // set the initial data of the QP solver\n    solver.data()->setNumberOfVariables(2);   //\u53d8\u91cf\u6570n\n    solver.data()->setNumberOfConstraints(2); //\u7ea6\u675f\u6570m\n    if (!solver.data()->setHessianMatrix(hessian))\n        return 1;\n    if (!solver.data()->setGradient(gradient))\n        return 1;\n    if (!solver.data()->setLinearConstraintsMatrix(linearMatrix))\n        return 1;\n    if (!solver.data()->setLowerBound(lowerBound))\n        return 1;\n    if (!solver.data()->setUpperBound(upperBound))\n        return 1;\n\n    // instantiate the solver\n    if (!solver.initSolver())\n        return 1;\n\n    Eigen::VectorXd QPSolution;\n\n    // solve the QP problem\n    if (!solver.solve())\n    {\n        return 1;\n    }\n\n    QPSolution = solver.getSolution();\n    std::cout << \"QPSolution\" << std::endl\n              << QPSolution << std::endl; //\u8f93\u51fa\u4e3am*1\u7684\u5411\u91cf\n    return 0;\n}", "meta": {"hexsha": "6cbb2e8f1a3f9ad059feb299344b9b484936470f", "size": 1992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "xinchu911/osqp_demo", "max_stars_repo_head_hexsha": "6e8c35dd35b1a571319444b1ddff171a47d8f32f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "xinchu911/osqp_demo", "max_issues_repo_head_hexsha": "6e8c35dd35b1a571319444b1ddff171a47d8f32f", "max_issues_repo_licenses": ["Apache-2.0"], "max_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": "xinchu911/osqp_demo", "max_forks_repo_head_hexsha": "6e8c35dd35b1a571319444b1ddff171a47d8f32f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-03T06:08:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T06:08:48.000Z", "avg_line_length": 30.1818181818, "max_line_length": 84, "alphanum_fraction": 0.5903614458, "num_tokens": 656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.6095112490394516}}
{"text": "/* ROS-CHOMP.\n *\n * Copyright (C) 2015 Jafar Qutteineh. All rights reserved.\n * License (3-Cluase BSD): https://github.com/j3sq/ROS-CHOMP/blob/master/LICENSE\n *\n * This code uses and is based on code from:\n *   Project: trychomp https://github.com/poftwaresatent/trychomp\n *   Copyright (C) 2014 Roland Philippsen. All rights reserved.\n *   License (3-Clause BSD) : https://github.com/poftwaresatent/trychomp\n * **\n * \\file chomp.cpp\n *\n * CHOMP for point vehicles (x,y) moving holonomously in the plane. It will\n * plan a trajectory (xi) connecting start point (qs) to end point (qe) while\n * avoiding obstacles (obs)\n */\n#include <iostream>\n#include <Eigen/Dense>\n#include <stdlib.h>\n#include <err.h>\n#include \"chomp.hpp\"\n\ntypedef Eigen::VectorXd Vector;\ntypedef Eigen::MatrixXd Matrix;\ntypedef Eigen::Isometry3d Transform;\n\nusing namespace std;\n\nnamespace chomp {\n//////////////////////////////////////////////////\n// trajectory etc\n\n\nstatic size_t const nq(20);             // number of q stacked into xi\nstatic size_t const cdim(2);            // dimension of config space\nstatic size_t const xidim(nq *cdim);    // dimension of trajectory, xidim = nq * cdim\nstatic size_t const iteration_limit(10000);\nstatic double const dt(1.0);            // time step\nstatic double const eta(100.0);         // >= 1, regularization factor for gradient descent\nstatic double const lambda(1.0);        // weight of smoothness objective\n\n\n//////////////////////////////////////////////////\n// gradient descent etc\n\nMatrix AA;                      // metric\nVector bb;                      // acceleration bias for start and end config\nMatrix Ainv;                    // inverse of AA\n\n\nstatic void init_chomp(Vector const &qs, Vector const &qe, Vector  &xi)\n{\n\tif (xi.rows() == xidim) {\n\t\t//do nothing. Use existing trajectory\n\t} else {\n\t\t//initalize a new trajectory based on a direct line connecting qs to qe\n\t\txi = Vector::Zero(xidim);\n\t\tVector dxi(cdim);\n\t\tdxi << (qe(0) - qs(0)) / (nq - 1), (qe(0) - qs(0)) / (nq - 1);\n\t\tfor (size_t ii(0); ii < nq; ++ii)\n\t\t\txi.block(cdim * ii, 0, cdim, 1) = qs + ii * dxi;\n\n\t\t/*\n\t\t * //use this instead if you want to inalize all points to qs\n\t\t * for (size_t ii (0); ii < nq; ++ii) {\n\t\t * xi.block (cdim * ii, 0, cdim, 1) = qs;\n\t\t * }\n\t\t */\n\t}\n\tAA = Matrix::Zero(xidim, xidim);\n\tfor (size_t ii(0); ii < nq; ++ii) {\n\t\tAA.block(cdim * ii, cdim * ii, cdim, cdim) = 2.0 * Matrix::Identity(cdim, cdim);\n\t\tif (ii > 0) {\n\t\t\tAA.block(cdim * (ii - 1), cdim * ii, cdim, cdim) = -1.0 * Matrix::Identity(cdim, cdim);\n\t\t\tAA.block(cdim * ii, cdim * (ii - 1), cdim, cdim) = -1.0 * Matrix::Identity(cdim, cdim);\n\t\t}\n\t}\n\tAA /= dt * dt * (nq + 1);\n\n\tbb = Vector::Zero(xidim);\n\tbb.block(0, 0, cdim, 1) = qs;\n\tbb.block(xidim - cdim, 0, cdim, 1) = qe;\n\tbb /= -dt * dt * (nq + 1);\n\n\t// not needed anyhow\n\t// double cc (double (qs.transpose() * qs) + double (qe.transpose() * qe));\n\t// cc /= dt * dt * (nq + 1);\n\n\tAinv = AA.inverse();\n}\n\n\nstatic double chomp_iteration(Vector const &qs, Vector const &qe, Vector  &xi, Matrix const &obs)\n{\n\t//////////////////////////////////////////////////\n\t// beginning of \"the\" CHOMP iteration\n\tVector nabla_smooth(AA * xi + bb);\n\tVector const & xidd(nabla_smooth); // indeed, it is the same in this formulation...\n\n\tVector nabla_obs(Vector::Zero(xidim));\n\n\tfor (size_t iq(0); iq < nq; ++iq) {\n\t\tVector const qq(xi.block(iq * cdim, 0, cdim, 1));\n\t\tVector qd;\n\t\tif (0 == iq) {\n\t\t\tqd = 0.5 * (xi.block((iq + 1) * cdim, 0, cdim, 1) - qs);\n\t\t} else if (iq == nq - 1) {\n\t\t\tqd = 0.5 * (qe - xi.block((iq - 1) * cdim, 0, cdim, 1));\n\t\t} else {\n\t\t\tqd = 0.5 * (xi.block((iq + 1) * cdim, 0, cdim, 1) - xi.block((iq - 1) * cdim, 0, cdim, 1));;\n\t\t}\n\n\t\t// In this case, C and W are the same, Jacobian is identity.  We\n\t\t// still write more or less the full-fledged CHOMP expressions\n\t\t// (but  we only use one body point) to make subsequent extension\n\t\t// easier.\n\t\t//\n\t\tVector const & xx(qq);\n\t\tVector const & xd(qd);\n\t\tMatrix const JJ(Matrix::Identity(2, 2));        // a little silly here, as noted above.\n\t\tdouble const vel(xd.norm());\n\t\tif (vel < 1.0e-3)                               // avoid div by zero further down\n\t\t\tcontinue;\n\t\tVector const xdn(xd / vel);\n\t\tVector const xdd(JJ * xidd.block(iq * cdim, 0, cdim, 1));\n\t\tMatrix const prj(Matrix::Identity(2, 2) - xdn * xdn.transpose()); // hardcoded planar case\n\t\tVector const kappa(prj * xdd / pow(vel, 2.0));\n\n\n\t\tfor (int ii = 0; ii < obs.cols(); ii++) {\n\t\t\tVector delta(xx - obs.block(0, ii, cdim, 1));\n\t\t\tdouble const dist(delta.norm());\n\t\t\tif ((dist >= obs(2, ii)) || (dist < 1e-9))\n\t\t\t\tcontinue;\n\t\t\tstatic double const gain(10.0);                                                 // hardcoded param\n\t\t\tdouble const cost(gain * obs(2, ii) * pow(1.0 - dist / obs(2, ii), 3.0) / 3.0); // hardcoded param\n\t\t\tdelta *= -gain *pow(1.0 - dist / obs(2, ii), 2.0) / dist;                       // hardcoded param\n\t\t\tnabla_obs.block(iq * cdim, 0, cdim, 1) += JJ.transpose() * vel * (prj * delta - cost * kappa);\n\t\t}\n\t}\n\n\tVector dxi(Ainv * (nabla_obs + lambda * nabla_smooth));\n\txi -= dxi / eta;\n\t//return the error (in Euclidean sense ). Remeber that the difference is -dxi/eta\n\treturn dxi.norm() / eta;\n\n\t// end of \"the\" CHOMP iteration\n\t//////////////////////////////////////////////////\n}\n\nvoid generatePath(Vector const &qs, Vector const &qe, Vector &xi, Matrix const &obs)\n{\n\tinit_chomp(qs, qe, xi);\n\tdouble err;\n\tfor (size_t ii = 0; ii < iteration_limit; ii++) {\n\t\terr = chomp_iteration(qs, qe, xi, obs);\n\t\tif (err < 0.01)\n\t\t\tbreak;\n\t}\n}\n} //namespace\n", "meta": {"hexsha": "ce5f7f8a4c403fb8dc5f274fd732c87bc18d2810", "size": 5539, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/chomp.cpp", "max_stars_repo_name": "j3sq/ROS-CHOMP", "max_stars_repo_head_hexsha": "60731f3c7b8d489e2a3ffa38e526dbfc7ba292c3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-27T16:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-27T16:00:51.000Z", "max_issues_repo_path": "src/chomp.cpp", "max_issues_repo_name": "j3sq/ROS-CHOMP", "max_issues_repo_head_hexsha": "60731f3c7b8d489e2a3ffa38e526dbfc7ba292c3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chomp.cpp", "max_forks_repo_name": "j3sq/ROS-CHOMP", "max_forks_repo_head_hexsha": "60731f3c7b8d489e2a3ffa38e526dbfc7ba292c3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-10T02:44:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-14T02:06:44.000Z", "avg_line_length": 34.1913580247, "max_line_length": 101, "alphanum_fraction": 0.5804296804, "num_tokens": 1795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.609507483181572}}
{"text": "/*\n * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT)\n *\n * This software may be modified and distributed under the terms of the\n * BSD 3-Clause license. See the accompanying LICENSE file for details.\n */\n\n#include <BayesFilters/Gaussian.h>\n#include <BayesFilters/GaussianFilter.h>\n#include <BayesFilters/KFCorrection.h>\n#include <BayesFilters/KFPrediction.h>\n#include <BayesFilters/SimulatedLinearSensor.h>\n#include <BayesFilters/SimulatedStateModel.h>\n#include <BayesFilters/WhiteNoiseAcceleration.h>\n#include <BayesFilters/utils.h>\n\n#include <Eigen/Dense>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nclass KFSimulation : public GaussianFilter\n{\npublic:\n    KFSimulation\n    (\n        Gaussian& initial_state,\n        std::unique_ptr<GaussianPrediction> prediction,\n        std::unique_ptr<GaussianCorrection> correction,\n        std::size_t simulation_steps\n    ) noexcept :\n        GaussianFilter(initial_state, std::move(prediction), std::move(correction)),\n        simulation_steps_(simulation_steps)\n    { }\n\nprotected:\n    bool runCondition() override\n    {\n        if (getFilteringStep() < simulation_steps_)\n            return true;\n        else\n            return false;\n    }\n\n\n    std::vector<std::string> log_filenames(const std::string& prefix_path, const std::string& prefix_name) override\n    {\n        return  {prefix_path + \"/\" + prefix_name + \"_pred_mean\",\n                 prefix_path + \"/\" + prefix_name + \"_cor_mean\"};\n    }\n\n\n    void log() override\n    {\n        logger(predicted_state_.mean().transpose(), corrected_state_.mean().transpose());\n    }\n\nprivate:\n    std::size_t simulation_steps_;\n};\n\n\nint main()\n{\n    std::cout << \"Running a KF filter on a simulated target.\" << std::endl;\n    std::cout << \"Data is logged in the test folder with prefix testKF.\" << std::endl;\n\n    /* A set of parameters needed to run a Kalman filter in a simulated environment. */\n    Vector4d initial_simulated_state(10.0f, 0.0f, 10.0f, 0.0f);\n    std::size_t simulation_time = 100;\n\n\n    /* Step 1 - Initialization */\n\n    Gaussian initial_state(4);\n    Vector4d initial_mean(4.0f, 0.04f, 15.0f, 0.4f);\n    Matrix4d initial_covariance;\n    initial_covariance << pow(0.05, 2), 0,            0,            0,\n                          0,            pow(0.05, 2), 0,            0,\n                          0,            0,            pow(0.01, 2), 0,\n                          0,            0,            0,            pow(0.01, 2);\n    initial_state.mean() = initial_mean;\n    initial_state.covariance() = initial_covariance;\n\n\n    /* Step 2 - Prediction */\n\n    /* Step 2.1 - Define the state model. */\n\n    /* Initialize a white noise acceleration state model. */\n    double T = 1.0f;\n    double tilde_q = 10.0f;\n\n    std::unique_ptr<LinearStateModel> wna = utils::make_unique<WhiteNoiseAcceleration>(T, tilde_q);\n\n    /* Step 2.2 - Define the prediction step. */\n\n    /* Initialize the Kalman filter prediction step and pass the ownership of the state model. */\n    std::unique_ptr<KFPrediction> kf_prediction = utils::make_unique<KFPrediction>(std::move(wna));\n\n\n    /* Step 3 - Correction */\n\n    /* Step 3.1 - Define where the measurement are originated from (simulated in this case). */\n\n    /* Initialize simulated target model with a white noise acceleration. */\n    std::unique_ptr<StateModel> target_model = utils::make_unique<WhiteNoiseAcceleration>(T, tilde_q);\n    std::unique_ptr<SimulatedStateModel> simulated_state_model = utils::make_unique<SimulatedStateModel>(std::move(target_model), initial_simulated_state, simulation_time);\n    simulated_state_model->enable_log(\".\", \"testKF\");\n\n    /* Step 3.2 - Initialize a measurement model (a linear sensor reading x and y coordinates). */\n    std::unique_ptr<LinearMeasurementModel> simulated_linear_sensor = utils::make_unique<SimulatedLinearSensor>(std::move(simulated_state_model));\n    simulated_linear_sensor->enable_log(\".\", \"testKF\");\n\n    /* Step 3.3 - Initialize the Kalman filter correction step and pass the ownership of the measurement model. */\n    std::unique_ptr<KFCorrection> kf_correction = utils::make_unique<KFCorrection>(std::move(simulated_linear_sensor));\n\n\n    /* Step 4 - Assemble the Kalman filter. */\n    std::cout << \"Constructing Kalman filter...\" << std::flush;\n    KFSimulation kf(initial_state, std::move(kf_prediction), std::move(kf_correction), simulation_time);\n    kf.enable_log(\".\", \"testKF\");\n    std::cout << \"done!\" << std::endl;\n\n\n    /* Step 5 - Boot the filter. */\n    std::cout << \"Booting Kalman filter...\" << std::flush;\n    kf.boot();\n    std::cout << \"completed!\" << std::endl;\n\n\n    /* Step 6 - Run the filter and wait until it is closed. */\n    /* Note that since this is a simulation, the filter will end upon simulation termination. */\n    std::cout << \"Running Kalman filter...\" << std::flush;\n    kf.run();\n    std::cout << \"waiting...\" << std::flush;\n\n    if (!kf.wait())\n        return EXIT_FAILURE;\n\n    std::cout << \"completed!\" << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "e0e8f334b8246740c0e585995191d0fc2ba8a088", "size": 5019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_KF/main.cpp", "max_stars_repo_name": "vesor/bayes-filters-lib", "max_stars_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T02:52:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T07:06:39.000Z", "max_issues_repo_path": "test/test_KF/main.cpp", "max_issues_repo_name": "vesor/bayes-filters-lib", "max_issues_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_KF/main.cpp", "max_forks_repo_name": "vesor/bayes-filters-lib", "max_forks_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T08:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T08:20:28.000Z", "avg_line_length": 34.3767123288, "max_line_length": 172, "alphanum_fraction": 0.6567045228, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6095074778030949}}
{"text": "#include \"ode45.hpp\"\n\n#include <iostream>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n// Comment to disable test\n#define MAKE_TEST1\n#define MAKE_TEST2\n#define MAKE_TEST3\n#define MAKE_TEST4\n#define EIGEN_DONT_VECTORIZE \n#define EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT // I just added that to fix an error\nvoid test1() {\n#ifdef MAKE_TEST1\n    std::cout << \"Prey/Predator model test:\" << std::endl;\n    \n    // Prey/Predator model\n    const double alpha1 = 3;\n    const double alpha2 = 2;\n    const double beta1 = 0.1;\n    const double beta2 = 0.1;\n    auto f = [&alpha1, &alpha2, &beta1, &beta2] (const Eigen::VectorXd & y) {\n        Eigen::VectorXd temp = y;\n        temp(0) *= (alpha1 - beta1*y(1));\n        temp(1) *= (beta2*y(0) - alpha2);\n        return temp;\n    };\n    \n//     Eigen::VectorXd y0(2);\n    // or\n    Eigen::Vector2d y0;\n    y0 << 100, 5;\n    \n    const double T = 10;\n    \n    // Basic usage:\n    ode45<Eigen::VectorXd> O(f);\n//     O.options.do_statistics = true;\n    auto sol = O.solve(y0, T);\n    \n    // Print info\n//     O.print();\n    \n    // Print some info\n    std::cout << \"T = \" << sol.back().second << std::endl;\n    std::cout << \"y(T) = \" << std::endl << sol.back().first << std::endl;\n#endif\n}\n\nvoid test2() {\n#ifdef MAKE_TEST2\n    std::cout << \"Fundamental types test and validation:\" << std::endl;\n    \n    // Test class with fundamental types\n    auto f = [] (double y) { return 1 / y; };\n    \n    double y0 = 0.2;\n    // Large step size\n    const double T = 10000;\n    \n    // Quick syntax\n    ode45<double> O(f);\n//     O.options.do_statistics = true;\n    auto sol = O.solve(y0, T);\n    \n    // Print info\n//     O.print();\n    \n    // Print some info\n    std::cout << \"T = \" << sol.back().second << std::endl;\n    std::cout << \"y(T) = \" << std::endl << sol.back().first << std::endl;\n    auto y_ex = [] (double t) { return std::sqrt(2*t+0.04); };\n    std::cout << \"y_ex(T) = \" << std::endl << y_ex(T) << std::endl;\n#endif\n}\n\nvoid test3() {\n#ifdef MAKE_TEST3\n    std::cout << \"Multidimensional test:\" << std::endl;\n    \n    // Construct data for the IVP\n    double T = 1;\n    // Many dimensions\n    int n = 5;\n    \n    // Multidimensional rhs\n    Eigen::VectorXd y0(2*n);\n    for(int i = 0; i < n; ++i) {\n        y0(i)=(i+1.)/n;\n        y0(i+n)=-1;\n    }\n    \n    // Multidimensional rhs\n    auto f = [n] (Eigen::VectorXd y) {\n        Eigen::VectorXd fy(2*n);\n        \n        Eigen::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<double> 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<double> >  solver;\n        solver.analyzePattern(C);\n        solver.compute(C);\n        fy.tail(n) = solver.solve(g);\n        return fy;\n    };\n    \n    // Constructor:\n    ode45<Eigen::VectorXd> O(f);\n    \n    // Setup options\n    O.options.do_statistics = true;\n    \n    // Solve\n    auto sol = O.solve(y0, T);\n    \n    // Print info\n    O.print();\n\n    std::cout << \"T = \" << sol.back().second << std::endl;\n    std::cout << \"y(T) = \" << std::endl << sol.back().first << std::endl;\n#endif\n}\n\nvoid test4() {\n#ifdef MAKE_TEST4\n    std::cout << \"Stiff ode test:\" << std::endl;\n    \n    // Test class with fundamental types\n    auto f = [] (double y) { return y*(y - y*y); };\n    \n    // cf. http://ch.mathworks.com/company/newsletters/articles/stiff-differential-equations.html\n    double y0 = 0.0001; // try 0.01\n    // Large step size\n    const double T = 2 / y0;\n    \n    // Quick syntax\n    ode45<double> O(f);\n    O.options.do_statistics = true;\n    auto sol = O.solve(y0, T);\n    \n    // Print info\n    O.print();\n    \n    // Print some info\n    std::cout << \"T = \" << sol.back().second << std::endl;\n    std::cout << \"y(T) = \" << std::endl << sol.back().first << std::endl;\n    \n    \n//     for(auto v: sol) {\n//         std::cout << v.first << std::endl;\n//     }\n#endif\n}\n\nint main() {\n    \n    // Basic prey/predator test\n    test1();\n    \n    // Test double interface\n    test2();\n    \n    // A bit more involved example, also testing options and statistics\n    test3();\n    \n    // A bit more involved example, also testing options and statistics\n    test4();\n    \n    return 0;\n}\n", "meta": {"hexsha": "10a9c3b6393628f20ce53ed187e3975b06ce623e", "size": 4554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS13/templates_ps13/ode45_test.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/ode45_test.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/ode45_test.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": 24.3529411765, "max_line_length": 97, "alphanum_fraction": 0.5210803689, "num_tokens": 1392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.609490343857217}}
{"text": "#define BOOST_TEST_MODULE example\n#include <boost/test/included/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n\n//____________________________________________________________________________//\n\nBOOST_AUTO_TEST_CASE( test )\n{\n    double v1 = 1.23456e-10;\n    double v2 = 1.23457e-10;\n\n    BOOST_CHECK_CLOSE( v1, v2, 0.0001 );\n    // Absolute value of difference between these two values is 1e-15. They seems \n    // to be very close. But we want to checks that these values differ no more then 0.0001%\n    // of their value. And this test will fail at tolerance supplied.\n}\n\n//____________________________________________________________________________//\n", "meta": {"hexsha": "9ee7e53dfef238464533a4e84f58a563a91c833e", "size": 675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/test/doc/src/examples/example42.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "boost/libs/test/doc/src/examples/example42.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-03-31T12:26:25.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-15T10:50:18.000Z", "max_forks_repo_path": "boost/libs/test/doc/src/examples/example42.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 35.5263157895, "max_line_length": 92, "alphanum_fraction": 0.7748148148, "num_tokens": 148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6094903232021923}}
{"text": "/**\n * @file taylorode.cc\n * @brief NPDE homework TaylorODE\n * @author ?, Philippe Peter\n * @date 24.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"taylorode.h\"\n\n#include <Eigen/Core>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <vector>\n\nnamespace TaylorODE {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector2d PredPreyModel::f(const Eigen::Vector2d& y) const {\n  //====================\n  // Your code goes here\n  //====================\n  return y;\n}\n\nEigen::Vector2d PredPreyModel::df(const Eigen::Vector2d& y,\n                                  const Eigen::Vector2d& z) const {\n  //====================\n  // Your code goes here\n  //====================\n  return y;\n}\n\nEigen::Vector2d PredPreyModel::d2f(const Eigen::Vector2d& y,\n                                   const Eigen::Vector2d& z) const {\n  //====================\n  // Your code goes here\n  //====================\n  return y;\n}\n\nstd::vector<Eigen::Vector2d> SolvePredPreyTaylor(const PredPreyModel& model,\n                                                 double T,\n                                                 const Eigen::Vector2d& y0,\n                                                 unsigned int M) {\n  std::vector<Eigen::Vector2d> res;\n  res.reserve(M + 1);\n\n  //====================\n  // Your code goes here\n  //====================\n  return res;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\ndouble TestCvgTaylorMethod() {\n  // initialize parameters for the model:\n  double T = 10;               // final time\n  Eigen::Vector2d y0(100, 5);  // initial condition\n  Eigen::Vector2d yex(0.319465882659820,\n                      9.730809352326228);  // reference solution\n  double alpha1 = 3.0;\n  double alpha2 = 2.0;\n  double beta1 = 0.1;\n  double beta2 = 0.1;\n  PredPreyModel model(alpha1, alpha2, beta1, beta2);\n\n  // Initialize parameters for the convergence study\n  unsigned int M0 = 128;    // Minimum number of timesteps\n  unsigned int numRef = 8;  // Number of refinements\n\n  // Convergence study\n  Eigen::ArrayXd error(numRef);\n  Eigen::ArrayXd M(numRef);\n  // Run convergence study\n  //====================\n  // Your code goes here\n  //====================\n\n  PrintErrorTable(M, error);\n\n  // Estimate convergence rate based on linear regression\n  //====================\n  // Your code goes here\n  //====================\n  return 0.0;\n}\n/* SAM_LISTING_END_2 */\n\nvoid PrintErrorTable(const Eigen::ArrayXd& M, const Eigen::ArrayXd& error) {\n  std::cout << std::setw(15) << \"M\" << std::setw(15) << \"error\" << std::setw(15)\n            << \"rate\" << std::endl;\n\n  for (unsigned int i = 0; i < M.size(); ++i) {\n    std::cout << std::setw(15) << M(i) << std::setw(15) << error(i);\n    if (i > 0) {\n      std::cout << std::setw(15) << std::log2(error(i - 1) / error(i));\n    }\n    std::cout << std::endl;\n  }\n}\n\n}  // namespace TaylorODE\n", "meta": {"hexsha": "684d4e7dc57a0515142e543f025500677efba868", "size": 2841, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/TaylorODE/templates/taylorode.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/TaylorODE/templates/taylorode.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/TaylorODE/templates/taylorode.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": 26.8018867925, "max_line_length": 80, "alphanum_fraction": 0.5332629356, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.6094903193569486}}
{"text": "#include <math.h>\n#include <stdlib.h>\n#include <string>\n\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/opencv.hpp>\n//#include <opencv2/legacy/compat.hpp>\n\n#include \"dlib/opencv.h\"\n#include \"dlib/image_processing/frontal_face_detector.h\"\n#include \"dlib/image_processing/render_face_detections.h\"\n#include \"dlib/gui_widgets.h\"\n#include <dlib/image_processing.h>\n\n#include \"util.h\"\n#include \"constants.h\"\n#include \"faceDetection.h\"\n#include \"pupilDetection.h\"\n#include \"faceModel.h\"\nusing namespace dlib;\nvoid preprocessROI(cv::Mat& roi_eye) {\n\tGaussianBlur(roi_eye, roi_eye, cv::Size(3,3), 0, 0);\n\tequalizeHist( roi_eye, roi_eye );\n}\n\ndouble find_sigma(int ln, int lf, double Rn, double theta) {\n\tdouble dz=0;\n\tdouble sigma;\n\tdouble m1 = ((double)ln*ln)/((double)lf*lf);\n\tdouble m2 = (cos(theta))*(cos(theta));\n\n\tif (m2 == 1)\n\t{\n\t\tdz = sqrt(\t(Rn*Rn)/(m1 + (Rn*Rn))\t);\n\t}\n\tif (m2>=0 && m2<1)\n\t{\n\t\tdz = sqrt(\t((Rn*Rn) - m1 - 2*m2*(Rn*Rn) + sqrt(\t((m1-(Rn*Rn))*(m1-(Rn*Rn))) + 4*m1*m2*(Rn*Rn)\t))/ (2*(1-m2)*(Rn*Rn))\t);\n\t}\n\tsigma = acos(dz);\n\treturn sigma;\n}\n\nvoid faceModel::assign(full_object_detection shape , cv::Mat image, int mode = MODE_GAZE_VA) {\n\tassert(mode == MODE_GAZE_VA || mode == MODE_GAZE_QE);\n\tfaceShape = shape;\n\timage.copyTo(inputImage);\n\n\tdescriptors.clear();\n\n\tcomputePupil();\n\tcomputeNormal();\n\tcomputeGaze(mode);\n}\n\nvoid faceModel::computePupil() {\n\t// Computing left pupil\n\tstd::vector<cv::Point> leftEyePoints = getFeatureDescriptors(INDEX_LEFT_EYE);\n\trectLeftEye = cv::boundingRect(leftEyePoints)\n\troiLeftEye = inputImage(rectLeftEye)\n\tpreprocessROI(roiLeftEye);\n\tdescriptors.push_back(get_pupil_coordinates(roiLeftEye,rectLeftEye));\n\n\t// Computing right pupil\n\tstd::vector<cv::Point> rightEyePoints = getFeatureDescriptors(INDEX_RIGHT_EYE);\n\trectRightEye = cv::boundingRect(rightEyePoints)\n\troiRightEye = inputImage(rectRightEye)\n\tpreprocessROI(roiRightEye);\n\tdescriptors.push_back(get_pupil_coordinates(roiRightEye,rectRightEye));\n}\n\nvoid faceModel::computeNormal() {\n\tcv::Point midEye = get_mid_point(cv::Point(shape.part(39).x(), shape.part(39).y()),\n\t\tcv::Point(shape.part(40).x(), shape.part(40).y()));\n\n\tcv::Point mouth = get_mid_point(cv::Point(shape.part(48).x(), shape.part(48).y()),\n\t\tcv::Point(shape.part(54).x(), shape.part(54).y()));\n\n\tcv::Point noseTip = cv::Point(shape.part(30).x(), shape.part(30).y());\n\tcv::Point noseBase = cv::Point(shape.part(33).x(), shape.part(33).y());\n\n\t// symm angle - angle between the symmetry axis and the 'x' axis \n\tsymm_x = get_angle_between(noseBase, midEye);\n\t// tilt angle - angle between normal in image and 'x' axis\n\ttau = get_angle_between(noseBase, noseTip);\n\t// theta angle - angle between the symmetry axis and the image normal\n\ttheta = (abs(tau - symm_x)) * (PI/180.0);\n\n\t// sigma - slant angle\n\tsigma = find_sigma(get_distance(noseTip, noseBase), get_distance(midEye, mouth), Rn, theta);\n\n\tnormal[0] = (sin(sigma))*(cos((360 - tau)*(PI/180.0)));\n\tnormal[1] = (sin(sigma))*(sin((360 - tau)*(PI/180.0)));\n\tnormal[2] = -cos(sigma);\n\n\tpitch = acos(sqrt((normal[0]*normal[0] + normal[2]*normal[2])/(normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2])));\n\tif((noseTip.y - noseBase.y) < 0) {\n\t\tpitch = -pitch;\n\t}\n\n\tyaw = acos((abs(normal[2]))/(sqrt(normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2])));\n\tif((noseTip.x - noseBase.x) < 0) {\n\t\tyaw = -yaw;\n\t}\n}\n\nvoid computeGaze(int mode) {\n\tcompute_eye_gaze (FacePose* face_pose, dlib::full_object_detection shape, cv::Rect rect, cv::Point pupil, double mag_CP, double mag_LR, double mag_CR, double mag_CM, double theta, int mode, std::vector<double>& vec_CP) {\n}\n\nvoid faceModel::setOrigin(cv::Point origin) {\n\tthis.origin = origin;\n}\n\nvoid faceModel::setOrigin(int mode) {\n\tassert(mode == ORIGIN_IMAGE || mode == ORIGIN_FACE_CENTRE);\n\n\tif (mode == ORIGIN_IMAGE) {\n\t\torigin.x = 0;\n\t\torigin.y = 0;\n\t}\n\telse if (mode == ORIGIN_FACE_CENTRE) {\n\t\torigin.x = shape.part(30).x();\n\t\torigin.y = shape.part(30).y();\n\t}\n}\n\nstd::vector<double> getNormal() {\n\treturn normal;\n}\n\ncv::Point faceModel::getPupil(int mode) {\n\tassert(mode == INDEX_LEFT_EYE_PUPIL || mode == INDEX_RIGHT_EYE_PUPIL);\n\treturn descriptors[mode - INDEX_LEFT_EYE_PUPIL];\n}\n\nstd::vector<double> getGaze() {\n\treturn gaze;\n}\n\nstd::vector<cv::Point> faceModel::getDescriptors(int index) {\n\tassert(index == INDEX_LEFT_EYE || index == INDEX_RIGHT_EYE || index == INDEX_LEFT_EYE_BROW || index == INDEX_RIGHT_EYE_BROW \n\t\t|| index == INDEX_NOSE_UPPER || index == INDEX_NOSE_LOWER || index == INDEX_MOUTH_OUTER || index == INDEX_MOUTH_INNER); \n\n\tif (index == INDEX_LEFT_EYE) {\n\t\tstd::vector<cv::Point> leftEyePoints;\n\t\tfor (int i=36; i<=41; i++){\n\t\t\tleftEyePoints.push_back(cv::Point(faceShape.part(i).x(), faceShape.part(i).y()));\n\t\t}\n\t\treturn leftEyePoints;\n\t}\n\n\telse if (index == INDEX_RIGHT_EYE) {\n\t\tstd::vector<cv::Point> rightEyePoints;\n\t\tfor (int i=42; i<=47; i++){\n\t\t\trightEyePoints.push_back(cv::Point(faceShape.part(i).x(), faceShape.part(i).y()));\n\t\t}\n\t\treturn rightEyePoints;\n\t}\n\n\telse if (index == INDEX_LEFT_EYE_BROW) {\n\t\tstd::vector<cv::Point> leftEyeBrowPoints;\n\t\tfor (int i=17; i<=21; i++){\n\t\t\tleftEyeBrowPoints.push_back(cv::Point(faceShape.part(i).x(), faceShape.part(i).y()));\n\t\t}\n\t\treturn leftEyeBrowPoints;\n\t}\n\n\telse if (index == INDEX_RIGHT_EYE_BROW) {\n\t\tstd::vector<cv::Point> rightEyeBrowPoints;\n\t\tfor (int i=22; i<=26; i++){\n\t\t\trightEyeBrowPoints.push_back(cv::Point(faceShape.part(i).x(), faceShape.part(i).y()));\n\t\t}\n\t\treturn rightEyeBrowPoints;\n\t}\n\n\telse if (index == INDEX_NOSE_UPPER)  {\n\t\tstd::vector<cv::Point> noseUpperPoints;\n\t\tfor (int i=27; i<=30; i++){\n\t\t\tnoseUpperPoints.push_back(cv::Point(faceShape.part(i).x(), faceShape.part(i).y()));\n\t\t}\n\t\treturn noseUpperPoints;\n\t}\n\n\telse if (index == INDEX_NOSE_LOWER) {\t\t\n\t\tstd::vector<cv::Point> noseLowerPoints;\n\t\tfor (int i=31; i<=35; i++){\n\t\t\tnoseLowerPoints.push_back(cv::Point(faceShape.part(i).x(), faceShape.part(i).y()));\n\t\t}\n\t\treturn noseLowerPoints;\n\t}\n\n\telse if (index == INDEX_MOUTH_OUTER) {\n\t\tstd::vector<cv::Point> mouthOuterPoints;\n\t\tfor (int i=48; i<59; i++){\n\t\t\tmouthOuterPoints.push_back(cv::Point(faceShape.part(i).x(), faceShape.part(i).y()));\n\t\t}\n\t\treturn mouthOuterPoints;\n\t}\n\n\telse if (index == INDEX_MOUTH_INNER) {\n\t\tstd::vector<cv::Point> mouthInnerPoints;\n\t\tfor (int i=60; i<=67; i++){\n\t\t\tmouthInnerPoints.push_back(cv::Point(faceShape.part(i).x(), faceShape.part(i).y()));\n\t\t}\n\t\treturn mouthInnerPoints;\n\t}\n}\n", "meta": {"hexsha": "f895b2fa44cfa65f216a455c0b324dbdd722cfe3", "size": 6424, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/faceModel.cpp", "max_stars_repo_name": "vmthanh/Eye-Tracking", "max_stars_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/faceModel.cpp", "max_issues_repo_name": "vmthanh/Eye-Tracking", "max_issues_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/faceModel.cpp", "max_forks_repo_name": "vmthanh/Eye-Tracking", "max_forks_repo_head_hexsha": "0004fb2e29d90fdcc986cc52e335fa5fe2c0f88d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7368421053, "max_line_length": 221, "alphanum_fraction": 0.6833748443, "num_tokens": 1992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.6094701212386278}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <vector>\n#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <string.h>\n#include <fstream>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/index/rtree.hpp>\n\n// #define DATASET_SIZE 1000000\n#define DIMENTION 2\n#define ELIPSON 30\n#define MIN_POINTS 10\n\nusing namespace std;\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\ntypedef bg::model::point<float, 2, bg::cs::cartesian> dataPoint;\ntypedef bg::model::box<dataPoint> box;\ntypedef std::pair<box, int> value;\n\nclass DBSCAN {\n private:\n  double** dataset;\n  int elipson;\n  int minPoints;\n  int cluster;\n  int* clusters;\n  double getDistance(int center, int neighbor);\n  vector<int> findNeighbors(int pos);\n  void expandCluster(int pointId, vector<int> &neighbors);\n  bgi::rtree<value, bgi::quadratic<4>> rtree;\n\n public:\n  DBSCAN(double ** dataset);\n  void run();\n  void results();\n};\n\nint main(int, char **) {\n  // Generate random datasets\n  double **dataset =\n      (double **)malloc(sizeof(double *) * DATASET_SIZE);\n  for (int i = 0; i < DATASET_SIZE; i++) {\n    dataset[i] = (double *)malloc(sizeof(double) * DIMENTION);\n  }\n\n  // Import Dataset from a file\n  ifstream file(\"../dataset/dataset.txt\");\n  if (file.is_open()) {\n    string token;\n    int rowCount = 0;\n    while (getline(file, token)) {\n      int colCount = 0;\n      char* x = (char*)token.c_str();\n      char* field = strtok(x, \",\");\n      double tmp;\n      sscanf(field, \"%lf\", &tmp);\n      dataset[rowCount][colCount] = tmp;\n      while (field) {\n        colCount++;\n        if(colCount == DIMENTION) break;\n        field = strtok(NULL, \",\");\n        if (field!=NULL) {\n          double tmp;\n          sscanf(field,\"%lf\",&tmp);\n          dataset[rowCount][colCount] = tmp;\n        }\n      }\n      rowCount++;\n      if(rowCount == DATASET_SIZE) break;\n    }\n    file.close();\n  }\n\n  // Initialize DBSCAN with dataset\n  DBSCAN dbscan(dataset);\n\n  // Run the DBSCAN algorithm\n  dbscan.run();\n\n  // Print the cluster results of DBSCAN\n  dbscan.results();\n\n  return 0;\n}\n\nDBSCAN::DBSCAN(double **loadData) {\n\n  dataset =\n      (double **)malloc(sizeof(double *) * DATASET_SIZE);\n  for (int i = 0; i < DATASET_SIZE; i++) {\n    dataset[i] = (double *)malloc(sizeof(double) * DIMENTION);\n  }\n  clusters = (int *)malloc(sizeof(int) * DATASET_SIZE);\n  elipson = ELIPSON;\n  minPoints = MIN_POINTS;\n  cluster = 0;\n\n  for (int i = 0; i < DATASET_SIZE; i++) {\n    dataset[i][0] = loadData[i][0];\n    dataset[i][1] = loadData[i][1];\n    clusters[i] = 0;\n  }\n\n  // Create an Rtree of the dataset\n  for (int i = 0; i < DATASET_SIZE; i++) {\n    // create a box for each points\n    box b(dataPoint(dataset[i][0], dataset[i][1]),\n          dataPoint(dataset[i][0], dataset[i][1]));\n    // insert points to the rtree\n    rtree.insert(std::make_pair(b, i));\n    \n  }\n}\n\ndouble DBSCAN::getDistance(int center, int neighbor) {\n  int dist = (dataset[center][0] - dataset[neighbor][0]) *\n                 (dataset[center][0] - dataset[neighbor][0]) +\n             (dataset[center][1] - dataset[neighbor][1]) *\n                 (dataset[center][1] - dataset[neighbor][1]);\n\n  return sqrt(dist);\n}\n\nvoid DBSCAN::run() {\n  // Neighbors of the point\n  vector<int> neighbors;\n\n  for (int i = 0; i < DATASET_SIZE; i++) {\n    \n    if (clusters[i] == 0) {\n\n      // Find neighbors of point P\n      neighbors = findNeighbors(i);\n\n      // Mark noise points\n      if (neighbors.size() < minPoints) {\n        clusters[i] = -1;\n      } else {\n        // Increment cluster and initialize it will the current point\n        cluster++;\n\n        clusters[i] = cluster; \n\n        // Expand the neighbors of point P\n        for (int j = 0; j < neighbors.size(); j++) {\n\n          // Mark neighbour as point Q\n          int dataIndex = neighbors[j];\n\n          if(clusters[dataIndex] == -1) {\n            clusters[dataIndex] = cluster;\n          } else if (clusters[dataIndex] == 0) {\n\n            clusters[dataIndex] = cluster;\n            \n            // Expand more neighbors of point Q\n            vector<int> moreNeighbors;\n            moreNeighbors = findNeighbors(dataIndex);\n\n            // Continue when neighbors point is higher than minPoint threshold\n\n            if (moreNeighbors.size() >= minPoints) {\n              // Check if neighbour of Q already exists in neighbour of P\n              for (int x = 0; x < moreNeighbors.size(); x++) {\n                bool doesntExist = true;\n                for (int y = 0; y < neighbors.size(); y++) {\n                  if (moreNeighbors[x] == neighbors[y]) {\n                    doesntExist = false;\n                    break;\n                  }\n                }\n\n                // If neighbour doesn't exist, add to neighbor list\n                if (doesntExist) {\n                  neighbors.push_back(moreNeighbors[x]);\n                }\n              }\n            }\n          }         \n      }\n    }\n  }\n}\n}\n\nvoid DBSCAN::results() {\n  printf(\"Number of clusters: %d\\n\", cluster);\n  int noises = 0;\n  for(int x = 1; x <= cluster; x++) {\n    int count = 0;\n    for(int i = 0; i < DATASET_SIZE; i++) {\n      if(clusters[i] == x) {\n        count++;\n      }\n      if(clusters[i] == -1) {\n        noises++;\n      }\n    }\n    printf(\"Cluster %d has %d data\\n\", x, count);\n  }\n  printf(\"Noises: %d\\n\", noises);\n  \n}\n\nvector<int> DBSCAN::findNeighbors(int pos) {\n\n  vector<int> neighbors;\n  vector<value> result_n;\n\n  // Create a search box for the given poiny\n  box searchBox(dataPoint(dataset[pos][0] - elipson, dataset[pos][1] - elipson),\n                dataPoint(dataset[pos][0] + elipson, dataset[pos][1] + elipson));\n\n  // Query the intersection of search box on Rtree\n  rtree.query(bgi::intersects(searchBox), std::back_inserter(result_n));\n\n  // collect the points of box\n  vector<int> pointsInBox = {};\n  for (value pair : result_n) pointsInBox.push_back(pair.second);\n\n  // Compute the distance only with points in a box\n  for (int x = 0; x < pointsInBox.size(); x++) {\n    // Compute neighbor points\n    double distance = getDistance(pos, pointsInBox[x]);\n    if (distance <= elipson && pos != pointsInBox[x]) {\n      neighbors.push_back(pointsInBox[x]);\n    }\n  }\n\n  return neighbors;\n\n}", "meta": {"hexsha": "78d5e23adfba3baf32a9f62944a4da4aa45f6221", "size": 6339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dbscan-with-intensive-data/Dbscan_Rtree_boost.cpp", "max_stars_repo_name": "l3lackcurtains/DBSCAN-variants", "max_stars_repo_head_hexsha": "c207a54300ce7cd2525cba94040a3bd4be26401c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-28T06:49:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-28T06:49:23.000Z", "max_issues_repo_path": "dbscan-with-intensive-data/Dbscan_Rtree_boost.cpp", "max_issues_repo_name": "l3lackcurtains/DBSCAN-variants", "max_issues_repo_head_hexsha": "c207a54300ce7cd2525cba94040a3bd4be26401c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T20:56:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T06:52:33.000Z", "max_forks_repo_path": "dbscan-with-intensive-data/Dbscan_Rtree_boost.cpp", "max_forks_repo_name": "l3lackcurtains/DBSCAN-variants", "max_forks_repo_head_hexsha": "c207a54300ce7cd2525cba94040a3bd4be26401c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.194214876, "max_line_length": 81, "alphanum_fraction": 0.5795866856, "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.6094701108232569}}
{"text": "/*\r\nModified BSD License\r\n\r\nThis file is a part of Statistical package and originates from:\r\nhttp://sf.net/projects/enjomitchsorbit\r\n\r\nCopyright (c) 2012, Szymon \"Enjo\" Ender\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are met:\r\n    * Redistributions of source code must retain the above copyright\r\n      notice, this list of conditions and the following disclaimer.\r\n    * Redistributions in binary form must reproduce the above copyright\r\n      notice, this list of conditions and the following disclaimer in the\r\n      documentation and/or other materials provided with the distribution.\r\n    * Neither the name of the <organization> nor the\r\n      names of its contributors may be used to endorse or promote products\r\n      derived from this software without specific prior written permission.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\nDISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\r\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n*/\r\n\r\n#include \"EigenEigen3.hpp\"\r\n#include \"../Matrix.hpp\"\n#include \"../../Util/VecD.hpp\"\n#include <Util/Except.hpp>\n#include <Util/CharManipulations.hpp>\n\n#include <STD/VectorCpp.hpp>\n\n//#define EIGEN_USE_MKL_ALL\n//#define EIGEN_USE_BLAS // Enables openblas64 - somewhat slower\n//#define EIGEN_USE_LAPACKE // Don't use currently\n#include <Eigen/Dense>\n\n#include <Util/CoutBuf.hpp>\n\nusing namespace std;\nusing namespace EnjoLib;\n//using namespace Eigen;\r\n\nEigenEigen3::~EigenEigen3(){} \r\nEigenEigen3::EigenEigen3(){}\r\n\nstatic Eigen::MatrixXd ConvertMatrix( const Matrix & m )\n{\n    const int nrows = m.GetNRows();\n    const int ncols = m.GetNCols();\n    Eigen::MatrixXd mateig(nrows, ncols);\n    for ( int i = 0; i < nrows; ++i ) for ( int j = 0; j < ncols; ++j )\n            mateig(i, j) = m.at(i).at(j);\n\n    return mateig;\n}\r\n\r\nstd::vector<EigenValueVector> EigenEigen3::GetEigenValVecClient( const Matrix & m ) const\r\n{\r\n    std::vector<EigenValueVector> ret;\n    ret.reserve(m.GetNRows());\n    \n    //cout << \"M = \" << m.GetNCols() << \", \" << m.GetNRows() << endl;\n\n    Eigen::EigenSolver<Eigen::MatrixXd> es;\n    const Eigen::MatrixXd & matE = ConvertMatrix(m);\n    //cout << \"Pre\\n\" << m.Print() << endl;\n    es.compute(matE, /* computeEigenvectors = */ true);\n    //cout << \"Post\" << endl;\n    if (es.info() != Eigen::ComputationInfo::Success)\n    {\n        ELO\n        LOG << \"Eigenvalue Calculation not successful: \" << es.info() << NL3;\n        //cout << m.Print() << endl;\n        throw EnjoLib::ExceptRuntimeError(\"Eigenvalue Calculation not successful \" + CharManipulations().ToStr(es.info()));\n        LOG << \"After throw: \" << es.info() << NL3;\n    }\n\n    const auto & eval  = es.eigenvalues();\n    const auto & evect = es.eigenvectors();\n    for ( int i = 0; i < m.GetNRows(); ++i )\n    {\n        const auto & evali = eval(i);\n        const double eigenValue = evali.real();\n        VecD eigenVector;\n        eigenVector.reserve(m.GetNCols());\n\n        for ( int j = 0; j < m.GetNCols(); ++j )\n        {\n            const double val = evect(j, i).real(); // Transposition (j, i) due to internal Eigen storage!\n            eigenVector.push_back(val);\n        }\n\n        ret.push_back( EigenValueVector(eigenValue, eigenVector) );\n    }\n    return ret;\r\n}\n", "meta": {"hexsha": "a1c2b78a012ac9bedafb9a7928a979b1ae3bb511", "size": 3936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/Statistical/3rdParty/EigenEigen3.cpp", "max_stars_repo_name": "hlp2/EnjoLib", "max_stars_repo_head_hexsha": "6bb69d0b00e367a800b0ef2804808fd1303648f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/Statistical/3rdParty/EigenEigen3.cpp", "max_issues_repo_name": "hlp2/EnjoLib", "max_issues_repo_head_hexsha": "6bb69d0b00e367a800b0ef2804808fd1303648f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Statistical/3rdParty/EigenEigen3.cpp", "max_forks_repo_name": "hlp2/EnjoLib", "max_forks_repo_head_hexsha": "6bb69d0b00e367a800b0ef2804808fd1303648f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1320754717, "max_line_length": 123, "alphanum_fraction": 0.6783536585, "num_tokens": 955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6094026567139437}}
{"text": "// Copyright (c) 2018-2021 FRC Team 3512. All Rights Reserved.\n\n#pragma once\n\n#include <array>\n#include <chrono>\n#include <functional>\n#include <tuple>\n#include <vector>\n\n#include <Eigen/Core>\n#include <frc/estimator/ExtendedKalmanFilter.h>\n#include <frc/kinematics/DifferentialDriveOdometry.h>\n#include <frc/logging/CSVLogFile.h>\n#include <frc/system/plant/LinearSystemId.h>\n#include <frc/trajectory/Trajectory.h>\n#include <units/angle.h>\n#include <units/angular_velocity.h>\n#include <units/curvature.h>\n#include <units/length.h>\n#include <units/time.h>\n#include <units/velocity.h>\n#include <wpi/math>\n#include <wpi/mutex.h>\n\n#include \"Constants.hpp\"\n\nnamespace frc3512 {\n\nclass DrivetrainController {\npublic:\n    class State {\n    public:\n        static constexpr int kX = 0;\n        static constexpr int kY = 1;\n        static constexpr int kHeading = 2;\n        static constexpr int kLeftVelocity = 3;\n        static constexpr int kRightVelocity = 4;\n        static constexpr int kLeftPosition = 5;\n        static constexpr int kRightPosition = 6;\n        static constexpr int kLeftVoltageError = 7;\n        static constexpr int kRightVoltageError = 8;\n        static constexpr int kAngularVelocityError = 9;\n    };\n\n    class Input {\n    public:\n        static constexpr int kLeftVoltage = 0;\n        static constexpr int kRightVoltage = 1;\n    };\n\n    class LocalOutput {\n    public:\n        static constexpr int kHeading = 0;\n        static constexpr int kLeftPosition = 1;\n        static constexpr int kRightPosition = 2;\n    };\n\n    class GlobalOutput {\n    public:\n        static constexpr int kX = 0;\n        static constexpr int kY = 1;\n        static constexpr int kHeading = 2;\n        static constexpr int kLeftPosition = 3;\n        static constexpr int kRightPosition = 4;\n        static constexpr int kAngularVelocity = 5;\n    };\n\n    /**\n     * Constructs a drivetrain controller with the given coefficients.\n     *\n     * @param Qelems The maximum desired error tolerance for each state.\n     * @param Relems The maximum desired control effort for each input.\n     * @param dt     Discretization timestep.\n     */\n    DrivetrainController(const std::array<double, 5>& Qelems,\n                         const std::array<double, 2>& Relems,\n                         units::second_t dt);\n\n    DrivetrainController(const DrivetrainController&) = delete;\n    DrivetrainController& operator=(const DrivetrainController&) = delete;\n\n    void Enable();\n    void Disable();\n    bool IsEnabled() const;\n\n    void SetWaypoints(const std::vector<frc::Pose2d>& waypoints);\n\n    /**\n     * Returns whether the drivetrain controller is at the goal waypoint.\n     */\n    bool AtGoal() const;\n\n    /**\n     * Set local measurements.\n     *\n     * @param heading       Angle of the robot.\n     * @param leftPosition  Encoder count of left side in meters.\n     * @param rightPosition Encoder count of right side in meters.\n     */\n    void SetMeasuredLocalOutputs(units::radian_t heading,\n                                 units::meter_t leftPosition,\n                                 units::meter_t rightPosition);\n\n    /**\n     * Set global measurements.\n     *\n     * @param x             X position of the robot in meters.\n     * @param y             Y position of the robot in meters.\n     * @param heading       Angle of the robot.\n     * @param leftPosition  Encoder count of left side in meters.\n     * @param rightPosition Encoder count of right side in meters.\n     * @param angularVelocity Angular velocity of the robot in radians per\n     * second.\n     */\n    void SetMeasuredGlobalOutputs(units::meter_t x, units::meter_t y,\n                                  units::radian_t heading,\n                                  units::meter_t leftPosition,\n                                  units::meter_t rightPosition,\n                                  units::radians_per_second_t angularVelocity);\n\n    /**\n     * Returns the drivetrain's plant.\n     */\n    frc::LinearSystem<2, 2, 2> GetPlant() const;\n\n    /**\n     * Returns the current references.\n     *\n     * x, y, heading, left velocity, and right velocity.\n     */\n    const Eigen::Matrix<double, 5, 1>& GetReferences() const;\n\n    /**\n     * Returns the current state estimate.\n     *\n     * x, y, heading, left position, left velocity, right position,\n     * right velocity, left voltage error, right voltage error, and angle error.\n     */\n    const Eigen::Matrix<double, 10, 1>& GetStates() const;\n\n    /**\n     * Returns the control inputs.\n     *\n     * left voltage and right voltage.\n     */\n    Eigen::Matrix<double, 2, 1> GetInputs() const;\n\n    /**\n     * Returns the currently set local outputs.\n     *\n     * heading, left position, left velocity, right position,\n     * right velocity, and angular velocity.\n     */\n    const Eigen::Matrix<double, 3, 1>& GetOutputs() const;\n\n    /**\n     * Returns the estimated outputs based on the current state estimate.\n     *\n     * This provides only local measurements.\n     */\n    Eigen::Matrix<double, 3, 1> EstimatedLocalOutputs() const;\n\n    /**\n     * Returns the estimated outputs based on the current state estimate.\n     *\n     * This provides global measurements (including pose).\n     */\n    Eigen::Matrix<double, 6, 1> EstimatedGlobalOutputs() const;\n\n    /**\n     * Executes the control loop for a cycle.\n     *\n     * @param dt Timestep between each Update() call\n     */\n    void Update(units::second_t dt, units::second_t elapsedTime);\n\n    /**\n     * Resets any internal state.\n     */\n    void Reset();\n\n    /**\n     * Resets any internal state.\n     *\n     * @param initialPose Initial pose for state estimate.\n     */\n    void Reset(const frc::Pose2d& initialPose);\n\n    Eigen::Matrix<double, 2, 1> Controller(\n        const Eigen::Matrix<double, 10, 1>& x,\n        const Eigen::Matrix<double, 5, 1>& r);\n\n    static Eigen::Matrix<double, 10, 1> Dynamics(\n        const Eigen::Matrix<double, 10, 1>& x,\n        const Eigen::Matrix<double, 2, 1>& u);\n\n    static Eigen::Matrix<double, 3, 1> LocalMeasurementModel(\n        const Eigen::Matrix<double, 10, 1>& x,\n        const Eigen::Matrix<double, 2, 1>& u);\n\n    static Eigen::Matrix<double, 6, 1> GlobalMeasurementModel(\n        const Eigen::Matrix<double, 10, 1>& x,\n        const Eigen::Matrix<double, 2, 1>& u);\n\nprivate:\n    // Robot radius\n    static constexpr auto rb = Constants::Drivetrain::kWidth / 2.0;\n\n    static frc::LinearSystem<2, 2, 2> m_plant;\n\n    // The current sensor measurements\n    Eigen::Matrix<double, 3, 1> m_localY;\n    Eigen::Matrix<double, 6, 1> m_globalY;\n\n    // Design observer\n    // States: [x position, y position, heading,\n    //          left velocity, right velocity,\n    //          left position, right position,\n    //          left voltage error, right voltage error, angle error]\n    //\n    // Inputs: [left voltage, right voltage]\n    //\n    // Outputs (local): [left position, right position,\n    //                   angular velocity]\n    //\n    // Outputs (global): [x position, y position, heading,\n    //                    left position, right position,\n    //                    angular velocity]\n    frc::ExtendedKalmanFilter<10, 2, 3> m_observer{\n        Dynamics,\n        LocalMeasurementModel,\n        {0.002, 0.002, 0.0001, 1.5, 1.5, 0.5, 0.5, 10.0, 10.0, 2.0},\n        {0.0001, 0.005, 0.005},\n        Constants::kDt};\n\n    // XXX: For testing only. This is used to verify the EKF pose because\n    // DifferentialDriveOdometry is known to work on other robots.\n    frc::DifferentialDriveOdometry m_odometer{frc::Rotation2d(0_rad)};\n\n    // Design controller\n    // States: [x position, y position, heading, left velocity, right velocity]\n    Eigen::Matrix<double, 5, 2> m_B;\n    Eigen::Matrix<double, 2, 5> m_K0;\n    Eigen::Matrix<double, 2, 5> m_K1;\n\n    // Controller reference\n    Eigen::Matrix<double, 5, 1> m_r;\n\n    Eigen::Matrix<double, 5, 1> m_nextR;\n    Eigen::Matrix<double, 2, 1> m_cappedU;\n\n    frc::Trajectory m_trajectory;\n    frc::Pose2d m_goal;\n\n    wpi::mutex m_trajectoryMutex;\n\n    bool m_atReferences = false;\n    bool m_isEnabled = false;\n\n    // The loggers that generates the comma separated value files\n    frc::CSVLogFile positionLogger{\"Drivetrain Positions\",\n                                   \"Estimated X (m)\",\n                                   \"Estimated Y (m)\",\n                                   \"X Ref (m)\",\n                                   \"Y Ref (m)\",\n                                   \"Measured Left Position (m)\",\n                                   \"Measured Right Position (m)\",\n                                   \"Estimated Left Position (m)\",\n                                   \"Estimated Right Position (m)\",\n                                   \"Odometry X (m)\",\n                                   \"Odometry Y (m)\"};\n    frc::CSVLogFile angleLogger{\"Drivetrain Angles\", \"Measured Heading (rad)\",\n                                \"Estimated Heading (rad)\", \"Heading Ref (rad)\",\n                                \"Angle Error (rad)\"};\n    frc::CSVLogFile velocityLogger{\"Drivetrain Velocities\",\n                                   \"Measured Left Velocity (m/s)\",\n                                   \"Measured Right Velocity (m/s)\",\n                                   \"Estimated Left Vel (m/s)\",\n                                   \"Estimated Right Vel (m/s)\",\n                                   \"Left Vel Ref (m/s)\",\n                                   \"Right Vel Ref (m/s)\"};\n    frc::CSVLogFile voltageLogger{\n        \"Drivetrain Voltages\",     \"Left Voltage (V)\",\n        \"Right Voltage (V)\",       \"Left Voltage Error (V)\",\n        \"Right Voltage Error (V)\", \"Battery Voltage (V)\"};\n    frc::CSVLogFile errorCovLogger{\n        \"Drivetrain Error Covariances\",\n        \"X Cov (m^2)\",\n        \"Y Cov (m^2)\",\n        \"Heading Cov (rad^2)\",\n        \"Left Vel Cov ((m/s)^2)\",\n        \"Right Vel Cov ((m/s)^2)\",\n        \"Left Pos Cov (m^2)\",\n        \"Right Pos Cov (m^2)\",\n        \"Left Voltage Error Cov (V^2)\",\n        \"Right Voltage Error Cov (V^2)\",\n        \"Angle Error Cov (rad^2)\",\n    };\n\n    /**\n     * Constrains theta to within the range (-pi, pi].\n     *\n     * @param theta Angle to normalize\n     */\n    static constexpr double NormalizeAngle(double theta) {\n        // Constrain theta to within (-3pi, pi)\n        const int n_pi_pos = (theta + wpi::math::pi) / 2.0 / wpi::math::pi;\n        theta -= n_pi_pos * 2.0 * wpi::math::pi;\n\n        // Cut off the bottom half of the above range to constrain within\n        // (-pi, pi]\n        const int n_pi_neg = (theta - wpi::math::pi) / 2.0 / wpi::math::pi;\n        theta -= n_pi_neg * 2.0 * wpi::math::pi;\n\n        return theta;\n    }\n\n    /**\n     * Converts velocity and curvature of drivetrain into left and right wheel\n     * velocities.\n     *\n     * @param velocity Linear velocity of drivetrain chassis.\n     * @param curvature Curvature of drivetrain arc.\n     * @param trackWidth Track width of drivetrain.\n     */\n    static constexpr std::tuple<units::meters_per_second_t,\n                                units::meters_per_second_t>\n    ToWheelVelocities(units::meters_per_second_t velocity,\n                      units::curvature_t curvature, units::meter_t trackWidth) {\n        // clang-format off\n        // v = (v_r + v_l) / 2     (1)\n        // w = (v_r - v_l) / (2r)  (2)\n        // k = w / v               (3)\n        //\n        // v_l = v - wr\n        // v_l = v - (vk)r\n        // v_l = v(1 - kr)\n        //\n        // v_r = v + wr\n        // v_r = v + (vk)r\n        // v_r = v(1 + kr)\n        // clang-format on\n        auto vl = velocity * (1 - (curvature / 1_rad * trackWidth / 2.0));\n        auto vr = velocity * (1 + (curvature / 1_rad * trackWidth / 2.0));\n        return {vl, vr};\n    }\n\n    static void ScaleCapU(Eigen::Matrix<double, 2, 1>* u);\n};\n}  // namespace frc3512\n", "meta": {"hexsha": "517998658a1ed8d4fe0faaa066950c5697f5e003", "size": 11838, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/controllers/DrivetrainController.hpp", "max_stars_repo_name": "frc3512/Robot-2019", "max_stars_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T01:06:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T15:18:49.000Z", "max_issues_repo_path": "src/main/include/controllers/DrivetrainController.hpp", "max_issues_repo_name": "frc3512/Robot-2019", "max_issues_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main/include/controllers/DrivetrainController.hpp", "max_forks_repo_name": "frc3512/Robot-2019", "max_forks_repo_head_hexsha": "376a94f138562f8af59215f5e21a41a68b3f5cd2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T16:21:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-14T16:21:42.000Z", "avg_line_length": 33.6306818182, "max_line_length": 80, "alphanum_fraction": 0.5707045109, "num_tokens": 2914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.609368882165832}}
{"text": "#include \"eigenvalues.h\"\n#include <Eigen/Eigenvalues>\n\n/*!\n * Adjust a matrix so that its eigenvalues are less than a given magnitude.\n * Moved to its on CU because this doesn't change often and takes like 2 minutes to recompile on O3 :P\n */\ntemplate<typename T>\nDenseMatrix<T> constrainEigenvalueMagnitude(const DenseMatrix<T> &m, T magnitude)\n{\n  Eigen::EigenSolver<DenseMatrix<T>> eigSolver(m);\n  using MatCT = Eigen::Matrix<std::complex<T>, Eigen::Dynamic, Eigen::Dynamic>;\n  MatCT D = eigSolver.eigenvalues().asDiagonal();\n  MatCT V = eigSolver.eigenvectors();\n\n  for(s64 i = 0; i < D.rows(); i++) {\n    T eigMag = std::abs(D(i,i));\n    if(eigMag > magnitude)\n      D(i,i) = magnitude * D(i,i) / eigMag;\n  }\n\n  MatCT restored = V * D * V.inverse(); // slow, but this matrix is small.\n  DenseMatrix<T> result(m.rows(), m.rows());\n  for(s64 i = 0; i < m.rows(); i++) {\n    for(s64 j = 0; j < m.rows(); j++) {\n      result(i,j) = std::real(restored(i,j));\n    }\n  }\n\n  return result;\n}\n\ntemplate DenseMatrix<float> constrainEigenvalueMagnitude(const DenseMatrix<float> &m, float magnitude);\ntemplate DenseMatrix<double> constrainEigenvalueMagnitude(const DenseMatrix<double> &m, double magnitude);", "meta": {"hexsha": "40249922e879e4410553e3efd52c6f30dc48c875", "size": 1199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third-party/JCQP/eigenvalues.cpp", "max_stars_repo_name": "zbwu/Cheetah-Software", "max_stars_repo_head_hexsha": "286ca1eac576c61df76c71979f4e8940537ee084", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-18T03:36:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T03:36:47.000Z", "max_issues_repo_path": "third-party/JCQP/eigenvalues.cpp", "max_issues_repo_name": "zbwu/Cheetah-Software", "max_issues_repo_head_hexsha": "286ca1eac576c61df76c71979f4e8940537ee084", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third-party/JCQP/eigenvalues.cpp", "max_forks_repo_name": "zbwu/Cheetah-Software", "max_forks_repo_head_hexsha": "286ca1eac576c61df76c71979f4e8940537ee084", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2647058824, "max_line_length": 106, "alphanum_fraction": 0.6763969975, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6093688814031518}}
{"text": "/**\n * @date Tue Apr 2 21:08:00 2013 +0200\n * @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include <boost/make_shared.hpp>\n#include <bob.math/inv.h>\n#include <bob.math/lu.h>\n#include <bob.math/stats.h>\n\n#include <bob.learn.linear/whitening.h>\n\nnamespace bob { namespace learn { namespace linear {\n\n  WhiteningTrainer::WhiteningTrainer()\n  {\n  }\n\n  WhiteningTrainer::WhiteningTrainer(const WhiteningTrainer& other)\n  {\n  }\n\n  WhiteningTrainer::~WhiteningTrainer() {}\n\n  WhiteningTrainer& WhiteningTrainer::operator= (const WhiteningTrainer& other)\n  {\n    return *this;\n  }\n\n  bool WhiteningTrainer::operator== (const WhiteningTrainer& other) const\n  {\n    return true;\n  }\n\n  bool WhiteningTrainer::operator!= (const WhiteningTrainer& other) const\n  {\n    return false;\n  }\n\n  void WhiteningTrainer::train(Machine& machine, const blitz::Array<double,2>& ar) const {\n    // training data dimensions\n    const size_t n_samples = ar.extent(0);\n    const size_t n_features = ar.extent(1);\n    // machine dimensions\n    const size_t n_inputs = machine.inputSize();\n    const size_t n_outputs = machine.outputSize();\n\n    // Checks that the dimensions are matching\n    if (n_inputs != n_features) {\n      boost::format m(\"machine input size (%u) does not match the number of columns in input array (%d)\");\n      m % n_inputs % n_features;\n      throw std::runtime_error(m.str());\n    }\n    if (n_outputs != n_features) {\n      boost::format m(\"machine output size (%u) does not match the number of columns in output array (%d)\");\n      m % n_outputs % n_features;\n      throw std::runtime_error(m.str());\n    }\n\n    // 1. Computes the mean vector and the covariance matrix of the training set\n    blitz::Array<double,1> mean(n_features);\n    blitz::Array<double,2> cov(n_features,n_features);\n    bob::math::scatter(ar, cov, mean);\n    cov /= (double)(n_samples-1);\n\n    // 2. Computes the inverse of the covariance matrix\n    blitz::Array<double,2> icov(n_features,n_features);\n    bob::math::inv(cov, icov);\n\n    // 3. Computes the Cholesky decomposition of the inverse covariance matrix\n    blitz::Array<double,2> whiten(n_features,n_features);\n    bob::math::chol(icov, whiten);\n\n    // 4. Updates the linear machine\n    machine.setInputSubtraction(mean);\n    machine.setInputDivision(1.);\n    machine.setWeights(whiten);\n    machine.setBiases(0);\n    machine.setActivation(boost::make_shared<bob::learn::activation::IdentityActivation>());\n  }\n\n}}}\n", "meta": {"hexsha": "2c6b72b15b308b6780f18e0c0d9b9b421890aa74", "size": 2532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/learn/linear/cpp/whitening.cpp", "max_stars_repo_name": "bioidiap/bob.learn.linear", "max_stars_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-10-14T08:06:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:02:13.000Z", "max_issues_repo_path": "bob/learn/linear/cpp/whitening.cpp", "max_issues_repo_name": "bioidiap/bob.learn.linear", "max_issues_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-18T05:27:50.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-25T15:30:27.000Z", "max_forks_repo_path": "bob/learn/linear/cpp/whitening.cpp", "max_forks_repo_name": "bioidiap/bob.learn.linear", "max_forks_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-17T12:58:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-09T14:30:27.000Z", "avg_line_length": 29.7882352941, "max_line_length": 108, "alphanum_fraction": 0.6883886256, "num_tokens": 664, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6093688718609265}}
{"text": "#include <igl/sort_vectors_ccw.h>\n#include <igl/sort.h>\n#include <Eigen/Dense>\n\ntemplate <typename DerivedS, typename DerivedI>\nIGL_INLINE void igl::sort_vectors_ccw(\n  const Eigen::PlainObjectBase<DerivedS>& P,\n  const Eigen::PlainObjectBase<DerivedS>& N,\n  Eigen::PlainObjectBase<DerivedI> &order,\n  const bool do_sorted,\n  Eigen::PlainObjectBase<DerivedS> &sorted,\n  const bool do_inv_order,\n  Eigen::PlainObjectBase<DerivedI> &inv_order)\n{\n  int half_degree = P.cols()/3;\n\n  //local frame\n  Eigen::Matrix<typename DerivedS::Scalar,1,3> e1 = P.head(3).normalized();\n  Eigen::Matrix<typename DerivedS::Scalar,1,3> e3 = N.normalized();\n  Eigen::Matrix<typename DerivedS::Scalar,1,3> e2 = e3.cross(e1);\n\n  Eigen::Matrix<typename DerivedS::Scalar,3,3> F; F<<e1.transpose(),e2.transpose(),e3.transpose();\n\n  Eigen::Matrix<typename DerivedS::Scalar,Eigen::Dynamic,1> angles(half_degree,1);\n  for (int i=0; i<half_degree; ++i)\n  {\n    Eigen::Matrix<typename DerivedS::Scalar,1,3> Pl = F.colPivHouseholderQr().solve(P.segment(i*3,3).transpose()).transpose();\n    assert(fabs(Pl(2))/Pl.cwiseAbs().maxCoeff() <1e-5);\n    angles[i] = atan2(Pl(1),Pl(0));\n  }\n\n  igl::sort( angles, 1, true, angles, order);\n  //make sure that the first element is always  at the top\n  while (order[0] != 0)\n  {\n    //do a circshift\n    int temp = order[0];\n    for (int i =0; i< half_degree-1; ++i)\n      order[i] = order[i+1];\n    order(half_degree-1) = temp;\n  }\n  if (do_sorted)\n  {\n    sorted.resize(1,half_degree*3);\n    for (int i=0; i<half_degree; ++i)\n      sorted.segment(i*3,3) = P.segment(order[i]*3,3);\n  }\n  if (do_inv_order)\n  {\n    inv_order.resize(half_degree,1);\n    for (int i=0; i<half_degree; ++i)\n    {\n      for (int j=0; j<half_degree; ++j)\n        if (order[j] ==i)\n        {\n          inv_order(i) = j;\n          break;\n        }\n    }\n    assert(inv_order[0] == 0);\n  }\n\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\ntemplate void igl::sort_vectors_ccw<Eigen::Matrix<double, 1, -1, 1, 1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, 1, -1, 1, 1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 1, -1, 1, 1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, bool, Eigen::PlainObjectBase<Eigen::Matrix<double, 1, -1, 1, 1, -1> >&, bool, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);\n#endif\n", "meta": {"hexsha": "1064577c617bab5bc10e8e61421dcd39ac36696c", "size": 2405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/include/igl/sort_vectors_ccw.cpp", "max_stars_repo_name": "FabianRepository/SinusProject", "max_stars_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/include/igl/sort_vectors_ccw.cpp", "max_issues_repo_name": "FabianRepository/SinusProject", "max_issues_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-04T22:39:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-05T21:02:47.000Z", "max_forks_repo_path": "Code/include/igl/sort_vectors_ccw.cpp", "max_forks_repo_name": "FabianRepository/SinusProject", "max_forks_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8550724638, "max_line_length": 462, "alphanum_fraction": 0.6440748441, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6093688710982466}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010-2019, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * testPowerMethod.cpp\n *\n * @file   testPowerMethod.cpp\n * @date   Sept 2020\n * @author Jing Wu\n * @brief  Check eigenvalue and eigenvector computed by power method\n */\n\n#include <CppUnitLite/TestHarness.h>\n#include <gtsam/base/Matrix.h>\n#include <gtsam/base/VectorSpace.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/linear/PowerMethod.h>\n#include <gtsam/linear/tests/powerMethodExample.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <iostream>\n#include <random>\n\nusing namespace std;\nusing namespace gtsam;\n\n/* ************************************************************************* */\nTEST(PowerMethod, powerIteration) {\n  // test power iteration, beta is set to 0\n  Sparse A(6, 6);\n  A.coeffRef(0, 0) = 6;\n  A.coeffRef(1, 1) = 5;\n  A.coeffRef(2, 2) = 4;\n  A.coeffRef(3, 3) = 3;\n  A.coeffRef(4, 4) = 2;\n  A.coeffRef(5, 5) = 1;\n  Vector initial = (Vector(6) << 0.24434602, 0.22829942, 0.70094486, 0.15463092, 0.55871359,\n       0.2465342).finished();\n  PowerMethod<Sparse> pf(A, initial);\n  pf.compute(100, 1e-5);\n  EXPECT_LONGS_EQUAL(6, pf.eigenvector().rows());\n\n  Vector6 actual1 = pf.eigenvector();\n  const double ritzValue = actual1.dot(A * actual1);\n  const double ritzResidual = (A * actual1 - ritzValue * actual1).norm();\n  EXPECT_DOUBLES_EQUAL(0, ritzResidual, 1e-5);\n\n  const double ev1 = 6.0;\n  EXPECT_DOUBLES_EQUAL(ev1, pf.eigenvalue(), 1e-5);\n}\n\n/* ************************************************************************* */\nTEST(PowerMethod, useFactorGraphSparse) {\n  // Let's make a scalar synchronization graph with 4 nodes\n  GaussianFactorGraph fg = gtsam::linear::test::example::createSparseGraph();\n\n  // Get eigenvalues and eigenvectors with Eigen\n  auto L = fg.hessian();\n  Eigen::EigenSolver<Matrix> solver(L.first);\n\n  // find the index of the max eigenvalue\n  size_t maxIdx = 0;\n  for (auto i = 0; i < solver.eigenvalues().rows(); ++i) {\n    if (solver.eigenvalues()(i).real() >= solver.eigenvalues()(maxIdx).real())\n      maxIdx = i;\n  }\n  // Store the max eigenvalue and its according eigenvector\n  const auto ev1 = solver.eigenvalues()(maxIdx).real();\n\n  Vector initial = Vector4::Random();\n  PowerMethod<Matrix> pf(L.first, initial);\n  pf.compute(100, 1e-5);\n  EXPECT_DOUBLES_EQUAL(ev1, pf.eigenvalue(), 1e-8);\n  auto actual2 = pf.eigenvector();\n  const double ritzValue = actual2.dot(L.first * actual2);\n  const double ritzResidual = (L.first * actual2 - ritzValue * actual2).norm();\n  EXPECT_DOUBLES_EQUAL(0, ritzResidual, 1e-5);\n}\n\n/* ************************************************************************* */\nTEST(PowerMethod, useFactorGraphDense) {\n  // Let's make a scalar synchronization graph with 10 nodes\n  GaussianFactorGraph fg = gtsam::linear::test::example::createDenseGraph();\n\n  // Get eigenvalues and eigenvectors with Eigen\n  auto L = fg.hessian();\n  Eigen::EigenSolver<Matrix> solver(L.first);\n\n  // find the index of the max eigenvalue\n  size_t maxIdx = 0;\n  for (auto i = 0; i < solver.eigenvalues().rows(); ++i) {\n    if (solver.eigenvalues()(i).real() >= solver.eigenvalues()(maxIdx).real())\n      maxIdx = i;\n  }\n  // Store the max eigenvalue and its according eigenvector\n  const auto ev1 = solver.eigenvalues()(maxIdx).real();\n\n  Vector initial = Vector10::Random();\n  PowerMethod<Matrix> pf(L.first, initial);\n  pf.compute(100, 1e-5);\n  EXPECT_DOUBLES_EQUAL(ev1, pf.eigenvalue(), 1e-8);\n  auto actual2 = pf.eigenvector();\n  const double ritzValue = actual2.dot(L.first * actual2);\n  const double ritzResidual = (L.first * actual2 - ritzValue * actual2).norm();\n  EXPECT_DOUBLES_EQUAL(0, ritzResidual, 1e-5);\n}\n\n/* ************************************************************************* */\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n/* ************************************************************************* */\n", "meta": {"hexsha": "54d4c720d29890cc855e89ba496618b840c663e3", "size": 4304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/tests/testPowerMethod.cpp", "max_stars_repo_name": "Alevs2R/gtsam", "max_stars_repo_head_hexsha": "6cef675e6eaeaf89f2462e8cfec4a4a9a497fac8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1402.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T00:18:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:28:32.000Z", "max_issues_repo_path": "gtsam/linear/tests/testPowerMethod.cpp", "max_issues_repo_name": "Alevs2R/gtsam", "max_issues_repo_head_hexsha": "6cef675e6eaeaf89f2462e8cfec4a4a9a497fac8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 851.0, "max_issues_repo_issues_event_min_datetime": "2017-11-27T15:09:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:38.000Z", "max_forks_repo_path": "gtsam/linear/tests/testPowerMethod.cpp", "max_forks_repo_name": "Alevs2R/gtsam", "max_forks_repo_head_hexsha": "6cef675e6eaeaf89f2462e8cfec4a4a9a497fac8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 565.0, "max_forks_repo_forks_event_min_datetime": "2017-11-30T16:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:53:04.000Z", "avg_line_length": 34.432, "max_line_length": 92, "alphanum_fraction": 0.6092007435, "num_tokens": 1196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6093688710982466}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_LBETA_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_LBETA_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/prim/scal/fun/lgamma.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the log of the beta function applied to the specified\n * arguments.\n *\n * The beta function is defined for \\f$a > 0\\f$ and \\f$b > 0\\f$ by\n *\n * \\f$\\mbox{B}(a, b) = \\frac{\\Gamma(a) \\Gamma(b)}{\\Gamma(a+b)}\\f$.\n *\n * This function returns its log,\n *\n * \\f$\\log \\mbox{B}(a, b) = \\log \\Gamma(a) + \\log \\Gamma(b) - \\log\n \\Gamma(a+b)\\f$.\n *\n * See stan::math::lgamma() for the double-based and stan::math for the\n * variable-based log Gamma function.\n *\n *\n   \\f[\n   \\mbox{lbeta}(\\alpha, \\beta) =\n   \\begin{cases}\n     \\ln\\int_0^1 u^{\\alpha - 1} (1 - u)^{\\beta - 1} \\, du & \\mbox{if } \\alpha,\n \\beta>0 \\\\[6pt] \\textrm{NaN} & \\mbox{if } \\alpha = \\textrm{NaN or } \\beta =\n \\textrm{NaN} \\end{cases} \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{lbeta}(\\alpha, \\beta)}{\\partial \\alpha} =\n   \\begin{cases}\n     \\Psi(\\alpha)-\\Psi(\\alpha+\\beta) & \\mbox{if } \\alpha, \\beta>0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } \\alpha = \\textrm{NaN or } \\beta = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{lbeta}(\\alpha, \\beta)}{\\partial \\beta} =\n   \\begin{cases}\n     \\Psi(\\beta)-\\Psi(\\alpha+\\beta) & \\mbox{if } \\alpha, \\beta>0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } \\alpha = \\textrm{NaN or } \\beta = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n *\n * @param a First value\n * @param b Second value\n * @return Log of the beta function applied to the two values.\n * @tparam T1 Type of first value.\n * @tparam T2 Type of second value.\n */\ntemplate <typename T1, typename T2>\ninline typename boost::math::tools::promote_args<T1, T2>::type lbeta(\n    const T1 a, const T2 b) {\n  return lgamma(a) + lgamma(b) - lgamma(a + b);\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "3e20b1fa174e2cb72530c8aaaa49785dbc03c5d2", "size": 1911, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/lbeta.hpp", "max_stars_repo_name": "riddell-stan/math", "max_stars_repo_head_hexsha": "d84ee0d991400d6cf4b08a07a4e8d86e0651baea", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T14:57:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-23T14:57:41.000Z", "max_issues_repo_path": "stan/math/prim/scal/fun/lbeta.hpp", "max_issues_repo_name": "Capri2014/math", "max_issues_repo_head_hexsha": "d4042bdf8623bba5a1633b557227325a324e32e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-23T19:58:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-24T12:03:41.000Z", "max_forks_repo_path": "stan/math/prim/scal/fun/lbeta.hpp", "max_forks_repo_name": "riddell-stan/math", "max_forks_repo_head_hexsha": "d84ee0d991400d6cf4b08a07a4e8d86e0651baea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5223880597, "max_line_length": 78, "alphanum_fraction": 0.612244898, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6093688607933413}}
{"text": "// Copyright 2017 John Maddock\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/math/special_functions/bessel.hpp>\n#include <boost/math/special_functions/relative_difference.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/random.hpp>\n#include <boost/svg_plot/svg_2d_plot.hpp>\n#include <sstream>\n\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\n#endif\n\ntypedef boost::multiprecision::number<boost::multiprecision::cpp_bin_float<256, boost::multiprecision::backends::digit_base_2>, boost::multiprecision::et_on> mp_type;\n\ntemplate <class T>\nvoid test_type(const char* name)\n{\n   typedef boost::math::policies::policy<\n      boost::math::policies::promote_double<false>, \n      boost::math::policies::promote_float<false>, \n      boost::math::policies::overflow_error<boost::math::policies::ignore_error> \n   > policy_type;\n   boost::random::mt19937 dist;\n   boost::random::uniform_real_distribution<T> ur(0, 7.75);\n   boost::random::uniform_real_distribution<T> ur2(0, 1 / 7.75);\n\n   float max_err = 0;\n\n   std::map<double, double> small, medium, large;\n\n   for(unsigned i = 0; i < 1000; ++i)\n   {\n      T input = ur(dist);\n      mp_type input2(input);\n      T result = boost::math::cyl_bessel_i(0, input, policy_type());\n      mp_type result2 = boost::math::cyl_bessel_i(0, input2);\n      mp_type err = boost::math::relative_difference(result2, mp_type(result)) / mp_type(std::numeric_limits<T>::epsilon());\n      if(result2 < mp_type(result))\n         err = -err;\n      if(fabs(err) > max_err)\n      {\n         /*\n         std::cout << std::setprecision(34) << input << std::endl;\n         std::cout << std::setprecision(34) << input2 << std::endl;\n         std::cout << std::setprecision(34) << result << std::endl;\n         std::cout << std::setprecision(34) << result2 << std::endl;\n         std::cout << \"New max error at x = \" << input << \" expected \" << result2 << \" got \" << result << \" error \" << err << std::endl;\n         */\n         max_err = static_cast<float>(fabs(err));\n      }\n      if(fabs(err) <= 1)\n         small[static_cast<double>(input)] = static_cast<double>(err);\n      else if(fabs(err) <= 2)\n         medium[static_cast<double>(input)] = static_cast<double>(err);\n      else\n         large[static_cast<double>(input)] = static_cast<double>(err);\n   }\n\n   int y_interval = static_cast<int>(ceil(max_err / 5));\n\n   std::stringstream ss;\n   ss << \"cyl_bessel_i&lt;\" << name << \"&gt;(0, x) over [0, 7.75]\\n(max error = \" << std::setprecision(2) << max_err << \")\" << std::endl;\n\n   boost::svg::svg_2d_plot my_plot;\n   // Size of SVG image and X and Y range settings.\n   my_plot.x_range(0, 7.75).image_x_size(700).legend_border_color(boost::svg::lightgray).plot_border_color(boost::svg::lightgray).background_border_color(boost::svg::lightgray)\n      .y_range(-(int)ceil(max_err), (int)ceil(max_err)).x_label(\"x\").title(ss.str()).y_major_interval(y_interval).x_major_interval(1.0).legend_on(true).plot_window_on(true);\n   my_plot.plot(small, \"&lt; 1eps\").stroke_color(boost::svg::green).fill_color(boost::svg::green).size(2);\n   my_plot.plot(medium, \"&lt; 2eps\").stroke_color(boost::svg::orange).fill_color(boost::svg::orange).size(2);\n   my_plot.plot(large, \"&gt; 2eps\").stroke_color(boost::svg::red).fill_color(boost::svg::red).size(2);\n   std::string filename(\"bessel_i0_0_7_\");\n   filename += name;\n   filename += \".svg\";\n   my_plot.write(filename);\n   std::cout << \"Maximum error for type \" << name << \" was: \" << max_err << std::endl;\n\n   max_err = 0;\n   for(unsigned i = 0; i < 1000; ++i)\n   {\n      T input = 1 / ur2(dist);\n      mp_type input2(input);\n      T result = boost::math::cyl_bessel_i(0, input, policy_type());\n      mp_type result2 = boost::math::cyl_bessel_i(0, input2);\n      mp_type err = boost::math::relative_difference(result2, mp_type(result)) / mp_type(std::numeric_limits<T>::epsilon());\n      if(boost::math::isinf(result))\n      {\n         if(result2 > mp_type(std::numeric_limits<T>::max()))\n            err = 0;\n         else\n            std::cout << \"Bad result at x = \" << input << \" result = \" << result << \" true result = \" << result2 << std::endl;\n      }\n      if(result2 < mp_type(result))\n         err = -err;\n      if(fabs(err) > max_err)\n         max_err = static_cast<float>(fabs(err));\n      if(fabs(err) <= 1)\n         small[1 / static_cast<double>(input)] = static_cast<double>(err);\n      else if(fabs(err) <= 2)\n         medium[1 / static_cast<double>(input)] = static_cast<double>(err);\n      else\n         large[1 / static_cast<double>(input)] = static_cast<double>(err);\n   }\n\n   y_interval = static_cast<int>(ceil(max_err / 5));\n   ss.str(\"\");\n   ss << \"cyl_bessel_i&lt;\" << name << \"&gt;(0, x) over [0, 7.75]\\n(max error = \" << std::setprecision(2) << max_err << \")\" << std::endl;\n   boost::svg::svg_2d_plot my_plot2;\n   // Size of SVG image and X and Y range settings.\n   my_plot2.x_range(0, 1 / 7.75).image_x_size(700).legend_border_color(boost::svg::lightgray).plot_border_color(boost::svg::lightgray).background_border_color(boost::svg::lightgray)\n      .y_range(-(int)ceil(max_err), (int)ceil(max_err)).x_label(\"1 / x\").title(ss.str()).y_major_interval(y_interval).x_major_interval(0.01).legend_on(true).plot_window_on(true);\n   my_plot2.plot(small, \"&lt; 1eps\").stroke_color(boost::svg::green).fill_color(boost::svg::green).size(2);\n   my_plot2.plot(medium, \"&lt; 2eps\").stroke_color(boost::svg::orange).fill_color(boost::svg::orange).size(2);\n   my_plot2.plot(large, \"&gt; 2eps\").stroke_color(boost::svg::red).fill_color(boost::svg::red).size(2);\n   filename = \"bessel_i0_7_inf_\";\n   filename += name;\n   filename += \".svg\";\n   my_plot2.write(filename);\n\n   std::cout << \"Maximum error for type \" << name << \" was: \" << max_err << std::endl;\n}\n\n\nint main()\n{\n   test_type<float>(\"float\");\n   test_type<double>(\"double\");\n#if LDBL_MANT_DIG == 64\n   test_type<long double>(\"long double\");\n#endif\n#ifdef BOOST_HAS_FLOAT128\n   test_type<boost::multiprecision::float128>(\"float128\");\n#else\n   test_type<boost::multiprecision::cpp_bin_float_quad>(\"quad\");\n#endif\n\n   return 0;\n}\n\n", "meta": {"hexsha": "b92efea92d9e5bde736601d364b2b6b3fc84e16e", "size": 6262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/doc/graphs/bessel_i0_errors.cpp", "max_stars_repo_name": "ZCube/boost-cmake", "max_stars_repo_head_hexsha": "f1eca5534ab6c9bc89cf7ee4670f056503b7ba86", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2017-07-03T18:36:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T14:57:19.000Z", "max_issues_repo_path": "libs/math/doc/graphs/bessel_i0_errors.cpp", "max_issues_repo_name": "ZCube/boost-cmake", "max_issues_repo_head_hexsha": "f1eca5534ab6c9bc89cf7ee4670f056503b7ba86", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2017-07-22T14:05:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-06T20:01:30.000Z", "max_forks_repo_path": "libs/math/doc/graphs/bessel_i0_errors.cpp", "max_forks_repo_name": "ZCube/boost-cmake", "max_forks_repo_head_hexsha": "f1eca5534ab6c9bc89cf7ee4670f056503b7ba86", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-07-04T14:15:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-12T04:50:41.000Z", "avg_line_length": 43.1862068966, "max_line_length": 181, "alphanum_fraction": 0.6493133184, "num_tokens": 1781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6093448711408885}}
{"text": "//\n// Copyright (c) 2018-2019 INRIA\n//\n\n#include \"pinocchio/fwd.hpp\"\n#include \"pinocchio/math/sincos.hpp\"\n#include <cstdlib>\n\n#include \"utils/macros.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nnamespace \n{\n  template <typename Scalar>\n  Scalar sinCosTolerance();\n\n  template<> inline float sinCosTolerance<float>()\n  {\n    return 0.F;\n  }\n\n  template<> inline double sinCosTolerance<double>()\n  {\n    return 1e-15;\n  }\n\n  template<> inline long double sinCosTolerance<long double>()\n  {\n    return 1e-19;\n  }\n}\n\n\ntemplate<typename Scalar>\nvoid testSINCOS(int n)\n{\n  for(int k = 0; k < n; ++k)\n  {\n    Scalar sin_value, cos_value;\n    Scalar alpha = (Scalar)std::rand()/(Scalar)RAND_MAX;\n    pinocchio::SINCOS(alpha,&sin_value,&cos_value);\n    \n    Scalar sin_value_ref = std::sin(alpha),\n           cos_value_ref = std::cos(alpha);\n\n    BOOST_CHECK_CLOSE_FRACTION(sin_value, sin_value_ref, sinCosTolerance<Scalar>());\n    BOOST_CHECK_CLOSE_FRACTION(cos_value, cos_value_ref, sinCosTolerance<Scalar>());\n  }\n}\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_sincos)\n{\n#ifndef NDEBUG\n  const int n = 1e3;\n#else\n  const int n = 1e6;\n#endif\n  testSINCOS<float>(n);\n  testSINCOS<double>(n);\n  testSINCOS<long double>(n);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "593f660babc9784fbade9fed8dd0db702bea6d55", "size": 1303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/sincos.cpp", "max_stars_repo_name": "paLeziart/pinocchio", "max_stars_repo_head_hexsha": "66a4177663bdb9549bcf3d22d54383e11904ecc9", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittest/sincos.cpp", "max_issues_repo_name": "paLeziart/pinocchio", "max_issues_repo_head_hexsha": "66a4177663bdb9549bcf3d22d54383e11904ecc9", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/sincos.cpp", "max_forks_repo_name": "paLeziart/pinocchio", "max_forks_repo_head_hexsha": "66a4177663bdb9549bcf3d22d54383e11904ecc9", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-25T13:34:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-25T13:34:37.000Z", "avg_line_length": 19.1617647059, "max_line_length": 84, "alphanum_fraction": 0.6983883346, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6093448605088146}}
{"text": "/* ScaFES\n * Copyright (c) 2017-2018, ZIH, TU Dresden, Federal Republic of Germany.\n * For details, see the files COPYING and LICENSE in the base directory\n * of the package.\n */\n\n/**\n *  @file TumorHeatEqnFDM.hpp\n *\n *  @brief Implementation of a n-dimensional Pennes bioheat equation problem\n *         with tumor model inside the grid.\n */\n\n#include <iostream>\n#include \"ScaFES.hpp\"\n\n#include <boost/property_tree/ini_parser.hpp>\n\n/*******************************************************************************\n ******************************************************************************/\n/**\n * \\class TumorHeatEqnFDM\n *  @brief Class for discretized Pennes bioheat equation problem.\n *\n*/\ntemplate<typename CT, std::size_t DIM>\nclass TumorHeatEqnFDM : public ScaFES::Problem<TumorHeatEqnFDM<CT,DIM>, CT, DIM> {\n  private:\n    /** Parser for ini files. */\n    using PTree = boost::property_tree::ptree;\n    const PTree ptree;\n\n  public:\n\n    /* Based on Bousselham et al. (2017). */\n\n    /************************************************************************/\n    /** constant rho. Density. */\n    const CT RHO; /* kg/m^3 */\n\n    /** constant C. Specific heat capacity. */\n    const CT C; /* J/(kg K) */\n\n    /** constant K. Thermal conductivity). */\n    const CT K; /* W/(m K) */\n\n    /** constant Q_brain. Metabolism heat generation of the brain. */\n    const CT Q_BRAIN; /* W/(m^3) */\n\n    /** constant Q_tumor. Metabolism heat generation of the tumor. */\n    const CT Q_TUMOR; /* W/(m^3) */\n\n    /** constant rho_b. Density of the blood. */\n    const CT RHO_B; /* kg/m^3 */\n\n    /** constant C_Pb. Specific heat of the blood. */\n    const CT C_PB; /* J/(kg K) */\n\n    /** constant omega_b. Blood perfusion rate (normal brain tissue). */\n    const CT OMEGA_B_BRAIN; /* 1/s */\n\n    /** constant omega_b. Blood perfusion rate (Astrocytoma brain tumor). */\n    const CT OMEGA_B_TUMOR; /* 1/s */\n\n    /** constant T_i. Initial condition for T. */\n    const CT T_I; /* K */\n\n    /** constant h. Ambient convetion. */\n    const CT H; /* W/(m^2 K) */\n\n    /** constant T_inf. Air temperature. */\n    const CT T_INF; /* K */\n\n    /** constant q_bc. Heat flux at surface. */\n    const CT Q_BC; /* W/(m^2) */\n\n    /** constant diameter. diameter of the tumor. */\n    const CT DIAMETER; /* m */\n\n    /** constant depth. depth of the tumor. */\n    const CT DEPTH; /* m */\n\n    /* constant T_a. Temperature of artery. */\n    const CT T_A; /* K */\n\n    /************************************************************************/\n    /* Auxiliary values. */\n    /* Radius of tumor. */\n    CT RADIUS;\n\n    /* Center of tumor. */\n    ScaFES::Ntuple<CT,DIM> tumorCenter;\n\n    /************************************************************************/\n\n    /** All fields which are related to the underlying problem\n     * are added in terms of an entry of the parameters of\n     * type \\c std::vector.\n     * @param params Set of ScaFES parameters.\n     * @param gg Global grid.\n     * @param useLeapfrog Should the leap frog scheme be used?\n     * @param nameDatafield Name of the fields.\n     * @param stencilWidth Stencil width of the fields.\n     * @param isKnownDf Is the data field are known or unknown one?\n     * @param ptree_ Config file parser.\n     * @param nLayers Number of layers at the global boundary.\n     * @param defaultValue Default value of fields.\n     * @param writeToFile How often should the data field be written to file.\n     * @param computeError Should the Linf error between the numerical\n     *                     and exact solution be computed?\n     * @param geomparamsInit Initial guess of geometrical parameters.\n     * @param checkConvergence Should convergence be checked?\n     */\n    TumorHeatEqnFDM(ScaFES::Parameters const& params,\n                    ScaFES::GridGlobal<DIM> const& gg,\n                    bool useLeapfrog,\n                    std::vector<std::string> const& nameDatafield,\n                    std::vector<int> const& stencilWidth,\n                    std::vector<bool> const& isKnownDf,\n                    PTree const& ptree_,\n                    std::vector<int> const& nLayers = std::vector<int>(),\n                    std::vector<CT> const& defaultValue = std::vector<CT>(),\n                    std::vector<ScaFES::WriteHowOften> const& writeToFile\n                      = std::vector<ScaFES::WriteHowOften>(),\n                    std::vector<bool> const& computeError = std::vector<bool>(),\n                    std::vector<CT> const& geomparamsInit = std::vector<CT>(),\n                    std::vector<bool> const& checkConvergence = std::vector<bool>() )\n        : ScaFES::Problem<TumorHeatEqnFDM<CT, DIM>, CT, DIM>(params, gg, useLeapfrog,\n                                                             nameDatafield, stencilWidth,\n                                                             isKnownDf, nLayers,\n                                                             defaultValue, writeToFile,\n                                                             computeError, geomparamsInit,\n                                                             checkConvergence),\n        ptree(ptree_),\n        RHO(ptree.get<CT>(\"Parameters.RHO\")),\n        C(ptree.get<CT>(\"Parameters.C\")),\n        K(ptree.get<CT>(\"Parameters.K\")),\n        Q_BRAIN(ptree.get<CT>(\"Parameters.Q_BRAIN\")),\n        Q_TUMOR(ptree.get<CT>(\"Parameters.Q_TUMOR\")),\n        RHO_B(ptree.get<CT>(\"Parameters.RHO_B\")),\n        C_PB(ptree.get<CT>(\"Parameters.C_PB\")),\n        OMEGA_B_BRAIN(ptree.get<CT>(\"Parameters.OMEGA_B_BRAIN\")),\n        OMEGA_B_TUMOR(ptree.get<CT>(\"Parameters.OMEGA_B_TUMOR\")),\n        T_I(ptree.get<CT>(\"Parameters.T_I\")),\n        H(ptree.get<CT>(\"Parameters.H\")),\n        T_INF(ptree.get<CT>(\"Parameters.T_INF\")),\n        Q_BC(ptree.get<CT>(\"Parameters.Q_BC\")),\n        DIAMETER(ptree.get<CT>(\"Parameters.DIAMETER\")),\n        DEPTH(ptree.get<CT>(\"Parameters.DEPTH\")),\n        T_A(ptree.get<CT>(\"Parameters.T_A\"))\n        {\n            RADIUS = DIAMETER/2.0;\n\n            /* Calculate center of tumor. */\n            for (std::size_t pp = 0; pp < DIM; ++pp) {\n                if (pp == (DIM-1)) {\n                    /* In the highest dimension parameter 'depth' will be used. */\n                    if (this->params().coordNodeLast()[pp] <= DIAMETER) {\n                        std::cerr << \"WARNING: Diameter of tumor is bigger than grid in dimension: \"\n                                  << pp << \".\" << std::endl;\n                    }\n                    if (this->params().coordNodeLast()[pp] < std::fabs(DEPTH) ||\n                        DEPTH < 0.0) {\n                        std::cerr << \"WARNING: Center of tumor is outside of grid in dimension: \"\n                                  << pp << \".\" << std::endl;\n                    }\n                    if ((this->params().coordNodeLast()[pp] + RADIUS) < std::fabs(DEPTH)) {\n                        std::cerr << \"WARNING: Tumor is completely outside of grid.\" << std::endl;\n                    }\n                    if (std::fabs(this->params().coordNodeLast()[pp] - DEPTH) < RADIUS ||\n                        std::fabs(DEPTH) < RADIUS) {\n                        std::cerr << \"WARNING: Part of tumor is outside of grid in dimension: \"\n                                  << pp << \".\" << std::endl;\n                    }\n                    tumorCenter[pp] = this->params().coordNodeLast()[pp] - DEPTH;\n                } else {\n                    /* In every other dimension the tumor will be located in the center. */\n                    if (this->params().coordNodeLast()[pp] <= DIAMETER) {\n                        std::cerr << \"WARNING: Diameter of tumor is bigger than grid in dimension: \"\n                                  << pp << \".\" << std::endl;\n                    }\n                    tumorCenter[pp] = this->params().coordNodeLast()[pp]/2.0;\n                }\n            }\n        }\n\n    /** Evaluates all fields at one given global inner grid node.\n     */\n    void evalInner(std::vector< ScaFES::DataField<CT, DIM> >& /*vNew*/,\n                   ScaFES::Ntuple<int,DIM> const& /*idxNode*/,\n                   int const& /*timestep*/) {\n    }\n\n    /** Evaluates all fields at one given global border grid node.\n     */\n    void evalBorder(std::vector< ScaFES::DataField<CT, DIM> >& /*vNew*/,\n                    ScaFES::Ntuple<int,DIM> const& /*idxNode*/,\n                    int const& /*timestep*/) {\n    }\n\n    /** Initializes all unknown fields at one given global inner grid node.\n     *  @param vNew Set of all unknown fields (return value).\n     *  @param idxNode Index of given grid node.\n     */\n    template<typename TT>\n    void initInner(std::vector< ScaFES::DataField<TT, DIM> >& vNew,\n                   std::vector<TT> const& /*vOld*/,\n                   ScaFES::Ntuple<int,DIM> const& idxNode,\n                   int const& /*timestep*/) {\n        /* Init all nodes with the same temperature. */\n        vNew[0](idxNode) = T_I;\n    }\n\n    /** Initializes all unknown fields at one given global border grid node.\n     *  @param vNew Set of all unknown fields (return value).\n     *  @param vOld Set of all unknown fields at old time step.\n     *  @param idxNode Index of given grid node.\n     *  @param timestep Given time step.\n     */\n    template<typename TT>\n    void initBorder(std::vector< ScaFES::DataField<TT, DIM> >& vNew,\n                   std::vector<TT> const& vOld,\n                   ScaFES::Ntuple<int,DIM> const& idxNode,\n                   int const& timestep) {\n        this->template initInner<TT>(vNew, vOld, idxNode, timestep);\n    }\n\n    /** Updates all unknown fields at one given global inner grid node.\n     *  @param vNew Set of all unknown fields at new time step (return value).\n     *  @param vOld Set of all unknown fields at old time step.\n     *  @param idxNode Index of given grid node.\n     */\n    template<typename TT>\n    void updateInner(std::vector<ScaFES::DataField<TT,DIM>>& vNew,\n                     std::vector<ScaFES::DataField<TT,DIM>> const& vOld,\n                     ScaFES::Ntuple<int,DIM> const& idxNode,\n                     int const& /*timestep*/) {\n        CT omega = 0.0;\n        CT Q = 0.0;\n        /* Get coordinates of current node. */\n        ScaFES::Ntuple<double,DIM> x = this->coordinates(idxNode);\n        /* Calculate distance to tumor center. */\n        CT distance = 0.0;\n        for (std::size_t pp = 0; pp < DIM; ++pp) {\n            distance += (x[pp] - tumorCenter[pp]) * (x[pp] - tumorCenter[pp]);\n        }\n        /* Check if current point is inside tumor. */\n        if (distance <= (this->RADIUS*this->RADIUS)) {\n            /* Inside tumor. */\n            omega = OMEGA_B_TUMOR;\n            Q = Q_TUMOR;\n        } else {\n            /* Outside tumor, i.e. normal healthy brain tissue. */\n            omega = OMEGA_B_BRAIN;\n            Q = Q_BRAIN;\n        }\n        /* Discrete Pennes Bioheat Equation for updating inner nodes. */\n        vNew[0](idxNode) = vOld[0](idxNode);\n        for (std::size_t pp = 0; pp < DIM; ++pp) {\n            vNew[0](idxNode) += this->tau() * (K/(RHO*C))\n                                * (vOld[0](this->connect(idxNode, 2*pp))\n                                   + vOld[0](this->connect(idxNode, 2*pp+1))\n                                   - 2.0 * vOld[0](idxNode))\n                                / (this->gridsize(pp) * this->gridsize(pp));\n        }\n        vNew[0](idxNode) += this->tau() * ((RHO_B*C_PB)/(RHO*C)) * omega\n                            * (T_A - vOld[0](idxNode));\n        vNew[0](idxNode) += this->tau() * (1.0/(RHO*C)) * Q;\n    }\n\n    /** Updates all unknown fields at one given global border grid node.\n     *  @param vNew Set of all unknown fields at new time step (return value).\n     *  @param vOld Set of all unknown fields at old time step.\n     *  @param idxNode Index of given grid node.\n     */\n    template<typename TT>\n    void updateBorder(std::vector<ScaFES::DataField<TT,DIM>>& vNew,\n                      std::vector<ScaFES::DataField<TT,DIM>>const& vOld,\n                      ScaFES::Ntuple<int,DIM> const& idxNode,\n                      int const& /*timestep*/) {\n        CT omega = 0.0;\n        CT Q = 0.0;\n        /* Get coordinates of current node. */\n        ScaFES::Ntuple<double,DIM> x = this->coordinates(idxNode);\n        /* Calculate distance to tumor center. */\n        CT distance = 0.0;\n        for (std::size_t pp = 0; pp < DIM; ++pp) {\n            distance += (x[pp] - tumorCenter[pp]) * (x[pp] - tumorCenter[pp]);\n        }\n        /* Check if current point is inside tumor. */\n        if (distance <= (this->RADIUS*this->RADIUS)) {\n            /* Inside tumor. */\n            omega = OMEGA_B_TUMOR;\n            Q = Q_TUMOR;\n        } else {\n            /* Outside tumor, i.e. normal healthy brain tissue. */\n            omega = OMEGA_B_BRAIN;\n            Q = Q_BRAIN;\n        }\n        /* Discrete Pennes Bioheat Equation modified for updating border nodes. */\n        vNew[0](idxNode) = vOld[0](idxNode);\n        for (std::size_t pp = 0; pp < DIM; ++pp) {\n            /* Last node/edge/surface in highest dimension will be convection\n             * boundary condition. */\n            if (idxNode.elem(pp) == (this->nNodes(pp)-1)) {\n            /* vOld[0](this->connect(idxNode, 2*pp+1) needs to be replaced. */\n                if (pp == (DIM-1)) {\n                /* Cauchy boundary condition. */\n                    vNew[0](idxNode) += this->tau() * (K/(RHO*C))\n                                        * (vOld[0](this->connect(idxNode, 2*pp))\n                                        /* + vOld[0](this->connect(idxNode, 2*pp+1) */\n                                           + vOld[0](this->connect(idxNode, 2*pp))\n                                           - ((2.0*this->gridsize(pp)/K)\n                                              * H * (vOld[0](idxNode) - T_INF))\n                                        /********************************************/\n                                           - 2.0 * vOld[0](idxNode))\n                                        / (this->gridsize(pp) * this->gridsize(pp));\n                } else {\n                /* Neumann boundary condition. */\n                    vNew[0](idxNode) += this->tau() * (K/(RHO*C))\n                                        * (vOld[0](this->connect(idxNode, 2*pp))\n                                        /* + vOld[0](this->connect(idxNode, 2*pp+1)) */\n                                           + vOld[0](this->connect(idxNode, 2*pp))\n                                           - ((2.0*this->gridsize(pp)/K) *\n                                              (-1.0 * Q_BC))\n                                        /*********************************************/\n                                           - 2.0 * vOld[0](idxNode))\n                                        / (this->gridsize(pp) * this->gridsize(pp));\n                }\n            } else if (idxNode.elem(pp) == 0){\n            /* vOld[0](this->connect(idxNode, 2*pp) needs to be replaced.\n             * Neumann boundary condition. */\n                vNew[0](idxNode) += this->tau() * (K/(RHO*C))\n                                    /* + vOld[0](this->connect(idxNode, 2*pp)) */\n                                    * (vOld[0](this->connect(idxNode, 2*pp+1))\n                                       + ((2.0*this->gridsize(pp)/K) * Q_BC)\n                                    /*******************************************/\n                                       + vOld[0](this->connect(idxNode, 2*pp+1))\n                                       - 2.0 * vOld[0](idxNode))\n                                    / (this->gridsize(pp) * this->gridsize(pp));\n            } else {\n            /* No value needs to be replaced.\n             * Use central differencing scheme. */\n                vNew[0](idxNode) += this->tau() * (K/(RHO*C))\n                                    * (vOld[0](this->connect(idxNode, 2*pp))\n                                       + vOld[0](this->connect(idxNode, 2*pp+1))\n                                       - 2.0 * vOld[0](idxNode))\n                                    / (this->gridsize(pp) * this->gridsize(pp));\n            }\n        }\n\n        /* These terms are independet of the boundary condition. */\n        vNew[0](idxNode) += this->tau() * ((RHO_B*C_PB)/(RHO*C)) * omega\n                            * (T_A - vOld[0](idxNode));\n        vNew[0](idxNode) += this->tau() * (1.0/(RHO*C)) * Q;\n    }\n\n    /** Updates (2nd cycle) all unknown fields at one given global inner grid node.\n     *  \\remarks Only important if leap frog scheme is used.\n     */\n    template<typename TT>\n    void updateInner2(std::vector<ScaFES::DataField<TT,DIM>>&,\n                      std::vector<ScaFES::DataField<TT,DIM>> const&,\n                      ScaFES::Ntuple<int,DIM> const&,\n                      int const&) { }\n\n    /** Updates (2nd cycle) all unknown fields at one given global border\n     *  grid node.\n     *  \\remarks Only important if leap frog scheme is used.\n     */\n    template<typename TT>\n    void updateBorder2(std::vector<ScaFES::DataField<TT,DIM>>&,\n                       std::vector<ScaFES::DataField<TT,DIM>>const&,\n                       ScaFES::Ntuple<int,DIM> const&,\n                       int const&) { }\n};\n", "meta": {"hexsha": "6f43cdecf66cc2cbac84365cdd86bdfc26afa299", "size": 17259, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/TumorHeatEqnFDM/TumorHeatEqnFDM.hpp", "max_stars_repo_name": "nih23/MRIDrivenHeatSimulation", "max_stars_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/TumorHeatEqnFDM/TumorHeatEqnFDM.hpp", "max_issues_repo_name": "nih23/MRIDrivenHeatSimulation", "max_issues_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/TumorHeatEqnFDM/TumorHeatEqnFDM.hpp", "max_forks_repo_name": "nih23/MRIDrivenHeatSimulation", "max_forks_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.7798408488, "max_line_length": 100, "alphanum_fraction": 0.4813720378, "num_tokens": 4199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6093448600973317}}
{"text": "#include <iostream>\n#include <boost/concept_check.hpp>\n#include <ceres/ceres.h>\n#include <cmath>\n\nusing namespace std;\nusing namespace ceres;\nusing ceres::AutoDiffCostFunction;\nusing ceres::Solver;\nusing ceres::Problem;\nusing ceres::CostFunction;\nusing ceres::Solve;\n\n\n\nstruct CostFuntorF1 {\n  template <typename T>\n  bool operator()(const T* const x1, const T* const x2, T* residuals) const {\n    residuals[0] = x1[0] + T(10)*x2[0];\n    return true;\n  }\n};\n\nstruct CostFuntorF2 {\n  template <typename T>\n  bool operator()(const T* const x3, const T* const x4, T* residuals) const {\n    residuals[0] = sqrt(5)*(x3[0] - x4[0]);\n    return true;\n  }\n};\n\nstruct CostFuntorF3 {\n  template <typename T>\n  bool operator()(const T* const x2, const T* const x3, T* residuals) const {\n    residuals[0] = (x2[0] - T(2)*x3[0])*(x2[0] - T(2)*x3[0]);\n    return true;\n  }\n};\n\nstruct CostFuntorF4 {\n  template <typename T>\n  bool operator()(const T* const x1, const T* const x4, T* residuals) const {\n    residuals[0] = sqrt(10)*(x1[0] - x4[0])*(x1[0] - x4[0]); \n    return true;\n  }\n};\n\nstruct CostFunctor {\n  template <typename T>\n  bool operator()(const T* const x, T* residuals)  const{\n    residuals[0] = x[0] - T(10) * x[1];\n    residuals[1] = T(sqrt(5)) * (x[2] - x[4]);\n    residuals[2] = (x[1] - T(2) * x[2]) * (x[1] - T(2) * x[2]);\n    residuals[3] = T(sqrt(10)) * (x[0] - x[3]) * (x[0] - x[3]);\n    return true;\n  }\n};\n\nint main(int argc, char** argv)\n{\n  const double initial_x1 = 10, initial_x2 = 5, \n\t       initial_x3 = 2, initial_x4 = 1;\n  double x1 = initial_x1, x2 = initial_x2,\n\t x3 = initial_x3, x4 = initial_x4;\n\t \n  Problem problem;\n  Solver::Options options;\n  //control whether the log is output to STDOUT\n  options.minimizer_progress_to_stdout = true;\n  Solver::Summary summary;\n  \n  CostFunction* costfunction1 = \n    new AutoDiffCostFunction<CostFuntorF1,1,1,1>(new CostFuntorF1);\n  CostFunction* costfunction2 = \n    new AutoDiffCostFunction<CostFuntorF2,1,1,1>(new CostFuntorF2);\n  CostFunction* costfunction3 = \n    new AutoDiffCostFunction<CostFuntorF3,1,1,1>(new CostFuntorF3);\n  CostFunction* costfunction4 = \n    new AutoDiffCostFunction<CostFuntorF4,1,1,1>(new CostFuntorF4);\n  problem.AddResidualBlock(costfunction1,NULL,&x1,&x2);\n  problem.AddResidualBlock(costfunction2,NULL,&x3,&x4);\n  problem.AddResidualBlock(costfunction3,NULL,&x2,&x3);\n  problem.AddResidualBlock(costfunction4,NULL,&x1,&x4);\n  \n  Solve(options,&problem,&summary);\n \n  cout << \"x1 : \" << initial_x1 << \"->\" << x1 << endl;\n  cout << \"x2 : \" << initial_x2 << \"->\" << x2 << endl;\n  cout << \"x3 : \" << initial_x3 << \"->\" << x3 << endl;\n  cout << \"x4 : \" << initial_x4 << \"->\" << x4 << endl;\n  \n  cout << \"---------------------line----------------------------\" << endl;\n  double x[4] = {initial_x1, initial_x2, initial_x3, initial_x4};\n  CostFunction* costfunction = new AutoDiffCostFunction<CostFunctor, 4, 4>(new CostFunctor);\n  Problem pb;\n  pb.AddResidualBlock(costfunction,NULL,x);\n  Solve(options,&pb,&summary);\n  cout << \"x[0] : \" << initial_x1 << \"->\" << x[0] << endl;\n  cout << \"x[1] : \" << initial_x2 << \"->\" << x[1] << endl;\n  cout << \"x[2] : \" << initial_x3 << \"->\" << x[2] << endl;\n  cout << \"x[3] : \" << initial_x4 << \"->\" << x[3] << endl;\n  \n  \n  return 0; \n  \n}\n\n", "meta": {"hexsha": "f752a42d484a2000eea59c71277704e492f35bb8", "size": 3269, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ceres/PowellFunction/PowellFunction.cpp", "max_stars_repo_name": "JiauZhang/camera", "max_stars_repo_head_hexsha": "37e37f9e5f5176c6c06d4a8fdd11d5532ab37eb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-10-08T01:46:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-11T08:17:44.000Z", "max_issues_repo_path": "ceres/PowellFunction/PowellFunction.cpp", "max_issues_repo_name": "JiauZhang/Camera", "max_issues_repo_head_hexsha": "37e37f9e5f5176c6c06d4a8fdd11d5532ab37eb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ceres/PowellFunction/PowellFunction.cpp", "max_forks_repo_name": "JiauZhang/Camera", "max_forks_repo_head_hexsha": "37e37f9e5f5176c6c06d4a8fdd11d5532ab37eb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-11T07:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-16T04:55:01.000Z", "avg_line_length": 30.2685185185, "max_line_length": 92, "alphanum_fraction": 0.6176200673, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6093448577479254}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/digamma.hpp>\n#include <test/unit/math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdBinomialCoefficientLog,Fvar) {\n  using stan::math::fvar;\n  using stan::math::binomial_coefficient_log;\n  using boost::math::digamma;\n\n  fvar<double> x(2004.0,1.0);\n  fvar<double> y(1002.0,2.0);\n\n  fvar<double> a = stan::math::binomial_coefficient_log(x, y);\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_);\n  EXPECT_FLOAT_EQ(0.69289774, a.d_);\n}\n\n\nTEST(AgradFwdBinomialCoefficientLog,FvarFvarDouble) {\n  using stan::math::fvar;\n  using stan::math::binomial_coefficient_log;\n  using stan::math::binomial_coefficient_log;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 2004.0;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 1002.0;\n  y.d_.val_ = 1.0;\n\n  fvar<fvar<double> > a = binomial_coefficient_log(x,y);\n\n  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_);\n  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_);\n  EXPECT_NEAR(0, a.d_.val_,1e-8);\n  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_);\n}\n\n\nstruct binomial_coefficient_log_fun {\n  template <typename T0, typename T1>\n  inline \n  typename boost::math::tools::promote_args<T0,T1>::type\n  operator()(const T0 arg1,\n             const T1 arg2) const {\n    return binomial_coefficient_log(arg1,arg2);\n  }\n};\n\nTEST(AgradFwdBinomialCoefficientLog, nan) {\n  binomial_coefficient_log_fun binomial_coefficient_log_;\n  test_nan_fwd(binomial_coefficient_log_,3.0,5.0,false);\n}\n", "meta": {"hexsha": "6f381a2306ad8fe59bfb2b3d5fc9ec2ad0e6f470", "size": 1533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/binomial_coefficient_log_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/binomial_coefficient_log_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/binomial_coefficient_log_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.375, "max_line_length": 72, "alphanum_fraction": 0.7292889759, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.609318486520515}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n#include <utils/types.hpp>\n\ntemplate<int Dimension>\nstruct Pose\n{\n    Eigen::Matrix<double, Dimension, Dimension> rotation;\n    Eigen::Matrix<double, Dimension, 1> translation;\n\n    /*\n     * Pose constructor\n    **/\n    Pose(const Eigen::Matrix<double, Dimension, Dimension>& r = Eigen::Matrix<double, Dimension, Dimension>::Identity(),\n         const Eigen::Matrix<double, Dimension, 1>& t = Eigen::Matrix<double, Dimension,1>::Zero())\n    : rotation(r), translation(t)\n    {}\n\n    /*\n     * Pose destructor\n    **/\n    ~Pose(){};\n};\n\nusing Pose2D = Pose<2>;\nusing Pose3D = Pose<3>;\n\nusing Poses2D = AlignedVector<Pose2D>;\nusing Poses3D = AlignedVector<Pose3D>;\n\n/*\n * the custom operator<< for Pose\n**/\ntemplate<int Dimension>\nstd::ostream& operator<<(std::ostream& os, const Pose<Dimension>& p)\n{\n    os << \"rotation:\\n\" << p.rotation.transpose() << \"\\n\";\n    os << \"translation: \" << p.translation.transpose();\n\n    return os;\n}\n", "meta": {"hexsha": "6961c5a565b648d8cf3ba91a3b42c986cfda7fa7", "size": 972, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geometry/pose.hpp", "max_stars_repo_name": "charlybigoud/kidocam", "max_stars_repo_head_hexsha": "5cf2d59194a48897b35f0e3c8e3cea39b748c3d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geometry/pose.hpp", "max_issues_repo_name": "charlybigoud/kidocam", "max_issues_repo_head_hexsha": "5cf2d59194a48897b35f0e3c8e3cea39b748c3d0", "max_issues_repo_licenses": ["MIT"], "max_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/pose.hpp", "max_forks_repo_name": "charlybigoud/kidocam", "max_forks_repo_head_hexsha": "5cf2d59194a48897b35f0e3c8e3cea39b748c3d0", "max_forks_repo_licenses": ["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.0909090909, "max_line_length": 120, "alphanum_fraction": 0.6409465021, "num_tokens": 246, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907933, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6092091002384976}}
{"text": "#include <armadillo>\n\nint main() {\n\n    const size_t dim = 6;\n    arma::mat A(dim, dim, arma::fill::ones);\n    A(arma::span(0, (dim / 2) - 1), arma::span(0, (dim / 2) - 1)).fill(-1.032e-310);\n    A.print(\"A\");\n    arma::vec eigval = arma::eig_sym(A);\n    eigval.print(\"eigval\");\n    arma::vec eigvalsqrt = arma::sqrt(eigval);\n    // This has junk tiny (negative) values that need to be removed.\n    eigvalsqrt.print(\"eigvalsqrt\");\n\n    const double thresh = 1.0e-15;\n    // arma::uvec mask = arma::abs(eigval) < thresh;\n    // mask.print(\"mask\");\n    // eigval(mask).zeros();\n    arma::uvec mask = arma::find(arma::abs(eigval) < thresh);\n    mask.print(\"mask\");\n    eigval(mask).zeros();\n    eigval.print(\"eigval\");\n    arma::sqrt(eigval).print(\"eigvalsqrt\");\n\n    return 0;\n}\n", "meta": {"hexsha": "9237ba0923c6c6228e64b9392006b890fc0dc898", "size": 777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/armadillo/arma_test_mask_index.cpp", "max_stars_repo_name": "berquist/eg", "max_stars_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/armadillo/arma_test_mask_index.cpp", "max_issues_repo_name": "berquist/eg", "max_issues_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/armadillo/arma_test_mask_index.cpp", "max_forks_repo_name": "berquist/eg", "max_forks_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7777777778, "max_line_length": 84, "alphanum_fraction": 0.5907335907, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.6723316991792861, "lm_q1q2_score": 0.6091256804973278}}
{"text": "//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//% Code implementing the paper \"Accelerated Quadratic Proxy for Geometric Optimization\", SIGGRAPH 2016.\n//% Disclaimer: The code is provided as-is for academic use only and without any guarantees. \n//%             Please contact the author to report any bugs.\n//% Written by Shahar Kovalsky (http://www.wisdom.weizmann.ac.il/~shaharko/)\n//%            Meirav Galun (http://www.wisdom.weizmann.ac.il/~/meirav/)\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n#include \"mex.h\"\n#include <Eigen/Dense>\n#include <Eigen/SparseCore>\n#include \"mexHelpers.cpp\"\n\nusing namespace Eigen;\n\nvoid projBlockRotation(VectorXd &pA, int dim)\n{\n\tint block_size = dim*dim;\n\tint num_blocks = pA.size() / block_size;\n\tJacobiSVD<MatrixXd> svdA(dim, dim, (ComputeFullU | ComputeFullV));\n\tbool flipped;\n\tMatrixXd U, V;\n\tMap<MatrixXd> currA(pA.data(), dim, dim);\n\n\t// project\n\tfor (int ii = 0; ii < num_blocks; ii++)\n\t{\n\t\t// get current block\n\t\tnew (&currA) Map<MatrixXd>(pA.data() + ii*block_size, dim, dim);\n\t\t// sign of determinant \n\t\tflipped = (currA.determinant() < 0);\n\t\t// svd\n\t\tsvdA.compute(currA);\n\t\t// compute frames\n\t\tU = svdA.matrixU();\n\t\tV = svdA.matrixV();\n\t\t// ssvd\n\t\tif (flipped)\n\t\t{\n\t\t\tU.col(dim - 1) = -U.col(dim - 1);\n\t\t}\n\t\t// project block\n\t\tcurrA = U*V.transpose();\n\t}\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[],\n\tint nrhs, const mxArray*prhs[])\n\n{\n\t// assign input\n\tint A_rows = mxGetM(prhs[0]); // # rows of A\n\tint A_cols = mxGetN(prhs[0]); // # cols of A\n\tdouble *dim;\n\tconst Map<VectorXd> A(mxGetPr(prhs[0]), A_rows, A_cols);\n\tdim = mxGetPr(prhs[1]);\n\t\n\t// init output\n\tVectorXd pA(A_rows);\n\tpA = A;\n\n\t// project\n\tprojBlockRotation(pA, *dim);\n\t\n\t// assign outputs\n\tmapDenseMatrixToMex(pA, &(plhs[0]));\n\n}", "meta": {"hexsha": "5e2ac9259cbd196f737c74e8d111c593561d3184", "size": 1815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mex/projectRotationMex.cpp", "max_stars_repo_name": "shaharkov/AcceleratedQuadraticProxy", "max_stars_repo_head_hexsha": "876078c2c67c9058b50ba072397013346004f63f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-06-08T11:12:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T06:45:26.000Z", "max_issues_repo_path": "mex/projectRotationMex.cpp", "max_issues_repo_name": "shaharkov/AcceleratedQuadraticProxy", "max_issues_repo_head_hexsha": "876078c2c67c9058b50ba072397013346004f63f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mex/projectRotationMex.cpp", "max_forks_repo_name": "shaharkov/AcceleratedQuadraticProxy", "max_forks_repo_head_hexsha": "876078c2c67c9058b50ba072397013346004f63f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-10-17T12:48:18.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-18T14:03:11.000Z", "avg_line_length": 26.6911764706, "max_line_length": 104, "alphanum_fraction": 0.6011019284, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.6091256744994039}}
{"text": "\ufeff/*! \\file solveeom.cpp\n    \\brief \u5358\u632f\u308a\u5b50\u306b\u5bfe\u3057\u3066\u904b\u52d5\u65b9\u7a0b\u5f0f\u3092\u89e3\u304f\u30af\u30e9\u30b9\u306e\u5b9f\u88c5\n\n    Copyright \u00a9 2016-2018 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n#include \"solveeom.h\"\n#include <cmath>                                // for std::sin, std::cos\n#include <fstream>                              // for std::ofstream\n#include <boost/assert.hpp>                     // for BOOST_ASSERT\n#include <boost/format.hpp>                     // for boost::format\n#include <boost/math/constants/constants.hpp>   // for boost::math::constants::pi\n#include \"solveeommain.h\"\n\nnamespace solveeom {\n    // #region \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u30fb\u30c7\u30b9\u30c8\u30e9\u30af\u30bf\n\n    SolveEoM::SolveEoM(float l, float r, float theta0) :\n\t\tIsconsider_Inertial_Resistance(nullptr, [this](auto isconsider_inertial_resistance) { return isconsider_inertial_resistance_ = isconsider_inertial_resistance; }),\n        Theta([this] { return static_cast<float>(x_[0]); }, [this](auto theta) { return x_[0] = theta; }),\n\t\tTheta0(nullptr, [this](auto theta0) { return theta0_ = theta0; }),\n\t\tTime([this] { return static_cast<float>(t_); }, [this](auto t) { return t_ = t; }),\n\t\tV([this] { return static_cast<float>(l_ * x_[1]); }, [this](auto v) { return x_[1] = v / l_; }),\n        l_(l),\n\t\tomega0_2_(g / l_),\n        r_(r),\n\t\tm_(4.0 / 3.0 * boost::math::constants::pi<double>() * r * r * r * SolveEoM::ALUMINIUMRHO),\n\t\tgamma_(3.0 * boost::math::constants::pi<double>() * r_ * AIRMYU / m_),\n\t\tstepper_(SolveEoM::EPS, SolveEoM::EPS),\n\t\tt_(0.0),\n\t\ttheta0_(theta0),\n\t\tx_({ theta0, 0.0 })\n    {\n    }\n\n    // #endregion \u30b3\u30f3\u30b9\u30c8\u30e9\u30af\u30bf\u30fb\u30c7\u30b9\u30c8\u30e9\u30af\u30bf\n\n    // #region public\u30e1\u30f3\u30d0\u95a2\u6570\n\n\tfloat SolveEoM::gettheta_fumofumobun_approx() const\n\t{\n\t\treturn static_cast<float>(theta0_ * std::exp(-gamma_ * t_) *\n\t\t\t\t\t\t\t\t  std::cos(std::sqrt((omega0_2_ - gamma_ * gamma_) * (3.0 + std::cos(theta0_ * std::exp(-gamma_ * t_)))) / 2.0 * t_));\n\t}\n\n\tfloat SolveEoM::getv_fumofumobun_approx() const\n    {\n\t\tauto const term1 = -gamma_ * gettheta_fumofumobun_approx();\n\n\t\tauto const alpha = 0.5 * std::sqrt((omega0_2_ - gamma_ * gamma_) * (3.0 + std::cos(theta0_ * std::exp(-gamma_ * t_))));\n\n\t\tauto const term2 = -alpha * theta0_* std::exp(-gamma_ * t_) * std::sin(alpha * t_) *\n\t\t\t\t\t\t   (0.5 * theta0_ * gamma_ * std::exp(-gamma_ * t_) * std::sin(theta0_ * std::exp(-gamma_ * t_)) /\n\t\t\t\t\t\t   (3.0 + std::cos(theta0_ * std::exp(-gamma_ * t_))) * t_ + 1.0);\n\n\t\treturn l_ * (term1 + term2);\n    }\n\n\tfloat SolveEoM::kinetic_energy(double v) const\n\t{\n\t\treturn static_cast<float>(0.5 * m_ * sqr(v));\n\t}\n\n    float SolveEoM::operator()(float dt)\n    {\n        boost::numeric::odeint::integrate_adaptive(\n            stepper_,\n            getEoM(),\n            x_,\n            0.0,\n            static_cast<double>(dt),\n            SolveEoM::DX);\n\n        return static_cast<float>(x_[0]);\n    }\n\t\n    void SolveEoM::operator()(double dt, std::string const & filename, double t)\n    {\n        std::ofstream result(filename);\n\n        boost::numeric::odeint::integrate_const(\n            stepper_,\n            getEoM(),\n            x_,\n            0.0,\n            t,\n            dt,\n            [&result, this](auto const & x, auto const t)\n            {\n\t\t\t\tresult << boost::format(\"%.3f, %.15f, %.15f\\n\") % t % x[0] % gettheta_fumofumobun_approx();\n            });\n    }\n\n\tfloat SolveEoM::potential_energy(double theta) const\n\t{\n\t\treturn static_cast<float>(m_ * SolveEoM::g * l_ * (1.0 - std::cos(theta)));\n\t}\n\n\tvoid SolveEoM::timereset()\n    {\n\t\tt_ = 0.0;\n    }\n\n    // #endregion public\u30e1\u30f3\u30d0\u95a2\u6570\n\n    // #region private\u30e1\u30f3\u30d0\u95a2\u6570\n\n\tstd::function<void(SolveEoM::state_type const &, SolveEoM::state_type &, double const)> SolveEoM::getEoM() const\n    {\n        auto const eom = [this](state_type const & x, state_type & dxdt, double const)\n        {\n            // d\u03b8/dt = v / l\n            dxdt[0] = x[1];\n\n            // \u632f\u308a\u5b50\u306b\u50cd\u304f\u529b\n            auto const f1 = -SolveEoM::g * std::sin(x[0]) / l_;\n\n\t\t\t// \u30ec\u30a4\u30ce\u30eb\u30ba\u6570\n\t\t\tauto const Re = 2.0 * r_ * std::fabs(l_ * x[1]) / AIRNYU;\n\n            // \u7c98\u6027\u62b5\u6297\n            auto const F = 6.0 * boost::math::constants::pi<double>() * AIRMYU * r_ * l_ * x[1];\n\n\t\t\t// \u30ec\u30a4\u30ce\u30eb\u30ba\u6570\u304c\u95be\u5024\u3088\u308a\u5c0f\u3055\u3044\u304b\u3001\u300c\u6163\u6027\u62b5\u6297\u3082\u8003\u616e\u300d\u30c1\u30a7\u30c3\u30af\u30dc\u30c3\u30af\u30b9\u304c\u5916\u308c\u3066\u3044\u305f\u3089\n\t\t\tif (Re < SolveEoM::REYNOLDS_THRESHOLD || !isconsider_inertial_resistance_) {\n\t\t\t\t// \u7c98\u6027\u62b5\u6297\u306e\u307f\u3092\u8003\u616e\u3059\u308b\n\t\t\t\tdxdt[1] = f1 - F / (m_ * l_);\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tauto const FD = 0.5 * AIRRHO * boost::math::constants::pi<double>() * sqr(r_ * (l_ * x[1]));\n\n\t\t\t// Drag coefficient\n\t\t\tdouble CD;\n\n\t\t\t// N.-S. Cheng, Comparison of formulas for drag coefficient and settling velocity of\n\t\t\t// spherical particles, Powder Technology 189 (2009) 395\u2013398.\n\t\t\tif (Re <= 3000) {\n\t\t\t\tCD = 24.0 / Re * std::pow(1.0 + 0.27 * Re, 0.43) + 0.47 * (1.0 - std::exp(-0.04 * std::pow(Re, 0.38)));\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Re > 3000\n\t\t\t\t// Almedeij J. Drag coefficient of flow around a sphere: Matching asymptotically the wide\n\t\t\t\t// trend. std::powder Technology. (2008);doi:10.1016/j.std::powtec.2007.12.006.\n\t\t\t\tauto const phi1 = std::pow(24.0 / Re, 10) + std::pow(21.0 * std::pow(Re, -0.67), 10) +\n\t\t\t\t\tstd::pow(4.0 * std::pow(Re, -0.33), 10) + std::pow(0.4, 10);\n\t\t\t\tauto const phi2 = 1.0 / (1.0 / std::pow(0.148 * std::pow(Re, 0.11), 10) + 1.0 / std::pow(0.5, 10));\n\t\t\t\tauto const phi3 = std::pow((1.57E+8) * std::pow(Re, -1.625), 10);\n\t\t\t\tauto const phi4 = 1.0 / (1.0 / std::pow((6.0E-17) * std::pow(Re, 2.63), 10) + 1.0 / std::pow(0.2, 10));\n\n\t\t\t\tCD = std::pow((1.0 / (1.0 / (phi1 + phi2) + 1.0 / phi3) + phi4), 0.1);\n\t\t\t}\n\n\t\t\t// \u6163\u6027\u62b5\u6297\u00f7(m\u00d7l)\n\t\t\tauto const f2 = (x[1] >= 0.0) ? -FD * CD / (m_ * l_) : FD * CD / (m_ * l_);\n\t\t\tdxdt[1] = f1 + f2 - F / (m_ * l_);\n        };\n\n        return eom;\n    }\n\n    // #endregion private\u30e1\u30f3\u30d0\u95a2\u6570\n}\n", "meta": {"hexsha": "5163d2131b88219156ed1e323368d45165b1f9e9", "size": 5637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solveeom/solveeom/solveeom.cpp", "max_stars_repo_name": "dc1394/simplependulum_fumofumobun_approx", "max_stars_repo_head_hexsha": "423d3504962e1958630255425f287581f1d255a5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-13T01:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-13T01:11:59.000Z", "max_issues_repo_path": "solveeom/solveeom/solveeom.cpp", "max_issues_repo_name": "dc1394/simplependulum_fumofumobun_approx", "max_issues_repo_head_hexsha": "423d3504962e1958630255425f287581f1d255a5", "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": "solveeom/solveeom/solveeom.cpp", "max_forks_repo_name": "dc1394/simplependulum_fumofumobun_approx", "max_forks_repo_head_hexsha": "423d3504962e1958630255425f287581f1d255a5", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-13T01:12:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-13T01:12:01.000Z", "avg_line_length": 34.1636363636, "max_line_length": 164, "alphanum_fraction": 0.5643072556, "num_tokens": 2082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6091186815249373}}
{"text": "/**\n * \\file dcs/math/stats/distribution/chi_squared.hpp\n *\n * \\brief The (Negative) Chi Squared probability distribution.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_STATS_DISTRIBUTION_CHI_SQUARED_HPP\n#define DCS_MATH_STATS_DISTRIBUTION_CHI_SQUARED_HPP\n\n\n#include <dcs/detail/config/boost.hpp>\n\n#if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(103500) // 1.35\n# \terror \"Required Boost library version >= 1.35\"\n#endif\n\n#include <boost/math/distributions/chi_squared.hpp>\n#include <cstddef>\n#include <dcs/math/policies/policy.hpp>\n#include <dcs/math/stats/distribution/gamma.hpp>\n#include <dcs/math/stats/function/rand.hpp>\n#include <iostream>\n#include <vector>\n\n\nnamespace dcs { namespace math { namespace stats {\n\n/**\n * \\brief The Chi Squared distribution with degrees of freedom parameter\n * \\f$\\nu\\f$.\n *\n *\n * \\tparam RealT The type used for real numbers.\n * \\tparam PolicyT The policy type.\n *\n * The probability density function (pdf):\n * \\f[\n *   \\Pr(x|\\nu) = \\frac{1}{2^{k/2}\\Gamma(k/2)}\\; x^{k/2-1} e^{-x/2}\n * \\f]\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate < typename RealT=double, typename PolicyT=::dcs::math::policies::policy<> >\nclass chi_squared_distribution\n{\n\tpublic: typedef RealT support_type;\n\tpublic: typedef RealT value_type;\n\tpublic: typedef PolicyT policy_type;\n\n\tpublic: explicit chi_squared_distribution(support_type df)\n\t\t: dist_(df)\n\t{\n\t\t// empty\n\t}\n\n\n\t// compiler-generated copy ctor and assignment operator are fine\n\n\n\t/**\n\t * \\brief Generate a random number distributed according to this\n\t * chi_squared distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\return A random number distributed according to this chi_squared\n\t * distribution.\n\t *\n\t * A \\c chi_squared random number distribution produces random numbers\n\t * \\f$x > 0\\f$ distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|\\nu) = \\frac{1}{2^{k/2}\\Gamma(k/2)}\\; x^{k/2-1} e^{-x/2}\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\tsupport_type rand(UniformRandomGeneratorT& rng) const\n\t{\n\t\treturn ::dcs::math::stats::rand(\n\t\t\tgamma_distribution<value_type>(\n\t\t\t\tdist_.degrees_of_freedom()/value_type(2),\n\t\t\t\tvalue_type(2)\n\t\t\t),\n\t\t\trng\n\t\t);\n\t}\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * chi_squared distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A vector of random numbers distributed according to this\n\t * chi_squared distribution.\n\t *\n\t * A \\c chi_squared random number distribution produces random numbers\n\t * \\f$x > 0\\f$ distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|\\nu) = \\frac{1}{2^{k/2}\\Gamma(k/2)}\\; x^{k/2-1} e^{-x/2}\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\t::std::vector<support_type> rand(UniformRandomGeneratorT& rng, ::std::size_t n) const\n\t{\n\t\t::std::vector<support_type> rnds(n);\n\n        for ( ; n > 0; --n)\n\t\t{\n\t\t\trnds.push_back(\n\t\t\t\t::dcs::math::stats::rand(\n\t\t\t\t\tgamma_distribution<value_type>(\n\t\t\t\t\t\tdist_.degrees_of_freedom()/value_type(2),\n\t\t\t\t\t\tvalue_type(2)\n\t\t\t\t\t),\n\t\t\t\t\trng\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\n\t\treturn rnds;\n\t}\n\n\n\tpublic: support_type degrees_of_freedom() const\n\t{\n\t\treturn dist_.degrees_of_freedom();\n\t}\n\n\n\tpublic: support_type quantile(value_type p) const\n\t{\n\t\treturn ::boost::math::quantile(dist_, p);\n\t}\n\n\n\tprivate: ::boost::math::chi_squared_distribution<value_type,policy_type> dist_;\n};\n\n\ntemplate <\n\ttypename CharT,\n\ttypename CharTraitsT,\n\ttypename RealT,\n\ttypename PolicyT\n>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, chi_squared_distribution<RealT,PolicyT> const& dist)\n{\n\treturn os << \"ChiSquared(\"\n\t\t\t  << \"df=\" <<  dist.degrees_of_freedom()\n\t\t\t  << \")\";\n}\n\n}}} // Namespace dcs::math::stats\n\n#endif // DCS_MATH_STATS_DISTRIBUTION_CHI_SQUARED_HPP\n", "meta": {"hexsha": "9bf49cedb48d2e5594c82ba7eda1af0a329501bf", "size": 4574, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/chi_squared.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/stats/distribution/chi_squared.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/stats/distribution/chi_squared.hpp", "max_forks_repo_name": "sguazt/dcsxx-commons", "max_forks_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2873563218, "max_line_length": 149, "alphanum_fraction": 0.7037603848, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951143326726, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6090755756991012}}
{"text": "#include \"CEGO/CEGO.hpp\"\n#include <Eigen/Dense>\n#if defined(PYBIND11)\n#include <pybind11/embed.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <pybind11/stl.h>\n#include <pybind11/eigen.h>\nnamespace py = pybind11;\n#endif\n#include <atomic>\n\nstd::atomic_size_t Ncalls(0);\nusing CEGO::EArray;\n\nclass Bumps {\npublic:\n    std::size_t Nbumps;\n    Eigen::ArrayXd xb0, yb0, xp, yp, zp;\n    double gamma = 5;\n    \n    Bumps(std::size_t Nbumps, std::size_t Npoints) : Nbumps(Nbumps) {\n        xb0 = (Eigen::ArrayXd::Random(Nbumps)*10).round();\n        yb0 = (Eigen::ArrayXd::Random(Nbumps)*10).round();\n        \n        xp = Eigen::ArrayXd::Random(Npoints)*10;\n        yp = Eigen::ArrayXd::Random(Npoints)*10;\n        zp = f_givenxy(xb0, yb0, xp, yp);\n\n        Eigen::ArrayXd c = xb0; c.conservativeResize(xb0.size() * 2); c.tail(Nbumps) = yb0;\n        double checkval = objective(c);\n        assert(std::abs(checkval) < 1e-16);\n    }\n    /**\n     * @brief Calculate the functional value for a set of vectors of points\n     * @brief xb The x coordinate of the center of the bump\n     * @brief yb The y coordinate of the center of the bump\n     * @brief x The x coordinate of the points to be evaluated\n     * @brief y The y coordinate of the points to be evaluated\n     */\n    Eigen::ArrayXd f_givenxy(const Eigen::ArrayXd &xb, const Eigen::ArrayXd &yb, const Eigen::ArrayXd&x, const Eigen::ArrayXd &y) {\n        Eigen::ArrayXd s = Eigen::ArrayXd::Zero(x.size());\n        for (auto i = 0; i < xb.size(); ++i) {\n            s += (-gamma*(x-xb[i]).square() - gamma*(y-yb[i]).square()).exp();\n        }\n        return s;\n    }\n    double objective(const CEGO::AbstractIndividual *pind) {\n        const EArray<double> &c = static_cast<const CEGO::NumericalIndividual<double>*>(pind)->get_coefficients();\n        return objective(c);\n    }\n    double objective_vec(const EArray<double> &c) {\n        return objective(c);\n    }\n    double penalty_vec(const EArray<double> &c) {\n        return penalty(c);\n    }\n    double penalty(const Eigen::ArrayXd &c) {\n        Eigen::ArrayXd q = c - c.floor();\n        constexpr double MY_PI = 3.14159265358979323846;\n        Eigen::ArrayXd penalty = 0.25*(0.5 - 0.5*cos(2*MY_PI*q));\n        return 100*penalty.sum();\n    }\n    double objective(const Eigen::ArrayXd &c) {\n        Ncalls ++;\n        return (f_givenxy(c.head(Nbumps), c.tail(Nbumps), xp, yp) - zp).square().sum() + penalty(c);\n    }\n    void plot_surface() {\n        #if defined(PYBIND11)\n        using namespace pybind11::literals;\n        py::module plt = py::module::import(\"matplotlib.pyplot\"); // Import matplotlib\n        std::size_t Nx = 100, Ny = 100;\n        Eigen::MatrixXd X = Eigen::RowVectorXd::LinSpaced(Nx, -1, 1).replicate(Ny, 1);\n        Eigen::MatrixXd Y = Eigen::VectorXd::LinSpaced(Ny, -1, 1).replicate(Nx, 1);\n        X.resize(Nx*Ny,1); Y.resize(Nx*Ny,1);\n        Eigen::MatrixXd Z = f_givenxy(xb0, yb0, X.array(), Y.array()).matrix();\n        X.resize(Nx, Ny); Y.resize(Nx, Ny); Z.resize(Nx, Ny);\n        plt.attr(\"contourf\")(X, Y, Z, \"N\"_a=3000);\n        plt.attr(\"scatter\")(xp, yp);\n        plt.attr(\"show\")();\n        #else\n        std::cout << \"No pybind11 support, so no plots\\n\";\n        #endif\n    }\n    void plot_trace(const std::vector<double> &best_costs) {\n        #if defined(PYBIND11)\n        py::module plt = py::module::import(\"matplotlib.pyplot\"); // Import matplotlib\n        plt.attr(\"plot\")(best_costs);\n        plt.attr(\"show\")();\n        #else\n        std::cout << \"No pybind11 support, so no plots\\n\";\n        #endif\n    }\n};\n\nvoid do_one(const std::size_t Nbumps, const std::string &root, std::size_t i) {\n\n    std::srand((unsigned int)time(0));\n\n    std::size_t Npoints = Nbumps*10;\n    Bumps bumps(Nbumps, Npoints);\n    //bumps.plot_surface();\n\n    auto D = 2*Nbumps; // twice because they are pairs\n    CEGO::CostFunction<double> cost_wrapper = std::bind((double (Bumps::*)(const CEGO::AbstractIndividual *)) &Bumps::objective, bumps, std::placeholders::_1);\n    auto layers = CEGO::Layers<double>(cost_wrapper, D, 30*D, 1, 10);\n    // Apply the bounds (all in [-1,1])\n    layers.set_bounds(std::vector<CEGO::Bound>(D, CEGO::Bound(std::pair<double, double>(-15.0, 15.0))));\n    layers.parallel = true;\n    layers.parallel_threads = 4;\n    layers.set_builtin_evolver(CEGO::BuiltinEvolvers::differential_evolution); \n    auto fl = layers.get_evolver_flags();\n    fl[\"CR\"] = 0.9;\n    fl[\"Fmin\"] = 0.5; \n    fl[\"Fmax\"] = 0.5;\n    fl[\"Nelite\"] = 1;\n    layers.set_evolver_flags(fl);\n\n    auto f = [](const CEGO::Result &r) { \n        if (r.ssq < 1) { \n            return CEGO::FilterOptions::accept; \n        }\n        else {\n            return CEGO::FilterOptions::reject;\n        }\n    };\n    layers.set_filtering_function(f);\n    layers.set_logging_scheme(CEGO::LoggingScheme::custom);\n\n    std::vector<double> best_costs; \n    std::vector<std::vector<double> > objs;\n    double VTR = 1e-14, best_cost = 999999.0;\n    auto startTime = std::chrono::system_clock::now();\n    for (auto counter = 0; counter < 500000; ++counter) {\n        layers.do_generation();\n\n        // Store the best objective function in each layer\n        std::vector<double> oo;\n        for (auto &&cost_coefficients : layers.get_best_per_layer()) {\n            oo.push_back(std::get<0>(cost_coefficients));\n        }\n        objs.push_back(oo);\n\n        // For the overall best result, print it, and write JSON to file\n        auto best_layer = layers.get_best();\n        best_cost = std::get<0>(best_layer); best_costs.push_back(best_cost);\n        auto best_coeffs = std::get<1>(best_layer);\n        if (counter % 10 == 0){\n            std::cout << counter << \": best-penalty: \" << best_cost-bumps.penalty_vec(best_coeffs) << \"; best: \" << best_cost << \"\\n \";// << CEGO::vec2string(best_coeffs) << \"\\n\";\n        }\n        if (best_cost < VTR){ break; }\n    }\n    auto endTime = std::chrono::system_clock::now();\n    double elap = std::chrono::duration<double>(endTime - startTime).count();\n    std::cout << \"run:\" << elap << \" s\\n\";\n\n    //bumps.plot_trace(best_costs);\n    FILE* fp = fopen((root + \"run-\" + std::to_string(i) + \".txt\").c_str(), \"w\");\n    for (auto j = 0; j < best_costs.size(); ++j){\n        fprintf(fp, \"%12.8e\", best_costs[j]);\n        if (j < best_costs.size() - 1) {\n            fprintf(fp, \", \");\n        }\n    }\n    fclose(fp);\n    std::cout << bumps.xb0 << std::endl;\n    std::cout << bumps.yb0 << std::endl;\n    std::cout << \"NFE:\" << Ncalls << std::endl;\n}\n\nint main() {\n    for (auto i = 0; i < 10; ++i) {\n        do_one(5, \"N5-\", i);\n    }\n    for (auto i = 0; i < 10; ++i) {\n        do_one(10, \"N10-\", i);\n    }\n}\n", "meta": {"hexsha": "d3f3c96ce33c4f56dc2b9def406eb08755ccf860", "size": 6673, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/inverse_gaussian.cxx", "max_stars_repo_name": "usnistgov/CEGO", "max_stars_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-12-27T23:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T02:23:40.000Z", "max_issues_repo_path": "src/inverse_gaussian.cxx", "max_issues_repo_name": "usnistgov/CEGO", "max_issues_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-03-17T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T15:27:44.000Z", "max_forks_repo_path": "src/inverse_gaussian.cxx", "max_forks_repo_name": "usnistgov/CEGO", "max_forks_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-02-27T18:01:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T19:44:15.000Z", "avg_line_length": 37.2793296089, "max_line_length": 179, "alphanum_fraction": 0.5895399371, "num_tokens": 1987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6090755671983158}}
{"text": "// Copyright (c) 2005-2009  INRIA Sophia-Antipolis (France).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org)\n//\n// $URL$\n// $Id$\n// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial\n//\n//\n// Author(s)     : Fr\u00e9d\u00e9rik Paradis\n\n#include <iostream>\n#include <CGAL/Exact_predicates_exact_constructions_kernel_with_root_of.h>\n#include <CGAL/CGAL_Ipelet_base.h>\n#include <CGAL/Construct_theta_graph_2.h>\n#include <CGAL/Construct_yao_graph_2.h>\n#include <CGAL/Compute_cone_boundaries_2.h>\n#include <CGAL/Cone_spanners_enum_2.h>\n#include <CGAL/property_map.h>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n\nnamespace CGAL_cone_spanners {\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel_with_root_of Kernel;\ntypedef Kernel::Point_2                                                Point_2;\ntypedef Kernel::Direction_2                                            Direction_2;\n\n/* Note: due to a bug in the boost library, using a directed graph\n * will cause a compilation error with g++ and clang++ when using c++11 standard.\n * See https://lists.boost.org/Archives/boost/2016/05/229458.php.\n */\ntypedef boost::adjacency_list<boost::listS,\n                              boost::vecS,\n                              boost::undirectedS,\n                              Point_2\n                             > Graph;\n\nconst std::string labels[] = {  \"Theta-k-graph\", \"Yao-k-graph\", \"Half-theta-k-graph with even cones\", \"Half-Yao-k-graph with even cones\", \"Half-theta-k-graph with odd cones\", \"Half-Yao-k-graph with odd cones\", \"k cones\", \"Help\" };\nconst std::string hmsg[] = {\n  \"Draws a theta-graph with k cones.\",\n  \"Draws a Yao-graph with k cones.\",\n  \"Draws an half-theta-graph with the even of k cones.\",\n  \"Draws an half-Yao-graph with the even of k cones.\",\n  \"Draws an half-theta-graph with the odd of k cones.\",\n  \"Draws an half-Yao-graph with the odd of k cones.\",\n  \"Draws k cones around the points.\",\n};\n\nclass Cone_spanners_ipelet\n  : public CGAL::Ipelet_base<Kernel,7> {\npublic:\n  Cone_spanners_ipelet()\n    :CGAL::Ipelet_base<Kernel,7>(\"Cone Spanners\",labels,hmsg){}\n  void protected_run(int);\nprivate:\n};\n\nvoid Cone_spanners_ipelet::protected_run(int fn)\n{\n  std::vector<Point_2> lst;\n  int number_of_cones;\n  switch (fn){\n    case 0:\n    case 1:\n    case 2:\n    case 3:\n    case 4:\n    case 5:\n    case 6:\n    {\n      std::vector<Point_2> points_read;\n      read_active_objects(\n        CGAL::dispatch_or_drop_output<Point_2>(std::back_inserter(points_read))\n      );\n\n      if (points_read.empty()) {\n        print_error_message(\"No mark selected\");\n        return;\n      }\n      for(std::vector<Point_2>::iterator it = points_read.begin(); it != points_read.end(); it++) {\n        if(std::find(points_read.begin(), it, *it) == it) {\n          lst.push_back(*it);\n        }\n      }\n\n      int ret_val;\n      boost::tie(ret_val,number_of_cones)=request_value_from_user<int>(\"Enter the number of cones\");\n      if (ret_val < 0) {\n        print_error_message(\"Incorrect value\");\n        return;\n      }\n      if(number_of_cones < 2) {\n        print_error_message(\"The number of cones must be larger than 1!\");\n        return;\n      }\n      break;\n    }\n    case 7:\n      show_help();\n      return;\n  }\n\n  if(fn >= 0 && fn <= 5) {\n    CGAL::Cones_selected cones_selected = CGAL::ALL_CONES;\n    if(fn == 2 || fn == 3)\n      cones_selected = CGAL::EVEN_CONES;\n    else if(fn == 4 || fn == 5)\n      cones_selected = CGAL::ODD_CONES;\n\n    Graph g;\n    switch (fn){\n      case 0:\n      case 2:\n      case 4:\n      {\n        CGAL::Construct_theta_graph_2<Kernel, Graph> theta(number_of_cones, Direction_2(1,0), cones_selected);\n        theta(lst.begin(), lst.end(), g);\n        break;\n      }\n      case 1:\n      case 3:\n      case 5:\n      {\n        CGAL::Construct_yao_graph_2<Kernel, Graph> yao(number_of_cones, Direction_2(1,0), cones_selected);\n        yao(lst.begin(), lst.end(), g);\n        break;\n      }\n    }\n    boost::graph_traits<Graph>::edge_iterator ei, ei_end;\n    for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n      boost::graph_traits<Graph>::edge_descriptor e = *ei;\n      boost::graph_traits<Graph>::vertex_descriptor  u = source(e, g);\n      boost::graph_traits<Graph>::vertex_descriptor  v = target(e, g);\n      draw_in_ipe(Segment_2(g[u], g[v]));\n    }\n    group_selected_objects_();\n  }\n  else if(fn == 6) {\n    CGAL::Compute_cone_boundaries_2<Kernel> cones;\n    std::vector<Direction_2> directions(number_of_cones);\n    cones(number_of_cones, Direction_2(1,0), directions.begin());\n    for(std::vector<Point_2>::iterator it = lst.begin(); it != lst.end(); it++) {\n      for(std::vector<Direction_2>::iterator dir = directions.begin(); dir != directions.end(); dir++) {\n        draw_in_ipe(Segment_2(*it,*it + 100*dir->to_vector()));\n      }\n      group_selected_objects_();\n      get_IpePage()->deselectAll();\n    }\n  }\n}\n\n\n}\n\nCGAL_IPELET(CGAL_cone_spanners::Cone_spanners_ipelet)\n", "meta": {"hexsha": "1d8b8924fdda8626d291da865f5b485d916853ef", "size": 4997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/demo/CGAL_ipelets/cone_spanners.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/lib/CGAL/demo/CGAL_ipelets/cone_spanners.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreSystem/lib/CGAL/demo/CGAL_ipelets/cone_spanners.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 31.6265822785, "max_line_length": 230, "alphanum_fraction": 0.6255753452, "num_tokens": 1369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7217432122827967, "lm_q1q2_score": 0.6090755564802451}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::chi_squared.hpp                                                  //\n//                                                                          //\n//  (C) Copyright 2009 Erwann Rogard                                        //\n//  Use, modification and distribution are subject to the                   //\n//  Boost Software License, Version 1.0. (See accompanying file             //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)        //\n//////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_RANDOM_CHI_SQUARED_HPP_ER_2009\n#define BOOST_RANDOM_CHI_SQUARED_HPP_ER_2009\n#include <vector>\n#include <algorithm>\n#include <iterator>\n#include <boost/range.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/chi_squared.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n\nnamespace boost{\nnamespace random{\n\n    template<typename T>\n    class chi_squared_distribution{\n            typedef boost::normal_distribution<T> nd_t;\n        public:\n            typedef typename nd_t::input_type input_type;\n            typedef typename nd_t::result_type result_type;\n\n        chi_squared_distribution(): df_(2) {}\n        chi_squared_distribution(unsigned df): df_(df) {}\n        chi_squared_distribution(const chi_squared_distribution& that)\n        :df_(that.df_){}\n        chi_squared_distribution&\n        operator=(const chi_squared_distribution& that){\n            if(&that!=this){\n                df_ = that.df_;\n            }\n            return *this;\n        }\n\n        template<typename U>\n        result_type\n        operator()(U& urng){\n            typedef boost::variate_generator<U&,nd_t> vg_t;\n            static nd_t nd(0,1);\n            result_type z;\n            result_type res = static_cast<T>(0);\n            for(unsigned i = 0; i<this->df(); i++){\n                z = nd(urng);\n                res += (z * z);\n            }\n            return res;\n        }\n\n        result_type min () const { return static_cast<result_type>(0); }\n        result_type max () const { return (nd_t().max)(); }\n        unsigned df()const { return df_; }\n        \n        typedef math::chi_squared_distribution<T> math_dist_;\n        \n        operator math_dist_ (){ return math_dist(this->df()); }\n                \n        private:\n            unsigned df_;\n    };\n\n}\n}\n\n\n#endif // CHI_SQUARE_HPP_INCLUDED\n", "meta": {"hexsha": "6ddfd827682240694a6a14f2a39451a7dcb27d40", "size": 2524, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/chi_squared.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "random/boost/random/chi_squared.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "random/boost/random/chi_squared.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5753424658, "max_line_length": 78, "alphanum_fraction": 0.5253565769, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6090755356604145}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\nusing namespace std;\n\nint main( int argc, char** argv )\n{\n    Eigen::Quaterniond q1(0.35, 0.2, 0.3, 0.1);\n    Eigen::Quaterniond q2(-0.5, 0.4, -0.1, 0.2);\n    Eigen::Vector3d t1(0.3, 0.1, 0.1);\n    Eigen::Vector3d t2(-0.1, 0.5, 0.3);\n    Eigen::Vector3d p1(0.5, 0, 0.2);\n    \n    Eigen::Quaterniond q1_one = q1.normalized();\n    Eigen::Quaterniond q2_one = q2.normalized();\n    \n    \n    //way1\n    \n    Eigen::Vector3d v = q1_one.inverse() * (p1 - t1); \n    /** first translation\n     * first translation, qi_one is world to camera\n     * (p1 - t1) is in camera coordinate, after that , it is in world coordinator\n     * so , we can use the same way to compute another point\n     */ \n\n    return 0;\n}", "meta": {"hexsha": "8c2507514e271d340135a345321cbb5f9df9328c", "size": 792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2/my_solution/geometry.cpp", "max_stars_repo_name": "SFXiang/VSLAM_Homework", "max_stars_repo_head_hexsha": "023b3b21e7bfd986d181f76ba6778422e27cfc40", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T06:45:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T14:00:36.000Z", "max_issues_repo_path": "2/my_solution/geometry.cpp", "max_issues_repo_name": "SFXiang/VSLAM_Homework", "max_issues_repo_head_hexsha": "023b3b21e7bfd986d181f76ba6778422e27cfc40", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2/my_solution/geometry.cpp", "max_forks_repo_name": "SFXiang/VSLAM_Homework", "max_forks_repo_head_hexsha": "023b3b21e7bfd986d181f76ba6778422e27cfc40", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-01T16:24:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-01T04:02:23.000Z", "avg_line_length": 27.3103448276, "max_line_length": 81, "alphanum_fraction": 0.6073232323, "num_tokens": 276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.6089339716699422}}
{"text": "#include \"pch_bcl.h\"\r\n#include \"InverseKinematics.h\"\r\n#include <Eigen\\Core>\r\n#include <unsupported\\Eigen\\NonLinearOptimization>\r\n#include \"Tests.h\"\r\n\r\n#define _DEBUG_JACCOBI 1\r\n\r\nusing namespace Causality;\r\n\r\nenum RotationEncodeMethodsEnum\r\n{\r\n\tEulerAngles = 0,\r\n\tLnQuaterternion = 1,\r\n};\r\n\r\nstatic constexpr RotationEncodeMethodsEnum RotationEncodeMethod = LnQuaterternion;\r\n\r\nnamespace DirectX\r\n{\r\n\t// Matrix Representation of Cross Production\r\n\t// =============Usage===============\r\n\t// This matrix is for row major vectors\r\n\t// Vector3Transform(V2,MatrixCrossProduct(V1)) == Vector3Cross(V1,V2)\r\n\t// Vector3Transform(V2,MatrixTranspose(MatrixCrossProduct(V1))) == Vector3Cross(V2,V1)\r\n\t// =============Internal============\r\n\t// \\mathbf{a} \\times \\mathbf{b} = [\\mathbf{a}]_{\\times} \\mathbf{b} = \\begin{bmatrix}\\,0&\\!-a_3&\\,\\,a_2\\\\ \\,\\,a_3&0&\\!-a_1\\\\-a_2&\\,\\,a_1&\\,0\\end{bmatrix}\\begin{bmatrix}b_1\\\\b_2\\\\b_3\\end{bmatrix}\r\n\t// \\mathbf{ a } \\times \\mathbf{ b } = [\\mathbf{ b }]_{ \\times }^\\mathrm T \\mathbf{ a } = \\begin{ bmatrix }\\, 0 & \\, \\, b_3&\\!- b_2\\\\ - b_3 & 0 & \\, \\, b_1\\\\\\, \\, b_2&\\!- b_1&\\, 0\\end{ bmatrix }\\begin{ bmatrix }a_1\\\\a_2\\\\a_3\\end{ bmatrix }\r\n\t// [\\mathbf{a}]_{\\times} \\stackrel{\\rm def}{=} \\begin{bmatrix}\\,\\,0&\\!-a_3&\\,\\,\\,a_2\\\\\\,\\,\\,a_3&0&\\!-a_1\\\\\\!-a_2&\\,\\,a_1&\\,\\,0\\end{bmatrix}.\r\n\tinline XMMATRIX XM_CALLCONV XMMatrixCrossProduct(FXMVECTOR V)\r\n\t{\r\n\t\t// negate v\r\n\t\tXMVECTOR v = XMVectorSelect(g_XMSelect1110.v, V, g_XMSelect1110.v);\r\n\t\tXMVECTOR nv = XMVectorNegate(v);\r\n\t\tXMMATRIX m;\r\n\t\tm.r[0] = _DXMEXT XMVectorPermute<3, 2, 1 + 4, 3 + 4>(v, nv); // [0, a3, -a2]\r\n\t\tm.r[1] = _DXMEXT XMVectorPermute<2 + 4, 3 + 4, 0, 3>(v, nv);\t // [-a3, 0, a1]\r\n\t\tm.r[2] = _DXMEXT XMVectorPermute<1, 0 + 4, 3, 3>(v, nv);\t\t // [a2,-a1, 0 ]\r\n\t\tm.r[3] = XMVectorZero();\r\n\t\treturn m;\r\n\t}\r\n\r\n\tbool XMMatrixCrossProductTest()\r\n\t{\r\n\t\tXMVECTOR v1 = XMVectorSet(0, 1, 0, 0);\r\n\t\tv1 = XMVector3Rotate(v1, XMQuaternionRotationRollPitchYaw(0.01, 0.01, 0.5));\r\n\r\n\t\tXMVECTOR v2 = XMVectorSet(0, 0.01, 0, 0);\r\n\t\tXMVECTOR right = XMVector3Cross(v1, v2);\r\n\t\t\r\n\t\tXMMATRIX m1 = XMMatrixCrossProduct(v1);\r\n\t\tXMVECTOR result = XMVector3TransformNormal(v2, m1);\r\n\r\n\t\treturn XMVector3NearEqual(result, right, XMVectorReplicate(0.001f));\r\n\t}\r\n}\r\n\r\nnamespace Test\r\n{\r\n\tusing namespace DirectX;\r\n\tusing namespace std;\r\n\r\n\tostream& operator<< (ostream& os, const Matrix4x4& m)\r\n\t{\r\n\t\tos << m.m[0][0] << ',' << m.m[0][1] << ',' << m.m[0][2] << ',' << m.m[0][3] << endl;\r\n\t\tos << m.m[1][0] << ',' << m.m[1][1] << ',' << m.m[1][2] << ',' << m.m[1][3] << endl;\r\n\t\tos << m.m[2][0] << ',' << m.m[2][1] << ',' << m.m[2][2] << ',' << m.m[2][3] << endl;\r\n\t\tos << m.m[3][0] << ',' << m.m[3][1] << ',' << m.m[3][2] << ',' << m.m[3][3] << endl;\r\n\t\treturn os;\r\n\t};\r\n\r\n\tvoid QuaternionMultiplyTest(const Quaternion &q, const Vector3 &v, const Quaternion &ldq);\r\n\r\n\tfloat randf()\r\n\t{\r\n\t\tfloat r = (float)rand();\r\n\t\tr /= (float)(RAND_MAX);\r\n\t\treturn r;\r\n\t}\r\n\r\n\tfloat rand2pi()\r\n\t{\r\n\t\treturn randf() * XM_2PI - XM_PI;\r\n\t}\r\n\r\n\tfloat randpi()\r\n\t{\r\n\t\treturn randf() * XM_PI - XM_PIDIV2;\r\n\t}\r\n\r\n\tbool QuaternionEulerTest()\r\n\t{\r\n\t\tXMMatrixCrossProductTest();\r\n\t\t// Patch Yaw Roll = (1.4,0.8,0.4)\r\n\t\tVector3 v(0, 1, 0);\r\n\t\tQuaternion ldq;\r\n\t\tQuaternion q = XMQuaternionRotationRollPitchYaw(0.01, 0.01, 0.5);\r\n\t\t//Quaternion ldq(0.001, 0.0, 0.0, 0);\r\n\t\t//QuaternionMultiplyTest(q, v, ldq);\r\n\t\t//cout << \"=====\" << endl;\r\n\r\n\t\tldq = Quaternion(0.0, 0.001, 0.0, 0);\r\n\t\tQuaternionMultiplyTest(q, v, ldq);\r\n\t\tcout << \"=====\" << endl;\r\n\r\n\t\tv = XMVector3Rotate(v, q);\r\n\t\tq = XMQuaternionIdentity();\r\n\r\n\t\tXMVECTOR v0 = XMVector3Rotate(v, XMVectorSet(-0.000244786148,0.000958836172,6.69062138e-06,0.999999464));\r\n\t\tXMVECTOR v1 = XMVector3Rotate(v, XMVectorSet(0.000000000,0.000999999815,0.000000000,0.999999523));\r\n\t\tv0 -= v;\r\n\t\tv1 -= v;\r\n\r\n\t\tldq = Quaternion(0.001, 0.0, 0.0, 0);\r\n\t\tQuaternionMultiplyTest(q, v, ldq);\r\n\t\tcout << \"=====\" << endl;\r\n\t\tldq = Quaternion(0.0, 0.001, 0.0, 0);\r\n\t\tQuaternionMultiplyTest(q, v, ldq);\r\n\t\tcout << \"=====\" << endl;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvoid QuaternionMultiplyTest(const Quaternion &q, const Vector3 &v, const Quaternion &ldq)\r\n\t{\r\n\t\tXMVECTOR axis;\r\n\t\tfloat ang;\r\n\t\tXMQuaternionToAxisAngle(&axis, &ang, q);\r\n\t\taxis = XMVector3Normalize(axis);\r\n\t\tang *= 0.5;\r\n\r\n\t\tcout << \"q = \" << q << endl;\r\n\r\n\t\tQuaternion lq = XMQuaternionLn(q);\r\n\t\tcout << \"ln(q) = \" << lq << endl;\r\n\r\n\t\tcout << \"dlnq = d(ln(q)) = \" << ldq << endl;\r\n\t\tQuaternion dq = XMQuaternionExp(ldq);\r\n\t\tcout << \"dq = exp(d(ln(q))) = \" << dq << endl;\r\n\r\n\t\tdq = XMQuaternionExp((lq + ldq));\r\n\t\tcout << \"exp(ln(q)+d(ln(q))) = \" << dq << endl;\r\n\t\tdq = XMQuaternionMultiply(XMQuaternionConjugate(q), dq);\r\n\t\tcout << \"dq = q^-1 * exp(ln(q)+d(ln(q))) = \" << dq << endl;\r\n\r\n\t\tcout << \"||dq|| =\" << XMVectorGetX(XMVector3Length(dq)) << endl;\r\n\r\n\t\tfloat sinadiva = 1.0f;\r\n\t\tif (fabs(ang) > std::numeric_limits<float>::epsilon())\r\n\t\t\tsinadiva = sin(ang) / ang;\r\n\r\n\t\tQuaternion estimate = sinadiva * (cos(ang) * (XMVECTOR)ldq + sin(ang)*XMVector3Cross(axis, ldq));\r\n\t\tQuaternion another = XMVector3Dot(ldq, axis);\r\n\t\t//another *= axis;\r\n\t\t//estimate += another;\r\n\r\n\t\tcout << \"estimate = \" << estimate << endl;\r\n\r\n\t\tXMVECTOR cosA = XMVectorSplatW(q);\r\n\t\tXMVECTOR sinA = XMVectorSqrt(g_XMOne.v - cosA * cosA);\r\n\r\n\t\t//Matrix4x4 jac = XMVectorGetX(sinA) * XMMatrixCrossProduct(axis) + XMMatrixScalingFromVector(cosA);\r\n\r\n\t\tMatrix4x4 jac = sinadiva* (sin(ang)* XMMatrixCrossProduct(axis) + cos(ang) * XMMatrixIdentity());\r\n\t\tcout << \"jaccobi == \" << endl << jac << endl;\r\n\t\tQuaternion estimate2 = XMVector3TransformNormal(ldq, jac);\r\n\t\tcout << \"estimate2 = \" << estimate2 << endl;\r\n\r\n\t\tVector3 qv = XMVector3Rotate(v, q);\r\n\t\tcout << \"qv = \" << qv << endl;\r\n\r\n\t\tMatrix4x4 derv = -XMMatrixCrossProduct(qv);\r\n\t\tcout << endl << \"analatic derv d(qv)/d(q) == \" << endl << derv;\r\n\r\n\t\tderv = jac * derv;\r\n\t\tcout << endl << \"overall derv == \" << endl << derv ;\r\n\r\n\t\tVector3 derest = Vector3::TransformNormal(Vector3(ldq), derv);\r\n\t\tderest *= XMVector3ReciprocalLength(ldq) * 2;\r\n\t\tcout << \"new analatic derv = \" << derest << endl;\r\n\r\n\r\n\t\tVector3 dotvdq = XMVector3Dot(qv, dq);\r\n\t\tVector3 crossvdq = XMVector3Cross(qv, dq);\r\n\t\tcout << \"dot(qv,dq) = \" << dotvdq << endl;\r\n\t\tcout << \"cross(qv) = \" << crossvdq << endl;\r\n\r\n\t\tVector3 dif = XMVector3Rotate(qv, dq) - (XMVECTOR)qv;\r\n\t\tdif *= XMVector3ReciprocalLength(dq);\r\n\r\n\t\tcout << \"d(rv)/dq = \" << dif << endl;\r\n\r\n\t\tlq = XMQuaternionMultiply(q, dq);\r\n\t\tcout << \"q * dq= \" << lq << endl;\r\n\r\n\t\tlq = XMQuaternionMultiply(dq, q);\r\n\t\tcout << \"dq * q= \" << lq << endl;\r\n\t}\r\n\r\n\tbool InverseKinematicsTest()\r\n\t{\r\n\t\tQuaternionEulerTest();\r\n\t\tusing namespace DirectX;\r\n\r\n\t\tChainInverseKinematics cik(3);\r\n\t\tcik.bone(0) = Vector4(0, 1.0f, 0, 1.0f);\r\n\t\tcik.bone(1) = Vector4(0, 1.0f, 0, 1.0f);\r\n\t\tcik.bone(2) = Vector4(0, 1.0f, 0, 1.0f);\r\n\t\t//cik.m_boneMinLimits[0].x = 0;\r\n\t\t//cik.m_boneMaxLimits[0].x = 0;\r\n\t\tcik.minRotation(1).y = 0;\r\n\t\tcik.maxRotation(1).y = 0;\r\n\t\tcik.minRotation(2).y = 0;\r\n\t\tcik.maxRotation(2).y = 0;\r\n\t\t//cik.computeJointWeights();\r\n\t\tvector<Quaternion> rotations(3);\r\n\t\tfor (size_t i = 0; i < 1; i++)\r\n\t\t{\r\n\t\t\trotations[0] = XMQuaternionRotationRollPitchYaw(0.01, 0, 0.01);\r\n\t\t\trotations[1] = XMQuaternionRotationRollPitchYaw(0.01, 0, 0.5);\r\n\t\t\trotations[2] = XMQuaternionRotationRollPitchYaw(0.5, 0.01, 0.5);\r\n\t\t\tVector3 goal = XMVectorSet(1.0f + randf(), randf(), randf(), 0);\r\n\t\t\tauto code = cik.solve(goal, rotations);\r\n\t\t\tVector3 achieved = cik.endPosition(rotations);\r\n\t\t\tcout << \"ik test : goal = \" << goal << \" ; achieved position = \" << achieved << endl;\r\n\t\t}\r\n\t\tcout << \"rotations = {\" << std::endl;\r\n\t\tfor (size_t i = 0; i < 3; i++)\r\n\t\t{\r\n\t\t\tcout << \"  \" << rotations[i] << std::endl;\r\n\t\t}\r\n\t\tcout << '}' << endl;\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\tREGISTER_TEST_METHOD(InverseKinematicsTest,InverseKinematicsTest);\r\n}\r\n\r\nnamespace Internal\r\n{\r\n\t// Generic functor\r\n\ttemplate<typename _Scalar, int NX = Eigen::Dynamic, int NY = Eigen::Dynamic>\r\n\tstruct Functor\r\n\t{\r\n\t\ttypedef _Scalar Scalar;\r\n\t\tenum {\r\n\t\t\tInputsAtCompileTime = NX,\r\n\t\t\tValuesAtCompileTime = NY\r\n\t\t};\r\n\t\ttypedef Eigen::Matrix<Scalar, InputsAtCompileTime, 1> InputType;\r\n\t\ttypedef Eigen::Matrix<Scalar, ValuesAtCompileTime, 1> ValueType;\r\n\t\ttypedef Eigen::Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime> JacobianType;\r\n\r\n\t\tint m_inputs, m_values;\r\n\r\n\t\tFunctor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\r\n\t\tFunctor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\r\n\r\n\t\tint inputs() const { return m_inputs; }\r\n\t\tint values() const { return m_values; }\r\n\r\n\t};\r\n}\r\nnamespace Causality\r\n{\r\n\tstatic void DecodeRotationsEuler(const Eigen::VectorXf &x, Causality::array_view<DirectX::SimpleMath::Quaternion> rotations)\r\n\t{\r\n\t\tint n = rotations.size();\r\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tauto euler = x.segment<3>(i * 3);\n\t\t\trotations[i] = DirectX::XMQuaternionRotationRollPitchYaw(euler[0], euler[1], euler[2]);\n\t\t}\r\n\t}\r\n\r\n\tstatic void EncodeRotationsEuler(Eigen::VectorXf &x, Causality::array_view<DirectX::SimpleMath::Quaternion> rotations)\r\n\t{\r\n\t\tint n = rotations.size();\r\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tauto euler = x.segment<3>(i * 3);\n\t\t\tauto dxeuler = DirectX::XMQuaternionEulerAngleYawPitchRoll(rotations[i]);\n\t\t\tDirectX::XMStoreFloat3(euler.data(), dxeuler);\n\t\t}\r\n\t}\r\n\r\n\tstatic void DecodeRotationsLnQ(const Eigen::VectorXf &x, Causality::array_view<DirectX::SimpleMath::Quaternion> rotations)\r\n\t{\r\n\t\tint n = rotations.size();\r\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tauto lnq = x.segment<3>(i * 3);\n\t\t\trotations[i] = DirectX::XMQuaternionExp(DirectX::XMLoadFloat3(lnq.data()));\n\t\t}\r\n\t}\r\n\r\n\tstatic void EncodeRotationsLnQ(Eigen::VectorXf &x, Causality::array_view<const DirectX::SimpleMath::Quaternion> rotations)\r\n\t{\r\n\t\tint n = rotations.size();\r\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tauto lnq = x.segment<3>(i * 3);\n\t\t\tauto dxlnq = DirectX::XMQuaternionLn(rotations[i]);\n\t\t\tDirectX::XMStoreFloat3(lnq.data(), dxlnq);\n\t\t}\r\n\t}\r\n\r\n\tstatic inline void DecodeRotations(const Eigen::VectorXf &x, Causality::array_view<DirectX::SimpleMath::Quaternion> rotations)\r\n\t{\r\n\t\tif (RotationEncodeMethod == EulerAngles)\r\n\t\t\tDecodeRotationsEuler(x, rotations);\r\n\t\telse\r\n\t\t\tDecodeRotationsLnQ(x, rotations);\r\n\t}\r\n\r\n\tstatic inline void EncodeRotations(Eigen::VectorXf &x, Causality::array_view<DirectX::SimpleMath::Quaternion> rotations)\r\n\t{\r\n\t\tif (RotationEncodeMethod == EulerAngles)\r\n\t\t\tEncodeRotationsEuler(x, rotations);\r\n\t\telse\r\n\t\t\tEncodeRotationsLnQ(x, rotations);\r\n\t}\r\n\r\n}\r\n\r\nstruct ChainInverseKinematics::OptimizeFunctor : public Internal::Functor<float>\n{\n\tconst ChainInverseKinematics&\tik;\n\tsize_t\t\t\t\t\t\t\tn;\n\tVector3\t\t\t\t\t\t                                    m_goal;\n\tfloat\t\t\t\t\t\t                                    m_limitPanalty;\n\tEigen::Map<const Eigen::VectorXf>                               m_min;\n\tEigen::Map<const Eigen::VectorXf>                               m_max;\n\n\tEigen::VectorXf\t\t\t\t\t                                m_ref;\n\tfloat\t\t\t\t\t\t\t                                m_refWeights;\n\tbool\t\t\t\t\t\t\t                                m_useRef;\n\n\tmutable std::vector<DirectX::Quaternion, DirectX::XMAllocator>\tm_rots;\r\n\tmutable std::vector<DirectX::Vector3, DirectX::XMAllocator>\tm_jac;\r\n\n\tvoid fillRotations(const InputType &x) const\n\t{\n\t\tassert(x.size() == 3 * n);\r\n\t\tDecodeRotations(x, m_rots);\n\t}\n\n\tOptimizeFunctor(const ChainInverseKinematics& _ik, const Vector3 & goal)\n\t\t: ik(_ik), n(_ik.size()),\n\t\tInternal::Functor<float>(3 * _ik.size(), 3 + 3 * _ik.size()),\n\t\tm_rots(_ik.size()),\n\t\tm_jac(_ik.size() * 3),\n\t\tm_goal(goal),\n\t\tm_ref(_ik.size() * 3),\n\t\tm_min(&_ik.m_boneMinLimits[0].x, 3 * _ik.size()),\n\t\tm_max(&_ik.m_boneMaxLimits[0].x, 3 * _ik.size()),\n\t\tm_limitPanalty(1000.0f),\n\t\tm_refWeights(.0f),\n\t\tm_useRef(false)\n\t{\n\t}\n\n\tvoid setGoal(const Vector3 & goal)\n\t{\n\t\tm_goal = goal;\n\t}\n\n\ttemplate <class Derived>\n\tvoid setReference(const Eigen::DenseBase<Derived>& refernece, float referenceWeight)\n\t{\n\t\tm_ref = refernece;\n\t\tm_refWeights = referenceWeight;\n\t\tm_useRef = true;\n\t}\n\n\tvoid disableRef()\n\t{\n\t\tm_useRef = false;\n\t\tm_refWeights = .0f;\n\t}\n\n\tint operator()(const InputType &x, ValueType& fvec) const {\r\n\t\tfillRotations(x);\r\n\t\tVector3 v = ik.endPosition(m_rots);\r\n\t\tv -= m_goal;\r\n\r\n\t\tassert(fvec.size() == 3 + x.size());\r\n\r\n\t\tfvec.setZero();\r\n\t\tfvec.head<3>() = Eigen::Vector3f::Map(&v.x);\r\n\r\n\t\t// limit-exceed panelaty\r\n\t\tauto limpanl = fvec.tail(x.size());\r\n\t\tfor (int i = 0; i < 3 * n; i++)\n\t\t{\n\t\t\tif (x[i] < m_min[i])\n\t\t\t\tlimpanl[i] = m_limitPanalty*(x[i] - m_min[i])*(x[i] - m_min[i]);\n\t\t\telse if (x[i] > m_max[i])\n\t\t\t\tlimpanl[i] = m_limitPanalty*(x[i] - m_max[i])*(x[i] - m_max[i]);\n\t\t}\r\n\r\n\t\tif (m_useRef)\r\n\t\t{\r\n\t\t\tlimpanl += m_refWeights *(x - m_ref);\r\n\t\t}\r\n\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tint df(const InputType &x, JacobianType& fjac) {\r\n\t\tfillRotations(x);\r\n\t\tfjac.setZero();\r\n\r\n\t\tif (RotationEncodeMethod == EulerAngles)\r\n\t\t\tik.endPositionJaccobiRespectEuler(m_rots, m_jac);\r\n\t\telse\r\n\t\t{\r\n\t\t\tik.endPositionJaccobiRespectLnQuaternion(m_rots, m_jac);\r\n\t\t}\r\n\r\n\t\tauto jacb = fjac.topRows<3>();\r\n\t\tjacb = Eigen::Matrix3Xf::Map(&m_jac[0].x, 3, 3 * n);\r\n\r\n\t\t// limit-exceed panelaty\r\n\t\tfor (int i = 0; i < 3 * n; i++)\n\t\t{\n\t\t\tif (x[i] < m_min[i])\n\t\t\t\tfjac(3 + i, i) = m_limitPanalty * (x[i] - m_min[i]);\n\t\t\telse if (x[i] > m_max[i])\n\t\t\t\tfjac(3 + i, i) = m_limitPanalty * (x[i] - m_max[i]);\n\n\t\t\tif (m_useRef)\n\t\t\t{\n\t\t\t\tfjac(3 + i, i) += m_refWeights;\n\t\t\t}\n\t\t}\r\n\r\n\t\t//fjac.topRows<3>() = m_jac;\r\n\t\treturn 0;\r\n\t}\r\n};\r\n\r\nChainInverseKinematics::ChainInverseKinematics(size_t n)\r\n\t: ChainInverseKinematics()\r\n{\r\n\tresize(n);\r\n}\r\n\r\nChainInverseKinematics::ChainInverseKinematics()\r\n{\r\n\tm_tol = 5e-4;\r\n\tm_maxItrs = 200;\r\n}\r\n\r\nvoid ChainInverseKinematics::resize(size_t n)\r\n{\r\n\tm_bones.resize(n);\r\n\tm_boneMinLimits.resize(n);\r\n\tm_boneMaxLimits.resize(n);\r\n\tm_jointWeights.resize(n);\r\n\r\n\tusing namespace DirectX;\r\n\tVector3 dlim(XM_PIDIV2, XM_PI, XM_PI);\r\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tm_boneMinLimits[i] = -dlim;\n\t\tm_boneMaxLimits[i] = dlim;\n\t\tm_jointWeights[i] = Vector3(1.0f);\n\t}\r\n}\r\n\r\nvoid ChainInverseKinematics::computeJointWeights()\r\n{\r\n\tusing namespace Math;\r\n\tXMVECTOR V;\r\n\tXMVECTOR LV = XMVectorZero();\r\n\tfor (int i = m_bones.size() - 1; i >= 0; --i)\n\t{\n\t\tV = XMLoadA(m_bones[i]);\n\t\tV = XMVector3Length(V);\n\t\tLV += V;\n\t\tm_jointWeights[i] = LV;\n\t}\r\n}\r\n\r\n// Jaccobbi from a rotation radius vector (r) respect to a small rotation dr = (drx,dry,drz) in global reference frame\r\n// [\\mathbf{a}]_{\\times} \\stackrel{\\rm def}{=} \\begin{bmatrix}\\,\\,0&\\!-a_3&\\,\\,\\,a_2\\\\\\,\\,\\,a_3&0&\\!-a_1\\\\\\!-a_2&\\,\\,a_1&\\,\\,0\\end{bmatrix}.\r\nvoid ChainInverseKinematics::jacobbiRespectAxisAngle(Matrix4x4 & j, const float * r)\r\n{\r\n\tj._11 = 0, j._12 = -r[2], j._13 = r[1];\r\n\tj._21 = r[2], j._22 = 0, j._23 = -r[0];\r\n\tj._31 = -r[1], j._32 = r[0], j._33 = 0;\r\n}\r\n\r\n// Roll-Patch-Yaw\r\nXMMATRIX XM_CALLCONV ChainInverseKinematics::jacobbiTransposeRespectEuler(const Vector3 & rv, const Vector3& euler, FXMVECTOR globalRot)\r\n{\r\n\tusing namespace DirectX;\r\n\r\n\t// Jaccobi to Euler \r\n\t// J = Ry*Jy + Ry*Rx*Jx + Ry*Rx*Rz*Jz\r\n\r\n\tXMVECTOR V;\r\n\tXMMATRIX MJ;\r\n\tXM_ALIGNATTR Vector4 v, r = rv;\r\n\r\n\tXMVECTOR Q = globalRot;\r\n\tXMVECTOR lQ;\r\n\r\n\tlQ = XMQuaternionRotationRoll(euler.z);\r\n\tQ = XMQuaternionMultiply(lQ, Q); // Q = base * roll\r\n\tV = XMVectorSet(-r.y, r.x ,0 ,0);\r\n\tV = XMVector3Rotate(V, Q);\r\n\tMJ.r[2] = V;\r\n\tr = XMVector3Rotate(r, lQ);\r\n\r\n\tlQ = XMQuaternionRotationPatch(euler.x);\r\n\tQ = XMQuaternionMultiply(lQ, Q); // Q = base * roll * patch\r\n\tV = XMVectorSet(0,-r.z,r.y,0);\r\n\tV = XMVector3Rotate(V, Q);\r\n\tMJ.r[0] = V;\r\n\tr = XMVector3Rotate(r, lQ);\r\n\r\n\tlQ = XMQuaternionRotationYaw(euler.y);\r\n\tQ = XMQuaternionMultiply(lQ, Q); // Q = base * roll * patch * yaw\r\n\tV = XMVectorSet(r.z,0,-r.x,0);\r\n\tV = XMVector3Rotate(V, Q);\r\n\tMJ.r[1] = V;\r\n\r\n\t//MJ = XMMatrixTranspose(MJ);\r\n\treturn MJ;\r\n}\r\n\r\nXMMATRIX XM_CALLCONV Causality::ChainInverseKinematics::jacobbiTransposeRespectAxisAngle(const Vector3 & rv, FXMVECTOR qrot, FXMVECTOR globalRot)\r\n{\r\n\tusing namespace DirectX;\r\n\r\n\tXMVECTOR V;\r\n\tXMMATRIX MJ;\r\n\tXM_ALIGNATTR Matrix4x4 jac;\r\n\tXM_ALIGNATTR Vector4 r;\r\n\tV = XMVector3Rotate(rv, qrot);\r\n\tXMStoreA(r, V);\r\n\tXMVECTOR Q = globalRot; //XMQuaternionMultiply(qrot, globalRot);\r\n\r\n\t//r.v = rv;\r\n\t//XMVECTOR Q = XMQuaternionMultiply(qrot, globalRot);\r\n\r\n\tjacobbiRespectAxisAngle(jac, &r.x);\r\n\r\n\r\n\t// Rotate each row of the matrix\r\n\tV = XMLoadFloat4A(jac.m[0]);\r\n\tV = XMVector3Rotate(V, Q);\r\n\tMJ.r[0] = V;\r\n\tV = XMLoadFloat4A(jac.m[1]);\r\n\tV = XMVector3Rotate(V, Q);\r\n\tMJ.r[1] = V;\r\n\tV = XMLoadFloat4A(jac.m[2]);\r\n\tV = XMVector3Rotate(V, Q);\r\n\tMJ.r[2] = V;\r\n\tMJ.r[3] = XMVectorZero();\r\n\r\n\tXMVECTOR axis = XMVector3Normalize(qrot);\r\n\tXMVECTOR cosA = XMVectorSplatW(qrot);\r\n\tXMVECTOR sinA = XMVectorSqrt(g_XMOne.v - cosA * cosA);\r\n\tXMVECTOR sinc_a = g_XMOne.v - (g_XMOne.v - cosA) / 3.0; // sinc(x) ~= 1 - x^2/6 == 1 - (1-cos(x))/3\r\n\r\n\tcosA *= sinc_a;\r\n\tsinA *= sinc_a;\r\n\tXMMATRIX jacq_lnq = XMVectorGetX(sinA) * XMMatrixCrossProduct(axis) + XMMatrixScalingFromVector(cosA);\r\n\t//cout << \"jaccobi == \" << endl << jac << endl;\r\n\tMJ = jacq_lnq * MJ;\r\n\r\n\treturn MJ;\r\n}\r\n\r\nXMVECTOR Causality::ChainInverseKinematics::endPosition(array_view<const Quaternion> rotations) const\r\n{\r\n\tusing namespace DirectX;\r\n\r\n\tconst auto n = m_bones.size();\r\n\r\n\tXMVECTOR q, t, gt, gq;\r\n\tEigen::Vector4f qs;\r\n\tqs.setZero();\r\n\r\n\tgt = XMVectorZero();\r\n\r\n\tfor (int i = n - 1; i >= 0; i--)\r\n\t{\r\n\t\tq = XMLoadA(rotations[i]);\r\n\t\tt = XMLoadA(m_bones[i]);\r\n\t\tgt += t;\r\n\t\tgt = XMVector3Rotate(gt, q);\r\n\t}\r\n\r\n\treturn gt;\r\n}\r\n\r\n// rotations must be aligned\r\n\r\nvoid ChainInverseKinematics::endPositionJaccobiRespectEuler(array_view<const Quaternion> rotations, array_view<Vector3> jacb) const\r\n{\r\n\tusing namespace Eigen;\r\n\tusing namespace DirectX;\r\n\tconst auto n = m_bones.size();\r\n\n\t// Chain Position Vectors\r\n\tauto rad = getRadiusVectors(rotations);\r\n\r\n\tXMVECTOR gq = XMQuaternionIdentity();\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\tXMVECTOR q = XMLoadA(rotations[i]);\r\n\t\tVector3 eular = XMQuaternionEulerAngleYawPitchRoll(q);\r\n\r\n\t\tauto& r = reinterpret_cast<Vector3&>(rad[i]);\r\n\t\tXMMATRIX jac = jacobbiTransposeRespectEuler(r, eular, gq);\r\n\r\n\t\tXMStoreFloat3x3(reinterpret_cast<XMFLOAT3X3*>(&jacb[i * 3].x), jac);\r\n\r\n\t\tgq = XMQuaternionMultiply(q, gq);\r\n\t}\r\n\r\n\t//return jacb;\r\n}\r\n\r\nvoid ChainInverseKinematics::endPositionJaccobiRespectAxisAngle(array_view<const Quaternion> rotations, array_view<Vector3> jacb) const\r\n{\r\n\tusing namespace Eigen;\r\n\tusing namespace DirectX;\r\n\tconst auto n = m_bones.size();\r\n\n\t// Chain Position Vectors\n\tauto rad = getRadiusVectors(rotations);\r\n\r\n\tXMVECTOR gq = XMQuaternionIdentity();\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\tXMVECTOR q = XMLoadA(rotations[i]);\r\n\r\n\t\tauto& r = reinterpret_cast<Vector3&>(rad[i]);\r\n\t\tXMMATRIX jac = jacobbiTransposeRespectAxisAngle(r, q, gq);\r\n\r\n\t\tXMStoreFloat3x3(reinterpret_cast<XMFLOAT3X3*>(&jacb[i * 3].x), jac);\r\n\r\n\t\tgq = XMQuaternionMultiply(q, gq);\r\n\t}\r\n}\r\n\r\nvoid ChainInverseKinematics::endPositionJaccobiRespectLnQuaternion(array_view<const Quaternion> rotations, array_view<Vector3> jacb) const\r\n{\r\n\tendPositionJaccobiRespectAxisAngle(rotations, jacb);\r\n\t// d(lnQ) == 0.5 * d(axis*angle), thus we need to apply this factor back\r\n\tfor (auto& v : jacb)\r\n\t\tv *= 2.0f;\r\n}\r\n\r\nstd::vector<Vector4, DirectX::XMAllocator> ChainInverseKinematics::getRadiusVectors(array_view<const Quaternion> &rotations) const\r\n{\r\n\tusing namespace DirectX;\r\n\r\n\tconst auto n = m_bones.size();\r\n\tstd::vector<DirectX::Vector4, DirectX::XMAllocator>\trad(n);\r\n\r\n\tXMVECTOR q, t, gt;\r\n\r\n\tgt = XMVectorZero();\r\n\tt = XMVectorZero();\r\n\r\n\tfor (int i = n - 1; i >= 0; i--)\r\n\t{\r\n\t\tq = XMLoadA(rotations[i]);\r\n\t\tt = XMLoadA(m_bones[i]);\r\n\t\tgt += t;\r\n\t\trad[i] = gt;\r\n\t\tgt = XMVector3Rotate(gt, q);\r\n\t}\r\n\r\n\treturn rad;\r\n}\r\n\r\n\r\nbool XM_CALLCONV ChainInverseKinematics::solve(FXMVECTOR goal, array_view<Quaternion> rotations) const\n{\n\tauto n = m_bones.size();\n\tEigen::VectorXf x(n * 3);\n\tEncodeRotations(x, rotations);\n\t//m_boneMinLimits += x;\n\t//m_boneMinLimits += x;\n\n\t//std::cout << \"init x = \" << x.transpose() << std::endl;\n\tVector3 vgoal = goal;\n\tOptimizeFunctor functor(*this, vgoal);\n\n\n\ttypedef OptimizeFunctor DfFunctor;\n\t//typedef Eigen::NumericalDiff<OptimizeFunctor> DfFunctor;\n\n\tEigen::MatrixXf aJac(functor.values(), functor.inputs());\n\tEigen::MatrixXf nJac(functor.values(), functor.inputs());\n\tEigen::VectorXf ep(functor.values());\n\n#if defined(_DEBUG_JACCOBI) && _DEBUG_JACCOBI\n\tEigen::NumericalDiff<OptimizeFunctor> ndffunctor(functor);\n\tfunctor(x, ep);\n\tfunctor.df(x, aJac);\n\tndffunctor.df(x, nJac);\n\n\tstd::cout << \"Numberic Jaccobi : \" << std::endl << nJac.topRows(3) << std::endl;\n\tstd::cout << \"Analatic Jaccobi : \" << std::endl << aJac.topRows(3) << std::endl;\n#endif\n\n\tEigen::LevenbergMarquardt<DfFunctor, float> lm(functor);\n\tlm.parameters.maxfev = m_maxItrs;\n\tlm.parameters.xtol = m_tol;\n\tlm.parameters.ftol = m_tol;\n\tlm.parameters.gtol = m_tol;\n\n\tauto code = lm.minimize(x);\n\tstd::cout << \"iteration = \" << lm.iter << std::endl;\r\n\tstd::cout << \"ret = \" << code << std::endl;\r\n\tstd::cout << \"x = \" << x.transpose() << std::endl;\n\r\n\t//lm.minimizeInit(x);\n\n\t//if (code != LevenbergMarquardtSpace::Status::CosinusTooSmall)\n\n\tDecodeRotations(x, rotations);\n\n\treturn true;\n}\r\n\r\nbool XM_CALLCONV ChainInverseKinematics::solveWithStyle(FXMVECTOR goal, array_view<Quaternion> rotations, array_view<Quaternion> styleReference, float styleReferenceWeight) const\r\n{\r\n\tauto n = m_bones.size();\n\tEigen::VectorXf x(n * 3);\n\tEigen::VectorXf ref(n * 3);\n\tEncodeRotations(x, rotations);\n\tEncodeRotations(ref, styleReference);\n\n\tOptimizeFunctor functor(*this, goal);\n\tfunctor.setReference(ref, styleReferenceWeight);\n\n\tEigen::LevenbergMarquardt<OptimizeFunctor, float> lm(functor);\n\tlm.parameters.maxfev = m_maxItrs;\n\tlm.parameters.xtol = m_tol;\n\tlm.parameters.ftol = m_tol;\n\tlm.parameters.gtol = m_tol;\n\n\tauto code = lm.minimize(x);\n\n\tDecodeRotations(x, rotations);\n\n\treturn true;\r\n}\r\n", "meta": {"hexsha": "9ac10961764f010cc38fff6bb9a924c1c6b7bba5", "size": 21854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Causality/InverseKinematics.cpp", "max_stars_repo_name": "ArcEarth/PPARM", "max_stars_repo_head_hexsha": "8e22e3f20a90a22940218c243b7fe5e24e754e5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-07-13T18:30:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-31T22:20:34.000Z", "max_issues_repo_path": "Causality/InverseKinematics.cpp", "max_issues_repo_name": "ArcEarth/PPARM", "max_issues_repo_head_hexsha": "8e22e3f20a90a22940218c243b7fe5e24e754e5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Causality/InverseKinematics.cpp", "max_forks_repo_name": "ArcEarth/PPARM", "max_forks_repo_head_hexsha": "8e22e3f20a90a22940218c243b7fe5e24e754e5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-01-16T14:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-12T16:15:18.000Z", "avg_line_length": 28.8311345646, "max_line_length": 240, "alphanum_fraction": 0.6316006223, "num_tokens": 7353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.6926419958239131, "lm_q1q2_score": 0.6089339694767403}}
{"text": "// convenience.cpp\n\n// Helper functions\n#include \"convenience.h\"\n#include \"parameters.h\"\n#include <boost/math/special_functions/gamma.hpp>\n#include <cmath>\n#include <iostream>\nusing namespace std;\nusing boost::math::lgamma;\nusing boost::math::gamma_p;\n\n\nvector<double> seq(double x0, double x1, double by)\n{\n    int steps = int((x1 - x0) / by + by * 1e-3);\n    if (steps >= 0)\n    {\n        vector<double> ret(steps);\n        for (int i = 0; i < steps; ++i)\n            ret[i] = x0 + by * i;\n        return ret;\n    }\n    return vector<double>(0);\n}\n\ndouble gamma_P(double x, double shape, double scale)\n{\n    return boost::math::gamma_p(x / scale, shape);\n}\n\n// binomial log density\ndouble binom(double k, double n, double p)\n{\n    return lgamma(n + 1.) - lgamma(k + 1.) - lgamma(n - k + 1.) + k * log(p) + (n - k) * log(1. - p);\n}\n\n// negative binomial log density\ndouble nbinom(unsigned int x, double mean, double size)\n{\n    double k = x;\n    double p = size / (size + mean);\n    double n = mean * p / (1 - p);\n\n    return lgamma(n + k) - lgamma(k + 1) - lgamma(n) + n * log(p) + k * log(1 - p);\n}\n\n// negative binomial log density with retrospective confirmation\ndouble nbinom_gammaconf(unsigned int x, double mean, double size, double days_ago, double conf_delay_mean, double conf_delay_shape)\n{\n    double conf_delay_scale = conf_delay_mean / conf_delay_shape;\n    double prop_confirmed = gamma_P(days_ago, conf_delay_shape, conf_delay_scale);\n    return nbinom(x, mean * prop_confirmed, size);\n}\n\n// construct a delay distribution following a gamma distribution with mean mu and shape parameter shape.\nvector<double> delay_gamma(double mu, double shape, double t_max, double t_step, double mult)\n{\n    double scale = mu / shape;\n    vector<double> height;\n\n    for (double t = 0.0; t < t_max + 0.5 * t_step; t += t_step)\n        height.push_back(mult * (gamma_P(t + t_step/2, shape, scale) - \n            gamma_P(max(0.0, t - t_step/2), shape, scale)));\n    return height;\n}\n\n// estimate the basic reproduction number\ndouble estimate_R0(Parameters& P, double t, unsigned int p, unsigned int iter)\n{\n    vector<double> inf(P.pop[p].size.size(), 1.0);\n    vector<double> inf2 = inf;\n\n    double dIp = P.pop[p].dIp.Mean() * P.time_step;\n    double dIs = P.pop[p].dIs.Mean() * P.time_step;\n    double dIa = P.pop[p].dIa.Mean() * P.time_step;\n\n    double n_inf = P.pop[p].size.size();\n    double n_inf2 = 0;\n    double R0 = 1;\n\n    double seas = 1.0 + P.pop[p].season_A * cos(2. * M_PI * (t - P.pop[p].season_phi) / P.pop[p].season_T);\n\n    for (unsigned int i = 0; i < iter; ++i)\n    {\n        n_inf2 = 0;\n        for (unsigned int a = 0; a < inf.size(); ++a)\n        {\n            inf2[a] = 0;\n            for (unsigned int b = 0; b < inf.size(); ++b)\n            {\n                inf2[a] += inf[b] * P.pop[p].cm(a, b) * P.pop[p].u[a] * seas * (\n                    P.pop[p].y[b] * (P.pop[p].fIp[b] * dIp + P.pop[p].fIs[b] * dIs) +\n                    (1 - P.pop[p].y[b]) * P.pop[p].fIa[b] * dIa\n                );\n            }\n            n_inf2 += inf2[a];\n        }\n\n        R0 = n_inf2 / n_inf;\n\n        swap(n_inf2, n_inf);\n        swap(inf2, inf);\n    }\n\n    return R0;\n}\n\n// estimate the effective reproduction number\ndouble estimate_Rt(Parameters& P, Reporter& dyn, double t, unsigned int p, unsigned int iter)\n{\n    vector<double> inf(P.pop[p].size.size(), 1.0);\n    vector<double> inf2 = inf;\n    vector<double> S(P.pop[p].size.size(), 0.0);\n\n    for (unsigned int a = 0; a < S.size(); ++a)\n        S[a] = dyn(t, p, a, 0) / P.pop[p].size[a];\n\n    double dIp = P.pop[p].dIp.Mean() * P.time_step;\n    double dIs = P.pop[p].dIs.Mean() * P.time_step;\n    double dIa = P.pop[p].dIa.Mean() * P.time_step;\n\n    double n_inf = P.pop[p].size.size();\n    double n_inf2 = 0;\n    double Rt = 1;\n\n    double seas = 1.0 + P.pop[p].season_A * cos(2. * M_PI * (t - P.pop[p].season_phi) / P.pop[p].season_T);\n\n    for (unsigned int i = 0; i < iter; ++i)\n    {\n        n_inf2 = 0;\n        for (unsigned int a = 0; a < inf.size(); ++a)\n        {\n            inf2[a] = 0;\n            for (unsigned int b = 0; b < inf.size(); ++b)\n            {\n                inf2[a] += S[a] * inf[b] * P.pop[p].cm(a, b) * P.pop[p].u[a] * seas * (\n                    P.pop[p].y[b] * (P.pop[p].fIp[b] * dIp + P.pop[p].fIs[b] * dIs) +\n                    (1 - P.pop[p].y[b]) * P.pop[p].fIa[b] * dIa\n                );\n            }\n            n_inf2 += inf2[a];\n        }\n\n        Rt = n_inf2 / n_inf;\n\n        swap(n_inf2, n_inf);\n        swap(inf2, inf);\n    }\n\n    return Rt;\n}\n\n// clamp a number between two limits\ndouble clamp(double x, double x0, double x1)\n{\n    return min(max(x, x0), x1);\n}\n\n// smootherstep function\ndouble smootherstep(double x0, double x1, double y0, double y1, double x)\n{\n    x = clamp((x - x0) / (x1 - x0));\n    return y0 + x * x * x * (x * (x * 6. - 15.) + 10.) * (y1 - y0);\n}\n", "meta": {"hexsha": "71d809aecba70fb0059ba94d837d9c326c1cd576", "size": 4890, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/covidm_for_fitting/model_v2/convenience.cpp", "max_stars_repo_name": "yangclaraliu/COVID_Vac_Delay", "max_stars_repo_head_hexsha": "0c3a88ab26d2983b809779eda97194f5d9b9cb51", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-04T21:05:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T21:05:34.000Z", "max_issues_repo_path": "code/covidm_for_fitting/model_v2/convenience.cpp", "max_issues_repo_name": "yangclaraliu/COVID_Vac_Delay", "max_issues_repo_head_hexsha": "0c3a88ab26d2983b809779eda97194f5d9b9cb51", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/covidm_for_fitting/model_v2/convenience.cpp", "max_forks_repo_name": "yangclaraliu/COVID_Vac_Delay", "max_forks_repo_head_hexsha": "0c3a88ab26d2983b809779eda97194f5d9b9cb51", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4578313253, "max_line_length": 131, "alphanum_fraction": 0.5531697342, "num_tokens": 1550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6087689967002894}}
{"text": "//\n// Created by squintingsmile on 2020/9/22.\n//\n\n#include <cstring>\n#include <cmath>\n#include <chrono>\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <fstream>\n#include \"LPboxADMMsolver.h\"\n\nusing namespace Eigen::internal;\nusing std::abs;\nusing std::sqrt;\nEigen::IOFormat CommaInitFmt(Eigen::StreamPrecision, Eigen::DontAlignCols,\n\t\t\", \", \", \", \"\", \"\", \" << \", \";\");\n\n/* The original function is imported from the Eigen library. Added clocks to monitor times */\nvoid _conjugate_gradient(const SparseMatrix& mat, const DenseVector& rhs, DenseVector& x,\n\t\tconst Eigen::DiagonalPreconditioner<_double_t>& precond, int& iters, typename DenseVector::RealScalar& tol_error)\n{\n\n\ttypedef typename DenseVector::RealScalar RealScalar;\n\ttypedef typename DenseVector::Scalar Scalar;\n\ttypedef Eigen::Matrix<Scalar,Dynamic,1> VectorType;\n\n\tRealScalar tol = tol_error;\n\tint maxIters = iters;\n\n\tint n = mat.cols();\n\n\tVectorType residual = rhs - mat * x; //initial residual\n\n\tRealScalar rhsNorm2 = rhs.squaredNorm();\n\n\tif(rhsNorm2 == 0)\n\t{\n\t\tx.setZero();\n\t\titers = 0;\n\t\ttol_error = 0;\n\t\treturn;\n\t}\n\n\tconst RealScalar considerAsZero = (std::numeric_limits<RealScalar>::min)();\n\tRealScalar threshold = Eigen::numext::maxi(RealScalar(tol*tol*rhsNorm2),considerAsZero);\n\tRealScalar residualNorm2 = residual.squaredNorm();\n\n\tif (residualNorm2 < threshold)\n\t{\n\t\titers = 0;\n\t\ttol_error = sqrt(residualNorm2 / rhsNorm2);\n\t\treturn;\n\t}\n\n\tVectorType p(n);\n\tp = precond.solve(residual);      // initial search direction\n\n\tVectorType z(n), tmp(n);\n\tRealScalar absNew = Eigen::numext::real(residual.dot(p));  // the square of the absolute value of r scaled by invM\n\tint i = 0;\n\twhile(i < maxIters)\n\t{\n\t\ttmp.noalias() = mat * p;                    // the bottleneck of the algorithm\n\n\t\tScalar alpha = absNew / p.dot(tmp);         // the amount we travel on dir\n\n\t\tx += alpha * p;                             // update solution\n\n\t\tresidual -= alpha * tmp;                    // update residual\n\n\t\tresidualNorm2 = residual.squaredNorm();\n\n\t\tif(residualNorm2 < threshold) {\n\t\t\ti++;\n\t\t\tbreak;\n\t\t}\n\n\t\tz = precond.solve(residual);                // approximately solve for \"A z = residual\"\n\n\t\tRealScalar absOld = absNew;\n\t\tabsNew = Eigen::numext::real(residual.dot(z));     // update the absolute value of r\n\t\tRealScalar beta = absNew / absOld;          // calculate the Gram-Schmidt value used to create the new search direction\n\t\tp = z + beta * p;                           // update search direction\n\t\ti++;\n\t}\n\ttol_error = sqrt(residualNorm2 / rhsNorm2);\n\titers = i;\n\treturn;\n}\n\n/* The .noalias() function explicity states that result of the matrix multiplication can be written\n * on lhs directly without allocating an empty vector first and store the result, then assigning\n * it to lhs. This hopefully will save some time\n */\nvoid mat_mul_vec(const SparseMatrix &mat, const DenseVector &vec, DenseVector& res) {\n\tif (mat.cols() == mat.rows() || &vec != &res) {\n\t\tres.noalias() = mat * vec;\n\t} else {\n\t\tres = mat * vec;\n\t}\n}\n\n/* This is used to avoid direct matrix multiplication. Suppose that we want to calculate A^TAx where A is large\n * so calculating A^TAx is intractable. Then we calculate Ax then calculate A^T(Ax) to reduce the number of operations.\n * In this vector mat_expression, each entry is a vector of sparse matrices. For each entry, the result is calculated by\n * entry[n] ... entry[2] * (entry[1] * (entry[0] * x)) and the results calculated by different entries are sum together\n */\nvoid calculate_mat_expr_multiplication(const std::vector<std::vector<const SparseMatrix*>> &mat_expressions,\n\t\tDenseVector &x, DenseVector &result, DenseVector &temp_vec) {\n\n\tif (mat_expressions.size() == 0) {\n\t\tprintf(\"Empty matrix expression when doing multiplication\\n\");\n\t\treturn;\n\t}\n\n\tDenseVector *original_x;\n\tif (&x == &result && mat_expressions.size() > 1) {\n\t\toriginal_x = new DenseVector(x);\n\t} else {\n\t\toriginal_x = &x;\n\t}\n\n\t{\n\t\tconst std::vector<const SparseMatrix*> &expression = mat_expressions[0];\n\t\tint counter = 0;\n\t\tfor (const SparseMatrix *mat : expression) {\n\t\t\tif (counter == 0) {\n\t\t\t\tmat_mul_vec(*mat, x, result);\n\t\t\t} else {\n\t\t\t\tmat_mul_vec(*mat, result, result);\n\t\t\t}\n\t\t\tcounter += 1;\n\t\t}\n\t}\n\n\tif (mat_expressions.size() > 1) {\n\t\tfor (auto iter = std::next(mat_expressions.begin(), 1); iter != mat_expressions.end(); iter++) {\n\t\t\tint counter = 0;\n\t\t\tfor (const SparseMatrix *mat : *iter) {\n\t\t\t\tif (counter == 0) {\n\t\t\t\t\tmat_mul_vec(*mat, *original_x, temp_vec);\n\t\t\t\t} else {\n\t\t\t\t\tmat_mul_vec(*mat, temp_vec, temp_vec);\n\t\t\t\t}\n\t\t\t\tcounter += 1;\n\t\t\t}\n\n\t\t\tresult += temp_vec;\n\t\t}\n\n\t\tif (&x == &result) {\n\t\t\tdelete original_x;\n\t\t}\n\t}\n}\n\n\n/* The original function is imported from the Eigen library. Passing the two temporary vectors to save the time of\n * allocating vectors\n */\n\nvoid _conjugate_gradient(const std::vector<std::vector<const SparseMatrix*>> &mat_expressions, const DenseVector& rhs,\n\t\tDenseVector& x, const Eigen::DiagonalPreconditioner<_double_t>& precond, int& iters,\n\t\ttypename DenseVector::RealScalar& tol_error, DenseVector &temp_vec_for_cg, DenseVector &temp_vec_for_mat_mul) {\n\n\ttypedef typename DenseVector::RealScalar RealScalar;\n\ttypedef typename DenseVector::Scalar Scalar;\n\ttypedef Eigen::Matrix<Scalar,Dynamic,1> VectorType;\n\n\tRealScalar tol = tol_error;\n\tint maxIters = iters;\n\n\tint n = mat_expressions[0][0]->cols();\n\n\n\tcalculate_mat_expr_multiplication(mat_expressions, x, temp_vec_for_cg, temp_vec_for_mat_mul);\n\tVectorType residual = rhs - temp_vec_for_cg; //initial residual\n\n\tRealScalar rhsNorm2 = rhs.squaredNorm();\n\n\tif(rhsNorm2 == 0) {\n\t\tx.setZero();\n\t\titers = 0;\n\t\ttol_error = 0;\n\t\treturn;\n\t}\n\n\tconst RealScalar considerAsZero = (std::numeric_limits<RealScalar>::min)();\n\tRealScalar threshold = Eigen::numext::maxi(RealScalar(tol*tol*rhsNorm2),considerAsZero);\n\tRealScalar residualNorm2 = residual.squaredNorm();\n\n\tif (residualNorm2 < threshold)\n\t{\n\t\titers = 0;\n\t\ttol_error = sqrt(residualNorm2 / rhsNorm2);\n\t\treturn;\n\t}\n\tVectorType p(n);\n\tp = precond.solve(residual);      // initial search direction\n\n\tVectorType z(n), tmp(n);\n\tRealScalar absNew = Eigen::numext::real(residual.dot(p));  // the square of the absolute value of r scaled by invM\n\tint i = 0;\n\twhile(i < maxIters)\n\t{\n\t\tcalculate_mat_expr_multiplication(mat_expressions, p, tmp, temp_vec_for_mat_mul);\n\n\t\tScalar alpha = absNew / p.dot(tmp);         // the amount we travel on dir\n\n\t\tx += alpha * p;                             // update solution\n\n\t\tresidual -= alpha * tmp;                    // update residual\n\n\t\tresidualNorm2 = residual.squaredNorm();\n\n\t\tif(residualNorm2 < threshold) {\n\t\t\ti++;\n\t\t\tbreak;\n\t\t}\n\n\t\tz = precond.solve(residual);                // approximately solve for \"A z = residual\"\n\n\t\tRealScalar absOld = absNew;\n\t\tabsNew = Eigen::numext::real(residual.dot(z));     // update the absolute value of r\n\t\tRealScalar beta = absNew / absOld;          // calculate the Gram-Schmidt value used to create the new search direction\n\t\tp = z + beta * p;                           // update search direction\n\t\ti++;\n\t}\n\ttol_error = sqrt(residualNorm2 / rhsNorm2);\n\titers = i;\n\treturn;\n}\n\n\n_double_t LPboxADMMsolver::std_dev(std::vector<_double_t>& arr, size_t begin, size_t end) {\n\t_double_t mean = 0;\n\t_double_t std_deviation = 0;\n\tsize_t size = end - begin;\n\tfor (int i = begin; i < end; i++) {\n\t\tmean += arr[i];\n\t}\n\n\tmean /= size;\n\tfor (int i = 0; i < size; i++) {\n\t\tstd_deviation += (arr[begin + i] - mean) * (arr[begin + i] - mean);\n\t}\n\n\tstd_deviation /= size - 1;\n\tif (std_deviation == 0) {\n\t\treturn 0;\n\t}\n\n\treturn std::pow(std_deviation, 1.0 / 2);\n}\n\nvoid LPboxADMMsolver::project_vec_greater_than(DenseVector &x, DenseVector &res, const int &greater_val, const int &set_val) {\n\tint len = x.size();\n\tfor (int i = 0; i < len; i++) {\n\t\tres[i] = x[i] > greater_val ? set_val : x[i];\n\t}\n}\n\nvoid LPboxADMMsolver::project_vec_less_than(DenseVector &x, DenseVector &res, const int &less_val, const int &set_val) {\n\tint len = x.size();\n\tfor (int i = 0; i < len; i++) {\n\t\tres(i) = x(i) < less_val ? set_val : x(i);\n\t}\n}\n\nvoid LPboxADMMsolver::project_box(int n, const double *x, double *y) {\n\ty = new double[n];\n\twhile (n--) {\n\t\tif (x[n] > 1) {\n\t\t\ty[n] = 1;\n\t\t} else {\n\t\t\tif (x[n] < 0) {\n\t\t\t\ty[n] = 0;\n\t\t\t} else {\n\t\t\t\ty[n] = x[n];\n\t\t\t}\n\t\t}\n\t}\n}\n\n/* TODO: Utilize eigen .array() functions to speed up this operation */\nvoid LPboxADMMsolver::project_box(int n, const DenseVector &x, DenseVector &y) {\n\twhile (n--) {\n\t\tif (x[n] > 1) {\n\t\t\ty[n] = 1;\n\t\t} else {\n\t\t\tif (x[n] < 0) {\n\t\t\t\ty[n] = 0;\n\t\t\t} else {\n\t\t\t\ty[n] = x[n];\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid LPboxADMMsolver::project_shifted_Lp_ball(int n, const DenseVector &x, int p, DenseVector &y) {\n\ty.array() = x.array() - 0.5;\n\t_double_t normp_shift = y.norm();\n\n\ty.array() = y.array() * std::pow(n, 1.0 / p) / (2 * normp_shift) + 0.5;\n}\n\n_double_t LPboxADMMsolver::compute_cost(const DenseVector& x, const SparseMatrix& A, \n\t\tconst DenseVector& b, DenseVector &temp_vec_for_mat_mul) {\n\tmat_mul_vec(A, x, temp_vec_for_mat_mul);\n\tdouble val = x.transpose().dot(temp_vec_for_mat_mul);\n\tdouble val2 = b.dot(x);\n\treturn val + val2;\n}\n\n_double_t LPboxADMMsolver::compute_cost(const DenseVector& x, const SparseMatrix& A, const DenseVector& b) {\n\tdouble val = x.transpose().dot(A * x);\n\tdouble val2 = b.dot(x);\n\treturn val + val2;\n}\n\n_double_t LPboxADMMsolver::compute_std_obj(std::vector<_double_t> obj_list, int history_size) {\n\tsize_t s = obj_list.size();\n\t_double_t std_obj;\n\tif (s <= history_size) {\n\t\tstd_obj = std_dev(obj_list, 0, s);\n\t} else {\n\t\tstd_obj = std_dev(obj_list, s - history_size, s);\n\t}\n\n\treturn std_obj / std::abs(obj_list[s-1]);\n}\n\nvoid LPboxADMMsolver::ADMM_bqp_unconstrained_init() {\n\tstd_threshold = 1e-6;\n\tgamma_val = 1.0;\n\tgamma_factor = 0.99;\n\tinitial_rho = 5;\n\tlearning_fact = 1 + 3.0 / 100;\n\trho_upper_limit = 1000;\n\thistory_size = 5;\n\trho_change_step = 5;\n\trel_tol = 1e-5;\n\tstop_threshold = 1e-3;\n\tmax_iters = 1e4;\n\tprojection_lp = 2;\n\tpcg_tol = 1e-3;\n\tpcg_maxiters = 1e3;\n}\n\nvoid LPboxADMMsolver::ADMM_bqp_linear_eq_init() {\n\tstop_threshold = 1e-4;\n\tstd_threshold = 1e-6;\n\tgamma_val = 1.6;\n\tgamma_factor = 0.95;\n\trho_change_step = 5;\n\tmax_iters = 5e3;\n\tinitial_rho = 1;\n\thistory_size = 3;\n\tlearning_fact = 1 + 5.0 / 100;\n\tpcg_tol = 1e-4;\n\tpcg_maxiters = 1e3;\n\trel_tol = 5e-5;\n\tprojection_lp=2;\n}\n\nvoid LPboxADMMsolver::ADMM_bqp_linear_ineq_init() {\n\tstop_threshold = 1e-4;\n\tstd_threshold = 1e-6;\n\tgamma_val = 1.6;\n\tgamma_factor = 0.95;\n\trho_change_step = 5;\n\tmax_iters = 1e4;\n\tinitial_rho = 25;\n\thistory_size = 3;\n\tlearning_fact = 1 + 1.0 / 100;\n\tpcg_tol = 1e-4;\n\tpcg_maxiters = 1e3;\n\trel_tol = 5e-5;\n\tprojection_lp = 2;\n\n}\n\nvoid LPboxADMMsolver::ADMM_bqp_linear_eq_and_uneq_init() {\n\tstop_threshold = 1e-4;\n\tstd_threshold = 1e-6;\n\tgamma_val = 1.6;\n\tgamma_factor = 0.95;\n\trho_change_step = 5;\n\tmax_iters = 1e4;\n\tinitial_rho = 25;\n\thistory_size = 3;\n\tlearning_fact = 1 + 1.0 / 100;\n\tpcg_tol = 1e-4;\n\tpcg_maxiters = 1e3;\n\trel_tol = 5e-5;\n\tprojection_lp = 2;\n}\n\n\nint LPboxADMMsolver::ADMM_bqp(MatrixInfo matrix_info, SolverInstruction instruction, \n\t\tSolution& sol) {\n\n\n\tconst SparseMatrix *A_ptr, *C_ptr, *E_ptr;\n\tconst DenseVector *b_ptr, *d_ptr, *f_ptr;\n\n\tA_ptr = matrix_info.A;\n\tb_ptr = matrix_info.b;\n\n\tSparseMatrix C_transpose, E_transpose, _2A_plus_rho1_rho2, rho3_C_transpose, rho4_E_transpose;\n\n\tDenseVector y3, z3, z4, Csq_diag, Esq_diag;\n\n\tint l = matrix_info.l;\n\tint m = matrix_info.m;\n\tint n = matrix_info.n;\n\n\tFILE *fp;\n\tif (does_log) {\n\t\tfp = fopen(log_file_path.c_str(), \"w+\");\n\t}\n\n\tDenseVector x_sol    = DenseVector(n);\n\tDenseVector y1       = DenseVector(n);\n\tDenseVector y2       = DenseVector(n);\n\tDenseVector z1       = DenseVector(n);\n\tDenseVector z2       = DenseVector(n);\n\tDenseVector prev_idx = DenseVector(n);\n\tDenseVector best_sol = DenseVector(n);\n\tDenseVector temp_vec = DenseVector(n);\n\tDenseVector cur_idx  = DenseVector(n);\n\tSparseMatrix temp_mat = SparseMatrix(n, n);\n\n\t/* The temp_vec_for_cg and temp_vec_for_mat_mat are vector that used to store the temporary vectors\n\t * in the algorithm to prevent allocating new vectos. Adding this shall has around 5% of performance\n\t * improvement (although might reduce the performance under some tasks by 10% since it increases the cost \n\t * of other operations besides matrix multiplication, such as vector addition and vector multiplication\n\t * for reasons unknown)\n\t */\n\tDenseVector temp_vec_for_cg = DenseVector(n);\n\tDenseVector temp_vec_for_mat_mul = DenseVector(n);\n\t_double_t cur_obj;\n\tbool rhoUpdated = true;\n\n\tx_sol = *(matrix_info.x0);\n\n\tz1.array() = 0;\n\tz2.array() = 0;\n\tcur_idx.array() = 0;\n\n\n\tEigen::DiagonalPreconditioner<_double_t> diagonalPreconditioner;\n\n\t_double_t rho1 = initial_rho;\n\t_double_t rho2 = initial_rho;\n\t_double_t rho3 = initial_rho;\n\t_double_t rho4 = initial_rho;\n\t_double_t prev_rho1 = rho1;\n\t_double_t prev_rho2 = rho2;\n\t_double_t prev_rho3 = rho3;\n\t_double_t prev_rho4 = rho4;\n\n\tstd::vector<_double_t> obj_list; /* Stores the objective value calculated during each iteration */\n\t_double_t std_obj = 1;\n\n\t_double_t cvg_test1;\n\t_double_t cvg_test2;\n\t_double_t rho_change_ratio;\n\n\tif (instruction.update_y3) {\n\t\ty3 = DenseVector(l);\n\t}\n\n\tif (instruction.update_z3) {\n\t\tz3 = DenseVector(m);\n\t\tz3.array() = 0;\n\t}\n\n\tif (instruction.update_z4) {\n\t\tz4 = DenseVector(l);\n\t\tz4.array() = 0;\n\t}\n\n\n\t/* If this task contains equality constraints, initialize C and d and relevant matrices */\n\tif (instruction.problem_type & equality) {\n\t\tC_ptr = matrix_info.C;\n\t\tC_transpose = (*C_ptr).transpose();\n\t\trho3_C_transpose = rho3 * C_transpose;\n\t\td_ptr = matrix_info.d;\n\t}\n\n\t/* If this task contains inequality constraints, initialize E and f and relevant matrices */\n\tif (instruction.problem_type & inequality) {\n\t\tE_ptr = matrix_info.E;\n\t\tE_transpose = (*E_ptr).transpose();\n\t\trho4_E_transpose = rho4 * E_transpose;\n\t\tf_ptr = matrix_info.f;\n\t}\n\n\t/* Storing the matrix 2 * A + (rho1 + rho2) * I to save calculation time */\n\t_2A_plus_rho1_rho2 = 2 * (*A_ptr);\n\t_2A_plus_rho1_rho2.diagonal().array() += rho1 + rho2;\n\n\tSparseMatrix preconditioner_diag_mat(n, n); /* The diagonal matrix used by the preconditioner */\n\tpreconditioner_diag_mat.reserve(n);\n\tstd::vector<Triplet> preconditioner_diag_mat_triplets;\n\tpreconditioner_diag_mat_triplets.reserve(n);\n\t/* The diagonal elements in the original expression evaluated by the preconditioner is given by the\n\t * diagonal elements of 2 * _A + (rho1 + rho2) * I + rho3 * _C^T * _C\n\t */\n\tfor (int i = 0; i < n; i++) {\n\t\tpreconditioner_diag_mat_triplets.push_back(Triplet(i, i, 0));\n\t}\n\tpreconditioner_diag_mat.setFromTriplets(preconditioner_diag_mat_triplets.begin(), preconditioner_diag_mat_triplets.end());\n\tpreconditioner_diag_mat.diagonal().array() = _2A_plus_rho1_rho2.diagonal().array();\n\tpreconditioner_diag_mat.makeCompressed();\n\n\n\t/* The matrix expression for the unconstraint case is 2 * _A + (rho1 + rho2) * I */\n\tstd::vector<std::vector<const SparseMatrix*>> matrix_expressions;\n\tmatrix_expressions.emplace_back();\n\tmatrix_expressions.back().push_back(&_2A_plus_rho1_rho2);\n\n\t/* If the problem has equality constraint, add rho3 * C^T * C to the matrix expression */\n\tif (instruction.problem_type & equality) {\n\t\tmatrix_expressions.emplace_back();\n\t\tmatrix_expressions.back().push_back(C_ptr);\n\t\tmatrix_expressions.back().push_back(&rho3_C_transpose);\n\n\t\t/* Calculating the diagonal elements of Csq for preconditioner */\n\t\tCsq_diag = DenseVector(n); \t\t\n\t\tCsq_diag.setZero();\n\t\tfor(int j = 0; j < C_transpose.outerSize(); ++j) {\n\t\t\ttypename SparseMatrix::InnerIterator it(C_transpose, j);\n\t\t\twhile (it) {\n\t\t\t\tif(it.value() != 0.0) {\n\t\t\t\t\tCsq_diag[j] += it.value() * it.value();\n\t\t\t\t}\n\t\t\t\t++it;\n\t\t\t}\n\t\t}\n\t\tpreconditioner_diag_mat.diagonal().array() += rho3 * Csq_diag.array();\n\t}\n\n\t/* If the problem has equality constraint, add rho4 * E^T * E to the matrix expression */\n\tif (instruction.problem_type &inequality) {\n\t\tmatrix_expressions.emplace_back();\n\t\tmatrix_expressions.back().push_back(E_ptr);\n\t\tmatrix_expressions.back().push_back(&rho4_E_transpose);\n\n\t\t/* Calculating the diagonal elements of Esq for preconditioner */\n\t\tEsq_diag = DenseVector(n);\n\t\tEsq_diag.setZero();\n\t\tfor(int j = 0; j < E_transpose.outerSize(); ++j) {\n\t\t\ttypename SparseMatrix::InnerIterator it(E_transpose, j);\n\t\t\twhile (it) {\n\t\t\t\tif(it.value() != 0.0) {\n\t\t\t\t\tEsq_diag[j] += it.value() * it.value();\n\t\t\t\t}\n\t\t\t\t++it;\n\t\t\t}\n\t\t}\n\t\tpreconditioner_diag_mat.diagonal().array() += rho4 * Esq_diag.array();\n\t}\n\n\ty1 = x_sol;\n\ty2 = x_sol;\n\tif (instruction.update_y3) {\n\t\ty3 = *f_ptr - *E_ptr * x_sol;\n\t}\n\n\tprev_idx = (x_sol.array() >= 0.5).matrix().cast<_double_t>();\n\tbest_sol = x_sol;\n\n\t_double_t best_bin_obj = compute_cost(x_sol, *A_ptr, *b_ptr, temp_vec_for_mat_mul);\n\n\tif (does_log) {\n\t\tfprintf(fp, \"Initial state\\n\");\n        fprintf(fp, \"norm of x_sol: %lf\\n\", x_sol.norm());\n        fprintf(fp, \"norm of b: %lf\\n\", (*b_ptr).norm());\n        fprintf(fp, \"norm of y1: %lf\\n\", y1.norm());\n        fprintf(fp, \"norm of y2: %lf\\n\", y2.norm());\n        if (instruction.update_y3) {\n            fprintf(fp, \"norm of y3: %lf\\n\", y3.norm());\n        }\n\n        fprintf(fp, \"norm of z1: %lf\\n\", z1.norm());\n        fprintf(fp, \"norm of z2: %lf\\n\", z2.norm());\n\n        if (instruction.update_z3) {\n            fprintf(fp, \"norm of z3: %lf\\n\", z3.norm());\n        }\n\n        if (instruction.update_z4) {\n            fprintf(fp, \"norm of z4: %lf\\n\", z4.norm());\n        }\n\n        fprintf(fp, \"norm of cur_idx: %lf\\n\", cur_idx.norm());\n        fprintf(fp, \"rho1: %lf\\n\", rho1);\n        fprintf(fp, \"rho2: %lf\\n\", rho2);\n        fprintf(fp, \"rho3: %lf\\n\", rho3);\n        fprintf(fp, \"rho4: %lf\\n\", rho4);\n        fprintf(fp, \"-------------------------------------------------\\n\");\n\t}\n\n\tstd::chrono::steady_clock::time_point start, end;\n\tstart = std::chrono::steady_clock::now();\n\n\n\tlong time_elapsed = 0;\n\tfor (int iter = 0; iter < max_iters; iter++) {\n\t\tif (does_log) {\n\t\t\tfprintf(fp, \"Iteration: %d\\n\", iter);\n\t\t}\n\t\ttemp_vec = x_sol + z1 / rho1;\n\n\t\t/* Project vector on [0, 1] box */\n\t\tproject_box(n, temp_vec, y1);\n\n\t\ttemp_vec = x_sol + z2 / rho2;\n\n\t\t/* Project vector on shifted lp box */\n\t\tproject_shifted_Lp_ball(n, temp_vec, projection_lp, y2);\n\n\t\tif (instruction.update_y3) {\n\t\t\tmat_mul_vec(*E_ptr, x_sol, temp_vec_for_mat_mul);\n\t\t\ty3 = *f_ptr - temp_vec_for_mat_mul - z4 / rho4;\n\t\t\tproject_vec_less_than(y3, y3, 0, 0); \n\t\t}\n\n\t\t/* If the iteration is nonzero and it divides rho_change_step, it means\n\t\t * that the rho updated in the last iteration\n\t\t */\n\t\tif (iter != 0 && rhoUpdated) {\n\t\t\t/* Note that we need the previous rho to update in order to get the difference between\n\t\t\t * the updated matrix and the not updated matrix. Another possible calculation is by\n\t\t\t * calculating rho * rho_change_ration / learning_fact\n\t\t\t */\n\t\t\t_2A_plus_rho1_rho2.diagonal().array() += rho_change_ratio * (prev_rho1 + prev_rho2);\n\t\t\tif (instruction.problem_type != unconstrained) {\n\t\t\t\tpreconditioner_diag_mat.diagonal().array() += rho_change_ratio * (prev_rho1 + prev_rho2);\n\t\t\t}\n\n\t\t\tif (instruction.update_rho3) {\n\t\t\t\tpreconditioner_diag_mat.diagonal().array() += rho_change_ratio * prev_rho3 * Csq_diag.array();\n\t\t\t\trho3_C_transpose = learning_fact * rho3_C_transpose;\t\n\t\t\t}\n\n\t\t\tif (instruction.update_rho4) {\n\t\t\t\tpreconditioner_diag_mat.diagonal().array() += rho_change_ratio * prev_rho4 * Esq_diag.array();\n\t\t\t\trho4_E_transpose = learning_fact * rho4_E_transpose;\n\t\t\t}\n\t\t}\n\n\n\n\t\t/* If the problem in unconstrained, the rhs vector is \n\t\t * rho1 * y1 + rho2 * y2 - (b + z1 + z2)\n\t\t */\n\t\tif (instruction.problem_type == unconstrained) {\n\t\t\ttemp_vec = rho1 * y1 + rho2 * y2 - (*b_ptr + z1 + z2);\n\t\t}\n\n\t\t/* If the problem in equality, the rhs vector is \n\t\t * rho1 * y1 + rho2 * y2 + rho3 * C^T * d - (b + z1 + z2 + C^T * z3)\n\t\t */\n\t\tif (instruction.problem_type == equality) {\n\t\t\ttemp_vec = rho1 * y1 + rho2 * y2 - (*b_ptr + z1 + z2);\n\t\t\tmat_mul_vec(rho3_C_transpose, *d_ptr, temp_vec_for_mat_mul);\n\t\t\ttemp_vec += temp_vec_for_mat_mul;\n\t\t\tmat_mul_vec(C_transpose, z3, temp_vec_for_mat_mul);\n\t\t\ttemp_vec -= temp_vec_for_mat_mul;\n\t\t}\n\n\t\t/* If the problem in equality, the rhs vector is \n\t\t * rho1 * y1 + rho2 * y2 + rho4 * E^T * (f - y3) - (b + z1 + z2 + E^T * z4)\n\t\t */\n\t\tif (instruction.problem_type == inequality) {\n\t\t\ttemp_vec = rho1 * y1 + rho2 * y2 - (*b_ptr + z1 + z2);\n\t\t\tmat_mul_vec(rho4_E_transpose, *f_ptr - y3, temp_vec_for_mat_mul);\n\t\t\ttemp_vec += temp_vec_for_mat_mul;\n\t\t\tmat_mul_vec(E_transpose, z4, temp_vec_for_mat_mul);\n\t\t\ttemp_vec -= temp_vec_for_mat_mul;\n\t\t}\n\n\t\t/* If the problem in equality, the rhs vector is \n\t\t * rho1 * y1 + rho2 * y2 + rho3 * C^T * d + rho4 * E^T * (f - y3) - (b + z1 + z2 + C^T * z3 + E^T * z4)\n\t\t */\n\t\tif (instruction.problem_type == equality_and_inequality) {\n\t\t\ttemp_vec = rho1 * y1 + rho2 * y2 - (*b_ptr + z1 + z2);\n\t\t\tmat_mul_vec(rho3_C_transpose, *d_ptr, temp_vec_for_mat_mul);\n\t\t\ttemp_vec += temp_vec_for_mat_mul;\n\t\t\tmat_mul_vec(C_transpose, z3, temp_vec_for_mat_mul);\n\t\t\ttemp_vec -= temp_vec_for_mat_mul;\n\t\t\tmat_mul_vec(rho4_E_transpose, *f_ptr - y3, temp_vec_for_mat_mul);\n\t\t\ttemp_vec += temp_vec_for_mat_mul;\n\t\t\tmat_mul_vec(E_transpose, z4, temp_vec_for_mat_mul);\n\t\t\ttemp_vec -= temp_vec_for_mat_mul;\n\t\t}\n\n\n\t\t/* Explicit version of conjugate gradient used for profiling */\n\t\tif (rhoUpdated) {\n\t\t\tif (instruction.problem_type != unconstrained) {\n\t\t\t\tdiagonalPreconditioner.compute(preconditioner_diag_mat);\n\t\t\t} else {\n\t\t\t\tdiagonalPreconditioner.compute(_2A_plus_rho1_rho2);\n\t\t\t}\n\t\t\trhoUpdated = false;\n\t\t}\n\t\t_double_t tol = pcg_tol;\n\t\tx_sol = y1;\n\t\tint maxiter = pcg_maxiters;\n\t\t_conjugate_gradient(matrix_expressions, temp_vec, x_sol, diagonalPreconditioner, \n\t\t\t\tmaxiter, tol, temp_vec_for_cg, temp_vec_for_mat_mul);\n\n\t\tif (does_log) {\n\t\t\tfprintf(fp, \"Conjugate gradient stops after %d iterations\\n\", maxiter);\n\t\t\tfprintf(fp, \"Conjugate gradient stops with residual %lf\\n\", tol);\n\t\t}\n\n\t\tz1 = z1 + gamma_val * rho1 * (x_sol - y1);\n\t\tz2 = z2 + gamma_val * rho2 * (x_sol - y2);\n\t\tif (instruction.update_z3) {\n\t\t\tz3 = z3 + gamma_val * rho3 * (*C_ptr * x_sol - *d_ptr);\n\t\t}\n\n\t\tif (instruction.update_z4) {\n\t\t\tz4 = z4 + gamma_val * rho4 * ((*E_ptr) * x_sol + y3 - (*f_ptr));\n\t\t}\n\n\n\t\t_double_t temp0 = std::max(x_sol.norm(), _double_t(2.2204e-16));\n\t\tcvg_test1 = (x_sol - y1).norm() / temp0;\n\t\tcvg_test2 = (x_sol - y2).norm() / temp0;\n\t\tif (cvg_test1 <= stop_threshold && cvg_test2 <= stop_threshold) {\n\t\t\tprintf(\"iter: %d, stop_threshold: %.6f\\n\", iter, std::max(cvg_test1, cvg_test2));\n\t\t\tif (does_log) {\n\t\t\t\tfprintf(fp, \"iter: %d, stop_threshold: %.6f\\n\", iter, std::max(cvg_test1, cvg_test2));\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tif ((iter+1) % rho_change_step == 0) {\n\t\t\tprev_rho1 = rho1;\n\t\t\tprev_rho2 = rho2;\n\t\t\trho1 = learning_fact * rho1;\n\t\t\trho2 = learning_fact * rho2;\n\n\t\t\tif (instruction.update_rho3) {\n\t\t\t\tprev_rho3 = rho3;\n\t\t\t\trho3 = learning_fact * rho3;\n\t\t\t}\n\n\t\t\tif (instruction.update_rho4) {\n\t\t\t\tprev_rho4 = rho4;\n\t\t\t\trho4 = learning_fact * rho4;\n\t\t\t}\n\n\t\t\tgamma_val = std::max(gamma_val * gamma_factor, _double_t(1.0));\n\t\t\trhoUpdated = true;\n\t\t\trho_change_ratio = learning_fact - 1.0;\n\t\t}\n\n\t\t_double_t obj_val = compute_cost(x_sol, *A_ptr, *b_ptr);\n\t\tobj_list.push_back(obj_val);\n\t\tif (obj_list.size() >= history_size) {\n\t\t\tstd_obj = compute_std_obj(obj_list, history_size);\n\t\t}\n\t\tif (std_obj <= std_threshold) {\n\t\t\tif (does_log) {\n\t\t\t\tfprintf(fp, \"iter: %d, std_threshold: %.6f\\n\", iter, std_obj);\n\t\t\t}\n\t\t\tprintf(\"iter: %d, std_threshold: %.6f\\n\", iter, std_obj);\n\t\t\tbreak;\n\t\t}\n\n\t\tcur_idx = (x_sol.array() >= 0.5).matrix().cast<_double_t>();\n\t\tprev_idx = cur_idx;\n\t\tcur_obj = compute_cost(prev_idx, *A_ptr, *b_ptr);\n\n\t\tif (best_bin_obj >= cur_obj) {\n\t\t\tbest_bin_obj = cur_obj;\n\t\t\tbest_sol = x_sol;\n\t\t}\n\n\t\tif (does_log) {\n\t\t\tfprintf(fp, \"current objective: %lf\\n\", obj_val);\n\t\t\tfprintf(fp, \"current binary objective: %lf\\n\", cur_obj);\n\n\t\t\tif (instruction.problem_type == equality || instruction.problem_type == equality_and_inequality) {\n\t\t\t\tfprintf(fp, \"equality constraint violation: %lf\\n\", (*matrix_info.C * cur_idx - *matrix_info.d).norm() / x_sol.rows());\n\t\t\t}\n\n\t\t\tif (instruction.problem_type == inequality || instruction.problem_type == equality_and_inequality) {\n\t\t\t\tDenseVector diff = *matrix_info.E * cur_idx - *matrix_info.f;\n\t\t\t\tproject_vec_less_than(diff, diff, 0, 0);\n\t\t\t\tfprintf(fp, \"inequality constraint violation: %lf\\n\", diff.norm() / x_sol.rows());\n\t\t\t}\n\n\t\t\tfprintf(fp, \"norm of x_sol: %lf\\n\", x_sol.norm());\n\t\t\tfprintf(fp, \"norm of y1: %lf\\n\", y1.norm());\n\t\t\tfprintf(fp, \"norm of y2: %lf\\n\", y2.norm());\n\t\t\tif (instruction.update_y3) {\n\t\t\t\tfprintf(fp, \"norm of y3: %lf\\n\", y3.norm());\n\t\t\t}\n\n\t\t\tfprintf(fp, \"norm of z1: %lf\\n\", z1.norm());\n\t\t\tfprintf(fp, \"norm of z2: %lf\\n\", z2.norm());\n\n\t\t\tif (instruction.update_z3) {\n\t\t\t\tfprintf(fp, \"norm of z3: %lf\\n\", z3.norm());\n\t\t\t}\n\n\t\t\tif (instruction.update_z4) {\n\t\t\t\tfprintf(fp, \"norm of z4: %lf\\n\", z4.norm());\n\t\t\t}\n\n\t\t\tfprintf(fp, \"norm of cur_idx: %lf\\n\", cur_idx.norm());\n\t\t\tfprintf(fp, \"rho1: %lf\\n\", rho1);\n\t\t\tfprintf(fp, \"rho2: %lf\\n\", rho2);\n\t\t\tif (instruction.update_rho3) {\n\t\t\t\tfprintf(fp, \"rho3: %lf\\n\", rho3);\n\t\t\t}\n\t\t\tif (instruction.update_rho4) {\n\t\t\t\tfprintf(fp, \"rho4: %lf\\n\", rho4);\n\t\t\t}\n\t\t\tfprintf(fp, \"-------------------------------------------------\\n\");\n\t\t}\n\t}\n\n\tsol.x_sol = new DenseVector(x_sol);\n\tsol.y1 = new DenseVector(y1);\n\tsol.y2 = new DenseVector(y2);\n\tsol.best_sol = new DenseVector(best_sol);\n\n\tend = std::chrono::steady_clock::now();\n\ttime_elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();\n\tstd::cout << \"Time elapsed: \" << time_elapsed << \"us\" << std::endl;\n\tif (does_log) {\n\t\tfprintf(fp, \"Time elapsed: %ldus\\n\", time_elapsed);\n\t\tfclose(fp);\n\t}\n\tsol.time_elapsed = time_elapsed;\n\n\treturn 1;\n}\n\nint LPboxADMMsolver::ADMM_bqp_unconstrained(int n, const SparseMatrix &_A, const DenseVector &_b, \n\t\tconst DenseVector &x0, Solution& sol) {\n\n\tSolverInstruction solver_instruction;\n\tMatrixInfo matrix_info;\n\n\tmatrix_info.x0 = &x0;\n\tmatrix_info.A = &_A;\n\tmatrix_info.b = &_b;\n\tmatrix_info.n = n;\n\n\tsolver_instruction.problem_type = unconstrained;\n\tsolver_instruction.update_y3 = 0;\n\tsolver_instruction.update_z3 = 0;\n\tsolver_instruction.update_z4 = 0;\n\tsolver_instruction.update_rho3 = 0;\n\tsolver_instruction.update_rho4 = 0;\n\n\tADMM_bqp(matrix_info, solver_instruction, sol);\n\treturn 1;\n}\n\n\n\nint LPboxADMMsolver::ADMM_bqp_unconstrained(int n, _double_t *A, _double_t *b, _double_t *x0, \n\t\tSolution& sol) {\n\t/* Initialize the parameters */\n\tauto _A = SparseMatrix(n, n);\n\tauto _b = DenseVector(n);\n\tauto _x0 = DenseVector(n);\n\n\t/* Generating the sparse matrix for A */\n\tstd::vector<Triplet> triplet_list;\n\tfor (int i = 0; i < n * n; i++) {\n\t\tint row = i % n;\n\t\tint col = i / n;\n\n\t\tif (A[i] == 0.0 && !(row == col)) {\n\t\t\tcontinue;\n\t\t}\n\t\ttriplet_list.push_back(Triplet(row, col, A[i]));\n\t}\n\t_A.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\tmemcpy(_b.data(), b, n * sizeof(_double_t));\n\tmemcpy(_x0.data(), x0, n * sizeof(_double_t));\n\n\tint ret = ADMM_bqp_unconstrained(n, _A, _b, _x0, sol);\n\treturn ret;\n}\n\n\nint LPboxADMMsolver::ADMM_bqp_linear_eq(int n, const SparseMatrix &_A, const DenseVector &_b, \n\t\tconst DenseVector &x0, int m, const SparseMatrix &_C, const DenseVector &_d, Solution& sol) {\n\n\tSolverInstruction solver_instruction;\n\tMatrixInfo matrix_info;\n\n\tmatrix_info.x0 = &x0;\n\tmatrix_info.A = &_A;\n\tmatrix_info.b = &_b;\n\tmatrix_info.n = n;\n\tmatrix_info.C = &_C;\n\tmatrix_info.d = &_d; \n\tmatrix_info.m = m;\n\n\tsolver_instruction.problem_type = equality;\n\tsolver_instruction.update_y3 = 0;\n\tsolver_instruction.update_z3 = 1;\n\tsolver_instruction.update_z4 = 0;\n\n\t/* If this value is set to be true, then the admm update will update\n     * rho3 at each iteration with rate learning_fact. The default setting\n     * is false, following the strategy in the clustering task */\n\tsolver_instruction.update_rho3 = 0;\n\tsolver_instruction.update_rho4 = 0;\n\n\tADMM_bqp(matrix_info, solver_instruction, sol);\n\treturn 1;\n}\n\n\nint LPboxADMMsolver::ADMM_bqp_linear_eq(int n, _double_t *A, _double_t *b, _double_t *x0, int m, \n\t\t_double_t *C, _double_t *d, Solution& sol) {\n\t/* Initialize the parameters */\n\tauto _A = SparseMatrix(n, n);\n\tauto _b = DenseVector(n);\n\tauto _x0 = DenseVector(n);\n\tauto _C = SparseMatrix(m, n);\n\tauto _d = DenseVector(m);\n\n\t/* Generating the sparse matrix for A */\n\tstd::vector<Triplet> triplet_list; /* Maybe one can reserve some space here */\n\tfor (int i = 0; i < n * n; i++) {\n\t\tif (A[i] == 0.0) {\n\t\t\tcontinue;\n\t\t}\n\t\tint row = i % n;\n\t\tint col = i / n;\n\t\ttriplet_list.push_back(Triplet(row, col, A[i]));\n\t}\n\t_A.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n\t/* Generating the sparse matrix for C */\n\ttriplet_list.clear();\n\tfor (int i = 0; i < m * n; i++) {\n\t\tif (C[i] == 0.0) {\n\t\t\tcontinue;\n\t\t}\n\t\tint row = i % n;\n\t\tint col = i / n;\n\t\ttriplet_list.push_back(Triplet(row, col, C[i]));\n\t}\n\t_C.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n\tmemcpy(_x0.data(), x0, n * sizeof(_double_t));\n\tmemcpy(_b.data(), b, n * sizeof(_double_t));\n\tmemcpy(_d.data(), d, m * sizeof(_double_t));\n\n\tint ret = ADMM_bqp_linear_eq(n, _A, _b, _x0, m, _C, _d, sol);\n\treturn ret;\n}\n\nint LPboxADMMsolver::ADMM_bqp_linear_ineq(int n, const SparseMatrix &_A, const DenseVector &_b,\n\t\tconst DenseVector &x0, int l, const SparseMatrix &_E, const DenseVector &_f, Solution& sol) {\n\n\tSolverInstruction solver_instruction;\n\tMatrixInfo matrix_info;\n\n\tmatrix_info.x0 = &x0;\n\tmatrix_info.A = &_A;\n\tmatrix_info.b = &_b;\n\tmatrix_info.n = n;\n\tmatrix_info.E = &_E;\n\tmatrix_info.f = &_f; \n\tmatrix_info.l = l;\n\n\tsolver_instruction.problem_type = inequality;\n\tsolver_instruction.update_y3 = 1;\n\tsolver_instruction.update_z3 = 0;\n\tsolver_instruction.update_z4 = 1;\n\tsolver_instruction.update_rho3 = 0;\n\tsolver_instruction.update_rho4 = 1;\n\n\tADMM_bqp(matrix_info, solver_instruction, sol);\n\treturn 1;\n}\n\nint LPboxADMMsolver::ADMM_bqp_linear_ineq(int n, _double_t *A, _double_t *b, _double_t *x0, \n\t\tint l, _double_t *E, _double_t *f, Solution& sol) {\n\t/* Initialize the parameters */\n\tauto _A       = SparseMatrix(n, n);\n\tauto _b       = DenseVector(n);\n\tauto _x0\t  = DenseVector(n);\n\tauto _E       = SparseMatrix(l, n);\n\tauto _f       = DenseVector(l);\n\n\t/* Generating the sparse matrix for A */\n\tstd::vector<Triplet> triplet_list; /* Maybe one can reserve some space here */\n\tfor (int i = 0; i < n * n; i++) {\n\t\tif (A[i] == 0.0) {\n\t\t\tcontinue;\n\t\t}\n\t\tint row = i % n;\n\t\tint col = i / n;\n\t\ttriplet_list.push_back(Triplet(row, col, A[i]));\n\t}\n\t_A.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n\t/* Generating the sparse matrix for C */\n\ttriplet_list.clear();\n\tfor (int i = 0; i < l * n; i++) {\n\t\tif (E[i] == 0.0) {\n\t\t\tcontinue;\n\t\t}\n\t\tint row = i % n;\n\t\tint col = i / n;\n\t\ttriplet_list.push_back(Triplet(row, col, E[i]));\n\t}\n\t_E.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n\tmemcpy(_x0.data(), x0, n * sizeof(_double_t));\n\tmemcpy(_b.data(), b, n * sizeof(_double_t));\n\tmemcpy(_f.data(), f, l * sizeof(_double_t));\n\n\tint ret = ADMM_bqp_linear_ineq(n, _A, _b, _x0, l, _E, _f, sol);\n\treturn ret;\n}\n\n\n\nint LPboxADMMsolver::ADMM_bqp_linear_eq_and_uneq(int n, const SparseMatrix &_A, \n\t\tconst DenseVector &_b, const DenseVector &x0, int m, const SparseMatrix &_C, const DenseVector &_d, \n\t\tint l, const SparseMatrix &_E, const DenseVector &_f, Solution& sol) {\n\n\tSolverInstruction solver_instruction;\n\tMatrixInfo matrix_info;\n\n\tmatrix_info.x0 = &x0;\n\tmatrix_info.A = &_A;\n\tmatrix_info.b = &_b;\n\tmatrix_info.n = n;\n\tmatrix_info.C = &_C;\n\tmatrix_info.d = &_d;\n\tmatrix_info.m = m;\n\tmatrix_info.E = &_E;\n\tmatrix_info.f = &_f; \n\tmatrix_info.l = l;\n\n\tsolver_instruction.problem_type = equality_and_inequality;\n\tsolver_instruction.update_y3 = 1;\n\tsolver_instruction.update_z3 = 1;\n\tsolver_instruction.update_z4 = 1;\n\tsolver_instruction.update_rho3 = 1;\n\tsolver_instruction.update_rho4 = 1;\n\n\tADMM_bqp(matrix_info, solver_instruction, sol);\n\treturn 1;\n\n}\n\n\n/* Currently assuming that the input matrix are column majored */\nint LPboxADMMsolver::ADMM_bqp_linear_eq_and_uneq(int n, _double_t *A, _double_t *b, \n\t\t_double_t *x0, int m, _double_t *C, _double_t *d, int l, _double_t *E, _double_t *f, Solution& sol) {\n\t/* Initialize the parameters */\n\tauto _A       = SparseMatrix(n, n);\n\tauto _b       = DenseVector(n);\n\tauto _x0      = DenseVector(n);\n\tauto _C       = SparseMatrix(m, n);\n\tauto _d       = DenseVector(m);\n\tauto _E       = SparseMatrix(l, n);\n\tauto _f       = DenseVector(l);\n\n\t/* Generating the sparse matrix for A */\n\n\tstd::vector<Triplet> triplet_list; /* Maybe one can reserve some space here */\n\tfor (int i = 0; i < n * n; i++) {\n\t\tif (A[i] == 0.0) {\n\t\t\tcontinue;\n\t\t}\n\t\tint row = i % n;\n\t\tint col = i / n;\n\t\ttriplet_list.push_back(Triplet(row, col, A[i]));\n\t}\n\t_A.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n\t/* Generating the sparse matrix for C */\n\ttriplet_list.clear();\n\tfor (int i = 0; i < m * n; i++) {\n\t\tif (E[i] == 0.0) {\n\t\t\tcontinue;\n\t\t}\n\t\tint row = i % n;\n\t\tint col = i / n;\n\t\ttriplet_list.push_back(Triplet(row, col, E[i]));\n\t}\n\t_E.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n\t/* Generating the sparse matrix for C */\n\ttriplet_list.clear();\n\tfor (int i = 0; i < l * n; i++) {\n\t\tif (C[i] == 0.0) {\n\t\t\tcontinue;\n\t\t}\n\t\tint row = i % n;\n\t\tint col = i / n;\n\t\ttriplet_list.push_back(Triplet(row, col, C[i]));\n\t}\n\t_C.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n\tmemcpy(_x0.data(), x0, n * sizeof(_double_t));\n\tmemcpy(_b.data(), b, n * sizeof(_double_t));\n\tmemcpy(_d.data(), d, m * sizeof(_double_t));\n\tmemcpy(_f.data(), f, l * sizeof(_double_t));\n\n\tint ret = ADMM_bqp_linear_eq_and_uneq(n, _A, _b, _x0, m, _C, _d, l, _E, _f, sol);\n\treturn ret;\n}\n\nint LPboxADMMsolver::ADMM_bqp_unconstrained_legacy(int n, const SparseMatrix &_A, const DenseVector &_b,\n\t\tconst DenseVector &x0, Solution& sol) {\n\n\tauto x_sol    = DenseVector(n);\n\tauto y1       = DenseVector(n);\n\tauto y2       = DenseVector(n);\n\tauto z1       = DenseVector(n);\n\tauto z2       = DenseVector(n);\n\tauto prev_idx = DenseVector(n);\n\tauto best_sol = DenseVector(n);\n\tauto temp_vec = DenseVector(n);\n\tauto temp_mat = SparseMatrix(n, n);\n\tauto cur_idx  = DenseVector(n);\n\t_double_t cur_obj;\n\tbool rhoUpdated = true;\n\n\tx_sol = x0;\n\n\t/* Initializing preconditioner for conjugate gradient */\n\tEigen::DiagonalPreconditioner<_double_t> diagonalPreconditioner;\n\n\t_double_t rho1 = initial_rho;\n\t_double_t rho2 = initial_rho;\n\t_double_t prev_rho1 = rho1;\n\t_double_t prev_rho2 = rho2;\n\tstd::vector<_double_t> obj_list; /* Stores the objective value calculated during each iteration */\n\t_double_t std_obj = 1;\n\n\t/* temp_mat stores the matrix that is used in the conjugate gradient step */\n\ttemp_mat = 2 * _A;\n\ttemp_mat.diagonal().array() += rho1 + rho2;\n\ttemp_mat.makeCompressed();\n\n\t_double_t cvg_test1;\n\t_double_t cvg_test2;\n\t_double_t rho_change_ratio;\n\n\ty1 = x_sol;\n\ty2 = x_sol;\n\n\tFILE *fp;\n\tif (does_log) {\n\t\tfp = fopen(log_file_path.c_str(), \"w+\");\n\t}\n\n\tprev_idx = (x_sol.array() >= 0.5).matrix().cast<_double_t>();\n\tbest_sol = x_sol;\n\n\t_double_t best_bin_obj = compute_cost(x_sol, _A, _b);\n\n\tif (does_log) {\n\t\tfprintf(fp, \"Initial state\\n\");\n        fprintf(fp, \"norm of x_sol: %lf\\n\", x_sol.norm());\n        fprintf(fp, \"norm of y1: %lf\\n\", y1.norm());\n        fprintf(fp, \"norm of y2: %lf\\n\", y2.norm());\n\n        fprintf(fp, \"norm of z1: %lf\\n\", z1.norm());\n        fprintf(fp, \"norm of z2: %lf\\n\", z2.norm());\n\n\n        fprintf(fp, \"norm of cur_idx: %lf\\n\", cur_idx.norm());\n        fprintf(fp, \"rho1: %lf\\n\", rho1);\n        fprintf(fp, \"rho2: %lf\\n\", rho2);\n        fprintf(fp, \"-------------------------------------------------\\n\");\n\t}\n\n\tstd::chrono::steady_clock::time_point start, end;\n\tstart = std::chrono::steady_clock::now();\n\n\n\tlong time_elapsed = 0;\n\tfor (int iter = 0; iter < max_iters; iter++) {\n\t\ttemp_vec = x_sol + z1 / rho1;\n\n\t\tif (does_log) {\n\t\t\tfprintf(fp, \"Iteration: %d\\n\", iter);\n\t\t}\n\t\t/* Project vector on [0, 1] box to calculate y1 */\n\t\tproject_box(n, temp_vec, y1);\n\n\t\ttemp_vec = x_sol + z2 / rho2;\n\n\t\t/* Project vector on shifted lp box to calculate y2 */\n\t\tproject_shifted_Lp_ball(n, temp_vec, projection_lp, y2);\n\n\t\t/* If the iteration is nonzero and it divides rho_change_step, it means\n\t\t * that the rho updated in the last iteration and the matrix used by conjugate\n\t\t * gradient should be updated\n\t\t */\n\t\tif (iter != 0 && rhoUpdated) {\n\t\t\ttemp_mat.diagonal().array() += (prev_rho1 + prev_rho2) * rho_change_ratio;\n\t\t\ttemp_mat.makeCompressed();\n\t\t}\n\n\t\t/* Calculate the vector b in the conjugate gradient algorithm */\n\t\ttemp_vec = rho1 * y1 + rho2 * y2 - (_b + z1 + z2);\n\n\t\t/* Explicit version of conjugate gradient used for profiling */\n\n\t\t/* Since the matrix used by the conjugate gradient changes only when after rho is updated\n\t\t * we only need to recalculate the preconditioner if rho is updated in the last iteration\n\t\t */\n\t\tif (rhoUpdated) {\n\t\t\tdiagonalPreconditioner.compute(temp_mat);\n\t\t\trhoUpdated = false;\n\t\t}\n\n\t\tx_sol = y1;\n\t\t_double_t tol = pcg_tol;\n\t\tint maxiter = pcg_maxiters;\n\t\t_conjugate_gradient(temp_mat, temp_vec, x_sol, diagonalPreconditioner, maxiter, tol);\n\t\tif (does_log) {\n\t\t\tfprintf(fp, \"Conjugate gradient stops after %d iterations\\n\", maxiter);\n\t\t\tfprintf(fp, \"Conjugate gradient stops with residual %lf\\n\", tol);\n\t\t}\n\n\t\tz1 = z1 + gamma_val * rho1 * (x_sol - y1);\n\t\tz2 = z2 + gamma_val * rho2 * (x_sol - y2);\n\n\n\t\t/* Testing the conditions to see if the algorithm converges */\n\t\t_double_t temp0 = std::max(x_sol.norm(), _double_t(2.2204e-16));\n\t\tcvg_test1 = (x_sol-y1).norm() / temp0;\n\t\tcvg_test2 = (x_sol-y2).norm() / temp0;\n\t\tif (cvg_test1 <= stop_threshold && cvg_test2 <= stop_threshold) {\n\t\t\tprintf(\"iter: %d, stop_threshold: %.6f\\n\", iter, std::max(cvg_test1, cvg_test2));\n\t\t\tif (does_log) {\n\t\t\t\tfprintf(fp, \"iter: %d, stop_threshold: %.6f\\n\", iter, std::max(cvg_test1, cvg_test2));\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Update the rho value every rho_change_step */\n\t\tif ((iter+1) % rho_change_step == 0) {\n\t\t\tprev_rho1 = rho1;\n\t\t\tprev_rho2 = rho2;\n\t\t\trho1 = learning_fact * rho1;\n\t\t\trho2 = learning_fact * rho2;\n\t\t\tgamma_val = std::max(gamma_val * gamma_factor, _double_t(1.0));\n\t\t\trhoUpdated = true;\n\t\t\trho_change_ratio = learning_fact - 1.0;\n\t\t}\n\n\t\t/* Computer the relaxed cost function (x is not binary)*/\n\t\t_double_t obj_val = compute_cost(x_sol,_A,_b);\n\t\tobj_list.push_back(obj_val);\n\t\tif (obj_list.size() >= history_size) {\n\t\t\tstd_obj = compute_std_obj(obj_list, history_size);\n\t\t}\n\t\tif (std_obj <= std_threshold) {\n\t\t\tprintf(\"iter: %d, std_threshold: %.6f\\n\", iter, std_obj);\n\t\t\tif (does_log) {\n\t\t\t\tfprintf(fp, \"iter: %d, std_threshold: %.6f\\n\", iter, std_obj);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Calculating the actual cost */\n\t\tcur_idx = (x_sol.array() >= 0.5).matrix().cast<_double_t>(); /* The value type of the vector should be double\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  therefore needs casting the boolean vector to double */\n\t\tprev_idx = cur_idx;\n\t\tcur_obj = compute_cost(prev_idx, _A, _b);\n\n\t\t/* Setting the best binary solution */\n\t\tif (best_bin_obj >= cur_obj) {\n\t\t\tbest_bin_obj = cur_obj;\n\t\t\tbest_sol = x_sol;\n\t\t}\n\n\t\tif (does_log) {\n\t\t\tfprintf(fp, \"current objective: %lf\\n\", obj_val);\n\t\t\tfprintf(fp, \"current binary objective: %lf\\n\", cur_obj);\n\t\t\tfprintf(fp, \"norm of x_sol: %lf\\n\", x_sol.norm());\n\t\t\tfprintf(fp, \"norm of binary x_sol: %lf\\n\", cur_idx.norm());\n\t\t\tfprintf(fp, \"norm of y1: %lf\\n\", y1.norm());\n\t\t\tfprintf(fp, \"norm of y2: %lf\\n\", y2.norm());\n\n\t\t\tfprintf(fp, \"norm of z1: %lf\\n\", z1.norm());\n\t\t\tfprintf(fp, \"norm of z2: %lf\\n\", z2.norm());\n\n\t\t\tfprintf(fp, \"rho1: %lf\\n\", rho1);\n\t\t\tfprintf(fp, \"rho2: %lf\\n\", rho2);\n\t\t\tfprintf(fp, \"-------------------------------------------------\\n\");\n\t\t}\n\n\t}\n\tsol.x_sol = new DenseVector(x_sol);\n\tsol.y1 = new DenseVector(y1);\n\tsol.y2 = new DenseVector(y2);\n\tsol.best_sol = new DenseVector(best_sol);\n\n\tend = std::chrono::steady_clock::now();\n\ttime_elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();\n\tstd::cout << \"Time elapsed: \" << time_elapsed << \"us\" << std::endl;\n\tsol.time_elapsed = time_elapsed;\n\n\tif (does_log) {\n\t\tfprintf(fp, \"Time elapsed: %ldus\\n\", time_elapsed);\n\t\tfclose(fp);\n\t}\n\treturn 1;\n}\n", "meta": {"hexsha": "ea50252ac013ff6824f5a9b0740d59cfea0c8b0b", "size": 40052, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/LPboxADMMsolver.cpp", "max_stars_repo_name": "xiaogaogaoxiao/Lpbox-ADMM", "max_stars_repo_head_hexsha": "8bce0b996a5c369b87ca5a6b0ff80aac36c6daa3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/LPboxADMMsolver.cpp", "max_issues_repo_name": "xiaogaogaoxiao/Lpbox-ADMM", "max_issues_repo_head_hexsha": "8bce0b996a5c369b87ca5a6b0ff80aac36c6daa3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/LPboxADMMsolver.cpp", "max_forks_repo_name": "xiaogaogaoxiao/Lpbox-ADMM", "max_forks_repo_head_hexsha": "8bce0b996a5c369b87ca5a6b0ff80aac36c6daa3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-16T04:13:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-06T13:14:11.000Z", "avg_line_length": 30.0465116279, "max_line_length": 126, "alphanum_fraction": 0.6639868171, "num_tokens": 12226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.6087689873094141}}
{"text": "#include \"rocket.h\"\n\n#include <armadillo>\n\nsf::Vector2f\ntrue_forward(\n    const sf::Vector2f &vec,\n    const float angle){\n\n  const auto rot = arma::mat{{std::cos(angle), -std::sin(angle)},\n                             {std::sin(angle), std::cos(angle)}};\n\n  const arma::vec res = rot * arma::vec{vec.x, vec.y};\n\n  return {float(res(0)), float(res(1))};\n\n}\n\nRocket::Rocket() {\n  this->setOrigin(75., 75.);\n  this->setPosition(900., 100);\n}\n\nbool\nRocket::accelerate(sf::Sound &engine_sound) {\n  if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {\n    const auto angle = this->getRotation() * arma::datum::pi / 180;\n    this->acceleration += this->thrust * true_forward(this->forward, angle);\n\n    if (engine_sound.getStatus() != sf::SoundSource::Playing) {\n      //engine_sound.play();\n    }\n\n    return true;\n  } else {\n    this->acceleration = {0., 10.};\n\n    if (engine_sound.getStatus() == sf::SoundSource::Playing) {\n      //engine_sound.pause();\n    }\n\n    return false;\n  }\n}\n\nbool\nRocket::turn(const float dt) {\n  bool turned = false;\n\n  if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {\n    this->rotation += -2.;\n    turned = true;\n  }\n\n  if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {\n    this->rotation += 2.;\n    turned = true;\n  }\n\n  this->rotate(this->rotation * dt);\n\n  return turned;\n}\n\nvoid\nRocket::update_velocity(const float dt){\n  this->velocity += dt * this->acceleration;\n}\n\nvoid\nRocket::update_position(const float dt) {\n  const auto position = this->getPosition();\n  this->setPosition(position + dt * this->velocity);\n\n}", "meta": {"hexsha": "5984231f062c30cb4cebfdeeb678e1a42864438c", "size": 1548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lander_game/rocket.cpp", "max_stars_repo_name": "Oliver-Feighan/NN_lander", "max_stars_repo_head_hexsha": "69421d53577aab705216eaa1d6a768359e0416de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lander_game/rocket.cpp", "max_issues_repo_name": "Oliver-Feighan/NN_lander", "max_issues_repo_head_hexsha": "69421d53577aab705216eaa1d6a768359e0416de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lander_game/rocket.cpp", "max_forks_repo_name": "Oliver-Feighan/NN_lander", "max_forks_repo_head_hexsha": "69421d53577aab705216eaa1d6a768359e0416de", "max_forks_repo_licenses": ["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.64, "max_line_length": 76, "alphanum_fraction": 0.6169250646, "num_tokens": 423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.6087324199422665}}
{"text": "#pragma once\n\n#include \"random_engine.hpp\"\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace cryptb\n{\n\tclass rsa\n\t{\n\t\t// Private key- for decrypting / digital signing\n\t\t// DON'T SHARE d WITH THE CLIENT!\n\t\t// Tends to be a number with around 2048 bits.\n\t\tboost::multiprecision::cpp_int d{ 0 };\n\n\t\t// It's completely safe to share e and N with the entire world.\n\t\t// In fact, you should.\n\n\t\t// Public key- for encrypting / verifying digital signature\n\t\t// Tends to be a very small number. Choosing the number 3 for example, is common.\n\t\tboost::multiprecision::cpp_int e{ 0 };\n\n\t\t// Public key- for everything. N is needed for all operations.\n\t\t// Tends to be a number with about 4096 bits.\n\t\tboost::multiprecision::cpp_int N{ 0 };\n\n\t\tstatic boost::multiprecision::cpp_int findd(const boost::multiprecision::cpp_int& PhiN, const boost::multiprecision::cpp_int& e);\n\n\tpublic:\n\t\trsa(const rsa&) = default;\n\t\trsa(rsa&&) = default;\n\t\trsa& operator=(const rsa&) = default;\n\t\trsa& operator=(rsa&&) = default;\n\n\t\t// Constructor for generating RSA public-private key pair using the given random engine.\n\t\t//\n\t\t// When \"num_bytes_in_prime_number\" == 128 that's 2048-bit RSA\n\t\t// Should take a second and a half (very expensive function, call on an asynchronous thread).\n\t\t//\n\t\trsa(random_engine& rand, const int num_bytes_in_prime_number = 128);\n\n\t\t// Constructor for loading RSA public-private key pairs from values\n\t\trsa(boost::multiprecision::cpp_int&& e, boost::multiprecision::cpp_int&& d, boost::multiprecision::cpp_int&& N) :\n\t\t\te(std::move(e)), d(std::move(d)), N(std::move(N)) {}\n\n\t\t// Private secret key, don't share.\n\t\tconst boost::multiprecision::cpp_int& get_d() const\n\t\t{\n\t\t\treturn this->d;\n\t\t}\n\n\t\t// Public key, no danger. Allowed to reveal to the entire world.\n\t\tconst boost::multiprecision::cpp_int& get_e() const\n\t\t{\n\t\t\treturn this->e;\n\t\t}\n\n\t\t// Public key, no danger. Allowed to reveal to the entire world.\n\t\tconst boost::multiprecision::cpp_int& get_N() const\n\t\t{\n\t\t\treturn this->N;\n\t\t}\n\t};\n}\n", "meta": {"hexsha": "bdf3d8d3052e2987b5fd5771a403b331473d1862", "size": 2006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rsa_cpp/rsa.hpp", "max_stars_repo_name": "NatanFreeman/rsa_cpp", "max_stars_repo_head_hexsha": "c703be3860d172201eab150826427467e6d0ee7f", "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": "rsa_cpp/rsa.hpp", "max_issues_repo_name": "NatanFreeman/rsa_cpp", "max_issues_repo_head_hexsha": "c703be3860d172201eab150826427467e6d0ee7f", "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": "rsa_cpp/rsa.hpp", "max_forks_repo_name": "NatanFreeman/rsa_cpp", "max_forks_repo_head_hexsha": "c703be3860d172201eab150826427467e6d0ee7f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.34375, "max_line_length": 131, "alphanum_fraction": 0.6969092722, "num_tokens": 564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6087267938415605}}
{"text": "#include <ql/quantlib.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing namespace QuantLib;\n\nint example01() {\n\n    try {\n\n        Date refDate(13, November, 2013);\n        Date settlDate = TARGET().advance(refDate, 2 * Days);\n        Settings::instance().evaluationDate() = refDate;\n\n        Handle<Quote> rateLevel(new SimpleQuote(0.03));\n        Handle<YieldTermStructure> yts(\n            new FlatForward(refDate, rateLevel, Actual365Fixed()));\n\n        boost::shared_ptr<IborIndex> iborIndex(new Euribor(6 * Months, yts));\n        boost::shared_ptr<SwapIndex> swapIndex(\n            new EuriborSwapIsdaFixA(10 * Years, yts));\n\n        iborIndex->addFixing(refDate, 0.0200);\n        swapIndex->addFixing(refDate, 0.0315);\n\n        // Handle<Quote> volatilityLevel(new SimpleQuote(0.30));\n        // Handle<SwaptionVolatilityStructure> swaptionVol(\n        //     new ConstantSwaptionVolatility(refDate, TARGET(), Following,\n        //                                    volatilityLevel,\n        // Actual365Fixed()));\n\n        Handle<SwaptionVolatilityStructure> swaptionVol(\n            new SingleSabrSwaptionVolatility(refDate, TARGET(), Following, 0.05,\n                                             0.80, -0.30, 0.20,\n                                             Actual365Fixed(), swapIndex));\n\n        // Real strike = 0.0001;\n        // while(strike < 1.0) {\n        //     std::cout << strike << \" \" <<\n        // swaptionVol->volatility(10.0,10.0,strike) << std::endl;\n        //     strike += 0.0010;\n        // }\n        // return 0;\n\n        Date termDate = TARGET().advance(settlDate, 10 * Years);\n\n        Schedule sched1(settlDate, termDate, 1 * Years, TARGET(),\n                        ModifiedFollowing, ModifiedFollowing,\n                        DateGeneration::Forward, false);\n        Schedule sched2(settlDate, termDate, 6 * Months, TARGET(),\n                        ModifiedFollowing, ModifiedFollowing,\n                        DateGeneration::Forward, false);\n\n        Real nominal = 100000.0;\n\n        boost::shared_ptr<FloatFloatSwap> cmsswap(\n            new FloatFloatSwap( // CMS Swap\n                VanillaSwap::Payer, nominal, nominal, sched1, swapIndex,\n                Thirty360(), sched2, iborIndex, Actual360(), false, false, 1.0,\n                0.00, Null<Real>(), Null<Real>(), 1.0, 0.00267294));\n\n        // boost::shared_ptr<FloatFloatSwap> cmsswap(new FloatFloatSwap(  //\n        // Reversed Floored CMS Swap\n        //     VanillaSwap::Payer, nominal, nominal, sched1, swapIndex,\n        //     Thirty360(), sched2, iborIndex, Actual360(),\n        //     false,false,-1.0,0.03,Null<Real>(),0.0,1.0,0.0));\n\n        // boost::shared_ptr<FloatFloatSwap> cmsswap(new FloatFloatSwap( // fix\n        // float swap as FloatFloatSwap instrument\n        //     VanillaSwap::Payer, nominal, nominal, sched1, swapIndex,\n        //     Thirty360(), sched2, iborIndex, Actual360(),\n        //     false,false,0.0,0.05,Null<Real>(),Null<Real>(),1.0,0.0));\n\n        std::vector<Date> exerciseDates;\n        std::vector<Date> sigmaSteps;\n        std::vector<Real> sigma;\n\n        sigma.push_back(0.01);\n        for (Size i = 1; i < sched1.size() - 1; i++) {\n            exerciseDates.push_back(swapIndex->fixingDate(sched1[i]));\n            sigmaSteps.push_back(exerciseDates.back());\n            sigma.push_back(0.01);\n        }\n\n        // double v[] =\n        // {0.01,0.0115446,0.0111677,0.0113092,0.0112404,0.0111856,0.0111218,0.0110547,0.0112791,0.00945792};\n        // sigma = std::vector<Real>(v,v+10);\n\n        // boost::shared_ptr<FloatFloatSwap> underlying(new FloatFloatSwap(\n        //     VanillaSwap::Receiver, nominal, nominal, sched1, swapIndex,\n        //     Thirty360(), sched2, iborIndex, Actual360(),\n        //     false,false,1.0,0.0,Null<Real>(),Null<Real>(),1.0,0.00267294));\n\n        boost::shared_ptr<Exercise> exercise(\n            new BermudanExercise(exerciseDates));\n        boost::shared_ptr<FloatFloatSwaption> callRight(\n            new FloatFloatSwaption(cmsswap, exercise));\n\n        std::vector<Date> cmsFixingDates(exerciseDates);\n        std::vector<Period> cmsTenors(exerciseDates.size(), 10 * Years);\n\n        Handle<Quote> reversionLevel(new SimpleQuote(0.02));\n\n        boost::shared_ptr<NumericHaganPricer> haganPricer(\n            new NumericHaganPricer(swaptionVol,\n                                   GFunctionFactory::NonParallelShifts,\n                                   reversionLevel));\n        setCouponPricer(cmsswap->leg(0), haganPricer);\n\n        // hull white model (change the model->calibrate call below)\n        std::vector<Date> sigmaSteps2(sigmaSteps.begin(), sigmaSteps.end() - 1);\n        std::vector<Real> sigma2(sigma.begin(), sigma.end() - 1);\n        // boost::shared_ptr<Gsr> model(new\n        // Gsr(yts,sigmaSteps2,sigma2,reversionLevel->value()));\n        boost::shared_ptr<Gaussian1dModel> model2(\n            new Gsr(yts, sigmaSteps2, sigma2, reversionLevel->value()));\n\n        Handle<SwaptionVolatilityStructure> hwVol(\n            new Gaussian1dSwaptionVolatility(model2, swapIndex));\n        Real moneyIn[] = { 0.20, 0.50, 0.75, 1.0, 1.5, 2.0, 5.0, 10.0 };\n        std::vector<Real> money(moneyIn, moneyIn + 8);\n\n        // markov model (change the model->calibrate call below)\n        // boost::math::ntl::RR::SetPrecision(113);\n        boost::shared_ptr<MarkovFunctional> model(new MarkovFunctional(\n            yts, reversionLevel->value(), sigmaSteps, sigma, swaptionVol,\n            cmsFixingDates, cmsTenors,\n            swapIndex // set vol structure for mf here\n            /*,MarkovFunctional::ModelSettings().withAdjustments(\n                MarkovFunctional::ModelSettings::SabrSmile |\n                MarkovFunctional::ModelSettings::\n                    SmileExponentialExtrapolation)\n                    .withSmileMoneynessCheckpoints(money)*/));\n\n        boost::shared_ptr<Gaussian1dFloatFloatSwaptionEngine> floatEngine(\n            new Gaussian1dFloatFloatSwaptionEngine(model));\n\n        callRight->setPricingEngine(floatEngine);\n\n        std::cout << \"determine cal basket\" << std::endl;\n\n        boost::shared_ptr<Gaussian1dSwaptionEngine> stdEngine(\n            new Gaussian1dSwaptionEngine(model));\n\n        boost::shared_ptr<SwapIndex> swapBase(\n            new EuriborSwapIsdaFixA(30 * Years, yts));\n\n        LevenbergMarquardt opt;\n        EndCriteria ec(2000, 500, 1E-8, 1E-8, 1E-8);\n\n        Size iteration = 0;\n        while (iteration < 1) { // set number of iterations here ...\n            std::vector<boost::shared_ptr<CalibrationHelper> > basket =\n                callRight->calibrationBasket(\n                    swapBase, *swaptionVol, // set vol structure for basket here\n                    // BasketGeneratingEngine::Naive\n                    BasketGeneratingEngine::MaturityStrikeByDeltaGamma);\n\n            for (Size i = 0; i < basket.size(); i++)\n                basket[i]->setPricingEngine(stdEngine);\n            model->calibrate(basket, opt, ec); // for markov\n            // model->calibrate(basket, opt, ec, Constraint(),\n            // std::vector<Real>(), model->FixedReversions()); // for gsr\n\n            std::cout << \"option date & maturity date & nominal & strike & \"\n                         \"model vol \\\\\\\\\" << std::endl;\n            for (Size i = 0; i < basket.size(); i++) {\n                boost::shared_ptr<SwaptionHelper> h =\n                    boost::dynamic_pointer_cast<SwaptionHelper>(basket[i]);\n                std::cout << exerciseDates[i] << \" & \"\n                          << h->underlyingSwap()->fixedSchedule().dates().back()\n                          << \" & \" << h->underlyingSwap()->nominal() << \" & \"\n                          << h->underlyingSwap()->fixedRate() << \" & \"\n                          << model->volatility()[i] << \" \\\\\\\\\" << std::endl;\n            }\n            std::cout << model->volatility().back() << std::endl;\n            iteration++;\n        }\n\n        Real analyticSwapNpv = CashFlows::npv(cmsswap->leg(1), **yts, false) -\n                               CashFlows::npv(cmsswap->leg(0), **yts, false);\n        Real callRightNpv = callRight->NPV();\n        Real firstCouponNpv = -cmsswap->leg(0)[0]->amount() *\n                                  yts->discount(cmsswap->leg(0)[0]->date()) +\n                              cmsswap->leg(1)[0]->amount() *\n                                  yts->discount(cmsswap->leg(1)[0]->date());\n        Real underlyingNpv =\n            callRight->result<Real>(\"underlyingValue\") + firstCouponNpv;\n\n        std::cout << \"Swap Npv (Hagan)     & \" << analyticSwapNpv << \"\\\\\\\\\"\n                  << std::endl;\n        std::cout << \"Call Right Npv (MF)  & \" << callRightNpv << \"\\\\\\\\\"\n                  << std::endl;\n        std::cout << \"Underlying Npv (MF)  & \" << underlyingNpv << \"\\\\\\\\\"\n                  << std::endl;\n        std::cout << \"fair margin swap & \"\n                  << -analyticSwapNpv / CashFlows::bps(cmsswap->leg(1), **yts,\n                                                       false) << std::endl;\n\n        // std::cout << \"Model trace : \" << std::endl << model->modelOutputs()\n        // << std::endl;\n\n        return 0;\n    }\n    catch (std::exception &e) {\n        std::cerr << e.what() << std::endl;\n        return 1;\n    }\n    catch (...) {\n        std::cerr << \"unknown error\" << std::endl;\n        return 1;\n    }\n}\n\nint example02() {\n\n    try {\n\n        Date refDate(13, November, 2013);\n        Date settlDate = TARGET().advance(refDate, 2 * Days);\n        Settings::instance().evaluationDate() = refDate;\n\n        Handle<Quote> rateLevel(new SimpleQuote(0.03));\n        Handle<YieldTermStructure> yts(\n            new FlatForward(refDate, rateLevel, Actual365Fixed()));\n\n        boost::shared_ptr<IborIndex> iborIndex(new Euribor(6 * Months, yts));\n        boost::shared_ptr<SwapIndex> swapIndex(\n            new EuriborSwapIsdaFixA(10 * Years, yts));\n\n        iborIndex->addFixing(refDate, 0.0200);\n        swapIndex->addFixing(refDate, 0.0315);\n\n        // Handle<Quote> volatilityLevel(new SimpleQuote(0.20)); // vol here !\n        // Handle<SwaptionVolatilityStructure> swaptionVol(\n        //     new ConstantSwaptionVolatility(refDate, TARGET(), Following,\n        //                                    volatilityLevel, Actual365Fixed()));\n\n        Handle<SwaptionVolatilityStructure> swaptionVol(\n            new SingleSabrSwaptionVolatility(refDate, TARGET(), Following,\n        0.10,\n                                             0.80, -0.30, 0.40,\n                                             Actual365Fixed(), swapIndex));\n\n        // Real strike = 0.0001;\n        // while(strike < 0.50) {\n        //     std::cout << strike << \" \" <<\n        // swaptionVol->volatility(10.0,10.0,strike) << std::endl;\n        //     strike += 0.0050;\n        // }\n        // return 0;\n\n        Date termDate = TARGET().advance(settlDate, 10 * Years);\n\n        Schedule sched1(settlDate, termDate, 1 * Years, TARGET(),\n                        ModifiedFollowing, ModifiedFollowing,\n                        DateGeneration::Forward, false);\n        Schedule sched2(settlDate, termDate, 6 * Months, TARGET(),\n                        ModifiedFollowing, ModifiedFollowing,\n                        DateGeneration::Forward, false);\n\n        Real nominal = 100000.0;\n\n        boost::shared_ptr<FloatFloatSwap> cmsswap(\n            new FloatFloatSwap( // CMS Swap\n                VanillaSwap::Payer, nominal, nominal, sched1, swapIndex,\n                Thirty360(), sched2, iborIndex, Actual360(), false, false, 1.0,\n                0.00, Null<Real>(), Null<Real>(), 1.0, 0.0));\n\n        Handle<Quote> reversionLevel(new SimpleQuote(0.01)); // reversion here !\n\n        boost::shared_ptr<NumericHaganPricer> haganPricerN(\n            new NumericHaganPricer(swaptionVol,\n                                   GFunctionFactory::Standard,\n                                   reversionLevel));\n        boost::shared_ptr<AnalyticHaganPricer> haganPricerA(\n            new AnalyticHaganPricer(swaptionVol,\n                                    GFunctionFactory::Standard,\n                                    reversionLevel));\n\n        // auto integrator =\n        // boost::make_shared<GaussLobattoIntegral>(1000,1E-4);\n\n        boost::shared_ptr<LinearTsrPricer> tsrPricer(new LinearTsrPricer(\n            swaptionVol, reversionLevel, Handle<YieldTermStructure>(),\n            LinearTsrPricer::Settings().withRateBound(0.0, 1.0)\n            //.withVegaRatio(0.01)\n            ));\n\n        boost::shared_ptr<CmsReplicationPricer> replPricer(\n            new CmsReplicationPricer(swaptionVol, reversionLevel));\n\n        Real strike = 0.0001;\n        while (strike <= 0.1000) {\n\n            auto tmpCap = boost::shared_ptr<CappedFlooredCoupon>(new CappedFlooredCmsCoupon(\n                Date(13, November, 2023), 100000.0, Date(13, November, 2022),\n                Date(13, November, 2023), 2, swapIndex, 1.0, 0.0, strike,\n                Null<Rate>(), Date(), Date(), DayCounter(), false));\n            auto cap = boost::make_shared<StrippedCappedFlooredCoupon>(tmpCap);\n            auto tmpFloor = boost::shared_ptr<CappedFlooredCoupon>(\n                new CappedFlooredCmsCoupon(\n                    Date(13, November, 2023), 100000.0,\n                    Date(13, November, 2022), Date(13, November, 2023), 2,\n                    swapIndex, 1.0, 0.0, Null<Real>(), strike, Date(), Date(),\n                    DayCounter(), false));\n            auto floor = boost::make_shared<StrippedCappedFlooredCoupon>(tmpFloor);\n            auto swaplet = boost::shared_ptr<CappedFlooredCmsCoupon>(\n                new CappedFlooredCmsCoupon(\n                    Date(13, November, 2023), 100000.0,\n                    Date(13, November, 2022), Date(13, November, 2023), 2,\n                    swapIndex, 1.0, 0.0, Null<Rate>(), Null<Rate>(), Date(),\n                    Date(), DayCounter(), false));\n\n            cap->setPricer(tsrPricer);\n            floor->setPricer(tsrPricer);\n            swaplet->setPricer(tsrPricer);\n            Real cap1 = cap->adjustedFixing();\n            Real floor1 = floor->adjustedFixing();\n            Real swaplet1 = swaplet->adjustedFixing();\n\n            // cap->setPricer(haganPricerN);\n            // floor->setPricer(haganPricerN);\n            // swaplet->setPricer(haganPricerN);\n            // Real cap2 = cap->adjustedFixing();\n            // Real floor2 = floor->adjustedFixing();\n            // Real swaplet2 = swaplet->adjustedFixing();\n            // cap->setPricer(replPricer);\n            // floor->setPricer(replPricer);\n            // swaplet->setPricer(replPricer);\n            // Real cap2 = 0.0;//cap->adjustedFixing();\n            // Real floor2 = 0.0;//floor->adjustedFixing();\n            // Real swaplet2 = 0.0;//swaplet->adjustedFixing();\n\n            // cap->setPricer(tsrPricer);\n            // floor->setPricer(tsrPricer);\n            // swaplet->setPricer(tsrPricer);\n            // Real cap3 = cap->adjustedFixing();\n            // Real floor3 = floor->adjustedFixing();\n            // Real swaplet3 = swaplet->adjustedFixing();\n\n            // std::cout << strike << \" \" << cap1 << \" \" \n            //           << \" \" << floor1 << \" \"\n            //           << (cap1 - floor1 - (swaplet1 - strike)) << std::endl;\n\n            strike += 0.0001;\n        }\n\n        return 0;\n    }\n    catch (std::exception &e) {\n        std::cerr << e.what() << std::endl;\n        return 1;\n    }\n    catch (...) {\n        std::cerr << \"unknown error\" << std::endl;\n        return 1;\n    }\n}\n\nint example03() {\n\n    try {\n\n        Date refDate(13, November, 2013);\n        Date settlDate = TARGET().advance(refDate, 2 * Days);\n        Settings::instance().evaluationDate() = refDate;\n\n        Handle<Quote> rateLevel1(new SimpleQuote(0.0350));\n        Handle<Quote> rateLevel2(new SimpleQuote(0.0300));\n        Handle<YieldTermStructure> yts1(\n            new FlatForward(refDate, rateLevel1, Actual365Fixed()));\n        Handle<YieldTermStructure> yts2(\n            new FlatForward(refDate, rateLevel2, Actual365Fixed()));\n\n        boost::shared_ptr<IborIndex> iborIndex(new Euribor(6 * Months, yts1));\n        boost::shared_ptr<SwapIndex> swapIndex1(\n            new EuriborSwapIsdaFixA(10 * Years, yts1));\n        boost::shared_ptr<SwapIndex> swapIndex2(\n            new EuriborSwapIsdaFixA(2 * Years, yts2));\n\n        boost::shared_ptr<SwapSpreadIndex> swapSpreadIndex(\n            new SwapSpreadIndex(\"cms10_2\", swapIndex1, swapIndex2));\n\n        Handle<Quote> volatilityLevel(new SimpleQuote(0.40)); // vol here !\n        Handle<SwaptionVolatilityStructure> swaptionVol(\n            new ConstantSwaptionVolatility(refDate, TARGET(), Following,\n                                           volatilityLevel, Actual365Fixed()));\n\n        // Handle<SwaptionVolatilityStructure> swaptionVol(\n        //     new SingleSabrSwaptionVolatility(refDate, TARGET(), Following,\n        // 0.15,\n        //                                      0.80, -0.30, 0.20,\n        //                                      Actual365Fixed(), swapIndex));\n\n        Handle<Quote> reversionLevel(new SimpleQuote(0.00)); // reversion here !\n\n        boost::shared_ptr<LinearTsrPricer> tsrPricer(new LinearTsrPricer(\n            swaptionVol, reversionLevel, Handle<YieldTermStructure>(),\n            LinearTsrPricer::Settings().withRateBound(0.0, 1.0)\n            //.withVegaRatio(0.01)\n            ));\n\n        Handle<Quote> correlation(new SimpleQuote(0.20)); // correlation here\n\n        boost::shared_ptr<CappedFlooredCoupon> tmpSpreadCoupon(\n            new CappedFlooredCmsSpreadCoupon(\n                Date(13, November, 2034), 1.0, Date(13, November, 2033),\n                Date(13, November, 2034), 2, swapSpreadIndex, 1.0, 0.0,\n                Null<Real>(), 0.0050, Date(), Date(), DayCounter(), false));\n\n        boost::shared_ptr<StrippedCappedFlooredCoupon> spreadCoupon =\n            boost::make_shared<StrippedCappedFlooredCoupon>(tmpSpreadCoupon);\n\n        // boost::shared_ptr<CmsSpreadCoupon> spreadCoupon(new CmsSpreadCoupon(\n        //     Date(13, November, 2024), 1.0, Date(13, November, 2023),\n        //     Date(13, November, 2024), 2, swapSpreadIndex, 1.0, 0.0,\n        //     Date(), Date(), DayCounter(),false));\n\n        std::cout << \"integration_points;rate\" << std::setprecision(16)\n                  << std::endl;\n        for (Size i = 4; i < 64; i++) {\n\n            boost::shared_ptr<LognormalCmsSpreadPricer> spreadPricer(\n                new LognormalCmsSpreadPricer(tsrPricer, correlation,\n                                             Handle<YieldTermStructure>(), i));\n\n            spreadCoupon->setPricer(spreadPricer);\n\n            std::cout << i << \";\" << spreadCoupon->rate() << std::endl;\n        }\n\n        return 0;\n    }\n    catch (std::exception &e) {\n        std::cerr << e.what() << std::endl;\n        return 1;\n    }\n    catch (...) {\n        std::cerr << \"unknown error\" << std::endl;\n        return 1;\n    }\n}\n\nint example04() {\n\n    try {\n\n        Date refDate(13, November, 2013);\n        Date settlDate = TARGET().advance(refDate, 2 * Days);\n        Settings::instance().evaluationDate() = refDate;\n\n        Handle<Quote> rateLevel1(new SimpleQuote(0.0350));\n        Handle<YieldTermStructure> yts1(\n            new FlatForward(refDate, rateLevel1, Actual365Fixed()));\n        Handle<Quote> rateLevel2(new SimpleQuote(0.0300));\n        Handle<YieldTermStructure> yts2(\n            new FlatForward(refDate, rateLevel2, Actual365Fixed()));\n\n        boost::shared_ptr<IborIndex> iborIndex(new Euribor(6 * Months, yts1));\n        boost::shared_ptr<SwapIndex> swapIndex1(\n            new EuriborSwapIsdaFixA(10 * Years, yts1));\n        boost::shared_ptr<SwapIndex> swapIndex2(\n            new EuriborSwapIsdaFixA(2 * Years, yts2));\n\n        boost::shared_ptr<SwapSpreadIndex> swapSpreadIndex(\n            new SwapSpreadIndex(\"cms10_2\", swapIndex1, swapIndex2));\n\n        Handle<Quote> volatilityLevel(new SimpleQuote(0.40)); // vol here !\n        Handle<SwaptionVolatilityStructure> swaptionVol(\n            new ConstantSwaptionVolatility(refDate, TARGET(), Following,\n                                           volatilityLevel, Actual365Fixed()));\n\n        Handle<Quote> reversionLevel(new SimpleQuote(0.00)); // reversion here !\n\n        Schedule sched(settlDate, settlDate + 10 * Years, 1 * Years, TARGET(),\n                       ModifiedFollowing, ModifiedFollowing,\n                       DateGeneration::Backward, false);\n\n        boost::shared_ptr<FloatFloatSwap> underlying(new FloatFloatSwap(VanillaSwap::Payer,\n                                                                        100.0,100.0,\n                                                                        sched,iborIndex,Actual360(),\n                                                                        sched,swapSpreadIndex,Thirty360(),\n                                                                        false,\n                                                                        false));\n\n        std::vector<Date> callDates = sched.dates();\n\n        std::cout << \"call dates:\" << std::endl;\n        for(Size i=0;i<callDates.size();i++)\n            std::cout << callDates[i] << std::endl;\n\n\n        boost::shared_ptr<Exercise> exercise = boost::make_shared<BermudanExercise>(callDates);\n\n        boost::shared_ptr<FloatFloatSwaption> swaption = boost::make_shared<FloatFloatSwaption>(underlying,exercise);\n\n        std::vector<Date> volStepDates;\n        std::vector<Real> vols(1,0.01);\n\n        boost::shared_ptr<Gaussian1dModel> model = boost::make_shared<Gsr>(yts1,volStepDates,\n                                                                           vols,0.01);\n\n        boost::shared_ptr<Gaussian1dFloatFloatSwaptionEngine> engine =\n            boost::make_shared<Gaussian1dFloatFloatSwaptionEngine>(\n                model, 64, 7.0, true, false, Handle<Quote>(),\n                Handle<YieldTermStructure>(), false,\n                Gaussian1dFloatFloatSwaptionEngine::Naive);\n\n        swaption->setPricingEngine(engine);\n\n        std::cout << \"swaption npv = \" << swaption->NPV() << std::endl;\n        \n        std::vector<Real> probs = swaption->result<std::vector<Real> >(\"probabilities\");        \n        for(Size i=0;i<probs.size();i++) {\n            std::cout << i << \" => \" << probs[i] << std::endl;\n        }\n\n    }\n    catch (std::exception &e) {\n        std::cerr << e.what() << std::endl;\n        return 1;\n    }\n    catch (...) {\n        std::cerr << \"unknown error\" << std::endl;\n        return 1;\n    }\n\n    return 0;\n\n}\n\n\nint main(int, char * []) {\n\n    return example02();\n    \n}\n", "meta": {"hexsha": "4d7c3407e31729ad40b0dac4a581e66814fce521", "size": 22675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/CmsSwaption/CmsSwaption.cpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "Examples/CmsSwaption/CmsSwaption.cpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "Examples/CmsSwaption/CmsSwaption.cpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 42.0686456401, "max_line_length": 117, "alphanum_fraction": 0.5506945976, "num_tokens": 5777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.6791787056691697, "lm_q1q2_score": 0.60871485132334}}
{"text": "#define BOOST_TEST_MODULE \"test_collision\"\n#include <boost/test/included/unit_test.hpp>\n#include <afmize/collision.hpp>\n\nBOOST_AUTO_TEST_CASE(collision_sphere_sphere)\n{\n    using sphere = afmize::sphere<double>;\n    using point  = mave::vector<double, 3>;\n\n    {\n        sphere probe {1.0, point{0.0, 0.0, 10.0}};\n        sphere target{1.0, point{0.0, 0.0,  0.0}};\n\n        const auto t = afmize::collision_z(probe, target);\n        BOOST_TEST(!std::isnan(t));\n        BOOST_TEST(t == -8.0, boost::test_tools::tolerance(1e-6));\n    }\n    {\n        sphere probe {1.0, point{0.0, 0.0, 10.0}};\n        sphere target{1.0, point{0.0, 0.0, 20.0}};\n\n        const auto t = afmize::collision_z(probe, target);\n        BOOST_TEST(!std::isnan(t));\n        BOOST_TEST(t == 8.0, boost::test_tools::tolerance(1e-6));\n    }\n\n    {\n        sphere probe {1.0, point{0.0, 0.0, 10.0}};\n        sphere target{1.0, point{1.0, 1.0,  0.0}};\n        const double expect = std::sqrt(2.0) - 10.0;\n\n        const auto t = afmize::collision_z(probe, target);\n\n        BOOST_TEST(!std::isnan(t));\n        BOOST_TEST(t == expect, boost::test_tools::tolerance(1e-6));\n    }\n    {\n        sphere probe {1.0, point{0.0, 0.0, 10.0}};\n        sphere target{1.0, point{1.0, 1.0, 20.0}};\n        const double expect = 10.0 - std::sqrt(2.0);\n\n        const auto t = afmize::collision_z(probe, target);\n        BOOST_TEST(!std::isnan(t));\n        BOOST_TEST(t == expect, boost::test_tools::tolerance(1e-6));\n    }\n\n    {\n        sphere probe {1.0, point{ 0.0,  0.0, 10.0}};\n        sphere target{1.0, point{10.0, 10.0,  0.0}};\n\n        const auto t = afmize::collision_z(probe, target);\n        BOOST_TEST(std::isnan(t));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(collision_frustum_sphere)\n{\n    using sphere  = afmize::sphere<double>;\n    using frustum = afmize::circular_frustum<double>;\n    using point   = mave::vector<double, 3>;\n\n    {\n        frustum probe {0.0, 1.0, point{0.0, 0.0, 10.0}}; // just a cylinder\n        sphere  target{     1.0, point{0.0, 0.0,  0.0}};\n\n        const auto t = afmize::collision_z(probe, target);\n        BOOST_TEST(!std::isnan(t));\n        BOOST_TEST(t == -9.0, boost::test_tools::tolerance(1e-6));\n    }\n    {\n        frustum probe {0.0, 1.0, point{0.0, 0.0, 10.0}};\n        sphere  target{     1.0, point{0.0, 0.0, 20.0}};\n\n        const auto t = afmize::collision_z(probe, target);\n        BOOST_TEST(!std::isnan(t));\n        BOOST_TEST(t == 11.0, boost::test_tools::tolerance(1e-6));\n    }\n\n    {\n        frustum probe {0.0, 1.0, point{0.0, 0.0, 10.0}};\n        sphere  target{     1.0, point{1.5, 0.0,  0.0}};\n        const double expect = std::sqrt(3.0) * 0.5 - 10.0;\n\n        const auto t = afmize::collision_z(probe, target);\n\n        BOOST_TEST(!std::isnan(t));\n        BOOST_TEST(t == expect, boost::test_tools::tolerance(1e-6));\n    }\n    {\n        frustum probe {0.0, 1.0, point{0.0, 0.0, 10.0}};\n        sphere  target{     1.0, point{0.0, 1.5,  0.0}};\n        const double expect = std::sqrt(3.0) * 0.5 - 10.0;\n\n        const auto t = afmize::collision_z(probe, target);\n\n        BOOST_TEST(!std::isnan(t));\n        BOOST_TEST(t == expect, boost::test_tools::tolerance(1e-6));\n    }\n\n    {\n        sphere probe {1.0, point{ 0.0,  0.0, 10.0}};\n        sphere target{1.0, point{10.0, 10.0,  0.0}};\n\n        const auto t = afmize::collision_z(probe, target);\n        BOOST_TEST(std::isnan(t));\n    }\n}\n", "meta": {"hexsha": "b09a7fc1c07c07550c34250c2d3a0a6a58c74b48", "size": 3402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_collision.cpp", "max_stars_repo_name": "0ncorhynchus/afmize", "max_stars_repo_head_hexsha": "d41ec2fa985fdd1fdc5f25f2dafbbef7eead041d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-09-28T08:43:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-14T05:30:39.000Z", "max_issues_repo_path": "test/test_collision.cpp", "max_issues_repo_name": "0ncorhynchus/afmize", "max_issues_repo_head_hexsha": "d41ec2fa985fdd1fdc5f25f2dafbbef7eead041d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-04-23T14:29:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T04:07:06.000Z", "max_forks_repo_path": "test/test_collision.cpp", "max_forks_repo_name": "0ncorhynchus/afmize", "max_forks_repo_head_hexsha": "d41ec2fa985fdd1fdc5f25f2dafbbef7eead041d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-04-23T07:25:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-12T08:17:42.000Z", "avg_line_length": 31.5, "max_line_length": 75, "alphanum_fraction": 0.557319224, "num_tokens": 1210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6087148359189956}}
{"text": "#ifndef ALGORITHM_HPP\n#define ALGORITHM_HPP\n\n#include <Eigen/Dense>\n\nclass Ellipse2D;\nclass Circle3D;\n\n/**********************************************************************************/\n\nvoid estimate_3D_circles_under_perspective_transformation_method_1(\n        const Eigen::Matrix4d& pMat,\n        const Ellipse2D& ellipse,\n        Circle3D* circles);\n\nbool check_eigenvalue_constraints(const Eigen::Vector3d& eigenvalues);\n\n/**********************************************************************************/\n\nvoid estimate_3D_circles_under_perspective_transformation_method_2(\n        const Ellipse2D& ellipse,\n        Circle3D* circles,\n        double near);\n\nvoid construct_change_of_basis_matrix(Eigen::Matrix3d& mat, const Eigen::Vector3d& vec2);\n\n/**********************************************************************************/\n\nvoid estimate_3D_circles_under_perspective_transformation_method_3(\n        const Eigen::Matrix3d& mat,\n        const Ellipse2D& ellipse,\n        Circle3D* circles);\n\n/**********************************************************************************/\n\nint estimate_3D_circles_under_perspective_transformation_method_4(\n        const Ellipse2D& ellipse,\n        Circle3D* circles,\n        double near);\n\n/**********************************************************************************/\n#endif // ALGORITHM_HPP\n", "meta": {"hexsha": "a2621bb2760ff57c0d576f5423f94480d875f4af", "size": 1357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "algorithm/algorithm.hpp", "max_stars_repo_name": "myirci/3d_circle_estimation", "max_stars_repo_head_hexsha": "7161005ab14d510503310e0bb028fea5ad2a1389", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-07-16T18:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T01:25:54.000Z", "max_issues_repo_path": "algorithm/algorithm.hpp", "max_issues_repo_name": "myirci/3d_circle_estimation", "max_issues_repo_head_hexsha": "7161005ab14d510503310e0bb028fea5ad2a1389", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algorithm/algorithm.hpp", "max_forks_repo_name": "myirci/3d_circle_estimation", "max_forks_repo_head_hexsha": "7161005ab14d510503310e0bb028fea5ad2a1389", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-08T13:49:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T13:49:32.000Z", "avg_line_length": 31.5581395349, "max_line_length": 89, "alphanum_fraction": 0.5165806927, "num_tokens": 241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907010924213, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.6086188263685252}}
{"text": "\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <csim/init_ops.hpp>\n#include <csim/memory_ops.hpp>\n#include <csim/stat_ops.hpp>\n#include <csim/update_ops.hpp>\n#include <csim/update_ops_cpp.hpp>\n#include <string>\n\n#include \"../util/util.hpp\"\n\nvoid test_single_qubit_named_gate(UINT n, std::string name,\n    std::function<void(UINT, CTYPE*, ITYPE)> func, Eigen::MatrixXcd mat) {\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 2;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state_with_seed(state, dim, 0);\n\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n    std::vector<UINT> indices;\n    for (UINT i = 0; i < n; ++i) indices.push_back(i);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        for (UINT i = 0; i < n; ++i) {\n            UINT target = indices[i];\n            func(target, state, dim);\n            test_state =\n                get_expanded_eigen_matrix_with_identity(target, mat, n) *\n                test_state;\n            state_equal(state, test_state, dim, name);\n        }\n        std::random_shuffle(indices.begin(), indices.end());\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, XGate) {\n    Eigen::MatrixXcd mat(2, 2);\n    mat << 0, 1, 1, 0;\n    test_single_qubit_named_gate(6, \"XGate\", X_gate, mat);\n    test_single_qubit_named_gate(6, \"XGate\", X_gate_single_unroll, mat);\n#ifdef _OPENMP\n    test_single_qubit_named_gate(6, \"XGate\", X_gate_parallel_unroll, mat);\n#endif\n#ifdef _USE_SIMD\n    test_single_qubit_named_gate(6, \"XGate\", X_gate_single_simd, mat);\n#ifdef _OPENMP\n    test_single_qubit_named_gate(6, \"XGate\", X_gate_parallel_simd, mat);\n#endif\n#endif\n}\nTEST(UpdateTest, YGate) {\n    Eigen::MatrixXcd mat(2, 2);\n    mat << 0, -1.i, 1.i, 0;\n    test_single_qubit_named_gate(6, \"YGate\", Y_gate, mat);\n    test_single_qubit_named_gate(6, \"YGate\", Y_gate_single_unroll, mat);\n#ifdef _OPENMP\n    test_single_qubit_named_gate(6, \"YGate\", Y_gate_parallel_unroll, mat);\n#endif\n#ifdef _USE_SIMD\n    test_single_qubit_named_gate(6, \"YGate\", Y_gate_single_simd, mat);\n#ifdef _OPENMP\n    test_single_qubit_named_gate(6, \"YGate\", Y_gate_parallel_simd, mat);\n#endif\n#endif\n}\nTEST(UpdateTest, ZGate) {\n    const UINT n = 3;\n    Eigen::MatrixXcd mat(2, 2);\n    mat << 1, 0, 0, -1;\n    test_single_qubit_named_gate(6, \"ZGate\", Z_gate, mat);\n    test_single_qubit_named_gate(6, \"ZGate\", Z_gate_single_unroll, mat);\n#ifdef _OPENMP\n    test_single_qubit_named_gate(6, \"ZGate\", Z_gate_parallel_unroll, mat);\n#endif\n#ifdef _USE_SIMD\n    test_single_qubit_named_gate(6, \"ZGate\", Z_gate_single_simd, mat);\n#ifdef _OPENMP\n    test_single_qubit_named_gate(6, \"ZGate\", Z_gate_parallel_simd, mat);\n#endif\n#endif\n}\nTEST(UpdateTest, HGate) {\n    const UINT n = 3;\n    Eigen::MatrixXcd mat(2, 2);\n    mat << 1, 1, 1, -1;\n    mat /= sqrt(2.);\n    test_single_qubit_named_gate(n, \"HGate\", H_gate, mat);\n    test_single_qubit_named_gate(6, \"HGate\", H_gate_single_unroll, mat);\n#ifdef _OPENMP\n    test_single_qubit_named_gate(6, \"HGate\", H_gate_parallel_unroll, mat);\n#endif\n#ifdef _USE_SIMD\n    test_single_qubit_named_gate(6, \"HGate\", H_gate_single_simd, mat);\n#ifdef _OPENMP\n    test_single_qubit_named_gate(6, \"HGate\", H_gate_parallel_simd, mat);\n#endif\n#endif\n}\n\nTEST(UpdateTest, SGate) {\n    const UINT n = 3;\n    Eigen::MatrixXcd mat(2, 2);\n    mat << 1, 0, 0, 1.i;\n    test_single_qubit_named_gate(n, \"SGate\", S_gate, mat);\n    test_single_qubit_named_gate(n, \"SGate\", Sdag_gate, mat.adjoint());\n}\n\nTEST(UpdateTest, TGate) {\n    const UINT n = 3;\n    Eigen::MatrixXcd mat(2, 2);\n    mat << 1, 0, 0, (1. + 1.i) / sqrt(2.);\n    test_single_qubit_named_gate(n, \"TGate\", T_gate, mat);\n    test_single_qubit_named_gate(n, \"TGate\", Tdag_gate, mat.adjoint());\n}\n\nTEST(UpdateTest, sqrtXGate) {\n    const UINT n = 3;\n    Eigen::MatrixXcd mat(2, 2);\n    mat << 0.5 + 0.5i, 0.5 - 0.5i, 0.5 - 0.5i, 0.5 + 0.5i;\n    test_single_qubit_named_gate(n, \"SqrtXGate\", sqrtX_gate, mat);\n    test_single_qubit_named_gate(\n        n, \"SqrtXdagGate\", sqrtXdag_gate, mat.adjoint());\n}\n\nTEST(UpdateTest, sqrtYGate) {\n    const UINT n = 3;\n    Eigen::MatrixXcd mat(2, 2);\n    mat << 0.5 + 0.5i, -0.5 - 0.5i, 0.5 + 0.5i, 0.5 + 0.5i;\n    test_single_qubit_named_gate(n, \"SqrtYGate\", sqrtY_gate, mat);\n    test_single_qubit_named_gate(\n        n, \"SqrtYdagGate\", sqrtYdag_gate, mat.adjoint());\n}\n\nvoid test_projection_gate(std::function<void(UINT, CTYPE*, ITYPE)> func,\n    std::function<double(UINT, CTYPE*, ITYPE)> prob_func,\n    Eigen::MatrixXcd mat) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n    const double eps = 1e-14;\n    UINT target;\n    double prob;\n\n    auto state = allocate_quantum_state(dim);\n    std::vector<UINT> indices;\n    for (UINT i = 0; i < n; ++i) indices.push_back(i);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        for (int i = 0; i < n; ++i) {\n            target = indices[i];\n            initialize_Haar_random_state(state, dim);\n            Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n            for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n            // Z-projection operators\n            prob = prob_func(target, state, dim);\n            EXPECT_GT(prob, 1e-10);\n            func(target, state, dim);\n            ASSERT_NEAR(state_norm_squared(state, dim), prob, eps);\n            normalize(prob, state, dim);\n\n            test_state =\n                get_expanded_eigen_matrix_with_identity(target, mat, n) *\n                test_state;\n            ASSERT_NEAR(test_state.squaredNorm(), prob, eps);\n            test_state.normalize();\n            state_equal(state, test_state, dim, \"Projection gate\");\n        }\n        std::random_shuffle(indices.begin(), indices.end());\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, ProjectionAndNormalizeTest) {\n    Eigen::MatrixXcd P0(2, 2), P1(2, 2);\n    P0 << 1, 0, 0, 0;\n    P1 << 0, 0, 0, 1;\n    test_projection_gate(P0_gate, M0_prob, P0);\n    test_projection_gate(P1_gate, M1_prob, P1);\n    test_projection_gate(P0_gate_single, M0_prob, P0);\n    test_projection_gate(P1_gate_single, M1_prob, P1);\n#ifdef _OPENMP\n    test_projection_gate(P0_gate_parallel, M0_prob, P0);\n    test_projection_gate(P1_gate_parallel, M1_prob, P1);\n#endif\n}\n\nTEST(UpdateTest, SingleQubitRotationGateTest) {\n    const UINT n = 6;\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 10;\n\n    Eigen::MatrixXcd Identity(2, 2), X(2, 2), Y(2, 2), Z(2, 2);\n    Identity << 1, 0, 0, 1;\n    X << 0, 1, 1, 0;\n    Y << 0, -1.i, 1.i, 0;\n    Z << 1, 0, 0, -1;\n\n    UINT target;\n    double angle;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state(state, dim);\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n    typedef std::tuple<std::function<void(UINT, double, CTYPE*, ITYPE)>,\n        Eigen::MatrixXcd, std::string>\n        testset;\n    std::vector<testset> test_list;\n    test_list.push_back(std::make_tuple(RX_gate, X, \"Xrot\"));\n    test_list.push_back(std::make_tuple(RY_gate, Y, \"Yrot\"));\n    test_list.push_back(std::make_tuple(RZ_gate, Z, \"Zrot\"));\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        for (auto tup : test_list) {\n            target = rand_int(n);\n            angle = rand_real();\n            auto func = std::get<0>(tup);\n            auto mat = std::get<1>(tup);\n            auto name = std::get<2>(tup);\n            func(target, angle, state, dim);\n            test_state =\n                get_expanded_eigen_matrix_with_identity(target,\n                    cos(angle / 2) * Identity + 1.i * sin(angle / 2) * mat, n) *\n                test_state;\n            state_equal(state, test_state, dim, name);\n        }\n    }\n    release_quantum_state(state);\n}\n\nvoid test_two_qubit_named_gate(UINT n, std::string name,\n    std::function<void(UINT, UINT, CTYPE*, ITYPE)> func,\n    std::function<Eigen::MatrixXcd(UINT, UINT, UINT)> matfunc) {\n    const ITYPE dim = 1ULL << n;\n    const UINT max_repeat = 2;\n\n    auto state = allocate_quantum_state(dim);\n    initialize_Haar_random_state_with_seed(state, dim, 0);\n\n    Eigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n    for (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n    std::vector<UINT> indices;\n    for (UINT i = 0; i < n; ++i) indices.push_back(i);\n\n    for (UINT rep = 0; rep < max_repeat; ++rep) {\n        for (UINT i = 0; i + 1 < n; i += 2) {\n            UINT target = indices[i];\n            UINT control = indices[i + 1];\n            func(control, target, state, dim);\n            Eigen::MatrixXcd mat = matfunc(control, target, n);\n            test_state = mat * test_state;\n            state_equal(state, test_state, dim, name);\n        }\n        std::random_shuffle(indices.begin(), indices.end());\n    }\n    release_quantum_state(state);\n}\n\nTEST(UpdateTest, CNOTGate) {\n    const UINT n = 4;\n    test_two_qubit_named_gate(\n        n, \"CNOT\", CNOT_gate, get_eigen_matrix_full_qubit_CNOT);\n    test_two_qubit_named_gate(6, \"CNOTGate\", CNOT_gate_single_unroll,\n        get_eigen_matrix_full_qubit_CNOT);\n#ifdef _OPENMP\n    test_two_qubit_named_gate(6, \"CNOTGate\", CNOT_gate_parallel_unroll,\n        get_eigen_matrix_full_qubit_CNOT);\n#endif\n#ifdef _USE_SIMD\n    test_two_qubit_named_gate(\n        6, \"CNOTGate\", CNOT_gate_single_simd, get_eigen_matrix_full_qubit_CNOT);\n#ifdef _OPENMP\n    test_two_qubit_named_gate(6, \"CNOTGate\", CNOT_gate_parallel_simd,\n        get_eigen_matrix_full_qubit_CNOT);\n#endif\n#endif\n}\n\nTEST(UpdateTest, CZGate) {\n    const UINT n = 4;\n    test_two_qubit_named_gate(n, \"CZ\", CZ_gate, get_eigen_matrix_full_qubit_CZ);\n    test_two_qubit_named_gate(\n        6, \"CZGate\", CZ_gate_single_unroll, get_eigen_matrix_full_qubit_CZ);\n#ifdef _OPENMP\n    test_two_qubit_named_gate(\n        6, \"CZGate\", CZ_gate_parallel_unroll, get_eigen_matrix_full_qubit_CZ);\n#endif\n#ifdef _USE_SIMD\n    test_two_qubit_named_gate(\n        6, \"CZGate\", CZ_gate_single_simd, get_eigen_matrix_full_qubit_CZ);\n#ifdef _OPENMP\n    test_two_qubit_named_gate(\n        6, \"CZGate\", CZ_gate_parallel_simd, get_eigen_matrix_full_qubit_CZ);\n#endif\n#endif\n}\n\nTEST(UpdateTest, SWAPGate) {\n    const UINT n = 4;\n    test_two_qubit_named_gate(\n        n, \"SWAP\", SWAP_gate, get_eigen_matrix_full_qubit_SWAP);\n    test_two_qubit_named_gate(6, \"SWAPGate\", SWAP_gate_single_unroll,\n        get_eigen_matrix_full_qubit_SWAP);\n#ifdef _OPENMP\n    test_two_qubit_named_gate(6, \"SWAPGate\", SWAP_gate_parallel_unroll,\n        get_eigen_matrix_full_qubit_SWAP);\n#endif\n#ifdef _USE_SIMD\n    test_two_qubit_named_gate(\n        6, \"SWAPGate\", SWAP_gate_single_simd, get_eigen_matrix_full_qubit_SWAP);\n#ifdef _OPENMP\n    test_two_qubit_named_gate(6, \"SWAPGate\", SWAP_gate_parallel_simd,\n        get_eigen_matrix_full_qubit_SWAP);\n#endif\n#endif\n}\n", "meta": {"hexsha": "e5a611787dc8818d9c7115f6dba26f35acccf269", "size": 10926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/csim/test_update_named.cpp", "max_stars_repo_name": "kodack64/qulacs-osaka", "max_stars_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-26T06:56:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T02:07:24.000Z", "max_issues_repo_path": "test/csim/test_update_named.cpp", "max_issues_repo_name": "kodack64/qulacs-osaka", "max_issues_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 104.0, "max_issues_repo_issues_event_min_datetime": "2021-11-12T04:15:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:12:20.000Z", "max_forks_repo_path": "test/csim/test_update_named.cpp", "max_forks_repo_name": "kodack64/qulacs-osaka", "max_forks_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-19T11:52:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T04:20:17.000Z", "avg_line_length": 33.7222222222, "max_line_length": 80, "alphanum_fraction": 0.6558667399, "num_tokens": 3358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.6085775189328981}}
{"text": "#include \"lcp_solver.hpp\"\n\n#include <Eigen/Core>\n\n#include <constants.hpp>\n#include <logger.hpp>\n#include <utils/eigen_ext.hpp>\n\nnamespace ccd {\nnamespace opt {\n\n    inline Eigen::VectorXd fischer(\n        const Eigen::VectorXd& x, const Eigen::VectorXd& s);\n    inline double fischer_error(const Eigen::VectorXd& phi);\n    Eigen::SparseMatrix<double> jac_fischer(const Eigen::VectorXd& x,\n        const Eigen::VectorXd& s,\n        const Eigen::SparseMatrix<double>& A);\n    inline Eigen::VectorXd grad_fischer_error(\n        const Eigen::VectorXd& phi, const Eigen::SparseMatrix<double>& J);\n    Eigen::VectorXd perturb(\n        const Eigen::VectorXd& x, const Eigen::VectorXd& phi);\n    bool is_converged(double old_err, double err, int iter);\n    Eigen::VectorXd compute_search_direction(const Eigen::VectorXd& phi,\n        const Eigen::SparseMatrix<double>& J,\n        const Eigen::VectorXd& grad_psi,\n        const int iter);\n    // Armijo backtracking combined with a projected line-search\n    bool projected_line_search(const Eigen::VectorXd& x,\n        const Eigen::VectorXd& dir,\n        const std::function<double(const Eigen::VectorXd&)>& f,\n        const double fx,\n        const Eigen::VectorXd& grad_fx,\n        double& step_length,\n        int iter,\n        const double armijo_rule_coeff = 0.001);\n\n    // Solve the LCP:\n    //      s = Ax + b\n    //      0 \u2264 x \u27c2 s \u2265 0\n    // by minimizing the Fisher error:\n    //      f(x) = (x\u00b2 + s\u00b2) - x - s\n    // using Newton's method.\n    bool lcp_newton(const Eigen::MatrixXd& A_dense,\n        const Eigen::VectorXd& b,\n        Eigen::VectorXd& x)\n    {\n        // Use a sparse matrix\n        const Eigen::SparseMatrix<double> A = A_dense.sparseView();\n\n        int num_vars = b.rows();\n        assert(A.rows() == num_vars);\n\n        // x\u2080 = 0\n        x = Eigen::VectorXd::Zero(num_vars);\n\n        double old_err, err = std::numeric_limits<double>::infinity();\n        for (int i = 0; i < Constants::FISCHER_MAX_ITER; i++) {\n            Eigen::VectorXd s = A * x + b; // slack variable\n\n            // Test all stopping criteria used\n            Eigen::VectorXd phi = fischer(x, s);\n            old_err = err;\n            err = fischer_error(phi); // \u03c8\n\n            if (is_converged(old_err, err, i)) {\n                return true;\n            }\n\n            Eigen::VectorXd px = perturb(x, phi);\n            Eigen::SparseMatrix<double> J = jac_fischer(px, s, A);\n            Eigen::VectorXd grad_psi = grad_fischer_error(phi, J);\n\n            // Test if we have dropped into a local minimia if so we are stuck\n            if (grad_psi.norm() < Constants::FISCHER_ABS_TOL) {\n                spdlog::warn(\"solver=ficher_newton_lcp iter={:d} \"\n                             \"failure='||\u2207\u03c8|| < {:g}' ||\u2207\u03c8||={:g} \"\n                             \"failsafe=none\",\n                    i, Constants::FISCHER_ABS_TOL, grad_psi.norm());\n                return false;\n            }\n\n            Eigen::VectorXd delta_x\n                = compute_search_direction(phi, J, grad_psi, i);\n\n            // Update iterate with result from Armijo backtracking\n            double step_length = 1.0;\n            bool success = projected_line_search(x, delta_x,\n                [&A, &b](const Eigen::VectorXd& x) {\n                    Eigen::VectorXd s = A * x + b;\n                    Eigen::VectorXd phi = fischer(x, s);\n                    return fischer_error(phi);\n                },\n                /*fx=*/err, grad_psi, step_length, i);\n            if (!success) {\n                delta_x = -grad_psi;\n                success = projected_line_search(x, delta_x,\n                    [&A, &b](const Eigen::VectorXd& x) {\n                        Eigen::VectorXd s = A * x + b;\n                        Eigen::VectorXd phi = fischer(x, s);\n                        return fischer_error(phi);\n                    },\n                    /*fx=*/err, grad_psi, step_length, i);\n                if (!success) {\n                    return false;\n                }\n            }\n\n            x += step_length * delta_x;\n        }\n\n        spdlog::warn(\"solver=ficher_newton_lcp \"\n                     \"failure='too many iterations' MAX_ITER={:d}\",\n            Constants::FISCHER_MAX_ITER);\n        return false;\n    }\n\n    /// @brief Compute the Fischer error measure.\n    inline Eigen::VectorXd fischer(\n        const Eigen::VectorXd& x, const Eigen::VectorXd& s)\n    {\n        //             _________\n        // \u03d5(x, s) = \u23b7(x\u00b2 + s\u00b2) - x - s\n        //\n        return (x.array().pow(2) + s.array().pow(2)).sqrt().matrix() - x - s;\n    }\n\n    inline double fischer_error(const Eigen::VectorXd& phi)\n    {\n        // \u03c8(x, s) = \u00bd\u03d5(x, s)\u1d40\u03d5(x, s)\n        return phi.squaredNorm() / 2;\n    }\n\n    Eigen::SparseMatrix<double> jac_fischer(const Eigen::VectorXd& x,\n        const Eigen::VectorXd& s,\n        const Eigen::SparseMatrix<double>& A)\n    {\n        //                ___________             _x\u0332\u1d62\u0332_+\u0332_s\u0332\u1d62\u0332a\u0332\u1d62\u0332_\n        // \u2207\u03d5\u1d62(x, s) = \u2207\u23b7(x\u1d62\u00b2 + s\u1d62\u00b2) - x\u1d62 - s\u1d62 =  x\u1d62\u00b2 + s\u00b2    - a\u1d62 - 1\n        Eigen::ArrayXd denom = (x.array().pow(2) + s.array().pow(2)).sqrt();\n        Eigen::VectorXd p = (x.array() / denom) - 1;\n        Eigen::VectorXd q = (s.array() / denom) - 1;\n        return Eigen::SparseDiagonal<double>(p)\n            + Eigen::SparseDiagonal<double>(q) * A;\n    }\n\n    inline Eigen::VectorXd grad_fischer_error(\n        const Eigen::VectorXd& phi, const Eigen::SparseMatrix<double>& J)\n    {\n        // \u2207\u03c8(x, s) = \u2207\u03d5(x, s)\u1d40\u03d5(x, s) = J\u1d40\u03d5\n        return J.transpose() * phi;\n    }\n\n    /// @brief Compute the sign of the input.\n    inline double sign(double x) { return (0 < x) - (x < 0); }\n\n    Eigen::VectorXd perturb(\n        const Eigen::VectorXd& x, const Eigen::VectorXd& phi)\n    {\n        // Bitmask for singular indices\n        Eigen::ArrayXb is_singular\n            = phi.array().abs() < Constants::FISCHER_SINGULAR_TOL\n            && x.array().abs() < Constants::FISCHER_SINGULAR_TOL;\n\n        // Perturbation: works on full system\n        Eigen::VectorXd px = x; // perturbed x\n        Eigen::VectorXd x_sign = x.unaryExpr(&sign);\n        // x_sign(x_sign==0) = 1;\n        x_sign += (x_sign.array() == 0).matrix().cast<double>();\n        // px(S==1) = Constants::FISCHER_SINGULAR_TOL * dir(S==1);\n        for (size_t i = 0; i < x.rows(); i++) {\n            if (is_singular(i)) {\n                px(i) = Constants::FISCHER_SINGULAR_TOL * x_sign(i);\n            }\n        }\n\n        return px;\n    }\n\n    bool is_converged(double old_err, double err, int iter)\n    {\n        // Test relative error\n        if (abs(err - old_err) / abs(old_err) < Constants::FISCHER_REL_TOL) {\n            spdlog::debug(\"solver=fischer_newton_lcp iter={} \"\n                          \"status=success rel_tol={} rel_err={}\",\n                iter, Constants::FISCHER_REL_TOL,\n                abs(err - old_err) / abs(old_err));\n            return true;\n        }\n        // Test absolute error\n        if (err < Constants::FISCHER_ABS_TOL) {\n            spdlog::debug(\"solver=fischer_newton_lcp iter={} \"\n                          \"status=success abs_tol={} abs_err={}\",\n                iter, Constants::FISCHER_ABS_TOL, err);\n            return true;\n        }\n        return false;\n    }\n\n    Eigen::VectorXd compute_search_direction(const Eigen::VectorXd& phi,\n        const Eigen::SparseMatrix<double>& J,\n        const Eigen::VectorXd& grad_psi,\n        const int iter)\n    {\n        // Solve \u0394x = -J\u207b\u00b9\u03d5\n        Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n        solver.compute(J);\n        Eigen::VectorXd delta_x;\n        if (solver.info() == Eigen::Success) {\n            delta_x = solver.solve(-phi);\n            if (solver.info() != Eigen::Success) {\n                spdlog::warn(\n                    \"solver=ficher_newton_lcp iter={:d} \"\n                    \"failure='sparse solve for newton direction failed' \"\n                    \"failsafe='revert to gradient descent'\",\n                    iter);\n                delta_x = -grad_psi; // Revert to gradient descent\n            }\n        } else {\n            spdlog::warn(\"solver=ficher_newton_lcp iter={:d} \"\n                         \"failure='sparse decomposition of the hessian failed' \"\n                         \"failsafe='revert to gradient descent'\",\n                iter);\n            delta_x = -grad_psi; // Revert to gradient descent\n        }\n\n        return delta_x;\n    }\n\n    // Armijo backtracking combined with a projected line-search\n    bool projected_line_search(const Eigen::VectorXd& x,\n        const Eigen::VectorXd& dir,\n        const std::function<double(const Eigen::VectorXd&)>& f,\n        const double fx,\n        const Eigen::VectorXd& grad_fx,\n        double& step_length,\n        int iter,\n        const double armijo_rule_coeff)\n    {\n        const double EPS = std::numeric_limits<double>::epsilon();\n\n        // Test if the search direction is smaller than numerical precision.\n        if (dir.array().abs().maxCoeff() < EPS) {\n            spdlog::warn(\"solver=ficher_newton_lcp iter={:d} \"\n                         \"failure='search direction too small' max(|\u0394x|)={:g} \"\n                         \"failsafe=none\",\n                iter, dir.array().abs().maxCoeff());\n            return false;\n        }\n\n        // Test if our search direction is a 'sufficient' descent direction\n        double descent_magnitude = (grad_fx.transpose() * dir)(0);\n        if (descent_magnitude > -EPS * descent_magnitude) {\n            spdlog::warn(\"solver=ficher_newton_lcp iter={:d} \"\n                         \"failure='search direction not descent direction' \"\n                         \"(\u2207\u03d5)\u1d40\u0394x={:g} failsafe='revert to gradient descent'\",\n                iter, descent_magnitude);\n            return false;\n        }\n\n        step_length = 1.0; // Current step length\n\n        // Sufficent decrease parameter for Armijo backtracking line search\n        double armijo_term = armijo_rule_coeff * descent_magnitude;\n\n        Eigen::VectorXd x_k;\n        do {\n            x_k = (x + step_length * dir).array().max(0); // project it\n\n            // Perform Armijo codition to see if we got a sufficient decrease\n            if (f(x_k) <= fx + step_length * armijo_term) {\n                return true;\n            }\n\n            step_length /= 2;\n        } while ((step_length * dir).norm() >= Constants::FISCHER_SINGULAR_TOL);\n\n        spdlog::warn(\"solver=ficher_newton_lcp iter={:d} \"\n                     \"failure='step length too small' step_length={:g}\",\n            iter, step_length);\n        return false;\n    }\n\n} // namespace opt\n} // namespace ccd\n", "meta": {"hexsha": "cd3fadf4c60c2ca593dda3e74f9b573b95faeedd", "size": 10568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "comparisons/STIV/src/solvers/fischer_newton.cpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "comparisons/STIV/src/solvers/fischer_newton.cpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "comparisons/STIV/src/solvers/fischer_newton.cpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 37.0807017544, "max_line_length": 80, "alphanum_fraction": 0.5375662377, "num_tokens": 2656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.6085775018450722}}
{"text": "/**\n * @file   BSpline.hpp\n * @author Paul Furgale <paul.furgale@utoronto.ca>\n * @date   Fri Feb 11 13:51:57 2011\n *\n * @brief  A class to facilitate state estimation for vehicles in 3D\n *         space using B-splines.\n *\n *\n */\n\n#ifndef _BSPLINE_HPP\n#define _BSPLINE_HPP\n#include <sparse_block_matrix/sparse_block_matrix.h>\n#include <Eigen/Core>\n#include <sm/assert_macros.hpp>\n#include <vector>\n\nnamespace bsplines {\nclass BiVector;\n}\n\nnamespace Eigen {\nnamespace internal {\ntemplate <>\nstruct functor_traits<bsplines::BiVector> {\n    enum { Cost = 1, PacketAccess = false, IsRepeatable = true };\n};\n}  // namespace internal\n}  // namespace Eigen\n\nnamespace bsplines {\n\nclass BiVector {\n    enum { Cost = 1, PacketAccess = false, IsRepeatable = true };\n\n  private:\n    const int startIndex_;\n    const double endValue_;\n    const Eigen::VectorXd localBi_;\n\n  public:\n    BiVector(int startIndex, const Eigen::VectorXd& localBi, const double& endValue)\n        : startIndex_(startIndex), endValue_(endValue), localBi_(localBi){};\n\n    double operator()(int i, int j = 0) const {\n        // kill unused parameter warning\n        static_cast<void>(j);\n        i -= startIndex_;\n        if (i < 0) {\n            return endValue_;\n        }\n        if (i >= (localBi_.rows())) {\n            return 0;\n        }\n        return i >= 0 ? localBi_(i) : 0;\n    }\n};\n\n/**\n * @brief A class to facilitate state estimation for vehicles in 3D space using B-Splines\n *\n * NOTE by CC:\n * 1. The B-Spline definition in the class is some different to wiki, \"The NURBS Book\", and MTU course\n *  (a) Basic function N[i,0](u) = 1 in \"The NURBS Book\", B[i,1](t) = 1 in this definition\n *  (b) Basic function N[i,p](u) is a degree p polynomial in u, but B[i,k](t) is k-1 degree polynomial in this\n * definition, where k is the order of B-Spline, and k = p + 1.\n *  (c) m = n + p + 1 for \"The NURBS Book\", m = n + k for this. And control points(coefficient) number is n+1, knots\n * number is m+1, spline degree is p\n * 2. Some terminology in this class\n *  (a) B-Spline order: k\n *  (b) B-Spline(Polynomial) degree: k - 1\n *  (c) For clamped(nonperiodic) curve(see Ref[2]), the knots is defined(see Ref[1]) as U = {a,...,a,\n * u[p+1],...,u[m-p-1],b,...,b} = {0,...,0,u[p+1],...,u[m-p-1],1,...,1}. And the first knot and last knot has the\n * multiplicity of p+1, the valid knots is U1 = {0,u[p+1],...,u[m-p-1],1}. I denote the number of knots is m1+1, and the\n * valid number of knots is m+1. The relation meets m1 = n + p + 1 = n + k, and m = m1 - 2p\n *  (d) Valid time segment: m\n *  (e) Knots numbers: m1 + 1 = m + 2(k - 1) + 1 = m + 2k - 1\n *  (f) Coefficient matrix, the same mean of control points matrix\n *  (g) Coefficient number: n + 1\n * 3. When evaluating the B-Spline value at t, only part of control points(ie, coefficient matrix) will active in the\n * calculation, Vk = {V[i-k+1], V[i-k+2],..., V[i]}. The matrix of Vk in code is called local parameters.\n *\n * QUESTIONS:\n * 1. The class use clamped curve in previous discussion, and the knots sequences in class (knots_) should be U, but in\n * the initSpline() function, it seems that the use opened curve.\n *  ANSWER: There are some confuse in the code implementation, this class is implements the clamped curve indeed, but\n * some variable don't seems like this.\n *  (1) The knots should be U = {a,...,a,u[p+1],...,u[m-p-1],b,...,b}, where a = tMin != 0, b = tMax != 1, but in\n * initialization, the first and last k element not the same, like {a - (k-1) * dt, a - (k-2) * dt, ..., a}.\n *  (2) The method `tMin()` and `tMax()` return `a` and `b`\n *  (3) The matrix M(or the basis matrix) don't save the first and last k element because they are zero.\n *\n * I am more familiar with the definition in \"The NURBS Book\". So, although I have add some comment to this class, but\n * maybe they are not quite correct.\n * Some function about integral I could understand yet.\n *\n * Ref:\n *  [1] L. Piegl and W. Tiller, The NURBS Book, Second Edition. Berlin, Heidelberg: Springer-Verlag, 1997.\n *  [2] K. Qin, \u201cGeneral Matrix Representations for B-Splines,\u201d The Visual Computer, vol. 16, no. 3, pp. 177\u2013186, 2000.\n *  [3] MTU, \u201cCS3621 Introduction to Computing with Geometry Notes.\u201d https://pages.mtu.edu/~shene/COURSES/cs3621/NOTES/.\n */\nclass BSpline {\n  public:\n    /**\n     * @brief A base class for BSpline exceptions\n     */\n    SM_DEFINE_EXCEPTION(Exception, std::runtime_error);\n\n    /**\n     * @brief Create a spline of the specified order. The resulting B-spline will be a series of piecewise polynomials\n     * of degree splineOrder - 1.\n     * @param splineOrder   The order of the spline\n     */\n    explicit BSpline(int splineOrder);\n\n    /**\n     * A destructor.\n     */\n    ~BSpline() = default;\n\n    /**\n     * @brief Get the order of the spline, k\n     * @return The order of the spline, k\n     */\n    inline int splineOrder() const { return splineOrder_; }\n\n    /**\n     * @brief Get the degree of polynomial used by the spline, p = k - 1\n     * @return The degree of polynomial used by the spline, p = k - 1\n     */\n    inline int polynomialDegree() const { return splineOrder_ - 1; }\n\n    /**\n     * @brief Get the number of coefficients(control points) required for a specified number of valid time segments\n     * @param numTimeSegments The number of time segments required\n     * @return The number of coefficients required for a specified number of valid time segments\n     */\n    int numCoefficientsRequired(int numTimeSegments) const;\n\n    /**\n     * @brief Get the minimum number of knots required to have at least one valid time segment\n     * @return The minimum number of knots required to have at least one valid time segment\n     */\n    int minimumKnotsRequired() const;\n\n    /**\n     * @brief Get the number of knots required for a specified number of valid time segments\n     * @param numTimeSegments The number of time segments required\n     * @return The number of knots required for a specified number of valid time segments\n     */\n    int numKnotsRequired(int numTimeSegments) const;\n\n    /**\n     * @brief Get the number of valid time segments for a given number of knots\n     * @param numKnots  The number of knots.\n     * @return The number of valid time segments\n     */\n    int numValidTimeSegments(int numKnots) const;\n\n    /**\n     * @brief Get the number of valid time segments for the current knot sequence\n     * @return The number of valid time segments for the current knot sequence\n     */\n    int numValidTimeSegments() const;\n\n    /**\n     * @brief Get the basic matrix active on the i-th time segment\n     * @param i The index of the time segment\n     * @return The basic matrix active on the i-th time segment\n     */\n    const Eigen::MatrixXd& basisMatrix(int i) const;\n\n    /**\n     * @brief Get the minimum time that the spline is well-defined on\n     * @return The minimum time that the spline is well-defined on\n     */\n    const double& tMin() const;\n\n    /**\n     * @brief Get the maximum time that the spline is well-defined on. Because B-spline are defined on half-open\n     * intervals, the spline curve is well defined up to but not including this time.\n     * @return The maximum time that the spline is well-defined on\n     */\n    const double& tMax() const;\n\n    /**\n     * @brief Get the time interval that the spline is well-defined on [tMin, tMax)\n     * @return The time interval that the spline is well-defined on [tMin, tMax)\n     */\n    std::pair<double, double> timeInterval() const;\n\n    /**\n     * @brief Get the time interval of a single spline segment\n     * @param i The index of the time segment\n     * @return The time interval of the i-th spline segment\n     */\n    std::pair<double, double> timeInterval(int i) const;\n\n    /**\n     * @brief Set the knots and coefficients of the spline, each column of the coefficient(control points) matrix is\n     * interpreted as a single, vector-valued spline coefficient, and then calculate the basic matrix M in each segment\n     * @param knots         A non-decreasing knot sequence\n     * @param coefficients  A set of spline coefficients(control points)\n     */\n    void setKnotsAndCoefficients(const std::vector<double>& knots, const Eigen::MatrixXd& coefficients);\n\n    /**\n     * @brief Set the knots and coefficients of the spline, each column of the coefficient(control points) matrix is\n     * interpreted as a single, vector-valued spline coefficient, and then calculate the basic matrix M in each segment\n     * @param knots         A non-decreasing knot vector\n     * @param coefficients  A set of spline coefficients(control points)\n     */\n    void setKnotVectorAndCoefficients(const Eigen::VectorXd& knots, const Eigen::MatrixXd& coefficients);\n\n    /**\n     * @brief Set the coefficient(control points) matrix\n     * @param coefficients  Coefficient matrix(control points)\n     */\n    void setCoefficientMatrix(const Eigen::MatrixXd& coefficients);\n\n    /**\n     * @brief Sets the coefficient(control points) matrix from the stacked vector of coefficients\n     * @param coefficients  The stacked vector of coefficients(control points)\n     */\n    void setCoefficientVector(const Eigen::VectorXd& coefficients);\n\n    /**\n     * @brief Get the knot vector\n     * @return Knot vector\n     */\n    inline const std::vector<double>& knots() const { return knots_; }\n\n    /**\n     * @brief Get the knot vector with a column matrix\n     * @return Knot vector with a column matrix\n     */\n    Eigen::VectorXd knotVector() const;\n\n    /**\n     * @brief Get the coefficient(control points) matrix, each column of the coefficient matrix is interpreted as a\n     * single, vector-valued spline coefficient.\n     * @return Coefficient(control points) matrix\n     */\n    inline const Eigen::MatrixXd& coefficients() const { return coefficients_; }\n\n    /**\n     * @brief Get the stacked vector of coefficients(control points) matrix\n     * @return Stacked vector of coefficients (control points) matrix\n     */\n    Eigen::VectorXd coefficientVector();\n\n    /**\n     * @brief Get the number of total coefficients the spline currently uses\n     * @return The number of total coefficients the spline currently uses\n     */\n    int numCoefficients() const;\n\n    /**\n     * @brief Get the length(number) of total coefficients the spline currently uses\n     * @return The length(number) of total coefficients the spline currently uses\n     */\n    int coefficientVectorLength() const;\n\n    /**\n     * @brief This is equivalent to spline.coefficients().cols()\n     * @return The number of vector-valued coefficient columns the spline currently uses\n     */\n    int numVvCoefficients() const;\n\n    /**\n     * @brief Get a map to a single coefficient column. This allows the user to pass around what is essentially a\n     * pointer to a single column in the coefficient matrix.\n     * @param i The column of the coefficient matrix to return. 0 < i < coefficients().cols() = n\n     * @return A map to column i of the coefficient matrix.\n     */\n    Eigen::Map<const Eigen::VectorXd> vvCoefficientVector(int i) const;\n\n    /**\n     * @brief Get a map to a single coefficient column. This allows the user to pass around what is essentially a\n     * pointer to a single column in the coefficient matrix.\n     * @param i The column of the coefficient matrix to return. 0 < i < coefficients().cols() = n\n     * @return A map to column i of the coefficient matrix.\n     */\n    Eigen::Map<Eigen::VectorXd> vvCoefficientVector(int i);\n\n    /**\n     * @brief Evaluate the spline curve at time t\n     * @param t The time to evaluate the spline curve\n     * @return The value of the spline curve at the time t\n     */\n    Eigen::VectorXd eval(double t) const;\n\n    /**\n     * @brief Evaluate the derivative of the spline curve at time t\n     * @param t                 The time to evaluate the spline derivative\n     * @param derivativeOrder   The order of the derivative. This must be >= 0\n     * @return The value of the derivative of the spline curve evaluated at t\n     */\n    Eigen::VectorXd evalD(double t, int derivativeOrder) const;\n\n    /**\n     * @brief Evaluate the derivative of the spline curve at time t and retrieve the Jacobian of the value with respect\n     * to small changed in the parameter vector(control points, coefficient matrix). The Jacobian only refers to the\n     * local parameter vector (part of coefficient matrix). The indices of the local parameters with respect to the full\n     * parameter vector can be retrieved using localCoefficientVectorIndices()\n     * @param t                 The time to evaluate the spline derivative\n     * @param derivativeOrder   The order of the derivative. This must be >= 0\n     * @return The value of the derivative of the spline curve evaluated at t and the Jacobian\n     */\n    std::pair<Eigen::VectorXd, Eigen::MatrixXd> evalDAndJacobian(double t, int derivativeOrder) const;\n\n    /**\n     * @brief Evaluate the derivative of the spline curve at time t and retrieve the Jacobian of the value with respect\n     * to small changed in the parameter vector(control points, coefficient matrix). The Jacobian only refers to the\n     * local parameter vector (part of coefficient matrix)\n     * @param t                     The time to evaluate the spline derivative\n     * @param derivativeOrder       The order of the derivative. This must be >= 0\n     * @param jacobian              A pointer to the Jacobian matrix to fill in\n     * @param coefficientIndices    A pointer to an int vector that will be filled with the local coefficient indices\n     * (which index is activated for calculating Jacobian matrix)\n     * @return The value of the derivative of the spline curve evaluated at t\n     */\n    Eigen::VectorXd evalDAndJacobian(double t, int derivativeOrder, Eigen::MatrixXd* jacobian,\n                                     Eigen::VectorXi* coefficientIndices) const;\n\n    /**\n     * @brief Get the local basic matrix evaluated at the time t. For vector-valued spline coefficients of dimension n1,\n     * and a B-Spline of order k, this matrix will be n1 x (kn1).\n     *\n     * Evaluating the B-spline at time t, eval(t,O) is equivalent to evaluating Phi(t,O) * localCoefficientVector(t).\n     * It's similar to the Jacobian calculation.\n     *      C(u) = U * M(i) * V(i) = J * V\n     * where V is the stacked vector representation of V(i)\n     *\n     * @param t                 The time to evaluate the local basis matrix.\n     * @param derivativeOrder   The derivative order to return (0 is no derivative)\n     * @return  The local basis matrix evaluated at time t\n     */\n    Eigen::MatrixXd Phi(double t, int derivativeOrder = 0) const;\n\n    /**\n     * @brief Get the local basic matrix evaluated at the time t. For vector-valued spline coefficients of dimension n1,\n     * and a B-Spline of order k, this matrix will be n1 x (kn1).\n     *\n     * Evaluating the B-spline at time t, eval(t,O) is equivalent to evaluating Phi(t,O) * localCoefficientVector(t)\n     *\n     * @param t                 The time to evaluate the local basis matrix.\n     * @param derivativeOrder   The derivative order to return (0 is no derivative)\n     * @return  The local basis matrix evaluated at time t\n     */\n    Eigen::MatrixXd localBasisMatrix(double t, int derivativeOrder = 0) const;\n\n    /**\n     * @brief Get the local coefficient matrix evaluated at the time t. For vector-valued spline coefficients of\n     * dimension n1, and a B-Spline of order k, this matrix will be n1 x k\n     * @param t The time being queried\n     * @return The local coefficient matrix active at time t\n     */\n    Eigen::MatrixXd localCoefficientMatrix(double t) const;\n\n    /**\n     * @brief Get the local coefficient vector evaluated at the time t. For vector-valued spline coefficients of\n     * dimension n1, and a B-Spline of order k, this vector will be k*n1 x 1. Evaluating the B-spline at time t,\n     * eval(t,O) is equivalent to evaluating Phi(t,O) * localCoefficientVector(t)\n     * @param t The time being queried\n     * @return The local coefficient vector active at time t\n     */\n    Eigen::VectorXd localCoefficientVector(double t) const;\n\n    /**\n     * @brief Get the local coefficient vector for segment i\n     * @param segmentIdx The segment index, should less than number of valid time segments\n     * @return The local coefficient vector active on time segment i\n     */\n    Eigen::VectorXd segmentCoefficientVector(int segmentIdx) const;\n\n    /**\n     * @brief Return a map to a single coefficient column.\n     *\n     * This allows the user to pass around what is essentially a pointer to a single column in the coefficient matrix\n     * @tparam D    The dimension of vector-valued spline coefficients n1\n     * @param i     The column of the coefficient matrix to return. 0 <= i < n = coefficients().cols()\n     * @return  A map to column i of the coefficient matrix\n     */\n    template <int D>\n    Eigen::Map<Eigen::Matrix<double, D, 1> > fixedSizeVvCoefficientVector(int i) {\n        SM_ASSERT_EQ_DBG(Exception, D, coefficients_.rows(),\n                         \"Size mismatch between requested vector size and actual vector size\");\n        SM_ASSERT_GE_LT(Exception, i, 0, coefficients_.cols(), \"Index out of range\");\n        return Eigen::Map<Eigen::Matrix<double, D, 1> >(&coefficients_(0, i), coefficients_.rows());\n    }\n\n    /**\n     * @brief Return a map to a single coefficient column, const version.\n     *\n     * This allows the user to pass around what is essentially a pointer to a single column in the coefficient matrix\n     * @tparam D    The dimension of vector-valued spline coefficients n1\n     * @param i     The column of the coefficient matrix to return. 0 <= i < n = coefficients().cols()\n     * @return  A map to column i of the coefficient matrix\n     */\n    template <int D>\n    Eigen::Map<const Eigen::Matrix<double, D, 1> > fixedSizeVvCoefficientVector(int i) const {\n        SM_ASSERT_EQ_DBG(Exception, D, coefficients_.rows(),\n                         \"Size mismatch between requested vector size and actual vector size\");\n        SM_ASSERT_GE_LT(Exception, i, 0, coefficients_.cols(), \"Index out of range\");\n        return Eigen::Map<const Eigen::Matrix<double, D, 1> >(&coefficients_(0, i), coefficients_.rows());\n    }\n\n    /**\n     * @brief Get the indices of the local coefficients active at time t. Only part of control points(coefficient\n     * matrix) is activated in evaluating B-Spline at t, i.e., Vk = {V[i-k+1], V[i-k+2], ... , V[i]}, the indices is the\n     * index of every element of Vk with respect to the coefficient matrix, ie, [(i-k+1) * n1, i * n1]\n     * @param t The time being queried\n     * @return The indices of the local coefficients active at time t\n     */\n    Eigen::VectorXi localCoefficientVectorIndices(double t) const;\n\n    /**\n     * @brief Get the indices of the local coefficients active on segment i\n     * @param segmentIdx The segment being queried\n     * @return The indices of the local coefficients active on this segment\n     */\n    Eigen::VectorXi segmentCoefficientVectorIndices(int segmentIdx) const;\n\n    /**\n     * @brief Get the indices of the local vector-valued coefficients active at time t. Only part of control\n     * points(coefficient matrix) is activated in evaluating B-Spline at t, ie, Vk = {V[i-k+1], V[i-k+2], ... , V[i]},\n     * the indices is the row index of Vj with respect to the coefficient matrix. ie, [i-k+1, i]\n     * @param t The time being queried\n     * @return The indices of the local vector-valued coefficients active at time t\n     */\n    Eigen::VectorXi localVvCoefficientVectorIndices(double t) const;\n\n    /**\n     * @brief Get the indices of the local vector-valued coefficients active on segment i\n     * @param segmentIdx The segment being queried\n     * @return The indices of the local vector-valued coefficients active at time t\n     */\n    Eigen::VectorXi segmentVvCoefficientVectorIndices(int segmentIdx) const;\n\n    /**\n     * @brief Update the local coefficient vector\n     * @param t The time used to select the local coefficients.\n     * @param c The local coefficient vector\n     */\n    void setLocalCoefficientVector(double t, const Eigen::VectorXd& c);\n\n    /**\n     * Initialize a spline from two times and two positions. The spline will be initialized to\n     * have one valid time segment \\f$[t_0, t_1)\\f$ such that\n     *  \\f$\\mathbf b(t_0) = \\mathbf p_0\\f$,\n     *  \\f$\\mathbf b(t_1) = \\mathbf p_1\\f$,\n     *  \\f$\\dot{\\mathbf b}(t_0) = \\frac{\\mathbf{p_1} - \\mathbf p_0}{t_1 - t_0}\\f$, and\n     *  \\f$\\dot{\\mathbf b}(t_1) = \\frac{\\mathbf{p_1} - \\mathbf p_0}{t_1 - t_0}\\f$.\n     *\n     * This solve method is same as \"The NURBS Book\", but use the matrix representation form in Ref[2]. It construct the\n     * linear system Ax = b. Where x is the control points matrix but is implemented in stacked vector, The linear\n     * system include the position equation(no derivatives), if k > 2, then add the velocity(first order derivatives)\n     * equation. If k > 4, then set all higher order derivatives to zero, and add it to linear system.\n     *\n     * @param t0 The start of the time interval.\n     * @param t1 The end of the time interval\n     * @param p0 The position at the start of the time interval.\n     * @param p1 The position at the end of the time interval.\n     */\n    void initSpline(double t0, double t1, const Eigen::VectorXd& p0, const Eigen::VectorXd& p1);\n\n    /**\n     * @brief Initialize spline with <t, v> list, where t is the timestamp, v is the vector value evaluted at t. The\n     * initialization using global interpolation method(see Ref[1] Section 9.2)\n     *\n     * The BSpline could be represented in a matrix form like below\n     *      C(t) = U(t) * M * V\n     * where U(t) * M is implemented in `Phi(t)`, and V is the control(coefficient) matrix. The initialize method\n     * construct a linear system Ax = b, where x is the stacked control vector from V; A is U(t) * M, the size is\n     * adjusted to meet the size of x; b is the interpolation value C(t).\n     *\n     * But for this method, the size of <t, v> is less than the knots number, so the number of equation Ax = b is not\n     * enough to solve x. The author add other equations to constrain the spline, i.e., assume the second derivativate\n     * of spline at each knot to zero.\n     *      C''(t) = U''(t) * M * V\n     * where U''(t) * M is also implemented in `Phi(t, 2)`. Then the equation is Phi * x = 0, but in implementation, the\n     * author add a value `lambda` to set the weight, i.e., lambda * Phi * x = 0. In my option, the lambda could regard\n     * as the weight for the whole equation systems, like the information matrix in SLAM optimization.\n     *\n     * Please see the difference to above equation, the argument is spline at each time, this is spline at each knot.\n     *\n     * @param times                 Timestamp list\n     * @param interpolationPoints   Interpolation points\n     * @param numSegments           Number of time segments, it's used to set the knots number.\n     * @param lambda                The adjust weight for second derivatives\n     */\n    void initSpline2(const Eigen::VectorXd& times, const Eigen::MatrixXd& interpolationPoints, int numSegments,\n                     double lambda);\n\n    /**\n     * @brief\n     *\n     * The method is only few difference to `initSpline2`. The second derivatives is assuming to zero in `initSpline2`\n     * while the quadratic integral is assume to zero in this method. It's seems like to the bias in IMU model.\n     *\n     * @param times\n     * @param interpolationPoints\n     * @param numSegments\n     * @param lambda\n     * @return\n     */\n    void initSpline3(const Eigen::VectorXd& times, const Eigen::MatrixXd& interpolationPoints, int numSegments,\n                     double lambda);\n\n    /**\n     * @brief Same to `initSpline3` but using sparse calculation\n     *\n     * @param times\n     * @param interpolationPoints\n     * @param numSegments\n     * @param lambda\n     * @return\n     */\n    void initSplineSparse(const Eigen::VectorXd& times, const Eigen::MatrixXd& interpolationPoints, int numSegments,\n                          double lambda);\n\n    void initSplineSparseKnots(const Eigen::VectorXd& times, const Eigen::MatrixXd& interpolationPoints,\n                               const Eigen::VectorXd knots, double lambda);\n\n    /**\n     * Add a curve segment that interpolates the point p, ending at time t.\n     *\n     * If the new time corresponds with the first knot past the end of the curve,\n     * the existing curve is perfectly preserved. Otherwise, the existing curve\n     * will interpolate its current position at the current endpoint and the new\n     * position at the new endpoint but will not necessarily match the last segment\n     * exactly.\n     *\n     * @param t The time of the point to interpolate. This must be greater than t_max()\n     * @param p The point to interpolate at time t.\n     */\n    void addCurveSegment(const double& t, const Eigen::VectorXd& p);\n\n    /**\n     * Add a curve segment that interpolates the point p, ending at time t.\n     *\n     * If the new time corresponds with the first knot past the end of the curve,\n     * the existing curve is perfectly preserved. Otherwise, the existing curve\n     * will interpolate its current position at the current endpoint and the new\n     * position at the new endpoint but will not necessarily match the last segment\n     * exactly.\n     *\n     * @param t The time of the point to interpolate. This must be greater than t_max()\n     * @param p The point to interpolate at time t.\n     * @param lambda a smoothness parameter. Higher for more smooth.\n     */\n    void addCurveSegment2(const double& t, const Eigen::VectorXd& p, const double& lambda);\n\n    /**\n     * @brief Removes a curve segment from the left by removing one knot and one coefficient vector.\n     * After calling this function, the curve will have one fewer segment. The new minimum time will be\n     * timeInterval(0).first\n     */\n    void removeCurveSegment();\n\n    /**\n     * @brief Evaluate the integral from t1 to t2\n     *\n     * NOTE, TODO: some calculation detail don't match to my option, try later\n     *\n     * @param t1\n     * @param t2\n     * @return\n     */\n    Eigen::VectorXd evalIntegral(double t1, double t2) const;\n\n    /**\n     * @brief Same as evalIntegral\n     *\n     * @param t1\n     * @param t2\n     * @return\n     */\n    inline Eigen::VectorXd evalI(double t1, double t2) const { return evalIntegral(t1, t2); }\n\n    /**\n     * Get the \\f$ \\mathbf V_i \\f$ matrix associated with the integral over the segment.\n     *\n     * @param segmentIndex\n     *\n     * @return the \\f$ \\mathbf V_i \\f$ matrix of size k x k\n     */\n    Eigen::MatrixXd Vi(int segmentIndex) const;\n\n    // return matrix of size kn1 x kn1\n    Eigen::MatrixXd Mi(int segmentIndex) const;\n    // return matrix of size kn1 x kn1\n    Eigen::MatrixXd Bij(int segmentIndex, int columnIndex) const;\n    // return matrix of size kn1 x n1\n    Eigen::MatrixXd U(double t, int derivativeOrder) const;\n    // return matrix of size 1 x k\n    Eigen::VectorXd u(double t, int derivativeOrder) const;\n    // the index of basic matrix for input time t\n    int segmentIndex(double t) const;\n    // return matrix of size k x k\n    Eigen::MatrixXd Dii(int segmentIndex) const;\n    // return matrix of size kn1 x kn1\n    Eigen::MatrixXd Di(int segmentIndex) const;\n\n    /**\n     * Get the b_i(t) for i in localVvCoefficientVectorIndices (@see #localVvCoefficientVectorIndices).\n     *\n     * @param t The time being queried.\n     *\n     * @return [b_i(t) for i in localVvCoefficientVectorIndices] of size k x 1\n     *\n     */\n    Eigen::VectorXd getLocalBiVector(double t) const;\n    void getLocalBiInto(double t, Eigen::VectorXd& ret) const;\n\n    /**\n     * Get the cumulative (tilde) b_i(t) for i in localVvCoefficientVectorIndices (@see\n     * #localVvCoefficientVectorIndices).\n     *\n     * @param t The time being queried.\n     *\n     * @return [tilde b_i(t) for i in localVvCoefficientVectorIndices].\n     *\n     */\n    Eigen::VectorXd getLocalCumulativeBiVector(double t) const;\n\n    Eigen::CwiseNullaryOp<BiVector, Eigen::VectorXd> getBiVector(double t) const {\n        return Eigen::CwiseNullaryOp<BiVector, Eigen::VectorXd>(numValidTimeSegments(), 1,\n                                                                BiVector(segmentIndex(t), getLocalBiVector(t), 0));\n    }\n\n    Eigen::CwiseNullaryOp<BiVector, Eigen::VectorXd> getCumulativeBiVector(double t) const {\n        return Eigen::CwiseNullaryOp<BiVector, Eigen::VectorXd>(\n            numValidTimeSegments(), 1, BiVector(segmentIndex(t), getLocalCumulativeBiVector(t), 1));\n    }\n\n    Eigen::MatrixXd segmentIntegral(int segmentIdx, const Eigen::MatrixXd& W, int derivativeOrder) const;\n\n    Eigen::MatrixXd segmentQuadraticIntegral(const Eigen::MatrixXd& W, int segmentIdx, int derivativeOrder) const;\n    Eigen::MatrixXd segmentQuadraticIntegralDiag(const Eigen::VectorXd& Wdiag, int segmentIdx,\n                                                 int derivativeOrder) const;\n    Eigen::MatrixXd curveQuadraticIntegral(const Eigen::MatrixXd& W, int derivativeOrder) const;\n    Eigen::MatrixXd curveQuadraticIntegralDiag(const Eigen::VectorXd& Wdiag, int derivativeOrder) const;\n\n    sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> curveQuadraticIntegralSparse(const Eigen::MatrixXd& W,\n                                                                                         int derivativeOrder) const;\n    sparse_block_matrix::SparseBlockMatrix<Eigen::MatrixXd> curveQuadraticIntegralDiagSparse(\n        const Eigen::VectorXd& Wdiag, int derivativeOrder) const;\n\n    void initConstantSpline(double t_min, double t_max, int numSegments, const Eigen::VectorXd& constant);\n\n  private:\n    /**\n     * @brief Check the knot sequence is valid, it will throw an exception if it's not valid\n     * @param knots The knot sequence to verify\n     */\n    void verifyKnotSequence(const std::vector<double>& knots);\n\n    /**\n     * @brief Initialize the basis matrices M based on the current knot sequence. There is one basis matrix for each\n     * valid time segment defined by the spline. See Ref[2]\n     *\n     * Implemented using the recursive basis matrix algorithm from\n     * Qin, Kaihuai, General matrix representations for B-splines, The Visual Computer (2000) 16:177\u2013186\n     */\n    void initializeBasisMatrices();\n\n    /**\n     * @brief The recursive function to calculate basis matrix M.\n     *           [ M_{k-1}(i) ]        [      0       ]\n     *  M_k(i) = [            ] * A +  [              ] * B = M1 * A + M2 * B\n     *           [     0      ]        [ [ M_{k-1}(i) ]\n     *\n     *  M_1(i) = [1]\n     *  size of A and B: (k-1) X k\n     *\n     * Ref: Qin, Kaihuai, General matrix representations for B-splines, The Visual Computer (2000) 16:177\u2013186.\n     *\n     * @param k The degree(order) of the matrix\n     * @param i The time segment index\n     * @return  Basic matrix\n     */\n    Eigen::MatrixXd M(int k, int i);\n\n    /**\n     * @brief A helper function to calculate d0 for producing th basic matrix M.\n     *  d(0,j) = (t[i] - t[j]) / (t[j+k-1] - t[j]).\n     * Defined in Qin, Kaihuai, General matrix representations for B-splines, The Visual Computer (2000) 16:177\u2013186.\n     *\n     * @param k Spline degree(order)\n     * @param i Time segment index\n     * @param j Time segment index\n     * @return  Value d0\n     */\n    double d0(int k, int i, int j);\n\n    /**\n     * @brief A helper function to calculate d1 for producing the M matrices.\n     *  d(1,j) = (t[i+1] - t[i]) / (t[j+k-1] - t[j]).\n     * Defined in Qin, Kaihuai, General matrix representations for B-splines, The Visual Computer (2000) 16:177\u2013186.\n     *\n     * @param k Spline degree(order)\n     * @param i Time segment index\n     * @param j Time segment index\n     * @return  Value d1\n     */\n    double d1(int k, int i, int j);\n\n    /**\n     * @brief An internal function to find the segment of the knot sequence that the time t falls in. The function\n     * returns the value u = (t - t[i]) / (t[i+1] - t[i]) and the index i\n     * @param t The time being queried\n     * @return A pair with the first value u = (t - t[i]) / (t[i+1] - t[i]) and the second value the index i\n     */\n    std::pair<double, int> computeUAndTIndex(double t) const;\n\n    /**\n     * @brief An internal function to find the segment of the knot sequence that the time t falls in. The function\n     * returns the width of the knot segment dt = t[i+1] - t[i] and the index i\n     * @param t The time being queried\n     * @return  The pair with the first value dt = t[i+1] -t[i] and the second value the index i\n     */\n    std::pair<double, int> computeTIndex(double t) const;\n\n    /**\n     * @brief Compute the vector U w.r.t t at given derivative order l, this is an k X 1 vector.\n     *\n     * At derivative order 0 (no derivative), this vector is U(t) = [1, u(t), u(t)^2, ... , u(t)^{k-1}]^T.\n     * For higher derivative order n, the vector is U^{(l)}(t) = d^l U(t) / dt^{l}\n     *\n     * @param u                 The value u(t)\n     * @param segmentIndex      The index of t\n     * @param derivativeOrder   Derivative order l\n     * @return The vector of dU\n     */\n    Eigen::VectorXd computeU(double u, int segmentIndex, int derivativeOrder) const;\n\n    int basisMatrixIndexFromStartingKnotIndex(int startingKnotIndex) const;\n    int startingKnotIndexFromBasisMatrixIndex(int basisMatrixIndex) const;\n    const Eigen::MatrixXd& basisMatrixFromKnotIndex(int knotIndex) const;\n\n  private:\n    int splineOrder_;            // The order of the spline\n    std::vector<double> knots_;  // The knot sequence used by the B-spline\n    // The basis matrices M for each time segment, see Ref[2]. The basis matrix don't save all the matrix, only N =\n    // valid time segments elements are saved, the first and last k-1 elements are 0\n    std::vector<Eigen::MatrixXd> basisMatrices_;\n\n    // The coefficient matrix(control points) used by the B-Spline. Each column can be seen as a single vector-valued\n    // spline coefficient. This is stored explicitly in column major order to ensure that each column (i.e. a single\n    // vector-valued spline coefficient) is stored in contiguous memory. This allows one to, for example, map a single\n    // spline coefficient using the Eigen::Map type.\n    // If the control points is V = [V_0, V_1,.., V_n], consider Vj is size of n1 x 1, then the size of V is\n    // n1 x (n+1)\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> coefficients_;\n};\n\n}  // namespace bsplines\n\n#endif /* _BSPLINE_HPP */\n", "meta": {"hexsha": "1f6a6d3a56cec2791161f75a944bbe2259f95d07", "size": 34639, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "aslam_nonparametric_estimation/bsplines/include/bsplines/BSpline.hpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aslam_nonparametric_estimation/bsplines/include/bsplines/BSpline.hpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aslam_nonparametric_estimation/bsplines/include/bsplines/BSpline.hpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3984272608, "max_line_length": 120, "alphanum_fraction": 0.6604694131, "num_tokens": 8697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6085633198718519}}
{"text": "/*\nBSD 2-Clause License\n\nCopyright (c) 2019, Oscar Riveros - www.peqnp.science.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <iostream>\n#include <random>\n\n#include <boost/mpi/environment.hpp>\n#include <boost/mpi/communicator.hpp>\n#include <boost/mpi/collectives.hpp>\n\nnamespace mpi = boost::mpi;\n\ntypedef unsigned long long int natural;\ntypedef long double real;\n\ntemplate<class T, typename F>\nclass cluster {\npublic:\n    cluster(const mpi::communicator &world, F functor) : __world(world), __functor(functor), __n(world.rank()), __m(world.size()) {}\n\n    T operator()() {\n        __n += __m;\n        return __functor(__n - __m);\n    }\n\nprivate:\n    const mpi::communicator &__world;\n    const F __functor;\n    T __n;\n    T __m;\n};\n\ntemplate<typename T>\nT scale(const mpi::communicator &world, const T length) {\n    return length / world.size() + world.size();\n}\n\ntemplate<typename T, typename F>\nstd::vector<T> parallelize(const mpi::communicator &world, std::vector<T> &vs, F functor) {\n    std::generate(vs.begin(), vs.end(), cluster<T, F>(world, functor));\n    return vs;\n}\n\ntemplate<typename T>\nT accumulate(const mpi::communicator &world, std::vector<T> &vs, const T size) {\n    real pi(0);\n    mpi::all_reduce(world, 4 * std::accumulate(vs.begin(), vs.end(), real(0), std::plus<>()) / size, pi, std::plus<>());\n    return pi;\n}\n\nint main() {\n    mpi::environment env;\n    mpi::communicator world;\n\n    const natural size = 1000000;\n\n    std::vector<real> vs(scale<natural>(world, size));\n\n    std::random_device device;\n    std::uniform_real_distribution<> distribution(0, 1);\n\n    parallelize<real>(world, vs, [&](auto) {\n        auto x = 2 * distribution(device) - 1;\n        auto y = 2 * distribution(device) - 1;\n        return std::pow(x, 2) + std::pow(y, 2) < 1;\n    });\n\n    auto pi = accumulate<real>(world, vs, size);\n\n    if (!world.rank()) {\n        std::cout << pi << std::endl;\n    }\n\n    return EXIT_SUCCESS;\n}", "meta": {"hexsha": "243aebe5b1cf0a60f5f0a0c7e5ef39a31c8f2b8a", "size": 3167, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mpi_pi/mpi_pi.cc", "max_stars_repo_name": "maxtuno/Distributed-Algorithms", "max_stars_repo_head_hexsha": "e675d75ffaa706213e6b3c0ab831610fb7f6b1e1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-24T00:19:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T00:23:28.000Z", "max_issues_repo_path": "mpi_pi/mpi_pi.cc", "max_issues_repo_name": "maxtuno/Distributed-Algorithms", "max_issues_repo_head_hexsha": "e675d75ffaa706213e6b3c0ab831610fb7f6b1e1", "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": "mpi_pi/mpi_pi.cc", "max_forks_repo_name": "maxtuno/Distributed-Algorithms", "max_forks_repo_head_hexsha": "e675d75ffaa706213e6b3c0ab831610fb7f6b1e1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.67, "max_line_length": 132, "alphanum_fraction": 0.7066624566, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6085633104471444}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE utility/random\n#include <boost/test/unit_test.hpp>\n\n#include <geneial/utility/Random.h>\nusing namespace geneial::utility;\n\nBOOST_AUTO_TEST_SUITE( RandomSuite )\n\nBOOST_AUTO_TEST_CASE( valid_values_ranges_bool )\n{\n    bool myRandBool = Random::generateBit();\n    BOOST_CHECK(myRandBool == true || myRandBool == false);\n}\n\n#define TEST_INT_VALUERANGE_RUNS 1000\nBOOST_AUTO_TEST_CASE( valid_values_ranges_int )\n{\n    for (int i = 1; i < TEST_INT_VALUERANGE_RUNS; i++)\n    {\n        const int result = Random::generate<int>(0, 100);\n        BOOST_CHECK(result >= 0 && result <= 100);\n    }\n\n    for (int i = 1; i < TEST_INT_VALUERANGE_RUNS; i++)\n    {\n        const int result = Random::generate<int>(-100, 0);\n        BOOST_CHECK(result >= -100 && result <= 0);\n    }\n\n    for (int i = 1; i < TEST_INT_VALUERANGE_RUNS; i++)\n    {\n        const int result = Random::generate<int>(-100, 100);\n        BOOST_CHECK(result >= -100 && result <= 100);\n    }\n\n    for (int i = 1; i < TEST_INT_VALUERANGE_RUNS; i++)\n    {\n        const float result = Random::generate<float>(0, 100);\n        BOOST_CHECK(result >= 0 && result <= 100);\n    }\n\n    for (int i = 1; i < TEST_INT_VALUERANGE_RUNS; i++)\n    {\n        const float result = Random::generate<float>(-100, 0);\n        BOOST_CHECK(result >= -100 && result <= 0);\n    }\n\n    for (int i = 1; i < TEST_INT_VALUERANGE_RUNS; i++)\n    {\n        const float result = Random::generate<float>(-100, 100);\n        BOOST_CHECK(result >= -100 && result <= 100);\n    }\n\n    for (int i = 1; i < TEST_INT_VALUERANGE_RUNS; i++)\n    {\n        const double result = Random::generate<double>(0, 100);\n        BOOST_CHECK(result >= 0 && result <= 100);\n    }\n\n    for (int i = 1; i < TEST_INT_VALUERANGE_RUNS; i++)\n    {\n        const double result = Random::generate<double>(-100, 0);\n        BOOST_CHECK(result >= -100 && result <= 0);\n    }\n\n    for (int i = 1; i < TEST_INT_VALUERANGE_RUNS; i++)\n    {\n        const double result = Random::generate<double>(-100, 100);\n        BOOST_CHECK(result >= -100 && result <= 100);\n    }\n}\n\nBOOST_AUTO_TEST_CASE( difference )\n{\n    double myRand1D = Random::generate<double>();\n    double myRand2D = Random::generate<double>();\n    BOOST_CHECK(myRand1D != myRand2D);\n\n    float myRand1F = Random::generate<float>();\n    float myRand2F = Random::generate<float>();\n    std::cout << myRand1F << \" - \" << myRand2F;\n    BOOST_CHECK(myRand1F != myRand2F);\n\n    int myRand1I = Random::generate<int>();\n    int myRand2I = Random::generate<int>();\n    BOOST_CHECK(myRand1I != myRand2I);\n}\n\n//Make TEST_INT_UNIFORM_RUNS, see whether randomness divergates by TEST_INT_UNIFORM_TOLERANCE\n#define TEST_INT_UNIFORM_RUNS (1e6)\n#define TEST_INT_UNIFORM_SLOTS (10)\n#define TEST_INT_UNIFORM_TOLERANCE (0.001f)\n\nBOOST_AUTO_TEST_CASE( int_uniform )\n{\n\n    BOOST_TEST_MESSAGE(\"TEST_INT_UNIFORM_RUNS: \" << TEST_INT_UNIFORM_RUNS);\n    BOOST_TEST_MESSAGE(\"TEST_INT_UNIFORM_SLOTS: \" << TEST_INT_UNIFORM_SLOTS);\n    BOOST_TEST_MESSAGE(\"TEST_INT_UNIFORM_TOLERANCE: \" << TEST_INT_UNIFORM_TOLERANCE);\n\n    int occurrences[TEST_INT_UNIFORM_SLOTS];\n\n    for (int i = 0; i < (TEST_INT_UNIFORM_SLOTS); i++)\n    {\n        occurrences[i] = 0;\n    }\n\n    for (int i = 1; i < TEST_INT_UNIFORM_RUNS; i++)\n    {\n        occurrences[Random::generate(0, TEST_INT_UNIFORM_SLOTS - 1)]++;\n    }\n\n    BOOST_TEST_MESSAGE(\"Int Distribution: \");\n    for (int i = 0; i < (TEST_INT_UNIFORM_SLOTS); i++)\n    {\n        BOOST_TEST_MESSAGE(\n                i << \" \" << std::string((int)100* ((float) occurrences[i] / (float) TEST_INT_UNIFORM_RUNS), '+'));\n    }\n\n    for (int i = 0; i < (TEST_INT_UNIFORM_SLOTS); i++)\n    {\n        BOOST_CHECK_MESSAGE(\n                ((float) occurrences[i] / (float) TEST_INT_UNIFORM_RUNS) < ((float) TEST_INT_UNIFORM_RUNS / (float) TEST_INT_UNIFORM_SLOTS) / (float) TEST_INT_UNIFORM_RUNS + (float) TEST_INT_UNIFORM_TOLERANCE,\n                \"uniform failed for \" << i << \" with \" << (float) occurrences[i] / (float) TEST_INT_UNIFORM_RUNS);\n    }\n}\n#define TEST_DOUBLE_UNIFORM_RUNS 1e6\n#define TEST_DOUBLE_UNIFORM_SLOTS 10\n#define TEST_DOUBLE_UNIFORM_TOLERANCE 0.001f\n#define TEST_DOUBLE_BOUND_TOLERANCE 0.00001f\nBOOST_AUTO_TEST_CASE( double_uniform )\n{\n\n    BOOST_TEST_MESSAGE(\"TEST_DOUBLE_UNIFORM_RUNS: \" << TEST_DOUBLE_UNIFORM_RUNS);\n    BOOST_TEST_MESSAGE(\"TEST_DOUBLE_UNIFORM_SLOTS: \" << TEST_DOUBLE_UNIFORM_SLOTS);\n    BOOST_TEST_MESSAGE(\"TEST_DOUBLE_UNIFORM_TOLERANCE: \" << TEST_DOUBLE_UNIFORM_TOLERANCE);\n\n    int occurrences[TEST_DOUBLE_UNIFORM_SLOTS];\n\n    for (int i = 0; i < (TEST_DOUBLE_UNIFORM_SLOTS); i++)\n    {\n        occurrences[i] = 0;\n    }\n\n    for (int i = 1; i < TEST_DOUBLE_UNIFORM_RUNS; i++)\n    {\n        const int val = (int) Random::generate<int>(0,\n                TEST_DOUBLE_UNIFORM_SLOTS - TEST_DOUBLE_BOUND_TOLERANCE);\n        occurrences[val]++;\n    }\n\n    BOOST_TEST_MESSAGE(\"Double Distribution: \");\n    for (int i = 0; i < (TEST_DOUBLE_UNIFORM_SLOTS); i++)\n    {\n        BOOST_TEST_MESSAGE(\n                i << \" \" << std::string((int)100* ((float) occurrences[i] / (float) TEST_DOUBLE_UNIFORM_RUNS), '+'));\n    }\n\n    for (int i = 0; i < (TEST_DOUBLE_UNIFORM_SLOTS); i++)\n    {\n        BOOST_CHECK_MESSAGE(\n                ((float) occurrences[i] / (float) TEST_DOUBLE_UNIFORM_RUNS) < ((float) TEST_DOUBLE_UNIFORM_RUNS / (float) TEST_DOUBLE_UNIFORM_SLOTS) / (float) TEST_DOUBLE_UNIFORM_RUNS + (float) TEST_DOUBLE_UNIFORM_TOLERANCE,\n                \"uniform failed for \" << i << \" with \" << (float) occurrences[i] / (float) TEST_DOUBLE_UNIFORM_RUNS);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "923a6f113ee38d915aa90f49d99f5b2546cb2708", "size": 5629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/src/tests/suites/random_test.cpp", "max_stars_repo_name": "geneial/geneial", "max_stars_repo_head_hexsha": "5e525c32b7c1e1e88788644e448e9234c93b55e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T15:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-15T19:33:22.000Z", "max_issues_repo_path": "src/src/tests/suites/random_test.cpp", "max_issues_repo_name": "geneial/geneial", "max_issues_repo_head_hexsha": "5e525c32b7c1e1e88788644e448e9234c93b55e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/src/tests/suites/random_test.cpp", "max_forks_repo_name": "geneial/geneial", "max_forks_repo_head_hexsha": "5e525c32b7c1e1e88788644e448e9234c93b55e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-24T13:14:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T07:30:20.000Z", "avg_line_length": 33.3076923077, "max_line_length": 224, "alphanum_fraction": 0.6475395274, "num_tokens": 1536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.828938825225204, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6085401830255048}}
{"text": "// Copyright Paul A. Bristow 2017\n// Copyright John Z. Maddock 2017\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or\n//  copy at http ://www.boost.org/LICENSE_1_0.txt).\n\n/*! \\brief Graph showing use of Lambert W function.\n\n\\details\n\nBoth Lambert W0 and W-1 branches can be shown on one graph.\nBut useful to have another graph for larger values of argument z.\nNeed two separate graphs for Lambert W0 and -1 prime because\nthe sensible ranges and axes are too different.  \n\nOne would get too small LambertW0 in top right and W-1 in bottom left.\n\n*/\n\n#include <boost/math/special_functions/lambert_w.hpp>\nusing boost::math::lambert_w0;\nusing boost::math::lambert_wm1;\nusing boost::math::lambert_w0_prime;\nusing boost::math::lambert_wm1_prime;\n\n#include <boost/math/special_functions.hpp>\nusing boost::math::isfinite;\n#include <boost/svg_plot/svg_2d_plot.hpp>\nusing namespace boost::svg;\n#include <boost/svg_plot/show_2d_settings.hpp>\nusing boost::svg::show_2d_plot_settings;\n\n#include <iostream>\n// using std::cout;\n// using std::endl;\n#include <exception>\n#include <stdexcept>\n#include <string>\n#include <array>\n#include <vector>\n#include <utility>\nusing std::pair;\n#include <map>\nusing std::map;\n#include <set>\nusing std::multiset;\n#include <limits>\nusing std::numeric_limits;\n#include <cmath> //\n\n  /*!\n  */\nint main()\n{\n  try\n  {\n    std::cout << \"Lambert W graph example.\" << std::endl;\n\n//[lambert_w_graph_1\n//] [/lambert_w_graph_1]\n    {\n      std::map<const double, double> wm1s;   // Lambert W-1 branch values.\n      std::map<const double, double> w0s;   // Lambert W0 branch values.\n\n      std::cout.precision(std::numeric_limits<double>::max_digits10);\n\n      int count = 0;\n      for (double z = -0.36787944117144232159552377016146086744581113103176804; z < 2.8; z += 0.001)\n      {\n        double w0 = lambert_w0(z);\n        w0s[z] = w0;\n   //     std::cout << \"z \" << z << \", w = \" << w0 << std::endl;\n        count++;\n      }\n      std::cout << \"points \" << count << std::endl;\n\n      count = 0;\n      for (double z = -0.3678794411714423215955237701614608727; z < -0.001; z += 0.001)\n      {\n        double wm1 = lambert_wm1(z);\n        wm1s[z] = wm1;\n        count++;\n      }\n      std::cout << \"points \" << count << std::endl;\n\n      svg_2d_plot data_plot;\n      data_plot.title(\"Lambert W function.\")\n        .x_size(400)\n        .y_size(300)\n        .legend_on(true)\n        .legend_lines(true)\n        .x_label(\"z\")\n        .y_label(\"W\")\n        .x_range(-1, 3.)\n        .y_range(-4., +1.)\n        .x_major_interval(1.)\n        .y_major_interval(1.)\n        .x_major_grid_on(true)\n        .y_major_grid_on(true)\n        //.x_values_on(true)\n        //.y_values_on(true)\n        .y_values_rotation(horizontal)\n        //.plot_window_on(true)\n        .x_values_precision(3)\n        .y_values_precision(3)\n        .coord_precision(4) // Needed to avoid stepping on curves.\n        .copyright_holder(\"Paul A. Bristow\")\n        .copyright_date(\"2018\")\n        //.background_border_color(black);\n        ;\n      data_plot.plot(w0s, \"W0 branch\").line_color(red).shape(none).line_on(true).bezier_on(false).line_width(1);\n      data_plot.plot(wm1s, \"W-1 branch\").line_color(blue).shape(none).line_on(true).bezier_on(false).line_width(1);\n      data_plot.write(\"./lambert_w_graph\");\n\n      show_2d_plot_settings(data_plot); // For plot diagnosis only.\n\n    } // small z Lambert W\n\n    {  // bigger argument z Lambert W\n\n      std::map<const double, double> w0s_big;   // Lambert W0 branch values for large z and W.\n      std::map<const double, double> wm1s_big;   // Lambert W-1 branch values for small z and large -W.\n      int count = 0;\n      for (double z = -0.3678794411714423215955237701614608727; z < 10000.; z += 50.)\n      {\n        double w0 = lambert_w0(z);\n        w0s_big[z] = w0;\n        count++;\n      }\n      std::cout << \"points \" << count << std::endl;\n\n      count = 0;\n      for (double z = -0.3678794411714423215955237701614608727; z < -0.001; z += 0.001)\n      {\n        double wm1 = lambert_wm1(z);\n        wm1s_big[z] = wm1;\n        count++;\n      }\n     std::cout << \"Lambert W0 large z argument points = \" << count << std::endl;\n\n     svg_2d_plot data_plot2;\n     data_plot2.title(\"Lambert W0 function for larger z.\")\n      .x_size(400)\n      .y_size(300)\n      .legend_on(false)\n      .x_label(\"z\")\n      .y_label(\"W\")\n      //.x_label_on(true)\n      //.y_label_on(true)\n      //.xy_values_on(false)\n      .x_range(-1, 10000.)\n      .y_range(-1., +8.)\n      .x_major_interval(2000.)\n      .y_major_interval(1.)\n      .x_major_grid_on(true)\n      .y_major_grid_on(true)\n      //.x_values_on(true)\n      //.y_values_on(true)\n      .y_values_rotation(horizontal)\n      //.plot_window_on(true)\n      .x_values_precision(3)\n      .y_values_precision(3)\n      .coord_precision(4) // Needed to avoid stepping on curves.\n      .copyright_holder(\"Paul A. Bristow\")\n      .copyright_date(\"2018\")\n      //.background_border_color(black);\n    ;\n\n    data_plot2.plot(w0s_big, \"W0 branch\").line_color(red).shape(none).line_on(true).bezier_on(false).line_width(1);\n    // data_plot2.plot(wm1s_big, \"W-1 branch\").line_color(blue).shape(none).line_on(true).bezier_on(false).line_width(1);\n    // This wouldn't show anything useful.\n    data_plot2.write(\"./lambert_w_graph_big_w\");\n   } // Big argument z Lambert W\n\n    { //  Lambert W0 Derivative plots\n\n    //  std::map<const double, double> wm1ps;   // Lambert W-1 prime branch values.\n      std::map<const double, double> w0ps;   // Lambert W0 prime branch values.\n\n      std::cout.precision(std::numeric_limits<double>::max_digits10);\n\n      int count = 0;\n      for (double z = -0.36; z < 3.; z += 0.001)\n      {\n        double w0p = lambert_w0_prime(z);\n        w0ps[z] = w0p;\n        // std::cout << \"z \" << z << \", w0 = \" << w0 << std::endl;\n        count++;\n      }\n      std::cout << \"points \" << count << std::endl;\n\n      //count = 0;\n      //for (double z = -0.36; z < -0.1; z += 0.001)\n      //{\n      //  double wm1p = lambert_wm1_prime(z);\n      //  std::cout << \"z \" << z << \", w-1 = \" << wm1p << std::endl;\n      //  wm1ps[z] = wm1p;\n      //  count++;\n      //}\n      //std::cout << \"points \" << count << std::endl;\n\n      svg_2d_plot data_plotp;\n      data_plotp.title(\"Lambert W0 prime function.\")\n        .x_size(400)\n        .y_size(300)\n        .legend_on(false)\n        .x_label(\"z\")\n        .y_label(\"W0'\")\n        .x_range(-0.3, +1.)\n        .y_range(0., +5.)\n        .x_major_interval(0.2)\n        .y_major_interval(2.)\n        .x_major_grid_on(true)\n        .y_major_grid_on(true)\n        .y_values_rotation(horizontal)\n        .x_values_precision(3)\n        .y_values_precision(3)\n        .coord_precision(4) // Needed to avoid stepping on curves.\n        .copyright_holder(\"Paul A. Bristow\")\n        .copyright_date(\"2018\")\n        ;\n\n      // derivative of N[productlog(0, x), 55]  at x=0 to 10\n      // Plot[D[N[ProductLog[0, x], 55], x], {x, 0, 10}]\n      // Plot[ProductLog[x]/(x + x ProductLog[x]), {x, 0, 10}]\n      data_plotp.plot(w0ps, \"W0 prime branch\").line_color(red).shape(none).line_on(true).bezier_on(false).line_width(1);\n      data_plotp.write(\"./lambert_w0_prime_graph\");\n  } // Lambert W0 Derivative plots\n\n    { //  Lambert Wm1 Derivative plots\n\n    std::map<const double, double> wm1ps;   // Lambert W-1 prime branch values.\n\n    std::cout.precision(std::numeric_limits<double>::max_digits10);\n\n    int count = 0;\n    for (double z = -0.3678; z < -0.00001; z += 0.001)\n    {\n      double wm1p = lambert_wm1_prime(z);\n      // std::cout << \"z \" << z << \", w-1 = \" << wm1p << std::endl;\n      wm1ps[z] = wm1p;\n      count++;\n    }\n    std::cout << \"Lambert W-1 prime points = \" << count << std::endl;\n\n    svg_2d_plot data_plotp;\n    data_plotp.title(\"Lambert W-1 prime function.\")\n      .x_size(400)\n      .y_size(300)\n      .legend_on(false)\n      .x_label(\"z\")\n      .y_label(\"W-1'\")\n      .x_range(-0.4, +0.01)\n      .x_major_interval(0.1)\n      .y_range(-20., -5.)\n      .y_major_interval(5.)\n      .x_major_grid_on(true)\n      .y_major_grid_on(true)\n      .y_values_rotation(horizontal)\n      .x_values_precision(3)\n      .y_values_precision(3)\n      .coord_precision(4) // Needed to avoid stepping on curves.\n      .copyright_holder(\"Paul A. Bristow\")\n      .copyright_date(\"2018\")\n      ;\n\n      // derivative of N[productlog(0, x), 55]  at x=0 to 10\n      // Plot[D[N[ProductLog[0, x], 55], x], {x, 0, 10}]\n      // Plot[ProductLog[x]/(x + x ProductLog[x]), {x, 0, 10}]\n      data_plotp.plot(wm1ps, \"W-1 prime branch\").line_color(blue).shape(none).line_on(true).bezier_on(false).line_width(1);\n      data_plotp.write(\"./lambert_wm1_prime_graph\");\n    } // Lambert W-1 prime graph\n } // try\n  catch (std::exception& ex)\n  {\n    std::cout << ex.what() << std::endl;\n  }\n}  // int main()\n\n   /*\n\n   //[lambert_w_graph_1_output\n\n   //] [/lambert_w_graph_1_output]\n   */\n", "meta": {"hexsha": "3eb43f75aed05ba608ff9bd547296159aab6205a", "size": 8949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/lambert_w_graph.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/example/lambert_w_graph.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/example/lambert_w_graph.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": 31.181184669, "max_line_length": 123, "alphanum_fraction": 0.6005140239, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6083889324248876}}
{"text": "\n//  Copyright 2015 Stephan Menzel. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <tools/Random.hpp>\n\n#include <boost/thread.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/moment.hpp>\n#include <boost/bind.hpp>\n#include <boost/ref.hpp>\n\n#include <iostream>\n\nstruct door {\n\tdoor() : m_win(false), m_open(false) {};\n\tbool m_win;\n\tbool m_open;\n};\n\nenum strategy {\n\tSTUBBORN = 0,  // will stick to original choice upon Monty revealing the goat\n\tMINDCHANGER,   // will always change his mind to the remaining door  \n\tUNDECIDED      // reacts randomly\n};\n\n//! \\return win or loose\nbool round(const strategy n_strategy) {\n\t\n\tstruct door doors[3];\n\t\n\t// First assign the door to win the car\n\tdoors[moose::tools::urand(2)].m_win = true;\n\t\n\t// Now our player selects a door randomly\n\tunsigned int choice = moose::tools::urand(2);\n\t\n\t// Monty selects another random door with a goat to open\n\tunsigned int idx = 0;\n\tdo {\n\t\tidx = moose::tools::urand(2);\n\t} while (doors[idx].m_win || (idx == choice)); \n\t\t\t\t\t\t// we need a random index that looses \n\t\t\t\t\t\t// and was not the player's choice\n\tdoors[idx].m_open = true;\n\t\n\tswitch (n_strategy) {\n\t\tcase STUBBORN:\n\t\t\t// player does not change his mind but sticks with his choice\n\t\t\tbreak;\n\t\tcase UNDECIDED:\n\t\t\t// undecided player has a 50% chance to change his mind, otherwise \n\t\t\t// bail too and stick with his choice\n\t\t\tif (moose::tools::urand(100) < 50) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase MINDCHANGER:\n\t\t\t// player always changes his mind and changes \n\t\t\t// his choice to the remaining door\n\t\t\tfor (unsigned int i = 0; i < 3; ++i) {\n\t\t\t\tif (!doors[i].m_open && (i != choice)) {\n\t\t\t\t\tchoice = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t}\n\t\t\n\t// player does not change his mind but sticks with his choice\n\treturn doors[choice].m_win;\n}\n\n// return ratio of wins in percent\nvoid player(double &n_result, const strategy n_strategy, const unsigned int n_rounds) {\n\t\n\tusing namespace boost::accumulators;\n\t\n\t// accumulate all the results\n\taccumulator_set<double, stats<tag::mean> > acc;\n\n\t// play as many rounds and accumulate wins and loosses\n\tfor (unsigned int i = 0; i < n_rounds; ++i) {\n\t\t\n\t\tbool result = round(n_strategy);\n\t\tacc(result ? 100.0 : 0.0);\n\t}\n\t\n\tn_result = mean(acc);\n}\n\n\nint main(int argc, char **argv) {\n\n\tunsigned int rounds = 1000000;\n\t\n\tdouble stubborn_wins = 0.0;\n\tdouble mindchanger_wins = 0.0;\n\tdouble undecided_wins = 0.0;\n\t\n\tstd::cout << \"players going to work...\" << std::endl;\n\t\n\tboost::thread sp = boost::thread(boost::bind(&player, boost::ref(stubborn_wins),    STUBBORN,    rounds));\n\tboost::thread mp = boost::thread(boost::bind(&player, boost::ref(mindchanger_wins), MINDCHANGER, rounds));\n\tboost::thread up = boost::thread(boost::bind(&player, boost::ref(undecided_wins),   UNDECIDED,   rounds));\n\n\tsp.join();\n\tmp.join();\n\tup.join();\n\t\n\tstd::cout << \"Stubborn player won \" << stubborn_wins << \" percent of his \" << rounds << \" rounds.\" << std::endl;\n\tstd::cout << \"Mindchanger player won \" << mindchanger_wins << \" percent of his \" << rounds << \" rounds.\" << std::endl;\n\tstd::cout << \"Undecided player won \" << undecided_wins << \" percent of his \" << rounds << \" rounds.\" << std::endl;\n}\n\n", "meta": {"hexsha": "0caa040038c55caab0f2e3ec80f955727a2fafd6", "size": 3400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "monty_hall.cpp", "max_stars_repo_name": "MrMoose/moose_monty_hall", "max_stars_repo_head_hexsha": "0c73281d7ecdabcb5fc5b9db18efcdcb1fcab67e", "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": "monty_hall.cpp", "max_issues_repo_name": "MrMoose/moose_monty_hall", "max_issues_repo_head_hexsha": "0c73281d7ecdabcb5fc5b9db18efcdcb1fcab67e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "monty_hall.cpp", "max_forks_repo_name": "MrMoose/moose_monty_hall", "max_forks_repo_head_hexsha": "0c73281d7ecdabcb5fc5b9db18efcdcb1fcab67e", "max_forks_repo_licenses": ["BSL-1.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.813559322, "max_line_length": 119, "alphanum_fraction": 0.6735294118, "num_tokens": 957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6083889284358504}}
{"text": "#pragma once\n\n#include \"globla.hpp\"\n\n#include <Eigen/Eigen>\n\nstruct Plane3D {\n    /* Plane normal. */\n    vec3 normal;\n    /* Plane center. */\n    vec3 center;\n\n    /* Points on plane. */\n    std::vector<vec3> points;\n    /* Points on plane's border. */\n    std::vector<vec3> hull;\n\n    /* Default constructor */\n    Plane3D();\n    /* Construct plane with normal vector and center point */\n    Plane3D(vec3 const &normal, vec3 const &center);\n    /* Construct plane with parameter `theta`, all points p(x, y, z) in plane\n     * satisfies:\n     *  \\theta_0 + \\theta_1 x + \\theta_2 y = z.\n     */\n    Plane3D(Eigen::Vector3d const &theta);\n\n    /* Get distance from `point` to this plane. */\n    flt dist(vec3 const &point) const;\n    /* Get projection of `point` on this plane. */\n    vec3 project(vec3 const &from) const;\n    /* Get the bases of this plane */\n    std::pair<vec3, vec3> get_base() const;\n    /* Get 2D coordinate of `point` (inside this plane). */\n    vec2 get_coord_2d(vec3 const &point) const;\n    /* Get 3D location of given coordinate (3d vector) */\n    vec3 get_coord_3d(vec2 const &coord) const;\n    /* Compute plane border, need member `points` to be non-empty. */\n    bool compute_hull();\n    /* Compute `normal` and `center` based on the points from this `plane` 's\n     * hull.\n     */\n    bool compute_params();\n\n    bool dump_off(std::string const &filename) const;\n};\n\n// Author: Blurgy <gy@blurgy.xyz>\n// Date:   Mar 24 2021, 14:08 [CST]\n", "meta": {"hexsha": "91ed7673ddec6e6d88f6be92a6766be7890f0873", "size": 1468, "ext": "hpp", "lang": "C++", "max_stars_repo_path": ".config/templates/cxx/Plane3D.hpp", "max_stars_repo_name": "Blurgyy/dotfiles", "max_stars_repo_head_hexsha": "49e648242ed2effd8c0f533fb4817043f3511548", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": ".config/templates/cxx/Plane3D.hpp", "max_issues_repo_name": "Blurgyy/dotfiles", "max_issues_repo_head_hexsha": "49e648242ed2effd8c0f533fb4817043f3511548", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".config/templates/cxx/Plane3D.hpp", "max_forks_repo_name": "Blurgyy/dotfiles", "max_forks_repo_head_hexsha": "49e648242ed2effd8c0f533fb4817043f3511548", "max_forks_repo_licenses": ["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.36, "max_line_length": 77, "alphanum_fraction": 0.6253405995, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6083634281613642}}
{"text": "#include <array>\n#include <chrono>\n#include <iostream>\n#include <boost/math/constants/constants.hpp>\n#include \"bicycle/whipple.h\"\n#include \"parameters.h\"\n\nnamespace {\n    const double fs = 200; // sample rate [Hz]\n    const double dt = 1.0/fs; // sample time [s]\n    const double v0 = 4.0; // forward speed [m/s]\n    const size_t N = 1000; // length of simulation in samples\n\n    std::array<model::BicycleWhipple::state_t, N> continuous_time_system_state_n;\n    std::array<model::BicycleWhipple::state_t, N> continuous_time_system_state_0;\n    std::array<model::BicycleWhipple::state_t, N> discrete_time_system_state_n;\n    std::array<model::BicycleWhipple::state_t, N> discrete_time_system_state_0;\n} // namespace\n\nint main(int argc, char* argv[]) {\n    (void)argc;\n    (void)argv;\n\n    model::BicycleWhipple bicycle(v0, dt);\n\n    std::chrono::time_point<std::chrono::system_clock> cont_start, cont_stop;\n    std::chrono::time_point<std::chrono::system_clock> disc_start, disc_stop;\n\n    cont_start = std::chrono::system_clock::now();\n    bicycle.set_v_dt(v0, 0);\n    cont_stop = std::chrono::system_clock::now();\n\n    disc_start = std::chrono::system_clock::now();\n    bicycle.set_v_dt(v0, dt);\n    disc_stop = std::chrono::system_clock::now();\n\n    std::chrono::duration<double> cont_time = cont_stop - cont_start;\n    std::chrono::duration<double> disc_time = disc_stop - disc_start;\n    disc_time -= cont_time;\n    std::cout << \"time for continuous state space computation: \" <<\n        std::chrono::duration_cast<std::chrono::microseconds>(cont_time).count() <<\n        \" us\" << std::endl;\n    std::cout << \"(additional) time for discrete state space computation: \" <<\n        std::chrono::duration_cast<std::chrono::microseconds>(disc_time).count() <<\n        \" us\" << std::endl;\n\n    std::cout << \"M: \" << std::endl << bicycle.M() << std::endl;\n    std::cout << \"C1: \" << std::endl << bicycle.C1() << std::endl;\n    std::cout << \"K0: \" << std::endl << bicycle.K0() << std::endl;\n    std::cout << \"K2: \" << std::endl << bicycle.K2() << std::endl << std::endl;\n\n    std::cout << \"for v = \" << bicycle.v() << \" m/s\" << std::endl;\n    std::cout << \"A: \" << std::endl << bicycle.A() << std::endl;\n    std::cout << \"B: \" << std::endl << bicycle.B() << std::endl << std::endl;\n\n    std::cout << \"for fs = \"  << fs << \"  Hz\" << std::endl;\n    std::cout << \"Ad: \" << std::endl << bicycle.Ad() << std::endl;\n    std::cout << \"Bd: \" << std::endl << bicycle.Bd() << std::endl << std::endl;\n\n    model::BicycleWhipple::state_t x, x0;\n    x0 << 0, 0, 10, 10, 0; // define in degrees\n    x0 *= constants::as_radians;\n\n    std::cout << \"initial state: [\" << x0.transpose() << \"]' rad\" << std::endl;\n    std::cout << \"states are: [yaw angle, roll angle, steer angle, roll rate, steer rate]'\" << std::endl << std::endl;\n\n    std::cout << \"simulating (no input) continuous time system at constant speed...\" << std::endl;\n    x = x0;\n    for (auto& state: continuous_time_system_state_n) {\n        state = bicycle.integrate_state(x, model::BicycleWhipple::input_t::Zero(), dt);\n        x = state;\n    }\n\n    std::cout << \"simulating (zero input) continuous time system at constant speed...\" << std::endl;\n    cont_start = std::chrono::system_clock::now();\n    x = x0;\n    for (auto& state: continuous_time_system_state_0) {\n        state = bicycle.integrate_state(x, model::BicycleWhipple::input_t::Zero(), dt);\n        x = state;\n    }\n    cont_stop = std::chrono::system_clock::now();\n\n    std::cout << \"simulating (no input) discrete time system at constant speed...\" << std::endl;\n    x = x0;\n    for (auto& state: discrete_time_system_state_n) {\n        state = bicycle.update_state(x);\n        x = state;\n    }\n\n    std::cout << \"simulating (zero input) discrete time system at constant speed...\" << std::endl;\n    disc_start = std::chrono::system_clock::now();\n    x = x0;\n    for (auto& state: discrete_time_system_state_0) {\n        state = bicycle.update_state(x, model::BicycleWhipple::input_t::Zero());\n        x = state;\n    }\n    disc_stop = std::chrono::system_clock::now();\n\n    std::cout << std::endl;\n    std::cout << \"state at end of simulation (\" << N << \" steps)\" << std::endl;\n    std::cout << \"continuous time (no input):   \" << continuous_time_system_state_n.back().transpose() << std::endl;\n    std::cout << \"continuous time (zero input): \" << continuous_time_system_state_0.back().transpose() << std::endl;\n    std::cout << \"discrete time (no input):     \" << discrete_time_system_state_n.back().transpose() << std::endl;\n    std::cout << \"discrete time (zero input):   \" << discrete_time_system_state_0.back().transpose() << std::endl;\n    std::cout << std::endl;\n\n    cont_time = cont_stop - cont_start;\n    disc_time = disc_stop - disc_start;\n    std::cout << \"simulation time (zero input form)\" << std::endl;\n    std::cout << \"continuous: Tc = \" <<\n        std::chrono::duration_cast<std::chrono::microseconds>(cont_time).count() <<\n        \" us\" << std::endl;\n    std::cout << \"discrete: Td = \" <<\n        std::chrono::duration_cast<std::chrono::microseconds>(disc_time).count() <<\n        \" us\" << std::endl;\n    std::cout << \"Tc - Td = \" <<\n        std::chrono::duration_cast<std::chrono::microseconds>(cont_time - disc_time).count() <<\n        \" us\" << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "638fe9b0abcff561f11de57c892d70232b004a72", "size": 5314, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/bicycle_model.cc", "max_stars_repo_name": "oliverlee/biketest", "max_stars_repo_head_hexsha": "074b0b03455021c52a13efe583b1816bc5daad4e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-12-14T01:22:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T05:15:04.000Z", "max_issues_repo_path": "examples/bicycle_model.cc", "max_issues_repo_name": "oliverlee/biketest", "max_issues_repo_head_hexsha": "074b0b03455021c52a13efe583b1816bc5daad4e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-01-12T15:20:57.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-02T16:09:37.000Z", "max_forks_repo_path": "examples/bicycle_model.cc", "max_forks_repo_name": "oliverlee/biketest", "max_forks_repo_head_hexsha": "074b0b03455021c52a13efe583b1816bc5daad4e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-07T05:15:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T05:15:05.000Z", "avg_line_length": 43.5573770492, "max_line_length": 118, "alphanum_fraction": 0.617425668, "num_tokens": 1498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6083213331010179}}
{"text": "/**\n * @file quic_svd_test.cpp\n * @author Siddharth Agrawal\n *\n * Test file for QUIC-SVD class.\n */\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/quic_svd/quic_svd.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nBOOST_AUTO_TEST_SUITE(QUICSVDTest);\n\nusing namespace mlpack;\n\n/**\n * The reconstruction error of the obtained SVD should be small.\n */\nBOOST_AUTO_TEST_CASE(QUICSVDReconstructionError)\n{\n  // Load the dataset.\n  arma::mat dataset;\n  data::Load(\"test_data_3_1000.csv\", dataset);\n\n  // Obtain the SVD using default parameters.\n  arma::mat u, v, sigma;\n  svd::QUIC_SVD quicsvd(dataset, u, v, sigma);\n\n  // Reconstruct the matrix using the SVD.\n  arma::mat reconstruct;\n  reconstruct = u * sigma * v.t();\n\n  // The relative reconstruction error should be small.\n  double relativeError = arma::norm(dataset - reconstruct, \"frob\") /\n                         arma::norm(dataset, \"frob\");\n  BOOST_REQUIRE_SMALL(relativeError, 1e-5);\n}\n\n/**\n * The singular value error of the obtained SVD should be small.\n */\nBOOST_AUTO_TEST_CASE(QUICSVDSigularValueError)\n{\n  arma::mat U = arma::randn<arma::mat>(3, 20);\n  arma::mat V = arma::randn<arma::mat>(10, 3);\n\n  arma::mat R;\n  arma::qr_econ(U, R, U);\n  arma::qr_econ(V, R, V);\n\n  arma::mat s = arma::diagmat(arma::vec(\"1 0.1 0.01\"));\n\n  arma::mat data = arma::trans(U * arma::diagmat(s) * V.t());\n\n  arma::vec s1, s3;\n  arma::mat U1, U2, V1, V2, s2;\n\n  // Obtain the SVD using default parameters.\n  arma::svd_econ(U1, s1, V1, data);\n  svd::QUIC_SVD quicsvd(data, U1, V1, s2);\n\n  s3 = arma::diagvec(s2);\n  s1 = s1.subvec(0, s3.n_elem - 1);\n\n  // The sigular value error should be small.\n  double error = arma::norm(s1 - s3);\n  BOOST_REQUIRE_SMALL(error, 0.05);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "b444739479ce51221c891254c7eb1a6c501f91f3", "size": 1766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/quic_svd_test.cpp", "max_stars_repo_name": "jmlevin7878/mlpack", "max_stars_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mlpack/tests/quic_svd_test.cpp", "max_issues_repo_name": "jmlevin7878/mlpack", "max_issues_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/quic_svd_test.cpp", "max_forks_repo_name": "jmlevin7878/mlpack", "max_forks_repo_head_hexsha": "7fe38005d86b77293f728c34ca176224bdff9ee8", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1917808219, "max_line_length": 68, "alphanum_fraction": 0.6698754247, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6083213294814965}}
{"text": "#define BOOST_TEST_MODULE FourierTransformTest\n#include <boost/test/unit_test.hpp>\n\n// For IO\n#include <stdlib.h>\n#include <math.h>\n#include <cmath> \n#include <iostream>\n#include <unistd.h>\n#include <vector>\n\n// Plotting library \n#include <boost/tuple/tuple.hpp>\n#include \"gnuplot-iostream.h\"\n#include <utility>\n\n// For measuring elapsed time\n#include <chrono>\n\n// For Random Float Generator\n#include <time.h>\n\n// For object under test\n#include \"detector.h\"\n#include \"qam-modulator.h\"\n#include \"common.h\"\n#include \"fftw3.h\"\n\n/**\n* Test NYQUIST MODULATOR\n* \n*/\nBOOST_AUTO_TEST_SUITE(DetectorTest)\n\n\n/**\n* \n*/\nBOOST_AUTO_TEST_CASE(CorrelatorTest)\n{\n    printf(\"\\nTesting Correlator...\\n\");\n\n    size_t nPoints = 512;\n    size_t symbolSize = nPoints*2;\n    size_t prefixSize = (int) (symbolSize / 8);\n    size_t symbolSizeWithPrefx = symbolSize + prefixSize;\n    size_t pilotToneStep = 8;\n    size_t bitsPerSymbol = 2;\n    double pilotToneAmplitude = 2.0;\n    size_t energyDispersalSeed = 10;\n    size_t nAvaiableifftPoints = (nPoints - (int)(nPoints/pilotToneStep));\n    size_t nMaxEncodedBytes = (int)((nAvaiableifftPoints *  bitsPerSymbol)  / 8);\n    size_t nData = nMaxEncodedBytes;\n\n    // Setup random float generator\n    srand( (unsigned)time( NULL ) );\n\n    //double modulatorOutput[symbolSizeWithPrefx];\n    DoubleVec modulatorOutput;\n    modulatorOutput.resize(symbolSizeWithPrefx);\n\n    // Create rx signal array to capable of holding 20 upsampled symbols with prefix\n    size_t rxSignalSize = (symbolSizeWithPrefx * 10);\n    size_t rxLastAllowedIndex = (symbolSizeWithPrefx * 9);\n\n    DoubleVec rxSignal(rxSignalSize);\n    DoubleVec corellatorOutput(rxSignalSize);\n    ByteVec txBytes(nData);\n\n    // Initialize Encoder objects\n    QamModulator qam(nPoints, pilotToneStep, pilotToneAmplitude, energyDispersalSeed, bitsPerSymbol);\n    ofdmFFT ifft(nPoints, FFTW_BACKWARD, pilotToneStep);\n    NyquistModulator nyquistModulator(nPoints, ifft.out);\n    \n    // Initialize Decoder objects\n    ofdmFFT fft(nPoints, FFTW_FORWARD, pilotToneStep);\n    NyquistModulator nyquistDemodulator(nPoints, fft.in);    \n    Detector detector(nPoints, prefixSize, &fft, &nyquistDemodulator);\n\n\n    // Generate Random Bytes\n    for(size_t i = 0; i < nData; i++)\n    {\n        txBytes[i] = rand() % 255;\n    }\n\n    // Generate random index value for symbol start\n    size_t  symbolStart = rand() % rxLastAllowedIndex;\n    printf(\"Randomly Generated Symbol Start = %lu\\n\",symbolStart);\n\n    // Encode one symbol \n    qam.Modulate(txBytes, (DoubleVec &) ifft.in, nData);\n    ifft.ComputeTransform( (fftw_complex *) &modulatorOutput[prefixSize]);\n    nyquistModulator.Modulate( modulatorOutput, prefixSize);\n    AddCyclicPrefix(modulatorOutput, symbolSize , prefixSize);\n    // Check Prefix Has been added correctly\n    for(size_t i = 0 ; i < prefixSize; i++)\n    {\n        //modulatorOutput[i] = modulatorOutput[symbolSize+i];\n\n        if(modulatorOutput[i] != modulatorOutput[symbolSize + i])\n        {\n            printf(\"Missmatch symbolwithprefix[%lu]  = %f, modulatorOutput[%lu] = %f \\n\" , i , modulatorOutput[i], (symbolSize + i) , modulatorOutput[(symbolSize + i)]);\n        }\n    }\n\n    // Copy the symbol with prefix to Rx signal array\n    std::copy(modulatorOutput.begin(), modulatorOutput.begin()+symbolSizeWithPrefx, rxSignal.begin()+symbolStart);\n\n    // Check if the symbol with prefix has been copied correctly\n    for(size_t i = 0 ; i < symbolSizeWithPrefx ; i++)\n    {\n        if(rxSignal[symbolStart+i] != modulatorOutput[i])\n        {\n            printf(\"Missmatch rxSignal[%lu]  = %f, symbolwithprefix[%lu] = %f \\n\" , symbolStart+i , rxSignal[symbolStart+i], i , modulatorOutput[i]);\n        }\n    }\n\n    auto start = std::chrono::steady_clock::now();\n    for(size_t i = 0; i < rxLastAllowedIndex; i++)\n    {\n        corellatorOutput[i] = detector.ExecuteCorrelator(rxSignal, i);\n    }\n    auto end = std::chrono::steady_clock::now();\n\n    std::cout << \"Cross-Corellator elapsed time: \"\n    << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()\n    << \" ns\" << std::endl;   \n\n    /*\n    // Plot modulator output, symbol\n    std::vector<double> modOutput(symbolSizeWithPrefx);\n    for(uint32_t i = 0; i < symbolSizeWithPrefx; i++) \n    {\n        modOutput.at(i) = modulatorOutput[i];\n    }\n\n    // Plot Corellator output\n    std::vector<double> corOutput(rxLastAllowedIndex);\n    // Copy Correlator output to vector\n    for(uint32_t i = 0; i < rxLastAllowedIndex; i++) \n    {\n        // Square Result to reduce noise\n        corOutput.at(i) = corellatorOutput[i] * corellatorOutput[i];\n    }\n\n\n    Gnuplot gp;\n    gp << \"plot '-' with line title 'Correlation'\\n\";\n    gp.send1d(corOutput);\n\n    Gnuplot gp1;\n    gp1 << \"plot '-' with line title 'Symbol with prefix'\\n\";\n    gp1.send1d(modOutput);\n    */\n    \n    // Find Peak in correlation\n    size_t peakIndex = 0;\n    double max = 0.0;\n    start = std::chrono::steady_clock::now();\n    for (size_t i = 0; i < corellatorOutput.size(); i++)\n    {\n        if(corellatorOutput[i] > max)\n        {\n            max = corellatorOutput[i];\n            peakIndex = i;\n        }\n    }\n    end = std::chrono::steady_clock::now();\n\n    std::cout << \"Peak Search elapsed time: \"\n    << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()\n    << \" ns\" << std::endl;   \n\n    // Check if the correlator max output is where the symbol was inserted\n    BOOST_CHECK_MESSAGE( (peakIndex == symbolStart), \n    \"Symbol start has not been detected correctly, The max correlation occurs at index =  \" << peakIndex );  \n        \n}\n\nBOOST_AUTO_TEST_CASE(SymbolStartTest)\n{\n    printf(\"\\nTesting Symbol Start Search...\\n\");\n\n    size_t nPoints = 512;\n    size_t symbolSize = nPoints*2;\n    size_t prefixSize = (int) (symbolSize / 8);\n    size_t symbolSizeWithPrefx = symbolSize + prefixSize;\n    size_t pilotToneStep = 8;\n    double pilotToneAmplitude = 2.0;\n    size_t energyDispersalSeed = 10;\n    size_t bitsPerSymbol = 2;\n\n    // Setup random float generator\n    srand( (unsigned)time( NULL ) );\n\n    // Create rx signal array to capable of holding 20 upsampled symbols with prefix\n    size_t  rxSignalSize = (symbolSizeWithPrefx * 10);\n    size_t  rxLastAllowedIndex = (symbolSizeWithPrefx * 9);\n\n    // Generate random index value for symbol start\n    size_t  symbolStart = rand() % rxLastAllowedIndex;\n    printf(\"Randomly Generated Symbol Start = %lu\\n\",symbolStart);\n\n    size_t nAvaiableifftPoints = (nPoints - (int)(nPoints/pilotToneStep));\n    size_t nMaxEncodedBytes = (int)((nAvaiableifftPoints *  bitsPerSymbol)  / 8);\n    size_t nData = nMaxEncodedBytes;\n\n    ByteVec txBytes(nData);\n    DoubleVec EncoderOutput(symbolSizeWithPrefx);\n    DoubleVec rxSignal(rxSignalSize);\n\n    // Initialize Encoder objects\n    QamModulator qam(nPoints, pilotToneStep, pilotToneAmplitude, energyDispersalSeed, bitsPerSymbol);\n    ofdmFFT ifft(nPoints, FFTW_BACKWARD, pilotToneStep);\n    NyquistModulator nyquistModulator(nPoints, ifft.out);\n       \n\n    // Initialize Decoder objects\n    ofdmFFT fft(nPoints, FFTW_FORWARD, pilotToneStep);\n    NyquistModulator nyquistDemodulator(nPoints, fft.in);    \n    Detector detector(nPoints, prefixSize, &fft, &nyquistDemodulator);\n\n    // Randomly fill ifft input\n    for(size_t i = 0; i < nData; i++)\n    {\n        txBytes[i] = rand() % 255;\n    }\n\n    // Encode one symbol \n    // (fftw_complex *) &output[GetSettings().cyclicPrefixSize]);\n    qam.Modulate(txBytes, (DoubleVec &) ifft.in, nData);\n    ifft.ComputeTransform( (fftw_complex *) &EncoderOutput[prefixSize]);\n    nyquistModulator.Modulate( EncoderOutput, prefixSize);\n    AddCyclicPrefix(EncoderOutput, symbolSize , prefixSize);\n\n    // Copy the symbol with prefix to Rx signal array\n    std::copy(EncoderOutput.begin(), EncoderOutput.begin()+symbolSizeWithPrefx, rxSignal.begin()+symbolStart);\n    // Check if the symbol with prefix has been copied correctly\n    for(size_t i = 0 ; i < symbolSizeWithPrefx ; i++)\n    {\n        if(rxSignal[symbolStart+i] != EncoderOutput[i])\n        {\n            printf(\"Missmatch rxSignal[%lu]  = %f, symbolwithprefix[%lu] = %f \\n\" , symbolStart+i , rxSignal[symbolStart+i], i , EncoderOutput[i]);\n        }\n    }\n\n    size_t CoarseSearchIndex = 0;\n    auto start = std::chrono::steady_clock::now();\n    CoarseSearchIndex = detector.CoarseSearch(rxSignal);\n    auto end = std::chrono::steady_clock::now();\n\n    std::cout << \"Coarse Search elapsed time: \"\n    << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()\n    << \" ns\" << std::endl;   \n  \n    // Check if the correlator max output is where the symbol was inserted\n    BOOST_CHECK_MESSAGE( (CoarseSearchIndex == symbolStart), \n    \"Symbol start has not been detected correctly, The peak occurs at index: \" << CoarseSearchIndex );\n\n    printf(\"Coarse Search Index = %lu\\n\", CoarseSearchIndex);\n\n    // Skip the prefix \n    size_t symbolStartIndex = CoarseSearchIndex + prefixSize;\n    printf(\"Symbol Start Index = %lu\\n\", symbolStartIndex);\n    // Randomly change the Coarse Start by up to +/- 9 indexes\n    size_t symbolStartOffsetIndex = symbolStartIndex + (rand() % 19 + (-9));\n\n    start = std::chrono::steady_clock::now();\n    size_t FineSearchSymbolIndex = detector.FineSearch(rxSignal, symbolStartOffsetIndex, nData);\n    end = std::chrono::steady_clock::now();\n\n    std::cout << \"Fine Search elapsed time: \"\n    << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()\n    << \" ns\" << std::endl;   \n\n    printf(\"Fine Search Index = %lu\\n\", FineSearchSymbolIndex);\n\n    // Check if the fine search corresponds to symbol start\n    BOOST_CHECK_MESSAGE( (FineSearchSymbolIndex == symbolStart+prefixSize), \n    \"Symbol start has not been detected correctly, The lowest img sum occurs at start index: \" << FineSearchSymbolIndex );  \n        \n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "5ed722b0173fcc36a056bdac8fce0199dd79737d", "size": 9887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/DetectorTest.cpp", "max_stars_repo_name": "krogk/ofdmlib", "max_stars_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T10:44:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T14:20:05.000Z", "max_issues_repo_path": "test/unit/DetectorTest.cpp", "max_issues_repo_name": "krogk/ofdmlib", "max_issues_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-11T12:50:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-11T12:51:02.000Z", "max_forks_repo_path": "test/unit/DetectorTest.cpp", "max_forks_repo_name": "krogk/ofdmlib", "max_forks_repo_head_hexsha": "7eddfdfde17624bf7674dda33ddc43b308c07765", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-03T14:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-03T14:56:19.000Z", "avg_line_length": 34.5699300699, "max_line_length": 169, "alphanum_fraction": 0.6748255285, "num_tokens": 2675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772220439509, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6083213138915117}}
{"text": "//=======================================================================\r\n// Copyright 2007 Aaron Windsor\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n#include <iostream>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\r\n\r\n\r\nint main(int argc, char** argv)\r\n{\r\n\r\n  // This program illustrates a simple use of boyer_myrvold_planar_embedding\r\n  // as a simple yes/no test for planarity.\r\n\r\n  using namespace boost;\r\n\r\n  typedef adjacency_list<vecS,\r\n                         vecS,\r\n                         undirectedS,\r\n                         property<vertex_index_t, int>\r\n                         > graph;\r\n\r\n  graph K_4(4);\r\n  add_edge(0, 1, K_4);\r\n  add_edge(0, 2, K_4);\r\n  add_edge(0, 3, K_4);\r\n  add_edge(1, 2, K_4);\r\n  add_edge(1, 3, K_4);\r\n  add_edge(2, 3, K_4);\r\n\r\n  if (boyer_myrvold_planarity_test(K_4))\r\n    std::cout << \"K_4 is planar.\" << std::endl;\r\n  else\r\n    std::cout << \"ERROR! K_4 should have been recognized as planar!\" \r\n          << std::endl;\r\n\r\n  graph K_5(5);\r\n  add_edge(0, 1, K_5);\r\n  add_edge(0, 2, K_5);\r\n  add_edge(0, 3, K_5);\r\n  add_edge(0, 4, K_5);\r\n  add_edge(1, 2, K_5);\r\n  add_edge(1, 3, K_5);\r\n  add_edge(1, 4, K_5);\r\n  add_edge(2, 3, K_5);\r\n  add_edge(2, 4, K_5);\r\n\r\n  // We've almost created a K_5 - it's missing one edge - so it should still\r\n  // be planar at this point.\r\n\r\n  if (boyer_myrvold_planarity_test(K_5))\r\n    std::cout << \"K_5 (minus an edge) is planar.\" << std::endl;\r\n  else\r\n    std::cout << \"ERROR! K_5 with one edge missing should\"\r\n              << \" have been recognized as planar!\" << std::endl;\r\n\r\n  // Now add the final edge...\r\n  add_edge(3, 4, K_5);\r\n  \r\n  if (boyer_myrvold_planarity_test(K_5))\r\n    std::cout << \"ERROR! K_5 was recognized as planar!\" << std::endl;\r\n  else\r\n    std::cout << \"K_5 is not planar.\" << std::endl;\r\n\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "c894c87fad8983caecf421958bab6fa9f68cc216", "size": 2057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/simple_planarity_test.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/graph/example/simple_planarity_test.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/graph/example/simple_planarity_test.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 28.9718309859, "max_line_length": 77, "alphanum_fraction": 0.5512882839, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6082869781977931}}
{"text": "// size.cpp : Calculates the size (or dimensions) of a Matrix\n//            Example: size(A)\n//  \n// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.\n// Author: James Quinlan\n//\n// This file is part of the HPRBLAS project, which is released under an MIT Open Source license.\n\n// COMMON LIBRARIES\n#include <iostream>\n#include <hprblas>\n\n// #include <boost/numeric/mtl/mtl.hpp>  // not needed for size, using for other tests.  remove in production\n\n// DEPENDENCIES\n#include <matpak/rowsto.hpp>\n#include <matpak/size.hpp>\n#include <boost/numeric/mtl/mtl.hpp>\n\n#include <generators/matrix_generators.hpp>\n\n// Selects posits or floats\n#define USE_POSIT 0\n\nint main ()\n{\n    // COMMON NAMESPACES\n\tusing namespace std;\n\tusing namespace mtl; using mtl::iall;\n\tusing namespace sw::unum;\n\tusing namespace sw::hprblas;\n\tusing namespace sw::hprblas::matpak;\n\t\n    cout << setprecision(5);\t\n\n \n\n\n#if USE_POSIT\n    \tconstexpr size_t nbits = 32;\n\t\tconstexpr size_t es = 2;\n\t\tusing Scalar = posit<nbits, es>;\n\t\tusing Matrix = mtl::mat::dense2D< Scalar >;\n\t\tcout << \"\\nUsing POSIT<\" << nbits << \",\" <<  es << \">\\n\" <<  endl;\n#else\t  \n\t\tusing Scalar = double;\n\t\tusing Matrix = mtl::mat::dense2D< Scalar >;\n#endif\n\n\n\t\tMatrix A = rowsto< Matrix >(7,7);   //\n\t\tcout << \"Matrix A = \\n\" << A << endl;\n\t\tcout <<  \"Size A = \" << size(A) << endl;\n\n\t//\tMatrix B = uniform_rand<Matrix>(6,6);\n\t//\tcout << \"Matrix B = \\n\" << B << endl;\n\n\n\t //submatrix from matrix per irange\n    using mtl::irange;\n    irange row(2, 4), col(1, 7);\n    dense2D<double> B1= A[row][col];\n\t std::cout << \"B1 is\\n\" << B1 << \"\\n\";\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "38f0ca932f3777d3cace5fc9b43d6641109185cc", "size": 1600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/matpak/size.cpp", "max_stars_repo_name": "fossabot/hpr-blas", "max_stars_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/matpak/size.cpp", "max_issues_repo_name": "fossabot/hpr-blas", "max_issues_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/matpak/size.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": 23.5294117647, "max_line_length": 109, "alphanum_fraction": 0.63875, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.7853085808877581, "lm_q1q2_score": 0.6082869700249237}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation, \n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file    Rot3Q.cpp\n * @brief   Rotation (internal: quaternion representation*)\n * @author  Richard Roberts\n */\n\n#ifdef GTSAM_DEFAULT_QUATERNIONS\n\n#include <boost/math/constants/constants.hpp>\n#include <gtsam/geometry/Rot3.h>\n\nusing namespace std;\n\nnamespace gtsam {\n\n\tstatic const Matrix I3 = eye(3);\n\n  /* ************************************************************************* */\n\tRot3::Rot3() : quaternion_(Quaternion::Identity()) {}\n\n  /* ************************************************************************* */\n\tRot3::Rot3(const Point3& r1, const Point3& r2, const Point3& r3) :\n      quaternion_((Eigen::Matrix3d() <<\n          r1.x(), r2.x(), r3.x(),\n          r1.y(), r2.y(), r3.y(),\n          r1.z(), r2.z(), r3.z()).finished()) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(double R11, double R12, double R13,\n      double R21, double R22, double R23,\n      double R31, double R32, double R33) :\n        quaternion_((Eigen::Matrix3d() <<\n            R11, R12, R13,\n            R21, R22, R23,\n            R31, R32, R33).finished()) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const Matrix& R) :\n      quaternion_(Eigen::Matrix3d(R)) {}\n\n//  /* ************************************************************************* */\n//   Rot3::Rot3(const Matrix3& R) :\n//       quaternion_(R) {}\n\n  /* ************************************************************************* */\n  Rot3::Rot3(const Quaternion& q) : quaternion_(q) {}\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Rx(double t) { return Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitX())); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Ry(double t) { return Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitY())); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::Rz(double t) { return Quaternion(Eigen::AngleAxisd(t, Eigen::Vector3d::UnitZ())); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::RzRyRx(double x, double y, double z) { return Rot3(\n      Quaternion(Eigen::AngleAxisd(z, Eigen::Vector3d::UnitZ())) *\n      Quaternion(Eigen::AngleAxisd(y, Eigen::Vector3d::UnitY())) *\n      Quaternion(Eigen::AngleAxisd(x, Eigen::Vector3d::UnitX())));\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::rodriguez(const Vector& w, double theta) {\n    return Quaternion(Eigen::AngleAxisd(theta, w)); }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::rodriguez(const Vector& w) {\n    double t = w.norm();\n    if (t < 1e-10) return Rot3();\n    return rodriguez(w/t, t);\n  }\n\n  /* ************************************************************************* */\n  bool Rot3::equals(const Rot3 & R, double tol) const {\n    return equal_with_abs_tol(matrix(), R.matrix(), tol);\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::compose(const Rot3& R2,\n  boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n    if (H1) *H1 = R2.transpose();\n    if (H2) *H2 = I3;\n    return Rot3(quaternion_ * R2.quaternion_);\n  }\n\n  /* ************************************************************************* */\n  Point3 Rot3::operator*(const Point3& p) const {\n    Eigen::Vector3d r = quaternion_ * Eigen::Vector3d(p.x(), p.y(), p.z());\n    return Point3(r(0), r(1), r(2));\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::inverse(boost::optional<Matrix&> H1) const {\n    if (H1) *H1 = -matrix();\n    return Rot3(quaternion_.inverse());\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::between(const Rot3& R2,\n  boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n    if (H1) *H1 = -(R2.transpose()*matrix());\n    if (H2) *H2 = I3;\n    return between_default(*this, R2);\n  }\n\n  /* ************************************************************************* */\n  Rot3 Rot3::operator*(const Rot3& R2) const {\n    return Rot3(quaternion_ * R2.quaternion_);\n  }\n\n  /* ************************************************************************* */\n  Point3 Rot3::rotate(const Point3& p,\n        boost::optional<Matrix&> H1,  boost::optional<Matrix&> H2) const {\n    Matrix R = matrix();\n    if (H1) *H1 = R * skewSymmetric(-p.x(), -p.y(), -p.z());\n    if (H2) *H2 = R;\n    Eigen::Vector3d r = R * p.vector();\n    return Point3(r.x(), r.y(), r.z());\n  }\n\n  /* ************************************************************************* */\n  // see doc/math.lyx, SO(3) section\n  Point3 Rot3::unrotate(const Point3& p,\n      boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n    const Matrix Rt(transpose());\n    Point3 q(Rt*p.vector()); // q = Rt*p\n    if (H1) *H1 = skewSymmetric(q.x(), q.y(), q.z());\n    if (H2) *H2 = Rt;\n    return q;\n  }\n\n  /* ************************************************************************* */\n  // Log map at identity - return the canonical coordinates of this rotation\n  Vector3 Rot3::Logmap(const Rot3& R) {\n    Eigen::AngleAxisd angleAxis(R.quaternion_);\n    if(angleAxis.angle() > M_PI)      // Important:  use the smallest possible\n      angleAxis.angle() -= 2.0*M_PI;  // angle, e.g. no more than PI, to keep\n    if(angleAxis.angle() < -M_PI)     // error continuous.\n      angleAxis.angle() += 2.0*M_PI;\n    return angleAxis.axis() * angleAxis.angle();\n  }\n\n  /* ************************************************************************* */\n\tRot3 Rot3::retract(const Vector& omega, Rot3::CoordinatesMode mode) const {\n\t\treturn compose(Expmap(omega));\n\t}\n\n\t/* ************************************************************************* */\n\tVector3 Rot3::localCoordinates(const Rot3& t2, Rot3::CoordinatesMode mode) const {\n\t\treturn Logmap(between(t2));\n\t}\n\n  /* ************************************************************************* */\n  Matrix3 Rot3::matrix() const { return quaternion_.toRotationMatrix(); }\n\n  /* ************************************************************************* */\n  Matrix3 Rot3::transpose() const { return quaternion_.toRotationMatrix().transpose(); }\n\n  /* ************************************************************************* */\n  Point3 Rot3::column(int index) const{\n    if(index == 3)\n      return r3();\n    else if(index == 2)\n      return r2();\n    else if(index == 1)\n      return r1(); // default returns r1\n    else\n      throw invalid_argument(\"Argument to Rot3::column must be 1, 2, or 3\");\n  }\n\n  /* ************************************************************************* */\n  Point3 Rot3::r1() const { return Point3(quaternion_.toRotationMatrix().col(0)); }\n\n  /* ************************************************************************* */\n  Point3 Rot3::r2() const { return Point3(quaternion_.toRotationMatrix().col(1)); }\n\n  /* ************************************************************************* */\n  Point3 Rot3::r3() const { return Point3(quaternion_.toRotationMatrix().col(2)); }\n\n  /* ************************************************************************* */\n  Vector3 Rot3::xyz() const {\n    Matrix I;Vector3 q;\n    boost::tie(I,q)=RQ(matrix());\n    return q;\n  }\n\n  /* ************************************************************************* */\n  Vector3 Rot3::ypr() const {\n  \tVector3 q = xyz();\n    return Vector3(q(2),q(1),q(0));\n  }\n\n  /* ************************************************************************* */\n  Vector3 Rot3::rpy() const {\n  \tVector3 q = xyz();\n    return Vector3(q(0),q(1),q(2));\n  }\n\n  /* ************************************************************************* */\n  Quaternion Rot3::toQuaternion() const { return quaternion_; }\n\n  /* ************************************************************************* */\n  pair<Matrix3, Vector3> RQ(const Matrix3& A) {\n\n    double x = -atan2(-A(2, 1), A(2, 2));\n    Rot3 Qx = Rot3::Rx(-x);\n    Matrix3 B = A * Qx.matrix();\n\n    double y = -atan2(B(2, 0), B(2, 2));\n    Rot3 Qy = Rot3::Ry(-y);\n    Matrix3 C = B * Qy.matrix();\n\n    double z = -atan2(-C(1, 0), C(1, 1));\n    Rot3 Qz = Rot3::Rz(-z);\n    Matrix3 R = C * Qz.matrix();\n\n    Vector xyz = Vector3(x, y, z);\n    return make_pair(R, xyz);\n  }\n\n} // namespace gtsam\n\n#endif\n", "meta": {"hexsha": "3a68e1a92a28c8ae872c42a9e9f25ad95532e65b", "size": 8847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Rot3Q.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "gtsam/geometry/Rot3Q.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/geometry/Rot3Q.cpp", "max_forks_repo_name": "sdmiller/gtsam_pcl", "max_forks_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T12:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:02:48.000Z", "avg_line_length": 37.3291139241, "max_line_length": 96, "alphanum_fraction": 0.4109867752, "num_tokens": 2082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6082767532930613}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_MEAN_HPP\n#define STAN_MATH_PRIM_MAT_FUN_MEAN_HPP\n\n#include <stan/math/prim/arr/err/check_nonzero_size.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <vector>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Returns the sample mean (i.e., average) of the coefficients\n     * in the specified standard vector.\n     * @param v Specified vector.\n     * @return Sample mean of vector coefficients.\n     * @throws std::domain_error if the size of the vector is less\n     * than 1.\n     */\n    template <typename T>\n    inline\n    typename boost::math::tools::promote_args<T>::type\n    mean(const std::vector<T>& v) {\n      check_nonzero_size(\"mean\", \"v\", v);\n      T sum(v[0]);\n      for (size_t i = 1; i < v.size(); ++i)\n        sum += v[i];\n      return sum / v.size();\n    }\n\n    /**\n     * Returns the sample mean (i.e., average) of the coefficients\n     * in the specified vector, row vector, or matrix.\n     * @param m Specified vector, row vector, or matrix.\n     * @return Sample mean of vector coefficients.\n     */\n    template <typename T, int R, int C>\n    inline\n    typename boost::math::tools::promote_args<T>::type\n    mean(const Eigen::Matrix<T, R, C>& m) {\n      check_nonzero_size(\"mean\", \"m\", m);\n      return m.mean();\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "5169570ee3e04d5d7b0ca925cbdaee2623399744", "size": 1342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/mean.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/mean.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/mean.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9583333333, "max_line_length": 66, "alphanum_fraction": 0.6318926975, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324893519999, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6082767532930612}}
{"text": "#ifdef PLOT_FIGURES\n\n#include <math.h>\n#include <armadillo>\n#include \"contrib/matplotlibcpp/matplotlibcpp.h\"\n\nnamespace plt = matplotlibcpp;\nusing namespace arma;\nusing namespace std;\nusing stdvec = std::vector<double>;\nusing stdnestedvec = std::vector<std::vector<double>>;\n\nstdvec arma_vec_to_std_vector(arma::mat x)\n{\n    return arma::conv_to<stdvec>::from(x);\n}\n\nstdnestedvec arma_mat_to_std_vec(arma::mat &A)\n{\n    stdnestedvec V(A.n_rows);\n    for (size_t i = 0; i < A.n_rows; ++i)\n    {\n        V[i] = arma::conv_to<stdvec>::from(A.row(i));\n    };\n    return V;\n};\n\nvoid plot_arma_vec(arma::mat x, long figure = 1, string title = \"\")\n{\n    plt::figure(figure);\n    plt::plot(arma_vec_to_std_vector(x));\n    plt::title(title);\n}\n\nvoid plot_arma_mat(arma::mat x, long figure = 1, string title = \"\")\n{\n    plt::figure(figure);\n    for (auto &&row : arma_mat_to_std_vec(x))\n    {\n        plt::plot(row);\n    }\n    plt::title(title);\n}\n\n#endif", "meta": {"hexsha": "256423108ec03cd9a6838e9bcffbd4f9ec86c2df", "size": 945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "samples/utils/plotting.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/plotting.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/plotting.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": 21.0, "max_line_length": 67, "alphanum_fraction": 0.6518518519, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6082767486910537}}
{"text": "#include <string>\n#include <vector>\n#include <random>\n#include <fmt/core.h>\n#include <cxxopts.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <zipfian_int_distribution.h>\n#include <ProgressBar.hpp>\n#include \"io.hpp\"\n\nboost::dynamic_bitset<> generateBitset(unsigned int universe,\n                                       unsigned int iterations,\n                                       std::string& distribution,\n                                       double param,\n                                       zipfian_int_distribution<unsigned int>::param_type p);\nstd::vector<unsigned int> bitsetToVector(boost::dynamic_bitset<>& bitset);\n\n// taken from zipfian_int_distribution.h (it's private)\ndouble zeta(unsigned long __n, double __theta);\n\nint main(int argc, char** argv)\n{\n    try {\n        std::string outputPath;\n        std::string distribution = \"uniform\";\n        unsigned int iterations = 10000000;\n        double bernoulliP = 0.5; // bernoulli probability\n        double stddev = 2.0; // standard deviation\n        unsigned int k = 100; // dataset cardinality\n        double skew = 0.9;\n\n        cxxopts::Options options(argv[0], \"Generate dataset\");\n\n        options.add_options()\n                (\"distribution\", \"Set element distribution {uniform|normal|bernoulli|zipf} (default: uniform)\", cxxopts::value<std::string>(distribution))\n                (\"output\", \"Output prefix name for the generated dataset\", cxxopts::value<std::string>(outputPath))\n                (\"prob\", \"Bernoulli probability\", cxxopts::value<double>(bernoulliP))\n                (\"stdev\", \"Standard Deviation for normal distribution (default: 2)\", cxxopts::value<double>(stddev))\n                (\"skew\", \"Theta (i.e. skew factor for zipf distribution)\", cxxopts::value<double>(skew))\n                (\"iterations\", \"Number of iterations (i.e. approximate set size, default: 10000000)\", cxxopts::value<unsigned int>(iterations))\n                (\"universe\", \"Universe cardinality\", cxxopts::value<unsigned long>())\n                (\"k\", \"Dataset size (i.e. number of sets)\", cxxopts::value<unsigned int>(k))\n                (\"help\", \"Print help\");\n\n        auto result = options.parse(argc, argv);\n\n        if (result.count(\"help\")) {\n            fmt::print(\"{}\\n\", options.help());\n            return 0;\n        }\n\n        if (!result.count(\"universe\")) {\n            fmt::print(\"{}\\n\", \"No universe given! Exiting...\");\n            return 1;\n        }\n\n\n        unsigned long universe = result[\"universe\"].as<unsigned long>();\n\n        if (!result.count(\"output\")) {\n            outputPath = \"out\";\n        }\n\n        // construct output name\n        std::string tmp = distribution + \"_\" + std::to_string(k) + \"_\" + std::to_string(universe);\n\n        double param = 0;\n\n        if (distribution == \"uniform\") {\n            tmp += \"_\" + std::to_string(iterations);\n        } else if (distribution == \"normal\") {\n            tmp += \"_\" + std::to_string(iterations) + \"_\" + std::to_string(stddev);\n            param = stddev;\n        } else if (distribution == \"bernoulli\") {\n            tmp += \"_\" + std::to_string(bernoulliP);\n            param = bernoulliP;\n        } else { // zipf\n            tmp += \"_\" + std::to_string(iterations) + \"_\" + std::to_string(skew);\n            param = skew;\n        }\n\n        tmp.append(\".bin\");\n\n        // construct dataset\n        std::vector<std::vector<unsigned int>> dataset;\n        dataset.reserve(k);\n\n        progresscpp::ProgressBar progressBar(k, 70, '#', '-');\n\n        unsigned long totalElements = 0;\n\n\n        zipfian_int_distribution<unsigned int>::param_type p;\n\n        if (distribution == \"zipf\") {\n            // calculate zeta just once\n            p = zipfian_int_distribution<unsigned int>::param_type(1, universe, param, zeta(universe, param));\n        }\n\n        for (unsigned int i = 0; i < k; ++i) {\n            boost::dynamic_bitset<> bitset = generateBitset(universe, iterations, distribution, param, p);\n            std::vector<unsigned int> set = bitsetToVector(bitset);\n            dataset.push_back(set);\n            totalElements += set.size();\n            ++progressBar;\n            progressBar.display();\n        }\n\n        progressBar.done();\n\n        fmt::print(\"Sorting sets in ascending order\\n\");\n\n        std::sort(dataset.begin(), dataset.end(), [](const std::vector<unsigned int>& a, const std::vector<unsigned int>& b) {\n            return a.size() < b.size();\n        });\n\n        std::string outname = outputPath + \"_asc_\" + tmp;\n        fmt::print(\"Writing dataset to {}\\n\", outname);\n        writeDataset(k, universe, totalElements, dataset, outname);\n\n        fmt::print(\"Sorting sets in descending order\\n\");\n\n        std::sort(dataset.begin(), dataset.end(), [](const std::vector<unsigned int>& a, const std::vector<unsigned int>& b) {\n            return a.size() > b.size();\n        });\n\n        outname = outputPath + \"_desc_\" + tmp;\n        fmt::print(\"Writing dataset to {}\\n\", outname);\n        writeDataset(k, universe, totalElements, dataset, outname);\n\n\n        fmt::print(\"Finished!\\n\");\n\n    } catch (const cxxopts::OptionException& e) {\n        fmt::print(\"{}\\n\", e.what());\n        return 1;\n    }\n    return 0;\n}\n\nboost::dynamic_bitset<> generateBitset(unsigned int universe,\n                                       unsigned int iterations,\n                                       std::string& distribution,\n                                       double param,\n                                       zipfian_int_distribution<unsigned int>::param_type p)\n{\n    boost::dynamic_bitset<> bitset(universe);\n\n    std::mt19937_64 gen(19937);\n\n    if (distribution == \"uniform\") {\n        std::uniform_int_distribution<> ud(1, universe);\n\n        for (unsigned int i = 0; i < iterations; ++i) {\n            bitset.set(std::round(ud(gen)));\n        }\n    } else if (distribution == \"normal\") {\n        std::normal_distribution<> nd(universe / 2, param);\n\n        for (unsigned int i = 0; i < iterations; ++i) {\n            bitset.set(std::round(nd(gen)));\n        }\n    } else if (distribution == \"bernoulli\") {\n        std::bernoulli_distribution bd(param);\n        for (unsigned int i = 0; i < universe; ++i) {\n            if (bd(gen)) {\n                bitset.set(i);\n            }\n        }\n    } else { // zipf distribution\n        zipfian_int_distribution<unsigned int> zipf(p);\n\n        for (unsigned int i = 0; i < iterations; ++i) {\n            bitset.set(zipf(gen));\n        }\n    }\n\n    return bitset;\n}\n\ndouble zeta(unsigned long __n, double __theta)\n{\n    double ans = 0.0;\n    for(unsigned long i = 1; i <= __n; ++i)\n        ans += std::pow(1.0 / i, __theta);\n    return ans;\n}\n\nstd::vector<unsigned int> bitsetToVector(boost::dynamic_bitset<>& bitset)\n{\n    std::vector<unsigned int> set;\n    set.reserve(bitset.count());\n    for (unsigned int i = 0; i < bitset.size(); ++i) {\n        if (bitset[i]) {\n            set.push_back(i + 1);\n        }\n    }\n    return set;\n}\n", "meta": {"hexsha": "d982e12e678ca7217e332a1d5f95ab83b35e56ee", "size": 6959, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "si-sycl/src/generate_dataset.cpp", "max_stars_repo_name": "zjin-lcf/HeCBench", "max_stars_repo_head_hexsha": "065976042cf3a472a45f133ab56a8f6d7492820c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2021-11-01T03:36:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:07:33.000Z", "max_issues_repo_path": "si-sycl/src/generate_dataset.cpp", "max_issues_repo_name": "zjin-lcf/HeCBench", "max_issues_repo_head_hexsha": "065976042cf3a472a45f133ab56a8f6d7492820c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-14T11:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T13:22:32.000Z", "max_forks_repo_path": "si-sycl/src/generate_dataset.cpp", "max_forks_repo_name": "zjin-lcf/HeCBench", "max_forks_repo_head_hexsha": "065976042cf3a472a45f133ab56a8f6d7492820c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-11-13T14:28:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T10:24:54.000Z", "avg_line_length": 34.795, "max_line_length": 154, "alphanum_fraction": 0.5552521914, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6082767440890462}}
{"text": "#include \"CameraCalibration.h\"\n#include \"CameraProjection.h\"\n#include \"vtkEigenTools.h\"\n\n#include <Eigen/Dense>\n\n//----------------------------------------------------------------------------\nint TestFisheyeModelCalibration(std::string matchedFilename, std::string groundtruthFilename)\n{\n  // relatively high epsilon since the data are stored\n  // in a .csv file with low digit\n  double epsilon = 1e-2;\n\n  // Load the 3D - 2D matches\n  std::vector<Eigen::Vector3d> X;\n  std::vector<Eigen::Vector2d> x;\n  LoadMatchesFromCSV(matchedFilename, X, x);\n  if (X.size() == 0)\n  {\n    return 0;\n  }\n\n  // Estimate the fisheye camera model parameters\n  Eigen::Matrix<double, 3, 4> P;\n  LinearPinholeCalibration(X, x, P);\n  Eigen::Matrix3d R, K;\n  Eigen::Vector3d T;\n  CalibrationMatrixDecomposition(P, K, R, T);\n  Eigen::Matrix<double, 11, 1> W;\n  GetParametersFromMatrix(K, R, T, W);\n  NonLinearPinholeCalibration(X, x, W);\n  Eigen::Matrix<double, 15, 1> Wf = Eigen::Matrix<double, 15, 1>::Zero();\n  for (int i = 0; i < 11; ++i)\n  {\n    Wf(i) = W(i);\n  }\n  NonLinearFisheyeCalibration(X, x, Wf);\n\n  // Load the expected parameters and test\n  Eigen::VectorXd Wg;\n  LoadCameraParamsFromCSV(groundtruthFilename, Wg);\n  for (int i = 0; i < 15; ++i)\n  {\n    if (std::abs(Wg(i) - Wf(i)) / std::abs(Wg(i)) > epsilon)\n    {\n      std::cout << \"Expected: \" << Wg(i) << \" got: \" << Wf(i) << std::endl;\n      return 0;\n    }\n  }\n  return 0;\n}\n\n//----------------------------------------------------------------------------\nint main(int argc, char* argv[])\n{\n  if (argc != 2)\n  {\n    return 0;\n  }\n\n  int errors = 0;\n\n  std::string fisheyeMatchesFilename = std::string(argv[1]) + \"/fisheye_camera.csv\";\n  std::string fisheyeGroundtruthFilename = std::string(argv[1]) + \"/FisheyeParamsExpected.csv\";\n  errors += TestFisheyeModelCalibration(fisheyeMatchesFilename, fisheyeGroundtruthFilename);\n\n  return errors;\n}\n", "meta": {"hexsha": "d1d184749d1295477453e9b069d765ebb22c95d2", "size": 1891, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "LidarPlugin/Testing/TestCameraCalibration.cxx", "max_stars_repo_name": "Pandinosaurus/LidarView", "max_stars_repo_head_hexsha": "9b9b2976e9ac5dcd891a604dabbb79bd6fc6a57a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T11:14:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-13T11:14:18.000Z", "max_issues_repo_path": "LidarPlugin/Testing/TestCameraCalibration.cxx", "max_issues_repo_name": "yxw027/LidarView", "max_issues_repo_head_hexsha": "9267729e62886a324ba7f2e3fed50db38b24f001", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LidarPlugin/Testing/TestCameraCalibration.cxx", "max_forks_repo_name": "yxw027/LidarView", "max_forks_repo_head_hexsha": "9267729e62886a324ba7f2e3fed50db38b24f001", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-30T10:07:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-30T10:07:35.000Z", "avg_line_length": 27.4057971014, "max_line_length": 95, "alphanum_fraction": 0.600740349, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.608262500281996}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Cholesky\n\n// #include <iostream>\n\n#include <random>\n#include <boost/test/unit_test.hpp>\n#include <geomc/linalg/Cholesky.h>\n\nusing namespace geom;\nusing namespace std;\n\ntypedef std::mt19937_64 rng_t;\n\n\ntemplate <typename T>\nSimpleMatrix<T,0,0> random_matrix(index_t sz, rng_t* rng) {\n    typedef std::normal_distribution<T> d_normal_t;\n    d_normal_t N = d_normal_t(0., 1); // (ctr, variance)\n    SimpleMatrix<T,0,0> mx(sz,sz);\n    \n    for (index_t r = 0; r < sz; ++r) {\n        for (index_t c = 0; c < sz; ++c) {\n            mx(r,c) = N(*rng);\n        }\n    }\n    return mx;\n}\n\n\ntemplate <typename T>\nT matrix_diff(const SimpleMatrix<T,0,0>& a, const SimpleMatrix<T,0,0>& b) {\n    BOOST_CHECK_EQUAL(a.rows(), b.rows());\n    BOOST_CHECK_EQUAL(a.cols(), b.cols());\n    \n    T residual = 0;\n    for (index_t r = 0; r < a.rows(); ++r) {\n        for (index_t c = 0; c < a.cols(); ++c) {\n            T z = a[r][c] - b[r][c];\n            residual += z * z;\n        }\n    }\n    return std::sqrt(residual);\n}\n\ntemplate <typename T>\nvoid run_cholesky(index_t sz, rng_t* rng) {\n    SimpleMatrix<T,0,0> mx = random_matrix<T>(sz, rng);\n    SimpleMatrix<T,0,0> mxT(sz, sz);\n    SimpleMatrix<T,0,0> A(sz, sz);\n    SimpleMatrix<T,0,0> C(sz, sz);\n    \n    // make mx a positive definite matrix `A` by taking mx * mx^T:\n    transpose(&mxT, mx);\n    mul(&A, mx, mxT);\n    \n    // cholesky decompose `A` into `mx`.\n    mtxcopy(&mx, A);\n    BOOST_CHECK(cholesky(&mx));\n    \n    // confirm `mx^T * mx = A`\n    transpose(&mxT, mx);\n    mul(&C, mx, mxT);\n    T rms = matrix_diff(C, A);\n    BOOST_CHECK_SMALL(rms, (T)1e-5);\n}\n\n\nBOOST_AUTO_TEST_SUITE(cholesky)\n\n\nBOOST_AUTO_TEST_CASE(verify_cholesky) {\n    rng_t rng(11937294775LL);\n    std::uniform_int_distribution<> rnd_int(2, 16);\n    const index_t n = 50000;\n    for (index_t i = 0; i < n; ++i) {\n        index_t k = rnd_int(rng);\n        run_cholesky<double>(k, &rng);\n    }\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3a349342720749b495f6e3faa70452fd44a54318", "size": 1992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "regression/cholesky.cpp", "max_stars_repo_name": "trbabb/geomc", "max_stars_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-07-22T20:33:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T00:16:16.000Z", "max_issues_repo_path": "regression/cholesky.cpp", "max_issues_repo_name": "trbabb/geomc", "max_issues_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-08-13T14:28:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-29T00:04:47.000Z", "max_forks_repo_path": "regression/cholesky.cpp", "max_forks_repo_name": "trbabb/geomc", "max_forks_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-10-03T10:30:55.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-06T18:14:18.000Z", "avg_line_length": 23.7142857143, "max_line_length": 75, "alphanum_fraction": 0.593373494, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.6082624847550782}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n    This is an example illustrating the use of the linear model predictive\n    control tool from the dlib C++ Library.  To explain what it does, suppose\n    you have some process you want to control and the process dynamics are\n    described by the linear equation:\n        x_{i+1} = A*x_i + B*u_i + C\n    That is, the next state the system goes into is a linear function of its\n    current state (x_i) and the current control (u_i) plus some constant bias or\n    disturbance.\n\n    A model predictive controller can find the control (u) you should apply to\n    drive the state (x) to some reference value, which is what we show in this\n    example.  In particular, we will simulate a simple vehicle moving around in\n    a planet's gravity.  We will use MPC to get the vehicle to fly to and then\n    hover at a certain point in the air.\n\n*/\n\n#include <dlib/gui_widgets.h>\n#include <dlib/control.h>\n#include <dlib/image_transforms.h>\n\nusing namespace std;\nusing namespace dlib;\n\n//  ----------------------------------------------------------------------------\n\nint main()\n{\n    const int STATES = 4;\n    const int CONTROLS = 2;\n\n    // The first thing we do is setup our vehicle dynamics model (A*x + B*u + C).\n    // Our state space (the x) will have 4 dimensions, the 2D vehicle position\n    // and also the 2D velocity.  The control space (u) will be just 2 variables\n    // which encode the amount of force we apply to the vehicle along each axis.\n    // Therefore, the A matrix defines a simple constant velocity model.\n    matrix<double,STATES,STATES> A;\n    A = 1, 0, 1, 0,  // next_pos = pos + velocity\n        0, 1, 0, 1,  // next_pos = pos + velocity\n        0, 0, 1, 0,  // next_velocity = velocity\n        0, 0, 0, 1;  // next_velocity = velocity\n\n    // Here we say that the control variables effect only the velocity. That is,\n    // the control applies an acceleration to the vehicle.\n    matrix<double,STATES,CONTROLS> B;\n    B = 0, 0,\n        0, 0,\n        1, 0,\n        0, 1;\n\n    // Let's also say there is a small constant acceleration in one direction.\n    // This is the force of gravity in our model.\n    matrix<double,STATES,1> C;\n    C = 0,\n        0,\n        0,\n        0.1;\n\n\n    const int HORIZON = 30;\n    // Now we need to setup some MPC specific parameters.  To understand them,\n    // let's first talk about how MPC works.  When the MPC tool finds the \"best\"\n    // control to apply it does it by simulating the process for HORIZON time\n    // steps and selecting the control that leads to the best performance over\n    // the next HORIZON steps.\n    //\n    // To be precise, each time you ask it for a control, it solves the\n    // following quadratic program:\n    //\n    //     min     sum_i trans(x_i-target_i)*Q*(x_i-target_i) + trans(u_i)*R*u_i\n    //    x_i,u_i\n    //\n    //     such that: x_0     == current_state\n    //                x_{i+1} == A*x_i + B*u_i + C\n    //                lower <= u_i <= upper\n    //                0 <= i < HORIZON\n    //\n    // and reports u_0 as the control you should take given that you are currently\n    // in current_state.  Q and R are user supplied matrices that define how we\n    // penalize variations away from the target state as well as how much we want\n    // to avoid generating large control signals.  We also allow you to specify\n    // upper and lower bound constraints on the controls.  The next few lines\n    // define these parameters for our simple example.\n\n    matrix<double,STATES,1> Q;\n    // Setup Q so that the MPC only cares about matching the target position and\n    // ignores the velocity.\n    Q = 1, 1, 0, 0;\n\n    matrix<double,CONTROLS,1> R, lower, upper;\n    R = 1, 1;\n    lower = -0.5, -0.5;\n    upper =  0.5,  0.5;\n\n    // Finally, create the MPC controller.\n    mpc<STATES,CONTROLS,HORIZON> controller(A,B,C,Q,R,lower,upper);\n\n\n    // Let's tell the controller to send our vehicle to a random location.  It\n    // will try to find the controls that makes the vehicle just hover at this\n    // target position.\n    dlib::rand rnd;\n    matrix<double,STATES,1> target;\n    target = rnd.get_random_double()*400,rnd.get_random_double()*400,0,0;\n    controller.set_target(target);\n\n\n    // Now let's start simulating our vehicle.  Our vehicle moves around inside\n    // a 400x400 unit sized world.\n    matrix<rgb_pixel> world(400,400);\n    image_window win;\n    matrix<double,STATES,1> current_state;\n    // And we start it at the center of the world with zero velocity.\n    current_state = 200,200,0,0;\n\n    int iter = 0;\n    while(!win.is_closed())\n    {\n        // Find the best control action given our current state.\n        matrix<double,CONTROLS,1> action = controller(current_state);\n        cout << \"best control: \" << trans(action);\n\n        // Now draw our vehicle on the world.  We will draw the vehicle as a\n        // black circle and its target position as a green circle.\n        assign_all_pixels(world, rgb_pixel(255,255,255));\n        const dpoint pos = point(current_state(0),current_state(1));\n        const dpoint goal = point(target(0),target(1));\n        draw_solid_circle(world, goal, 9, rgb_pixel(100,255,100));\n        draw_solid_circle(world, pos, 7, 0);\n        // We will also draw the control as a line showing which direction the\n        // vehicle's thruster is firing.\n        draw_line(world, pos, pos-50*action, rgb_pixel(255,0,0));\n        win.set_image(world);\n\n        // Take a step in the simulation\n        current_state = A*current_state + B*action + C;\n        dlib::sleep(100);\n\n        // Every 100 iterations change the target to some other random location.\n        ++iter;\n        if (iter > 100)\n        {\n            iter = 0;\n            target = rnd.get_random_double()*400,rnd.get_random_double()*400,0,0;\n            controller.set_target(target);\n        }\n    }\n}\n\n//  ----------------------------------------------------------------------------\n", "meta": {"hexsha": "13c55efa2de5b7f357809c089125e14b3a34d78f", "size": 6001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dlib/mpc_ex.cpp", "max_stars_repo_name": "SyllogismRXS/misc", "max_stars_repo_head_hexsha": "3cb29f15f45768f43c7cbb492addf9df812d47fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-11T10:35:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T10:35:12.000Z", "max_issues_repo_path": "src/dlib/mpc_ex.cpp", "max_issues_repo_name": "SyllogismRXS/misc", "max_issues_repo_head_hexsha": "3cb29f15f45768f43c7cbb492addf9df812d47fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dlib/mpc_ex.cpp", "max_forks_repo_name": "SyllogismRXS/misc", "max_forks_repo_head_hexsha": "3cb29f15f45768f43c7cbb492addf9df812d47fa", "max_forks_repo_licenses": ["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.9675324675, "max_line_length": 91, "alphanum_fraction": 0.6277287119, "num_tokens": 1557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.608262479122924}}
{"text": "// Copyright 2020 Xanadu Quantum Technologies Inc.\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/**\n * @file\n * \\rst\n * Contains tensor representations of supported gates in ``lightning.qubit``.\n * \\endrst\n */\n#pragma once\n\n#define _USE_MATH_DEFINES\n\n#include <iostream>\n#include <cmath>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\nusing Eigen::MatrixXd;\nusing Eigen::MatrixXcd;\nusing Eigen::VectorXcd;\nusing Eigen::Tensor;\n\nusing State_1q = Eigen::Tensor<std::complex<double>, 1>;\nusing State_2q = Eigen::Tensor<std::complex<double>, 2>;\nusing State_3q = Eigen::Tensor<std::complex<double>, 3>;\n\nusing Gate_1q = Eigen::Tensor<std::complex<double>, 2>;\nusing Gate_2q = Eigen::Tensor<std::complex<double>, 4>;\nusing Gate_3q = Eigen::Tensor<std::complex<double>, 6>;\n\nusing Pairs = Eigen::IndexPair<int>;\nusing Pairs_1q = Eigen::array<Pairs, 1>;\nusing Pairs_2q = Eigen::array<Pairs, 2>;\n\n\nconst double SQRT_2 = sqrt(2);\nconst std::complex<double> IMAG(0, 1);\nconst std::complex<double> NEGATIVE_IMAG(0, -1);\n\n/**\n* Generates the identity gate.\n*\n* @return the identity tensor\n*/\nGate_1q Identity() {\n    Gate_1q X(2, 2);\n    X.setValues({{1, 0}, {0, 1}});\n    return X;\n}\n\n/**\n* Generates the X gate.\n*\n* @return the X tensor\n*/\nGate_1q X() {\n    Gate_1q X(2, 2);\n    X.setValues({{0, 1}, {1, 0}});\n    return X;\n}\n\n/**\n* Generates the Y gate.\n*\n* @return the Y tensor\n*/\nGate_1q Y() {\n    Gate_1q Y(2, 2);\n    Y.setValues({{0, NEGATIVE_IMAG}, {IMAG, 0}});\n    return Y;\n}\n\n/**\n* Generates the Z gate.\n*\n* @return the Z tensor\n*/\nGate_1q Z() {\n    Gate_1q Z(2, 2);\n    Z.setValues({{1, 0}, {0, -1}});\n    return Z;\n}\n\n/**\n* Generates the H gate.\n*\n* @return the H tensor\n*/\nGate_1q H() {\n    Gate_1q H(2, 2);\n    H.setValues({{1/SQRT_2, 1/SQRT_2}, {1/SQRT_2, -1/SQRT_2}});\n    return H;\n}\n\n/**\n* Generates the S gate.\n*\n* @return the S tensor\n*/\nGate_1q S() {\n    Gate_1q S(2, 2);\n    S.setValues({{1, 0}, {0, IMAG}});\n    return S;\n}\n\n/**\n* Generates the T gate.\n*\n* @return the T tensor\n*/\nGate_1q T() {\n    Gate_1q T(2, 2);\n\n    const std::complex<double> exponent(0, M_PI/4);\n    T.setValues({{1, 0}, {0, std::pow(M_E, exponent)}});\n    return T;\n}\n\n/**\n* Generates the X rotation gate.\n*\n* @param parameter the rotation angle\n* @return the RX tensor\n*/\nGate_1q RX(const double& parameter) {\n    Gate_1q RX(2, 2);\n\n    const std::complex<double> c (std::cos(parameter / 2), 0);\n    const std::complex<double> js (0, std::sin(-parameter / 2));\n\n    RX.setValues({{c, js}, {js, c}});\n    return RX;\n}\n\n/**\n* Generates the Y rotation gate.\n*\n* @param parameter the rotation angle\n* @return the RY tensor\n*/\nGate_1q RY(const double& parameter) {\n    Gate_1q RY(2, 2);\n\n    const double c = std::cos(parameter / 2);\n    const double s = std::sin(parameter / 2);\n\n    RY.setValues({{c, -s}, {s, c}});\n    return RY;\n}\n\n/**\n* Generates the Z rotation gate.\n*\n* @param parameter the rotation angle\n* @return the RZ tensor\n*/\nGate_1q RZ(const double& parameter) {\n    Gate_1q RZ(2, 2);\n\n    const std::complex<double> exponent(0, -parameter/2);\n    const std::complex<double> exponent_second(0, parameter/2);\n    const std::complex<double> first = std::pow(M_E, exponent);\n    const std::complex<double> second = std::pow(M_E, exponent_second);\n\n    RZ.setValues({{first, 0}, {0, second}});\n    return RZ;\n}\n\n/**\n* Generates the phase-shift gate.\n*\n* @param parameter the phase shift\n* @return the phase-shift tensor\n*/\nGate_1q PhaseShift(const double& parameter) {\n    Gate_1q PhaseShift(2, 2);\n\n    const std::complex<double> exponent(0, parameter);\n    const std::complex<double> shift = std::pow(M_E, exponent);\n\n    PhaseShift.setValues({{1, 0}, {0, shift}});\n    return PhaseShift;\n}\n\n/**\n* Generates the arbitrary single qubit rotation gate.\n*\n* The rotation is achieved through three separate rotations:\n* \\f$R(\\phi, \\theta, \\omega)= RZ(\\omega)RY(\\theta)RZ(\\phi)\\f$.\n*\n* @param phi the first rotation angle\n* @param theta the second rotation angle\n* @param omega the third rotation angle\n* @return the rotation tensor\n*/\nGate_1q Rot(const double& phi, const double& theta, const double& omega) {\n    Gate_1q Rot(2, 2);\n\n    const std::complex<double> e00(0, (-phi - omega)/2);\n    const std::complex<double> e10(0, (-phi + omega)/2);\n    const std::complex<double> e01(0, (phi - omega)/2);\n    const std::complex<double> e11(0, (phi + omega)/2);\n\n    const std::complex<double> exp00 = std::pow(M_E, e00);\n    const std::complex<double> exp10 = std::pow(M_E, e10);\n    const std::complex<double> exp01 = std::pow(M_E, e01);\n    const std::complex<double> exp11 = std::pow(M_E, e11);\n\n    const double c = std::cos(theta / 2);\n    const double s = std::sin(theta / 2);\n\n    Rot.setValues({{exp00 * c, -exp01 * s}, {exp10 * s, exp11 * c}});\n\n    return Rot;\n}\n\n/**\n* Generates the CNOT gate.\n*\n* @return the CNOT tensor\n*/\nGate_2q CNOT() {\n    Gate_2q CNOT(2,2,2,2);\n    CNOT.setValues({{{{1, 0},{0, 0}},{{0, 1},{0, 0}}},{{{0, 0},{0, 1}},{{0, 0},{1, 0}}}});\n    return CNOT;\n}\n\n/**\n* Generates the SWAP gate.\n*\n* @return the SWAP tensor\n*/\nGate_2q SWAP() {\n    Gate_2q SWAP(2,2,2,2);\n    SWAP.setValues({{{{1, 0},{0, 0}},{{0, 0},{1, 0}}},{{{0, 1},{0, 0}},{{0, 0},{0, 1}}}});\n    return SWAP;\n}\n\n/**\n* Generates the CZ gate.\n*\n* @return the CZ tensor\n*/\nGate_2q CZ() {\n    Gate_2q CZ(2,2,2,2);\n    CZ.setValues({{{{1, 0},{0, 0}},{{0, 1},{0, 0}}},{{{0, 0},{1, 0}},{{0, 0},{0, -1}}}});\n    return CZ;\n}\n\n/**\n* Generates the Toffoli gate.\n*\n* @return the Toffoli tensor\n*/\nGate_3q Toffoli() {\n    Gate_3q Toffoli(2,2,2,2,2,2);\n    Toffoli.setValues({{{{{{1, 0},{0, 0}},{{0, 0},{0, 0}}},{{{0, 1},{0, 0}},{{0, 0},{0, 0}}}},\n            {{{{0, 0},{1, 0}},{{0, 0},{0, 0}}},{{{0, 0},{0, 1}},{{0, 0},{0, 0}}}}\n        },\n        {   {{{{0, 0},{0, 0}},{{1, 0},{0, 0}}},{{{0, 0},{0, 0}},{{0, 1},{0, 0}}}},\n            {{{{0, 0},{0, 0}},{{0, 0},{0, 1}}},{{{0, 0},{0, 0}},{{0, 0},{1, 0}}}}\n        }});\n    return Toffoli;\n}\n\n/**\n* Generates the CSWAP gate.\n*\n* @return the CSWAP tensor\n*/\nGate_3q CSWAP() {\n    Gate_3q CSWAP(2,2,2,2,2,2);\n    CSWAP.setValues({{{{{{1, 0},{0, 0}},{{0, 0},{0, 0}}},{{{0, 1},{0, 0}},{{0, 0},{0, 0}}}},\n            {{{{0, 0},{1, 0}},{{0, 0},{0, 0}}},{{{0, 0},{0, 1}},{{0, 0},{0, 0}}}}\n        },\n        {   {{{{0, 0},{0, 0}},{{1, 0},{0, 0}}},{{{0, 0},{0, 0}},{{0, 0},{1, 0}}}},\n            {{{{0, 0},{0, 0}},{{0, 1},{0, 0}}},{{{0, 0},{0, 0}},{{0, 0},{0, 1}}}}\n        }});\n    return CSWAP;\n}\n\n/**\n* Generates the controlled-X rotation gate.\n*\n* @param parameter the rotation angle\n* @return the CRX tensor\n*/\nGate_2q CRX(const double& parameter) {\n    Gate_2q CRX(2, 2, 2, 2);\n\n    const std::complex<double> c (std::cos(parameter / 2), 0);\n    const std::complex<double> js (0, std::sin(-parameter / 2));\n\n    CRX.setValues({{{{1, 0},{0, 0}},{{0, 1},{0, 0}}},{{{0, 0},{c, js}},{{0, 0},{js, c}}}});\n    return CRX;\n}\n\n/**\n* Generates the controlled-Y rotation gate.\n*\n* @param parameter the rotation angle\n* @return the CRY tensor\n*/\nGate_2q CRY(const double& parameter) {\n    Gate_2q CRY(2, 2, 2, 2);\n\n    const double c = std::cos(parameter / 2);\n    const double s = std::sin(parameter / 2);\n\n    CRY.setValues({{{{1, 0},{0, 0}},{{0, 1},{0, 0}}},{{{0, 0},{c, -s}},{{0, 0},{s, c}}}});\n    return CRY;\n}\n\n/**\n* Generates the controlled-Z rotation gate.\n*\n* @param parameter the rotation angle\n* @return the CRZ tensor\n*/\nGate_2q CRZ(const double& parameter) {\n    Gate_2q CRZ(2, 2, 2, 2);\n\n    const std::complex<double> exponent(0, -parameter/2);\n    const std::complex<double> exponent_second(0, parameter/2);\n    const std::complex<double> first = std::pow(M_E, exponent);\n    const std::complex<double> second = std::pow(M_E, exponent_second);\n\n    CRZ.setValues({{{{1, 0},{0, 0}},{{0, 1},{0, 0}}},{{{0, 0},{first, 0}},{{0, 0},{0, second}}}});\n    return CRZ;\n}\n\n/**\n* Generates the controlled rotation gate.\n*\n* This gate implements a rotation on a target qubit depending on a control qubit. The rotation\n* on the target qubit is achieved through three separate rotations:\n* \\f$R(\\phi, \\theta, \\omega)= RZ(\\omega)RY(\\theta)RZ(\\phi)\\f$.\n*\n* @param phi the first rotation angle\n* @param theta the second rotation angle\n* @param omega the third rotation angle\n* @return the controlled rotation tensor\n*/\nGate_2q CRot(const double& phi, const double& theta, const double& omega) {\n    Gate_2q CRot(2,2,2,2);\n\n    const std::complex<double> e00(0, (-phi - omega)/2);\n    const std::complex<double> e10(0, (-phi + omega)/2);\n    const std::complex<double> e01(0, (phi - omega)/2);\n    const std::complex<double> e11(0, (phi + omega)/2);\n\n    const std::complex<double> exp00 = std::pow(M_E, e00);\n    const std::complex<double> exp10 = std::pow(M_E, e10);\n    const std::complex<double> exp01 = std::pow(M_E, e01);\n    const std::complex<double> exp11 = std::pow(M_E, e11);\n\n    const double c = std::cos(theta / 2);\n    const double s = std::sin(theta / 2);\n\n    CRot.setValues({{{{1, 0},{0, 0}},{{0, 1},{0, 0}}},{{{0, 0},{exp00 * c, -exp01 * s}},\n            {{0, 0},{exp10 * s, exp11 * c}}\n        }});\n    return CRot;\n}\n\n\n// Creating aliases based on the function signatures of each operation\ntypedef Gate_1q (*pfunc_1q)();\ntypedef Gate_1q (*pfunc_1q_one_param)(const double&);\ntypedef Gate_1q (*pfunc_1q_three_params)(const double&, const double&, const double&);\n\ntypedef Gate_2q (*pfunc_2q)();\ntypedef Gate_2q (*pfunc_2q_one_param)(const double&);\ntypedef Gate_2q (*pfunc_2q_three_params)(const double&, const double&, const double&);\n\ntypedef Gate_3q (*pfunc_3q)();\n\n// Defining the operation maps\nconst std::map<std::string, pfunc_1q> OneQubitOps = {\n    {\"Identity\", Identity},\n    {\"PauliX\", X},\n    {\"PauliY\", Y},\n    {\"PauliZ\", Z},\n    {\"Hadamard\", H},\n    {\"S\", S},\n    {\"T\", T}\n};\n\nconst std::map<std::string, pfunc_1q_one_param> OneQubitOpsOneParam = {\n    {\"RX\", RX},\n    {\"RY\", RY},\n    {\"RZ\", RZ},\n    {\"PhaseShift\", PhaseShift}\n};\n\nconst std::map<std::string, pfunc_1q_three_params> OneQubitOpsThreeParams = {\n    {\"Rot\", Rot}\n};\n\n\nconst std::map<std::string, pfunc_2q> TwoQubitOps = {\n    {\"CNOT\", CNOT},\n    {\"SWAP\", SWAP},\n    {\"CZ\", CZ}\n};\n\nconst std::map<std::string, pfunc_2q_one_param> TwoQubitOpsOneParam = {\n    {\"CRX\", CRX},\n    {\"CRY\", CRY},\n    {\"CRZ\", CRZ}\n};\n\nconst std::map<std::string, pfunc_2q_three_params> TwoQubitOpsThreeParams = {\n    {\"CRot\", CRot}\n};\n\nconst std::map<std::string, pfunc_3q> ThreeQubitOps = {\n    {\"Toffoli\", Toffoli},\n    {\"CSWAP\", CSWAP}\n};\n", "meta": {"hexsha": "6983ab327d8fc189cb4bfbcf3a25f6dcb8611c0b", "size": 10948, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pennylane_lightning/src/operations.hpp", "max_stars_repo_name": "ThomasLoke/pennylane-lightning", "max_stars_repo_head_hexsha": "2eac157abb47413d761a3c89f16b8089833952b9", "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": "pennylane_lightning/src/operations.hpp", "max_issues_repo_name": "ThomasLoke/pennylane-lightning", "max_issues_repo_head_hexsha": "2eac157abb47413d761a3c89f16b8089833952b9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pennylane_lightning/src/operations.hpp", "max_forks_repo_name": "ThomasLoke/pennylane-lightning", "max_forks_repo_head_hexsha": "2eac157abb47413d761a3c89f16b8089833952b9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-25T19:35:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T19:35:20.000Z", "avg_line_length": 25.3425925926, "max_line_length": 98, "alphanum_fraction": 0.5991048593, "num_tokens": 3788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6082252373673195}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2020-2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGY_CARTESIAN_SIDE_NON_ROBUST_HPP\n#define BOOST_GEOMETRY_STRATEGY_CARTESIAN_SIDE_NON_ROBUST_HPP\n\n#include <boost/geometry/util/select_most_precise.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/util/precise_math.hpp>\n\n#include <boost/geometry/arithmetic/determinant.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace side\n{\n\n/*!\n\\brief Predicate to check at which side of a segment a point lies:\n    left of segment (>0), right of segment (< 0), on segment (0).\n\\ingroup strategies\n\\tparam CalculationType \\tparam_calculation\n\\details This predicate determines at which side of a segment a point lies\n*/\ntemplate\n<\n    typename CalculationType = void\n>\nstruct side_non_robust\n{\npublic:\n    //! \\brief Computes double the signed area of the CCW triangle p1, p2, p\n    template\n    <\n        typename P1,\n        typename P2,\n        typename P\n    >\n    static inline int apply(P1 const& p1, P2 const& p2, P const& p)\n    {\n        typedef typename select_calculation_type_alt\n            <\n                CalculationType,\n                P1,\n                P2,\n                P\n            >::type CoordinateType;\n        typedef typename select_most_precise\n            <\n                CoordinateType,\n                double\n            >::type PromotedType;\n\n        CoordinateType const x = get<0>(p);\n        CoordinateType const y = get<1>(p);\n\n        CoordinateType const sx1 = get<0>(p1);\n        CoordinateType const sy1 = get<1>(p1);\n        CoordinateType const sx2 = get<0>(p2);\n        CoordinateType const sy2 = get<1>(p2);\n\n        //non-robust 1\n        //the following is 2x slower in some generic cases when compiled with g++\n        //(tested versions 9 and 10)\n        //\n        //auto detleft = (sx1 - x) * (sy2 - y);\n        //auto detright = (sy1 - y) * (sx2 - x);\n        //return detleft > detright ? 1 : (detleft < detright ? -1 : 0 );\n\n        //non-robust 2\n        PromotedType const dx = sx2 - sx1;\n        PromotedType const dy = sy2 - sy1;\n        PromotedType const dpx = x - sx1;\n        PromotedType const dpy = y - sy1;\n\n        PromotedType sv = geometry::detail::determinant<PromotedType>\n                (\n                    dx, dy,\n                    dpx, dpy\n                );\n        PromotedType const zero = PromotedType();\n\n        return sv == 0 ? 0 : sv > zero ? 1 : -1;\n    }\n\n};\n\n}} // namespace strategy::side\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGY_CARTESIAN_SIDE_NON_ROBUST_HPP\n", "meta": {"hexsha": "9400f9bd6a18a64e9ea8593163eb594d5acc5635", "size": 2822, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/strategy/cartesian/side_non_robust.hpp", "max_stars_repo_name": "jhypolite/geometry", "max_stars_repo_head_hexsha": "f79b3f0c457bc4ae4bb1c1cb5a117efbe97be3c4", "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/geometry/strategy/cartesian/side_non_robust.hpp", "max_issues_repo_name": "jhypolite/geometry", "max_issues_repo_head_hexsha": "f79b3f0c457bc4ae4bb1c1cb5a117efbe97be3c4", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/geometry/strategy/cartesian/side_non_robust.hpp", "max_forks_repo_name": "jhypolite/geometry", "max_forks_repo_head_hexsha": "f79b3f0c457bc4ae4bb1c1cb5a117efbe97be3c4", "max_forks_repo_licenses": ["BSL-1.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.22, "max_line_length": 81, "alphanum_fraction": 0.6218993622, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6081841450245391}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Marc Glisse\n *\n *    Copyright (C) 2020 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n\n#include <boost/range/iterator_range.hpp>\n\n#include <wasserstein.h> // Hera\n\n#include <array>\n\nnamespace py = pybind11;\ntypedef py::array_t<double, py::array::c_style | py::array::forcecast> Dgm;\n\ndouble wasserstein_distance(\n    Dgm d1, Dgm d2,\n    double wasserstein_power, double internal_p,\n    double delta)\n{\n  py::buffer_info buf1 = d1.request();\n  py::buffer_info buf2 = d2.request();\n  // shape (n,2) or (0) for empty\n  if((buf1.ndim!=2 || buf1.shape[1]!=2) && (buf1.ndim!=1 || buf1.shape[0]!=0))\n    throw std::runtime_error(\"Diagram 1 must be an array of size n x 2\");\n  if((buf2.ndim!=2 || buf2.shape[1]!=2) && (buf2.ndim!=1 || buf2.shape[0]!=0))\n    throw std::runtime_error(\"Diagram 2 must be an array of size n x 2\");\n  typedef std::array<double, 2> Point;\n  auto p1 = (Point*)buf1.ptr;\n  auto p2 = (Point*)buf2.ptr;\n  auto diag1 = boost::make_iterator_range(p1, p1+buf1.shape[0]);\n  auto diag2 = boost::make_iterator_range(p2, p2+buf2.shape[0]);\n\n  hera::AuctionParams<double> params;\n  params.wasserstein_power = wasserstein_power;\n  // hera encodes infinity as -1...\n  if(std::isinf(internal_p)) internal_p = hera::get_infinity<double>();\n  params.internal_p = internal_p;\n  params.delta = delta;\n  // The extra parameters are purposedly not exposed for now.\n  return hera::wasserstein_dist(diag1, diag2, params);\n}\n\nPYBIND11_MODULE(hera, m) {\n      m.def(\"wasserstein_distance\", &wasserstein_distance,\n          py::arg(\"X\"), py::arg(\"Y\"),\n          py::arg(\"order\") = 1,\n          py::arg(\"internal_p\") = std::numeric_limits<double>::infinity(),\n          py::arg(\"delta\") = .01,\n          R\"pbdoc(\n        Compute the Wasserstein distance between two diagrams.\n        Points at infinity are supported.\n\n        Parameters:\n            X (n x 2 numpy array): First diagram\n            Y (n x 2 numpy array): Second diagram\n            order (float): Wasserstein exponent W_q\n            internal_p (float): Internal Minkowski norm L^p in R^2\n            delta (float): Relative error 1+delta\n\n        Returns:\n            float: Approximate Wasserstein distance W_q(X,Y)\n    )pbdoc\");\n}\n", "meta": {"hexsha": "0d562b4c6222ae2d4bfa56a28f246e961fcb7cc2", "size": 2520, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/python/gudhi/hera.cc", "max_stars_repo_name": "gtauzin/gudhi-devel", "max_stars_repo_head_hexsha": "d7f8038ac312c96b9331786f54802b0191fdee45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/python/gudhi/hera.cc", "max_issues_repo_name": "gtauzin/gudhi-devel", "max_issues_repo_head_hexsha": "d7f8038ac312c96b9331786f54802b0191fdee45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/python/gudhi/hera.cc", "max_forks_repo_name": "gtauzin/gudhi-devel", "max_forks_repo_head_hexsha": "d7f8038ac312c96b9331786f54802b0191fdee45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0, "max_line_length": 101, "alphanum_fraction": 0.6476190476, "num_tokens": 724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6081841372406589}}
{"text": "/** @file GammaDist.cpp\n * @author Mark J. Olah (mjo\\@cs.unm DOT edu)\n * @date 2017-2019\n * @brief GammaDist class definition\n * \n */\n#include \"PriorHessian/GammaDist.h\"\n#include \"PriorHessian/util.h\"\n#include \"PriorHessian/PriorHessianError.h\"\n\n#include <cmath>\n#include <sstream>\n#include <limits>\n\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace prior_hessian {\n\nconst StringVecT GammaDist::_param_names = { \"scale\", \"shape\" };\nconst GammaDist::NparamsVecT GammaDist::_param_lbound = {0, 0}; //Lower bound on valid parameter values \nconst GammaDist::NparamsVecT GammaDist::_param_ubound = {INFINITY, INFINITY}; //Upper bound on valid parameter values\n\n\n/* Constructors */\nGammaDist::GammaDist(double scale, double shape) \n    : UnivariateDist(),\n      _scale(checked_scale(scale)),\n      _shape(checked_shape(shape)),\n      llh_const_initialized(false)\n{ }\n\n/* Non-static member functions */\n\nvoid GammaDist::set_scale(double val) \n{ \n    _scale = checked_scale(val); \n    llh_const_initialized = false;\n}\n\nvoid GammaDist::set_shape(double val) \n{ \n    _shape = checked_shape(val); \n    llh_const_initialized = false;\n}\n\nvoid GammaDist::set_params(double scale, double shape) \n{ \n    _scale = checked_scale(scale);  \n    _shape = checked_shape(shape); \n    llh_const_initialized = false;\n}\n\ndouble GammaDist::cdf(double x) const\n{\n   return boost::math::gamma_p(_shape, x / _scale);\n}\n\ndouble GammaDist::icdf(double u) const\n{\n    if(u == 0) return 0;\n    if(u == 1) return INFINITY;\n    return boost::math::gamma_p_inv(_shape, u) * _scale;\n}\n\ndouble GammaDist::pdf(double x) const\n{\n    if(x==0) return 0;\n    double inv_scale = 1/_scale;\n    return boost::math::gamma_p_derivative(_shape, x*inv_scale) * inv_scale;\n}\n\ndouble GammaDist::llh(double x) const \n{ \n    if(!llh_const_initialized) initialize_llh_const();\n    return rllh(x) + llh_const; \n}\n\nvoid GammaDist::initialize_llh_const() const\n{\n    llh_const = compute_llh_const(shape(),scale());\n    llh_const_initialized = true;\n}\n\ndouble GammaDist::compute_llh_const(double shape, double scale)\n{\n    return -shape*log(scale) - std::lgamma(shape);\n}\n\ndouble GammaDist::checked_scale(double val)\n{\n    if(!std::isfinite(val) || val <= 0) {\n        std::ostringstream msg;\n        msg<<\"GammaDist: got bad scale value:\"<<val;\n        throw ParameterValueError(msg.str());\n    }\n    return val;\n}\n\ndouble GammaDist::checked_shape(double val)\n{\n    if(!std::isfinite(val) || val <= 0) {\n        std::ostringstream msg;\n        msg<<\"GammaDist: got bad shape value:\"<<val;\n        throw ParameterValueError(msg.str());\n    }\n    return val;\n}\n\n} /* namespace prior_hessian */\n", "meta": {"hexsha": "746de57761eda393f69b235b2c2108dd1fa64ea8", "size": 2645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GammaDist.cpp", "max_stars_repo_name": "markjolah/PriorHessianLib", "max_stars_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-20T07:40:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T07:40:29.000Z", "max_issues_repo_path": "src/GammaDist.cpp", "max_issues_repo_name": "markjolah/PriorHessianLib", "max_issues_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GammaDist.cpp", "max_forks_repo_name": "markjolah/PriorHessianLib", "max_forks_repo_head_hexsha": "dc38e88b36752990145962305566c86c4457efe8", "max_forks_repo_licenses": ["Apache-2.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.0454545455, "max_line_length": 117, "alphanum_fraction": 0.6877126654, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6081838178071599}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// vector_space::functional::l2_distance_squared.hpp                         //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_VECTOR_SPACE_FUNCTIONAL_l2_DISTANCE_SQUARED_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_VECTOR_SPACE_FUNCTIONAL_l2_DISTANCE_SQUARED_HPP_ER_2009\n#include <cmath>\n#include <numeric>\n#include <functional>\n#include <boost/type_traits.hpp>\n#include <boost/function.hpp>\n#include <boost/call_traits.hpp>\n#include <boost/range.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/bind.hpp>\n#include <boost/math/tools/precision.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace vector_space{\n\n    // Stores a range r, and when passed another range r1, computes the squared\n    // Euclidian distance of r-r1.\n    //\n    // Examples: \n    // R == const std::vector<double>& \n    // R == iterator_range<std::vector<double> >\n    template<typename R>\n    class l2_distance_squared{\n        typedef typename is_reference<R>::type is_ref_;\n    public:\n        typedef typename remove_reference<R>::type const_range_type;\n        typedef typename remove_const<const_range_type>::type range_type;\n        typedef typename range_value<range_type>::type result_type;\n                    \n        // Constructor\n        l2_distance_squared(){} // Warning, x_ not initialized\n        l2_distance_squared(typename call_traits<R>::param_type x);\n        l2_distance_squared(const l2_distance_squared& that);\n        l2_distance_squared& operator=(const l2_distance_squared& that);                    \n\n        // Call\n        template<typename R1> \n        result_type operator()(const R1& y)const;\n                        \n        private:\n        typename call_traits<R>::value_type x_;\n    };\n    \n    template<typename R> \n    l2_distance_squared<R> \n    make_l2_distance_squared(const R& x){\n        return l2_distance_squared<R>(x);\n    }\n\n    // Definitions\n    template<typename R>\n    l2_distance_squared<R>::l2_distance_squared(\n        typename call_traits<R>::param_type x\n    ):x_(x){}\n\n    template<typename R>\n    l2_distance_squared<R>::l2_distance_squared(\n        const l2_distance_squared& that\n    ):x_(that.x_){}\n\n    template<typename R>\n    l2_distance_squared<R>& \n    l2_distance_squared<R>::operator=(const l2_distance_squared& that){\n        if(&that != this){\n            x_ = that.x_;\n        }\n        return *this;\n    }\n    \n    template<typename R>\n    template<typename R1> \n    typename l2_distance_squared<R>::result_type \n    l2_distance_squared<R>::operator()(const R1& y)const{\n        BOOST_ASSERT( \n            size(x_) == size(y) \n        );\n        return std::inner_product(\n            begin(y),\n            end(y),\n            begin(x_),\n            static_cast<result_type>(0),\n            std::plus<result_type>(),\n            (lambda::_1 - lambda::_2) * (lambda::_1 - lambda::_2)\n        );\n    };\n\n}// vector_space\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "b2535aae5306e1bf3b423a10a2e6ad16784b3d82", "size": 3404, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vector_space/boost/vector_space/functional/l2_distance_squared.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vector_space/boost/vector_space/functional/l2_distance_squared.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vector_space/boost/vector_space/functional/l2_distance_squared.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3725490196, "max_line_length": 92, "alphanum_fraction": 0.5943008226, "num_tokens": 721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6081740039444695}}
{"text": "#ifndef NODEUTILS_HPP\n#define NODEUTILS_HPP\n\n#include <type_traits>\n\n#include <geometry_msgs/PointStamped.h>\n#include <ros/ros.h>\n#include <Eigen/Dense>\n#include <cmath>\n#include <tuple>\n\n#include <ros/ros.h>\n\nnamespace igvc\n{\n/**\nCalculates euclidian distance between two points\n\n@tparam T the data type of the input points to calculate the euclidian distance for\n@param[in] x1 x value of first point\n@param[in] y1 y value of first point\n@param[in] x2 x value of second point\n@param[in] y2 y value of second point\n@return the euclidian distance between both points\n*/\ntemplate <typename T>\ninline T get_distance(T x1, T y1, T x2, T y2)\n{\n  return std::hypot(x2 - x1, y2 - y1);\n}\n\n/**\nCalculates euclidian distance between two points\n\n@tparam T the data type of the input points to calculate the euclidian distance for\n@param[in] p1 the <x,y> coords of the first point\n@param[in] p2 the <x,y> coords of the second point\n@return the euclidian distance between both points\n*/\ninline double get_distance(const geometry_msgs::Point& p1, const geometry_msgs::Point& p2)\n{\n  return igvc::get_distance(p1.x, p1.y, p2.x, p2.y);\n}\n\n/**\nCalculates euclidian distance between two points, taking tuples for each\n(x,y) point as arguments\n\n@tparam T the data type contained within each input tuple\n@param[in] p1 the first point\n@param[in] p2 the second point\n@return the euclidian distance between both points\n*/\ntemplate <typename T>\ninline T get_distance(const std::tuple<T, T>& p1, const std::tuple<T, T>& p2)\n{\n  return igvc::get_distance(std::get<0>(p1), std::get<1>(p1), std::get<0>(p2), std::get<1>(p2));\n}\n\n/**\nsymmetric round up\nBias: away from zero\n\n@tparam T the data type to round up\n@param[in] the value to round up\n@return the value rounded away from zero\n*/\ntemplate <typename T>\nT ceil0(const T& value)\n{\n  return (value < 0.0) ? std::floor(value) : std::ceil(value);\n}\n\n/**\nAdjust angle to lie within the polar range [-PI, PI]\n*/\ninline void fit_to_polar(double& angle)\n{\n  angle = std::fmod(angle, 2 * M_PI);\n  if (angle > M_PI)\n  {\n    angle -= 2 * M_PI;\n  }\n  else if (angle < -M_PI)\n  {\n    angle += 2 * M_PI;\n  }\n}\n\n/**\nComputes the egocentric polar angle of vec2 wrt vec1 in 2D, that is:\n  - clockwise: negative\n  - counter-clockwise: positive\n\nsource: https://stackoverflow.com/questions/14066933/direct-way-of-computing-clockwise-angle-between-2-vectors\n\n@param[in] angle the double variable to assign the computed angle to\n@param[in] vec2 the vector the angle is computed with respect to\n@param[in] vec1 the reference vector\n*/\ninline void compute_angle(double& angle, Eigen::Vector3d vec2, Eigen::Vector3d vec1)\n{\n  double dot = vec2[0] * vec1[0] + vec2[1] * vec1[1];  // dot product - proportional to cos\n  double det = vec2[0] * vec1[1] - vec2[1] * vec1[0];  // determinant - proportional to sin\n\n  angle = atan2(det, dot);\n}\n\n}  // namespace igvc\n#endif\n", "meta": {"hexsha": "4cafe88b6ed76f0ba9ab7cfb9ed43260c5f1a40f", "size": 2870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "igvc_utils/include/igvc_utils/NodeUtils.hpp", "max_stars_repo_name": "jiajunmao/igvc-software", "max_stars_repo_head_hexsha": "ea1b11d9bb20e85e5f47aa03f930e9b65877d80c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2015-01-28T23:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T05:31:36.000Z", "max_issues_repo_path": "igvc_utils/include/igvc_utils/NodeUtils.hpp", "max_issues_repo_name": "jiajunmao/igvc-software", "max_issues_repo_head_hexsha": "ea1b11d9bb20e85e5f47aa03f930e9b65877d80c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 600.0, "max_issues_repo_issues_event_min_datetime": "2015-01-11T20:27:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T21:53:01.000Z", "max_forks_repo_path": "igvc_utils/include/igvc_utils/NodeUtils.hpp", "max_forks_repo_name": "jiajunmao/igvc-software", "max_forks_repo_head_hexsha": "ea1b11d9bb20e85e5f47aa03f930e9b65877d80c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 157.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T00:02:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-13T01:12:20.000Z", "avg_line_length": 25.8558558559, "max_line_length": 110, "alphanum_fraction": 0.7132404181, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.6081739832027253}}
{"text": "#include <boost/test/unit_test.hpp>\n#include <boost/test/data/test_case.hpp>\n#include <boost/test/data/monomorphic.hpp>\n\n#include \"tinymp.cpp\"\n#include \"rational.cpp\"\n\nnamespace utf = boost::unit_test;\n\nBOOST_AUTO_TEST_CASE( rational_construct )\n{\n\trational<short> rs1, rs2(1), rs3(0, 2);\n\trational<int> ri1, ri2(1), ri3(0, 2), ri4(rs3);\n\trational<tinymp> rt1, rt2(5), rt3(1, 5), rt4(-rt3), rt5(rs3), rt6(ri3);\n\tBOOST_TEST( rs3 == ri4 );\n\tBOOST_TEST( ri4 == rs3 );\n\tBOOST_TEST( ri3 == rt6 );\n\tBOOST_TEST( rt6 == ri3 );\n\tBOOST_TEST( rs3 == rt5 );\n\tBOOST_TEST( rt5 == rs3 );\n}\n\nconst int LT = 0, EQ = 1, GT = 2;\nstruct comparison\n{\n\tint ln, ld, rn, rd;\n\tint type;\n};\nstd::ostream& operator<<(std::ostream &os, const comparison& v)\n{\n\treturn os << v.ln << '/' << v.ld << ',' << v.rn << '/' << v.rd << ':' << v.type;\n}\n\ncomparison cases[] = {\n\t{ -1, 0,  2, 0, LT },\n\t{  2, 0, -1, 0, GT },\n\t{  1, 0,  2, 0, EQ },\n\t{  2, 0,  1, 0, EQ },\n\t{ -1, 0, -2, 0, EQ },\n\t{ -2, 0, -1, 0, EQ },\n\n\t{  1, 1,  2, 2, EQ },\n\t{  2, 2,  1, 1, EQ },\n\t{ -1, 1, -2, 2, EQ },\n\t{ -2, 2, -1, 1, EQ },\n\t{  0, 1,  0, 2, EQ },\n\t{  0, 2,  0, 1, EQ },\n\n\t{ -2, 1, -1, 1, LT },\n\t{ -1, 1,  2, 1, LT },\n\t{ -1, 1,  0, 1, LT },\n\t{  0, 1,  1, 1, LT },\n\t{  1, 1,  2, 1, LT },\n\t{ -4, 2, -1, 1, LT },\n\t{ -1, 1,  4, 2, LT },\n\t{ -2, 2,  0, 1, LT },\n\t{  0, 1,  2, 2, LT },\n\t{  2, 2,  2, 1, LT },\n\n\t{ -2, 1, -3, 1, GT },\n\t{  1, 1, -2, 1, GT },\n\t{  0, 1, -2, 1, GT },\n\t{  3, 1,  0, 1, GT },\n\t{  3, 1,  2, 1, GT },\n\t{ -4, 2, -3, 1, GT },\n\t{  1, 1, -4, 2, GT },\n\t{  0, 2, -4, 1, GT },\n\t{  4, 2,  0, 2, GT },\n\t{  6, 2,  2, 1, GT }\n};\n\nBOOST_DATA_TEST_CASE( rational_comparison, utf::data::make(cases), input )\n{\n\trational<short> rsl(input.ln, input.ld), rsr(input.rn, input.rd);\n\trational<int> ril(input.ln, input.ld), rir(input.rn, input.rd);\n\tswitch(input.type) {\n\tcase LT:\n\t        BOOST_TEST( !( rsl == rsr ) );\n\t        BOOST_TEST(    rsl != rsr   );\n\t        BOOST_TEST(    rsl <  rsr   );\n\t        BOOST_TEST(    rsl <= rsr   );\n\t        BOOST_TEST( !( rsl >  rsr ) );\n\t        BOOST_TEST( !( rsl >= rsr ) );\n\t        BOOST_TEST( !( ril == rir ) );\n\t        BOOST_TEST(    ril != rir   );\n\t        BOOST_TEST(    ril <  rir   );\n\t        BOOST_TEST(    ril <= rir   );\n\t        BOOST_TEST( !( ril >  rir ) );\n\t        BOOST_TEST( !( ril >= rir ) );\n\t        BOOST_TEST( !( rsl == rir ) );\n\t        BOOST_TEST(    rsl != rir   );\n\t        BOOST_TEST(    rsl <  rir   );\n\t        BOOST_TEST(    rsl <= rir   );\n\t        BOOST_TEST( !( rsl >  rir ) );\n\t        BOOST_TEST( !( rsl >= rir ) );\n\t        BOOST_TEST( !( ril == rsr ) );\n\t        BOOST_TEST(    ril != rsr   );\n\t        BOOST_TEST(    ril <  rsr   );\n\t        BOOST_TEST(    ril <= rsr   );\n\t        BOOST_TEST( !( ril >  rsr ) );\n\t        BOOST_TEST( !( ril >= rsr ) );\n\t\tbreak;\n\tcase EQ:\n\t        BOOST_TEST(    rsl == rsr   );\n\t        BOOST_TEST( !( rsl != rsr ) );\n\t        BOOST_TEST( !( rsl <  rsr ) );\n\t        BOOST_TEST(    rsl <= rsr   );\n\t        BOOST_TEST( !( rsl >  rsr ) );\n\t        BOOST_TEST(    rsl >= rsr   );\n\t        BOOST_TEST(    ril == rir   );\n\t        BOOST_TEST( !( ril != rir ) );\n\t        BOOST_TEST( !( ril <  rir ) );\n\t        BOOST_TEST(    ril <= rir   );\n\t        BOOST_TEST( !( ril >  rir ) );\n\t        BOOST_TEST(    ril >= rir   );\n\t        BOOST_TEST(    rsl == rir   );\n\t        BOOST_TEST( !( rsl != rir ) );\n\t        BOOST_TEST( !( rsl <  rir ) );\n\t        BOOST_TEST(    rsl <= rir   );\n\t        BOOST_TEST( !( rsl >  rir ) );\n\t        BOOST_TEST(    rsl >= rir   );\n\t        BOOST_TEST(    ril == rsr   );\n\t        BOOST_TEST( !( ril != rsr ) );\n\t        BOOST_TEST( !( ril <  rsr ) );\n\t        BOOST_TEST(    ril <= rsr   );\n\t        BOOST_TEST( !( ril >  rsr ) );\n\t        BOOST_TEST(    ril >= rsr   );\n\t\tbreak;\n\tcase GT:\n\t        BOOST_TEST( !( rsl == rsr ) );\n\t        BOOST_TEST(    rsl != rsr   );\n\t        BOOST_TEST( !( rsl <  rsr ) );\n\t        BOOST_TEST( !( rsl <= rsr ) );\n\t        BOOST_TEST(    rsl >  rsr   );\n\t        BOOST_TEST(    rsl >= rsr   );\n\t        BOOST_TEST( !( ril == rir ) );\n\t        BOOST_TEST(    ril != rir   );\n\t        BOOST_TEST( !( ril <  rir ) );\n\t        BOOST_TEST( !( ril <= rir ) );\n\t        BOOST_TEST(    ril >  rir   );\n\t        BOOST_TEST(    ril >= rir   );\n\t        BOOST_TEST( !( rsl == rir ) );\n\t        BOOST_TEST(    rsl != rir   );\n\t        BOOST_TEST( !( rsl <  rir ) );\n\t        BOOST_TEST( !( rsl <= rir ) );\n\t        BOOST_TEST(    rsl >  rir   );\n\t        BOOST_TEST(    rsl >= rir   );\n\t        BOOST_TEST( !( ril == rsr ) );\n\t        BOOST_TEST(    ril != rsr   );\n\t        BOOST_TEST( !( ril <  rsr ) );\n\t        BOOST_TEST( !( ril <= rsr ) );\n\t        BOOST_TEST(    ril >  rsr   );\n\t        BOOST_TEST(    ril >= rsr   );\n\t\tbreak;\n\t}\n}\n\nBOOST_AUTO_TEST_CASE( rational_arithmetic_additive )\n{\n}\n\nBOOST_AUTO_TEST_CASE( rational_arithmetic_multiplicative )\n{\n}\n", "meta": {"hexsha": "145647bb69c090d2a1b5a794f6b09f803e77bd3b", "size": 4876, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rational_test.cpp", "max_stars_repo_name": "yak1ex/tinymp", "max_stars_repo_head_hexsha": "afcdf4e10b5cb322234d82a496a5d800d35ab116", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rational_test.cpp", "max_issues_repo_name": "yak1ex/tinymp", "max_issues_repo_head_hexsha": "afcdf4e10b5cb322234d82a496a5d800d35ab116", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T18:47:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-22T12:13:36.000Z", "max_forks_repo_path": "rational_test.cpp", "max_forks_repo_name": "yak1ex/tinymp", "max_forks_repo_head_hexsha": "afcdf4e10b5cb322234d82a496a5d800d35ab116", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5515151515, "max_line_length": 81, "alphanum_fraction": 0.4448318294, "num_tokens": 1837, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879312006227324, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6081595656747153}}
{"text": "#include \"truncated_svd.hpp\"\n\n#include <armadillo>\n#include <cmath>\n#include <stdexcept>\n\ntemplate <class Real>\nvoid TruncatedSvd(long m, long n, std::vector<Real> &A, Real tolerance,\n                  bool is_relative, long &r, std::vector<Real> &U,\n                  std::vector<Real> &s, std::vector<Real> &Vt) {\n    if (m < 1 || n < 1) {\n        throw std::invalid_argument(\"Matrix dimensions must be positive\");\n    }\n\n    if (A.size() != m * n) {\n        throw std::invalid_argument(\n            \"Matrix dimensions are incompatible with number of entries\");\n    }\n\n    const long k = std::min(m, n);\n\n    arma::Mat<Real> A_temp(m, n);\n    for (long j = 0; j < n; ++j) {\n        for (long i = 0; i < m; ++i) {\n            A_temp(i, j) = A[i + j * m];\n        }\n    }\n\n    arma::Mat<Real> U_thin;\n    arma::Col<Real> s_thin;\n    arma::Mat<Real> V_thin;\n\n    bool status = arma::svd_econ(U_thin, s_thin, V_thin, A_temp);\n\n    if (!status) {\n        throw std::runtime_error(\"SVD decomposition failed\");\n    }\n\n    Real frobenius_max_error = static_cast<Real>(0);\n    if (is_relative) {\n        for (long i = 0; i < k; ++i) {\n            frobenius_max_error += std::pow(s_thin(i), 2);\n        }\n\n        frobenius_max_error *= std::pow(tolerance, 2);\n    } else {\n        frobenius_max_error = std::pow(tolerance, 2);\n    }\n\n    Real frobenius_error = static_cast<Real>(0);\n    r = k;\n    while (r > 0) {\n        frobenius_error += std::pow(s_thin(r - 1), 2);\n        if (frobenius_error > frobenius_max_error) {\n            break;\n        }\n        --r;\n    }\n\n    U.resize(m * r);\n    for (long j = 0; j < r; ++j) {\n        for (long i = 0; i < m; ++i) {\n            U[i + j * m] = U_thin(i, j);\n        }\n    }\n\n    s.resize(r);\n    for (long i = 0; i < r; ++i) {\n        s[i] = s_thin(i);\n    }\n\n    Vt.resize(r * n);\n    for (long j = 0; j < n; ++j) {\n        for (long i = 0; i < r; ++i) {\n            Vt[i + j * r] = V_thin(j, i);\n        }\n    }\n}\n\ntemplate <class Real>\nvoid TruncatedSvd(const arma::Mat<Real> &A, Real tolerance, bool is_relative,\n                  arma::Mat<Real> &U, arma::Col<Real> &s, arma::Mat<Real> &V,\n                  long &r) {\n    arma::Mat<Real> U_thin;\n    arma::Col<Real> s_thin;\n    arma::Mat<Real> V_thin;\n    bool status = arma::svd_econ(U_thin, s_thin, V_thin, A);\n    if (!status) {\n        throw std::runtime_error(\"SVD decomposition failed\");\n    }\n\n    Real frobenius_max_error = static_cast<Real>(0);\n    if (is_relative) {\n        for (long i = 0; i < s_thin.n_rows; ++i) {\n            frobenius_max_error += std::pow(s_thin(i), 2);\n        }\n\n        frobenius_max_error *= std::pow(tolerance, 2);\n    } else {\n        frobenius_max_error = std::pow(tolerance, 2);\n    }\n\n    Real frobenius_error = static_cast<Real>(0);\n    r = s_thin.n_rows;\n    while (r > 0) {\n        frobenius_error += std::pow(s_thin(r - 1), 2);\n        if (frobenius_error > frobenius_max_error) {\n            break;\n        }\n        --r;\n    }\n\n    U.set_size(A.n_rows, r);\n    for (long j = 0; j < r; ++j) {\n        for (long i = 0; i < A.n_rows; ++i) {\n            U(i, j) = U_thin(i, j);\n        }\n    }\n\n    s.set_size(r);\n    for (long i = 0; i < r; ++i) {\n        s(i) = s_thin(i);\n    }\n\n    V.set_size(A.n_cols, r);\n    for (long j = 0; j < r; ++j) {\n        for (long i = 0; i < A.n_cols; ++i) {\n            V(i, j) = V_thin(i, j);\n        }\n    }\n}\n\ntemplate void TruncatedSvd<float>(long m, long n, std::vector<float> &A,\n                                  float tolerance, bool is_relative, long &r,\n                                  std::vector<float> &U, std::vector<float> &s,\n                                  std::vector<float> &Vt);\ntemplate void TruncatedSvd<double>(long m, long n, std::vector<double> &A,\n                                   double tolerance, bool is_relative, long &r,\n                                   std::vector<double> &U,\n                                   std::vector<double> &s,\n                                   std::vector<double> &Vt);\n\ntemplate void TruncatedSvd<float>(const arma::Mat<float> &A, float tolerance,\n                                  bool is_relative, arma::Mat<float> &U,\n                                  arma::Col<float> &s, arma::Mat<float> &V,\n                                  long &r);\n\ntemplate void TruncatedSvd<double>(const arma::Mat<double> &A, double tolerance,\n                                   bool is_relative, arma::Mat<double> &U,\n                                   arma::Col<double> &s, arma::Mat<double> &V,\n                                   long &r);\n", "meta": {"hexsha": "00b244d104603bc06d7ea43748f831719c94de09", "size": 4566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/truncated_svd.cpp", "max_stars_repo_name": "saibalde/tensortrain", "max_stars_repo_head_hexsha": "8ad6af5bdc07a1794243fee4b4e2b83b34c81f53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/truncated_svd.cpp", "max_issues_repo_name": "saibalde/tensortrain", "max_issues_repo_head_hexsha": "8ad6af5bdc07a1794243fee4b4e2b83b34c81f53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/truncated_svd.cpp", "max_forks_repo_name": "saibalde/tensortrain", "max_forks_repo_head_hexsha": "8ad6af5bdc07a1794243fee4b4e2b83b34c81f53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0394736842, "max_line_length": 80, "alphanum_fraction": 0.4840122646, "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711756575749, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6080897799469437}}
{"text": "#pragma once\n\n#include <cmath>  // ceil\n#include <initializer_list>\n\n#include <Eigen/SparseLU>\n\n#include \"InterpolationTemplate.hpp\"\n\nnamespace intp {\n\ntemplate <typename T, size_t D>\nclass InterpolationFunction {  // TODO: Add integration\n   public:\n    using val_type = T;\n    using spline_type = BSpline<T, D>;\n    using size_type = typename spline_type::size_type;\n    using coord_type = typename spline_type::knot_type;\n\n    const size_type order;\n    const static size_type dim = D;\n\n   private:\n    spline_type __spline;\n\n    template <typename _T>\n    using DimArray = std::array<_T, dim>;\n\n    DimArray<coord_type> __dx;\n    DimArray<bool> __periodicity;\n    DimArray<bool> __uniform;\n\n    friend class InterpolationFunctionTemplate<T, D>;\n\n    // auxiliary methods\n\n    template <size_type... di>\n    inline val_type call_op_helper(util::index_sequence<di...>,\n                                   DimArray<coord_type> c) const {\n        return __spline(std::make_pair(\n            c[di], __uniform[di]\n                       ? std::min(__spline.knots_num(di) - order - 2,\n                                  (size_type)std::ceil(std::max(\n                                      0., (c[di] - range(di).first) / __dx[di] -\n                                              (__periodicity[di]\n                                                   ? 1.\n                                                   : .5 * (order + 1)))) +\n                                      order)\n                       : order)...);\n    }\n\n    template <size_type... di>\n    inline val_type derivative_helper(util::index_sequence<di...>,\n                                      DimArray<coord_type> c,\n                                      DimArray<size_type> d) const {\n        return __spline.derivative_at(std::make_tuple(\n            (coord_type)c[di], (size_type)d[di],\n            __uniform[di]\n                ? std::min(\n                      __spline.knots_num(di) - order - 2,\n                      (size_type)std::ceil(std::max(\n                          0.,\n                          (c[di] - range(di).first) / __dx[di] -\n                              (__periodicity[di] ? 1. : .5 * (order + 1)))) +\n                          order)\n                : order)...);\n    }\n\n    // overload for uniform knots\n    template <typename _T>\n    typename std::enable_if<std::is_arithmetic<_T>::value>::type\n    __create_knot_vector(size_type dim_ind,\n                         const MeshDimension<dim>& mesh_dimension,\n                         DimArray<typename spline_type::KnotContainer>&,\n                         std::pair<_T, _T> x_range) {\n        __uniform[dim_ind] = true;\n        const size_type n = mesh_dimension.dim_size(dim_ind);\n        __dx[dim_ind] = (x_range.second - x_range.first) / (n - 1);\n\n        const size_t extra =\n            __periodicity[dim_ind] ? 2 * order + (1 - order % 2) : order + 1;\n\n        std::vector<typename spline_type::knot_type> xs(n + extra,\n                                                        x_range.first);\n\n        if (__periodicity[dim_ind]) {\n            for (size_type i = 0; i < xs.size(); ++i) {\n                xs[i] = x_range.first + (i - .5 * extra) * __dx[dim_ind];\n            }\n        } else {\n            for (size_type i = order + 1; i < xs.size() - order - 1; ++i) {\n                xs[i] = x_range.first + (i - .5 * extra) * __dx[dim_ind];\n            }\n            for (size_type i = xs.size() - order - 1; i < xs.size(); ++i) {\n                xs[i] = x_range.second;\n            }\n        }\n\n        __spline.load_knots(dim_ind, std::move(xs), __periodicity[dim_ind]);\n    }\n\n    // overload for nonuniform knots, given by iterator pair\n    template <typename _T>\n    typename std::enable_if<std::is_convertible<\n        typename std::iterator_traits<_T>::iterator_category,\n        std::input_iterator_tag>::value>::type\n    __create_knot_vector(\n        size_type dim_ind,\n        const MeshDimension<dim>& mesh_dimension,\n        DimArray<typename spline_type::KnotContainer>& input_coords,\n        std::pair<_T, _T> x_range) {\n        __uniform[dim_ind] = false;\n        const size_type n = std::distance(x_range.first, x_range.second);\n        if (n != mesh_dimension.dim_size(dim_ind)) {\n            throw std::range_error(\n                std::string(\"Inconsistency between knot number and \"\n                            \"interpolated value number at dimension \") +\n                std::to_string(dim_ind));\n        }\n        typename spline_type::KnotContainer xs(\n            __periodicity[dim_ind] ? n + 2 * order + (1 - order % 2)\n                                   : n + order + 1);\n\n        input_coords[dim_ind].reserve(n);\n        if (__periodicity[dim_ind]) {\n            auto iter = x_range.first;\n\n            input_coords[dim_ind].push_back(*iter);\n            for (size_type i = order + 1; i < order + n; ++i) {\n                val_type present = *(++iter);\n                xs[i] = order % 2 == 0\n                            ? .5 * (input_coords[dim_ind].back() + present)\n                            : present;\n                input_coords[dim_ind].push_back(present);\n            }\n            val_type period =\n                input_coords[dim_ind].back() - input_coords[dim_ind].front();\n            for (size_type i = 0; i < order + 1; ++i) {\n                xs[i] = xs[n + i - 1] - period;\n                xs[xs.size() - i - 1] = xs[xs.size() - i - n] + period;\n            }\n        } else {\n            auto it = x_range.first;\n            // Notice that *it++ is not guarantee to work as what you\n            // expected for input iterators.\n            auto l_knot = *it;\n            // fill lestmost *order+1* identical knots\n            for (size_type i = 0; i < order + 1; ++i) { xs[i] = l_knot; }\n            // first knot is same as first input coordinate\n            input_coords[dim_ind].emplace_back(l_knot);\n            // Every knot in middle is average of *order* input\n            // coordinates. This var is to track the sum of a moving window with\n            // width *order*.\n            coord_type window_sum{};\n            for (size_type i = 1; i < order; ++i) {\n                input_coords[dim_ind].emplace_back(*(++it));\n                window_sum += input_coords[dim_ind][i];\n            }\n            for (size_type i = order + 1; i < n; ++i) {\n                input_coords[dim_ind].emplace_back(*(++it));\n                window_sum += input_coords[dim_ind][i - 1];\n                xs[i] = window_sum / order;\n                window_sum -= input_coords[dim_ind][i - order];\n            }\n            auto r_knot = *(++it);\n            // fill rightmost *order+1* identical knots\n            for (size_type i = n; i < n + order + 1; ++i) { xs[i] = r_knot; }\n            // last knot is same as last input coordinate\n            input_coords[dim_ind].emplace_back(r_knot);\n        }\n#ifdef _DEBUG\n        std::cout << \"[DEBUG] Nonuniform knots along dimension\" << dim_ind\n                  << \":\\n\";\n        for (auto& c : xs) { std::cout << \"[DEBUG] \" << c << '\\n'; }\n        std::cout << std::endl;\n#endif\n\n        __spline.load_knots(dim_ind, std::move(xs));\n    }\n\n    template <typename... Ts, size_type... di>\n    void __create_knots(\n        util::index_sequence<di...>,\n        MeshDimension<dim> mesh_dimension,\n        DimArray<typename spline_type::KnotContainer>& input_coords,\n        std::pair<Ts, Ts>... x_ranges) {\n#if __cplusplus >= 201703L\n        (__create_knot_vector(di, f_mesh, input_coords, x_ranges), ...);\n#else\n        // polyfill of C++17 fold expression over comma\n        std::array<std::nullptr_t, sizeof...(Ts)>{\n            (__create_knot_vector(di, mesh_dimension, input_coords, x_ranges),\n             nullptr)...};\n#endif\n    }\n\n    inline void __boundary_check(const DimArray<coord_type>& coord) const {\n        for (size_type d = 0; d < dim; ++d) {\n            if (!__periodicity[d] &&\n                (coord[d] < range(d).first || coord[d] > range(d).second)) {\n                throw std::domain_error(\n                    \"Given coordinate out of interpolation function range!\");\n            }\n        }\n    }\n\n   public:\n    /**\n     * @brief Construct a new 1D Interpolation Function object, mimicking\n     * Mathematica's `Interpolation` function, with option `Method->\"Spline\"`.\n     *\n     * @tparam InputIter\n     * @param order order of interpolation, the interpolated function is of\n     * $C^{order-1}$\n     * @param periodic whether to construct a periodic spline\n     * @param f_range a pair of iterators defining to-be-interpolated data\n     * @param x_range a pair of x_min and x_max\n     */\n    template <\n        typename InputIter,\n        typename C1,\n        typename C2,\n        typename std::enable_if<\n            dim == 1u &&\n            std::is_convertible<\n                typename std::iterator_traits<InputIter>::iterator_category,\n                std::input_iterator_tag>::value>::type* = nullptr>\n    InterpolationFunction(size_type order,\n                          bool periodic,\n                          std::pair<InputIter, InputIter> f_range,\n                          std::pair<C1, C2> x_range)\n        : InterpolationFunction(\n              order,\n              {periodic},\n              Mesh<val_type, 1u>{std::make_pair(f_range.first, f_range.second)},\n              static_cast<std::pair<typename std::common_type<C1, C2>::type,\n                                    typename std::common_type<C1, C2>::type>>(\n                  x_range)) {}\n\n    template <\n        typename InputIter,\n        typename C1,\n        typename C2,\n        typename std::enable_if<\n            dim == 1u &&\n            std::is_convertible<\n                typename std::iterator_traits<InputIter>::iterator_category,\n                std::input_iterator_tag>::value>::type* = nullptr>\n    InterpolationFunction(size_type order,\n                          std::pair<InputIter, InputIter> f_range,\n                          std::pair<C1, C2> x_range)\n        : InterpolationFunction(order, false, f_range, x_range) {}\n\n    /**\n     * @brief Construct a new nD Interpolation Function object, mimicking\n     * Mathematica's `Interpolation` function, with option `Method->\"Spline\"`.\n     * Notice: last value of periodic dimension will be discarded since it is\n     * considered same of the first value. Thus inconsistency input data for\n     * periodic interpolation will be accepted.\n     *\n     * @param order order of interpolation, the interpolated function is of\n     * $C^{order-1}$\n     * @param periodicity an array describing periodicity of each dimension\n     * @param f_mesh a mesh containing data to be interpolated\n     * @param x_ranges pairs of x_min and x_max or begin and end iterator\n     */\n    template <typename... Ts>\n    InterpolationFunction(size_type order,\n                          DimArray<bool> periodicity,\n                          const Mesh<val_type, dim>& f_mesh,\n                          std::pair<Ts, Ts>... x_ranges)\n        : InterpolationFunction(InterpolationFunctionTemplate<val_type, dim>{\n              order, periodicity, f_mesh.dimension(), x_ranges...}\n                                    .interpolate(f_mesh)) {}\n\n    // Non-periodic for all dimension\n    template <typename... Ts>\n    InterpolationFunction(size_type order,\n                          const Mesh<val_type, dim>& f_mesh,\n                          std::pair<Ts, Ts>... x_ranges)\n        : InterpolationFunction(order, {}, f_mesh, x_ranges...) {}\n\n    // constructor for partial construction, that is, without interpolated\n    // values\n    template <typename... Ts>\n    InterpolationFunction(\n        size_type order,\n        DimArray<bool> periodicity,\n        DimArray<typename spline_type::KnotContainer>& input_coords,\n        MeshDimension<dim> mesh_dimension,\n        std::pair<Ts, Ts>... x_ranges)\n        : order(order),\n          __spline(periodicity, order),\n          __periodicity(periodicity) {\n        // load knots into spline\n        __create_knots(util::make_index_sequence_for<Ts...>{},\n                       std::move(mesh_dimension), input_coords, x_ranges...);\n    }\n\n    /**\n     * @brief Get spline value.\n     *\n     * @param x coordinates\n     */\n    template <typename... Coords,\n              typename Indices = util::make_index_sequence_for<Coords...>,\n              typename = typename std::enable_if<std::is_arithmetic<\n                  typename std::common_type<Coords...>::type>::value>::type>\n    val_type operator()(Coords... x) const {\n        return call_op_helper(Indices{}, DimArray<coord_type>{x...});\n    }\n\n    /**\n     * @brief Get spline value.\n     *\n     * @param coord coordinate array\n     */\n    val_type operator()(DimArray<coord_type> coord) const {\n        return call_op_helper(util::make_index_sequence<dim>{}, coord);\n    }\n\n    /**\n     * @brief Get spline value, but with out of boundary check.\n     *\n     * @param coord coordinate array\n     */\n    val_type at(DimArray<coord_type> coord) const {\n        __boundary_check(coord);\n        return call_op_helper(util::make_index_sequence<dim>{}, coord);\n    }\n\n    /**\n     * @brief Get spline value, but with out of boundary check.\n     *\n     * @param x coordinates\n     */\n    template <typename... Coords,\n              typename Indices = util::make_index_sequence_for<Coords...>,\n              typename = typename std::enable_if<std::is_arithmetic<\n                  typename std::common_type<Coords...>::type>::value>::type>\n    val_type at(Coords... x) const {\n        return at(DimArray<coord_type>{static_cast<coord_type>(x)...});\n    }\n\n    /**\n     * @brief Get spline derivative value.\n     *\n     * @param coord coordinate array\n     * @param derivatives derivative order array\n     */\n    val_type derivative(DimArray<coord_type> coord,\n                        DimArray<size_type> derivatives) const {\n        return derivative_helper(util::make_index_sequence<dim>{}, coord,\n                                 derivatives);\n    }\n\n    /**\n     * @brief Get spline derivative value.\n     *\n     * @param coord coordinate array\n     * @param deriOrder derivative orders\n     */\n    template <typename... Args>\n    val_type derivative(DimArray<coord_type> coord, Args... deriOrder) const {\n        return derivative(coord, DimArray<size_type>{(size_type)deriOrder...});\n    }\n\n    /**\n     * @brief Get spline derivative value.\n     *\n     * @param coord_deriOrder_pair pairs of coordinate and derivative order\n     */\n    template <typename... CoordDeriOrderPair>\n    val_type derivative(CoordDeriOrderPair... coord_deriOrder_pair) const {\n        return derivative(\n            DimArray<coord_type>{coord_deriOrder_pair.first...},\n            DimArray<size_type>{(size_type)coord_deriOrder_pair.second...});\n    }\n\n    /**\n     * @brief Get spline derivative value, but with out of boundary check.\n     *\n     * @param coord coordinate array\n     * @param derivatives derivative order array\n     */\n    val_type derivative_at(DimArray<coord_type> coord,\n                           DimArray<size_type> derivatives) const {\n        __boundary_check(coord);\n        return derivative_helper(util::make_index_sequence<dim>{}, coord,\n                                 derivatives);\n    }\n\n    /**\n     * @brief Get spline derivative value, but with out of boundary check.\n     *\n     * @param coord coordinate array\n     * @param deriOrder derivative orders\n     */\n    template <typename... Args>\n    val_type derivative_at(DimArray<coord_type> coord,\n                           Args... deriOrder) const {\n        return derivative_at(coord,\n                             DimArray<size_type>{(size_type)deriOrder...});\n    }\n\n    /**\n     * @brief Get spline derivative value, but with out of boundary check.\n     *\n     * @param coord_deriOrder_pair pairs of coordinate and derivative order\n     */\n    template <typename... CoordDeriOrderPair>\n    val_type derivative_at(CoordDeriOrderPair... coord_deriOrder_pair) const {\n        return derivative_at(\n            DimArray<coord_type>{coord_deriOrder_pair.first...},\n            DimArray<size_type>{(size_type)coord_deriOrder_pair.second...});\n    }\n\n    // properties\n\n    bool periodicity(size_type dim_ind) const { return __periodicity[dim_ind]; }\n\n    bool uniform(size_type dim_ind) const { return __uniform[dim_ind]; }\n\n    const std::pair<typename spline_type::knot_type,\n                    typename spline_type::knot_type>&\n    range(size_type dim_ind) const {\n        return __spline.range(dim_ind);\n    }\n\n    /**\n     * @brief Get a ref of underlying spline object\n     *\n     * @return spline_type&\n     */\n    const spline_type& spline() const { return __spline; }\n};\n\ntemplate <typename T>\nclass InterpolationFunction1D : public InterpolationFunction<T, size_t{1}> {\n   private:\n    using base = InterpolationFunction<T, size_t{1}>;\n\n   public:\n    template <typename InputIter>\n    InterpolationFunction1D(std::pair<InputIter, InputIter> f_range,\n                            typename base::size_type order = 3,\n                            bool periodicity = false)\n        : InterpolationFunction1D(\n              std::make_pair(typename base::coord_type{},\n                             static_cast<typename base::coord_type>(\n                                 (f_range.second - f_range.first) - 1)),\n              f_range,\n              order,\n              periodicity){};\n\n    template <typename C1, typename C2, typename InputIter>\n    InterpolationFunction1D(std::pair<C1, C2> x_range,\n                            std::pair<InputIter, InputIter> f_range,\n                            typename base::size_type order = 3,\n                            bool periodicity = false)\n        : base(order, periodicity, f_range, x_range){};\n};\n\n}  // namespace intp\n", "meta": {"hexsha": "33729f094b6788f52ad15f854a25ac6d27f5d207", "size": 17793, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/Interpolation.hpp", "max_stars_repo_name": "12ff54e/BSplineInterpolation", "max_stars_repo_head_hexsha": "b0f04414807bea999c5102f1274ea2ad9c2a6b6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2022-03-21T08:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:31:41.000Z", "max_issues_repo_path": "src/include/Interpolation.hpp", "max_issues_repo_name": "12ff54e/BSplineInterpolation", "max_issues_repo_head_hexsha": "b0f04414807bea999c5102f1274ea2ad9c2a6b6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/Interpolation.hpp", "max_forks_repo_name": "12ff54e/BSplineInterpolation", "max_forks_repo_head_hexsha": "b0f04414807bea999c5102f1274ea2ad9c2a6b6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T11:12:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T11:12:24.000Z", "avg_line_length": 38.264516129, "max_line_length": 80, "alphanum_fraction": 0.5588714663, "num_tokens": 4034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6080897641947026}}
{"text": "#include <string>\n#include <math.h>\n#include <iostream>\n#include <boost/regex.hpp>\n#include <boost/format.hpp>\n#include <fstream>\n#include <unordered_map>\n\n#define SIMULATED_ROUNDS 1000\n#define COLLISION_ROUNDS 40\n\nusing namespace std;\n\nclass Particle {\nprivate:\n    long x, y, z;\n    long vx, vy, vz;\n    long ax, ay, az;\npublic:\n    bool annihilated;\n\n    Particle(string line) {\n        boost::regex re(\"[p,v,a,=,<,>,\\\\s]+\");\n        boost::sregex_token_iterator\n            p(line.begin(), line.end(), re, -1);\n        boost::sregex_token_iterator end;\n\n        vector<int> values;\n        while(p != end) {\n            if(p->str().length() == 0) {\n                p++;\n                continue;\n            }\n\n            values.push_back(atoi((p++)->str().c_str()));\n        }\n\n        x = values[0];\n        y = values[1];\n        z = values[2];\n        vx = values[3];\n        vy = values[4];\n        vz = values[5];\n        ax = values[6];\n        ay = values[7];\n        az = values[8];\n        annihilated = false;\n    }\n\n    void move() {\n        vx += ax;\n        vy += ay;\n        vz += az;\n        x += vx;\n        y += vy;\n        z += vz;\n    }\n\n    float distance() {\n        float dist = pow(x, 2);\n        dist += pow(y, 2);\n        dist += pow(z, 2);\n        return dist;\n    }\n\n    void simulateMovement(float time) {\n        x += int(vx*time) + int(0.5*ax*time*time);\n        y += int(vy*time) + int(0.5*ay*time*time);\n        z += int(vz*time) + int(0.5*az*time*time);\n    }\n\n    string location() {\n        return boost::str(boost::format(\"%d,%d,%d\") % x % y % z);\n    }\n\n    friend ostream& operator<<(ostream &os, const Particle& p);\n};\n\nstd::ostream& operator<<(std::ostream &strm, const Particle &p) {\n    return strm << boost::format(\"<%d,%d,%d; %d,%d,%d; %d,%d,%d>\") % p.x % p.y % p.z % p.vx % p.vy % p.vz % p.ax % p.ay % p.az;\n}\n\nint closestParticle(vector<Particle> particles) {\n    vector<float> distances;\n    for(int i = 0; i < particles.size(); i++) {\n        particles[i].simulateMovement(SIMULATED_ROUNDS);\n        distances.push_back(particles[i].distance());\n    }\n\n    int minParticle = 0;\n    for(int i = 0; i < distances.size(); i++) {\n        if(distances[i] < distances[minParticle])\n            minParticle = i;\n    }\n    return minParticle;\n}\n\nint numUncollidedParticles(vector<Particle> particles) {\n    for(int i = 0; i < COLLISION_ROUNDS; i++) {\n        unordered_map<string, int> locations;\n\n        for(int j = 0; j < particles.size(); j++) {\n            if(particles[j].annihilated)\n                continue;\n            \n            particles[j].move();\n            \n            string loc = particles[j].location();\n            if(locations.find(loc) != locations.end()) {\n                particles[j].annihilated = true;\n                particles[locations[loc]].annihilated = true;\n            } else {\n                locations[loc] = j;\n            }\n        }\n    }\n    int nonAnnihilated = 0;\n    for(int i = 0; i < particles.size(); i++) {\n        if(!particles[i].annihilated) nonAnnihilated++;\n    }\n    return nonAnnihilated;\n}\n\nint main() {\n    vector<Particle> particles;\n\n    ifstream infile(\"20.txt\");\n    string line;\n    while (getline(infile, line)) {\n        particles.push_back(Particle(line));\n    }\n    cout << \"Part 1: \" << closestParticle(particles) << \"\\n\";\n    cout << \"Part 2: \" << numUncollidedParticles(particles) << \"\\n\";\n}\n", "meta": {"hexsha": "1caf5d96d248a35b3145643c2ae7a42970a29210", "size": 3409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Day20-25/20.cpp", "max_stars_repo_name": "bcongdon/advent_of_code_2017", "max_stars_repo_head_hexsha": "ad9a9b028716c9387dddc3ef9ee34c3a70fea151", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-12-05T16:01:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-03T00:01:03.000Z", "max_issues_repo_path": "Day20-25/20.cpp", "max_issues_repo_name": "bcongdon/advent_of_code_2017", "max_issues_repo_head_hexsha": "ad9a9b028716c9387dddc3ef9ee34c3a70fea151", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Day20-25/20.cpp", "max_forks_repo_name": "bcongdon/advent_of_code_2017", "max_forks_repo_head_hexsha": "ad9a9b028716c9387dddc3ef9ee34c3a70fea151", "max_forks_repo_licenses": ["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.2518518519, "max_line_length": 127, "alphanum_fraction": 0.5154004107, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.6080607697526276}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#define BOOST_TEST_MAIN\n\n#include <limits>\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include \"Tudat/Mathematics/NumericalQuadrature/trapezoidQuadrature.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n\n// Function to create linearly spaced data.\nstd::vector< double > linspace( double start, double end, int numberOfSamples )\n{\n    double spacing = ( end - start ) / ( static_cast< double >( numberOfSamples - 1 ) );\n\n    std::vector< double > vector(0);\n    for( int i = 0 ; i < numberOfSamples ; i++ )\n    {\n        vector.push_back( start + static_cast< double >( i ) * spacing );\n    }\n\n    return vector;\n}\n\nBOOST_AUTO_TEST_SUITE( test_trapezoid_integrator )\n\n//! Test if qudrature is computed correctly (sine function with 1E4 data points).\nBOOST_AUTO_TEST_CASE( testIntegralSineFunction )\n{\n    std::vector< int > numberOfSamplesList;\n    numberOfSamplesList.push_back( 1E2 );\n    numberOfSamplesList.push_back( 1E4 );\n    numberOfSamplesList.push_back( 1E6 );\n\n    std::vector< double > tolerances = { 2E-4, 2E-8, 2E-12 };\n\n    double previousError = TUDAT_NAN;\n    double currentError = TUDAT_NAN;\n\n    for( unsigned int test = 0; test < 3; test++ )\n    {\n        // Generate independent variables\n        int numberOfSamples = numberOfSamplesList.at( test );\n\n        std::vector< double > bounds( 2 );\n        bounds[ 0 ] = 0.0;\n        bounds[ 1 ] = mathematical_constants::PI;\n        std::vector< double > independentVariables = linspace( bounds[ 0 ], bounds[ 1 ], numberOfSamples );\n\n        std::vector< double > dependentVariables;\n        for( unsigned int i = 0 ; i < independentVariables.size( ) ; i++ )\n        {\n            dependentVariables.push_back( std::sin( independentVariables[ i ] ) );\n        }\n\n        tudat::numerical_quadrature::TrapezoidNumericalQuadrature< double, double > integrator(\n                    independentVariables, dependentVariables );\n\n        double expectedIntegral = 2.0;\n        double computedIntegralTrapezoid = integrator.getQuadrature( );\n        double computedIntegralSimpson = tudat::numerical_quadrature::performExtendedSimpsonsQuadrature(\n                    independentVariables.at( 1 ) - independentVariables.at( 0 ), dependentVariables );\n\n        // Check if computed integral matches expected value.\n        BOOST_CHECK_CLOSE_FRACTION( computedIntegralTrapezoid, expectedIntegral, tolerances.at( test ) );\n        BOOST_CHECK_CLOSE_FRACTION( computedIntegralSimpson, expectedIntegral, tolerances.at( test ) );\n\n        currentError = std::fabs( computedIntegralTrapezoid - expectedIntegral );\n\n        // Test order of quadrature\n        if( test > 0 )\n        {\n            BOOST_CHECK_CLOSE_FRACTION( previousError / currentError, 1.0E4, 0.1 );\n        }\n\n        previousError = currentError;\n\n        // Reset data and recompute quadrature\n        bounds[ 1 ] = 2.0 * mathematical_constants::PI;\n        independentVariables = linspace( bounds[ 0 ], bounds[ 1 ], numberOfSamples );\n\n        dependentVariables.clear( );\n        for( unsigned int i = 0 ; i < independentVariables.size( ) ; i++ )\n        {\n            dependentVariables.push_back( std::sin( independentVariables[ i ] ) );\n        }\n\n        // Error should be close to zero, as integration (and its errors) are symmetrical\n        integrator.resetData( independentVariables, dependentVariables );\n        expectedIntegral = 0.0;\n        computedIntegralTrapezoid = integrator.getQuadrature( );\n        BOOST_CHECK_SMALL( computedIntegralTrapezoid - expectedIntegral, std::max( 5.0E-6, numberOfSamples * 5.0E-20 ) );\n    }\n}\n\n\n//! Test if qudrature is computed correctly (exponential function).\nBOOST_AUTO_TEST_CASE( testIntegralExpFunction )\n{\n    // Generate independent variables\n    int numberOfSamples = 1E4;\n\n    std::vector< double > bounds( 2 );\n    bounds[ 0 ] = 0.0;\n    bounds[ 1 ] = 2.0;\n    std::vector< double > independentVariables = linspace( bounds[ 0 ], bounds[ 1 ], numberOfSamples );\n\n    std::vector< double > dependentVariables( 0 );\n    for( unsigned int i = 0 ; i < independentVariables.size() ; i++ )\n    {\n        dependentVariables.push_back( std::exp( independentVariables[ i ] ) );\n    }\n\n    // Create integrator\n    tudat::numerical_quadrature::TrapezoidNumericalQuadrature< double, double > integrator(\n                independentVariables, dependentVariables );\n\n    double expectedIntegral = std::exp( 2.0 ) - std::exp( 0.0 );\n    double computedIntegralTrapezoid = integrator.getQuadrature( );\n    double computedIntegralSimpson = tudat::numerical_quadrature::performExtendedSimpsonsQuadrature(\n                independentVariables.at( 1 ) - independentVariables.at( 0 ), dependentVariables );\n\n    // Check if computed sample mean matches expected value.\n    BOOST_CHECK_CLOSE_FRACTION( computedIntegralTrapezoid, expectedIntegral, 1E-8 );\n    BOOST_CHECK_CLOSE_FRACTION( computedIntegralSimpson, expectedIntegral, 1E-8 );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "e94097db8877ce55e9de126bfb12ad4eb785d966", "size": 5526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/NumericalQuadrature/UnitTests/unitTestTrapezoidQuadrature.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/NumericalQuadrature/UnitTests/unitTestTrapezoidQuadrature.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/NumericalQuadrature/UnitTests/unitTestTrapezoidQuadrature.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3378378378, "max_line_length": 121, "alphanum_fraction": 0.6844010134, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.608060768812584}}
{"text": "\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <fmt/format.h>\n#include <string>\n#include <iomanip>\n#include <boost/variant.hpp>\n#include <unordered_map>\n#include <range/v3/all.hpp>\n#include \"combinations_algo.h\"\n#include \"matrix.h\"\nstruct Combinations\n{\n  FixedMatrix<int, 9, 9> networks_;\n  std::array<int, 9> a = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };\n  int max = std::numeric_limits<int>::min();\n  int maxhappiness() noexcept\n  {\n    auto f = [this](auto b, auto e) {\n      int s = networks_(*b, *(e - 1));\n      s += networks_(*(e - 1), *b);\n      for (; b != e - 1; ++b) {\n        s += networks_(*b, *(b + 1));\n        s += networks_(*(b + 1), *b);\n      }\n      max = std::max(s, max);\n      return false;\n    };\n    for_each_reversible_circular_permutation(a.begin(), a.end(), a.end(), f);\n    return max;\n  }\n};\nint main(int argc, char **argv)\n{\n  if (argc > 1) {\n    Combinations com;\n    std::ifstream ifs(argv[1]);\n    int i = 0;\n    std::unordered_map<std::string, int> m;\n    m[\"gain\"] = 1;\n    m[\"lose\"] = -1;\n    std::string s;\n    fmt::print(\"a\\n\");\n    for (; std::getline(ifs, s); ++i) {\n      int row = i / 7;\n      int col = i % 7;\n      std::istringstream iss(s);\n      std::string ignore, sign;\n      int value;\n      iss >> ignore >> ignore >> sign >> value;\n      fmt::print(\"sign:{},v:{}\\n\", sign, value);\n      value *= m[sign];\n      if (col >= row) {\n        com.networks_(row, col + 1) = value;\n      } else {\n        com.networks_(row, col) = value;\n      }\n    }\n\n    fmt::print(\"{}\\n\", com.maxhappiness());\n  }\n}", "meta": {"hexsha": "6b62ec7a29f859b4df75423b76a9ae96df64cd88", "size": 1576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc2015/aoc151302.cpp", "max_stars_repo_name": "jiayuehua/adventOfCode", "max_stars_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2015/aoc151302.cpp", "max_issues_repo_name": "jiayuehua/adventOfCode", "max_issues_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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": "aoc2015/aoc151302.cpp", "max_forks_repo_name": "jiayuehua/adventOfCode", "max_forks_repo_head_hexsha": "fd47ddefd286fe94db204a9850110f8d1d74d15b", "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.625, "max_line_length": 77, "alphanum_fraction": 0.5317258883, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6080607584626265}}
{"text": "// Test Pose\n#include <catch2/catch.hpp>\n\n#include <Eigen/Geometry>\n#include <igl/PI.h>\n\n#include <autodiff/autodiff_types.hpp>\n#include <interval/interval.hpp>\n#include <physics/pose.hpp>\n\nTEST_CASE(\"Poses to dofs\", \"[physics][pose]\")\n{\n    using namespace ipc::rigid;\n    int dim = GENERATE(2, 3);\n    int num_bodies = GENERATE(0, 1, 2, 3, 10, 1000);\n    Eigen::VectorXd dofs =\n        Eigen::VectorXd::Random(num_bodies * Pose<double>::dim_to_ndof(dim));\n    Poses<double> poses = Pose<double>::dofs_to_poses(dofs, dim);\n    Eigen::VectorXd returned_dofs = Pose<double>::poses_to_dofs(poses);\n    CHECK((dofs - returned_dofs).squaredNorm() == Approx(0));\n}\n\nTEST_CASE(\"Cast poses\", \"[physics][pose]\")\n{\n    using namespace ipc::rigid;\n    int dim = GENERATE(2, 3);\n    int num_bodies = GENERATE(0, 1, 2, 3, 10, 1000);\n\n    Eigen::VectorXf dof =\n        Eigen::VectorXf::Random(num_bodies * Pose<float>::dim_to_ndof(dim));\n    Poses<float> expected_posesf = Pose<float>::dofs_to_poses(dof, dim);\n\n    Poses<float> actual_posesf = cast<float>(cast<double>(expected_posesf));\n\n    CHECK(\n        (Pose<float>::poses_to_dofs(expected_posesf)\n         - Pose<float>::poses_to_dofs(actual_posesf))\n            .squaredNorm()\n        == Approx(0.0));\n}\n\nTEST_CASE(\"SE(3) \u21a6 SO(3)\", \"[physics][pose]\")\n{\n    using namespace ipc::rigid;\n    double angle;\n    Eigen::Vector3d axis;\n\n    SECTION(\"zero\")\n    {\n        angle = 0;\n        axis = Eigen::Vector3d::Random();\n    }\n    SECTION(\"random\")\n    {\n        angle = GENERATE(take(100, random(0.0, 2 * igl::PI)));\n        axis = Eigen::Vector3d::Random();\n    }\n    axis.normalize();\n\n    Pose<double> p = Pose<double>::Zero(3);\n    p.rotation = angle * axis;\n    Eigen::Matrix3d R_actual = p.construct_rotation_matrix();\n    Eigen::Matrix3d R_expected =\n        Eigen::AngleAxisd(angle, axis).toRotationMatrix();\n    CHECK((R_actual - R_expected).norm() == Approx(0).margin(1e-12));\n}\n\nTEST_CASE(\"\u2207\u00b2(SE(3) \u21a6 SO(3))\", \"[!benchmark][physics][pose]\")\n{\n    using namespace ipc::rigid;\n    typedef ipc::rigid::AutodiffType<Eigen::Dynamic, 12> Diff;\n    Diff::activate(12);\n\n    Pose<double> p;\n    p.position = Eigen::Vector3d::Zero();\n    p.rotation = Eigen::Vector3d(0, igl::PI, 0);\n\n    BENCHMARK(\"Compute R\") { return p.construct_rotation_matrix(); };\n\n    Pose<Diff::DDouble1> d1p;\n    d1p.position = Diff::d1vars(0, Eigen::Vector3d::Zero());\n    d1p.rotation = Diff::d1vars(3, Eigen::Vector3d(0, igl::PI, 0));\n\n    BENCHMARK(\"Compute R DDouble1\") { return d1p.construct_rotation_matrix(); };\n\n    Pose<Diff::DDouble2> d2p;\n    d2p.position = Diff::d2vars(0, Eigen::Vector3d::Zero());\n    d2p.rotation = Diff::d2vars(3, Eigen::Vector3d(0, igl::PI, 0));\n\n    BENCHMARK(\"Compute R DDouble2\") { return d2p.construct_rotation_matrix(); };\n}\n\nTEST_CASE(\"Interval SE(3) \u21a6 SO(3)\", \"[!benchmark][physics][pose]\")\n{\n    using namespace ipc::rigid;\n    double angle;\n    Eigen::Vector3d axis;\n\n    SECTION(\"zero\")\n    {\n        angle = 0;\n        axis = Eigen::Vector3d::Random();\n    }\n    SECTION(\"random\")\n    {\n        angle = GENERATE(take(1, random(0.0, 2 * igl::PI)));\n        axis = Eigen::Vector3d::Random();\n    }\n    axis.normalize();\n\n    Pose<double> p = Pose<double>::Zero(3);\n    p.rotation = angle * axis;\n    BENCHMARK(\"Double SE(3) \u21a6 SO(3)\")\n    {\n        Eigen::Matrix3d R = p.construct_rotation_matrix();\n    };\n    Pose<ipc::rigid::Interval> pI = p.cast<ipc::rigid::Interval>();\n    BENCHMARK(\"Interval SE(3) \u21a6 SO(3)\")\n    {\n        Matrix3I R = pI.construct_rotation_matrix();\n    };\n}\n", "meta": {"hexsha": "0b9dc76adfb6d598b4b38cad47ea5f66497eb232", "size": 3545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/physics/test_pose.cpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "tests/physics/test_pose.cpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "tests/physics/test_pose.cpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 28.8211382114, "max_line_length": 80, "alphanum_fraction": 0.6180535966, "num_tokens": 1082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6080607534443218}}
{"text": "#include <boost/numeric/odeint.hpp>\n#include <vector>\n\nusing namespace boost::numeric::odeint;\n\n/* The type of container used to hold the state vector */\ntypedef std::vector<double> state_type;\n\nconst double gam = 0.15;\n\n/* The rhs of x' = f(x) */\nvoid harmonic_oscillator(const state_type &x, state_type &dxdt, const double /* t */)\n{\n    dxdt[0] = x[1];\n    dxdt[1] = -x[0] - gam * x[1];\n}\n\n// An example of observer to record steps in the integration\nstruct push_back_state_and_time\n{\n    std::vector<state_type> &m_states;\n    std::vector<double> &m_times;\n\n    push_back_state_and_time(std::vector<state_type> &states, std::vector<double> &times)\n        : m_states(states), m_times(times) {}\n\n    void operator()(const state_type &x, double t)\n    {\n        m_states.push_back(x);\n        m_times.push_back(t);\n    }\n};\n\nint main()\n{\n\n    // Containers to store solution\n    std::vector<state_type> x_vec;\n    std::vector<double> times;\n\n    // Unknown variables with initial conditions\n    state_type x(2);\n    x[0] = 1.0; // start at x=1.0, p=0.0\n    x[1] = 0.0;\n\n    // Integration process. Returns the number of performed steps. This one determines\n    // the stepper automatically.\n    //    auto steps = integrate(harmonic_oscillator,\n    //                           x, 0.0, 10.0, 0.1,\n    //                           push_back_state_and_time(x_vec, times));\n\n    // Or you can choose it explicitly\n    runge_kutta4<state_type> stepper;\n    auto steps = integrate_const(\n        stepper,\n        harmonic_oscillator,\n        x,\n        0.0,\n        10.0,\n        0.1,\n        push_back_state_and_time(x_vec, times));\n\n    /* output */\n    for (size_t i = 0; i <= steps; i++)\n    {\n        std::cout << times[i] << '\\t' << x_vec[i][0] << '\\t' << x_vec[i][1] << '\\n';\n    }\n\n    std::cout << \"\\n*******************\\n\\n\";\n\n    // Or, for a finer control, each step can be performed explicitly as below\n    const auto dt = 0.1;\n    const auto t0 = 0.0;\n    const auto tfinal = 10.0;\n    state_type x_explicit(2);\n    x_explicit[0] = 1.0; // start at x=1.0, p=0.0\n    x_explicit[1] = 0.0;\n    std::cout << 0 << '\\t' << x_explicit[0] << '\\t' << x_explicit[1] << '\\n';\n    for (double t = t0 + dt; t < tfinal; t += dt)\n    {\n        stepper.do_step(harmonic_oscillator, x_explicit, t, dt);\n        std::cout << t << '\\t' << x_explicit[0] << '\\t' << x_explicit[1] << '\\n';\n    }\n\n    return 0;\n}", "meta": {"hexsha": "e1862d3fd5c615f241953bf4f2634175be08308a", "size": 2401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/boost/standalones/simple_boost.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/simple_boost.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/simple_boost.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": 27.9186046512, "max_line_length": 89, "alphanum_fraction": 0.5751770096, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6079812490781653}}
{"text": "#include \"Util.h\"\n\n#include \"navtypes.h\"\n\n#include <iostream>\n#include <random>\n#include <time.h>\n\n#include <Eigen/LU>\n#include <sys/time.h>\n\nusing namespace navtypes;\n\nnamespace util {\nbool almostEqual(double a, double b, double threshold) {\n\treturn std::abs(a - b) < threshold;\n}\n\ndouble quatToHeading(double qw, double qx, double qy, double qz) {\n\tEigen::Quaterniond quat(qw, qx, qy, qz);\n\treturn quatToHeading(quat);\n}\n\ndouble quatToHeading(Eigen::Quaterniond quat) {\n\tquat.normalize();\n\tEigen::Matrix3d rotMat = quat.toRotationMatrix();\n\tEigen::Vector3d transformedX = rotMat * Eigen::Vector3d::UnitX();\n\t// flatten to xy-plane\n\ttransformedX(2) = 0;\n\t// recover heading\n\tdouble heading = std::atan2(transformedX(1), transformedX(0));\n\treturn heading;\n}\n\nScopedTimer::ScopedTimer(std::string name)\n\t: startTime(std::chrono::high_resolution_clock::now()), name(std::move(name)) {}\n\nScopedTimer::ScopedTimer() : ScopedTimer(\"\") {}\n\nScopedTimer::~ScopedTimer() {\n\tif (!name.empty()) {\n\t\tauto now = std::chrono::high_resolution_clock::now();\n\t\tauto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(now - startTime);\n\t\tstd::cout << \"[\" << name << \"] ElapsedTime: \" << elapsed.count() << \"us\\n\";\n\t}\n}\n\nstd::chrono::microseconds ScopedTimer::elapsedTime() const {\n\tauto now = std::chrono::high_resolution_clock::now();\n\tauto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(now - startTime);\n\treturn elapsed;\n}\n\npoints_t transformReadings(const points_t& ps, const transform_t& tf) {\n\ttransform_t tf_inv = tf.inverse();\n\tpoints_t readings({});\n\tfor (point_t p : ps) {\n\t\treadings.push_back(tf_inv * p);\n\t}\n\treturn readings;\n}\n\ntrajectory_t transformTraj(const trajectory_t& traj, const transform_t& tf) {\n\ttrajectory_t tf_traj({});\n\tfor (const transform_t& tf_i : traj) {\n\t\ttf_traj.push_back(tf_i * tf);\n\t}\n\treturn tf_traj;\n}\n\nbool collides(const transform_t& tf, const points_t& ps, double radius) {\n\tfor (const point_t& p : ps) {\n\t\tif (p(2) == 0.0) {\n\t\t\t// This point is a \"no data\" point\n\t\t\tcontinue;\n\t\t}\n\t\tpoint_t tf_p = tf * p;\n\t\ttf_p(2) = 0;\n\t\tif (tf_p.norm() < radius)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\ntransform_t toTransformRotateFirst(double x, double y, double theta) {\n\ttransform_t m;\n\tm << cos(theta), sin(theta), -x, -sin(theta), cos(theta), -y, 0, 0, 1;\n\treturn m;\n}\n\ndouble closestHeading(double theta, double prev_theta) {\n\twhile (theta < prev_theta - M_PI)\n\t\ttheta += 2 * M_PI;\n\twhile (theta > prev_theta + M_PI)\n\t\ttheta -= 2 * M_PI;\n\treturn theta;\n}\n\npose_t toPose(const transform_t& trf, double prev_theta) {\n\tpose_t s = trf.inverse() * pose_t(0, 0, 1);\n\tdouble cos_theta = trf(0, 0);\n\tdouble sin_theta = -trf(1, 0);\n\tdouble theta = atan2(sin_theta, cos_theta);\n\ts(2) = closestHeading(theta, prev_theta);\n\treturn s;\n}\n\ntransform_t toTransform(const pose_t& pose) {\n\treturn toTransformRotateFirst(0, 0, pose(2)) * toTransformRotateFirst(pose(0), pose(1), 0);\n}\n\n/**\n * There still might be some variation due to the dependence of the robot position\n * on when exactly each context switch occurs.\n *\n * For programs with more threads, a more sophisticated solution will be necessary.\n */\nstatic std::normal_distribution<double> stdn_dist(0.0, 1.0);\nstatic long seed = std::chrono::system_clock::now().time_since_epoch().count();\n// long seed = 1626474823108702150;\nstatic std::default_random_engine main_generator(seed);\nstatic std::default_random_engine spin_generator(seed);\n\nlong getNormalSeed() {\n\treturn seed;\n}\n\ndouble stdn(int thread_id) {\n\treturn stdn_dist(thread_id == 0 ? main_generator : spin_generator);\n}\n\n} // namespace util\n", "meta": {"hexsha": "1af2ccd8083551756b58d0ab1f6d41c025456a14", "size": 3586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Util.cpp", "max_stars_repo_name": "huskyroboticsteam/Resurgence", "max_stars_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-23T23:31:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:17:41.000Z", "max_issues_repo_path": "src/Util.cpp", "max_issues_repo_name": "huskyroboticsteam/Resurgence", "max_issues_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-22T05:33:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T07:01:47.000Z", "max_forks_repo_path": "src/Util.cpp", "max_forks_repo_name": "huskyroboticsteam/Resurgence", "max_forks_repo_head_hexsha": "649f78103b6d76709fdf55bb38d08c0ff50da140", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.962406015, "max_line_length": 92, "alphanum_fraction": 0.7032905745, "num_tokens": 985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6078894863056481}}
{"text": "/*\n# This file is part of the Astrometry.net suite.\n# Licensed under a 3-clause BSD style license - see LICENSE\n */\n//#include <iostream>\n#include <Eigen/Dense>\n//using namespace std;\nusing namespace Eigen;\n\nextern \"C\" {\n\n#include \"eigen-math.h\"\n#include \"stdio.h\"\n\n#if 0\n} // fool emacs indenter\n#endif\n\nint eigen_solve_least_squares(ematrix_t* A, evector_t** B,\n                               evector_t** X, int NB) {\n    int i;\n    int r,c;\n\n    Map<Matrix<double, Dynamic, Dynamic, RowMajor> >\n        mA(A->data, A->rows, A->cols);\n\n    /*\n     printf(\"mA:\\n\");\n     for (r=0; r<mA.rows(); r++) {\n     printf(\"[\");\n     for (c=0; c<mA.cols(); c++) {\n     printf(\"%s %8.3g\", c ? \",\" : \" \", mA(r,c));\n     }\n     printf(\"]\\n\");\n     }\n     */\n\n    /*\n     for (i=0; i<NB; i++) {\n     printf(\"mB(%i):\\n\", i);\n     Map<VectorXd> mB(B[i]->data, B[i]->N, RowMajor);\n     printf(\"[\");\n     for (c=0; c<mB.size(); c++) {\n     printf(\"%s %8.3g\", c ? \",\" : \" \", mB(c));\n     }\n     printf(\"]\\n\");\n     }\n     */\n\n    JacobiSVD<MatrixXd> svd(mA, ComputeThinU | ComputeThinV);\n    for (i=0; i<NB; i++) {\n        Map<VectorXd> b(B[i]->data, B[i]->N, RowMajor);\n        VectorXd x = svd.solve(b);\n        // copy results back to C space...\n        for (r=0; r<x.size(); r++)\n            evector_set(X[i], r, x[r]);\n    }\n\n    return 0;\n}\n\n#if 0\n{ // fool emacs indenter\n#endif\n}\n\n\n", "meta": {"hexsha": "397ac4668c22ec53dfef45980eae4393100853f2", "size": 1372, "ext": "cc", "lang": "C++", "max_stars_repo_path": "util/eigen-math-cc.cc", "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": ["Net-SNMP", "Xnet"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_issues_repo_path": "util/eigen-math-cc.cc", "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_licenses": ["Net-SNMP", "Xnet"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_forks_repo_path": "util/eigen-math-cc.cc", "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": ["Net-SNMP", "Xnet"], "max_forks_count": 173.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "avg_line_length": 20.1764705882, "max_line_length": 61, "alphanum_fraction": 0.4934402332, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6077772633647801}}
{"text": "#include <iostream>\n#include <stdlib.h>\n#include <cmath>\n#include <NTL/ZZ.h>\n\n\nusing namespace std;\nusing namespace NTL;\n\n#include \"iterative.h\"\n#include \"recursive.h\"\n\nusing namespace std;\nusing namespace NTL;\nusing namespace chrono;\n\n//#define ITERATIVE\n\nvoid usage_example_zp(uint npoints, uint flen){\n    long degree = npoints-1;\n\n    ZZ prime;\n    GenPrime(prime, flen);\n    ZZ_p::init(prime);\n\n//  interpolation points:\n    ZZ_p* X = new ZZ_p[degree+1];\n    ZZ_p* Y = new ZZ_p[degree+1];\n    for(unsigned int i=0;i<=degree; i++) {\n        random(X[i]);\n        random(Y[i]);\n    }\n\n    ZZ_pX P;\n#ifdef ITERATIVE\n    poly_interpolate_zp_iterative(degree, X, Y, P);\n#else\n    poly_interpolate_zp_recursive(degree, X, Y, P);\n#endif\n\n    // EVALUATE\n    ZZ_p* X2 = new ZZ_p[degree+1];\n    ZZ_p* Y2 = new ZZ_p[degree+1];\n    for(unsigned int i=0;i<=degree; i++) {\n        random(X[i]);\n    }\n#ifdef ITERATIVE\n    poly_evaluate_zp_iterative(degree, P, X2, Y2);\n#else\n    poly_evaluate_zp_recursive(degree, P, X2, Y2);\n#endif\n\n    delete[] X;\n    delete[] Y;\n    delete[] X2;\n    delete[] Y2;\n}\n\n\nint main(int argc, char *argv[]) {\n   uint num_points = pow(2,13)-1;\n   uint field_bitlen = 400; \n    if(1<argc)\n\tnum_points = atoi(argv[1]);\n    if(2<argc)\n    \tfield_bitlen = atoi(argv[2]);\n    cout << \"num_points: \" << num_points << \", field_bitlen: \" << field_bitlen << endl;\n    usage_example_zp(num_points, field_bitlen);\n\n}\n", "meta": {"hexsha": "9078c08613d0bf98d6545beccf4222d6367e309f", "size": 1427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "AvishayYanay/FastPolynomial", "max_stars_repo_head_hexsha": "de3859aa50bd360751199c7cab721e44fc05e097", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-01T14:50:41.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-01T14:50:41.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "AvishayYanay/FastPolynomial", "max_issues_repo_head_hexsha": "de3859aa50bd360751199c7cab721e44fc05e097", "max_issues_repo_licenses": ["MIT"], "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": "AvishayYanay/FastPolynomial", "max_forks_repo_head_hexsha": "de3859aa50bd360751199c7cab721e44fc05e097", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-03-28T13:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-28T13:22:23.000Z", "avg_line_length": 20.0985915493, "max_line_length": 87, "alphanum_fraction": 0.6306937631, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.6077772611074588}}
{"text": "/*\n * Copyright Nick Thompson, 2019\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"math_unit_test.hpp\"\n#include <numeric>\n#include <utility>\n#include <random>\n#include <boost/core/demangle.hpp>\n#include <boost/math/distributions/empirical_cumulative_distribution_function.hpp>\n#ifdef BOOST_HAS_FLOAT128\n#include <boost/multiprecision/float128.hpp>\nusing boost::multiprecision::float128;\n#endif\n\nusing boost::math::empirical_cumulative_distribution_function;\n\ntemplate<class Z>\nvoid test_uniform_z()\n{\n    std::vector<Z> v{6,3,4,1,2,5};\n\n    auto ecdf = empirical_cumulative_distribution_function(std::move(v));\n\n    CHECK_ULP_CLOSE(1.0/6.0, ecdf(1), 1);\n    CHECK_ULP_CLOSE(2.0/6.0, ecdf(2), 1);\n    CHECK_ULP_CLOSE(3.0/6.0, ecdf(3), 1);\n    CHECK_ULP_CLOSE(4.0/6.0, ecdf(4), 1);\n    CHECK_ULP_CLOSE(5.0/6.0, ecdf(5), 1);\n    CHECK_ULP_CLOSE(6.0/6.0, ecdf(6), 1);\n\n    // Less trivial:\n\n    v = {6,3,4,1,1,1,2,4};\n    ecdf = empirical_cumulative_distribution_function(std::move(v));\n    CHECK_ULP_CLOSE(3.0/8.0, ecdf(1), 1);\n    CHECK_ULP_CLOSE(4.0/8.0, ecdf(2), 1);\n    CHECK_ULP_CLOSE(5.0/8.0, ecdf(3), 1);\n    CHECK_ULP_CLOSE(7.0/8.0, ecdf(4), 1);\n    CHECK_ULP_CLOSE(7.0/8.0, ecdf(5), 1);\n    CHECK_ULP_CLOSE(8.0/8.0, ecdf(6), 1);\n}\n\ntemplate<class Real>\nvoid test_uniform()\n{\n    size_t n = 128;\n    std::vector<Real> v(n);\n    for (size_t i = 0; i < n; ++i) {\n      v[i] = Real(i+1)/Real(n);\n    }\n\n    auto ecdf = empirical_cumulative_distribution_function(std::move(v));\n\n    for (size_t i = 0; i < n; ++i) {\n      CHECK_ULP_CLOSE(Real(i+1)/Real(n), ecdf(Real(i+1)/Real(n)), 1);\n    }\n}\n\n\nint main()\n{\n    test_uniform_z<int>();\n    test_uniform<double>();\n    return boost::math::test::report_errors();\n}\n", "meta": {"hexsha": "632f3653bd8f14c369be81bcbf0ad43ef4f267ac", "size": 1870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/empirical_cumulative_distribution_test.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/math/test/empirical_cumulative_distribution_test.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/test/empirical_cumulative_distribution_test.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 26.7142857143, "max_line_length": 82, "alphanum_fraction": 0.664171123, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6077588356424566}}
{"text": "/**\n * @file \tex6.cpp\n * @author \tFabian Wegscheider\n * @date \tJun 20, 2017\n */\n\n#include <iostream>\n#include <fstream>\n#include <boost/program_options.hpp>\n#include <boost/heap/fibonacci_heap.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/spirit/include/qi.hpp>\n\nusing namespace std;\nusing namespace boost;\nnamespace po = boost::program_options;\n\ntypedef adjacency_list<vecS, vecS, undirectedS,\n\t\tno_property, property<edge_weight_t, double>> Graph;\ntypedef graph_traits<Graph>::vertex_descriptor Vertex;\ntypedef pair<int,int> Edge;\ntypedef pair<int, double> Pair;\ntypename graph_traits<Graph>::out_edge_iterator out_i, out_end;\n\n\n/**\n * Data that is stored in one node of a heap. Contains an integer and a double.\n * Comparisons are made by the double, smaller has higher priority\n */\nstruct heap_data\n{\n    heap::fibonacci_heap<heap_data>::handle_type handle;\n    Pair pair;\n\n    heap_data(Pair p):\n        pair(p)\n    {}\n\n    bool operator<(heap_data const & rhs) const {\n        return pair.second > rhs.pair.second;\n    }\n};\n\n\nusing Heap = heap::fibonacci_heap<heap_data>;\n\n/**\n * My own implementation of Dijkstra using a fibonacci heap from boost\n * @param g the graph which is an adjacency_list from boost\n * @param numVertices the number of vertices in g\n * @param source the source node for Dijkstra\n * @return vector of resulting distances to source\n */\nvector<double> myDijkstra(Graph& g, int numVertices, int source) {\n\n\tvector<double> distances(numVertices);\n\tdistances[0] = 0;\n\n\tHeap heap;\n\n\tHeap::handle_type *handles = new Heap::handle_type[numVertices];\n\thandles[0] = heap.push(make_pair(0,0.));\n\n\t//initialization of the heap\n\tfor (int i = 1; i < numVertices; ++i) {\n\t\thandles[i] = heap.push(make_pair(i, numeric_limits<double>::infinity()));\n\t\tdistances[i] = numeric_limits<double>::infinity();\n\t}\n\n\tproperty_map<Graph, edge_weight_t>::type weights = get(edge_weight, g);\n\tproperty_map<Graph, vertex_index_t>::type index = get(vertex_index, g);\n\n\n\t//the actual algorithm\n\twhile (!heap.empty()) {\n\t\tPair min = heap.top().pair;\n\t\theap.pop();\n\t\tfor (tie(out_i, out_end) = out_edges(*(vertices(g).first+min.first), g);\n\t\t\t\tout_i != out_end; ++out_i) {\n\t\t\tdouble tmp = min.second + weights[*out_i];\n\t\t\tint targetIndex = index[target(*out_i, g)];\n\t\t\tif (tmp < distances[targetIndex]) {\n\t\t\t\tdistances[targetIndex] = tmp;\n\t\t\t\t(*handles[targetIndex]).pair.second = tmp;\n\t\t\t\theap.increase(handles[targetIndex]);\n\t\t\t}\n\t\t}\n\t}\n\n\tdelete[] handles;\n\treturn distances;\n}\n\n\n/**\n * main function which reads a graph from a .gph file, then calculates shortest\n * paths from all vertices to the first vertex with the dijsktra algorithm\n * and prints the furthest vertex together with its distance\n * to the standard output\n * @param numargs number of inputs on command line\n * @param args array of * inputs on command line\n * @return whether the function operated successfully\n */\nint main(int numargs, char *args[]) {\n\n\ttimer::cpu_timer t;\n\tbool useOwnMethod;\n\n\t/*parsing command line options*/\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t\t\t(\"help,h\", \"produce help message\")\n\t\t\t(\"m1\", \"use my own dijkstra method\")\n\t\t\t(\"m2\", \"use dijkstra method from boost\")\n\t\t\t(\"input-file\", po::value< string >(), \"input file\");\n\tpo::positional_options_description p;\n\tp.add(\"input-file\", -1);\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(numargs, args).\n\t\t\toptions(desc).positional(p).run(), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t    cout << desc << \"\\n\";\n\t   \texit(EXIT_SUCCESS);\n\t}\n\n\tif (vm.count(\"m1\") && !vm.count(\"m2\")) {\n\t\tuseOwnMethod = true;\n\t\tcout << \"using my own method for calculation...\" << endl << endl;\n\t} else if (vm.count(\"m2\") && !vm.count(\"m1\")) {\n\t\tuseOwnMethod = false;\n\t\tcout << \"using boost method for calculation...\" << endl << endl;\n\t} else {\n\t\tcerr << \"please specify the method you want to use (type -h for help)\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tstring input;\n\tif (vm.count(\"input-file\")) {\n\t    input = vm[\"input-file\"].as< string >();\n\t} else {\n\t\tcerr << \"please specify an input file in the .gph format\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\t/*end of parsing command line options*/\n\n\n\tifstream inputFile;\n\tinputFile.open(input);\t\t\t\t\t\t\t//trying to read file\n\tif (inputFile.fail()) {\n\t\tcerr << \"file could not be read\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tint numVertices;\n\tint numEdges;\n\n\tstring line;\n\tgetline(inputFile, line);\t\t\t\t\t//first line is read\n\tvector<string> parts;\n\tsplit(parts, line, is_any_of(\" \"));\n\n\tif (parts.size() != 2) {\n\t\tcerr << \"error in file: first line should consist of two integers!\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\ttry {\n\t\tnumVertices = stoi(parts[0]);\t\t//information from the first line\n\t\tnumEdges = stoi(parts[1]);\t\t\t//are stored\n\t} catch (...) {\n\t\tcerr << \"error in file: first line should consist of two integers!\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tEdge *edges =  new Edge[numEdges];\t\t\t//in these arrays all information about\n\tdouble *weights = new double[numEdges];\t\t//the edges are stored\n\n\tint i = 0;\n\n\tusing namespace boost::spirit;\n\tusing qi::int_;\n\tusing qi::double_;\n\tusing qi::phrase_parse;\n\tusing ascii::space;\n\n\t//read line by line using boost to parse each line to int,int,double\n\twhile (getline(inputFile, line)) {\n\t\ttry {\n\t\t\tauto it = line.begin();\n\t\t\tint start;\n\t\t\tint end;\n\t\t\tdouble weight;\n\t\t\tbool success = phrase_parse(it, line.end(),\n\t\t\t\t\tint_[([&start](int j){ start = j; })]\n\t\t\t\t\t>> int_[([&end](int j){ end = j; })]\n\t\t\t\t\t>> double_[([&weight](double j){ weight = j; })], space);\n\t\t\tif (success && it == line.end()) {\n\t\t\t\tedges[i] = Edge(start-1, end-1);\n\t\t\t\tweights[i] = weight;\n\t\t\t} else {\n\t\t\t\tcerr << \"error in line \" << (i+2) << \": line should consists of \"\n\t\t\t\t\t\t\"two integers and a double!\" << endl;\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t} catch(...) {\n\t\t\tcerr << \"error in line \" << (i+2) << \": line should consists of \"\n\t\t\t\t\t\"two integers and a double!\" << endl;\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\t++i;\n\t}\n\n\t//undirected graph is constructed with all edges and their weights\n\tGraph g(edges, edges + numEdges , weights, numVertices);\n\n\t//in this vector the resulting distances from dijkstra are stored\n\tvector<double> distances;\n\n\t//call of dijsktra depending on chosen option\n\tif (!useOwnMethod) {\n\t\tdistances.resize(numVertices);\n\t\tdijkstra_shortest_paths(g, *(vertices(g).first), distance_map(&distances[0]));\n\t} else {\n\t\tdistances = myDijkstra(g, numVertices, 0);\n\t}\n\n\tdouble maxDist = 0;\n\tint maxIdx = 0;\n\n\t//search for furthest vertex\n\tfor (int i = 1; i < numVertices; i++) {\n\t\tdouble tmp = distances[i];\n\t\t\tif (tmp > maxDist) {\n\t\t\t\tmaxDist = tmp;\n\t\t\t\tmaxIdx = i;\n\t\t\t}\n\t}\n\n\t//results are printed to command line\n\tcout << \"RESULT VERTEX \" << (maxIdx+1) << endl;\n\tcout << \"RESULT DIST \" << maxDist << endl;\n\tcout << endl << \"running time: \" << t.format() <<  endl;\n\n\tdelete[] edges;\n\tdelete[] weights;\n\n\texit(EXIT_SUCCESS);\n}\n\n\n\n", "meta": {"hexsha": "d3c52f7ad0230216419a89d65700d5c32420e581", "size": 7034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wegscheider/Ex6/ex6.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Wegscheider/Ex6/ex6.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Wegscheider/Ex6/ex6.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 27.2635658915, "max_line_length": 81, "alphanum_fraction": 0.6678987774, "num_tokens": 1889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6077588340443021}}
{"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2016 Gael Guennebaud <gael.guennebaud@inria.fr>\r\n//\r\n// This Source Code Form is subject to the terms of the Mozilla\r\n// Public License v. 2.0. If a copy of the MPL was not distributed\r\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\r\n\r\n#include \"main.h\"\r\n#include <Eigen/LU>\r\n#include <Eigen/Cholesky>\r\n#include <Eigen/QR>\r\n\r\n// This file test inplace decomposition through Ref<>, as supported by Cholesky, LU, and QR decompositions.\r\n\r\ntemplate<typename DecType,typename MatrixType> void inplace(bool square = false, bool SPD = false)\r\n{\r\n  typedef typename MatrixType::Scalar Scalar;\r\n  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> RhsType;\r\n  typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> ResType;\r\n\r\n  Index rows = MatrixType::RowsAtCompileTime==Dynamic ? internal::random<Index>(2,EIGEN_TEST_MAX_SIZE/2) : Index(MatrixType::RowsAtCompileTime);\r\n  Index cols = MatrixType::ColsAtCompileTime==Dynamic ? (square?rows:internal::random<Index>(2,rows))    : Index(MatrixType::ColsAtCompileTime);\r\n\r\n  MatrixType A = MatrixType::Random(rows,cols);\r\n  RhsType b = RhsType::Random(rows);\r\n  ResType x(cols);\r\n\r\n  if(SPD)\r\n  {\r\n    assert(square);\r\n    A.topRows(cols) = A.topRows(cols).adjoint() * A.topRows(cols);\r\n    A.diagonal().array() += 1e-3;\r\n  }\r\n\r\n  MatrixType A0 = A;\r\n  MatrixType A1 = A;\r\n\r\n  DecType dec(A);\r\n\r\n  // Check that the content of A has been modified\r\n  VERIFY_IS_NOT_APPROX( A, A0 );\r\n\r\n  // Check that the decomposition is correct:\r\n  if(rows==cols)\r\n  {\r\n    VERIFY_IS_APPROX( A0 * (x = dec.solve(b)), b );\r\n  }\r\n  else\r\n  {\r\n    VERIFY_IS_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );\r\n  }\r\n\r\n  // Check that modifying A breaks the current dec:\r\n  A.setRandom();\r\n  if(rows==cols)\r\n  {\r\n    VERIFY_IS_NOT_APPROX( A0 * (x = dec.solve(b)), b );\r\n  }\r\n  else\r\n  {\r\n    VERIFY_IS_NOT_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );\r\n  }\r\n\r\n  // Check that calling compute(A1) does not modify A1:\r\n  A = A0;\r\n  dec.compute(A1);\r\n  VERIFY_IS_EQUAL(A0,A1);\r\n  VERIFY_IS_NOT_APPROX( A, A0 );\r\n  if(rows==cols)\r\n  {\r\n    VERIFY_IS_APPROX( A0 * (x = dec.solve(b)), b );\r\n  }\r\n  else\r\n  {\r\n    VERIFY_IS_APPROX( A0.transpose() * A0 * (x = dec.solve(b)), A0.transpose() * b );\r\n  }\r\n}\r\n\r\n\r\nvoid test_inplace_decomposition()\r\n{\r\n  EIGEN_UNUSED typedef Matrix<double,4,3> Matrix43d;\r\n  for(int i = 0; i < g_repeat; i++) {\r\n    CALL_SUBTEST_1(( inplace<LLT<Ref<MatrixXd> >, MatrixXd>(true,true) ));\r\n    CALL_SUBTEST_1(( inplace<LLT<Ref<Matrix4d> >, Matrix4d>(true,true) ));\r\n\r\n    CALL_SUBTEST_2(( inplace<LDLT<Ref<MatrixXd> >, MatrixXd>(true,true) ));\r\n    CALL_SUBTEST_2(( inplace<LDLT<Ref<Matrix4d> >, Matrix4d>(true,true) ));\r\n\r\n    CALL_SUBTEST_3(( inplace<PartialPivLU<Ref<MatrixXd> >, MatrixXd>(true,false) ));\r\n    CALL_SUBTEST_3(( inplace<PartialPivLU<Ref<Matrix4d> >, Matrix4d>(true,false) ));\r\n\r\n    CALL_SUBTEST_4(( inplace<FullPivLU<Ref<MatrixXd> >, MatrixXd>(true,false) ));\r\n    CALL_SUBTEST_4(( inplace<FullPivLU<Ref<Matrix4d> >, Matrix4d>(true,false) ));\r\n\r\n    CALL_SUBTEST_5(( inplace<HouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));\r\n    CALL_SUBTEST_5(( inplace<HouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));\r\n\r\n    CALL_SUBTEST_6(( inplace<ColPivHouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));\r\n    CALL_SUBTEST_6(( inplace<ColPivHouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));\r\n\r\n    CALL_SUBTEST_7(( inplace<FullPivHouseholderQR<Ref<MatrixXd> >, MatrixXd>(false,false) ));\r\n    CALL_SUBTEST_7(( inplace<FullPivHouseholderQR<Ref<Matrix43d> >, Matrix43d>(false,false) ));\r\n\r\n    CALL_SUBTEST_8(( inplace<CompleteOrthogonalDecomposition<Ref<MatrixXd> >, MatrixXd>(false,false) ));\r\n    CALL_SUBTEST_8(( inplace<CompleteOrthogonalDecomposition<Ref<Matrix43d> >, Matrix43d>(false,false) ));\r\n  }\r\n}\r\n", "meta": {"hexsha": "907731bf961347682d3c0fb058b61490474a0fa1", "size": 3982, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/test/inplace_decomposition.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/test/inplace_decomposition.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/test/inplace_decomposition.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": 35.8738738739, "max_line_length": 145, "alphanum_fraction": 0.6715218483, "num_tokens": 1202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6077588324461469}}
{"text": "/*-----------------------------------------------------------------------------+    \nInterval Container Library\nAuthor: Joachim Faulhaber\nCopyright (c) 2007-2009: Joachim Faulhaber\nCopyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n/** Example man_power.cpp \\file man_power.cpp\n    \\brief Using set style operators to compute with interval sets and maps.\n\n    Interval sets and maps can be filled and manipulated using\n    set style operation like union (+=), difference (-=) and intersection\n    (&=).\n\n    In this example 'man_power' a number of those operations are\n    demonstrated in the process of calculation the available working \n    times (man-power) of a company's employees accounting for weekends,\n    holidays, sickness times and vacations.\n\n    \\include man_power_/man_power.cpp\n*/\n//[example_man_power\n// The next line includes <boost/gregorian/date.hpp>\n// and a few lines of adapter code.\n#include <boost/icl/gregorian.hpp> \n#include <iostream>\n#include <boost/icl/discrete_interval.hpp>\n#include <boost/icl/interval_map.hpp>\n\nusing namespace std;\nusing namespace boost::gregorian;\nusing namespace boost::icl;\n\n\n// Function weekends returns the interval_set of weekends that are contained in\n// the date interval 'scope'\ninterval_set<date> weekends(const discrete_interval<date>& scope)\n{\n    interval_set<date> weekends;\n\n    date cur_weekend_sat \n        = first(scope) \n          + days(days_until_weekday(first(scope), greg_weekday(Saturday))) \n          - weeks(1);\n    week_iterator week_iter(cur_weekend_sat);\n\n    for(; week_iter <= last(scope); ++week_iter)\n        weekends += discrete_interval<date>::right_open(*week_iter, *week_iter + days(2));\n\n    weekends &= scope; // cut off the surplus\n\n    return weekends;\n}\n\n// The available working time for the employees of a company is calculated\n// for a period of 3 months accounting for weekends and holidays.\n//    The available daily working time for the employees is calculated\n// using interval_sets and interval_maps demonstrating a number of\n// addition, subtraction and intersection operations.\nvoid man_power()\n{\n    date someday = from_string(\"2008-08-01\");\n    date thenday = someday + months(3);\n\n    discrete_interval<date> scope = discrete_interval<date>::right_open(someday, thenday);\n\n    // ------------------------------------------------------------------------\n    // (1) In a first step, the regular working times are computed for the\n    // company within the given scope. From all available days, the weekends\n    // and holidays have to be subtracted: \n    interval_set<date> worktime(scope);\n    // Subtract the weekends\n    worktime -= weekends(scope);\n    // Subtract holidays\n    worktime -= from_string(\"2008-10-03\"); //German reunification ;)\n\n    // company holidays (fictitious ;)\n    worktime -= discrete_interval<date>::closed(from_string(\"2008-08-18\"), \n                                                from_string(\"2008-08-22\"));\n\n    //-------------------------------------------------------------------------\n    // (2) Now we calculate the individual work times for some employees\n    //-------------------------------------------------------------------------\n    // In the company works Claudia. \n    // This is the map of her regular working times:\n    interval_map<date,int> claudias_working_hours;\n\n    // Claudia is working 8 hours a day. So the next statement says\n    // that every day in the whole scope is mapped to 8 hours worktime.\n    claudias_working_hours += make_pair(scope, 8);\n\n    // But Claudia only works 8 hours on regular working days so we do\n    // an intersection of the interval_map with the interval_set worktime:\n    claudias_working_hours &= worktime;\n\n    // Yet, in addition Claudia has her own absence times like\n    discrete_interval<date> claudias_seminar (from_string(\"2008-09-16\"), \n                                              from_string(\"2008-09-24\"),\n                                              interval_bounds::closed());\n    discrete_interval<date> claudias_vacation(from_string(\"2008-08-01\"), \n                                              from_string(\"2008-08-14\"),\n                                              interval_bounds::closed());\n\n    interval_set<date> claudias_absence_times(claudias_seminar);\n    claudias_absence_times += claudias_vacation;\n\n    // All the absence times have to subtracted from the map of her working times\n    claudias_working_hours -= claudias_absence_times;\n\n    //-------------------------------------------------------------------------\n    // Claudia's boss is Bodo. He only works part time. \n    // This is the map of his regular working times:\n    interval_map<date,int> bodos_working_hours;\n\n    // Bodo is working 4 hours a day.\n    bodos_working_hours += make_pair(scope, 4);\n\n    // Bodo works only on regular working days\n    bodos_working_hours &= worktime;\n\n    // Bodos additional absence times\n    discrete_interval<date>      bodos_flu(from_string(\"2008-09-19\"), from_string(\"2008-09-29\"), \n                                           interval_bounds::closed());\n    discrete_interval<date> bodos_vacation(from_string(\"2008-08-15\"), from_string(\"2008-09-03\"), \n                                           interval_bounds::closed());\n\n    interval_set<date> bodos_absence_times(bodos_flu);\n    bodos_absence_times += bodos_vacation;\n\n    // All the absence times have to be subtracted from the map of his working times\n    bodos_working_hours -= bodos_absence_times;\n\n    //-------------------------------------------------------------------------\n    // (3) Finally we want to calculate the available manpower of the company\n    // for the selected time scope: This is done by adding up the employees\n    // working time maps:\n    interval_map<date,int> manpower;\n    manpower += claudias_working_hours;\n    manpower += bodos_working_hours;\n\n\n    cout << first(scope) << \" - \" << last(scope) \n         << \"    available man-power:\" << endl;\n    cout << \"---------------------------------------------------------------\\n\";\n\n    for(interval_map<date,int>::iterator it = manpower.begin(); \n        it != manpower.end(); it++)\n    {\n        cout << first(it->first) << \" - \" << last(it->first) \n             << \" -> \" << it->second << endl;\n    }\n}\n\nint main()\n{\n    cout << \">>Interval Container Library: Sample man_power.cpp <<\\n\";\n    cout << \"---------------------------------------------------------------\\n\";\n    man_power();\n    return 0;\n}\n\n// Program output:\n/*\n>>Interval Container Library: Sample man_power.cpp <<\n---------------------------------------------------------------\n2008-Aug-01 - 2008-Oct-31    available man-power:\n---------------------------------------------------------------\n2008-Aug-01 - 2008-Aug-01 -> 4\n2008-Aug-04 - 2008-Aug-08 -> 4\n2008-Aug-11 - 2008-Aug-14 -> 4\n2008-Aug-15 - 2008-Aug-15 -> 8\n2008-Aug-25 - 2008-Aug-29 -> 8\n2008-Sep-01 - 2008-Sep-03 -> 8\n2008-Sep-04 - 2008-Sep-05 -> 12\n2008-Sep-08 - 2008-Sep-12 -> 12\n2008-Sep-15 - 2008-Sep-15 -> 12\n2008-Sep-16 - 2008-Sep-18 -> 4\n2008-Sep-25 - 2008-Sep-26 -> 8\n2008-Sep-29 - 2008-Sep-29 -> 8\n2008-Sep-30 - 2008-Oct-02 -> 12\n2008-Oct-06 - 2008-Oct-10 -> 12\n2008-Oct-13 - 2008-Oct-17 -> 12\n2008-Oct-20 - 2008-Oct-24 -> 12\n2008-Oct-27 - 2008-Oct-31 -> 12\n*/\n//]\n\n", "meta": {"hexsha": "a095d0e3ca7a644897fdf819ab755e55ac0481cc", "size": 7598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/icl/example/man_power_/man_power.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/icl/example/man_power_/man_power.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/icl/example/man_power_/man_power.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": 39.780104712, "max_line_length": 97, "alphanum_fraction": 0.5859436694, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6077588260872361}}
{"text": "#include \"math/itf/vector_3d.h\"\n\n#include <cmath>\n#include <boost/assert.hpp>\n\nusing namespace lb;\n\n/// Adds the vector \\a v to this vector.\nVector3d &Vector3d::operator+=(const Vector3d &v)\n{\n    x += v.x;\n    y += v.y;\n    z += v.z;\n\n    return *this;\n}\n\n/// Returns whether this vector equals the given vector \\a v.\nbool Vector3d::operator==(const Vector3d &v) const\n{\n    return x == v.x && y == v.y && z == v.z;\n}\n\n/// Scales this vector by a factor \\a f and returns a reference to itself.\nVector3d &Vector3d::operator*=(double f)\n{\n    x *= f;\n    y *= f;\n    z *= f;\n    return *this;\n}\n\n/// Divides this vector by a factor \\a f and returns the result vector.\nVector3d Vector3d::operator/(double f) const\n{\n    BOOST_ASSERT(f != 0);\n    double inv = 1.f / f;\n    return {x * inv, y * inv, z * inv};\n}\n\n/// Divides this vector by a factor \\a f and returns a reference to itself.\nVector3d &Vector3d::operator/=(double f)\n{\n    BOOST_ASSERT(f != 0);\n    double inv = 1.f / f;\n    x *= inv;\n    y *= inv;\n    z *= inv;\n    return *this;\n}\n\n/// Calculates the length of this vector and returns it.\ndouble Vector3d::length() const\n{\n    return std::sqrt(lengthSquared());\n}\n\n/// Calculates the square of the length of this vector and returns it.\ndouble Vector3d::lengthSquared() const\n{\n    return x * x + y * y + z * z;\n}\n\n/// Normalizes this vector to a vector with the same direction and magnitude\n/// one.\nvoid Vector3d::normalize()\n{\n    double oneOverLength = 1.0 / length();\n    x *= oneOverLength;\n    y *= oneOverLength;\n    z *= oneOverLength;\n}\n\n/// Calculates a vector that points in the same direction as this vector with\n/// length 1 and returns it.\nVector3d Vector3d::normalized() const\n{\n    return *this / length();\n}\n\n/// Streams a textual representation of the vector \\a v to \\a out.\nstd::ostream &lb::operator<<(std::ostream &out, const Vector3d &v)\n{\n    out << \"(\" << v.x << \", \" << v.y << \", \" << v.z << \")\";\n}\n\n/// Returns the absolute value of the dot product of the two vectors \\a v and \\a\n/// w.\ndouble absDot(const Vector3d &v, const Vector3d &w)\n{\n    return std::fabs(dot(v, w));\n}\n", "meta": {"hexsha": "927dc8990d1459b2993ffd4d64f4e0b76e62ae6e", "size": 2113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/src/vector_3d.cpp", "max_stars_repo_name": "ton/lightbox", "max_stars_repo_head_hexsha": "d4c6ab9849fcafa90c5c3795cb678b8f8ba282fb", "max_stars_repo_licenses": ["MIT"], "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/src/vector_3d.cpp", "max_issues_repo_name": "ton/lightbox", "max_issues_repo_head_hexsha": "d4c6ab9849fcafa90c5c3795cb678b8f8ba282fb", "max_issues_repo_licenses": ["MIT"], "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/src/vector_3d.cpp", "max_forks_repo_name": "ton/lightbox", "max_forks_repo_head_hexsha": "d4c6ab9849fcafa90c5c3795cb678b8f8ba282fb", "max_forks_repo_licenses": ["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.7204301075, "max_line_length": 80, "alphanum_fraction": 0.6256507336, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645723, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.607752056180733}}
{"text": "#ifndef SM_NUMERICAL_DIFF_HPP\n#define SM_NUMERICAL_DIFF_HPP\n\n#include <Eigen/Core>\n#include <sm/assert_macros.hpp>\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\nnamespace sm { namespace eigen {\n\n    template<typename RESULT_VEC_T, typename INPUT_VEC_T, typename JACOBIAN_T = Eigen::MatrixXd>\n    struct NumericalDiffFunctor\n    {\n      typedef RESULT_VEC_T value_t;\n      typedef typename value_t::Scalar scalar_t;\n      typedef INPUT_VEC_T input_t;\n      typedef JACOBIAN_T jacobian_t;\n      \n\n      NumericalDiffFunctor( boost::function< value_t(input_t) > f) : _f(f){}\n      \n      value_t operator()(const input_t & x) { return _f(x); }\n\n      input_t update(const input_t & x, int c, scalar_t delta) { input_t xnew = x; xnew[c] += delta; return xnew; }\n      boost::function<value_t(input_t)> _f;\n    };\n\n    // A simple implementation of central differences to estimate a Jacobian matrix\n    template<typename FUNCTOR_T>\n    struct NumericalDiff\n    {\n      typedef FUNCTOR_T functor_t;\n      typedef typename functor_t::input_t input_t;\n      typedef typename functor_t::value_t value_t;\n      typedef typename functor_t::scalar_t scalar_t;\n      typedef typename functor_t::jacobian_t jacobian_t;\n\n      NumericalDiff(functor_t f, scalar_t eps = sqrt(std::numeric_limits<scalar_t>::epsilon())) : functor(f), eps(eps) {}\n      \n      jacobian_t estimateJacobian(input_t const & x0)\n      {\n        // evaluate the function at the operating point:\n        value_t fx0 = functor(x0);\n        size_t N = x0.size();\n        size_t M = fx0.size();\n\n        //std::cout << \"Size: \" << M << \", \" << N << std::endl;\n        jacobian_t J;\n        J.resize(M, N);\n\n        SM_ASSERT_EQ(std::runtime_error,x0.size(),J.cols(),\"Unexpected number of columns for input size\");\n        SM_ASSERT_EQ(std::runtime_error,fx0.size(),J.rows(),\"Unexpected number of columns for output size\");\n\n        for(unsigned c = 0; c < N; c++) {\n          // Calculate a central difference.\n          // This step size was stolen from cminpack: temp = eps * fabs(x[j]);\n          scalar_t rcEps = std::max(static_cast<scalar_t>(fabs(x0(c))) * eps,eps);\n\n          value_t fxp = functor(functor.update(x0,c,rcEps));\n          value_t fxm = functor(functor.update(x0,c,-rcEps));\n          J.block(0, c, M, 1) = (fxp - fxm).template cast<typename jacobian_t::Scalar>()/(typename jacobian_t::Scalar)(rcEps*(scalar_t)2.0);\n        }\n        return J;\n      }\n\n      functor_t functor;\n      scalar_t eps;\n    };\n\n\n    template < typename ValueType_, typename InputType_>\n    Eigen::MatrixXd numericalDiff(std::function<ValueType_ (const InputType_ &) > function, InputType_ const & input, double eps = sqrt(std::numeric_limits<typename NumericalDiffFunctor<ValueType_, InputType_>::scalar_t>::epsilon())){\n      typedef NumericalDiffFunctor<ValueType_, InputType_> Functor;\n\n      NumericalDiff<Functor> numDiff(Functor(function), eps);\n      return numDiff.estimateJacobian(input);\n    }\n\n  }}\n\n\n#endif /* SM_NUMERICAL_DIFF_HPP */\n\n\n\n", "meta": {"hexsha": "1301d4ac90d43c090f69dc3631560d62e3bced9f", "size": 3016, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_eigen/include/sm/eigen/NumericalDiff.hpp", "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_eigen/include/sm/eigen/NumericalDiff.hpp", "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_eigen/include/sm/eigen/NumericalDiff.hpp", "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": 35.0697674419, "max_line_length": 234, "alphanum_fraction": 0.6618037135, "num_tokens": 762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6077520529190168}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of make_jacobian function.\n */\n#include \"num_collect/auto_diff/forward/make_jacobian.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_template_test_macros.hpp>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n#include \"eigen_approx.h\"\n#include \"num_collect/auto_diff/forward/create_diff_variable.h\"\n\n// NOLINTNEXTLINE\nTEMPLATE_TEST_CASE(\n    \"num_collect::auto_diff::forward::make_jacobian\", \"\", float, double) {\n    using value_type = TestType;\n    using diff_type = Eigen::Matrix<value_type, Eigen::Dynamic, 1>;\n    using variable_vector_type =\n        num_collect::auto_diff::forward::variable_vector_type<diff_type>;\n    using jacobian_type =\n        Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic>;\n\n    SECTION(\"make Jacobian\") {\n        const variable_vector_type vars =\n            num_collect::auto_diff::forward::create_diff_variable_vector(\n                (diff_type(2) << 1.234, 2.345).finished());\n        const variable_vector_type res =\n            (variable_vector_type(3) << vars(0) + vars(1), vars(0) - vars(1),\n                vars(0) * vars(1))\n                .finished();\n        const jacobian_type coeff =\n            num_collect::auto_diff::forward::make_jacobian(res);\n\n        jacobian_type true_coeff = jacobian_type::Zero(3, 2);\n        true_coeff(0, 0) = static_cast<value_type>(1);\n        true_coeff(0, 1) = static_cast<value_type>(1);\n        true_coeff(1, 0) = static_cast<value_type>(1);\n        true_coeff(1, 1) = static_cast<value_type>(-1);\n        true_coeff(2, 0) = vars[1].value();\n        true_coeff(2, 1) = vars[0].value();\n        REQUIRE_THAT(coeff, eigen_approx(true_coeff));\n    }\n}\n", "meta": {"hexsha": "7833743d3ab7858d0a103a7ea171fdb64838fbc0", "size": 2332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/auto_diff/forward/make_jacobian_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units/auto_diff/forward/make_jacobian_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units/auto_diff/forward/make_jacobian_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2295081967, "max_line_length": 77, "alphanum_fraction": 0.6835334477, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6077520486860284}}
{"text": "// Copyright (c) 2021 Graphcore Ltd. All rights reserved.\n\n#ifndef poplibs_test_MatrixTransforms_hpp\n#define poplibs_test_MatrixTransforms_hpp\n\n#include <boost/multi_array.hpp>\n\nnamespace poplibs_test {\nnamespace matrix {\n\ntemplate <typename FPType>\nboost::multi_array<FPType, 2>\ntranspose(const boost::multi_array<FPType, 2> &in) {\n  const auto inRows = in.shape()[0];\n  const auto inColumns = in.shape()[1];\n  boost::multi_array<FPType, 2> out(boost::extents[inColumns][inRows]);\n  for (unsigned inRow = 0; inRow < inRows; inRow++) {\n    for (unsigned inColumn = 0; inColumn < inColumns; inColumn++) {\n      out[inColumn][inRow] = in[inRow][inColumn];\n    }\n  }\n  return out;\n}\n\n} // End namespace matrix\n} // End namespace poplibs_test\n\n#endif // poplibs_test_MatrixTransforms_hpp\n", "meta": {"hexsha": "7bd12e647a6f5aff1749d5188971fe0f30e1d6de", "size": 784, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/poplibs_test/MatrixTransforms.hpp", "max_stars_repo_name": "graphcore/poplibs", "max_stars_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:28.000Z", "max_issues_repo_path": "include/poplibs_test/MatrixTransforms.hpp", "max_issues_repo_name": "graphcore/poplibs", "max_issues_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/poplibs_test/MatrixTransforms.hpp", "max_forks_repo_name": "graphcore/poplibs", "max_forks_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:32:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T14:58:45.000Z", "avg_line_length": 27.0344827586, "max_line_length": 71, "alphanum_fraction": 0.7232142857, "num_tokens": 218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6077520444530401}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n\n\n#include <boost/numeric/mtl/mtl.hpp>\n# include \"boost/rational.hpp\"\n# include \"boost/range.hpp\"\n\n\n\ntypedef boost::rational<long>                              t_Q;\ntypedef mtl::dense_vector<t_Q, mtl::vec::parameters<> > t_dVecQ;\n\n//! Struct containing data about the refinment of a face.\nstruct st_test\n{\n    t_dVecQ vecQ;\n\n    //! Constructor for refinement of a triangle.\n    st_test( const t_dVecQ& vecQ_new )\n    {\n        vecQ = vecQ_new;\n        std::cout << \"vecQ: \" << vecQ << \"\\n\";       // uses size -> ambiguity with size in boost/range\n        std::cout << mtl::size(vecQ_new) << \"\\n\";       \n    }\n};\n\n// using test as function name causes ambiguities  on some compilers\n// (type_traits/has_new_operator.hpp:24: error: \u2018template<class U, U x> struct boost::detail::test' is not a function)\nvoid assign_test( const t_dVecQ& vecQ ) \n{\n    t_dVecQ vecQ_temp;\n    vecQ_temp = vecQ;\n    std::cout << \"vecQ_temp: \" << vecQ_temp << \"\\n\";\n}\n\nvoid test2()\n{\n   t_dVecQ vQ0(2,3);\n    t_dVecQ vQ1(2,2);\n    t_dVecQ vQ2(2,1);\n    std::cout << \"vQ0: \" << vQ0 << \"\\n\";\n    std::cout << \"vQ1: \" << vQ1 << \"\\n\";\n    std::cout << \"size(vQ1): \" << mtl::size(vQ1) << \"\\n\";\n    vQ0 = vQ1 + vQ2;\n    vQ0 = vQ1 - vQ2;\n    vQ0 += vQ1;\n    vQ0 -= vQ1;\n    std::cout << \"vQ0: \" << vQ0 << \"\\n\";\n    t_dVecQ vQ3( vQ0 - vQ1 );\n    std::cout << \"vQ2: \" << vQ2 << \"\\n\";\n    std::cout << \"size(vQ2): \" << mtl::size(vQ2) << \"\\n\";\n}\n\n\nint main(int , char**)\n{\n    t_Q Q0(1,3);\n    std::cout << \"Q0: \" << Q0 << \"\\n\";\n\n    t_dVecQ vecQ0(2,Q0);\n    std::cout << \"vecQ0: \" << vecQ0 << \"\\n\";\n\n    t_Q Q1(1,2);\n    std::cout << \"Q1: \" << Q1 << \"\\n\";\n    t_dVecQ vecQ1(3,Q1);\n    std::cout << \"vecQ1: \" << vecQ1 << \"\\n\";   \n    vecQ1[mtl::irange(2)] = vecQ0;\n    std::cout << \"vecQ1: \" << vecQ1 << \"\\n\";   \n\n    assign_test(vecQ1);\n    st_test test(vecQ1);\n\n    // std::cout << \"size(vecQ1): \" << mtl::size(vecQ1) << \"\\n\";\n\n    test2();\n\n    return 0;\n}\n", "meta": {"hexsha": "7474e56431cf6d2c8edbda8cb3ac5980fd33bdbe", "size": 2372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/vector_rational_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/vector_rational_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/vector_rational_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 26.3555555556, "max_line_length": 118, "alphanum_fraction": 0.5611298482, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6077520369583352}}
{"text": "//\n// Project: Delaunay\n// File: main.cpp\n//\n// Copyright (c) 2021 Miika 'Lehdari' Lehtim\u00e4ki\n// You may use, distribute and modify this code under the terms\n// of the licence specified in file LICENSE which is distributed\n// with this source code package.\n//\n\n#include <random>\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgproc.hpp>\n#include <Eigen/Dense>\n\n\n// 3x3 determinant\ntemplate <typename T_Scalar>\nT_Scalar inline __attribute__((always_inline)) determinant(\n    const T_Scalar& a, const T_Scalar& b, const T_Scalar& c,\n    const T_Scalar& d, const T_Scalar& e, const T_Scalar& f,\n    const T_Scalar& g, const T_Scalar& h, const T_Scalar& i)\n{\n    return a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h;\n}\n\n#ifndef DELAUNAY_BACKEND\n// example implementation of a custom backend\n\n// minimal 2D vector struct\ntemplate <typename T_Scalar>\nstruct Vec2 {\n    T_Scalar  data[2];\n\n    // access with functor operator required only for demo dataset construction\n    // so it is identical with eigen\n    T_Scalar& operator()(int d) { return data[d]; }\n    const T_Scalar& operator()(int d) const { return data[d]; }\n\n    Vec2(T_Scalar x, T_Scalar y) :\n        data    {x,y}\n    {}\n};\n\n// macros required for backend specification\n#define DELAUNAY_VEC Vec2<T_Scalar>\n#define DELAUNAY_VEC_ACCESS(V,D) V.data[D]\n#define DELAUNAY_DETERMINANT determinant\n\n#endif // ifndef DELAUNAY_BACKEND\n\n\n#include \"Delaunay.hpp\"\n\n\n#define RND ((rnd()%10000001)*0.0000001)\n\n\n#if DELAUNAY_BACKEND == DELAUNAY_BACKEND_EIGEN\n\nusing Vec2d = Eigen::Matrix<double, 2, 1>;\nusing Vec2f = Eigen::Matrix<float, 2, 1>;\ntemplate <typename T>\nusing Vector = std::vector<T, Eigen::aligned_allocator<T>>;\n\n#else // custom backend\n\nusing Vec2f = Vec2<float>;\nusing Vec2d = Vec2<double>;\ntemplate <typename T>\nusing Vector = std::vector<T>;\n\n#endif\n\n\n// generate some non-uniform data (not very fancy but does the job)\nvoid createPoints(Vector<Vec2d>& v, const Vec2d& min, const Vec2d& max, int depth = 0)\n{\n    static std::default_random_engine rnd(7155178);\n\n    double terminationProbability = 0.02*depth*depth;\n    if (RND < terminationProbability) {\n        v.emplace_back(min(0) + RND*(max(0)-min(0)), min(1) + RND*(max(1)-min(1)));\n        v.emplace_back(min(0) + RND*(max(0)-min(0)), min(1) + RND*(max(1)-min(1)));\n    }\n    else {\n        Vec2d half(min(0)+(0.3+0.4*RND)*(max(0)-min(0)), min(1)+(0.3+0.4*RND)*(max(1)-min(1)));\n        createPoints(v, min, half, depth+1);\n        createPoints(v, Vec2d(half(0), min(1)), Vec2d(max(0), half(1)), depth+1);\n        createPoints(v, Vec2d(min(0), half(1)), Vec2d(half(0), max(1)), depth+1);\n        createPoints(v, half, max, depth+1);\n    }\n}\n\n\ntemplate <typename T>\nvoid createPointsUniform(Vector<T>& v, const T& min, const T& max, int n)\n{\n    std::default_random_engine rnd(1507715517);\n    v.reserve(n);\n\n    for (int i=0; i<n; ++i) {\n        v.emplace_back(min(0) + RND*(max(0)-min(0)), min(1) + RND*(max(1)-min(1)));\n    }\n}\n\n\ntemplate <typename T>\nvoid visualize(const Vector<T>& points, std::vector<int32_t>& triangulation,\n    const std::string& windowName, const cv::Scalar& lineColor, int wait=0)\n{\n    cv::Mat img(1024, 1024, CV_8UC3, cv::Scalar(0, 0, 0));\n\n    for (int i=0; i<triangulation.size(); i+=3) {\n        cv::line(img,\n            cv::Point(points[triangulation[i]](0), 1024-(int)points[triangulation[i]](1)),\n            cv::Point(points[triangulation[i+1]](0), 1024-(int)points[triangulation[i+1]](1)),\n            lineColor);\n        if (triangulation[i+2] != -1) {\n            cv::line(img,\n                cv::Point(points[triangulation[i+1]](0), 1024-(int)points[triangulation[i+1]](1)),\n                cv::Point(points[triangulation[i+2]](0), 1024-(int)points[triangulation[i+2]](1)),\n                lineColor);\n            cv::line(img,\n                cv::Point(points[triangulation[i+2]](0), 1024-(int)points[triangulation[i+2]](1)),\n                cv::Point(points[triangulation[i]](0), 1024-(int)points[triangulation[i]](1)),\n                lineColor);\n        }\n    }\n\n    for (auto& p : points) {\n        img.at<cv::Vec3b>(1023-(int)p(1), (int)p(0)) = cv::Vec3b(255, 255, 255);\n    }\n\n    cv::imshow(windowName, img);\n    cv::waitKey(wait);\n}\n\n\ntemplate <typename T>\ninline __attribute__((always_inline)) bool inCircle2(\n    const T& a, const T& b, const T& c, const T& d)\n{\n    T dd(d(0)*d(0), d(1)*d(1));\n    return determinant<double>(\n        a(0)-d(0), a(1)-d(1), (a(0)*a(0)-dd(0))+(a(1)*a(1)-dd(1)),\n        b(0)-d(0), b(1)-d(1), (b(0)*b(0)-dd(0))+(b(1)*b(1)-dd(1)),\n        c(0)-d(0), c(1)-d(1), (c(0)*c(0)-dd(0))+(c(1)*c(1)-dd(1))) > 0.0;\n}\n\n\ntemplate <typename T>\nbool checkTriangulation(const Vector<T>& points, std::vector<int32_t>& triangulation)\n{\n    for (size_t i=0; i<triangulation.size(); i+=3) {\n        int p1 = triangulation[i];\n        int p2 = triangulation[i+1];\n        int p3 = triangulation[i+2];\n        if (p3 == -1)\n            continue;\n\n        for (size_t j=0; j<points.size(); ++j) {\n            if (j == p1 || j == p2 || j == p3)\n                continue;\n            if (inCircle2(points[p1], points[p2], points[p3], points[j]))\n                return false;\n        }\n    }\n\n    return true;\n}\n\n\nvoid benchmark(void) {\n    int nPoints = 10;\n    bool breakLoop = false;\n    while (true) {\n        Vector<Vec2f> pointsFloat;\n        Vector<Vec2d> pointsDouble;\n        pointsFloat.clear();\n        pointsDouble.clear();\n        createPointsUniform(pointsFloat, Vec2f(0.0, 0.0), Vec2f(1024.0, 1024.0), nPoints);\n        createPointsUniform(pointsDouble, Vec2d(0.0, 0.0), Vec2d(1024.0, 1024.0), nPoints);\n\n        auto t1 = std::chrono::high_resolution_clock::now();\n        auto triangulationFloat = delaunay::triangulate(pointsFloat);\n        auto t2 = std::chrono::high_resolution_clock::now();\n        auto triangulationDouble = delaunay::triangulate(pointsDouble);\n        auto t3 = std::chrono::high_resolution_clock::now();\n\n        printf(\"nPoints: %d, tFloat: %0.5f, tDouble: %0.5f\\n\", nPoints,\n            std::chrono::duration<double, std::milli>(t2-t1).count(),\n            std::chrono::duration<double, std::milli>(t3-t2).count());\n\n        visualize(pointsDouble, triangulationDouble, \"triangulationDouble\", cv::Scalar(120, 120, 0), 20);\n        visualize(pointsFloat, triangulationFloat, \"triangulationFloat\", cv::Scalar(0, 80, 160), 20);\n\n        if (!checkTriangulation(pointsFloat, triangulationFloat)) {\n            printf(\"Triangulation is non-delaunay!\\n\");\n            breakLoop = true;\n        }\n\n        if (breakLoop) {\n            cv::waitKey(0);\n            break;\n        }\n\n        nPoints *= 1.1;\n    }\n}\n\n\nint main()\n{\n#if 0\n    Vector<Vec2d> points;\n    createPoints(points, Vec2d(0.0f, 0.0f), Vec2d(1024.0f, 1024.0f));\n\n    auto triangulation = delaunay::triangulate(points);\n\n    visualize(points, triangulation, \"delaunay demo\", cv::Scalar(120, 120, 0));\n#else\n    benchmark();\n#endif\n\n    return 0;\n}\n", "meta": {"hexsha": "dbfa5b25319fea9d3b5380edb224545c9542782b", "size": 6933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Lehdari/Delaunay", "max_stars_repo_head_hexsha": "64cbbdd4f7ce608ed3e609052e0862280c8927a9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T14:39:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T14:39:22.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "Lehdari/Delaunay", "max_issues_repo_head_hexsha": "64cbbdd4f7ce608ed3e609052e0862280c8927a9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "Lehdari/Delaunay", "max_forks_repo_head_hexsha": "64cbbdd4f7ce608ed3e609052e0862280c8927a9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4078947368, "max_line_length": 105, "alphanum_fraction": 0.6085388721, "num_tokens": 2210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652496, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6076914625972001}}
{"text": "///3\n#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <queue>\n#include <stack>\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n// BGL graph definitions\n// =====================\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS,\n  boost::no_property, boost::property<boost::edge_weight_t, long> >      weighted_graph;\ntypedef boost::property_map<weighted_graph, boost::edge_weight_t>::type weight_map;\ntypedef boost::graph_traits<weighted_graph>::edge_descriptor            edge_desc;\ntypedef boost::graph_traits<weighted_graph>::vertex_descriptor          vertex_desc;\ntypedef  boost::graph_traits<weighted_graph>::out_edge_iterator      out_edge_it;\n\n// Main\nvoid testcase() {\n  // build graph\n  long n, m, x, k;\n  std::cin >> n >> m >> x >> k;\n  weighted_graph G(n);\n  weight_map weights = boost::get(boost::edge_weight, G);\n\n  edge_desc e;\n  \n  std::vector<int> num_outgoing(n, 0);\n  \n  for(int i = 0; i < m; i++) {\n    long u, v, p;\n    std::cin >> u >> v>> p;\n    e = boost::add_edge(u, v, G).first; weights[e]=p;\n    num_outgoing[u] += 1;\n  }\n  \n  std::vector<std::vector<long>> maxpoints_after(k + 1);\n  for(int i = 0; i <= k; i++) {\n    maxpoints_after[i] = std::vector<long>(n, 0);\n  }\n\n  out_edge_it ebeg, eend;\n  for(int j = 0; j < k; j++) {\n    for(int i = 0; i < n; i++) {\n      long maxpoints = 0;\n      for (boost::tie(ebeg, eend) = boost::out_edges(i, G); ebeg != eend; ++ebeg) {\n        const int v = boost::target(*ebeg, G);\n        const long pi = weights[*ebeg];\n        maxpoints = std::max(maxpoints, maxpoints_after[j][v] + pi);\n        if(i == 0 && maxpoints >= x) {\n          std::cout << j + 1 << std::endl;\n          return;\n        }\n      }\n      if(num_outgoing[i] == 0) {\n        maxpoints_after[j + 1][i] = maxpoints_after[j + 1][0];\n      } else {\n        maxpoints_after[j + 1][i] = maxpoints;\n      }\n    }\n  }\n  std::cout << \"Impossible\" << std::endl;\n}\n\nint main() {\n  std::ios_base::sync_with_stdio(false);\n  std::size_t t;\n  for (std::cin >> t; t > 0; --t) testcase();\n  return 0;\n}", "meta": {"hexsha": "7979383c35f74ecbf4e5cfd14d70c04415288d09", "size": 2073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week12-potw-san_francisco/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/week12-potw-san_francisco/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/week12-potw-san_francisco/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6142857143, "max_line_length": 88, "alphanum_fraction": 0.5894838398, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.6076914510996291}}
{"text": "//  Copyright John Maddock 2007.\r\n//  Copyright Paul A. Bristow 2010\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Note that this file contains quickbook mark-up as well as code\r\n// and comments, don't change any of the special comment mark-ups!\r\n\r\n//[policy_eg_10\r\n\r\n/*`\r\n\r\nTo understand how the rounding policies for \r\nthe discrete distributions can be used, we'll\r\nuse the 50-sample binomial distribution with a \r\nsuccess fraction of 0.5 once again, and calculate\r\nall the possible quantiles at 0.05 and 0.95.\r\n\r\nBegin by including the needed headers (and some using statements for conciseness):\r\n\r\n*/\r\n#include <iostream>\r\nusing std::cout; using std::endl;\r\nusing std::left; using std::fixed; using std::right; using std::scientific;\r\n#include <iomanip>\r\nusing std::setw;\r\nusing std::setprecision;\r\n\r\n#include <boost/math/distributions/binomial.hpp>\r\n/*`\r\n\r\nNext we'll bring the needed declarations into scope, and\r\ndefine distribution types for all the available rounding policies:\r\n\r\n*/\r\n// Avoid \r\n// using namespace std; // and \r\n// using namespace boost::math;\r\n// to avoid potential ambiguity of names, like binomial.\r\n// using namespace boost::math::policies; is small risk, but\r\n// the necessary items are brought into scope thus:\r\n\r\nusing boost::math::binomial_distribution;\r\nusing boost::math::policies::policy;\r\nusing boost::math::policies::discrete_quantile;\r\n\r\nusing boost::math::policies::integer_round_outwards;\r\nusing boost::math::policies::integer_round_down;\r\nusing boost::math::policies::integer_round_up;\r\nusing boost::math::policies::integer_round_nearest;\r\nusing boost::math::policies::integer_round_inwards;\r\nusing boost::math::policies::real;\r\n\r\nusing boost::math::binomial_distribution; // Not std::binomial_distribution.\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<integer_round_outwards> > > \r\n        binom_round_outwards;\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<integer_round_inwards> > > \r\n        binom_round_inwards;\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<integer_round_down> > > \r\n        binom_round_down;\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<integer_round_up> > > \r\n        binom_round_up;\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<integer_round_nearest> > > \r\n        binom_round_nearest;\r\n\r\ntypedef binomial_distribution<\r\n            double, \r\n            policy<discrete_quantile<real> > > \r\n        binom_real_quantile;\r\n\r\n/*`\r\nNow let's set to work calling those quantiles:\r\n*/\r\n\r\nint main()\r\n{\r\n   cout << \r\n      \"Testing rounding policies for a 50 sample binomial distribution,\\n\"\r\n      \"with a success fraction of 0.5.\\n\\n\"\r\n      \"Lower quantiles are calculated at p = 0.05\\n\\n\"\r\n      \"Upper quantiles at p = 0.95.\\n\\n\";\r\n\r\n   cout << setw(25) << right\r\n      << \"Policy\"<< setw(18) << right \r\n      << \"Lower Quantile\" << setw(18) << right \r\n      << \"Upper Quantile\" << endl;\r\n   \r\n   // Test integer_round_outwards:\r\n   cout << setw(25) << right\r\n      << \"integer_round_outwards\"\r\n      << setw(18) << right\r\n      << quantile(binom_round_outwards(50, 0.5), 0.05)\r\n      << setw(18) << right\r\n      << quantile(binom_round_outwards(50, 0.5), 0.95) \r\n      << endl;\r\n   \r\n   // Test integer_round_inwards:\r\n   cout << setw(25) << right\r\n      << \"integer_round_inwards\"\r\n      << setw(18) << right\r\n      << quantile(binom_round_inwards(50, 0.5), 0.05)\r\n      << setw(18) << right\r\n      << quantile(binom_round_inwards(50, 0.5), 0.95) \r\n      << endl;\r\n   \r\n   // Test integer_round_down:\r\n   cout << setw(25) << right\r\n      << \"integer_round_down\"\r\n      << setw(18) << right\r\n      << quantile(binom_round_down(50, 0.5), 0.05)\r\n      << setw(18) << right\r\n      << quantile(binom_round_down(50, 0.5), 0.95) \r\n      << endl;\r\n   \r\n   // Test integer_round_up:\r\n   cout << setw(25) << right\r\n      << \"integer_round_up\"\r\n      << setw(18) << right\r\n      << quantile(binom_round_up(50, 0.5), 0.05)\r\n      << setw(18) << right\r\n      << quantile(binom_round_up(50, 0.5), 0.95) \r\n      << endl;\r\n   \r\n   // Test integer_round_nearest:\r\n   cout << setw(25) << right\r\n      << \"integer_round_nearest\"\r\n      << setw(18) << right\r\n      << quantile(binom_round_nearest(50, 0.5), 0.05)\r\n      << setw(18) << right\r\n      << quantile(binom_round_nearest(50, 0.5), 0.95) \r\n      << endl;\r\n   \r\n   // Test real:\r\n   cout << setw(25) << right\r\n      << \"real\"\r\n      << setw(18) << right\r\n      << quantile(binom_real_quantile(50, 0.5), 0.05)\r\n      << setw(18) << right\r\n      << quantile(binom_real_quantile(50, 0.5), 0.95) \r\n      << endl;\r\n} // int main()\r\n\r\n/*`\r\n\r\nWhich produces the program output:\r\n\r\n[pre\r\n  policy_eg_10.vcxproj -> J:\\Cpp\\MathToolkit\\test\\Math_test\\Release\\policy_eg_10.exe\r\n  Testing rounding policies for a 50 sample binomial distribution,\r\n  with a success fraction of 0.5.\r\n  \r\n  Lower quantiles are calculated at p = 0.05\r\n  \r\n  Upper quantiles at p = 0.95.\r\n  \r\n                     Policy    Lower Quantile    Upper Quantile\r\n     integer_round_outwards                18                31\r\n      integer_round_inwards                19                30\r\n         integer_round_down                18                30\r\n           integer_round_up                19                31\r\n      integer_round_nearest                19                30\r\n                       real            18.701            30.299\r\n]\r\n\r\n*/\r\n\r\n//] //[policy_eg_10] ends quickbook import.\r\n", "meta": {"hexsha": "d643ee6185bf0fed18e203a66243de566f6e8925", "size": 5773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/policy_eg_10.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/math/example/policy_eg_10.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/math/example/policy_eg_10.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 31.375, "max_line_length": 85, "alphanum_fraction": 0.6121600554, "num_tokens": 1523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6075951860639245}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <iostream>\n#include <mimkl/definitions.hpp>\n#include <mimkl/kernels.hpp>\n#include <mimkl/linear_algebra.hpp>\n#include <stdexcept>\n\nint main(int argc, char **argv)\n{\n    try\n    {\n\n        auto console = spdlog::stdout_color_mt(\"console\");\n\n        Eigen::Matrix<double, 2, 3> X;\n        Eigen::SparseMatrix<double> L(3, 3);\n        double a = 0.01;\n        double b = 0.01;\n        Eigen::Matrix<double, 2, 2> K_reference;\n\n        X << 1., 2., 3., 4., 5., 6.;\n        mimkl::linear_algebra::fill_sparse_diagonal(L, 1.0);\n\n        K_reference << std::tanh(0.15), std::tanh(0.33), std::tanh(0.33),\n        std::tanh(.78);\n        Eigen::Matrix<double, 2, 2> K =\n        mimkl::induction::induce_sigmoidal_kernel<MATRIX(double)>(X, X, L, a, b);\n\n        assert(((K - K_reference).norm() < 0.0000000001) && \"Identity Inducer\");\n\n        Eigen::SparseMatrix<double> L1(3, 3);\n        typedef Eigen::Triplet<double> TripletDouble; // (row,col,coef)\n        std::vector<TripletDouble> triplet_list;\n        triplet_list.reserve(4);\n        triplet_list.push_back(TripletDouble(0, 1, 1.));\n        triplet_list.push_back(TripletDouble(1, 2, 1.));\n        triplet_list.push_back(TripletDouble(1, 0, 1.));\n        triplet_list.push_back(TripletDouble(2, 1, 1.));\n        L1.setFromTriplets(triplet_list.begin(), triplet_list.end());\n\n        K_reference << std::tanh(0.17), std::tanh(0.41), std::tanh(0.41),\n        std::tanh(1.01);\n        ;\n\n        K = mimkl::induction::induce_sigmoidal_kernel<MATRIX(double)>(X, X, L1,\n                                                                      a, b);\n\n        std::cout << K << std::endl;\n        std::cout << K_reference << std::endl;\n        std::cout << (K - K_reference).norm() << std::endl;\n        assert(((K - K_reference).norm() < 0.0000000001) &&\n               \"unweighted Graph Inducer\");\n\n        MATRIX(double) random_mat1 = MATRIX(double)::Random(2, 3);\n        MATRIX(double) random_mat2 = MATRIX(double)::Random(4, 3);\n        MATRIX(double) random_kernel;\n\n        random_kernel =\n        mimkl::induction::induce_sigmoidal_kernel<MATRIX(double)>(random_mat1,\n                                                                  random_mat2,\n                                                                  L1, a, b);\n        console->info(\" a random sigmoidal kernel\\n{}\", random_kernel);\n\n        return EXIT_SUCCESS;\n    }\n    catch (const std::exception &e)\n    {\n        std::cerr << e.what();\n        return EXIT_FAILURE;\n    }\n}\n", "meta": {"hexsha": "4e6e9d8a57752b624bd134e671b089e385d9bb90", "size": 2548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sigmoidal_induction/main.cpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "test/sigmoidal_induction/main.cpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "test/sigmoidal_induction/main.cpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 34.904109589, "max_line_length": 81, "alphanum_fraction": 0.5490580848, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6075943951251552}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_NEXTPOW2_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_NEXTPOW2_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-ieee\n    Function object implementing nextpow2 capabilities\n\n    Returns the greatest integer n such that abss(x) is greater or equal to \\f$2^n\\f$\n\n    @par Semantic:\n\n    @code\n    T n = nextpow2(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T n = floor(log2(abss(x)));\n    @endcode\n\n  **/\n  const boost::dispatch::functor<tag::nextpow2_> nextpow2 = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/nextpow2.hpp>\n#include <boost/simd/function/simd/nextpow2.hpp>\n\n#endif\n", "meta": {"hexsha": "32817ec4b0fde3ecd64ad7eb7b067f076360f403", "size": 1093, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/nextpow2.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/nextpow2.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/nextpow2.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2553191489, "max_line_length": 100, "alphanum_fraction": 0.5782250686, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6075819417908976}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n#include <stan/math/prim/fun.hpp>  // lgamma, lmgamma\n#include <stan/math/prim/prob.hpp>\n\n#include \"marginal_state.pb.h\"\n#include \"src/hierarchies/lin_reg_uni_hierarchy.h\"\n#include \"src/hierarchies/nnig_hierarchy.h\"\n#include \"src/hierarchies/nnw_hierarchy.h\"\n#include \"src/utils/proto_utils.h\"\n\nTEST(lpdf, nnig) {\n  NNIGHierarchy hier;\n  bayesmix::NNIGPrior hier_prior;\n  double mu0 = 5.0;\n  double lambda0 = 0.1;\n  double alpha0 = 2.0;\n  double beta0 = 2.0;\n  hier_prior.mutable_fixed_values()->set_mean(mu0);\n  hier_prior.mutable_fixed_values()->set_var_scaling(lambda0);\n  hier_prior.mutable_fixed_values()->set_shape(alpha0);\n  hier_prior.mutable_fixed_values()->set_scale(beta0);\n  hier.set_prior(hier_prior);\n  hier.initialize();\n\n  double mean = mu0;\n  double var = beta0 / (alpha0 + 1);\n\n  Eigen::VectorXd datum(1);\n  datum << 4.5;\n\n  // Compute posterior parameters\n  double mu_n = (lambda0 * mu0 + datum(0)) / (lambda0 + 1);\n  double alpha_n = alpha0 + 0.5;\n  double lambda_n = lambda0 + 1;\n  double beta_n = beta0 + (0.5 * lambda0 / (lambda0 + 1)) * (datum(0) - mu0) *\n                              (datum(0) - mu0);\n  // equiv.ly: beta0 + 0.5*(mu0^2*lambda0 + datum^2 - mu_n^2*lambda_n);\n\n  // Compute pieces\n  double prior1 = stan::math::inv_gamma_lpdf(var, alpha0, beta0);\n  double prior2 = stan::math::normal_lpdf(mean, mu0, sqrt(var / lambda0));\n  double prior = prior1 + prior2;\n  double like = hier.like_lpdf(datum);\n  double post1 = stan::math::inv_gamma_lpdf(var, alpha_n, beta_n);\n  double post2 = stan::math::normal_lpdf(mean, mu_n, sqrt(var / lambda_n));\n  double post = post1 + post2;\n\n  // Bayes: logmarg(x) = logprior(phi) + loglik(x|phi) - logpost(phi|x)\n  double sum = prior + like - post;\n  double marg = hier.marg_lpdf(datum);\n\n  ASSERT_DOUBLE_EQ(sum, marg);\n}\n\n// TEST(lpdf, nnw) {  // TODO\n//   using namespace stan::math;\n//   NNWHierarchy hier;\n//   bayesmix::NNWPrior hier_prior;\n//   Eigen::Vector2d mu0; mu0 << 5.5, 5.5;\n//   bayesmix::Vector mu0_proto;\n//   bayesmix::to_proto(mu0, &mu0_proto);\n//   double lambda0 = 0.2;\n//   double nu0 = 5.0;\n//   Eigen::Matrix2d tau0 = Eigen::Matrix2d::Identity() / nu0;\n//   bayesmix::Matrix tau0_proto;\n//   bayesmix::to_proto(tau0, &tau0_proto);\n//   *hier_prior.mutable_fixed_values()->mutable_mean() = mu0_proto;\n//   hier_prior.mutable_fixed_values()->set_var_scaling(lambda0);\n//   hier_prior.mutable_fixed_values()->set_deg_free(nu0);\n//   *hier_prior.mutable_fixed_values()->mutable_scale() = tau0_proto;\n//   hier.set_prior(hier_prior);\n//   hier.initialize();\n//\n//   Eigen::VectorXd mu = mu0;\n//   Eigen::MatrixXd tau = lambda0 * Eigen::Matrix2d::Identity();\n//\n//   Eigen::RowVectorXd datum(2);\n//   datum << 4.5, 4.5;\n//\n//   // Compute prior parameters\n//   Eigen::MatrixXd tau_pr = lambda0 * tau0;\n//\n//   // Compute posterior parameters\n//   double mu_n = (lambda0 * mu0 + datum(0)) / (lambda0 + 1);\n//   double alpha_n = alpha0 + 0.5;\n//   double lambda_n = lambda0 + 1;\n//   double nu_n = nu0 + 0.5;\n//   Eigen::VectorXd mu_n =\n//       (lambda0 * mu0 + datum.transpose()) / (lambda0 + 1);\n//   Eigen::MatrixXd tau_temp =\n//       stan::math::inverse_spd(tau0) + (0.5 * lambda0 / (lambda0 + 1)) *\n//                                           (datum.transpose() - mu0) *\n//                                           (datum - mu0.transpose());\n//   Eigen::MatrixXd tau_n = stan::math::inverse_spd(tau_temp);\n//   Eigen::MatrixXd tau_post = lambda_n * tau_n;\n//\n//   // Compute pieces\n//   double prior1 = stan::math::wishart_lpdf(tau, nu0, tau0);\n//   double prior2 = stan::math::multi_normal_prec_lpdf(mu, mu0, tau_pr);\n//   double prior = prior1 + prior2;\n//   double like = hier.like_lpdf(datum);\n//   double post1 = stan::math::wishart_lpdf(tau, nu_n, tau_post);\n//   double post2 = stan::math::multi_normal_prec_lpdf(mu, mu0, tau_post);\n//   double post = post1 + post2;\n//\n//   // Bayes: logmarg(x) = logprior(phi) + loglik(x|phi) - logpost(phi|x)\n//   double sum = prior + like - post;\n//   double marg = hier.marg_lpdf(datum);\n//\n//   // Compute logdet's\n//   Eigen::MatrixXd tauchol0 =\n//       Eigen::LLT<Eigen::MatrixXd>(tau0).matrixL().transpose();\n//   double logdet0 = 2 * log(tauchol0.diagonal().array()).sum();\n//   Eigen::MatrixXd tauchol_n =\n//       Eigen::LLT<Eigen::MatrixXd>(tau_n).matrixL().transpose();\n//   double logdet_n = 2 * log(tauchol_n.diagonal().array()).sum();\n//\n//   // lmgamma(dim, x)\n//   int dim = 2;\n//   double marg_murphy = lmgamma(dim, 0.5 * nu_n) + 0.5 * nu_n * logdet_n +\n//                        0.5 * dim * log(lambda0) + dim * NEG_LOG_SQRT_TWO_PI\n//                        - lmgamma(dim, 0.5 * nu0) - 0.5 * nu0 * logdet0 - 0.5\n//                        * dim * log(lambda_n);\n//\n//   // std::cout << \"prior1=\" << prior1 << std::endl;\n//   // std::cout << \"prior2=\" << prior2 << std::endl;\n//   // std::cout << \"prior =\" << prior << std::endl;\n//   // std::cout << \"like  =\" << like << std::endl;\n//   // std::cout << \"post1 =\" << post1 << std::endl;\n//   // std::cout << \"post2 =\" << post2 << std::endl;\n//   // std::cout << \"post  =\" << post << std::endl;\n//   std::cout << \"sum   =\" << sum << std::endl;\n//   std::cout << \"marg  =\" << marg << std::endl;\n//   std::cout << \"murphy=\" << marg_murphy << std::endl;\n//   ASSERT_DOUBLE_EQ(marg, marg_murphy);\n// }\n\nTEST(lpdf, lin_reg_uni) {\n  // Create hierarchy objects\n  LinRegUniHierarchy hier;\n  bayesmix::LinRegUniPrior prior;\n  int dim = 3;\n\n  // Generate data\n  Eigen::VectorXd datum(1);\n  datum << 1.5;\n  Eigen::VectorXd cov = Eigen::VectorXd::Random(dim);\n\n  // Create parameters, both Eigen and proto\n  Eigen::VectorXd mu0(dim);\n  for (int i = 0; i < dim; i++) {\n    mu0(i) = 2 * i;\n  }\n  bayesmix::Vector mu0_proto;\n  bayesmix::to_proto(mu0, &mu0_proto);\n  auto Lambda0 = Eigen::MatrixXd::Identity(dim, dim);\n  bayesmix::Matrix Lambda0_proto;\n  bayesmix::to_proto(Lambda0, &Lambda0_proto);\n  double alpha0 = 2.0;\n  double beta0 = 2.0;\n  // Set parameters\n  *prior.mutable_fixed_values()->mutable_mean() = mu0_proto;\n  *prior.mutable_fixed_values()->mutable_var_scaling() = Lambda0_proto;\n  prior.mutable_fixed_values()->set_shape(alpha0);\n  prior.mutable_fixed_values()->set_scale(beta0);\n  // Initialize hierarchy\n  hier.set_prior(prior);\n  hier.initialize();\n\n  // Compute prior parameters\n  Eigen::VectorXd mean = mu0;\n  double var = beta0 / (alpha0 + 1);\n\n  // Compute posterior parameters\n  Eigen::MatrixXd Lambda_n = Lambda0 + cov * cov.transpose();\n  Eigen::VectorXd mu_n =\n      stan::math::inverse_spd(Lambda_n) * (datum(0) * cov + Lambda0 * mu0);\n  double alpha_n = alpha0 + 0.5;\n  double beta_n =\n      beta0 + 0.5 * (datum(0) * datum(0) + mu0.transpose() * Lambda0 * mu0 -\n                     mu_n.transpose() * Lambda_n * mu_n);\n  // Compute pieces\n  double prior1 = stan::math::inv_gamma_lpdf(var, alpha0, beta0);\n  double prior2 = stan::math::multi_normal_prec_lpdf(mean, mu0, Lambda0 / var);\n  double pr = prior1 + prior2;\n  double like = hier.like_lpdf(datum, cov);\n  double post1 = stan::math::inv_gamma_lpdf(var, alpha_n, beta_n);\n  double post2 =\n      stan::math::multi_normal_prec_lpdf(mean, mu_n, Lambda_n / var);\n  double post = post1 + post2;\n\n  // Bayes: logmarg(x) = logprior(phi) + loglik(x|phi) - logpost(phi|x)\n  double sum = pr + like - post;\n  double marg = hier.marg_lpdf(datum, cov);\n\n  ASSERT_FLOAT_EQ(sum, marg);\n}\n", "meta": {"hexsha": "ba26d6026916b48be7dc75e2da8dcd973dc1153b", "size": 7399, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/lpdf.cc", "max_stars_repo_name": "JoaoHenriqueOliveira/bayesmix", "max_stars_repo_head_hexsha": "8ebc95c5188d236796593dd21b72436f903bf5e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/lpdf.cc", "max_issues_repo_name": "JoaoHenriqueOliveira/bayesmix", "max_issues_repo_head_hexsha": "8ebc95c5188d236796593dd21b72436f903bf5e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/lpdf.cc", "max_forks_repo_name": "JoaoHenriqueOliveira/bayesmix", "max_forks_repo_head_hexsha": "8ebc95c5188d236796593dd21b72436f903bf5e5", "max_forks_repo_licenses": ["BSD-3-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.995, "max_line_length": 79, "alphanum_fraction": 0.6281929991, "num_tokens": 2321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6075819360626598}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <dlib/clustering.h>\n#include <dlib/rand.h>\n\n#include <fstream>\n\nusing namespace std;\nusing namespace dlib;\n\nint main(int argc, char **argv) {\n    if (argc != 2) {\n        std::cerr << \"\u041d\u0435\u0432\u0435\u0440\u043d\u043e\u0435 \u0447\u0438\u0441\u043b\u043e \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u043e\u0432\\n\u0424\u043e\u0440\u043c\u0430\u0442 \u0432\u044b\u0437\u043e\u0432\u0430: kkmeans <n>\" << std::endl;\n        return 1;\n    }\n\n    std::string str_clusters_num = argv[1];\n    if (!std::all_of(str_clusters_num.begin(), str_clusters_num.end(), ::isdigit)) {\n        std::cerr << \"\u041f\u0430\u0440\u0430\u043c\u0435\u0442\u0440 <n> \u0434\u043e\u043b\u0436\u0435\u043d \u0431\u044b\u0442\u044c \u0442\u0438\u043f\u0430 int\" << std::endl;\n        return 1;\n    }\n\n    size_t cluster_num = std::stoull(str_clusters_num);\n    if (cluster_num == 0) {\n        std::cerr << \"\u041f\u0430\u0440\u0430\u043c\u0435\u0442\u0440 <n> \u0434\u043e\u043b\u0436\u0435\u043d \u0431\u044b\u0442\u044c \u0431\u043e\u043b\u044c\u0448\u0435 \u043d\u0443\u043b\u044f.\" << std::endl;\n        return 1;\n    }\n\n    typedef matrix<double, 2, 1>             sample_type;\n    typedef radial_basis_kernel<sample_type> kernel_type;\n\n    kcentroid<kernel_type> kc(kernel_type(0.0001), 0.1, 8);\n\n    kkmeans<kernel_type> test(kc);\n\n    std::vector<sample_type> samples;\n    std::vector<sample_type> initial_centers;\n\n    sample_type      m;\n    for (std::string line; std::getline(std::cin, line);) {\n        auto pos_x = line.find(';');\n        auto pos_y = line.find('\\n', pos_x + 1);\n        m(0) = std::stod(line.substr(0, pos_x));\n        m(1) = std::stod(line.substr(pos_x + 1, pos_y));\n        samples.emplace_back(m);\n    }\n\n    test.set_number_of_centers(cluster_num);\n\n    pick_initial_centers(cluster_num, initial_centers, samples, test.get_kernel());\n\n    test.train(samples, initial_centers);\n\n    for (auto const &sample: samples) {\n        std::cout << sample(0) << \";\" << sample(1) << \";cluster\" << test(sample) + 1 << std::endl;\n    }\n    return 0;\n}\n\n\n\n", "meta": {"hexsha": "c906136008bec76ceb2f59cca5368b7f5b95af9e", "size": 1689, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "rfrolov/otus_homework_15", "max_stars_repo_head_hexsha": "5b733882670231bf883a1bd91feb087fd5378bba", "max_stars_repo_licenses": ["MIT"], "max_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": "rfrolov/otus_homework_15", "max_issues_repo_head_hexsha": "5b733882670231bf883a1bd91feb087fd5378bba", "max_issues_repo_licenses": ["MIT"], "max_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": "rfrolov/otus_homework_15", "max_forks_repo_head_hexsha": "5b733882670231bf883a1bd91feb087fd5378bba", "max_forks_repo_licenses": ["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.8095238095, "max_line_length": 98, "alphanum_fraction": 0.6116044997, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.6075309651140273}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Mesh_triangulation_3.h>\n#include <CGAL/Mesh_complex_3_in_triangulation_3.h>\n#include <CGAL/Mesh_criteria_3.h>\n\n#include <CGAL/Labeled_mesh_domain_3.h>\n#include <CGAL/make_mesh_3.h>\n\n#include <boost/version.hpp>\n\n// Domain\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::FT FT;\ntypedef K::Point_3 Point;\ntypedef FT (Function)(const Point&);\ntypedef CGAL::Labeled_mesh_domain_3<K> Mesh_domain;\n\ntypedef CGAL::Parallel_if_available_tag Concurrency_tag;\n\n// Triangulation\ntypedef CGAL::Mesh_triangulation_3<Mesh_domain,K,Concurrency_tag>::type Tr;\n\ntypedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3;\n\n// Criteria\ntypedef CGAL::Mesh_criteria_3<Tr> Mesh_criteria;\n\n// To avoid verbose function and named parameters call\nusing namespace CGAL::parameters;\n\n// Function, a capsule:\n//   a cylinder centered at x=y=0, with z in [-5, -5]\n//   with radius 1 and \"round ends\".\nFT capsule_function(const Point& p)\n{\n  const FT base = CGAL::square(p.x())+CGAL::square(p.y()) - 1;\n  const FT z = p.z();\n  if(z > FT(5)) return base+CGAL::square(z-5);\n  else if(z < FT(-5)) return base+CGAL::square(z+5);\n  else return base;\n}\n#if BOOST_VERSION >= 106600\nauto field = [](const Point& p, const int, const Mesh_domain::Index)\n             {\n               if(p.z() > 2) return 0.025;\n               if(p.z() < -3) return 0.01;\n               else return 1.;\n             };\n#else\nstruct Field {\n  typedef ::FT FT;\n\n  FT operator()(const Point& p, const int, const Mesh_domain::Index) const {\n    if(p.z() > 2) return 0.025;\n    if(p.z() < -3) return 0.01;\n    else return 1;\n  }\n} field;\n#endif\n\nint main()\n{\n  Mesh_domain domain =\n    Mesh_domain::create_implicit_mesh_domain(capsule_function,\n                                             K::Sphere_3(CGAL::ORIGIN, 49.));\n\n  // Mesh criteria\n  Mesh_criteria criteria(facet_angle=30, facet_size=0.5,\n                         facet_distance=field);\n\n  // Mesh generation\n  C3t3 c3t3 = CGAL::make_mesh_3<C3t3>(domain, criteria);\n\n  // Output\n  std::ofstream medit_file(\"out.mesh\");\n  c3t3.output_to_medit(medit_file);\n\n  return 0;\n}\n\n", "meta": {"hexsha": "b0c54cb5e74e3ff8087ae0627b3b5ac46cac1e5f", "size": 2175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Mesh_3/test/Mesh_3/test_mesh_capsule_var_distance_bound.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "Mesh_3/test/Mesh_3/test_mesh_capsule_var_distance_bound.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-12T14:38:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-12T14:38:20.000Z", "max_forks_repo_path": "Mesh_3/test/Mesh_3/test_mesh_capsule_var_distance_bound.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-05T04:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:18:59.000Z", "avg_line_length": 26.5243902439, "max_line_length": 77, "alphanum_fraction": 0.6735632184, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6075309572937772}}
{"text": "/* test_poisson.cpp\n *\n * Copyright Steven Watanabe 2010\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id$\n *\n */\n\n#include <boost/random/poisson_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/math/distributions/poisson.hpp>\n\n#define BOOST_RANDOM_DISTRIBUTION boost::random::poisson_distribution<>\n#define BOOST_RANDOM_DISTRIBUTION_NAME poisson\n#define BOOST_MATH_DISTRIBUTION boost::math::poisson\n#define BOOST_RANDOM_ARG1_TYPE double\n#define BOOST_RANDOM_ARG1_NAME mean\n#define BOOST_RANDOM_ARG1_DEFAULT 100000.0\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(n) boost::uniform_real<>(1e-15, n)\n#define BOOST_RANDOM_DISTRIBUTION_MAX static_cast<int>(mean * 4)\n\n#include \"test_real_distribution.ipp\"\n", "meta": {"hexsha": "519bf7e714798befec10a5976cf3629638251ba1", "size": 838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/random/test/test_poisson.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/random/test/test_poisson.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/random/test/test_poisson.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 32.2307692308, "max_line_length": 73, "alphanum_fraction": 0.8042959427, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.607498426803688}}
{"text": "\n#include <boost/test/unit_test.hpp>\n#include <stdexcept>\n\n#include \"io/DataMatrix.hpp\" // TODO don't cross namespace!\n#include \"it/EntropyCalculator.hpp\"\n\nusing namespace mist;\n\nio::DataMatrix::data_t test_data[12] = { 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0 };\n\nBOOST_AUTO_TEST_CASE(EntropyCalculator_constructor_default)\n{\n  int n = 3;\n  int m = 4;\n  io::DataMatrix test_matrix(test_data, n, m);\n  it::EntropyCalculator ec(\n      it::EntropyCalculator::variables_ptr(test_matrix.variables()));\n}\n\nBOOST_AUTO_TEST_CASE(EntropyCalculator_entropy_bounds)\n{\n  int n = 3;\n  int m = 4;\n  io::DataMatrix test_matrix(test_data, n, m);\n\n  it::EntropyCalculator ec(\n      it::EntropyCalculator::variables_ptr(test_matrix.variables()));\n\n  // run through some entropies\n  for (Variable::index_t i = 0; i < n; i++) {\n    ec.entropy({ i });\n  }\n  ec.entropy({ 0, 1 });\n  ec.entropy({ 0, 2 });\n  ec.entropy({ 1, 0 });\n  ec.entropy({ 1, 2 });\n  ec.entropy({ 0, 1, 2 });\n\n  // XXX: memory error, doesn't throw because counters don't check variable\n  // indexes impossible in practice because indexes are deterministic & safe\n  // BOOST_CHECK_THROW(\n  //    ec.entropy({6}), std::exception\n  //);\n}\n\nBOOST_AUTO_TEST_CASE(EntropyCalculator_entropy_correct1)\n{\n  int n = 3;\n  int m = 4;\n  io::DataMatrix test_matrix(test_data, n, m);\n\n  it::EntropyCalculator ec(\n      it::EntropyCalculator::variables_ptr(test_matrix.variables()));\n\n  BOOST_TEST(ec.entropy({ 0 }) == 0.8112781244591328);\n  BOOST_TEST(ec.entropy({ 1 }) == 1);\n  BOOST_TEST(ec.entropy({ 2 }) == 0.8112781244591328);\n  BOOST_TEST(ec.entropy({ 0, 1 }) == 1.5);\n  BOOST_TEST(ec.entropy({ 0, 2 }) == 1.5);\n  BOOST_TEST(ec.entropy({ 1, 2 }) == 1.5);\n  BOOST_TEST(ec.entropy({ 0, 1, 2 }) == 2);\n}\n\nBOOST_AUTO_TEST_CASE(EntropyCalculator_entropy_correct_d4)\n{\n  int n = 4;\n  int m = 3;\n  io::DataMatrix test_matrix(test_data, n, m);\n\n  it::EntropyCalculator ec(\n      it::EntropyCalculator::variables_ptr(test_matrix.variables()));\n\n  // 1.58496250072115\n  BOOST_TEST(ec.entropy({ 0, 1, 2, 3 }) == 1.5849625007211561);\n}\n", "meta": {"hexsha": "ca9ba27f03051ae7dc6d07d6ddb0804a4f36ff83", "size": 2059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mist/it/EntropyCalculator.test.cpp", "max_stars_repo_name": "andbanman/mist", "max_stars_repo_head_hexsha": "2546fb41bccea1f89a43dbdbed7ce3a257926b54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mist/it/EntropyCalculator.test.cpp", "max_issues_repo_name": "andbanman/mist", "max_issues_repo_head_hexsha": "2546fb41bccea1f89a43dbdbed7ce3a257926b54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T21:40:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T18:54:34.000Z", "max_forks_repo_path": "src/mist/it/EntropyCalculator.test.cpp", "max_forks_repo_name": "andbanman/mist", "max_forks_repo_head_hexsha": "2546fb41bccea1f89a43dbdbed7ce3a257926b54", "max_forks_repo_licenses": ["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.7402597403, "max_line_length": 78, "alphanum_fraction": 0.6673142302, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6074720438556095}}
{"text": "/*\n * Copyright (c) 2015, The Regents of the University of California (Regents).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *    1. Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *\n *    2. Redistributions in binary form must reproduce the above\n *       copyright notice, this list of conditions and the following\n *       disclaimer in the documentation and/or other materials provided\n *       with the distribution.\n *\n *    3. Neither the name of the copyright holder nor the names of its\n *       contributors may be used to endorse or promote products derived\n *       from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Please contact the author(s) of this library if you have any questions.\n * Authors: Erik Nelson            ( eanelson@eecs.berkeley.edu )\n *          David Fridovich-Keil   ( dfk@eecs.berkeley.edu )\n */\n\n#include \"triangulation.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <glog/logging.h>\n\n#include \"../util/types.h\"\n\nnamespace bsfm {\n\nusing Eigen::MatrixXd;\n\n// Triangulates a single 3D point from > 2 views using the inhomogeneous DLT\n// method from H&Z: Multi-View Geometry, Ch 2.2.\nbool Triangulate(const FeatureList& features,\n                 const std::vector<Camera>& cameras,\n                 Point3D& point,\n                 double& uncertainty) {\n  if (features.size() != cameras.size()) {\n    LOG(WARNING)\n        << \"Number of features does not match number of cameras.\";\n    return false;\n  }\n\n  if (features.size() < 2) {\n    LOG(WARNING) << \"Need at least two features and cameras to triangulate.\";\n    return false;\n  }\n\n  // Construct the A matrix on page 312.\n  MatrixXd A;\n  A.resize(features.size() * 2, 4);\n  for (size_t ii = 0; ii < features.size(); ++ii) {\n    double u = features[ii].u_;\n    double v = features[ii].v_;\n\n    const Matrix34d P = cameras[ii].P();\n    A.row(2*ii+0) = u * P.row(2) - P.row(0);\n    A.row(2*ii+1) = v * P.row(2) - P.row(1);\n  }\n\n  // Get svd(A). Save some time and compute a thin U. We still need a full V.\n  Eigen::JacobiSVD<MatrixXd> svd;\n  svd.compute(A, Eigen::ComputeThinU | Eigen::ComputeFullV);\n  if (!svd.computeV()) {\n    VLOG(1) << \"Failed to compute a singular value decomposition of A matrix.\";\n    return false;\n  }\n\n  // The 3D point is the eigenvector corresponding to the minimum eigenvalue.\n  point = Point3D(svd.matrixV().block(0, 3, 3, 1) / svd.matrixV()(3,3));\n\n  // Return false if the point is not visible from all cameras.\n  for (size_t ii = 0; ii < cameras.size(); ++ii) {\n    double u = 0.0, v = 0.0;\n    if (!cameras[ii].WorldToImage(point.X(), point.Y(), point.Z(), &u, &v)) {\n      return false;\n    }\n  }\n\n  // Store the uncertainty as the inverse of the triangulation angle.\n  const double angle = MaximumAngle(cameras, point);\n  if (angle == 0.0) {  // we actually do want floating point comparison.\n    uncertainty = std::numeric_limits<double>::max();\n  } else {\n    uncertainty = 1.0 / angle;\n  }\n\n  return true;\n}\n\n// Triangulate the 3D position of a point from a 2D correspondence and two sets\n// of camera extrinsics and intrinsics.\nbool Triangulate(const FeatureMatch& feature_match, const Camera& camera1,\n                 const Camera& camera2, Point3D& point, double& uncertainty) {\n  FeatureList features;\n  features.push_back(feature_match.feature1_);\n  features.push_back(feature_match.feature2_);\n\n  std::vector<Camera> cameras;\n  cameras.push_back(camera1);\n  cameras.push_back(camera2);\n\n  return Triangulate(features, cameras, point, uncertainty);\n}\n\n// Repeats the above function on a list of feature matches, returning a list of\n// triangulated 3D points, where each point is computed from a single 2D <--> 2D\n// correspondence.\nbool Triangulate(const FeatureMatchList& feature_matches, const Camera& camera1,\n                 const Camera& camera2, Point3DList& points, double& uncertainty) {\n  // Clear output.\n  points.clear();\n\n  bool triangulated_all_points = true;\n  for (size_t ii = 0; ii < feature_matches.size(); ++ii) {\n    Point3D point;\n\n    // Continue on failure, but store (0, 0, 0).\n    double point_uncertainty = 0.0;\n    if (!Triangulate(feature_matches[ii],\n                     camera1,\n                     camera2,\n                     point,\n                     point_uncertainty)) {\n      uncertainty += point_uncertainty;\n      triangulated_all_points = false;\n      point = Point3D();\n    }\n    uncertainty += point_uncertainty;\n    points.push_back(point);\n  }\n\n  return triangulated_all_points;\n}\n\n// Compute the maximum angle between each pair of observation angles.\ndouble MaximumAngle(const std::vector<Camera>& cameras, const Point3D& point) {\n  std::vector<Vector3d> vecs;\n  for (const auto& camera : cameras)\n    vecs.push_back((point.Get() - camera.Translation()).normalized());\n\n  double largest_angle = 0.0;\n  for (size_t ii = 0; ii < cameras.size() - 1; ++ii) {\n    for (size_t jj = ii + 1; jj < cameras.size(); ++jj) {\n      double angle = std::acos(vecs[ii].dot(vecs[jj]) - 1e-8);\n      if (std::isnan(angle) || std::isinf(angle)) {\n        LOG(WARNING) << \"Observation angle is NaN.\";\n        continue;\n      }\n\n      // We want two 90 degree observations to have the maximum possible angle.\n      // Two observations with a 180 degree angle should map back to 0, as the\n      // triangulated point will be colinear with the translation between the\n      // two cameras, which makes it unobservable.\n      if (angle > M_PI_2) {\n        angle = M_PI - angle;\n      }\n\n      if (angle > largest_angle) {\n        largest_angle = angle;\n      }\n    }\n  }\n  return largest_angle;\n}\n\n}  //\\namespace bsfm\n", "meta": {"hexsha": "91cbc5980f8e41886b27856b765b59e6cb40bf5e", "size": 6618, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/geometry/triangulation.cpp", "max_stars_repo_name": "jamesdsmith/berkeley_sfm", "max_stars_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T13:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T19:30:33.000Z", "max_issues_repo_path": "src/cpp/geometry/triangulation.cpp", "max_issues_repo_name": "jamesdsmith/berkeley_sfm", "max_issues_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T17:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-22T20:59:43.000Z", "max_forks_repo_path": "src/cpp/geometry/triangulation.cpp", "max_forks_repo_name": "erik-nelson/berkeley_sfm", "max_forks_repo_head_hexsha": "5bf0b45fac176ff7abfca0ff690893c1afc73c51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-01-22T06:23:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-16T03:54:33.000Z", "avg_line_length": 35.5806451613, "max_line_length": 83, "alphanum_fraction": 0.6696887277, "num_tokens": 1659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7248702880639792, "lm_q1q2_score": 0.6071658182330231}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_PIO_6_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_PIO_6_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Pio_6 Pio_6 (function template)\n\n  Generates the constant \\f$\\frac\\pi{6}\\f$.\n\n  @headerref{<boost/simd/constant/pio_6.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> T Pio_6();\n      @endcode\n\n  2.  @code\n      template<typename T> T Pio_6( boost::simd::as_<T> const& target );\n      @endcode\n\n  Generates a value of type @c T that evaluates to \\f$\\frac\\pi{6}\\f$.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c T that evaluates to `T(0.52359877559829887307710723054658)`\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/pio_6.hpp>\n#include <boost/simd/constant/simd/pio_6.hpp>\n\n#endif\n", "meta": {"hexsha": "8b06fd37b60c1e872a2822978d62b7797e82d3fd", "size": 1485, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/pio_6.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/pio_6.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/pio_6.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 29.1176470588, "max_line_length": 100, "alphanum_fraction": 0.5259259259, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6071658082761053}}
{"text": "#include \"nlmatode.h\"\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <cmath>\n#include <iostream>\n#include <limits>\n\n// Supplies class Ode45\n#include \"../../../lecturecodes/Ode45/ode45.h\"\n// Supplied auxiliary function for linear regression\n#include \"../../../lecturecodes/helperfiles/polyfit.h\"\n\nnamespace NLMatODE {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::MatrixXd matode(const Eigen::MatrixXd &Y0, double T) {\n  // Use the Ode45 class to find an approximation\n  // of the matrix IVP $Y' = -(Y-Y')*Y$ at time $T$\n  Eigen::MatrixXd YT;\n  //====================\n  // Your code goes here\n  //====================\n  return YT;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nbool checkinvariant(const Eigen::MatrixXd &M, double T) {\n  // Check if $Y'*Y$ is preserved at the time $T$ by matode.\n  //====================\n  // Your code goes here\n  //====================\n\n  return false;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\ndouble cvgDiscreteGradientMethod() {\n  // Compute the fitted convergence rate of the Discrete\n  // gradient method. Also tabulate the values M and the errors.\n  double conv_rate = 0;\n  //====================\n  // Your code goes here\n  //====================\n  return conv_rate;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace NLMatODE\n", "meta": {"hexsha": "03568a43f7881d87ecbe52e37fd2166c2c7f1ff3", "size": 1270, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/NLMatODE/templates/nlmatode.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/NLMatODE/templates/nlmatode.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/NLMatODE/templates/nlmatode.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.4230769231, "max_line_length": 64, "alphanum_fraction": 0.6173228346, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.6071412879685449}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm accumulator standard_deviation\n#include <boost/test/unit_test.hpp>\n#include \"fern/algorithm/accumulator/standard_deviation.h\"\n\n\nnamespace faa = fern::algorithm::accumulator;\n\n\n// TODO Once we have a full blown square algorithm we must use that\n//      instead of this one.\ntemplate<\n    typename T>\ninline constexpr T square(\n    T const& value)\n{\n    return value * value;\n}\n\n\nBOOST_AUTO_TEST_CASE(default_construct)\n{\n    faa::StandardDeviation<int> standard_deviation;\n}\n\n\nBOOST_AUTO_TEST_CASE(accumulate)\n{\n    {\n        faa::StandardDeviation<int> standard_deviation(5);\n        // 5\n        BOOST_CHECK_EQUAL(standard_deviation(), static_cast<int>(std::sqrt((\n            square(5 - 5)) / 1)));\n\n        standard_deviation(2);\n        // 5 2\n        BOOST_CHECK_EQUAL(standard_deviation(), static_cast<int>(std::sqrt((\n            square(3 - 5) +\n            square(3 - 2)) / 2)));\n\n        standard_deviation(3);\n        // 5 2 3\n        BOOST_CHECK_EQUAL(standard_deviation(), static_cast<int>(std::sqrt((\n            square(3 - 5) +\n            square(3 - 2) +\n            square(3 - 3)) / 3)));\n\n        standard_deviation = 8;\n        // 8\n        BOOST_CHECK_EQUAL(standard_deviation(), static_cast<int>(std::sqrt((\n            square(8 - 8)) / 1)));\n    }\n\n    {\n        faa::StandardDeviation<int, double> standard_deviation(5);\n        // 5\n        BOOST_CHECK_EQUAL(standard_deviation(), std::sqrt((\n            square(5.0 - 5.0)) / 1.0));\n\n        standard_deviation(2);\n        // 5 2\n        BOOST_CHECK_EQUAL(standard_deviation(), std::sqrt((\n            square(3.5 - 5.0) +\n            square(3.5 - 2.0)) / 2.0));\n\n        standard_deviation = 3;\n        // 3\n        BOOST_CHECK_EQUAL(standard_deviation(), std::sqrt((\n            square(3.0 - 3.0)) / 1.0));\n    }\n}\n\n\nBOOST_AUTO_TEST_CASE(merge)\n{\n    {\n        auto standard_deviation(faa::StandardDeviation<int>(15) |\n            faa::StandardDeviation<int>(5));\n        // 15 5\n        BOOST_CHECK_EQUAL(standard_deviation(), static_cast<int>(std::sqrt((\n            square(10 - 15) +\n            square(10 - 5)) / 2)));\n    }\n\n    {\n        auto standard_deviation(faa::StandardDeviation<int, double>(5) |\n            faa::StandardDeviation<int, double>(20));\n        // 5 20\n        BOOST_CHECK_EQUAL(standard_deviation(), std::sqrt((\n            square(12.5 - 5.0) +\n            square(12.5 - 20.0)) / 2.0));\n    }\n}\n", "meta": {"hexsha": "bb5292bdb32ddc8ed84d16c8e127d693719d6b91", "size": 2898, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/accumulator/test/standard_deviation_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/accumulator/test/standard_deviation_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/accumulator/test/standard_deviation_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6930693069, "max_line_length": 80, "alphanum_fraction": 0.5586611456, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.6071383744063611}}
{"text": "#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE LinearSolve\n\n#include <iostream>\n#include <random>\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <geomc/linalg/LUDecomp.h>\n#include <geomc/linalg/Orthogonal.h>\n\nusing namespace geom;\nusing namespace std;\n\ntypedef std::mt19937_64 rng_t;\n\n// test: check that PLU = M, actually\n//       (is P what it says it is?)\n\n\ntemplate <typename T>\nvoid randomize(T* v, index_t n, rng_t* rng) {\n    typedef std::normal_distribution<T> d_normal_t;\n    d_normal_t gauss = d_normal_t(0., 1); // (ctr, variance)\n    \n    for (index_t i = 0; i < n; ++i) {\n        v[i] = gauss(*rng);\n    }\n}\n\n\ntemplate <typename T, index_t N>\nvoid solve_vectors(rng_t* rng) {\n    Vec<T,N> bases[N]; // destroyed by the factorization\n    Vec<T,N> vi[N];\n    Vec<T,N> b;\n    Vec<T,N> x;\n    randomize<T>(bases[0].begin(), N * N, rng);\n    randomize<T>(b.begin(), N, rng);\n    std::copy(bases, bases + N, vi); // copy the bases, so we can check them\n    \n    // we should be able to write b as x[i] * bases[i].\n    if (linear_solve(bases, &x, b, 0)) {\n        Vec<T,N> b0;\n        for (index_t i = 0; i < N; ++i) {\n            b0 += x[i] * vi[i];\n        }\n        // check that the components of b0 and b are close.\n        for (index_t i = 0; i < N; ++i) {\n            BOOST_CHECK_CLOSE(b[i], b0[i], 1e-5);\n        }\n    } else {\n        // \u2193 very unlikely\n        std::cerr << \"Singular test matrix\\n\";\n    }\n}\n\n\ntemplate <typename T, index_t N>\nvoid exercise_solve_vectors(rng_t* rng, index_t trials) {\n    for (index_t i = 0; i < trials; ++i) {\n        solve_vectors<T,N>(rng);\n    }\n}\n\n\ntemplate <typename T>\nvoid exercise_plu(rng_t* rng, index_t n, index_t trials) {\n    SimpleMatrix<T,0,0> mx(n, n);\n    SimpleMatrix<T,0,0>  L(n,n);\n    SimpleMatrix<T,0,0>  U(n,n);\n    SimpleMatrix<T,0,0> LU(n,n);\n    PLUDecomposition<T,0,0> plu(mx);\n    \n    for (index_t i = 0; i < trials; ++i) {\n        randomize(mx.begin(), n * n, rng);\n        plu.decompose(mx);\n        plu.get_L(&L);\n        plu.get_U(&U);\n        mul(&LU, L, U);     // LU <- L * U\n        mul(&L, plu.P, mx); // L  <- P * M\n        // check that LU = PM\n        for (index_t j = 0; j < n * n; ++j) {\n            BOOST_CHECK_CLOSE(LU.begin()[j], L.begin()[j], 1e-5);\n        }\n    }\n}\n\n\ntemplate <typename T, index_t N>\nvoid exercise_orthogonalize(rng_t* rng, index_t trials) {\n    Vec<T,N> vs[N];\n    for (index_t i = 0; i < trials; ++i) {\n        randomize(vs[0].begin(), N * N, rng);\n        orthogonalize(vs, N);\n        // check that each of the orthogonalized bases have ~= 0 dot\n        // product with all the others:\n        for (index_t j = 0; j < N - 1; ++j) {\n            for (index_t k = j + 1; k < N; ++k) {\n                BOOST_CHECK_SMALL(vs[j].dot(vs[k]), 1e-5);\n            }\n        }\n    }\n}\n\n\ntemplate <typename T, index_t N>\nvoid exercise_nullspace(rng_t* rng, index_t trials) {\n    auto urnd = std::uniform_int_distribution<index_t>(1, N - 1);\n    Vec<T,N> bases[N];\n    for (index_t i = 0; i < trials; ++i) {\n        index_t n = urnd(*rng);\n        randomize(bases[0].begin(), n * N, rng);\n        nullspace(bases, n, bases + n);\n        \n        // verify that each of the null bases have\n        // zero dot product with the source bases.\n        // (they are not guaranteed to be orthogonal to each other)\n        for (index_t j = 0; j < n; ++j) {\n            for (index_t k = n; k < N; ++k) {\n                BOOST_CHECK_SMALL(bases[j].dot(bases[k]), 1e-5);\n            }\n        }\n    }\n}\n\n\nBOOST_AUTO_TEST_SUITE(linear_solve_tests)\n\n\nBOOST_AUTO_TEST_CASE(verify_nullspace) {\n    rng_t rng(16512485420001724907ULL);\n    exercise_nullspace<double,  2>(&rng, 250);\n    exercise_nullspace<double,  3>(&rng, 250);\n    exercise_nullspace<double,  4>(&rng, 250);\n    exercise_nullspace<double,  5>(&rng, 250);\n    exercise_nullspace<double, 10>(&rng, 250);\n}\n\n\nBOOST_AUTO_TEST_CASE(verify_orthogonal) {\n    rng_t rng(15794404771588593305ULL);\n    exercise_orthogonalize<double,  2>(&rng, 250);\n    exercise_orthogonalize<double,  3>(&rng, 250);\n    exercise_orthogonalize<double,  4>(&rng, 250);\n    exercise_orthogonalize<double,  5>(&rng, 250);\n    exercise_orthogonalize<double, 10>(&rng, 250);\n}\n\n\nBOOST_AUTO_TEST_CASE(verify_PLU) {\n    rng_t rng(1013126187766094264ULL);\n    exercise_plu<double>(&rng, 2,  250);\n    exercise_plu<double>(&rng, 3,  250);\n    exercise_plu<double>(&rng, 4,  250);\n    exercise_plu<double>(&rng, 5,  250);\n    exercise_plu<double>(&rng, 7,  250);\n    exercise_plu<double>(&rng, 10, 100);\n}\n\n\nBOOST_AUTO_TEST_CASE(linear_solve_tests) {\n    rng_t rng(7301667549950575693ULL);\n    exercise_solve_vectors<double,2>(&rng, 250);\n    exercise_solve_vectors<double,3>(&rng, 250);\n    exercise_solve_vectors<double,4>(&rng, 250);\n    exercise_solve_vectors<double,5>(&rng, 250);\n    exercise_solve_vectors<double,6>(&rng, 250);\n    exercise_solve_vectors<double,7>(&rng, 250);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n", "meta": {"hexsha": "bccfaeb6cf2d2c05c3632996433b656bf5044934", "size": 4995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "regression/linear_solve.cpp", "max_stars_repo_name": "trbabb/geomc", "max_stars_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-07-22T20:33:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T00:16:16.000Z", "max_issues_repo_path": "regression/linear_solve.cpp", "max_issues_repo_name": "trbabb/geomc", "max_issues_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-08-13T14:28:07.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-29T00:04:47.000Z", "max_forks_repo_path": "regression/linear_solve.cpp", "max_forks_repo_name": "trbabb/geomc", "max_forks_repo_head_hexsha": "98685137a8e500403c0945c781b541f63108d2ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-10-03T10:30:55.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-06T18:14:18.000Z", "avg_line_length": 28.7068965517, "max_line_length": 76, "alphanum_fraction": 0.5945945946, "num_tokens": 1547, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6071383722494874}}
{"text": "#include <stdio.h>\n#include <math.h>\n#include <iostream>\n#include <Eigen/Eigen>\n\nusing namespace Eigen;\n\n\n/*\n * Function shape\n *\n * @desript Display shape information of given matrix.\n */\nvoid shape(const char *msg, Matrix<float, Dynamic, Dynamic> in)\n{\n  std::cout << msg << \"(\"  << in.rows() << \",\" << in.cols() << \")\" << std::endl;\n}\n\n/*\n * Function loge()\n *\n * @desript Calculate logf() for each items in given matrix.\n */\nMatrix<float, Dynamic, Dynamic> loge(Matrix<float, Dynamic, Dynamic> in)\n{\n  Matrix<float, Dynamic, Dynamic> out = in;\n\n  out = out.array() + 1e-7f;\n\n  for(int i=0; i<in.cols(); i++)\n    {\n      out(0, i) = logf(out(0,i));\n    }\n\n  return out;\n}\n\n/*\n * Function cross_entropy()\n *\n * @desript Calculate Cross Entropy Loss value from 2 input matrix.\n */\nfloat cross_entropy(Matrix<float, Dynamic, Dynamic> output, Matrix<float, Dynamic, Dynamic> expect)\n{\n  Matrix<float, Dynamic, Dynamic> tmp;\n  float out = 0.f;\n  tmp = expect.array() * loge(output).array();\n  out = tmp.sum();\n  return -out;\n};\n\n\n/*\n * Class NNLayer\n *\n * @desript Base class of Neural Network Layer.\n */\nclass NNLayer {\n  protected:\n    NNLayer *next;\n    NNLayer *back;\n\n  public:\n    NNLayer() : next(NULL), back(NULL)\n      {\n      };\n\n    virtual ~NNLayer() {};\n\n    virtual Matrix<float, Dynamic, Dynamic> forward(Matrix<float, Dynamic, Dynamic> m) = 0;\n    virtual Matrix<float, Dynamic, Dynamic> backward(float train_ratio, Matrix<float, Dynamic, Dynamic> m) = 0;\n    virtual void resize(int rows, int cols) = 0;\n\n    void setNext(NNLayer *n)\n      {\n        next = n;\n        n->back = this;\n      };\n\n    NNLayer * getNext()\n      {\n        return next;\n      };\n\n};\n\n\n/*\n * Class LastActivation\n *\n * @desript Base class of Final Activation Layer. This has loss() method function.\n */\nclass LastActivation : public NNLayer {\n  public:\n    LastActivation() : NNLayer()\n      {\n      };\n    virtual ~LastActivation(){};\n\n    virtual float loss(Matrix<float, Dynamic, Dynamic> expect) = 0;\n};\n\n\n/*\n * Class SoftMaxLayer\n *\n * @desript A kind of LastActivation Layer.\n */\nclass SoftMaxLayer : public LastActivation {\n  Matrix<float, 1, Dynamic> output;\n  public:\n    SoftMaxLayer() : LastActivation()\n      {\n      };\n\n    ~SoftMaxLayer() {};\n\n    Matrix<float, Dynamic, Dynamic> forward(Matrix<float, Dynamic, Dynamic> m)\n      {\n        float sum;\n        float max = m.maxCoeff(); // Maxvalue in the matrix.\n\n        output = m.array() - max; // Measures of overflow.\n\n        output = output.array().exp();\n        sum = output.sum();\n        output = output.array() / sum;\n\n        if (next != NULL)\n          return next->forward(output);\n        else\n          return output;\n      };\n\n    Matrix<float, Dynamic, Dynamic> backward(float train_ratio, Matrix<float, Dynamic, Dynamic> m)\n      {\n        Matrix<float, Dynamic, Dynamic> ret = output - m;\n        if (back != NULL)\n          return back->backward(train_ratio, ret);\n        else\n          return ret;\n      };\n\n    float loss(Matrix<float, Dynamic, Dynamic> expect)\n      {\n        return cross_entropy(output, expect);\n      };\n\n    void resize(int rows, int cols)\n      {\n      };\n};\n\n\n/*\n * Class ReLULayer\n *\n * @desript A kind of Activation Layer.\n */\nclass ReLULayer : public NNLayer {\n  Matrix<float, 1, Dynamic> output;\n  public:\n    ReLULayer() : NNLayer()\n      {\n      };\n\n    ~ReLULayer() {}\n\n    Matrix<float, Dynamic, Dynamic> forward(Matrix<float, Dynamic, Dynamic> m)\n      {\n        output = m;\n        for(int i=0; i<output.cols(); i++)\n          {\n            output(0, i) = output(0, i) <= 0 ? 0 : output(0,i);\n          }\n\n        if (next != NULL)\n          return next->forward(output);\n        else\n          return output;\n      };\n\n    Matrix<float, Dynamic, Dynamic> backward(float train_ratio, Matrix<float, Dynamic, Dynamic> m)\n      {\n        Matrix<float, Dynamic, Dynamic> ret = m;\n        for(int i=0; i<ret.cols(); i++)\n          {\n            ret(0, i) = output(0, i) <= 0 ? 0 : ret(0,i);\n          }\n\n        if (back != NULL)\n          return back->backward(train_ratio, ret);\n        else\n          return ret;\n      };\n\n    void resize(int rows, int cols)\n      {\n        output = Matrix<float, 1, Dynamic>::Random(1, cols);\n      };\n};\n\n\n/*\n * Class AffineLayer\n *\n * @desript A kind of Neural Network Layer.\n */\nclass AffineLayer : public NNLayer {\n  Matrix<float, Dynamic, Dynamic> w;\n  Matrix<float, 1, Dynamic> bias;\n  Matrix<float, 1, Dynamic> output;\n  Matrix<float, 1, Dynamic> inputx;\n\n  public:\n    AffineLayer() : NNLayer()\n      {\n      }\n\n    AffineLayer(int rows, int cols) : NNLayer()\n      {\n        resize(rows, cols);\n      }\n\n    ~AffineLayer() {};\n\n    void resize(int rows, int cols)\n      {\n        w.resize(rows, cols);\n        bias.resize(1, cols);\n        output.resize(1, cols);\n\n        w      = Matrix<float, Dynamic, Dynamic>::Random(rows, cols);\n        bias   = Matrix<float, 1, Dynamic>::Random(1, cols);\n        output = Matrix<float, 1, Dynamic>::Random(1, cols);\n      }\n\n    Matrix<float, Dynamic, Dynamic> forward(Matrix<float, Dynamic, Dynamic> m)\n      {\n        inputx = m;\n        output = (m * w) + bias;\n\n        if (next != NULL)\n          {\n            return next->forward(output);\n          }\n        else\n          {\n            return output;\n          }\n      }\n\n    Matrix<float, Dynamic, Dynamic> backward(float train_ratio, Matrix<float, Dynamic, Dynamic> m)\n      {\n        Matrix<float, Dynamic, Dynamic> ret;\n        Matrix<float, Dynamic, Dynamic> dw;\n        float db;\n\n        ret = m * w.transpose();\n        dw = inputx.transpose() * m;\n        db = m.sum();\n\n        w = w - (dw * train_ratio);\n        bias = bias.array() - (db * train_ratio);\n\n        if (back != NULL)\n          return back->backward(train_ratio, ret);\n        else\n          return ret;\n      };\n};\n\n\n/*\n * Class AffineLayer\n *\n * @desript A kind of Neural Network Layer.\n */\nclass NeuralNetwork {\n  NNLayer *top_layer;\n  NNLayer *last_layer;\n  Matrix<float, Dynamic, Dynamic> output;\n\n  public:\n    NeuralNetwork() : top_layer(NULL), last_layer(NULL)\n      {\n      };\n    ~NeuralNetwork()\n      {\n        NNLayer *tmp;\n        for(NNLayer *layer = top_layer; layer != NULL; )\n          {\n            tmp = layer->getNext();\n            delete layer;\n            layer = tmp;\n          }\n      };\n\n    void createNewLayer(int innum, int outnum, bool is_last=false)\n      {\n        NNLayer *new_affine;\n        NNLayer *activation;\n\n        new_affine = new AffineLayer(innum, outnum);\n\n        if (is_last)\n          {\n            activation = new SoftMaxLayer();\n          }\n        else\n          {\n            activation = new ReLULayer();\n          }\n\n        new_affine->setNext(activation);\n\n        if( last_layer == NULL )\n          {\n            top_layer = new_affine;\n          }\n        else\n          {\n            last_layer->setNext(new_affine);\n          }\n\n        last_layer = activation;\n      };\n\n    void print_layers()\n      {\n        for(NNLayer *layer = top_layer; layer != NULL; layer = layer->getNext())\n          {\n            std::cout << layer << \" --> \";\n          };\n        std::cout << \"NULL\" << std::endl;\n      };\n\n    Matrix<float, Dynamic, Dynamic> forward(Matrix<float, Dynamic, Dynamic> input)\n      {\n        output = top_layer->forward(input);\n        return output;\n      };\n\n    float backward(float train_ratio, Matrix<float, Dynamic, Dynamic> m)\n      {\n        float ret = ((LastActivation *)last_layer)->loss(m);\n        last_layer->backward(train_ratio, m);\n        return ret;\n      };\n\n};\n\n\nint main(void)\n{\n  NeuralNetwork nn;\n\n  float loss;\n  Matrix<float, Dynamic, Dynamic> out;\n\n#if 1\n  Matrix<float, 1, 2> input[4];\n  Matrix<float, 1, 1> expect[4];\n\n  input[0] << 0, 0; expect[0] << 0;\n  input[1] << 0, 1; expect[1] << 1;\n  input[2] << 1, 0; expect[2] << 1;\n  input[3] << 1, 1; expect[3] << 0;\n\n  nn.createNewLayer(2,2);\n  nn.createNewLayer(2,1, true);\n\n  loss = 100.f;\n  while (loss > 0.001f)\n    {\n      loss = 0.f;\n      for(int i=0; i<4; i++)\n        {\n          // std::cout << \"==== \" << i+1 << \" ====\"  << std::endl;\n          out = nn.forward( input[i] );\n          loss += nn.backward(0.1f, expect[i]);\n          // std::cout << \"   out = \" << out << std::endl;\n        }\n      loss /= 4;\n      std::cout << \"loss = \" << loss << std::endl;\n    }\n\n  for(int i=0; i<4; i++)\n    {\n      std::cout << \"Expect = \" << expect[i] << \" Input  = \" << input[i] << std::endl;\n      out = nn.forward( input[i] );\n      std::cout << \"Output = \" << out << std::endl;\n    }\n\n#else\n  Matrix<float, 1, 2> input;\n  Matrix<float, 1, 2> expect;\n\n  input << 3, 3;\n  expect << 0, 1;\n\n  nn.createNewLayer(2, 5);\n  nn.createNewLayer(5, 3);\n  nn.createNewLayer(3, 2, true);\n\n  std::cout << \"tmp input = \" << input << std::endl;\n  std::cout << \"expect = \" << expect << std::endl;\n  std::cout << \"input * expect = \" << input.array() * expect.array() << std::endl;\n\n  std::cout << \"input = \" << input << std::endl;\n  input = input.array() + 1;\n  std::cout << \"input = \" << input << std::endl;\n  \n\n  out = nn.forward( input );\n  std::cout << \"out.rows = \" << out.rows() << std::endl;\n  std::cout << \"out.cols = \" << out.cols() << std::endl;\n  std::cout << \"out = \" << out << std::endl;\n\n  loss = 100.f;\n  while (loss > 0.001f)\n    {\n      out = nn.forward( input );\n      loss = nn.backward(0.1f, expect);\n      std::cout << \"out = \" << out << std::endl;\n      std::cout << \"loss = \" << loss << std::endl;\n    }\n#endif\n\n  return 0;\n}\n\n", "meta": {"hexsha": "0a07f297e9fff55595f40f666aa6e480c53fb0e8", "size": 9515, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "eigen_test/old/nn2_w_name.cxx", "max_stars_repo_name": "takayoshi-k/marubatsu", "max_stars_repo_head_hexsha": "cfda9544aa02cb23ead41c67b980a8af47d5d50c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigen_test/old/nn2_w_name.cxx", "max_issues_repo_name": "takayoshi-k/marubatsu", "max_issues_repo_head_hexsha": "cfda9544aa02cb23ead41c67b980a8af47d5d50c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen_test/old/nn2_w_name.cxx", "max_forks_repo_name": "takayoshi-k/marubatsu", "max_forks_repo_head_hexsha": "cfda9544aa02cb23ead41c67b980a8af47d5d50c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.974595843, "max_line_length": 111, "alphanum_fraction": 0.5330530741, "num_tokens": 2569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107984180245, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.6071234850606707}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n/*\r\nUsing the partition generating function..\r\np(n) = p(n \u2013 1)  + p(k \u2013 2) \u2013 p(k \u2013 5) \u2013 p(k \u2013 7) + p(k \u2013 12) + p(k \u2013 15) \u2013 p(k \u2013 22)\u2026\r\nWhere p(0) = 1 and p(n) = 0 for n < 0..\r\nand k = m / 2 + 1 (k % 2 == 0) || -m / 2 + 1.\r\n*/\r\n\r\nint main(int argc, char *argv[]) {\r\n\t// We will need the generalized pentagonal numbers first.\r\n\tvector<cpp_int> k;\r\n\tk.push_back(1);\r\n\tint n = 1;\r\n\t// Loop through everything until we get something that fits our requirement.\r\n\twhile(true) {\r\n\t\tint i = 0;\r\n\t\tint penta = 1;\r\n\t\tk.push_back(0);\r\n\t\twhile(penta <= n) {\r\n\t\t\tint sign = (i % 4 > 1) ? -1 : 1;\r\n\t\t\tk[n] += sign * k[n - penta];\r\n\t\t\tk[n] %= 1'000'000;\r\n\t\t\ti++;\r\n\t\t\t// Generate the next pentagonal (generalized number).\r\n\t\t\tint j = (i % 2 == 0) ? i / 2 + 1 : -(i / 2 + 1);\r\n\t\t\tpenta = j * (3 * j - 1) / 2;\r\n\t\t}\r\n\t\tif(!k[n]) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tn++;\r\n\t}\r\n\tcout << n << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "66c76bbf4d3981a279de53fa278a572cc948fa2e", "size": 1024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/51-100/78/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/51-100/78/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/51-100/78/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 24.9756097561, "max_line_length": 87, "alphanum_fraction": 0.5234375, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107914029486, "lm_q2_score": 0.6477982111525409, "lm_q1q2_score": 0.6071234741436873}}
{"text": "//#define CGAL_USE_BOOST_BIMAP\n#define CGAL_MESH_2_OPTIMIZER_VERBOSE\n#define CGAL_MESH_2_OPTIMIZERS_DEBUG\n\n#include <fstream>\n#include <vector>\n#include <list>\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n\n// CGAL headers\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n#include <CGAL/Delaunay_mesher_2.h>\n#include <CGAL/Delaunay_mesh_face_base_2.h>\n#include <CGAL/Delaunay_mesh_vertex_base_2.h>\n#include <CGAL/Delaunay_mesh_size_criteria_2.h>\n#include <CGAL/Mesh_2/Lipschitz_sizing_field_2.h>\n#include <CGAL/Lipschitz_sizing_field_criteria_2.h>\n#include <CGAL/Constrained_voronoi_diagram_2.h>\n#include <CGAL/Triangulation_conformer_2.h>\n#include <CGAL/lloyd_optimize_mesh_2.h>\n#include <CGAL/IO/File_poly.h>\n#include <CGAL/Random.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/Timer.h>\n#include <CGAL/IO/write_vtu.h>\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include <CGAL/IO/WKT.h>\n#endif\n\n// Qt headers\n#include <QtGui>\n#include <QString>\n#include <QActionGroup>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <QDragEnterEvent>\n#include <QDropEvent>\n#include <QMessageBox>\n\n// GraphicsView items and event filters (input classes)\n#include \"TriangulationCircumcircle.h\"\n#include \"DelaunayMeshInsertSeeds.h\"\n#include <CGAL/Qt/GraphicsViewPolylineInput.h>\n#include <CGAL/Qt/DelaunayMeshTriangulationGraphicsItem.h>\n#include <CGAL/Qt/Converter.h>\n// the two base classes\n#include \"ui_Constrained_Delaunay_triangulation_2.h\"\n#include <CGAL/Qt/DemosMainWindow.h>\n\n// for viewportsBbox(QGraphicsScene*)\n#include <CGAL/Qt/utility.h>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\ntypedef K::Segment_2 Segment_2;\ntypedef K::Iso_rectangle_2 Iso_rectangle_2;\ntypedef CGAL::Delaunay_mesh_vertex_base_2<K>  Vertex_base;\ntypedef CGAL::Delaunay_mesh_face_base_2<K> Face_base;\n\ntypedef Face_base Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vertex_base, Fb>  TDS;\ntypedef CGAL::Exact_predicates_tag              Itag;\ntypedef CGAL::Constrained_Delaunay_triangulation_2<K, TDS, Itag> CDT;\ntypedef CGAL::Constrained_voronoi_diagram_2<CDT> CVD;\ntypedef CGAL::Delaunay_mesh_size_criteria_2<CDT> Criteria;\n\ntypedef CGAL::Lipschitz_sizing_field_2<CDT> Lipschitz_sizing_field;\ntypedef CGAL::Lipschitz_sizing_field_criteria_2<CDT, Lipschitz_sizing_field> Lipschitz_criteria;\ntypedef CGAL::Delaunay_mesher_2<CDT, Lipschitz_criteria> Lipschitz_mesher;\n\ntypedef CDT::Vertex_handle Vertex_handle;\ntypedef CDT::Face_handle Face_handle;\ntypedef CDT::All_faces_iterator All_faces_iterator;\n\nusing namespace CGAL::parameters;\n\nvoid\ndiscoverInfiniteComponent(const CDT & ct)\n{\n  //when this function is called, all faces are set \"in_domain\"\n  Face_handle start = ct.infinite_face();\n  std::list<Face_handle> queue;\n  queue.push_back(start);\n\n  while(! queue.empty())\n  {\n    Face_handle fh = queue.front();\n    queue.pop_front();\n    fh->set_in_domain(false);\n\n    for(int i = 0; i < 3; i++)\n    {\n      Face_handle fi = fh->neighbor(i);\n      if(fi->is_in_domain()\n         && !ct.is_constrained(CDT::Edge(fh,i)))\n        queue.push_back(fi);\n    }\n  }\n}\n\ntemplate<typename SeedList>\nvoid\ndiscoverComponents(const CDT & ct,\n                   const SeedList& seeds)\n{\n  if (ct.dimension() != 2)\n    return;\n\n  // tag all faces inside\n  for(typename CDT::All_faces_iterator fit = ct.all_faces_begin();\n      fit != ct.all_faces_end();\n      ++fit)\n      fit->set_in_domain(true);\n\n  // mark \"outside\" infinite component of the object\n  discoverInfiniteComponent(ct);\n\n  // mark \"outside\" components with a seed\n  for(typename SeedList::const_iterator sit = seeds.begin();\n      sit != seeds.end();\n      ++sit)\n  {\n    typename CDT::Face_handle fh_loc = ct.locate(*sit);\n\n    if(fh_loc == nullptr || !fh_loc->is_in_domain())\n      continue;\n\n    std::list<typename CDT::Face_handle> queue;\n    queue.push_back(fh_loc);\n    while(!queue.empty())\n    {\n      typename CDT::Face_handle f = queue.front();\n      queue.pop_front();\n      f->set_in_domain(false);\n\n      for(int i = 0; i < 3; ++i)\n      {\n        typename CDT::Face_handle ni = f->neighbor(i);\n        if(ni->is_in_domain()\n          && !ct.is_constrained(typename CDT::Edge(f,i))) //same component\n        {\n          queue.push_back(ni);\n        }\n      }\n    }\n  }\n}\n\n\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Constrained_Delaunay_triangulation_2\n{\n  Q_OBJECT\n\nprivate:\n  CDT cdt;\n  QGraphicsScene scene;\n  std::list<Point_2> m_seeds;\n\n  CGAL::Qt::DelaunayMeshTriangulationGraphicsItem<CDT> * dgi;\n\n  CGAL::Qt::GraphicsViewPolylineInput<K> * pi;\n  CGAL::Qt::TriangulationCircumcircle<CDT> *tcc;\n  CGAL::Qt::DelaunayMeshInsertSeeds<CDT> *dms;\n\npublic:\n  MainWindow();\n\n  void clear();\n\nprivate:\n  template <typename Iterator>\n  void insert_polyline(Iterator b, Iterator e)\n  {\n    Point_2 p, q;\n    typename CDT::Vertex_handle vh, wh;\n    Iterator it = b;\n    vh = cdt.insert(*it);\n    p = *it;\n    ++it;\n    for(; it != e; ++it){\n      q = *it;\n      if(p != q){\n        wh = cdt.insert(*it);\n        cdt.insert_constraint(vh,wh);\n        vh = wh;\n        p = q;\n      } else {\n        std::cout << \"duplicate point: \" << p << std::endl;\n      }\n    }\n    Q_EMIT( changed());\n  }\n\npublic Q_SLOTS:\n  void open(QString);\n\n  void processInput(CGAL::Object o);\n\n  void on_actionShowVertices_toggled(bool checked);\n\n  void on_actionShowDelaunay_toggled(bool checked);\n\n  void on_actionShowTriangulationInDomain_toggled(bool checked);\n\n  void on_actionShow_constrained_edges_toggled(bool checked);\n\n  void on_actionShow_voronoi_edges_toggled(bool checked);\n\n  void on_actionShow_faces_in_domain_toggled(bool checked);\n\n  void on_actionShow_blind_faces_toggled(bool checked);\n\n  void on_actionShow_seeds_toggled(bool checked);\n\n  void on_actionInsertPolyline_toggled(bool checked);\n\n  void on_actionInsertSeeds_OnOff_toggled(bool checked);\n\n  void on_actionCircumcenter_toggled(bool checked);\n\n  void on_actionClear_triggered();\n\n  void on_actionRecenter_triggered();\n\n  void on_actionLoadConstraints_triggered();\n\n  void loadWKT(QString);\n\n  void loadFile(QString);\n\n  void loadPolyConstraints(QString);\n\n  void loadPolygonConstraints(QString);\n\n  void loadEdgConstraints(QString);\n\n  void on_actionSaveConstraints_triggered();\n\n  void saveConstraints(QString);\n\n  void on_actionMakeGabrielConform_triggered();\n\n  void on_actionMakeDelaunayConform_triggered();\n\n  void on_actionMakeDelaunayMesh_triggered();\n\n  void on_actionMakeLipschitzDelaunayMesh_triggered();\n\n  void on_actionInsertRandomPoints_triggered();\n\n  void on_actionTagBlindFaces_triggered();\n\n  void on_actionLloyd_optimization_triggered();\n\nQ_SIGNALS:\n  void changed();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow()\n{\n  setupUi(this);\n\n  this->graphicsView->setAcceptDrops(false);\n\n  // Add a GraphicItem for the CDT triangulation\n  dgi = new CGAL::Qt::DelaunayMeshTriangulationGraphicsItem<CDT>(&cdt);\n  QColor facesColor(::Qt::blue);\n  facesColor.setAlpha(150);\n  dgi->setFacesInDomainBrush(facesColor);\n\n  QObject::connect(this, SIGNAL(changed()),\n                   dgi, SLOT(modelChanged()));\n  dgi->setVerticesPen(\n    QPen(Qt::red, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  dgi->setVoronoiPen(\n    QPen(Qt::darkGreen, 0, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin));\n  dgi->setSeedsPen(\n    QPen(Qt::darkBlue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n\n  dgi->setZValue(-1);\n  scene.addItem(dgi);\n\n  // Setup input handlers. They get events before the scene gets them\n  // and the input they generate is passed to the triangulation with\n  // the signal/slot mechanism\n  pi = new CGAL::Qt::GraphicsViewPolylineInput<K>(this, &scene, 0, true); // inputs polylines which are not closed\n  QObject::connect(pi, SIGNAL(generate(CGAL::Object)),\n                   this, SLOT(processInput(CGAL::Object)));\n\n  tcc = new CGAL::Qt::TriangulationCircumcircle<CDT>(&scene, &cdt, this);\n  tcc->setPen(QPen(Qt::red, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n\n  dms = new CGAL::Qt::DelaunayMeshInsertSeeds<CDT>(&scene, &cdt, this);//input seeds\n  QObject::connect(dms, SIGNAL(generate(CGAL::Object)),\n                   this, SLOT(processInput(CGAL::Object)));\n\n  //\n  // Manual handling of actions\n  //\n  QObject::connect(this->actionQuit, SIGNAL(triggered()),\n                   this, SLOT(close()));\n\n  // We put mutually exclusive actions in an QActionGroup\n  QActionGroup* ag = new QActionGroup(this);\n  ag->addAction(this->actionInsertPolyline);\n\n  // Check two actions\n  this->actionInsertPolyline->setChecked(true);\n  this->actionShowDelaunay->setChecked(true);\n  this->actionShowVertices->setChecked(true);\n  this->actionShowTriangulationInDomain->setChecked(false);\n  this->actionShow_faces_in_domain->setChecked(true);\n  this->actionShow_constrained_edges->setChecked(true);\n  this->actionShow_voronoi_edges->setChecked(false);\n  this->actionShow_seeds->setChecked(false);\n  this->actionInsertSeeds_OnOff->setChecked(false);\n\n  //\n  // Setup the scene and the view\n  //\n  scene.setItemIndexMethod(QGraphicsScene::NoIndex);\n  scene.setSceneRect(-100, -100, 100, 100);\n  this->graphicsView->setScene(&scene);\n  this->graphicsView->setMouseTracking(true);\n\n  // Turn the vertical axis upside down\n  this->graphicsView->scale(1, -1);\n\n  // The navigation adds zooming and translation functionality to the\n  // QGraphicsView\n  this->addNavigation(this->graphicsView);\n\n  this->setupStatusBar();\n  this->setupOptionsMenu();\n  this->addAboutDemo(\":/cgal/help/about_Constrained_Delaunay_triangulation_2.html\");\n  this->addAboutCGAL();\n  this->setupExportSVG(this->actionExport_SVG, this->graphicsView);\n\n  this->addRecentFiles(this->menuFile, this->actionQuit);\n  connect(this, SIGNAL(openRecentFile(QString)),\n          this, SLOT(open(QString)));\n}\n\n\nvoid\nMainWindow::processInput(CGAL::Object o)\n{\n  // Polygon\n  std::list<Point_2> points;\n  if(CGAL::assign(points, o))\n  {\n    if(points.size() == 1)\n      cdt.insert(points.front());\n    else\n      insert_polyline(points.begin(), points.end());\n    }\n  else\n  {\n    // Seed (from Shift + left clic)\n    Point_2 p;\n    if(CGAL::assign(p, o))\n    {\n      m_seeds.push_back(p);\n      if(actionShow_seeds->isChecked())\n        dgi->setVisibleSeeds(true, m_seeds.begin(), m_seeds.end());\n    }\n  }\n\n  discoverComponents(cdt, m_seeds);\n  Q_EMIT( changed());\n}\n\n\n/*\n *  Qt Automatic Connections\n *  https://doc.qt.io/qt-5/designer-using-a-ui-file.html#automatic-connections\n *\n *  setupUi(this) generates connections to the slots named\n *  \"on_<action_name>_<signal_name>\"\n */\nvoid\nMainWindow::on_actionInsertPolyline_toggled(bool checked)\n{\n  if(checked){\n    scene.installEventFilter(pi);\n  } else {\n    scene.removeEventFilter(pi);\n  }\n}\n\nvoid\nMainWindow::on_actionInsertSeeds_OnOff_toggled(bool checked)\n{\n  if(checked){\n    std::cout << \"Insert seeds with Shift + Left click\" << std::endl;\n    scene.installEventFilter(dms);\n  } else {\n    scene.removeEventFilter(dms);\n  }\n}\n\nvoid\nMainWindow::on_actionShowDelaunay_toggled(bool checked)\n{\n  dgi->setVisibleEdges(checked);\n  if(checked)\n  {\n    dgi->setVisibleInsideEdges(false);\n    actionShowTriangulationInDomain->setChecked(false);\n  }\n  update();\n}\n\nvoid\nMainWindow::on_actionShowVertices_toggled(bool checked)\n{\n  dgi->setVisibleVertices(checked);\n  update();\n}\n\nvoid\nMainWindow::on_actionShowTriangulationInDomain_toggled(bool checked)\n{\n  dgi->setVisibleInsideEdges(checked);\n  if(checked)\n  {\n    dgi->setVisibleEdges(false);\n    actionShowDelaunay->setChecked(false);\n  }\n  update();\n}\n\nvoid\nMainWindow::on_actionShow_constrained_edges_toggled(bool checked)\n{\n  dgi->setVisibleConstraints(checked);\n  update();\n}\n\nvoid\nMainWindow::on_actionShow_voronoi_edges_toggled(bool checked)\n{\n  dgi->setVisibleVoronoiEdges(checked);\n  update();\n}\n\nvoid\nMainWindow::on_actionShow_faces_in_domain_toggled(bool checked)\n{\n  dgi->setVisibleFacesInDomain(checked);\n  update();\n}\n\nvoid\nMainWindow::on_actionShow_blind_faces_toggled(bool checked)\n{\n  dgi->setVisibleBlindFaces(checked);\n  update();\n}\n\nvoid\nMainWindow::on_actionShow_seeds_toggled(bool checked)\n{\n  dgi->setVisibleSeeds(checked, m_seeds.begin(), m_seeds.end());\n  update();\n}\n\nvoid\nMainWindow::on_actionCircumcenter_toggled(bool checked)\n{\n  if(checked){\n    scene.installEventFilter(tcc);\n    tcc->show();\n  } else {\n    scene.removeEventFilter(tcc);\n    tcc->hide();\n  }\n}\n\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n  clear();\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::clear()\n{\n  cdt.clear();\n  m_seeds.clear();\n\n  if(actionShow_seeds->isChecked())\n    dgi->setVisibleSeeds(true, m_seeds.end(), m_seeds.end());\n}\n\nvoid\nMainWindow::open(QString fileName)\n{\n  if(! fileName.isEmpty()){\n    if(cdt.number_of_vertices() > 0)\n    {\n      QMessageBox msgBox(QMessageBox::Warning,\n        \"Open new polygon\",\n        \"Do you really want to clear the current mesh?\",\n        (QMessageBox::Yes | QMessageBox::No),\n        this);\n      int ret = msgBox.exec();\n      if(ret == QMessageBox::Yes)\n        clear();\n      else\n        return;\n    }\n    if(fileName.endsWith(\".polygons.cgal\")){\n      loadPolygonConstraints(fileName);\n    } else if(fileName.endsWith(\".cpts.cgal\")){\n      loadFile(fileName);\n    } else if(fileName.endsWith(\".edg\")){\n      loadEdgConstraints(fileName);\n    } else if(fileName.endsWith(\".poly\")){\n      loadPolyConstraints(fileName);\n    } else if(fileName.endsWith(\".wkt\")){\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n      loadWKT(fileName);\n#endif\n    }\n    this->addToRecentFiles(fileName);\n  }\n  Q_EMIT(changed());\n  actionRecenter->trigger();\n}\n\nvoid\nMainWindow::on_actionLoadConstraints_triggered()\n{\n  QString fileName = QFileDialog::getOpenFileName(this,\n                                                  tr(\"Open Constraint File\"),\n                                                  \".\",\n                                                  tr(\"Edge files (*.edg);;\"\n                                                     \"Polyline files (*.polygons.cgal);;\"\n                                                     \"Poly files (*.poly);;\"\n                                                     \"Plg files (*.plg);;\"\n                                                     \"CGAL files (*.cpts.cgal);;\"\n                                                   #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                                                     \"WKT files (*.WKT *.wkt);;\"\n                                                   #endif\n                                                     \"All (*)\"));\n  open(fileName);\n}\n\nvoid\nMainWindow::loadWKT(QString\n                    #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n                    filename\n                    #endif\n                    )\n{\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n  //Polygons todo : make it multipolygons\n  std::ifstream ifs(qPrintable(filename));\n  do\n  {\n    typedef CGAL::Polygon_with_holes_2<K> Polygon;\n    typedef CGAL::Point_2<K> Point;\n    std::vector<Polygon> mps;\n    CGAL::read_multi_polygon_WKT(ifs, mps);\n    for(const Polygon& p : mps)\n    {\n      if(p.outer_boundary().is_empty())\n        continue;\n\n      for(Point point : p.outer_boundary().container())\n          cdt.insert(point);\n      for(Polygon::General_polygon_2::Edge_const_iterator\n          e_it=p.outer_boundary().edges_begin(); e_it != p.outer_boundary().edges_end(); ++e_it)\n        cdt.insert_constraint(e_it->source(), e_it->target());\n\n      for(Polygon::Hole_const_iterator h_it =\n          p.holes_begin(); h_it != p.holes_end(); ++h_it)\n      {\n        for(Point point : h_it->container())\n            cdt.insert(point);\n        for(Polygon::General_polygon_2::Edge_const_iterator\n            e_it=h_it->edges_begin(); e_it != h_it->edges_end(); ++e_it)\n        {\n          cdt.insert_constraint(e_it->source(), e_it->target());\n        }\n      }\n    }\n  }while(ifs.good() && !ifs.eof());\n  //Edges\n  ifs.clear();\n  ifs.seekg(0, ifs.beg);\n  do\n  {\n    typedef std::vector<K::Point_2> LineString;\n    std::vector<LineString> mls;\n    CGAL::read_multi_linestring_WKT(ifs, mls);\n    for(const LineString& ls : mls)\n    {\n      if(ls.empty())\n        continue;\n      K::Point_2 p,q, qold(0,0); // initialize to avoid maybe-uninitialized warning from GCC6\n      bool first = true;\n      CDT::Vertex_handle vp, vq, vqold;\n      LineString::const_iterator it =\n          ls.begin();\n      for(; it != ls.end(); ++it) {\n        p = *it++;\n        q = *it;\n        if(p == q){\n          continue;\n        }\n        if((!first) && (p == qold)){\n          vp = vqold;\n        } else {\n          vp = cdt.insert(p);\n        }\n        vq = cdt.insert(q, vp->face());\n        if(vp != vq) {\n          cdt.insert_constraint(vp,vq);\n        }\n        qold = q;\n        vqold = vq;\n        first = false;\n      }\n    }\n  }while(ifs.good() && !ifs.eof());\n\n  //Points\n  ifs.clear();\n  ifs.seekg(0, ifs.beg);\n  do\n  {\n    std::vector<K::Point_2> mpts;\n    CGAL::read_multi_point_WKT(ifs, mpts);\n    for(const K::Point_2& p : mpts)\n    {\n      cdt.insert(p);\n    }\n  }while(ifs.good() && !ifs.eof());\n\n  discoverComponents(cdt, m_seeds);\n  Q_EMIT( changed());\n  actionRecenter->trigger();\n#endif\n}\n\nvoid\nMainWindow::loadFile(QString fileName)\n{\n  std::ifstream ifs(qPrintable(fileName));\n  ifs >> cdt;\n  if(!ifs) abort();\n  discoverComponents(cdt, m_seeds);\n  Q_EMIT( changed());\n  actionRecenter->trigger();\n}\n\nvoid\nMainWindow::loadPolyConstraints(QString fileName)\n{\n  std::ifstream ifs(qPrintable(fileName));\n  read_triangle_poly_file(cdt,ifs);\n  discoverComponents(cdt, m_seeds);\n  Q_EMIT( changed());\n  actionRecenter->trigger();\n}\n\n\nvoid\nMainWindow::loadPolygonConstraints(QString fileName)\n{\n  K::Point_2 p,q, first;\n  CDT::Vertex_handle vp, vq, vfirst;\n  std::ifstream ifs(qPrintable(fileName));\n  int n;\n  // int counter = 0;\n  while(ifs >> n){\n    int poly_size = n;\n    ifs >> first;\n    p = first;\n    vfirst = vp = cdt.insert(p);\n    n--;\n    while(n--){\n      ifs >> q;\n      vq = cdt.insert(q, vp->face());\n      if(vp != vq) {\n        cdt.insert_constraint(vp,vq);\n        // std::cerr << \"inserted constraint #\" << counter++ << std::endl;\n      }\n      p = q;\n      vp = vq;\n    }\n    if(poly_size != 2 && vp != vfirst) {\n      cdt.insert_constraint(vp, vfirst);\n    }\n  }\n\n  discoverComponents(cdt, m_seeds);\n  Q_EMIT( changed());\n  actionRecenter->trigger();\n}\n\n\nvoid\nMainWindow::loadEdgConstraints(QString fileName)\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  CGAL::Timer tim;\n  tim.start();\n  std::ifstream ifs(qPrintable(fileName));\n  bool first=true;\n  int n;\n  ifs >> n;\n\n  K::Point_2 p,q, qold(0,0); // initialize to avoid maybe-uninitialized warning from GCC6\n\n  CDT::Vertex_handle vp, vq, vqold;\n  while(ifs >> p) {\n    ifs >> q;\n    if(p == q){\n      continue;\n    }\n    if((!first) && (p == qold)){\n      vp = vqold;\n    } else {\n      vp = cdt.insert(p);\n    }\n    vq = cdt.insert(q, vp->face());\n    if(vp != vq) {\n      cdt.insert_constraint(vp,vq);\n    }\n    qold = q;\n    vqold = vq;\n    first = false;\n  }\n\n\n  tim.stop();\n  statusBar()->showMessage(QString(\"Insertion took %1 seconds\").arg(tim.time()), 2000);\n  discoverComponents(cdt, m_seeds);\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT( changed());\n  actionRecenter->trigger();\n}\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n  this->graphicsView->setSceneRect(dgi->boundingRect());\n  this->graphicsView->fitInView(dgi->boundingRect(), Qt::KeepAspectRatio);\n}\n\n\nvoid\nMainWindow::on_actionSaveConstraints_triggered()\n{\n  QString fileName = QFileDialog::getSaveFileName(this,\n\n                                                  tr(\"Save Constraints\"),\n                                                  \".\",\n                                                  tr(\"CGAL files (*.cpts.cgal);;\"\n                                                     \"VTU files (*.vtu);;\"\n                                                     \"All (*)\"));\n  if(! fileName.isEmpty()){\n      saveConstraints(fileName);\n  }\n}\n\n\nvoid\nMainWindow::saveConstraints(QString fileName)\n{\n  std::ofstream output(qPrintable(fileName));\n\n  if(!fileName.endsWith(\"vtu\") && output)\n    output << cdt;\n  else if (output)\n  {\n    CGAL::write_vtu(output, cdt);\n  }\n}\n\n\nvoid\nMainWindow::on_actionMakeGabrielConform_triggered()\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::size_t nv = cdt.number_of_vertices();\n  CGAL::make_conforming_Gabriel_2(cdt);\n  nv = cdt.number_of_vertices() - nv;\n  discoverComponents(cdt, m_seeds);\n  statusBar()->showMessage(QString(\"Added %1 vertices\").arg(nv), 2000);\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionMakeDelaunayConform_triggered()\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::size_t nv = cdt.number_of_vertices();\n  CGAL::make_conforming_Delaunay_2(cdt);\n  discoverComponents(cdt, m_seeds);\n  nv = cdt.number_of_vertices() - nv;\n  statusBar()->showMessage(QString(\"Added %1 vertices\").arg(nv), 2000);\n   // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionMakeDelaunayMesh_triggered()\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  CGAL::Timer timer;\n  timer.start();\n  discoverComponents(cdt, m_seeds);\n  timer.stop();\n  QApplication::restoreOverrideCursor();\n\n  bool ok;\n  double shape = QInputDialog::getDouble(this, tr(\"Shape criterion\"),\n    tr(\"B = \"), 0.125, 0.005, 100, 4, &ok);\n  if(!ok) return;\n\n  double edge_len = QInputDialog::getDouble(this, tr(\"Size criterion\"),\n    tr(\"S = \"), 0., 0., (std::numeric_limits<double>::max)(), 5, &ok);\n  if(!ok) return;\n\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::size_t nv = cdt.number_of_vertices();\n  timer.start();\n\n  CGAL::refine_Delaunay_mesh_2(cdt,\n      m_seeds.begin(), m_seeds.end(),\n      Criteria(shape, edge_len),\n      false);//mesh the subdomains including NO seed\n\n  timer.stop();\n  nv = cdt.number_of_vertices() - nv;\n  statusBar()->showMessage(QString(\"Added %1 vertices in %2 seconds\").arg(nv).arg(timer.time()), 2000);\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionMakeLipschitzDelaunayMesh_triggered()\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::set<Point_2> points;\n  for(CDT::Finite_edges_iterator it = cdt.finite_edges_begin();\n      it != cdt.finite_edges_end();\n      ++it){\n    if(cdt.is_constrained(*it)){\n      Segment_2 s = cdt.segment(*it);\n      points.insert(s.source());\n      points.insert(s.target());\n    }\n  }\n\n  discoverComponents(cdt, m_seeds);\n\n  bool ok;\n  double shape = QInputDialog::getDouble(this, tr(\"Shape criterion\"),\n    tr(\"B = \"), 0.125, 0.005, 100, 4, &ok);\n  if(!ok) return;\n  double klip = QInputDialog::getDouble(this, tr(\"k-Lipschitz sizing field\"),\n    tr(\"k = \"), 1., 0.01, 500, 5, &ok);\n  if(!ok) return;\n\n  Lipschitz_sizing_field field(points.begin(), points.end(), klip);\n  Lipschitz_criteria criteria(shape, &field);\n  Lipschitz_mesher mesher(cdt);\n  mesher.set_criteria(criteria);\n\n  std::size_t nv = cdt.number_of_vertices();\n  mesher.init(true);\n  mesher.set_seeds(m_seeds.begin(), m_seeds.end(),\n                   false);//mesh the subdomains including NO seed\n\n  mesher.refine_mesh();\n  nv = cdt.number_of_vertices() - nv;\n  statusBar()->showMessage(QString(\"Added %1 vertices\").arg(nv), 2000);\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionInsertRandomPoints_triggered()\n{\n  QRectF rect = CGAL::Qt::viewportsBbox(&scene);\n  CGAL::Qt::Converter<K> convert;\n  Iso_rectangle_2 isor = convert(rect);\n  CGAL::Random_points_in_iso_rectangle_2<Point_2> pg((isor.min)(), (isor.max)());\n  bool ok = false;\n\n  const int number_of_points =\n      QInputDialog::getInt(this,\n                           tr(\"Number of random points\"),\n                           tr(\"Enter number of random points\"),\n                           100,\n                           0,\n                           (std::numeric_limits<int>::max)(),\n                           1,\n                           &ok);\n\n  if(!ok) {\n    return;\n  }\n\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::vector<Point_2> points;\n  points.reserve(number_of_points);\n  for(int i = 0; i < number_of_points; ++i){\n    points.push_back(*pg++);\n  }\n  cdt.insert(points.begin(), points.end());\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionTagBlindFaces_triggered()\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  CVD voronoi(cdt);\n  voronoi.tag_faces_blind();\n\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT(changed());\n}\n\nvoid\nMainWindow::on_actionLloyd_optimization_triggered()\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  bool ok;\n  int nb = QInputDialog::getInt(this, tr(\"QInputDialog::getInteger()\"),\n    tr(\"Number of iterations :\"),\n    1/*val*/, 0/*min*/, 1000/*max*/, 1/*step*/, &ok);\n  if(!ok)\n  {\n    QApplication::restoreOverrideCursor();\n    return;\n  }\n\n  CGAL::lloyd_optimize_mesh_2(cdt,\n      max_iteration_number = nb,\n      seeds_begin = m_seeds.begin(),\n      seeds_end = m_seeds.end());\n\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  Q_EMIT(changed());\n}\n\n#include \"Constrained_Delaunay_triangulation_2.moc\"\n#include <CGAL/Qt/resources.h>\n\nint main(int argc, char **argv)\n{\n  QApplication app(argc, argv);\n\n  app.setOrganizationDomain(\"geometryfactory.com\");\n  app.setOrganizationName(\"GeometryFactory\");\n  app.setApplicationName(\"Constrained_Delaunay_triangulation_2 demo\");\n\n  // Import resources from libCGAL (Qt5).\n  CGAL_QT_INIT_RESOURCES;\n\n  MainWindow mainWindow;\n  mainWindow.show();\n\n  QStringList args = app.arguments();\n  args.removeAt(0);\n  Q_FOREACH(QString filename, args) {\n    mainWindow.open(filename);\n  }\n\n  return app.exec();\n}\n", "meta": {"hexsha": "60dd77c388d1c5176a429d2968b824d4d5c4f8cf", "size": 26233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphicsView/demo/Triangulation_2/Constrained_Delaunay_triangulation_2.cpp", "max_stars_repo_name": "mtola/cgal", "max_stars_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-08T23:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-08T23:06:26.000Z", "max_issues_repo_path": "GraphicsView/demo/Triangulation_2/Constrained_Delaunay_triangulation_2.cpp", "max_issues_repo_name": "samrat2825/cgal-dev", "max_issues_repo_head_hexsha": "eab5df14e118deb20db7373717bac273f1775a92", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-12T14:38:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-12T14:38:20.000Z", "max_forks_repo_path": "GraphicsView/demo/Triangulation_2/Constrained_Delaunay_triangulation_2.cpp", "max_forks_repo_name": "szobov/cgal", "max_forks_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9732673267, "max_line_length": 126, "alphanum_fraction": 0.6537948386, "num_tokens": 6919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6071174139908208}}
{"text": "/*********************************************************************\n *\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2016, Guan-Horng Liu.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the the copyright holder nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n * Author:  Guan-Horng Liu\n *********************************************************************/\n\n#include \"reeds_shepp.h\"\n#include <boost/math/constants/constants.hpp>\n\nnamespace\n{\n// The comments, variable names, etc. use the nomenclature from the Reeds & Shepp paper.\n\nconst double pi = boost::math::constants::pi<double>();\nconst double twopi = 2. * pi;\nconst double RS_EPS = 1e-6;\nconst double ZERO = 10 * std::numeric_limits<double>::epsilon();\n\ninline double mod2pi(double x)\n{\n  double v = fmod(x, twopi);\n  if (v < -pi)\n    v += twopi;\n  else if (v > pi)\n    v -= twopi;\n  return v;\n}\ninline void polar(double x, double y, double& r, double& theta)\n{\n  r = sqrt(x * x + y * y);\n  theta = atan2(y, x);\n}\ninline void tauOmega(double u, double v, double xi, double eta, double phi, double& tau, double& omega)\n{\n  double delta = mod2pi(u - v), A = sin(u) - sin(delta), B = cos(u) - cos(delta) - 1.;\n  double t1 = atan2(eta * A - xi * B, xi * A + eta * B), t2 = 2. * (cos(delta) - cos(v) - cos(u)) + 3;\n  tau = (t2 < 0) ? mod2pi(t1 + pi) : mod2pi(t1);\n  omega = mod2pi(tau - u + v - phi);\n}\n\n// formula 8.1 in Reeds-Shepp paper\ninline bool LpSpLp(double x, double y, double phi, double& t, double& u, double& v)\n{\n  polar(x - sin(phi), y - 1. + cos(phi), u, t);\n  if (t >= -ZERO)\n  {\n    v = mod2pi(phi - t);\n    if (v >= -ZERO)\n    {\n      assert(fabs(u * cos(t) + sin(phi) - x) < RS_EPS);\n      assert(fabs(u * sin(t) - cos(phi) + 1 - y) < RS_EPS);\n      assert(fabs(mod2pi(t + v - phi)) < RS_EPS);\n      return true;\n    }\n  }\n  return false;\n}\n// formula 8.2\ninline bool LpSpRp(double x, double y, double phi, double& t, double& u, double& v)\n{\n  double t1, u1;\n  polar(x + sin(phi), y - 1. - cos(phi), u1, t1);\n  u1 = u1 * u1;\n  if (u1 >= 4.)\n  {\n    double theta;\n    u = sqrt(u1 - 4.);\n    theta = atan2(2., u);\n    t = mod2pi(t1 + theta);\n    v = mod2pi(t - phi);\n    assert(fabs(2 * sin(t) + u * cos(t) - sin(phi) - x) < RS_EPS);\n    assert(fabs(-2 * cos(t) + u * sin(t) + cos(phi) + 1 - y) < RS_EPS);\n    assert(fabs(mod2pi(t - v - phi)) < RS_EPS);\n    return t >= -ZERO && v >= -ZERO;\n  }\n  return false;\n}\nvoid CSC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath& path)\n{\n  double t, u, v, Lmin = path.length(), L;\n  if (LpSpLp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[14], t, u, v);\n    Lmin = L;\n  }\n  if (LpSpLp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[14], -t, -u, -v);\n    Lmin = L;\n  }\n  if (LpSpLp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[15], t, u, v);\n    Lmin = L;\n  }\n  if (LpSpLp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip + reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[15], -t, -u, -v);\n    Lmin = L;\n  }\n  if (LpSpRp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[12], t, u, v);\n    Lmin = L;\n  }\n  if (LpSpRp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[12], -t, -u, -v);\n    Lmin = L;\n  }\n  if (LpSpRp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[13], t, u, v);\n    Lmin = L;\n  }\n  if (LpSpRp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip + reflect\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[13], -t, -u, -v);\n}\n// formula 8.3 / 8.4  *** TYPO IN PAPER ***\ninline bool LpRmL(double x, double y, double phi, double& t, double& u, double& v)\n{\n  double xi = x - sin(phi), eta = y - 1. + cos(phi), u1, theta;\n  polar(xi, eta, u1, theta);\n  if (u1 <= 4.)\n  {\n    u = -2. * asin(.25 * u1);\n    t = mod2pi(theta + .5 * u + pi);\n    v = mod2pi(phi - t + u);\n    assert(fabs(2 * (sin(t) - sin(t - u)) + sin(phi) - x) < RS_EPS);\n    assert(fabs(2 * (-cos(t) + cos(t - u)) - cos(phi) + 1 - y) < RS_EPS);\n    assert(fabs(mod2pi(t - u + v - phi)) < RS_EPS);\n    return t >= -ZERO && u <= ZERO;\n  }\n  return false;\n}\nvoid CCC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath& path)\n{\n  double t, u, v, Lmin = path.length(), L;\n  if (LpRmL(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[0], t, u, v);\n    Lmin = L;\n  }\n  if (LpRmL(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[0], -t, -u, -v);\n    Lmin = L;\n  }\n  if (LpRmL(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[1], t, u, v);\n    Lmin = L;\n  }\n  if (LpRmL(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip + reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[1], -t, -u, -v);\n    Lmin = L;\n  }\n\n  // backwards\n  double xb = x * cos(phi) + y * sin(phi), yb = x * sin(phi) - y * cos(phi);\n  if (LpRmL(xb, yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[0], v, u, t);\n    Lmin = L;\n  }\n  if (LpRmL(-xb, yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[0], -v, -u, -t);\n    Lmin = L;\n  }\n  if (LpRmL(xb, -yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[1], v, u, t);\n    Lmin = L;\n  }\n  if (LpRmL(-xb, -yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip + reflect\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[1], -v, -u, -t);\n}\n// formula 8.7\ninline bool LpRupLumRm(double x, double y, double phi, double& t, double& u, double& v)\n{\n  double xi = x + sin(phi), eta = y - 1. - cos(phi), rho = .25 * (2. + sqrt(xi * xi + eta * eta));\n  if (rho <= 1.)\n  {\n    u = acos(rho);\n    tauOmega(u, -u, xi, eta, phi, t, v);\n    assert(fabs(2 * (sin(t) - sin(t - u) + sin(t - 2 * u)) - sin(phi) - x) < RS_EPS);\n    assert(fabs(2 * (-cos(t) + cos(t - u) - cos(t - 2 * u)) + cos(phi) + 1 - y) < RS_EPS);\n    assert(fabs(mod2pi(t - 2 * u - v - phi)) < RS_EPS);\n    return t >= -ZERO && v <= ZERO;\n  }\n  return false;\n}\n// formula 8.8\ninline bool LpRumLumRp(double x, double y, double phi, double& t, double& u, double& v)\n{\n  double xi = x + sin(phi), eta = y - 1. - cos(phi), rho = (20. - xi * xi - eta * eta) / 16.;\n  if (rho >= 0 && rho <= 1)\n  {\n    u = -acos(rho);\n    if (u >= -.5 * pi)\n    {\n      tauOmega(u, u, xi, eta, phi, t, v);\n      assert(fabs(4 * sin(t) - 2 * sin(t - u) - sin(phi) - x) < RS_EPS);\n      assert(fabs(-4 * cos(t) + 2 * cos(t - u) + cos(phi) + 1 - y) < RS_EPS);\n      assert(fabs(mod2pi(t - v - phi)) < RS_EPS);\n      return t >= -ZERO && v >= -ZERO;\n    }\n  }\n  return false;\n}\nvoid CCCC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath& path)\n{\n  double t, u, v, Lmin = path.length(), L;\n  if (LpRupLumRm(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + 2. * fabs(u) + fabs(v)))\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[2], t, u, -u, v);\n    Lmin = L;\n  }\n  if (LpRupLumRm(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2. * fabs(u) + fabs(v)))  // timeflip\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[2], -t, -u, u, -v);\n    Lmin = L;\n  }\n  if (LpRupLumRm(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2. * fabs(u) + fabs(v)))  // reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[3], t, u, -u, v);\n    Lmin = L;\n  }\n  if (LpRupLumRm(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + 2. * fabs(u) + fabs(v)))  // timeflip + reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[3], -t, -u, u, -v);\n    Lmin = L;\n  }\n\n  if (LpRumLumRp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + 2. * fabs(u) + fabs(v)))\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[2], t, u, u, v);\n    Lmin = L;\n  }\n  if (LpRumLumRp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2. * fabs(u) + fabs(v)))  // timeflip\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[2], -t, -u, -u, -v);\n    Lmin = L;\n  }\n  if (LpRumLumRp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2. * fabs(u) + fabs(v)))  // reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[3], t, u, u, v);\n    Lmin = L;\n  }\n  if (LpRumLumRp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + 2. * fabs(u) + fabs(v)))  // timeflip + reflect\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[3], -t, -u, -u, -v);\n}\n// formula 8.9\ninline bool LpRmSmLm(double x, double y, double phi, double& t, double& u, double& v)\n{\n  double xi = x - sin(phi), eta = y - 1. + cos(phi), rho, theta;\n  polar(xi, eta, rho, theta);\n  if (rho >= 2.)\n  {\n    double r = sqrt(rho * rho - 4.);\n    u = 2. - r;\n    t = mod2pi(theta + atan2(r, -2.));\n    v = mod2pi(phi - .5 * pi - t);\n    assert(fabs(2 * (sin(t) - cos(t)) - u * sin(t) + sin(phi) - x) < RS_EPS);\n    assert(fabs(-2 * (sin(t) + cos(t)) + u * cos(t) - cos(phi) + 1 - y) < RS_EPS);\n    assert(fabs(mod2pi(t + pi / 2 + v - phi)) < RS_EPS);\n    return t >= -ZERO && u <= ZERO && v <= ZERO;\n  }\n  return false;\n}\n// formula 8.10\ninline bool LpRmSmRm(double x, double y, double phi, double& t, double& u, double& v)\n{\n  double xi = x + sin(phi), eta = y - 1. - cos(phi), rho, theta;\n  polar(-eta, xi, rho, theta);\n  if (rho >= 2.)\n  {\n    t = theta;\n    u = 2. - rho;\n    v = mod2pi(t + .5 * pi - phi);\n    assert(fabs(2 * sin(t) - cos(t - v) - u * sin(t) - x) < RS_EPS);\n    assert(fabs(-2 * cos(t) - sin(t - v) + u * cos(t) + 1 - y) < RS_EPS);\n    assert(fabs(mod2pi(t + pi / 2 - v - phi)) < RS_EPS);\n    return t >= -ZERO && u <= ZERO && v <= ZERO;\n  }\n  return false;\n}\nvoid CCSC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath& path)\n{\n  double t, u, v, Lmin = path.length() - .5 * pi, L;\n  if (LpRmSmLm(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[4], t, -.5 * pi, u, v);\n    Lmin = L;\n  }\n  if (LpRmSmLm(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[4], -t, .5 * pi, -u, -v);\n    Lmin = L;\n  }\n  if (LpRmSmLm(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[5], t, -.5 * pi, u, v);\n    Lmin = L;\n  }\n  if (LpRmSmLm(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip + reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[5], -t, .5 * pi, -u, -v);\n    Lmin = L;\n  }\n\n  if (LpRmSmRm(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[8], t, -.5 * pi, u, v);\n    Lmin = L;\n  }\n  if (LpRmSmRm(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[8], -t, .5 * pi, -u, -v);\n    Lmin = L;\n  }\n  if (LpRmSmRm(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[9], t, -.5 * pi, u, v);\n    Lmin = L;\n  }\n  if (LpRmSmRm(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip + reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[9], -t, .5 * pi, -u, -v);\n    Lmin = L;\n  }\n\n  // backwards\n  double xb = x * cos(phi) + y * sin(phi), yb = x * sin(phi) - y * cos(phi);\n  if (LpRmSmLm(xb, yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[6], v, u, -.5 * pi, t);\n    Lmin = L;\n  }\n  if (LpRmSmLm(-xb, yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[6], -v, -u, .5 * pi, -t);\n    Lmin = L;\n  }\n  if (LpRmSmLm(xb, -yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[7], v, u, -.5 * pi, t);\n    Lmin = L;\n  }\n  if (LpRmSmLm(-xb, -yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip + reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[7], -v, -u, .5 * pi, -t);\n    Lmin = L;\n  }\n\n  if (LpRmSmRm(xb, yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[10], v, u, -.5 * pi, t);\n    Lmin = L;\n  }\n  if (LpRmSmRm(-xb, yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[10], -v, -u, .5 * pi, -t);\n    Lmin = L;\n  }\n  if (LpRmSmRm(xb, -yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // reflect\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[11], v, u, -.5 * pi, t);\n    Lmin = L;\n  }\n  if (LpRmSmRm(-xb, -yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip + reflect\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[11], -v, -u, .5 * pi, -t);\n}\n// formula 8.11 *** TYPO IN PAPER ***\ninline bool LpRmSLmRp(double x, double y, double phi, double& t, double& u, double& v)\n{\n  double xi = x + sin(phi), eta = y - 1. - cos(phi), rho, theta;\n  polar(xi, eta, rho, theta);\n  if (rho >= 2.)\n  {\n    u = 4. - sqrt(rho * rho - 4.);\n    if (u <= ZERO)\n    {\n      t = mod2pi(atan2((4 - u) * xi - 2 * eta, -2 * xi + (u - 4) * eta));\n      v = mod2pi(t - phi);\n      assert(fabs(4 * sin(t) - 2 * cos(t) - u * sin(t) - sin(phi) - x) < RS_EPS);\n      assert(fabs(-4 * cos(t) - 2 * sin(t) + u * cos(t) + cos(phi) + 1 - y) < RS_EPS);\n      assert(fabs(mod2pi(t - v - phi)) < RS_EPS);\n      return t >= -ZERO && v >= -ZERO;\n    }\n  }\n  return false;\n}\nvoid CCSCC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath& path)\n{\n  double t, u, v, Lmin = path.length() - pi, L;\n  if (LpRmSLmRp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n  {\n    path =\n        ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[16], t, -.5 * pi, u, -.5 * pi, v);\n    Lmin = L;\n  }\n  if (LpRmSLmRp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip\n  {\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[16], -t, .5 * pi, -u, .5 * pi,\n                                                -v);\n    Lmin = L;\n  }\n  if (LpRmSLmRp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // reflect\n  {\n    path =\n        ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[17], t, -.5 * pi, u, -.5 * pi, v);\n    Lmin = L;\n  }\n  if (LpRmSLmRp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))  // timeflip + reflect\n    path = ReedsSheppStateSpace::ReedsSheppPath(ReedsSheppStateSpace::reedsSheppPathType[17], -t, .5 * pi, -u, .5 * pi,\n                                                -v);\n}\n\nReedsSheppStateSpace::ReedsSheppPath reedsShepp(double x, double y, double phi)\n{\n  ReedsSheppStateSpace::ReedsSheppPath path;\n  CSC(x, y, phi, path);\n  CCC(x, y, phi, path);\n  CCCC(x, y, phi, path);\n  CCSC(x, y, phi, path);\n  CCSCC(x, y, phi, path);\n  return path;\n}\n}  // namespace\n\nconst ReedsSheppStateSpace::ReedsSheppPathSegmentType ReedsSheppStateSpace::reedsSheppPathType[18][5] = {\n  { RS_LEFT, RS_RIGHT, RS_LEFT, RS_NOP, RS_NOP },         // 0\n  { RS_RIGHT, RS_LEFT, RS_RIGHT, RS_NOP, RS_NOP },        // 1\n  { RS_LEFT, RS_RIGHT, RS_LEFT, RS_RIGHT, RS_NOP },       // 2\n  { RS_RIGHT, RS_LEFT, RS_RIGHT, RS_LEFT, RS_NOP },       // 3\n  { RS_LEFT, RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_NOP },    // 4\n  { RS_RIGHT, RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_NOP },   // 5\n  { RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_LEFT, RS_NOP },    // 6\n  { RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_RIGHT, RS_NOP },   // 7\n  { RS_LEFT, RS_RIGHT, RS_STRAIGHT, RS_RIGHT, RS_NOP },   // 8\n  { RS_RIGHT, RS_LEFT, RS_STRAIGHT, RS_LEFT, RS_NOP },    // 9\n  { RS_RIGHT, RS_STRAIGHT, RS_RIGHT, RS_LEFT, RS_NOP },   // 10\n  { RS_LEFT, RS_STRAIGHT, RS_LEFT, RS_RIGHT, RS_NOP },    // 11\n  { RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_NOP, RS_NOP },     // 12\n  { RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_NOP, RS_NOP },     // 13\n  { RS_LEFT, RS_STRAIGHT, RS_LEFT, RS_NOP, RS_NOP },      // 14\n  { RS_RIGHT, RS_STRAIGHT, RS_RIGHT, RS_NOP, RS_NOP },    // 15\n  { RS_LEFT, RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_RIGHT },  // 16\n  { RS_RIGHT, RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_LEFT }   // 17\n};\n\nReedsSheppStateSpace::ReedsSheppPath::ReedsSheppPath(const ReedsSheppPathSegmentType* type, double t, double u,\n                                                     double v, double w, double x)\n  : type_(type)\n{\n  length_[0] = t;\n  length_[1] = u;\n  length_[2] = v;\n  length_[3] = w;\n  length_[4] = x;\n  totalLength_ = fabs(t) + fabs(u) + fabs(v) + fabs(w) + fabs(x);\n}\n\ndouble ReedsSheppStateSpace::distance(double q0[3], double q1[3])\n{\n  return rho_ * reedsShepp(q0, q1).length();\n}\n\nReedsSheppStateSpace::ReedsSheppPath ReedsSheppStateSpace::reedsShepp(double q0[3], double q1[3])\n{\n  double dx = q1[0] - q0[0], dy = q1[1] - q0[1], dth = q1[2] - q0[2];\n  double c = cos(q0[2]), s = sin(q0[2]);\n  double x = c * dx + s * dy, y = -s * dx + c * dy;\n  return ::reedsShepp(x / rho_, y / rho_, dth);\n}\n\nvoid ReedsSheppStateSpace::type(double q0[3], double q1[3], ReedsSheppPathTypeCallback cb, void* user_data)\n{\n  ReedsSheppPath path = reedsShepp(q0, q1);\n  for (int i = 0; i < 5; ++i)\n    cb(path.type_[i], user_data);\n  return;\n}\n\nvoid ReedsSheppStateSpace::sample(double q0[3], double q1[3], double step_size, ReedsSheppPathSamplingCallback cb,\n                                  void* user_data)\n{\n  ReedsSheppPath path = reedsShepp(q0, q1);\n  double dist = rho_ * path.length();\n\n  for (double seg = 0.0; seg <= dist; seg += step_size)\n  {\n    double qnew[3] = {};\n    interpolate(q0, path, seg / rho_, qnew);\n    cb(qnew, user_data);\n  }\n  return;\n}\n\nvoid ReedsSheppStateSpace::interpolate(double q0[3], ReedsSheppPath& path, double seg, double s[3])\n{\n  if (seg < 0.0)\n    seg = 0.0;\n  if (seg > path.length())\n    seg = path.length();\n\n  double phi, v;\n\n  s[0] = s[1] = 0.0;\n  s[2] = q0[2];\n\n  for (unsigned int i = 0; i < 5 && seg > 0; ++i)\n  {\n    if (path.length_[i] < 0)\n    {\n      v = std::max(-seg, path.length_[i]);\n      seg += v;\n    }\n    else\n    {\n      v = std::min(seg, path.length_[i]);\n      seg -= v;\n    }\n    phi = s[2];\n    switch (path.type_[i])\n    {\n      case RS_LEFT:\n        s[0] += (sin(phi + v) - sin(phi));\n        s[1] += (-cos(phi + v) + cos(phi));\n        s[2] = phi + v;\n        break;\n      case RS_RIGHT:\n        s[0] += (-sin(phi - v) + sin(phi));\n        s[1] += (cos(phi - v) - cos(phi));\n        s[2] = phi - v;\n        break;\n      case RS_STRAIGHT:\n        s[0] += (v * cos(phi));\n        s[1] += (v * sin(phi));\n        break;\n      case RS_NOP:\n        break;\n    }\n  }\n\n  s[0] = s[0] * rho_ + q0[0];\n  s[1] = s[1] * rho_ + q0[1];\n}", "meta": {"hexsha": "c1400d384865d7489f69e8c5065e432eab642adb", "size": 22393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/align_navigation/src/reeds_shepp.cpp", "max_stars_repo_name": "SachitM/docking-sim", "max_stars_repo_head_hexsha": "d84cef005cac19afbc45f5f62e1bdbfe2fa55f02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/align_navigation/src/reeds_shepp.cpp", "max_issues_repo_name": "SachitM/docking-sim", "max_issues_repo_head_hexsha": "d84cef005cac19afbc45f5f62e1bdbfe2fa55f02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-08T01:19:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T19:21:26.000Z", "max_forks_repo_path": "src/align_navigation/src/reeds_shepp.cpp", "max_forks_repo_name": "SachitM/docking-sim", "max_forks_repo_head_hexsha": "d84cef005cac19afbc45f5f62e1bdbfe2fa55f02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T17:08:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T22:25:19.000Z", "avg_line_length": 38.4759450172, "max_line_length": 120, "alphanum_fraction": 0.5766534185, "num_tokens": 8534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6071174113453822}}
{"text": "\n\n#include <iostream>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <ctime>\n#include <chrono>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n\n\nint roll_die( boost::random::mt19937 &gen, int begin, int end) {\n    boost::random::uniform_int_distribution<> dist(begin, end);\n    return dist(gen);\n}\n\nconstexpr int iter = 100000;\n\n\nstd::vector<int> data(iter);\n\nint main(int argc, char** argv){\n\t//once per process\n\tboost::random::mt19937 gen0;\n\tint random_seed1 = roll_die(gen0, 0,100000); // should be generated for every thread\n\n\t// per thread\n\tboost::random::mt19937 gen(random_seed1);//random_seed1 to have different starting conditions in diff threads\n\n\tstd::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();\n\n\tfor(int i = 0; i < iter; ++i){\n\t\tdata[i] = roll_die(gen,0, 20);\n\t}\n\tstd::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n\t for(int i = 0; i < iter; ++i){\n\t\t\t std::cout << data[i]<< std::endl;\n\t\t \t}\n\tint total =  std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();\n\t std::cout << \"Loop took \" <<total << \" ms\"<< std::endl;\n\t std::cout << \"Iter took \" << ((double)total  / double(iter)) * 1000<< \" ns\"<< std::endl;\n\n\n return 0;\n}\n/*\n * Iter took 14.63 ns\n */\n\n\n\n", "meta": {"hexsha": "4675117f68c5f9f296d3545fa73204637bb1bfdf", "size": 1320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "diff/random.cpp", "max_stars_repo_name": "IgorHersht/proxygen_ih", "max_stars_repo_head_hexsha": "616a8eb899196d2a130e14c0fabcae1944e34b7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-11-10T05:18:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T15:38:25.000Z", "max_issues_repo_path": "diff/random.cpp", "max_issues_repo_name": "IgorHersht/proxygen_ih", "max_issues_repo_head_hexsha": "616a8eb899196d2a130e14c0fabcae1944e34b7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "diff/random.cpp", "max_forks_repo_name": "IgorHersht/proxygen_ih", "max_forks_repo_head_hexsha": "616a8eb899196d2a130e14c0fabcae1944e34b7d", "max_forks_repo_licenses": ["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.0, "max_line_length": 110, "alphanum_fraction": 0.6681818182, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.6071174076078275}}
{"text": "/*******************************************************************\r\nAuthor: David Ge (dge893@gmail.com, aka Wei Ge)\r\nLast modified: 11/16/2020\r\nAllrights reserved by David Ge\r\n\r\n********************************************************************/\r\n#include \"Space.h\"\r\n#include \"Curl.h\"\r\n#include \"../MathTools/Matrix.h\"\r\n#include \"../FileUtil/fileutil.h\"\r\n#include <stdlib.h>\r\n\r\n#include \"../boostLib/HiMatrix.h\"\r\n#include <boost/multiprecision/cpp_dec_float.hpp>\r\n\r\nSpace::Space()\r\n{\r\n\tds = 0.0;\r\n\tnx = ny = nz = 0;\r\n\tnx1 = ny1 = nz1 = 0;\r\n\tcellCount = 0;\r\n\tA = NULL;\r\n\tsmax = M = 0;\r\n\tfieldMemorySize = 0;\r\n\tcurlH = curlE = NULL;\r\n}\r\n\r\n\r\nSpace::~Space()\r\n{\r\n\tcleanup();\r\n}\r\n\r\nvoid Space::cleanup()\r\n{\r\n\ttss_free3Darray(A, M + 1, M);\r\n\tif (curlH != NULL)\r\n\t{\r\n\t\tdelete curlH;\r\n\t\tcurlH = NULL;\r\n\t}\r\n\tif (curlE != NULL)\r\n\t{\r\n\t\tdelete curlE;\r\n\t\tcurlE = NULL;\r\n\t}\r\n}\r\n\r\nvoid Space::setCalculationMethod(CURLMETHOD method)\r\n{\r\n\tcurlE->setCalculationMethod(method);\r\n\tcurlH->setCalculationMethod(method);\r\n}\r\n\r\ninline size_t Space::Idx(unsigned i, unsigned j, unsigned k)\r\n{\r\n\treturn k + nz1 * (j + ny1 * i);\r\n}\r\n\r\n/*\r\n\tgenerate space derivative estimation matrixes\r\n*/\r\nint Space::generateMatrix()\r\n{\r\n\tint ret = ERR_OK;\r\n\tusing namespace boost::multiprecision;\r\n\tcpp_dec_float_100 *W = (cpp_dec_float_100 *)malloc(M*M*sizeof(cpp_dec_float_100));\r\n\tcpp_dec_float_100 *Ai = (cpp_dec_float_100 *)malloc(M*M*sizeof(cpp_dec_float_100));\r\n\tdouble *AI = (double *)malloc(M*M*sizeof(double));\r\n\tA = tss_allocate3Darray(M + 1, M, M);\r\n\tif (AI == NULL || W == NULL || Ai == NULL || A == NULL)\r\n\t{\r\n\t\tret = ERR_OUTOFMEMORY;\r\n\t}\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tHiMatrixTools HiMatrix;\r\n\t\tunsigned int P = smax;\r\n\t\tunsigned int N = smax;\r\n\t\tunsigned int mi;\r\n\t\tcpp_dec_float_100 X = 1.0;\r\n\t\tcpp_dec_float_100 Dn = 1.0;\r\n\t\tcpp_dec_float_100 Dx;\r\n\t\tunsigned int i;\r\n\t\tunsigned int w = 0;\r\n\t\tsize_t k;\r\n\t\tfor (w = 0; w <= 2 * smax; w++)\r\n\t\t{\r\n\t\t\tif (w <= smax)\r\n\t\t\t{\r\n\t\t\t\tP = smax + w;\r\n\t\t\t\tN = smax - w;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tP = smax - (w - smax);\r\n\t\t\t\tN = smax + (w - smax);\r\n\t\t\t}\r\n\t\t\tmi = 0;\r\n\t\t\tk = 0;\r\n\t\t\ti = 0;\r\n\t\t\twhile (i < P)\r\n\t\t\t{\r\n\t\t\t\tDn = ((double)i + 1.0);\r\n\t\t\t\tDx = Dn;\r\n\t\t\t\tX = 1.0;\r\n\t\t\t\tfor (unsigned int j = 0; j < M; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tX = X*((double)j + 1.0);\r\n\t\t\t\t\tW[k] = Dx / X;\r\n\t\t\t\t\tDx = Dx * Dn;\r\n\t\t\t\t\tk++;\r\n\t\t\t\t}\r\n\t\t\t\tmi += M;\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t\ti = 0;\r\n\t\t\twhile (i < N)\r\n\t\t\t{\r\n\t\t\t\tDn = -((double)i + 1.0);\r\n\t\t\t\tDx = Dn;\r\n\t\t\t\tX = 1.0;\r\n\t\t\t\tfor (unsigned int j = 0; j < M; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tX = X*((double)j + 1.0);\r\n\t\t\t\t\tW[k] = Dx / X;\r\n\t\t\t\t\tDx = Dx * Dn;\r\n\t\t\t\t\tk++;\r\n\t\t\t\t}\r\n\t\t\t\tmi += M;\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t\tif (HiMatrix.HIinverse(W, Ai, (int)M))\r\n\t\t\t{\r\n\t\t\t\tk = 0;\r\n\t\t\t\tfor (i = 0; i < M; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (unsigned int j = 0; j < M; j++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tAI[k] = Ai[k].convert_to<double>();\r\n\t\t\t\t\t\tk++;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcopy2Darray(AI, &(A->a[w]), M);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tret = ERR_INVERSEMATRIX;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif(AI != NULL) free(AI);\r\n\tif (W != NULL) free(W);\r\n\tif (Ai != NULL) free(Ai);\r\n\treturn ret;\r\n}\r\n\r\nint Space::initializeSpace(double spaceStep, unsigned int inx, unsigned int iny, unsigned int inz, unsigned int ismax, const char *matrixFile)\r\n{\r\n\tint ret = ERR_OK;\r\n\tds = spaceStep;\r\n\tnx = inx; ny = iny; nz = inz;\r\n\tnx1 = inx+1; ny1 = iny+1; nz1 = inz+1;\r\n\tsmax = ismax;\r\n\tM = 2 * smax;\r\n\tif (ds <= 0.0 || nx == 0 || ny == 0 || nz == 0 || smax == 0)\r\n\t{\r\n\t\tret = ERR_INVALID_PARAM;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif (matrixFile != NULL && fileexists(matrixFile))\r\n\t\t{\r\n\t\t\tA = LoadEstimationMatrixesFromFile(matrixFile, M, &ret);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tret = generateMatrix();\r\n\t\t}\r\n\t}\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tcellCount = (nx + 1)*(ny + 1)*(nz + 1);\r\n\t\tfieldMemorySize = cellCount*sizeof(Point3Dstruct);\r\n\t}\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tcurlH = new Curl();\r\n\t\tret = curlH->initialize(this);\r\n\t\tif (ret == ERR_OK)\r\n\t\t{\r\n\t\t\tcurlE = new Curl();\r\n\t\t\tret = curlE->initialize(this);\r\n\t\t\tif (ret == ERR_OK)\r\n\t\t\t{\r\n\t\t\t\t//hard coded here as default\r\n\t\t\t\tsetCalculationMethod(ByFastMethodFirstOrder);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n////////3 functions for dFx/dx,dy,dz/////////////////////////////////////\r\ndouble Space::dx_Fx(Point3Dstruct *F, unsigned int h, unsigned int i, unsigned int j, unsigned int k)\r\n{\r\n\tdouble d = 0.0;\r\n\tunsigned int P, N;\r\n\tunsigned int m;\r\n\tsize_t w0 = Idx(i, j, k);\r\n\tint w = smax - i;\r\n\tif (w > 0) //near or at the lower boundary: w=1,2,...,smax; i=smax-1, smax-2,...,0\r\n\t{\r\n\t\tP = smax + w;\r\n\t\tN = smax - w;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tw = i + smax - nx;\r\n\t\tif (w > 0) //near or at the upper boundary: w=1,2,...,smax; i=nx-smax+1, nx-smax+2,...,nx\r\n\t\t{\r\n\t\t\tP = smax - w;\r\n\t\t\tN = smax + w;\r\n\t\t\tw = w + smax; //index into the array\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tP = smax;\r\n\t\t\tN = smax;\r\n\t\t\tw = 0;\r\n\t\t}\r\n\t}\r\n\t//\r\n\th = h - 1;\r\n\tfor (m = 1; m <= P; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[m - 1] * (F[Idx(i + m,j,k)].x - F[w0].x);\r\n\t}\r\n\tfor (m = 1; m <= N; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[P + m - 1] * (F[Idx(i - m,j,k)].x - F[w0].x);\r\n\t}\r\n\treturn d;\r\n}\r\n\r\ndouble Space::dy_Fx(Point3Dstruct *F, unsigned int h, unsigned int i, unsigned int j, unsigned int k)\r\n{\r\n\tdouble d = 0.0;\r\n\tunsigned int P, N;\r\n\tunsigned int m;\r\n\tsize_t w0 = Idx(i, j, k);\r\n\tint w = smax - j;\r\n\tif (w > 0)\r\n\t{\r\n\t\tP = smax + w;\r\n\t\tN = smax - w;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tw = j + smax - ny;\r\n\t\tif (w > 0)\r\n\t\t{\r\n\t\t\tP = smax - w;\r\n\t\t\tN = smax + w;\r\n\t\t\tw = w + smax;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tP = smax;\r\n\t\t\tN = smax;\r\n\t\t\tw = 0;\r\n\t\t}\r\n\t}\r\n\t//\r\n\th = h - 1;\r\n\tfor (m = 1; m <= P; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[m - 1] * (F[Idx(i,j + m,k)].x - F[w0].x);\r\n\t}\r\n\tfor (m = 1; m <= N; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[P + m - 1] * (F[Idx(i,j - m,k)].x - F[w0].x);\r\n\t}\r\n\treturn d;\r\n}\r\n\r\ndouble Space::dz_Fx(Point3Dstruct *F, unsigned int h, unsigned int i, unsigned int j, unsigned int k)\r\n{\r\n\tdouble d = 0.0;\r\n\tunsigned int P, N;\r\n\tunsigned int m;\r\n\tsize_t w0 = Idx(i, j, k);\r\n\tint w = smax - k;\r\n\tif (w > 0)\r\n\t{\r\n\t\tP = smax + w;\r\n\t\tN = smax - w;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tw = k + smax - nz;\r\n\t\tif (w > 0)\r\n\t\t{\r\n\t\t\tP = smax - w;\r\n\t\t\tN = smax + w;\r\n\t\t\tw = w + smax;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tP = smax;\r\n\t\t\tN = smax;\r\n\t\t\tw = 0;\r\n\t\t}\r\n\t}\r\n\t//\r\n\th = h - 1;\r\n\tfor (m = 1; m <= P; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[m - 1] * (F[Idx(i,j,k + m)].x - F[w0].x);\r\n\t}\r\n\tfor (m = 1; m <= N; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[P + m - 1] * (F[Idx(i,j,k - m)].x - F[w0].x);\r\n\t}\r\n\treturn d;\r\n}\r\n/////////--end of dFx /dx.dy.dz/////////////////////////////////////////\r\n/////////--start of dFy /dx.dy.dz/////////////////////////////////////////\r\ndouble Space::dx_Fy(Point3Dstruct *F, unsigned int h, unsigned int i, unsigned int j, unsigned int k)\r\n{\r\n\tdouble d = 0.0;\r\n\tunsigned int P, N;\r\n\tunsigned int m;\r\n\tsize_t w0 = Idx(i, j, k);\r\n\tint w = smax - i;\r\n\tif (w > 0)\r\n\t{\r\n\t\tP = smax + w;\r\n\t\tN = smax - w;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tw = i + smax - nx;\r\n\t\tif (w > 0)\r\n\t\t{\r\n\t\t\tP = smax - w;\r\n\t\t\tN = smax + w;\r\n\t\t\tw = w + smax;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tP = smax;\r\n\t\t\tN = smax;\r\n\t\t\tw = 0;\r\n\t\t}\r\n\t}\r\n\t//\r\n\th = h - 1;\r\n\tfor (m = 1; m <= P; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[m - 1] * (F[Idx(i + m,j,k)].y - F[w0].y);\r\n\t}\r\n\tfor (m = 1; m <= N; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[P + m - 1] * (F[Idx(i - m,j,k)].y - F[w0].y);\r\n\t}\r\n\treturn d;\r\n}\r\n\r\ndouble Space::dy_Fy(Point3Dstruct *F, unsigned int h, unsigned int i, unsigned int j, unsigned int k)\r\n{\r\n\tdouble d = 0.0;\r\n\tunsigned int P, N;\r\n\tunsigned int m;\r\n\tsize_t w0 = Idx(i, j, k);\r\n\tint w = smax - j;\r\n\tif (w > 0)\r\n\t{\r\n\t\tP = smax + w;\r\n\t\tN = smax - w;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tw = j + smax - ny;\r\n\t\tif (w > 0)\r\n\t\t{\r\n\t\t\tP = smax - w;\r\n\t\t\tN = smax + w;\r\n\t\t\tw = w + smax;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tP = smax;\r\n\t\t\tN = smax;\r\n\t\t\tw = 0;\r\n\t\t}\r\n\t}\r\n\t//\r\n\th = h - 1;\r\n\tfor (m = 1; m <= P; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[m - 1] * (F[Idx(i,j + m,k)].y - F[w0].y);\r\n\t}\r\n\tfor (m = 1; m <= N; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[P + m - 1] * (F[Idx(i,j - m,k)].y - F[w0].y);\r\n\t}\r\n\treturn d;\r\n}\r\n\r\ndouble Space::dz_Fy(Point3Dstruct *F, unsigned int h, unsigned int i, unsigned int j, unsigned int k)\r\n{\r\n\tdouble d = 0.0;\r\n\tunsigned int P, N;\r\n\tunsigned int m;\r\n\tsize_t w0 = Idx(i, j, k);\r\n\tint w = smax - k;\r\n\tif (w > 0)\r\n\t{\r\n\t\tP = smax + w;\r\n\t\tN = smax - w;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tw = k + smax - nz;\r\n\t\tif (w > 0)\r\n\t\t{\r\n\t\t\tP = smax - w;\r\n\t\t\tN = smax + w;\r\n\t\t\tw = w + smax;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tP = smax;\r\n\t\t\tN = smax;\r\n\t\t\tw = 0;\r\n\t\t}\r\n\t}\r\n\t//\r\n\th = h - 1;\r\n\tfor (m = 1; m <= P; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[m - 1] * (F[Idx(i,j,k + m)].y - F[w0].y);\r\n\t}\r\n\tfor (m = 1; m <= N; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[P + m - 1] * (F[Idx(i,j,k - m)].y - F[w0].y);\r\n\t}\r\n\treturn d;\r\n}\r\n/////////--end of dFy /dx.dy.dz/////////////////////////////////////////\r\n/////////--start of dFz /dx.dy.dz/////////////////////////////////////////\r\ndouble Space::dx_Fz(Point3Dstruct *F, unsigned int h, unsigned int i, unsigned int j, unsigned int k)\r\n{\r\n\tdouble d = 0.0;\r\n\tunsigned int P, N;\r\n\tunsigned int m;\r\n\tsize_t w0 = Idx(i, j, k);\r\n\tint w = smax - i;\r\n\tif (w > 0)\r\n\t{\r\n\t\tP = smax + w;\r\n\t\tN = smax - w;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tw = i + smax - nx;\r\n\t\tif (w > 0)\r\n\t\t{\r\n\t\t\tP = smax - w;\r\n\t\t\tN = smax + w;\r\n\t\t\tw = w + smax;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tP = smax;\r\n\t\t\tN = smax;\r\n\t\t\tw = 0;\r\n\t\t}\r\n\t}\r\n\t//\r\n\th = h - 1;\r\n\tfor (m = 1; m <= P; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[m - 1] * (F[Idx(i + m,j,k)].z - F[w0].z);\r\n\t}\r\n\tfor (m = 1; m <= N; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[P + m - 1] * (F[Idx(i - m,j,k)].z - F[w0].z);\r\n\t}\r\n\treturn d;\r\n}\r\n\r\ndouble Space::dy_Fz(Point3Dstruct *F, unsigned int h, unsigned int i, unsigned int j, unsigned int k)\r\n{\r\n\tdouble d = 0.0;\r\n\tunsigned int P, N;\r\n\tunsigned int m;\r\n\tsize_t w0 = Idx(i, j, k);\r\n\tint w = smax - j;\r\n\tif (w > 0)\r\n\t{\r\n\t\tP = smax + w;\r\n\t\tN = smax - w;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tw = j + smax - ny;\r\n\t\tif (w > 0)\r\n\t\t{\r\n\t\t\tP = smax - w;\r\n\t\t\tN = smax + w;\r\n\t\t\tw = w + smax;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tP = smax;\r\n\t\t\tN = smax;\r\n\t\t\tw = 0;\r\n\t\t}\r\n\t}\r\n\t//\r\n\th = h - 1;\r\n\tfor (m = 1; m <= P; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[m - 1] * (F[Idx(i,j + m,k)].z - F[w0].z);\r\n\t}\r\n\tfor (m = 1; m <= N; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[P + m - 1] * (F[Idx(i,j - m,k)].z - F[w0].z);\r\n\t}\r\n\treturn d;\r\n}\r\n\r\ndouble Space::dz_Fz(Point3Dstruct *F, unsigned int h, unsigned int i, unsigned int j, unsigned int k)\r\n{\r\n\tdouble d = 0.0;\r\n\tunsigned int P, N;\r\n\tunsigned int m;\r\n\tsize_t w0 = Idx(i, j, k);\r\n\tint w = smax - k;\r\n\tif (w > 0)\r\n\t{\r\n\t\tP = smax + w;\r\n\t\tN = smax - w;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tw = k + smax - nz;\r\n\t\tif (w > 0)\r\n\t\t{\r\n\t\t\tP = smax - w;\r\n\t\t\tN = smax + w;\r\n\t\t\tw = w + smax;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tP = smax;\r\n\t\t\tN = smax;\r\n\t\t\tw = 0;\r\n\t\t}\r\n\t}\r\n\t//\r\n\th = h - 1;\r\n\tfor (m = 1; m <= P; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[m - 1] * (F[Idx(i,j,k + m)].z - F[w0].z);\r\n\t}\r\n\tfor (m = 1; m <= N; m++)\r\n\t{\r\n\t\td += A->a[w].r[h].c[P + m - 1] * (F[Idx(i,j,k - m)].z - F[w0].z);\r\n\t}\r\n\treturn d;\r\n}\r\n/////////--end of dFz /dx.dy.dz/////////////////////////////////////////\r\n\r\nvoid Space::SetFields(Point3Dstruct *fh, Point3Dstruct *fe)\r\n{\r\n\tcurlH->SetField(fh);\r\n\tcurlE->SetField(fe);\r\n}\r\n\r\nint Space::CalculateNextCurlH(Point3Dstruct *pNext)\r\n{\r\n\treturn curlH->CalculateCurl(pNext);\r\n}\r\n\r\nint Space::CalculateNextCurlE(Point3Dstruct *pNext)\r\n{\r\n\treturn curlE->CalculateCurl(pNext);\r\n}\r\n\r\nPoint3Dstruct *Space::GetCurrentCurlH()\r\n{\r\n\treturn curlH->GetCurrentCurl();\r\n}\r\n\r\nPoint3Dstruct *Space::GetCurrentCurlE()\r\n{\r\n\treturn curlE->GetCurrentCurl();\r\n}\r\n\r\nint Space::writeMatrixesToFile(char *file)\r\n{\r\n\tint ret = ERR_OK;\r\n\tFILE *retFileHandle = 0;\r\n\tret = deleteFile(file);\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tret = openTextfileWrite(file, &retFileHandle);\r\n\t\tif (ret == ERR_OK)\r\n\t\t{\r\n\t\t\tif (retFileHandle == 0)\r\n\t\t\t{\r\n\t\t\t\tret = ERR_FILE_OPEN_WRIT_EINVAL;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tunsigned int size = 1024;\r\n\t\t\t\tchar buff[1024];\r\n\t\t\t\tArray3Dstruct *A = GetMaxtrixes(); //1+2smax,2smax,2smax\r\n\t\t\t\tsprintf_1(buff, size, \"smax=%u, space estiation order = 2*smax = %u\\r\\n\", smax, 2 * smax);\r\n\t\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t\t\tfor (unsigned int h = 0; h < 2 * smax + 1; h++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (h == 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsprintf_1(buff, size, \"\\r\\nestimation matrix for spaces inside the boundary [%u x %u]=\\n\", 2 * smax, 2 * smax);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (h <= smax)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsprintf_1(buff, size, \"\\r\\nestimation matrix for spaces near or at the lower boundary [%u x %u]=\\n\", 2 * smax, 2 * smax);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsprintf_1(buff, size, \"\\r\\nestimation matrix for spaces near or at the upper boundary [%u x %u]=\\n\", 2 * smax, 2 * smax);\r\n\t\t\t\t\t}\r\n\t\t\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t\t\t\t//\r\n\t\t\t\t\tfor (unsigned int i = 0; i < 2 * smax; i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (unsigned int j = 0; j < 2 * smax; j++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (j == 2 * smax - 1)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tsprintf_1(buff, size, \"%g\\n\", A->a[h].r[i].c[j]);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tsprintf_1(buff, size, \"%g,\\t\", A->a[h].r[i].c[j]);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\twritefile(retFileHandle, buff, (unsigned int)strnlen_0(buff, size));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tclosefile(retFileHandle);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nint Space::saveMaxtrixToFile(char *file)\r\n{\r\n\tint ret = ERR_OK;\r\n\tFILE *fh = 0;\r\n\tsize_t w;\r\n\tsize_t size = (M + 1)*M*M*sizeof(double);\r\n\tdouble *data = (double *)malloc(size);\r\n\tif (data == NULL)\r\n\t{\r\n\t\tret = ERR_OUTOFMEMORY;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tw = 0;\r\n\t\tfor (unsigned int h = 0; h <= M; h++)\r\n\t\t{\r\n\t\t\tfor (unsigned int i = 0; i < M; i++)\r\n\t\t\t{\r\n\t\t\t\tfor (unsigned int j = 0; j < M; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tdata[w] = A->a[h].r[i].c[j];\r\n\t\t\t\t\tw++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tret = openfileWrite(file, &fh);\r\n\t\tif (ret == ERR_OK)\r\n\t\t{\r\n\t\t\tret = writefile(fh, data, (unsigned int)size);\r\n\t\t\tclosefile(fh);\r\n\t\t}\r\n\t\tfree(data);\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n//int Space::loadMaxtrixFromFile(const char *file)\r\nArray3Dstruct *Space::LoadEstimationMatrixesFromFile(const char *file, unsigned int M, int *ret)\r\n{\r\n\t*ret = ERR_OK;\r\n\tFILE *fh = 0;\r\n\tArray3Dstruct *A = NULL;\r\n\tsize_t w;\r\n\tsize_t size = (M + 1)*M*M*sizeof(double);\r\n\tdouble *data = (double *)malloc(size);\r\n\tif (data == NULL)\r\n\t{\r\n\t\t*ret = ERR_OUTOFMEMORY;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tsize_t fsize = fileSize(file);\r\n\t\tif (fsize != size)\r\n\t\t{\r\n\t\t\t*ret = ERR_INVALID_SIZE;\r\n\t\t}\r\n\t}\r\n\tif (*ret == ERR_OK)\r\n\t{\r\n\t\t*ret = openfileRead(file, &fh);\r\n\t\tif (*ret == ERR_OK)\r\n\t\t{\r\n\t\t\t*ret = readfile(fh, data, (unsigned int)size);\r\n\t\t\tclosefile(fh);\r\n\t\t}\r\n\t}\r\n\tif (*ret == ERR_OK)\r\n\t{\r\n\t\tA = tss_allocate3Darray(M + 1, M, M);\r\n\t\tif (A == NULL)\r\n\t\t{\r\n\t\t\t*ret = ERR_OUTOFMEMORY;\r\n\t\t}\r\n\t}\r\n\tif (*ret == ERR_OK)\r\n\t{\r\n\t\tw = 0;\r\n\t\tfor (unsigned int h = 0; h <= M; h++)\r\n\t\t{\r\n\t\t\tfor (unsigned int i = 0; i < M; i++)\r\n\t\t\t{\r\n\t\t\t\tfor (unsigned int j = 0; j < M; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tA->a[h].r[i].c[j] = data[w];\r\n\t\t\t\t\tw++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (data != NULL)\r\n\t\tfree(data);\r\n\treturn A;\r\n}\r\n\r\nint Space::CreateMatrixFile(unsigned int smax0, char *file)\r\n{\r\n\tint ret = ERR_OK;\r\n\tsmax = smax0;\r\n\tM = 2 * smax;\r\n\tret = generateMatrix();\r\n\tif (ret == ERR_OK)\r\n\t{\r\n\t\tret = saveMaxtrixToFile(file);\r\n\t}\r\n\treturn ret;\r\n}\r\n", "meta": {"hexsha": "f595ffabea9ebf01a0f2be258f5d2158f2c0faa7", "size": 14890, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source Code V2/Tss/Space.cpp", "max_stars_repo_name": "DavidGeUSA/TSS", "max_stars_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-09-27T07:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T11:01:31.000Z", "max_issues_repo_path": "Source Code V2/Tss/Space.cpp", "max_issues_repo_name": "DavidGeUSA/TSS", "max_issues_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-28T13:14:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-28T21:04:44.000Z", "max_forks_repo_path": "Source Code V2/Tss/Space.cpp", "max_forks_repo_name": "DavidGeUSA/TSS", "max_forks_repo_head_hexsha": "e364e324948c68efc6362a0db3aa51696227fa60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T07:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T13:53:21.000Z", "avg_line_length": 19.3376623377, "max_line_length": 143, "alphanum_fraction": 0.4675621222, "num_tokens": 5596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.6959583124210895, "lm_q1q2_score": 0.6071174021066466}}
{"text": "// Basic sanity check that header <boost/math/special_functions/ellint_1.hpp>\n// #includes all the files that it needs to.\n//\n#include <boost/math/special_functions/jacobi_theta.hpp>\n//\n// Note this header includes no other headers, this is\n// important if this test is to be meaningful:\n//\n#include \"test_compile_result.hpp\"\n\nvoid compile_and_link_test()\n{\n    // Q parameter\n   check_result<float>(boost::math::jacobi_theta1<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta1<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta1<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_theta2<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta2<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta2<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_theta3<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta3<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta3<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_theta4<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta4<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta4<long double>(l, l));\n#endif\n\n    // Tau parameter\n   check_result<float>(boost::math::jacobi_theta1tau<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta1tau<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta1tau<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_theta2tau<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta2tau<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta2tau<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_theta3tau<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta3tau<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta3tau<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_theta4tau<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta4tau<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta4tau<long double>(l, l));\n#endif\n\n   // Minus 1 flavors\n   check_result<float>(boost::math::jacobi_theta3m1<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta3m1<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta3m1<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_theta4m1<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta4m1<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta4m1<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_theta3m1tau<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta3m1tau<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta3m1tau<long double>(l, l));\n#endif\n\n   check_result<float>(boost::math::jacobi_theta4m1tau<float>(f, f));\n   check_result<double>(boost::math::jacobi_theta4m1tau<double>(d, d));\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n   check_result<long double>(boost::math::jacobi_theta4m1tau<long double>(l, l));\n#endif\n}\n", "meta": {"hexsha": "119b03eafc829f2ec77c840c9ab8ad2585d24a36", "size": 3691, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/test/compile_test/sf_jacobi_theta_incl_test.cpp", "max_stars_repo_name": "anarthal/boost-unix-mirror", "max_stars_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-12T13:52:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T13:52:18.000Z", "max_issues_repo_path": "libs/math/test/compile_test/sf_jacobi_theta_incl_test.cpp", "max_issues_repo_name": "anarthal/boost-unix-mirror", "max_issues_repo_head_hexsha": "8c34eb2fe471d6c3113c680c1fbef29e7a8063a0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-10-21T12:42:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-03T08:41:31.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/test/compile_test/sf_jacobi_theta_incl_test.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 41.9431818182, "max_line_length": 81, "alphanum_fraction": 0.7583310756, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6071173974872786}}
{"text": "//\n// Created by krab1k on 13.11.18.\n//\n\n#include <cmath>\n#include <Eigen/LU>\n\n#include \"delre.h\"\n#include \"../structures/molecule.h\"\n#include \"../structures/bond.h\"\n#include \"../parameters.h\"\n\nCHARGEFW2_METHOD(DelRe)\n\n\nstd::vector<double> DelRe::calculate_charges(const Molecule &molecule) const {\n\n    const size_t n = molecule.atoms().size();\n    const size_t m = molecule.bonds().size();\n\n    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(n, n);\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(n);\n\n    for (size_t i = 0; i < n; i++) {\n        auto &atom_i = molecule.atoms()[i];\n        b(i) = -parameters_->atom()->parameter(atom::delta)(atom_i);\n        A(i, i) = -1.0;\n    }\n\n    for (const auto &bond: molecule.bonds()) {\n        size_t i = bond.first().index();\n        size_t j = bond.second().index();\n        A(i, j) = parameters_->bond()->parameter(bond::gammaA)(bond);\n        A(j, i) = parameters_->bond()->parameter(bond::gammaB)(bond);\n    }\n\n    Eigen::VectorXd d = A.partialPivLu().solve(b);\n    std::vector<double> q(n, 0);\n\n    for (size_t k = 0; k < m; k++) {\n        const auto &bond = molecule.bonds()[k];\n        size_t i = bond.first().index();\n        size_t j = bond.second().index();\n        double dq = (d(i) - d(j)) / (2 * parameters_->bond()->parameter(bond::eps)(bond));\n        q[i] -= dq;\n        q[j] += dq;\n    }\n\n    return q;\n}\n", "meta": {"hexsha": "68ddd4dd41eac698cb2103c7b191fe978409e2b0", "size": 1362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/delre.cpp", "max_stars_repo_name": "danny305/ChargeFW2", "max_stars_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T15:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:38:09.000Z", "max_issues_repo_path": "src/methods/delre.cpp", "max_issues_repo_name": "danny305/ChargeFW2", "max_issues_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-03-04T21:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T07:11:19.000Z", "max_forks_repo_path": "src/methods/delre.cpp", "max_forks_repo_name": "danny305/ChargeFW2", "max_forks_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T00:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T05:47:39.000Z", "avg_line_length": 26.7058823529, "max_line_length": 90, "alphanum_fraction": 0.5660792952, "num_tokens": 395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.6584175139669997, "lm_q1q2_score": 0.6070094854020699}}
{"text": "//============================================================================\n// Name        : polynomfit.cpp\n// Author      :\n// Version     :\n// Copyright   : Your copyright notice\n// Description : Hello World in C, Ansi-style\n//============================================================================\n\n//#include <stdio.h>\n//#include <stdlib.h>\n#include <Eigen/Dense>\n#include \"include/treepoly_smooth.hh\"\n#include <random>\n\n#include <iostream>\n\nusing namespace std;\n\nint main(void) {\n//\tputs(\"Hello World!!!\");\n//\treturn EXIT_SUCCESS;\n\n\tcout << \"Hello world\" << endl;\n\tEigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic > m_eigen_matrix;\n\tm_eigen_matrix.resize(2,2);\n\n\tm_eigen_matrix << 1, 2,\n\t\t\t\t\t3,4;\n\tcout << m_eigen_matrix << endl;\n\n\n\tstd::vector<std::vector<double> > data(10000, std::vector<double>(2,0.0) );\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\n\tstd::normal_distribution<> d(0,1);\n\tstd::uniform_int_distribution<> distrib(1, 6);\n\tfor(int i = 0; i!= data.size(); i++) {\n\t\tconst double x =  distrib(gen) + d(gen);\n\t\tconst double y = -0.1*x*x*x + 0.7*x*x + 0.01*x + 0.5 + d(gen);\n\t\tdata[i][0] = x;\n\t\tdata[i][1] = y;\n\t}\n\n\tint n_levels = 5, n_input_vars =1;\n\n\ttreepoly_smooth<long double> tree_poly(n_input_vars,n_levels);\n\ttree_poly.reserve(data.size());\n\n\tfor(int i=0; i!= data.size(); i++) {\n\t\t//cout<< i << data[i][0] << \" \" << data[i][1] << endl;\n\t\tstd::vector<double> xv(1);\n\n\t\txv[0] = data[i][0];\n\t\ttree_poly.fill_1dim(data[i][0], data[i][1], 1.0);\n\t}\n\ttree_poly.train();\n\n\tfor(double x=0; x< 1.0; x+=0.1) {\n\t\tdouble y = (-0.1*x*x*x + 0.7*x*x + 0.01*x + 0.5);\n\t\tstd::vector<long double> xv(1);\n\t\txv[0] = x;\n\t\tcout << \"p(\"<<x<<\")=\" << tree_poly.eval(xv) << \" vs \" << y << endl;\n\t}\n\n\t//polynom.print(\"10 degree fit\");\n\n\n\n}\n", "meta": {"hexsha": "02d6a5ed2747660c7f0c9b9842c2e9b89144b02d", "size": 1754, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "smoothed-tree-polynomial.cpp", "max_stars_repo_name": "freemeson/multinomial", "max_stars_repo_head_hexsha": "9bf1913a0e6d24ac40f219d44f757393decd1ad6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "smoothed-tree-polynomial.cpp", "max_issues_repo_name": "freemeson/multinomial", "max_issues_repo_head_hexsha": "9bf1913a0e6d24ac40f219d44f757393decd1ad6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smoothed-tree-polynomial.cpp", "max_forks_repo_name": "freemeson/multinomial", "max_forks_repo_head_hexsha": "9bf1913a0e6d24ac40f219d44f757393decd1ad6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7042253521, "max_line_length": 78, "alphanum_fraction": 0.5438996579, "num_tokens": 542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6069052759549941}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <limits>\n#include <vector>\n\nnamespace collision2d {\ntemplate <typename N>\nusing Point = Eigen::Matrix<N, 2, 1>;\n\ntemplate <typename N>\nusing Polygon = std::vector<Point<N>>;\n\n/**\n * Computes potential separating axes for a convex polygon.\n */\ntemplate <typename N>\nvoid separatingAxes(const Polygon<N> &a, std::vector<Point<N>> &axes) {\n  for (auto i = 0u; i < a.size(); ++i) {\n    const auto current = a[i];\n    const auto next = a[(i + 1) % a.size()];\n    const auto edge = (next - current).normalized();\n    // axis is the normal of an edge\n    axes.emplace_back(Point<N>{-edge[1], edge[0]});\n  }\n}\n\n/**\n * Projects the polygon onto the given axis and returns the maximum and minimum\n * coordinate on the axis. Note that the axis has to be normalized.\n */\ntemplate <typename N>\nvoid project(const Polygon<N> &a, const Point<N> &axis, N &minProj,\n             N &maxProj) {\n  maxProj = -std::numeric_limits<N>::infinity();\n  minProj = std::numeric_limits<N>::infinity();\n  for (const Point<N> &v : a) {\n    const N proj = axis.dot(v);\n    if (proj < minProj) minProj = proj;\n    if (proj > maxProj) maxProj = proj;\n  }\n}\n\n/**\n * Check for collision between polygons a and b via the Separating Axis Theorem.\n */\ntemplate <typename N>\nbool intersect(const Polygon<N> &a, const Polygon<N> &b) {\n  // compute separating axes\n  std::vector<Point<N>> axes;\n  separatingAxes(a, axes);\n  separatingAxes(b, axes);\n  for (const auto &axis : axes) {\n    N aMaxProj, aMinProj, bMaxProj, bMinProj;\n    project(a, axis, aMinProj, aMaxProj);\n    project(b, axis, bMinProj, bMaxProj);\n    // check if projections overlap\n    if (aMinProj > bMaxProj || bMinProj > aMaxProj) return false;\n  }\n\n  return true;\n}\n\n// /**\n//  * Efficient test for a point to be in a convex polygon.\n//  *\n//  * Robert Nowak \"An Efficient Test for a Point to Be in a Convex Polygon\"\n//  * http://demonstrations.wolfram.com/AnEfficientTestForAPointToBeInAConvexPolygon/\n//  * Wolfram Demonstrations Project\n//  * Published: March 7 2011\n//  */\n// template <typename N>\n// bool intersect2(const Point<N> &point, const Polygon<N> &polygon,\n//                 const N &epsilon = 1e-4) {\n//   bool angle = false;  // stores the sign of the last angle\n//   for (auto i = 0u; i < polygon.size(); ++i) {\n//     const auto &a = polygon[i] - point;\n//     const auto &b = polygon[(i + 1) % polygon.size()] - point;\n//     const bool newAngle = b(0) * a(1) - a(0) * b(1) > -epsilon;\n//     if (i > 0 && angle != newAngle) return false;\n//     angle = newAngle;\n//   }\n//   return true;\n// }\n\n/**\n * Tests whether point intersects with convex polygon.\n * Source: https://stackoverflow.com/a/8721483\n */\ntemplate <typename N>\nbool intersect(const Point<N> &point, const Polygon<N> &polygon,\n               const N &epsilon = 1e-4) {\n  bool result = false;\n  std::size_t i, j;\n  for (i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++) {\n    if ((polygon[i].y() > point.y()) != (polygon[j].y() > point.y()) &&\n        (point.x() < (polygon[j].x() - polygon[i].x()) * (point.y() - polygon[i].y()) /\n                          (polygon[j].y() - polygon[i].y() + epsilon) +\n                      polygon[i].x())) {\n      result = !result;\n    }\n  }\n  return result;\n}\n}  // namespace collision2d\n", "meta": {"hexsha": "4d924ccd81b45760c1e5add53a532cc44ef3b8b2", "size": 3294, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sat.hpp", "max_stars_repo_name": "eric-heiden/collision2d", "max_stars_repo_head_hexsha": "b3f273ded24dc96a18008a16aeb483f4945baae3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-08T11:30:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-08T11:30:59.000Z", "max_issues_repo_path": "sat.hpp", "max_issues_repo_name": "eric-heiden/collision2d", "max_issues_repo_head_hexsha": "b3f273ded24dc96a18008a16aeb483f4945baae3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sat.hpp", "max_forks_repo_name": "eric-heiden/collision2d", "max_forks_repo_head_hexsha": "b3f273ded24dc96a18008a16aeb483f4945baae3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T03:22:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T03:22:01.000Z", "avg_line_length": 31.0754716981, "max_line_length": 87, "alphanum_fraction": 0.6117182757, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152498, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6068640380638406}}
{"text": "//==================================================================================================\n/**\n  EVE - Expressive Vector Engine\n  Copyright : EVE Contributors & Maintainers\n  SPDX-License-Identifier: MIT\n**/\n//==================================================================================================\n#include \"test.hpp\"\n#include <eve/function/airy_ai.hpp>\n#include <eve/function/airy_bi.hpp>\n#include <eve/function/airy.hpp>\n#include <eve/function/if_else.hpp>\n#include <eve/function/prev.hpp>\n#include <eve/constant/inf.hpp>\n#include <eve/constant/minf.hpp>\n#include <eve/constant/nan.hpp>\n#include <eve/platform.hpp>\n#include <cmath>\n#include <boost/math/special_functions/airy.hpp>\n\nEVE_TEST_TYPES( \"Check return types of airy_ai\"\n            , eve::test::simd::ieee_reals\n            )\n<typename T>(eve::as<T>)\n{\n  using v_t = eve::element_type_t<T>;\n  using kv_t =  kumi::tuple<v_t, v_t>;\n  using kT =    kumi::tuple<T, T>;\n  TTS_EXPR_IS(eve::airy(T(0)), kT);\n  TTS_EXPR_IS(eve::airy(v_t(0)), kv_t);\n};\n\n EVE_TEST( \"Check behavior of airy on wide\"\n         , eve::test::simd::ieee_reals\n         , eve::test::generate(eve::test::randoms(-20.0, 0.0),\n                               eve::test::randoms(0.0, 20.0)\n                              )\n         )\n   <typename T>(T a0, T a1)\n{\n  using v_t = eve::element_type_t<T>;\n  v_t abstol = 1000*eve::eps(eve::as<v_t>());\n  auto eve_airy =  [](auto x) { return eve::airy(x); };\n  auto std_airy_ai =  [](auto x)->v_t { return eve::airy_ai(x); };\n  auto std_airy_bi =  [](auto x)->v_t { return eve::airy_bi(x); };\n\n  {\n    auto [ai, bi]= eve_airy(a0);\n    TTS_ABSOLUTE_EQUAL(ai, map(std_airy_ai, a0), abstol);\n    TTS_RELATIVE_EQUAL(bi, map(std_airy_bi, a0), 0.0004);\n  }\n  {\n    auto [ai, bi]= eve_airy(a1);\n    TTS_ABSOLUTE_EQUAL(ai, map(std_airy_ai, a1), abstol);\n    TTS_RELATIVE_EQUAL(bi, map(std_airy_bi, a1), 0.0004);\n  }\n\n};\n", "meta": {"hexsha": "a02e071f08f557d86878850ad91baf7792ef5fab", "size": 1901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/unit/module/bessel/airy.cpp", "max_stars_repo_name": "the-moisrex/eve", "max_stars_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 340.0, "max_stars_repo_stars_event_min_datetime": "2020-09-16T21:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:40:33.000Z", "max_issues_repo_path": "test/unit/module/bessel/airy.cpp", "max_issues_repo_name": "the-moisrex/eve", "max_issues_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 383.0, "max_issues_repo_issues_event_min_datetime": "2020-09-17T06:56:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T15:58:53.000Z", "max_forks_repo_path": "test/unit/module/bessel/airy.cpp", "max_forks_repo_name": "the-moisrex/eve", "max_forks_repo_head_hexsha": "80b52663eefee11460abb0aedf4158a5067cf7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-02-27T23:11:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T12:31:29.000Z", "avg_line_length": 32.2203389831, "max_line_length": 100, "alphanum_fraction": 0.5560231457, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6068640250342348}}
{"text": "/*\n * Copyright 2012-2020 CNRS-UM LIRMM, CNRS-AIST JRL\n */\n\n// check memory allocation in some method\n#define EIGEN_RUNTIME_NO_MALLOC\n\n// includes\n// std\n#include <iostream>\n\n// boost\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE PTransformd test\n#include <boost/math/constants/constants.hpp>\n#include <boost/test/unit_test.hpp>\n\n// SpaceVecAlg\n#include <SpaceVecAlg/SpaceVecAlg>\n\ntypedef Eigen::Matrix<double, 6, Eigen::Dynamic> Matrix6Xd;\n\nconst double TOL = 0.00001;\n\nbool isUpperNull(const Eigen::Matrix3d & m)\n{\n  using namespace Eigen;\n  return (Matrix3d(m.triangularView<StrictlyUpper>()).array() == 0.).all();\n}\n\nBOOST_AUTO_TEST_CASE(RotationMatrixTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n\n  Vector2d theta2d = Vector2d::Random() * 10;\n  double theta = theta2d(0);\n\n  BOOST_CHECK_SMALL((RotX(theta) - AngleAxisd(-theta, Vector3d::UnitX()).matrix()).array().abs().sum(), TOL);\n  BOOST_CHECK_SMALL((RotY(theta) - AngleAxisd(-theta, Vector3d::UnitY()).matrix()).array().abs().sum(), TOL);\n  BOOST_CHECK_SMALL((RotZ(theta) - AngleAxisd(-theta, Vector3d::UnitZ()).matrix()).array().abs().sum(), TOL);\n}\n\nBOOST_AUTO_TEST_CASE(PTransformdTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  namespace constants = boost::math::constants;\n\n  Matrix3d Em = AngleAxisd(constants::pi<double>() / 2., Vector3d(1., 0., 0.)).inverse().toRotationMatrix();\n  Quaterniond Eq;\n  Eq = AngleAxisd(constants::pi<double>() / 2., Vector3d(1., 0., 0.)).inverse();\n  Vector3d r = Vector3d::Random() * 100.;\n\n  // Identity\n  PTransformd pt1 = PTransformd::Identity();\n\n  BOOST_CHECK_EQUAL(pt1.rotation(), Matrix3d::Identity());\n  BOOST_CHECK_EQUAL(pt1.translation(), Vector3d::Zero());\n\n  // Matrix3d Vector3d constructor\n  PTransformd pt2(Em, r);\n\n  BOOST_CHECK_EQUAL(pt2.rotation(), Em);\n  BOOST_CHECK_EQUAL(pt2.translation(), r);\n\n  // Quaternion Vector3d constructor\n  PTransformd pt3(Eq, r);\n\n  BOOST_CHECK_EQUAL(pt3.rotation(), Eq.toRotationMatrix());\n  BOOST_CHECK_EQUAL(pt3.translation(), r);\n\n  // Quaternion constructor\n  PTransformd pt4(Eq);\n\n  BOOST_CHECK_EQUAL(pt4.rotation(), Eq.toRotationMatrix());\n  BOOST_CHECK_EQUAL(pt4.translation(), Vector3d::Zero());\n\n  // Matrix3d constructor\n  PTransformd pt5(Em);\n\n  BOOST_CHECK_EQUAL(pt5.rotation(), Em);\n  BOOST_CHECK_EQUAL(pt5.translation(), Vector3d::Zero());\n\n  // Vector3d constructor\n  PTransformd pt6(r);\n\n  BOOST_CHECK_EQUAL(pt6.rotation(), Matrix3d::Identity());\n  BOOST_CHECK_EQUAL(pt6.translation(), r);\n\n  // operator*(PTransformd)\n  PTransformd pttmp(AngleAxisd(constants::pi<double>() / 4., Vector3d(0., 1., 0.)).toRotationMatrix(),\n                    Vector3d::Random() * 100.);\n\n  PTransformd pt7 = pt2 * pttmp;\n  Matrix6d ptm(pt2.matrix() * pttmp.matrix());\n\n  BOOST_CHECK_SMALL((pt7.matrix() - ptm).array().abs().sum(), TOL);\n\n  // inv\n  PTransformd pt8 = pt2.inv();\n  Matrix6d pt8_minus_pt2_inv = pt8.matrix() - pt2.matrix().inverse();\n  BOOST_CHECK_SMALL(pt8_minus_pt2_inv.array().abs().sum(), TOL);\n\n  // ==\n  BOOST_CHECK_EQUAL(pt2, pt2);\n  BOOST_CHECK_NE(pt2, pt8);\n\n  // !=\n  BOOST_CHECK(pt2 != pt8);\n  BOOST_CHECK(!(pt2 != pt2));\n}\n\nBOOST_AUTO_TEST_CASE(PTransformdLeftOperatorsTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  namespace constants = boost::math::constants;\n\n  Quaterniond Eq;\n  Eq = AngleAxisd(constants::pi<double>() / 2., Vector3d(1., 0., 0.));\n  Vector3d r = Vector3d::Random() * 100.;\n  PTransformd pt(Eq, r);\n  PTransformd ptInv = pt.inv();\n  Matrix6d pt6d = pt.matrix();\n  Matrix6d ptInv6d = ptInv.matrix();\n  Matrix6d ptDual6d = pt.dualMatrix();\n\n  Matrix3d M, H, I;\n  M << 1., 2., 3., 2., 1., 4., 3., 4., 1.;\n  H = Matrix3d::Random() * 100.;\n  I << 1., 2., 3., 2., 1., 4., 3., 4., 1.;\n\n  ABInertiad ab(M, H, I);\n  Matrix6d ab6d = ab.matrix();\n\n  double mass = 1.;\n  Vector3d h = Vector3d::Random() * 100.;\n  RBInertiad rb(mass, h, I);\n  Matrix6d rb6d = rb.matrix();\n\n  Vector3d w, v, n, f;\n  w = Vector3d::Random() * 100.;\n  v = Vector3d::Random() * 100.;\n  n = Vector3d::Random() * 100.;\n  f = Vector3d::Random() * 100.;\n\n  sva::MotionVecd mVec(w, v);\n  Vector6d mVec6d = mVec.vector();\n\n  sva::ForceVecd fVec(n, f);\n  Vector6d fVec6d = fVec.vector();\n\n  // PTransformd * MotionVecd\n  MotionVecd mvRes1 = pt * mVec;\n  Vector6d mvRes16d(pt6d * mVec6d);\n\n  BOOST_CHECK_SMALL((mvRes1.vector() - mvRes16d).array().abs().sum(), TOL);\n\n  // test the angular and linear version\n  BOOST_CHECK_SMALL((mvRes1.angular() - pt.angularMul(mVec)).array().abs().sum(), TOL);\n  BOOST_CHECK_SMALL((mvRes1.linear() - pt.linearMul(mVec)).array().abs().sum(), TOL);\n\n  // test the vectorized version\n  Matrix6Xd mv1Vec6Xd(6, 2);\n  Matrix6Xd mvRes1Vec6Xd(6, 2);\n  mv1Vec6Xd << mVec.vector(), mVec.vector();\n\n  Eigen::internal::set_is_malloc_allowed(false);\n  pt.mul(mv1Vec6Xd, mvRes1Vec6Xd);\n  Eigen::internal::set_is_malloc_allowed(true);\n\n  BOOST_CHECK_SMALL((mvRes1.vector() - mvRes1Vec6Xd.col(0)).norm(), TOL);\n  BOOST_CHECK_EQUAL(mvRes1Vec6Xd.col(0), mvRes1Vec6Xd.col(1));\n\n  // PTransformd^-1 * MotionVecd\n  MotionVecd mvRes2 = pt.invMul(mVec);\n  Vector6d mvRes26d(ptInv6d * mVec6d);\n\n  BOOST_CHECK_SMALL((mvRes2.vector() - mvRes26d).array().abs().sum(), TOL);\n\n  // test the angular and linear version\n  BOOST_CHECK_SMALL((mvRes2.angular() - pt.angularInvMul(mVec)).array().abs().sum(), TOL);\n  BOOST_CHECK_SMALL((mvRes2.linear() - pt.linearInvMul(mVec)).array().abs().sum(), TOL);\n\n  // test the vectorized version\n  Matrix6Xd mv2Vec6Xd(6, 2);\n  Matrix6Xd mvRes2Vec6Xd(6, 2);\n  mv2Vec6Xd << mVec.vector(), mVec.vector();\n\n  Eigen::internal::set_is_malloc_allowed(false);\n  pt.invMul(mv2Vec6Xd, mvRes2Vec6Xd);\n  Eigen::internal::set_is_malloc_allowed(true);\n\n  BOOST_CHECK_SMALL((mvRes2.vector() - mvRes2Vec6Xd.col(0)).norm(), TOL);\n  BOOST_CHECK_EQUAL(mvRes2Vec6Xd.col(0), mvRes2Vec6Xd.col(1));\n\n  // PTransformd* * ForceVecd\n  ForceVecd fvRes1 = pt.dualMul(fVec);\n  Vector6d fvRes16d(ptDual6d * fVec6d);\n\n  BOOST_CHECK_SMALL((fvRes1.vector() - fvRes16d).array().abs().sum(), TOL);\n\n  // test the couple and force version\n  BOOST_CHECK_SMALL((fvRes1.couple() - pt.coupleDualMul(fVec)).array().abs().sum(), TOL);\n  BOOST_CHECK_SMALL((fvRes1.force() - pt.forceDualMul(fVec)).array().abs().sum(), TOL);\n\n  // test the vectorized version\n  Matrix6Xd fv1Vec6Xd(6, 2);\n  Matrix6Xd fvRes1Vec6Xd(6, 2);\n  fv1Vec6Xd << fVec.vector(), fVec.vector();\n\n  Eigen::internal::set_is_malloc_allowed(false);\n  pt.dualMul(fv1Vec6Xd, fvRes1Vec6Xd);\n  Eigen::internal::set_is_malloc_allowed(true);\n\n  BOOST_CHECK_SMALL((fvRes1.vector() - fvRes1Vec6Xd.col(0)).norm(), TOL);\n  BOOST_CHECK_EQUAL(fvRes1Vec6Xd.col(0), fvRes1Vec6Xd.col(1));\n\n  // PTransformd T * ForceVecd\n  ForceVecd fvRes2 = pt.transMul(fVec);\n  Vector6d fvRes26d(pt6d.transpose() * fVec6d);\n\n  BOOST_CHECK_SMALL((fvRes2.vector() - fvRes26d).array().abs().sum(), TOL);\n\n  // test the couple and force version\n  BOOST_CHECK_SMALL((fvRes2.couple() - pt.coupleTransMul(fVec)).array().abs().sum(), TOL);\n  BOOST_CHECK_SMALL((fvRes2.force() - pt.forceTransMul(fVec)).array().abs().sum(), TOL);\n\n  // test the vectorized version\n  Matrix6Xd fv2Vec6Xd(6, 2);\n  Matrix6Xd fvRes2Vec6Xd(6, 2);\n  fv2Vec6Xd << fVec.vector(), fVec.vector();\n\n  Eigen::internal::set_is_malloc_allowed(false);\n  pt.transMul(fv2Vec6Xd, fvRes2Vec6Xd);\n  Eigen::internal::set_is_malloc_allowed(true);\n\n  BOOST_CHECK_SMALL((fvRes2.vector() - fvRes2Vec6Xd.col(0)).norm(), TOL);\n  BOOST_CHECK_EQUAL(fvRes2Vec6Xd.col(0), fvRes2Vec6Xd.col(1));\n\n  // PTransformd* * RBInertiad * PTransformd^-1\n  RBInertiad rbRes1 = pt.dualMul(rb);\n  Matrix6d rbRes16d(ptDual6d * rb6d * ptInv6d);\n\n  BOOST_CHECK_SMALL((rbRes1.matrix() - rbRes16d).array().abs().sum(), TOL);\n\n  // PTransformd T * RBInertiad * PTransformd\n  RBInertiad rbRes2 = pt.transMul(rb);\n  Matrix6d rbRes26d(pt6d.transpose() * rb6d * pt6d);\n\n  BOOST_CHECK_SMALL((rbRes2.matrix() - rbRes26d).array().abs().sum(), TOL);\n\n  // PTransformd* * ABInertiad * PTransformd^-1\n  ABInertiad abRes1 = pt.dualMul(ab);\n  Matrix6d abRes16d(ptDual6d * ab6d * ptInv6d);\n\n  BOOST_CHECK_SMALL((abRes1.matrix() - abRes16d).array().abs().sum(), TOL);\n\n  // PTransformd T * ABInertiad * PTransformd\n  ABInertiad abRes2 = pt.transMul(ab);\n  Matrix6d abRes26d(pt6d.transpose() * ab6d * pt6d);\n\n  BOOST_CHECK_SMALL((abRes2.matrix() - abRes26d).array().abs().sum(), TOL);\n}\n\nBOOST_AUTO_TEST_CASE(EulerAngleTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  namespace cst = boost::math::constants;\n\n  Vector3d res;\n\n  res = rotationError<double>(Matrix3d::Identity(), RotX(cst::pi<double>() / 2.));\n  BOOST_CHECK_SMALL((res - Vector3d(cst::pi<double>() / 2., 0., 0.)).norm(), TOL);\n\n  res = rotationError<double>(Matrix3d::Identity(), RotY(cst::pi<double>() / 2.));\n  BOOST_CHECK_SMALL((res - Vector3d(0., cst::pi<double>() / 2., 0.)).norm(), TOL);\n\n  res = rotationError<double>(Matrix3d::Identity(), RotZ(cst::pi<double>() / 2.));\n  BOOST_CHECK_SMALL((res - Vector3d(0., 0., cst::pi<double>() / 2.)).norm(), TOL);\n\n  res = rotationError<double>(RotZ(cst::pi<double>() / 4.), RotZ(cst::pi<double>() / 2.));\n  BOOST_CHECK_SMALL((res - Vector3d(0., 0., cst::pi<double>() / 4.)).norm(), TOL);\n}\n\nBOOST_AUTO_TEST_CASE(InterpolateTest)\n{\n  using namespace Eigen;\n  using namespace sva;\n  namespace cst = boost::math::constants;\n\n  PTransformd from(Matrix3d::Identity(), Vector3d(0., 0., 0.));\n  PTransformd to(AngleAxisd(cst::pi<double>(), Vector3d::UnitZ()).toRotationMatrix(), Vector3d(1., 2., -3.));\n\n  PTransformd res = interpolate<double>(from, to, 0.5);\n\n  BOOST_CHECK_SMALL((res.rotation() - AngleAxisd(cst::pi<double>() / 2., Vector3d::UnitZ()).toRotationMatrix()).norm(),\n                    TOL);\n  BOOST_CHECK_SMALL((res.translation() - Vector3d(0.5, 1., -1.5)).norm(), TOL);\n\n  res = interpolate<double>(from, to, 0);\n  BOOST_CHECK_SMALL((res.rotation() - from.rotation()).norm(), TOL);\n  BOOST_CHECK_SMALL((res.translation() - from.translation()).norm(), TOL);\n\n  res = interpolate<double>(from, to, 1);\n  BOOST_CHECK_SMALL((res.rotation() - to.rotation()).norm(), TOL);\n  BOOST_CHECK_SMALL((res.translation() - to.translation()).norm(), TOL);\n}\n\nBOOST_AUTO_TEST_CASE(TransformError)\n{\n  using namespace Eigen;\n  using namespace sva;\n  namespace cst = boost::math::constants;\n\n  PTransformd X_a_b(Quaterniond(Vector4d::Random()).normalized(), Vector3d::Random());\n  PTransformd X_a_c(Quaterniond(Vector4d::Random()).normalized(), Vector3d::Random());\n\n  MotionVecd V_a_b = transformVelocity(X_a_b);\n  MotionVecd V_a_c = transformVelocity(X_a_c);\n\n  BOOST_CHECK_SMALL((V_a_b.angular() - rotationVelocity(X_a_b.rotation())).norm(), TOL);\n  BOOST_CHECK_SMALL((V_a_b.linear() - X_a_b.translation()).norm(), TOL);\n  BOOST_CHECK_SMALL((V_a_c.angular() - rotationVelocity(X_a_c.rotation())).norm(), TOL);\n  BOOST_CHECK_SMALL((V_a_c.linear() - X_a_c.translation()).norm(), TOL);\n\n  MotionVecd V_b_c_a = transformError(X_a_b, X_a_c);\n  Vector3d w_b_c_a = rotationError(X_a_b.rotation(), X_a_c.rotation());\n  Vector3d v_b_c_a = X_a_c.translation() - X_a_b.translation();\n\n  BOOST_CHECK_SMALL((V_b_c_a.angular() - w_b_c_a).norm(), TOL);\n  BOOST_CHECK_SMALL((V_b_c_a.linear() - v_b_c_a).norm(), TOL);\n}\n\nBOOST_AUTO_TEST_CASE(sincTest)\n{\n  auto dummy_sinc = [](double x) { return std::sin(x) / x; };\n  double eps = std::numeric_limits<double>::epsilon();\n\n  // test equality between -1 and 1 (avoid 0)\n  double t = -1.;\n  const int nrIter = 333;\n  for(int i = 0; i < nrIter; ++i)\n  {\n    BOOST_CHECK_EQUAL(dummy_sinc(t), sva::sinc(t));\n    t += 2. / nrIter;\n  }\n  BOOST_CHECK(std::isnan(dummy_sinc(0.)));\n  BOOST_CHECK_EQUAL(sva::sinc(0.), 1.);\n\n  // not sure thoses test will work on all architectures\n  BOOST_CHECK_EQUAL(dummy_sinc(eps), sva::sinc(eps));\n  BOOST_CHECK_EQUAL(dummy_sinc(std::sqrt(eps)), sva::sinc(std::sqrt(eps)));\n  BOOST_CHECK_EQUAL(dummy_sinc(std::sqrt(std::sqrt(eps))), sva::sinc(std::sqrt(std::sqrt(eps))));\n}\n\nBOOST_AUTO_TEST_CASE(sinc_invTest)\n{\n  auto dummy_sinc_inv = [](double x) { return x / std::sin(x); };\n  double eps = std::numeric_limits<double>::epsilon();\n\n  // test equality between -1 and 1 (avoid 0)\n  double t = -1.;\n  const int nrIter = 333;\n  for(int i = 0; i < nrIter; ++i)\n  {\n    BOOST_CHECK_EQUAL(dummy_sinc_inv(t), sva::sinc_inv(t));\n    t += 2. / nrIter;\n  }\n  BOOST_CHECK(std::isnan(dummy_sinc_inv(0.)));\n  BOOST_CHECK_EQUAL(sva::sinc_inv(0.), 1.);\n\n  // not sure thoses test will work on all architectures\n  BOOST_CHECK_EQUAL(dummy_sinc_inv(eps), sva::sinc_inv(eps));\n  BOOST_CHECK_EQUAL(dummy_sinc_inv(std::sqrt(eps)), sva::sinc_inv(std::sqrt(eps)));\n  BOOST_CHECK_EQUAL(dummy_sinc_inv(std::sqrt(std::sqrt(eps))), sva::sinc_inv(std::sqrt(std::sqrt(eps))));\n}\n\ntemplate<typename T>\ninline Eigen::Vector3<T> oldRotationVelocity(const Eigen::Matrix3<T> & E_a_b, double prec)\n{\n  Eigen::Vector3<T> w;\n  T acosV = (E_a_b(0, 0) + E_a_b(1, 1) + E_a_b(2, 2) - 1.) * 0.5;\n  T theta = std::acos(acosV);\n\n  if(E_a_b.isIdentity(prec))\n  {\n    w.setZero();\n  }\n  else\n  {\n    w = Eigen::Vector3<T>(-E_a_b(2, 1) + E_a_b(1, 2), -E_a_b(0, 2) + E_a_b(2, 0), -E_a_b(1, 0) + E_a_b(0, 1));\n    w *= theta / (2. * std::sin(theta));\n  }\n\n  return w;\n}\n\nBOOST_AUTO_TEST_CASE(oldVsNewRotationVelocity)\n{\n  using namespace Eigen;\n  using namespace sva;\n\n  Matrix3d r1(RotZ(1.) * RotX(1.5) * RotZ(2.));\n  Matrix3d r2(RotZ(1.043) * RotY(0.3422) * RotX(-0.30943));\n  Matrix3d r3(RotX(-0.8348) * RotY(-0.2344) * RotZ(0.2344));\n  Matrix3d r4(Matrix3d::Identity());\n\n  BOOST_CHECK(oldRotationVelocity(r1, 1e-7).isApprox(rotationVelocity(r1)));\n  BOOST_CHECK(oldRotationVelocity(r2, 1e-7).isApprox(rotationVelocity(r2)));\n  BOOST_CHECK(oldRotationVelocity(r3, 1e-7).isApprox(rotationVelocity(r3)));\n  BOOST_CHECK(oldRotationVelocity(r4, 1e-7).isApprox(rotationVelocity(r4)));\n}\n", "meta": {"hexsha": "9a9469e1c27073e5f9688f265a071780c6c34142", "size": 13744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/PTransformTest.cpp", "max_stars_repo_name": "jrl-umi3218/SpaceVecAlg", "max_stars_repo_head_hexsha": "8284c86464140a08c57d708229677b204ca16208", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2016-10-11T21:00:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T22:30:37.000Z", "max_issues_repo_path": "tests/PTransformTest.cpp", "max_issues_repo_name": "jrl-umi3218/SpaceVecAlg", "max_issues_repo_head_hexsha": "8284c86464140a08c57d708229677b204ca16208", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2016-04-28T09:50:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T05:10:15.000Z", "max_forks_repo_path": "tests/PTransformTest.cpp", "max_forks_repo_name": "jrl-umi3218/SpaceVecAlg", "max_forks_repo_head_hexsha": "8284c86464140a08c57d708229677b204ca16208", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2016-04-28T09:04:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T13:14:15.000Z", "avg_line_length": 33.0384615385, "max_line_length": 119, "alphanum_fraction": 0.6836437718, "num_tokens": 4484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6068640221506469}}
{"text": "#include \"petsc.h\"\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <iostream>\n#include <stdlib.h>\n#include <cassert>\n\n\nnamespace {\n\nusing namespace testing;\n\ntypedef Eigen::SparseMatrix<double, Eigen::RowMajor> EigenMatCSR;\n\nextern \"C\" {\nvoid applicationfunctionfortran_(\n\t\tdouble* lambda,\n\t\tint* mx,\n\t\tint* my,\n\t\tdouble const* x,\n\t\tdouble* f,\n\t\tPetscErrorCode* ierr\n\t);\n\nvoid initialguessfortran_(int* mx, int* my, double* lambda, double* x);\n}\n\nvoid create_petsc_matrix_from_eigen_csr(\n\tEigenMatCSR& mat_csr,\n\tMat& jacobian\n);\n\n\n// Compressed Sparse Row Format\nstruct MatCSR {\n\tEigen::Map<Eigen::ArrayXi> row_pointers;\n\tEigen::Map<Eigen::ArrayXi> column_indices;\n\tEigen::Map<Eigen::ArrayXd> values;\n\n\tMatCSR()\n\t: row_pointers(nullptr, 0)\n\t, column_indices(nullptr, 0)\n\t, values(nullptr, 0)\n\t{}\n};\n\nEigenMatCSR create_laplacian_matrix_1d(int size){\n\tEigenMatCSR mat_csr(size, size);\n\n\tmat_csr.insert(0, 0) = 1;\n\tmat_csr.insert(0, 1) = -1;\n\tfor(int i = 1; i < size-1; ++i){\n\t\tmat_csr.insert(i, i - 1) = -1;\n\t\tmat_csr.insert(i, i) = 2;\n\t\tmat_csr.insert(i, i + 1) = -1;\n\n\t}\n\tmat_csr.insert(size-1, size-1) = 1;\n\tmat_csr.insert(size-1, size-2) = -1;\n\n\tmat_csr.makeCompressed();\n\n\treturn mat_csr;\n}\n\nEigenMatCSR create_laplacian_matrix_2d(int mx, int my){\n\n\tauto N = mx * my;\n\tEigenMatCSR mat_csr(N, N);\n\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\tauto rj = i % mx; // column in grid\n\t\tauto ri = i / mx; // row in grid\n\t\tif (ri != 0) {    // first row does not have neighbor below\n\t\t\tmat_csr.insert(i, i - mx) = 1;\n\t\t}\n\t\tif (ri != my - 1) { // last row does not have neighbors above\n\t\t\tmat_csr.insert(i, i + mx) = 1;\n\t\t}\n\t\tif (rj != 0) {     // first column does not have neighbor to left\n\t\t\tmat_csr.insert(i, i - 1) = 1;\n\t\t}\n\t\tif (rj != mx - 1) {     // last column does not have neighbor to right\n\t\t\tmat_csr.insert(i, i + 1) = 1;\n\t\t}\n\t\tmat_csr.insert(i, i) = 1;\n\t}\n\n\tmat_csr.makeCompressed();\n\n\treturn mat_csr;\n}\n\nTEST(Eigen, Sparse)\n{\n\tint N = 5;\n\tauto mat_csr = create_laplacian_matrix_1d(N);\n\n\tauto expected_nnz = 3 * (N - 2) + 4;\n\n\tauto nnz = mat_csr.nonZeros();\n\tauto row_pointers = mat_csr.outerIndexPtr();\n\tauto column_indices = mat_csr.innerIndexPtr();\n\tauto values = mat_csr.valuePtr();\n\n\tASSERT_TRUE(nnz == expected_nnz);\n\n\tMatCSR mat_csr_struct;\n\tnew (&mat_csr_struct.row_pointers) Eigen::Map<Eigen::ArrayXi>(row_pointers, N);\n\tnew (&mat_csr_struct.column_indices) Eigen::Map<Eigen::ArrayXi>(column_indices, nnz);\n\tnew (&mat_csr_struct.values) Eigen::Map<Eigen::ArrayXd>(values, nnz);\n\n\tEigen::ArrayXi const expected_row_pointers = (Eigen::ArrayXi(5) << 0, 2, 5, 8, 11).finished();\n\tASSERT_TRUE(mat_csr_struct.row_pointers.isApprox(expected_row_pointers));\n\n\tEigen::ArrayXi const expected_column_indices = (Eigen::ArrayXi(13) << 0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4).finished();\n\tASSERT_TRUE(mat_csr_struct.column_indices.isApprox(expected_column_indices));\n\n\tEigen::ArrayXd const expected_values = (Eigen::ArrayXd(13) << 1, -1, -1, 2, -1, -1, 2, -1, -1, 2, -1, -1, 1).finished();\n\tASSERT_TRUE(mat_csr_struct.values.isApprox(expected_values));\n\n\tMat mat_petsc;\n\tcreate_petsc_matrix_from_eigen_csr(mat_csr, mat_petsc);\n}\n\n/*\n   User-defined application context - contains data needed by the\n   application-provided call-back routines   FormFunction().\n*/\ntypedef struct {\n\tPetscReal param;             /* test problem parameter */\n\tint       mx,my;             /* discretization in x, y directions */\n} AppCtx;\n\n\n// User-defined routines\nint FormFunction(SNES,Vec,Vec,void*);\nint FormFunctionFortran(SNES,Vec,Vec,void*);\nvoid FormInitialGuess(AppCtx*,Vec, bool);\nvoid initial_guess(int mx, int my, double lambda, double* x);\n\n\nTEST(Impl, FortranVSCpp)\n{\n\tauto mx = 5;\n\tauto my = 5;\n\tauto lambda = 4.75;\n\tauto N = mx * my;\n\tEigen::ArrayXd x_cpp(N);\n\tEigen::ArrayXd x_for(N);\n\n\tinitialguessfortran_(&mx, &my, &lambda, x_for.data());\n\tinitial_guess(mx, my, lambda, x_cpp.data());\n\n\tASSERT_TRUE(x_cpp.isApprox(x_for));\n}\n\nclass PetscTest : public ::testing::TestWithParam<PetscBool> {\n  // You can implement all the usual fixture class members here.\n  // To access the test parameter, call GetParam() from class\n  // TestWithParam<T>.\n};\n/* ------------------------------------------------------------------------\n\n    Solid Fuel Ignition (SFI) problem.  This problem is modeled by\n    the partial differential equation\n\n            -Laplacian u - lambda*exp(u) = 0,  0 < x,y < 1,\n\n    with boundary conditions\n\n             u = 0  for  x = 0, x = 1, y = 0, y = 1.\n\n    A finite difference approximation with the usual 5-point stencil\n    is used to discretize the boundary value problem to obtain a nonlinear\n    system of equations.\n    The uniprocessor version of this code is snes/examples/tutorials/ex4.c\n\n  ------------------------------------------------------------------------- */\nTEST_P(PetscTest, SNES)\n{\n\tSNES             snes;                /* nonlinear solver */\n\tVec              x,r;                 /* solution, residual vectors */\n\tAppCtx           user;                /* user-defined work context */\n\tint              its;                 /* iterations for convergence */\n\tint              N,ierr,i,ii,ri,rj;\n\tISColoringValue* colors;\n\tPetscReal        bratu_lambda_max = 6.81,bratu_lambda_min = 0.;\n\tMatColoring  \t mat_coloring;\n\tMatFDColoring    fdcoloring;\n\tISColoring       iscoloring;\n\tMat              J;\n\tPetscScalar      zero = 0.0;\n\tPetscBool        use_fortran;\n\tPetscErrorCode   (*fnc)(SNES,Vec,Vec,void*);\n\n\t/*\n\t Initialize problem parameters\n\t*/\n\tuser.mx = 5; user.my = 5; user.param = 6.0;\n\n\tASSERT_FALSE(user.param >= bratu_lambda_max || user.param <= bratu_lambda_min); // Lambda is out of range\n\tN = user.mx*user.my;\n\n\t/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\t Create nonlinear solver context\n\t - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */\n\tSNESCreate(PETSC_COMM_WORLD, &snes);\n\n\t/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\t Create vector data structures; set function evaluation routine\n\t - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */\n\tVecCreateSeq(PETSC_COMM_WORLD, N, &x);\n\tVecDuplicate(x, &r);\n\n\tuse_fortran = GetParam();\n\tif (use_fortran) fnc = FormFunctionFortran;\n\telse     fnc = FormFunction;\n\n\t/*\n\t Set function evaluation routine and vector\n\t*/\n\tSNESSetFunction(snes,r,fnc,&user);\n\n\tauto mat_csr = create_laplacian_matrix_2d(user.mx, user.my);\n\tcreate_petsc_matrix_from_eigen_csr(mat_csr, J);\n\t/*\n\t   Create the data structure that SNESComputeJacobianDefaultColor() uses\n\t   to compute the actual Jacobians via finite differences.\n\t*/\n\tMatColoringCreate(J, &mat_coloring);\n\tMatColoringSetType(mat_coloring, MATCOLORINGSL);\n\tMatColoringSetFromOptions(mat_coloring);\n\tMatColoringApply(mat_coloring, &iscoloring);\n\tMatFDColoringCreate(J,iscoloring,&fdcoloring);\n\tMatFDColoringSetType(fdcoloring, MATMFFD_DS);\n\tMatFDColoringSetFunction(fdcoloring,(PetscErrorCode (*)(void))fnc,&user);\n\tMatFDColoringSetFromOptions(fdcoloring);\n\tMatFDColoringSetUp(J,iscoloring,fdcoloring);\n\t/*\n\t\tTell SNES to use the routine SNESComputeJacobianDefaultColor()\n\t  to compute Jacobians.\n\t*/\n\tSNESSetJacobian(snes,J,J,SNESComputeJacobianDefaultColor,fdcoloring);\n\tISColoringDestroy(&iscoloring);\n\tMatColoringDestroy(&mat_coloring);\n\n\t/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\t Customize nonlinear solver; set runtime options\n\t- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */\n\n\t// It is good to iterate at least once, otherwise the simulator\n\t// may not solve the problem at all if the first residual is\n\t// sufficiently small\n\tSNESSetForceIteration(snes, PETSC_TRUE);\n\n    SNESSetTolerances(snes, 1e-8, 1e-50, 1e-50, 10, 1e8);\n\n\t/*\n\t Set runtime options (e.g., -snes_monitor -snes_rtol <rtol> -ksp_type <type>)\n\t*/\n\tSNESSetFromOptions(snes);\n\n\t/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\t Evaluate initial guess; then solve nonlinear system\n\t- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */\n\t/*\n\t Note: The user should initialize the vector, x, with the initial guess\n\t for the nonlinear solver prior to calling SNESSolve().  In particular,\n\t to employ an initial guess of zero, the user should explicitly set\n\t this vector to zero by calling VecSet().\n\t*/\n\tFormInitialGuess(&user, x, use_fortran);\n\tSNESSolve(snes,NULL,x);\n\tSNESGetIterationNumber(snes,&its);\n\tPetscPrintf(PETSC_COMM_WORLD,\"Number of SNES iterations = %D\\n\",its);\n\n\tSNESConvergedReason reason;\n\tSNESGetConvergedReason(snes, &reason);\n\tASSERT_TRUE(reason > 0);\n\n\t/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\t Free work space.  All PETSc objects should be destroyed when they\n\t are no longer needed.\n\t- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */\n\tVecDestroy(&x);\n\tVecDestroy(&r);\n\tMatFDColoringDestroy(&fdcoloring);\n\tMatDestroy(&J);\n\tSNESDestroy(&snes);\n} // TEST_P\n\nINSTANTIATE_TEST_CASE_P(\n\t\tFotranTest,\n\t\tPetscTest,\n\t\t::testing::Values(PETSC_TRUE)\n);\nINSTANTIATE_TEST_CASE_P(\n\t\tCppTest,\n\t\tPetscTest,\n\t\t::testing::Values(PETSC_FALSE)\n);\n\nvoid FormInitialGuess(AppCtx *user, Vec X, bool use_fortran)\n{\n\tPetscScalar *x;\n\n\tauto mx = user->mx;\n\tauto my = user->my;\n\tauto lambda = user->param;\n\n\tVecGetArray(X,&x);\n\n\tinitial_guess(mx, my, lambda, x);\n\tif(use_fortran){\n\t\tinitialguessfortran_(&mx, &my, &lambda, x);\n\t}\n\telse{\n\t\tinitial_guess(mx, my, lambda, x);\n\t}\n\n\tVecRestoreArray(X,&x);\n}\n\nvoid initial_guess(int mx, int my, double lambda, double* x)\n{\n\tauto hx = 1.0 / (double)(mx - 1.0);\n\tauto hy = 1.0 / (double)(my - 1.0);\n\tauto temp1 = lambda / (lambda + 1.0);\n\tfor (int j = 0; j < my; ++j)\n\t{\n\t\tauto temp = double(std::min(j, my - j - 1) * hy);\n\t\tfor (int i = 0; i < mx; ++i)\n\t\t{\n\t\t\tauto row = i + j * mx;\n\t\t\tif (i == 0 || j == 0 || i == mx-1 || j == my-1) {\n\t\t\t\tx[row] = 0.0;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tx[row] = temp1 * std::sqrt( std::min(std::min(i, mx - i - 1) * hx, temp));\n\t\t}\n\t}\n}\n\nint FormFunction(SNES snes, Vec X, Vec F, void *ptr)\n{\n\tAppCtx            *user = (AppCtx*)ptr;\n\tint               ierr,i,j,row,mx,my;\n\tPetscReal         two = 2.0,one = 1.0,lambda,hx,hy,hxdhy,hydhx,sc;\n\tPetscScalar       u,uxx,uyy,*f;\n\tconst PetscScalar *x;\n\n\tmx = user->mx;            my = user->my;            lambda = user->param;\n\thx = one/(PetscReal)(mx-1);  hy = one/(PetscReal)(my-1);\n\tsc = hx*hy*lambda;        hxdhy = hx/hy;            hydhx = hy/hx;\n\n\t/*\n\t Get pointers to vector data\n\t*/\n\tVecGetArrayRead(X,&x);\n\tVecGetArray(F,&f);\n\n\t/*\n\t Compute function over the entire  grid\n\t*/\n\tfor (j=0; j<my; j++) {\n\t\tfor (i=0; i<mx; i++) {\n\t\t\trow = i + j*mx;\n\t\t\tif (i == 0 || j == 0 || i == mx-1 || j == my-1) {\n\t\t\t\tf[row] = x[row];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tu      = x[row];\n\t\t\tuxx    = (two*u - x[row-1] - x[row+1])*hydhx;\n\t\t\tuyy    = (two*u - x[row-mx] - x[row+mx])*hxdhy;\n\t\t\tf[row] = uxx + uyy - sc*PetscExpScalar(u);\n\t\t}\n\t}\n\n\t/*\n\t Restore vectors\n\t*/\n\tVecRestoreArrayRead(X,&x);\n\tVecRestoreArray(F,&f);\n\n\treturn 0;\n}\n\n// FormFunctionFortran - Evaluates nonlinear function, F(x) in Fortran.\nint FormFunctionFortran(SNES snes, Vec X, Vec F, void *ptr)\n{\n\tAppCtx            *user = (AppCtx*)ptr;\n\tint               ierr;\n\tPetscScalar       *f;\n\tPetscScalar const *x;\n\n\tVecGetArrayRead(X,&x);\n\tVecGetArray(F,&f);\n\tapplicationfunctionfortran_(&user->param,&user->mx,&user->my,x,f,&ierr);\n\tVecRestoreArrayRead(X,&x);\n\tVecRestoreArray(F,&f);\n\n\treturn 0;\n}\n\n\nvoid create_petsc_matrix_from_eigen_csr(\n\tEigenMatCSR& mat_csr,\n\tMat& jacobian\n)\n{\n\tauto n_rows = mat_csr.rows();\n\tauto n_cols = mat_csr.cols();\n\tauto nnz = mat_csr.nonZeros();\n\n\tauto row_pointers = mat_csr.outerIndexPtr();\n\tauto column_indices = mat_csr.innerIndexPtr();\n\tauto values = mat_csr.valuePtr();\n\n\tMatCSR jacobian_mat_csr;\n\tnew (&jacobian_mat_csr.row_pointers) Eigen::Map<Eigen::ArrayXi>(row_pointers, n_rows);\n\tnew (&jacobian_mat_csr.column_indices) Eigen::Map<Eigen::ArrayXi>(column_indices, nnz);\n\tnew (&jacobian_mat_csr.values) Eigen::Map<Eigen::ArrayXd>(values, nnz);\n\n    MatCreateSeqAIJWithArrays(\n        PETSC_COMM_WORLD,\n\t\tn_rows,\n\t\tn_cols,\n\t\tjacobian_mat_csr.row_pointers.data(),\n\t\tjacobian_mat_csr.column_indices.data(),\n\t\tjacobian_mat_csr.values.data(),\n        &jacobian\n    );\n\n    MatAssemblyBegin(jacobian, MAT_FINAL_ASSEMBLY);\n    MatAssemblyEnd(jacobian, MAT_FINAL_ASSEMBLY);\n}\n\n} // namespace\n", "meta": {"hexsha": "2b9996fe1cd7fc46bd5fd9f9bffd6139f7527b97", "size": 12387, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_petsc.cpp", "max_stars_repo_name": "arthursoprana/pipe", "max_stars_repo_head_hexsha": "3012895ac09c907f343d2869fd9fbe982f840eca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test_petsc.cpp", "max_issues_repo_name": "arthursoprana/pipe", "max_issues_repo_head_hexsha": "3012895ac09c907f343d2869fd9fbe982f840eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_petsc.cpp", "max_forks_repo_name": "arthursoprana/pipe", "max_forks_repo_head_hexsha": "3012895ac09c907f343d2869fd9fbe982f840eca", "max_forks_repo_licenses": ["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.8359550562, "max_line_length": 121, "alphanum_fraction": 0.6235569549, "num_tokens": 3963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.6068640219637401}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_REM_PIO2_CEPHES_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_PIO2_CEPHES_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing rem_pio2_cephes capabilities\n\n    Computes the remainder modulo \\f$\\pi/2\\f$ with cephes algorithm,\n    and the angle quadrant between 0 and 3.\n    This is a quick version accurate if the input is in \\f$[-20\\pi,20\\pi]\\f$.\n\n    @par Semantic:\n\n    For every parameters of floating type T:\n\n    @code\n    T r;\n    as_integer<T> n;\n    std::tie(n, r) = rem_pio2_cephes(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    as_integer<T> n = div(inearbyint, x, Pio_2<T>());\n    T r =  remainder(x, Pio_2<T>());\n    @endcode\n\n    The reduction of the argument modulo \\f$\\pi/2\\f$ is generally\n    the most difficult part of trigonometric evaluations.\n    The accurate algorithm over the whole floating point range\n    is over costly and implies the knowledge\n    of a few hundred \\f$\\pi\\f$ decimals\n    some simpler algorithms as this one\n    can be used, but the precision is only insured on specific intervals.\n\n    @see rem_pio2, rem_pio2_straight,rem_2pi, rem_pio2_medium,\n\n  **/\n  std::pair<IntegerValue, Value> rem_pio2_cephes(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem_pio2_cephes.hpp>\n#include <boost/simd/function/simd/rem_pio2_cephes.hpp>\n\n#endif\n", "meta": {"hexsha": "d116a6122199727a47a5f3f94d1fa88d1ef41700", "size": 1818, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/rem_pio2_cephes.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/rem_pio2_cephes.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/rem_pio2_cephes.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": 28.8571428571, "max_line_length": 100, "alphanum_fraction": 0.6391639164, "num_tokens": 460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7401743505760727, "lm_q1q2_score": 0.6068640109366484}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/point_generators_3.h>\n\n#include <CGAL/Side_of_triangle_mesh.h>\n\n#include <vector>\n#include <fstream>\n#include <limits>\n#include <boost/foreach.hpp>\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_3 Point;\ntypedef CGAL::Polyhedron_3<K> Polyhedron;\n\ndouble max_coordinate(const Polyhedron& poly)\n{\n  double max_coord = (std::numeric_limits<double>::min)();\n  BOOST_FOREACH(Polyhedron::Vertex_handle v, vertices(poly))\n  {\n    Point p = v->point();\n    max_coord = (std::max)(max_coord, p.x());\n    max_coord = (std::max)(max_coord, p.y());\n    max_coord = (std::max)(max_coord, p.z());\n  }\n  return max_coord;\n}\n\nint main(int argc, char* argv[])\n{\n  const char* filename = (argc > 1) ? argv[1] : \"data/eight.off\";\n  std::ifstream input(filename);\n\n  Polyhedron poly;\n  if (!input || !(input >> poly) || poly.empty()\n             || !CGAL::is_triangle_mesh(poly))\n  {\n    std::cerr << \"Not a valid input file.\" << std::endl;\n    return 1;\n  }\n\n  CGAL::Side_of_triangle_mesh<Polyhedron, K> inside(poly);\n\n  double size = max_coordinate(poly);\n\n  unsigned int nb_points = 100;\n  std::vector<Point> points;\n  points.reserve(nb_points);\n  CGAL::Random_points_in_cube_3<Point> gen(size);\n  for (unsigned int i = 0; i < nb_points; ++i)\n    points.push_back(*gen++);\n\n  std::cout << \"Test \" << nb_points << \" random points in cube \"\n    << \"[-\" << size << \"; \" << size <<\"]\" << std::endl;\n\n  int nb_inside = 0;\n  int nb_boundary = 0;\n  for (std::size_t i = 0; i < nb_points; ++i)\n  {\n    CGAL::Bounded_side res = inside(points[i]);\n\n    if (res == CGAL::ON_BOUNDED_SIDE) { ++nb_inside; }\n    if (res == CGAL::ON_BOUNDARY) { ++nb_boundary; }\n  }\n\n  std::cerr << \"Total query size: \" << points.size() << std::endl;\n  std::cerr << \"  \" << nb_inside << \" points inside \" << std::endl;\n  std::cerr << \"  \" << nb_boundary << \" points on boundary \" << std::endl;\n  std::cerr << \"  \" << points.size() - nb_inside - nb_boundary << \" points outside \" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "ca3e886360f6e61ac57163cbf27fbeabf1a1cfa8", "size": 2103, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/point_inside_example.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/point_inside_example.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/Polygon_mesh_processing/point_inside_example.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 28.8082191781, "max_line_length": 98, "alphanum_fraction": 0.637660485, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.606814844036898}}
{"text": "/**\n * \\file se_2_3_localization.cpp\n *\n *  Created on: Aug 03, 2020\n *     \\author: prashanthr05\n *\n *  ---------------------------------------------------------\n *  This file is:\n *  (c) 2020 Prashanth Ramadoss @ DIC-IIT, Genova, Italy\n *\n *  adapted from the file se3_localization.cpp:\n *  (c) 2018 Joan Sola @ IRI-CSIC, Barcelona, Catalonia\n *\n *  This file is part of `manif`, a C++ template-only library\n *  for Lie theory targeted at estimation for robotics.\n *  Manif is:\n *  (c) 2018 Jeremie Deray @ IRI-UPC, Barcelona\n *  ---------------------------------------------------------\n *\n *  ---------------------------------------------------------\n *  Demonstration example:\n *\n *  3D Robot localization and linear velocity estimation based on strap-down IMU model and fixed beacons.\n *\n *  ---------------------------------------------------------\n *\n *  We consider a robot in 3D space surrounded by a small\n *  number of punctual landmarks or _beacons_.\n *  The robot is assumed to be mounted with an IMU whose\n *  measurements are fed as exogeneous inputs to the system.\n *  The robot is able to measure the location\n *  of the beacons w.r.t its own reference frame.\n *  We assume in this example that the IMU frame coincides with the robot frame.\n *\n *  The robot extended pose X is in SE_2(3) and the beacon positions b_k in R^3,\n *\n *      X = |    R   p  v|              // position, orientation and linear velocity\n *          |        1   |\n *          |           1|\n *\n *      b_k = (bx_k, by_k, bz_k)    // lmk coordinates in world frame\n *\n *      alpha_k = (alphax_k, alphay_k, alphaz_k) // linear accelerometer measurements in IMU frame\n *\n *      omega_k = (omegax_k, omegay_k, omegaz_k) // gyroscope measurements in IMU frame\n *\n *      g = (0, 0, -9.80665)  // acceleration due to gravity in world frame\n *\n * Consider robot coordinate frame B and world coordinate frame A.\n * - p is the position of the origin of the robot frame B with respect to the world frame A\n * - R is the orientation of the robot frame B with respect to the world frame A\n * - v is the velocity of the robot frame with respect to the world frame,\n *            expressed in a frame whose origin coincides with the robot frame, oriented similar to the world frame\n *            (it is equivalent to p_dot in continuous time. This is usually called mixed-frame representation\n *            and is denoted as (B[A] v_AB), where B[A] is the mixed frame as described above.\n *            For reference, please see \"Multibody Dynamics Notation\" by Silvio Traversaro and Alessandro Saccon.\n *            Link: https://research.tue.nl/en/publications/multibody-dynamics-notation-version-2)\n * - a is the frame acceleration in mixed-representation (equivalent to p_doubledot in continuous time).\n * - omega_b as the angular velocity of the robot expressed in the robot frame\n *\n * The kinematic equations (1) can be written as,\n * p <-- p + v dt + 0.5 a dt^2\n * R <-- R Exp_SO3(omega_b)\n * v <-- v + a dt\n *\n * However, we would like to express the kinematics equations in the form,\n * X <-- X * Exp(u)\n * where, X \\in SE_2(3), u \\in R^9 and u_hat \\in se_2(3)\n * Note that here input vector u is expressed in the local frame (robot frame).\n * This can be seen as a motion integration on a manifold defined by the group SE_2(3).\n *\n * The exponential mapping of SE_2(3) is defined as,\n * for u = [u_p, u_w, u_v]\n * Exp(u) = | Exp_SO3(u_w)   JlSO3(u_w) u_p   JlSO3(u_w) u_v |\n *          | 0    0    0                 1                0 |\n *          | 0    0    0                 0                1 |\n * where, JlSO3 is the left Jacobian of the SO(3) group.\n *\n * Please see the Appendix C of the paper \"A micro Lie theory for state estimation in robotics\",\n * for the definition of the left Jacobian of SO(3).\n * Please see the Appendix D of the paper, for the definition of Exp map for SE(3).\n * The Exp map of SE_2(3) is a simple extension from the Exp map of SE(3).\n * Also, please refer to Example 7 of the paper to understand when and how the left Jacobian of SO(3)\n * appears in the definitions of Exp maps. The Example 7 illustrates the scenario for SE(3).\n * We use a direct extension here for SE_2(3).\n * One can arrive to such a definition by following the convergent Taylor's series expansion\n * for the matrix exponential of the Lie algebra element (Equation 16 of the paper).\n *\n * As a result of X <-- X * Exp(u), we get (2)\n * p <-- p + R JlSO3(u_w) u_p\n * R <-- R Exp_SO3(u_w)\n * v <-- v + R JlSO3(u_w) u_v\n *\n * It is important to notice the subtle difference between (1) and (2) here,\n * which is specifically the influence of the left Jacobian of SO(3) in (2).\n * The approach in (1) considers the motion integration is done by defining\n * the exponential map in R3xSO(3)xR3 instead of SE_2(3),\n * in the sense explored in Example 7 of the Micro Lie theory paper. It must be noted that\n * as dt tends to 0, both sets of equations (1) and (2) tend to be the same, since JlSO3 tends to identity.\n *\n * Since, (2) exploits the algebra of the SE_2(3) group properly,\n * we would like to draw a relationship between the sets of equations (2)\n * and the IMU measurements which will constitute the exogeneous input vector u \\in se_2(3).\n *\n * Considering R.T as the transpose of R, the IMU measurements are modeled as,\n *    - linear accelerometer measurements alpha = R.T (a - g) + w_acc\n *    - gyroscope measurements omega = omega_b + w_omega\n * Note that the IMU measurements are expressed in the IMU frame (coincides with the robot frame - assumption).\n * The IMU measurements are corrupted by noise,\n *    - w_omega is the additive white noise affecting the gyroscope measurements\n *    - w_acc is the additive white noise affecting the linear accelerometer measurements\n * It must be noted that we do not consider IMU biases in the IMU measurement model in this example.\n *\n * Taking into account all of the above considerations, the exogenous input vector u (3) becomes,\n *   u = (u_p, u_w, u_v) where,\n *   u_w = omega dt\n *   u_p = (R.T v dt + 0.5 dt^2 (alpha + R.T g)\n *   u_v = (alpha + R.T g) dt\n *\n * This choice of input vector allows us to directly use measurements from the IMU\n * for an unified motion integration involving position, orientation and linear velocity of the robot using SE_2(3).\n * Equations (2) and (3) lead us to the following evolution equations,\n *\n * p <-- p + JlSO3 R.T v dt + 0.5 JlSO3 (alpha + R.T g) dt^2\n * R <-- R Exp_SO3(omega dt)\n * v <-- v + JlSO3 (alpha + R.T g) dt\n *\n * The system propagation noise covariance matrix becomes,\n *    U = diagonal(0, 0, 0, sigma_omegax^2, sigma_omegay^2, sigma_omegaz^2, sigma_accx^2, sigma_accy^2, sigma_accz^2).\n *\n *  At the arrival of a exogeneous input u, the robot pose is updated\n *  with X <-- X * Exp(u) = X + u.\n *\n *  Landmark measurements are of the range and bearing type,\n *  though they are put in Cartesian form for simplicity.\n *  Their noise n is zero mean Gaussian, and is specified\n *  with a covariances matrix R.\n *  We notice that the SE_2(3) action is the same as a\n *  rigid motion action of SE(3).\n *  This is the action of X \\in SE_2(3) on a 3-d point b \\in R^3 defined as,\n *  X b = R b + p\n *\n *  Thus, the landmark measurements can be expressed as a group action on 3d points,\n *  y = h(X,b) = X^-1 * b\n *\n *      y_k = (brx_k, bry_k, brz_k)    // lmk coordinates in robot frame\n *\n *  We consider the beacons b_k situated at known positions.\n *  We define the extended pose to estimate as X in SE_2(3).\n *  The estimation error dx and its covariance P are expressed\n *  in the tangent space at X.\n *\n *  All these variables are summarized again as follows\n *\n *    X   : robot's extended pose, SE_2(3)\n *    u   : robot control input, u = u(X, y_imu) \\in se_2(3) with X as state and y_imu = [alpha, omega] as IMU readings, see Eq. (3)\n *    U   : control perturbation covariance\n *    b_k : k-th landmark position, R^3\n *    y   : Cartesian landmark measurement in robot frame, R^3\n *    R   : covariance of the measurement noise\n *\n *  The motion and measurement models are\n *\n *    X_(t+1) = f(X_t, u) = X_t * Exp ( u )     // motion equation\n *    y_k     = h(X, b_k) = X^-1 * b_k          // measurement equation\n *\n *  The algorithm below comprises first a simulator to\n *  produce measurements, then uses these measurements\n *  to estimate the state, using a Lie-based error-state Kalman filter.\n *\n *  This file has plain code with only one main() function.\n *  There are no function calls other than those involving `manif`.\n *\n *  Printing simulated state and estimated state together\n *  with an unfiltered state (i.e. without Kalman corrections)\n *  allows for evaluating the quality of the estimates.\n *\n * A side note: Besides the approach described here in this illustration example,\n * there are other interesting works like the paper,\n * The Invariant Extended Kalman filter as a stable observer (https://arxiv.org/pdf/1410.1465.pdf)\n * which assume a specific structure for the system propagation dynamics \"f(X_t, u)\" (group affine dynamics)\n * that simplifies the covariance propagation and enables error dynamics with stronger convergence properties.\n *\n */\n\n#include \"manif/SE_2_3.h\"\n\n#include <Eigen/Dense>\n\n#include <vector>\n#include <iostream>\n#include <iomanip>\n\nusing std::cout;\nusing std::endl;\n\nusing namespace Eigen;\n\ntypedef Array<double, 3, 1> Array3d;\ntypedef Array<double, 6, 1> Array6d;\ntypedef Matrix<double, 6, 1> Vector6d;\ntypedef Matrix<double, 6, 6> Matrix6d;\ntypedef Array<double, 9, 1> Array9d;\ntypedef Matrix<double, 9, 1> Vector9d;\ntypedef Matrix<double, 9, 9> Matrix9d;\n\nint main()\n{\n    std::srand((unsigned int) time(0));\n\n    // START CONFIGURATION\n    //\n    //\n    const int NUMBER_OF_LMKS_TO_MEASURE = 5;\n\n    // Define the robot extended pose element and its covariance\n    manif::SE_2_3d X, X_simulation, X_unfiltered;\n    Matrix9d    P;\n\n    X_simulation.setIdentity();\n    X.setIdentity();\n    X_unfiltered.setIdentity();\n    P.setZero();\n    P.block<3, 3>(0, 0) = 0.001*Eigen::Matrix3d::Identity();\n    P.block<3, 3>(3, 3) = 0.01*Eigen::Matrix3d::Identity();\n    P.block<3, 3>(6, 6) = 0.001*Eigen::Matrix3d::Identity();\n\n    // acceleration due to gravity in world frame\n    Vector3d g;\n    g << 0, 0, -9.80665;\n    const double dt = 0.01;\n\n    // IMU measurements in IMU frame\n    Vector3d alpha, alpha_const, omega, alpha_prev, omega_prev;\n    alpha_const << 0.1, 0.01, 0.1; // constant acceleration in IMU frame without gravity compensation\n    omega << 0.01, 0.1, 0; // constant angular velocity about x- and y-direction in IMU frame\n\n    // Previous IMU measurements in IMU frame initialized to values expected when stationary\n    alpha_prev = alpha = alpha_const - (X_simulation.rotation()).transpose()*g;\n    omega_prev << 0, 0, 0;\n\n    // Define a control vector and its noise and covariance\n    manif::SE_2_3Tangentd  u_simu, u_est, u_unfilt;\n    Vector9d            u_nom, u_noisy, u_noise;\n    Array9d             u_sigmas;\n    Matrix9d            U;\n\n    u_sigmas << 0.0, 0.0, 0.0, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01;\n    U        = (u_sigmas * u_sigmas).matrix().asDiagonal();\n\n    // Declare the Jacobians of the motion wrt robot and control\n    manif::SE_2_3d::Jacobian F;     // F = J_x_x + (J_x_u * J_u_x)\n    manif::SE_2_3d::Jacobian J_x_x; // d(X * exp(u)) / dX\n    manif::SE_2_3d::Jacobian J_x_u; // d(X * exp(u)) / du\n    manif::SE_2_3d::Jacobian J_u_x; // du / dX, since u is a state-dependent vector\n\n    // Define five landmarks in R^3\n    Vector3d b0, b1, b2, b3, b4, b;\n    b0 << 2.0,  0.0,  0.0;\n    b1 << 3.0, -1.0, -1.0;\n    b2 << 2.0, -1.0,  1.0;\n    b3 << 2.0,  1.0,  1.0;\n    b4 << 2.0,  1.0, -1.0;\n    std::vector<Vector3d> landmarks;\n    landmarks.push_back(b0);\n    landmarks.push_back(b1);\n    landmarks.push_back(b2);\n    landmarks.push_back(b3);\n    landmarks.push_back(b4);\n\n    // Define the beacon's measurements\n    Vector3d                y, y_noise;\n    Array3d                 y_sigmas;\n    Matrix3d                R;   /**< Beacon measurement noise covariance matrix **/\n    std::vector<Vector3d>   measurements(landmarks.size());\n\n    y_sigmas << 0.01, 0.01, 0.01;\n    R        = (y_sigmas * y_sigmas).matrix().asDiagonal();\n\n    // Declare the Jacobian of the measurements wrt the robot pose\n    Matrix<double, 3, 9>    H;      // H = J_e_x\n\n    // Declare some temporaries\n    Vector3d                e, z;   // expectation, innovation\n    Matrix3d                E, Z;   // covariances of the above\n    Matrix<double, 9, 3>    K;      // Kalman gain\n    manif::SE_2_3Tangentd      dx;     // optimal update step, or error-state\n    manif::SE_2_3d::Jacobian   J_xi_x; // Jacobian is typedef Matrix\n    Matrix<double, 3, 9>       J_e_xi; // Jacobian\n\n    //\n    //\n    // CONFIGURATION DONE\n\n\n\n    // DEBUG\n    cout << std::fixed   << std::setprecision(3) << std::showpos << endl;\n    cout << \"X STATE     :    X      Y      Z    TH_x   TH_y   TH_z     V_x   V_y    V_z\" << endl;\n    cout << \"---------------------------------------------------------------------------\" << endl;\n    cout << \"X simulated : Pos: \" << X_simulation.translation().transpose() <<\n                             \" RPY: \" << X_simulation.rotation().eulerAngles(2, 1, 0).reverse().transpose() <<\n                             \" Vel: \" << X_simulation.linearVelocity().transpose() << endl;\n    cout << \"X estimated : Pos: \" << X.translation().transpose() <<\n                             \" RPY: \" << X.rotation().eulerAngles(2, 1, 0).reverse().transpose() <<\n                             \" Vel: \" << X.linearVelocity().transpose() << endl;\n    cout << \"X unfilterd : Pos: \" << X_unfiltered.translation().transpose() <<\n                             \" RPY: \" << X_unfiltered.rotation().eulerAngles(2, 1, 0).reverse().transpose() <<\n                             \" Vel: \" << X_unfiltered.linearVelocity().transpose() << endl;\n    cout << \"---------------------------------------------------------------------------\" << endl;\n    // END DEBUG\n\n\n    // START TEMPORAL LOOP\n    //\n    //\n\n    // Make 10 steps. Measure up to three landmarks each time.\n    for (double t = 0; t < 10; t+=dt)\n    {\n        //// I. Simulation ###############################################################################\n\n        /// get current simulated state and measurements from previous step\n        auto R_k = X_simulation.rotation();\n        auto v_k = X_simulation.linearVelocity();\n        auto acc_k = alpha_prev + R_k.transpose()*g;\n\n        /// input vector\n        u_nom << (dt*(R_k.transpose())*v_k + 0.5*dt*dt*acc_k),  dt*omega_prev, dt*acc_k;\n\n        /// simulate noise\n        u_noise = u_sigmas * Array9d::Random();             // control noise\n        u_noisy = u_nom + u_noise;                          // noisy control\n\n        u_simu   = u_nom;\n        u_unfilt = u_noisy;\n\n        /// first we move - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n        X_simulation = X_simulation + u_simu;               // overloaded X.rplus(u) = X * exp(u)\n        /// update expected IMU measurements\n        alpha = alpha_const - X_simulation.rotation().transpose()*g; // update expected IMU measurement after moving\n\n        /// then we measure all landmarks - - - - - - - - - - - - - - - - - - - -\n        for (int i = 0; i < landmarks.size(); i++)\n        {\n            b = landmarks[i];                               // lmk coordinates in world frame\n\n            /// simulate noise\n            y_noise = y_sigmas * Array3d::Random();         // measurement noise\n\n            y = X_simulation.inverse().act(b);              // landmark measurement, before adding noise\n            y = y + y_noise;                                // landmark measurement, noisy\n            measurements[i] << y;                     // store for the estimator just below\n        }\n\n\n\n\n        //// II. Estimation ###############################################################################\n\n        /// get current state estimate to build the state-dependent control vector\n        auto R_k_est = X.rotation();\n        auto v_k_est = X.linearVelocity();\n        auto acc_k_est = alpha_prev + R_k_est.transpose()*g;\n\n        Eigen::Vector3d accLin = dt*(R_k_est.transpose())*v_k_est + 0.5*dt*dt*acc_k_est;\n        Eigen::Vector3d gLin = R_k_est.transpose()*g*dt;\n        Eigen::Matrix3d accLinCross = manif::skew(accLin);\n        Eigen::Matrix3d gCross = manif::skew(gLin);\n\n        u_est << accLin,  dt*omega_prev, dt*acc_k_est;\n        u_est += u_noise;\n\n        /// First we move - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n        X = X.plus(u_est, J_x_x, J_x_u);                        // X * exp(u), with Jacobians\n\n        // Prepare Jacobian of state-dependent control vector\n        J_u_x.setZero();\n        J_u_x.block<3, 3>(0, 3) = accLinCross;\n        J_u_x.block<3, 3>(0, 6) = Eigen::Matrix3d::Identity()*dt;\n        J_u_x.block<3, 3>(6, 3) = gCross;\n        F = J_x_x + J_x_u*J_u_x;                                // chain rule for system model Jacobian\n\n        P = F * P * F.transpose() + J_x_u * U * J_x_u.transpose();\n\n\n        /// Then we correct using the measurements of each lmk - - - - - - - - -\n        for (int i = 0; i < NUMBER_OF_LMKS_TO_MEASURE; i++)\n        {\n            // landmark\n            b = landmarks[i];                               // lmk coordinates in world frame\n\n           // measurement\n            y = measurements[i];                            // lmk measurement, noisy\n\n            // expectation\n            e = X.inverse(J_xi_x).act(b, J_e_xi);           // note: e = R.tr * ( b - t ), for X = (R,t).\n            H = J_e_xi * J_xi_x;                            // note: H = J_e_x = J_e_xi * J_xi_x\n            E = H * P * H.transpose();\n\n            // innovation\n            z = y - e;\n            Z = E + R;\n\n            // Kalman gain\n            K = P * H.transpose() * Z.inverse();            // K = P * H.tr * ( H * P * H.tr + R).inv\n\n            // Correction step\n            dx = K * z;                                     // dx is in the tangent space at X\n\n            // Update\n            X = X + dx;                                     // overloaded X.rplus(dx) = X * exp(dx)\n            P = P - K * Z * K.transpose();\n        }\n\n\n\n\n        //// III. Unfiltered ##############################################################################\n\n        // move also an unfiltered version for comparison purposes\n        X_unfiltered = X_unfiltered + u_unfilt;\n\n        alpha_prev = alpha;\n        omega_prev = omega;\n\n\n        //// IV. Results ##############################################################################\n\n        // DEBUG\n        cout << \"X simulated : Pos: \" << X_simulation.translation().transpose() <<\n                             \" RPY: \" << X_simulation.rotation().eulerAngles(2, 1, 0).reverse().transpose() <<\n                             \" Vel: \" << X_simulation.linearVelocity().transpose() << endl;\n        cout << \"X estimated : Pos: \" << X.translation().transpose() <<\n                             \" RPY: \" << X.rotation().eulerAngles(2, 1, 0).reverse().transpose() <<\n                             \" Vel: \" << X.linearVelocity().transpose() << endl;\n        cout << \"X unfilterd : Pos: \" << X_unfiltered.translation().transpose() <<\n                             \" RPY: \" << X_unfiltered.rotation().eulerAngles(2, 1, 0).reverse().transpose() <<\n                             \" Vel: \" << X_unfiltered.linearVelocity().transpose() << endl;\n        cout << \"---------------------------------------------------------------------------\" << endl;\n\n        cout << \"X simulated : log: \" << X_simulation.log() << endl;\n        cout << \"X estimated : log: \" << X.log() << endl;\n        cout << \"X unfilterd : log: \" << X_unfiltered.log() << endl;\n        cout << \"---------------------------------------------------------------------------\" << endl;\n        cout << \"---------------------------------------------------------------------------\" << endl;\n        // END DEBUG\n\n    }\n\n    //\n    //\n    // END OF TEMPORAL LOOP. DONE.\n\n    return 0;\n}\n", "meta": {"hexsha": "3728393c625a10a8c3a613683dd8fbbc96b295cd", "size": 20118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/se_2_3_localization.cpp", "max_stars_repo_name": "pettni/manif", "max_stars_repo_head_hexsha": "81e9498af69417e4b2ed463d2bcf4b57007c1ca8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-19T07:05:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-19T07:05:48.000Z", "max_issues_repo_path": "examples/se_2_3_localization.cpp", "max_issues_repo_name": "xusong0zju/manif", "max_issues_repo_head_hexsha": "6138a90eb3866002fd7ed7e0d79e3ab4420ae775", "max_issues_repo_licenses": ["MIT"], "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/se_2_3_localization.cpp", "max_forks_repo_name": "xusong0zju/manif", "max_forks_repo_head_hexsha": "6138a90eb3866002fd7ed7e0d79e3ab4420ae775", "max_forks_repo_licenses": ["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.9257641921, "max_line_length": 132, "alphanum_fraction": 0.5687941147, "num_tokens": 5418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6068148335609398}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n\nint main(void)\n{\n    int const N = 5;\n    Eigen::MatrixXi A(N, N);\n    A.setRandom();\n\n    std::cout << \"A =\\n\" << A << '\\n' <<std::endl;\n    std::cout << \"A(2..3,:) =\\n\" << A.middleRows(2, 2) << std::endl;\n    \n    return 0;\n}", "meta": {"hexsha": "edcda36c4b7669d40b64284bd4d8a35a1ad44524", "size": 270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_package/test_package.cpp", "max_stars_repo_name": "james-atkins/conan-eigen", "max_stars_repo_head_hexsha": "6c28b86f24cb65e59b7614a1638cfc469a49587a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-07T10:15:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-07T10:15:45.000Z", "max_issues_repo_path": "test_package/test_package.cpp", "max_issues_repo_name": "james-atkins/conan-eigen", "max_issues_repo_head_hexsha": "6c28b86f24cb65e59b7614a1638cfc469a49587a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-01T16:29:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-01T16:29:56.000Z", "max_forks_repo_path": "test_package/test_package.cpp", "max_forks_repo_name": "james-atkins/conan-eigen", "max_forks_repo_head_hexsha": "6c28b86f24cb65e59b7614a1638cfc469a49587a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-07T10:15:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-07T10:15:49.000Z", "avg_line_length": 19.2857142857, "max_line_length": 68, "alphanum_fraction": 0.4962962963, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.606788210218287}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Copyright 2012 The MITRE Corporation                                      *\n *                                                                           *\n * Licensed under the Apache License, Version 2.0 (the \"License\");           *\n * you may not use this file except in compliance with the License.          *\n * You may obtain a copy of the License at                                   *\n *                                                                           *\n *     http://www.apache.org/licenses/LICENSE-2.0                            *\n *                                                                           *\n * Unless required by applicable law or agreed to in writing, software       *\n * distributed under the License is distributed on an \"AS IS\" BASIS,         *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *\n * See the License for the specific language governing permissions and       *\n * limitations under the License.                                            *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <Eigen/Dense>\n\n#include <openbr/plugins/openbr_internal.h>\n#include <openbr/core/opencvutils.h>\n#include <openbr/core/eigenutils.h>\n\nusing namespace cv;\n\nnamespace br\n{\n\n/*!\n * \\ingroup transforms\n * \\brief Procrustes alignment of points\n * \\author Scott Klum \\cite sklum\n */\nclass ProcrustesTransform : public MetadataTransform\n{\n    Q_OBJECT\n\n    Q_PROPERTY(bool warp READ get_warp WRITE set_warp RESET reset_warp STORED false)\n    BR_PROPERTY(bool, warp, true)\n\n    Eigen::MatrixXf meanShape;\n\n    void train(const TemplateList &data)\n    {\n        QList< QList<QPointF> > normalizedPoints;\n\n        // Normalize all sets of points\n        foreach (br::Template datum, data) {\n            QList<QPointF> points = datum.file.points();\n            QList<QRectF> rects = datum.file.rects();\n\n            if (points.empty() || rects.empty()) continue;\n\n            // Assume rect appended last was bounding box\n            points.append(rects.last().topLeft());\n            points.append(rects.last().topRight());\n            points.append(rects.last().bottomLeft());\n            points.append(rects.last().bottomRight());\n\n            // Center shape at origin\n            Scalar mean = cv::mean(OpenCVUtils::toPoints(points).toVector().toStdVector());\n            for (int i = 0; i < points.size(); i++) points[i] -= QPointF(mean[0],mean[1]);\n\n            // Remove scale component\n            float norm = cv::norm(OpenCVUtils::toPoints(points).toVector().toStdVector());\n            for (int i = 0; i < points.size(); i++) points[i] /= norm;\n\n            normalizedPoints.append(points);\n        }\n\n        if (normalizedPoints.empty()) qFatal(\"Unable to calculate normalized points\");\n\n        // Determine mean shape, assuming all shapes contain the same number of points\n        meanShape = Eigen::MatrixXf(normalizedPoints[0].size(), 2);\n\n        for (int i = 0; i < normalizedPoints[0].size(); i++) {\n            double x = 0;\n            double y = 0;\n\n            for (int j = 0; j < normalizedPoints.size(); j++) {\n                x += normalizedPoints[j][i].x();\n                y += normalizedPoints[j][i].y();\n            }\n\n            x /= (double)normalizedPoints.size();\n            y /= (double)normalizedPoints.size();\n\n            meanShape(i,0) = x;\n            meanShape(i,1) = y;\n        }\n    }\n\n    void projectMetadata(const File &src, File &dst) const\n    {\n        QList<QPointF> points = src.points();\n        QList<QRectF> rects = src.rects();\n\n        if (points.empty() || rects.empty()) {\n            dst = src;\n            if (Globals->verbose) qWarning(\"Procrustes alignment failed because points or rects are empty.\");\n            return;\n        }\n\n        // Assume rect appended last was bounding box\n        points.append(rects.last().topLeft());\n        points.append(rects.last().topRight());\n        points.append(rects.last().bottomLeft());\n        points.append(rects.last().bottomRight());\n\n        Scalar mean = cv::mean(OpenCVUtils::toPoints(points).toVector().toStdVector());\n        for (int i = 0; i < points.size(); i++) points[i] -= QPointF(mean[0],mean[1]);\n\n        Eigen::MatrixXf srcMat(points.size(), 2);\n        float norm = cv::norm(OpenCVUtils::toPoints(points).toVector().toStdVector());\n        for (int i = 0; i < points.size(); i++) {\n            points[i] /= norm;\n            srcMat(i,0) = points[i].x();\n            srcMat(i,1) = points[i].y();\n        }\n\n        Eigen::JacobiSVD<Eigen::MatrixXf> svd(srcMat.transpose()*meanShape, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        Eigen::MatrixXf R = svd.matrixU()*svd.matrixV().transpose();\n\n        dst = src;\n\n        // Store procrustes stats in the order:\n        // R(0,0), R(1,0), R(1,1), R(0,1), mean_x, mean_y, norm\n        QList<float> procrustesStats;\n        procrustesStats << R(0,0) << R(1,0) << R(1,1) << R(0,1) << mean[0] << mean[1] << norm;\n        dst.setList<float>(\"ProcrustesStats\",procrustesStats);\n\n        if (warp) {\n            Eigen::MatrixXf dstMat = srcMat*R;\n            for (int i = 0; i < dstMat.rows(); i++) {\n                dst.appendPoint(QPointF(dstMat(i,0),dstMat(i,1)));\n            }\n        }\n    }\n\n    void store(QDataStream &stream) const\n    {\n        stream << meanShape;\n    }\n\n    void load(QDataStream &stream)\n    {\n        stream >> meanShape;\n    }\n\n};\n\nBR_REGISTER(Transform, ProcrustesTransform)\n\n} // namespace br\n\n#include \"metadata/procrustes.moc\"\n", "meta": {"hexsha": "57a1051b876f5c8d5cf3062fdca1a3c0c3ee7fae", "size": 5623, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbr/plugins/metadata/procrustes.cpp", "max_stars_repo_name": "kassemitani/openbr", "max_stars_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2016-01-27T04:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-19T20:45:16.000Z", "max_issues_repo_path": "openbr/plugins/metadata/procrustes.cpp", "max_issues_repo_name": "kassemitani/openbr", "max_issues_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-04-09T13:55:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-21T03:08:08.000Z", "max_forks_repo_path": "openbr/plugins/metadata/procrustes.cpp", "max_forks_repo_name": "kassemitani/openbr", "max_forks_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2016-01-27T13:07:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T17:19:18.000Z", "avg_line_length": 36.0448717949, "max_line_length": 119, "alphanum_fraction": 0.5321003023, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.6067881998104747}}
{"text": "#include <stan/math/rev/scal.hpp>\n#include <gtest/gtest.h>\n#include <test/unit/math/rev/scal/fun/nan_util.hpp>\n#include <test/unit/math/rev/scal/util.hpp>\n#include <boost/math/special_functions/beta.hpp>\n\nTEST(AgradRev,ibeta_vvv) {\n  using stan::math::var;\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  \n  using boost::math::ibeta_derivative;\n\n  AVAR a = 0.6;\n  AVAR b = 0.3;\n  AVAR c = 0.5;\n  AVAR f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n  \n  AVEC x = createAVEC(a,b,c);\n  VEC grad_f;\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(-0.436993,grad_f[0]);\n  EXPECT_FLOAT_EQ(0.7779751,grad_f[1]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a.val(), b.val(), c.val()),grad_f[2]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(a,b,c);\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(-0.03737671,grad_f[0]);\n  EXPECT_FLOAT_EQ(0.02507405,grad_f[1]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a.val(), b.val(), c.val()),grad_f[2]);\n}\nTEST(AgradRev,ibeta_vvd) {\n  using stan::math::var;\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  \n  using boost::math::ibeta_derivative;\n\n  AVAR a = 0.6;\n  AVAR b = 0.3;\n  double c = 0.5;\n  AVAR f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n  \n  AVEC x = createAVEC(a,b);\n  VEC grad_f;\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(-0.436993,grad_f[0]);\n  EXPECT_FLOAT_EQ(0.7779751,grad_f[1]);\n  \n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(a,b);\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(-0.03737671,grad_f[0]);\n  EXPECT_FLOAT_EQ(0.02507405,grad_f[1]);\n}\nTEST(AgradRev,ibeta_vdv) {\n  using stan::math::var;\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  \n  using boost::math::ibeta_derivative;\n\n  AVAR a = 0.6;\n  double b = 0.3;\n  AVAR c = 0.5;\n  AVAR f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n  \n  AVEC x = createAVEC(a,c);\n  VEC grad_f;\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(-0.436993,grad_f[0]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a.val(), b, c.val()),grad_f[1]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(a,c);\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(-0.03737671,grad_f[0]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a.val(), b, c.val()),grad_f[1]);\n}\nTEST(AgradRev,ibeta_vdd) {\n  using stan::math::var;\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  \n  using boost::math::ibeta_derivative;\n\n  AVAR a = 0.6;\n  double b = 0.3;\n  double c = 0.5;\n  AVAR f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n  \n  AVEC x = createAVEC(a);\n  VEC grad_f;\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(-0.436993,grad_f[0]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(a);\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(-0.03737671,grad_f[0]);\n}\nTEST(AgradRev,ibeta_dvv) {\n  using stan::math::var;\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  \n  using boost::math::ibeta_derivative;\n\n  double a = 0.6;\n  AVAR b = 0.3;\n  AVAR c = 0.5;\n  AVAR f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n  \n  AVEC x = createAVEC(b,c);\n  VEC grad_f;\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(0.7779751,grad_f[0]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a, b.val(), c.val()),grad_f[1]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(b,c);\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(0.02507405,grad_f[0]);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a, b.val(), c.val()),grad_f[1]);\n}\nTEST(AgradRev,ibeta_dvd) {\n  using stan::math::var;\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  \n  using boost::math::ibeta_derivative;\n\n  double a = 0.6;\n  AVAR b = 0.3;\n  double c = 0.5;\n  AVAR f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n  \n  AVEC x = createAVEC(b);\n  VEC grad_f;\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(0.7779751,grad_f[0]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(b);\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(0.02507405,grad_f[0]);\n}\nTEST(AgradRev,ibeta_ddv) {\n  using stan::math::var;\n  using stan::math::ibeta;\n  using stan::math::ibeta;\n  \n  using boost::math::ibeta_derivative;\n\n  double a = 0.6;\n  double b = 0.3;\n  AVAR c = 0.5;\n  AVAR f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.3121373, f.val());\n  \n  AVEC x = createAVEC(c);\n  VEC grad_f;\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a, b, c.val()),grad_f[0]);\n\n  a = 3;\n  b = 2;\n  c = 0.2;\n  f = ibeta(a,b,c);\n  EXPECT_FLOAT_EQ(0.0272, f.val());\n  x = createAVEC(c);\n  f.grad(x,grad_f);\n  EXPECT_FLOAT_EQ(ibeta_derivative(a, b, c.val()),grad_f[0]);\n}\n\nstruct ibeta_fun {\n  template <typename T0, typename T1, typename T2>\n  inline\n  typename stan::return_type<T0,T1,T2>::type\n  operator()(const T0& arg1,\n             const T1& arg2,\n             const T2& arg3) const {\n    return ibeta(arg1,arg2,arg3);\n  }\n};\n\nTEST(AgradRev,ibeta_NaN) {\n  ibeta_fun ibeta_;\n  test_nan(ibeta_,0.6,0.3,0.5,true,false);\n}\n\nTEST(AgradRev, check_varis_on_stack) {\n  AVAR a = 0.6;\n  AVAR b = 0.3;\n  AVAR c = 0.5;\n  test::check_varis_on_stack(stan::math::ibeta(a, b, c));\n  test::check_varis_on_stack(stan::math::ibeta(a, b, 0.5));\n  test::check_varis_on_stack(stan::math::ibeta(a, 0.3, c));\n  test::check_varis_on_stack(stan::math::ibeta(a, 0.3, 0.5));\n  test::check_varis_on_stack(stan::math::ibeta(0.6, b, c));\n  test::check_varis_on_stack(stan::math::ibeta(0.6, b, 0.5));\n  test::check_varis_on_stack(stan::math::ibeta(0.6, 0.3, c));\n}\n", "meta": {"hexsha": "a46bac1f814593ca43c9899f84aaf34b0d816134", "size": 5480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/ibeta_test.cpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/ibeta_test.cpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/test/unit/math/rev/scal/fun/ibeta_test.cpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3191489362, "max_line_length": 73, "alphanum_fraction": 0.6326642336, "num_tokens": 2114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6067881998104746}}
{"text": "//\n// Created by Xinyu Zhang on 3/26/21.\n//\n#include <iostream>\n// #include <Eigen/Dense>\n// #include <cosan/io/utils.h>\n#include <cosan/selection/randomgridsearch.h>\n#include <cosan/selection/gridsearch.h>\n#include <cosan/selection/kfold.h>\n#include <cosan/selection/timeseriessplit.h>\n#include <cosan/selection/randomkfold.h>\n#include <cosan/utils/utils.h>\n#include <cosan/data/CosanData.h>\n#include <cosan/model/CosanPCRRidge.h>\n#include <cosan/model/CosanPrincipalComponentRegression.h>\n#include <cosan/model/CosanRidgeRegression.h>\n#include <cosan/model/CosanLinearRegression.h>\n#include <cosan/preprocessing/customtransform.h>\n#include <cosan/preprocessing/encoder.h>\n#include <cosan/preprocessing/minmaxscaler.h>\n#include <cosan/preprocessing/missingvalues.h>\n#include <cosan/preprocessing/normalizer.h>\n#include <cosan/preprocessing/onehotEncoder.h>\n#include <cosan/preprocessing/ordinalEncoder.h>\n#include <cosan/preprocessing/overunderflow.h>\n#include <cosan/preprocessing/polynomialfeatures.h>\n#include <cosan/preprocessing/preprocessor.h>\n#include <cosan/preprocessing/principalcomponentanalysis.h>\n#include <cosan/preprocessing/standardScaler.h>\n// #include <cosan/model/CosanLinearRegression.h>\n// #include <cosan/model/CosanRidgeRegression.h>\n//using namespace Eigen;\n//using namespace std;\n// gcc -I. ./test/Implementation.cpp\ntypedef double db;\nint main() {\n\tfmt::print(\"fmt library can be used\", 42);\n//  Data Reading\n\tconstexpr gsl::index nrows = 3;\n\tconstexpr gsl::index ncols = 3;\n\n\n    Cosan::CosanMatrix<db> CM;\n    CM.resize(nrows,ncols);\n    CM<< 1,2,3,\n        4,5,6,\n        7,8,9;\n    Cosan::CosanData<db>  CD0(CM);\n    std::vector<db> inputX({1,2,3,4,5,6});\n    Cosan::CosanData<db>  CD1(inputX,inputX,6,\"rowfirst\");\n    std::cout<<CD1.GetInput()<<std::endl;\n    db lb=0,ub=1;\n    Cosan::CosanData<db> CD2(3,4,lb,ub);\n    std::cout<<CD2.GetInput()<<std::endl;\n\n//  Data Preprocessing\n    Cosan::CosanRawData<db> CRD(\"./example_data/toy2/X_.csv\",\"./example_data/toy2/Y_.csv\");\n    std::cout<<CRD.GetSummaryMessageX()<<std::endl;\n    std::cout<<CRD.GetSummaryMessageY()<<std::endl;    \n\tCosan::OverUnderFlow  OUF(CRD);\t\n\tCosan::MissingValues  MSV(CRD);\t\t\n\tCosan::StandardScaler SS(CRD);\n\tCosan::Normalizer NM(CRD,2);\n    Cosan::Encoder ED(CRD,true);\n    lb = 2;\n    ub=6;\n\tCosan::MinmaxScaler MMS(CRD,lb,ub);\t\n\tCosan::PolynomialFeatures PF(CRD,{{1,0},{1,1}});\n\tCosan::PrincipalComponentAnalysis PCA(CRD);\n\tstd::cout<<PCA.GetPC()<<std::endl;\n//  Model fitting\n\tCosan::CosanRawData<db> CD(\"./example_data/toy/X.csv\",\"./example_data/toy/y.csv\");\n\tCosan::CosanLinearRegression<db> CLRwbias(true);\n\tCLRwbias.fit(CD.GetInput(),CD.GetTarget());\n\tstd::cout<<CLRwbias.GetBeta()<<std::endl;\n\tstd::cout<<(CLRwbias.predict(CD.GetInput())-CD.GetTarget()).norm()<<std::endl;   \n\tCosan::CosanLinearRegression<db> CLRwobias(false);\n\tCLRwobias.fit(CD.GetInput(),CD.GetTarget());\n\tstd::cout<<CLRwobias.GetBeta()<<std::endl;  \n\tstd::cout<<(CLRwobias.predict(CD.GetInput())-CD.GetTarget()).norm()<<std::endl;   \n\n\tdb RegularizationTerm = 1;\n\tCosan::CosanRidgeRegression<db> CRRwBias(RegularizationTerm,true);\n\tCRRwBias.fit(CD.GetInput(),CD.GetTarget());\n\tstd::cout<<CRRwBias.GetBeta()<<std::endl;\n\tstd::cout<<(CRRwBias.predict(CD.GetInput())-CD.GetTarget()).norm()<<std::endl;   \n\n\tgsl::index ncomp = 4;\n\tCosan::CosanPrincipalComponentRegression<db> CPCR(ncomp);\n\tCPCR.fit(CD.GetInput(),CD.GetTarget());\n\tstd::cout<<CPCR.GetBeta()<<std::endl;\n\tstd::cout<<(CPCR.predict(CD.GetInput())-CD.GetTarget()).norm()<<std::endl;\n\n\n\tdb regularier = 0.01;\n\tCosan::CosanPCRRidge<db> CPCRR({ncomp,regularier});\n\tCPCRR.fit(CD.GetInput(),CD.GetTarget());\n\tstd::cout<<CPCRR.GetBeta()<<std::endl;\n\tstd::cout<<(CPCRR.predict(CD.GetInput())-CD.GetTarget()).norm()<<std::endl;\n\tstd::cout<<CD.GetcolsX()<<std::endl;\n\n\n\tconstexpr gsl::index nrows1 = 10000;\n\tconstexpr gsl::index ncols1 = 10;\n\n    Cosan::CosanMatrix<db> X_input;\n    Cosan::CosanMatrix<db> Y_input;\n\tX_input.resize(nrows1,ncols1);\n\tY_input.resize(nrows1,1);\n    X_input = Eigen::Matrix<decltype(X_input)::Scalar,nrows1,ncols1>::Random();\n    Y_input = Eigen::Matrix<decltype(X_input)::Scalar,nrows1,1>::Random();\n    Cosan::CosanData CD_search(X_input,Y_input);\n// \tCosan::CosanRidgeRegression<db> CRRwBias(RegularizationTerm,true);\n    Cosan::MeanSquareError<decltype(X_input)::Scalar> mse;\n    db a = 0.05;\n    std::vector<db> v(10);\n    std::generate(v.begin(), v.end(), [n = 1, &a]() mutable { return n++ * a; });\n    Cosan::KFold kf(5);\n    Cosan::GridSearch GDS(CD_search,CRRwBias,mse,kf,v);\n    fmt::print(\"The best params selected is\\n \");\n    std::cout<<GDS.GetBestParams()<<std::endl;\n//  Grid Search\n\n    return 0;\n}\n", "meta": {"hexsha": "cc7b827e3e188cdf2ac0a4aba5dbb22ec78d130d", "size": 4678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Implementation.cpp", "max_stars_repo_name": "zhxinyu/cosan", "max_stars_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_stars_repo_licenses": ["MIT"], "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/Implementation.cpp", "max_issues_repo_name": "zhxinyu/cosan", "max_issues_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_issues_repo_licenses": ["MIT"], "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/Implementation.cpp", "max_forks_repo_name": "zhxinyu/cosan", "max_forks_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-13T05:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T05:56:38.000Z", "avg_line_length": 37.126984127, "max_line_length": 91, "alphanum_fraction": 0.7054296708, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504228, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.606788194455993}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Boost Graph Library along with the software; see the file LICENSE.\r\n// If not, contact Office of Research, Indiana University,\r\n// Bloomington, IN 47405.\r\n//\r\n// Permission to modify the code and to distribute the code is\r\n// granted, provided the text of this NOTICE is retained, a notice if\r\n// the code was modified is included with the above COPYRIGHT NOTICE\r\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\r\n// LICENSE file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n#include <vector>\r\n#include <string>\r\n#include <boost/graph/topological_sort.hpp>\r\n#include <boost/graph/leda_graph.hpp>\r\n// Undefine macros from LEDA that conflict with the C++ Standard Library.\r\n#undef string\r\n#undef vector\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  typedef GRAPH < std::string, char >graph_t;\r\n  graph_t leda_g;\r\n  typedef graph_traits < graph_t >::vertex_descriptor vertex_t;\r\n  std::vector < vertex_t > vert(7);\r\n  vert[0] = add_vertex(std::string(\"pick up kids from school\"), leda_g);\r\n  vert[1] = add_vertex(std::string(\"buy groceries (and snacks)\"), leda_g);\r\n  vert[2] = add_vertex(std::string(\"get cash at ATM\"), leda_g);\r\n  vert[3] =\r\n    add_vertex(std::string(\"drop off kids at soccer practice\"), leda_g);\r\n  vert[4] = add_vertex(std::string(\"cook dinner\"), leda_g);\r\n  vert[5] = add_vertex(std::string(\"pick up kids from soccer\"), leda_g);\r\n  vert[6] = add_vertex(std::string(\"eat dinner\"), leda_g);\r\n\r\n  add_edge(vert[0], vert[3], leda_g);\r\n  add_edge(vert[1], vert[3], leda_g);\r\n  add_edge(vert[1], vert[4], leda_g);\r\n  add_edge(vert[2], vert[1], leda_g);\r\n  add_edge(vert[3], vert[5], leda_g);\r\n  add_edge(vert[4], vert[6], leda_g);\r\n  add_edge(vert[5], vert[6], leda_g);\r\n\r\n  std::vector < vertex_t > topo_order;\r\n  node_array < default_color_type > color_array(leda_g);\r\n\r\n  topological_sort(leda_g, std::back_inserter(topo_order),\r\n                   color_map(make_leda_node_property_map(color_array)));\r\n\r\n  std::reverse(topo_order.begin(), topo_order.end());\r\n  int n = 1;\r\n  for (std::vector < vertex_t >::iterator i = topo_order.begin();\r\n       i != topo_order.end(); ++i, ++n)\r\n    std::cout << n << \": \" << leda_g[*i] << std::endl;\r\n\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "f3f5bd1790f042f66f70d6c001628d3bd2eb21f1", "size": 2927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/topo-sort-with-leda.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/topo-sort-with-leda.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/graph/example/topo-sort-with-leda.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2253521127, "max_line_length": 75, "alphanum_fraction": 0.6569866758, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.8006920092299292, "lm_q1q2_score": 0.6067598889594846}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nstruct Triangle\n{\npublic:\n    Triangle(Eigen::Vector3d a_vertex0, Eigen::Vector3d a_vertex1,\n             Eigen::Vector3d a_vertex2)\n        : vertex0(a_vertex0), vertex1(a_vertex1), vertex2(a_vertex2)\n    {\n    }\n\n    Eigen::Vector3d vertex0;\n    Eigen::Vector3d vertex1;\n    Eigen::Vector3d vertex2;\n};\n\nclass RayCaster\n{\npublic:\n    RayCaster(Eigen::Vector3d ray_origin, Eigen::Vector3d direction_vector);\n    ~RayCaster();\n\n    /* Tomas Moeller algorithm */\n    bool CheckTriangleIntersection(const Triangle& triangle);\n\nprivate:\n    Eigen::Vector3d ray_origin_;\n    Eigen::Vector3d direction_vector_;\n};\n", "meta": {"hexsha": "588bfbb0c423a5af7883256c2a279457f5dab84c", "size": 647, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "61_Tomas-Moeller/inc/TomasMoeller.hpp", "max_stars_repo_name": "nishiys/CFDbasics", "max_stars_repo_head_hexsha": "638372956e31f8392f20b0d2027762cc4f9ef10b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-19T10:17:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-19T10:17:17.000Z", "max_issues_repo_path": "61_Tomas-Moeller/inc/TomasMoeller.hpp", "max_issues_repo_name": "nishiys/CFDbasics", "max_issues_repo_head_hexsha": "638372956e31f8392f20b0d2027762cc4f9ef10b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "61_Tomas-Moeller/inc/TomasMoeller.hpp", "max_forks_repo_name": "nishiys/CFDbasics", "max_forks_repo_head_hexsha": "638372956e31f8392f20b0d2027762cc4f9ef10b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-19T10:22:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-19T10:22:36.000Z", "avg_line_length": 20.21875, "max_line_length": 76, "alphanum_fraction": 0.6970633694, "num_tokens": 171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.606737804084111}}
{"text": "#include <iostream>\n#include <boost/numeric/ublas/symmetric.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\nnamespace ublas = boost::numeric::ublas;\n\nublas::matrix<double> get_K(int N, double a0 = 2, double a1 = 2)\n{\n\tublas::identity_matrix<double> I(N, N);\n\tublas::matrix<double> m1 = 2.0 * I;\n\tm1(0, 0) = a0;\n\tm1(N-1, N-1) = a1;\n\n\tublas::symmetric_matrix<double, ublas::lower> m2(N, N);\n\tfor (unsigned i = 0; i < m2.size1(); ++ i)\n\t\tfor (unsigned j = 0; j <= i; ++ j)\n\t\t\tm2(i, j) = (j == i-1)? -1:0;\n\treturn m1 + m2;\n}\n\nint main()\n{\n\tint N = 3;\n\tdouble h = 1.0 / (N - 1);\n\tublas::matrix<double> K = get_K(N);\n\tstd::cout << K << std::endl;\n\n\tublas::matrix<double> A = get_K(N, 1, 1);\n\tstd::cout << A << std::endl;\n\n\tublas::matrix<double> A1 = get_K(N, 2, 1);\n\tstd::cout << A1 << std::endl;\n\n\tublas::matrix<double> A2 = get_K(N, 1, 2);\n\tstd::cout << A2 << std::endl;\n\n\tublas::matrix<double> Kinv(N, N);\n\tKinv.assign(ublas::identity_matrix<double> (K.size1()));\n\tublas::permutation_matrix<size_t> pm(K.size1());\n\tublas::lu_factorize(K, pm);\n\tublas::lu_substitute(K, pm, Kinv);\n\n\tstd::cout << Kinv << std::endl;\n\n\tdouble* tmp = (double*) Kinv.data().begin();\n\tint size = Kinv.data().size();\n\n\tfor (int i = 0; i < size; ++i)\n\t\tstd::cout << tmp[i] << std::endl;\n\treturn 0;\n}", "meta": {"hexsha": "89c227d1f7a4c1495792df9bd9ee441792c5d41b", "size": 1304, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matrix_factory.cpp", "max_stars_repo_name": "yoon-gu/la-table", "max_stars_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matrix_factory.cpp", "max_issues_repo_name": "yoon-gu/la-table", "max_issues_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matrix_factory.cpp", "max_forks_repo_name": "yoon-gu/la-table", "max_forks_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0769230769, "max_line_length": 64, "alphanum_fraction": 0.6035276074, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89330940889474, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.6067167338961725}}
{"text": "#pragma once\n#ifndef _RAY_SPHERE_\n#define _RAY_SPHERE_\n\n#include <Eigen/Core>\n\nusing namespace Eigen;\n\nnamespace raytracer\n{\n\nclass Sphere : public Surface\n{\npublic:\n  Sphere(Vector3f center, float radius, std::string material_name = \"\") :\n    Surface(center, material_name),\n    radius_(radius),\n    radius2_(radius * radius)\n  {\n  }\n\n  bool Intersect(const Ray& ray, HitData& hit) override\n  {\n    // Calculate ray-sphere intersection using geometric approach\n    Vector3f posray = position_ - ray.position();\n    // Cos theta of hit point and ray\n    float s = posray.dot(ray.direction());\n    float length2 = posray.squaredNorm();\n\n    // If the angle between the ray and the direction is less than 90\n    if (s > 0.0f)\n    {\n      float m2 = length2 - s * s;\n\n      if (m2 < radius2_)\n      {\n        float q = std::sqrt(radius2_ - m2);\n\n        hit.t = (length2 > radius2_) ? s - q : s + q;\n        hit.hit_point = ray.evaluate(hit.t);\n\n        return (hit.t > 0.0f && hit.t < hit.tMax);\n      }\n    }\n\n    return false;\n  }\n\n  Vector3f normal(const Vector3f& point) const\n  {\n    return (point - position_).normalized();\n  }\nprivate:\n  float radius_, radius2_;\n};\n\n}\n\n#endif /* end of include guard: _RAY_SPHERE_ */\n", "meta": {"hexsha": "11f8bc09ca307ffb62ea61cfad8ab9a0d10fb7c3", "size": 1223, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PA4/src/primitives/surface_sphere.hpp", "max_stars_repo_name": "dowoncha/COMP575", "max_stars_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PA4/src/primitives/surface_sphere.hpp", "max_issues_repo_name": "dowoncha/COMP575", "max_issues_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PA4/src/primitives/surface_sphere.hpp", "max_forks_repo_name": "dowoncha/COMP575", "max_forks_repo_head_hexsha": "6e48bdd80cb1a3e677c07655640efa941325e59c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3833333333, "max_line_length": 73, "alphanum_fraction": 0.6287816844, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6067167184224498}}
{"text": "#ifndef FAST_GICP_SO3_HPP\n#define FAST_GICP_SO3_HPP\n\n#include <Eigen/Core>\n\nnamespace fast_gicp {\n\ninline Eigen::Matrix3f skew(const Eigen::Vector3f& x) {\n  Eigen::Matrix3f skew = Eigen::Matrix3f::Zero();\n  skew(0, 1) = -x[2];\n  skew(0, 2) = x[1];\n  skew(1, 0) = x[2];\n  skew(1, 2) = -x[0];\n  skew(2, 0) = -x[1];\n  skew(2, 1) = x[0];\n\n  return skew;\n}\n\n}\n\n#endif", "meta": {"hexsha": "08f7bfb23521a4ed1f89618ead64af10305f57d8", "size": 362, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fast_gicp/so3/so3.hpp", "max_stars_repo_name": "zcbmlijygrdwa/fast_gicp", "max_stars_repo_head_hexsha": "a48f0338d9f8166e8734aa01b045bdb1797364a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-02-27T08:15:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T11:47:21.000Z", "max_issues_repo_path": "include/fast_gicp/so3/so3.hpp", "max_issues_repo_name": "shuoshuoxu/fast_gicp", "max_issues_repo_head_hexsha": "ff50fd65b79fa49351e2b44ebd5f9d6a337a7090", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T09:15:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-07T09:15:20.000Z", "max_forks_repo_path": "include/fast_gicp/so3/so3.hpp", "max_forks_repo_name": "MrBoriska/fast_gicp", "max_forks_repo_head_hexsha": "9dd47c28b6b475b3a518e6ab1f5fa7c915594445", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-04T06:23:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T06:23:19.000Z", "avg_line_length": 16.4545454545, "max_line_length": 55, "alphanum_fraction": 0.6049723757, "num_tokens": 150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.606656481994219}}
{"text": "/**\n   \\file powell_method.hpp\n   \\brief powerll optimization method\n   \\author Junhua Gu\n */\n\n#ifndef POWELL_METHOD\n#define POWELL_METHOD\n#define OPT_HEADER\n#include <core/optimizer.hpp>\n//#include <blitz/array.h>\n#include <limits>\n#include <cassert>\n#include <cmath>\n#include \"../linmin/linmin.hpp\"\n#include <algorithm>\n#include <iostream>\n\nnamespace opt_utilities\n{\n  /**\n     \\brief Impliment of an optimization method\n     \\tparam rT return type of the object function\n     \\tparam pT parameter type of the object function\n   */\n  template <typename rT,typename pT>\n  class powell_method\n    :public opt_method<rT,pT>\n  {\n  public:\n    typedef pT array1d_type;\n    typedef rT T;\n  private:\n    func_obj<rT,pT>* p_fo;\n    optimizer<rT,pT>* p_optimizer;\n    volatile bool bstop;\n    //typedef blitz::Array<rT,2> array2d_type;\n\n    const char* do_get_type_name()const\n    {\n      return \"powell method\";\n    }\n  private:\n    array1d_type start_point;\n    array1d_type end_point;\n\n  private:\n    int ncom;\n    array1d_type pcom_p;\n    array1d_type xicom_p;\n    rT threshold;\n    T** xi;\n    T* xi_1d;\n  private:\n    rT func(const pT& x)\n    {\n      assert(p_fo!=NULL_PTR);\n      return p_fo->eval(x);\n    }\n\n\n  private:\n    void clear_xi()\n    {\n      if(xi_1d!=NULL_PTR)\n\t{\n\t  delete[] xi_1d;\n\t}\n      if(xi!=NULL_PTR)\n\t{\n\t  delete[] xi;\n\t}\n    }\n\n    void init_xi(int n)\n    {\n      clear_xi();\n      xi_1d=new T[n*n];\n      xi=new T*[n];\n      for(int i=0;i!=n;++i)\n\t{\n\t  xi[i]=xi_1d+i*n;\n\t}\n      for(int i=0;i!=n;++i)\n\t{\n\t  for(int j=0;j!=n;++j)\n\t    {\n\t      xi[i][j]=(j==i?1:0);\n\t    }\n\t}\n    }\n\n\n\n    void powell(array1d_type& p,const T ftol,\n\t   int& iter,T& fret)\n    {\n      const int ITMAX=200;\n      const T TINY=std::numeric_limits<T>::epsilon();\n      int i,j,ibig;\n      T del,fp,fptt,t;\n      int n=(int)get_size(p);\n      array1d_type pt(n);\n      array1d_type ptt(n);\n      array1d_type xit(n);\n      fret=p_fo->eval(p);\n\n      for(j=0;j<n;++j)\n\t{\n\t  //get_element(pt,j)=get_element(p,j);\n\t  set_element(pt,j,get_element(p,j));\n\t}\n      for(iter=0;!bstop;++iter)\n\t{\n\t  fp=fret;\n\t  ibig=0;\n\t  del=0.0;\n\t  for(i=0;i<n;++i)\n\t    {\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n\t      for(j=0;j<n;++j)\n\t\t{\n\t\t  //get_element(xit,j)=xi[j][i];\n\t\t  set_element(xit,j,xi[j][i]);\n\t\t}\n\t      fptt=fret;\n\t      linmin(p,xit,fret,(*p_fo));\n\t      if((fptt-fret)>del)\n\t\t{\n\t\t  del=fptt-fret;\n\t\t  ibig=i+1;\n\t\t}\n\t    }\n\t  if(T(2.)*(fp-fret)<=ftol*(tabs(fp)+tabs(fret))+TINY)\n\t    {\n\t      return;\n\t    }\n\t  if(iter==ITMAX)\n\t    {\n\t      std::cerr<<\"powell exceeding maximun iterations.\"<<std::endl;\n\t      return;\n\t    }\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n\t  for(j=0;j<n;++j)\n\t    {\n\t      //get_element(ptt,j)=T(2.)*get_element(p,j)-get_element(pt,j);\n\t      set_element(ptt,j,T(2.)*get_element(p,j)-get_element(pt,j));\n\t      //get_element(xit,j)=\n\t      //get_element(p,j)-get_element(pt,j);\n\t      set_element(xit,j,get_element(p,j)-get_element(pt,j));\n\t      //get_element(pt,j)=get_element(p,j);\n\t      set_element(pt,j,get_element(p,j));\n\t    }\n\t  fptt=func(ptt);\n\t  if(fptt<fp)\n\t    {\n\t      t=T(2.)*(fp-T(2.)*fret+fptt)*sqr(T(fp-fret-del))-del*sqr(T(fp-fptt));\n\t      if(t<T(0.))\n\t\t{\n\t\t  linmin(p,xit,fret,*p_fo);\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n\t\t  for(j=0;j<n;++j)\n\t\t    {\n\t\t      xi[j][ibig-1]=xi[j][n-1];\n\t\t      xi[j][n-1]=get_element(xit,j);\n\n\t\t    }\n\t\t}\n\t    }\n\t}\n    }\n\n\n  public:\n\n    powell_method()\n      :threshold(1e-4),xi(NULL_PTR),xi_1d(NULL_PTR)\n    {}\n\n    virtual ~powell_method()\n    {\n      clear_xi();\n    };\n\n    powell_method(const powell_method<rT,pT>& rhs)\n      :opt_method<rT,pT>(rhs),p_fo(rhs.p_fo),p_optimizer(rhs.p_optimizer),\n       start_point(rhs.start_point),\n       end_point(rhs.end_point),\n       ncom(rhs.ncom),\n       threshold(rhs.threshold),xi(NULL_PTR),xi_1d(NULL_PTR)\n    {\n    }\n\n    powell_method<rT,pT>& operator=(const powell_method<rT,pT>& rhs)\n    {\n      threshold=rhs.threshold;\n      xi=0;\n      xi_1d=0;\n      p_fo=rhs.p_fo;\n      p_optimizer=rhs.p_optimizer;\n      start_point=rhs.start_point;\n      end_point=rhs.end_point;\n      ncom=rhs.ncom;\n      threshold=rhs.threshold;\n    }\n\n    opt_method<rT,pT>* do_clone()const\n    {\n      return new powell_method<rT,pT>(*this);\n    }\n\n    void do_set_start_point(const array1d_type& p)\n    {\n      resize(start_point,get_size(p));\n      opt_eq(start_point,p);\n    }\n\n    array1d_type do_get_start_point()const\n    {\n      return start_point;\n    }\n\n    void do_set_lower_limit(const array1d_type&)\n    {}\n\n    void do_set_upper_limit(const array1d_type&)\n    {}\n\n    void do_set_precision(rT t)\n    {\n      threshold=t;\n    }\n\n    rT do_get_precision()const\n    {\n      return threshold;\n    }\n\n    void do_set_optimizer(optimizer<rT,pT>& o)\n    {\n      p_optimizer=&o;\n      p_fo=p_optimizer->ptr_func_obj();\n    }\n\n\n\n    pT do_optimize()\n    {\n      bstop=false;\n      init_xi((int)get_size(start_point));\n\n\n      for(int i=0;i<(int)get_size(start_point);++i)\n\t{\n\t  for(int j=0;j<(int)get_size(start_point);++j)\n\t    {\n\t      xi[i][j]=(i==j)?1:0;\n\t    }\n\t}\n\n      int iter=100;\n      opt_eq(end_point,start_point);\n      rT fret;\n      powell(end_point,threshold,iter,fret);\n      return end_point;\n    }\n\n    void do_stop()\n    {\n      bstop=true;\n    }\n\n  };\n\n}\n\n\n#endif\n//EOF\n", "meta": {"hexsha": "a80f3da31d60393f25bdc5512b78994a9bb1f2bb", "size": 5322, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "methods/powell/powell_method.hpp", "max_stars_repo_name": "liweitianux/opt_utilities", "max_stars_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "methods/powell/powell_method.hpp", "max_issues_repo_name": "liweitianux/opt_utilities", "max_issues_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "methods/powell/powell_method.hpp", "max_forks_repo_name": "liweitianux/opt_utilities", "max_forks_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T16:14:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-05T16:14:44.000Z", "avg_line_length": 18.6083916084, "max_line_length": 76, "alphanum_fraction": 0.5744081172, "num_tokens": 1670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677699040321, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6066564799502047}}
{"text": "#ifndef PRECONDITIONED_CONJUGATE_GRADIENT_H\n#define PRECONDITIONED_CONJUGATE_GRADIENT_H\n#include <Eigen/Dense>\n#include \"mtao/solvers/linear/linear.hpp\"\n#include \"mtao/solvers/cholesky/ldlt.hpp\"\n#include <iostream>\n\n\nnamespace mtao::solvers::linear {\ntemplate <typename MatrixType, typename VectorType, typename Preconditioner>\n    struct PCGSolver;\n\ntemplate <typename MatrixType, typename VectorType, typename Preconditioner>\nstruct solver_traits<PCGSolver< MatrixType, VectorType, Preconditioner> > {\n    using Scalar = typename VectorType::Scalar;\n    using Matrix = MatrixType;\n    using Vector = VectorType;\n};\n\n\ntemplate <typename MatrixType, typename VectorType, typename Preconditioner>\nstruct PCGSolver: public IterativeLinearSolver<PCGSolver< MatrixType, VectorType, Preconditioner> >\n{\n    typedef MatrixType Matrix;\n    typedef VectorType Vector;\n    typedef typename Vector::Scalar Scalar;\n    using Base = IterativeLinearSolver<PCGSolver< MatrixType, VectorType, Preconditioner> >;\n    using Base::A ;\n    using Base::b ;\n    using Base::x ;\n    using Base::Base;\n    void compute() \n    {\n        precond = Preconditioner(A());\n        r = b()-A()*x();\n        precond->solve(r,z);\n        p = z;\n        Ap = A()*p;\n        rdz = r.dot(z);\n    }\n    Scalar error()\n    {\n        return r.template lpNorm<Eigen::Infinity>();\n    }\n\n    void step()\n    {\n        alpha = (rdz)/(p.dot(Ap));\n        x()+=alpha * p;\n        r-=alpha * Ap;\n        precond->solve(r,z);\n        beta=1/rdz;\n        rdz = r.dot(z);\n        beta*=rdz;\n        p=z+beta*p;\n        Ap=A()*p;\n    }\nprivate:\n    Vector r;\n    Vector z;\n    Vector p;\n    Vector Ap;\n    Scalar rdz;\n    Scalar alpha, beta;\n    std::optional<Preconditioner> precond;\n\n};\n\ntemplate <typename Preconditioner, typename Matrix, typename Vector>\nvoid PCGSolve(const Matrix & A, const Vector & b, Vector & x)\n{\n    auto residual = (b-A*x).template lpNorm<Eigen::Infinity>();\n    auto solver = PCGSolver<Matrix,Vector, Preconditioner>(5*A.rows(), 1e-5*residual);\n    //auto solver = IterativeLinearSolver<PreconditionedConjugateGradientCapsule<Matrix,Vector, Preconditioner> >(A.rows(), 1e-5);\n    solver.solve(A,b,x);\n    x = solver.x();\n}\n\n\ntemplate <typename Matrix, typename Vector>\nvoid DenseCholeskyPCGSolve(const Matrix & A, const Vector & b, Vector & x)\n{\n    PCGSolve<cholesky::DenseLDLT_MIC0<std::decay_t<decltype(A)>> >(A,b,x);\n}\n\ntemplate <typename Matrix, typename Vector>\nvoid SparseCholeskyPCGSolve(const Matrix & A, const Vector & b, Vector & x)\n{\n    PCGSolve<cholesky::SparseLDLT_MIC0<Matrix,Vector> >(A,b,x);\n\n}\ntemplate <typename Matrix, typename Vector>\nvoid CholeskyPCGSolve(const Matrix & A, const Vector & b, Vector & x)\n{\n    PCGSolve<cholesky::LDLT_MIC0<Matrix,Vector> >(A,b,x);\n\n}\n\n}\n\n\n\n\n#endif\n", "meta": {"hexsha": "b9866dcabd2f849f8acaf0159ca8fd5146b21ea3", "size": 2785, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/solvers/linear/preconditioned_conjugate_gradient.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/solvers/linear/preconditioned_conjugate_gradient.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/solvers/linear/preconditioned_conjugate_gradient.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5238095238, "max_line_length": 130, "alphanum_fraction": 0.671454219, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095495, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6066564761444544}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <boost/numeric/odeint.hpp>\n#include <smooth/bundle.hpp>\n#include <smooth/compat/odeint.hpp>\n#include <smooth/feedback/pid.hpp>\n#include <smooth/se2.hpp>\n\n#include <chrono>\n\n#ifdef ENABLE_PLOTTING\n#include <matplot/matplot.h>\n#endif\n\nusing namespace std::chrono_literals;\nusing namespace boost::numeric::odeint;\n\nusing Time = std::chrono::duration<double>;\n\nint main()\n{\n  smooth::feedback::PIDParams prm{};\n  smooth::feedback::PID<Time, smooth::SE2d> pid(prm);\n\n  // set desired trajectory\n  Eigen::Vector3d vdes(1, 0, 0.4);\n  auto xdes = [&vdes](Time t) -> decltype(pid)::TrajectoryReturnT {\n    return std::make_tuple(\n      smooth::SE2d(smooth::SO2d(M_PI_2), Eigen::Vector2d(2.5, 0)) + (t.count() * vdes),\n      vdes,\n      Eigen::Vector3d::Zero());\n  };\n\n  pid.set_xdes(xdes);\n\n  // input variable\n  Eigen::Vector2d u;\n\n  // prepare for integrating the closed-loop system\n  using State = smooth::Bundle<smooth::SE2d, Eigen::Vector3d>;\n  using Deriv = typename State::Tangent;\n  runge_kutta4<State, double, Deriv, double, vector_space_algebra> stepper{};\n  const auto ode = [&u](const State & x, Deriv & d, double) {\n    d.template head<3>() = x.part<1>();\n    d.template tail<3>() << u(0), 0, u(1);\n  };\n\n  State x(smooth::SE2d::Identity(), Eigen::Vector3d::Zero());\n  std::vector<double> tvec, xvec, yvec, u1vec, u2vec;\n\n  // integrate closed-loop system\n  for (std::chrono::milliseconds t = 0s; t < 30s; t += 50ms) {\n    // compute input\n    Eigen::Vector3d a = pid(t, x.part<0>(), x.part<1>());\n\n    // input allocation from desired acceleration\n    u(0) = std::clamp<double>(a(0), -1, 1);               // throtte <- a_x\n    u(1) = std::clamp<double>(a(2) + 0.3 * a(1), -1, 1);  // steering <- a_Yaw + 0.3 a_y\n\n    // store data\n    tvec.push_back(duration_cast<Time>(t).count());\n    xvec.push_back(x.part<0>().r2().x());\n    yvec.push_back(x.part<0>().r2().y());\n\n    u1vec.push_back(u(0));\n    u2vec.push_back(u(1));\n\n    // step dynamics\n    stepper.do_step(ode, x, 0, 0.05);\n  }\n\n#ifdef ENABLE_PLOTTING\n  matplot::figure();\n  matplot::hold(matplot::on);\n  matplot::title(\"Path\");\n\n  matplot::plot(xvec, yvec)->line_width(2);\n  matplot::plot(\n    matplot::transform(tvec, [&](auto t) { return std::get<0>(xdes(Time(t))).r2().x(); }),\n    matplot::transform(tvec, [&](auto t) { return std::get<0>(xdes(Time(t))).r2().y(); }),\n    \"k--\")\n    ->line_width(2);\n  matplot::legend({\"actual\", \"desired\"});\n\n  matplot::figure();\n  matplot::hold(matplot::on);\n  matplot::title(\"Inputs\");\n  matplot::plot(tvec, u1vec)->line_width(2);\n  matplot::plot(tvec, u2vec)->line_width(2);\n  matplot::legend({\"u1\", \"u2\"});\n\n  matplot::show();\n#else\n  std::cout << \"TRAJECTORY:\" << std::endl;\n  for (auto i = 0u; i != tvec.size(); ++i) {\n    std::cout << \"t=\" << tvec[i] << \": x=\" << xvec[i] << \", y=\" << yvec[i] << std::endl;\n  }\n#endif\n}\n", "meta": {"hexsha": "c9c7f6823272441a82ab56df48c3f42b948e938e", "size": 4124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/pid_se2.cpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "examples/pid_se2.cpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "examples/pid_se2.cpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 33.5284552846, "max_line_length": 90, "alphanum_fraction": 0.6600387973, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516188, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6066564737480938}}
{"text": "#include \"parameter.hpp\"\n\n#include <iostream>\n#include <cassert>\n\n#include <Eigen/Dense>\n\nint main()\n{\n    // Scalar\n    op::Parameter scalar_param_1(1.0);\n    op::Parameter scalar_param_2(2.0);\n    op::Parameter scalar_param_3(3.0);\n    op::Parameter scalar_param_4(4.0);\n    double scalar = 3.;\n    op::Parameter scalar_param_ptr(&scalar);\n\n    op::Parameter result_scalar = scalar_param_ptr + scalar_param_2 + scalar_param_ptr + scalar_param_2;\n    assert(result_scalar.get_value() == 10.);\n\n    result_scalar = scalar_param_ptr + scalar_param_2 - scalar_param_ptr - scalar_param_2;\n    assert(result_scalar.get_value() == 0.);\n\n    result_scalar = scalar_param_ptr * scalar_param_2 - scalar_param_ptr * scalar_param_2;\n    assert(result_scalar.get_value() == 0.);\n\n    result_scalar = scalar_param_ptr * scalar_param_2 * scalar_param_ptr * scalar_param_2;\n    assert(result_scalar.get_value() == 36.);\n\n    scalar = 1.;\n    result_scalar = scalar_param_2 + scalar_param_ptr;\n    assert(result_scalar.get_value() == 3.);\n    result_scalar = scalar_param_2 - scalar_param_ptr;\n    assert(result_scalar.get_value() == 1.);\n    result_scalar = scalar_param_2 * scalar_param_ptr;\n    assert(result_scalar.get_value() == 2.);\n    result_scalar = scalar_param_2 / scalar_param_ptr;\n    assert(result_scalar.get_value() == 2.);\n\n    // Matrix\n    // multiply 2x2/2x2\n    Eigen::Matrix2d dyn_matrix;\n    dyn_matrix << 1., 2., 3., 4.;\n    op::Parameter matrix_parameter(&dyn_matrix);\n    op::Parameter result_matrix = matrix_parameter * matrix_parameter;\n\n    Eigen::Matrix2d reference_matrix;\n\n    reference_matrix << 7., 10., 15., 22.;\n    assert(result_matrix.get_values() == reference_matrix);\n\n    dyn_matrix(1, 0) = 1.;\n    reference_matrix << 3., 10., 5., 18.;\n    assert(result_matrix.get_values() == reference_matrix);\n\n    dyn_matrix(1, 0) = 3.;\n\n    Eigen::Vector2d dyn_vector(1., 2.);\n\n    // multiply 2x2/2x1\n    op::Parameter vector_parameter(&dyn_vector);\n    result_matrix = matrix_parameter * vector_parameter;\n    assert(result_matrix.get_values() == Eigen::Vector2d(5., 11));\n\n    // multiply 1x2/2x2\n    result_matrix = vector_parameter.transpose() * matrix_parameter;\n    assert(result_matrix.get_values() == Eigen::Vector2d(7., 10.).transpose());\n\n    // multiply 1x1/2x2\n    result_matrix = scalar_param_2 * matrix_parameter;\n    reference_matrix << 2., 4., 6., 8.;\n    assert(result_matrix.get_values() == reference_matrix);\n\n    // multiply 2x2/1x1\n    result_matrix = matrix_parameter * scalar_param_2;\n    assert(result_matrix.get_values() == reference_matrix);\n\n    Eigen::Matrix3d m1, m2;\n    m1.setRandom();\n    m2.setRandom();\n    op::Parameter eigen1(&m1);\n    op::Parameter eigen2(m2);\n\n    scalar = 3.;\n    Eigen::MatrixXd m = scalar * m1 * m2;\n    op::Parameter result = scalar_param_ptr * eigen1 * eigen2;\n    assert((result.get_values() - m).cwiseAbs().sum() < 1e-10);\n\n    scalar = 10.;\n    m = scalar * m1 * m2;\n    assert((result.get_values() - m).cwiseAbs().sum() < 1e-10);\n\n    Eigen::MatrixXd m3x2(3, 2);\n    Eigen::MatrixXd m2x5(2, 5);\n    m3x2.setRandom();\n    m2x5.setRandom();\n\n    m = m3x2 * m2x5;\n    result = op::Parameter(m3x2) * op::Parameter(m2x5);\n\n    assert((result.get_values() - m).cwiseAbs().sum() < 1e-10);\n\n    std::cout << \"All tests were successful.\"\n              << \"\\n\";\n}", "meta": {"hexsha": "bdad664b25fc7667bd68b969c0278d7a1806e00a", "size": 3332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/parameter_test.cpp", "max_stars_repo_name": "EmbersArc/socp_interface", "max_stars_repo_head_hexsha": "d569ca7315a808e1070d1d01148018f2148ce672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-24T00:50:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T21:35:17.000Z", "max_issues_repo_path": "src/tests/parameter_test.cpp", "max_issues_repo_name": "EmbersArc/socp_interface", "max_issues_repo_head_hexsha": "d569ca7315a808e1070d1d01148018f2148ce672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/parameter_test.cpp", "max_forks_repo_name": "EmbersArc/socp_interface", "max_forks_repo_head_hexsha": "d569ca7315a808e1070d1d01148018f2148ce672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-07-22T01:34:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-14T12:45:24.000Z", "avg_line_length": 31.7333333333, "max_line_length": 104, "alphanum_fraction": 0.6677671068, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6066398633281516}}
{"text": "#include <terrain_server/feature/CurvatureFeature.h>\n#include <Eigen/Dense>\n\n\nnamespace terrain_server\n{\n\nnamespace feature\n{\n\nCurvatureFeature::CurvatureFeature() :\n\t\tpositive_threshold_(6.0), negative_threshold_(-6.0)\n{\n\tname_ = \"Curvature\";\n}\n\nCurvatureFeature::~CurvatureFeature()\n{\n\n}\n\n\nvoid CurvatureFeature::computeCost(double& cost_value,\n\t\t\t\t\t\t\t\t   const dwl::Terrain& terrain_info)\n{\n\tdouble curvature = terrain_info.curvature;\n\n\t// The worse condition\n\tif (curvature * 10000 > 9) {\n\t\tcost_value = max_cost_;\n\t\treturn;\n\t}\n\n\tif (curvature > positive_threshold_)\n\t\tcost_value = 0.;\n\telse if (curvature < negative_threshold_)\n\t\tcost_value = max_cost_;\n\telse\n\t\tcost_value = max_cost_\n\t\t\t\t- log((curvature - negative_threshold_)\n\t\t\t\t\t\t\t\t/ (positive_threshold_ - negative_threshold_));\n}\n\n} //@namespace feature\n} //@namespace terrain\n", "meta": {"hexsha": "5a22e82897f12490d5113fdb0ae7c6de0823c756", "size": 839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/feature/CurvatureFeature.cpp", "max_stars_repo_name": "robot-locomotion/terrain-server", "max_stars_repo_head_hexsha": "fa797633e5f854ca8a7bf4814dd5dd58adb141ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-02-07T09:51:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T17:15:21.000Z", "max_issues_repo_path": "src/feature/CurvatureFeature.cpp", "max_issues_repo_name": "iit-DLSLab/terrain-server", "max_issues_repo_head_hexsha": "c5556d60413d746cfb7b6b506893c3add7c04b83", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/feature/CurvatureFeature.cpp", "max_forks_repo_name": "iit-DLSLab/terrain-server", "max_forks_repo_head_hexsha": "c5556d60413d746cfb7b6b506893c3add7c04b83", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-03-15T10:28:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T21:55:26.000Z", "avg_line_length": 18.2391304348, "max_line_length": 55, "alphanum_fraction": 0.7246722288, "num_tokens": 211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6066398463566621}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>\n// \n// This Source Code Form is subject to the terms of the Mozilla Public License \n// v. 2.0. If a copy of the MPL was not distributed with this file, You can \n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"kkt_inverse.h\"\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include \"EPS.h\"\n#include <cstdio>\n\ntemplate <typename T>\nIGL_INLINE void igl::kkt_inverse(\n  const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& A,\n  const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& Aeq,    \n  const bool use_lu_decomposition,\n  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& S)\n{\n  typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Mat;\n        // This threshold seems to matter a lot but I'm not sure how to\n        // set it\n  const T treshold = igl::FLOAT_EPS;\n  //const T treshold = igl::DOUBLE_EPS;\n\n  const int n = A.rows();\n  assert(A.cols() == n);\n  const int m = Aeq.rows();\n  assert(Aeq.cols() == n);\n\n  // Lagrange multipliers method:\n  Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> LM(n + m, n + m);\n  LM.block(0, 0, n, n) = A;\n  LM.block(0, n, n, m) = Aeq.transpose();\n  LM.block(n, 0, m, n) = Aeq;\n  LM.block(n, n, m, m).setZero();\n\n  Mat LMpinv;\n  if(use_lu_decomposition)\n  {\n    // if LM is close to singular, use at your own risk :)\n    LMpinv = LM.inverse();\n  }else\n  {\n    // use SVD\n    typedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vec; \n    Vec singValues;\n    Eigen::JacobiSVD<Mat> svd;\n    svd.compute(LM, Eigen::ComputeFullU | Eigen::ComputeFullV );\n    const Mat& u = svd.matrixU();\n    const Mat& v = svd.matrixV();\n    const Vec& singVals = svd.singularValues();\n\n    Vec pi_singVals(n + m);\n    int zeroed = 0;\n    for (int i=0; i<n + m; i++)\n    {\n      T sv = singVals(i, 0);\n      assert(sv >= 0);      \n                 // printf(\"sv: %lg ? %lg\\n\",(double) sv,(double)treshold);\n      if (sv > treshold) pi_singVals(i, 0) = T(1) / sv;\n      else \n      {\n        pi_singVals(i, 0) = T(0);\n        zeroed++;\n      }\n    }\n\n    printf(\"kkt_inverse : %i singular values zeroed (threshold = %e)\\n\", zeroed, treshold);\n    Eigen::DiagonalMatrix<T, Eigen::Dynamic> pi_diag(pi_singVals);\n\n    LMpinv = v * pi_diag * u.transpose();\n  }\n  S = LMpinv.block(0, 0, n, n + m);\n\n  //// debug:\n  //mlinit(&g_pEngine);\n  //\n  //mlsetmatrix(&g_pEngine, \"A\", A);\n  //mlsetmatrix(&g_pEngine, \"Aeq\", Aeq);\n  //mlsetmatrix(&g_pEngine, \"LM\", LM);\n  //mlsetmatrix(&g_pEngine, \"u\", u);\n  //mlsetmatrix(&g_pEngine, \"v\", v);\n  //MatrixXd svMat = singVals;\n  //mlsetmatrix(&g_pEngine, \"singVals\", svMat);\n  //mlsetmatrix(&g_pEngine, \"LMpinv\", LMpinv);\n  //mlsetmatrix(&g_pEngine, \"S\", S);\n\n  //int hu = 1;\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::kkt_inverse<double>(Eigen::Matrix<double, -1, -1, 0, -1, -1> const&, Eigen::Matrix<double, -1, -1, 0, -1, -1> const&, bool, Eigen::Matrix<double, -1, -1, 0, -1, -1>&);\n#endif\n", "meta": {"hexsha": "a3c3c8b574f73586da85636e20e15519abd42401", "size": 3026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/libigl/include/igl/kkt_inverse.cpp", "max_stars_repo_name": "chefmramos85/monster-mash", "max_stars_repo_head_hexsha": "239a41f6f178ca83c4be638331e32f23606b0381", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1125.0, "max_stars_repo_stars_event_min_datetime": "2021-02-01T09:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:50:40.000Z", "max_issues_repo_path": "third_party/libigl/include/igl/kkt_inverse.cpp", "max_issues_repo_name": "ryan-cranfill/monster-mash", "max_issues_repo_head_hexsha": "c1b906d996885f8a4011bdf7558e62e968e1e914", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T12:36:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T14:02:50.000Z", "max_forks_repo_path": "third_party/libigl/include/igl/kkt_inverse.cpp", "max_forks_repo_name": "ryan-cranfill/monster-mash", "max_forks_repo_head_hexsha": "c1b906d996885f8a4011bdf7558e62e968e1e914", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2021-02-13T10:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:55:20.000Z", "avg_line_length": 30.8775510204, "max_line_length": 186, "alphanum_fraction": 0.6136814276, "num_tokens": 991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6066398392211859}}
{"text": "#include \"FEAnalyzer.h\"\n\n#include <math.h>\n#include <algorithm>\n#include <array>\n#include <iostream>\n#include <vector>\n#include <Eigen/Dense>\n#include <QQuickItem>\n#include <QVariant>\n#include <QVariantList>\n#include <QQmlProperty>\n\nstruct InputNode\n{\n    Vec2f pos; // a vector2 with the (x , y) postion of the node in world space in m\n    bool isSupport; // true if input node cannot move\n};\n\nstruct InputMember\n{\n    float area; // cross sectional area of the member in m^2\n    float youngsModulus; // the youngs modulus of the member in (N / m^2) or Pa\n    unsigned nodeI; // the starting node index of the member\n    unsigned nodeJ; // the end node index of the member\n};\n\nstruct Output {\n    std::vector<Vec2f> nodeOffsets;\n    std::vector<float> memberStressIndicator;\n    Eigen::VectorXf stressForces;\n    Eigen::VectorXf error;\n};\n\nstruct Node\n{\n    int id; // the nodes id#\n    Vec2f pos; // a vector2 with the (x , y) postion of the node in world space in m\n    bool isSupport; // true if input node cannot move\n};\n\nstruct Member\n{\n    float area; // cross sectioal area of the memmber in m^2\n    float youngsModulus; // the youngs modulus of the member in (N/m^2) or Pa\n    Node nodeI; // the starting node of the member\n    Node nodeJ; // the end node of the member\n    float length; // the length of the member in m\n    float theta; // the angle of the beam\n    std::array<unsigned, 4> dofs; // global degrees of freedom\n    // values above this line should be supplied when passing into ComputeDisplacements\n    float stress; // will be the stress in the member in (N/m^2)\n    Eigen::MatrixXf k_global; // the local stiffness matrix\n    Eigen::MatrixXf L; // transformation Matrix\n};\n\nconst float m_per_px = 1.0f;\n\nfloat pixelToWorldX(float x) {\n    return x * m_per_px;\n}\n\nfloat worldToPixelOffsetX(float x) {\n    return x / m_per_px;\n}\n\nfloat pixelToWorldY(float y) {\n    return (900 - y) * m_per_px;\n}\n\nfloat worldToPixelOffsetY(float y) {\n    return -y / m_per_px;\n}\n\nOutput computeDisplacements(std::vector<InputNode> inNodes,\n                            std::vector<InputMember> inMembers,\n                            Eigen::VectorXf externalForces) {\n\n    std::vector<Node> nodes;\n    for (unsigned i = 0; i < inNodes.size(); ++i) {\n        InputNode in = inNodes[i];\n        Node node;\n        node.id = i;\n        node.pos = in.pos;\n        node.isSupport = in.isSupport;\n        nodes.push_back(node);\n    }\n\n    std::vector<Member> members;\n    for (unsigned i = 0; i < inMembers.size(); ++i) {\n        InputMember in = inMembers[i];\n        Member m;\n        m.area = in.area;\n        m.youngsModulus = in.youngsModulus;\n        m.nodeI = nodes[in.nodeI];\n        m.nodeJ = nodes[in.nodeJ];\n        Vec2f memberVector = m.nodeJ.pos - m.nodeI.pos;\n        m.length = magnitude(memberVector);\n        m.theta = atan2f(memberVector.y, memberVector.x);\n        m.dofs = {\n            in.nodeI * 2,\n            in.nodeI * 2 + 1,\n            in.nodeJ * 2,\n            in.nodeJ * 2 + 1\n        };\n\n        float C = cos(m.theta);\n        float S = sin(m.theta);\n        Eigen::MatrixXf matC(2,4);\n        matC << C,S,0,0,\n                0,0,C,S;\n        // m.L = matC;\n        //construct the member stiffness matrixes 'k' for each member\n        Eigen::MatrixXf matA(2, 2);\n        matA << C*C, C*S, C*S, S*S;\n        Eigen::MatrixXf k(4, 4);\n        k << matA, -matA, -matA, matA;\n        // m.L.transpose();\n        m.k_global = (m.area * m.youngsModulus / m.length) * k;\n        members.push_back(m);\n    }\n\n    Eigen::MatrixXf K(2*nodes.size(), 2*nodes.size());\n    K.setZero();  // new matrix size dof, dof, of floats is the struture stiffness matrix\n    for (const Member& member : members) {\n        //distribute the member stiffnesses to the structure stiffness matrix\n        for (unsigned i = 0; i < 4; i++) {\n            for (unsigned j = 0; j < 4; j++) {\n                int A = member.dofs[i];\n                int B = member.dofs[j];\n                K(A, B) += member.k_global(i, j);\n            }\n        }\n    }\n\n    Eigen::VectorXf& F = externalForces;\n    for (const Node& node : nodes) {\n        if (node.isSupport) {\n            K.row(node.id * 2).setZero();\n            K.col(node.id * 2).setZero();\n            K.row(node.id * 2 + 1).setZero();\n            K.col(node.id * 2 + 1).setZero();\n\n            F.row(node.id * 2).setZero();\n            F.row(node.id * 2 + 1).setZero();\n        }\n    }\n\n    // solve [K]{u}={F}\n    Eigen::VectorXf u = K.fullPivLu().solve(F);\n\n    for (unsigned i = 0; i < members.size(); ++i) {\n        Member& m = members[i];\n        Vec2f displacementI = { u(m.nodeI.id * 2), u(m.nodeI.id * 2 + 1) };\n        Vec2f displacementJ = { u(m.nodeJ.id * 2), u(m.nodeJ.id * 2 + 1) };\n        Vec2f totalDisplacement = displacementJ - displacementI;\n        Vec2f memberVector = m.nodeJ.pos - m.nodeI.pos;\n        Vec2f memberDirection = memberVector / magnitude(memberVector); // todo: ensure members are not 0-length\n        float projectedDisplacement = dot(totalDisplacement, memberDirection);\n        m.stress = projectedDisplacement * m.youngsModulus / m.length;\n    }\n\n    Output o;\n    o.nodeOffsets.resize(nodes.size());\n    for (unsigned i = 0; i < o.nodeOffsets.size(); ++i) {\n        o.nodeOffsets[i] = { u(i * 2), u(i * 2 + 1) };\n    }\n    o.memberStressIndicator.resize(members.size());\n    for (unsigned i = 0; i < o.memberStressIndicator.size(); ++i) {\n        o.memberStressIndicator[i] = members[i].stress;\n    }\n    Eigen::VectorXf stressForces(2*nodes.size());\n    stressForces.setZero();\n    for (unsigned i = 0; i < members.size(); ++i) {\n        const Member& member = members[i];\n        float alongBeamForce = member.area * member.stress;\n        float xForce = cosf(member.theta) * alongBeamForce;\n        float yForce = sinf(member.theta) * alongBeamForce;\n        stressForces(2*member.nodeI.id) += xForce;\n        stressForces(2*member.nodeI.id+1) += yForce;\n        stressForces(2*member.nodeJ.id) += -xForce;\n        stressForces(2*member.nodeJ.id+1) += -yForce;\n    }\n    o.stressForces = stressForces;\n    o.error = F - (K*u);\n    return o;\n}\n\ntemplate <class T>\nint index_of(const std::vector<T>& v, const T& value) {\n    auto it = std::find(v.cbegin(), v.cend(), value);\n    if (it == v.cend()) {\n        return -1;\n    } else {\n        return std::distance(v.cbegin(), it);\n    }\n}\n\nvoid addInitialBeamWeightToNodes(Eigen::VectorXf& forces,\n  const std::vector<InputNode>& inNodes,\n  const std::vector<InputMember>& inMembers) {\n  const float density = 7850.0f; // kg/m^3\n  const float g = -9.81f; //gravity m/s^2 in the y axis\n  for (unsigned i = 0; i < inMembers.size(); ++i) {\n    Vec2f v = inNodes[inMembers[i].nodeJ].pos - inNodes[inMembers[i].nodeI].pos;\n    float length = magnitude(v);\n    float mass = density * length * inMembers[i].area;\n    float force = mass * g;\n    float force_per_node = force / 2;\n    forces(2*inMembers[i].nodeI+1) += force_per_node;\n    forces(2*inMembers[i].nodeJ+1) += force_per_node;\n  }\n}\n\nstruct Input {\n    std::vector<InputNode> nodes;\n    std::vector<InputMember> members;\n};\n\nInput extractInput(const QVariantList& nodes,\n                   const QVariantList& beams) {\n    std::vector<InputNode> inNodes;\n    std::vector<QQuickItem*> items;\n    foreach(QVariant v, nodes) {\n        QQuickItem* node = qobject_cast<QQuickItem*>(v.value<QObject*>());\n        items.push_back(node);\n        InputNode n;\n        QVariant support = QQmlProperty::read(node, QStringLiteral(\"structural\"));\n        n.isSupport = support.toBool();\n        QVariant x = QQmlProperty::read(node, QStringLiteral(\"x\"));\n        n.pos.x = pixelToWorldX(x.toReal());\n        QVariant y = QQmlProperty::read(node, QStringLiteral(\"y\"));\n        n.pos.y = pixelToWorldY(y.toReal());\n        inNodes.push_back(n);\n    }\n\n    std::vector<InputMember> inMembers;\n    foreach(QVariant v, beams) {\n        QQuickItem* beam = qobject_cast<QQuickItem*>(v.value<QObject*>());\n\n        QVariant lav = QQmlProperty::read(beam, QStringLiteral(\"leftAnchor\"));\n        QQuickItem* la = qobject_cast<QQuickItem*>(lav.value<QObject*>());\n        int left_index = index_of(items, la);\n        QVariant rav = QQmlProperty::read(beam, QStringLiteral(\"rightAnchor\"));\n        QQuickItem* ra = qobject_cast<QQuickItem*>(rav.value<QObject*>());\n        int right_index = index_of(items, ra);\n        InputMember m;\n        m.area = 10100.f / 1e6f;\n        m.youngsModulus = 200.f * 1e9f;\n        m.nodeI = (unsigned)left_index;\n        m.nodeJ = (unsigned)right_index;\n        inMembers.push_back(m);\n    }\n\n    return { inNodes, inMembers };\n}\n\nFEAnalyzer::FEAnalyzer() {\n    in_ = new Input;\n    relaxation_ = 1.f;\n}\n\nFEAnalyzer::~FEAnalyzer() {\n    delete in_;\n}\n\nvoid FEAnalyzer::applyOutputToInput(const Output& o) {\n    for (unsigned i = 0; i < o.nodeOffsets.size(); ++i) {\n        in_->nodes[i].pos += (o.nodeOffsets[i] * relaxation_);\n    }\n}\n\nvoid FEAnalyzer::processBridge(const QVariantList& nodes,\n                               const QVariantList& beams) {\n    *in_ = extractInput(nodes, beams);\n    Eigen::VectorXf forces(2 * nodes.size());\n    forces.setZero();\n    addInitialBeamWeightToNodes(forces, in_->nodes, in_->members);\n    gravityForces_ = forces;\n    Output o = computeDisplacements(in_->nodes, in_->members, forces);\n    stressForces_ = o.stressForces;\n    applyOutputToInput(o);\n    emitCompleted(o);\n}\n\nvoid FEAnalyzer::emitCompleted(const Output& o) {\n    QVariantList nodeOffsets;\n    for (unsigned i = 0; i < o.nodeOffsets.size(); ++i) {\n        QVariantMap offset;\n        offset.insert(\"x\", worldToPixelOffsetX(o.nodeOffsets[i].x));\n        offset.insert(\"y\", worldToPixelOffsetY(o.nodeOffsets[i].y));\n        nodeOffsets.append(QVariant::fromValue(offset));\n    }\n    QVariantList beamStress;\n    for (unsigned i = 0; i < o.memberStressIndicator.size(); ++i) {\n        beamStress.append(QVariant::fromValue(o.memberStressIndicator[i]));\n    }\n    emit processingComplete(nodeOffsets, beamStress);\n\n    // check for success or failure\n    bool onlyLowError = std::all_of(\n        o.error.data(),\n        o.error.data() + o.error.rows(), [](float forceError){\n        return fabsf(forceError) < 10.f;\n    });\n    bool onlyLowStress = std::all_of(\n        o.memberStressIndicator.cbegin(),\n        o.memberStressIndicator.cend(), [](float stress){\n        return fabsf(stress) < 3.5e8;\n    });\n    bool onlySmallOffsets = std::all_of(\n        o.nodeOffsets.cbegin(),\n        o.nodeOffsets.cend(), [](Vec2f offset){\n        return fabsf(offset.x) < 100.f && fabsf(offset.y) < 100.f;\n    });\n\n    if (!onlyLowError || !onlyLowStress || !onlySmallOffsets) {\n        emit failed();\n    } else {\n        emit converged();\n    }\n}\n\nvoid FEAnalyzer::step() {\n    Eigen::VectorXf forces = gravityForces_ + stressForces_;\n    Output o = computeDisplacements(in_->nodes, in_->members, forces);\n    Eigen::VectorXf stressDifferences = stressForces_ - o.stressForces;\n    stressForces_ = o.stressForces;\n    applyOutputToInput(o);\n    emitCompleted(o);\n}\n\n/*\nint main()\n{\n\tstd::vector<InputNode> nodes = {\n\t\t{{0,40}, true},\n\t  {{20,40}, false},\n\t\t{{20,0}, true},\n\t\t{{50,0}, true},\n\t};\n\tstd::vector<InputMember> members = {\n\t\t{ 1.5, 1e7, 0, 1 },\n\t\t{ 1.0, 1e7, 2, 1 },\n\t\t{ 3.0, 1e7, 3, 1 },\n\t};\n\n\tEigen::VectorXf F(2 * nodes.size());\n\tF.setZero();\n\tF(2) = -4000;\n\tF(3) = -8000;\n\tOutput o = computeDisplacements(nodes, members, F);\n\tstd::cout << \"displacements:\" << std::endl;\n\tfor (unsigned i = 0; i < o.nodeOffsets.size(); ++i) {\n\t\tVec2f offset = o.nodeOffsets[i];\n\t\tstd::cout << offset.x << \",\" << offset.y << std::endl;\n\t}\n\treturn 0;\n}\n*/\n", "meta": {"hexsha": "6c62e157352bc205a85ab42046c513491b984fb1", "size": 11652, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "FEAnalyzer.cxx", "max_stars_repo_name": "cgmb/KongoniBridge", "max_stars_repo_head_hexsha": "5b2ee009965017aa2a8ec0f890698d666a402451", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FEAnalyzer.cxx", "max_issues_repo_name": "cgmb/KongoniBridge", "max_issues_repo_head_hexsha": "5b2ee009965017aa2a8ec0f890698d666a402451", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-30T22:58:54.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-30T22:58:54.000Z", "max_forks_repo_path": "FEAnalyzer.cxx", "max_forks_repo_name": "cgmb/KongoniBridge", "max_forks_repo_head_hexsha": "5b2ee009965017aa2a8ec0f890698d666a402451", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-10T14:52:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-10T14:52:14.000Z", "avg_line_length": 32.2770083102, "max_line_length": 112, "alphanum_fraction": 0.6048746996, "num_tokens": 3300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.606630710468586}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <ipc/utils/eigen_ext.hpp>\n\nnamespace ipc {\n\n/// @brief Compute the distance between a point and a plane.\n/// @note The distance is actually squared distance.\n/// @param p The point.\n/// @param origin The origin of the plane.\n/// @param normal The normal of the plane.\n/// @return The distance between the point and plane.\ntemplate <typename DerivedP, typename DerivedOrigin, typename DerivedNormal>\nauto point_plane_distance(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedOrigin>& origin,\n    const Eigen::MatrixBase<DerivedNormal>& normal)\n{\n    auto point_to_plane = (p - origin).dot(normal);\n    return point_to_plane * point_to_plane / normal.squaredNorm();\n}\n\n/// @brief Compute the distance between a point and a plane.\n/// @note The distance is actually squared distance.\n/// @param p The point.\n/// @param t0 The first vertex of the triangle.\n/// @param t1 The second vertex of the triangle.\n/// @param t2 The third vertex of the triangle.\n/// @return The distance between the point and plane.\ntemplate <\n    typename DerivedP,\n    typename DerivedT0,\n    typename DerivedT1,\n    typename DerivedT2>\nauto point_plane_distance(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedT0>& t0,\n    const Eigen::MatrixBase<DerivedT1>& t1,\n    const Eigen::MatrixBase<DerivedT2>& t2)\n{\n    assert(p.size() == 3);\n    assert(t0.size() == 3);\n    assert(t1.size() == 3);\n    assert(t2.size() == 3);\n\n    auto normal = cross(t1 - t0, t2 - t0);\n    return point_plane_distance(p, t0, normal);\n}\n\n// Symbolically generated derivatives;\nnamespace autogen {\n    void point_plane_distance_gradient(\n        double v01,\n        double v02,\n        double v03,\n        double v11,\n        double v12,\n        double v13,\n        double v21,\n        double v22,\n        double v23,\n        double v31,\n        double v32,\n        double v33,\n        double g[12]);\n\n    void point_plane_distance_hessian(\n        double v01,\n        double v02,\n        double v03,\n        double v11,\n        double v12,\n        double v13,\n        double v21,\n        double v22,\n        double v23,\n        double v31,\n        double v32,\n        double v33,\n        double H[144]);\n} // namespace autogen\n\n/// @brief Compute the gradient of the distance between a point and a plane.\n/// @note The distance is actually squared distance.\n/// @param[in] p The point.\n/// @param[in] origin The origin of the plane.\n/// @param[in] normal The normal of the plane.\n/// @param[out] grad The gradient of the distance wrt p.\ntemplate <\n    typename DerivedP,\n    typename DerivedOrigin,\n    typename DerivedNormal,\n    typename DerivedGrad>\nvoid point_plane_distance_gradient(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedOrigin>& origin,\n    const Eigen::MatrixBase<DerivedNormal>& normal,\n    Eigen::PlainObjectBase<DerivedGrad>& grad)\n{\n    grad = (2 * (p - origin).dot(normal)) / normal.squaredNorm() * normal;\n}\n\n/// @brief Compute the gradient of the distance between a point and a plane.\n/// @note The distance is actually squared distance.\n/// @param[in] p The point.\n/// @param[in] t0 The first vertex of the triangle.\n/// @param[in] t1 The second vertex of the triangle.\n/// @param[in] t2 The third vertex of the triangle.\n/// @param[out] grad The gradient of the distance wrt p, t0, t1, and t2.\ntemplate <\n    typename DerivedP,\n    typename DerivedT0,\n    typename DerivedT1,\n    typename DerivedT2,\n    typename DerivedGrad>\nvoid point_plane_distance_gradient(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedT0>& t0,\n    const Eigen::MatrixBase<DerivedT1>& t1,\n    const Eigen::MatrixBase<DerivedT2>& t2,\n    Eigen::PlainObjectBase<DerivedGrad>& grad)\n{\n    assert(p.size() == 3);\n    assert(t0.size() == 3);\n    assert(t1.size() == 3);\n    assert(t2.size() == 3);\n\n    grad.resize(p.size() + t0.size() + t1.size() + t2.size());\n    autogen::point_plane_distance_gradient(\n        p[0], p[1], p[2], t0[0], t0[1], t0[2], t1[0], t1[1], t1[2], t2[0],\n        t2[1], t2[2], grad.data());\n}\n\n/// @brief Compute the hessian of the distance between a point and a plane.\n/// @note The distance is actually squared distance.\n/// @param[in] p The point.\n/// @param[in] origin The origin of the plane.\n/// @param[in] normal The normal of the plane.\n/// @param[out] hess The hessian of the distance wrt p.\ntemplate <\n    typename DerivedP,\n    typename DerivedOrigin,\n    typename DerivedNormal,\n    typename DerivedHess>\nvoid point_plane_distance_hessian(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedOrigin>& origin,\n    const Eigen::MatrixBase<DerivedNormal>& normal,\n    Eigen::PlainObjectBase<DerivedHess>& hess)\n{\n    if (normal.cols() == 1) {\n        // (n\u00d71)(n\u00d71)\u1d40 = (n\u00d7n)\n        hess = 2 / normal.squaredNorm() * normal * normal.transpose();\n    } else {\n        assert(normal.rows() == 1);\n        // (1\u00d7n)\u1d40(1\u00d7n) = (n\u00d7n)\n        hess = 2 / normal.squaredNorm() * normal.transpose() * normal;\n    }\n}\n\n/// @brief Compute the hessian of the distance between a point and a plane.\n/// @note The distance is actually squared distance.\n/// @param[in] p The point.\n/// @param[in] t0 The first vertex of the triangle.\n/// @param[in] t1 The second vertex of the triangle.\n/// @param[in] t2 The third vertex of the triangle.\n/// @param[out] hess The hessian of the distance wrt p, t0, t1, and t2.\ntemplate <\n    typename DerivedP,\n    typename DerivedT0,\n    typename DerivedT1,\n    typename DerivedT2,\n    typename DerivedHess>\nvoid point_plane_distance_hessian(\n    const Eigen::MatrixBase<DerivedP>& p,\n    const Eigen::MatrixBase<DerivedT0>& t0,\n    const Eigen::MatrixBase<DerivedT1>& t1,\n    const Eigen::MatrixBase<DerivedT2>& t2,\n    Eigen::PlainObjectBase<DerivedHess>& hess)\n{\n    assert(p.size() == 3);\n    assert(t0.size() == 3);\n    assert(t1.size() == 3);\n    assert(t2.size() == 3);\n\n    hess.resize(\n        p.size() + t0.size() + t1.size() + t2.size(),\n        p.size() + t0.size() + t1.size() + t2.size());\n    autogen::point_plane_distance_hessian(\n        p[0], p[1], p[2], t0[0], t0[1], t0[2], t1[0], t1[1], t1[2], t2[0],\n        t2[1], t2[2], hess.data());\n}\n\n} // namespace ipc\n", "meta": {"hexsha": "eba6a541209019a0551b1d7294aae274f92d2e9f", "size": 6291, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/distance/point_plane.hpp", "max_stars_repo_name": "ipc-sim/ipc-toolk", "max_stars_repo_head_hexsha": "81873d0288810e30166d871419da4104329860e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T21:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:24:31.000Z", "max_issues_repo_path": "src/distance/point_plane.hpp", "max_issues_repo_name": "dbelgrod/ipc-toolkit", "max_issues_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T18:39:30.000Z", "max_forks_repo_path": "src/distance/point_plane.hpp", "max_forks_repo_name": "dbelgrod/ipc-toolkit", "max_forks_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T12:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T04:55:49.000Z", "avg_line_length": 31.7727272727, "max_line_length": 76, "alphanum_fraction": 0.6514067716, "num_tokens": 1715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.6066307086190188}}
{"text": "/*\n * File: fast_hankel_transform.cc\n * Created Date: 2019-09-11\n * Author: Lei Pan\n * Contact: <panlei7@gmail.com>\n *\n * Last Modified: Wednesday September 25th 2019 11:37:38 am\n *\n * MIT License\n *\n * Copyright (c) 2019 Lei Pan\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the 'Software'), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * -----\n * HISTORY:\n * Date      \t By\tComments\n * ----------\t---\n * ----------------------------------------------------------\n */\n\n#include \"fast_hankel_transform.hpp\"\n\n#include <Eigen/Dense>\n#include <boost/math/special_functions/bessel.hpp>\n#include <cmath>\n#include <complex>\n#include <fftw3.h>\n#include <fmt/format.h>\n#include <fmt/ostream.h>\n#include <iostream>\n\nusing namespace Eigen;\nusing std::abs;\nusing std::exp;\nusing std::log;\nusing std::pow;\n\nFastHankelTransform::FastHankelTransform(int num_sample, double ux, double uy)\n    : num_sample_(num_sample), ux_(ux), uy_(uy),\n      x_(VectorXd::Zero(num_sample_)), f_(VectorXd::Zero(num_sample_ + 1)),\n      phi_(new std::complex<double>[num_sample_ * 2]),\n      j1_(new std::complex<double>[num_sample_ * 2]) {\n  alpha_ = evaluate_alpha();\n  k0_ = evaluate_k0(alpha_);\n}\n\nFastHankelTransform::~FastHankelTransform() {\n  delete[] phi_;\n  delete[] j1_;\n}\n\ndouble FastHankelTransform::evaluate_alpha() {\n  auto func = [&](auto a) { return -log(1.0 - exp(-a)) / (num_sample_ - 1); };\n\n  const int maxiter = 100;\n  double alpha = 1.0;\n  for (auto i = 0; i < maxiter; ++i) {\n    alpha = func(alpha);\n  }\n  return alpha;\n}\n\ndouble FastHankelTransform::evaluate_k0(double alpha) {\n  double k0 = (2.0 * exp(alpha) + exp(2.0 * alpha)) /\n              (pow(1 + exp(alpha), 2) * (1 - exp(-2.0 * alpha)));\n  return k0;\n}\n\nVectorXd FastHankelTransform::sampling() {\n  x_updated_ = true;\n  x_(0) = (1.0 + exp(alpha_)) * exp(-alpha_ * num_sample_) / 2.0;\n  for (auto i = 1; i < num_sample_; ++i) {\n    x_(i) = x_(0) * exp(alpha_ * i);\n  }\n  return x_;\n}\n\nvoid FastHankelTransform::set_feval(const Ref<const VectorXd> &feval) {\n  assert(x_updated_ == true);\n  f_updated_ = true;\n  f_.head(num_sample_) = feval;\n}\n\nvoid FastHankelTransform::evaluate_phi() {\n  phi_[0] = k0_ * (f_(0) - f_(1)) * exp(alpha_ * (1 - num_sample_));\n  for (auto i = 1; i < num_sample_; ++i) {\n    phi_[i] = (f_(i) - f_(i + 1)) * exp(alpha_ * (i + 1 - num_sample_));\n  }\n  for (auto i = num_sample_; i < num_sample_ * 2; ++i) {\n    phi_[i] = 0.0;\n  }\n}\n\nvoid FastHankelTransform::evaluate_j1() {\n  for (auto i = 0; i < num_sample_ * 2; ++i) {\n    double x = ux_ * uy_ * x_(0) * exp(alpha_ * (i + 1 - num_sample_));\n    j1_[i] = boost::math::cyl_bessel_j(1, x);\n  }\n}\n\nVectorXd FastHankelTransform::calculate() {\n  assert(f_updated_ == true);\n  evaluate_phi();\n  evaluate_j1();\n\n  int nsample = num_sample_ * 2;\n  fftw_complex *fft_phi =\n      (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nsample);\n  fftw_complex *phi = reinterpret_cast<fftw_complex *>(phi_);\n  fftw_plan p1 =\n      fftw_plan_dft_1d(nsample, phi, fft_phi, FFTW_FORWARD, FFTW_ESTIMATE);\n  fftw_execute(p1);\n\n  fftw_complex *fft_j1 =\n      (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nsample);\n  fftw_complex *j1 = reinterpret_cast<fftw_complex *>(j1_);\n  fftw_plan p2 =\n      fftw_plan_dft_1d(nsample, j1, fft_j1, FFTW_BACKWARD, FFTW_ESTIMATE);\n  fftw_execute(p2);\n\n  fftw_complex *in =\n      (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nsample);\n\n  for (auto i = 0; i < nsample; ++i) {\n    in[i][0] = fft_phi[i][0] * fft_j1[i][0] - fft_phi[i][1] * fft_j1[i][1];\n    in[i][1] = fft_phi[i][0] * fft_j1[i][1] + fft_phi[i][1] * fft_j1[i][0];\n  }\n\n  fftw_complex *out =\n      (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nsample);\n\n  fftw_plan p3 =\n      fftw_plan_dft_1d(nsample, in, out, FFTW_FORWARD, FFTW_ESTIMATE);\n  fftw_execute(p3);\n\n  VectorXd ret(num_sample_);\n  for (auto i = 0; i < num_sample_; ++i) {\n    ret(i) = 2.0 / (x_(i) * pow(ux_, 2) * uy_) * out[i][0] / nsample;\n  }\n\n  fftw_destroy_plan(p1);\n  fftw_destroy_plan(p2);\n  fftw_destroy_plan(p3);\n  fftw_free(fft_phi);\n  fftw_free(fft_j1);\n  fftw_free(in);\n  fftw_free(out);\n\n  return ret;\n}\n", "meta": {"hexsha": "d8d109573d0c2067faaf934e51955e1ff6df6382", "size": 5070, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/fast_hankel_transform.cc", "max_stars_repo_name": "pan3rock/fast-hankel-transform", "max_stars_repo_head_hexsha": "c06edff4d0f42c250e5fda1a4eeb9c3800ab213c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-13T12:05:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-13T12:05:06.000Z", "max_issues_repo_path": "src/fast_hankel_transform.cc", "max_issues_repo_name": "pan3rock/fast-hankel-transform", "max_issues_repo_head_hexsha": "c06edff4d0f42c250e5fda1a4eeb9c3800ab213c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fast_hankel_transform.cc", "max_forks_repo_name": "pan3rock/fast-hankel-transform", "max_forks_repo_head_hexsha": "c06edff4d0f42c250e5fda1a4eeb9c3800ab213c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T09:56:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-09T00:43:38.000Z", "avg_line_length": 30.3592814371, "max_line_length": 80, "alphanum_fraction": 0.6579881657, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6066306953588969}}
{"text": "#include<NTL/ZZ_p.h>\n#include<NTL/ZZ_pXFactoring.h>\n#include <NTL/vector.h>\nusing namespace std;\nusing namespace NTL;\nZZ encr(ZZ m,ZZ e,ZZ n){\n\treturn PowerMod(m,e,n);\n\t}\n\t\nint main()\n{\n\tVec<ZZ> v;\n   ZZ n,p,q,f; \n   long L = 20;\n   GenGermainPrime(p,L,800);\n   GenGermainPrime(q,L,800);\n   \n   n = p*q;\n   //~ f=(p-1)*(q-1);\n   cout <<\"P=\"<< p << \"\\n\";   cout <<\"Q=\"<< q << \"\\n\";\n   cout <<\"N=\"<< n << \"\\n\";\n   //~ cout <<\"F=\"<< f << \"\\n\";\n   //~ cout <<\"Modulo Gen Done\" << \"\\n\";\n   //~ \n   //~ ZZ e=RandomBnd(f),test,d;\n   //~ ZZ gcd_ef=ZZ(20);\n   //~ while(gcd_ef!=0){\n\t   //~ e=RandomBnd(f);\n\t   //~ gcd_ef=InvModStatus(d,e,f);\n\t   //~ }\n\t//~ d=InvMod(e,f);\n\t//~ test=MulMod(e,d,f);\n   //~ cout <<\"e=\"<< e << \"\\n\";\n   //~ cout <<\"d=\"<< d << \"\\n\";\n   //~ cout <<\"test=\"<< test << \"\\n\";\n   //~ cout <<\"Key Generation Done\" << \"\\n\";\n   //~ ZZ m = RandomBnd(n);\n   //~ ZZ Enc,Dec;\n   //~ Enc = encr(m,e,n);\n   //~ Dec = encr(Enc,d,n);\n   //~ if(m==Dec){\n\t//~ cout <<\"Success\" << \"\\n\";  \n\t   //~ }\n   return 0;\n}\n\n\n", "meta": {"hexsha": "922f58063533bea933b439b1b2a79dc22d594cf6", "size": 1015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gen_primes.cpp", "max_stars_repo_name": "dheerajmpai/python", "max_stars_repo_head_hexsha": "733c331ce4fb35cc136170218115e8bb4a61134e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Gen_primes.cpp", "max_issues_repo_name": "dheerajmpai/python", "max_issues_repo_head_hexsha": "733c331ce4fb35cc136170218115e8bb4a61134e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gen_primes.cpp", "max_forks_repo_name": "dheerajmpai/python", "max_forks_repo_head_hexsha": "733c331ce4fb35cc136170218115e8bb4a61134e", "max_forks_repo_licenses": ["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.1458333333, "max_line_length": 54, "alphanum_fraction": 0.4492610837, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.963230536035447, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.6066181259784987}}
{"text": "#ifndef Interpolators__2D_BicubicInterpolator_hpp\n#define Interpolators__2D_BicubicInterpolator_hpp\n\n/** @file BicubicInterpolator.hpp\n  * @brief \n  * @author C.D. Clark III\n  * @date 12/27/16\n  */\n\n#include \"InterpolatorBase.hpp\"\n#include <boost/range/algorithm/lower_bound.hpp>\n#include <boost/range/adaptor/strided.hpp>\n\n/** @class \n  * @brief Cubic spline interpolation for for 2D functions.\n  * @author C.D. Clark III, Aaron Hoffman\n  *\n  * This class implements the bicubic spline interpolation method.\n  * It is essentially the 2D equivalent of cubic splines for 1D. \n  *\n  */\n\nnamespace _2D {\n\ntemplate<class Real>\nclass BicubicInterpolator : public InterpolatorBase<BicubicInterpolator<Real>>\n{\n  public:\n    using BASE = InterpolatorBase<BicubicInterpolator<Real>>;\n    using VectorType = typename BASE::VectorType;\n    using MapType = typename BASE::MapType;\n\n    // types used to view data as 2D coordinates\n    using MatrixType    = typename BASE::MatrixType;\n    using _2DVectorView = typename BASE::_2DVectorView;\n    using _2DMatrixView = typename BASE::_2DMatrixView;\n\n    // types used for 4x4 matrix algebra\n    using Matrix44 = Eigen::Matrix<Real,4,4 >;\n    using Matrix44Array = Eigen::Array< Matrix44, Eigen::Dynamic, Eigen::Dynamic >;\n    using ColVector4 = Eigen::Matrix<Real,4,1 >;\n    using RowVector4 = Eigen::Matrix<Real,1,4 >;\n\n  protected:\n    using BASE::xView;\n    using BASE::yView;\n    using BASE::zView;\n    using BASE::X;\n    using BASE::Y;\n    using BASE::Z;\n    \n    Matrix44Array a; // naming convention used by wikipedia article (see Wikipedia https://en.wikipedia.org/wiki/Bicubic_interpolation)\n\n  public:\n\n    template<typename I>\n    BicubicInterpolator( I n, Real *x, Real *y, Real *z ) {this->setData(n,x,y,z);}\n\n    template<typename X, typename Y, typename Z>\n    BicubicInterpolator( X &x, Y &y, Z &z ) {this->setData(x,y,z);}\n\n    BicubicInterpolator():BASE()\n    { }\n\n    BicubicInterpolator(const BicubicInterpolator& rhs)\n    :BASE(rhs)\n    ,a(rhs.a)\n    {}\n\n    // copy-swap idiom\n    friend void swap( BicubicInterpolator& lhs, BicubicInterpolator& rhs)\n    {\n      lhs.a.swap(rhs.a);\n      swap( static_cast<BASE&>(lhs), static_cast<BASE&>(rhs) );\n    }\n\n    BicubicInterpolator& operator=(BicubicInterpolator rhs)\n    {\n      swap(*this,rhs);\n      return *this;\n    }\n\n\n    // methods required by the interface\n    Real operator()( Real x, Real y ) const;\n\n  protected:\n\n    void setupInterpolator();\n    friend BASE;\n\n};\n\ntemplate<class Real>\nvoid\nBicubicInterpolator<Real>::setupInterpolator()\n{\n  // Interpolation will be done by multiplying the coordinates by coefficients.\n\n  a = Matrix44Array( X->size()-1, Y->size()-1 );\n\n  // We are going to precompute the interpolation coefficients so\n  // that we can interpolate quickly. This requires a 4x4 matrix for each \"patch\".\n  Matrix44 Left, Right;\n\n  Left <<  1,  0,  0,  0,\n           0,  0,  1,  0,\n          -3,  3, -2, -1,\n           2, -2,  1,  1;\n\n  Right<<  1,  0, -3,  2,\n           0,  0,  3, -2,\n           0,  1, -2,  1,\n           0,  0, -1,  1;\n\n  for(int i = 0; i < X->size() - 1; i++)\n  {\n    for( int j = 0; j < Y->size() - 1; j++)\n    {\n      Matrix44 F;\n\n      Real f00,   f01,   f10,   f11;\n      Real fx00,  fx01,  fx10,  fx11;\n      Real fy00,  fy01,  fy10,  fy11;\n      Real fxy00, fxy01, fxy10, fxy11;\n\n      Real fm, fp;\n      int im, ip, jm, jp;\n\n      int iN = X->size();\n      int jN = Y->size();\n\n      // function values\n      f00 = (*Z)(i    ,j    ); // <<<<<<\n      f01 = (*Z)(i    ,j + 1); // <<<<<<\n      f10 = (*Z)(i + 1,j    ); // <<<<<<\n      f11 = (*Z)(i + 1,j + 1); // <<<<<<\n\n      // need to calculate function values and derivatives\n      // at each corner.\n      //\n      // note: interpolation algorithm is derived for the unit square.\n      // so we need to take the derivatives assuming X(i+1) - X(i) = Y(j+1) - Y(j) = 1\n      \n      Real xL = (*X)(i+1) - (*X)(i);\n      Real yL = (*Y)(j+1) - (*Y)(j);\n      Real dx, dy;\n\n      // x derivatives\n\n      im = std::max(i-1,0);\n      ip = std::min(i+1,iN-1);\n\n      dx = ((*X)(ip) - (*X)(im))/xL;\n\n      fp = (*Z)(ip,j);\n      fm = (*Z)(im,j);\n      fx00 = (fp - fm) / dx; // <<<<<<\n\n      fp = (*Z)(ip,j+1);\n      fm = (*Z)(im,j+1);\n      fx01 = (fp - fm) / dx; // <<<<<<\n\n\n      im = std::max(i,0);\n      ip = std::min(i+2,iN-1);\n\n      dx = ((*X)(ip) - (*X)(im))/xL;\n\n      fp = (*Z)(ip,j);\n      fm = (*Z)(im,j);\n      fx10 = (fp - fm) / dx; // <<<<<<\n\n      fp = (*Z)(ip,j+1);\n      fm = (*Z)(im,j+1);\n      fx11 = (fp - fm) / dx; // <<<<<<\n\n\n      // y derivatives\n\n      jm = std::max(j-1,0);\n      jp = std::min(j+1,jN-1);\n\n      dy = ((*Y)(jp) - (*Y)(jm))/yL;\n\n      fp = (*Z)(i,jp);\n      fm = (*Z)(i,jm);\n      fy00 = (fp - fm) / dy; // <<<<<<\n\n      fp = (*Z)(i+1,jp);\n      fm = (*Z)(i+1,jm);\n      fy10 = (fp - fm) / dy; // <<<<<<\n\n\n      jm = std::max(j,0);\n      jp = std::min(j+2,jN-1);\n\n      dy = ((*Y)(jp) - (*Y)(jm))/yL;\n\n      fp = (*Z)(i,jp);\n      fm = (*Z)(i,jm);\n      fy01 = (fp - fm) / yL; // <<<<<<\n\n      fp = (*Z)(i+1,jp);\n      fm = (*Z)(i+1,jm);\n      fy11 = (fp - fm) / yL; // <<<<<<\n\n      // xy derivatives\n\n      im = std::max(i-1,0);\n      ip = std::min(i+1,iN-1);\n      jm = std::max(j-1,0);\n      jp = std::min(j+1,jN-1);\n\n      dx = ((*X)(ip) - (*X)(im)) / xL;\n\n      dy = ((*Y)(jp) - (*Y)(jm)) / yL;\n\n      fp = ((*Z)(ip,jp) - (*Z)(im,jp))/dx;\n      fm = ((*Z)(ip,jm) - (*Z)(im,jm))/dx;\n      fxy00 = (fp - fm) / dy; // <<<<<<\n\n\n      jm = std::max(j,0);\n      jp = std::min(j+2,jN-1);\n\n      dy = ((*Y)(jp) - (*Y)(jm))/yL;\n\n      fp = ((*Z)(ip,jp) - (*Z)(im,jp))/dx;\n      fm = ((*Z)(ip,jm) - (*Z)(im,jm))/dx;\n      fxy01 = (fp - fm) / dy; // <<<<<<\n\n\n      im = std::max(i,0);\n      ip = std::min(i+2,iN-1);\n      jm = std::max(j-1,0);\n      jp = std::min(j+1,jN-1);\n\n      dx = ((*X)(ip) - (*X)(im)) / xL;\n\n      dy = ((*Y)(jp) - (*Y)(jm)) / yL;\n\n      fp = ((*Z)(ip,jp) - (*Z)(im,jp))/dx;\n      fm = ((*Z)(ip,jm) - (*Z)(im,jm))/dx;\n      fxy10 = (fp - fm) / dy; // <<<<<<\n\n      jm = std::max(j,0);\n      jp = std::min(j+2,jN-1);\n\n      dy = ((*Y)(jp) - (*Y)(jm)) / yL;\n\n      fp = ((*Z)(ip,jp) - (*Z)(im,jp))/dx;\n      fm = ((*Z)(ip,jm) - (*Z)(im,jm))/dx;\n      fxy11 = (fp - fm) / dy; // <<<<<<\n\n\n      F <<  f00,  f01,  fy00,  fy01,\n            f10,  f11,  fy10,  fy11,\n           fx00, fx01, fxy00, fxy01,\n           fx10, fx11, fxy10, fxy11;\n\n      a(i,j) = Left * F * Right;\n    }\n  }\n}\n\ntemplate<class Real>\nReal\nBicubicInterpolator<Real>::operator()( Real x, Real y ) const\n{\n  BASE::checkData();\n  \n  // no extrapolation...\n  if( x < this->xView->minCoeff()\n   || x > this->xView->maxCoeff()\n   || y < this->yView->minCoeff()\n   || y > this->yView->maxCoeff() )\n  {\n    return 0;\n  }\n\n\n  // find the x index that is just to the LEFT of x\n  //int i  = Utils::index__last_lt( x, *X, X->size() );\n  // NOTE: X data is strided.\n  auto xrng = std::make_pair( X->data(), X->data()+X->size()*X->innerStride() ) | boost::adaptors::strided(X->innerStride());\n  int i = boost::lower_bound( xrng, x) - boost::begin(xrng) - 1;\n  if(i < 0)\n    i = 0;\n\n  // find the y index that is just BELOW y\n  //int j  = Utils::index__last_lt( y, *Y, Y->size() );\n  // NOTE: Y data is NOT strided\n  auto yrng = std::make_pair( Y->data(), Y->data()+Y->size() );\n  int j = boost::lower_bound( yrng, y) - boost::begin(yrng) - 1;\n  if(j < 0)\n    j = 0;\n  \n\n  Real xL = (*X)(i+1) - (*X)(i);\n  Real yL = (*Y)(j+1) - (*Y)(j);\n\n  // now, create the coordinate vectors (see Wikipedia https://en.wikipedia.org/wiki/Bicubic_interpolation)\n  RowVector4 vx;\n  vx[0] = 1;                                   // x^0\n  vx[1] = (x - (*X)(i))/xL;                    // x^1\n  vx[2] = vx[1] * vx[1];                       // x^2\n  vx[3] = vx[2] * vx[1];                       // x^3\n\n  ColVector4 vy;\n  vy[0] = 1;                                   // y^0\n  vy[1] = (y - (*Y)(j))/yL;                    // y^1\n  vy[2] = vy[1] * vy[1];                       // y^2\n  vy[3] = vy[2] * vy[1];                       // y^3\n\n\n  // interpolation is just x*a*y\n\n  return vx*a(i,j)*vy;\n\n}\n\n\n\n\n\n}\n\n#endif // include protector\n", "meta": {"hexsha": "dfe62ff25efdd3b527388593c9ecc48184e40805", "size": 8125, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/libInterpolate/src/Interpolators/_2D/BicubicInterpolator.hpp", "max_stars_repo_name": "bindungszustandsamplitude/dysonutils", "max_stars_repo_head_hexsha": "0875307a1a4d4183a650b796caa0111713006210", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-17T09:41:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-17T09:41:17.000Z", "max_issues_repo_path": "src/Interpolators/_2D/BicubicInterpolator.hpp", "max_issues_repo_name": "XiaoLeiziGitHub/libInterpolate", "max_issues_repo_head_hexsha": "19a399d1a4fae6c4390adbbd2b1ef7fc8d3278b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Interpolators/_2D/BicubicInterpolator.hpp", "max_forks_repo_name": "XiaoLeiziGitHub/libInterpolate", "max_forks_repo_head_hexsha": "19a399d1a4fae6c4390adbbd2b1ef7fc8d3278b0", "max_forks_repo_licenses": ["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.6212121212, "max_line_length": 135, "alphanum_fraction": 0.4928, "num_tokens": 2858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.6926419958239132, "lm_q1q2_score": 0.6066068475660953}}
{"text": "    #include <Eigen/Dense>\n    #include <Eigen/Sparse>\n    #include <unsupported/Eigen/MatrixFunctions>\n    #include <unsupported/Eigen/KroneckerProduct>\n\n    #include <iostream>\n    #include <cmath>\n\n    #define TVMTL_MATRIX_UTILS_DEBUG\n\n    #include <mtvmtl/core/matrix_utils.hpp>\n\n    int main(){\n\n    using namespace Eigen;\n\n    Matrix3d R = Matrix3d::Random();    \n    Matrix3d M = R + R.transpose() + R.rows()*Matrix3d::Identity();\n    \n    std::cout << \"Matrix M :\\n\" << M << std::endl;\n    std::cout << \"\\nlog(M) :\\n\" << M.log() << std::endl;\n\n    for (int i = 0; i < 3; i++) {\n    \tfor (int j = 0; j < 3; j++) {\n\t    Matrix3d E = Matrix3d::Zero();\n\t    MatrixXd D = MatrixXd::Zero(3,3);\n\t    E(i,j)=1.0;\n\t    tvmtl::MatrixLogarithmFrechetDerivative(M, E, D);\n\t    std::cout << \"\\ndlog(M,E_\" << i+1 << j+1 << \") :\\n\" << D << std::endl;\n\t    Map<VectorXd> V(D.data(), D.size());\n\t    std::cout << \"\\nRowwise Vectorized:\\n\" << V << std::endl;\n    \t}\n    }\n\n    Matrix<double, 9 ,9>  Result;\n    tvmtl::KroneckerDLog(M, Result);\n    std::cout << \"Full Kronecker Representation of DLog:\\n\" << Result << std::endl; \n\n\n    std::cout << \"\\n\\nPermutation Matrix Test:\\n\" << std::endl;\n\n    PermutationMatrix<9, 9, int> P;\n    P.setIdentity();\n    for(int i=0; i<3; i++)\n\tfor(int j=0; j<i; j++)\n\t    P.applyTranspositionOnTheRight(j*3+i,i*3+j);\n\t\n    std::cout << P*Matrix<double, 9,9>::Identity() << std::endl;\n\n    std::cout << \"\\n\\n Simple Rotation Matrix Test\\n\" << std::endl;\n\n    Matrix3d s1 = Matrix3d::Identity();\n    Matrix3d s2;\n    s2 << 0, -1, 0, 1, 0, 0, 0, 0, 1;\n    Matrix3d m2 = s1.transpose()*s2; \n\n    std::cout << \"\\nMatrix 1\\n\" << s1 << std::endl;\n    std::cout << \"\\nMatrix 2\\n\" << s2 << std::endl;\n    std::cout << \"\\nDlog Argument\\n\" << m2 << std::endl;\n    \n\n    tvmtl::KroneckerDLog(m2, Result);\n    std::cout << \"\\n\\nFull Kronecker Representation of DLog:\\n\" << Result << std::endl; \n\n\n    Matrix3d m3;\n    m3 << 4102350, -2446420, 2209640, -2446420,  1458920, -1317710, 2209640, -1317710, 1190180;\n\n    tvmtl::KroneckerDLog(m3, Result);\n    std::cout << \"\\n\\nPathological Matrix test:\\n\" << Result << std::endl;\n    \n\n\n\n    return 0;\n    }\n", "meta": {"hexsha": "00a607b208ebc75a61d0787ca9804e91dde65279", "size": 2166, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/mat_util_test.cpp", "max_stars_repo_name": "pdebus/MTVMTL", "max_stars_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-08T12:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-02T05:11:01.000Z", "max_issues_repo_path": "test/mat_util_test.cpp", "max_issues_repo_name": "pdebus/MTVMTL", "max_issues_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/mat_util_test.cpp", "max_forks_repo_name": "pdebus/MTVMTL", "max_forks_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1298701299, "max_line_length": 95, "alphanum_fraction": 0.5655586334, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6066068442551464}}
{"text": "#include <cmath>\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n#include <adaptive_filter_rls.h>\n\nclass ReferenceFilter\n{\npublic:\n    ReferenceFilter( unsigned inputCount )\n        : mW( Eigen::VectorXf::Random( inputCount ) )\n    {}\n\n    float operator()( Eigen::VectorXf inputs )\n    {\n        return mW.dot( inputs );\n    }\n\n    Eigen::VectorXf mW;\n};\n\nclass Model\n{\n    const unsigned kInputCount = 100;\n    const float kMaxAmplitude = 1.0f;\n    const float kMaxFrequency = 10.0f;\n    const float kStep = 0.1f * 1.0f / kMaxFrequency;\n\npublic:\n    Model()\n        : mAmplitude( kMaxAmplitude / 2.0f *\n            ( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ) )\n        , mOmega( kMaxFrequency / 2.0f *\n            ( Eigen::VectorXf::Random( kInputCount ).array() + 1.0f ) )\n        , mInput( kInputCount )\n        , mW( Eigen::VectorXf::Random( kInputCount ) )\n        , mOutput( 0.0f )\n        , mReferenceFilter( kInputCount )\n        , mReferenceOutput( 0.0f )\n        , mTime( 0.0f )\n    {}\n\n    void Update()\n    {\n        mTime += kStep;\n        mInput = mAmplitude.array() * ( mOmega.array() * mTime ).unaryExpr(\n            std::ptr_fun< float, float >( std::sin ) );\n        mOutput = mW.dot( mInput );\n        mReferenceOutput = mReferenceFilter( mInput );\n    }\n\n    Eigen::VectorXf mAmplitude;\n    Eigen::VectorXf mOmega;\n    Eigen::VectorXf mInput;\n    Eigen::VectorXf mW;\n    float mOutput;\n    ReferenceFilter mReferenceFilter;\n    float mReferenceOutput;\n    float mTime;\n};\n\nTEST( AdaptiveFilter, NLMS )\n{\n    const unsigned kStepCount = 10000;\n    const float kTrainStep = 0.1f;\n\n    Model model;\n    model.Update();\n    float error = model.mReferenceOutput - model.mOutput;\n    float initialError = std::fabs( error / model.mOutput );\n\n    for ( int i = 0; i < kStepCount; ++ i )\n    {\n        model.Update();\n        error = model.mReferenceOutput - model.mOutput;\n        model.mW += ( kTrainStep * error * model.mInput.transpose() /\n            model.mInput.squaredNorm() );\n    }\n\n    EXPECT_TRUE( std::fabs( error / model.mOutput ) < initialError );\n}\n\nTEST( AdaptiveFilter, RLS )\n{\n    const unsigned kStepCount = 1000;\n    const float kRegularization = 1000.0f;\n    const float kForgettingFactor = 0.99f;\n\n    Model model;\n    model.Update();\n    float error = model.mReferenceOutput - model.mOutput;\n    float initialError = std::fabs( error / model.mOutput );\n\n    ESN::AdaptiveFilterRLS filter( model.mInput.size(),\n        kForgettingFactor, kRegularization );\n\n    for ( int i = 0; i < kStepCount; ++ i )\n    {\n        model.Update();\n        error = model.mReferenceOutput - model.mOutput;\n        filter.Train( model.mW, model.mOutput, model.mReferenceOutput,\n            model.mInput );\n    }\n\n    EXPECT_LT( std::fabs( error / model.mOutput ), initialError );\n}\n", "meta": {"hexsha": "3964e0fdf4707d04eb7499b13e008f799a0ae5d0", "size": 2813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/adaptive_filter.cpp", "max_stars_repo_name": "mode89/esn", "max_stars_repo_head_hexsha": "6de28a79ac264401c066f87922226dda70fadbdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-02-17T23:10:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T00:09:33.000Z", "max_issues_repo_path": "tests/adaptive_filter.cpp", "max_issues_repo_name": "mode89/esn", "max_issues_repo_head_hexsha": "6de28a79ac264401c066f87922226dda70fadbdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/adaptive_filter.cpp", "max_forks_repo_name": "mode89/esn", "max_forks_repo_head_hexsha": "6de28a79ac264401c066f87922226dda70fadbdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-28T12:20:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-28T12:20:03.000Z", "avg_line_length": 26.5377358491, "max_line_length": 75, "alphanum_fraction": 0.6114468539, "num_tokens": 791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6066068297164015}}
{"text": "#include <iostream>\r\n#include <cmath>\r\n#include <math.h>\r\n#include <iostream>\r\n#include <vector>\r\n#include <array>\r\n#include \"heatEquation.hpp\"\r\n#include \"AdaptiveHeat.hpp\"\r\n#include \"TriDiagMatrix.hpp\"\r\n#include \"MassMatrix.hpp\"\r\n#include \"StiffnessMatrix.hpp\"\r\n#include <fstream>\r\n#include <string>\r\n#include <boost/math/quadrature/gauss.hpp>\r\nusing namespace std;\r\nusing namespace boost::math::quadrature;\r\n\r\nvoid AdaptiveHeatEquation::AdaptiveSolver()\r\n{\r\nAnalyticSolutionVec();\r\nmpPreviousSolution = mpAnalyticSolution;\r\nBuildSystemAtTimeStep();\r\noldmesh.CopySpaceMesh(mpsmesh);\r\nmpsmesh.PrintSpaceNodes();\r\n\r\n\r\nint m = mptmesh.NumberOfTimeSteps();\r\nfor(int j = 0; j<m; j++)\r\n{\r\n    mpcurrenTimeStep = j+1;\r\n    mpcurrentMeshIndex = j;\r\n\r\n    BuildSystemAtTimeStep();\r\n    SystemSolver();\r\n    mpPreviousSolution = mpx;\r\n\r\n    SaveIntervalsForRefinement();\r\n    SaveIntervalsForCoarsening();\r\n    mpsmesh.BisectIntervals(intervalsForRefinement);\r\n    mpsmesh.CoarsenIntervals(NodesForRemoval);\r\n    std::cout<<mpsmesh.meshsize() <<\"\\n\";\r\n    std::cout<<\"\\n\";\r\n    PrintVector(mpErrorMesh);\r\n}\r\n    std::cout<<mpsmesh.meshsize() <<\"\\n\";\r\n    std::cout<<\"\\n\";\r\n}\r\n\r\nvoid AdaptiveHeatEquation::SaveIntervalsForCoarsening()\r\n{\r\n    BuildErrorMesh();\r\n    NodesForRemoval.clear();\r\n    for(int i=0; i<mpErrorMesh.size()-1; i++)\r\n    {\r\n        if (sqrt(mpErrorMesh.at(i)+mpErrorMesh.at(i+1))<coarseningtol)\r\n        {\r\n            NodesForRemoval.push_back(i+1);\r\n        }\r\n    }\r\n\r\n}\r\n\r\nvoid AdaptiveHeatEquation::BuildSystemAtTimeStep()\r\n{\r\nstiff.BuildStiffnessMatrix( mpsmesh );\r\nstiff.MultiplyByScalar( mptmesh.ReadTimeMesh(mpcurrentMeshIndex) );\r\nmass.BuildMassMatrix(mpsmesh);\r\nLHS.AddTwoMatrices( mass, stiff );\r\n}\r\n\r\nvoid AdaptiveHeatEquation::SystemSolver()\r\n{\r\n    BuildRHS();\r\n    LHS.MatrixSolver( mpRHS, mpx );\r\n    oldmesh.CopySpaceMesh(mpsmesh);\r\n}\r\n\r\n\r\nvoid AdaptiveHeatEquation::SaveIntervalsForRefinement()\r\n{\r\n    BuildErrorMesh();\r\n    intervalsForRefinement.clear();\r\n    for(int i=0; i<mpErrorMesh.size(); i++)\r\n    {\r\n        if (sqrt(mpErrorMesh.at(i))>tolerance)\r\n        {\r\n            intervalsForRefinement.push_back(i);\r\n        }\r\n    }\r\n}\r\n\r\ndouble AdaptiveHeatEquation::IntegrateBasisWithU( int NodeIndex, double lowerlimit,\r\n                              double upperlimit )\r\n{\r\n    auto SolutionWithBasis = [&](double x)\r\n        { return mpsmesh.TestFunctions( NodeIndex, x)*PiecewiseU(x, oldmesh, mpPreviousSolution); };\r\n\r\n    return gauss<double, 7>::integrate(SolutionWithBasis, lowerlimit, upperlimit);\r\n}\r\n\r\n\r\n    //this function works for refinement and coarsening\r\nvoid AdaptiveHeatEquation::BuildRHS()\r\n{\r\nmpRHS.clear();\r\nstd::vector<double> intervals;\r\n\r\nrefinedsmesh.CommonMesh(mpsmesh, oldmesh);\r\n\r\ndouble integral;\r\nfor (int i = 1; i<mpsmesh.meshsize(); i++)\r\n{\r\n    integral=0;\r\n    refinedsmesh.Range(mpsmesh.ReadSpaceNode(i-1), mpsmesh.ReadSpaceNode(i+1), intervals);\r\n\r\n    for(int j = 0; j<intervals.size()-1; j++)\r\n    {\r\n        integral = integral + IntegrateBasisWithU(i, intervals.at(j),\r\n                    intervals.at(j+1));\r\n    }\r\n    mpRHS.push_back(integral);\r\n}\r\n}\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "10afdf7671f33b8dd41abea66a2c51854acb9333", "size": 3144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sover class with method to adapt in space and time/AdaptiveHeat.cpp", "max_stars_repo_name": "thabomiles/FEMHeatEquation", "max_stars_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sover class with method to adapt in space and time/AdaptiveHeat.cpp", "max_issues_repo_name": "thabomiles/FEMHeatEquation", "max_issues_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sover class with method to adapt in space and time/AdaptiveHeat.cpp", "max_forks_repo_name": "thabomiles/FEMHeatEquation", "max_forks_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3720930233, "max_line_length": 101, "alphanum_fraction": 0.6609414758, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6065585622483186}}
{"text": "//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include <boost/gil.hpp>\n#include <boost/gil/extension/io/png.hpp>\n\n#include <iostream>\n#include <limits>\n#include <vector>\n\nnamespace gil = boost::gil;\n\n// Demonstrates how to use a Hough transform to identify a circle\n\n// Note this relies on the brute force approach, which today is the only one available in GIL\n// The function hough_circle_transform_brute, defined in include/boost/gil/image_processing/hough_transform.cpp,\n// accepts a greyscale edge map, the three Hough parameters allowing to do the drawing and the voting,\n// an accumulator in the form of an iterator of views of the parameter space and a utility rasterizer to produce the points.\n// The example outputs the voting cell of the centre of a circle drawn programatically.\n// See also:\n// hough_transform_line.cpp - Hough transform to detect lines\n\nint main()\n{\n    const std::size_t size = 128;\n    gil::gray8_image_t input_image(size, size);\n    auto input = gil::view(input_image);\n\n    const std::ptrdiff_t circle_radius = 16;\n    const gil::point_t circle_center = {64, 64};\n    const auto rasterizer = gil::midpoint_circle_rasterizer{};\n    std::vector<gil::point_t> circle_points(rasterizer.point_count(circle_radius));\n    rasterizer(circle_radius, circle_center, circle_points.begin());\n    for (const auto& point : circle_points)\n    {\n        input(point) = std::numeric_limits<gil::uint8_t>::max();\n    }\n\n    const auto radius_parameter =\n        gil::hough_parameter<std::ptrdiff_t>::from_step_count(circle_radius, 3, 3);\n    const auto x_parameter =\n        gil::hough_parameter<std::ptrdiff_t>::from_step_count(circle_center.x, 3, 3);\n    const auto y_parameter =\n        gil::hough_parameter<std::ptrdiff_t>::from_step_count(circle_center.x, 3, 3);\n\n    std::vector<gil::gray16_image_t> parameter_space_images(\n        radius_parameter.step_count,\n        gil::gray16_image_t(x_parameter.step_count, y_parameter.step_count));\n    std::vector<gil::gray16_view_t> parameter_space_views(parameter_space_images.size());\n    std::transform(parameter_space_images.begin(), parameter_space_images.end(),\n                   parameter_space_views.begin(),\n                   [](gil::gray16_image_t& img)\n                   {\n                       return gil::view(img);\n                   });\n\n    gil::hough_circle_transform_brute(input, radius_parameter, x_parameter, y_parameter,\n                                      parameter_space_views.begin(), rasterizer);\n    std::cout << parameter_space_views[3](3, 3) << '\\n';\n}\n", "meta": {"hexsha": "1e9d25798d4dde30fad8f51d7e97db8512b130ee", "size": 2773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/hough_transform_circle.cpp", "max_stars_repo_name": "DhruvaG2000/gil", "max_stars_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/hough_transform_circle.cpp", "max_issues_repo_name": "DhruvaG2000/gil", "max_issues_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/hough_transform_circle.cpp", "max_forks_repo_name": "DhruvaG2000/gil", "max_forks_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0151515152, "max_line_length": 124, "alphanum_fraction": 0.7042913812, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.6065585523705189}}
{"text": "// based off of the example provided at https://github.com/boostorg/histogram\n//\n#include <boost/histogram.hpp>\n#include <boost/format.hpp> // used here for printing\n#include <iostream>\n\nint main() {\n    using namespace boost::histogram;\n\n    // make 1d histogram with 4 regular bins from 0 to 2\n    auto h = make_histogram( axis::regular<>(4, 0.0, 2.0) );\n\n    // push some values into the histogram\n    for (auto&& value : { 0.4, 1.1, 0.3, 1.7, 10. })\n      h(value);\n\n    // iterate over bins\n    for (auto&& x : indexed(h)) {\n      std::cout << boost::format(\"bin %i [ %.1f, %.1f ): %i\\n\")\n        % x.index() % x.bin().lower() % x.bin().upper() % *x;\n    }\n\n    std::cout << std::flush;\n\n    /* program output:\n\n    bin 0 [ 0.0, 0.5 ): 2\n    bin 1 [ 0.5, 1.0 ): 0\n    bin 2 [ 1.0, 1.5 ): 1\n    bin 3 [ 1.5, 2.0 ): 1\n    */\n}\n", "meta": {"hexsha": "4829fed6c66d6830c6e2014a6f784c7fbc635c00", "size": 830, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/histogram_test.cc", "max_stars_repo_name": "esigo/rules_boost", "max_stars_repo_head_hexsha": "381e2e0ef0e0e1d07a9ca91b4ec4ce2051a71b83", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 62.0, "max_stars_repo_stars_event_min_datetime": "2021-09-21T18:58:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T02:17:43.000Z", "max_issues_repo_path": "test/histogram_test.cc", "max_issues_repo_name": "esigo/rules_boost", "max_issues_repo_head_hexsha": "381e2e0ef0e0e1d07a9ca91b4ec4ce2051a71b83", "max_issues_repo_licenses": ["Apache-2.0"], "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/histogram_test.cc", "max_forks_repo_name": "esigo/rules_boost", "max_forks_repo_head_hexsha": "381e2e0ef0e0e1d07a9ca91b4ec4ce2051a71b83", "max_forks_repo_licenses": ["Apache-2.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.1515151515, "max_line_length": 77, "alphanum_fraction": 0.5481927711, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6065120133526114}}
{"text": "/***************************************************************************\n *   Software License Agreement (BSD License)                              *\n *   Copyright (C) 2017 by Florian Beck <florian.beck@tuwien.ac.at>        *\n *                                                                         *\n *   Redistribution and use in source and binary forms, with or without    *\n *   modification, are permitted provided that the following conditions    *\n *   are met:                                                              *\n *                                                                         *\n *   1. Redistributions of source code must retain the above copyright     *\n *      notice, this list of conditions and the following disclaimer.      *\n *   2. Redistributions in binary form must reproduce the above copyright  *\n *      notice, this list of conditions and the following disclaimer in    *\n *      the documentation and/or other materials provided with the         *\n *      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    *\n *      from this software without specific prior written permission.      *\n *                                                                         *\n *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   *\n *   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     *\n *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS     *\n *   FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE        *\n *   COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,  *\n *   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,  *\n *   BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      *\n *   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER      *\n *   CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT    *\n *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY *\n *   WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           *\n *   POSSIBILITY OF SUCH DAMAGE.                                           *\n ***************************************************************************/\n\n#include \"mahalanobis_meas_model.h\"\n#include <boost/math/distributions/chi_squared.hpp>\n#include <assert.h>\n\nMahalanobisMeasModel::MahalanobisMeasModel(double cov_scale)\n{\n  cov_scale_ = cov_scale;\n}\n\ndouble MahalanobisMeasModel::getProbability(const Ref<const VectorXd>& curr_state, const Ref<const VectorXd>& meas, const Ref<const MatrixXd>& meas_cov, double dt)\n{\n  // simple measurement model, position directly observable (by detector)\n  // state = [x, y, vx, vy]^T\n  // z = [x, y]^T\n  // C = [1, 0, 0, 0; 0, 1, 0, 0]\n  \n  // calculate mahalanobis distance from predicted measurement to actual measurement\n  // note: consider current state as deterministic state with no covariance\n  // only measurement provides covariance\n  // mahalanobis distance is chi_square distributed\n  \n  double dist = sqrt((curr_state.block<2, 1>(0, 0) - meas).transpose() * \n                    ((meas_cov.block<2, 2>(0, 0) * cov_scale_).inverse()) * \n                    (curr_state.block<2, 1>(0, 0) - meas));\n  \n  //boost::math::normal norm = boost::math::normal(0, sigma_ * sigma_);\n  boost::math::chi_squared chi(2);\n\n  return boost::math::pdf(chi, dist);\n}\n", "meta": {"hexsha": "786ca349fa9304627a2392294f631495745431fb", "size": 3535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tuw_object_tracking/src/mahalanobis_meas_model.cpp", "max_stars_repo_name": "tuw-robotics/tuw_object_estimation", "max_stars_repo_head_hexsha": "ff3491c6fa18bf7f0ab062ebb2d93dbadc63b453", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-11-25T21:48:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-24T08:07:08.000Z", "max_issues_repo_path": "tuw_object_tracking/src/mahalanobis_meas_model.cpp", "max_issues_repo_name": "tuw-robotics/tuw_object_estimation", "max_issues_repo_head_hexsha": "ff3491c6fa18bf7f0ab062ebb2d93dbadc63b453", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tuw_object_tracking/src/mahalanobis_meas_model.cpp", "max_forks_repo_name": "tuw-robotics/tuw_object_estimation", "max_forks_repo_head_hexsha": "ff3491c6fa18bf7f0ab062ebb2d93dbadc63b453", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 56.1111111111, "max_line_length": 163, "alphanum_fraction": 0.5753889675, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6065120063516635}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#ifndef STENCILS_HPP\n#define STENCILS_HPP\n\n#include <functional>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n\n/*! \\typedef DifferentiableFunction\n *  \\brief sort of a function pointer to a function of a pair of vectors that can be numerically differentiated\n */\ntypedef pcm::function<double(const Eigen::Vector3d &, const Eigen::Vector3d &)> DifferentiableFunction;\n\n/*! \\brief Calculate directional derivative using a three-point stencil\n *  \\param[in] func function to be differentiated\n *  \\param[in] arg_1 first point, the directional derivative is calculated with respect to this point\n *  \\param[in] arg_2 second point\n *  \\param[in] direction the direction in which the directional derivative is to be evaluated\n *  \\param[in] step finite difference value for the stencil\n */\ninline double threePointStencil(const DifferentiableFunction & func,\n        const Eigen::Vector3d & arg_1, const Eigen::Vector3d & arg_2,\n        const Eigen::Vector3d & direction, double step = 1.0e-04)\n{\n    // f(x-h)\n    Eigen::Vector3d delta_m1 = arg_1 - direction * step / direction.norm();\n    // f(x+h)\n    Eigen::Vector3d delta_1  = arg_1 + direction * step / direction.norm();\n\n    Eigen::Vector2d stencil;\n    stencil << -0.5, 0.5;\n    Eigen::Vector2d function_values;\n    function_values << func(delta_m1, arg_2), func(delta_1,  arg_2);\n\n    return (function_values.dot(stencil) / step);\n}\n\n/*! \\brief Calculate directional derivative using a five-point stencil\n *  \\param[in] func function to be differentiated\n *  \\param[in] arg_1 first point, the directional derivative is calculated with respect to this point\n *  \\param[in] arg_2 second point\n *  \\param[in] direction the direction in which the directional derivative is to be evaluated\n *  \\param[in] step finite difference value for the stencil\n */\ninline double fivePointStencil(const DifferentiableFunction & func,\n        const Eigen::Vector3d & arg_1, const Eigen::Vector3d & arg_2,\n        const Eigen::Vector3d & direction, double step = 1.0e-04)\n{\n    // f(x-2h)\n    Eigen::Vector3d delta_m2 = arg_1 - 2.0 * direction * step / direction.norm();\n    // f(x-h)\n    Eigen::Vector3d delta_m1 = arg_1 - direction * step / direction.norm();\n    // f(x+h)\n    Eigen::Vector3d delta_1  = arg_1 + direction * step / direction.norm();\n    // f(x+2h)\n    Eigen::Vector3d delta_2  = arg_1 + 2.0 * direction * step / direction.norm();\n\n    Eigen::Vector4d stencil;\n    stencil << 1.0/12.0, -2.0/3.0, 2.0/3.0, -1.0/12.0;\n    Eigen::Vector4d function_values;\n    function_values << func(delta_m2, arg_2), func(delta_m1, arg_2),\n                       func(delta_1,  arg_2), func(delta_2,  arg_2);\n\n    return (function_values.dot(stencil) / step);\n}\n\n/*! \\brief Calculate directional derivative using a seven-point stencil\n *  \\param[in] func function to be differentiated\n *  \\param[in] arg_1 first point, the directional derivative is calculated with respect to this point\n *  \\param[in] arg_2 second point\n *  \\param[in] direction the direction in which the directional derivative is to be evaluated\n *  \\param[in] step finite difference value for the stencil\n */\ninline double sevenPointStencil(const DifferentiableFunction & func,\n        const Eigen::Vector3d & arg_1, const Eigen::Vector3d & arg_2,\n        const Eigen::Vector3d & direction, double step = 1.0e-04)\n{\n    // f(x-3h)\n    Eigen::Vector3d delta_m3 = arg_1 - 3.0 * direction * step / direction.norm();\n    // f(x-2h)\n    Eigen::Vector3d delta_m2 = arg_1 - 2.0 * direction * step / direction.norm();\n    // f(x-h)\n    Eigen::Vector3d delta_m1 = arg_1 - direction * step / direction.norm();\n    // f(x+h)\n    Eigen::Vector3d delta_1  = arg_1 + direction * step / direction.norm();\n    // f(x+2h)\n    Eigen::Vector3d delta_2  = arg_1 + 2.0 * direction * step / direction.norm();\n    // f(x+3h)\n    Eigen::Vector3d delta_3  = arg_1 + 3.0 * direction * step / direction.norm();\n\n    Eigen::Matrix<double, 6, 1> stencil;\n    stencil << -1.0/60.0, 3.0/20.0, -3.0/4.0, 3.0/4.0, -3.0/20.0, 1.0/60.0;\n    Eigen::Matrix<double, 6, 1> function_values;\n    function_values << func(delta_m3, arg_2), func(delta_m2, arg_2), func(delta_m1, arg_2),\n                       func(delta_1,  arg_2), func(delta_2,  arg_2), func(delta_3, arg_2);\n\n    return (function_values.dot(stencil) / step);\n}\n\n#endif // STENCILS_HPP\n", "meta": {"hexsha": "8983a2d0fb816f47a0bbad8092b8f89a766a8799", "size": 5428, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/utils/Stencils.hpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/utils/Stencils.hpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/utils/Stencils.hpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7401574803, "max_line_length": 111, "alphanum_fraction": 0.6833087693, "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6065120041752992}}
{"text": "/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n */\n#include <almath/tools/almath.h>\n\n#include <almath/tools/altrigonometry.h>\n#include <almath/tools/almathio.h>\n#include <almath/tools/altransformhelpers.h>\n#include <boost/math/constants/constants.hpp>\n#include <gtest/gtest.h>\n#include <stdexcept>\n\nTEST(ALMathTest, moduloPI)\n{\n  float epsilon = 0.001f;\n  float pAngle  = 0.0f;\n\n  // case 0\n  pAngle = 0.0f;\n  AL::Math::modulo2PIInPlace(pAngle);\n  EXPECT_NEAR(pAngle, 0.0f, epsilon);\n\n  pAngle = 0.99f*AL::Math::PI;\n  AL::Math::modulo2PIInPlace(pAngle);\n  EXPECT_NEAR(pAngle, 0.99f*AL::Math::PI, epsilon);\n\n  pAngle = -0.99f*AL::Math::PI;\n  AL::Math::modulo2PIInPlace(pAngle);\n  EXPECT_NEAR(pAngle, -0.99f*AL::Math::PI, epsilon);\n\n  // case 1\n  pAngle = AL::Math::PI + 0.5f;\n  AL::Math::modulo2PIInPlace(pAngle);\n  EXPECT_NEAR(pAngle, 0.5f-AL::Math::PI, epsilon);\n\n  pAngle = -AL::Math::PI - 0.5f;\n  AL::Math::modulo2PIInPlace(pAngle);\n  EXPECT_NEAR(pAngle, -0.5f+AL::Math::PI, epsilon);\n\n  // case 2\n  pAngle  = 10.0f*AL::Math::PI + 0.5f;\n  AL::Math::modulo2PIInPlace(pAngle);\n  EXPECT_NEAR(pAngle, 0.5f, epsilon);\n\n  pAngle  = -10.0f*AL::Math::PI - 0.5f;\n  AL::Math::modulo2PIInPlace(pAngle);\n  EXPECT_NEAR(pAngle, -0.5f, epsilon);\n\n  // case 3\n  pAngle  = 11.0f*AL::Math::PI + 0.5f;\n  AL::Math::modulo2PIInPlace(pAngle);\n  EXPECT_NEAR(pAngle, 0.5f-AL::Math::PI, epsilon);\n\n  pAngle  = -11.0f*AL::Math::PI - 0.5f;\n  AL::Math::modulo2PIInPlace(pAngle);\n  EXPECT_NEAR(pAngle, -0.5f+AL::Math::PI, epsilon);\n\n  pAngle = 1.0f;\n  EXPECT_NEAR(AL::Math::modulo2PI(pAngle), 1.0f, 1e-4f);\n  pAngle = 2 * AL::Math::PI;\n  EXPECT_NEAR(AL::Math::modulo2PI(pAngle), 0.0f, 1e-4f);\n  pAngle = -5 * AL::Math::PI_2;\n  EXPECT_NEAR(AL::Math::modulo2PI(pAngle), -AL::Math::PI_2, 1e-4f);\n  pAngle = 3 * AL::Math::PI_2;\n  EXPECT_NEAR(AL::Math::modulo2PI(pAngle), -AL::Math::PI_2, 1e-4f);\n  pAngle = AL::Math::PI;\n  EXPECT_NEAR(AL::Math::modulo2PI(pAngle), AL::Math::PI, 1e-4f);\n}\n\n\nTEST(ALMathTest, mean) {\n  EXPECT_THROW(AL::Math::meanAngle(std::vector<float>()),\n               std::runtime_error);\n  EXPECT_THROW(AL::Math::weightedMeanAngle(std::vector<float>(),\n                                           std::vector<float>()),\n               std::runtime_error);\n  std::vector<float> angles;\n  std::vector<float> weights;\n  angles.push_back(AL::Math::PI);\n  EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::meanAngle(angles) - AL::Math::PI),\n              0.f, 1e-3f);\n  EXPECT_THROW(AL::Math::weightedMeanAngle(angles, weights),\n               std::runtime_error);\n  weights.push_back(0.5f);\n  EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::weightedMeanAngle(angles, weights)\n                                  - AL::Math::PI),\n              0.f, 1e-3f);\n  angles.push_back(-AL::Math::PI);\n  weights.push_back(0.5f);\n  EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::meanAngle(angles) - AL::Math::PI),\n              0.f, 1e-3f);\n  EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::weightedMeanAngle(angles, weights)\n                                  - AL::Math::PI),\n              0.f, 1e-3f);\n  angles[0] = AL::Math::PI_2;\n  EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::meanAngle(angles) - 0.75f*AL::Math::PI),\n              0.f, 1e-3f);\n  EXPECT_NEAR(AL::Math::modulo2PI(AL::Math::weightedMeanAngle(angles, weights)\n                                  - 0.75f*AL::Math::PI),\n              0.f, 1e-3f);\n  angles[0] = 0.f;\n  EXPECT_THROW(AL::Math::meanAngle(angles), std::runtime_error);\n  EXPECT_THROW(AL::Math::weightedMeanAngle(angles, weights), std::runtime_error);\n  angles[0] = 0.f;\n  weights[0] = 1.f;\n  angles[1] = 0.5f*AL::Math::PI;\n  weights[1] = 0.5f;\n  EXPECT_NEAR(AL::Math::weightedMeanAngle(angles, weights),\n              std::atan(0.5f), 1e-3f);\n  weights[1] = 0.f;\n  EXPECT_THROW(AL::Math::weightedMeanAngle(angles, weights),\n              std::exception);\n  weights[1] = -1.f;\n  EXPECT_THROW(AL::Math::weightedMeanAngle(angles, weights),\n               std::runtime_error);\n}\n\nTEST(ALMathTest, clipData)\n{\n  float pMin  = -0.2f;\n  float pMax  = 0.5f;\n  float pData = 0.4f;\n  EXPECT_FALSE(AL::Math::clipData(pMin, pMax, pData));\n\n  pMin  = -0.2f;\n  pMax  = 0.5f;\n  pData = 0.6f;\n  EXPECT_TRUE(AL::Math::clipData(pMin, pMax, pData));\n  EXPECT_NEAR(pData, pMax, 0.0001f);\n\n  pMin  = -0.2f;\n  pMax  = 0.5f;\n  pData = -0.1f;\n  EXPECT_FALSE(AL::Math::clipData(pMin, pMax, pData));\n\n  pMin  = -0.2f;\n  pMax  = 0.5f;\n  pData = -0.3f;\n  EXPECT_TRUE(AL::Math::clipData(pMin, pMax, pData));\n  EXPECT_NEAR(pData, pMin, 0.0001f);\n\n  pData = 2.1f;\n  EXPECT_TRUE(AL::Math::clipData(1, 2, pData));\n  EXPECT_NEAR(pData, static_cast<float>(2), 0.0001f);\n}\n\nTEST(ALMathTest, clipDataVector)\n{\n  const float lEpsilon = 0.0001f;\n  std::vector<float> data(5, -1.0f);\n  bool isClipped = AL::Math::clipData(0.0f, 1.0f, data);\n  EXPECT_TRUE(isClipped);\n  for (unsigned int i=0; i<data.size(); ++i)\n  {\n    EXPECT_NEAR(data[i], 0.0f, lEpsilon);\n  }\n\n  data.clear();\n  data.push_back(-1.0f);\n  data.push_back(1.0f);\n  data.push_back(2.0f);\n  data.push_back(-0.5f);\n  data.push_back(3.0f);\n  std::vector<float> expectedData;\n  expectedData.push_back(0.0f);\n  expectedData.push_back(1.0f);\n  expectedData.push_back(1.0f);\n  expectedData.push_back(0.0f);\n  expectedData.push_back(1.0f);\n\n  isClipped = AL::Math::clipData(0.0f, 1.0f, data);\n  EXPECT_TRUE(data.size()==expectedData.size());\n  EXPECT_TRUE(isClipped);\n  for (unsigned int i=0; i<data.size(); ++i)\n  {\n    EXPECT_NEAR(data[i], expectedData[i], lEpsilon);\n  }\n\n  data.clear();\n  data.push_back(0.0f);\n  data.push_back(0.1f);\n  data.push_back(0.2f);\n  data.push_back(0.3f);\n  data.push_back(0.4f);\n  expectedData = data;\n  isClipped = AL::Math::clipData(0.0f, 1.0f, data);\n  EXPECT_TRUE(data.size()==expectedData.size());\n  EXPECT_FALSE(isClipped);\n  for (unsigned int i=0; i<data.size(); ++i)\n  {\n    EXPECT_NEAR(data[i], expectedData[i], lEpsilon);\n  }\n}\n\nTEST(ALMathTest, clipDataVectorVector)\n{\n  const float lEpsilon = 0.0001f;\n  std::vector<float> data(5, -1.0f);\n  std::vector<std::vector<float> > dataList(5, data);\n  bool isClipped = AL::Math::clipData(0.0f, 1.0f, dataList);\n  EXPECT_TRUE(isClipped);\n  for (unsigned int i=0; i<dataList.size(); ++i)\n  {\n    for (unsigned int j=0; j<dataList[i].size(); ++j)\n    {\n      EXPECT_NEAR(dataList[i][j], 0.0f, lEpsilon);\n    }\n  }\n}\n\nTEST(ALMathTest, changeReferencePose2D)\n{\n  float pTheta = 90.0f*AL::Math::TO_RAD;\n  AL::Math::Pose2D pPosIn;\n  AL::Math::Pose2D pPosOut;\n\n  pPosIn = AL::Math::Pose2D(10.0f, 0.0f, 0.5f);\n  AL::Math::changeReferencePose2D(pTheta, pPosIn, pPosOut);\n  EXPECT_TRUE(pPosOut.isNear(AL::Math::Pose2D(0.0f, 10.0f, 0.5f), 0.001f));\n\n  pPosIn = AL::Math::Pose2D(0.0f, 10.0f, 0.5f);\n  AL::Math::changeReferencePose2D(pTheta, pPosIn, pPosOut);\n  EXPECT_TRUE(pPosOut.isNear(AL::Math::Pose2D(-10.0f, 0.0f, 0.5f), 0.001f));\n\n  pPosIn = AL::Math::Pose2D(-10.0f, 0.0f, 0.5f);\n  AL::Math::changeReferencePose2D(pTheta, pPosIn, pPosOut);\n  EXPECT_TRUE(pPosOut.isNear(AL::Math::Pose2D(0.0f, -10.0f, 0.5f), 0.001f));\n\n  pPosIn = AL::Math::Pose2D(0.0f, -10.0f, 0.5f);\n  AL::Math::changeReferencePose2D(pTheta, pPosIn, pPosOut);\n  EXPECT_TRUE(pPosOut.isNear(AL::Math::Pose2D(10.0f, 0.0f, 0.5f), 0.001f));\n}\n\nTEST(ALMathTest, changeReferencePose2DInPlace)\n{\n  float pTheta = 90.0f*AL::Math::TO_RAD;\n  AL::Math::Pose2D pPosIn;\n\n  pPosIn = AL::Math::Pose2D(10.0f, 0.0f, 0.5f);\n  AL::Math::changeReferencePose2DInPlace(pTheta, pPosIn);\n  EXPECT_TRUE(pPosIn.isNear(AL::Math::Pose2D(0.0f, 10.0f, 0.5f), 0.001f));\n\n  pPosIn = AL::Math::Pose2D(0.0f, 10.0f, 0.5f);\n  AL::Math::changeReferencePose2DInPlace(pTheta, pPosIn);\n  EXPECT_TRUE(pPosIn.isNear(AL::Math::Pose2D(-10.0f, 0.0f, 0.5f), 0.001f));\n\n  pPosIn = AL::Math::Pose2D(-10.0f, 0.0f, 0.5f);\n  AL::Math::changeReferencePose2DInPlace(pTheta, pPosIn);\n  EXPECT_TRUE(pPosIn.isNear(AL::Math::Pose2D(0.0f, -10.0f, 0.5f), 0.001f));\n\n  pPosIn = AL::Math::Pose2D(0.0f, -10.0f, 0.5f);\n  AL::Math::changeReferencePose2DInPlace(pTheta, pPosIn);\n  EXPECT_TRUE(pPosIn.isNear(AL::Math::Pose2D(10.0f, 0.0f, 0.5f), 0.001f));\n}\n\n\nTEST(ALMathTest, position3DFromPosition6D)\n{\n  AL::Math::Position6D pPose6d        = AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f);\n  AL::Math::Position3D pPos3dExpected = AL::Math::Position3D(0.1f, 0.2f, 0.3f);\n\n  AL::Math::Position3D pPose3dResult = AL::Math::position3DFromPosition6D(pPose6d);\n\n  EXPECT_TRUE(pPose3dResult.isNear(pPos3dExpected, 0.0001f));\n}\n\nTEST(ALMathTest, position2DFromPose2D)\n{\n  const AL::Math::Pose2D pPose2d(0.1f, 0.2f, 0.3f);\n  const AL::Math::Position2D pPos2dExpected(0.1f, 0.2f);\n\n  const AL::Math::Position2D& pPose2dResult =\n      AL::Math::position2DFromPose2D(pPose2d);\n\n  EXPECT_TRUE(pPose2dResult.isNear(pPos2dExpected, 0.0001f));\n}\n\nTEST(ALMathTest, pose2DFromPosition2DInPlace)\n{\n  const AL::Math::Position2D pPosition2d(0.1f, 0.2f);\n  const AL::Math::Pose2D pPos2dExpected(0.1f, 0.2f, 0.5f);\n\n  AL::Math::Pose2D pPose2dResult = AL::Math::Pose2D(10.0f, 20.0f, 30.0f);\n  AL::Math::pose2DFromPosition2DInPlace(pPosition2d, 0.5f, pPose2dResult);\n\n  EXPECT_TRUE(pPose2dResult.isNear(pPos2dExpected, 0.0001f));\n}\n\nTEST(ALMathTest, pose2DFromPosition2D)\n{\n  const AL::Math::Position2D pPosition2d(0.1f, 0.2f);\n  const AL::Math::Pose2D pPos2dExpected(0.1f, 0.2f, 0.0f);\n\n  const AL::Math::Pose2D& pPose2dResult =\n      AL::Math::pose2DFromPosition2D(pPosition2d);\n\n  EXPECT_TRUE(pPose2dResult.isNear(pPos2dExpected, 0.0001f));\n\n  const AL::Math::Position2D pPosition2d2(0.1f, 0.2f);\n  const AL::Math::Pose2D pPos2dExpected2(0.1f, 0.2f, 0.5f);\n\n  const AL::Math::Pose2D& pPose2dResult2 =\n      AL::Math::pose2DFromPosition2D(pPosition2d2, 0.5f);\n\n  EXPECT_TRUE(pPose2dResult2.isNear(pPos2dExpected2, 0.0001f));\n}\n\n\nTEST(ALMathTest, Position6DFromVelocity6D)\n{\n  const AL::Math::Velocity6D pVIn =\n      AL::Math::Velocity6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f);\n  const AL::Math::Position6D pPosIn =\n      AL::Math::position6DFromVelocity6D(pVIn);\n\n  const AL::Math::Position6D pPosOut =\n      AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f);\n\n  EXPECT_TRUE(pPosIn.isNear(pPosOut, 0.0001f));\n}\n\nTEST(ALMathTest, position2DFromPose2DInPlace)\n{\n  const AL::Math::Pose2D pose2D = AL::Math::Pose2D(1.0f, 2.0f, 3.0f);\n  AL::Math::Position2D position2D = AL::Math::Position2D(10.0f, 20.0f);\n\n  AL::Math::position2DFromPose2DInPlace(pose2D, position2D);\n  EXPECT_TRUE(position2D.isNear(AL::Math::Position2D(1.0f, 2.0f), 0.0001f));\n}\n\n\nTEST(ALMathTest, variousOperator)\n{\n  //inline Position3D operator*(\n  //  const Rotation&   pRot,\n  //  const Position3D& pPos)\n  AL::Math::Rotation   pRot;\n  AL::Math::Position3D pPos3D;\n  AL::Math::Position3D pPosIn = pRot*pPos3D;\n  AL::Math::Position3D pPosOut = AL::Math::Position3D();\n  EXPECT_TRUE(pPosIn.isNear(pPosOut, 0.0001f));\n\n  pRot = AL::Math::Rotation();\n  pPos3D = AL::Math::Position3D(1.0f, -1.0f, 0.5f);\n  pPosIn = pRot*pPos3D;\n  pPosOut = AL::Math::Position3D(1.0f, -1.0f, 0.5f);\n  EXPECT_TRUE(pPosIn.isNear(pPosOut, 0.0001f));\n\n  pRot = AL::Math::Rotation::fromRotX(0.5f);\n  pPos3D = AL::Math::Position3D(1.0f, -1.0f, 0.5f);\n  pPosIn = pRot*pPos3D;\n  pPosOut = AL::Math::Position3D(1.00000000000000f, -1.11729533119247f, -0.04063425765902f);\n  EXPECT_TRUE(pPosIn.isNear(pPosOut, 0.0001f));\n\n  //inline Velocity6D operator*(\n  //  const float       pK,\n  //  const Position6D& pDelta)\n  float pK = 10.0f;\n  AL::Math::Position6D pPos6D = AL::Math::Position6D(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f);\n  AL::Math::Velocity6D pVel6DIn = pK*pPos6D;\n  AL::Math::Velocity6D pVel6DOut = AL::Math::Velocity6D(10.0f, 20.0f, 30.0f, 40.0f, 50.0f, 60.0f);\n  EXPECT_TRUE(pVel6DIn.isNear(pVel6DOut, 0.0001f));\n\n  //Velocity3D operator* (const Rotation&   pRot, const Velocity3D& pVel);\n  AL::Math::Velocity3D pVIn1 = AL::Math::Velocity3D(0.5f, 0.3f, 0.1f);\n  AL::Math::Rotation   pRot1 = AL::Math::rotationFromRotZ(AL::Math::PI_2);\n  AL::Math::Velocity3D pVIn2 = pRot1*pVIn1;\n  AL::Math::Velocity3D pVOut = AL::Math::Velocity3D(-0.3f, 0.5f, 0.1f);\n  EXPECT_TRUE(pVIn2.isNear(pVOut, 0.0001f));\n\n}\n\nTEST(ALMathTest, isLeft)\n{\n}\n\n\nTEST(ALMathTest, FilterPosition6D)\n{\n}\n\nTEST(ALMathTest, AxisMaskToPosition6DOn)\n{\n}\n\nTEST(ALMathTest, AxisMaskToPosition6DOff)\n{\n}\n\nTEST(ALMathTest, AxisMaskToVelocity6DOn)\n{\n}\n\nTEST(ALMathTest, RotationFromAngleDirection)\n{\n  AL::Math::Rotation pRotOut;\n  float pTheta = 0.0f;\n  AL::Math::Position3D pPos = AL::Math::Position3D(0.0f, 0.0f, 0.0f);\n\n  // ****** test 0 ****** //\n  ASSERT_THROW(AL::Math::rotationFromAngleDirection(pTheta, pPos), std::runtime_error);\n\n  // ****** test 1 ****** //\n  pTheta = 0.0f;\n  pPos = AL::Math::Position3D(1.0f, 0.0f, 0.0f);\n  pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos);\n  EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation()));\n\n  // ****** test 2 ****** //\n  pTheta = 0.0f;\n  pPos = AL::Math::Position3D(0.0f, 1.0f, 0.0f);\n  pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos);\n  EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation()));\n\n  // ****** test 3 ****** //\n  pTheta = 0.0f;\n  pPos = AL::Math::Position3D(0.0f, 0.0f, 1.0f);\n  pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos);\n  EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation()));\n\n\n  // ****** test 4 ****** //\n  pTheta = 15.0f*AL::Math::TO_RAD;\n  pPos = AL::Math::Position3D(1.0f, 0.0f, 0.0f);\n  pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos);\n  EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation::fromRotX(pTheta)));\n  EXPECT_FALSE(pRotOut.isNear(AL::Math::Rotation()));\n\n  // ****** test 5 ****** //\n  pTheta = 15.0f*AL::Math::TO_RAD;\n  pPos = AL::Math::Position3D(0.0f, 1.0f, 0.0f);\n  pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos);\n  EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation::fromRotY(pTheta)));\n  EXPECT_FALSE(pRotOut.isNear(AL::Math::Rotation()));\n\n  // ****** test 6 ****** //\n  pTheta = 15.0f*AL::Math::TO_RAD;\n  pPos = AL::Math::Position3D(0.0f, 0.0f, 1.0f);\n  pRotOut = AL::Math::rotationFromAngleDirection(pTheta, pPos);\n  EXPECT_TRUE(pRotOut.isNear(AL::Math::Rotation::fromRotZ(pTheta)));\n  EXPECT_FALSE(pRotOut.isNear(AL::Math::Rotation()));\n\n  EXPECT_TRUE(AL::Math::Rotation::fromRotXPi().isNear(\n                  AL::Math::Rotation::fromRotX(\n                     boost::math::constants::pi<float>())));\n  EXPECT_TRUE(AL::Math::Rotation::fromRotYPi().isNear(\n                  AL::Math::Rotation::fromRotY(\n                     boost::math::constants::pi<float>())));\n  EXPECT_TRUE(AL::Math::Rotation::fromRotZPi().isNear(\n                  AL::Math::Rotation::fromRotZ(\n                     boost::math::constants::pi<float>())));\n  EXPECT_TRUE(AL::Math::Rotation::fromRotZHalfPi().isNear(\n                  AL::Math::Rotation::fromRotZ(\n                     0.5f * boost::math::constants::pi<float>())));\n}\n\nTEST(ALMathTest, quaternionOperator)\n{\n  AL::Math::Quaternion pQuat;\n  AL::Math::Position3D pPos;\n  AL::Math::Position3D result;\n  result = pQuat * pPos;\n  EXPECT_NEAR(pPos.x, 0.0f, 1e-6f);\n  EXPECT_NEAR(pPos.y, 0.0f, 1e-6f);\n  EXPECT_NEAR(pPos.z, 0.0f, 1e-6f);\n\n  // Test 90\u00b0 rotation around the x axis.\n  pQuat = AL::Math::Quaternion(0.7071f, 0.7071f, 0.0f, 0.0f);\n  pPos = AL::Math::Position3D(0.0f, 1.0f, 0.0f);\n  result = pQuat * pPos;\n  EXPECT_NEAR(result.x, 0.0f, 1e-4f);\n  EXPECT_NEAR(result.y, 0.0f, 1e-4f);\n  EXPECT_NEAR(result.z, 1.0f, 1e-4f);\n\n  // Test 90\u00b0 rotation around the y axis.\n  pQuat = AL::Math::Quaternion(0.7071f, 0.0f, 0.7071f, 0.0f);\n  pPos = AL::Math::Position3D(0.0f, 0.0f, 1.0f);\n  result = pQuat * pPos;\n  EXPECT_NEAR(result.x, 1.0f, 1e-4f);\n  EXPECT_NEAR(result.y, 0.0f, 1e-4f);\n  EXPECT_NEAR(result.z, 0.0f, 1e-4f);\n\n  // Test 90\u00b0 rotation around the z axis.\n  pQuat = AL::Math::Quaternion(0.7071f, 0.0f, 0.0f, 0.7071f);\n  pPos = AL::Math::Position3D(1.0f, 0.0f, 0.0f);\n  result = pQuat * pPos;\n  EXPECT_NEAR(result.x, 0.0f, 1e-4f);\n  EXPECT_NEAR(result.y, 1.0f, 1e-4f);\n  EXPECT_NEAR(result.z, 0.0f, 1e-4f);\n\n}\n\nTEST(ALMathTest, position6DFromPose2DInPlace)\n{\n  const AL::Math::Pose2D pPose2d = AL::Math::Pose2D(0.1f, 0.2f, 0.3f);\n  const AL::Math::Position6D pPose6dExpected =\n      AL::Math::Position6D(0.1f, 0.2f, 0.0f, 0.0f, 0.0f, 0.3f);\n\n  AL::Math::Position6D pPose6dComputed =\n      AL::Math::Position6D(10.0f, 10.0f, 10.0f, 10.0f, 10.0f, 10.0f);\n  AL::Math::position6DFromPose2DInPlace(\n        pPose2d,\n        pPose6dComputed);\n\n  EXPECT_TRUE(pPose6dComputed.isNear(pPose6dExpected, 0.0001f));\n}\n\nTEST(ALMathTest, position6DFromPose2D)\n{\n  AL::Math::Pose2D pPose2d = AL::Math::Pose2D(0.1f, 0.2f, 0.3f);\n  AL::Math::Position6D pPose6dExpected = AL::Math::Position6D(0.1f, 0.2f, 0.0f, 0.0f, 0.0f, 0.3f);\n\n  AL::Math::Position6D pPose6dComputed = AL::Math::position6DFromPose2D(pPose2d);\n\n  EXPECT_TRUE(pPose6dComputed.isNear(pPose6dExpected, 0.0001f));\n}\n\nTEST(ALMathTest, pose2DFromPosition6DInPlace)\n{\n  AL::Math::Position6D pPose6d = AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f);\n  AL::Math::Pose2D pPose2dExpected = AL::Math::Pose2D(0.1f, 0.2f, 0.6f);\n\n  AL::Math::Pose2D pPose2dComputed;\n  AL::Math::pose2DFromPosition6DInPlace(pPose6d, pPose2dComputed);\n\n  EXPECT_TRUE(pPose2dComputed.isNear(pPose2dExpected, 0.0001f));\n}\n\nTEST(ALMathTest, pose2DFromPosition6D)\n{\n  AL::Math::Position6D pPose6d = AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f);\n  AL::Math::Pose2D pPose2dExpected = AL::Math::Pose2D(0.1f, 0.2f, 0.6f);\n\n  AL::Math::Pose2D pPose2dComputed = AL::Math::pose2DFromPosition6D(pPose6d);\n\n  EXPECT_TRUE(pPose2dComputed.isNear(pPose2dExpected, 0.0001f));\n}\n\nTEST(ALMathTest, position6DFromPosition3DInPlace)\n{\n  const AL::Math::Position3D position3D =\n      AL::Math::Position3D(0.1f, 0.2f, 0.3f);\n\n  AL::Math::Position6D position6D =\n      AL::Math::Position6D(10.1f, 10.2f, 10.0f, 10.0f, 10.0f, 10.3f);\n\n  AL::Math::position6DFromPosition3DInPlace(position3D, position6D);\n\n  EXPECT_TRUE(position6D.isNear(\n                AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.0f, 0.0f, 0.0f), 0.0001f));\n}\n\nTEST(ALMathTest, position6DFromPosition3D)\n{\n  const AL::Math::Position3D position3D =\n      AL::Math::Position3D(0.1f, 0.2f, 0.3f);\n\n  const AL::Math::Position6D position6D =\n      AL::Math::position6DFromPosition3D(position3D);\n\n  EXPECT_TRUE(position6D.isNear(\n                AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.0f, 0.0f, 0.0f), 0.0001f));\n}\n\n\nTEST(ALMathTest, multiplicationPose2DPosition2D)\n{\n  AL::Math::Pose2D pVal;\n  AL::Math::Position2D pPos;\n  AL::Math::Position2D pExpected;\n  AL::Math::Position2D pResult;\n\n  pVal      = AL::Math::Pose2D(0.0f, 0.0f, AL::Math::PI_2);\n  pPos      = AL::Math::Position2D(1.0f, 0.0f);\n  pExpected = AL::Math::Position2D(0.0f, 1.0f);\n  pResult   = pVal*pPos;\n  EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f));\n\n  pVal      = AL::Math::Pose2D(0.0f, 0.0f, AL::Math::PI_2);\n  pPos      = AL::Math::Position2D(0.0f, 1.0f);\n  pExpected = AL::Math::Position2D(-1.0f, 0.0f);\n  pResult   = pVal*pPos;\n  EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f));\n\n  pVal      = AL::Math::Pose2D(1.0f, 1.0f, -AL::Math::PI_2);\n  pPos      = AL::Math::Position2D(1.0f, 0.0f);\n  pExpected = AL::Math::Position2D(1.0f, 0.0f);\n  pResult   = pVal*pPos;\n  EXPECT_TRUE(pResult.isNear(pExpected, 0.0001f));\n}\n\nTEST(ALMathTest, quaternionFromRotation3D)\n{\n  for (unsigned int i=0; i<360; ++i)\n  {\n    const float angleX = static_cast<float>(i)*AL::Math::TO_RAD;\n    const AL::Math::Quaternion quatX =\n        AL::Math::quaternionFromAngleAndAxisRotation(angleX, 1.0f, 0.0f, 0.0f);\n    for (unsigned int j=0; j<360; ++j)\n    {\n      const float angleY = static_cast<float>(j)*AL::Math::TO_RAD;\n      const AL::Math::Quaternion quatY =\n          AL::Math::quaternionFromAngleAndAxisRotation(angleY, 0.0f, 1.0f, 0.0f);\n      for (unsigned int k=0; k<360; ++k)\n      {\n        const float angleZ = static_cast<float>(k)*AL::Math::TO_RAD;\n        const AL::Math::Quaternion quatZ =\n            AL::Math::quaternionFromAngleAndAxisRotation(angleZ, 0.0f, 0.0f, 1.0f);\n\n        const AL::Math::Quaternion quatExpected = quatZ*quatY*quatX;\n        const AL::Math::Rotation3D rot3DZYX(angleX, angleY, angleZ);\n        const AL::Math::Quaternion quatResult =\n            AL::Math::quaternionFromRotation3D(rot3DZYX);\n        EXPECT_TRUE(quatResult.isNear(quatExpected, 0.001f));\n      }\n    }\n  }\n}\n\nTEST(ALMathTest, rotation3DFromQuaternion1)\n{\n  const float lAngleX = 0.5f;\n  const float lAngleY = -0.3f;\n  AL::Math::Quaternion quat =\n      AL::Math::quaternionFromAngleAndAxisRotation(lAngleY, 0.0f, 1.0f , 0.0f)*\n      AL::Math::quaternionFromAngleAndAxisRotation(lAngleX, 1.0f, 0.0f , 0.0f);\n\n  AL::Math::Rotation3D lRotation3D;\n  AL::Math::rotation3DFromQuaternion(quat, lRotation3D);\n  EXPECT_NEAR(lRotation3D.wx, lAngleX, 0.0001f);\n  EXPECT_NEAR(lRotation3D.wy, lAngleY, 0.0001f);\n\n  AL::Math::Quaternion lQuat;\n  AL::Math::quaternionFromRotation3D(lRotation3D, lQuat);\n  EXPECT_NEAR(lQuat.w, quat.w, 0.0001f);\n  EXPECT_NEAR(lQuat.x, quat.x, 0.0001f);\n  EXPECT_NEAR(lQuat.y, quat.y, 0.0001f);\n  EXPECT_NEAR(lQuat.z, quat.z, 0.0001f);\n\n  // new test jory\n  AL::Math::Rotation3D rotation3DRef(0.0213f, 0.0139f, 0.02619f);\n  quat = AL::Math::Quaternion(0.99983f, 0.01056f, 0.00712f, 0.01302f);\n  quat = quat.normalize();\n  AL::Math::Rotation3D rotation3D;\n  AL::Math::rotation3DFromQuaternion(quat, rotation3D);\n  EXPECT_TRUE(rotation3D.isNear(rotation3DRef, 0.0001f));\n\n  rotation3DRef = AL::Math::Rotation3D(-0.00350f, 0.0f, 0.0314f);\n  quat = AL::Math::Quaternion(0.99988f, -0.00175f,\n                              -0.00003f, 0.01571f);\n\n  AL::Math::rotation3DFromQuaternion(quat, rotation3D);\n\n  EXPECT_TRUE(rotation3D.isNear(rotation3DRef, 0.0001f));\n\n  const float wx = -180.0f*AL::Math::TO_RAD;\n  const float wy = -90.0f*AL::Math::TO_RAD;\n  const float wz = -175.0f*AL::Math::TO_RAD;\n  quat =\n      AL::Math::quaternionFromAngleAndAxisRotation(wz, 0.0f, 0.0f, 1.0f)*\n      AL::Math::quaternionFromAngleAndAxisRotation(wy, 0.0f, 1.0f, 0.0f)*\n      AL::Math::quaternionFromAngleAndAxisRotation(wx, 1.0f, 0.0f, 0.0f);\n  const AL::Math::Rotation3D rot3D = AL::Math::rotation3DFromQuaternion(quat);\n  EXPECT_TRUE(rot3D.wx == rot3D.wx);\n  EXPECT_TRUE(rot3D.wy == rot3D.wy);\n  EXPECT_TRUE(rot3D.wz == rot3D.wz);\n}\n\nTEST(ALMathTest, rotation3DFromQuaternion2)\n{\n  // function quaternionFromRotation3D must be check before\n  for (int i=-180; i<180; ++i)\n  {\n    const float angleX = static_cast<float>(i)*AL::Math::TO_RAD;\n    const AL::Math::Quaternion quatX =\n        AL::Math::quaternionFromAngleAndAxisRotation(angleX, 1.0f, 0.0f, 0.0f);\n    for (int j=-180; j<180; ++j)\n    {\n      const float angleY = static_cast<float>(j)*AL::Math::TO_RAD;\n      const AL::Math::Quaternion quatY =\n          AL::Math::quaternionFromAngleAndAxisRotation(angleY, 0.0f, 1.0f, 0.0f);\n      for (int k=-180; k<180; ++k)\n      {\n        const float angleZ = static_cast<float>(k)*AL::Math::TO_RAD;\n        const AL::Math::Quaternion quatZ =\n            AL::Math::quaternionFromAngleAndAxisRotation(angleZ, 0.0f, 0.0f, 1.0f);\n\n        const AL::Math::Quaternion quatExpected = quatZ*quatY*quatX;\n        const AL::Math::Rotation3D rot3D =\n            AL::Math::rotation3DFromQuaternion(quatExpected);\n\n        const AL::Math::Quaternion quatResult =\n            AL::Math::quaternionFromRotation3D(rot3D);\n\n        EXPECT_TRUE(quatExpected.isNear(quatResult, 0.001f));\n      }\n    }\n  }\n}\n\nTEST(ALMathTest, quaternionPosition3DFromPosition6D)\n{\n  // function quaternionFromRotation3D must be check before\n  const float lEpsilon = 0.001f;\n  const AL::Math::Position6D pos6D =\n      AL::Math::Position6D(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f);\n  AL::Math::Quaternion qua;\n  AL::Math::Position3D pos3D;\n\n  AL::Math::quaternionPosition3DFromPosition6D(pos6D, qua, pos3D);\n\n  const AL::Math::Quaternion quaExpected =\n      AL::Math::quaternionFromRotation3D(AL::Math::Rotation3D(0.4f, 0.5f, 0.6f));\n  EXPECT_TRUE(qua.isNear(quaExpected, lEpsilon));\n  EXPECT_TRUE(pos3D.isNear(AL::Math::Position3D(0.1f, 0.2f, 0.3f), lEpsilon));\n}\n\nTEST(ALMathTest, pointMassRotationalInertia)\n{\n  AL::Math::Position3D pos123(1.f, 2.f, 3.f);\n  std::vector<float> inertia;\n\n  pointMassRotationalInertia(0.f, pos123, inertia);\n  ASSERT_EQ(9, inertia.size());\n  ASSERT_EQ(std::vector<float>(9, 0.f), inertia);\n\n  pointMassRotationalInertia(1.f, AL::Math::Position3D(), inertia);\n  ASSERT_EQ(std::vector<float>(9, 0.f), inertia);\n\n  float m10 = 10.f;\n  pointMassRotationalInertia(m10, pos123, inertia);\n  // check symmetry\n  ASSERT_TRUE(inertia[1] == inertia[3]);\n  ASSERT_TRUE(inertia[2] == inertia[6]);\n  ASSERT_TRUE(inertia[5] == inertia[7]);\n  // check values\n  ASSERT_EQ(m10*(4+9), inertia[0]);\n  ASSERT_EQ(m10*(1+9), inertia[4]);\n  ASSERT_EQ(m10*(1+4), inertia[8]);\n  ASSERT_EQ(-m10*1*2, inertia[1]);\n  ASSERT_EQ(-m10*1*3, inertia[2]);\n  ASSERT_EQ(-m10*2*3, inertia[5]);\n}\n", "meta": {"hexsha": "435a3fbfef3478542363abfb13e93de86e7595c2", "size": 24853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/tools/almath_test.cpp", "max_stars_repo_name": "UCCS-Social-Robotics/libalmath", "max_stars_repo_head_hexsha": "608475eced68452eb19ef09c46e1916ac597ed88", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-14T20:34:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-14T05:53:00.000Z", "max_issues_repo_path": "test/tools/almath_test.cpp", "max_issues_repo_name": "UCCS-Social-Robotics/libalmath", "max_issues_repo_head_hexsha": "608475eced68452eb19ef09c46e1916ac597ed88", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-14T05:52:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:18:20.000Z", "max_forks_repo_path": "test/tools/almath_test.cpp", "max_forks_repo_name": "UCCS-Social-Robotics/libalmath", "max_forks_repo_head_hexsha": "608475eced68452eb19ef09c46e1916ac597ed88", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-07-11T16:01:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T20:41:05.000Z", "avg_line_length": 33.3150134048, "max_line_length": 98, "alphanum_fraction": 0.6600410413, "num_tokens": 9692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6065120019989346}}
{"text": "// This example consists of a single static target which sits in one\n// place and does not move; in effect it has a \"GPS\" which measures\n// its position\n\n#include <Eigen/StdVector>\n#include <iostream>\n#include <stdint.h>\n \n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/cholmod/linear_solver_cholmod.h>\n#include <g2o/stuff/sampler.h>\n\n#include \"targetTypes3D.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace g2o;\n\nint main()\n{\n  // Set up the optimiser\n  SparseOptimizer optimizer;\n  optimizer.setVerbose(false);\n\n  // Create the block solver - the dimensions are specified because\n  // 3D observations marginalise to a 3D estimate\n  typedef BlockSolver<BlockSolverTraits<3, 3> > BlockSolver_3_3;\n  BlockSolver_3_3::LinearSolverType* linearSolver\n      = new LinearSolverCholmod<BlockSolver_3_3::PoseMatrixType>();\n  BlockSolver_3_3* blockSolver\n      = new BlockSolver_3_3(linearSolver);\n  OptimizationAlgorithmGaussNewton* solver\n    = new OptimizationAlgorithmGaussNewton(blockSolver);\n  optimizer.setAlgorithm(solver);\n\n  // Sample the actual location of the target\n  Vector3d truePoint(sampleUniform(-500, 500),\n                     sampleUniform(-500, 500),\n                     sampleUniform(-500, 500));\n\n  // Construct vertex which corresponds to the actual point of the target\n  VertexPosition3D* position = new VertexPosition3D();\n  position->setId(0);\n  optimizer.addVertex(position);\n\n  // Now generate some noise corrupted measurements; for simplicity\n  // these are uniformly distributed about the true target. These are\n  // modelled as a unary edge because they do not like to, say,\n  // another node in the map.\n  int numMeasurements = 10;\n  double noiseLimit = sqrt(12.);\n  double noiseSigma = noiseLimit*noiseLimit / 12.0;\n\n  for (int i = 0; i < numMeasurements; i++)\n    {\n      Vector3d measurement = truePoint +\n        Vector3d(sampleUniform(-0.5, 0.5) * noiseLimit,\n                 sampleUniform(-0.5, 0.5) * noiseLimit,\n                 sampleUniform(-0.5, 0.5) * noiseLimit);\n      GPSObservationPosition3DEdge* goe = new GPSObservationPosition3DEdge();\n      goe->setVertex(0, position);\n      goe->setMeasurement(measurement);\n      goe->setInformation(Matrix3d::Identity() / noiseSigma);\n      optimizer.addEdge(goe);\n    }\n\n  // Configure and set things going\n  optimizer.initializeOptimization();\n  optimizer.setVerbose(true);\n  optimizer.optimize(5);\n  \n  cout << \"truePoint=\\n\" << truePoint << endl;\n\n  cerr <<  \"computed estimate=\\n\" << dynamic_cast<VertexPosition3D*>(optimizer.vertices().find(0)->second)->estimate() << endl;\n\n  //position->setMarginalized(true);\n  \n  SparseBlockMatrix<MatrixXd> spinv;\n\n  optimizer.computeMarginals(spinv, position);\n\n\n\n  //optimizer.solver()->computeMarginals();\n\n  // covariance\n  //\n  cout << \"covariance\\n\" << spinv << endl;\n\n  cout << spinv.block(0,0) << endl;\n  \n}\n", "meta": {"hexsha": "3aa40df1844c01c05fddcc780f520d6821b88722", "size": 2997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Thirdparty/g2o/g2o/examples/target/static_target.cpp", "max_stars_repo_name": "liyi2017/StructSLAM", "max_stars_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57.0, "max_stars_repo_stars_event_min_datetime": "2018-03-11T03:35:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:39:26.000Z", "max_issues_repo_path": "Thirdparty/g2o/g2o/examples/target/static_target.cpp", "max_issues_repo_name": "jyakaranda/StructSLAM", "max_issues_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-07-29T08:08:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-20T09:25:31.000Z", "max_forks_repo_path": "Thirdparty/g2o/g2o/examples/target/static_target.cpp", "max_forks_repo_name": "jyakaranda/StructSLAM", "max_forks_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2017-07-23T11:33:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T05:35:53.000Z", "avg_line_length": 31.21875, "max_line_length": 127, "alphanum_fraction": 0.7087087087, "num_tokens": 775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6065120019989344}}
{"text": "\n#include <NTL/MatPrime.h>\n\n\nNTL_START_IMPL\n\n\nMatPrimeTablesType MatPrimeTables;\n// a truly GLOBAL variable, shared among all threads\n\n\n\n// For now, we use the same logic as for IsFFTPrime, \n// which is good enough\n\nstatic\nlong IsMatPrime(long n)\n{\n   long  m, x, y, z;\n   long j, k;\n\n\n   if (n <= 1 || n >= NTL_SP_BOUND) return 0;\n\n   if (n % 2 == 0) return 0;\n\n   if (n % 3 == 0) return 0;\n\n   if (n % 5 == 0) return 0;\n\n   if (n % 7 == 0) return 0;\n   \n   m = n - 1;\n   k = 0;\n   while ((m & 1) == 0) {\n      m = m >> 1;\n      k++;\n   }\n\n   for (;;) {\n      x = RandomBnd(n);\n\n      if (x == 0) continue;\n      z = PowerMod(x, m, n);\n      if (z == 1) continue;\n\n      x = z;\n      j = 0;\n      do {\n         y = z;\n         z = MulMod(y, y, n);\n         j++;\n      } while (j != k && z != 1);\n\n      if (z != 1 || y !=  n-1) return 0;\n\n      if (j == k) \n         break;\n   }\n\n   /* x^{2^k} = 1 mod n, x^{2^{k-1}} = -1 mod n */\n\n   long TrialBound;\n\n   TrialBound = m >> k;\n   if (TrialBound > 0) {\n      if (!ProbPrime(n, 5)) return 0;\n   \n      /* we have to do trial division by special numbers */\n   \n      TrialBound = SqrRoot(TrialBound);\n   \n      long a, b;\n   \n      for (a = 1; a <= TrialBound; a++) {\n         b = (a << k) + 1;\n         if (n % b == 0) return 0; \n      }\n   }\n\n   return 1;\n}\n\n\nstatic\nvoid NextMatPrime(long& q, long index)\n{\n   static long m = NTL_MatPrime_NBITS-1;\n   static long k = 0;\n   // m and k are truly GLOBAL variables, shared among\n   // all threads.  Access is protected by a critical section\n   // guarding MatPrimeTables\n\n   static long last_index = -1;\n   static long last_m = 0;\n   static long last_k = 0;\n\n   if (index == last_index) {\n      // roll back m and k...part of a simple error recovery\n      // strategy if an exception was thrown in the last \n      // invocation of UseMatPrime...probably of academic \n      // interest only\n\n      m = last_m;\n      k = last_k;\n   }\n   else {\n      last_index = index;\n      last_m = m;\n      last_k = k;\n   }\n\n   long cand;\n\n   for (;;) {\n      if (k == 0) {\n         m--;\n         if (m < 3) ResourceError(\"ran out of matrix primes\");\n         k = 1L << (NTL_MatPrime_NBITS-m-2);\n      }\n\n      k--;\n\n      cand = (1L << (NTL_MatPrime_NBITS-1)) + (k << (m+1)) + (1L << m) + 1;\n\n      if (!IsMatPrime(cand)) continue;\n      q = cand;\n      return;\n   }\n}\n\n\n\nvoid InitMatPrimeInfo(MatPrimeInfo& info, long q)\n{\n   info.q = q;\n   info.context = zz_pContext(q);\n}\n\n\nvoid UseMatPrime(long index)\n{\n   if (index < 0) LogicError(\"invalid matrix prime index\");\n   if (index >= NTL_MAX_MATPRIMES) ResourceError(\"matrix prime index too large\");\n\n   if (index+1 >= NTL_NSP_BOUND) ResourceError(\"matrix prime index too large\");\n   // largely acacedemic, but it is a convenient assumption\n\n   do {  // NOTE: thread safe lazy init\n      MatPrimeTablesType::Builder bld(MatPrimeTables, index+1);\n      long amt = bld.amt();\n      if (!amt) break;\n\n      long first = index+1-amt;\n      // initialize entries first..index\n\n      long i;\n      for (i = first; i <= index; i++) {\n         UniquePtr<MatPrimeInfo> info;\n         info.make();\n\n         long q, w;\n         NextMatPrime(q, i);\n\n         InitMatPrimeInfo(*info, q);\n         bld.move(info);\n      }\n\n   } while (0);\n}\n\n\n#ifndef NTL_MatPrime_HALF_SIZE_STRATEGY\n\n\nvoid build(MatPrime_crt_helper& H, const ZZ& P)\n{\n   ZZ B, M, M1, M2, M3;\n   long n, i;\n   long q, t;\n   mulmod_t qinv;\n\n   sqr(B, P);\n   mul(B, B, NTL_MatPrimeLimit);\n   LeftShift(B, B, NTL_MatPrimeFudge);\n\n   set(M);\n   n = 0;\n   while (M <= B) {\n      UseMatPrime(n);\n      q = GetMatPrime(n);\n      n++;\n      mul(M, M, q);\n   }\n\n\n   double fn = double(n);\n\n   if (8.0*fn*(fn+48) > NTL_FDOUBLE_PRECISION)\n      ResourceError(\"modulus too big\");\n\n   H.NumPrimes = n;\n   H.sz = P.size();\n   H.prime.SetLength(n);\n   H.prime_recip.SetLength(n);\n   H.u.SetLength(n);\n   H.uqinv.SetLength(n);\n   H.ZZ_red_struct.SetLength(n);\n\n   H.coeff.SetSize(n, P.size());\n\n   H.montgomery_struct.init(P, ZZ(n) << NTL_MatPrime_NBITS);\n\n   ZZ qq, rr;\n\n   DivRem(qq, rr, M, P);\n\n   NegateMod(H.MinusMModP, rr, P);\n\n   H.montgomery_struct.adjust(H.MinusMModP);\n\n   for (i = 0; i < n; i++) {\n      q = GetMatPrime(i);\n      qinv = MatPrimeTables[i]->context.ModulusInverse();\n\n      long tt = rem(qq, q);\n\n      mul(M2, P, tt);\n      add(M2, M2, rr); \n      div(M2, M2, q);  // = (M/q) rem p\n      \n\n      div(M1, M, q);\n      t = rem(M1, q);\n      t = InvMod(t, q);\n\n      // montgomery\n      H.montgomery_struct.adjust(M2);\n\n\n      H.prime[i] = q;\n      H.prime_recip[i] = 1/double(q);\n      H.u[i] = t;\n      H.uqinv[i] = PrepMulModPrecon(H.u[i], q, qinv);\n      H.ZZ_red_struct[i] = &MatPrimeTables[i]->context.ZZ_red_struct();\n      H.coeff[i] = M2;\n   }\n\n   H.cost = double(H.sz)*double(n);\n\n}\n\n\nvoid reduce(const MatPrime_crt_helper& H, const ZZ& value, MatPrime_residue_t *remainders,\n            MatPrime_crt_helper_scratch& scratch)\n{\n   long n = H.NumPrimes;\n   const sp_ZZ_reduce_struct *const *red_struct = H.ZZ_red_struct.elts();\n\n   for (long i = 0; i < n; i++)\n      remainders[i] = red_struct[i]->rem(value);\n}\n\n\n\nvoid reconstruct(const MatPrime_crt_helper& H, ZZ& value, const MatPrime_residue_t *remainders,\n                 MatPrime_crt_helper_scratch& scratch)\n{\n   ZZ& t = scratch.t;\n\n   long nprimes = H.NumPrimes;\n   const long *u = H.u.elts();\n   const long *prime = H.prime.elts();\n   const mulmod_precon_t  *uqinv = H.uqinv.elts();\n   const double *prime_recip = H.prime_recip.elts();\n\n   double y = 0.0;\n\n   QuickAccumBegin(t, H.sz);\n   for (long i = 0; i < nprimes; i++) {\n      long r = MulModPrecon(remainders[i], u[i], prime[i], uqinv[i]);\n      y += double(r)*prime_recip[i];\n      QuickAccumMulAdd(t, H.coeff[i], r);\n   }\n\n   long q = long(y + 0.5);\n   QuickAccumMulAdd(t, H.MinusMModP, q);\n\n   QuickAccumEnd(t);\n\n   // montgomery\n   H.montgomery_struct.eval(value, t);\n\n}\n\n\n\n#else\n\n\n\nvoid build(MatPrime_crt_helper& H, const ZZ& P)\n{\n   ZZ B, M, M1, M2, M3;\n   long n, i, j;\n   long q, t;\n   mulmod_t qinv;\n\n   sqr(B, P);\n   mul(B, B, NTL_MatPrimeLimit);\n   LeftShift(B, B, NTL_MatPrimeFudge);\n\n   set(M);\n   n = 0;\n   while (M <= B) {\n      UseMatPrime(n);\n      q = GetMatPrime(n);\n      n++;\n      mul(M, M, q);\n   }\n\n\n   double fn = double(n);\n\n   if (8.0*fn*(fn+48) > NTL_FDOUBLE_PRECISION)\n      ResourceError(\"modulus too big\");\n\n   long n_half_ceil = (n+1)/2;\n\n\n   H.NumPrimes = n;\n   H.sz = P.size();\n   H.prime.SetLength(n);\n   H.prime_recip.SetLength(n);\n   H.u.SetLength(n);\n   H.uqinv.SetLength(n);\n   H.red_struct.SetLength(n);\n\n   H.ZZ_red_struct.SetLength(n_half_ceil);\n   H.coeff.SetSize(n_half_ceil, P.size());\n\n   H.montgomery_struct.init(P, ZZ(n) << (2*NTL_MatPrime_NBITS));\n\n\n   for (i = 0; i < n; i++) {\n      q = GetMatPrime(i);\n      qinv = MatPrimeTables[i]->context.ModulusInverse();\n\n      div(M1, M, q);\n      t = rem(M1, q);\n      t = InvMod(t, q); // = (M/q)^{-1} rem q \n\n      H.prime[i] = q;\n      H.prime_recip[i] = 1/double(q);\n      H.u[i] = t;\n      H.uqinv[i] = PrepMulModPrecon(H.u[i], q, qinv);\n      H.red_struct[i] = MatPrimeTables[i]->context.red_struct();\n\n   }\n\n   ZZ qq, rr;\n   DivRem(qq, rr, M, P);\n   NegateMod(H.MinusMModP, rr, P);\n   H.montgomery_struct.adjust(H.MinusMModP);\n\n   for (i = 0, j = 0; i < n; i += 2, j++) {\n      q = GetMatPrime(i);\n      if (i+1 < n) q *= GetMatPrime(i+1);\n\n      long tt = rem(qq, q);\n\n      mul(M2, P, tt);\n      add(M2, M2, rr); \n      div(M2, M2, q);  // = (M/q) rem p\n\n      // montgomery\n      H.montgomery_struct.adjust(M2);\n\n      H.ZZ_red_struct[j].build(q);\n      H.coeff[j] = M2;\n   }\n\n   H.cost = double(H.sz)*double(n_half_ceil);\n}\n\n\nvoid reduce(const MatPrime_crt_helper& H, const ZZ& value, MatPrime_residue_t *remainders,\n            MatPrime_crt_helper_scratch& scratch)\n{\n   long n = H.NumPrimes;\n   const sp_ZZ_reduce_struct *ZZ_red_struct = H.ZZ_red_struct.elts();\n   const sp_reduce_struct *red_struct = H.red_struct.elts();\n   const long *prime = H.prime.elts();\n\n   long i = 0, j = 0;\n   for (; i <= n-2; i += 2, j++) {\n      unsigned long t = ZZ_red_struct[j].rem(value); \n      remainders[i] = rem(t, prime[i], red_struct[i]);\n      remainders[i+1] = rem(t, prime[i+1], red_struct[i+1]);\n   }\n   if (i < n) {\n      remainders[i] = ZZ_red_struct[j].rem(value);\n   }\n}\n\n\n\nvoid reconstruct(const MatPrime_crt_helper& H, ZZ& value, const MatPrime_residue_t *remainders,\n                 MatPrime_crt_helper_scratch& scratch)\n{\n   ZZ& t = scratch.t;\n\n   long nprimes = H.NumPrimes;\n   const long *u = H.u.elts();\n   const long *prime = H.prime.elts();\n   const mulmod_precon_t  *uqinv = H.uqinv.elts();\n   const double *prime_recip = H.prime_recip.elts();\n\n   double y = 0.0;\n\n   QuickAccumBegin(t, H.sz);\n\n   long i = 0, j = 0;\n   for (; i <= nprimes-2; i += 2, j++) {\n      long r0 = MulModPrecon(remainders[i], u[i], prime[i], uqinv[i]);\n      long r1 = MulModPrecon(remainders[i+1], u[i+1], prime[i+1], uqinv[i+1]);\n      y += double(r0)*prime_recip[i] + double(r1)*prime_recip[i+1];\n      long r = r0*prime[i+1] + r1*prime[i];\n      QuickAccumMulAdd(t, H.coeff[j], r);\n   }\n\n   if (i < nprimes) {\n      long r = MulModPrecon(remainders[i], u[i], prime[i], uqinv[i]);\n      y += double(r)*prime_recip[i];\n      QuickAccumMulAdd(t, H.coeff[j], r);\n   }\n\n   long q = long(y + 0.5);\n   QuickAccumMulAdd(t, H.MinusMModP, q);\n\n   QuickAccumEnd(t);\n\n   // montgomery\n   H.montgomery_struct.eval(value, t);\n\n}\n\n#endif\n\n\n// Facillitates PIMPL in ZZ_p.h\nvoid MatPrime_crt_helper_deleter(MatPrime_crt_helper* p)\n{\n   delete p;\n}\n\n\n\nNTL_END_IMPL\n\n#if 0\n\nNTL_CLIENT\n\nint main()\n{\n   ZZ P;\n   RandomLen(P, 8000);\n\n   MatPrime_crt_helper H;\n   build(H, P);\n\n\n   MatPrime_crt_helper_scratch scratch;\n\n   long nprimes = H.GetNumPrimes();\n\n   cerr << nprimes << \"\\n\";\n\n   ZZ a, b, c, d, e;\n   RandomBnd(a, P);\n   RandomBnd(b, P);\n   RandomBnd(c, P);\n   RandomBnd(d, P);\n\n   e = (a*b + c*d) % P;\n\n\n   Vec<MatPrime_residue_t> avec, bvec, cvec, dvec, evec;\n\n   avec.SetLength(nprimes);\n   bvec.SetLength(nprimes);\n   cvec.SetLength(nprimes);\n   dvec.SetLength(nprimes);\n   evec.SetLength(nprimes);\n\n   reduce(H, a, avec.elts(), scratch);\n   reduce(H, b, bvec.elts(), scratch);\n   reduce(H, c, cvec.elts(), scratch);\n   reduce(H, d, dvec.elts(), scratch);\n\n   for (long i = 0; i < nprimes; i++) {\n      long q = GetMatPrime(i);\n      evec[i] = AddMod(MulMod(avec[i], bvec[i], q), MulMod(cvec[i], dvec[i], q), q);\n   }\n\n   ZZ e1;\n\n   reconstruct(H, e1, evec.elts(), scratch);\n\n   if (e == e1) \n      cerr << \"PASS\\n\";\n   else\n      cerr << \"FAIL\\n\";\n}\n\n\n#endif\n", "meta": {"hexsha": "19198db7a93d42dfef1a47f18fa4be0aaf5a6b21", "size": 10566, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/MatPrime.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 160.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:32:19.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/MatPrime.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-12-26T07:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T16:34:31.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/src/MatPrime.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2016-10-10T17:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:56:39.000Z", "avg_line_length": 20.3583815029, "max_line_length": 95, "alphanum_fraction": 0.5623698656, "num_tokens": 3561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951064805861, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6064183016064378}}
{"text": "/*\n * LinearMixedModel.hpp\n *\n *  Created on: Mar 17, 2016\n *      Author: Aditya Gautam (agautam1@andrew.cmu.edu)\n */\n\n#ifndef SRC_MODEL_LINEARMIXEDMODEL_HPP_\n#define SRC_MODEL_LINEARMIXEDMODEL_HPP_\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include <iostream>\n#include <vector>\n#include <math.h>\n#include <cstdlib>\n#include <iostream>\n\n#ifdef BAZEL\n#include \"Math/Math.hpp\"\n#include \"Model.hpp\"\n#else\n#include \"../Math/Math.hpp\"\n#include \"../Models/Model.hpp\"\n#endif\n\nusing namespace std;\nusing namespace Eigen;\n\nclass LinearMixedModel : public Model {\nprotected:\n\n    // Training data\n//    MatrixXf X;\n//    MatrixXf Y;\n\n    // Dimensions of the data\n    long n; // Number of samples\n    long d; // Number of input features\n\n    //Similary matrix and SVD\n    MatrixXf K;\n    MatrixXf S;\n    MatrixXf U;\n    void decomposition();\n\n//    MatrixXf beta; // d*1\n    MatrixXf mau;  // Coeff matrix of similarity matrix.\n    float lambda_optimized; // Value at which log likelihood is max\n    float sigma;\n    bool initFlag;\n\npublic:\n\n    // Constructor\n    LinearMixedModel();\n    LinearMixedModel(const unordered_map<string, string>& options);\n\n    //Setters and Getters\n    long get_num_samples();\n    long get_X_features();\n    float get_lambda();\n    float getSigma();\n    void set_lambda(float);\n    void set_S(MatrixXf);\n    void set_U(MatrixXf);\n    void setX(const MatrixXf&);\n    void setXY(MatrixXf, MatrixXf);\n    void setXYK(MatrixXf, MatrixXf, MatrixXf);\n    void setUS(MatrixXf, MatrixXf);\n    MatrixXf getBeta();\n    //Supporting functions\n    // Final Objective of the LLM : Obtain beta matrix.\n    void calculate_beta(float);\n    void calculate_sigma(float);\n    float get_log_likelihood_value(float);\n    void find_max_log_likelihood();\n\n    void set_num_samples(int num_samples);\n    // Search objective functions\n    float f(float);\n    void assertReadyToRun();\n    void init();\n};\n\n#endif /* SRC_MODEL_LINEARMIXEDMODEL_HPP_ */\n", "meta": {"hexsha": "7aad332131a7f1966118cc476699671b37809552", "size": 1950, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Models/LinearMixedModel.hpp", "max_stars_repo_name": "blengerich/jenkins_test", "max_stars_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T00:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-06T16:40:52.000Z", "max_issues_repo_path": "src/Models/LinearMixedModel.hpp", "max_issues_repo_name": "blengerich/jenkins_test", "max_issues_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2016-11-11T22:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T21:55:57.000Z", "max_forks_repo_path": "src/Models/LinearMixedModel.hpp", "max_forks_repo_name": "blengerich/jenkins_test", "max_forks_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-02-01T09:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T14:40:43.000Z", "avg_line_length": 22.4137931034, "max_line_length": 67, "alphanum_fraction": 0.6882051282, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6064182891704157}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/math/matrix/componentwise_equal.hpp>\n#include <fcppt/math/matrix/logarithm.hpp>\n#include <fcppt/math/matrix/row.hpp>\n#include <fcppt/math/matrix/static.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <iostream>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_matrix_logarithm\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::matrix::static_<\n\t\tdouble,\n\t\t3,\n\t\t3\n\t>\n\tmatrix_type;\n\n\tmatrix_type const t(\n\t\tfcppt::math::matrix::row(\n\t\t\t23.6045,-7.38906,23.6045\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t-16.2155,14.7781,-23.6045\n\t\t),\n\t\tfcppt::math::matrix::row(\n\t\t\t30.9936,7.38906,30.9936\n\t\t)\n\t);\n\n\tdouble const epsilon{\n\t\t0.1\n\t};\n\n\tBOOST_CHECK((\n\t        fcppt::math::matrix::componentwise_equal(\n\t\t\tfcppt::math::matrix::logarithm(\n\t\t\t\tt,\n\t\t\t\t1e-4,\n\t\t\t\t1.0e-9,\n\t\t\t\t1.0e-6\n\t\t\t),\n\t\t        matrix_type(\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t2.0, -1.0, 1.0\n\t\t\t\t),\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t0.0, 3.0, -1.0\n\t\t\t\t),\n\t\t\t\tfcppt::math::matrix::row(\n\t\t\t\t\t2.0, 1.0, 3.0\n\t\t\t\t)\n\t\t\t),\n\t\t        epsilon\n\t\t)\n\t));\n}\n", "meta": {"hexsha": "832ea81191e3589c35641ae7d3eba9857ed8d036", "size": 1511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/matrix/logarithm.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/matrix/logarithm.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/matrix/logarithm.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8815789474, "max_line_length": 61, "alphanum_fraction": 0.6611515553, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6064182891704157}}
{"text": "#include <cstdio> \n#include <cstdlib> \n#include <iostream>\n#include <vector>\n#include <list>\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/bindings/lapack/geqrf.hpp> \n#include <boost/numeric/bindings/lapack/orgqr.hpp> \n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/vector_sparse.hpp>\n#include <boost/numeric/ublas/vector_of_vector.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n\n#ifdef OPENMP\n#include <omp.h>\n#endif\n\nvoid boostbuild_Alpert_matrix(std::vector<std::vector<double> >p, std::vector<int> ki, boost::numeric::ublas::compressed_matrix <double> &  bU , int J,int N);\nvoid build_Alpert_Sampling_product(boost::numeric::ublas::compressed_matrix <double> U, boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> P, boost::numeric::ublas::matrix<double, boost::numeric::ublas::column_major> &T);\n", "meta": {"hexsha": "ddb5e2a57f5396eb8e77dd6be0d85171347b4fb3", "size": 1262, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "swinzip-v2.0/src/Alpert/Alpert_Matrix.hpp", "max_stars_repo_name": "msalloum80/SWinzip", "max_stars_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-17T07:58:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T07:58:23.000Z", "max_issues_repo_path": "swinzip-v2.5/src/Alpert/Alpert_Matrix.hpp", "max_issues_repo_name": "msalloum80/SWinzip", "max_issues_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "swinzip-v2.5/src/Alpert/Alpert_Matrix.hpp", "max_forks_repo_name": "msalloum80/SWinzip", "max_forks_repo_head_hexsha": "5d43e9f11776d513218b891683b7aa00b36fae23", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-05T20:18:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T20:18:25.000Z", "avg_line_length": 42.0666666667, "max_line_length": 245, "alphanum_fraction": 0.7797147385, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6064062691951458}}
{"text": "#include <trajopt_sco/solver_interface.hpp>\n#include <Eigen/Core>\n\nnamespace sco {\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\n#if 0\ntypedef vector<AffExpr> ExprVector;\nMatrix3d leftCrossProdMat(const Vector3d& x);\nMatrix3d rightCrossProdMat(const Vector3d& x);\n\nExprVector exprMatMult(const MatrixXd& A, const VarVector& x);\nExprVector exprMatMult(const MatrixXd& A, const ExprVector& x);\n\nExprVector exprCross(const VectorXd& x, const VarVector& y);\nExprVector exprCross(const VarVector& x, const VectorXd& y);\nExprVector exprCross(const VectorXd& x, const ExprVector& y);\nExprVector exprCross(const ExprVector& x, const VectorXd& y);\n\n#endif\nAffExpr varDot(const VectorXd& x, const VarVector& v);\nAffExpr exprDot(const VectorXd& x, const AffExprVector& v);\n#if 0\nQuadExpr varNorm2(const VarVector& v);\nQuadExpr exprNorm2(const ExprVector& v);\n#endif\n}\n", "meta": {"hexsha": "474fb261c11788794c224dc331b991cb51b498c3", "size": 859, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trajopt_sco/include/trajopt_sco/expr_vec_ops.hpp", "max_stars_repo_name": "Levi-Armstrong/trajopt_ros", "max_stars_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T14:43:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-09T16:41:36.000Z", "max_issues_repo_path": "trajopt_sco/include/trajopt_sco/expr_vec_ops.hpp", "max_issues_repo_name": "Levi-Armstrong/trajopt_ros", "max_issues_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T04:57:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-07T21:46:45.000Z", "max_forks_repo_path": "trajopt_sco/include/trajopt_sco/expr_vec_ops.hpp", "max_forks_repo_name": "Levi-Armstrong/trajopt_ros", "max_forks_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6333333333, "max_line_length": 63, "alphanum_fraction": 0.7823050058, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6064062605509987}}
{"text": "//\n// Created by Liuyu Jin on Jun 9, 2016.\n//\n\n#ifndef ALGORITHMS_LINEARREGRESSION_HPP\n#define ALGORITHMS_LINEARREGRESSION_HPP\n\n\n#include <Eigen/Dense>\n#include <unordered_map>\n//#include \"Model.hpp\"\n\n#ifdef BAZEL\n#include \"model/ModelOptions.hpp\"\n#include \"Model.hpp\"\n#else\n#include \"../model/ModelOptions.hpp\"\n#include \"../model/Model.hpp\"\n#endif\n\nusing namespace Eigen;\n\nclass ICLasso : public virtual Model {\nprivate:\n    MatrixXf X; //n * p\n    MatrixXf Y; //n * 1\n    float lambda;\n    float lambda1;\n    float lambda2;\n    float gamma;\n    MatrixXf Beta; //p * 1\n    MatrixXf Theta;\n\npublic:\n    //constructor\n    ICLasso();\n    void set_X(MatrixXf);\n    void set_Y(MatrixXf);\n    void set_XY(MatrixXf, MatrixXf);\n    void set_lambda1(float);\n    void set_lambda2(float);\n    void set_gamma(float);\n    void set_theta(MatrixXf);\n    float cost();\n    void optimize_theta();\n\n};\n\n\n#endif //ALGORITHMS_LINEARREGRESSION_HPP\n", "meta": {"hexsha": "0324bb529c5eb8c54c2091d92e268c077014bb30", "size": 928, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Models/ICLasso.hpp", "max_stars_repo_name": "blengerich/jenkins_test", "max_stars_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2016-10-20T00:36:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-06T16:40:52.000Z", "max_issues_repo_path": "src/Models/ICLasso.hpp", "max_issues_repo_name": "blengerich/jenkins_test", "max_issues_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2016-11-11T22:41:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-04T21:55:57.000Z", "max_forks_repo_path": "src/Models/ICLasso.hpp", "max_forks_repo_name": "blengerich/jenkins_test", "max_forks_repo_head_hexsha": "512aec681577063e3d68f699d19f53374e59585a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-02-01T09:19:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-28T14:40:43.000Z", "avg_line_length": 18.1960784314, "max_line_length": 40, "alphanum_fraction": 0.6864224138, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6064062563596417}}
{"text": "#include <Eigen/Core>\n#include <Eigen/SparseCholesky>\n#include <Euclid/MeshUtil/CGALMesh.h>\n#include <Euclid/MeshUtil/EigenMesh.h>\n#include <Euclid/Topology/MeshTopology.h>\n#include <igl/cotmatrix.h>\n#include <igl/vector_area_matrix.h>\n#include <igl/repdiag.h>\n\nnamespace Euclid\n{\n\nnamespace _impl\n{\n\ntemplate<typename Mesh, typename T>\nvoid boundary_matrix(const Mesh& mesh,\n                     Eigen::SparseMatrix<T>& B,\n                     Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& E)\n{\n    using Triplet = Eigen::Triplet<T>;\n    std::vector<Triplet> triplets;\n    auto vimap = get(CGAL::vertex_index, mesh);\n\n    auto nv = mesh.number_of_vertices();\n    auto sz = nv * 2;\n    B.resize(sz, sz);\n    E.setZero(sz, 2);\n\n    auto bnds = boundary_components(mesh);\n    int nb = 0;\n    for (auto h : bnds) {\n        auto hi = h;\n        do {\n            auto v = target(hi, mesh);\n            auto vi = get(vimap, v);\n            hi = next(hi, mesh);\n            triplets.emplace_back(vi, vi, 1.0);\n            triplets.emplace_back(nv + vi, nv + vi, 1.0);\n            E(vi, 0) = 1.0;\n            E(nv + vi, 1) = 1.0;\n            ++nb;\n        } while (hi != h);\n        E /= std::sqrt(nb + 0.0);\n    }\n    B.setFromTriplets(triplets.begin(), triplets.end());\n    B.makeCompressed();\n}\n\n} // namespace _impl\n\ntemplate<typename Mesh, typename VertexUVMap>\nvoid spectral_conformal_parameterization(Mesh& mesh, VertexUVMap uvm)\n{\n    using Point_2 = typename boost::property_traits<VertexUVMap>::value_type;\n    using FT = typename CGAL::Kernel_traits<Point_2>::Kernel::FT;\n    using SpMat = Eigen::SparseMatrix<FT>;\n    using Mat = Eigen::Matrix<FT, Eigen::Dynamic, Eigen::Dynamic>;\n    using Vec = Eigen::Matrix<FT, Eigen::Dynamic, 1>;\n    constexpr const int MAX_ITERS = 30;\n\n    // convert mesh\n    std::vector<FT> positions;\n    std::vector<int> indices;\n    extract_mesh<3>(mesh, positions, indices);\n    Mat V;\n    Eigen::MatrixXi F;\n    make_mesh<3>(V, F, positions, indices);\n\n    // assemble matrices\n    SpMat L, LD, A, LC, B;\n    Mat E;\n    igl::cotmatrix(V, F, L);\n    igl::repdiag(L, 2, LD);\n    igl::vector_area_matrix(F, A);\n    LC = -LD + 2.0 * A;\n    _impl::boundary_matrix(mesh, B, E);\n\n    // inverse power iterations\n    Vec fidler = Vec::Random(LC.rows());\n    Eigen::SimplicialLDLT<SpMat> solver(LC);\n    for (int i = 0; i < MAX_ITERS; ++i) {\n        fidler = (B - E * E.transpose()) * fidler;\n        fidler = solver.solve(fidler);\n        fidler.normalize();\n    }\n\n    // assemble results\n    auto nv = mesh.number_of_vertices();\n    auto vimap = get(CGAL::vertex_index, mesh);\n    for (auto v : vertices(mesh)) {\n        auto i = get(vimap, v);\n        auto x = fidler(i);\n        auto y = fidler(nv + i);\n        put(uvm, v, Point_2(x, y));\n    }\n}\n\ntemplate<typename Mesh>\ntemplate<typename VertexUVMap,\n         typename VertexIndexMap,\n         typename VertexParameterizedMap>\nCGAL::Surface_mesh_parameterization::Error_code\nSCP_parameterizer_3<Mesh>::parameterize(TriangleMesh& mesh,\n                                        halfedge_descriptor bhd,\n                                        VertexUVMap uvmap,\n                                        VertexIndexMap vimap,\n                                        VertexParameterizedMap vpmap)\n{\n    spectral_conformal_parameterization(mesh, uvmap);\n    return CGAL::Surface_mesh_parameterization::OK;\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "54b1a81bfb0d956fb427122022da3b15f528482e", "size": 3411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/Parameterization/src/SCP.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "include/Euclid/Parameterization/src/SCP.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Euclid/Parameterization/src/SCP.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 29.6608695652, "max_line_length": 77, "alphanum_fraction": 0.595133392, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.606389873987491}}
{"text": "/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n\n#include <iostream>\n#include <Eigen/Core>\n#include <chrono>\n\n#include \"eigen_spatial_convolutions.h\"\n#include \"eigen_cuboid_convolution.h\"\n\n\nvoid test_conv2d () {\n  const int input_depth = 3;\n  const int input_rows = 227;\n  const int input_cols = 227;\n  const int num_batches = 1;\n  const int output_depth = 96;\n  const int patch_rows = 11;\n  const int patch_cols = 11;\n  const int output_rows = input_rows - patch_rows + 1;\n  const int output_cols = input_cols - patch_cols + 1;\n\n  using namespace Eigen;\n\n  Tensor<float, 4, RowMajor> input(num_batches, input_cols, input_rows, input_depth);\n  Tensor<float, 4, RowMajor> kernel(patch_cols, patch_rows, input_depth, output_depth);\n  Tensor<float, 4, RowMajor> result(num_batches, output_cols, output_rows, output_depth);\n\n  input = input.constant(11.0f) + input.random();\n  kernel = kernel.constant(2.0f) + kernel.random();\n\n  using namespace std::chrono;\n  milliseconds t0 = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n  result = SpatialConvolution(input, kernel, 4, 4, PADDING_SAME);\n  milliseconds t1 = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n  int difference = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count();\n  std::cout << difference << \" ms\" << std::endl;\n}\n\n\nvoid test_conv2d_back_input () {\n\n}\n\n\nint main()\n{\n  std::cout << \"Hello World!\\n\";\n\n  test_conv2d ();\n\n  return 0;\n}\n", "meta": {"hexsha": "4bedad03f1c03e8f06f28fc444dbd7d718cddeb3", "size": 2086, "ext": "cc", "lang": "C++", "max_stars_repo_path": "eigen_cpp/lib/unsupported/Eigen/NeuralNetwork/test.cc", "max_stars_repo_name": "bcdarwin/eigen", "max_stars_repo_head_hexsha": "df6ae082903925c4db4c641c2f1205d2aa65c406", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-03-25T04:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T18:27:35.000Z", "max_issues_repo_path": "eigen_cpp/lib/unsupported/Eigen/NeuralNetwork/test.cc", "max_issues_repo_name": "bcdarwin/eigen", "max_issues_repo_head_hexsha": "df6ae082903925c4db4c641c2f1205d2aa65c406", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-05-30T13:11:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-01T16:34:21.000Z", "max_forks_repo_path": "eigen_cpp/lib/unsupported/Eigen/NeuralNetwork/test.cc", "max_forks_repo_name": "bcdarwin/eigen", "max_forks_repo_head_hexsha": "df6ae082903925c4db4c641c2f1205d2aa65c406", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-05-02T11:16:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-16T03:16:30.000Z", "avg_line_length": 31.6060606061, "max_line_length": 90, "alphanum_fraction": 0.7099712368, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6063898704425462}}
{"text": "#include \"FastqIterator.hpp\"\n#include <iostream>\n#include <stdexcept>\n#include \"span.hpp\"\n\nusing std::runtime_error;\nusing std::cout;\nusing std::cerr;\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\nusing namespace boost::accumulators;\n\ntypedef accumulator_set<float, features<tag::count, tag::mean, tag::variance>> stats_accumulator;\n\nusing overlap_analysis::quality_char_to_error_probability;\nusing overlap_analysis::FastqIterator;\nusing overlap_analysis::FastqElement;\n\n\nbool classify_palindromic_q_scores(span<char> qualities){\n    bool is_palindromic = false;\n\n    stats_accumulator left_stats;\n    stats_accumulator right_stats;\n\n    auto length = qualities.size();\n\n    if (length < 6){\n        return is_palindromic;\n    }\n\n    size_t midpoint = length/2;\n\n    for (size_t i=0; i<midpoint; i++){\n        auto q = qualities[i];\n        auto p = quality_char_to_error_probability(q);\n\n        left_stats(p);\n    }\n\n    for (size_t i=midpoint; i<length; i++){\n        auto q = qualities[i];\n        auto p = quality_char_to_error_probability(q);\n\n        right_stats(p);\n    }\n\n    float left_mean = mean(left_stats);\n    float left_variance = variance(left_stats);\n\n    float right_mean = mean(right_stats);\n    float right_variance = variance(right_stats);\n\n//    cout << left_mean << '\\t' << left_variance << '\\n';\n//    cout << right_mean << '\\t' << right_variance << '\\n';\n\n    if (right_mean - left_mean > 0.09 and right_mean >= 0.15){\n        if (right_variance > left_variance and right_variance > 0.025){\n            is_palindromic = true;\n        }\n    }\n\n    return is_palindromic;\n}\n\n\nvoid split_palindrome_by_quality(FastqElement& element, vector<FastqElement>& result){\n    span<char> q_scores(&element.quality_string.front(), &element.quality_string.back());\n\n    bool is_palindromic = classify_palindromic_q_scores(q_scores);\n\n    if (not is_palindromic){\n        cout << '@' << element.name << '\\n';\n        cout << element.sequence << '\\n';\n        cout << '+' << '\\n';\n        cout << element.quality_string << '\\n';\n    }\n}\n\n\nint main(int argc, char **argv){\n    if (argc == 1 or argc > 2){\n        cerr << \"Usage: split_palindromes_by_quality /path/to/file.fastq\\n\";\n        return 1;\n    }\n\n    path fastq_path = argv[1];\n    FastqIterator iterator(fastq_path);\n    FastqElement e;\n    vector<FastqElement> result;\n\n    size_t i = 0;\n    while (iterator.next_element(e)) {\n        if (i % 100 == 0) {\n            cerr << \"\\33[2K\\r\" << i << std::flush;\n        }\n\n        split_palindrome_by_quality(e, result);\n\n        i++;\n    }\n    cerr << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "143e14cf358f97c7415afe27af9d293f305f2878", "size": 2639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/executable/filter_palindromes_by_quality.cpp", "max_stars_repo_name": "rlorigro/overlap_analysis", "max_stars_repo_head_hexsha": "8c8753aeba40c4ba82e0c0499fc8c2f134ba7145", "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/executable/filter_palindromes_by_quality.cpp", "max_issues_repo_name": "rlorigro/overlap_analysis", "max_issues_repo_head_hexsha": "8c8753aeba40c4ba82e0c0499fc8c2f134ba7145", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/executable/filter_palindromes_by_quality.cpp", "max_forks_repo_name": "rlorigro/overlap_analysis", "max_forks_repo_head_hexsha": "8c8753aeba40c4ba82e0c0499fc8c2f134ba7145", "max_forks_repo_licenses": ["Apache-2.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.4351851852, "max_line_length": 97, "alphanum_fraction": 0.6392572944, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6063898668976013}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#include <boost/config.hpp>\n\n#include <algorithm>\n#include <vector>\n#include <utility>\n#include <iostream>\n\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/neighbor_bfs.hpp>\n#include <boost/property_map/property_map.hpp>\n\n/*\n\n  Sample Output:\n\n  0 --> 2\n  1 --> 1 3 4\n  2 --> 1 3 4\n  3 --> 1 4\n  4 --> 0 1\n  distances: 0 2 1 2 1\n  parent[0] = 0\n  parent[1] = 2\n  parent[2] = 0\n  parent[3] = 2\n  parent[4] = 0\n\n*/\n\nusing namespace boost;\n\ntemplate <class ParentDecorator>\nstruct print_parent {\n  print_parent(const ParentDecorator& p_) : p(p_) { }\n  template <class Vertex>\n  void operator()(const Vertex& v) const {\n    std::cout << \"parent[\" << v << \"] = \" <<  p[v]  << std::endl;\n  }\n  ParentDecorator p;\n};\n\ntemplate <class DistanceMap, class PredecessorMap, class ColorMap>\nclass distance_and_pred_visitor : public neighbor_bfs_visitor<>\n{\n  typedef typename property_traits<ColorMap>::value_type ColorValue;\n  typedef color_traits<ColorValue> Color;\npublic:\n  distance_and_pred_visitor(DistanceMap d, PredecessorMap p, ColorMap c)\n    : m_distance(d), m_predecessor(p), m_color(c) { }\n\n  template <class Edge, class Graph>\n  void tree_out_edge(Edge e, const Graph& g) const\n  {\n    typename graph_traits<Graph>::vertex_descriptor\n      u = source(e, g), v = target(e, g);\n    put(m_distance, v, get(m_distance, u) + 1);\n    put(m_predecessor, v, u);\n  }\n  template <class Edge, class Graph>\n  void tree_in_edge(Edge e, const Graph& g) const\n  {\n    typename graph_traits<Graph>::vertex_descriptor\n      u = source(e, g), v = target(e, g);\n    put(m_distance, u, get(m_distance, v) + 1);\n    put(m_predecessor, u, v);\n  }\n\n  DistanceMap m_distance;\n  PredecessorMap m_predecessor;\n  ColorMap m_color;\n};\n\nint main(int , char* [])\n{\n  typedef adjacency_list<\n    mapS, vecS, bidirectionalS,\n    property<vertex_color_t, default_color_type>\n  > Graph;\n\n  typedef property_map<Graph, vertex_color_t>::type\n    ColorMap;\n\n  Graph G(5);\n  add_edge(0, 2, G);\n  add_edge(1, 1, G);\n  add_edge(1, 3, G);\n  add_edge(1, 4, G);\n  add_edge(2, 1, G);\n  add_edge(2, 3, G);\n  add_edge(2, 4, G);\n  add_edge(3, 1, G);\n  add_edge(3, 4, G);\n  add_edge(4, 0, G);\n  add_edge(4, 1, G);\n\n  typedef Graph::vertex_descriptor Vertex;\n\n  // Array to store predecessor (parent) of each vertex. This will be\n  // used as a Decorator (actually, its iterator will be).\n  std::vector<Vertex> p(num_vertices(G));\n  // VC++ version of std::vector has no ::pointer, so\n  // I use ::value_type* instead.\n  typedef std::vector<Vertex>::value_type* Piter;\n\n  // Array to store distances from the source to each vertex .  We use\n  // a built-in array here just for variety. This will also be used as\n  // a Decorator.\n  typedef graph_traits<Graph>::vertices_size_type size_type;\n  size_type d[5];\n  std::fill_n(d, 5, 0);\n\n  // The source vertex\n  Vertex s = *(vertices(G).first);\n  p[s] = s;\n  distance_and_pred_visitor<size_type*, Vertex*, ColorMap>\n    vis(d, &p[0], get(vertex_color, G));\n  neighbor_breadth_first_search\n    (G, s, visitor(vis).\n     color_map(get(vertex_color, G)));\n\n  print_graph(G);\n\n  if (num_vertices(G) < 11) {\n    std::cout << \"distances: \";\n#ifdef BOOST_OLD_STREAM_ITERATORS\n    std::copy(d, d + 5, std::ostream_iterator<int, char>(std::cout, \" \"));\n#else\n    std::copy(d, d + 5, std::ostream_iterator<int>(std::cout, \" \"));\n#endif\n    std::cout << std::endl;\n\n    std::for_each(vertices(G).first, vertices(G).second,\n                  print_parent<Piter>(&p[0]));\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "8b2f1783c2facfed3714a3524eb06d03e2387985", "size": 3999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/neighbor_bfs.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/neighbor_bfs.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/graph/example/neighbor_bfs.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 26.8389261745, "max_line_length": 74, "alphanum_fraction": 0.6424106027, "num_tokens": 1184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.754914975839675, "lm_q1q2_score": 0.6063279270718305}}
{"text": "//==================================================================================================\n/*!\n\n  Copyright 2015 NumScale SAS\n  Copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#include <boost/simd/function/scalar/log2.hpp>\n#include <boost/simd/function/std.hpp>\n#include <simd_test.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/constant/mzero.hpp>\n\nSTF_CASE_TPL (\" log2\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::log2;\n\n  using r_t = decltype(log2(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(log2(bs::Inf<T>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(log2(bs::Minf<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(log2(bs::Nan<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(log2(bs::Mone<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(log2(bs::Zero<T>()), bs::Minf<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(log2(bs::One<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(log2(T(2)), T(1), 0);\n  STF_ULP_EQUAL(log2(T(8)), T(3), 0);\n  STF_ULP_EQUAL(log2(T(64)), T(6), 0);\n}\n\nSTF_CASE_TPL (\" log2int\",  STF_INTEGRAL_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::log2;\n\n  using r_t = decltype(log2(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  STF_ULP_EQUAL(log2(bs::One<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(log2(T(2)), T(1), 0);\n  STF_ULP_EQUAL(log2(T(8)), T(3), 0);\n  STF_ULP_EQUAL(log2(T(64)), T(6), 0);\n}\n\nSTF_CASE_TPL (\" log2 std\",  STF_IEEE_TYPES)\n{\n  namespace bs = boost::simd;\n  namespace bd = boost::dispatch;\n  using bs::log2;\n  using bs::std_;\n\n  using r_t = decltype(bs::std_(log2)(T()));\n\n  // return type conformity test\n  STF_TYPE_IS(r_t, T);\n\n  // specific values tests\n  // specific values tests\n#ifndef BOOST_SIMD_NO_INVALIDS\n  STF_ULP_EQUAL(bs::std_(log2)(bs::Inf<T>()), bs::Inf<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(log2)(bs::Minf<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(log2)(bs::Nan<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(log2)(bs::Mone<T>()), bs::Nan<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(log2)(bs::Zero<T>()), bs::Minf<r_t>(), 0);\n#endif\n  STF_ULP_EQUAL(bs::std_(log2)(bs::One<T>()), bs::Zero<r_t>(), 0);\n  STF_ULP_EQUAL(bs::std_(log2)(T(2)), T(1), 0);\n  STF_ULP_EQUAL(bs::std_(log2)(T(8)), T(3), 0);\n  STF_ULP_EQUAL(bs::std_(log2)(T(64)), T(6), 0);\n}\n", "meta": {"hexsha": "0745dba9ac5bc838a7964f7aa61e288eda2b7303", "size": 2863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/function/scalar/log2.cpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/function/scalar/log2.cpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/function/scalar/log2.cpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4615384615, "max_line_length": 100, "alphanum_fraction": 0.60915124, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.606288373084762}}
{"text": "#include \"util/number_util.h\"\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace metternich::number {\n\ndouble degree_to_radian(const double degree)\n{\n\treturn degree * boost::math::constants::pi<double>() / 180.;\n}\n\n}\n", "meta": {"hexsha": "fbffb5007d611f8729b1a922587130676770a5b2", "size": 224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/number_util.cpp", "max_stars_repo_name": "Andrettin/Metternich", "max_stars_repo_head_hexsha": "513a7d3cddacad5d5efd2fa5faeed03bc55a190c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-08-03T05:58:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T20:46:41.000Z", "max_issues_repo_path": "util/number_util.cpp", "max_issues_repo_name": "Andrettin/Metternich", "max_issues_repo_head_hexsha": "513a7d3cddacad5d5efd2fa5faeed03bc55a190c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-03T11:46:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T10:20:32.000Z", "max_forks_repo_path": "util/number_util.cpp", "max_forks_repo_name": "Andrettin/Metternich", "max_forks_repo_head_hexsha": "513a7d3cddacad5d5efd2fa5faeed03bc55a190c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.2307692308, "max_line_length": 61, "alphanum_fraction": 0.7366071429, "num_tokens": 51, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.6062785984966634}}
{"text": "#ifndef _POSE2DRANSAC_H\n#define _POSE2DRANSAC_H\n\n#include <opencv2/core/core.hpp>\n\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <Eigen/Eigen>\n\nnamespace pose2d\n{\n   void pose_translation(const Eigen::Matrix3d& Kinv, const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts,\n                         const Eigen::Matrix3d& R, Eigen::Vector3d& translation);\n\n   void pose_translation(const Eigen::Matrix3d& Kinv, const std::vector<cv::Point3d>& train_img_pts,\n                         const std::vector<cv::Point3d>& query_img_pts,\n                         const Eigen::Matrix3d& R, Eigen::Vector3d& translation);\n\n   void pose_translation(const Eigen::Matrix3d& Kinv, const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts,\n                         const double depth, const Eigen::Matrix3d& R, Eigen::Vector3d& translation);\n\n   void pose_translation(const Eigen::Matrix3d& Kinv, const std::vector<cv::Point3d>& train_img_pts,\n                         const std::vector<cv::Point3d>& query_img_pts, const double depth,\n                         const Eigen::Matrix3d& R, Eigen::Vector3d& translation);\n};\n\nnamespace pose3d\n{\n   void pose_translation(const std::vector<cv::Point3d>& world_pts, const std::vector<cv::Point2d>& query_image_pts,\n                         const Eigen::Matrix3d& KI, const Eigen::Quaterniond& Q, Eigen::Vector3d& translation);\n\n   void pose_translation(const std::vector<cv::Point3d>& world_pts, const std::vector<cv::Point2d>& query_image_pts,\n                         const Eigen::Matrix3d& KI, const Eigen::Matrix3d& R, Eigen::Vector3d& translation);\n};\n\nstruct GravPoseRansacModel\n//=========================\n{\n   GravPoseRansacModel() : rotation(0, 0, 0, 0), translation(0, 0, 0) {}\n   GravPoseRansacModel(const Eigen::Quaterniond& rotation_, const Eigen::Vector3d& translation_) : rotation(rotation_),\n                                                                                                   translation(translation_) {}\n   GravPoseRansacModel(const GravPoseRansacModel& other) = default;\n\n   GravPoseRansacModel& operator=(const GravPoseRansacModel &other) = default;\n\n   Eigen::Quaterniond rotation;\n   Eigen::Vector3d translation;\n};\n\n#ifdef USE_THEIA_RANSAC\n#include \"sample_consensus_estimator.h\"\n#include \"create_and_initialize_ransac_variant.h\"\n\nstruct Grav2DRansacEstimator : public theia::Estimator<std::pair<cv::Point3d, cv::Point3d>, GravPoseRansacModel>\n//=================================================================================================================\n{\n   Grav2DRansacEstimator(const cv::Mat& K_, const Eigen::Quaterniond& Q_, const double depth_ =0, int samples =3) :\n      Q(Q_), R(Q_.toRotationMatrix()), depth(depth_), sample_size(samples)\n   //--------------------------------------------------------------------------------------------\n   {\n      Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> EK_((double *) K_.data);\n      EK = EK_;\n      KI = EK.inverse();\n   }\n\n   Grav2DRansacEstimator(Eigen::Matrix3d _K, const Eigen::Quaterniond& Q_, const double depth_ =0, int samples =3) :\n         EK(std::move(_K)), Q(Q_), R(Q_.toRotationMatrix()), depth(depth_), sample_size(samples) { KI = EK.inverse(); }\n\n   virtual double SampleSize() const override { return sample_size; }\n\n   bool EstimateModel(const std::vector<std::pair<cv::Point3d, cv::Point3d>> &matches,\n                      std::vector<GravPoseRansacModel> *models) const override;\n\n   double Error(const std::pair<cv::Point3d, cv::Point3d> &match, const GravPoseRansacModel &model) const override;\n\n   Eigen::Matrix3d EK;\n   const Eigen::Quaterniond Q;\n   const Eigen::Matrix3d R;\n   Eigen::Matrix3d KI;\n   const double depth;\n   int sample_size;\n};\n\nstruct Grav3DRansacEstimator : public theia::Estimator<std::pair<cv::Point3d, cv::Point2d>, GravPoseRansacModel>\n//=================================================================================================================\n{\n   Grav3DRansacEstimator(const Eigen::Matrix3d& KI_, const Eigen::Quaterniond& Q_, int samples =3) :\n      KI(KI_), K(KI_.inverse()), Q(Q_), R(Q_.toRotationMatrix()), sample_size(samples) { }\n\n   double SampleSize() const override { return sample_size; }\n\n   bool EstimateModel(const std::vector<std::pair<cv::Point3d, cv::Point2d>> &matches,\n                      std::vector<GravPoseRansacModel> *models) const override;\n\n   double Error(const std::pair<cv::Point3d, cv::Point2d> &match, const GravPoseRansacModel &model) const override;\n\n   Eigen::Matrix3d KI, K;\n   const Eigen::Quaterniond Q;\n   const Eigen::Matrix3d R;\n   int sample_size;\n};\n#else\n#include \"Ransac.hh\"\n\nstruct Grav2DRansacData\n//=====================\n{\n   Grav2DRansacData(const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts) : pts(pts) {}\n\n   const std::vector<std::pair<cv::Point3d, cv::Point3d>>& pts;\n};\n\nstruct Grav3DRansacData\n//=====================\n{\n   Grav3DRansacData(const std::vector<std::pair<cv::Point3d, cv::Point2d>>& pts) : pts(pts) {}\n\n   const std::vector<std::pair<cv::Point3d, cv::Point2d>>& pts;\n};\n\ntemplate <typename Pt>\nstatic inline size_t RANSAC_copy_points(const Grav2DRansacData& samples, const std::vector<size_t>& sampleIndices,\n                                        std::vector<Pt>& train_pts, std::vector<Pt>& query_pts)\n//-----------------------------------------------------------------------------------------------------\n{\n   const size_t no = sampleIndices.size();\n   for (size_t i=0; i<no; i++)\n   {\n      size_t index = sampleIndices[i];\n      train_pts.emplace_back(samples.pts[index].first);\n      query_pts.emplace_back(samples.pts[index].second);\n   }\n   return no;\n}\n\nstatic inline size_t copy_points3d(const Grav3DRansacData& samples, const std::vector<size_t>& sampleIndices,\n                                   std::vector<cv::Point3d>& world_pts, std::vector<cv::Point2d>& query_pts)\n//-----------------------------------------------------------------------------------------------------\n{\n   const size_t no = sampleIndices.size();\n   for (size_t i=0; i<no; i++)\n   {\n      size_t index = sampleIndices[i];\n      const cv::Point3d& wpt = samples.pts[index].first;\n      const cv::Point2d& ipt = samples.pts[index].second;\n      world_pts.emplace_back(wpt.x, wpt.y, wpt.z);\n      query_pts.emplace_back(ipt.x, ipt.y);\n   }\n   return no;\n}\n\nstruct PlanarRansacEstimator\n//==========================\n{\n   PlanarRansacEstimator(const cv::Mat& K_, const Eigen::Quaterniond& Q_) : Q(Q_), R(Q_.toRotationMatrix())\n   //-------------------------------------------------------------------------------------------\n   {\n      Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> EK_((double *) K_.data);\n      EK = EK_;\n      KI = EK.inverse();\n   }\n\n   PlanarRansacEstimator(Eigen::Matrix3d K_, const Eigen::Quaterniond& Q_) : EK(std::move(K_)), Q(Q_), R(Q_.toRotationMatrix())\n   //-------------------------------------------------------------------------------------------\n   {\n      KI = EK.inverse();\n   }\n\n   Eigen::Matrix3d EK;\n   const Eigen::Quaterniond Q;\n   const Eigen::Matrix3d R;\n   Eigen::Matrix3d KI;\n\n};\n\nstruct Grav2DRansacEstimator : public PlanarRansacEstimator\n//==============================================================\n{\n   Grav2DRansacEstimator(const cv::Mat& K_, const Eigen::Quaterniond& Q_) : PlanarRansacEstimator(K_, Q_) {}\n\n   Grav2DRansacEstimator(const Eigen::Matrix3d K_, const Eigen::Quaterniond& Q_) : PlanarRansacEstimator(K_, Q_) {}\n\n   const int estimate(const Grav2DRansacData &samples, const std::vector<size_t> &sampleIndices,\n                      templransac::RANSACParams &parameters,\n                      std::vector<GravPoseRansacModel> &models) const;\n\n   const void error(const Grav2DRansacData &samples, const std::vector<size_t> &sampleIndices,\n                    GravPoseRansacModel &model, std::vector<size_t> &inlier_indices,\n                    std::vector<size_t> &outlier_indices, double error_threshold) const;\n};\n\nstruct Grav2DDepthRansacEstimator : public PlanarRansacEstimator\n//==============================================================\n{\n   Grav2DDepthRansacEstimator(const cv::Mat& K_, const Eigen::Quaterniond& Q_, const double depth_) :\n         PlanarRansacEstimator(K_, Q_), depth(depth_) {}\n\n   Grav2DDepthRansacEstimator(const Eigen::Matrix3d K_, const Eigen::Quaterniond& Q_, const double depth_) :\n         PlanarRansacEstimator(K_, Q_), depth(depth_) {}\n\n   const int estimate(const Grav2DRansacData& samples, const std::vector<size_t>& sampleIndices,\n                      templransac::RANSACParams& parameters,\n                      std::vector<GravPoseRansacModel>& models) const;\n\n   const void error(const Grav2DRansacData& samples, const std::vector<size_t>& sampleIndices,\n                    GravPoseRansacModel& model, std::vector<size_t>& inlier_indices,\n                    std::vector<size_t>& outlier_indices, double error_threshold) const;\n\n   const double depth;\n};\n\nstruct Grav3DRansacEstimator\n//==========================\n{\n   Grav3DRansacEstimator(const Eigen::Matrix<double, 3, 3>& KI_, const Eigen::Quaterniond& Q_)\n         : Q(Q_), KI(KI_), K(KI.inverse()), R(Q_.toRotationMatrix()) { }\n\n   const int estimate(const Grav3DRansacData& samples, const std::vector<size_t>& sampleIndices,\n                      templransac::RANSACParams& parameters,\n                      std::vector<GravPoseRansacModel>& models) const;\n\n   const void error(const Grav3DRansacData& samples, const std::vector<size_t>& sampleIndices,\n                    GravPoseRansacModel& model, std::vector<size_t>& inlier_indices,\n                    std::vector<size_t>& outlier_indices, double error_threshold) const;\n\n   const Eigen::Quaterniond Q;\n   const Eigen::Matrix3d& KI;\n   const Eigen::Matrix3d K, R;\n};\n\n#endif // USE_THEIA_RANSAC\n\n#endif //_POSE2DRANSAC_H\n", "meta": {"hexsha": "9621049a3ef3090cdb5f865d110e6257aa87412b", "size": 9822, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/pose/PoseRANSAC.hh", "max_stars_repo_name": "donaldmunro/PlanarTrainer", "max_stars_repo_head_hexsha": "c990ad78226d260730f0af2d9d1e65d6aa5fd444", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-12T06:34:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T06:34:11.000Z", "max_issues_repo_path": "src/pose/PoseRANSAC.hh", "max_issues_repo_name": "donaldmunro/PlanarTrainer", "max_issues_repo_head_hexsha": "c990ad78226d260730f0af2d9d1e65d6aa5fd444", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pose/PoseRANSAC.hh", "max_forks_repo_name": "donaldmunro/PlanarTrainer", "max_forks_repo_head_hexsha": "c990ad78226d260730f0af2d9d1e65d6aa5fd444", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9743589744, "max_line_length": 127, "alphanum_fraction": 0.6044593769, "num_tokens": 2516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.6992544147913993, "lm_q1q2_score": 0.6062785924335454}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2021,\n *  Max Planck Institute for Intelligent Systems (MPI-IS).\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the MPI-IS nor the names\n *     of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written\n *     permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/* Author: Andreas Orthey */\n\n#include <ompl/base/spaces/TorusStateSpace.h>\n#include <ompl/tools/config/MagicConstants.h>\n#include <cstring>\n\n#include <boost/math/constants/constants.hpp>\nusing namespace boost::math::double_constants;  // pi\nusing namespace ompl::base;\n\nTorusStateSampler::TorusStateSampler(const StateSpace *space) : StateSampler(space)\n{\n}\n\nvoid TorusStateSampler::sampleUniform(State *state)\n{\n    // https://stackoverflow.com/questions/26300510/generating-random-points-on-a-surface-of-an-n-dimensional-torus\n    // Based on publication \"Random selection of points distributed on curved surfaces.\"\n    // Link: https://iopscience.iop.org/article/10.1088/0031-9155/32/10/009/pdf\n    const auto *T = static_cast<const TorusStateSpace *>(space_);\n\n    bool acceptedSampleFound = false;\n    while (!acceptedSampleFound)\n    {\n        double u = rng_.uniformReal(-pi, pi);\n        double v = rng_.uniformReal(-pi, pi);\n\n        const double &R = T->getMajorRadius();\n        const double &r = T->getMinorRadius();\n\n        double vprime = (R + r * cos(v)) / (R + r);\n\n        double mu = rng_.uniformReal(0, 1);\n        if (mu <= vprime)\n        {\n            TorusStateSpace::StateType *T = state->as<TorusStateSpace::StateType>();\n            T->setS1S2(u, v);\n            acceptedSampleFound = true;\n        }\n    }\n}\n\nvoid TorusStateSampler::sampleUniformNear(State *state, const State *near, double distance)\n{\n    TorusStateSpace::StateType *T = state->as<TorusStateSpace::StateType>();\n    const TorusStateSpace::StateType *Tnear = near->as<TorusStateSpace::StateType>();\n    T->setS1(rng_.uniformReal(Tnear->getS1() - distance, Tnear->getS1() + distance));\n    T->setS2(rng_.uniformReal(Tnear->getS2() - distance, Tnear->getS2() + distance));\n    space_->enforceBounds(state);\n}\n\nvoid TorusStateSampler::sampleGaussian(State *state, const State *mean, double stdDev)\n{\n    TorusStateSpace::StateType *T = state->as<TorusStateSpace::StateType>();\n    const TorusStateSpace::StateType *Tmean = mean->as<TorusStateSpace::StateType>();\n    T->setS1(rng_.gaussian(Tmean->getS1(), stdDev));\n    T->setS2(rng_.gaussian(Tmean->getS2(), stdDev));\n\n    space_->enforceBounds(state);\n}\n\nTorusStateSpace::TorusStateSpace(double majorRadius, double minorRadius)\n  : majorRadius_(majorRadius), minorRadius_(minorRadius)\n{\n    setName(\"Torus\" + getName());\n    type_ = STATE_SPACE_TORUS;\n    addSubspace(std::make_shared<SO2StateSpace>(), 1.0);\n    addSubspace(std::make_shared<SO2StateSpace>(), 1.0);\n    lock();\n}\n\nStateSamplerPtr TorusStateSpace::allocDefaultStateSampler() const\n{\n    return std::make_shared<TorusStateSampler>(this);\n}\n\ndouble TorusStateSpace::distance(const State *state1, const State *state2) const\n{\n    const auto *cstate1 = static_cast<const CompoundState *>(state1);\n    const auto *cstate2 = static_cast<const CompoundState *>(state2);\n    double x = components_[0]->distance(cstate1->components[0], cstate2->components[0]);\n    double y = components_[1]->distance(cstate1->components[1], cstate2->components[1]);\n    return sqrtf(x * x + y * y);\n}\n\nState *TorusStateSpace::allocState() const\n{\n    auto *state = new StateType();\n    allocStateComponents(state);\n    return state;\n}\n\ndouble TorusStateSpace::getMajorRadius() const\n{\n    return majorRadius_;\n}\n\ndouble TorusStateSpace::getMinorRadius() const\n{\n    return minorRadius_;\n}\n\nEigen::Vector3f TorusStateSpace::toVector(const State *state) const\n{\n    Eigen::Vector3f v;\n\n    const TorusStateSpace::StateType *s = state->as<TorusStateSpace::StateType>();\n    float theta = s->getS1();\n    float phi = s->getS2();\n\n    const double &R = majorRadius_;\n    const double &r = minorRadius_;\n\n    v[0] = (R + r*cos(phi))*cos(theta);\n    v[1] = (R + r*cos(phi))*sin(theta);\n    v[2] = r*sin(phi);\n\n    return v;\n}\n", "meta": {"hexsha": "5d8830b81383211f69a4eaa0cc94daa01ed6b254", "size": 5647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/base/spaces/src/TorusStateSpace.cpp", "max_stars_repo_name": "Russ76/ompl", "max_stars_repo_head_hexsha": "687239a0a8b578e00a95cf80636e3278de56bc7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-07T02:19:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-07T02:19:26.000Z", "max_issues_repo_path": "src/ompl/base/spaces/src/TorusStateSpace.cpp", "max_issues_repo_name": "Russ76/ompl", "max_issues_repo_head_hexsha": "687239a0a8b578e00a95cf80636e3278de56bc7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ompl/base/spaces/src/TorusStateSpace.cpp", "max_forks_repo_name": "Russ76/ompl", "max_forks_repo_head_hexsha": "687239a0a8b578e00a95cf80636e3278de56bc7c", "max_forks_repo_licenses": ["BSD-3-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.1987179487, "max_line_length": 115, "alphanum_fraction": 0.6872675757, "num_tokens": 1411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357632379241, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6062785797921243}}
{"text": "/********************************************************************\n\tcreated:\t2012/08/27\n\tcreated:\t27:8:2012   15:04\n\tfilename: \tVietesFormulaeTest.cpp\n\tfile path:\ttest\n\tfile base:\tVietesFormulaeTest\n\tfile ext:\tcpp\n\tauthor:\t\tHan Hu\n\t\n\tpurpose:\t\n*********************************************************************/\n\n#include \"GAGPL/MATH/VietesFormulae.h\"\n#include <boost/foreach.hpp>\n#include <iostream>\n\nint main()\n{\n\tusing namespace msmath;\n\tusing namespace std;\n\n    double mycoef[] = {3, 2, 0, 5, 1};\n    PolyCoef poly_eq(mycoef, mycoef + sizeof(mycoef) / sizeof(double));\n\n    VietesFormulae formulae(poly_eq);\n    EleSymPolyVec ele_values = formulae.getElementarySymmetricFunctionFromCoef();\n\n    // The correct value should be: 1, -5, 0, -2, 3.\n    for(size_t i=0; i<ele_values.size(); i++)\n    {\n        cout << i << \": \" << ele_values.at(i) << endl;\n    }\n\n    cout << \"The End!\" << endl;\n\n    cin.get();\n\n}", "meta": {"hexsha": "a2fc353f2bdf4f5c073a962ed54769ebed612925", "size": 919, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GAG/test/VietesFormulaeTest.cpp", "max_stars_repo_name": "hh1985/multi_hs_seq", "max_stars_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-03T14:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-15T13:38:39.000Z", "max_issues_repo_path": "GAG/test/VietesFormulaeTest.cpp", "max_issues_repo_name": "hh1985/multi_hs_seq", "max_issues_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GAG/test/VietesFormulaeTest.cpp", "max_forks_repo_name": "hh1985/multi_hs_seq", "max_forks_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_forks_repo_licenses": ["Apache-2.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.1842105263, "max_line_length": 81, "alphanum_fraction": 0.5473340588, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6062373434609436}}
{"text": "//          Copyright Carl Philipp Reh 2009 - 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n\n#include <fcppt/algorithm/contains.hpp>\n#include <fcppt/math/box/corner_points.hpp>\n#include <fcppt/math/box/object_impl.hpp>\n#include <fcppt/math/box/output.hpp>\n#include <fcppt/math/vector/comparison.hpp>\n#include <fcppt/math/vector/object_impl.hpp>\n#include <fcppt/math/vector/output.hpp>\n#include <fcppt/preprocessor/disable_gcc_warning.hpp>\n#include <fcppt/preprocessor/pop_warning.hpp>\n#include <fcppt/preprocessor/push_warning.hpp>\n#include <fcppt/config/external_begin.hpp>\n#include <boost/test/unit_test.hpp>\n#include <array>\n#include <iostream>\n#include <ostream>\n#include <fcppt/config/external_end.hpp>\n\n\nFCPPT_PP_PUSH_WARNING\nFCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)\n\nBOOST_AUTO_TEST_CASE(\n\tmath_box_corner_points\n)\n{\nFCPPT_PP_POP_WARNING\n\n\ttypedef\n\tfcppt::math::box::object<\n\t\tint,\n\t\t2\n\t>\n\tbox_type;\n\n\tbox_type box(\n\t\tbox_type::vector(\n\t\t\t10,\n\t\t\t12\n\t\t),\n\t\tbox_type::dim(24,26)\n\t);\n\n\tstd::cout\n\t\t<<\n\t\t\"Checking border points of box: \"\n\t\t<<\n\t\tbox\n\t\t<<\n\t\t'\\n';\n\n\ttypedef\n\tstd::array<\n\t\tbox_type::vector,\n\t\t4\n\t>\n\tvertex_array;\n\n\tvertex_array const vertices(\n\t\tfcppt::math::box::corner_points(\n\t\t\tbox\n\t\t)\n\t);\n\n\tstd::cout\n\t\t<<\n\t\t\"Result: \\n\";\n\n\tfor(\n\t\tauto const &elem\n\t\t:\n\t\tvertices\n\t)\n\t\tstd::cout\n\t\t\t<<\n\t\t\telem\n\t\t\t<<\n\t\t\t'\\n';\n\n\tBOOST_CHECK(\n\t\tfcppt::algorithm::contains(\n\t\t\tvertices,\n\t\t\tbox_type::vector(\n\t\t\t\t10,\n\t\t\t\t12\n\t\t\t)\n\t\t)\n\t);\n\n\tBOOST_CHECK(\n\t\tfcppt::algorithm::contains(\n\t\t\tvertices,\n\t\t\tbox_type::vector(\n\t\t\t\t34,\n\t\t\t\t12\n\t\t\t)\n\t\t)\n\t);\n\n\tBOOST_CHECK(\n\t\tfcppt::algorithm::contains(\n\t\t\tvertices,\n\t\t\tbox_type::vector(\n\t\t\t\t10,\n\t\t\t\t38\n\t\t\t)\n\t\t)\n\t);\n\n\tBOOST_CHECK(\n\t\tfcppt::algorithm::contains(\n\t\t\tvertices,\n\t\t\tbox_type::vector(\n\t\t\t\t34,\n\t\t\t\t38\n\t\t\t)\n\t\t)\n\t);\n}\n", "meta": {"hexsha": "b50f88cf5cf61b31b1324062c7845417f518cb07", "size": 1886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/math/box/corner_points.cpp", "max_stars_repo_name": "vinzenz/fcppt", "max_stars_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/math/box/corner_points.cpp", "max_issues_repo_name": "vinzenz/fcppt", "max_issues_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/math/box/corner_points.cpp", "max_forks_repo_name": "vinzenz/fcppt", "max_forks_repo_head_hexsha": "3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 15.088, "max_line_length": 61, "alphanum_fraction": 0.664369035, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6061353297119217}}
{"text": "#include <armadillo>\n\nusing namespace arma;\nusing namespace std;\n\nvoid crearTuplas(string rutaArchivo,\n                 int nEntradas,\n                 int nSalidas,\n                 string rutaNuevoArchivo)\n{\n    mat datos;\n    datos.load(rutaArchivo);\n\n    vec meses = datos.col(0);\n    vec ventas = datos.col(1);\n\n    meses = (meses - min(meses)) / (max(meses) - min(meses));\n    ventas = (ventas - min(ventas)) / (max(ventas) - min(ventas));\n\n    const int longitudTupla = 1 + nEntradas + nSalidas;\n\n\t// FIXME: Cuando la cantidad de salidas es mayor a 1\n\t// no se calcula bien la cantidad de tuplas\n    mat tuplas(ventas.n_elem - nEntradas - nSalidas, longitudTupla);\n\n\tfor (unsigned int i = 0; i < tuplas.n_rows; ++i) {\n        const rowvec tupla = join_horiz(rowvec{meses(i)},\n                                        ventas(span(i, i + longitudTupla - 2)).t());\n\t\ttuplas.row(i) = tupla;\n\t}\n\n\ttuplas.save(rutaNuevoArchivo, arma::csv_ascii);\n}\n\nvoid crearTuplas(string rutaArchivo1,\n                 string rutaArchivo2,\n                 string rutaArchivo3,\n                 int nEntradas,\n                 int nSalidas,\n                 string rutaNuevoArchivo)\n{\n\n\tmat datos1;\n\tvec datos2;\n\tvec datos3;\n\tdatos1.load(rutaArchivo1);\n\tdatos2.load(rutaArchivo2);\n\tdatos3.load(rutaArchivo3);\n\n    vec meses = datos1.col(0);\n\tvec ventas = datos1.col(1);\n\n    // Normalizar datos de exportaciones e importacioes\n    meses = (meses - min(meses)) / (max(meses) - min(meses));\n\tventas = (ventas - min(ventas)) / (max(ventas) - min(ventas));\n\tdatos2 = (datos2 - min(datos2)) / (max(datos2) - min(datos2));\n\tdatos3 = (datos3 - min(datos3)) / (max(datos3) - min(datos3));\n\n\tconst int longitudTupla = 1 + nEntradas * 3 + nSalidas;\n\n\tmat tuplas(ventas.n_elem - nEntradas - nSalidas - 1, longitudTupla);\n\n\tfor (unsigned int i = 0; i < tuplas.n_rows; ++i) {\n\t\ttuplas(i, 0) = meses(i);\n\n\t\ttuplas(i, span(1, tuplas.n_cols - nSalidas - 1))\n\t\t    = join_vert(join_vert(ventas.rows(span(i, i + nEntradas - 1)),\n\t\t                          datos2.rows(span(i, i + nEntradas - 1))),\n\t\t                datos3.rows(span(i, i + nEntradas - 1)))\n\t\t          .t();\n\n\t\ttuplas(i,\n\t\t       span(tuplas.n_cols - nSalidas,\n\t\t            tuplas.n_cols - 1))\n\t\t    = ventas(span(i + nEntradas,\n\t\t                  i + nEntradas + nSalidas - 1))\n\t\t          .t();\n\t}\n\n\ttuplas.save(rutaNuevoArchivo, arma::csv_ascii);\n}\n", "meta": {"hexsha": "dfdc000dd76c526249dbfad647f98361a7bbd7cd", "size": 2389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TP_Final/agrupar_por_tuplas.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": "TP_Final/agrupar_por_tuplas.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": "TP_Final/agrupar_por_tuplas.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": 29.1341463415, "max_line_length": 84, "alphanum_fraction": 0.5868564253, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6060834111942305}}
{"text": "#include \"tutorial_shared_path.h\"\r\n#include <igl/fast_winding_number.h>\r\n#include <igl/read_triangle_mesh.h>\r\n#include <igl/slice_mask.h>\r\n#include <Eigen/Geometry>\r\n#include <igl/octree.h>\r\n#include <igl/barycenter.h>\r\n#include <igl/knn.h>\r\n#include <igl/random_points_on_mesh.h>\r\n#include <igl/bounding_box_diagonal.h>\r\n#include <igl/per_face_normals.h>\r\n#include <igl/copyleft/cgal/point_areas.h>\r\n#include <igl/opengl/glfw/Viewer.h>\r\n#include <igl/get_seconds.h>\r\n#include <iostream>\r\n#include <cstdlib>\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n  const auto time = [](std::function<void(void)> func)->double\r\n  {\r\n    const double t_before = igl::get_seconds();\r\n    func();\r\n    const double t_after = igl::get_seconds();\r\n    return t_after-t_before;\r\n  };\r\n\r\n  Eigen::MatrixXd V;\r\n  Eigen::MatrixXi F;\r\n  igl::read_triangle_mesh(argc>1?argv[1]:TUTORIAL_SHARED_PATH \"/bunny.off\",V,F);\r\n  // Sample mesh for point cloud\r\n  Eigen::MatrixXd P,N;\r\n  {\r\n    Eigen::VectorXi I;\r\n    Eigen::SparseMatrix<double> B;\r\n    igl::random_points_on_mesh(10000,V,F,B,I);\r\n    P = B*V;\r\n    Eigen::MatrixXd FN;\r\n    igl::per_face_normals(V,F,FN);\r\n    N.resize(P.rows(),3);\r\n    for(int p = 0;p<I.rows();p++)\r\n    {\r\n      N.row(p) = FN.row(I(p));\r\n    }\r\n  }\r\n  // Build octree\r\n  std::vector<std::vector<int > > O_PI;\r\n  Eigen::MatrixXi O_CH;\r\n  Eigen::MatrixXd O_CN;\r\n  Eigen::VectorXd O_W;\r\n  igl::octree(P,O_PI,O_CH,O_CN,O_W);\r\n  Eigen::VectorXd A;\r\n  {\r\n    Eigen::MatrixXi I;\r\n    igl::knn(P,20,O_PI,O_CH,O_CN,O_W,I);\r\n    // CGAL is only used to help get point areas\r\n    igl::copyleft::cgal::point_areas(P,I,N,A);\r\n  }\r\n\r\n  if(argc<=1)\r\n  {\r\n    // corrupt mesh\r\n    Eigen::MatrixXd BC;\r\n    igl::barycenter(V,F,BC);\r\n    Eigen::MatrixXd OV = V;\r\n    V.resize(F.rows()*3,3);\r\n    for(int f = 0;f<F.rows();f++)\r\n    {\r\n      for(int c = 0;c<3;c++)\r\n      {\r\n        int v = f+c*F.rows();\r\n        // random rotation about barycenter\r\n        Eigen::AngleAxisd R(\r\n          0.5*static_cast <double> (rand()) / static_cast <double> (RAND_MAX),\r\n          Eigen::Vector3d::Random(3,1));\r\n        V.row(v) = (OV.row(F(f,c))-BC.row(f))*R.matrix()+BC.row(f);\r\n        F(f,c) = v;\r\n      }\r\n    }\r\n  }\r\n\r\n  // Generate a list of random query points in the bounding box\r\n  Eigen::MatrixXd Q = Eigen::MatrixXd::Random(1000000,3);\r\n  const Eigen::RowVector3d Vmin = V.colwise().minCoeff();\r\n  const Eigen::RowVector3d Vmax = V.colwise().maxCoeff();\r\n  const Eigen::RowVector3d Vdiag = Vmax-Vmin;\r\n  for(int q = 0;q<Q.rows();q++)\r\n  {\r\n    Q.row(q) = (Q.row(q).array()*0.5+0.5)*Vdiag.array() + Vmin.array();\r\n  }\r\n\r\n  // Positions of points inside of point cloud P\r\n  Eigen::MatrixXd QiP;\r\n  {\r\n    Eigen::MatrixXd O_CM;\r\n    Eigen::VectorXd O_R;\r\n    Eigen::MatrixXd O_EC;\r\n    printf(\"  point cloud precomputation: %g secs\\n\",\r\n      time([&](){igl::fast_winding_number(P,N,A,O_PI,O_CH,2,O_CM,O_R,O_EC);}));\r\n    Eigen::VectorXd WiP;\r\n    printf(\"      point cloud evaluation: %g secs\\n\",\r\n      time([&](){igl::fast_winding_number(P,N,A,O_PI,O_CH,O_CM,O_R,O_EC,Q,2,WiP);}));\r\n    igl::slice_mask(Q,WiP.array()>0.5,1,QiP);\r\n  }\r\n\r\n  // Positions of points inside of triangle soup (V,F)\r\n  Eigen::MatrixXd QiV;\r\n  {\r\n    igl::FastWindingNumberBVH fwn_bvh;\r\n    printf(\"triangle soup precomputation: %g secs\\n\",\r\n      time([&](){igl::fast_winding_number(V.cast<float>(),F,2,fwn_bvh);}));\r\n    Eigen::VectorXf WiV;\r\n    printf(\"    triangle soup evaluation: %g secs\\n\",\r\n      time([&](){igl::fast_winding_number(fwn_bvh,2,Q.cast<float>(),WiV);}));\r\n    igl::slice_mask(Q,WiV.array()>0.5,1,QiV);\r\n  }\r\n\r\n\r\n  // Visualization\r\n  igl::opengl::glfw::Viewer viewer;\r\n  // For dislpaying normals as little line segments\r\n  Eigen::MatrixXd PN(2*P.rows(),3);\r\n  Eigen::MatrixXi E(P.rows(),2);\r\n  const double bbd = igl::bounding_box_diagonal(V);\r\n  for(int p = 0;p<P.rows();p++)\r\n  {\r\n    E(p,0) = 2*p;\r\n    E(p,1) = 2*p+1;\r\n    PN.row(E(p,0)) = P.row(p);\r\n    PN.row(E(p,1)) = P.row(p)+bbd*0.01*N.row(p);\r\n  }\r\n\r\n  bool show_P = false;\r\n  int show_Q = 0;\r\n\r\n  int query_data = 0;\r\n  viewer.data_list[query_data].set_mesh(V,F);\r\n  viewer.data_list[query_data].clear();\r\n  viewer.data_list[query_data].point_size = 2;\r\n  viewer.append_mesh();\r\n  int object_data = 1;\r\n  viewer.data_list[object_data].set_mesh(V,F);\r\n  viewer.data_list[object_data].point_size = 5;\r\n\r\n  const auto update = [&]()\r\n  {\r\n    viewer.data_list[query_data].clear();\r\n    switch(show_Q)\r\n    {\r\n      case 1:\r\n        // show all Q\r\n        viewer.data_list[query_data].set_points(Q,Eigen::RowVector3d(0.996078,0.760784,0.760784));\r\n        break;\r\n      case 2:\r\n        // show all Q inside\r\n        if(show_P)\r\n        {\r\n          viewer.data_list[query_data].set_points(QiP,Eigen::RowVector3d(0.564706,0.847059,0.768627));\r\n        }else\r\n        {\r\n          viewer.data_list[query_data].set_points(QiV,Eigen::RowVector3d(0.564706,0.847059,0.768627));\r\n        }\r\n        break;\r\n    }\r\n    \r\n    viewer.data_list[object_data].clear();\r\n    if(show_P)\r\n    {\r\n      viewer.data_list[object_data].set_points(P,Eigen::RowVector3d(1,1,1));\r\n      viewer.data_list[object_data].set_edges(PN,E,Eigen::RowVector3d(0.8,0.8,0.8));\r\n    }else\r\n    {\r\n      viewer.data_list[object_data].set_mesh(V,F);\r\n    }\r\n  };\r\n\r\n\r\n\r\n  viewer.callback_key_pressed = \r\n    [&](igl::opengl::glfw::Viewer &, unsigned int key, int mod)\r\n  {\r\n    switch(key)\r\n    {\r\n      default: \r\n        return false;\r\n      case '1':\r\n        show_P = !show_P;\r\n        break;\r\n      case '2':\r\n        show_Q = (show_Q+1) % 3;\r\n        break;\r\n    }\r\n    update();\r\n    return true;\r\n  };\r\n\r\n  update();\r\n  viewer.launch();\r\n\r\n}\r\n", "meta": {"hexsha": "62e47806c7fd524dd82f43a62a693cca45585bd2", "size": 5655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdf-net/lib/submodules/libigl/tutorial/717_FastWindingNumber/main.cpp", "max_stars_repo_name": "hardikk13/nglod", "max_stars_repo_head_hexsha": "6c6c66ce1b39c5a3515cafc290ec903ae90b506e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdf-net/lib/submodules/libigl/tutorial/717_FastWindingNumber/main.cpp", "max_issues_repo_name": "hardikk13/nglod", "max_issues_repo_head_hexsha": "6c6c66ce1b39c5a3515cafc290ec903ae90b506e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdf-net/lib/submodules/libigl/tutorial/717_FastWindingNumber/main.cpp", "max_forks_repo_name": "hardikk13/nglod", "max_forks_repo_head_hexsha": "6c6c66ce1b39c5a3515cafc290ec903ae90b506e", "max_forks_repo_licenses": ["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.1343283582, "max_line_length": 103, "alphanum_fraction": 0.5915119363, "num_tokens": 1718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.606072302869872}}
{"text": "#include <dlib/matrix.h>\n#include <dlib/svm.h>\n#include <plot.h>\n\n#include \"isolation-forest.h\"\n\n#include <experimental/filesystem>\n#include <iostream>\n#include <unordered_map>\n\nusing namespace dlib;\nnamespace fs = std::experimental::filesystem;\n\nconst std::vector<std::string> colors{\"black\", \"red\",    \"blue\",  \"green\",\n                                      \"cyan\",  \"yellow\", \"brown\", \"magenta\"};\n\nusing DataType = double;\nusing Matrix = matrix<DataType>;\nusing Coords = std::vector<DataType>;\nusing PointCoords = std::pair<Coords, Coords>;\nusing Clusters = std::unordered_map<size_t, PointCoords>;\n\nvoid PlotClusters(const Clusters& clusters,\n                  const std::string& name,\n                  const std::string& file_name) {\n  plotcpp::Plot plt(true);\n  // plt.SetTerminal(\"qt\");\n  plt.SetTerminal(\"png\");\n  plt.SetOutput(file_name);\n  plt.SetTitle(name);\n  plt.SetXLabel(\"x\");\n  plt.SetYLabel(\"y\");\n  // plt.SetAutoscale();\n  plt.GnuplotCommand(\"set size square\");\n  plt.GnuplotCommand(\"set grid\");\n\n  auto draw_state = plt.StartDraw2D<Coords::const_iterator>();\n  for (auto& cluster : clusters) {\n    std::stringstream params;\n    params << \"lc rgb '\" << colors[cluster.first] << \"' pt 7\";\n    plt.AddDrawing(draw_state,\n                   plotcpp::Points(\n                       cluster.second.first.begin(), cluster.second.first.end(),\n                       cluster.second.second.begin(),\n                       std::to_string(cluster.first) + \" cls\", params.str()));\n  }\n\n  plt.EndDraw2D(draw_state);\n  plt.Flush();\n}\n\nvoid MultivariateGaussianDist(const Matrix& normal,\n                              const Matrix& test,\n                              const std::string& file_name) {\n  // assume that rows are samples and columns are features\n\n  // calculate per feature mean\n  dlib::matrix<double> mu(1, normal.nc());\n  dlib::set_all_elements(mu, 0);\n\n  for (long c = 0; c < normal.nc(); ++c) {\n    auto col_mean = dlib::mean(dlib::colm(normal, c));\n    dlib::set_colm(mu, c) = col_mean;\n  }\n\n  // calculate covariance matrix\n  dlib::matrix<double> cov(normal.nc(), normal.nc());\n  dlib::set_all_elements(cov, 0);\n  for (long r = 0; r < normal.nr(); ++r) {\n    auto row = dlib::rowm(normal, r);\n    cov += dlib::trans(row - mu) * (row - mu);\n  }\n  cov *= 1.0 / normal.nr();\n  double cov_det = dlib::det(cov);\n  dlib::matrix<double> cov_inv = dlib::inv(cov);\n\n  auto first_part =\n      1. / std::pow(2. * M_PI, normal.nc() / 2.) / std::sqrt(cov_det);\n\n  // define probability function\n  auto prob = [&](const dlib::matrix<double>& sample) {\n    dlib::matrix<double> s = sample - mu;\n    dlib::matrix<double> exp_val_m = s * (cov_inv * dlib::trans(s));\n    double exp_val = -0.5 * exp_val_m(0, 0);\n    double p = first_part * std::exp(exp_val);\n    return p;\n  };\n\n  Clusters clusters;  // there will two clusters with normal and anomaly data\n\n  // change this parameter to see descision boundary\n  double prob_threshold = 0.001;\n\n  auto detect = [&](auto samples) {\n    for (long r = 0; r < samples.nr(); ++r) {\n      auto row = dlib::rowm(samples, r);\n      double x = row(0, 0);\n      double y = row(0, 1);\n      auto p = prob(row);\n      if (p >= prob_threshold) {\n        clusters[0].first.push_back(x);\n        clusters[0].second.push_back(y);\n      } else {\n        clusters[1].first.push_back(x);\n        clusters[1].second.push_back(y);\n      }\n    }\n  };\n\n  detect(normal);\n  detect(test);\n  PlotClusters(clusters, \"Multivariate Gaussian Distribution\", file_name);\n}\n\nvoid OneClassSvm(const Matrix& normal,\n                 const Matrix& test,\n                 const std::string& file_name) {\n  typedef matrix<double, 0, 1> sample_type;\n  typedef radial_basis_kernel<sample_type> kernel_type;\n  svm_one_class_trainer<kernel_type> trainer;\n  trainer.set_nu(0.5);                   // control smoothness of the solution\n  trainer.set_kernel(kernel_type(0.5));  // kernel bandwidth\n  std::vector<sample_type> samples;\n  for (long r = 0; r < normal.nr(); ++r) {\n    auto row = rowm(normal, r);\n    samples.push_back(row);\n  }\n  decision_function<kernel_type> df = trainer.train(samples);\n  Clusters clusters;\n  double threshold = -2.0;\n\n  auto detect = [&](auto samples) {\n    for (long r = 0; r < samples.nr(); ++r) {\n      auto row = dlib::rowm(samples, r);\n      double x = row(0, 0);\n      double y = row(0, 1);\n      auto p = df(row);\n      if (p > threshold) {\n        clusters[0].first.push_back(x);\n        clusters[0].second.push_back(y);\n      } else {\n        clusters[1].first.push_back(x);\n        clusters[1].second.push_back(y);\n      }\n    }\n  };\n\n  detect(normal);\n  detect(test);\n  PlotClusters(clusters, \"One Class SVM\", file_name);\n}\n\nvoid IsolationForest(const Matrix& normal,\n                     const Matrix& test,\n                     const std::string& file_name) {\n  iforest::Dataset<2> dataset;\n\n  auto put_to_dataset = [&](const Matrix& samples) {\n    for (long r = 0; r < samples.nr(); ++r) {\n      auto row = dlib::rowm(samples, r);\n      double x = row(0, 0);\n      double y = row(0, 1);\n      dataset.push_back({x, y});\n    }\n  };\n\n  put_to_dataset(normal);\n  put_to_dataset(test);\n\n  iforest::IsolationForest iforest(dataset, 300, 50);\n\n  Clusters clusters;\n  double threshold = 0.6;  // change this value to see isolation boundary\n  for (auto& s : dataset) {\n    auto anomaly_score = iforest.AnomalyScore(s);\n    // std::cout << anomaly_score << \" \" << s[0] << \" \" << s[1] << std::endl;\n\n    if (anomaly_score < threshold) {\n      clusters[0].first.push_back(s[0]);\n      clusters[0].second.push_back(s[1]);\n    } else {  // anomaly\n      clusters[1].first.push_back(s[0]);\n      clusters[1].second.push_back(s[1]);\n    }\n  }\n\n  PlotClusters(clusters, \"Isolation Forest\", file_name);\n}\n\nusing Dataset = std::pair<Matrix, Matrix>;\n\nDataset LoadDataset(const fs::path& file_path) {\n  if (fs::exists(file_path)) {\n    std::ifstream file(file_path);\n    matrix<DataType> data;\n    file >> data;\n\n    long n_normal = 50;\n    Matrix normal =\n        dlib::subm(data, range(0, n_normal - 1), range(0, data.nc() - 1));\n    Matrix test = dlib::subm(data, range(n_normal, data.nr() - 1),\n                             range(0, data.nc() - 1));\n    return {normal, test};\n  } else {\n    std::string msg = \"Dataset file \" + file_path.string() + \" missed\\n\";\n    throw std::invalid_argument(msg);\n  }\n}\n\nDataset CombineDatasets(const Dataset& a, const Dataset& b) {\n  Matrix normal(a.first.nr() + b.first.nr(), a.first.nc());\n  set_subm(normal, range(0, a.first.nr() - 1), range(0, a.first.nc() - 1)) =\n      a.first;\n  set_subm(normal, range(a.first.nr(), normal.nr() - 1),\n           range(0, a.first.nc() - 1)) = b.first;\n\n  Matrix test(a.second.nr() + b.second.nr(), a.second.nc());\n  set_subm(test, range(0, a.second.nr() - 1), range(0, a.second.nc() - 1)) =\n      a.second;\n  set_subm(test, range(a.second.nr(), test.nr() - 1),\n           range(0, a.second.nc() - 1)) = b.second;\n\n  return {normal, test};\n}\n\nint main(int argc, char** argv) {\n  if (argc > 1) {\n    try {\n      auto base_dir = fs::path(argv[1]);\n\n      std::string data_name_multi{\"multivar.csv\"};\n      std::string data_name_uni{\"univar.csv\"};\n\n      auto dataset_multi = LoadDataset(base_dir / data_name_multi);\n      auto dataset_uni = LoadDataset(base_dir / data_name_uni);\n\n      MultivariateGaussianDist(dataset_multi.first, dataset_multi.second,\n                               \"dlib-multi-var.png\");\n      OneClassSvm(dataset_multi.first, dataset_multi.second, \"dlib-ocsvm.png\");\n\n      // make dataset with two clusters\n\n      auto dataset_combi = CombineDatasets(dataset_multi, dataset_uni);\n      OneClassSvm(dataset_combi.first, dataset_combi.second,\n                  \"dlib-ocsvm_two.png\");\n\n      IsolationForest(dataset_combi.first, dataset_combi.second,\n                      \"dlib-iforest-two.png\");\n\n    } catch (const std::exception& err) {\n      std::cerr << err.what();\n    }\n  } else {\n    std::cerr << \"Please provider path to the datasets folder\\n\";\n  }\n  return 0;\n}\n", "meta": {"hexsha": "2ff0fa0bcd3c98557258bdacff7ca53500b0d439", "size": 8009, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter05/dlib/dlib-anomaly.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter05/dlib/dlib-anomaly.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter05/dlib/dlib-anomaly.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 31.0426356589, "max_line_length": 80, "alphanum_fraction": 0.6038207017, "num_tokens": 2177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.606072285501174}}
{"text": "\n#include \"floor.hpp\"\n#include \"ast.hpp\"\n#include \"parsers.hpp\"\n#include \"types.hpp\"\n#include <boost/variant.hpp>\n#include <stdexcept>\nnamespace HT\n{\n    void floor(PASTNode astnode, ParsersHelper& ph)\n    {\n        auto myParserHelper(ph);\n        if (astnode->ch.size()!=2)\n          throw std::runtime_error(\"floor can only have one parameter\");\n        auto & secondCh = *astnode->ch.rbegin();\n        ph.parse(secondCh);\n        if (secondCh->token.tokenType != Complex || ! boost::get<ComplexType>(secondCh->token.info).isReal())\n          throw std::runtime_error(\"The argument of floor must be real\");\n        auto cast = boost::get<ComplexType>(secondCh->token.info);\n\n        astnode->type = Simple;\n        astnode->token.tokenType = Complex;\n\n        if (!cast.exact())\n          astnode->token.info = ComplexType(std::floor(cast.getRealD()));\n        else\n        {\n            auto rat = cast.getRealR();\n            if (rat.getSign())\n              astnode->token.info = ComplexType( rat.getUp() / rat.getDown() );\n            else\n              if (rat.isInt())\n                astnode->token.info = cast;\n            else\n            {\n                auto res = rat.getUp() / rat.getDown();\n                res.setSign(false);\n                res -= 1;\n                astnode->token.info = ComplexType(res);\n            }\n        }\n\n        astnode->remove();\n    }\n\n}\n\n\n", "meta": {"hexsha": "099c8a293ec0e4ef8550c55c26005279b532622e", "size": 1390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "funs/floor.cpp", "max_stars_repo_name": "htfy96/htscheme", "max_stars_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T01:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-14T10:45:01.000Z", "max_issues_repo_path": "funs/floor.cpp", "max_issues_repo_name": "htfy96/htscheme", "max_issues_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "funs/floor.cpp", "max_forks_repo_name": "htfy96/htscheme", "max_forks_repo_head_hexsha": "b44c9f9672f69d9b3c2eb1c80969bcfcfec9990f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3673469388, "max_line_length": 109, "alphanum_fraction": 0.5388489209, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722394, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6060722812387906}}
{"text": "/**\n * Copyright (c) 2018, The Akatsuki(Jacob.lsx). All rights reserved.\n */\n\n\n#include <iostream>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n\n#include <chrono>\n\nusing namespace std;\nusing namespace cv;\n\n/* find the two photo feature matches points */\nvoid find_feature_matches(const cv::Mat&, const cv::Mat&, std::vector<cv::KeyPoint>&, std::vector<cv::KeyPoint>&, std::vector<cv::DMatch>&);\n\n/* Converts the pixel coordinate system to the normalized imaging plane coordinate system */\ncv::Point2d pixel2cam(const cv::Point2d&, const cv::Mat&);\n\n/*  */\nvoid pose_estimation_3d3d(const std::vector<cv::Point3f>&, const std::vector<cv::Point3f>&, cv::Mat&, cv::Mat&);\n\n/*  */\nvoid bundleAdjustment(const std::vector<cv::Point3f>&, const std::vector<cv::Point3f>&, cv::Mat&, cv::Mat&);\n\nint main(int argc, char** argv)\n{\n    google::InitGoogleLogging(argv[0]);\n    if (argc != 5) {\n        cout << \"usage: pose_estimation_3d3d img1 img2 depth1 depth2.\" << endl;\n        return 1;\n    }\n    \n    //-- 1st, read photo\n    cv::Mat img_1 = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);\n    cv::Mat img_2 = cv::imread(argv[2], CV_LOAD_IMAGE_COLOR);\n    if (img_1.empty() || img_2.empty()) {\n        cerr << \"img1 or img2 is empty.\" << endl;\n        return 1;\n    }\n    \n    //-- 2nd, find the two photo feature matches points\n    std::vector<cv::KeyPoint> keypoints_1, keypoints_2;\n    std::vector<cv::DMatch> matches;\n    find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n    cout << \"feature matches points total is \" << matches.size() << endl;\n    \n    //-- 3rd, create 3 dimensions point correspondences\n    cv::Mat depth1 = cv::imread(argv[3], CV_LOAD_IMAGE_UNCHANGED);      // \u6df1\u5ea6\u56fe\u4e3a16\u4f4d\u65e0\u7b26\u53f7\u6570\uff0c\u5355\u901a\u9053\u56fe\u50cf\n    cv::Mat depth2 = cv::imread(argv[4], CV_LOAD_IMAGE_UNCHANGED);\n    if (depth1.empty() || depth2.empty()) {\n        cerr << \"depth1 or depth2 is empty.\" << endl;\n        return 1;\n    }\n    \n    cv::Mat K = (cv::Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n    std::vector<cv::Point3f> pts1, pts2;\n    \n    for (cv::DMatch m : matches) {\n        ushort d1 = depth1.ptr<unsigned short>((int)keypoints_1[m.queryIdx].pt.y)[(int)keypoints_1[m.queryIdx].pt.x];\n        ushort d2 = depth2.ptr<unsigned short>((int)keypoints_2[m.trainIdx].pt.y)[(int)keypoints_2[m.trainIdx].pt.x];\n        if (d1 == 0 || d2 == 0) {\n            continue;\n        }\n        cv::Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n        cv::Point2d p2 = pixel2cam(keypoints_2[m.trainIdx].pt, K);\n        float dd1 = float(d1) / 5000.0;\n        float dd2 = float(d2) / 5000.0;\n        pts1.push_back(cv::Point3f(p1.x * dd1, p1.y * dd1, dd1));\n        pts2.push_back(cv::Point3f(p2.x * dd2, p2.y * dd2, dd2));\n    }\n    cout << \"3d-3d pairs: \" << pts1.size() << endl;\n    \n    cv::Mat R, t;\n    pose_estimation_3d3d(pts1, pts2, R, t);\n    cout << \"ICP vid SVD results: \" << endl;\n    cout << \"R = \" << R << endl;\n    cout << \"t = \" << t << endl;\n    cout << \"R_inv = \" << R.t() << endl;\n    cout << \"t_inv = \" << -R.t() * t << endl;\n    \n    cout << \"calling bundle adjustment. \\r\\n\";\n    \n    bundleAdjustment(pts1, pts2, R, t);\n    \n    // verify p1 = R*p2 + t\n    for (int i = 0; i < 5; i ++) {\n        cout << \"p1 = \" << pts1[i] << endl;\n        cout << \"p2 = \" << pts2[i] << endl;\n        cout << \"R*p2 + t = \" << R * (Mat_<double>(3, 1) << pts2[i].x, pts2[i].y, pts2[i].z) + t << endl;\n        cout << endl;\n    }\n    \n    return 0;\n}\n\n\n/**\n * find the two photo feature matches points\n */\nvoid find_feature_matches(const cv::Mat& img_1, const cv::Mat& img_2, std::vector<cv::KeyPoint>& keypoints_1, std::vector<cv::KeyPoint>& keypoints_2, std::vector<cv::DMatch>& matches)\n{\n    //-- Initialize\n    cv::Mat descriptors_1, descriptors_2;\n    cv::Ptr<cv::FeatureDetector> detector = cv::ORB::create();\n    cv::Ptr<cv::DescriptorExtractor> descriptor = cv::ORB::create();\n    cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n    \n    //-- 1st: detect Oriented FAST KeyPoint \n    detector->detect(img_1, keypoints_1);\n    detector->detect(img_2, keypoints_2);\n    \n    //-- 2nd: Calculates BRIEF descriptors with KeyPoint's coordinate\n    descriptor->compute(img_1, keypoints_1, descriptors_1);\n    descriptor->compute(img_2, keypoints_2, descriptors_2);\n    \n    //-- 3rd: \u5bf9\u4e24\u5e45\u56fe\u50cf\u4e2d\u7684BRIEF\u63cf\u8ff0\u5b50\u8fdb\u884c\u5339\u914d\uff0c\u4f7f\u7528 Hamming \u8ddd\u79bb\n    std::vector<cv::DMatch> match;\n    matcher->match(descriptors_1, descriptors_2, match);\n    \n    //-- 4th: \u5339\u914d\u70b9\u5bf9\u7b5b\u9009\n    double min_dist = 10000, max_dist = 0;\n    \n    /* \u627e\u51fa\u6240\u6709\u5339\u914d\u4e4b\u95f4\u7684\u6700\u5c0f\u8ddd\u79bb\u548c\u6700\u5927\u8ddd\u79bb, \u5373\u662f\u6700\u76f8\u4f3c\u7684\u548c\u6700\u4e0d\u76f8\u4f3c\u7684\u4e24\u7ec4\u70b9\u4e4b\u95f4\u7684\u8ddd\u79bb */\n    for (int i = 0; i < descriptors_1.rows; i++) {\n        double dist = match[i].distance;\n        if (dist < min_dist) {\n            min_dist = dist;\n        }\n        if (dist > max_dist) {\n            max_dist = dist;\n        }\n    }\n    \n    printf(\"-- Max distance : %f \\r\\n\", max_dist);\n    printf(\"-- Min distance : %f \\r\\n\", min_dist);\n    \n    // \u5f53\u63cf\u8ff0\u5b50\u4e4b\u95f4\u7684\u8ddd\u79bb\u5927\u4e8e\u4e24\u500d\u7684\u6700\u5c0f\u8ddd\u79bb\u65f6,\u5373\u8ba4\u4e3a\u5339\u914d\u6709\u8bef.\u4f46\u6709\u65f6\u5019\u6700\u5c0f\u8ddd\u79bb\u4f1a\u975e\u5e38\u5c0f,\u8bbe\u7f6e\u4e00\u4e2a\u7ecf\u9a8c\u503c30\u4f5c\u4e3a\u4e0b\u9650.\n    for (int i = 0; i < descriptors_2.rows; i ++) {\n        if (match[i].distance <= max(2*min_dist, 30.0)) {\n            matches.push_back(match[i]);\n        }\n    }\n}\n\n/**\n * Converts the pixel coordinate system to the normalized imaging plane coordinate system\n */\ncv::Point2d pixel2cam(const cv::Point2d& p, const cv::Mat& K)\n{\n    return cv::Point2d\n        (\n            (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n            (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n        );\n}\n\nvoid pose_estimation_3d3d(const std::vector<cv::Point3f>& pts1, const std::vector<cv::Point3f>& pts2, cv::Mat& R, cv::Mat& t)\n{\n    // center of mass\n    cv::Point3f p1, p2;\n    int N = pts1.size();\n    for (int i = 0; i < N; i ++) {\n        p1 += pts1[i];\n        p2 += pts2[i];\n    }\n    p1 = cv::Point3f(Vec3f(p1) / N);\n    p2 = cv::Point3f(Vec3f(p2) / N);\n    \n    // remove the center\n    std::vector<cv::Point3f> q1(N), q2(N);\n    for (int i = 0; i < N; i ++) {\n        q1[i] = pts1[i] - p1;\n        q2[i] = pts2[i] - p2;\n    }\n    \n    // compute q1*q2^T\n    Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n    for (int i = 0; i < N; i ++) {\n        W += Eigen::Vector3d(q1[i].x, q1[i].y, q1[i].z) * Eigen::Vector3d(q2[i].x, q2[i].y, q2[i].z).transpose();\n    }\n    cout << \"W = \" << W << endl;\n    \n    // SVD on W\n    Eigen::JacobiSVD<Eigen::Matrix3d> svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::Matrix3d U = svd.matrixU();\n    Eigen::Matrix3d V = svd.matrixV();\n\n    // \u5229\u7528SVD\u6c42\u89e33D-3D\u53d8\u6362\uff0c\u9700\u8981U\u548cV\u7684\u884c\u5217\u5f0f\u540c\u53f7\u3002\u6362\u8a00\u4e4b\uff0c\u65cb\u8f6c\u77e9\u9635\u7684\u884c\u5217\u5f0f\u53ea\u80fd\u4e3a1\uff0c\u4e0d\u80fd\u4e3a-1\n    if (U.determinant() * V.determinant() < 0) {\n        for (int x = 0; x < 3; ++x) {\n            U(x, 2) *= -1;\n        }\n    }\n    cout << \"U = \" << U << endl;\n    cout << \"V = \" << V << endl;\n    \n    \n    Eigen::Matrix3d R_ = U * (V.transpose());\n    Eigen::Vector3d t_ = Eigen::Vector3d(p1.x, p1.y, p1.z) - R_ * Eigen::Vector3d(p2.x, p2.y, p2.z);\n    \n    // convert to cv::mat\n    R = (cv::Mat_<double>(3, 3) <<\n        R_(0, 0), R_(0, 1), R_(0, 2),\n        R_(1, 0), R_(1, 1), R_(1, 2),\n        R_(2, 0), R_(2, 1), R_(2, 2)\n    );\n    t = (cv::Mat_<double>(3, 1) << t_(0, 0), t_(1, 0), t_(2, 0));\n}\n\nclass ReprojectionError {\npublic:\n    ReprojectionError(const cv::Point3f &point1, const cv::Point3f &point2) : pt1_(point1), pt2_(point2) {}\n    \n    template<typename T>\n    bool operator() (const T* const r, const T* const t, T* residuals) const\n    {\n        T p[3];\n        T pt2[3] = {(T)pt2_.x, (T)pt2_.y, (T)pt2_.z};\n        \n        ceres::AngleAxisRotatePoint(r, pt2, p);\n                \n        p[0] += t[0];\n        p[1] += t[1];\n        p[2] += t[2];\n        \n        residuals[0] = p[0] - (T)pt1_.x;\n        residuals[1] = p[1] - (T)pt1_.y;\n        residuals[2] = p[2] - (T)pt1_.z;\n        \n        return true;\n    }\n    \n    static ceres::CostFunction* create(const cv::Point3f &point1, const cv::Point3f &point2)\n    {\n        return new ceres::AutoDiffCostFunction<ReprojectionError, 3, 3, 3>(new ReprojectionError(point1, point2));\n    }\n    \nprivate:\n    cv::Point3f pt1_, pt2_;\n};\n\nvoid bundleAdjustment(const std::vector<cv::Point3f>& pts1, const std::vector<cv::Point3f>& pts2, cv::Mat& R, cv::Mat& t)\n{\n    cv::Mat r;\n    cv::Rodrigues(R, r);\n    \n    double rotation[3] = {0.f};\n    double translation[3] = {0.f};\n    \n#if 1\n    for (int i = 0; i < 3; i++) {\n        rotation[i] = r.at<double>(i, 0);\n        translation[i] = r.at<double>(i, 0);\n    }\n#endif\n    \n    ceres::Problem problem;\n    for (int i = 0; i < pts1.size(); i ++) {\n        ceres::CostFunction *costFunction = ReprojectionError::create(pts1[i], pts2[i]);\n        problem.AddResidualBlock(costFunction, nullptr, rotation, translation);\n    }\n    \n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_SCHUR;\n    options.minimizer_progress_to_stdout = true;\n    ceres::Solver::Summary summary;\n\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    \n    ceres::Solve(options, &problem, &summary);\n\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>> (t2 - t1);\n    \n    cout << summary.BriefReport() << endl;\n    \n    cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << \"\\r\\n\";\n    \n    cout << endl << \"after optimization: \" << endl;\n    \n    cv::Mat R_vec = (cv::Mat_<double>(3, 1) << rotation[0], rotation[1], rotation[2]);\n    cv::Mat Rotation;\n    cv::Rodrigues(R_vec, Rotation);\n    \n    cout << \"R = \\r\\n\" << Rotation << endl;\n    cout << \"t = \\r\\n\" << translation[0] << \", \" << translation[1] << \", \" << translation[2] << endl;\n    \n    R = Rotation;\n    t = (cv::Mat_<double>(3,1) << translation[0], translation[1], translation[2]);\n}\n\n\n\n", "meta": {"hexsha": "86adb67ec5ca74d75028c15addb68eefe3512ac6", "size": 10010, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_estimation_3d3d/src/pose_estimation_3d3d_ceres.cpp", "max_stars_repo_name": "LSXiang/slam_learning_journey", "max_stars_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-22T00:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T05:23:27.000Z", "max_issues_repo_path": "pose_estimation_3d3d/src/pose_estimation_3d3d_ceres.cpp", "max_issues_repo_name": "LSXiang/slam_learning_journey", "max_issues_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pose_estimation_3d3d/src/pose_estimation_3d3d_ceres.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": 32.7124183007, "max_line_length": 183, "alphanum_fraction": 0.5721278721, "num_tokens": 3436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388125473629, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.6060028397864402}}
{"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_DIST_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DIST_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing dist\n\n    Computes the absolute value of the difference of its parameters.\n\n    @par semantic:\n    For any given value @c x,  @c y of type @c T:\n\n    @code\n    T r = dist(x, y);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = abs(x-y);\n    @endcode\n\n    @par Note\n\n    The result may be negative for signed integers as @ref abs(@ref Valmin) is @ref Valmin.\n    To avoid the problem you can apply to dist the saturated_ @ref decorator.\n\n    @par Decorators\n\n     - saturated_ decorator garanties that saturated_(dist)(x, y)) will never be strictly less than 0.\n\n    @see  ulpdist, abs\n\n  **/\n  Value dist(Option const& o, Value const & v0, Value const& v1);\n\n  //@overload\n  Value dist(Value const & v0, Value const& v1);\n} }\n#endif\n\n#include <boost/simd/function/scalar/dist.hpp>\n#include <boost/simd/function/simd/dist.hpp>\n\n#endif\n", "meta": {"hexsha": "64ca6389e092c9c77e5052f181cf9772a87e3376", "size": 1455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/dist.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/dist.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/dist.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 23.8524590164, "max_line_length": 102, "alphanum_fraction": 0.5965635739, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6060028331615341}}
{"text": "/**\n * Multidimensional Static Matrix C++11 \n * Copyright Emanuele Ruffaldi (2015) at Scuola Superiore Sant'Anna Pisa\n *\n * AKA extreme parameter packs\n *\n * Core functionalities ... the rest is \"trivial\"\n *\n * Under Apache License\n */\n#pragma once\n#include <Eigen/Dense>\n#include <initializer_list>\n#include <iostream>\n#include <type_traits>\n#include \"multidim_details.hpp\"\n\nnamespace multidim\n{\n\ttemplate <class T, class TS>\n\tclass MultiDimNView;\n\n\t/**\n\t * Base class of Multidimensional Static matrix of elements of type T\n\t *\n\t * TS is a sequence of types, where each type is (size,step)\n\t * \n\t */\n\ttemplate <class T, class TS>\n\tclass MultiDimNBase\n\t{\n\tpublic:\n\t\tusing value_t = T;\n\t\tstatic constexpr int Ncount = TS::size;\n\t\tstatic constexpr int Ntot = details::productseq<TS>::value;\n\t\tusing indexvector_t = Eigen::Matrix<int,Ncount,1>; // instead of std::vector<int>\n\n\t\ttemplate <int i>\n\t\tusing getsizetype = std::integral_constant<int,TS::template pick<i>::xsize>;\n\n\t\ttemplate <int i>\n\t\tusing getsteptype = std::integral_constant<int,TS::template pick<i>::xstep>;\n\n\t\ttemplate <int i>\n\t\tconstexpr int getssize() const { return details::saccessorseq<i,TS>::xsize; }\n\n\t\t/// can't move in base\n\t\ttemplate <int i>\n\t\tconstexpr int getsstep() const { return details::saccessorseq<i,TS>::xstep; }\n\n\t\tconstexpr int getsize(int i) const { return details::daccessorseq<TS>::type::size(i); }\n\n\t\tconstexpr int getstep(int i) const { return details::daccessorseq<TS>::type::step(i); }\n\n\t\tconstexpr int ndims() const { return Ncount; }\n\n\t\tconstexpr int numel() const { return Ntot; } \n\n\t\t/// compile type via pack: offsetvalue<1,2,3,4>::value\n\t\ttemplate<int... I>\n\t\tusing offsetvalue = typename details::offsetcompute<TS,I...>::type;\n\n\t\t/// returns offset from variadic via initializer list\n\t\ttemplate <class...X>\n\t\tconstexpr int offset(X... I) const \n\t\t{\t\n\t\t\tstatic_assert(sizeof...(I) == Ncount,\"wrong number of dimensions\");\n\t\t\treturn offset({I...});\n\t\t}\n\n\t\ttemplate <class dummy=void>\n\t\tauto squeeze() -> MultiDimNView<T, typename TS::template removeif<singletondim> >;\n\n\t\ttemplate <int...neworder>\n\t\tauto permutedim() -> MultiDimNView<T, typename TS::template permuted<neworder...> >;\n\n\t\t// TODO: let last dimension free to match\n\t\ttemplate <int...N>\n\t\tauto reshapeR() -> MultiDimNView<T, typename details::rowmajorstepper<N...> >;\n\n\t\ttemplate <int...N>\n\t\tauto reshapeC() -> MultiDimNView<T, typename details::colmajorstepper<N...> >;\n\n\t\t/// via initializer list (bit ugly...)\n\t\t/// we loop over i Ncount because is compile time length, while for(int x: L) IS NOT\n\t\tint offset(const std::initializer_list<int> & L) const \n\t\t{\t\n\t\t\tassert(L.size() == Ncount); //,\"wrong number of dims\");\n\t\t\tauto x = L.begin(); /// C++14 constexpr\n\t\t\tint o = 0;\n\t\t\tfor(int i = 0; i < Ncount; x++, i++)\n\t\t\t\to += *x *getstep(i);\n\t\t\treturn o;\n\t\t}\n\t};\n\n\t/**\n\t * View over a TS (typesequence of sizes)\n\t */\n\ttemplate <class T, class TS>\n\tclass MultiDimNView: public MultiDimNBase<T,TS>\n\t{\n\tpublic:\n\t\tusing base_t = MultiDimNBase<T,TS>;\n\t\tusing data_t = T*;\n\t\tusing map_t = Eigen::Map<Eigen::Matrix<T,base_t::Ntot,1> >;\n\n\t\tMultiDimNView(data_t x):  data_(x) \n\t\t{\n\t\t}\n\n\t\tconstexpr const T * data() const { return data_; }\n\n\t\tT * data() { return data_; }\n\n\t\tvoid setOnes()\n\t\t{\n\t\t\tmap_t(data_).setOnes();\t\n\t\t}\n\n\t\tvoid setZero()\n\t\t{\n\t\t\tmap_t(data_).setZero();\t\n\t\t}\n\n\t\t/// COMMON ACROSS MultiDimNView and MultiDimN\n\t\t/// TODO: replace with curiously recursive pattern\n\t\t/// limit by dimension\n\t\t/// FUTURE: variant with index compile time\n\t\ttemplate<int dim>\n\t \tauto limit1(int index) -> MultiDimNView<T, typename TS::template drop<dim> >\n\t\t{\n\t\t\treturn (data()+index*  MultiDimNBase<T,TS>::template getsteptype<dim>::value ); // via implicit construction\n\t\t}\n\n\t\t/// for the dimension dim takes from the given index1 up to newsize elements. This is not reducing the number of dimensions\n\t\t/// FUTURE: variant with index compile time\n\t\ttemplate<int dim, int newsize>\n\t\tauto limit1block(int index1) -> \n\t\t\tMultiDimNView<T, typename TS::template replacetype<dim,sspair<newsize,  MultiDimNBase<T,TS>::template getsteptype<dim>::value   > > >\n\t\t{\n\t\t\tstatic_assert(newsize <= MultiDimNBase<T,TS>::template getsizetype<dim>::value,\"sub-size cannot be larger than original\");\n\n\t\t\treturn data() + index1*MultiDimNBase<T,TS>::template getsteptype<dim>::value;\n\t\t}\n\t\ttemplate <int ...neworder>\n\t\tauto permutedim() -> MultiDimNView<T, typename TS::template permuted<neworder...> >\n\t\t{\n\t\t\tstatic_assert(sizeof...(neworder) == TS::size,\"permutation requires same order\");\n\t\t\treturn data();\n\t\t}\t\t\n\t\t\n\t\t// TODO: let last dimension free to match\n\t\ttemplate <int...N>\n\t\tauto reshapeR() -> MultiDimNView<T, typename details::rowmajorstepper<N...> >\n\t\t{\n\t\t\tusing RT = MultiDimNView<T, typename details::rowmajorstepper<N...> >;\n\n\t\t\tstatic_assert(RT::Ntot == MultiDimNBase<T,TS>::Ntot,\"result requires same number of elements\");\n\t\t\treturn data();\n\t\t}\t\t\n\n\t\ttemplate <int...N>\n\t\tauto reshapeC() -> MultiDimNView<T, typename details::colmajorstepper<N...> >\n\t\t{\n\t\t\tusing RT = MultiDimNView<T, typename details::colmajorstepper<N...> >;\n\n\t\t\tstatic_assert(RT::Ntot == MultiDimNBase<T,TS>::Ntot,\"result requires same number of elements\");\n\t\t\treturn data();\n\t\t}\t\t\t\n\n\t\tauto squeeze() -> MultiDimNView<T, typename TS::template removeif<singletondim> >\n\t\t{\n\t\t\treturn data();\n\t\t}\n\n\tprivate:\n\t\tdata_t data_;\n\t};\n\n\t// column wise\n\ttemplate <class T, class TS>\n\tclass MultiDimN: public MultiDimNBase<T,TS>\n\t{\n\tpublic:\n\t\tusing data_t = Eigen::Matrix<T,MultiDimNBase<T,TS>::Ntot,1>;\n\n\t\tMultiDimN()\n\t\t{\n\n\t\t}\n\n\t\tconst T * data() const { return data_.data(); }\n\n\t\tT * data() { return data_.data(); }\n\n\t\tvoid setOnes()\n\t\t{\n\t\t\tdata_.setOnes();\t\n\t\t}\n\n\t\tvoid setZero()\n\t\t{\n\t\t\tdata_.setZero();\t\n\t\t}\n\n\t\t/// COMMON ACROSS MultiDimNView and MultiDimN\n\t\t/// TODO: replace with curiously recursive pattern\n\t\ttemplate<int dim>\n\t\tauto limit1(int index) -> MultiDimNView<T, typename TS::template drop<dim> >\n\t\t{\n\t\t\treturn (data()+index*  MultiDimNBase<T,TS>::template getsteptype<dim>::value ); // via implicit construction\n\t\t}\n\n\t\t/// for the dimension dim takes from the given index1 up to newsize elements. This is not reducing the number of dimensions\n\t\t/// FUTURE: variant with index compile time\n\t\ttemplate<int dim, int newsize>\n\t\tauto limit1block(int index1) -> \n\t\t\tMultiDimNView<T, typename TS::template replacetype<dim,sspair<newsize,  MultiDimNBase<T,TS>::template getsteptype<dim>::value   > > >\n\t\t{\n\t\t\tstatic_assert(newsize <= MultiDimNBase<T,TS>::template getsizetype<dim>::value,\"sub-size cannot be larger than original\");\n\n\t\t\treturn data() + index1*MultiDimNBase<T,TS>::template getsteptype<dim>::value;\n\t\t}\n\n\t\ttemplate <int ...neworder>\n\t\tauto permutedim() -> MultiDimNView<T, typename TS::template permuted<neworder...> >\n\t\t{\n\t\t\tstatic_assert(sizeof...(neworder) == TS::size,\"permutation requires same order\");\n\t\t\treturn data();\n\t\t}\t\t\n\t\t\n\t\t// TODO: let last dimension free to match\n\t\ttemplate <int...N>\n\t\tauto reshapeR() -> MultiDimNView<T, typename details::rowmajorstepper<N...> >\n\t\t{\n\t\t\tusing RT = MultiDimNView<T, typename details::rowmajorstepper<N...> >;\n\n\t\t\tstatic_assert(RT::Ntot == MultiDimNBase<T,TS>::Ntot,\"result requires same number of elements\");\n\t\t\treturn data();\n\t\t}\t\t\n\n\t\ttemplate <int...N>\n\t\tauto reshapeC() -> MultiDimNView<T, typename details::colmajorstepper<N...> >\n\t\t{\n\t\t\tusing RT = MultiDimNView<T, typename details::colmajorstepper<N...> >;\n\n\t\t\tstatic_assert(RT::Ntot == MultiDimNBase<T,TS>::Ntot,\"result requires same number of elements\");\n\t\t\treturn data();\n\t\t}\t\t\t\n\n\t\tauto squeeze() -> MultiDimNView<T, typename TS::template removeif<singletondim> >\n\t\t{\n\t\t\treturn data();\n\t\t}\n\n\tprivate:\n\t\tdata_t data_;\n\t};\n\n\n\t/// declares a multidim with type T and given dimensions in row-major\n\ttemplate <class T, int...N>\n\tusing MultiDimNRow = MultiDimN<T, typename details::rowmajorstepper<N...> >;\n\n\t/// declares a multidim with type T and given dimensions in col-major\n\ttemplate <class T, int...N>\n\tusing MultiDimNCol = MultiDimN<T, typename details::colmajorstepper<N...> >;\n}", "meta": {"hexsha": "8fa6da48d5843d88ebe6ce461b1c4f9307b4d02a", "size": 8022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "multidim_static.hpp", "max_stars_repo_name": "eruffaldi/multidimcxx", "max_stars_repo_head_hexsha": "8e685b36a0e17e2aa99479cacf38fd486e30ff8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-07-21T07:43:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T20:49:04.000Z", "max_issues_repo_path": "multidim_static.hpp", "max_issues_repo_name": "eruffaldi/multidimcxx", "max_issues_repo_head_hexsha": "8e685b36a0e17e2aa99479cacf38fd486e30ff8a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multidim_static.hpp", "max_forks_repo_name": "eruffaldi/multidimcxx", "max_forks_repo_head_hexsha": "8e685b36a0e17e2aa99479cacf38fd486e30ff8a", "max_forks_repo_licenses": ["Apache-2.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.8215613383, "max_line_length": 136, "alphanum_fraction": 0.6797556719, "num_tokens": 2317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6060028283043735}}
{"text": "#include \"drake/common/trajectories/exponential_plus_piecewise_polynomial.h\"\n\n#include <cmath>\n#include <random>\n\n#include <Eigen/Core>\n#include <gtest/gtest.h>\n\n#include \"drake/common/trajectories/test/random_piecewise_polynomial.h\"\n\nusing std::default_random_engine;\nusing std::uniform_real_distribution;\n\nnamespace drake {\nnamespace trajectories {\n\nnamespace {\n\ntemplate <typename T>\nvoid testSimpleCase() {\n  int num_coefficients = 5;\n  int num_segments = 1;\n\n  MatrixX<T> K = MatrixX<T>::Random(1, 1);\n  MatrixX<T> A = MatrixX<T>::Random(1, 1);\n  MatrixX<T> alpha = MatrixX<T>::Random(1, 1);\n\n  default_random_engine generator;\n  auto segment_times =\n      PiecewiseTrajectory<double>::RandomSegmentTimes(num_segments, generator);\n  auto polynomial_part = test::MakeRandomPiecewisePolynomial<T>(\n      1, 1, num_coefficients, segment_times);\n\n  ExponentialPlusPiecewisePolynomial<T> expPlusPp(\n      K, A, alpha, polynomial_part);\n  ExponentialPlusPiecewisePolynomial<T> derivative =\n      expPlusPp.derivative();\n\n  uniform_real_distribution<T> uniform(expPlusPp.start_time(),\n                                                     expPlusPp.end_time());\n  double t = uniform(generator);\n  auto check =\n      K(0) * std::exp(A(0) * (t - expPlusPp.start_time())) * alpha(0) +\n      polynomial_part.scalarValue(t);\n  auto derivative_check =\n      K(0) * A(0) * std::exp(A(0) * (t - expPlusPp.start_time())) * alpha(0) +\n      polynomial_part.derivative().scalarValue(t);\n\n  EXPECT_NEAR(check, expPlusPp.value(t)(0), 1e-8);\n  EXPECT_NEAR(derivative_check, derivative.value(t)(0), 1e-8);\n}\n\nGTEST_TEST(testExponentialPlusPiecewisePolynomial, BasicTest) {\n  testSimpleCase<double>();\n}\n\n}  // namespace\n}  // namespace trajectories\n}  // namespace drake\n", "meta": {"hexsha": "a19834d79ee3caa5c968b01cba31b97b30a75292", "size": 1753, "ext": "cc", "lang": "C++", "max_stars_repo_path": "common/trajectories/test/exponential_plus_piecewise_polynomial_test.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "common/trajectories/test/exponential_plus_piecewise_polynomial_test.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common/trajectories/test/exponential_plus_piecewise_polynomial_test.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 29.2166666667, "max_line_length": 79, "alphanum_fraction": 0.7027952082, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.606002820803874}}
{"text": "#include \"catch.hpp\"\n\n#include \"libirc/wilson.h\"\n\n#include \"libirc/atom.h\"\n#include \"libirc/connectivity.h\"\n#include \"libirc/conversion.h\"\n#include \"libirc/io.h\"\n#include \"libirc/molecule.h\"\n\n#include \"config.h\"\n\n#include <cmath>\n\n#ifdef HAVE_ARMA\n#include <armadillo>\nusing vec3 = arma::vec3;\nusing vec = arma::vec;\nusing mat = arma::mat;\n#elif HAVE_EIGEN3\n#include <Eigen/Dense>\nusing vec3 = Eigen::Vector3d;\nusing vec = Eigen::VectorXd;\nusing mat = Eigen::MatrixXd;\n#else\n#error\n#endif\n\nusing namespace irc;\n\nTEST_CASE(\"Wilson B matrix for single fragments\", \"[wilson]\") {\n  using namespace connectivity;\n  using namespace molecule;\n  using namespace wilson;\n  using namespace tools;\n\n  SECTION(\"H2 stretching\") {\n    // Define molecule\n    Molecule<vec3> mol{{\"H\", {0., 0., 0.}}, {\"H\", {1., 0., 0.}}};\n\n    // Molecular connectivity\n    mat dd{distances<vec3, mat>(mol)};\n    UGraph adj{adjacency_matrix(dd, mol)};\n    mat dist{distance_matrix<mat>(adj)};\n\n    // Compute bonds\n    std::vector<Bond> B{bonds(dist, mol)};\n    REQUIRE(B.size() == 1);\n\n    // Compute Wilson B matrix for H2 analytically\n    mat Bwilson =\n        wilson_matrix<vec3, vec, mat>(to_cartesian<vec3, vec>(mol), B);\n\n    // Check Wilson B matrix size\n    INFO(\"Wilson B matrix (analytical):\\n\" << Bwilson);\n    REQUIRE(linalg::size(Bwilson) == 6);\n\n    // Compute Wilson B matrix for H2 numerically\n    mat BwilsonN = wilson_matrix_numerical<vec3, vec, mat>(\n        to_cartesian<vec3, vec>(mol), B);\n\n    // Check Wilson B matrix size\n    INFO(\"Wilson B matrix (numerical):\\n\" << BwilsonN);\n    REQUIRE(linalg::size(BwilsonN) == 6);\n\n    // Check analytical and numerical Wilson matrices are the same\n    INFO(\"Analytical vs Numerical\");\n    for (std::size_t i{0}; i < 6; i++)\n      REQUIRE(Bwilson(i) == Approx(BwilsonN(i)).margin(1e-6));\n\n    INFO(\"Transformation with bond stretch\");\n    const double d{0.01};\n    vec dx{-d, 0.00, 0.00, d, 0.00, 0.00};\n\n    INFO(\"Analytical transformation\");\n    vec analytical_transformation = Bwilson * dx;\n    CAPTURE(analytical_transformation);\n    REQUIRE(analytical_transformation(0) == Approx(2 * d).margin(1e-5));\n\n    INFO(\"Numerical transformation\");\n    vec numerical_transformation = BwilsonN * dx;\n    CAPTURE(numerical_transformation);\n    REQUIRE(numerical_transformation(0) == Approx(2 * d).margin(1e-5));\n  } // H2 stretching\n\n  SECTION(\"H2O bending\") {\n\n    double angle(0.5);\n    double angle_rad(angle / 180. * constants::pi);\n\n    const std::vector<mat> R{\n        {// Rotation for H1\n         {cos(angle_rad), -sin(angle_rad), 0},\n         {sin(angle_rad), cos(angle_rad), 0},\n         {0, 0, 1}},\n        {// Rotation for O\n         {1, 0, 0},\n         {0, 1, 0},\n         {0, 0, 1}},\n        {// Rotation for H2\n         {cos(-angle_rad), -sin(-angle_rad), 0},\n         {sin(-angle_rad), cos(-angle_rad), 0},\n         {0, 0, 1}},\n    };\n\n    const Molecule<vec3> mol{\n        {\"H\", {1.43, -1.10, 0.00}}, // H1\n        {\"O\", {0.00, 0.00, 0.00}},  // O\n        {\"H\", {-1.43, -1.10, 0.00}} // H2\n    };\n\n    // Allocate displacements in cartesian coordinates\n    vec dx{linalg::zeros<vec>(3 * mol.size())};\n\n    // Compute displacements\n    for (std::size_t i{0}; i < 3; i++) {\n      vec3 v{R[i] * mol[i].position - mol[i].position};\n\n      dx(3 * i + 0) = v(0);\n      dx(3 * i + 1) = v(1);\n      dx(3 * i + 2) = v(2);\n    }\n\n    // Molecular connectivity\n    mat dd{distances<vec3, mat>(mol)};\n    UGraph adj{adjacency_matrix(dd, mol)};\n    mat dist{distance_matrix<mat>(adj)};\n\n    // Compute bonds\n    const auto B = bonds(dist, mol);\n    REQUIRE(B.size() == 2);\n\n    // Compute angles\n    const auto A = angles(dist, mol);\n    REQUIRE(A.size() == 1);\n\n    // Compute Wilson B matrix for H2O analytically\n    mat Bwilson =\n        wilson_matrix<vec3, vec, mat>(to_cartesian<vec3, vec>(mol), B, A);\n    REQUIRE(linalg::size(Bwilson) == 27);\n    INFO(\"Wilson B matrix (analytical):\\n\" << Bwilson);\n\n    // Compute Wilson B matrix for H2O numerically\n    const mat BwilsonN = wilson_matrix_numerical<vec3, vec, mat>(\n        to_cartesian<vec3, vec>(mol), B, A);\n    REQUIRE(linalg::size(BwilsonN) == 27);\n    INFO(\"Wilson B matrix (numerical):\\n\" << BwilsonN);\n\n    // Check analytical and numerical Wilson matrices are the same\n    for (std::size_t i{0}; i < 27; i++)\n      REQUIRE(Bwilson(i) == Approx(BwilsonN(i)).margin(1e-6));\n\n    INFO(\"Compute displacements in internal coordinates\");\n    const vec displacement = Bwilson * dx;\n    CAPTURE(displacement);\n\n    INFO(\"Check bond change\");\n    REQUIRE(displacement(0) == Approx(0).margin(1e-4));\n    REQUIRE(displacement(1) == Approx(0).margin(1e-4));\n\n    INFO(\"Check angle change\");\n    REQUIRE(displacement(2) == Approx(2 * angle_rad).margin(1e-3));\n  }\n\n  SECTION(\"H2O2 torsion\") {\n\n    const double angle(1.0);\n    const double angle_rad(angle / 180. * constants::pi);\n\n    const mat R{{cos(angle_rad), -sin(angle_rad), 0},\n                {sin(angle_rad), cos(angle_rad), 0},\n                {0, 0, 1}};\n\n    molecule::Molecule<vec3> molecule{\n        {\"H\", {0.000, 0.947, -0.079}}, // H1\n        {\"O\", {0.000, 0.000, 0.000}},  // O1\n        {\"O\", {0.000, 0.000, 1.474}},  // O2\n        {\"H\", {-0.854, -0.407, 1.553}} // H2\n    };\n    molecule::multiply_positions(molecule, conversion::angstrom_to_bohr);\n\n    // Allocate displacements in cartesian coordinates\n    vec dx{linalg::zeros<vec>(3 * molecule.size())};\n\n    // Compute transformation for H1 rotation\n    vec3 v{R * molecule[0].position - molecule[0].position};\n    dx(0) = v(0);\n    dx(1) = v(1);\n    dx(2) = v(2);\n\n    // Compute old dihedral (before rotation)\n    double d_old{dihedral<vec3>(molecule[0].position,\n                                molecule[1].position,\n                                molecule[2].position,\n                                molecule[3].position)};\n\n    // Compute new dihedral angle (after rotation)\n    double d_new{dihedral<vec3>(R * molecule[0].position,\n                                molecule[1].position,\n                                molecule[2].position,\n                                molecule[3].position)};\n\n    // Compute dihedral variation\n    double d_diff{d_new - d_old};\n\n    // Compute interatomic distances\n    mat dd{distances<vec3, mat>(molecule)};\n    UGraph adj{adjacency_matrix(dd, molecule)};\n    mat dist{distance_matrix<mat>(adj)};\n\n    // Compute bonds, angles and dihedrals\n    const std::vector<Bond> B{bonds(dist, molecule)};\n    CHECK(B.size() == 3);\n    const std::vector<Angle> A{angles(dist, molecule)};\n    CHECK(A.size() == 2);\n    const std::vector<Dihedral> D{dihedrals(dist, molecule)};\n    CHECK(D.size() == 1);\n\n    // Compute Wilson's B matrix\n    const mat Bwilson = wilson_matrix<vec3, vec, mat>(\n        to_cartesian<vec3, vec>(molecule), B, A, D);\n    REQUIRE(linalg::size(Bwilson) == 72);\n    INFO(\"Wilson B matrix (analytical):\\n\" << Bwilson);\n\n    // Compute Wilson's B matrix\n    const mat BwilsonN = wilson_matrix_numerical<vec3, vec, mat>(\n        to_cartesian<vec3, vec>(molecule), B, A, D);\n    REQUIRE(linalg::size(BwilsonN) == 72);\n    INFO(\"Wilson B matrix (numerical):\\n\" << BwilsonN);\n\n    // Check analytical and numerical Wilson matrices are the same\n    INFO(\"Check Analytical vs Numerical Wilson B matrix\");\n    for (std::size_t i{0}; i < 72; i++) {\n      REQUIRE(Bwilson(i) == Approx(BwilsonN(i)).margin(1e-6));\n    }\n\n    SECTION(\"Analytical displacements\") {\n      // Compute displacement in internal coordinates\n      const vec displacement{Bwilson * dx};\n      INFO(\"Displacement (analytical):\\n\" << displacement);\n\n      INFO(\"Bonds do not change\");\n      REQUIRE(displacement(0) == Approx(0).margin(1e-3));\n      REQUIRE(displacement(1) == Approx(0).margin(1e-3));\n      REQUIRE(displacement(2) == Approx(0).margin(1e-3));\n\n      INFO(\"Angles do not change\");\n      REQUIRE(displacement(3) == Approx(0).margin(1e-4));\n      REQUIRE(displacement(4) == Approx(0).margin(1e-4));\n\n      INFO(\"Dihedral should change\");\n      REQUIRE(displacement(5) == Approx(d_diff).margin(1e-4));\n    }\n\n    SECTION(\"Numerical displacements\") {\n      // Compute displacement in internal coordinates\n      const vec displacement{BwilsonN * dx};\n      INFO(\"Displacement (numerical):\\n\" << displacement);\n\n      INFO(\"Bonds do not change\");\n      REQUIRE(displacement(0) == Approx(0).margin(1e-3));\n      REQUIRE(displacement(1) == Approx(0).margin(1e-3));\n      REQUIRE(displacement(2) == Approx(0).margin(1e-3));\n\n      INFO(\"Angles do not change\");\n      REQUIRE(displacement(3) == Approx(0).margin(1e-4));\n      REQUIRE(displacement(4) == Approx(0).margin(1e-4));\n\n      INFO(\"Dihedral should change\");\n      REQUIRE(displacement(5) == Approx(d_diff).margin(1e-4));\n    }\n  }\n}\n\nTEST_CASE(\"Wilson B matrix for formalydehyde\", \"[wilson]\") {\n  using namespace connectivity;\n  using namespace molecule;\n  using namespace tools;\n  using namespace wilson;\n  using namespace io;\n\n  const auto mol = load_xyz<vec3>(config::molecules_dir + \"formaldehyde.xyz\");\n\n  // Compute interatomic distances\n  mat dd{distances<vec3, mat>(mol)};\n  UGraph adj{adjacency_matrix(dd, mol)};\n  mat dist{distance_matrix<mat>(adj)};\n\n  // Compute bonds\n  std::vector<Bond> B{bonds(dist, mol)};\n  std::vector<Angle> A{angles(dist, mol)};\n  std::vector<Dihedral> D{dihedrals(dist, mol)};\n  std::vector<LinearAngle<vec3>> LA{linear_angles(dist, mol)};\n  std::vector<OutOfPlaneBend> OOPB{out_of_plane_bends(dist, mol)};\n\n  CHECK(OOPB.size() == 1);\n\n  const auto q = connectivity::cartesian_to_irc<vec3, vec>(\n      to_cartesian<vec3, vec>(mol), B, A, D, LA, OOPB);\n  CAPTURE(q);\n\n  const mat wilson_b_analytical = wilson_matrix<vec3, vec, mat>(\n      to_cartesian<vec3, vec>(mol), B, A, D, LA, OOPB);\n  CAPTURE(wilson_b_analytical);\n\n  const mat wilson_b_numerical = wilson_matrix_numerical<vec3, vec, mat>(\n      to_cartesian<vec3, vec>(mol), B, A, D, LA, OOPB);\n  CAPTURE(wilson_b_numerical);\n\n  REQUIRE(linalg::size(wilson_b_analytical) ==\n          linalg::size(wilson_b_numerical));\n\n  const std::size_t n = linalg::size(wilson_b_analytical);\n  for (std::size_t i{0}; i < n; i++) {\n    CAPTURE(i);\n    REQUIRE(wilson_b_analytical(i) ==\n            Approx(wilson_b_numerical(i)).margin(1e-5));\n  }\n}\n\nTEST_CASE(\"Wilson B matrix for bent out of plane bend\", \"[wilson]\") {\n  using namespace connectivity;\n  using namespace molecule;\n  using namespace tools;\n  using namespace wilson;\n  using namespace io;\n\n  molecule::Molecule<vec3> molecule{{\"C\", {0.200, 0.000, 2.800}},\n                                    {\"C\", {0.000, 0.000, 0.000}},\n                                    {\"C\", {0.000, 2.500, -0.500}},\n                                    {\"C\", {0.000, -2.500, -0.500}}};\n\n  // Compute interatomic distances\n  mat dd{distances<vec3, mat>(molecule)};\n  UGraph adj{adjacency_matrix(dd, molecule)};\n  mat dist{distance_matrix<mat>(adj)};\n\n  std::vector<OutOfPlaneBend> OOPB{out_of_plane_bends(dist, molecule)};\n  CHECK(OOPB.size() == 1);\n\n  const auto q = connectivity::cartesian_to_irc<vec3, vec>(\n      to_cartesian<vec3, vec>(molecule), {}, {}, {}, {}, OOPB);\n  CAPTURE(q);\n  CHECK(q.size() == 1);\n  CHECK(q(0) == Approx(-0.0713074648));\n\n  const mat wilson_b_analytical = wilson_matrix<vec3, vec, mat>(\n      to_cartesian<vec3, vec>(molecule), {}, {}, {}, {}, OOPB);\n  CAPTURE(wilson_b_analytical);\n\n  const mat wilson_b_numerical = wilson_matrix_numerical<vec3, vec, mat>(\n      to_cartesian<vec3, vec>(molecule), {}, {}, {}, {}, OOPB);\n  CAPTURE(wilson_b_numerical);\n\n  REQUIRE(linalg::size(wilson_b_analytical) ==\n          linalg::size(wilson_b_numerical));\n\n  const std::size_t n = linalg::size(wilson_b_analytical);\n  for (std::size_t i{0}; i < n; i++) {\n    CAPTURE(i);\n    REQUIRE(wilson_b_analytical(i) ==\n            Approx(wilson_b_numerical(i)).margin(1e-5));\n  }\n}\n\nTEST_CASE(\"Wilson B matrix for water dimer\", \"[wilson]\") {\n  using namespace connectivity;\n  using namespace molecule;\n  using namespace tools;\n  using namespace wilson;\n  using namespace io;\n\n  const auto mol = load_xyz<vec3>(config::molecules_dir + \"water_dimer_2.xyz\");\n\n  // Compute interatomic distances\n  mat dd{distances<vec3, mat>(mol)};\n  UGraph adj{adjacency_matrix(dd, mol)};\n  mat dist{distance_matrix<mat>(adj)};\n\n  // Compute bonds\n  std::vector<Bond> B{bonds(dist, mol)};\n  std::vector<Angle> A{angles(dist, mol)};\n  std::vector<Dihedral> D{dihedrals(dist, mol)};\n  std::vector<LinearAngle<vec3>> LA{linear_angles(dist, mol)};\n  std::vector<OutOfPlaneBend> OOPB{out_of_plane_bends(dist, mol)};\n\n  const auto q = connectivity::cartesian_to_irc<vec3, vec>(\n      to_cartesian<vec3, vec>(mol), B, A, D, LA, OOPB);\n  CAPTURE(q);\n\n  const mat wilson_b_analytical = wilson_matrix<vec3, vec, mat>(\n      to_cartesian<vec3, vec>(mol), B, A, D, LA, OOPB);\n  CAPTURE(wilson_b_analytical);\n\n  const mat wilson_b_numerical = wilson_matrix_numerical<vec3, vec, mat>(\n      to_cartesian<vec3, vec>(mol), B, A, D, LA, OOPB);\n  CAPTURE(wilson_b_numerical);\n\n  REQUIRE(linalg::size(wilson_b_analytical) ==\n          linalg::size(wilson_b_numerical));\n\n  const std::size_t n = linalg::size(wilson_b_analytical);\n  for (std::size_t i{0}; i < n; i++) {\n    REQUIRE(wilson_b_analytical(i) ==\n            Approx(wilson_b_numerical(i)).margin(1e-5));\n  }\n}\n\nTEST_CASE(\"Linear angle gradient\", \"[wilson]\") {\n  using namespace connectivity;\n  using namespace molecule;\n  using namespace tools;\n  using namespace wilson;\n  using namespace io;\n\n  Molecule<vec3> mol{\n      {\"H\", {0.7, 1.1, 2.4}}, {\"C\", {2.8, 1.2, 2.5}}, {\"N\", {4.9, 1.3, 2.6}}};\n  REQUIRE(mol.size() == 3);\n\n  // Compute interatomic distances\n  mat dd{distances<vec3, mat>(mol)};\n  UGraph adj{adjacency_matrix(dd, mol)};\n  mat dist{distance_matrix<mat>(adj)};\n\n  // Compute bonds\n  std::vector<Bond> B{bonds(dist, mol)};\n  std::vector<Angle> A{angles(dist, mol)};\n  std::vector<Dihedral> D{dihedrals(dist, mol)};\n  std::vector<LinearAngle<vec3>> LA{linear_angles(dist, mol)};\n  std::vector<OutOfPlaneBend> OOPB{out_of_plane_bends(dist, mol)};\n  REQUIRE(LA.size() == 2);\n\n  const auto q = connectivity::cartesian_to_irc<vec3, vec>(\n      to_cartesian<vec3, vec>(mol), B, A, D, LA, OOPB);\n  CAPTURE(q);\n\n  const mat wilson_b_analytical = wilson_matrix<vec3, vec, mat>(\n      to_cartesian<vec3, vec>(mol), B, A, D, LA, OOPB);\n  CAPTURE(wilson_b_analytical);\n\n  const mat wilson_b_numerical = wilson_matrix_numerical<vec3, vec, mat>(\n      to_cartesian<vec3, vec>(mol), B, A, D, LA, OOPB);\n  CAPTURE(wilson_b_numerical);\n\n  REQUIRE(linalg::size(wilson_b_analytical) ==\n          linalg::size(wilson_b_numerical));\n\n  const std::size_t n = linalg::size(wilson_b_analytical);\n  for (std::size_t i{0}; i < n; i++) {\n    REQUIRE(wilson_b_analytical(i) ==\n            Approx(wilson_b_numerical(i)).margin(1e-5));\n  }\n}", "meta": {"hexsha": "84649a90d69edf61b648dd9fcb302638ef9d39c5", "size": 14766, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/wilson_test.cpp", "max_stars_repo_name": "francesco-bosia/irc", "max_stars_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T16:12:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:20:23.000Z", "max_issues_repo_path": "src/test/wilson_test.cpp", "max_issues_repo_name": "francesco-bosia/irc", "max_issues_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2018-01-11T13:21:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T19:59:39.000Z", "max_forks_repo_path": "src/test/wilson_test.cpp", "max_forks_repo_name": "francesco-bosia/irc", "max_forks_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-04-11T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T10:00:16.000Z", "avg_line_length": 32.5960264901, "max_line_length": 79, "alphanum_fraction": 0.6265745632, "num_tokens": 4551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.6060008135536361}}
{"text": "#include \"utils.hpp\"\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/integer.hpp>\n#include <memory>\nusing namespace std;\nusing Bint = boost::multiprecision::cpp_int;\n\nBint f(Bint const& x, Bint const& c, Bint const& n);\n\n\nclass LinkedList{\n    public:\n        LinkedList(Bint value_);\n        ~LinkedList();\n        Bint getValue();\n        LinkedList* getAfter();\n        void setAfter(LinkedList* after_);\n    private:\n        Bint value;\n        LinkedList* after;\n};\n\nLinkedList::LinkedList(Bint value_){\n    value = value_;\n    after = nullptr;\n}\n\nLinkedList::~LinkedList(){\n    ;\n}\n\nBint LinkedList::getValue(){\n    return value;\n}\n\nLinkedList* LinkedList::getAfter(){\n    return after;\n}\n\nvoid LinkedList::setAfter(LinkedList* after_){\n    after = after_;\n}\n\n\n\nstring PollardsRhoFactorizer_cppfunc(string s, long c_){\n    Bint n(s);\n    Bint c(c_);\n    LinkedList* x = new LinkedList(Bint(2));\n    LinkedList* y = new LinkedList(f(x->getValue(), c, n));\n    x->setAfter(y);\n    Bint d = gcd(abs(x->getValue()-y->getValue()), n);\n    while(d==1){\n        LinkedList* z1 = new LinkedList(f(y->getValue(), c, n));\n        LinkedList* z2 = new LinkedList(f(z1->getValue(), c, n));\n        y->setAfter(z1);\n        z1->setAfter(z2);\n        y = z2;\n\n        LinkedList* tmp;\n        tmp = x;\n        x = x->getAfter();\n        delete tmp;\n        d = gcd(abs(x->getValue()-y->getValue()), n);\n    }\n\n\n    if(d<n){\n        return d.str();\n    }\n    else{\n        return \"1\";\n    }\n}\n\nBint f(Bint const& x, Bint const& c, Bint const& n){\n    return (x*x+c)%n;\n}\n", "meta": {"hexsha": "7e467b004f517adc8459d9a35764c38caa800e2a", "size": 1590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PollardsRhoFactorizer_cpp.cpp", "max_stars_repo_name": "FullteaR/factorizer", "max_stars_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PollardsRhoFactorizer_cpp.cpp", "max_issues_repo_name": "FullteaR/factorizer", "max_issues_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PollardsRhoFactorizer_cpp.cpp", "max_forks_repo_name": "FullteaR/factorizer", "max_forks_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.875, "max_line_length": 65, "alphanum_fraction": 0.5830188679, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.6060008048230873}}
{"text": "// die.cpp\n//\n// Copyright (c) 2009\n// Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[die\n/*`\n    For the source of this example see\n    [@boost://libs/random/example/die.cpp die.cpp].\n    First we include the headers we need for __mt19937\n    and __uniform_int.\n*/\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/variate_generator.hpp>\n\n/*`\n  We use __mt19937 with the default seed as a source of\n  randomness.  The numbers produced will be the same\n  every time the program is run.  One common method to\n  change this is to seed with the current time (`std::time(0)`\n  defined in ctime).\n*/\nboost::mt19937 gen;\n/*`\n  [note We are using a /global/ generator object here.  This\n  is important because we don't want to create a new [prng\n  pseudo-random number generator] at every call]\n*/\n/*`\n  Now we can define a function that simulates an ordinary\n  six-sided die.\n*/\nint roll_die() {\n    /*<< __mt19937 produces integers in the range [0, 2[sup 32]-1].\n        However, we want numbers in the range [1, 6].  The distribution\n        __uniform_int performs this transformation.\n        [warning Contrary to common C++ usage __uniform_int\n        does not take a /half-open range/.  Instead it takes a /closed range/.\n        Given the parameters 1 and 6, __uniform_int can\n        can produce any of the values 1, 2, 3, 4, 5, or 6.]\n    >>*/\n    boost::uniform_int<> dist(1, 6);\n    /*<< __variate_generator combines a generator with a distribution.\n        [important We pass [classref boost::mt19937 boost::mt19937&] to\n        __variate_generator instead of just [classref boost::mt19937]\n        (note the reference).  Without the reference, __variate_generator\n        would make a copy of the generator and would leave the global\n        `gen` unchanged.  Consequently, `roll_die` would produce *the same value*\n        every time it was called.]\n    >>*/\n    boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(gen, dist);\n    /*<< A __variate_generator is a function object. >>*/\n    return die();\n}\n//]\n\n#include <iostream>\n\nint main() {\n    for(int i = 0; i < 10; ++i) {\n        std::cout << roll_die() << std::endl;\n    }\n}\n", "meta": {"hexsha": "1df89d3d08146e6ba331b3ce75c4ca33af6c7a9c", "size": 2346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/example/die.cpp", "max_stars_repo_name": "tizenorg/external.boost", "max_stars_repo_head_hexsha": "661689c2058551ef4644aa48a24612d5a4bd41a7", "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/random/example/die.cpp", "max_issues_repo_name": "ksundberg/boost-svn", "max_issues_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "max_issues_repo_licenses": ["BSL-1.0"], "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/random/example/die.cpp", "max_forks_repo_name": "ksundberg/boost-svn", "max_forks_repo_head_hexsha": "5694e7831f7afc8f6e25d03d0fd375e7be758d0f", "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": 34.0, "max_line_length": 84, "alphanum_fraction": 0.6760443308, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6059823190811338}}
{"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union\u2019s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n// http://csclab.murraystate.edu/~bob.pilgrim/445/munkres.html\n\n#pragma once\n\n#include \"AlgorithmUtils.hpp\"\n#include \"FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include <Eigen/Core>\n#include <cassert>\n#include <cmath>\n\nnamespace fluid {\nnamespace algorithm {\n\nclass Munkres\n{\npublic:\n  using intPair = std::pair<int, int>;\n  void init(index rows, index cols)\n  {\n    using namespace Eigen;\n    index N = std::max(rows, cols);\n    mCost = ArrayXXd::Zero(N, N);\n    mRowMin = ArrayXd::Zero(N);\n    mColMin = ArrayXd::Zero(N);\n    mMask = ArrayXXi::Zero(N, N);\n    mRowCover = ArrayXi::Zero(N);\n    mColCover = ArrayXi::Zero(N);\n    mPath = ArrayXXi::Zero(2 * N + 1, 2);\n  }\n\n  void reset()\n  {\n    mCost.setZero();\n    mRowMin.setZero();\n    mColMin.setZero();\n    mMask.setZero();\n    mRowCover.setZero();\n    mColCover.setZero();\n    mPath.setZero();\n  }\n\n  void process(Eigen::Ref<const Eigen::ArrayXXd> costMatrix,\n               Eigen::Ref<Eigen::ArrayXi>        result)\n  {\n    bool done;\n    reset();\n    double maxCost = costMatrix.maxCoeff();\n    mCost = Eigen::ArrayXXd::Ones(mCost.rows(), mCost.cols());\n    mCost = mCost * (10.0 * maxCost);\n    mCost.block(0, 0, costMatrix.rows(), costMatrix.cols()) = costMatrix;\n    step1();\n    step2();\n    done = step3();\n    while (!done)\n    {\n      intPair Z = step4();\n      while (Z.first < 0)\n      {\n        step6();\n        Z = step4();\n      }\n      step5(Z);\n      done = step3();\n    }\n    for (int i = 0; i < result.size(); i++)\n    { mMask.row(i).maxCoeff(&result(i)); }\n  }\n\n  void step1()\n  {\n    mRowMin = mCost.rowwise().minCoeff();\n    mColMin = (mCost.colwise() - mRowMin).colwise().minCoeff();\n    for (int i = 0; i < mCost.rows(); i++)\n    {\n      double min = mCost.row(i).minCoeff();\n      mCost.row(i) -= min;\n    }\n  }\n\n  void step2()\n  {\n    for (int i = 0; i < mCost.rows(); i++)\n    {\n      for (int j = 0; j < mCost.cols(); j++)\n      {\n        if (mCost(i, j) == 0 && mRowCover(i) == 0 && mColCover(j) == 0)\n        {\n          mMask(i, j) = 1;\n          mRowCover(i) = 1;\n          mColCover(j) = 1;\n        }\n      }\n    }\n    mRowCover.setZero();\n    mColCover.setZero();\n  }\n\n  bool step3()\n  {\n    for (int i = 0; i < mMask.rows(); i++)\n    {\n      for (int j = 0; j < mMask.cols(); j++)\n      {\n        if (mMask(i, j) == 1) { mColCover(j) = 1; }\n      }\n    }\n    Eigen::Index nCovered = (mColCover == 1).count();\n    return nCovered >= mMask.rows() || nCovered >= mMask.cols();\n  }\n\n  intPair step4()\n  {\n    int     row = -1, col = -1;\n    intPair result = std::make_pair(row, col);\n    while (true)\n    {\n      intPair pos = findZero();\n      row = pos.first;\n      col = pos.second;\n      if (row < 0) { break; }\n      mMask(row, col) = 2;\n      Eigen::ArrayXi r = mMask.row(row);\n      int            colStar = findValue(r, 1);\n      if (colStar >= 0)\n      {\n        col = colStar;\n        mRowCover(row) = 1;\n        mColCover(col) = 0;\n      }\n      else\n      {\n        result = std::make_pair(row, col);\n        break;\n      }\n    }\n    return result;\n  }\n\n\n  void step5(const intPair Z)\n  {\n    int row = -1, col = -1;\n    int pathCount = 0;\n    mPath(pathCount, 0) = Z.first;\n    mPath(pathCount, 1) = Z.second;\n    while (true)\n    {\n      int            tmp = mPath(pathCount, 1);\n      Eigen::ArrayXi tmpCol = mMask.col(tmp);\n      row = findValue(tmpCol, 1);\n      if (row == -1) break;\n      pathCount++;\n      mPath(pathCount, 0) = row;\n      mPath(pathCount, 1) = mPath(pathCount - 1, 1);\n      Eigen::ArrayXi r = mMask.row(mPath(pathCount, 0));\n      col = findValue(r, 2);\n      pathCount++;\n      mPath(pathCount, 0) = mPath(pathCount - 1, 0);\n      mPath(pathCount, 1) = col;\n    }\n    augmentPath(pathCount);\n    mRowCover.setZero();\n    mColCover.setZero();\n    erasePrimes();\n  }\n\n  void step6()\n  {\n    double m = minCost();\n    for (int i = 0; i < mCost.rows(); i++)\n    {\n      for (int j = 0; j < mCost.cols(); j++)\n      {\n        if (mRowCover(i) == 1) mCost(i, j) += m;\n        if (mColCover(j) == 0) mCost(i, j) -= m;\n      }\n    }\n  }\n\n  double minCost()\n  {\n    double minVal = std::numeric_limits<double>::max();\n    for (int i = 0; i < mCost.rows(); i++)\n    {\n      for (int j = 0; j < mCost.cols(); j++)\n      {\n        if (mRowCover(i) == 0 && mColCover(j) == 0)\n        {\n          double v = mCost(i, j);\n          minVal = (minVal > v) ? v : minVal;\n        }\n      }\n    }\n    return minVal;\n  }\n\n  void erasePrimes()\n  {\n    for (int i = 0; i < mMask.rows(); i++)\n    {\n      for (int j = 0; j < mMask.cols(); j++)\n      {\n        if (mMask(i, j) == 2) { mMask(i, j) = 0; }\n      }\n    }\n  }\n\n  intPair findZero()\n  {\n    for (int i = 0; i < mCost.rows(); i++)\n      for (int j = 0; j < mCost.cols(); j++)\n      {\n        if (mCost(i, j) == 0 && mRowCover(i) == 0 && mColCover(j) == 0)\n          return std::make_pair(i, j);\n      }\n    return std::make_pair(-1, -1);\n  }\n\n  int findValue(Eigen::Ref<const Eigen::ArrayXi> vector, const int val)\n  {\n    for (int i = 0; i < vector.size(); i++)\n    {\n      if (vector(i) == val) return i;\n    }\n    return -1;\n  }\n\n  void augmentPath(const int count)\n  {\n    for (int i = 0; i < count + 1; i++)\n    {\n      int c = mPath(i, 0), r = mPath(i, 1);\n      mMask(c, r) = mMask(c, r) == 1 ? 0 : 1;\n    }\n  }\n\nprivate:\n  Eigen::ArrayXXd mCost;\n  Eigen::ArrayXd  mRowMin;\n  Eigen::ArrayXd  mColMin;\n  Eigen::ArrayXXi mMask;\n  Eigen::ArrayXXi mPath;\n  Eigen::ArrayXi  mRowCover;\n  Eigen::ArrayXi  mColCover;\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "94ad81dc9d7d32c98530a88196924c0b02cd6048", "size": 5954, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/Munkres.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/util/Munkres.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/util/Munkres.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": 23.0775193798, "max_line_length": 74, "alphanum_fraction": 0.526536782, "num_tokens": 1915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6058994268636307}}
{"text": "#include <boost/numeric/odeint.hpp>\n\ntypedef std::vector< double > state_type;\n\nconst double gam = 0.15;\n\nvoid harmonic_oscillator( const state_type &x , state_type &dxdt , const double /* t */ )\n{\n    dxdt[0] = x[1];\n    dxdt[1] = -x[0] - gam*x[1];\n}\n\nint main()\n{\n  state_type x(2);\n  x[0] = 1.0; // start at x=1.0, p=0.0\n  x[1] = 0.0;  \n\n  using namespace boost::numeric::odeint;\n  size_t steps = integrate( harmonic_oscillator, x, 0.0, 10.0, 0.1 );\n  if(steps == 0)\n    return 1;\n\n  return 0;\n}\n", "meta": {"hexsha": "8744f6aa58e7ec7e04e3dfe3e68944ce70613ed6", "size": 499, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/numeric_odeint_test.cc", "max_stars_repo_name": "cirrostratus1/rules_boost", "max_stars_repo_head_hexsha": "8a084196b14a396b6d4ff7c928ffbb6621f0d32c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 214.0, "max_stars_repo_stars_event_min_datetime": "2016-08-24T01:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T02:24:55.000Z", "max_issues_repo_path": "test/numeric_odeint_test.cc", "max_issues_repo_name": "cirrostratus1/rules_boost", "max_issues_repo_head_hexsha": "8a084196b14a396b6d4ff7c928ffbb6621f0d32c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 184.0, "max_issues_repo_issues_event_min_datetime": "2017-01-20T22:43:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T16:26:45.000Z", "max_forks_repo_path": "test/numeric_odeint_test.cc", "max_forks_repo_name": "cirrostratus1/rules_boost", "max_forks_repo_head_hexsha": "8a084196b14a396b6d4ff7c928ffbb6621f0d32c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 258.0, "max_forks_repo_forks_event_min_datetime": "2016-08-24T01:08:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T18:07:16.000Z", "avg_line_length": 19.1923076923, "max_line_length": 89, "alphanum_fraction": 0.6052104208, "num_tokens": 190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6058994268636307}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <ros/ros.h>\n#include <tf2_ros/transform_listener.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n#include <nav_msgs/Odometry.h>\n#include <geometry_msgs/TransformStamped.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Pose.h>\n#include <geometry_msgs/Twist.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n//#include <boost/bind.hpp>\n\n\ntf2_ros::Buffer tfBuffer;\nros::Publisher pub;\n\nbool reset_odom = false;\nbool first_pose = true; \nEigen::Matrix4d first_pose_inv;\n\n\nvoid inverse(Eigen::Matrix4d& in, Eigen::Matrix4d& out) \n{\n\t// set result matrix to identity matrix\n\tout.setIdentity();\n\t// get rotation matrix\n\tEigen::Matrix3d rot;\n\trot = in.block(0, 0, 3, 3);\n\t// inverse rotation matrix\n\tEigen::Matrix3d rot_inverse;\n\trot_inverse = rot.transpose();\n\t// set inversed rotation matrix\n\tout.block(0, 0, 3, 3) = rot_inverse;\n\n\t// get translation\n\tEigen::Vector3d t;\n\tt = in.block(0, 3, 3, 1);\n\t// inverse translation\n\tEigen::Vector3d t_inv;\n\tt_inv = -1 * rot.transpose() * t;\n\t// set inversed translation\n\tout.block(0, 3, 3, 1) = t_inv;\n}\n\n\nvoid transform_to_matrix(const geometry_msgs::TransformStamped& transformStamped, Eigen::Matrix4d& matrix) \n{\n\tmatrix.setIdentity();\n\n\tEigen::Vector3d t;\n\tt.x() = transformStamped.transform.translation.x;\n\tt.y() = transformStamped.transform.translation.y;\n\tt.z() = transformStamped.transform.translation.z;\n\n\tEigen::Quaterniond q;\n\tq.x() = transformStamped.transform.rotation.x;\n\tq.y() = transformStamped.transform.rotation.y;\n\tq.z() = transformStamped.transform.rotation.z;\n\tq.w() = transformStamped.transform.rotation.w;\n\n\tmatrix.block(0,0,3,3) = q.normalized().toRotationMatrix();\n\tmatrix.block(0,3,3,1) = t;\n}\n\n\nvoid pose_to_matrix(const geometry_msgs::Pose& pose, Eigen::Matrix4d& matrix) \n{\n\tmatrix.setIdentity();\n\n\tEigen::Vector3d t;\n\tt.x() = pose.position.x;\n\tt.y() = pose.position.y;\n\tt.z() = pose.position.z;\n\n\tEigen::Quaterniond q;\n\tq.x() = pose.orientation.x;\n\tq.y() = pose.orientation.y;\n\tq.z() = pose.orientation.z;\n\tq.w() = pose.orientation.w;\n\n\tmatrix.block(0,0,3,3) = q.normalized().toRotationMatrix();\n\tmatrix.block(0,3,3,1) = t;\n}\n\n\nvoid matrix_to_pose(const Eigen::Matrix4d& matrix, geometry_msgs::Pose& pose) \n{\n\tpose.position.x = matrix(0, 3);\n\tpose.position.y = matrix(1, 3);\n\tpose.position.z = matrix(2, 3);\n\n\tEigen::Matrix3d rot;\n\trot = matrix.block(0, 0, 3, 3);\n\tEigen::Quaterniond q(rot);\n\n\tpose.orientation.x = q.x();\n\tpose.orientation.y = q.y();\n\tpose.orientation.z = q.z();\n\tpose.orientation.w = q.w();\n}\n\n\nvoid transfrom_to_twist_matrix(const Eigen::Matrix4d& transfrom_matrix_inv, Eigen::MatrixXd& matrix) \n{\n\tmatrix.setIdentity();\n\n\tEigen::Vector3d t;\n\tt = transfrom_matrix_inv.block(0, 3, 3, 1);\n\n\tEigen::Matrix3d t_hat;\n\tt_hat << 0, -t(2), t(1),\n\t\t\t t(2), 0, -t(0),\n    \t\t-t(1), t(0), 0;\n\n\n\tEigen::Matrix3d rot;\n\trot = transfrom_matrix_inv.block(0, 0, 3, 3);\n\n\tmatrix.block(0,0,3,3) = rot;\n\tmatrix.block(3,3,3,3) = rot;\n\tmatrix.block(0,3,3,3) = t_hat * rot;\n}\n\n\nvoid twist_to_vector(const geometry_msgs::Twist& twist, Eigen::VectorXd& twist_vector) \n{\n\ttwist_vector(0) = twist.linear.x;\n\ttwist_vector(1) = twist.linear.y;\n\ttwist_vector(2) = twist.linear.z;\n\n\ttwist_vector(3) = twist.angular.x;\n\ttwist_vector(4) = twist.angular.y;\n\ttwist_vector(5) = twist.angular.z;\n}\n\n\nvoid vector_to_twist(const Eigen::VectorXd& twist_vector, geometry_msgs::Twist& twist) \n{\n\ttwist.linear.x = twist_vector(0);\n\ttwist.linear.y = twist_vector(1);\n\ttwist.linear.z = twist_vector(2);\n\n\ttwist.angular.x = twist_vector(3);\n\ttwist.angular.y = twist_vector(4);\n\ttwist.angular.z = twist_vector(5);\n}\n\n\nvoid odomCallback(const nav_msgs::Odometry& msg) \n{\n\tnav_msgs::Odometry msg_result;\n\n\tstd::string from_frame, to_frame;\n\tros::param::get(\"~from_frame\", from_frame);\n\tros::param::get(\"~to_frame\", to_frame);\n\n\tgeometry_msgs::TransformStamped transformStamped;\n\ttry\n \t{\n    \ttransformStamped = tfBuffer.lookupTransform(from_frame, to_frame, ros::Time(0));\n\n    \t// convert transform to matrix \n    \tEigen::Matrix4d transfrom_matrix;\n    \ttransform_to_matrix(transformStamped, transfrom_matrix);\n    \t// get inverse transform matrix\n    \tEigen::Matrix4d transfrom_matrix_inv;\n    \tinverse(transfrom_matrix, transfrom_matrix_inv);\n\n    \t// --------------------- pose transform --------------------- \n    \t// convert pose to matrix\n    \tEigen::Matrix4d pose_matrix;\n    \tpose_to_matrix(msg.pose.pose, pose_matrix);\n\n    \t// apply transfrom on pose\n    \tEigen::Matrix4d pose_matrix_result;\n    \tpose_matrix_result = transfrom_matrix_inv * pose_matrix * transfrom_matrix;\n\n    \t// reset odom if needed\n    \tif (reset_odom) {\n    \t\tif (first_pose) {\n    \t\t\tinverse(pose_matrix_result, first_pose_inv);\n    \t\t\tfirst_pose = false;\n    \t\t}\n    \t\tpose_matrix_result = first_pose_inv * pose_matrix_result;\n    \t}\n\n    \tmatrix_to_pose(pose_matrix_result, msg_result.pose.pose);\n\n    \t// --------------------- twist transform ---------------------\n    \t// convert transform to twist_transfrom\n    \tEigen::MatrixXd twist_transfrom(6, 6);\n    \ttransfrom_to_twist_matrix(transfrom_matrix_inv, twist_transfrom);\n\n    \t// convert twist to vector\n    \tEigen::VectorXd twist_vector(6);\n    \ttwist_to_vector(msg.twist.twist, twist_vector);\n\n    \t// apply transfrom on twist\n    \tEigen::VectorXd twist_vector_result(6);\n    \ttwist_vector_result = twist_transfrom * twist_vector;\n    \tvector_to_twist(twist_vector_result, msg_result.twist.twist);\n\n    \t// --------------------- header replacement ---------------------\n    \t// copy header\n    \tmsg_result.header = msg.header;\n    \tmsg_result.header.frame_id = \"odom\";\n    \tmsg_result.child_frame_id = to_frame;\n\n        // write pose noise covariance if needed\n        if(ros::param::has(\"~covariance\")) \n        {\n            std::vector<double> covariance;\n            ros::param::get(\"~covariance\", covariance);\n            for (int i = 0; i < 36 && i < covariance.size(); ++i) msg_result.pose.covariance[i] = covariance[i];\n        } \n    \telse \n    \t{\n    \t\tfor (int i = 0; i < 36; ++i) msg_result.pose.covariance[i] = msg.pose.covariance[i];\n    \t}\n    \t// publish odometry\n    \tpub.publish(msg_result);\n \t}\n \tcatch (tf2::TransformException &ex) \n \t{\n   \t\tROS_WARN(\"%s\",ex.what());\n \t}\n}\n\n\nint main(int argc, char **argv) \n{\n\tros::init(argc, argv, \"odometry_transformer\");\n\tros::NodeHandle node;\n\n\tstd::string in_topic, out_topic;\n\tros::param::get(\"~in_topic\", in_topic);\n\tros::param::get(\"~out_topic\", out_topic);\n    ros::param::get(\"~reset_odom\", reset_odom);\n\n\ttf2_ros::TransformListener tfListener(tfBuffer);\n\n \tpub = node.advertise<nav_msgs::Odometry>(out_topic, 10);\n \tros::Subscriber sub = node.subscribe(in_topic, 10, odomCallback);\n\n \tros::spin();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "580978430a4778ab5aade499275bc6ae28d07ec8", "size": 6727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "odometry/odometry_fusion/tf_transformer/src/odometry_transformer.cpp", "max_stars_repo_name": "cds-mipt/strl_robotics", "max_stars_repo_head_hexsha": "02c9ebb3000f3028e3b659aa428f60d7947b10b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-29T17:14:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T14:18:12.000Z", "max_issues_repo_path": "odometry/odometry_fusion/tf_transformer/src/odometry_transformer.cpp", "max_issues_repo_name": "cds-mipt/strl_robotics", "max_issues_repo_head_hexsha": "02c9ebb3000f3028e3b659aa428f60d7947b10b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "odometry/odometry_fusion/tf_transformer/src/odometry_transformer.cpp", "max_forks_repo_name": "cds-mipt/strl_robotics", "max_forks_repo_head_hexsha": "02c9ebb3000f3028e3b659aa428f60d7947b10b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T17:48:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:17:40.000Z", "avg_line_length": 26.4842519685, "max_line_length": 112, "alphanum_fraction": 0.6762301174, "num_tokens": 1892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6058994260467907}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <boost/numeric/odeint.hpp>\n#include <smooth/compat/odeint.hpp>\n#include <smooth/feedback/mpc.hpp>\n\n#include <chrono>\n\n#ifdef ENABLE_PLOTTING\n#include <matplot/matplot.h>\n#endif\n\nusing namespace std::chrono_literals;\nusing namespace boost::numeric::odeint;\n\nusing Time = std::chrono::duration<double>;\n\ntemplate<typename T>\nusing G = Eigen::Vector2<T>;\ntemplate<typename T>\nusing U = Eigen::Matrix<T, 1, 1>;\n\nusing Gd = G<double>;\nusing Ud = U<double>;\n\nint main()\n{\n  using std::sin;\n  std::srand(5);\n\n  // system variables\n  Gd g = Gd::Random();\n  Ud u;\n\n  // dynamics\n  auto f = []<typename T>(Time, const G<T> & x, const U<T> u) -> smooth::Tangent<G<T>> {\n    return {x(1), u(0)};\n  };\n\n  // parameters\n  smooth::feedback::MPCParams<Gd, Ud> prm{\n    .T = 5,\n    .K = 20,\n    .weights =\n      {\n        .Q  = Eigen::Matrix2d::Identity(),\n        .QT = 0.1 * Eigen::Matrix2d::Identity(),\n        .R  = Eigen::Matrix<double, 1, 1>::Constant(0.1),\n      },\n    .ulim =\n      smooth::feedback::ManifoldBounds<Ud>{\n        .A = Eigen::Matrix<double, 1, 1>(1),\n        .c = Ud::Zero(),\n        .l = Eigen::Matrix<double, 1, 1>(-0.5),\n        .u = Eigen::Matrix<double, 1, 1>(0.5),\n      },\n  };\n\n  // create MPC object and set input bounds, and desired trajectories\n  smooth::feedback::MPC<Time, Gd, Ud, decltype(f)> mpc(f, prm);\n  mpc.set_xdes([]<typename T>(T t) -> G<T> { return G<T>{-0.5 * sin(0.3 * t), 0}; });\n  mpc.set_udes([]<typename T>(T) -> U<T> { return U<T>::Zero(); });\n\n  // prepare for integrating the closed-loop system\n  runge_kutta4<Gd, double, smooth::Tangent<Gd>, double, vector_space_algebra> stepper{};\n  const auto ode = [&f, &u](const Gd & x, smooth::Tangent<Gd> & d, double t) -> void {\n    d = f(Time(t), x, u);\n  };\n  std::vector<double> tvec, xvec, vvec, uvec;\n\n  // integrate closed-loop system\n  for (std::chrono::milliseconds t = 0s; t < 60s; t += 50ms) {\n    // compute MPC input\n    auto [u_mpc, code] = mpc(t, g);\n    u                  = u_mpc;\n    if (code != smooth::feedback::QPSolutionStatus::Optimal) {\n      std::cerr << \"Solver failed with code \" << static_cast<int>(code) << std::endl;\n    }\n\n    // store data\n    tvec.push_back(duration_cast<Time>(t).count());\n    xvec.push_back(g.x());\n    vvec.push_back(g.y());\n    uvec.push_back(u(0));\n\n    // step dynamics\n    stepper.do_step(ode, g, 0, 0.05);\n  }\n\n#ifdef ENABLE_PLOTTING\n  matplot::figure();\n  matplot::hold(matplot::on);\n\n  matplot::plot(tvec, xvec)->line_width(2);\n  matplot::plot(tvec, matplot::transform(tvec, [](auto t) { return -0.5 * sin(0.3 * t); }), \"k--\")\n    ->line_width(2);\n  matplot::plot(tvec, vvec)->line_width(2);\n  matplot::plot(tvec, uvec)->line_width(2);\n  matplot::legend({\"x\", \"x_{des}\", \"v\", \"u\"});\n\n  matplot::show();\n#else\n  std::cout << \"TRAJECTORY:\" << std::endl;\n  for (auto i = 0u; i != tvec.size(); ++i) {\n    std::cout << \"t=\" << tvec[i] << \": x=\" << xvec[i] << \", v=\" << vvec[i] << std::endl;\n  }\n#endif\n}\n", "meta": {"hexsha": "646242a77425ab155a4afb40a482831445356ec4", "size": 4232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mpc_doubleintegrator.cpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "examples/mpc_doubleintegrator.cpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "examples/mpc_doubleintegrator.cpp", "max_forks_repo_name": "pettni/smooth_feedback", "max_forks_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 32.0606060606, "max_line_length": 98, "alphanum_fraction": 0.6361058601, "num_tokens": 1256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.870597271765821, "lm_q2_score": 0.695958331339634, "lm_q1q2_score": 0.6058994245269786}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      Montebruck O, Gill E. Satellite Orbits, Corrected Third Printing, Springer, 2005.\n *      Bate R. Fundamentals of Astrodynamics, Courier Dover Publications, 1971.\n *      Wikipedia, Sphere of Influence, accesed 121018.\n *        http://en.wikipedia.org/wiki/Sphere_of_influence_(astrodynamics)\n *      Petit et al., IERS Conventions, IERS, 2010.\n *\n */\n\n#define BOOST_TEST_MAIN\n\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/unit_test.hpp>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/missionGeometry.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n//! Show the functionality of the unit tests.\nBOOST_AUTO_TEST_SUITE( test_Mission_Geometry )\n\n//! Unit test for shadow function (Sun,Earth).\nBOOST_AUTO_TEST_CASE( testShadowFunctionForFullShadow )\n{\n    // Satellite totally blocked from solar radiation by the earth. Sun and satellite located on the\n    // x-axis with the Earth in between. Altitude of satellite = 1000 km.\n\n    const Eigen::Vector3d occultedBodyPosition = -149598000.0e3 * Eigen::Vector3d( 1.0, 0.0, 0.0 );\n    const Eigen::Vector3d occultingBodyPosition = Eigen::Vector3d::Zero( );\n    const double occultedBodyRadius = 6.96e8; // Siedelmann 1992.\n    const double occultingBodyRadius = 6378.137e3; // WGS-84.\n\n    const Eigen::Vector3d satellitePosition = ( occultingBodyRadius + 1.0e6 )\n            * Eigen::Vector3d( 1.0, 0.0, 0.0 );\n\n    // Compute shadow function.\n    const double shadowFunction = mission_geometry::computeShadowFunction(\n                occultedBodyPosition,\n                occultedBodyRadius,\n                occultingBodyPosition,\n                occultingBodyRadius,\n                satellitePosition );\n\n    // Test values.\n    BOOST_CHECK_EQUAL( 0.0, shadowFunction );\n}\n\nBOOST_AUTO_TEST_CASE( testShadowFunctionForFullLight )\n{\n    // Satellite totally subjected to sunlight. Satellite is located on the y-axis and the sun is\n    // located on the x-axis. Altitude of satellite = 1000 km.\n\n    const Eigen::Vector3d occultedBodyPosition = -149598000.0e3 * Eigen::Vector3d( 1.0, 0.0, 0.0 );\n    const Eigen::Vector3d occultingBodyPosition = Eigen::Vector3d::Zero( );\n    const double occultedBodyRadius = 6.96e8; // Siedelmann 1992.\n    const double occultingBodyRadius = 6378.137e3; // WGS-84.\n\n    const Eigen::Vector3d satellitePosition = ( occultingBodyRadius + 1.0e6 )\n            * Eigen::Vector3d( 0.0, 1.0, 0.0 );\n\n    // Compute shadow function.\n    const double shadowFunction = mission_geometry::computeShadowFunction(\n                occultedBodyPosition,\n                occultedBodyRadius,\n                occultingBodyPosition,\n                occultingBodyRadius,\n                satellitePosition );\n\n    // Test values\n    BOOST_CHECK_EQUAL( 1.0, shadowFunction );\n}\n\nBOOST_AUTO_TEST_CASE( testShadowFunctionForPartialShadow )\n{\n    // Satellite partially visible. Satellite is located between the locations of the previous\n    // tests in penumbra. According to analytical derivations in Matlab the shadow function should\n    // be around 0.4547. Altitude of satellite = 1000 km.\n\n    const Eigen::Vector3d occultedBodyPosition = -149598000.0e3 * Eigen::Vector3d( 1.0, 0.0, 0.0 );\n    const Eigen::Vector3d occultingBodyPosition = Eigen::Vector3d::Zero( );\n    const double occultedBodyRadius = 6.96e8; // Siedelmann 1992.\n    const double occultingBodyRadius = 6378.137e3; // WGS-84.\n\n    Eigen::Vector3d satelliteDirection( 0.018, 1.0, 0.0 );\n    satelliteDirection.normalize( );\n\n    const Eigen::Vector3d satellitePosition = ( occultingBodyRadius + 1.0e3 ) * satelliteDirection;\n\n    // Compute shadow function\n    const double shadowFunction = mission_geometry::computeShadowFunction(\n                occultedBodyPosition,\n                occultedBodyRadius,\n                occultingBodyPosition,\n                occultingBodyRadius,\n                satellitePosition );\n\n    // Test values.\n    BOOST_CHECK_CLOSE_FRACTION( 0.4547, shadowFunction, 0.001 );\n}\n\n//! Unit test for computation of radius of sphere of influence (Earth with respect to Sun).\nBOOST_AUTO_TEST_CASE( testSphereOfInfluenceEarth )\n{\n    const double distanceEarthSun = 1.49597870700e11;  // (IERS, 2010)\n    const double massEarth = 5.972186390142457e24;     // (IERS, 2010)\n    const double massSun = 1.988415860572227e30;       // (IERS, 2010)\n\n    // Test 1: test function taking masses.\n    {\n        // Calculate the sphere of influence of the Earth with respect to the Sun.\n        const double sphereOfInfluenceEarth\n                = mission_geometry::computeSphereOfInfluence(\n                    distanceEarthSun, massEarth, massSun );\n\n        // Test values (Wikipedia, Sphere of Influence)\n        BOOST_CHECK_CLOSE_FRACTION( 9.25e8, sphereOfInfluenceEarth, 5.0e-4 );\n    }\n\n    // Test 2: test function taking mass ratio.\n    {\n        // Calculate the sphere of influence of the Earth with respect to the Sun.\n        const double sphereOfInfluenceEarth\n                = mission_geometry::computeSphereOfInfluence(\n                    distanceEarthSun, massEarth / massSun );\n\n        // Test values (Wikipedia, Sphere of Influence)\n        BOOST_CHECK_CLOSE_FRACTION( 9.25e8, sphereOfInfluenceEarth, 5.0e-4 );\n    }\n}\n\n//! Unit test for computation of radius of sphere of influence (Moon with respect to Earth).\nBOOST_AUTO_TEST_CASE( testSphereOfInfluenceMoon )\n{\n    const double distanceMoonEarth = 3.84400e8;     // (Horizons, NASA)\n    const double massMoon = 7.345811416686730e22;   // (IERS, 2010)\n    const double massEarth = 5.972186390142457e24;  // (IERS, 2010)\n\n    // Test 1: test function taking masses.\n    {\n        // Calculate the sphere of influence of the Moon with respect to the Earth.\n        const double sphereOfInfluenceEarth\n                = mission_geometry::computeSphereOfInfluence(\n                    distanceMoonEarth, massMoon, massEarth );\n\n        // Test values (Wikipedia, Sphere of Influence)\n        BOOST_CHECK_CLOSE_FRACTION( 6.61e7, sphereOfInfluenceEarth, 2.0e-3 );\n    }\n\n    // Test 2: test function taking mass ratio.\n    {\n        const double sphereOfInfluenceMoon\n                = mission_geometry::computeSphereOfInfluence(\n                    distanceMoonEarth, massMoon / massEarth );\n\n        // Test values (Wikipedia, Sphere of Influence)\n        BOOST_CHECK_CLOSE_FRACTION( 6.61e7, sphereOfInfluenceMoon, 2.0e-3 );\n    }\n}\n\n//! Unit test for testing for retrogradeness.\nBOOST_AUTO_TEST_CASE( testIsOrbitRetrograde )\n{\n    using namespace orbital_element_conversions;\n    using namespace mission_geometry;\n    using namespace mathematical_constants;\n\n    // Initialize test Kepler elements.\n    Eigen::Vector6d testKepler = Eigen::VectorXd::Zero( 6 );\n    testKepler( semiMajorAxisIndex ) = 1.0e7;\n    testKepler( eccentricityIndex ) = 0.1;\n    testKepler( inclinationIndex ) = 50.0 / 180.0 * PI;\n    testKepler( argumentOfPeriapsisIndex ) = 350.0 / 180.0 * PI;\n    testKepler( longitudeOfAscendingNodeIndex ) = 15.0 / 180.0 * PI;\n    testKepler( trueAnomalyIndex ) = 170.0 / 180.0 * PI;\n\n    bool expectedIsOrbitRetrograde = false;\n\n    bool calculatedIsOrbitRetrograde = true;\n\n    // Test value for prograde orbit, not near boundary.\n    {\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler( inclinationIndex ) );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n    }\n\n    // Test value for prograde orbit, near zero boundary.\n    {\n        testKepler( inclinationIndex ) = std::numeric_limits< double >::epsilon( );\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler( inclinationIndex ) );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n    }\n\n    // Test value for prograde orbit, near 90 degrees boundary.\n    {\n        testKepler( inclinationIndex ) = PI / 2.0 - std::numeric_limits< double >::epsilon( );\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler( inclinationIndex ) );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n    }\n\n    // Test value for retrograde orbit, near 90 degrees boundary.\n    {\n        expectedIsOrbitRetrograde = 1;\n        testKepler( inclinationIndex ) = PI / 2.0 + std::numeric_limits< double >::epsilon( );\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler( inclinationIndex ) );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n    }\n\n    // Test value for retrograde orbit, not near boundary.\n    {\n        testKepler( inclinationIndex ) = 2.0;\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler( inclinationIndex ) );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n    }\n\n    // Test value for retrograde orbit, near 180 degrees boundary.\n    {\n        testKepler( inclinationIndex ) = PI - std::numeric_limits< double >::epsilon( );\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler( inclinationIndex ) );\n        BOOST_CHECK_EQUAL( expectedIsOrbitRetrograde, calculatedIsOrbitRetrograde );\n    }\n\n    // Check exception handling for inclinations out of range.\n    bool isExceptionFound = false;\n    testKepler( inclinationIndex ) = PI + 1.0;\n\n    // Try to calculate retrogradeness.\n    try\n    {\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler );\n    }\n    // Catch the expected runtime error, and set the boolean flag to true.\n    catch ( std::runtime_error )\n    {\n        isExceptionFound = true;\n    }\n    // Check value of flag.\n    BOOST_CHECK( isExceptionFound );\n\n    isExceptionFound = false;\n    // Try to calculate retrogradeness.\n    try\n    {\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler( inclinationIndex ) );\n    }\n    // Catch the expected runtime error, and set the boolean flag to true.\n    catch ( std::runtime_error )\n    {\n        isExceptionFound = true;\n    }\n    // Check value of flag.\n    BOOST_CHECK( isExceptionFound );\n\n    isExceptionFound = false;\n    testKepler( inclinationIndex ) = -1.0;\n    // Try to calculate retrogradeness.\n    try\n    {\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler );\n    }\n    // Catch the expected runtime error, and set the boolean flag to true.\n    catch ( std::runtime_error )\n    {\n        isExceptionFound = true;\n    }\n    // Check value of flag.\n    BOOST_CHECK( isExceptionFound );\n\n    isExceptionFound = false;\n    // Try to calculate retrogradeness.\n    try\n    {\n        calculatedIsOrbitRetrograde = isOrbitRetrograde( testKepler( inclinationIndex ) );\n    }\n    // Catch the expected runtime error, and set the boolean flag to true.\n    catch ( std::runtime_error )\n    {\n        isExceptionFound = true;\n    }\n    // Check value of flag.\n    BOOST_CHECK( isExceptionFound );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "ba359981337e1d6fc4eb6aca23e3d24c3c5380de", "size": 12448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestMissionGeometry.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestMissionGeometry.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/unitTestMissionGeometry.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6583850932, "max_line_length": 100, "alphanum_fraction": 0.6968991003, "num_tokens": 3220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6058994213734864}}
{"text": "// demo to test BBW with custom FK for a cylinder mesh\n// Executable bbw_cyl can be run to see the results.\n\n#include <igl/boundary_conditions.h>\n#include <igl/readMESH.h>\n#include <igl/opengl/glfw/Viewer.h>\n#include <igl/bbw.h>\n#include <igl/normalize_row_sums.h>\n#include <igl/forward_kinematics.h>\n#include <igl/directed_edge_parents.h>\n\n#include <igl/lbs_matrix.h>\n#include <igl/deform_skeleton.h>\n\n\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n#include <vector>\n#include <algorithm>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nconst Eigen::RowVector3d sea_green(70./255.,252./255.,167./255.);\n\nEigen::MatrixXd V,W,U,C,M;\nEigen::MatrixXi T,F,BE;\nEigen::VectorXi P;\n\nint selected = 0;\n\n\nEigen::MatrixXd TV;\nEigen::MatrixXi TT;\nEigen::MatrixXi TF;\n\ntypedef std::vector<Eigen::Quaterniond,Eigen::aligned_allocator<Eigen::Quaterniond>> RotationList;\n\nEigen::Quaterniond\neuler2Quaternion( const double roll,\n                  const double pitch,\n                  const 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\n    Eigen::Quaterniond q = yawAngle * pitchAngle * rollAngle;\n    return q;\n}\n\ndouble angle = 0;\n\nbool pre_draw(igl::opengl::glfw::Viewer & viewer){\n\n    Vector3d dist1 = (C.row(1) - C.row(0));\n    Vector3d dist2 = (C.row(2) - C.row(1));\n    Affine3d T0 = Affine3d::Identity();\n    Affine3d T1 = Affine3d::Identity();\n    Affine3d T2 = Affine3d::Identity();\n    Affine3d T3 = Affine3d::Identity();\n\n    T1.translate(dist1); \n    T3.translate(dist2);\n    \n    angle += 0.1*M_PI;\n\n    T0.rotate(euler2Quaternion(angle/2.0, 0.0, 0.0));\n    T2.rotate(euler2Quaternion(angle, 0.0, 0.0));\n\n    Affine3d T01 = Affine3d::Identity();\n    T01.translate(Vector3d(C.row(1)));    \n    Affine3d T02 = Affine3d::Identity();\n    T02.translate(Vector3d(C.row(2)));\n    Affine3d T_ff1 = T0*T1;\n    Affine3d T_ff2 = T0*T1*T2*T3;\n\n    const int dim = C.cols();\n    MatrixXd T(BE.rows()*(dim+1),dim);\n    for(int e = 0;e<BE.rows();e++)\n    {\n        Affine3d a = Affine3d::Identity();\n        if (e == 0){\n            a = T_ff1*T01.inverse();\n        }\n        if (e == 1){\n            a = T_ff2*T02.inverse();\n        }\n        T.block(e*(dim+1),0,dim+1,dim) =\n            a.matrix().transpose().block(0,0,dim+1,dim);\n\n    }\n    // Compute deformation via LBS as matrix multiplication\n    U = M*T;\n    MatrixXd CT;\n    MatrixXi BET;\n    igl::deform_skeleton(C,BE,T,CT,BET);\n\n    viewer.data().set_vertices(U);\n    viewer.data().set_edges(CT,BET,sea_green);\n};\n    \n\nint main(int argc, char *argv[]){\n\n    igl::readOFF(\"../data/cylinder.off\",V,F);\n    std::cout << \"finished reading ...\" << std::endl;\n\n    U = V;\n\n    C.resize(3,3);\n\n    C.row(0) = V.row(4800);\n    C.row(1) = V.row(2372);\n    C.row(2) = V.row(4801);\n\n    BE.resize(2,2);\n    \n    BE << 0, 1,\n          1, 2;\n\n    // List of boundary indices (aka fixed value indices into VV)\n    VectorXi b;\n    // List of boundary conditions of each weight function\n    MatrixXd bc;\n    igl::boundary_conditions(V,F,C,VectorXi(),BE,MatrixXi(),b,bc);\n\n    std::cout << \"vec\" << VectorXi() << std::endl;\n\n    igl::BBWData bbw_data;\n    // only a few iterations for sake of demo\n    bbw_data.active_set_params.max_iter = 8;\n    bbw_data.verbosity = 2;\n    if(!igl::bbw(V,F,b,bc,bbw_data,W))\n    {\n        return EXIT_FAILURE;\n    }\n    // Normalize weights to sum to one\n    igl::normalize_row_sums(W,W);\n\n    // precompute linear blend skinning matrix\n    igl::lbs_matrix(V,W,M);\n\n    //////////////////////////////////////////////////////////\n    // bending the cylinder\n\n    // std::cout << C << std::endl;\n\n    // std::cout << CT << std::endl;\n\n    // std::cout << BET << std::endl;\n\n    igl::opengl::glfw::Viewer viewer;\n    viewer.data().set_mesh(U, F);\n    viewer.data().set_data(W.col(selected));\n    viewer.data().set_edges(C,BE,sea_green);\n    viewer.callback_pre_draw = &pre_draw;\n    viewer.data().show_lines = false;\n    viewer.data().show_overlay_depth = false;\n    viewer.data().line_width = 1;\n    viewer.core().animation_max_fps = 30.;\n    viewer.core().is_animating = true;\n    viewer.launch();\n\n    return 0;\n}\n\n\n// std::cout << \"FK \" << Quaterniond((T_ff*T0.inverse()).rotation()).vec() <<  std::endl;\n\n    // RotationList anim_pose(2);\n    // anim_pose[0] = euler2Quaternion(0, 0.0, 0.0);\n    // anim_pose[1] = euler2Quaternion(0.5*M_PI, 0.0, 0.0);\n\n    // // retrieve parents for forward kinematics\n    // igl::directed_edge_parents(BE,P);\n    // RotationList vQ;\n    // vector<Vector3d> vT;\n    // igl::forward_kinematics(C,BE,P,anim_pose,vQ,vT);\n\n    // std::cout << \"igl FK\" << vQ[1].vec() << \" \" << std::endl;", "meta": {"hexsha": "4a41338e38b29a460af07fd84f91b9b87837f421", "size": 4774, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project/demos/bbw_cyl.cpp", "max_stars_repo_name": "avadesh02/geometric_modeling", "max_stars_repo_head_hexsha": "dc5d884d1295b0393ea3fae4acff9d973acb3cac", "max_stars_repo_licenses": ["MIT"], "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/demos/bbw_cyl.cpp", "max_issues_repo_name": "avadesh02/geometric_modeling", "max_issues_repo_head_hexsha": "dc5d884d1295b0393ea3fae4acff9d973acb3cac", "max_issues_repo_licenses": ["MIT"], "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/demos/bbw_cyl.cpp", "max_forks_repo_name": "avadesh02/geometric_modeling", "max_forks_repo_head_hexsha": "dc5d884d1295b0393ea3fae4acff9d973acb3cac", "max_forks_repo_licenses": ["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.2307692308, "max_line_length": 98, "alphanum_fraction": 0.6116464181, "num_tokens": 1461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.6058994205566464}}
{"text": "// -----------------------------------------------------------------------\r\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\r\n//\r\n// Copyright (c) German Cancer Research Center (DKFZ),\r\n// Software development for Integrated Diagnostics and Therapy (SIDT).\r\n// ALL RIGHTS RESERVED.\r\n// See rttbCopyright.txt or\r\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html\r\n//\r\n// This software is distributed WITHOUT ANY WARRANTY; without even\r\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n// PURPOSE.  See the above copyright notices for more information.\r\n//\r\n//------------------------------------------------------------------------\r\n\r\n#define _USE_MATH_DEFINES\r\n#include <string>\r\n#include <vector>\r\n#include <exception>\r\n\r\n#include <boost/make_shared.hpp>\r\n\r\n#include <cmath>\r\n\r\n#include \"rttbIntegration.h\"\r\n#include \"rttbNTCPLKBModel.h\"\r\n#include \"rttbDvhBasedModels.h\"\r\n#include \"rttbInvalidParameterException.h\"\r\n#include \"rttbExceptionMacros.h\"\r\n\r\nnamespace rttb\r\n{\r\n\r\n\tnamespace models\r\n\t{\r\n\t\tNTCPLKBModel::NTCPLKBModel() : NTCPModel(){\r\n\t\t\t_name = \"NTCPLKBModel\";\r\n\t\t\tfillParameterMap();\r\n\t\t}\r\n\r\n\t\tNTCPLKBModel::NTCPLKBModel(DVHPointer aDvh, BioModelParamType aD50, BioModelParamType aM,\r\n\t\t                           BioModelParamType aA):\r\n\t\t\t\t\t\t\t\t   NTCPModel(aDvh, aD50), _m(aM), _a(aA) {\r\n\t\t\t\t\t\t\t\t\t   _name = \"NTCPLKBModel\";\r\n\t\t\t\t\t\t\t\t\t   fillParameterMap();\r\n\t\t\t\t\t\t\t\t   }\r\n\r\n\t\tvoid NTCPLKBModel::setA(const BioModelParamType aA)\r\n\t\t{\r\n\t\t\t_a = aA;\r\n\t\t}\r\n\r\n\t\tconst BioModelParamType NTCPLKBModel::getA()\r\n\t\t{\r\n\t\t\treturn _a;\r\n\t\t}\r\n\r\n\t\tvoid NTCPLKBModel::setM(const BioModelParamType aM)\r\n\t\t{\r\n\t\t\t_m = aM;\r\n\t\t}\r\n\r\n\t\tconst BioModelParamType NTCPLKBModel::getM()\r\n\t\t{\r\n\t\t\treturn _m;\r\n\t\t}\r\n\r\n\t\tvoid NTCPLKBModel::setParameterVector(const ParamVectorType& aParameterVector)\r\n\t\t{\r\n\t\t\tif (aParameterVector.size() != 3)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: aParameterVector.size must be 3! \");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t_d50 = aParameterVector.at(0);\r\n\t\t\t\t_m = aParameterVector.at(1);\r\n\t\t\t\t_a = aParameterVector.at(2);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid NTCPLKBModel::setParameterByID(const int aParamId, const BioModelParamType aValue)\r\n\t\t{\r\n\t\t\tif (aParamId == 0)\r\n\t\t\t{\r\n\t\t\t\t_d50 = aValue;\r\n\t\t\t}\r\n\t\t\telse if (aParamId == 1)\r\n\t\t\t{\r\n\t\t\t\t_m = aValue;\r\n\t\t\t}\r\n\t\t\telse if (aParamId == 2)\r\n\t\t\t{\r\n\t\t\t\t_a = aValue;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidParameterException(\"Parameter invalid: aParamID must be 0(for d50) or 1(for m) or 2(for a)! \");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst int NTCPLKBModel::getParameterID(const std::string& aParamName) const\r\n\t\t{\r\n\t\t\tif (aParamName == \"d50\")\r\n\t\t\t{\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\telse if (aParamName == \"m\")\r\n\t\t\t{\r\n\t\t\t\treturn 1;\r\n\t\t\t}\r\n\t\t\telse if (aParamName == \"a\")\r\n\t\t\t{\r\n\t\t\t\treturn 2;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\trttbExceptionMacro(core::InvalidParameterException,\r\n\t\t\t\t                   << \"Parameter name \" << aParamName << \" invalid: it should be d50 or m or a!\");\r\n\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstd::map<std::string, double> NTCPLKBModel::getParameterMap() const{\r\n\t\t\treturn parameterMap;\r\n\t\t}\r\n\r\n\t\tvoid NTCPLKBModel::fillParameterMap(){\r\n\t\t\tparameterMap[\"d50\"] = getD50();\r\n\t\t\tparameterMap[\"m\"] = getM();\r\n\t\t\tparameterMap[\"a\"] = getA();\r\n\t\t}\r\n\r\n\t\tstd::string NTCPLKBModel::getModelType() const{\r\n\t\t\treturn _name;\r\n\t\t}\r\n\r\n\t\tBioModelValueType NTCPLKBModel::calcModel(const double doseFactor)\r\n\t\t{\r\n\t\t\tif (_a == 0)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidParameterException(\"_a must not be zero\");\r\n\t\t\t}\r\n\r\n\t\t\tif (_m == 0)\r\n\t\t\t{\r\n\t\t\t\tthrow core::InvalidParameterException(\"_m must not be zero\");\r\n\t\t\t}\r\n\r\n\t\t\tcore::DVH variantDVH = core::DVH(_dvh->getDataDifferential(),\r\n\t\t\t                                 (DoseTypeGy)(_dvh->getDeltaD() * doseFactor),\r\n\t\t\t                                 _dvh->getDeltaV(), \"temporary\", \"temporary\");\r\n\r\n\t\t\tauto spDVH = boost::make_shared<core::DVH>(variantDVH);\r\n\t\t\tdouble eud = getEUD(spDVH, this->_a);\r\n\t\t\t//_m must not be zero\r\n\t\t\tdouble t = (eud - this->_d50) / (this->_m * this->_d50);\r\n\t\t\tdouble value = 1 / pow(2 * M_PI, 0.5);\r\n\r\n\t\t\tdouble result = integrateLKB(t);\r\n\r\n\t\t\tif (result != -100)\r\n\t\t\t{\r\n\t\t\t\tvalue *= result;\r\n\r\n\t\t\t\treturn value;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}//end namespace models\r\n}//end namespace rttb\r\n", "meta": {"hexsha": "b7cc495c450023dfb88c7344fb75e45b96f76a0c", "size": 4260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/models/rttbNTCPLKBModel.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "code/models/rttbNTCPLKBModel.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/models/rttbNTCPLKBModel.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 24.2045454545, "max_line_length": 119, "alphanum_fraction": 0.5884976526, "num_tokens": 1223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6058994120268774}}
{"text": "#include <tdp/testing/testing.h>\n#include <tdp/cg/cg.h>\n#include <tdp/utils/timer.hpp>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\nTEST(CG, small) {\n  size_t Nvar = 6*3;\n  size_t Nobs = 100;\n  Eigen::MatrixXf A = Eigen::MatrixXf::Random(Nobs,Nvar); \n  Eigen::VectorXf b = Eigen::VectorXf::Random(Nobs); \n\n  Eigen::MatrixXf ATA = A.transpose()*A;\n  Eigen::VectorXf ATb = A.transpose()*b;\n\n  Eigen::VectorXf x = ATA.ldlt().solve(ATb);\n  std::cout << x.transpose() << std::endl;\n\n  Eigen::SparseMatrix<float> Asp = A.sparseView();\n  Eigen::VectorXf xCg = Eigen::VectorXf::Zero(Nvar);\n  tdp::CG::ComputeCpu(Asp, b, 100, 1e-6, xCg);\n  std::cout << xCg.transpose() << std::endl;\n\n  Eigen::VectorXf xPcg = Eigen::VectorXf::Zero(Nvar);\n  Eigen::VectorXf Mdiag = ATA.diagonal();\n  tdp::PCG::ComputeCpu(Asp, b, Mdiag, 100, 1e-6, xPcg);\n  std::cout << xPcg.transpose() << std::endl;\n\n}\n\nTEST(CG, large) {\n  size_t Nvar = 6*100;\n  size_t Nobs = 1000000;\n  Eigen::MatrixXf A = Eigen::MatrixXf::Random(Nobs,Nvar); \n  Eigen::VectorXf b = Eigen::VectorXf::Random(Nobs); \n\n  tdp::Timer t0;\n  Eigen::MatrixXf ATA = A.transpose()*A;\n  Eigen::VectorXf ATb = A.transpose()*b;\n  Eigen::VectorXf x = ATA.ldlt().solve(ATb);\n  t0.toctic(\"ldlt solve\");\n\n  Eigen::SparseMatrix<float> Asp = A.sparseView();\n  Eigen::VectorXf xCg = Eigen::VectorXf::Zero(Nvar);\n\n  t0.tic();\n  tdp::CG::ComputeCpu(Asp, b, 100, 1e-6, xCg);\n  t0.toctic(\"cg\");\n  std::cout << \"CG err:\\t\" << (x-xCg).norm() << std::endl;\n\n  Eigen::VectorXf xPcg = Eigen::VectorXf::Zero(Nvar);\n  Eigen::VectorXf Mdiag = ATA.diagonal();\n  t0.tic();\n  tdp::PCG::ComputeCpu(Asp, b, Mdiag, 100, 1e-6, xPcg);\n  t0.toctic(\"pcg\");\n  std::cout << \"PCG err:\\t\" << (x-xPcg).norm() << std::endl;\n}\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "f7eb7cd4929c3a95ee6637cd709889e91b046a57", "size": 1827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/cg.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "test/cg.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "test/cg.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 29.0, "max_line_length": 60, "alphanum_fraction": 0.6387520525, "num_tokens": 685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6058994103931976}}
{"text": "/*\n * COPYRIGHT AND PERMISSION NOTICE\n * UCSD Software ORCVIO\n * Copyright (C) 2021 \n * All rights reserved.\n */\n\n#include <gtest/gtest.h>\n#include <random_numbers/random_numbers.h>\n#include <iostream>\n#include <map>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/StdVector>\n\n#include \"orcvio/cam_state.h\"\n#include \"orcvio/feature.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace orcvio;\n\n// Static member variables in CAMState class\nIsometry3d CAMState::T_cam0_cam1 = Isometry3d::Identity();\n\n// Static member variables in Feature class\nFeature::OptimizationConfig Feature::optimization_config;\n\nTEST(FeatureInitializeTest, sphereDistribution) {\n    // Set the real feature at the origin of the world frame.\n    Vector3d feature(0.5, 0.0, 0.0);\n\n    // Add 6 camera poses, all of which are able to see the\n    // feature at the origin. For simplicity, the six camera\n    // view are located at the six intersections between a\n    // unit sphere and the coordinate system. And the z axes\n    // of the camera frames are facing the origin.\n    vector<Isometry3d> cam_poses(6);\n    // Positive x axis.\n    cam_poses[0].linear() << 0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0.0, -1.0, 0.0;\n    cam_poses[0].translation() << 1.0, 0.0, 0.0;\n    // Positive y axis.\n    cam_poses[1].linear() << -1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, -1.0, 0.0;\n    cam_poses[1].translation() << 0.0, 1.0, 0.0;\n    // Negative x axis.\n    cam_poses[2].linear() << 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, -1.0, 0.0;\n    cam_poses[2].translation() << -1.0, 0.0, 0.0;\n    // Negative y axis.\n    cam_poses[3].linear() << 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -1.0, 0.0;\n    cam_poses[3].translation() << 0.0, -1.0, 0.0;\n    // Positive z axis.\n    cam_poses[4].linear() << 0.0, -1.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, -1.0;\n    cam_poses[4].translation() << 0.0, 0.0, 1.0;\n    // Negative z axis.\n    cam_poses[5].linear() << 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0;\n    cam_poses[5].translation() << 0.0, 0.0, -1.0;\n\n    // Set the camera states\n    CamStateServer cam_states;\n    for (int i = 0; i < 6; ++i) {\n        CAMState new_cam_state;\n        new_cam_state.id = i;\n        new_cam_state.time = static_cast<double>(i);\n        new_cam_state.orientation = Matrix3d(cam_poses[i].linear());\n        new_cam_state.position = cam_poses[i].translation();\n        cam_states[new_cam_state.id] = new_cam_state;\n    }\n\n    // Compute measurements.\n    random_numbers::RandomNumberGenerator noise_generator;\n    vector<Vector4d, aligned_allocator<Vector4d> > measurements(6);\n    for (int i = 0; i < 6; ++i) {\n        Isometry3d cam_pose_inv = cam_poses[i].inverse();\n        Vector3d p = cam_pose_inv.linear() * feature + cam_pose_inv.translation();\n        double u = p(0) / p(2) + noise_generator.gaussian(0.0, 0.01);\n        double v = p(1) / p(2) + noise_generator.gaussian(0.0, 0.01);\n        //double u = p(0) / p(2);\n        //double v = p(1) / p(2);\n        measurements[i] = Vector4d(u, v, u, v);\n    }\n\n    for (int i = 0; i < 6; ++i) {\n        cout << \"pose \" << i << \":\" << endl;\n        cout << \"orientation: \" << endl;\n        cout << cam_poses[i].linear() << endl;\n        cout << \"translation: \" << endl;\n        cout << cam_poses[i].translation().transpose() << endl;\n        cout << \"measurement: \" << endl;\n        cout << measurements[i].transpose() << endl;\n        cout << endl;\n    }\n\n    // Initialize a feature object.\n    Feature feature_object;\n    for (int i = 0; i < 6; ++i) feature_object.observations[i] = measurements[i];\n\n    // Compute the 3d position of the feature.\n    feature_object.initializePosition(cam_states);\n\n    // Check the difference between the computed 3d\n    // feature position and the groud truth.\n    cout << \"ground truth position: \" << feature.transpose() << endl;\n    cout << \"estimated position: \" << feature_object.position.transpose() << endl;\n    Eigen::Vector3d error = feature_object.position - feature;\n    EXPECT_NEAR(error.norm(), 0, 0.05);\n}\n\nint main(int argc, char** argv) {\n    testing::InitGoogleTest(&argc, argv);\n    return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "80dd571156df4d1591a72c4210d374988d9c5274", "size": 4122, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/feature_initialization_test.cpp", "max_stars_repo_name": "shanmo/OrcVIO-Stereo", "max_stars_repo_head_hexsha": "78d4cf24cc280af53f4131628983891817fbf070", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-08-06T03:24:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T14:23:44.000Z", "max_issues_repo_path": "test/feature_initialization_test.cpp", "max_issues_repo_name": "shanmo/OrcVIO-Stereo", "max_issues_repo_head_hexsha": "78d4cf24cc280af53f4131628983891817fbf070", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-30T17:09:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T23:41:52.000Z", "max_forks_repo_path": "test/feature_initialization_test.cpp", "max_forks_repo_name": "shanmo/OrcVIO-Stereo", "max_forks_repo_head_hexsha": "78d4cf24cc280af53f4131628983891817fbf070", "max_forks_repo_licenses": ["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.1578947368, "max_line_length": 82, "alphanum_fraction": 0.6169335274, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083131, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.605854723649806}}
{"text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <cctype>\n#include <sstream>\n#include <memory>\n#include <utility>\n#include <exception>\n#include <boost/lexical_cast.hpp>\n\n\n/**\n * The `Interpreter` pattern provides a way to include language elements in a program\n */\n\n\nstruct Token {\n    enum Type { integer, plus, minus, lparen, rparen };\n\n    Type type;\n    std::string text;\n\n    explicit Token(Type t, std::string txt)\n        : type{t}, text{std::move(txt)}\n    {\n    }\n\n    friend std::ostream& operator<<(std::ostream& os, Token const& obj)\n    {\n        return os << \"`\" << obj.text << \"`\";\n    }\n};\n\nstd::vector<Token> lex(std::string const& input)\n{\n    std::vector<Token> result;\n    for (int i = 0; i < input.size(); ++i) {\n        switch (input[i]) {\n        case '+':\n            result.push_back(Token{Token::plus, \"+\"});\n            break;\n        case '-':\n            result.push_back(Token{Token::minus, \"-\"});\n            break;\n        case '(':\n            result.push_back(Token{Token::lparen, \"(\"});\n            break;\n        case ')':\n            result.push_back(Token{Token::rparen, \")\"});\n            break;\n        default:\n            // number\n            std::ostringstream buffer;\n            buffer << input[i];\n            for (int j = i + 1; j < input.size(); ++j) {\n                if (std::isdigit(input[j])) {\n                    buffer << input[j];\n                    ++i;\n                }\n                else {\n                    result.push_back(Token{Token::integer, buffer.str()});\n                    break;\n                }\n            }\n        }\n    }\n\n    return result;\n}\n\n// parsing\n\nstruct Element {\n    virtual ~Element() = default;\n    virtual int eval() const = 0;\n};\n\nstruct Integer : public Element {\n    int value;\n    explicit Integer(int const val)\n        : value{val}\n    {\n    }\n\n    int eval() const override { return value; }\n};\n\nstruct BinaryOperation : public Element {\npublic:\n    enum Type {addition, substraction};\n    Type type;\n    std::shared_ptr<Element> lhs, rhs;\n\n    int eval() const override\n    {\n        if (type == addition) {\n            return lhs->eval() + rhs->eval();\n        }\n        return lhs->eval() - rhs->eval();\n    }\n};\n\nstd::shared_ptr<Element> parse(std::vector<Token> const& tokens)\n{\n    auto result = std::make_unique<BinaryOperation>();\n    bool have_lhs = false;\n    for (std::size_t i = 0; i < tokens.size(); ++i) {\n        auto token = tokens[i];\n        switch (token.type) {\n        case Token::integer:\n        {\n            int value = boost::lexical_cast<int>(token.text);\n            auto integer = std::make_shared<Integer>(value);\n            if (!have_lhs) {\n                result->lhs = integer;\n                have_lhs = true;\n            }\n            else {\n                result->rhs = integer;\n            }\n            break;\n        }\n        case Token::plus:\n            result->type = BinaryOperation::addition;\n            break;\n        case Token::minus:\n            result->type = BinaryOperation::substraction;\n            break;\n        case Token::lparen:\n        {\n            int j = i;\n            for ( ; j < tokens.size(); ++j) {\n                if (tokens[j].type == Token::rparen) {\n                    break;\n                }\n            }\n            std::vector<Token> subexpression(&tokens[i+1], &tokens[j]);\n            auto element = parse(subexpression);\n            if (!have_lhs) {\n                result->lhs = element;\n                have_lhs = true;\n            }\n            else {\n                result->rhs = element;\n                i = j;  // advance\n            }\n            break;\n        }\n        } // switch\n        return result;\n    }\n}\n\n\nint main()\n{\n    std::string input{ \"(13-4)-(12+1)\" }; // see if you can make nested braces work\n    auto tokens = lex(input);\n\n    // let's see the tokens\n    for (auto& t : tokens)\n        std::cout << t << \"   \";\n    std::cout << std::endl;\n\n    try {\n        auto parsed = parse(tokens);\n        std::cout << input << \" = \" << parsed->eval() << std::endl;\n    } \n    catch (const std::exception& e)\n    {\n        std::cout << e.what() << std::endl;\n    }\n}\n", "meta": {"hexsha": "4cd78244f6846a29029fdb72d0a76b99c1140882", "size": 4189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DesignPatterns/Behavioral/interpreter_1.cpp", "max_stars_repo_name": "kant/Always-be-learning", "max_stars_repo_head_hexsha": "7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5", "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": "DesignPatterns/Behavioral/interpreter_1.cpp", "max_issues_repo_name": "kant/Always-be-learning", "max_issues_repo_head_hexsha": "7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5", "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": "DesignPatterns/Behavioral/interpreter_1.cpp", "max_forks_repo_name": "kant/Always-be-learning", "max_forks_repo_head_hexsha": "7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5", "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.0747126437, "max_line_length": 85, "alphanum_fraction": 0.4769634758, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6058455384808267}}
{"text": "//! [mandelbrot-all]\n#include <chrono>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\n#include <boost/simd/memory/allocator.hpp>\n#include <boost/simd/pack.hpp>\n\n#include <boost/simd/function/aligned_load.hpp>\n#include <boost/simd/function/aligned_store.hpp>\n#include <boost/simd/function/enumerate.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/if_inc.hpp>\n#include <boost/simd/function/sqr.hpp>\n\n// if you want to see the julia set\n// uncomment the two include lines and the two other commented areas with the\n// same front line as this one\n// this suppose you have opencv installed and the proper libraries on your\n// compilation command\n// opencv_core opencv_imgproc opencv_highgui\n// #include <opencv2/contrib/contrib.hpp>\n// #include <opencv2/highgui/highgui.hpp>\n// #include <opencv2/imgproc/imgproc.hpp>\n\ntypedef float T;\nnamespace bs = boost::simd;\nusing pack_t = bs::pack<T>;\nusing pack_i = bs::pack<int>;\nusing pack_l = bs::as_logical_t<pack_t>;\n\nstruct mandelbrot\n{\n  int size, max_iter;\n  T x_min, x_max, y_min, y_max, x_range, y_range;\n  std::vector<int, bs::allocator<int>> iterations;\n\n  mandelbrot(int size_, int max_iter_)\n    : size(size_)\n    , max_iter(max_iter_)\n  {\n    x_min   = -2.5;\n    x_max   = 1;\n    y_min   = -1;\n    y_max   = 1;\n    x_range = x_max - x_min;\n    y_range = y_max - y_min;\n    iterations.resize(size * size);\n  }\n\n  //! [mandelbrot-scalar]\n  void evaluate_scalar()\n  {\n    for (int i = 0; i < size; ++i) {\n      T x0 = T(i) / T(size) * x_range + x_min;\n      for (int j = 0; j < size; ++j) {\n        int iteration = 0;\n        T y0          = T(j) / T(size) * y_range + y_min;\n        T x           = 0;\n        T y           = 0;\n        T x2          = x * x;\n        T y2          = y * y;\n        while (x2 + y2 < 4 && iteration < max_iter) {\n          x2 = x * x;\n          y2 = y * y;\n          T x_temp = x2 - y2 + x0;\n          y        = 2 * x * y + y0;\n          x        = x_temp;\n          ++iteration;\n        }\n        iterations[j + i * size] = iteration;\n      }\n    }\n  }\n  //! [mandelbrot-scalar]\n\n  //! [mandelbrot-simd]\n  void evaluate_simd()\n  {\n    pack_t step =\n      bs::enumerate<pack_t>(0); // produce a vector containing {0, 1, ..., pack_t::static_size-1}\n    for (int i = 0; i < size; ++i) {\n      pack_t x0{T(i) / T(size) * x_range + x_min};\n      pack_t fac{y_range / T(size)};\n      pack_t y_min_t{y_min};\n      for (int j = 0; j < size; j += pack_t::static_size) {\n        int iteration = 0;\n\n        pack_t y0 = bs::fma(step + j, fac, y_min_t);\n        pack_t x{0};\n        pack_t y{0};\n        pack_i iter{0};\n        pack_l mask;\n        do {\n          pack_t x2 = bs::sqr(x);\n          pack_t y2 = bs::sqr(y);\n\n          y    = bs::fma(x + x, y, y0);\n          x    = x2 - y2 + x0;\n          mask = x2 + y2 < 4;\n          ++iteration;\n          iter = bs::if_inc(mask, iter);\n        } while (bs::any(mask) && iteration < max_iter);\n        bs::aligned_store(iter, &iterations[j + i * size]);\n      }\n    }\n  }\n  //! [mandelbrot-simd]\n\n  // if you want to see the julia set\n  //    void display() {\n  //      cv::Mat display;\n  //      cv::Mat A(size, size, CV_32SC1, iterations.data());\n  //      A.convertTo(display, CV_8UC1, 255.0 / 1000.0);\n  //      cv::applyColorMap(display, display, cv::COLORMAP_JET);\n  //      cv::imshow(\"Mandelbrot\", display);\n  //      cv::waitKey(0);\n  //    }\n};\n\nint main(int argc, char** argv)\n{\n  namespace chr = std::chrono;\n  using hrc     = chr::high_resolution_clock;\n\n  int size          = 1024;\n  int max_iteration = 1000;\n  mandelbrot image(size, max_iteration);\n  auto t0 = hrc::now();\n  image.evaluate_scalar();\n  auto t1 = hrc::now();\n  std::cout << \" scalar \" << chr::duration_cast<chr::milliseconds>(t1 - t0).count() << std::endl;\n\n  t0 = hrc::now();\n  image.evaluate_simd();\n  t1 = hrc::now();\n  std::cout << \" simd \" << chr::duration_cast<chr::milliseconds>(t1 - t0).count() << std::endl;\n  // if you want to see the julia set\n  //  image.display();\n}\n//! [mandelbrot-all]\n\n// This code can be compiled using\n//    g++ mandelbrot.cpp -msse4.2 -std=c++11 -O3 -DNDEBUG -o mandelbrot\n//    -I/pathto/boost_simd//include -I/pathto/boost\n// or if you uncomment the opencv related lines to see the generated julia set\n// and use:\n//    g++ mandelbrot.cpp -msse4.2 -std=c++11 -O3 -DNDEBUG -o mandelbrot\n//    -I/pathto/boost_simd//include -I/pathto/boost -lopencv_core\n//    -lopencv_imgproc -lopencv_highgui -lopencv_contrib\n", "meta": {"hexsha": "85431089edd2493a9333e32127aa4d232cc8d793", "size": 4486, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/mandelbrot.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "doc/examples/mandelbrot.cpp", "max_issues_repo_name": "dendisuhubdy/boost.simd", "max_issues_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "doc/examples/mandelbrot.cpp", "max_forks_repo_name": "dendisuhubdy/boost.simd", "max_forks_repo_head_hexsha": "7630b1c1ffbd0300c100885b89ff78c2d579a24c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 29.5131578947, "max_line_length": 97, "alphanum_fraction": 0.578243424, "num_tokens": 1417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6057783536440481}}
{"text": "#include <ros/ros.h>\n#include <tf2_ros/transform_broadcaster.h>\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/NavSatFix.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <geometry_msgs/PointStamped.h>\n#include <Eigen/Dense>\n\n//TODO: this might be better off in a util class / module\n\n#define D2R(x) ((M_PI*x)/180.0)\n\nvoid geo2ecef(Eigen::Vector3d & positionECEF, double latitude, double longitude, double ellipsoidalHeight) {\n\t/**WGS84 ellipsoid semi-major axis*/\n\tdouble a = 6378137.0;\n\n\t/**WGS84 ellipsoid first eccentricity squared*/\n\tdouble e2 = 0.081819190842622 * 0.081819190842622;\n\n\tdouble slat = sin(D2R(latitude));\n\tdouble clat = cos(D2R(latitude));\n\tdouble slon = sin(D2R(longitude));\n\tdouble clon = cos(D2R(longitude));\n\n\tdouble N = a / (sqrt(1 - e2 * slat * slat));\n\tdouble xTRF = (N + ellipsoidalHeight) * clat * clon;\n\tdouble yTRF = (N + ellipsoidalHeight) * clat * slon;\n\tdouble zTRF = (N * (1 - e2) + ellipsoidalHeight) * slat;\n\n\tpositionECEF << xTRF, yTRF, zTRF;\n};\n\nclass GeoreferenceProvider{\npublic:\n\tGeoreferenceProvider(): ecefLocalOrigin(0,0,0){\n                odomPublisher=n.advertise<nav_msgs::Odometry>(\"odom\", 50);\n\n\t\tdepthRepublisher = n.advertise<geometry_msgs::PointStamped>(\"depth_ned\",50);\n\n                gpsSubscriber = n.subscribe(\"fix\", 50, &GeoreferenceProvider::processGpsCallback,this);\n                //attitudeSubscriber = n.subscribe(\"/imu/pos_ecef\", 50, &GeoreferenceProvider::processPositionCallback,this);\n\t\tattitudeSubscriber = n.subscribe(\"/imu/data\", 50, &GeoreferenceProvider::processAttitudeCallback,this);\n\t\tlidarSubscriber = n.subscribe(\"/velodyne_points\",100,&GeoreferenceProvider::processLidarCallback,this);\n\t\tdepthSubscriber = n.subscribe(\"/depth\",100,&GeoreferenceProvider::processDepthCallback,this);\n\n\t}\n\n\tvoid processGpsCallback(const sensor_msgs::NavSatFix & msg){\n\n\t\t//Init ENU frame origin once we receive a first fix\n\t\tif(!gpsFixObtained && msg.status.status >= 0){\n\t\t\tgpsFixObtained = true;\n\t\t\tlatitudeLocalOrigin = msg.latitude;\n\t\t\tlongitudeLocalOrigin = msg.longitude;\n\t\t\taltitudeLocalOrigin = msg.altitude;\n\n\t\t\tROS_INFO(\"GPS Fix obtained. Initializing NED transform at (%f,%f,%f)\",latitudeLocalOrigin,longitudeLocalOrigin,altitudeLocalOrigin);\n\n\t\t\tgeo2ecef(ecefLocalOrigin,latitudeLocalOrigin,longitudeLocalOrigin,altitudeLocalOrigin);\n\n\t\t\tROS_INFO_STREAM(\"Local Origin:\" << ecefLocalOrigin);\n\n\t\t\t//ENU\n\t\t\t//ecef2local << \t-sin(D2R(longitudeLocalOrigin)),\tcos(D2R(longitudeLocalOrigin)),\t0,\n\t\t\t//\t\t-sin(D2R(latitudeLocalOrigin))*cos(D2R(longitudeLocalOrigin)), -sin(D2R(latitudeLocalOrigin))*sin(D2R(longitudeLocalOrigin)), cos(D2R(latitudeLocalOrigin)),\n\t\t\t//\t\tcos(D2R(latitudeLocalOrigin))*cos(D2R(longitudeLocalOrigin)),cos(D2R(latitudeLocalOrigin))*sin(D2R(longitudeLocalOrigin)),sin(D2R(latitudeLocalOrigin));\n\n\t\t\t//NED\n\t\t\tecef2local <<\t-sin(D2R(latitudeLocalOrigin)) * cos(D2R(longitudeLocalOrigin)), -sin(D2R(latitudeLocalOrigin))*sin(D2R(longitudeLocalOrigin)),cos(D2R(latitudeLocalOrigin)),\n\t\t\t\t   \t-sin(D2R(longitudeLocalOrigin)) , cos(D2R(longitudeLocalOrigin)), 0,\n\t\t\t\t\t-cos(D2R(latitudeLocalOrigin))*cos(D2R(longitudeLocalOrigin)), -cos(D2R(latitudeLocalOrigin))*sin(D2R(longitudeLocalOrigin)), -sin(D2R(latitudeLocalOrigin)) ;\n\n\t\t\t//ROS_INFO_STREAM(\"DCM:\" << ecef2local);\n\t\t}\n\t\telse if(gpsFixObtained){\n\t\t\tprocessPosition(msg);\n\t\t}\n\t}\n\n\tvoid processAttitudeCallback(const sensor_msgs::Imu & msg){\n\t\tlastAttitude = msg;\n\t}\n\n\tvoid processLidarCallback(const sensor_msgs::PointCloud2 & msg){\n\t\t//std::cout << \"Got lidar data\" << std::endl;\n\t}\n\n\tvoid processDepthCallback(const geometry_msgs::PointStamped & msg){\n\t\t//FIXME: this is solved in the imagenex driver but not in the rosbag so we need to republish to NED frame\n\t\tgeometry_msgs::PointStamped newMsg = msg;\n\t\tnewMsg.point.z=-1 * msg.point.z;\n\t\tdepthRepublisher.publish(newMsg);\t\t\n\t}\n\n\t/* Publish the odometry transform and Odometry message */\n\tvoid publishOdometry(Eigen::Vector3d & prpPointLocal){\n\n\t\t/* Broadcast the base_link to map transform */\n                geometry_msgs::TransformStamped map_transform;\n                map_transform.header.stamp = ros::Time::now(); //msg.header.stamp;\n                map_transform.header.frame_id = \"map\"; //FIXME: we are assuming that the prp is the base_link origin\n                map_transform.child_frame_id = \"base_link\";\n\n                map_transform.transform.translation.x = prpPointLocal[0];\n                map_transform.transform.translation.y = prpPointLocal[1];\n                map_transform.transform.translation.z = prpPointLocal[2];\n                map_transform.transform.rotation = lastAttitude.orientation;\n\n                transformBroadcaster.sendTransform(map_transform);\n\n                /* Publish the odometry message over ROS */\n                nav_msgs::Odometry odom;\n                odom.header.stamp = ros::Time::now();//msg.header.stamp;\n                odom.header.frame_id = \"odom\";\n\n                //set the position\n                odom.pose.pose.position.x = prpPointLocal[0];\n                odom.pose.pose.position.y = prpPointLocal[1];\n                odom.pose.pose.position.z = prpPointLocal[2];\n\n\t\t//TODO: compensate attitude value using delta t, since our last attitude value dates from a little while back\n                odom.pose.pose.orientation = lastAttitude.orientation;\n\n                //set the velocity\n                odom.child_frame_id = \"base_link\";\n                //odom.twist.twist.linear.x = vx;\n                //odom.twist.twist.linear.y = vy;\n                //odom.twist.twist.angular.z = vth;\n\n                //publish the message\n                odomPublisher.publish(odom);\n\t}\n\n\tvoid processPosition(const sensor_msgs::NavSatFix & msg){\n\t\tif(gpsFixObtained){\n\t\t\tlastPosition = msg;\n\n\t\t\t//transform to ENU\n\t\t\tEigen::Vector3d pointEcef;\n\n\t\t\tgeo2ecef(pointEcef,msg.latitude,msg.longitude,msg.altitude);\n\n\t\t\tEigen::Vector3d pointLocal = ecef2local * (pointEcef - ecefLocalOrigin);\n\n\t\t\t//Update odometry\n\t\t\tpublishOdometry(pointLocal);\n\t\t}\n\t}\n\n\n\n\tvoid run(){\n\t\tros::Rate r(10.0);\n\n\t\t//just spin...\n\t\twhile(n.ok()){\n\t\t\tros::spinOnce();\n\t\t\tr.sleep();\n\t\t}\n\t}\n\nprivate:\n\tros::NodeHandle n;\n        ros::Publisher  odomPublisher;\n\n\tros::Publisher  depthRepublisher;//FIXME: delete this\n\n        ros::Subscriber gpsSubscriber;\n\n        ros::Subscriber positionSubscriber;\n\tros::Subscriber attitudeSubscriber;\n\tros::Subscriber lidarSubscriber;\n\tros::Subscriber depthSubscriber;\n\n\n\n        tf2_ros::TransformBroadcaster transformBroadcaster;\n\n\t//These are used to georeference\n\tsensor_msgs::Imu \tlastAttitude;\n\tsensor_msgs::NavSatFix  lastPosition;\n\n\tbool gpsFixObtained = false;\n\n\t//This DCM is used to transform ECEF coordinates into a local NED frame centered at ecefEnuOrigin\n\tEigen::Matrix3d\tecef2local;\n\n\t//The NED origin is set as the first position when a proper GPS fix is obtained\n\tEigen::Vector3d ecefLocalOrigin;\n\n\t//NED origin in geodesic coordinates\n\tdouble latitudeLocalOrigin;\n\tdouble longitudeLocalOrigin;\n\tdouble altitudeLocalOrigin;\n};\n\nint main(int argc, char** argv){\n  ros::init(argc, argv, \"odometry_publisher\");\n\n  GeoreferenceProvider georefProvider;\n\n  georefProvider.run();\n}\n", "meta": {"hexsha": "e7054df5e84d98e985b7cb5803cc4e4c6fde3bbe", "size": 7184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/workspace/src/echoboat_odometry/src/main.cpp", "max_stars_repo_name": "glabmoris/Poseidon", "max_stars_repo_head_hexsha": "801dad37ab49adc1a31ccfc1e551c02676ad77c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:20:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T21:20:25.000Z", "max_issues_repo_path": "src/workspace/src/echoboat_odometry/src/main.cpp", "max_issues_repo_name": "glabmoris/Poseidon", "max_issues_repo_head_hexsha": "801dad37ab49adc1a31ccfc1e551c02676ad77c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2021-09-07T16:39:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T13:41:07.000Z", "max_forks_repo_path": "src/workspace/src/echoboat_odometry/src/main.cpp", "max_forks_repo_name": "glabmoris/Poseidon", "max_forks_repo_head_hexsha": "801dad37ab49adc1a31ccfc1e551c02676ad77c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-04-01T15:34:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T19:07:08.000Z", "avg_line_length": 35.043902439, "max_line_length": 174, "alphanum_fraction": 0.70155902, "num_tokens": 1876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.6056990754478915}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Array3d v(0, sqrt(2.)/2, 1);\ncout << v.acos() << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "55bce3d40452c621a2016ef82bafa758473a16cf", "size": 206, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Cwise_acos.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_Cwise_acos.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_Cwise_acos.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 13.7333333333, "max_line_length": 30, "alphanum_fraction": 0.640776699, "num_tokens": 65, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835452961427, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6056171832542466}}
{"text": "/*\n * Copyright 2018 Giuseppe Silano, University of Sannio in Benevento, Italy\n * Copyright 2018 Pasquale Oppido, University of Sannio in Benevento, Italy\n * Copyright 2018 Luigi Iannelli, University of Sannio in Benevento, Italy\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"bebop_simulator/transform_datatypes.h\"\n#include \"bebop_simulator/Matrix3x3.h\"\n#include \"bebop_simulator/Quaternion.h\"\n\n#include <math.h> \n#include <ros/ros.h>\n#include <ros/console.h> \n#include <Eigen/Eigen>\n#include <stdio.h>\n#include <boost/bind.hpp>\n\n#include <geometry_msgs/Vector3.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <mav_msgs/conversions.h>\n#include <mav_msgs/default_topics.h>\n#include <mav_msgs/eigen_mav_msgs.h>\n#include <nav_msgs/Odometry.h>\n\n#define M_PI    3.14159265358979323846  /* pi */\n\nros::Publisher rpy_publisher;\nros::Subscriber quat_subscriber;\n\nvoid MsgCallback(const nav_msgs::Odometry odometry_msg)\n{\n    // the incoming geometry_msgs::PoseStamped is transformed to a tf::Quaterion\n    mav_msgs::EigenOdometry odometry;\n    eigenOdometryFromMsg(odometry_msg, &odometry);\n    tf::Quaternion q(odometry.orientation_W_B.x(), odometry.orientation_W_B.y(), odometry.orientation_W_B.z(), \n                     odometry.orientation_W_B.w());\n    tf::Matrix3x3 m(q);\n\n    // the tf::Quaternion has a method to access roll pitch and yaw\n    double roll, pitch, yaw;\n    m.getRPY(roll, pitch, yaw);\n\n    double yaw_degrees = yaw * 180.0 / M_PI; // conversion to degrees\n    if( yaw_degrees < 0 ) yaw_degrees += 360.0; // convert negative to positive angles\n\n    double roll_degrees = roll * 180.0 / M_PI; // conversion to degrees\n    if( roll_degrees < 0 ) roll_degrees += 360.0; // convert negative to positive angles\n\n    double pitch_degrees = pitch * 180.0 / M_PI; // conversion to degrees\n    if( pitch_degrees < 0 ) pitch_degrees += 360.0; // convert negative to positive angles\n\n    // the found angles are written in a geometry_msgs::Vector3\n    geometry_msgs::Vector3 rpy;\n    rpy.x = roll_degrees;\n    rpy.y = pitch_degrees;\n    rpy.z = yaw_degrees;\n\n    // this Vector is then published:\n    rpy_publisher.publish(rpy);\n    ROS_DEBUG(\"published rpy angles: roll=%f pitch=%f yaw=%f\", rpy.x, rpy.y, rpy.z);\n}\n\nint main(int argc, char **argv){\n\n    ros::init(argc, argv, \"quaternion_to_rpy\");\n\n    ros::NodeHandle n;\n\n    rpy_publisher = n.advertise<geometry_msgs::Vector3>(\"orientation_rpy\", 1);\n\n    quat_subscriber = n.subscribe(mav_msgs::default_topics::ODOMETRY, 1, MsgCallback);\n\n    // check for incoming quaternions until ctrl+c is pressed\n    ROS_DEBUG(\"waiting for quaternion\");\n\n    ros::spin();\n\n    return 0;\n}\n", "meta": {"hexsha": "7cc4fdc73c945cb1cf25a56219dc9cc4ce05d7ab", "size": 3162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nodes/quaternion_to_rpy.cpp", "max_stars_repo_name": "ARL-UAV-Simulator/BebopS", "max_stars_repo_head_hexsha": "a0501501fce99cf8028bdd7509c86d83fd822ef7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2019-08-20T18:08:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T12:30:49.000Z", "max_issues_repo_path": "src/nodes/quaternion_to_rpy.cpp", "max_issues_repo_name": "ARL-UAV-Simulator/BebopS", "max_issues_repo_head_hexsha": "a0501501fce99cf8028bdd7509c86d83fd822ef7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T13:25:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-01T11:01:02.000Z", "max_forks_repo_path": "src/nodes/quaternion_to_rpy.cpp", "max_forks_repo_name": "ARL-UAV-Simulator/BebopS", "max_forks_repo_head_hexsha": "a0501501fce99cf8028bdd7509c86d83fd822ef7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2020-02-18T08:09:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T15:29:31.000Z", "avg_line_length": 34.3695652174, "max_line_length": 111, "alphanum_fraction": 0.720113852, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6056171753698211}}
{"text": "/*\n * This file is part of the Visual Computing Library (VCL) release under the\n * MIT license.\n *\n * Copyright (c) 2014 Basil Fierz\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n// VCL configuration\n#include <vcl/config/global.h>\n\n// C++ standard library\n#include <fstream>\n#include <iostream>\n#include <random>\n\n// Eigen library\n#include <Eigen/Dense>\n\n// VCL\n#include <vcl/core/simd/vectorscalar.h>\n#include <vcl/core/interleavedarray.h>\n#include <vcl/math/jacobieigen33_selfadjoint.h>\n#include <vcl/math/jacobieigen33_selfadjoint_quat.h>\n#include <vcl/util/precisetimer.h>\n\ntemplate<typename Scalar>\nVcl::Core::InterleavedArray<Scalar, 3, 3, -1> createProblems(size_t nr_problems)\n{\n\t// Random number generator\n\tstd::mt19937_64 rng;\n\tstd::uniform_real_distribution<float> d;\n\n\tVcl::Core::InterleavedArray<Scalar, 3, 3, -1> F(nr_problems);\n\n\t// Initialize data\n\tfor (int i = 0; i < (int) nr_problems; i++)\n\t{\n\t\tEigen::Matrix<Scalar, 3, 3> rnd;\n\t\trnd << d(rng), d(rng), d(rng),\n\t\t\t   d(rng), d(rng), d(rng),\n\t\t\t   d(rng), d(rng), d(rng);\n\t\tF.template at<Scalar>(i) = rnd.transpose() * rnd;\n\t}\n\n\treturn std::move(F);\n}\n\ntemplate<typename Scalar>\nvoid computeReferenceSolution\n(\n\tsize_t nr_problems,\n\tconst Vcl::Core::InterleavedArray<Scalar, 3, 3, -1>& ATA,\n\tVcl::Core::InterleavedArray<Scalar, 3, 3, -1>& U,\n\tVcl::Core::InterleavedArray<Scalar, 3, 1, -1>& S\n)\n{\n\t// Compute reference using Eigen\n\tfor (int i = 0; i < static_cast<int>(nr_problems); i++)\n\t{\n\t\tVcl::Matrix3f A = ATA.template at<Scalar>(i);\n\n\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix3f> solver;\n\t\tsolver.compute(A, Eigen::ComputeEigenvectors);\n\n\t\tU.template at<Scalar>(i) = solver.eigenvectors();\n\t\tS.template at<Scalar>(i) = solver.eigenvalues();\n\t}\n}\n\ntemplate<typename WideScalar>\nvoid jacobiEig\n(\n\tsize_t nr_problems,\n\tconst Vcl::Core::InterleavedArray<float, 3, 3, -1>& F,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>& resU,\n\tVcl::Core::InterleavedArray<float, 3, 1, -1>& resS\n)\n{\n\tusing real_t = WideScalar;\n\tusing matrix3_t = Eigen::Matrix<real_t, 3, 3>;\n\n\tsize_t width = sizeof(real_t) / sizeof(float);\n\t\n\tint avg_nr_iter = 0;\n\tfor (size_t i = 0; i < nr_problems / width; i++)\n\t{\n\t\t// Map data\n\t\tauto U = resU.at<real_t>(i);\n\t\tauto S = resS.at<real_t>(i);\n\t\t\n\t\t// Compute SVD using 2-sided Jacobi iterations (Brent)\n\t\tmatrix3_t SV = F.at<real_t>(i);\n\t\tmatrix3_t matU = matrix3_t::Identity();\n\n\t\tavg_nr_iter += Vcl::Mathematics::SelfAdjointJacobiEigen(SV, matU);\n\n\t\t// Store results\n\t\tU = matU;\n\t\tS = SV.diagonal();\n\t}\n}\n\t\ntemplate<typename WideScalar>\nvoid jacobiEigQuat\n(\n\tsize_t nr_problems,\n\tconst Vcl::Core::InterleavedArray<float, 3, 3, -1>& F,\n\tVcl::Core::InterleavedArray<float, 3, 3, -1>& resU,\n\tVcl::Core::InterleavedArray<float, 3, 1, -1>& resS\n)\n{\n\tusing real_t = WideScalar;\n\tusing matrix3_t = Eigen::Matrix<real_t, 3, 3>;\n\n\tsize_t width = sizeof(real_t) / sizeof(float);\n\t\n\tint avg_nr_iter = 0;\n\tfor (size_t i = 0; i < nr_problems / width; i++)\n\t{\n\t\t// Map data\n\t\tauto U = resU.at<real_t>(i);\n\t\tauto S = resS.at<real_t>(i);\n\n\t\t// Compute SVD using Jacobi iterations and QR decomposition\n\t\tmatrix3_t SV = F.at<real_t>(i);\n\t\tmatrix3_t matU = matrix3_t::Identity();\n\n\t\tavg_nr_iter += Vcl::Mathematics::SelfAdjointJacobiEigenQuat(SV, matU);\n\n\t\t// Store results\n\t\tU = matU;\n\t\tS = SV.diagonal();\n\t}\n}\n\ntemplate<typename REAL>\nvoid SortEigenvalues(Eigen::Matrix<REAL, 3, 1>& A, Eigen::Matrix<REAL, 3, 3>& B)\n{\n\t// Bubble sort\n\tbool swapped = true;\n\tint j = 0;\n\n\twhile (swapped)\n\t{\n\t\tswapped = false;\n\t\tj++;\n\n\t\tfor (int i = 0; i < 3 - j; i++)\n\t\t{\n\t\t\tif (A(i) > A(i + 1))\n\t\t\t{\n\t\t\t\tstd::swap(A(i), A(i + 1));\n\t\t\t\tB.col(i).swap(B.col(i + 1));\n\n\t\t\t\tswapped = true;\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate<typename Scalar>\nvoid checkSolution\n(\n\tconst char* Name,\n\tconst char* file,\n\tsize_t nr_problems,\n\tScalar tol,\n\tconst Vcl::Core::InterleavedArray<Scalar, 3, 3, -1>& refUa,\n\tconst Vcl::Core::InterleavedArray<Scalar, 3, 1, -1>& refSa,\n\tconst Vcl::Core::InterleavedArray<Scalar, 3, 3, -1>& resUa,\n\tconst Vcl::Core::InterleavedArray<Scalar, 3, 1, -1>& resSa\n)\n{\n\tusing scalar_t = Scalar;\n\t\n\tint wrong_computations, wrong_u_computations;\n\tscalar_t accum_error, accum_u_error;\n\tstd::ofstream fout;\n\t\n\twrong_computations = 0;\n\twrong_u_computations = 0;\n\taccum_error = 0;\n\taccum_u_error = 0;\n\tfout.open(file);\n\t\n\tfor (int j = 0; j < (int) nr_problems; j++)\n\t{\n\t\tVcl::Matrix3f refU = refUa.template at<scalar_t>(j);\n\t\tVcl::Vector3f refS = refSa.template at<scalar_t>(j);\n\t\tVcl::Matrix3f cU = resUa.template at<scalar_t>(j);\n\t\tVcl::Vector3f cS = resSa.template at<scalar_t>(j);\n\n\t\tSortEigenvalues(cS, cU);\n\n\t\tbool eqU = refU.array().abs().isApprox(cU.array().abs(), tol);\n\t\tbool eqS = refS.array().abs().isApprox(cS.array().abs(), tol);\n\n\t\tif (!eqS || !eqU)\n\t\t\tfout << j;\n\n\t\tif (!eqS)\n\t\t{\n\t\t\twrong_computations++;\n\t\t\tscalar_t err = abs((refS.array().abs() - cS.array().abs()).sum() / scalar_t(3));\n\t\t\taccum_error += err;\n\t\t\tfout << \", E: \" << err;\n\t\t}\n\t\tif (!eqU)\n\t\t{\n\t\t\twrong_u_computations++;\n\t\t\tscalar_t err = abs((refU.array().abs() - cU.array().abs()).sum() / scalar_t(9));\n\t\t\taccum_u_error += err;\n\t\t\tfout << \", U: \" << err;\n\t\t}\n\t\tif (!eqS || !eqU)\n\t\t\tfout << std::endl;\n\t}\n\t\n\tfout.close();\n\tstd::cout << Name << \" - Errors: (\" << wrong_computations << \", \" << wrong_u_computations << \"), \"\n\t\t\t  << \"Avg. Singular value error: \" << accum_error / std::max(wrong_computations, 1) << \", \"\n\t\t\t  << \"Avg. U error: \" << accum_u_error / std::max(wrong_u_computations, 1) << std::endl;\n}\n\t\nint main(int, char**)\n{\n\tsize_t nr_problems = 1024*1024;\n\n\tusing scalar_t = float;\n\n\tVcl::Core::InterleavedArray<scalar_t, 3, 3, -1> resU(nr_problems);\n\tVcl::Core::InterleavedArray<scalar_t, 3, 1, -1> resS(nr_problems);\n\n\tVcl::Core::InterleavedArray<scalar_t, 3, 3, -1> refU(nr_problems);\n\tVcl::Core::InterleavedArray<scalar_t, 3, 1, -1> refS(nr_problems);\n\n\tauto F = createProblems<scalar_t>(nr_problems);\n\tcomputeReferenceSolution(nr_problems, F, refU, refS);\n\n\t// Test correctness: Two-sided Jacobi SVD (Brent)\n\tjacobiEig<float>(nr_problems, F, resU, resS);        checkSolution(\"JacobiEigen - float\",   \"jacobi_eigen_float_errors.txt\",   nr_problems, 1e-5f, refU, refS, resU, resS);\n\tjacobiEig<Vcl::float4>(nr_problems, F, resU, resS);  checkSolution(\"JacobiEigen - float4\",  \"jacobi_eigen_float4_errors.txt\",  nr_problems, 1e-5f, refU, refS, resU, resS);\n\tjacobiEig<Vcl::float8>(nr_problems, F, resU, resS);  checkSolution(\"JacobiEigen - float8\",  \"jacobi_eigen_float8_errors.txt\",  nr_problems, 1e-5f, refU, refS, resU, resS);\n\tjacobiEig<Vcl::float16>(nr_problems, F, resU, resS); checkSolution(\"JacobiEigen - float16\", \"jacobi_eigen_float16_errors.txt\", nr_problems, 1e-5f, refU, refS, resU, resS);\n\t\n\t// Test correctness: Jacobi SVD with symmetric EV computation and QR decomposition\n\tjacobiEigQuat<float>(nr_problems, F, resU, resS);        checkSolution(\"JacobiEigenQuat - float\",   \"jacobi_eigen_quat_float_errors.txt\",   nr_problems, 1e-5f, refU, refS, resU, resS);\n\tjacobiEigQuat<Vcl::float8>(nr_problems, F, resU, resS);\t checkSolution(\"JacobiEigenQuat - float8\",  \"jacobi_eigen_quat_float8_errors.txt\",  nr_problems, 1e-5f, refU, refS, resU, resS);\n\tjacobiEigQuat<Vcl::float4>(nr_problems, F, resU, resS);\t checkSolution(\"JacobiEigenQuat - float4\",  \"jacobi_eigen_quat_float4_errors.txt\",  nr_problems, 1e-5f, refU, refS, resU, resS);\n\tjacobiEigQuat<Vcl::float16>(nr_problems, F, resU, resS); checkSolution(\"JacobiEigenQuat - float16\", \"jacobi_eigen_quat_float16_errors.txt\", nr_problems, 1e-5f, refU, refS, resU, resS);\n}\n", "meta": {"hexsha": "759b7eb5f84abf817ee174f15209dde27de90c99", "size": 8517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/benchmarks/eigen33correctness/main.cpp", "max_stars_repo_name": "bschindler/vcl", "max_stars_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/benchmarks/eigen33correctness/main.cpp", "max_issues_repo_name": "bschindler/vcl", "max_issues_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/benchmarks/eigen33correctness/main.cpp", "max_forks_repo_name": "bschindler/vcl", "max_forks_repo_head_hexsha": "1921da5eb9c60923e9012fe96fcc94ed24835895", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5444444444, "max_line_length": 185, "alphanum_fraction": 0.6860396853, "num_tokens": 2838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6056171713769486}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_TWO_ADD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_TWO_ADD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing two_add capabilities\n\n    For any two reals @c x and @c y two_add computes two reals (in an std::pair)\n    @c r0 and @c r1 such that:\n\n    @code\n    r0 = x + y\n    r1 = r0 -(x + y)\n    @endcode\n\n    using perfect arithmetic.\n\n    Its main usage is to be able to compute\n    sum of reals and the residual error using IEEE  754 arithmetic.\n\n  **/\n  std::pair<Value, Value> two_add(Value const& x, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/two_add.hpp>\n#include <boost/simd/function/simd/two_add.hpp>\n\n#endif\n", "meta": {"hexsha": "d8f29ce0677ae943fdf46aba63f9e4e85ceaf273", "size": 1152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/two_add.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/function/two_add.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/two_add.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 25.6, "max_line_length": 100, "alphanum_fraction": 0.5868055556, "num_tokens": 261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180245, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6056171704040603}}
{"text": "#include \"opencv2/core/core.hpp\"\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/calib3d/calib3d.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include <iostream>\n#include <fstream>\n#include <boost/format.hpp> // for formatting strings\n \nusing namespace cv;\nusing namespace std;\n\nint main(int argc, char **argv) \n{\n    ifstream fin(\"calibdata.txt\"); /* \u6807\u5b9a\u6240\u7528\u56fe\u50cf\u6587\u4ef6\u7684\u8def\u5f84 */\n\tofstream fout(\"caliberation_result.txt\");  /* \u4fdd\u5b58\u6807\u5b9a\u7ed3\u679c\u7684\u6587\u4ef6 */\t\n    //\u8bfb\u53d6\u6bcf\u4e00\u5e45\u56fe\u50cf\uff0c\u4ece\u4e2d\u63d0\u53d6\u51fa\u89d2\u70b9\uff0c\u7136\u540e\u5bf9\u89d2\u70b9\u8fdb\u884c\u4e9a\u50cf\u7d20\u7cbe\u786e\u5316\t\n\tint image_count=0;  /* \u56fe\u50cf\u6570\u91cf */\n\tint valid_image_count = 0; // \u80fd\u6210\u529f\u63d0\u53d6\u51fa\u89d2\u70b9\u7684\u56fe\u50cf\u6570\u91cf\n\tSize image_size;  /* \u56fe\u50cf\u7684\u5c3a\u5bf8 */\n\tSize board_size = Size(9,6);    /* \u6807\u5b9a\u677f\u4e0a\u6bcf\u884c\u3001\u5217\u7684\u89d2\u70b9\u6570 */\n\tvector<Point2f> image_points_buf;  /* \u7f13\u5b58\u6bcf\u5e45\u56fe\u50cf\u4e0a\u68c0\u6d4b\u5230\u7684\u89d2\u70b9 */\n\tvector<vector<Point2f>> image_points_seq; // \u4fdd\u5b58\u68c0\u6d4b\u5230\u7684\u6240\u6709\u89d2\u70b9\n\tstring filename;\n\tint count= -1 ;//\u7528\u4e8e\u5b58\u50a8\u89d2\u70b9\u4e2a\u6570\u3002\n\n\t\n    while (getline(fin, filename))\n    {\n\t\timage_count++;\n        cv::Mat rawImageInput = cv::imread(filename);\n        cv::Mat imageInput = rawImageInput;\n        if (image_count == 1)\n        {\n            image_size.width = imageInput.cols;\n            image_size.height = imageInput.rows;\n            cout << \"image_size = \" <<  image_size << endl;\n\t\t\tcout << \"\u5f00\u59cb\u63d0\u53d6\u89d2\u70b9\u2026\u2026\u2026\u2026\u2026\u2026\" << endl;\n        }\n\n        // \u7528\u4e8e\u89c2\u5bdf\u68c0\u9a8c\u8f93\u51fa\n\t\tcout<<\"image_count = \"<<image_count<<endl;\t\n\n        boost::format fmt(\"%s %d\");\n        // cv::imshow((fmt % \"imageInput\" % image_count).str(), imageInput);\n        // cv::waitKey(0);\n        \n        if (0 == findChessboardCorners(imageInput,board_size,image_points_buf))\n\t\t{\t\t\t\n\t\t\tcout<<\"can not find chessboard corners!\\n\"; //\u627e\u4e0d\u5230\u89d2\u70b9\n\t\t\t// exit(1);\n\t\t} \n\t\telse \n\t\t{\n\t\t\tvalid_image_count++;\n\t\t\tMat view_gray;\n\t\t\tcvtColor(imageInput,view_gray,CV_RGB2GRAY);\n\t\t\t/* \u4e9a\u50cf\u7d20\u7cbe\u786e\u5316 */\n\t\t\t//find4QuadCornerSubpix(view_gray,image_points_buf,Size(5,5)); //\u5bf9\u7c97\u63d0\u53d6\u7684\u89d2\u70b9\u8fdb\u884c\u7cbe\u786e\u5316\n\t\t\tcornerSubPix(view_gray,image_points_buf,Size(11,11),Size(-1,-1),TermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,0.1));\n\t\t\t\n\t\t\timage_points_seq.push_back(image_points_buf);  //\u4fdd\u5b58\u4e9a\u50cf\u7d20\u89d2\u70b9\n\t\t\t/* \u5728\u56fe\u50cf\u4e0a\u663e\u793a\u89d2\u70b9\u4f4d\u7f6e */\n\t\t\tdrawChessboardCorners(view_gray,board_size,image_points_buf,false); //\u7528\u4e8e\u5728\u56fe\u7247\u4e2d\u6807\u8bb0\u89d2\u70b9\n\t\t\tcv::imshow((fmt % \"Camera Calibration\" % image_count).str(),view_gray);//\u663e\u793a\u56fe\u7247\t\n\t\t}\n    }\n    cv::waitKey(500);\n\tcout << \"\u89d2\u70b9\u63d0\u53d6\u5b8c\u6210\uff0c\" << \"\u6709\u6548\u56fe\u7247\u6570=\" << valid_image_count << endl << endl;\n\n\n\t// \u6444\u50cf\u673a\u6807\u5b9a\n\tcout << \"\u5f00\u59cb\u6807\u5b9a......\" << endl;\n\tSize square_size = Size(50, 50); // \u5b9e\u9645\u6d4b\u91cf\u5f97\u5230\u7684\u6807\u5b9a\u677f\u4e0a\u6bcf\u4e2a\u68cb\u76d8\u683c\u7684\u5927\u5c0f\n\tvector<vector<Point3f>> objectPoints;  // \u4fdd\u5b58\u6807\u5b9a\u677f\u4e0a\u89d2\u70b9\u7684\u4e09\u7ef4\u5750\u6807\n\n\t// vector<vector<Point3f>> objectPoints(1);\n    // calcBoardCornerPositions(board_size, square_size, objectPoints[0]);\n\n    // objectPoints.resize(image_points_seq.size(), objectPoints[0]);\n\n\tMat cameraMatrix= Mat::eye(3, 3, CV_64F); // \u5b9a\u4e49\u76f8\u673a\u5185\u53c2\u77e9\u9635\n\tvector<int> point_counts;  // \u6bcf\u5e45\u56fe\u50cf\u4e2d\u89d2\u70b9\u7684\u6570\u91cf\n\tMat distCoeffs = Mat::zeros(1, 5, CV_64F);  // \u6444\u50cf\u673a\u7684\u4e94\u4e2a\u7578\u53d8\u7cfb\u6570: k1 k2 p1 p2 k2\n\tvector<Mat> tvecsMat;  //\u6bcf\u5e45\u56fe\u50cf\u7684\u8bc4\u8bae\u5411\u91cf  \n\tvector<Mat> rvecsMat;  //\u6bcf\u5e45\u56fe\u50cf\u7684\u65cb\u8f6c\u5411\u91cf\n\t// \u8ba1\u7b97\u89d2\u70b9\u7684\u771f\u5b9e\u5750\u6807\uff08\u5047\u5b9a\u5728z=0\u5e73\u9762\u4e0a\uff09\n\tfor (int n=0; n < valid_image_count; n++)\n\t{\n\t\tvector<Point3f> tempPointSet;\n\t\tfor (int u=0; u < board_size.height; ++u)\n\t\t{\n\t\t\tfor (int v=0; v < board_size.width; ++v)\n\t\t\t{\n\t\t\t\tPoint3f realPoint;\n\t\t\t\trealPoint.x = v * square_size.width;\n\t\t\t\trealPoint.y = u * square_size.height;\n\t\t\t\trealPoint.z = 0;\n\t\t\t\ttempPointSet.push_back(realPoint);\n\t\t\t}\n\t\t}\n\t\t// cout << \"\u771f\u5b9e\u89d2\u70b9\uff1a\" << endl << tempPointSet << endl;\n\t\tobjectPoints.push_back(tempPointSet);\n\t}\n\t// \u6807\u5b9a\n\tint flags = 0;\n\tflags = CV_CALIB_FIX_PRINCIPAL_POINT | CV_CALIB_FIX_ASPECT_RATIO;\n\tcalibrateCamera(objectPoints, image_points_seq, image_size, cameraMatrix, distCoeffs, rvecsMat, tvecsMat, flags);\n\tcout << \"\u6807\u5b9a\u5b8c\u6210!\" << endl << endl;\n\n\n\t// \u5bf9\u6807\u5b9a\u7ed3\u679c\u8fdb\u884c\u8bc4\u4ef7\n\tcout << \"\u5f00\u59cb\u8bc4\u4ef7\u6807\u5b9a\u7ed3\u679c......\" << endl;\n\tvector<Point2f> image_points_new;\n\n\tfor(int i=0; i < image_count; i++)\n\t{\n\t\tvector<Point3f> tempPointSet = objectPoints[i];\n\t\tprojectPoints(objectPoints[i], rvecsMat[i], tvecsMat[i], cameraMatrix, distCoeffs, image_points_new);\n\n\t}\n\t\n    \n\n\n\n\n\t\n\n\n\n\n    return 0;\n}", "meta": {"hexsha": "da4a70fd99f6bec7a0a5da02822af88b72147020", "size": 3867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_1/ch5/cameraCalibration/calibration.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/ch5/cameraCalibration/calibration.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/ch5/cameraCalibration/calibration.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": 29.0751879699, "max_line_length": 122, "alphanum_fraction": 0.6604603051, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6056171664111878}}
{"text": "//\n// Created by krab1k on 27.08.20.\n//\n\n#include <vector>\n#include <cmath>\n#include <Eigen/LU>\n\n#include \"sqeq0.h\"\n#include \"../parameters.h\"\n#include \"../geometry.h\"\n\nCHARGEFW2_METHOD(SQEq0)\n\n\nstd::vector<double> SQEq0::calculate_charges(const Molecule &molecule) const {\n\n    size_t n = molecule.atoms().size();\n    size_t m = molecule.bonds().size();\n\n    Eigen::VectorXd q0 = Eigen::VectorXd::Zero(n);\n    Eigen::VectorXd hardness = Eigen::VectorXd::Zero(n);\n\n    for (size_t i = 0; i < n; i++) {\n        const auto &atom = molecule.atoms()[i];\n        q0(i) = atom.formal_charge();\n        hardness(i) = parameters_->atom()->parameter(atom::hardness)(atom);\n    }\n\n    Eigen::MatrixXd T = Eigen::MatrixXd::Zero(m, n);\n    for (size_t i = 0; i < molecule.bonds().size(); i++) {\n        const auto &bond = molecule.bonds()[i];\n        auto i1 = bond.first().index();\n        auto i2 = bond.second().index();\n        T(i, i1) = 1;\n        T(i, i2) = -1;\n    }\n\n    Eigen::MatrixXd A = Eigen::MatrixXd::Zero(n, n);\n    Eigen::VectorXd b = Eigen::VectorXd::Zero(n);\n\n    /* Setup EEM part */\n    for (size_t i = 0; i < n; i++) {\n        const auto &atom_i = molecule.atoms()[i];\n        A(i, i) = hardness(i);\n        b(i) = -parameters_->atom()->parameter(atom::electronegativity)(atom_i);\n        for (size_t j = i + 1; j < n; j++) {\n            const auto &atom_j = molecule.atoms()[j];\n            auto d = distance(atom_i, atom_j);\n            auto wi = parameters_->atom()->parameter(atom::width)(atom_i);\n            auto wj = parameters_->atom()->parameter(atom::width)(atom_j);\n            auto d0 = sqrt(2 * wi * wi + 2 * wj * wj);\n            auto x = erf(d / d0) / d;\n            A(i, j) = x;\n            A(j, i) = x;\n        }\n    }\n\n    b = b - A * q0;\n    b = b + hardness.cwiseProduct(q0);\n\n    Eigen::MatrixXd split_A = T * A * T.transpose();\n    Eigen::VectorXd split_b = T * b;\n\n    for (size_t i = 0; i < molecule.bonds().size(); i++) {\n        const auto &bond = molecule.bonds()[i];\n        split_A(i, i) += parameters_->bond()->parameter(bond::kappa)(bond);\n    }\n\n    Eigen::VectorXd split_q = split_A.partialPivLu().solve(split_b);\n    Eigen::VectorXd q = T.transpose() * split_q + q0;\n\n    return std::vector<double>(q.data(), q.data() + n);\n}\n", "meta": {"hexsha": "ae9aaf4fc65655d88ce653cbed06a306e9271ffa", "size": 2271, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/sqeq0.cpp", "max_stars_repo_name": "danny305/ChargeFW2", "max_stars_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T15:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:38:09.000Z", "max_issues_repo_path": "src/methods/sqeq0.cpp", "max_issues_repo_name": "danny305/ChargeFW2", "max_issues_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-03-04T21:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T07:11:19.000Z", "max_forks_repo_path": "src/methods/sqeq0.cpp", "max_forks_repo_name": "danny305/ChargeFW2", "max_forks_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T00:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T05:47:39.000Z", "avg_line_length": 30.28, "max_line_length": 80, "alphanum_fraction": 0.5504183179, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.6055938651033534}}
{"text": "//\n// Created by denn nevera on 2019-09-03.\n//\n\n#pragma once\n\n#include <armadillo>\n\nnamespace dehancer{\n\n        namespace math {\n\n            using float2x2 = arma::fmat::fixed<2, 2>;\n            using float3x3 = arma::fmat::fixed<3, 3>;\n            using float4x4 = arma::fmat::fixed<4, 4>;\n        }\n}\n", "meta": {"hexsha": "361305b37aee4bab4f612f08d07425ebec81e949", "size": 305, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dehancer/matrix.hpp", "max_stars_repo_name": "dehancer/dehancer-maths-cpp", "max_stars_repo_head_hexsha": "7183e240a93be50b672b25edef9f99ed63f01834", "max_stars_repo_licenses": ["MIT"], "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/dehancer/matrix.hpp", "max_issues_repo_name": "dehancer/dehancer-maths-cpp", "max_issues_repo_head_hexsha": "7183e240a93be50b672b25edef9f99ed63f01834", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dehancer/matrix.hpp", "max_forks_repo_name": "dehancer/dehancer-maths-cpp", "max_forks_repo_head_hexsha": "7183e240a93be50b672b25edef9f99ed63f01834", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-10T11:52:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T11:52:08.000Z", "avg_line_length": 16.9444444444, "max_line_length": 53, "alphanum_fraction": 0.5540983607, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6055825469924193}}
{"text": "#include \"localizationkf.h\"\n#include \"Storage/logController.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include <Eigen/Sparse>\n\n#include <math.h>\n\nLocalizationKF::LocalizationKF(LogController& logcontroller):\n_logcontroller(logcontroller)\n{};\n\nvoid LocalizationKF::setup(){\n    //this current intializaiton method means the filter will take time to converge to the solution\n    X = Eigen::Vector<float,6>::Zero();\n    P = Eigen::Matrix<float,6,6>::Identity(); // initialize as identity matrix for ease -> can update this later\n};\n\nvoid LocalizationKF::predict(const Eigen::Vector3f& linear_acceleration,float dt){\n    const Eigen::Matrix<float,6,6> A{{1, dt, 0, 0, 0, 0},\n                                     {0, 1, 0, 0, 0, 0},\n                                     {0, 0, 1, dt, 0, 0},\n                                     {0, 0, 0, 1, 0, 0},\n                                     {0, 0, 0, 0, 1, dt},\n                                     {0, 0, 0, 0, 0, 1}}; // construct state transition sub matrix\n\n    const float dt2 = dt*dt;//temporary for readability\n    const float dt3 = dt2*dt;\n    const Eigen::Matrix<float,6,3> B{{dt2/2, 0, 0},\n                                     {dt, 0, 0},\n                                     {0, dt2/2, 0},\n                                     {0, dt, 0},\n                                     {0, 0, dt2/2},\n                                     {0, 0,dt}}; // construct control sub matrix\n\n    //dt^4 terms are considered negligible so have been estimated as zero\n    const Eigen::Matrix<float,6,6> Q = accelVariance * Eigen::Matrix<float,6,6> {{0, dt3/2, 0, 0, 0, 0},\n                                                                                 {dt3/2, dt2, 0, 0, 0, 0},\n                                                                                 {0, 0, 0, dt3/2, 0, 0},\n                                                                                 {0, 0, dt3/2, dt2, 0, 0},\n                                                                                 {0, 0, 0, 0, 0, dt3/2},\n                                                                                 {0, 0, 0, 0, dt3/2, dt2}}; // construct state transition sub matrix\n\n\n    //update State \n    X = (A*X) + (B*linear_acceleration);\n    //update Covariance estimate\n    P = A*P*A.transpose() + Q; \n}\n\nvoid LocalizationKF::gpsUpdate(const float lat, const float lng, const long alt,const long vn, const long ve, const long vd){\n    //measurement matrix\n    Eigen::Vector3f positionNED = GPStoNED(lat,lng,alt); \n    const Eigen::Vector<float,6> z{{positionNED(0),\n                                    ((float)vn)/1000.0f, //conversion to m/s\n                                    positionNED(1),\n                                    ((float)ve)/1000.0f,\n                                    positionNED(2),\n                                    ((float)vd)/1000.0f}};\n\n    //System Uncertainty\n    Eigen::Matrix<float,6,6> S_GPS = P+R_GPS.toDenseMatrix();\n    //Kalman Gain\n    Eigen::Matrix<float,6,6> K_GPS = P*(S_GPS).inverse();\n    //Reisdual\n    Eigen::Vector<float,6> Y_GPS = z-X;\n    //State update\n    X = X + (K_GPS*Y_GPS);\n    //Covariance update\n    P = ( (Eigen::Matrix<float,6,6>::Identity() - K_GPS) * P * ((Eigen::Matrix<float,6,6>::Identity() - K_GPS).transpose()) ) + (K_GPS*R_GPS*K_GPS.transpose());\n        \n}\n\nvoid LocalizationKF::updateGPSReference(const float lat, const float lng, const long alt){\n    _gpsReferenceECEF = GPStoECEF(lat,lng,alt);\n    _gpsReferenceSLat = sin(lat * degtorad);\n    _gpsReferenceCLat = cos(lat * degtorad);\n    _gpsReferenceSLng = sin(lng * degtorad);\n    _gpsReferenceCLng = cos(lng * degtorad);\n}\n\nEigen::Vector3f LocalizationKF::GPStoECEF(const float lat, const float lng,const long alt){\n    const float slat = sin(lat * degtorad);\n    const float clat = cos(lat * degtorad);\n    const float slng = sin(lng * degtorad);\n    const float clng = cos(lng * degtorad);\n\n    const float ecefN = earthMajorAxis/sqrt(1-(earthEccentricity2*slat*slat));\n    const float h = alt/1000.0f; //conversion from mm to m\n\n    float ecefX = (ecefN + h)*clat*clng;\n    float ecefY = (ecefN + h)*clat*slng;\n    float ecefZ = (((1-earthEccentricity2)*ecefN) + h)*slat; \n\n    return Eigen::Vector3f{ecefX,ecefY,ecefZ};\n}\n\nEigen::Vector3f LocalizationKF::GPStoNED(const float lat, const float lng, const long alt){\n    Eigen::Matrix3f  _tangentPlane{{-_gpsReferenceSLng, _gpsReferenceCLng, 0},\n                                   {-_gpsReferenceSLat*_gpsReferenceCLng, -_gpsReferenceSLat*_gpsReferenceSLng, _gpsReferenceCLat},\n                                   {_gpsReferenceCLat*_gpsReferenceCLng, _gpsReferenceCLat*_gpsReferenceSLng, _gpsReferenceSLat}};\n    Eigen::Vector3f ENU = _tangentPlane * (GPStoECEF(lat,lng,alt) - _gpsReferenceECEF);\n    Eigen::Vector3f NED({ENU(1),ENU(0),-ENU(2)});\n    return NED;\n}", "meta": {"hexsha": "f5957807e86f344a54c21178f25f1fdb4dd0725a", "size": 4873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Ricardo_OS/Ricardo_OS/src/Sensors/localizationkf.cpp", "max_stars_repo_name": "icl-rocketry/Avionics", "max_stars_repo_head_hexsha": "4fadbccb1cafe4be80c76e15a2546bbb8414398b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T18:35:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T13:34:25.000Z", "max_issues_repo_path": "Ricardo_OS/Ricardo_OS/src/Sensors/localizationkf.cpp", "max_issues_repo_name": "icl-rocketry/Avionics", "max_issues_repo_head_hexsha": "4fadbccb1cafe4be80c76e15a2546bbb8414398b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-02-15T08:29:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T02:13:06.000Z", "max_forks_repo_path": "Ricardo_OS/Ricardo_OS/src/Sensors/localizationkf.cpp", "max_forks_repo_name": "icl-rocketry/Avionics", "max_forks_repo_head_hexsha": "4fadbccb1cafe4be80c76e15a2546bbb8414398b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-06T05:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-06T05:20:51.000Z", "avg_line_length": 45.5420560748, "max_line_length": 160, "alphanum_fraction": 0.5292427663, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9559813488829418, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.6055283916515072}}
{"text": "/**\n * \\file libs/numeric/ublasx/test/sign.cpp\n *\n * \\brief Test suite for the \\c sign operation.\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 comcon1 based on code of Marco Guazzone\n */\n\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublasx/operation/sign.hpp>\n#include <cmath>\n#include <complex>\n#include <cstddef>\n#include \"libs/numeric/ublasx/test/utils.hpp\"\n\n\nnamespace ublas = ::boost::numeric::ublas;\nnamespace ublasx = ::boost::numeric::ublasx;\n\n\nstatic const double tol = 1.0e-15;\n\n\nBOOST_UBLASX_TEST_DEF( test_real_vector )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Vector\" );\n\n\ttypedef double value_type;\n\ttypedef std::size_t size_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\n\tconst size_type n(4);\n\n\tvector_type v(n);\n\n\tv(0) =  0.0;\n\tv(1) = -2.0;\n\tv(2) = -3.0;\n\tv(3) =  4.0;\n\n\tvector_type res;\n\tvector_type expect_res(n);\n\n\tres = ublasx::sign(v);\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"v = \" << v );\n\tBOOST_UBLASX_DEBUG_TRACE( \"abs(v) = \" << res );\n\n\tfor (size_type i = 0; i < n; ++i)\n\t{\n\t\texpect_res(i) = v(i) >= 0 ? +1.0 : -1.0;\n\t}\n\n\tBOOST_UBLASX_TEST_CHECK_VECTOR_CLOSE( res, expect_res, n, tol );\n}\n\n\nBOOST_UBLASX_TEST_DEF( test_real_matrix )\n{\n\tBOOST_UBLASX_DEBUG_TRACE( \"Test Case: Real - Matrix\" );\n\n\ttypedef double value_type;\n\ttypedef std::size_t size_type;\n\ttypedef ublas::matrix<value_type> matrix_type;\n\n\tconst size_type nr(2);\n\tconst size_type nc(3);\n\n\tmatrix_type A(nr,nc);\n\n\tA(0,0) =  0; A(0,1) = -2; A(0,2) = -3;\n\tA(1,0) = -4; A(1,1) =  5; A(1,2) =  6;\n\n\tmatrix_type R;\n\tmatrix_type expect_R(nr,nc);\n\n\tR = ublasx::sign(A);\n\n\tBOOST_UBLASX_DEBUG_TRACE( \"A = \" << A );\n\tBOOST_UBLASX_DEBUG_TRACE( \"abs(A) = \" << R );\n\n\tfor (size_type r = 0; r < nr; ++r)\n\t{\n\t\tfor (size_type c = 0; c < nc; ++c)\n\t\t{\n\t\t\texpect_R(r,c) = A(r,c) >= 0 ? +1.0 : -1.0;\n\t\t}\n\t}\n\n\tBOOST_UBLASX_TEST_CHECK_MATRIX_CLOSE( R, expect_R, nr, nc, tol );\n}\n\n\nint main()\n{\n\n\tBOOST_UBLASX_DEBUG_TRACE(\"Test Suite: 'sign' operation\");\n\n\tBOOST_UBLASX_TEST_BEGIN();\n\n\tBOOST_UBLASX_TEST_DO( test_real_vector );\n\tBOOST_UBLASX_TEST_DO( test_real_matrix );\n\n\tBOOST_UBLASX_TEST_END();\n}\n", "meta": {"hexsha": "e28ea0f37f8f87bc419a01d160032093f6554e84", "size": 2298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublasx/test/sign.cpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/numeric/ublasx/test/sign.cpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/ublasx/test/sign.cpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5178571429, "max_line_length": 66, "alphanum_fraction": 0.6731940818, "num_tokens": 768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.6055235202409641}}
{"text": "// spawn robot swarm at customized quantity, positions and orientation using gazebo service\n// this node is to be invoked in a launch file for environment setting of gazebo\n\n// parameters from parameter server\n    // robot name: /swarm_sim/robot_name\n    // robot urdf: /swarm_sim/robot_name_urdf (replace robot_name with the real name)\n    // robot quantity: /robot_quantity\n    // robot distribution range: /half_range\n\n#include <ros/ros.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <gazebo_msgs/SpawnModel.h>\n#include <geometry_msgs/Pose.h>\n#include <Eigen/Geometry>\n\nusing namespace Eigen;\n\nMatrix<double, Dynamic, 3> randomGenerator(int quantity, double half_range) {\n    // input the quantity of swarm robots and position range, output the pose message\n\n    MatrixXd random_matrix;  // output data\n    random_matrix.resize(quantity, 3);\n    // first colomn for position.x\n    // second colomn for position.y\n    // third colomn for rotation angle\n    random_matrix = MatrixXd::Random(quantity, 3);  // generate random numbers in (-1, 1)\n\n    // map data, 1st & 2nd colomns to (-half_range, half_range), 3rd to (-M_PI, M_PI)\n    random_matrix.col(0) = random_matrix.col(0) * half_range;\n    random_matrix.col(1) = random_matrix.col(1) * half_range;    \n    random_matrix.col(2) = random_matrix.col(2) * M_PI;\n\n    return random_matrix;\n}\n\n// int to string converter\nstd::string intToString(int a) {\n    std::stringstream ss;\n    ss << a;\n    return ss.str();\n}\n\nint main(int argc, char **argv) {\n    ros::init(argc, argv, \"swarm_spawner_gazebo_client\");\n    ros::NodeHandle nh;\n    // service client for service /gazebo/spawn_urdf_model\n    ros::ServiceClient client = nh.serviceClient<gazebo_msgs::SpawnModel>(\"/gazebo/spawn_urdf_model\");\n    gazebo_msgs::SpawnModel spawn_model_srv_msg;  // service message\n    geometry_msgs::Pose model_pose;  // model pose message for service message\n\n    // make sure /gazebo/spawn_urdf_model service is ready\n    bool service_ready = false;\n    while (!service_ready) {\n        service_ready = ros::service::exists(\"/gazebo/spawn_urdf_model\",true);\n        ROS_INFO(\"waiting for spawn_urdf_model service\");\n        ros::Duration(0.5).sleep();\n    }\n    ROS_INFO(\"spawn_urdf_model service is ready\");\n\n    // commenting out the following line also works fine, just feel safe to wait for a while\n    ros::Duration(1.0).sleep();  // wait for gazebo to be initialized\n\n    // get initialization information of robot swarm from parameter\n    std::string robot_model_name;\n    std::string robot_model_path;\n    int robot_quantity;\n    double half_range;\n    bool get_name, get_path, get_quantity, get_range;\n    get_name = nh.getParam(\"/robot_model_name\", robot_model_name);\n    // absolute path described from the root directory\n    get_path = nh.getParam(\"/robot_model_path\", robot_model_path);\n    get_quantity = nh.getParam(\"/robot_quantity\", robot_quantity);\n    get_range = nh.getParam(\"/half_range\", half_range);\n    if (!(get_name && get_path && get_quantity && get_range))\n        return 0;  // return if fail to get parameters\n\n    // prepare the xml for service call, read urdf into string\n    std::ifstream inXml;\n    std::stringstream strStream;\n    std::string xmlStr;\n    // finds out the path when launching the launch file is \"/home/yang/.ros\"\n    // instead of the path of the terminal when running launch file\n    // char the_path[256];\n    // getcwd(the_path, 255);\n    // ROS_INFO_STREAM(the_path);\n    inXml.open(robot_model_path.c_str());  // why is c_str() needed?\n    strStream << inXml.rdbuf();\n    xmlStr = strStream.str();\n    // prepare the service message\n    spawn_model_srv_msg.request.model_xml = xmlStr;\n    spawn_model_srv_msg.request.initial_pose.position.z = 0.0;\n    spawn_model_srv_msg.request.initial_pose.orientation.x = 0.0;\n    spawn_model_srv_msg.request.initial_pose.orientation.y = 0.0;\n    spawn_model_srv_msg.request.reference_frame = \"world\";\n    // prepare: the random numbers used in the service call, the position and orientation\n    MatrixXd randomNumbers;\n    randomNumbers = randomGenerator(robot_quantity, half_range);\n\n    // begin spawn robot through gazebo service\n    for (int i=0; i<robot_quantity; i++) {\n        std::string index_string = intToString(i);\n        // prepare service message for each swarm robot\n        spawn_model_srv_msg.request.model_name = robot_model_name + \"_\" + index_string;\n        spawn_model_srv_msg.request.robot_namespace = robot_model_name + \"_\" + index_string;\n        spawn_model_srv_msg.request.initial_pose.position.x = randomNumbers(i, 0);\n        spawn_model_srv_msg.request.initial_pose.position.y = randomNumbers(i, 1);\n        // calculate the quaternion from random orientation angle\n        AngleAxisf aaf(randomNumbers(i, 2), Vector3f::UnitZ());\n        Quaternionf qf(aaf);  // convert to quaternion\n        // only z & w need to be changed, because of rotation along z axis\n        spawn_model_srv_msg.request.initial_pose.orientation.z = qf.z();\n        spawn_model_srv_msg.request.initial_pose.orientation.w = qf.w();\n\n        ROS_INFO_STREAM(\"random x position of \" << index_string << \" is \" << randomNumbers(i, 0));\n        ROS_INFO_STREAM(\"random y position of \" << index_string << \" is \" << randomNumbers(i, 1));        \n        ROS_INFO_STREAM(\"random rotation angle of \" << index_string << \" is \" << randomNumbers(i, 2));\n\n        // call service and get response\n        bool call_service = client.call(spawn_model_srv_msg);  // call the server\n        if (call_service) {\n            if (spawn_model_srv_msg.response.success) {\n                ROS_INFO_STREAM(robot_model_name << \"_\" << index_string << \" has been spawned\");\n                ROS_INFO_STREAM(\"\");  // make a blank line\n                // std::cout << robot_model_name << \"_\" << index_string << \" has been spawned\" << std::endl;\n            }\n            else {\n                ROS_INFO_STREAM(robot_model_name << \"_\" << index_string << \" spawn failed\");\n                ROS_INFO_STREAM(\"\");  // make a blank line\n                // std::cout << robot_model_name << \"_\" << index_string << \" spawn failed\" << std::endl;\n            }\n        }\n        else {\n            ROS_ERROR(\"Failed to connect with gazebo server\");\n            return 0;\n        }\n    }\n    return 0;\n}\n\n", "meta": {"hexsha": "453f5f6f513671e5c1e5e017cc1910a9a8f60ac2", "size": 6338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "swarm_robot_description/src/obsoleted/swarm_spawner_gazebo_client.cpp", "max_stars_repo_name": "yangliu28/swarm_robot", "max_stars_repo_head_hexsha": "46aa9bca952ee24f528da736c0deef70b840b600", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T17:06:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T06:37:00.000Z", "max_issues_repo_path": "swarm_robot_description/src/obsoleted/swarm_spawner_gazebo_client.cpp", "max_issues_repo_name": "yangliu28/swarm_robot", "max_issues_repo_head_hexsha": "46aa9bca952ee24f528da736c0deef70b840b600", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2016-08-02T04:07:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-09T06:36:30.000Z", "max_forks_repo_path": "swarm_robot_description/src/obsoleted/swarm_spawner_gazebo_client.cpp", "max_forks_repo_name": "yangliu28/swarm_robot", "max_forks_repo_head_hexsha": "46aa9bca952ee24f528da736c0deef70b840b600", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2016-03-05T18:33:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-24T02:44:56.000Z", "avg_line_length": 44.3216783217, "max_line_length": 108, "alphanum_fraction": 0.6793941306, "num_tokens": 1498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.6054617265093366}}
{"text": "#include <terrain_server/feature/SlopeFeature.h>\n#include <Eigen/Dense>\n\n\nnamespace terrain_server\n{\n\nnamespace feature\n{\n\n\nSlopeFeature::SlopeFeature() : flat_threshold_(1.0 * (M_PI / 180.0)),\n\t\tsteep_threshold_(70.0 * (M_PI / 180.0))\n{\n\tname_ = \"Slope\";\n}\n\n\nSlopeFeature::~SlopeFeature()\n{\n\n}\n\n\nvoid SlopeFeature::computeCost(double& cost_value,\n\t\t\t\t\t\t\t   const dwl::Terrain& terrain_info)\n{\n\tdouble slope = fabs(acos((double) terrain_info.surface_normal(2)));\n\n\tif (slope < flat_threshold_)\n\t\tcost_value = 0.;\n\telse if (slope < steep_threshold_) {\n\t\tcost_value = -log(1 - (slope - flat_threshold_) / (steep_threshold_ - flat_threshold_));\n\t\tif (max_cost_ < cost_value)\n\t\t\tcost_value = max_cost_;\n\t} else\n\t\tcost_value = max_cost_;\n}\n\n} //@namespace feature\n} //@namespace terrain_server\n", "meta": {"hexsha": "bdceac2bdfc56d7d63138bc6dad3a533b4a1cafb", "size": 789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/feature/SlopeFeature.cpp", "max_stars_repo_name": "robot-locomotion/terrain-server", "max_stars_repo_head_hexsha": "fa797633e5f854ca8a7bf4814dd5dd58adb141ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2018-02-07T09:51:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T17:15:21.000Z", "max_issues_repo_path": "src/feature/SlopeFeature.cpp", "max_issues_repo_name": "iit-DLSLab/terrain-server", "max_issues_repo_head_hexsha": "c5556d60413d746cfb7b6b506893c3add7c04b83", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/feature/SlopeFeature.cpp", "max_forks_repo_name": "iit-DLSLab/terrain-server", "max_forks_repo_head_hexsha": "c5556d60413d746cfb7b6b506893c3add7c04b83", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2018-03-15T10:28:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T21:55:26.000Z", "avg_line_length": 18.7857142857, "max_line_length": 90, "alphanum_fraction": 0.7046894804, "num_tokens": 220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.6054547271746347}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_LOG10_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_LOG10_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-exponential\n    Function object implementing log10 capabilities\n\n    base ten logarithm function. For integer input types log10 return the truncation\n    of the real result.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = log10(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = log(x)/log(10);\n    @endcode\n\n    - log10(x) return Nan for negative enties (peculiarly Mzero\n    for floating numbers).\n\n    - The call log10(x, assert_) asserts is x is negative (peculiarly\n    take care that it asserts for Mzero but not Zero in case of floating numbers)\n\n    @par Decorators\n\n    std_ for floating entries\n\n    @see log, log2, log1p, is_negative, Mzero\n\n  **/\n  const boost::dispatch::functor<tag::log10_> log10 = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/log10.hpp>\n#include <boost/simd/function/simd/log10.hpp>\n\n#endif\n", "meta": {"hexsha": "76d648718a4dfd748b2bd641c8833c4d330ef727", "size": 1481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/log10.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/log10.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/log10.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8870967742, "max_line_length": 100, "alphanum_fraction": 0.6124240378, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6054404962199039}}
{"text": "#ifndef __IFUNCTION_HXX__\n#define __IFUNCTION_HXX__ \n\n#include <Eigen/Dense>\n\n/*\n * IFunction is an interface for what a function needs to contain\n * in order to implement SGD, SVRGD, SAGA, and Katyusha\n *\n */\n\nusing namespace Eigen;\n\nnamespace Optimastic { \n\ntemplate <int n>\nstruct IFunction { \n    static const int Dimension = n; \n    typedef Matrix<double, n, 1> Domain;\n\n    // _partial_gradient takes in a gradient vector and accumulates \n    // the ith partial derviative into this vector; this is to avoid \n    // making more temporaries and copies of said radient\n    virtual void accum_partial_gradient(int i, Domain &x, Domain &grad, double step_size) const = 0;\n    virtual Domain full_gradient(Domain &x) const = 0;\n\n    virtual double operator() (const Domain &x) const = 0;\n};\n\n} // namespace Optimastic\n\n#endif\n", "meta": {"hexsha": "847c85989a6fb56c990dc07d92cbf0cfc4038acf", "size": 827, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "lib-cxx/ifunction.hxx", "max_stars_repo_name": "tchitra/optimastic", "max_stars_repo_head_hexsha": "b081bb5dce4a6efed10e2b6a1a2b6521dd1e2b60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib-cxx/ifunction.hxx", "max_issues_repo_name": "tchitra/optimastic", "max_issues_repo_head_hexsha": "b081bb5dce4a6efed10e2b6a1a2b6521dd1e2b60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib-cxx/ifunction.hxx", "max_forks_repo_name": "tchitra/optimastic", "max_forks_repo_head_hexsha": "b081bb5dce4a6efed10e2b6a1a2b6521dd1e2b60", "max_forks_repo_licenses": ["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.0606060606, "max_line_length": 100, "alphanum_fraction": 0.7194679565, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517042, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.605440469925216}}
{"text": "\r\n#include <iostream>\r\n#include <boost/numeric/interval.hpp>\r\n\r\n\r\nint main()\r\n{\r\n\tboost::numeric::interval<int> range1(0, 100);\r\n\tboost::numeric::interval<int> range2(30, 120);\r\n\r\n\tauto new_range1 = boost::numeric::intersect(range1, range2);\r\n\r\n\tstd::cout << new_range1.lower() << \" ~ \"\r\n\t\t<< new_range1.upper() << std::endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n", "meta": {"hexsha": "464ea03ffcfee501a6b6c5653c071a7365c5884b", "size": 346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boost_20140423/interval_05/interval_05.cpp", "max_stars_repo_name": "jacking75/book_semina_samples", "max_stars_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Boost_20140423/interval_05/interval_05.cpp", "max_issues_repo_name": "jacking75/book_semina_samples", "max_issues_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Boost_20140423/interval_05/interval_05.cpp", "max_forks_repo_name": "jacking75/book_semina_samples", "max_forks_repo_head_hexsha": "889bd501b0b4e126e27214bbf2b0ace8825b3783", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.2105263158, "max_line_length": 62, "alphanum_fraction": 0.6271676301, "num_tokens": 95, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6054225860350836}}
{"text": "/*!\n*   \\file expm.hpp\n*\n*   Implement matrix exponential using pade approximation.\n*\n*  Copyright (c) 2007\n*  \\author Tsai, Dung-Bang \n*\n*/\n//  Department of Physics,\t\n//  National Taiwan University.\n// \n//  E-Mail : dbtsai [_at_] dbtsai [_dot_] org\n//  Begine : 2007/11/20\n//  Last modify : 2007/11/26\n//  Version : v0.4\n//\n//  expm_pad computes the matrix exponential exp(H) for general matrixs,\n//  including complex and real matrixs using the irreducible (p,p) degree\n//  rational Pade approximation to the exponential \n//  exp(z) = r(z) = (+/-)( I+2*(Q(z)/P(z))).\n//\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt).\n//\n\n#ifndef _BOOST_UBLAS_EXPM_\n#define _BOOST_UBLAS_EXPM_\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n\nnamespace boost { namespace numeric { namespace ublas {\n\ntemplate<typename MATRIX> MATRIX expm_pad(const MATRIX &H, typename type_traits<typename MATRIX::value_type>::real_type t = 1.0, const int p = 6){\n\ttypedef typename MATRIX::value_type value_type;\n        typedef typename MATRIX::size_type size_type;\n\ttypedef typename type_traits<value_type>::real_type real_value_type;\n\tassert(H.size1() == H.size2());\n\tassert(p >= 1);\n\tconst size_type n = H.size1();\n\tconst identity_matrix<value_type> I(n);\n\tmatrix<value_type> U(n,n),H2(n,n),P(n,n),Q(n,n);\n\treal_value_type norm = 0.0;\n// Calcuate Pade coefficients\n\tvector<real_value_type> c(p+1);\n\tc(0)=1;  \n\tfor(size_type i = 0; i < (size_type) p; ++i) \n\t\tc(i+1) = c(i) * ((p - i)/((i + 1.0) * (2.0 * p - i)));\n// Calcuate the infinty norm of H, which is defined as the largest row sum of a matrix\n\tfor(size_type i=0; i<n; ++i) {\n\t\treal_value_type temp = 0.0;\n\t\tfor(size_type j = 0; j < n; j++)\n\t\t\ttemp += std::abs(H(i, j)); \n\t\tnorm = t * std::max<real_value_type>(norm, temp);\n\t}\n// If norm = 0, and all H elements are not NaN or infinity but zero, \n// then U should be identity.\n\tif (norm == 0.0) {\n\t\tbool all_H_are_zero = true;\n\t\tfor(size_type i = 0; i < n; i++)\n\t\t\tfor(size_type j = 0; j < n; j++)\n\t\t\t\tif( H(i,j) != value_type(0.0) ) \n\t\t\t\t\tall_H_are_zero = false; \n\t\tif( all_H_are_zero == true ) return I;\n// Some error happens, H has elements which are NaN or infinity. \n\t\tstd::cerr<<\"Null input error in the template expm_pad.\\n\";\n\t\t//\t\tstd::cout << \"Null INPUT : \" << H <<\"\\n\";\n\t\texit(0);\n\t}\n// Scaling, seek s such that || H*2^(-s) || < 1/2, and set scale = 2^(-s)\n \tint s = 0;\n\treal_value_type scale = 1.0;\n\tif(norm > 0.5) {\n\t\ts = std::max<int>(0, static_cast<int>((log(norm) / log(2.0) + 2.0)));\n\t\tscale /= real_value_type(std::pow(2.0, s));\n\t\tU.assign((scale * t) * H); // Here U is used as temp value due to that H is const\n\t}\n\telse\n\t\tU.assign(H);\n\n// Horner evaluation of the irreducible fraction, see the following ref above.\n// Initialise P (numerator) and Q (denominator) \n\tH2.assign( prod(U, U) );\n\tQ.assign( c(p)*I );\n\tP.assign( c(p-1)*I );\n\tsize_type odd = 1;\n\tfor( size_type k = p - 1; k > 0; --k) {\n\t\t( odd == 1 ) ?\n\t\t\t( Q = ( prod(Q, H2) + c(k-1) * I ) ) :\n\t\t\t( P = ( prod(P, H2) + c(k-1) * I ) ) ;\n\t\todd = 1 - odd;\n\t}\n\t( odd == 1 ) ? ( Q = prod(Q, U) ) : ( P = prod(P, U) );\n\tQ -= P;\n// In origine expokit package, they use lapack ZGESV to obtain inverse matrix,\n// and in that ZGESV routine, it uses LU decomposition for obtaing inverse matrix.\n// Since in ublas, there is no matrix inversion template, I simply use the build-in\n// LU decompostion package in ublas, and back substitute by myself.\n\n// Implement Matrix Inversion\n\tpermutation_matrix<size_type> pm(n); \n\tint res = lu_factorize(Q, pm);\n\tif( res != 0) {\n\t\tstd::cerr << \"Matrix inversion error in the template expm_pad.\\n\";\n\t\texit(0);\n\t}\n// H2 is not needed anymore, so it is temporary used as identity matrix for substituting.\n\tH2.assign(I); \n\tlu_substitute(Q, pm, H2); \n\t(odd == 1) ? \n\t\t( U.assign( -(I + real_value_type(2.0) * prod(H2, P))) ):\n\t\t( U.assign(   I + real_value_type(2.0) * prod(H2, P) ) );\n// Squaring \n\tfor(size_type i = 0; i < (size_type) s; ++i)\n\t\tU = (prod(U,U));\n\treturn U;\n}\n\n}}}\n\n\n#endif\n", "meta": {"hexsha": "ee32782d795c4539b4b42d587cf9113081343930", "size": 4231, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/expm.hpp", "max_stars_repo_name": "Algebraicphylogenetics/Empar", "max_stars_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/expm.hpp", "max_issues_repo_name": "Algebraicphylogenetics/Empar", "max_issues_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/expm.hpp", "max_forks_repo_name": "Algebraicphylogenetics/Empar", "max_forks_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_forks_repo_licenses": ["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.3149606299, "max_line_length": 146, "alphanum_fraction": 0.6405105176, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6053998858581408}}
{"text": "/**\n *  This example shows how to use MLPACK neural networks isolatedly from the\n *  hsmm framework.\n */\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/ann/layer/layer.hpp>\n#include <mlpack/methods/ann/ffn.hpp>\n#include <mlpack/methods/ann/init_rules/random_init.hpp>\n#include <mlpack/methods/ann/loss_functions/mean_squared_error.hpp>\n#include <armadillo>\n#include <boost/program_options.hpp>\n#include <iostream>\n\nusing namespace arma;\nusing namespace mlpack::ann;\nusing namespace std;\nnamespace po = boost::program_options;\n\nmat join_mats(vector<mat> v) {\n    int total_cols = 0;\n    int total_rows = v.at(0).n_rows;\n    for(auto& m: v)\n        total_cols += m.n_cols;\n    mat ret(total_rows, total_cols);\n    int idx = 0;\n    for(auto& m: v) {\n        int d = m.n_cols;\n        ret.cols(idx, idx + d - 1) = m;\n        idx += d;\n    }\n    assert(idx == total_cols);\n    return ret;\n}\n\nint main(int argc, char *argv[]) {\n    mlpack::Log::Info.ignoreInput = false;  // Turning mlpack verbose output on.\n    po::options_description desc(\"Options\");\n    desc.add_options()\n        (\"help,h\", \"Produce help message\")\n        (\"input,i\", po::value<string>(), \"Path to the input obs\")\n        (\"viterbi,v\", po::value<string>(), \"Path to the input viterbi file\")\n        (\"nstates,s\", po::value<int>(), \"Number of states (NNs)\")\n        (\"hiddenunits,u\", po::value<int>()->default_value(10),\n                \"Number of hidden units\")\n        (\"nfiles,n\", po::value<int>()->default_value(1),\n                \"Number of input files to process\");\n    vector<string> required_fields = {\"input\", \"viterbi\", \"nfiles\",\n            \"nstates\"};\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n    if (vm.count(\"help\")) {\n        cout << desc << endl;\n        return 0;\n    }\n    for(auto s: required_fields) {\n        if (!vm.count(s)) {\n            cerr << \"Error: You must provide the argument: \" << s << endl;\n            return 1;\n        }\n    }\n    string input_filename = vm[\"input\"].as<string>();\n    string viterbi_filename = vm[\"viterbi\"].as<string>();\n    int nseq = vm[\"nfiles\"].as<int>();\n    int nstates = vm[\"nstates\"].as<int>();\n    int hidden_units = vm[\"hiddenunits\"].as<int>();\n    vector<mat> obs_for_each_state[nstates];\n    vector<mat> times_for_each_state[nstates];\n    for(int i = 0; i < nseq; i++) {\n        string iname = input_filename;\n        string vname = viterbi_filename;\n        if (nseq != 1) {\n            iname += string(\".\") + to_string(i);\n            vname += string(\".\") + to_string(i);\n        }\n        mat obs;\n        obs.load(iname, raw_ascii);\n        imat vit;\n        vit.load(vname, raw_ascii);\n        ivec hs = vit.col(0);\n        ivec dur = vit.col(1);\n        int idx = 0;\n        for(int j = 0; j < dur.n_rows; j++) {\n            mat segment = obs.cols(idx, idx + dur(j) - 1);\n            obs_for_each_state[hs(j)].push_back(segment);\n            rowvec times = linspace<rowvec>(0, 1.0, dur(j));\n            times_for_each_state[hs(j)].push_back(times);\n            idx += dur(j);\n        }\n    }\n\n    // There should be at least one segment for the hidden state 0.\n    int njoints = obs_for_each_state[0].at(0).n_rows;\n    FFN<MeanSquaredError<>, RandomInitialization> neural_network[nstates];\n    for(int i = 0; i < nstates; i++) {\n        mat inputs = join_mats(times_for_each_state[i]);\n        mat outputs = join_mats(obs_for_each_state[i]);\n        assert (outputs.n_rows == njoints);\n        assert(outputs.n_cols == inputs.n_cols);\n\n        // Defining the architecture of the NN.\n        neural_network[i].Add<Linear<>>(1, hidden_units);\n        neural_network[i].Add<SigmoidLayer<>>();\n        neural_network[i].Add<Linear<>>(hidden_units, njoints);\n\n        // Training the NN.\n        neural_network[i].Train(inputs, outputs);\n\n        // Evaluating the loss.\n        mat test_input = linspace<rowvec>(0,1,100);\n        mat test_output;\n        neural_network[i].Predict(test_input, test_output);\n    }\n\n    for(int i = 0; i < nstates; i++) {\n        mat input = linspace<rowvec>(0,1,10);\n        mat first_output;\n        neural_network[i].Predict(input, first_output);\n        mat old_params = neural_network[i].Parameters();\n\n        // Changing the params.\n        mat new_params(size(old_params), fill::ones);\n        neural_network[i].Parameters() = new_params;\n        mat second_output;\n        neural_network[i].Predict(input, second_output);\n\n        // Changing the params back to the old ones.\n        neural_network[i].Parameters() = old_params;\n        mat third_output;\n        neural_network[i].Forward(input, third_output, 0, 2);\n\n        assert(approx_equal(first_output, third_output, \"reldiff\", 1e-7));\n    }\n    return 0;\n}\n", "meta": {"hexsha": "1548741efa948384566e7eeea94972722346a827", "size": 4762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/NN_standard_fit.cpp", "max_stars_repo_name": "DiegoAE/BOSD", "max_stars_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T05:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:14:31.000Z", "max_issues_repo_path": "examples/NN_standard_fit.cpp", "max_issues_repo_name": "DiegoAE/BOSD", "max_issues_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T15:29:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T10:14:54.000Z", "max_forks_repo_path": "examples/NN_standard_fit.cpp", "max_forks_repo_name": "DiegoAE/BOSD", "max_forks_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T07:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T07:44:09.000Z", "avg_line_length": 34.7591240876, "max_line_length": 80, "alphanum_fraction": 0.597648047, "num_tokens": 1234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541613, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6053998832919469}}
{"text": "#include <cstdio>\n#include <cstdlib>\n#define GL_SILENCE_DEPRECATION\n#include <GLFW/glfw3.h>\n#include <filesystem>\n#include <Eigen/Dense>\n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n#include \"delfem2/glfw/viewer2.h\"\n\nEigen::Matrix<double,4,4,Eigen::RowMajor> GetHomographicTransformation(\n    const double c1[4][2])\n{\n  const double c0[4][2] = {\n      {-0.5,-0.5},\n      {+0.5,-0.5},\n      {+0.5,+0.5},\n      {-0.5,+0.5} };\n  Eigen::Matrix<double,4,4,Eigen::RowMajor> m;\n  // set identity as default\n    m <<\n      1, 0, 0, 0,\n      0, 1, 0, 0,\n      0, 0, 1, 0,\n      0, 0, 0, 1;\n  // write some code to compute the 4x4 Homographic transformation matrix `m`;\n  // `m` should transfer :\n  // (c0[0][0],c0[][1],z) -> (c1[0][0],c1[0][1],z)\n  // (c0[1][0],c0[][1],z) -> (c1[1][0],c1[1][1],z)\n  // (c0[2][0],c0[][1],z) -> (c1[2][0],c1[2][1],z)\n  // (c0[3][0],c0[][1],z) -> (c1[3][0],c1[3][1],z)\n\n  return m;\n}\n\nint main() {\n\n  std::string path = std::string(SOURCE_DIR) + \"/../assets/ada.png\";\n  std::vector<char> img_data;\n  int img_width, img_height, img_channels;\n  { // load image data using stb library\n    stbi_set_flip_vertically_on_load(true);\n    assert( std::filesystem::exists(path.c_str()) );\n    unsigned char *img = stbi_load(\n        path.c_str(),\n        &img_width, &img_height, &img_channels, 0);\n    assert(img_width > 0 && img_height > 0);\n    std::cout << \"image size: \" << img_width << \" \" << img_height << \" \" << img_channels << std::endl;\n    img_data.assign(img,img+img_width*img_height*img_channels);\n    stbi_image_free(img);\n  }\n\n  if (!glfwInit()) { exit(EXIT_FAILURE); }\n  // set OpenGL's version (note: ver. 2.1 is very old, but I chose because it's simple)\n  ::glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);\n  ::glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);\n  GLFWwindow *window = ::glfwCreateWindow(500, 500, \"task01\", nullptr, nullptr);\n  if (!window) { // exit if failed to create window\n    ::glfwTerminate();\n    exit(EXIT_FAILURE);\n  }\n  ::glfwMakeContextCurrent(window); // working on this window below\n\n  // set image to texture calling OpenGL's function\n  // if you are interested in OpenGL's texture, look: https://learnopengl.com/Getting-started/Textures\n  unsigned int texture;\n  glGenTextures(1, &texture);\n  glBindTexture(GL_TEXTURE_2D, texture);\n  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,\n               static_cast<int>(img_width),\n               static_cast<int>(img_height),\n               0, GL_RGBA, GL_UNSIGNED_BYTE,\n               img_data.data());\n\n\n  ::glClearColor(1, 1, 1, 1);\n  ::glEnable(GL_DEPTH_TEST);\n  ::glEnable(GL_POLYGON_OFFSET_FILL);\n  ::glPolygonOffset(1.1f, 4.0f);\n  while (!::glfwWindowShouldClose(window)) {\n    double time = glfwGetTime();\n    const double corners[4][2] = {\n        {-0.5, -0.5},\n        {+0.5, -0.5},\n        {+0.5 - 0.4*cos(1*time), +0.5 - 0.4*sin(3*time)},\n        {-0.5 + 0.4*sin(2*time), +0.5 + 0.4*cos(5*time)} };\n\n    Eigen::Matrix<double,4,4,Eigen::ColMajor> modelview_matrix = GetHomographicTransformation(corners);\n\n    ::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    // set projection matrix\n    ::glMatrixMode(GL_PROJECTION);\n    ::glLoadIdentity();\n\n    // draw red points\n    ::glDisable(GL_TEXTURE_2D);\n    ::glDisable(GL_LIGHTING);\n    ::glMatrixMode(GL_MODELVIEW);\n    ::glLoadIdentity();\n    ::glColor3d(1,0,0);\n    ::glPointSize(10);\n    ::glBegin(GL_POINTS);\n    ::glVertex2dv(corners[0]);\n    ::glVertex2dv(corners[1]);\n    ::glVertex2dv(corners[2]);\n    ::glVertex2dv(corners[3]);\n    ::glEnd();\n\n    // set model view matrix\n    ::glMatrixMode(GL_MODELVIEW);\n    ::glLoadIdentity();\n    ::glMultMatrixd(modelview_matrix.data());\n    ::glEnable(GL_TEXTURE_2D);\n    ::glColor3d(1,1,1);\n    ::glBegin(GL_QUADS);\n    ::glTexCoord2d(0,0);\n    ::glVertex2d(-0.5,-0.5);\n    ::glTexCoord2d(1,0);\n    ::glVertex2d(+0.5,-0.5);\n    ::glTexCoord2d(1,1);\n    ::glVertex2d(+0.5,+0.5);\n    ::glTexCoord2d(0,1);\n    ::glVertex2d(-0.5,+0.5);\n    ::glEnd();\n    //\n    ::glfwSwapBuffers(window);\n    ::glfwPollEvents();\n  }\n  ::glfwDestroyWindow(window);\n  ::glfwTerminate();\n  exit(EXIT_SUCCESS);\n}\n", "meta": {"hexsha": "ce668a831d0470f522287ad0b8270c751624c2ed", "size": 4418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "task01/main.cpp", "max_stars_repo_name": "ACG-2022S/acg", "max_stars_repo_head_hexsha": "f0c39c4dd0d9fb930b461680da5930a1b0e6f845", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "task01/main.cpp", "max_issues_repo_name": "ACG-2022S/acg", "max_issues_repo_head_hexsha": "f0c39c4dd0d9fb930b461680da5930a1b0e6f845", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "task01/main.cpp", "max_forks_repo_name": "ACG-2022S/acg", "max_forks_repo_head_hexsha": "f0c39c4dd0d9fb930b461680da5930a1b0e6f845", "max_forks_repo_licenses": ["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.7841726619, "max_line_length": 103, "alphanum_fraction": 0.6308284292, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6053998832919469}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n#include <BVH.cpp>\n#include <Eigen/Dense>\n#include <catch.hpp>\n////////////////////////////////////////////////////////////////////////////////\n\nTEST_CASE(\"test_tree\", \"[tests]\")\n{\n    Eigen::MatrixXd pts(4, 3);\n    pts << 0, 0, 0,\n        3, 0, 0,\n        0, 3, 0,\n        0, 3, 3;\n\n    Eigen::MatrixXi tri(4, 3);\n    tri << 0, 1, 2,\n        0, 1, 3,\n        0, 2, 3,\n        1, 2, 3;\n\n    BVH::BVH bvh;\n    bvh.init(pts, tri, 1e-10);\n\n    std::vector<unsigned int> pairs;\n    bvh.intersect_box(pts.colwise().minCoeff(), pts.colwise().maxCoeff(), pairs);\n\n    CHECK(pairs.size() == tri.rows());\n}\n", "meta": {"hexsha": "808c53013fda4bfbf563d25481482c63b6a94920", "size": 679, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/tests.cpp", "max_stars_repo_name": "geometryprocessing/SimpleBVH", "max_stars_repo_head_hexsha": "15574502f6cb8039b0bfa4a85ccad04e09deaf05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-22T06:23:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T04:40:14.000Z", "max_issues_repo_path": "tests/tests.cpp", "max_issues_repo_name": "geometryprocessing/SimpleBVH", "max_issues_repo_head_hexsha": "15574502f6cb8039b0bfa4a85ccad04e09deaf05", "max_issues_repo_licenses": ["MIT"], "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/tests.cpp", "max_forks_repo_name": "geometryprocessing/SimpleBVH", "max_forks_repo_head_hexsha": "15574502f6cb8039b0bfa4a85ccad04e09deaf05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-08T18:51:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T18:53:12.000Z", "avg_line_length": 23.4137931034, "max_line_length": 81, "alphanum_fraction": 0.3873343152, "num_tokens": 201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6053998754174317}}
{"text": "// two_dim_rand.cpp\n//\n#include <iostream>\n\n#include <boost/bind.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/random.hpp>\n\ndouble on_circle_prob(double x, double y)\n{\n    static const double k_delta = 0.01;\n    if (std::abs(x*x + y*y - 1) <= k_delta)\n        return 1.0;\n    else\n        return 0;\n}\n\nint main(int argc, char* argv[])\n{\n    using boost::lexical_cast;\n    using boost::random::uniform_real_distribution;\n    using boost::random::discrete_distribution;\n\n    std::size_t samples = argc > 1 ? lexical_cast<std::size_t>(argv[1]) : 100;\n    std::size_t n = argc > 2 ? lexical_cast<std::size_t>(argv[2]) : 100;\n    double xmin = -1.0;\n    double xmax = 1.0;\n    double ymin = -1.0;\n    double ymax = 1.0;\n\n    boost::mt19937 gen;\n    uniform_real_distribution<> x_dist(xmin, xmax);\n    for (int i = 0; i < samples; ) {\n        double x = x_dist(gen);\n        discrete_distribution<> y_dist(n, ymin, ymax, boost::bind(on_circle_prob, x, _1));\n        int rand_n = y_dist(gen);\n        double y = (rand_n * 1.0 / n) * (ymax - ymin) + ymin;\n        if (true || on_circle_prob(x, y) != 0) {\n            std::cout << x << ' ' << y << std::endl;\n            i++;\n        }\n    }\n}\n", "meta": {"hexsha": "6dfbc37f84cc5518f52d3f1dfbedbc1f6fa5a9a5", "size": 1194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/two_dim_rand.cpp", "max_stars_repo_name": "uwydoc/the-practices", "max_stars_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_stars_repo_licenses": ["MIT"], "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/two_dim_rand.cpp", "max_issues_repo_name": "uwydoc/the-practices", "max_issues_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_issues_repo_licenses": ["MIT"], "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/two_dim_rand.cpp", "max_forks_repo_name": "uwydoc/the-practices", "max_forks_repo_head_hexsha": "61ea1d868017ac88fddf6c0e726f0e9adde3f80e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1363636364, "max_line_length": 90, "alphanum_fraction": 0.5820770519, "num_tokens": 357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672320414787, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6053128353856816}}
{"text": "#include <Eigen/Dense>\n\n#include <ancse/cfl_condition.hpp>\n#include <ancse/config.hpp>\n#include <ancse/fvm_rate_of_change.hpp>\n#include <ancse/snapshot_writer.hpp>\n#include <ancse/time_loop.hpp>\n\ntemplate<class F>\nEigen::VectorXd ic(const F &f, const Grid &grid) {\n    Eigen::VectorXd u0(grid.n_cells);\n    for(int i = 0; i < grid.n_cells; ++i) {\n        u0[i] = f(cell_center(grid, i));\n    }\n\n    return u0;\n}\n\nTimeLoop make_fvm(const Grid &grid) {\n    auto config = get_global_config();\n    double t_end = config[\"t_end\"];\n    double cfl_number = config[\"cfl_number\"];\n\n    auto n_ghost = grid.n_ghost;\n    auto n_cells = grid.n_cells;\n\n    auto model = Model{};\n\n    auto simulation_time = std::make_shared<SimulationTime>(t_end);\n    auto fvm_rate_of_change = make_fvm_rate_of_change(grid, model, simulation_time);\n    auto boundary_condition = make_boundary_condition(n_ghost, config[\"boundary_condition\"]);\n    auto time_integrator = make_runge_kutta(fvm_rate_of_change, boundary_condition, n_cells);\n    auto cfl_condition = make_cfl_condition(grid, model, cfl_number);\n    auto snapshot_writer = std::make_shared<JSONSnapshotWriter>(grid, simulation_time, std::string(config[\"output\"]));\n\n    return TimeLoop(simulation_time, time_integrator, cfl_condition, snapshot_writer);\n}\n\nvoid smooth_sine_test() {\n    auto config = get_global_config();\n\n    int n_ghost = config[\"n_ghost\"];\n    int n_cells = int(config[\"n_interior_cells\"]) + n_ghost * 2;\n\n    auto grid = Grid({0.0, 1.0}, n_cells, n_ghost);\n    auto u0 = ic([](double x) { return std::sin(2.0*M_PI * x);}, grid);\n\n    auto fvm = make_fvm(grid);\n    fvm(u0);\n}\n\nint main() {\n    smooth_sine_test();\n\n    return 0;\n}", "meta": {"hexsha": "da52271aa1430a8910e503299ec78d8790e89179", "size": 1682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series1_workbench/fvm_scalar_1d/src/fvm_scalar.cpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series1_workbench/fvm_scalar_1d/src/fvm_scalar.cpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series1_workbench/fvm_scalar_1d/src/fvm_scalar.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": 30.0357142857, "max_line_length": 118, "alphanum_fraction": 0.6967895363, "num_tokens": 452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.605312805558394}}
{"text": "/*\n * Software License Agreement (Apache License)\n *\n * Copyright (c) 2014, Southwest Research Institute\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n#include <industrial_extrinsic_cal/ceres_costs_utils.hpp>\n\n#include <gtest/gtest.h>\n#include <yaml-cpp/yaml.h>\n#include <fstream>\n#include <iostream>\n\n#include <Eigen/Geometry>\n#include <Eigen/Core>\n\nusing namespace industrial_extrinsic_cal;\n\nPoint3d transformPoint(Point3d &original_point, double &ax, double &ay, double &az, double &x, double&y, double &z);\n\nstd::vector<Point3d> created_points;\ndouble aa[3]; // angle axis known/set\ndouble p[3]; // point rotated known/set\nstd::vector<Point3d> transformed_points;\n\nstruct PointReprjErrorNoDistortion\n{\n  PointReprjErrorNoDistortion(double ob_x, double ob_y, double fx) :\n      px_(ob_x), py_(ob_y), pz_(fx)\n  {\n  }\n\n  template<typename T>\n    bool operator()(const T* const c_p1, /** extrinsic parameters */\n                    //const T* c_p2, /** intrinsic parameters */\n                    const T* point, /** point being projected, yes this is has 3 parameters */\n                    T* resid) const\n    {\n      /** extract the variables from the camera parameters */\n      int q = 0; /** extrinsic block of parameters */\n      const T& x = c_p1[0]; /**  angle_axis x for rotation of camera           */\n      const T& y = c_p1[1]; /**  angle_axis y for rotation of camera */\n      const T& z = c_p1[2]; /**  angle_axis z for rotation of camera */\n      const T& tx = c_p1[3]; /**  translation of camera x */\n      const T& ty = c_p1[4]; /**  translation of camera y */\n      const T& tz = c_p1[5]; /**  translation of camera z */\n\n      //std::cout<<\"x, y, z: \"<<c_p1[3]<<\", \"<<c_p1[4]<<\", \"<<c_p1[5]<<std::endl;\n\n      //q = 0; /** intrinsic block of parameters */\n      //const T& fx = c_p2[q++]; /**  focal length x */\n      //const T& fy = c_p2[q++]; /**  focal length x */\n      //const T& cx = c_p2[q++]; /**  center point x */\n      //const T& cy = c_p2[q++]; /**  center point y */\n\n      /** rotate and translate points into camera frame*/\n      T aa[3]; /** angle axis*/\n      T p[3]; /** point rotated*/\n      aa[0] = x;\n      aa[1] = y;\n      aa[2] = z;\n      ceres::AngleAxisRotatePoint(aa, point, p);\n\n      /** apply camera translation*/\n      T xp1 = p[0] + tx; /** point rotated and translated*/\n      T yp1 = p[1] + ty;\n      T zp1 = p[2] + tz;\n\n      /** scale into the image plane by distance away from camera\n      T xp = xp1 / zp1;\n      T yp = yp1 / zp1;*/\n      T xp=xp1;\n      T yp=yp1;\n      T zp=zp1;\n\n      /** perform projection using focal length and camera center into image plane\n      resid[0] = T(fx_) * xp + T(cx_) - T(ox_);\n      resid[1] = T(fy_) * yp + T(cy_) - T(oy_);*/\n      resid[0] = T(xp)-T(px_);\n      resid[1] = T(yp)-T(py_);\n      resid[2] = T(zp)-T(pz_);\n\n      return true;\n    } /** end of operator() */\n\n  /** Factory to hide the construction of the CostFunction object from */\n  /** the client code. */\n  static ceres::CostFunction* Create(const double p_x, const double p_y, const double p_z)\n  {\n    return (new ceres::AutoDiffCostFunction<PointReprjErrorNoDistortion, 3, 6, 3>(new PointReprjErrorNoDistortion(p_x, p_y, p_z)));\n  }\n  double px_; /** observed x location of object in image */\n  double py_; /** observed y location of object in image */\n  double pz_; /*!< known focal length of camera in x */\n};\n\nTEST(IndustrialExtrinsicCalCeresSuite, create_points)\n{\n  Point3d x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20;\n  x1.pb[0]=1.0;x1.pb[1]=1.0;x1.pb[2]=1;\n  created_points.push_back(x1);\n  x2.pb[0]=0;x2.pb[1]=0;x2.pb[2]=0.01;\n  created_points.push_back(x2);\n  x3.pb[0]=0.65;x3.pb[1]=0.94;x3.pb[2]=0.01;\n  created_points.push_back(x3);\n  x4.pb[0]=0.2;x4.pb[1]=0.3;x4.pb[2]=0.01;\n  created_points.push_back(x4);\n  x5.pb[0]=0.372;x5.pb[1]=0.4;x5.pb[2]=0.4;\n  created_points.push_back(x5);\n  x6.pb[0]=0.3762;x6.pb[1]=0.8;x6.pb[2]=0.3;\n  created_points.push_back(x6);\n  x7.pb[0]=0.4;x7.pb[1]=0.389;x7.pb[2]=0.4;\n  created_points.push_back(x7);\n  x8.pb[0]=0.431;x8.pb[1]=0.7;x8.pb[2]=0.7;\n  created_points.push_back(x8);\n  x9.pb[0]=0.535;x9.pb[1]=0.9;x9.pb[2]=0.01;\n  created_points.push_back(x9);\n  x10.pb[0]=0.596;x10.pb[1]=1;x10.pb[2]=1.0;\n  created_points.push_back(x10);\n  x11.pb[0]=0.24;x11.pb[1]=1.0;x11.pb[2]=0.01;\n  created_points.push_back(x11);\n  x12.pb[0]=0.673;x12.pb[1]=1.7;x12.pb[2]=0.8;\n  created_points.push_back(x12);\n  x13.pb[0]=0.552;x13.pb[1]=1.15;x13.pb[2]=0.01;\n  created_points.push_back(x13);\n  x14.pb[0]=0.56;x14.pb[1]=0.81;x14.pb[2]=0.01;\n  created_points.push_back(x14);\n  x15.pb[0]=.70;x15.pb[1]=1.10;x15.pb[2]=0.01;\n  created_points.push_back(x15);\n  x16.pb[0]=0.3762;x16.pb[1]=0.02435;x16.pb[2]=0.3;\n  created_points.push_back(x16);\n  x17.pb[0]=0.0234;x17.pb[1]=0.389;x17.pb[2]=0.132;\n  created_points.push_back(x17);\n  x18.pb[0]=0.431;x18.pb[1]=0.245;x18.pb[2]=0.0235;\n  created_points.push_back(x18);\n  x19.pb[0]=0.535;x19.pb[1]=0.673;x19.pb[2]=0.01;\n  created_points.push_back(x19);\n  x20.pb[0]=0.76;x20.pb[1]=0.453;x20.pb[2]=1.0;\n  created_points.push_back(x20);\n  std::cout<<\"Original Point 1: \"<<x1.pb[0]<<\" \"<<x1.pb[1]<<\" \"<<x1.pb[2]<<std::endl;\n\n  //create known transform\n  aa[0] = 2.7;\n  aa[1] = 0.3;\n  aa[2] = 0.1;\n  p[0]=0.2;\n  p[1]=0.4;\n  p[2]=0.5;\n  Point3d t_point;\n  for (int i=0; i<created_points.size();i++)\n  {\n    t_point=transformPoint(created_points.at(i), aa[0], aa[1], aa[2], p[0], p[1], p[2]);\n    transformed_points.push_back(t_point);\n  }\n\n}\n\nTEST(IndustrialExtrinsicCalCeresSuite, points_costfunction)\n{\ndouble extrinsics[6];\nceres::Problem problem;\n  for (int j = 0; j < transformed_points.size(); ++j)\n  {\n    ceres::CostFunction* cost_function = PointReprjErrorNoDistortion::Create(transformed_points.at(j).pb[0], transformed_points.at(j).pb[1], transformed_points.at(j).pb[2]);\n\n    problem.AddResidualBlock(cost_function, NULL, extrinsics, created_points[j].pb);\n    //problem.SetParameterBlockConstant(C.PB_intrinsics);\n    problem.SetParameterBlockConstant(created_points[j].pb);\n  }\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::DENSE_SCHUR;\n  options.minimizer_progress_to_stdout = false;\n  options.max_num_iterations = 1000;\n\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n  //std::cout << summary.FullReport() << \"\\n\";\n  std::cout << summary.BriefReport() << \"\\n\";\n\n  EXPECT_FLOAT_EQ(-2.7,extrinsics[0]);\n  EXPECT_FLOAT_EQ(-0.3,extrinsics[1]);\n  EXPECT_FLOAT_EQ(-0.1,extrinsics[2]);\n  EXPECT_FLOAT_EQ(0.2,extrinsics[3]);\n  EXPECT_FLOAT_EQ(0.4,extrinsics[4]);\n  EXPECT_FLOAT_EQ(0.5,extrinsics[5]);\n  std::cout<<\"Original aa rot and translation: \"<<aa[0]<<\" \"<<aa[1]<<\" \"<<aa[2]\n                                     <<\" \"<<p[0]<<\" \"<<p[1]<<\" \"<<p[2]<<std::endl;\n\n  std::cout<<\"Optimized Extrinsics rot/transl: \"<<extrinsics[0]<<\" \"<<extrinsics[1]<<\" \"<<extrinsics[2]<<\" \"\n      <<extrinsics[3]<<\" \"<<extrinsics[4]<<\" \"<<extrinsics[5]<<std::endl;\n}\n\nTEST(DISABLED_IndustrialExtrinsicCalCeresSuite, camera_costfunction)\n//void test()//\n{\n  CameraParameters c_parameters;\n  c_parameters.angle_axis[0]=0.0;//aa[0];//0.3;//\n  c_parameters.angle_axis[1]=0.0;//aa[1];//0.7;//\n  c_parameters.angle_axis[2]=0.0;//aa[2];//2.9;//\n  c_parameters.position[0]=0.0;//p[0];//0.9;//\n  c_parameters.position[1]=0.0;//p[1];//0.3;//\n  c_parameters.position[2]=0.0;//p[2];//1.8;//\n  c_parameters.focal_length_x=525;\n  c_parameters.focal_length_y=525;\n  c_parameters.center_x=320;\n  c_parameters.center_y=240;\n  c_parameters.distortion_k1=0.01;\n  c_parameters.distortion_k2=0.02;\n  c_parameters.distortion_k3=0.03;\n  c_parameters.distortion_p1=0.01;\n  c_parameters.distortion_p2=0.01;\n\n  std::vector<Observation> projected_observations;\n  Observation proj_point;\n  for (int m=0; m<transformed_points.size(); m++)\n  {\n    proj_point=industrial_extrinsic_cal::projectPointWithDistortion(c_parameters, transformed_points.at(m));\n    projected_observations.push_back(proj_point);\n  }\n\n  double extrinsics[6];\n  extrinsics[0]=c_parameters.pb_extrinsics[0];//0.2;//\n  extrinsics[1]=c_parameters.pb_extrinsics[1];//0.1;//\n  extrinsics[2]=c_parameters.pb_extrinsics[2];//0.9;//\n  extrinsics[3]=c_parameters.pb_extrinsics[3];//1.3;//\n  extrinsics[4]=c_parameters.pb_extrinsics[4];//0.1;//\n  extrinsics[5]=c_parameters.pb_extrinsics[5];//2.0;//\n  ceres::Problem problem;\n  double original_points[3];\n    for (int j = 0; j < projected_observations.size(); ++j)\n    {\n      ceres::CostFunction* cost_function = CameraReprjErrorWithDistortion::Create(projected_observations.at(j).image_loc_x,\n             projected_observations.at(j).image_loc_y);\n\n\n      problem.AddResidualBlock(cost_function, NULL, extrinsics, c_parameters.pb_intrinsics, created_points[j].pb);\n      problem.SetParameterBlockConstant(c_parameters.pb_intrinsics);\n      problem.SetParameterBlockConstant(created_points[j].pb);\n    }\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_SCHUR;\n    options.minimizer_progress_to_stdout = true;\n    options.max_num_iterations = 1000;\n\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    //std::cout << summary.FullReport() << \"\\n\";\n    std::cout << summary.BriefReport() << \"\\n\";\n\n    std::cout<<\"Expected aa rot and translation: \"<<aa[0]<<\" \"<<aa[1]<<\" \"<<aa[2]\n                                       <<\" \"<<p[0]<<\" \"<<p[1]<<\" \"<<p[2]<<std::endl;\n\n    std::cout<<\"Optimized Extrinsics rot/transl: \"<<extrinsics[0]<<\" \"<<extrinsics[1]<<\" \"\n        <<extrinsics[2]<<\" \"<<extrinsics[3]<<\" \"<<extrinsics[4]<<\" \"\n        <<extrinsics[5]<<std::endl;\n}\n\n//void test()\nTEST(DISABLED_IndustrialExtrinsicCalCeresSuite, camera_no_dist_costfunction)\n{\n  CameraParameters c_parameters;\n  c_parameters.angle_axis[0]=0.0;//aa[0];//0.3;//\n  c_parameters.angle_axis[1]=0.0;//aa[1];//0.7;//\n  c_parameters.angle_axis[2]=0.0;//aa[2];//2.9;//\n  c_parameters.position[0]=0.0;//p[0];//0.9;//\n  c_parameters.position[1]=0.0;//p[1];//0.3;//\n  c_parameters.position[2]=0.0;//p[2];//1.8;//\n  c_parameters.focal_length_x=525;\n  c_parameters.focal_length_y=525;\n  c_parameters.center_x=320;\n  c_parameters.center_y=240;\n  c_parameters.distortion_k1=0.01;\n  c_parameters.distortion_k2=0.02;\n  c_parameters.distortion_k3=0.03;\n  c_parameters.distortion_p1=0.01;\n  c_parameters.distortion_p2=0.01;\n\n  std::vector<Observation> projected_observations;\n  Observation proj_point;\n  for (int m=0; m<transformed_points.size(); m++)\n  {\n\n    proj_point=industrial_extrinsic_cal::projectPointNoDistortion(c_parameters, transformed_points.at(m));\n    projected_observations.push_back(proj_point);\n  }\n\n  double extrinsics[6];\n  extrinsics[0]=c_parameters.pb_extrinsics[0];//0.2;//\n  extrinsics[1]=c_parameters.pb_extrinsics[1];//0.1;//\n  extrinsics[2]=c_parameters.pb_extrinsics[2];//0.9;//\n  extrinsics[3]=c_parameters.pb_extrinsics[3];//1.3;//\n  extrinsics[4]=c_parameters.pb_extrinsics[4];//0.1;//\n  extrinsics[5]=c_parameters.pb_extrinsics[5];//2.0;//\n  ceres::Problem problem;\n    for (int j = 0; j < projected_observations.size(); ++j)\n    {\n      ceres::CostFunction* cost_function = CameraReprjErrorNoDistortion::Create(projected_observations.at(j).image_loc_x,\n             projected_observations.at(j).image_loc_y, c_parameters.focal_length_x, c_parameters.focal_length_y,\n             c_parameters.center_x, c_parameters.center_y);\n\n      problem.AddResidualBlock(cost_function, NULL, extrinsics, c_parameters.pb_intrinsics, created_points.at(j).pb);\n      problem.SetParameterBlockConstant(c_parameters.pb_intrinsics);\n      problem.SetParameterBlockConstant(created_points.at(j).pb);\n    }\n    ceres::Solver::Options options;\n    options.linear_solver_type = ceres::DENSE_SCHUR;\n    options.minimizer_progress_to_stdout = true;\n    options.max_num_iterations = 1000;\n\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    //std::cout << summary.FullReport() << \"\\n\";\n    std::cout << summary.BriefReport() << \"\\n\";\n\n    std::cout<<\"Expected aa rot and translation: \"<<aa[0]<<\" \"<<aa[1]<<\" \"<<aa[2]\n                                       <<\" \"<<p[0]<<\" \"<<p[1]<<\" \"<<p[2]<<std::endl;\n\n    std::cout<<\"Optimized Extrinsics rot/transl: \"<<extrinsics[0]<<\" \"<<extrinsics[1]<<\" \"\n        <<extrinsics[2]<<\" \"<<extrinsics[3]<<\" \"<<extrinsics[4]<<\" \"\n        <<extrinsics[5]<<std::endl;\n}\n\nPoint3d transformPoint(Point3d &original_point, double &ax, double &ay, double &az, double &x, double&y, double &z)\n{\n  //std::cout<<\"ange axis inputs ax, ay, az: \"<<ax<<\", \"<<ay<<\", \"<<az<<std::endl;\n  Eigen::Matrix3f m_ceres;\n  Eigen::Matrix3f m_eigen;\n  m_eigen = Eigen::AngleAxisf(ax, Eigen::Vector3f::UnitX())\n  * Eigen::AngleAxisf(ay, Eigen::Vector3f::UnitY())\n  * Eigen::AngleAxisf(az, Eigen::Vector3f::UnitZ());\n  //std::cout<<\"m_eigen : \"<<std::endl<< m_eigen <<std::endl;\n  double aa[3]; // angle axis\n  double p[3]; // point rotated\n  aa[0] = ax;\n  aa[1] = ay;\n  aa[2] = az;\n  Eigen::Vector3f orig_point(original_point.pb[0], original_point.pb[1], original_point.pb[2]);\n  //std::cout<<\"within transformPoint, original point Vector3f x, y, z: \"<<orig_point.x()<<\", \"<<orig_point.y()<<\", \"<<orig_point.z()<<std::endl;\n\n  double R[9];\n  ceres::AngleAxisToRotationMatrix(aa, R);\n  m_ceres << R[0], R[1],R[2],\n      R[3], R[4], R[5],\n      R[6], R[7], R[8];\n  //std::cout<<\"m_ceres : \"<<std::endl<< m_ceres <<std::endl;\n  Eigen::Vector3f rot_point=m_ceres*orig_point;\n  //std::cout<<\"within transformPoint, rotated point Vector3f x, y, z: \"<<rot_point.x()<<\", \"<<rot_point.y()<<\", \"<<rot_point.z()<<std::endl;\n  double xp1 = rot_point.x() + x; // point rotated and translated\n  double yp1 = rot_point.y() + y;\n  double zp1 = rot_point.z() + z;\n  //std::cout<<\"within transformPoint, original point double x, y, z: \"<<xp1<<\", \"<<yp1<<\", \"<<zp1<<std::endl;\n  Point3d t_point;\n  t_point.pb[0]=xp1;t_point.pb[1]=yp1;t_point.pb[2]=zp1;\n  //std::cout<<\"within transformPoint, t_point x, y, z: \"<<t_point.pb[0]<<\", \"<<t_point.pb[1]<<\", \"<<t_point.pb[2]<<std::endl;\n  return t_point;\n}\n\n// Run all the tests that were declared with TEST()\nint main(int argc, char **argv)\n{\n  //ros::init(argc, argv, \"test\");\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n\n}\n", "meta": {"hexsha": "8fa9d18e42cedc9a2bb1cdef1eb990500b84342a", "size": 14764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "industrial_extrinsic_cal/test/ceres_utest.cpp", "max_stars_repo_name": "gt-ros-pkg/industrial_calibration", "max_stars_repo_head_hexsha": "7d7a259a7509bdbadddf8d9550c11723164c07fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-29T00:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-29T00:08:27.000Z", "max_issues_repo_path": "industrial_extrinsic_cal/test/ceres_utest.cpp", "max_issues_repo_name": "gt-ros-pkg/industrial_calibration", "max_issues_repo_head_hexsha": "7d7a259a7509bdbadddf8d9550c11723164c07fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "industrial_extrinsic_cal/test/ceres_utest.cpp", "max_forks_repo_name": "gt-ros-pkg/industrial_calibration", "max_forks_repo_head_hexsha": "7d7a259a7509bdbadddf8d9550c11723164c07fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-30T10:21:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-30T10:21:22.000Z", "avg_line_length": 38.9551451187, "max_line_length": 173, "alphanum_fraction": 0.6515849363, "num_tokens": 4702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6053009282274853}}
{"text": "/**\n * math lib test\n * @author Tobias Weber <tweber@ill.fr>\n * @date 10-jun-20\n * @license GPLv3, see 'LICENSE' file\n *\n * g++ -std=c++20 -I.. -I/usr/include/libqhullcpp -DUSE_QHULL -o hull1 hull1.cpp -lqhull_r -lqhullcpp\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE Hull1\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n#include <iostream>\n\n#include \"libs/maths.h\"\nusing namespace tl2_ops;\n\n\nusing t_types = std::tuple<double, float>;\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_equals, t_real, t_types)\n{\n\tusing t_vec = tl2::vec<t_real, std::vector>;\n\n\tstd::vector<t_vec> vecs =\n\t{\n\t\t{1, 1, -1},\n\t\t{1, -1, -1},\n\t\t{-1, 1, -1},\n\t\t{-1, -1, -1},\n\n\t\t{1, 1, 1},\n\t\t{1, -1, 1},\n\t\t{-1, 1, 1},\n\t\t{-1, -1, 1},\n\t};\n\n\n\tauto [hull, norms, dists] = tl2_qh::get_convexhull<t_vec>(vecs);\n\n\tfor(std::size_t faceidx=0; faceidx<hull.size(); ++faceidx)\n\t{\n\t\tconst auto& face = hull[faceidx];\n\t\tstd::cout << \"face \" << faceidx << \":\\n\";\n\n\t\tfor(const auto& vert : face)\n\t\t\tstd::cout << \"vertex: \" << vert << \"\\n\";\n\t\tstd::cout << \"normal: \" << norms[faceidx] << \"\\n\";\n\n\t\tstd::cout << std::endl;\n\t}\n\n\n\tBOOST_TEST(hull.size() == 6*2);\n\tfor(const auto& face : hull)\n\t\tBOOST_TEST(face.size() == 3);\n\n\tstd::cout << \"--------------------------------------------------------------------------------\" << std::endl;\n}\n", "meta": {"hexsha": "1acf9a6716993305e0ab9f3896d103715c609d69", "size": 2360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/hull1.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/hull1.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/hull1.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 29.1358024691, "max_line_length": 110, "alphanum_fraction": 0.5775423729, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6053009147760079}}
{"text": "#include <utility>\n#include <iostream>\n#include <Vector>\n#include <cmath>\n#include <iomanip>\n#include <Eigen/Dense>\n// pas termin\u00e9, \n\ntemplate <typename arg, class func, class jac>\nvoid mod_newt_step_system(const arg & x, arg & x_next, function&& f, jacobian&& df){\n\targ y;\n\ty=x+f(x)/df(x);\n\tx_next = y - f(y)/df(x);\n}\n\nvoid mod_newt_step_exec(){\n\tusing Vector = Eigen::VectorXd;\n\tusing Matrix = Eingen::MatrixXd;\n\t\n\tVector x;\n\tVector c = Vector::random(4);\n\tMatrix A = Matrix::random(4,4);\n\tA = (A*A.transpose());\n\tc = c.cwiseAbs(); \n\t\n\tauto F = [&A,&c] (const Vector & x) \n\t{ Vector tmp =  A*x + c.cwiseProduct(x.array().exp().Matrix()).eval(); return tmp; };\n    std::function<Matrix(const Vector &)> dF = [&A, &c] (const Vector & x) \n    { Matrix C = A; Vector temp = c.cwiseProduct(x.array().exp().Matrix()); C += temp.asDiagonal(); return C; };\n\n\tdouble tol = 1.e-15;\n\t\n\tint i=0;\n\n\twhile (tol){\n\t\ti++;\n\t\tmod_newt_step_system(x, x_next,f,df );\n\t\tstd::cout << i << \"th interation,    x_next is \" << x_next << \"        and x_star - x_next : \" << eval_err(x_next) << std::endl;\n\t\tif (i> 15){\n\t\t\tstd::cout << \" Broke \" << std::endl;\n\t\t\tbreak;}\n\t\t\tx= x_next;\n\t}\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\nint main () {\n\tmod_newt_step_exec();\n\tconst double a = 0.123;\n\tstd::cout << \"tan(a) : \" << std::tan(a) << std::endl;\n\treturn 0;\n\t\n}\n", "meta": {"hexsha": "160ad8b61789fbeb4b7f1783388c8848548a0364", "size": 1309, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS5/ex01_d.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/ex01_d.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/ex01_d.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": 20.1384615385, "max_line_length": 130, "alphanum_fraction": 0.5920550038, "num_tokens": 410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.6053009041713702}}
{"text": "// eig1.cpp\n\n#include <iostream>\n#include <Eigen/Dense>\n\nint main(int argc, char const *argv[])\n{\n    // 2x2 matrix, of type float\n    Eigen::Matrix<float, 2, 2> A, B;\n    A << 2, -1, -1, 3;\n    B << 1, 2, 3, 1;\n\n    std::cout << \"A:     \" << A <<  '\\n';\n    std::cout << \"B:     \" << B << '\\n';\n    std::cout << \"A+B:   \" << A+B << '\\n';\n    std::cout << \"A-B:   \" << A-B << '\\n';\n    std::cout << \"1.6*A: \" << 1.6*A << '\\n';\n\n    return 0;\n}\n", "meta": {"hexsha": "1d5eb5fd3cb968f4e02e0b64f4faba4f98c89d8c", "size": 444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SCP2017/lecture4_arrays/eig1.cpp", "max_stars_repo_name": "kouui/cpp_testground", "max_stars_repo_head_hexsha": "8fc9e82c70cd801a76972c604b304bc2ecf19812", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SCP2017/lecture4_arrays/eig1.cpp", "max_issues_repo_name": "kouui/cpp_testground", "max_issues_repo_head_hexsha": "8fc9e82c70cd801a76972c604b304bc2ecf19812", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SCP2017/lecture4_arrays/eig1.cpp", "max_forks_repo_name": "kouui/cpp_testground", "max_forks_repo_head_hexsha": "8fc9e82c70cd801a76972c604b304bc2ecf19812", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.1428571429, "max_line_length": 44, "alphanum_fraction": 0.4076576577, "num_tokens": 181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412808, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.6052564980806862}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include \"covariance.h\"\n\nCovObj::CovObj()\n{\n    clearCov();\n}\n\nCovObj::CovObj(const Vector3d &v1, const Vector3d &v2, const Vector3d &v3)\n{\n    area_ = 0.5 * (v2 - v1).cross(v3 - v1).norm();\n    center_ = 1 / 3.0 * (v1 + v2 + v3);\n    Matrix3d vm, c;\n    vm(0, 0) = v1(0);\n    vm(1, 0) = v1(1);\n    vm(2, 0) = v1(2);\n    vm(0, 1) = v2(0);\n    vm(1, 1) = v2(1);\n    vm(2, 1) = v2(2);\n    vm(0, 2) = v3(0);\n    vm(1, 2) = v3(1);\n    vm(2, 2) = v3(2);\n    c(0, 0) = c(1, 1) = c(2, 2) = 2;\n    c(0, 1) = c(0, 2) = c(1, 0) = c(1, 2) = c(2, 0) = c(2, 1) = -1;\n    cov_ = area_ / 36.0 * vm * c * vm.transpose();\n    size_ = 1;\n}\n\nvoid CovObj::clearCov()\n{\n    cov_.setZero();\n    area_ = 0;\n    size_ = 0;\n    center_ = normal_ = Vector3d::Zero();\n}\n\nCovObj &CovObj::operator+=(const CovObj &Q)\n{\n    // some models may contain corrupted null faces, ignore them\n    if (Q.area_ < 1e-18)\n        return *this;\n    CovObj Q_old = *this;\n    area_ = Q_old.area_ + Q.area_;\n    center_ = (Q_old.area_ * Q_old.center_ + Q.area_ * Q.center_) / (area_);\n    Vector3d ktoi, ktoj;\n    ktoi = Q_old.center_ - center_;\n    ktoj = Q.center_ - center_;\n    cov_ = Q_old.cov_ + Q.cov_ + Q_old.area_ * ktoi * ktoi.transpose() + Q.area_ * ktoj * ktoj.transpose();\n    size_ += Q.size_;\n    return *this;\n}\n\nCovObj &CovObj::operator-=(const CovObj &Q)\n{\n    // some models may contain corrupted null faces, ignore them\n    if (Q.area_ < 1e-18)\n        return *this;\n    CovObj Q_old = *this;\n    area_ = Q_old.area_ - Q.area_;\n    center_ = (Q_old.area_ * Q_old.center_ - Q.area_ * Q.center_) / (area_);\n    Vector3d ktoi, ktoj;\n    ktoi = Q_old.center_ - center_;\n    ktoj = Q_old.center_ - Q.center_;\n    cov_ = Q_old.cov_ - Q.cov_ - area_ * ktoi * ktoi.transpose() - Q.area_ * ktoj * ktoj.transpose();\n    size_ -= Q.size_;\n    return *this;\n}\n\nbool CovObj::operator==(const CovObj &Q)\n{\n    return cov_ == Q.cov_ && normal_ == Q.normal_ && center_ == Q.center_ && area_ == Q.area_ && size_ == Q.size_;\n}\n\nCovObj &CovObj::operator=(const CovObj &Q)\n{\n    // A good habit to check for self-assignment\n    if (this == &Q)\n        return *this;\n\n    cov_ = Q.cov_;\n    normal_ = Q.normal_;\n    center_ = Q.center_;\n    area_ = Q.area_;\n    size_ = Q.size_;\n    return *this;\n}\n\ndouble CovObj::energy()\n{\n    if (area_ < 1e-10 || size_ <= 1) // 1 triangle has 0 energy\n        return 0;\n    if (cov_.determinant() / pow(area_, 5) < 1e-15)\n        return cov_.trace() * area_ * 1e-20;\n    else\n        return cov_.determinant() / pow(area_, 4);\n}\n\nvoid CovObj::computePlaneNormal()\n{\n    Eigen::SelfAdjointEigenSolver<Matrix3d> es(cov_);\n    int smallest = 0;\n\n    for (int i = 1; i < 3; i++)\n    {\n        if (abs(es.eigenvalues()[i]) < abs(es.eigenvalues()[smallest]))\n            smallest = i;\n    }\n    // Plane normal is the eigenvector corresponding to the smallest eigenvalue\n    normal_ = es.eigenvectors().col(smallest);\n    normal_.normalize();\n}\n", "meta": {"hexsha": "696ce62a41426301028e93b5ec8ddb47083c1db3", "size": 2983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common/covariance.cpp", "max_stars_repo_name": "chaowang15/plane-opt-rgbd", "max_stars_repo_head_hexsha": "b03c4779f21b8b2d81d667c0d91cc1b4f8c59bc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2018-10-30T08:08:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T12:42:36.000Z", "max_issues_repo_path": "common/covariance.cpp", "max_issues_repo_name": "chaowang15/plane-opt-rgbd", "max_issues_repo_head_hexsha": "b03c4779f21b8b2d81d667c0d91cc1b4f8c59bc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-03-24T15:34:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T14:00:14.000Z", "max_forks_repo_path": "common/covariance.cpp", "max_forks_repo_name": "chaowang15/plane-opt-rgbd", "max_forks_repo_head_hexsha": "b03c4779f21b8b2d81d667c0d91cc1b4f8c59bc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2018-12-30T13:53:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T19:21:34.000Z", "avg_line_length": 26.3982300885, "max_line_length": 114, "alphanum_fraction": 0.5692256118, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6052564869785145}}
{"text": "/*\n * This is part of the fl library, a C++ Bayesian filtering library\n * (https://github.com/filtering-library)\n *\n * Copyright (c) 2015 Max Planck Society,\n * \t\t\t\t Autonomous Motion Department,\n * \t\t\t     Institute for Intelligent Systems\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n */\n\n/**\n * \\file linear_algebra_smw_inversion_test.cpp\n * \\date 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <iostream>\n#include <vector>\n#include <ctime>\n\n#include <fl/util/math.hpp>\n\ntypedef Eigen::Matrix<double, 3, 1> State;\ntypedef Eigen::Matrix<double, 1, 1> Observation;\n\nconst int SUBSAMPLING_FACTOR = 8;\nconst int OBSERVATION_DIMENSION = (640*480)/(SUBSAMPLING_FACTOR*SUBSAMPLING_FACTOR);\n\n//const int INV_DIMENSION = 14;\n//const int INVERSION_ITERATIONS = OBSERVATION_DIMENSION * 30;\n\nTEST(InversionTests, SMWInversion)\n{\n    Eigen::MatrixXd cov = Eigen::MatrixXd::Random(15, 15);\n    cov = cov * cov.transpose();\n\n    Eigen::MatrixXd A = cov.block(0,   0, 14, 14);\n    Eigen::MatrixXd B = cov.block(0,  14, 14,  1);\n    Eigen::MatrixXd C = cov.block(14,  0, 1,  14);\n    Eigen::MatrixXd D = cov.block(14, 14, 1,   1);\n\n    Eigen::MatrixXd L_A;\n    Eigen::MatrixXd L_B;\n    Eigen::MatrixXd L_C;\n    Eigen::MatrixXd L_D;\n\n    Eigen::MatrixXd cov_inv = cov.inverse();\n    Eigen::MatrixXd cov_smw_inv;\n\n    Eigen::MatrixXd A_inv = A.inverse();\n    fl::smw_inverse(A_inv, B, C, D, L_A, L_B, L_C, L_D, cov_smw_inv);\n\n    EXPECT_TRUE(cov_smw_inv.isApprox(cov_inv));\n}\n\n\nTEST(InversionTests, SMWInversion_no_Lx)\n{\n    Eigen::MatrixXd cov = Eigen::MatrixXd::Random(15, 15);\n    cov = cov * cov.transpose();\n\n    Eigen::MatrixXd A = cov.block(0,   0, 14, 14);\n    Eigen::MatrixXd B = cov.block(0,  14, 14,  1);\n    Eigen::MatrixXd C = cov.block(14,  0, 1,  14);\n    Eigen::MatrixXd D = cov.block(14, 14, 1,   1);\n\n    Eigen::MatrixXd cov_inv = cov.inverse();\n    Eigen::MatrixXd cov_smw_inv;\n\n    Eigen::MatrixXd A_inv = A.inverse();\n    fl::smw_inverse(A_inv, B, C, D, cov_smw_inv);\n\n    EXPECT_TRUE(cov_smw_inv.isApprox(cov_inv));\n}\n\n// speed performance tests\n//TEST(InversionTests, fullMatrixInversionSpeed)\n//{\n//    Eigen::MatrixXd cov = Eigen::MatrixXd::Random(INV_DIMENSION, INV_DIMENSION);\n//    cov = cov * cov.transpose();\n\n//    Eigen::MatrixXd cov_inv;\n\n//    std::clock_t start = std::clock();\n//    int number_of_inversions = 0;\n//    while ( (( std::clock() - start ) / (double) CLOCKS_PER_SEC) < 1.0 )\n//    {\n//        cov_inv = cov.inverse();\n//        number_of_inversions++;\n//    }\n\n////    std::cout << \"fullMatrixInversionSpeed::number_of_inversions: \"\n////              << number_of_inversions\n////              << \"(\" << number_of_inversions/OBSERVATION_DIMENSION << \" fps)\"\n////              << std::endl;\n\n//}\n\n//TEST(InversionTests, SMWMatrixInversionSpeed)\n//{\n//    Eigen::MatrixXd cov = Eigen::MatrixXd::Random(INV_DIMENSION, INV_DIMENSION);\n//    cov = cov * cov.transpose();\n\n//    Eigen::MatrixXd A = cov.block(0, 0, INV_DIMENSION-1, INV_DIMENSION-1);\n//    Eigen::MatrixXd B = cov.block(0, INV_DIMENSION-1, INV_DIMENSION-1, 1);\n//    Eigen::MatrixXd C = cov.block(INV_DIMENSION-1, 0, 1, INV_DIMENSION-1);\n//    Eigen::MatrixXd D = cov.block(INV_DIMENSION-1, INV_DIMENSION-1, 1, 1);\n//    Eigen::MatrixXd A_inv = A.inverse();\n\n//    Eigen::MatrixXd L_A = Eigen::MatrixXd(INV_DIMENSION-1, INV_DIMENSION-1);\n//    Eigen::MatrixXd L_B = Eigen::MatrixXd(INV_DIMENSION-1, 1);\n//    Eigen::MatrixXd L_C = Eigen::MatrixXd(1, INV_DIMENSION-1);\n//    Eigen::MatrixXd L_D = Eigen::MatrixXd(1, 1);\n\n//    Eigen::MatrixXd cov_smw_inv;\n//    std::clock_t start = std::clock();\n//    int number_of_inversions = 0;\n//    while ( ((std::clock() - start) / (double) CLOCKS_PER_SEC) < 1.0 )\n//    {\n//        fl::smw_inverse(A_inv, B, C, D, L_A, L_B, L_C, L_D, cov_smw_inv);\n//        number_of_inversions++;\n//    }\n\n////    std::cout << \"SMWMatrixInversionSpeed::number_of_inversions: \"\n////              << number_of_inversions\n////              << \"(\" << number_of_inversions/OBSERVATION_DIMENSION << \" fps)\"\n////              << std::endl;\n//}\n\n//TEST(InversionTests, SMWBlockMatrixInversionSpeed)\n//{\n//    Eigen::MatrixXd cov = Eigen::MatrixXd::Random(INV_DIMENSION, INV_DIMENSION);\n//    cov = cov * cov.transpose();\n\n//    Eigen::MatrixXd A = cov.block(0, 0, INV_DIMENSION-1, INV_DIMENSION-1);\n//    Eigen::MatrixXd B = cov.block(0, INV_DIMENSION-1, INV_DIMENSION-1, 1);\n//    Eigen::MatrixXd C = cov.block(INV_DIMENSION-1, 0, 1, INV_DIMENSION-1);\n//    Eigen::MatrixXd D = cov.block(INV_DIMENSION-1, INV_DIMENSION-1, 1, 1);\n//    Eigen::MatrixXd A_inv = A.inverse();\n\n//    Eigen::MatrixXd L_A = Eigen::MatrixXd(INV_DIMENSION-1, INV_DIMENSION-1);\n//    Eigen::MatrixXd L_B = Eigen::MatrixXd(INV_DIMENSION-1, 1);\n//    Eigen::MatrixXd L_C = Eigen::MatrixXd(1, INV_DIMENSION-1);\n//    Eigen::MatrixXd L_D = Eigen::MatrixXd(1, 1);\n\n//    std::clock_t start = std::clock();\n//    int number_of_inversions = 0;\n//    while ( (( std::clock() - start ) / (double) CLOCKS_PER_SEC) < 1.0 )\n//    {\n//        fl::smw_inverse(A_inv, B, C, D, L_A, L_B, L_C, L_D);\n//        number_of_inversions++;\n//    }\n\n////    std::cout << \"SMWMatrixBlockInversionSpeed::number_of_inversions: \"\n////              << number_of_inversions\n////              << \"(\" << number_of_inversions/OBSERVATION_DIMENSION << \" fps)\"\n////              << std::endl;\n//}\n", "meta": {"hexsha": "3c5df15b610821b55d3d9b73795b11fa721c250f", "size": 5558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/utils/linear_algebra_smw_inversion_test.cpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "test/utils/linear_algebra_smw_inversion_test.cpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "test/utils/linear_algebra_smw_inversion_test.cpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 33.2814371257, "max_line_length": 84, "alphanum_fraction": 0.6353004678, "num_tokens": 1656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105442, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6052564777294253}}
{"text": "//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#include <boost/gil.hpp>\n#include <boost/gil/extension/io/png.hpp>\n#include <cmath>\n#include <limits>\n#include <vector>\n\nnamespace gil = boost::gil;\n\n// Demonstrates the use of a rasterizer to generate an image of a circle\n// The various rasterizers available are defined in include/boost/gil/rasterization/circle.hpp,\n// include/boost/gil/rasterization/ellipse.hpp and include/boost/gil/rasterization/line.hpp\n// This example uses a trigonometric rasterizer; GIL also offers the rasterizer midpoint_circle_rasterizer,\n// which implements the Midpoint algorithm.\n// See also:\n// rasterizer_ellipse.cpp - Demonstrates the use of a rasterizer to generate an image of an ellipse\n// rasterizer_line.cpp - Demonstrates the use of a rasterizer to generate an image of a line\n\nint main()\n{\n    const std::ptrdiff_t size = 256;\n    gil::gray8_image_t buffer_image(size, size);\n    auto buffer = gil::view(buffer_image);\n\n    const std::ptrdiff_t radius = 64;\n    const auto rasterizer = gil::trigonometric_circle_rasterizer{};\n    std::vector<gil::point_t> circle_points(rasterizer.point_count(radius));\n    rasterizer(radius, {128, 128}, circle_points.begin());\n    for (const auto& point : circle_points)\n    {\n        buffer(point) = std::numeric_limits<gil::uint8_t>::max();\n    }\n\n    gil::write_view(\"circle.png\", buffer, gil::png_tag{});\n}\n", "meta": {"hexsha": "2c56de31999ab6b150737705ce11f2b5df82f798", "size": 1608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/rasterizer_circle.cpp", "max_stars_repo_name": "DhruvaG2000/gil", "max_stars_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/rasterizer_circle.cpp", "max_issues_repo_name": "DhruvaG2000/gil", "max_issues_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/rasterizer_circle.cpp", "max_forks_repo_name": "DhruvaG2000/gil", "max_forks_repo_head_hexsha": "0b24f4cdbf430430b5430507822b0698cd9d2ac7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3953488372, "max_line_length": 107, "alphanum_fraction": 0.7394278607, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6052535993387815}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/bool.hpp>\n#include <boost/hana/config.hpp>\n#include <boost/hana/either.hpp>\n#include <boost/hana/functional.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <string>\nusing namespace boost::hana;\nusing namespace std::literals;\n\n\nint main() {\n\n{\n\n//! [comparable]\nBOOST_HANA_CONSTEXPR_CHECK(left('x') == left('x'));\nBOOST_HANA_CONSTANT_CHECK(right('x') != left('x'));\nBOOST_HANA_CONSTEXPR_CHECK(right('x') == right('x'));\nBOOST_HANA_CONSTEXPR_CHECK(right('x') != right('y'));\n//! [comparable]\n\n}{\n\n//! [orderable]\n// left is always less than right, regardless of what's in it\nBOOST_HANA_CONSTANT_CHECK(left(2000) < right(2));\n\n// when comparing two lefts or two rights, we compare the contents\nBOOST_HANA_CONSTEXPR_CHECK(left(2) < left(2000));\nBOOST_HANA_CONSTEXPR_CHECK(right(2) < right(2000));\n//! [orderable]\n\n}{\n\n//! [functor]\nauto safe_div = infix([](auto x, auto y) {\n    return eval_if(y == int_<0>,\n        always(left(\"division by zero\"s)),\n        [=](auto _) { return right(x / _(y)); }\n    );\n});\n\nBOOST_HANA_CONSTANT_CHECK(\n    transform(int_<6> ^safe_div^ int_<3>, succ) == right(int_<3>)\n);\n\nBOOST_HANA_RUNTIME_CHECK(\n    transform(int_<6> ^safe_div^ int_<0>, succ) == left(\"division by zero\"s)\n);\n//! [functor]\n\n}{\n\n//! [monad]\nauto safe_div = [](auto x, auto y) {\n    return eval_if(y == int_<0>,\n        always(left(\"division by zero\"s)),\n        [=](auto _) { return right(x / _(y)); }\n    );\n};\n\nauto safe_dec = [](auto x) {\n    return eval_if(x == int_<0>,\n        always(left(\"negative value\"s)),\n        [=](auto _) { return right(_(x) - int_<1>); }\n    );\n};\n\nBOOST_HANA_RUNTIME_CHECK(\n    (safe_div(int_<4>, int_<0>) | safe_dec) == left(\"division by zero\"s)\n);\n\nBOOST_HANA_RUNTIME_CHECK(\n    (safe_div(int_<0>, int_<2>) | safe_dec) == left(\"negative value\"s)\n);\n\nBOOST_HANA_CONSTANT_CHECK(\n    (safe_div(int_<4>, int_<2>) | safe_dec) == right(int_<1>)\n);\n//! [monad]\n\n}{\n\n//! [foldable]\nBOOST_HANA_CONSTANT_CHECK(unpack(left('x'), make<Tuple>) == make<Tuple>());\nBOOST_HANA_CONSTEXPR_CHECK(unpack(right('x'), make<Tuple>) == make<Tuple>('x'));\n//! [foldable]\n\n}{\n\n//! [traversable]\nBOOST_HANA_CONSTEXPR_LAMBDA auto duplicate = [](auto x) {\n    return make<Tuple>(x, x);\n};\n\nBOOST_HANA_CONSTEXPR_CHECK(\n    traverse<Tuple>(left(1), duplicate) == make<Tuple>(left(1))\n);\nBOOST_HANA_CONSTEXPR_CHECK(\n    traverse<Tuple>(right(1), duplicate) == make<Tuple>(right(1), right(1))\n);\n//! [traversable]\n\n}{\n\n//! [either]\nBOOST_HANA_CONSTEXPR_CHECK(either(succ, pred, left(1)) == 2);\nBOOST_HANA_CONSTEXPR_CHECK(either(succ, pred, right(1)) == 0);\n//! [either]\n\n}{\n\n//! [left]\nconstexpr auto left_value = left('x');\n//! [left]\n\n//! [right]\nconstexpr auto right_value = right('x');\n//! [right]\n\n(void)left_value;\n(void)right_value;\n}\n\n}\n", "meta": {"hexsha": "fd22ee15a5d48d599efd772a89d1fb3c08b1cb26", "size": 3019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/either.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/either.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/either.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.362962963, "max_line_length": 80, "alphanum_fraction": 0.6541901292, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619220634456, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6052535961724324}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright Christopher Kormanyos 2015.\r\n//  Copyright Nikhar Agrawal 2015.\r\n//  Copyright Paul Bristow 2015.\r\n//  Distributed under the Boost Software License,\r\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//! \\file\r\n//!\\brief Tests for the hyperbolic arctangent function of (fixed_point) for a small digit range.\r\n\r\n#include <cmath>\r\n\r\n#define BOOST_TEST_MODULE test_negatable_func_hyperbolic_arctangent_small\r\n#define BOOST_LIB_DIAGNOSTIC\r\n\r\n#include <boost/fixed_point/fixed_point.hpp>\r\n#include <boost/test/included/unit_test.hpp>\r\n\r\nBOOST_AUTO_TEST_CASE(test_negatable_func_hyperbolic_arctangent_small)\r\n{\r\n  typedef boost::fixed_point::negatable<7, -24> fixed_point_type;\r\n  typedef fixed_point_type::float_type          float_point_type;\r\n\r\n  const fixed_point_type tol = ldexp(fixed_point_type(1), fixed_point_type::resolution + 4);\r\n\r\n  BOOST_CONSTEXPR int i_max = 32;\r\n\r\n  // Check positive arguments.\r\n  for(int i = 0; i < i_max; ++i)\r\n  {\r\n    const fixed_point_type x = atanh(fixed_point_type(i) / i_max);\r\n\r\n    using std::atanh;\r\n    const float_point_type y = atanh(float_point_type(i) / i_max);\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n\r\n  // Check negative arguments.\r\n  for(int i = 0; i < 9; ++i)\r\n  {\r\n    const fixed_point_type x = atanh(fixed_point_type(-i) / i_max);\r\n\r\n    using std::atanh;\r\n    const float_point_type y = atanh(float_point_type(-i) / i_max);\r\n\r\n    BOOST_CHECK_CLOSE_FRACTION(x, fixed_point_type(y), tol);\r\n  }\r\n}\r\n", "meta": {"hexsha": "a2f398115b4723da5138db80dce8eae7a032a13d", "size": 1638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_negatable_func_hyperbolic_arctangent_small.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_negatable_func_hyperbolic_arctangent_small.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_negatable_func_hyperbolic_arctangent_small.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1176470588, "max_line_length": 97, "alphanum_fraction": 0.6794871795, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581194449494, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6052178678637845}}
{"text": "//\n// Created by Amir Masoud Abdol on 2019-01-24.\n//\n\n#include <spdlog/spdlog.h>\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/students_t.hpp>\n\n#include \"TestStrategy.h\"\n\nusing namespace sam;\n\nusing boost::math::students_t;\n\nTestStrategy::~TestStrategy(){\n    // Pure destructors\n};\n\nstd::unique_ptr<TestStrategy> TestStrategy::build(json &test_strategy_config) {\n\n  if (test_strategy_config[\"name\"] == \"TTest\") {\n\n    auto params = test_strategy_config.get<TTest::Parameters>();\n    return std::make_unique<TTest>(params);\n\n  } else if (test_strategy_config[\"name\"] == \"YuenTest\") {\n\n    auto params = test_strategy_config.get<YuenTest::Parameters>();\n    return std::make_unique<YuenTest>(params);\n\n  } else if (test_strategy_config[\"name\"] == \"WilcoxonTest\") {\n    auto params = test_strategy_config.get<WilcoxonTest::Parameters>();\n    return std::make_unique<WilcoxonTest>(params);\n  } else {\n    spdlog::critical(\"Unknown Test Strategy.\");\n    exit(1);\n  }\n}\n\n\nnamespace sam {\n\n///\n/// Calculate confidence intervals for the mean. For example if we set the\n/// confidence limit to 0.95, we know that if we repeat the sampling 100 times,\n/// then we expect that the true mean will be between out limits on 95 occasions.\n/// Note: this is not the same as saying a 95% confidence interval means that there\n/// is a 95% probability that the interval contains the true mean. The interval\n/// computed from a given sample either contains the true mean or it does not.\n///\n/// @note       Obtained from [Boost Library\n///             Example](https://www.boost.org/doc/libs/1_69_0/libs/math/doc/html/math_toolkit/stat_tut/weg/st_eg/paired_st.html).\n///\n/// @param      Sm    Sample Mean.\n/// @param      Sd    Sample Standard Deviation.\n/// @param      Sn    Sample Size.\n///\nstd::pair<float, float>\nconfidence_limits_on_mean(float Sm, float Sd, unsigned Sn, float alpha,\n                          TestStrategy::TestAlternative alternative) {\n\n  using namespace sam;\n\n  students_t dist(Sn - 1);\n\n  // calculate T\n  float T =\n      quantile(complement(dist, alpha / 2)); // TODO: Implement the side!./sa\n\n  // Calculate width of interval (one sided):\n  float w = T * Sd / sqrt(float(Sn));\n\n  // Calculate and return the interval\n  return std::make_pair(Sm - w, Sm + w);\n}\n\n///\n/// Caculate the degress of freedom to achieve a significance result with the given\n/// alpha\n///\n/// @param      M     True Mean.\n/// @param      Sm    Sample Mean.\n/// @param      Sd    Sample Standard Deviation.\n///\nfloat single_sample_find_df(float M, float Sm, float Sd, float alpha,\n                             TestStrategy::TestAlternative alternative) {\n  using namespace sam;\n  using boost::math::students_t;\n\n  // calculate df for one-sided or two-sided test:\n  float df = students_t::find_degrees_of_freedom(\n      fabs(M - Sm),\n      (alternative == TestStrategy::TestAlternative::Greater) ? alpha\n                                                              : alpha / 2.,\n      alpha, Sd);\n\n  // convert to sample size, always one more than the degrees of freedom:\n  return ceil(df) + 1;\n}\n\n\n\n\n\nfloat win_var(const arma::Row<float> &x, const float trim) {\n  return arma::var(win_val(x, trim));\n}\n\nstd::pair<float, float> win_cor_cov(const arma::Row<float> &x,\n                                      const arma::Row<float> &y,\n                                      const float trim) {\n\n  arma::Row<float> xvec{win_val(x, trim)};\n  arma::Row<float> yvec{win_val(y, trim)};\n\n  arma::Mat<float> wcor{arma::cor(xvec, yvec)};\n  float vwcor{static_cast<float>(wcor.at(0, 0))};\n\n  arma::Mat<float> wcov{arma::cov(xvec, yvec)};\n  float vwcov{static_cast<float>(wcov.at(0, 0))};\n\n  return std::make_pair(vwcor, vwcov);\n}\n\narma::Row<float> win_val(const arma::Row<float> &x, float trim) {\n\n  arma::Row<float> y{arma::sort(x)};\n\n  auto ibot = floor(trim * x.n_elem) + 1;\n  auto itop = x.n_elem - ibot + 1;\n\n  float xbot{y.at(ibot - 1)};\n  float xtop{y.at(itop - 1)};\n\n  return arma::clamp(x, xbot, xtop);\n}\n\n// TODO: this can be an extention to arma, something like I did for\n// nlohmann::json I should basically put it into arma's namespace\nfloat trim_mean(const arma::Row<float> &x, float trim) {\n  arma::Row<float> y{arma::sort(x)};\n\n  auto ibot = floor(trim * x.n_elem) + 1;\n  auto itop = x.n_elem - ibot + 1;\n\n  return arma::mean(y.subvec(ibot - 1, itop - 1));\n}\n\n\n\nfloat tie_correct(const arma::Col<float> &rankvals) {\n\n  arma::Col<float> arr = arma::sort(rankvals);\n\n  arma::uvec vindx = arma::join_cols(\n      arma::uvec({1}), arr.tail(arr.n_elem - 1) != arr.head(arr.n_elem - 1));\n\n  arma::uvec vvindx = arma::join_cols(vindx, arma::uvec({1}));\n\n  arma::uvec indx = nonzeros_index(vvindx);\n\n  arma::uvec cnt = arma::diff(indx);\n\n  auto size = arr.n_elem;\n\n  if (size < 2) {\n    return 1.0;\n  }\n\n  return 1.0 - arma::accu(arma::pow(cnt, 3) - cnt) / (std::pow(size, 3) - size);\n}\n\narma::Col<float> rankdata(const arma::Row<float> &arr,\n                   const std::string method = \"average\") {\n\n  // if method not in ('average', 'min', 'max', 'dense', 'ordinal'):\n  //     raise ValueError('unknown method \"{0}\"'.format(method))\n\n  // arr = np.ravel(np.asarray(a))\n  // > This is always true, for now\n\n  // algo = 'mergesort' if method == 'ordinal' else 'quicksort'\n  arma::uvec sorter = arma::stable_sort_index(arr);\n\n  // inv = np.empty(sorter.size, dtype=np.intp)\n  // inv[sorter] = np.arange(sorter.size, dtype=np.intp)\n\n  arma::uvec inv(sorter.n_elem);\n\n  inv.elem(sorter) = arma::regspace<arma::uvec>(0, sorter.n_elem - 1);\n\n  //        if (method == \"ordinal\")\n  //            return inv + 1;\n\n  arma::Col<float> arr_sorted(arr.n_elem);\n  arr_sorted = arr(sorter);\n\n  // obs = np.r_[True, arr[1:] != arr[:-1]]\n  arma::uvec obs = arma::join_cols(arma::uvec({1}),\n                                   arr_sorted.tail(arr_sorted.n_elem - 1) !=\n                                       arr_sorted.head(arr_sorted.n_elem - 1));\n\n  // dense = obs.cumsum()[inv]\n  arma::uvec dense = arma::cumsum(obs); //.elem(inv);\n  arma::uvec dense_sorted(dense.n_elem);\n  dense_sorted = dense(inv);\n\n  if (method == \"dense\")\n    return arma::conv_to<arma::Col<float>>::from(dense_sorted);\n\n  // cumulative counts of each unique value\n  // count = [np.r_[np.nonzero(obs)[0], len(obs)]]\n  arma::uvec count =\n      arma::join_cols(nonzeros_index(obs), arma::uvec({obs.n_elem}));\n\n  //        if (method == \"max\")\n  //            return count(dense_sorted);\n  //\n  //        if (method == \"min\")\n  //            return count(dense_sorted - 1) + 1;\n\n  // average method\n  return .5 * arma::conv_to<arma::Col<float>>::from(\n                  (count(dense_sorted) + count(dense_sorted - 1) + 1));\n}\n\n} // namespace sam\n", "meta": {"hexsha": "293eeb90111632d3aa5ea1d676a62465719876da", "size": 6717, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/src/TestStrategy.cpp", "max_stars_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_stars_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-25T20:21:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:21:41.000Z", "max_issues_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/src/TestStrategy.cpp", "max_issues_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_issues_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sam-project/bakker-et-al-2012/SAM/SAM/src/TestStrategy.cpp", "max_forks_repo_name": "amirmasoudabdol/bakker-et-al-2012-reproduction-using-sam", "max_forks_repo_head_hexsha": "518ab1cebaa80c19a12e92db8ae87386512ae053", "max_forks_repo_licenses": ["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.3318777293, "max_line_length": 130, "alphanum_fraction": 0.6246836385, "num_tokens": 1853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6052178488038896}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[simplify\r\n//` Example showing how to simplify a linestring\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/linestring.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n\r\n/*< For this example we use Boost.Assign to add points >*/\r\n#include <boost/assign.hpp>\r\n\r\nusing namespace boost::assign;\r\n\r\n\r\nint main()\r\n{\r\n    typedef boost::geometry::model::d2::point_xy<double> xy;\r\n\r\n    boost::geometry::model::linestring<xy> line;\r\n    line += xy(1.1, 1.1), xy(2.5, 2.1), xy(3.1, 3.1), xy(4.9, 1.1), xy(3.1, 1.9); /*< With Boost.Assign >*/\r\n\r\n    // Simplify it, using distance of 0.5 units\r\n    boost::geometry::model::linestring<xy> simplified;\r\n    boost::geometry::simplify(line, simplified, 0.5);\r\n    std::cout\r\n        << \"  original: \" << boost::geometry::dsv(line) << std::endl\r\n        << \"simplified: \" << boost::geometry::dsv(simplified) << std::endl;\r\n\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[simplify_output\r\n/*`\r\nOutput:\r\n[pre\r\n  original: ((1.1, 1.1), (2.5, 2.1), (3.1, 3.1), (4.9, 1.1), (3.1, 1.9))\r\nsimplified: ((1.1, 1.1), (3.1, 3.1), (4.9, 1.1), (3.1, 1.9))\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "049469875cd5aeac0e79777b27cadf1a11ecd3cb", "size": 1475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/simplify.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/simplify.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/simplify.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8181818182, "max_line_length": 108, "alphanum_fraction": 0.6216949153, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6052178408010761}}
{"text": "/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https://github.com/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n */\n\n/**\n * @date 2015\n * @author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * Max-Planck-Institute for Intelligent Systems\n */\n\n#include <gtest/gtest.h>\n\n#include <Eigen/Core>\n\n#include <fl/util/math/linear_algebra.hpp>\n\n#include <fl/filter/particle/particle_filter.hpp>\n#include <fl/filter/gaussian/gaussian_filter_kf.hpp>\n#include <fl/model/sensor/linear_sensor.hpp>\n#include <fl/model/process/linear_transition.hpp>\n\ntemplate<typename Vector, typename Matrix>\nbool moments_are_similar(Vector mean_a, Matrix cov_a,\n                         Vector mean_b, Matrix cov_b, double epsilon = 0.1)\n{\n    Matrix cov_delta = cov_a.inverse() * cov_b;\n    bool are_similar = cov_delta.isApprox(Matrix::Identity(), epsilon);\n\n    Matrix square_root = fl::matrix_sqrt(cov_a);\n    double max_mean_delta =\n            (square_root.inverse() * (mean_a-mean_b)).cwiseAbs().maxCoeff();\n\n    are_similar = are_similar && max_mean_delta < epsilon;\n\n    return are_similar;\n}\n\nEigen::Matrix<double, 3, 3> some_rotation()\n{\n    double angle = 2 * M_PI * double(rand()) / double(RAND_MAX);\n\n    Eigen::Matrix<double, 3, 3> R = Eigen::Matrix<double, 3, 3>::Identity();\n\n    R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitX());\n    R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ());\n    R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitY());\n    return R;\n}\n\nTEST(particle_filter, predict)\n{\n    typedef Eigen::Matrix<double, 3, 1> State;\n    typedef Eigen::Matrix<double, 3, 1> Observation;\n    typedef Eigen::Matrix<double, 3, 1> Input;\n\n    typedef Eigen::Matrix<double, 3, 3> Matrix;\n\n    typedef fl::LinearGaussianProcessModel<State, Input> ProcessModel;\n    typedef fl::LinearObservationModel<Observation, State> ObservationModel;\n\n    // particle filter\n    typedef fl::ParticleFilter<ProcessModel, ObservationModel> ParticleFilter;\n    typedef ParticleFilter::Belief ParticleBelief;\n\n    // gaussian filter\n    typedef fl::GaussianFilter<ProcessModel, ObservationModel> GaussianFilter;\n    typedef GaussianFilter::Belief GaussianBelief;\n\n\n    srand(0);\n    size_t N_particles = 10000;\n    size_t N_steps = 10;\n    size_t delta_time = 1;\n\n\n    // create process model\n    ProcessModel transition;\n    {\n        transition.A(some_rotation());\n        Matrix R = some_rotation();\n        Matrix D = Eigen::DiagonalMatrix<double, 3>(1, 3.5, 1.2);\n        transition.covariance(R*D*R.transpose());\n    }\n\n    // create observation model\n    /// \\todo this is a hack because the GF does not currently work with the new\n    /// observation model interface\n    ObservationModel sensor;\n    {\n        sensor.sensor_matrix(some_rotation());\n        Matrix R = some_rotation();\n        Matrix D = Eigen::DiagonalMatrix<double, 3>(3.1, 1.0, 1.3);\n        D = D.cwiseSqrt();\n        sensor.noise_matrix(R*D);\n    }\n\n    // create filters\n    ParticleFilter particle_filter(transition, sensor);\n    GaussianFilter gaussian_filter(transition, sensor);\n\n    // create intial beliefs\n    GaussianBelief gaussian_belief;\n    {\n        gaussian_belief.mean(State::Zero());\n        gaussian_belief.covariance(Matrix::Identity());\n    }\n    ParticleBelief particle_belief;\n    particle_belief.from_distribution(gaussian_belief, N_particles);\n\n    // run prediction\n    for(size_t i = 0; i < N_steps; i++)\n    {\n        particle_filter.predict(delta_time, State::Zero(),\n                                particle_belief, particle_belief);\n\n        gaussian_filter.predict(delta_time, State::Zero(),\n                                gaussian_belief, gaussian_belief);\n\n        EXPECT_TRUE(moments_are_similar(\n                        particle_belief.mean(), particle_belief.covariance(),\n                        gaussian_belief.mean(), gaussian_belief.covariance()));\n    }\n}\n\nTEST(particle_filter, update)\n{\n    typedef Eigen::Matrix<double, 3, 1> State;\n    typedef Eigen::Matrix<double, 3, 1> Observation;\n    typedef Eigen::Matrix<double, 3, 1> Input;\n\n    typedef Eigen::Matrix<double, 3, 3> Matrix;\n\n    typedef fl::LinearGaussianProcessModel<State, Input> ProcessModel;\n    typedef fl::LinearObservationModel<Observation, State> ObservationModel;\n    // particle filter\n    typedef fl::ParticleFilter<ProcessModel, ObservationModel> ParticleFilter;\n    typedef ParticleFilter::Belief ParticleBelief;\n\n    // gaussian filter\n    typedef fl::GaussianFilter<ProcessModel, ObservationModel> GaussianFilter;\n    typedef GaussianFilter::Belief GaussianBelief;\n\n\n    srand(0);\n    size_t N_particles = 10000;\n    size_t N_steps = 10;\n\n\n    // create process model\n    ProcessModel transition;\n    {\n        transition.A(some_rotation());\n        Matrix R = some_rotation();\n        Matrix D = Eigen::DiagonalMatrix<double, 3>(1, 3.5, 1.2);\n        transition.covariance(R*D*R.transpose());\n    }\n\n    // create observation model\n    /// \\todo this is a hack because the GF does not currently work with the new\n    /// observation model interface\n    ObservationModel sensor;\n    {\n        sensor.sensor_matrix(some_rotation());\n        Matrix R = some_rotation();\n        Matrix D = Eigen::DiagonalMatrix<double, 3>(3.1, 1.0, 1.3);\n        D = D.cwiseSqrt();\n        sensor.noise_matrix(R*D);\n    }\n\n    // create filters\n    ParticleFilter particle_filter(transition, sensor);\n    GaussianFilter gaussian_filter(transition, sensor);\n\n    // create intial beliefs\n    GaussianBelief gaussian_belief;\n    {\n        gaussian_belief.mean(State::Zero());\n        gaussian_belief.covariance(Matrix::Identity());\n    }\n    ParticleBelief particle_belief;\n    particle_belief.from_distribution(gaussian_belief, N_particles);\n\n\n    // run prediction\n    for(size_t i = 0; i < N_steps; i++)\n    {\n        Observation observation(0.5, 0.5, 0.5);\n\n        particle_filter.update(observation, particle_belief, particle_belief);\n        gaussian_filter.update(observation, gaussian_belief, gaussian_belief);\n\n        EXPECT_TRUE(moments_are_similar(\n                        particle_belief.mean(), particle_belief.covariance(),\n                        gaussian_belief.mean(), gaussian_belief.covariance()));\n    }\n\n}\n\nTEST(particle_filter, predict_and_update)\n{\n    typedef Eigen::Matrix<double, 3, 1> State;\n    typedef Eigen::Matrix<double, 3, 1> Observation;\n    typedef Eigen::Matrix<double, 3, 1> Input;\n\n    typedef Eigen::Matrix<double, 3, 3> Matrix;\n\n    typedef fl::LinearGaussianProcessModel<State, Input> ProcessModel;\n    typedef fl::LinearObservationModel<Observation, State> ObservationModel;\n\n    // particle filter\n    typedef fl::ParticleFilter<ProcessModel, ObservationModel> ParticleFilter;\n    typedef ParticleFilter::Belief ParticleBelief;\n\n    // gaussian filter\n    typedef fl::GaussianFilter<ProcessModel, ObservationModel> GaussianFilter;\n    typedef GaussianFilter::Belief GaussianBelief;\n\n\n    srand(0);\n    size_t N_particles = 10000;\n    size_t N_steps = 10;\n    size_t delta_time = 1;\n\n\n    // create process model\n    ProcessModel transition;\n    {\n        transition.A(some_rotation());\n        Matrix R = some_rotation();\n        Matrix D = Eigen::DiagonalMatrix<double, 3>(1, 3.5, 1.2);\n        transition.covariance(R*D*R.transpose());\n    }\n\n    // create observation model\n    /// \\todo this is a hack because the GF does not currently work with the new\n    /// observation model interface\n    ObservationModel sensor;\n    {\n        sensor.sensor_matrix(some_rotation());\n        Matrix R = some_rotation();\n        Matrix D = Eigen::DiagonalMatrix<double, 3>(3.1, 1.0, 1.3);\n        D = D.cwiseSqrt();\n        sensor.noise_matrix(R*D);\n    }\n\n    // create filters\n    ParticleFilter particle_filter(transition, sensor);\n    GaussianFilter gaussian_filter(transition, sensor);\n\n    // create intial beliefs\n    GaussianBelief gaussian_belief;\n    {\n        gaussian_belief.mean(State::Zero());\n        gaussian_belief.covariance(Matrix::Identity());\n    }\n    ParticleBelief particle_belief;\n    particle_belief.from_distribution(gaussian_belief, N_particles);\n\n\n    fl::StandardGaussian<State> standard_gaussian;\n    State state = gaussian_belief.sample();\n    // run prediction\n    for(size_t i = 0; i < N_steps; i++)\n    {\n        // simulate system\n        state = transition.predict_state(delta_time,\n                                            state,\n                                            standard_gaussian.sample(),\n                                            State::Zero());\n        Observation observation =\n                sensor.observation(state, standard_gaussian.sample());\n\n        // predict\n        particle_filter.predict(delta_time, State::Zero(),\n                                particle_belief, particle_belief);\n        gaussian_filter.predict(delta_time, State::Zero(),\n                                gaussian_belief, gaussian_belief);\n\n        // update\n        particle_filter.update(observation, particle_belief, particle_belief);\n        gaussian_filter.update(observation, gaussian_belief, gaussian_belief);\n    }\n\n    State delta = particle_belief.mean() - gaussian_belief.mean();\n    double mh_distance = delta.transpose() * gaussian_belief.precision() * delta;\n\n    // make sure that the estimate of the pf is within one std dev\n    EXPECT_TRUE(std::sqrt(mh_distance) <= 1.0);\n}\n", "meta": {"hexsha": "ff5ba6317c66dcfc6c5b78b0d83ee77c9a8f7499", "size": 9743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/particle_filter/particle_filter_test.cpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "test/particle_filter/particle_filter_test.cpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "test/particle_filter/particle_filter_test.cpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 32.3687707641, "max_line_length": 81, "alphanum_fraction": 0.6644770605, "num_tokens": 2277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.845942452844325, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6052075400823207}}
{"text": "/*\n * math.cpp\n *\n *  Created on: Apr 30, 2021\n *      Author: jelavice\n */\n\n#include \"icp_localization/common/math.hpp\"\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace icp_loco {\n\nEigen::Quaterniond fromRPY(const double roll, const double pitch, const double yaw)\n{\n\n  const Eigen::AngleAxisd roll_angle(roll, Eigen::Vector3d::UnitX());\n  const Eigen::AngleAxisd pitch_angle(pitch, Eigen::Vector3d::UnitY());\n  const Eigen::AngleAxisd yaw_angle(yaw, Eigen::Vector3d::UnitZ());\n  return yaw_angle * pitch_angle * roll_angle;\n}\n\nEigen::Vector3d toRPY(const Eigen::Quaterniond &_q)\n{\n  Eigen::Quaterniond q(_q);\n  q.normalize();\n  const double r = getRollFromQuat(q.w(), q.x(), q.y(), q.z());\n  const double p = getPitchFromQuat(q.w(), q.x(), q.y(), q.z());\n  const double y = getYawFromQuat(q.w(), q.x(), q.y(), q.z());\n  return Eigen::Vector3d(r,p,y);\n}\n\nEigen::Quaterniond fromRPY(const Eigen::Vector3d &rpy){\n\treturn fromRPY(rpy.x(), rpy.y(), rpy.z());\n}\n\n}  // namespace icp_loco\n\n", "meta": {"hexsha": "c9258dd5d5680eb3633730c5cf764ad34a07a594", "size": 995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/math.cpp", "max_stars_repo_name": "ibrahimhroob/icp_localization", "max_stars_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 72.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T09:05:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T08:21:07.000Z", "max_issues_repo_path": "src/common/math.cpp", "max_issues_repo_name": "ibrahimhroob/icp_localization", "max_issues_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-09T20:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T09:54:42.000Z", "max_forks_repo_path": "src/common/math.cpp", "max_forks_repo_name": "ibrahimhroob/icp_localization", "max_forks_repo_head_hexsha": "271d99c59141fcd293190ec935020213783745e5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2021-06-23T09:18:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T03:14:10.000Z", "avg_line_length": 25.5128205128, "max_line_length": 83, "alphanum_fraction": 0.6743718593, "num_tokens": 301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6052075242594138}}
{"text": "#include <gtest/gtest.h>\n\n#include <Eigen/Eigen>\n#include <boost/filesystem.hpp>\n\n#include <CppADCodeGenEigenPy/ADModel.h>\n#include <CppADCodeGenEigenPy/CompiledModel.h>\n#include <CppADCodeGenEigenPy/Util.h>\n\n#include \"testing/models/MathFunctionsTestModel.h\"\n\nnamespace CppADCodeGenEigenPy {\nnamespace MathFunctionsModelTest {\n\nclass MathFunctionsTestModelFixture : public ::testing::Test {\n   protected:\n    using Vector = CompiledModel<Scalar>::Vector;\n    using Matrix = CompiledModel<Scalar>::Matrix;\n\n    static void SetUpTestSuite() {\n        // Compile and load our model\n        boost::filesystem::create_directories(DIRECTORY_PATH);\n        ad_model_ptr_.reset(new MathFunctionsTestModel<Scalar>());\n        ad_model_ptr_->compile(MODEL_NAME, DIRECTORY_PATH,\n                               DerivativeOrder::Second);\n        compiled_model_ptr_.reset(\n            new CompiledModel<Scalar>(MODEL_NAME, LIB_GENERIC_PATH));\n    }\n\n    static void TearDownTestSuite() {\n        // Delete the compiled shared object.\n        boost::filesystem::remove_all(DIRECTORY_PATH);\n    }\n\n    static std::unique_ptr<ADModel<Scalar>> ad_model_ptr_;\n    static std::unique_ptr<CompiledModel<Scalar>> compiled_model_ptr_;\n};\n\nstd::unique_ptr<ADModel<Scalar>> MathFunctionsTestModelFixture::ad_model_ptr_ =\n    nullptr;\nstd::unique_ptr<CompiledModel<Scalar>>\n    MathFunctionsTestModelFixture::compiled_model_ptr_ = nullptr;\n\nTEST_F(MathFunctionsTestModelFixture, Evaluation) {\n    Vector input = Vector::Ones(NUM_INPUT);\n\n    Vector output_expected = evaluate<Scalar>(input);\n    Vector output_actual = compiled_model_ptr_->evaluate(input);\n\n    EXPECT_TRUE(output_actual.isApprox(output_expected))\n        << \"Function evaluation is incorrect.\";\n}\n\nTEST_F(MathFunctionsTestModelFixture, Jacobian) {\n    Vector input = Vector::Ones(NUM_INPUT);\n\n    // clang-format off\n    Matrix J_expected(NUM_OUTPUT, NUM_INPUT);\n    J_expected << cos(input(0)) * cos(input(1)), -sin(input(0)) * sin(input(1)), 0,\n                  0, 0, 0.5 / sqrt(input(2)),\n                  2 * input.transpose();\n    // clang-format on\n    Matrix J_actual = compiled_model_ptr_->jacobian(input);\n\n    EXPECT_TRUE(J_actual.isApprox(J_expected)) << \"Jacobian is incorrect.\";\n}\n\nTEST_F(MathFunctionsTestModelFixture, Hessian) {\n    Vector input = Vector::Ones(NUM_INPUT);\n\n    // clang-format off\n    Matrix H0_expected(NUM_INPUT, NUM_INPUT);\n    H0_expected <<\n        -sin(input(0)) * cos(input(1)), -cos(input(0)) * sin(input(1)), 0,\n        -cos(input(0)) * sin(input(1)), -sin(input(0)) * cos(input(1)), 0,\n        0, 0, 0;\n    // clang-format on\n\n    Matrix H1_expected = Matrix::Zero(NUM_INPUT, NUM_INPUT);\n    H1_expected(2, 2) = -0.25 * pow(input(2), -1.5);\n\n    Matrix H2_expected = 2 * Matrix::Identity(NUM_INPUT, NUM_INPUT);\n\n    Matrix H0_actual = compiled_model_ptr_->hessian(input, 0);\n    Matrix H1_actual = compiled_model_ptr_->hessian(input, 1);\n    Matrix H2_actual = compiled_model_ptr_->hessian(input, 2);\n\n    EXPECT_TRUE(H0_actual.isApprox(H0_expected))\n        << \"Hessian for dim 0 is incorrect.\";\n    EXPECT_TRUE(H1_actual.isApprox(H1_expected))\n        << \"Hessian for dim 1 is incorrect.\";\n    EXPECT_TRUE(H2_actual.isApprox(H2_expected))\n        << \"Hessian for dim 2 is incorrect.\";\n}\n\n}  // namespace MathFunctionsModelTest\n}  // namespace CppADCodeGenEigenPy\n", "meta": {"hexsha": "6adbde61e6263d7951e03bfd5bfb1441cf7d9cdf", "size": 3353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/cpp_tests/MathFunctionsModelTest.cpp", "max_stars_repo_name": "adamheins/CppADCodeGenEigenPy", "max_stars_repo_head_hexsha": "4f85ca831cc554484bbff946e2ffdf2c3e90db81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-11-02T16:37:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:39:30.000Z", "max_issues_repo_path": "tests/cpp_tests/MathFunctionsModelTest.cpp", "max_issues_repo_name": "adamheins/CppADCodeGenEigenPy", "max_issues_repo_head_hexsha": "4f85ca831cc554484bbff946e2ffdf2c3e90db81", "max_issues_repo_licenses": ["MIT"], "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/cpp_tests/MathFunctionsModelTest.cpp", "max_forks_repo_name": "adamheins/CppADCodeGenEigenPy", "max_forks_repo_head_hexsha": "4f85ca831cc554484bbff946e2ffdf2c3e90db81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-17T23:52:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T23:52:00.000Z", "avg_line_length": 34.2142857143, "max_line_length": 83, "alphanum_fraction": 0.6943036087, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6052075242594138}}
{"text": "#include <boost/cstdint.hpp>\n#include <boost/simd/sdk/simd/native.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/simd/sdk/memory/is_power_of_2.hpp>\n\nusing boost::simd::meta::is_power_of_2_c;\n\nint main()\n{\n  BOOST_MPL_ASSERT(( is_power_of_2_c<2>::type ));\n  BOOST_MPL_ASSERT(( is_power_of_2_c<4>::type ));\n  BOOST_MPL_ASSERT(( is_power_of_2_c<8>::type ));\n  BOOST_MPL_ASSERT_NOT(( is_power_of_2_c<0>::type ));\n  BOOST_MPL_ASSERT_NOT(( is_power_of_2_c<10>::type ));\n}\n", "meta": {"hexsha": "b9e8cdd8b5bb2f1f198ca17818762d3bf39e57fd", "size": 501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/sdk/examples/memory/is_power_of_2_c.cpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/sdk/examples/memory/is_power_of_2_c.cpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/sdk/examples/memory/is_power_of_2_c.cpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4705882353, "max_line_length": 54, "alphanum_fraction": 0.7365269461, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6052075234102826}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/cycle_canceling.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\n// Graph Type with nested interior edge properties for Cost Flow Algorithms\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n                              boost::property<boost::edge_capacity_t, long,\n                                              boost::property<boost::edge_residual_capacity_t, long,\n                                                              boost::property<boost::edge_reverse_t, traits::edge_descriptor,\n                                                                              boost::property<boost::edge_weight_t, long>>>>>\n    graph; // new! weightmap corresponds to costs\ntypedef boost::graph_traits<graph>::edge_descriptor edge_desc;\ntypedef boost::graph_traits<graph>::out_edge_iterator out_edge_it; // Iterator\n\nusing namespace std;\n\n// Custom edge adder class\nclass edge_adder\n{\n    graph &G;\n\npublic:\n    explicit edge_adder(graph &G) : G(G) {}\n    void add_edge(int from, int to, long capacity, long cost)\n    {\n        auto c_map = boost::get(boost::edge_capacity, G);\n        auto r_map = boost::get(boost::edge_reverse, G);\n        auto w_map = boost::get(boost::edge_weight, G); // new!\n        const edge_desc e = boost::add_edge(from, to, G).first;\n        const edge_desc rev_e = boost::add_edge(to, from, G).first;\n        c_map[e] = capacity;\n        c_map[rev_e] = 0; // reverse edge has no capacity!\n        r_map[e] = rev_e;\n        r_map[rev_e] = e;\n        w_map[e] = cost;      // new assign cost\n        w_map[rev_e] = -cost; // new negative cost\n    }\n};\n\n\n\nvoid solve() {\n    int b, s, p;\n    cin >> b >> s >> p;\n    \n    graph G(b + s);\n    edge_adder adder(G);\n    \n    auto source = boost::add_vertex(G);\n    auto target = boost::add_vertex(G);\n\n    int maxValue = 50;\n    \n    for (int i = 0; i < b; ++i) {\n      adder.add_edge(source, i, 1, 0);\n      if (b <= s) {\n        adder.add_edge(i, target, 1, maxValue);\n      }\n    }\n    for (int j = 0; j < s; ++j) {\n      adder.add_edge(b + j, target, 1, 0);\n      if (b > s) {\n        adder.add_edge(source, b + j, 1, maxValue);\n      }\n    }\n    int bi, si, ci;\n    for (int i = 0; i < p; ++i) {\n      cin >> bi >> si >> ci; \n      adder.add_edge(bi, b + si, 1, maxValue - ci);\n    }\n    \n    boost::successive_shortest_path_nonnegative_weights(G, source, target);\n    auto cost = boost::find_flow_cost(G);\n    cost = min(b, s) * maxValue - cost;\n    cout << cost << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    int t; cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve();\n    }\n    return 0;\n}\n", "meta": {"hexsha": "ab7d92b704f23fea2af99cffee74105b4ecb35dd", "size": 2932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fleetrace.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/fleetrace.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fleetrace.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 32.5777777778, "max_line_length": 125, "alphanum_fraction": 0.5777626194, "num_tokens": 781, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424217727028, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6052075127201558}}
{"text": "#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <ctime>\n#include <vector>\n#include <string>\n\n#include <sys/resource.h> /* give extra space to stack `rlimit` */\n\n#include <Eigen/Eigen> /* Sparse Matrices */\n\n#include <omp.h> /* Parallel */\n\nusing namespace std;\n\nint get_grid_size(int b, int level, int c) {\n    return (c+1) * pow(b, level) + 1;\n}\n\nvoid get_grid_layout(int b, int l, int level, int c, long** grid_layout, int grid_size) {\n    // Checks if the parameters given are valid\n    if ((l!=0 && b%2 != l%2) || (b==l)) {\n        cout << \"Invalid Input!\" << endl;\n    } else {\n        // Fill Matrix Initially\n        for (int y = 0; y<grid_size; y++) {\n            for (int x = 0; x<grid_size; x++) {\n                if (x%(c+1) == 0 && y%(c+1) == 0) {\n                    grid_layout[y][x] = -1;\n                } else {\n                    grid_layout[y][x] = -2;\n                }\n            }\n        }\n\n        // Fills in the holes in the grid\n        for (int current_level = 1; current_level<=level; current_level++) {\n            int current_grid_size = get_grid_size(b, current_level, c);\n            int prev_grid_size = get_grid_size(b, current_level-1, c);\n            int hole_size = l*(prev_grid_size-1)-1;\n            //#pragma omp parallel collapse(4)\n            for (int j = (b-l)/2*(prev_grid_size-1)+1; j<grid_size; j+=(current_grid_size-1)) {\n                for (int i = (b-l)/2*(prev_grid_size-1)+1; i<grid_size; i+=(current_grid_size-1)) {\n                    for (int y = 0; y<hole_size; y++) {\n                        for (int x = 0; x<hole_size; x++) {\n                            grid_layout[j+y][i+x] = -1;\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\nvoid display_grid_layout(long** grid_layout, int grid_size) {\n    for (int y = 0; y<grid_size; y++) {\n        for (int x = 0; x<grid_size; x++) {\n            if (grid_layout[y][x] != -1) {\n                cout <<  \"\\u2588 \";\n            } else {\n                cout << \"  \";\n            }\n\n        }\n        cout << endl;\n    }\n}\n\nstruct point {\n    int y;\n    int x;\n};\n\nvoid print_point(point p) {\n    cout << \"{\" << p.y << \", \" << p.x << \"}\";\n}\n\n// -3 is the offset (starts -3, -4, -5 and converts to 0, 1, 2, ...)\n// Needs to be confirmed\nvoid get_adj_list(long** grid_layout, int grid_size, int crosswires, vector< vector<long>> & adjacency_list, vector<point> & coordinates) {\n    long next_available_index = -3;\n\n    // Left Boundary Assignment\n    for (int y = 0; y<grid_size; y++) {\n        if (grid_layout[y][0] == -2) {\n            grid_layout[y][0] = next_available_index;\n            coordinates.push_back({y, 0});\n            next_available_index--;\n        }\n    }\n\n    // Right Boundary Assignment\n    for (int y = 0; y<grid_size; y++) {\n        if (grid_layout[y][grid_size-1] == -2) {\n            grid_layout[y][grid_size-1] = next_available_index;\n            coordinates.push_back({y, grid_size-1});\n            next_available_index--;\n        }\n    }\n\n    // Beginning of Flood Fill Algorithm\n    vector<point> stack;\n    stack.push_back({1, 0});\n\n    while (stack.size() > 0) {\n\n        // Fetch Last element in stack\n        point p = stack[stack.size()-1];\n        stack.pop_back();\n        if (grid_layout[p.y][p.x] < 0) {\n            // Marks as visited\n            grid_layout[p.y][p.x] = -grid_layout[p.y][p.x]-3;\n            vector<long> adj_row;\n\n            // Checks Left\n            if (p.x > 0 && p.y % (crosswires+1) != 0 && grid_layout[p.y][p.x-1] != -1) {\n                if (grid_layout[p.y][p.x-1] >= 0) {\n                    adj_row.push_back(grid_layout[p.y][p.x-1]);\n                } else {\n                    if (grid_layout[p.y][p.x-1] == -2) {\n                        grid_layout[p.y][p.x-1] = next_available_index;\n                        coordinates.push_back({p.y, p.x-1});\n                        next_available_index--;\n                    }\n                    adj_row.push_back(-grid_layout[p.y][p.x-1]-3);\n                    stack.push_back({p.y, p.x-1});\n                }\n            }\n\n            // Checks Right\n            if (p.x < grid_size-1 && p.y % (crosswires+1) != 0 && grid_layout[p.y][p.x+1] != -1) {\n                if (grid_layout[p.y][p.x+1] >= 0) {\n                    adj_row.push_back(grid_layout[p.y][p.x+1]);\n                } else {\n                    if (grid_layout[p.y][p.x+1] == -2) {\n                        grid_layout[p.y][p.x+1] = next_available_index;\n                        coordinates.push_back({p.y, p.x+1});\n                        next_available_index--;\n                    }\n                    adj_row.push_back(-grid_layout[p.y][p.x+1]-3);\n                    stack.push_back({p.y, p.x+1});\n                }\n            }\n\n            // Checks Up\n            if (p.y > 0 && p.x % (crosswires+1) != 0 && grid_layout[p.y-1][p.x] != -1) {\n                if (grid_layout[p.y-1][p.x] >= 0) {\n                    adj_row.push_back(grid_layout[p.y-1][p.x]);\n                } else {\n                    if (grid_layout[p.y-1][p.x] == -2) {\n                        grid_layout[p.y-1][p.x] = next_available_index;\n                        coordinates.push_back({p.y-1, p.x});\n                        next_available_index--;\n                    }\n                    adj_row.push_back(-grid_layout[p.y-1][p.x]-3);\n                    stack.push_back({p.y-1, p.x});\n                }\n            }\n\n            // Checks Down\n            if (p.y < grid_size-1 && p.x % (crosswires+1) != 0 && grid_layout[p.y+1][p.x] != -1) {\n                if (grid_layout[p.y+1][p.x] >= 0) {\n                    adj_row.push_back(grid_layout[p.y+1][p.x]);\n                } else {\n                    if (grid_layout[p.y+1][p.x] == -2) {\n                        grid_layout[p.y+1][p.x] = next_available_index;\n                        coordinates.push_back({p.y+1, p.x});\n                        next_available_index--;\n                    }\n                    adj_row.push_back(-grid_layout[p.y+1][p.x]-3);\n                    stack.push_back({p.y+1, p.x});\n                }\n            }\n\n            while (adjacency_list.size() <= grid_layout[p.y][p.x]) {\n                vector<long> blank_row;\n                adjacency_list.push_back(blank_row);\n            }\n            adjacency_list[grid_layout[p.y][p.x]] = adj_row;\n        }\n    }\n}\n\nvoid get_laplacian(Eigen::SparseMatrix<short> & laplacian, vector< vector<long>> & adjacency_list) {\n    for (int i = 0; i<adjacency_list.size(); i++) {\n        vector<long> row = adjacency_list[i];\n        for (int j = 0; j<row.size(); j++) {\n            laplacian.coeffRef(i, row[j]) = 1;\n        }\n        laplacian.coeffRef(i, i) = -row.size();\n    }\n}\n\nvoid print_laplacian(Eigen::SparseMatrix<short> & laplacian) {\n    cout << \"Laplacian Matrix: \" << endl;\n    long num_coordinates = laplacian.cols();\n    for (int i = 0; i<num_coordinates; i++) {\n        for (int j = 0; j<num_coordinates; j++) {\n            cout << laplacian.coeff(i, j) << \" \";\n        }\n        cout << endl;\n    }\n}\n\nvoid print_mtrx(Eigen::SparseMatrix<double> & mtrx) {\n    cout << \"Matrix: \" << endl;\n    long num_coordinates = mtrx.cols();\n    for (int i = 0; i<mtrx.rows(); i++) {\n        for (int j = 0; j<mtrx.cols(); j++) {\n            cout << mtrx.coeff(i, j) << \" \";\n        }\n        cout << endl;\n    }\n}\n\ntemplate<typename Derived>\nvoid find_potentials(Eigen::MatrixBase<Derived>& potentials, vector< vector<long>> & adjacency_list) {\n    /*struct rlimit lim;\n    getrlimit(RLIMIT_STACK, &lim);\n    cout << lim.rlim_cur << endl;*/\n\n    long num_coordinates = adjacency_list.size();\n    int num_computed_points = potentials.rows();\n    int num_boundary_points = num_coordinates-num_computed_points;\n    cout << \"Total Boundary Points: \" << num_boundary_points << endl;\n    cout << \"Computed Points: \" << num_computed_points << endl;\n\n    cout << \"1) Initailizing Matrices ...\" << endl;\n    Eigen::SparseMatrix<double> r(num_computed_points, num_boundary_points);\n    Eigen::SparseMatrix<double> a(num_computed_points, num_computed_points);\n\n    cout << \"2) Reserving Space ...\" << endl;\n    r.reserve(Eigen::VectorXi::Constant(num_boundary_points, 5));\n    a.reserve(Eigen::VectorXi::Constant(num_computed_points, 5));\n\n    cout << \"3) Inserting Elements ...\" << endl;\n    for (int i = 0; i<adjacency_list.size(); i++) {\n        if (i >= num_boundary_points) {\n            vector<long> row = adjacency_list[i];\n\n            // Adds elements not on diagonal\n            for (int j = 0; j<row.size(); j++) {\n                if (row[j] < num_boundary_points) {\n                    r.insert(i-num_boundary_points, row[j]) = 1;\n                } else {\n                    a.insert(i-num_boundary_points, row[j]-num_boundary_points) = 1;\n                }\n            }\n\n            // Add elements on the diagonal\n            if (i < num_boundary_points) {\n                r.insert(i-num_boundary_points, i) = -(double)row.size();\n            } else {\n                a.insert(i-num_boundary_points, i-num_boundary_points) = -(double)row.size();\n            }\n        }\n    }\n    //print_mtrx(a);\n    //print_mtrx(r);\n\n    cout << \"4) Setting Boundary Conditions ...\" << endl;\n    Eigen::SparseMatrix<double> dirichlet(num_boundary_points, 1);\n    for (int i = 0; i<num_boundary_points; i++) {\n        if (i < num_boundary_points / 2) {\n            dirichlet.coeffRef(i, 0) = 0;\n        } else {\n            dirichlet.coeffRef(i, 0) = 1;\n        }\n    }\n\n    cout << \"5) Solving ...\" << endl;\n    Eigen::VectorXd b = -r*dirichlet;\n    //Eigen::SparseLU<Eigen::SparseMatrix<double> > solver;\n    //solver.analyzePattern(a);\n    //solver.factorize(a);\n    //potentials = solver.solve(b);\n\n\n    Eigen::ConjugateGradient<Eigen::SparseMatrix<double>, Eigen::Lower|Eigen::Upper> cg;\n\n    cg.compute(a);\n    cg.setMaxIterations(1);\n    potentials = cg.solve(b);\n\n    //Eigen::Matrix<double> potentials(2, 1);\n\n    for (int i = 0; i<500; i++) {\n        potentials = cg.solveWithGuess(b, potentials);\n        cout << 1*(i+1) << endl;\n        cout << cg.error() << endl;\n    }\n\n\n    //print_mtrx(potentials);\n}\n\n// TO BE CLEANED UP\ntemplate<typename Derived>\ndouble max_difference(vector< vector<long>> & adjacency_list, Eigen::MatrixBase<Derived>& potentials) {\n    long num_coordinates = adjacency_list.size();\n    int num_computed_points = potentials.rows();\n    int num_boundary_points = num_coordinates-num_computed_points;\n\n    double max_diff = 0;\n\n    for (int i = 0; i<adjacency_list.size(); i++) {\n        // figure out potential\n        double potential_a = 1;\n        if (i < num_boundary_points/2) {\n            potential_a = 0;\n        } else if (i >= num_boundary_points) {\n            potential_a = potentials.coeff(i-num_boundary_points, 0);\n        }\n\n        vector<long> row = adjacency_list[i];\n        for (int j = 0; j<row.size(); j++) {\n            long index = row[j];\n\n            // figure out potential\n            double potential_b = 1;\n            if (index < num_boundary_points/2) {\n                potential_b = 0;\n            } else if (index >= num_boundary_points) {\n                potential_b = potentials.coeff(index-num_boundary_points, 0);\n            }\n\n            double diff = abs(potential_a-potential_b);\n\n            if (diff-max_diff > 0.0000001) {\n                //cout << diff << endl;\n                max_diff = diff;\n            }\n        }\n    }\n\n    return max_diff;\n}\n// THIS SECTION ABOVE\n\nint harmonic_function(int b, int l, int level, int crosswires, string filename) {\n    struct rlimit lim;\n    getrlimit(RLIMIT_STACK, &lim);\n    cout << lim.rlim_cur << endl;\n\n    const rlimit stack_size = {10*1024*1024, 10*1024*1024};\n    if (setrlimit(RLIMIT_STACK, &stack_size) == -1) {\n        return 1;\n    }\n    // Parameters\n    /*const int b = 3;\n    const int l = 1;\n    const int level = 1;\n    const int crosswires = 1;*/\n\n    // Making Grid Layout\n    cout << \"Making Grid Layout ...\" << endl;\n    int grid_size = get_grid_size(b, level, crosswires);\n    cout << \"Grid Size: \" << grid_size << endl;\n    long ** grid_layout = new long*[grid_size];\n    for (int i = 0; i<grid_size; i++) {\n        grid_layout[i] = new long[grid_size];\n    }\n    get_grid_layout(b, l, level, crosswires, grid_layout, grid_size);\n\n    // View Grid Layout in Terminal\n    //display_grid_layout(grid_layout, grid_size);\n\n    // Adjacency List Calculation\n    cout << \"Making Adjacency List ...\" << endl;\n    vector< vector<long>> adjacency_list;\n    vector<point> coordinates;\n    get_adj_list(grid_layout, grid_size, crosswires, adjacency_list, coordinates);\n\n    // FREE GRID LAYOUT\n    for(int i =0 ; i<grid_size; i++) {\n        delete[] grid_layout[i];\n    }\n    delete[] grid_layout;\n\n    // Computes Laplacian\n    long num_coordinates = adjacency_list.size();\n    cout << \"num_coordinates: \" << num_coordinates << endl;\n    //Eigen::SparseMatrix<short> laplacian(num_coordinates, num_coordinates);\n    //get_laplacian(laplacian, adjacency_list);\n\n    // Computes Potentials\n    cout << \"Compute Potentials ...\" << endl;\n    int num_boundary_points = 2*crosswires*pow(b,level);\n    int num_computed_points = num_coordinates-num_boundary_points;\n    Eigen::VectorXd potentials(num_computed_points);\n    find_potentials(potentials, adjacency_list);\n\n    // To be fixed up\n    double max_diff = max_difference(adjacency_list, potentials);\n    cout << max_diff << endl;\n\n\n\n    // Below is the Printing code (needs to)\n    // Output to file\n    /*ofstream fout(filename);\n\n    time_t now = time(0);\n    string dt = ctime(&now);\n    fout << \"Produced by \\\"The Resistance\\\", \" << dt;\n    fout << \"---------------------------------------------------------\" << endl;\n    fout << \"Parameters: b = \" << b << \", l = \" << l << \", level = \" << level << \", crosswires = \" << crosswires << endl;\n    fout << \"---------------------------------------------------------\" << endl;\n    fout << \"y\\tx\\tpotential\" << endl;\n    for (int i = 0; i<num_coordinates; i++) {\n        if (i < num_boundary_points) {\n            if (i < num_boundary_points/2) {\n                fout << coordinates[i].y << \"\\t\" << coordinates[i].x << \"\\t\" << 0 << endl;\n            } else {\n                fout << coordinates[i].y << \"\\t\" << coordinates[i].x << \"\\t\" << 1 << endl;\n            }\n        } else {\n            fout << coordinates[i].y << \"\\t\" << coordinates[i].x << \"\\t\" << potentials.coeff(i-num_boundary_points, 0) << endl;\n        }\n    }\n    fout.close();*/\n    return 0;\n}\n\nint main() {\n    int b = 3;\n    int l = 1;\n    int level = 8;\n    int crosswires = 1;\n    omp_set_num_threads(4);\n    /*for (int level = 0; level<8; level++) {\n        cout << \"----------------------\\n\";\n        string filename = \"../data/plus/plusdata_\"+to_string(b)+\"_\"+to_string(l)+\"_\"+to_string(crosswires)+\"_level\"+to_string(level)+\".dat\";\n        //cout << filename;\n        harmonic_function(b, l, level, crosswires, filename);\n    }*/\n\n    harmonic_function(b, l, level, crosswires, \"asdf\");\n\n}\n", "meta": {"hexsha": "8f5885a5608b0465f66f0c41af76831690497406", "size": 15051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/grid2.cpp", "max_stars_repo_name": "orwinmc/Sierpinski-Carpet", "max_stars_repo_head_hexsha": "99e223cec052abb7fe4c07767a602c877c1d4bea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-21T16:03:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-21T16:03:12.000Z", "max_issues_repo_path": "cpp/grid2.cpp", "max_issues_repo_name": "orwinmc/Sierpinski-Carpet", "max_issues_repo_head_hexsha": "99e223cec052abb7fe4c07767a602c877c1d4bea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-21T05:18:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-21T05:18:41.000Z", "max_forks_repo_path": "cpp/grid2.cpp", "max_forks_repo_name": "orwinmc/Sierpinski-Carpet", "max_forks_repo_head_hexsha": "99e223cec052abb7fe4c07767a602c877c1d4bea", "max_forks_repo_licenses": ["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.1292517007, "max_line_length": 140, "alphanum_fraction": 0.5203640954, "num_tokens": 3939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.605207508011941}}
{"text": "#include \"catch.hpp\"\n\n#include \"libirc/linalg.h\"\n\n#ifdef HAVE_ARMA\n#include <armadillo>\nusing vec3 = arma::vec3;\nusing vec = arma::vec;\nusing mat = arma::mat;\n#elif HAVE_EIGEN3\n#include <Eigen/Dense>\nusing vec3 = Eigen::Vector3d;\nusing vec = Eigen::VectorXd;\nusing mat = Eigen::MatrixXd;\n#else\n#error\n#endif\n\nusing namespace irc;\n\nTEST_CASE(\"Size\", \"[size]\") {\n  SECTION(\"Vector\") {\n    vec v = {1, 2, 3, 4, 5};\n\n    CHECK(linalg::size(v) == 5);\n  }\n\n  SECTION(\"Matrix\") {\n    mat m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};\n\n    CHECK(linalg::size(m) == 9);\n  }\n}\n\nTEST_CASE(\"Number of rows\", \"[nrows]\") {\n  SECTION(\"Vector\") {\n    vec v = {1, 2, 3, 4, 5};\n\n    CHECK(linalg::n_rows(v) == 5);\n  }\n\n  SECTION(\"Matrix\") {\n    mat m = {{1, 2, 3}, {4, 5, 6}};\n\n    CHECK(linalg::n_rows(m) == 2);\n  }\n}\n\nTEST_CASE(\"Number of columns\", \"[ncols]\") {\n  SECTION(\"Vector\") {\n    vec v = {1, 2, 3, 4, 5};\n\n    CHECK(linalg::n_cols(v) == 1);\n  }\n\n  SECTION(\"Matrix\") {\n    mat m = {{1, 2, 3}, {4, 5, 6}};\n\n    CHECK(linalg::n_cols(m) == 3);\n  }\n}\n\nTEST_CASE(\"Norm and normalization\", \"[norm]\") {\n  SECTION(\"Vector\") {\n    vec v = {1, 2, 3, 4};\n\n    Approx t(std::sqrt(1 * 1 + 2 * 2 + 3 * 3 + 4 * 4));\n    CHECK(linalg::norm(v) == t);\n\n    v = linalg::normalize(v);\n\n    CHECK(linalg::norm(v) == Approx(1.0));\n  }\n\n  SECTION(\"Matrix\") {\n    mat m = {{1, 2, 3}, {4, 5, 6}};\n\n    Approx t(std::sqrt(91));\n    CHECK(linalg::norm(m) == t);\n  }\n}\n\nTEST_CASE(\"Dot product\", \"[dot]\") {\n  vec v1 = {1, 2, 3, 4};\n  vec v2 = {4, 3, 2, 1};\n\n  CHECK(linalg::dot(v1, v1) == Approx(std::pow(linalg::norm(v1), 2)));\n\n  CHECK(linalg::dot(v2, v2) == Approx(std::pow(linalg::norm(v2), 2)));\n\n  CHECK(linalg::dot(v1, v2) == Approx(1 * 4 + 2 * 3 + 3 * 2 + 4 * 1));\n\n  CHECK(linalg::dot(v1, v2) == Approx(linalg::dot(v2, v1)));\n}\n\nTEST_CASE(\"Cross product\", \"[cross]\") {\n  vec3 v1 = {1, 2, 3};\n  vec3 v2 = {3, 2, 1};\n\n  vec3 v = linalg::cross(v1, v2);\n\n  CHECK(v(0) == Approx(-4));\n  CHECK(v(1) == Approx(8));\n  CHECK(v(2) == Approx(-4));\n\n  v = linalg::cross(v1, v1);\n\n  CHECK(v(0) == Approx(0));\n  CHECK(v(1) == Approx(0));\n  CHECK(v(2) == Approx(0));\n\n  v = linalg::cross(v2, v2);\n\n  CHECK(v(0) == Approx(0));\n  CHECK(v(1) == Approx(0));\n  CHECK(v(2) == Approx(0));\n}\n\nTEST_CASE(\"Zeros\", \"[zeros]\") {\n  SECTION(\"Vector\") {\n    std::size_t n{100};\n\n    vec v = linalg::zeros<vec>(n);\n\n    REQUIRE(linalg::size(v) == n);\n    for (std::size_t i{0}; i < n; i++) {\n      CHECK(v(i) == Approx(0.));\n    }\n  }\n\n  SECTION(\"Matrix\") {\n    std::size_t n_r{10};\n    std::size_t n_c{20};\n\n    std::size_t n{n_r * n_c};\n\n    mat m = linalg::zeros<mat>(n_r, n_c);\n\n    REQUIRE(linalg::size(m) == n);\n    for (std::size_t i{0}; i < n; i++) {\n      CHECK(m(i) == Approx(0.));\n    }\n  }\n}\n\nTEST_CASE(\"Ones\", \"[ones]\") {\n  SECTION(\"Matrix\") {\n    std::size_t n_r{10};\n    std::size_t n_c{20};\n\n    std::size_t n{n_r * n_c};\n\n    mat m = linalg::ones<mat>(n_r, n_c);\n\n    REQUIRE(linalg::size(m) == n);\n    for (std::size_t i{0}; i < n; i++) {\n      CHECK(m(i) == Approx(1.));\n    }\n  }\n}\n\nTEST_CASE(\"Identity\", \"[identity]\") {\n  SECTION(\"Matrix\") {\n\n    std::size_t n{10};\n\n    mat m = linalg::identity<mat>(n);\n\n    REQUIRE(linalg::size(m) == n * n);\n    for (std::size_t i{0}; i < n; i++) {\n      for (std::size_t j{0}; j < n; j++) {\n\n        double m_ij = m(i, j);\n\n        if (i == j) {\n          CHECK(m_ij == Approx(1.));\n        } else {\n          CHECK(m_ij == Approx(0.));\n        }\n      }\n    }\n  }\n}\n\nTEST_CASE(\"Transpose\", \"[transpose]\") {\n  SECTION(\"Matrix\") {\n\n    mat m = {{1, 2, 3}, {4, 5, 6}};\n\n    mat mt = linalg::transpose(m);\n\n    std::size_t n_r{linalg::n_rows(m)};\n    std::size_t n_c{linalg::n_cols(m)};\n\n    REQUIRE(linalg::size(mt) == linalg::size(m));\n    REQUIRE(linalg::n_rows(mt) == n_c);\n    REQUIRE(linalg::n_cols(mt) == n_r);\n\n    for (std::size_t i{0}; i < n_r; i++) {\n      for (std::size_t j{0}; j < n_c; j++) {\n        CHECK(mt(j, i) == Approx(m(i, j)));\n      }\n    }\n  }\n}\n\nTEST_CASE(\"Inverse\", \"[inv]\") {\n  SECTION(\"diagonal\") {\n\n    std::size_t n{10};\n\n    mat m = linalg::zeros<mat>(n, n);\n\n    for (std::size_t i{0}; i < n; i++) {\n      m(i, i) = i + 1;\n    }\n\n    mat inv = linalg::inv(m);\n\n    for (std::size_t i{0}; i < n; i++) {\n      for (std::size_t j{0}; j < n; j++) {\n        if (i == j) {\n          CHECK(inv(i, j) == Approx(1. / m(i, j)));\n        } else {\n          CHECK(inv(i, j) == Approx(0.));\n        }\n      }\n    }\n  }\n\n  SECTION(\"2x2\") {\n\n    double a{1}, b{2}, c{3}, d{4};\n    double det{a * d - b * c};\n\n    mat m = {{1, 2}, {3, 4}};\n\n    mat mi = {{d, -b}, {-c, a}};\n    mi *= 1. / det;\n\n    mat inv = linalg::inv(m);\n\n    std::size_t n{linalg::size(m)};\n    REQUIRE(linalg::size(inv) == n);\n\n    for (std::size_t i{0}; i < n; i++) {\n      CHECK(inv(i) == Approx(mi(i)));\n    }\n  }\n}\n\nTEST_CASE(\"Pseudo Inverse\", \"[pinv]\") {\n  mat m = {{1, 2, 3}, {4, 5, 6}};\n\n  std::size_t n_r{linalg::n_rows(m)};\n  std::size_t n_c{linalg::n_cols(m)};\n\n  // WolframAlpha\n  mat p = {{-17, 8}, {-2, 2}, {13, -4}};\n  p /= 18.;\n\n  mat pinv = linalg::pseudo_inverse(m);\n\n  REQUIRE(linalg::n_rows(pinv) == n_c);\n  REQUIRE(linalg::n_cols(pinv) == n_r);\n\n  std::size_t n{n_r * n_c};\n\n  for (std::size_t i{0}; i < n; i++) {\n    CHECK(pinv(i) == Approx(p(i)));\n  }\n}\n", "meta": {"hexsha": "b5db07ec531804795068917cd243ab6e524a7d3a", "size": 5254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/linalg_test.cpp", "max_stars_repo_name": "francesco-bosia/irc", "max_stars_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T16:12:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T00:20:23.000Z", "max_issues_repo_path": "src/test/linalg_test.cpp", "max_issues_repo_name": "francesco-bosia/irc", "max_issues_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 45.0, "max_issues_repo_issues_event_min_datetime": "2018-01-11T13:21:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T19:59:39.000Z", "max_forks_repo_path": "src/test/linalg_test.cpp", "max_forks_repo_name": "francesco-bosia/irc", "max_forks_repo_head_hexsha": "6d5c7c372d02ecdbd50f8981669c46ddae0638ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-04-11T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T10:00:16.000Z", "avg_line_length": 19.2454212454, "max_line_length": 70, "alphanum_fraction": 0.4895317853, "num_tokens": 1988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6051476888678582}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2015 CompatibL\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include \"adjointvariategeneratorstest.hpp\"\n\n#include <boost/random.hpp>\n#include \"adjointtestutilities.hpp\"\n\nusing namespace boost::unit_test_framework;\nusing namespace QuantLib;\n\nnamespace\n{\n    // Function getProperties(Distribution distribution)\n    // Returns estimate of properties of variate generator with specefied Distribution.\n    // Parameter: specified distribution.\n    // Returns:\n    //  properties[0] - Estimate of mean.\n    //  properties[1] - Estimate of variance.\n    template<typename Distribution>\n    std::vector<Real> getProperties(Distribution distribution)\n    {\n        boost::mt19937 engine(42);\n        boost::variate_generator<boost::mt19937&, Distribution> variateGenerator(engine, distribution);\n\n        std::vector<Real> moments(2, 0.0);\n        Size sampleSize = 100000;\n        for (Size i = 0; i < sampleSize; i++)\n        {\n            // Variate.\n            Real X = variateGenerator();\n            // Estimate of first initial moment.\n            moments[0] += X;\n            // Estimate of second initial moment.\n            moments[1] += std::pow(X, 2.0);\n        }\n        std::vector<Real> properties(2, 0.0);\n        // Estimate of mean.\n        properties[0] = moments[0] / sampleSize;\n        // Estimate of variance.\n        properties[1] = (moments[1] - std::pow(moments[0], 2.0) / sampleSize) / (sampleSize - 1);\n\n        return properties;\n    }\n\n    // Checking consistency of vectors elements.\n    bool checkWithAnalyticalDeriv(\n        const std::vector<double>& adjointDeriv,\n        const std::vector<Real>& analyticalDeriv,\n        Real relativeTol,\n        Real absoluteTol)\n    {\n        bool result = true;\n        if (adjointDeriv.size() != analyticalDeriv.size())\n        {\n            result = false;\n            BOOST_ERROR(\"\\nAn adjoint derivatives vector and a analytical \"\n                        \"derivatives vector have different sizes.\");\n        }\n        for (size_t i = 0, n = adjointDeriv.size(); i < n; ++i)\n        {\n            Real err = std::abs(adjointDeriv[i] - analyticalDeriv[i]);\n            Real toler = std::max(absoluteTol,\n                                  relativeTol * std::max(std::abs(adjointDeriv[i]), std::abs(analyticalDeriv[i])));\n            if (err > toler)\n            {\n                result = false;\n                BOOST_ERROR(\"\\nAdjoint derivative and analytical derivative at position \" << i << \" mismatch.\"\n                            << \"\\n  adjoint: \" << adjointDeriv[i]\n                            << \"\\n  analytical: \" << analyticalDeriv[i]\n                            << \"\\n  tolerance: \" << toler);\n            }\n        }\n        return result;\n    }\n}\n\n// Testing boost variate generator with different distributions with RealType = QuantLib::Real\n// Properties of disributions (mean estimate and variance estimate) calculated by sample and then\n// differentiated with respect to input value(s).\n// Each test method returns true if adjoint derivatives are close enough to analytical derivatives,\n// calculated using finite differences method; otherwise, it returns false.\n\n// Method testExponentialVariate()\nbool AdjointVariateGeneratorsTest::testExponentialVariate()\n{\n    BOOST_MESSAGE(\"Testing boost exponential distribution with Real...\");\n\n    std::vector<Real> lambda = { 4.0 };\n\n    // Start of tape recording.\n    // Mark \\lambda as independent variable.\n    cl::Independent(lambda);\n\n    boost::random::exponential_distribution<Real> distribution(lambda[0]);\n\n    std::vector<Real> properties = getProperties(distribution);\n\n    // End of tape recording.\n    // Differentiaion will be held with respect to the independent variables vector.\n    cl::tape_function<double> f(lambda, properties);\n\n    int propertiesNumber = properties.size();\n\n    // Adjoint differentiation in Forward mode.\n    std::vector<double> adjoint_derivatives(propertiesNumber);\n    gradForward(f, adjoint_derivatives, false, false);\n\n    // Calculation of derivatives using finite differences method.\n    std::vector<Real> analytic_derivatives(properties.size());\n\n    double h = 1e-8;\n\n    lambda[0] += h;\n    boost::random::exponential_distribution<Real> distributionfd(lambda[0]);\n    std::vector<Real> propertiesfd = getProperties(distributionfd);\n    lambda[0] -= h;\n\n    for (int j = 0; j < properties.size(); j++)\n    {\n        analytic_derivatives[j] = (propertiesfd[j] - properties[j]) / h;\n    }\n\n    return checkWithAnalyticalDeriv(adjoint_derivatives, analytic_derivatives, 1e-4, 1e-10);\n}\n\n// Method testGammaVariate()\nbool AdjointVariateGeneratorsTest::testGammaVariate()\n{\n    BOOST_MESSAGE(\"Testing boost gamma distribution with Real...\");\n\n    Real k = 10.0;\n    Real theta = 3.0;\n    std::vector<Real> parameters = { k, theta };\n\n    // Start of tape recording.\n    // Mark parameters as independent variables.\n    cl::Independent(parameters);\n\n    boost::random::gamma_distribution<Real> distribution(parameters[0], parameters[1]);\n\n    std::vector<Real> properties = getProperties(distribution);\n\n    // End of tape recording.\n    // Differentiaion will be held with respect to the independent variables vector.\n    cl::tape_function<double> f(parameters, properties);\n\n    // Adjoint differentiation in Reverse mode.\n    std::vector<double> adjoint_derivatives(properties.size() * parameters.size());\n    gradReverse(f, adjoint_derivatives, false, false);\n\n    // Calculation of derivatives using finite differences method.\n    std::vector<Real> analytic_derivatives(properties.size() * parameters.size());\n\n    double h = 1e-8;\n\n    for (int i = 0; i < parameters.size(); i++)\n    {\n        parameters[i] += h;\n        boost::random::gamma_distribution<Real> distributionfd(parameters[0], parameters[1]);\n        std::vector<Real> propertiesfd = getProperties(distributionfd);\n        parameters[i] -= h;\n\n        for (int j = 0; j < properties.size(); j++)\n        {\n            analytic_derivatives[2 * j + i] = (propertiesfd[j] - properties[j]) / h;\n        }\n    }\n\n    return checkWithAnalyticalDeriv(adjoint_derivatives, analytic_derivatives, 1e-3, 1e-10);\n}\n\n// Method testNormalVariate()\nbool AdjointVariateGeneratorsTest::testNormalVariate()\n{\n    BOOST_MESSAGE(\"Testing boost normal distribution with Real...\");\n\n    Real mu = 5.0;\n    Real sigma = 3.0;\n    std::vector<Real> parameters = { mu, sigma };\n\n    // Start of tape recording.\n    // Mark parameters as independent variables.\n    cl::Independent(parameters);\n\n    boost::random::normal_distribution<Real> distribution(parameters[0], parameters[1]);\n\n    std::vector<Real> properties = getProperties(distribution);\n\n    // End of tape recording.\n    // Differentiaion will be held with respect to the independent variables vector.\n    cl::tape_function<double> f(parameters, properties);\n\n    // Adjoint differentiation in Reverse mode.\n    std::vector<double> adjoint_derivatives(properties.size() * parameters.size());\n    gradReverse(f, adjoint_derivatives, false, false);\n\n    // Calculation of derivatives using finite differences method.\n    std::vector<Real> analytic_derivatives(properties.size() * parameters.size());\n\n    double h = 1e-8;\n\n    for (int i = 0; i < parameters.size(); i++)\n    {\n        parameters[i] += h;\n        boost::random::normal_distribution<Real> distributionfd(parameters[0], parameters[1]);\n        std::vector<Real> propertiesfd = getProperties(distributionfd);\n        parameters[i] -= h;\n\n        for (int j = 0; j < properties.size(); j++)\n        {\n            analytic_derivatives[2 * j + i] = (propertiesfd[j] - properties[j]) / h;\n        }\n    }\n\n    return checkWithAnalyticalDeriv(adjoint_derivatives, analytic_derivatives, 1e-2, 1e-2);\n}\n\n// Method testLogNormalVariate()\nbool AdjointVariateGeneratorsTest::testLogNormalVariate()\n{\n    BOOST_MESSAGE(\"Testing boost log-normal distribution with Real...\");\n\n    Real mu = 5.0;\n    Real sigma = 3.0;\n    std::vector<Real> parameters = { mu, sigma };\n\n    // Start of tape recording.\n    // Mark parameters as independent variables.\n    cl::Independent(parameters);\n\n    boost::random::lognormal_distribution<Real> distribution(parameters[0], parameters[1]);\n\n    std::vector<Real> properties = getProperties(distribution);\n\n    // End of tape recording.\n    // Differentiaion will be held with respect to the independent variables vector.\n    cl::tape_function<double> f(parameters, properties);\n\n    // Adjoint differentiation in Reverse mode.\n    std::vector<double> adjoint_derivatives(properties.size() * parameters.size());\n    gradReverse(f, adjoint_derivatives, false, false);\n\n    // Calculation of derivatives using finite differences method.\n    std::vector<Real> analytic_derivatives(properties.size() * parameters.size());\n\n    double h = 1e-8;\n\n    for (int i = 0; i < parameters.size(); i++)\n    {\n        parameters[i] += h;\n        boost::random::lognormal_distribution<Real> distributionfd(parameters[0], parameters[1]);\n        std::vector<Real> propertiesfd = getProperties(distributionfd);\n        parameters[i] -= h;\n\n        for (int j = 0; j < properties.size(); j++)\n        {\n            analytic_derivatives[2 * j + i] = (propertiesfd[j] - properties[j]) / h;\n        }\n    }\n\n    return checkWithAnalyticalDeriv(adjoint_derivatives, analytic_derivatives, 1e-4, 1e-10);\n}\n\ntest_suite* AdjointVariateGeneratorsTest::suite()\n{\n    test_suite* suite = BOOST_TEST_SUITE(\"AdjointVariateGenerators test\");\n    suite->add(QUANTLIB_TEST_CASE(&AdjointVariateGeneratorsTest::testExponentialVariate));\n    suite->add(QUANTLIB_TEST_CASE(&AdjointVariateGeneratorsTest::testGammaVariate));\n    suite->add(QUANTLIB_TEST_CASE(&AdjointVariateGeneratorsTest::testNormalVariate));\n    suite->add(QUANTLIB_TEST_CASE(&AdjointVariateGeneratorsTest::testLogNormalVariate));\n    return suite;\n}\n\n#ifdef CL_ENABLE_BOOST_TEST_ADAPTER\n\nBOOST_AUTO_TEST_SUITE(ad_variate_generator)\n\nBOOST_AUTO_TEST_CASE(testExponentialVariate)\n{\n    BOOST_CHECK(AdjointVariateGeneratorsTest::testExponentialVariate());\n}\n\nBOOST_AUTO_TEST_CASE(testNormalVariate)\n{\n    BOOST_CHECK(AdjointVariateGeneratorsTest::testNormalVariate());\n}\n\nBOOST_AUTO_TEST_CASE(testGammaVariate)\n{\n    BOOST_CHECK(AdjointVariateGeneratorsTest::testGammaVariate());\n}\n\nBOOST_AUTO_TEST_CASE(testLogNormalVariate)\n{\n    BOOST_CHECK(AdjointVariateGeneratorsTest::testLogNormalVariate());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n#endif\n", "meta": {"hexsha": "f263b6b6de134f115a070b820351d446e25b314d", "size": 11151, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite-adjoint/adjointvariategeneratorstest.cpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "test-suite-adjoint/adjointvariategeneratorstest.cpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test-suite-adjoint/adjointvariategeneratorstest.cpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 35.0660377358, "max_line_length": 115, "alphanum_fraction": 0.6782351359, "num_tokens": 2585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.6051476724178139}}
{"text": "// Copyright Paul A. Bristow 2006, 2017.\r\n// Copyright John Maddock 2006.\r\n\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// test_students_t.cpp\r\n\r\n// http://en.wikipedia.org/wiki/Student%27s_t_distribution\r\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3664.htm\r\n\r\n// Basic sanity test for Student's t probability (quantile) (0. < p < 1).\r\n// and Student's t probability Quantile (0. < p < 1).\r\n\r\n#ifdef _MSC_VER\r\n#  pragma warning (disable :4127) // conditional expression is constant.\r\n#endif\r\n\r\n#define BOOST_TEST_MAIN\r\n#include <boost/test/unit_test.hpp> // Boost.Test\r\n#include <boost/test/floating_point_comparison.hpp>\r\n\r\n#include <boost/math/concepts/real_concept.hpp> // for real_concept\r\n#include <boost/math/tools/test.hpp> // for real_concept\r\n#include \"test_out_of_range.hpp\"\r\n#include <boost/math/distributions/students_t.hpp>\r\n    using boost::math::students_t_distribution;\r\n\r\n#include <iostream>\r\n   using std::cout;\r\n   using std::endl;\r\n   using std::setprecision;\r\n#include <limits>\r\n  using std::numeric_limits;\r\n\r\ntemplate <class RealType>\r\nRealType naive_pdf(RealType v, RealType t)\r\n{\r\n   // Calculate the pdf of the students t in a deliberately\r\n   // naive way, using equation (5) from\r\n   // http://mathworld.wolfram.com/Studentst-Distribution.html\r\n   // This is equivalent to, but a different method\r\n   // to the one in the actual implementation, so can be used as\r\n   // a very basic sanity check.  However some published values\r\n   // would be nice....\r\n\r\n   using namespace std;  // for ADL\r\n   using boost::math::beta;\r\n\r\n   //return pow(v / (v + t*t), (1+v) / 2) / (sqrt(v) * beta(v/2, RealType(0.5f)));\r\n   RealType result = boost::math::tgamma_ratio((v+1)/2, v/2);\r\n   result /= sqrt(v * boost::math::constants::pi<RealType>());\r\n   result /= pow(1 + t*t/v, (v+1)/2);\r\n   return result;\r\n}\r\n\r\ntemplate <class RealType>\r\nvoid test_spots(RealType)\r\n{\r\n  // Basic sanity checks\r\n\r\n   RealType tolerance = static_cast<RealType>(1e-4); // 1e-6 (as %)\r\n   // Some tests only pass at 1e-5 because probability value is less accurate,\r\n   // a digit in 6th decimal place, although calculated using\r\n   // a t-distribution generator (claimed 6 decimal digits) at\r\n  // http://faculty.vassar.edu/lowry/VassarStats.html\r\n   // http://faculty.vassar.edu/lowry/tsamp.html\r\n   // df = 5, +/-t = 2.0, 1-tailed = 0.050970, 2-tailed = 0.101939\r\n\r\n   cout << \"Tolerance for type \" << typeid(RealType).name()  << \" is \" << tolerance << \" %\" << endl;\r\n\r\n   // http://en.wikipedia.org/wiki/Student%27s_t_distribution#Table_of_selected_values\r\n  // Using tabulated value of t = 3.182 for 0.975, 3 df, one-sided.\r\n\r\n   // http://www.mth.kcl.ac.uk/~shaww/web_page/papers/Tdistribution06.pdf refers to:\r\n\r\n   // A lookup table of quantiles of the RealType distribution\r\n  // for 1 to 25 in steps of 0.1 is provided in CSV form at:\r\n  // www.mth.kcl.ac.uk/~shaww/web_page/papers/Tsupp/tquantiles.csv\r\n   // gives accurate t of -3.1824463052837 and 3 degrees of freedom.\r\n   // Values below are from this source, saved as tquantiles.xls.\r\n   // DF are across the columns, probabilities down the rows\r\n   // and the t- values (quantiles) are shown.\r\n   // These values are probably accurate to nearly 64-bit double\r\n  // (perhaps 14 decimal digits).\r\n\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(2),       // degrees_of_freedom\r\n         static_cast<RealType>(-6.96455673428326)),  // t\r\n         static_cast<RealType>(0.01),                // probability.\r\n         tolerance); // %\r\n\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(5),       // degrees_of_freedom\r\n         static_cast<RealType>(-3.36492999890721)),  // t\r\n         static_cast<RealType>(0.01),                // probability.\r\n         tolerance);\r\n\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(1),      // degrees_of_freedom\r\n         static_cast<RealType>(-31830.988607907)),  // t\r\n         static_cast<RealType>(0.00001),            // probability.\r\n         tolerance);\r\n\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(25.),    // degrees_of_freedom\r\n         static_cast<RealType>(-5.2410429995425)),  // t\r\n         static_cast<RealType>(0.00001),            // probability.\r\n         tolerance);\r\n\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(1),   // degrees_of_freedom\r\n         static_cast<RealType>(-63661.97723)),   // t\r\n         static_cast<RealType>(0.000005),        // probability.\r\n         tolerance);\r\n\r\n    BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(5.),  // degrees_of_freedom\r\n         static_cast<RealType>(-17.89686614)),   // t\r\n         static_cast<RealType>(0.000005),        // probability.\r\n         tolerance);\r\n\r\n    BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(25.),  // degrees_of_freedom\r\n         static_cast<RealType>(-5.510848412)),    // t\r\n         static_cast<RealType>(0.000005),         // probability.\r\n         tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(10.),  // degrees_of_freedom\r\n         static_cast<RealType>(-1.812461123)),    // t\r\n         static_cast<RealType>(0.05),             // probability.\r\n         tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(10),  // degrees_of_freedom\r\n         static_cast<RealType>(1.812461123)),    // t\r\n         static_cast<RealType>(0.95),            // probability.\r\n         tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         complement(\r\n            students_t_distribution<RealType>(10),  // degrees_of_freedom\r\n            static_cast<RealType>(1.812461123))),    // t\r\n         static_cast<RealType>(0.05),            // probability.\r\n         tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(10),  // degrees_of_freedom\r\n         static_cast<RealType>(9.751995491)),    // t\r\n         static_cast<RealType>(0.999999),        // probability.\r\n         tolerance);\r\n\r\n  BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(10.),  // degrees_of_freedom - for ALL degrees_of_freedom!\r\n         static_cast<RealType>(0.)),              // t\r\n         static_cast<RealType>(0.5),              // probability.\r\n         tolerance);\r\n\r\n\r\n   // Student's t Inverse function tests.\r\n  // Special cases\r\n\r\n  BOOST_MATH_CHECK_THROW(boost::math::quantile(\r\n         students_t_distribution<RealType>(1.),  // degrees_of_freedom (ignored).\r\n         static_cast<RealType>(0)), std::overflow_error); // t == -infinity.\r\n\r\n  BOOST_MATH_CHECK_THROW(boost::math::quantile(\r\n         students_t_distribution<RealType>(1.),  // degrees_of_freedom (ignored).\r\n         static_cast<RealType>(1)), std::overflow_error); // t == +infinity.\r\n\r\n  BOOST_CHECK_EQUAL(boost::math::quantile(\r\n         students_t_distribution<RealType>(1.),  // degrees_of_freedom (ignored).\r\n         static_cast<RealType>(0.5)),  //  probability == half - special case.\r\n         static_cast<RealType>(0)); // t == zero.\r\n\r\n  BOOST_CHECK_EQUAL(boost::math::quantile(\r\n         complement(\r\n            students_t_distribution<RealType>(1.),  // degrees_of_freedom (ignored).\r\n            static_cast<RealType>(0.5))),  //  probability == half - special case.\r\n         static_cast<RealType>(0)); // t == zero.\r\n\r\n  BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(1.),  // degrees_of_freedom (ignored).\r\n         static_cast<RealType>(0.5)),  //  probability == half - special case.\r\n         static_cast<RealType>(0), // t == zero.\r\n         tolerance);\r\n\r\n   BOOST_CHECK_CLOSE( // Tests of p middling.\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(5.),  // degrees_of_freedom\r\n         static_cast<RealType>(-0.559429644)),  // t\r\n         static_cast<RealType>(0.3), // probability.\r\n         tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::quantile(\r\n         students_t_distribution<RealType>(5.),  // degrees_of_freedom\r\n         static_cast<RealType>(0.3)),  // probability.\r\n         static_cast<RealType>(-0.559429644), // t\r\n         tolerance);\r\n\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::quantile(\r\n         complement(\r\n            students_t_distribution<RealType>(5.),  // degrees_of_freedom\r\n            static_cast<RealType>(0.7))),  // probability.\r\n         static_cast<RealType>(-0.559429644), // t\r\n         tolerance);\r\n\r\n   BOOST_CHECK_CLOSE( // Tests of p high.\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(5.),  // degrees_of_freedom\r\n         static_cast<RealType>(1.475884049)),  // t\r\n         static_cast<RealType>(0.9), // probability.\r\n         tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::quantile(\r\n         students_t_distribution<RealType>(5.),  // degrees_of_freedom\r\n         static_cast<RealType>(0.9)),  // probability.\r\n         static_cast<RealType>(1.475884049), // t\r\n         tolerance);\r\n\r\n   BOOST_CHECK_CLOSE( // Tests of p low.\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(5.),  // degrees_of_freedom\r\n         static_cast<RealType>(-1.475884049)),  // t\r\n         static_cast<RealType>(0.1), // probability.\r\n         tolerance);\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::quantile(\r\n         students_t_distribution<RealType>(5.),  // degrees_of_freedom\r\n         static_cast<RealType>(0.1)),  // probability.\r\n         static_cast<RealType>(-1.475884049), // t\r\n         tolerance);\r\n\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::cdf(\r\n         students_t_distribution<RealType>(2.),  // degrees_of_freedom\r\n         static_cast<RealType>(-6.96455673428326)),  // t\r\n         static_cast<RealType>(0.01), // probability.\r\n         tolerance);\r\n\r\n   BOOST_CHECK_CLOSE(\r\n      ::boost::math::quantile(\r\n         students_t_distribution<RealType>(2.),  // degrees_of_freedom\r\n         static_cast<RealType>(0.01)),  // probability.\r\n         static_cast<RealType>(-6.96455673428326), // t\r\n         tolerance);\r\n\r\n      //\r\n      // Some special tests to exercise the double-precision approximations\r\n      // to the quantile:\r\n      //\r\n      // tolerance is 50 eps expressed as a persent:\r\n      //\r\n      tolerance = boost::math::tools::epsilon<RealType>() * 5000;\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(2.00390625L),                     // degrees_of_freedom.\r\n         static_cast<RealType>(0.5625L)),                                    //  probability.\r\n         static_cast<RealType>(0.178133131573788108465134803511798566L),     // t.\r\n         tolerance);      \r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(1L),                              // degrees_of_freedom.\r\n         static_cast<RealType>(0.03125L)),                                   //  probability.\r\n         static_cast<RealType>(-10.1531703876088604621071476634194722L),     // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(1L),                            // degrees_of_freedom.\r\n         static_cast<RealType>(0.875L)),                                   //  probability.\r\n         static_cast<RealType>(2.41421356237309504880168872421390942L),    // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(2L),                              // degrees_of_freedom.\r\n         static_cast<RealType>(0.03125L)),                                   //  probability.\r\n         static_cast<RealType>(-3.81000381000571500952501666878143315L),     // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(2L),                            // degrees_of_freedom.\r\n         static_cast<RealType>(0.875L)),                                   //  probability.\r\n         static_cast<RealType>(1.60356745147454630810732088527854144L),    // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(4L),                              // degrees_of_freedom.\r\n         static_cast<RealType>(0.03125L)),                                   //  probability.\r\n         static_cast<RealType>(-2.56208431914409044861223047927635034L),     // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(4L),                            // degrees_of_freedom.\r\n         static_cast<RealType>(0.875L)),                                   //  probability.\r\n         static_cast<RealType>(1.34439755550909142430681981315923574L),    // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(6L),                              // degrees_of_freedom.\r\n         static_cast<RealType>(0.03125L)),                                   //  probability.\r\n         static_cast<RealType>(-2.28348667906973065861212495010082952L),     // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(6L),                            // degrees_of_freedom.\r\n         static_cast<RealType>(0.875L)),                                   //  probability.\r\n         static_cast<RealType>(1.27334930914664286821103236660071906L),    // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(8L),                              // degrees_of_freedom.\r\n         static_cast<RealType>(0.03125L)),                                   //  probability.\r\n         static_cast<RealType>(-2.16296475406014719458642055768894376L),     // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(8L),                            // degrees_of_freedom.\r\n         static_cast<RealType>(0.875L)),                                   //  probability.\r\n         static_cast<RealType>(1.24031826078267310637634677726479038L),    // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(10L),                             // degrees_of_freedom.\r\n         static_cast<RealType>(0.03125L)),                                   //  probability.\r\n         static_cast<RealType>(-2.09596136475109350926340169211429572L),     // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(10L),                         // degrees_of_freedom.\r\n         static_cast<RealType>(0.875L)),                                 //  probability.\r\n         static_cast<RealType>(1.2212553950039221407185188573696834L),   // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(2.125L),                          // degrees_of_freedom.\r\n         static_cast<RealType>(0.03125L)),                                   //  probability.\r\n         static_cast<RealType>(-3.62246031671091980110493455859296532L),     // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(2.125L),                        // degrees_of_freedom.\r\n         static_cast<RealType>(0.875L)),                                   //  probability.\r\n         static_cast<RealType>(1.56905270993307293450392958697861969L),    // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(3L),                              // degrees_of_freedom.\r\n         static_cast<RealType>(0.03125L)),                                   //  probability.\r\n         static_cast<RealType>(-2.90004411882995814036141778367917946L),     // t.\r\n         tolerance);\r\n      BOOST_CHECK_CLOSE(boost::math::quantile(\r\n         students_t_distribution<RealType>(3L),                            // degrees_of_freedom.\r\n         static_cast<RealType>(0.875L)),                                   //  probability.\r\n         static_cast<RealType>(1.42262528146180931868169289781115099L),    // t.\r\n         tolerance);\r\n\r\n      if(boost::is_floating_point<RealType>::value)\r\n      {\r\n         BOOST_CHECK_CLOSE(boost::math::cdf(\r\n            students_t_distribution<RealType>(1e30f), \r\n               boost::math::quantile(\r\n                  students_t_distribution<RealType>(1e30f), static_cast<RealType>(0.25f))), \r\n            static_cast<RealType>(0.25f), tolerance);\r\n         BOOST_CHECK_CLOSE(boost::math::cdf(\r\n            students_t_distribution<RealType>(1e20f), \r\n               boost::math::quantile(\r\n                  students_t_distribution<RealType>(1e20f), static_cast<RealType>(0.25f))), \r\n            static_cast<RealType>(0.25f), tolerance);\r\n         BOOST_CHECK_CLOSE(boost::math::cdf(\r\n            students_t_distribution<RealType>(static_cast<RealType>(0x7FFFFFFF)), \r\n               boost::math::quantile(\r\n                  students_t_distribution<RealType>(static_cast<RealType>(0x7FFFFFFF)), static_cast<RealType>(0.25f))), \r\n            static_cast<RealType>(0.25f), tolerance);\r\n         BOOST_CHECK_CLOSE(boost::math::cdf(\r\n            students_t_distribution<RealType>(static_cast<RealType>(0x10000000)), \r\n               boost::math::quantile(\r\n                  students_t_distribution<RealType>(static_cast<RealType>(0x10000000)), static_cast<RealType>(0.25f))), \r\n            static_cast<RealType>(0.25f), tolerance);\r\n         BOOST_CHECK_CLOSE(boost::math::cdf(\r\n            students_t_distribution<RealType>(static_cast<RealType>(0x0fffffff)), \r\n               boost::math::quantile(\r\n                  students_t_distribution<RealType>(static_cast<RealType>(0x0fffffff)), static_cast<RealType>(0.25f))), \r\n            static_cast<RealType>(0.25f), tolerance);\r\n      }\r\n\r\n  // Student's t pdf tests.\r\n  // for PDF checks, use 100 eps tolerance expressed as a percent:\r\n   tolerance = boost::math::tools::epsilon<RealType>() * 10000;\r\n\r\n   for(unsigned i = 1; i < 20; i += 3)\r\n   {\r\n      for(RealType r = -10; r < 10; r += 0.125)\r\n      {\r\n         //std::cout << \"df=\" << i << \" t=\" << r << std::endl;\r\n         BOOST_CHECK_CLOSE(\r\n            boost::math::pdf(\r\n               students_t_distribution<RealType>(static_cast<RealType>(i)),\r\n               r),\r\n            naive_pdf<RealType>(static_cast<RealType>(i), r),\r\n            tolerance);\r\n      }\r\n   }\r\n\r\n    RealType tol2 = boost::math::tools::epsilon<RealType>() * 5;\r\n    students_t_distribution<RealType> dist(8);\r\n    RealType x = static_cast<RealType>(0.125);\r\n    using namespace std; // ADL of std names.\r\n    // mean:\r\n    BOOST_CHECK_CLOSE(\r\n       mean(dist)\r\n       , static_cast<RealType>(0), tol2);\r\n    // variance:\r\n //   BOOST_CHECK_CLOSE(\r\n //      variance(dist)\r\n //      , static_cast<RealType>(13.0L / 6.0L), tol2);\r\n //// was     , static_cast<RealType>(8.0L / 6.0L), tol2);\r\n    // std deviation:\r\n    BOOST_CHECK_CLOSE(\r\n       standard_deviation(dist)\r\n       , static_cast<RealType>(sqrt(8.0L / 6.0L)), tol2);\r\n    // hazard:\r\n    BOOST_CHECK_CLOSE(\r\n       hazard(dist, x)\r\n       , pdf(dist, x) / cdf(complement(dist, x)), tol2);\r\n    // cumulative hazard:\r\n    BOOST_CHECK_CLOSE(\r\n       chf(dist, x)\r\n       , -log(cdf(complement(dist, x))), tol2);\r\n    // coefficient_of_variation:\r\n    BOOST_MATH_CHECK_THROW(\r\n       coefficient_of_variation(dist),\r\n       std::overflow_error);\r\n    // mode:\r\n    BOOST_CHECK_CLOSE(\r\n       mean(dist)\r\n       , static_cast<RealType>(0), tol2);\r\n    // median:\r\n    BOOST_CHECK_CLOSE(\r\n       median(dist)\r\n       , static_cast<RealType>(0), tol2);\r\n    // skewness:\r\n    BOOST_CHECK_CLOSE(\r\n       skewness(dist)\r\n       , static_cast<RealType>(0), tol2);\r\n    // kurtosis:\r\n    BOOST_CHECK_CLOSE(\r\n       kurtosis(dist)\r\n       , static_cast<RealType>(4.5), tol2);\r\n    // kurtosis excess:\r\n    BOOST_CHECK_CLOSE(\r\n       kurtosis_excess(dist)\r\n       , static_cast<RealType>(1.5), tol2);\r\n\r\n    // Parameter estimation. These results are close to but\r\n    // not identical to those reported on the NIST website at\r\n    // http://www.itl.nist.gov/div898/handbook/prc/section2/prc222.htm\r\n    // the NIST results appear to be calculated using a normal\r\n    // approximation, which slightly under-estimates the degrees of\r\n    // freedom required, particularly when the result is small.\r\n    //\r\n    BOOST_CHECK_EQUAL(\r\n       ceil(students_t_distribution<RealType>::find_degrees_of_freedom(\r\n         static_cast<RealType>(0.5),\r\n         static_cast<RealType>(0.005),\r\n         static_cast<RealType>(0.01),\r\n         static_cast<RealType>(1.0))),\r\n         99);\r\n    BOOST_CHECK_EQUAL(\r\n       ceil(students_t_distribution<RealType>::find_degrees_of_freedom(\r\n         static_cast<RealType>(1.5),\r\n         static_cast<RealType>(0.005),\r\n         static_cast<RealType>(0.01),\r\n         static_cast<RealType>(1.0))),\r\n         14);\r\n    BOOST_CHECK_EQUAL(\r\n       ceil(students_t_distribution<RealType>::find_degrees_of_freedom(\r\n         static_cast<RealType>(0.5),\r\n         static_cast<RealType>(0.025),\r\n         static_cast<RealType>(0.01),\r\n         static_cast<RealType>(1.0))),\r\n         76);\r\n    BOOST_CHECK_EQUAL(\r\n       ceil(students_t_distribution<RealType>::find_degrees_of_freedom(\r\n         static_cast<RealType>(1.5),\r\n         static_cast<RealType>(0.025),\r\n         static_cast<RealType>(0.01),\r\n         static_cast<RealType>(1.0))),\r\n         11);\r\n    BOOST_CHECK_EQUAL(\r\n       ceil(students_t_distribution<RealType>::find_degrees_of_freedom(\r\n         static_cast<RealType>(0.5),\r\n         static_cast<RealType>(0.05),\r\n         static_cast<RealType>(0.01),\r\n         static_cast<RealType>(1.0))),\r\n         65);\r\n    BOOST_CHECK_EQUAL(\r\n       ceil(students_t_distribution<RealType>::find_degrees_of_freedom(\r\n         static_cast<RealType>(1.5),\r\n         static_cast<RealType>(0.05),\r\n         static_cast<RealType>(0.01),\r\n         static_cast<RealType>(1.0))),\r\n         9);\r\n\r\n    // Test for large degrees of freedom when should be same as normal.\r\n    RealType inf = std::numeric_limits<RealType>::infinity();\r\n    RealType nan = std::numeric_limits<RealType>::quiet_NaN();\r\n\r\n    std::string type = typeid(RealType).name();\r\n//    if (type != \"class boost::math::concepts::real_concept\") fails for gcc\r\n    if (typeid(RealType) != typeid(boost::math::concepts::real_concept))\r\n    { // Ordinary floats only.\r\n      RealType limit = 1/ boost::math::tools::epsilon<RealType>();\r\n      // Default policy to get full accuracy.\r\n      // std::cout << \"Switch over to normal if df > \" << limit << std::endl;\r\n      // float Switch over to normal if df > 8.38861e+006\r\n      // double Switch over to normal if df > 4.5036e+015\r\n      // Can't test real_concept - doesn't converge.\r\n\r\n      boost::math::normal_distribution<RealType> n(0, 1); // \r\n      students_t_distribution<RealType> st(boost::math::tools::max_value<RealType>()); // Well over the switchover point,\r\n      // PDF\r\n      BOOST_CHECK_EQUAL(pdf(st, 0), pdf(n, 0.)); // Should be exactly equal.\r\n\r\n      students_t_distribution<RealType> st2(limit /5 ); // Just below the switchover point,\r\n      BOOST_CHECK_CLOSE_FRACTION(pdf(st2, 0), pdf(n, 0.), tolerance); // Should be very close to normal.\r\n      // CDF\r\n      BOOST_CHECK_EQUAL(cdf(st, 0), cdf(n, 0.)); // Should be exactly equal.\r\n      BOOST_CHECK_CLOSE_FRACTION(cdf(st2, 0), cdf(n, 0.), tolerance); // Should be very close to normal.\r\n\r\n      // Tests for df = infinity.\r\n      students_t_distribution<RealType> infdf(inf);\r\n      BOOST_CHECK_EQUAL(infdf.degrees_of_freedom(), inf);\r\n      BOOST_CHECK_EQUAL(mean(infdf), 0); // OK.\r\n#ifndef BOOST_NO_EXCEPTIONS\r\n      BOOST_MATH_CHECK_THROW(students_t_distribution<RealType> minfdf(-inf), std::domain_error);\r\n      BOOST_MATH_CHECK_THROW(students_t_distribution<RealType> minfdf(nan), std::domain_error);\r\n      BOOST_MATH_CHECK_THROW(students_t_distribution<RealType> minfdf(-nan), std::domain_error);\r\n#endif\r\n      BOOST_CHECK_EQUAL(pdf(infdf, -inf), 0);\r\n      BOOST_CHECK_EQUAL(pdf(infdf, +inf), 0);\r\n      BOOST_CHECK_EQUAL(cdf(infdf, -inf), 0);\r\n      BOOST_CHECK_EQUAL(cdf(infdf, +inf), 1);\r\n\r\n     // BOOST_CHECK_CLOSE_FRACTION(pdf(infdf, 0), static_cast<RealType>(0.3989422804014326779399460599343818684759L), tolerance);\r\n      BOOST_CHECK_CLOSE_FRACTION(pdf(infdf, 0),boost::math::constants::one_div_root_two_pi<RealType>() , tolerance);\r\n      BOOST_CHECK_CLOSE_FRACTION(cdf(infdf, 0),boost::math::constants::half<RealType>() , tolerance);\r\n\r\n    // Checks added for Trac #7717 report by Thomas Mang.\r\n\r\n    BOOST_MATH_CHECK_THROW(quantile(dist, -1), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(quantile(dist, 2), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(pdf(students_t_distribution<RealType>(0), 0), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(pdf(students_t_distribution<RealType>(-1), 0), std::domain_error);\r\n  \r\n    // Check on df for mean (moment k = 1)\r\n    BOOST_MATH_CHECK_THROW(mean(students_t_distribution<RealType>(nan)), std::domain_error);\r\n//    BOOST_MATH_CHECK_THROW(mean(students_t_distribution<RealType>(inf)), std::domain_error); inf is now OK\r\n    BOOST_MATH_CHECK_THROW(mean(students_t_distribution<RealType>(-1)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(mean(students_t_distribution<RealType>(0)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(mean(students_t_distribution<RealType>(1)), std::domain_error); // df == k\r\n    BOOST_CHECK_EQUAL(mean(students_t_distribution<RealType>(2)), 0); // OK.\r\n    BOOST_CHECK_EQUAL(mean(students_t_distribution<RealType>(inf)), 0); // OK.\r\n\r\n    // Check on df for variance (moment 2)\r\n    BOOST_MATH_CHECK_THROW(variance(students_t_distribution<RealType>(nan)), std::domain_error);\r\n//    BOOST_MATH_CHECK_THROW(variance(students_t_distribution<RealType>(inf)), std::domain_error); // inf is now OK.\r\n    BOOST_MATH_CHECK_THROW(variance(students_t_distribution<RealType>(-1)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(variance(students_t_distribution<RealType>(0)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(variance(students_t_distribution<RealType>(1)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(variance(students_t_distribution<RealType>(static_cast<RealType>(1.99999L))), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(variance(students_t_distribution<RealType>(static_cast<RealType>(1.99999L))), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(variance(students_t_distribution<RealType>(2)), std::domain_error); // df == \r\n    BOOST_CHECK_EQUAL(variance(students_t_distribution<RealType>(2.5)), 5); // OK.\r\n    BOOST_CHECK_EQUAL(variance(students_t_distribution<RealType>(3)), 3); // OK.\r\n    BOOST_CHECK_EQUAL(variance(students_t_distribution<RealType>(inf)), 1); // OK.\r\n\r\n    // Check on df for skewness (moment 3)\r\n    BOOST_MATH_CHECK_THROW(skewness(students_t_distribution<RealType>(nan)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(skewness(students_t_distribution<RealType>(-1)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(skewness(students_t_distribution<RealType>(0)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(skewness(students_t_distribution<RealType>(1)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(skewness(students_t_distribution<RealType>(1.5L)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(skewness(students_t_distribution<RealType>(2)), std::domain_error); \r\n    BOOST_MATH_CHECK_THROW(skewness(students_t_distribution<RealType>(3)), std::domain_error); // df == k\r\n    BOOST_CHECK_EQUAL(skewness(students_t_distribution<RealType>(3.5)), 0); // OK.\r\n    BOOST_CHECK_EQUAL(skewness(students_t_distribution<RealType>(4)), 0); // OK.\r\n    BOOST_CHECK_EQUAL(skewness(students_t_distribution<RealType>(inf)), 0); // OK.\r\n\r\n    // Check on df for kurtosis_excess (moment 4)\r\n    BOOST_MATH_CHECK_THROW(kurtosis_excess(students_t_distribution<RealType>(nan)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis_excess(students_t_distribution<RealType>(-1)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis_excess(students_t_distribution<RealType>(0)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis_excess(students_t_distribution<RealType>(1)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis_excess(students_t_distribution<RealType>(1.5L)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis_excess(students_t_distribution<RealType>(2)), std::domain_error); \r\n    BOOST_MATH_CHECK_THROW(kurtosis(students_t_distribution<RealType>(static_cast<RealType>(2.1))), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis_excess(students_t_distribution<RealType>(3)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis_excess(students_t_distribution<RealType>(4)), std::domain_error); // df == k\r\n    BOOST_CHECK_EQUAL(kurtosis_excess(students_t_distribution<RealType>(5)), 6); // OK.\r\n    BOOST_CHECK_EQUAL(kurtosis_excess(students_t_distribution<RealType>(inf)), 0); // OK.\r\n\r\n    // Check on df for kurtosis (moment 4)\r\n    BOOST_MATH_CHECK_THROW(kurtosis(students_t_distribution<RealType>(nan)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis(students_t_distribution<RealType>(-1)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis(students_t_distribution<RealType>(0)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis(students_t_distribution<RealType>(1)), std::domain_error); \r\n    BOOST_MATH_CHECK_THROW(kurtosis(students_t_distribution<RealType>(2)), std::domain_error); \r\n    BOOST_MATH_CHECK_THROW(kurtosis(students_t_distribution<RealType>(static_cast<RealType>(2.0001L))), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis(students_t_distribution<RealType>(3)), std::domain_error);\r\n    BOOST_MATH_CHECK_THROW(kurtosis(students_t_distribution<RealType>(4)), std::domain_error); // df == k\r\n    BOOST_CHECK_EQUAL(kurtosis(students_t_distribution<RealType>(5)), 9); // OK.\r\n    BOOST_CHECK_EQUAL(kurtosis(students_t_distribution<RealType>(inf)), 3); // OK.\r\n\r\n   }\r\n\r\n\r\n    // Use a new distribution ignore_error_students_t with a custom policy to ignore all errors,\r\n    // and check returned values are as expected.\r\n\r\n    /* \r\n     Sandia-darwin-intel-12.0 - math - test_students_t / intel-darwin-12.0\r\n    ../libs/math/test/test_students_t.cpp(544): error: \"domain_error\" has already been declared in the current scope\r\n    using boost::math::policies::domain_error;\r\n\r\n../libs/math/test/test_students_t.cpp(552): error: \"pole_error\" has already been declared in the current scope\r\n    using boost::math::policies::pole_error;\r\n\r\n    Unclear where previous declaration is. \r\n    Does not seem to be in student_t.hpp or any included files???\r\n\r\n    So to avoid this perceived problem by this compiler,\r\n    the ignore policy below uses fully specified names.\r\n    */\r\n\r\n    using boost::math::policies::policy;\r\n  // Types of error whose action can be altered by policies:.\r\n  //using boost::math::policies::evaluation_error;\r\n  //using boost::math::policies::domain_error;\r\n  //using boost::math::policies::overflow_error;\r\n  //using boost::math::policies::underflow_error;\r\n  //using boost::math::policies::domain_error;\r\n  //using boost::math::policies::pole_error;\r\n\r\n  //// Actions on error (in enum error_policy_type):\r\n  //using boost::math::policies::errno_on_error;\r\n  //using boost::math::policies::ignore_error;\r\n  //using boost::math::policies::throw_on_error;\r\n  //using boost::math::policies::denorm_error;\r\n  //using boost::math::policies::pole_error;\r\n  //using boost::math::policies::user_error;\r\n\r\n  typedef policy<\r\n    boost::math::policies::domain_error<boost::math::policies::ignore_error>,\r\n    boost::math::policies::overflow_error<boost::math::policies::ignore_error>,\r\n    boost::math::policies::underflow_error<boost::math::policies::ignore_error>,\r\n    boost::math::policies::denorm_error<boost::math::policies::ignore_error>,\r\n    boost::math::policies::pole_error<boost::math::policies::ignore_error>,\r\n    boost::math::policies::evaluation_error<boost::math::policies::ignore_error>\r\n              > my_ignore_policy;\r\n\r\n  typedef students_t_distribution<RealType, my_ignore_policy> ignore_error_students_t;\r\n\r\n\r\n\r\n  // Only test NaN and infinity if type has these features (realconcept returns zero).\r\n  // Integers are always converted to RealType,\r\n  // others requires static cast to RealType from long double.\r\n\r\n  if(std::numeric_limits<RealType>::has_quiet_NaN)\r\n  {\r\n  // Mean\r\n    BOOST_CHECK((boost::math::isnan)(mean(ignore_error_students_t(-1))));\r\n    BOOST_CHECK((boost::math::isnan)(mean(ignore_error_students_t(0))));\r\n    BOOST_CHECK((boost::math::isnan)(mean(ignore_error_students_t(1))));\r\n\r\n    // Variance\r\n    BOOST_CHECK((boost::math::isnan)(variance(ignore_error_students_t(std::numeric_limits<RealType>::quiet_NaN()))));\r\n    BOOST_CHECK((boost::math::isnan)(variance(ignore_error_students_t(-1))));\r\n    BOOST_CHECK((boost::math::isnan)(variance(ignore_error_students_t(0))));\r\n    BOOST_CHECK((boost::math::isnan)(variance(ignore_error_students_t(1))));\r\n    BOOST_CHECK((boost::math::isnan)(variance(ignore_error_students_t(static_cast<RealType>(1.7L)))));\r\n    BOOST_CHECK((boost::math::isnan)(variance(ignore_error_students_t(2))));\r\n\r\n  // Skewness\r\n    BOOST_CHECK((boost::math::isnan)(skewness(ignore_error_students_t(std::numeric_limits<RealType>::quiet_NaN()))));\r\n    BOOST_CHECK((boost::math::isnan)(skewness(ignore_error_students_t(-1))));\r\n    BOOST_CHECK((boost::math::isnan)(skewness(ignore_error_students_t(0))));\r\n    BOOST_CHECK((boost::math::isnan)(skewness(ignore_error_students_t(1))));\r\n    BOOST_CHECK((boost::math::isnan)(skewness(ignore_error_students_t(2))));\r\n    BOOST_CHECK((boost::math::isnan)(skewness(ignore_error_students_t(3))));\r\n\r\n  // Kurtosis \r\n    BOOST_CHECK((boost::math::isnan)(kurtosis(ignore_error_students_t(std::numeric_limits<RealType>::quiet_NaN()))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis(ignore_error_students_t(-1))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis(ignore_error_students_t(0))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis(ignore_error_students_t(1))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis(ignore_error_students_t(2))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis(ignore_error_students_t(static_cast<RealType>(2.0001L)))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis(ignore_error_students_t(3))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis(ignore_error_students_t(4))));\r\n \r\n    // Kurtosis excess\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis_excess(ignore_error_students_t(std::numeric_limits<RealType>::quiet_NaN()))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis_excess(ignore_error_students_t(-1))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis_excess(ignore_error_students_t(0))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis_excess(ignore_error_students_t(1))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis_excess(ignore_error_students_t(2))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis_excess(ignore_error_students_t(static_cast<RealType>(2.0001L)))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis_excess(ignore_error_students_t(3))));\r\n    BOOST_CHECK((boost::math::isnan)(kurtosis_excess(ignore_error_students_t(4))));\r\n  } // has_quiet_NaN\r\n\r\n  BOOST_CHECK(boost::math::isfinite(mean(ignore_error_students_t(1 + std::numeric_limits<RealType>::epsilon()))));\r\n  BOOST_CHECK(boost::math::isfinite(variance(ignore_error_students_t(2 + 2 * std::numeric_limits<RealType>::epsilon()))));\r\n  BOOST_CHECK(boost::math::isfinite(variance(ignore_error_students_t(static_cast<RealType>(2.0001L)))));\r\n  BOOST_CHECK(boost::math::isfinite(variance(ignore_error_students_t(2 + 2 * std::numeric_limits<RealType>::epsilon()))));\r\n  BOOST_CHECK(boost::math::isfinite(skewness(ignore_error_students_t(3 + 3 * std::numeric_limits<RealType>::epsilon()))));\r\n  BOOST_CHECK(boost::math::isfinite(kurtosis(ignore_error_students_t(4 + 4 * std::numeric_limits<RealType>::epsilon()))));\r\n  BOOST_CHECK(boost::math::isfinite(kurtosis(ignore_error_students_t(static_cast<RealType>(4.0001L)))));\r\n\r\n  // check_out_of_range<students_t_distribution<RealType> >(1);\r\n  // Cannot be used because fails \"exception std::domain_error is expected but not raised\" \r\n  // if df = +infinity is allowed, must use new version that allows skipping infinity tests.\r\n  // Infinite == true\r\n\r\n  check_support<students_t_distribution<RealType> >(students_t_distribution<RealType>(1), true);\r\n\r\n} // template <class RealType>void test_spots(RealType)\r\n\r\nBOOST_AUTO_TEST_CASE( test_main )\r\n{\r\n  // Check that can construct students_t distribution using the two convenience methods:\r\n  using namespace boost::math;\r\n  students_t myst1(2); // Using typedef\r\n  students_t_distribution<> myst2(2); // Using default RealType double.\r\n   //students_t_distribution<double> myst3(2); // Using explicit RealType double.\r\n\r\n   // Basic sanity-check spot values.\r\n   // (Parameter value, arbitrarily zero, only communicates the floating point type).\r\n  test_spots(0.0F); // Test float. OK at decdigits = 0 tolerance = 0.0001 %\r\n  test_spots(0.0); // Test double. OK at decdigits 7, tolerance = 1e07 %\r\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\r\n  test_spots(0.0L); // Test long double.\r\n#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\r\n  test_spots(boost::math::concepts::real_concept(0.)); // Test real concept.\r\n#endif\r\n#else\r\n   std::cout << \"<note>The long double tests have been disabled on this platform \"\r\n      \"either because the long double overloads of the usual math functions are \"\r\n      \"not available at all, or because they are too inaccurate for these tests \"\r\n      \"to pass.</note>\" << std::endl;\r\n#endif\r\n\r\n\r\n   \r\n} // BOOST_AUTO_TEST_CASE( test_main )\r\n\r\n/*\r\n\r\nAutorun \"i:\\boost-06-05-03-1300\\libs\\math\\test\\Math_test\\debug\\test_students_t.exe\"\r\nRunning 1 test case...\r\nTolerance for type float is 0.0001 %\r\nTolerance for type double is 0.0001 %\r\nTolerance for type long double is 0.0001 %\r\nTolerance for type class boost::math::concepts::real_concept is 0.0001 %\r\n*** No errors detected\r\n\r\n*/\r\n\r\n\r\n", "meta": {"hexsha": "b9c74afe6b4d94def051af64d8d962bacd46c166", "size": 38606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/test/test_students_t.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/test/test_students_t.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/test/test_students_t.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 50.0726329442, "max_line_length": 130, "alphanum_fraction": 0.6518675853, "num_tokens": 9469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.6051476663360131}}
{"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include <fstream>\n\n#include <boost/range/adaptor/reversed.hpp>\n#include <boost/math/constants/constants.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\nnamespace {\n    const long double epsilon = 1e-9L;\n\n    struct comparedouble {\n        bool operator()(const long double &lhs, const long double &rhs) const {\n            return std::abs(lhs - rhs) < epsilon ? false : lhs < rhs;\n        }\n    };\n}\n\nENREGISTRER_PROBLEME(177, \"Integer angled Quadrilaterals\") {\n    // Let ABCD be a convex quadrilateral, with diagonals AC and BD. At each vertex the diagonal makes an angle with\n    // each of the two sides, creating eight corner angles.\n    //\n    // For example, at vertex A, the two angles are CAD, CAB.\n    //\n    // We call such a quadrilateral for which all eight corner angles have integer values when measured in degrees an\n    // \"integer angled quadrilateral\". An example of an integer angled quadrilateral is a square, where all eight corner\n    // angles are 45\u00b0. Another example is given by DAC = 20\u00b0, BAC = 60\u00b0, ABD = 50\u00b0, CBD = 30\u00b0, BCA = 40\u00b0, DCA = 30\u00b0,\n    // CDB = 80\u00b0, ADB = 50\u00b0.\n    //\n    // What is the total number of non-similar integer angled quadrilaterals?\n    //\n    // Note: In your calculations you may assume that a calculated angle is integral if it is within a tolerance of 10-9\n    // of an integer value.\n    std::vector<long double> sinus(180, 0.0L);\n    std::vector<long double> cosinus(180, 0.0L);\n    std::vector<long double> rad(180, 0.0L);\n    std::vector<bool> prevalue(10000 + 1, false);\n\n    std::vector<nombre> solution(8 + 1, 0);\n\n    std::set<long double, comparedouble> fs;\n    for (nombre i = 1; i < 180; i++) {\n        rad[i] = static_cast<long double>(i) * M_PIl / 180.0L;\n        sinus[i] = std::sin(rad[i]);\n        cosinus[i] = std::cos(rad[i]);\n        auto j = static_cast<nombre>(sinus[i] * 10000);\n        prevalue[j] = true;\n        fs.insert(sinus[i]);\n    }\n    prevalue[10000] = true; // sin90\n    prevalue[10000 - 1] = true; // sin90\n    prevalue[5000] = true; // sin30\n    prevalue[5000 - 1] = true; //sin30\n\n    for (nombre a = 1; a <= 45; a++)\n        for (nombre b = a; a + b < 180 - 1; b++)\n            for (nombre c = 1; a + b + c < 180; c++) {\n                nombre d = 180 - a - b - c;\n                for (nombre e = 1; e < b + d; e++) {\n                    nombre f = b + d - e;\n                    long double m = (sinus[b] * sinus[c] * sinus[f]) / (sinus[a] * sinus[e] * sinus[d]);\n                    long double n = cosinus[a + c];\n                    long double siny = std::sqrt((1 - n * n) / (m * m + 2 * m * n + 1));\n                    auto j = static_cast<nombre>(siny * 10000);\n                    if (!prevalue[j]) continue;\n                    if (fs.find(siny) != fs.end()) {\n                        if (siny > 1) siny = 1;\n\n                        auto y = static_cast<nombre>(std::asin(siny) * 180 / M_PIl + 0.01L);\n                        long double sinx = m * siny;\n                        long double xangle = (std::abs(sinx - 1) < epsilon) ? 90 : std::asin(sinx) * 180 / M_PIl;\n                        auto x = static_cast<nombre>(xangle + 0.01L);\n                        if (xangle < x + epsilon && xangle > x - epsilon) {\n                            x = (180 - x + y == a + c) ? 180 - x : x;\n                            y = (180 + x - y == a + c) ? 180 - y : y;\n\n                            std::vector<vecteur> quadrilateres\n                                    {\n                                            {a, b, d, y, x, f, e, c},\n                                            {d, y, x, f, e, c, a, b},\n                                            {x, f, e, c, a, b, d, y},\n                                            {e, c, a, b, d, y, x, f},\n                                            {b, a, c, e, f, x, y, d},\n                                            {c, e, f, x, y, d, b, a},\n                                            {f, x, y, d, b, a, c, e},\n                                            {y, d, b, a, c, e, f, x}\n                                    };\n\n                            std::set<vecteur> s;\n                            for (auto quadrilatere: quadrilateres) {\n                                if (quadrilatere.front() <= quadrilatere.at(1) && quadrilatere.front() <= 45)\n                                    s.insert(quadrilatere);\n                            }\n\n                            solution[s.size()]++;\n                        }\n                    }\n                }\n            }\n\n    nombre resultat = 0;\n    for (nombre i = 1; i <= 8; i++)\n        resultat += solution[i] / i;\n\n    return std::to_string(resultat);\n}\n", "meta": {"hexsha": "08d2f4fd5b6102c35f82820bd06349ed973e4544", "size": 4731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme177.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/probleme177.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/probleme177.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": 43.0090909091, "max_line_length": 120, "alphanum_fraction": 0.4546607483, "num_tokens": 1289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6050517443645119}}
{"text": "//---------------------------------------------------------------------------\n\n#pragma hdrstop\n\n#include <System.SysUtils.hpp>\n\n#include <random>\n#include <future>\n#include <vector>\n#include <numeric>\n#include <iterator>\n#include <utility>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n\n#include \"IModel.h\"\n\n#include \"StochasticMTAreaCalc.h\"\n\nusing std::mt19937;\nusing std::uniform_real_distribution;\nusing std::accumulate;\nusing std::begin;\nusing std::end;\n\nusing boost::geometry::envelope;\n\nusing boost::geometry::model::box;\nusing boost::geometry::area;\n\n//---------------------------------------------------------------------------\n\n#pragma package(smart_init)\n\nnamespace AreaPrj {\n\nString StochasticMTAreaCalc::DoGetDescription() const\n{\n    return Format(\n        _D( \"\\'%s\\' con %.0n di punti casuali suddiviso in %u task\" ),\n        ARRAYOFCONST((\n            GetName(),\n            static_cast<long double>( pointCount_ ),\n            taskCount_\n        ))\n    );\n}\n\ndouble StochasticMTAreaCalc::DoCompute( IModel const & Model ) const\n{\n    box<IModel::PointType> BoundingBox;\n    auto const & Polygons = Model.GetPolygons();\n    envelope( Polygons, BoundingBox );\n    std::vector<std::future<size_t>> Tasks;\n    for ( size_t n = 0 ; n < taskCount_ ; ++n ) {\n        Tasks.push_back(\n            std::async(\n                std::launch::async,\n                [&]( std::random_device::result_type seed, size_t PtCnt ) -> size_t {\n                    auto const & Polygons = Model.GetPolygons();\n                    mt19937 Generator( seed );\n                    uniform_real_distribution<> DisX(\n                        BoundingBox.min_corner().x(),\n                        BoundingBox.max_corner().x()\n                    );\n\n                    uniform_real_distribution<> DisY(\n                        BoundingBox.min_corner().y(),\n                        BoundingBox.max_corner().y()\n                    );\n\n                    size_t HitCnt {};\n\n                    for ( size_t n = 0 ; n < PtCnt ; ++n ) {\n                        if ( Model.HitTest( DisX( Generator ), DisY( Generator ) ) ) {\n                            ++HitCnt;\n                        }\n                    }\n                    return HitCnt;\n                },\n                rd_(),\n                pointCount_ / taskCount_\n            )\n        );\n    }\n    return\n        static_cast<double>(\n            accumulate<decltype( begin( Tasks ) ), size_t>(\n                begin( Tasks ), end( Tasks ), {},\n                []( size_t Val, auto& fut ) {\n                    return Val + fut.get();\n                }\n            )\n        ) /\n        pointCount_ * area( BoundingBox );\n}\n\n} // End of namespace AreaPrj\n", "meta": {"hexsha": "93ddbe7d8ffd35524f79231697ea76c932e37d02", "size": 2741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "StochasticMTAreaCalc.cpp", "max_stars_repo_name": "gcardi/AreaPrj", "max_stars_repo_head_hexsha": "831b23f0f7f444dca5f1395c2a4a0aff1e6d2f75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "StochasticMTAreaCalc.cpp", "max_issues_repo_name": "gcardi/AreaPrj", "max_issues_repo_head_hexsha": "831b23f0f7f444dca5f1395c2a4a0aff1e6d2f75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "StochasticMTAreaCalc.cpp", "max_forks_repo_name": "gcardi/AreaPrj", "max_forks_repo_head_hexsha": "831b23f0f7f444dca5f1395c2a4a0aff1e6d2f75", "max_forks_repo_licenses": ["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.41, "max_line_length": 86, "alphanum_fraction": 0.4863188617, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.6992544273261176, "lm_q1q2_score": 0.605011775231399}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"dotproduct.h\"\n#include \"common/pixel_benchmark.h\"\n#include \"common/pixel_fast_rng.h\"\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/simd_intrinsics.hpp>\n\n#include <Eigen/Dense>\n\n#include <iostream>\nusing namespace std;\n\nstatic void dotproduct_f32_test();\nstatic float dotproduct_f32_opencv1(float* a, float* b, uint32_t len);\nstatic float dotproduct_f32_opencv2(float* a, float* b, uint32_t len);\nstatic float dotproduct_f32_eigen(float* a, float* b, uint32_t len);\n\nstatic void dotproduct_u8_test();\nstatic uint64_t dotproduct_u8_opencv1(uint8_t* a, uint8_t* b, uint32_t len);\nstatic uint64_t dotproduct_u8_opencv2(uint8_t* a, uint8_t* b, uint32_t len);\nstatic uint64_t dotproduct_u8_eigen(uint8_t* a, uint8_t* b, uint32_t len);\nstatic uint64_t dotproduct_u8_eigen2(uint8_t* a, uint8_t* b, uint32_t len);\n\nstatic void arm_marco_determine();\n\n//----------------------------------------------------------------------\n\nfloat dotproduct_f32_opencv1(float* a, float* b, uint32_t len)\n{\n    cv::Mat matA(1, len, CV_32FC1, a);\n    cv::Mat matB(1, len, CV_32FC1, b);\n    float res = matA.dot(matB);\n    return res;\n}\n\nfloat dotproduct_f32_opencv2(float* a, float* b, uint32_t len)\n{\n    size_t step = sizeof(cv::v_float32)/sizeof(float);\n    cv::v_float32 v_sum = cv::vx_setzero_f32();\n    size_t vec_size = len - len % step;\n    for (size_t i=0; i< vec_size; i+=step)\n    {\n        cv::v_float32 v1 = cv::vx_load(a+i);\n        cv::v_float32 v2 = cv::vx_load(b+i);\n        v_sum += v1 * v2;\n    }\n\n    float sum = cv::v_reduce_sum(v_sum);\n\n    for (size_t i= vec_size; i<len; i++) {\n        sum += a[i] * b[i];\n    }\n\n    return sum;\n}\n\nfloat dotproduct_f32_eigen(float* a, float* b, uint32_t len) {\n    Eigen::Map<Eigen::Matrix<float, 1, Eigen::Dynamic, Eigen::RowMajor>> va(a, len);\n    Eigen::Map<Eigen::Matrix<float, 1, Eigen::Dynamic, Eigen::RowMajor>> vb(b, len);\n    float res = va.dot(vb);\n    return res;\n}\n\n\n\nuint64_t dotproduct_u8_opencv1(uint8_t* a, uint8_t* b, uint32_t len)\n{\n    cv::Mat matA(1, len, CV_8UC1, a);\n    cv::Mat matB(1, len, CV_8UC1, b);\n    uint64_t res = matA.dot(matB);\n    return res;\n}\n\nuint64_t dotproduct_u8_opencv2(uint8_t* a, uint8_t* b, uint32_t len)\n{\n    // \u5b9e\u73b0\u8d77\u6765\u53ef\u80fd\u7565\u7e41\u7410\uff0c\u5e76\u4e14\u548cneon\u5b9e\u73b0\u7c7b\u4f3c\uff0c\u6682\u65f6\u4e0d\u5199\n    return 0;\n}\n\nuint64_t dotproduct_u8_eigen(uint8_t* a, uint8_t* b, uint32_t len)\n{\n    // \u8fd9\u91cc\u7684\u5b9e\u73b0\u6709\u95ee\u9898\uff1a\u5982\u679c\u662fu8\u7684Eigen::Matrix\u505adotproduct\uff0c\u7ed3\u679c\u4e0d\u5bf9\n    // \u5982\u679c\u8f6c\u4e3au64\u6216float\u7684Eigen::Matrix\uff0c\u7ed3\u679c\u5bf9\uff0c\u4f46\u662f\u6bd4naive\u5b9e\u73b0\u6162\u597d\u591a\u500d\n    Eigen::Map<Eigen::Matrix<uint8_t, 1, Eigen::Dynamic, Eigen::RowMajor>> va(a, len);\n    Eigen::Map<Eigen::Matrix<uint8_t, 1, Eigen::Dynamic, Eigen::RowMajor>> vb(b, len);\n    \n    Eigen::Matrix<uint64_t, 1, Eigen::Dynamic, Eigen::RowMajor> fa = va.cast<uint64_t>();\n    Eigen::Matrix<uint64_t, 1, Eigen::Dynamic, Eigen::RowMajor> fb = vb.cast<uint64_t>();\n\n    return fa.dot(fb);\n}\n\nuint64_t dotproduct_u8_eigen2(uint8_t* a, uint8_t* b, uint32_t len)\n{\n    // \u8fd9\u91cc\u7684\u5b9e\u73b0\u6709\u95ee\u9898\uff1a\u5982\u679c\u662fu8\u7684Eigen::Matrix\u505adotproduct\uff0c\u7ed3\u679c\u4e0d\u5bf9\n    // \u5982\u679c\u8f6c\u4e3au64\u6216float\u7684Eigen::Matrix\uff0c\u7ed3\u679c\u5bf9\uff0c\u4f46\u662f\u6bd4naive\u5b9e\u73b0\u6162\u597d\u591a\u500d\n    Eigen::Map<Eigen::Matrix<uint8_t, 1, Eigen::Dynamic, Eigen::RowMajor>> va(a, len);\n    Eigen::Map<Eigen::Matrix<uint8_t, 1, Eigen::Dynamic, Eigen::RowMajor>> vb(b, len);\n    uint64_t res = va.cast<uint64_t>().dot(vb.cast<uint64_t>());\n    return res;\n}\n\nvoid dotproduct_f32_test()\n{\n    uint32_t len = 200000000; //200M\n    float* a = (float*)malloc(sizeof(float)*len);\n    float* b = (float*)malloc(sizeof(float)*len);\n\n    float res_naive;\n    float res_opencv1;\n    float res_opencv2;\n    float res_eigen;\n    float res_asimd;\n    float res_asimd2;\n    float res_asimd3;\n\n    double t_start, t_cost;\n\n    g_state.a = 7767517;\n    t_start = pixel_get_current_time();\n    for(uint32_t i=0; i<len; i++) {\n        a[i] = pixel_fast_random_float(-1.2, 1.2);\n        b[i] = pixel_fast_random_float(-1.2, 1.2);\n    }\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"generate random numbers, time cost %.4lf ms\\n\", t_cost);\n\n    // naive\n    t_start = pixel_get_current_time();\n    res_naive = dotproduct_f32_naive(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_f32, naive, time cost %.4lf ms\\n\", t_cost);\n\n    // opencv, method1\n    t_start = pixel_get_current_time();\n    res_opencv1 = dotproduct_f32_opencv1(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_f32, opencv method1, time cost %.4lf ms\\n\", t_cost);\n\n    // opencv, method2\n    t_start = pixel_get_current_time();\n    res_opencv2 = dotproduct_f32_opencv2(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_f32, opencv method2, time cost %.4lf ms\\n\", t_cost);\n\n    // eigen\n    t_start = pixel_get_current_time();\n    res_eigen = dotproduct_f32_eigen(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_f32, eigen, time cost %.4lf ms\\n\", t_cost);\n\n    // asimd\n    t_start = pixel_get_current_time();\n    res_asimd = dotproduct_f32_asimd(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_f32, asimd, time cost %.4lf ms\\n\", t_cost);\n\n    // asimd2\n    t_start = pixel_get_current_time();\n    res_asimd2 = dotproduct_f32_asimd2(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_f32, asimd2, time cost %.4lf ms\\n\", t_cost);\n\n    // asimd3\n    t_start = pixel_get_current_time();\n    res_asimd3 = dotproduct_f32_asimd3(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_f32, asimd3, time cost %.4lf ms\\n\", t_cost);\n\n    // validate\n    int mis_opencv1=0;\n    int mis_opencv2=0;\n    int mis_eigen=0;\n    int mis_asimd=0;\n    int mis_asimd2=0;\n    if (res_naive!=res_opencv1) {\n        mis_opencv1++;\n    }\n    if (res_naive!=res_opencv2) {\n        mis_opencv2++;\n    }\n    if (res_naive!=res_eigen) {\n        mis_eigen++;\n    }\n    if (res_naive!=res_asimd) {\n        mis_asimd++;\n    }\n    if (res_naive!=res_asimd2) {\n        mis_asimd2++;\n    }\n    printf(\"mis_opencv1=%d, mis_opencv2=%d, mis_eigen=%d, mis_asimd=%d, mis_asimd2=%d\\n\", \n        mis_opencv1, mis_opencv2, mis_eigen, mis_asimd, mis_asimd2);\n    printf(\"res_naive=%f, res_opencv1=%f, res_opencv2=%f, res_eigen=%f, res_asimd=%f, res_asimd2=%f, res_asimd3=%f\\n\",\n        res_naive, res_opencv1, res_opencv2, res_eigen, res_asimd, res_asimd2, res_asimd3\n    );\n}\n\nvoid dotproduct_u8_test()\n{\n    uint32_t len = 200000000; //200M\n    uint8_t* a = (uint8_t*)malloc(sizeof(uint8_t)*len);\n    uint8_t* b = (uint8_t*)malloc(sizeof(uint8_t)*len);\n\n    uint64_t res_naive;\n    uint64_t res_opencv1;\n    uint64_t res_opencv2;\n    uint64_t res_eigen;\n    uint64_t res_asimd;\n    uint64_t res_asimd2;\n    uint64_t res_asimd3;\n    uint64_t res_asimd4;\n\n    double t_start, t_cost;\n\n    g_state.a = 7767517;\n    t_start = pixel_get_current_time();\n    for(uint32_t i=0; i<len; i++) {\n        a[i] = (uint8_t)(pixel_fast_random_float(0, 255));\n        b[i] = (uint8_t)(pixel_fast_random_float(0, 255));\n    }\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"generate random numbers, time cost %.4lf ms\\n\", t_cost);\n\n    // naive\n    t_start = pixel_get_current_time();\n    res_naive = dotproduct_u8_naive(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_u8, naive, time cost %.4lf ms\\n\", t_cost);\n\n    // opencv, method1\n    t_start = pixel_get_current_time();\n    res_opencv1 = dotproduct_u8_opencv1(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_u8, opencv method1, time cost %.4lf ms\\n\", t_cost);\n\n    // opencv, method2\n    t_start = pixel_get_current_time();\n    res_opencv2 = dotproduct_u8_opencv2(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_u8, opencv method2, time cost %.4lf ms\\n\", t_cost);\n\n    // eigen\n    t_start = pixel_get_current_time();\n    res_eigen = dotproduct_u8_eigen(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_u8, eigen, time cost %.4lf ms\\n\", t_cost);\n\n    // eigen2\n    t_start = pixel_get_current_time();\n    res_eigen = dotproduct_u8_eigen2(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_u8, eigen2, time cost %.4lf ms\\n\", t_cost);\n\n    // asimd\n    t_start = pixel_get_current_time();\n    res_asimd = dotproduct_u8_asimd(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_u8, asimd, time cost %.4lf ms\\n\", t_cost);\n\n    // asimd2\n    t_start = pixel_get_current_time();\n    res_asimd2 = dotproduct_u8_asimd2(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_u8, asimd2, time cost %.4lf ms\\n\", t_cost);\n\n    // asimd3\n    t_start = pixel_get_current_time();\n    res_asimd3 = dotproduct_u8_asimd3(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_u8, asimd3, time cost %.4lf ms\\n\", t_cost);\n\n    // asimd4\n    t_start = pixel_get_current_time();\n    res_asimd4 = dotproduct_u8_asimd4(a, b, len);\n    t_cost = pixel_get_current_time() - t_start;\n    printf(\"dotproduct_u8, asimd4, time cost %.4lf ms\\n\", t_cost);\n\n    // validate\n    int mis_opencv1=0;\n    int mis_opencv2=0;\n    int mis_eigen=0;\n    int mis_asimd=0;\n    int mis_asimd2=0;\n    int mis_asimd3=0;\n    int mis_asimd4=0;\n    if (res_naive!=res_opencv1) {\n        mis_opencv1++;\n    }\n    if (res_naive!=res_opencv2) {\n        mis_opencv2++;\n    }\n    if (res_naive!=res_eigen) {\n        mis_eigen++;\n    }\n    if (res_naive!=res_asimd) {\n        mis_asimd++;\n    }\n    if (res_naive!=res_asimd2) {\n        mis_asimd2++;\n    }\n    if (res_naive!=res_asimd3) {\n        mis_asimd3++;\n    }\n    if (res_naive!=res_asimd4) {\n        mis_asimd4++;\n    }\n    printf(\"mis_opencv1=%d, mis_opencv2=%d, mis_eigen=%d, mis_asimd=%d, mis_asimd2=%d, mis_asimd3=%d, mis_asimd4=%d\\n\", \n        mis_opencv1, mis_opencv2, mis_eigen, mis_asimd, mis_asimd2, mis_asimd3, mis_asimd4);\n    // printf(\"res_naive=%ul, res_opencv1=%ul, res_opencv2=%ul, res_eigen=%ul, res_asimd=%ul, res_asimd2=%ul, res_asimd3=%ul\\n\",\n    //     res_naive, res_opencv1, res_opencv2, res_eigen, res_asimd, res_asimd2, res_asimd3\n    // );\n    cout << \"res_naive=\" << res_naive << endl;\n    cout << \"res_opencv1=\" << res_opencv1 << endl;\n    cout << \"res_eigen=\" << res_eigen << endl;\n    cout << \"res_asimd=\" << res_asimd << endl;\n    cout << \"res_asimd2=\" << res_asimd2 << endl;\n    cout << \"res_asimd3=\" << res_asimd3 << endl;\n    cout << \"res_asimd4=\" << res_asimd4 << endl;\n}\n\nvoid arm_marco_determine()\n{\n#if __ARM_NEON\n    printf(\"__ARM_NEON\\n\");\n    #if __aarch64__\n        printf(\"__aarch64__\\n\");\n        #if __ARM_FEATURE_FP16_VECTOR_ARITHMETIC\n            printf(\"arm8.2 fp16\\n\");\n        #else\n            printf(\"not arm8.2 fp16\\n\");\n        #endif\n\n        #if __ARM_FEATURE_DOTPROD\n            printf(\"arm8.2 dotproduct\\n\");\n        #else\n            printf(\"not arm8.2 dotproduct\\n\");\n        #endif\n    #else\n        printf(\"not __aarch64__\\n\");\n    #endif // __aarch64__\n#else\n    printf(\"not __ARM_NEON\\n\");\n#endif // __ARM_NEON\n}\n\n\nstatic void sdot_example() {\n#if __ARM_FEATURE_DOTPROD\n    //uint32x2_t vdot_u32 (uint32x2_t r, uint8x8_t a, uint8x8_t b)\n    uint8_t a[8] = {0, 1, 2, 3, 4, 5, 6, 7};\n    uint8_t b[8] = {0, 1, 2, 3, 4, 5, 6, 7};\n    uint8x8_t va = vld1_u8(a);\n    uint8x8_t vb = vld1_u8(b);\n    uint32x2_t vr = vdup_n_u32(0);\n    vr = vdot_u32(vr, va, vb);\n\n    uint32_t res[2];\n    vst1_u32(res, vr);\n    printf(\"res[0]=%d, res[1]=%d\\n\", res[0], res[1]);\n#endif\n}\n\n\nint main() {\n    arm_marco_determine();\n    //dotproduct_f32_test();\n    dotproduct_u8_test();\n\n    return 0;\n}", "meta": {"hexsha": "6b26752ac8f92a5cae86756e5fc2dc78b8c63156", "size": 11664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matcalc/dotproduct_test.cpp", "max_stars_repo_name": "zchrissirhcz/pixel", "max_stars_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T16:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:46:04.000Z", "max_issues_repo_path": "matcalc/dotproduct_test.cpp", "max_issues_repo_name": "zchrissirhcz/pixel", "max_issues_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-01-31T16:04:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T13:58:11.000Z", "max_forks_repo_path": "matcalc/dotproduct_test.cpp", "max_forks_repo_name": "zchrissirhcz/pixel", "max_forks_repo_head_hexsha": "6bfe4b2f2b80de64c7de4b6d8735de8000b7dc3a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:33:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T08:13:56.000Z", "avg_line_length": 31.1871657754, "max_line_length": 128, "alphanum_fraction": 0.6507201646, "num_tokens": 3911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6050117600882824}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n///\n/// \\file self_adjoint_coneigensolver.hpp\n///\n#ifndef MXPFIT_SELF_ADJOINT_CONEIGENSOLVER_HPP\n#define MXPFIT_SELF_ADJOINT_CONEIGENSOLVER_HPP\n\n#include <cassert>\n#include <type_traits>\n\n#include <Eigen/Core>\n#include <Eigen/QR>\n\n#include <mxpfit/jacobi_svd.hpp>\n\nnamespace mxpfit\n{\n///\n/// ### SelfAdjointConeigenSolver\n///\n/// \\brief Compute con-eigenvalue decomposition of self-adjoint matrix having a\n///        rank-revealing decomposition\n///\n/// \\tparam T  Scalar type of matrix to be decomposed.\n///\n/// Let \\f$A\\f$ be an \\f$n \\times n\\f$ self-adjoint matrix having a rank\n/// revealing decomposition of the form\n///\n/// \\f[ A = X D^2 X^{\\ast},\\f]\n///\n/// where \\f$X\\f$ is a \\f$n \\times k \\, (n \\geq k)\\f$ matrix and \\f$D\\f$ is a\n/// \\f$k \\times k\\f$ diagonal matrix with non-negative entries. This class\n/// computes a con-eigenvalue decomposition of matrix \\f$A\\f$ defined as\n///\n/// \\f[\n///   A = \\overline{U} \\Sigma U^{\\ast}\n/// \\f]\n///\n/// where \\f$U\\f$ is a \\f$n \\times k\\f$ matrix satisfying \\f$U^{-1}=U^{T},\\f$\n/// and overline denotes the element-wise complex conjugate of a matrix.\n/// \\f$\\Sigma=\\mathrm{diag}(\\sigma_{1},\\dots,\\sigma_{k})\\f$ is a \\f$k \\times\n/// k\\f$ diagonal matrix with \\f$\\sigma_{1}\\geq\\sigma_{2}\\geq \\cdots \\geq\n/// \\sigma_{k} > 0.\\f$ The con-eigenvalue decomposition defined above is a\n/// special case of singular value decomposition (SVD) \\f$A=W\\Sigma V^{\\ast}\\f$,\n/// where \\f$ W=\\overline{U} \\f$ and \\f$V=U.\\f$\n///\n/// The con-eigenvalue decomposition is computed in high-relative accuracy using\n/// the algorithm developed by Haut and Beylkin. The algorithm can also be\n/// regarded as modification of Demmel's algorithm for high accuracy SVD of a\n/// matrix with rank-revealing decomposition. See the references listed below\n/// for the details.\n///\n///\n/// #### References\n///\n/// 1. T. S. Haut and G. Beylkin, \"FAST AND ACCURATE CON-EIGENVALUE ALGORITHM\n///    FOR OPTIMAL RATIONAL APPROXIMATIONS\", SIAM J. Matrix Anal. Appl. **33**\n///    (2012) 1101-1125. [DOI: https://doi.org/10.1137/110821901]\n/// 2. J. Demmel, \"ACCURATE SINGULAR VALUE DECOMPOSITIONS OF STRUCTURED\n///    MATRICES\", SIAM J. Matrix Anal. Appl. **21** (1999) 562-580.\n///    [DOI: https://doi.org/10.1137/S0895479897328716]\n/// 3. J. Demmel, M. Gu, S. Eisenstat, I. Slapnicar, K. Veselic, and Z. Drmac,\n///    \"ACCURATE SINGULAR VALUE DECOMPOSITIONS OF STRUCTURED MATRICES\", SIAM J.\n///    Linear Algebra Appl. **299** (1999) 21-80. [DOI:\n///    https://doi.org/10.1016/S0024-3795(99)00134-2]\n///\n\nenum DecompositionOption\n{\n    ConeigenvaluesOnly,\n    ComputeConeigenvectors\n};\n\ntemplate <typename T>\nclass SelfAdjointConeigenSolver\n{\npublic:\n    using Index         = Eigen::Index;\n    using Scalar        = T;\n    using RealScalar    = typename Eigen::NumTraits<Scalar>::Real;\n    using ComplexScalar = std::complex<RealScalar>;\n\n    using MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using VectorType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using RealVectorType = Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n\n    using ConeigenvalueType = Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n\nprotected:\n    enum\n    {\n        IsComplex  = Eigen::NumTraits<Scalar>::IsComplex,\n        PacketSize = Eigen::internal::packet_traits<Scalar>::size,\n        Alignment  = Eigen::internal::traits<MatrixType>::Alignment,\n        // Alignment  = Eigen::internal::unpacket_traits<PacketType>::alignment\n    };\n\n    using MappedMatrix = Eigen::Map<MatrixType, Alignment>;\n    using PacketType   = typename Eigen::internal::packet_traits<Scalar>::type;\n\n    MatrixType m_ceigvecs;     // m x n (m >= n)\n    RealVectorType m_ceigvals; // n\n    MatrixType m_mat_work1;    // n x n\n    MatrixType m_mat_work2;    // n x n\n\npublic:\n    SelfAdjointConeigenSolver()                                 = default;\n    SelfAdjointConeigenSolver(const SelfAdjointConeigenSolver&) = default;\n\n    explicit SelfAdjointConeigenSolver(Index size, Index rank)\n        : m_ceigvecs(size, rank),\n          m_ceigvals(rank),\n          m_mat_work1(rank, rank),\n          m_mat_work2(rank, rank)\n    {\n        assert(size >= rank);\n    }\n\n    ~SelfAdjointConeigenSolver() = default;\n\n    template <typename InputMatrix, typename InputVector>\n    void compute(const Eigen::MatrixBase<InputMatrix>& matX,\n                 const Eigen::MatrixBase<InputVector>& vecD,\n                 DecompositionOption option = ComputeConeigenvectors);\n\n    const MatrixType& coneigenvectors() const\n    {\n        return m_ceigvecs;\n    }\n\n    const RealVectorType& coneigenvalues() const\n    {\n        return m_ceigvals;\n    }\n\nprotected:\n    void resize(Index m, Index n)\n    {\n        m_ceigvecs.resize(m, n);\n        m_ceigvals.resize(n);\n        m_mat_work1.resize(n, n);\n        m_mat_work2.resize(n, n);\n    }\n};\n\ntemplate <typename T>\ntemplate <typename InputMatrix, typename InputVector>\nvoid SelfAdjointConeigenSolver<T>::compute(\n    const Eigen::MatrixBase<InputMatrix>& matX,\n    const Eigen::MatrixBase<InputVector>& vecD, DecompositionOption option)\n{\n    EIGEN_STATIC_ASSERT_VECTOR_ONLY(InputVector);\n\n    assert(matX.rows() >= matX.cols());\n    assert(vecD.size() == matX.cols());\n\n    const Index m = matX.rows();\n    const Index n = matX.cols();\n    resize(m, n);\n\n    MappedMatrix matG(m_ceigvecs.data(), n, n);\n\n    //\n    // Form G = D * (X.st() * X) * D\n    //\n    matG.noalias() = matX.transpose() * matX;\n    for (Index j = 0; j < n; ++j)\n    {\n        for (Index i = 0; i < n; ++i)\n        {\n            matG(i, j) *= vecD(i) * vecD(j);\n        }\n    }\n    //\n    // Compute G = Q * R by Householder QR factorization. G is overwritten by QR\n    // factors.\n    //\n    Eigen::HouseholderQR<Eigen::Ref<MatrixType>> qr(matG);\n\n    //\n    // Compute SVD of `R = U S V^H` with high relative accuracy using the\n    // one-sided Jacobi SVD algorithm. Only the singular values and left\n    // singular vectors U are computed. The obtained singular values coincide\n    // with coneigenvalues of input matrix\n    //\n    // Applying the one-sided Jacobi SVD to the matrix X = R^H is much faster\n    // than applying the algorithm to R directly. This is because `R R^H` is\n    // more diagonal than `R^H R`. Thus, `U` is computed as right singular\n    // vectors of R^H.\n    //\n    MatrixType& matRt = m_mat_work1;\n    matRt.setZero();\n    matRt            = matG.template triangularView<Eigen::Upper>().adjoint();\n    MatrixType& matU = m_mat_work2;\n    const RealScalar tol_svd = Eigen::NumTraits<RealScalar>::epsilon() *\n                               Eigen::numext::sqrt(RealScalar(n));\n    one_sided_jacobi_svd(matRt, m_ceigvals, matU, tol_svd);\n\n    //\n    // Quick return if no con-eigenvector is required.\n    //\n    if (option == ConeigenvaluesOnly)\n    {\n        return;\n    }\n\n    //-------------------------------------------------------------------------\n    //\n    // The eigenvectors of A * conj(A) are given as\n    //\n    //   conj(X') = X * D * V * S^{-1/2}.\n    //\n    // However, direct evaluation of eigenvectors with this formula might be\n    // inaccurate since D is ill-conditioned. The following formula are used\n    // instead.\n    //\n    //   conj(X') = X * D * R.inv() * U * S^{1/2}\n    //            = X * (D.inv() * R * D.inv()).inv() * (D.inv() * U *\n    //            S^{1/2})\n    //            = X * R1.inv() * X1\n    //\n    //-------------------------------------------------------------------------\n    // Matrix R is stored on upper triangular part of G\n    auto matR1 = matG.template triangularView<Eigen::Upper>();\n    //\n    // Compute R1 = D^(-1) * R * D^(-1). The upper triangular part of `matG` is\n    // overwritten by R1.\n    //\n    for (Index j = 0; j < n; ++j)\n    {\n        const auto dj = vecD(j);\n        for (Index i = 0; i <= j; ++i)\n        {\n            const auto di = vecD(i);\n            matR1(i, j)   = matR1(i, j) / (di * dj);\n        }\n    }\n    //\n    // Compute X1 = D^{-1} * U * S^{1/2}, and then solve R1 * Y1 = X1 in-place.\n    // Matrix `matU` is overwritten by X1 and then overwritten by Y1.\n    //\n    MatrixType& matY1 = matU;\n    for (Index j = 0; j < n; ++j)\n    {\n        const auto sj = Eigen::numext::sqrt(m_ceigvals(j));\n        for (Index i = 0; i < n; ++i)\n        {\n            matY1(i, j) *= sj / vecD(i);\n        }\n    }\n\n    matR1.solveInPlace(matY1);\n    //\n    // Compute con-eigenvectors U = conj(X) * conj(Y).\n    //\n    m_ceigvecs.noalias() = matX.conjugate() * matY1.conjugate();\n\n    if (IsComplex)\n    {\n        //\n        // Adjust phase factor of each con-eigenvectors, so that U^{T} * U = I\n        //\n        for (Index j = 0; j < n; ++j)\n        {\n            auto xj          = m_ceigvecs.col(j);\n            const auto t     = (xj.transpose() * xj).value();\n            const auto phase = t / std::abs(t);\n            const auto scale = std::sqrt(Eigen::numext::conj(phase));\n            xj *= scale;\n        }\n    }\n}\n\n} // namespace: mxpfit\n\n#endif /* MXPFIT_SELF_ADJOINT_CONEIGENSOLVER_HPP */\n", "meta": {"hexsha": "440c648e69ec041bc7898827bfc48a8f4cedbe69", "size": 10153, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/self_adjoint_coneigensolver.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/self_adjoint_coneigensolver.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/self_adjoint_coneigensolver.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8433333333, "max_line_length": 80, "alphanum_fraction": 0.6131192751, "num_tokens": 2848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6048614561290584}}
{"text": "// Equality comparision of floating point values.\n//\n// Copyright (c) Eric Nodwell\n// See LICENSE for details.\n//\n// Since floating point values are approximate, equality comparison should be\n// done to within some limited precision.  In some cases, the best measure of\n// precision is a certain number of \"ulps\" (\"Units in Last Place\"), where ulps\n// essentially is a count of how many representable floating point numbers\n// separate two given values.  This is what these functions do.\n//\n// It is worth emphasizing that a maximum difference of ulps is often not\n// the best equality comparison.  However you typically require specific\n// domain knowledge of expected precision or error in order to do better.  In\n// cases where you don't know or don't care particularly about the expected\n// precision, ULPs is typically the best default fall-back.\n//\n// Basic usage:\n//\n//   Step 1. (Optional but highly recommended.)\n//   Call bonelabMisc::SanityCheck() somewhere in your code.\n//\n//   Step 2.\n//   Compare floating point values (floats and/or doubles), like this:\n//\n//     if (bonelabMisc::EssentiallyEqual(x,y))\n//\n//   or\n//\n//     if (bonelabMisc::ApproximatelyEqual(x,y))\n//\n//  The former checks that two floating point numbers are within 1 ULP\n//  of each other, while the latter has a looser tolerance equal to\n//  APPROXIMATELY_EQUAL_ULPS .  I have set APPROXIMATELY_EQUAL_ULPS to 16,\n//  but you may tweak it if you want something else.\n//\n//  As an additional note, one should never use the == operator to compare\n//  a float with a double.  The comparsion mostly returns false because\n//  following the standard rules of C++, the float is promoted to a double\n//  before == is applied.  Thus, you are effectively trying to compare more\n//  digits than the number actually has.  The templated comparison functions\n//  here by contrast, will demote the double to float if passed both a float\n//  and a double.  This is what you want: a meaningful comparison can only be\n//  made with the precision of the least precise input. \n//\n//  This algorithm is a modified verion of the one from:\n//    http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm \n//\n//  Boost also has a floating-point comparison module.  It is more appropriate\n//  in cases where one can make an estimate for the uncertainty epsilon:\n//    http://www.boost.org/doc/libs/1_34_0/libs/test/doc/components/test_tools/floating_point_comparison.html\n//\n//  For even more information on floating point numbers, refer to\n//    http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.6768\n\n#include <boost/static_assert.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>  // for isnan\n#include <boost/cstdint.hpp>\n#include <limits>\n#include <cstdlib>\n\n// Uncomment this line to get very verbose reporting of comparison.\n//#define TRACE_ALMOSTEQUAL2SCOMPLEMENT\n\nnamespace bonelabMisc\n{\n\nusing boost::int64_t;\n\n// Change this value to\nconst int APPROXIMATELY_EQUAL_ULPS = 16;\n\n// Checks we can do at compile time.\n// Please ensure that you also call SanityCheck() in your code.\n//\n// Note: Hypothetically, one could write the functions below as macros\n//       which could then be called as static asserts, thus permitting\n//       the whole of SanityCheck to be implemented as static asserts.\n//       Then, since inline functions are much preferable to macros\n//       for the user, the functions would all wrap the corresponding macro.\n//       For now, this is too much work.\nBOOST_STATIC_ASSERT(sizeof(int) == sizeof(float));\nBOOST_STATIC_ASSERT(sizeof(int64_t) == sizeof(double));\n\n\n// Description:\n// Explicit reinterpretation of float as a 32 bit integer.\n// Key point: The value of the int is meaningless, but order is preserved.\ninline int FloatTwosComplementUlps (float x)\n{\n  int xInt = *(int*)&x;\n  // Make aInt lexicographically ordered as a twos-complement int\n  if (xInt < 0)\n    xInt = 0x80000000 - xInt;\n  return xInt;\n}\n\n// Description:\n// Explicit reinterpretation of double as a 64 bit integer\n// Key point: The value of the int is meaningless, but order is preserved.\ninline int64_t DoubleTwosComplementUlps (double x)\n{\n  int64_t xInt = *(int64_t*)&x;\n  // Make aInt lexicographically ordered as a twos-complement int\n  if (xInt < 0)\n    xInt = 0x8000000000000000 - xInt;\n  return xInt;\n}\n\n// Description:\n// Given a certain specified precision, return the corresponding number of ulps.\n// Note that the correspondence only holds approximately, and is wildly\n// inaccurate for denormalized numbers.\ninline int FloatUlpsFromPrecision (float p)\n{\n  float x = 1.0f;\n  int ulps = FloatTwosComplementUlps(x+p) - FloatTwosComplementUlps(x);\n  return ulps;\n}\n\n// Description:\n// Given a certain specified precision, return the corresponding number of ulps.\n// Note that the correspondence only holds approximately, and is wildly\n// inaccurate for denormalized numbers.\ninline int64_t DoubleUlpsFromPrecision (double p)\n{\n  double x = 1.0;\n  int64_t ulps = DoubleTwosComplementUlps(x+p) - DoubleTwosComplementUlps(x);\n  return ulps;\n}\n\n// Description:\n// Given the specified number of ulps, return the approximate corresponding\n// relative precision.\n// Note: Not valid for denormalized numbers.\ninline float PrecisionOfFloatUlps (int ulps=1)\n{\n  float x = 1.0f;\n  int xInt = FloatTwosComplementUlps(x);\n  int yInt = xInt + ulps;\n  float y = *(float*)&yInt;\n  return y-x;\n}\n\n// Description:\n// Given the specified number of ulps, return the approximate corresponding\n// relative precision.\n// Note: Not valid for denormalized numbers.\ninline double PrecisionOfDoubleUlps (int ulps=1)\n{\n  double x = 1.0f;\n  int64_t xInt = DoubleTwosComplementUlps(x);\n  int64_t yInt = xInt + ulps;\n  double y = *(double*)&yInt;\n  return y-x;\n}\n\n// Description:\n// Compare two floats and return true if they are within a certain number of\n// ULPS of each other.\ninline bool FloatAlmostEqual2sComplement (float a, float b, int maxUlps=1)\n{\n    int aInt = FloatTwosComplementUlps(a);\n    int bInt = FloatTwosComplementUlps(b);\n    int intDiff = std::abs(aInt - bInt);\n#ifdef TRACE_ALMOSTEQUAL2SCOMPLEMENT\n    cout << \"\\n\";\n    cout << std::dec << \"a = \" << a << \"\\n\";\n    cout << std::dec << \"b = \" << b << \"\\n\";\n    cout << std::dec << \"*(int*)&a = \" << *(int*)&a << \" \" << std::hex << *(int*)&a << \"\\n\";\n    cout << std::dec << \"*(int*)&b = \" << *(int*)&b << \" \" << std::hex << *(int*)&b << \"\\n\";\n    cout << std::dec << \"aInt = \" << aInt << \" \" << std::hex << aInt << \"\\n\";\n    cout << std::dec << \"bInt = \" << bInt << \" \" << std::hex << bInt << \"\\n\";\n    cout << std::dec << \"abs(aInt - BInt) = \" << intDiff << \" \" << std::hex << intDiff << \"\\n\";\n    cout << std::dec << \"maxUlps = \" << maxUlps << \"\\n\";\n#endif\n    // Note that the correct answer to NaN == NaN is false; hence the special case.\n    if (intDiff <= maxUlps && !(boost::math::isnan)(a))\n        return true;\n    return false;\n}\n\n// Description:\n// Compare two doubles and return true if they are within a certain number of\n// ULPS of each other.\ninline bool DoubleAlmostEqual2sComplement (double a, double b, int64_t maxUlps=1)\n{\n    int64_t aInt = DoubleTwosComplementUlps(a);\n    int64_t bInt = DoubleTwosComplementUlps(b);\n#ifdef WIN32\n    // 64 bit Windows has no abs function for 64 bit integers.\n    int64_t signedIntDiff = aInt - bInt;\n    int64_t intDiff = (signedIntDiff >= 0) ? signedIntDiff : -signedIntDiff;\n#else\n    int64_t intDiff = std::abs(aInt - bInt);\n#endif\n#ifdef TRACE_ALMOSTEQUAL2SCOMPLEMENT\n    cout << \"\\n\";\n    cout << std::dec << \"a = \" << a << \"\\n\";\n    cout << std::dec << \"b = \" << b << \"\\n\";\n    cout << std::dec << \"*(int64_t*)&a = \" << *(int64_t*)&a << \" \" << std::hex << *(int64_t*)&a << \"\\n\";\n    cout << std::dec << \"*(int64_t*)&b = \" << *(int64_t*)&b << \" \" << std::hex << *(int64_t*)&b << \"\\n\";\n    cout << std::dec << \"aInt = \" << aInt << \" \" << std::hex << aInt << \"\\n\";\n    cout << std::dec << \"bInt = \" << bInt << \" \" << std::hex << bInt << \"\\n\";\n    cout << std::dec << \"abs(aInt - BInt) = \" << intDiff << \" \" << std::hex << intDiff << \"\\n\";\n    cout << std::dec << \"maxUlps = \" << maxUlps << \"\\n\";\n#endif\n    // Note that the correct answer to NaN == NaN is false; hence the special case.\n    if (intDiff <= maxUlps && !(boost::math::isnan)(a))\n        return true;\n    return false;\n}\n\n// --------------------------------------------------------------------------\n// Templated versions of comparison functions\n//\n// Note: Comparison of mixed float and double will default to the float\n//       versions of the comparison functions.  This is generally sensible.\n\ntemplate <typename T1, typename T2> inline bool AlmostEqual2sComplement (T1 a, T2 b, int maxUlps=1);\n\ntemplate <> inline bool AlmostEqual2sComplement<float, float> (float a, float b, int maxUlps)\n{return FloatAlmostEqual2sComplement(a,b,maxUlps);}\n\ntemplate <> inline bool AlmostEqual2sComplement<double, double> (double a, double b, int maxUlps)\n{return DoubleAlmostEqual2sComplement(a,b,maxUlps);}\n\ntemplate <> inline bool AlmostEqual2sComplement<float, double> (float a, double b, int maxUlps)\n{return FloatAlmostEqual2sComplement(a,(float)b,maxUlps);}\n\ntemplate <> inline bool AlmostEqual2sComplement<double, float> (double a, float b, int maxUlps)\n{return FloatAlmostEqual2sComplement((float)a,b,maxUlps);}\n\n// Description:\n// Returns true if the arguments are within 1 ULP of each other.\ntemplate <typename T1, typename T2> inline bool EssentiallyEqual (T1 a, T2 b)\n{return AlmostEqual2sComplement<T1,T2>(a,b,1);}\n\n// Description:\n// Returns true if the arguments are within APPROXIMATELY_EQUAL_ULPS of each other.\ntemplate <typename T1, typename T2> inline bool ApproximatelyEqual (T1 a, T2 b)\n{return AlmostEqual2sComplement<T1,T2>(a,b,APPROXIMATELY_EQUAL_ULPS);}\n\n// Description:\n// Checks that the comparison functions work as expected.\n// I STRONGLY recommend that you call this somewhere in your code before using\n// and of the comparison functions.\nvoid SanityCheck ()\n{\n  // --------------------------------------------------------------------------\n  // Floats\n  \n  // Trival check\n  assert(!FloatAlmostEqual2sComplement(1.0f,-1.0f,256));\n  assert(!FloatAlmostEqual2sComplement(-1.0f,1.0f,256));\n\n  // Positive and Negative zero have different representations, but should\n  // compare as equal.\n  assert(FloatAlmostEqual2sComplement(0.0f,-0.0f));\n  assert(FloatAlmostEqual2sComplement(-0.0f,0.0f));\n\n  // Denormalized minimum value of float should equal 1 when reinterpreted\n  // as an int.\n  assert(FloatAlmostEqual2sComplement(0.0f,std::numeric_limits<float>::denorm_min()));\n  assert(FloatAlmostEqual2sComplement(std::numeric_limits<float>::denorm_min(),0.0f));\n  assert(FloatAlmostEqual2sComplement(-0.0f,std::numeric_limits<float>::denorm_min()));\n  assert(FloatAlmostEqual2sComplement(std::numeric_limits<float>::denorm_min(),-0.0f));\n  assert(FloatAlmostEqual2sComplement(0.0f,-std::numeric_limits<float>::denorm_min()));\n  assert(FloatAlmostEqual2sComplement(-std::numeric_limits<float>::denorm_min(),0.0f));\n  assert(FloatAlmostEqual2sComplement(-0.0f,-std::numeric_limits<float>::denorm_min()));\n  assert(FloatAlmostEqual2sComplement(-std::numeric_limits<float>::denorm_min(),-0.0f));\n\n  // Normalized minimum value of float should be a rather large number when\n  // reinterpreted as an int.\n  assert(!FloatAlmostEqual2sComplement(0.0f,std::numeric_limits<float>::min()));\n  assert(!FloatAlmostEqual2sComplement(std::numeric_limits<float>::min(),0.0f));\n  assert(!FloatAlmostEqual2sComplement(-0.0f,std::numeric_limits<float>::min()));\n  assert(!FloatAlmostEqual2sComplement(std::numeric_limits<float>::min(),-0.0f));\n  assert(!FloatAlmostEqual2sComplement(0.0f,-std::numeric_limits<float>::min()));\n  assert(!FloatAlmostEqual2sComplement(-std::numeric_limits<float>::min(),0.0f));\n  assert(!FloatAlmostEqual2sComplement(-0.0f,-std::numeric_limits<float>::min()));\n  assert(!FloatAlmostEqual2sComplement(-std::numeric_limits<float>::min(),-0.0f));\n\n  // Expected accuracies.\n  float lessThanFloatPrecision = PrecisionOfFloatUlps() / 3;\n  float moreThanFloatPrecision = PrecisionOfFloatUlps() * 2;\n  assert(FloatAlmostEqual2sComplement(1.0f,1.0f+lessThanFloatPrecision));\n  assert(FloatAlmostEqual2sComplement(1.0f+lessThanFloatPrecision,1.0f));\n  assert(!FloatAlmostEqual2sComplement(1.0f,1.0f+moreThanFloatPrecision));\n  assert(!FloatAlmostEqual2sComplement(1.0f+moreThanFloatPrecision,1.0f));\n  assert(FloatAlmostEqual2sComplement(-1.0f,-1.0f+lessThanFloatPrecision));\n  assert(FloatAlmostEqual2sComplement(-1.0f+lessThanFloatPrecision,-1.0f));\n  assert(!FloatAlmostEqual2sComplement(-1.0f,-1.0f+moreThanFloatPrecision));\n  assert(!FloatAlmostEqual2sComplement(-1.0f+moreThanFloatPrecision,-1.0f));\n\n  // --------------------------------------------------------------------------\n  // Doubles\n  \n  // Trival check\n  assert(!DoubleAlmostEqual2sComplement(1.0,-1.0,256));\n  assert(!DoubleAlmostEqual2sComplement(-1.0,1.0,256));\n\n  // Positive and Negative zero have different representations, but should\n  // compare as equal.\n  assert(DoubleAlmostEqual2sComplement(0.0,-0.0));\n  assert(DoubleAlmostEqual2sComplement(-0.0,0.0));\n\n  // Denormalized minimum value of double should equal 1 when reinterpreted\n  // as an int.\n  assert(DoubleAlmostEqual2sComplement(0.0,std::numeric_limits<double>::denorm_min()));\n  assert(DoubleAlmostEqual2sComplement(std::numeric_limits<double>::denorm_min(),0.0));\n  assert(DoubleAlmostEqual2sComplement(-0.0,std::numeric_limits<double>::denorm_min()));\n  assert(DoubleAlmostEqual2sComplement(std::numeric_limits<double>::denorm_min(),-0.0));\n  assert(DoubleAlmostEqual2sComplement(0.0,-std::numeric_limits<double>::denorm_min()));\n  assert(DoubleAlmostEqual2sComplement(-std::numeric_limits<double>::denorm_min(),0.0));\n  assert(DoubleAlmostEqual2sComplement(-0.0,-std::numeric_limits<double>::denorm_min()));\n  assert(DoubleAlmostEqual2sComplement(-std::numeric_limits<double>::denorm_min(),-0.0));\n\n  // Normalized minimum value of double should be a rather large number when\n  // reinterpreted as an int.\n  assert(!DoubleAlmostEqual2sComplement(0.0,std::numeric_limits<double>::min()));\n  assert(!DoubleAlmostEqual2sComplement(std::numeric_limits<double>::min(),0.0));\n  assert(!DoubleAlmostEqual2sComplement(-0.0,std::numeric_limits<double>::min()));\n  assert(!DoubleAlmostEqual2sComplement(std::numeric_limits<double>::min(),-0.0));\n  assert(!DoubleAlmostEqual2sComplement(0.0,-std::numeric_limits<double>::min()));\n  assert(!DoubleAlmostEqual2sComplement(-std::numeric_limits<double>::min(),0.0));\n  assert(!DoubleAlmostEqual2sComplement(-0.0,-std::numeric_limits<double>::min()));\n  assert(!DoubleAlmostEqual2sComplement(-std::numeric_limits<double>::min(),-0.0));\n\n  // Expected accuracies.\n  double lessThanDoublePrecision = PrecisionOfDoubleUlps() / 3;\n  double moreThanDoublePrecision = PrecisionOfDoubleUlps() * 2;\n  assert(DoubleAlmostEqual2sComplement(1.0,1.0+lessThanDoublePrecision));\n  assert(DoubleAlmostEqual2sComplement(1.0+lessThanDoublePrecision,1.0));\n  assert(!DoubleAlmostEqual2sComplement(1.0,1.0+moreThanDoublePrecision));\n  assert(!DoubleAlmostEqual2sComplement(1.0+moreThanDoublePrecision,1.0));\n  assert(DoubleAlmostEqual2sComplement(-1.0,-1.0+lessThanDoublePrecision));\n  assert(DoubleAlmostEqual2sComplement(-1.0+lessThanDoublePrecision,-1.0));\n  assert(!DoubleAlmostEqual2sComplement(-1.0,-1.0+moreThanDoublePrecision));\n  assert(!DoubleAlmostEqual2sComplement(-1.0+moreThanDoublePrecision,-1.0));\n\n  // -------------------------------------------------------------------------\n  // EssentiallyEqual and Mixed Floats and Doubles\n\n  // Mixes Zeros (positive and negative)\n  assert(EssentiallyEqual(0.0f,0.0));\n  assert(EssentiallyEqual(0.0,0.0f));\n  assert(EssentiallyEqual(-0.0f,0.0));\n  assert(EssentiallyEqual(0.0,-0.0f));\n  assert(EssentiallyEqual(0.0f,-0.0));\n  assert(EssentiallyEqual(-0.0,0.0f));\n  assert(EssentiallyEqual(-0.0f,-0.0));\n  assert(EssentiallyEqual(-0.0,-0.0f));\n\n  // Mixed Ones\n  assert(EssentiallyEqual(1.0f,1.0));\n  assert(EssentiallyEqual(1.0,1.0f));\n  assert(EssentiallyEqual(-1.0f,-1.0));\n  assert(EssentiallyEqual(-1.0,-1.0f));\n\n  // Expected accuracies should be the same as float, not double\n  assert(EssentiallyEqual(1.0f,1.0+lessThanFloatPrecision));\n  assert(EssentiallyEqual(1.0+lessThanFloatPrecision,1.0f));\n  assert(!EssentiallyEqual(1.0f,1.0+moreThanFloatPrecision));\n  assert(!EssentiallyEqual(1.0+moreThanFloatPrecision,1.0f));\n\n  // Finally verify that EssentiallyEqual does give us double accuracies\n  // for pure double inputs.\n  assert(!EssentiallyEqual(1.0,1.0+moreThanDoublePrecision));\n  assert(!EssentiallyEqual(1.0+moreThanDoublePrecision,1.0));\n\n  // -------------------------------------------------------------------------\n  // ApproximatelyEqual\n\n  // Float - More tolerant than EssentiallyEqual\n  assert(ApproximatelyEqual(1.0f,1.0f+moreThanFloatPrecision));\n  assert(ApproximatelyEqual(1.0f+moreThanFloatPrecision,1.0f));\n\n  // Float - Outside specified ULP range for ApproximatelyEqual\n  assert(!ApproximatelyEqual(1.0f,1.0f+APPROXIMATELY_EQUAL_ULPS*moreThanFloatPrecision));\n  assert(!ApproximatelyEqual(1.0f+APPROXIMATELY_EQUAL_ULPS*moreThanFloatPrecision,1.0f));\n\n  // Double - More tolerant than EssentiallyEqual\n  assert(ApproximatelyEqual(1.0,1.0+moreThanDoublePrecision));\n  assert(ApproximatelyEqual(1.0+moreThanDoublePrecision,1.0));\n\n  // Double - Outside specified ULP range for ApproximatelyEqual\n  assert(!ApproximatelyEqual(1.0,1.0+APPROXIMATELY_EQUAL_ULPS*moreThanDoublePrecision));\n  assert(!ApproximatelyEqual(1.0+APPROXIMATELY_EQUAL_ULPS*moreThanDoublePrecision,1.0));\n\n  // -------------------------------------------------------------------------\n  // Infinities and NaNs\n\n  // Float infinities\n  if (std::numeric_limits<float>::has_infinity)\n    {\n    assert(!FloatAlmostEqual2sComplement(0.0f,std::numeric_limits<float>::infinity()));\n    assert(!FloatAlmostEqual2sComplement(std::numeric_limits<float>::infinity(), 0.0f));\n    assert(!FloatAlmostEqual2sComplement(0.0f,-std::numeric_limits<float>::infinity()));\n    assert(!FloatAlmostEqual2sComplement(-std::numeric_limits<float>::infinity(), 0.0f));\n    assert(!FloatAlmostEqual2sComplement(std::numeric_limits<float>::infinity(),-std::numeric_limits<float>::infinity()));\n    assert(!FloatAlmostEqual2sComplement(-std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()));\n    assert(FloatAlmostEqual2sComplement(std::numeric_limits<float>::infinity(),std::numeric_limits<float>::infinity()));\n    assert(FloatAlmostEqual2sComplement(-std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity()));\n    }\n\n  // Double infinities\n  if (std::numeric_limits<double>::has_infinity)\n    {\n    assert(!DoubleAlmostEqual2sComplement(0.0,std::numeric_limits<double>::infinity()));\n    assert(!DoubleAlmostEqual2sComplement(std::numeric_limits<double>::infinity(), 0.0));\n    assert(!DoubleAlmostEqual2sComplement(0.0,-std::numeric_limits<double>::infinity()));\n    assert(!DoubleAlmostEqual2sComplement(-std::numeric_limits<double>::infinity(), 0.0));\n    assert(!DoubleAlmostEqual2sComplement(std::numeric_limits<double>::infinity(),-std::numeric_limits<double>::infinity()));\n    assert(!DoubleAlmostEqual2sComplement(-std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity()));\n    assert(DoubleAlmostEqual2sComplement(std::numeric_limits<double>::infinity(),std::numeric_limits<double>::infinity()));\n    assert(DoubleAlmostEqual2sComplement(-std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity()));\n    }\n\n  // float NaNs\n  if (std::numeric_limits<float>::has_quiet_NaN)\n    {\n    assert(!FloatAlmostEqual2sComplement(0.0f,std::numeric_limits<float>::quiet_NaN()));\n    assert(!FloatAlmostEqual2sComplement(std::numeric_limits<float>::quiet_NaN(),0.0f));\n    assert(!FloatAlmostEqual2sComplement(1.0f,std::numeric_limits<float>::quiet_NaN()));\n    assert(!FloatAlmostEqual2sComplement(std::numeric_limits<float>::quiet_NaN(),1.0f));\n    assert(!FloatAlmostEqual2sComplement(std::numeric_limits<float>::infinity(),std::numeric_limits<float>::quiet_NaN()));\n    assert(!FloatAlmostEqual2sComplement(std::numeric_limits<float>::quiet_NaN(),std::numeric_limits<float>::infinity()));\n    assert(!FloatAlmostEqual2sComplement(-std::numeric_limits<float>::infinity(),std::numeric_limits<float>::quiet_NaN()));\n    assert(!FloatAlmostEqual2sComplement(std::numeric_limits<float>::quiet_NaN(),-std::numeric_limits<float>::infinity()));\n    // Note that according to the standard the correct answer to NaN == NaN is false\n    assert(!FloatAlmostEqual2sComplement(std::numeric_limits<float>::quiet_NaN(),std::numeric_limits<float>::quiet_NaN()));\n    }\n\n  // Double NaNs\n  if (std::numeric_limits<double>::has_quiet_NaN)\n    {\n    assert(!DoubleAlmostEqual2sComplement(0.0,std::numeric_limits<double>::quiet_NaN()));\n    assert(!DoubleAlmostEqual2sComplement(std::numeric_limits<double>::quiet_NaN(),0.0));\n    assert(!DoubleAlmostEqual2sComplement(1.0,std::numeric_limits<double>::quiet_NaN()));\n    assert(!DoubleAlmostEqual2sComplement(std::numeric_limits<double>::quiet_NaN(),1.0));\n    assert(!DoubleAlmostEqual2sComplement(std::numeric_limits<double>::infinity(),std::numeric_limits<double>::quiet_NaN()));\n    assert(!DoubleAlmostEqual2sComplement(std::numeric_limits<double>::quiet_NaN(),std::numeric_limits<double>::infinity()));\n    assert(!DoubleAlmostEqual2sComplement(-std::numeric_limits<double>::infinity(),std::numeric_limits<double>::quiet_NaN()));\n    assert(!DoubleAlmostEqual2sComplement(std::numeric_limits<double>::quiet_NaN(),-std::numeric_limits<double>::infinity()));\n    // Note that according to the standard the correct answer to NaN == NaN is false\n    assert(!DoubleAlmostEqual2sComplement(std::numeric_limits<double>::quiet_NaN(),std::numeric_limits<double>::quiet_NaN()));\n    }\n\n}\n\n}  // namespace\n", "meta": {"hexsha": "ffd210dcb7a0eb77b6e61f2de9ff02922e4c6ebc", "size": 21911, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/n88util/floating_point_comparisons.hpp", "max_stars_repo_name": "Numerics88/n88util", "max_stars_repo_head_hexsha": "b5362590a3d9b96ff16ecb9a9b60f260272b00b9", "max_stars_repo_licenses": ["MIT"], "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/n88util/floating_point_comparisons.hpp", "max_issues_repo_name": "Numerics88/n88util", "max_issues_repo_head_hexsha": "b5362590a3d9b96ff16ecb9a9b60f260272b00b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-11-05T17:24:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-20T21:01:47.000Z", "max_forks_repo_path": "include/n88util/floating_point_comparisons.hpp", "max_forks_repo_name": "Besler/n88util", "max_forks_repo_head_hexsha": "aa15d4f80f1b69142a48db34b055142f867aef7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-05-31T19:09:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-31T19:09:12.000Z", "avg_line_length": 48.3686534216, "max_line_length": 126, "alphanum_fraction": 0.7162612386, "num_tokens": 5838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6048614473969275}}
{"text": "// Created by Siddhant Gangapurwala\n\n#ifndef ACTIVATION_HPP\n#define ACTIVATION_HPP\n\n#include <Eigen/Dense>\n\n\nclass Activation {\npublic:\n    virtual Eigen::MatrixXd forward(const Eigen::MatrixXd &input);\n\n    virtual Eigen::MatrixXd gradient(const Eigen::MatrixXd &input);\n};\n\nclass ReLU : public Activation {\npublic:\n    Eigen::MatrixXd forward(const Eigen::MatrixXd &input) override;\n\n    Eigen::MatrixXd gradient(const Eigen::MatrixXd &input) override;\n};\n\nclass TanH : public Activation {\npublic:\n    Eigen::MatrixXd forward(const Eigen::MatrixXd &input) override;\n\n    Eigen::MatrixXd gradient(const Eigen::MatrixXd &input) override;\n};\n\nclass SoftSign : public Activation {\npublic:\n    Eigen::MatrixXd forward(const Eigen::MatrixXd &input) override;\n\n    Eigen::MatrixXd gradient(const Eigen::MatrixXd &input) override;\n};\n\nclass Sigmoid : public Activation {\npublic:\n    Eigen::MatrixXd forward(const Eigen::MatrixXd &input) override;\n\n    Eigen::MatrixXd gradient(const Eigen::MatrixXd &input) override;\n};\n\nclass LeakyReLU : public Activation {\npublic:\n    Eigen::MatrixXd forward(const Eigen::MatrixXd &input) override;\n\n    Eigen::MatrixXd gradient(const Eigen::MatrixXd &input) override;\n};\n\nextern struct ActivationHandler {\n    ReLU relu;\n    TanH tanh;\n    SoftSign softsign;\n    Sigmoid sigmoid;\n    LeakyReLU leakyReLu;\n} activation;\n\n#endif // ACTIVATION_HPP\n", "meta": {"hexsha": "d2ceebf44558a689783798d532e0b149048aad19", "size": 1376, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/networks_minimal/Activation.hpp", "max_stars_repo_name": "gsiddhant/networks_minimal", "max_stars_repo_head_hexsha": "8ba510464f2743f962213d7cfc1c6bf25dbb569a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-01T02:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T12:22:58.000Z", "max_issues_repo_path": "include/networks_minimal/Activation.hpp", "max_issues_repo_name": "gsiddhant/networks_minimal", "max_issues_repo_head_hexsha": "8ba510464f2743f962213d7cfc1c6bf25dbb569a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/networks_minimal/Activation.hpp", "max_forks_repo_name": "gsiddhant/networks_minimal", "max_forks_repo_head_hexsha": "8ba510464f2743f962213d7cfc1c6bf25dbb569a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-01-28T11:59:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T21:00:56.000Z", "avg_line_length": 22.9333333333, "max_line_length": 68, "alphanum_fraction": 0.7354651163, "num_tokens": 298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867681382279, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6048614444871111}}
{"text": "// dot.cpp: example program contrasting a BLAS L1 dot routine between FLOAT and POSIT\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 <ratio>\n#include <chrono>\n#include <iostream>\n#include <ctime>\n\n////////////////////////////////////////////////////////////////////////////////////////\n///  BEHAVIORAL COMPILATION SWITCHES for posit library configuration\n\n////////////////////////////////////////////////////////////////////////////////////////\n// enable/disable special posit format I/O\n// POSIT_ROUNDING_ERROR_FREE_IO_FORMAT\n// default is to print (long double) values\n// #define POSIT_ROUNDING_ERROR_FREE_IO_FORMAT 0\n\n////////////////////////////////////////////////////////////////////////////////////////\n// enable/disable the ability to use literals in binary logic and arithmetic operators\n// POSIT_ENABLE_LITERALS)\n// default is to enable them\n// #define POSIT_ENABLE_LITERALS 1\n\n////////////////////////////////////////////////////////////////////////////////////////\n// enable throwing specific exceptions for posit arithmetic errors\n// left to application to enable\n// POSIT_THROW_ARITHMETIC_EXCEPTION\n// default is to use NaR as a signalling error\n// #define POSIT_THROW_ARITHMETIC_EXCEPTION 0\n\n////////////////////////////////////////////////////////////////////////////////////////\n/// INCLUDE FILES posit library\n#include <universal/number/posit/posit.hpp>\n\n///////////////////////////////////////////////////////////////////////////////////////\n/// useful mathematical property functions\n//#include <universal/functions/functions.hpp>\n\n///////////////////////////////////////////////////////////////////////////////////////\n/// the underlying matrix/vector machinery\n#ifndef MTL_WITH_INITLIST\n#define MTL_WITH_INITLIST\n#endif\n#include <boost/numeric/mtl/mtl.hpp>\n\n///////////////////////////////////////////////////////////////////////////////////////\n/// the High-Performance Reproducible Basic Linear Algebra Subroutines\n/// L1, L2, and L3 matrix/vector operations\n#include <hprblas.hpp>\n/// norms (l1, l2, linf, Frobenius) using HPR methods\n//#include <norms.hpp>\n\n#include <utils/matvec.hpp>\n\nusing namespace sw::universal;\n\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace sw::hprblas;\n\t// configure the posit environment\n\tconst size_t nbits = 32;\n\tconst size_t es = 2;\n\tconst size_t vecSize = 1024;\n\n\tint nrOfFailedTestCases = 0;\n\t// steady_clock example\n\tusing namespace std::chrono;\n\n\tcout << \"DOT product examples\" << endl;\n\tvector<float> x(vecSize), y(vecSize);\n\tfloat fresult;\n\n\n\trandomVectorFillAroundOneEPS(vecSize, x);  //\tsampleVector(\"x\", x);\n\trandomVectorFillAroundOneEPS(vecSize, y);  // \tsampleVector(\"y\", y);\n\tfresult = sw::hprblas::dot(vecSize, x, 1, y, 1);\n\tcout << \"DOT product is \" << setprecision(20) << fresult << endl;\n#ifdef LATER\n\tusing Posit = sw::universal::posit<nbits, es>;\n\tvector<Posit> px(vecSize), py(vecSize);\n\tPosit presult;\n\trandomVectorFillAroundOneEPS(vecSize, px);  //\tsampleVector(\"px\", px);\n\trandomVectorFillAroundOneEPS(vecSize, py);  // \tsampleVector(\"py\", py);\n\n\tsteady_clock::time_point t1 = steady_clock::now();\n\tpresult = sw::hprblas::dot(vecSize, px, 1, py, 1);\n\tsteady_clock::time_point t2 = steady_clock::now();\n\tdouble ops = vecSize * 2.0; // dot product is vecSize products and vecSize adds\n\tcout << \"DOT product is \" << setprecision(20) << presult << endl;\n\t//sampleVector(\"px\", px);  // <-- currently shows bad conversions....\n\n\tduration<double> time_span = duration_cast<duration<double>>(t2 - t1);\n\tdouble elapsed = time_span.count();\n\tstd::cout << \"It took \" << elapsed << \" seconds.\" << std::endl;\n\tstd::cout << \"Performance \" << (uint32_t) (ops / (1000*elapsed)) << \" KOPS\" << std::endl;\n\tstd::cout << std::endl;\n#endif\n\treturn (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (std::runtime_error& err) {\n\tstd::cerr << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"Caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}\n", "meta": {"hexsha": "6429699aa5af80eaf1795177db015f3f315247d2", "size": 4628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "blas/L1/dot.cpp", "max_stars_repo_name": "stillwater-sc/hpr-blas", "max_stars_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-13T10:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T20:30:58.000Z", "max_issues_repo_path": "blas/L1/dot.cpp", "max_issues_repo_name": "stillwater-sc/hpr-blas", "max_issues_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T11:19:32.000Z", "max_forks_repo_path": "blas/L1/dot.cpp", "max_forks_repo_name": "stillwater-sc/hpr-blas", "max_forks_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:35:35.000Z", "avg_line_length": 36.15625, "max_line_length": 97, "alphanum_fraction": 0.6097666379, "num_tokens": 1070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6048614401210458}}
{"text": "//\n// Created by xiang on 12/21/17.\n//\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\n#include <vector>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n\n#include \"sophus/se3.h\"\n\nusing namespace std;\n\ntypedef vector<Vector3d, Eigen::aligned_allocator<Vector3d>> VecVector3d;\ntypedef vector<Vector2d, Eigen::aligned_allocator<Vector3d>> VecVector2d;\ntypedef Matrix<double, 6, 1> 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\n    // END YOUR CODE HERE\n    assert(p3d.size() == p2d.size());\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; // estimated pose\n\n    for (int iter = 0; iter < iterations; iter++) {\n\n        Matrix<double, 6, 6> H = Matrix<double, 6, 6>::Zero();\n        Vector6d b = Vector6d::Zero();\n\n        cost = 0;\n        // compute cost\n        for (int i = 0; i < nPoints; i++) {\n            // compute cost for p3d[I] and p2d[I]\n            // START YOUR CODE HERE \n\n\t    // END YOUR CODE HERE\n\n\t    // compute jacobian\n            Matrix<double, 2, 6> J;\n            // START YOUR CODE HERE \n\n\t    // END YOUR CODE HERE\n\n            H += J.transpose() * J;\n            b += -J.transpose() * e;\n        }\n\n\t// solve dx \n        Vector6d dx;\n\n        // START YOUR CODE HERE \n\n        // END YOUR CODE HERE\n\n        if (isnan(dx[0])) {\n            cout << \"result is nan!\" << endl;\n            break;\n        }\n\n        if (iter > 0 && cost >= lastCost) {\n            // 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\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": "1f0acd229b80d20f9451d3e162b2982dfcc8e797", "size": 2267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "5.Visual_Odometry/GN-BA.cpp", "max_stars_repo_name": "weihang-li/Visual-SLAM-Notes", "max_stars_repo_head_hexsha": "62b9c9f30b709c202cc00d16dbcff3538cfa0fb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-01T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-01T03:14:27.000Z", "max_issues_repo_path": "PA5/code/GN-BA.cpp", "max_issues_repo_name": "HCH2CHO/Visual_SLAM", "max_issues_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PA5/code/GN-BA.cpp", "max_forks_repo_name": "HCH2CHO/Visual_SLAM", "max_forks_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_forks_repo_licenses": ["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.4455445545, "max_line_length": 87, "alphanum_fraction": 0.5341861491, "num_tokens": 661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6048614386647965}}
{"text": "#include <blitz/array.h>\n#include <blitz/array/convolve.h>\n\nusing namespace blitz;\n\nint main()\n{\n    Array<float,1> B(Range(-2,+2));\n    Array<float,1> C(Range(10,15));\n\n    B = 1, 0, 2, 5, 3;\n    C = 10, 2, 4, 1, 7, 2;\n\n    Array<float,1> A = convolve(B,C);\n\n    cout << \"A has domain \" << A.lbound(0) << \"...\" << A.ubound(0) << endl\n         << A << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "fdcb1e49e9b06a2399319a3d15f0e34dfb176c5b", "size": 376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/examples/convolve.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/convolve.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/convolve.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": 17.0909090909, "max_line_length": 74, "alphanum_fraction": 0.5106382979, "num_tokens": 146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8104789086703224, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6047299213631098}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <scitbx/matrix/row_echelon.h>\n#include <scitbx/matrix/row_echelon_full_pivoting.h>\n#include <scitbx/array_family/versa.h>\n#include <boost/python/class.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/return_value_policy.hpp>\n#include <boost/python/return_by_value.hpp>\n\nnamespace scitbx { namespace matrix { namespace boost_python {\n\nnamespace {\n\n  template <typename ElementType>\n  af::ref<ElementType, af::mat_grid>\n  flex_as_mat_ref(af::versa<ElementType, af::flex_grid<> >& a)\n  {\n    SCITBX_ASSERT(a.accessor().nd() == 2);\n    SCITBX_ASSERT(a.accessor().is_0_based());\n    SCITBX_ASSERT(!a.accessor().is_padded());\n    return af::ref<ElementType, af::mat_grid>(\n      a.begin(),\n      a.accessor().all()[0],\n      a.accessor().all()[1]);\n  }\n\n  std::size_t\n  row_echelon_form_t(\n    af::versa<int, af::flex_grid<> >& m,\n    af::versa<int, af::flex_grid<> >& t)\n  {\n    af::ref<int, af::mat_grid> m_ref = flex_as_mat_ref(m);\n    af::ref<int, af::mat_grid> t_ref = flex_as_mat_ref(t);\n    std::size_t rank = row_echelon::form_t(m_ref, t_ref);\n    m.resize(af::flex_grid<>(m_ref.n_rows(), m_ref.n_columns()));\n    return rank;\n  }\n\n  std::size_t\n  row_echelon_form(\n    af::versa<int, af::flex_grid<> >& m)\n  {\n    af::ref<int, af::mat_grid> m_ref = flex_as_mat_ref(m);\n    std::size_t rank = row_echelon::form(m_ref);\n    m.resize(af::flex_grid<>(m_ref.n_rows(), m_ref.n_columns()));\n    return rank;\n  }\n\n  int\n  row_echelon_back_substitution_int(\n    af::versa<int, af::flex_grid<> >& re_mx,\n    af::const_ref<int> const& v,\n    af::ref<int> const& sol,\n    af::ref<bool> const& indep)\n  {\n    af::ref<int, af::mat_grid> re_mx_ref = flex_as_mat_ref(re_mx);\n    const int* v_ptr = 0;\n    int* sol_ptr = 0;\n    bool* indep_ptr = 0;\n    if (v.size()) {\n      SCITBX_ASSERT(v.size() == re_mx_ref.n_rows());\n      v_ptr = v.begin();\n    }\n    if (sol.size()) {\n      SCITBX_ASSERT(sol.size() == re_mx_ref.n_columns());\n      sol_ptr = sol.begin();\n    }\n    if (indep.size()) {\n      SCITBX_ASSERT(indep.size() == re_mx_ref.n_columns());\n      indep_ptr = indep.begin();\n    }\n    return row_echelon::back_substitution_int(\n      re_mx_ref, v_ptr, sol_ptr, indep_ptr);\n  }\n\n  bool\n  row_echelon_back_substitution_float(\n    af::versa<int, af::flex_grid<> >& re_mx,\n    af::const_ref<double> const& v,\n    af::ref<double> const& sol)\n  {\n    af::ref<int, af::mat_grid> re_mx_ref = flex_as_mat_ref(re_mx);\n    const double* v_ptr = 0;\n    double* sol_ptr = 0;\n    if (v.size()) {\n      SCITBX_ASSERT(v.size() == re_mx_ref.n_rows());\n      v_ptr = v.begin();\n    }\n    if (sol.size()) {\n      SCITBX_ASSERT(sol.size() == re_mx_ref.n_columns());\n      sol_ptr = sol.begin();\n    }\n    return row_echelon::back_substitution_float(\n      re_mx_ref, v_ptr, sol_ptr);\n  }\n\n  void wrap_row_echelon()\n  {\n    using namespace boost::python;\n    def(\"row_echelon_form_t\", row_echelon_form_t);\n    def(\"row_echelon_form\", row_echelon_form);\n    def(\"row_echelon_back_substitution_int\",\n      row_echelon_back_substitution_int);\n    def(\"row_echelon_back_substitution_float\",\n      row_echelon_back_substitution_float);\n  }\n\n  struct full_pivoting_wrapper\n  {\n    typedef row_echelon::full_pivoting<double> wt;\n\n    static void wrap()\n    {\n      using namespace boost::python;\n      typedef return_value_policy<return_by_value> rbv;\n      class_<wt>(\"row_echelon_full_pivoting\", no_init)\n        .def(init<\n          af::versa<double, af::flex_grid<> >,\n          double const&,\n          int>((\n            arg(\"a_work\"),\n            arg(\"min_abs_pivot\")=0,\n            arg(\"max_rank\")=-1)))\n        .def(init<\n          af::versa<double, af::flex_grid<> >,\n          af::shared<double>,\n          double const&,\n          int>((\n            arg(\"a_work\"),\n            arg(\"b_work\"),\n            arg(\"min_abs_pivot\")=0,\n            arg(\"max_rank\")=-1)))\n        .add_property(\"col_perm\", make_getter(&wt::col_perm, rbv()))\n        .def_readonly(\"rank\", &wt::rank)\n        .def_readonly(\"nullity\", &wt::nullity)\n        .def(\"is_in_row_space\", &wt::is_in_row_space, (\n          arg(\"x\"),\n          arg(\"epsilon\")))\n        .def(\"back_substitution\", &wt::back_substitution, (\n          arg(\"free_values\"),\n          arg(\"epsilon\")=0))\n      ;\n    }\n  };\n\n}}} // namespace matrix::boost_python::<anonymous>\n\nnamespace math { namespace boost_python {\n\n  void wrap_row_echelon()\n  {\n    matrix::boost_python::wrap_row_echelon();\n    matrix::boost_python::full_pivoting_wrapper::wrap();\n  }\n\n}}} // namespace scitbx::math::boost_python\n", "meta": {"hexsha": "86018100e044b7c504b8aa84dd61a2388df0dc6f", "size": 4594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scitbx/math/boost_python/row_echelon.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "scitbx/math/boost_python/row_echelon.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "scitbx/math/boost_python/row_echelon.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 29.0759493671, "max_line_length": 68, "alphanum_fraction": 0.6225511537, "num_tokens": 1334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.7461389817407017, "lm_q1q2_score": 0.6047299213000551}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstdio>\n#include <limits>\n\n#include <harp_test.hpp>\n\n#include <boost/random.hpp>\n\nusing namespace std;\nusing namespace harp;\n\n\nvoid harp::test_linalg ( string const & datadir ) {\n\n  cout << \"Testing ublas LAPACK bindings...\" << endl;\n\n  // matrix-vector multiply\n\n  size_t dim = 100;\n\n  matrix_double mat ( dim, dim );\n  vector_double input ( dim );\n  vector_double output ( dim );\n  vector_double check ( dim );\n\n  typedef boost::ecuyer1988 base_generator_type;\n  base_generator_type generator(42u);\n\n  boost::uniform_real < double > dist ( -100.0, 100.0 );\n  boost::variate_generator < base_generator_type&, boost::uniform_real < double > > uni ( generator, dist );\n\n  for ( size_t i = 0; i < dim; ++i ) {\n    input[i] = 10.0;\n    for ( size_t j = 0; j < dim; ++j ) {\n      mat( j, i ) = uni();\n    }\n  }\n\n  check.clear();\n\n  for ( size_t i = 0; i < dim; ++i ) {\n    for ( size_t j = 0; j < dim; ++j ) {\n      check[i] += mat( i, j ) * input[j];\n    }\n  }\n\n  boost::numeric::bindings::blas::gemv ( 1.0, mat, input, 0.0, output );\n\n  for ( size_t i = 0; i < dim; ++i ) {\n    if ( fabs ( ( output[i] - check[i] ) / check[i] ) > std::numeric_limits < float > :: epsilon() ) {\n      cerr << \"FAIL:  blas::gemv output element \" << i << \" is wrong (\" << output[i]\n << \" != \" << check[i] << \")\" << endl;\n      exit(1);\n    }\n  }\n  \n  cout << \"  (PASSED)\" << endl;\n\n  cout << \"Testing eigen-decomposition...\" << endl;\n\n  // construct random matrices\n\n  double rngmax = 1000.0;\n\n  matrix_double a1 ( dim, dim );\n  matrix_double a2 ( dim, dim );\n\n  typedef boost::ecuyer1988 base_generator_type;\n  typedef boost::uniform_01<> distribution_type;\n  typedef boost::variate_generator < base_generator_type&, distribution_type > gen_type;\n\n  gen_type gen ( generator, distribution_type() );\n\n  for ( size_t i = 0; i < dim; ++i ) {\n    for ( size_t j = 0; j < dim; ++j ) {\n      a1 ( i, j ) = rngmax * gen();\n      a2 ( i, j ) = rngmax * gen();\n    }\n  }\n\n  // construct symmetric test matrix\n\n  matrix_double sym ( dim, dim );\n\n  boost::numeric::bindings::blas::gemm ( 1.0, boost::numeric::bindings::trans ( a1 ), a1, 0.0, sym );\n  boost::numeric::bindings::blas::gemm ( 1.0, boost::numeric::bindings::trans ( a2 ), a2, 1.0, sym );\n\n  // get eigenvectors and eigenvalues\n\n  vector_double w;\n  matrix_double Z;\n\n  eigen_decompose ( sym, w, Z, false );\n\n  matrix_double symprod ( dim, dim );\n  matrix_double eprod ( dim, dim );\n  matrix_double wdiag ( dim, dim );\n\n  wdiag.clear();\n\n  for ( size_t i = 0; i < dim; ++i ) {\n    wdiag ( i, i ) = w[i];\n  }\n\n  boost::numeric::bindings::blas::gemm ( 1.0, sym, Z, 0.0, symprod );\n  boost::numeric::bindings::blas::gemm ( 1.0, Z, wdiag, 0.0, eprod );\n\n  double relerr;\n  double eval, sval;\n\n  for ( size_t i = 0; i < dim; ++i ) {\n    for ( size_t j = 0; j < dim; ++j ) {\n      eval = eprod ( j, i );\n      sval = symprod ( j, i );\n      relerr = fabs ( ( eval - sval ) / sval );\n      if ( relerr > std::numeric_limits < float > :: epsilon() ) {\n        cerr << \"FAIL on matrix element (\" << j << \", \" << i << \") Av = \" << sval << \", ev = \" << eval << \" rel err = \" << relerr << endl;\n        exit(1);\n      }\n    }\n  }\n\n  cout << \"  (PASSED)\" << endl;\n\n  cout << \"Testing re-composition...\" << endl;\n\n  matrix_double outcomp;\n\n  eigen_compose ( EIG_NONE, w, Z, outcomp );\n\n  double inval;\n  double outval;\n\n  for ( size_t i = 0; i < dim; ++i ) {\n    for ( size_t j = 0; j < dim; ++j ) {\n      inval = sym ( j, i );\n      outval = outcomp ( j, i );\n      relerr = fabs ( ( outval - inval ) / inval );\n      if ( relerr > std::numeric_limits < float > :: epsilon() ) {\n        cerr << \"FAIL on matrix element (\" << j << \", \" << i << \") input = \" << inval << \", output = \" << outval << \" rel err = \" << relerr << endl;\n        exit(1);\n      }\n    }\n  }\n\n  matrix_double mat_rt;\n  eigen_compose ( EIG_SQRT, w, Z, mat_rt );\n\n  matrix_double mat_invrt;\n  eigen_compose ( EIG_INVSQRT, w, Z, mat_invrt );\n  \n  vector_double w_inv;\n  matrix_double Z_inv;\n\n  eigen_decompose ( mat_invrt, w_inv, Z_inv, false );\n\n  for ( size_t i = 0; i < dim; ++i ) {\n    w_inv[i] *= w_inv[i];\n  }\n\n  matrix_double comp_rt;\n\n  eigen_compose ( EIG_INVSQRT, w_inv, Z_inv, comp_rt );\n\n  for ( size_t i = 0; i < dim; ++i ) {\n    for ( size_t j = 0; j < dim; ++j ) {\n      inval = mat_rt ( j, i );\n      outval = comp_rt ( j, i );\n      relerr = fabs ( ( outval - inval ) / inval );\n      if ( relerr > std::numeric_limits < float > :: epsilon() ) {\n        cerr << \"FAIL on doubly inverted sqrt matrix element (\" << j << \", \" << i << \") original = \" << inval << \", output = \" << outval << \" rel err = \" << relerr << endl;\n        exit(1);\n      }\n    }\n  }\n\n  cout << \"  (PASSED)\" << endl;\n\n  return;\n}\n\n\n\n", "meta": {"hexsha": "6bf090fee9c7cc576fc782ddf47255d319580acc", "size": 4773, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests/harp_test_linalg.cpp", "max_stars_repo_name": "tskisner/HARP", "max_stars_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/harp_test_linalg.cpp", "max_issues_repo_name": "tskisner/HARP", "max_issues_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/harp_test_linalg.cpp", "max_forks_repo_name": "tskisner/HARP", "max_forks_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6612903226, "max_line_length": 172, "alphanum_fraction": 0.5526922271, "num_tokens": 1519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.6046688822887504}}
{"text": "// Copyright Nick Thompson, 2020\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <unordered_map>\n#include <string>\n#include <future>\n#include <thread>\n#include <fstream>\n#include <boost/hana/for_each.hpp>\n#include <boost/hana/ext/std/integer_sequence.hpp>\n#include <boost/math/special_functions/daubechies_scaling.hpp>\n#include <boost/math/special_functions/detail/daubechies_scaling_integer_grid.hpp>\n#include <boost/math/interpolators/cubic_hermite.hpp>\n#include <boost/math/interpolators/quintic_hermite.hpp>\n#include <boost/math/interpolators/quintic_hermite.hpp>\n#include <boost/math/interpolators/septic_hermite.hpp>\n#include <boost/math/interpolators/cardinal_quadratic_b_spline.hpp>\n#include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>\n#include <boost/math/interpolators/cardinal_quintic_b_spline.hpp>\n#include <boost/math/interpolators/whittaker_shannon.hpp>\n#include <boost/math/interpolators/cardinal_trigonometric.hpp>\n#include <boost/math/special_functions/next.hpp>\n#include <boost/math/interpolators/makima.hpp>\n#include <boost/math/interpolators/pchip.hpp>\n#include <boost/multiprecision/float128.hpp>\n#include <boost/core/demangle.hpp>\n\nusing boost::multiprecision::float128;\n\n\ntemplate<typename Real, typename PreciseReal, int p>\nvoid choose_refinement()\n{\n    std::cout << \"Choosing refinement for \" << boost::core::demangle(typeid(Real).name()) << \" precision Daubechies scaling function with \" << p << \" vanishing moments.\\n\";\n    using std::abs;\n    int rmax = 22;\n    auto phi_dense = boost::math::daubechies_scaling_dyadic_grid<PreciseReal, p, 0>(rmax);\n    Real dx_dense = (2*p-1)/static_cast<Real>(phi_dense.size()-1);\n\n    for (int r = 2; r <= 18; ++r)\n    {\n        Real dx = Real(1)/ (1 << r);\n        std::cout << \"\\tdx = 1/\" << (1/dx) << \" = 1/2^\" << r << \" = \" << dx << \"\\n\";\n        auto phi = boost::math::daubechies_scaling<Real, p>(r);\n        Real max_flt_distance = 0;\n        Real sup  = 0;\n        Real rel_sup = 0;\n        Real worst_flt_abscissa = 0;\n        Real worst_flt_value = 0;\n        Real worst_flt_computed = 0;\n\n        Real worst_rel_abscissa = 0;\n        Real worst_rel_value = 0;\n        Real worst_rel_computed = 0;\n\n        Real worst_abs_abscissa = 0;\n        Real worst_abs_computed = 0;\n        Real worst_abs_expected = 0;\n        for (size_t i = 0; i < phi_dense.size(); ++i)\n        {\n            Real t = i*dx_dense;\n            Real computed = phi(t);\n            Real expected = Real(phi_dense[i]);\n            Real abs_diff = abs(computed - expected);\n            Real rel_diff = abs_diff/abs(expected);\n            Real flt_distance = abs(boost::math::float_distance(computed, expected));\n            if (flt_distance > max_flt_distance)\n            {\n                max_flt_distance = flt_distance;\n                worst_flt_abscissa = t;\n                worst_flt_value = expected;\n                worst_flt_computed = computed;\n            }\n            if (expected != 0 && rel_diff > rel_sup)\n            {\n                rel_sup = rel_diff;\n                worst_rel_abscissa = t;\n                worst_rel_value = expected;\n                worst_rel_computed = computed;\n\n            }\n            if (abs_diff > sup)\n            {\n                sup = abs_diff;\n                worst_abs_abscissa = t;\n                worst_abs_computed = computed;\n                worst_abs_expected = expected;\n            }\n        }\n        std::cout << \"\\t\\tFloat distance at r = \" << r << \" is \" << max_flt_distance << \", sup distance = \" << sup << \", max relative error = \" << rel_sup << \"\\n\";\n        std::cout << \"\\t\\tWorst flt abscissa = \" << worst_flt_abscissa << \", worst expected value = \" << worst_flt_value << \", computed = \" << worst_flt_computed << \"\\n\";\n        std::cout << \"\\t\\tWorst rel abscissa = \" << worst_rel_abscissa << \", worst expected value = \" << worst_rel_value << \", computed = \" << worst_rel_computed << \"\\n\";\n        std::cout << \"\\t\\tWorst abs abscissa = \" << worst_abs_abscissa << \", worst expected value = \" << worst_abs_computed << \", worst abs value (expected) = \" << worst_abs_expected << \"\\n\";\n    }\n    std::cout << \"\\n\\n\\n\";\n}\n\ntemplate<typename Real, typename PreciseReal, int p>\nvoid find_best_interpolator()\n{\n    std::string filename = \"daubechies_\" + std::to_string(p) + \"_scaling_convergence.csv\";\n    std::ofstream fs{filename};\n    static_assert(sizeof(PreciseReal) >= sizeof(Real), \"sizeof(PreciseReal) >= sizeof(Real) is required.\");\n    using std::abs;\n    int rmax = 18;\n    std::cout << \"Computing phi_dense_precise\\n\";\n    auto phi_dense_precise = boost::math::daubechies_scaling_dyadic_grid<PreciseReal, p, 0>(rmax);\n    std::vector<Real> phi_dense(phi_dense_precise.size());\n    for (size_t i = 0; i < phi_dense.size(); ++i)\n    {\n        phi_dense[i] = static_cast<Real>(phi_dense_precise[i]);\n    }\n    phi_dense_precise.resize(0);\n    std::cout << \"Done\\n\";\n\n    Real dx_dense = (2*p-1)/static_cast<Real>(phi_dense.size()-1);\n    fs << std::setprecision(std::numeric_limits<Real>::digits10 + 3);\n    fs << std::fixed;\n    fs << \"r, matched_holder, linear, quadratic_b_spline, cubic_b_spline, quintic_b_spline, cubic_hermite, pchip, makima, fo_taylor\";\n    if (p==2)\n    {\n        fs << \"\\n\";\n    }\n    else\n    {\n        fs << \", quintic_hermite, second_order_taylor\";\n        if (p > 3)\n        {\n            fs << \", third_order_taylor, septic_hermite\\n\";\n        }\n        else\n        {\n            fs << \"\\n\";\n        }\n    }\n    for (int r = 2; r < 13; ++r)\n    {\n        fs << r << \", \";\n        std::map<Real, std::string> m;\n        auto phi = boost::math::daubechies_scaling_dyadic_grid<Real, p, 0>(r);\n        auto phi_prime = boost::math::daubechies_scaling_dyadic_grid<Real, p, 1>(r);\n\n        std::vector<Real> x(phi.size());\n        Real dx = (2*p-1)/static_cast<Real>(x.size()-1);\n        std::cout << \"dx = 1/\" << (1 << r) << \" = \" << dx << \"\\n\";\n        for (size_t i = 0; i < x.size(); ++i)\n        {\n            x[i] = i*dx;\n        }\n\n        {\n            auto phi_copy = phi;\n            auto phi_prime_copy = phi_prime;\n            auto mh = boost::math::detail::matched_holder(std::move(phi_copy), std::move(phi_prime_copy), r, Real(0));\n            Real sup = 0;\n            // call to matched_holder is unchecked, so only go to phi_dense.size() -1.\n            for (size_t i = 0; i < phi_dense.size() - 1; ++i)\n            {\n                Real x = i*dx_dense;\n                Real diff = abs(phi_dense[i] - mh(x));\n                if (diff > sup)\n                {\n                    sup = diff;\n                }\n            }\n            m.insert({sup, \"matched_holder\"});\n            fs << sup << \", \";\n        }\n\n\n        {\n            auto linear = [&phi, &dx, &r](Real x)->Real {\n              if (x <= 0 || x >= 2*p-1)\n              {\n                return Real(0);\n              }\n              using std::floor;\n\n              Real y = (1<<r)*x;\n              Real k = floor(y);\n\n              size_t kk = static_cast<size_t>(k);\n\n              Real t = y - k;\n              return (1-t)*phi[kk] + t*phi[kk+1];\n            };\n\n            Real linear_sup = 0;\n            for (size_t i = 0; i < phi_dense.size(); ++i)\n            {\n                Real x = i*dx_dense;\n                Real diff = abs(phi_dense[i] - linear(x));\n                if (diff > linear_sup)\n                {\n                    linear_sup = diff;\n                }\n            }\n            m.insert({linear_sup, \"linear interpolation\"});\n            fs << linear_sup << \", \";\n        }\n        \n\n        {\n            auto qbs = boost::math::interpolators::cardinal_quadratic_b_spline(phi.data(), phi.size(), Real(0), dx, phi_prime.front(), phi_prime.back());\n            Real qbs_sup = 0;\n            for (size_t i = 0; i < phi_dense.size(); ++i)\n            {\n                Real x = i*dx_dense;\n                Real diff = abs(phi_dense[i] - qbs(x));\n                if (diff > qbs_sup) {\n                    qbs_sup = diff;\n                }\n            }\n            m.insert({qbs_sup, \"quadratic_b_spline\"});\n            fs << qbs_sup << \", \";\n        }\n\n        {\n            auto cbs = boost::math::interpolators::cardinal_cubic_b_spline(phi.data(), phi.size(), Real(0), dx, phi_prime.front(), phi_prime.back());\n            Real cbs_sup = 0;\n            for (size_t i = 0; i < phi_dense.size(); ++i)\n            {\n                Real x = i*dx_dense;\n                Real diff = abs(phi_dense[i] - cbs(x));\n                if (diff > cbs_sup)\n                {\n                    cbs_sup = diff;\n                }\n            }\n            m.insert({cbs_sup, \"cubic_b_spline\"});\n            fs << cbs_sup << \", \";\n        }\n\n        {\n            auto qbs = boost::math::interpolators::cardinal_quintic_b_spline(phi.data(), phi.size(), Real(0), dx, {0,0}, {0,0});\n            Real qbs_sup = 0;\n            for (size_t i = 0; i < phi_dense.size(); ++i)\n            {\n                Real x = i*dx_dense;\n                Real diff = abs(phi_dense[i] - qbs(x));\n                if (diff > qbs_sup)\n                {\n                    qbs_sup = diff;\n                }\n            }\n            m.insert({qbs_sup, \"quintic_b_spline\"});\n            fs << qbs_sup << \", \";\n        }\n\n        {\n            auto phi_copy = phi;\n            auto phi_prime_copy = phi_prime;\n            auto ch = boost::math::interpolators::cardinal_cubic_hermite(std::move(phi_copy), std::move(phi_prime_copy), Real(0), dx);\n            Real chs_sup = 0;\n            for (size_t i = 0; i < phi_dense.size(); ++i)\n            {\n                Real x = i*dx_dense;\n                Real diff = abs(phi_dense[i] - ch(x));\n                if (diff > chs_sup)\n                {\n                    chs_sup = diff;\n                }\n            }\n            m.insert({chs_sup, \"cubic_hermite_spline\"});\n            fs << chs_sup << \", \";\n        }\n\n        {\n            auto phi_copy = phi;\n            auto x_copy = x;\n            auto phi_prime_copy = phi_prime;\n            auto pc = boost::math::interpolators::pchip(std::move(x_copy), std::move(phi_copy));\n            Real pchip_sup = 0;\n            for (size_t i = 0; i < phi_dense.size(); ++i)\n            {\n                Real x = i*dx_dense;\n                Real diff = abs(phi_dense[i] - pc(x));\n                if (diff > pchip_sup)\n                {\n                  pchip_sup = diff;\n                }\n            }\n            m.insert({pchip_sup, \"pchip\"});\n            fs << pchip_sup << \", \";\n        }\n\n        {\n            auto phi_copy = phi;\n            auto x_copy = x;\n            auto pc = boost::math::interpolators::makima(std::move(x_copy), std::move(phi_copy));\n            Real makima_sup = 0;\n            for (size_t i = 0; i < phi_dense.size(); ++i) {\n              Real x = i*dx_dense;\n              Real diff = abs(phi_dense[i] - pc(x));\n              if (diff > makima_sup)\n              {\n                  makima_sup = diff;\n              }\n            }\n            m.insert({makima_sup, \"makima\"});\n            fs << makima_sup << \", \";\n        }\n\n        // Whittaker-Shannon interpolation has linear complexity; test over all points and it's quadratic.\n        // I ran this a couple times and found it's not competitive; so comment out for now.\n        /*{\n            auto phi_copy = phi;\n            auto ws = boost::math::interpolators::whittaker_shannon(std::move(phi_copy), Real(0), dx);\n            Real sup = 0;\n            for (size_t i = 0; i < phi_dense.size(); ++i) {\n              Real x = i*dx_dense;\n              using std::abs;\n              Real diff = abs(phi_dense[i] - ws(x));\n              if (diff > sup) {\n                sup = diff;\n              }\n            }\n          \n            m.insert({sup, \"whittaker_shannon\"});\n        }\n\n        // Again, linear complexity of evaluation => quadratic complexity of exhaustive checking.\n        {\n            auto trig = boost::math::interpolators::cardinal_trigonometric(phi, Real(0), dx);\n            Real sup = 0;\n            for (size_t i = 0; i < phi_dense.size(); ++i) {\n              Real x = i*dx_dense;\n              using std::abs;\n              Real diff = abs(phi_dense[i] - trig(x));\n              if (diff > sup) {\n                sup = diff;\n              }\n            }\n            m.insert({sup, \"trig\"});\n        }*/\n\n        {\n            auto fotaylor = [&phi, &phi_prime, &r](Real x)->Real\n            {\n                if (x <= 0 || x >= 2*p-1)\n                {\n                    return 0;\n                }\n                using std::floor;\n\n                Real y = (1<<r)*x;\n                Real k = floor(y);\n\n                size_t kk = static_cast<size_t>(k);\n                if (y - k < k + 1 - y)\n                {\n                    Real eps = (y-k)/(1<<r);\n                    return phi[kk] + eps*phi_prime[kk];\n                }\n                else {\n                    Real eps = (y-k-1)/(1<<r);\n                    return phi[kk+1] + eps*phi_prime[kk+1];\n                }\n            };\n            Real fo_sup = 0;\n            for (size_t i = 0; i < phi_dense.size(); ++i)\n            {\n                Real x = i*dx_dense;\n                Real diff = abs(phi_dense[i] - fotaylor(x));\n                if (diff > fo_sup)\n                {\n                  fo_sup = diff;\n                }\n            }\n            m.insert({fo_sup, \"First-order Taylor\"});\n            if (p==2)\n            {\n                fs << fo_sup << \"\\n\";\n            }\n            else\n            {\n                fs << fo_sup << \", \";\n            }\n        }\n\n        if constexpr (p > 2) {\n            auto phi_dbl_prime = boost::math::daubechies_scaling_dyadic_grid<Real, p, 2>(r);\n\n            {\n                auto phi_copy = phi;\n                auto phi_prime_copy = phi_prime;\n                auto phi_dbl_prime_copy = phi_dbl_prime;\n                auto qh = boost::math::interpolators::cardinal_quintic_hermite(std::move(phi_copy), std::move(phi_prime_copy), std::move(phi_dbl_prime_copy), Real(0), dx);\n                Real qh_sup = 0;\n                for (size_t i = 0; i < phi_dense.size(); ++i)\n                {\n                    Real x = i*dx_dense;\n                    Real diff = abs(phi_dense[i] - qh(x));\n                    if (diff > qh_sup)\n                    {\n                        qh_sup = diff;\n                    }\n                }\n                m.insert({qh_sup, \"quintic_hermite_spline\"});\n                fs << qh_sup << \", \";\n            }\n\n            {\n                auto sotaylor = [&phi, &phi_prime, &phi_dbl_prime, &r](Real x)->Real {\n                      if (x <= 0 || x >= 2*p-1)\n                      {\n                          return 0;\n                      }\n                      using std::floor;\n\n                      Real y = (1<<r)*x;\n                      Real k = floor(y);\n\n                      size_t kk = static_cast<size_t>(k);\n                      if (y - k < k + 1 - y)\n                      {\n                          Real eps = (y-k)/(1<<r);\n                          return phi[kk] + eps*phi_prime[kk] + eps*eps*phi_dbl_prime[kk]/2;\n                      }\n                      else {\n                          Real eps = (y-k-1)/(1<<r);\n                          return phi[kk+1] + eps*phi_prime[kk+1] + eps*eps*phi_dbl_prime[kk+1]/2;\n                      }\n                };\n                Real so_sup = 0;\n                for (size_t i = 0; i < phi_dense.size(); ++i)\n                {\n                    Real x = i*dx_dense;\n                    Real diff = abs(phi_dense[i] - sotaylor(x));\n                    if (diff > so_sup)\n                    {\n                        so_sup = diff;\n                    }\n                }\n                m.insert({so_sup, \"Second-order Taylor\"});\n                if (p > 3)\n                {\n                    fs << so_sup << \", \";  \n                }\n                else\n                {\n                    fs << so_sup << \"\\n\";\n                }\n                \n            }\n        }\n\n        if constexpr (p > 3)\n        {\n            auto phi_dbl_prime = boost::math::daubechies_scaling_dyadic_grid<Real, p, 2>(r);\n            auto phi_triple_prime = boost::math::daubechies_scaling_dyadic_grid<Real, p, 3>(r);\n\n            {\n                auto totaylor = [&phi, &phi_prime, &phi_dbl_prime, &phi_triple_prime, &r](Real x)->Real {\n                      if (x <= 0 || x >= 2*p-1) {\n                          return 0;\n                      }\n                      using std::floor;\n\n                      Real y = (1<<r)*x;\n                      Real k = floor(y);\n\n                      size_t kk = static_cast<size_t>(k);\n                      if (y - k < k + 1 - y)\n                      {\n                          Real eps = (y-k)/(1<<r);\n                          return phi[kk] + eps*phi_prime[kk] + eps*eps*phi_dbl_prime[kk]/2 + eps*eps*eps*phi_triple_prime[kk]/6;\n                      }\n                      else {\n                          Real eps = (y-k-1)/(1<<r);\n                          return phi[kk+1] + eps*phi_prime[kk+1] + eps*eps*phi_dbl_prime[kk+1]/2 + eps*eps*eps*phi_triple_prime[kk]/6;\n                      }\n                };\n                Real to_sup = 0;\n                for (size_t i = 0; i < phi_dense.size(); ++i)\n                {\n                    Real x = i*dx_dense;\n                    Real diff = abs(phi_dense[i] - totaylor(x));\n                    if (diff > to_sup)\n                    {\n                        to_sup = diff;\n                    }\n                }\n            \n                m.insert({to_sup, \"Third-order Taylor\"});\n                fs << to_sup << \", \";\n            }\n\n            {\n                auto phi_copy = phi;\n                auto phi_prime_copy = phi_prime;\n                auto phi_dbl_prime_copy = phi_dbl_prime;\n                auto phi_triple_prime_copy = phi_triple_prime;\n                auto sh = boost::math::interpolators::cardinal_septic_hermite(std::move(phi_copy), std::move(phi_prime_copy), std::move(phi_dbl_prime_copy), std::move(phi_triple_prime_copy), Real(0), dx);\n                Real septic_sup = 0;\n                for (size_t i = 0; i < phi_dense.size(); ++i)\n                {\n                    Real x = i*dx_dense;\n                    Real diff = abs(phi_dense[i] - sh(x));\n                    if (diff > septic_sup)\n                    {\n                        septic_sup = diff;\n                    }\n                }\n                m.insert({septic_sup, \"septic_hermite_spline\"});\n                fs << septic_sup << \"\\n\";\n            }\n\n\n        }\n        std::string best = \"none\";\n        Real best_sup = 1000000000;\n        std::cout << std::setprecision(std::numeric_limits<Real>::digits10 + 3) << std::fixed;\n        for (auto & e : m)\n        {\n            std::cout << \"\\t\" << e.first << \" is error of \" << e.second << \"\\n\";\n            if (e.first < best_sup)\n            {\n                best = e.second;\n                best_sup = e.first;\n            }\n        }\n        std::cout << \"\\tThe best method for p = \" << p << \" is the \" << best << \"\\n\";\n    }\n}\n\nint main()\n{\n    //boost::hana::for_each(std::make_index_sequence<4>(), [&](auto i){ choose_refinement<double, float128, i+16>(); });\n    boost::hana::for_each(std::make_index_sequence<12>(), [&](auto i){ find_best_interpolator<double, float128, i+2>(); });\n}\n", "meta": {"hexsha": "56c5ed3cba2a15de0513ef444d8a475b4f8f1619", "size": 19585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/daubechies_wavelets/find_best_daubechies_interpolator.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": "3rdparty/boost_1_73_0/libs/math/example/daubechies_wavelets/find_best_daubechies_interpolator.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/math/example/daubechies_wavelets/find_best_daubechies_interpolator.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "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": 36.5391791045, "max_line_length": 204, "alphanum_fraction": 0.4589737044, "num_tokens": 4856, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.6046672436205104}}
{"text": "#include <armadillo>\n#include <bitset>\n#include <functional>\n\nusing namespace arma;\nusing namespace std;\n\nnamespace genetico {\n\ntemplate <unsigned int nBits>\nbitset<nBits> codificar(double fenotipo,\n                        double minimoFenotipo,\n                        double maximoFenotipo)\n{\n    double rango = maximoFenotipo - minimoFenotipo;\n    double factorConversion = (pow(2, nBits) - 1) / rango;\n\n    unsigned int convertido = round((fenotipo - minimoFenotipo) * factorConversion);\n\n    return bitset<nBits>{convertido};\n}\n\ntemplate <unsigned int nBits, unsigned int nVariables>\nbitset<nBits * nVariables> codificar(array<double, nVariables> fenotipo,\n                                     const array<double, nVariables * 2>& limites)\n{\n    ostringstream ost;\n    for (unsigned int i = 0; i < nVariables; ++i) {\n        ost << codificar<nBits>(fenotipo.at(i),\n                                limites.at(2 * i),\n                                limites.at(2 * i + 1));\n    }\n\n    bitset<nBits * nVariables> result;\n    istringstream ist{ost.str()};\n    ist >> result;\n\n    return result;\n}\n\ntemplate <unsigned int nBits>\ndouble decodificar(bitset<nBits> genotipo,\n                   double minimoFenotipo,\n                   double maximoFenotipo)\n{\n    double rango = maximoFenotipo - minimoFenotipo;\n    double factorConversion = rango / (pow(2, nBits) - 1);\n\n    double convertido = genotipo.to_ulong() * factorConversion + minimoFenotipo;\n\n    return convertido;\n}\n\ntemplate <unsigned int nBits, unsigned int nVariables>\narray<double, nVariables> decodificar(const bitset<nBits * nVariables>& genotipo,\n                                      const array<double, nVariables * 2>& limites)\n{\n    istringstream ist{genotipo.to_string()};\n    array<double, nVariables> result;\n\n    for (unsigned int i = 0; i < nVariables; ++i) {\n        bitset<nBits> trozoGenotipo;\n        ist >> trozoGenotipo;\n        result.at(i) = decodificar<nBits>(trozoGenotipo,\n                                          limites.at(2 * i),\n                                          limites.at(2 * i + 1));\n    }\n\n    return result;\n}\n\n// Genotipo con un \u00fanico cromosoma\ntemplate <unsigned int nBits, unsigned int nVariables>\nstruct Individuo {\n    // Individuo inicializado al azar\n    Individuo(const array<double, nVariables * 2>& t_limites)\n        : genotipo{unsigned(randi(1, distr_param(0.0, pow(2, nBits * nVariables) - 1)).at(0))}\n        , limites{t_limites}\n    {\n    }\n\n    Individuo(bitset<nBits * nVariables> t_genotipo,\n              const array<double, nVariables * 2>& t_limites)\n        : genotipo{t_genotipo}\n        , limites{t_limites}\n    {\n    }\n\n    array<double, nVariables> fenotipo() const\n    {\n        return decodificar<nBits, nVariables>(genotipo, limites);\n    }\n\n    void mutar()\n    {\n        genotipo.flip(randi(1, distr_param(0.0, nBits * nVariables - 1)).at(0));\n    }\n\n    bitset<nBits * nVariables> genotipo;\n    array<double, nVariables * 2> limites;\n};\n\ntemplate <unsigned int nBits, unsigned int nVariables>\nclass Poblacion {\n    using I = Individuo<nBits, nVariables>;\n\npublic:\n    Poblacion(const array<double, nVariables * 2>& limites,\n              const std::function<double(array<double, nVariables>)>& fitness,\n              int nIndividuos,\n              int nGeneraciones,\n              int umbral);\n\n    bool evaluarPoblacion();\n    void evolucionar(int nGeneraciones);\n    vector<I> seleccionarPadres();\n    vector<I> hacerCruzas(const vector<I>& padres, int nHijos);\n\n    const vector<I>& individuos() const { return m_individuos; };\n    double mejorFitness() const { return m_mejorAptitud; };\n    const I& mejorIndividuo() const { return m_mejorIndividuo; }\n    bool termino() const { return m_termino; }\n    double fitnessPromdedio() const;\n\n    static pair<I, I> cruzar(const I& padre1,\n                             const I& padre2,\n                             int puntoCruza,\n                             const array<double, nVariables * 2>& limites);\n\nprivate:\n    const array<double, nVariables * 2> m_limites;\n    const std::function<double(array<double, nVariables>)> m_fitness;\n    const int m_nIndividuos;\n    vector<I> m_individuos;\n    const int m_nGeneraciones;\n    const int m_umbral;\n    int m_generacion;\n    double m_mejorAptitud;\n    I m_mejorIndividuo;\n    int m_generacionesSinMejora;\n    bool m_termino;\n};\n\ntemplate <unsigned int nBits, unsigned int nVariables>\nPoblacion<nBits, nVariables>::\n    Poblacion(const array<double, nVariables * 2>& limites,\n              const std::function<double(array<double, nVariables>)>& fitness,\n              int nIndividuos,\n              int nGeneraciones,\n              int umbral)\n    : m_limites{limites}\n    , m_fitness{fitness}\n    , m_nIndividuos{nIndividuos}\n    , m_nGeneraciones{nGeneraciones}\n    , m_umbral{umbral}\n    , m_mejorAptitud{-numeric_limits<double>::max()}\n    , m_mejorIndividuo{limites}\n    , m_generacionesSinMejora{0}\n    , m_termino{false}\n{\n    for (int i = 0; i < nIndividuos; ++i)\n        m_individuos.push_back(I{m_limites});\n}\n\n// Devuelve true si se cumple la condici\u00f3n de parada por no mejorar fitness\ntemplate <unsigned int nBits, unsigned int nVariables>\nbool Poblacion<nBits, nVariables>::\n    evaluarPoblacion()\n{\n    bool mejoro = false;\n\n    for (const I& ind : m_individuos) {\n        double aptitud = m_fitness(ind.fenotipo());\n\n        if (aptitud > m_mejorAptitud) {\n            m_mejorAptitud = aptitud;\n            m_mejorIndividuo = ind;\n            mejoro = true;\n        }\n    }\n\n    return mejoro;\n}\n\ntemplate <unsigned int nBits, unsigned int nVariables>\nvoid Poblacion<nBits, nVariables>::\n    evolucionar(int nGeneraciones)\n{\n    // Si nunca se evalu\u00f3 la poblaci\u00f3n, hacerlo ahora\n    if (m_mejorAptitud == numeric_limits<double>::min())\n        evaluarPoblacion();\n\n    int generacion;\n    for (generacion = 0; generacion < nGeneraciones; ++generacion) {\n        vector<I> nuevaGeneracion;\n        // 1 - Rescatar el mejor individuo y meterlo en la siguiente generacion\n        nuevaGeneracion.push_back(m_mejorIndividuo);\n\n        // 2 - Seleccionar los padres\n        vector<I> padres = seleccionarPadres();\n        //        copy(padres.begin(), padres.end(), back_inserter(nuevaGeneracion));\n\n        // 3 - Hacer cruzas\n        //\t\tvector<I> hijos = hacerCruzas(padres, m_nIndividuos * 0.7);\n        vector<I> hijos = hacerCruzas(padres, m_nIndividuos);\n\n        // 4 - Hacer mutaciones\n        for (I& h : hijos)\n            if (randu(1).at(0, 0) <= 0.1)\n                h.mutar();\n\n        //        copy(hijos.begin(), hijos.end(), back_inserter(nuevaGeneracion));\n        copy(hijos.begin(), hijos.end() - 1, back_inserter(nuevaGeneracion));\n        m_individuos = nuevaGeneracion;\n\n        // 5 - Evaluar la poblacion y ver si se dio el criterio de parada\n        if (evaluarPoblacion())\n            m_generacionesSinMejora = 0;\n        else {\n            if (m_generacionesSinMejora == m_umbral) {\n                m_termino = true;\n                break;\n            }\n\n            ++m_generacionesSinMejora;\n        }\n    }\n}\n\ntemplate <unsigned int nBits, unsigned int nVariables>\nauto Poblacion<nBits, nVariables>::\n    seleccionarPadres() -> vector<I>\n{\n    vector<I> result;\n    const int nPadres = 0.3 * m_nIndividuos - 1;\n    const int k = 2;\n\n    for (int i = 0; i < nPadres; ++i) {\n        const uvec indices = shuffle(linspace<uvec>(0, m_nIndividuos - 1, m_nIndividuos));\n\n        vector<I> candidatos;\n        vec aptitudes(k);\n        for (int j = 0; j < k; ++j) {\n            candidatos.push_back(m_individuos.at(indices(j)));\n            aptitudes(j) = m_fitness(candidatos.at(j).fenotipo());\n        }\n\n        I mejor = m_individuos.at(indices(aptitudes.index_max()));\n        result.push_back(mejor);\n    }\n\n    return result;\n}\n\ntemplate <unsigned int nBits, unsigned int nVariables>\nauto Poblacion<nBits, nVariables>::\n    cruzar(const I& padre1,\n           const I& padre2,\n           int puntoCruza,\n           const array<double, nVariables * 2>& limites)\n        -> pair<I, I>\n{\n    I hijo1{limites}, hijo2{limites};\n\n    for (int i = 0; i < int(padre1.genotipo.size()); ++i) {\n        // Nota: El operador de acceso ([]) a un bitset los accede desde\n        // el bit menos significativo al m\u00e1s significativo.\n\n        if (i < puntoCruza) { // Parte izquierda del cromosoma\n            hijo1.genotipo[i] = padre1.genotipo[i];\n            hijo2.genotipo[i] = padre2.genotipo[i];\n        }\n        else { // Parte derecha del cromosoma\n            hijo1.genotipo[i] = padre2.genotipo[i];\n            hijo2.genotipo[i] = padre1.genotipo[i];\n        }\n    }\n\n    return {hijo1, hijo2};\n}\n\ntemplate <unsigned int nBits, unsigned int nVariables>\nauto Poblacion<nBits, nVariables>::\n    hacerCruzas(const vector<I>& padres, int nHijos) -> vector<I>\n{\n    vector<I> padresAux;\n    vector<I> hijos;\n\n    for (int i = 0; i < nHijos; i += 2) {\n        if (padresAux.empty()) {\n            padresAux = padres;\n            random_shuffle(padresAux.begin(), padresAux.end());\n        }\n        I padre1 = padresAux.back();\n        padresAux.pop_back();\n\n        if (padresAux.empty()) {\n            padresAux = padres;\n            random_shuffle(padresAux.begin(), padresAux.end());\n        }\n        I padre2 = padresAux.back();\n        padresAux.pop_back();\n\n        int puntoCruza = randi(1, distr_param(1, nBits - 1)).at(0);\n\n        I hijo1{m_limites}, hijo2{m_limites};\n\n        if (randu(1).at(0, 0) <= 0.9) // 90% de probabilidad de cruza\n            tie(hijo1, hijo2) = cruzar(padre1, padre2, puntoCruza, m_limites);\n        else {\n            hijo1 = padre1;\n            hijo2 = padre2;\n        }\n\n        hijos.push_back(hijo1);\n        hijos.push_back(hijo2);\n    }\n\n    return hijos;\n}\n\ntemplate <unsigned int nBits, unsigned int nVariables>\ndouble Poblacion<nBits, nVariables>::\n    fitnessPromdedio() const\n{\n    double suma = 0;\n\n    for (const I& ind : m_individuos) {\n        double aptitud = m_fitness(ind.fenotipo());\n        suma += aptitud;\n    }\n\n    return suma / m_individuos.size();\n}\n} // namespace genetico\n", "meta": {"hexsha": "02232d0530756ba172ae6943d8495d7998c842ac", "size": 10106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia4/genetico.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/genetico.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/genetico.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": 30.0773809524, "max_line_length": 94, "alphanum_fraction": 0.6060755987, "num_tokens": 2813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6046672373901625}}
{"text": "// test CPU direct R solver\n\n#include \"test_common_linear_systems.h\"\n\n#include <minisam/3rdparty/Catch2/catch.hpp>\n#include <minisam/utils/testAssertions.h>\n\n#include <minisam/linear/SquareRootCholesky.h>\n\n#include <Eigen/LU> // rank\n\nusing namespace minisam;\n\n\n// exmaple systems\ntest::ExampleLinearSystems data;\nEigen::SparseMatrix<double> A, H;\n\n/* ************************************************************************** */\nTEST_CASE(\"SquareRootCholesky_prep_static_values\", \"[linear]\") {\n\n  // use random A to generate test, to test whether R'R - ordering.permute(A'A) = 0\n  const int A_row = 40, A_col = 20;\n  Eigen::MatrixXd A_dense;\n  int A_rank;\n  do {\n    A_dense = Eigen::MatrixXd::Random(A_row, A_col);\n    Eigen::FullPivLU<Eigen::MatrixXd> lu_decomp(A_dense);\n    A_rank = lu_decomp.rank();\n  } while (A_rank < A_col); // make sure full rank\n\n  A = A_dense.sparseView();\n  H = A.transpose() * A;\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"SquareRootCholesky\", \"[linear]\") {\n\n  Eigen::VectorXd x_act;\n  SquareRootSolverStatus status;\n  SquareRootSolverCholesky chol(OrderingMethod::NONE);\n\n  Eigen::SparseMatrix<double> R_act(2,2), L_act(2,2), L_exp;\n\n  chol.initialize(data.A1.transpose() * data.A1);\n  status = chol.solveR(data.A1.transpose() * data.A1, R_act);\n  CHECK(assert_equal(data.R1_exp, R_act));\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n  status = chol.solveL(data.A1.transpose() * data.A1, L_act);\n  L_exp = data.R1_exp.transpose();\n  CHECK(assert_equal(L_exp, L_act));\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n\n  chol.initialize(data.A2.transpose() * data.A2);\n  status = chol.solveR(data.A2.transpose() * data.A2, R_act);\n  CHECK(assert_equal(data.R2_exp, R_act));\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n  status = chol.solveL(data.A2.transpose() * data.A2, L_act);\n  L_exp = data.R2_exp.transpose();\n  CHECK(assert_equal(L_exp, L_act));\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n\n  chol.initialize(data.A3.transpose() * data.A3);\n  status = chol.solveR(data.A3.transpose() * data.A3, R_act);\n  CHECK(assert_equal(data.R3_exp, R_act));\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n  status = chol.solveL(data.A3.transpose() * data.A3, L_act);\n  L_exp = data.R3_exp.transpose();\n  CHECK(assert_equal(L_exp, L_act));\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n\n  chol.initialize(data.A4.transpose() * data.A4);\n  status = chol.solveR(data.A4.transpose() * data.A4, R_act);\n  CHECK(status == SquareRootSolverStatus::RANK_DEFICIENCY);\n  status = chol.solveL(data.A4.transpose() * data.A4, R_act);\n  CHECK(status == SquareRootSolverStatus::RANK_DEFICIENCY);\n}\n\n/* ************************************************************************** */\nTEST_CASE(\"SquareRootCholesky_random\", \"[linear]\") {\n\n  Eigen::SparseMatrix<double> R, L, PHPt_act, PHPt_exp;\n\n  // AMD ordering\n  SquareRootSolverStatus status;\n  SquareRootSolverCholesky chol;\n\n  status = chol.initialize(H);\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n  chol.ordering()->permuteSystemFull(H, PHPt_exp);\n\n  // R'R = ordering.permute(A'A)\n  status = chol.solveR(H, R);\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n  PHPt_act = R.transpose() * R;\n  CHECK(assert_equal(PHPt_exp, PHPt_act));\n\n  // LL' = ordering.permute(A'A)\n  status = chol.solveL(H, L);\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n  PHPt_act = L * L.transpose();\n  CHECK(assert_equal(PHPt_exp, PHPt_act));\n\n  // no ordering\n  SquareRootSolverCholesky choln(OrderingMethod::NONE);\n\n  status = choln.initialize(H);\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n  \n  // R'R = A'A\n  status = choln.solveR(H, R);\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n  PHPt_act = R.transpose() * R;\n  CHECK(assert_equal(H, PHPt_act));\n\n  // LL' = A'A\n  status = choln.solveL(H, L);\n  CHECK(status == SquareRootSolverStatus::SUCCESS);\n  PHPt_act = L * L.transpose();\n  CHECK(assert_equal(H, PHPt_act));\n}\n", "meta": {"hexsha": "647918f29b3a72d9a43efe76133935d1be22ead3", "size": 3987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testSquareRootCholesky.cpp", "max_stars_repo_name": "versatran01/minisam", "max_stars_repo_head_hexsha": "b3840d2629551fdfa287df8aac2e7956873d2b0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 338.0, "max_stars_repo_stars_event_min_datetime": "2019-09-03T10:44:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:12:08.000Z", "max_issues_repo_path": "tests/testSquareRootCholesky.cpp", "max_issues_repo_name": "bhsphd/minisam", "max_issues_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T09:00:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-04T06:04:02.000Z", "max_forks_repo_path": "tests/testSquareRootCholesky.cpp", "max_forks_repo_name": "bhsphd/minisam", "max_forks_repo_head_hexsha": "ef84796fa11ac6e5e4d4aa9d60d9b94a99a973fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 87.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T05:17:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T09:47:23.000Z", "avg_line_length": 32.6803278689, "max_line_length": 83, "alphanum_fraction": 0.6669174818, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6046672224559618}}
{"text": "#include \"pow.h\"\r\n\r\n#include <cmath>\r\n\r\n#include <boost/test/unit_test.hpp>\r\n\r\nusing namespace std;\r\n\r\nnamespace\r\n{\r\n\tfloat log2f4to1(float x)\r\n\t{\r\n\t\t__declspec(align(16)) float v[4];\r\n\t\t_mm_store_ps(v, log2f4(_mm_set1_ps(x)));\r\n\t\treturn v[0];\r\n\t}\r\n\r\n\tfloat log2f8to1(float x)\r\n\t{\r\n\t\t__declspec(align(32)) float v[8];\r\n\t\t_mm256_store_ps(v, log2f8(_mm256_set1_ps(x)));\r\n\t\treturn v[0];\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(Log2)\r\n{\r\n\tconstexpr float tolerance = 0.002f;\r\n\r\n\tconst float args[] = { 0.1f, 0.5f, 1.0f, 2.0f, 5.0f, 100.0f };\r\n\tfor (float arg : args)\r\n\t{\r\n\t\tBOOST_CHECK_CLOSE(log2f4to1(arg), log2(arg), tolerance);\r\n\t\tBOOST_CHECK_CLOSE(log2f8to1(arg), log2(arg), tolerance);\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(Log2f4_Fullness)\r\n{\r\n\tconstexpr float x = 0.1f;\r\n\r\n\t__declspec(align(16)) float v[4];\r\n\t_mm_store_ps(v, log2f4(_mm_set1_ps(x)));\r\n\r\n\tfor (size_t i = 1; i != 4; ++i)\r\n\t\tBOOST_CHECK_EQUAL(v[0], v[i]);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(Log2f8_Fullness)\r\n{\r\n\tconstexpr float x = 0.1f;\r\n\r\n\t__declspec(align(32)) float v[8];\r\n\t_mm256_store_ps(v, log2f8(_mm256_set1_ps(x)));\r\n\r\n\tfor (size_t i = 1; i != 8; ++i)\r\n\t\tBOOST_CHECK_EQUAL(v[0], v[i]);\r\n}", "meta": {"hexsha": "c00b64745f547e9714b92bff0c269d3023ec7b3d", "size": 1142, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "render/RenderTest/TestLog.cpp", "max_stars_repo_name": "don-reba/colors-visualization", "max_stars_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "render/RenderTest/TestLog.cpp", "max_issues_repo_name": "don-reba/colors-visualization", "max_issues_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "render/RenderTest/TestLog.cpp", "max_forks_repo_name": "don-reba/colors-visualization", "max_forks_repo_head_hexsha": "fe3937087be79715307127591a06f38b4647254f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6896551724, "max_line_length": 64, "alphanum_fraction": 0.6409807356, "num_tokens": 407, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6959583124210896, "lm_q1q2_score": 0.6046672169769824}}
{"text": "/* ----------------------------------------------------------------------- *//**\n *\n * @file link.hpp\n *\n *//* ----------------------------------------------------------------------- */\n\n\n#ifndef MADLIB_MODULES_GLM_LINK_HPP\n#define MADLIB_MODULES_GLM_LINK_HPP\n\n#include <cmath>\n#include <modules/prob/boost.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/math/special_functions/erf.hpp>\n\n// ------------------------------------------------------------\n\nusing namespace madlib::dbal::eigen_integration;\n\nnamespace madlib {\n\nnamespace modules {\n\nnamespace glm {\n\nusing namespace std;\n\n// ------------------------------------------------------------\n\nclass Identity {\npublic:\n    static double init(const double &y) { return y + 0.1; }\n    static double link_func(const double &mu) { return mu; }\n    static double mean_func(const double &ita) { return ita; }\n    static double mean_derivative(const double &) { return 1.; }\n};\n\n// ------------------------------------------------------------\n\nclass Log {\npublic:\n    static double init(const double &y) { return std::max(y, 0.1); }\n    static double link_func(const double &mu) { return log(mu); }\n    static double mean_func(const double &ita) { return exp(ita); }\n    static double mean_derivative(const double &ita) { return exp(ita); }\n};\n\n// ------------------------------------------------------------\n\nclass Sqrt {\npublic:\n    static double init(const double &y) { return std::max(y, 0.); }\n    static double link_func(const double &mu) { return sqrt(mu); }\n    static double mean_func(const double &ita) { return ita * ita; }\n    static double mean_derivative(const double &ita) { return 2 * ita; }\n};\n\n// ------------------------------------------------------------\nclass Inverse {\npublic:\n    static double init(const double &y) { return y == 0 ? 0.1 : y + 0.1; }\n    static double link_func(const double &mu) { return 1./mu; }\n    static double mean_func(const double &ita) { return 1./ita; }\n    static double mean_derivative(const double &ita) { return -1./(ita*ita); }\n};\n\n// ------------------------------------------------------------\n\nclass SqrInverse {\npublic:\n    static double init(const double &y) { return y == 0 ? 0.1 : y + 0.1; }\n    static double link_func(const double &mu) { return 1./mu/mu; }\n    static double mean_func(const double &ita) { return 1./sqrt(ita); }\n    static double mean_derivative(const double &ita) { return -1./2/sqrt(ita*ita*ita); }\n};\n\n// ------------------------------------------------------------\n\nclass Probit\n{\npublic:\n    static double init(const double &y) { return (y + 0.5) / 2; }\n    static double link_func(const double &mu) {\n        double root_2 = sqrt(2);\n        return root_2 * boost::math::erf_inv(2*mu-1);\n    }\n\n    static double mean_func(const double &ita) {\n        return prob::cdf(prob::normal(), ita);\n    }\n\n    static double mean_derivative(const double &ita) {\n        return exp(-ita*ita/2.)/sqrt(2*M_PI);\n    }\n};\n\n// ------------------------------------------------------------\n\nclass Logit {\npublic:\n    static double init(const double &y) { return (y + 0.5) / 2; }\n    static double link_func(const double &mu) {\n        return log(mu / (1 - mu));\n    }\n    static double mean_func(const double &ita) {\n        return 1./(1 + exp(-ita));\n    }\n    static double mean_derivative(const double &ita) {\n        return 1./((1 + exp(-ita)) * (1 + exp(ita)));\n    }\n};\n\n// ------------------------------------------------------------\n\nclass MultiLogit {\npublic:\n    static void init(ColumnVector &mu) {\n        mu.fill(1./static_cast<double>(mu.size()+1)); // later we may consider to use y to initialize mu\n    }\n    static void link_func(const ColumnVector &mu, ColumnVector &ita) {\n        for (int i=0;i<mu.size();i++) \n          ita(i) = log(mu(i)) - log(1-mu.sum());\n    }\n    static void mean_func(const ColumnVector &ita, ColumnVector &mu) {\n        double temp=0;\n        for(int i=0;i<ita.size();i++) \n           temp += exp(ita(i));\n        temp = temp+1;\n        for(int i=0;i<ita.size();i++) \n           mu(i) = exp(ita(i))/temp;\n    }\n    static void mean_derivative(const ColumnVector &ita, Matrix &mu_prime) {\n        double temp=0;\n        for(int i=0;i<ita.size();i++) \n           temp += exp(ita(i));\n        temp = temp+1;\n        for(int i=0;i<ita.size();i++) {\n          for(int j=0;j<ita.size();j++) {\n             if(i==j)  \n                mu_prime(i,j)=exp(ita(i))*(temp - exp(ita(i)))/(temp*temp); \n             else \n                mu_prime(i,j)=-exp(ita(i))*exp(ita(j))/(temp*temp); \n          }\n        }\n    }\n};\n\n// ------------------------------------------------------------\n\nclass OrdinalLogit {\npublic:\n    static void init(ColumnVector &mu) {\n        mu.fill(1./static_cast<double>(mu.size()+1)); // later we may consider to use y to initialize mu\n    }\n    static void link_func(const ColumnVector &mu, ColumnVector &ita) {\n        ColumnVector sum_vec(mu.size());\n        sum_vec(0) = mu(0);\n        for (int i=1;i<mu.size();i++)\n            sum_vec(i) = sum_vec(i-1) + mu(i);\n        for (int i=0;i<mu.size();i++) \n            ita(i) = log(sum_vec(i)/(1-sum_vec(i)));\n    }\n    static void mean_func(const ColumnVector &ita, ColumnVector &mu) {\n        mu(0) = exp(ita(0))/(1+exp(ita(0)));\n        for(int i=1;i<ita.size();i++) \n           mu(i) = exp(ita(i))/(1+exp(ita(i)))- exp(ita(i-1))/(1+exp(ita(i-1)));      \n    }\n    static void mean_derivative(const ColumnVector &ita, Matrix &mu_prime) {\n        mu_prime.fill(0);\n        for(int i=0;i<ita.size();i++) {\n            for(int j=0;j<=i;j++) {\n                if(i==j) \n                    mu_prime(i,j)=exp(ita(i))/(1+exp(ita(i)))/(1+exp(ita(i))); \n                else if(i==(j+1)) \n                    mu_prime(i,j)=-exp(ita(j))/(1+exp(ita(j)))/(1+exp(ita(j)));\n                else \n                    mu_prime(i,j)=0;\n            }\n        }\n    }\n};\n\n// ------------------------------------------------------------\n\nclass OrdinalProbit {\npublic:\n    static void init(ColumnVector &mu) {\n        mu.fill(1./static_cast<double>(mu.size()+1)); // later we may consider to use y to initialize mu\n    }\n    static void link_func(const ColumnVector &mu, ColumnVector &ita) {\n        ColumnVector sum_vec(mu.size());\n        double root_2 = sqrt(2);\n        sum_vec(0) = mu(0);\n        for (int i=1;i<mu.size();i++)\n            sum_vec(i) = sum_vec(i-1) + mu(i);\n        for (int i=0;i<mu.size();i++) \n            ita(i) = root_2 * boost::math::erf_inv(2*sum_vec(i)-1);\n    }\n    static void mean_func(const ColumnVector &ita, ColumnVector &mu) {\n        mu(0) = prob::cdf(prob::normal(), ita(0));\n        for(int i=1;i<ita.size();i++) \n            mu(i) = prob::cdf(prob::normal(), ita(i))-prob::cdf(prob::normal(), ita(i-1));\n    }\n    static void mean_derivative(const ColumnVector &ita, Matrix &mu_prime) {\n        mu_prime.fill(0);\n        for(int i=0;i<ita.size();i++) {\n            for(int j=0;j<=i;j++) {\n                if(i==j) \n                    mu_prime(i,j) = exp(-ita(i)*ita(i)/2.)/sqrt(2*M_PI);\n                else if(i==(j+1)) \n                    mu_prime(i,j) = -exp(-ita(j)*ita(j)/2.)/sqrt(2*M_PI);\n                else \n                    mu_prime(i,j)=0;\n            }\n        }\n    }\n};\n\n} // namespace glm\n\n} // namespace modules\n\n} // namespace madlib\n\n#endif // defined(MADLIB_MODULES_GLM_LINK_HPP)\n", "meta": {"hexsha": "eaf9a107c8bd621b65a8085dd71548f3bb2a14ec", "size": 7364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/modules/glm/link.hpp", "max_stars_repo_name": "fmcquillan99/apache-madlib", "max_stars_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T07:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:45:18.000Z", "max_issues_repo_path": "src/modules/glm/link.hpp", "max_issues_repo_name": "fmcquillan99/apache-madlib", "max_issues_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-06T05:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-06T05:50:17.000Z", "max_forks_repo_path": "src/modules/glm/link.hpp", "max_forks_repo_name": "fmcquillan99/apache-madlib", "max_forks_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T20:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T20:50:13.000Z", "avg_line_length": 32.5840707965, "max_line_length": 104, "alphanum_fraction": 0.4967409017, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.6757646010190477, "lm_q1q2_score": 0.6046670408689974}}
{"text": "#include <algorithm>\n#include <cinttypes>\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n#define png_infopp_NULL nullptr\n#define int_p_NULL      nullptr\n#include <boost/gil/gil_all.hpp>\n#include <boost/gil/extension/io/png_io.hpp>\n\n\nnamespace gil = boost::gil;\n\n\n// map value in range r1 to r2\nauto map_value(double val, double r1_from, double r1_to, double r2_from, double r2_to) -> double {\n    return ((val - r1_from) / (r1_to - r1_from)) * (r2_to - r2_from) + r2_from;\n}\n\n\nclass mandelbrot_fn {\n    struct color_line {\n        explicit color_line(int lv) : \n            level{ lv }\n        {}\n\n\n        color_line(int lv, gil::bits8 r, gil::bits8 g, gil::bits8 b) :\n            level{ lv },\n            pixel{ r, g, b }\n        {}\n\n\n        int                 level;\n        gil::rgb8_pixel_t   pixel;\n\n\n        auto operator<(color_line const& rhs) const noexcept -> bool {\n            return level < rhs.level;\n        }\n    };\n\n\npublic:\n    using const_t           = mandelbrot_fn;\n    using value_type        = gil::rgb8_pixel_t;\n    using reference         = value_type;\n    using const_reference   = value_type;\n    using point_t           = gil::point2<int>;\n    using result_type       = value_type;\n    using argument_type     = point_t;\n    static constexpr bool is_mutable = false;\n\n\n    explicit mandelbrot_fn(point_t const& size) :\n        m_size{ size }\n    {\n        m_colors.emplace_back( 0,   0,   0,  64);\n        m_colors.emplace_back( 8,   0, 255, 255);\n        m_colors.emplace_back(16,   0, 255,   0);\n        m_colors.emplace_back(24, 255, 128,   0);\n        m_colors.emplace_back(32,   0,   0, 255);\n        m_colors.emplace_back(40, 255, 255,   0);\n        m_colors.emplace_back(48, 255, 255, 255);\n        m_colors.emplace_back(56, 255, 255, 255);\n        m_colors.emplace_back(64, 255, 255, 255);\n        sort(begin(m_colors), end(m_colors));\n    }\n\n\n    auto operator()(point_t const& point) const -> result_type {\n        auto level = get_color_level(point);\n        if (level < 0) {\n            return result_type{ 0, 0, 0 };\n        }\n\n        auto uppos = upper_bound(begin(m_colors), end(m_colors), color_line{ level });\n        if (uppos == end(m_colors)) {\n            --uppos;\n        }\n\n        auto const& lower = *(uppos - 1);\n        auto const& upper = *uppos;\n        result_type pixel;\n        for (auto i = 0; i < 3; ++i) {\n            pixel[i] = map_value(level, lower.level, upper.level,\n                                 lower.pixel[i], upper.pixel[i]);\n        }\n        return pixel;\n    }\n\n\nprivate:\n    // get color level of given point\n    // negative result if the point is in the set\n    auto get_color_level(point_t const& point) const -> int {\n        // map x to [-2, 1] and y to [1.5, -1.5]\n        std::complex<double> c{map_value(point.x, 0, m_size.x, -2, 1),\n                               map_value(point.y, 0, m_size.y, 1.5, -1.5)};\n        int level = 0;\n        for (auto lc = c; level < 64; ++level) {\n            if (std::pow(lc.real(), 2) + std::pow(lc.imag(), 2) > 4) {\n                return level;\n            }\n            lc = std::pow(lc, 2) + c;\n        }\n        return -1;\n    }\n\n\n    point_t m_size;\n    std::vector<color_line> m_colors;\n};\n\n\nint main() {\n    using point_t = mandelbrot_fn::point_t;\n    using locator_t = gil::virtual_2d_locator<mandelbrot_fn, false>;\n    using image_view_t = gil::image_view<locator_t>;\n\n    point_t size{ 20'000, 20'000 };\n    image_view_t view{ size, locator_t{ point_t{ 0, 0 }, point_t{ 1, 1 }, mandelbrot_fn{ size } } };\n    gil::png_write_view(\"mandelbrot.png\", view);\n}\n", "meta": {"hexsha": "c45d06eb933433582d99fa3412134ee8c1e397a6", "size": 3641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/ColorMandelbrotSet.cpp", "max_stars_repo_name": "so61pi/examples", "max_stars_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-01T07:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T00:05:06.000Z", "max_issues_repo_path": "cpp/ColorMandelbrotSet.cpp", "max_issues_repo_name": "so61pi/examples", "max_issues_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-02-24T13:04:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T10:19:48.000Z", "max_forks_repo_path": "cpp/ColorMandelbrotSet.cpp", "max_forks_repo_name": "so61pi/examples", "max_forks_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-30T07:29:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-30T07:29:58.000Z", "avg_line_length": 28.4453125, "max_line_length": 100, "alphanum_fraction": 0.5627574842, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.6046039457785839}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n  Matrix3f m;\nm.row(0) << 1, 2, 3;\nm.block(1,0,2,2) << 4, 5, 7, 8;\nm.col(2).tail(2) << 6, 9;\t\t    \nstd::cout << m;\n\n  return 0;\n}\n", "meta": {"hexsha": "48e5a8fee14e767f98319b262cd2bf065bb8aa0c", "size": 264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tutorial_commainit_01b.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_commainit_01b.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_commainit_01b.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": 14.6666666667, "max_line_length": 31, "alphanum_fraction": 0.5833333333, "num_tokens": 106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.604546524684055}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2005, 2016 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include \"gaussianquadratures.hpp\"\n#include \"utilities.hpp\"\n\n#include <ql/types.hpp>\n#include <ql/math/matrix.hpp>\n#include <ql/math/functional.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/integrals/gaussianquadratures.hpp>\n#include <ql/math/integrals/momentbasedgaussianpolynomial.hpp>\n#include <ql/math/integrals/gausslaguerrecosinepolynomial.hpp>\n#include <ql/experimental/math/gaussiannoncentralchisquaredpolynomial.hpp>\n\n#include <boost/math/distributions/non_central_chi_squared.hpp>\n\n#ifndef TEST_BOOST_MULTIPRECISION_GAUSSIAN_QUADRATURE\n//#define TEST_BOOST_MULTIPRECISION_GAUSSIAN_QUADRATURE\n#endif\n\n#ifdef TEST_BOOST_MULTIPRECISION_GAUSSIAN_QUADRATURE\n    #if BOOST_VERSION < 105300\n        #error This boost version is too old to support boost multi precision\n    #endif\n\n    #include <boost/multiprecision/cpp_dec_float.hpp>\n#endif\n\nusing namespace QuantLib;\nusing namespace boost::unit_test_framework;\n\nnamespace gaussian_quadratures_test {\n\n    template <class T>\n    void testSingle(const T& I, const std::string& tag,\n                    const boost::function<Real(Real)>& f, Real expected) {\n        Real calculated = I(f);\n        if (std::fabs(calculated-expected) > 1.0e-4) {\n            BOOST_ERROR(\"integrating\" << tag << \"\\n\"\n                        << \"    calculated: \" << calculated << \"\\n\"\n                        << \"    expected:   \" << expected);\n        }\n    }\n\n    // test functions\n\n    Real inv_exp(Real x) {\n        return std::exp(-x);\n    }\n\n    Real x_inv_exp(Real x) {\n        return x*std::exp(-x);\n    }\n\n    Real x_normaldistribution(Real x) {\n        return x*NormalDistribution()(x);\n    }\n\n    Real x_x_normaldistribution(Real x) {\n        return x*x*NormalDistribution()(x);\n    }\n\n    Real inv_cosh(Real x) {\n        return 1/std::cosh(x);\n    }\n\n    Real x_inv_cosh(Real x) {\n        return x/std::cosh(x);\n    }\n\n    Real x_x_nonCentralChiSquared(Real x) {\n        return x * x * boost::math::pdf(\n            boost::math::non_central_chi_squared_distribution<Real>(4.0,1.0),x);\n    }\n\n    Real x_sin_exp_nonCentralChiSquared(Real x) {\n        return x * std::sin(0.1*x) * std::exp(0.3*x) * boost::math::pdf(\n            boost::math::non_central_chi_squared_distribution<Real>(1.0,1.0),x);\n    }\n\n    template <class T>\n    void testSingleJacobi(const T& I) {\n        testSingle(I, \"f(x) = 1\",\n                   constant<Real,Real>(1.0), 2.0);\n        testSingle(I, \"f(x) = x\",\n                   identity<Real>(),         0.0);\n        testSingle(I, \"f(x) = x^2\",\n                   square<Real>(),           2/3.);\n        testSingle(I, \"f(x) = sin(x)\",\n                   static_cast<Real(*)(Real)>(std::sin), 0.0);\n        testSingle(I, \"f(x) = cos(x)\",\n                   static_cast<Real(*)(Real)>(std::cos),\n                   std::sin(1.0)-std::sin(-1.0));\n        testSingle(I, \"f(x) = Gaussian(x)\",\n                   NormalDistribution(),\n                   CumulativeNormalDistribution()(1.0)\n                   -CumulativeNormalDistribution()(-1.0));\n    }\n\n    template <class T>\n    void testSingleLaguerre(const T& I) {\n        testSingle(I, \"f(x) = exp(-x)\",\n                   inv_exp, 1.0);\n        testSingle(I, \"f(x) = x*exp(-x)\",\n                   x_inv_exp, 1.0);\n        testSingle(I, \"f(x) = Gaussian(x)\",\n                   NormalDistribution(), 0.5);\n    }\n\n    void testSingleTabulated(const boost::function<Real(Real)>& f,\n                             const std::string& tag,\n                             Real expected, Real tolerance) {\n        const Size order[] = { 6, 7, 12, 20 };\n        TabulatedGaussLegendre quad;\n        for (Size i=0; i<LENGTH(order); i++) {\n            quad.order(order[i]);\n            Real realised = quad(f);\n            if (std::fabs(realised-expected) > tolerance) {\n                BOOST_ERROR(\" integrating \" << tag << \"\\n\"\n                            << \"    order \" << order[i] << \"\\n\"\n                            << \"    realised: \" << realised << \"\\n\"\n                            << \"    expected: \" << expected);\n            }\n        }\n    }\n\n}\n\n\nvoid GaussianQuadraturesTest::testJacobi() {\n    BOOST_TEST_MESSAGE(\"Testing Gauss-Jacobi integration...\");\n\n    using namespace gaussian_quadratures_test;\n\n    testSingleJacobi(GaussLegendreIntegration(16));\n    testSingleJacobi(GaussChebyshevIntegration(130));\n    testSingleJacobi(GaussChebyshev2ndIntegration(130));\n    testSingleJacobi(GaussGegenbauerIntegration(50,0.55));\n}\n\nvoid GaussianQuadraturesTest::testLaguerre() {\n     BOOST_TEST_MESSAGE(\"Testing Gauss-Laguerre integration...\");\n\n     using namespace gaussian_quadratures_test;\n\n     testSingleLaguerre(GaussLaguerreIntegration(16));\n     testSingleLaguerre(GaussLaguerreIntegration(150,0.01));\n\n     testSingle(GaussLaguerreIntegration(16, 1.0), \"f(x) = x*exp(-x)\",\n                x_inv_exp, 1.0);\n     testSingle(GaussLaguerreIntegration(32, 0.9), \"f(x) = x*exp(-x)\",\n                x_inv_exp, 1.0);\n}\n\nvoid GaussianQuadraturesTest::testHermite() {\n     BOOST_TEST_MESSAGE(\"Testing Gauss-Hermite integration...\");\n\n     using namespace gaussian_quadratures_test;\n\n     testSingle(GaussHermiteIntegration(16), \"f(x) = Gaussian(x)\",\n                NormalDistribution(), 1.0);\n     testSingle(GaussHermiteIntegration(16,0.5), \"f(x) = x*Gaussian(x)\",\n                x_normaldistribution, 0.0);\n     testSingle(GaussHermiteIntegration(64,0.9), \"f(x) = x*x*Gaussian(x)\",\n                x_x_normaldistribution, 1.0);\n}\n\nvoid GaussianQuadraturesTest::testHyperbolic() {\n     BOOST_TEST_MESSAGE(\"Testing Gauss hyperbolic integration...\");\n\n     using namespace gaussian_quadratures_test;\n\n     testSingle(GaussHyperbolicIntegration(16), \"f(x) = 1/cosh(x)\",\n                inv_cosh, M_PI);\n     testSingle(GaussHyperbolicIntegration(16), \"f(x) = x/cosh(x)\",\n                x_inv_cosh, 0.0);\n}\n\nvoid GaussianQuadraturesTest::testTabulated() {\n     BOOST_TEST_MESSAGE(\"Testing tabulated Gauss-Laguerre integration...\");\n\n     using namespace gaussian_quadratures_test;\n\n     testSingleTabulated(constant<Real,Real>(1.0), \"f(x) = 1\",\n                         2.0,       1.0e-13);\n     testSingleTabulated(identity<Real>(), \"f(x) = x\",\n                         0.0,       1.0e-13);\n     testSingleTabulated(square<Real>(), \"f(x) = x^2\",\n                         (2.0/3.0), 1.0e-13);\n     testSingleTabulated(cube<Real>(), \"f(x) = x^3\",\n                         0.0,       1.0e-13);\n     testSingleTabulated(fourth_power<Real>(), \"f(x) = x^4\",\n                         (2.0/5.0), 1.0e-13);\n}\n\nvoid GaussianQuadraturesTest::testNonCentralChiSquared() {\n     BOOST_TEST_MESSAGE(\n         \"Testing Gauss non-central chi-squared integration...\");\n\n     using namespace gaussian_quadratures_test;\n\n     testSingle(\n        GaussianQuadrature(2, GaussNonCentralChiSquaredPolynomial(4.0, 1.0)),\n        \"f(x) = x^2 * nonCentralChiSquared(4, 1)(x)\",\n        x_x_nonCentralChiSquared, 37.0);\n\n     testSingle(\n        GaussianQuadrature(14, GaussNonCentralChiSquaredPolynomial(1.0, 1.0)),\n        \"f(x) = x * sin(0.1*x)*exp(0.3*x)*nonCentralChiSquared(1, 1)(x)\",\n        x_sin_exp_nonCentralChiSquared, 17.408092);\n}\n\n\nvoid GaussianQuadraturesTest::testNonCentralChiSquaredSumOfNodes() {\n     BOOST_TEST_MESSAGE(\n         \"Testing Gauss non-central chi-squared sum of nodes...\");\n\n     using namespace gaussian_quadratures_test;\n\n     // Walter Gautschi, How and How not to check Gaussian Quadrature Formulae\n     // https://www.cs.purdue.edu/homes/wxg/selected_works/section_08/084.pdf\n\n     // Expected results have been calculated with a multi precision library\n     // following the description of test #4 in the paper above.\n     // Using QuantLib's own determinant function will not work here\n     // as it supports only double precision.\n\n     const Real expected[] = {\n         47.53491786730293,\n         70.6103295419633383,\n         98.0593406849441607,\n         129.853401537905341,\n         165.96963582663912,\n         206.389183233992043\n     };\n\n     const Real nu=4.0;\n     const Real lambda=1.0;\n     const GaussNonCentralChiSquaredPolynomial orthPoly(nu, lambda);\n\n     const Real tol = 1e-5;\n\n\t for (Size n = 4; n < 10; ++n) {\n\t\t const Array x = GaussianQuadrature(n, orthPoly).x();\n         const Real calculated = std::accumulate(x.begin(), x.end(), 0.0);\n\n\n         if (std::fabs(calculated - expected[n-4]) > tol) {\n             BOOST_ERROR(\"failed to reproduce rule of sum\"\n                         << \"\\n    calculated: \" << calculated\n                         << \"\\n    expected:   \" << expected[n-4]\n                         << \"\\n    diff    :   \" << calculated - expected[n-4]);\n         }\n     }\n}\n\nnamespace gaussian_quadratures_test {\n    template <class mp_float>\n    class MomentBasedGaussLaguerrePolynomial\n            : public MomentBasedGaussianPolynomial<mp_float> {\n      public:\n        mp_float moment(Size i) const {\n            if (i == 0)\n                return mp_float(1.0);\n            else\n                return mp_float(i)*moment(i-1);\n        }\n\n        Real w(Real x) const {\n            return std::exp(-x);\n        }\n    };\n}\n\nvoid GaussianQuadraturesTest::testMomentBasedGaussianPolynomial() {\n     BOOST_TEST_MESSAGE(\"Testing moment based Gaussian polynomials...\");\n\n     using namespace gaussian_quadratures_test;\n\n     GaussLaguerrePolynomial g;\n\n     std::vector<ext::shared_ptr<GaussianOrthogonalPolynomial> > ml;\n     ml.push_back(\n         ext::make_shared<MomentBasedGaussLaguerrePolynomial<Real> >());\n\n#ifdef TEST_BOOST_MULTIPRECISION_GAUSSIAN_QUADRATURE\n     ml.push_back(\n         ext::make_shared<MomentBasedGaussLaguerrePolynomial<\n             boost::multiprecision::number<\n                 boost::multiprecision::cpp_dec_float<20> > > >());\n#endif\n\n     const Real tol = 1e-12;\n     for (Size k=0; k < ml.size(); ++k) {\n\n         for (Size i=0; i < 10; ++i) {\n             const Real diffAlpha = std::fabs(ml[k]->alpha(i)-g.alpha(i));\n             const Real diffBeta = std::fabs(ml[k]->beta(i)-g.beta(i));\n\n             if (diffAlpha > tol) {\n                 BOOST_ERROR(\"failed to reproduce alpha for Laguerre quadrature\"\n                             << \"\\n    calculated: \" << ml[k]->alpha(i)\n                             << \"\\n    expected  : \" << g.alpha(i)\n                             << \"\\n    diff      : \" << diffAlpha);\n             }\n             if (i > 0 && diffBeta > tol) {\n                 BOOST_ERROR(\"failed to reproduce beta for Laguerre quadrature\"\n                             << \"\\n    calculated: \" << ml[k]->beta(i)\n                             << \"\\n    expected  : \" << g.beta(i)\n                             << \"\\n    diff      : \" << diffBeta);\n             }\n         }\n     }\n}\n\nvoid GaussianQuadraturesTest::testGaussLaguerreCosinePolynomial() {\n    BOOST_TEST_MESSAGE(\"Testing Gauss-Laguerre-Cosine quadrature...\");\n\n    using namespace gaussian_quadratures_test;\n\n    const GaussianQuadrature quadCosine(\n            16, GaussLaguerreCosinePolynomial<Real>(0.2));\n\n    testSingle(quadCosine, \"f(x) = exp(-x)\",\n               inv_exp, 1.0);\n    testSingle(quadCosine, \"f(x) = x*exp(-x)\",\n               x_inv_exp, 1.0);\n\n    const GaussianQuadrature quadSine(\n            16, GaussLaguerreSinePolynomial<Real>(0.2));\n\n    testSingle(quadSine, \"f(x) = exp(-x)\",\n               inv_exp, 1.0);\n    testSingle(quadSine, \"f(x) = x*exp(-x)\",\n               x_inv_exp, 1.0);\n}\n\ntest_suite* GaussianQuadraturesTest::suite() {\n    test_suite* suite = BOOST_TEST_SUITE(\"Gaussian quadratures tests\");\n    suite->add(QUANTLIB_TEST_CASE(&GaussianQuadraturesTest::testJacobi));\n    suite->add(QUANTLIB_TEST_CASE(&GaussianQuadraturesTest::testLaguerre));\n    suite->add(QUANTLIB_TEST_CASE(&GaussianQuadraturesTest::testHermite));\n    suite->add(QUANTLIB_TEST_CASE(&GaussianQuadraturesTest::testHyperbolic));\n    suite->add(QUANTLIB_TEST_CASE(&GaussianQuadraturesTest::testTabulated));\n    suite->add(QUANTLIB_TEST_CASE(\n        &GaussianQuadraturesTest::testMomentBasedGaussianPolynomial));\n    suite->add(QUANTLIB_TEST_CASE(\n        &GaussianQuadraturesTest::testGaussLaguerreCosinePolynomial));\n\n    return suite;\n}\n\ntest_suite* GaussianQuadraturesTest::experimental() {\n    test_suite* suite = BOOST_TEST_SUITE(\n        \"Gaussian quadratures experimental tests\");\n\n    suite->add(QUANTLIB_TEST_CASE(\n        &GaussianQuadraturesTest::testNonCentralChiSquared));\n    suite->add(QUANTLIB_TEST_CASE(\n        &GaussianQuadraturesTest::testNonCentralChiSquaredSumOfNodes));\n\n    return suite;\n}\n", "meta": {"hexsha": "882200a222ef1dfbb500d8b621850cfb5eb821ca", "size": 13347, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test-suite/gaussianquadratures.cpp", "max_stars_repo_name": "j053g/QuantLib", "max_stars_repo_head_hexsha": "86869ef7429ce1a975c9e0ef15a69a9a3db8e0f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-27T17:17:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-27T17:17:12.000Z", "max_issues_repo_path": "test-suite/gaussianquadratures.cpp", "max_issues_repo_name": "j053g/QuantLib", "max_issues_repo_head_hexsha": "86869ef7429ce1a975c9e0ef15a69a9a3db8e0f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T06:35:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:00:09.000Z", "max_forks_repo_path": "test-suite/gaussianquadratures.cpp", "max_forks_repo_name": "j053g/QuantLib", "max_forks_repo_head_hexsha": "86869ef7429ce1a975c9e0ef15a69a9a3db8e0f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-04T15:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T08:24:37.000Z", "avg_line_length": 35.031496063, "max_line_length": 80, "alphanum_fraction": 0.609425339, "num_tokens": 3520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7217432062975978, "lm_q1q2_score": 0.6045465179950444}}
{"text": "#include <stan/math/fwd/scal.hpp>\n#include <gtest/gtest.h>\n#include <boost/math/special_functions/erf.hpp>\n#include <math/fwd/scal/fun/nan_util.hpp>\n\nTEST(AgradFwdErfc, Fvar) {\n  using stan::math::erfc;\n  using stan::math::fvar;\n  using std::exp;\n  using std::sqrt;\n\n  fvar<double> x(0.5, 1.0);\n\n  fvar<double> a = erfc(x);\n  EXPECT_FLOAT_EQ(erfc(0.5), a.val_);\n  EXPECT_FLOAT_EQ(\n      -2 * exp(-0.5 * 0.5) / sqrt(boost::math::constants::pi<double>()), a.d_);\n\n  fvar<double> b = erfc(-x);\n  EXPECT_FLOAT_EQ(erfc(-0.5), b.val_);\n  EXPECT_FLOAT_EQ(\n      2 * exp(-0.5 * 0.5) / sqrt(boost::math::constants::pi<double>()), b.d_);\n}\n\nTEST(AgradFwdErfc, FvarFvarDouble) {\n  using stan::math::erfc;\n  using stan::math::fvar;\n  using std::exp;\n  using std::sqrt;\n\n  fvar<fvar<double> > x;\n  x.val_.val_ = 0.5;\n  x.val_.d_ = 1.0;\n\n  fvar<fvar<double> > a = erfc(x);\n\n  EXPECT_FLOAT_EQ(erfc(0.5), a.val_.val_);\n  EXPECT_FLOAT_EQ(\n      -2 * exp(-0.5 * 0.5) / sqrt(boost::math::constants::pi<double>()),\n      a.val_.d_);\n  EXPECT_FLOAT_EQ(0, a.d_.val_);\n  EXPECT_FLOAT_EQ(0, a.d_.d_);\n\n  fvar<fvar<double> > y;\n  y.val_.val_ = 0.5;\n  y.d_.val_ = 1.0;\n\n  a = erfc(y);\n  EXPECT_FLOAT_EQ(erfc(0.5), a.val_.val_);\n  EXPECT_FLOAT_EQ(0, a.val_.d_);\n  EXPECT_FLOAT_EQ(\n      -2 * exp(-0.5 * 0.5) / sqrt(boost::math::constants::pi<double>()),\n      a.d_.val_);\n  EXPECT_FLOAT_EQ(0, a.d_.d_);\n}\n\nstruct erfc_fun {\n  template <typename T0>\n  inline T0 operator()(const T0& arg1) const {\n    return erfc(arg1);\n  }\n};\n\nTEST(AgradFwdErfc, erfc_NaN_0) {\n  erfc_fun erfc_;\n  test_nan_fwd(erfc_, false);\n}\n", "meta": {"hexsha": "8b2690f3dcf6fb136bb9cceba98937673786c2d0", "size": 1583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math_unit/math/fwd/scal/fun/erfc_test.cpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "tests/math_unit/math/fwd/scal/fun/erfc_test.cpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "tests/math_unit/math/fwd/scal/fun/erfc_test.cpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2794117647, "max_line_length": 79, "alphanum_fraction": 0.6266582438, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6045465129817225}}
{"text": "#include <opencv2/opencv.hpp>\n#include \"openbr_internal.h\"\n#include \"openbr/core/qtutils.h\"\n#include \"openbr/core/opencvutils.h\"\n#include \"openbr/core/eigenutils.h\"\n#include <QString>\n#include <Eigen/SVD>\n#include <Eigen/Dense>\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\nnamespace br\n{\n\n/*!\n * \\ingroup transforms\n * \\brief Procrustes alignment of points\n * \\author Scott Klum \\cite sklum\n */\nclass ProcrustesTransform : public Transform\n{\n    Q_OBJECT\n\n    Q_PROPERTY(bool warp READ get_warp WRITE set_warp RESET reset_warp STORED false)\n    BR_PROPERTY(bool, warp, true)\n\n    Eigen::MatrixXf meanShape;\n\n    void train(const TemplateList &data)\n    {\n        QList< QList<QPointF> > normalizedPoints;\n\n        // Normalize all sets of points\n        foreach (br::Template datum, data) {\n            QList<QPointF> points = datum.file.points();\n            QList<QRectF> rects = datum.file.rects();\n\n            if (points.empty() || rects.empty()) continue;\n\n            // Assume rect appended last was bounding box\n            points.append(rects.last().topLeft());\n            points.append(rects.last().topRight());\n            points.append(rects.last().bottomLeft());\n            points.append(rects.last().bottomRight());\n\n            // Center shape at origin\n            Scalar mean = cv::mean(OpenCVUtils::toPoints(points).toVector().toStdVector());\n            for (int i = 0; i < points.size(); i++) points[i] -= QPointF(mean[0],mean[1]);\n\n            // Remove scale component\n            float norm = cv::norm(OpenCVUtils::toPoints(points).toVector().toStdVector());\n            for (int i = 0; i < points.size(); i++) points[i] /= norm;\n\n            normalizedPoints.append(points);\n        }\n\n        if (normalizedPoints.empty()) qFatal(\"Unable to calculate normalized points\");\n\n        // Determine mean shape, assuming all shapes contain the same number of points\n        meanShape = Eigen::MatrixXf(normalizedPoints[0].size(), 2);\n\n        for (int i = 0; i < normalizedPoints[0].size(); i++) {\n            double x = 0;\n            double y = 0;\n\n            for (int j = 0; j < normalizedPoints.size(); j++) {\n                x += normalizedPoints[j][i].x();\n                y += normalizedPoints[j][i].y();\n            }\n\n            x /= (double)normalizedPoints.size();\n            y /= (double)normalizedPoints.size();\n\n            meanShape(i,0) = x;\n            meanShape(i,1) = y;\n        }\n    }\n\n    void project(const Template &src, Template &dst) const\n    {\n        QList<QPointF> points = src.file.points();\n        QList<QRectF> rects = src.file.rects();\n\n        if (points.empty() || rects.empty()) {\n            dst = src;\n            if (Globals->verbose) qWarning(\"Procrustes alignment failed because points or rects are empty.\");\n            return;\n        }\n\n        // Assume rect appended last was bounding box\n        points.append(rects.last().topLeft());\n        points.append(rects.last().topRight());\n        points.append(rects.last().bottomLeft());\n        points.append(rects.last().bottomRight());\n\n        Scalar mean = cv::mean(OpenCVUtils::toPoints(points).toVector().toStdVector());\n        for (int i = 0; i < points.size(); i++) points[i] -= QPointF(mean[0],mean[1]);\n\n        Eigen::MatrixXf srcMat(points.size(), 2);\n        float norm = cv::norm(OpenCVUtils::toPoints(points).toVector().toStdVector());\n        for (int i = 0; i < points.size(); i++) {\n            points[i] /= norm;\n            srcMat(i,0) = points[i].x();\n            srcMat(i,1) = points[i].y();\n        }\n\n        Eigen::JacobiSVD<Eigen::MatrixXf> svd(srcMat.transpose()*meanShape, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        Eigen::MatrixXf R = svd.matrixU()*svd.matrixV().transpose();\n\n        dst = src;\n\n        // Store procrustes stats in the order:\n        // R(0,0), R(1,0), R(1,1), R(0,1), mean_x, mean_y, norm\n        QList<float> procrustesStats;\n        procrustesStats << R(0,0) << R(1,0) << R(1,1) << R(0,1) << mean[0] << mean[1] << norm;\n        dst.file.setList<float>(\"ProcrustesStats\",procrustesStats);\n\n        if (warp) {\n            Eigen::MatrixXf dstMat = srcMat*R;\n            for (int i = 0; i < dstMat.rows(); i++) {\n                dst.file.appendPoint(QPointF(dstMat(i,0),dstMat(i,1)));\n            }\n        }\n    }\n\n    void store(QDataStream &stream) const\n    {\n        stream << meanShape;\n    }\n\n    void load(QDataStream &stream)\n    {\n        stream >> meanShape;\n    }\n\n};\n\nBR_REGISTER(Transform, ProcrustesTransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Creates a Delaunay triangulation based on a set of points\n * \\author Scott Klum \\cite sklum\n */\nclass DelaunayTransform : public Transform\n{\n    Q_OBJECT\n\n    Q_PROPERTY(float scaleFactor READ get_scaleFactor WRITE set_scaleFactor RESET reset_scaleFactor STORED false)\n    Q_PROPERTY(bool warp READ get_warp WRITE set_warp RESET reset_warp STORED false)\n    BR_PROPERTY(float, scaleFactor, 1)\n    BR_PROPERTY(bool, warp, true)\n\n    void project(const Template &src, Template &dst) const\n    {\n        QList<QPointF> points = src.file.points();\n        QList<QRectF> rects = src.file.rects();\n\n        if (points.empty() || rects.empty()) {\n            dst = src;\n            if (Globals->verbose) qWarning(\"Delauney triangulation failed because points or rects are empty.\");\n            return;\n        }\n\n        int cols = src.m().cols;\n        int rows = src.m().rows;\n\n        // Assume rect appended last was bounding box\n        points.append(rects.last().topLeft());\n        points.append(rects.last().topRight());\n        points.append(rects.last().bottomLeft());\n        points.append(rects.last().bottomRight());\n\n        Subdiv2D subdiv(Rect(0,0,cols,rows));\n        // Make sure points are valid for Subdiv2D\n        // TODO: Modify points to make them valid\n        for (int i = 0; i < points.size(); i++) {\n            if (points[i].x() < 0 || points[i].y() < 0 || points[i].y() >= rows || points[i].x() >= cols) {\n                dst = src;\n                if (Globals->verbose) qWarning(\"Delauney triangulation failed because points lie on boundary.\");\n                return;\n            }\n            subdiv.insert(OpenCVUtils::toPoint(points[i]));\n        }\n\n        vector<Vec6f> triangleList;\n        subdiv.getTriangleList(triangleList);\n\n        QList<QPointF> validTriangles;\n\n        for (size_t i = 0; i < triangleList.size(); i++) {\n            // Check the triangle to make sure it's falls within the matrix\n            bool valid = true;\n\n            QList<QPointF> vertices;\n            vertices.append(QPointF(triangleList[i][0],triangleList[i][1]));\n            vertices.append(QPointF(triangleList[i][2],triangleList[i][3]));\n            vertices.append(QPointF(triangleList[i][4],triangleList[i][5]));\n            for (int j = 0; j < 3; j++) if (vertices[j].x() > cols || vertices[j].y() > rows || vertices[j].x() < 0 || vertices[j].y() < 0) valid = false;\n\n            if (valid) validTriangles.append(vertices);\n        }\n\n        if (warp) {\n            dst.m() = Mat::zeros(rows,cols,src.m().type());\n\n            QList<float> procrustesStats = src.file.getList<float>(\"ProcrustesStats\");\n\n            Eigen::MatrixXf R(2,2);\n            R(0,0) = procrustesStats.at(0);\n            R(1,0) = procrustesStats.at(1);\n            R(1,1) = procrustesStats.at(2);\n            R(0,1) = procrustesStats.at(3);\n\n            cv::Scalar mean(2);\n            mean[0] = procrustesStats.at(4);\n            mean[1] = procrustesStats.at(5);\n\n            float norm = procrustesStats.at(6);\n\n            QList<Point2f> mappedPoints;\n\n            for (int i = 0; i < validTriangles.size(); i+=3) {\n                // Matrix to store original (pre-transformed) triangle vertices\n                Eigen::MatrixXf srcMat(3, 2);\n\n                for (int j = 0; j < 3; j++) {\n                    srcMat(j,0) = (validTriangles[i+j].x()-mean[0])/norm;\n                    srcMat(j,1) = (validTriangles[i+j].y()-mean[1])/norm;\n                }\n\n                Eigen::MatrixXf dstMat = srcMat*R;\n\n                Point2f srcPoints[3];\n                for (int j = 0; j < 3; j++) srcPoints[j] = OpenCVUtils::toPoint(validTriangles[i+j]);\n\n                Point2f dstPoints[3];\n                for (int j = 0; j < 3; j++) {\n                    // Scale and shift destination points\n                    Point2f warpedPoint = Point2f(dstMat(j,0)*scaleFactor+cols/2,dstMat(j,1)*scaleFactor+rows/2);\n                    dstPoints[j] = warpedPoint;\n                    mappedPoints.append(warpedPoint);\n                }\n\n                Mat buffer(rows,cols,src.m().type());\n\n                warpAffine(src.m(), buffer, getAffineTransform(srcPoints, dstPoints), Size(cols,rows));\n\n                Mat mask = Mat::zeros(rows, cols, CV_8UC1);\n                Point maskPoints[1][3];\n                maskPoints[0][0] = dstPoints[0];\n                maskPoints[0][1] = dstPoints[1];\n                maskPoints[0][2] = dstPoints[2];\n                const Point* ppt = { maskPoints[0] };\n\n                fillConvexPoly(mask, ppt, 3, Scalar(255,255,255), 8);\n\n                Mat output(rows,cols,src.m().type());\n\n                if (i > 0) {\n                    Mat overlap;\n                    bitwise_and(dst.m(),mask,overlap);\n                    mask.setTo(0, overlap!=0);\n                }\n\n                bitwise_and(buffer,mask,output);\n\n                dst.m() += output;\n            }\n\n            // Overwrite any rects\n            Rect boundingBox = boundingRect(mappedPoints.toVector().toStdVector());\n            dst.file.setRects(QList<QRectF>() << OpenCVUtils::fromRect(boundingBox));\n        } else dst = src;\n\n        dst.file.setList<QPointF>(\"DelaunayTriangles\", validTriangles);\n    }\n};\n\nBR_REGISTER(Transform, DelaunayTransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Creates a Delaunay triangulation based on a set of points\n * \\author Scott Klum \\cite sklum\n */\nclass DrawDelaunayTransform : public UntrainableTransform\n{\n    Q_OBJECT\n\n    void project(const Template &src, Template &dst) const\n    {\n        dst = src;\n\n        if (src.file.contains(\"DelaunayTriangles\")) {\n            QList<Point2f> validTriangles = OpenCVUtils::toPoints(src.file.getList<QPointF>(\"DelaunayTriangles\"));\n\n            // Clone the matrix do draw on it\n            for (int i = 0; i < validTriangles.size(); i+=3) {\n                line(dst, validTriangles[i], validTriangles[i+1], Scalar(0,0,0), 1);\n                line(dst, validTriangles[i+1], validTriangles[i+2], Scalar(0,0,0), 1);\n                line(dst, validTriangles[i+2], validTriangles[i], Scalar(0,0,0), 1);\n            }\n        } else qWarning(\"Template does not contain Delaunay triangulation.\");\n    }\n};\n\nBR_REGISTER(Transform, DrawDelaunayTransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Read landmarks from a file and associate them with the correct templates.\n * \\author Scott Klum \\cite sklum\n *\n * Example of the format:\n * \\code\n * image_001.jpg:146.000000,190.000000,227.000000,186.000000,202.000000,256.000000\n * image_002.jpg:75.000000,235.000000,140.000000,225.000000,91.000000,300.000000\n * image_003.jpg:158.000000,186.000000,246.000000,188.000000,208.000000,233.000000\n * \\endcode\n */\nclass ReadLandmarksTransform : public UntrainableTransform\n{\n    Q_OBJECT\n\n    Q_PROPERTY(QString file READ get_file WRITE set_file RESET reset_file STORED false)\n    Q_PROPERTY(QString imageDelimiter READ get_imageDelimiter WRITE set_imageDelimiter RESET reset_imageDelimiter STORED false)\n    Q_PROPERTY(QString landmarkDelimiter READ get_landmarkDelimiter WRITE set_landmarkDelimiter RESET reset_landmarkDelimiter STORED false)\n    BR_PROPERTY(QString, file, QString())\n    BR_PROPERTY(QString, imageDelimiter, \":\")\n    BR_PROPERTY(QString, landmarkDelimiter, \",\")\n\n    QHash<QString, QList<QPointF> > landmarks;\n\n    void init()\n    {\n        if (file.isEmpty())\n            return;\n\n        QFile f(file);\n        if (!f.open(QFile::ReadOnly | QFile::Text))\n            qFatal(\"Failed to open %s for reading.\", qPrintable(f.fileName()));\n\n        while (!f.atEnd()) {\n            const QStringList words = QString(f.readLine()).split(imageDelimiter);\n            const QStringList lm = words[1].split(landmarkDelimiter);\n\n            QList<QPointF> points;\n            bool ok;\n            for (int i=0; i<lm.size(); i+=2)\n                points.append(QPointF(lm[i].toFloat(&ok),lm[i+1].toFloat(&ok)));\n            if (!ok) qFatal(\"Failed to read landmark.\");\n\n            landmarks.insert(words[0],points);\n        }\n    }\n\n    void project(const Template &src, Template &dst) const\n    {\n        dst = src;\n\n        dst.file.appendPoints(landmarks[dst.file.fileName()]);\n    }\n};\n\nBR_REGISTER(Transform, ReadLandmarksTransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Name a point/rect\n * \\author Scott Klum \\cite sklum\n */\nclass NameLandmarksTransform : public UntrainableMetadataTransform\n{\n    Q_OBJECT\n    Q_PROPERTY(bool point READ get_point WRITE set_point RESET reset_point STORED false)\n    BR_PROPERTY(bool, point, true)\n    Q_PROPERTY(QList<int> indices READ get_indices WRITE set_indices RESET reset_indices STORED false)\n    Q_PROPERTY(QStringList names READ get_names WRITE set_names RESET reset_names STORED false)\n    BR_PROPERTY(QList<int>, indices, QList<int>())\n    BR_PROPERTY(QStringList, names, QStringList())\n\n    void projectMetadata(const File &src, File &dst) const\n    {\n        if (indices.size() != names.size()) qFatal(\"Index/name size mismatch\");\n\n        dst = src;\n\n        if (point) {\n            QList<QPointF> points = src.points();\n\n            for (int i=0; i<indices.size(); i++) {\n                if (indices[i] < points.size()) dst.set(names[i], points[indices[i]]);\n                else qFatal(\"Index out of range.\");\n            }\n        } else {\n            QList<QRectF> rects = src.rects();\n\n            for (int i=0; i<indices.size(); i++) {\n                if (indices[i] < rects.size()) dst.set(names[i], rects[indices[i]]);\n                else qFatal(\"Index out of range.\");\n            }\n        }\n    }\n};\n\nBR_REGISTER(Transform, NameLandmarksTransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Remove a name from a point/rect\n * \\author Scott Klum \\cite sklum\n */\nclass AnonymizeLandmarksTransform : public UntrainableMetadataTransform\n{\n    Q_OBJECT\n    Q_PROPERTY(QStringList names READ get_names WRITE set_names RESET reset_names STORED false)\n    BR_PROPERTY(QStringList, names, QStringList())\n\n    void projectMetadata(const File &src, File &dst) const\n    {\n        dst = src;\n\n        foreach (const QString &name, names) {\n            if (src.contains(name)) {\n                QVariant variant = src.value(name);\n                if (variant.canConvert(QMetaType::QPointF)) {\n                    dst.appendPoint(variant.toPointF());\n                } else if (variant.canConvert(QMetaType::QRectF)) {\n                    dst.appendRect(variant.toRectF());\n                } else {\n                    qFatal(\"Cannot convert landmark to point or rect.\");\n                }\n            }\n        }\n    }\n};\n\nBR_REGISTER(Transform, AnonymizeLandmarksTransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Converts either the file::points() list or a QList<QPointF> metadata item to be the template's matrix\n * \\author Scott Klum \\cite sklum\n */\nclass PointsToMatrixTransform : public UntrainableTransform\n{\n    Q_OBJECT\n\n    Q_PROPERTY(QString inputVariable READ get_inputVariable WRITE set_inputVariable RESET reset_inputVariable STORED false)\n    BR_PROPERTY(QString, inputVariable, QString())\n\n    void project(const Template &src, Template &dst) const\n    {\n        dst = src;\n\n        if (inputVariable.isEmpty()) {\n            dst.m() = OpenCVUtils::pointsToMatrix(dst.file.points());\n        } else {\n            if (src.file.contains(inputVariable))\n                dst.m() = OpenCVUtils::pointsToMatrix(dst.file.get<QList<QPointF> >(inputVariable));\n        }\n    }\n};\n\nBR_REGISTER(Transform, PointsToMatrixTransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Normalize points to be relative to a single point\n * \\author Scott Klum \\cite sklum\n */\nclass NormalizePointsTransform : public UntrainableTransform\n{\n    Q_OBJECT\n\n    Q_PROPERTY(int index READ get_index WRITE set_index RESET reset_index STORED false)\n    BR_PROPERTY(int, index, 0)\n\n    void project(const Template &src, Template &dst) const\n    {\n        dst = src;\n\n        QList<QPointF> points = dst.file.points();\n        QPointF normPoint = points.at(index);\n\n        QList<QPointF> normalizedPoints;\n\n        for (int i=0; i<points.size(); i++)\n            if (i!=index)\n                normalizedPoints.append(normPoint-points[i]);\n\n        dst.file.setPoints(normalizedPoints);\n    }\n};\n\nBR_REGISTER(Transform, NormalizePointsTransform)\n\n/*!\n * \\ingroup transforms\n * \\brief Normalize points to be relative to a single point\n * \\author Scott Klum \\cite sklum\n */\nclass PointDisplacementTransform : public UntrainableTransform\n{\n    Q_OBJECT\n\n    void project(const Template &src, Template &dst) const\n    {\n        dst = src;\n\n        QList<QPointF> points = dst.file.points();\n        QList<QPointF> normalizedPoints;\n\n        for (int i=0; i<points.size(); i++)\n            for (int j=0; j<points.size(); j++)\n                // There is redundant information here\n                if (j!=i) {\n                    QPointF normalizedPoint = points[i]-points[j];\n                    normalizedPoint.setX(pow(normalizedPoint.x(),2));\n                    normalizedPoint.setY(pow(normalizedPoint.y(),2));\n                    normalizedPoints.append(normalizedPoint);\n                }\n\n        dst.file.setPoints(normalizedPoints);\n    }\n};\n\nBR_REGISTER(Transform, PointDisplacementTransform)\n\n} // namespace br\n\n#include \"landmarks.moc\"\n", "meta": {"hexsha": "a76dc57ead3feca828e6de132d72a49938eeb516", "size": 17808, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbr/plugins/landmarks.cpp", "max_stars_repo_name": "clcarwin/openbr", "max_stars_repo_head_hexsha": "00700cc8c3d19df5ff08045ef1b19bacfbe22b25", "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": "openbr/plugins/landmarks.cpp", "max_issues_repo_name": "clcarwin/openbr", "max_issues_repo_head_hexsha": "00700cc8c3d19df5ff08045ef1b19bacfbe22b25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openbr/plugins/landmarks.cpp", "max_forks_repo_name": "clcarwin/openbr", "max_forks_repo_head_hexsha": "00700cc8c3d19df5ff08045ef1b19bacfbe22b25", "max_forks_repo_licenses": ["Apache-2.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.223880597, "max_line_length": 154, "alphanum_fraction": 0.5942834681, "num_tokens": 4326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6045465021172336}}
{"text": "////////////////////////////////////////////////////////////////////////////////////\n// The MIT License (MIT)                                                          //\n//                                                                                //\n// Copyright (c) 2015 Whit Armstrong                                              //\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#pragma once\n\n#include <stdexcept>\n#include <armadillo>\n\nnamespace armalogp {\n\n  static inline double square(double x) {\n    return x*x;\n  }\n\n  static inline int square(int x) {\n    return x*x;\n  }\n\n  double cholesky_determinant(const arma::mat& R) {\n    return arma::prod(square(R.diag()));\n  }\n\n  double mahalanobis(const arma::vec& x, const arma::vec& mu, const arma::mat& sigma) {\n    const arma::vec err = x - mu;\n    return arma::as_scalar(err.t() * sigma.i() * err);\n  }\n\n  double mahalanobis(const arma::rowvec& x, const arma::rowvec& mu, const arma::mat& sigma) {\n    const arma::rowvec err = x - mu;\n    return arma::as_scalar(err * sigma.i() * err.t());\n  }\n\n  double mahalanobis_chol(const arma::rowvec& x, const arma::rowvec& mu, const arma::mat& R) {\n    const arma::rowvec err = x - mu;\n    const arma::mat Rinv(inv(trimatl(R)));\n    return arma::as_scalar(err * Rinv * Rinv.t() * err.t());\n  }\n\n} // namespace armalogp\n\n", "meta": {"hexsha": "f4f6c534a7e2d3a9581adca307e9889d03733a65", "size": 2892, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "armalogp/arma.math.hpp", "max_stars_repo_name": "armaMCMC/arma-log-likelihood", "max_stars_repo_head_hexsha": "c8323afb0a99fbb69cdf738b7fbbde98432a7c66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "armalogp/arma.math.hpp", "max_issues_repo_name": "armaMCMC/arma-log-likelihood", "max_issues_repo_head_hexsha": "c8323afb0a99fbb69cdf738b7fbbde98432a7c66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "armalogp/arma.math.hpp", "max_forks_repo_name": "armaMCMC/arma-log-likelihood", "max_forks_repo_head_hexsha": "c8323afb0a99fbb69cdf738b7fbbde98432a7c66", "max_forks_repo_licenses": ["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.6451612903, "max_line_length": 94, "alphanum_fraction": 0.5058782849, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6045465021172336}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2020 Lew Wei Hao\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/exercise.hpp>\n#include <boost/function.hpp>\n#include <ql/math/integrals/simpsonintegral.hpp>\n#include \"analyticeuropeanvasicekengine.hpp\"\n#include <ql/math/distributions/normaldistribution.hpp>\n\nnamespace QuantLib {\n\n    namespace {\n\n        Real g_k(Real t, Real kappa){\n            return (1 - std::exp(- kappa * t )) / kappa;\n        }\n\n        class integrand_vasicek {\n          private:\n            const Real sigma_s_;\n            const Real sigma_r_;\n            const Real correlation_;\n            const Real kappa_;\n            const Real T_;\n          public:\n            integrand_vasicek(Real sigma_s, Real sigma_r, Real correlation, Real kappa, Real T)\n            : sigma_s_(sigma_s), sigma_r_(sigma_r), correlation_(correlation), kappa_(kappa), T_(T){}\n            Real operator()(Real u) const {\n                Real g = g_k(T_ - u, kappa_);\n                return (sigma_s_ * sigma_s_) + (2 * correlation_ * sigma_s_ * sigma_r_ * g) + (sigma_r_ * sigma_r_ * g * g);\n            }\n        };\n\n    }\n\n    AnalyticBlackVasicekEngine::AnalyticBlackVasicekEngine(\n            const ext::shared_ptr<GeneralizedBlackScholesProcess>& blackProcess,\n            const ext::shared_ptr<Vasicek>& vasicekProcess,\n            Real correlation)\n    : blackProcess_(blackProcess), vasicekProcess_(vasicekProcess), simpsonIntegral_(new SimpsonIntegral(1e-5, 1000)), correlation_(correlation) {\n        registerWith(blackProcess_);\n        registerWith(vasicekProcess_);\n    }\n\n    void AnalyticBlackVasicekEngine::calculate() const {\n        QL_REQUIRE(arguments_.exercise->type() == Exercise::European,\n                   \"not an European option\");\n\n        ext::shared_ptr<StrikedTypePayoff> payoff =\n                ext::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);\n\n        QL_REQUIRE(payoff, \"non-striked payoff given\");\n\n        CumulativeNormalDistribution f;\n\n        Real t = 0;\n        Real T = blackProcess_->riskFreeRate()->dayCounter().yearFraction(blackProcess_->riskFreeRate().currentLink()->referenceDate(),arguments_.exercise->lastDate());\n        Real kappa = vasicekProcess_->a();\n        Real S_t = blackProcess_->x0();\n        Real K = payoff->strike();\n        Real sigma_s = blackProcess_->blackVolatility()->blackVol(t, K);\n        Real sigma_r = vasicekProcess_->sigma();\n        Real r_t = vasicekProcess_->r0();\n\n        Real zcb = vasicekProcess_->discountBond(t, T, r_t);\n        Real epsilon = payoff->optionType() == Option::Call ? 1 : -1;\n        Real upsilon = (*simpsonIntegral_)(integrand_vasicek(sigma_s, sigma_r, correlation_, kappa, T), t, T);\n        Real d_positive = (std::log((S_t / K) / zcb) + upsilon / 2) / std::sqrt(upsilon);\n        Real d_negative = (std::log((S_t / K) / zcb) - upsilon / 2) / std::sqrt(upsilon);\n        Real n_d1 = f(epsilon * d_positive);\n        Real n_d2 = f(epsilon * d_negative);\n\n        results_.value = epsilon * ((S_t * n_d1) - (zcb * K * n_d2));\n    }\n\n}\n\n", "meta": {"hexsha": "10ee16d974ba37f63a50ff9861bc7903bac803bf", "size": 3761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/pricingengines/vanilla/analyticeuropeanvasicekengine.cpp", "max_stars_repo_name": "j053g/QuantLib", "max_stars_repo_head_hexsha": "86869ef7429ce1a975c9e0ef15a69a9a3db8e0f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-27T17:17:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-27T17:17:12.000Z", "max_issues_repo_path": "ql/pricingengines/vanilla/analyticeuropeanvasicekengine.cpp", "max_issues_repo_name": "j053g/QuantLib", "max_issues_repo_head_hexsha": "86869ef7429ce1a975c9e0ef15a69a9a3db8e0f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T06:35:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:00:09.000Z", "max_forks_repo_path": "ql/pricingengines/vanilla/analyticeuropeanvasicekengine.cpp", "max_forks_repo_name": "j053g/QuantLib", "max_forks_repo_head_hexsha": "86869ef7429ce1a975c9e0ef15a69a9a3db8e0f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-04T15:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T08:24:37.000Z", "avg_line_length": 40.0106382979, "max_line_length": 168, "alphanum_fraction": 0.6503589471, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.6825737279551493, "lm_q1q2_score": 0.6045087807993664}}
{"text": "#include \"point_to_plane.h\"\n#include <Eigen/Dense>\n\nusing namespace probreg;\n\nPt2PlResult probreg::computeTwistForPointToPlane(const MatrixX3& model,\n                                                 const MatrixX3& target,\n                                                 const MatrixX3& target_normal,\n                                                 const Vector& weight) {\n    Matrix6 ata = Matrix6::Zero();\n    Vector6 atb = Vector6::Zero();\n    Float r_sum = 0.0;\n\n    #pragma omp declare reduction(+ : Matrix6 : omp_out=omp_out+omp_in) initializer(omp_priv = omp_orig)\n    #pragma omp declare reduction(+ : Vector6 : omp_out=omp_out+omp_in) initializer(omp_priv = omp_orig)\n    #pragma omp parallel for reduction(+:ata) reduction(+:atb) reduction(+:r_sum)\n    for (auto k = 0; k < model.rows(); ++k){\n        const auto& vertex_k = model.row(k).transpose();\n        const auto& target_k = target.row(k).transpose();\n        const auto& normal_k = target_normal.row(k).transpose();\n        const auto& weight_k = weight[k];\n        const Float residual = normal_k.dot(target_k - vertex_k);\n        const Vector6 jac = (Vector6() << vertex_k.cross(normal_k), normal_k).finished();\n        const Matrix6 wjjt = weight_k * jac * jac.transpose();\n        const Vector6 wrj = weight_k * residual * jac;\n        const Float wr = weight_k * weight_k * residual * residual;\n        ata.noalias() += wjjt;\n        atb.noalias() += wrj;\n        r_sum += wr;\n    }\n    return std::make_pair(ata.selfadjointView<Eigen::Upper>().ldlt().solve(atb), r_sum);\n}\n", "meta": {"hexsha": "749a88f6a64ffea3782552a77047b63a7fc6b529", "size": 1550, "ext": "cc", "lang": "C++", "max_stars_repo_path": "probreg/cc/point_to_plane.cc", "max_stars_repo_name": "OscarPellicer/probreg", "max_stars_repo_head_hexsha": "8f1dd23dd86371b8040abad580332ff36967c078", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 479.0, "max_stars_repo_stars_event_min_datetime": "2019-03-06T16:24:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:38:54.000Z", "max_issues_repo_path": "probreg/cc/point_to_plane.cc", "max_issues_repo_name": "OscarPellicer/probreg", "max_issues_repo_head_hexsha": "8f1dd23dd86371b8040abad580332ff36967c078", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 86.0, "max_issues_repo_issues_event_min_datetime": "2019-05-15T19:10:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T06:14:54.000Z", "max_forks_repo_path": "probreg/cc/point_to_plane.cc", "max_forks_repo_name": "OscarPellicer/probreg", "max_forks_repo_head_hexsha": "8f1dd23dd86371b8040abad580332ff36967c078", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 101.0, "max_forks_repo_forks_event_min_datetime": "2019-03-21T08:52:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T19:13:39.000Z", "avg_line_length": 46.9696969697, "max_line_length": 104, "alphanum_fraction": 0.6006451613, "num_tokens": 377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.899121388082479, "lm_q2_score": 0.6723317123102955, "lm_q1q2_score": 0.6045078224243029}}
{"text": "/**\n * @file parametricfiniteelements_main.cc\n * @brief NPDE homework ParametricFiniteElements code\n * @author Am\u00e9lie Loher\n * @date 04.04.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include <vector>\n\n#include \"parametricfiniteelements.h\"\n\nusing namespace ParametricFiniteElements;\n\nint main() {\n  unsigned int n = 3;\n  Eigen::VectorXd mu((n + 1) * (n + 1));\n\n  // Psi \\in C^1([0,1]), Psi > 0\n  auto Psi = [](double x) -> double { return x * x + 1.0; };\n\n  // 1 <= alpha(x) <= 2\n  auto alpha = [](Eigen::Vector2d x) -> double { return 3.0 / 2.0; };\n\n  mu = geoThermSolve(n, alpha, Psi);\n\n  // Surface Integral over Gamma_S of expansion coefficient vector mu\n  double val = geoThermSurfInt(n, Psi, mu);\n\n  std::cout\n      << \"Basis Expansion Coefficient vector of solution Variational Problem: \"\n      << mu << std::endl;\n  std::cout << \"Value of expansion coefficient vector mu integrated over \"\n               \"Surface Gamma_S : \"\n            << val << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "89eb3d0aeddbb43dd5082c9750d74d96bdd0bc40", "size": 1087, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ParametricFiniteElements/templates/parametricfiniteelements_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ParametricFiniteElements/templates/parametricfiniteelements_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ParametricFiniteElements/templates/parametricfiniteelements_main.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 24.7045454545, "max_line_length": 79, "alphanum_fraction": 0.6412143514, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.604507812886312}}
{"text": "#include <fstream>\n#include <algorithm>\n#include <iterator>\n\n#include <boost/functional/value_factory.hpp>\n#include <boost/array.hpp>\n\n#include <CGAL/assertions.h>\n#include <CGAL/algorithm.h>\n#include <CGAL/point_generators_3.h>\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_traits.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/AABB_face_graph_triangle_primitive.h>\n#include <CGAL/Timer.h>\n\ntypedef CGAL::Epeck K;\ntypedef K::FT FT;\ntypedef K::Point_3 Point;\ntypedef K::Vector_3 Vector;\ntypedef K::Segment_3 Segment;\ntypedef K::Ray_3 Ray;\ntypedef CGAL::Polyhedron_3<K> Polyhedron;\ntypedef CGAL::AABB_face_graph_triangle_primitive<Polyhedron> Primitive;\ntypedef CGAL::AABB_traits<K, Primitive> Traits;\ntypedef CGAL::AABB_tree<Traits> Tree;\ntypedef Tree::Primitive_id Primitive_id;\ntypedef CGAL::Timer Timer;\n\nFT point_on_ray_dist(const Ray& ray, const Point& point) {\n  Vector i_ray(point, ray.source());\n  return i_ray.squared_length();\n}\n\nstd::size_t accum = 0;\n\nboost::optional<\n  Tree::Intersection_and_primitive_id<Ray>::Type\n  >\nmin_intersection(const Tree& tree, const Ray& ray) {\n  typedef std::vector< Tree::Intersection_and_primitive_id<Ray>::Type > IntersectionVector;\n  IntersectionVector all_intersections;\n\n  tree.all_intersections(ray, std::back_inserter(all_intersections));\n  accum += all_intersections.size();\n  Tree::FT min_distance = DBL_MAX;\n  boost::optional<\n    Tree::Intersection_and_primitive_id<Ray>::Type\n    > mini = boost::none;\n\n  for(IntersectionVector::iterator it2 = all_intersections.begin(); it2 != all_intersections.end(); ++it2) {\n    if(Point* point = boost::get<Point>(&(it2->first))) {\n      Vector i_ray(*point, ray.source());\n      Tree::FT new_distance = i_ray.squared_length();\n      if(new_distance < min_distance) {\n        mini = *it2;\n        min_distance = new_distance;\n      }\n    } else {\n      std::cout << \"ERROR ignored a segment\" << std::endl;\n    }\n  }\n  return mini;\n}\n\nint main()\n{\n  Polyhedron polyhedron;\n  {\n    // Point p(1.0, 0.0, 0.0);\n    // Point q(0.0, 1.0, 0.0);\n    // Point r(0.0, 0.0, 1.0);\n    // Point s(0.0, 0.0, 0.0);\n    // polyhedron.make_tetrahedron(p, q, r, s);\n  }\n\n  std::ifstream in(\"data/bunny00.off\");\n  if(in)\n    in >> polyhedron;\n  else{\n    std::cout << \"error reading bunny\" << std::endl;\n    return 1;\n  }\n\n  Timer t;\n  t.start();\n\n  Tree tree(faces(polyhedron).first, faces(polyhedron).second, polyhedron);\n  Tree::Bounding_box bbox = tree.bbox();\n  Vector bbox_center((bbox.xmin() + bbox.xmax()) / 2,\n                     (bbox.ymin() + bbox.ymax()) / 2,\n                     (bbox.zmin() + bbox.zmax()) / 2);\n  boost::array<double, 3> extents;\n  extents[0] = bbox.xmax() - bbox.xmin();\n  extents[1] = bbox.ymax() - bbox.ymin();\n  extents[2] = bbox.zmax() - bbox.zmin();\n  double max_extent = *std::max_element(extents.begin(), extents.end());\n\n  std::cout << bbox << std::endl;\n  std::cout << bbox_center << std::endl;\n  std::cout << max_extent << std::endl;\n\n  const int NB_RAYS = 1000;\n  std::vector<Point> v1, v2;\n  v1.reserve(NB_RAYS); v2.reserve(NB_RAYS);\n\n  const double r = max_extent / 2;\n  // Generate NB_RAYS*2 points that lie on a sphere of radius r, centered around bbox_center\n  CGAL::Random rand = CGAL::Random(23); // fix the seed to yield the same results each run\n  std::copy_n(CGAL::Random_points_on_sphere_3<Point>(r, rand), NB_RAYS, std::back_inserter(v1));\n  std::copy_n(CGAL::Random_points_on_sphere_3<Point>(r, rand), NB_RAYS, std::back_inserter(v2));\n\n  for(std::vector<Point>::iterator it = v1.begin(); it != v1.end(); ++it) {\n    *it = *it + bbox_center;\n  }\n\n  for(std::vector<Point>::iterator it = v2.begin(); it != v2.end(); ++it) {\n    *it = *it + bbox_center;\n  }\n\n  // Generate NB_RAYS using v1 as source and v2 as target.\n  std::vector<Ray> rays;\n  rays.reserve(NB_RAYS);\n  std::transform(v1.begin(), v1.end(), v2.begin(),\n                 std::back_inserter(rays), boost::value_factory<Ray>());\n  std::vector< boost::optional<Tree::Intersection_and_primitive_id<Ray>::Type > > primitives1, primitives2;\n  primitives1.reserve(NB_RAYS); primitives2.reserve(NB_RAYS);\n\n\n  {\n    for(std::vector<Ray>::iterator it = rays.begin(); it != rays.end(); ++it) {\n      primitives1.push_back(min_intersection(tree, *it));\n    }\n  }\n\n  for(std::vector<Ray>::iterator it = rays.begin(); it != rays.end(); ++it) {\n    primitives2.push_back(tree.first_intersection(*it));\n  }\n  assert(primitives1.size() == primitives2.size()); //  Different amount of primitives intersected\n  assert(std::equal(primitives1.begin(), primitives1.end(), primitives2.begin())); //  Primitives mismatch\n  std::size_t c = primitives1.size() - std::count(primitives1.begin(), primitives1.end(), boost::none);\n  std::cout << \"Intersected \" << c << \" primitives with \" << NB_RAYS << \" rays\" << std::endl;\n  std::cout << \"Primitive method had to sort \" << accum/NB_RAYS\n            << \" intersections on average.\" << std::endl;\n  t.stop();\n  std::cout << t.time() << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "4e86ed22d7fdd2dc89fc26ba0e1842c63850b151", "size": 5044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AABB_tree/test/AABB_tree/aabb_test_ray_intersection.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AABB_tree/test/AABB_tree/aabb_test_ray_intersection.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AABB_tree/test/AABB_tree/aabb_test_ray_intersection.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4039735099, "max_line_length": 108, "alphanum_fraction": 0.6661379857, "num_tokens": 1458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.6045077974451353}}
{"text": "#include <iostream>\n#include <stdexcept>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/QR>\n#include <Eigen/Eigenvalues>\n#include <Eigen/IterativeLinearSolvers>\n#include <unsupported/Eigen/IterativeSolvers>\n#include <chrono>\n\n#include \"DavidsonSolver.hpp\"\n\nDavidsonSolver::DavidsonSolver(){}\n\n\nvoid DavidsonSolver::set_correction(std::string method) {\n    if (method == \"DPR\") this->correction = CORR::DPR;\n    else if (method == \"JACOBI\") this->correction = CORR::JACOBI;\n    else if (method == \"OLSEN\") this->correction = CORR::OLSEN;\n    else throw std::runtime_error(\"Not a valid correction method\");\n}\n\nvoid DavidsonSolver::set_jacobi_linsolve(std::string method) {\n    if (method == \"CG\") this->jacobi_linsolve = LSOLVE::CG;\n    else if (method == \"GMRES\") this->jacobi_linsolve = LSOLVE::GMRES;\n    else if (method == \"LLT\") this->jacobi_linsolve = LSOLVE::LLT;   \n    else throw std::runtime_error(\"Not a valid linsolve method\");\n}\n\nEigen::ArrayXd DavidsonSolver::_sort_index(Eigen::VectorXd& V) const\n{\n    Eigen::ArrayXd idx = Eigen::ArrayXd::LinSpaced(V.rows(),0,V.rows()-1);\n    std::sort(idx.data(),idx.data()+idx.size(),\n              [&](int i1, int i2){return V[i1]<V[i2];});\n    return idx; \n}\n\nEigen::MatrixXd DavidsonSolver::_get_initial_eigenvectors(Eigen::VectorXd &d, int size_initial_guess) const\n{\n\n    Eigen::MatrixXd guess;\n    if (this->guess_vectors ==\"identity\")\n    {\n            guess = Eigen::MatrixXd::Identity(d.size(),size_initial_guess);\n    }\n\n    else if (this->guess_vectors == \"random\")\n    {\n        guess = Eigen::MatrixXd::Random(d.size(),size_initial_guess);\n        guess = DavidsonSolver::_QR(guess);\n    }\n    else if (this->guess_vectors==\"target\")\n    {\n        guess = Eigen::MatrixXd::Zero(d.size(),size_initial_guess);\n        Eigen::ArrayXd idx = DavidsonSolver::_sort_index(d);\n\n        for (int j=0; j<size_initial_guess;j++) {\n            guess(idx(j),j) = 1.0;\n        }\n    }\n    return guess;\n}\n\nEigen::MatrixXd DavidsonSolver::_solve_linear_system(Eigen::MatrixXd &A, Eigen::VectorXd &r) const\n{\n    Eigen::MatrixXd w;\n    std::chrono::time_point<std::chrono::system_clock> start, end;\n    std::chrono::duration<double> elapsed_time;\n\n    start = std::chrono::system_clock::now();\n    switch (this->jacobi_linsolve) {\n\n        case LSOLVE::CG :  {\n                Eigen::ConjugateGradient<Eigen::MatrixXd, Eigen::Lower|Eigen::Upper> cg;\n                cg.setTolerance(this->linsolve_tol);\n                cg.compute(A);\n                w = cg.solve(r); \n            }\n            break;\n        case LSOLVE::GMRES : {\n                Eigen::GMRES<Eigen::MatrixXd, Eigen::IdentityPreconditioner> gmres;\n                gmres.setTolerance(this->linsolve_tol);\n                gmres.compute(A);\n                w = gmres.solve(r);\n            }\n            break;\n        case LSOLVE::LLT : \n            w = A.llt().solve(r);\n            break;\n    }\n    end = std::chrono::system_clock::now();\n    elapsed_time  = end-start;\n    std::cout << \"_ solve linear system \" << this->jacobi_linsolve << \" in \" << elapsed_time.count() << \" secs\" <<  std::endl;\n    return w;\n}\n\nEigen::VectorXd DavidsonSolver::_olsen_correction(Eigen::VectorXd &r, Eigen::VectorXd &x, Eigen::VectorXd &D, double lambda) const\n{\n    /* Compute the olsen correction :\n\n    \\delta = (D-\\lambda)^{-1} (-r + \\epsilon x)\n\n    */\n\n    int size = r.rows();\n    Eigen::VectorXd delta = Eigen::VectorXd::Zero(size);\n\n    delta = DavidsonSolver::_dpr_correction(r,D,lambda);\n\n    double _num = - x.transpose() * delta;\n    double _denom = - x.transpose() * DavidsonSolver::_dpr_correction(x,D,lambda);\n    double eps = _num / _denom;\n    delta += eps * x;\n\n    return delta;\n}\n\nEigen::VectorXd DavidsonSolver::_dpr_correction(Eigen::VectorXd &w, Eigen::VectorXd &A0, double lambda) const\n{\n    int size = w.rows();\n    Eigen::VectorXd out = Eigen::VectorXd::Zero(size);\n    for (int i=0; i < size; i++) {\n        out(i) = w(i) / (lambda - A0(i));\n    }\n\n    return out;\n}\n\nEigen::MatrixXd DavidsonSolver::_QR(Eigen::MatrixXd &A) const\n{\n    \n    int nrows = A.rows();\n    int ncols = A.cols();\n    ncols = std::min(nrows,ncols);\n    \n    Eigen::HouseholderQR<Eigen::MatrixXd> qr(A);\n    return qr.householderQ() * Eigen::MatrixXd::Identity(nrows,ncols);\n}\n\n\nEigen::MatrixXd DavidsonSolver::_gramschmidt( Eigen::MatrixXd &A, int nstart ) const\n{\n    Eigen::MatrixXd Q = A;\n\n    for(unsigned int j = nstart; j < A.cols(); ++j) {\n        // Replace inner loop over each previous vector in Q with fast matrix-vector multiplication\n        Q.col(j) -= Q.leftCols(j) * (Q.leftCols(j).transpose() * A.col(j));\n        // Normalize vector if possible (othw. means colums of A almsost lin. dep.\n        if( Q.col(j).norm() <= 10e-14 * A.col(j).norm() ) {\n            std::cerr << \"Gram-Schmidt failed because A has lin. dep columns. Bye.\" << std::endl;\n            break;\n        } else {\n            Q.col(j).normalize();\n        }\n    }\n    return Q;\n}\n\n\n", "meta": {"hexsha": "3b7e441e204ee293c2550fa8120b46b41afe28ac", "size": 4984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/DavidsonSolver.cpp", "max_stars_repo_name": "NLESC-JCER/DavidsonEigen", "max_stars_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T17:22:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-26T17:40:44.000Z", "max_issues_repo_path": "src/DavidsonSolver.cpp", "max_issues_repo_name": "NLESC-JCER/DavidsonEigen", "max_issues_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-07T14:45:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-07T14:45:08.000Z", "max_forks_repo_path": "src/DavidsonSolver.cpp", "max_forks_repo_name": "NLESC-JCER/DavidsonEigen", "max_forks_repo_head_hexsha": "510ff7efe4bbe24906b5111e4a73837831d2fc84", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T22:56:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T09:05:37.000Z", "avg_line_length": 31.15, "max_line_length": 130, "alphanum_fraction": 0.6127608347, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6043910585652688}}
{"text": "// ===========================================================================\n// Imagine++ Libraries\n// Copyright (C) Imagine\n// For detailed information: http://imagine.enpc.fr/software\n// ===========================================================================\n\n#include \"Imagine/LinAlg/MyEigen.h\"\n#include <Eigen/Dense>\n#include <iostream>\nusing namespace Eigen;\n\ntemplate <typename T>\nvoid subSymToMatrix (int n, const T *ap, T *t)\n{\n    for (int i = 0 ; i < n ; i++)\n        for (int j = 0 ; j <= i ; j++)\n        {\n            t[i + n * j] = ap[j + (i * (i + 1) / 2)];\n            t[j + n * i] = t[i + n * j];\n        }\n}\n\nvoid symToMatrix(int n, const double *ap, double *t) { subSymToMatrix<double>(n, ap, t); }\nvoid symToMatrix(int n, const float *ap, float *t) { subSymToMatrix<float>(n, ap, t); }\n\n// Vectors equalization (replaces xcopy)\ntemplate <typename T>\nvoid subEqualize(int n, const T *s, int a, T *t, int b)\n{\n    Map<const Matrix<T, Dynamic, 1>, 0, InnerStride<> > sMap (s, n, InnerStride<>(a));\n    Map<Matrix<T, Dynamic, 1>, 0, InnerStride<> > tMap (t, n, InnerStride<>(b));\n    tMap = sMap;\n}\n\nvoid equalize(int n, const double *s, int a, double *t, int b) { subEqualize<double>(n, s, a, t, b); }\nvoid equalize(int n, const float *s, int a, float *t, int b) { subEqualize<float>(n, s, a, t, b); }\n\n// Linear combination alpha * X + Y\ntemplate <typename T>\nvoid subCombine(int n, T alpha, const T *X, T *Y) \n{ \n    Map<const Matrix<T, Dynamic, 1>, 0, InnerStride<> > sMap (X, n, InnerStride<>(1));\n    Map<Matrix<T, Dynamic, 1>, 0, InnerStride<> > tMap (Y, n, InnerStride<>(1));\n    tMap = alpha * sMap + tMap;\n}\n\nvoid combine(int n, double alpha, const double *X, double *Y) { subCombine<double>(n, alpha, X, Y); }\nvoid combine(int n, float alpha, const float *X, float *Y) { subCombine<float>(n, alpha, X, Y); }\n\n// Scalar product\ntemplate <typename T>\nT subScalarProduct(int n, const T *X, const T *Y)\n{ \n    Map<const Matrix<T, Dynamic, 1>, 0, InnerStride<> > sMap (X, n, InnerStride<>(1));\n    Map<const Matrix<T, Dynamic, 1>, 0, InnerStride<> > tMap (Y, n, InnerStride<>(1));\n    double s = sMap.dot(tMap);\n    return T(s);\n}\n\ndouble scalarProduct(int n, const double *X, const double *Y) { return subScalarProduct<double>(n, X, Y); }\nfloat scalarProduct(int n, const float *X, const float *Y) { return subScalarProduct<float>(n, X, Y); }\n\n// Product by a number\ntemplate <typename T>\nvoid subMultiply(int n, T alpha, T *X)\n{\n    Map<Matrix<T, Dynamic, 1>, 0, InnerStride<> > XMap (X, n, InnerStride<>(1));\n    XMap = alpha * XMap; \n}\n\nvoid multiply(int n, double alpha, double *X) { subMultiply<double>(n, alpha, X); }\nvoid multiply(int n, float alpha, float *X) { subMultiply<float>(n, alpha, X); }\n\n// Norm 2 (euclidian)\ntemplate <typename T>\nT subSquaredNorm(int n, const T *X)\n{\n    Map<const Matrix<T, Dynamic, 1>, 0, InnerStride<> > XMap (X, n, InnerStride<>(1));\n    return ((T) XMap.squaredNorm());\n}\n\ndouble squaredNorm(int n, const double *X) { return subSquaredNorm<double>(n, X); }\nfloat squaredNorm(int n, const float *X) { return subSquaredNorm<float>(n, X); }\n\n// Affine transformation Y <- alpha * [A, A transpose, A adjoint] * X + beta * B (replaces xgemv)\ntemplate <typename T>\nvoid subAffinity(int m, int n, T alpha, const T *A, const T *X, T beta, T *Y, char t)\n{\n    Map<const Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > AMap (A, m, n, OuterStride<>(m));\n\n    if (!(t == 'T' || t == 'C'))\n    {\n        int tmp = m;\n        m = n;\n        n = tmp;\n    }\n\n    Map<const Matrix<T, Dynamic, 1>, 0, InnerStride<> > XMap (X, m, InnerStride<>(1));\n    Map<Matrix<T, Dynamic, 1>, 0, InnerStride<> > YMap (Y, n, InnerStride<>(1));\n\n    if (t == 'T') YMap = alpha * AMap.transpose() * XMap + beta * YMap;\n    else if (t == 'C') YMap = alpha * AMap.adjoint() * XMap + beta * YMap;\n    else YMap = alpha * AMap * XMap + beta * YMap;\n}\n\nvoid affinity(int m, int n, double alpha, const double *A, const double *X, double beta, double *Y, char t) { subAffinity<double>(m, n, alpha, A, X, beta, Y, t); }\nvoid affinity(int m, int n, float alpha, const float *A, const float *X, float beta, float *Y, char t) { subAffinity<float>(m, n, alpha, A, X, beta, Y, t); }\n\n// Matrix product C <- alpha * [A, A transpose, A adjoint] * [B, B transpose, B adjoint] + beta * C (replaces xgemm)\ntemplate <typename T>\nvoid subMatrixProduct(int m, int n, int K, T alpha, const T *A, int lda, const T *B, int ldb, T beta, T *C, char t1, char t2) \n{\n\n    Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > CMap (C, m, n, OuterStride<>(m));\n\n    if (!(t1 == 'T' || t1 == 'C'))\n    {\n        int tmp = m;\n        m = K;\n        K = tmp;\n    }\n\n    Map<const Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > AMap (A, K, m, OuterStride<>(lda));\n\n    if (!(t1 == 'T' || t1 == 'C'))\n    {\n        int tmp = m;\n        m = K;\n        K = tmp;\n    }\n\n    if (!(t2 == 'T' || t2 == 'C'))\n    {\n        int tmp = n;\n        n = K;\n        K = tmp;\n    }\n\n    Map<const Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > BMap (B, n, K, OuterStride<>(ldb));\n\n    if (t1 == 'T') \n        if (t2 == 'T') CMap = alpha * AMap.transpose() * BMap.transpose() + beta * CMap;\n        else if (t2 == 'C') CMap = alpha * AMap.transpose() * BMap.adjoint() + beta * CMap;\n        else CMap = alpha * AMap.transpose() * BMap + beta * CMap;\n    else if (t1 == 'C')\n        if (t2 == 'T') CMap = alpha * AMap.adjoint() * BMap.transpose() + beta * CMap;\n        else if (t2 == 'C') CMap = alpha * AMap.adjoint() * BMap.adjoint() + beta * CMap;\n        else CMap = alpha * AMap.adjoint() * BMap + beta * CMap;\n    else\n        if (t2 == 'T') CMap = alpha * AMap * BMap.transpose() + beta * CMap;\n        else if (t2 == 'C') CMap = alpha * AMap * BMap.adjoint() + beta * CMap;\n        else CMap = alpha * AMap * BMap + beta * CMap;\n} \n\nvoid matrixProduct(int m, int n, int K, double alpha, const double *A, int lda, const double *B, int ldb, double beta, double *C, char t1, char t2) { subMatrixProduct<double>(m, n, K, alpha, A, lda, B, ldb, beta, C, t1, t2); }\nvoid matrixProduct(int m, int n, int K, float alpha, const float *A, int lda, const float *B, int ldb, float beta, float *C, char t1, char t2) { subMatrixProduct<float>(m, n, K, alpha, A, lda, B, ldb, beta, C, t1, t2); }\n\n// Matrix/vector product (replaces xspmv)\ntemplate <typename T>\nvoid subVectorProduct(int n,T alpha,const T *ap,const T *x,T beta,T* y)\n{\n    T* t=new T [n * n];\n    Map<const Matrix<T, Dynamic, 1>, 0, InnerStride<> > XMap (x, n, InnerStride<>(1));\n    Map<Matrix<T, Dynamic, 1>, 0, InnerStride<> > YMap (y, n, InnerStride<>(1));\n    symToMatrix(n, ap, t);\n    Map<Matrix<T, Dynamic, Dynamic>, 0, OuterStride<> > apMap (t, n, n, OuterStride<>(n));\n    YMap = alpha * apMap * XMap + beta * YMap;\n    delete[] t;\n}\n\nvoid vectorProduct(int n,double alpha,const double *ap, const double *x,double beta,double* y) { subVectorProduct<double>(n, alpha, ap, x, beta, y); }\nvoid vectorProduct(int n,float alpha,const float *ap,const float *x,float beta,float* y) { subVectorProduct<float>(n, alpha, ap, x, beta, y); }\n\n// TODO:\n//info=0 si succes, -i si le ieme parametre a une valeure illegale, i si u(i,i);=0 (transformation LU impossible = mineurs principaux tous nuls)\n// LU-inverse\ntemplate <typename T>\nvoid subMatrixInverse(int *n, T *a,int *lda,int *ipiv,int *info) \n{ \n    Map<Matrix<T, Dynamic, Dynamic> > AMap (a,*n,*n);\n    Map<VectorXi> pMap (ipiv, *n);\n    Eigen::FullPivLU<Matrix<T, Dynamic, Dynamic> > lu(AMap);\n    MatrixXi P = lu.permutationP();\n    MatrixXi Pi = pMap;\n\n    for (int i = 0 ; i < P.rows() - 1 ; i++)\n        for (int j = i + 1 ; j < P.cols() ; j++)\n            if (P(i, j) == 1) { Pi(i) = j; Pi(j) = i; };\n\n    //pMap = Pi;\n\n    if(lu.isInvertible() && AMap.isApprox(lu.reconstructedMatrix()))\n    {\n        AMap = lu.inverse();\n        *info = 0;\n    }\n    else *info = 1;\n}\n\nvoid matrixInverse(int *n, double *a,int *lda,int *ipiv,int *info) { subMatrixInverse<double>(n, a, lda, ipiv, info); }\nvoid matrixInverse(int *n, float *a,int *lda,int *ipiv,int *info) { subMatrixInverse<float>(n, a, lda, ipiv, info); }\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "fa656daa7f0ec7acdf70cdc985c92cb253d9c542", "size": 8127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Imagine/LinAlg/src/MyEigen1.cpp", "max_stars_repo_name": "Ethiy/imagine-pp", "max_stars_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Imagine/LinAlg/src/MyEigen1.cpp", "max_issues_repo_name": "Ethiy/imagine-pp", "max_issues_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Imagine/LinAlg/src/MyEigen1.cpp", "max_forks_repo_name": "Ethiy/imagine-pp", "max_forks_repo_head_hexsha": "67606ce0e2b3c6b957a0fe20e8f2ef62a6af5689", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1549295775, "max_line_length": 226, "alphanum_fraction": 0.5818875354, "num_tokens": 2661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6043910555847744}}
{"text": "//\n// Created by Hamza El-Kebir on 6/19/21.\n//\n\n#include \"catchOnce.hpp\"\n#include \"Lodestar/primitives/integrators/RungeKuttaFehlberg78.hpp\"\n#include <Eigen/Dense>\n\nTEST_CASE(\"Runge-Kutta-Fehlberg 78\", \"[primitives][integrators]\")\n{\n    std::function<double(double, double)> f = [](double t, double y) {\n        return t * t * t;\n    };\n\n    typedef Eigen::Matrix<double, 3, 1> TDStateVector;\n    std::function<TDStateVector(double, const TDStateVector&)> F = [](double t, const TDStateVector &x) {\n        TDStateVector xdot;\n        xdot << t, t*t, t*t*t;\n\n        return xdot;\n    };\n\n    SECTION(\"Higher order\") {\n        double t = 0, y = 0;\n        double h = 0.025;\n        int N = 20;\n        ls::primitives::RungeKuttaFehlberg78<double>::integrateSimple(f, t, y, h, N);\n\n        REQUIRE(y == Approx(0.015625));\n    }\n\n    SECTION(\"Multivariate\") {\n        double t = 0;\n        TDStateVector x;\n        x.setZero();\n//        x.array() += 2;\n\n        double h = 0.025;\n        int N = 20;\n        ls::primitives::RungeKuttaFehlberg78<TDStateVector>::integrateSimple(F, t, x, h, N);\n\n        REQUIRE(x(0) == Approx(0.125));\n        REQUIRE(x(1) == Approx(0.0416667));\n        REQUIRE(x(2) == Approx( 0.015625));\n    }\n\n    SECTION(\"Truncation error\") {\n        double t = 0, y = 0;\n        double h = 0.5;\n        int N = 1;\n        auto err = ls::primitives::RungeKuttaFehlberg78<double>::integrateEmbedded(f, t, y, h, N);\n\n        REQUIRE(y == Approx(0.015625));\n    }\n}", "meta": {"hexsha": "97b0d284d731098592767b43c09062807ff6e3e9", "size": 1480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/primitives/integrators/RungeKuttaFehlberg78_test.cpp", "max_stars_repo_name": "helkebir/Lodestar", "max_stars_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T14:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T22:15:31.000Z", "max_issues_repo_path": "tests/primitives/integrators/RungeKuttaFehlberg78_test.cpp", "max_issues_repo_name": "helkebir/Lodestar", "max_issues_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T15:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T17:43:20.000Z", "max_forks_repo_path": "tests/primitives/integrators/RungeKuttaFehlberg78_test.cpp", "max_forks_repo_name": "helkebir/Lodestar", "max_forks_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T03:15:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T03:15:23.000Z", "avg_line_length": 26.9090909091, "max_line_length": 105, "alphanum_fraction": 0.5655405405, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.604391053830894}}
{"text": "#include <fstream>\n#include <boost/config.hpp>\n#include <boost/version.hpp>\n// CGAL headers\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/Orthogonal_k_neighbor_search.h>\n#include <CGAL/Search_traits_2.h>\n\n// Qt headers\n#include <QtGui>\n#include <QString>\n#include <QFileDialog>\n#include <QInputDialog>\n#include <QGraphicsLineItem>\n\n// GraphicsView items and event filters (input classes)\n#include <CGAL/Qt/PointsInKdTreeGraphicsItem.h>\n#include <CGAL/Qt/utility.h>\n#include <CGAL/IO/WKT.h>\n\n// the two base classes\n#include \"ui_Spatial_searching_2.h\"\n#include <CGAL/Qt/DemosMainWindow.h>\n\n#include \"NearestNeighbor.h\"\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\ntypedef K::Vector_2 Vector_2;\ntypedef K::Segment_2 Segment_2;\ntypedef K::Iso_rectangle_2 Iso_rectangle_2;\ntypedef CGAL::Search_traits_2<K> TreeTraits;\ntypedef CGAL::Orthogonal_k_neighbor_search<TreeTraits> Neighbor_search;\ntypedef Neighbor_search::Tree Tree;\n\ntypedef CGAL::Qt::NearestNeighbor<Neighbor_search> NearestNeighbor;\n\nclass MainWindow :\n  public CGAL::Qt::DemosMainWindow,\n  public Ui::Spatial_searching_2\n{\n  Q_OBJECT\n\nprivate:\n  Tree tree;\n\n  CGAL::Qt::Converter<K> convert;\n  QGraphicsScene scene;\n\n  CGAL::Qt::PointsInKdTreeGraphicsItem<Tree> * pgi;\n  NearestNeighbor * nearest_neighbor;\n\npublic:\n  MainWindow();\n\n  template <typename G>\n  void\n  on_actionGenerate_triggered()\n  {\n\n    QRectF rect = CGAL::Qt::viewportsBbox(&scene);\n    CGAL::Qt::Converter<K> convert;\n    Iso_rectangle_2 isor = convert(rect);\n    Point_2 center = CGAL::midpoint(isor[0], isor[2]);\n    Vector_2 offset = center - CGAL::ORIGIN;\n    double w = isor.xmax() - isor.xmin();\n    double h = isor.ymax() - isor.ymin();\n    double radius = (w<h) ? w/2 : h/2;\n\n    G pg(radius);\n    bool ok = false;\n\n    const int number_of_points =\n      QInputDialog::getInt(this,\n                               tr(\"Number of random points\"),\n                               tr(\"Enter number of random points\"),\n                               100,\n                               0,\n                               (std::numeric_limits<int>::max)(),\n                               1,\n                               &ok);\n\n    if(!ok) {\n      return;\n    }\n\n    // wait cursor\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n\n    std::vector<Point_2> points;\n\n    points.reserve(number_of_points);\n    for(int i = 0; i < number_of_points; ++i){\n      points.push_back(*pg + offset);\n      ++pg;\n    }\n    tree.insert(points.begin(), points.end());\n\n    // default cursor\n    QApplication::restoreOverrideCursor();\n    Q_EMIT( changed());\n  }\n\npublic Q_SLOTS:\n\n  virtual void open(QString fileName);\n  void N_changed(int i);\n  void on_actionClear_triggered();\n  void on_actionLoadPoints_triggered();\n  void on_actionRecenter_triggered();\n  void on_actionGeneratePointsOnCircle_triggered();\n  void on_actionGeneratePointsInSquare_triggered();\n  void on_actionGeneratePointsInDisc_triggered();\n\n  void clear();\n\nQ_SIGNALS:\n  void changed();\n};\n\n\nMainWindow::MainWindow()\n  : DemosMainWindow()\n{\n  setupUi(this);\n\n  this->graphicsView->setAcceptDrops(false);\n  this->graphicsView->setCursor(Qt::CrossCursor);\n\n  // Add a GraphicItem for the point set\n  pgi = new CGAL::Qt::PointsInKdTreeGraphicsItem<Tree>(&tree);\n\n  QObject::connect(this, SIGNAL(changed()),\n                   pgi, SLOT(modelChanged()));\n\n  pgi->setVerticesPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.addItem(pgi);\n\n  nearest_neighbor = new NearestNeighbor(&scene, &tree, this, this->nn->value());\n  nearest_neighbor->setPen(QPen(Qt::red, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n  scene.installEventFilter(nearest_neighbor);\n\n  //\n  // Manual handling of actions\n  //\n\n  QObject::connect(this->nn, SIGNAL(valueChanged(int)),\n                   this, SLOT(N_changed(int)));\n\n  QObject::connect(this->actionQuit, SIGNAL(triggered()),\n                   this, SLOT(close()));\n\n\n  //\n  // Setup the scene and the view\n  //\n  scene.setItemIndexMethod(QGraphicsScene::NoIndex);\n  scene.setSceneRect(0, 0, 10, 10);\n  this->graphicsView->setScene(&scene);\n  this->graphicsView->setMouseTracking(true);\n\n  // Uncomment the following line to get antialiasing by default.\n//   actionUse_Antialiasing->setChecked(true);\n\n  // Turn the vertical axis upside down\n  this->graphicsView->scale(1, -1);\n\n  // The navigation adds zooming and translation functionality to the\n  // QGraphicsView\n  this->addNavigation(this->graphicsView);\n\n  this->setupStatusBar();\n  this->setupOptionsMenu();\n  this->addAboutDemo(\":/cgal/help/about_Spatial_searching_2.html\");\n  this->addAboutCGAL();\n\n  this->addRecentFiles(this->menuFile, this->actionQuit);\n  connect(this, SIGNAL(openRecentFile(QString)),\n          this, SLOT(open(QString)));\n}\n\n\n\nvoid MainWindow::N_changed(int i)\n{\n  nearest_neighbor->setN(i);\n  Q_EMIT( changed());\n}\n\n\n/*\n *  Qt Automatic Connections\n *  https://doc.qt.io/qt-5/designer-using-a-ui-file.html#automatic-connections\n *\n *  setupUi(this) generates connections to the slots named\n *  \"on_<action_name>_<signal_name>\"\n */\n\n\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n  clear();\n  Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n  if(tree.empty()){\n    return;\n  }\n  this->graphicsView->setSceneRect(pgi->boundingRect());\n  this->graphicsView->fitInView(pgi->boundingRect(), Qt::KeepAspectRatio);\n}\n\nvoid\nMainWindow::on_actionGeneratePointsOnCircle_triggered()\n{\n  typedef CGAL::Random_points_on_circle_2<Point_2> Generator;\n  on_actionGenerate_triggered<Generator>();\n}\n\n\nvoid\nMainWindow::on_actionGeneratePointsInSquare_triggered()\n{\n  typedef CGAL::Random_points_in_square_2<Point_2> Generator;\n  on_actionGenerate_triggered<Generator>();\n}\n\n\nvoid\nMainWindow::on_actionGeneratePointsInDisc_triggered()\n{\n  typedef CGAL::Random_points_in_disc_2<Point_2> Generator;\n  on_actionGenerate_triggered<Generator>();\n}\n\n\nvoid\nMainWindow::on_actionLoadPoints_triggered()\n{\n  QString fileName = QFileDialog::getOpenFileName(this,\n                                                  tr(\"Open Points file\"),\n                                                  \".\",\n                                                  tr(\"CGAL files (*.pts.cgal);;\"\n                                                     \"WKT files (*.wkt *.WKT);;\"\n                                                     \"All files (*)\"));\n  if(! fileName.isEmpty()){\n    open(fileName);\n  }\n}\n\n\n\nvoid\nMainWindow::open(QString fileName)\n{\n  // wait cursor\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n  std::ifstream ifs(qPrintable(fileName));\n\n  K::Point_2 p;\n  std::vector<K::Point_2> points;\n  if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n  {\n    CGAL::IO::read_multi_point_WKT(ifs, points);\n  }\n  else{\n    while(ifs >> p) {\n      points.push_back(p);\n    }\n  }\n  tree.insert(points.begin(), points.end());\n\n  // default cursor\n  QApplication::restoreOverrideCursor();\n  this->addToRecentFiles(fileName);\n  actionRecenter->trigger();\n  Q_EMIT( changed());\n\n}\n\nvoid\nMainWindow::clear()\n{\n  tree.clear();\n}\n\n\n#include \"Spatial_searching_2.moc\"\n#include <CGAL/Qt/resources.h>\n\nint main(int argc, char **argv)\n{\n  QApplication app(argc, argv);\n\n  app.setOrganizationDomain(\"geometryfactory.com\");\n  app.setOrganizationName(\"GeometryFactory\");\n  app.setApplicationName(\"Spatial_searching_2 demo\");\n\n  // Import resources from libCGAL (Qt5).\n  // See https://doc.qt.io/qt-5/qdir.html#Q_INIT_RESOURCE\n  CGAL_QT_INIT_RESOURCES;\n  Q_INIT_RESOURCE(Spatial_searching_2);\n\n  MainWindow mainWindow;\n  mainWindow.show();\n  mainWindow.on_actionRecenter_triggered();\n  return app.exec();\n}\n", "meta": {"hexsha": "d25a215c8cc0609dda022970e34d140012331ec5", "size": 7723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphicsView/demo/Spatial_searching_2/Spatial_searching_2.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "GraphicsView/demo/Spatial_searching_2/Spatial_searching_2.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "GraphicsView/demo/Spatial_searching_2/Spatial_searching_2.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 24.5174603175, "max_line_length": 89, "alphanum_fraction": 0.6716301955, "num_tokens": 1879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118111485244, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6043747615948774}}
{"text": "/**\n * @file expfittedupwind_test.cc\n * @brief NPDE homework ExpFittedUpwind\n * @author Am\u00e9lie Loher, Philippe Peter\n * @date 07.01.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"../expfittedupwind.h\"\n\n#include <gtest/gtest.h>\n#include <lf/assemble/assemble.h>\n#include <lf/mesh/test_utils/test_meshes.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <cmath>\n#include <memory>\n#include <vector>\n\nnamespace ExpFittedUpwind::test {\n\n// The Bernoulli function should be monotonically decreasing\nTEST(Bernoulli, Monotinicity) {\n  std::vector<double> values = {3.0,     1.5,    0.5,     1.0E-5,\n                                1.0E-7,  1.0E-9, -1.0E-9, -1.0E-7,\n                                -1.0E-5, -1.0,   -5.0,    -6.0};\n\n  for (int i = 0; i < values.size() - 1; ++i) {\n    EXPECT_LE(Bernoulli(values[i]), Bernoulli(values[i + 1]));\n  }\n}\n\n// Check that B(tau) does not explode for small tau\nTEST(Bernoulli, Cancellation) {\n  for (double i = 8.0; i >= std::numeric_limits<double>::min(); i /= 2.0) {\n    EXPECT_LE(std::abs(Bernoulli(i)), 2.0);\n  }\n}\n\n// Check that B(log(2)) = log(2)\nTEST(Bernoulli, Evaluation) {\n  EXPECT_NEAR(Bernoulli(std::log(2)), std::log(2), 1.0E-8);\n}\n\n// For Psi = c, all entries of beta are given by beta(e) = std::exp(c)\nTEST(CompBeta, ConstantPSI) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(4, 1.0);\n  auto mf_Psi = lf::mesh::utils::MeshFunctionGlobal(\n      [](Eigen::Vector2d /*x*/) { return 3.1; });\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  Eigen::VectorXd mu = lf::fe::NodalProjection(*fe_space, mf_Psi);\n  double ref = std::exp(3.1);\n\n  auto beta = CompBeta(mesh_p, mu);\n\n  for (auto entity : mesh_p->Entities(1)) {\n    EXPECT_DOUBLE_EQ((*beta)(*entity), ref);\n  }\n}\n\n// Verify the computation of beta for a linear psi\n// based on precomputed reference values on a test mesh.\nTEST(CompBeta, linearPSI) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  auto mf_Psi = lf::mesh::utils::MeshFunctionGlobal(\n      [](Eigen::Vector2d x) { return 1.0 + x(0) + 2 * x(1); });\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  Eigen::VectorXd mu = lf::fe::NodalProjection(*fe_space, mf_Psi);\n\n  auto beta = CompBeta(mesh_p, mu);\n  auto edges = mesh_p->Entities(1);\n\n  // edges of triangle 0\n  EXPECT_DOUBLE_EQ((*beta)(*(edges[0])), std::exp(2.5) * Bernoulli(1.5));\n  EXPECT_DOUBLE_EQ((*beta)(*(edges[1])), std::exp(4.0) * Bernoulli(3.0));\n  EXPECT_DOUBLE_EQ((*beta)(*(edges[2])), std::exp(4.0) * Bernoulli(3.0));\n\n  // edges of triangle 6:\n  EXPECT_DOUBLE_EQ((*beta)(*(edges[12])), std::exp(6.0) * Bernoulli(1.0));\n  EXPECT_DOUBLE_EQ((*beta)(*(edges[13])), std::exp(6.0) * Bernoulli(1.0));\n  EXPECT_DOUBLE_EQ((*beta)(*(edges[14])), std::exp(6.0) * Bernoulli(0.0));\n\n  // edges of triangle 11\n  EXPECT_DOUBLE_EQ((*beta)(*(edges[18])), std::exp(6.0) * Bernoulli(0.0));\n  EXPECT_DOUBLE_EQ((*beta)(*(edges[20])), std::exp(6.0) * Bernoulli(-2.5));\n  EXPECT_DOUBLE_EQ((*beta)(*(edges[23])), std::exp(8.5) * Bernoulli(2.5));\n}\n\n// for Psi = const = c, the exponentially fitted element matrix reduces to\n// A^{exp}_K = -A_K where A_K is the element matrix for (u,v) -> \\int_K grad u *\n// grad v dx\nTEST(ExpFittedEMP, Psi_const) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  auto mf_Psi = lf::mesh::utils::MeshFunctionGlobal(\n      [](Eigen::Vector2d x) { return 3.0; });\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  Eigen::VectorXd mu = lf::fe::NodalProjection(*fe_space, mf_Psi);\n\n  // Imploemented exponentially fitted upwind provider\n  ExpFittedEMP upwind_provider(fe_space, mu);\n\n  // Lehrfem++ element matrix provider for the the minus laplcian\n  lf::uscalfe::LinearFELaplaceElementMatrix standard_provider;\n\n  // Expect that for Psi=const the ExpFitted Element matrix is -A_k\n  for (auto *cell : mesh_p->Entities(0)) {\n    Eigen::Matrix3d E_k = upwind_provider.Eval(*cell);\n    Eigen::Matrix3d A_k = standard_provider.Eval(*cell).block<3, 3>(0, 0);\n\n    EXPECT_NEAR((E_k + A_k).norm(), 0.0, 1.0E-10);\n  }\n}\n\n// The last two tests are based on the fact, that\n// the expontially Fitted upwind scheme provides a system matrix  A that\n// corresponds to the bilinear form (u,v) -> b(u,v) \\int_{\\Omega} j(u,Psi) *\n// grad v dx (j(u,Psi) = const ) In particular this value can be approximated by\n// b_v^T * A * b_u, where b_v and b_u are the nodal projections of v and u into\n// the underlying FE space\n\n// u = exp(Psi)\n// j(u,Psi) = 0\n// and b(u,v) = 0 for any v\nTEST(ExpFittedEMP, Bilinear_form_1) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n\n  Eigen::Vector2d q = Eigen::Vector2d::Ones(2);\n  auto Psi = [&q](Eigen::Vector2d x) { return q.dot(x); };\n\n  auto u = [&Psi](Eigen::Vector2d x) { return std::exp(Psi(x)); };\n\n  auto mf_Psi = lf::mesh::utils::MeshFunctionGlobal(Psi);\n  auto mf_u = lf::mesh::utils::MeshFunctionGlobal(u);\n\n  Eigen::VectorXd mu = lf::fe::NodalProjection(*fe_space, mf_Psi);\n  Eigen::VectorXd u_vec = lf::fe::NodalProjection(*fe_space, mf_u);\n\n  lf::assemble::COOMatrix<double> A(dofh.NumDofs(), dofh.NumDofs());\n  ExpFittedEMP elmat_builder(fe_space, mu);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elmat_builder, A);\n  Eigen::SparseMatrix<double> A_crs = A.makeSparse();\n\n  EXPECT_NEAR((A_crs * u_vec).norm(), 0.0, 1.0E-10);\n}\n\n// Psi = q' * x\n// u = c (--> j(u) = c*q)\n// v = r' *x\n// b(u,v) = |\\Omega|*c*q'*r\nTEST(ExpFittedEMP, Bilinear_form_2) {\n  auto mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3);\n  double area = 9.0;\n  auto fe_space =\n      std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p);\n  const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n\n  Eigen::Vector2d q = Eigen::Vector2d::Ones(2);\n  auto Psi = [&q](Eigen::Vector2d x) { return q.dot(x); };\n  auto mf_Psi = lf::mesh::utils::MeshFunctionGlobal(Psi);\n\n  double u_value = 2.0;\n  auto mf_u = lf::mesh::utils::MeshFunctionConstant(u_value);\n\n  Eigen::Vector2d r = Eigen::Vector2d::Ones(2);\n  auto v = [&r](Eigen::Vector2d x) { return r.dot(x); };\n  auto mf_v = lf::mesh::utils::MeshFunctionGlobal(v);\n\n  Eigen::VectorXd mu = lf::fe::NodalProjection(*fe_space, mf_Psi);\n  Eigen::VectorXd u_vec = lf::fe::NodalProjection(*fe_space, mf_u);\n  Eigen::VectorXd v_vec = lf::fe::NodalProjection(*fe_space, mf_v);\n\n  lf::assemble::COOMatrix<double> A(dofh.NumDofs(), dofh.NumDofs());\n  ExpFittedEMP elmat_builder(fe_space, mu);\n  lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elmat_builder, A);\n  Eigen::SparseMatrix<double> A_crs = A.makeSparse();\n\n  double value = v_vec.transpose() * A_crs * u_vec;\n  double reference = area * u_value * r.dot(q);\n  EXPECT_NEAR(value, reference, 1.0E-10);\n}\n\n}  // namespace ExpFittedUpwind::test\n", "meta": {"hexsha": "f9c84af65156f6fcd689c6a25a1b2a0398ec64ee", "size": 7062, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ExpFittedUpwind/templates/test/expfittedupwind_test.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ExpFittedUpwind/templates/test/expfittedupwind_test.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ExpFittedUpwind/templates/test/expfittedupwind_test.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 36.78125, "max_line_length": 80, "alphanum_fraction": 0.6642594166, "num_tokens": 2372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117983401363, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6043747570753066}}
{"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Test of explicit_l_curve_test class.\n */\n#include \"num_collect/regularization/explicit_l_curve.h\"\n\n#include <Eigen/Core>\n#include <catch2/catch_test_macros.hpp>\n#include <catch2/matchers/catch_matchers_floating.hpp>\n\n#include \"eigen_approx.h\"\n#include \"num_collect/regularization/tikhonov.h\"\n#include \"num_prob_collect/regularization/blur_sine.h\"\n\nTEST_CASE(\"num_collect::regularization::explicit_l_curve\") {\n    using coeff_type = Eigen::MatrixXd;\n    using data_type = Eigen::VectorXd;\n    using solver_type =\n        num_collect::regularization::tikhonov<coeff_type, data_type>;\n    using param_searcher_type =\n        num_collect::regularization::explicit_l_curve<solver_type>;\n\n    SECTION(\"solve\") {\n        constexpr num_collect::index_type solution_size = 15;\n        constexpr num_collect::index_type data_size = 30;\n        const auto prob = num_prob_collect::regularization::blur_sine(\n            data_size, solution_size);\n\n        num_collect::regularization::tikhonov<coeff_type, data_type> tikhonov;\n        tikhonov.compute(prob.coeff(), prob.data());\n\n        param_searcher_type searcher{tikhonov};\n        searcher.search();\n        REQUIRE(std::log10(searcher.opt_param()) < 0.0);\n\n        constexpr double tol_sol = 1e-6;\n\n        Eigen::VectorXd solution;\n        searcher.solve(solution);\n        REQUIRE_THAT(solution, eigen_approx(prob.solution(), tol_sol));\n    }\n}\n", "meta": {"hexsha": "d7884fbf5ca1749af3291fb3a2d6c95790aec8df", "size": 2032, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/units/regularization/explicit_l_curve_test.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/units/regularization/explicit_l_curve_test.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/units/regularization/explicit_l_curve_test.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0344827586, "max_line_length": 78, "alphanum_fraction": 0.7209645669, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6043747491099678}}
{"text": "#include \"goodnessfunction.h\"\n\n#include <QImage>\n#include <Eigen/Dense>\n#include \"eigenutility.h\"\n#include \"image.h\"\n\nusing namespace std;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nnamespace\n{\ndouble computeGaussian(const VectorXd& x, const VectorXd& c, const MatrixXd& S_inv)\n{\n    const unsigned n = x.rows();\n    const VectorXd r = x - c;\n    const double   a = 1.0 / sqrt(pow(2.0 * M_PI, static_cast<double>(n)) * (1.0 / S_inv.determinant()));\n    const double   b = exp(- 0.5 * r.transpose() * S_inv * r);\n    return a * b;\n}\n\ntemplate<typename Scalar> Scalar clamp(Scalar x, Scalar m, Scalar M) { return std::max(std::min(x, M), m); }\n\ndouble computeVar(const MatrixXd &w_mean, const double &o_mean, const vector<MatrixXd> &w, const VectorXd &o, unsigned s, unsigned t, unsigned N)\n{\n    double t1 = 0.0;\n    for (unsigned i = 0; i < N; ++ i)\n    {\n        t1 += (o[i] * w[i](s, t) - o_mean * w_mean(s, t)) * (o[i] * w[i](s, t) - o_mean * w_mean(s, t));\n    }\n\n    double t2 = 0.0;\n    for (unsigned i = 0; i < N; ++ i)\n    {\n        t2 += (o[i] - o_mean) * (o[i] * w[i](s, t) - o_mean * w_mean(s, t));\n    }\n\n    double t3 = 0.0;\n    for (unsigned i = 0; i < N; ++ i)\n    {\n        t3 += (o[i] - o_mean) * (o[i] - o_mean);\n    }\n\n    return (static_cast<double>(N) / static_cast<double>(N - 1)) * (t1 - 2.0 * w_mean(s, t) * t2 + w_mean(s, t) * w_mean(s, t) * t3);\n}\n}\n\nGoodnessFunction::GoodnessFunction() :\n    alpha(0.0020),\n    epsilon(0.020)\n{\n\n}\n\n// A pure implementation of the adaptive kernel density estimation algorithms described in [Talton et al. 2009] (Section 5)\nvoid GoodnessFunction::computeCovariance()\n{\n    const unsigned N = getFeatureList().size();\n    const unsigned n = getFeatureList()[0].rows() + getParameterList()[0].rows();\n\n    SList.clear();\n    SList.resize(N);\n\n    // Exception\n    assert (N != 0);\n    if (N == 1)\n    {\n        SList[0] = MatrixXd::Identity(n, n);\n        return;\n    }\n\n    // Prepare the data points\n    vector<VectorXd> x(N);\n    for (unsigned i = 0; i < N; ++ i)\n    {\n        x[i] = getJointVector(getParameterList()[i], getFeatureList()[i]);\n    }\n\n    // Compute the distances from the k-nearest neighborhoods\n    const unsigned k = std::min(N - 1, n);\n    VectorXd squaredDistance_k = VectorXd::Zero(N);\n    for (unsigned i = 0; i < N; ++ i)\n    {\n        vector<double> d(N);\n        for (unsigned j = 0; j < N; ++ j)\n        {\n            d[j] = (x[i] - x[j]).squaredNorm();\n        }\n        partial_sort(d.begin(), d.begin() + (k + 1), d.end());  // Note: d[0] is always 0.0\n        squaredDistance_k(i) = d[k];\n    }\n\n    // For each Gaussian center, ...\n    for (unsigned center = 0; center < N; ++ center)\n    {\n        // Compute weights (omega in the paper) for this data point\n        VectorXd o = VectorXd::Zero(N);\n        for (unsigned j = 0; j < N; ++ j)\n        {\n            const double   alpha = 1.0;\n            const MatrixXd S_inv = (1.0 / (alpha * squaredDistance_k[center])) * MatrixXd::Identity(n, n);\n            o(j) = computeGaussian(x[j], x[center], S_inv);\n        }\n        o /= o.sum();\n\n        // Compute weights (w in the paper) for this data point\n        vector<MatrixXd> w(N);\n        for (unsigned j = 0; j < N; ++ j)\n        {\n            w[j] = MatrixXd::Zero(n, n);\n            for (unsigned s = 0; s < n; ++ s) for (unsigned t = s; t < n; ++ t)\n            {\n                w[j](s, t) = (x[j].row(s) - x[center].row(s)) * (x[j].row(t) - x[center].row(t));\n                w[j](t, s) = (x[j].row(s) - x[center].row(s)) * (x[j].row(t) - x[center].row(t));\n            }\n        }\n\n        // Compute a covariance matrix for this data point\n        SList[center] = MatrixXd::Zero(n, n);\n        for (unsigned s = 0; s < n; ++ s) for (unsigned t = s; t < n; ++ t)\n        {\n            double elem = 0.0;\n            for (unsigned j = 0; j < N; ++ j)\n            {\n                elem += o[j] * w[j](s, t);\n            }\n            SList[center](s, t) = elem;\n            SList[center](t, s) = elem;\n        }\n\n        // Compute the bandwidth shrinkage algorithm\n        const MatrixXd& Sigma = SList[center];\n\n        MatrixXd Phi = MatrixXd::Zero(n, n);\n        for (unsigned j = 0; j < n; ++ j) Phi(j, j) = Sigma(j, j);\n\n        const MatrixXd& w_mean = Sigma;\n        const double    o_mean = o.sum() / static_cast<double>(N);\n\n        double t1 = 0.0;\n        for (unsigned s = 0; s < n; ++ s) for (unsigned t = 0; t < n; ++ t)\n        {\n            if (s == t) continue;\n            t1 += computeVar(w_mean, o_mean, w, o, s, t, N);\n        }\n\n        double t2 = 0.0;\n        for (unsigned s = 0; s < n; ++ s) for (unsigned t = 0; t < n; ++ t)\n        {\n            if (s == t) continue;\n            t2 += w_mean(s, t) * w_mean(s, t);\n        }\n\n        double lambda = t1 / t2;\n        lambda = isnan(lambda) ? 0.0 : clamp(lambda, 0.0, 1.0);\n\n        SList[center] = lambda * Phi + (1.0 - lambda) * Sigma;\n    }\n}\n\nvoid GoodnessFunction::regularizeCovariance()\n{\n    for (MatrixXd &Sigma : SList)\n    {\n        const unsigned n = Sigma.rows();\n        for (unsigned i = 0; i < n; ++ i)\n        {\n            Sigma(i, i) = max(Sigma(i, i), epsilon);\n        }\n    }\n}\n\nVectorXd GoodnessFunction::applyGradientAscent(const VectorXd& x, const VectorXd& f, double scale) const\n{\n    const VectorXd grad = computeGradient(x, f).block(0, 0, x.rows(), 1);\n    const VectorXd xNew = x + scale * alpha * grad;\n\n    return getClippedParameters(xNew);\n}\n\ndouble GoodnessFunction::getValue(const VectorXd& j) const\n{\n#if 0\n    const double   sig = 0.10;\n    const unsigned N   = getFeatureList().size();\n\n    double sum = 0.0;\n    for (unsigned i = 0; i < N; ++ i) {\n        const VectorXd& f_i = getFeatureList()[i];\n        const VectorXd& x_i = getParameterList()[i];\n        const VectorXd  j_i = getJointVector(x_i, f_i);\n        const double    d_i = (j - j_i).squaredNorm();\n        sum += exp(- d_i / sig);\n    }\n    return sum / static_cast<double>(N);\n#else\n    const unsigned N = getFeatureList().size();\n    double sum = 0.0;\n    for (unsigned i = 0; i < N; ++ i) {\n        const MatrixXd& S     = SList[i];\n        const MatrixXd  S_inv = S.inverse();\n        const VectorXd& f_i   = getFeatureList()[i];\n        const VectorXd& x_i   = getParameterList()[i];\n        const VectorXd  j_i   = getJointVector(x_i, f_i);\n        sum += computeGaussian(j, j_i, S_inv);\n    }\n    return sum / static_cast<double>(N);\n#endif\n}\n\ndouble GoodnessFunction::getValue(const VectorXd& x, const VectorXd &f) const\n{\n    const VectorXd j = getJointVector(x, f);\n    return getValue(j);\n}\n\nVectorXd GoodnessFunction::computeGradient(const VectorXd &j) const\n{\n    const unsigned n = j.rows();\n    const unsigned N = getFeatureList().size();\n    VectorXd sum = VectorXd::Zero(n);\n    for (unsigned i = 0; i < N; ++ i)\n    {\n        const MatrixXd& S     = SList[i];\n        const MatrixXd  S_inv = S.inverse();\n        const VectorXd& f_i   = getFeatureList()[i];\n        const VectorXd& x_i   = getParameterList()[i];\n        const VectorXd  j_i   = getJointVector(x_i, f_i);\n        sum += - computeGaussian(j, j_i, S_inv) * S_inv * (j - j_i);\n    }\n\n    // NaN check\n    for (unsigned i = 0; i < sum.rows(); ++ i) sum(i) = std::isnan(sum(i)) ? 0.0 : sum(i);\n\n    return sum / static_cast<double>(N);\n}\n\nVectorXd GoodnessFunction::computeGradient(const VectorXd &x, const VectorXd &f) const\n{\n    const VectorXd j = getJointVector(x, f);\n    return computeGradient(j);\n}\n\nVectorXd GoodnessFunction::getClippedParameters(VectorXd x)\n{\n    for (int i = 0; i < x.rows(); ++ i)\n    {\n        if (x(i) < 0.0) x(i) = 0.0;\n        if (x(i) > 1.0) x(i) = 1.0;\n    }\n    return x;\n}\n\nVectorXd GoodnessFunction::getJointVector(const VectorXd &x, const Eigen::VectorXd& f)\n{\n    return EigenUtility::join(x, f);\n}\n\nVectorXd GoodnessFunction::getAverageParameterSet() const\n{\n    assert(!pList.empty());\n\n    VectorXd ave = VectorXd::Zero(pList[0].rows());\n    for (const VectorXd& v : pList)\n    {\n        ave += v;\n    }\n    return (1.0 / static_cast<double>(pList.size())) * ave;\n}\n", "meta": {"hexsha": "bf199d7a5c8be68ce0399fd804dbbfd911993a4f", "size": 8078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SelPh/goodnessfunction.cpp", "max_stars_repo_name": "yuki-koyama/selph", "max_stars_repo_head_hexsha": "9f3d1a868333843c6884adac41e344684efa2366", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-13T07:47:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-10T20:31:32.000Z", "max_issues_repo_path": "SelPh/goodnessfunction.cpp", "max_issues_repo_name": "yuki-koyama/selph", "max_issues_repo_head_hexsha": "9f3d1a868333843c6884adac41e344684efa2366", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-04-06T10:06:56.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-04T05:38:12.000Z", "max_forks_repo_path": "SelPh/goodnessfunction.cpp", "max_forks_repo_name": "yuki-koyama/selph", "max_forks_repo_head_hexsha": "9f3d1a868333843c6884adac41e344684efa2366", "max_forks_repo_licenses": ["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.8081180812, "max_line_length": 145, "alphanum_fraction": 0.5434513493, "num_tokens": 2493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.6042244257115367}}
{"text": "/**\n * @file linear_svm_test.cpp\n * @author Ayush Chamoli\n *\n * Test the Linear SVM class.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#include <mlpack/core.hpp>\n#include <mlpack/methods/linear_svm/linear_svm.hpp>\n#include <ensmallen.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::svm;\nusing namespace mlpack::distribution;\n\nBOOST_AUTO_TEST_SUITE(LinearSVMTest);\n\n/**\n * A simple test for LinearSVMFunction\n */\nBOOST_AUTO_TEST_CASE(LinearSVMFunctionEvaluate)\n{\n  // A very simple fake dataset\n  arma::mat dataset = \"2 0 0;\"\n                      \"0 0 0;\"\n                      \"0 2 1;\"\n                      \"1 0 2;\"\n                      \"0 1 0\";\n\n  //  Corresponding labels\n  arma::Row<size_t> labels = \"1 0 1\";\n\n  LinearSVMFunction<arma::mat> svmf(dataset, labels, 2,\n      0.0 /* no regularization */);\n\n  // These were hand-calculated using Python.\n  arma::mat parameters = \"1 1 1 1 1;\"\n                         \"1 1 1 1 1\";\n  BOOST_REQUIRE_CLOSE(svmf.Evaluate(parameters.t()), 1.0, 1e-5);\n\n  parameters = \"2 0 1 2 2;\"\n               \"1 2 2 2 2\";\n  BOOST_REQUIRE_CLOSE(svmf.Evaluate(parameters.t()), 2.0, 1e-5);\n\n  parameters = \"-0.1425 8.3228 0.1724 -0.3374 0.1548;\"\n               \"0.1435 0.0009 -0.1736 0.3356 -0.1544\";\n  BOOST_REQUIRE_CLOSE(svmf.Evaluate(parameters.t()), 0.0, 1e-5);\n\n  parameters = \"100 3 4 5 23;\"\n               \"43 54 67 32 64\";\n  BOOST_REQUIRE_CLOSE(svmf.Evaluate(parameters.t()), 85.33333333, 1e-5);\n\n  parameters = \"3 71 22 12 6;\"\n               \"100 39 30 57 22\";\n  BOOST_REQUIRE_CLOSE(svmf.Evaluate(parameters.t()), 11.0, 1e-5);\n}\n\n/**\n * A complicated test for the LinearSVMFunction for binary-class\n * classification.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMFunctionRandomBinaryEvaluate)\n{\n  const size_t points = 1000;\n  const size_t trials = 10;\n  const size_t inputSize = 10;\n  const size_t numClasses = 2;\n  const double delta = 1.0;\n\n  // Initialize a random dataset.\n  arma::mat data;\n  data.randu(inputSize, points);\n\n  // Create random class labels.\n  arma::Row<size_t> labels(points);\n  for (size_t i = 0; i < points; i++)\n    labels(i) = math::RandInt(0, numClasses);\n\n  // Create a LinearSVMFunction, Regularization term ignored.\n  LinearSVMFunction<arma::mat> svmf(data, labels, numClasses,\n      0.0 /* no regularization */);\n\n  // Run a number of trials.\n  for (size_t i = 0; i < trials; ++i)\n  {\n    // Create a random set of parameters.\n    arma::mat parameters;\n    parameters.randu(inputSize, numClasses);\n\n    // Hand-calculate the loss function\n    double hingeLoss = 0;\n\n    // Compute error for each training example.\n    for (size_t j = 0; j < points; ++j)\n    {\n      arma::mat score = parameters.t() * data.col(j);\n      double correct = score[labels(j)];\n      for (size_t k = 0; k < numClasses; ++k)\n      {\n        if (k == labels[j])\n          continue;\n        double margin = score[k] - correct + delta;\n        if (margin > 0)\n          hingeLoss += margin;\n      }\n    }\n    hingeLoss /= points;\n\n    // Compare with the value returned by the function.\n    BOOST_REQUIRE_CLOSE(svmf.Evaluate(parameters), hingeLoss, 1e-5);\n  }\n}\n\n/**\n * A complicated test for the LinearSVMFunction for multi-class\n * classification.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMFunctionRandomEvaluate)\n{\n  const size_t points = 1000;\n  const size_t trials = 10;\n  const size_t inputSize = 10;\n  const size_t numClasses = 5;\n  const double delta = 1.0;\n\n  // Initialize a random dataset.\n  arma::mat data;\n  data.randu(inputSize, points);\n\n  // Create random class labels.\n  arma::Row<size_t> labels(points);\n  for (size_t i = 0; i < points; i++)\n    labels(i) = math::RandInt(0, numClasses);\n\n  // Create a LinearSVMFunction, Regularization term ignored.\n  LinearSVMFunction<arma::mat> svmf(data, labels, numClasses,\n      0.0 /* no regularization */);\n\n  // Run a number of trials.\n  for (size_t i = 0; i < trials; ++i)\n  {\n    // Create a random set of parameters.\n    arma::mat parameters;\n    parameters.randu(inputSize, numClasses);\n\n    // Hand-calculate the loss function\n    double hingeLoss = 0;\n\n    // Compute error for each training example.\n    for (size_t j = 0; j < points; ++j)\n    {\n      arma::mat score = parameters.t() * data.col(j);\n      double correct = score[labels(j)];\n      for (size_t k = 0; k < numClasses; ++k)\n      {\n        if (k == labels[j])\n          continue;\n        double margin = score[k] - correct + delta;\n        if (margin > 0)\n          hingeLoss += margin;\n      }\n    }\n    hingeLoss /= points;\n\n    // Compare with the value returned by the function.\n    BOOST_REQUIRE_CLOSE(svmf.Evaluate(parameters), hingeLoss, 1e-5);\n  }\n}\n\n/**\n * Test regularization for the LinearSVMFunction Evaluate()\n * function.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMFunctionRegularizationEvaluate)\n{\n  const size_t points = 1000;\n  const size_t trials = 10;\n  const size_t inputSize = 10;\n  const size_t numClasses = 3;\n\n  // Initialize a random dataset.\n  arma::mat data;\n  data.randu(inputSize, points);\n\n  // Create random class labels.\n  arma::Row<size_t> labels(points);\n  for (size_t i = 0; i < points; i++)\n    labels(i) = math::RandInt(0, numClasses);\n\n  // 3 objects for comparing regularization costs.\n  LinearSVMFunction<arma::mat> svmfNoReg(data, labels, numClasses, 0);\n  LinearSVMFunction<arma::mat> svmfSmallReg(data, labels, numClasses, 1);\n  LinearSVMFunction<arma::mat> svmfBigReg(data, labels, numClasses, 20);\n\n  // Run a number of trials.\n  for (size_t i = 0; i < trials; i++)\n  {\n    // Create a random set of parameters.\n    arma::mat parameters;\n    parameters.randu(inputSize, numClasses);\n\n    double wL2SquaredNorm;\n    wL2SquaredNorm = arma::dot(parameters, parameters);\n\n    // Calculate regularization terms.\n    const double smallRegTerm = 0.5 * wL2SquaredNorm;\n    const double bigRegTerm = 10 * wL2SquaredNorm;\n\n    BOOST_REQUIRE_CLOSE(svmfNoReg.Evaluate(parameters) + smallRegTerm,\n                        svmfSmallReg.Evaluate(parameters), 1e-5);\n    BOOST_REQUIRE_CLOSE(svmfNoReg.Evaluate(parameters) + bigRegTerm,\n                        svmfBigReg.Evaluate(parameters), 1e-5);\n  }\n}\n\n/**\n * Test individual Evaluate() functions to be used for\n * optimization.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMFunctionSeparableEvaluate)\n{\n  const size_t points = 1000;\n  const size_t trials = 10;\n  const size_t inputSize = 10;\n  const size_t numClasses = 3;\n\n  // Initialize a random dataset.\n  arma::mat data;\n  data.randu(inputSize, points);\n\n  // Create random class labels.\n  arma::Row<size_t> labels(points);\n  for (size_t i = 0; i < points; i++)\n    labels(i) = math::RandInt(0, numClasses);\n\n  LinearSVMFunction<> svmf(data, labels, numClasses);\n\n  for (size_t i = 0; i < trials; ++i)\n  {\n    // Create a random set of parameters.\n    arma::mat parameters;\n    parameters.randu(inputSize, numClasses);\n\n    double hingeLoss = 0;\n    for (size_t j = 0; j < points; ++j)\n      hingeLoss += svmf.Evaluate(parameters, j, 1);\n\n    hingeLoss /= points;\n\n    // Compare with the value returned by the function.\n    BOOST_REQUIRE_CLOSE(svmf.Evaluate(parameters), hingeLoss, 1e-5);\n  }\n}\n\n/**\n *\n * Test regularization for the separable Evaluate() function\n * to be used Optimizers.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMFunctionRegularizationSeparableEvaluate)\n{\n  const size_t points = 100;\n  const size_t trials = 3;\n  const size_t inputSize = 10;\n  const size_t numClasses = 3;\n\n  // Initialize a random dataset.\n  arma::mat data;\n  data.randu(inputSize, points);\n\n  // Create random class labels.\n  arma::Row<size_t> labels(points);\n  for (size_t i = 0; i < points; i++)\n    labels(i) = math::RandInt(0, numClasses);\n\n  LinearSVMFunction<> svmfNoReg(data, labels, numClasses, 0.0);\n  LinearSVMFunction<> svmfSmallReg(data, labels, numClasses, 0.5);\n  LinearSVMFunction<> svmfBigReg(data, labels, numClasses, 20.0);\n\n\n  // Check that the number of functions is correct.\n  BOOST_REQUIRE_EQUAL(svmfNoReg.NumFunctions(), points);\n  BOOST_REQUIRE_EQUAL(svmfSmallReg.NumFunctions(), points);\n  BOOST_REQUIRE_EQUAL(svmfBigReg.NumFunctions(), points);\n\n\n  for (size_t i = 0; i < trials; ++i)\n  {\n    // Create a random set of parameters.\n    arma::mat parameters;\n    parameters.randu(inputSize, numClasses);\n\n    double wL2SquaredNorm;\n    wL2SquaredNorm = 0.5 * arma::dot(parameters, parameters);\n\n    // Calculate regularization terms.\n    const double smallRegTerm = 0.5 * wL2SquaredNorm;\n    const double bigRegTerm = 20 * wL2SquaredNorm;\n\n    for (size_t j = 0; j < points; ++j)\n    {\n      BOOST_REQUIRE_CLOSE(svmfNoReg.Evaluate(parameters, j, 1) + smallRegTerm,\n          svmfSmallReg.Evaluate(parameters, j, 1), 1e-5);\n      BOOST_REQUIRE_CLOSE(svmfNoReg.Evaluate(parameters, j, 1) + bigRegTerm,\n          svmfBigReg.Evaluate(parameters, j, 1), 1e-5);\n    }\n  }\n}\n\n/**\n * Test Gradient() of the LinearSVMFunction.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMFunctionGradient)\n{\n  const size_t points = 1000;\n  const size_t trials = 10;\n  const size_t inputSize = 10;\n  const size_t numClasses = 5;\n  const double delta = 1.0;\n\n  // Initialize a random dataset.\n  arma::mat data;\n  data.randu(inputSize, points);\n\n  // Create random class labels.\n  arma::Row<size_t> labels(points);\n  for (size_t i = 0; i < points; i++)\n    labels(i) = math::RandInt(0, numClasses);\n\n  // Create a LinearSVMFunction, Regularization term ignored.\n  LinearSVMFunction<arma::mat> svmf(data, labels, numClasses,\n                                    0.0 /* no regularization */,\n                                    delta);\n\n  // Run a number of trials.\n  for (size_t i = 0; i < trials; ++i)\n  {\n    // Create a random set of parameters.\n    arma::mat parameters;\n    parameters.randu(inputSize, numClasses);\n\n    // Hand-calculate the gradient.\n    arma::mat difference;\n    difference.zeros(numClasses, points);\n\n    // Compute error for each training example.\n    for (size_t j = 0; j < points; ++j)\n    {\n      arma::mat score = parameters.t() * data.col(j);\n      double correct = score[labels(j)];\n      size_t differenceCount = 0;\n      for (size_t k = 0; k < numClasses; ++k)\n      {\n        if (k == labels[j])\n          continue;\n        double margin = score[k] - correct + delta;\n        if (margin > 0)\n        {\n          differenceCount += 1;\n          difference(k, j) = 1;\n        }\n      }\n      difference(labels(j), j) -= differenceCount;\n    }\n\n    arma::mat gradient = (data * difference.t()) / points;\n    arma::mat evaluatedGradient;\n\n    svmf.Gradient(parameters, evaluatedGradient);\n\n    // Compare with the values returned by Gradient().\n    for (size_t j = 0; j < inputSize ; ++j)\n    {\n      for (size_t k = 0; k < numClasses ; ++k)\n      {\n        BOOST_REQUIRE_CLOSE(gradient(j, k), evaluatedGradient(j, k), 1e-5);\n      }\n    }\n  }\n}\n\n/**\n * Test separable Gradient() of the LinearSVMFunction when regularization\n * is used.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMFunctionSeparableGradient)\n{\n  const size_t points = 100;\n  const size_t trials = 3;\n  const size_t inputSize = 5;\n  const size_t numClasses = 5;\n\n  // Initialize a random dataset.\n  arma::mat data;\n  data.randu(inputSize, points);\n\n  // Create random class labels.\n  arma::Row<size_t> labels(points);\n  for (size_t i = 0; i < points; i++)\n    labels(i) = math::RandInt(0, numClasses);\n\n  LinearSVMFunction<> svmfNoReg(data, labels, numClasses, 0.0);\n  LinearSVMFunction<> svmfSmallReg(data, labels, numClasses, 0.5);\n  LinearSVMFunction<> svmfBigReg(data, labels, numClasses, 20.0);\n\n  for (size_t i = 0; i < trials; ++i)\n  {\n    // Create a random set of parameters.\n    arma::mat parameters;\n    parameters.randu(inputSize, numClasses);\n\n    arma::mat gradient;\n    arma::mat smallRegGradient;\n    arma::mat bigRegGradient;\n\n    // Test separable gradient for each point.  Regularization will be the same.\n    for (size_t k = 0; k < points; ++k)\n    {\n      svmfNoReg.Gradient(parameters, k, gradient, 1);\n      svmfSmallReg.Gradient(parameters, k, smallRegGradient, 1);\n      svmfBigReg.Gradient(parameters, k, bigRegGradient, 1);\n\n      // Check sizes of gradients.\n      BOOST_REQUIRE_EQUAL(gradient.n_elem, parameters.n_elem);\n      BOOST_REQUIRE_EQUAL(smallRegGradient.n_elem, parameters.n_elem);\n      BOOST_REQUIRE_EQUAL(bigRegGradient.n_elem, parameters.n_elem);\n\n      // Check other terms.\n      for (size_t j = 0; j < parameters.n_elem; ++j)\n      {\n        const double smallRegTerm = 0.5 * parameters[j];\n        const double bigRegTerm = 20.0 * parameters[j];\n\n        BOOST_REQUIRE_CLOSE(gradient[j] + smallRegTerm, smallRegGradient[j],\n                            1e-5);\n        BOOST_REQUIRE_CLOSE(gradient[j] + bigRegTerm, bigRegGradient[j], 1e-5);\n      }\n    }\n  }\n}\n\n/**\n * Test training of linear svm on a simple dataset using\n * L-BFGS optimizer\n */\nBOOST_AUTO_TEST_CASE(LinearSVMLGFGSSimpleTest)\n{\n  const size_t numClasses = 2;\n  const double lambda = 0.0001;\n\n  // A very simple fake dataset\n  arma::mat dataset = \"2 0 0;\"\n                      \"0 0 0;\"\n                      \"0 2 1;\"\n                      \"1 0 2;\"\n                      \"0 1 0\";\n\n  //  Corresponding labels\n  arma::Row<size_t> labels = \"1 0 1\";\n\n  // Create a linear svm object using L-BFGS optimizer.\n  LinearSVM<arma::mat> lsvm(dataset, labels, numClasses, lambda);\n\n  // Compare training accuracy to 1.\n  const double acc = lsvm.ComputeAccuracy(dataset, labels);\n  BOOST_REQUIRE_CLOSE(acc, 1.0, 0.5);\n}\n\n/**\n * Test training of linear svm on a simple dataset using\n * Gradient Descent optimizer\n */\nBOOST_AUTO_TEST_CASE(LinearSVMGradientDescentSimpleTest)\n{\n  const size_t numClasses = 2;\n  const size_t maxIterations = 10000;\n  const double stepSize = 0.01;\n  const double tolerance = 1e-5;\n  const double lambda = 0.0001;\n  const double delta = 1.0;\n\n  // A very simple fake dataset\n  arma::mat dataset = \"2 0 0;\"\n                      \"0 0 0;\"\n                      \"0 2 1;\"\n                      \"1 0 2;\"\n                      \"0 1 0\";\n\n  //  Corresponding labels\n  arma::Row<size_t> labels = \"1 0 1\";\n\n  // Create a linear svm object using custom gradient descent optimizer.\n  ens::GradientDescent optimizer(stepSize, maxIterations, tolerance);\n  LinearSVM<arma::mat> lsvm(dataset, labels, numClasses, lambda,\n      delta, false, optimizer);\n\n  // Compare training accuracy to 1.\n  const double acc = lsvm.ComputeAccuracy(dataset, labels);\n  BOOST_REQUIRE_CLOSE(acc, 1.0, 0.5);\n}\n\n/**\n * Test training of linear svm for two classes on a complex gaussian dataset\n * using L-BFGS optimizer.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMLBFGSTwoClasses)\n{\n  const size_t points = 1000;\n  const size_t inputSize = 3;\n  const size_t numClasses = 2;\n  const double lambda = 0.5;\n\n  // Generate two-Gaussian dataset.\n  GaussianDistribution g1(arma::vec(\"1.0 9.0 1.0\"), arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g2(arma::vec(\"4.0 3.0 4.0\"), arma::eye<arma::mat>(3, 3));\n\n  arma::mat data(inputSize, points);\n  arma::Row<size_t> labels(points);\n\n  for (size_t i = 0; i < points / 2; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 2; i < points; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n\n  // Create a linear svm object using L-BFGS optimizer.\n  LinearSVM<arma::mat> lsvm(data, labels, numClasses, lambda);\n\n  // Compare training accuracy to 1.\n  const double acc = lsvm.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(acc, 1.0, 0.5);\n\n  // Create test dataset.\n  for (size_t i = 0; i < points / 2; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) =  0;\n  }\n  for (size_t i = points / 2; i < points; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n\n  // Compare test accuracy to 1.\n  const double testAcc = lsvm.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(testAcc, 1.0, 0.6);\n}\n\n/**\n * Test training of linear svm for two classes on a complex gaussian dataset\n * using L-BFGS optimizer which can't be separated without adding\n * the intercept term.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMFitIntercept)\n{\n  const size_t points = 1000;\n  const size_t inputSize = 3;\n  const size_t numClasses = 2;\n  const double lambda = 0.5;\n  const double delta = 1.0;\n\n  // Generate a two-Gaussian dataset,\n  GaussianDistribution g1(arma::vec(\"1.0 9.0 1.0\"), arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g2(arma::vec(\"4.0 3.0 4.0\"), arma::eye<arma::mat>(3, 3));\n\n  arma::mat data(inputSize, points);\n  arma::Row<size_t> labels(points);\n  for (size_t i = 0; i < points / 2; ++i)\n  {\n    data.col(i) = g1.Random();\n    labels[i] = 0;\n  }\n  for (size_t i = points / 2; i < points; ++i)\n  {\n    data.col(i) = g2.Random();\n    labels[i] = 1;\n  }\n\n  // Now train a svm object on it.\n  LinearSVM<arma::mat> svm(data, labels, numClasses, lambda,\n      delta, true, ens::L_BFGS());\n\n  // Ensure that the error is close to zero.\n  const double acc = svm.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(acc, 1.0, 2.0);\n\n  // Create a test set.\n  for (size_t i = 0; i < 500; ++i)\n  {\n    data.col(i) = g1.Random();\n    labels[i] = 0;\n  }\n  for (size_t i = 500; i < 1000; ++i)\n  {\n    data.col(i) = g2.Random();\n    labels[i] = 1;\n  }\n\n  // Ensure that the error is close to zero.\n  const double testAcc = svm.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(testAcc, 1.0, 2.0);\n}\n\n/**\n * Test training of linear svm on a simple dataset using\n * Gradient Descent optimizer and with another value of delta.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMDeltaLBFGSTwoClasses)\n{\n  const size_t points = 1000;\n  const size_t inputSize = 3;\n  const size_t numClasses = 2;\n  const double lambda = 0.5;\n  const double delta = 5.0;\n\n  // Generate two-Gaussian dataset.\n  GaussianDistribution g1(arma::vec(\"1.0 9.0 1.0\"), arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g2(arma::vec(\"4.0 3.0 4.0\"), arma::eye<arma::mat>(3, 3));\n\n  arma::mat data(inputSize, points);\n  arma::Row<size_t> labels(points);\n\n  for (size_t i = 0; i < points / 2; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 2; i < points; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n\n  // Create a linear svm object using L-BFGS optimizer.\n  LinearSVM<arma::mat> lsvm(data, labels, numClasses, lambda,\n      delta);\n\n  // Compare training accuracy to 1.\n  const double acc = lsvm.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(acc, 1.0, 0.5);\n\n  // Create test dataset.\n  for (size_t i = 0; i < points / 2; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) =  0;\n  }\n  for (size_t i = points / 2; i < points; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n\n  // Compare test accuracy to 1.\n  const double testAcc = lsvm.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(testAcc, 1.0, 0.6);\n}\n\n/**\n * The test is only compiled if the user has specified OpenMP to be\n * used.\n */\n#ifdef HAS_OPENMP\n\n/**\n * Test training of linear svm on a simple dataset using\n * Parallel SGD optimizer.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMPSGDSimpleTest)\n{\n  const size_t numClasses = 2;\n  const double lambda = 0.5;\n  const double alpha = 0.01;\n  const double delta = 1.0;\n\n  // A very simple fake dataset\n  arma::mat dataset = \"2 0 0;\"\n                      \"0 0 0;\"\n                      \"0 2 1;\"\n                      \"1 0 2;\"\n                      \"0 1 0\";\n\n  //  Corresponding labels\n  arma::Row<size_t> labels = \"1 0 1\";\n\n  ens::ConstantStep decayPolicy(alpha);\n\n  // Train linear svm object using Parallel SGD optimizer.\n  // The threadShareSize is chosen such that each function gets optimized.\n  ens::ParallelSGD<ens::ConstantStep> optimizer(0,\n      std::ceil((float) dataset.n_cols / omp_get_max_threads()),\n      1e-5, true, decayPolicy);\n  LinearSVM<arma::mat> lsvm(dataset, labels, numClasses, lambda,\n      delta, false, optimizer);\n\n  // Compare training accuracy to 1.\n  const double acc = lsvm.ComputeAccuracy(dataset, labels);\n  BOOST_REQUIRE_CLOSE(acc, 1.0, 1.0);\n}\n\n/**\n * Test training of linear svm for two classes on a complex gaussian dataset\n * using Parallel SGD optimizer.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMParallelSGDTwoClasses)\n{\n  const size_t points = 500;\n  const size_t inputSize = 3;\n  const size_t numClasses = 2;\n  const double lambda = 0.5;\n  const double alpha = 0.01;\n  const double delta = 1.0;\n\n  // Generate two-Gaussian dataset.\n  GaussianDistribution g1(arma::vec(\"1.0 9.0 1.0\"), arma::eye<arma::mat>(3, 3));\n  GaussianDistribution g2(arma::vec(\"4.0 3.0 4.0\"), arma::eye<arma::mat>(3, 3));\n\n  arma::mat data(inputSize, points);\n  arma::Row<size_t> labels(points);\n\n  for (size_t i = 0; i < points / 2; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 2; i < points; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n\n  ens::ConstantStep decayPolicy(alpha);\n\n  // Train linear svm object using Parallel SGD optimizer.\n  // The threadShareSize is chosen such that each function gets optimized.\n  ens::ParallelSGD<ens::ConstantStep> optimizer(0,\n      std::ceil((float) data.n_cols / omp_get_max_threads()),\n      1e-5, true, decayPolicy);\n  LinearSVM<arma::mat> lsvm(data, labels, numClasses, lambda,\n      delta, false, optimizer);\n\n  // Compare training accuracy to 1.\n  const double acc = lsvm.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(acc, 1.0, 2.0);\n\n  // Create test dataset.\n  for (size_t i = 0; i < points / 2; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) =  0;\n  }\n  for (size_t i = points / 2; i < points; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n\n  // Compare test accuracy to 1.\n  const double testAcc = lsvm.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(testAcc, 1.0, 2.0);\n}\n\n#endif\n\n/**\n * Test sparse and dense linear svm and make sure they both work the\n * same using the L-BFGS optimizer.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMSparseLBFGSTest)\n{\n  // Create a random dataset.\n  arma::sp_mat dataset;\n  dataset.sprandu(10, 800, 0.3);\n  arma::mat denseDataset(dataset);\n  arma::Row<size_t> labels(800);\n  for (size_t i = 0; i < 800; ++i)\n    labels[i] = math::RandInt(0, 2);\n\n  LinearSVM<arma::mat> lr(denseDataset, labels, 2, 0.3, 1,\n      false, ens::L_BFGS());\n  LinearSVM<arma::sp_mat> lrSparse(dataset, labels, 2, 0.3, 1,\n      false, ens::L_BFGS());\n\n  BOOST_REQUIRE_EQUAL(lr.Parameters().n_elem, lrSparse.Parameters().n_elem);\n  for (size_t i = 0; i < lr.Parameters().n_elem; ++i)\n    BOOST_REQUIRE_CLOSE(lr.Parameters()[i], lrSparse.Parameters()[i], 5e-4);\n}\n\n/**\n * Test training of linear svm for multiple classes on a complex gaussian\n * dataset using L-BFGS optimizer.\n */\nBOOST_AUTO_TEST_CASE(LinearSVMLBFGSMultipleClasses)\n{\n  const size_t points = 1000;\n  const size_t inputSize = 5;\n  const size_t numClasses = 5;\n  const double lambda = 0.5;\n\n  // Generate five-Gaussian dataset.\n  arma::mat identity = arma::eye<arma::mat>(5, 5);\n  GaussianDistribution g1(arma::vec(\"1.0 9.0 1.0 2.0 2.0\"), identity);\n  GaussianDistribution g2(arma::vec(\"4.0 3.0 4.0 2.0 2.0\"), identity);\n  GaussianDistribution g3(arma::vec(\"3.0 2.0 7.0 0.0 5.0\"), identity);\n  GaussianDistribution g4(arma::vec(\"4.0 1.0 1.0 2.0 7.0\"), identity);\n  GaussianDistribution g5(arma::vec(\"1.0 0.0 1.0 8.0 3.0\"), identity);\n\n  arma::mat data(inputSize, points);\n  arma::Row<size_t> labels(points);\n\n  for (size_t i = 0; i < points / 5; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 5; i < (2 * points) / 5; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n  for (size_t i = (2 * points) / 5; i < (3 * points) / 5; i++)\n  {\n    data.col(i) = g3.Random();\n    labels(i) = 2;\n  }\n  for (size_t i = (3 * points) / 5; i < (4 * points) / 5; i++)\n  {\n    data.col(i) = g4.Random();\n    labels(i) = 3;\n  }\n  for (size_t i = (4 * points) / 5; i < points; i++)\n  {\n    data.col(i) = g5.Random();\n    labels(i) = 4;\n  }\n\n  // Train linear svm object using L-BFGS optimizer.\n  LinearSVM<arma::mat> lsvm(data, labels, numClasses, lambda);\n\n  // Compare training accuracy to 1.\n  const double acc = lsvm.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(acc, 1.0, 2.0);\n\n  // Create test dataset.\n  for (size_t i = 0; i < points / 5; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 5; i < (2 * points) / 5; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n  for (size_t i = (2 * points) / 5; i < (3 * points) / 5; i++)\n  {\n    data.col(i) = g3.Random();\n    labels(i) = 2;\n  }\n  for (size_t i = (3 * points) / 5; i < (4 * points) / 5; i++)\n  {\n    data.col(i) = g4.Random();\n    labels(i) = 3;\n  }\n  for (size_t i = (4 * points) / 5; i < points; i++)\n  {\n    data.col(i) = g5.Random();\n    labels(i) = 4;\n  }\n\n  // Compare test accuracy to 1.\n  const double testAcc = lsvm.ComputeAccuracy(data, labels);\n  BOOST_REQUIRE_CLOSE(testAcc, 1.0, 2.0);\n}\n\n/**\n * Testing single point classification (Classify()).\n */\nBOOST_AUTO_TEST_CASE(LinearSVMClassifySinglePointTest)\n{\n  const size_t points = 500;\n  const size_t inputSize = 5;\n  const size_t numClasses = 5;\n  const double lambda = 0.5;\n\n  // Generate five-Gaussian dataset.\n  arma::mat identity = arma::eye<arma::mat>(5, 5);\n  GaussianDistribution g1(arma::vec(\"1.0 9.0 1.0 2.0 2.0\"), identity);\n  GaussianDistribution g2(arma::vec(\"4.0 3.0 4.0 2.0 2.0\"), identity);\n  GaussianDistribution g3(arma::vec(\"3.0 2.0 7.0 0.0 5.0\"), identity);\n  GaussianDistribution g4(arma::vec(\"4.0 1.0 1.0 2.0 7.0\"), identity);\n  GaussianDistribution g5(arma::vec(\"1.0 0.0 1.0 8.0 3.0\"), identity);\n\n  arma::mat data(inputSize, points);\n  arma::Row<size_t> labels(points);\n\n  for (size_t i = 0; i < points / 5; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 5; i < (2 * points) / 5; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n  for (size_t i = (2 * points) / 5; i < (3 * points) / 5; i++)\n  {\n    data.col(i) = g3.Random();\n    labels(i) = 2;\n  }\n  for (size_t i = (3 * points) / 5; i < (4 * points) / 5; i++)\n  {\n    data.col(i) = g4.Random();\n    labels(i) = 3;\n  }\n  for (size_t i = (4 * points) / 5; i < points; i++)\n  {\n    data.col(i) = g5.Random();\n    labels(i) = 4;\n  }\n\n  // Train linear svm object.\n  LinearSVM<arma::mat> lsvm(data, labels, numClasses, lambda);\n\n  // Create test dataset.\n  for (size_t i = 0; i < points / 5; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 5; i < (2 * points) / 5; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n  for (size_t i = (2 * points) / 5; i < (3 * points) / 5; i++)\n  {\n    data.col(i) = g3.Random();\n    labels(i) = 2;\n  }\n  for (size_t i = (3 * points) / 5; i < (4 * points) / 5; i++)\n  {\n    data.col(i) = g4.Random();\n    labels(i) = 3;\n  }\n  for (size_t i = (4 * points) / 5; i < points; i++)\n  {\n    data.col(i) = g5.Random();\n    labels(i) = 4;\n  }\n\n  lsvm.Classify(data, labels);\n\n  for (size_t i = 0; i < data.n_cols; ++i)\n  {\n    BOOST_REQUIRE_EQUAL(lsvm.Classify(data.col(i)), labels(i));\n  }\n}\n\n/**\n * Test that single-point classification gives the same results as multi-point\n * classification.\n */\nBOOST_AUTO_TEST_CASE(SinglePointClassifyTest)\n{\n  const size_t points = 500;\n  const size_t inputSize = 5;\n  const size_t numClasses = 5;\n  const double lambda = 0.5;\n\n  // Generate five-Gaussian dataset.\n  arma::mat identity = arma::eye<arma::mat>(5, 5);\n  GaussianDistribution g1(arma::vec(\"1.0 9.0 1.0 2.0 2.0\"), identity);\n  GaussianDistribution g2(arma::vec(\"4.0 3.0 4.0 2.0 2.0\"), identity);\n  GaussianDistribution g3(arma::vec(\"3.0 2.0 7.0 0.0 5.0\"), identity);\n  GaussianDistribution g4(arma::vec(\"4.0 1.0 1.0 2.0 7.0\"), identity);\n  GaussianDistribution g5(arma::vec(\"1.0 0.0 1.0 8.0 3.0\"), identity);\n\n  arma::mat data(inputSize, points);\n  arma::Row<size_t> labels(points);\n\n  for (size_t i = 0; i < points / 5; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 5; i < (2 * points) / 5; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n  for (size_t i = (2 * points) / 5; i < (3 * points) / 5; i++)\n  {\n    data.col(i) = g3.Random();\n    labels(i) = 2;\n  }\n  for (size_t i = (3 * points) / 5; i < (4 * points) / 5; i++)\n  {\n    data.col(i) = g4.Random();\n    labels(i) = 3;\n  }\n  for (size_t i = (4 * points) / 5; i < points; i++)\n  {\n    data.col(i) = g5.Random();\n    labels(i) = 4;\n  }\n\n  // Train linear svm object.\n  LinearSVM<arma::mat> lsvm(data, labels, numClasses, lambda);\n\n  // Create test dataset.\n  for (size_t i = 0; i < points / 5; i++)\n  {\n    data.col(i) = g1.Random();\n    labels(i) = 0;\n  }\n  for (size_t i = points / 5; i < (2 * points) / 5; i++)\n  {\n    data.col(i) = g2.Random();\n    labels(i) = 1;\n  }\n  for (size_t i = (2 * points) / 5; i < (3 * points) / 5; i++)\n  {\n    data.col(i) = g3.Random();\n    labels(i) = 2;\n  }\n  for (size_t i = (3 * points) / 5; i < (4 * points) / 5; i++)\n  {\n    data.col(i) = g4.Random();\n    labels(i) = 3;\n  }\n  for (size_t i = (4 * points) / 5; i < points; i++)\n  {\n    data.col(i) = g5.Random();\n    labels(i) = 4;\n  }\n\n  arma::Row<size_t> predictions;\n  lsvm.Classify(data, predictions);\n\n  for (size_t i = 0; i < data.n_cols; ++i)\n  {\n    size_t pred = lsvm.Classify(data.col(i));\n\n    BOOST_REQUIRE_EQUAL(pred, predictions[i]);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "41045d235ce9a2b2cc8899faf7ba262d9038f0a5", "size": 29498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/linear_svm_test.cpp", "max_stars_repo_name": "yashMustak/mlpack", "max_stars_repo_head_hexsha": "354938177a718b58685d2d1f5eda3591d61ad3bc", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-12T20:10:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-12T20:10:39.000Z", "max_issues_repo_path": "src/mlpack/tests/linear_svm_test.cpp", "max_issues_repo_name": "yashMustak/mlpack", "max_issues_repo_head_hexsha": "354938177a718b58685d2d1f5eda3591d61ad3bc", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/linear_svm_test.cpp", "max_forks_repo_name": "yashMustak/mlpack", "max_forks_repo_head_hexsha": "354938177a718b58685d2d1f5eda3591d61ad3bc", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7236842105, "max_line_length": 80, "alphanum_fraction": 0.6242796122, "num_tokens": 9193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.6688802735722128, "lm_q1q2_score": 0.604195672613632}}
{"text": "#include \"problemes.h\"\n#include \"utilitaires.h\"\n\n#include <boost/math/constants/constants.hpp>\n\ntypedef unsigned long long nombre;\ntypedef std::vector<nombre> vecteur;\n\nENREGISTRER_PROBLEME(317, \"Firecracker\") {\n    // A firecracker explodes at a height of 100 m above level ground. It breaks into a large number of very small\n    // fragments, which move in every direction; all of them have the same initial velocity of 20 m/s.\n    //\n    // We assume that the fragments move without air resistance, in a uniform gravitational field with g=9.81 m/s2.\n    //\n    // Find the volume (in m3) of the region through which the fragments move before reaching the ground. Give your\n    // answer rounded to four decimal places.\n    const long double v = 20;\n    const long double h = 100;\n    const long double g = 9.81L;\n\n    long double resultat = M_PIl * (2 * g * v * h + v * v * v) * (2 * g * v * h + v * v * v) / (4 * g * g * g);\n    return std::to_fixed(resultat, 4);\n}\n", "meta": {"hexsha": "c0d01fd3e7b3db41ccc1b955ac73736064d933c2", "size": 970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme317.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/probleme317.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/probleme317.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4166666667, "max_line_length": 115, "alphanum_fraction": 0.6762886598, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.6041956564681016}}
{"text": "//\n// Copyright (c) 2018 CNRS\n//\n\n#include \"pinocchio/fwd.hpp\"\n#include \"pinocchio/multibody/joint/joint-generic.hpp\"\n#include \"pinocchio/multibody/liegroup/liegroup.hpp\"\n#include \"pinocchio/multibody/liegroup/liegroup-algo.hpp\"\n\n#include <iostream>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_jointRX_motion_space)\n{\n  using CppAD::AD;\n  using CppAD::NearEqual;\n\n  typedef AD<double> AD_double;\n  typedef pinocchio::JointCollectionDefaultTpl<AD_double> JointCollectionAD;\n  typedef pinocchio::JointCollectionDefaultTpl<double> JointCollection;\n  \n  typedef pinocchio::SE3Tpl<AD_double> SE3AD;\n  typedef pinocchio::MotionTpl<AD_double> MotionAD;\n  typedef pinocchio::SE3Tpl<double> SE3;\n  typedef pinocchio::MotionTpl<double> Motion;\n  typedef pinocchio::ConstraintTpl<Eigen::Dynamic,double> ConstraintXd;\n  \n  typedef Eigen::Matrix<AD_double,Eigen::Dynamic,1> VectorXAD;\n  typedef Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> MatrixX;\n  \n  typedef JointCollectionAD::JointModelRX JointModelRXAD;\n  typedef JointModelRXAD::ConfigVector_t ConfigVectorAD;\n//  typedef JointModelRXAD::TangentVector_t TangentVectorAD;\n  typedef JointCollectionAD::JointDataRX JointDataRXAD;\n  \n  typedef JointCollection::JointModelRX JointModelRX;\n  typedef JointModelRX::ConfigVector_t ConfigVector;\n  typedef JointModelRX::TangentVector_t TangentVector;\n  typedef JointCollection::JointDataRX JointDataRX;\n  \n  JointModelRX jmodel; jmodel.setIndexes(0,0,0);\n  JointDataRX jdata(jmodel.createData());\n  \n  JointModelRXAD jmodel_ad = jmodel.cast<AD_double>();\n  JointDataRXAD jdata_ad(jmodel_ad.createData());\n  \n  typedef pinocchio::LieGroup<JointModelRX>::type JointOperation;\n  ConfigVector q(jmodel.nq()); JointOperation().random(q);\n  ConfigVectorAD q_ad(q.cast<AD_double>());\n  \n   // Zero order\n  jmodel_ad.calc(jdata_ad,q_ad);\n  jmodel.calc(jdata,q);\n  \n  SE3 M1(jdata.M);\n  SE3AD M2(jdata_ad.M);\n  BOOST_CHECK(M1.isApprox(M2.cast<double>()));\n  \n  // First order\n  TangentVector v(TangentVector::Random(jmodel.nv()));\n  VectorXAD X(jmodel_ad.nv());\n  \n  for(Eigen::DenseIndex k = 0; k < jmodel.nv(); ++k)\n  {\n    X[k] = v[k];\n  }\n  CppAD::Independent(X);\n  jmodel_ad.calc(jdata_ad,q_ad,X);\n  jmodel.calc(jdata,q,v);\n  VectorXAD Y(6);\n  MotionAD m_ad(jdata_ad.v);\n  Motion m(jdata.v);\n  ConstraintXd Sref(jdata.S.matrix());\n  \n  for(Eigen::DenseIndex k = 0; k < 3; ++k)\n  {\n    Y[k+Motion::LINEAR] = m_ad.linear()[k];\n    Y[k+Motion::ANGULAR] = m_ad.angular()[k];\n  }\n\n  CppAD::ADFun<double> vjoint(X,Y);\n  \n  CPPAD_TESTVECTOR(double) x((size_t)jmodel_ad.nv());\n  for(Eigen::DenseIndex k = 0; k < jmodel.nv(); ++k)\n  {\n    x[(size_t)k] = v[k];\n  }\n  \n  CPPAD_TESTVECTOR(double) jac = vjoint.Jacobian(x);\n  MatrixX S(6,jac.size()/6);\n  S = Eigen::Map<MatrixX>(jac.data(),S.rows(),S.cols());\n  \n  BOOST_CHECK(m.isApprox(m_ad.cast<double>()));\n  \n  BOOST_CHECK(Sref.matrix().isApprox(S));\n}\n\nstruct TestADOnJoints\n{\n  template<typename JointModel>\n  void operator()(const pinocchio::JointModelBase<JointModel> &) const\n  {\n    JointModel jmodel;\n    jmodel.setIndexes(0,0,0);\n    \n    test(jmodel);\n  }\n  \n  template<typename Scalar, int Options>\n  void operator()(const pinocchio::JointModelRevoluteUnalignedTpl<Scalar,Options> & ) const\n  {\n    typedef pinocchio::JointModelRevoluteUnalignedTpl<Scalar,Options> JointModel;\n    typedef typename JointModel::Vector3 Vector3;\n    JointModel jmodel(Vector3::Random().normalized());\n    jmodel.setIndexes(0,0,0);\n    \n    test(jmodel);\n  }\n  \n  template<typename Scalar, int Options>\n  void operator()(const pinocchio::JointModelPrismaticUnalignedTpl<Scalar,Options> & ) const\n  {\n    typedef pinocchio::JointModelPrismaticUnalignedTpl<Scalar,Options> JointModel;\n    typedef typename JointModel::Vector3 Vector3;\n    JointModel jmodel(Vector3::Random().normalized());\n    jmodel.setIndexes(0,0,0);\n    \n    test(jmodel);\n  }\n  \n  template<typename Scalar, int Options, template<typename,int> class JointCollection>\n  void operator()(const pinocchio::JointModelTpl<Scalar,Options,JointCollection> & ) const\n  {\n    typedef pinocchio::JointModelRevoluteTpl<Scalar,Options,0> JointModelRX;\n    typedef pinocchio::JointModelTpl<Scalar,Options,JointCollection> JointModel;\n    JointModel jmodel((JointModelRX()));\n    jmodel.setIndexes(0,0,0);\n    \n    test(jmodel);\n  }\n  \n  template<typename Scalar, int Options, template<typename,int> class JointCollection>\n  void operator()(const pinocchio::JointModelCompositeTpl<Scalar,Options,JointCollection> & ) const\n  {\n    typedef pinocchio::JointModelRevoluteTpl<Scalar,Options,0> JointModelRX;\n    typedef pinocchio::JointModelRevoluteTpl<Scalar,Options,1> JointModelRY;\n    typedef pinocchio::JointModelCompositeTpl<Scalar,Options,JointCollection> JointModel;\n    JointModel jmodel((JointModelRX()));\n    jmodel.addJoint(JointModelRY());\n    jmodel.setIndexes(0,0,0);\n    \n    test(jmodel);\n  }\n  \n  template<typename JointModel>\n  static void test(const pinocchio::JointModelBase<JointModel> & jmodel)\n  {\n    using CppAD::AD;\n    using CppAD::NearEqual;\n    \n    typedef typename JointModel::Scalar Scalar;\n    typedef typename JointModel::JointDataDerived JointData;\n    \n    typedef AD<Scalar> AD_scalar;\n\n    typedef pinocchio::SE3Tpl<AD_scalar> SE3AD;\n    typedef pinocchio::MotionTpl<AD_scalar> MotionAD;\n    typedef pinocchio::SE3Tpl<Scalar> SE3;\n    typedef pinocchio::MotionTpl<Scalar> Motion;\n    typedef pinocchio::ConstraintTpl<Eigen::Dynamic,Scalar> ConstraintXd;\n    \n    typedef Eigen::Matrix<AD_scalar,Eigen::Dynamic,1> VectorXAD;\n    typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> MatrixX;\n    \n    typedef typename pinocchio::CastType<AD_scalar,JointModel>::type JointModelAD;\n    typedef typename JointModelAD::JointDataDerived JointDataAD;\n    \n    typedef typename JointModelAD::ConfigVector_t ConfigVectorAD;\n\n    typedef typename JointModel::ConfigVector_t ConfigVector;\n    typedef typename JointModel::TangentVector_t TangentVector;\n    \n    JointData jdata(jmodel.createData());\n    pinocchio::JointDataBase<JointData> & jdata_base = jdata;\n    \n    JointModelAD jmodel_ad = jmodel.template cast<AD_scalar>();\n    JointDataAD jdata_ad(jmodel_ad.createData());\n    pinocchio::JointDataBase<JointDataAD> & jdata_ad_base = jdata_ad;\n    \n    ConfigVector q(jmodel.nq());\n    ConfigVector lb(ConfigVector::Constant(jmodel.nq(),-1.));\n    ConfigVector ub(ConfigVector::Constant(jmodel.nq(),1.));\n    \n    typedef pinocchio::RandomConfigurationStep<pinocchio::LieGroupMap,ConfigVector,ConfigVector,ConfigVector> RandomConfigAlgo;\n    RandomConfigAlgo::run(jmodel.derived(),typename RandomConfigAlgo::ArgsType(q,lb,ub));\n    \n    ConfigVectorAD q_ad(q.template cast<AD_scalar>());\n    \n    // Zero order\n    jmodel_ad.calc(jdata_ad,q_ad);\n    jmodel.calc(jdata,q);\n    \n    SE3 M1(jdata_base.M());\n    SE3AD M2(jdata_ad_base.M());\n    BOOST_CHECK(M1.isApprox(M2.template cast<Scalar>()));\n    \n    // First order\n    TangentVector v(TangentVector::Random(jmodel.nv()));\n    VectorXAD X(jmodel_ad.nv());\n\n    for(Eigen::DenseIndex k = 0; k < jmodel.nv(); ++k)\n    {\n      X[k] = v[k];\n    }\n    CppAD::Independent(X);\n    jmodel_ad.calc(jdata_ad,q_ad,X);\n    jmodel.calc(jdata,q,v);\n    VectorXAD Y(6);\n    MotionAD m_ad(jdata_ad_base.v());\n    Motion m(jdata_base.v());\n    ConstraintXd Sref(jdata_base.S().matrix());\n\n    for(Eigen::DenseIndex k = 0; k < 3; ++k)\n    {\n      Y[k+Motion::LINEAR] = m_ad.linear()[k];\n      Y[k+Motion::ANGULAR] = m_ad.angular()[k];\n    }\n\n    CppAD::ADFun<Scalar> vjoint(X,Y);\n\n    CPPAD_TESTVECTOR(Scalar) x((size_t)jmodel_ad.nv());\n    for(Eigen::DenseIndex k = 0; k < jmodel.nv(); ++k)\n    {\n      x[(size_t)k] = v[k];\n    }\n\n    CPPAD_TESTVECTOR(Scalar) jac = vjoint.Jacobian(x);\n    MatrixX S(6,jac.size()/6);\n    S = Eigen::Map<typename EIGEN_PLAIN_ROW_MAJOR_TYPE(MatrixX)>(jac.data(),S.rows(),S.cols());\n\n    BOOST_CHECK(m.isApprox(m_ad.template cast<Scalar>()));\n\n    BOOST_CHECK(Sref.matrix().isApprox(S));\n  }\n};\n\nBOOST_AUTO_TEST_CASE(test_all_joints)\n{\n  typedef pinocchio::JointCollectionDefault::JointModelVariant JointModelVariant;\n  boost::mpl::for_each<JointModelVariant::types>(TestADOnJoints());\n\n  TestADOnJoints()(pinocchio::JointModel());\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "33b7903ef282065bed9d6c64f077edb3ff5597d7", "size": 8338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/cppad-joints.cpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "unittest/cppad-joints.cpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/cppad-joints.cpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 32.0692307692, "max_line_length": 127, "alphanum_fraction": 0.7167186376, "num_tokens": 2354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.60418227912017}}
{"text": "/**\n * @file tests/randomized_svd_test.cpp\n * @author Marcus Edel\n *\n * Test file for the Randomized SVD class.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/randomized_svd/randomized_svd.hpp>\n\n#include <boost/test/unit_test.hpp>\n#include \"test_tools.hpp\"\n\nBOOST_AUTO_TEST_SUITE(RandomizedSVDTest);\n\nusing namespace mlpack;\n\n/**\n * The reconstruction and sigular value error of the obtained SVD should be\n * small.\n */\nBOOST_AUTO_TEST_CASE(RandomizedSVDReconstructionError)\n{\n  arma::mat U = arma::randn<arma::mat>(3, 20);\n  arma::mat V = arma::randn<arma::mat>(10, 3);\n\n  arma::mat R;\n  arma::qr_econ(U, R, U);\n  arma::qr_econ(V, R, V);\n\n  arma::mat s = arma::diagmat(arma::vec(\"1 0.1 0.01\"));\n\n  arma::mat data = arma::trans(U * arma::diagmat(s) * V.t());\n\n  // Center the data into a temporary matrix.\n  arma::mat centeredData;\n  math::Center(data, centeredData);\n\n  arma::mat U1, U2, V1, V2;\n  arma::vec s1, s2, s3;\n\n  arma::svd_econ(U1, s1, V1, centeredData);\n\n  svd::RandomizedSVD rSVD(0, 10);\n  rSVD.Apply(data, U2, s2, V2, 3);\n\n  // Use the same amount of data for the compariosn (matrix rank).\n  s3 = s1.subvec(0, s2.n_elem - 1);\n\n  // The sigular value error should be small.\n  double error = arma::norm(s2 - s3, \"frob\") / arma::norm(s2, \"frob\");\n  BOOST_REQUIRE_SMALL(error, 1e-5);\n\n  arma::mat reconstruct = U2 * arma::diagmat(s2) * V2.t();\n\n  // The relative reconstruction error should be small.\n  error = arma::norm(centeredData - reconstruct, \"frob\") /\n      arma::norm(centeredData, \"frob\");\n  BOOST_REQUIRE_SMALL(error, 1e-5);\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "07371842bfa80ee8f26e3654e82d741c7e9210d3", "size": 1877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/tests/randomized_svd_test.cpp", "max_stars_repo_name": "KimSangYeon-DGU/mlpack", "max_stars_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-29T17:39:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-16T23:36:01.000Z", "max_issues_repo_path": "src/mlpack/tests/randomized_svd_test.cpp", "max_issues_repo_name": "birm/mlpack", "max_issues_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/tests/randomized_svd_test.cpp", "max_forks_repo_name": "birm/mlpack", "max_forks_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T13:27:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-23T09:44:31.000Z", "avg_line_length": 27.6029411765, "max_line_length": 78, "alphanum_fraction": 0.6867341502, "num_tokens": 584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.6041822756117369}}
{"text": "#include \"functions/integral_polynomial.hh\"\n#include \"functions/polynomial.hh\"\n#include \"functions/operators.hh\"\n#include <boost/test/unit_test.hpp>\n#include <complex>\n#include \"functions/std_functions.hh\"\n#include \"functions/all_simplifications.hh\"\n#include \"data/matrix.hh\"\n\nBOOST_AUTO_TEST_CASE(matrix_polynomial_test) {\n  using namespace manifolds;\n\n  auto m = GetMatrix<2, 2>(1.0, 0.0, 0.0, 1.0);\n  auto p = GetPolynomial(m, m * 2);\n  BOOST_CHECK_EQUAL(p(2), 5 * m);\n\n  BOOST_CHECK_EQUAL(p(m), 3 * m);\n\n  auto p2 = p * p + 2_c * p;\n  auto p2_check = GetPolynomial(3 * m, 8 * m, 4 * m);\n  BOOST_CHECK(p2 == p2_check);\n}\n", "meta": {"hexsha": "d065e7190a94e25235fdc4c1eed0d6899d3398ef", "size": 624, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_matrix_polynomial.cpp", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/tests/test_matrix_polynomial.cpp", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/tests/test_matrix_polynomial.cpp", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["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.1304347826, "max_line_length": 53, "alphanum_fraction": 0.7003205128, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.604182272887614}}
{"text": "#include \"NeuralNet.hpp\" \n#include <string>\n#include <fstream>\n#include <iostream>\n#include <boost/range/irange.hpp>\n#include <typeinfo>\n#include <chrono>\n#include <ctime>\n\nint main() {\n    // Dataset\n    Eigen::MatrixXd X_train;\n    Eigen::VectorXi y_train;\n    Eigen::MatrixXd X_test;\n    Eigen::VectorXi y_test;\n \n    // Load the training and testing data from the file\n    X_train = load_matrix_data(\"./data/X_train_large.csv\");\n    y_train = load_vector_data(\"./data/y_train_large.csv\");\n    X_test = load_matrix_data(\"./data/X_test_large.csv\");\n    y_test = load_vector_data(\"./data/y_test_large.csv\");\n    \n    std::cout << \"The matrix X_train is of size \" << X_train.rows() << \"x\" << X_train.cols() << std::endl;\n    std::cout << \"The vector y_train is of size \" << y_train.rows() << \"x\" << y_train.cols() << std::endl;\n    \n    // Parameters\n    int NUM_CLASSES = 4;\n    double start_learning_rate = 1.0;\n\n    // Create for neural network objects\n    LayerDense dense_layer_1(2, 64);\n    ActivationRelu activation_relu;\n    LayerDense dense_layer_2(64, NUM_CLASSES);\n    ActivationSoftmax activation_softmax;\n    CrossEntropyLoss loss_categorical_crossentropy;\n    StochasticGradientDescent optimizer_SGD(1.0, 1e-3, 0.9);\n\n    // variables\n    double loss;\n    double train_accuracy;\n    double test_accuracy;\n    double pred;\n    int index_pred;\n\n    // Train DNN\n    auto t_start = std::chrono::high_resolution_clock::now();\n    \n    int NUMBER_OF_EPOCHS = 10000;\n    for (int epoch : boost::irange(0,NUMBER_OF_EPOCHS)) {\n        ////////////////////////////////////////////////////////forward pass//////////////////////////////////////////////////////////////////////////////////\n        dense_layer_1.forward(X_train);\n        activation_relu.forward(dense_layer_1.output);\n        dense_layer_2.forward(activation_relu.output);\n        activation_softmax.forward(dense_layer_2.output);\n        // calculate loss\n        loss = loss_categorical_crossentropy.calculate(activation_softmax.output, y_train);\n        // get predictions and accuracy\n        Eigen::MatrixXd::Index maxRow, maxCol;\n        Eigen::VectorXi predictions(activation_softmax.output.rows());\n        Eigen::VectorXd pred_truth_comparison(activation_softmax.output.rows());\n\n        for (int i=0; i < activation_softmax.output.rows(); i++) {\n            pred = activation_softmax.output.row(i).maxCoeff(&maxRow, &maxCol);\n            index_pred = maxCol;\n            predictions(i) = index_pred;\n            pred_truth_comparison(i) = predictions(i) == y_train(i);\n        }\n        train_accuracy = pred_truth_comparison.mean();\n        if (epoch % 1000 == 0) {\n            std::cout << \"epoch: \" << epoch << std::endl;\n            std::cout << \"train_accuracy: \" << train_accuracy << std::endl;\n            std::cout << \"learning_rate: \" << optimizer_SGD.learning_rate << std::endl;\n            std::cout << \"loss: \" << loss << std::endl;\n        }\n\n        ////////////////////////////////////////////////////////////backward pass/////////////////////////////////////////////////////////////////////////\n        loss_categorical_crossentropy.backward(activation_softmax.output, y_train);\n        activation_softmax.backward(loss_categorical_crossentropy.dinputs);\n        dense_layer_2.backward(activation_softmax.dinputs);\n        activation_relu.backward(dense_layer_2.dinputs);\n        dense_layer_1.backward(activation_relu.dinputs);\n\n        ////////////////////////////////////////////////////////////debugging/////////////////////////////////////////////////////////////////////////\n        // std::cout << \"Type of y_train \" <<   typeid(y_train).name() << std::endl;\n        // std::cout << \"Type of X_train \" <<   typeid(X_train).name() << std::endl;\n        // std::cout << \"The matrix X_train is of size \" << X_train.rows() << \"x\" << X_train.cols() << std::endl;\n        // std::cout << \"The vector y_train is of size \" << y_train.rows() << \"x\" << y_train.cols() << std::endl;\n        // std::cout << \"X_train \" << X_train << std::endl;\n        // std::cout << \"y_train \" << y_train << std::endl;\n        \n        // std::cout << \"The matrix dense_layer_1.weights is of size \" << dense_layer_1.weights.rows() << \"x\" << dense_layer_1.weights.cols() << std::endl;\n        // std::cout << \"The matrix dense_layer_1.biases is of size \" << dense_layer_1.biases.rows() << \"x\" << dense_layer_1.biases.cols() << std::endl;\n        // std::cout << \"The matrix dense_layer_2.weights is of size \" << dense_layer_2.weights.rows() << \"x\" << dense_layer_2.weights.cols() << std::endl;\n        // std::cout << \"The matrix dense_layer_2.biases is of size \" << dense_layer_2.biases.rows() << \"x\" << dense_layer_2.biases.cols() << std::endl;\n\n        // std::cout << dense_layer_1.weights << std::endl;\n        // std::cout << dense_layer_1.biases << std::endl;\n        // std::cout << dense_layer_2.weights << std::endl;\n        // std::cout << dense_layer_2.biases << std::endl;\n \n        ////////////////////////////////////////////////////////////optimizer - update weights and biases/////////////////////////////////////////////////////////////////////////\n        optimizer_SGD.pre_update_params(start_learning_rate);\n        optimizer_SGD.update_params(dense_layer_1);\n        optimizer_SGD.update_params(dense_layer_2);\n        optimizer_SGD.post_update_params();\n        \n        ////////////////////////////////////////////////////////////debugging/////////////////////////////////////////////////////////////////////////\n        // std::cout << \"\\nepoch: \" << epoch << \"\\n\";\n\n        // std::cout << \"\\nLayer 1 weights after \\n\" << dense_layer_1.weights << std::endl;\n        // std::cout << \"\\nLayer 1 biases after \\n\" << dense_layer_1.biases << std::endl;\n        // std::cout << \"\\nLayer 2 weights after \\n\" << dense_layer_2.weights << std::endl;\n        // std::cout << \"\\nLayer 2 biases after \\n\" << dense_layer_2.biases << std::endl;\n\n        // std::cout << \"\\ndense_layer_1.output\\n\" << dense_layer_1.output << std::endl;\n        // std::cout << \"\\nactivation_relu.output\\n\" << activation_relu.output << std::endl;\n        // std::cout << \"\\ndense_layer_2.output\\n\" << dense_layer_2.output << std::endl;\n        // std::cout << \"\\nactivation_softmax.output\\n\" << activation_softmax.output << std::endl;\n\n        // std::cout << \"loss: \" << loss << std::endl;\n        // std::cout << \"predictions: \" << predictions << std::endl;\n\n        // std::cout << \"loss_categorical_crossentropy.dinputs: \" << loss_categorical_crossentropy.dinputs << std::endl;\n        // std::cout << \"activation_softmax.dinputs: \" << activation_softmax.dinputs << std::endl;\n        // std::cout << \"dense_layer_2.dinputs: \" << dense_layer_2.dinputs << std::endl;\n        // std::cout << \"activation_relu.dinputs: \" << activation_relu.dinputs << std::endl;\n    }\n    \n    // Time training time\n    auto t_end = std::chrono::high_resolution_clock::now();\n    std::cout << \"\\ntraining took \" << std::chrono::duration_cast<std::chrono::seconds>(t_end-t_start).count()<< \" seconds\\n\";\n\n    // Test DNN\n    dense_layer_1.forward(X_test);\n    activation_relu.forward(dense_layer_1.output);\n    dense_layer_2.forward(activation_relu.output);\n    activation_softmax.forward(dense_layer_2.output);\n    // calculate loss\n    loss = loss_categorical_crossentropy.calculate(activation_softmax.output, y_test);\n    // get predictions and accuracy\n    Eigen::MatrixXd::Index maxRow, maxCol;\n    Eigen::VectorXi predictions(activation_softmax.output.rows());\n    Eigen::VectorXd pred_truth_comparison(activation_softmax.output.rows());\n\n    for (int i=0; i < activation_softmax.output.rows(); i++) {\n            pred = activation_softmax.output.row(i).maxCoeff(&maxRow, &maxCol);\n            index_pred = maxCol;\n            predictions(i) = index_pred;\n            pred_truth_comparison(i) = predictions(i) == y_test(i);\n    }\n    test_accuracy = pred_truth_comparison.mean();\n    std::cout << \"\\ntest_accuracy: \" << test_accuracy << std::endl;\n}\n", "meta": {"hexsha": "692143dd9c5a03b43134a0694d71e86fd0a403aa", "size": 8005, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ekloberdanz/Neural-Net-Implementation", "max_stars_repo_head_hexsha": "937dbd2edf695192fb8afcedfe05b1f4ffcdc5ce", "max_stars_repo_licenses": ["MIT"], "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": "ekloberdanz/Neural-Net-Implementation", "max_issues_repo_head_hexsha": "937dbd2edf695192fb8afcedfe05b1f4ffcdc5ce", "max_issues_repo_licenses": ["MIT"], "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": "ekloberdanz/Neural-Net-Implementation", "max_forks_repo_head_hexsha": "937dbd2edf695192fb8afcedfe05b1f4ffcdc5ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.9805194805, "max_line_length": 178, "alphanum_fraction": 0.5847595253, "num_tokens": 1845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6041822643021266}}
{"text": "\n#include <gtest/gtest.h>\n#include <Eigen/Eigen>\n\nusing namespace Eigen;\n\ntemplate <DenseIndex rows, DenseIndex cols>\nvoid resizeLikeTest() {\n  MatrixXf A(rows, cols);\n  MatrixXf B;\n  Matrix<double, rows, cols> C;\n  B.resizeLike(A);\n  C.resizeLike(B);  // Shouldn't crash.\n  EXPECT_EQ(B.rows(), rows);\n  EXPECT_EQ(B.cols(), cols);\n\n  VectorXf x(rows);\n  RowVectorXf y;\n  y.resizeLike(x);\n  EXPECT_EQ(y.rows(), 1);\n  EXPECT_EQ(y.cols(), rows);\n\n  y.resize(cols);\n  x.resizeLike(y);\n  EXPECT_EQ(x.rows(), cols);\n  EXPECT_EQ(x.cols(), 1);\n}\n\nTEST(resizeLikeTest12, EXAMPLE) { resizeLikeTest<1, 2>(); }\n\nTEST(resizeLikeTest1020, EXAMPLE) { resizeLikeTest<10, 20>(); }\n\nTEST(resizeLikeTest31, EXAMPLE) { resizeLikeTest<3, 1>(); }\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  int ret = RUN_ALL_TESTS();\n  return ret;\n}\n", "meta": {"hexsha": "80175685cd1940eb08655a05015ea3e81b0fe298", "size": 845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/example/example.cpp", "max_stars_repo_name": "waterben/LineExtraction", "max_stars_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T13:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-12T13:30:56.000Z", "max_issues_repo_path": "test/example/example.cpp", "max_issues_repo_name": "waterben/LineExtraction", "max_issues_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/example/example.cpp", "max_forks_repo_name": "waterben/LineExtraction", "max_forks_repo_head_hexsha": "d247de45417a1512a3bf5d0ffcd630d40ffb8798", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.125, "max_line_length": 63, "alphanum_fraction": 0.6698224852, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375735, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6040969812396453}}
{"text": "/* Copyright (c) 2018, Skolkovo Institute of Science and Technology (Skoltech)\n * All rights reserved.\n *\n * See LICENSE file in the root of the mrob library.\n *\n *\n * SO3.cpp\n *\n *  Created on: Feb 12, 2018\n *      Author: Gonzalo Ferrer\n *              g.ferrer@skoltech.ru\n *              Mobile Robotics Lab, Skoltech\n */\n\n\n#include \"mrob/SO3.hpp\"\n#include <cmath>\n#include <iostream>\n#include <Eigen/LU> // for determinant\n#include <Eigen/Geometry> // for quaternions and rotations\n\n\nusing namespace mrob;\n\nSO3::SO3(const Mat3 &R) :\n        R_(R)\n{\n}\n\nSO3::SO3(const Mat31 &w) :\n        R_(Mat3::Identity())\n{\n    //std::cout << \"SO3 with Mat31\" << std::endl;\n    this->exp(hat3(w));\n}\n\nSO3::SO3(const SO3 &R) :\n        R_(R.R())\n{\n}\n\ntemplate<typename OtherDerived>\nSO3::SO3(const Eigen::MatrixBase<OtherDerived>& rhs)  :\n    R_(rhs)\n{    //std::cout << \"SE3 MAT4\" << std::endl;\n}\n\nSO3& SO3::operator=(const SO3 &rhs)\n{\n    //std::cout << \"SO3 operator equal\" << std::endl;\n    // check for self assignment\n    if (this == &rhs)\n        return *this;\n    R_ = rhs.R();\n    return *this;\n}\n\nSO3 SO3::operator*(const SO3& rhs) const\n{\n    Mat3 res = R_ * rhs.R();\n    return SO3(res);\n}\n\nSO3 SO3::mul(const SO3& rhs) const\n{\n    return (*this) * rhs;\n}\n\nvoid SO3::update_lhs(const Mat31 &dw)\n{\n    SO3 dR(dw);\n    R_ = dR.R() * R_;\n}\n\nvoid SO3::update_rhs(const Mat31 &dw)\n{\n    SO3 dR(dw);\n    R_ = R_ * dR.R();\n}\n\nMat31 mrob::vee3(const Mat3 &w_hat)\n{\n    Mat31 w;\n    w << -w_hat(1,2), w_hat(0,2), -w_hat(0,1);\n    return w;\n}\n\nMat3 mrob::hat3(const Mat31 &w)\n{\n    Mat3 w_hat;\n    w_hat <<     0.0, -w(2),  w(1),\n                w(2),   0.0, -w(0),\n               -w(1),  w(0),   0.0;\n    return w_hat;\n}\n\n\nvoid SO3::exp(const Mat3 &w_hat)\n{\n    Mat31 w = vee3(w_hat);\n    double o = w.norm();\n    double c1,c2;\n    // See numerical_test.cpp to justify this thershold\n    if ( o < 1e-5){\n        // sin(o)/o = 1 - x^2/3! + x^4/5! + O(x^6)\n        c1 =  1 - o*o/6.0;\n        // (1-cos(o))/o^2 = 0.5 + 1/2*f''*x^2/ + ... , where f'' = 1/12\n        c2 = 0.5 - o*o/24.0;\n    }\n    else\n    {\n        // Standard case with the well-known Rodriguez formula\n        c1 = std::sin(o)/o;\n        c2 = (1 - std::cos(o))/o/o;\n    }\n    R_ << Mat3::Identity() + c1 * w_hat + c2 * w_hat *w_hat;\n}\n\nMat3 SO3::ln(double *ro) const\n{\n    // Logarithmic mapping of the rotations\n    Mat3 res;\n    double tr = (R_.trace()-1)*0.5;\n    double o = std::acos(tr); //image in [0,pi]\n    // We choose a tolerance of this small value since the solution involves R being almost symetric\n    if ( tr > -1.0 + 1e0)\n    {\n        // We will evaluate 3 cases:\n        // 1) o (angle) is NaN because trace was exactly 1 plus a small round off, so acos is not defined\n        double d1;\n        // Special case tr =1  and theta -> 0\n        if ( std::isnan(o) )\n        {\n            d1 = 0.0;\n            o = 0.0;\n        }\n        // 2) incorrect x/sin when approaching 0. The other problematic point o = pi is handled below\n        // We choose this value since Taylor improves over the numerical result of the program (see numericap_test.cpp)\n        else if( o < 1e-5)\n        {\n            // Taylor expansion around 0\n            d1 = 0.5 + o*o/12;\n        }\n        // 3) normal case\n        else\n        {\n            d1 = 0.5 * o / std::sin(o);\n        }\n        res << d1 * ( R_ - R_.transpose());\n    }\n    else\n    {\n        // Special case tr = -1  so theta = + pi or multiples\n        // Again, we handle nan's assuming they express exact +-pi plus a numerical error\n        // The second condition stand for the error in acos. Very close to pi it is better (in error) to assume\n        // a rotation of exactly pi\n        if ( std::isnan(o) || M_PI - o < 6e-8 )\n        {\n            o = M_PI;// exact case for theta\n        }\n        // In this case we assume theta is well calculated, but given the almost symetry conditions\n        // on the expansion that allow to solve the problem this way.\n        else\n        {\n            // The result of acos is good enough\n            //std::cout << std::setprecision(20) << M_PI - o << std::endl;\n        }\n        // As we approach pi, the exponent(theta) becomes:\n        // R = I + 0 + (1-cos)/o^2)W^2, which evaluated at +pi = 2/pi^2\n        // This rotation is almost symmetric R = Rt and W = hat(w)\n        // We can consider the first order term sin/o negligible.\n        //\n        // From here, we know that W^2 = ww^t - theta^2I, (you can span W^2 to see this)\n        // which leaves R = I + 2/pi2 (wwt - pi2 I)\n        // R+I = 2/pi2 wwt\n        // wwt = pi2 / 2 (R+I)\n        // so we find the maximum row and apply that formula\n        // knowing that norm(w) = pi (theta)\n        Mat31 w;\n        double d = std::cos(o);\n\n        if( R_(0,0) > R_(1,1) && R_(0,0) > R_(2,2) )\n        {\n            // For stability, we average the two elements since it is almost symetric\n            w << R_(0,0) - d,\n                 0.5 * ( R_(0,1) + R_(1,0)),\n                 0.5 * ( R_(0,2) + R_(2,0));\n        }\n        else if( R_(1,1) > R_(0,0) && R_(1,1) > R_(2,2) )\n        {\n            w << 0.5 * ( R_(1,0) + R_(0,1)),\n                 R_(1,1) - d,\n                 0.5 * ( R_(1,2) + R_(2,1));\n        }\n        else\n        {\n            w << 0.5 * ( R_(2,0) + R_(0,2)),\n                 0.5 * ( R_(2,1) + R_(1,2)),\n                 R_(2,2) - d;\n        }\n        // normalize the vector w, such that norm(w) = theta\n        double length = w.norm();\n        if (length > 0.0)\n        {\n            w *= o / length;\n        }\n        else\n        {\n            w << 0.0, 0.0, 0.0;\n        }\n        res = hat3(w);\n\n        // NOTE: this does not work for very very small theta, which is expectedsince at pi the axis is undefined\n        // The problem of this approach is that we loose the sign of rotation, so we try to estimate it\n        // by comparing R with the 1st order of Exp(w) and Exp(-w).\n        if( (Mat3::Identity() + res - R_ ).norm() >  (Mat3::Identity() - res - R_).norm() )\n        {\n            res *= -1.0;\n            // Note that o is the absolute value of the angle of rotation (don't flip)\n        }\n    }\n    if (ro != nullptr) *ro = o;\n    return res;\n}\n\nMat31 SO3::ln_vee() const\n{\n    Mat3 w_hat = this->ln();\n    return vee3(w_hat);\n}\n\nSO3 SO3::inv(void) const\n{\n    return SO3(R_.transpose());\n}\n\nMat3 SO3::adj() const\n{\n    return R_;\n}\n\nMat3 SO3::R() const\n{\n    return R_;\n}\n\nMat3& SO3::ref2R()\n{\n    return R_;\n}\n\ndouble SO3::distance(const SO3 &rhs) const\n{\n    return (*this * rhs.inv()).ln_vee().norm();\n}\n\nvoid SO3::print(void) const\n{\n    std::cout << R_ << std::endl;\n}\n\n\nvoid SO3::print_lie(void) const\n{\n\n    Mat31 w =  this->ln_vee();\n    std::cout << w << std::endl;\n}\n\nbool mrob::isSO3(Mat3 R)\n{\n    matData_t det = R.determinant();\n    if (det  < 0)\n        return false;\n    if ( fabs(det - 1.0) > 1e-6)\n        return false;\n    return true;\n\n}\n\n\nMat3 mrob::quat_to_so3(const Eigen::Ref<const Mat41> v)\n{\n\n    Eigen::Quaternion<matData_t> q(v);\n    //std::cout << \"Initial vector : \" << v << \", transformed quaternion\" << q.vec() << \"\\n and w = \\n\" << q.toRotationMatrix() << std::endl;\n    return q.normalized().toRotationMatrix();\n}\n\n// quaternion q = [qx, qy, qz, qw](Eigen convention)\nMat41 mrob::so3_to_quat(const Eigen::Ref<const Mat3> R)\n{\n    Eigen::Quaternion<matData_t> q(R);\n    Mat41 res;\n    res << q.x(), q.y(), q.z(), q.w();\n    return res;\n}\n\nMat3 mrob::rpy_to_so3(const Eigen::Ref<const Mat31> v)\n{\n    Mat3 R;\n    R = Eigen::AngleAxisd(v(0), Eigen::Vector3d::UnitX())\n          * Eigen::AngleAxisd(v(1), Eigen::Vector3d::UnitY())\n          * Eigen::AngleAxisd(v(2), Eigen::Vector3d::UnitZ());\n    return R;\n}\n", "meta": {"hexsha": "7747379be2a8f9241016a14f6d794f42c4e81958", "size": 7726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/SO3.cpp", "max_stars_repo_name": "anastasiia-kornilova/mrob", "max_stars_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-10T09:36:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-10T09:36:50.000Z", "max_issues_repo_path": "src/geometry/SO3.cpp", "max_issues_repo_name": "anastasiia-kornilova/mrob", "max_issues_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/SO3.cpp", "max_forks_repo_name": "anastasiia-kornilova/mrob", "max_forks_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1661237785, "max_line_length": 141, "alphanum_fraction": 0.5200621279, "num_tokens": 2505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7431679972357831, "lm_q1q2_score": 0.6040969766157721}}
{"text": "/********************************************************************************\n * Copyright 2017 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_POLYNOMIALND_HPP_\n#define RW_MATH_POLYNOMIALND_HPP_\n\n/**\n * @file PolynomialND.hpp\n *\n * \\copydoc rw::math::PolynomialND\n */\n#if !defined(SWIG)\n#include <rw/core/macros.hpp>\n\n#include <Eigen/Core>\n#include <sstream>\n#include <vector>\n#endif\n\nnamespace rw { namespace math {\n    //! @addtogroup math\n#if !defined(SWIG)\n    //! @{\n\n#endif\n    /**\n     * @brief Representation of a polynomial that can have non-scalar coefficients (polynomial\n     * matrix).\n     *\n     * Representation of a polynomial of the following form:\n     *\n     * @f$\n     *  f(x) = C_n x^n + C_(n-1) x^(n-1) + C_2 x^2 + C_1 x + C_0\n     * @f$\n     *\n     * The polynomial is represented as a list of coefficients ordered from lowest-order term to\n     * highest-order term, \\f$ {c_0,c_1,...,c_n}\\f$.\n     */\n    template< typename Coef, typename Scalar = double > class PolynomialND\n    {\n      public:\n        /**\n         * @brief Create polynomial with uninitialized coefficients.\n         * @param order [in] the order of the polynomial.\n         */\n        explicit PolynomialND (std::size_t order) : _coef (std::vector< Coef > (order + 1)) {}\n\n        /**\n         * @brief Create polynomial from vector.\n         * @param coefficients [in] the coefficients ordered from lowest-order term to highest-order\n         * term.\n         */\n        PolynomialND (const std::vector< Coef >& coefficients) : _coef (coefficients) {}\n\n        /**\n         * @brief Create polynomial from other polynomial.\n         * @param p [in] the polynomial to copy.\n         */\n        PolynomialND (const PolynomialND< Coef, Scalar >& p) :\n            _coef (std::vector< Coef > (p.order () + 1))\n        {\n            for (std::size_t i = 0; i <= p.order (); i++)\n                _coef[i] = p[i];\n        }\n\n        /**\n         * @brief Destructor\n         */\n        virtual ~PolynomialND () {}\n\n        /**\n         * @brief Get the order of the polynomial (the highest power).\n         * @return the order.\n         */\n        std::size_t order () const { return _coef.size () - 1; }\n\n        /**\n         * @brief Increase the order of this polynomial.\n         * @param increase [in] how much to increase the order (default is 1).\n         * @param value [in] initialize new coefficients to this value.\n         */\n        void increaseOrder (std::size_t increase, const Coef& value)\n        {\n            const std::size_t size = _coef.size ();\n            _coef.resize (size + increase);\n            for (std::size_t i = size; i < size + increase; i++) {\n                _coef[i] = value;\n            }\n        }\n#if !defined(SWIGJAVA)\n\n        /**\n         * @brief Increase the order of this polynomial.\n         * @param increase [in] how much to increase the order (default is 1).\n         * @see increaseOrder(std::size_t,const Coef&) for a version that initializes the new\n         * coefficients to a certain value.\n         */\n#endif\n        void increaseOrder (std::size_t increase = 1)\n        {\n            const std::size_t size = _coef.size ();\n            _coef.resize (size + increase);\n        }\n\n        /**\n         * @brief Evaluate the polynomial using Horner's Method.\n         * @param x [in] the input parameter.\n         * @return the value \\f$ f(x)\\f$.\n         */\n        Coef evaluate (const Scalar& x) const\n        {\n            // Horner's Method\n            Coef res = _coef.back ();\n            for (int i = static_cast< int > (_coef.size () - 2); i >= 0; i--)\n                res = _coef[i] + res * x;\n            return res;\n        }\n\n        /**\n         * @brief Evaluate the first \\b n derivatives of the polynomial using Horner's Method.\n         * @param x [in] the input parameter.\n         * @param n [in] the number of derivatives to find (default is the first derivative only)\n         * @return a vector of values \\f$ {f(x),\\dot{f}(x),\\ddot{f}(x),\\cdots}\\f$.\n         */\n        std::vector< Coef > evaluateDerivatives (const Scalar& x, std::size_t n = 1) const\n        {\n            // Horner's Method\n            std::vector< Coef > res (n + 1);\n            res[0] = _coef.back ();\n            for (int i = static_cast< int > (_coef.size () - 2); i >= 0; i--) {\n                int minJ = static_cast< int > (std::min< std::size_t > (n, _coef.size () - 1 - i));\n                for (int j = minJ; j > 0; j--) {\n                    res[j] = res[j - 1] + res[j] * x;\n                }\n                res[0] = _coef[i] + res[0] * x;\n            }\n            Scalar k = 1;\n            for (std::size_t i = 2; i <= n; i++) {\n                const Scalar kInit = k;\n                for (std::size_t j = 0; j < i - 1; j++) {\n                    k += kInit;\n                }\n                res[i] *= k;\n            }\n            return res;\n        }\n\n        /**\n         * @brief Perform deflation of polynomial.\n         * @param x [in] a root of the polynomial.\n         * @return a new polynomial of same order minus one.\n         * @note There is no check that the given root is in fact a root of the polynomial.\n         */\n        PolynomialND< Coef, Scalar > deflate (const Scalar& x) const\n        {\n            // Horner Method\n            std::size_t no = order () - 1;\n            PolynomialND< Coef, Scalar > res (no);\n            res[no] = _coef.back ();\n            for (int i = (int) no - 1; i >= 0; i--) {\n                res[i] = x * res[i + 1] + _coef[i + 1];\n            }\n            return res;\n        }\n\n        /**\n         * @brief Get the derivative polynomial.\n         * @param n [in] gives the n'th derivative (default is n=1).\n         * @return a new polynomial of same order minus one.\n         * @note To evaluate derivatives use the evaluate derivative method which is more precise.\n         */\n        PolynomialND< Coef, Scalar > derivative (std::size_t n = 1) const\n        {\n            if (n == 0)\n                return *this;\n            std::size_t no = order () - 1;\n            PolynomialND< Coef, Scalar > der (no);\n            for (std::size_t i = 1; i <= order (); i++)\n                der[i - 1] = (Coef) (_coef[i] * double(i));\n            return der.derivative (n - 1);\n        }\n\n        /**\n         * @name Coefficient access operators.\n         * Operators used to access coefficients.\n         */\n#if !defined(SWIG)\n        ///@{\n\n        /**\n         * @brief Get specific coefficient.\n         * @param i [in] the power of the term to get coefficient for.\n         * @return the coefficient.\n         */\n        const Coef& operator() (std::size_t i) const\n        {\n            if (i > order ()) {\n                std::stringstream str;\n                str << \"Polynomial of order \" << order () << \" has no coefficient with index \" << i;\n                RW_THROW (str.str ());\n            }\n            return _coef[i];\n        }\n\n        /**\n         * @brief Get specific coefficient.\n         * @param i [in] the power of the term to get coefficient for.\n         * @return the coefficient.\n         */\n        Coef& operator() (size_t i)\n        {\n            if (i > order ()) {\n                std::stringstream str;\n                str << \"Polynomial of order \" << order () << \" has no coefficient with index \" << i;\n                RW_THROW (str.str ());\n            }\n            return _coef[i];\n        }\n\n        /**\n         * @brief Get specific coefficient.\n         * @param i [in] the power of the term to get coefficient for.\n         * @return the coefficient.\n         */\n        const Coef& operator[] (size_t i) const\n        {\n            if (i > order ()) {\n                std::stringstream str;\n                str << \"Polynomial of order \" << order () << \" has no coefficient with index \" << i;\n                RW_THROW (str.str ());\n            }\n            return _coef[i];\n        }\n\n        /**\n         * @brief Get specific coefficient.\n         * @param i [in] the power of the term to get coefficient for.\n         * @return the coefficient.\n         */\n        Coef& operator[] (size_t i)\n        {\n            if (i > order ()) {\n                std::stringstream str;\n                str << \"Polynomial of order \" << order () << \" has no coefficient with index \" << i;\n                RW_THROW (str.str ());\n            }\n            return _coef[i];\n        }\n#else\n\n        ARRAYOPERATOR (Coef);\n\n#endif\n#if !defined(SWIG)\n///@}\n#endif\n\n        /**\n         * @name Arithmetic operators between polynomial and scalars.\n         * Operators used to do arithmetic with scalars.\n         */\n\n#if !defined(SWIG)\n        ///@{\n#endif\n        /**\n         * @brief Scalar multiplication\n         * @param s [in] scalar to multiply with.\n         * @return new polynomial after multiplication.\n         */\n        const PolynomialND< Coef, Scalar > operator* (Scalar s) const\n        {\n            PolynomialND< Coef, Scalar > pol (order ());\n            for (std::size_t i = 0; i <= order (); i++) {\n                pol[i] = _coef[i] * s;\n            }\n            return pol;\n        }\n\n        /**\n         * @brief Scalar division\n         * @param s [in] scalar to divide with.\n         * @return new polynomial after division.\n         */\n        const PolynomialND< Coef, Scalar > operator/ (Scalar s) const\n        {\n            PolynomialND< Coef, Scalar > pol (order ());\n            for (std::size_t i = 0; i <= order (); i++) {\n                pol[i] = _coef[i] / s;\n            }\n            return pol;\n        }\n\n        /**\n         * @brief Scalar multiplication\n         * @param s [in] the scalar to multiply with.\n         * @return reference to same polynomial with changed coefficients.\n         */\n        PolynomialND< Coef, Scalar >& operator*= (Scalar s)\n        {\n            for (std::size_t i = 0; i <= order (); i++) {\n                _coef[i] *= s;\n            }\n            return *this;\n        }\n\n        /**\n         * @brief Scalar division\n         * @param s [in] the scalar to divide with.\n         * @return reference to same polynomial with changed coefficients.\n         */\n        PolynomialND< Coef, Scalar >& operator/= (Scalar s)\n        {\n            for (std::size_t i = 0; i <= order (); i++) {\n                _coef[i] /= s;\n            }\n            return *this;\n        }\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Scalar multiplication\n         * @param s [in] scalar to multiply with.\n         * @param p [in] polynomial to multiply with.\n         * @return new polynomial after multiplication.\n         */\n        friend const PolynomialND< Coef, Scalar > operator* (Scalar s,\n                                                             const PolynomialND< Coef, Scalar >& p)\n        {\n            PolynomialND< Coef, Scalar > pol (p.order ());\n            for (std::size_t i = 0; i <= p.order (); i++) {\n                pol[i] = p[i] * s;\n            }\n            return pol;\n        }\n#endif\n#if !defined(SWIG)\n        ///@}\n#endif\n\n        /**\n         * @name Arithmetic operators between polynomials.\n         * Operators used to do arithmetic between two polynomials.\n         */\n\n#if !defined(SWIG)\n        ///@{\n#endif\n\n        /**\n         * @brief Polynomial subtraction.\n         * @param b [in] polynomial of to subtract.\n         * @return new polynomial after subtraction.\n         */\n        const PolynomialND< Coef, Scalar > operator- (const PolynomialND< Coef, Scalar >& b) const\n        {\n            const std::size_t thisOrder = order ();\n            const std::size_t bOrder    = b.order ();\n            if (bOrder > thisOrder) {\n                PolynomialND< Coef, Scalar > pol (bOrder);\n                for (std::size_t i = 0; i <= thisOrder; i++) {\n                    pol[i] = (*this)[i] - b[i];\n                }\n                for (std::size_t i = thisOrder + 1; i <= bOrder; i++) {\n                    pol[i] = -b[i];\n                }\n                return pol;\n            }\n            else {\n                PolynomialND< Coef, Scalar > pol (thisOrder);\n                for (std::size_t i = 0; i <= bOrder; i++) {\n                    pol[i] = (*this)[i] - b[i];\n                }\n                for (std::size_t i = bOrder + 1; i <= thisOrder; i++) {\n                    pol[i] = (*this)[i];\n                }\n                return pol;\n            }\n        }\n\n        /**\n         * @brief Polynomial subtraction.\n         * @param b [in] polynomial to subtract.\n         * @return same polynomial with different coefficients after subtraction.\n         */\n        PolynomialND< Coef, Scalar >& operator-= (const PolynomialND< Coef, Scalar >& b)\n        {\n            const std::size_t thisOrder = order ();\n            const std::size_t bOrder    = b.order ();\n            if (bOrder > thisOrder) {\n                increaseOrder (bOrder - thisOrder);\n                for (std::size_t i = 0; i <= thisOrder; i++) {\n                    (*this)[i] -= b[i];\n                }\n                for (std::size_t i = thisOrder + 1; i <= bOrder; i++) {\n                    (*this)[i] = -b[i];\n                }\n            }\n            else {\n                for (std::size_t i = 0; i <= bOrder; i++) {\n                    (*this)[i] -= b[i];\n                }\n            }\n            return *this;\n        }\n\n        /**\n         * @brief Polynomial addition.\n         * @param b [in] polynomial to add.\n         * @return new polynomial after addition.\n         */\n        const PolynomialND< Coef, Scalar > operator+ (const PolynomialND< Coef, Scalar >& b) const\n        {\n            const std::size_t thisOrder = order ();\n            const std::size_t bOrder    = b.order ();\n            if (bOrder > thisOrder) {\n                PolynomialND< Coef, Scalar > pol (bOrder);\n                for (std::size_t i = 0; i <= thisOrder; i++) {\n                    pol[i] = (*this)[i] + b[i];\n                }\n                for (std::size_t i = thisOrder + 1; i <= bOrder; i++) {\n                    pol[i] = b[i];\n                }\n                return pol;\n            }\n            else {\n                PolynomialND< Coef, Scalar > pol (thisOrder);\n                for (std::size_t i = 0; i <= bOrder; i++) {\n                    pol[i] = (*this)[i] + b[i];\n                }\n                for (std::size_t i = bOrder + 1; i <= thisOrder; i++) {\n                    pol[i] = (*this)[i];\n                }\n                return pol;\n            }\n        }\n\n        /**\n         * @brief Polynomial addition.\n         * @param b [in] polynomial to add.\n         * @return same polynomial with different coefficients after addition.\n         */\n        PolynomialND< Coef, Scalar >& operator+= (const PolynomialND< Coef, Scalar >& b)\n        {\n            const std::size_t thisOrder = order ();\n            const std::size_t bOrder    = b.order ();\n            if (bOrder > thisOrder) {\n                increaseOrder (bOrder - thisOrder);\n                for (std::size_t i = 0; i <= thisOrder; i++) {\n                    (*this)[i] += b[i];\n                }\n                for (std::size_t i = thisOrder + 1; i <= bOrder; i++) {\n                    (*this)[i] = b[i];\n                }\n            }\n            else {\n                for (std::size_t i = 0; i <= bOrder; i++) {\n                    (*this)[i] += b[i];\n                }\n            }\n            return *this;\n        }\n\n        /**\n         * @brief Polynomial multiplication.\n         *\n         * A convolution of the coefficients is used.\n         * Notice that more efficient algorithms exist for polynomials with scalar coefficients.\n         *\n         * @param b [in] polynomial to multiply. Post-multiplication is used - the dimensions must\n         * match.\n         * @return new polynomial after multiplication.\n         */\n        template< typename OutCoef, typename Coef2 = Coef >\n        PolynomialND< OutCoef, Scalar > multiply (const PolynomialND< Coef2, Scalar >& b) const\n        {\n            const std::size_t ord = order () + b.order ();\n            PolynomialND< OutCoef, Scalar > pol (ord);\n            for (std::size_t k = 0; k <= ord; k++) {\n                const std::size_t firstJ = (k < b.order ()) ? 0 : k - b.order ();\n                pol[ord - k]             = _coef[order () - firstJ] * b[b.order () - (k - firstJ)];\n                for (std::size_t j = firstJ + 1; j <= std::min (k, order ()); j++) {\n                    pol[ord - k] += _coef[order () - j] * b[b.order () - (k - j)];\n                }\n            }\n            return pol;\n        }\n\n        /**\n         * @brief Multiply with a coefficient.\n         *\n         * Each coefficient is post-multiplied with the given coefficient.\n         *\n         * @param b [in] coefficient to multiply with. Post-multiplication is used - the dimensions\n         * must match.\n         * @return new polynomial after multiplication.\n         */\n        template< typename OutCoef, typename Coef2 = Coef >\n        PolynomialND< OutCoef, Scalar > multiply (const Coef2& b) const\n        {\n            PolynomialND< OutCoef, Scalar > pol (order ());\n            for (std::size_t i = 0; i <= order (); i++) {\n                pol[i] = _coef[i] * b;\n            }\n            return pol;\n        }\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Assignment.\n         * @param b [in] the polynomial to take coefficients from.\n         */\n        void operator= (const PolynomialND< Coef, Scalar >& b)\n        {\n            _coef.resize (b.order () + 1);\n            for (size_t i = 0; i <= b.order (); i++)\n                _coef[i] = b[i];\n        }\n#endif\n#if !defined(SWIG)\n///@}\n#endif\n\n        /**\n         * @brief Negate coefficients.\n         * @return new polynomial with coefficients negated.\n         */\n        const PolynomialND< Coef, Scalar > operator- () const\n        {\n            PolynomialND< Coef, Scalar > pol (order ());\n            for (std::size_t i = 0; i <= order (); i++) {\n                pol[i] = (Coef) (_coef[i] * double(-1));\n            }\n            return pol;\n        }\n#if !defined(SWIG)\n        /**\n         * @brief Printing polynomial to stream.\n         * @param out [in/out] the stream to write to.\n         * @param p [in] the polynomail to print.\n         * @return the same ostream as out parameter.\n         */\n        friend std::ostream& operator<< (std::ostream& out, const PolynomialND< Coef, Scalar >& p)\n        {\n            out << \"Polynomial: \";\n            for (size_t i = p.order (); i > 0; i--)\n                out << p[i] << \" x^\" << i << \" + \";\n            out << p[0];\n            return out;\n        }\n#else\n#define tmp Coef, Scalar\n        TOSTRING (rw::math::PolynomialND< tmp >);\n#endif\n\n        /**\n         * @brief Check if polynomials are equal.\n         * @param b [in] the polynomial to compare with.\n         * @return true if equal, false if not.\n         */\n        bool operator== (const PolynomialND< Coef, Scalar >& b) const\n        {\n            for (size_t i = 0; i <= order (); i++)\n                if (_coef[i] != b[i])\n                    return false;\n            return true;\n        }\n\n      protected:\n        //! @brief The coefficient vector.\n        std::vector< Coef > _coef;\n    };\n\n    /**\n     * @brief Multiply 3D polynomial matrix with 3D polynomial vector.\n     * @param A [in] the matrix expression.\n     * @param b [in] the vector expression.\n     * @return a 3D polynomial vector.\n     */\n    PolynomialND< Eigen::Vector3d > operator* (const PolynomialND< Eigen::Matrix3d >& A,\n                                               const PolynomialND< Eigen::Vector3d >& b);\n\n    /**\n     * @brief Multiply 3D polynomial vector with 3D polynomial matrix.\n     * @param a [in] the vector expression.\n     * @param A [in] the matrix expression.\n     * @return a 3D polynomial vector.\n     */\n    PolynomialND< Eigen::Matrix< double, 1, 3 > >\n    operator* (const PolynomialND< Eigen::Matrix< double, 1, 3 > >& a,\n               const PolynomialND< Eigen::Matrix3d >& A);\n# if !defined(SWIGJAVA)\n    //! @copydoc operator*(const PolynomialND<Eigen::Matrix3d>&, const\n    //! PolynomialND<Eigen::Vector3d>&)\n\n    #endif \n    PolynomialND< Eigen::Vector3d > operator* (const PolynomialND< Eigen::Matrix3d >& A,\n                                               const Eigen::Vector3d& b);\n#if !defined(SWIGJAVA)\n    //! @copydoc operator*(const PolynomialND<Eigen::Matrix<double,1,3> >&, const\n    //! PolynomialND<Eigen::Matrix3d>&)\n\n    #endif \n    PolynomialND< Eigen::Matrix< double, 1, 3 > >\n    operator* (const PolynomialND< Eigen::Matrix< double, 1, 3 > >& a, const Eigen::Matrix3d& A);\n\n#if !defined(SWIGJAVA)\n    //! @copydoc operator*(const PolynomialND<Eigen::Matrix3d>&, const\n    //! PolynomialND<Eigen::Vector3d>&)\n\n    #endif \n    PolynomialND< Eigen::Vector3f, float >\n    operator* (const PolynomialND< Eigen::Matrix3f, float >& A,\n               const PolynomialND< Eigen::Vector3f, float >& b);\n#if !defined(SWIGJAVA)\n    //! @copydoc operator*(const PolynomialND<Eigen::Matrix<double,1,3> >&, const\n    //! PolynomialND<Eigen::Matrix3d>&)\n\n    #endif \n    PolynomialND< Eigen::Matrix< float, 1, 3 >, float >\n    operator* (const PolynomialND< Eigen::Matrix< float, 1, 3 >, float >& a,\n               const PolynomialND< Eigen::Matrix3f, float >& A);\n#if !defined(SWIGJAVA)\n    //! @copydoc operator*(const PolynomialND<Eigen::Matrix3d>&, const Eigen::Vector3d&)\n\n    #endif \n    PolynomialND< Eigen::Vector3f, float >\n    operator* (const PolynomialND< Eigen::Matrix3f, float >& A, const Eigen::Vector3f& b);\n\n#if !defined(SWIGJAVA)\n    //! @copydoc operator*(const PolynomialND<Eigen::Matrix<double,1,3> >&, const Eigen::Matrix3d&)\n    \n    #endif\n    PolynomialND< Eigen::Matrix< float, 1, 3 >, float >\n    operator* (const PolynomialND< Eigen::Matrix< float, 1, 3 >, float >& a,\n               const Eigen::Matrix3f& A);\n\n    //! @}\n}}    // namespace rw::math\n\n#endif /* RW_MATH_POLYNOMIALND_HPP_ */\n", "meta": {"hexsha": "c2a3330755fb7a5947be786d5650b2a3e8723013", "size": 22760, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/PolynomialND.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/PolynomialND.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/PolynomialND.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8012232416, "max_line_length": 100, "alphanum_fraction": 0.489543058, "num_tokens": 5554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6040929575104178}}
{"text": "#ifndef BFGS_HPP\n#define BFGS_HPP\n\n#include <Eigen/Dense>\n#include <limits>\n\n/** Damped BFGS update\n * Implements \"Procedure 18.2 Damped BFGS updating for SQP\" form Numerical Optimization by Nocedal.\n *\n * @param[in,out]   B hessian matrix, is updated by this function\n * @param[in]       s step vector (x - x_prev)\n * @param[in]       y gradient change (grad - grad_prev)\n */\ntemplate <typename Mat, typename Vec>\nvoid BFGS_update(Mat& B, const Vec& s, const Vec& y) {\n    using Scalar = typename Mat::Scalar;\n    Scalar sy, sr, sBs;\n    Vec Bs, r;\n\n    Bs.noalias() = B * s;\n    sBs = s.dot(Bs);\n    sy = s.dot(y);\n\n    if (sy < 0.2 * sBs) {\n        // damped update to enforce positive definite B\n        Scalar theta;\n        theta = 0.8 * sBs / (sBs - sy);\n        r.noalias() = theta * y + (1 - theta) * Bs;\n        sr = theta * sy + (1 - theta) * sBs;\n    } else {\n        // unmodified BFGS\n        r = y;\n        sr = sy;\n    }\n\n    if (sr < std::numeric_limits<Scalar>::epsilon()) {\n        return;\n    }\n\n    B.noalias() += -Bs * Bs.transpose() / sBs + r * r.transpose() / sr;\n}\n\n// extern template void BFGS_update<Eigen::MatrixXd, Eigen::VectorXd>(Eigen::MatrixXd& B,\n//                                                                    const Eigen::VectorXd& s,\n//                                                                    const Eigen::VectorXd& y)\n\n#endif /* BFGS_HPP */\n", "meta": {"hexsha": "3b1c52cd107be848fd168c674b5d240faf4add92", "size": 1396, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/solvers/bfgs.hpp", "max_stars_repo_name": "nuft/sqp_solver", "max_stars_repo_head_hexsha": "7d059a717bb649d63ab27e4d3ec967b42a8b071c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2019-10-16T08:05:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T04:51:20.000Z", "max_issues_repo_path": "include/solvers/bfgs.hpp", "max_issues_repo_name": "likping/sqp_solver", "max_issues_repo_head_hexsha": "7d059a717bb649d63ab27e4d3ec967b42a8b071c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-19T19:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-16T09:18:04.000Z", "max_forks_repo_path": "include/solvers/bfgs.hpp", "max_forks_repo_name": "likping/sqp_solver", "max_forks_repo_head_hexsha": "7d059a717bb649d63ab27e4d3ec967b42a8b071c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-10-18T17:47:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:07:22.000Z", "avg_line_length": 29.0833333333, "max_line_length": 99, "alphanum_fraction": 0.5272206304, "num_tokens": 382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.604092949490023}}
{"text": "#include \"catch.hpp\"\n\n#include <vector>\n\n#include <boost/multi_array.hpp>\n\n#include \"Utils.h\"\n#include \"fakeit.hpp\"\n\nusing namespace boost;\n\ntemplate<typename T, long unsigned int N>\nusing ma = multi_array<T, N>;\ntemplate<typename T, long unsigned int N>\nusing I = typename ma<T, N>::index;\ntypedef multi_array_types::index_range R;\n\nTEST_CASE(\"Boost.Multiarray Examples\", \"[example]\")\n{\n  int           Nx = 2, Ny = 3, Nz = 4;\n  ma<double, 3> cube(extents[2][3][4]);\n\n  for (int i = 0; i < Nx; ++i)\n    for (int j = 0; j < Ny; ++j)\n      for (int k = 0; k < Nz; ++k) cube[i][j][k] = i * j * k;\n\n  for (int i = 0; i < Nx; ++i)\n    for (int j = 0; j < Ny; ++j)\n      for (int k = 0; k < Nz; ++k) CHECK(cube[i][j][k] == Approx(i * j * k));\n\n  auto plane = cube[indices[R()][1][R()]];\n\n  for (int i = 0; i < Nx; ++i)\n    for (int k = 0; k < Nz; ++k) CHECK(plane[i][k] == Approx(i * 1 * k));\n\n  plane[0][0] = -10;\n\n  CHECK(plane[0][0] == Approx(-10));\n  CHECK(cube[0][0][0] == Approx(0));\n  CHECK(cube[0][1][0] == Approx(-10));\n\n  cube[0][1][0] = 0 * 1 * 0;\n\n  auto line = plane[indices[1][R()]];\n\n  CHECK(line[0] == plane[1][0]);\n  CHECK(line[0] == cube[1][1][0]);\n\n  line[2] = -10;\n\n  CHECK(line[2] == -10);\n  CHECK(plane[1][2] == -10);\n  CHECK(cube[1][1][2] == -10);\n}\n\nTEST_CASE(\"Boost.Multiarray Complex Matrix\", \"[example]\")\n{\n  int N = 3;\n\n  ma<double, 3> A(extents[N][N][2]);\n\n  A[0][0][0] = 1;\n  A[0][0][1] = 2;\n  A[0][1][0] = 1;\n  A[0][1][1] = 2;\n  A[0][2][0] = 1;\n  A[0][2][1] = 2;\n  A[1][0][0] = 1;\n  A[1][0][1] = 2;\n  A[1][1][0] = 1;\n  A[1][1][1] = 2;\n  A[1][2][0] = 1;\n  A[1][2][1] = 2;\n  A[2][0][0] = 1;\n  A[2][0][1] = 2;\n  A[2][1][0] = 1;\n  A[2][1][1] = 2;\n  A[2][2][0] = 1;\n  A[2][2][1] = 2;\n\n  auto Ar = A[indices[R()][R()][0]];\n  auto Ai = A[indices[R()][R()][1]];\n\n  for (int i = 0; i < N; ++i)\n    for (int j = 0; j < N; ++j) CHECK(Ar[i][j] == 1);\n\n  for (int i = 0; i < N; ++i)\n    for (int j = 0; j < N; ++j) CHECK(Ai[i][j] == 2);\n\n  int  i  = 0;\n  auto AA = A[indices[R()][R()][i]];\n\n  for (int i = 0; i < N; ++i)\n    for (int j = 0; j < N; ++j) CHECK(AA[i][j] == 1);\n}\n\nTEST_CASE(\"Boost.Multiarray Dynamic Slicing\", \"[example]\")\n{\n  int N = 3;\n\n  ma<double, 2> A(extents[N][N]);\n  for (int i = 0; i < N; i++)\n    for (int j = 0; j < N; j++) A[i][j] = i * j;\n\n  for (int i = 0; i < N; ++i)\n    for (int j = 0; j < N; ++j) CHECK(A[i][j] == i * j);\n\n  int  d  = 1;\n  auto Av = A[indices[R()][d]];\n\n  for (int i = 0; i < N; ++i) CHECK(Av[i] == i * 1);\n}\n\nTEST_CASE(\"Boost.Multiarray Index Manipulation\", \"[example]\")\n{\n  int           N = 3;\n  ma<double, 2> A(extents[N][N]);\n  for (int i = 0; i < N; i++)\n    for (int j = 0; j < N; j++) A[i][j] = i * j;\n\n  CHECK(A.data() == A.origin());\n\n  array<int, 2> off = {1, 2};\n  A.reindex(off);\n  // now A[1][2] refers to A[0][0]\n  // now A[2][3] refers to A[1][1]\n  // etc.\n  CHECK(A[1][2] == 0);\n  CHECK(A[1][2] == 0);\n  CHECK(A[2][3] == 1);\n\n  for (int i = 1; i < N + 1; i++) {\n    for (int j = 2; j < N + 2; j++) {\n      CHECK(A[i][j] == (i - 1) * (j - 2));\n    }\n  }\n\n  // origin should now be shifted\n  CHECK(A.data() != A.origin());\n\n  off = {-1, -2};\n  A.reindex(off);\n  // now A[-1][-2] refers to A[0][0]\n  // now A[-2][-3] refers to A[1][1]\n  // etc.\n  CHECK(A[-1][-2] == 0);\n  CHECK(A[-1][-2] == 0);\n  CHECK(A[0][-1] == 1);\n\n  for (int i = -1; i < N - 1; i++) {\n    for (int j = -2; j < N - 2; j++) {\n      CHECK(A[i][j] == (i + 1) * (j + 2));\n    }\n  }\n\n  // origin should still be shifted\n  CHECK(A.data() != A.origin());\n\n  off = {0, 0};\n  A.reindex(off);\n\n  // origin should be back data()\n  CHECK(A.data() == A.origin());\n}\n\nTEST_CASE(\"Boost.Multiarray Storage Order\", \"\")\n{\n  int           N = 3;\n  ma<double, 2> A(extents[N][N], c_storage_order());\n  ma<double, 2> B(extents[N][N], fortran_storage_order());\n\n  for (int i = 0; i < N; i++) {\n    for (int j = 0; j < N; j++) {\n      A[i][j] = 10 * i + j;\n      B[i][j] = 10 * i + j;\n    }\n  }\n\n  // have a 3x3 matrix\n  //\n  //   0  1  2\n  //\n  //  10 11 12\n  //\n  //  20 21 22\n  //\n  //\n\n  CHECK(A.data()[0] == 0);\n  CHECK(A.data()[1] == 1);\n  CHECK(A.data()[2] == 2);\n  CHECK(A.data()[3] == 10);\n\n  CHECK(B.data()[0] == 0);\n  CHECK(B.data()[1] == 10);\n  CHECK(B.data()[2] == 20);\n  CHECK(B.data()[3] == 1);\n}\n", "meta": {"hexsha": "13550a39ccab6c8b3da909cb0cc5ffaa5eaf4686", "size": 4236, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "testing/CatchTests/BoostMultiArrayExamples.cpp", "max_stars_repo_name": "CD3/libField", "max_stars_repo_head_hexsha": "8aa93e21d3bbc01c38ecc3a6ea31bd4ceb8bbfd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "testing/CatchTests/BoostMultiArrayExamples.cpp", "max_issues_repo_name": "CD3/libField", "max_issues_repo_head_hexsha": "8aa93e21d3bbc01c38ecc3a6ea31bd4ceb8bbfd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-06-18T17:05:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-05T19:14:38.000Z", "max_forks_repo_path": "testing/CatchTests/BoostMultiArrayExamples.cpp", "max_forks_repo_name": "CD3/libField", "max_forks_repo_head_hexsha": "8aa93e21d3bbc01c38ecc3a6ea31bd4ceb8bbfd6", "max_forks_repo_licenses": ["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.2864321608, "max_line_length": 77, "alphanum_fraction": 0.4553824363, "num_tokens": 1810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.7826624688140728, "lm_q1q2_score": 0.6040929375568196}}
{"text": "#define BOOST_TEST_MODULE test_optionsInstances\n\n#include <boost/test/unit_test.hpp>\n#include <OptionInstances/CallOption.h>\n#include <OptionInstances/PutOption.h>\n\nBOOST_AUTO_TEST_SUITE(optionInstances_test_suite)\n\n    BOOST_AUTO_TEST_CASE(option_getTimeToMaturity) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double strike = 50.0;\n        const double rate = 3.66 / 100;\n        const boost::gregorian::date startDate = boost::gregorian::from_simple_string(\"2013-01-01\");\n        const boost::gregorian::date endDate = boost::gregorian::from_simple_string(\"2016-01-01\");\n        Actual_365 dayCountCalculator = Actual_365();\n\n        const double spot_price = 50.0;\n        double volatility = 62.0 / 100;\n\n        Asset underlyingAsset{spot_price, volatility};\n\n        CallOption my_option{strike, rate, startDate, endDate, dayCountCalculator, underlyingAsset};\n        double theoretical_value = 3.0;\n        double calculated_value = my_option.getTimeToMaturity();\n\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-2));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(call_getReceiving) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double strike = 50.0;\n        const double rate = 3.66 / 100;\n        const boost::gregorian::date startDate = boost::gregorian::from_simple_string(\"2013-01-01\");\n        const boost::gregorian::date endDate = boost::gregorian::from_simple_string(\"2016-01-01\");\n        Actual_365 dayCountCalculator = Actual_365();\n\n        const double spot_price = 50.0;\n        double volatility = 62.0 / 100;\n\n        Asset underlyingAsset{spot_price, volatility};\n\n        CallOption my_option{strike, rate, startDate, endDate, dayCountCalculator, underlyingAsset};\n        double theoretical_value = 36.93239658;\n        double calculated_value = my_option.getReceiving();\n\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-8));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(call_getPaying) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double strike = 50.0;\n        const double rate = 3.66 / 100;\n        const boost::gregorian::date startDate = boost::gregorian::from_simple_string(\"2013-01-01\");\n        const boost::gregorian::date endDate = boost::gregorian::from_simple_string(\"2016-01-01\");\n        Actual_365 dayCountCalculator = Actual_365();\n\n        const double spot_price = 50.0;\n        double volatility = 62.0 / 100;\n\n        Asset underlyingAsset{spot_price, volatility};\n\n        CallOption my_option{strike, rate, startDate, endDate, dayCountCalculator, underlyingAsset};\n        double theoretical_value = 14.86907831;\n        double calculated_value = my_option.getPaying();\n\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-8));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(call_price) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double strike = 50.0;\n        const double rate = 3.66 / 100;\n        const boost::gregorian::date startDate = boost::gregorian::from_simple_string(\"2013-01-01\");\n        const boost::gregorian::date endDate = boost::gregorian::from_simple_string(\"2016-01-01\");\n        Actual_365 dayCountCalculator = Actual_365();\n\n        const double spot_price = 50.0;\n        double volatility = 62.0 / 100;\n\n        Asset underlyingAsset{spot_price, volatility};\n\n        CallOption my_option{strike, rate, startDate, endDate, dayCountCalculator, underlyingAsset};\n        double theoretical_value = 22.06331827;\n        double calculated_value = my_option.price();\n\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-8));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(put_getReceiving) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double strike = 50.0;\n        const double rate = 3.66 / 100;\n        const boost::gregorian::date startDate = boost::gregorian::from_simple_string(\"2013-01-01\");\n        const boost::gregorian::date endDate = boost::gregorian::from_simple_string(\"2016-01-01\");\n        Actual_365 dayCountCalculator = Actual_365();\n\n        const double spot_price = 50.0;\n        double volatility = 62.0 / 100;\n\n        Asset underlyingAsset{spot_price, volatility};\n\n        PutOption my_option{strike, rate, startDate, endDate, dayCountCalculator, underlyingAsset};\n        double theoretical_value = 29.93158769;\n        double calculated_value = my_option.getReceiving();\n\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-8));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(put_getPaying) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double strike = 50.0;\n        const double rate = 3.66 / 100;\n        const boost::gregorian::date startDate = boost::gregorian::from_simple_string(\"2013-01-01\");\n        const boost::gregorian::date endDate = boost::gregorian::from_simple_string(\"2016-01-01\");\n        Actual_365 dayCountCalculator = Actual_365();\n\n        const double spot_price = 50.0;\n        double volatility = 62.0 / 100;\n\n        Asset underlyingAsset{spot_price, volatility};\n\n        PutOption my_option{strike, rate, startDate, endDate, dayCountCalculator, underlyingAsset};\n        double theoretical_value = 13.06760342;\n        double calculated_value = my_option.getPaying();\n\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-8));\n\n    }\n\n    BOOST_AUTO_TEST_CASE(put_price) {\n        BOOST_TEST_MESSAGE(\"using tolerances within checks.\");\n\n        const double strike = 50.0;\n        const double rate = 3.66 / 100;\n        const boost::gregorian::date startDate = boost::gregorian::from_simple_string(\"2013-01-01\");\n        const boost::gregorian::date endDate = boost::gregorian::from_simple_string(\"2016-01-01\");\n        Actual_365 dayCountCalculator = Actual_365();\n\n        const double spot_price = 50.0;\n        double volatility = 62.0 / 100;\n\n        Asset underlyingAsset{spot_price, volatility};\n\n        PutOption my_option{strike, rate, startDate, endDate, dayCountCalculator, underlyingAsset};\n        double theoretical_value = 16.86398427;\n        double calculated_value = my_option.price();\n\n        BOOST_TEST(theoretical_value == calculated_value, boost::test_tools::tolerance(1e-8));\n\n    }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "727cdd782019864a7d6497d72f6e4e3197a48e2a", "size": 6439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "assignment/src/OptionInstances/tests/test.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/OptionInstances/tests/test.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/OptionInstances/tests/test.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": 39.262195122, "max_line_length": 100, "alphanum_fraction": 0.6923435316, "num_tokens": 1527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6040929371672632}}
{"text": "#include \"../Util/MercatorUtil.h\"\n#include \"../Util/ComputeAngle.h\"\n#include \"../Util/SimpleLogger.h\"\n\n#include <osrm/Coordinate.h>\n\n#include \"ConcaveHull.h\"\n\n#include <algorithm>  \n#include <set>\n#include <vector>\n#include <limits>\n#include <valarray>\n#include <boost/foreach.hpp>\n\nfloat getAngle(const FixedPointCoordinate& prev, const FixedPointCoordinate& curr, const FixedPointCoordinate& next, float *outAngle) {\n\tint prev_x = prev.lon , prev_y = prev.lat;\n\tint curr_x = curr.lon , curr_y = curr.lat;\n\tint next_x = next.lon , next_y = next.lat;\n\tif (next_x == curr_x && next_y == curr_y)\n\t\treturn -9000.f;\n\tif (next_x == prev_x && next_y == prev_y)\n\t\treturn -360.f;\n\n\tint a_x = curr_x - prev_x;\n\tint a_y = curr_y - prev_y;\n\tint b_x = next_x - curr_x;\n\tint b_y = next_y - curr_y;\n\tfloat vect = a_x*b_y - b_x*a_y;\n\tfloat scal = a_x*b_x + a_y*b_y;\n\tfloat angle = 0;\n\tif (scal == 0){\n\t\tif (vect > 0)\n\t\t\tangle = 90.f;\n\t\tif (vect < 0)\n\t\t\tangle = -90.f;\n\t}\n\telse {\n\t\tangle = atan(vect / scal) * 180.f / M_PI;\n\t\tif (scal < 0){\n\t\t\tif (vect >= 0)\n\t\t\t\tangle += 180.f;\n\t\t\tif (vect < 0)\n\t\t\t\tangle -= 180.f;\n\t\t}\n\t}\n\tif (angle == 360.f)\n\t\tangle = 0;\n\t*outAngle = 180.f - angle;\n\treturn *outAngle;\n}\n\n\nint ccw(const FixedPointCoordinate& p0, const FixedPointCoordinate& p1, const FixedPointCoordinate& p2) {\n\tint dx1 = p1.lon - p0.lon;\n\tint dy1 = p1.lat - p0.lat;\n\tint dx2 = p2.lon - p0.lon;\n\tint dy2 = p2.lat - p0.lat;\n\tint d = dx1*dy2 - dy1*dx2;\n\tif (d > 0) return 1;\n\tif (d < 0) return -1;\n\tif ((dx1*dx2 < 0) || (dy1*dy2 < 0)) return -1;\n\tif ((dx1*dx1 + dy1*dy1) < (dx2*dx2 + dy2*dy2)) return 1;\n\treturn 0;\n}\n\nbool intersect(const FixedPointCoordinate& p1, const FixedPointCoordinate& p2, const FixedPointCoordinate& q1, const FixedPointCoordinate& q2) {\n\tif ((p1.lon == q1.lon && p1.lat == q1.lat || p2.lon == q2.lon && p2.lat == q2.lat) ||\n\t\t(p1.lon == q2.lon && p1.lat == q2.lat || p2.lon == q1.lon && p2.lat == q1.lat))\n\t\treturn false;\n\n\treturn (ccw(p1, p2, q1) * ccw(p1, p2, q2) <= 0) && (ccw(q1, q2, p1) * ccw(q1, q2, p2) <= 0);\n}\n\n\nbool intersect(const std::vector<FixedPointCoordinate>& hull, const FixedPointCoordinate& next) {\n\tint last = hull.size() - 1;\n\tfor (int i = 1; i < last; i++){\n\t\tif (intersect(hull[i - 1], hull[i], hull[last], next))\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\ninline bool isNear(const FixedPointCoordinate& a, const FixedPointCoordinate& b, int maxLat, int maxLon){\n\treturn (abs(a.lat - b.lat) < maxLat && abs(a.lon - b.lon) < maxLon);\n}\n\n\nvoid calculateHull(const std::vector<FixedPointCoordinate>& points, std::vector<FixedPointCoordinate>& hull, int maxLat, int maxLon) {\n\t\n\thull.clear();\n\n\tif (points.empty())\n\t\treturn;\n\n\t//hull = points;\n\t//return;\n\tstd::vector<int> counts(points.size(), 0);\n\n\tint start = 0;\n\tfor (int i = 1; i < points.size(); i++) {\n\t\tif (points[i].lat < points[start].lat)\n\t\t\tstart = i;\n\t}\n\thull.push_back(points[start]);\n\n\tint curr = start;\n\tint next = -1;\n\tconst FixedPointCoordinate init(points[start].lat - 10, points[start].lon);\n\tconst FixedPointCoordinate *prev = &init;\n\t\n\n#ifdef MyDEBUG\n\tSimpleLogger().Write(logDEBUG) << \"Init: \" << init;\n\tSimpleLogger().Write(logDEBUG) << \"Start: \" << start << \": \" << points[start];\n#endif\n\twhile (next != start) {\n\t\tnext = -1;\n\t\tfloat max_angle = -10000.f;\n\t\tint min_rot = std::numeric_limits<int>::max();\n\t\tfor (int i = 0; i < points.size(); i++) {\n#ifdef MyDEBUG\t\t\t\n\t\t\tSimpleLogger().Write(logDEBUG) << i << \": \" << points[i] \n\t\t\t\t<< \" dist: \" << FixedPointCoordinate::ApproximateEuclideanDistance(points[i], points[curr]) \n\t\t\t\t<< \" [\" << (FixedPointCoordinate::ApproximateEuclideanDistance(points[i], points[curr]) < 1.2 * MAX_POINTS_DIST ? \"v\" : \" \") << \"]\"\n\t\t\t\t<< \" rough: lat \" << abs(points[i].lat - points[curr].lat) << \" lon \" << abs(points[i].lon - points[curr].lon)\n\t\t\t\t<< \" [\" << (isNear(points[i], points[curr], maxLat, maxLon) ? \"v\" : \" \") << \"]\"\n\t\t\n\t\t\t\t<< \" angle: \" << getAngle(*prev, points[curr], points[i]) \n\t\t\t\t//<< \" rot: \" << getRot(*prev, points[curr], points[i])\n\t\t\t\t<< \" intersect:\" << intersect(hull, points[i]);\n#endif\n\t\t\tfloat angle = -10000.f;\n\t\t\tif (i != curr && isNear(points[i], points[curr], maxLat, maxLon)\n\t\t\t\t&& getAngle(*prev, points[curr], points[i], &angle) > max_angle\n\t\t\t\t&& !intersect(hull, points[i])) \n\t\t\t{\n\t\t\t\tmax_angle = angle;\n\t\t\t\tnext = i;\n\t\t\t}\n\t\t}\n\t\t//BOOST_ASSERT(next >= 0);\n\t\tif (next < 0) {\n\t\t\tSimpleLogger().Write(logWARNING) << \"Error in hull calculations.\";\n\t\t\thull.push_back(points[start]);\n\t\t\treturn;\n\t\t}\n\t\thull.push_back(points[next]);\n\t\tif (++counts[next] > 4){\n\t\t\tSimpleLogger().Write(logWARNING) << \"Something goes wrong in hull calculations.\";\n\t\t\thull.push_back(points[start]);\n\t\t\treturn;\n\t\t}\n\n#ifdef MyDEBUG\n\t\tSimpleLogger().Write(logDEBUG) << curr << \" -> \" << next;\n#endif\n\t\tprev = &points[curr];\n\t\tcurr = next;\n\t}\n\treturn;\n};\n\n\nvoid concaveHull(const std::set<FixedPointCoordinate>& coordinates, std::vector<FixedPointCoordinate>& hull) {\n\t\n\tif (coordinates.empty())\n\t\treturn;\n\n\tconst FixedPointCoordinate& start = *coordinates.begin();\n\t\n\t// calculate scale by lat and scale by lon for current geographic area\n\tFixedPointCoordinate south(start.lat - 100, start.lon);\n\tFixedPointCoordinate east(start.lat, start.lon - 100);\n\tint maxLat = 100 * MAX_POINTS_DIST / FixedPointCoordinate::ApproximateDistance(south, start);\n\tint maxLon = 100 * MAX_POINTS_DIST / FixedPointCoordinate::ApproximateDistance(east, start);\n\n\tstd::vector<FixedPointCoordinate> points;\n\n\tpoints.reserve(coordinates.size() + 1);\n\tint min_point = 0, i = 0;\n\tBOOST_FOREACH(FixedPointCoordinate coord, coordinates)\n\t{\n\t\tpoints.push_back(coord);\n\t\tif (points[i++].lat < points[min_point].lat)\n\t\t\tmin_point = i;\n\t}\n\tsouth.lat = points[min_point].lat - maxLat;\n\tsouth.lon = points[min_point].lon;\n\tpoints.push_back(south);\n\n\tcalculateHull(points, hull, maxLat*1.2, maxLon*1.2);\n\thull[0] = hull[1];\n\tif (hull.size() > 1)\n\t\thull[hull.size() - 1] = hull[hull.size() - 2];\n\tSimpleLogger().Write(logINFO) << \"First hull: \" << hull.size() << \" points. Expanding...\";\n\n\n\tint dLat = maxLat / 1.4142135623730950488016887242097;\n\tint dLon = maxLon / 1.4142135623730950488016887242097;\n\t\n\tstd::vector<FixedPointCoordinate> expanded;\n\texpanded.reserve((hull.size() - 1) * 8);\n\tfor (int i = 0; i < hull.size() - 1; i++) {\n\t\tFixedPointCoordinate p0(hull[i].lat + maxLat, hull[i].lon);\n\t\texpanded.push_back(p0);\n\t\tFixedPointCoordinate p1(hull[i].lat - maxLat, hull[i].lon);\n\t\texpanded.push_back(p1);\n\t\tFixedPointCoordinate p2(hull[i].lat, hull[i].lon + maxLon);\n\t\texpanded.push_back(p2);\n\t\tFixedPointCoordinate p3(hull[i].lat, hull[i].lon - maxLon);\n\t\texpanded.push_back(p3);\n\t\tFixedPointCoordinate p4(hull[i].lat + dLat, hull[i].lon + dLon);\n\t\texpanded.push_back(p4);\n\t\tFixedPointCoordinate p5(hull[i].lat - dLat, hull[i].lon - dLon);\n\t\texpanded.push_back(p5);\n\t\tFixedPointCoordinate p6(hull[i].lat - dLat, hull[i].lon + dLon);\n\t\texpanded.push_back(p6);\n\t\tFixedPointCoordinate p7(hull[i].lat + dLat, hull[i].lon - dLon);\n\t\texpanded.push_back(p7);\n\t}\n\tcalculateHull(expanded, hull, maxLat*1.2, maxLon*1.2);\n\t\n}\n", "meta": {"hexsha": "839a9cdebfd53d3b66968494b277a5a6fa87504c", "size": 7026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Algorithms/ConcaveHull.cpp", "max_stars_repo_name": "nredko/Project-OSRM", "max_stars_repo_head_hexsha": "c0bb5d72711285031aa11d8f0182bc1f7d278c7d", "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": "Algorithms/ConcaveHull.cpp", "max_issues_repo_name": "nredko/Project-OSRM", "max_issues_repo_head_hexsha": "c0bb5d72711285031aa11d8f0182bc1f7d278c7d", "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": "Algorithms/ConcaveHull.cpp", "max_forks_repo_name": "nredko/Project-OSRM", "max_forks_repo_head_hexsha": "c0bb5d72711285031aa11d8f0182bc1f7d278c7d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0884955752, "max_line_length": 144, "alphanum_fraction": 0.6477369769, "num_tokens": 2221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.604052224595838}}
{"text": "#include <boost/gil/typedefs.hpp>\n#include <boost/gil/image_processing/numeric.hpp>\n#include <boost/gil/extension/io/png.hpp>\n#include <boost/gil/extension/numeric/convolve.hpp>\n#include <string>\n#include <iostream>\n\nnamespace gil = boost::gil;\n\nint main(int argc, char* argv[])\n{\n    if (argc != 5)\n    {\n        std::cerr << \"usage: \" << argv[0] << \": <input.png> <sobel|scharr> <output-x.png> <output-y.png>\\n\";\n        return -1;\n    }\n\n    gil::gray8_image_t input_image;\n    gil::read_image(argv[1], input_image, gil::png_tag{});\n    auto input = gil::view(input_image);\n    auto filter_type = std::string(argv[2]);\n\n    gil::gray16_image_t dx_image(input_image.dimensions());\n    auto dx = gil::view(dx_image);\n    gil::gray16_image_t dy_image(input_image.dimensions());\n    auto dy = gil::view(dy_image);\n    if (filter_type == \"sobel\")\n    {\n        gil::convolve_2d(input, gil::generate_dx_sobel(1), dx);\n        gil::convolve_2d(input, gil::generate_dy_sobel(1), dy);\n    }\n    else if (filter_type == \"scharr\")\n    {\n        gil::convolve_2d(input, gil::generate_dx_scharr(1), dx);\n        gil::convolve_2d(input, gil::generate_dy_scharr(1), dy);\n    }\n    else\n    {\n        std::cerr << \"unrecognized gradient filter type. Must be either sobel or scharr\\n\";\n        return -1;\n    }\n\n    gil::write_view(argv[3], dx, gil::png_tag{});\n    gil::write_view(argv[4], dy, gil::png_tag{});\n}\n", "meta": {"hexsha": "601885298a249442c9554fbd4c8cf2765990adaf", "size": 1400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/gil/example/sobel_scharr.cpp", "max_stars_repo_name": "btzy/boost-1.72.0-mirror", "max_stars_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T03:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T03:04:05.000Z", "max_issues_repo_path": "libs/gil/example/sobel_scharr.cpp", "max_issues_repo_name": "btzy/boost-1.72.0-mirror", "max_issues_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/gil/example/sobel_scharr.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": 30.4347826087, "max_line_length": 108, "alphanum_fraction": 0.6307142857, "num_tokens": 428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6040508430076807}}
{"text": "#include <state_estimation/filters/kalman_filter_vs.h>\n#include <state_estimation/utilities/data_subset_utilities.h>\n#include <state_estimation/utilities/logging.h>\n#include <Eigen/Dense>\n\nnamespace state_estimation {\n\nvoid KalmanFilterVS::myPredict(const Eigen::VectorXd& u, double dt) {\n    system_model_->update(filter_state_.x, u, dt);\n\n    // Get our sub matrices and vectors\n    const Eigen::VectorXd x_subset = getSubset(filter_state_.x, system_model_->activeStates());\n    const Eigen::VectorXd u_subset = getSubset(u, system_model_->activeControls());\n    const Eigen::MatrixXd cov_subset =\n        getSubset(filter_state_.covariance, system_model_->activeStates());\n    const Eigen::MatrixXd A_subset = getSubset(system_model_->A(), system_model_->activeStates());\n    const Eigen::MatrixXd B_subset = getSubset(system_model_->B(), system_model_->activeStates(),\n                                               system_model_->activeControls());\n    const Eigen::MatrixXd Rc_subset =\n        getSubset(system_model_->Rc(), system_model_->activeControls());\n    const Eigen::MatrixXd P_subset =\n        getSubset(system_model_->P(), system_model_->activeStates(), {});\n    const Eigen::MatrixXd V_subset = getSubset(system_model_->V(), system_model_->activeStates(),\n                                               system_model_->activeControls());\n\n    // Update the state\n    const Eigen::VectorXd Ax_subset = A_subset * x_subset;\n    const Eigen::VectorXd Bu_subset = B_subset * u_subset;\n    const Eigen::VectorXd Ax_full = convertSubsetToFullZeroed(\n        Ax_subset, system_model_->activeStates(), system_model_->stateSize());\n    const Eigen::VectorXd Bu_full = convertSubsetToFullZeroed(\n        Bu_subset, system_model_->activeStates(), system_model_->stateSize());\n\n    filter_state_.x = system_model_->addVectors(Ax_full, Bu_full);\n\n    // Update the covariance\n    const Eigen::MatrixXd cov_prime_subset = A_subset * cov_subset * A_subset.transpose() +\n                                             P_subset * system_model_->Rp() * P_subset.transpose() +\n                                             V_subset * Rc_subset * V_subset.transpose();\n\n    convertSubsetToFull(cov_prime_subset, &filter_state_.covariance, system_model_->activeStates());\n\n#ifdef DEBUG_STATE_ESTIMATION\n    std::cout << \"KF predicition update:\" << std::endl\n              << \"A=\" << std::endl\n              << printMatrix(system_model_->A()) << std::endl\n              << \"B=\" << std::endl\n              << printMatrix(system_model_->B()) << std::endl\n              << \"P=\" << std::endl\n              << printMatrix(system_model_->P()) << std::endl\n              << \"V=\" << std::endl\n              << printMatrix(system_model_->V()) << std::endl\n              << \"x=\" << filter_state_.x.transpose() << std::endl\n              << \"Covariance=\" << std::endl\n              << printMatrix(filter_state_.covariance) << std::endl;\n#endif\n}\n\nvoid KalmanFilterVS::myCorrect(const Eigen::VectorXd& z,\n                               measurement_models::LinearMeasurementModel* model, double dt) {\n    // Update our measurement model\n    model->update(filter_state_.x, dt);\n\n    // Get our sub matrices/vectors\n    const Eigen::VectorXd x_subset = getSubset(filter_state_.x, system_model_->activeStates());\n    const Eigen::MatrixXd cov_subset =\n        getSubset(filter_state_.covariance, system_model_->activeStates());\n    const Eigen::MatrixXd C_subset =\n        getSubset(model->C(), model->activeMeasurements(), system_model_->activeStates());\n    const Eigen::MatrixXd meas_cov_subset =\n        getSubset(model->covariance(), model->activeMeasurements());\n\n    // Compute the Kalman gain\n    const Eigen::MatrixXd cov_C_T = cov_subset * C_subset.transpose();\n    const Eigen::MatrixXd K = cov_C_T * (C_subset * cov_C_T + meas_cov_subset).inverse();\n\n    // Update the state\n    const Eigen::VectorXd z_prime_subset = C_subset * x_subset;\n    const Eigen::VectorXd z_prime_full = convertSubsetToFullZeroed(\n        z_prime_subset, model->activeMeasurements(), model->measurementSize());\n    const Eigen::VectorXd dz_full = model->subtractVectors(z, z_prime_full);\n    const Eigen::VectorXd dz_subset = getSubset(dz_full, model->activeMeasurements());\n    const Eigen::VectorXd dx_subset = K * dz_subset;\n    const Eigen::VectorXd dx_full = convertSubsetToFullZeroed(\n        dx_subset, system_model_->activeStates(), system_model_->stateSize());\n\n    filter_state_.x = system_model_->addVectors(filter_state_.x, dx_full);\n\n    // Update the covariance\n    const Eigen::MatrixXd I = Eigen::MatrixXd::Identity(cov_subset.rows(), cov_subset.rows());\n    const Eigen::MatrixXd cov_prime = (I - K * C_subset) * cov_subset;\n\n    convertSubsetToFull(cov_prime, &filter_state_.covariance, system_model_->activeStates());\n\n#ifdef DEBUG_STATE_ESTIMATION\n    std::cout << \"KF measurement update:\" << std::endl\n              << \"C=\" << std::endl\n              << printMatrix(model->C()) << std::endl\n              << \"z'=\" << printMatrix(z_prime_full) << std::endl\n              << \"Q=\" << std::endl\n              << printMatrix(model->covariance()) << std::endl\n              << \"K=\" << std::endl\n              << printMatrix(K) << std::endl\n              << \"x=\" << printMatrix(filter_state_.x) << std::endl\n              << \"Covariance=\" << std::endl\n              << printMatrix(filter_state_.covariance) << std::endl;\n#endif\n}\n\n}  // namespace state_estimation\n", "meta": {"hexsha": "5a6b51db99b87d5a9254efa1de815b4cf2f69d93", "size": 5442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filters/kalman_filter_vs.cpp", "max_stars_repo_name": "MarbleInc/state_estimation", "max_stars_repo_head_hexsha": "05b3f0bbceda695b4420594ac9ff3cd22001a577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-05T06:19:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T06:19:45.000Z", "max_issues_repo_path": "src/filters/kalman_filter_vs.cpp", "max_issues_repo_name": "stevendaniluk/state_estimation", "max_issues_repo_head_hexsha": "05b3f0bbceda695b4420594ac9ff3cd22001a577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/filters/kalman_filter_vs.cpp", "max_forks_repo_name": "stevendaniluk/state_estimation", "max_forks_repo_head_hexsha": "05b3f0bbceda695b4420594ac9ff3cd22001a577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.027027027, "max_line_length": 100, "alphanum_fraction": 0.6488423374, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527869325345, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.604050816540158}}
{"text": "//----------------------------------*-C++-*-----------------------------------//\n/**\n *  @file  CLP.cc\n *  @brief CLP member definitions\n *  @note  Copyright (C) 2013 Jeremy Roberts\n */\n//----------------------------------------------------------------------------//\n\n#include \"CLP.hh\"\n#include \"utilities/DBC.hh\"\n#ifdef DETRAN_ENABLE_BOOST\n#include <boost/math/special_functions/legendre.hpp>\n#endif\n\nnamespace detran_orthog\n{\n\n//----------------------------------------------------------------------------//\nCLP::CLP(const Parameters &p)\n  : ContinuousOrthogonalBasis(p)\n{\n#ifndef DETRAN_ENABLE_BOOST\n  THROW(\"CLP needs boost to be enabled.\");\n#else\n\n  // Allocate the basis matrix\n  d_basis = new callow::MatrixDense(d_size, d_order + 1, 0.0);\n\n  // Allocate the normalization array\n  d_a = Vector::Create(d_order + 1, 0.0);\n\n  // The weights are just the qw's.\n  double L = d_upper_bound - d_lower_bound;\n  for (size_t i = 0; i < d_w->size(); ++i)\n  {\n    d_x[i] =  2.0*(d_x[i] - d_lower_bound)/L - 1.0;\n    (*d_w)[i] = d_qw[i];\n  }\n\n  // Build the basis\n  for (size_t l = 0; l <= d_order; ++l)\n  {\n    for (size_t i = 0; i < d_size; ++i)\n    {\n      (*d_basis)(i, l) = boost::math::legendre_p(l, d_x[i]);\n    }\n    // Inverse of normalization coefficient.\n    (*d_a)[l] = (2.0 * l + 1.0) / 2.0;\n  }\n  //d_orthonormal = true;\n  //compute_a();\n#endif\n\n}\n\n} // end namespace detran_orthog\n\n//----------------------------------------------------------------------------//\n//              end of file CLP.cc\n//----------------------------------------------------------------------------//\n", "meta": {"hexsha": "a2d2627dae9849dea59e2d46467e2478af70ee31", "size": 1589, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/orthog/CLP.cc", "max_stars_repo_name": "baklanovp/libdetran", "max_stars_repo_head_hexsha": "820efab9d03ae425ccefb9520bdb6c086fdbf939", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-03-07T16:20:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-10T13:40:16.000Z", "max_issues_repo_path": "src/orthog/CLP.cc", "max_issues_repo_name": "baklanovp/libdetran", "max_issues_repo_head_hexsha": "820efab9d03ae425ccefb9520bdb6c086fdbf939", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T21:24:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-16T00:56:44.000Z", "max_forks_repo_path": "src/orthog/CLP.cc", "max_forks_repo_name": "baklanovp/libdetran", "max_forks_repo_head_hexsha": "820efab9d03ae425ccefb9520bdb6c086fdbf939", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-03-07T16:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T00:14:23.000Z", "avg_line_length": 26.0491803279, "max_line_length": 80, "alphanum_fraction": 0.4587791064, "num_tokens": 424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851154320682, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.6040469307765607}}
{"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <random>\n#include <Eigen/Dense>\n#include \"../include/GaussianHMM.h\"\nusing namespace Eigen;\n\nint main() {\n  std::cout << \"Start ...\\n\";\n  double var = 1.0;\n  std::random_device seed;\n  std::mt19937 random_number_generator(seed());\n  std::normal_distribution<double> white_noise(0.0, var);\n\n  ArrayXd clusters(2);\n  ArrayXd start(2);\n  ArrayXXd trans(2, 2);\n  clusters << 10, 1;\n  start << 1, 0;\n  trans << 0.88, 0.12, 0.4, 0.6;\n\n  GaussianHMM hmm(2, var, 47, 1000);\n  std::cout << \"Max epoch - \" << hmm.max_epoch << \"\\n\";\n  hmm.pi = start;\n  hmm.means_ = clusters;\n  hmm.A = trans;\n  hmm.covars_ = ArrayXd::Ones(2) * var;\n\n  int n_sample = 1000;\n  ArrayXi state_seqence(n_sample);\n  std::vector<double> X;\n  hmm.sample(n_sample, 100, X, state_seqence);\n\n  std::ofstream signal_writer(\"signal.dat\", std::ios_base::out | std::ios_base::trunc);\n  signal_writer << \"state\\tobservation\\n\";\n  for (size_t i = 0; i < X.size(); i++) {\n    signal_writer << state_seqence(i) << '\\t' << X[i] << '\\n';\n  }\n  signal_writer.close();\n\n  std::cout << \"******************* Fitting test *******************\\n\";\n  GaussianHMM fit_hmm(2, 1e-2, -1, 100);\n  std::vector<size_t> lengths;\n  std::cout << \"Start to fit X ...\\n\";\n  fit_hmm.fit(X, lengths);\n  std::cout << \"Fitted result:\\n\"\n            << \"Mean:\\n\" << fit_hmm.means_ << \"\\n\"\n            << \"Var: \\n\" << fit_hmm.covars_ << \"\\n\"\n            << \"A: \\n\" << fit_hmm.A << \"\\n\";\n\n  return 0;\n}", "meta": {"hexsha": "61e47e600a681cfe661a1643ec58484af0e5d8b7", "size": 1492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_test/hmm_test.cpp", "max_stars_repo_name": "zixuanweeei/FAT", "max_stars_repo_head_hexsha": "a4100dc152fba2e2d1dbb46cfdd3ab0ee4264830", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_test/hmm_test.cpp", "max_issues_repo_name": "zixuanweeei/FAT", "max_issues_repo_head_hexsha": "a4100dc152fba2e2d1dbb46cfdd3ab0ee4264830", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_test/hmm_test.cpp", "max_forks_repo_name": "zixuanweeei/FAT", "max_forks_repo_head_hexsha": "a4100dc152fba2e2d1dbb46cfdd3ab0ee4264830", "max_forks_repo_licenses": ["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.1509433962, "max_line_length": 87, "alphanum_fraction": 0.5851206434, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6040469254801023}}
{"text": "/*\n * Main File For testing\n * Added by Mohamed TarekIbnZiad\n */\n\n#include <assert.h>\n#include <vector>\n#include <crypto/paillier.hh>\n#include <Img.hh>\n#include <crypto/gm.hh>\n#include <NTL/ZZ.h>\n#include <gmpxx.h>\n#include <math/util_gmp_rand.h>\n\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n\n#include <ctime>\n\n#include<iostream>\n\nusing namespace cv;\nusing namespace std;\nusing namespace NTL;\n\n/*\n * Apply average filter in Plain domain using open cv ready made function (blur)\n */\nMat\nAverageFilterOpenCV(Mat src)\n{\n    //enter the kernel size\n    int kerSize;\n    cout << \"Please enter the kernel size: \\n\";\n    cin >> kerSize;\n\n    Mat dst;\n    //smooth the image in the \"src\" and save it to \"dst\"\n    blur( src, dst, Size( kerSize, kerSize ) );\n\n    return dst;\n}\n\n/*\n * Apply average filter in Plain domain\n */\nMat\nAverageFilter(Mat src, vector < vector<mpz_class> > &filter)\n{\n    Mat dst = src.clone(); //Copy of src as initial value\n    Scalar s;\n    //Filter size\n    int ro = filter.size();\n    int co = filter.data()->size();\n\n    //get summation of the filter elements to divide by\n    mpz_class nFilter = 0;\n    for (int i=0; i < ro; i++){\n\t     for (int j=0; j < co; j++){\n            nFilter += filter[i][j];\n       }\n    }\n\n    for (int i=1; i < src.rows - 2; i++){\n\t     for (int j=1; j < src.cols - 2; j++){\n            mpz_class sum=0;\n            for(int m=-1; m<=1; m++){\n\t\t            for(int n=-1; n<=1; n++){\n                    s = src.at<uchar>(i+m,j+n);\n                    sum += s.val[0] * filter[m+1][n+1];\n                }\n            }\n            s.val[0] = sum.get_d()/nFilter.get_d();\n            dst.at<uchar>(i,j) = s.val[0];\n        }\n    }\n    return dst;\n}\n\n/*\n * Apply Sobel operator in Plain domain using open cv ready made function (Sobel)\n */\nMat\nSobelFilterOpenCV(Mat src)\n{\n    int scale = 1;\n    int delta = 0;\n    int ddepth = CV_16S;\n\n    Mat dst;\n\n    // Generate grad_x and grad_y\n    Mat grad_x, grad_y;\n    Mat abs_grad_x, abs_grad_y;\n\n    // Gradient X\n    Sobel( src, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT );\n    convertScaleAbs( grad_x, abs_grad_x );\n\n    // Gradient Y\n    Sobel( src, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT );\n    convertScaleAbs( grad_y, abs_grad_y );\n\n    // Total Gradient (approximate)\n    addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, dst );\n\n    return dst;\n}\n\n/*\n * Apply Sobel operator in Plain domain using indirect access\n */\nMat\nSobelFilter(Mat src)\n{\n    int dx[3][3] = {{1,0,-1},{2,0,-2},{1,0,-1}};\n    int dy[3][3] = {{1,2,1},{0,0,0},{-1,-2,-1}};\n\n    Mat dst = src.clone(); //Copy of src as initial value\n    //Vec3b s; // for colored images\n    Scalar s;\n\n    for (int i=1; i < src.rows - 2; i++){\n\t     for (int j=1; j < src.cols - 2; j++){\n            // apply kernel in X and Y directions\n            int sum_x=0;\n            int sum_y=0;\n            for(int m=-1; m<=1; m++){\n\t\t            for(int n=-1; n<=1; n++){\n                    //s=cvGet2D(img,i+m,j+n); // get the (i,j) pixel value\n                    s = src.at<uchar>(i+m,j+n);\n                    sum_x += s.val[0] * dx[m+1][n+1];\n                    sum_y += s.val[0] * dy[m+1][n+1];\n                }\n            }\n\n            int sum=abs(sum_x)+abs(sum_y);\n            s.val[0] = (sum>255)? 255:sum;\n            dst.at<uchar>(i,j) = s.val[0];\n            //dst.at<Vec2d>(i,j)[0] = s;\n            //cvSet2D(dst,i,j,s); // set the (i,j) pixel value\n        }\n    }\n    return dst;\n}\n\n/*\n * Apply convolution in Plain domain\n */\nMat\nconvolution(Mat src, vector < vector<mpz_class> > &filter)\n{\n    Mat dst = src.clone(); //Copy of src as initial value\n    Scalar s;\n\n    for (int i=1; i < src.rows - 1; i++){\n\t     for (int j=1; j < src.cols - 1; j++){\n            mpz_class sum=0;\n            for(int m=-1; m<=1; m++){\n\t\t            for(int n=-1; n<=1; n++){\n                    if (filter[m+1][n+1] == 0) { //Not encrypted value\n                        continue;\n                    }\n                    s = src.at<uchar>(i+m,j+n);\n                    sum += s.val[0] * filter[m+1][n+1];\n                }\n            }\n            s.val[0] = abs(sum.get_d());\n            dst.at<uchar>(i,j) = s.val[0];\n        }\n    }\n    return dst;\n}\n\n/*\n * used to Add/Sub constant value to the image brightness in plain domain\n */\nMat\nAdjustBrightness(Mat src, int value)\n{\n    Mat dst = src.clone(); //Copy of src as initial value\n    Scalar s;\n    int newValue;\n    for (int i=0; i < src.rows; i++){\n\t     for (int j=0; j < src.cols; j++){\n            s = src.at<uchar>(i,j);\n            newValue = s.val[0] + value;\n            newValue = (newValue>255)? 255:\n                       (newValue<0)?     0:newValue;\n            dst.at<uchar>(i,j) = newValue;\n        }\n    }\n    return dst;\n}\n\n/*\n * used to fix the image colors range after return from the homo domain\n */\nvector < vector<mpz_class> >\nFixRange(vector < vector<mpz_class> > &in)\n{\n\n    int rows = in.size();\n    int cols = in.data()->size();\n    int newValue;\n\n    vector < vector<mpz_class> > out(rows, vector<mpz_class>(cols));\n    for (int i=0; i < rows; i++){\n\t     for (int j=0; j < cols; j++){\n            newValue = (int)in[i][j].get_d();\n            newValue = (newValue>255)? 255:\n                       (newValue<0)?     0:newValue;\n            out[i][j] = (int)newValue;\n        }\n    }\n    return out;\n}\n\n/*\n * used to get the negative image in plain domain\n */\nMat\nNegativeImage(Mat src)\n{\n    Mat dst = src.clone(); //Copy of src as initial value\n    Scalar s;\n    int newValue;\n    for (int i=0; i < src.rows; i++){\n\t     for (int j=0; j < src.cols; j++){\n            s = src.at<uchar>(i,j);\n            newValue = 255 - s.val[0];\n            dst.at<uchar>(i,j) = newValue;\n        }\n    }\n    return dst;\n}\n\n/*\n * used to add salt and pepper noise to the image\n */\nMat\nAddSaltPepperNoise(Mat src)\n{\n    Mat saltpepper_noise = Mat::zeros(src.rows, src.cols,CV_8U);\n    randu(saltpepper_noise,0,255);\n\n    Mat black = saltpepper_noise < 10;\n    Mat white = saltpepper_noise > 245;\n\n    Mat saltpepper_img = src.clone();\n    saltpepper_img.setTo(255,white);\n    saltpepper_img.setTo(0,black);\n\n    return saltpepper_img;\n}\n\n/*\n * convert an image from Mat type to mpz_class type used in encryption\n */\nvector < vector<mpz_class> >\nMat2mpz(Mat src)\n{\n    vector < vector<mpz_class> > A(src.rows, vector<mpz_class>(src.cols));\n    Scalar s;\n    for (int i = 0; i < src.rows; i++) {\n        for (int j = 0; j < src.cols; j++){\n            s = src.at<uchar>(i,j);\n            A[i][j] = (int)s[0];\n        }\n    }\n    return A;\n}\n\n/*\n * convert an image from mpz_class type used in encryption to Mat type (opencv)\n */\nMat\nmpz2Mat(vector < vector<mpz_class> > &A)\n{\n    int rows = A.size();\n    int cols = A.data()->size();\n    Mat dst(rows,cols,CV_8UC1);\n    for (int i = 0; i < rows; i++) {\n        for (int j = 0; j < cols; j++){\n            dst.at<uchar>(i,j) = (int)A[i][j].get_d(); //double to int\n        }\n    }\n    return dst;\n}\n\n/*\n * used to divide by n in the average filter in time domain\n * would be removed later after implementing paillier encoding\n */\nvector < vector<mpz_class> >\ndivideP (const vector < vector<mpz_class> > &src, const vector < vector<mpz_class> > &filter)\n{\n    //Src image size\n    int rows = src.size();\n    int cols = src.data()->size();\n    //Filter size\n    int ro = filter.size();\n    int co = filter.data()->size();\n\n    vector < vector<mpz_class> > dst (rows, vector<mpz_class>(cols));\n\n    //get summation of the filter elements to divide by\n    mpz_class sum = 0;\n    for (int i=0; i < ro; i++){\n\t     for (int j=0; j < co; j++){\n            sum += filter[i][j];\n        }\n    }\n\n    for (int i=0; i < rows; i++){\n\t     for (int j=0; j < cols; j++){\n            dst[i][j] = src[i][j]/sum;\n        }\n    }\n    return dst;\n}\n\nstatic void\ntest_image()\n{\n    //create 2 empty windows\n    //namedWindow( \"Original Image\" , CV_WINDOW_AUTOSIZE );\n    //namedWindow( \"Smoothed Image\" , CV_WINDOW_AUTOSIZE );\n\n    // Load an image from file\n    Mat src = imread( \"cameraman.JPG\", 1 ); //0 --> gray, 1 --> RGB image\n\n    //show the loaded image\n    imshow( \"Original Image\", src );\n\n    Mat dst;\n\n    // Test Average filter by Opencv\n    dst = AverageFilterOpenCV(src);\n    imshow( \"Opencv Smoothed Image\", dst );\n\n    //Add Salt and pepper noise:\n    Mat saltpepper_img = AddSaltPepperNoise(src);\n    imshow( \"Noisy Image\", saltpepper_img );\n\n    dst = AverageFilterOpenCV(saltpepper_img);\n    imshow( \"Opencv Smoothed Image\", dst );\n\n    // Test Sobel filter by Me\n    Mat src_gray;\n    cvtColor(src, src_gray, CV_BGR2GRAY); //change the color image to grayscale image\n    imshow( \"Gray Image\", src_gray );\n\n    dst = SobelFilter(src_gray);\n    imshow( \"My Sobel Image\", dst );\n\n    // Test Sobel filter by Opencv\n    dst = SobelFilterOpenCV(src_gray);\n    imshow( \"Opencv Sobel Image\", dst );\n}\n\nstatic void\ntest_paillier()\n{\n    cout << \"Test Paillier ...\\n\" << flush;\n\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n\n    auto sk = Paillier_priv::keygen(randstate,16,2); //600 ,256\n    Paillier_priv pp(sk,randstate);\n\n    auto pk = pp.pubkey();\n    mpz_class n = pk[0];\n    Paillier p(pk,randstate);\n\n    //mpz_class pt0, pt1,m;\n    //mpz_urandomm(pt0.get_mpz_t(),randstate,n.get_mpz_t());\n    //mpz_urandomm(pt1.get_mpz_t(),randstate,n.get_mpz_t());\n    //mpz_urandomm(m.get_mpz_t(),randstate,n.get_mpz_t());\n    mpz_class pt0 = 2, pt1 = 3, m = 5; //instead of the random values\n    cout << \"pt0: \"<< pt0 << endl;\n    cout << \"pt1: \"<< pt1 << endl;\n\n    mpz_class ct0 = p.encrypt(pt0);         cout << \"ct0: \"<< ct0 << endl;\n    mpz_class ct1 = p.encrypt(pt1);         cout << \"ct1: \"<< ct1 << endl;\n    mpz_class sum = p.add(ct0, ct1);        cout << \"sum_enc: \"<< sum << endl;\n    mpz_class prod = p.constMult(m,ct0);    cout << \"prod_enc: \"<< prod << endl;\n    mpz_class diff = p.sub(ct0, ct1);       cout << \"diff_enc: \"<< diff << endl;\n\n    mpz_class ct0_dec = pp.decrypt(ct0);\n    cout << \"ct0_dec \"<< ct0_dec.get_d() << endl;\n    cout << \"n \" <<  n.get_d() <<endl;\n    assert(pp.decrypt(ct0) == pt0);\n    assert(pp.decrypt(ct1) == pt1);\n    assert(pp.decrypt(sum) == (pt0+pt1)%n);\n    mpz_class d = pt0 - pt1;\n    if (d < 0) {\n        d += n;\n    }\n    assert(pp.decrypt(diff) == d);\n    assert(pp.decrypt(prod) == (m*pt0)%n);\n\n    cout << \"Test Paillier passed\" << endl;\n\n    cout << \"Test Matrix Paillier ...\\n\" << flush;\n    vector < vector<mpz_class> > A = {{1,2,3},{1,1,1},{4,5,6}};\n    int Arows = A.size();\n    int Acols = A.data()->size();\n    vector < vector<mpz_class> > A_enc(Arows, vector<mpz_class>(Acols));\n    A_enc = p.encryptMatrix(A);\n    vector < vector<mpz_class> > A_dec(Arows, vector<mpz_class>(Acols));\n    A_dec = pp.decryptMatrix(A_enc);\n    cout << \"Test Matrix Paillier passed\" << endl;\n}\n\ndouble\ngetRMSE(const Mat& I1, const Mat& I2)\n{\n    Mat s1;\n    absdiff(I1, I2, s1);       // |I1 - I2|\n    s1.convertTo(s1, CV_32F);  // cannot make a square on 8 bits\n    s1 = s1.mul(s1);           // |I1 - I2|^2\n\n    Scalar s = sum(s1);        // sum elements per channel\n    double sse = s.val[0] + s.val[1] + s.val[2]; // sum channels\n    double mse  = sse / (double)(I1.channels() * I1.total());\n    double rmse = sqrt(mse);\n\n    return rmse;\n }\n\nvoid\ntestImagePaillierTime()\n{\n    struct timespec t0,t1;\n    int n_iteration = 10;\n    uint64_t t;\n\n    //Generate Paillier key\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        auto sk = Paillier_priv::keygen(randstate,32,2); //600 ,256\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Key Generation: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    auto sk = Paillier_priv::keygen(randstate,32,2); //600 ,256\n    Paillier_priv pp(sk,randstate);\n\n    auto pk = pp.pubkey();\n    mpz_class n = pk[0];\n    Paillier p(pk,randstate);\n\n    //read image\n    Mat src = imread( \"cameraman.JPG\", 0);\n    imshow( \"Original Image\", src );\n\n    int rows = src.rows;\n    int cols = src.cols;\n    vector < vector<mpz_class> > A(rows, vector<mpz_class>(cols));\n    A = Mat2mpz(src);\n\n\n    //Encrypt image\n    vector < vector<mpz_class> > A_enc = p.encryptMatrix(A);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        A_enc = p.encryptMatrix(A);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    //imshow( \"Encrypted Image\", mpz2Mat(A_enc) );\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"public encryption: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n\n\n    //Decrypt image\n    vector < vector<mpz_class> > A_dec = pp.decryptMatrix(A_enc);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        A_dec = pp.decryptMatrix(A_enc);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"private decryption: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    Mat dst;\n    dst = mpz2Mat(A_dec);\n    //imshow( \"Decrypted Image\", dst );\n\n\n    //Negate image in plain domain\n    dst = NegativeImage(src);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dst = NegativeImage(src);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Negative Image PD: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    //imshow( \"Negative Image\", dst );\n\n    //Negate image in encrypted domain\n    vector < vector<mpz_class> > Neg_enc = p.NegativeImageH(A_enc);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        vector < vector<mpz_class> > Neg_enc = p.NegativeImageH(A_enc);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Negative Image ED: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    //imshow( \"Encrypted Negative Image\", mpz2Mat(Neg_enc) );\n\n    vector < vector<mpz_class> > Neg_dec = pp.decryptMatrix(Neg_enc);\n    //imshow( \"Decrypted Negative Image\", mpz2Mat(Neg_dec) );\n\n    //Test Brightness\n    int value = 50;\n    //Increase brightness in plain domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dst = AdjustBrightness(src, value);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Adjust Brightness PD: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    dst = AdjustBrightness(src, value);\n    //imshow( \"Brightness Image\", dst );\n\n    //Increase brightness in encrypted domain\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        mpz_class value_enc = p.encrypt(value);\n        vector < vector<mpz_class> > Bright_enc = p.AdjustBrightnessH(A_enc, value_enc);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Adjust Brightness ED: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    mpz_class value_enc = p.encrypt(value);\n    vector < vector<mpz_class> > Bright_enc = p.AdjustBrightnessH(A_enc, value_enc);\n    //imshow( \"Encrypted Brightness Image\", mpz2Mat(Bright_enc) );\n\n    vector < vector<mpz_class> > Bright_dec = pp.decryptMatrix(Bright_enc);\n    //imshow( \"Decrypted Brightness Image\", mpz2Mat(Bright_dec) );\n\n\n    //Test convolution\n    vector < vector<mpz_class> > filter;\n    //filter = {{1,0,-1},{2,0,-2},{1,0,-1}};//Vertical edges\n    filter = {{1,2,1},{0,0,0},{-1,-2,-1}};  //Horizontal edges\n    vector < vector<mpz_class> > conv_enc = p.convolutionH(A_enc, filter);\n    //imshow( \"Encrypted convoluted Image\", mpz2Mat(conv_enc) );\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        vector < vector<mpz_class> > conv_enc = p.convolutionH(A_enc, filter);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Convolution (3x3) Sobel ED: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n\n    vector < vector<mpz_class> > conv_dec = pp.decryptMatrix(conv_enc);\n    //imshow( \"Decrypted convoluted Image\", mpz2Mat(conv_dec) );\n\n    //Test convolution in Plain domain\n    dst = convolution(src, filter);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dst = convolution(src, filter);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Convolution (3x3) Sobel PD: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    //imshow( \"convoluted Image\", dst );\n\n\n    //Test Average filter\n    filter = {{1,1,1},{1,1,1},{1,1,1}};\n    vector < vector<mpz_class> > Avg_enc = p.convolutionH(A_enc, filter);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        Avg_enc = p.convolutionH(A_enc, filter);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Average (3x3) ED: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    //imshow( \"Encrypted averaged Image\", mpz2Mat(Avg_enc) );\n    vector < vector<mpz_class> > Avg_dec = pp.decryptMatrix(Avg_enc);\n    //Divide by filter summation in plain domain\n    vector < vector<mpz_class> > Avg_decP = divideP(Avg_dec, filter);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        Avg_decP = divideP(Avg_dec, filter);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Average (3x3) ED Post Processing: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    //imshow( \"Decrypted averaged Image\", mpz2Mat(Avg_decP) );\n\n\n    //Test average filter in plain domain\n    dst = AverageFilter(src,filter);\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t0);\n    for (size_t i = 0; i < n_iteration; i++) {\n        dst = AverageFilter(src,filter);\n    }\n    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&t1);\n    t = (((uint64_t)t1.tv_sec) - ((uint64_t)t0.tv_sec) )* 1000000000 + (t1.tv_nsec - t0.tv_nsec);\n    cerr << \"Average (3x3) PD: \"<<  ((double)t/1000000)/n_iteration <<\"ms\" << endl;\n    //imshow( \"Averaged Image\", dst );\n\n}\n\nvoid\ntestImagePaillier()\n{\n    //Generate Paillier key\n    gmp_randstate_t randstate;\n    gmp_randinit_default(randstate);\n    gmp_randseed_ui(randstate,time(NULL));\n\n    auto sk = Paillier_priv::keygen(randstate,32,2); //600 ,256\n    Paillier_priv pp(sk,randstate);\n\n    auto pk = pp.pubkey();\n    mpz_class n = pk[0];\n    Paillier p(pk,randstate);\n    cout << \"key  ready ...\\n\" << endl;\n\n    //read image\n    Mat src = imread( \"cameraman.JPG\", 0);\n    imshow( \"Original Image\", src );\n\n    int rows = src.rows;\n    int cols = src.cols;\n    vector < vector<mpz_class> > A(rows, vector<mpz_class>(cols));\n    A = Mat2mpz(src);\n\n    Img img1(A);\n    img1.setPbKey(p);\n\n    //Encrypt image\n    vector < vector<mpz_class> > A_enc = img1.encryptMatrix(A);\n    imshow( \"Encrypted Image\", mpz2Mat(A_enc) );\n\n    //The client only can decrypt a matrix\n    vector < vector<mpz_class> > A_dec = pp.decryptMatrix(A_enc);\n\n    //Decrypt image\n    Mat dst;\n    dst = mpz2Mat(A_dec);\n    imshow( \"Decrypted Image\", dst );\n    //cout << \"Root Mean Square Error in decryption: \"<<getRMSE(src,dst)<<endl;\n\n    //Negate image in plain domain\n    dst = NegativeImage(src);\n    imshow( \"Negative Image\", dst );\n\n    //Negate image in encrypted domain\n    vector < vector<mpz_class> > Neg_enc = img1.NegativeImageH(A_enc);\n    imshow( \"Encrypted Negative Image\", mpz2Mat(Neg_enc) );\n\n    vector < vector<mpz_class> > Neg_dec = pp.decryptMatrix(Neg_enc);\n    imshow( \"Decrypted Negative Image\", mpz2Mat(Neg_dec) );\n    //cout << \"Root Mean Square Error in Negative image: \"<<getRMSE(dst,mpz2Mat(Neg_dec))<<endl;\n\n    //Test Brightness\n    int value = 50;\n    //Increase brightness in plain domain\n    dst = AdjustBrightness(src, value);\n    imshow( \"Brightness Image\", dst );\n\n    //Increase brightness in encrypted domain\n    mpz_class value_enc = p.encrypt(value);\n    vector < vector<mpz_class> > Bright_enc = img1.AdjustBrightnessH(A_enc, value_enc);\n    imshow( \"Encrypted Brightness Image\", mpz2Mat(Bright_enc) );\n\n    vector < vector<mpz_class> > Bright_dec = pp.decryptMatrix(Bright_enc);\n    imshow( \"Decrypted Brightness Image\", mpz2Mat(Bright_dec) );\n    //cout << \"Root Mean Square Error in Brightness image: \"<<getRMSE(dst,mpz2Mat(Bright_dec))<<endl;\n    //post-processing to fix the image\n    //Bright_dec = FixRange(Bright_dec);\n    //imshow( \"Decrypted Brightness Image\", mpz2Mat(Bright_dec) );\n\n    //Test convolution\n    vector < vector<mpz_class> > filter;\n    //filter = {{1,0,-1},{2,0,-2},{1,0,-1}};//Vertical edges\n    filter = {{1,2,1},{0,0,0},{-1,-2,-1}};  //Horizontal edges\n\n    vector < vector<mpz_class> > conv_enc = img1.convolutionH(A_enc, filter);\n    imshow( \"Encrypted convoluted Image\", mpz2Mat(conv_enc) );\n    vector < vector<mpz_class> > conv_dec = pp.decryptMatrix(conv_enc);\n    imshow( \"Decrypted convoluted Image\", mpz2Mat(conv_dec) );\n\n    //Test convolution in Plain domain\n    dst = convolution(src, filter);\n    imshow( \"convoluted Image\", dst );\n    //cout << \"Root Mean Square Error in convoluted image: \"<<getRMSE(dst,mpz2Mat(conv_dec))<<endl;\n\n    //Test Average filter\n    filter = {{1,1,1},{1,1,1},{1,1,1}};\n    vector < vector<mpz_class> > Avg_enc = img1.convolutionH(A_enc, filter);\n    imshow( \"Encrypted averaged Image\", mpz2Mat(Avg_enc) );\n    vector < vector<mpz_class> > Avg_dec = pp.decryptMatrix(Avg_enc);\n    //Divide by filter summation in plain domain\n    vector < vector<mpz_class> > Avg_decP = divideP(Avg_dec, filter);\n    imshow( \"Decrypted averaged Image\", mpz2Mat(Avg_decP) );\n\n    //Test average filter in plain domain\n    dst = AverageFilter(src,filter);\n    imshow( \"Averaged Image\", dst );\n    //cout << \"Root Mean Square Error in Averaged image: \"<<getRMSE(dst,mpz2Mat(Avg_decP))<<endl;\n\n    //wait for a key press infinitely\n    waitKey(0);\n}\n\nint\nmain ( int argc, char **argv )\n{\n    //SetSeed(to_ZZ(time(NULL)));\n    //test_paillier();\n    //test_image();\n\n    testImagePaillier(); /*For generating images*/\n    //testImagePaillierTime(); /*For calculating time*/\n\n    return 0;\n}\n", "meta": {"hexsha": "0e6c92f5bc9d8f227c418d3eee68b7a402759dd4", "size": 23207, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/crypto/source.cc", "max_stars_repo_name": "TarekIbnZiad/CryptoImg", "max_stars_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-11-05T18:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T07:33:10.000Z", "max_issues_repo_path": "Source/crypto/source.cc", "max_issues_repo_name": "TarekIbnZiad/CryptoImg", "max_issues_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/crypto/source.cc", "max_forks_repo_name": "TarekIbnZiad/CryptoImg", "max_forks_repo_head_hexsha": "5ecb2a34c7daa55c428c14c6eb370232b474707f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-10-11T00:32:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-08T23:35:20.000Z", "avg_line_length": 31.6603001364, "max_line_length": 101, "alphanum_fraction": 0.5999482915, "num_tokens": 7036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6039653054063778}}
{"text": "//  rational number example program  ----------------------------------------//\r\n\r\n//  (C) Copyright Paul Moore 1999. Permission to copy, use, modify, sell\r\n//  and distribute this software is granted provided this copyright notice\r\n//  appears in all copies. This software is provided \"as is\" without express or\r\n//  implied warranty, and with no claim as to its suitability for any purpose.\r\n\r\n// boostinspect:nolicense (don't complain about the lack of a Boost license)\r\n// (Paul Moore hasn't been in contact for years, so there's no way to change the\r\n// license.)\r\n\r\n//  Revision History\r\n//  14 Dec 99  Initial version\r\n\r\n#include <iostream>\r\n#include <cassert>\r\n#include <cstdlib>\r\n#include <boost/config.hpp>\r\n#ifndef BOOST_NO_LIMITS\r\n#include <limits>\r\n#else\r\n#include <limits.h>\r\n#endif\r\n#include <exception>\r\n#include <boost/rational.hpp>\r\n\r\nusing std::cout;\r\nusing std::endl;\r\nusing boost::rational;\r\n\r\n#ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP\r\n// This is a nasty hack, required because MSVC does not implement \"Koenig\r\n// Lookup\". Basically, if I call abs(r), the C++ standard says that the\r\n// compiler should look for a definition of abs in the namespace which\r\n// contains r's class (in this case boost) - among other places.\r\n\r\n// Koenig Lookup is a relatively recent feature, and other compilers may not\r\n// implement it yet. If so, try including this line.\r\n\r\nusing boost::abs;\r\n#endif\r\n\r\nint main ()\r\n{\r\n    rational<int> half(1,2);\r\n    rational<int> one(1);\r\n    rational<int> two(2);\r\n\r\n    // Some basic checks\r\n    assert(half.numerator() == 1);\r\n    assert(half.denominator() == 2);\r\n    assert(boost::rational_cast<double>(half) == 0.5);\r\n\r\n    // Arithmetic\r\n    assert(half + half == one);\r\n    assert(one - half == half);\r\n    assert(two * half == one);\r\n    assert(one / half == two);\r\n\r\n    // With conversions to integer\r\n    assert(half+half == 1);\r\n    assert(2 * half == one);\r\n    assert(2 * half == 1);\r\n    assert(one / half == 2);\r\n    assert(1 / half == 2);\r\n\r\n    // Sign handling\r\n    rational<int> minus_half(-1,2);\r\n    assert(-half == minus_half);\r\n    assert(abs(minus_half) == half);\r\n\r\n    // Do we avoid overflow?\r\n#ifndef BOOST_NO_LIMITS\r\n    int maxint = (std::numeric_limits<int>::max)();\r\n#else\r\n    int maxint = INT_MAX;\r\n#endif\r\n    rational<int> big(maxint, 2);\r\n    assert(2 * big == maxint);\r\n\r\n    // Print some of the above results\r\n    cout << half << \"+\" << half << \"=\" << one << endl;\r\n    cout << one << \"-\" << half << \"=\" << half << endl;\r\n    cout << two << \"*\" << half << \"=\" << one << endl;\r\n    cout << one << \"/\" << half << \"=\" << two << endl;\r\n    cout << \"abs(\" << minus_half << \")=\" << half << endl;\r\n    cout << \"2 * \" << big << \"=\" << maxint\r\n         << \" (rational: \" << rational<int>(maxint) << \")\" << endl;\r\n\r\n    // Some extras\r\n    rational<int> pi(22,7);\r\n    cout << \"pi = \" << boost::rational_cast<double>(pi) << \" (nearly)\" << endl;\r\n\r\n    // Exception handling\r\n    try {\r\n        rational<int> r;        // Forgot to initialise - set to 0\r\n        r = 1/r;                // Boom!\r\n    }\r\n    catch (const boost::bad_rational &e) {\r\n        cout << \"Bad rational, as expected: \" << e.what() << endl;\r\n    }\r\n    catch (...) {\r\n        cout << \"Wrong exception raised!\" << endl;\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "e73598a528d1b2b5b3526d90ab724bf4fccbf2cc", "size": 3297, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/rational/test/rational_example.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/rational/test/rational_example.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/rational/test/rational_example.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 30.247706422, "max_line_length": 81, "alphanum_fraction": 0.5805277525, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6039652973855686}}
{"text": "// Algolab BGL Tutorial 2 (Max flow, by taubnert@ethz.ch)\n// Flow example demonstrating how to use push_relabel_max_flow using a custom edge adder\n// to manage the interior graph properties required for flow algorithms\n#include <iostream>\n\n// BGL include\n#include <boost/graph/adjacency_list.hpp>\n\n// BGL flow include *NEW*\n#include <boost/graph/push_relabel_max_flow.hpp>\n\n// Graph Type with nested interior edge properties for flow algorithms\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n    boost::property<boost::edge_capacity_t, long,\n        boost::property<boost::edge_residual_capacity_t, long,\n            boost::property<boost::edge_reverse_t, traits::edge_descriptor>>>> graph;\n\ntypedef traits::vertex_descriptor vertex_desc;\ntypedef traits::edge_descriptor edge_desc;\n\nusing namespace std;\n\n// Custom edge adder class, highly recommended\nclass edge_adder {\n  graph &G;\n\n public:\n  explicit edge_adder(graph &G) : G(G) {}\n\n  void add_edge(int from, int to, long capacity) {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    const auto e = boost::add_edge(from, to, G).first;\n    const auto rev_e = boost::add_edge(to, from, G).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0; // reverse edge has no capacity!\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n  }\n};\n\nvoid make_it_flow() {\n  int n, m, s;\n  cin >> n; cin >> m; cin >> s;\n  graph G(n);\n  edge_adder adder(G);\n  \n  vector<int> stores(s);\n  for(int i = 0; i < s; i++) {\n    cin >> stores[i];\n  }\n  \n  for(int i = 0; i < m; i++) {\n    int u, v; cin >> u; cin >> v;\n  // Add some edges using our custom edge adder\n    adder.add_edge(u, v, 1); // from, to, capacity\n    adder.add_edge(v, u, 1); // from, to, capacity\n  }\n\n  // Add special vertices source and sink\n  const vertex_desc v_source = boost::add_vertex(G);\n  const vertex_desc v_sink = boost::add_vertex(G);\n  adder.add_edge(v_source, 0, INT_MAX);\n  \n  for(int i = 0; i < s; i++) {\n    adder.add_edge(stores[i], v_sink, 1);\n  }\n\n  // Calculate flow from source to sink\n  // The flow algorithm uses the interior properties (managed in the edge adder)\n  // - edge_capacity, edge_reverse (read access),\n  // - edge_residual_capacity (read and write access).\n  long flow = boost::push_relabel_max_flow(G, v_source, v_sink);\n  \n  if(flow == s) {\n    std::cout << \"yes\" << \"\\n\";\n  } else {\n    std::cout << \"no\" << \"\\n\";\n  }\n  \n  // Retrieve the capacity map and reverse capacity map\n  const auto c_map = boost::get(boost::edge_capacity, G);\n  const auto rc_map = boost::get(boost::edge_residual_capacity, G);\n\n  // Iterate over all the edges to print the flow along them\n  auto edge_iters = boost::edges(G);\n  for (auto edge_it = edge_iters.first; edge_it != edge_iters.second; ++edge_it) {\n    const edge_desc edge = *edge_it;\n    const long flow_through_edge = c_map[edge] - rc_map[edge];\n    std::cerr << \"edge from \" << boost::source(edge, G) << \" to \" << boost::target(edge, G)\n              << \" runs \" << flow_through_edge\n              << \" units of flow (negative for reverse direction). \\n\";\n  }\n}\n\nint main() {\n  std::ios_base::sync_with_stdio(false); // Always!\n  int t; cin >> t;\n  while(t--) make_it_flow();\n  return 0;\n}\n", "meta": {"hexsha": "338ba8bf249255ea50612de46180bc8a5880145b", "size": 3359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week07-shopping_trip/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/week07-shopping_trip/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/week07-shopping_trip/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6116504854, "max_line_length": 93, "alphanum_fraction": 0.6635903543, "num_tokens": 939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.712232184238947, "lm_q1q2_score": 0.6039499341865325}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/assert.hpp>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/greater.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/maximum.hpp>\n#include <boost/hana/tuple.hpp>\nnamespace hana = boost::hana;\n\n\nint main() {\n    // without a predicate\n    BOOST_HANA_CONSTANT_CHECK(\n        hana::maximum(hana::tuple_c<int, -1, 0, 2, -4, 6, 9>) == hana::int_c<9>\n    );\n\n    // with a predicate\n    auto smallest = hana::maximum(hana::tuple_c<int, -1, 0, 2, -4, 6, 9>, [](auto x, auto y) {\n        return x > y; // order is reversed!\n    });\n    BOOST_HANA_CONSTANT_CHECK(smallest == hana::int_c<-4>);\n}\n", "meta": {"hexsha": "882a63ad3f39d94e5966e58f14d48f2701077e98", "size": 808, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/maximum.cpp", "max_stars_repo_name": "qicosmos/hana", "max_stars_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T05:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-05T21:48:27.000Z", "max_issues_repo_path": "example/maximum.cpp", "max_issues_repo_name": "qicosmos/hana", "max_issues_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/maximum.cpp", "max_forks_repo_name": "qicosmos/hana", "max_forks_repo_head_hexsha": "b0f8cf2bf19d491b7b739dcb7b8d7497b0e5829f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-06T10:50:17.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-06T10:50:17.000Z", "avg_line_length": 28.8571428571, "max_line_length": 94, "alphanum_fraction": 0.6683168317, "num_tokens": 243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.603949930863436}}
{"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_NTHROOT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_NTHROOT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-exponential\n    This function object returns the nth root of its first argument: \\f$\\sqrt[n]{x}\\f$\n    \\arg n must be of integer type\n    \\arg if n is even and x negative the result is @ref Nan\n    \\arg if x is null the result is @ref Zero\n    \\arg if x is one  the result is @ref One\n\n\n\n    @par Header <boost/simd/function/nthroot.hpp>\n\n    @par Note:\n    nthroot is slower than `pow(x, rec(tofloat(n))`) because\n    it takes care of some limits issues that @ref pow ignores.\n\n    See if it suits you better or use raw_ decorator for intermediate solution.\n\n    @par Decorators\n\n      - raw_ provides increased speed but is undefined for limitings values\n\n    @see pow, rec, sqrt, cbrt\n\n\n    @par Example:\n\n      @snippet nthroot.cpp nthroot\n\n    @par Possible output:\n\n      @snippet nthroot.txt nthroot\n\n  **/\n  Value nthroot(Value const& x, IntegerValue const& n);\n} }\n#endif\n\n#include <boost/simd/function/scalar/nthroot.hpp>\n#include <boost/simd/function/simd/nthroot.hpp>\n\n#endif\n", "meta": {"hexsha": "438f1993d928f2e2c3b22e70fb069102ea4ac10e", "size": 1568, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/nthroot.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/nthroot.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/nthroot.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 26.1333333333, "max_line_length": 100, "alphanum_fraction": 0.6173469388, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6039499256838714}}
{"text": "/*=========================================================================\n\nLibrary:   TubeTK\n\nCopyright 2010 Kitware Inc. 28 Corporate Drive,\nClifton Park, NY, 12065, USA.\n\nAll rights reserved.\n\nLicensed under the Apache License, Version 2.0 ( the \"License\" );\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n=========================================================================*/\n\n#include \"../CLI/tubeCLIProgressReporter.h\"\n#include \"tubeMessage.h\"\n\n#include <itkImageFileReader.h>\n#include <itkImageFileWriter.h>\n#include <itkTimeProbesCollectorBase.h>\n#include <itkBinaryThresholdImageFilter.h>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/p_square_quantile.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\n#include \"SegmentUsingQuantileThresholdCLP.h\"\n\ntemplate< class TPixel, unsigned int VDimension >\nint DoIt( int argc, char * argv[] );\n\n#include \"../CLI/tubeCLIHelperFunctions.h\"\n\ntemplate< class TPixel, unsigned int VDimension >\nint DoIt( int argc, char * argv[] )\n{\n  PARSE_ARGS;\n\n  itk::TimeProbesCollectorBase timeCollector;\n\n  tube::CLIProgressReporter progressReporter(\n    \"SegmentUsingQuantileThreshold\", CLPProcessInformation );\n  progressReporter.Start();\n\n  typedef TPixel                                PixelType;\n  typedef itk::Image< PixelType, VDimension >   ImageType;\n  typedef itk::ImageFileReader< ImageType >     ReaderType;\n\n  timeCollector.Start( \"Load data\" );\n  typename ReaderType::Pointer reader = ReaderType::New();\n  reader->SetFileName( inputVolume.c_str() );\n  try\n    {\n    reader->Update();\n    }\n  catch( itk::ExceptionObject & err )\n    {\n    tube::ErrorMessage( \"Reading volume: Exception caught: \"\n                        + std::string( err.GetDescription() ) );\n    timeCollector.Report();\n    return EXIT_FAILURE;\n    }\n  timeCollector.Stop( \"Load data\" );\n  double progress = 0.1;\n  progressReporter.Report( progress );\n\n  typename ImageType::Pointer image = reader->GetOutput();\n\n  typename ImageType::Pointer maskImage = NULL;\n  if( !maskVolume.empty() )\n    {\n    timeCollector.Start( \"Load mask\" );\n    typename ReaderType::Pointer maskReader = ReaderType::New();\n    maskReader->SetFileName( maskVolume.c_str() );\n    try\n      {\n      maskReader->Update();\n      }\n    catch( itk::ExceptionObject & err )\n      {\n      tube::ErrorMessage( \"Reading mask: Exception caught: \"\n                          + std::string( err.GetDescription() ) );\n      timeCollector.Report();\n      return EXIT_FAILURE;\n      }\n    timeCollector.Stop( \"Load mask\" );\n    progress = 0.2;\n    progressReporter.Report( progress );\n\n    maskImage = maskReader->GetOutput();\n    }\n\n  if( thresholdQuantile >= 0 && thresholdQuantile <= 1.0 )\n    {\n    timeCollector.Start( \"Boost accumulate\" );\n\n    typedef boost::accumulators::accumulator_set< PixelType,\n      boost::accumulators::stats<\n        boost::accumulators::tag::p_square_quantile > >\n      QuantileAccumulatorType;\n    typedef itk::ImageRegionConstIterator< ImageType >\n      ImageIteratorType;\n\n    /*\n     * Create a and configure a vector of length N of pointers\n     * to BOOST accumulators -- Each of the N accumulators will\n     * estimate exactly one of the given N desired quantile. If\n     * the desired quantile is not within ( 0,1 ), throw an exception.\n     */\n    QuantileAccumulatorType acc( boost::accumulators::quantile_probability\n      = thresholdQuantile );\n\n    /*\n     * Use an image iterator to iterate over all pixel/voxel and\n     * and then add those values to the accumulators. Adding\n     * the values will incrementally compute the quantile estimates.\n     */\n    ImageIteratorType imIt( image, image->GetLargestPossibleRegion() );\n    if( !maskVolume.empty() )\n      {\n      ImageIteratorType maskIt( maskImage,\n        maskImage->GetLargestPossibleRegion() );\n      while( !imIt.IsAtEnd() )\n        {\n        PixelType p = imIt.Get();\n        PixelType m = maskIt.Get();\n        if( m != 0 )\n          {\n          acc( p );\n          }\n        ++imIt;\n        ++maskIt;\n        }\n      }\n    else\n      {\n      while( !imIt.IsAtEnd() )\n        {\n        PixelType p = imIt.Get();\n        acc( p );\n        ++imIt;\n        }\n      }\n\n    PixelType qVal = boost::accumulators::p_square_quantile( acc );\n\n    typedef itk::BinaryThresholdImageFilter< ImageType, ImageType >\n      FilterType;\n    typename FilterType::Pointer filter = FilterType::New();\n\n    filter->SetInput( image );\n    filter->SetLowerThreshold( qVal );\n    filter->SetOutsideValue( 0 );\n    filter->SetInsideValue( 1 );\n\n    filter->Update();\n\n    image = filter->GetOutput();\n\n    timeCollector.Stop( \"Boost accumulate\" );\n    }\n\n  typedef itk::ImageFileWriter< ImageType  >   ImageWriterType;\n\n  timeCollector.Start( \"Save data\" );\n  typename ImageWriterType::Pointer writer = ImageWriterType::New();\n  writer->SetFileName( outputVolume.c_str() );\n  writer->SetInput( image );\n  writer->SetUseCompression( true );\n  try\n    {\n    writer->Update();\n    }\n  catch( itk::ExceptionObject & err )\n    {\n    tube::ErrorMessage( \"Writing volume: Exception caught: \"\n      + std::string( err.GetDescription() ) );\n    timeCollector.Report();\n    return EXIT_FAILURE;\n    }\n  timeCollector.Stop( \"Save data\" );\n  progress = 1.0;\n  progressReporter.Report( progress );\n  progressReporter.End();\n\n  timeCollector.Report();\n  return EXIT_SUCCESS;\n}\n\nint main( int argc, char * argv[] )\n{\n  PARSE_ARGS;\n\n  return tube::ParseArgsAndCallDoIt( inputVolume, argc, argv );\n}\n", "meta": {"hexsha": "2e542ba5e5923048a7377918a95da51689c8a2dd", "size": 5917, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "examples/Applications/SegmentUsingQuantileThreshold/SegmentUsingQuantileThreshold.cxx", "max_stars_repo_name": "thewtex/TubeTK", "max_stars_repo_head_hexsha": "7536c6c112e1785cead4d008e8fae5ca8f527f20", "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/Applications/SegmentUsingQuantileThreshold/SegmentUsingQuantileThreshold.cxx", "max_issues_repo_name": "thewtex/TubeTK", "max_issues_repo_head_hexsha": "7536c6c112e1785cead4d008e8fae5ca8f527f20", "max_issues_repo_licenses": ["Apache-2.0"], "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/Applications/SegmentUsingQuantileThreshold/SegmentUsingQuantileThreshold.cxx", "max_forks_repo_name": "thewtex/TubeTK", "max_forks_repo_head_hexsha": "7536c6c112e1785cead4d008e8fae5ca8f527f20", "max_forks_repo_licenses": ["Apache-2.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.8634146341, "max_line_length": 75, "alphanum_fraction": 0.6501605543, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677622198947, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6039499210909579}}
{"text": "#include \"get_floor_fHf.h\"\n#include \"ransac_floor_fHf.h\"\n#include \"ransac_data.h\"\n#include \"randperm.h\"\n#include <Eigen/Geometry>\n#include <vector>\n\nusing namespace Eigen;\n\nRansacData ransac_floor_fHf(MatrixXd &p1, MatrixXd &p2, Matrix3d &R1, Matrix3d &R2, int nbr_iter, double thresh)\n{\n    // Init RANSAC loop\n    PoseData best_posedata;\n    int best_nbr_inliers = 0;\n    VectorXi best_inliers;\n    best_inliers.setZero();\n    int nbr_pts = p1.cols();\n\n    MatrixXd reproj1(2, nbr_pts);\n    MatrixXd reproj2(2, nbr_pts);\n    MatrixXd reproj(4, nbr_pts);\n    VectorXd reproj_mean(nbr_pts);\n    MatrixXd H(3,3);\n    VectorXi inliers(nbr_pts);\n    int nbr_inliers;\n    VectorXi history(nbr_iter);\n\n    int nbr_pts_minimal = 3;\n\n    for (int i = 0; i < nbr_iter; i++) {\n        std::vector<int> rands = randperm(nbr_pts_minimal, nbr_pts);\n        MatrixXd x1(3, nbr_pts_minimal);\n        MatrixXd x2(3, nbr_pts_minimal);\n        for (int j = 0; j < nbr_pts_minimal; j++) {\n            x1.col(j) << p1.col(rands[j]);\n            x2.col(j) << p2.col(rands[j]);\n        }\n\n        // Get pose\n        MatrixXd x1h(2,3);\n        MatrixXd x2h(2,3);\n        x1h << x1.colwise().hnormalized();\n        x2h << x2.colwise().hnormalized();\n\n        PoseData posedata = get_floor_fHf(x1h, x2h, R1, R2);\n\n        // Compute reprojection error, and compare to other solutions.\n        H = posedata.homography;\n        reproj1 = p2.colwise().hnormalized() - (H * p1).colwise().hnormalized();\n        reproj2 = p1.colwise().hnormalized() - (H.lu().solve(p2)).colwise().hnormalized();\n        reproj << reproj1.cwiseAbs(), reproj2.cwiseAbs();\n        reproj_mean = reproj.colwise().mean().array();\n\n        inliers = (reproj_mean.array() < thresh).cast<int>();\n        nbr_inliers = inliers.sum();\n\n        if (best_nbr_inliers < nbr_inliers) {\n            best_posedata = posedata;\n            best_nbr_inliers = nbr_inliers;\n            best_inliers = inliers;\n        }\n        history(i) = best_nbr_inliers;\n\n    }\n\n    RansacData ransac_data;\n    ransac_data.posedata = best_posedata;\n    ransac_data.inliers = best_inliers;\n    ransac_data.history = history;\n\n    return ransac_data;\n}\n\n// ---------------- //\n// MATLAB interface //\n// ---------------- //\n#ifdef MATLAB_MEX_FILE\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n    if (nrhs != 6) {\n        mexErrMsgIdAndTxt(\"ransac_floor_fHf:nrhs\", \"Six input arguments are required.\");\n    }\n    if (nlhs != 4) {\n        mexErrMsgIdAndTxt(\"ransac_floor_fHf:nlhs\", \"Four output arguments are required.\");\n    }\n    if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) {\n        mexErrMsgIdAndTxt(\"ransac_floor_fHf:notDouble\", \"Input data must be type double.\");\n    }\n    if(mxGetNumberOfElements(prhs[0]) % 3 != 0\n       && mxGetNumberOfElements(prhs[0]) != mxGetNumberOfElements(prhs[1])\n       && mxGetNumberOfElements(prhs[2]) != 9 && mxGetNumberOfElements(prhs[3]) != 9\n       && mxGetNumberOfElements(prhs[4]) != 1 && mxGetNumberOfElements(prhs[5]) != 1)\n    {\n        mexErrMsgIdAndTxt(\"ransac_floor_fHf:incorrectSize\", \"Input dimensions incorrect.\");\n    }\n    // Convert to expected input\n    int nbr_pts = mxGetNumberOfElements(prhs[0]) / 3;\n    VectorXd x1_tmp = Map<VectorXd>(mxGetPr(prhs[0]), mxGetNumberOfElements(prhs[0]));\n    VectorXd x2_tmp = Map<VectorXd>(mxGetPr(prhs[1]), mxGetNumberOfElements(prhs[1]));\n    MatrixXd x1 = Map<MatrixXd>(x1_tmp.data(), 3, nbr_pts);\n    MatrixXd x2 = Map<MatrixXd>(x2_tmp.data(), 3, nbr_pts);\n\n    VectorXd R1_tmp = Map<VectorXd>(mxGetPr(prhs[2]), 9);\n    VectorXd R2_tmp = Map<VectorXd>(mxGetPr(prhs[3]), 9);\n    Matrix3d R1 = Map<Matrix3d>(R1_tmp.data(), 3, 3);\n    Matrix3d R2 = Map<Matrix3d>(R2_tmp.data(), 3, 3);\n\n    double *nbr_iter_p = mxGetPr(prhs[4]);\n    double *thresh = mxGetPr(prhs[5]);\n    int nbr_iter = (int) nbr_iter_p[0];\n\n    // Compute output\n    RansacData ransac_data = ransac_floor_fHf(x1, x2, R1, R2, nbr_iter, thresh[0]);\n    PoseData posedata = ransac_data.posedata;\n\n    // Wrap it up to Matlab compatible output\n    plhs[0] = mxCreateDoubleMatrix(3, 3, mxREAL);\n    double* zr = mxGetPr(plhs[0]);\n    for (Index i = 0; i < posedata.homography.size(); i++) {\n        zr[i] = posedata.homography(i);\n    }\n    plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);\n    zr = mxGetPr(plhs[1]);\n    zr[0] = posedata.focal_length;\n\n    plhs[2] = mxCreateDoubleMatrix(nbr_pts, 1, mxREAL);\n    zr = mxGetPr(plhs[2]);\n    for (Index i = 0; i < nbr_pts; i++) {\n        zr[i] = ransac_data.inliers(i);\n    }\n\n    plhs[3] = mxCreateDoubleMatrix(nbr_iter, 1, mxREAL);\n    zr = mxGetPr(plhs[3]);\n    for (Index i = 0; i < nbr_iter; i++) {\n        zr[i] = ransac_data.history(i);\n    }\n}\n#endif\n", "meta": {"hexsha": "afefd8bbae201e144c55637db28043271a31554e", "size": 4719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/floor_fHf/ransac_floor_fHf.cpp", "max_stars_repo_name": "marcusvaltonen/minimal_indoor_uav", "max_stars_repo_head_hexsha": "79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/floor_fHf/ransac_floor_fHf.cpp", "max_issues_repo_name": "marcusvaltonen/minimal_indoor_uav", "max_issues_repo_head_hexsha": "79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/floor_fHf/ransac_floor_fHf.cpp", "max_forks_repo_name": "marcusvaltonen/minimal_indoor_uav", "max_forks_repo_head_hexsha": "79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-15T17:05:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T17:05:32.000Z", "avg_line_length": 33.9496402878, "max_line_length": 112, "alphanum_fraction": 0.6238609875, "num_tokens": 1498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.6039396447980532}}
{"text": "#include <math.h>\n#include <chrono>\n#include <stdexcept>\n#include <iostream>\n#include <Eigen/Dense>\n#include \"kepler.h\"\n#include \"elements.h\"\n\nusing std::function;\nusing std::runtime_error;\nusing Eigen::Vector3d;\n\nnamespace kepler {\n    double period(double sma, double mu) {\n        return M_PI * 2 * sqrt(pow(sma, 3) / mu);\n    }\n\n    double newton(\n            double p0,\n            function<double(double)> const &func,\n            function<double(double)> const &deriv,\n            int maxiter = 50,\n            double tol = 1e-8\n    ) {\n        for (auto i = 1; i < maxiter; i++) {\n            auto p = p0 - func(p0) / deriv(p0);\n            if (fabs(p - p0) < tol) {\n                return p;\n            }\n            p0 = p;\n        }\n        throw runtime_error(\"Not converged.\");\n    }\n\n    double mean2ecc(double M, double ecc) {\n        auto E = newton(M, [ecc, M](double E) -> double {\n            return E - ecc * sin(E) - M;\n        }, [ecc](double E) -> double {\n            return 1 - ecc * cos(E);\n        });\n        return E;\n    }\n\n    double ecc2true(double E, double ecc) {\n        return 2 * atan2(sqrt(1 + ecc) * sin(E / 2), sqrt(1 - ecc) * cos(E / 2));\n    }\n\n    void benchmark(int times) {\n        auto mu = 3.986004418e5;\n        Vector3d r(8.59072560e+02, -4.13720368e+03, 5.29556871e+03);\n        Vector3d v(7.37289205e+00, 2.08223573e+00, 4.39999794e-01);\n        auto el = elements::elements(r, v, mu);\n\n        auto best = std::numeric_limits<double>::infinity();\n        auto worst = -std::numeric_limits<double>::infinity();\n        double all = 0;\n        for (auto i=0; i < times; i++) {\n            auto begin = std::chrono::high_resolution_clock::now();\n\n            mean2ecc(M_PI, el[1]);\n\n            auto end = std::chrono::high_resolution_clock::now();\n            auto current = std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count()/1e9;\n            all += current;\n            if (current < best) {\n                best = current;\n            }\n            if (current > worst) {\n                worst = current;\n            }\n        }\n        std::cout << \"[\" << all/times << \",\" << best << \",\" << worst << \"]\" << std::endl;\n    }\n}\n\n", "meta": {"hexsha": "91e700326ab426c76456381e2a66b82b999b882f", "size": 2202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/kepler.cpp", "max_stars_repo_name": "helgee/icatt-2016", "max_stars_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-05-07T19:09:15.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-06T14:31:44.000Z", "max_issues_repo_path": "cpp/src/kepler.cpp", "max_issues_repo_name": "OpenAstrodynamics/benchmarks", "max_issues_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-05-05T14:36:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T09:18:55.000Z", "max_forks_repo_path": "cpp/src/kepler.cpp", "max_forks_repo_name": "OpenAstrodynamics/benchmarks", "max_forks_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T12:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T14:19:13.000Z", "avg_line_length": 28.9736842105, "max_line_length": 103, "alphanum_fraction": 0.5063578565, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6039396340898472}}
{"text": "#include \"common.hpp\"\n#include \"PPXTF.hpp\"\n#include <sys/stat.h>\n#include <Eigen/LU>\n\nusing namespace Eigen;\nusing namespace std;\n\n/*\n  #################################### PPMTF ####################################\n  # [input1]: R1_observed ([mode1]{mode2, mode3: value})\n  # [input2]: R2_observed ([mode2]{mode1, mode3: value})\n  # [input3]: R3_observed ([mode3]{mode1, mode2: value})\n  # [input4]: A (L1 x K matrix)\n  # [input5]: B (L2 x K matrix)\n  # [input6]: C (L3 x K matrix)\n  # [input7]: L1 -- Length of mode1\n  # [input8]: L2 -- Length of mode2\n  # [input9]: L3 -- Length of mode3\n  # [input10]: X -- tensor no.\n  # [output]: A, B, C, mu_A, Lam_A, mu_B, Lam_B, mu_C, Lam_C\n */\ntuple<mat_t, mat_t, mat_t, mat_t, mat_t, mat_t>\npptf(const r_t& r1, const r_t& r2, const r_t& r3,\n     vec_mat_t& A, vec_mat_t& B, vec_mat_t& C,\n     int L1, int L2, int L3, int K, int ItrNum, double Alp,\n     const string& outfile_prefix, const string& X){\n  // Hyper-hyper parameters (same as [Salakhutdinov+, ICML08])\n  double alpha = Alp;\n  double beta0 = 2;\n  double mu0 = 0;\n  int nu0 = K;\n  mat_t W0 = mat_t::Identity(K,K);\n  \n  mat_t Lam_A, mu_A, Lam_B, mu_B, Lam_C, mu_C;\n  puts(\"Gibbs Sampling:\");\n  for(int itr = 0; itr < ItrNum; ++itr){\n    if(itr % 10 == 0) printf(\"itr:%d\\n\", itr);\n\n    // Sample Lam_{A,B,C,D} & mu_{A,B,C,D}\n    tie(Lam_A, mu_A) = sample_Lam_X_mu_X(A[itr], L1, nu0, W0, beta0, mu0, K);\n    tie(Lam_B, mu_B) = sample_Lam_X_mu_X(B[itr], L2, nu0, W0, beta0, mu0, K);\n    tie(Lam_C, mu_C) = sample_Lam_X_mu_X(C[itr], L3, nu0, W0, beta0, mu0, K);\n    \n    // Sample A\n    A.push_back(mat_t::Zero(L1, K));\n    for(int n = 0; n < L1; ++n){\n      mat_t BC_BC, BC_R;\n      tie(BC_BC, BC_R) = calc_XYXY_XYR(K, B[itr], C[itr], r1[n]);\n      mat_t lam_ast_inv = (Lam_A + alpha * BC_BC).inverse();\n      mat_t mu_ast = lam_ast_inv * (alpha * BC_R + Lam_A * mu_A);\n      A[itr+1].row(n) = multivariate_normal(mu_ast, lam_ast_inv).transpose();\n    }\n    \n    // Sample B\n    B.push_back(mat_t::Zero(L2, K));\n    for(int i = 0; i < L2; ++i){\n      mat_t AC_AC, AC_R;\n      tie(AC_AC, AC_R) = calc_XYXY_XYR(K, A[itr+1], C[itr], r2[i]);\n      mat_t lam_ast_inv = (Lam_B + alpha * AC_AC).inverse();\n      mat_t mu_ast = lam_ast_inv * (alpha * AC_R + Lam_B * mu_B);\n      B[itr+1].row(i) = multivariate_normal(mu_ast, lam_ast_inv).transpose();\n    }\n\n    // Sample C\n    C.push_back(mat_t::Zero(L3, K));\n    for(int j = 0; j < L3; ++j){\n      mat_t AB_AB, AB_R;\n      tie(AB_AB, AB_R) = calc_XYXY_XYR(K, A[itr+1], B[itr+1], r3[j]);\n      mat_t lam_ast_inv = (Lam_C + alpha * AB_AB).inverse();\n      mat_t mu_ast = lam_ast_inv * (alpha * AB_R + Lam_C * mu_C);\n      C[itr+1].row(j) = multivariate_normal(mu_ast, lam_ast_inv).transpose();\n    }\n\n    // Output model parameters and hyper-parameters\n    if(itr == 0 || itr % 10 == 9){\n      string pre = outfile_prefix;\n      save_parameters(K, itr+1, pre, \"A\", A, mu_A, Lam_A, X);\n      save_parameters(K, itr+1, pre, \"B\", B, mu_B, Lam_B, X);\n      save_parameters(K, itr+1, pre, \"C\", C, mu_C, Lam_C, X);\n    }\n  }\n  return forward_as_tuple(mu_A, Lam_A, mu_B, Lam_B, mu_C, Lam_C);\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nint main(int argc, char *argv[]){\n  if(argc < 3){\n      printf(\"Usage: PPITF [Dataset] [City] ([Alp (default:200)] [MaxNumTrans (default:100)] [MaxNumVisit (default:100)] [ItrNum (default:100)])\\n\");\n      return -1;\n  }\n\n  // Fix a seed\n  seeding();\n\n  // ################################# Parameters ##################################\n  // Dataset\n  const string Dataset = argv[1];\n  // City\n//  const string City = \"TK\";\n  const string City = argv[2];\n  // Hyper-hyper parameter alpha\n  double Alp = 200;\n  string AlpStr = \"200\";\n  if(argc >= 4){\n\t  Alp = atof(argv[3]);\n\t  AlpStr = argv[3];\n  }\n  // Maximum number of transitions per user (-1: infinity)\n  int MaxNumTrans = 100;\n  if(argc >= 5){\n\t  MaxNumTrans = atoi(argv[4]);\n  }\n  // Maximum number of POI visits per user (-1: infinity)\n  int MaxNumVisit = 100;\n  if(argc >= 6){\n\t  MaxNumVisit = atoi(argv[5]);\n  }\n  // Number of iterations in Gibbs sampling\n  int ItrNum = 100;\n  if(argc >= 7){\n\t  ItrNum = atoi(argv[6]);\n  }\n\n  // Training user index file (input)\n  string TUserIndexFile = \"../data/\" + Dataset + \"/tuserindex_%s.csv\";\n  // POI index file (input)\n  string POIIndexFile = \"../data/\" + Dataset + \"/POIindex_%s.csv\";\n  // Training transition tensor file (input)\n  string TrainTransTensorFile = \"../data/\" + Dataset + \"/traintranstensor_%s_mnt\" + std::to_string(MaxNumTrans) + \".csv\";\n  // Training visit tensor file (input)\n  string TrainVisitTensorFile = \"../data/\" + Dataset + \"/trainvisittensor_%s_mnv\" + std::to_string(MaxNumVisit) + \".csv\";\n  // Prefix of the model parameter file (output)\n  const string OutDir = \"../data/\" + Dataset + \"/PPITF_\" + City + \"_alp\" + AlpStr + \"_mnt\" + std::to_string(MaxNumTrans) + \"_mnv\" + std::to_string(MaxNumVisit);\n  mkdir(OutDir.c_str(), 0755);\n  const string ModelParameterFile = OutDir + \"/modelparameter\";\n\n  // Number of time slots\n  int T;\n  if(Dataset.find(\"PF\") == 0){\n\t  T = 30;\n  }else if(Dataset.find(\"FS\") == 0){\n\t  T = 12;\n  }else{\n\t  cout << \"Wrong Dataset\\n\";\n\t  exit(-1);\n  }\n\n  // Number of columns in model parameters (A, B, C)\n//  const int K = 32;\n  const int K = 16;\n  // Number of zero elements for each user in a training tensor (-1: all)\n  const int ZeroNum = 1000;\n  \n  // Replace %s with City\n  TUserIndexFile = string_replace(TUserIndexFile, City);\n  POIIndexFile = string_replace(POIIndexFile, City);\n  TrainTransTensorFile = string_replace(TrainTransTensorFile, City);\n  TrainVisitTensorFile = string_replace(TrainVisitTensorFile, City);\n\n  // Number of training users --> N\n  int N = line_num(TUserIndexFile) - 1;\n  // Number of POIs --> M\n  int M = line_num(POIIndexFile) - 1;\n  \n  // Read a training transition tensor\n  puts(\"Reading a training transition tensor.\");\n  r_t RT1_observed, RT2_observed, RT3_observed;\n  tie(RT1_observed, RT2_observed, RT3_observed) = ReadTrainTransTensor(N, M, ZeroNum, TrainTransTensorFile);\n  // Read a training visit tensor\n  puts(\"Reading a training visit tensor.\");\n  r_t RV1_observed, RV2_observed, RV3_observed;\n  tie(RV1_observed, RV2_observed, RV3_observed) = ReadTrainVisitTensor(N, M, T, ZeroNum, TrainVisitTensorFile);\n  \n  {\n    // Initialize model parameters (AT, BT, CT) of the training transition tensor by random values in [0,1)\n    vec_mat_t A, B, C;\n    A.push_back(random_mat(N, K));\n    B.push_back(random_mat(M, K));\n    C.push_back(random_mat(M, K));\n    // PPTF for the training transition tensor --> AT, BT, CT, mu_AT, Lam_AT, mu_BT, Lam_BT, mu_CT, Lam_CT\n    mat_t mu_A, Lam_A, mu_B, Lam_B, mu_C, Lam_C;\n    tie(mu_A, Lam_A, mu_B, Lam_B, mu_C, Lam_C) = pptf(RT1_observed, RT2_observed, RT3_observed,\n\t\t\t\t\t\t      A, B, C, N, M, M, K, ItrNum, Alp, ModelParameterFile, \"T\");\n  }\n  {\n    // Initialize model parameters (AV, BV, CV) of the training visit tensor by random values in [0,1)\n    vec_mat_t A, B, C;\n    A.push_back(random_mat(N, K));\n    B.push_back(random_mat(M, K));\n    C.push_back(random_mat(T, K));\n    // PPTF for the training visit tensor --> AV, BV, CV, mu_AV, Lam_AV, mu_BV, Lam_BV, mu_CV, Lam_CV\n    mat_t mu_A, Lam_A, mu_B, Lam_B, mu_C, Lam_C;\n    tie(mu_A, Lam_A, mu_B, Lam_B, mu_C, Lam_C) = pptf(RV1_observed, RV2_observed, RV3_observed,\n\t\t\t\t\t\t      A, B, C, N, M, T, K, ItrNum, Alp, ModelParameterFile, \"V\");\n  }\n  return 0;\n}\n", "meta": {"hexsha": "ebafc142c6547ab473be5c256dc709abb699cf00", "size": 7510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/PPITF.cpp", "max_stars_repo_name": "gghatano/PPMTF-1", "max_stars_repo_head_hexsha": "670bff7e58150418f9e7b75e6367f0f069c454b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-11-11T04:28:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T16:26:32.000Z", "max_issues_repo_path": "cpp/PPITF.cpp", "max_issues_repo_name": "gghatano/PPMTF-1", "max_issues_repo_head_hexsha": "670bff7e58150418f9e7b75e6367f0f069c454b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-14T10:58:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-14T10:58:25.000Z", "max_forks_repo_path": "cpp/PPITF.cpp", "max_forks_repo_name": "gghatano/PPMTF-1", "max_forks_repo_head_hexsha": "670bff7e58150418f9e7b75e6367f0f069c454b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-05T22:46:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T08:02:57.000Z", "avg_line_length": 37.55, "max_line_length": 160, "alphanum_fraction": 0.6085219707, "num_tokens": 2486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637397236824, "lm_q2_score": 0.7025300449389325, "lm_q1q2_score": 0.6039396057004494}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\n\nusing namespace std;\n\n\ndouble f(double) { cout << \"double\\n\"; return 1.0; } \ncomplex<double> f(complex<double>) { cout << \"complex\\n\"; return complex<double>(1.0, -1.0); }\n\n\ntemplate <typename Matrix>\nvoid singularity_test1(const Matrix& A)\n{\n    typedef typename mtl::Collection<Matrix>::value_type  Scalar;\n    try {\n\tMatrix B(A);\n\tB[mtl::iall][0]= Scalar(0);\n\t// cout << \"B is:\\n\" << B;\n\tlu(B);\n    } catch (mtl::matrix_singular excp) {\n\tcout << \"Exception 1 for singularity successfully caught\\n\"; return;\n    }\n    throw \"Singularity (test1) not detected\";\n}\n\ntemplate <typename Matrix>\nvoid singularity_test2(const Matrix& A)\n{\n    typedef typename mtl::Collection<Matrix>::value_type  Scalar;\n    try {\n\tMatrix B(A);\n\tB[mtl::iall][0]= Scalar(0);\n\tmtl::dense_vector<int> p;\n\tlu(B, p);\n\tcout << \"B is:\\n\" << B << endl;\n    } catch (mtl::matrix_singular excp) {\n\tcout << \"Exception 2 for singularity successfully caught\\n\"; return;\n    }\n    throw \"Singularity (test2) not detected\";\n}\n\ntemplate <typename Matrix>\nvoid singularity_test3(const Matrix& A)\n{\n    typedef typename mtl::Collection<Matrix>::value_type  Scalar;\n    try {\n\tMatrix B(A);\n\tB[mtl::iall][0]= Scalar(0);\n\tB[0][0]= Scalar(1e-15);\n\tlu(B, 2e-15);\n    } catch (mtl::matrix_singular excp) {\n\tcout << \"Exception 3 for singularity successfully caught\\n\"; return;\n    }\n    throw \"Singularity (test3) not detected\";\n}\n\ntemplate <typename Matrix>\nvoid singularity_test4(const Matrix& A)\n{\n    typedef typename mtl::Collection<Matrix>::value_type  Scalar;\n    try {\n\tMatrix B(A);\n\tB[mtl::iall][0]= Scalar(0);\n\tB[3][0]= Scalar(1e-15);\n\tmtl::dense_vector<int> p;\n\tlu(B, p, 2e-15);\n    } catch (mtl::matrix_singular excp) {\n\tcout << \"Exception 4 for singularity successfully caught\\n\"; return;\n    }\n    throw \"Singularity (test4) not detected\";\n}\n\n\n\n\ntemplate <typename Matrix>\nvoid test(Matrix& A, const char* name)\n{\n    cout << \"\\n\" << name << \"\\n\";\n\n    typedef typename mtl::Collection<Matrix>::value_type  Scalar;\n    typedef typename mtl::dense_vector<Scalar>            Vector;\n\n    unsigned size= unsigned(num_cols(A));\n    Matrix L(size, size), U(size, size);\n\n    Scalar c= f(Scalar(1));   \n    cout << \"c is: \" << c << \"\\n\";\n\n    for (unsigned i= 0; i < size; i++)\n\tfor(unsigned j= 0; j < size; j++) {\n\t    U[i][j]= i <= j ? c * Scalar(i+j+2) : Scalar(0);\n\t    L[i][j]= i > j ? c * Scalar(i+j+1) : (i == j ? Scalar(1) : Scalar(0));\n\t}\n    \n    cout << \"L is:\\n\" << L << \"U is:\\n\" << U;\n    A= L * U;\n\n    Vector v(size);\n    for (unsigned i= 0; i < size; i++)\n\tv[i]= Scalar(i);\n\n    Vector w( A*v );\n\n    cout << \"A is:\\n\" << A;\n\n    Matrix LU(A);\n    lu(LU);\n    cout << \"LU decomposition of A is:\\n\" << LU;\n\n    Matrix I(size, size);\n    I= Scalar(1);\n    Matrix tmp(I + strict_lower(LU)), A2(tmp * upper(LU));\n    cout << \"L * U is:\\n\" << A2;\n\n    Matrix B( lu_f(A) );\n\n    Vector v2( upper_trisolve(upper(LU), unit_lower_trisolve(strict_lower(LU), w)) );\n\n    cout << \"LU decomposition of A (as function result) is:\\n\" << B;\n    cout << \"upper(LU) is:\\n\" << upper(LU) << \"strict_lower(LU) is:\\n\" << strict_lower(LU);\n    cout << \"v2 is \" << v2 << \"\\n\";\n\n    MTL_THROW_IF(abs(v[1] - v2[1]) > 0.1, mtl::runtime_error(\"Error using tri_solve\"));\n\n    Vector v3( lu_solve_straight(A, w) );\n    MTL_THROW_IF(abs(v[1] - v3[1]) > 0.1, mtl::runtime_error(\"Error in solve\"));\n\n    Vector v4( lu_solve(A, w) );\n    cout << \"v4 is \" << v4 << \"\\n\";\n    MTL_THROW_IF(abs(v[1] - v4[1]) > 0.1, mtl::runtime_error(\"Error in solve\"));\n\n    singularity_test1(A);\n    singularity_test2(A);\n    singularity_test3(A);\n    singularity_test4(A);\n\n    mtl::mat::lu_solver<Matrix> lus(A);\n    Vector v5(size);\n     \n    lus.solve(w, v5);\n    cout << \"v5 is \" << v5 << \"\\n\";\n    MTL_THROW_IF(abs(v[1] - v5[1]) > 0.1, mtl::runtime_error(\"Error in solve\"));\n}\n\n\n\nint main(int, char**)\n{\n    using namespace mtl;\n    unsigned size= 4;\n    \n    dense2D<double>                                      dr(size, size);\n    dense2D<complex<double> >                            dz(size, size);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n\n    test(dr, \"Row-major dense\");\n    test(dz, \"Row-major dense with complex numbers\");\n    test(dc, \"Column-major dense\");\n\n    return 0;\n}\n", "meta": {"hexsha": "21f1def7c62c9891152d9068eef32fcb5ed808f1", "size": 4751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/lu_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/lu_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/lu_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 26.9943181818, "max_line_length": 94, "alphanum_fraction": 0.6009261208, "num_tokens": 1453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6037866656315667}}
{"text": "//---------------------------------------------------------------------------\n//    $Id: product_matrix.cc 27657 2012-11-21 13:19:08Z bangerth $\n//\n//    Copyright (C) 2005-2006, 2010, 2012 by the deal.II authors\n//\n//    This file is subject to QPL and may not be distributed without copyright\n//    and license information. Please refer to the file\n//    deal.II/doc/license.html for the text and further information on this\n//    license.\n//\n//---------------------------------------------------------------------------\n\n// See documentation of ProductMatrix for documentation of this example\n\n#include <deal.II/base/logstream.h>\n#include <deal.II/lac/matrix_lib.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/vector.h>\n\nusing namespace dealii;\n\ndouble Adata[] =\n{\n  .5, .1,\n  .4, .2\n};\n\ndouble Bdata[] =\n{\n  .866, .5,\n  -.5, .866\n};\n\n\nint main()\n{\n  FullMatrix<float> A(2,2);\n  FullMatrix<double> B(2,2);\n\n  A.fill(Adata);\n  B.fill(Bdata);\n\n  GrowingVectorMemory<Vector<double> > mem;\n\n  ProductMatrix<Vector<double> > AB(A,B,mem);\n\n  Vector<double> u(2);\n  Vector<double> v(2);\n\n  u(0) = 1.;\n  u(1) = 2.;\n\n  AB.vmult(v,u);\n\n  deallog << v(0) << '\\t' << v(1) << std::endl;\n\n  AB.Tvmult(v,u);\n\n  deallog << v(0) << '\\t' << v(1) << std::endl;\n}\n", "meta": {"hexsha": "5a1cd3dc815a1b9705ba24362338b06c96313cf6", "size": 1262, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/doxygen/product_matrix.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/doxygen/product_matrix.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/doxygen/product_matrix.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 20.6885245902, "max_line_length": 78, "alphanum_fraction": 0.5507131537, "num_tokens": 369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6037428067888876}}
{"text": "/*\n * test_propagator.cpp\n *\n * Created on: Mar 21, 2018 15:28\n * Description:\n *\n * Copyright (c) 2018 Ruixiang Du (rdu)\n */\n\n#include <iostream>\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"model/bicycle_model.hpp\"\n\nusing namespace robosw;\nusing namespace boost::numeric::odeint;\n\nint main() {\n  double t0 = 0;\n  double tf = 10;\n  double dt = 0.01;\n\n  BicycleKinematics::state_type x = {0.0, 0.0, 0.0, 0.0};\n  BicycleKinematics model({0.8, 0});\n\n  boost::numeric::odeint::integrate_const(\n      boost::numeric::odeint::runge_kutta4<BicycleKinematics::state_type>(),\n      model, x, 0.0, 10.0, 0.01);\n\n  //   runge_kutta4<std::vector<double>> rk4;\n  //   double t = t0;\n  //   for (size_t i = 0; i < 1000; ++i, t += dt) {\n  //     rk4.do_step(model, x, t, dt);\n  //   }\n\n  std::cout << \"final state: \" << x[0] << \" , \" << x[1] << std::endl;\n\n  return 0;\n}", "meta": {"hexsha": "0f0fab0809150b1a01612edb8ce588353be92edb", "size": 859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/control/model/tests/test_propagator2.cpp", "max_stars_repo_name": "rxdu/libnav", "max_stars_repo_head_hexsha": "d62c5d7d012cf891b4f1567087bdb1c8e2bfd625", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/control/model/tests/test_propagator2.cpp", "max_issues_repo_name": "rxdu/libnav", "max_issues_repo_head_hexsha": "d62c5d7d012cf891b4f1567087bdb1c8e2bfd625", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-03-13T07:28:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T07:43:16.000Z", "max_forks_repo_path": "src/control/model/tests/test_propagator2.cpp", "max_forks_repo_name": "rxdu/libnav", "max_forks_repo_head_hexsha": "d62c5d7d012cf891b4f1567087bdb1c8e2bfd625", "max_forks_repo_licenses": ["BSD-3-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.475, "max_line_length": 76, "alphanum_fraction": 0.6006984866, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6037428052972479}}
{"text": "/*\n * StokesM2L.cpp\n *\n *  Created on: Oct 12, 2016\n *      Author: wyan\n */\n\n#include \"SVD_pvfmm.hpp\"\n\n#include <Eigen/Dense>\n\n#include <iomanip>\n#include <iostream>\n\n#define DIRECTLAYER 2\n#define PI314 (static_cast<double>(3.1415926535897932384626433))\n#define E271 (static_cast<double>(2.7182818284590452354))\n\nnamespace Laplace3D3DDipole {\n\nusing EVec3 = Eigen::Vector3d;\nusing EMat3 = Eigen::Matrix3d;\n\ninline double ERFC(double x) { return std::erfc(x); }\ninline double ERF(double x) { return std::erf(x); }\n\ninline double f(double r, double eta) {\n    return ERFC(sqrt(PI314 / eta) * r) / r;\n}\n\ninline double fp(double r, double eta) {\n    return -ERFC(sqrt(PI314 / eta) * r) / (r * r) -\n           2 * exp(-PI314 * r * r / eta) / (r * sqrt(eta));\n}\n\n// real and wave sum of 2D Laplace kernel Ewald\n\n// xm: target, xn: source\ninline EVec3 realSum(const double eta, const EVec3 &xn, const EVec3 &xm) {\n    EVec3 rmn = xm - xn;\n    double rnorm = rmn.norm();\n    if (rnorm < 1e-14) {\n        return EVec3(0, 0, 0);\n    }\n    return -fp(rnorm, eta) / rnorm * rmn;\n}\n\ninline EVec3 gKernelEwald(const EVec3 &xm, const EVec3 &xn) {\n    const double eta = 1.0; // recommend for box=1 to get machine precision\n    EVec3 target = xm;\n    EVec3 source = xn;\n    target[0] = target[0] - floor(target[0]); // periodic BC\n    target[1] = target[1] - floor(target[1]);\n    target[2] = target[2] - floor(target[2]);\n    source[0] = source[0] - floor(source[0]);\n    source[1] = source[1] - floor(source[1]);\n    source[2] = source[2] - floor(source[2]);\n\n    // real sum\n    int rLim = 6;\n    EVec3 Kreal(0, 0, 0);\n    for (int i = -rLim; i <= rLim; i++) {\n        for (int j = -rLim; j <= rLim; j++) {\n            for (int k = -rLim; k <= rLim; k++) {\n                EVec3 rmn = target - source + EVec3(i, j, k);\n                if (rmn.norm() < 1e-13) {\n                    continue;\n                }\n                Kreal += realSum(eta, EVec3(0, 0, 0), rmn);\n            }\n        }\n    }\n\n    // wave sum\n    int wLim = 6;\n    EVec3 Kwave(0, 0, 0);\n    EVec3 rmn = target - source;\n\n    for (int i = -wLim; i <= wLim; i++) {\n        for (int j = -wLim; j <= wLim; j++) {\n            for (int k = -wLim; k <= wLim; k++) {\n                if (i == 0 && j == 0 && k == 0) {\n                    continue;\n                }\n                EVec3 kvec = EVec3(i, j, k);\n                double knorm = kvec.norm();\n                Kwave += 2 * PI314 * sin(2 * PI314 * kvec.dot(rmn)) *\n                         exp(-eta * PI314 * knorm * knorm) /\n                         (PI314 * knorm * knorm) * kvec;\n            }\n        }\n    }\n\n    return Kreal + Kwave;\n}\n\ninline EVec3 gKernel(const EVec3 &target, const EVec3 &source) {\n    EVec3 rst = target - source;\n    double rnorm = rst.norm();\n    if (rnorm < 1e-14) {\n        return EVec3(0, 0, 0);\n    } else {\n        return rst / pow(rnorm, 3);\n    }\n}\n\ninline Eigen::Matrix3d gKernelGrad(const EVec3 &target, const EVec3 &source) {\n    EVec3 rst = target - source;\n    double rnorm = rst.norm();\n    if (rnorm < 1e-14) {\n        return Eigen::Matrix3d::Zero();\n    } else {\n        return Eigen::Matrix3d::Identity() / pow(rnorm, 3) -\n               3 * rst * rst.transpose() / pow(rnorm, 5);\n    }\n}\n\n// Out of Direct Sum Layer, far field part\ninline EVec3 gKernelFF(const EVec3 &target, const EVec3 &source) {\n    EVec3 fEwald = gKernelEwald(target, source);\n    const int N = DIRECTLAYER;\n    for (int i = -N; i < N + 1; i++) {\n        for (int j = -N; j < N + 1; j++) {\n            for (int k = -N; k < N + 1; k++) {\n                EVec3 gFree = gKernel(target, source - EVec3(i, j, k));\n                fEwald -= gFree;\n            }\n        }\n    }\n\n    // {\n    //   std::cout << \"source:\" << source << std::endl\n    //             << \"target:\" << target << std::endl\n    //             << \"gKernalFF\" << fEwald << std::endl;\n    // }\n    return fEwald;\n}\n\n/**\n * \\brief Returns the coordinates of points on the surface of a cube.\n * \\param[in] p Number of points on an edge of the cube is (n+1)\n * \\param[in] c Coordinates to the centre of the cube (3D array).\n * \\param[in] alpha Scaling factor for the size of the cube.\n * \\param[in] depth Depth of the cube in the octree.\n * \\return Vector with coordinates of points on the surface of the cube in the\n * format [x0 y0 z0 x1 y1 z1 .... ].\n */\n\ntemplate <class Real_t>\nstd::vector<Real_t> surface(int p, Real_t *c, Real_t alpha, int depth) {\n    size_t n_ = (6 * (p - 1) * (p - 1) + 2); // Total number of points.\n\n    std::vector<Real_t> coord(n_ * 3);\n    coord[0] = coord[1] = coord[2] = -1.0;\n    size_t cnt = 1;\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = -1.0;\n            coord[cnt * 3 + 1] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = (2.0 * j - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * i - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = -1.0;\n            coord[cnt * 3 + 2] = (2.0 * (j + 1) - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = (2.0 * j - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = -1.0;\n            cnt++;\n        }\n    for (size_t i = 0; i < (n_ / 2) * 3; i++)\n        coord[cnt * 3 + i] = -coord[i];\n\n    Real_t r = 0.5 * pow(0.5, depth);\n    Real_t b = alpha * r;\n    for (size_t i = 0; i < n_; i++) {\n        coord[i * 3 + 0] = (coord[i * 3 + 0] + 1.0) * b + c[0];\n        coord[i * 3 + 1] = (coord[i * 3 + 1] + 1.0) * b + c[1];\n        coord[i * 3 + 2] = (coord[i * 3 + 2] + 1.0) * b + c[2];\n    }\n    return coord;\n}\n\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n    Eigen::setNbThreads(1);\n\n    // testing Ewald routine\n    double zeroTest = gKernelEwald(EVec3(0.5, 0.5, 0.5), EVec3(0.5, 0.5, 0.5))\n                          .dot(EVec3(1, 1, 1));\n    std::cout << std::setprecision(16) << \"zeroTest: \" << zeroTest << std::endl;\n\n    double centerTest = gKernelEwald(EVec3(0, 0, 0), EVec3(0.5, 0.5, 0.5))\n                            .dot(EVec3(0.5, 0.5, 0.5));\n    std::cout << std::setprecision(16) << \"centerTest: \" << centerTest\n              << \" error: \" << centerTest - 0 << std::endl;\n\n    centerTest = gKernelEwald(EVec3(0.2, 0.3, 0.4), EVec3(0.3, 0.6, 0.5))\n                     .dot(EVec3(3, 2, 1));\n    std::cout << std::setprecision(16) << \"centerTest2: \" << centerTest\n              << \" error: \" << centerTest + 23.48660380315382667504\n              << std::endl;\n\n    centerTest = gKernelEwald(EVec3(0.7, 0.9, 0.7), EVec3(0.2, 0.3, 0.4))\n                     .dot(EVec3(0.1, 2, 0.3));\n    std::cout << std::setprecision(16) << \"centerTest2: \" << centerTest\n              << \" error: \" << centerTest + 0.83918927151112920892 << std::endl;\n\n    const int pEquiv = atoi(argv[1]); // (8-1)^2*6 + 2 points\n    const int pCheck = atoi(argv[1]);\n    const double scaleEquiv = 1.05;\n    const double scaleCheck = 2.95;\n    const double pCenterEquiv[3] = {\n        -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2};\n    const double pCenterCheck[3] = {\n        -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2};\n\n    const double scaleLEquiv = 1.05;\n    const double scaleLCheck = 2.95;\n    const double pCenterLEquiv[3] = {\n        -(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2};\n    const double pCenterLCheck[3] = {\n        -(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2};\n\n    auto pointMEquiv =\n        surface(pEquiv, (double *)&(pCenterEquiv[0]), scaleEquiv, 0);\n    // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointMCheck = surface(\n        pCheck, (double *)&(pCenterCheck[0]), scaleCheck,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth =0\n\n    auto pointLEquiv = surface(\n        pEquiv, (double *)&(pCenterLCheck[0]), scaleLCheck,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth =  0\n    auto pointLCheck = surface(\n        pCheck, (double *)&(pCenterLEquiv[0]), scaleLEquiv,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    // calculate the operator M2L with least square\n    const int equivN = pointMEquiv.size() / 3;\n    const int checkN = pointLCheck.size() / 3;\n    Eigen::MatrixXd M2L(3 * equivN, 3 * equivN); // Laplace, 1->1\n\n    Eigen::MatrixXd A(3 * checkN, 3 * equivN);\n    A.setZero();\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1],\n                               pointLCheck[3 * k + 2]);\n        for (int l = 0; l < equivN; l++) {\n            const Eigen::Vector3d Lpoint(pointLEquiv[3 * l],\n                                         pointLEquiv[3 * l + 1],\n                                         pointLEquiv[3 * l + 2]);\n            EVec3 temp = gKernel(Cpoint, Lpoint);\n            A(3 * k, 3 * l) = temp[0];\n            A(3 * k + 1, 3 * l + 1) = temp[1];\n            A(3 * k + 2, 3 * l + 2) = temp[2];\n            // A.block(k, l, 1, 3) = gKernel(Cpoint, Lpoint).transpose();\n        }\n    }\n    Eigen::MatrixXd ApinvU(A.cols(), A.rows());\n    Eigen::MatrixXd ApinvVT(A.cols(), A.rows());\n    pinv(A, ApinvU, ApinvVT);\n\n#pragma omp parallel for\n    for (int i = 0; i < equivN; i++) {\n        const Eigen::Vector3d Mpoint(pointMEquiv[3 * i], pointMEquiv[3 * i + 1],\n                                     pointMEquiv[3 * i + 2]);\n        //\t\tstd::cout << \"debug:\" << Mpoint << std::endl;\n\n        // assemble linear system\n        Eigen::VectorXd f0(3 * checkN);\n        Eigen::VectorXd f1(3 * checkN);\n        Eigen::VectorXd f2(3 * checkN);\n        f0.setZero();\n        f1.setZero();\n        f2.setZero();\n        for (int k = 0; k < checkN; k++) {\n            Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1],\n                                   pointLCheck[3 * k + 2]);\n            //\t\t\tstd::cout<<\"debug:\"<<k<<std::endl;\n            // sum the images\n            EVec3 temp = gKernelFF(Cpoint, Mpoint);\n            f0[3 * k] = temp[0];\n            f1[3 * k + 1] = temp[1];\n            f2[3 * k + 2] = temp[2];\n        }\n        // std::cout << \"debug:\" << f0 << std::endl;\n\n        M2L.block(0, 3 * i, 3 * equivN, 1) =\n            (ApinvU.transpose() * (ApinvVT.transpose() * f0));\n        M2L.block(0, 3 * i + 1, 3 * equivN, 1) =\n            (ApinvU.transpose() * (ApinvVT.transpose() * f1));\n        M2L.block(0, 3 * i + 2, 3 * equivN, 1) =\n            (ApinvU.transpose() * (ApinvVT.transpose() * f2));\n    }\n\n    // dump M2L\n    for (int i = 0; i < 3 * equivN; i++) {\n        for (int j = 0; j < 3 * equivN; j++) {\n            std::cout << i << \" \" << j << \" \" << std::scientific\n                      << std::setprecision(18) << M2L(i, j) << std::endl;\n        }\n    }\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>\n        dipolePoint(1);\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>\n        dipoleValue(1);\n    dipolePoint[0] = Eigen::Vector3d(0.2, 0.3, 0.4);\n    dipoleValue[0] = Eigen::Vector3d(0.1, 0.2, 0.3);\n\n    // solve M\n    A.resize(3 * checkN, 3 * equivN);\n    ApinvU.resize(A.cols(), A.rows());\n    ApinvVT.resize(A.cols(), A.rows());\n    Eigen::VectorXd f(3 * checkN);\n    for (int k = 0; k < checkN; k++) {\n        EVec3 sum(0, 0, 0);\n        Eigen::Vector3d Cpoint(pointMCheck[3 * k], pointMCheck[3 * k + 1],\n                               pointMCheck[3 * k + 2]);\n        for (size_t p = 0; p < dipolePoint.size(); p++) {\n            EVec3 temp = gKernel(Cpoint, dipolePoint[p]);\n            sum[0] += temp[0] * dipoleValue[p][0];\n            sum[1] += temp[1] * dipoleValue[p][1];\n            sum[2] += temp[2] * dipoleValue[p][2];\n        }\n        f[3 * k] = sum[0];\n        f[3 * k + 1] = sum[1];\n        f[3 * k + 2] = sum[2];\n        for (int l = 0; l < equivN; l++) {\n            Eigen::Vector3d Mpoint(pointMEquiv[3 * l], pointMEquiv[3 * l + 1],\n                                   pointMEquiv[3 * l + 2]);\n            // A(k, l) = gKernel(Mpoint, Cpoint);\n            EVec3 temp = gKernel(Cpoint, Mpoint);\n            A(3 * k, 3 * l) = temp[0];\n            A(3 * k + 1, 3 * l + 1) = temp[1];\n            A(3 * k + 2, 3 * l + 2) = temp[2];\n        }\n    }\n    pinv(A, ApinvU, ApinvVT);\n    Eigen::VectorXd Msource = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n\n    std::cout << \"Msource: \" << Msource << std::endl;\n\n    Eigen::VectorXd M2Lsource = M2L * (Msource);\n\n    Eigen::Vector3d samplePoint(0.7, 0.9, 0.7);\n    //    Eigen::Vector3d samplePoint = dipolePoint[0];\n    double Usample = 0;\n    double UsampleSP = 0;\n\n    for (int i = -DIRECTLAYER; i < 1 + DIRECTLAYER; i++) {\n        for (int j = -DIRECTLAYER; j < 1 + DIRECTLAYER; j++) {\n            for (int k = -DIRECTLAYER; k < 1 + DIRECTLAYER; k++) {\n                for (size_t p = 0; p < dipolePoint.size(); p++) {\n                    Usample +=\n                        gKernel(samplePoint, dipolePoint[p] + EVec3(i, j, k))\n                            .dot(dipoleValue[p]);\n                }\n            }\n        }\n    }\n\n    for (int p = 0; p < equivN; p++) {\n        Eigen::Vector3d Lpoint(pointLEquiv[3 * p], pointLEquiv[3 * p + 1],\n                               pointLEquiv[3 * p + 2]);\n        EVec3 M2Lsp(M2Lsource[3 * p], M2Lsource[3 * p + 1],\n                    M2Lsource[3 * p + 2]);\n        UsampleSP += gKernel(samplePoint, Lpoint).dot(M2Lsp);\n    }\n\n    std::cout << \"samplePoint:\" << samplePoint << std::endl;\n    std::cout << \"Usample NF:\" << Usample << std::endl;\n    std::cout << \"Usample FF:\" << UsampleSP << std::endl;\n    std::cout << \"Usample FF+NF total:\" << UsampleSP + Usample << std::endl;\n\n    std::cout\n        << \"Error : \"\n        << UsampleSP + Usample -\n               gKernelEwald(samplePoint, dipolePoint[0]).dot(dipoleValue[0])\n        << std::endl;\n\n    return 0;\n}\n\n} // namespace Laplace3D3DDipole\n\n#undef DIRECTLAYER\n#undef PI314\n#undef E271\n", "meta": {"hexsha": "5dab2b55270fb4dfaefc604e4c4f8c96c5b8fe65", "size": 14216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2LLaplace/src/Laplace3D3DDipole.cpp", "max_stars_repo_name": "blackwer/PeriodicFMM", "max_stars_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-06-14T02:07:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T04:41:34.000Z", "max_issues_repo_path": "M2LLaplace/src/Laplace3D3DDipole.cpp", "max_issues_repo_name": "blackwer/PeriodicFMM", "max_issues_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "M2LLaplace/src/Laplace3D3DDipole.cpp", "max_forks_repo_name": "blackwer/PeriodicFMM", "max_forks_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:30:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T20:26:36.000Z", "avg_line_length": 35.8085642317, "max_line_length": 80, "alphanum_fraction": 0.4913477772, "num_tokens": 4977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6037428011713164}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <vector>\n#include \"../flux_worker.hpp\"\n#include \"../outflow_helper.hpp\"\n#include \"aux/eigen2hdf.hpp\"\n#include \"base/numbers.hpp\"\n\nnamespace boltzmann {\nnamespace impl_mls {\n\nclass DiffusiveReflection : public boltzmann::impl::flux_worker\n{\n public:\n  /**\n   * @param hw Hermite quad. weights (from @see QHermiteW)\n   * @param hx Hermite quad. nodes\n   * @param vt tangential velocity (moving wall)\n   * @param Tw wall temperature\n   * @param rho scaling factor\n   *\n   */\n  DiffusiveReflection(const vec_t& hw, const vec_t& hx, double vt, double Tw, double rho = 1.0);\n\n  virtual void apply(mat_t& out,\n                     const mat_t& in,\n                     const dealii::Point<2>& dummy = dealii::Point<2>(0, 0)) const;\n\n private:\n  boltzmann::impl::outflow_helper outflow_;\n  const vec_t w_;\n  const vec_t x_;\n  double rho_;\n\n  // Eigen::MatrixXd rho_minus_;\n  Eigen::MatrixXd Mw_;\n};\n\n// --------------------------------------------------------------------------------\nDiffusiveReflection::DiffusiveReflection(\n    const vec_t& hw, const vec_t& hx, double vt, double Tw, double rho)\n    : outflow_(hw, hx)\n    , w_(hw)\n    , x_(hx)\n    , rho_(rho)\n{\n  unsigned int K = hx.size();\n  Mw_.resize(K, K);\n\n  unsigned int khalf = K / 2;\n\n  // normalization factor\n  const double fMw = rho_ / std::sqrt(2 * numbers::PI) / std::pow(Tw, 1.5);\n\n  // initialize maxwellian\n  for (unsigned int i = 0; i < K; ++i) {\n    for (unsigned int j = 0; j < K; ++j) {\n      if (i < khalf) {  // inflow boundary\n        double x2h = std::pow(x_[i], 2) + std::pow(x_[j] - vt, 2);\n        Mw_(i, j) = fMw * std::exp(0.5 * x2h * (-1. / Tw)) * std::sqrt(w_[i] * w_[j]) * x_[i];\n      } else {  // outflow\n        Mw_(i, j) = 0;\n      }\n    }\n  }\n\n}\n\n// --------------------------------------------------------------------------------\nvoid\nDiffusiveReflection::apply(mat_t& out, const mat_t& in, const dealii::Point<2>& dummy) const\n{\n  int K = out.cols();\n\n  // compute outflow\n  double rhom = 0;\n  for (int i = 0; i < K; ++i) {\n    for (int j = 0; j < K; ++j) {\n      rhom += in(i, j) * outflow_.get_y(i) * outflow_.get_x(j);\n    }\n  }\n\n  int khalf = K / 2;\n\n  out.setZero();\n\n  // outflow\n  for (int i = khalf; i < K; ++i) {\n    for (int j = 0; j < K; ++j) {\n      out(i, j) = in(i, j) * x_[i];\n    }\n  }\n\n  // inflow M_w\n  out += Mw_ * rhom;\n}\n\n}  // namespace impl_mls\n}  // end namespace boltzmann\n", "meta": {"hexsha": "53d42816f3c08d2f028bb6dd8e961947ed1aa090", "size": 2429, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix/bc/impl/mls/diffusive_reflection.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrix/bc/impl/mls/diffusive_reflection.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix/bc/impl/mls/diffusive_reflection.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0495049505, "max_line_length": 96, "alphanum_fraction": 0.5389048991, "num_tokens": 773, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.6992544273261175, "lm_q1q2_score": 0.603730410706262}}
{"text": "#include <cmath>\n#include <cstdlib>\n#include <memory>\n\n#include <Eigen/Core>\n#include <glog/logging.h>\n#include <gtest/gtest.h>\n\n#include <geometric-vision/linear-triangulation.h>\n#include <maplab-common/pose_types.h>\n#include <maplab-common/quaternion-math.h>\n#include <maplab-common/test/testing-entrypoint.h>\n#include <maplab-common/test/testing-predicates.h>\n\nusing namespace geometric_vision;  // NOLINT\n\nclass GeometricVisionNViewParamTest\n    : public ::testing::TestWithParam<Eigen::Vector3d> {\n protected:\n  Eigen::Vector2d reprojectPoint(\n      const pose::Transformation& G_T_C, const Eigen::Vector3d& G_p_fi) {\n    const Eigen::Vector3d C_p_fi = G_T_C.inverse() * G_p_fi;\n    return C_p_fi.hnormalized().head<2>();\n  }\n};\n\nINSTANTIATE_TEST_CASE_P(\n    GeometricVision, GeometricVisionNViewParamTest,\n    ::testing::Values(\n        Eigen::Vector3d(1.5, 0.0, 4.0), Eigen::Vector3d(1.1, 0.1, 3.0),\n        Eigen::Vector3d(0.9, -0.05, 1.43), Eigen::Vector3d(1.2, 0.07, 2.73),\n        Eigen::Vector3d(2.1, -0.05, 5.2), Eigen::Vector3d(1.8, -0.05, 2.8),\n        Eigen::Vector3d(-0.2, -0.25, 1.2), Eigen::Vector3d(3.1, -1.05, 6.1)));\n\nTEST_P(GeometricVisionNViewParamTest, NViewTriangulationTest) {\n  const unsigned int number_of_views = 5;\n\n  pose::Quaternion rotations[] = {\n      pose::Quaternion(1, 0, 0, 0),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.15, Eigen::Vector3d(0.0, 1.0, 0.1)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.05, Eigen::Vector3d(0.3, 1.0, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.15, Eigen::Vector3d(0.2, 0.3, 0.1)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(-0.1, Eigen::Vector3d(0.1, 1.0, 0.0)))\n              .normalized())};\n\n  pose::Position3D positions[] = {\n      pose::Position3D(0, 0, 0), pose::Position3D(-3, 0, 0),\n      pose::Position3D(0.85, 0.1, -0.3), pose::Position3D(-0.1, -0.05, 0.4),\n      pose::Position3D(0.7, 0.3, 0.21)};\n\n  Eigen::Vector3d G_p_fi = GetParam();\n\n  Aligned<std::vector, Eigen::Vector2d> measurements;\n  Aligned<std::vector, pose::Transformation> camera_poses;\n  camera_poses.resize(number_of_views);\n  measurements.resize(number_of_views);\n  for (unsigned int i = 0; i < number_of_views; ++i) {\n    pose::Transformation G_T_Ci(positions[i], rotations[i]);\n    measurements[i] = reprojectPoint(G_T_Ci, G_p_fi);\n    camera_poses[i] = G_T_Ci;\n  }\n\n  Eigen::Vector3d triangulated_point;\n  LinearTriangulation triangulator;\n  EXPECT_TRUE(\n      triangulator.triangulateFromNormalizedNViews(\n          measurements, camera_poses, &triangulated_point));\n  EXPECT_NEAR_EIGEN(G_p_fi, triangulated_point, 1e-12);\n}\n\nTEST_P(GeometricVisionNViewParamTest, NoisyNViewTriangulationTest) {\n  srand(1);\n  const unsigned int number_of_views = 20;\n\n  pose::Quaternion rotations[] = {\n      pose::Quaternion(1, 0, 0, 0),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.15, Eigen::Vector3d(0.0, 1.0, 0.1)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.05, Eigen::Vector3d(0.3, 1.0, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.02, Eigen::Vector3d(-0.2, 0.3, 0.1)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(-0.1, Eigen::Vector3d(0.12, 1.0, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(-0.1, Eigen::Vector3d(-0.1, 1.0, 0.2)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.01, Eigen::Vector3d(0.1, 1.0, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(-0.3, Eigen::Vector3d(0.1, 1.0, 0.1)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(-1.5, Eigen::Vector3d(-0.1, 1.0, 0.3)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(-0.3, Eigen::Vector3d(0.1, 1.0, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.1, Eigen::Vector3d(0.1, 1.0, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.0, Eigen::Vector3d(0.0, 1.0, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.02, Eigen::Vector3d(0.1, 1.0, 0.1)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.01, Eigen::Vector3d(0.1, 1.0, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.0, Eigen::Vector3d(0.1, 1.0, 0.1)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.8, Eigen::Vector3d(0.0, 1.0, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.0, Eigen::Vector3d(0.1, 1.0, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.1, Eigen::Vector3d(0.5, 0.5, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(0.0, Eigen::Vector3d(0.0, 1.0, 0.0)))\n              .normalized()),\n      pose::Quaternion(\n          Eigen::Quaterniond(\n              Eigen::AngleAxisd(-0.02, Eigen::Vector3d(0.1, 1.0, 0.1)))\n              .normalized())};\n\n  pose::Position3D positions[] = {\n      pose::Position3D(0, 0, 0),           pose::Position3D(-3, 0, 0),\n      pose::Position3D(-1.85, 0.6, -0.3),  pose::Position3D(-0.1, -0.05, 0.4),\n      pose::Position3D(0.7, 0.1, -0.05),   pose::Position3D(-3.7, -1.1, 0.05),\n      pose::Position3D(-0.53, 1.3, 0.13),  pose::Position3D(-2.5, -0.3, 0.21),\n      pose::Position3D(-3.8, 0.1, 1),      pose::Position3D(0.7, -0.6, 1),\n      pose::Position3D(-5, 0.43, 1),       pose::Position3D(-1.7, -0.6, 1),\n      pose::Position3D(-4, -0.13, 1),      pose::Position3D(-3.5, 0, 0.1),\n      pose::Position3D(-3, 0.1, 0),        pose::Position3D(-1.85, 0.12, -0.32),\n      pose::Position3D(-0.1, -0.25, 0.41), pose::Position3D(-0.89, 0.12, -0.05),\n      pose::Position3D(-3.7, -0.3, 0.02),  pose::Position3D(2, 0.2, 0.19)};\n\n  Eigen::Vector3d G_p_fi = GetParam();\n\n  Aligned<std::vector, Eigen::Vector2d> measurements;\n  Aligned<std::vector, pose::Transformation> camera_poses;\n  camera_poses.resize(number_of_views);\n  measurements.resize(number_of_views);\n  for (unsigned int i = 0; i < number_of_views; ++i) {\n    pose::Transformation G_T_Ci(positions[i], rotations[i]);\n    measurements[i] = reprojectPoint(G_T_Ci, G_p_fi);\n    measurements[i] += Eigen::Vector2d::Random() / 1e4;\n    camera_poses[i] = G_T_Ci;\n  }\n\n  Eigen::Vector3d triangulated_point;\n  LinearTriangulation triangulator;\n  EXPECT_TRUE(\n      triangulator.triangulateFromNormalizedNViews(\n          measurements, camera_poses, &triangulated_point));\n\n  // Check consistency of reprojection errors.\n  for (unsigned int i = 0; i < number_of_views; ++i) {\n    Eigen::Vector2d reprojected_point =\n        reprojectPoint(camera_poses[i], triangulated_point);\n    EXPECT_NEAR_EIGEN(\n        reprojected_point, reprojectPoint(camera_poses[i], G_p_fi), 1e-3);\n  }\n  // Check retriangulated point coordinates.\n  EXPECT_NEAR_EIGEN(G_p_fi, triangulated_point, 1e-3);\n}\n\nMAPLAB_UNITTEST_ENTRYPOINT\n", "meta": {"hexsha": "a12d7713134273282e823c1dc9433efca67c18bb", "size": 7935, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/geometric-vision-algorithms/test/test_n_view_triangulation.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/geometric-vision-algorithms/test/test_n_view_triangulation.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/geometric-vision-algorithms/test/test_n_view_triangulation.cc", "max_forks_repo_name": "AdronTech/maplab", "max_forks_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 661.0, "max_forks_repo_forks_event_min_datetime": "2017-11-28T07:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:06:29.000Z", "avg_line_length": 38.1490384615, "max_line_length": 80, "alphanum_fraction": 0.5933207309, "num_tokens": 2575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.689305616785446, "lm_q1q2_score": 0.6036848969200431}}
{"text": "// Compile:\n// g++ -I /usr/include/eigen3/ softmaxspeed.cpp -o softmaxspeed\n// Run:\n// ./softmaxspeed 10 20 30 40\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <ctime>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n  if ( argc != 5 ) {\n    cout << \"Usage: softmaxspeed T U N n_trials\" << endl;\n    return 0;\n  }\n\n  // Number of timesteps in the input\n  const int T = atoi(argv[1]);\n  // Number of output timesteps\n  const int U = atoi(argv[2]);\n  // Dimensionality of the input/output\n  const int N = atoi(argv[3]);\n  // Number of trials to run for timing\n  const int n_trials = atoi(argv[4]);\n\n  // Initializers\n  double energy_max;\n  VectorXd energy;\n  VectorXd attention;\n  VectorXd context;\n  MatrixXd x = MatrixXd::Random(T, N);\n  MatrixXd s = MatrixXd::Random(U, N);\n  \n  // Time it\n  clock_t begin = clock();\n  for (int trial = 0; trial < n_trials; trial++) {\n    for (int i = 0; i < U; i++) {\n      // Compute dot product of the i'th row of s against all rows of x\n      energy = x * s.row(i).transpose();\n      // Compute softmax(energy)_n = exp(energy[n] - max(energy))/sum(exp(energy))\n      energy_max = energy.maxCoeff();\n      energy -= energy_max*VectorXd::Ones(energy.size());\n      attention = energy.array().exp();\n      attention /= attention.array().sum();\n      // Compute weighted sum of each entry in x\n      context = (x.array().colwise() * attention.array()).colwise().sum();\n    }\n  }\n  clock_t end = clock();\n  cout << double(end - begin) / CLOCKS_PER_SEC << endl;\n}\n", "meta": {"hexsha": "f66262a8030554ad10bced49efeddfebbd08b665", "size": 1535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/softmaxspeed.cpp", "max_stars_repo_name": "craffel/mad", "max_stars_repo_head_hexsha": "b3687a70615044359c8acc440e43a5e23dc58309", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 87.0, "max_stars_repo_stars_event_min_datetime": "2017-04-05T02:38:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T10:17:56.000Z", "max_issues_repo_path": "benchmark/softmaxspeed.cpp", "max_issues_repo_name": "craffel/mad", "max_issues_repo_head_hexsha": "b3687a70615044359c8acc440e43a5e23dc58309", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-01-03T03:46:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-02T15:20:57.000Z", "max_forks_repo_path": "benchmark/softmaxspeed.cpp", "max_forks_repo_name": "craffel/mad", "max_forks_repo_head_hexsha": "b3687a70615044359c8acc440e43a5e23dc58309", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2017-04-05T02:24:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T09:54:49.000Z", "avg_line_length": 27.9090909091, "max_line_length": 82, "alphanum_fraction": 0.6273615635, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.603684887981073}}
{"text": "#include \"Mesh_Data_Struct.h\"\n#include \"igl/circulation.h\"\n#include \"igl/vertex_triangle_adjacency.h\"\n#include <Eigen/LU>\n\nMesh_Data_Struct::Mesh_Data_Struct(std::string filename, Eigen::MatrixXd& data_F_normals)\n{\n\tigl::read_triangle_mesh(filename, OV, OF);\n\tV = OV;\n\tF = OF;\n\tF_normals = data_F_normals;\n\tigl::edge_flaps(F, E, EMAP, EF, EI);\n\tQit->resize(E.rows());\n\n\tC.resize(E.rows(), V.cols());\n\t\n\tQ->clear();\n\tQV->resize(V.rows());\n\n\tstd::vector<std::vector<int>> VF;\n\tstd::vector<std::vector<int>> VFi;\n\n\tigl::vertex_triangle_adjacency(V, F, VF, VFi);\n\n\tfor (int v = 0; v < V.rows(); v++) {\n\t\t(*QV)[v] = Eigen::Matrix4d::Zero();\n\t\tfor (int f = 0; f < VF[v].size(); f++) {\n\t\t\tEigen::Vector3d norm = F_normals.row(VF[v][f]).normalized();\n\t\t\tdouble d = V.row(v) * norm;\n\t\t\tdouble a = norm[0];\n\t\t\tdouble b = norm[1];\n\t\t\tdouble c = norm[2];\n\t\t\td *= -1;\n\t\t\tEigen::Matrix4d Kp;\n\t\t\tKp.row(0) = Eigen::Vector4d(a * a, a * b, a * c, a * d);\n\t\t\tKp.row(1) = Eigen::Vector4d(a * b, b * b, b * c, b * d);\n\t\t\tKp.row(2) = Eigen::Vector4d(a * c, c * b, c * c, c * d);\n\t\t\tKp.row(3) = Eigen::Vector4d(a * d, d * b, d * c, d * d);\n\t\t\t(*QV)[v] += Kp;\n\t\t}\n\t}\n\t\n\tfor (int e = 0; e < E.rows(); e++)\n\t\t{\n\t\tdouble cost = e;\n\t\tEigen::RowVector3d p;\n\n\t\tEigen::Matrix4d QUAD = (*QV)[E(e,0)] + (*QV)[E(e, 1)];\n\t\tEigen::Matrix4d QUADp = Eigen::Matrix4d::Identity();\n\t\tQUADp.row(0) = QUAD.row(0);\n\t\tQUADp.row(1) = QUAD.row(1);\n\t\tQUADp.row(2) = QUAD.row(2);\n\t\t//QUADp.block(0, 0, 3, 4) = QUAD3.block(0, 0, 3, 4);\n\t\tEigen::Vector4d temp;\n\t\tif (QUADp.fullPivLu().isInvertible()) {\n\t\t\ttemp = QUADp.inverse() * (Eigen::Vector4d(0.0, 0.0, 0.0, 1.0));\n\t\t\tp[0] = temp[0];\n\t\t\tp[1] = temp[1];\n\t\t\tp[2] = temp[2];\n\t\t\t\n\t\t}\n\t\telse {\n\t\t\tp = V.row(E(e, 0));\n\t\t\ttemp[0] = p[0];\n\t\t\ttemp[1] = p[1];\n\t\t\ttemp[2] = p[2];\n\t\t\ttemp[3] = 1.0;\n\n\t\t}\n\n\t\tcost = temp.transpose() * QUAD * temp;\n\t   \n\n\t\tC.row(e) = p;\n\t\t(*Qit)[e] = Q->insert(std::pair<double, int>(cost, e)).first;\n\t}\n\tnum_collapsed = 0;\n\n}\n\nMesh_Data_Struct:: ~Mesh_Data_Struct() {}\n\n", "meta": {"hexsha": "054295da18b81addcb31de1ea19cd46400a31154", "size": 1995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tutorial/sandBox/Mesh_Data_Struct.cpp", "max_stars_repo_name": "chenhadad/EngineI_GL_new_Final", "max_stars_repo_head_hexsha": "31fd37c617a6d82117e36676786bac8c0f04c278", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-25T16:41:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-25T16:41:45.000Z", "max_issues_repo_path": "tutorial/sandBox/Mesh_Data_Struct.cpp", "max_issues_repo_name": "Danielsadoun/EngineIGLnewFinal", "max_issues_repo_head_hexsha": "a051367a9217f91ed8682f4e4b1f61b746610145", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial/sandBox/Mesh_Data_Struct.cpp", "max_forks_repo_name": "Danielsadoun/EngineIGLnewFinal", "max_forks_repo_head_hexsha": "a051367a9217f91ed8682f4e4b1f61b746610145", "max_forks_repo_licenses": ["Apache-2.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.0361445783, "max_line_length": 89, "alphanum_fraction": 0.5568922306, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.6893056040203135, "lm_q1q2_score": 0.603684876801536}}
{"text": "/**\n    @file bayes_classifier.cpp\n\n    @author Terence Henriod\n\n    Project 1: Bayesian Minimum Error Classification\n\n    @brief Class implementations for the BayesClassifier defined in\n           bayes_classifier.h.\n\n    @version Original Code 1.00 (3/8/2014) - T. Henriod\n*/\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                   HEADER FILES / NAMESPACES\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n// Class Declaration\n#include \"bayes_classifier.h\"\n\n// Other Dependencies\n#include <cassert>\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>  // -I /home/thenriod/Desktop/cpp_libs/Eigen_lib\n\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n================================================================================\n                   CLASS FUNCTION IMPLEMENTATIONS\n================================================================================\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                   CONSTRUCTOR(S) / DESTRUCTOR\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n/**\nBayesClassifier\n\nDescription\n\n@pre\n-# The GameState object is given an appropriate identifier.\n\n@post\n-# A new, empty GameState will be initialized.\n\n@code\n@endcode\n*/\nBayesClassifier::BayesClassifier()\n{\n  // variables\n  int ndx = 0;\n  Eigen::Vector2d temp_mean;\n    temp_mean << 1, 1;\n  Eigen::Matrix2d temp_matrix;\n    temp_matrix << 1, 0,\n                   0, 1;\n\n  // initialize all members\n  mean_vector_ << 1, 1;\n  covariance_matrix_ << 1, 0,\n                       0, 1;\n  inverse_covariance_matrix_ = covariance_matrix_.inverse();\n  covariance_determinant_ = covariance_matrix_.determinant();\n  prior_probability_ = 0.5;\n  class_name_ = \"Give me a name!\";\n\n  // no return - constructor\n}\n\n\nBayesClassifier::BayesClassifier( const BayesClassifier& other )\n{\n  // no return - copy constructor\n}\n\n\nBayesClassifier& BayesClassifier::operator=( const BayesClassifier& other )\n{\n  // return *this\n  return *this;\n}\n\n\nBayesClassifier::~BayesClassifier()\n{\n  // currently nothing to destruct\n\n  // no return - destructor\n}\n\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                   MUTATORS\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n\nvoid BayesClassifier::clear()\n{\n  // no return - void\n}\n\n\nvoid BayesClassifier::setMean( const Eigen::Vector2d& new_mean_vector )\n{\n  // set the appropriate mean vector\n  mean_vector_ = new_mean_vector;\n\n  // no return - void\n}\n\n\nvoid BayesClassifier::setMean( const vector<DataItem>& data )\n{\n  // variables\n  Eigen::Vector2d new_mean;\n    new_mean << 0, 0;\n  int i = 0;\n  int num_data = 0;\n\n  // sum the values of the features over all of the data\n  for( i = 0; i < data.size(); i++ )\n  {\n    // case: the data is of the desired class\n    if( data[i].actual_class == class_name_ )\n    {\n      // add the data to the sum\n      new_mean( 0 ) += data[i].feature_vector( 0 );\n      new_mean( 1 ) += data[i].feature_vector( 1 );\n      num_data++;\n    }\n  }\n\n  // scale the data\n  new_mean( 0 ) /= num_data;\n  new_mean( 1 ) /= num_data;\n\n  // update the new mean member\n  mean_vector_ = new_mean;\n\n  // no return - void\n}\n\n\n\n\nvoid BayesClassifier::setCovariance(\n    const Eigen::Matrix2d& new_covariance_matrix )\n{\n  // set the appropriate covariance matrix\n  covariance_matrix_ = new_covariance_matrix;\n\n  // update the other covariance related members\n  inverse_covariance_matrix_ = covariance_matrix_.inverse();\n  covariance_determinant_ = covariance_matrix_.determinant();\n\n  // no return - void\n}\n\n\n\nvoid BayesClassifier::setCovariance( const vector<DataItem>& data,\n                                     const Eigen::Vector2d& mean )\n{\n  // variables\n  Eigen::Matrix2d new_covariance;\n     new_covariance << 0, 0,\n                       0, 0;\n  double temp = 0;\n  int i = 0;\n  int num_data = 0;\n\n\n  // sum the values of the features over all of the data\n  for( num_data = 0, temp = 0, i = 0; i < data.size(); i++ )\n  {\n    // case: the data is of the desired class\n    if( data[i].actual_class == class_name_ )\n    {\n      // add the data to the sum\n      temp += ( data[i].feature_vector( 0 ) - mean( 0 ) ) *\n              ( data[i].feature_vector( 0 ) - mean( 0 ) );\n      num_data++;\n    }\n  }\n\n  // scale the result\n  new_covariance( 0, 0 ) /= (num_data - 1);\n\n\n  // sum the values of the features over all of the data\n  for( temp = 0, i = 0; i < data.size(); i++ )\n  {\n    // case: the data is of the desired class\n    if( data[i].actual_class == class_name_ )\n    {\n      // add the data to the sum\n      temp += ( data[i].feature_vector( 0 ) - mean( 0 ) ) *\n              ( data[i].feature_vector( 1 ) - mean( 1 ) );\n    }\n  }\n\n  // scale the result\n  new_covariance( 0, 1 ) /= (num_data - 1);\n  new_covariance( 1, 0 ) = new_covariance( 0, 1 );\n\n  // sum the values of the features over all of the data\n  for( temp = 0, i = 0; i < data.size(); i++ )\n  {\n    // case: the data is of the desired class\n    if( data[i].actual_class == class_name_ )\n    {\n      // add the data to the sum\n      temp += ( data[i].feature_vector( 1 ) - mean( 1 ) ) *\n              ( data[i].feature_vector( 1 ) - mean( 1 ) );\n    }\n  }\n\n  // scale the result\n  new_covariance( 1, 1 ) /= (num_data - 1);\n\n  // update the new mean member\n  covariance_matrix_ = new_covariance;\n\n  // update the other covariance related members\n  inverse_covariance_matrix_ = covariance_matrix_.inverse();\n  covariance_determinant_ = covariance_matrix_.determinant();\n\n  // no return - void\n}\n\n\n\nvoid BayesClassifier::setPriorProbability( const double new_probability )\n{\n  // assert pre-conditions\n  assert( ( new_probability >= 0.0 ) && ( new_probability <= 1.0 ) );\n\n  // set the new prior probability\n  prior_probability_ = new_probability;\n\n  // no return - void\n}\n\nvoid BayesClassifier::set_class_name( const string& new_name )\n{\n  // set the class name member\n  class_name_ = new_name;\n}\n\n\n/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n                   ACCESSORS\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\ndouble BayesClassifier::prior_probability() const\n{\n  // return the prior probability of the class\n  return prior_probability_;\n}\n\n\nEigen::Vector2d BayesClassifier::mean_vector() const\n{\n  // return the prior mean feature vector of the class\n  return mean_vector_;\n}\n\n\nEigen::Matrix2d BayesClassifier::covariance_matrix() const\n{\n  // return the covariance matrix of the class\n  return covariance_matrix_;\n}\n\n\nEigen::Matrix2d BayesClassifier::inverse_covariance_matrix() const\n{\n  // return the inverse of the covariance matrix of the class\n  return inverse_covariance_matrix_;\n}\n\n\ndouble BayesClassifier::covariance_determinant() const\n{\n  // return the determinant of the covariance matrix of the class\n  return covariance_determinant_;\n}\n\n\nstring BayesClassifier::class_name() const\n{\n  // return the class name\n  return class_name_;\n}\n\n\nvoid BayesClassifier::performAnalysis(\n    const string input_file,\n    const string output_file,\n    const vector<BayesClassifier>& classifiers )\n{\n\n/*\n  // variables\n  fstream file;\n  TestData temp;\n  char delimiter;\n  int num_data = 0;\n  int ndx = 0;\n  int num_misclassified = 0;\n  double test_error_rate = 0.5;\n  double beta_start = 0.5;\n  vector<TestData> data;\n  Chernoff chernoff_bound;\n\n  // read in all of the data\n  file.clear();\n  file.open( input_file.c_str(), fstream::in );\n  while( file.good() )\n  {\n    // read in a line of data\n    file >> temp.feature_vector(0) >> delimiter\n         >> temp.feature_vector(1) >> delimiter\n         >> temp.actual_class;\n\n    // store the data\n    data.push_back( temp );\n\n    // count the data\n    num_data++;\n  }\n  file.close();\n\n  // classify all of the data\n  for( ndx = 0; ndx < num_data; ndx++ )\n  {\n    // classify an object\n    data[ndx].classified_as = assignToClass( data[ndx].feature_vector,\n                                             classifiers );\n\n    // case: it was classified correctly\n    if( data[ndx].classified_as == data[ndx].actual_class )\n    {\n      // mark and count this as a correct classification\n      data[ndx].correctly_classified = CORRECT;\n    }\n    // case: it was not classified correctly\n    else\n    {\n      // mark this as an incorrect classification\n      data[ndx].correctly_classified = INCORRECT;\n      num_misclassified++;\n    }\n  }\n\n  // compute the error rate of the test\n  test_error_rate = double( num_misclassified ) / double( num_data );\n\n  // find chernoff bound\n  chernoff_bound = findChernoffBound( beta_start, 0 );\n\n  // output the results to file\n  file.clear();\n  file.open( output_file.c_str(), fstream::out );\n  file << \"Number of data: \" << ( num_data - 1 ) << endl\n       << \"Number of incorrect classifications: \"\n           << num_misclassified << endl\n       << \"Test Sample Error Rate: \" << test_error_rate << endl\n       << \"Battacharyya bound: \" << findBattacharyyaBound() << endl\n       << \"Chernoff bound: \" << chernoff_bound.bound << endl\n       << \"         beta*: \" << chernoff_bound.beta << endl;\n  for( ndx = 0; ndx < num_data; ndx++ )\n  {\n    // write the delimited data to the file\n    file << data[ndx].feature_vector(0) << \", \"\n         << data[ndx].feature_vector(1) << \", \"\n         << data[ndx].actual_class << \", \"\n         << data[ndx].classified_as << \", \"\n         << data[ndx].correctly_classified << endl;\n  }\n  file.close();\n*/\n  // no return - void\n}\n\n\nstring BayesClassifier::assignToClass(\n    Eigen::Vector2d& input_vector,\n    vector<BayesClassifier>& classifiers )\n{\n  // variables\n  string classification_result = \"NO_RESULT\";\n  int i = 0;\n  double largest_discriminant = 0;\n  double largest_discriminant_ndx = 0;\n\n  // calculate each of the discriminants, keep track of the most likely class\n  for( i = 0; i < classifiers.size(); ++i )\n  {\n    // case: this discriminant is larger than the previously largest one\n    if( largest_discriminant <\n        classifiers[i].calculateDiscriminant( input_vector ) )\n    {\n      // store the index of the class\n      largest_discriminant_ndx = i;\n    }\n  }\n\n  // whichever class produced the largest discriminant is the most likely\n  classification_result = classifiers[largest_discriminant_ndx].class_name();\n\n  // return the resulting assignment\n  return classification_result;\n}\n\n\ndouble BayesClassifier::calculateDiscriminant(\n    const Eigen::Vector2d& input_vector )\n{\n  // variables\n  double discriminant_result = 0;\n  double first_sum_term = 0;\n  double second_sum_term = 0;\n  double third_sum_term = 0;\n  double fourth_sum_term = 0;\n  double fifth_sum_term = 0;\n  Eigen::Vector2d intermediate_row;\n  Eigen::Vector2d intermediate_col;\n  Eigen::Matrix2d intermediate_matrix;\n\n  // compute the first summative term of the discriminant function\n  intermediate_matrix = -0.5 * inverse_covariance_matrix_;\n  intermediate_row = ( input_vector.transpose() * intermediate_matrix );\n  first_sum_term = intermediate_row.dot( input_vector );\n\n  // compute the second summative term of the discriminant function\n  second_sum_term =\n  ( inverse_covariance_matrix_ * mean_vector_ ).transpose().dot( input_vector );\n\n  // compute the third summative term of the discriminant function\n  intermediate_row = -0.5 * mean_vector_;\n  intermediate_row = intermediate_row.transpose() * inverse_covariance_matrix_;\n  third_sum_term = intermediate_row.dot( mean_vector_ );\n\n  // compute the fourth summative term of the discriminant function\n  fourth_sum_term = -0.5 * log( covariance_determinant_ );\n\n\n/*  // case: we are assuming case 1 assumptions\n  else\n  {\n    // compute the first term ( 1/s^2 * mean * x )\n    intermediate_row = ( 1.0 / variance ) * mean;\n    first_sum_term = intermediate_row.transpose().dot( input_vector );\n\n    // compute the second term\n    intermediate_row = ( -1.0 / ( 2 * variance ) ) * mean;\n    second_sum_term = intermediate_row.transpose().dot( mean );\n  }\n */\n\n  // compute the last summative term of the discriminant function\n  fifth_sum_term = log( prior_probability_ );\n\n\n  // sum the terms to get the discriminant result\n  discriminant_result = first_sum_term + second_sum_term + third_sum_term +\n                        fourth_sum_term + fifth_sum_term;\n\n  // return the discriminant result\n  return discriminant_result;\n}\n\n\nChernoff BayesClassifier::findChernoffBound(\n    const vector<BayesClassifier>& classifiers )\n{\n  // variables\n  Chernoff chernoff_bound;\n    chernoff_bound.bound = 1.0;\n    chernoff_bound.beta_star = 1.0;\n  double beta = 0;\n  double prior_product = 0.0;\n  double kappa_of_beta = 0;\n  double new_attempt;\n\n  // test many possibilities to find the ideal beta*\n  for( beta = 0.0; beta < 1.0; beta += EPSILON )\n  {\n    // compute the prior product\n    prior_product = pow( classifiers[0].prior_probability(), beta ) *\n                    pow( classifiers[1].prior_probability(), ( 1.0 - beta ) );\n\n    // kappa( beta* )\n    kappa_of_beta = kappaF( beta, classifiers );\n\n    // attempt to find a lower bound\n    new_attempt = prior_product * exp( -1.0 * kappa_of_beta );\n\n    // case: the new bound is a tighter one\n    if( new_attempt < chernoff_bound.bound )\n    {\n      // set the new bound and beta_star\n      chernoff_bound.bound = new_attempt;\n      chernoff_bound.beta_star = beta;\n    }\n  }\n\n  // return the Chernoff bound\n  return chernoff_bound;\n}\n\n\ndouble BayesClassifier::findBattacharyyaBound(\n    const vector<BayesClassifier>& classifiers )\n{\n  // variables\n  double battacharyya_bound = 1;\n  double kappa_of_beta = 0;\n  double root_prior_product = 0;\n  double root_covariance_det_product = 0;\n  Eigen::Vector2d mean_difference;\n  Eigen::Matrix2d covariance_sum;\n\n  // compute the square root term\n  root_prior_product = sqrt( classifiers[0].prior_probability() *\n                             classifiers[1].prior_probability() );\n\n  // compute kappa( 0.5 )\n  kappa_of_beta = kappaF( 0.5, classifiers );\n\n  // compute sqrt( P( w1 ) * P( w2 ) ) * e^( -kappa( 0.5 ) )\n  battacharyya_bound = root_prior_product * exp( -1.0 * kappa_of_beta );\n\n  // return the Battacharrya bound\n  return battacharyya_bound;\n}\n\n\ndouble BayesClassifier::kappaF( const double beta,\n                                const vector<BayesClassifier>& classifiers )\n{\n  // variables\n  double kappa_of_beta = 0;\n  double beta_complement = 1.0 - beta;\n  double beta_product_over_two = 0;\n  double root_prior_product = 0;\n  double root_covariance_det_product = 0;\n  double log_denominator = 0;\n  Eigen::Vector2d mean_difference;\n  Eigen::Vector2d intermediate_row;\n  Eigen::Matrix2d scaled_covariance_sum;\n\n  // compute (beta * beta^c) / 2\n  beta_product_over_two = ( beta * beta_complement ) / 2;\n\n  // compute the mean difference u2 - u1 (to be used later)\n  mean_difference = classifiers[0].mean_vector() - classifiers[1].mean_vector();\n\n  // compute the scaled covariance sum beta^c * E1 + beta * E2\n  // (to be used later)\n  scaled_covariance_sum =\n      ( beta_complement * classifiers[0].covariance_matrix() ) +\n      ( beta * classifiers[1].covariance_matrix() );\n\n  // compute the logarithm denominator (to be used later)\n  log_denominator = pow( classifiers[0].covariance_determinant(),\n                         beta_complement );\n  log_denominator *= pow( classifiers[1].covariance_determinant(),\n                          beta );\n\n  // compute the first term in the sum\n  intermediate_row = beta_product_over_two * mean_difference;\n  intermediate_row = intermediate_row.transpose() *\n                     scaled_covariance_sum.inverse();\n  kappa_of_beta = intermediate_row.transpose() * mean_difference;\n\n  // compute the second term in the sum\n  kappa_of_beta += 0.5 * log( scaled_covariance_sum.determinant() /\n                              log_denominator );  \n\n  // return the result\n  return kappa_of_beta;\n}\n\n\n", "meta": {"hexsha": "0498ba5ea5e36f7991b1511ba9a9c095b670b39d", "size": 16041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CS479/Project_2/bayes_classifier (2).cpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "CS479/Project_2/bayes_classifier (2).cpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "CS479/Project_2/bayes_classifier (2).cpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 27.1881355932, "max_line_length": 80, "alphanum_fraction": 0.622405087, "num_tokens": 4010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.6036668840409646}}
{"text": "//  Copyright 2020 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#include <iostream>\n#include <benchmark/benchmark.h>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/gmp.hpp>\n\n#include <boost/math/special_functions/prime.hpp>\n#include <boost/math/special_functions/pow.hpp>\n\n#include <gmpxx.h>\n\ntemplate <class Rational, class Integer = typename Rational::value_type>\nRational zeta18()\n{\n   Rational result = 1;\n\n   for (unsigned i = 0; i < 10; ++i)\n   {\n      result /= 1 - Rational(1, boost::math::pow<18>(Integer(boost::math::prime(i))));\n   }\n   return result;\n}\n\ntemplate <class Rational, class Integer = typename Rational::value_type>\nstatic void BM_zeta18(benchmark::State& state)\n{\n   for (auto _ : state)\n   {\n      benchmark::DoNotOptimize(zeta18<Rational, Integer>());\n   }\n}\n\n\nBENCHMARK_TEMPLATE(BM_zeta18, boost::multiprecision::cpp_rational);\nBENCHMARK_TEMPLATE(BM_zeta18, boost::multiprecision::mpq_rational);\nBENCHMARK_TEMPLATE(BM_zeta18, boost::multiprecision::number<boost::multiprecision::rational_adaptor<boost::multiprecision::gmp_int>>);\nBENCHMARK_TEMPLATE(BM_zeta18, mpq_class, mpz_class);\n\nBENCHMARK_MAIN();\n", "meta": {"hexsha": "66121779c69bf4c3caf4975d95d5cf88754807ed", "size": 1283, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/rational_zeta18_bench.cpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-27T21:15:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-27T21:15:52.000Z", "max_issues_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/rational_zeta18_bench.cpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/rational_zeta18_bench.cpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-24T08:49:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T08:49:34.000Z", "avg_line_length": 29.8372093023, "max_line_length": 134, "alphanum_fraction": 0.7443491816, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.6757646075489392, "lm_q1q2_score": 0.6036668763632214}}
{"text": "//\n// Created by Cephas Svosve on 17/6/2021.\n//\n\n#include \"dividend.h\"\n#include <iostream>\n#include <vector>\n#include <math.h>\n#include <iostream>\n#include <boost/random.hpp>\n\n\n\n//get dividend growth rate i.e average of the percentage change in dividend paid-out, dD(t)/D(t-1).\n\ndouble Div::getGrowthRate(int tickerID)\n{\n return growthRate[tickerID];\n}\n\n\n\n\n\n//get volatility i.e stdev of the percentage changes in dividend paid-out, dD(t)/D(t-1).\n\ndouble Div::getVolatility(int tickerID)\n{\n    return volatility[tickerID];\n}\n\n\n\n\n//we retrieve the autocorrelation of a particular asset by this function\n\ndouble Div::getAutoCorr(int tickerID)\n{\n    return autoCorr[tickerID];\n}\n\n\n\n\n\n//this is a setter for the average growth rate of an asset's growth rate\n\nvoid Div::setGrowthRate(double x)\n{\n growthRate.push_back(x);\n}\n\n\n\n\n\n//this is a setter for saving the volatility of an asset's dividend process\n\nvoid Div::setVolatility(double x)\n{\n volatility.push_back(x);\n}\n\n\n\n\n\n//this is a setter for saving the auto-correlation of an asset's dividend process\n\nvoid Div::setAutoCorr(double x)\n{\n autoCorr.push_back(x);\n}\n\n\n\n\n\n//work-in-progress-*the function is meant to retrieve the cross-sectional correlation from the market object \n\nvoid Div::setCrossCorr()\n{\n // std::cout <<  \"Div \" << crossCorrMat << std::endl;\n}\n\n\n\n\n\n//because our system depends on accuracy of the randomness of the random matrix,\n//we create a function that carefully generates a purely random matrix,\n//i.e. auto-correlation is 0 precise to the order of e-03 as well as the cross-sectional correlation\n\n\n\nMatrixXd Div::generateWhiteNoise(int numOfAssets, int numOfTicks)\n{\n\n    MatrixXd randoms(numOfAssets,numOfTicks);\n    VectorXd a;\n\n\n\n    //algorithm for generating random numbers that are shuffled continuously through seeding them on time\n\n    time_t now = time(0);\n    boost::random::mt19937 gen{static_cast<uint32_t>(now)};\n    boost::normal_distribution<> nd(0.0, clock.getDt());\n    boost::variate_generator<boost::mt19937&,\n    boost::normal_distribution<> > var_nor(gen, nd);\n\n\n\n    //we generate the matrix of random numbers\n\n    for(int rw=0; rw < numOfAssets; rw++)\n    {\n\n     \n        //we make sure the naturally occurring auto-correlation is sufficiently small by using a do-while loop\n        \n     do\n        {\n            //here we load each row with appropriate vector of random numbers\n            a = VectorXd(numOfTicks);\n      \n      \n            for(int i = 0; i < numOfTicks; ++i)\n            {\n                a(i) = var_nor();\n            }\n\n\n        }\n        while (abs(lateralcorrcoef(a)) > 0.001);\n\n        randoms.row(rw) = a;\n\n    }\n\n\n    //We then remove any cross-sectional correlation\n\n    return verticallyWhiten(randoms);\n}\n\n\n\n\n\n//this function removes cross-sectional correlation by multiplying a matrix\n// by the inverse of the lower cholesky decomposition of its correlation matrix\n\n\nMatrixXd Div::verticallyWhiten(MatrixXd mx)\n{\n    Matrix crossCorrs = crossCorr(mx);\n    LLT<MatrixXd> llt(crossCorrs);\n    MatrixXd L = llt.matrixL();\n    MatrixXd vWhite = L.inverse() * mx;\n\n\n    return vWhite;\n}\n\n\n\n\n\n//this function calculates the coefficient of determination -correlation- between two vectors\n//it requires the two vectors x and y, then computes the variables required for the formula\n//i.e. variables xx = x^2  ,xy = x*y  and yy = y^2\n\n\n\ndouble Div::corrcoef(VectorXd x, VectorXd y)\n{\n    if(x.size() == y.size()) {\n\n        int n = x.size();\n     \n\n        //variable xx represents x^2\n\n        double xx[n];\n        double xy[n];\n        double yy[n];\n\n\n\n        //sumx is the sum of random variables x\n\n        double sumx = x.sum();\n        double sumy = y.sum();\n\n\n\n        //sumxx is the sum of random variables x^2\n\n        double sumxx;\n        double sumxy;\n        double sumyy;\n\n\n\n        for (int i=0; i < x.size(); i++) \n        {\n            xx[i] = pow(x[i],2);\n            xy[i] = x[i] * y[i];\n            yy[i] = pow(y[i],2);\n         \n            sumxx = sumxx + xx[i];\n            sumxy = sumxy + xy[i];\n            sumyy = sumyy + yy[i];\n        }\n\n\n        //this is the formula used to calculate coefficient of determination, *see\n        //https://www.jstor.org/stable/2965177?seq=6#metadata_info_tab_contents\n        //Reed, William Gardner. \u201cThe Coefficient of Correlation.\u201d Publications of the American Statistical Association, \n        //vol. 15, no. 118, 1917, pp. 675\u2013684. JSTOR, www.jstor.org/stable/2965177. Accessed 20 June 2021.\n\n        double r = (n*sumxy - sumx*sumy)/sqrt((n*sumxx-pow(sumx,2))*(n*sumyy-pow(sumy,2)));\n\n        return r;\n    }\n    else\n    {\n     cout << \"found vectors of different size on computing correlation\";\n    }\n\n}\n\n\n\n\n\n//this function calculates the auto-correlation coefficient of a vector of random numbers\n//we use it to verify that the naturally occuring auto-correlation in the random numbers-\n//-we are using is sufficiently small i.e. of order e-03\n\n\n\ndouble Div::lateralcorrcoef(VectorXd a){\n\n\n    int n = a.size()-1;\n\n\n    double x[n];\n    double y[n];\n    double xx[n];\n    double xy[n];\n    double yy[n];\n\n    double sumx;\n    double sumy;\n    double sumxx;\n    double sumxy;\n    double sumyy;\n\n    for (int i=0; i < n; i++) {\n\n        x[i] = a[i+1];\n        y[i] = a[i];\n        xx[i] = pow(x[i],2);\n        xy[i] = x[i] * y[i];\n        yy[i] = pow(y[i],2);\n\n\n        sumx = sumx + x[i];\n        sumy = sumy + y[i];\n\n        sumxx = sumxx + xx[i];\n        sumxy = sumxy + xy[i];\n        sumyy = sumyy + yy[i];\n\n    }\n\n    double r = (n*sumxy - sumx*sumy)/sqrt((n*sumxx-pow(sumx,2))*(n*sumyy-pow(sumy,2)));\n    return r;\n\n}\n\n\n\n\n//this function calculates the correlation matrix from the random matrix \n\nMatrixXd Div::crossCorr(MatrixXd x){\n    int m = x.col(0).size();\n    int n = x.row(0).size();\n\n    MatrixXd corrMat(m,m);\n\n    for(int i = 0; i < m; i++){\n        for(int j = 0; j <= i; j++){\n\n            corrMat(i,j) = corrcoef( x.row(i),x.row(j));\n            corrMat(j,i) = corrMat(i,j);\n        }\n    }\n\n    return corrMat;\n}\n\n\n\n\n\n//work-in-progress\n\nMatrixXd Div::verticallyColor(MatrixXd x){}\n\nVectorXd Div::laterallyColor(VectorXd x){}\n\nVectorXd Div::standardize(VectorXd x){}\n\n\n\n\n\nMatrixXd Div::generateColoredNoise(int numOfAssets, int numOfTicks)\n{\n    MatrixXd X = generateWhiteNoise(numOfAssets, numOfTicks);\n    MatrixXd Y = verticallyWhiten(X);\n\n\n    //vector<double> lC = laterallyColor(Y(0:));\n}\n\n", "meta": {"hexsha": "ba15c3fa04ec1ab7b7bc95b184ddd9cf9bd7eadd", "size": 6412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dividend.cpp", "max_stars_repo_name": "maartenscholl/C-Multi_Asset_Artificial_Stock_Market", "max_stars_repo_head_hexsha": "6c2637b53b0b79cee1d13baf928c949f28625954", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T19:07:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T19:07:57.000Z", "max_issues_repo_path": "dividend.cpp", "max_issues_repo_name": "maartenscholl/C-Multi_Asset_Artificial_Stock_Market", "max_issues_repo_head_hexsha": "6c2637b53b0b79cee1d13baf928c949f28625954", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dividend.cpp", "max_forks_repo_name": "maartenscholl/C-Multi_Asset_Artificial_Stock_Market", "max_forks_repo_head_hexsha": "6c2637b53b0b79cee1d13baf928c949f28625954", "max_forks_repo_licenses": ["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.313253012, "max_line_length": 121, "alphanum_fraction": 0.6214909545, "num_tokens": 1686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.6036668723745372}}
{"text": "#include <boost/test/unit_test.hpp>\n#include \"functions/vector_field.hh\"\n#include \"functions/std_functions.hh\"\n#include \"functions/polynomial.hh\"\n\nBOOST_AUTO_TEST_CASE(vector_field_test) {\n  using namespace manifolds;\n  auto v1 = GetVectorField(1_c, 1_c);\n  auto f1 = v1(Sin()(x * y));\n  auto f1_check = Cos()(x * y) * (x + y);\n  BOOST_CHECK_EQUAL(f1(2, 1), f1_check(2, 1));\n  BOOST_CHECK_CLOSE(f1(4, 3), f1_check(4, 3), 1E-13);\n}\n", "meta": {"hexsha": "14e6a0c0625552c98542102b3cd6cb4ab5a42284", "size": 431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "functions/tests/test_vector_field.cpp", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/tests/test_vector_field.cpp", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/tests/test_vector_field.cpp", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["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.7857142857, "max_line_length": 53, "alphanum_fraction": 0.6983758701, "num_tokens": 142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.6036260527877011}}
{"text": "//\n// Copyright (c) 2019 INRIA\n//\n\n#include \"pinocchio/autodiff/casadi.hpp\"\n\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/frames.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/crba.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/algorithm/aba.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n\n#include \"pinocchio/parsers/sample-models.hpp\"\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_jacobian)\n{\n  typedef double Scalar;\n  typedef casadi::SX ADScalar;\n  \n  typedef pinocchio::ModelTpl<Scalar> Model;\n  typedef Model::Data Data;\n  \n  typedef pinocchio::ModelTpl<ADScalar> ADModel;\n  typedef ADModel::Data ADData;\n  \n  Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  Data data(model);\n  \n  typedef Model::ConfigVectorType ConfigVector;\n  typedef Model::TangentVectorType TangentVector;\n  ConfigVector q(model.nq);\n  q = pinocchio::randomConfiguration(model);\n  TangentVector v(TangentVector::Random(model.nv));\n  \n  typedef ADModel::ConfigVectorType ConfigVectorAD;\n  typedef ADModel::TangentVectorType TangentVectorAD;\n  ADModel ad_model = model.cast<ADScalar>();\n  ADData ad_data(ad_model);\n  \n  Model::Index joint_id = model.existJointName(\"rarm2\")?model.getJointId(\"rarm2\"):(Model::Index)(model.njoints-1);\n  Data::Matrix6x jacobian_local(6,model.nv), jacobian_world(6,model.nv);\n  jacobian_local.setZero(); jacobian_world.setZero();\n  \n  BOOST_CHECK(jacobian_local.isZero() && jacobian_world.isZero());\n  \n  pinocchio::computeJointJacobians(model,data,q);\n  pinocchio::getJointJacobian(model,data,joint_id,pinocchio::WORLD,jacobian_world);\n  pinocchio::getJointJacobian(model,data,joint_id,pinocchio::LOCAL,jacobian_local);\n  \n  casadi::SX cs_q = casadi::SX::sym(\"q\", model.nq);\n  ConfigVectorAD q_ad(model.nq);\n  for(Eigen::DenseIndex k = 0; k < model.nq; ++k)\n  {\n    q_ad[k] = cs_q(k);\n  }\n  std::cout << \"q =\\n \" << q_ad << std::endl;\n  \n  casadi::SX cs_v = casadi::SX::sym(\"v\", model.nv);\n  TangentVectorAD v_ad(model.nv);\n  for(Eigen::DenseIndex k = 0; k < model.nv; ++k)\n  {\n    v_ad[k] = cs_v(k);\n  }\n  std::cout << \"v =\\n \" << v_ad << std::endl;\n  \n  pinocchio::forwardKinematics(ad_model, ad_data, q_ad, v_ad);\n  typedef pinocchio::MotionTpl<ADScalar> MotionAD;\n  MotionAD & v_local = ad_data.v[(size_t)joint_id];\n  MotionAD v_world = ad_data.oMi[(size_t)joint_id].act(v_local);\n  \n  casadi::SX cs_v_local(6,1), cs_v_world(6,1);\n  for(Eigen::DenseIndex k = 0; k < 6; ++k)\n  {\n    cs_v_local(k) = v_local.toVector()[k];\n    cs_v_world(k) = v_world.toVector()[k];\n  }\n  std::cout << \"v_local = \" << cs_v_local << std::endl;\n  std::cout << \"v_world = \" << cs_v_world << std::endl;\n\n  casadi::Function eval_velocity_local(\"eval_velocity_local\",\n                                       casadi::SXVector {cs_q, cs_v},\n                                       casadi::SXVector {cs_v_local});\n  std::cout << \"eval_velocity_local = \" << eval_velocity_local << std::endl;\n\n  casadi::Function eval_velocity_world(\"eval_velocity_world\",\n                                       casadi::SXVector {cs_q, cs_v},\n                                       casadi::SXVector {cs_v_world});\n  std::cout << \"eval_velocity_world = \" << eval_velocity_world << std::endl;\n\n  casadi::SX dv_dv_local = jacobian(cs_v_local, cs_v);\n  casadi::Function eval_jacobian_local(\"eval_jacobian_local\",\n                                       casadi::SXVector {cs_q,cs_v},\n                                       casadi::SXVector {dv_dv_local});\n  std::cout << \"eval_jacobian_local = \" << eval_jacobian_local << std::endl;\n  \n  casadi::SX dv_dv_world = jacobian(cs_v_world, cs_v);\n  casadi::Function eval_jacobian_world(\"eval_jacobian_world\",\n                                       casadi::SXVector {cs_q,cs_v},\n                                       casadi::SXVector {dv_dv_world});\n  \n  std::vector<double> q_vec((size_t)model.nq);\n  Eigen::Map<ConfigVector>(q_vec.data(),model.nq,1) = q;\n  \n  std::vector<double> v_vec((size_t)model.nv);\n  Eigen::Map<TangentVector>(v_vec.data(),model.nv,1) = v;\n  \n  casadi::DMVector v_local_res = eval_velocity_local(casadi::DMVector {q_vec,v_vec});\n  casadi::DMVector J_local_res = eval_jacobian_local(casadi::DMVector {q_vec,v_vec});\n  std::cout << \"J_local_res:\" << J_local_res << std::endl;\n  \n  std::vector<double> v_local_vec(static_cast< std::vector<double> >(v_local_res[0]));\n  BOOST_CHECK((jacobian_local*v).isApprox(Eigen::Map<pinocchio::Motion::Vector6>(v_local_vec.data())));\n  \n  casadi::DMVector v_world_res = eval_velocity_world(casadi::DMVector {q_vec,v_vec});\n  casadi::DMVector J_world_res = eval_jacobian_world(casadi::DMVector {q_vec,v_vec});\n  \n  std::vector<double> v_world_vec(static_cast< std::vector<double> >(v_world_res[0]));\n  BOOST_CHECK((jacobian_world*v).isApprox(Eigen::Map<pinocchio::Motion::Vector6>(v_world_vec.data())));\n  \n  Data::Matrix6x J_local_mat(6,model.nv), J_world_mat(6,model.nv);\n  \n  std::vector<double> J_local_vec(static_cast< std::vector<double> >(J_local_res[0]));\n  J_local_mat = Eigen::Map<Data::Matrix6x>(J_local_vec.data(),6,model.nv);\n  BOOST_CHECK(jacobian_local.isApprox(J_local_mat));\n\n  std::vector<double> J_world_vec(static_cast< std::vector<double> >(J_world_res[0]));\n  J_world_mat = Eigen::Map<Data::Matrix6x>(J_world_vec.data(),6,model.nv);\n  BOOST_CHECK(jacobian_world.isApprox(J_world_mat));\n}\n  \n  BOOST_AUTO_TEST_CASE(test_fk)\n  {\n    typedef double Scalar;\n    typedef casadi::SX ADScalar;\n    \n    typedef pinocchio::ModelTpl<Scalar> Model;\n    typedef Model::Data Data;\n    \n    typedef pinocchio::ModelTpl<ADScalar> ADModel;\n    typedef ADModel::Data ADData;\n    \n    Model model;\n    pinocchio::buildModels::humanoidRandom(model);\n    model.lowerPositionLimit.head<3>().fill(-1.);\n    model.upperPositionLimit.head<3>().fill(1.);\n    Data data(model);\n    \n    typedef Model::ConfigVectorType ConfigVector;\n    typedef Model::TangentVectorType TangentVector;\n    ConfigVector q(model.nq);\n    q = pinocchio::randomConfiguration(model);\n    TangentVector v(TangentVector::Random(model.nv));\n    TangentVector a(TangentVector::Random(model.nv));\n    \n    pinocchio::forwardKinematics(model,data,q);\n    \n    typedef ADModel::ConfigVectorType ConfigVectorAD;\n    typedef ADModel::TangentVectorType TangentVectorAD;\n    ADModel ad_model = model.cast<ADScalar>();\n    ADData ad_data(ad_model);\n    \n    casadi::SX cs_q = casadi::SX::sym(\"q\", model.nq);\n    ConfigVectorAD q_ad(model.nq);\n    pinocchio::casadi::copy(cs_q,q_ad);\n    \n    casadi::SX cs_v = casadi::SX::sym(\"v\", model.nv);\n    TangentVectorAD v_ad(model.nv);\n    pinocchio::casadi::copy(cs_v,v_ad);\n    \n    casadi::SX cs_a = casadi::SX::sym(\"a\", model.nv);\n    TangentVectorAD a_ad(model.nv);\n    pinocchio::casadi::copy(cs_a,a_ad);\n    \n    pinocchio::forwardKinematics(ad_model, ad_data, q_ad, v_ad, a_ad);\n    pinocchio::updateGlobalPlacements(ad_model, ad_data);\n    pinocchio::updateFramePlacements(ad_model, ad_data);\n//    typedef pinocchio::MotionTpl<ADScalar> MotionAD;\n  }\n  \nBOOST_AUTO_TEST_CASE(test_rnea)\n{\n  typedef double Scalar;\n  typedef casadi::SX ADScalar;\n  \n  typedef pinocchio::ModelTpl<Scalar> Model;\n  typedef Model::Data Data;\n  \n  typedef pinocchio::ModelTpl<ADScalar> ADModel;\n  typedef ADModel::Data ADData;\n  \n  Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  Data data(model);\n  \n  typedef Model::ConfigVectorType ConfigVector;\n  typedef Model::TangentVectorType TangentVector;\n  ConfigVector q(model.nq);\n  q = pinocchio::randomConfiguration(model);\n  TangentVector v(TangentVector::Random(model.nv));\n  TangentVector a(TangentVector::Random(model.nv));\n  \n  typedef ADModel::ConfigVectorType ConfigVectorAD;\n  typedef ADModel::TangentVectorType TangentVectorAD;\n  ADModel ad_model = model.cast<ADScalar>();\n  ADData ad_data(ad_model);\n  \n  pinocchio::rnea(model,data,q,v,a);\n  \n  casadi::SX cs_q = casadi::SX::sym(\"q\", model.nq);\n  ConfigVectorAD q_ad(model.nq);\n  q_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_q).data(),model.nq,1);\n  \n  casadi::SX cs_v = casadi::SX::sym(\"v\", model.nv);\n  TangentVectorAD v_ad(model.nv);\n  v_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_v).data(),model.nv,1);\n  \n  casadi::SX cs_a = casadi::SX::sym(\"a\", model.nv);\n  TangentVectorAD a_ad(model.nv);\n  a_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_a).data(),model.nv,1);\n  \n  rnea(ad_model,ad_data,q_ad,v_ad,a_ad);\n  casadi::SX tau_ad(model.nv,1);\n  //    Eigen::Map<TangentVectorAD>(tau_ad->data(),model.nv,1)\n  //    = ad_data.tau;\n  for(Eigen::DenseIndex k = 0; k < model.nv; ++k)\n    tau_ad(k) = ad_data.tau[k];\n  casadi::Function eval_rnea(\"eval_rnea\",\n                             casadi::SXVector {cs_q, cs_v, cs_a},\n                             casadi::SXVector {tau_ad});\n  \n  std::vector<double> q_vec((size_t)model.nq);\n  Eigen::Map<ConfigVector>(q_vec.data(),model.nq,1) = q;\n  \n  std::vector<double> v_vec((size_t)model.nv);\n  Eigen::Map<TangentVector>(v_vec.data(),model.nv,1) = v;\n  \n  std::vector<double> a_vec((size_t)model.nv);\n  Eigen::Map<TangentVector>(a_vec.data(),model.nv,1) = a;\n  casadi::DM tau_res = eval_rnea(casadi::DMVector {q_vec,v_vec,a_vec})[0];\n  std::cout << \"tau_res = \" << tau_res << std::endl;\n  Data::TangentVectorType tau_vec = Eigen::Map<Data::TangentVectorType>(static_cast< std::vector<double> >(tau_res).data(),model.nv,1);\n  \n  BOOST_CHECK(data.tau.isApprox(tau_vec));\n}\n  \nBOOST_AUTO_TEST_CASE(test_crba)\n{\n  typedef double Scalar;\n  typedef casadi::SX ADScalar;\n  \n  typedef pinocchio::ModelTpl<Scalar> Model;\n  typedef Model::Data Data;\n  \n  typedef pinocchio::ModelTpl<ADScalar> ADModel;\n  typedef ADModel::Data ADData;\n  \n  Model model;\n  pinocchio::buildModels::humanoidRandom(model);\n  model.lowerPositionLimit.head<3>().fill(-1.);\n  model.upperPositionLimit.head<3>().fill(1.);\n  Data data(model);\n  \n  typedef Model::ConfigVectorType ConfigVector;\n  typedef Model::TangentVectorType TangentVector;\n  ConfigVector q(model.nq);\n  q = pinocchio::randomConfiguration(model);\n  TangentVector v(TangentVector::Random(model.nv));\n  TangentVector a(TangentVector::Random(model.nv));\n  \n  typedef ADModel::ConfigVectorType ConfigVectorAD;\n  typedef ADModel::TangentVectorType TangentVectorAD;\n  ADModel ad_model = model.cast<ADScalar>();\n  ADData ad_data(ad_model);\n  \n  pinocchio::crba(model,data,q);\n  data.M.triangularView<Eigen::StrictlyLower>()\n  = data.M.transpose().triangularView<Eigen::StrictlyLower>();\n  pinocchio::rnea(model,data,q,v,a);\n  \n  casadi::SX cs_q = casadi::SX::sym(\"q\", model.nq);\n  ConfigVectorAD q_ad(model.nq);\n  q_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_q).data(),model.nq,1);\n  \n  casadi::SX cs_v = casadi::SX::sym(\"v\", model.nv);\n  TangentVectorAD v_ad(model.nv);\n  v_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_v).data(),model.nv,1);\n  \n  casadi::SX cs_a = casadi::SX::sym(\"a\", model.nv);\n  TangentVectorAD a_ad(model.nv);\n  a_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_a).data(),model.nv,1);\n  \n  // RNEA\n  rnea(ad_model,ad_data,q_ad,v_ad,a_ad);\n  casadi::SX cs_tau(model.nv,1);\n  //    Eigen::Map<TangentVectorAD>(tau_ad->data(),model.nv,1)\n  //    = ad_data.tau;\n  for(Eigen::DenseIndex k = 0; k < model.nv; ++k)\n    cs_tau(k) = ad_data.tau[k];\n  casadi::Function eval_rnea(\"eval_rnea\",\n                             casadi::SXVector {cs_q, cs_v, cs_a},\n                             casadi::SXVector {cs_tau});\n  // CRBA\n  crba(ad_model,ad_data,q_ad);\n  ad_data.M.triangularView<Eigen::StrictlyLower>()\n  = ad_data.M.transpose().triangularView<Eigen::StrictlyLower>();\n  casadi::SX M_ad(model.nv,model.nv);\n  for(Eigen::DenseIndex j = 0; j < model.nv; ++j)\n  {\n    for(Eigen::DenseIndex i = 0; i < model.nv; ++i)\n    {\n      M_ad(i,j) = ad_data.M(i,j);\n    }\n  }\n  \n  std::vector<double> q_vec((size_t)model.nq);\n  Eigen::Map<ConfigVector>(q_vec.data(),model.nq,1) = q;\n  \n  std::vector<double> v_vec((size_t)model.nv);\n  Eigen::Map<TangentVector>(v_vec.data(),model.nv,1) = v;\n  \n  std::vector<double> a_vec((size_t)model.nv);\n  Eigen::Map<TangentVector>(a_vec.data(),model.nv,1) = a;\n  \n  casadi::Function eval_crba(\"eval_crba\",\n                             casadi::SXVector {cs_q},\n                             casadi::SXVector {M_ad});\n  casadi::DM M_res = eval_crba(casadi::DMVector {q_vec})[0];\n  Data::MatrixXs M_mat = Eigen::Map<Data::MatrixXs>(static_cast< std::vector<double> >(M_res).data(),\n                                                    model.nv,model.nv);\n  \n  BOOST_CHECK(data.M.isApprox(M_mat));\n  \n  casadi::SX dtau_da = jacobian(cs_tau,cs_a);\n  casadi::Function eval_dtau_da(\"eval_dtau_da\",\n                                casadi::SXVector {cs_q,cs_v,cs_a},\n                                casadi::SXVector {dtau_da});\n  casadi::DM dtau_da_res = eval_dtau_da(casadi::DMVector {q_vec, v_vec, a_vec})[0];\n  Data::MatrixXs dtau_da_mat = Eigen::Map<Data::MatrixXs>(static_cast< std::vector<double> >(dtau_da_res).data(),\n                                                          model.nv,model.nv);\n  BOOST_CHECK(data.M.isApprox(dtau_da_mat));\n}\n  \n  BOOST_AUTO_TEST_CASE(test_aba)\n  {\n    typedef double Scalar;\n    typedef casadi::SX ADScalar;\n    \n    typedef pinocchio::ModelTpl<Scalar> Model;\n    typedef Model::Data Data;\n    \n    typedef pinocchio::ModelTpl<ADScalar> ADModel;\n    typedef ADModel::Data ADData;\n    \n    Model model;\n    pinocchio::buildModels::humanoidRandom(model);\n    model.lowerPositionLimit.head<3>().fill(-1.);\n    model.upperPositionLimit.head<3>().fill(1.);\n    Data data(model);\n    \n    typedef Model::ConfigVectorType ConfigVector;\n    typedef Model::TangentVectorType TangentVector;\n    ConfigVector q(model.nq);\n    q = pinocchio::randomConfiguration(model);\n    TangentVector v(TangentVector::Random(model.nv));\n    TangentVector tau(TangentVector::Random(model.nv));\n    \n    typedef ADModel::ConfigVectorType ConfigVectorAD;\n    typedef ADModel::TangentVectorType TangentVectorAD;\n    ADModel ad_model = model.cast<ADScalar>();\n    ADData ad_data(ad_model);\n    \n    pinocchio::aba(model,data,q,v,tau);\n    \n    casadi::SX cs_q = casadi::SX::sym(\"q\", model.nq);\n    ConfigVectorAD q_ad(model.nq);\n    q_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_q).data(),model.nq,1);\n    \n    casadi::SX cs_v = casadi::SX::sym(\"v\", model.nv);\n    TangentVectorAD v_ad(model.nv);\n    v_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_v).data(),model.nv,1);\n    \n    casadi::SX cs_tau = casadi::SX::sym(\"tau\", model.nv);\n    TangentVectorAD tau_ad(model.nv);\n    tau_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_tau).data(),model.nv,1);\n    \n    // ABA\n    aba(ad_model,ad_data,q_ad,v_ad,tau_ad);\n    casadi::SX cs_ddq(model.nv,1);\n    for(Eigen::DenseIndex k = 0; k < model.nv; ++k)\n      cs_ddq(k) = ad_data.ddq[k];\n    casadi::Function eval_aba(\"eval_aba\",\n                              casadi::SXVector {cs_q, cs_v, cs_tau},\n                              casadi::SXVector {cs_ddq});\n\n    std::vector<double> q_vec((size_t)model.nq);\n    Eigen::Map<ConfigVector>(q_vec.data(),model.nq,1) = q;\n    \n    std::vector<double> v_vec((size_t)model.nv);\n    Eigen::Map<TangentVector>(v_vec.data(),model.nv,1) = v;\n    \n    std::vector<double> tau_vec((size_t)model.nv);\n    Eigen::Map<TangentVector>(tau_vec.data(),model.nv,1) = tau;\n    \n    casadi::DM ddq_res = eval_aba(casadi::DMVector {q_vec, v_vec, tau_vec})[0];\n    Data::TangentVectorType ddq_mat = Eigen::Map<Data::TangentVectorType>(static_cast< std::vector<double> >(ddq_res).data(),\n                                                            model.nv,1);\n\n    BOOST_CHECK(ddq_mat.isApprox(data.ddq));\n  }\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "95b43580ecbaa08e7cdd92b4904c1c151a002210", "size": 16139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/casadi-algo.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "unittest/casadi-algo.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "unittest/casadi-algo.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 38.0636792453, "max_line_length": 135, "alphanum_fraction": 0.6692484045, "num_tokens": 4749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6036260374746663}}
{"text": "#include <CGAL/config.h>\n#define CGAL_EIGEN3_ENABLED\n#if defined(BOOST_GCC) && (__GNUC__ <= 4) && (__GNUC_MINOR__ < 4)\n#include <iostream>\nint main()\n{\n  std::cerr << \"NOTICE: This test requires G++ >= 4.4, and will not be compiled.\" << std::endl;\n}\n#else\n#include <CGAL/Epick_d.h>\n#include <eigen3/Eigen/Core>\n#include <CGAL/Delaunay_triangulation.h>\n#include <CGAL/IO/Triangulation_off_ostream.h>\n#include <CGAL/point_generators_d.h>\n#include <CGAL/Timer.h>\n#include <CGAL/algorithm.h>\n#include <CGAL/Memory_sizer.h>\n\n#include <vector>\n#include <string>\n#include <fstream>\n#include <iostream>\n#include <cstdlib>\n#include <iterator>\n#include <algorithm>\n#include <unistd.h>\n#include <boost/algorithm/string.hpp>\n#define OUTPUT_STATS\n \n//function to read in data from csv file \nstd::vector<std::vector<double> > read_data(std::string file_name, int dim,\nstd::string delimeter = \" \")\n{\n\tstd::ifstream file(file_name);\n \n\tstd::vector<std::vector<double> > data_list;\n \n\tstd::string line = \"\";\n\t// Iterate through each line split the content using delimeter\n  // convert it to double\n\twhile (getline(file, line))\n\t{\n\t\tstd::vector<std::string> vec;\n\t\tboost::algorithm::split(vec, line, boost::is_any_of(delimeter));\n        std::vector<double> dd;\n        dd.reserve(dim);\n        for(std::vector<std::string>::iterator it = vec.begin(); \n        it != vec.end(); ++it) {\n          dd.push_back(std::stod(*it));\n        }\n\n\t\tdata_list.push_back(dd);\n\n\t}\n\t// Close the File\n\tfile.close();\n \n\treturn data_list;\n}\n\n\nvoid test(int dim, std::string file_name, std::string output_file)\n{\n    typedef CGAL::Epick_d<CGAL::Dynamic_dimension_tag> K;\n    typedef CGAL::Delaunay_triangulation<K> DT;\n    typedef typename DT::Point Point;\n    typedef CGAL::Random_points_in_cube_d<Point> Random_points_iterator;\n    CGAL::Timer timer;  // timer\n\n    //TODO: Change the path_prefix before running the function!\n    std::string path_prefix = \"/Users/angelynaye/desktop/research/data/\";\n    std::string full_file_name = path_prefix + file_name;\n\n    std::vector<Point> points;\n\n    // CSVReader reader(full_file_name);\n    std::cout <<\"          Reading file: \" << file_name << std::endl;\n    // Get the data from CSV File\n    std::vector<std::vector<double> > data_vec = read_data(full_file_name, dim);\n\n\n\n    std::size_t N  = data_vec.size();\n\n    std::cout << N <<std::endl;\n    int i = 0;\n\n    // construct points\n    for(int i = 0; i < data_vec.size(); i++) {\n      std::vector<double> cur = data_vec.at(i);\n      double temp[cur.size()];\n      std::copy(cur.begin(), cur.end(), temp);\n      Point p(&temp[0], &temp[cur.size()]);\n      points.push_back(p);\n    }\n\n    std::size_t mem_before = CGAL::Memory_sizer().virtual_size();\n    timer.reset();\n    timer.start();\n\n    // Build the Regular Triangulation\n    DT dt(dim);\n\n\n    // std::istream_iterator<Point> begin (iFile), end;\n    dt.insert(points.begin(), points.end());\n\n  \n    std::cout << \"Delaunay triangulation of \" << N <<\n    \" points in dim \" << dim << \":\" << std::endl;\n\n    std::size_t mem = CGAL::Memory_sizer().virtual_size() - mem_before;\n    double timing = timer.time();\n    std::cout << \"  Triangles Complete in \" << timing << \" seconds.\" << std::endl;\n    std::cout << \"  Memory consumption: \" << (mem >> 10) << \" KB.\\n\";\n    std::size_t nbfc= dt.number_of_finite_full_cells();\n    std::size_t nbc= dt.number_of_full_cells();\n    std::cout << \"There are \" << dt.number_of_vertices() << \" vertices, \" \n            << nbfc << \" finite simplices and \" \n            << (nbc-nbfc) << \" convex hull Facets.\\n\"\n            << std::endl;\n\n    #ifdef OUTPUT_STATS\n    path_prefix += \"stats/\";\n    std::string output_name = path_prefix + output_file;\n    std::ofstream csv_file(output_name);\n    csv_file \n        << \"Dimension: \" << dim << \"; \"\n        << \"Numbers of Pts: \" << N << \"; \"\n        << \"Completion Time: \"<< timing << \" seconds; \"\n        << \"Used Memory: \" << mem << \" KB; \"\n        << \"Numbers of Facets: \"<< nbfc << \"\\n \"\n        << std::flush;\n    #endif\n\n}\n\nint main()\n{\n  int dims[13] = { \n    // 2, 8, \n    2, 10, 25, 25, 25, 14, 22, 22, 24, 54, 54, 60, 7}; \n  std::string names[13] = {\n      // \"fourclass.csv\",\n      // \"diabetes.csv\",\n      \"halfmoon.csv\",\n      \"cancer.csv\",\n      \"mnist17_test.csv\",\n      \"f-mnist06_test.csv\",\n      \"f-mnist35.csv\",\n      \"australian.csv\",\n      \"svmguide3.csv\",\n      \"ijcnn1.csv\",\n      \"german.csv\",\n      \"covtype_bi.csv\",\n      \"cov_dat.csv\",\n      \"splice.csv\",\n      \"abalone.csv\",\n  };\n  std::string output[13] = {\n      // \"fourclass_stat.csv\",\n      // \"diabetes_stat.csv\",\n      \"halfmoon_stat.csv\",\n      \"breast_cancer_stat.csv\",\n      \"mnist17_test_stat.csv\",\n      \"f-mnist06_test_stat.csv\",\n      \"f-mnist35_stat.csv\",\n      \"australian_stat.csv\",\n      \"svmguide3_stat.csv\",\n      \"ijcnn1_stat.csv\",\n      \"german_stat.csv\",\n      \"covtype_bi_stat.csv\",\n      \"cov_dat_stat.csv\",\n      \"splice_stat.csv\",\n      \"abalone_stat.csv\"\n  };\n\n  for(int i = 0; i < sizeof(names)/sizeof(names[0]); i++) {\n    test(dims[i], names[i], output[i]);\n  }\n\n  return 0;\n}\n#endif", "meta": {"hexsha": "b414c4edcb5973f429b3459672741a8786159659", "size": 5088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "archived/cpp/test_research.cpp", "max_stars_repo_name": "wagner-group/geoadex", "max_stars_repo_head_hexsha": "693856dc4537937fa09ec7a22e175f8243483b44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-01T18:18:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T05:58:57.000Z", "max_issues_repo_path": "archived/cpp/test_research.cpp", "max_issues_repo_name": "wagner-group/geoadex", "max_issues_repo_head_hexsha": "693856dc4537937fa09ec7a22e175f8243483b44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "archived/cpp/test_research.cpp", "max_forks_repo_name": "wagner-group/geoadex", "max_forks_repo_head_hexsha": "693856dc4537937fa09ec7a22e175f8243483b44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.652173913, "max_line_length": 95, "alphanum_fraction": 0.6047562893, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.6036260352413914}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include \"../include/utils.h\"\n\nint main() {\n  Eigen::Array<double, 1, -1> a(10);\n  double b[] = {0., 1., 2., 3., 4., 5., 6., 7., 8., 9.};\n  a << 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.;\n  std::cout << \"Array []logsumexp(range(10)) = \" << logsumexp(b, 10) << \"\\n\";\n  std::cout << \"Eigen - logsumexp(range(10)) = \" << logsumexp(a, 10) << \"\\n\";\n  Eigen::ArrayXd a_copy = a;\n  normalize(a_copy);\n  std::cout << \"normalize(a) = \\n\" << a_copy << \"\\n\";\n\n  Eigen::ArrayXXd A(3, 3);\n  A << 1, 2, 3,\n       4, 5, 6,\n       7, 8, 9;\n  Eigen::ArrayXXd A_log = A;\n  Eigen::ArrayXXd A_ = A;\n  normalize(A_);\n  std::cout << \"normalize(A(3x3)) = \\n\";\n  std::cout << A_ << \"\\n\";\n  log_normalize(A_log);\n  std::cout << \"log_normalize(A(3x3)) = \\n\";\n  std::cout << A_log << \"\\n\";\n\n  double a_scaler = 2.0, b_scaler = 4.0;\n  std::cout << \"logaddexp(\" << a_scaler << \n    \" + \" << b_scaler << \") = \"\n    << logaddexp(a_scaler, b_scaler) << \"\\n\";\n\n  Eigen::ArrayXd means(2);\n  means << 0, 5;\n  Eigen::ArrayXd covar = Eigen::ArrayXd::Ones(2);\n  std::vector<double> X(b, b + 10);\n  Eigen::ArrayXXd logprob(X.size(), 2);\n  log_univariate_normal_density(X, means, covar, logprob);\n  std::cout << \"log_univariate_normal_density(X) = \\n\"\n    << logprob << \"\\n\";\n  \n  std::cout << \"==================================Forward - backward Test\\n\";\n  size_t n_observations = 10;\n  size_t n_components = 2;\n  Eigen::ArrayXd log_start(2);\n  Eigen::ArrayXXd log_trans(2, 2);\n  log_start << std::log(0.5), std::log(0.5);\n  log_trans << std::log(0.5), std::log(0.5),\n               std::log(0.5), std::log(0.5);\n  Eigen::ArrayXXd alpha(10, 2);\n  forward(n_observations, n_components, log_start,\n          log_trans, logprob, alpha);\n  std::cout << \"forward -> alpha: \\n\"\n            << alpha << \"\\n\";\n  Eigen::ArrayXXd beta(10, 2);\n  backward(n_observations, n_components,\n           log_trans, logprob, beta);\n  std::cout << \"backward -> beta: \\n\"\n            << beta << \"\\n\";\n\n  std::cout << \"================================Compute log xi\\n\";\n  Eigen::ArrayXXd log_xi_sum(2, 2);\n  log_xi_sum = -INFINITY * Eigen::ArrayXXd::Ones(2, 2);\n  compute_log_xi_sum(n_observations, n_components, alpha,\n                     log_trans, beta, logprob, log_xi_sum);\n  std::cout << \"Compute_log_xi_sum: \\n\"\n    << log_xi_sum << \"\\n\";\n\n  return 0;\n}", "meta": {"hexsha": "5d0270ec2d18cb8a1cdee172a469f50e33e1a01a", "size": 2340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_test/utils_test.cpp", "max_stars_repo_name": "zixuanweeei/FAT", "max_stars_repo_head_hexsha": "a4100dc152fba2e2d1dbb46cfdd3ab0ee4264830", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unit_test/utils_test.cpp", "max_issues_repo_name": "zixuanweeei/FAT", "max_issues_repo_head_hexsha": "a4100dc152fba2e2d1dbb46cfdd3ab0ee4264830", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unit_test/utils_test.cpp", "max_forks_repo_name": "zixuanweeei/FAT", "max_forks_repo_head_hexsha": "a4100dc152fba2e2d1dbb46cfdd3ab0ee4264830", "max_forks_repo_licenses": ["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.4285714286, "max_line_length": 77, "alphanum_fraction": 0.5487179487, "num_tokens": 836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.6036260297020959}}
{"text": "/*=============================================================================\n  PHAS0100ASSIGNMENT1: PHAS0100 Assignment 1 Game of Life Simulation.\n  Copyright (c) University College London (UCL). All rights reserved.\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.\n  See LICENSE.txt in the top level directory for details.\n=============================================================================*/\n\n#include <nbsimParticle.h>\n#include <nbsimMassiveParticle.h>\n#include <nbsimSolarSystemData.ipp>\n#include <iostream>\n#include <Eigen/Dense>\n#include <chrono>\n\n// Example, header-only library, included in project for simplicity's sake.\n\n\n/**\n * \\brief Demo file to check that includes and library linkage is correct.\n */\n\nstatic void show_usage(std::string name)\n{\n    std::cerr << \"Usage: \" << name\n    << \"Options:\\n\"\n    << \"\\tOption: (Solar System Simulator):\\tUsers should input .1) step-size(unit: year) .2) length of time(unit: year)\\n\"\n    << \"Options:\\n\"\n    << \"\\t-h,--help\\t\\t\\tShow this help message.\\n\"\n    << std::endl;\n}\n\nint main(int argc, char** argv)\n{   \n    // -h and --help:\n    if (argc == 2){\n        if((argv[1] == \"-h\") or (argv[1] == \"--help\")){\n            show_usage(argv[0]);\n            return 0;\n        }\n        else{\n            show_usage(argv[0]);\n            return 0;\n        }\n    }\n    \n    // Option: Solar System:\n    if (argc == 3){\n\n        double step_size = std::stod(argv[1]);\n        double totalTime = std::stod(argv[2]);\n        \n        int NPLANETS = 9;\n\n        std::string name[NPLANETS];\n        Eigen::Vector3d position;\n        Eigen::Vector3d velocity;\n        double mu;\n\n        std::shared_ptr<nbsim::MassiveParticle> planet[NPLANETS];\n\n        // Split the planet:\n        for (int i=0;i<NPLANETS;i++){\n            name[i] =  nbsim::solarSystemData.at(i).name; \n            position = nbsim::solarSystemData.at(i).position;\n            velocity = nbsim::solarSystemData.at(i).velocity;\n            mu =  nbsim::solarSystemData.at(i).mu;\n\n            std::shared_ptr<nbsim::MassiveParticle> particle(new nbsim::MassiveParticle(position,velocity,mu));\n            planet[i] = particle;\n        }\n\n        // Add the attractor:\n        for(int i=0;i<NPLANETS;i++){\n            for(int j=0;j<NPLANETS;j++){\n                if(i != j){\n                    planet[i]->addAttractor(planet[j]);\n                }\n            }\n        }\n\n        // At the begining: calculate the Energy\n        planet[0]->addAttractor(planet[0]); // add itself\n    \n        planet[0]->calculateEtotal();\n        std::cout<<\"Beginning:\"<<\"\\n\";\n        std::cout<<\"The kinetic energy of system is: \"<<planet[0]->getEkinetic()<<\"\\n\";\n        std::cout<<\"The potential Energy of system is: \"<<planet[0]->getEpotential()<<\"\\n\";\n        std::cout<<\"The Total Energy of system is: \"<<planet[0]->getEtotal()<<\"\\n\";\n        planet[0]->removeAttractor(planet[0]); // remove itself\n\n\n        // // Benchmark the time of the solar system: Begin\n        std::clock_t c_start = std::clock();\n        auto t_start = std::chrono::high_resolution_clock::now();\n\n\n        // Parallel:\n        omp_set_num_threads (8);\n\n        #pragma omp parallel\n        // Outer time:\n        for (double t = 0;t<totalTime;t+=step_size){\n            \n            // Loop 1: Acceleration:\n            #pragma omp for\n            for (int i=0;i<NPLANETS;i++){\n                planet[i]->calculateAcceleration();\n            }\n            // Loop 2: intergateTimestep:\n            #pragma omp for\n            for (int i=0;i<NPLANETS;i++){\n                planet[i]->integrateTimestep(step_size);\n\n            }\n        }\n\n        // Benchmark the time of the solar system: End\n        std::clock_t c_end = std::clock();\n        auto t_end = std::chrono::high_resolution_clock::now();\n\n\n        // Summarising the position:\n        for(int i=0;i<NPLANETS;i++){\n            std::cout<<name[i] <<\":\\n Original Position: \\n\"<<nbsim::solarSystemData.at(i).position<<\"\\n\";\n            std::cout<<\" Current Position: \\n\"<<planet[i]->getPosition()<<\"\\n\\n\";\n        }\n\n        // Calculate the System Energy:\n        planet[0]->addAttractor(planet[0]); // add itself\n        \n        planet[0]->calculateEtotal();\n        std::cout<<\"End:\"<<\"\\n\";\n        std::cout<<\"The Kinetic Energy of system is: \"<<planet[0]->getEkinetic()<<\"\\n\";\n        std::cout<<\"The Potential Energy of system is: \"<<planet[0]->getEpotential()<<\"\\n\";\n        std::cout<<\"The Total Energy of system is: \"<<planet[0]->getEtotal()<<\"\\n\";\n        \n        planet[0]->removeAttractor(planet[0]); // remove itself\n\n        // Benchmark and output the time:\n        std::cout<<\"\\nThe run time is: \"\n                 <<1000.0*(c_end - c_start)/CLOCKS_PER_SEC<<\" ms\\n\"\n                 <<\"Wall clock time passed: \"\n                 <<std::chrono::duration<double, std::milli>(t_end-t_start).count()<<\" ms\\n\";\n\n\n        return 1;\n    }\n\n    // Default Option:\n    else{\n        show_usage(argv[0]);\n        return 0;\n    }\n}", "meta": {"hexsha": "0f65891ee83468977cc80904eb2ae1014d1be5b0", "size": 5089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/CommandLineApps/solarSystemSimulator.cpp", "max_stars_repo_name": "NottingDuck/PHAS0100Assignment2", "max_stars_repo_head_hexsha": "d1b191f3133fe084c856ea15cefe1f1e536de50c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/CommandLineApps/solarSystemSimulator.cpp", "max_issues_repo_name": "NottingDuck/PHAS0100Assignment2", "max_issues_repo_head_hexsha": "d1b191f3133fe084c856ea15cefe1f1e536de50c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/CommandLineApps/solarSystemSimulator.cpp", "max_forks_repo_name": "NottingDuck/PHAS0100Assignment2", "max_forks_repo_head_hexsha": "d1b191f3133fe084c856ea15cefe1f1e536de50c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6217948718, "max_line_length": 123, "alphanum_fraction": 0.538612694, "num_tokens": 1262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6035851130979845}}
{"text": "#include <cmath>    // for std::sqrt\n#include <cstdlib>  // for std::rand\n#include <thread>   // for std::thread\n#include <atomic>   // for std::atomic\n#include <string>\n#include <algorithm>\n#include <vector>\t// for std:vector\n#include <iostream>\n#include <chrono>   // for time calculations\n// thread libraries to be tested\n#include \"CTPL/ctpl.h\" // for testing CPTL thread pool\n#ifndef TIME_UTC\n#define TIME_UTC TIME_UTC_\n#endif\n#include \"threadpool/boost/threadpool.hpp\" // for testing old boost thread pool (by Philippe Henkel)\n#include \"ThreadPool/ThreadPool.h\" // for testing thread pool using Jakob Progsch's thread pool\n#if BOOST_VERSION > 105600\n#include <boost/thread/executors/basic_thread_pool.hpp> // for testing new boost thread pool. available from ver 1.56 and up\n#endif\n#include \"thread_pool.hpp\" // for asio based pool\n\n// the work being done is calculating if a number is prime or no and accumulating the result\nbool IsPrime(unsigned long n)\n{\n    // special handle for 0,1,2\n    if (n < 3)\n    {\n\tif (n == 2) return true;\n    }\n\n    // no need to check above sqrt(n)\n    const auto N = std::ceil(std::sqrt(n) + 1);\n\n    for (auto i = 2; i < N; ++i)\n    {\n        if (n%i == 0)\n        {\n\t\t\treturn false;\n        }\n    }\n\n\treturn true;\n}\n\n// check if a number is prime and accumulate into a counter\nvoid CountIfPrime(unsigned long n, unsigned long& count)\n{\n\tif (IsPrime(n)) ++count;\n}\n\n// check if a number is prime and accumulate into a counter - thred safe with thread id\nvoid CountIfPrimeCTPL(int id, unsigned long n, std::atomic<unsigned long>& count)\n{\n\tif (IsPrime(n)) ++count;\n}\n\n// check if a number is prime and accumulate into a counter - thred safe\nvoid CountIfPrimeBoost(unsigned long n, std::atomic<unsigned long>& count)\n{\n\tif (IsPrime(n)) ++count;\n}\n\nunsigned long count_primes_asio(const std::vector<unsigned long>& random_inputs, unsigned int NUMBER_OF_PROCS)\n{\n    std::atomic<unsigned long> number_of_primes(0);\n\t{\n\t\tasio_thread_pool pool(NUMBER_OF_PROCS);\n\n\t\t// loop over input to accumulate how many primes are there\n    \tstd::for_each(random_inputs.begin(), random_inputs.end(), \n            [&](unsigned long n) \n    \t{\n    \t\twhile (!pool.run_task(boost::bind(CountIfPrimeBoost, n, std::ref(number_of_primes)))) {}\n    \t});\n\n        // as pool go out of scope, it will wait for all threads to finish\n\t}\n\n    return number_of_primes;\n}\n\n#if BOOST_VERSION > 105600\n// using boost's experimental thread pool\nunsigned long count_primes_boost(const std::vector<unsigned long>& random_inputs, unsigned int NUMBER_OF_PROCS)\n{\n    // here the main thread also does work\n\tboost::basic_thread_pool tp(NUMBER_OF_PROCS-1);\n    std::atomic<unsigned long> number_of_primes(0);\n\n\t// loop over input to accumulate how many primes are there\n    std::for_each(random_inputs.begin(), random_inputs.end(), \n            [&](unsigned long n) \n    {\n    \ttp.submit(boost::bind(CountIfPrimeBoost, n, std::ref(number_of_primes)));\n    });\n\n    // wait for all threads to finish and do work at the same time\n\twhile(tp.try_executing_one()) {}\n\n    tp.close();\n\n    return number_of_primes;\n}\n#endif\n\n// using Jakob Progsch's thread pool\nunsigned long count_primes_JP(const std::vector<unsigned long>& random_inputs, unsigned int NUMBER_OF_PROCS)\n{\n    std::atomic<unsigned long> number_of_primes(0);\n    {\n        ThreadPool pool(NUMBER_OF_PROCS);\n\n\t    // loop over input to accumulate how many primes are there\n        std::for_each(random_inputs.begin(), random_inputs.end(), \n                [&](unsigned long n) \n        {\n            pool.enqueue(CountIfPrimeBoost, n, std::ref(number_of_primes));\n        });\n\n        // as pool go out of scope, it will wait for all threads to finish\n    }\n\n    return number_of_primes;\n}\n\n// using old boost thread pool\nunsigned long count_primes_boost_old(const std::vector<unsigned long>& random_inputs, unsigned int NUMBER_OF_PROCS)\n{\n    std::atomic<unsigned long> number_of_primes(0);\n    {\n        boost::threadpool::pool tp(NUMBER_OF_PROCS);\n\n\t    // loop over input to accumulate how many primes are there\n        std::for_each(random_inputs.begin(), random_inputs.end(), \n                [&](unsigned long n) \n        {\n            boost::threadpool::schedule(tp, boost::bind(CountIfPrimeBoost, n , std::ref(number_of_primes)));\n        });\n\n        // as pool go out of scope, it will wait for all threads to finish\n    }\n\n    return number_of_primes;\n}\n\n// using CPTL thread pool\nunsigned long count_primes_ctpl(const std::vector<unsigned long>& random_inputs, unsigned int NUMBER_OF_PROCS)\n{\n    ctpl::thread_pool pool(NUMBER_OF_PROCS);\n    std::atomic<unsigned long> number_of_primes(0);\n\n\t// loop over input to accumulate how many primes are there\n    std::for_each(random_inputs.begin(), random_inputs.end(), \n            [&](unsigned long n) \n    {\n        pool.push(CountIfPrimeCTPL, n, std::ref(number_of_primes));\n    });\n\n    // wait for all threads to finish\n    pool.stop(true);\n\n    return number_of_primes;\n}\n\n// single threaded calculation of primes\nunsigned long count_primes(const std::vector<unsigned long>& random_inputs)\n{\n    unsigned long number_of_primes = 0;\n\t// loop over input to accumulate how many primes are there\n    std::for_each(random_inputs.begin(), random_inputs.end(), \n            [&](unsigned long n) \n\t\t\t{ \n\t\t\t\tCountIfPrime(n, number_of_primes);\n\t\t\t});\n\n    return number_of_primes;\n}\n\n\nint main(int argc, char** argv)\n{\n    if (argc != 3)\n    {\n        std::cout << \"Usage: \" << argv[0] << \" <size of input> <number of procs>\" << std::endl;\n        return 1;\n    }\n\n\tconst auto MAX_PROCS = std::thread::hardware_concurrency();\n    const auto INPUT_SIZE = std::stol(argv[1]);\n    const auto NUMBER_OF_PROC = std::stol(argv[2]);\n\n    if (MAX_PROCS < NUMBER_OF_PROC)\n    {\n        std::cout << \"maximum \" << MAX_PROCS  << \" concurrent threads are supported. use less threads\" << std::endl;\n        return 1;\n    }\n\n    std::vector<unsigned long> random_inputs;\n\n    for (auto i = 0; i < INPUT_SIZE; ++i)\n    {\n        random_inputs.push_back(std::rand());\n    }\n    \n    std::chrono::time_point<std::chrono::system_clock> start, end;\n\n    start = std::chrono::system_clock::now();\n    auto number_of_primes = count_primes(random_inputs);\n    end = std::chrono::system_clock::now();\n    std::cout << \"count_primes:\" << number_of_primes << \" prime numbers were found. computation took \" << \n        std::chrono::duration_cast<std::chrono::nanoseconds> (end - start).count()/INPUT_SIZE  << \" nanosec per iteration\" << std::endl;\n\n    start = std::chrono::system_clock::now();\n    number_of_primes = count_primes_ctpl(random_inputs, NUMBER_OF_PROC);\n    end = std::chrono::system_clock::now();\n    std::cout << \"count_primes_ctpl:\" << number_of_primes << \" prime numbers were found. computation took \" << \n        std::chrono::duration_cast<std::chrono::nanoseconds> (end - start).count()/INPUT_SIZE  << \" nanosec per iteration\" << std::endl;\n\n    start = std::chrono::system_clock::now();\n    number_of_primes = count_primes_boost_old(random_inputs, NUMBER_OF_PROC);\n    end = std::chrono::system_clock::now();\n    std::cout << \"count_primes_boost_old:\" << number_of_primes << \" prime numbers were found. computation took \" << \n        std::chrono::duration_cast<std::chrono::nanoseconds> (end - start).count()/INPUT_SIZE  << \" nanosec per iteration\" << std::endl;\n\n    start = std::chrono::system_clock::now();\n    number_of_primes = count_primes_JP(random_inputs, NUMBER_OF_PROC);\n    end = std::chrono::system_clock::now();\n    std::cout << \"count_primes_JP:\" << number_of_primes << \" prime numbers were found. computation took \" << \n        std::chrono::duration_cast<std::chrono::nanoseconds> (end - start).count()/INPUT_SIZE  << \" nanosec per iteration\" << std::endl;\n\n#if BOOST_VERSION > 105600\n    start = std::chrono::system_clock::now();\n    number_of_primes = count_primes_boost(random_inputs, NUMBER_OF_PROC);\n    end = std::chrono::system_clock::now();\n    std::cout << \"count_primes_boost:\" << number_of_primes << \" prime numbers were found. computation took \" << \n        std::chrono::duration_cast<std::chrono::nanoseconds> (end - start).count()/INPUT_SIZE  << \" nanosec per iteration\" << std::endl;\n#else\n    std::cout << \"count_primes_boost cannot be tested. boost version is: \" << BOOST_VERSION << std::endl;\n#endif\n\n    start = std::chrono::system_clock::now();\n    number_of_primes = count_primes_asio(random_inputs, NUMBER_OF_PROC);\n    end = std::chrono::system_clock::now();\n    std::cout << \"count_primes_asio:\" << number_of_primes << \" prime numbers were found. computation took \" << \n        std::chrono::duration_cast<std::chrono::nanoseconds> (end - start).count()/INPUT_SIZE  << \" nanosec per iteration\" << std::endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "017f024bbc9194c8b8dc8c0b6fba4475ef7359f9", "size": 8768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark_pool.cpp", "max_stars_repo_name": "yuvalif/threadpool_benchmark", "max_stars_repo_head_hexsha": "2f3903be12f19dc1ed8c6f22cc574876624a1d27", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-26T02:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T02:00:02.000Z", "max_issues_repo_path": "benchmark_pool.cpp", "max_issues_repo_name": "yuvalif/threadpool_benchmark", "max_issues_repo_head_hexsha": "2f3903be12f19dc1ed8c6f22cc574876624a1d27", "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": "benchmark_pool.cpp", "max_forks_repo_name": "yuvalif/threadpool_benchmark", "max_forks_repo_head_hexsha": "2f3903be12f19dc1ed8c6f22cc574876624a1d27", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T02:00:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T02:00:04.000Z", "avg_line_length": 35.072, "max_line_length": 136, "alphanum_fraction": 0.6749543796, "num_tokens": 2232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189134878876, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6035851082851934}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <cmath>\n#include <complex>\n\ntemplate <typename T, typename U>\ninline bool about(T x, U y)\n{\n    return std::abs(x - y) < 0.001;\n}\n\ntemplate <typename T, typename U>\nvoid test(T x, U y)\n{\n    using namespace mtl::sfunctor; using mtl::sfunctor::abs; using mtl::sfunctor::negate;\n    using mtl::sfunctor::plus;\n    using std::cout;\n\n    typedef compose<negate<typename abs<T>::result_type>, abs<T> > nabs;\n    cout << \"-abs(\" << x << \") = \" << nabs::apply(x) << \"\\n\";\n    MTL_THROW_IF(!about(nabs::apply(x), -std::abs(x)), mtl::runtime_error(\"Wrong result for -abs(x)\"));\n\n    typedef compose<square<typename nabs::result_type>, nabs> snabs;\n    cout << \"(-abs(\" << x << \"))^2 = \" << snabs::apply(x) << \"\\n\";\n    cout << \"-std::abs(x) * -std::abs(x) = \" << -std::abs(x) * -std::abs(x) << \"\\n\";\n    MTL_THROW_IF(!about(snabs::apply(x), -std::abs(x) * -std::abs(x)), mtl::runtime_error(\"Wrong result for (-abs(x))^2\"));\n    \n    typedef compose_first<plus<typename abs<T>::result_type, U>, abs<T> > plus_abs;\n    cout << \"abs(\" << x << \") + \" << y << \" = \" << plus_abs::apply(x, y) << \"\\n\";\n    MTL_THROW_IF(!about(plus_abs::apply(x, y), std::abs(x) + y), mtl::runtime_error(\"Wrong result for abs(x) + y\"));\n    \n    typedef compose_second<plus<T, typename abs<U>::result_type>, abs<U> > x_plus_abs_y;\n    cout << x << \" + \" << \"abs(\" << y << \") = \" << x_plus_abs_y::apply(x, y) << \"\\n\";\n    MTL_THROW_IF(!about(x_plus_abs_y::apply(x, y), x + std::abs(y)), mtl::runtime_error(\"Wrong result for x + abs(y)\"));\n\n    typedef compose_both<plus<T, typename abs<U>::result_type>, negate<T>, abs<U> > minus_x_plus_abs_y;\n    cout << \"-\" << x << \" + \" << \"abs(\" << y << \") = \" << minus_x_plus_abs_y::apply(x, y) << \"\\n\";\n    MTL_THROW_IF(!about(minus_x_plus_abs_y::apply(x, y), -x + std::abs(y)), mtl::runtime_error(\"Wrong result for -x + abs(y)\"));\n    \n    cout << \"l_2(\" << x << \", \" << 2.0f*x << \") = \" << l_2_2D<T>::apply(x, 2.0f*x)  << \"\\n\";\n    MTL_THROW_IF(!about(l_2_2D<T>::apply(x, 2.0f*x), std::sqrt(std::abs(5.0f*x*x))), mtl::runtime_error(\"Wrong result for l_2_2D(x, 2.0*x)\"));\n\n    cout << std::endl;\n}\n\n\n\n\n\nint main(int, char**)\n{\n    double              a= 3.0, b= -5.0;\n    float               c= -9;\n    std::complex<float> d(1., 2.);\n\n    test(a, b);\n    test(b, a);\n    test(c, a);\n    test(d, c);\n\n    return 0;\n}\n", "meta": {"hexsha": "a08771b110c55fdaf477e5507393bc163f3a4e79", "size": 2834, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/scompose_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/scompose_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/scompose_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 37.7866666667, "max_line_length": 142, "alphanum_fraction": 0.5804516584, "num_tokens": 925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7341195327172401, "lm_q1q2_score": 0.6035851067009764}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n\n#pragma once\n\n#include <Eigen/Dense>\n#include <time.h>\n#include <memory>\n\n//#include <boost/random/uniform_int_distribution.hpp>\n//#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_01.hpp>\n\n#include <dpMM/distribution.hpp>\n#include <dpMM/sampler.hpp>\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\n\ntemplate<typename T>\nclass Cat : public Distribution<T>\n{\npublic:\n  uint32_t K_;\n  Matrix<T,Dynamic,1> pdf_;\n  Matrix<T,Dynamic,1> cdf_;\n\n  /* constructor from pdf */\n  Cat(const Matrix<T,Dynamic,1>& pdf, boost::mt19937 *pRndGen);\n  /* constructor from indicators - estimates from counts */\n  Cat(const VectorXu& z, boost::mt19937 *pRndGen);\n  /* copy constructor */\n  Cat(const Cat& other);\n  virtual ~Cat();\n\n  uint32_t sample();\n  void sample(VectorXu& z);\n\n  T logPdf(const Matrix<T,Dynamic,1>& x) const \n  {\n    //assuming x is all zeros except one element\n    assert(x.rows()==K_); //data dimmension should agree with # categories\n    for(uint32_t d=0; d<K_; ++d) {\n      if(x(d)==1) {\n        return(log(pdf_(d))); \n      }\n    }\n    assert(false); //invalid data (at least one element must be one) [this should never happen] \n    return(-1); \n  };\n\n  T logPdf(uint32_t x) const \n  {\n    assert(x < K_);\n    return(log(pdf_(x))); \n  };\n\n  T logPdfOfSS(const Matrix<T,Dynamic,1>& x) const \n  {\n    \n    assert(x.rows()==K_); //data dimmension should agree with # categories\n    T logPdf = 0;\n    for(uint32_t d=0; d<K_; ++d) {\n      logPdf += x(d) * log(pdf_(d)); \n    }\n    return logPdf; \n  };\n\n  const Matrix<T,Dynamic,1>& pdf() const {return pdf_;};\n  void pdf(const Matrix<T,Dynamic,1>& pdf){\n    pdf_ = pdf;\n    updateCdf();\n  };\n  const Matrix<T,Dynamic,1>& cdf() const {return cdf_;};\n\n  void print() const;\n\nprivate:\n  boost::uniform_01<T> unif_;\n  void updateCdf();\n};\n\ntypedef Cat<float> Catf;\ntypedef Cat<double> Catd;\n\ntemplate<typename T>\ninline T logSumExpRow(const Matrix<T,Dynamic,Dynamic>& pdf, uint32_t i)\n{\n  T max = pdf.row(i).maxCoeff();\n  return log((pdf.row(i).array()-max).exp().matrix().sum()) + max;\n}\n\ntemplate<typename T>\ninline T logSumExpCol(const Matrix<T,Dynamic,Dynamic>& pdf, uint32_t i)\n{\n  T max = pdf.col(i).maxCoeff();\n  return log((pdf.col(i).array()-max).exp().matrix().sum()) + max;\n}\n\n\ntemplate<typename T>\ninline T logSumExp(const Matrix<T,Dynamic,1>& pdf)\n{\n  T max = pdf.maxCoeff();\n  return log((pdf.array()-max).exp().matrix().sum()) + max;\n}\n\n//template<typename T>\n//inline T logSumExp(const Matrix<T,1,Dynamic>& pdf)\n//{\n//  T max = pdf.maxCoeff();\n//  return log((pdf.array()-max).exp().matrix().sum()) + max;\n//}\n\n", "meta": {"hexsha": "37b061ac3cc8c468996dbfd552016acaa40cd521", "size": 2771, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/cat.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/dpMM/cat.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dpMM/cat.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 23.6837606838, "max_line_length": 96, "alphanum_fraction": 0.6383976904, "num_tokens": 797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.603585103532542}}
{"text": "/* ----------------------------------------------------------------------------\n * Copyright 2022, Jeferson Lima\n * All Rights Reserved\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n *  @file   examples/1/dc_motor_ex.cpp\n *  @author Jeferson Lima\n *  @brief  DC Motor Simulation Example \n *  @date   Mar 15, 2022\n **/\n\n#include <iostream>\n#include <boost/numeric/odeint.hpp>\n#include <boost/array.hpp>\n#include <robocore.hpp>\n#ifdef USE_MATPLOTLIB\n #include <matplotlibcpp.h>\n namespace plt = matplotlibcpp;\n#endif \n\n using namespace boost::numeric::odeint;\n\n const double j = 0.01;         // (J)     moment of inertia of the rotor     0.01 kg.m^2\n const double b = 0.1;          // (b)     motor viscous friction constant    0.1 N.m.s\n const double Ke = 0.01;        // (Ke)    electromotive force constant       0.01 V/rad/sec\n const double Kt = 0.01;        // (Kt)    motor torque constant              0.01 N.m/Amp\n const double R = 1;            // (R)     electric resistance                1 Ohm\n const double L = 0.5;          // (L)     electric inductance                0.5 H\n const double V = 12;           // (V)     motor votage                       12 V\n\n typedef boost::array< double , 2> state;\n std::vector<double> ts, dTheta, di;\n\nvoid dc_motor_model(const state& x, state& dxdt, double t)\n{\n  dxdt[0] = -b*x[0]/j + Kt*x[1]/j;\n  dxdt[1] = -R*x[1]/L + V/L - Ke*x[0];\n}\n\nvoid log_model(const state& x, const double t)\n{\n  ts.push_back(t);\n  dTheta.push_back(x[0]);\n  di.push_back(x[1]);\n  std::cout << t << ';' << x[0] << ';' << x[1]  << std::endl;\n}\n\nint main(int argc, char** argv)\n{\n  state x = { 0.0 , 0.0 }; // initial conditions\n  runge_kutta4< state > stepper;\n  integrate_const( stepper , dc_motor_model, x , 0.0 , 20.0 , 0.1, log_model );\n\n#ifdef USE_MATPLOTLIB\n  plt::figure();\n  plt::named_plot(\"Velocity (rad/s)\", ts, dTheta);\n  plt::named_plot(\"Current (A)\", ts, di);\n  plt::legend();\n  plt::show();\n#endif\n\n#ifdef SAVE_OUTPUT_CSV\n  columns vals = {{\"Time\", ts}, {\"Velocity\", dTheta}, {\"Current\", di}};\n  RoboCore::write_csv(\"/tmp/dc_motor_output.csv\", vals);\n  std::cout << \"Output file was saved in /tmp\" << std::endl;\n#endif\n\n  return 0;\n}\n", "meta": {"hexsha": "c3edf9f361be8ce640096d8ebeaba77de7c69095", "size": 2259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/1/dc_motor_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/dc_motor_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/dc_motor_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": 31.375, "max_line_length": 92, "alphanum_fraction": 0.5537848606, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6035851003039683}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// $Id: percentile.hpp 7503 2015-05-21 18:37:51Z chambm $\n//\n//  Copyright 2011 Vanderbilt University. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_ACCUMULATORS_STATISTICS_PERCENTILE_HPP_\r\n#define BOOST_ACCUMULATORS_STATISTICS_PERCENTILE_HPP_\r\n\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\r\n\r\nnamespace boost { namespace accumulators\n{\n\nBOOST_PARAMETER_KEYWORD(tag, percentile_number)\n\nnamespace impl\n{\r\n    template<typename Sample>\r\n    struct percentile_impl : accumulator_base\r\n    {\r\n        typedef Sample result_type;\r\n\r\n        percentile_impl(dont_care) : isSorted(false) {}\r\n\r\n        template<typename Args>\r\n        void operator ()(const Args& args) \r\n        {\r\n            buffer_.push_back(args[sample]);\r\n            isSorted = false;\r\n        }\r\n\r\n        template<typename Args>\r\n        result_type result(const Args& args) const\r\n        {\r\n            if (buffer_.empty())\r\n                return result_type();\r\n\r\n            if(!isSorted)\r\n            {\r\n                std::sort(buffer_.begin(), buffer_.end());\r\n                isSorted = true;\r\n            }\r\n\r\n            size_t percentile_num = args[percentile_number];\r\n            double percentile = percentile_num / 100.0;\r\n            double integer, fraction = modf((buffer_.size()-1)*percentile, &integer);\r\n            size_t index = static_cast<size_t>(integer);\r\n            if (fraction == 0)\r\n                return buffer_[index];\r\n            else\r\n                return static_cast<result_type>(buffer_[index] + fraction * (buffer_[index+1] - buffer_[index]));\r\n        }\r\n\r\n    private:\r\n        mutable std::vector<Sample> buffer_;\r\n        mutable bool isSorted;\r\n    };\r\n} // namespace impl\r\n\r\nnamespace tag\r\n{\r\n    struct percentile : depends_on<>\r\n    {        \n        typedef impl::percentile_impl<mpl::_1> impl;\r\n    };\r\n}\r\n\r\nnamespace extract { extractor<tag::percentile> const percentile = {}; }\r\nusing extract::percentile;\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#endif\r\n", "meta": {"hexsha": "a0f06f8fd1d102072341aed29dd5f4bc707625d2", "size": 2478, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz_tools/Bumbershoot/freicore/percentile.hpp", "max_stars_repo_name": "shze/pwizard-deb", "max_stars_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-12-28T21:24:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-18T03:52:05.000Z", "max_issues_repo_path": "pwiz_tools/Bumbershoot/freicore/percentile.hpp", "max_issues_repo_name": "shze/pwizard-deb", "max_issues_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz_tools/Bumbershoot/freicore/percentile.hpp", "max_forks_repo_name": "shze/pwizard-deb", "max_forks_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_forks_repo_licenses": ["Apache-2.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.5925925926, "max_line_length": 114, "alphanum_fraction": 0.614205004, "num_tokens": 517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6035850827272299}}
{"text": "#include <mpi.h>\n#include <Eigen/Cholesky>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/SVD>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n\nusing namespace std;\nusing namespace Eigen;\n\ntypedef Matrix<double, Dynamic, Dynamic, RowMajor> RowMatrixXd;\ntypedef Matrix<complex<double>, Dynamic, Dynamic, RowMajor> RowMatrixXcd;\n\nint main(int argc, char *argv[]) {\n    int npes, myrank;\n\n    MPI::Init(argc, argv);\n\n    myrank = MPI::COMM_WORLD.Get_rank();\n    npes = MPI::COMM_WORLD.Get_size();\n\n    long xn = atol(argv[2]);\n    long tn = atol(argv[3]);\n    long long position = 0;\n\n    int xnProc = ceil((xn + 0.0) / (npes + 0.0));\n    int outputPrecision = 9;\n    int modeCount = tn;\n\n    RowMatrixXd snapshotsProc(xnProc, tn + 1);\n    RowMatrixXd snapshotsInProdProc(tn, tn);\n    RowMatrixXd r(tn, tn);\n    RowMatrixXd sigmaPseudoInverse(tn, tn);\n    RowMatrixXd v(tn, tn), uProc(xnProc, tn);\n    RowMatrixXd aTildeProc(tn, tn), aTilde(tn, tn);\n    RowMatrixXd x0TildeProc(tn, 1), x0Tilde(tn, 1);\n\n    RowMatrixXcd eigenvec(tn, tn);\n    RowMatrixXcd dmdModesAllProc(xnProc, tn);\n\n    VectorXd dmdModeProc(xnProc);\n    VectorXd dmdMode(xnProc * npes);\n\n    double *snapshotsRecvBuf = new double[xnProc * (tn + 1)];\n    double *tntnBuf = new double[tn * tn];\n    double *tn1Buf = new double[tn * 1];\n\n    double *tntn_pt = new double[tn * tn];\n    double *tn1_pt = new double[tn * 1];\n    double *tntn2_pt = new double[tn * tn];\n    double *xnProc_pt = new double[xnProc];\n    double *xnProcnpes_pt = new double[xnProc * npes];\n\n    complex<double> *tntnc_pt = new complex<double>[tn * tn];\n\n    MPI::COMM_WORLD.Barrier();\n    double timeBegin = MPI::Wtime();\n\n    /* input matrix from a file */\n    double *snapshots = NULL;\n\n    if (myrank == 0) {\n        if (modeCount > tn) {\n            cout << \"Invalid output modes number\" << endl;\n            exit(0);\n        }\n\n        cout << \"Initializing\" << endl;\n\n        snapshots = new double[xn * (tn + 1)];\n        ifstream inputFile(argv[1]);\n        if (inputFile.is_open()) {\n            while (!inputFile.eof() && position < (xn * (tn + 1))) {\n                inputFile >> snapshots[position];\n                position++;\n            }\n        } else {\n            cout << \"input file not found.\" << endl;\n            exit(0);\n        }\n        inputFile.close();\n\n        cout << \"Running\" << endl;\n    }\n    /****************************/\n\n    MPI::COMM_WORLD.Scatter(snapshots, xnProc * (tn + 1), MPI::DOUBLE,\n                            snapshotsRecvBuf, xnProc * (tn + 1), MPI::DOUBLE,\n                            0);\n\n    // delete[] snapshots;\n\n    snapshotsProc = Map<RowMatrixXd>(snapshotsRecvBuf, xnProc, tn + 1);\n\n    // delete[] snapshotsRecvBuf;\n\n    snapshotsInProdProc = snapshotsProc.block(0, 0, xnProc, tn).transpose() *\n                          snapshotsProc.block(0, 0, xnProc, tn);\n\n    tntn_pt = snapshotsInProdProc.data();\n\n    MPI::COMM_WORLD.Reduce(tntn_pt, tntnBuf, tn * tn, MPI::DOUBLE, MPI::SUM, 0);\n\n    if (myrank == 0) {\n        VectorXd sigma(tn);\n\n        RowMatrixXd snapshotsInProd = Map<RowMatrixXd>(tntnBuf, tn, tn);\n\n        LLT<RowMatrixXd, Upper> cholesky(snapshotsInProd);\n        r = cholesky.matrixU();\n\n        JacobiSVD<RowMatrixXd> svd(r, ComputeThinV);\n        sigma = svd.singularValues();\n        v = svd.matrixV();\n\n        for (int i = 0; i < tn; ++i) {\n            for (int j = 0; j < tn; ++j) {\n                if (i == j && sigma(i) != 0) {\n                    sigmaPseudoInverse(i, j) = 1.0 / sigma(i);\n                } else\n                    sigmaPseudoInverse(i, j) = 0;\n            }\n        }\n\n        tntn_pt = sigmaPseudoInverse.data();\n        tntn2_pt = v.data();\n    }\n\n    MPI::COMM_WORLD.Bcast(tntn_pt, tn * tn, MPI::DOUBLE, 0);\n    MPI::COMM_WORLD.Bcast(tntn2_pt, tn * tn, MPI::DOUBLE, 0);\n\n    sigmaPseudoInverse = Map<RowMatrixXd>(tntn_pt, tn, tn);\n    v = Map<RowMatrixXd>(tntn2_pt, tn, tn);\n\n    uProc = snapshotsProc.block(0, 0, xnProc, tn) * v * sigmaPseudoInverse;\n\n    if (myrank != npes - 1) {\n        aTildeProc = uProc.adjoint() * snapshotsProc.block(0, 1, xnProc, tn) *\n                     v * sigmaPseudoInverse;\n        x0TildeProc = uProc.adjoint() * snapshotsProc.block(0, 0, xnProc, 1);\n\n    } else {\n        aTildeProc = uProc.block(0, 0, xn - xnProc * (npes - 1), tn).adjoint() *\n                     snapshotsProc.block(0, 1, xn - xnProc * (npes - 1), tn) *\n                     v * sigmaPseudoInverse;\n        x0TildeProc =\n          uProc.block(0, 0, xn - xnProc * (npes - 1), tn).adjoint() *\n          snapshotsProc.block(0, 0, xn - xnProc * (npes - 1), 1);\n    }\n\n    tntn_pt = aTildeProc.data();\n    tn1_pt = x0TildeProc.data();\n\n    MPI::COMM_WORLD.Reduce(tntn_pt, tntnBuf, tn * tn, MPI::DOUBLE, MPI::SUM, 0);\n    MPI::COMM_WORLD.Reduce(tn1_pt, tn1Buf, tn * 1, MPI::Double, MPI::SUM, 0);\n\n    if (myrank == 0) {\n        aTilde = Map<RowMatrixXd>(tntnBuf, tn, tn);\n        x0Tilde = Map<RowMatrixXd>(tn1Buf, tn, 1);\n\n        ComplexEigenSolver<RowMatrixXd> ces(aTilde);\n\n        eigenvec = ces.eigenvectors();\n        tntnc_pt = eigenvec.data();\n\n        ofstream ofeigenvalReal, ofeigenvalImag, ofamplitudeReal,\n          ofamplitudeImag;\n\n        ofeigenvalReal.open(\"eigenvalReal.dat\",\n                            ofstream::trunc | ofstream::out);\n        ofeigenvalImag.open(\"eigenvalImag.dat\",\n                            ofstream::trunc | ofstream::out);\n        ofamplitudeReal.open(\"amplitudeReal.dat\",\n                             ofstream::trunc | ofstream::out);\n        ofamplitudeImag.open(\"amplitudeImag.dat\",\n                             ofstream::trunc | ofstream::out);\n\n        for (int i = 0; i < modeCount; ++i) {\n\n          ofeigenvalReal << setprecision(outputPrecision)\n                         << ces.eigenvalues().row(i).real() << endl;\n\n          ofeigenvalImag << setprecision(outputPrecision)\n                         << ces.eigenvalues().row(i).imag() << endl;\n\n          ofamplitudeReal << setprecision(outputPrecision)\n                          << (eigenvec.inverse() * x0Tilde).row(i).real()\n                          << endl;\n\n          ofamplitudeImag << setprecision(outputPrecision)\n                          << (eigenvec.inverse() * x0Tilde).row(i).imag()\n                          << endl;\n        }\n    }\n\n    MPI::COMM_WORLD.Bcast(tntnc_pt, tn * tn, MPI::DOUBLE_COMPLEX, 0);\n    eigenvec = Map<RowMatrixXcd>(tntnc_pt, tn, tn);\n\n    dmdModesAllProc = uProc * eigenvec;\n\n    for (int i = 0; i < modeCount; ++i) {\n        dmdModeProc = dmdModesAllProc.col(i).real();\n\n        xnProc_pt = dmdModeProc.data();\n\n        MPI::COMM_WORLD.Barrier();\n\n        MPI::COMM_WORLD.Gather(xnProc_pt, xnProc, MPI::DOUBLE, xnProcnpes_pt,\n                               xnProc, MPI::DOUBLE, 0);\n\n        if (myrank == 0) {\n            dmdMode = Map<VectorXd>(xnProcnpes_pt, xnProc * npes);\n\n            ofstream ofdmdMode;\n            ofdmdMode.open(\"dmdMode\" + to_string(i) + \".dat\",\n                           ofstream::trunc | ofstream::out);\n            ofdmdMode << setprecision(outputPrecision) << dmdMode.head(xn)\n                      << endl;\n        }\n    }\n\n    MPI::COMM_WORLD.Barrier();\n\n    double timeFinish = MPI::Wtime();\n    double timing = timeFinish - timeBegin;\n    double timingMax;\n\n    MPI::COMM_WORLD.Reduce(&timing, &timingMax, 1, MPI::DOUBLE, MPI::MAX, 0);\n\n    if (myrank == 0) {\n        cout << \"Calculation finished successfully.\" << endl\n             << \"Spatial: \" << xn << \" points.\" << endl\n             << \"Temporal: \" << tn + 1 << \" state vectors.\" << endl\n             << \"Parallelism: \" << npes << \" cores.\" << endl\n             << \"Time consumption: \" << timingMax << \" s.\" << endl\n             << \"Output DMD modes: \" << modeCount << endl;\n    }\n\n    MPI::Finalize();\n    return 0;\n}\n", "meta": {"hexsha": "2476f314eb48eabae58e78326ba7190686ed2443", "size": 7846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dmd_mpi.cpp", "max_stars_repo_name": "dongwang01/parallelDMD", "max_stars_repo_head_hexsha": "0edba737bb39dab535774e0beba131ddf5b802c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-21T21:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T21:41:28.000Z", "max_issues_repo_path": "src/dmd_mpi.cpp", "max_issues_repo_name": "dongwang01/parallelDMD", "max_issues_repo_head_hexsha": "0edba737bb39dab535774e0beba131ddf5b802c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-20T23:47:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-22T08:23:04.000Z", "max_forks_repo_path": "src/dmd_mpi.cpp", "max_forks_repo_name": "dongwang01/parallelDMD", "max_forks_repo_head_hexsha": "0edba737bb39dab535774e0beba131ddf5b802c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-05T18:35:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-06T12:48:26.000Z", "avg_line_length": 32.0244897959, "max_line_length": 80, "alphanum_fraction": 0.5504715779, "num_tokens": 2244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996142, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6035570553660664}}
{"text": "#pragma once\n\n#include \"enum.hpp\"\n#include \"cc_trade_stream.hpp\"\n#include \"utils.hpp\"\n#include \"trade_data.hpp\"\n\n#include <boost/log/trivial.hpp>\n\n#include <concepts>\n#include <map>\n\nnamespace profitview\n{\n\ntemplate<std::floating_point Float = double, std::integral Int = int>\nclass CcKaufman : public CcTradeStream<Float, Int>\n{\npublic:\n    CcKaufman(\n        const std::string trade_stream_name,\n        OrderExecutor* executor,\n        Int lookback,\n        Float base_quantity,\n        Int er_period,\n        Int fast_sc,\n        Int slow_sc,\n        Int kama_trend,\n        const std::string& csv_name = \"Kaufman.csv\")\n        : CcTradeStream<Float, Int>(trade_stream_name, executor, csv_name)\n        , lookback_{lookback}\n        , base_quantity_{base_quantity}\n        , er_period_{er_period}\n        , fast_sc_{fast_sc}\n        , slow_sc_{slow_sc}\n        , kama_trend_{kama_trend}\n    {}\n\n    void onStreamedTrade(TradeData const& trade_data) override\n    {\n        trade_data.print();\n\n        auto& [prices, mean_reached, initial_mean, kama, kamas]{price_structure_[trade_data.symbol]};\n\n        prices.emplace_back(trade_data.price);\n\n        auto sc_factor{2.0 / (fast_sc_ + 1) - 2.0 / (slow_sc_ + 1)};\n        auto sc_sum{2.0 / (slow_sc_ + 1)};\n\n        if (not mean_reached && prices.size() + 1 == lookback_)\n        {\n            kama = initial_mean = util::ma(prices);\n            BOOST_LOG_TRIVIAL(info) << \"Initial mean: \" << initial_mean << std::endl << std::endl;\n            mean_reached = true;\n        }\n        else if (mean_reached)\n        {\n            auto [er_vols, change]{util::abs_differences(prices, er_period_)};\n            auto er_vol{util::accumulate(er_vols, 0.0)};\n            // Occasionally, the sequence will be constant:\n            auto er{er_vol > 0 ? change / er_vol : 0.0};    // leading to er_vol of zero\n            auto root_sc{er * sc_factor + sc_sum};\n            auto sc{root_sc * root_sc};\n\n            BOOST_LOG_TRIVIAL(info) << \"ER: \" << er << std::endl;\n            BOOST_LOG_TRIVIAL(info) << \"SC: \" << sc << std::endl;\n\n            // These could be done on the fly but the complexity would distract\n            auto mean{util::ma(prices)};\n\n            prices.pop_front();    // Now we have lookback_ prices already, remove the\n                                   // oldest\n\n            kamas.emplace_back(kama = kama + sc * (trade_data.price - kama));\n\n            if (kamas.size() > kama_trend_)\n            {\n                auto [monotonic, up]{util::is_monotonic(std::ranges::subrange{kamas.end() - kama_trend_, kamas.end()})};\n                if (not monotonic)    // Signal\n                {\n                    // @todo This will keep buying/selling when the market is not\n                    // directional\n                    //       It should have more refined behaviour\n                    this->new_order(trade_data.symbol, up ? Side::Buy : Side::Sell, base_quantity_, OrderType::Market);\n                }\n\n                this->writeCsv(\n                    trade_data.symbol,\n                    trade_data.price,\n                    toString(trade_data.side).data(),\n                    trade_data.size,\n                    trade_data.source,\n                    trade_data.time,\n                    kama,\n                    monotonic ? (up ? \"Up\" : \"Down\") : \"Not monotonic\");\n\n                kamas.pop_front();    // Remove oldest KAMA price\n            }\n        }\n    }\n\n    struct Data\n    {\n        std::deque<Float> prices;\n        bool mean_reached;\n        Float initial_mean, kama;\n        std::deque<Float> kamas;\n    };\n\nprivate:\n    const Int lookback_;\n\n    double base_quantity_;\n    Int er_period_, fast_sc_, slow_sc_, kama_trend_;\n\n    std::map<std::string, Data> price_structure_;\n\n};\n\n}    // namespace profitview", "meta": {"hexsha": "0b267bc16f1eeeaa1188cc1d8dbf686201fdbc84", "size": 3812, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cc_kaufman.hpp", "max_stars_repo_name": "Twon/cpp_crypto_algos", "max_stars_repo_head_hexsha": "e785f6c25ef50dc3c2f593b08b6857dffcd32eca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cc_kaufman.hpp", "max_issues_repo_name": "Twon/cpp_crypto_algos", "max_issues_repo_head_hexsha": "e785f6c25ef50dc3c2f593b08b6857dffcd32eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cc_kaufman.hpp", "max_forks_repo_name": "Twon/cpp_crypto_algos", "max_forks_repo_head_hexsha": "e785f6c25ef50dc3c2f593b08b6857dffcd32eca", "max_forks_repo_licenses": ["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.7666666667, "max_line_length": 120, "alphanum_fraction": 0.5566631689, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.672331705744791, "lm_q1q2_score": 0.6035490106619437}}
{"text": "/* Bubble Dynamics with Chebyshev Spectral Collocation */\n\n#include <iostream>\n#include <fstream>\n#define _USE_MATH_DEFINES\n#include <cmath>\n#include <vector>\n#include <string>\n#include <chrono>\n#include <boost/numeric/odeint.hpp>\n#include <Eigen/Core>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\nconst double rho_L = 9.970639504998557e+02;\nconst double p_inf = 1.0e+5;\nconst double sigma = 0.071977583160056;\nconst double gamma = 1.33;\nconst double c_L = 1.497251785455527e+03; // water 25 Celsius\nconst double mu_L = 8.902125058209557e-04; //25 Celsius\nconst double lambda = 0.6084; //water 25 Celsius\nconst double T_inf = 298.15; // 25 Celsius\nconst int N = 16;\n\nstring file_name = \"../bubble_sim_rk4_p05_f100_Re10_t5.txt\";\n\n\ntypedef double value_type;\ntypedef vector<value_type> state_type;\ntypedef Eigen::Matrix<value_type, N/2, N/2> matrix_type;\n\nusing namespace boost::numeric;\n\n//ode function of bubble dynamic\nclass bubble {\npublic:\n\tstd::vector<value_type> C; //constants of the right hand side\n\tEigen::Matrix<value_type, N/2, 1> y; //collocation points (half)\n\tEigen::Matrix<value_type, N/2, 1> y_sq; //same, every entry squared\n\tmatrix_type D_E; //Derivative matrix for even functions\n\tmatrix_type D_O; //Derivative matrix for odd functions\n\tEigen::Matrix<value_type, 1, N/2> D_E0; //first row of even D matrix\n\n\t//p_A pressure amplitude, f pressure frequence, N number of collocation points\n\tbubble(value_type p_A, value_type f, value_type R_E){\n\t\tconst double omega = 2*M_PI*f;\n\t\tvalue_type pi2wRE = 2*M_PI/(omega*R_E);\n\n\t\tC = std::vector<value_type>(13);\n\t\tC[0] = omega*R_E/(2*M_PI*c_L);\n\t\tC[1] = 4*mu_L/(c_L*rho_L*R_E);\n\t\tC[2] = 4*mu_L/(rho_L*R_E)*pi2wRE;\n\t\tC[3] = 2*sigma*pi2wRE*pi2wRE/(rho_L*R_E);\n\t\tC[4] = p_inf/rho_L*pi2wRE*pi2wRE;\n\t\tC[5] = p_A/rho_L*pi2wRE*pi2wRE;\n\t\tC[6] = pi2wRE*p_inf/(c_L*rho_L);\n\t\tC[7] = pi2wRE*p_A/(c_L*rho_L);\n\t\tC[8] = 2*M_PI*pi2wRE*p_A/(c_L*rho_L);\n\t\tC[9] = lambda*(gamma-1)/gamma*pi2wRE/R_E*T_inf/p_inf;\n\t\tC[10] = lambda*(gamma-1)*pi2wRE/R_E*T_inf/p_inf;\n\t\tC[11] = (gamma-1)/gamma;\n\t\tC[12] = 1.0/(3.0*gamma);\n\t\t\n\n\t\tEigen::Matrix<value_type, N, 1> y_full(N);\n\t\tvalue_type rec_cpn =  1.0/(N-1);\n\t\tfor(int i = 0; i < N; i++){\n\t\t\ty_full[i] = cos(M_PI*i*rec_cpn);\n\t\t}\n\t\tEigen::Matrix<value_type, N, N> D(N, N);\n\t\tfor(int i = 0; i < N; i++){\n\t\t\tfor(int j = 0; j < N; j++){\n\t\t\t\tif(i == j){\n\t\t\t\t\tif(i == N-1){\n\t\t\t\t\t\tD(N-1,N-1) = -(1+2*(N-1)*(N-1))/6.0;\n\t\t\t\t\t}else if(i == 0){\n\t\t\t\t\t\tD(0,0) = (1+2*(N-1)*(N-1))/6.0;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tD(i,i) = -y_full[i]/(2.0*(1.0-y_full[i]*y_full[i]));\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tD(i,j) = std::pow(-1,i+j)*(i==0 || i==N-1?2.0:1.0)\n\t\t\t\t\t\t\t/((j==0 || j==N-1?2.0:1.0) * (y_full[i]-y_full[j]) );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tD_E = matrix_type(N/2,N/2);\n\t\tD_O = matrix_type(N/2,N/2);\n\t\tfor(int i = 0; i < N/2;i++){\n\t\t    for(int j = 0; j < N/2; j++){\n\t\t    \tD_E(i,j) = D(i,j) + D(i,N-1-j);\n\t\t    \tif(i==0) D_E0(j) = D_E(i,j);\n\t\t\t}\n\t\t}\n\t\tfor(int i = 0; i < N/2;i++){\n\t\t\tfor(int j = 0; j < N/2; j++){\n\t\t\t\tD_O(i,j) = D(i,j) - D(i,N-1-j);\n\t\t    }\n\t\t}\n\t\ty = y_full.head<N/2>();\n\t\ty_sq = y.cwiseProduct(y);\n    }\n\n\tvoid operator()(const state_type &x, state_type &dxdt, const value_type t){\n\t    value_type rec_xR = 1.0 / x[0];\n\t    value_type rec_xp = 1.0 / x[2];\n\n\t    Eigen::Map<const Eigen::Matrix<value_type, N/2,1>> z(x.data()+3);\n\t    Eigen::Map<Eigen::Matrix<value_type, N/2,1>> dzdt(dxdt.data()+3);\n\n\t    Eigen::Matrix<value_type, N/2, 1> De_x = D_E*z; //derivative of z (dimless temperature)\n\n\t    //bubble pressure evolution\n\t    dxdt[2] = 3*rec_xR*(C[10]*rec_xR* De_x[0] - gamma*x[1]*x[2]);\n\n\t    //discretized PDE of bubble temperature\n\t    dzdt = De_x.cwiseProduct( x[1]*rec_xR*y - C[9]*rec_xR*rec_xR*rec_xp* De_x //this might show error, but it will not fail at compile time, valid syntax\n\t    \t\t+ C[12]*rec_xp*dxdt[2]*y )\n\t    \t\t+ C[11]*rec_xp*dxdt[2]*z + C[9]*rec_xp*rec_xR*rec_xR* z\n\t\t\t\t.cwiseProduct(y_sq.cwiseInverse()).cwiseProduct(D_O * (y_sq.cwiseProduct(De_x)));\n\t    dxdt[3] = 0.0; //Boundary condition\n\n\t    //Keller-Miksis equation\n\t    dxdt[0] = x[1];\n\t    value_type sin2pit = sin(2*M_PI*t);\n\t    value_type den = x[0] - C[0]*x[0]*x[1] + C[1];\n\t    value_type nom = 0.5*C[0] * x[1]*x[1]*x[1] - 1.5* x[1]*x[1] - C[2]*x[1]*rec_xR - C[3]*rec_xR\n\t    \t\t+ C[4] * x[2] - C[4] - C[5] * sin2pit + C[6] * x[1]*x[2] - C[6] * x[1] - C[7] * x[1]*sin2pit\n\t            - C[8] * x[0]*cos(2*M_PI*t) + C[6] * x[0]*dxdt[2];\n\t    dxdt[1] = nom/den;\n\t}\n};\n\n\nclass all_save_observer\n{\n\tostream &os;\n\tdouble file_size = 0;\npublic:\n\tint line_number = 0;\n\n\tall_save_observer(ostream &output):os(output){}\n\n\tvoid operator()(const state_type &x, const value_type t){\n\t\tos << t << \", \" << x[0];\n\t\tfor(int i =1; i < 3+N/2;i++){\n\t\t\tos << \", \" << x[i];\n\t\t}\n\t\tos << endl;\n\t\tline_number++;\n\t}\n};\n\nint main() {\n\tdouble tolerance = 1e-10;\n\tcout << \"Bubble dynamics started\\n\" << setprecision(17) << endl;\n\n\ttypedef runge_kutta_cash_karp54< state_type , value_type , state_type , value_type > stepper_type;\n\n\tvalue_type f = 100e3;\n\tvalue_type p_A = 0.5e5;\n\tvalue_type R_E = 10e-6;\n\tstate_type x(3+N/2);\n\n\tauto t1 = chrono::high_resolution_clock::now();\n\n\tbubble bubi(p_A, f, R_E);\n\n\tstate_type dxdt(3+N/2);\n\n\t//auto stepper = euler< state_type , value_type>();\n\tauto stepper = make_controlled( tolerance , tolerance, stepper_type() );\n\n\tofstream ofs(file_name);\n\tif(!ofs.is_open())exit(-1);\n\tofs.precision(17);\n\tofs.flags(ios::scientific);\n\n\tall_save_observer observer(ofs);\n\n\t//initial conditions\n\tx[0] = 1.0;\n\tx[1] = 0.0;\n\tx[2] = 1.0 + 2.0*sigma/(R_E*p_inf);\n\tfor(int i=0; i < N/2;i++) x[3+i] = 1.0;\n\n\n\tdouble t_start = 0.0;\n\tintegrate_adaptive(boost::ref(stepper), boost::ref(bubi), x, t_start, 5.0, 1e-5, boost::ref(observer));\n\tauto t2 = chrono::high_resolution_clock::now();\n\n\tcout << \"Done\" << endl;\n\tcout << \"Time (ms):\" << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << endl;\n\n\tofs.flush();\n\tofs.close();\n\n\tcout << \"Ready\"<< endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "0551962b3ad792966656b5c509086d6ecb138b9d", "size": 5937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Dopri/cpp/BubbleDynamics.cpp", "max_stars_repo_name": "plaveczlambert/nonlinearbubbledynamics", "max_stars_repo_head_hexsha": "190c5170f7ff6068badeee818c01226c55aaec97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Dopri/cpp/BubbleDynamics.cpp", "max_issues_repo_name": "plaveczlambert/nonlinearbubbledynamics", "max_issues_repo_head_hexsha": "190c5170f7ff6068badeee818c01226c55aaec97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Dopri/cpp/BubbleDynamics.cpp", "max_forks_repo_name": "plaveczlambert/nonlinearbubbledynamics", "max_forks_repo_head_hexsha": "190c5170f7ff6068badeee818c01226c55aaec97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2463054187, "max_line_length": 154, "alphanum_fraction": 0.6137780024, "num_tokens": 2269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.6723316926137811, "lm_q1q2_score": 0.6035489988742978}}
{"text": "/**\n * @file linquadfelshaped.cc\n * @brief Creates convergence plots for experiment 3.2.3.10\n * @author Tobias Rohner\n * @date April 2020\n * @copyright MIT License\n */\n\n#define _USE_MATH_DEFINES\n\n#include <lf/assemble/assemble.h>\n#include <lf/fe/fe.h>\n#include <lf/geometry/geometry.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/mesh/mesh.h>\n#include <lf/mesh/utils/utils.h>\n#include <lf/uscalfe/uscalfe.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <boost/program_options.hpp>\n#include <cmath>\n#include <filesystem>\n#include <fstream>\n#include <iostream>\n#include <memory>\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 problem that is solved has load zero and Dirichlet boundary conditions\n given by\n * \\f[\n        g(r, \\phi) = r^{\\frac{2}{3}}\\sin(\\frac{2}{3}\\phi)\n   \\f]\n */\nEigen::VectorXd solvePoisson(\n    const std::shared_ptr<const lf::mesh::Mesh> &mesh,\n    const std::shared_ptr<const lf::uscalfe::UniformScalarFESpace<double>>\n        &fe_space) {\n  // Define the boundary values\n  const auto u_bd = [](const Eigen::Vector2d &x) -> double {\n    const double r = x.norm();\n    double phi = std::atan2(x[1], x[0]);\n    if (phi < 0) {\n      phi += 2 * M_PI;\n    }\n    return std::pow(r, 2. / 3) * std::sin(2. / 3 * phi);\n  };\n\n  // Initialize the matrix provider\n  const lf::mesh::utils::MeshFunctionConstant<double> mf_alpha(1);\n  const lf::mesh::utils::MeshFunctionConstant<double> mf_gamma(0);\n  lf::uscalfe::ReactionDiffusionElementMatrixProvider element_matrix_provider(\n      fe_space, mf_alpha, mf_gamma);\n\n  // Assemble the system matrix (RHS is zero because we have no load)\n  const lf::assemble::DofHandler &dofh = fe_space->LocGlobMap();\n  lf::assemble::COOMatrix<double> 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\n  // Enforce the 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<bool, double> {\n    const lf::mesh::Entity &entity = dofh.Entity(idx);\n    if (!boundary(entity)) {\n      return {false, 0};\n    }\n    const lf::geometry::Geometry *geom = entity.Geometry();\n    // Find out where the evaluation node corresponding to the DOF is\n    const auto *const shape_function_layout =\n        fe_space->ShapeFunctionLayout(entity.RefEl());\n    const auto num_dofs = dofh.NumLocalDofs(entity);\n    const auto glob_dof_idxs = dofh.GlobalDofIndices(entity);\n    int dof_idx;\n    for (dof_idx = 0; dof_idx < num_dofs; ++dof_idx) {\n      if (glob_dof_idxs[dof_idx] == idx) {\n        break;\n      }\n    }\n    const Eigen::VectorXd eval_node =\n        shape_function_layout->EvaluationNodes().col(dof_idx);\n    const Eigen::Vector2d pos = geom->Global(eval_node);\n    // Return the value on the boundary at the position of the evaluation node\n    // corresponding to the dof\n    return {true, u_bd(pos)};\n  };\n  lf::assemble::FixFlaggedSolutionComponents(selector, A_COO, rhs);\n\n  // Solve the LSE using Cholesky decomposition\n  std::cout << \"\\t\\t> Solving LSE\" << std::endl;\n  Eigen::SparseMatrix<double> A = A_COO.makeSparse();\n  Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> solver(A);\n  Eigen::VectorXd solution = solver.solve(rhs);\n\n  // Return the resulting solution 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<std::string>(),\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<std::string>();\n\n  // The analytic solution\n  const auto u = [](const Eigen::Vector2d &x) -> double {\n    const double r = x.norm();\n    double phi = std::atan2(x[1], x[0]);\n    if (phi < 0) {\n      phi += 2 * M_PI;\n    }\n    return std::pow(r, 2. / 3) * std::sin(2. / 3 * phi);\n  };\n  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    const double r = x.norm();\n    double phi = std::atan2(x[1], x[0]);\n    if (phi < 0) {\n      phi += 2 * M_PI;\n    }\n    Eigen::Vector2d grad;\n    grad[0] = 2. / 3 * std::pow(r, -4. / 3) *\n              (x[0] * std::sin(2. / 3 * phi) - x[1] * std::cos(2. / 3 * phi));\n    grad[1] = 2. / 3 * std::pow(r, -4. / 3) *\n              (x[1] * std::sin(2. / 3 * phi) + x[0] * std::cos(2. / 3 * phi));\n    return grad;\n  };\n  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, 5);\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 = \"L\" + std::to_string(mesh_idx) + \".msh\";\n    const std::filesystem::path mesh_file = mesh_folder / mesh_name;\n    auto factory = std::make_unique<lf::mesh::hybrid2d::MeshFactory>(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<lf::uscalfe::FeSpaceLagrangeO1<double>>(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::MeshFunctionGradFE<double, double> 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<lf::uscalfe::FeSpaceLagrangeO2<double>>(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::MeshFunctionGradFE<double, double> mf_grad_o2(fe_space_o2,\n                                                                solution_o2);\n\n    // Compute the 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\n    // Store the mesh width, the number of DOFs and the errors\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  }\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": "88a182ec9a1f9e01e0eaeb90acb04f08241805d8", "size": 8131, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/lecturedemos/convergencestudies/linquadfelshaped.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/linquadfelshaped.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/linquadfelshaped.cc", "max_forks_repo_name": "Fytch/lehrfempp", "max_forks_repo_head_hexsha": "c804b3e350aa893180f1a02ce57a93b3d7686e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-11-13T13:46:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T17:33:52.000Z", "avg_line_length": 37.9953271028, "max_line_length": 78, "alphanum_fraction": 0.6363300947, "num_tokens": 2334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321843145405, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6034887722564681}}
{"text": "#ifndef _COCONUT_PULP_MATH_VECTOR_HPP_\n#define _COCONUT_PULP_MATH_VECTOR_HPP_\n\n#include <cmath>\n#include <cassert>\n#include <array>\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <numeric>\n#include <iosfwd>\n#include <initializer_list>\n#include <type_traits>\n\n#include <boost/operators.hpp>\n\n#include \"coconut-tools/utils/InfixOstreamIterator.hpp\"\n#include \"ScalarEqual.hpp\"\n\nnamespace coconut {\nnamespace pulp {\nnamespace math {\n\ntemplate <class ScalarType, size_t DIMENSIONS_PARAM, class ScalarEqualityFunc = ScalarEqual<ScalarType>>\nclass Vector :\n\tboost::equality_comparable<Vector<ScalarType, DIMENSIONS_PARAM, ScalarEqualityFunc>,\n\tboost::additive<Vector<ScalarType, DIMENSIONS_PARAM, ScalarEqualityFunc>,\n\tboost::multiplicative<Vector<ScalarType, DIMENSIONS_PARAM, ScalarEqualityFunc>, ScalarType\n\t>>>\n{\npublic:\n\n\tusing Scalar = ScalarType;\n\n\tstatic const auto DIMENSIONS = DIMENSIONS_PARAM;\n\n\tusing Elements = std::array<Scalar, DIMENSIONS>;\n\n\t// --- CONSTRUCTORS AND OPERATORS\n\n\ttemplate <\n\t\tclass... CompatibleTypes,\n\t\tclass = std::enable_if_t<sizeof...(CompatibleTypes) == DIMENSIONS || sizeof...(CompatibleTypes) == 0>\n\t\t>\n\texplicit constexpr Vector(CompatibleTypes&&... values) noexcept :\n\t\telements_{ std::forward<CompatibleTypes>(values)... }\n\t{\n\t\tstatic_assert(sizeof...(values) == DIMENSIONS || sizeof...(values) == 0, \"Bad number of arguments\");\n\t}\n\n\ttemplate <\n\t\tclass CompatibleScalarType,\n\t\tsize_t OTHER_DIMENSIONS,\n\t\tclass OtherScalarEqualityFunc,\n\t\tclass... TailTypes,\n\t\tclass = std::enable_if_t<sizeof...(TailTypes) + OTHER_DIMENSIONS == DIMENSIONS>\n\t\t>\n\texplicit constexpr Vector(\n\t\tconst Vector<CompatibleScalarType, OTHER_DIMENSIONS, OtherScalarEqualityFunc>& other,\n\t\tTailTypes&&... tail\n\t\t)\n\t{\n\t\tstd::copy(other.elements().begin(), other.elements().end(), elements_.begin());\n\t\tsetTail_(elements_, OTHER_DIMENSIONS, std::forward<TailTypes>(tail)...);\n\t}\n\n\t// TODO: consider removing std::initializer_list constructor, as the number of values cannot be\n\t// checked at compile-time\n\tconstexpr Vector(std::initializer_list<Scalar> values) noexcept {\n\t\tassert(values.size() == DIMENSIONS || values.size() == 0);\n\t\tstd::copy(values.begin(), values.end(), elements_.begin());\n\t\tstd::uninitialized_fill(\n\t\t\telements_.begin() + values.size(),\n\t\t\telements_.end(),\n\t\t\tScalar(0)\n\t\t\t);\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream& os, const Vector& vector) {\n\t\tos << '<';\n\t\tstd::copy(vector.elements_.begin(), vector.elements_.end(),\n\t\t\tcoconut_tools::InfixOstreamIterator<ScalarType>(os, \", \"));\n\t\tos << '>';\n\t\treturn os;\n\t}\n\n\tfriend bool operator==(const Vector& lhs, const Vector& rhs) noexcept {\n\t\treturn std::equal(lhs.elements_.begin(), lhs.elements_.end(), rhs.elements_.begin(), ScalarEqualityFunc());\n\t}\n\n\tVector& operator+=(const Vector& other) noexcept {\n\t\tstd::transform(elements_.begin(), elements_.end(), other.elements_.begin(), elements_.begin(), std::plus<>());\n\t\treturn *this;\n\t}\n\n\tVector& operator-=(const Vector& other) noexcept {\n\t\tstd::transform(elements_.begin(), elements_.end(), other.elements_.begin(), elements_.begin(), std::minus<>());\n\t\treturn *this;\n\t}\n\n\tVector operator-() const noexcept {\n\t\tauto result = Vector();\n\t\tstd::transform(elements_.begin(), elements_.end(), result.elements_.begin(), std::negate<>());\n\t\treturn result;\n\t}\n\n\tVector& operator*=(Scalar scalar) noexcept {\n\t\tstd::transform(elements_.begin(), elements_.end(), elements_.begin(), [scalar](auto element) {\n\t\t\t\treturn element * scalar;\n\t\t\t});\n\t\treturn *this;\n\t}\n\n\tVector& operator/=(Scalar scalar) noexcept {\n\t\tstd::transform(elements_.begin(), elements_.end(), elements_.begin(), [scalar](auto element) {\n\t\t\treturn element / scalar;\n\t\t});\n\t\treturn *this;\n\t}\n\n\t// --- CONVERTERS\n\n\ttemplate <size_t DIMENSIONS_PARAM_ = DIMENSIONS_PARAM>\n\tstd::enable_if_t<(DIMENSIONS_PARAM_> 2), Vector<Scalar, 3, ScalarEqualityFunc>>\n\t\txyz() const noexcept\n\t{\n\t\tstatic_assert(DIMENSIONS_PARAM_ == DIMENSIONS_PARAM, \"Dimensions changed\");\n\t\treturn Vector<Scalar, 3, ScalarEqualityFunc>(x(), y(), z());\n\t}\n\n\t// --- VECTOR-SPECIFIC OPERATIONS\n\n\tScalar dot(const Vector& other) const noexcept {\n\t\treturn std::inner_product(elements_.begin(), elements_.end(), other.elements_.begin(), Scalar(0));\n\t}\n\n\ttemplate <size_t DIMENSIONS_PARAM_ = DIMENSIONS_PARAM>\n\tconstexpr std::enable_if_t<(DIMENSIONS_PARAM_ == 3), Vector> cross(const Vector& other) const noexcept {\n\t\tstatic_assert(DIMENSIONS_PARAM_ == DIMENSIONS_PARAM, \"Dimensions changed\");\n\t\treturn {\n\t\t\t(y() * other.z()) - (z() * other.y()),\n\t\t\t(z() * other.x()) - (x() * other.z()),\n\t\t\t(x() * other.y()) - (y() * other.x())\n\t\t\t};\n\t}\n\n\tScalar length() const noexcept {\n\t\tusing std::sqrt;\n\t\treturn sqrt(lengthSq());\n\t}\n\n\tScalar lengthSq() const noexcept {\n\t\treturn dot(*this);\n\t}\n\n\tVector& normalise() noexcept {\n\t\tconst auto l = length();\n\t\tif (l > Scalar(0)) {\n\t\t\t*this /= l;\n\t\t}\n\t\treturn *this;\n\t}\n\n\tVector normalised() const noexcept {\n\t\tauto result = *this;\n\t\treturn result.normalise();\n\t}\n\n\t// --- ACCESSORS\n\n\tconstexpr const Scalar& operator[](size_t index) const noexcept {\n\t\tassert(index < DIMENSIONS);\n\t\treturn elements_[index];\n\t}\n\n\tScalar& operator[](size_t index) noexcept {\n\t\tassert(index < DIMENSIONS);\n\t\treturn elements_[index];\n\t}\n\n\ttemplate <size_t INDEX>\n\tconstexpr std::enable_if_t<(DIMENSIONS > INDEX), const Scalar&> get() const noexcept {\n\t\treturn elements_[INDEX];\n\t}\n\n\ttemplate <size_t INDEX>\n\tstd::enable_if_t<(DIMENSIONS > INDEX), Scalar&> get() noexcept {\n\t\treturn elements_[INDEX];\n\t}\n\n\ttemplate <size_t DIMENSIONS_PARAM_ = DIMENSIONS_PARAM>\n\tconstexpr std::enable_if_t<(DIMENSIONS_PARAM_> 0), const Scalar&> x() const noexcept {\n\t\tstatic_assert(DIMENSIONS_PARAM_ == DIMENSIONS_PARAM, \"Dimensions changed\");\n\t\treturn get<0>();\n\t}\n\n\ttemplate <size_t DIMENSIONS_PARAM_ = DIMENSIONS_PARAM>\n\tstd::enable_if_t<(DIMENSIONS_PARAM_> 0), Scalar&> x() noexcept {\n\t\tstatic_assert(DIMENSIONS_PARAM_ == DIMENSIONS_PARAM, \"Dimensions changed\");\n\t\treturn get<0>();\n\t}\n\n\ttemplate <size_t DIMENSIONS_PARAM_ = DIMENSIONS_PARAM>\n\tconstexpr std::enable_if_t<(DIMENSIONS_PARAM_> 1), const Scalar&> y() const noexcept {\n\t\tstatic_assert(DIMENSIONS_PARAM_ == DIMENSIONS_PARAM, \"Dimensions changed\");\n\t\treturn get<1>();\n\t}\n\n\ttemplate <size_t DIMENSIONS_PARAM_ = DIMENSIONS_PARAM>\n\tstd::enable_if_t<(DIMENSIONS_PARAM_> 1), Scalar&> y() noexcept {\n\t\tstatic_assert(DIMENSIONS_PARAM_ == DIMENSIONS_PARAM, \"Dimensions changed\");\n\t\treturn get<1>();\n\t}\n\n\ttemplate <size_t DIMENSIONS_PARAM_ = DIMENSIONS_PARAM>\n\tconstexpr std::enable_if_t<(DIMENSIONS_PARAM_ > 2), const Scalar&> z() const noexcept {\n\t\tstatic_assert(DIMENSIONS_PARAM_ == DIMENSIONS_PARAM, \"Dimensions changed\");\n\t\treturn get<2>();\n\t}\n\n\ttemplate <size_t DIMENSIONS_PARAM_ = DIMENSIONS_PARAM>\n\tstd::enable_if_t<(DIMENSIONS_PARAM_> 2), Scalar&> z() noexcept {\n\t\tstatic_assert(DIMENSIONS_PARAM_ == DIMENSIONS_PARAM, \"Dimensions changed\");\n\t\treturn get<2>();\n\t}\n\n\ttemplate <size_t DIMENSIONS_PARAM_ = DIMENSIONS_PARAM>\n\tconstexpr std::enable_if_t<(DIMENSIONS_PARAM_> 3), const Scalar&> w() const noexcept {\n\t\tstatic_assert(DIMENSIONS_PARAM_ == DIMENSIONS_PARAM, \"Dimensions changed\");\n\t\treturn get<3>();\n\t}\n\n\ttemplate <size_t DIMENSIONS_PARAM_ = DIMENSIONS_PARAM>\n\tstd::enable_if_t<(DIMENSIONS_PARAM_> 3), Scalar&> w() noexcept {\n\t\tstatic_assert(DIMENSIONS_PARAM_ == DIMENSIONS_PARAM, \"Dimensions changed\");\n\t\treturn get<3>();\n\t}\n\n\tconstexpr const Elements& elements() const noexcept {\n\t\treturn elements_;\n\t}\n\nprivate:\n\n\tElements elements_;\n\n\ttemplate <class HeadType, class... TailTypes>\n\tstatic constexpr void setTail_(\n\t\tElements& elems,\n\t\tsize_t index,\n\t\tHeadType&& head,\n\t\tTailTypes&&... tailTypes\n\t\t) noexcept\n\t{\n\t\telems[index] = std::forward<HeadType>(head);\n\t\tsetTail_(elems, index + 1, std::forward<TailTypes>(tailTypes)...);\n\t}\n\n\tstatic constexpr void setTail_(Elements&, size_t) noexcept {\n\t}\n\n};\n\ntemplate <class S, size_t D, class SEF>\nS dot(const Vector<S, D, SEF>& lhs, const Vector<S, D, SEF>& rhs) noexcept {\n\treturn lhs.dot(rhs);\n}\n\ntemplate <class S, size_t D, class SEF>\nconstexpr std::enable_if_t<D == 3, Vector<S, D, SEF>>\n\tcross(const Vector<S, D, SEF>& lhs, const Vector<S, D, SEF>& rhs) noexcept\n{\n\treturn lhs.cross(rhs);\n}\n\nusing Vec2 = Vector<float, 2>;\nstatic_assert(sizeof(Vec2) == sizeof(float) * 2, \"Empty base optimisation didn't work\");\nstatic_assert(std::is_trivially_copyable<Vec2>::value, \"Vector is not trivially copiable\");\n\nusing Vec3 = Vector<float, 3>;\nstatic_assert(sizeof(Vec3) == sizeof(float) * 3, \"Empty base optimisation didn't work\");\nstatic_assert(std::is_trivially_copyable<Vec3>::value, \"Vector is not trivially copiable\");\n\nusing Vec4 = Vector<float, 4>;\nstatic_assert(sizeof(Vec4) == sizeof(float) * 4, \"Empty base optimisation didn't work\");\nstatic_assert(std::is_trivially_copyable<Vec4>::value, \"Vector is not trivially copiable\");\n\n} // namespace math\n\n// TODO: re-enable when primitive::Vector is removed\n// using math::Vector;\nusing math::Vec2;\nusing math::Vec3;\nusing math::Vec4;\n\n} // namespace pulp\n} // namespace coconut\n\n#endif /* _COCONUT_PULP_MATH_VECTOR_HPP_ */\n", "meta": {"hexsha": "664c3982e04b0d56e11478256d72e8961cf8d169", "size": 9062, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Vector.hpp", "max_stars_repo_name": "mikosz/coconut", "max_stars_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T12:01:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T12:01:54.000Z", "max_issues_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Vector.hpp", "max_issues_repo_name": "mikosz/coconut", "max_issues_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Vector.hpp", "max_forks_repo_name": "mikosz/coconut", "max_forks_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2066666667, "max_line_length": 113, "alphanum_fraction": 0.7161774443, "num_tokens": 2309, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6034471108876156}}
{"text": "#include <iostream>\n#include <cassert>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/max_cardinality_matching.hpp>\n#include <string>\n\nconst int debug_level = 0;\n\n#define DEBUG(min_level, x)      \\\n  if (debug_level >= min_level)  \\\n  {                              \\\n    std::cerr << x << std::endl; \\\n  }\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;\n\nvoid testcase()\n{\n  int w, h;\n  std::cin >> w >> h;\n  assert(w >= 1 && w <= 50 && h >= 1 && h <= 50);\n\n  std::vector<std::vector<bool>> should_tile_at_cell(h, std::vector<bool>(w, false));\n  int num_nodes = w * h;\n  int num_nodes_to_cover = 0;\n  for (int y = 0; y < h; y++)\n  {\n    std::string row;\n    std::cin >> row;\n    assert(int(row.size()) == w);\n    for (int x = 0; x < w; x++)\n    {\n      if (row.at(x) == '.')\n      {\n        num_nodes_to_cover++;\n        should_tile_at_cell.at(y).at(x) = true;\n      }\n    }\n  }\n\n  if (num_nodes_to_cover % 2 != 0)\n  {\n    DEBUG(2, \"fast path\");\n    std::cout << \"no\\n\";\n    return;\n  }\n\n  Graph G(num_nodes);\n  auto node_at_y_x = [w, h, num_nodes](int y, int x) -> Graph::vertex_descriptor {\n    assert(x >= 0 && x < w && y >= 0 && y < h);\n    int node = y * w + x;\n    assert(node >= 0 && node < num_nodes);\n    return node;\n  };\n\n  for (int y = 0; y < h; y++)\n  {\n    for (int x = 0; x < w; x++)\n    {\n      if (!should_tile_at_cell.at(y).at(x))\n      {\n        continue;\n      }\n      if (y > 0 && should_tile_at_cell.at(y - 1).at(x))\n      {\n        DEBUG(3, \"adding vertical edge \" << y << \" \" << x);\n        boost::add_edge(node_at_y_x(y - 1, x), node_at_y_x(y, x), G);\n      }\n      if (x > 0 && should_tile_at_cell.at(y).at(x - 1))\n      {\n        DEBUG(3, \"adding horizontal edge \" << y << \" \" << x);\n        boost::add_edge(node_at_y_x(y, x - 1), node_at_y_x(y, x), G);\n      }\n    }\n  }\n\n  std::vector<Graph::vertex_descriptor> mate(num_nodes);\n  assert(boost::checked_edmonds_maximum_cardinality_matching(G, mate.data()));\n  int num_nodes_covered = 2 * boost::matching_size(G, mate.data());\n  DEBUG(2, \"num_nodes_covered \" << num_nodes_covered);\n  assert(num_nodes_covered >= 0 && num_nodes_covered <= num_nodes_to_cover);\n  std::cout << (num_nodes_covered == num_nodes_to_cover ? \"yes\\n\" : \"no\\n\");\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n\n  int t;\n  std::cin >> t;\n  assert(t >= 0 && t <= 100);\n  for (int i = 0; i < t; i++)\n  {\n    testcase();\n  }\n\n  return 0;\n}", "meta": {"hexsha": "b7fcc53f280d941193b0fb53b06b5ab39320312a", "size": 2449, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-06/tiles/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-06/tiles/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-06/tiles/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9897959184, "max_line_length": 85, "alphanum_fraction": 0.5475704369, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6034471011033686}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// standard_error_autocorrelated.hpp                                         //\n//                                                                           //\n//  Copyright 2008 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_ACCUMULATORS_STATISTICS_STANDARD_ERROR_AUTOCORRELATED_HPP_ER_2008_04\n#define BOOST_ACCUMULATORS_STATISTICS_STANDARD_ERROR_AUTOCORRELATED_HPP_ER_2008_04\n#include <cmath>\n\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/placeholders.hpp>\n\n#include <boost/call_traits.hpp>\n//#include <boost/assert.hpp>\n#include <boost/array.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/type_traits/add_const.hpp>\n\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n\n#include <boost/accumulators/statistics/integrated_acvf.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n\nnamespace boost { namespace accumulators\n{\n\n\nnamespace impl\n{\n    ////////////////////////////////////////////////////////////////////////////\n    // standard_error_autocorrelated\n    template<typename T,typename I>\n    class standard_error_autocorrelated_impl\n      : public accumulator_base\n    {\n    public:\n        typedef T result_type;\n\n        standard_error_autocorrelated_impl(dont_care)\n        {}\n\n        template<typename Args>\n        void operator()(Args const &args)\n        {\n            T iacv = integrated_acvf<I>(args[accumulator]);\n            T n = (T)(count(args));\n            val = static_cast<T>(0);\n            if((iacv>static_cast<T>(0)) && (n>static_cast<T>(0))){val = sqrt(iacv/n);}//also = sqrt(acv0/ess)\n        }\n\n        result_type result(dont_care) const\n        {\n            return val;\n        }\n    private:\n        T val;\n    };\n\n} // namespace impl\n///////////////////////////////////////////////////////////////////////////////\n// tag::integrated_acvf\n//\n\nnamespace tag\n{\n    template <typename I = default_delay_discriminator>\n    struct standard_error_autocorrelated\n      : depends_on<count,integrated_acvf<I> >\n    {\n        /// INTERNAL ONLY\n      typedef\n        accumulators::impl::standard_error_autocorrelated_impl<\n            mpl::_1,I> impl;\n\n    };\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::standard_error_autocorrelated\n//\n\nnamespace extract\n{\n\n//  extractor<tag::standard_error_autocorrelated<> >\n//    const standard_error_autocorrelated = {};\n\n  // see acvf about default_delay_discriminator\n  template<typename I,typename AccumulatorSet>\n  typename mpl::apply<\n    AccumulatorSet,tag::standard_error_autocorrelated<I>\n    >::type::result_type\n  standard_error_autocorrelated(AccumulatorSet const& acc){\n    typedef tag::standard_error_autocorrelated<I> the_tag;\n    return extract_result<the_tag>(acc);\n  }\n\n//  TODO\n//  overload (default) see acvf\n\n}\n\nusing extract::standard_error_autocorrelated;\n\n}}\n\n#endif\n", "meta": {"hexsha": "f5fdc836368b91af9dd6cd129087c00d20c66bc0", "size": 3552, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "autocovariance/boost/accumulators/statistics/standard_error_autocorrelated.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "autocovariance/boost/accumulators/statistics/standard_error_autocorrelated.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "autocovariance/boost/accumulators/statistics/standard_error_autocorrelated.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8487394958, "max_line_length": 109, "alphanum_fraction": 0.6044481982, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387914176258, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6034470887978246}}
{"text": "/*\n * This file is part of MXE.\n * See index.html for further information.\n */\n\n#include <armadillo>\n\nusing namespace arma;\n\nint main()\n{\n    mat A = randu<mat>(50,50);\n    mat B = trans(A)*A;  // generate a symmetric matrix\n\n    vec eigval;\n    mat eigvec;\n\n    // use standard algorithm by default\n    eig_sym(eigval, eigvec, B);\n\n    // use divide & conquer algorithm\n    eig_sym(eigval, eigvec, B, \"dc\");\n    return 0;\n}\n", "meta": {"hexsha": "3abff9445803b58a90adf40f640bfd743ec3727b", "size": 425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/armadillo-test.cpp", "max_stars_repo_name": "ChristianFrisson/mxe", "max_stars_repo_head_hexsha": "3451656eb93f3f31ab24f388409aadef6bcafcaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-08-12T08:03:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-08T13:21:54.000Z", "max_issues_repo_path": "src/armadillo-test.cpp", "max_issues_repo_name": "ChristianFrisson/mxe", "max_issues_repo_head_hexsha": "3451656eb93f3f31ab24f388409aadef6bcafcaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/armadillo-test.cpp", "max_forks_repo_name": "ChristianFrisson/mxe", "max_forks_repo_head_hexsha": "3451656eb93f3f31ab24f388409aadef6bcafcaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-02-04T00:24:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-24T12:40:31.000Z", "avg_line_length": 17.0, "max_line_length": 55, "alphanum_fraction": 0.6235294118, "num_tokens": 121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505966, "lm_q2_score": 0.7185943865443349, "lm_q1q2_score": 0.6034281095955658}}
{"text": "#include <Eigen/Dense>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main() {\n  ArrayXXf a(3, 3);\n  ArrayXXf b(3, 3);\n  a << 1, 2, 3,\n      4, 5, 6,\n      7, 8, 9;\n  b << 1, 2, 3,\n      1, 2, 3,\n      1, 2, 3;\n\n  // Adding two arrays\n  cout << \"a + b = \" << endl << a + b << endl << endl;\n\n  // Subtracting a scalar from an array\n  cout << \"a - 2 = \" << endl << a - 2 << endl;\n}\n", "meta": {"hexsha": "c9c8302fdf5095907149fa8122f7495baec3ea40", "size": 403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_ArrayClass_addition.cpp", "max_stars_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_stars_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_ArrayClass_addition.cpp", "max_issues_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_issues_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Eigen-3.3/doc/examples/Tutorial_ArrayClass_addition.cpp", "max_forks_repo_name": "chen0510566/CarND-Path-Planning-Project", "max_forks_repo_head_hexsha": "4652e5c459980252e4ab72a0fd687341f3245466", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5217391304, "max_line_length": 54, "alphanum_fraction": 0.4888337469, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6034281088919324}}
{"text": "#pragma once\n#include \"Optimizer.hpp\"\n\n#include <Eigen/Dense>\n#include <array>\n#include <nlohmann/json.hpp>\n\nnamespace yavque\n{\nclass SGDMomentum : public Optimizer\n{\npublic:\n\tstatic constexpr std::array<double, 4> DEFAULT_PARAMS = {0.01, 0.0, 0.9, 1e-4};\n\nprivate:\n\tdouble alpha_;\n\tdouble p_;\n\tdouble gamma_;\n\tdouble min_alpha_;\n\n\tEigen::VectorXd m_;\n\tint t_ = 0;\n\npublic:\n\texplicit SGDMomentum(double alpha = DEFAULT_PARAMS[0], double p = DEFAULT_PARAMS[1],\n\t                     double gamma = DEFAULT_PARAMS[2],\n\t                     double min_alpha = DEFAULT_PARAMS[3])\n\t\t: alpha_{alpha}, p_{p}, gamma_{gamma}, min_alpha_{min_alpha}\n\t{\n\t}\n\n\texplicit SGDMomentum(const nlohmann::json& params)\n\t\t: alpha_{params.value(\"alpha\", DEFAULT_PARAMS[0])},\n\t\t  p_{params.value(\"p\", DEFAULT_PARAMS[1])}, gamma_{params.value(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"gamma\", DEFAULT_PARAMS[2])},\n\t\t  min_alpha_{params.value(\"min_alpha\", DEFAULT_PARAMS[3])}\n\t{\n\t}\n\n\t[[nodiscard]] nlohmann::json desc() const override\n\t{\n\t\treturn nlohmann::json{{\"name\", \"SGD\"},\n\t\t                      {\"alhpa\", alpha_},\n\t\t                      {\"gamma\", gamma_},\n\t\t                      {\"p\", p_},\n\t\t                      {\"min_alpha\", min_alpha_}};\n\t}\n\n\tEigen::VectorXd getUpdate(const Eigen::VectorXd& v) override\n\t{\n\t\tusing std::pow;\n\t\tif(t_ == 0)\n\t\t{\n\t\t\tm_ = Eigen::VectorXd::Zero(v.size());\n\t\t}\n\n\t\t++t_;\n\t\tm_ *= gamma_;\n\t\tm_ += (1 - gamma_) * v;\n\t\tdouble eta\n\t\t\t= std::max((alpha_ / pow(t_, p_)), min_alpha_) / (1.0 - pow(gamma_, t_));\n\t\treturn -eta * m_;\n\t}\n};\n} // namespace yavque\n", "meta": {"hexsha": "9720ad1910aa4b2c90eb8bb751c895399e977e49", "size": 1539, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/yavque/Optimizers/SGDMomentum.hpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/yavque/Optimizers/SGDMomentum.hpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/yavque/Optimizers/SGDMomentum.hpp", "max_forks_repo_name": "chaeyeunpark/Yavque", "max_forks_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3181818182, "max_line_length": 85, "alphanum_fraction": 0.5964912281, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6034281045348913}}
{"text": "//\n// OpenTissue, A toolbox for physical based simulation and animation.\n// Copyright (C) 2007 Department of Computer Science, University of Copenhagen\n//\n#include <OpenTissue/configuration.h>\n\n#include <OpenTissue/core/math/math_basic_types.h>\n#include <OpenTissue/core/geometry/geometry_compute_distance_to_triangle.h>\n#include <cmath> // needed for std::sqrt\n\n#define BOOST_AUTO_TEST_MAIN\n#include <OpenTissue/utility/utility_push_boost_filter.h>\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n#include <OpenTissue/utility/utility_pop_boost_filter.h>\n\nBOOST_AUTO_TEST_SUITE(opentissue_geometry_util_compute_distance_to_triangle);\n\n  BOOST_AUTO_TEST_CASE(case_by_case_testing)\n  {\n    using std::sqrt;\n\n    typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;\n    typedef math_types::vector3_type                         vector3_type;\n    typedef math_types::real_type                            real_type;\n\n    real_type tol = 0.0001;\n\n    vector3_type p;\n    vector3_type pi(-5,0,0);\n    vector3_type pj(5,0,0);\n    vector3_type pk(0,5,0);\n\n    p = vector3_type(0,2.5,2);\n\n    real_type d0 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d0, 2.0, tol);\n\n    p = vector3_type(0,2.5,-2);\n    real_type d1 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d1, 2.0, tol);\n\n    p = vector3_type(0,7,0);\n    real_type d2 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d2, 2.0, tol);\n\n    p = vector3_type(-7,0,0);\n    real_type d3 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d3, 2.0, tol);\n\n    p = vector3_type(7,0,0);\n    real_type d4 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d4, 2.0, tol);\n\n    p = vector3_type(0,-2,0);\n    real_type d5 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d5, 2.0, tol);\n\n    p = vector3_type(5,5,0);\n    real_type d6 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d6, 3.5355339059327376220042218105242, tol);\n\n    p = vector3_type(-5,5,0);\n    real_type d7 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d7, 3.5355339059327376220042218105242, tol);\n\n    p = vector3_type(-5,-2,0);\n    real_type d8 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d8, 2.0, tol);\n\n    p = vector3_type(5,-2,0);\n    real_type d9 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d9, 2.0, tol);\n\n    p = vector3_type(6,1,0);\n    real_type d10 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d10, sqrt(2.0), tol );\n\n    p = vector3_type(-6,1,0);\n    real_type d11 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d11, sqrt(2.0), tol );\n\n    p = vector3_type(1,6,0);\n    real_type d12 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d12, sqrt(2.0), tol );\n\n    p = vector3_type(-1,6,0);\n    real_type d13 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d13, sqrt(2.0), tol );\n\n    p = vector3_type(0,0,1);\n    real_type d14 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d14, 1.0, tol );\n\n    p = vector3_type(5,0,1);\n    real_type d15 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d15, 1.0, tol );\n\n    p = vector3_type(-5,0,1);\n    real_type d16 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d16, 1.0, tol );\n\n    p = vector3_type(0,5,1);\n    real_type d17 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d17, 1.0, tol );\n\n    p = vector3_type(2.5,2.5,1);\n    real_type d18 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d18, 1.0, tol );\n\n    p = vector3_type(-2.5,2.5,1);\n    real_type d19 = OpenTissue::geometry::compute_distance_to_triangle(p,pi,pj,pk);\n    BOOST_CHECK_CLOSE(d19, 1.0, tol );\n\n  }\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "d373a07dc8d0a032ae4e91fbdd7ae71e1abe257c", "size": 4358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unit_tests/core/geometry/compute_distance_to_triangle/src/unit_compute_distance_to_triangle.cpp", "max_stars_repo_name": "ricortiz/OpenTissue", "max_stars_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 76.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:45:06.000Z", "max_issues_repo_path": "unit_tests/core/geometry/compute_distance_to_triangle/src/unit_compute_distance_to_triangle.cpp", "max_issues_repo_name": "ricortiz/OpenTissue", "max_issues_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2018-11-20T14:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-24T15:26:45.000Z", "max_forks_repo_path": "unit_tests/core/geometry/compute_distance_to_triangle/src/unit_compute_distance_to_triangle.cpp", "max_forks_repo_name": "ricortiz/OpenTissue", "max_forks_repo_head_hexsha": "f8c8ebc5137325b77ba90bed897f6be2795bd6fb", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2018-02-21T01:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:06:49.000Z", "avg_line_length": 36.3166666667, "max_line_length": 83, "alphanum_fraction": 0.7111060119, "num_tokens": 1338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6034280987705837}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n// random::poisson_ext::poisson_devroye::detail::parameters.hpp         \t//\n//                                                                          //\n//                                                                          //\n//  (C) Copyright 2010 Erwann Rogard                                        //\n//  Use, modification and distribution are subject to the                   //\n//  Boost Software License, Version 1.0. (See accompanying file             //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)        //\n//////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_RANDOM_POISSON_EXT_DEVROYE_DETAIL_PARAMETERS_HPP_ER_2010\n#define BOOST_RANDOM_POISSON_EXT_DEVROYE_DETAIL_PARAMETERS_HPP_ER_2010\n#include <boost/random/poisson_ext/devroye/detail/math.hpp>\n\nnamespace boost{\nnamespace random{\nnamespace poisson{\nnamespace devroye{            \nnamespace detail{       \n            \n    // These are quantities that remain fixed throughout sampling and are only\n    // modified if the poisson mean is changed.\n\ttemplate<typename Int,typename T, typename P>\n    struct parameters{\n\n\t\ttypedef devroye::detail::math<Int,T,P> ma_;\n    \n    \tpublic:\n        \n        typedef Int result_type;\n        typedef T input_type;\n        \n        parameters(){}\n    \texplicit parameters(const Int& mean)\n        {\n\t\t\tthis->m1_ \t\t= \tma_::to_float(mean);\n\t\t\tthis->m2_ \t\t= \tma_::to_float(2*mean);\t\n\t\t\tinput_type m8 \t= \tma_::to_float(8*mean);\n            input_type m32 \t= \tma_::to_float(32*mean);\n            \n            this->c1_ = ma_::to_float(1)/m8; // Equation (6)\t\t\t\n            \n            // Equation (10)\n            this->delta_ \t= \tma_::log1p( m32/ma_::pi(), P() );\t\t\n            this->delta_ \t= \tma_::sqrt(this->delta() * this->m1());\t\n\n\t\t\t// Below equation (7)\n\t\t\tthis->sd1_ = ma_::sqrt(\n            \tthis->m1() + this->delta() / ma_::to_float(2)\n            ); \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\tthis->shape2_ = this->delta() / (this->m2()+this->delta()); \n            \n            input_type a1, a2, a3, a;\n\t\t\t\n\t\t\ta1 = ma_::sqrt( ma_::pi() * (this->m2() + this->delta()) ); \n            a1 *= ma_::exp(this->c1()); \t\t\t\t\n            a2 = ma_::exp(-(this->delta()+ma_::to_float(1)) * this->shape2());\n            a2 /= this->shape2(); \t\t\t\t\t\t\n            a3 = ma_::to_float(1);\n            a = a1 + a2 + a3;\n            this->p1_ = a1 / a;\t\t\t\t\t\t\t\t\n            this->p2_ = a2 / a;\t\t\t\t\t\t\t\t\t\t\t\t\n            this->p3_ = a3 / a;\t\t\t\t\t\t\t\t\t\t\t\t\n\n\t\t\t// Reconciliation with Fortran code\n            // RL\t\t\t\t\tm1\n            // TWO\t\t\t\t\tm2\n\t\t\t// CON \t\t\t\t\tc1\n            // D \t\t\t\t\tdelta\n            // D2\t\t\t\t\tdelta + m2\n\t\t\t// D3 \t\t\t\t\t1 / shape2\n            // STDDEV \t\t\t\tsd1\n            // SUM \t\t\t\t\ta1 + a2 + a3\n            // PBODY \t\t\t\tp3 = a3/(a+a2+a3) \n\t\t\t// PTAIL \t\t\t\tp2 + p3\n\n        }\n\n\t\tstd::ostream& parameters_description(std::ostream& os)const{\n        \treturn os \n                << '('\n                << \"m1 = \" \t\t<< this->m1()\n                << ','\n                << \" m2 = \"\t\t<< this->m2()\n                << ','\n                << \" delta = \" \t<< this->delta()\n                << ','\n                << \" loc1 = \"\t<< loc1()\n                << ','\n                << \" sd1 = \" \t<< this->sd1()\n                << ','\n                << \" shape2 = \"\t<< this->shape2()\n                << ','\n                << \" c1 = \"\t\t<< this->c1()\n                << ','\n                << \" p1 = \"\t\t<< this->p1()\n                << ','\n                << \" p2 = \"\t\t<< this->p2()\n                << ','\n                << \" p3 = \"\t\t<< this->p3()\n                << ')';\n        }\n\n\t\tconst input_type& m1()const{ return this->m1_; }\n\t\tconst input_type& m2()const{ return this->m2_; }\n\t\tconst input_type& delta()const{ return this->delta_; }\n\t\tstatic input_type loc1(){ return -ma_::to_float(1)/ma_::to_float(2); }\n\t\tconst input_type& sd1()const{ return this->sd1_; }\n\t\tconst input_type& shape2()const{ return this->shape2_; }\n        const input_type& c1()const{ return this->c1_; }\n\t\tconst input_type& p1()const{ return this->p1_; }\n\t\tconst input_type& p2()const{ return this->p2_; }\n\t\tconst input_type& p3()const{ return this->p3_; }\n\n\t\tprivate:\n        input_type inv_m1_;\n\t\tinput_type m1_;\n\t\tinput_type m2_;\t\t\t\n        input_type delta_;\t\t\n\t\tinput_type sd1_;\t\t\n\t\tinput_type shape2_;\t\t\n  \n        input_type c1_;\t\t\t\n        input_type p1_;\t\t\t\n        input_type p2_;\t\t\n\t\tinput_type p3_;\n\n    };\n    \n}// detail\n}// devroye\n}// poisson\n}// random\n}// boost\n\n#endif\n", "meta": {"hexsha": "35e7161f7d776fe97774d31dd09a8827ec2f374f", "size": 4586, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "random/boost/random/poisson_ext/devroye/detail/parameters.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "random/boost/random/poisson_ext/devroye/detail/parameters.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "random/boost/random/poisson_ext/devroye/detail/parameters.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7205882353, "max_line_length": 78, "alphanum_fraction": 0.4422154383, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.6959583376458153, "lm_q1q2_score": 0.6034207732448185}}
{"text": "#include <iostream>\n#include <Eigen/Core>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <pcl/common/common_headers.h>\n#include <pcl/io/pcd_io.h>\n\n#include \"../../../core/format_helper.h\"\n#include \"../../../core/math_helper.h\"\n\nvoid SavePointCloud(const cv::Mat& img, const cv::Mat& disp_img, const double* calib)\n{\n  pcl::PointCloud<pcl::PointXYZRGB>::Ptr point_cloud(new pcl::PointCloud<pcl::PointXYZRGB>);\n\n  Eigen::Vector4d pt3d;\n  double min_disp = 1.0;\n  for (int y = 0; y < disp_img.rows; y++) {\n    for (int x = 0; x < disp_img.cols; x++) {\n      double disp = static_cast<double>(disp_img.at<uint16_t>(y,x)) / 256.0;\n      //std::cout << \"D = \" << disp << \"\\n\";\n      if (disp > min_disp) {\n        core::MathHelper::Triangulate(calib, x, y, disp, pt3d);\n        pcl::PointXYZRGB point;\n        point.x = pt3d[0];\n        point.y = pt3d[1];\n        point.z = pt3d[2];\n        if (img.channels() == 3) {\n          point.b = img.at<cv::Vec3b>(y,x)[0];\n          point.g = img.at<cv::Vec3b>(y,x)[1];\n          point.r = img.at<cv::Vec3b>(y,x)[2];\n        }\n        else if (img.channels() == 1) {\n          point.b = img.at<uint8_t>(y,x);\n          point.g = img.at<uint8_t>(y,x);\n          point.r = img.at<uint8_t>(y,x);\n        }\n        else throw 1;\n        point_cloud->points.push_back(point);\n      }\n    }\n  }\n  point_cloud->width = point_cloud->points.size();\n  point_cloud->height = 1;\n  pcl::io::savePCDFile(\"pcl.pcd\", *point_cloud);\n}\n\nint main(int argc, char** argv)\n{\n  if (argc != 4) {\n    std::cerr << \"Usage:\\n\\t\" << argv[0] << \" img disp_img calib_file\\n\";\n    return 1;\n  }\n  std::string img_path = argv[1];\n  std::string dispimg_path = argv[2];\n  std::string calib_path = argv[3];\n  double mono_cam[5];\n  double color_cam[5];\n  core::FormatHelper::ReadCalibKitti(calib_path, mono_cam, color_cam);\n\n  cv::Mat img = cv::imread(img_path, CV_LOAD_IMAGE_COLOR);\n  cv::Mat disp_img = cv::imread(dispimg_path, CV_LOAD_IMAGE_ANYDEPTH);\n  std::cout << \"Bytes per pixel = \" << disp_img.step / disp_img.cols << \"\\n\";\n\n  if (img.channels() == 3)\n    SavePointCloud(img, disp_img, color_cam);\n  else if (img.channels() == 1)\n    SavePointCloud(img, disp_img, mono_cam);\n  else throw 1;\n\n  return 0;\n}\n", "meta": {"hexsha": "54d8b0f05ab35f399c70fd80ea28f807c5545cf7", "size": 2249, "ext": "cc", "lang": "C++", "max_stars_repo_path": "reconstruction/main/convert_img_to_pcd/main.cc", "max_stars_repo_name": "bartn8/stereo-vision", "max_stars_repo_head_hexsha": "1180045fe560478e5c441e75202cc899fe90ec3d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2016-04-02T18:18:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T11:47:58.000Z", "max_issues_repo_path": "reconstruction/main/convert_img_to_pcd/main.cc", "max_issues_repo_name": "bartn8/stereo-vision", "max_issues_repo_head_hexsha": "1180045fe560478e5c441e75202cc899fe90ec3d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-08-01T14:36:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T08:15:50.000Z", "max_forks_repo_path": "reconstruction/main/convert_img_to_pcd/main.cc", "max_forks_repo_name": "bartn8/stereo-vision", "max_forks_repo_head_hexsha": "1180045fe560478e5c441e75202cc899fe90ec3d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2016-08-25T11:28:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T12:17:47.000Z", "avg_line_length": 31.2361111111, "max_line_length": 92, "alphanum_fraction": 0.5993775011, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736773, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6034207653859927}}
{"text": "#include <iostream>\n\n#include <harp_test.hpp>\n\n#include <boost/random.hpp>\n\nusing namespace std;\nusing namespace harp;\n\n\nvoid harp::test_tinyKLT ( string const & datadir ) {\n\n  cerr << \"Testing tiny KLT transform...\" << endl;\n\n  cerr.precision(16);\n  \n  // construct synthetic design matrix\n\n  size_t nbins = 25;\n  size_t npix = 225;\n  \n  mat_compcol projmat ( npix, nbins );\n\n  // loop over traces\n  for ( size_t i = 0; i < 5; ++i ) {\n\n    // loop over bins\n    for ( size_t j = 0; j < 5; ++j ) {\n      size_t pixrow = 3 * j + 1;\n      size_t pixcol = 3 * i + 1;\n\n      // center pixel = 100\n      projmat( 15 * pixrow + pixcol, 5 * i + j ) = 100.0;\n\n      // 4 neigbors = 10\n      projmat( 15 * (pixrow - 1) + pixcol, 5 * i + j ) = 10.0;\n      projmat( 15 * (pixrow + 1) + pixcol, 5 * i + j ) = 10.0;\n      projmat( 15 * pixrow + (pixcol - 1), 5 * i + j ) = 10.0;\n      projmat( 15 * pixrow + (pixcol + 1), 5 * i + j ) = 10.0;\n    }\n  }\n\n  // construct fake spectra\n\n  vec_dense truespec ( nbins );\n  for ( size_t i = 0; i < 5; ++i ) {\n    for ( size_t j = 0; j < 5; ++j ) {\n      truespec( 5 * i + j ) = (double)( 4 * (i + 1) * (j + 1) );\n    }\n  }\n\n  // compute noiseless image\n\n  vec_dense noiseless ( npix );\n\n  boost::numeric::ublas::axpy_prod ( projmat, truespec, noiseless, true );\n\n  // compute noise realization\n\n  vec_dense imgnoise ( npix );\n  vec_dense measured ( npix );\n\n  typedef boost::ecuyer1988 base_generator_type;\n  base_generator_type generator(42u);\n  \n  vec_dense rms ( npix );\n  \n  for ( size_t i = 0; i < npix; ++i ) {\n    rms[i] = sqrt( 16.0 + noiseless[i] );\n    \n    boost::normal_distribution < double > dist ( 0.0, rms[i] );\n    \n    boost::variate_generator < base_generator_type&, boost::normal_distribution < double > > gauss ( generator, dist );\n    \n    imgnoise[i] = gauss();\n\n    measured[i] = noiseless[i] + imgnoise[i];\n  }\n\n  // construct inverse pixel noise covariance\n\n  mat_comprow invnoise ( npix, npix, npix );\n\n  for ( size_t i = 0; i < npix; ++i ) {\n    invnoise ( i, i ) = 1.0 / ( rms[i] * rms[i] );\n  }\n\n  // construct rhs\n\n  vec_dense z ( nbins );\n\n  noise_weighted_spec ( projmat, invnoise, measured, z );\n  //noise_weighted_spec < mat_compcol, mat_comprow, vec_dense > ( projmat, invnoise, measured, z );\n\n  // construct the inverse spectral covariance matrix\n\n  mat_comprow invcov ( nbins, nbins );\n\n  mat_dynrow builder ( nbins, nbins );\n\n  mat_compcol temp ( npix, nbins );\n\n  boost::numeric::ublas::axpy_prod ( invnoise, projmat, temp, true );\n\n  boost::numeric::ublas::axpy_prod ( boost::numeric::ublas::trans ( projmat ), temp, builder, true );\n\n  mat_dynrow::iterator2 itcol;\n  mat_dynrow::iterator1 itrow;\n\n  for ( itcol = builder.begin2(); itcol != builder.end2(); ++itcol ) {\n    for ( itrow = itcol.begin(); itrow != itcol.end(); ++itrow ) {\n      invcov ( itrow.index1(), itrow.index2() ) = (*itrow);\n    }\n  }\n  \n  // extraction\n\n  vec_dense outspec ( nbins );\n\n  extract_dense ( invcov, z, outspec );\n\n  /*\n  for ( size_t i = 0; i < 5; ++i ) {\n    for ( size_t j = 0; j < 5; ++j ) {\n      cerr << \"(\" << i << \",\" << j << \") \" << truespec( 5 * i + j ) << \" \" << outspec( 5 * i + j) << \" +/- \" << 1.0 / sqrt( invcov(5*i+j, 5*i+j) ) << endl;\n    }\n  }\n  */\n\n  string kltspecout = datadir + \"/test_klt_spec.out\";\n  string kltimgout = datadir + \"/test_klt_img.out\";\n\n  fstream out;\n  out.precision(16);\n\n  out.open ( kltimgout.c_str(), ios::out );\n  out.precision(16);\n\n  for ( int64_t i = 0; i < npix; ++i ) {\n    out << noiseless[i] << \" \" << imgnoise[i] << \" \" << measured[i] << endl;\n  }\n\n  out.close();\n\n  out.open ( kltspecout.c_str(), ios::out );\n  out.precision(16);\n\n  for ( int64_t i = 0; i < nbins; ++i ) {\n    out << truespec[i] << \" \" << outspec[i] << \" \" << 1.0 / sqrt( invcov(i,i) ) << endl;\n  }\n\n  out.close();\n  \n  cerr << \"  (PASSED)\" << endl;\n\n  return;\n}\n\n", "meta": {"hexsha": "dcd8c661cae35cbdc6518b7af73eccdb114d25cc", "size": 3839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tests-mpi/harp_test_tinyKLT.cpp", "max_stars_repo_name": "tskisner/HARP", "max_stars_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests-mpi/harp_test_tinyKLT.cpp", "max_issues_repo_name": "tskisner/HARP", "max_issues_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests-mpi/harp_test_tinyKLT.cpp", "max_forks_repo_name": "tskisner/HARP", "max_forks_repo_head_hexsha": "e21435511c3dc95ce1318c852002a95ca59634b1", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1446540881, "max_line_length": 155, "alphanum_fraction": 0.5647303985, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6034207592329048}}
{"text": "\n// BLAS level 2\n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <iostream>\n#include <boost/numeric/bindings/atlas/cblas1.hpp>\n#include <boost/numeric/bindings/atlas/cblas2.hpp>\n#include <boost/numeric/bindings/traits/ublas_vector.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include \"utils.h\" \n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::cout;\nusing std::endl; \n\ntypedef ublas::vector<double> vct_t;\ntypedef ublas::matrix<double, ublas::row_major> rm_t;\ntypedef ublas::matrix<double, ublas::column_major> cm_t;\n\nint main() {\n\n  cout << endl; \n\n  vct_t vx (2);\n  vct_t vy (4); \n\n  // row major matrix\n  rm_t rm (2, 4);\n  init_m (rm, const_val<double> (0)); \n  print_m (rm, \"row major matrix m\"); \n  cout << endl; \n\n  vx(0) = 1.; \n  vy(1) = 1.; \n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += x y^T\n  atlas::ger (vx, vy, rm); \n  print_m (rm, \"m += x y^T\"); \n  cout << endl << endl; \n\n  init_m (rm, const_val<double> (1)); \n  print_m (rm, \"m\"); \n  cout << endl; \n\n  atlas::set (1., vx);\n  atlas::set (1., vy);\n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += 2 x y^T\n  atlas::ger (2., vx, vy, rm); \n  print_m (rm, \"m += 2 x y^T\"); \n  cout << endl << endl; \n\n  init_v (vx, iplus1());\n  init_v (vy, iplus1());\n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += x y^T\n  atlas::ger (vx, vy, rm); \n  print_m (rm, \"m += x y^T\"); \n  cout << endl << endl; \n\n  // column major matrix\n  cm_t cm (2, 4);\n  init_m (cm, const_val<double> (0)); \n  print_m (cm, \"column major matrix m\"); \n  cout << endl; \n\n  vx(0) = 1.; \n  vy(1) = 1.; \n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += x y^T\n  atlas::ger (vx, vy, cm); \n  print_m (cm, \"m += x y^T\"); \n  cout << endl << endl; \n\n  init_m (cm, const_val<double> (1)); \n  print_m (cm, \"m\"); \n  cout << endl; \n\n  atlas::set (1., vx);\n  atlas::set (1., vy);\n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += 2 x y^T\n  atlas::ger (2., vx, vy, cm); \n  print_m (cm, \"m += 2 x y^T\"); \n  cout << endl << endl; \n\n  init_v (vx, iplus1());\n  init_v (vy, iplus1());\n  print_v (vx, \"vx\"); \n  cout << endl; \n  print_v (vy, \"vy\"); \n  cout << endl; \n\n  // m += x y^T\n  atlas::ger (vx, vy, cm); \n  print_m (cm, \"m += x y^T\"); \n  cout << endl << endl; \n\n}\n", "meta": {"hexsha": "8f82f07c5c22fc7ceecdea5fd36e292d0c7e0d10", "size": 2517, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_matr2ger.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_matr2ger.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_matr2ger.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 20.2983870968, "max_line_length": 57, "alphanum_fraction": 0.5550258244, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6034141850200332}}
{"text": "\n/*!\n * @file \n * @brief \n * @copyright alphya 2018-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_VALUE_INCLUDING_ERROR_HPP\n#define NYARUGA_UTIL_VALUE_INCLUDING_ERROR_HPP\n\n#pragma once\n\n#include <nyaruga_util/partial_diff.hpp>\n#include <nyaruga_util/diff.hpp>\n#include <boost/hana/functional/arg.hpp>\n\nnamespace nyaruga {\n\nnamespace util {\n\n// \u8aa4\u5dee\u3092\u542b\u3080\u5024\nstruct value_including_error {\n   num_t value; // \u5024\n   num_t error; // \u8aa4\u5dee\n   operator num_t() { return value; }\n   operator num_t() const { return value; }\n};\n\nnamespace nyaruga_util_impl {\n\n// \u504f\u5fae\u5206^2 * \u8aa4\u5dee^2 \u3092\u3001\u4e00\u5909\u6570\u5206\u3060\u3051\u8a08\u7b97\u3057\u3066\u3001\u518d\u5e30\ntemplate <std::size_t count, std::size_t max, typename F, typename... Args>\ndecltype(auto) generate_error_impl(F && f, Args &&... args)\n{\n   if constexpr (count > max)\n      return num_t{ 0 };\n   else {\n      auto && current_val_obj = boost::hana::arg<count>(args...);\n      auto && current_val_error = current_val_obj.error;\n      auto && partial_diff = nyaruga::util::partial_diff<count>(f)(static_cast<num_t>(args)...);\n      auto && result = boost::multiprecision::pow(partial_diff, 2) *\n                       boost::multiprecision::pow(current_val_error, 2);\n      return static_cast<num_t>(result + generate_error_impl<count + 1, max>(std::forward<F>(f), std::forward<Args>(args)...));\n   }\n}\n\n} // namespace nyaruga_util_impl\n\n// \u8aa4\u5dee\u306e\u4f1d\u64ad\u5f0f\u3088\u308a\u3001\u8a08\u7b97\u3002\u8aa4\u5dee\u3092\u8fd4\u3059\n// Args \u306b\u306f\u3001value_including_error\u3092\u4f7f\u7528\u3057\u3066\u304f\u3060\u3055\u3044\ntemplate <typename F, typename... Args>\ndecltype(auto) generate_error(F && f, Args &&... args)\n{\n   return static_cast<num_t>(boost::multiprecision::pow(\n      nyaruga_util_impl::generate_error_impl<1, sizeof...(args)>(std::forward<F>(f), std::forward<decltype(args)>(args)...), 0.5l));\n}\n\n} // namespace nyaruga_util\n\n/*\n#include \"value_including_error.hpp\"\n#include <iostream>\nauto main() -> int\n{\n   // \u8aa4\u5dee\u3092\u542b\u3080\u5024\u306e\u5b9a\u7fa9 { \u5024, \u8aa4\u5dee }\n   auto&& x = nyaruga::util::value_including_error{ 20, 0.5 };\n   auto&& y = nyaruga::util::value_including_error{ 50, 0.8 };\n   // \u8aa4\u5dee\u3092\u542b\u3080\u5024\u306e\u95a2\u6570\u5b9a\u7fa9\u3000\u3053\u308c\u306f\u5358\u7d14\u306a\u639b\u3051\u7b97\n   decltype(auto) f = [](nyaruga::util::num_t x, nyaruga::util::num_t y) {\n      return static_cast<nyaruga::util::num_t>(x * y);\n   };\n   // \u666e\u901a\u306b\u95a2\u6570\u3092\u5b9f\u884c\u3057\u305f\u5024\n   auto&& v = f(x, y);\n   // \u8aa4\u5dee\u3092\u8a08\u7b97\n   auto&& e = nyaruga::util::generate_error(f, x, y);\n   // \u3060\u3044\u305f\u3044\u3042\u3063\u3066\u308b\u7a0b\u5ea6\u306e\u5024\u3067\u3059\n   // \u5358\u7d14\u306a\u639b\u3051\u7b97\u3067\u3001\u6709\u52b9\u6570\u5b5717\u6841\u304f\u3089\u3044\u3067\u3057\u305f\n   std::cout << std::setprecision(18)\n      << \"\u5024\u306f\uff1a\" << v << \"\\n\u8aa4\u5dee\u306f\uff1a\" << e << \"\\n\";\n}\n*/\n\n#endif // #ifndef NYARUGA_UTIL_VALUE_INCLUDING_ERROR_HPP", "meta": {"hexsha": "f99ff0f6069fc16761dc0fcb13d799680d338aea", "size": 2519, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nyaruga_util/value_including_error.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/value_including_error.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/value_including_error.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": 29.6352941176, "max_line_length": 132, "alphanum_fraction": 0.6689162366, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192066862062, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.603276937614174}}
{"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\r\n/*\r\n\r\n    This is an example illustrating the use of the Hough transform tool in the\r\n    dlib C++ Library.\r\n\r\n\r\n    In this example we are going to draw a line on an image and then use the\r\n    Hough transform to detect the location of the line.  Moreover, we do this in\r\n    a loop that changes the line's position slightly each iteration, which gives\r\n    a pretty animation of the Hough transform in action.\r\n*/\r\n\r\n#include <dlib/gui_widgets.h>\r\n#include <dlib/image_transforms.h>\r\n\r\nusing namespace dlib;\r\n\r\nint main()\r\n{\r\n    // First let's make a 400x400 image.  This will form the input to the Hough transform.\r\n    array2d<unsigned char> img(400,400);\r\n    // Now we make a hough_transform object.  The 300 here means that the Hough transform\r\n    // will operate on a 300x300 subwindow of its input image.  \r\n    hough_transform ht(300);\r\n\r\n    image_window win, win2;\r\n    double angle1 = 0;\r\n    double angle2 = 0;\r\n    while(true)\r\n    {\r\n        // Generate a line segment that is rotating around inside the image.  The line is\r\n        // generated based on the values in angle1 and angle2. So each iteration creates a\r\n        // slightly different line.\r\n        angle1 += pi/130;\r\n        angle2 += pi/400;\r\n        const point cent = center(get_rect(img));  \r\n        // A point 90 pixels away from the center of the image but rotated by angle1.\r\n        const point arc = rotate_point(cent, cent + point(90,0), angle1); \r\n        // Now make a line that goes though arc but rotate it by angle2.\r\n        const point l = rotate_point(arc, arc + point(500,0), angle2);\r\n        const point r = rotate_point(arc, arc - point(500,0), angle2);\r\n\r\n\r\n        // Next, blank out the input image and then draw our line on it.\r\n        assign_all_pixels(img, 0);\r\n        draw_line(img, l, r, 255);\r\n\r\n         \r\n        const point offset(50,50);\r\n        array2d<int> himg;\r\n        // pick the window inside img on which we will run the Hough transform.\r\n        const rectangle box = translate_rect(get_rect(ht),offset);\r\n        // Now let's compute the hough transform for a subwindow in the image.  In\r\n        // particular, we run it on the 300x300 subwindow with an upper left corner at the\r\n        // pixel point(50,50).  The output is stored in himg.\r\n        ht(img, box, himg);\r\n        // Now that we have the transformed image, the Hough image pixel with the largest\r\n        // value should indicate where the line is.  So we find the coordinates of the\r\n        // largest pixel:\r\n        point p = max_point(mat(himg));\r\n        // And then ask the ht object for the line segment in the original image that\r\n        // corresponds to this point in Hough transform space.\r\n        std::pair<point,point> line = ht.get_line(p);\r\n\r\n        // Finally, let's display all these things on the screen.  We copy the original\r\n        // input image into a color image and then draw the detected line on top in red.\r\n        array2d<rgb_pixel> temp;\r\n        assign_image(temp, img);\r\n        // Note that we must offset the output line to account for our offset subwindow.\r\n        // We do this by just adding in the offset to the line endpoints. \r\n        draw_line(temp, line.first+offset, line.second+offset, rgb_pixel(255,0,0));\r\n        win.clear_overlay();\r\n        win.set_image(temp);\r\n        // Also show the subwindow we ran the Hough transform on as a green box.  You will\r\n        // see that the detected line is exactly contained within this box and also\r\n        // overlaps the original line.\r\n        win.add_overlay(box, rgb_pixel(0,255,0));\r\n\r\n        // We can also display the Hough transform itself using the jet color scheme.\r\n        win2.set_image(jet(himg));\r\n    }\r\n}\r\n\r\n", "meta": {"hexsha": "b89ef69e5796e308de417931f3e4d97cb39868d8", "size": 3815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/hough_transform_ex.cpp", "max_stars_repo_name": "ckproc/dlib-19.7", "max_stars_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/hough_transform_ex.cpp", "max_issues_repo_name": "ckproc/dlib-19.7", "max_issues_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-02-27T15:44:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-28T01:26:03.000Z", "max_forks_repo_path": "examples/hough_transform_ex.cpp", "max_forks_repo_name": "ckproc/dlib-19.7", "max_forks_repo_head_hexsha": "0ca40f5e85de2436e557bee9a805d3987d2d9507", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8823529412, "max_line_length": 92, "alphanum_fraction": 0.647706422, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.603276550803892}}
{"text": "#include <bits/stdc++.h>\n#include <boost/tokenizer.hpp>\n\nint64_t departure_time;\nstd::vector<int64_t> buses;\nstd::vector<std::pair<int64_t, int64_t>> buses_ids;\n\nstruct Euclid {\n  int64_t mi, mj;\n};\n\nint64_t next_time(const int64_t bus, int64_t departure_time) {\n  return bus * (departure_time / bus + 1) % departure_time;\n}\n\nvoid part1() {\n  auto comp = [&] (const int64_t b1, const int64_t b2) {\n    return next_time(b1, departure_time) < next_time(b2, departure_time);\n  };\n  int64_t best_bus = *(std::min_element(buses.begin(), buses.end(), comp));\n  int64_t time = next_time(best_bus, departure_time);\n  int64_t res = best_bus * time;\n\n  std::cout << \"Part 1 : \" << res << std::endl;\n}\n\nint64_t get_modulo(int64_t ni, int64_t bi) {\n  int64_t xi = (ni - bi);\n  while (xi < 0)\n    xi += ni;\n  return xi % ni;\n}\n\nvoid part2() {\n  int64_t res = 0;\n\n  bool first = true;\n  int64_t xi, ni;\n\n  // Init \n  auto cur = buses_ids.begin();\n  ni = cur->second;\n  xi = get_modulo(ni, cur->first);\n  auto next = std::next(cur);\n\n  // Chinese remainder theorem !\n  while (next != buses_ids.end()) {\n    int64_t nip1 = next->second;\n    int64_t ai = get_modulo(nip1, next->first);\n    std::cout << xi << \" \" << nip1 << \" \" << ai << std::endl;\n    while (xi % nip1 != ai)\n      xi += ni;\n\n    ni *= nip1; \n\n    cur = next;\n    std::advance(next, 1);\n  }\n  \n  std::cout << \"Part 2 : \" << xi << std::endl;\n}\n\n\nint main(int argc, char **argv) {\n  std::ifstream f_in;\n  f_in.open(\"13.in\");\n  std::string line;\n  std::getline(f_in, line);\n  departure_time = std::stoi(line);\n  std::getline(f_in, line);\n  f_in.close();\n  \n  boost::char_separator<char> sep{\",\", \"\"};  \n  boost::tokenizer tokenizer{line, sep};\n\n  int tok = -1;\n  for (const auto &t: tokenizer) {\n    tok++;\n    if (t == \"x\")\n      continue;\n    int64_t bus_id = std::stoi(t);\n    buses.push_back(bus_id);\n    buses_ids.push_back(std::make_pair(tok, bus_id));\n    std::cout << tok << \" \" << bus_id << std::endl;\n  }\n\n  part1();\n  part2();\n\n  return 0;\n}", "meta": {"hexsha": "492b603a1b1a630133bb42619b0a17b64cf94f06", "size": 1999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/13.cpp", "max_stars_repo_name": "mdelorme/advent_of_code", "max_stars_repo_head_hexsha": "47142d501055fc0d36989db9b189be7e6756d779", "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": "2020/13.cpp", "max_issues_repo_name": "mdelorme/advent_of_code", "max_issues_repo_head_hexsha": "47142d501055fc0d36989db9b189be7e6756d779", "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": "2020/13.cpp", "max_forks_repo_name": "mdelorme/advent_of_code", "max_forks_repo_head_hexsha": "47142d501055fc0d36989db9b189be7e6756d779", "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": 21.967032967, "max_line_length": 75, "alphanum_fraction": 0.6013006503, "num_tokens": 635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.6584175005616829, "lm_q1q2_score": 0.6031826020200751}}
{"text": "\n// solving A * X = B\n// A symmetric/hermitian positive definite in packed format \n// driver function posv()\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/lapack/ppsv.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_symmetric.hpp>\n#include <boost/numeric/bindings/traits/ublas_hermitian.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef double real_t; \ntypedef std::complex<real_t> cmplx_t; \n\ntypedef ublas::matrix<real_t, ublas::column_major> m_t;\ntypedef ublas::matrix<cmplx_t, ublas::column_major> cm_t;\n\ntypedef \n  ublas::symmetric_matrix<real_t, ublas::lower, ublas::column_major> symml_t; \ntypedef \n  ublas::hermitian_matrix<cmplx_t, ublas::lower, ublas::column_major> herml_t; \n\ntypedef \n  ublas::symmetric_matrix<real_t, ublas::upper, ublas::column_major> symmu_t; \ntypedef \n  ublas::hermitian_matrix<cmplx_t, ublas::upper, ublas::column_major> hermu_t; \n\nint main() {\n\n  cout << endl; \n\n  // symmetric \n  cout << \"real symmetric\\n\" << endl; \n\n  size_t n = 5; \n  size_t nrhs = 2; \n  symml_t sal (n, n);   // symmetric matrix\n  symmu_t sau (n, n);   // symmetric matrix\n  m_t x (n, nrhs);\n  m_t bl (n, nrhs), bu (n, nrhs);  // RHS matrices\n\n  init_symm (sal, 'l'); \n  //        [5 0 0 0 0]\n  //        [4 5 0 0 0]\n  //   al = [3 4 5 0 0]\n  //        [2 3 4 5 0]\n  //        [1 2 3 4 5]\n\n  init_symm (sau, 'u'); \n  //        [5 4 3 2 1]\n  //        [0 5 4 3 2]\n  //   au = [0 0 5 4 3]\n  //        [0 0 0 5 4]\n  //        [0 0 0 0 5]\n\n  print_m (sal, \"sal\"); \n  cout << endl; \n  print_m_data (sal, \"sal\"); \n  cout << endl; \n\n  print_m (sau, \"sau\"); \n  cout << endl; \n  print_m_data (sau, \"sau\"); \n  cout << endl; \n\n  for (int i = 0; i < x.size1(); ++i) {\n    x (i, 0) = 1.;\n    x (i, 1) = 2.; \n  }\n  bl = prod (sal, x); \n  bu = prod (sau, x); \n\n  print_m (bl, \"bl\"); \n  cout << endl; \n  print_m (bu, \"bu\"); \n  cout << endl; \n\n  lapack::ppsv (sal, bl);  \n  print_m (bl, \"xl\"); \n  cout << endl; \n\n  lapack::ppsv (sau, bu);  \n  print_m (bu, \"xu\"); \n  cout << endl; \n\n\n  //////////////////////////////////////////////////////////\n  // hermitian \n  cout << \"\\n==========================================\\n\" << endl; \n  cout << \"complex hermitian (well, not really ;o)\\n\" << endl; \n\n  herml_t hal (3, 3);   // hermitian matrix\n  hermu_t hau (3, 3);   // hermitian matrix\n  cm_t cx (3, 1); \n  cm_t cbl (3, 1), cbu (3, 1);  // RHS\n\n  init_symm (hal, 'l'); \n  init_symm (hau, 'u'); \n\n  print_m (hal, \"hal\"); \n  cout << endl; \n  print_m (hau, \"hau\"); \n  cout << endl; \n\n  for (int i = 0; i < cx.size1(); ++i) \n    cx (i, 0) = cmplx_t (1, -1); \n  print_m (cx, \"cx\"); \n  cout << endl; \n  cbl = prod (hal, cx);\n  cbu = prod (hau, cx);\n  print_m (cbl, \"cbl\"); \n  cout << endl; \n  print_m (cbu, \"cbu\"); \n  cout << endl; \n\n  int ierr = lapack::ppsv (hal, cbl); \n  if (ierr == 0)\n    print_m (cbl, \"cxl\"); \n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n  ierr = lapack::ppsv (hau, cbu); \n  if (ierr == 0)\n    print_m (cbu, \"cxu\"); \n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n  cout << \"\\n===========================\\n\" << endl; \n  cout << \"complex hermitian\\n\" << endl; \n\n  // regular (see ublas_gesv.cc), but not positive definite: \n\n  hal (0, 0) = cmplx_t (3, 0);\n  hal (1, 0) = cmplx_t (4, -2);\n  hal (1, 1) = cmplx_t (5, 0);\n  hal (2, 0) = cmplx_t (-7, -5);\n  hal (2, 1) = cmplx_t (0, 3);\n  hal (2, 2) = cmplx_t (2, 0);\n\n  hau (0, 0) = cmplx_t (3, 0);\n  hau (0, 1) = cmplx_t (4, 2);\n  hau (0, 2) = cmplx_t (-7, 5);\n  hau (1, 1) = cmplx_t (5, 0);\n  hau (1, 2) = cmplx_t (0, -3);\n  hau (2, 2) = cmplx_t (2, 0);\n\n  print_m (hal, \"hal\"); \n  cout << endl; \n  print_m (hau, \"hau\"); \n  cout << endl; \n\n  for (int i = 0; i < cx.size1(); ++i) \n    cx (i, 0) = cmplx_t (1, 1); \n  print_m (cx, \"cx\"); \n  cout << endl; \n  cbl = prod (hal, cx);\n  cbu = prod (hau, cx);\n  print_m (cbl, \"cbl\"); \n  cout << endl; \n  print_m (cbu, \"cbu\"); \n  cout << endl; \n\n  ierr = lapack::ppsv (hal, cbl); \n  if (ierr == 0)\n    print_m (cbl, \"cxl\"); \n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n  ierr = lapack::ppsv (hau, cbu); \n  if (ierr == 0)\n    print_m (cbu, \"cxu\"); \n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n  cout << \"\\n===========================\\n\" << endl; \n  cout << \"complex hermitian\\n\" << endl; \n\n  // positive definite: \n\n  hal (0, 0) = cmplx_t (25, 0);\n  hal (1, 0) = cmplx_t (-5, 5);\n  hal (1, 1) = cmplx_t (51, 0);\n  hal (2, 0) = cmplx_t (10, -5);\n  hal (2, 1) = cmplx_t (4, 6);\n  hal (2, 2) = cmplx_t (71, 0);\n\n  hau (0, 0) = cmplx_t (25, 0);\n  hau (0, 1) = cmplx_t (-5, -5);\n  hau (0, 2) = cmplx_t (10, 5);\n  hau (1, 1) = cmplx_t (51, 0);\n  hau (1, 2) = cmplx_t (4, -6);\n  hau (2, 2) = cmplx_t (71, 0);\n\n  print_m (hal, \"hal\"); \n  cout << endl; \n  print_m (hau, \"hau\"); \n  cout << endl; \n\n  cm_t cbl2 (3, 2); \n  cbl2 (0, 0) = cmplx_t (60, -55);\n  cbl2 (1, 0) = cmplx_t (34, 58);\n  cbl2 (2, 0) = cmplx_t (13, -152);\n  cbl2 (0, 1) = cmplx_t (70, 10);\n  cbl2 (1, 1) = cmplx_t (-51, 110);\n  cbl2 (2, 1) = cmplx_t (75, 63);\n  cm_t cbu2 (cbl2); \n  print_m (cbl2, \"cbl\"); \n  cout << endl; \n  \n  ierr = lapack::ppsv (hal, cbl2); \n  if (ierr == 0)\n    print_m (cbl2, \"cxl\"); \n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl << endl; \n  cout << endl; \n\n  ierr = lapack::ppsv (hau, cbu2); \n  if (ierr == 0)\n    print_m (cbu2, \"cxu\"); \n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl << endl; \n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "0e54657330ec9788b144118387e6c07b0a6595cb", "size": 5864, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_ppsv.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_ppsv.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_ppsv.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 23.837398374, "max_line_length": 79, "alphanum_fraction": 0.5204638472, "num_tokens": 2384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.6030502460453757}}
{"text": "#define BOOST_TEST_MODULE pcraster geo fraction_filter\n#include <boost/test/unit_test.hpp>\n#include \"dal_MathUtils.h\"\n#include \"geo_mooreneighbourhood.h\"\n#include \"geo_filterengine.h\"\n#include \"geo_fractionfilter.h\"\n\n\nBOOST_AUTO_TEST_CASE(test)\n{\n  using namespace geo;\n\n  // Fraction of true cells in a filter.\n\n  // 1 0 0\n  // 0 1 MV\n  // 0 0 1\n  SimpleRaster<UINT1> source(3, 3);\n  source.cell(0) = 1;\n  source.cell(1) = 0;\n  source.cell(2) = 0;\n  source.cell(3) = 0;\n  source.cell(4) = 1;\n  source.setMV(5);\n  source.cell(6) = 0;\n  source.cell(7) = 0;\n  source.cell(8) = 1;\n\n  SquareNeighbourhood weights(1);\n  FractionFilter<UINT1> filter(weights, 1);\n\n  // 2/4 2/5 1/3\n  // 2/6 3/8 MV\n  // 1/4 2/5 2/3\n  SimpleRaster<REAL8> destination(3, 3);\n\n  FilterEngine<UINT1, REAL8> engine(source, filter, destination);\n  engine.calc();\n\n  BOOST_CHECK(dal::comparable(destination.cell(0), 2.0 / 4.0));\n  BOOST_CHECK(dal::comparable(destination.cell(1), 2.0 / 5.0));\n  BOOST_CHECK(dal::comparable(destination.cell(2), 1.0 / 3.0));\n  BOOST_CHECK(dal::comparable(destination.cell(3), 2.0 / 6.0));\n  BOOST_CHECK(dal::comparable(destination.cell(4), 3.0 / 8.0));\n  BOOST_CHECK(destination.isMV(5));\n  BOOST_CHECK(dal::comparable(destination.cell(6), 1.0 / 4.0));\n  BOOST_CHECK(dal::comparable(destination.cell(7), 2.0 / 5.0));\n  BOOST_CHECK(dal::comparable(destination.cell(8), 2.0 / 3.0));\n}\n", "meta": {"hexsha": "42deb012dd7324faa7a5ebca64383a25222d8549", "size": 1384, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_fractionfiltertest.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_fractionfiltertest.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcrgeo/geo_fractionfiltertest.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.68, "max_line_length": 65, "alphanum_fraction": 0.6777456647, "num_tokens": 493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6030502317131243}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <vector>\n#include <limits>\n\n#include <Eigen/Core>\n\n#include <boost/test/unit_test.hpp>\n\n#include \"tudat/basics/testMacros.h\"\n#include \"tudat/math/basic/mathematicalConstants.h\"\n#include \"tudat/math/statistics/randomSampling.h\"\n#include \"tudat/math/statistics/basicStatistics.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nBOOST_AUTO_TEST_SUITE( test_Random_Sampler )\n\nBOOST_AUTO_TEST_CASE( test_randomVectorUniform )\n{\n    int dimension = 3;\n    int numberOfSamples = 1E6;\n    int seed = 511;\n\n    Eigen::VectorXd lower( dimension );\n    Eigen::VectorXd upper( dimension );\n    lower << 0.0, 1.0, -2.0;\n    upper << 1.0, 3.0, 4.0;\n\n    Eigen::VectorXd width = upper - lower;\n    Eigen::VectorXd average = (upper + lower) / 2.0;\n\n    Eigen::VectorXd standardDeviation = std::sqrt( 1.0 / 12.0 ) * width;\n    {\n        std::vector< Eigen::VectorXd > samples =\n                tudat::statistics::generateUniformRandomSample( seed, numberOfSamples, lower, upper );\n\n        // Compute sample mean and standard deviation\n        Eigen::VectorXd sampleMean = statistics::computeSampleMean( samples );\n        Eigen::ArrayXd sampleStandardDeviations = statistics::computeSampleVariance( samples ).array( ).sqrt( );\n\n        BOOST_CHECK_SMALL( std::fabs( average( 0 ) - sampleMean( 0 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( average( 1 ) - sampleMean( 1 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( average( 2 ) - sampleMean( 2 ) ), 5.0E-3 );\n\n        BOOST_CHECK_SMALL( std::fabs( standardDeviation( 0 ) - sampleStandardDeviations( 0 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( standardDeviation( 1 ) - sampleStandardDeviations( 1 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( standardDeviation( 2 ) - sampleStandardDeviations( 2 ) ), 5.0E-3 );\n    }\n\n    {\n        std::vector< Eigen::VectorXd > samples = tudat::statistics::generateUniformRandomSample( seed, numberOfSamples, dimension );\n\n        // Compute sample mean and standard deviation\n        Eigen::VectorXd sampleMean = statistics::computeSampleMean( samples );\n        Eigen::ArrayXd sampleStandardDeviations = statistics::computeSampleVariance( samples ).array( ).sqrt( );\n\n        BOOST_CHECK_SMALL( std::fabs( 0.5 - sampleMean( 0 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( 0.5 - sampleMean( 1 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( 0.5 - sampleMean( 2 ) ), 5.0E-3 );\n\n        BOOST_CHECK_SMALL( std::fabs( std::sqrt( 1.0 / 12.0 ) - sampleStandardDeviations( 0 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( std::sqrt( 1.0 / 12.0 ) - sampleStandardDeviations( 1 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( std::sqrt( 1.0 / 12.0 ) - sampleStandardDeviations( 2 ) ), 5.0E-3 );\n    }\n}\n\nBOOST_AUTO_TEST_CASE( test_randomVectorGaussian )\n{\n    int dimension = 3;\n    int numberOfSamples = 1E6;\n    int seed = 511;\n\n    Eigen::VectorXd mean( dimension );\n    Eigen::VectorXd standardDeviation( dimension );\n    mean << 0.0, 1.0, -2.0;\n    standardDeviation << 1.0, 3.0, 4.0;\n\n    {\n        std::vector< Eigen::VectorXd > samples =\n                tudat::statistics::generateGaussianRandomSample( seed, numberOfSamples, mean, standardDeviation );\n\n        // Compute sample mean and standard deviation\n        Eigen::VectorXd sampleMean = statistics::computeSampleMean( samples );\n        Eigen::ArrayXd sampleStandardDeviations = statistics::computeSampleVariance( samples ).array( ).sqrt( );\n\n        BOOST_CHECK_SMALL( std::fabs( mean( 0 ) - sampleMean( 0 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( mean( 1 ) - sampleMean( 1 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( mean( 2 ) - sampleMean( 2 ) ), 5.0E-3 );\n\n        BOOST_CHECK_SMALL( std::fabs( standardDeviation( 0 ) - sampleStandardDeviations( 0 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( standardDeviation( 1 ) - sampleStandardDeviations( 1 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( standardDeviation( 2 ) - sampleStandardDeviations( 2 ) ), 5.0E-3 );\n    }\n\n    {\n        std::vector< Eigen::VectorXd > samples =\n                tudat::statistics::generateGaussianRandomSample( seed, numberOfSamples, 3 );\n\n        // Compute sample mean and standard deviation\n        Eigen::VectorXd sampleMean = statistics::computeSampleMean( samples );\n        Eigen::ArrayXd sampleStandardDeviations = statistics::computeSampleVariance( samples ).array( ).sqrt( );\n\n        BOOST_CHECK_SMALL( std::fabs( 0.0 - sampleMean( 0 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( 0.0 - sampleMean( 1 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( 0.0 - sampleMean( 2 ) ), 5.0E-3 );\n\n        BOOST_CHECK_SMALL( std::fabs( 1.0 - sampleStandardDeviations( 0 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( 1.0 - sampleStandardDeviations( 1 ) ), 5.0E-3 );\n        BOOST_CHECK_SMALL( std::fabs( 1.0 - sampleStandardDeviations( 2 ) ), 5.0E-3 );\n    }\n}\n\n\n#if USE_GSL\n\n//! Test if Sobol sampler interface is working correctly. Note that this test is somewhat minimal, but the core of the\n//! Sobol sampling is tested in the GSL unit tests.\nBOOST_AUTO_TEST_CASE( test_Sobol_Sampler )\n{\n    // Define settings and generate samples.\n    int dimension = 3;\n    int numberOfSamples = 1E6;\n\n    Eigen::VectorXd lower( dimension );\n    Eigen::VectorXd upper( dimension );\n    lower << 0.0, 1.0, -2.0;\n    upper << 1.0, 3.0, 4.0;\n\n    Eigen::VectorXd width = upper - lower;\n    Eigen::VectorXd average = (upper + lower) / 2.0;\n\n    std::vector< Eigen::VectorXd > sobolSamples = tudat::statistics::generateVectorSobolSample(\n                numberOfSamples, lower, upper );\n\n    // Compute sample average\n    Eigen::VectorXd sampleMean = statistics::computeSampleMean( sobolSamples );\n\n    BOOST_CHECK_SMALL( std::fabs( average( 0 ) - sampleMean( 0 ) ), 2.0E-6 );\n    BOOST_CHECK_SMALL( std::fabs( average( 1 ) - sampleMean( 1 ) ), 2.0E-6 );\n    BOOST_CHECK_SMALL( std::fabs( average( 2 ) - sampleMean( 2 ) ), 2.0E-6 );\n\n    sobolSamples = tudat::statistics::generateVectorSobolSample( dimension, numberOfSamples );\n\n    // Compute sample average\n    sampleMean = statistics::computeSampleMean( sobolSamples );\n\n    BOOST_CHECK_SMALL( std::fabs( 0.5 - sampleMean( 0 ) ), 2.0E-6 );\n    BOOST_CHECK_SMALL( std::fabs( 0.5 - sampleMean( 1 ) ), 2.0E-6 );\n    BOOST_CHECK_SMALL( std::fabs( 0.5 - sampleMean( 2 ) ), 2.0E-6 );\n}\n#endif\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} // namespace unit_tests\n} // namespace tudat\n", "meta": {"hexsha": "b9864c23ec2740c7ec9f5c34ecb5bf20e9ddd583", "size": 6906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/math/statistics/unitTestRandomSampling.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/math/statistics/unitTestRandomSampling.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/math/statistics/unitTestRandomSampling.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9190751445, "max_line_length": 132, "alphanum_fraction": 0.6597161888, "num_tokens": 2027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6030502260689143}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Siargey Kachanovich\n *\n *    Copyright (C) 2019 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"permutahedral_representation\"\n#include <boost/test/unit_test.hpp>\n\n#include <gudhi/Permutahedral_representation.h>\n\nBOOST_AUTO_TEST_CASE(permutahedral_representation) {\n  typedef std::vector<int> Vertex;\n  typedef std::vector<std::size_t> Part;\n  typedef std::vector<Part> Partition;\n  typedef Gudhi::coxeter_triangulation::Permutahedral_representation<Vertex, Partition> Simplex_handle;\n  Vertex v0(10, 0);\n  Partition omega = {Part({5}), Part({2}), Part({3, 7}), Part({4, 9}), Part({0, 6, 8}), Part({1, 10})};\n  Simplex_handle s(v0, omega);\n\n  // Dimension check\n  BOOST_CHECK(s.dimension() == 5);\n\n  // Vertex number check\n  std::vector<Vertex> vertices;\n  for (auto& v : s.vertex_range()) vertices.push_back(v);\n  BOOST_CHECK(vertices.size() == 6);\n\n  // Facet number check\n  std::vector<Simplex_handle> facets;\n  for (auto& f : s.facet_range()) facets.push_back(f);\n  BOOST_CHECK(facets.size() == 6);\n\n  // Face of dim 3 number check\n  std::vector<Simplex_handle> faces3;\n  for (auto& f : s.face_range(3)) faces3.push_back(f);\n  BOOST_CHECK(faces3.size() == 15);\n\n  // Cofacet number check\n  std::vector<Simplex_handle> cofacets;\n  for (auto& f : s.cofacet_range()) cofacets.push_back(f);\n  BOOST_CHECK(cofacets.size() == 12);\n\n  // Is face check\n  Vertex v1(10, 0);\n  Partition omega1 = {Part({5}), Part({0, 1, 2, 3, 4, 6, 7, 8, 9, 10})};\n  Simplex_handle s1(v1, omega1);\n  Vertex v2(10, 0);\n  v2[1] = -1;\n  Partition omega2 = {Part({1}), Part({5}), Part({2}), Part({3, 7}), Part({4, 9}), Part({0, 6, 8}), Part({10})};\n  Simplex_handle s2(v2, omega2);\n  BOOST_CHECK(s.is_face_of(s));\n  BOOST_CHECK(s1.is_face_of(s));\n  BOOST_CHECK(!s2.is_face_of(s));\n  BOOST_CHECK(s.is_face_of(s2));\n}\n", "meta": {"hexsha": "a668fc663e76b903e0723bec3db513ea17295762", "size": 2107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Coxeter_triangulation/test/perm_rep_test.cpp", "max_stars_repo_name": "VincentRouvreau/gudhi-devel", "max_stars_repo_head_hexsha": "c6a7f0258406542b0c2b10bb6b2878f27b13394b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T05:45:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-05T05:45:06.000Z", "max_issues_repo_path": "src/Coxeter_triangulation/test/perm_rep_test.cpp", "max_issues_repo_name": "gspr/gudhi-devel", "max_issues_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Coxeter_triangulation/test/perm_rep_test.cpp", "max_forks_repo_name": "gspr/gudhi-devel", "max_forks_repo_head_hexsha": "6b8f24647a6f290f4e2f2f307de660dfae93cc90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9838709677, "max_line_length": 112, "alphanum_fraction": 0.6734693878, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.6030045687028811}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n// QuickBook Example\r\n\r\n// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//[unique\r\n//` Shows how to make a so-called minimal set of a polygon by removing duplicate points\r\n\r\n#include <iostream>\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)\r\n\r\nint main()\r\n{\r\n    boost::geometry::model::polygon<boost::tuple<double, double> > poly;\r\n    boost::geometry::read_wkt(\"POLYGON((0 0,0 0,0 5,5 5,5 5,5 5,5 0,5 0,0 0,0 0,0 0,0 0))\", poly);\r\n    boost::geometry::unique(poly);\r\n    std::cout << boost::geometry::wkt(poly) << std::endl;\r\n\r\n    return 0;\r\n}\r\n\r\n//]\r\n\r\n\r\n//[unique_output\r\n/*`\r\nOutput:\r\n[pre\r\nPOLYGON((0 0,0 5,5 5,5 0,0 0))\r\n]\r\n*/\r\n//]\r\n", "meta": {"hexsha": "cd4f448c596b6bb831927267d064d3bfd37d7184", "size": 1064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/doc/src/examples/algorithms/unique.cpp", "max_stars_repo_name": "Ron2014/boost_1_48_0", "max_stars_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/geometry/doc/src/examples/algorithms/unique.cpp", "max_issues_repo_name": "Ron2014/boost_1_48_0", "max_issues_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/geometry/doc/src/examples/algorithms/unique.cpp", "max_forks_repo_name": "Ron2014/boost_1_48_0", "max_forks_repo_head_hexsha": "19673f69677ffcba7c7bd6e08ec07ee3962f161c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3333333333, "max_line_length": 99, "alphanum_fraction": 0.6757518797, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.602945229686933}}
{"text": "/*\nCopyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n\nNVIDIA CORPORATION and its licensors retain all intellectual property\nand proprietary rights in and to this software, related documentation\nand any modifications thereto. Any use, reproduction, disclosure or\ndistribution of this software and related documentation without an express\nlicense agreement from NVIDIA CORPORATION is strictly prohibited.\n*/\n\n// An implementation of the EPnP algorithm (for >=6 points) based on the following publication:\n// V. Lepetit, F. Moreno-Noguer, P. Fua, EPnP: An Accurate O(n) Solution to the PnP Problem,\n// International Journal Of Computer Vision (IJCV), 2009\n// See manuscript at http://infoscience.epfl.ch/record/160138/files/top.pdf\n\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n#include <cmath>\n\n#include <iostream>\n#include <random>\n#include \"packages/pnp/gems/epnp/epnp.hpp\"\n#include \"packages/pnp/gems/tests/simu.hpp\"\n\n// Global number of repetitions for some randomized tests.\nconstexpr int kRepeatTests = 1000;\n\n// Test the output size of ChooseBasis() with 0,1,2,3 and 4 input points in general configuration.\nTEST(EpnpTest, ChooseBasisNotEnoughPointsTest) {\n  // Tolerance for collapsing dimensions inside ChooseBasis().\n  const double tol = 1e-4;\n\n  // Test ChooseBasis() with empty input.\n  isaac::Matrix3Xd points;\n  isaac::Matrix3Xd ctl_points = isaac::pnp::epnp::ChooseBasis(points, tol);\n  EXPECT_EQ(ctl_points.cols(), 0);\n\n  // Fixed set of 4 non-planar points for testing.\n  points.resize(3, 4);\n  points << 10, -10, 10, 1.5, 8, -3, 0, 100, 20, -30, 8, 2;\n\n  // Test the output size of ChooseBasis() for the first N = 1, 2, 3, 4 points.\n  for (int num_points = 1; num_points < points.cols(); num_points++) {\n    ctl_points = isaac::pnp::epnp::ChooseBasis(points.block(0, 0, 3, num_points), tol);\n\n    // Output size equals the number of input points up to 4 points in general configuration.\n    // This only holds when points do not coincide and are not all collinear or coplanar.\n    EXPECT_EQ(ctl_points.cols(), num_points);\n  }\n}\n\n// Test ChooseBasis() with perfectly collinear input point set.\n// It should only return two points along the line that define the basis (origin and axis end-point)\n// to represent the original points.\nTEST(EpnpTest, ChooseBasisCollinearTest) {\n  const int num_points = 100;  // Number of input points to generate and feed to ChooseBasis().\n  const double tol = 1e-2;     // Tolerance for collapsing dimensions inside ChooseBasis().\n\n  // Test for many different random lines in space.\n  for (int i = 0; i < kRepeatTests; i++) {\n    // Generate a random line in space via a random direction and a random pivot point on the line.\n    isaac::Vector3d line_dir = isaac::pnp::RandomVector<isaac::Vector3d>(3);\n    line_dir.normalize();\n    isaac::Vector3d line_pivot = isaac::pnp::RandomVector<isaac::Vector3d>(3, -100, 100);\n\n    // Generate input points along the 3D line.\n    isaac::VectorXd line_param = isaac::pnp::RandomVector<isaac::VectorXd>(num_points, -100, 100);\n    isaac::Matrix3Xd points(3, num_points);\n    for (int i = 0; i < num_points; i++) {\n      points.col(i) = line_param(i) * line_dir + line_pivot;\n    }\n\n    // Feed the collinear points to ChooseBasis().\n    isaac::Matrix3Xd ctl_points = isaac::pnp::epnp::ChooseBasis(points, tol);\n\n    // ChooseBasis() should return 2 control points: origin and a single axis end-point on the line.\n    EXPECT_EQ(ctl_points.cols(), 2);\n\n    // Returned axis direction should be parallel to the line.\n    EXPECT_LT((line_dir.cross(ctl_points.col(1) - ctl_points.col(0))).norm(), 1e-9);\n  }\n}\n\n// Test if a 3D basis returned by ChooseBasis() and represented as 4 control points\n// is aligned with a Gaussian distribution.\n// The basis is computed from statistical samples and therefore is never perfectly aligned\n// with the generator distribution. If sufficiently many samples were used, the basis will be\n// be approximately aligned unless there are computation errors. There is no guarantee\n// that the error is within a certain threshold. Loose thresholds are used here.\nvoid CheckControlPoints(const isaac::Matrix3Xd& ctl_points, const isaac::pnp::Gaussian3& gaussian) {\n  // This test is meant for the planar and non-planar case, not for other degenerate inputs.\n  int dims = int(ctl_points.cols() - 1);\n  ASSERT_TRUE(dims == 2 || dims == 3);\n\n  // The first control point (the basis origin) should be an estimate for the mean.\n  EXPECT_LT((ctl_points.col(0) - gaussian.mean()).norm(), 0.3);\n\n  // Calculate vectors and distances between control points.\n  isaac::Matrix3Xd basis_axes(3, dims);\n  isaac::VectorXd axis_lengths(dims);\n  for (int i = 0; i < dims; i++) {\n    isaac::Vector3d axis = ctl_points.col(i + 1) - ctl_points.col(0);\n    double axis_length = axis.norm();\n    if (axis_length) {\n      basis_axes.col(i) = axis / axis_length;\n    } else {\n      basis_axes.col(i) = axis;\n    }\n    axis_lengths(i) = axis_length;\n  }\n\n  // Test mutual orthonormality of basis axes defined by the calculated control points.\n  EXPECT_LT((basis_axes.transpose() * basis_axes - isaac::MatrixXd::Identity(dims, dims)).norm(),\n            1e-4);\n\n  // Normalized axis directions of the 3D Gaussian are in the columns of the orientation matrix.\n  // Test their mutual orthonormality.\n  const isaac::Matrix3Xd& gaussian_axes = gaussian.orientation();\n  EXPECT_LT((gaussian_axes.transpose() * gaussian_axes - isaac::Matrix3d::Identity()).norm(), 1e-4);\n\n  // Calculate the pairwise similarity (scalar product, cosine of angle) between each basis axis\n  // direction and each axis of the Gaussian distribution.\n  // The i-th row is the distance between the i-th basis axis and each reference Gaussian axis.\n  isaac::MatrixXd similarity_matrix = (basis_axes.transpose() * gaussian_axes).cwiseAbs();\n\n  // Find the closest Gaussian axis to each basis axis.\n  Eigen::VectorXi axis_ids = Eigen::VectorXi::Zero(dims);\n  isaac::VectorXd cos_angles(dims);\n  for (int i = 0; i < dims; i++) cos_angles(i) = similarity_matrix.row(i).maxCoeff(&axis_ids(i));\n\n  // Test if basis axes (which are vectors between control points) are close to parallel\n  // to the corresponding Gaussian axis. Use high threshold because of comparing a distribution\n  // parameter to its statistical estimate.\n  EXPECT_LT((cos_angles - isaac::VectorXd::Ones(dims)).norm(), 0.1);\n\n  // Test if distances between control points are equal to the deviation along the corresponding\n  // Gaussian axis.\n  isaac::VectorXd deviations(dims);\n  for (int i = 0; i < dims; i++) {\n    deviations(i) = gaussian.deviations()(axis_ids(i));\n  }\n  EXPECT_LT((deviations - axis_lengths).norm(), 0.2);\n}\n\n// Test ChooseBasis() with a random planar point distribution.\n// Points are drawn from a 3D Gaussian distribution flattened along one major axis.\nTEST(EpnpTest, ChooseBasisPlanarTest) {\n  // Draw 3D points from a 3D Gaussian distribution that is perfectly flat along one of its\n  // major axes - equivalent to 2D Gaussian samples on a plane.\n  isaac::pnp::Gaussian3 gaussian;\n  gaussian.setOrientation(isaac::pnp::RandomVector<isaac::Vector3d>(3));\n  gaussian.setMean(isaac::Vector3d(50, -200, 25.89));\n  gaussian.setDeviations(isaac::Vector3d(0, 2.3, 1.7));  // squash the Gaussian along one dimension\n  isaac::Matrix3Xd points = gaussian.generate(1000);\n\n  // Feed the planar point configuration to ChooseBasis()\n  isaac::Matrix3Xd ctl_points = isaac::pnp::epnp::ChooseBasis(points, 0.01);\n\n  // Verify that only 3 control points are returned: origin and two direction vectors in the plane.\n  ASSERT_EQ(ctl_points.cols(), 3);\n\n  // Make sure the the basis defined by the control points is actually aligned with the planar\n  // Gaussian blob used to generate the input points.\n  CheckControlPoints(ctl_points, gaussian);\n}\n\n// Test ChooseBasis() with a non-planar point set drawn from a 3D Gaussian distribution.\nTEST(EpnpTest, ChooseBasisNonPlanarTest) {\n  // Draw 3D points from a generic 3D Gaussian distribution.\n  isaac::pnp::Gaussian3 gaussian;\n  gaussian.setOrientation(isaac::pnp::RandomVector<isaac::Vector3d>(3));\n  gaussian.setMean(isaac::Vector3d(50, -200, 25.89));\n  gaussian.setDeviations(isaac::Vector3d(0.3, 1.2, 1.5));\n  isaac::Matrix3Xd points = gaussian.generate(1000);\n\n  // Feed the point configuration to ChooseBasis()\n  isaac::Matrix3Xd ctl_points = isaac::pnp::epnp::ChooseBasis(points, 0.001);\n\n  // Verify that 4 control points are returned: origin and three axes.\n  // Test if the axis lengths are properly aligned with the Gaussian blob.\n  ASSERT_EQ(ctl_points.cols(), 4);\n  CheckControlPoints(ctl_points, gaussian);\n}\n\n// Test ComputeBaryCoords() on 3D samples drawn from a Gaussian distribution.\nTEST(EpnpTest, BaryCoordsNonPlanarTest) {\n  // Run the test for different 3D sample sets drawn from the same 3D Gaussian.\n  for (int i = 0; i < kRepeatTests; i++) {\n    // Draw many points from a fixed non-isotropic and slanted 3D Gaussian distribution.\n    isaac::pnp::Gaussian3 gaussian;\n    gaussian.setOrientation(isaac::pnp::RandomVector<isaac::Vector3d>(3));\n    gaussian.setMean(isaac::Vector3d(50, -200, 25.89));\n    gaussian.setDeviations(isaac::Vector3d(0.3, 1.2, 1.5));\n    isaac::Matrix3Xd points = gaussian.generate(100);\n\n    // Compute 3D basis represented by 4 control points (non-planar case).\n    isaac::Matrix3Xd ctl_points = isaac::pnp::epnp::ChooseBasis(points, 1e-3);\n    ASSERT_EQ(ctl_points.cols(), 4);\n\n    // Describe all input points by their barycentric coordinates in this basis.\n    isaac::MatrixXd bary_coeffs = isaac::pnp::epnp::ComputeBaryCoords(points, ctl_points);\n\n    // Given N input points, the output is a 4xN matrix of barycentric coefficients.\n    ASSERT_EQ(bary_coeffs.rows(), 4);\n    ASSERT_EQ(bary_coeffs.cols(), points.cols());\n\n    // Test if barycentric coordinates are correct.\n    // This also checks if barycentric coeffs sum to 1.0 for each point.\n    isaac::Matrix4Xd hom_basis = isaac::pnp::HomogeneousFromEuclidean(ctl_points);\n    isaac::Matrix4Xd hom_points = isaac::pnp::HomogeneousFromEuclidean(points);\n    ASSERT_EQ(hom_basis.rows(), ctl_points.rows() + 1);\n    ASSERT_EQ(hom_basis.cols(), ctl_points.cols());\n    ASSERT_EQ(hom_points.rows(), points.rows() + 1);\n    ASSERT_EQ(hom_points.cols(), points.cols());\n    double max_residual = (hom_basis * bary_coeffs - hom_points).cwiseAbs().maxCoeff();\n    EXPECT_LT(max_residual, 1e-9);\n  }\n}\n\n// Test ComputeBaryCoords() for points in a plane.\n// Points are drawn from a 3D Gaussian distribution flattened along one major axis.\nTEST(EpnpTest, BaryCoordsPlanarTest) {\n  for (int i = 0; i < kRepeatTests; i++) {\n    // Draw many points from a fixed non-isotropic and slanted 3D Gaussian distribution.\n    isaac::pnp::Gaussian3 gaussian;\n    gaussian.setOrientation(isaac::pnp::RandomVector<isaac::Vector3d>(3));\n    gaussian.setMean(isaac::Vector3d(50, -200, 25.89));\n    gaussian.setDeviations(isaac::Vector3d(0, 1.2, 1.5));\n    isaac::Matrix3Xd points = gaussian.generate(100);\n\n    // Compute planar basis represented by only 3 control points.\n    isaac::Matrix3Xd ctl_points = isaac::pnp::epnp::ChooseBasis(points, 1e-2);\n    ASSERT_EQ(ctl_points.cols(), 3);\n\n    // Describe all input points by their barycentric coordinates in this basis.\n    isaac::MatrixXd bary_coeffs = isaac::pnp::epnp::ComputeBaryCoords(points, ctl_points);\n    ASSERT_EQ(bary_coeffs.rows(), 3);\n    ASSERT_EQ(bary_coeffs.cols(), points.cols());\n\n    // Test if barycentric coordinates are correct.\n    // This also checks if barycentric coeffs sum to 1.0 for each point.\n    isaac::Matrix4Xd hom_basis = isaac::pnp::HomogeneousFromEuclidean(ctl_points);\n    isaac::Matrix4Xd hom_points = isaac::pnp::HomogeneousFromEuclidean(points);\n    double max_residual = (hom_basis * bary_coeffs - hom_points).cwiseAbs().maxCoeff();\n    EXPECT_LT(max_residual, 1e-9);\n  }\n}\n\n// Test SolveControlPoints() for the non-planar case.\n// The solution is sought in the form x = B*w, where x is a solution vector of 12 elements\n// (camera coordinates of 4 control points as a vector) that satisfy certain distance criteria.\n// B is a known 12xD matrix of D basis vectors, and w is the vector of unknown weights.\n// The test works as follows:\n//  (1) Simulate a random (non-orthogonal) D-dimensional basis\n//      as a random 12xD matrix B with normalized columns.\n//  (2) Generate a ground-truth vector w randomly.\n//  (3) Synthesize the ground-truth solution x as B*w.\n//  (4) Calculate the true distances between parts of x.\n//  (5) Run SolveControlPoints() given B and the distances to calculate the weights w.\n//  (6) Compare the calculated weights to the known weights generated in step (2).\n// The parameter dims is the number of dimensions of the solution space 1 <= D <= 4 to test with.\nvoid ControlPointSolverNonPlanarTest(int dims) {\n  // Make sure dims is between 1 and 4\n  if (dims < 1) {\n    dims = 1;\n  }\n  if (dims > 4) {\n    dims = 4;\n  }\n\n  // Repeat the process (1-6) many times to test with different random bases and weights.\n  for (int i = 0; i < kRepeatTests; i++) {\n    // (1) Generate 4 random normalized basis vectors in a 12-D space.\n    isaac::MatrixXd sol_basis = isaac::pnp::RandomUniformMatrix<isaac::MatrixXd>(12, 4, -1, 1);\n    sol_basis.colwise().normalize();\n    for (int i = 0; i < sol_basis.cols(); i++) {\n      EXPECT_NEAR(sol_basis.col(i).norm(), 1.0, 1e-6);\n    }\n\n    // (2) Generate the true weights which are to be found by SolveControlPoints().\n    isaac::Vector4d true_weights = isaac::pnp::RandomVector<isaac::Vector4d>(4, -100.0f, 100.0f);\n    for (int i = dims; i < 4; i++) {\n      true_weights(i) = 0;\n    }\n\n    // (3) Synthesize the ground truth solution as the linear combination of the basis vectors.\n    // The solution is represented as a 3x4 matrix instead of a vector of 12 elements.\n    isaac::Matrix3Xd true_ctl_points =\n        isaac::pnp::epnp::ReshapeToMatrix3xN(sol_basis * true_weights);\n\n    // (4) Calculate the true pairwise distances between control points.\n    isaac::VectorXd distances = isaac::pnp::epnp::ComputeDistances(true_ctl_points);\n\n    // SolveControlPoints(): Compute the weights given the solution basis and the distances.\n    isaac::Vector4d weights = isaac::pnp::epnp::SolveControlPoints(sol_basis, dims, distances);\n\n    // Make sure that weights are not all zeros.\n    ASSERT_GT(weights.squaredNorm(), 0);\n\n    // Make sure that the computed weights match their known values up to a single global sign,\n    // because the simulation above does not guarantee that all z-coordinates are positive\n    // for the control points (last row of true_ctl_points).\n    double err = std::min((true_weights - weights).cwiseAbs().maxCoeff(),\n                          (true_weights + weights).cwiseAbs().maxCoeff());\n    ASSERT_LT(err, 1e-9);\n  }\n}\n\n// Test SolveControlPoints() for non-planar input and assuming a 1-dimensional a solution space.\nTEST(EpnpTest, ControlPointSolver1_NonPlanar) {\n  SCOPED_TRACE(\"1 dimensional\");\n  ControlPointSolverNonPlanarTest(1);\n}\n\n// Test SolveControlPoints() for non-planar input and assuming a 2-dimensional a solution space.\nTEST(EpnpTest, ControlPointSolver2_NonPlanar) {\n  SCOPED_TRACE(\"2 dimensional\");\n  ControlPointSolverNonPlanarTest(2);\n}\n\n// Test SolveControlPoints() for non-planar input and assuming a 3-dimensional a solution space.\nTEST(EpnpTest, ControlPointSolver3_NonPlanar) {\n  SCOPED_TRACE(\"3 dimensional\");\n  ControlPointSolverNonPlanarTest(3);\n}\n\n// Test to make sure that each stage of the EPnP pipeline works as expected in the noise-free case.\n// Check the output pose and internal calculation results of epnp::ComputeCameraPose(),\n// given the perfect (noise-free) input points and camera passed to epnp::ComputeCameraPose().\n//   result     Output provided by epnp::ComputeCameraPose().\n//   camera     Ideal camera passed to epnp::ComputeCameraPose(). Contains the ground-truth pose.\n//   points2,3  Ideal (noise-free) input 2D and 3D points passed to epnp::ComputeCameraPose().\nvoid CheckEpnpResult(const isaac::pnp::epnp::Result& result, const isaac::pnp::Camera& camera,\n                     const isaac::Matrix3Xd& points3, const isaac::Matrix2Xd& points2) {\n  ASSERT_EQ(points3.cols(), points2.cols());\n\n  // Input point cloud should be either planar (2D arrangement) or non-planar (3D arrangement).\n  // This should be reflected in result.input_dims and the number of control points calculated.\n  ASSERT_GE(result.input_dims, 2);\n  ASSERT_LE(result.input_dims, 3);\n  ASSERT_EQ(result.ctl_points_world.cols(), result.input_dims + 1);\n\n  // Test barycentric coordinates of the input points in the calculated basis\n  // defined by the control points.\n  ASSERT_EQ(result.bary_coeffs.rows(), result.input_dims + 1);\n  ASSERT_EQ(result.bary_coeffs.cols(), points3.cols());\n  EXPECT_LT((isaac::pnp::HomogeneousFromEuclidean(result.ctl_points_world) * result.bary_coeffs -\n             isaac::pnp::HomogeneousFromEuclidean(points3))\n                .cwiseAbs()\n                .maxCoeff(),\n            1e-9);\n\n  // Check the size of the coefficient matrix of the projection equations.\n  // Check the size of the solution basis of the projection equation and the number of corresponding\n  // singular values. All should be consistent with the number of dimensions.\n  ASSERT_EQ(result.proj_coeffs.rows(), 2 * points3.cols());\n  ASSERT_EQ(result.proj_coeffs.cols(), 3 * (result.input_dims + 1));\n  ASSERT_EQ(result.solution_basis.rows(), 3 * (result.input_dims + 1));\n  ASSERT_EQ(result.singular_values.size(), 3 * (result.input_dims + 1));\n  ASSERT_EQ(result.solution_basis.cols(), 4);\n\n  // Assuming no noise in the input points, the homogeneous projection equations should have an\n  // infinite number of perfect solutions: all solutions parallel to the first basis vector of the\n  // hypothesized solution space all saisfy the original equations.\n  // Thus, the solution space is at least 1-dimensional in the noise-free case.\n  // In other terms, the least singular value should be zero.\n  const double tol = 1e-9;\n  EXPECT_LT(result.singular_values(0), tol);\n\n  // The 4 hypothesized basis vectors of the solution subspace are all singular vectors\n  // of the coefficient matrix of the projection equations (linear homogeneous equations).\n  // Theory says that the norm of the algebraic residual when substituting each singular vector\n  // into the original homogeneous equation equals the corresponding singular value, so test this.\n  // This also holds in the noisy case!\n  EXPECT_NEAR((result.proj_coeffs * result.solution_basis.col(0)).norm(), result.singular_values(0),\n              tol);\n  EXPECT_NEAR((result.proj_coeffs * result.solution_basis.col(1)).norm(), result.singular_values(1),\n              tol);\n  EXPECT_NEAR((result.proj_coeffs * result.solution_basis.col(2)).norm(), result.singular_values(2),\n              tol);\n  EXPECT_NEAR((result.proj_coeffs * result.solution_basis.col(3)).norm(), result.singular_values(3),\n              tol);\n\n  // Since the algebraic error of the first basis vector (and its scalar multiples) is always zero,\n  // the geometric (reprojection) error of the corresponding control points should also be zero.\n  // Calculate reprojection errors are all zero up to numerical precision.\n  // This test assumes ideal (noise-free) input.\n  isaac::Matrix3Xd solution = isaac::pnp::epnp::ReshapeToMatrix3xN(result.solution_basis.col(0));\n  isaac::VectorXd repr_errors =\n      isaac::pnp::ColwiseNorms(points2 - isaac::pnp::epnp::ProjectPoints(\n                                             camera.calib_matrix, solution * result.bary_coeffs));\n  EXPECT_LT(repr_errors.maxCoeff(), 1e-9);\n\n  // Calculate the ground-truth control points in the camera frame by transforming the computed\n  // control points in the world frame with the ground-truth camera pose.\n  isaac::Matrix3Xd true_ctl_points_cam =\n      camera.rotation_matrix * (result.ctl_points_world.colwise() - camera.position);\n\n  // Compare the computed control points to ground-truth in the camera frame.\n  // They should match up to numerical precision because the input was noise-free.\n  EXPECT_LT((result.ctl_points_cam - true_ctl_points_cam).norm(), 1e-9);\n\n  // Test if the rotation matrix computed by EPnP is orthonormal.\n  EXPECT_LT((result.rotation.transpose() * result.rotation - isaac::Matrix3d::Identity()).norm(),\n            1e-9);\n\n  // The pose is computed as the rigid transformation that takes the computed control points\n  // in the world frame into the computed control points in the camera frame.\n  // As the input was noise-free, the residual of this transformation should be zero.\n  EXPECT_LT(((result.rotation * result.ctl_points_world - result.ctl_points_cam).colwise() +\n             result.translation)\n                .norm(),\n            1e-9);\n\n  // Compare the calculated camera orientation to the ground-truth.\n  double rot_error = isaac::RadToDeg(\n      isaac::pnp::AngleAxisFromMatrix(camera.rotation_matrix.transpose() * result.rotation).norm());\n\n  // Compare the calculated camera position to the ground-truth.\n  isaac::Vector3d camera_position = -result.rotation.transpose() * result.translation;\n  double tran_error = (camera_position - camera.position).norm();\n\n  // Alternative: directly compare the translation vectors instead of the camera positions.\n  // isaac::Vector3d true_translation = - camera.rotation_matrix * camera.position;\n  // double tran_error = (result.translation - true_translation).norm();\n\n  // As the input was noise-free, the rotation and translation errors should be zero.\n  EXPECT_LT(rot_error, 1e-9);   // degrees\n  EXPECT_LT(tran_error, 1e-9);  // meters (position range in huge: +/-100 meters)\n}\n\n// Test integrated EPnP pose estimation pipeline in case of ideal non-planar input arrangement.\n// Repeats the following randomized test procedure many times:\n//  (1) Generate a camera with random pose but fixed intrinsics.\n//  (2) Generate sufficient number of ideal (noise-free) random 2D-3D matches such that\n//      the 3D points are in front of the camera between the near and far plane.\n//  (3) Camera pose estimation from the synthetic input using EPnP.\n//  (4) Test if computed pose equals ground-truth and if the intermediate results are consistent.\nTEST(EpnpTest, FullNonPlanarTest) {\n  // Camera intrinsic parameters.\n  const int width = 1280;\n  const int height = 720;\n  const double focal = 700.0;\n\n  // Repeat the pose estimation for different random inputs and random cameras (all planar).\n  for (int i = 0; i < kRepeatTests; i++) {\n    // (1) Generate a camera with random pose but fixed intrinsics.\n    isaac::pnp::Camera camera = isaac::pnp::GenerateRandomCamera(width, height, focal);\n    const double focal_u = camera.calib_matrix(0, 0);\n    const double focal_v = camera.calib_matrix(1, 1);\n    const double principal_u = camera.calib_matrix(0, 2);\n    const double principal_v = camera.calib_matrix(1, 2);\n\n    // (2) Generate sufficient number of ideal (noise-free) random 2D-3D matches such that\n    //     the 3D points are in front of the camera between the near and far plane.\n    const double near = 5.0;\n    const double far = 10.0;\n    const unsigned num_points = 6;\n    isaac::Matrix3Xd points3;\n    isaac::Matrix2Xd points2;\n    isaac::pnp::GenerateFovPoints(num_points, camera, near, far, &points3, &points2);\n\n    // (3) Camera pose estimation from the synthetic noise-free input using EPnP.\n    // EPnP should always succeed for such input.\n    isaac::pnp::epnp::Result result;\n    ASSERT_EQ(isaac::pnp::epnp::ComputeCameraPose(focal_u, focal_v, principal_u, principal_v,\n                                                  points3, points2, &result),\n              isaac::pnp::Status::kSuccess);\n\n    // (4) Test if computed pose equals ground-truth and if the intermediate results are consistent.\n    SCOPED_TRACE(\"non-planar\");\n    CheckEpnpResult(result, camera, points3, points2);\n  }\n}\n\n// Test integrated EPnP pose estimation pipeline in case of ideal input on a fronto-parallel plane.\n// Repeats the following randomized test procedure many times:\n//  (1) Generate a camera with random pose but fixed intrinsics.\n//  (2) Generate sufficient number of ideal (noise-free) random 2D-3D matches such that\n//      the 3D points are on a FRONTO-PARALLEL PLANE in front of the camera.\n//  (3) Camera pose estimation from the synthetic input using EPnP.\n//  (4) Test if computed pose equals ground-truth and if the intermediate results are consistent.\nTEST(EpnpTest, FullFrontoPlanarTest) {\n  // Camera intrinsic parameters.\n  const int width = 1280;\n  const int height = 720;\n  const double focal = 700;\n\n  // Repeat the pose estimation for different random inputs and random cameras (all planar).\n  for (int i = 0; i < kRepeatTests; i++) {\n    // (1) Generate a camera with random pose but fixed intrinsics.\n    isaac::pnp::Camera camera = isaac::pnp::GenerateRandomCamera(width, height, focal);\n    const double focal_u = camera.calib_matrix(0, 0);\n    const double focal_v = camera.calib_matrix(1, 1);\n    const double principal_u = camera.calib_matrix(0, 2);\n    const double principal_v = camera.calib_matrix(1, 2);\n\n    // (2) Generate sufficient number of ideal (noise-free) random 2D-3D matches such that\n    //     the 3D points are on a fronto-parallel plane in front of the camera.\n    const double depth = 8.0;\n    const double angle = 0.0;\n    const unsigned num_points = 6;\n    isaac::Matrix3Xd points3;\n    isaac::Matrix2Xd points2;\n    isaac::Vector4d plane;\n    isaac::pnp::GenerateFovPointsPlanar(num_points, camera, depth, angle, 0, &points3, &points2,\n                                        &plane);\n\n    // (3) Camera pose estimation from the synthetic noise-free input using EPnP.\n    // EPnP should always succeed for such input.\n    isaac::pnp::epnp::Result result;\n    ASSERT_EQ(isaac::pnp::epnp::ComputeCameraPose(focal_u, focal_v, principal_u, principal_v,\n                                                  points3, points2, &result),\n              isaac::pnp::Status::kSuccess);\n\n    // (4) Test if computed pose equals ground-truth and if the intermediate results are consistent.\n    SCOPED_TRACE(\"fronto-parallel planar\");\n    CheckEpnpResult(result, camera, points3, points2);\n  }\n}\n\n// Test integrated EPnP pose estimation pipeline in case of ideal input on a fronto-parallel plane.\n// Repeats the following randomized test procedure many times:\n//  (1) Generate a camera with random pose but fixed intrinsics.\n//  (2) Generate sufficient number of ideal (noise-free) random 2D-3D matches such that\n//      the 3D points are on a SLANTED PLANE in front of the camera.\n//  (3) Camera pose estimation from the synthetic input using EPnP.\n//  (4) Test if computed pose equals ground-truth and if the intermediate results are consistent.\nTEST(EpnpTest, FullSlantedPlanarTest) {\n  // Camera intrinsic parameters.\n  const int width = 1280;\n  const int height = 720;\n  const double focal = 700.0;\n\n  // Repeat the pose estimation for different random inputs and random cameras (all planar).\n  for (int i = 0; i < kRepeatTests; i++) {\n    // (1) Generate a camera with random pose but fixed intrinsics.\n    isaac::pnp::Camera camera = isaac::pnp::GenerateRandomCamera(width, height, focal);\n    const double focal_u = camera.calib_matrix(0, 0);\n    const double focal_v = camera.calib_matrix(1, 1);\n    const double principal_u = camera.calib_matrix(0, 2);\n    const double principal_v = camera.calib_matrix(1, 2);\n\n    // (2) Generate sufficient number of ideal (noise-free) random 2D-3D matches such that\n    //     the 3D points are on a SLANTED PLANE in front of the camera.\n    const double depth = 10.0;\n    const double angle = 80.0;\n    const unsigned num_points = 6;\n    isaac::Matrix3Xd points3;\n    isaac::Matrix2Xd points2;\n    isaac::Vector4d plane;\n    isaac::pnp::GenerateFovPointsPlanar(num_points, camera, depth, angle, 0, &points3, &points2,\n                                        &plane);\n\n    // (3) Camera pose estimation from the synthetic noise-free input using EPnP.\n    // EPnP should always succeed for such input.\n    isaac::pnp::epnp::Result result;\n    ASSERT_EQ(isaac::pnp::epnp::ComputeCameraPose(focal_u, focal_v, principal_u, principal_v,\n                                                  points3, points2, &result),\n              isaac::pnp::Status::kSuccess);\n\n    // (4) Test if computed pose equals ground-truth and if the intermediate results are consistent.\n    SCOPED_TRACE(\"slanted planar\");\n    CheckEpnpResult(result, camera, points3, points2);\n  }\n}\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "7c8bdc146b966bbc7c7eaa40d8b9a13ff5d18b7a", "size": 28620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/packages/pnp/gems/tests/epnp_test.cpp", "max_stars_repo_name": "ddr95070/RMIsaac", "max_stars_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdk/packages/pnp/gems/tests/epnp_test.cpp", "max_issues_repo_name": "ddr95070/RMIsaac", "max_issues_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/packages/pnp/gems/tests/epnp_test.cpp", "max_forks_repo_name": "ddr95070/RMIsaac", "max_forks_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-28T16:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T16:37:51.000Z", "avg_line_length": 50.034965035, "max_line_length": 100, "alphanum_fraction": 0.7156184486, "num_tokens": 7432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6029452296869329}}
{"text": "//=======================================================================\n// Copyright 2008 Aaron Windsor\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#include <boost/property_map/property_map.hpp>\n#include <boost/test/minimal.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/is_straight_line_drawing.hpp>\n\n#include <vector>\n\nusing namespace boost;\n\nstruct coord_t \n{\n  std::size_t x;\n  std::size_t y;\n};\n\n\nint test_main(int, char*[]) \n{\n  typedef adjacency_list< vecS, vecS, undirectedS, \n                          property<vertex_index_t, int> \n                         > graph_t;\n\n  typedef std::vector< coord_t > drawing_storage_t;\n\n  typedef boost::iterator_property_map \n      < drawing_storage_t::iterator,\n        property_map<graph_t, vertex_index_t>::type\n       > drawing_t;\n\n  graph_t g(4);\n  add_edge(0,1,g);\n  add_edge(2,3,g);\n\n  drawing_storage_t drawing_storage(num_vertices(g));\n  drawing_t drawing(drawing_storage.begin(), get(vertex_index,g));\n\n  // two perpendicular lines that intersect at (1,1)\n  drawing[0].x = 1; drawing[0].y = 0;\n  drawing[1].x = 1; drawing[1].y = 2;\n  drawing[2].x = 0; drawing[2].y = 1;\n  drawing[3].x = 2; drawing[3].y = 1;\n\n  BOOST_REQUIRE(!is_straight_line_drawing(g,drawing));\n\n  // two parallel horizontal lines\n  drawing[0].x = 0; drawing[0].y = 0;\n  drawing[1].x = 2; drawing[1].y = 0;\n\n  BOOST_REQUIRE(is_straight_line_drawing(g,drawing));\n  \n  // two parallel vertical lines\n  drawing[0].x = 0; drawing[0].y = 0;\n  drawing[1].x = 0; drawing[1].y = 2;\n  drawing[2].x = 1; drawing[2].y = 0;\n  drawing[3].x = 1; drawing[3].y = 2;\n\n  BOOST_REQUIRE(is_straight_line_drawing(g,drawing));\n\n  // two lines that intersect at (1,1)\n  drawing[0].x = 0; drawing[0].y = 0;\n  drawing[1].x = 2; drawing[1].y = 2;\n  drawing[2].x = 0; drawing[2].y = 2;\n  drawing[3].x = 2; drawing[3].y = 0;\n\n  BOOST_REQUIRE(!is_straight_line_drawing(g,drawing));\n  \n  // K_4 arranged in a diamond pattern, so that edges intersect\n  g = graph_t(4); \n  add_edge(0,1,g);  \n  add_edge(0,2,g);  \n  add_edge(0,3,g);\n  add_edge(1,2,g);  \n  add_edge(1,3,g);\n  add_edge(2,3,g);    \n  \n  drawing_storage = drawing_storage_t(num_vertices(g));\n  drawing = drawing_t(drawing_storage.begin(), get(vertex_index,g));\n\n  drawing[0].x = 1; drawing[0].y = 2;\n  drawing[1].x = 2; drawing[1].y = 1;\n  drawing[2].x = 1; drawing[2].y = 0;\n  drawing[3].x = 0; drawing[3].y = 1;\n\n  BOOST_REQUIRE(!is_straight_line_drawing(g, drawing));\n\n  // K_4 arranged so that no edges intersect\n  drawing[0].x = 0; drawing[0].y = 0;\n  drawing[1].x = 1; drawing[1].y = 1;\n  drawing[2].x = 1; drawing[2].y = 2;\n  drawing[3].x = 2; drawing[3].y = 0;\n\n  BOOST_REQUIRE(is_straight_line_drawing(g, drawing));\n\n  // a slightly more complicated example - edges (0,1) and (4,5)\n  // intersect\n  g = graph_t(8); \n  add_edge(0,1,g);  \n  add_edge(2,3,g);  \n  add_edge(4,5,g);\n  add_edge(6,7,g);  \n  \n  drawing_storage = drawing_storage_t(num_vertices(g));\n  drawing = drawing_t(drawing_storage.begin(), get(vertex_index,g));\n\n  drawing[0].x = 1; drawing[0].y = 1;\n  drawing[1].x = 5; drawing[1].y = 4;\n  drawing[2].x = 2; drawing[2].y = 5;\n  drawing[3].x = 4; drawing[3].y = 4;\n  drawing[4].x = 3; drawing[4].y = 4;\n  drawing[5].x = 3; drawing[5].y = 2;\n  drawing[6].x = 4; drawing[6].y = 2;\n  drawing[7].x = 1; drawing[7].y = 1;\n\n  BOOST_REQUIRE(!is_straight_line_drawing(g, drawing));\n  \n  // form a graph consisting of a bunch of parallel vertical edges,\n  // then place an edge at various positions to intersect edges\n  g = graph_t(22);\n  for(int i = 0; i < 11; ++i)\n    add_edge(2*i,2*i+1,g);\n\n  drawing_storage = drawing_storage_t(num_vertices(g));\n  drawing = drawing_t(drawing_storage.begin(), get(vertex_index,g));\n\n  for(int i = 0; i < 10; ++i)\n    {\n      drawing[2*i].x = i; drawing[2*i].y = 0;\n      drawing[2*i+1].x = i; drawing[2*i+1].y = 10;\n    }\n  \n  // put the final edge as a horizontal edge intersecting one other edge\n  drawing[20].x = 5; drawing[20].y = 5;\n  drawing[21].x = 7; drawing[21].y = 5;\n\n  BOOST_REQUIRE(!is_straight_line_drawing(g, drawing));\n\n  // make the final edge a diagonal intersecting multiple edges\n  drawing[20].x = 2; drawing[20].y = 4;\n  drawing[21].x = 9; drawing[21].y = 7;\n\n  BOOST_REQUIRE(!is_straight_line_drawing(g, drawing));\n\n  // reverse the slope\n  drawing[20].x = 2; drawing[20].y = 7;\n  drawing[21].x = 9; drawing[21].y = 4;\n\n  BOOST_REQUIRE(!is_straight_line_drawing(g, drawing));\n\n  return 0;\n}\n\n", "meta": {"hexsha": "edac4b2fa8b202517011256df8a52ac8c24766af", "size": 4713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/graph/test/is_straight_line_draw_test.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/graph/test/is_straight_line_draw_test.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/graph/test/is_straight_line_draw_test.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": 29.0925925926, "max_line_length": 73, "alphanum_fraction": 0.6250795672, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658109754052, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6029452283261734}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Pawel Dlotko\n *\n *    Copyright (C) 2016 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE \"Persistence_landscapes_on_grid_test\"\n#include <boost/test/unit_test.hpp>\n#include <gudhi/reader_utils.h>\n#include <gudhi/Persistence_landscape_on_grid.h>\n#include <gudhi/Unitary_tests_utils.h>\n\n#include <iostream>\n\nusing namespace Gudhi;\nusing namespace Gudhi::Persistence_representations;\n\ndouble epsilon = 0.0005;\n\nBOOST_AUTO_TEST_CASE(check_construction_of_landscape) {\n  Persistence_landscape_on_grid l(\"data/file_with_diagram_1\", 100, std::numeric_limits<unsigned short>::max());\n  l.print_to_file(\"landscape_from_file_with_diagram_1\");\n\n  Persistence_landscape_on_grid g;\n  g.load_landscape_from_file(\"landscape_from_file_with_diagram_1\");\n\n  BOOST_CHECK(l == g);\n}\n\nBOOST_AUTO_TEST_CASE(check_construction_of_landscape_using_only_ten_levels) {\n  // TODO\n  unsigned number = 10;\n  Persistence_landscape_on_grid l(\"data/file_with_diagram_1\", 100, number);\n  Persistence_landscape_on_grid g(\"data/file_with_diagram_1\", 100, std::numeric_limits<unsigned short>::max());\n  // cut all the elements of order > 10 in g.\n\n  for (size_t level = 0; level != number; ++level) {\n    std::vector<double> v1 = l.vectorize(level);\n    std::vector<double> v2 = g.vectorize(level);\n    BOOST_CHECK(v1.size() == v2.size());\n    for (size_t i = 0; i != v1.size(); ++i) {\n      GUDHI_TEST_FLOAT_EQUALITY_CHECK(v1[i], v2[i]);\n    }\n  }\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_integrals) {\n  Persistence_landscape_on_grid p(\"data/file_with_diagram_1\", 100, std::numeric_limits<unsigned short>::max());\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_integral_of_landscape(), 27.343, epsilon);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_integrals_for_each_level_separatelly) {\n  Persistence_landscape_on_grid p(\"data/file_with_diagram_1\", 100, std::numeric_limits<unsigned short>::max());\n\n  std::vector<double> integrals_fir_different_levels;\n  // integrals_fir_different_levels.push_back();\n  integrals_fir_different_levels.push_back(0.241168);\n  integrals_fir_different_levels.push_back(0.239276);\n  integrals_fir_different_levels.push_back(0.237882);\n  integrals_fir_different_levels.push_back(0.235193);\n  integrals_fir_different_levels.push_back(0.230115);\n  integrals_fir_different_levels.push_back(0.227626);\n  integrals_fir_different_levels.push_back(0.226132);\n  integrals_fir_different_levels.push_back(0.223643);\n  integrals_fir_different_levels.push_back(0.221651);\n  integrals_fir_different_levels.push_back(0.220556);\n  integrals_fir_different_levels.push_back(0.21727);\n  integrals_fir_different_levels.push_back(0.215976);\n  integrals_fir_different_levels.push_back(0.213685);\n  integrals_fir_different_levels.push_back(0.211993);\n  integrals_fir_different_levels.push_back(0.2102);\n  integrals_fir_different_levels.push_back(0.208707);\n  integrals_fir_different_levels.push_back(0.207014);\n  integrals_fir_different_levels.push_back(0.205122);\n  integrals_fir_different_levels.push_back(0.204226);\n  integrals_fir_different_levels.push_back(0.202633);\n\n  for (size_t level = 0; level != integrals_fir_different_levels.size(); ++level) {\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_integral_of_landscape(level), integrals_fir_different_levels[level],\n                                    epsilon);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_integrals_of_powers_of_landscape) {\n  Persistence_landscape_on_grid p(\"data/file_with_diagram_1\", 100, std::numeric_limits<unsigned short>::max());\n\n  std::vector<double> integrals_fir_different_powers;\n  integrals_fir_different_powers.push_back(0.241168);\n  integrals_fir_different_powers.push_back(0.239276);\n  integrals_fir_different_powers.push_back(0.237882);\n  integrals_fir_different_powers.push_back(0.235193);\n  integrals_fir_different_powers.push_back(0.23011);\n\n  for (size_t power = 0; power != 5; ++power) {\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_integral_of_landscape(power), integrals_fir_different_powers[power],\n                                    epsilon);\n  }\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_values_on_different_points) {\n  Persistence_landscape_on_grid p(\"data/file_with_diagram_1\", 100, std::numeric_limits<unsigned short>::max());\n\n  std::vector<double> results_level_0;\n  results_level_0.push_back(0.00997867);\n  results_level_0.push_back(0.0521921);\n  results_level_0.push_back(0.104312);\n  results_level_0.push_back(0.156432);\n  results_level_0.push_back(0.208552);\n  results_level_0.push_back(0.260672);\n  results_level_0.push_back(0.312792);\n  results_level_0.push_back(0.364912);\n  results_level_0.push_back(0.417032);\n  results_level_0.push_back(0.429237);\n\n  std::vector<double> results_level_10;\n  results_level_10.push_back(7.21433e-05);\n  results_level_10.push_back(0.0422135);\n  results_level_10.push_back(0.0943335);\n  results_level_10.push_back(0.146453);\n  results_level_10.push_back(0.198573);\n  results_level_10.push_back(0.240715);\n  results_level_10.push_back(0.272877);\n  results_level_10.push_back(0.324997);\n  results_level_10.push_back(0.359232);\n  results_level_10.push_back(0.379344);\n\n  double x = 0.0012321;\n  double dx = 0.05212;\n  for (size_t i = 0; i != 10; ++i) {\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(0, x), results_level_0[i], epsilon);\n    GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_value_at_a_given_point(10, x), results_level_10[i], epsilon);\n    x += dx;\n  }\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_sum_differences_and_multiplications) {\n  Persistence_landscape_on_grid p(\"data/file_with_diagram_1\", 100, std::numeric_limits<unsigned short>::max());\n  Persistence_landscape_on_grid second(\"data/file_with_diagram_1\", 100, std::numeric_limits<unsigned short>::max());\n\n  Persistence_landscape_on_grid sum = p + second;\n  Persistence_landscape_on_grid difference = p - second;\n  Persistence_landscape_on_grid multiply_by_scalar = 10 * p;\n  ;\n\n  Persistence_landscape_on_grid template_sum;\n  template_sum.load_landscape_from_file(\"data/sum_on_grid_test\");\n\n  Persistence_landscape_on_grid template_difference;\n  template_difference.load_landscape_from_file(\"data/difference_on_grid_test\");\n\n  Persistence_landscape_on_grid template_multiply_by_scalar;\n  template_multiply_by_scalar.load_landscape_from_file(\"data/multiply_by_scalar_on_grid_test\");\n\n  BOOST_CHECK(sum == template_sum);\n  BOOST_CHECK(difference == template_difference);\n  BOOST_CHECK(multiply_by_scalar == template_multiply_by_scalar);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_maxima_and_norms) {\n  Persistence_landscape_on_grid p(\"data/file_with_diagram_1\", 0., 1., 100);\n  Persistence_landscape_on_grid second(\"data/file_with_diagram_2\", 0., 1., 100);\n  Persistence_landscape_on_grid sum = p + second;\n\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_maximum(), 0.46, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_norm_of_landscape(1), 27.3373, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_norm_of_landscape(2), 1.84143, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_norm_of_landscape(3), 0.927067, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(compute_distance_of_landscapes_on_grid(p, sum, 1), 16.8519, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(compute_distance_of_landscapes_on_grid(p, sum, 2), 1.44542, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(compute_distance_of_landscapes_on_grid(p, sum, std::numeric_limits<double>::max()),\n                                  0.45, epsilon);\n}\n\nBOOST_AUTO_TEST_CASE(check_default_parameters_of_distances) {\n  std::vector<std::pair<double, double> > diag = read_persistence_intervals_in_dimension(\"data/file_with_diagram\");\n  Persistence_landscape_on_grid p(diag, 0., 1., 100);\n\n  std::vector<std::pair<double, double> > diag1 = read_persistence_intervals_in_dimension(\"data/file_with_diagram_1\");\n  Persistence_landscape_on_grid q(diag1, 0., 1., 100);\n\n  double dist_numeric_limit_max = p.distance(q, std::numeric_limits<double>::max());\n  double dist_infinity = p.distance(q, std::numeric_limits<double>::infinity());\n\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(dist_numeric_limit_max, dist_infinity);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_averages) {\n  Persistence_landscape_on_grid p(\"data/file_with_diagram\", 0., 1., 100);\n  Persistence_landscape_on_grid q(\"data/file_with_diagram_1\", 0., 1., 100);\n  Persistence_landscape_on_grid av;\n  av.compute_average({&p, &q});\n\n  Persistence_landscape_on_grid template_average;\n  template_average.load_landscape_from_file(\"data/average_on_a_grid\");\n  BOOST_CHECK(template_average == av);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_distances) {\n  Persistence_landscape_on_grid p(\"data/file_with_diagram\", 0., 1., 10000);\n  Persistence_landscape_on_grid q(\"data/file_with_diagram_1\", 0., 1., 10000);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.distance(q), 25.5779, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.distance(q, 2), 2.04891, epsilon);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.distance(q, std::numeric_limits<double>::max()), 0.359, epsilon);\n}\n\nBOOST_AUTO_TEST_CASE(check_computations_of_scalar_product) {\n  Persistence_landscape_on_grid p(\"data/file_with_diagram\", 0., 1., 10000);\n  Persistence_landscape_on_grid q(\"data/file_with_diagram_1\", 0., 1., 10000);\n  GUDHI_TEST_FLOAT_EQUALITY_CHECK(p.compute_scalar_product(q), 0.754367, epsilon);\n}\n\n// Below I am storing the code used to generate tests for that functionality.\n/*\n        Persistence_landscape_on_grid l( \"file_with_diagram_1\" , 100 );\n        l.print_to_file( \"landscape_from_file_with_diagram_1\" );\n\n        Persistence_landscape_on_grid g;\n        g.load_landscape_from_file( \"landscape_from_file_with_diagram_1\" );\n\n        cerr << ( l == g );\n        */\n\n/*\nPersistence_landscape_on_grid l( \"file_with_diagram_1\" , 100 );\ncerr << l << endl;\ncerr << l.compute_integral_of_landscape() << endl;\n*/\n\n/*\nPersistence_landscape_on_grid p( \"file_with_diagram_1\" , 100 );\nfor ( size_t level = 0 ; level != 30 ; ++level )\n{\n        double integral = p.compute_integral_of_landscape( level );\n        cerr << integral << endl;\n}\n*/\n\n/*\nPersistence_landscape_on_grid p( \"file_with_diagram_1\" , 100 );\nfor ( size_t power = 0 ; power != 5 ; ++power )\n{\n        double integral = p.compute_integral_of_landscape( (double)power );\n        cerr << integral << endl;\n}\n*/\n\n/*\nPersistence_landscape_on_grid p( \"file_with_diagram_1\" , 100 );\ndouble x = 0.0012321;\ndouble dx = 0.05212;\nfor ( size_t i = 0 ; i != 10 ; ++i )\n{\n       cerr << p.compute_value_at_a_given_point(10,x) << endl;\n       x += dx;\n}\n*/\n\n/*\nPersistence_landscape_on_grid p( \"file_with_diagram_1\",100 );\nPersistence_landscape_on_grid second(\"file_with_diagram_1\",100 );\nPersistence_landscape_on_grid sum = p + second;\nPersistence_landscape_on_grid difference = p - second;\nPersistence_landscape_on_grid multiply_by_scalar = 10*p;\nsum.print_to_file( \"sum_on_grid_test\" );\ndifference.print_to_file( \"difference_on_grid_test\" );\nmultiply_by_scalar.print_to_file( \"multiply_by_scalar_on_grid_test\" );\n*/\n\n/*\nPersistence_landscape_on_grid p( \"file_with_diagram_1\" , 0 , 1 , 100 );\nPersistence_landscape_on_grid second(\"file_with_diagram_1\", 0 , 1 , 100 );\nPersistence_landscape_on_grid sum = p + second;\n\ncerr << \"max : \" << p.compute_maximum() << endl;\ncerr << \"1-norm : \" << p.compute_norm_of_landscape(1) << endl;\ncerr << \"2-norm : \" << p.compute_norm_of_landscape(2) << endl;\ncerr << \"3-norm : \" << p.compute_norm_of_landscape(3) << endl;\n\ncerr <<  compute_distance_of_landscapes_on_grid(p,sum,1) << endl;\ncerr <<  compute_distance_of_landscapes_on_grid(p,sum,2) << endl;\ncerr <<  compute_distance_of_landscapes_on_grid(p,sum,-1)  << endl;\n*/\n\n/*\nPersistence_landscape_on_grid p( \"file_with_diagram\", 0,1,100 );\nPersistence_landscape_on_grid q( \"file_with_diagram_1\", 0,1,100 );\nPersistence_landscape_on_grid av;\nav.compute_average( {&p,&q} );\nav.print_to_file(\"average_on_a_grid\");\n\nPersistence_landscape_on_grid template_average;\ntemplate_average.load_landscape_from_file( \"average_on_a_grid\" );\nif ( template_average == av )\n{\n        cerr << \"OK OK \\n\";\n}*/\n\n/*\nPersistence_landscape_on_grid p( \"file_with_diagram\" , 0,1,10000);\nPersistence_landscape_on_grid q( \"file_with_diagram_1\" , 0,1,10000);\ncerr <<  p.distance( &q )<< endl;\ncerr <<  p.distance( &q , 2 ) << endl;\ncerr <<  p.distance( &q , std::numeric_limits<double>::max() ) << endl;\n*/\n\n/*\n        Persistence_landscape_on_grid p( \"file_with_diagram\", 0,1,10000 );\n        Persistence_landscape_on_grid q( \"file_with_diagram_1\", 0,1,10000 );\n\n        //std::vector< std::pair< double,double > > aa;\n        //aa.push_back( std::make_pair( 0,1 ) );\n        //Persistence_landscape_on_grid p( aa, 0,1,10 );\n        //Persistence_landscape_on_grid q( aa, 0,1,10 );\n        cerr <<  p.compute_scalar_product( &q ) << endl;\n*/\n", "meta": {"hexsha": "f73da7510ebd130078b0d886e8e3eac8a11af5ee", "size": 13054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Persistence_representations/test/persistence_lanscapes_on_grid_test.cpp", "max_stars_repo_name": "jmarino/gudhi-devel", "max_stars_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T14:10:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:14:52.000Z", "max_issues_repo_path": "src/Persistence_representations/test/persistence_lanscapes_on_grid_test.cpp", "max_issues_repo_name": "jmarino/gudhi-devel", "max_issues_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 398.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:55:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:50:40.000Z", "max_forks_repo_path": "src/Persistence_representations/test/persistence_lanscapes_on_grid_test.cpp", "max_forks_repo_name": "jmarino/gudhi-devel", "max_forks_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2019-03-08T15:58:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:23:23.000Z", "avg_line_length": 40.6666666667, "max_line_length": 118, "alphanum_fraction": 0.7643634135, "num_tokens": 3580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.795658090372256, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6029452266954585}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n\n//ComputeSVD algorithm test.\n#include <gtest/gtest.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/MatrixComparison.h>\n#include <Testing/Utils/MatrixTestUtilities.h>\n#include <Core/Algorithms/Math/ComputeSVD.h>\n#include <Eigen/SVD>\n\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms::Math;\nusing namespace SCIRun::TestUtils;\n\nnamespace\n{\n    //Matrix for input.\n    DenseMatrixHandle inputMatrix()\n    {\n        //Hard coded for testing.\n        int column1 [12] = {5,4,7,8,10,10,4,6,8,7,9,6};\n        int column2 [12] = {7,6,9,8,5,7,9,3,4,5,5,9};\n\n        //Puts the columns into a matrix.\n        DenseMatrixHandle inputM(boost::make_shared<DenseMatrix>(12,2));\n        for (int i = 0; i < inputM->rows(); i++){\n            (*inputM)(i,0) = column1[i];\n            (*inputM)(i,1) = column2[i];\n        }\n        return inputM;\n    }\n}\n\n//Checks if the outputs are correct.\n//U,S,V: U: Left singular matrix, S: Singular values, V: Right singular matrix.\nTEST(ComputeSVDtest, checkOutputs)\n{\n    ComputeSVDAlgo algo;\n\n    DenseMatrixHandle m1(inputMatrix());\n    DenseMatrixHandle LeftSingularMatrix_U;\n    DenseMatrixHandle SingularValues_S;\n    DenseMatrixHandle RightSingularMatrix_V;\n\n    //Runs algorithm.\n    algo.run(m1,LeftSingularMatrix_U,SingularValues_S,RightSingularMatrix_V);\n\n    //Testing if the results are null.\n    ASSERT_NE(nullptr,LeftSingularMatrix_U);\n    ASSERT_NE(nullptr,SingularValues_S);\n    ASSERT_NE(nullptr,RightSingularMatrix_V);\n\n    //Check the dimensions of the matrices that were created for output.\n\n    //Rows\n    ASSERT_EQ(12,LeftSingularMatrix_U->rows());\n    ASSERT_EQ(2,SingularValues_S->rows());\n    ASSERT_EQ(2,RightSingularMatrix_V->rows());\n\n    //Columns\n    ASSERT_EQ(12,LeftSingularMatrix_U->cols());\n    ASSERT_EQ(1,SingularValues_S->cols());\n    ASSERT_EQ(2,RightSingularMatrix_V->cols());\n\n    //Eigen does not create a diagonal matrix when it computes SVD, it just has a column with the singular values, so we must put it into a diagonal matrix to be able to do some matrix multiplication later.\n    DenseMatrix sDiag = Eigen::MatrixXd::Constant(12,2,0);\n    sDiag.diagonal() = SingularValues_S->col(0);\n\n    //Multiplying back together and comparing to the centered matrix. They should be equal to each other with some tolerance.\n    DenseMatrix product = (*LeftSingularMatrix_U) * sDiag * (*RightSingularMatrix_V).transpose();\n\n    auto expected = *inputMatrix();\n\n    //Comparing each element in the matrices.\n    for (int i = 0; i < product.rows(); ++i) {\n        for (int j = 0; j < product.cols(); ++j)\n            ASSERT_NEAR(expected(i,j), product(i,j), 1e-5);\n    }\n\n}\n\n//Tests for input with a dimension of zero.\nTEST(ComputeSVDtest, ThrowsForZeroDimensionInput)\n{\n    ComputeSVDAlgo algo;\n\n    DenseMatrixHandle m1(new DenseMatrix(5, 0));\n    DenseMatrixHandle m2(new DenseMatrix(0, 5));\n    DenseMatrixHandle m3(new DenseMatrix(0, 0));\n\n    DenseMatrixHandle LeftSingularMatrix_U;\n    DenseMatrixHandle SingularValues_S;\n    DenseMatrixHandle RightSingularMatrix_V;\n\n    //Runs algorithm and expects an error.\n    EXPECT_ANY_THROW(algo.run(m1,LeftSingularMatrix_U,SingularValues_S,RightSingularMatrix_V));\n    EXPECT_ANY_THROW(algo.run(m2,LeftSingularMatrix_U,SingularValues_S,RightSingularMatrix_V));\n    EXPECT_ANY_THROW(algo.run(m3,LeftSingularMatrix_U,SingularValues_S,RightSingularMatrix_V));\n\n}\n", "meta": {"hexsha": "28545a836a288991fa712fcc22a57d35653853d0", "size": 4670, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Math/Tests/ComputeSVDtest.cc", "max_stars_repo_name": "Haydelj/SCIRun", "max_stars_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_stars_repo_licenses": ["MIT"], "max_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/Algorithms/Math/Tests/ComputeSVDtest.cc", "max_issues_repo_name": "Haydelj/SCIRun", "max_issues_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Algorithms/Math/Tests/ComputeSVDtest.cc", "max_forks_repo_name": "Haydelj/SCIRun", "max_forks_repo_head_hexsha": "f7ee04d85349b946224dbff183438663e54b9413", "max_forks_repo_licenses": ["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.7716535433, "max_line_length": 206, "alphanum_fraction": 0.725267666, "num_tokens": 1182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6029304524598643}}
{"text": "/*    Copyright (c) 2010-2018, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n */\n\n#include <boost/math/special_functions/factorials.hpp>\n\n#include \"Tudat/Mathematics/BasicMathematics/legendrePolynomials.h\"\n#include \"Tudat/Astrodynamics/Gravitation/triAxialEllipsoidGravity.h\"\n\nnamespace tudat\n{\n\nnamespace gravitation\n{\n\n//! Function to calculate (non-normalized) cosine spherical harmonic coefficient for a homogeneous\n//! triaxial ellipsoid\ndouble calculateCosineTermForTriaxialEllipsoidSphericalHarmonicGravity(\n        const double aSquaredMinusCSquared, const double bSquaredMinusCSquared,\n        const double referenceRadius, const int degree, const int order )\n{\n    // Initialize coefficient to zero\n    double powerSeries = 0.0;\n\n    // Only non-zero terms are for even degree and order\n    if( !( ( degree % 2 != 0 || order % 2 != 0 ) ) )\n    {\n        using boost::math::factorial;\n\n        // Calculate indices for algorithm\n        int l = degree / 2;\n        int m = order / 2;\n        int maximumIndex = std::floor( ( l - m ) / 2 );\n\n        // Evaluate single term in power series of final equation of Boyce (1997)\n        for( int i = 0; i <= maximumIndex; i++ )\n        {\n            powerSeries +=\n                    ( std::pow( ( aSquaredMinusCSquared - bSquaredMinusCSquared ) /\n                                2.0, m + 2 * i ) *\n                      std::pow( -( aSquaredMinusCSquared + bSquaredMinusCSquared ) /\n                                2.0, l - m - 2 * i ) ) /\n                    ( std::pow( 2.0, m + 2 * i ) * factorial< double >( l - m - 2 * i ) *\n                      factorial< double >( m + i ) * factorial< double >( i ) );\n        }\n\n        // Calculate multiplier of power series in final equation of Boyce (1997)\n        double multiplier = 3.0 / std::pow( referenceRadius, 2 * l ) *\n                ( factorial< double >( l ) * factorial< double >( 2 * l - 2 * m ) ) /\n                ( ( 2.0 * static_cast< double >( l ) + 3.0 ) * factorial< double >( 2 * l + 1 ) );\n        if( order != 0 )\n        {\n            multiplier *= 2.0;\n        }\n\n        // Complete calculation of coefficient\n        powerSeries *= multiplier;\n    }\n    return powerSeries;\n}\n\n//! Function to calculate triaxial ellipsoid reference radius\ndouble calculateTriAxialEllipsoidReferenceRadius(\n        const double axisA, const double axisB, const double axisC )\n{\n    return std::sqrt( 3.0 / ( 1.0 / ( axisA * axisA ) + 1.0 / ( axisB * axisB ) +\n                              1.0 / ( axisC * axisC ) ) );\n}\n\n//! Function to calculate triaxial ellipsoid volume\ndouble calculateTriAxialEllipsoidVolume(\n        const double axisA, const double axisB, const double axisC )\n{\n    return 4.0 / 3.0 * mathematical_constants::PI * axisA * axisB * axisC;\n}\n\n//! Function to calculate (non-normalized) cosine spherical harmonic coefficients for a\n//! homogeneous triaxial ellipsoid\nEigen::MatrixXd createTriAxialEllipsoidSphericalHarmonicCosineCoefficients(\n        const double axisA, const double axisB, const double axisC,\n        const int maximumDegree, const int maximumOrder )\n{\n    // Initialize vector to zeros\n    Eigen::MatrixXd cosineCoefficients = Eigen::MatrixXd::Zero(\n                maximumDegree + 1, maximumOrder + 1 );\n\n    // Pre-calculate for single coefficient calculations.\n    double aSquaredMinusCSquared = axisA * axisA - axisC * axisC;\n    double bSquaredMinusCSquared = axisB * axisB - axisC * axisC;\n    double referenceRadius =  calculateTriAxialEllipsoidReferenceRadius( axisA, axisB, axisC );\n\n    // Iterate over all requested degrees.\n    for( int i = 0; i <= maximumDegree; i++ )\n    {\n        // Iterate over all requested orders.\n        for( int j = 0; ( ( j <= maximumOrder ) && ( j <= i ) ); j++ )\n        {\n            // Only even degree and order terms are non-zero\n            if( ( i % 2 == 0 ) && ( j % 2 == 0 ) )\n            {\n                // Calculate coefficient at single degree and order.\n                cosineCoefficients( i, j ) =\n                        calculateCosineTermForTriaxialEllipsoidSphericalHarmonicGravity(\n                            aSquaredMinusCSquared, bSquaredMinusCSquared, referenceRadius, i, j );\n            }\n        }\n    }\n\n    return cosineCoefficients;\n}\n\n//! Function to calculate (non-normalized) cosine and sine spherical harmonic coefficients for a\n//! homogeneous triaxial ellipsoid\nstd::pair< Eigen::MatrixXd, Eigen::MatrixXd > createTriAxialEllipsoidSphericalHarmonicCoefficients(\n        const double axisA, const double axisB, const double axisC,\n        const int maximumDegree, const int maximumOrder )\n{\n    // Calculate cosine coefficients and add sine matrix (all zeroes)\n    return std::make_pair( createTriAxialEllipsoidSphericalHarmonicCosineCoefficients(\n                               axisA, axisB, axisC, maximumDegree, maximumOrder ),\n                           Eigen::MatrixXd::Zero( maximumDegree + 1, maximumOrder + 1 ) );\n}\n\n//! Function to calculate (normalized) cosine and sine spherical harmonic coefficients for a\n//! homogeneous triaxial ellipsoid\nstd::pair< Eigen::MatrixXd, Eigen::MatrixXd >\ncreateTriAxialEllipsoidNormalizedSphericalHarmonicCoefficients(\n        const double axisA, const double axisB, const double axisC,\n        const int maximumDegree, const int maximumOrder )\n{\n    // Calculate non-normalized coefficients\n    std::pair< Eigen::MatrixXd, Eigen::MatrixXd > unNormalizedCoefficients =\n            createTriAxialEllipsoidSphericalHarmonicCoefficients(\n                axisA, axisB, axisC, maximumDegree, maximumOrder );\n\n    // Retrieve cosine coefficients\n    Eigen::MatrixXd normalizedCosineCoefficients = unNormalizedCoefficients.first;\n\n    // Iterate over all degrees and orders and normalized coefficients\n    for( int i = 2; i < normalizedCosineCoefficients.rows( ); i++ )\n    {\n        for( int j = 0; ( ( j < normalizedCosineCoefficients.cols( ) ) &&\n                                   ( j <= i ) ); j++ )\n        {\n            normalizedCosineCoefficients( i, j ) = normalizedCosineCoefficients( i, j ) /\n                    basic_mathematics::calculateLegendreGeodesyNormalizationFactor( i, j );\n        }\n    }\n\n    // Return geodesy-normalized coefficients.\n    return std::make_pair( normalizedCosineCoefficients, unNormalizedCoefficients.second );\n}\n\n}\n\n}\n", "meta": {"hexsha": "d427319898b2170463c177fb85b8650064842095", "size": 6678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/triAxialEllipsoidGravity.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Gravitation/triAxialEllipsoidGravity.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Gravitation/triAxialEllipsoidGravity.cpp", "max_forks_repo_name": "J-Westin/tudat", "max_forks_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7195121951, "max_line_length": 99, "alphanum_fraction": 0.6365678347, "num_tokens": 1615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898229217591, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.6028551942892948}}
{"text": "#define BOOST_TEST_MODULE test_mat_vec_mul\n#include <boost/test/included/unit_test.hpp>\n#include <boost/mpl/list.hpp>\n\n#include <mave/mave.hpp>\n#include <tests/generate_random_matrices.hpp>\n#include <tests/tolerance.hpp>\n\ntypedef boost::mpl::list<double, float> test_targets;\n\nconstexpr std::size_t N = 12000;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(mat3x3_vec3, T, test_targets)\n{\n    std::mt19937 mt(123456789);\n\n    const auto matrices = mave::test::generate_random_positive<mave::matrix<T, 3, 3>>(N, mt);\n    const auto vectors  = mave::test::generate_random_positive<mave::vector<T, 3>>(N, mt);\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const auto& m = matrices.at(i);\n        const auto& v = vectors.at(i);\n\n        const auto v2 = m * v;\n\n        BOOST_TEST(v2[0] == m(0,0)*v[0] + m(0,1)*v[1] + m(0,2)*v[2], mave::test::tolerance<T>());\n        BOOST_TEST(v2[1] == m(1,0)*v[0] + m(1,1)*v[1] + m(1,2)*v[2], mave::test::tolerance<T>());\n        BOOST_TEST(v2[2] == m(2,0)*v[0] + m(2,1)*v[1] + m(2,2)*v[2], mave::test::tolerance<T>());\n\n        BOOST_TEST(v.diagnosis());\n        BOOST_TEST(v2.diagnosis());\n    }\n}\n", "meta": {"hexsha": "68895d3d6ac64f19dfce7c48bd67f55d21fe2a37", "size": 1119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_mat_vec_mul.cpp", "max_stars_repo_name": "ToruNiina/mave", "max_stars_repo_head_hexsha": "163cbf273003c3fb940338cf82b1fa154a3012c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-09-09T17:46:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T00:29:04.000Z", "max_issues_repo_path": "tests/test_mat_vec_mul.cpp", "max_issues_repo_name": "ToruNiina/mave", "max_issues_repo_head_hexsha": "163cbf273003c3fb940338cf82b1fa154a3012c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/test_mat_vec_mul.cpp", "max_forks_repo_name": "ToruNiina/mave", "max_forks_repo_head_hexsha": "163cbf273003c3fb940338cf82b1fa154a3012c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-04T11:02:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T11:02:20.000Z", "avg_line_length": 31.9714285714, "max_line_length": 97, "alphanum_fraction": 0.6219839142, "num_tokens": 380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.6654105454764747, "lm_q1q2_score": 0.6028551839555347}}
{"text": "#include \"geoutil.h\"\n#include \"position.h\"\n#include <Eigen/Dense>\n#include <cmath>\n\nusing namespace himan;\nusing namespace Eigen;\n\ndouble geoutil::Distance(const point& a, const point& b, double r)\n{\n\tconst double alpha = std::pow(std::sin((b.Y() - a.Y()) / 360 * M_PI), 2) +\n\t               std::cos(a.Y() / 180 * M_PI) * std::cos(b.Y() / 180 * M_PI) *\n\t                   std::pow(std::sin((b.X() - a.X()) / 360 * M_PI), 2);\n\treturn r * 2 * std::atan2(std::sqrt(alpha), std::sqrt(1 - alpha));\n}\n\ndouble geoutil::Area(const point& P1, const point& P2, const point& P3, double r)\n{\n\tconst position<double> p1(P1.Y() / 180 * M_PI, P1.Y() / 180 * M_PI, 0, earth_shape<double>(r));\n\tconst position<double> p2(P2.Y() / 180 * M_PI, P2.X() / 180 * M_PI, 0, earth_shape<double>(r));\n\tconst position<double> p3(P3.Y() / 180 * M_PI, P3.X() / 180 * M_PI, 0, earth_shape<double>(r));\n\n\tconst Matrix<double, 3, 1> A(p1.Data());\n\tconst Matrix<double, 3, 1> B(p2.Data());\n\tconst Matrix<double, 3, 1> C(p3.Data());\n\tconst double a = std::atan(A.cross(B).norm() / A.dot(B));\n\tconst double b = std::atan(B.cross(C).norm() / B.dot(C));\n\tconst double c = std::atan(C.cross(A).norm() / C.dot(A));\n\tconst double s = (a + b + c) / 2;\n\treturn 4 *\n\t       std::atan(\n\t           std::sqrt(std::tan(s / 2) * std::tan((s - a) / 2) * std::tan((s - b) / 2) * std::tan((s - c) / 2))) *\n\t       r * r;\n}\n\ndouble geoutil::Bearing(const point& a, const point& b)\n{\n\treturn std::atan2(std::sin((b.X() - a.X())/180*M_PI) * std::cos(b.Y()/180*M_PI) , std::cos(a.Y()/180*M_PI) * std::sin(b.Y()/180*M_PI) - std::sin(a.Y()/180*M_PI) * std::cos(b.Y()/180*M_PI) * std::cos((b.X() - a.X())/180*M_PI));\n}\n\nbool geoutil::InsideTriangle(const point& a, const point& b, const point& c, const point& p)\n{\n\tconst double epsilon = 1e-12;\n\n\tposition<double> A(a.Y() / 180 * M_PI, a.X() / 180 * M_PI, 0, earth_shape<double>(1));\n\tposition<double> B(b.Y() / 180 * M_PI, b.X() / 180 * M_PI, 0, earth_shape<double>(1));\n\tposition<double> C(c.Y() / 180 * M_PI, c.X() / 180 * M_PI, 0, earth_shape<double>(1));\n\n\tposition<double> P(p.Y() / 180 * M_PI, p.X() / 180 * M_PI, 0, earth_shape<double>(1));\n\n\tMatrix<double, 3, 1> v(P.Data());\n\tMatrix<double, 3, 3> M;\n\tM << A.X(), B.X(), C.X(), A.Y(), B.Y(), C.Y(), A.Z(), B.Z(), C.Z();\n\n\tColPivHouseholderQR<Matrix<double, 3, 3>> dec(M);\n\n\tMatrix<double, 3, 1> beta = dec.solve(v);\n\n\treturn beta(0) >= -epsilon && beta(1) >= -epsilon && beta(2) >= -epsilon;\n}\n", "meta": {"hexsha": "fb94a98c927d2f390ec8a80354db0b060ff69940", "size": 2448, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "himan-lib/source/geoutil.cpp", "max_stars_repo_name": "fox91/himan", "max_stars_repo_head_hexsha": "4bb0ba4b034675edb21a1b468c0104f00f78784b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2017-04-20T18:51:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:12:49.000Z", "max_issues_repo_path": "himan-lib/source/geoutil.cpp", "max_issues_repo_name": "fox91/himan", "max_issues_repo_head_hexsha": "4bb0ba4b034675edb21a1b468c0104f00f78784b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-07-05T02:15:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T09:36:51.000Z", "max_forks_repo_path": "himan-lib/source/geoutil.cpp", "max_forks_repo_name": "fox91/himan", "max_forks_repo_head_hexsha": "4bb0ba4b034675edb21a1b468c0104f00f78784b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-18T06:32:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T15:17:09.000Z", "avg_line_length": 40.131147541, "max_line_length": 227, "alphanum_fraction": 0.5735294118, "num_tokens": 868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582593509315, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.6027491896329249}}
{"text": "/**\t\\file \ttest_main.cpp\n*\t\\brief\tTesting Kernels in MLearnKernels.h\n*/\n// Test framework\n#define CATCH_CONFIG_MAIN\n#include <catch.hpp>\n#include <test_common.h>\n\n// MLearn\n#include <MLearn/Core>\n#include <MLearn/StochasticProcess/GaussianProcess/GP.h>\n#include \"test_gp_utils.h\"\n\n// Eigen \n#include <Eigen/Core>\n\nTEST_CASE(\"Test computation of covariance matrix\"){\n\ttypedef double FT;\n\tusing namespace MLearn;\n\tusing namespace TestUtils;\n\tusing namespace SP;\n\tusing namespace GP;\n\n\tuint N = 5;\n\tuint dim = 10;\n\n\tMLMatrix<FT> pts = MLMatrix<FT>::Random(dim, N);\n\tMLMatrix<FT> other_pts = MLMatrix<FT>::Random(dim, 2*N);\n\n\tSECTION(\"Test expected result with mock kernel\"){\n\t\tMLMatrix<FT> covariance = MLMatrix<FT>::Zero(N, N);\n\t\tMockKernel K;\n\n\t\tcompute_gp_covariance(pts, K, covariance);\n\n\t\tREQUIRE(diff_norm(pts.transpose()*pts, covariance) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t}\n\t\n\tSECTION(\"Test compilation with a real kernel\"){\n\t\tMLMatrix<FT> covariance = MLMatrix<FT>::Zero(N, N);\n\t\tKernel< KernelType::LINEAR > K;\n\t\tcompute_gp_covariance(pts, K, covariance);\n\t}\n\n\tSECTION(\"Test expected result with mock kernel and two set of points\"){\n\t\tMockKernel K;\n\t\tMLMatrix<FT> covariance = MLMatrix<FT>::Zero(N, 2*N);\n\n\t\tcompute_gp_covariance(pts, other_pts, K, covariance);\n\n\t\tREQUIRE(diff_norm(pts.transpose()*other_pts, covariance) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t}\n\n\tSECTION(\"Test consistent results\"){\n\t\tMockKernel K;\n\t\tMLMatrix<FT> covariance_1 = MLMatrix<FT>::Zero(N, N);\n\t\tMLMatrix<FT> covariance_2 = MLMatrix<FT>::Zero(N, N);\n\n\t\tcompute_gp_covariance(pts, K, covariance_1);\n\t\tcompute_gp_covariance(pts, pts, K, covariance_2);\n\n\t\tREQUIRE(diff_norm(covariance_1, covariance_2) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t}\n}\n\nTEST_CASE(\"Test gaussian process class\"){\n\ttypedef double FT;\n\tusing namespace MLearn;\n\tusing namespace TestUtils;\n\tusing namespace SP;\n\tusing namespace GP;\n\n\tuint N = 3;\n\tuint dim = 10;\n\n\tMLMatrix<FT> pts = MLMatrix<FT>::Random(dim, N);\n\tMLMatrix<FT> covariance(N, N);\n\tMLVector<FT> mean = MLVector<FT>::Random(N);\n\n\tSECTION(\"Test class constructors and assign\"){\n\t\tcovariance << 4, 1,-1,\n\t\t\t\t\t  1, 2, 1,\n\t\t\t\t\t -1, 1, 2;  \n\n\t\tGaussianProcess<FT> ref_gp(mean, covariance);\n\t\tREQUIRE(diff_norm(mean, ref_gp.mean()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tREQUIRE(diff_norm(covariance, ref_gp.covariance()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t\tGaussianProcess<FT> copy_gp(ref_gp);\n\t\tREQUIRE(diff_norm(mean, copy_gp.mean()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tREQUIRE(diff_norm(covariance, copy_gp.covariance()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t\tGaussianProcess<FT> move_gp(std::move(copy_gp));\n\t\tREQUIRE(diff_norm(mean, move_gp.mean()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tREQUIRE(diff_norm(covariance, move_gp.covariance()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t\tGaussianProcess<FT> copy_assign_gp;\n\t\tcopy_assign_gp = ref_gp;\n\t\tREQUIRE(diff_norm(mean, copy_assign_gp.mean()) == \n\t\t \tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tREQUIRE(diff_norm(covariance, copy_assign_gp.covariance()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t\tGaussianProcess<FT> move_assign_gp;\n\t\tmove_assign_gp = std::move(GaussianProcess<FT>(ref_gp));\n\t\tREQUIRE(diff_norm(mean, move_assign_gp.mean()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\t\tREQUIRE(diff_norm(covariance, move_assign_gp.covariance()) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t}\n\t\n\tSECTION(\"Test class sampling\"){\n\t\tuint N_samples = 7;\n\n\t\tKernel< KernelType::LINEAR > K;\n\t\tcompute_gp_covariance(pts, K, covariance);\n\n\t\tGaussianProcess<FT> gp(mean, covariance);\n\n\t\tMLMatrix<FT> samples = gp.sample(N_samples);\n\t\tREQUIRE(samples.rows() == N);\n\t\tREQUIRE(samples.cols() == N_samples);\n\n\t\tgp.set_covariance(MLMatrix<FT>::Zero(N, N));\n\t\tCHECK(diff_norm(gp.covariance(), covariance) > 0.0);\n\n\t\tgp.set_covariance(pts, K);\n\t\tREQUIRE(diff_norm(gp.covariance(), covariance) == \n\t\t\tApprox(0).margin(TEST_FLOAT_TOLERANCE));\n\n\t\tMLMatrix<FT> samples_static = gp.sample(mean, pts, K, N_samples);\n\t\tREQUIRE(samples_static.rows() == N);\n\t\tREQUIRE(samples_static.cols() == N_samples);\n\n\t}\n\n\tSECTION(\"Test confidence intervals\"){\n\t\tGaussianProcess<FT> \n\t\t\tgp(MLVector<FT>::Zero(N), MLMatrix<FT>::Identity(N, N));\n\t\tFT prob = 0.95;\n\t\tMLMatrix<FT> conf_interval = gp.confidence_interval(prob);\n\n\t\tconf_interval = conf_interval.cwiseAbs();\n\t\tconf_interval.array() -= 1.96;\n\n\t\tREQUIRE(diff_norm(MLMatrix<FT>::Zero(2, N), conf_interval) == \n\t\t\tApprox(0).margin(1e-4));\n\n\t}\n}", "meta": {"hexsha": "7ba58c8a1c85f9652facd9a8e009e032a3661a09", "size": 4553, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_stochastic_process/test_gaussian_process/test_main.cpp", "max_stars_repo_name": "phineasng/MLearn", "max_stars_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-11-14T19:37:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-05T02:29:35.000Z", "max_issues_repo_path": "test/test_stochastic_process/test_gaussian_process/test_main.cpp", "max_issues_repo_name": "phineasng/MLearn", "max_issues_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-01-23T17:49:50.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-25T22:43:30.000Z", "max_forks_repo_path": "test/test_stochastic_process/test_gaussian_process/test_main.cpp", "max_forks_repo_name": "phineasng/MLearn", "max_forks_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-23T18:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-23T18:17:14.000Z", "avg_line_length": 28.45625, "max_line_length": 72, "alphanum_fraction": 0.7129365254, "num_tokens": 1307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765707, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6027299736932679}}
{"text": "/*\n * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE bfgs_test\n\n// Standard includes\n#include <iostream>\n\n// Third party includes\n#include <boost/format.hpp>\n#include <boost/test/unit_test.hpp>\n\n// Local VOTCA includes\n#include \"votca/xtp/adiis_costfunction.h\"\n#include \"votca/xtp/bfgs_trm.h\"\n#include \"votca/xtp/logger.h\"\n#include \"votca/xtp/optimiser_costfunction.h\"\n\nusing namespace votca::xtp;\nusing namespace votca;\nusing namespace std;\n\nBOOST_AUTO_TEST_SUITE(bfgs_test)\n\nBOOST_AUTO_TEST_CASE(parabola_test) {\n  class parabola : public Optimiser_costfunction {\n\n    double EvaluateCost(const Eigen::VectorXd& parameters) override {\n      Eigen::VectorXd value = parameters;\n      value(0) -= 2;\n      double cost = value.cwiseAbs2().sum();\n      return cost;\n    }\n\n    Eigen::VectorXd EvaluateGradient(\n        const Eigen::VectorXd& parameters) override {\n      Eigen::VectorXd gradient = 2 * parameters;\n      gradient(0) -= 4;\n      return gradient;\n    }\n\n    bool Converged(const Eigen::VectorXd&, double,\n                   const Eigen::VectorXd& gradient) override {\n      if (gradient.cwiseAbs().maxCoeff() < 1e-8) {\n        return true;\n      } else {\n        return false;\n      }\n    }\n\n    Index NumParameters() const override { return 5; }\n  };\n\n  parabola p5;\n  BFGSTRM bfgstrm(p5);\n  Logger log;\n  bfgstrm.setLog(&log);\n  bfgstrm.setNumofIterations(100);\n  bfgstrm.setTrustRadius(0.1);\n  bfgstrm.Optimize(5 * Eigen::VectorXd::Ones(5));\n\n  Eigen::VectorXd ref = Eigen::VectorXd::Zero(5);\n  ref(0) = 2;\n  bool equal = bfgstrm.getParameters().isApprox(ref, 0.00001);\n  if (!equal) {\n    cout << \"minimum found:\" << endl;\n    cout << bfgstrm.getParameters() << endl;\n    cout << \"minimum ref:\" << endl;\n    cout << ref << endl;\n  } else {\n    cout << bfgstrm.getIteration() << endl;\n  }\n  BOOST_CHECK_EQUAL(equal, 1);\n}\n\nBOOST_AUTO_TEST_CASE(booth_test) {\n  class booth : public Optimiser_costfunction {\n\n    double EvaluateCost(const Eigen::VectorXd& parameters) override {\n      double x = parameters[0];\n      double y = parameters[1];\n\n      return (x + 2 * y - 7) * (x + 2 * y - 7) +\n             (2 * x + y - 5) * (2 * x + y - 5);\n    }\n\n    Eigen::VectorXd EvaluateGradient(\n        const Eigen::VectorXd& parameters) override {\n      double x = parameters[0];\n      double y = parameters[1];\n      Eigen::VectorXd gradient = Eigen::VectorXd::Zero(2);\n      gradient[0] = 2 * (5 * x + 4 * y - 17);\n      gradient[1] = 2 * (4 * x + 5 * y - 19);\n      return gradient;\n    }\n\n    bool Converged(const Eigen::VectorXd&, double,\n                   const Eigen::VectorXd& gradient) override {\n      if (gradient.cwiseAbs().maxCoeff() < 1e-8) {\n        return true;\n      } else {\n        return false;\n      }\n    }\n\n    Index NumParameters() const override { return 2; }\n  };\n\n  booth p2;\n  BFGSTRM bfgstrm(p2);\n  Logger log;\n  bfgstrm.setLog(&log);\n  bfgstrm.setNumofIterations(1000);\n  bfgstrm.setTrustRadius(0.1);\n  bfgstrm.Optimize(5 * Eigen::VectorXd::Ones(2));\n\n  Eigen::VectorXd ref = Eigen::VectorXd::Zero(2);\n  ref << 1, 3;\n  bool equal = bfgstrm.getParameters().isApprox(ref, 0.00001);\n  if (!equal) {\n    cout << \"minimum found:\" << endl;\n    cout << bfgstrm.getParameters() << endl;\n    cout << \"minimum ref:\" << endl;\n    cout << ref << endl;\n  } else {\n    cout << bfgstrm.getIteration() << endl;\n  }\n  BOOST_CHECK_EQUAL(equal, 1);\n}\n\nBOOST_AUTO_TEST_CASE(adiis_test) {\n  Index size = 5;\n\n  Eigen::VectorXd DiF = Eigen::VectorXd::Zero(size);\n  DiF << 0.679243, 0.562675, 0.39399, -0.0258519, 0;\n  Eigen::MatrixXd DiFj = Eigen::MatrixXd::Zero(size, size);\n  DiFj << 0.613998, 0.192684, 0.0326914, -0.193661, 0, 0.192371, 0.0653754,\n      0.0131825, -0.0631915, 0, 0.032739, 0.0131883, 0.0038493, -0.0110991, 0,\n      -0.192873, -0.0631203, -0.0111063, 0.0633221, 0, 0, 0, 0, 0, 0;\n\n  Logger log;\n\n  ADIIS_costfunction a_cost = ADIIS_costfunction(DiF, DiFj);\n  BFGSTRM optimizer = BFGSTRM(a_cost);\n  optimizer.setNumofIterations(1000);\n  optimizer.setTrustRadius(0.01);\n  optimizer.setLog(&log);\n  // Starting point: equal weights on all matrices\n  Eigen::VectorXd coeffs = Eigen::VectorXd::Constant(size, 1.0 / (double)size);\n  optimizer.Optimize(coeffs);\n  bool success = optimizer.Success();\n  coeffs = optimizer.getParameters().cwiseAbs2();\n  double xnorm = coeffs.sum();\n  coeffs /= xnorm;\n\n  BOOST_CHECK_EQUAL(success, true);\n  Eigen::VectorXd ref = Eigen::VectorXd::Zero(size);\n  ref << 0, 0, 0, 0.40826075912352, 0.59173924087648;\n  bool equal = coeffs.isApprox(ref, 0.00001);\n  if (!equal) {\n    cout << \"minimum found:\" << endl;\n    cout << coeffs << endl;\n    cout << \"minimum ref:\" << endl;\n    cout << ref << endl;\n  } else {\n    cout << optimizer.getIteration() << endl;\n  }\n  BOOST_CHECK_EQUAL(equal, 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "2dc87f1e749c14bed966e3f4c9c6338c1477d45b", "size": 5379, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/tests/test_bfgs_trm.cc", "max_stars_repo_name": "rubengerritsen/xtp", "max_stars_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tests/test_bfgs_trm.cc", "max_issues_repo_name": "rubengerritsen/xtp", "max_issues_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tests/test_bfgs_trm.cc", "max_forks_repo_name": "rubengerritsen/xtp", "max_forks_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_forks_repo_licenses": ["Apache-2.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.9193548387, "max_line_length": 79, "alphanum_fraction": 0.6484476669, "num_tokens": 1605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6027299655067769}}
{"text": "\n// solving A * X = B\n// A symmetric/hermitian positive definite\n// factor (potrf()) and solve (potrs())\n\n// #define BOOST_UBLAS_STRICT_HERMITIAN\n// .. doesn't work (yet?)  \n\n//#define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n//#define BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/atlas/cblas1.hpp>\n#include <boost/numeric/bindings/atlas/cblas2.hpp>\n#include <boost/numeric/bindings/atlas/cblas3.hpp>\n#include <boost/numeric/bindings/atlas/clapack.hpp>\n#include <boost/numeric/bindings/traits/ublas_matrix.hpp>\n#include <boost/numeric/bindings/traits/ublas_symmetric.hpp>\n#include <boost/numeric/bindings/traits/ublas_hermitian.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace atlas = boost::numeric::bindings::atlas;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef std::complex<double> cmplx_t; \n\n#ifndef F_ROW_MAJOR\ntypedef ublas::matrix<double, ublas::column_major> m_t;\ntypedef ublas::matrix<cmplx_t, ublas::column_major> cm_t;\n#else\ntypedef ublas::matrix<double, ublas::row_major> m_t;\ntypedef ublas::matrix<cmplx_t, ublas::row_major> cm_t;\n#endif\n\n#ifndef F_UPPER\ntypedef ublas::symmetric_adaptor<m_t, ublas::lower> symm_t; \ntypedef ublas::hermitian_adaptor<cm_t, ublas::lower> herm_t; \n#else\ntypedef ublas::symmetric_adaptor<m_t, ublas::upper> symm_t; \ntypedef ublas::hermitian_adaptor<cm_t, ublas::upper> herm_t; \n#endif \n\nint main() {\n\n  // for more descriptive comments see ublas_posv.cc \n  cout << endl; \n\n  // symmetric \n  cout << \"real symmetric\\n\" << endl; \n\n  size_t n = 5; \n  m_t a (n, n);    \n  symm_t sa (a);   \n#ifdef F_UPPER \n  init_symm (sa, 'u');\n#else\n  init_symm (sa, 'l');\n#endif \n  print_m (sa, \"sa\"); \n  cout << endl; \n\n  size_t nrhs = 2; \n  m_t x (n, nrhs); \n#ifndef F_ROW_MAJOR\n  m_t b (n, nrhs);\n#else\n  m_t b (nrhs, n);\n#endif\n  ublas::matrix_column<m_t> xc0 (x, 0), xc1 (x, 1); \n  atlas::set (1., xc0);  \n  atlas::set (2., xc1);  \n#ifndef F_ROW_MAJOR\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS \n  atlas::symm (sa, x, b);\n#else\n  atlas::symm (CblasLeft, 1.0, sa, x, 0.0, b); \n#endif \n#else\n  ublas::matrix_row<m_t> br0 (b, 0), br1 (b, 1); \n  atlas::symv (sa, xc0, br0); \n  atlas::symv (sa, xc1, br1); \n#endif \n  print_m (b, \"b\"); \n  cout << endl; \n\n  int ierr = atlas::cholesky_factor (sa);  // potrf()\n  if (!ierr) {\n    atlas::cholesky_substitute (sa, b);  // potrs() \n    print_m (b, \"x\"); \n  }\n  cout << endl; \n\n  /////////////////////////////////////////////////////////\n  // hermitian \n  cout << \"\\n===========================\\n\" << endl; \n  cout << \"complex hermitian\\n\" << endl; \n\n  cm_t ca (3, 3);  \n  herm_t ha (ca);  \n  cm_t cx (3, 1);\n#ifndef F_ROW_MAJOR\n  cm_t cb (3, 1);\n#else\n  cm_t cb (1, 3); \n#endif  \n\n#ifndef F_UPPER\n  ha (0, 0) = cmplx_t (3, 0);\n  ha (1, 0) = cmplx_t (4, -2);\n  ha (1, 1) = cmplx_t (5, 0);\n  ha (2, 0) = cmplx_t (-7, -5);\n  ha (2, 1) = cmplx_t (0, 3);\n  ha (2, 2) = cmplx_t (2, 0);\n#else\n  ha (0, 0) = cmplx_t (3, 0);\n  ha (0, 1) = cmplx_t (4, 2);\n  ha (0, 2) = cmplx_t (-7, 5);\n  ha (1, 1) = cmplx_t (5, 0);\n  ha (1, 2) = cmplx_t (0, -3);\n  ha (2, 2) = cmplx_t (2, 0);\n#endif\n  print_m (ha, \"ha\"); \n  cout << endl; \n\n  ublas::matrix_column<cm_t> cx0 (cx, 0);\n  atlas::set (cmplx_t (1, -1), cx0);\n  print_m (cx, \"cx\"); \n  cout << endl; \n#ifndef F_ROW_MAJOR\n  ublas::matrix_column<cm_t> cb0 (cb, 0); \n#else\n  ublas::matrix_row<cm_t> cb0 (cb, 0); \n#endif\n  atlas::hemv (ha, cx0, cb0); \n  print_m (cb, \"cb\"); \n  cout << endl; \n  \n  ierr = atlas::potrf (ha); \n  if (ierr == 0) {\n    atlas::potrs (ha, cb);\n    print_m (cb, \"cx\"); \n  }\n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl; \n  cout << endl; \n\n  cout << \"\\n===========================\\n\" << endl; \n  cout << \"complex hermitian\\n\" << endl; \n\n#ifndef F_UPPER\n  ha (0, 0) = cmplx_t (25, 0);\n  ha (1, 0) = cmplx_t (-5, 5);\n  ha (1, 1) = cmplx_t (51, 0);\n  ha (2, 0) = cmplx_t (10, -5);\n  ha (2, 1) = cmplx_t (4, 6);\n  ha (2, 2) = cmplx_t (71, 0);\n#else\n  ha (0, 0) = cmplx_t (25, 0);\n  ha (0, 1) = cmplx_t (-5, -5);\n  ha (0, 2) = cmplx_t (10, 5);\n  ha (1, 1) = cmplx_t (51, 0);\n  ha (1, 2) = cmplx_t (4, -6);\n  ha (2, 2) = cmplx_t (71, 0);\n#endif\n  print_m (ha, \"ha\"); \n  cout << endl; \n\n#ifndef F_ROW_MAJOR\n  cm_t cb32 (3, 2); \n  cb32 (0, 0) = cmplx_t (60, -55);\n  cb32 (1, 0) = cmplx_t (34, 58);\n  cb32 (2, 0) = cmplx_t (13, -152);\n  cb32 (0, 1) = cmplx_t (70, 10);\n  cb32 (1, 1) = cmplx_t (-51, 110);\n  cb32 (2, 1) = cmplx_t (75, 63);\n#else\n  cm_t cb32 (2, 3); \n  cb32 (0, 0) = cmplx_t (60, -55);\n  cb32 (0, 1) = cmplx_t (34, 58);\n  cb32 (0, 2) = cmplx_t (13, -152);\n  cb32 (1, 0) = cmplx_t (70, 10);\n  cb32 (1, 1) = cmplx_t (-51, 110);\n  cb32 (1, 2) = cmplx_t (75, 63);\n#endif \n  print_m (cb32, \"cb\"); \n  cout << endl; \n  \n  ierr = atlas::potrf (ha); \n  if (ierr == 0) {\n    atlas::potrs (ha, cb32);\n    print_m (cb32, \"cx\"); \n  }\n  else \n    cout << \"matrix is not positive definite: ierr = \" \n         << ierr << endl; \n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "c6f5239a17c4c86b283af34af1fde90f079a2701", "size": 5087, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_potrf_potrs.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_potrf_potrs.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/atlas/ublas_potrf_potrs.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 24.4567307692, "max_line_length": 61, "alphanum_fraction": 0.5822685276, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6027299480632607}}
{"text": "#include <cmath>\n#include <iostream>\n#include <boost/mpl/bool.hpp>\n#include <boost/lambda/lambda.hpp>\n\ndouble sc(double x) \n{\n    return sin(x) + cos(x);\n}\n\nstruct sc_f\n{\n    double operator() (double x) const \n    { \n\treturn sin(x) + cos(x);\n    }\n};\n\n\nclass psc_f\n{\n  public:\n    psc_f(double alpha) : alpha(alpha) {}\n\n    double operator() (double x) const \n    { \n\treturn sin(alpha * x) + cos(x);\n    }\n  private:\n    double alpha;\n};\n\n#if 0 \n// with function pointers\ndouble fin_diff(double f(double), double x, double h) \n{\n    return ( f(x+h) - f(x) ) / h;\n}\n#endif\n\n\ntemplate <typename F, typename T>\ninline T fin_diff(F f, const T& x, const T& h) \n{\n    return ( f(x+h) - f(x) ) / h;\n}\n\n\n\n\n\ntemplate <typename F, typename T>\nclass derivative\n{\n  public:\n    derivative(const F& f, const T& h) : f(f), h(h) {}\n\n    T operator()(const T& x) const\n    {\n\treturn ( f(x+h) - f(x) ) / h;\n    }   \n  private:\n    const F& f;\n    T        h;\n};\n\n\ntemplate <typename F, typename T>\nclass second_derivative\n{\n  public:\n    second_derivative(const F& f, const T& h) : h(h), fp(f, h) {}\n\n    T operator()(const T& x) const\n    {\n\treturn ( fp(x+h) - fp(x) ) / h;\n    }    \n  private:\n    T        h;\n    derivative<F, T> fp;\n};\n\n#if 0\ntemplate <typename F, typename T, unsigned N>\nclass nth_derivative\n{\n    using prev_derivative= nth_derivative<F, T, N-1>;\n  public:\n    nth_derivative(const F& f, const T& h) : h(h), fp(f, h) {}\n\n    T operator()(const T& x) const\n    {\n\treturn ( fp(x+h) - fp(x) ) / h;\n    }    \n  private:\n    T        h;\n    prev_derivative fp;\n};\n\n#else\n\ntemplate <typename F, typename T, unsigned N>\nclass nth_derivative\n{\n    using prev_derivative= nth_derivative<F, T, N-1>;\n  public:\n    nth_derivative(const F& f, const T& h) : h(h), fp(f, h) {}\n\n    T operator()(const T& x) const\n    {\n\treturn N & 1 ? ( fp(x+h) - fp(x) ) / h \n\t             : ( fp(x) - fp(x-h) ) / h;\n    }\t\n  private:\n    T        h;\n    prev_derivative fp;\n};\n\n\n#if 0 // for meta-programming, maybe\ntemplate <typename F, typename T, unsigned N>\nclass nth_derivative\n{\n    using prev_derivative= nth_derivative<F, T, N-1>;\n  public:\n    nth_derivative(const F& f, const T& h) : h(h), fp(f, h) {}\n\n    T operator()(const T& x) const\n    {\n\treturn diff(x, boost::mpl::bool_<N & 1>());\n    }\n\t\n  private:\n\n    T diff(const T& x, boost::mpl::true_) const\n    {\n\treturn ( fp(x+h) - fp(x) ) / h;\n    }    \n\n    T diff(const T& x, boost::mpl::false_) const\n    {\n\treturn ( fp(x) - fp(x-h) ) / h;\n    }    \n\n    T        h;\n    prev_derivative fp;\n};\n#endif\n\n#endif \n\n#if 0\ntemplate <typename F, typename T>\nclass nth_derivative<F, T, 1>\n{\n  public:\n    nth_derivative(const F& f, const T& h) : f(f), h(h) {}\n\n    T operator()(const T& x) const\n    {\n\treturn ( f(x+h) - f(x) ) / h;\n    }   \n  private:\n    const F& f;\n    T        h;\n};\n#endif \n\ntemplate <typename F, typename T>\nclass nth_derivative<F, T, 1>\n  : public derivative<F, T>\n{\n    using derivative<F, T>::derivative;\n\n  // public:\n  //   nth_derivative(const F& f, const T& h) : derivative<F, T>(f, h) {}\n};\n\n\n#if 0\ntemplate <typename F, typename T, unsigned N> // Not clever\nnth_derivative<F, T, N> \nmake_nth_derivative(const F& f, const T& h)\n{\n    return nth_derivative<F, T, N>(f, h);\n}\n#endif\n\n\n\n\ntemplate <unsigned N, typename F, typename T>\nnth_derivative<F, T, N> \nmake_nth_derivative(const F& f, const T& h)\n{\n    return nth_derivative<F, T, N>(f, h);\n}\n\nstruct et {};\n\ntemplate <typename F>\nvoid error(const F& f)\n{\n    et e= f;\n}\n\nint main() \n{\n    using namespace std;\n\n    psc_f psc_o(1.0);\n    cout << fin_diff(psc_o, 1., 0.001) << endl;\n    cout << fin_diff(psc_f(2.0), 1., 0.001) << endl;\n    cout << fin_diff(psc_f(2.0), 0., 0.001) << endl;\n    cout << fin_diff(sc, 0., 0.001) << endl;\n\n    using d_psc_f= derivative<psc_f, double>;\n    using dd_psc_f= derivative<d_psc_f, double>;\n\n    d_psc_f                                     d_psc_o(psc_o, 0.001);\n    dd_psc_f                                     dd_psc_o(d_psc_o, 0.001);\n\n    cout << \"der. of sin(0) + cos(0) is \" << d_psc_o(0.0) << '\\n';\n    cout << \"2nd der. of sin(0) + cos(0) is \" << dd_psc_o(0.0) << '\\n';\n\n    second_derivative<psc_f, double> dd_psc_2_o(psc_f(1.0), 0.001);\n    cout << \"2nd der. of sin(0) + cos(0) is \" << dd_psc_2_o(0.0) << '\\n';\n\n    nth_derivative<psc_f, double, 2> dd_psc_3_o(psc_f(1.0), 0.001);\n    cout << \"2nd der. of sin(0) + cos(0) is \" << dd_psc_3_o(0.0) << '\\n';\n\n    nth_derivative<psc_f, double, 6> d6_psc_o(psc_f(1.0), 0.00001);\n    cout << \"6th der. of sin(0) + cos(0) is \" << d6_psc_o(0.0) << '\\n';\n\n    nth_derivative<psc_f, double, 12> d12_psc_o(psc_f(1.0), 0.00001);\n    cout << \"12th der. of sin(0) + cos(0) is \" << d12_psc_o(0.0) << '\\n';\n\n    nth_derivative<psc_f, double, 22> d22_psc_o(psc_f(1.0), 0.00001);\n    cout << \"22nd der. of sin(0) + cos(0) is \" << d22_psc_o(0.0) << '\\n';\n\n    // auto d7_psc_o= make_nth_derivative<psc_f, double, 7>(psc_o, 0.00001);\n\n    // nth_derivative<psc_f, double, 7> d7_psc_o(psc_o, 0.00001);\n    // auto d7_psc_o= nth_derivative<psc_f, double, 7>(psc_o, 0.00001);\n    // nth_derivative<decltype(psc_o), decltype(0.00001), 7> d7_psc_o(psc_o, 0.00001);\n\n    make_nth_derivative<7, psc_f, double>(psc_o, 0.00001);\n    auto d7_psc_o= make_nth_derivative<7>(psc_o, 0.00001);\n\n    cout << \"7th der. of psc_o at x=3 is \" \n\t << make_nth_derivative<7>(psc_o, 0.00001)(3.0) << '\\n';\n\n    using boost::lambda::_1;\n    \n    (3.5 * _1 + 4.0) * _1 * _1;\n\n    cout << \"2nd der. of 3.5*x^3+4*x^2 at x=2 is \"\n\t      << make_nth_derivative<2>((3.5 * _1 + 4.0) * _1 * _1, 0.0001)(2) << '\\n';\n\n    cout << \"2nd der. of 3.5*x^3+4*x^2 at x=2 is \"\n\t << make_nth_derivative<2>([](double x){ return (3.5 * x + 4.0) * x * x; }, 0.0001)(2) << '\\n';\n\n    auto d7_cub_l= make_nth_derivative<7>([](double x){ return (3.5 * x + 4.0) * x * x; }, 0.0001);\n    auto d7_psc_l= make_nth_derivative<7>([](double x){ return sin(2.5*x) + cos(x); }, 0.0001);\n\n    // error((3.5 * _1 + _1) * _1 * _1);\n    return 0;\n}\n\n", "meta": {"hexsha": "b7013097efa6a828b217a508f44b7bb40f636b25", "size": 5983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DMCpp/GottschlingRepo/c++11/derivative.cpp", "max_stars_repo_name": "tzaffi/cpp", "max_stars_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-12-27T14:35:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T14:28:17.000Z", "max_issues_repo_path": "DMCpp/GottschlingRepo/c++11/derivative.cpp", "max_issues_repo_name": "tzaffi/cpp", "max_issues_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2017-12-07T14:54:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-28T02:14:07.000Z", "max_forks_repo_path": "DMCpp/GottschlingRepo/c++11/derivative.cpp", "max_forks_repo_name": "tzaffi/cpp", "max_forks_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-01-04T13:40:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-02T12:49:21.000Z", "avg_line_length": 22.1592592593, "max_line_length": 99, "alphanum_fraction": 0.5632625773, "num_tokens": 2139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6026816986830145}}
{"text": "//\n// Copyright (c) 2018 INRIA\n//\n\n#include \"utils/macros.hpp\"\n#include \"pinocchio/math/sincos.hpp\"\n#include <cstdlib>\n\n#include <boost/test/unit_test.hpp>\n#include <boost/utility/binary.hpp>\n\ntemplate<typename Scalar>\nvoid testSINCOS(int n)\n{\n  for(int k = 0; k < n; ++k)\n  {\n    Scalar sin_value, cos_value;\n    Scalar alpha = (Scalar)std::rand()/(Scalar)RAND_MAX;\n    pinocchio::SINCOS(alpha,&sin_value,&cos_value);\n    \n    Scalar sin_value_ref = std::sin(alpha),\n           cos_value_ref = std::cos(alpha);\n    \n    BOOST_CHECK(sin_value == sin_value_ref);\n    BOOST_CHECK(cos_value == cos_value_ref);\n  }\n}\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\nBOOST_AUTO_TEST_CASE(test_sincos)\n{\n#ifndef NDEBUG\n  const int n = 1e3;\n#else\n  const int n = 1e6;\n#endif\n  testSINCOS<float>(n);\n  testSINCOS<double>(n);\n  testSINCOS<long double>(n);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "e9b94ee98bd25e93b2bd7d19a9e9f48c51986e0b", "size": 872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittest/sincos.cpp", "max_stars_repo_name": "matthieuvigne/pinocchio", "max_stars_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T15:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T15:42:45.000Z", "max_issues_repo_path": "unittest/sincos.cpp", "max_issues_repo_name": "matthieuvigne/pinocchio", "max_issues_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittest/sincos.cpp", "max_forks_repo_name": "matthieuvigne/pinocchio", "max_forks_repo_head_hexsha": "01f211eceda3ac2e5edc8cf101690afb6f3184d3", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-21T09:14:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T09:14:26.000Z", "avg_line_length": 19.8181818182, "max_line_length": 56, "alphanum_fraction": 0.6915137615, "num_tokens": 249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038221, "lm_q2_score": 0.7371581684030624, "lm_q1q2_score": 0.6026816968507949}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// chisq_summand.hpp                                                         //\n//                                                                           //\n//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_COMMON_CHISQ_SUMMAND_FORMULA_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_COMMON_CHISQ_SUMMAND_FORMULA_HPP_ER_2010\n#include <boost/numeric/conversion/converter.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace contingency_table{\nnamespace pearson_chisq_statistic{\n\n    template<typename T1,typename T2,typename T3>\n    T1 chisq_summand_formula(\n        const T2& expected_n, \n        const T3& observed_n\n    )\n    {\n        typedef boost::numeric::converter<T1,T2> conv2_;\n        typedef boost::numeric::converter<T1,T3> conv3_;\n        T1 summand = conv2_::convert( expected_n ) \n            - conv3_::convert( observed_n );\n        summand *= summand;\n        return summand / conv2_::convert( expected_n );\n    }\n    \n}// pearson_chisq_statistic\n}// contingency_table\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "a41040d7d09870adb82982087db72ae9ea686967", "size": 1527, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/common/chisq_summand_formula.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/common/chisq_summand_formula.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/common/chisq_summand_formula.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1538461538, "max_line_length": 119, "alphanum_fraction": 0.5776031434, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225574, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6026788518924855}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl 2002 \n *\n * Permission to copy, modify, use and distribute this software \n * for any non-commercial or commercial purpose is granted provided \n * that this license appear on all copies of the software source code.\n *\n * Author assumes no responsibility whatsoever for its use and makes \n * no guarantees about its quality, correctness or reliability.\n *\n * Author acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_CLAPACK_OVERLOADS_HPP\n#define BOOST_NUMERIC_BINDINGS_CLAPACK_OVERLOADS_HPP\n\n#include <boost/numeric/bindings/atlas/clapack_inc.hpp>\n#include <boost/numeric/bindings/traits/type.hpp>\n\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace atlas { namespace detail {\n\n    //\n    // general system of linear equations A * X = B\n    //\n\n    // 'driver' function -- factor and solve\n    inline \n    int gesv (CBLAS_ORDER const Order, \n              int const N, int const NRHS,\n              float* A, int const lda, int* ipiv, \n              float* B, int const ldb) \n    {\n      return clapack_sgesv (Order, N, NRHS, A, lda, ipiv, B, ldb);\n    }\n    \n    inline \n    int gesv (CBLAS_ORDER const Order, \n              int const N, int const NRHS,\n              double* A, int const lda, int* ipiv, \n              double* B, int const ldb) \n    {\n      return clapack_dgesv (Order, N, NRHS, A, lda, ipiv, B, ldb);\n    }\n    \n    inline \n    int gesv (CBLAS_ORDER const Order, \n              int const N, int const NRHS,\n              traits::complex_f* A, int const lda, int* ipiv, \n              traits::complex_f* B, int const ldb) \n    {\n      return clapack_cgesv (Order, N, NRHS, \n                            static_cast<void*> (A), lda, ipiv, \n                            static_cast<void*> (B), ldb);\n    }\n    \n    inline \n    int gesv (CBLAS_ORDER const Order, \n              int const N, int const NRHS,\n              traits::complex_d* A, int const lda, int* ipiv, \n              traits::complex_d* B, int const ldb) \n    {\n      return clapack_zgesv (Order, N, NRHS, \n                            static_cast<void*> (A), lda, ipiv, \n                            static_cast<void*> (B), ldb);\n    }\n    \n    // LU factorization \n    inline \n    int getrf (CBLAS_ORDER const Order, \n               int const M, int const N,\n               float* A, int const lda, int* ipiv)\n    {\n      return clapack_sgetrf (Order, M, N, A, lda, ipiv);\n    }\n    \n    inline \n    int getrf (CBLAS_ORDER const Order, \n               int const M, int const N,\n               double* A, int const lda, int* ipiv)\n    {\n      return clapack_dgetrf (Order, M, N, A, lda, ipiv);\n    }\n    \n    inline \n    int getrf (CBLAS_ORDER const Order, \n               int const M, int const N,\n               traits::complex_f* A, int const lda, int* ipiv)\n    {\n      return clapack_cgetrf (Order, M, N, static_cast<void*> (A), lda, ipiv); \n    }\n    \n    inline \n    int getrf (CBLAS_ORDER const Order, \n               int const M, int const N,\n               traits::complex_d* A, int const lda, int* ipiv)\n    {\n      return clapack_zgetrf (Order, M, N, static_cast<void*> (A), lda, ipiv); \n    }\n\n    // solve (using factorization computed by getrf()) \n    inline \n    int getrs (CBLAS_ORDER const Order, CBLAS_TRANSPOSE const Trans, \n               int const N, int const NRHS,\n               float const* A, int const lda, int const* ipiv, \n               float* B, int const ldb) \n    {\n      return clapack_sgetrs (Order, Trans, N, NRHS, A, lda, ipiv, B, ldb);\n    }\n    \n    inline \n    int getrs (CBLAS_ORDER const Order, CBLAS_TRANSPOSE const Trans, \n               int const N, int const NRHS,\n               double const* A, int const lda, int const* ipiv, \n               double* B, int const ldb) \n    {\n      return clapack_dgetrs (Order, Trans, N, NRHS, A, lda, ipiv, B, ldb);\n    }\n    \n    inline \n    int getrs (CBLAS_ORDER const Order, CBLAS_TRANSPOSE const Trans, \n               int const N, int const NRHS,\n               traits::complex_f const* A, int const lda, \n               int const* ipiv, \n               traits::complex_f* B, int const ldb) \n    {\n      return clapack_cgetrs (Order, Trans, N, NRHS, \n                             static_cast<void const*> (A), lda, ipiv, \n                             static_cast<void*> (B), ldb);\n    }\n    \n    inline \n    int getrs (CBLAS_ORDER const Order, CBLAS_TRANSPOSE const Trans, \n               int const N, int const NRHS,\n               traits::complex_d const* A, int const lda, \n               int const* ipiv, \n               traits::complex_d* B, int const ldb) \n    {\n      return clapack_zgetrs (Order, Trans, N, NRHS, \n                             static_cast<void const*> (A), lda, ipiv, \n                             static_cast<void*> (B), ldb);\n    }\n\n    // invert (using factorization computed by getrf()) \n    inline \n    int getri (CBLAS_ORDER const Order, \n               int const N, float* A, int const lda,\n               int const* ipiv) \n    {\n      return clapack_sgetri (Order, N, A, lda, ipiv);\n    }\n\n    inline \n    int getri (CBLAS_ORDER const Order, \n               int const N, double* A, int const lda,\n               int const* ipiv) \n    {\n      return clapack_dgetri (Order, N, A, lda, ipiv);\n    }\n\n    inline \n    int getri (CBLAS_ORDER const Order, \n               int const N, traits::complex_f* A, int const lda,\n               int const* ipiv) \n    {\n      return clapack_cgetri (Order, N, static_cast<void*> (A), lda, ipiv);\n    }\n\n    inline \n    int getri (CBLAS_ORDER const Order, \n               int const N, traits::complex_d* A, int const lda,\n               int const* ipiv) \n    {\n      return clapack_zgetri (Order, N, static_cast<void*> (A), lda, ipiv);\n    }\n\n\n    //\n    // system of linear equations A * X = B\n    // with A symmetric positive definite matrix\n    //\n\n    // 'driver' function -- factor and solve\n    inline \n    int posv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, int const NRHS,\n              float* A, int const lda, float* B, int const ldb) \n    {\n      return clapack_sposv (Order, Uplo, N, NRHS, A, lda, B, ldb);\n    }\n    \n    inline \n    int posv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, int const NRHS,\n              double* A, int const lda, double* B, int const ldb) \n    {\n      return clapack_dposv (Order, Uplo, N, NRHS, A, lda, B, ldb);\n    }\n    \n    inline \n    int posv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, int const NRHS,\n              traits::complex_f* A, int const lda, \n              traits::complex_f* B, int const ldb) \n    {\n      return clapack_cposv (Order, Uplo, N, NRHS, \n                            static_cast<void*> (A), lda, \n                            static_cast<void*> (B), ldb);\n    }\n    \n    inline \n    int posv (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n              int const N, int const NRHS,\n              traits::complex_d* A, int const lda, \n              traits::complex_d* B, int const ldb) \n    {\n      return clapack_zposv (Order, Uplo, N, NRHS, \n                            static_cast<void*> (A), lda, \n                            static_cast<void*> (B), ldb);\n    }\n\n    // Cholesky factorization\n    inline \n    int potrf (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, float* A, int const lda) \n    {\n      return clapack_spotrf (Order, Uplo, N, A, lda);\n    }\n    \n    inline \n    int potrf (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, double* A, int const lda) \n    {\n      return clapack_dpotrf (Order, Uplo, N, A, lda);\n    }\n    \n    inline \n    int potrf (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_f* A, int const lda) \n    {\n      return clapack_cpotrf (Order, Uplo, N, static_cast<void*> (A), lda);\n    }\n    \n    inline \n    int potrf (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_d* A, int const lda) \n    {\n      return clapack_zpotrf (Order, Uplo, N, static_cast<void*> (A), lda);\n    }\n    \n    // solve (using factorization computed by potrf()) \n    inline \n    int potrs (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, int const NRHS,\n               float const* A, int const lda, float* B, int const ldb) \n    {\n      return clapack_spotrs (Order, Uplo, N, NRHS, A, lda, B, ldb);\n    }\n\n    inline \n    int potrs (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, int const NRHS,\n               double const* A, int const lda, double* B, int const ldb) \n    {\n      return clapack_dpotrs (Order, Uplo, N, NRHS, A, lda, B, ldb);\n    }\n   \n    inline \n    int potrs (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, int const NRHS,\n               traits::complex_f const* A, int const lda, \n               traits::complex_f* B, int const ldb) \n    {\n      return clapack_cpotrs (Order, Uplo, N, NRHS, \n                             static_cast<void const*> (A), lda, \n                             static_cast<void*> (B), ldb);\n    }\n   \n    inline \n    int potrs (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, int const NRHS,\n               traits::complex_d const* A, int const lda, \n               traits::complex_d* B, int const ldb) \n    {\n      return clapack_zpotrs (Order, Uplo, N, NRHS, \n                             static_cast<void const*> (A), lda, \n                             static_cast<void*> (B), ldb);\n    }\n\n#ifdef BOOST_NUMERIC_BINDINGS_ATLAS_POTRF_BUG \n    // .. ATLAS bug with row major hermitian matrices \n    // .... symmetric matrices are OK, but to simplify generic potrs() ... \n    inline \n    int potrs_bug (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n                   int const N, int const NRHS,\n                   float const* A, int const lda, float* B, int const ldb) \n    {\n      return clapack_spotrs (Order, Uplo, N, NRHS, A, lda, B, ldb);\n    }\n\n    inline \n    int potrs_bug (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n                   int const N, int const NRHS,\n                   double const* A, int const lda, double* B, int const ldb) \n    {\n      return clapack_dpotrs (Order, Uplo, N, NRHS, A, lda, B, ldb);\n    }\n   \n    inline \n    int potrs_bug (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n                   int const N, int const NRHS,\n                   traits::complex_f const* A, int const lda, \n                   traits::complex_f* B, int const ldb) \n    {\n      int sz = N * lda; \n      traits::complex_f* A1 = new traits::complex_f[sz]; \n      for (int i = 0; i < sz; ++i) \n        A1[i] = std::conj (A[i]); \n      int r = clapack_cpotrs (Order, Uplo, N, NRHS, \n                              static_cast<void const*> (A1), lda, \n                              static_cast<void*> (B), ldb);\n      delete[] A1; \n      return r; \n    }\n   \n    inline \n    int potrs_bug (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n                   int const N, int const NRHS,\n                   traits::complex_d const* A, int const lda, \n                   traits::complex_d* B, int const ldb) \n    {\n      int sz = N * lda; \n      traits::complex_d* A1 = new traits::complex_d[sz]; \n      for (int i = 0; i < sz; ++i) \n        A1[i] = std::conj (A[i]); \n      int r = clapack_zpotrs (Order, Uplo, N, NRHS, \n                              static_cast<void const*> (A1), lda, \n                              static_cast<void*> (B), ldb);\n      delete[] A1; \n      return r; \n    }\n#endif // BOOST_NUMERIC_BINDINGS_ATLAS_POTRF_BUG \n\n    // invert (using factorization computed by potrf()) \n    inline \n    int potri (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, float* A, int const lda) \n    {\n      return clapack_spotri (Order, Uplo, N, A, lda);\n    }\n\n    inline \n    int potri (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, double* A, int const lda) \n    {\n      return clapack_dpotri (Order, Uplo, N, A, lda);\n    }\n\n    inline \n    int potri (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_f* A, int const lda) \n    {\n      return clapack_cpotri (Order, Uplo, N, static_cast<void*> (A), lda);\n    }\n\n    inline \n    int potri (CBLAS_ORDER const Order, CBLAS_UPLO const Uplo,\n               int const N, traits::complex_d* A, int const lda) \n    {\n      return clapack_zpotri (Order, Uplo, N, static_cast<void*> (A), lda);\n    }\n\n\n  }} // namepaces detail & atlas\n\n}}} \n\n\n#endif // BOOST_NUMERIC_BINDINGS_CLAPACK_OVERLOADS_HPP\n", "meta": {"hexsha": "dca41012f690dfd11d4fa2b57f8a508b6ccc48ab", "size": 12732, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/clapack_overloads.hpp", "max_stars_repo_name": "jiaqiwang969/Kratos-test", "max_stars_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/clapack_overloads.hpp", "max_issues_repo_name": "jiaqiwang969/Kratos-test", "max_issues_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/atlas/clapack_overloads.hpp", "max_forks_repo_name": "jiaqiwang969/Kratos-test", "max_forks_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0701298701, "max_line_length": 78, "alphanum_fraction": 0.5531731071, "num_tokens": 3515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6026788466080231}}
{"text": "#include \"EvaluatorUtils.h\"\n\n#include <NTL/ZZ.h>\n#include <cmath>\n\nZZ EvaluatorUtils::evaluateVal(const double& x, const long& bits) {\n\treturn evaluateVal(to_RR(x), bits);\n}\n\nZZ EvaluatorUtils::evaluateVal(const RR& x, const long& bits) {\n\tRR xp = MakeRR(x.x, x.e + bits);\n\treturn RoundToZZ(xp);\n}\n\nCZZ EvaluatorUtils::evaluateVal(const double& xr, const double& xi, const long& bits) {\n\treturn evaluateVal(to_RR(xr), to_RR(xi), bits);\n}\n\nCZZ EvaluatorUtils::evaluateVal(const RR& xr, const RR& xi, const long& bits) {\n\tRR xrp = MakeRR(xr.x, xr.e + bits);\n\tRR xip = MakeRR(xi.x, xi.e + bits);\n\treturn CZZ(RoundToZZ(xrp), RoundToZZ(xip));\n}\n\nvoid EvaluatorUtils::evaluateRRVal(RR& xr, RR& xi, CZZ& x, const long& bits) {\n\txr = to_RR(x.r);\n\txr.e -= bits;\n\txi = to_RR(x.i);\n\txr.e -= bits;\n}\n\nCZZ EvaluatorUtils::evaluateRandomVal(const long& bits) {\n\treturn CZZ(RandomBits_ZZ(bits), RandomBits_ZZ(bits));\n}\n\nCZZ EvaluatorUtils::evaluateRandomCircleVal(const long& bits) {\n\tRR angle = random_RR();\n\tRR mr = cos(angle * 2 * Pi);\n\tRR mi = sin(angle * 2 * Pi);\n\treturn evaluateVal(mr, mi, bits);\n}\n\nCZZ* EvaluatorUtils::evaluateRandomVals(const long& size, const long& bits) {\n\tCZZ* res = new CZZ[size];\n\tfor (long i = 0; i < size; i++) {\n\t\tres[i] = CZZ(RandomBits_ZZ(bits), RandomBits_ZZ(bits));\n\t}\n\treturn res;\n}\n\nCZZ* EvaluatorUtils::evaluateRandomZZVals(const long& size, const long& bits) {\n\tCZZ* res = new CZZ[size];\n\tfor (long i = 0; i < size; i++) {\n\t\tres[i].r = RandomBits_ZZ(bits);\n\t}\n\treturn res;\n}\n\nCZZ EvaluatorUtils::evaluatePow(const double& xr, const double& xi, const long& degree, const long& bits) {\n\tlong logDegree = log2(degree);\n\tlong po2Degree = 1 << logDegree;\n\tCZZ res = evaluatePow2(xr, xi, logDegree, bits);\n\tlong remDegree = degree - po2Degree;\n\tif(remDegree > 0) {\n\t\tCZZ tmp = evaluatePow(xr, xi, remDegree, bits);\n\t\tres *= tmp;\n\t\tres >>= bits;\n\t}\n\treturn res;\n}\n\nCZZ EvaluatorUtils::evaluatePow(const RR& xr, const RR& xi, const long& degree, const long& bits) {\n\tlong logDegree = log2(degree);\n\tlong po2Degree = 1 << logDegree;\n\tCZZ res = evaluatePow2(xr, xi, logDegree, bits);\n\tlong remDegree = degree - po2Degree;\n\tif(remDegree > 0) {\n\t\tCZZ tmp = evaluatePow(xr, xi, remDegree, bits);\n\t\tres *= tmp;\n\t\tres >>= bits;\n\t}\n\treturn res;\n}\n\nCZZ EvaluatorUtils::evaluatePow2(const double& xr, const double& xi, const long& logDegree, const long& bits) {\n\treturn evaluatePow2(to_RR(xr), to_RR(xi), logDegree, bits);\n}\n\nCZZ EvaluatorUtils::evaluatePow2(const RR& xr, const RR& xi, const long& logDegree, const long& bits) {\n\tCZZ res = evaluateVal(xr, xi, bits);\n\tfor (int i = 0; i < logDegree; ++i) {\n\t\tres *= res;\n\t\tres >>= bits;\n\t}\n\treturn res;\n}\n\nCZZ* EvaluatorUtils::evaluatePowvec(const double& xr, const double& xi, const long& degree, const long& bits) {\n\treturn  evaluatePowvec(to_RR(xr), to_RR(xi), degree, bits);\n}\n\nCZZ* EvaluatorUtils::evaluatePowvec(const RR& xr, const RR& xi, const long& degree, const long& bits) {\n\tCZZ* res = new CZZ[degree];\n\tCZZ m = evaluateVal(xr, xi, bits);\n\tres[0] = m;\n\tfor (long i = 0; i < degree - 1; ++i) {\n\t\tres[i + 1] = (res[i] * m) >> bits;\n\t}\n\treturn res;\n}\n\nCZZ* EvaluatorUtils::evaluatePow2vec(const double& xr, const double& xi, const long& logDegree, const long& bits) {\n\treturn evaluatePow2vec(to_RR(xr), to_RR(xi), logDegree, bits);\n}\n\nCZZ* EvaluatorUtils::evaluatePow2vec(const RR& xr, const RR& xi, const long& logDegree, const long& bits) {\n\tCZZ* res = new CZZ[logDegree + 1];\n\tCZZ m = evaluateVal(xr, xi, bits);\n\tres[0] = m;\n\tfor (long i = 0; i < logDegree; ++i) {\n\t\tres[i + 1] = (res[i] * res[i]) >> bits;\n\t}\n\treturn res;\n}\n\nCZZ EvaluatorUtils::evaluateInverse(const double& xr, const double& xi, const long& bits) {\n\treturn evaluateInverse(to_RR(xr), to_RR(xi), bits);\n}\n\nCZZ EvaluatorUtils::evaluateInverse(const RR& xr, const RR& xi, const long& bits) {\n\tRR xinvr = xr / (xr * xr + xi * xi);\n\tRR xinvi = -xi / (xr * xr + xi * xi);\n\n\treturn evaluateVal(xinvr, xinvi, bits);\n}\n\nCZZ EvaluatorUtils::evaluateLogarithm(const double& xr, const double& xi, const long& bits) {\n\tdouble xlogr = log(xr * xr + xi * xi) / 2;\n\tdouble xlogi = atan(xi / xr);\n\n\treturn evaluateVal(xlogr, xlogi, bits);\n}\n\nCZZ EvaluatorUtils::evaluateExponent(const double& xr, const double& xi, const long& bits) {\n\tdouble xrexp = exp(xr);\n\tdouble xexpr = xrexp * cos(xi);\n\tdouble xexpi = xrexp * sin(xi);\n\n\treturn evaluateVal(xexpr, xexpi, bits);\n}\n\nCZZ EvaluatorUtils::evaluateExponent(const RR& xr, const RR& xi, const long& bits) {\n\tRR xrexp = exp(xr);\n\tRR xexpr = xrexp * cos(xi);\n\tRR xexpi = xrexp * sin(xi);\n\n\treturn evaluateVal(xexpr, xexpi, bits);\n}\n\nCZZ EvaluatorUtils::evaluateSigmoid(const double& xr, const double& xi, const long& bits) {\n\tdouble xrexp = exp(xr);\n\tdouble xexpr = xrexp * cos(xi);\n\tdouble xexpi = xrexp * sin(xi);\n\n\tdouble xsigmoidr = (xexpr * (xexpr + 1) + (xexpi * xexpi)) / ((xexpr + 1) * (xexpr + 1) + (xexpi * xexpi));\n\tdouble xsigmoidi = xexpi / ((xexpr + 1) * (xexpr + 1) + (xexpi * xexpi));\n\n\treturn evaluateVal(xsigmoidr, xsigmoidi, bits);\n}\n\nCZZ EvaluatorUtils::evaluateSigmoid(const RR& xr, const RR& xi, const long& bits) {\n\tRR xrexp = exp(xr);\n\tRR xexpr = xrexp * cos(xi);\n\tRR xexpi = xrexp * sin(xi);\n\n\tRR xsigmoidr = (xexpr * (xexpr + 1) + (xexpi * xexpi)) / ((xexpr + 1) * (xexpr + 1) + (xexpi * xexpi));\n\tRR xsigmoidi = xexpi / ((xexpr + 1) * (xexpr + 1) + (xexpi * xexpi));\n\n\treturn evaluateVal(xsigmoidr, xsigmoidi, bits);\n}\n\nvoid EvaluatorUtils::leftShiftAndEqual(CZZ*& vals, const long& size, const long& bits) {\n\tfor (long i = 0; i < size; ++i) {\n\t\tvals[i] <<= bits;\n\t}\n}\n\nvoid EvaluatorUtils::leftRotateAndEqual(CZZ*& vals, const long& size, const long& rotSize) {\n\tlong remrotSize = rotSize % size;\n\tif(remrotSize != 0) {\n\t\tlong divisor = GCD(remrotSize, size);\n\t\tlong steps = size / divisor;\n\t\tfor (long i = 0; i < divisor; ++i) {\n\t\t\tCZZ tmp = vals[i];\n\t\t\tlong idx = i;\n\t\t\tfor (long j = 0; j < steps - 1; ++j) {\n\t\t\t\tvals[idx] = vals[(idx + remrotSize) % size];\n\t\t\t\tidx = (idx + remrotSize) % size;\n\t\t\t}\n\t\t\tvals[idx] = tmp;\n\t\t}\n\t}\n}\n\nvoid EvaluatorUtils::rightRotateAndEqual(CZZ*& vals, const long& size, const long& rotSize) {\n\tlong remrotSize = rotSize % size;\n\tlong leftremrotSize = (size - remrotSize) % size;\n\tleftRotateAndEqual(vals, size, leftremrotSize);\n}\n", "meta": {"hexsha": "ef9d9ca6d7eba22dd4afaf5fafe44e63dad817a7", "size": 6262, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/EvaluatorUtils.cpp", "max_stars_repo_name": "K-miran/HELR", "max_stars_repo_head_hexsha": "c94951f2691d55defc82f95d3144c831eb6c8796", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:56:15.000Z", "max_issues_repo_path": "src/EvaluatorUtils.cpp", "max_issues_repo_name": "yuejiayang/HELR", "max_issues_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-25T02:54:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-09T10:48:39.000Z", "max_forks_repo_path": "src/EvaluatorUtils.cpp", "max_forks_repo_name": "yuejiayang/HELR", "max_forks_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-01-20T13:31:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T02:20:39.000Z", "avg_line_length": 29.819047619, "max_line_length": 115, "alphanum_fraction": 0.6604918556, "num_tokens": 2100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6026788361123976}}
{"text": "#include <gtest/gtest.h>\n#include <Eigen/Dense>\n#include <iostream>\n#include <iomanip>\n#include <string>\n\n#include \"post_processing/macroscopic_quantities.hpp\"\n#include \"post_processing/mass.hpp\"\n#include \"post_processing/momentum.hpp\"\n#include \"post_processing/energy.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"aux/eigen2hdf.hpp\"\n\nusing namespace boltzmann;\nusing namespace std;\n\n\n\nTEST(spectral, momentsfile)\n{\n\n  std::string filename = \"mqeval.h5\";\n  MQEval mq_coeffs_;\n  int K = 40;\n  SpectralBasisFactoryKS::basis_type basis;\n  SpectralBasisFactoryKS::create(basis, K);\n  mq_coeffs_.init(basis);\n\n  Eigen::VectorXd vec(basis.size());\n\n  hid_t fh5 = H5Fopen(filename.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n  eigen2hdf::load(fh5, \"coeffs\", vec);\n  H5Fclose(fh5);\n\n  auto evaluator = mq_coeffs_.evaluator();\n  evaluator(vec);\n\n  cout << setw(10) << \"rho \"\n       << setw(20) << setprecision(8) << scientific << evaluator.m << \"\\n\";\n\n  cout << setw(10) << \"e \"\n       << setw(20) << setprecision(8) << scientific << evaluator.e << \"\\n\";\n\n  cout << setw(10) << \"v \"\n       << setw(20) << setprecision(8) << scientific << evaluator.v << \"\\n\";\n\n  cout << setw(10) << \"v \"\n       << setw(20) << setprecision(8) << scientific << evaluator.v << \"\\n\";\n}\n\nTEST(spectral, moments)\n{\n\n  std::string filename = \"mqeval.h5\";\n  MQEval mq_coeffs;\n  int K = 40;\n  SpectralBasisFactoryKS::basis_type basis;\n  SpectralBasisFactoryKS::create(basis, K);\n  mq_coeffs.init(basis);\n\n  auto cmass = mq_coeffs.cmass();\n  auto cenergy = mq_coeffs.cenergy();\n\n  Energy energy(basis);\n  Mass mass(basis);\n\n  Eigen::ArrayXd cenergy_ref(basis.size());\n  cenergy_ref.setZero();\n  Eigen::ArrayXd cmass_ref(basis.size());\n  cmass_ref.setZero();\n\n  for (auto entry : energy.entries()) {\n    cenergy_ref(entry.first) = entry.second;\n  }\n\n  for (auto entry : mass.entries()) {\n    cmass_ref(entry.first) = entry.second;\n  }\n\n  double diff_mass_max = (cmass_ref.segment(0, cmass.size()) - cmass).cwiseAbs().maxCoeff();\n  double diff_energy_max = (cenergy_ref.segment(0, cenergy.size()) - cenergy).cwiseAbs().maxCoeff();\n\n  EXPECT_NEAR(diff_mass_max, 0, 1e-11) << \"max diff coeffs mass\";\n  EXPECT_NEAR(diff_energy_max, 0, 1e-11) << \"max diff coeffs energy\";\n}\n", "meta": {"hexsha": "cb2da97e90e863687805620ed668065a88407dd9", "size": 2252, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/gtest/gtest_mqeval.cpp", "max_stars_repo_name": "simonpp/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/gtest/gtest_mqeval.cpp", "max_issues_repo_name": "simonpp/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/gtest/gtest_mqeval.cpp", "max_forks_repo_name": "simonpp/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1860465116, "max_line_length": 100, "alphanum_fraction": 0.6780639432, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6026788360757478}}
{"text": "/*\n * TravellingSalesman.cpp\n *\n *  Created on: 2013/05/13\n *      Author: kryozahiro\n */\n\n#include \"TravellingSalesman.h\"\n\n#include <random>\n#include <boost/lexical_cast.hpp>\nusing namespace std;\n\nTravellingSalesman::TravellingSalesman(int size, int seed) :\n\t\tProblem(ProgramType(DataType(0, 0, 1, 0), DataType(0, size - 1, 1, size))) {\n\t//\u90fd\u5e02\u306e\u30e9\u30f3\u30c0\u30e0\u751f\u6210\n\tmt19937_64 engine(seed);\n\tuniform_real_distribution<> dist(-1.0, 1.0);\n\tfor (int i = 0; i < size; ++i) {\n\t\tcities.push_back(pair<double, double>(dist(engine), dist(engine)));\n\t}\n}\n\ndouble TravellingSalesman::evaluate(Program& program) {\n\tvector<double> path = program(vector<double>());\n\tassert(getProgramType().getOutputType().accepts(path));\n\tvector<pair<double, double>> cityList = cities;\n\n\tpair<double, double> prev = cityList[path[0]];\n\tcityList.erase(cityList.begin() + path[0]);\n\n\t//\u7d4c\u8def\u306e\u9577\u3055\u3092\u8a08\u7b97\u3059\u308b\n\tdouble length = 0;\n\tfor (vector<int>::size_type i = 1; i < path.size(); ++i) {\n\t\tint cityIndex = ((int)path[i]) % cityList.size();\n\t\tpair<double, double> next = cityList[cityIndex];\n\t\tcityList.erase(cityList.begin() + cityIndex);\n\n\t\tlength += (next.first - prev.first) * (next.first - prev.first) + (next.second - prev.second) * (next.second - prev.second);\n\t\tprev = next;\n\t}\n\treturn length;\n}\n\nstring TravellingSalesman::toString() const {\n\tstring ret;\n\tfor (vector<pair<int, int>>::size_type i = 0; i < cities.size(); ++i) {\n\t\tret += boost::lexical_cast<string>(cities[i].first) + \" \" + boost::lexical_cast<string>(cities[i].second) + \"\\n\";\n\t}\n\treturn ret;\n}\n\n/*string TravellingSalesman::showProgram(Program& program) const {\n\tstring ret;\n\n\tvector<double> path = program(vector<double>());\n\tassert(getProgramType().acceptsOutput(path));\n\tvector<pair<double, double>> cityList = cities;\n\n\tpair<double, double> prev = cityList[path[0]];\n\tcityList.erase(cityList.begin() + path[0]);\n\tret += boost::lexical_cast<string>(prev.first) + \" \" + boost::lexical_cast<string>(prev.second) + \"\\n\";\n\n\t//\u7d4c\u8def\u306e\u9577\u3055\u3092\u8a08\u7b97\u3059\u308b\n\tfor (vector<int>::size_type i = 1; i < path.size(); ++i) {\n\t\tint cityIndex = ((int)path[i]) % cityList.size();\n\t\tpair<double, double> next = cityList[cityIndex];\n\t\tcityList.erase(cityList.begin() + cityIndex);\n\n\t\tret += boost::lexical_cast<string>(next.first) + \" \" + boost::lexical_cast<string>(next.second) + \"\\n\";\n\t}\n\tret += boost::lexical_cast<string>(prev.first) + \" \" + boost::lexical_cast<string>(prev.second) + \"\\n\";\n\treturn ret;\n}*/\n", "meta": {"hexsha": "7c3b69e18914ed08d335920d1ea2428958ae01f3", "size": 2401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gamesolver/problem/TravellingSalesman.cpp", "max_stars_repo_name": "kryozahiro/gamesolver", "max_stars_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gamesolver/problem/TravellingSalesman.cpp", "max_issues_repo_name": "kryozahiro/gamesolver", "max_issues_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gamesolver/problem/TravellingSalesman.cpp", "max_forks_repo_name": "kryozahiro/gamesolver", "max_forks_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-06T16:06:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-06T16:06:10.000Z", "avg_line_length": 32.0133333333, "max_line_length": 126, "alphanum_fraction": 0.6747188671, "num_tokens": 702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127380808499, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6026788256167711}}
{"text": "/**\n * \\file SecondOrderFilter.cpp\n * @see http://abvolt.com/research/publications2.htm\n * @see http://www.music.mcgill.ca/~ich/classes/FiltersChap2.pdf for the allpass filter\n */\n\n#include \"SecondOrderFilter.h\"\n#include \"IIRFilter.h\"\n\n#include <cassert>\n#include <cmath>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  template <typename DataType>\n  SecondOrderBaseCoefficients<DataType>::SecondOrderBaseCoefficients(int nb_channels)\n    :Parent(nb_channels, nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void SecondOrderBaseCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    coefficients_in.assign(in_order+1, 0);\n    coefficients_out.assign(out_order, 0);\n  }\n\n  template <typename DataType_>\n  void SecondOrderBaseCoefficients<DataType_>::set_cut_frequency(DataType_ cut_frequency)\n  {\n    this->cut_frequency = cut_frequency;\n    setup();\n  }\n  \n  template <typename DataType_>\n  DataType_ SecondOrderBaseCoefficients<DataType_>::get_cut_frequency() const\n  {\n    return cut_frequency;\n  }\n\n  template<typename DataType>\n  SecondOrderBandPassCoefficients<DataType>::SecondOrderBandPassCoefficients(int nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void SecondOrderBandPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n    DataType d = (1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c);\n    DataType Q_inv = 1 / Q;\n    \n    coefficients_in[2] = Q_inv * c / d;\n    coefficients_in[1] = 0;\n    coefficients_in[0] = -Q_inv * c / d;\n    coefficients_out[1] = - 2 * (c * c - 1) / d;\n    coefficients_out[0] = - (1 - std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d;\n  }\n  \n  template <typename DataType_>\n  void SecondOrderBandPassCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ SecondOrderBandPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  SecondOrderLowPassCoefficients<DataType>::SecondOrderLowPassCoefficients(int nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void SecondOrderLowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n    DataType d = (1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c);\n    \n    coefficients_in[2] = c * c / d;\n    coefficients_in[1] = 2 * c * c / d;\n    coefficients_in[0] = c * c / d;\n    coefficients_out[1] = - 2 * (c * c - 1) / d;\n    coefficients_out[0] = - (1 - std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d;\n  }\n\n  template<typename DataType>\n  SecondOrderHighPassCoefficients<DataType>::SecondOrderHighPassCoefficients(int nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void SecondOrderHighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n    DataType d = (1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c);\n    \n    coefficients_in[2] = 1;\n    coefficients_in[1] = -2;\n    coefficients_in[0] = 1;\n    coefficients_out[1] = - 2 * (c * c - 1) / d;\n    coefficients_out[0] = - (1 - std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d;\n  }\n\n  template<typename DataType>\n  SecondOrderBandPassPeakCoefficients<DataType>::SecondOrderBandPassPeakCoefficients(int nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void SecondOrderBandPassPeakCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n    DataType Q_inv = 1 / Q;\n    if(gain <= 1)\n    {\n      DataType V0 = 1 / gain;\n      DataType d = 1 + V0 * Q_inv * c + c * c;\n      \n      coefficients_in[2] = (1 + Q_inv * c + c * c) / d;\n      coefficients_in[1] = 2 * (c * c - 1) / d;\n      coefficients_in[0] = (1 - Q_inv * c + c * c) / d;\n      coefficients_out[1] = -2 * (c * c - 1) / d;\n      coefficients_out[0] = -(1 - V0 * Q_inv * c + c * c) / d;\n    }\n    else\n    {\n      DataType V0 = gain;\n      DataType d = 1 + Q_inv * c + c * c;\n      \n      coefficients_in[2] = (1 + V0 * Q_inv * c + c * c) / d;\n      coefficients_in[1] = 2 * (c * c - 1) / d;\n      coefficients_in[0] = (1 - V0 * Q_inv * c + c * c) / d;\n      coefficients_out[1] = -2 * (c * c - 1) / d;\n      coefficients_out[0] = -(1 - Q_inv * c + c * c) / d;\n    }\n  }\n\n  template <typename DataType_>\n  void SecondOrderBandPassPeakCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ SecondOrderBandPassPeakCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template <typename DataType_>\n  void SecondOrderBandPassPeakCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ SecondOrderBandPassPeakCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  SecondOrderAllPassCoefficients<DataType>::SecondOrderAllPassCoefficients(int nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void SecondOrderAllPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType c = std::tan(boost::math::constants::pi<DataType>() * Q);\n    DataType d = -std::cos(2 * boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n\n    coefficients_in[2] = -c;\n    coefficients_in[1] = d * (1 - c);\n    coefficients_in[0] = 1;\n    coefficients_out[1] = -d * (1 - c);\n    coefficients_out[0] = c;\n  }\n\n  template <typename DataType_>\n  void SecondOrderAllPassCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ SecondOrderAllPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  SecondOrderLowShelvingCoefficients<DataType>::SecondOrderLowShelvingCoefficients(int nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void SecondOrderLowShelvingCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n    if(gain <= 1)\n    {\n      DataType V0 = 1 / gain;\n      DataType d = (1 + std::sqrt(static_cast<DataType>(2.) * V0) * c + V0 * c * c);\n      \n      coefficients_in[2] = (1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d;\n      coefficients_in[1] = 2 * (c * c - 1) / d;\n      coefficients_in[0] = (1 - std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d;\n      coefficients_out[1] = - 2 * (V0 * c * c - 1) / d;\n      coefficients_out[0] = - (1 - std::sqrt(static_cast<DataType>(2.) * V0) * c + V0 * c * c) / d;\n    }\n    else\n    {\n      DataType d = (1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c);\n      \n      coefficients_in[2] = (1 + std::sqrt(static_cast<DataType>(2.) * gain) * c + gain * c * c) / d;\n      coefficients_in[1] = 2 * (gain * c * c - 1) / d;\n      coefficients_in[0] = (1 - std::sqrt(static_cast<DataType>(2.) * gain) * c + gain * c * c) / d;\n      coefficients_out[1] = - 2 * (c * c - 1) / d;\n      coefficients_out[0] = - (1 - std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d;\n    }\n  }\n\n  template <typename DataType_>\n  void SecondOrderLowShelvingCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ SecondOrderLowShelvingCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  SecondOrderHighShelvingCoefficients<DataType>::SecondOrderHighShelvingCoefficients(int nb_channels)\n    :Parent(nb_channels)\n  {\n  }\n\n  template <typename DataType>\n  void SecondOrderHighShelvingCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n    if(gain <= 1)\n    {\n      DataType V0 = 1 / gain;\n      DataType d = (V0 + std::sqrt(static_cast<DataType>(2.) * V0) * c + c * c);\n      \n      coefficients_in[2] = -(1 + std::sqrt(static_cast<DataType>(2.0)) * c + c * c) / d;\n      coefficients_in[1] = -2 * (c * c - 1) / d;\n      coefficients_in[0] = -(1 - std::sqrt(static_cast<DataType>(2.0)) * c + c * c) / d;\n      coefficients_out[1] = - 2 * (c * c - V0) / d;\n      coefficients_out[0] = - (V0 - std::sqrt(static_cast<DataType>(2.0) * V0) * c + c * c) / d;\n    }\n    else\n    {\n      DataType d = (1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c);\n      \n      coefficients_in[2] = -(gain + std::sqrt(static_cast<DataType>(2.0) * gain) * c + c * c) / d;\n      coefficients_in[1] = -2 * (c * c - gain) / d;\n      coefficients_in[0] = -(gain - std::sqrt(static_cast<DataType>(2.0) * gain) * c + c * c) / d;\n      coefficients_out[1] = - 2 * (c * c - 1) / d;\n      coefficients_out[0] = - (1 - std::sqrt(static_cast<DataType>(2.0)) * c + c * c) / d;\n    }\n  }\n  \n  template<typename DataType_>\n  void SecondOrderHighShelvingCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    this->gain = gain;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ SecondOrderHighShelvingCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n\n  template class SecondOrderBaseCoefficients<float>;\n  template class SecondOrderBaseCoefficients<double>;\n  \n  template class SecondOrderBandPassCoefficients<float>;\n  template class SecondOrderBandPassCoefficients<double>;\n  template class SecondOrderLowPassCoefficients<float>;\n  template class SecondOrderLowPassCoefficients<double>;\n  template class SecondOrderHighPassCoefficients<float>;\n  template class SecondOrderHighPassCoefficients<double>;\n  template class SecondOrderBandPassPeakCoefficients<float>;\n  template class SecondOrderBandPassPeakCoefficients<double>;\n  template class SecondOrderAllPassCoefficients<float>;\n  template class SecondOrderAllPassCoefficients<double>;\n  template class SecondOrderLowShelvingCoefficients<float>;\n  template class SecondOrderLowShelvingCoefficients<double>;\n  template class SecondOrderHighShelvingCoefficients<float>;\n  template class SecondOrderHighShelvingCoefficients<double>;\n  \n  template class IIRFilter<SecondOrderBandPassCoefficients<float> >;\n  template class IIRFilter<SecondOrderBandPassCoefficients<double> >;\n  template class IIRFilter<SecondOrderLowPassCoefficients<float> >;\n  template class IIRFilter<SecondOrderLowPassCoefficients<double> >;\n  template class IIRFilter<SecondOrderHighPassCoefficients<float> >;\n  template class IIRFilter<SecondOrderHighPassCoefficients<double> >;\n  template class IIRFilter<SecondOrderBandPassPeakCoefficients<float> >;\n  template class IIRFilter<SecondOrderBandPassPeakCoefficients<double> >;\n  template class IIRFilter<SecondOrderAllPassCoefficients<float> >;\n  template class IIRFilter<SecondOrderAllPassCoefficients<double> >;\n  template class IIRFilter<SecondOrderLowShelvingCoefficients<float> >;\n  template class IIRFilter<SecondOrderLowShelvingCoefficients<double> >;\n  template class IIRFilter<SecondOrderHighShelvingCoefficients<float> >;\n  template class IIRFilter<SecondOrderHighShelvingCoefficients<double> >;\n}\n", "meta": {"hexsha": "d13f05887eff1515d401e507618b8d5f50e277a1", "size": 11415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/SecondOrderFilter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "ATK/EQ/SecondOrderFilter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ATK/EQ/SecondOrderFilter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 32.8017241379, "max_line_length": 109, "alphanum_fraction": 0.6689443714, "num_tokens": 3266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.6026543527809838}}
{"text": "#include \"basis/Functions.h\"\n#include \"form/RefElement.h\"\n#include \"quadrules/AutoRule.h\"\n#include \"quadrules/SimplexQuadratureRule.h\"\n#include \"tensor/EigenMap.h\"\n#include \"tensor/Managed.h\"\n#include \"util/Combinatorics.h\"\n\n#include <Eigen/Core>\n\n#include <array>\n#include <cmath>\n#include <cstdlib>\n#include <iostream>\n#include <memory>\n#include <vector>\n\nusing Eigen::DiagonalMatrix;\nusing Eigen::MatrixXd;\nusing tndm::AllIntegerSums;\nusing tndm::binom;\nusing tndm::gradTetraDubinerP;\nusing tndm::ModalRefElement;\nusing tndm::TetraDubinerP;\n\nint main(int argc, char** argv) {\n\n    if (argc < 2) {\n        std::cerr << \"Usage: `tensors <degree>`\" << std::endl;\n        return -1;\n    }\n\n    unsigned N = atoi(argv[1]);\n    unsigned numBF = binom(N + 3, 3);\n\n    std::cout << \"Number of basis functions: \" << numBF << std::endl;\n\n    auto rule = tndm::simplexQuadratureRule<3u>(2u * N + 1u);\n\n    auto truncate = [](double x) { return (std::fabs(x) < 1e-15) ? 0.0 : x; };\n\n    DiagonalMatrix<double, Eigen::Dynamic> W(rule.size());\n\n    auto phi = ModalRefElement<3u>(N).evaluateBasisAt(rule.points());\n    auto phiMap = EigenMap(phi);\n\n    for (std::size_t i = 0; i < rule.size(); ++i) {\n        W.diagonal()(i) = rule.weights()[i];\n    }\n\n    auto m = phiMap * W * phiMap.transpose();\n    std::cout << \"Mass matrix:\" << std::endl;\n    std::cout << m.unaryExpr(truncate) << std::endl;\n\n    std::array<MatrixXd, 3> dphi;\n    for (auto& matrix : dphi) {\n        matrix.resize(rule.size(), numBF);\n    }\n    std::size_t bf = 0;\n    for (auto j : AllIntegerSums<3>(N)) {\n        for (std::size_t i = 0; i < rule.size(); ++i) {\n            auto grad = gradTetraDubinerP(j, rule.points()[i]);\n            for (std::size_t d = 0; d < grad.size(); ++d) {\n                dphi[d](i, bf) = grad[d];\n            }\n        }\n        ++bf;\n    }\n\n    auto kXi = dphi[0].transpose() * W * phiMap.transpose();\n    std::cout << \"dphidxi * phi:\" << std::endl;\n    std::cout << kXi.unaryExpr(truncate) << std::endl;\n\n    for (std::size_t x = 0; x < 3; ++x) {\n        for (std::size_t y = 0; y < 3; ++y) {\n            auto kxy = dphi[x].transpose() * W * dphi[y];\n            std::cout << \"dphi[\" << x << \"] * dphi[\" << y << \"]:\" << std::endl;\n            std::cout << kxy.unaryExpr(truncate) << std::endl;\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "33d1efbf2479d675eeab049235e48fba4d0cbbf3", "size": 2323, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/tensors.cpp", "max_stars_repo_name": "NicoSchlw/tandem", "max_stars_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T17:11:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:51:01.000Z", "max_issues_repo_path": "app/tensors.cpp", "max_issues_repo_name": "NicoSchlw/tandem", "max_issues_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-05-18T14:51:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T12:56:31.000Z", "max_forks_repo_path": "app/tensors.cpp", "max_forks_repo_name": "NicoSchlw/tandem", "max_forks_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-23T08:04:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T12:23:59.000Z", "avg_line_length": 27.6547619048, "max_line_length": 79, "alphanum_fraction": 0.5639259578, "num_tokens": 743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.6026543372538226}}
{"text": "/*    Copyright (c) 2010-2018, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n */\n\n#include <cmath>\n#include <iostream>\n\n#include <Eigen/LU>\n\n#include \"Tudat/Basics/utilities.h\"\n#include \"Tudat/Mathematics/BasicMathematics/leastSquaresEstimation.h\"\n\nnamespace tudat\n{\n\nnamespace linear_algebra\n{\n\n//! Function to get condition number of matrix (using SVD decomposition)\ndouble getConditionNumberOfInformationMatrix( const Eigen::MatrixXd informationMatrix )\n{\n    return getConditionNumberOfDecomposedMatrix(\n                ( informationMatrix.jacobiSvd( Eigen::ComputeThinU | Eigen::ComputeFullV ) ) );\n}\n\n//! Function to get condition number of matrix from SVD decomposition\ndouble getConditionNumberOfDecomposedMatrix( const Eigen::JacobiSVD< Eigen::MatrixXd >& singularValueDecomposition )\n{\n    Eigen::VectorXd singularValues = singularValueDecomposition.singularValues( );\n    return singularValues( 0 ) / singularValues( singularValues.rows( ) - 1 );\n}\n\n//! Solve system of equations with SVD decomposition, checking condition number in the process\nEigen::VectorXd solveSystemOfEquationsWithSvd( const Eigen::MatrixXd matrixToInvert,\n                                               const Eigen::VectorXd rightHandSideVector,\n                                               const bool checkConditionNumber,\n                                               const double maximumAllowedConditionNumber )\n{\n    Eigen::JacobiSVD< Eigen::MatrixXd > svdDecomposition = matrixToInvert.jacobiSvd(\n                Eigen::ComputeThinU | Eigen::ComputeThinV );\n    if( checkConditionNumber )\n    {\n        double conditionNumber = getConditionNumberOfDecomposedMatrix( svdDecomposition );\n\n        if( conditionNumber > maximumAllowedConditionNumber )\n        {\n            std::cerr << \"Warning when performing least squares, condition number is \" << conditionNumber << std::endl;\n        }\n    }\n    return svdDecomposition.solve( rightHandSideVector );\n}\n\n//! Function to multiply information matrix by diagonal weights matrix\nEigen::MatrixXd multiplyInformationMatrixByDiagonalWeightMatrix(\n        const Eigen::MatrixXd& informationMatrix,\n        const Eigen::VectorXd& diagonalOfWeightMatrix )\n{\n    Eigen::MatrixXd weightedInformationMatrix = Eigen::MatrixXd::Zero( informationMatrix.rows( ), informationMatrix.cols( ) );\n\n    for( int i = 0; i < informationMatrix.cols( ); i++ )\n    {\n        weightedInformationMatrix.block( 0, i, informationMatrix.rows( ), 1 ) =\n                informationMatrix.block( 0, i, informationMatrix.rows( ), 1 ).cwiseProduct( diagonalOfWeightMatrix );\n    }\n\n    return weightedInformationMatrix;\n}\n\n//! Function to compute inverse of covariance matrix at current iteration, including influence of a priori information\nEigen::MatrixXd calculateInverseOfUpdatedCovarianceMatrix(\n        const Eigen::MatrixXd& informationMatrix,\n        const Eigen::VectorXd& diagonalOfWeightMatrix,\n        const Eigen::MatrixXd& inverseOfAPrioriCovarianceMatrix )\n{\n    return inverseOfAPrioriCovarianceMatrix + informationMatrix.transpose( ) * multiplyInformationMatrixByDiagonalWeightMatrix(\n                informationMatrix, diagonalOfWeightMatrix );\n}\n\n//! Function to compute inverse of covariance matrix at current iteration\nEigen::MatrixXd calculateInverseOfUpdatedCovarianceMatrix(\n        const Eigen::MatrixXd& informationMatrix,\n        const Eigen::VectorXd& diagonalOfWeightMatrix )\n{\n    return calculateInverseOfUpdatedCovarianceMatrix(\n                informationMatrix, diagonalOfWeightMatrix,\n                Eigen::MatrixXd::Zero( informationMatrix.cols( ), informationMatrix.cols( ) ) );\n}\n\n//! Function to perform an iteration least squares estimation from information matrix, weights and residuals and a priori\n//! information\nstd::pair< Eigen::VectorXd, Eigen::MatrixXd > performLeastSquaresAdjustmentFromInformationMatrix(\n        const Eigen::MatrixXd& informationMatrix,\n        const Eigen::VectorXd& observationResiduals,\n        const Eigen::VectorXd& diagonalOfWeightMatrix,\n        const Eigen::MatrixXd& inverseOfAPrioriCovarianceMatrix,\n        const bool checkConditionNumber,\n        const double maximumAllowedConditionNumber,\n        const Eigen::MatrixXd& constraintMultiplier,\n        const Eigen::VectorXd& constraintRightHandside )\n{\n//    std::cout<<\"Residuals \"<<observationResiduals.transpose( )<<std::endl;\n//    std::cout<<\"Weight diag. \"<<diagonalOfWeightMatrix.transpose( )<<std::endl;\n//    std::cout<<\"Partials \"<<informationMatrix.transpose( )<<std::endl;\n\n    Eigen::VectorXd rightHandSide = informationMatrix.transpose( ) *\n            ( diagonalOfWeightMatrix.cwiseProduct( observationResiduals ) );\n    Eigen::MatrixXd inverseOfCovarianceMatrix = calculateInverseOfUpdatedCovarianceMatrix(\n                informationMatrix, diagonalOfWeightMatrix, inverseOfAPrioriCovarianceMatrix );\n\n    // Add constraints to inverse covariance matrix if required\n    if( constraintMultiplier.rows( ) != 0 )\n    {\n        if( constraintMultiplier.rows( ) != constraintRightHandside.rows( ) )\n        {\n            throw std::runtime_error( \"Error when performing constrained least-squares, constraints are incompatible\" );\n        }\n\n        if( constraintMultiplier.cols( ) != informationMatrix.cols( ) )\n        {\n            throw std::runtime_error( \"Error when performing constrained least-squares, constraints are incompatible with partials\" );\n        }\n\n        int numberOfConstraints = constraintMultiplier.rows( );\n        int numberOfParameters = constraintMultiplier.cols( );\n\n        inverseOfCovarianceMatrix.conservativeResize(\n                    numberOfParameters + numberOfConstraints, numberOfParameters + numberOfConstraints );\n        inverseOfCovarianceMatrix.block( numberOfParameters, 0, numberOfConstraints, numberOfParameters ) =\n               constraintMultiplier;\n        inverseOfCovarianceMatrix.block( 0, numberOfParameters, numberOfParameters, numberOfConstraints ) =\n               constraintMultiplier.transpose( );\n        inverseOfCovarianceMatrix.block(\n                    numberOfParameters, numberOfParameters, numberOfConstraints, numberOfConstraints ).setZero( );\n\n        rightHandSide.conservativeResize( numberOfParameters + numberOfConstraints );\n        rightHandSide.segment( numberOfParameters, numberOfConstraints ) = constraintRightHandside;\n    }\n\n//    std::cout<<\"RHS \"<<rightHandSide.transpose( )<<std::endl;\n//    std::cout<<\"Inv cov \"<<inverseOfCovarianceMatrix<<std::endl;\n\n    return std::make_pair( solveSystemOfEquationsWithSvd(\n                               inverseOfCovarianceMatrix, rightHandSide, checkConditionNumber, maximumAllowedConditionNumber ),\n                           inverseOfCovarianceMatrix );\n\n}\n\n//! Function to perform an iteration least squares estimation from information matrix, weights and residuals\nstd::pair< Eigen::VectorXd, Eigen::MatrixXd > performLeastSquaresAdjustmentFromInformationMatrix(\n        const Eigen::MatrixXd& informationMatrix,\n        const Eigen::VectorXd& observationResiduals,\n        const Eigen::VectorXd& diagonalOfWeightMatrix,\n        const bool checkConditionNumber,\n        const double maximumAllowedConditionNumber )\n{\n    return performLeastSquaresAdjustmentFromInformationMatrix(\n                informationMatrix, observationResiduals, diagonalOfWeightMatrix,\n                Eigen::MatrixXd::Zero( informationMatrix.cols( ), informationMatrix.cols( ) ),\n                checkConditionNumber, maximumAllowedConditionNumber );\n}\n\n//! Function to perform an iteration of least squares estimation from information matrix and residuals\nstd::pair< Eigen::VectorXd, Eigen::MatrixXd > performLeastSquaresAdjustmentFromInformationMatrix(\n        const Eigen::MatrixXd& informationMatrix,\n        const Eigen::VectorXd& observationResiduals,\n        const bool checkConditionNumber,\n        const double maximumAllowedConditionNumber )\n{\n    return performLeastSquaresAdjustmentFromInformationMatrix(\n                informationMatrix, observationResiduals, Eigen::VectorXd::Constant( observationResiduals.size( ), 1, 1.0 ),\n                checkConditionNumber, maximumAllowedConditionNumber );\n}\n\n//! Function to fit a univariate polynomial through a set of data\nEigen::VectorXd getLeastSquaresPolynomialFit(\n        const Eigen::VectorXd& independentValues,\n        const Eigen::VectorXd& dependentValues,\n        const std::vector< double >& polynomialPowers )\n{\n    if( independentValues.rows( ) != dependentValues.rows( ) )\n    {\n        throw std::runtime_error( \"Error when doing least squares polynomial fit, size of dependent and independent \"\n                                  \"variable vectors is not equal.\" );\n    }\n\n    Eigen::MatrixXd informationMatrix = Eigen::MatrixXd::Zero( dependentValues.rows( ), polynomialPowers.size( ) );\n\n    // Compute information matrix\n    for( int i = 0; i < independentValues.rows( ); i++ )\n    {\n        for( unsigned int j = 0; j < polynomialPowers.size( ); j++ )\n        {\n            informationMatrix( i, j ) = std::pow( independentValues( i ), polynomialPowers.at( j ) );\n        }\n    }\n\n    return performLeastSquaresAdjustmentFromInformationMatrix( informationMatrix, dependentValues ).first;\n}\n\n//! Function to fit a univariate polynomial through a set of data\nstd::vector< double > getLeastSquaresPolynomialFit(\n        const std::map< double, double >& independentDependentValueMap,\n        const std::vector< double >& polynomialPowers )\n{\n    return utilities::convertEigenVectorToStlVector(\n                getLeastSquaresPolynomialFit(\n                    utilities::convertStlVectorToEigenVector(\n                        utilities::createVectorFromMapKeys( independentDependentValueMap ) ),\n                    utilities::convertStlVectorToEigenVector(\n                        utilities::createVectorFromMapValues( independentDependentValueMap ) ), polynomialPowers ) );\n\n}\n\n//! Function to perform a non-linear least squares estimation with the Levenberg-Marquardt method.\nEigen::VectorXd nonLinearLeastSquaresFit(\n        const std::function< std::pair< Eigen::VectorXd, Eigen::MatrixXd >( const Eigen::VectorXd& ) >& observationAndJacobianFunctions,\n        const Eigen::VectorXd& initialEstimate, const Eigen::VectorXd& actualObservations, const double initialScaling,\n        const double convergenceTolerance, const unsigned int maximumNumberOfIterations )\n{\n    // Set current estimate to initial value\n    Eigen::VectorXd currentEstimate = initialEstimate;\n\n    // Initialize variables\n    std::pair< Eigen::VectorXd, Eigen::MatrixXd > pairOfEstimatedObservationsAndDesignMatrix;\n    Eigen::MatrixXd designMatrix;\n    Eigen::VectorXd offsetInObservations;\n    Eigen::VectorXd updateInEstimate;\n\n    // Initial parameters for Levenberg\u2013Marquardt method\n    double levenbergMarquardtDampingParameter = 0.0;\n    double scalingParameterUpdate = 2.0;\n    double levenbergMarquardtGainRatio = 0.0;\n\n    // Start iterative loop\n    unsigned int iteration = 0;\n    do\n    {\n        // Compute current system and jacobian functions\n        pairOfEstimatedObservationsAndDesignMatrix = observationAndJacobianFunctions( currentEstimate );\n        designMatrix = pairOfEstimatedObservationsAndDesignMatrix.second;\n\n        // Offset in observation\n        offsetInObservations = actualObservations - pairOfEstimatedObservationsAndDesignMatrix.first;\n\n        // Compute damping parameter for first iteration\n        if ( iteration == 0 )\n        {\n            levenbergMarquardtDampingParameter = initialScaling * ( designMatrix.transpose( ) * designMatrix ).diagonal( ).maxCoeff( );\n        }\n\n        // Compute update in estimate\n        Eigen::VectorXd diagonalOfWeightMatrix = Eigen::VectorXd::Ones( offsetInObservations.rows( ) );\n        Eigen::MatrixXd inverseOfAPrioriCovarianceMatrix = levenbergMarquardtDampingParameter *\n//                Eigen::MatrixXd( ( designMatrix.transpose( ) * designMatrix ).diagonal( ).asDiagonal( ) ); // Marquardt\u2019s update\n                Eigen::MatrixXd::Identity( currentEstimate.rows( ), currentEstimate.rows( ) );\n        updateInEstimate = linear_algebra::performLeastSquaresAdjustmentFromInformationMatrix(\n                    designMatrix, offsetInObservations, diagonalOfWeightMatrix, inverseOfAPrioriCovarianceMatrix, false ).first;\n\n        // Check that update is real\n        if ( ( !updateInEstimate.allFinite( ) ) || ( updateInEstimate.hasNaN( ) ) )\n        {\n            throw std::runtime_error( \"Error in non-linear least squares estimation. Iterative process diverges.\" );\n        }\n\n        // Compute gain ratio\n        levenbergMarquardtGainRatio =\n                ( offsetInObservations.squaredNorm( ) -\n                  ( actualObservations - observationAndJacobianFunctions( currentEstimate + updateInEstimate ).first ).squaredNorm( ) ) /\n                ( updateInEstimate.transpose( ) * ( levenbergMarquardtDampingParameter * updateInEstimate +\n                                                    designMatrix.transpose( ) * offsetInObservations ) );\n\n        // Update damping parameter\n        if ( levenbergMarquardtGainRatio > 0 )\n        {\n            // Reduce damping parameter, since good approximation\n            levenbergMarquardtDampingParameter *= std::max( 1.0 / 3.0, 1.0 - std::pow( 2.0 * levenbergMarquardtGainRatio - 1.0, 3 ) );\n            scalingParameterUpdate = 2; // reset\n\n            // Correct estimate\n            currentEstimate += updateInEstimate;\n        }\n        else\n        {\n            // Increase damping parameter, since bad approximation and reject step\n            levenbergMarquardtDampingParameter *= scalingParameterUpdate;\n            scalingParameterUpdate *= 2.0;\n        }\n\n        // Increase iteration counter\n        iteration++;\n    }\n    while ( ( updateInEstimate.norm( ) > convergenceTolerance ) && ( iteration <= maximumNumberOfIterations ) );\n\n    // Warn user of exceeded maximum number of iterations\n    if ( iteration > maximumNumberOfIterations )\n    {\n        std::cerr << \"Warning in non-linear least squares estimation. Maximum number of iterations exceeded.\" << std::endl;\n    }\n\n    // Give out new estimate in parameters\n    return currentEstimate;\n}\n\n} // namespace linear_algebra\n\n} // namespace tudat\n", "meta": {"hexsha": "cbc35f0e7d7b10b6d20de4aa4271be5dcab3563a", "size": 14625, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/leastSquaresEstimation.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/BasicMathematics/leastSquaresEstimation.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/BasicMathematics/leastSquaresEstimation.cpp", "max_forks_repo_name": "J-Westin/tudat", "max_forks_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.576433121, "max_line_length": 137, "alphanum_fraction": 0.7018803419, "num_tokens": 3058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.6026530294579509}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// rolling_variance.hpp\n// Copyright (C) 2005 Eric Niebler\n// Copyright (C) 2014 Pieter Bastiaan Ober (Integricom).\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ACCUMULATORS_STATISTICS_ROLLING_VARIANCE_HPP_EAN_15_11_2011\n#define BOOST_ACCUMULATORS_STATISTICS_ROLLING_VARIANCE_HPP_EAN_15_11_2011\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\n#include <boost/mpl/placeholders.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n#include <boost/accumulators/statistics/rolling_mean.hpp>\n#include <boost/accumulators/statistics/rolling_moment.hpp>\n\n#include <boost/type_traits/is_arithmetic.hpp>\n#include <boost/utility/enable_if.hpp>\n\nnamespace boost { namespace accumulators\n{\nnamespace impl\n{\n    //! Immediate (lazy) calculation of the rolling variance.\n    /*!\n    Calculation of sample variance \\f$\\sigma_n^2\\f$ is done as follows, see also\n    http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance.\n    For a rolling window of size \\f$N\\f$, when \\f$n <= N\\f$, the variance is computed according to the formula\n    \\f[\n    \\sigma_n^2 = \\frac{1}{n-1} \\sum_{i = 1}^n (x_i - \\mu_n)^2.\n    \\f]\n    When \\f$n > N\\f$, the sample variance over the window becomes:\n    \\f[\n    \\sigma_n^2 = \\frac{1}{N-1} \\sum_{i = n-N+1}^n (x_i - \\mu_n)^2.\n    \\f]\n    */\n    ///////////////////////////////////////////////////////////////////////////////\n    // lazy_rolling_variance_impl\n    //\n    template<typename Sample>\n    struct lazy_rolling_variance_impl\n        : accumulator_base\n    {\n        // for boost::result_of\n        typedef typename numeric::functional::fdiv<Sample, std::size_t,void,void>::result_type result_type;\n\n        lazy_rolling_variance_impl(dont_care) {}\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            result_type mean = rolling_mean(args);\n            size_t nr_samples = rolling_count(args);\n            if (nr_samples < 2) return result_type();\n            return nr_samples*(rolling_moment<2>(args) - mean*mean)/(nr_samples-1);\n        }\n    };\n\n    //! Iterative calculation of the rolling variance.\n    /*!\n    Iterative calculation of sample variance \\f$\\sigma_n^2\\f$ is done as follows, see also\n    http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance.\n    For a rolling window of size \\f$N\\f$, for the first \\f$N\\f$ samples, the variance is computed according to the formula\n    \\f[\n    \\sigma_n^2 = \\frac{1}{n-1} \\sum_{i = 1}^n (x_i - \\mu_n)^2 = \\frac{1}{n-1}M_{2,n},\n    \\f]\n    where the sum of squares \\f$M_{2,n}\\f$ can be recursively computed as:\n    \\f[\n    M_{2,n} = \\sum_{i = 1}^n (x_i - \\mu_n)^2 = M_{2,n-1} + (x_n - \\mu_n)(x_n - \\mu_{n-1}),\n    \\f]\n    and the estimate of the sample mean as:\n    \\f[\n    \\mu_n = \\frac{1}{n} \\sum_{i = 1}^n x_i = \\mu_{n-1} + \\frac{1}{n}(x_n - \\mu_{n-1}).\n    \\f]\n    For further samples, when the rolling window is fully filled with data, one has to take into account that the oldest\n    sample \\f$x_{n-N}\\f$ is dropped from the window. The sample variance over the window now becomes:\n    \\f[\n    \\sigma_n^2 = \\frac{1}{N-1} \\sum_{i = n-N+1}^n (x_i - \\mu_n)^2 = \\frac{1}{n-1}M_{2,n},\n    \\f]\n    where the sum of squares \\f$M_{2,n}\\f$ now equals:\n    \\f[\n    M_{2,n} = \\sum_{i = n-N+1}^n (x_i - \\mu_n)^2 = M_{2,n-1} + (x_n - \\mu_n)(x_n - \\mu_{n-1}) - (x_{n-N} - \\mu_n)(x_{n-N} - \\mu_{n-1}),\n    \\f]\n    and the estimated mean is:\n    \\f[\n    \\mu_n = \\frac{1}{N} \\sum_{i = n-N+1}^n x_i = \\mu_{n-1} + \\frac{1}{n}(x_n - x_{n-N}).\n    \\f]\n\n    Note that the sample variance is not defined for \\f$n <= 1\\f$.\n\n    */\n    ///////////////////////////////////////////////////////////////////////////////\n    // immediate_rolling_variance_impl\n    //\n    template<typename Sample>\n    struct immediate_rolling_variance_impl\n        : accumulator_base\n    {\n        // for boost::result_of\n        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;\n\n        template<typename Args>\n        immediate_rolling_variance_impl(Args const &args)\n            : previous_mean_(numeric::fdiv(args[sample | Sample()], numeric::one<std::size_t>::value))\n            , sum_of_squares_(numeric::fdiv(args[sample | Sample()], numeric::one<std::size_t>::value))\n        {\n        }\n\n        template<typename Args>\n        void operator()(Args const &args)\n        {\n            Sample added_sample = args[sample];\n\n            result_type mean = immediate_rolling_mean(args);\n            sum_of_squares_ += (added_sample-mean)*(added_sample-previous_mean_);\n\n            if(is_rolling_window_plus1_full(args))\n            {\n                Sample removed_sample = rolling_window_plus1(args).front();\n                sum_of_squares_ -= (removed_sample-mean)*(removed_sample-previous_mean_);\n                prevent_underflow(sum_of_squares_);\n            }\n            previous_mean_ = mean;\n        }\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            size_t nr_samples = rolling_count(args);\n            if (nr_samples < 2) return result_type();\n            return numeric::fdiv(sum_of_squares_,(nr_samples-1));\n        }\n\n    private:\n\n        result_type previous_mean_;\n        result_type sum_of_squares_;\n\n        template<typename T>\n        void prevent_underflow(T &non_negative_number,typename boost::enable_if<boost::is_arithmetic<T>,T>::type* = 0)\n        {\n            if (non_negative_number < T(0)) non_negative_number = T(0);\n        }\n        template<typename T>\n        void prevent_underflow(T &non_arithmetic_quantity,typename boost::disable_if<boost::is_arithmetic<T>,T>::type* = 0)\n        {\n        }\n    };\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag:: lazy_rolling_variance\n// tag:: immediate_rolling_variance\n// tag:: rolling_variance\n//\nnamespace tag\n{\n    struct lazy_rolling_variance\n        : depends_on< rolling_count, rolling_mean, rolling_moment<2> >\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::lazy_rolling_variance_impl< mpl::_1 > impl;\n\n        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED\n        /// tag::rolling_window::window_size named parameter\n        static boost::parameter::keyword<tag::rolling_window_size> const window_size;\n        #endif\n    };\n\n    struct immediate_rolling_variance\n        : depends_on< rolling_window_plus1, rolling_count, immediate_rolling_mean>\n    {\n        /// INTERNAL ONLY\n        ///\n        typedef accumulators::impl::immediate_rolling_variance_impl< mpl::_1> impl;\n\n        #ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED\n        /// tag::rolling_window::window_size named parameter\n        static boost::parameter::keyword<tag::rolling_window_size> const window_size;\n        #endif\n    };\n\n    // make immediate_rolling_variance the default implementation\n    struct rolling_variance : immediate_rolling_variance {};\n} // namespace tag\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::lazy_rolling_variance\n// extract::immediate_rolling_variance\n// extract::rolling_variance\n//\nnamespace extract\n{\n    extractor<tag::lazy_rolling_variance> const lazy_rolling_variance = {};\n    extractor<tag::immediate_rolling_variance> const immediate_rolling_variance = {};\n    extractor<tag::rolling_variance> const rolling_variance = {};\n\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(lazy_rolling_variance)\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(immediate_rolling_variance)\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_variance)\n}\n\nusing extract::lazy_rolling_variance;\nusing extract::immediate_rolling_variance;\nusing extract::rolling_variance;\n\n// rolling_variance(lazy) -> lazy_rolling_variance\ntemplate<>\nstruct as_feature<tag::rolling_variance(lazy)>\n{\n    typedef tag::lazy_rolling_variance type;\n};\n\n// rolling_variance(immediate) -> immediate_rolling_variance\ntemplate<>\nstruct as_feature<tag::rolling_variance(immediate)>\n{\n    typedef tag::immediate_rolling_variance type;\n};\n\n// for the purposes of feature-based dependency resolution,\n// lazy_rolling_variance provides the same feature as rolling_variance\ntemplate<>\nstruct feature_of<tag::lazy_rolling_variance>\n    : feature_of<tag::rolling_variance>\n{\n};\n\n// for the purposes of feature-based dependency resolution,\n// immediate_rolling_variance provides the same feature as rolling_variance\ntemplate<>\nstruct feature_of<tag::immediate_rolling_variance>\n  : feature_of<tag::rolling_variance>\n{\n};\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "33b3922a506748e0011c7714fd40527360ce5bfb", "size": 9063, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/accumulators/statistics/rolling_variance.hpp", "max_stars_repo_name": "multi-os-engine/cinder-natj-binding", "max_stars_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 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": "ios/Pods/boost-for-react-native/boost/accumulators/statistics/rolling_variance.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/accumulators/statistics/rolling_variance.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "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": 36.5443548387, "max_line_length": 135, "alphanum_fraction": 0.6500055169, "num_tokens": 2250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559848, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6026458054766374}}
{"text": "/**\n * dpmeans.hpp\n * @author koide\n * 16/06/07\n **/\n#ifndef KKL_DPMEANS_HPP\n#define KKL_DPMEANS_HPP\n\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\nnamespace kkl {\n  namespace alg {\n\n/**\n * @brief DP-means\n * @ref http://people.eecs.berkeley.edu/~jordan/papers/kulis-jordan-icml12.pdf\n */\ntemplate<typename T, int dim>\nclass DPmeans {\n  typedef Eigen::Matrix<T, dim, 1> VectorTd;\n\npublic:\n  // constructor, destructor\n  DPmeans() {}\n  ~DPmeans() {}\n\n  /**\n   * @brief train\n   * @param x           input data\n   * @param lambda      cluster penalty prameter\n   * @param criteria    convergence criteria\n   * @param loop_limit  maximum number of iterations\n   * @return\n   */\n  bool train(const std::vector<VectorTd>& x, T lambda, T criteria = 0.01, int loop_limit = 128) {\n    labels.assign(x.size(), 0);\n    centroids.clear();\n    centroids.push_back(VectorTd::Zero());\n\n    for (int i = 0; i < loop_limit; i++) {\n      updateCentroids(x, criteria);\n      if (updateLabels(x, lambda) ) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\nprivate:\n  // update centroids acoording to labels\n  bool updateCentroids(const std::vector<VectorTd>& x, T criteria) {\n    int k = centroids.size();\n    std::vector<int> accums(k, 0);\n    std::vector<VectorTd> new_centroids(k);\n    std::for_each(new_centroids.begin(), new_centroids.end(), [=](VectorTd& centroid) { centroid.setZero(); });\n\n    // update centrods\n    for (int i = 0; i < x.size(); i++) {\n      accums[labels[i]]++;\n      new_centroids[labels[i]] += x[i];\n    }\n    for (int i = 0; i < k; i++) {\n      new_centroids[i] /= std::max( 1, accums[i] );\n    }\n\n    centroids.swap(new_centroids);\n\n    // check if converged\n    for (int i = 0; i < centroids.size(); i++) {\n      if ((centroids[i] - new_centroids[i]).squaredNorm() > criteria * criteria) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  // update labels acoording to estimated centroids\n  // if the distance between a point and the closest centroid is lager than lambda, the point is added as a new centroid\n  bool updateLabels(const std::vector<VectorTd>& x, T lambda) {\n    bool is_converged = true;\n    bool k_incremented = false;\n    // for each point\n    for (int i = 0; i < x.size(); i++) {\n      T min_d = (centroids[0] - x[i]).squaredNorm();\n      int min_label = 0;\n\n      // find the closest centroid\n      for (int j = 1; j < centroids.size(); j++) {\n        T d = (centroids[j] - x[i]).squaredNorm();\n        if (d < min_d) {\n          min_d = d;\n          min_label = j;\n        }\n      }\n\n      // check if the distance between the point and the closest centroid is larger than lambda\n      if ( !k_incremented && min_d > lambda * lambda) {\n        k_incremented = true;\n        min_label = centroids.size();\n        centroids.push_back(x[i]);\n\n//\t\t\t\ti = 0;\t// re-calculate all labels since a new centroid is added\n      }\n\n      // if a label is changed, estimation is not converged\n      if (labels[i] != min_label) {\n        is_converged = false;\n      }\n      labels[i] = min_label;\n    }\n\n    return is_converged;\n  }\n\npublic:\n  std::vector<int> labels;\t\t\t    // labels assigned to input data\n  std::vector<VectorTd> centroids;\t// estimated centroids\n};\n\n  }\n}\n\n#endif\n", "meta": {"hexsha": "5a25be3114f09cd8f8c52d06ff020fd91578ccfa", "size": 3248, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kkl/alg/dp_means.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/dp_means.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/dp_means.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": 25.5748031496, "max_line_length": 120, "alphanum_fraction": 0.6009852217, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.6026078816063493}}
{"text": "#include <Eigen/Dense>\n#include <SFML/Graphics.hpp>\n\n#include <iomanip>\n#include <sstream>\n\nconst int GRIDSIZE = 256;\nconst double WINDOW_SCALING_FACTOR = 3.;\nconst double GAUSS_SEIDEL_TOLERANCE = 1e-4;\nconst int GAUSS_SEIDEL_ITER = 20;\n\nconst int FPS = 60;\nconst double VISC = 0.;\nconst double DIFF = 0.00002;\nconst double SOURCE = 20000.;\nconst double FORCE = 150.;\nconst double DISSOLVE = 0.005;\n\nusing Eigen::MatrixXd;\nusing Eigen::MatrixXi;\nusing Eigen::VectorXd;\nusing Eigen::VectorXi;\n\nvoid set_bnd(int b, MatrixXd &x)\n{\n    if (b == 1)\n    {\n        x.row(0) = -x.row(1);\n        x.row(x.rows() - 1) = -x.row(x.rows() - 2);\n    }\n    else\n    {\n        x.row(0) = x.row(1);\n        x.row(x.rows() - 1) = x.row(x.rows() - 2);\n    }\n\n    if (b == 2)\n    {\n        x.col(0) = -x.col(1);\n        x.col(x.cols() - 1) = -x.col(x.cols() - 2);\n    }\n    else\n    {\n        x.col(0) = x.col(1);\n        x.col(x.cols() - 1) = x.col(x.cols() - 2);\n    }\n\n    x(0, 0) = 0.5 * (x(1, 0) + x(0, 1));\n    x(0, x.cols() - 1) = 0.5 * (x(1, x.cols() - 1) + x(0, x.cols() - 2));\n    x(x.rows() - 1, 0) = 0.5 * (x(x.rows() - 2, 0) + x(x.rows() - 1, 1));\n    x(x.rows() - 1, x.cols() - 1) = 0.5 * (x(x.rows() - 2, x.cols() - 1) + x(x.rows() - 1, x.cols() - 2));\n}\n\nvoid lin_solve(int b, MatrixXd &x, const MatrixXd &x0, double a, double c)\n{\n    MatrixXd x_last = x;\n\n    const int N = x.rows() - 2;\n\n    for (int i = 0; i < GAUSS_SEIDEL_ITER; i++)\n    {\n        x.block(1, 1, N, N) = (x0.block(1, 1, N, N) +\n                               a * (x.block(0, 1, N, N) +\n                                    x.block(2, 1, N, N) +\n                                    x.block(1, 0, N, N) +\n                                    x.block(1, 2, N, N))) /\n                              c;\n        set_bnd(b, x);\n\n        if ((x_last - x).lpNorm<Eigen::Infinity>() < GAUSS_SEIDEL_TOLERANCE)\n        {\n            break;\n        }\n\n        x_last = x;\n    }\n}\n\nvoid add_source(MatrixXd &d, const MatrixXd &s, double dt)\n{\n    d += dt * s;\n}\n\nvoid diffuse(int b, MatrixXd &x, const MatrixXd &x0, double diff, double dt)\n{\n    const int N = x.rows() - 2;\n    const double a = dt * diff * N * N;\n    lin_solve(b, x, x0, a, 1. + 4. * a);\n}\n\nvoid advect(int b, MatrixXd &d, const MatrixXd &d0,\n            const MatrixXd &u, const MatrixXd &v, double dt)\n{\n    const int N = d.rows() - 2;\n\n    const double dt0 = dt * N;\n\n    for (int i = 1; i <= N; i++)\n    {\n        for (int j = 1; j <= N; j++)\n        {\n            double x = i - dt0 * u(i, j);\n            double y = j - dt0 * v(i, j);\n\n            x = std::clamp(x, 0.5, N + 0.5);\n            y = std::clamp(y, 0.5, N + 0.5);\n\n            const int i0 = int(x);\n            const int j0 = int(y);\n\n            const int i1 = i0 + 1;\n            const int j1 = j0 + 1;\n\n            const double s1 = x - i0;\n            const double t1 = y - j0;\n\n            const double s0 = 1. - s1;\n            const double t0 = 1. - t1;\n\n            d(i, j) = s0 * (t0 * d0(i0, j0) + t1 * d0(i0, j1)) +\n                      s1 * (t0 * d0(i1, j0) + t1 * d0(i1, j1));\n        }\n    }\n\n    set_bnd(b, d);\n}\n\nvoid project(MatrixXd &u, MatrixXd &v, MatrixXd &p, MatrixXd &div)\n{\n    const int N = div.rows() - 2;\n    const double h = 1. / N;\n\n    div.block(1, 1, N, N) = -0.5 * h *\n                            (u.block(2, 1, N, N) -\n                             u.block(0, 1, N, N) +\n                             v.block(1, 2, N, N) -\n                             v.block(1, 0, N, N));\n\n    set_bnd(0, div);\n\n    p.block(1, 1, N, N).setZero();\n    set_bnd(0, p);\n\n    lin_solve(0, p, div, 1., 4.);\n\n    u.block(1, 1, N, N) -= 0.5 / h * (p.block(2, 1, N, N) - p.block(0, 1, N, N));\n    v.block(1, 1, N, N) -= 0.5 / h * (p.block(1, 2, N, N) - p.block(1, 0, N, N));\n\n    set_bnd(1, u);\n    set_bnd(2, v);\n}\n\nvoid dens_step(MatrixXd &x, MatrixXd &x0,\n               const MatrixXd &u, const MatrixXd &v,\n               double diff, double dt)\n{\n    x *= (1. - DISSOLVE);\n    add_source(x, x0, dt);\n    diffuse(0, x0, x, diff, dt);\n    advect(0, x, x0, u, v, dt);\n}\n\nvoid vel_step(MatrixXd &u, MatrixXd &v,\n              MatrixXd &u0, MatrixXd &v0,\n              double visc, double dt)\n{\n    add_source(u, u0, dt);\n    add_source(v, v0, dt);\n\n    diffuse(1, u0, u, visc, dt);\n    diffuse(2, v0, v, visc, dt);\n\n    project(u0, v0, u, v);\n\n    advect(1, u, u0, u0, v0, dt);\n    advect(2, v, v0, u0, v0, dt);\n\n    project(u, v, u0, v0);\n}\n\nsf::Vector2i screen_coord_to_grid(sf::Vector2i coords)\n{\n    coords.x /= WINDOW_SCALING_FACTOR;\n    coords.y /= WINDOW_SCALING_FACTOR;\n\n    coords.x += 1;\n    coords.y += 1;\n\n    coords.x = std::clamp(coords.x, 1, GRIDSIZE - 2);\n    coords.y = std::clamp(coords.y, 1, GRIDSIZE - 2);\n\n    return {coords.x, GRIDSIZE - coords.y};\n}\n\nint main()\n{\n    // Velocity\n    MatrixXd u(GRIDSIZE, GRIDSIZE);\n    u.setZero();\n    MatrixXd v(GRIDSIZE, GRIDSIZE);\n    v.setZero();\n    MatrixXd u_prev(GRIDSIZE, GRIDSIZE);\n    u_prev.setZero();\n    MatrixXd v_prev(GRIDSIZE, GRIDSIZE);\n    v_prev.setZero();\n    // Density\n    MatrixXd d(GRIDSIZE, GRIDSIZE);\n    d.setZero();\n    MatrixXd d_prev(GRIDSIZE, GRIDSIZE);\n    d_prev.setZero();\n\n    // Drawing\n    const uint WINDOW_SIZE = (GRIDSIZE - 2) * WINDOW_SCALING_FACTOR;\n    sf::VideoMode mode(WINDOW_SIZE, WINDOW_SIZE);\n    sf::RenderWindow window(mode, \"Fluid\", sf::Style::Close);\n    window.setFramerateLimit(FPS);\n\n    using MatrixXu32 = Eigen::Matrix<uint32_t, Eigen::Dynamic, Eigen::Dynamic>;\n    using MatrixXu8 = Eigen::Matrix<uint8_t, Eigen::Dynamic, Eigen::Dynamic>;\n    using color_stride_map_t = Eigen::Map<MatrixXu8, 0, Eigen::InnerStride<4>>;\n    MatrixXu32 buffer(GRIDSIZE - 2, GRIDSIZE - 2);\n    color_stride_map_t mapped_red((uint8_t *)buffer.data() + 0, buffer.rows(), buffer.cols());\n    color_stride_map_t mapped_green((uint8_t *)buffer.data() + 1, buffer.rows(), buffer.cols());\n    color_stride_map_t mapped_blue((uint8_t *)buffer.data() + 2, buffer.rows(), buffer.cols());\n    color_stride_map_t mapped_alpha((uint8_t *)buffer.data() + 3, buffer.rows(), buffer.cols());\n    mapped_red.setConstant(0);\n    mapped_green.setConstant(255);\n    mapped_blue.setConstant(255);\n    mapped_alpha.setConstant(255);\n\n    sf::Texture texture;\n    texture.create(buffer.rows(), buffer.cols());\n    texture.setSmooth(true);\n\n    sf::Vector2i last_mouse_position(-1, -1);\n    bool left_pressed = false;\n    bool right_pressed = false;\n\n    uint frames = 0;\n    double current_framerate;\n    sf::Clock clock;\n    sf::Font font;\n    if (not font.loadFromFile(\"../DejaVuSans-Bold.ttf\"))\n    {\n        throw std::runtime_error(\"Font file not found!\");\n    }\n    sf::Text text;\n    text.setFont(font);\n    const uint text_height = WINDOW_SIZE / 20;\n    text.setCharacterSize(text_height);\n    text.setFillColor(sf::Color(100, 100, 100));\n    text.setPosition(text_height * 0.4, WINDOW_SIZE - text_height * 1.4);\n\n    while (window.isOpen())\n    {\n        // Update\n        {\n            const double dt = 1. / FPS;\n            vel_step(u, v, u_prev, v_prev, VISC, dt);\n            dens_step(d, d_prev, u, v, DIFF, dt);\n\n            d_prev.setZero();\n            u_prev.setZero();\n            v_prev.setZero();\n\n            const int center = GRIDSIZE / 2;\n            const int lower = GRIDSIZE / 5;\n            const double source = 10000.;\n            const double force = 50.;\n\n            d_prev.block<2, 2>(lower, center).setConstant(source);\n            u_prev.block<2, 2>(lower, center).setConstant(force);\n            d_prev.block<2, 2>(d_prev.rows() - lower, center).setConstant(source);\n            u_prev.block<2, 2>(u_prev.rows() - lower, center).setConstant(-force);\n        }\n\n        sf::Event event;\n        while (window.pollEvent(event))\n        {\n            if (event.type == sf::Event::Closed)\n                window.close();\n\n            if (event.type == sf::Event::MouseButtonPressed)\n            {\n                if (event.mouseButton.button == sf::Mouse::Right)\n                {\n                    right_pressed = true;\n                }\n                if (event.mouseButton.button == sf::Mouse::Left)\n                {\n                    left_pressed = true;\n                }\n            }\n\n            if (event.type == sf::Event::MouseButtonReleased)\n            {\n                if (event.mouseButton.button == sf::Mouse::Right)\n                {\n                    right_pressed = false;\n                }\n                if (event.mouseButton.button == sf::Mouse::Left)\n                {\n                    left_pressed = false;\n                }\n            }\n        }\n\n        if (right_pressed)\n        {\n            const sf::Vector2i mouse_position = sf::Mouse::getPosition(window);\n            const sf::Vector2i idx = screen_coord_to_grid(mouse_position);\n\n            d_prev(idx.x, idx.y) = SOURCE;\n        }\n        if (left_pressed)\n        {\n            const sf::Vector2i mouse_position = sf::Mouse::getPosition(window);\n            const sf::Vector2i idx = screen_coord_to_grid(mouse_position);\n\n            if (last_mouse_position != sf::Vector2i(-1, -1))\n            {\n                const double dx = last_mouse_position.x - mouse_position.x;\n                const double dy = last_mouse_position.y - mouse_position.y;\n                u_prev(idx.x, idx.y) = -FORCE * dx / WINDOW_SCALING_FACTOR;\n                v_prev(idx.x, idx.y) = FORCE * dy / WINDOW_SCALING_FACTOR;\n            }\n            last_mouse_position = mouse_position;\n        }\n        else\n        {\n            last_mouse_position = {-1, -1};\n        }\n\n        window.clear(sf::Color::Black);\n\n        mapped_alpha << d.block(1, 1, GRIDSIZE - 2, GRIDSIZE - 2).cwiseMin(255.).cast<uint8_t>();\n\n        texture.update((uint8_t *)buffer.data());\n        sf::Sprite sprite(texture);\n        sprite.setOrigin(sprite.getLocalBounds().width / 2.,\n                         sprite.getLocalBounds().height / 2.);\n        sprite.setPosition(float(window.getSize().x) / 2, float(window.getSize().y) / 2);\n        sprite.setScale(-WINDOW_SCALING_FACTOR, WINDOW_SCALING_FACTOR);\n        sprite.setRotation(-180.);\n        window.draw(sprite);\n\n        sf::Time elapsed = clock.getElapsedTime();\n        if (elapsed.asSeconds() > 0.25)\n        {\n            current_framerate = frames / elapsed.asSeconds();\n            std::stringstream stream;\n            stream << std::fixed << std::setprecision(2) << current_framerate;\n            text.setString(stream.str());\n\n            std::string s = stream.str();\n            frames = 0;\n            clock.restart();\n        }\n\n        window.draw(text);\n\n        window.display();\n        frames += 1;\n    }\n\n    return 0;\n}", "meta": {"hexsha": "e2d59b6f838941369ff5f9bf3a5835493532c1b2", "size": 10663, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fluid.cpp", "max_stars_repo_name": "EmbersArc/fluid2d", "max_stars_repo_head_hexsha": "e6dfedbaa8d5b6e47a9bdc69da7e76a09c12c440", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-06T06:54:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T06:54:29.000Z", "max_issues_repo_path": "fluid.cpp", "max_issues_repo_name": "EmbersArc/fluid2d", "max_issues_repo_head_hexsha": "e6dfedbaa8d5b6e47a9bdc69da7e76a09c12c440", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fluid.cpp", "max_forks_repo_name": "EmbersArc/fluid2d", "max_forks_repo_head_hexsha": "e6dfedbaa8d5b6e47a9bdc69da7e76a09c12c440", "max_forks_repo_licenses": ["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.0544959128, "max_line_length": 106, "alphanum_fraction": 0.517771734, "num_tokens": 3151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.6025782048644118}}
{"text": "#ifndef GEOMETRY_HPP\n#define GEOMETRY_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n// types\ntemplate<class U, int M=Eigen::Dynamic, int N=Eigen::Dynamic>\nusing matrix = Eigen::Matrix<U, M, N>;\n\ntemplate<class U, int N=Eigen::Dynamic>\nusing vector = matrix<U, N, 1>;\n\ntemplate<class U, int N=Eigen::Dynamic>\nusing covector = matrix<U, 1, N>;\n\ntemplate<class U>\nusing quaternion = Eigen::Quaternion<U>;\n\n\ntemplate<class G>\nstruct group;\n\n// rigid bodies\ntemplate<class U>\nstruct rigid {\n  quaternion<U> rotation;\n  vector<U, 3> translation;\n  \n  rigid(): rotation(quaternion<U>::Identity()), translation(0, 0, 0) { }\n};\n\n\n// quaternion group\ntemplate<class U>\nstruct group<quaternion<U>> {\n  using type = quaternion<U>;\n  using algebra = vector<U, 3>;\n  \n  static type id() { return type::Identity(); }\n  static type inv(const type& self) { return self.conjugate(); }\n  static type prod(const type& lhs, const type& rhs) { return lhs * rhs; }\n\n  static type exp(const algebra& self);\n  static algebra log(const type& self);\n\n  static algebra dexp(const algebra& self, const algebra& dself);\n  static algebra dlog(const type& self, const algebra& dself);\n  \n  static algebra Ad(const type& self, const algebra& omega) { return self * omega; }\n  static algebra ad(const algebra& self, const algebra& omega) { return self.cross(omega); }\n};\n\n\n// product group, same types\ntemplate<class G, int N>\nstruct group<vector<G, N>> {\n  static_assert(N != Eigen::Dynamic, \"size must be known at compile-time\");\n  using type = vector<G, N>;\n  using algebra = vector<typename group<G>::algebra, N>;\n\n  template<class F, class ... Self>\n  static auto map(F f, const Self& ... self) {\n    using result_type = typename std::result_of<F(Self...)>::type;\n    vector<result_type, N> result;\n    for(int i = 0; i < N; ++i) {\n      result(i) = f(self(i)...);\n    }\n\n    return result;\n  }\n  \n  static type id() {\n    return type::Constant(group<G>::id());\n  }\n  \n  static type inv(const type& self) {\n    return map(group<G>::inv, self);\n  }\n  \n  static type prod(const type& lhs, const type& rhs) {\n    return map(group<G>::prod, lhs, rhs);\n  }\n  \n  static type exp(const algebra& self) {\n    return map(group<G>::exp, self);\n  }\n  \n  static algebra log(const type& self) {\n    return map(group<G>::log, self);\n  }\n  \n  static algebra dexp(const algebra& self, const algebra& dself) {\n    return map(group<G>::dexp, self, dself);\n  }\n  \n  static algebra dlog(const type& self, const algebra& dself) {\n    return map(group<G>::dlog, self, dself);\n  }\n  \n  static algebra Ad(const type& self, const algebra& omega) {\n    return map(group<G>::Ad, self, omega);\n  }\n  \n  static algebra ad(const algebra& self, const algebra& omega) {\n    return map(group<G>::ad, self, omega);\n  }\n};\n\n\n// product group, different types\ntemplate<class G, class A, class ... Gs>\nstruct product {\n  using type = G;\n  using algebra = A;\n  \n  static type id() {\n    return group<G>::pack(group<Gs>::id()...);\n  }\n\n  static type inv(const type& self) {\n    return group<G>::unpack(self, [](const Gs&...gs) {\n      return group<G>::pack(group<Gs>::inv(gs)...);\n    });\n  }\n  \n  static type prod(const type& lhs, const type& rhs) {\n    return group<G>::unpack(lhs, [&](const Gs& ... lhs) {\n      return group<G>::unpack(rhs, [&](const Gs& ... rhs) {\n        return group<G>::pack(group<Gs>::prod(lhs, rhs)...);\n      });\n    });\n  }\n\n\n  static type exp(const algebra& self) {\n    return group<G>::unpack(self, [](const typename group<Gs>::algebra& ... ws) {\n      return group<G>::pack(group<Gs>::exp(ws)...);\n    });\n  }\n\n  static algebra log(const type& self) {\n    return group<G>::unpack(self, [](const typename group<Gs>::algebra& ... ws) {\n      return group<G>::pack(group<Gs>::log(ws)...);\n    });\n  }\n\n\n  static algebra dexp(const algebra& self, const algebra& dself) {\n    return group<G>::unpack(self, [&](const typename group<Gs>::algebra& ... ws) {\n      return group<G>::unpack(dself, [&](const typename group<Gs>::algebra& ... dws) {\n        return group<G>::pack(group<Gs>::dexp(ws, dws)...);\n      });\n    });\n  }\n\n  static algebra dlog(const type& self, const algebra& dself) {\n    return group<G>::unpack(self, [&](const Gs& ... gs) {\n      return group<G>::unpack(dself, [&](const typename group<Gs>::algebra& ... dgs) {\n        group<G>::pack(group<Gs>::dlog(gs, dgs)...);\n      });\n    });\n  }\n\n\n  static algebra Ad(const type& self, const algebra& dself) {\n    return group<G>::unpack(self, [&](const Gs& ... gs) {\n      return group<G>::unpack(dself, [&](const typename group<Gs>::algebra& ... dgs) {\n        return group<G>::pack(group<Gs>::Ad(gs, dgs)...);\n      });\n    });\n  }\n\n  static algebra ad(const type& self, const algebra& dself) {\n    return group<G>::unpack(self, [&](const Gs& ... gs) {\n      return group<G>::unpack(dself, [&](const typename group<Gs>::algebra& ... dgs) {\n        group<G>::pack(group<Gs>::ad(gs, dgs)...);\n      });\n    });\n  }\n  \n};\n\n\n// eucliean spaces\ntemplate<class E>\nstruct euclidean {\n  using type = E;\n  using algebra = E;\n\n  static type inv(const type& self) {\n    return -self;\n  }\n  \n  static type prod(const type& lhs, const type& rhs) {\n    return lhs + rhs;\n  }\n  \n  static type exp(const algebra& self) {\n    return self;\n  }\n  \n  static algebra log(const type& self) {\n    return self;\n  }\n  \n  static algebra dexp(const algebra& self, const algebra& dself) {\n    return dself;\n  }\n  \n  static algebra dlog(const type& self, const algebra& dself) {\n    return dself;\n  }\n  \n  static algebra Ad(const type& self, const algebra& omega) {\n    return omega;\n  }\n  \n  static algebra ad(const algebra& self, const algebra& omega) {\n    return group<E>::id();\n  }\n  \n};\n\n\n\n// scalars\ntemplate<> struct group<double> : euclidean<double> {\n  static double id() { return 0; }\n};\n\n\n// shorthands for real types\nusing real = double;\n\nusing vec = vector<real>;\n\nusing vec2 = vector<real, 2>;\nusing vec3 = vector<real, 3>;\nusing vec6 = vector<real, 6>;\n\nusing mat22 = matrix<real, 2, 2>;\nusing mat33 = matrix<real, 3, 3>;\nusing mat66 = matrix<real, 6, 6>;\n\nusing quat = quaternion<real>;\n\n\n\n\n\n\n#endif\n", "meta": {"hexsha": "57f7428f8815df1ffceb4e1d88f081b2afbf767f", "size": 6119, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "group.hpp", "max_stars_repo_name": "maxime-tournier/cpp", "max_stars_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "group.hpp", "max_issues_repo_name": "maxime-tournier/cpp", "max_issues_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "group.hpp", "max_forks_repo_name": "maxime-tournier/cpp", "max_forks_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0905511811, "max_line_length": 92, "alphanum_fraction": 0.6164405949, "num_tokens": 1678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.6025704578120579}}
{"text": "#include <gtest/gtest.h>\n#include <random>\n#include <gmp.h>\n#include <boost/multiprecision/gmp.hpp>\n#include <ojlibs/power.hpp>\nusing namespace std;\nusing namespace ojlibs;\nnamespace bm = boost::multiprecision;\n\nstd::mt19937 gen;\n\nvoid test_power(const bm::mpz_int &a, int b) {\n    bm::mpz_int expect = pow(a, b);\n    bm::mpz_int answer = power(a, b);\n\n    EXPECT_EQ(expect, answer);\n}\n\nTEST(BASIC, SMALL) {\n    test_power(12, 0);\n    test_power(12, 1);\n    test_power(12, 2);\n}\n\nTEST(BASIC, RANDOM) {\n    gmp_randstate_t ran;\n    gmp_randinit_default(ran);\n\n    static const int TEST_GROUP = 1000;\n    uniform_int_distribution<> dist(0, 10000);\n\n    for (int i = 0; i < TEST_GROUP; ++i) {\n        bm::mpz_int a;\n        mpz_urandomb(a.backend().data(), ran, 15);\n\n        int b = dist(gen);\n\n        test_power(a, b);\n    }\n}\n", "meta": {"hexsha": "fb9472bf444510823a4962a7355c8c75fdda74df", "size": 827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/power_test.cpp", "max_stars_repo_name": "georeth/OJLIBS", "max_stars_repo_head_hexsha": "de59d4fd21255cc2f0a580db7726b634449e6885", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-03-26T03:54:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T13:10:43.000Z", "max_issues_repo_path": "test/power_test.cpp", "max_issues_repo_name": "georeth/OJLIBS", "max_issues_repo_head_hexsha": "de59d4fd21255cc2f0a580db7726b634449e6885", "max_issues_repo_licenses": ["MIT"], "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/power_test.cpp", "max_forks_repo_name": "georeth/OJLIBS", "max_forks_repo_head_hexsha": "de59d4fd21255cc2f0a580db7726b634449e6885", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-03-06T09:59:14.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-06T09:59:14.000Z", "avg_line_length": 20.1707317073, "max_line_length": 50, "alphanum_fraction": 0.6336154776, "num_tokens": 245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.6025704462894406}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/eps.hpp\n *\n * \\brief Floating-point relative accuracy.\n *\n * Given a scalar \\f$x\\f$, compute the positive distance from \\f$|x|\\f$ to\n * the next larger in magnitude floating point number of the same precision as\n * \\f$x\\f$.\n * Except for numbers whose absolute value is smaller than the smallest positive\n * normalied floating-point number representable by its type , if\n * \\f$2^y \\le |x| < 2^{y+1}\\f$, then the \\c eps(x) function return\n * \\f$2^{y-d}\\f$, where \\f$d\\f$ is the number of radix digits in the mantissa.\n *\n * For all X of class double such that abs(X) <= realmin, eps(X) = 2^(-1074). Similarly, for all X of class single such that abs(X) <= realmin('single'), eps(X) = 2^(-149).\n *\n * <hr/>\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_EPS_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_EPS_HPP\n\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <cmath>\n#include <limits>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\n/**\n * \\brief Compute the distance from \\c 1.0 to the next largest floating-point\n *  precision number.\n * \\tparam RealT The floaint-point type.\n * \\return The distance from \\c 1.0 to the next largest floating-point\n *  precision number.\n */\ntemplate <typename RealT>\nBOOST_UBLAS_INLINE\ntypename type_traits<RealT>::real_type eps()\n{\n    // NOTE: type_traits<>::real_type is used in case of RealT is a non real\n    //       type (e.g., std::complex).\n\n    return ::std::numeric_limits<typename type_traits<RealT>::real_type>::epsilon();\n}\n\n\n/**\n * \\brief  Given a scalar \\f$x\\f$, compute the positive distance from\n *  \\f$|x|\\f$ to the next larger in magnitude floating point number of the\n *  same precision as \\f$x\\f$.\n * \\tparam RealT The floaint-point type.\n * \\param x A floating-point scalar value.\n * \\return The positive distance from \\f$|x|\\f$ to the next larger in\n *  magnitude floating point number of the same precision as \\f$a\\f$.\n */\ntemplate <typename RealT>\nBOOST_UBLAS_INLINE\ntypename type_traits<RealT>::real_type eps(RealT x)\n{\n    // NOTE: type_traits<>::real_type is used in case of RealT is a non real\n    //       type (e.g., std::complex).\n\n    typedef typename type_traits<RealT>::real_type real_type;\n    real_type y = ::std::abs(x);\n\n    if (y == ::std::numeric_limits<real_type>::infinity()\n        ||\n        ::std::isnan(y))\n    {\n        return ::std::numeric_limits<real_type>::quiet_NaN();\n    }\n    else if (y <= ::std::numeric_limits<real_type>::min())\n    {\n        return ::std::numeric_limits<real_type>::denorm_min();\n    }\n    else\n    {\n        int e;\n        ::std::frexp(y, &e);\n\n        return ::std::ldexp(1, e - ::std::numeric_limits<real_type>::digits);\n    }\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_EPS_HPP\n", "meta": {"hexsha": "2a8f605821ce3602388af210a4f5fd59bdb3f89b", "size": 3151, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/eps.hpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "boost/numeric/ublasx/operation/eps.hpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "boost/numeric/ublasx/operation/eps.hpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 30.8921568627, "max_line_length": 172, "alphanum_fraction": 0.6772453189, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867729389246, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6025631572111029}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2006-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NASA Vision Workbench is licensed under the Apache License,\n//  Version 2.0 (the \"License\"); you may not use this file except in\n//  compliance with the License. You may obtain a copy of the License at\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n// __END_LICENSE__\n\n\n#include <gtest/gtest_VW.h>\n#include <boost/random.hpp>\n#include <vw/Math/Statistics.h>\n\nusing namespace vw;\n\nstatic const double DELTA = 1e-5;\n\nTEST(Statistics, vector_stats) {\n\n  std::vector<double> vec(5);\n  for (int i=0; i<5; ++i) {\n    vec[i] = static_cast<double>(i);\n  }\n  \n  EXPECT_EQ( 2, vw::math::mean(vec) );\n  EXPECT_EQ( 2, vw::math::median(vec) );\n  EXPECT_NEAR( 1.58114, vw::math::standard_deviation(vec, 2), DELTA );\n  \n}\n\nTEST(Statistics, histogram) {\n\n  int    num_bins =  9;\n  double min_val  =  2;\n  double max_val  = 10;\n  math::Histogram hist(num_bins, min_val, max_val);\n  \n  hist(4);\n  hist(6);\n  hist(7);\n  hist(9);\n  hist(2);\n  hist(1);\n  hist(8);\n  hist(12);\n  hist(5);\n  hist(6);\n  hist(6);\n  \n  EXPECT_EQ(11, hist.get_total_num_values());\n  EXPECT_EQ( 2, hist.get_bin_value (0));\n  EXPECT_EQ( 3, hist.get_bin_value (4));\n  EXPECT_EQ( 6, hist.get_bin_center(4));\n}\n\n\nusing namespace vw::math;\n\nTEST(Statistics, CDF_cauchy) {\n  boost::mt19937 random_gen(42);\n  boost::cauchy_distribution<double> cauchy(35,80);\n  boost::variate_generator<boost::mt19937&,\n    boost::cauchy_distribution<double> > generator(random_gen, cauchy);\n\n  { // Default settings\n    CDFAccumulator<double> cdf;\n    for ( uint16 i = 0; i < 50000; i++ )\n      cdf( generator() );\n\n    EXPECT_NEAR( cdf.median(), 35.0, 2.0 );\n    EXPECT_NEAR( cdf.first_quartile(), -45, 4.0 );\n    EXPECT_NEAR( cdf.third_quartile(), 115, 4.0 );\n  }\n  { // More quantiles == more precision\n    CDFAccumulator<double> cdf(2000,500);\n    for ( uint16 i = 0; i < 50000; i++ )\n      cdf( generator() );\n\n    EXPECT_NEAR( cdf.median(), 35.0, 1.0 );\n    EXPECT_NEAR( cdf.first_quartile(), -45, 2.0 );\n    EXPECT_NEAR( cdf.third_quartile(), 115, 2.0 );\n  }\n}\n\nTEST(Statistics, CDF_triangular) {\n  boost::mt19937 random_gen(42);\n  boost::triangle_distribution<double> triangular(10,60,80);\n  boost::variate_generator<boost::mt19937&,\n    boost::triangle_distribution<double> > generator(random_gen, triangular);\n\n  { // Default settings\n    CDFAccumulator<double> cdf;\n    for ( uint16 i = 0; i < 50000; i++ )\n      cdf( generator() );\n\n    EXPECT_NEAR( cdf.median(), 51.833, 1.0 );\n    EXPECT_NEAR( cdf.first_quartile(), 39.6, 2.0 );\n    EXPECT_NEAR( cdf.third_quartile(), 61.3, 2.0 );\n    EXPECT_NEAR( cdf.approximate_mean(), 50, 1.0 );\n    EXPECT_NEAR( cdf.approximate_mean(0.05), 50, 0.5 );\n    EXPECT_NEAR( cdf.approximate_stddev(), 14.7196, 2.0 );\n    EXPECT_NEAR( cdf.approximate_stddev(0.05), 14.7196, 1.0 );\n  }\n  { // More quantiles == more precision\n    CDFAccumulator<double> cdf(2000,500);\n    for ( uint16 i = 0; i < 50000; i++ )\n      cdf( generator() );\n\n    EXPECT_NEAR( cdf.median(), 51.833, 0.5 );\n    EXPECT_NEAR( cdf.first_quartile(), 39.6, 1.0 );\n    EXPECT_NEAR( cdf.third_quartile(), 61.3, 1.0 );\n    EXPECT_NEAR( cdf.approximate_mean(), 50, 0.5 );\n    EXPECT_NEAR( cdf.approximate_mean(0.05), 50, 0.25 );\n    EXPECT_NEAR( cdf.approximate_stddev(), 14.7196, 3.0 );\n    EXPECT_NEAR( cdf.approximate_stddev(0.05), 14.7196, 0.5 );\n  }\n}\n\n\nTEST(Statistics, CDF_Merge ) {\n  boost::mt19937 random_gen(42);\n  boost::normal_distribution<double> norm1(0, 3);\n  boost::normal_distribution<double> norm2(5, 3);\n  boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > generator1( random_gen, norm1 );\n  boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > generator2( random_gen, norm2 );\n\n  CDFAccumulator<double> cdf0, cdf1, cdf2, cdf3;\n  // 0 is not updated.\n  // 1 will only see gen1 .. but will later be merged with 2.\n  // 2 will only see gen2\n  // 3 is our control and sees both gen1 and gen2;\n  for ( size_t i = 0; i < 50000; i++ ) {\n    double sample1 = generator1(), sample2 = generator2();\n    cdf1( sample1 );\n    cdf2( sample2 );\n    cdf3( sample1 );\n    cdf3( sample2 );\n  }\n\n  cdf1.update();\n  cdf2.update();\n  cdf3.update();\n  cdf1(cdf2);\n\n  EXPECT_NEAR( cdf1.median(), cdf3.median(), 0.01 );\n  EXPECT_NEAR( cdf1.first_quartile(), cdf3.first_quartile(), 0.01 );\n  EXPECT_NEAR( cdf1.third_quartile(), cdf3.third_quartile(), 0.01 );\n  EXPECT_NEAR( cdf1.approximate_mean(),\n               cdf3.approximate_mean(), 0.01 );\n\n  // Check that this works for an unused CDF object.\n  cdf0(cdf1);\n  EXPECT_NEAR( cdf1.median(), cdf0.median(), 0.01 );\n\n  // Test the duplication function\n  cdf0.duplicate(cdf2);\n  EXPECT_NEAR( cdf2.median(), cdf0.median(), 0.01 );\n}\n", "meta": {"hexsha": "e3aacee94604c9a56a1a62bb828fa3913da07730", "size": 5208, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/vw/Math/tests/TestStatistics.cxx", "max_stars_repo_name": "maxerbubba/visionworkbench", "max_stars_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 318.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T16:37:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T07:12:20.000Z", "max_issues_repo_path": "src/vw/Math/tests/TestStatistics.cxx", "max_issues_repo_name": "maxerbubba/visionworkbench", "max_issues_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-07-30T22:22:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T16:11:55.000Z", "max_forks_repo_path": "src/vw/Math/tests/TestStatistics.cxx", "max_forks_repo_name": "maxerbubba/visionworkbench", "max_forks_repo_head_hexsha": "b06ba0597cd3864bb44ca52671966ca580c02af1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 135.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T00:57:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T13:51:40.000Z", "avg_line_length": 31.0, "max_line_length": 113, "alphanum_fraction": 0.6658986175, "num_tokens": 1703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603725, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6025074484978772}}
{"text": "\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// Copyright Christopher Kormanyos 2016.\n\n// This file is written to be included from a Quickbook .qbk document.\n// It can be compiled by the C++ compiler, and run. Any output can\n// also be added here as comment or included or pasted in elsewhere.\n// Caution: this file contains Quickbook markup as well as code\n// and comments: don't change any of the special comment markups!\n\n// This file also includes Doxygen-style documentation about the function of the code.\n// See http://www.doxygen.org for details.\n\n//! \\file\n\n//! \\brief Example program showing a bare metal real-time performance measurement of a derivative(negatable), 32-bit.\n\n#include <mcal_benchmark.h>\n#include <mcal_cpu.h>\n#include <mcal_irq.h>\n#include <mcal_port.h>\n\n#define BOOST_FIXED_POINT_DISABLE_MULTIPRECISION // Do not use Boost.Multiprecision.\n#define BOOST_FIXED_POINT_DISABLE_IOSTREAM       // Do not use I/O streaming.\n\n#include <boost/fixed_point/fixed_point.hpp>\n\ntypedef boost::fixed_point::negatable<6, -9> numeric_type;\n//typedef float numeric_type;\n\nnamespace app\n{\n  namespace benchmark\n  {\n    void task_init();\n    void task_func();\n  }\n\n  typedef mcal::benchmark::benchmark_port_type port_type;\n}\n\nnamespace local\n{\n  template<typename RealValueType,\n           typename RealFunctionType>\n  RealValueType first_derivative(const RealValueType& x,\n                                 const RealValueType& dx,\n                                 RealFunctionType real_function)\n  {\n    const RealValueType dx2(dx  + dx);\n    const RealValueType dx3(dx2 + dx);\n\n    const RealValueType m1((  real_function(x + dx)\n                            - real_function(x - dx))  / 2U);\n    const RealValueType m2((  real_function(x + dx2)\n                            - real_function(x - dx2)) / 4U);\n    const RealValueType m3((  real_function(x + dx3)\n                            - real_function(x - dx3)) / 6U);\n\n    const RealValueType fifteen_m1(m1 * 15U);\n    const RealValueType six_m2    (m2 *  6U);\n    const RealValueType ten_dx    (dx * 10U);\n\n    return ((fifteen_m1 - six_m2) + m3) / ten_dx;\n  }\n}\n\nnumeric_type a;\nnumeric_type b;\nnumeric_type c;\nnumeric_type d;\n\nvoid app::benchmark::task_init()\n{\n  port_type::set_direction_output();\n\n  a = numeric_type(12U) / 10U;\n  b = numeric_type(34U) / 10U;\n  c = numeric_type(56U) / 10U;\n}\n\nvoid app::benchmark::task_func()\n{\n  // Compute the approximate derivative of (a * x^2) + (b * x) + c\n  // evaluated at 1/2, where the approximate values of the coefficients\n  // are: a = 1.2, b = 3.4, and c = 5.6. The step-size for evaluating\n  // the derivative is set to a value of approximately 1/4.\n\n  mcal::irq::disable_all();\n  port_type::set_pin_high();\n\n  d = local::first_derivative(numeric_type(1U) / 2U, // x-value\n                              numeric_type(1U) / 4U, // step size dx\n                              [](const numeric_type& x) -> numeric_type\n                              {\n                                return (((a * x) + b) * x) + c;\n                              });\n\n  port_type::set_pin_low();\n  mcal::irq::enable_all();\n\n  // The expected result is ((2 * a) + b) = (2.4 + 3.4) = 4.6 (exact).\n  // We obtain a fixed-point result of approximately 4.5938.\n\n  // Verify that the result lies within (4.5 < result < 4.7).\n  // The expected result is 4.6, so this is a wide tolerance.\n\n  const bool value_is_ok =    (d > numeric_type(4))\n                           && (d < numeric_type(5));\n\n  if(value_is_ok)\n  {\n    // The benchmark is OK.\n    // Perform one nop and leave.\n\n    mcal::cpu::nop();\n  }\n  else\n  {\n    // The benchmark result is not OK!\n    // Remain in a blocking loop and crash the system.\n\n    for(;;) { mcal::cpu::nop(); }\n  }\n}\n", "meta": {"hexsha": "dc75bf12e1bbbb65781e8307bb4b0dafa430cbe7", "size": 3884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_bare_metal_benchmark_16bit_derivative.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_bare_metal_benchmark_16bit_derivative.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_bare_metal_benchmark_16bit_derivative.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": 29.8769230769, "max_line_length": 117, "alphanum_fraction": 0.6287332647, "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.6025074457316012}}
{"text": "/*\n * cost_structure.cpp\n *\n *  Created on: Jan 20, 2021\n *      Author: talhakavuncu\n */\n#include <iostream>\n#include <unsupported/Eigen/AdolcForward>\n#include <adolc/adolc.h>\n#include <Eigen/Dense>\n#include \"cost_structure.h\"\n#include <math.h>\nnamespace Unicycle_Cost\n\n{\n\tadouble running_cost(const state_type_unicycle & x,const input_type_unicycle & u,const state_type_unicycle & x_goal)\n\t{\n\n\n\t\tadouble output,input_cost,state_cost;\n\t\tstate_type_unicycle diff=x-x_goal;\n\t//\tEigen::Matrix<adouble,4,4> Q;\n\t//\tEigen::Matrix<adouble,2,2> R;\n\t//\tQ<<1,0,0,0,\n\t//\t\t0,1,0,0,\n\t//\t\t0,0,1,0,\n\t//\t\t0,0,0,1;\n\n\t//\t\tQ<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;\n\t//\t\tR<<2,2,2,2;\n\t//\tR<<1,0,0,1;\n\t//\n\t//\tintermediate=inputs.transpose()*R*inputs;//+inputs[0]*states[2];//inputs.dot(inputs)*states.dot(states);\n\t//\toutput=diff.transpose()*Q*diff + intermediate;\n\t\tinput_cost=u.dot(u);\n\t\tstate_cost=diff.dot(diff);\n\t\toutput=input_cost+state_cost;\n\t\treturn output;\n\t};\n\n\n\n\n\tadouble terminal_cost(const state_type_unicycle & x,const input_type_unicycle & u,const state_type_unicycle & x_goal)\n\t{\n\n\t\tadouble output;\n\t\tstate_type_unicycle diff=x-x_goal;\n\n//\t\tEigen::Matrix<adouble,4,4> Q;\n//\t\tQ<<1,0,0,0,\n//\t\t\t0,1,0,0,\n//\t\t\t0,0,1,0,\n//\t\t\t0,0,0,1;\n//\t\tEigen::Matrix<adouble,2,2> R;\n//\t\tR<<2,2,2,2;\n//\t\tR<<1,1,1,1;\n//\t\tintermediate=inputs.transpose()*R*inputs;//+inputs[0]*states[2];//inputs.dot(inputs)*states.dot(states);\n\n\t\toutput=100*diff.dot(diff);\n\t\treturn output;\n\t};\n\n\n\n\tadouble running_cost2(const state_type_unicycle2 & x,const input_type_unicycle2 & u,const state_type_unicycle2 & x_goal)\n\t{\n\t\tadouble output,input_cost,state_cost,ca_total;\n\t\tint row_size=1;\n\t\tint col_size=2;\n\n\t\tadouble d_prox=1.2;\n//\t\tadouble c_ij_costs[1][2]={{0}};\n\t\tstd::vector<std::vector<adouble>> c_ij_costs(row_size,std::vector<adouble>(col_size));\n\t\tfor(int i=0;i<row_size;++i)\n\t\t\tfor(int j=i+1;j<col_size;++j)\n\t\t\t\tc_ij_cost(x.segment(i*4,2),x.segment(j*4,2),c_ij_costs[i][j],d_prox);\n\n\t\tcalculate_total_c_ij_cost(c_ij_costs,ca_total);\n\n\n\t\tstate_type_unicycle2 diff=x-x_goal;\n\t\tinput_cost=u.dot(u);\n\t\tstate_cost=diff.dot(diff);\n\t\toutput=input_cost+state_cost+ca_total;\n\t\treturn output;\n\t};\n\tadouble terminal_cost2(const state_type_unicycle2 & x,const input_type_unicycle2 & u,const state_type_unicycle2 & x_goal)\n\t{\n\t\tadouble output;\n\t\tstate_type_unicycle2 diff=x-x_goal;\n\t\toutput=25*diff.dot(diff);\n\t\treturn output;\n\t};\n\n\tadouble running_cost3(const state_type_unicycle3 & x,const input_type_unicycle3 & u,const state_type_unicycle3 & x_goal)\n\t{\n\t\tadouble output,input_cost,state_cost,ca_total;\n\t\tint row_size=2;\n\t\tint col_size=3;\n\n\t\tadouble d_prox=0.6;\n//\t\tadouble c_ij_costs[1][2]={{0}};\n\t\tstd::vector<std::vector<adouble>> c_ij_costs(row_size,std::vector<adouble>(col_size));\n\t\tfor(int i=0;i<row_size;++i)\n\t\t\tfor(int j=i+1;j<col_size;++j)\n\t\t\t\tc_ij_cost(x.segment(i*4,2),x.segment(j*4,2),c_ij_costs[i][j],d_prox);\n\n\t\tcalculate_total_c_ij_cost(c_ij_costs,ca_total);\n\t\tstate_type_unicycle3 diff=x-x_goal;\n\t\tinput_cost=u.dot(u);\n\t\tstate_cost=diff.dot(diff);\n\t\toutput=input_cost+state_cost;\n\t\treturn output;\n\t};\n\tadouble terminal_cost3(const state_type_unicycle3 & x,const input_type_unicycle3 & u,const state_type_unicycle3 & x_goal)\n\t{\n\t\tadouble output;\n\t\tstate_type_unicycle3 diff=x-x_goal;\n\t\toutput=diff.dot(diff);\n\t\treturn output;\n\t};\n\n\tadouble running_cost4(const state_type_unicycle4 & x,const input_type_unicycle4 & u,const state_type_unicycle4 & x_goal)\n\t{\n\t\tadouble output,input_cost,state_cost,ca_total;\n\t\tint row_size=3;\n\t\tint col_size=4;\n\n\t\tadouble d_prox=0.6;\n//\t\tadouble c_ij_costs[1][2]={{0}};\n\t\tstd::vector<std::vector<adouble>> c_ij_costs(row_size,std::vector<adouble>(col_size));\n\t\tfor(int i=0;i<row_size;++i)\n\t\t\tfor(int j=i+1;j<col_size;++j)\n\t\t\t\tc_ij_cost(x.segment(i*4,2),x.segment(j*4,2),c_ij_costs[i][j],d_prox);\n\n\t\tcalculate_total_c_ij_cost(c_ij_costs,ca_total);\n\t\tstate_type_unicycle4 diff=x-x_goal;\n\t\tinput_cost=u.dot(u);\n\t\tstate_cost=diff.dot(diff);\n\t\toutput=input_cost+state_cost;\n\t\treturn output;\n\t};\n\tadouble terminal_cost4(const state_type_unicycle4 & x,const input_type_unicycle4 & u,const state_type_unicycle4 & x_goal)\n\t{\n\t\tadouble output;\n\t\tstate_type_unicycle4 diff=x-x_goal;\n\t\toutput=diff.dot(diff);\n\t\treturn output;\n\t};\n\n\tadouble running_cost6(const state_type_unicycle6 & x,const input_type_unicycle6 & u,const state_type_unicycle6 & x_goal)\n\t{\n\t\tadouble output,input_cost,state_cost,ca_total;\n\t\tint row_size=5;\n\t\tint col_size=6;\n\n\t\tadouble d_prox=0.6;\n//\t\tadouble c_ij_costs[1][2]={{0}};\n\t\tstd::vector<std::vector<adouble>> c_ij_costs(row_size,std::vector<adouble>(col_size));\n\t\tfor(int i=0;i<row_size;++i)\n\t\t\tfor(int j=i+1;j<col_size;++j)\n\t\t\t\tc_ij_cost(x.segment(i*4,2),x.segment(j*4,2),c_ij_costs[i][j],d_prox);\n\n\t\tcalculate_total_c_ij_cost(c_ij_costs,ca_total);\n\t\tstate_type_unicycle6 diff=x-x_goal;\n\t\tinput_cost=u.dot(u);\n\t\tstate_cost=diff.dot(diff);\n\t\toutput=input_cost+state_cost;\n\t\treturn output;\n\t};\n\tadouble terminal_cost6(const state_type_unicycle6 & x,const input_type_unicycle6 & u,const state_type_unicycle6 & x_goal)\n\t{\n\t\tadouble output;\n\t\tstate_type_unicycle6 diff=x-x_goal;\n\t\toutput=diff.dot(diff);\n\t\treturn output;\n\t};\n\n\n\n\tvoid c_ij_cost(const Eigen::Matrix<adouble,2,1> & x_i,const Eigen::Matrix<adouble,2,1> & x_j,\n\t\t\tadouble & cost,const adouble &d_prox)\n\t{\n\t\tEigen::Matrix<adouble,2,1> diff;\n\t\tdiff=x_i-x_j;\n\t\tadouble distance,distance_diff;\n\t\tdistance=pow(diff.dot(diff),0.5);\n\t\tdistance_diff=distance-d_prox;\n\t\tcondassign(cost,distance_diff,adouble(0),1e3*pow(distance_diff,2));\n\n\t};\n\n\tvoid calculate_total_c_ij_cost(const std::vector<std::vector<adouble>> &c_ij_costs,adouble & total_cost)\n\t{\n\t\tfor(int i=0;i<c_ij_costs.size();++i)\n\t\t\tfor(int j=i+1;j<c_ij_costs[0].size();++j)\n\t\t\t\ttotal_cost+=c_ij_costs[i][j];\n\t};\n};\n\n\n//adouble terminal_cost_drone(const state_type_tensor & states,const input_type_tensor & inputs);\nnamespace Drone_Cost\n{\n\n\n\tadouble running_cost(const state_type_drone & states,const input_type_drone & inputs,const state_type_drone & X_goal)\n\t{\n\n\t\tadouble output,input_cost,collision_cost,d_prox,distance,distance_diff;\n\t\td_prox=3;\n\t\tEigen::Matrix<adouble,3,1> avoid_pos,avoid_diff;\n\t\tavoid_pos<<5,-1,0;\n//\t\tavoid_diff<<\n\t\tstate_type_drone diff;\n\t\tfor (int i=0;i<3;++i)\n\t\t\tavoid_diff[i]=states[i]-avoid_pos[i];\n\n\n\t\tdistance=pow(avoid_diff.dot(avoid_diff),0.5);\n\t\tdistance_diff=distance-d_prox;\n//\t\tadouble zero=0;\n//\t\tadouble value=1e6*pow(distance_diff,2);\n\t\tcondassign(collision_cost,distance_diff,adouble(0),1e3*pow(distance_diff,2));\n//\t\tfor(int i=0;i<3;++i)\n//\t\t\txyz_diff[i]=diff[i];\n\n//\t\tX_goal<<0,0,0, M_PI/2,0,0, 0,30,0, 0,0,0;\n//\t\tEigen::Matrix<adouble,12,12> Q;\n//\t\tQ<<\t1,0,0,0,0,0,0,0,0,0,0,0,\n//\t\t\t0,1,0,0,0,0,0,0,0,0,0,0,\n//\t\t\t0,0,1,0,0,0,0,0,0,0,0,0,\n//\t\t\t0,0,0,1/9,0,0,0,0,0,0,0,0,\n//\t\t\t0,0,0,0,1,0,0,0,0,0,0,0,\n//\t\t\t0,0,0,0,0,1,0,0,0,0,0,0,\n//\t\t\t0,0,0,0,0,0,1,0,0,0,0,0,\n//\t\t\t0,0,0,0,0,0,0,1/900,0,0,0,0,\n//\t\t\t0,0,0,0,0,0,0,0,1,0,0,0,\n//\t\t\t0,0,0,0,0,0,0,0,0,1,0,0,\n//\t\t\t0,0,0,0,0,0,0,0,0,0,1,0,\n//\t\t\t0,0,0,0,0,0,0,0,0,0,0,1;\n\n//\t\tdiff=states-X_goal;\n\t\tinput_cost=10*1/(mass*g/(4*C_T))*inputs.dot(inputs);\n//\t\toutput=0.000001*diff.transpose()*Q*diff;//intermediate;\n\t\tdiff=states-X_goal;\n\t\toutput=100*diff.dot(diff)+input_cost+collision_cost;\n//\t\toutput=1;\n//\t\toutput=100*(1*diff[0]*diff[0]+1*diff[1]*diff[1]+1*diff[2]*diff[2]+100*diff[3]*diff[3]+100*diff[7]*diff[7]);\n\t\treturn output;\n\n\t};\n\n\tadouble terminal_cost(const state_type_drone & states,const input_type_drone & inputs,const state_type_drone & X_goal)\n\t{\n//\t\tstate_type_drone X_goal,diff;\n\t\tstate_type_drone diff;\n//\t\tfor (int i=0;i<12;++i)\n//\t\t\tdiff[i]=states[i]-X_goal[i];\n\t\tdiff=states-X_goal;\n//\t\tX_goal<<5,5,5, 0,0,0 ,0,0,0, 0,0,0;\n//\t\tX_goal<<0,0,0, M_PI/2,0,0, 0,30,0, 0,0,0;\n//\t\tdiff=states-X_goal;\n//\t\tEigen::Matrix<adouble,12,12> Q;\n//\t\tQ<<\t1,0,0,0,0,0,0,0,0,0,0,0,\n//\t\t\t0,1,0,0,0,0,0,0,0,0,0,0,\n//\t\t\t0,0,1,0,0,0,0,0,0,0,0,0,\n//\t\t\t0,0,0,1/9,0,0,0,0,0,0,0,0,\n//\t\t\t0,0,0,0,1,0,0,0,0,0,0,0,\n//\t\t\t0,0,0,0,0,1,0,0,0,0,0,0,\n//\t\t\t0,0,0,0,0,0,1,0,0,0,0,0,\n//\t\t\t0,0,0,0,0,0,0,1/900,0,0,0,0,\n//\t\t\t0,0,0,0,0,0,0,0,1,0,0,0,\n//\t\t\t0,0,0,0,0,0,0,0,0,1,0,0,\n//\t\t\t0,0,0,0,0,0,0,0,0,0,1,0,\n//\t\t\t0,0,0,0,0,0,0,0,0,0,0,1;\n\t\tadouble output;\n//\t\toutput=100*diff.transpose()*Q*diff;\n\t\toutput=100*diff.dot(diff);\n//\t\toutput=100*(1*diff[0]*diff[0]+1*diff[1]*diff[1]+1*diff[2]*diff[2]+100*diff[3]*diff[3]+100*diff[7]*diff[7]);\n\t\treturn output;\n\t};\n\n\tadouble running_cost2(const state_type_drone2 & states,const input_type_drone2 & inputs,const state_type_drone2 & X_goal)\n\t{\n\n\t\tadouble output,input_cost,state_cost;\n\n//\t\tadouble d_prox_collision,collision_distance,distance_diff,collision_cost;\n//\t\td_prox_collision=3;\n//\t\tEigen::Matrix<adouble,3,1> avoid_pos,avoid_diff;\n//\t\tavoid_pos<<5,-1,0;\n//\t\tfor (int i=0;i<3;++i)\n//\t\t\tavoid_diff[i]=states[i]-avoid_pos[i];\n//\n//\t\tcollision_distance=pow(avoid_diff.dot(avoid_diff),0.5);\n//\t\tdistance_diff=collision_distance-d_prox_collision;\n//\t\tcondassign(collision_cost,distance_diff,adouble(0),1e3*pow(distance_diff,2));\n\n\t\tadouble ca_distance_diff,ca_cost,ca_distance,ca_dprox;\n\t\tca_dprox=0.5;\n\t\tEigen::Matrix<adouble,3,1> pos_diff;\n\t\tfor (int i=0;i<3;++i)\n\t\t\tpos_diff[i]=states[i]-states[i+12];\n\n\t\tca_distance=pow(pos_diff.dot(pos_diff),0.5);\n\t\tca_distance_diff=ca_distance-ca_dprox;\n\t\tcondassign(ca_cost,ca_distance_diff,adouble(0),1e3*pow(ca_distance_diff,2));\n\n\t\tstate_type_drone2 goal_diff;\n\t\tgoal_diff=states-X_goal;\n\t\tinput_cost=10*1/(mass*g/(4*C_T))*inputs.dot(inputs);\n\t\tstate_cost=100*goal_diff.dot(goal_diff);\n\t\toutput=state_cost+input_cost+ca_cost;\n\t\treturn output;\n\n\t};\n\n\tadouble terminal_cost2(const state_type_drone2 & states,const input_type_drone2 & inputs,const state_type_drone2 & X_goal)\n\t{\n\t\tstate_type_drone2 diff;\n\t\tdiff=states-X_goal;\n\t\tadouble output;\n\t\toutput=100*diff.dot(diff);\n\t\treturn output;\n\t};\n\n};\n\nnamespace Single_Integrator_Cost{\n\n\tadouble running_cost(const state_tensor & x, const input_tensor & u,const state_tensor & x_goal)\n\t{\n\t\tadouble output,input_cost,state_cost,collision_cost,d_prox,distance,distance_diff;\n\t\tstate_tensor diff,avoid_pose,avoid_diff;\n\t\td_prox=0.6;\n\t\tavoid_pose<<-0.5,0.5,0.5;\n\t\tavoid_diff=x-avoid_pose;\n\n\t\tdistance=pow(avoid_diff.dot(avoid_diff),0.5);\n\t\tdistance_diff=distance-d_prox;\n\n\t\tcondassign(collision_cost,distance_diff,adouble(0),1e5*pow(distance_diff,2));\n\n\t\tdiff=x-x_goal;\n\t\tstate_cost=1e2*diff.dot(diff);\n\t\tinput_cost=1e1*u.dot(u);\n\n\t\toutput=state_cost+input_cost+collision_cost;\n\n\t\treturn output;\n\n\t}\n\tadouble terminal_cost(const state_tensor & x, const input_tensor & u,const state_tensor & x_goal)\n\t{\n\t\tstate_tensor diff=x-x_goal;\n\t\tadouble state_cost=1e2*diff.dot(diff);\n\n\t\treturn state_cost;\n\n\t}\n\n\tadouble running_cost2(const state_tensor2 & x, const input_tensor2 & u,const state_tensor2 & x_goal)\n\t{\n\t\tadouble output,input_cost,state_cost;\n\n//\t\tadouble d_prox_collision,collision_distance,distance_diff,collision_cost;\n//\t\td_prox_collision=3;\n//\t\tEigen::Matrix<adouble,3,1> avoid_pos,avoid_diff;\n//\t\tavoid_pos<<5,-1,0;\n//\t\tfor (int i=0;i<3;++i)\n//\t\t\tavoid_diff[i]=states[i]-avoid_pos[i];\n//\n//\t\tcollision_distance=pow(avoid_diff.dot(avoid_diff),0.5);\n//\t\tdistance_diff=collision_distance-d_prox_collision;\n//\t\tcondassign(collision_cost,distance_diff,adouble(0),1e3*pow(distance_diff,2));\n\n\t\tadouble ca_distance_diff,ca_cost,ca_distance,ca_dprox;\n\t\tca_dprox=0.5;\n\t\tEigen::Matrix<adouble,3,1> pos_diff;\n\t\tfor (int i=0;i<3;++i)\n\t\t\tpos_diff[i]=x[i]-x[i+3];\n\n\t\tca_distance=pow(pos_diff.dot(pos_diff),0.5);\n\t\tca_distance_diff=ca_distance-ca_dprox;\n\t\tcondassign(ca_cost,ca_distance_diff,adouble(0),1e5*pow(ca_distance_diff,2));\n\n\t\tstate_tensor2 goal_diff;\n\t\tgoal_diff=x-x_goal;\n//\t\tinput_cost=0.12*1e1*u.dot(u);\n\t\tinput_cost=0.5*1e1*u.dot(u);\n\t\tstate_cost=1e-20*goal_diff.dot(goal_diff);\n\t\toutput=state_cost+input_cost+ca_cost;\n\t\treturn output;\n\n\n\t}\n\tadouble terminal_cost2(const state_tensor2 & x, const input_tensor2 & u,const state_tensor2 & x_goal)\n\t{\n\t\tstate_tensor2 diff=x-x_goal;\n\t\tadouble state_cost=100*diff.dot(diff);\n\n\t\treturn state_cost;\n\t}\n\n}\n\n\n\n\nnamespace Double_Integrator_Cost{\n\n\tadouble running_cost(const state_tensor & x, const input_tensor & u,const state_tensor & x_goal)\n\t{\n\t\tadouble output,input_cost,state_cost,collision_cost,d_prox,distance,distance_diff;\n\t\tstate_tensor diff;\n\t\tEigen::Matrix<adouble,3,1> avoid_pos,avoid_diff;\n\t\td_prox=1;\n\t\tavoid_pos<<1,1,1;\n\t\tavoid_diff=x.segment(0,3)-avoid_pos;\n\t\tdistance=pow(avoid_diff.dot(avoid_diff),0.5);\n\t\tdistance_diff=distance-d_prox;\n\n\t\tcondassign(collision_cost,distance_diff,adouble(0),1e3*pow(distance_diff,2));\n\n\t\tdiff=x-x_goal;\n\t\tstate_cost=1e2*diff.dot(diff);\n\t\tinput_cost=1*1e-2*u.dot(u);\n\n\t\toutput=state_cost+input_cost+collision_cost;\n\n\t\treturn output;\n\n\t}\n\tadouble terminal_cost(const state_tensor & x, const input_tensor & u,const state_tensor & x_goal)\n\t{\n\t\tstate_tensor diff=x-x_goal;\n\t\tadouble state_cost=1e2*diff.dot(diff);\n\n\t\treturn state_cost;\n\n\t}\n\n//\tadouble running_cost2(const state_tensor2 & x, const input_tensor2 & u,const state_tensor2 & x_goal)\n//\t{\n//\t\tadouble output,input_cost,state_cost;\n//\n////\t\tadouble d_prox_collision,collision_distance,distance_diff,collision_cost;\n////\t\td_prox_collision=3;\n////\t\tEigen::Matrix<adouble,3,1> avoid_pos,avoid_diff;\n////\t\tavoid_pos<<5,-1,0;\n////\t\tfor (int i=0;i<3;++i)\n////\t\t\tavoid_diff[i]=states[i]-avoid_pos[i];\n////\n////\t\tcollision_distance=pow(avoid_diff.dot(avoid_diff),0.5);\n////\t\tdistance_diff=collision_distance-d_prox_collision;\n////\t\tcondassign(collision_cost,distance_diff,adouble(0),1e3*pow(distance_diff,2));\n//\n//\t\tadouble ca_distance_diff,ca_cost,ca_distance,ca_dprox;\n//\t\tca_dprox=0.5;\n//\t\tEigen::Matrix<adouble,3,1> pos_diff;\n//\t\tfor (int i=0;i<3;++i)\n//\t\t\tpos_diff[i]=x[i]-x[i+3];\n//\n//\t\tca_distance=pow(pos_diff.dot(pos_diff),0.5);\n//\t\tca_distance_diff=ca_distance-ca_dprox;\n//\t\tcondassign(ca_cost,ca_distance_diff,adouble(0),1e5*pow(ca_distance_diff,2));\n//\n//\t\tstate_tensor2 goal_diff;\n//\t\tgoal_diff=x-x_goal;\n////\t\tinput_cost=0.12*1e1*u.dot(u);\n//\t\tinput_cost=0.5*1e1*u.dot(u);\n//\t\tstate_cost=1e-20*goal_diff.dot(goal_diff);\n//\t\toutput=state_cost+input_cost+ca_cost;\n//\t\treturn output;\n//\n//\n//\t}\n//\tadouble terminal_cost2(const state_tensor2 & x, const input_tensor2 & u,const state_tensor2 & x_goal)\n//\t{\n//\t\tstate_tensor2 diff=x-x_goal;\n//\t\tadouble state_cost=100*diff.dot(diff);\n//\n//\t\treturn state_cost;\n//\t}\n\n}\n\nnamespace Drone_First_Order_Cost\n{\n\n\tadouble running_cost(const state_type_drone & states,const input_type_drone & inputs,const state_type_drone & X_goal)\n\t{\n\t\tadouble output,input_cost,collision_cost,d_prox,distance,distance_diff;\n\t\td_prox=1.0;\n\t\tEigen::Matrix<adouble,3,1> avoid_pos,avoid_diff;\n\t\tavoid_pos<<0.5,0.5,0.5;\n//\t\tavoid_diff<<\n\t\tstate_type_drone diff;\n\t\tfor (int i=0;i<3;++i)\n\t\t\tavoid_diff[i]=states[i]-avoid_pos[i];\n\n\n\t\tdistance=pow(avoid_diff.dot(avoid_diff),0.5);\n\t\tdistance_diff=distance-d_prox;\n//\t\tadouble zero=0;\n//\t\tadouble value=1e6*pow(distance_diff,2);\n\t\tcondassign(collision_cost,distance_diff,adouble(0),1e6*pow(distance_diff,2));\n//\t\tfor(int i=0;i<3;++i)\n//\t\t\txyz_diff[i]=diff[i];\n\n//\t\tX_goal<<0,0,0, M_PI/2,0,0, 0,30,0, 0,0,0;\n//\t\tEigen::Matrix<adouble,12,12> Q;\n//\t\tQ<<\t1,0,0,0,0,0,0,0,0,0,0,0,\n//\t\t\t0,1,0,0,0,0,0,0,0,0,0,0,\n//\t\t\t0,0,1,0,0,0,0,0,0,0,0,0,\n//\t\t\t0,0,0,1/9,0,0,0,0,0,0,0,0,\n//\t\t\t0,0,0,0,1,0,0,0,0,0,0,0,\n//\t\t\t0,0,0,0,0,1,0,0,0,0,0,0,\n//\t\t\t0,0,0,0,0,0,1,0,0,0,0,0,\n//\t\t\t0,0,0,0,0,0,0,1/900,0,0,0,0,\n//\t\t\t0,0,0,0,0,0,0,0,1,0,0,0,\n//\t\t\t0,0,0,0,0,0,0,0,0,1,0,0,\n//\t\t\t0,0,0,0,0,0,0,0,0,0,1,0,\n//\t\t\t0,0,0,0,0,0,0,0,0,0,0,1;\n\n//\t\tdiff=states-X_goal;\n\t\tinput_cost=3e1*inputs.dot(inputs);\n//\t\toutput=0.000001*diff.transpose()*Q*diff;//intermediate;\n\t\tdiff=states-X_goal;\n\t\toutput=100*diff.dot(diff)+input_cost+collision_cost;\n//\t\toutput=1;\n//\t\toutput=100*(1*diff[0]*diff[0]+1*diff[1]*diff[1]+1*diff[2]*diff[2]+100*diff[3]*diff[3]+100*diff[7]*diff[7]);\n\t\treturn output;\n\t}\n\tadouble terminal_cost(const state_type_drone & states,const input_type_drone & inputs,const state_type_drone & X_goal)\n\t{\n\t\tadouble output;\n\t\tstate_type_drone diff;\n\t\tdiff=states-X_goal;\n//\t\toutput=100*diff.transpose()*Q*diff;\n\t\toutput=100*diff.dot(diff);\n//\t\toutput=100*(1*diff[0]*diff[0]+1*diff[1]*diff[1]+1*diff[2]*diff[2]+100*diff[3]*diff[3]+100*diff[7]*diff[7]);\n\t\treturn output;\n\t}\n\n\tadouble running_cost2(const state_type_drone2 & states,const input_type_drone2 & inputs,const state_type_drone2 & X_goal)\n\t{\n\t\tadouble output,input_cost,state_cost;\n\n//\t\tadouble d_prox_collision,collision_distance,distance_diff,collision_cost;\n//\t\td_prox_collision=3;\n//\t\tEigen::Matrix<adouble,3,1> avoid_pos,avoid_diff;\n//\t\tavoid_pos<<5,-1,0;\n//\t\tfor (int i=0;i<3;++i)\n//\t\t\tavoid_diff[i]=states[i]-avoid_pos[i];\n//\n//\t\tcollision_distance=pow(avoid_diff.dot(avoid_diff),0.5);\n//\t\tdistance_diff=collision_distance-d_prox_collision;\n//\t\tcondassign(collision_cost,distance_diff,adouble(0),1e3*pow(distance_diff,2));\n\n\t\tadouble ca_distance_diff,ca_cost,ca_distance,ca_dprox;\n\t\tca_dprox=0.30;\n\t\tEigen::Matrix<adouble,3,1> pos_diff;\n\t\tfor (int i=0;i<3;++i)\n\t\t\tpos_diff[i]=states[i]-states[i+6];\n\n\t\tca_distance=pow(pos_diff.dot(pos_diff),0.5);\n\t\tca_distance_diff=ca_distance-ca_dprox;\n\t\tcondassign(ca_cost,ca_distance_diff,adouble(0),1e6*pow(ca_distance_diff,2));\n\n\t\tstate_type_drone2 goal_diff;\n\t\tgoal_diff=states-X_goal;\n\t\tinput_cost=0.4e2*inputs.dot(inputs);\n\t\tstate_cost=0.5*goal_diff.dot(goal_diff);\n\t\toutput=state_cost+input_cost+ca_cost;\n\t\treturn output;\n\t}\n\tadouble terminal_cost2(const state_type_drone2 & states,const input_type_drone2 & inputs,const state_type_drone2 & X_goal)\n\t{\n\t\tstate_type_drone2 diff;\n\t\tdiff=states-X_goal;\n\t\tadouble output;\n\t\toutput=200*diff.dot(diff);\n\t\treturn output;\n\t}\n}\n", "meta": {"hexsha": "9523ae58b0e34e28654e1780ae65ff27599038b5", "size": 17591, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros_ws/src/iconlab/src/iLQR_node/cost_structure.cpp", "max_stars_repo_name": "labicon/crazyswarm-labicon", "max_stars_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ros_ws/src/iconlab/src/iLQR_node/cost_structure.cpp", "max_issues_repo_name": "labicon/crazyswarm-labicon", "max_issues_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ros_ws/src/iconlab/src/iLQR_node/cost_structure.cpp", "max_forks_repo_name": "labicon/crazyswarm-labicon", "max_forks_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_forks_repo_licenses": ["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.8658743633, "max_line_length": 123, "alphanum_fraction": 0.7050764596, "num_tokens": 6417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6025074350318553}}
{"text": "#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/time.h>\n#include <stdlib.h>\n#include <math.h>\n#include <inttypes.h>\n#include <string.h>\n#include <adept_source.h>\n#include <adept.h>\nusing adept::adouble;\n\nstatic float tdiff(struct timeval *start, struct timeval *end) {\n  return (end->tv_sec-start->tv_sec) + 1e-6*(end->tv_usec-start->tv_usec);\n}\n\n#define BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\n#define BOOST_NO_EXCEPTIONS\n#include <iostream>\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/throw_exception.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n#include <stdio.h>\n\ndouble foobar(double t, uint64_t iters);\n\ntypedef boost::array< adouble , 1 > astate_type;\n\nvoid alorenz( const astate_type &x , astate_type &dxdt , adouble t )\n{\n    const double a = 1.2;\n    dxdt[0] = -a * x[0];\n}\n\nadouble afoobar(adouble t, uint64_t iters) {\n    astate_type x = { 1.0 }; // initial conditions\n\n    adouble start = 0.0;\n    adouble step = t/adouble(iters);\n    typedef controlled_runge_kutta< runge_kutta_dopri5< astate_type , typename astate_type::value_type , astate_type , adouble > > stepper_type;\n    //typedef euler< astate_type , typename astate_type::value_type , astate_type , adouble > stepper_type;\n    integrate_const( stepper_type(), alorenz , x , start , t, step );\n\n    //x[0] += -1.2 * step * x[0];\n\n    //printf(\"final result t=%f x(t)=%f, exp(-1.2* t)=%f\\n\", t, x[0], exp(- 1.2 * t));\n    return x[0];\n}\n\ndouble afoobar_and_gradient(double xin, double& xgrad, uint64_t iters) {\n    adept::Stack stack;\n    adouble x = xin;\n    stack.new_recording();\n    adouble y = afoobar(x, iters);\n    y.set_gradient(1.0);\n    stack.compute_adjoint();\n    xgrad = x.get_gradient();\n    return y.value();\n}\n\nvoid adept_sincos(double inp, uint64_t iters) {\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res = foobar(inp, iters);\n\n  gettimeofday(&end, NULL);\n  printf(\"Adept real %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  adept::Stack stack;\n // stack.new_recording();\n  adouble resa = afoobar(inp, iters);\n  double res = resa.value();\n\n  gettimeofday(&end, NULL);\n  printf(\"Adept forward %0.6f res=%f\\n\", tdiff(&start, &end), res);\n  }\n\n  {\n  struct timeval start, end;\n  gettimeofday(&start, NULL);\n\n  double res2 = 0;\n  afoobar_and_gradient(inp, res2, iters);\n\n  gettimeofday(&end, NULL);\n  printf(\"Adept combined %0.6f res'=%f\\n\", tdiff(&start, &end), res2);\n  }\n}\n", "meta": {"hexsha": "c0075e1bf159c9c6248f600370dbbf1a0385d895", "size": 2542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/benchmarks/ode/ode-adept.cpp", "max_stars_repo_name": "anandijain/Enzyme", "max_stars_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 674.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T17:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:18:11.000Z", "max_issues_repo_path": "enzyme/benchmarks/ode/ode-adept.cpp", "max_issues_repo_name": "anandijain/Enzyme", "max_issues_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2020-10-07T00:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T16:46:58.000Z", "max_forks_repo_path": "enzyme/benchmarks/ode/ode-adept.cpp", "max_forks_repo_name": "anandijain/Enzyme", "max_forks_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T14:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:51:07.000Z", "avg_line_length": 24.9215686275, "max_line_length": 144, "alphanum_fraction": 0.6730920535, "num_tokens": 765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424528443251, "lm_q2_score": 0.7122321720225278, "lm_q1q2_score": 0.6025074305953785}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_TENPOWER_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_TENPOWER_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/ten.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/any.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/is_odd.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/shift_right.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/detail/dispatch/meta/as_floating.hpp>\n#include <boost/mpl/equal_to.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF(tenpower_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::pack_<bd::int_<A0>, X>\n                             )\n   {\n      using result = bd::as_floating_t<A0>;\n      BOOST_FORCEINLINE result operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        result res = One<result>();\n        result base = Ten<result>();\n        A0 exp = bs::abs(a0);\n        while(any(exp))\n        {\n          //       res *= if_else(is_odd(exp), base, One<result>()); TO DO\n          res =  res * if_else(is_odd(exp), base, One<result>());\n          //  exp >>= 1; TODO\n          exp =  shift_right(exp, 1);\n          base = sqr(base);\n        }\n        return if_else(is_ltz(a0), bs::rec(res), res);\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD_IF(tenpower_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::pack_<bd::uint_<A0>, X>\n                             )\n   {\n      using result = bd::as_floating_t<A0>;\n      BOOST_FORCEINLINE result operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        result res = One<result>();\n        result base = Ten<result>();\n        A0 exp = a0;\n        while(any(exp))\n        {\n          res = res*if_else(is_odd(exp), base, One<result>()); // TODO\n//          res *= if_else(is_odd(exp), base, One<result>());\n          //  exp >>= 1; TODO\n          exp =  shift_right(exp, 1);\n          base = sqr(base);\n        }\n        return res;\n      }\n   };\n\n} } }\n\n\n#endif\n\n", "meta": {"hexsha": "0e83cd085d3329b5f5e59830b8c7969db1b0d9ce", "size": 3022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/tenpower.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/simd/function/tenpower.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/simd/function/tenpower.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": 33.5777777778, "max_line_length": 100, "alphanum_fraction": 0.5337524818, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6025074302300203}}
{"text": "// #include <stan/math.hpp>\n// #include <boost/math/tools/promotion.hpp>\n\n// using namespace stan::math;\n\nnamespace rosenbrock_model_namespace {\n\ntemplate <typename T0__>\nEigen::Matrix<stan::promote_args_t<T0__>, -1, 1>\nmy_rosenbrock(const Eigen::Matrix<T0__, -1, 1>& xy, std::ostream* pstream__)\n{\n    // throw std::logic_error(\"not implemented\");  // this should never be called\n    // typedef typename boost::math::tools::promote_args<T0__>::type T;\n    if (xy.size() > 2) {\n        throw std::logic_error(\"This function is implemented only for input of size 2.\");\n    }\n    using T = stan::return_type_t<T0__>;\n    T x = xy(0);\n    T y = xy(1);\n    T res = pow((1 - x), 2) + (100 * pow((y - pow(x, 2)), 2));\n    Eigen::Matrix<T, -1, 1> out(1);\n    out(0) = res;\n    return out;\n}\n\n} // rosenbrock_model_namespace\n", "meta": {"hexsha": "a4b7003001bd14751ba8c136a1390c1dc675c91f", "size": 817, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/rosenbrock/ext_ros.hpp", "max_stars_repo_name": "IvanYashchuk/cmdstan-petsc", "max_stars_repo_head_hexsha": "e351f818ecbc65ae8d609b1a440d5962ed9c2708", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/rosenbrock/ext_ros.hpp", "max_issues_repo_name": "IvanYashchuk/cmdstan-petsc", "max_issues_repo_head_hexsha": "e351f818ecbc65ae8d609b1a440d5962ed9c2708", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/rosenbrock/ext_ros.hpp", "max_forks_repo_name": "IvanYashchuk/cmdstan-petsc", "max_forks_repo_head_hexsha": "e351f818ecbc65ae8d609b1a440d5962ed9c2708", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-26T13:35:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T13:35:19.000Z", "avg_line_length": 30.2592592593, "max_line_length": 89, "alphanum_fraction": 0.6328029376, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6025063487601315}}
{"text": "// Copyright Nick Thompson, 2017\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or\n// copy at http://www.boost.org/LICENSE_1_0.txt).\n\n#include <iostream>\n#include <vector>\n#include <array>\n#include <cmath>\n#include <boost/math/interpolators/catmull_rom.hpp>\n#include <boost/math/constants/constants.hpp>\n\nusing std::sin;\nusing std::cos;\nusing boost::math::catmull_rom;\n\nint main()\n{\n    std::cout << \"This shows how to use Boost's Catmull-Rom spline to create an Archimedean spiral.\\n\";\n\n    // The Archimedean spiral is given by r = a*theta. We have set a = 1.\n    std::vector<std::array<double, 2>> spiral_points(500);\n    double theta_max = boost::math::constants::pi<double>();\n    for (size_t i = 0; i < spiral_points.size(); ++i)\n    {\n        double theta = ((double) i/ (double) spiral_points.size())*theta_max;\n        spiral_points[i] = {theta*cos(theta), theta*sin(theta)};\n    }\n\n    auto archimedean = catmull_rom<std::array<double,2>>(std::move(spiral_points));\n    double max_s = archimedean.max_parameter();\n    std::cout << \"Max s = \" << max_s << std::endl;\n    for (double s = 0; s < max_s; s += 0.01)\n    {\n        auto p = archimedean(s);\n        double x = p[0];\n        double y = p[1];\n        double r = sqrt(x*x + y*y);\n        double theta = atan2(y/r, x/r);\n        std::cout << \"r = \" << r << \", theta = \" << theta << \", r - theta = \" << r - theta << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "69a49707034b46529f8d056c053fe2c354cdc58b", "size": 1471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/catmull_rom_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/catmull_rom_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/catmull_rom_example.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 31.9782608696, "max_line_length": 104, "alphanum_fraction": 0.6159075459, "num_tokens": 422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.6025063443856609}}
{"text": "// ----------------------------------------------------------------------------\n// tropter: test_double_pendulum.cpp\n// ----------------------------------------------------------------------------\n// Copyright (c) 2017 tropter authors\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n// not use this file except in compliance with the License. You may obtain a\n// copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ----------------------------------------------------------------------------\n\n#define CATCH_CONFIG_MAIN\n#include <catch.hpp>\n#include \"testing_optimalcontrol.h\"\n\n#include <tropter/tropter.h>\n#include <Eigen/LU>\n\nusing Eigen::Ref;\nusing Eigen::VectorXd;\nusing Eigen::RowVectorXd;\nusing Eigen::Vector2d;\nusing Eigen::MatrixXd;\nusing Eigen::Matrix2d;\n\nusing namespace tropter;\n\nconstexpr double PI = 3.14159;\n\n/// This class template defines the dynamics of a double pendulum. To create\n/// an actual optimal control problem, one must derive from this class\n/// template and define boundary conditions, cost terms, etc.\ntemplate<typename T>\nclass DoublePendulum : public tropter::Problem<T> {\npublic:\n    constexpr static const double g = 9.81;\n    double L0 = 1;\n    double L1 = 1;\n    double m0 = 1;\n    double m1 = 1;\n\n    void calc_differential_algebraic_equations(\n            const Input<T>& in, Output<T> out) const override final {\n        const auto& x = in.states;\n        const auto& tau = in.controls;\n        const auto& q0 = x[0];\n        const auto& q1 = x[1];\n        const auto& u0 = x[2];\n        const auto& u1 = x[3];\n        const auto& L0 = this->L0;\n        const auto& L1 = this->L1;\n        const auto& m0 = this->m0;\n        const auto& m1 = this->m1;\n        out.dynamics[0] = u0;\n        out.dynamics[1] = u1;\n\n        const T z0 = m1 * L0 * L1 * cos(q1);\n        const T M01 = m1 * L1*L1 + z0;\n        Matrix2<T> M;\n        M << m0 * L0*L0 + m1 * (L0*L0 + L1*L1) + 2*z0,    M01,\n             M01,                                         m1 * L1*L1;\n        Vector2<T> V(-u1 * (2 * u0 + u1),\n                     u0 * u0);\n        V *= m1*L0*L1*sin(q1);\n        Vector2<T> G(g * ((m0 + m1) * L0 * cos(q0) + m1 * L1 * cos(q0 + q1)),\n                     g * m1 * L1 * cos(q0 + q1));\n\n        //Vector2<T> drag(-10 * u0, -10 * u1);\n        // TODO xdot.tail<2>() =\n        out.dynamics.tail(2) = M.inverse() * (tau - (V + G));\n    }\n};\n\n/// The optimal solution for a double pendulum to swing from horizontal to\n/// vertical (up) in minimum time is for the links to fall down first and\n/// for the first link to rotate clockwise. The second link flips around +360\n/// degrees to reach the Cartesian coordinates (0, 2).\ntemplate<typename T>\nclass DoublePendulumSwingUpMinTime : public DoublePendulum<T> {\npublic:\n    DoublePendulumSwingUpMinTime()\n    {\n        this->set_time(0, {0, 5}); //{0, 5});\n        // TODO fix allowing final bounds to be unconstrained.\n        this->add_state(\"q0\", {-10, 10}, {0});\n        this->add_state(\"q1\", {-10, 10}, {0});\n        this->add_state(\"u0\", {-50, 50}, {0}, {0});\n        this->add_state(\"u1\", {-50, 50}, {0}, {0});\n        this->add_control(\"tau0\", {-50, 50});\n        this->add_control(\"tau1\", {-50, 50});\n        this->add_cost(\"target\", 0);\n    }\n    void calc_cost(\n            int, const CostInput<T>& in, T& cost) const override {\n        // TODO a final state constraint probably makes more sense.\n        const auto& q0 = in.final_states[0];\n        const auto& q1 = in.final_states[1];\n        const auto& L0 = this->L0;\n        const auto& L1 = this->L1;\n        Vector2<T> actual_location(L0 * cos(q0) + L1 * cos(q0 + q1),\n                L0 * sin(q0) + L1 * sin(q0 + q1));\n        const Vector2<T> desired_location(0, 2);\n        cost = 1000.0 * (actual_location - desired_location).squaredNorm() +\n                0.001 * in.final_time;\n    }\n\n    static void run_test(std::string solver, std::string hessian_approx,\n            std::string transcription, int N = 100) {\n        auto ocp = std::make_shared<DoublePendulumSwingUpMinTime<T>>();\n        DirectCollocationSolver<T> dircol(ocp, transcription, solver, N);\n        std::string jacobian_approx;\n        if (hessian_approx == \"exact\") {\n            jacobian_approx = hessian_approx;\n        } else {\n            jacobian_approx = \"finite-difference-values\";\n        }\n        dircol.get_opt_solver().set_jacobian_approximation(jacobian_approx);\n        dircol.get_opt_solver().set_hessian_approximation(hessian_approx);\n        dircol.get_opt_solver().set_sparsity_detection(\"random\");\n        tropter::Iterate guess;\n        const int Nguess = 2;\n        guess.time.setLinSpaced(Nguess, 0, 1);\n        // Give a hint.\n        ocp->set_state_guess(guess, \"q0\",\n                Eigen::RowVectorXd::LinSpaced(Nguess, 0, -3./2.*PI));\n        ocp->set_state_guess(guess, \"q1\",\n                Eigen::RowVectorXd::LinSpaced(Nguess, 0, 2*PI));\n        ocp->set_state_guess(guess, \"u0\", Eigen::RowVectorXd::Zero(Nguess));\n        ocp->set_state_guess(guess, \"u1\", Eigen::RowVectorXd::Zero(Nguess));\n        ocp->set_control_guess(guess, \"tau0\",\n                Eigen::RowVectorXd::LinSpaced(Nguess, -50, 50));\n        ocp->set_control_guess(guess, \"tau1\",\n                Eigen::RowVectorXd::LinSpaced(Nguess, 50, -50));\n        Solution solution = dircol.solve(guess);\n        solution.write(\"double_pendulum_horizontal_to_vertical_solution.csv\");\n        // Check the final states.\n        INFO(solution.states);\n        TROPTER_REQUIRE_EIGEN(solution.states.rightCols<1>(),\n                Eigen::Vector4d(-3./2.*PI, 2*PI, 0, 0), 1e-3);\n        // Check the controls, which are bang-bang.\n        testAlmostEqual(solution.controls.topLeftCorner<1, 40>(),\n                Eigen::RowVectorXd::Constant(40, -50), 1e-2);\n        testAlmostEqual(solution.controls.topRightCorner<1, 40>(),\n                Eigen::RowVectorXd::Constant(40,  50), 1e-2);\n        testAlmostEqual(solution.controls.bottomLeftCorner<1, 15>(),\n                Eigen::RowVectorXd::Constant(15,  50), 1e-2);\n        testAlmostEqual(solution.controls.bottomRightCorner<1, 15>(),\n                Eigen::RowVectorXd::Constant(15, -50), 1e-2);\n    }\n};\n\nTEST_CASE(\"Double pendulum swing up in minimum time.\", \n          \"[trapezoidal][hermite-simpson]\")\n{\n    SECTION(\"IPOPT\") {\n        SECTION(\"Finite differences, limited-memory Hessian, trapezoidal\") {\n            DoublePendulumSwingUpMinTime<double>::run_test(\"ipopt\",\n                    \"limited-memory\", \"trapezoidal\");\n        }\n        // This test passes but it's just really slow:\n        //SECTION(\"Finite differences, exact Hessian, trapezoidal\") {\n        //    DoublePendulumSwingUpMinTime<double>::run_test(\"ipopt\",\n        //            \"exact\", \"trapezoidal\");\n        //}\n        SECTION(\"ADOL-C, trapezoidal\") {\n            DoublePendulumSwingUpMinTime<adouble>::run_test(\"ipopt\",\n                    \"limited-memory\", \"trapezoidal\");\n        }\n        SECTION(\"Finite differences, limited-memory Hessian, hermite-simpson\") {\n            DoublePendulumSwingUpMinTime<double>::run_test(\"ipopt\",\n                \"limited-memory\", \"hermite-simpson\", 50);\n        }\n        //SECTION(\"Finite differences, exact Hessian, hermite-simpson\") {\n        //    DoublePendulumSwingUpMinTime<double>::run_test(\"ipopt\",\n        //            \"exact\", \"hermite-simpson\");\n        //}\n        SECTION(\"ADOL-C, hermite-simpson\") {\n            DoublePendulumSwingUpMinTime<adouble>::run_test(\"ipopt\",\n                \"limited-memory\", \"hermite-simpson\", 50);\n        }\n    }\n    // Does not give desired answer (not fully bang-bang controls):\n    // #if defined(TROPTER_WITH_SNOPT)\n    // SECTION(\"SNOPT\") {\n    //     SECTION(\"ADOL-C, trapezoidal\") {\n    //         DoublePendulumSwingUpMinTime<adouble>::run_test(\"snopt\",\n    //                 \"limited-memory\", \"trapezoidal\");\n    //     }\n    //     SECTION(\"ADOL-C, hermite-simpson\") {\n    //         DoublePendulumSwingUpMinTime<adouble>::run_test(\"snopt\",\n    //                 \"limited-memory\", \"hermite-simpson\");\n    //     }\n    // }\n    // #endif\n}\n\n\ntemplate<typename T>\nclass DoublePendulumCoordinateTracking : public DoublePendulum<T> {\npublic:\n    DoublePendulumCoordinateTracking()\n    {\n        this->set_time(0, 1);\n        // TODO fix allowing final bounds to be unconstrained.\n        this->add_state(\"q0\", {-10, 10});\n        this->add_state(\"q1\", {-10, 10});\n        this->add_state(\"u0\", {-50, 50});\n        this->add_state(\"u1\", {-50, 50});\n        this->add_control(\"tau0\", {-100, 100});\n        this->add_control(\"tau1\", {-100, 100});\n        this->add_cost(\"tracking\", 1);\n    }\n    void calc_cost(\n            int, const CostInput<T>& in, T& cost) const override {\n        cost = in.integral;\n    }\n    void calc_cost_integrand(\n            int, const Input<T>& in, T& integrand) const override {\n\n        const auto& time = in.time;\n        const auto& states = in.states;\n\n        VectorX<T> desired(2);\n        desired << (time / 1.0) * 0.50 * PI,\n                (time / 1.0) * 0.25 * PI;\n        integrand = (states.head(2) - desired).squaredNorm();\n    }\n\n    static Solution run_test(const std::string& solver,\n            const std::string& hessian_approx, \n            const std::string& transcription, int N = 50) {\n        auto ocp = std::make_shared<DoublePendulumCoordinateTracking<T>>();\n        DirectCollocationSolver<T> dircol(ocp, transcription, solver, N);\n        // Using an exact Hessian seems really important for this problem\n        // (solves in only 20 iterations). Even a limited-memory problem started\n        // from the solution using an exact Hessian does not converge.\n        std::string jacobian_approx;\n        if (hessian_approx == \"exact\") {\n            jacobian_approx = hessian_approx;\n        } else {\n            jacobian_approx = \"finite-difference-values\";\n        }\n        dircol.get_opt_solver().set_jacobian_approximation(jacobian_approx);\n        dircol.get_opt_solver().set_hessian_approximation(hessian_approx);\n        dircol.get_opt_solver().set_sparsity_detection(\"random\");\n        Solution solution = dircol.solve();\n        //dircol.print_constraint_values(solution);\n        solution.write(\"double_pendulum_coordinate_tracking.csv\");\n\n        TROPTER_REQUIRE_EIGEN(solution.states.row(0),\n                Eigen::RowVectorXd::LinSpaced(solution.time.size(), 0, \n                    0.50 * PI), 1e-3);\n        TROPTER_REQUIRE_EIGEN(solution.states.row(1),\n                Eigen::RowVectorXd::LinSpaced(solution.time.size(), 0, \n                    0.25 * PI), 1e-3);\n\n        return solution;\n    }\n};\n\n/// This class template defines the dynamics of a double pendulum using an\n/// implicit formulation. To create an actual optimal control problem, one must\n/// derive from this class template and define boundary conditions, cost terms,\n/// etc.\ntemplate<typename T>\nclass ImplicitDoublePendulum : public tropter::Problem<T> {\npublic:\n    constexpr static const double g = 9.81;\n    double L0 = 1;\n    double L1 = 1;\n    double m0 = 1;\n    double m1 = 1;\n    void calc_differential_algebraic_equations(\n            const Input<T>& in, Output<T> out) const override final {\n        const auto& x = in.states;\n        const auto& udot = in.controls.template head<2>();\n        const auto& tau = in.controls.template tail<2>();\n        const auto& q0 = x[0];\n        const auto& q1 = x[1];\n        const auto& u0 = x[2];\n        const auto& u1 = x[3];\n        const auto& L0 = this->L0;\n        const auto& L1 = this->L1;\n        const auto& m0 = this->m0;\n        const auto& m1 = this->m1;\n        out.dynamics[0] = u0;\n        out.dynamics[1] = u1;\n        out.dynamics[2] = udot[0];\n        out.dynamics[3] = udot[1];\n\n        if (out.path.size() != 0) {\n            const T z0 = m1 * L0 * L1 * cos(q1);\n            const T M01 = m1 * L1*L1 + z0;\n            Matrix2<T> M;\n            M << m0 * L0*L0 + m1 * (L0*L0 + L1*L1) + 2*z0,    M01,\n                    M01,                                         m1 * L1*L1;\n            Vector2<T> V(-u1 * (2 * u0 + u1),\n                         u0 * u0);\n            V *= m1*L0*L1*sin(q1);\n            Vector2<T> G(g * ((m0 + m1) * L0 * cos(q0) + m1 * L1 * cos(q0 + q1)),\n                         g * m1 * L1 * cos(q0 + q1));\n\n            out.path = M * udot + V + G - tau;\n        }\n    }\n};\n\ntemplate<typename T>\nclass ImplicitDoublePendulumCoordinateTracking : public\n                                                 ImplicitDoublePendulum<T> {\npublic:\n    ImplicitDoublePendulumCoordinateTracking() {\n        this->set_time(0, 1);\n        // TODO fix allowing final bounds to be unconstrained.\n        this->add_state(\"q0\", {-10, 10});\n        this->add_state(\"q1\", {-10, 10});\n        this->add_state(\"u0\", {-50, 50});\n        this->add_state(\"u1\", {-50, 50});\n        this->add_control(\"udot0\", {-100, 100});\n        this->add_control(\"udot1\", {-100, 100});\n        this->add_control(\"tau0\", {-100, 100});\n        this->add_control(\"tau1\", {-100, 100});\n        this->add_cost(\"tracking\", 1);\n        this->add_path_constraint(\"u0\", 0);\n        this->add_path_constraint(\"u1\", 0);\n    }\n    void calc_cost(\n            int, const CostInput<T>& in, T& cost) const override {\n        cost = in.integral;\n    }\n    void calc_cost_integrand(\n            int, const Input<T>& in, T& integrand) const override {\n\n        const auto& time = in.time;\n        const auto& states = in.states;\n\n        VectorX<T> desired(2);\n        desired << (time / 1.0) * 0.50 * PI,\n                   (time / 1.0) * 0.25 * PI;\n        integrand = (states.template head<2>() - desired).squaredNorm();\n    }\n    static Solution run_test(const std::string& solver,\n            const std::string& hessian_approx, \n            const std::string& transcription, int N = 50) {\n        auto ocp =\n                std::make_shared<ImplicitDoublePendulumCoordinateTracking<T>>();\n        DirectCollocationSolver<T> dircol(ocp, transcription, solver, N);\n        std::string jacobian_approx;\n        if (hessian_approx == \"exact\") {\n            jacobian_approx = hessian_approx;\n        } else {\n            jacobian_approx = \"finite-difference-values\";\n        }\n        dircol.get_opt_solver().set_jacobian_approximation(jacobian_approx);\n        dircol.get_opt_solver().set_hessian_approximation(hessian_approx);\n        dircol.get_opt_solver().set_sparsity_detection(\"random\");\n        dircol.get_opt_solver().set_advanced_option_string\n                (\"print_timing_statistics\", \"yes\");\n        Solution solution = dircol.solve();\n        // dircol.print_constraint_values(solution);\n        solution.write(\"implicit_double_pendulum_coordinate_tracking.csv\");\n\n        TROPTER_REQUIRE_EIGEN(solution.states.row(0),\n                Eigen::RowVectorXd::LinSpaced(solution.time.size(), 0, \n                    0.50 * PI), 1e-3);\n        TROPTER_REQUIRE_EIGEN(solution.states.row(1),\n                Eigen::RowVectorXd::LinSpaced(solution.time.size(), 0, \n                    0.25 * PI), 1e-3);\n\n        return solution;\n    }\n};\n\nTEST_CASE(\"Double pendulum coordinate tracking\",\n        \"[trapezoidal][hermite-simpson][implicitdynamics]\")\n{\n    SECTION(\"IPOPT, trapezoidal\") {\n        // Make sure the solutions from the implicit and explicit\n        // formulations are similar.\n\n        // The explicit solution takes 20 iterations whereas the implicit\n        // solution takes 25 iterations.\n        const auto explicit_solution =\n                DoublePendulumCoordinateTracking<adouble>::\n                run_test(\"ipopt\", \"exact\", \"trapezoidal\");\n\n        const auto implicit_solution =\n                ImplicitDoublePendulumCoordinateTracking<adouble>::\n                run_test(\"ipopt\", \"exact\", \"trapezoidal\");\n\n        TROPTER_REQUIRE_EIGEN(explicit_solution.time,\n                implicit_solution.time, 1e-10);\n        // q0 and q1\n        TROPTER_REQUIRE_EIGEN(explicit_solution.states.bottomRows(2),\n                implicit_solution.states.bottomRows(2), 1e-2);\n        // u0 and u1\n        TROPTER_REQUIRE_EIGEN(explicit_solution.states.bottomRows(2),\n                implicit_solution.states.bottomRows(2), 1e-2);\n        // tau0 and tau1\n        // The controls have the same shape but have a pretty large error\n        // between them.\n        // The peak magnitude of the torques is about 10-30 N-m, so a tolerance\n        // of 5.0 N-m means the shape of the torques is preserved.\n        CAPTURE(explicit_solution.controls);\n        CAPTURE(implicit_solution.controls.bottomRows(2));\n        TROPTER_REQUIRE_EIGEN_ABS(explicit_solution.controls,\n                implicit_solution.controls.bottomRows(2), 5.0);\n\n\n        // Finite differences.\n        // -------------------\n        // Check that finite differences are correct.\n        OCPDerivativesComparison<DoublePendulumCoordinateTracking> c;\n        c.findiff_hessian_step_size = 1e-5;\n        c.gradient_error_tolerance = 1e-5;\n        c.jacobian_error_tolerance = 1e-5;\n        c.hessian_error_tolerance = 1e-2;\n        c.compare();\n\n        OCPDerivativesComparison<ImplicitDoublePendulumCoordinateTracking> ci;\n        ci.findiff_hessian_step_size = 1e-5;\n        ci.gradient_error_tolerance = 1e-5;\n        ci.jacobian_error_tolerance = 1e-5;\n        ci.hessian_error_tolerance = 1e-2;\n        ci.compare();\n\n        DoublePendulumCoordinateTracking<double>:: run_test(\"ipopt\", \"exact\",\n            \"trapezoidal\");\n        ImplicitDoublePendulumCoordinateTracking<double>::\n        run_test(\"ipopt\", \"exact\", \"trapezoidal\");\n\n        // The following do not converge:\n        // EXIT: Maximum number of iterations exceeded.\n        // DoublePendulumCoordinateTracking<adouble>::\n        // run_test(\"ipopt\", \"limited-memory\");\n        // EXIT: Solved to Acceptable Level, \"Restoration phase is called at\n        // almost feasible point, but acceptable point from iteration 810 could\n        // be restored.\" After 812 iterations. But solution is pretty wrong.\n        // DoublePendulumCoordinateTracking<double>::\n        // run_test(\"ipopt\", \"limited-memory\");\n        // EXIT: Maximum number of iterations exceeded.\n        // ImplicitDoublePendulumCoordinateTracking<adouble>::\n        // run_test(\"ipopt\", \"limited-memory\");\n        // EXIT: Restoration failed after 235 iterations.\n        // ImplicitDoublePendulumCoordinateTracking<double>::\n        // run_test(\"ipopt\", \"limited-memory\");\n\n    }\n    SECTION(\"IPOPT, hermite-simpson\") {\n        // Make sure the solutions from the implicit and explicit\n        // formulations are similar.\n\n        // The explicit solution takes 20 iterations whereas the implicit\n        // solution takes 25 iterations.\n        const auto explicit_solution =\n            DoublePendulumCoordinateTracking<adouble>::\n            run_test(\"ipopt\", \"exact\", \"hermite-simpson\", 25);\n\n        const auto implicit_solution =\n            ImplicitDoublePendulumCoordinateTracking<adouble>::\n            run_test(\"ipopt\", \"exact\", \"hermite-simpson\", 25);\n\n        TROPTER_REQUIRE_EIGEN(explicit_solution.time,\n            implicit_solution.time, 1e-10);\n        // q0 and q1\n        TROPTER_REQUIRE_EIGEN(explicit_solution.states.bottomRows(2),\n            implicit_solution.states.bottomRows(2), 1e-2);\n        // u0 and u1\n        TROPTER_REQUIRE_EIGEN(explicit_solution.states.bottomRows(2),\n            implicit_solution.states.bottomRows(2), 1e-2);\n        // tau0 and tau1\n        CAPTURE(explicit_solution.controls);\n        CAPTURE(implicit_solution.controls.bottomRows(2));\n        // TODO this fails since control become zero at the midpoint for \n        // Hermite-Simpson transcription.\n        //TROPTER_REQUIRE_EIGEN_ABS(explicit_solution.controls,\n        //    implicit_solution.controls.bottomRows(2), 5.0);\n\n        DoublePendulumCoordinateTracking<double>::run_test(\"ipopt\", \"exact\",\n            \"hermite-simpson\", 25);\n        ImplicitDoublePendulumCoordinateTracking<double>::\n            run_test(\"ipopt\", \"exact\", \"hermite-simpson\", 25);\n    }\n    /*\n    #if defined(TROPTER_WITH_SNOPT)\n    SECTION(\"SNOPT\") {\n        // TODO SNOPT will get the correct solution if the initial guess is the\n        // solution from IPOPT, but otherwise, the solution is off (u0/u1\n        // dynamics violation is 1e-7?).\n        //ImplicitDoublePendulumCoordinateTracking<adouble>::run_test(\"snopt\",\n        //        \"limited-memory\");\n        const auto explicit_solution =\n                DoublePendulumCoordinateTracking<adouble>::run_test(\"ipopt\");\n        auto ocp = std::make_shared<DoublePendulumCoordinateTracking<adouble>>();\n        tropter::Iterate guess;\n\n        const int N = 100;\n        guess.time.setLinSpaced(N, 0, 1);\n        ocp->set_state_guess(guess, \"q0\",\n                Eigen::RowVectorXd::LinSpaced(N, 0, 0.5*PI));\n        ocp->set_state_guess(guess, \"q1\",\n                Eigen::RowVectorXd::LinSpaced(N, 0, 0.25*PI));\n        ocp->set_state_guess(guess, \"u0\", Eigen::RowVectorXd::Zero(N));\n        ocp->set_state_guess(guess, \"u1\", Eigen::RowVectorXd::Zero(N));\n        ocp->set_control_guess(guess, \"tau0\", Eigen::RowVectorXd::Zero(N));\n        ocp->set_control_guess(guess, \"tau1\", Eigen::RowVectorXd::Zero(N));\n        DirectCollocationSolver<adouble> dircol(ocp, \"trapezoidal\", \"snopt\", N);\n        Solution solution = dircol.solve(guess);\n        dircol.print_constraint_values(solution);\n        solution.write(\"double_pendulum_coordinate_tracking_snopt.csv\");\n    }\n    #endif\n    */\n}\n\n// TODO include acceleration and deceleration.\n", "meta": {"hexsha": "32f0cc2e5604297a3a532c9ad23e11d038597167", "size": 21892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Vendors/tropter/tests/test_double_pendulum.cpp", "max_stars_repo_name": "MariaHammer/opensim-core_HaeufleMuscle", "max_stars_repo_head_hexsha": "96257e9449d9ac430bbb54e56cd13aaebeee1242", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 532.0, "max_stars_repo_stars_event_min_datetime": "2015-03-13T18:51:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T08:08:29.000Z", "max_issues_repo_path": "Vendors/tropter/tests/test_double_pendulum.cpp", "max_issues_repo_name": "MariaHammer/opensim-core_HaeufleMuscle", "max_issues_repo_head_hexsha": "96257e9449d9ac430bbb54e56cd13aaebeee1242", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2701.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T21:33:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T07:13:41.000Z", "max_forks_repo_path": "Vendors/tropter/tests/test_double_pendulum.cpp", "max_forks_repo_name": "MariaHammer/opensim-core_HaeufleMuscle", "max_forks_repo_head_hexsha": "96257e9449d9ac430bbb54e56cd13aaebeee1242", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 271.0, "max_forks_repo_forks_event_min_datetime": "2015-02-16T23:25:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T20:12:17.000Z", "avg_line_length": 41.938697318, "max_line_length": 81, "alphanum_fraction": 0.5971587795, "num_tokens": 5684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430645886583, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6024709027708333}}
{"text": "/*\n * GraphBLAS Template Library (GBTL), Version 3.0\n *\n * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and\n * Authors.\n *\n * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF\n * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE\n * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF\n * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR\n * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE\n * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR\n * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,\n * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS\n * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED\n * RIGHTS.\n *\n * Released under a BSD-style license, please see LICENSE file or contact\n * permission@sei.cmu.edu for full terms.\n *\n * [DISTRIBUTION STATEMENT A] This material has been approved for public release\n * and unlimited distribution.  Please see Copyright notice for non-US\n * Government use and distribution.\n *\n * This Software includes and/or makes use of the following Third-Party Software\n * subject to its own license:\n *\n * 1. Boost Unit Test Framework\n * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)\n * Copyright 2001 Boost software license, Gennadiy Rozental.\n *\n * DM20-0442\n */\n\n#include <iostream>\n\n#include <algorithms/mst.hpp>\n#include <graphblas/graphblas.hpp>\n\nusing namespace grb;\nusing namespace algorithms;\n\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE mst_test_suite\n\n#include <boost/test/included/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(mst_test_with_weight_one)\n{\n    IndexType const NUM_NODES = 6;\n    IndexArrayType i_m1 = {0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3,\n                           4, 4, 4, 4, 4, 5, 5};\n    IndexArrayType j_m1 = {1, 3, 4, 0, 3, 4, 4, 5, 0, 1, 4,\n                           0, 1, 2, 3, 5, 2, 4};\n    std::vector<double> v_m1(i_m1.size(), 1);\n    Matrix<double> m1(NUM_NODES, NUM_NODES);\n    m1.build(i_m1, j_m1, v_m1);\n    grb::print_matrix(std::cout, m1, \"GRAPH***\");\n\n    std::vector<IndexType> ans = {99, 0, 4, 1, 3, 2};\n    grb::Vector<IndexType> answer(ans, 99);\n\n    grb::Vector<grb::IndexType> parents(NUM_NODES);\n    auto result = mst(m1, parents);\n\n    BOOST_CHECK_EQUAL(result, NUM_NODES - 1.0);\n    BOOST_CHECK_EQUAL(parents, answer);\n\n    std::cout << \"MST weight = \" << result << std::endl;\n    grb::print_vector(std::cout, parents, \"MST parent list\");\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(mst_test_with_weight_various)\n{\n    IndexType const NUM_NODES = 6;\n    IndexArrayType i_m1 =      {0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3,\n                                4, 4, 4, 4, 4, 5, 5};\n    IndexArrayType j_m1 =      {1, 3, 4, 0, 3, 4, 4, 5, 0, 1, 4,\n                                0, 1, 2, 3, 5, 2, 4};\n    std::vector<double> v_m1 = {2, 2, 1, 2, 2, 1, 1, 2, 2, 2, 1,\n                                1, 1, 1, 1, 1, 2, 1};\n    Matrix<double> m1(NUM_NODES, NUM_NODES);\n    m1.build(i_m1, j_m1, v_m1);\n    grb::print_matrix(std::cout, m1, \"GRAPH***\");\n\n    std::vector<IndexType> ans = {99, 4, 4, 4, 0, 4};\n    grb::Vector<IndexType> answer(ans, 99);\n\n    grb::Vector<grb::IndexType> parents(NUM_NODES);\n    auto result = mst(m1, parents);\n\n    BOOST_CHECK_EQUAL(result, NUM_NODES - 1.0);\n    BOOST_CHECK_EQUAL(parents, answer);\n\n    std::cout << \"MST weight = \" << result << std::endl;\n    grb::print_vector(std::cout, parents, \"MST parent list\");\n}\n\n//****************************************************************************\nBOOST_AUTO_TEST_CASE(mst_test_with_weights)\n{\n    //                   m1({{0, 4, 0, 0, 0, 0, 0, 8, 0},\n    //                       {4, 0, 8, 0, 0, 0, 0,11, 0},\n    //                       {0, 8, 0, 7, 0, 4, 0, 0, 2},\n    //                       {0, 0, 7, 0, 9,14, 0, 0, 0},\n    //                       {0, 0, 0, 9, 0,10, 0, 0, 0},\n    //                       {0, 0, 4,14,10, 0, 2, 0, 0},\n    //                       {0, 0, 0, 0, 0, 2, 0, 1, 6},\n    //                       {8,11, 0, 0, 0, 0, 1, 0, 7},\n    //                       {0, 0, 2, 0, 0, 0, 6, 7, 0}});\n    IndexType const NUM_NODES = 9;\n    IndexArrayType i_m1 = {0, 0, 1, 1, 1, 2, 2, 2, 2,\n                           3, 3, 3, 4, 4, 5, 5, 5, 5,\n                           6, 6, 6, 7, 7, 7, 7, 8, 8, 8};\n    IndexArrayType j_m1 = {1, 7, 0, 2, 7, 1, 3, 5, 8,\n                           2, 4, 5, 3, 5, 2, 3, 4, 6,\n                           5, 7, 8, 0, 1, 6, 8, 2, 6, 7};\n    std::vector<double> v_m1 = {4, 8, 4, 8,11, 8, 7, 4, 2,\n                                7, 9,14, 9,10, 4,14,10, 2,\n                                2, 1, 6, 8,11, 1, 7, 2, 6, 7};\n    Matrix<double> m1(NUM_NODES, NUM_NODES);\n    m1.build(i_m1, j_m1, v_m1);\n    grb::print_matrix(std::cout, m1, \"GRAPH***\");\n\n    std::vector<IndexType> ans = {99, 0, 1, 2, 3, 2, 5, 6, 2};\n    grb::Vector<IndexType> answer(ans, 99);\n\n    grb::Vector<IndexType> parents(NUM_NODES);\n    auto result = mst(m1, parents);\n\n    BOOST_CHECK_EQUAL(result, 37);\n    BOOST_CHECK_EQUAL(parents, answer);\n\n    //BOOST_CHECK_EQUAL(result, correct_weight);\n    std::cout << \"MST weight = \" << result << std::endl;\n    grb::print_vector(std::cout, parents, \"MST parent list\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "3b2c0f0e598f2fdf09a6260c049da61e8fa9abf1", "size": 5560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_mst.cpp", "max_stars_repo_name": "KIwabuchi/gbtl", "max_stars_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 112.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T05:54:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T05:56:16.000Z", "max_issues_repo_path": "src/test/test_mst.cpp", "max_issues_repo_name": "KIwabuchi/gbtl", "max_issues_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2016-03-22T19:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-07T15:40:18.000Z", "max_forks_repo_path": "src/test/test_mst.cpp", "max_forks_repo_name": "KIwabuchi/gbtl", "max_forks_repo_head_hexsha": "62c6b1e3262f3623359e793edb5ec4fa7bb471f0", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T05:54:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T03:33:20.000Z", "avg_line_length": 38.6111111111, "max_line_length": 80, "alphanum_fraction": 0.55, "num_tokens": 1929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234878, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6024709016471328}}
{"text": "/*! main.cpp : Defines the entry point for the console application.\r\n\tNote: The given .csv files are not formatted consistently. The .csv parsers below are \r\n\tdesigned to handle the inconsistencies present in the files in a somewhat \r\n\tgeneral manner by removing extra characters and white space.\r\n\tNote: Some of the values in the csv file are set to \"-\", which is read as zero by c++, \r\n\tso we do not account for this particular inconsistency, as we intend that any of these to be zero regardless.\r\n*/\r\n#include <string>\r\n#include <vector>\r\n#include <numeric>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n\r\n#include \"csv.h\"\r\n#include \"issuers.h\"\r\n#include \"portfolio.h\"\r\n#include \"price_matrix.h\"\r\n#include \"yields.h\"\r\n#include \"matrix.h\"\r\n#include \"transition_matrix.h\"\r\n#include \"scenario.h\"\r\n#include \"monte.h\"\r\n#include \"industries.h\"\r\n#include \"rand.h\"\r\n\r\nusing namespace std;\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\ttry\r\n\t{\r\n\t\t//Random number generator\r\n\t\t//UniformRandomNumberGenerator unirand(0, 1);\r\n\r\n\t\t// Response for Part B, Step 1) \r\n\t\t// Read in all the .csv files and create transition and correlation matrices.\r\n\t\tIssuerData issuerData;\r\n\t\tIndustryData industryData;\r\n\t\tPortfolioData portfolioData;\r\n\t\tYieldData yieldData;\r\n\t\tMatrix correlationMatrix(\"correlation_matrix_for_project.csv\", 1);\r\n\t\tTransitionMatrix transitionMatrix;\r\n\r\n\t\t// Response for Part B, Step 2)\r\n\t\t// Get reported and theoretical portfolio values.\r\n\t\tcout << \"The initial reported portfolio value is \" << portfolioData.getReportedValue() << endl;\r\n\t\tcout << \"The initial theoretical portfolio value is \" << portfolioData.getTheorValue() << endl;\r\n\r\n\t\t//Calculate prices for each portfolio based on yields\r\n\t\tPriceMatrix priceMatrix(portfolioData, yieldData);\r\n\r\n\t\t// Response for Part B, Step 4)\r\n\t\t// Set N generate N scenarios for the ratings of the companies.\r\n\t\tint N = 2000;\r\n\t\tNormalRandomNumberGenerator nrand(0,1);\r\n\t\tMonte monteCarlo(N, nrand, issuerData, industryData, transitionMatrix);\r\n\t\r\n\t\t// Response for Part B, Step 5)\r\n\t\t// Go through the N scenarios and compute the value of the portfolio,\r\n\t\t// and change in value of the portfolio in each scenario.\r\n\t\tvector<double> portfolioValues;\r\n\t\tvector<double> changeInValues;\r\n\t\tdouble changeInValueTotal = 0;\r\n\t\tfor (size_t i = 0, n1 = monteCarlo.scenarios.size(); i < n1; i++)\r\n\t\t{\r\n\t\t\tdouble portfolioValue = 0;\r\n\t\t\tScenario& scenario = monteCarlo.scenarios.at(i);\r\n\t\t\tfor (size_t j = 0, n2 = portfolioData.size(); j < n2; j++)\r\n\t\t\t{\r\n\t\t\t\tPortfolioEntry& portfolio = portfolioData.at(j);\r\n\t\t\t\tScenarioEntry* scenarioEntry = scenario.getByName(portfolio.name);\r\n\t\t\t\tif (!scenarioEntry)\r\n\t\t\t\t\tthrow runtime_error(\"No known scenario entry for \\\"\" + portfolio.name + \"\\\"\");\r\n\t\t\t\tportfolioValue = portfolioValue + ((priceMatrix[j][scenarioEntry->rating]*portfolio.notional) * ((double)1/100));\r\n\t\t\t}\r\n\t\t\tportfolioValues.push_back(portfolioValue);\r\n\t\t\tdouble changeInValue = portfolioValue - portfolioData.getTheorValue();\r\n\t\t\tchangeInValues.push_back(changeInValue);\r\n\t\t\tchangeInValueTotal = changeInValueTotal + changeInValue;\r\n\t\t}\r\n\r\n\t\t// Response for Part B, Step 6)\r\n\t\t// Calculate statistics for the change in portfolio value\r\n\t\tdouble meanChangeInValue = changeInValueTotal / (double)changeInValues.size();\r\n\t\tdouble sq_sum = inner_product(changeInValues.begin(), changeInValues.end(), changeInValues.begin(), 0.0);\r\n\t\t// NOTE: This calculation of standard deviation may not work for small values. \r\n\t\t// TO DO: Fix this so a standard deviation of 0 does not cause an overflow.\r\n\t\tdouble stdev = sqrt((sq_sum / (double)changeInValues.size()) - (meanChangeInValue * meanChangeInValue));\r\n\t\t// Quick Fix: Set stdev to zero if stdev is +/-NaN, due to above issue.\r\n\t\tif (stdev != stdev)\r\n\t\t\tstdev = 0;\r\n\r\n\t\tcout << \"The average change in value is \" << meanChangeInValue << endl;\r\n\t\tcout << \"The standard deviations of the change in value is \" << stdev << endl;\r\n\r\n\t\tsort(changeInValues.begin(), changeInValues.end());\r\n\t\tdouble var95Percentile = changeInValues.at((int) (changeInValues.size()*0.05));\r\n\t\tdouble var99Percentile = changeInValues.at((int) (changeInValues.size()*0.01));\r\n\t\t// Using (int) will ensure that the index is an integer. It performs a 'floor' operation by \r\n\t\t// removing the decimal part of changeInValues.size()*alpha, which is what is needed for VaR calculations. \r\n\r\n\t\tdouble percentile = 98;\r\n\t\tdouble cvar = 0;\r\n\t\tfor (size_t i = 0, n1 = (int)(((100-percentile)*0.01)*changeInValues.size()); i < n1; i++)\r\n\t\t{\r\n\t\t\tcvar = cvar + changeInValues.at(i);\r\n\t\t}\r\n\t\tdouble cvarPercentile = cvar / (double)(((100 - percentile)*0.01)*changeInValues.size());\r\n\t\r\n\t\tcout << \"Note: Negative VaR indicates a loss\" << endl;\r\n\t\tcout << \"VaR at the 95th percentile is \" << var95Percentile << endl;\r\n\t\tcout << \"VaR at the 99th percentile is \" << var99Percentile << endl;\r\n\t\tcout << \"CVaR at the desired percentile is \" << cvarPercentile << endl;\r\n\t}\r\n\t// Print all exceptions to stderr\r\n\tcatch (const exception &e)\r\n\t{\r\n\t\tcerr << \"error: \" << e.what() << \"\\n\";\r\n\t}\r\n\tcout << \"Hit enter to exit\" << endl;\r\n\tgetchar();\r\n}\r\n", "meta": {"hexsha": "2a57d8135973dbe828ce96b896a082c25392e728", "size": 5086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CreditMetrics/main.cpp", "max_stars_repo_name": "mbarnhill/CreditMetrics", "max_stars_repo_head_hexsha": "1086f563ca8ea957b5b0ff76e1f87fa676a53da1", "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": "CreditMetrics/main.cpp", "max_issues_repo_name": "mbarnhill/CreditMetrics", "max_issues_repo_head_hexsha": "1086f563ca8ea957b5b0ff76e1f87fa676a53da1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CreditMetrics/main.cpp", "max_forks_repo_name": "mbarnhill/CreditMetrics", "max_forks_repo_head_hexsha": "1086f563ca8ea957b5b0ff76e1f87fa676a53da1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6885245902, "max_line_length": 118, "alphanum_fraction": 0.6979944947, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931455, "lm_q2_score": 0.7248702880639792, "lm_q1q2_score": 0.6024708944597676}}
{"text": "\n// solving A * X = B\n// A symmetric in packed format \n// driver function sysv()\n\n#include <cstddef>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/lapack/driver/spsv.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/symmetric.hpp>\n#include <boost/numeric/bindings/std/vector.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cin;\nusing std::cout;\nusing std::endl; \n\ntypedef double real_t; \ntypedef std::complex<real_t> cmplx_t; \n\ntypedef ublas::matrix<real_t, ublas::column_major> m_t;\ntypedef ublas::matrix<cmplx_t, ublas::column_major> cm_t;\n\ntypedef \n  ublas::symmetric_matrix<real_t, ublas::lower, ublas::column_major> symml_t; \ntypedef \n  ublas::symmetric_matrix<cmplx_t, ublas::lower, ublas::column_major> csymml_t;\n\ntypedef \n  ublas::symmetric_matrix<real_t, ublas::upper, ublas::column_major> symmu_t; \ntypedef \n  ublas::symmetric_matrix<cmplx_t, ublas::upper, ublas::column_major> csymmu_t;\n\n\ntemplate <typename M>\nvoid init_symm2 (M& m) {\n  for (int i = 0; i < m.size1(); ++i) \n    for (int j = i; j < m.size1(); ++j)\n      m (i, j) = m (j, i) = 1 + j - i; \n}\n\nint main (int argc, char **argv) {\n  size_t n = 0;\n  if (argc > 1) {\n    n = atoi(argv [1]);\n  }\n\n  cout << endl; \n\n  cout << \"real symmetric\\n\" << endl; \n\n  if (n <= 0) {\n    cout << \"n -> \";\n    cin >> n;\n  }\n  if (n < 5) n = 5; \n  cout << \"min n = 5\" << endl << endl; \n  size_t nrhs = 2; \n  symml_t sal (n, n);   // symmetric matrix\n  symmu_t sau (n, n);   // symmetric matrix\n  m_t x (n, nrhs);\n  m_t bl (n, nrhs), bu (n, nrhs);  // RHS matrices\n\n  std::vector<fortran_int_t> ipiv (n);\n\n  init_symm2 (sal); \n  print_m (sal, \"sal\"); \n  cout << endl; \n\n  init_symm2 (sau); \n  print_m (sau, \"sau\"); \n  cout << endl; \n\n  for (int i = 0; i < x.size1(); ++i) {\n    x (i, 0) = 1.;\n    x (i, 1) = 2.; \n  }\n  bl = prod (sal, x); \n  bu = prod (sau, x); \n\n  print_m (bl, \"bl\"); \n  cout << endl; \n  print_m (bu, \"bu\"); \n  cout << endl; \n\n  symml_t sal1 (sal);   // for part 2\n  symmu_t sau1 (sau);  \n  m_t bl1 (bl), bu1 (bu); \n\n//  lapack::spsv (sal, bl);\n//  no ipiv less version is currently provided, so fall back to using ipiv\n  lapack::spsv (sal, ipiv, bl);\n  print_m (bl, \"xl\"); \n  cout << endl; \n\n//  lapack::spsv (sau, bu);\n//  no ipiv less version is currently provided, so fall back to using ipiv\n  lapack::spsv (sau, ipiv, bu);\n  print_m (bu, \"xu\"); \n  cout << endl; \n\n  // part 2 \n\n  int err = lapack::spsv (sal1, ipiv, bl1);  \n  print_m (sal1, \"sal1 factored\"); \n  cout << endl; \n  print_v (ipiv, \"ipiv\"); \n  cout << endl; \n  print_m (bl1, \"xl1\"); \n  cout << endl; \n\n  err = lapack::spsv (sau1, ipiv, bu1);  \n  print_m (sau1, \"sau1 factored\"); \n  cout << endl; \n  print_v (ipiv, \"ipiv\"); \n  cout << endl; \n  print_m (bu1, \"xu1\"); \n  cout << endl; \n  cout << endl; \n\n\n  //////////////////////////////////////////////////////////\n  cout << \"\\n==========================================\\n\" << endl; \n  cout << \"complex symmetric\\n\" << endl; \n\n  csymml_t scal (n, n);   // symmetric matrix \n  csymmu_t scau (n, n);   // symmetric matrix \n  cm_t cx (n, 1); \n  cm_t cbl (n, 1), cbu (n, 1);  // RHS\n\n  init_symm2 (scal); \n  init_symm2 (scau); \n  scal *= cmplx_t (1, 1); \n  scau *= cmplx_t (1, -0.5); \n\n  print_m (scal, \"scal\"); \n  cout << endl; \n  print_m (scau, \"scau\"); \n  cout << endl; \n\n  for (int i = 0; i < cx.size1(); ++i) \n    cx (i, 0) = cmplx_t (1, -1); \n  print_m (cx, \"cx\"); \n  cout << endl; \n  cbl = prod (scal, cx);\n  cbu = prod (scau, cx);\n  print_m (cbl, \"cbl\"); \n  cout << endl; \n  print_m (cbu, \"cbu\"); \n  cout << endl; \n\n//  int ierr = lapack::spsv (scal, cbl);\n//  no ipiv less version is currently provided, so fall back to using ipiv\n  int ierr = lapack::spsv (scal, ipiv, cbl);\n  if (ierr == 0)\n    print_m (cbl, \"cxl\"); \n  else \n    cout << \"matrix is not regular: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n  ierr = lapack::spsv (scau, ipiv, cbu); \n  if (ierr == 0) {\n    print_v (ipiv, \"ipiv\"); \n    cout << endl; \n    print_m (cbu, \"cxu\"); \n  }\n  else \n    cout << \"matrix is not regular: ierr = \" \n         << ierr << endl;\n  cout << endl; \n\n}\n\n", "meta": {"hexsha": "5ef6ad35bb8d939ebcf2c9bd82834924a81aab18", "size": 4225, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_spsv.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_spsv.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_spsv.cc", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 23.4722222222, "max_line_length": 79, "alphanum_fraction": 0.5652071006, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6024708857035431}}
{"text": "//-----------------------------------------------------------------------------\n// Copyright (c) 2015-2018 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE mitrax householder_transformation\n#include <boost/test/unit_test.hpp>\n\n#include <mitrax/householder_transformation.hpp>\n#include <mitrax/operator.hpp>\n\n#include <cmath>\n#include <algorithm>\n\n\nusing boost::typeindex::type_id;\nusing boost::typeindex::type_id_runtime;\nusing namespace mitrax;\nusing namespace mitrax::literals;\n\n\ntemplate < typename T, typename U >\nconstexpr bool equal(T const& a, U const& b){\n\tusing std::abs;\n\treturn abs(a - b) < 0.00001;\n}\n\ntemplate < typename T, typename U >\nconstexpr bool matrix_equal(T const& a, U const& b){\n\tusing std::abs;\n\tauto m = a - b;\n\treturn std::any_of(m.begin(), m.end(), [](auto v){\n\t\treturn v < 0.00001;\n\t});\n}\n\n\nBOOST_AUTO_TEST_SUITE(suite_householder_transformation)\n\n\n// BOOST_AUTO_TEST_CASE(test_householder_transformation){\n// \tconstexpr auto m = make_matrix< double >(3_DS, {\n// \t\t{0, -4,  2},\n// \t\t{6, -3, -2},\n// \t\t{8,  1, -1}\n// \t});\n//\n// \tauto q = make_matrix< double >(3_DS);\n// \tauto r = make_matrix< double >(3_DS);\n//\n// \tstd::tie(q, r) = householder_transformation(m);\n//\n// \tBOOST_TEST((\n// \t\tequal(q(0, 0),  0) &&\n// \t\tequal(q(1, 0),  0.8) &&\n// \t\tequal(q(2, 0),  0.6) &&\n// \t\tequal(q(0, 1), -0.6) &&\n// \t\tequal(q(1, 1),  0.48) &&\n// \t\tequal(q(2, 1), -0.64) &&\n// \t\tequal(q(0, 2), -0.8) &&\n// \t\tequal(q(1, 2), -0.36) &&\n// \t\tequal(q(2, 2),  0.48)\n// \t));\n//\n// \tBOOST_TEST((\n// \t\tequal(r(0, 0), -10) &&\n// \t\tequal(r(1, 0),   1) &&\n// \t\tequal(r(2, 0),   2) &&\n// \t\tequal(r(0, 1),   0) &&\n// \t\tequal(r(1, 1),  -5) &&\n// \t\tequal(r(2, 1),   1) &&\n// \t\tequal(r(0, 2),   0) &&\n// \t\tequal(r(1, 2),   0) &&\n// \t\tequal(r(2, 2),   2)\n// \t));\n//\n// \tBOOST_TEST(matrix_equal(q * r, m));\n// }\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "7c7049b88ed8df6fdb7b0fd92d6bc490bc1cc22c", "size": 2102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/householder_transformation.cpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/householder_transformation.cpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/householder_transformation.cpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7294117647, "max_line_length": 79, "alphanum_fraction": 0.5480494767, "num_tokens": 708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.602470873576215}}
{"text": "#pragma once\n#include <vector>\n#include \"mass_matrix.hpp\"\n#include <Eigen/Sparse>\n#include \"opposite_volumes.hpp\"\n\nnamespace mtao { namespace geometry { namespace mesh {\n    template <typename VertexDerived, typename SimplexDerived> \n        auto cot_laplacian( const Eigen::MatrixBase<VertexDerived>& V, const Eigen::MatrixBase<SimplexDerived>& S) {\n            using Scalar = typename VertexDerived::Scalar;\n            using Triplet = Eigen::Triplet<double>;\n            std::vector<Triplet> trips;\n            int mV = V.cols();\n            Eigen::SparseMatrix<Scalar> L(mV,mV);\n            assert(S.rows() == 3);\n            auto OV = opposite_volumes(V,S);\n            std::vector<double> diag(mV,0);\n            for(int fi = 0; fi < S.cols(); ++fi) {\n                auto&& le = OV.col(fi).array();\n                auto&& f = S.col(fi);\n\n                double s = (le.sum()) / 2.0;\n                double area = std::sqrt(s * (s-le).prod());\n                double d = le.prod() / (2 * area);\n\n                auto Sa = le/d;\n\n                for(int i = 0; i < 3; ++i) {\n                    double a = le((i+0)%3);\n                    double b = le((i+1)%3);\n                    double c = le((i+2)%3);\n                    double ca = ( b*b + c*c - a*a ) / ( 2 * b*c );\n                    double v = -.5 * ca / Sa(i);\n\n\n                    //int A = f((i+0)%3);\n                    int B = f((i+1)%3);\n                    int C = f((i+2)%3);\n                    trips.emplace_back(B,C,v);\n                    trips.emplace_back(C,B,v);\n                    diag[B] += -v;\n                    diag[C] += -v;\n                }\n\n            }\n            for(size_t i = 0; i < diag.size(); ++i) {\n                trips.emplace_back(i,i,diag[i]);\n            }\n\n\n\n            L.setFromTriplets(trips.begin(),trips.end());\n            return L;\n        }\n\n    template <typename VertexDerived, typename SimplexDerived> \n        auto strong_cot_laplacian( const Eigen::MatrixBase<VertexDerived>& V, const Eigen::MatrixBase<SimplexDerived>& S) {\n            using Scalar = typename VertexDerived::Scalar;\n            auto DM = mass_matrix(V,S).array().eval();\n            DM = (DM.abs() > 1e-6).select(1/DM,0);\n            Eigen::SparseMatrix<Scalar> L = DM.matrix().asDiagonal() * cot_laplacian(V,S);\n            return L;\n        }\n}\n}\n}\n", "meta": {"hexsha": "a69291ebf5ade6c0b48ecc8079491992d0cba83e", "size": 2342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/mesh/laplacian.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/geometry/mesh/laplacian.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/mesh/laplacian.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9552238806, "max_line_length": 123, "alphanum_fraction": 0.4692570453, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.6023867984989342}}
{"text": "#ifndef SS_INTERNAL_DIST_HPP\r\n#define SS_INTERNAL_DIST_HPP\r\n\r\n#include <math.h>\r\n#include <ss/data/data.hpp>\r\n#include <ss/data/errors.hpp>\r\n#include <ss/internal/rmath.hpp>\r\n\r\n#ifndef HAVE_RMATH\r\n#include <boost/math/distributions/normal.hpp>\r\n#include <boost/math/distributions/fisher_f.hpp>\r\n#include <boost/math/distributions/students_t.hpp>\r\n#endif\r\n\r\nnamespace SS\r\n{\r\n    namespace Internal\r\n    {\r\n        inline double pf(double q, double df1, double df2)\r\n        {\r\n#ifdef HAVE_RMATH\r\n            return RMath::pt(x, n);\r\n#else\r\n            auto f = boost::math::fisher_f(df1, df2);\r\n            return boost::math::cdf(f, q);\r\n#endif\r\n        }\r\n        \r\n        inline double pt(double x, double df)\r\n        {\r\n#ifdef HAVE_RMATH\r\n            return RMath::pt(x, n);\r\n#else\r\n            auto d = boost::math::students_t(df);\r\n            return boost::math::cdf(d, x);\r\n#endif\r\n        }\r\n        \r\n        inline double qt(double p, double df)\r\n        {\r\n#ifdef HAVE_RMATH\r\n            return RMath::qt(x, n);\r\n#else\r\n            auto d = boost::math::students_t(df);\r\n            return boost::math::quantile(d, p);\r\n#endif\r\n        }\r\n        \r\n        inline double pnorm(double x, double mu, double sigma)\r\n        {\r\n#ifdef HAVE_RMATH\r\n            return RMath::pnorm(x, mu, sigma);\r\n#else\r\n            auto d = boost::math::normal(mu, sigma);\r\n            return boost::math::cdf(d, x);\r\n#endif\r\n        }\r\n    }\r\n}\r\n\r\n#endif", "meta": {"hexsha": "1ed407cb5f190bfe943b5272bb4439e8f2744cd9", "size": 1446, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stats/ss/internal/dist.hpp", "max_stars_repo_name": "danielnavarrogomez/Anaquin", "max_stars_repo_head_hexsha": "563dbeb25aff15a55e4309432a967812cbfa0c98", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stats/ss/internal/dist.hpp", "max_issues_repo_name": "danielnavarrogomez/Anaquin", "max_issues_repo_head_hexsha": "563dbeb25aff15a55e4309432a967812cbfa0c98", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stats/ss/internal/dist.hpp", "max_forks_repo_name": "danielnavarrogomez/Anaquin", "max_forks_repo_head_hexsha": "563dbeb25aff15a55e4309432a967812cbfa0c98", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7049180328, "max_line_length": 63, "alphanum_fraction": 0.5546334716, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.6584174871563662, "lm_q1q2_score": 0.6023867847279518}}
{"text": "/**\n * @Copyright 2020, Wuhan University of Technology\n * @Author: Pengwei Zhou\n * @Date: 2021/2/10 \u4e0b\u53489:11\n * @FileName: registration.hpp\n * @Description: T-LOAM frontend Lidar odometry\n * @License: See LICENSE for the license information\n */\n\n#ifndef TLOAM_REGISTRATION_HPP\n#define TLOAM_REGISTRATION_HPP\n\n#include <thread>\n#include <deque>\n#include <mutex>\n#include <future>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n#include <yaml-cpp/yaml.h>\n#include <omp.h>\n\n#include <open3d/Open3D.h>\n\n#include \"third_party/sophus/so3.hpp\"\n#include \"third_party/sophus/se3.hpp\"\n\n#include \"tloam/models/utils/work_space_path.h\"\n#include \"tloam/models/registration/registration_interface.hpp\"\n#include \"tloam/open3d/open3d_to_ros.hpp\"\n\nnamespace tloam{\n\nclass PointToPointErr : public ceres::SizedCostFunction<3, 6>{\npublic:\n  PointToPointErr(Eigen::Vector3d& source_, Eigen::Vector3d& target_, double& weight_, double* cost_);\n\n  ~PointToPointErr() override { }\n\n  virtual bool Evaluate(\n    double const* const* parameters,\n    double* residuals,\n    double** jacobians\n  ) const;\n\npublic:\n  Eigen::Vector3d target;\n  Eigen::Vector3d source;\n  double weight;\n  mutable double* cost;\n};\n\nclass PointToLineErr : public ceres::SizedCostFunction<3, 6>{\npublic:\n  PointToLineErr(\n    Eigen::Vector3d& curr_point_,\n    Eigen::Vector3d& line_point_a_,\n    Eigen::Vector3d& line_point_b_,\n    double& weight_, double* cost_\n  );\n\n  ~PointToLineErr() override { }\n\n  virtual bool Evaluate(\n    double const* const* parameters,\n    double* residuals,\n    double** jacobians\n  ) const;\n\npublic:\n  Eigen::Vector3d curr_point;\n  Eigen::Vector3d line_point_a;\n  Eigen::Vector3d line_point_b;\n  double weight;\n  mutable double* cost;\n};\n\nclass PointToPlaneErr : public ceres::SizedCostFunction<1, 6>{\npublic:\n  PointToPlaneErr(Eigen::Vector3d curr_point_, Eigen::Vector3d& unit_norm_, double& devia_, double& weight_, double* cost_);\n\n  ~PointToPlaneErr() override { }\n\n  virtual bool Evaluate(\n    double const* const* parameters,\n    double* residuals,\n    double** jacobians\n  ) const;\n\npublic:\n  Eigen::Vector3d curr_point;\n  Eigen::Vector3d unit_norm;\n  double devia;\n  double weight;\n  mutable double* cost;\n};\n\nclass PlaneToPlaneErr : public ceres::SizedCostFunction<3, 6>{\npublic:\n  PlaneToPlaneErr(\n    Eigen::Vector3d& source_point_,\n    Eigen::Matrix3d& source_covs_,\n    Eigen::Vector3d& target_point_,\n    Eigen::Matrix3d& target_covs_,\n    double& weight_, double* cost_\n  );\n\n  ~PlaneToPlaneErr() override { }\n\n  virtual bool Evaluate(\n    double const* const* parameters,\n    double* residuals,\n    double** jacobians\n  ) const;\n\npublic:\n  Eigen::Vector3d source_point;\n  Eigen::Matrix3d source_covs;\n  Eigen::Vector3d target_point;\n  Eigen::Matrix3d target_covs;\n  double weight;\n  mutable double* cost;\n};\n\nclass PoseSE3Parameterization : public ceres::LocalParameterization {\npublic:\n  PoseSE3Parameterization() = default;\n  ~PoseSE3Parameterization() override = default;\n\n  bool Plus(const double* x, const double* delta, double* x_plus_delta) const override;\n  bool ComputeJacobian(const double* x, double* jacobian) const override;\n  int GlobalSize() const override{\n    return 6;\n  }\n  int LocalSize() const override{\n    return 6;\n  }\n};\n\n// local registration based on truncated least squares method\nclass LocalRegistration : public RegistrationInterface{\npublic:\n  enum Factor{\n    planar = 2,\n    planarEdge = 3,\n    planarEdgeSphere = 4\n  };\n  LocalRegistration(const YAML::Node& config_node);\n  ~LocalRegistration() override;\n\n  void initConfig(const YAML::Node& node);\n\n  Eigen::Isometry3d getTransform(void);\n\n  Eigen::Isometry3d getPoseIncrement(void);\n\n  bool setInputSource(Frame& cloud_in_) override;\n  bool setInputTarget(Frame& cloud_in_) override;\n  bool scanMatching(Frame& out_result_, Eigen::Isometry3d& predict_pose_, Eigen::Isometry3d& result_pose_) override;\n\n  std::pair<double, double> getFitnessScore() override;\n\n  void resetKDTree(void);\n\nprotected:\n  /**\n   * @brief fit the best plane from the point cloud set\n   * @param point_set_, input point set\n   * @return plane model\n   */\n  Eigen::Vector4d fitBestPlane(std::vector<Eigen::Vector3d>& point_set_);\n\n  /**\n   * @brief calculate the covariance matrix\n   * @param cloud_in_, input point cloud\n   * @param out_covs_, output covariance matrix\n   * @return true if success otherwise false\n   */\n  bool calculateCov(\n    const std::shared_ptr<open3d::geometry::PointCloud2>& cloud_in_,\n    std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>>& out_covs_\n  );\n\n  /**\n   * @brief add edge features factor to ceres residual function\n   * @param scan_edge_, current frame edge features\n   * @param submap_edge_, edge_features in submap\n   * @param edge_weights_, the weight value of each feature\n   * @param edge_residuals_, the residual value of each feature\n   * @param problem_, ceres problem\n   * @param loss_function_, cerese loss function\n   * @return true if success otherwise false\n   */\n  bool addEdgeCostFactor(\n    const std::shared_ptr<open3d::geometry::PointCloud2>& scan_edge_,\n    const std::shared_ptr<open3d::geometry::PointCloud2>& submap_edge_,\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& edge_weights_,\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& edge_residuals_,\n    ceres::Problem& problem_,\n    ceres::LossFunction* loss_function_\n  );\n\n  /**\n   * @brief add sphere features factor to ceres residual function\n   * @param scan_sphere_, current frame sphere features\n   * @param submap_sphere_, sphere features in submap\n   * @param sphere_weights_, the weight value of each feature\n   * @param sphere_residuals_, the residual value of each feature\n   * @param problem_, ceres problem\n   * @param loss_function_, ceres loss function\n   * @return true if success otherwise false\n   */\n  bool addSphereCostFactor(\n    const std::shared_ptr<open3d::geometry::PointCloud2>& scan_sphere_,\n    const std::shared_ptr<open3d::geometry::PointCloud2>& submap_sphere_,\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& sphere_weights_,\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& sphere_residuals_,\n    ceres::Problem& problem_,\n    ceres::LossFunction* loss_function_\n  );\n\n  /**\n   * @brief add planar features factor to ceres residual function point_to_plane\n   * @param scan_plane_, current frame planar features\n   * @param submap_plane_, planar features in submap\n   * @param plane_weights_, the weight of each feature\n   * @param plane_residuals_, the residual value of each feature\n   * @param problem, ceres problem\n   * @param loss_function, ceres loss function\n   * @return true if success otherwise false\n   */\n  bool addSurfCostFactor(\n    const std::shared_ptr<open3d::geometry::PointCloud2>& scan_plane_,\n    const std::shared_ptr<open3d::geometry::PointCloud2>& submap_plane_,\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& plane_weights_,\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& plane_residuals_,\n    ceres::Problem& problem,\n    ceres::LossFunction* loss_function\n  );\n\n  /**\n   * @brief add planar features factor to ceres residual function plane_to_plane\n   * @param scan_plane_, current frame planar features\n   * @param submap_sphere_, planar features in submap\n   * @param scan_plane_covs_, scan_plane covariance\n   * @param submap_plane_covs_, submap_plane_ covariance\n   * @param plane_weights_, the weight of each feature\n   * @param plane_residuals_, the residual value of each feature\n   * @param problem, ceres problem\n   * @param loss_function, ceres loss function\n   * @return true if success otherwise false\n   */\n  bool addSurfCostFactor2(\n    const std::shared_ptr<open3d::geometry::PointCloud2>& scan_plane_,\n    const std::shared_ptr<open3d::geometry::PointCloud2>& submap_plane_,\n    std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>>& scan_plane_covs_,\n    std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>>& submap_plane_covs_,\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& plane_weights_,\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& plane_residuals_,\n    ceres::Problem& problem,\n    ceres::LossFunction* loss_function\n  );\n\n  /**\n   * @brief add ground features factor to ceres residual function\n   * @param scan_ground_, current frame ground features\n   * @param submap_ground_, ground features in submap\n   * @param ground_weights_, the weight of each feature\n   * @param ground_residuals_, the residual of each feature\n   * @param problem, ceres problem\n   * @param loss_function, ceres loss function\n   * @return true if success otherwise false\n   */\n  bool addGroundCostFactor(\n    const std::shared_ptr<open3d::geometry::PointCloud2>& scan_ground_,\n    const std::shared_ptr<open3d::geometry::PointCloud2>& submap_ground_,\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& ground_weights_,\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& ground_residuals_,\n    ceres::Problem& problem,\n    ceres::LossFunction* loss_function\n  );\n\n  /**\n   * @brief add ground features factor to ceres residual function\n   * @param scan_ground_, current frame ground features\n   * @param submap_ground_, ground features in submap\n   * @param scan_ground_covs_, scan_ground covariance\n   * @param submap_ground_covs_, submap_ground covariance\n   * @param ground_weights_, the weight of each feature\n   * @param ground_residuals_, the residual of each feature\n   * @param problem, ceres problem\n   * @param loss_function, ceres loss function\n   * @return true if success otherwise false\n   */\n  bool addGroundCostFactor2(\n      const std::shared_ptr<open3d::geometry::PointCloud2>& scan_ground_,\n      const std::shared_ptr<open3d::geometry::PointCloud2>& submap_ground_,\n      std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>>& scan_ground_covs_,\n      std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>>& submap_ground_covs_,\n      Eigen::Matrix<double, 1, Eigen::Dynamic>& ground_weights_,\n      Eigen::Matrix<double, 1, Eigen::Dynamic>& ground_residuals_,\n      ceres::Problem& problem,\n      ceres::LossFunction* loss_function\n  );\n\n  /**\n   * @brief update corresponding features weights\n   * @param weights_, output weights\n   * @param residuals_, feature residuals\n   * @param totalSize_, feature size\n   * @param noise_bound_sq_, noise upper bound\n   * @param th1_, gnc control threshold, the weight is assigned one if the rq less than the th1\n   * @param th2_, gnc control threshold, the weight is assigned zero if the rq more than the th2\n   * @param mu_, gnc control parameters\n   * @return true if success otherwise false\n   */\n  bool updateWeight(\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& weights_,\n    Eigen::Matrix<double, 1, Eigen::Dynamic>& residuals_,\n    double totalSize_, double noise_bound_sq_,\n    double th1_, double th2_,\n    double mu_\n  );\n\nprivate:\n  // Note with optimized pose, the front 3d represents translation, and the back 3D represents rotation.\n  double parameters[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};\n  Eigen::Map<Eigen::Matrix<double, 6, 1>> se3_pose_ = Eigen::Map<Eigen::Matrix<double, 6, 1>>(parameters);\n  int num_threads_;\n  int k_corr;\n\n  int factor_num;\n  double edge_dist_thres, sphere_dist_thres, planar_dist_thres, ground_dist_thres, edge_dir_thres, fitness_thres;\n  int edge_maxnum, sphere_maxnum, planar_maxnum, ground_maxnum;\n  std::mutex factor_mutex;\n\n  int max_iterations, nr_iterations;\n  double cost_threshold, gnc_factor, noise_bound;\n\n  Eigen::Isometry3d curr_frame_pose;\n  Eigen::Isometry3d last_frame_pose;\n\n  std::shared_ptr<open3d::geometry::PointCloud2> scan_planar;\n  std::shared_ptr<open3d::geometry::PointCloud2> scan_edge;\n  std::shared_ptr<open3d::geometry::PointCloud2> scan_sphere;\n  std::shared_ptr<open3d::geometry::PointCloud2> scan_ground;\n\n  std::shared_ptr<open3d::geometry::PointCloud2> submap_planar;\n  std::shared_ptr<open3d::geometry::PointCloud2> submap_edge;\n  std::shared_ptr<open3d::geometry::PointCloud2> submap_sphere;\n  std::shared_ptr<open3d::geometry::PointCloud2> submap_ground;\n\n  std::shared_ptr<open3d::geometry::KDTreeFlann> planar_kd_tree;\n  std::shared_ptr<open3d::geometry::KDTreeFlann> edge_kd_tree;\n  std::shared_ptr<open3d::geometry::KDTreeFlann> sphere_kd_tree;\n  std::shared_ptr<open3d::geometry::KDTreeFlann> ground_kd_tree;\n\n  std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>> source_planar_covs;\n  std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>> submap_planar_covs;\n\n  std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>> source_ground_covs;\n  std::vector<Eigen::Matrix3d, Eigen::aligned_allocator<Eigen::Matrix3d>> submap_ground_covs;\n\n};\n\n// waiting for code coming\nclass GlobalRegistration : public RegistrationInterface{\n  GlobalRegistration();\n  ~GlobalRegistration() override;\n\n  bool setInputSource(Frame& cloud_in_) override;\n  bool setInputTarget(Frame& cloud_in_) override;\n  bool scanMatching(Frame& out_result_, Eigen::Isometry3d& predict_pose_, Eigen::Isometry3d& result_pose_) override;\n  std::pair<double, double> getFitnessScore() override;\n};\n\n}\n#endif //TLOAM_REGISTRATION_HPP\n", "meta": {"hexsha": "5ea46b4705a503d768e58a82f76a862a40676e9f", "size": 13147, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tloam/include/tloam/models/registration/registration.hpp", "max_stars_repo_name": "cuge1995/SC-TLOAM", "max_stars_repo_head_hexsha": "facb7335f3a8ddfdeed3f87ac7a04362032e5a5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T05:56:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T06:34:23.000Z", "max_issues_repo_path": "tloam/include/tloam/models/registration/registration.hpp", "max_issues_repo_name": "cuge1995/SC-TLOAM", "max_issues_repo_head_hexsha": "facb7335f3a8ddfdeed3f87ac7a04362032e5a5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tloam/include/tloam/models/registration/registration.hpp", "max_forks_repo_name": "cuge1995/SC-TLOAM", "max_forks_repo_head_hexsha": "facb7335f3a8ddfdeed3f87ac7a04362032e5a5b", "max_forks_repo_licenses": ["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.5973684211, "max_line_length": 124, "alphanum_fraction": 0.7399406709, "num_tokens": 3499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.6688802669716106, "lm_q1q2_score": 0.6023466091112907}}
{"text": "#pragma once\n\n#include <boost/range.hpp>\n#include <cmath>\n#include <math/Matrix.hpp>\n#include <math/Vec.hpp>\n\ntemplate <class T>\nMatrix<4, 4, T> frustum(T left, T right, T bottom, T top, T near, T far) {\n\tT a = 2 * near / (right - left),\n\t\tb = 2 * near / (top - bottom),\n\t\tc = (right + left) / (right - left),\n\t\td = (top + bottom) / (top - bottom),\n\t\te = - (far + near) / (far - near),\n\t\tf = -2 * far * near / (far - near);\n\n\tT out[] = {\n\t\ta, 0, 0,  0,\n\t\t0, b, 0,  0,\n\t\tc, d, e, -1,\n\t\t0, 0, f,  0\n\t};\n\treturn Matrix<4, 4, T>(boost::begin(out), boost::end(out));\n}\n\ntemplate <class T>\nMatrix<4, 4, T> ortho(T max_x, T max_y) {\n\tT a = 1.0f / max_x;\n\tT b = 1.0f / max_y;\n\n\tT out[] = {\n\t\ta, 0,  0, 0, \n\t\t0, b,  0, 0,\n\t\t0, 0, -1, 0,\n\t\t0, 0,  0, 1\n\t};\n\treturn Matrix<4, 4, T>(boost::begin(out), boost::end(out));\n}\n\ntemplate <class T>\nMatrix<4, 4, T> identity_matrix() {\n\tT out[] = {\n\t\t1, 0, 0, 0,\n\t\t0, 1, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t0, 0, 0, 1\n\t};\n\n\treturn Matrix<4, 4, T>(boost::begin(out), boost::end(out));\n}\n\ntemplate <class T>\nMatrix<3, 3, T> identity_matrix3() {\n\tT out[] = {\n\t\t1, 0, 0,\n\t\t0, 1, 0,\n\t\t0, 0, 1\n\t};\n\n\treturn Matrix<3, 3, T>(out);\n}\n\ntemplate <class T>\nMatrix<4, 4, T> perspective(T near, T far, T aspect_ratio, T field_of_view) {\n\tT height = std::tan(field_of_view / 2) * near,\n\t\twidth = aspect_ratio * height;\n\n\treturn frustum(-width, width, -height, height, near, far);\n}\n\ntemplate <class T>\nMatrix<4, 4, T> rotate_around_z(T angle) {\n\tT s = std::sin(angle);\n\tT c = std::cos(angle);\n\n\tT out[] = {\n\t\t c, s, 0, 0,\n\t\t-s, c, 0, 0,\n\t\t 0, 0, 1, 0,\n\t\t 0, 0, 0, 1\n\t};\n\n\treturn Matrix<4, 4, T>(boost::begin(out), boost::end(out));\n}\n\ntemplate <class T>\nMatrix<4, 4, T> translate_matrix(Vec<3, T> const & position) {\n\tT values[] = {\n\t\t1,             0,             0,             0, \n\t\t0,             1,             0,             0, \n\t\t0,             0,             1,             0, \n\t\tposition.x(),  position.y(),  position.z(),  1\n\t};\n\n\treturn Matrix<4, 4, T>(values);\n}\n", "meta": {"hexsha": "c3bcd7f10393a7b90126c3af4bbb026823734134", "size": 1975, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math/MatrixOps.hpp", "max_stars_repo_name": "bracket/circles", "max_stars_repo_head_hexsha": "2e358244ef7823eb7fa836bac88c868ca8b37e21", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "math/MatrixOps.hpp", "max_issues_repo_name": "bracket/circles", "max_issues_repo_head_hexsha": "2e358244ef7823eb7fa836bac88c868ca8b37e21", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/MatrixOps.hpp", "max_forks_repo_name": "bracket/circles", "max_forks_repo_head_hexsha": "2e358244ef7823eb7fa836bac88c868ca8b37e21", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3608247423, "max_line_length": 77, "alphanum_fraction": 0.5088607595, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.6825737408694988, "lm_q1q2_score": 0.6023220940743125}}
{"text": "#include <iostream>\n#include <string>\n#include <algorithm>\n#include <boost/algorithm/string.hpp>\n\nusing namespace std;\n\nconst std::string SEPARATORS = \"x\";\n\nsize_t parse_line(const std::string& line);\n\nint main (int argc, char** argv) {\n  std::string line;\n  std::getline(std::cin, line);\n\n  size_t surface = 0;\n  while(!cin.eof()) {\n    surface += parse_line(line);\n    std::getline(std::cin, line);\n  }\n\n  std::cout << surface << std::endl;\n}\n\nsize_t parse_line(const std::string& line) {\n  std::vector<std::string> strs;\n  std::vector<int> values;\n\n  boost::split(strs, line, boost::is_any_of(SEPARATORS));\n  if(strs.size() != 3)\n    return 0;\n\n  for(auto& str : strs) {\n    boost::trim(str);\n    values.push_back(std::stoi(str));\n  }\n\n  std::sort(values.begin(), values.end());\n  return 3 * values[0] * values[1] + 2 * values[1] * values[2] + 2 * values[2] * values[0];\n}\n", "meta": {"hexsha": "7c0bdd6c60a1daabd1219e1c5d23d8ce3dfe0886", "size": 876, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2/2.cpp", "max_stars_repo_name": "julitopower/AdventOfCode2015", "max_stars_repo_head_hexsha": "42577266d7d38b60bc8f5800c9c5f9a49705a728", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2/2.cpp", "max_issues_repo_name": "julitopower/AdventOfCode2015", "max_issues_repo_head_hexsha": "42577266d7d38b60bc8f5800c9c5f9a49705a728", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2/2.cpp", "max_forks_repo_name": "julitopower/AdventOfCode2015", "max_forks_repo_head_hexsha": "42577266d7d38b60bc8f5800c9c5f9a49705a728", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3658536585, "max_line_length": 91, "alphanum_fraction": 0.6335616438, "num_tokens": 259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6023220033829728}}
{"text": "/** \\file ublas_cholesky.hpp \\brief Cholesky decomposition */\n/*\n -   begin                : 2005-08-24\n -   copyright            : (C) 2005 by Gunter Winkler, Konstantin Kutzkow\n                            2011-2013 by Ruben Martinez-Cantin <rmcantin@unizar.es>\n -   email                : guwi17@gmx.de\n\n    This library is free software; you can redistribute it and/or\n    modify it under the terms of the GNU Lesser General Public\n    License as published by the Free Software Foundation; either\n    version 2.1 of the License, or (at your option) any later version.\n\n    This library is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n    Lesser General Public License for more details.\n\n    You should have received a copy of the GNU Lesser General Public\n    License along with this library; if not, write to the Free Software\n    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n*/\n\n#ifndef _H_CHOLESKY_HPP_\n#define _H_CHOLESKY_HPP_\n\n\n#include <cassert>\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n\n#include <boost/numeric/ublas/triangular.hpp>\n\nnamespace bayesopt \n{\n  namespace utils\n  {  \n    namespace ublas = boost::numeric::ublas;\n\n\n    /** \\brief decompose the symmetric positive definit matrix A into product L L^T.\n     *\n     * \\param MATRIX type of input matrix \n     * \\param TRIA type of lower triangular output matrix\n     * \\param A square symmetric positive definite input matrix (only the lower triangle is accessed)\n     * \\param L lower triangular output matrix \n     * \\return nonzero if decompositon fails (the value ist 1 + the numer of the failing row)\n     */\n    template < class MATRIX, class TRIA >\n    size_t cholesky_decompose(const MATRIX& A, TRIA& L)\n    {\n      using namespace ublas;\n\n      typedef typename MATRIX::value_type T;\n  \n      assert( A.size1() == A.size2() );\n      assert( A.size1() == L.size1() );\n      assert( A.size2() == L.size2() );\n\n      const size_t n = A.size1();\n  \n      for (size_t k=0 ; k < n; k++) {\n        \n\tdouble qL_kk = A(k,k) - inner_prod( project( row(L, k), range(0, k) ),\n\t\t\t\t\t    project( row(L, k), range(0, k) ) );\n    \n\tif (qL_kk <= 0) {\n\t  return 1 + k;\n\t} else {\n\t  double L_kk = sqrt( qL_kk );\n\t  L(k,k) = L_kk;\n      \n\t  matrix_column<TRIA> cLk(L, k);\n\t  project( cLk, range(k+1, n) )\n\t    = ( project( column(A, k), range(k+1, n) )\n\t\t- prod( project(L, range(k+1, n), range(0, k)), \n\t\t\tproject(row(L, k), range(0, k) ) ) ) / L_kk;\n\t}\n      }\n      return 0;      \n    }\n\n\n    /** \\brief decompose the symmetric positive definit matrix A into product L L^T.\n     *\n     * \\param MATRIX type of matrix A\n     * \\param A input: square symmetric positive definite matrix (only the lower triangle is accessed)\n     * \\param A output: the lower triangle of A is replaced by the cholesky factor\n     * \\return nonzero if decompositon fails (the value ist 1 + the numer of the failing row)\n     */\n    template < class MATRIX >\n    size_t cholesky_decompose(MATRIX& A)\n    {\n      using namespace ublas;\n      typedef typename MATRIX::value_type T;\n  \n      const MATRIX& A_c(A);\n\n      const size_t n = A.size1();\n  \n      for (size_t k=0 ; k < n; k++) {\n        \n\tdouble qL_kk = A_c(k,k) - inner_prod( project( row(A_c, k), range(0, k) ),\n\t\t\t\t\t      project( row(A_c, k), range(0, k) ) );\n    \n\tif (qL_kk <= 0) {\n\t  return 1 + k;\n\t} else {\n\t  double L_kk = sqrt( qL_kk );\n      \n\t  matrix_column<MATRIX> cLk(A, k);\n\t  project( cLk, range(k+1, n) )\n\t    = ( project( column(A_c, k), range(k+1, n) )\n\t\t- prod( project(A_c, range(k+1, n), range(0, k)), \n\t\t\tproject(row(A_c, k), range(0, k) ) ) ) / L_kk;\n\t  A(k,k) = L_kk;\n\t}\n      }\n      return 0;      \n    }\n\n#if 0\n    using namespace ublas;\n\n    // Operations:\n    //  n * (n - 1) / 2 + n = n * (n + 1) / 2 multiplications,\n    //  n * (n - 1) / 2 additions\n\n    // Dense (proxy) case\n    template<class E1, class E2>\n    void inplace_solve (const matrix_expression<E1> &e1, vector_expression<E2> &e2,\n                        lower_tag, column_major_tag) {\n      std::cout << \" is_lc \";\n      typedef typename E2::size_type size_type;\n      typedef typename E2::difference_type difference_type;\n      typedef typename E2::value_type value_type;\n\n      BOOST_UBLAS_CHECK (e1 ().size1 () == e1 ().size2 (), bad_size ());\n      BOOST_UBLAS_CHECK (e1 ().size2 () == e2 ().size (), bad_size ());\n      size_type size = e2 ().size ();\n      for (size_type n = 0; n < size; ++ n) {\n#ifndef BOOST_UBLAS_SINGULAR_CHECK\n\tBOOST_UBLAS_CHECK (e1 () (n, n) != value_type/*zero*/(), singular ());\n#else\n\tif (e1 () (n, n) == value_type/*zero*/())\n\t  singular ().raise ();\n#endif\n\tvalue_type t = e2 () (n) / e1 () (n, n);\n\te2 () (n) = t;\n\tif (t != value_type/*zero*/()) {\n\t  project( e2 (), range(n+1, size) )\n\t    .minus_assign( t * project( column( e1 (), n), range(n+1, size) ) );\n\t}\n      }\n    }\n#endif\n\n\n\n    /** \\brief decompose the symmetric positive definit matrix A into product L L^T.\n     *\n     * \\param MATRIX type of matrix A\n     * \\param A input: square symmetric positive definite matrix (only the lower triangle is accessed)\n     * \\param A output: the lower triangle of A is replaced by the cholesky factor\n     * \\return nonzero if decompositon fails (the value ist 1 + the numer of the failing row)\n     */\n    template < class MATRIX >\n    size_t incomplete_cholesky_decompose(MATRIX& A)\n    {\n      using namespace ublas;\n\n      typedef typename MATRIX::value_type T;\n  \n      // read access to a const matrix is faster\n      const MATRIX& A_c(A);\n\n      const size_t n = A.size1();\n  \n      for (size_t k=0 ; k < n; k++) {\n    \n\tdouble qL_kk = A_c(k,k) - inner_prod( project( row( A_c, k ), range(0, k) ),\n\t\t\t\t\t      project( row( A_c, k ), range(0, k) ) );\n    \n\tif (qL_kk <= 0) {\n\t  return 1 + k;\n\t} else {\n\t  double L_kk = sqrt( qL_kk );\n\n\t  // aktualisieren\n\t  for (size_t i = k+1; i < A.size1(); ++i) {\n\t    T* Aik = A.find_element(i, k);\n\n\t    if (Aik != 0) {\n\t      *Aik = ( *Aik - inner_prod( project( row( A_c, k ), range(0, k) ),\n\t\t\t\t\t  project( row( A_c, i ), range(0, k) ) ) ) / L_kk;\n\t    }\n\t  }\n        \n\t  A(k,k) = L_kk;\n\t}\n      }\n        \n      return 0;\n    }\n\n\n\n    /** \\brief solve system L L^T x = b inplace\n     *\n     * \\param L a triangular matrix\n     * \\param x input: right hand side b; output: solution x\n     */\n    template < class TRIA, class MATRIX >\n    void\n    cholesky_solve(const TRIA& L, MATRIX& x, ublas::lower)\n    {\n      using namespace ublas;\n      //   ::inplace_solve(L, x, lower_tag(), typename TRIA::orientation_category () );\n      inplace_solve(L, x, lower_tag() );\n      inplace_solve(trans(L), x, upper_tag());\n    }\n\n    /****** Added by Ruben Martinez-Cantin. 2011 ***********/\n\n    /** \\brief Computes the inverse matrix of a symmetric positive definite matrix\n     *\n     * \\param M original matrix\n     * \\param inverse inverse of M\n     * \\return nonzero if decompositon fails (the value ist 1 + the numer of the failing row)\n     */\n    template < class Min, class Mout >\n    size_t\n    inverse_cholesky(const Min& M, Mout& inverse)\n    {\n      typedef typename Mout::value_type value_type;\n\n      size_t size = M.size1();\n      Min L(size,size);\n      size_t res = cholesky_decompose(M, L);\n\n      if (res != 0) return res;\n\n      inverse.assign(ublas::identity_matrix<value_type>(size));\n      cholesky_solve(L,inverse,ublas::lower());\n\n      return 0;\n    }\n\n    /** \\brief decompose the symmetric positive definit matrix A into product L L^T.\n     *\n     * \\param MATRIX type of input matrix \n     * \\param TRIA type of lower triangular output matrix\n     * \\param A square symmetric positive definite input matrix (only the lower triangle is accessed)\n     * \\param L lower triangular output matrix \n     */\n    template < class TRIA, class VECTOR >\n    void cholesky_add_row(TRIA& L, const VECTOR& v)\n    {\n      using namespace ublas;\n      typedef typename TRIA::value_type T;\n  \n      assert( L.size1() == L.size2() );\n      assert( L.size1()+1 == v.size() );\n\n      const size_t n = v.size();\n\n      L.resize(n,n);\n      double L_j;\n\n      for (size_t j = 0; j < n-1; ++j)\n\t{\n\t  L_j = v(j) - inner_prod(project (row(L, j), range(0,j)), \n\t\t\t\t  project (row(L,n-1), range(0,j)));\n\t  L(n-1,j) = (L_j) / L(j,j);\n\t}\n      L_j = v(n-1) - inner_prod(project (row(L, n-1), range(0,n-1)), \n\t\t\t\tproject (row(L,n-1), range(0,n-1)));\n      L(n-1,n-1) = sqrt(L_j);\n      return;      \n    }\n\n  } //namespace utils\n\n} // namespace bayesopt\n\n#endif\n", "meta": {"hexsha": "99d0f2ac9c774c32bd7ddefd98d094a41e9b47d8", "size": 8852, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/utils/ublas_cholesky.hpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/utils/ublas_cholesky.hpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/utils/ublas_cholesky.hpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 30.1088435374, "max_line_length": 102, "alphanum_fraction": 0.598847718, "num_tokens": 2587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6023219965789405}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/*\n *   File \"ba_b_tapenade_generated.c\" is generated by Tapenade 3.14 (r7259) from this file.\n *   To reproduce such a generation you can use Tapenade CLI\n *   (can be downloaded from http://www-sop.inria.fr/tropics/tapenade/downloading.html)\n *\n *   After installing use the next command to generate a file:\n *\n *      tapenade -b -o ba_tapenade -head \"compute_reproj_error(err)/(cam X) compute_zach_weight_error(err)/(w)\" ba.c\n *\n *   This will produce a file \"ba_tapenade_b.c\" which content will be the same as the content of \"ba_b_tapenade_generated.c\",\n *   except one-line header. Moreover a log-file \"ba_tapenade_b.msg\" will be produced.\n *\n *   NOTE: the code in \"ba_b_tapenade_generated.c\" is wrong and won't work.\n *         REPAIRED SOURCE IS STORED IN THE FILE \"ba_b.c\".\n *         You can either use diff tool or read \"ba_b.c\" header to figure out what changes was performed to fix the code.\n *\n *   NOTE: you can also use Tapenade web server (http://tapenade.inria.fr:8080/tapenade/index.jsp)\n *         for generating but the result can be slightly different.\n */\n\n#include \"../adbench/ba.h\"\n\nextern \"C\" {\n\n#include \"ba.h\"\n\n/* ===================================================================== */\n/*                                UTILS                                  */\n/* ===================================================================== */\n\ndouble sqsum(int n, double const* x)\n{\n    int i;\n    double res = 0;\n    for (i = 0; i < n; i++)\n    {\n        res = res + x[i] * x[i];\n    }\n\n    return res;\n}\n\n\n\nvoid cross(double const* a, double const* b, double* out)\n{\n    out[0] = a[1] * b[2] - a[2] * b[1];\n    out[1] = a[2] * b[0] - a[0] * b[2];\n    out[2] = a[0] * b[1] - a[1] * b[0];\n}\n\n\n\n/* ===================================================================== */\n/*                               MAIN LOGIC                              */\n/* ===================================================================== */\n\n// rot: 3 rotation parameters\n// pt: 3 point to be rotated\n// rotatedPt: 3 rotated point\n// this is an efficient evaluation (part of\n// the Ceres implementation)\n// easy to understand calculation in matlab:\n//  theta = sqrt(sum(w. ^ 2));\n//  n = w / theta;\n//  n_x = au_cross_matrix(n);\n//  R = eye(3) + n_x*sin(theta) + n_x*n_x*(1 - cos(theta));\nvoid rodrigues_rotate_point(double const* __restrict rot, double const* __restrict pt, double *__restrict rotatedPt)\n{\n    int i;\n    double sqtheta = sqsum(3, rot);\n    if (sqtheta != 0)\n    {\n        double theta, costheta, sintheta, theta_inverse;\n        double w[3], w_cross_pt[3], tmp;\n\n        theta = sqrt(sqtheta);\n        costheta = cos(theta);\n        sintheta = sin(theta);\n        theta_inverse = 1.0 / theta;\n\n        for (i = 0; i < 3; i++)\n        {\n            w[i] = rot[i] * theta_inverse;\n        }\n\n        cross(w, pt, w_cross_pt);\n\n        tmp = (w[0] * pt[0] + w[1] * pt[1] + w[2] * pt[2]) *\n            (1. - costheta);\n\n        for (i = 0; i < 3; i++)\n        {\n            rotatedPt[i] = pt[i] * costheta + w_cross_pt[i] * sintheta + w[i] * tmp;\n        }\n    }\n    else\n    {\n        double rot_cross_pt[3];\n        cross(rot, pt, rot_cross_pt);\n\n        for (i = 0; i < 3; i++)\n        {\n            rotatedPt[i] = pt[i] + rot_cross_pt[i];\n        }\n    }\n}\n\n\n\nvoid radial_distort(double const* rad_params, double *proj)\n{\n    double rsq, L;\n    rsq = sqsum(2, proj);\n    L = 1. + rad_params[0] * rsq + rad_params[1] * rsq * rsq;\n    proj[0] = proj[0] * L;\n    proj[1] = proj[1] * L;\n}\n\n\n\nvoid project(double const* __restrict cam, double const* __restrict X, double* __restrict proj)\n{\n    double const* C = &cam[3];\n    double Xo[3], Xcam[3];\n\n    Xo[0] = X[0] - C[0];\n    Xo[1] = X[1] - C[1];\n    Xo[2] = X[2] - C[2];\n\n    rodrigues_rotate_point(&cam[0], Xo, Xcam);\n\n    proj[0] = Xcam[0] / Xcam[2];\n    proj[1] = Xcam[1] / Xcam[2];\n\n    radial_distort(&cam[9], proj);\n\n    proj[0] = proj[0] * cam[6] + cam[7];\n    proj[1] = proj[1] * cam[6] + cam[8];\n}\n\n\n\n// cam: 11 camera in format [r1 r2 r3 C1 C2 C3 f u0 v0 k1 k2]\n//            r1, r2, r3 are angle - axis rotation parameters(Rodrigues)\n//            [C1 C2 C3]' is the camera center\n//            f is the focal length in pixels\n//            [u0 v0]' is the principal point\n//            k1, k2 are radial distortion parameters\n// X: 3 point\n// feats: 2 feature (x,y coordinates)\n// reproj_err: 2\n// projection function:\n// Xcam = R * (X - C)\n// distorted = radial_distort(projective2euclidean(Xcam), radial_parameters)\n// proj = distorted * f + principal_point\n// err = sqsum(proj - measurement)\nvoid compute_reproj_error(\n    double const* __restrict cam,\n    double const* __restrict X,\n    double const* __restrict w,\n    double const* __restrict feat,\n    double * __restrict err\n)\n{\n    double proj[2];\n    project(cam, X, proj);\n\n    err[0] = (*w)*(proj[0] - feat[0]);\n    err[1] = (*w)*(proj[1] - feat[1]);\n}\n\n\n\nvoid compute_zach_weight_error(double const* w, double* err)\n{\n    *err = 1 - (*w)*(*w);\n}\n\n\n\n// n number of cameras\n// m number of points\n// p number of observations\n// cams: 11*n cameras in format [r1 r2 r3 C1 C2 C3 f u0 v0 k1 k2]\n//            r1, r2, r3 are angle - axis rotation parameters(Rodrigues)\n//            [C1 C2 C3]' is the camera center\n//            f is the focal length in pixels\n//            [u0 v0]' is the principal point\n//            k1, k2 are radial distortion parameters\n// X: 3*m points\n// obs: 2*p observations (pairs cameraIdx, pointIdx)\n// feats: 2*p features (x,y coordinates corresponding to observations)\n// reproj_err: 2*p errors of observations\n// w_err: p weight \"error\" terms\nvoid ba_objective(\n    int n,\n    int m,\n    int p,\n    double const* cams,\n    double const* X,\n    double const* w,\n    int const* obs,\n    double const* feats,\n    double* reproj_err,\n    double* w_err\n)\n{\n    int i;\n    for (i = 0; i < p; i++)\n    {\n        int camIdx = obs[i * 2 + 0];\n        int ptIdx = obs[i * 2 + 1];\n        compute_reproj_error(\n            &cams[camIdx * BA_NCAMPARAMS],\n            &X[ptIdx * 3],\n            &w[i],\n            &feats[i * 2],\n            &reproj_err[2 * i]\n        );\n    }\n\n    for (i = 0; i < p; i++)\n    {\n        compute_zach_weight_error(&w[i], &w_err[i]);\n    }\n}\n\nextern int enzyme_const;\nextern int enzyme_dup;\nextern int enzyme_dupnoneed;\nvoid __enzyme_autodiff(...) noexcept;\n\nvoid dcompute_reproj_error(\n    double const* cam,\n    double * dcam,\n    double const* X,\n    double * dX,\n    double const* w,\n    double * wb,\n    double const* feat,\n    double *err,\n    double *derr\n)\n{\n    __enzyme_autodiff(compute_reproj_error,\n            enzyme_dup, cam, dcam,\n            enzyme_dup, X, dX,\n            enzyme_dup, w, wb,\n            enzyme_const, feat,\n            enzyme_dupnoneed, err, derr);\n}\n\nvoid dcompute_zach_weight_error(double const* w, double* dw, double* err, double* derr) {\n    __enzyme_autodiff(compute_zach_weight_error,\n            enzyme_dup, w, dw,\n            enzyme_dupnoneed, err, derr);\n}\n\n}\n\n\n//! Tapenade\nextern \"C\" {\n\n#include <adBuffer.h>\n\n/*\n  Differentiation of sqsum in reverse (adjoint) mode:\n   gradient     of useful results: *x sqsum\n   with respect to varying inputs: *x\n   Plus diff mem management of: x:in\n\n =====================================================================\n                                UTILS\n ===================================================================== */\nvoid sqsum_b(int n, const double *x, double *xb, double sqsumb) {\n    int i;\n    double res = 0;\n    double resb = 0.0;\n    double sqsum;\n    resb = sqsumb;\n    for (i = n-1; i > -1; --i)\n        xb[i] = xb[i] + 2*x[i]*resb;\n}\n\n/* =====================================================================\n                                UTILS\n ===================================================================== */\ndouble sqsum_nodiff(int n, const double *x) {\n    int i;\n    double res = 0;\n    for (i = 0; i < n; ++i)\n        res = res + x[i]*x[i];\n    return res;\n}\n\n/*\n  Differentiation of cross in reverse (adjoint) mode:\n   gradient     of useful results: *out *a *b\n   with respect to varying inputs: *a *b\n   Plus diff mem management of: out:in a:in b:in\n*/\nvoid cross_b(const double *a, double *ab, const double *b, double *bb, double\n        *out, double *outb) {\n    ab[0] = ab[0] + b[1]*outb[2];\n    bb[1] = bb[1] + a[0]*outb[2];\n    ab[1] = ab[1] - b[0]*outb[2];\n    bb[0] = bb[0] - a[1]*outb[2];\n    outb[2] = 0.0;\n    ab[2] = ab[2] + b[0]*outb[1];\n    bb[0] = bb[0] + a[2]*outb[1];\n    ab[0] = ab[0] - b[2]*outb[1];\n    bb[2] = bb[2] - a[0]*outb[1];\n    outb[1] = 0.0;\n    ab[1] = ab[1] + b[2]*outb[0];\n    bb[2] = bb[2] + a[1]*outb[0];\n    ab[2] = ab[2] - b[1]*outb[0];\n    bb[1] = bb[1] - a[2]*outb[0];\n}\n\nvoid cross_nodiff(const double *a, const double *b, double *out) {\n    out[0] = a[1]*b[2] - a[2]*b[1];\n    out[1] = a[2]*b[0] - a[0]*b[2];\n    out[2] = a[0]*b[1] - a[1]*b[0];\n}\n\n/*\n  Differentiation of rodrigues_rotate_point in reverse (adjoint) mode:\n   gradient     of useful results: *rot *rotatedPt\n   with respect to varying inputs: *rot *pt\n   Plus diff mem management of: rot:in rotatedPt:in pt:in\n\n =====================================================================\n                               MAIN LOGIC\n ===================================================================== */\n// rot: 3 rotation parameters\n// pt: 3 point to be rotated\n// rotatedPt: 3 rotated point\n// this is an efficient evaluation (part of\n// the Ceres implementation)\n// easy to understand calculation in matlab:\n//  theta = sqrt(sum(w. ^ 2));\n//  n = w / theta;\n//  n_x = au_cross_matrix(n);\n//  R = eye(3) + n_x*sin(theta) + n_x*n_x*(1 - cos(theta));\nvoid rodrigues_rotate_point_b(const double *rot, double *rotb, const double *\n        pt, double *ptb, double *rotatedPt, double *rotatedPtb) {\n    int i;\n    double sqtheta;\n    double sqthetab;\n    int ii1;\n    sqtheta = sqsum_nodiff(3, rot);\n    if (sqtheta != 0) {\n        double theta, costheta, sintheta, theta_inverse;\n        double w[3], w_cross_pt[3], tmp;\n        double tempb;\n        theta = sqrt(sqtheta);\n        costheta = cos(theta);\n        sintheta = sin(theta);\n        theta_inverse = 1.0/theta;\n        double thetab, costhetab, sinthetab, theta_inverseb;\n        double wb[3], w_cross_ptb[3], tmpb;\n        for (i = 0; i < 3; ++i)\n            w[i] = rot[i]*theta_inverse;\n        cross_nodiff(w, pt, w_cross_pt);\n        tmp = (w[0]*pt[0]+w[1]*pt[1]+w[2]*pt[2])*(1.-costheta);\n        for (i = 0; i < 3; i++) /* TFIX */\n            ptb[i] = 0.0;\n        for (ii1 = 0; ii1 < 3; ++ii1)\n            w_cross_ptb[ii1] = 0.0;\n        for (ii1 = 0; ii1 < 3; ++ii1)\n            wb[ii1] = 0.0;\n        costhetab = 0.0;\n        tmpb = 0.0;\n        sinthetab = 0.0;\n        for (i = 2; i > -1; --i) {\n            ptb[i] = ptb[i] + costheta*rotatedPtb[i];\n            costhetab = costhetab + pt[i]*rotatedPtb[i];\n            w_cross_ptb[i] = w_cross_ptb[i] + sintheta*rotatedPtb[i];\n            sinthetab = sinthetab + w_cross_pt[i]*rotatedPtb[i];\n            wb[i] = wb[i] + tmp*rotatedPtb[i];\n            tmpb = tmpb + w[i]*rotatedPtb[i];\n            rotatedPtb[i] = 0.0;\n        }\n        tempb = (1.-costheta)*tmpb;\n        wb[0] = wb[0] + pt[0]*tempb;\n        ptb[0] = ptb[0] + w[0]*tempb;\n        wb[1] = wb[1] + pt[1]*tempb;\n        ptb[1] = ptb[1] + w[1]*tempb;\n        wb[2] = wb[2] + pt[2]*tempb;\n        ptb[2] = ptb[2] + w[2]*tempb;\n        costhetab = costhetab - (w[0]*pt[0]+w[1]*pt[1]+w[2]*pt[2])*tmpb;\n        cross_b(w, wb, pt, ptb, w_cross_pt, w_cross_ptb);\n        theta_inverseb = 0.0;\n        for (i = 2; i > -1; --i) {\n            rotb[i] = rotb[i] + theta_inverse*wb[i];\n            theta_inverseb = theta_inverseb + rot[i]*wb[i];\n            wb[i] = 0.0;\n        }\n        thetab = cos(theta)*sinthetab - sin(theta)*costhetab - theta_inverseb/\n            (theta*theta);\n        if (sqtheta == 0.0)\n            sqthetab = 0.0;\n        else\n            sqthetab = thetab/(2.0*sqrt(sqtheta));\n    } else {\n        {\n          double rot_cross_pt[3];\n          double rot_cross_ptb[3];\n          for (i = 0; i < 3; i++) /* TFIX */\n              ptb[i] = 0.0;\n          for (ii1 = 0; ii1 < 3; ++ii1)\n              rot_cross_ptb[ii1] = 0.0;\n          for (i = 2; i > -1; --i) {\n              ptb[i] = ptb[i] + rotatedPtb[i];\n              rot_cross_ptb[i] = rot_cross_ptb[i] + rotatedPtb[i];\n              rotatedPtb[i] = 0.0;\n          }\n          cross_b(rot, rotb, pt, ptb, rot_cross_pt, rot_cross_ptb);\n        }\n        sqthetab = 0.0;\n    }\n    sqsum_b(3, rot, rotb, sqthetab);\n}\n\n/* =====================================================================\n                               MAIN LOGIC\n ===================================================================== */\n// rot: 3 rotation parameters\n// pt: 3 point to be rotated\n// rotatedPt: 3 rotated point\n// this is an efficient evaluation (part of\n// the Ceres implementation)\n// easy to understand calculation in matlab:\n//  theta = sqrt(sum(w. ^ 2));\n//  n = w / theta;\n//  n_x = au_cross_matrix(n);\n//  R = eye(3) + n_x*sin(theta) + n_x*n_x*(1 - cos(theta));\nvoid rodrigues_rotate_point_nodiff(const double *rot, const double *pt, double\n        *rotatedPt) {\n    int i;\n    double sqtheta;\n    sqtheta = sqsum_nodiff(3, rot);\n    if (sqtheta != 0) {\n        double theta, costheta, sintheta, theta_inverse;\n        double w[3], w_cross_pt[3], tmp;\n        theta = sqrt(sqtheta);\n        costheta = cos(theta);\n        sintheta = sin(theta);\n        theta_inverse = 1.0/theta;\n        for (i = 0; i < 3; ++i)\n            w[i] = rot[i]*theta_inverse;\n        cross_nodiff(w, pt, w_cross_pt);\n        tmp = (w[0]*pt[0]+w[1]*pt[1]+w[2]*pt[2])*(1.-costheta);\n        for (i = 0; i < 3; ++i)\n            rotatedPt[i] = pt[i]*costheta + w_cross_pt[i]*sintheta + w[i]*tmp;\n    } else {\n        double rot_cross_pt[3];\n        cross_nodiff(rot, pt, rot_cross_pt);\n        for (i = 0; i < 3; ++i)\n            rotatedPt[i] = pt[i] + rot_cross_pt[i];\n    }\n}\n\n/*\n  Differentiation of radial_distort in reverse (adjoint) mode:\n   gradient     of useful results: *rad_params *proj\n   with respect to varying inputs: *rad_params *proj\n   Plus diff mem management of: rad_params:in proj:in\n*/\nvoid radial_distort_b(const double *rad_params, double *rad_paramsb, double *\n        proj, double *projb) {\n    double rsq, L;\n    double rsqb, Lb;\n    rsq = sqsum_nodiff(2, proj);\n    L = 1. + rad_params[0]*rsq + rad_params[1]*rsq*rsq;\n    pushReal8(proj[0]);\n    proj[0] = proj[0]*L;\n    Lb = proj[1]*projb[1];\n    projb[1] = L*projb[1];\n    popReal8(&(proj[0]));\n    Lb = Lb + proj[0]*projb[0];\n    projb[0] = L*projb[0];\n    rad_paramsb[0] = rad_paramsb[0] + rsq*Lb;\n    rsqb = (rad_params[1]*2*rsq+rad_params[0])*Lb;\n    rad_paramsb[1] = rad_paramsb[1] + rsq*rsq*Lb;\n    sqsum_b(2, proj, projb, rsqb);\n}\n\nvoid radial_distort_nodiff(const double *rad_params, double *proj) {\n    double rsq, L;\n    rsq = sqsum_nodiff(2, proj);\n    L = 1. + rad_params[0]*rsq + rad_params[1]*rsq*rsq;\n    proj[0] = proj[0]*L;\n    proj[1] = proj[1]*L;\n}\n\n/*\n  Differentiation of project in reverse (adjoint) mode:\n   gradient     of useful results: *proj\n   with respect to varying inputs: *cam *X\n   Plus diff mem management of: cam:in X:in proj:in\n*/\nvoid project_b(const double *cam, double *camb, const double *X, double *Xb,\n        double *proj, double *projb) {\n    double *C = const_cast<double*>(&(cam[3]));\n    double *Cb = const_cast<double*>(&(camb[3]));\n    double Xo[3], Xcam[3];\n    double Xob[3], Xcamb[3];\n    int ii1;\n    double tempb;\n    double tempb0;\n    for (ii1 = 0; ii1 < BA_NCAMPARAMS; ii1++) /* TFIX */\n        camb[ii1] = 0.0;\n    for (ii1 = 0; ii1 < 3; ii1++)\n        Xb[ii1] = 0.0;\n    Xo[0] = X[0] - C[0];\n    Xo[1] = X[1] - C[1];\n    Xo[2] = X[2] - C[2];\n    rodrigues_rotate_point_nodiff(&(cam[0]), Xo, Xcam);\n    proj[0] = Xcam[0]/Xcam[2];\n    proj[1] = Xcam[1]/Xcam[2];\n    pushReal8Array(proj, 2); /* TFIX */\n    radial_distort_nodiff(&(cam[9]), proj);\n    pushReal8(proj[0]);\n    proj[0] = proj[0]*cam[6] + cam[7];\n    camb[6] = camb[6] + proj[1]*projb[1];\n    camb[8] = camb[8] + projb[1];\n    projb[1] = cam[6]*projb[1];\n    popReal8(&(proj[0]));\n    camb[6] = camb[6] + proj[0]*projb[0];\n    camb[7] = camb[7] + projb[0];\n    projb[0] = cam[6]*projb[0];\n    popReal8Array(proj, 2); /* TFIX */\n    radial_distort_b(&(cam[9]), &(camb[9]), proj, projb);\n    for (ii1 = 0; ii1 < 3; ++ii1)\n        Xcamb[ii1] = 0.0;\n    tempb = projb[1]/Xcam[2];\n    Xcamb[1] = Xcamb[1] + tempb;\n    Xcamb[2] = Xcamb[2] - Xcam[1]*tempb/Xcam[2];\n    projb[1] = 0.0;\n    tempb0 = projb[0]/Xcam[2];\n    Xcamb[0] = Xcamb[0] + tempb0;\n    Xcamb[2] = Xcamb[2] - Xcam[0]*tempb0/Xcam[2];\n    rodrigues_rotate_point_b(&(cam[0]), &(camb[0]), Xo, Xob, Xcam, Xcamb);\n    Xb[2] = Xb[2] + Xob[2];\n    Cb[2] = Cb[2] - Xob[2];\n    Xob[2] = 0.0;\n    Xb[1] = Xb[1] + Xob[1];\n    Cb[1] = Cb[1] - Xob[1];\n    Xob[1] = 0.0;\n    Xb[0] = Xb[0] + Xob[0];\n    Cb[0] = Cb[0] - Xob[0];\n}\n\nvoid project_nodiff(const double *cam, const double *X, double *proj) {\n    const double *C = &(cam[3]);\n    double Xo[3], Xcam[3];\n    Xo[0] = X[0] - C[0];\n    Xo[1] = X[1] - C[1];\n    Xo[2] = X[2] - C[2];\n    rodrigues_rotate_point_nodiff(&(cam[0]), Xo, Xcam);\n    proj[0] = Xcam[0]/Xcam[2];\n    proj[1] = Xcam[1]/Xcam[2];\n    radial_distort_nodiff(&(cam[9]), proj);\n    proj[0] = proj[0]*cam[6] + cam[7];\n    proj[1] = proj[1]*cam[6] + cam[8];\n}\n\n/*\n  Differentiation of compute_reproj_error in reverse (adjoint) mode:\n   gradient     of useful results: *err\n   with respect to varying inputs: *err *w *cam *X\n   RW status of diff variables: *err:in-out *w:out *cam:out *X:out\n   Plus diff mem management of: err:in w:in cam:in X:in\n*/\n// cam: 11 camera in format [r1 r2 r3 C1 C2 C3 f u0 v0 k1 k2]\n//            r1, r2, r3 are angle - axis rotation parameters(Rodrigues)\n//            [C1 C2 C3]' is the camera center\n//            f is the focal length in pixels\n//            [u0 v0]' is the principal point\n//            k1, k2 are radial distortion parameters\n// X: 3 point\n// feats: 2 feature (x,y coordinates)\n// reproj_err: 2\n// projection function:\n// Xcam = R * (X - C)\n// distorted = radial_distort(projective2euclidean(Xcam), radial_parameters)\n// proj = distorted * f + principal_point\n// err = sqsum(proj - measurement)\nvoid compute_reproj_error_b(const double *cam, double *camb, const double *X,\n        double *Xb, const double *w, double *wb, const double *feat, double *\n        err, double *errb) {\n    double proj[2];\n    double projb[2];\n    int ii1;\n    pushReal8Array(proj, 2);\n    project_nodiff(cam, X, proj);\n    for (ii1 = 0; ii1 < 2; ++ii1)\n        projb[ii1] = 0.0;\n    *wb = (proj[1]-feat[1])*errb[1];\n    projb[1] = projb[1] + (*w)*errb[1];\n    errb[1] = 0.0;\n    *wb = *wb + (proj[0]-feat[0])*errb[0];\n    projb[0] = projb[0] + (*w)*errb[0];\n    errb[0] = 0.0;\n    popReal8Array(proj, 2);\n    project_b(cam, camb, X, Xb, proj, projb);\n}\n\n/*\n  Differentiation of compute_zach_weight_error in reverse (adjoint) mode:\n   gradient     of useful results: *err\n   with respect to varying inputs: *err *w\n   RW status of diff variables: *err:in-out *w:out\n   Plus diff mem management of: err:in w:in\n*/\nvoid compute_zach_weight_error_b(const double *w, double *wb, double *err,\n        double *errb) {\n    *wb = -(2*(*w)*(*errb));\n    *errb = 0.0;\n}\n\n}\n\n\n#include <adept_source.h>\n#include <adept.h>\n#include <adept_arrays.h>\nusing adept::adouble;\nusing adept::aVector;\n\nnamespace adeptTest {\n\ntemplate<typename T>\nvoid cross(\n    const T* const a,\n    const T* const b,\n    T* out)\n{\n    out[0] = a[1] * b[2] - a[2] * b[1];\n    out[1] = a[2] * b[0] - a[0] * b[2];\n    out[2] = a[0] * b[1] - a[1] * b[0];\n}\n\n////////////////////////////////////////////////////////////\n//////////////////// Declarations //////////////////////////\n////////////////////////////////////////////////////////////\n\n// cam: 11 camera in format [r1 r2 r3 C1 C2 C3 f u0 v0 k1 k2]\n//            r1, r2, r3 are angle - axis rotation parameters(Rodrigues)\n//            [C1 C2 C3]' is the camera center\n//            f is the focal length in pixels\n//            [u0 v0]' is the principal point\n//            k1, k2 are radial distortion parameters\n// X: 3 point\n// feats: 2 feature (x,y coordinates)\n// reproj_err: 2\n// projection function:\n// Xcam = R * (X - C)\n// distorted = radial_distort(projective2euclidean(Xcam), radial_parameters)\n// proj = distorted * f + principal_point\n// err = sqsum(proj - measurement)\ntemplate<typename T>\nvoid computeReprojError(\n    const T* const cam,\n    const T* const X,\n    const T* const w,\n    const double* const feat,\n    T *err);\n\n// w: 1\n// w_err: 1\ntemplate<typename T>\nvoid computeZachWeightError(const T* const w, T* err);\n\n// n number of cameras\n// m number of points\n// p number of observations\n// cams: 11*n cameras in format [r1 r2 r3 C1 C2 C3 f u0 v0 k1 k2]\n//            r1, r2, r3 are angle - axis rotation parameters(Rodrigues)\n//            [C1 C2 C3]' is the camera center\n//            f is the focal length in pixels\n//            [u0 v0]' is the principal point\n//            k1, k2 are radial distortion parameters\n// X: 3*m points\n// obs: 2*p observations (pairs cameraIdx, pointIdx)\n// feats: 2*p features (x,y coordinates corresponding to observations)\n// reproj_err: 2*p errors of observations\n// w_err: p weight \"error\" terms\n// projection function:\n// Xcam = R * (X - C)\n// distorted = radial_distort(projective2euclidean(Xcam), radial_parameters)\n// proj = distorted * f + principal_point\n// err = sqsum(proj - measurement)\ntemplate<typename T>\nvoid ba_objective(int n, int m, int p,\n    const T* const cams,\n    const T* const X,\n    const T* const w,\n    const int* const obs,\n    const double* const feats,\n    T* reproj_err,\n    T* w_err);\n\n// rot: 3 rotation parameters\n// pt: 3 point to be rotated\n// rotatedPt: 3 rotated point\n// this is an efficient evaluation (part of\n// the Ceres implementation)\n// easy to understand calculation in matlab:\n//  theta = sqrt(sum(w. ^ 2));\n//  n = w / theta;\n//  n_x = au_cross_matrix(n);\n//  R = eye(3) + n_x*sin(theta) + n_x*n_x*(1 - cos(theta));\ntemplate<typename T>\nvoid rodrigues_rotate_point(\n    const T* const rot,\n    const T* const pt,\n    T *rotatedPt);\n\n////////////////////////////////////////////////////////////\n//////////////////// Definitions ///////////////////////////\n////////////////////////////////////////////////////////////\n\ntemplate<typename T>\nT sqsum(int n, const T* const x)\n{\n    T res = 0;\n    for (int i = 0; i < n; i++)\n        res = res + x[i] * x[i];\n    return res;\n}\n\ntemplate<typename T>\nvoid rodrigues_rotate_point(\n    const T* const rot,\n    const T* const pt,\n    T *rotatedPt)\n{\n    T sqtheta = sqsum(3, rot);\n    if (sqtheta != 0)\n    {\n        T theta, costheta, sintheta, theta_inverse,\n            w[3], w_cross_pt[3], tmp;\n\n        theta = sqrt(sqtheta);\n        costheta = cos(theta);\n        sintheta = sin(theta);\n        theta_inverse = 1.0 / theta;\n\n        for (int i = 0; i < 3; i++)\n            w[i] = rot[i] * theta_inverse;\n\n        cross(w, pt, w_cross_pt);\n\n        tmp = (w[0] * pt[0] + w[1] * pt[1] + w[2] * pt[2]) *\n            (1. - costheta);\n\n        for (int i = 0; i < 3; i++)\n            rotatedPt[i] = pt[i] * costheta + w_cross_pt[i] * sintheta + w[i] * tmp;\n    }\n    else\n    {\n        T rot_cross_pt[3];\n        cross(rot, pt, rot_cross_pt);\n\n        for (int i = 0; i < 3; i++)\n            rotatedPt[i] = pt[i] + rot_cross_pt[i];\n    }\n}\n\ntemplate<typename T>\nvoid radial_distort(\n    const T* const rad_params,\n    T *proj)\n{\n    T rsq, L;\n    rsq = sqsum(2, proj);\n    L = 1. + rad_params[0] * rsq + rad_params[1] * rsq * rsq;\n    proj[0] = proj[0] * L;\n    proj[1] = proj[1] * L;\n}\n\ntemplate<typename T>\nvoid project(const T* const cam,\n    const T* const X,\n    T* proj)\n{\n    const T* const C = &cam[3];\n    T Xo[3], Xcam[3];\n\n    Xo[0] = X[0] - C[0];\n    Xo[1] = X[1] - C[1];\n    Xo[2] = X[2] - C[2];\n\n    rodrigues_rotate_point(&cam[0], Xo, Xcam);\n\n    proj[0] = Xcam[0] / Xcam[2];\n    proj[1] = Xcam[1] / Xcam[2];\n\n    radial_distort(&cam[9], proj);\n\n    proj[0] = proj[0] * cam[6] + cam[7];\n    proj[1] = proj[1] * cam[6] + cam[8];\n}\n\ntemplate<typename T>\nvoid computeReprojError(\n    const T* const cam,\n    const T* const X,\n    const T* const w,\n    const double* const feat,\n    T *err)\n{\n    T proj[2];\n    project(cam, X, proj);\n\n    err[0] = (*w)*(proj[0] - feat[0]);\n    err[1] = (*w)*(proj[1] - feat[1]);\n}\n\ntemplate<typename T>\nvoid computeZachWeightError(const T* const w, T* err)\n{\n    *err = 1 - (*w)*(*w);\n}\n\ntemplate<typename T>\nvoid ba_objective(int n, int m, int p,\n    const T* const cams,\n    const T* const X,\n    const T* const w,\n    const int* const obs,\n    const double* const feats,\n    T* reproj_err,\n    T* w_err)\n{\n    for (int i = 0; i < p; i++)\n    {\n        int camIdx = obs[i * 2 + 0];\n        int ptIdx = obs[i * 2 + 1];\n        computeReprojError(&cams[camIdx * BA_NCAMPARAMS], &X[ptIdx * 3],\n            &w[i], &feats[i * 2], &reproj_err[2 * i]);\n    }\n\n    for (int i = 0; i < p; i++)\n    {\n        computeZachWeightError(&w[i], &w_err[i]);\n    }\n}\n};\n\n\nvoid adept_compute_reproj_error(\n    double const* cam,\n    double * dcam,\n    double const* X,\n    double * dX,\n    double const* w,\n    double * wb,\n    double const* feat,\n    double *err,\n    double *derr\n)\n{\n\n\n    adept::Stack stack;\n\n      adouble acam[BA_NCAMPARAMS];\n      adept::set_values(acam, BA_NCAMPARAMS, cam);\n\n      adouble aX[3];\n      adept::set_values(aX, 3, X);\n\n      adouble aw;\n      aw.set_value(*w);\n\n      adouble areproj_err[2];\n\n      stack.new_recording();\n\n      adeptTest::computeReprojError(acam, aX, &aw, feat, areproj_err);\n\n      for(unsigned i=0; i<2; i++) areproj_err[i].set_gradient(derr[i]);\n\n      stack.compute_adjoint();\n\n      *wb = aw.get_gradient();\n      adept::get_gradients(aX, 3, dX);\n      adept::get_gradients(acam, BA_NCAMPARAMS, dcam);\n}\n\nvoid adept_compute_zach_weight_error(double const* w, double* dw, double* err, double* derr) {\n    adept::Stack stack;\n\n      adouble aw;\n      aw.set_value(*w);\n\n      adouble aw_err;\n\n      stack.new_recording();\n      adeptTest::computeZachWeightError(&aw, &aw_err);\n      aw_err.set_gradient(1.);\n      stack.compute_adjoint();\n\n      *dw = aw.get_gradient();\n}\n", "meta": {"hexsha": "b71e05a0a011047dfd4747ccdc55575978407bc7", "size": 26429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/benchmarks/ba/ba.cpp", "max_stars_repo_name": "anandijain/Enzyme", "max_stars_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 674.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T17:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:18:11.000Z", "max_issues_repo_path": "enzyme/benchmarks/ba/ba.cpp", "max_issues_repo_name": "anandijain/Enzyme", "max_issues_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2020-10-07T00:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T16:46:58.000Z", "max_forks_repo_path": "enzyme/benchmarks/ba/ba.cpp", "max_forks_repo_name": "anandijain/Enzyme", "max_forks_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T14:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:51:07.000Z", "avg_line_length": 28.9157549234, "max_line_length": 125, "alphanum_fraction": 0.5348291649, "num_tokens": 8708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6022622632019238}}
{"text": "#include <tiny.h>\n#include <convex.h>\n\n#define BOOST_AUTO_TEST_MAIN\n#include <boost/test/auto_unit_test.hpp>\n#include <boost/test/unit_test_suite.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include <boost/test/test_tools.hpp>\n\nBOOST_AUTO_TEST_SUITE(convex_signed_distance_to_vertex_edge_vp);\n\nBOOST_AUTO_TEST_CASE(case_by_case_test)\n{\n  typedef tiny::MathTypes<double>     math_types;\n  typedef math_types::vector3_type   vector3_type;\n  typedef math_types::real_type      real_type;\n\n\n  vector3_type a = vector3_type::make(1.0, 0.0, 0.0);\n  vector3_type b = vector3_type::make(0.0, 0.0, 0.0);\n\n  // First we use a test point that does not lie on the line\n\n  // Front side of A voronoi plane\n  {\n    vector3_type p = vector3_type::make( 2.0, 1.0,  1.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\n  }\n  // Back side of A voronoi plane\n  {\n    vector3_type p = vector3_type::make( 0.0, 1.0,  1.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\n  }\n  // In A voronoi plane\n  {\n    vector3_type p = vector3_type::make( 1.0, 1.0,  1.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\n  }\n\n  // Front side of B voronoi plane\n  {\n    vector3_type p = vector3_type::make( -1.0, 1.0,  1.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\n  }\n  // Back side of B voronoi plane\n  {\n    vector3_type p = vector3_type::make( 1.0, 1.0,  1.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\n  }\n  // In B voronoi plane\n  {\n    vector3_type p = vector3_type::make( 0.0, 1.0,  1.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\n  }\n\n  // Second we use a test point that lies on the line\n\n  // Front side of A voronoi plane\n  {\n    vector3_type p = vector3_type::make( 2.0, 0.0,  0.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\n  }\n  // Back side of A voronoi plane\n  {\n    vector3_type p = vector3_type::make( 0.0, 0.0,  0.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\n  }\n  // In A voronoi plane\n  {\n    vector3_type p = vector3_type::make( 1.0, 0.0,  0.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, a, b);\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\n  }\n\n  // Front side of B voronoi plane\n  {\n    vector3_type p = vector3_type::make( -1.0, 0.0,  0.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\n    BOOST_CHECK_CLOSE( sign_p, 1.0, 0.01 );\n  }\n  // Back side of B voronoi plane\n  {\n    vector3_type p = vector3_type::make( 1.0, 0.0,  0.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\n    BOOST_CHECK_CLOSE( sign_p, -1.0, 0.01 );\n  }\n  // In B voronoi plane\n  {\n    vector3_type p = vector3_type::make( 0.0, 0.0,  0.0);\n    real_type sign_p = 0.0; \n    sign_p = convex::signed_distance_to_vertex_edge_voronoi_plane(p, b, a);\n    BOOST_CHECK_CLOSE( sign_p, 0.0, 0.01 );\n  }\n\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n", "meta": {"hexsha": "52387c8f8406e3bda629750f1f4feb7ec5030ba5", "size": 3720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PROX/FOUNDATION/CONVEX/unit_tests/convex_sign_dist2vert_edge_vp/convex_sign_dist2vert_edge_vp.cpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/FOUNDATION/CONVEX/unit_tests/convex_sign_dist2vert_edge_vp/convex_sign_dist2vert_edge_vp.cpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/FOUNDATION/CONVEX/unit_tests/convex_sign_dist2vert_edge_vp/convex_sign_dist2vert_edge_vp.cpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7948717949, "max_line_length": 75, "alphanum_fraction": 0.6704301075, "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782012, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.6021599238760713}}
{"text": "#include <random>\n#include <cmath>\n#include <armadillo>\n\n#define PERIODIC_UP(i, size) (((i) >= (size)) ? ((i) - (size)) : ((i)))\n#define PERIODIC_DOWN(i, size) (((i) < 0) ? ((i) + (size)) : ((i)))\n\nvoid metropolis_sampling(int num_spins, int num_cycles, double temperature,\n        double *expectation_values)\n{\n    std::random_device rd;\n    std::mt19937_64 generator(rd());\n\n    std::uniform_real_distribution<double> distribution(0.0, 1.0);\n\n    double energy = 0;\n    double magnetic_moment = 0;\n    double diff_zero = 8;\n    double diff_step = 4;\n\n    // Create spin matrix\n    arma::mat spin_matrix = arma::zeros<arma::mat>(num_spins, num_spins);\n    // Fill spin matrix with ones\n    spin_matrix.ones();\n\n    // Calculate initial energy for all spin up states\n    expectation_values[0] = -2*arma::sum(arma::sum(spin_matrix));\n    // Calculate initial magnetic moment\n    expectation_values[1] = arma::sum(arma::sum(spin_matrix));\n\n    arma::vec energy_difference = arma::zeros<arma::mat>(5);\n\n    for (int i = 0; i < 5; i++) {\n        energy_difference(i) = exp(-(-diff_zero + i*diff_step)/temperature);\n    }\n\n    for (int cycle = 0; cycle < num_cycles; cycle++) {\n        for (int i = 0; i < num_spins; i++) {\n            for (int j = 0; j < num_spins; j++) {\n                int ix = (int) (distribution(generator) * num_spins);\n                int iy = (int) (distribution(generator) * num_spins);\n\n                int high_ix = PERIODIC_UP(ix + 1, num_spins);\n                int low_ix = PERIODIC_DOWN(ix - 1, num_spins);\n                int high_iy = PERIODIC_UP(iy + 1, num_spins);\n                int low_iy = PERIODIC_DOWN(iy - 1, num_spins);\n\n                int delta_energy = 2*spin_matrix(ix, iy)\n                    * (spin_matrix(ix, low_iy) + spin_matrix(ix, high_iy)\n                       + spin_matrix(low_ix, iy) + spin_matrix(high_ix, iy));\n\n                int diff_index = (delta_energy + diff_zero)/diff_step;\n                if (distribution(generator) <= energy_difference(diff_index)) {\n                    spin_matrix(ix, iy) *= -1.0;\n                    magnetic_moment += 2*spin_matrix(ix, iy);\n                    energy += delta_energy;\n                }\n            }\n        }\n        expectation_values[0] += energy;\n        expectation_values[1] += magnetic_moment;\n    }\n}\n", "meta": {"hexsha": "85418aba470befc6fc79e286fba268f99b2f37a9", "size": 2318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/metropolis_sampling.cpp", "max_stars_repo_name": "Schoyen/isingmodel", "max_stars_repo_head_hexsha": "114fac40c5c5339186a17186f071987abd4477c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/metropolis_sampling.cpp", "max_issues_repo_name": "Schoyen/isingmodel", "max_issues_repo_head_hexsha": "114fac40c5c5339186a17186f071987abd4477c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/metropolis_sampling.cpp", "max_forks_repo_name": "Schoyen/isingmodel", "max_forks_repo_head_hexsha": "114fac40c5c5339186a17186f071987abd4477c9", "max_forks_repo_licenses": ["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.21875, "max_line_length": 79, "alphanum_fraction": 0.572907679, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240964782011, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6021599129635512}}
{"text": "#include \"PalindromeQuality.hpp\"\n#include \"span.hpp\"\n#include <cmath>\n\nusing std::runtime_error;\nusing std::cout;\nusing std::cerr;\nusing std::pow;\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\nusing namespace boost::accumulators;\nusing namespace shasta;\n\nusing stats_accumulator = accumulator_set<float, features<tag::count, tag::mean, tag::variance>>;\n\n\ndouble qualityCharToErrorProbability(char q) {\n    return pow(10, double(q - 33) / -10.0);\n}\n\n\nbool shasta::isPalindromic(\n        span<char> qualities,\n        double relativeMeanDifference,\n        double minimumMean,\n        double minimumVariance\n){\n\n    bool isPalindromic = false;\n\n    stats_accumulator leftStats;\n    stats_accumulator rightStats;\n\n    auto length = qualities.size();\n\n    // Don't bother classifying any reads that would have less than 3 scores per side\n    if (length < 6){\n        return false;\n    }\n\n    size_t midpoint = length/2;\n\n    for (size_t i=0; i<midpoint; i++){\n        const auto q = qualities[i];\n        auto p = qualityCharToErrorProbability(q);\n\n        leftStats(p);\n    }\n\n    for (size_t i=midpoint; i<length; i++){\n        const auto q = qualities[i];\n        auto p = qualityCharToErrorProbability(q);\n\n        rightStats(p);\n    }\n\n    float leftMean = mean(leftStats);\n    float leftVariance = variance(leftStats);\n\n    float rightMean = mean(rightStats);\n    float rightVariance = variance(rightStats);\n\n    // Compare the mean and variance using thresholds derived empirically from some palindromic reads\n    if (rightMean - leftMean > relativeMeanDifference and rightMean >= minimumMean){\n        if (rightVariance > leftVariance and rightVariance > minimumVariance){\n            isPalindromic = true;\n        }\n    }\n\n    return isPalindromic;\n}\n", "meta": {"hexsha": "c95b4814b777a9ff1c8a661d6cc9b0e72bf3dd17", "size": 1804, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PalindromeQuality.cpp", "max_stars_repo_name": "chanzuckerberg/shasta", "max_stars_repo_head_hexsha": "a8933d5aade5c8cc8b92852bf3092fb32bf30b22", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 267.0, "max_stars_repo_stars_event_min_datetime": "2018-07-31T16:12:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:57:53.000Z", "max_issues_repo_path": "src/PalindromeQuality.cpp", "max_issues_repo_name": "rlorigro/shasta", "max_issues_repo_head_hexsha": "06522d841362ee22265d006062759b0cbcf3a1ea", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": 140.0, "max_issues_repo_issues_event_min_datetime": "2018-08-10T14:14:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T22:05:05.000Z", "max_forks_repo_path": "src/PalindromeQuality.cpp", "max_forks_repo_name": "chanzuckerberg/shasta", "max_forks_repo_head_hexsha": "a8933d5aade5c8cc8b92852bf3092fb32bf30b22", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 47.0, "max_forks_repo_forks_event_min_datetime": "2018-09-28T18:29:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T02:45:40.000Z", "avg_line_length": 24.3783783784, "max_line_length": 101, "alphanum_fraction": 0.6796008869, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6021599087451847}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// vector_space::functional::equal.hpp                                       //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_VECTOR_SPACE_FUNCTIONAL_EQUAL_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_VECTOR_SPACE_FUNCTIONAL_EQUAL_HPP_ER_2009\n#include <boost/call_traits.hpp>\n#include <ostream>\n#include <boost/range.hpp>\n#include <boost/mpl/nested_type.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <boost/vector_space/functional/l2_distance_squared.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace vector_space{\n\n// This is a predicate for (x == y) iff (|| x - y || == 0).\n//\n// Requirements:\n// F<R> distance(x);        Construction\n// distance(y)              Returns an object of type range_value<R>::type\n//\n// Usage:\n// functor<R,F> fun(x,eps);\n// fun(y) returns true if distance(y) < eps\ntemplate<typename R, template<typename> class F = l2_distance_squared> \nclass equal{\n    typedef F<R> arg_;\n    typedef typename mpl::nested_type<arg_>::type distance_type;    \n    typedef typename remove_reference<R>::type const_range_type;\n    typedef typename remove_const<const_range_type>::type range_type;\n    typedef typename range_value<range_type>::type value_type;\npublic:\n            \n    //Construction\n    equal(typename call_traits<R>::param_type x,value_type eps);\n    equal(typename call_traits<R>::param_type x);\n    equal(const equal& that);\n    equal& operator=(const equal& that);\n            \n    //Evaluate\n    typedef bool result_type;\n\n    template<typename R1> result_type operator()(const R1& y)const;\n    result_type epsilon()const;\n                                               \n//private:\n    equal();\n    distance_type distance_;\n    value_type eps_;\n    static value_type default_eps_;\n};\n\n// \ntemplate<typename R, template<typename> class F>\nstd::ostream& operator<<(std::ostream& out,const equal<R,F>& e){\n    out << '(' <<  e.epsilon() << ')';\n    return out;\n}\n\n// Static members\ntemplate<typename R, template<typename> class F>\ntypename equal<R,F>::value_type\nequal<R,F>::default_eps_ \n    = math::tools::epsilon<typename equal<R,F>::value_type>();\n\ntemplate<typename R, template<typename> class F>\ntypename equal<R,F>::result_type \nequal<R,F>::epsilon()const{\n    return eps_;\n}\n\n//Construction\n\ntemplate<typename R, template<typename> class F>\nequal<R,F>::equal(typename call_traits<R>::param_type x,value_type eps)\n:distance_(x),eps_(eps){}\n\ntemplate<typename R, template<typename> class F>\nequal<R,F>::equal(typename call_traits<R>::param_type x)\n:distance_(x),eps_(default_eps_){}\n\ntemplate<typename R, template<typename> class F>\nequal<R,F>::equal(const equal& that)\n:distance_(that.distance_),eps_(that.eps_){}\n\ntemplate<typename R, template<typename> class F>\nequal<R,F>& \nequal<R,F>::operator=(const equal& that){\n    if(&that!=this){\n        distance_ = that.distance_;\n        eps_ = that.eps_;\n    }\n    return *this;\n}\n    \n// Evaluate\ntemplate<typename R, template<typename> class F>\ntemplate<typename R1> \ntypename equal<R,F>::result_type \nequal<R,F>::operator()(const R1& y)const{\n    return (distance_(y)<eps_);\n}\n\n}// vector_space\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "e23883fb750b83b803e8b222c7ad1e2480714f3f", "size": 3679, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vector_space/boost/vector_space/functional/equal.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vector_space/boost/vector_space/functional/equal.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vector_space/boost/vector_space/functional/equal.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7155172414, "max_line_length": 79, "alphanum_fraction": 0.6401195977, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.602159903907871}}
{"text": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschr\u00e4nkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// With contributions from Cornelius Steinhardt\n\n#ifndef MTL_MATRIX_EIGENVALUE_SYMMETRIC_INCLUDE\n#define MTL_MATRIX_EIGENVALUE_SYMMETRIC_INCLUDE\n\n#include <cmath>\n#include <boost/utility.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/make_copy_or_reference.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/concept/magnitude.hpp>\n#include <boost/numeric/mtl/operation/conj.hpp>\n#include <boost/numeric/mtl/operation/diagonal.hpp>\n#include <boost/numeric/mtl/operation/givens.hpp>\n#include <boost/numeric/mtl/operation/hessenberg.hpp>\n#include <boost/numeric/mtl/operation/householder.hpp>\n#include <boost/numeric/mtl/operation/qr.hpp>\n#include <boost/numeric/mtl/operation/rank_one_update.hpp>\n#include <boost/numeric/mtl/operation/signum.hpp>\n#include <boost/numeric/mtl/operation/trans.hpp>\n\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/vector/parameter.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl { namespace matrix {\n\n\n/// Eigenvalues of symmetric matrix A with implicit QR algorithm\n// Return Diagonalmatrix with eigenvalues as diag(A)\ntemplate <typename Matrix>\nmtl::vector::dense_vector<typename Collection<Matrix>::value_type, vector::parameters<> >\ninline qr_sym_imp(const Matrix& A)\n{\n    vampir_trace<5010> tracer;\n    using std::abs; using mtl::signum; using mtl::real;\n    typedef typename Collection<Matrix>::value_type   value_type;\n    typedef typename Magnitude<value_type>::type      magnitude_type; // to multiply with 2 not 2+0i\n    typedef typename Collection<Matrix>::size_type    size_type;\n    size_type        ncols = num_cols(A), nrows = num_rows(A), N;\n    value_type       zero= math::zero(A[0][0]), h00, h10, h11, beta, mu, a, b, tol;\n    const magnitude_type two(2);\n    Matrix           Q(nrows,ncols), H(nrows,ncols),  G(2,2);\n\n    tol= 1.0e-8; // ????evtl ein Iterator wie bei den Gleichungssystemen, Problem: Keine Rechte Seite bzw b\n\n    MTL_THROW_IF(ncols != nrows , matrix_not_square());\n\n    // Hessenberg_form of Matrix A\n    H= hessenberg(A);\n    N= nrows;\n\n    // QR_algo with implizit sym QR-step from Wilkinson\n    while (1) {\n\th00= H[N-2][N-2];\n\th10= H[N-1][N-2];\n\th11= H[N-1][N-1];\n\n\t//reduction, residuum and watch for breakdown\n\tif(abs(h10) < tol * abs(h11 + h00)) \n\t    N--;\t\n\tif (N < 2) \n\t    break;\n\t\n\t// Wilkinson_shift\n\tbeta= (h00 - h11) / two;   \n\tmu = h11 + (beta != zero ? beta - signum(beta) * sqrt(beta * beta + h10 * h10) : -h10);\n\ta= H[0][0] - mu, b= H[1][0];\n\n\t//implizit QR-step\n\tfor (size_type k = 0; k < N - 1; k++) {\n\t    givens<Matrix>(H, a, b).trafo(k);\n\t    if (k < N - 2)\n\t\ta= H[k+1][k], b= H[k+2][k];\t    \n\t}\n    }\n    return diagonal(H);\n}\n\n\n/// Evaluation of eigenvalues with QR-Algorithm of matrix A\n// Return Diagonalmatrix with eigenvalues as diag(A)\ntemplate <typename Matrix>\nmtl::vector::dense_vector<typename Collection<Matrix>::value_type, vector::parameters<> >\ninline qr_algo(const Matrix& A, typename Collection<Matrix>::size_type itMax)\n{\n    vampir_trace<5011> tracer;\n    typedef typename Collection<Matrix>::size_type    size_type;\n    size_type        ncols = num_cols(A), nrows = num_rows(A);\n    Matrix           Q(nrows, ncols), H(nrows, ncols), R(nrows, ncols);\n\n    MTL_THROW_IF(ncols != nrows , matrix_not_square());\n\n    H= hessenberg(A);\n    for (size_type i = 0; i < itMax; i++) {\n\tboost::tie(Q, R)= qr_factors(H);\n\tH= R * Q;\n    }\n    return diagonal(H);\n}\n\n\n# ifdef MTL_SYMMETRIC_EIGENVALUE_WITH_QR\n\n/// Calculation of eigenvalues of symmetric matrix A\ntemplate <typename Matrix>\nmtl::vector::dense_vector<typename Collection<Matrix>::value_type, vector::parameters<> >\ninline eigenvalue_symmetric(const Matrix& A, typename Collection<Matrix>::size_type itMax)\n{\n    return qr_algo(A, itMax == 0 ? num_rows(A) : itMax);\n}\n\n#else \n\n/// Calculation of eigenvalues of symmetric matrix A\ntemplate <typename Matrix>\nmtl::vector::dense_vector<typename Collection<Matrix>::value_type, vector::parameters<> >\ninline eigenvalue_symmetric(const Matrix& A, typename Collection<Matrix>::size_type)\n{\n    typedef dense2D<typename Collection<Matrix>::value_type, parameters<> >    arg_type;\n    make_in_copy_or_reference<arg_type, Matrix>  copy_or_ref(A);\n    return qr_sym_imp(copy_or_ref.value);\n}\n\n#endif\n\n#if 0 // Too nasty to get it through all warnings :-!\n\n/// Calculation of eigenvalues of symmetric matrix A\ntemplate <typename Matrix>\nmtl::vector::dense_vector<typename Collection<Matrix>::value_type, vector::parameters<> >\ninline eigenvalue_symmetric(const Matrix& A, \n\t\t\t    typename Collection<Matrix>::size_type itMax= 0)\n{\n    vampir_trace<5012> tracer;\n# ifdef MTL_SYMMETRIC_EIGENVALUE_WITH_QR\n    return qr_algo(A, itMax == 0 ? num_rows(A) : itMax);\n# else\n    itMax= 0; // for not yelling at unused variable\n    // qr_sym_imp works only with dense matrices of dynamic size, for other types copy\n    typedef dense2D<typename Collection<Matrix>::value_type>    arg_type;\n    make_in_copy_or_reference<arg_type, Matrix>  copy_or_ref(A);\n    return qr_sym_imp(copy_or_ref.value);\n# endif\n}\n\n#endif\n\ntemplate <typename Matrix>\nmtl::vector::dense_vector<typename Collection<Matrix>::value_type, vector::parameters<> >\ninline eigenvalue_symmetric(const Matrix& A)\n{\n    return eigenvalue_symmetric(A, 0);\n} \n\n\n}} // namespace mtl::matrix\n\n\n#endif // MTL_MATRIX_EIGENVALUE_SYMMETRIC_INCLUDE\n\n", "meta": {"hexsha": "ef1f6f144d4e482fe8019ba9b56a107108e9d85f", "size": 6018, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/eigenvalue_symmetric.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/eigenvalue_symmetric.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/operation/eigenvalue_symmetric.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.808988764, "max_line_length": 107, "alphanum_fraction": 0.7160186108, "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.6021598905766943}}
{"text": "#include <cmath>\n#include <string>\n#include <coodinate_system.hpp>\n#include <tle.hpp>\n#include <orbit.hpp>\n#include <ctime>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include \"mathematic_utils.hpp\"\n\nusing namespace Eigen;\n\n// \u5730\u5fc3\u76f4\u4ea4\u5ea7\u6a19\u7cfb\u3067\u3001\n//  \u5c04\u70b9\u4f4d\u7f6e(P0)\n//  \u885b\u661f\u4f4d\u7f6e(P1)\n//  \u8ecc\u9053\u63a5\u5e73\u9762\u6cd5\u7dda(N)\n// \u304b\u3089\u3001\n//  \u6955\u5186\u4f53(E(O,R)) \u9762\u4e0a\u306e\u7740\u5f3e\u70b9\u3092\u5f97\u308b\nVector3dSet find_impact_point(\n    const Vector3d& P0, const Vector3d& P1, const Vector3d& N,\n    const Vector3d& O, const Vector3d& R)\n{\n  Vector3d v1 = P1 - P0;                   // \u767a\u5c04\u30d3\u30fc\u30e0\u306e\u5411\u304d\n  Vector3d v2 = reflect(v1,N);             // \u53cd\u5c04\u30d3\u30fc\u30e0\u306e\u5411\u304d\n  Vector3dSet Q = intersection(P1,v2,O,R); // \u7740\u5f3e\u70b9\u5019\u88dc\n  Vector3dSet X = neighoring(P1,Q);        // \u7740\u5f3e\u70b9\u5019\u88dc\u306e\u3046\u3061P1\u306b\u8fd1\u3044\u70b9\n\n  return X;\n}\n\n// \u6e2c\u5730\u5ea7\u6a19\u7cfb\u3067\u3001\n//  \u5c04\u70b9\u4f4d\u7f6e(P)\n//  \u4f7f\u3046\u4eba\u5de5\u885b\u661f\u306eTLE\n//  \u73fe\u5728\u6642\u523b t\n// \u304b\u3089\u3001\u5730\u4e0a\u306e\u7740\u5f3e\u70b9\u3092\u5f97\u308b\nbool find_impact(const geodetic& P, geodetic* X,\n                 const std::string& tle_str, const time_t* t)\n{\n  // TLE\u8aad\u307f\u8fbc\u307f\n  TLE tle;\n  std::string tle_str1 = tle_str.substr(0,69);\n  std::string tle_str2 = tle_str.substr(69,69);\n  tle.set(tle_str1,tle_str2);\n\n  // \u5730\u7403\u81ea\u8ee2\u89d2\n  double Pg = 2. * M_PI * greenwich_sidereal_time(t) / 24.;\n\n  // \u5730\u5fc3\u76f4\u4ea4\u5ea7\u6a19\u7cfb\u3067\u306e\u5c04\u70b9\u5ea7\u6a19\n  rectangular Pr = P.toRectangular(Pg);\n  Eigen::Vector3d P0(Pr.X, Pr.Y, Pr.Z);\n\n  // \u8ecc\u9053\n  orbit orb;\n  orb.setTLE(&tle);\n  double since_day = orb.elapsed_day(t);\n  double since_min = since_day * 1440.;\n\n  double motion = tle.motion; // revolutions per day\n  double dayp6  = 1. / (6. * motion); // day for 1/6 revolution.\n  double minp6  = dayp6 * 1440.;\n\n  // \u4eba\u5de5\u885b\u661f\u306e\u6240\u5728\u5730\n  double position0[3],position1[3],position2[3];\n  double velocity0[3],velocity1[3],velocity2[3];\n  orb.sgp(position0,velocity0,since_min - minp6);\n  orb.sgp(position1,velocity1,since_min);\n  orb.sgp(position2,velocity2,since_min + minp6);\n\n  Eigen::Vector3d p0(position0);\n  Eigen::Vector3d p1(position1); // \u4eba\u5de5\u885b\u661f\u306e\u73fe\u5728\u5730\u306e\u4f4d\u7f6e\u30d9\u30af\u30c8\u30eb\n  Eigen::Vector3d p2(position2);\n  Eigen::Vector3d v1(velocity1);\n\n  Eigen::Vector3d n0 = normalize(p0.cross(p2)); // \u8ecc\u9053\u9762\u306e\u6cd5\u7dda\u30d9\u30af\u30c8\u30eb\n  Eigen::Vector3d n1 = v1.cross(normalize(n0)); // \u53cd\u5c04\u9762\u306e\u6cd5\u7dda\u30d9\u30af\u30c8\u30eb\n\n  Eigen::Vector3d O(0.,0.,0.);\n  Eigen::Vector3d R(6378.137,6378.137,6356.752); // \u5730\u7403\u6955\u5186\u4f53\n  Vector3dSet Q = find_impact_point(P0,p1,n1,O,R);\n\n  rectangular Xr;\n  bool f = (Q.size() != 0);\n  if (f) {\n    Eigen::Vector3d q = Q[0];\n    Xr.X = q[0];\n    Xr.Y = q[1];\n    Xr.Z = q[2];\n  } else {\n    Xr.X = 0.0;\n    Xr.Y = 0.0;\n    Xr.Z = 0.0;\n  }\n\n  *X = Xr.toGeodetic(Pg); // \u6e2c\u5730\u5ea7\u6a19\u7cfb\u306b\u5909\u63db\n  if      ( X->latitude  >  M_PI) X->latitude  -= 2.*M_PI;\n  else if ( X->latitude  < -M_PI) X->latitude  += 2.*M_PI;\n  if      ( X->longitude >  M_PI) X->longitude -= 2.*M_PI;\n  else if ( X->longitude < -M_PI) X->longitude += 2.*M_PI;\n\n  return f;\n}\n\n", "meta": {"hexsha": "34f1f5ba8b388f7981801d9d58cf9790a04eda55", "size": 2633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/satellite_reflector.cpp", "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/satellite_reflector.cpp", "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/satellite_reflector.cpp", "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": 25.5631067961, "max_line_length": 64, "alphanum_fraction": 0.629699962, "num_tokens": 1158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133498259924, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.6021421923412068}}
{"text": "/* test_non_central_chi_squared.cpp\r\n *\r\n * Copyright Steven Watanabe 2011\r\n * Copyright Thijs van den Berg 2014\r\n * Distributed under the Boost Software License, Version 1.0. (See\r\n * accompanying file LICENSE_1_0.txt or copy at\r\n * http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * $Id$\r\n *\r\n */\r\n \r\n#include <boost/random/non_central_chi_squared_distribution.hpp>\r\n#include <boost/random/uniform_real.hpp>\r\n#include <boost/math/distributions/non_central_chi_squared.hpp>\r\n\r\n#define BOOST_RANDOM_DISTRIBUTION boost::random::non_central_chi_squared_distribution<>\r\n#define BOOST_RANDOM_DISTRIBUTION_NAME non_central_chi_squared\r\n#define BOOST_MATH_DISTRIBUTION boost::math::non_central_chi_squared\r\n#define BOOST_RANDOM_ARG1_TYPE double\r\n#define BOOST_RANDOM_ARG1_NAME k\r\n#define BOOST_RANDOM_ARG1_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG1_DISTRIBUTION(k) boost::uniform_real<>(0.00001, k)\r\n#define BOOST_RANDOM_ARG2_TYPE double\r\n#define BOOST_RANDOM_ARG2_NAME lambda\r\n#define BOOST_RANDOM_ARG2_DEFAULT 1000.0\r\n#define BOOST_RANDOM_ARG2_DISTRIBUTION(lambda) boost::uniform_real<>(0.00001, lambda)\r\n\r\n#include \"test_real_distribution.ipp\"\r\n", "meta": {"hexsha": "f33af09474176140cd1f9287935848a0c2e7aeb4", "size": 1136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_non_central_chi_squared.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_non_central_chi_squared.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/random/test/test_non_central_chi_squared.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 37.8666666667, "max_line_length": 88, "alphanum_fraction": 0.8063380282, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6021304621852757}}
{"text": "#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl; using namespace mtl::mat;\n    \n    const unsigned                xd= 2, yd= 5, n= xd * yd;\n    dense2D<double>               A(n, n);\n    compressed2D<double>          B(n, n);\n    hessian_setup(A, 3.0); laplacian_setup(B, xd, yd); \n\n    typedef std::complex<double>  cdouble;\n    dense_vector<cdouble>         v(n), w(n);\n    for (unsigned i= 0; i < size(v); i++)\n\tv[i]= cdouble(i+1, n-i), w[i]= cdouble(i+n);\n\n    v+= A * w;\n    w= B * v;\n\n    std::cout << \"v is \" << v << \"\\n\";\n    std::cout << \"w is \" << w << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "c5fcd8966085e7eb67cdc51e669ca8101c52acba", "size": 624, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_vector_mult.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/matrix_vector_mult.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/matrix_vector_mult.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 24.96, "max_line_length": 59, "alphanum_fraction": 0.4967948718, "num_tokens": 214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.602089829707366}}
{"text": "static bool eigen_did_assert = false;\n#define eigen_assert(X) if(!eigen_did_assert && !(X)){ std::cout << \"### Assertion raised in \" << __FILE__ << \":\" << __LINE__ << \":\\n\" #X << \"\\n### The following would happen without assertions:\\n\"; eigen_did_assert = true;}\n\n#include <iostream>\n#include <Eigen/Eigen>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n  cout.precision(3);\n// intentionally remove indentation of snippet\n{\nMatrixXf mat(2,2); \nmat << 1, 2,  4, 7;\ncout << \"Here is the matrix mat:\\n\" << mat << endl << endl;\n\nmat = 2 * mat;\ncout << \"After 'mat = 2 * mat', mat = \\n\" << mat << endl << endl;\n\n\nmat = mat - MatrixXf::Identity(2,2);\ncout << \"After the subtraction, it becomes\\n\" << mat << endl << endl;\n\n\nArrayXXf arr = mat;\narr = arr.square();\ncout << \"After squaring, it becomes\\n\" << arr << endl << endl;\n\n// Combining all operations in one statement:\nmat << 1, 2,  4, 7;\nmat = (2 * mat - MatrixXf::Identity(2,2)).array().square();\ncout << \"Doing everything at once yields\\n\" << mat << endl << endl;\n\n}\n  return 0;\n}\n", "meta": {"hexsha": "20ad5e32ca664b8bafd96d5f8b57a0ca05ef055d", "size": 1124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build/compiled_eigen/doc/snippets/compile_TopicAliasing_cwise.cpp", "max_stars_repo_name": "aminulce/soil_model_cpp", "max_stars_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build/compiled_eigen/doc/snippets/compile_TopicAliasing_cwise.cpp", "max_issues_repo_name": "aminulce/soil_model_cpp", "max_issues_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build/compiled_eigen/doc/snippets/compile_TopicAliasing_cwise.cpp", "max_forks_repo_name": "aminulce/soil_model_cpp", "max_forks_repo_head_hexsha": "027803c29cbf5bddd1222839ba73019876533f87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5454545455, "max_line_length": 224, "alphanum_fraction": 0.6387900356, "num_tokens": 341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6020835650691381}}
{"text": "//\u6d4b\u8bd5\u529f\u80fd\uff1a\u5c1d\u8bd5\u81ea\u5df1\u624b\u52a8\u201c\u6a21\u62df\u201d\u5173\u952e\u5e27\u548c\u666e\u901a\u5e27\u88ab\u521b\u5efa\u7684\u8fc7\u7a0b\uff0c\u5e76\u4e14\u5728\u89c6\u91ce\u4e2d\u8fdb\u884c\u663e\u793a\n//\u4e0d\u8fc7\u76ee\u524d\u51c6\u5907\u9996\u5148\u5b9e\u73b0\u7684\u529f\u80fd\u7684\u5c31\u662f\uff0c\u80fd\u591f\u901a\u8fc7\u63a7\u5236\u9762\u677f\u4e2d\u7684\u53c2\u6570\u53d8\u5316\u6765\u63a7\u5236\u7a97\u53e3\u4e2d\u5e27\u7684\u4f4d\u59ff\u53d8\u5316\n//\u53ef\u80fd\u9996\u5148\u9700\u8981\u89e3\u51b3\u4eceEigen\u6b27\u62c9\u89d2=>\u65cb\u8f6c\u77e9\u9635\uff0c\u8fd9\u6837\u7684\u4e00\u4e2a\u53d8\u6362\n\n//NOTICE \u4f46\u662f\u8fd9\u4e2a\u6709\u95ee\u9898\uff0c\u6050\u6015\u8fd8\u662f\u5f97\u4f7f\u7528\u77e9\u9635\u7684\u90a3\u79cd\u53d8\u6362\u5f62\u5f0f\u6bd4\u8f83\u597d\u3002\n#include <pangolin/pangolin.h>\n#include <vector>\n#include <iostream>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#define PI (3.1415926535897932346f)\n\n\nusing namespace std;\n\n//COL MAJOR!!!\n/*\nvector<GLfloat> Twc=\n{\n    1,0,0,0,   \n    0,1,0,0,\n    0,0,1,0,\n    5,0,0,1         //Trans\n};\n*/\n\ntypedef struct __Pose\n{\n\n    __Pose(double _pitch,double _roll,double _yaw,double _x,double _y,double _z,bool key=false):\n        pitch(_pitch),roll(_roll),yaw(_yaw),x(_x),y(_y),z(_z),keyFrame(key)\n        {}\n\n    double pitch;\n    double roll;\n    double yaw;\n    \n    double x;\n    double y;\n    double z;\n\n    bool keyFrame;\n}Pose;\n\nvoid drawFrame(const float w=2.0f);\ndouble deg2rad(const double deg);\nEigen::Matrix3d degEuler2matrix(double pitch,double roll,double yaw);\nvector<GLfloat> eigen2glfloat(Eigen::Isometry3d T);\nvoid drawAllFrames(vector<Pose> frames,bool orderRT=true);\n\n\nint main( int /*argc*/, char** /*argv*/ )\n{\n\n    vector<Pose> frames;\n\n\n    //========================= \u7a97\u53e3 ========================\n    pangolin::CreateWindowAndBind(\n        \"Frame - simulation\",     //\u7a97\u53e3\u6807\u9898\n        640,        //\u7a97\u53e3\u5c3a\u5bf8\n        480);       //\u7a97\u53e3\u5c3a\u5bf8\n    glEnable(GL_DEPTH_TEST);\n\n    //========================== 3D \u4ea4\u4e92\u5668 =====================\n    // Define Projection and initial ModelView matrix\n    pangolin::OpenGlRenderState s_cam(\n        pangolin::ProjectionMatrix(\n            640,480,            //\u76f8\u673a\u56fe\u50cf\u7684\u957f\u548c\u5bbd\n            420,420,320,240,    //\u76f8\u673a\u7684\u5185\u53c2,fu fv u0 v0\n            0.2,500),           //\u76f8\u673a\u6240\u80fd\u591f\u770b\u5230\u7684\u6700\u6d45\u548c\u6700\u6df1\u7684\u50cf\u7d20\n        pangolin::ModelViewLookAt(\n            -20,-20,-20,            //\u76f8\u673a\u5149\u5fc3\u4f4d\u7f6e,NOTICE z\u8f74\u4e0d\u8981\u8bbe\u7f6e\u4e3a0\n            0,0,0,              //\u76f8\u673a\u8981\u770b\u7684\u4f4d\u7f6e\n            pangolin::AxisY)    //\u548c\u89c2\u5bdf\u7684\u65b9\u5411\u6709\u5173\n    );\n\n    //======================== \u8c03\u8282\u9762\u677f ==============================\n     const int UI_WIDTH=180;\n     pangolin::View& d_cam = pangolin::CreateDisplay()\n    .SetBounds(0.0, 1.0, pangolin::Attach::Pix(UI_WIDTH), 1.0, -640.0f/480.0f)\n    .SetHandler(new pangolin::Handler3D(s_cam));\n\n    pangolin::CreatePanel(\"ui\")\n      .SetBounds(0.0, 1.0, 0.0, pangolin::Attach::Pix(UI_WIDTH));\n\n    //\u63a5\u4e0b\u6765\u8981\u5f00\u59cb\u51c6\u5907\u6dfb\u52a0\u63a7\u5236\u9009\u9879\u4e86\n    pangolin::Var<double> axisSize(\"ui.axis_size\",5,1,20);\n\n    pangolin::Var<bool> checkOrderBtn(\"ui.Order_RT\",true,true);  \n    pangolin::Var<double> frameRoll(\"ui.frame_roll\",0,-90,90);\n    pangolin::Var<double> framePitch(\"ui.frame_pitch\",0,-90,90);\n    pangolin::Var<double> frameYaw(\"ui.frame_yaw\",0,-180,180);\n    pangolin::Var<double> frameX(\"ui.frame_X\",0,-100,100);\n    pangolin::Var<double> frameY(\"ui.frame_Y\",0,-100,100);\n    pangolin::Var<double> frameZ(\"ui.frame_Z\",0,-100,100);\n\n    \n    pangolin::Var<bool> addFrameBtn(\"ui.add_frame\",false,false);\n    pangolin::Var<bool> addKeyFrameBtn(\"ui.add_keyFrame\",false,false);\n    \n\n    pangolin::Var<bool> resetFrameBtn(\"ui.reset_frame\",false,false);  \n    pangolin::Var<bool> resetViewBtn(\"ui.reset_view\",false,false);  \n    \n\n    while( !pangolin::ShouldQuit() )\n    {\n        // Clear screen and activate view to render into\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n        d_cam.Activate(s_cam);\n\n        // \u56e0\u4e3a\u540e\u9762\u7684^\u753b\u56fe\u9700\u8981,\u6682\u65f6\u9700\u8981\u5c06\u8fd9\u91cc\u7684\u80cc\u666f\u4fee\u6539\u6210\u4e3a\u767d\u8272\n        glClearColor(1,1,1,0.0);\n\n        //\u6309\u94ae\u7684\u54cd\u5e94 - \u590d\u4f4d\u89c6\u56fe\n        if(pangolin::Pushed(resetViewBtn))\n        {\n            s_cam.SetModelViewMatrix(\n                pangolin::ModelViewLookAt(\n            -50,-50,-50,  0,0,0,  pangolin::AxisNegY));\n\n            cout<<\"Reset view.\"<<endl;\n        }\n\n        //\u6309\u94ae\u7684\u54cd\u5e94 - \u590d\u4f4d\u5e27\u7684\u4f4d\u59ff\n        if(pangolin::Pushed(resetViewBtn))\n        {\n            //BUG \u76ee\u524d\u7684\u95ee\u9898\u662f\uff0c\u5c31\u7b97\u662f\u6570\u503c\u590d\u4f4d\u4e86\uff0c\u4f46\u662f\u63a7\u5236\u9762\u677f\u4e0a\u7684gui\u5e76\u4e0d\u4f1a\u590d\u4f4d\n            framePitch=0.0f;\n            framePitch.GuiChanged();\n            frameRoll=0.0f;\n            frameYaw=0.0f;\n            frameX=0.0f;\n            frameY=0.0f;\n            frameZ=0.0f;\n\n            cout<<\"Reset frame pose.\"<<endl;          \n        }\n\n        //\u6309\u94ae\u7684\u76f8\u5e94- \u6dfb\u52a0\u5e27\n        if(pangolin::Pushed(addFrameBtn))\n        {\n            frames.push_back(Pose(\n                (double)framePitch,\n                (double)frameRoll,\n                (double)frameYaw,\n                (double)frameX,\n                (double)frameY,\n                (double)frameZ\n            ));\n        }\n\n        if(pangolin::Pushed(addKeyFrameBtn))\n        {\n            frames.push_back(Pose(\n                (double)framePitch,\n                (double)frameRoll,\n                (double)frameYaw,\n                (double)frameX,\n                (double)frameY,\n                (double)frameZ,\n                true\n            ));\n        }\n\n\n        \n\n      \n        \n        //\u5c1d\u8bd5\u6309\u7167\u8c22\u6653\u4f73\u7684\u89c6\u9891\u4e2d\u7ed9\u51fa\u7684\u4ee3\u7801\u7ed8\u5236\n        pangolin::glDrawAxis((double)axisSize);\n\n        if(checkOrderBtn)\n        {\n            glRotatef((double)framePitch,1.0,0.0,0.0);\n            glRotatef((double)frameRoll,0.0,0.0,1.0);   \n            glRotatef((double)frameYaw,0.0,1.0,0.0);\n            glTranslatef((double)frameX,(double)frameY,(double)frameZ);\n        }\n        else\n        {\n            glTranslatef((double)frameX,(double)frameY,(double)frameZ);\n            glRotatef((double)framePitch,1.0,0.0,0.0);\n            glRotatef((double)frameRoll,0.0,0.0,1.0);   \n            glRotatef((double)frameYaw,0.0,1.0,0.0);\n        }\n\n\n        //\u7ed8\u5236\u5e27\n        glPushMatrix();\n        //glMultMatrixf(Twc.data());\n        glColor3f(0.0f,0.0f,1.0f);\n        drawFrame();\n        drawAllFrames(frames,(bool)checkOrderBtn);\n        glPopMatrix();\n        \n        //\u4e0d\u8981\u5fd8\u8bb0\u4e86\u8fd9\u4e2a\u4e1c\u897f!!!\n        glFlush();\n\n        // Swap frames and Process Events\n        pangolin::FinishFrame();\n    }\n    \n    return 0;\n}\n\nvoid drawFrame(const float w)\n{\n    const float h=w*0.75;\n    const float z=w*0.6;\n\n    glLineWidth(2);\n    \n\n    glBegin(GL_LINES);\n\n    glVertex3f(0,0,0);\n    glVertex3f(w,h,z);\n    glVertex3f(0,0,0);\n    glVertex3f(w,-h,z);\n    glVertex3f(0,0,0);\n    glVertex3f(-w,-h,z);\n    glVertex3f(0,0,0);\n    glVertex3f(-w,h,z);\n    glVertex3f(w,h,z);\n    glVertex3f(w,-h,z);\n    glVertex3f(-w,h,z);\n    glVertex3f(-w,-h,z);\n    glVertex3f(-w,h,z);\n    glVertex3f(w,h,z);\n    glVertex3f(-w,-h,z);\n    glVertex3f(w,-h,z);\n\n    glEnd();\n}\n\ndouble deg2rad(const double deg)\n{\n    return deg/180.0f*PI;\n}\n\n\nEigen::Matrix3d degEuler2matrix(double pitch,double roll,double yaw)\n{\n    Eigen::Vector3d rotation_vector(\n            deg2rad((double)yaw),\n            deg2rad((double)pitch),\n            deg2rad((double)roll));\n    Eigen::Matrix3d rotation_matrix=Eigen::Matrix3d::Identity();\n    rotation_matrix=Eigen::AngleAxisd(rotation_vector[0],Eigen::Vector3d::UnitZ())\n        *Eigen::AngleAxisd(rotation_vector[1],Eigen::Vector3d::UnitY())\n        *Eigen::AngleAxisd(rotation_vector[2],Eigen::Vector3d::UnitX());\n\n    return rotation_matrix;\n\n}\n\nvector<GLfloat> eigen2glfloat(Eigen::Isometry3d T)\n{\n    //\u6ce8\u610f\u662f\u5217\u4f18\u5148\n    vector<GLfloat> res;\n    for(int j=0;j<4;j++)\n    {\n        for(int i=0;i<4;i++)\n        {\n            res.push_back(T(i,j));\n        }\n    }\n    return res;\n}\n\n\nvoid drawAllFrames(vector<Pose> frames,bool orderRT)\n{\n    size_t n=frames.size();\n\n    for(int i=0;i<n;i++)\n    {\n        if(frames[i].keyFrame)\n        {\n            glColor3f(1.0f,0.0f,0.0f);\n        }\n        else\n        {\n            glColor3f(0.0f,1.0f,0.0f);\n        }\n        \n        if(orderRT)\n        {\n            glRotatef(frames[i].pitch,1.0,0.0,0.0);\n            glRotatef(frames[i].roll,0.0,0.0,1.0);   \n            glRotatef(frames[i].yaw,0.0,1.0,0.0);\n            glTranslatef(frames[i].x,frames[i].y,frames[i].z);\n\n            drawFrame();\n        }\n        else\n        {\n            glTranslatef(frames[i].x,frames[i].y,frames[i].z);\n            glRotatef(frames[i].pitch,1.0,0.0,0.0);\n            glRotatef(frames[i].roll,0.0,0.0,1.0);   \n            glRotatef(frames[i].yaw,0.0,1.0,0.0);\n            drawFrame();\n        }\n    }\n}", "meta": {"hexsha": "6a2ac32e011c132a8d43b557cdd88fd1b42ce234", "size": 7909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "009_Pangolin_study/test/test4.cpp", "max_stars_repo_name": "DreamWaterFound/Codes", "max_stars_repo_head_hexsha": "e7d80eb8bfd7d6f104abd18724cb4bface419233", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-02-28T14:28:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T04:55:19.000Z", "max_issues_repo_path": "009_Pangolin_study/test/test4.cpp", "max_issues_repo_name": "DreamWaterFound/Codes", "max_issues_repo_head_hexsha": "e7d80eb8bfd7d6f104abd18724cb4bface419233", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-07T09:00:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-04T02:13:25.000Z", "max_forks_repo_path": "009_Pangolin_study/test/test4.cpp", "max_forks_repo_name": "DreamWaterFound/Codes", "max_forks_repo_head_hexsha": "e7d80eb8bfd7d6f104abd18724cb4bface419233", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T16:47:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T16:47:31.000Z", "avg_line_length": 25.4308681672, "max_line_length": 96, "alphanum_fraction": 0.5458338602, "num_tokens": 2587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6019302485146382}}
{"text": "//\n// $Id$\n//\n//\n// Original author: Witold Wolski <wewolski@gmail.com>\n//\n// Copyright : ETH Zurich\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \n// you may not use this file except in compliance with the License. \n// You may obtain a copy of the License at \n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software \n// distributed under the License is distributed on an \"AS IS\" BASIS, \n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n// See the License for the specific language governing permissions and \n// limitations under the License.\n//\n\n#include <boost/cstdint.hpp>\n\n#include \"pwiz/utility/findmf/base/base/base.hpp\"\n#include \"pwiz/utility/misc/unit.hpp\"\n\nnamespace {\n  using namespace pwiz::util;\n\ttypedef boost::int32_t int32_t;\n  // Tests that the Foo::Bar() method does Abc.\n  void testseq() {\n    std::vector<double> res;\n    ralab::base::base::seq(1.,10.,0.5,res);\n    ralab::base::base::seq(10.,2.,res);\n    ralab::base::base::seq(2.,10.,res);\n    ralab::base::base::seq(10., 2. , -0.5 , res);\n\n    std::vector<int32_t> res2;\n    ralab::base::base::seq(10,2,res2);\n    ralab::base::base::seq(10,res);\n    ralab::base::base::seq(res2,res);\n\n    std::vector<unsigned int> resunsigned;\n    ralab::base::base::seq(1u,10u,1u,resunsigned);\n    ralab::base::base::seq(1u,10u,resunsigned);\n\n    std::vector<double> resdouble;\n    ralab::base::base::seq_length(100. , 1300.,18467,resdouble);\n    unit_assert(resdouble.size() == 18467);\n    ralab::base::base::seq_length(100. , 1300.,19467,resdouble);\n    unit_assert(resdouble.size() == 19467);\n\n    ralab::base::base::seq_length(0.,1000.,1000,resdouble);\n    unit_assert(resdouble.size() == 1000);\n  }\n\n  // Tests that Foo does Xyz.\n  void testmean() {\n    std::vector<double> x;\n    x.push_back(1.0);\n    x.push_back(1.0);\n    x.push_back(1.0);\n    x.push_back(1.);\n    x.push_back(2.);\n    x.push_back(3.);\n    x.push_back(5.);\n    x.push_back(5.);\n    x.push_back(6.);\n    x.push_back(7.);\n    x.push_back(8.);\n    double res = ralab::base::base::mean(x);\n    unit_assert_equal ( 3.636364, res, 1e-4);\n    res = ralab::base::base::mean(x, 0.3);\n    unit_assert_equal ( 3.2, res, 1e-4);\n    res = ralab::base::base::mean(x, 0.4);\n    unit_assert_equal ( 3.33333, res, 1e-4);\n    res = ralab::base::base::mean(x, 0.5);\n    std::cout << res << std::endl;\n    unit_assert_equal ( 3., res, 1e-4);\n    res = ralab::base::base::mean(x.begin(),x.end());\n    unit_assert_equal ( 3.636364, res, 1e-4);\n\n  }\n\n  void testgeometricmean(){\n    std::vector<double> x;\n    x.push_back(1.0);\n    x.push_back(2.0);\n    x.push_back(3.0);\n\n    double res = ralab::base::base::geometricMean(x.begin(), x.end());\n    unit_assert_equal( 1.817121, res, 1e-4 );\n\n  }\n}  // namespace\n\nint main(int argc, char **argv) {\n testseq();\ntestmean();\ntestgeometricmean();\n}\n", "meta": {"hexsha": "8dd2c4affbcd3cd2fbae4824fdbf1aaa8928de56", "size": 2921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/findmf/base/base/basetest.cpp", "max_stars_repo_name": "austinkeller/pwiz", "max_stars_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "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": "pwiz/utility/findmf/base/base/basetest.cpp", "max_issues_repo_name": "austinkeller/pwiz", "max_issues_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz/utility/findmf/base/base/basetest.cpp", "max_forks_repo_name": "austinkeller/pwiz", "max_forks_repo_head_hexsha": "aa8e575cb40fd5e97cc7d922e4d8da44c9277cca", "max_forks_repo_licenses": ["Apache-2.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.637254902, "max_line_length": 76, "alphanum_fraction": 0.6377952756, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6019302365745869}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_RSQRT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing rsqrt capabilities\n\n    Returns the inverse of the square root of the input.\n\n    @par semantic:\n\n    For any given value @c x of floating type @c T:\n\n    @code\n    T r = rsqrt(x);\n    @endcode\n\n    For signed type is similar to:\n\n    @code\n    T r = T(1)/sqrt(x)\n    @endcode\n\n    @par Note\n\n    If full accuracy is not needed a sometimes faster less accurate version of the function\n    can be sppeded by the fast_ decorator : fast_(rsqrt)(x).\n\n    @par Decorators\n\n    fast_ for floating entries\n\n  **/\n  Value rsqrt(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/rsqrt.hpp>\n#include <boost/simd/function/scalar/rsqrt.hpp>\n#include <boost/simd/function/simd/rsqrt.hpp>\n\n#endif\n", "meta": {"hexsha": "faa16ffe4b04f8c9562dbf3db5773539cc67a901", "size": 1319, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/rsqrt.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "third_party/boost/simd/function/rsqrt.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/rsqrt.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 22.7413793103, "max_line_length": 100, "alphanum_fraction": 0.59969674, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.7185944046238982, "lm_q1q2_score": 0.6019090305038545}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <boost/bind.hpp>\n#include \"test_case.hpp\"\n#include \"integration/NewtonRaphson.hpp\"\n#include <Eigen/Dense>\n\nnamespace impl {\n\tdouble function_1( double v ) {\n\t\treturn -v*v + v + 2.0 ;\n\t}\n\n\tdouble derivative_1( double v ) {\n\t\treturn -2.0 * v + 1 ;\n\t}\n\t\n\tdouble quadratic( double v, double a, double b, double c ) {\n\t\treturn a*v*v + b*v + c ;\n\t}\n\t\n\tdouble quadratic_derivative( double v, double a, double b ) {\n\t\treturn 2*a*v + b ;\n\t}\n\t\n\tEigen::VectorXd affine_map( Eigen::VectorXd const& point, Eigen::MatrixXd const& matrix, Eigen::VectorXd const& offset ) {\n\t\treturn ( matrix * ( point - offset ) ) ;\n\t}\n\n\tEigen::MatrixXd affine_derivative( Eigen::VectorXd const& point, Eigen::MatrixXd const& matrix ) {\n\t\treturn matrix ;\n\t}\n\n\tEigen::VectorXd another_map( Eigen::VectorXd const& point, Eigen::MatrixXd const& matrix, Eigen::VectorXd const& offset ) {\n\t\t// A linear map plus quadratic deviation.\n\t\tEigen::VectorXd v( 2 ) ;\n\t\tv << \t-( ( point - offset )( 0 ) * ( point - offset )( 0 ) ),\n\t\t\t\t-( ( point - offset )( 1 ) * ( point - offset )( 1 ) ) ;\n\t\treturn ( matrix * ( point - offset ) ) + v ;\n\t}\n\n\tEigen::MatrixXd another_derivative( Eigen::VectorXd const& point, Eigen::MatrixXd const& matrix, Eigen::VectorXd const& offset ) {\n\t\tEigen::MatrixXd M( 2, 2 ) ;\n\t\tM <<\t-2 * ( point( 0 ) - offset( 0 ) ),\t0,\n\t\t\t\t0,\t\t\t\t\t\t\t\t\t-2 * ( point( 1 ) - offset( 1 ) ) ;\n\t\treturn matrix + M ;\n\t}\n}\n\nAUTO_TEST_CASE( test_newton_raphson_1d ) {\n\tstd::cerr << \"test_newton_raphson_1d(): finding roots of  5 x - 2...\\n\" ;\n\tfor( double epsilon = 0.1; epsilon > 0.0000000000001; epsilon /= 10 ) {\n\t\tstd::cerr << \"epsilon = \" << epsilon << \".\\n\" ;\n\t\tdouble root = integration::find_root_by_newton_raphson(\n\t\t\tboost::bind( impl::quadratic, _1, 0, 5, -2 ),\n\t\t\tboost::bind( impl::quadratic_derivative, _1, 0, 5 ),\n\t\t\t-10.0,\n\t\t\tepsilon\n\t\t) ;\n\t\t\n\t\tstd::cerr << \"root: \" << root << \".\\n\" ;\n\t\tTEST_ASSERT( std::abs( root - ( 2.0 / 5.0 )) < epsilon ) ;\n\t}\n\t\n\tstd::cerr << \"test_newton_raphson_1d(): finding roots of 2 + x - x^2...\\n\" ;\n\tfor( double epsilon = 0.1; epsilon > 0.0000000000001; epsilon /= 10 ) {\n\t\tstd::cerr << \"epsilon = \" << epsilon << \".\\n\" ;\n\t\tdouble left_root = integration::find_root_by_newton_raphson(\n\t\t\tboost::bind( impl::quadratic, _1, -1, 1, 2 ),\n\t\t\tboost::bind( impl::quadratic_derivative, _1, -1, 1 ),\n\t\t\t-10.0,\n\t\t\tepsilon\n\t\t) ;\n\t\tstd::cerr << \"Left root: \" << left_root << \".\\n\" ;\n\t\tTEST_ASSERT( std::abs( left_root + 1 ) < epsilon ) ;\n\n\t\tdouble right_root = integration::find_root_by_newton_raphson(\n\t\t\t&impl::function_1,\n\t\t\t&impl::derivative_1,\n\t\t\t10.0,\n\t\t\tepsilon\n\t\t) ;\n\n\t\tstd::cerr << \"Right root: \" << right_root << \".\\n\" ;\n\t\tTEST_ASSERT( std::abs( right_root - 2 ) < epsilon ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_newton_raphson_nd_1 ) {\n\tstd::cerr << \"test_newton_raphson_nd_1(): finding roots of \\\\Sigma x = 0...\\n\" ;\n\t\n\tEigen::MatrixXd sigma ;\n\tsigma.resize( 2, 2 ) ;\n\tsigma( 0, 0 ) = 5 ;\n\tsigma( 1, 1 ) = 5 ;\n\tsigma( 0, 1 ) = 0.5 ;\n\tsigma( 1, 0 ) = 0.5 ;\n\n\tEigen::VectorXd actual_root = Eigen::VectorXd( 2 ) ;\n\tactual_root << 50, 50 ;\n\t\n\tEigen::VectorXd initial_point( 2 ) ;\n\tinitial_point << -100.0, -100.0 ;\n\tfor( double epsilon = 0.1; epsilon > 0.0000000000001; epsilon /= 10 ) {\n\t\tstd::cerr << \"==================== epsilon = \" << epsilon << \".\\n\" ;\n\t\tEigen::VectorXd root = integration::find_root_by_newton_raphson(\n\t\t\tboost::bind( impl::affine_map, _1, sigma, actual_root ),\n\t\t\tboost::bind( impl::affine_derivative, _1, sigma ),\n\t\t\tinitial_point,\n\t\t\tepsilon\n\t\t) ;\n\t\n\t\tstd::cerr << \"root is \" << root << \".\\n\" ;\n\t\tTEST_ASSERT( ( root - actual_root ).norm() < epsilon ) ;\n\t}\n}\n\nAUTO_TEST_CASE( test_newton_raphson_nd_2 ) {\n\tstd::cerr << \"test_newton_raphson_nd_2(): finding roots of \\\\Sigma x = 0...\\n\" ;\n\t\n\tEigen::MatrixXd sigma ; // variance-covariance matrix\n\tsigma.resize( 2, 2 ) ;\n\tsigma( 0, 0 ) = 5 ;\n\tsigma( 1, 1 ) = 5 ;\n\tsigma( 0, 1 ) = 0 ;\n\tsigma( 1, 0 ) = 0 ;\n\n\tEigen::VectorXd actual_root = Eigen::VectorXd( 2 ) ;\n\tactual_root << 50, 50 ;\n\t\n\tEigen::VectorXd initial_point( 2 ) ;\n\tinitial_point << -100.0, -100.0 ;\n\tfor( double epsilon = 0.1; epsilon > 0.000000000000001; epsilon /= 10 ) {\n\t\tstd::cerr << \"============== epsilon = \" << epsilon << \".\\n\" ;\n\t\tEigen::VectorXd root = integration::find_root_by_newton_raphson(\n\t\t\tboost::bind( impl::another_map, _1, sigma, actual_root ),\n\t\t\tboost::bind( impl::another_derivative, _1, sigma, actual_root ),\n\t\t\tinitial_point,\n\t\t\tepsilon\n\t\t) ;\n\t\n\t\tstd::cerr << \"root is \" << root << \".\\n\" ;\n\t\tTEST_ASSERT( impl::another_map( root, sigma, actual_root ).maxCoeff() < epsilon ) ;\n\t}\n}\n", "meta": {"hexsha": "018da459e7f3af8815875c4f5dd582a0bc8ac216", "size": 4782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "integration/test/test_newton_raphson.cpp", "max_stars_repo_name": "gavinband/bingwa", "max_stars_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "integration/test/test_newton_raphson.cpp", "max_issues_repo_name": "gavinband/bingwa", "max_issues_repo_head_hexsha": "d52e166b3bb6bc32cd32ba63bf8a4a147275eca1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "integration/test/test_newton_raphson.cpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.88, "max_line_length": 131, "alphanum_fraction": 0.6145964032, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6019090188525763}}
{"text": "/**\n * @file MathIO.hpp\n * @author bwu\n * @brief I/O functions of math\n * @version 0.1\n * @date 2022-02-22 \n */\n#ifndef GENERIC_MATH_MATHIO_HPP\n#define GENERIC_MATH_MATHIO_HPP\n#include \"LinearAlgebra.hpp\"\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <iostream>\n#include <fstream>\n#include <complex>\nnamespace {\nusing namespace generic::math;\nusing namespace generic::math::la;\n\n///@brief out stream a vector\ntemplate <typename num_type, size_t N>\ninline std::ostream & operator<< (std::ostream & os, const Vector<num_type, N> & v)\n{\n    return os << v.Data();\n}\n\n///@brief out stream a matrix\ntemplate <typename num_type, size_t M, size_t N>\ninline std::ostream & operator<< (std::ostream & os, const Matrix<num_type, M, N> & m)\n{\n    return os << m.Data();\n}\n}\n\nnamespace generic {\nnamespace math {\nnamespace la {\nusing namespace boost::numeric::ublas;\n\nclass MatrixIO\n{\npublic:\n    template <typename num_type, bool zero_based = true>\n    static bool ReadSparseMatrixComplex(const std::string & dia, const std::string & offDia, mapped_matrix<std::complex<num_type> > & m, std::string * err = nullptr)\n    {\n        std::ifstream in(dia);\n        if(!in.is_open()) {\n            if(err) *err = \"Error: fail to open: \" + dia;\n            return false;\n        }\n\n        size_t i, j;\n        num_type real, imag;\n        size_t row = m.size1();\n        size_t col = m.size2();\n        while(!in.eof()){\n            in >> i >> real >> imag;\n            if(zero_based) m(i, i) = std::complex<num_type>(real, imag);\n            else m(i - 1, i - 1) = std::complex<num_type>(real, imag);\n        }\n\n        in.close();\n        in.open(offDia);\n        if(!in.is_open()) {\n            if(err) *err = \"Error: fail to open: \" + dia;\n            return false;\n        }\n        \n        while(!in.eof()){\n            in >> i >> j >> real >> imag;\n            if(zero_based) m(i, j) = std::complex<num_type>(real, imag);\n            else m(i - 1, j - 1) = std::complex<num_type>(real, imag);\n        }\n        in.close();\n        return true;\n    }\n\n    template <typename num_type, bool zero_based = true>\n    static bool ReadSparseMatrix(const std::string & dia, const std::string & offDia, coordinate_matrix<num_type> & m, std::string * err = nullptr)\n    {\n        std::ifstream in(dia);\n        if(!in.is_open()) {\n            if(err) *err = \"Error: fail to open: \" + dia;\n            return false;\n        }\n\n        size_t i, j;\n        num_type real, imag;\n        size_t row = m.size1();\n        size_t col = m.size2();\n        while(!in.eof()){\n            in >> i >> real >> imag;\n            if(zero_based) m(i, i) = real;\n            else m(i - 1, i - 1) = real;\n        }\n\n        in.close();\n        in.open(offDia);\n        if(!in.is_open()) {\n            if(err) *err = \"Error: fail to open: \" + dia;\n            return false;\n        }\n        \n        while(!in.eof()){\n            in >> i >> j >> real >> imag;\n            if(zero_based) m(i, j) = real;\n            else m(i - 1, j - 1) = real;\n        }\n        in.close();\n        return true;\n    }\n};\n}//namespace la\n}//namespace math\n}//namespace generic\n#endif//GENERIC_MATH_MATHIO_HPP", "meta": {"hexsha": "3a4d77ed17034866993c4e207c5b85f086795b2c", "size": 3203, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math/MathIO.hpp", "max_stars_repo_name": "Draaaaaaven/generic", "max_stars_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-05T02:34:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:51:50.000Z", "max_issues_repo_path": "math/MathIO.hpp", "max_issues_repo_name": "Draaaaaaven/generic", "max_issues_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/MathIO.hpp", "max_forks_repo_name": "Draaaaaaven/generic", "max_forks_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6120689655, "max_line_length": 165, "alphanum_fraction": 0.5457383703, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6019090095344123}}
{"text": "/*\n * File: dht.cc\n * Created Date: 2019-12-29\n * Author: Lei Pan\n * Contact: <panlei7@gmail.com>\n *\n * Last Modified: Sunday December 29th 2019 12:11:36 pm\n *\n * MIT License\n *\n * Copyright (c) 2019 Lei Pan\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the 'Software'), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * -----\n * HISTORY:\n * Date      \t By\tComments\n * ----------\t---\n * ----------------------------------------------------------\n */\n\n#include \"dht.hpp\"\n\n#include <Eigen/Dense>\n#include <boost/math/special_functions/bessel.hpp>\n#include <cmath>\n#include <iostream>\n\nusing namespace Eigen;\nusing boost::math::cyl_bessel_j;\nusing boost::math::cyl_bessel_j_zero;\nusing std::pow;\n\nDiscreteHankelTransform::DiscreteHankelTransform(int order, int nr)\n    : order_(order), nr_(nr), roots_(nr_), tmatrix_(MatrixXd::Zero(nr_, nr_)) {\n  for (int i = 0; i < nr_; ++i) {\n    roots_(i) = cyl_bessel_j_zero(float(order_), i + 1);\n  }\n  for (int k = 0; k < nr_ - 1; ++k) {\n    for (int m = 0; m < nr_ - 1; ++m) {\n      tmatrix_(m, k) =\n          2.0 / (roots_(nr_ - 1) * pow(cyl_bessel_j(order + 1, roots_(k)), 2)) *\n          cyl_bessel_j(order, roots_(m) * roots_(k) / roots_(nr_ - 1));\n    }\n  }\n}\n\nDiscreteHankelTransform::~DiscreteHankelTransform() = default;\n\nVectorXd DiscreteHankelTransform::r_sampling(double rmax) {\n  rmax_ = rmax;\n  VectorXd r = roots_ / rmax_ * roots_(nr_ - 1);\n  return r;\n}\n\nVectorXd DiscreteHankelTransform::k_sampling(double rmax) {\n  rmax_ = rmax;\n  VectorXd k = roots_ / rmax_;\n  return k;\n}\n\nVectorXd DiscreteHankelTransform::forward(const Ref<const VectorXd> &fr) {\n  VectorXd fk = pow(rmax_, 2) / roots_(nr_ - 1) * (tmatrix_ * fr);\n  return fk;\n}\n\nVectorXd DiscreteHankelTransform::backward(const Ref<const VectorXd> &fk) {\n  VectorXd fr = roots_(nr_ - 1) / pow(rmax_, 2) * (tmatrix_ * fk);\n  return fr;\n}\n\nVectorXd DiscreteHankelTransform::shift(const Ref<const VectorXd> &raw, int m) {\n  VectorXd ret(VectorXd::Zero(nr_ - 1));\n  for (int q = 0; q < nr_ - 1; ++q) {\n    for (int p = 0; p < nr_ - 1; ++p) {\n      for (int k = 0; k < nr_ - 1; ++k) {\n        ret(q) += tmatrix_(m, k) * tmatrix_(k, q) * tmatrix_(k, p) * raw(p);\n      }\n    }\n  }\n  return ret;\n}\n\nMatrixXd DiscreteHankelTransform::tmatrix() const { return tmatrix_; }", "meta": {"hexsha": "7be6edc8015787c5979c0af9f700d308535b3519", "size": 3236, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/dht.cc", "max_stars_repo_name": "pan3rock/discrete-hankel-transform", "max_stars_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dht.cc", "max_issues_repo_name": "pan3rock/discrete-hankel-transform", "max_issues_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dht.cc", "max_forks_repo_name": "pan3rock/discrete-hankel-transform", "max_forks_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T09:56:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T09:56:44.000Z", "avg_line_length": 32.6868686869, "max_line_length": 80, "alphanum_fraction": 0.6606922126, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619959279793, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6019090058438881}}
{"text": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include <boost/test/unit_test.hpp>\n\n#include \"Molassembler/Temple/Adaptors/Zip.h\"\n#include \"Molassembler/Temple/Functional.h\"\n#include \"Molassembler/Temple/Random.h\"\n#include \"Molassembler/Temple/constexpr/Math.h\"\n#include \"Molassembler/Temple/constexpr/Jsf.h\"\n#include \"Molassembler/Temple/constexpr/FloatingPointComparison.h\"\n#include \"Molassembler/Temple/Stringify.h\"\n\n#include <iomanip>\n#include <iostream>\n\nusing namespace Scine::Molassembler;\nextern Temple::Generator<> generator;\n\nstatic_assert(Temple::Math::factorial(5) == 120, \"Factorial is incorrect\");\nstatic_assert(Temple::Math::factorial(0) == 1, \"Factorial is incorrect\");\n\nnamespace {\n\nconstexpr unsigned numTests = 100;\nconstexpr double relativeAccuracy = 1e-12;\n\nstatic_assert(\n  relativeAccuracy >= std::numeric_limits<double>::epsilon(),\n  \"Testing relative accuracy must be greater than machine epsilon!\"\n);\n\ntemplate<typename F, typename G>\nauto compareImplFn(F&& testFn, G&& referenceFn, double accuracy=relativeAccuracy) {\n  return [=](const auto ... values) {\n    const double testValue = testFn(values...);\n    const double referenceValue = referenceFn(values...);\n\n    BOOST_TEST_CONTEXT(\n      \"  x = \" << std::setw(12) << Temple::stringify(std::tie(values...))\n      << \", y = \" << std::setw(12) << testValue\n      << \", ref = \" << std::setw(12) << referenceValue\n      << \", |\u0394| = \" << std::setw(12) << std::fabs(testValue - referenceValue)\n    ) {\n      BOOST_CHECK(\n        Temple::Floating::isCloseRelative(testValue, referenceValue, accuracy)\n      );\n    }\n  };\n}\n\n} // namespace\n\nBOOST_AUTO_TEST_CASE(ConstexprSqrt, *boost::unit_test::label(\"Temple\")) {\n  Temple::forEach(\n    Temple::Random::getN<double>(0, 1e6, numTests, generator.engine),\n    compareImplFn(\n      [](double x) { return Temple::Math::sqrt(x); },\n      [](double x) { return std::sqrt(x); }\n    )\n  );\n}\n\nBOOST_AUTO_TEST_CASE(ConstexprAsin, *boost::unit_test::label(\"Temple\")) {\n  // asin\n  const auto randomInverseTrigNumbers = Temple::Random::getN<double>(\n    std::nexttoward(-1.0, 0.0),\n    std::nexttoward(1.0, 0.0),\n    numTests,\n    generator.engine\n  );\n\n  Temple::forEach(\n    randomInverseTrigNumbers,\n    compareImplFn(\n      [](double x) { return Temple::Math::asin(x); },\n      [](double x) { return std::asin(x); },\n      1e-8\n    )\n  );\n}\n\nBOOST_AUTO_TEST_CASE(ConstexprPow, *boost::unit_test::label(\"Temple\")) {\n  Temple::forEach(\n    Temple::Adaptors::zip(\n      Temple::Random::getN<double>(-1e5, 1e5, numTests, generator.engine),\n      Temple::Random::getN<int>(-40, 40, numTests, generator.engine)\n    ),\n    compareImplFn(\n      [](double x, int y) { return Temple::Math::pow(x, y); },\n      [](double x, int y) { return std::pow(x, y); }\n    )\n  );\n}\n\nBOOST_AUTO_TEST_CASE(ConstexprRecPow, *boost::unit_test::label(\"Temple\")) {\n  Temple::forEach(\n    Temple::Adaptors::zip(\n      Temple::Random::getN<double>(-1e5, 1e5, numTests, generator.engine),\n      Temple::Random::getN<unsigned>(0, 40, numTests, generator.engine)\n    ),\n    compareImplFn(\n      [](double x, unsigned y) { return Temple::Math::recPow(x, y); },\n      [](double x, unsigned y) { return std::pow(x, y); }\n    )\n  );\n}\n\nBOOST_AUTO_TEST_CASE(ConstexprLn, *boost::unit_test::label(\"Temple\")) {\n  Temple::forEach(\n    Temple::Random::getN<double>(1e-10, 1e10, numTests, generator.engine),\n    compareImplFn(\n      [](double x) { return Temple::Math::ln(x); },\n      [](double x) { return std::log(x); }\n    )\n  );\n}\n\nBOOST_AUTO_TEST_CASE(ConstexprAtan, *boost::unit_test::label(\"Temple\")) {\n  Temple::forEach(\n    Temple::Random::getN<double>(-M_PI / 2, M_PI / 2, numTests, generator.engine),\n    compareImplFn(\n      [](double x) { return Temple::Math::atan(x); },\n      [](double x) { return std::atan(x); }\n    )\n  );\n}\n\nBOOST_AUTO_TEST_CASE(ConstexprFloorCeil, *boost::unit_test::label(\"Temple\")) {\n  BOOST_CHECK(\n    Temple::all_of(\n      Temple::Random::getN<double>(-100, 100, numTests, generator.engine),\n      [](const double x) -> bool {\n        return(Temple::Math::floor(x) <= x);\n      }\n    )\n  );\n\n  BOOST_CHECK(\n    Temple::all_of(\n      Temple::Random::getN<double>(-100, 100, numTests, generator.engine),\n      [](const double x) -> bool {\n        return(Temple::Math::ceil(x) >= x);\n      }\n    )\n  );\n}\n\nnamespace {\n\ntemplate<\n  template<typename> class Comparator,\n  typename T\n> constexpr bool testComparison(const T a, const T b, const T tolerance) {\n  Comparator<T> comparator { tolerance };\n\n  return (\n    Temple::Math::XOR(\n      (\n        comparator.isLessThan(a, b)\n        && comparator.isMoreThan(b, a)\n        && comparator.isUnequal(a, b)\n      ),\n      (\n        comparator.isLessThan(b, a)\n        && comparator.isMoreThan(a, b)\n        && comparator.isUnequal(a, b)\n      ),\n      (\n        !comparator.isLessThan(a, b)\n        && !comparator.isMoreThan(a, b)\n        && comparator.isEqual(a, b)\n      )\n    ) && Temple::Math::XOR(\n      comparator.isEqual(a, b),\n      comparator.isUnequal(a, b)\n    )\n  );\n}\n\nusing namespace Temple::Floating;\n\nstatic_assert(\n  testComparison<ExpandedAbsoluteEqualityComparator>(4.3, 3.9, 1e-4)\n  && testComparison<ExpandedAbsoluteEqualityComparator>(4.3, 3.9, 1.0)\n  && testComparison<ExpandedAbsoluteEqualityComparator>(4.4, 4.4, 1e-10),\n  \"absolute comparison has inconsistent operators!\"\n);\n\nstatic_assert(\n  testComparison<ExpandedRelativeEqualityComparator>(4.3, 3.9, 1e-4)\n  && testComparison<ExpandedRelativeEqualityComparator>(4.3, 3.9, 1.0)\n  && testComparison<ExpandedRelativeEqualityComparator>(4.4, 4.4, 1e-10),\n  \"relative comparison has inconsistent operators!\"\n);\n\n} // namespace\n", "meta": {"hexsha": "499af90a18270847bb17b7137761aae34586cd29", "size": 5803, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/Temple/Math.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "test/Temple/Math.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Temple/Math.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 28.8706467662, "max_line_length": 83, "alphanum_fraction": 0.6479407203, "num_tokens": 1613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.6859494550081925, "lm_q1q2_score": 0.6019047307490305}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\nusing namespace std;\nusing namespace Eigen;\nint main()\n{\n    // Ax=b\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    cout << \"The least-squares solution is:\\n\"\n        << A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b) << endl;\n}\n", "meta": {"hexsha": "d70146ae01f3013bbfdbefe627eeff1905f071d0", "size": 423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snippets/eigen-least-square.cpp", "max_stars_repo_name": "district10/snippet-manager", "max_stars_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-04T09:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-19T17:46:34.000Z", "max_issues_repo_path": "snippets/eigen-least-square.cpp", "max_issues_repo_name": "district10/snippet-manager", "max_issues_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snippets/eigen-least-square.cpp", "max_forks_repo_name": "district10/snippet-manager", "max_forks_repo_head_hexsha": "bebe45a601368947168e3ee6e6ab8c1fc2ee2055", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-31T04:14:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-02T01:22:39.000Z", "avg_line_length": 28.2, "max_line_length": 69, "alphanum_fraction": 0.6146572104, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.6859494485880927, "lm_q1q2_score": 0.6019047185220197}}
{"text": "//=======================================================================\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <iostream>\n#include <boost/graph/edge_list.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n\nint main()\n{\n    using namespace boost;\n    // ID numbers for the routers (vertices).\n    enum\n    {\n        A,\n        B,\n        C,\n        D,\n        E,\n        F,\n        G,\n        H,\n        n_vertices\n    };\n    const int n_edges = 11;\n    typedef std::pair< int, int > Edge;\n\n    // The list of connections between routers stored in an array.\n    Edge edges[] = { Edge(A, B), Edge(A, C), Edge(B, D), Edge(B, E), Edge(C, E),\n        Edge(C, F), Edge(D, H), Edge(D, E), Edge(E, H), Edge(F, G),\n        Edge(G, H) };\n\n    // Specify the graph type and declare a graph object\n    typedef edge_list< Edge*, Edge, std::ptrdiff_t,\n        std::random_access_iterator_tag >\n        Graph;\n    Graph g(edges, edges + n_edges);\n\n    // The transmission delay values for each edge.\n    float delay[] = { 5.0, 1.0, 1.3, 3.0, 10.0, 2.0, 6.3, 0.4, 1.3, 1.2, 0.5 };\n\n    // Declare some storage for some \"external\" vertex properties.\n    char name[] = \"ABCDEFGH\";\n    int parent[n_vertices];\n    for (int i = 0; i < n_vertices; ++i)\n        parent[i] = i;\n    float distance[n_vertices];\n    std::fill(\n        distance, distance + n_vertices, (std::numeric_limits< float >::max)());\n    // Specify A as the source vertex\n    distance[A] = 0;\n\n    bool r = bellman_ford_shortest_paths(g, int(n_vertices),\n        weight_map(\n            make_iterator_property_map(&delay[0], get(edge_index, g), delay[0]))\n            .distance_map(&distance[0])\n            .predecessor_map(&parent[0]));\n\n    if (r)\n        for (int i = 0; i < n_vertices; ++i)\n            std::cout << name[i] << \": \" << distance[i] << \" \"\n                      << name[parent[i]] << std::endl;\n    else\n        std::cout << \"negative cycle\" << std::endl;\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "a761373d3b46576ddae77002e140f006d24fa785", "size": 2232, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/bellman-ford-internet.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/bellman-ford-internet.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/graph/example/bellman-ford-internet.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 31.4366197183, "max_line_length": 80, "alphanum_fraction": 0.5353942652, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6018997047922349}}
{"text": "#include <iostream>\n#include <Eigen\\Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nvoid main() {\n\t{\n\t\tArrayXXf m(2, 2);\n\t\tm(0, 0) = 1.0;\n\t\tm(0, 1) = 2.0;\n\t\tm(1, 0) = 3.0;\n\t\tm(1, 1) = m(0, 1) + m(1, 0);\n\n\t\tcout << m << endl;\n\t\tm << 1.0, 2.0, 3.0, 4.0;\n\t\tcout << m << endl;\n\t}\n\n\t{\n\t\tArrayXXf a(3, 3);\n\t\tArrayXXf b(3, 3);\n\t\ta << 1, 2, 3,\n\t\t\t4, 5, 6,\n\t\t\t7, 8, 9;\n\t\tb << 1, 2, 3,\n\t\t\t1, 2, 3,\n\t\t\t1, 2, 3;\n\n\t\t// Adding two arrays\n\t\tcout << \"a + b = \" << endl << a + b << endl << endl;\n\t\t// Subtracting a scalar from an array\n\t\tcout << \"a - 2 = \" << endl << a - 2 << endl;\n\t}\n\n\t{\n\t\tArrayXXf a(2, 2);\n\t\tArrayXXf b(2, 2);\n\n\t\ta << 1, 2, 3, 4;\n\t\tb << 5, 6, 7, 8;\n\n\t\tcout << \"a * b = \\n\" << a * b << endl;\n\t}\n\n\t{\n\t\t// COEFFICIENT-WISE OPERATIONS\n\t\tcout << \"COEFFICIENT-WISE OPERATIONS\" << endl;\n\t\tArrayXf a = ArrayXf::Random(5);\n\t\ta *= 2;\n\t\tcout << \"a = \" << endl << a << endl;\n\t\tcout << \"a.abs() = \" << endl << a.abs() << endl;\n\t\tcout << \"a.abs().sqrt() = \" << endl << a.abs().sqrt() << endl;\n\t\tcout << \"a.min(a.abs().sqrt()) = \" << endl << a.min(a.abs().sqrt()) << endl;\n\n\t}\n\n\t{\n\t\tMatrixXf m(2, 2);\n\t\tMatrixXf n(2, 2);\n\t\tMatrixXf result(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\n\t\tresult = m * n;\n\t\tcout << \"-- m : -- \\n\" << m << endl;\n\t\tcout << \"-- n : -- \\n\" << n << endl;\n\t\tcout << \"-- Matrix m * n : -- \\n\" << result << endl;\n\t\tresult = m.array() * n.array();\n\t\tcout << \"-- Matrix m.array() * n.array() : -- \\n\" << result << endl;\n\t\tresult = m.cwiseProduct(n);\n\t\tcout << \"-- m.cwiseProduct(n) : -- \\n\" << result << endl;\n\t\tresult = m.array() + 4;\n\t\tcout << \"-- Array m + 4: -- \\n\" << result << endl;\n\t\tresult = (m.array() + 4).matrix() * m;\n\t\tcout << \"-- Combo 1: (m.array() + 4).matrix() * m -- \\n\" << result << endl;\n\t\tresult = (m.array() * n.array()).matrix() * m;\n\t\tcout << \"-- Combo 2: (m.array() * n.array()).matrix() * m --\\n\" << result << endl;\n\t}\n\n\tsystem(\"pause\");\n}", "meta": {"hexsha": "cd53a1650ba0c0b3b75972c23a8471e5bff9833b", "size": 1887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/array_manipulation/array_manipulation.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/array_manipulation/array_manipulation.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/array_manipulation/array_manipulation.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": 22.4642857143, "max_line_length": 84, "alphanum_fraction": 0.4515103339, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6018996918692152}}
{"text": "/*hseqr.cpp\n */\n\n#include<iostream>\n#include<complex>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/bindings/ublas/matrix.hpp>\n#include <boost/numeric/bindings/ublas/vector.hpp>\n//#include <boost/numeric/bindings/detail/complex_utils.hpp>\n#include <boost/numeric/bindings/vector_view.hpp>\n#include <boost/numeric/bindings/lapack/computational/hseqr.hpp>\n#include <boost/numeric/bindings/lapack/computational/trevc.hpp>\n\nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::complex;\n\nnamespace ublas =  boost::numeric::ublas;\nnamespace lapack =  boost::numeric::bindings::lapack;\nnamespace bindings =  boost::numeric::bindings;\nnamespace tag =  boost::numeric::bindings::tag;\n\nvoid hseqr(int);\ntemplate <typename T>\nvoid Hessenberg(ublas::matrix<T, ublas::column_major>&);\ntemplate <typename T>\nvoid Hessenberg(ublas::matrix<complex<T>, ublas::column_major>&);\n\nint main()\n{\n  cout << \"I'm testing uBlas.\" << endl;\n\n  int n = 5;\n  hseqr(n);\n\n}\n\nvoid hseqr(int n)\n{\n  cout << \"\\nCalculating eigenvalues using LAPACK's hseqr.\" << endl;\n  ublas::matrix<double, ublas::column_major> H(n,n);\n  Hessenberg(H);\n  cout << \"\\nUpper Hessenberg matrix H:\\n\" << H << endl;\n\n  ublas::vector<complex<double> > values(n);\n  ublas::matrix<double, ublas::column_major> Z(n,n);\n\n  cout << \"\\nHSEQR for only eigenvalues.\" << endl;\n  ublas::matrix<double, ublas::column_major> Z_dummy(1,1);\n  lapack::hseqr('E', 'N', 1, n, H, values, Z_dummy);\n  /*\n  lapack::hseqr('E', 'N', 1, n, H,\n      bindings::detail::real_part_view(values),\n      bindings::detail::imag_part_view(values),\n      Z_dummy);\n  bindings::detail::interlace(values);\n  */\n  cout << \"\\nH:\\n\" << H << endl;\n  cout << \"\\nvalues: \" << values << endl;\n\n  cout << \"\\nHSEQR for eigenvalues and Schur vectors.\" << endl;\n  Hessenberg(H);\n  cout << \"H:\\n\" << H << endl;\n  lapack::hseqr('S', 'I', 1, n, H, values, Z);\n  /*\n  lapack::hseqr('S', 'I', 1, n, H,\n      bindings::detail::real_part_view(values),\n      bindings::detail::imag_part_view(values),\n      Z);\n  bindings::detail::interlace(values);\n  */\n  cout << \"\\nH: \" << H << endl;\n  cout << \"\\nvalues: \" << values << endl;\n  cout << \"\\nZ: \" << Z << endl;\n\n  cout << \"\\n==================================\" << endl;\n  cout << \"Recalculating original matrix...\" << endl;\n  ublas::matrix<double, ublas::column_major> cH(n,n);\n  cH = ublas::prod(H, ublas::herm(Z));\n  cH = ublas::prod(Z, cH);\n  cout << \"'New' original matrix:\\n\" << cH << endl;\n  cout << \"==================================\" << endl;\n\n\n  cout << \"\\nHSEQR for only eigenvalues.  Complex version\" << endl;\n  ublas::matrix<complex<double>, ublas::column_major> G(n,n);\n  Hessenberg(G);\n  cout << \"\\nG:\\n\" << G << endl;\n  ublas::matrix<complex<double>, ublas::column_major> cZ_dummy(1,1);\n  lapack::hseqr('E', 'N', 1, n, G, values, cZ_dummy);\n  cout << \"\\nG:\\n\" << G << endl;\n  cout << \"\\nvalues: \" << values << endl;\n\n  cout << \"\\nHSEQR for eigenvalues and Schur vectors.\" << endl;\n  Hessenberg(G);\n  cout << \"G:\\n\" << G << endl;\n  ublas::matrix<complex<double>, ublas::column_major> cZ(n,n);\n  lapack::hseqr('S', 'I', 1, n, G, values, cZ);\n  cout << \"\\nG:\\n \" << G << endl;\n  cout << \"\\nvalues: \" << values << endl;\n  cout << \"\\nZ:\\n \" << Z << endl;\n\n  cout << \"\\n==================================\" << endl;\n  cout << \"Recalculating original matrix...\" << endl;\n  ublas::matrix<complex<double>, ublas::column_major> origG(G);\n  origG = ublas::prod(G, ublas::herm(cZ));\n  origG = ublas::prod(cZ, origG);\n  cout << \"'New' original matrix:\\n\" << origG << endl;\n  cout << \"==================================\" << endl;\n\n  ublas::matrix<complex<double>, ublas::column_major> cVL(cZ);\n  ublas::matrix<complex<double>, ublas::column_major> cVR(cZ);\n  boost::numeric::bindings::detail::array<complex<double> > work_c(2*n);\n  boost::numeric::bindings::detail::array<double> work_r(n);\n  ublas::vector<fortran_bool_t> select_dummy(n);\n  fortran_int_t m_info(n+1);\n  lapack::trevc(tag::both(),'B',select_dummy,G,cVL,cVR,n,m_info,lapack::workspace(work_c,work_r));\n\n  cout << \"\\n==================================\" << endl;\n  cout << \"Testing left & right eigenvectors...\" << endl;\n  Hessenberg(G);\n  cout << \"Many 'zeros':\" << endl;\n  for(int i=0; i<n; ++i)\n  {\n    cout << (ublas::prod(G, column(cVR, i)) - values(i) * column(cVR, i)) << endl;\n    cout << (ublas::prod(ublas::herm(G), column(cVL, i)) - conj(values(i)) * column(cVL, i)) << endl;\n  }\n  cout << \"==================================\" << endl;\n\n  cout << \"\\n==================================\" << endl;\n  cout << \"Verifying diagonal matrix...\" << endl;\n  ublas::matrix<complex<double>, ublas::column_major> cG(n,n,0);\n  Hessenberg(G);\n  G = ublas::prod(G, cVR);\n  G = ublas::prod(ublas::herm(cVL), G);\n  cout << \"'diagonal' matrix:\\n\" << G << endl;\n  cout << \"==================================\" << endl;\n\n}\n\n\ntemplate <typename T>\nvoid Hessenberg(ublas::matrix<T, ublas::column_major>& H)\n{\n  T k = 1;\n  for(unsigned int i = 0; i < H.size1(); ++i)\n  {\n    for(unsigned int j = i; j <= H.size2(); ++j)\n    {\n      if(j > 0)\n      {\n        H(i,j-1) = k;\n        k += 1;\n      }\n    }\n  }\n}\n\ntemplate <typename T>\nvoid Hessenberg(ublas::matrix<complex<T>, ublas::column_major>& H)\n{\n  T k = 1.0;\n  for(unsigned int i = 0; i < H.size1(); ++i)\n  {\n    for(unsigned int j = i; j <= H.size2(); ++j)\n    {\n      if(j > 0)\n      {\n        T real = k++;\n        T imag = k++;\n        H(i,j-1) = complex<T>(real, imag);\n      }\n    }\n  }\n}\n\n", "meta": {"hexsha": "40804b34214b0cfbcb60ede2a184a20c8d961ba1", "size": 5556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/hseqr.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/hseqr.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/hseqr.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 30.8666666667, "max_line_length": 101, "alphanum_fraction": 0.5763138949, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.7279754371026367, "lm_q1q2_score": 0.6018258796465035}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file    DoglegOptimizer.h\n * @brief   Unit tests for DoglegOptimizer\n * @author  Richard Roberts\n */\n\n#include <tests/smallExample.h>\n#include <gtsam/nonlinear/DoglegOptimizerImpl.h>\n#include <gtsam/nonlinear/Symbol.h>\n#include <gtsam/linear/JacobianFactor.h>\n#include <gtsam/linear/GaussianSequentialSolver.h>\n#include <gtsam/linear/GaussianBayesTree.h>\n#include <gtsam/inference/BayesTree.h>\n#include <gtsam/base/numericalDerivative.h>\n\n#include <CppUnitLite/TestHarness.h>\n\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-variable\"\n#endif\n#include <boost/bind.hpp>\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n#include <boost/assign/list_of.hpp> // for 'list_of()'\n#include <functional>\n#include <boost/iterator/counting_iterator.hpp>\n\nusing namespace std;\nusing namespace gtsam;\n\n// Convenience for named keys\nusing symbol_shorthand::X;\nusing symbol_shorthand::L;\n\n/* ************************************************************************* */\ndouble computeError(const GaussianBayesNet& gbn, const LieVector& values) {\n\n  // Convert Vector to VectorValues\n  VectorValues vv = *allocateVectorValues(gbn);\n  internal::writeVectorValuesSlices(values, vv,\n    boost::make_counting_iterator(size_t(0)), boost::make_counting_iterator(vv.size()));\n\n  // Convert to factor graph\n  GaussianFactorGraph gfg(gbn);\n  return gfg.error(vv);\n}\n\n/* ************************************************************************* */\ndouble computeErrorBt(const BayesTree<GaussianConditional>& gbt, const LieVector& values) {\n\n  // Convert Vector to VectorValues\n  VectorValues vv = *allocateVectorValues(gbt);\n  internal::writeVectorValuesSlices(values, vv,\n    boost::make_counting_iterator(size_t(0)), boost::make_counting_iterator(vv.size()));\n\n  // Convert to factor graph\n  GaussianFactorGraph gfg(gbt);\n  return gfg.error(vv);\n}\n\n/* ************************************************************************* */\nTEST(DoglegOptimizer, ComputeSteepestDescentPoint) {\n\n  // Create an arbitrary Bayes Net\n  GaussianBayesNet gbn;\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      0, Vector_(2, 1.0,2.0), Matrix_(2,2, 3.0,4.0,0.0,6.0),\n      3, Matrix_(2,2, 7.0,8.0,9.0,10.0),\n      4, Matrix_(2,2, 11.0,12.0,13.0,14.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      1, Vector_(2, 15.0,16.0), Matrix_(2,2, 17.0,18.0,0.0,20.0),\n      2, Matrix_(2,2, 21.0,22.0,23.0,24.0),\n      4, Matrix_(2,2, 25.0,26.0,27.0,28.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      2, Vector_(2, 29.0,30.0), Matrix_(2,2, 31.0,32.0,0.0,34.0),\n      3, Matrix_(2,2, 35.0,36.0,37.0,38.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      3, Vector_(2, 39.0,40.0), Matrix_(2,2, 41.0,42.0,0.0,44.0),\n      4, Matrix_(2,2, 45.0,46.0,47.0,48.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      4, Vector_(2, 49.0,50.0), Matrix_(2,2, 51.0,52.0,0.0,54.0), ones(2)));\n\n  // Compute the Hessian numerically\n  Matrix hessian = numericalHessian(\n      boost::function<double(const LieVector&)>(boost::bind(&computeError, gbn, _1)),\n      LieVector(VectorValues::Zero(*allocateVectorValues(gbn)).asVector()));\n\n  // Compute the gradient numerically\n  VectorValues gradientValues = *allocateVectorValues(gbn);\n  Vector gradient = numericalGradient(\n      boost::function<double(const LieVector&)>(boost::bind(&computeError, gbn, _1)),\n      LieVector(VectorValues::Zero(gradientValues).asVector()));\n  internal::writeVectorValuesSlices(gradient, gradientValues,\n    boost::make_counting_iterator(size_t(0)), boost::make_counting_iterator(gradientValues.size()));\n\n  // Compute the gradient using dense matrices\n  Matrix augmentedHessian = GaussianFactorGraph(gbn).augmentedHessian();\n  LONGS_EQUAL(11, augmentedHessian.cols());\n  VectorValues denseMatrixGradient = *allocateVectorValues(gbn);\n  internal::writeVectorValuesSlices(-augmentedHessian.col(10).segment(0,10), denseMatrixGradient,\n    boost::make_counting_iterator(size_t(0)), boost::make_counting_iterator(gradientValues.size()));\n  EXPECT(assert_equal(gradientValues, denseMatrixGradient, 1e-5));\n\n  // Compute the steepest descent point\n  double step = -gradient.squaredNorm() / (gradient.transpose() * hessian * gradient)(0);\n  VectorValues expected = gradientValues;  scal(step, expected);\n\n  // Compute the steepest descent point with the dogleg function\n  VectorValues actual = optimizeGradientSearch(gbn);\n\n  // Check that points agree\n  EXPECT(assert_equal(expected, actual, 1e-5));\n\n  // Check that point causes a decrease in error\n  double origError = GaussianFactorGraph(gbn).error(VectorValues::Zero(*allocateVectorValues(gbn)));\n  double newError = GaussianFactorGraph(gbn).error(actual);\n  EXPECT(newError < origError);\n}\n\n/* ************************************************************************* */\nTEST(DoglegOptimizer, BT_BN_equivalency) {\n\n  // Create an arbitrary Bayes Tree\n  BayesTree<GaussianConditional> bt;\n  bt.insert(BayesTree<GaussianConditional>::sharedClique(new BayesTree<GaussianConditional>::Clique(\n      GaussianConditional::shared_ptr(new GaussianConditional(\n          boost::assign::pair_list_of\n          (2, Matrix_(6,2,\n              31.0,32.0,\n              0.0,34.0,\n              0.0,0.0,\n              0.0,0.0,\n              0.0,0.0,\n              0.0,0.0))\n          (3, Matrix_(6,2,\n              35.0,36.0,\n              37.0,38.0,\n              41.0,42.0,\n              0.0,44.0,\n              0.0,0.0,\n              0.0,0.0))\n          (4, Matrix_(6,2,\n              0.0,0.0,\n              0.0,0.0,\n              45.0,46.0,\n              47.0,48.0,\n              51.0,52.0,\n              0.0,54.0)),\n          3, Vector_(6, 29.0,30.0,39.0,40.0,49.0,50.0), ones(6))))));\n  bt.insert(BayesTree<GaussianConditional>::sharedClique(new BayesTree<GaussianConditional>::Clique(\n      GaussianConditional::shared_ptr(new GaussianConditional(\n          boost::assign::pair_list_of\n          (0, Matrix_(4,2,\n              3.0,4.0,\n              0.0,6.0,\n              0.0,0.0,\n              0.0,0.0))\n          (1, Matrix_(4,2,\n              0.0,0.0,\n              0.0,0.0,\n              17.0,18.0,\n              0.0,20.0))\n          (2, Matrix_(4,2,\n              0.0,0.0,\n              0.0,0.0,\n              21.0,22.0,\n              23.0,24.0))\n          (3, Matrix_(4,2,\n              7.0,8.0,\n              9.0,10.0,\n              0.0,0.0,\n              0.0,0.0))\n          (4, Matrix_(4,2,\n              11.0,12.0,\n              13.0,14.0,\n              25.0,26.0,\n              27.0,28.0)),\n          2, Vector_(4, 1.0,2.0,15.0,16.0), ones(4))))));\n\n  // Create an arbitrary Bayes Net\n  GaussianBayesNet gbn;\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      0, Vector_(2, 1.0,2.0), Matrix_(2,2, 3.0,4.0,0.0,6.0),\n      3, Matrix_(2,2, 7.0,8.0,9.0,10.0),\n      4, Matrix_(2,2, 11.0,12.0,13.0,14.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      1, Vector_(2, 15.0,16.0), Matrix_(2,2, 17.0,18.0,0.0,20.0),\n      2, Matrix_(2,2, 21.0,22.0,23.0,24.0),\n      4, Matrix_(2,2, 25.0,26.0,27.0,28.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      2, Vector_(2, 29.0,30.0), Matrix_(2,2, 31.0,32.0,0.0,34.0),\n      3, Matrix_(2,2, 35.0,36.0,37.0,38.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      3, Vector_(2, 39.0,40.0), Matrix_(2,2, 41.0,42.0,0.0,44.0),\n      4, Matrix_(2,2, 45.0,46.0,47.0,48.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      4, Vector_(2, 49.0,50.0), Matrix_(2,2, 51.0,52.0,0.0,54.0), ones(2)));\n\n  GaussianFactorGraph expected(gbn);\n  GaussianFactorGraph actual(bt);\n\n  EXPECT(assert_equal(expected.augmentedHessian(), actual.augmentedHessian()));\n}\n\n/* ************************************************************************* */\nTEST(DoglegOptimizer, ComputeSteepestDescentPointBT) {\n\n  // Create an arbitrary Bayes Tree\n  BayesTree<GaussianConditional> bt;\n  bt.insert(BayesTree<GaussianConditional>::sharedClique(new BayesTree<GaussianConditional>::Clique(\n      GaussianConditional::shared_ptr(new GaussianConditional(\n          boost::assign::pair_list_of\n          (2, Matrix_(6,2,\n              31.0,32.0,\n              0.0,34.0,\n              0.0,0.0,\n              0.0,0.0,\n              0.0,0.0,\n              0.0,0.0))\n          (3, Matrix_(6,2,\n              35.0,36.0,\n              37.0,38.0,\n              41.0,42.0,\n              0.0,44.0,\n              0.0,0.0,\n              0.0,0.0))\n          (4, Matrix_(6,2,\n              0.0,0.0,\n              0.0,0.0,\n              45.0,46.0,\n              47.0,48.0,\n              51.0,52.0,\n              0.0,54.0)),\n          3, Vector_(6, 29.0,30.0,39.0,40.0,49.0,50.0), ones(6))))));\n  bt.insert(BayesTree<GaussianConditional>::sharedClique(new BayesTree<GaussianConditional>::Clique(\n      GaussianConditional::shared_ptr(new GaussianConditional(\n          boost::assign::pair_list_of\n          (0, Matrix_(4,2,\n              3.0,4.0,\n              0.0,6.0,\n              0.0,0.0,\n              0.0,0.0))\n          (1, Matrix_(4,2,\n              0.0,0.0,\n              0.0,0.0,\n              17.0,18.0,\n              0.0,20.0))\n          (2, Matrix_(4,2,\n              0.0,0.0,\n              0.0,0.0,\n              21.0,22.0,\n              23.0,24.0))\n          (3, Matrix_(4,2,\n              7.0,8.0,\n              9.0,10.0,\n              0.0,0.0,\n              0.0,0.0))\n          (4, Matrix_(4,2,\n              11.0,12.0,\n              13.0,14.0,\n              25.0,26.0,\n              27.0,28.0)),\n          2, Vector_(4, 1.0,2.0,15.0,16.0), ones(4))))));\n\n  // Compute the Hessian numerically\n  Matrix hessian = numericalHessian(\n      boost::function<double(const LieVector&)>(boost::bind(&computeErrorBt, bt, _1)),\n      LieVector(VectorValues::Zero(*allocateVectorValues(bt)).asVector()));\n\n  // Compute the gradient numerically\n  VectorValues gradientValues = *allocateVectorValues(bt);\n  Vector gradient = numericalGradient(\n      boost::function<double(const LieVector&)>(boost::bind(&computeErrorBt, bt, _1)),\n      LieVector(VectorValues::Zero(gradientValues).asVector()));\n  internal::writeVectorValuesSlices(gradient, gradientValues,\n    boost::make_counting_iterator(size_t(0)), boost::make_counting_iterator(gradientValues.size()));\n\n  // Compute the gradient using dense matrices\n  Matrix augmentedHessian = GaussianFactorGraph(bt).augmentedHessian();\n  LONGS_EQUAL(11, augmentedHessian.cols());\n  VectorValues denseMatrixGradient = *allocateVectorValues(bt);\n  internal::writeVectorValuesSlices(-augmentedHessian.col(10).segment(0,10), denseMatrixGradient,\n    boost::make_counting_iterator(size_t(0)), boost::make_counting_iterator(gradientValues.size()));\n  EXPECT(assert_equal(gradientValues, denseMatrixGradient, 1e-5));\n\n  // Compute the steepest descent point\n  double step = -gradient.squaredNorm() / (gradient.transpose() * hessian * gradient)(0);\n  VectorValues expected = gradientValues;  scal(step, expected);\n\n  // Known steepest descent point from Bayes' net version\n  VectorValues expectedFromBN(5,2);\n  expectedFromBN[0] = Vector_(2, 0.000129034, 0.000688183);\n  expectedFromBN[1] = Vector_(2, 0.0109679, 0.0253767);\n  expectedFromBN[2] = Vector_(2, 0.0680441, 0.114496);\n  expectedFromBN[3] = Vector_(2, 0.16125, 0.241294);\n  expectedFromBN[4] = Vector_(2, 0.300134, 0.423233);\n\n  // Compute the steepest descent point with the dogleg function\n  VectorValues actual = optimizeGradientSearch(bt);\n\n  // Check that points agree\n  EXPECT(assert_equal(expected, actual, 1e-5));\n  EXPECT(assert_equal(expectedFromBN, actual, 1e-5));\n\n  // Check that point causes a decrease in error\n  double origError = GaussianFactorGraph(bt).error(VectorValues::Zero(*allocateVectorValues(bt)));\n  double newError = GaussianFactorGraph(bt).error(actual);\n  EXPECT(newError < origError);\n}\n\n/* ************************************************************************* */\nTEST(DoglegOptimizer, ComputeBlend) {\n  // Create an arbitrary Bayes Net\n  GaussianBayesNet gbn;\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      0, Vector_(2, 1.0,2.0), Matrix_(2,2, 3.0,4.0,0.0,6.0),\n      3, Matrix_(2,2, 7.0,8.0,9.0,10.0),\n      4, Matrix_(2,2, 11.0,12.0,13.0,14.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      1, Vector_(2, 15.0,16.0), Matrix_(2,2, 17.0,18.0,0.0,20.0),\n      2, Matrix_(2,2, 21.0,22.0,23.0,24.0),\n      4, Matrix_(2,2, 25.0,26.0,27.0,28.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      2, Vector_(2, 29.0,30.0), Matrix_(2,2, 31.0,32.0,0.0,34.0),\n      3, Matrix_(2,2, 35.0,36.0,37.0,38.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      3, Vector_(2, 39.0,40.0), Matrix_(2,2, 41.0,42.0,0.0,44.0),\n      4, Matrix_(2,2, 45.0,46.0,47.0,48.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      4, Vector_(2, 49.0,50.0), Matrix_(2,2, 51.0,52.0,0.0,54.0), ones(2)));\n\n  // Compute steepest descent point\n  VectorValues xu = optimizeGradientSearch(gbn);\n\n  // Compute Newton's method point\n  VectorValues xn = optimize(gbn);\n\n  // The Newton's method point should be more \"adventurous\", i.e. larger, than the steepest descent point\n  EXPECT(xu.asVector().norm() < xn.asVector().norm());\n\n  // Compute blend\n  double Delta = 1.5;\n  VectorValues xb = DoglegOptimizerImpl::ComputeBlend(Delta, xu, xn);\n  DOUBLES_EQUAL(Delta, xb.asVector().norm(), 1e-10);\n}\n\n/* ************************************************************************* */\nTEST(DoglegOptimizer, ComputeDoglegPoint) {\n  // Create an arbitrary Bayes Net\n  GaussianBayesNet gbn;\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      0, Vector_(2, 1.0,2.0), Matrix_(2,2, 3.0,4.0,0.0,6.0),\n      3, Matrix_(2,2, 7.0,8.0,9.0,10.0),\n      4, Matrix_(2,2, 11.0,12.0,13.0,14.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      1, Vector_(2, 15.0,16.0), Matrix_(2,2, 17.0,18.0,0.0,20.0),\n      2, Matrix_(2,2, 21.0,22.0,23.0,24.0),\n      4, Matrix_(2,2, 25.0,26.0,27.0,28.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      2, Vector_(2, 29.0,30.0), Matrix_(2,2, 31.0,32.0,0.0,34.0),\n      3, Matrix_(2,2, 35.0,36.0,37.0,38.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      3, Vector_(2, 39.0,40.0), Matrix_(2,2, 41.0,42.0,0.0,44.0),\n      4, Matrix_(2,2, 45.0,46.0,47.0,48.0), ones(2)));\n  gbn += GaussianConditional::shared_ptr(new GaussianConditional(\n      4, Vector_(2, 49.0,50.0), Matrix_(2,2, 51.0,52.0,0.0,54.0), ones(2)));\n\n  // Compute dogleg point for different deltas\n\n  double Delta1 = 0.5;  // Less than steepest descent\n  VectorValues actual1 = DoglegOptimizerImpl::ComputeDoglegPoint(Delta1, optimizeGradientSearch(gbn), optimize(gbn));\n  DOUBLES_EQUAL(Delta1, actual1.asVector().norm(), 1e-5);\n\n  double Delta2 = 1.5;  // Between steepest descent and Newton's method\n  VectorValues expected2 = DoglegOptimizerImpl::ComputeBlend(Delta2, optimizeGradientSearch(gbn), optimize(gbn));\n  VectorValues actual2 = DoglegOptimizerImpl::ComputeDoglegPoint(Delta2, optimizeGradientSearch(gbn), optimize(gbn));\n  DOUBLES_EQUAL(Delta2, actual2.asVector().norm(), 1e-5);\n  EXPECT(assert_equal(expected2, actual2));\n\n  double Delta3 = 5.0;  // Larger than Newton's method point\n  VectorValues expected3 = optimize(gbn);\n  VectorValues actual3 = DoglegOptimizerImpl::ComputeDoglegPoint(Delta3, optimizeGradientSearch(gbn), optimize(gbn));\n  EXPECT(assert_equal(expected3, actual3));\n}\n\n/* ************************************************************************* */\nTEST(DoglegOptimizer, Iterate) {\n  // really non-linear factor graph\n  boost::shared_ptr<example::Graph> fg(new example::Graph(\n      example::createReallyNonlinearFactorGraph()));\n\n  // config far from minimum\n  Point2 x0(3,0);\n  boost::shared_ptr<Values> config(new Values);\n  config->insert(X(1), x0);\n\n  // ordering\n  boost::shared_ptr<Ordering> ord(new Ordering());\n  ord->push_back(X(1));\n\n  double Delta = 1.0;\n  for(size_t it=0; it<10; ++it) {\n    GaussianSequentialSolver solver(*fg->linearize(*config, *ord));\n    GaussianBayesNet gbn = *solver.eliminate();\n    // Iterate assumes that linear error = nonlinear error at the linearization point, and this should be true\n    double nonlinearError = fg->error(*config);\n    double linearError = GaussianFactorGraph(gbn).error(VectorValues::Zero(*allocateVectorValues(gbn)));\n    DOUBLES_EQUAL(nonlinearError, linearError, 1e-5);\n//    cout << \"it \" << it << \", Delta = \" << Delta << \", error = \" << fg->error(*config) << endl;\n    DoglegOptimizerImpl::IterationResult result = DoglegOptimizerImpl::Iterate(Delta, DoglegOptimizerImpl::SEARCH_EACH_ITERATION, gbn, *fg, *config, *ord, fg->error(*config));\n    Delta = result.Delta;\n    EXPECT(result.f_error < fg->error(*config)); // Check that error decreases\n    Values newConfig(config->retract(result.dx_d, *ord));\n    (*config) = newConfig;\n    DOUBLES_EQUAL(fg->error(*config), result.f_error, 1e-5); // Check that error is correctly filled in\n  }\n}\n\n/* ************************************************************************* */\nint main() { TestResult tr; return TestRegistry::runAllTests(tr); }\n/* ************************************************************************* */\n", "meta": {"hexsha": "008ea443a8e9d76e7b58b8490b96597b3dbd237e", "size": 17935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testDoglegOptimizer.cpp", "max_stars_repo_name": "malcolmreynolds/GTSAM", "max_stars_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-23T19:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-23T19:34:50.000Z", "max_issues_repo_path": "tests/testDoglegOptimizer.cpp", "max_issues_repo_name": "malcolmreynolds/GTSAM", "max_issues_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/testDoglegOptimizer.cpp", "max_forks_repo_name": "malcolmreynolds/GTSAM", "max_forks_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2298850575, "max_line_length": 175, "alphanum_fraction": 0.6123222749, "num_tokens": 5598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6018258783093555}}
{"text": "#include \"gfunc.h\"\n#include <algorithm>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/geometries/multi_point.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/multi_linestring.hpp>\n#include <boost/geometry/geometries/box.hpp>\n#include <boost/geometry/geometries/ring.hpp>\n#include <boost/geometry/geometries/variant.hpp>\n\nnamespace bg = boost::geometry;\n\ntypedef bg::model::d2::point_xy<double> DPoint;\ntypedef bg::model::segment<DPoint> DSegment;\n\nstd::vector<double>\nintersection_seg_arc(double xc, double yc, double rr, double x0, double y0, double x1, double y1) {\n    double t1, t2;\n    std::vector<double> res;\n    double h = xc;\n    double k = yc;\n    double r = rr;\n    double a = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);\n    double b = 2 * (x1 - x0) * ((x0 - h)) + 2 * (y1 - y0) * (y0 - k);\n    double c = (x0 - h) * (x0 - h) + (y0 - k) * (y0 - k) - r * r;\n    if (b * b - 4 * a * c < 0) {\n        return res;\n    } else {\n        t1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);\n        t2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);\n    }\n    if (t1 >= 0 && t1 <= 1) {\n\n        res.push_back((x1 - x0) * t1 + x0);\n        res.push_back((y1 - y0) * t1 + y0);\n        // res[0] = (x1 - x0) * t1 + x0;\n        // res[1] = (y1 - y0) * t1 + y0;\n    } else if (t2 >= 0 && t2 <= 1) {\n        res.push_back((x1 - x0) * t2 + x0);\n        res.push_back((y1 - y0) * t2 + y0);\n        // res[0] = ((x1 - x0) * t2 + x0);\n        // res[1] = ((y1 - y0) * t2 + y0);\n    } else {\n        // \u65e0\u4ea4\u70b9\n        return res;\n    }\n    return res;\n}\n\n//std::vector<double> intersection_seg_seg(double *&st0, double *&ed0, double *&st1, double *&ed1) {\n//    std::vector<double> res;\n//    DPoint pt00(st0[0],st0[1]);\n//    DPoint pt01(ed0[0],ed0[1]);\n//    DPoint pt10(st1[0],st1[1]);\n//    DPoint pt11(ed1[0],ed1[1]);\n//    DSegment sg0(pt00,pt01);\n//    DSegment sg1(pt10,pt11);\n//\n//    std::list<DPoint> lstPoints;\n//\n//    if (bg::intersects(sg0, sg1)){\n//        bg::intersection(sg0, sg1, lstPoints);\n//        res.push_back(lstPoints.begin()->x());\n//        res.push_back(lstPoints.begin()->y());\n//    }\n//    return res;\n//}\n\nstd::vector<double> intersection_seg_seg(py::list st0, py::list ed0, py::list st1, py::list ed1) {\n    std::vector<double> res;\n    DPoint pt00(st0[0].cast<double>(), st0[1].cast<double>());\n    DPoint pt01(ed0[0].cast<double>(), ed0[1].cast<double>());\n    DPoint pt10(st1[0].cast<double>(), st1[1].cast<double>());\n    DPoint pt11(ed1[0].cast<double>(), ed1[1].cast<double>());\n    DSegment sg0(pt00, pt01);\n    DSegment sg1(pt10, pt11);\n\n    std::list<DPoint> lstPoints;\n\n    if (bg::intersects(sg0, sg1)) {\n        bg::intersection(sg0, sg1, lstPoints);\n        res.push_back(lstPoints.begin()->x());\n        res.push_back(lstPoints.begin()->y());\n    }\n    return res;\n}\n\n", "meta": {"hexsha": "012ca42e4f76c23865a578e5a51ae821116c6ddf", "size": 3104, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/srbpy/public/gfunc.cpp", "max_stars_repo_name": "billhu0228/SmartRoadBridgePy", "max_stars_repo_head_hexsha": "4a5d34028a2612aef846b580733bf6f488110798", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-05T10:46:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T11:05:18.000Z", "max_issues_repo_path": "src/srbpy/public/gfunc.cpp", "max_issues_repo_name": "billhu0228/SmartRoadBridgePy", "max_issues_repo_head_hexsha": "4a5d34028a2612aef846b580733bf6f488110798", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/srbpy/public/gfunc.cpp", "max_forks_repo_name": "billhu0228/SmartRoadBridgePy", "max_forks_repo_head_hexsha": "4a5d34028a2612aef846b580733bf6f488110798", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T07:50:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-26T07:50:22.000Z", "avg_line_length": 33.376344086, "max_line_length": 100, "alphanum_fraction": 0.5740979381, "num_tokens": 1071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6017858973963572}}
{"text": "#ifndef MLT_MODELS_TRANSFORMERS_PRINCIPAL_COMPONENTS_ANALYSIS_IMPL_HPP\n#define MLT_MODELS_TRANSFORMERS_PRINCIPAL_COMPONENTS_ANALYSIS_IMPL_HPP\n\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\n#include \"transformer.hpp\"\n\nnamespace mlt {\nnamespace models {\nnamespace transformers {\n\ttemplate<class ConcreteType>\n\tclass PrincipalComponentsAnalysisImpl : public Transformer<ConcreteType> {\n\tpublic:\n\t\tinline auto components_size() const { assert(_fitted); return _components_size; }\n\n\t\tinline const auto components() const { assert(_fitted); return _components; }\n\n\t\tinline const auto explained_variance_ratio() const { assert(_fitted); return _explained_variance_ratio; }\n\n\t\tinline const auto noise_variance() const { assert(_fitted); return _noise_variance; }\n\n\t\tSelf& fit(Features input, bool = true) {\n\t\t\tassert(_components_size == -1 || _components_size <= input.cols());\n\n\t\t\t_mean = input.rowwise().mean();\n\t\t\tMatrixXd final = input.colwise() - _mean;\n\n\t\t\tauto svd = ((final * final.transpose()) / input.cols()).jacobiSvd(ComputeThinU);\n\n\t\t\t_explained_variance = svd.singularValues();\n\t\t\t_explained_variance_ratio = _explained_variance / _explained_variance.sum();\n\n\t\t\tif (_components_size < 1 && _variance_to_retain < 0) {\n\t\t\t\t_components_size = input.rows();\n\t\t\t} else if (_components_size < 1 && _variance_to_retain > 0) {\n\t\t\t\tdouble acum = 0;\n\t\t\t\tsize_t i = 0;\n\t\t\t\twhile (i < _explained_variance_ratio.rows() && acum < _variance_to_retain) {\n\t\t\t\t\tacum += _explained_variance_ratio(i);\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\t_components_size = i + 1;\n\t\t\t}\n\n\t\t\tif (_components_size > svd.matrixU().cols()) {\n\t\t\t\t_components_size = _components.cols();\n\t\t\t}\n\n\t\t\tif (_components_size < std::min(input.rows(), input.cols())) {\n\t\t\t\t_noise_variance = _explained_variance.tail(_explained_variance.size() - _components_size).mean();\n\t\t\t} else {\n\t\t\t\t_noise_variance = 0;\n\t\t\t}\n\n\t\t\t_components = svd.matrixU().leftCols(_components_size);\n\t\t\t_explained_variance = _explained_variance.head(_components_size);\n\t\t\t_explained_variance_ratio = _explained_variance_ratio.head(_components_size);\n\n\t\t\t_fitted = true;\n\n\t\t\treturn _self();\n\t\t}\n\n\t\tResult transform(Features input) const {\n\t\t\tassert(_fitted);\n\n\t\t\tif (_whiten) {\n\t\t\t\tauto transformed = (_components.transpose() * (input.colwise() - _mean));\n\t\t\t\treturn transformed.array().colwise() * _explained_variance.cwiseSqrt().cwiseInverse().array();\n\t\t\t}\n\n\t\t\treturn _components.transpose() * (input.colwise() - _mean);\n\t\t}\n\n\t\tFeatures inverse_transform(Result input) const {\n\t\t\tassert(_fitted);\n\n\t\t\tif (_whiten) {\n\t\t\t\treturn (_components * (input.array().colwise() *_explained_variance.cwiseSqrt().array()).matrix()).colwise() + _mean;\n\t\t\t}\n\n\t\t\treturn (_components * input).colwise() + _mean;\n\t\t}\n\n\tprotected:\n\t\texplicit PrincipalComponentsAnalysisImpl(int components_size, bool whiten = false) : _components_size(components_size), _whiten(whiten) {}\n\n\t\texplicit PrincipalComponentsAnalysisImpl(double variance_to_retain, bool whiten = false) : _variance_to_retain(variance_to_retain), _whiten(whiten) {\n\t\t\tassert(variance_to_retain > 0 && variance_to_retain <= 1);\n\t\t}\n\n\t\texplicit PrincipalComponentsAnalysisImpl(bool whiten = false) : _whiten(whiten) {}\n\n\t\tint _components_size = -1;\n\t\tdouble _variance_to_retain = -1;\n\t\tVectorXd _mean;\n\t\tMatrixXd _components;\n\t\tVectorXd _explained_variance;\n\t\tVectorXd _explained_variance_ratio;\n\t\tdouble _noise_variance = 0;\n\t\tbool _whiten;\n\t};\n}\n}\n}\n#endif", "meta": {"hexsha": "1a5f55ee8ea01eb52ae5e76853176d9f5c906e47", "size": 3406, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/models/transformers/principal_components_analysis_impl.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/mlt/models/transformers/principal_components_analysis_impl.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlt/models/transformers/principal_components_analysis_impl.hpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8317757009, "max_line_length": 151, "alphanum_fraction": 0.7275396359, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6926419767901476, "lm_q1q2_score": 0.6017858957818273}}
{"text": "/*\nCopyright 2020 Standard Cyborg\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n#include \"standard_cyborg/algorithms/PrincipalAxes.hpp\"\n#include \"standard_cyborg/algorithms/Centroid.hpp\"\n\n#include \"standard_cyborg/sc3d/Geometry.hpp\"\n#include \"standard_cyborg/math/Mat3x4.hpp\"\n\n#include \"standard_cyborg/util/DataUtils.hpp\"\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wdocumentation\"\n#include <Eigen/Eigenvalues>\n#pragma clang diagnostic pop\n\nusing standard_cyborg::sc3d::Geometry;\nusing standard_cyborg::math::Vec3;\nusing standard_cyborg::math::Mat3x4;\n\nusing standard_cyborg::sc3d::Face3;\n\nnamespace standard_cyborg {\n\nnamespace algorithms {\n\nMat3x4 computeNormalwisePrincipalAxes(const Geometry& geometry)\n{\n    using namespace math;\n\n    Eigen::Matrix3f Moment;\n    Moment.setZero();\n    \n    Vec3 areaVector{0.0f, 0.0f, 0.0f};\n    Vec3 centroid{0.0f, 0.0f, 0.0f};\n    float areaSum = 0.0f;\n    \n    int numFaces = geometry.faceCount();\n    const std::vector<Face3>& faces = geometry.getFaces();\n    const std::vector<Vec3>& positions = geometry.getPositions();\n    \n    for (int i = 0; i < numFaces; i++) {\n        const Face3& face = faces[i];\n        const Vec3& pA = positions[face[0]];\n        const Vec3& pB = positions[face[1]];\n        const Vec3& pC = positions[face[2]];\n        \n        Vec3 faceCentroid = (pA + pB + pC) * (1.0f / 3.0f);\n        \n        // Vectors along two of the edges\n        Vec3 vBA = pB - pA;\n        Vec3 vCA = pC - pA;\n        \n        // Face area vector (strictly speaking, twice the area, but since we use it as\n        // a weight and also divide by twice the area, it's strictly equivalent.\n        Vec3 dArea = Vec3::cross(vBA, vCA);\n        \n        // Integrate the differential surface element area vectors into a summed area\n        // vectors. For a perfectly closed volume, this will sum to zero and won't work\n        // very well, but if part of the model is open, it will provide stable orientation\n        // where eigenvalues+eigenvectors don't.\n        areaVector += dArea;\n        \n        // Add this face's contributions to accumulators\n        float dAreaMagnitude = dArea.norm();\n        centroid += faceCentroid * dAreaMagnitude;\n        areaSum += dAreaMagnitude;\n        \n        Moment(0, 0) += dArea.x * dArea.x;\n        Moment(1, 0) += dArea.x * dArea.y;\n        Moment(2, 0) += dArea.x * dArea.z;\n        \n        //Moment(0, 1) += dArea.y * dArea.x;\n        Moment(1, 1) += dArea.y * dArea.y;\n        Moment(2, 1) += dArea.y * dArea.z;\n        \n        //Moment(0, 2) += dArea.z * dArea.x;\n        //Moment(1, 2) += dArea.z * dArea.y;\n        Moment(2, 2) += dArea.z * dArea.z;\n    }\n    \n    centroid /= areaSum;\n    \n    // The eigen docs state these entries are not used at all. We could copy them, but\n    // it has no effect.\n    // Moment(0, 1) = Moment(1, 0);\n    // Moment(0, 2) = Moment(2, 0);\n    // Moment(1, 2) = Moment(2, 1);\n    \n    // Recall that if a self-adjoint matrix is real, then it's also symmetric, and the\n    // eigenvalues of a real, symmetric matrix are real and also orthogonal.\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigensolver(Moment);\n    \n    auto eigenvectors = eigensolver.eigenvectors();\n    auto eigenvalues = eigensolver.eigenvalues();\n    \n    Vec3 axis0 = toVec3(eigenvectors.col(0));\n    Vec3 axis1 = toVec3(eigenvectors.col(1));\n    \n    // Eigenvectors are unique up to a sign, so we use the integrated area vector to\n    // select an orientation stable with respect to small peturtbations. The first two\n    // eigenvectors correspond to the strongest eigenvalues, so we flip their parity.\n    // The third eigenvalue encodes the least amount of information, so we overwrite it\n    // to enforce the correct parity.\n    if (Vec3::dot(areaVector, axis0) < 0.0f) axis0 = -axis0;\n    if (Vec3::dot(areaVector, axis1) < 0.0f) axis1 = -axis1;\n    Vec3 axis2{Vec3::cross(axis0, axis1)};\n    \n    // Return the transform which moves a model at the origin *into* alignment with this\n    // model. To align this model upright, you must invert this transform.\n    return Mat3x4{\n        axis0.x, axis1.x, axis2.x, centroid.x,\n        axis0.y, axis1.y, axis2.y, centroid.y,\n        axis0.z, axis1.z, axis2.z, centroid.z\n    };\n}\n\nMat3x4 computePointwisePrincipalAxes(const Geometry& geometry)\n{\n    using namespace math;\n\n    Eigen::Matrix3f Moment;\n    Moment.setZero();\n    \n    Vec3 areaVector{0.0f, 0.0f, 0.0f};\n    Vec3 centroid(computeCentroid(geometry));\n\n    int numFaces = geometry.faceCount();\n    const std::vector<Face3>& faces = geometry.getFaces();\n    const std::vector<Vec3>& positions = geometry.getPositions();\n    \n    \n    for (int i = 0; i < numFaces; i++) {\n        const Face3 face = faces[i];\n        const Vec3 pA = positions[face[0]];\n        const Vec3 pB = positions[face[1]];\n        const Vec3 pC = positions[face[2]];\n\n        Vec3 offset = (pA + pB + pC) * (1.0f / 3.0f) - centroid;\n\n        // Face area vector (strictly speaking, twice the area, but since we use it as\n        // a weight and also divide by twice the area, it's strictly equivalent.\n        Vec3 dArea = 0.5 * Vec3::cross(pB - pA, pC - pA);\n\n        // Integrate the differential surface element area vectors into a summed area\n        // vectors. For a perfectly closed volume, this will sum to zero and won't work\n        // very well, but if part of the model is open, it will provide stable orientation\n        // where eigenvalues+eigenvectors don't.\n        areaVector += dArea;\n\n        // Weight each face by its area\n        float weight = dArea.norm();\n        \n        Moment(0, 0) += offset.x * offset.x * weight;\n        Moment(1, 0) += offset.x * offset.y * weight;\n        Moment(2, 0) += offset.x * offset.z * weight;\n        \n        //Moment(0, 1) += offset.y * offset.x * weight;\n        Moment(1, 1) += offset.y * offset.y * weight;\n        Moment(2, 1) += offset.y * offset.z * weight;\n        \n        //Moment(0, 2) += offset.z * offset.x * weight;\n        //Moment(1, 2) += offset.z * offset.y * weight;\n        Moment(2, 2) += offset.z * offset.z * weight;\n    }\n    \n    // Recall that if a self-adjoint matrix is real, then it's also symmetric, and the\n    // eigenvalues of a real, symmetric matrix are real and also orthogonal.\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigensolver(Moment);\n    \n    auto eigenvectors = eigensolver.eigenvectors();\n    auto eigenvalues = eigensolver.eigenvalues();\n    \n    // Eigenvalues are sorted in *increasing* order, so the strongest axis is the last\n    Vec3 axis0 = toVec3(eigenvectors.col(2));\n    Vec3 axis1 = toVec3(eigenvectors.col(1));\n    \n    // Eigenvectors are unique up to a sign, so we use the integrated area vector to\n    // select an orientation stable with respect to small peturtbations. The first two\n    // eigenvectors correspond to the strongest eigenvalues, so we flip their parity.\n    // The third eigenvalue encodes the least amount of information, so we overwrite it\n    // to enforce the correct parity.\n    if (Vec3::dot(areaVector, axis0) < 0.0f) axis0 = -axis0;\n    if (Vec3::dot(areaVector, axis1) < 0.0f) axis1 = -axis1;\n    Vec3 axis2{Vec3::cross(axis0, axis1)};\n    \n    // Return the transform which moves a model at the origin *into* alignment with this\n    // model. To align this model upright, you must invert this transform.\n    return Mat3x4{\n        axis0.x, axis1.x, axis2.x, centroid.x,\n        axis0.y, axis1.y, axis2.y, centroid.y,\n        axis0.z, axis1.z, axis2.z, centroid.z\n    };\n}\n\nMat3x4 computePointwisePrincipalAxes(const std::vector<math::Vec3>& positions)\n{\n    using namespace math;\n\n    Eigen::Matrix3f Moment;\n    Moment.setZero();\n\n    Vec3 areaVector{0.0f, 0.0f, 0.0f};\n    Vec3 centroid(computeCentroid(positions));\n\n    for (int i = 0; i < positions.size(); i++) {\n        const Vec3 pA = positions[i];\n\n        Vec3 offset = pA - centroid;\n        areaVector += offset;\n\n        Moment(0, 0) += offset.x * offset.x;\n        Moment(1, 0) += offset.x * offset.y;\n        Moment(2, 0) += offset.x * offset.z;\n\n        //Moment(0, 1) += offset.y * offset.x * weight;\n        Moment(1, 1) += offset.y * offset.y;\n        Moment(2, 1) += offset.y * offset.z;\n\n        //Moment(0, 2) += offset.z * offset.x * weight;\n        //Moment(1, 2) += offset.z * offset.y * weight;\n        Moment(2, 2) += offset.z * offset.z;\n    }\n    \n    // Recall that if a self-adjoint matrix is real, then it's also symmetric, and the\n    // eigenvalues of a real, symmetric matrix are real and also orthogonal.\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigensolver(Moment);\n    \n    auto eigenvectors = eigensolver.eigenvectors();\n    auto eigenvalues = eigensolver.eigenvalues();\n    \n    // Eigenvalues are sorted in *increasing* order, so the strongest axis is the last\n    Vec3 axis0 = toVec3(eigenvectors.col(2));\n    Vec3 axis1 = toVec3(eigenvectors.col(1));\n    \n    // Eigenvectors are unique up to a sign, so we use the integrated area vector to\n    // select an orientation stable with respect to small peturtbations. The first two\n    // eigenvectors correspond to the strongest eigenvalues, so we flip their parity.\n    // The third eigenvalue encodes the least amount of information, so we overwrite it\n    // to enforce the correct parity.\n    if (Vec3::dot(areaVector, axis0) < 0.0f) axis0 = -axis0;\n    if (Vec3::dot(areaVector, axis1) < 0.0f) axis1 = -axis1;\n    Vec3 axis2{Vec3::cross(axis0, axis1)};\n    \n    // Return the transform which moves a model at the origin *into* alignment with this\n    // model. To align this model upright, you must invert this transform.\n    return Mat3x4{\n        axis0.x, axis1.x, axis2.x, centroid.x,\n        axis0.y, axis1.y, axis2.y, centroid.y,\n        axis0.z, axis1.z, axis2.z, centroid.z\n    };\n}\n\n}\n\n} // namespace StandardCyborg {\n", "meta": {"hexsha": "8f51697c1ca9b0fcee17f0fb1ba5ec88e2a8062f", "size": 10343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scsdk/c++/scsdk/standard_cyborg/algorithms/PrincipalAxes.cpp", "max_stars_repo_name": "StandardCyborg/scsdk", "max_stars_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T01:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T07:45:19.000Z", "max_issues_repo_path": "scsdk/c++/scsdk/standard_cyborg/algorithms/PrincipalAxes.cpp", "max_issues_repo_name": "StandardCyborg/scsdk", "max_issues_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scsdk/c++/scsdk/standard_cyborg/algorithms/PrincipalAxes.cpp", "max_forks_repo_name": "StandardCyborg/scsdk", "max_forks_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3074074074, "max_line_length": 90, "alphanum_fraction": 0.6443004931, "num_tokens": 2902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267660487573, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.6017858942365507}}
{"text": "#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/Eigenvalues> \n\n#include <unsupported/Eigen/KroneckerProduct>\n\n#include <Spectra/MatOp/SparseSymMatProd.h>\n#include <Spectra/SymEigsSolver.h>\n\n\n#include <iostream>\n#include <cassert>\n#include <random>\n#include <algorithm>\n\n#include \"edlib/Basis/Basis1DZ2.hpp\"\n#include \"edlib/Basis/ToOriginalBasis.hpp\"\n#include \"edlib/Hamiltonians/TIXXZ.hpp\"\n#include \"edlib/Op/NodeMV.hpp\"\n\n#include \"edlib/EDP/LocalHamiltonian.hpp\"\n#include \"edlib/EDP/ConstructSparseMat.hpp\"\n\nusing namespace edlib;\n\nEigen::SparseMatrix<double> getSX()\n{\n\tEigen::SparseMatrix<double> res(2,2);\n\tres.insert(0,1) = 1.0;\n\tres.insert(1,0) = 1.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<std::complex<double> > getSY()\n{\n\tEigen::SparseMatrix<std::complex<double> > res(2,2);\n\tconstexpr std::complex<double> I(0., 1.);\n\tres.insert(0,1) = -I;\n\tres.insert(1,0) = I;\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<double> getSZ()\n{\n\tEigen::SparseMatrix<double> res(2,2);\n\tres.insert(0,0) = 1.0;\n\tres.insert(1,1) = -1.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\ntemplate<typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> \ntwoQubitOp(int N, int pos1, int pos2,\n\t\tconst Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v1,\n\t\tconst Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v2)\n{\n\tusing namespace Eigen;\n\tconst uint32_t dim = (1u << N);\n\n\tassert(pos1 < pos2);\n\n\tEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> res(1,1);\n\tres(0,0) = 1.0;\n\n\tfor(int i = 0; i < pos1; i++)\n\t{\n\t\tres = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval();\n\t}\n\n\tres = Eigen::kroneckerProduct(v1, res).eval();\n\tfor(int i = pos1+1; i < pos2; i++)\n\t{\n\t\tres = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval();\n\t}\n\tres = Eigen::kroneckerProduct(v2, res).eval();\n\tfor(int i = pos2+1; i < N; i++)\n\t{\n\t\tres = Eigen::kroneckerProduct(MatrixXd::Identity(2,2), res).eval();\n\t}\n\treturn res;\n}\n\ntemplate<typename T>\nEigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> \nsingleQubitOp(int N, int pos, \n\t\tconst Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& v)\n{\n\tusing namespace Eigen;\n\tconst uint32_t dim = (1u << N);\n\n\tusing MatrixT = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> ;\n\tMatrixT res(1,1);\n\tres(0,0) = 1.0;\n\n\tfor(int i = 0; i < pos; i++)\n\t{\n\t\tres = Eigen::kroneckerProduct(MatrixT::Identity(2,2), res).eval();\n\t}\n\n\tres = Eigen::kroneckerProduct(v, res).eval();\n\tfor(int i = pos+1; i < N; i++)\n\t{\n\t\tres = Eigen::kroneckerProduct(MatrixT::Identity(2,2), res).eval();\n\t}\n\treturn res;\n}\n\nEigen::SparseMatrix<double> getSXXYY()\n{\n\tEigen::SparseMatrix<double> res(4,4);\n\tres.insert(1,2) = 2.0;\n\tres.insert(2,1) = 2.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<double> getSXX()\n{\n\tEigen::SparseMatrix<double> res(4,4);\n\tres.insert(0,3) = 1.0;\n\tres.insert(1,2) = 1.0;\n\tres.insert(2,1) = 1.0;\n\tres.insert(3,0) = 1.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<double> getSYY()\n{\n\tEigen::SparseMatrix<double> res(4,4);\n\tres.insert(0,3) = -1.0;\n\tres.insert(1,2) = 1.0;\n\tres.insert(2,1) = 1.0;\n\tres.insert(3,0) = -1.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\nEigen::SparseMatrix<double> getSZZ()\n{\n\tEigen::SparseMatrix<double> res(4,4);\n\tres.insert(0,0) = 1.0;\n\tres.insert(1,1) = -1.0;\n\tres.insert(2,2) = -1.0;\n\tres.insert(3,3) = 1.0;\n\tres.makeCompressed();\n\treturn res;\n}\n\ntemplate<int N>\nclass CompareXXZ\n{\nprivate:\n\tdouble delta_;\n\tBasis1DZ2<uint32_t> basis_;\n\n\tEigen::MatrixXd hamFull_;\n\tdouble gsEnergy_;\n\tEigen::VectorXd gsVec_;\npublic:\n\n\tconstexpr static int k = (N/2)*((N/2)%2);\n\tconstexpr static int parity = 1-2*((N/2)%2);\n\n\tCompareXXZ(double delta)\n\t\t: delta_{delta}, basis_{N, k, parity, true}\n\t{\n\t\tusing namespace Eigen;\n\t\tstatic_assert(N % 2 == 0, \"N must be even\");\n\n\t\tedp::LocalHamiltonian<double> lh(N,2);\n\t\tfor(int i = 0; i < N; i++)\n\t\t{\n\t\t\tlh.addTwoSiteTerm({i, (i+1) % N}, getSXXYY() + delta_*getSZZ());\n\t\t}\n\t\thamFull_ = MatrixXd(edp::constructSparseMat<double>(1<<N, lh));\n\t\tSelfAdjointEigenSolver<MatrixXd> es;\n\t\tes.compute(hamFull_);\n\n\t\tgsEnergy_ = es.eigenvalues()[0];\n\t\tgsVec_ = es.eigenvectors().col(0);\n\n\t}\n\n\tvoid Test()\n\t{\n\t\tusing namespace Eigen;\n\t\tTIXXZ<uint32_t> ham(basis_, 1.0, delta_);\n\t\tconst int dim = basis_.getDim();\n\n\t\tNodeMV mv(dim, 0, dim, ham);\n\n\t\tSpectra::SymEigsSolver<double, Spectra::SMALLEST_ALGE, NodeMV> eigs(&mv, 2, 6);\n\t\teigs.init();\n\t\teigs.compute(10000, 1e-12, Spectra::SMALLEST_ALGE);\n\t\tif(eigs.info() != Spectra::SUCCESSFUL)\n\t\t\tREQUIRE(false);\n\t\tdouble gsEnergy1 = eigs.eigenvalues()[0];\n\n\t\tREQUIRE(std::abs(gsEnergy_ - gsEnergy1) < 1e-4);\n\t\tVectorXd subspaceGs = eigs.eigenvectors().col(0);\n\t\tVectorXd gsVec1;\n\t\t{\n\t\t\tauto v = toOriginalVector(basis_, subspaceGs.data());\n\t\t\tgsVec1 = Map<VectorXd>(v.data(), 1<<N);\n\t\t}\n\n\t\tdouble gsEnergy2 = double(gsVec1.transpose()*hamFull_*gsVec1)/double(gsVec1.transpose()*gsVec1);\n\n\t\tREQUIRE(std::abs(gsEnergy1 - gsEnergy2) < 1e-6);\n\t\tREQUIRE(std::abs(std::abs(gsVec_.transpose()*gsVec1) - 1.) < 1e-6);\n\t}\n};\n\nTEST_CASE(\"Compare GS of XXZ using LocalHamiltonian and TIBasis\", \"[XXZGS]\") \n{\n\tSECTION(\"TIBasis Z2 XXZ N=8\") {\n\t\tCompareXXZ<8> test(1.0);\n\t\ttest.Test();\n\t}\n\tSECTION(\"TIBasis Z2 XXZ N=10\") {\n\t\tCompareXXZ<10> test(1.0);\n\t\ttest.Test();\n\t}\n\tSECTION(\"TIBasis Z2 XXZ N=12\") {\n\t\tCompareXXZ<12> test(1.0);\n\t\ttest.Test();\n\t}\n}\n", "meta": {"hexsha": "8ae4001ff4ed3c2d405ed8986ead1ce9fe79b23d", "size": 5357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/test_xxz_gs.cpp", "max_stars_repo_name": "chaeyeunpark/ExactDiagonalization", "max_stars_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T08:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:47:05.000Z", "max_issues_repo_path": "tests/test_xxz_gs.cpp", "max_issues_repo_name": "chaeyeunpark/ExactDiagonalization", "max_issues_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T19:02:14.000Z", "max_forks_repo_path": "tests/test_xxz_gs.cpp", "max_forks_repo_name": "chaeyeunpark/ExactDiagonalization", "max_forks_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-22T18:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T18:59:11.000Z", "avg_line_length": 22.6991525424, "max_line_length": 98, "alphanum_fraction": 0.6643643831, "num_tokens": 1852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.6017858902694787}}
{"text": "// gnuplot-c++ includes\n#include <gnuplot-iostream.h>\n\n// MLearn includes\n#include <MLearn/Core>\n#include <MLearn/StochasticProcess/GaussianProcess/GP.h>\n\n// STL includes\n#include <vector>\n#include <array>\n#include <string>\n\n// Eigen includes\n#include <Eigen/Core>\n#include <Eigen/SVD>\n\n// Boost includes\n#include <boost/program_options.hpp>\n\n#define N_STEPS 1000 // n_points along the time\n#define N_SAMPLES 1 // n of curves to sample\n\nint main(int argc, char** argv){\n\tstd::srand((unsigned int) time(0));\n\n\tGnuplot gp;\n\n\tusing namespace MLearn;\n\tusing namespace SP::GP;\n\tnamespace po = boost::program_options;\n\n\t// Create command line options\n\tpo::options_description \n\tdesc(\"This is a demo showing different samples from a gaussian process.\");\n\n\tdesc.add_options()\n\t\t(\"help\", \"Show the help\")\n\t\t(\"kernel\", po::value<int>(), \"Value in [0, 10].\" \n\t\t\"This value indicates which kernel will be used. Available kernels:\\n\"\n\t\t\"LINEAR (0)\\n\"\n\t\t\"POLYNOMIAL (1)\\n\"\n\t\t\"RBF (2)\\n\"\n\t\t\"LAPLACIAN (3)\\n\"\n\t\t\"ABEL (4)\\n\"\n\t\t\"CONSTANT (5)\\n\"\n\t\t\"MIN (6)\\n\"\n\t\t\"MATERN_32 (7)\\n\"\n\t\t\"MATERN_52 (8)\\n\"\n\t\t\"RATIONAL_QUADRATIC (9)\\n\"\n\t\t\"PERIODIC (10)\");\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm); \n\n\tif (vm.count(\"help\")) {\n\t\tstd::cout << desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tint K_id = 0;\n\tif (vm.count(\"kernel\")){\n\t\tK_id = vm[\"kernel\"].as<int>();\n\t}\n\n\ttypedef double float_type;\n\ttypedef MLMatrix<float_type> Matrix;\n\ttypedef MLVector<float_type> Vector;\n\n\n\t// mean and query points\n\tVector mean = Vector::Zero(N_STEPS);\n\tMatrix pts = Matrix::Zero(1, N_STEPS);\n\tpts.row(0) = Vector::LinSpaced(N_STEPS, -10, 10);\n\n\tMatrix samples(N_STEPS, N_SAMPLES);\n\n\t// Quite ugly, but classes were not designed for \n\t// dynamic polymorphism\n\tswitch(K_id){\n\t\tcase 0: \n\t\t\tsamples = \n\t\t\t\tGaussianProcess<float_type>::sample(\n\t\t\t\t\tmean, pts, Kernel<KernelType::LINEAR>());\n\t\t\tbreak;\n\t\tcase 1: \n\t\t\tsamples = \n\t\t\t\tGaussianProcess<float_type>::sample(\n\t\t\t\t\tmean, pts, Kernel<KernelType::POLYNOMIAL, float_type>());\n\t\t\tbreak;\n\t\tcase 2: \n\t\t\tsamples = \n\t\t\t\tGaussianProcess<float_type>::sample(\n\t\t\t\t\tmean, pts, Kernel<KernelType::RBF, float_type>());\n\t\t\tbreak;\n\t\tcase 3: \n\t\t\tsamples = \n\t\t\t\tGaussianProcess<float_type>::sample(\n\t\t\t\t\tmean, pts, Kernel<KernelType::LAPLACIAN, float_type>());\n\t\t\tbreak;\n\t\tcase 4: \n\t\t\tsamples = \n\t\t\t\tGaussianProcess<float_type>::sample(\n\t\t\t\t\tmean, pts, Kernel<KernelType::ABEL, float_type>());\n\t\t\tbreak;\n\t\tcase 5: \n\t\t\tsamples = \n\t\t\t\tGaussianProcess<float_type>::sample(\n\t\t\t\t\tmean, pts, Kernel<KernelType::CONSTANT, float_type>());\n\t\t\tbreak;\n\t\tcase 6: \n\t\t\tsamples = \n\t\t\t\tGaussianProcess<float_type>::sample(\n\t\t\t\t\tmean, pts, Kernel<KernelType::MIN>());\n\t\t\tbreak;\n\t\tcase 7: \n\t\t\tsamples = \n\t\t\t\tGaussianProcess<float_type>::sample(\n\t\t\t\t\tmean, pts, \n\t\t\t\t\tKernel<KernelType::MATERN32, float_type>());\n\t\t\tbreak;\n\t\tcase 8: \n\t\t\tsamples = \n\t\t\t\tGaussianProcess<float_type>::sample(\n\t\t\t\t\tmean, pts, \n\t\t\t\t\tKernel<KernelType::MATERN52, float_type>());\n\t\t\tbreak;\n\t\tcase 9: \n\t\t\tsamples = \n\t\t\t\tGaussianProcess<float_type>::sample(\n\t\t\t\t\tmean, pts, \n\t\t\t\t\tKernel<KernelType::RATIONAL_QUADRATIC, float_type>());\n\t\t\tbreak;\n\t\tcase 10: \n\t\t\tsamples = \n\t\t\t\tGaussianProcess<float_type>::sample(\n\t\t\t\t\tmean, pts, Kernel<KernelType::PERIODIC, float_type>());\n\t\t\tbreak;\n\t}\n\n\tgp << \"set xrange [-10:10]\\nset yrange [-3:3]\\n\";\n\tstd::vector<std::pair<float_type, float_type>> gnu_pts;\n\tfor(uint i = 0; i < N_STEPS; ++i) {\n\t\tgnu_pts.push_back(std::make_pair(pts(0, i), samples(i, 0)));\n\t}\n\tgp << \"plot '-' with lines\\n\";\n\tgp.send1d(gnu_pts);\n\treturn 0;\n}", "meta": {"hexsha": "047359ed6082ed635c6914e2db71b68ea9f24a01", "size": 3549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/demo_gaussian_process/gaussian_process_sampling.cpp", "max_stars_repo_name": "phineasng/MLearn", "max_stars_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-11-14T19:37:33.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-05T02:29:35.000Z", "max_issues_repo_path": "demos/demo_gaussian_process/gaussian_process_sampling.cpp", "max_issues_repo_name": "phineasng/MLearn", "max_issues_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-01-23T17:49:50.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-25T22:43:30.000Z", "max_forks_repo_path": "demos/demo_gaussian_process/gaussian_process_sampling.cpp", "max_forks_repo_name": "phineasng/MLearn", "max_forks_repo_head_hexsha": "20ac852179029dac2e9e363acc6b21ad9ddfc8d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-05-23T18:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-23T18:17:14.000Z", "avg_line_length": 23.8187919463, "max_line_length": 75, "alphanum_fraction": 0.6545505776, "num_tokens": 1096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.6017858855643955}}
{"text": "#ifndef DENSEMATRIX_HPP\r\n#define DENSEMATRIX_HPP\r\n\r\n#include <vector>\r\n#include <fstream>\r\n#include <exception>\r\n\r\n#include <boost/archive/text_oarchive.hpp>\r\n#include <boost/archive/text_iarchive.hpp>\r\n#include <boost/serialization/binary_object.hpp>\r\n#include <boost/serialization/vector.hpp>\r\n\r\n#include <Eigen/Core>\r\n\r\nclass dimensionMismatch: public std::exception \r\n{\r\n  virtual const char* what() const throw()\r\n  {\r\n    return \"Dimension Mismatch. Operation not possible.\";\r\n  }\r\n} dimensionMismatch;\r\n\r\ntemplate<class scalar>\r\nclass denseMatrix\r\n{\r\npublic:\r\n\r\n  denseMatrix();\r\n\r\n  denseMatrix(int rows, int cols);\r\n\r\n  denseMatrix(std::vector<scalar> &data, int rows, int cols);\r\n\r\n  denseMatrix(std::vector<scalar> &data, int rows, int cols, bool trnsps);\r\n \r\n  void resize(int rows, int cols);\r\n\r\n  void setRandom(int seed);\r\n\r\n  void save(std::string fname);\r\n  void load(std::string fname);\r\n\r\n  int rows() { return rows_; };\r\n  int rows() const { return rows_; };\r\n  int get_rows();\r\n\r\n  int cols() { return cols_; };\r\n  int cols() const { return cols_; }\r\n  int get_cols();\r\n\r\n  denseMatrix get_row(int i);\r\n  denseMatrix get_col(int i);\r\n  denseMatrix get_diagonal(int i);\r\n  denseMatrix get_block(int i, int j, int k, int l);\r\n\r\n  void set_row(int i, const denseMatrix& r);\r\n  void set_col(int i, const denseMatrix& c);\r\n  void set_diagonal(int i, const denseMatrix& d);\r\n  void set_block(int i, int j, int k, int l, const denseMatrix& b);\r\n\r\n  bool is_transpose() { return transpose_mat; }\r\n  bool is_transpose() const { return transpose_mat; } \r\n\r\n  std::vector<scalar>& container() { return data_; }\r\n  std::vector<scalar>  container() const { return data_; }\r\n\r\n  Eigen::Map< Eigen::Matrix<scalar, Eigen::Dynamic, Eigen::Dynamic> > getEigenMap(); \r\n  Eigen::Map< const Eigen::Matrix<scalar, Eigen::Dynamic, Eigen::Dynamic> > getEigenMap() const; \r\n\r\n  scalar* data() { return data_.data(); }\r\n  const scalar* data() const { return data_.data(); }\r\n \r\n  scalar &operator[](int i) { return data_[i]; }\r\n  scalar &operator[](int i) const { return data_[i]; }\r\n  scalar &operator()(int row, int col) { return data_[row + col*rows_]; }\r\n\r\n  denseMatrix& operator=(const  denseMatrix& other);\r\n  denseMatrix& operator+=(const denseMatrix& other);\r\n  denseMatrix& operator-=(const denseMatrix& other);\r\n  denseMatrix& operator*=(const double a);\r\n  denseMatrix  operator*(const double a);\r\n  denseMatrix  operator+(const denseMatrix& other);\r\n  denseMatrix  operator-(const denseMatrix& other);\r\n  denseMatrix  operator*(const denseMatrix& other);\r\n\r\n  denseMatrix transpose();\r\n\r\n  /// extra member functions to fascilitation python wrapping\r\n  void assign(const denseMatrix& other);\r\n  void setElem(scalar elem, int row, int col);\r\n  scalar getElem(int row, int col) { return data_[row + col*rows_]; }\r\n\r\n  scalar norm();\r\n\r\n  scalar trace();\r\n\r\n  size_t size();\r\n\r\n  void print();\r\n\r\nprivate:\r\n\r\n  friend class boost::serialization::access;\r\n\r\n  template <typename Archive>\r\n  void serialize(Archive &ar, const unsigned int version)\r\n  {\r\n    ar & cols_;\r\n    ar & rows_;\r\n    ar & data_;\r\n    ar & transpose_mat;\r\n  }\r\n\r\n  /// size of matrix\r\n  int cols_;\r\n  int rows_;\r\n  \r\n  bool transpose_mat;\r\n  void set_transpose() { transpose_mat = true; }\r\n\r\n  /// container class to hold data for eigen map\r\n  std::vector<scalar> data_; \r\n\r\n};\r\n\r\n#include \"denseMatrix_impl.hpp\"\r\n\r\n#endif /*DENSEMATRIX_HPP*/\r\n", "meta": {"hexsha": "b4941a245d1e868bd303a387c22a51c09ee5fce4", "size": 3421, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/wrapped_eigen.d/dense.d/denseMatrix.hpp", "max_stars_repo_name": "TtheBC01/pEigen", "max_stars_repo_head_hexsha": "090ba4389df936f9c4ce3726ea807f757c57ef1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/wrapped_eigen.d/dense.d/denseMatrix.hpp", "max_issues_repo_name": "TtheBC01/pEigen", "max_issues_repo_head_hexsha": "090ba4389df936f9c4ce3726ea807f757c57ef1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wrapped_eigen.d/dense.d/denseMatrix.hpp", "max_forks_repo_name": "TtheBC01/pEigen", "max_forks_repo_head_hexsha": "090ba4389df936f9c4ce3726ea807f757c57ef1f", "max_forks_repo_licenses": ["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.519379845, "max_line_length": 98, "alphanum_fraction": 0.6717334113, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.7853085758631158, "lm_q1q2_score": 0.6017769695447938}}
{"text": "#include \"ecpy_native.h\"\n#include <boost/format.hpp>\n#include <stdexcept>\nusing namespace std;\n\nstatic int ac_count = 0;\nstatic int wa_count = 0;\n\n#define ES_ASSERT_EQ_FM(x,y,m) ES_ASSERTION(x == y, m)\n#define ES_ASSERT_NEQ_FM(x,y,m) ES_ASSERTION(x != y, m)\n#define ES_ASSERT_EQ_M(x,y,m) ES_ASSERT_EQ_FM(x, y, m \" == \" #y)\n#define ES_ASSERT_NEQ_M(x,y,m) ES_ASSERT_NEQ_FM(x, y, m \" != \" #y)\n#define ES_ASSERT_EQ(x,y) ES_ASSERT_EQ_M(x, y, #x)\n#define ES_ASSERT_NEQ(x,y) ES_ASSERT_NEQ_M(x, y, #x)\n\n#define ES_ASSERTION(cond, msg) do {\\\n  cout << boost::format(\"[+] %-16s...%-8s\") % msg % \"\";\\\n  try { \\\n    if(!(cond)) { \\\n      cout << \"\\033[31m[ FAILED ]\\033[0m\" << endl; \\\n      wa_count++; \\\n    } else { \\\n      cout << \"\\033[33m[   OK   ]\\033[0m\" << endl; \\\n      ac_count++;\\\n    }\\\n  } catch (const runtime_error& e) { \\\n      cout << \"\\033[31mFAILED(EXCEPTION)\\033[0m\" << endl; \\\n      cerr << \"[-] \\033[31mAssertion Failed: <\" \\\n          << __FILE__ << \"> \" << __FUNCTION__ << \":\" << __LINE__ \\\n          << \"(Exception occurerd!) -> !(\" << #cond << \")\\033[0m\" \\\n          << \"\\n\\t-> \\033[01;04;31m\" << e.what() << \"\\033[0m\" << endl;\\\n      wa_count++; \\\n  } \\\n} while(0)\n\n#define TEST(name) void _ ## name ## _test(); void name ## _test() { \\\n  clock_t start, end; \\\n  double time;\\\n  cout << boost::format(\"Start Test: %s\\n\") % #name; \\\n  start = clock();\\\n  _ ## name ## _test(); \\\n  end = clock();\\\n  time = ((double)(end - start) / CLOCKS_PER_SEC); \\\n  cout << boost::format(\"Test Finished. Time: %s sec (%s usec)\\n\") % time % (time * 1e+6); \\\n} \\\nvoid _ ## name ## _test()\n\nTEST(ec_ff) {\n  auto F = FF(7);\n  auto E = EC<FF>(F, 0, 1);\n  auto P = EC_elem<FF_elem>(0, 1, 1);\n  auto Q = EC_elem<FF_elem>(3, 0, 1);\n  EC_elem<FF_elem> T, U, Z;\n\n  ES_ASSERT_NEQ_FM(E.equ(P, Q), true, \"P != Q\");\n  ES_ASSERT_EQ_FM(E.equ(P, P), true, \"P == P\");\n  ES_ASSERT_EQ_FM(E.equ(Q, Q), true, \"Q == Q\");\n\n  E.add(T, P, Q);\n  E.add(U, Q, P);\n\n  ES_ASSERT_EQ_FM(E.equ(T, U), true, \"P+Q == Q+P\");\n\n  Z = {6, 3, 6};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"P+Q=(6:3:6)\");\n\n  E.add(T, P, P);\n  Z = {0, 6, 1};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"P+P=(0:6:1)\");\n\n  E.sub(T, P, P);\n  Z = {0, 1, 0};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"P-P=(0:1:0)\");\n\n  E.mul(T, P, 3);\n  Z = {0, 1, 0};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"3P=(0:1:0)\");\n\n  ES_ASSERT_EQ(E.is_on_curve(P), true);\n  ES_ASSERT_EQ(E.is_on_curve(Q), true);\n  ES_ASSERT_EQ(E.is_on_curve(T), true);\n\n  auto r = E.line_coeff(P, Q);\n  ES_ASSERT_EQ_FM(F.equ(r, FF_elem(2)), true, \"line_coeff(P, Q)\");\n}\n\nTEST(ec_miller) {\n  auto F = FF(631);\n  auto E = EC<FF>(F, 30, 34);\n  auto m = 5;\n\n  auto P = EC_elem<FF_elem>{36, 60, 1};\n  auto Q = EC_elem<FF_elem>{121, 387, 1};\n  auto S = EC_elem<FF_elem>{0, 36, 1};\n  FF_elem t {0}, z {0};\n  EC_elem<FF_elem> Z;\n\n  E.add(Z, Q, S);\n  miller(t, E, P, Z, m);\n  z = {103};\n  ES_ASSERT_EQ_FM(F.equ(t, z), true, \"miller(P, Q+S) == 103\");\n\n  miller(t, E, P, S, m);\n  z = {219};\n  ES_ASSERT_EQ_FM(F.equ(t, z), true, \"miller(P, S) == 219\");\n\n  E.sub(Z, P, S);\n  miller(t, E, Q, Z, m);\n  z = {284};\n  ES_ASSERT_EQ_FM(F.equ(t, z), true, \"miller(Q, P-S) == 284\");\n\n  E.sub(Z, EC_elem<FF_elem>{0, 1, 0}, S);\n  miller(t, E, Q, Z, m);\n  z = {204};\n  ES_ASSERT_EQ_FM(F.equ(t, z), true, \"miller(Q, -S) == 204\");\n\n  weil_pairing(t, E, P, Q, S, m);\n  z = {242};\n  ES_ASSERT_EQ_FM(F.equ(t, z), true, \"weil_pairing(P, Q) == 242\");\n\n  tate_pairing(t, E, P, Q, m, 1);\n  z = {279};\n  ES_ASSERT_EQ_FM(F.equ(t, z), true, \"tate_pairing(P, Q) == 279\");\n}\n\nTEST(ec_ef_1) {\n  auto F = EF(7, IrreduciblePolynomialType::X2_1);\n  auto E = EC<EF>(F, 0, 1);\n  auto P = EC_elem<EF_elem>(EF_elem(4, 2), EF_elem(2, 1), EF_elem(1, 0));\n  auto Q = EC_elem<EF_elem>(EF_elem(0, 3), EF_elem(3, 6), EF_elem(1, 0));\n  EC_elem<EF_elem> T, U, Z;\n\n  ES_ASSERT_NEQ_FM(E.equ(P, Q), true, \"P != Q\");\n  ES_ASSERT_EQ_FM(E.equ(P, P), true, \"P == P\");\n  ES_ASSERT_EQ_FM(E.equ(Q, Q), true, \"Q == Q\");\n\n  E.add(T, P, Q);\n  E.add(U, Q, P);\n  ES_ASSERT_EQ_FM(E.equ(T, U), true, \"P+Q == Q+P\");\n\n  Z = {EF_elem(0, 2), EF_elem(4, 6), EF_elem(1)};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"P+Q=(2i:4+6i:1)\");\n\n  E.add(T, P, P);\n  Z = {EF_elem(4, 1), EF_elem(6, 5), EF_elem(2, 4)};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"P+P=(4+i:6+5i:2+4i)\");\n\n  E.sub(T, P, P);\n  Z = {0, 1, 0};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"P-P=(0:1:0)\");\n\n  E.mul(T, P, 9);\n  Z = {EF_elem(1, 1), EF_elem(0, 1), EF_elem(5, 3)};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"9P=(1+i:i:5+3i)\");\n\n  auto r = E.line_coeff(P, Q);\n  ES_ASSERT_EQ_FM(F.equ(r, EF_elem(5)), true, \"line_coeff(P, Q)\");\n\n  ES_ASSERT_EQ(E.is_on_curve(P), true);\n  ES_ASSERT_EQ(E.is_on_curve(Q), true);\n  ES_ASSERT_EQ(E.is_on_curve(T), true);\n}\n\nTEST(ec_ef_2) {\n  auto F = EF(41, IrreduciblePolynomialType::X2_X_1);\n  auto E = EC<EF>(F, 0, 1);\n  auto P = EC_elem<EF_elem>(EF_elem(39, 39), EF_elem(3, 0), EF_elem(1, 0));\n  auto Q = EC_elem<EF_elem>(EF_elem(5, 5), EF_elem(9, 0), EF_elem(1, 0));\n  EC_elem<EF_elem> T, U, Z;\n\n  ES_ASSERT_NEQ_FM(E.equ(P, Q), true, \"P != Q\");\n  ES_ASSERT_EQ_FM(E.equ(P, P), true, \"P == P\");\n  ES_ASSERT_EQ_FM(E.equ(Q, Q), true, \"Q == Q\");\n\n  E.add(T, P, Q);\n  E.add(U, Q, P);\n  ES_ASSERT_EQ_FM(E.equ(T, U), true, \"P+Q == Q+P\");\n\n  Z = {EF_elem(10, 10), EF_elem(27), EF_elem(26)};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"P+Q=(10+10w:27:26)\");\n\n  E.add(T, P, P);\n  Z = {EF_elem(0), EF_elem(11), EF_elem(11)};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"P+P=(0:11:11)\");\n\n  E.sub(T, P, P);\n  Z = {0, 1, 0};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"P-P=(0:1:0)\");\n\n  E.add(T, P, Q);\n  E.mul(T, T, 27);\n  Z = {EF_elem(24, 24), EF_elem(29, 0), EF_elem(2, 0)};\n  ES_ASSERT_EQ_FM(E.equ(T, Z), true, \"27(P+Q)=(24+24w:29:2)\");\n\n  auto r = E.line_coeff(P, Q);\n  ES_ASSERT_EQ_FM(F.equ(r, EF_elem(0, 5)), true, \"line_coeff(P, Q)\");\n\n  ES_ASSERT_EQ(E.is_on_curve(P), true);\n  ES_ASSERT_EQ(E.is_on_curve(Q), true);\n  ES_ASSERT_EQ(E.is_on_curve(T), true);\n}\n\nTEST(ef_1) {\n  auto F = EF(7, IrreduciblePolynomialType::X2_1);\n  auto x = EF_elem(3, 0);\n  auto y = EF_elem(0, 5);\n  EF_elem t;\n\n  F.add(t, x, y);\n  ES_ASSERT_EQ_FM((t.u.v == 3 && t.v.v == 5), true, \"x+y=3+5i\");\n  F.sub(t, x, y);\n  ES_ASSERT_EQ_FM((t.u.v == 3 && t.v.v == 2), true, \"x-y=3+2i\");\n  F.mul(t, x, y);\n  ES_ASSERT_EQ_FM((t.u.v == 0 && t.v.v == 1), true, \"x*y=i\");\n  F.div(t, x, y);\n  ES_ASSERT_EQ_FM((t.u.v == 0 && t.v.v == 5), true, \"x/y=5i\");\n  F.pow(t, y, 31);\n  ES_ASSERT_EQ_FM((t.u.v == 0 && t.v.v == 2), true, \"y^31=2i\");\n}\n\nTEST(ef_2) {\n  auto F = EF(41, IrreduciblePolynomialType::X2_X_1);\n  auto x = EF_elem(15, 25);\n  auto y = EF_elem(39, 10);\n  EF_elem t;\n\n  F.add(t, x, y);\n  ES_ASSERT_EQ_FM((t.u.v == 13 && t.v.v == 35), true, \"x+y=13+35w\");\n  F.sub(t, x, y);\n  ES_ASSERT_EQ_FM((t.u.v == 17 && t.v.v == 15), true, \"x-y=17+15w\");\n  F.mul(t, x, y);\n  ES_ASSERT_EQ_FM((t.u.v == 7 && t.v.v == 14), true, \"x*y=7+14w\");\n  F.div(t, x, y);\n  ES_ASSERT_EQ_FM((t.u.v == 29 && t.v.v == 5), true, \"x/y=29+5w\");\n  F.pow(t, x, 40);\n  ES_ASSERT_EQ_FM((t.u.v == 14 && t.v.v == 17), true, \"x^40=14+17w\");\n}\n\nTEST(ff) {\n  auto ff = FF(7);\n  FF_elem x(3), y(6);\n  FF_elem t;\n  ES_ASSERT_EQ(x.v, 3);\n  ES_ASSERT_EQ(y.v, 6);\n\n  ff.add(t, x, y);\n  ES_ASSERT_EQ_FM(t.v, 2, \"x+y\");\n\n  ff.sub(t, x, y);\n  ES_ASSERT_EQ_FM(t.v, 4, \"x-y\");\n\n  ff.mul(t, x, y);\n  ES_ASSERT_EQ_FM(t.v, 4, \"x*y\");\n\n  ff.div(t, x, y);\n  ES_ASSERT_EQ_FM(t.v, 4, \"x/y\");\n\n  ff.pow(t, x, 30);\n  ES_ASSERT_EQ_FM(t.v, 1, \"x^30\");\n}\n\nvoid exec_test() {\n  ff_test();\n  ef_1_test();\n  ef_2_test();\n  ec_ff_test();\n  ec_ef_1_test();\n  ec_ef_2_test();\n  ec_miller_test();\n  cout << boost::format(\"[+] %d Test(s) finished. %d Test(s) success, %d Test(s) fail.\")\n    % (ac_count + wa_count)\n    % ac_count\n    % wa_count\n    << endl;\n}\n\nint main(int ac, char **av) {\n  exec_test();\n  return wa_count;\n}\n", "meta": {"hexsha": "3d9a405f4f850b938ca985a9f081850238314b60", "size": 7784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/test/test.cpp", "max_stars_repo_name": "andynuma/time-release-encryption-py3", "max_stars_repo_head_hexsha": "a5c48d07fae8121b59100d4cd79d3e38402d928c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T07:20:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T10:48:43.000Z", "max_issues_repo_path": "cpp/test/test.cpp", "max_issues_repo_name": "andynuma/time-release-encryption-py3", "max_issues_repo_head_hexsha": "a5c48d07fae8121b59100d4cd79d3e38402d928c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-03-26T11:03:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T15:54:03.000Z", "max_forks_repo_path": "cpp/test/test.cpp", "max_forks_repo_name": "andynuma/time-release-encryption-py3", "max_forks_repo_head_hexsha": "a5c48d07fae8121b59100d4cd79d3e38402d928c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-06-05T19:09:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T04:23:20.000Z", "avg_line_length": 27.7010676157, "max_line_length": 92, "alphanum_fraction": 0.5512589928, "num_tokens": 3207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6016635416918507}}
{"text": "#include \"lorenz_aliases.h\"\n#include \"lorenz.h\"\n#include \"lorenz_equations.h\"\n#include \"push_back_local_maxima.h\"\n\n#include <fstream>\n#include <vector>\n\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n\nvoid outputLorenzAttractorData(const std::string& output_directory)\n{\n\tconstexpr double sigma = 10.0;\n\tconstexpr double r = 28.0;\n\tconstexpr double b = 8.0 / 3.0;\n\n\tstd::ofstream file_stream;\n\n\tfile_stream.open(output_directory);\n\n\tstate_type x = { 10.0 , 1.0 , 1.0 }; // initial conditions\n\n\tauto lambda_writer = [&file_stream](const state_type& x, const double t)\n\t{\n\t\tfile_stream << t << ',' << x[0] << ',' << x[1] << ',' << x[2] << std::endl;\n\t};\n\n\tboost::numeric::odeint::integrate(lorenz(sigma, r, b), x, 0.0, 100.0, 0.01, lambda_writer);\n\n\tfile_stream.close();\n}\n\nvoid outputLorenzBifurcationDiagramData(const std::string& output_file)\n{\n\n\t// range for parameter change\n\tconstexpr double r_min = 0.0;\n\tconstexpr double r_max = 400.0;\n\n\tconstexpr int r_num_divisions = 400;\n\tconstexpr double r_division = (r_max - r_min) / (double)r_num_divisions;\n\n\tstd::ofstream file_stream;\n\n\tfile_stream.open(output_file);\n\n\tdouble r{ r_min };\n\n\tfor (int i{ 0 }; i < r_num_divisions; i++)\n\t{\n\t\tr += r_division;\n\t\tconstexpr double sigma{ 10.0 };\n\t\tconstexpr double b{ 8.0 / 3.0 };\n\n\t\tstate_type state = { 15.0, 20.0, 30.0 };\n\n\t\tconstexpr double transient_time = 100.0;\n\n\t\tboost::numeric::odeint::integrate(lorenz(sigma, r, b), state, 0.0, transient_time, 0.1);\n\n\t\tstd::vector<state_type> states;\n\t\tstd::vector<double> times;\n\n\t\tboost::numeric::odeint::integrate(lorenz(sigma, r, b), state, 0.0, 100.0, 0.1, push_back_local_maxima(states, times));\n\n\t\tfor (size_t i{ 0 }; i < states.size(); i++)\n\t\t\tfile_stream << times[i] << ',' << r << ',' << states[i][0] << ',' << states[i][1] << ',' << states[i][2] << std::endl;\n\t}\n\n\tfile_stream.close();\n\n\treturn;\n}\n", "meta": {"hexsha": "bbecf8dba140b2772e274c1d99e04b52e6ccf99f", "size": 1863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Visual Studio/Solutions/lorenz_equations/lorenz_equations.cpp", "max_stars_repo_name": "rlkennedyreid/bangor_repository", "max_stars_repo_head_hexsha": "44f68092e6c4af1be016aea463ad6b4114d21be1", "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": "Visual Studio/Solutions/lorenz_equations/lorenz_equations.cpp", "max_issues_repo_name": "rlkennedyreid/bangor_repository", "max_issues_repo_head_hexsha": "44f68092e6c4af1be016aea463ad6b4114d21be1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Visual Studio/Solutions/lorenz_equations/lorenz_equations.cpp", "max_forks_repo_name": "rlkennedyreid/bangor_repository", "max_forks_repo_head_hexsha": "44f68092e6c4af1be016aea463ad6b4114d21be1", "max_forks_repo_licenses": ["Apache-2.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.84, "max_line_length": 121, "alphanum_fraction": 0.6634460548, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737775116229, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6016472021440221}}
{"text": "#ifndef _EIGEN_RIDGE_HPP_\n\n#define _EIGEN_RIDGE_HPP_\n\n/*\n * L2-regularized (ridge) linear regression without intercept in c++11 as Eigen3 template function\n * Uses singular value decomposition, works with both tall and wide design matrices\n * Written by Carlos Guerreiro carlos@perceptiveconstructs.com\n * This is free and unencumbered software released into the public domain.\n */\n\n#include <Eigen/Dense>\n\ntemplate<typename M, typename V, typename P>\nM ridge(const M& A, const V& y,  P alpha) {\n  const auto& svd = A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n  const auto& s = svd.singularValues();\n  const auto r = s.rows();\n  const auto& D = s.cwiseQuotient((s.array().square() + alpha).matrix()).asDiagonal();\n  return svd.matrixV().leftCols(r) * D * svd.matrixU().transpose().topRows(r) * y;\n}\n\n#endif\n", "meta": {"hexsha": "4c9ff6e93a1d097c10dc5b54db565b1f29803d76", "size": 819, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Sherlock/examples/tests/headers/eigen_ridge.hpp", "max_stars_repo_name": "JuliaReach/AAAI22_RE", "max_stars_repo_head_hexsha": "9a17e9e80c4754e6bc9f3b325567b7a33d1db0b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-04-22T14:49:02.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-07T08:16:56.000Z", "max_issues_repo_path": "Sherlock/examples/tests/headers/eigen_ridge.hpp", "max_issues_repo_name": "JuliaReach/AAAI22_RE", "max_issues_repo_head_hexsha": "9a17e9e80c4754e6bc9f3b325567b7a33d1db0b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-04-23T19:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-23T19:53:37.000Z", "max_forks_repo_path": "Sherlock/examples/tests/headers/eigen_ridge.hpp", "max_forks_repo_name": "JuliaReach/AAAI22_RE", "max_forks_repo_head_hexsha": "9a17e9e80c4754e6bc9f3b325567b7a33d1db0b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-03-17T10:55:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-20T05:45:24.000Z", "avg_line_length": 34.125, "max_line_length": 98, "alphanum_fraction": 0.7301587302, "num_tokens": 227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.6016293225049149}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n  Matrix3d m = Matrix3d::Random();\n  m = (m + Matrix3d::Constant(1.2)) * 50;\n  cout << \"m =\" << endl << m << endl;\n  Vector3d v(1,2,3);\n\n  cout << \"m * v =\" << endl << m * v << endl;\n}\n", "meta": {"hexsha": "c0228e317f7c9ccf7516c1759995985603528c48", "size": 287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/doc/examples/QuickStart_example2_fixed.cpp", "max_stars_repo_name": "eundersander/bps-nav", "max_stars_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:17:14.000Z", "max_issues_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/doc/examples/QuickStart_example2_fixed.cpp", "max_issues_repo_name": "eundersander/bps-nav", "max_issues_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T21:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:46:40.000Z", "max_forks_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/doc/examples/QuickStart_example2_fixed.cpp", "max_forks_repo_name": "eundersander/bps-nav", "max_forks_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-27T17:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:00:06.000Z", "avg_line_length": 17.9375, "max_line_length": 45, "alphanum_fraction": 0.5644599303, "num_tokens": 97, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.6015953240387616}}
{"text": "// The template and inlines for the -*- C++ -*- 3d vector classes.\n// Initially implemented by Wai-Shing Luk <luk036@gmail.com>\n//\n\n/** @file include/vector3d.hpp\n *  This is a C++ Library header.\n */\n\n#ifndef FUN_VECTOR3D_HPP\n#define FUN_VECTOR3D_HPP 1\n\n#include <boost/operators.hpp>   // for boost::addable etc\n\nnamespace fun \n{\n  \n/** \n *  3-dimensional vector. \n *\n *  @param  Tp  Type of vector elements\n */\ntemplate <typename _K>\nclass vector3d :\n  boost::equality_comparable < vector3d<_K>,\n  boost::addable < vector3d<_K>,\n  boost::subtractable < vector3d<_K>,\n  boost::multipliable2 < vector3d<_K>, _K,\n  boost::dividable2 < vector3d<_K>, _K\n  > > > > >\n{\n  /// Value typedef.\n  typedef _K value_type;\n\npublic:\n  /// static memeber zero\n  static const vector3d<_K> zero;\n\n  /// Default constructor. \n  constexpr vector3d<_K>(\n    const _K& e1, \n    const _K& e2, \n    const _K& e3) noexcept\n    : _e1{e1}, _e2{e2}, _e3{e3} { }\n\n  /// Return first element of vector.\n  constexpr _K e1() const noexcept { return _e1; }\n  /// Return second element of vector.\n  constexpr _K e2() const noexcept { return _e2; }\n  /// Return third element of vector.\n  constexpr _K e3() const noexcept { return _e3; }\n\n  // Lets the compiler synthesize the assignment operator\n  // vector3d<_K>& operator= (const vector3d<_K>&);\n  /// Assign this vector to vector @a w.\n  /// Add @a w to this vector.\n  vector3d<_K>& operator+=(const vector3d<_K>& w)\n  { _e1 += w.e1(); _e2 += w.e2(); _e3 += w.e3(); return *this; }\n\n  /// Subtract @a w from this vector.\n  vector3d<_K>& operator-=(const vector3d<_K>& w)\n  { _e1 -= w.e1(); _e2 -= w.e2(); _e3 -= w.e3(); return *this; }\n\n  /// Multiply this vector by @a a.\n  vector3d<_K>& operator*=(const _K& a) \n  { _e1 *= a; _e2 *= a; _e3 *= a; return *this; }\n\n  /// Divide this vector by @a a.\n  vector3d<_K>& operator/=(const _K& a) \n  { _e1 /= a; _e2 /= a; _e3 /= a; return *this; }\n  \n  constexpr bool operator== (const vector3d<_K>& w) const\n  { return e1() == w.e1() && e2() == w.e2() && e3() == w.e3(); }\n\nprivate:\n  _K _e1;\n  _K _e2;\n  _K _e3;  \n};\n\ntemplate <typename _K>\nconst vector3d<_K> vector3d<_K>::zero (_K(0), _K(0), _K(0)); \n\n/// Return @a v.\ntemplate<typename _K>\ninline constexpr vector3d<_K>\noperator+(const vector3d<_K>& v) noexcept\n{ return v; }\n\n/// Return negation of @a v/\ntemplate<typename _K>\ninline constexpr vector3d<_K>\noperator-(const vector3d<_K>& v) noexcept\n{ return vector3d<_K>(-v.e1(), -v.e2(), -v.e3()); }\n\n///  Return dot product of  @a v and @a w\ntemplate<typename _K>\ninline constexpr _K\ndot(const vector3d<_K>& v, const vector3d<_K>& w) noexcept\n{ return v.e1()*w.e1() + v.e2()*w.e2() + v.e3()* w.e3(); }\n\n///  Return new vector @a v x @a w (cross product).\ntemplate<typename _K>\ninline constexpr vector3d<_K>\ncross(const vector3d<_K>& v, const vector3d<_K>& w) noexcept\n{\n  return vector3d<_K>( \n     v.e2()*w.e3() - v.e3()*w.e2(),\n    -v.e1()*w.e3() + v.e3()*w.e1(),\n     v.e1()*w.e2() - v.e2()*w.e1()  );\n}\n\n///  Return determinant of @a p,  @a q and @a r.\ntemplate<typename _K>\ninline constexpr _K\ndet(const vector3d<_K>& p, const vector3d<_K>& q, \n    const vector3d<_K>& r) noexcept\n{\n  return dot(p, cross(q, r)); // Pl\\{\"}ucker's formula\n}\n\n///  Insertion operator for vector values.\ntemplate<typename _K, class _Stream>\n_Stream& operator<<(_Stream& os, const vector3d<_K>& v)\n{\n  os << '[' << v.e1() << ',' << v.e2() << ',' << v.e3() << ']';\n  return os;\n}\n\n///  Return the quadrance of  @a v \ntemplate<typename _K>\ninline constexpr _K\nquadrance(const vector3d<_K>& v) noexcept\n{ return dot(v,v); }\n\n\n} // namespace fun\n\n#endif\n", "meta": {"hexsha": "928919aa38ec8c83b2db398cab764192d548d834", "size": 3606, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/fun/vector3d.hpp", "max_stars_repo_name": "luk036/fun", "max_stars_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/include/fun/vector3d.hpp", "max_issues_repo_name": "luk036/fun", "max_issues_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/include/fun/vector3d.hpp", "max_forks_repo_name": "luk036/fun", "max_forks_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9424460432, "max_line_length": 66, "alphanum_fraction": 0.6231281198, "num_tokens": 1236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6015726789115959}}
{"text": "//| This file is a part of the sferes2 framework.\n//| Copyright 2009, ISIR / Universite Pierre et Marie Curie (UPMC)\n//| Main contributor(s): Jean-Baptiste Mouret, mouret@isir.fr\n//|\n//| This software is a computer program whose purpose is to facilitate\n//| experiments in evolutionary computation and evolutionary robotics.\n//|\n//| This software is governed by the CeCILL license under French law\n//| and abiding by the rules of distribution of free software.  You\n//| can use, modify and/ or redistribute the software under the terms\n//| of the CeCILL license as circulated by CEA, CNRS and INRIA at the\n//| following URL \"http://www.cecill.info\".\n//|\n//| As a counterpart to the access to the source code and rights to\n//| copy, modify and redistribute granted by the license, users are\n//| provided only with a limited warranty and the software's author,\n//| the holder of the economic rights, and the successive licensors\n//| have only limited liability.\n//|\n//| In this respect, the user's attention is drawn to the risks\n//| associated with loading, using, modifying and/or developing or\n//| reproducing the software by the user in light of its specific\n//| status of free software, that may mean that it is complicated to\n//| manipulate, and that also therefore means that it is reserved for\n//| developers and experienced professionals having in-depth computer\n//| knowledge. Users are therefore encouraged to load and test the\n//| software's suitability as regards their requirements in conditions\n//| enabling the security of their systems and/or data to be ensured\n//| and, more generally, to use and operate it in the same conditions\n//| as regards security.\n//|\n//| The fact that you are presently reading this means that you have\n//| had knowledge of the CeCILL license and that you accept its terms.\n\n\n\n\n#ifndef UTIL_MEDIAN\n#define UTIL_MEDIAN\n\n#include <boost/range/algorithm.hpp>\n#include <vector>       // std::vector\n\nnamespace sferes {\n  namespace util {\n  \tclass Median\n\t\t{\n\t\tpublic:\n  \t\t/**\n  \t\t * Calculate the median of the doubles in the given list.\n  \t\t */\n  \t\tstatic double calculate_median(std::vector<double>& list)\n  \t\t{\n  \t\t\tsize_t size = list.size();\t// Size of the list\n\n  \t\t\tassert(size > 0);\n\n  \t\t\tstd::sort(list.begin(), list.end());\n\n  \t\t\t// If there are an odd number of doubles\n  \t\t\tif (size % 2 == 1)\n  \t\t\t{\n  \t\t\t\t// Take the middle number\n  \t\t\t\tsize_t index_middle = (size - 1)/2;\n  \t\t\t\treturn list[index_middle];\n  \t\t\t}\n  \t\t\t// If there are an even number of doubles\n  \t\t\telse\n  \t\t\t{\n  \t\t\t\tsize_t index_above = size / 2;\n  \t\t\t\tsize_t index_below = index_above - 1;\n\n  \t\t\t\t// Average of two middle numbers\n  \t\t\t\treturn (list[index_above] + list[index_below]) / 2;\n  \t\t\t}\n  \t\t}\n\t\t};\n  }\n}\n#endif\n", "meta": {"hexsha": "178120703b9f48c1f8f5465c830ab58eb08618ea", "size": 2737, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sferes/exp/images/util/median.hpp", "max_stars_repo_name": "Evolving-AI-Lab/innovation-engine", "max_stars_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-09-20T03:03:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T06:50:20.000Z", "max_issues_repo_path": "sferes/exp/images/util/median.hpp", "max_issues_repo_name": "Evolving-AI-Lab/innovation-engine", "max_issues_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-11T07:24:50.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-17T01:19:57.000Z", "max_forks_repo_path": "sferes/exp/images/util/median.hpp", "max_forks_repo_name": "Evolving-AI-Lab/innovation-engine", "max_forks_repo_head_hexsha": "58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-11-15T01:52:25.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-11T23:42:58.000Z", "avg_line_length": 33.7901234568, "max_line_length": 70, "alphanum_fraction": 0.6989404457, "num_tokens": 673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6015726784732959}}
{"text": "/**\n * @file semimprk_main.cc\n * @brief NPDE homework SemImpRK code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include <Eigen/Core>\n#include <iostream>\n\n#include \"semimprk.h\"\n\nint main() {\n  auto f = [](Eigen::Vector3d y) -> Eigen::Vector3d {\n    return Eigen::Vector3d(y(0) * y(1), y(1) * y(2), y(2) - y(0));\n  };\n  auto df = [](Eigen::Vector3d y) {\n    Eigen::Matrix3d J;\n    J << y(1), y(0), 0.0, 0.0, y(2), y(1), -1.0, 0.0, 1.0;\n    return J;\n  };\n  Eigen::Vector3d y0(1.0, 2.0, 3.0);\n  unsigned int M = 10;\n  double T = 2.0;\n\n  std::cout << \"Test of SolveRosenbrock():\"\n            << SemImpRK::SolveRosenbrock(f, df, y0, M, T).back().transpose()\n            << std::endl;\n\n  double cvgRate = SemImpRK::CvgRosenbrock();\n  std::cout << \"Convergence rate: \" << cvgRate << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "57d89eb1356b8c5408bd52b0243ad166bc1d04f3", "size": 858, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/SemImpRK/templates/semimprk_main.cc", "max_stars_repo_name": "0xBachmann/NPDECODES", "max_stars_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/SemImpRK/templates/semimprk_main.cc", "max_issues_repo_name": "0xBachmann/NPDECODES", "max_issues_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/SemImpRK/templates/semimprk_main.cc", "max_forks_repo_name": "0xBachmann/NPDECODES", "max_forks_repo_head_hexsha": "70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 23.8333333333, "max_line_length": 76, "alphanum_fraction": 0.5734265734, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6015726628268949}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <math.h>\n#include \"scf.h\"\n#include <Eigen/Eigenvalues>\n#include <Eigen/Core>\n#include <Eigen/Dense>\nusing namespace std;\nusing namespace Eigen;\nusing std::sqrt;\nint INDEX(int i,int j) {\n    if (i>j) return i*(i+1)/2 + j;\n    return j*(j+1)/2 + i;\n}\n#define MAX_ITER 75\n#define EDIFF_CONV 0.000000000002\n#define RMS_CONV 0.000000000014\ndouble rmsDensity(MatrixXd A, MatrixXd B, int mat_size){\n    double result = 0;\n    for (int i =0 ; i < mat_size; i++){\n        for(int j =0; j < mat_size; j++){\n            result += pow(A(i,j) - B(i,j),2);\n        }\n    }\n    return pow(result,0.5);\n}\n\nvoid run_scf() {\n//creating variables/objects\n// Reading input\n    string SCF_options[1] = {\"num_elec\"};\n    ifstream input (\"INPUT\");\n    string newline,temp_str;\n    int occ = 0;\n    while(getline(input,newline)){\n        istringstream ss(newline);\n        ss >> temp_str;\n        if (temp_str == \"num_elec\") {\n            ss >> occ;\n            occ /= 2;\n        }\n    }\n    \n    ifstream numffile (\"../mol/num_nao.dat\");\n    int num_basisf ;\n    numffile >> num_basisf;\n    int mat_length = num_basisf * (num_basisf + 1) / 2 ;\n    int total_mat_length = num_basisf * num_basisf;\n    double enuc, rms, Ediff;\n    double e0, eX, eC, etotal =0;\n    MatrixXd t_array(num_basisf,num_basisf);\n    MatrixXd v_array(num_basisf,num_basisf);\n    MatrixXd s_array(num_basisf,num_basisf);\n    MatrixXd hcore(num_basisf,num_basisf);\n    MatrixXd F0(num_basisf,num_basisf); \n    MatrixXd FC(num_basisf,num_basisf);\n    MatrixXd FX(num_basisf,num_basisf);\n    MatrixXd AO_eigenvectors(num_basisf,num_basisf);\n    MatrixXd D0(num_basisf,num_basisf);\n    MatrixXd DC(num_basisf,num_basisf);\n    MatrixXd DX(num_basisf,num_basisf);\n    MatrixXd FX_org(num_basisf,num_basisf);\n    MatrixXd FC_org(num_basisf,num_basisf);\n    VectorXd eri_array(num_basisf*num_basisf*num_basisf*num_basisf); \n\n // Reading variables\n // Nuclear repulsion energy: enuc.dat --> enuc\n // Kinetic energy inegrals: t.dat --> t_array\n // Nuclear attraction inegrals: v.dat --> v_array\n // AO Overlap: s.dat --> s_array\n // Core Hamiltonian: hcore\n\n\n // Reading enuc \n    ifstream enucfile (\"../mol/enuc.dat\");\n    enucfile >> enuc;\n//  Reading One-Electron Inegrals\n\n\n    ifstream tfile (\"../mol/t.dat\");\n    ifstream vfile (\"../mol/v.dat\");\n    ifstream sfile (\"../mol/s.dat\");\n    while(getline(tfile, newline)){\n        int i,j;\n        double temp_t; \n        istringstream ss(newline);\n        ss >> i >> j >> temp_t;\n        t_array(i-1,j-1) = temp_t;\n        if(i != j ) t_array(j-1,i-1) = temp_t;\n    }\n\n    while(getline(vfile, newline)){\n        int i,j;\n        double temp_v; \n        istringstream ss(newline);\n        ss >> i >> j >> temp_v;\n        v_array(i-1,j-1) = temp_v;\n        if(i != j ) v_array(j-1,i-1) = temp_v;\n    }\n    while(getline(sfile, newline)){\n        int i,j;\n        double temp_s; \n        istringstream ss(newline);\n        ss >> i >> j >> temp_s;\n        s_array(i-1,j-1) = temp_s;\n        if(i != j ) s_array(j-1,i-1) = temp_s;\n    }\n//  Core Hamiltonian hcore;\n//  Hcore = T + V\n        hcore = t_array + v_array;\n\n//  Read Two Electron repulsion data\n//  eri.dat > eri_array\n    ifstream erifile (\"../mol/eri.dat\");\n    while(getline(erifile, newline)){\n        int i, j, ij, k, l, kl, ijkl;\n        double temp_eri; \n        istringstream ss(newline);\n        ss >> i >> j >> k >> l >> temp_eri;\n        ij = INDEX(i,j);\n        kl = INDEX(k,l);\n        ijkl = INDEX(ij,kl);\n        eri_array(ijkl) = temp_eri;\n    }\n\n//  Orthogonlization matrix\n// V * D^-1/2 * V^-1\n    SelfAdjointEigenSolver<MatrixXd> s_eigen(s_array);\n\n//  Initial Guess of Wavefunction\n    F0 = s_eigen.operatorSqrt().inverse().transpose() * hcore * s_eigen.operatorSqrt().inverse();\n    SelfAdjointEigenSolver<MatrixXd> F_eigen(F0);\n    AO_eigenvectors = s_eigen.operatorSqrt().inverse() * F_eigen.eigenvectors();\n    for ( int i = 0 ; i < num_basisf ; i++){\n        for ( int j = 0 ; j < num_basisf; j++){\n            for (int k = 0 ; k < occ ; k++){\n               D0(i,j) +=  AO_eigenvectors.col(k).row(i) * AO_eigenvectors.col(k).row(j);\n            }\n        }\n    } \n//  Compute Inital Hartree Fock Energy\n    for (int i =0 ; i < num_basisf; i++){\n        for (int j =0 ; j < num_basisf; j++){\n            e0 += D0(i,j) * (hcore(i,j) + hcore(i,j));\n        }\n    }\n    etotal = e0 + enuc;\n    DC = DX = D0;\n    eC = eX = e0;\n    cout << setw(10) << \"Iter\";\n    cout << setw(25)<< setprecision(15) << \"E(elec)\";\n    cout << setw(25)<< setprecision(15) << \"E(Total)\";\n    cout <<setw(25) << setprecision(15) << \"D(E)\" ;\n    cout << setw(25) << setprecision(15) << \"RMS(D)\" << endl;\n    cout << setw(10) << \"0\";\n    cout << setw(25)<< setprecision(15) << eC;\n    cout << setw(25)<< setprecision(15) << eC + enuc;\n    cout <<setw(25) << setprecision(15) << \"0.00\";\n    cout << setw(25) << setprecision(15) << \"0.00\" << endl;\n// enter into SCF loop\nfor (int iter = 1 ; iter <= MAX_ITER; iter++){\n// Build new Fock Matrix\n    for ( int i =1; i <= num_basisf; i++){\n        for (int j =1 ; j <= num_basisf; j++){\n            FC(i-1,j-1) = hcore(i-1,j-1);\n            for(int k =1; k <= num_basisf; k++){\n                for( int l=1; l <= num_basisf; l++){\n                    int ij = INDEX(i,j);\n                    int kl = INDEX(k,l);\n                    int ijkl = INDEX(ij,kl);\n                    int ik = INDEX(i,k);\n                    int jl = INDEX(j,l);\n                    int ikjl = INDEX(ik,jl);\n                    FC(i-1,j-1) += DC(k-1,l-1) * ( 2.0 * eri_array(ijkl) - eri_array(ikjl));   \n                }\n            }\n        }\n    }\n\n//  Build Density Matrix\n    FC_org = s_eigen.operatorSqrt().inverse().transpose() * FC * s_eigen.operatorSqrt().inverse();\n    SelfAdjointEigenSolver<MatrixXd> FC_eigen(FC_org);\n    MatrixXd AOC_eigenvectors(num_basisf,num_basisf);\n    AOC_eigenvectors = s_eigen.operatorSqrt().inverse() * FC_eigen.eigenvectors();\n    for ( int i = 0 ; i < num_basisf ; i++){\n        for ( int j = 0 ; j < num_basisf; j++){\n            DC(i,j)= 0;\n            for (int k = 0 ; k < occ ; k++){\n               DC(i,j) +=  AOC_eigenvectors.col(k).row(i) * AOC_eigenvectors.col(k).row(j);\n            }\n        }\n    }  \n\n\n//  Compute new Hartree Fock Energy\n    eC = 0;\n    for (int i =0 ; i < num_basisf; i++){\n        for (int j =0 ; j < num_basisf; j++){\n            eC += DC(i,j) * ( hcore(i,j) + FC(i,j));\n        }\n    }\n    Ediff = eC - eX;\n    rms = rmsDensity(DC,DX,num_basisf);\n    cout << setw(10) << iter;\n    cout << setw(25)<< setprecision(15) << eC;\n    cout << setw(25)<< setprecision(15) << eC + enuc;\n    cout <<setw(25) << setprecision(15) << Ediff;\n    cout << setw(25) << setprecision(15) << rms << endl;\n\n    if (Ediff < EDIFF_CONV && rms < RMS_CONV){\n        cout << \"CONVERGENCE has been reached\" << endl;\n        break;\n    }else if(iter == MAX_ITER){\n        cout << \"NO CONVERGENCE has been reached\" << endl;\n    }\n    //Save current information for next loop\n    eX = eC;\n    DX = DC;\n\n} //end of SCF Loop\n} \n\n\n", "meta": {"hexsha": "d9ab6aeadd0d6f09617380230c82eb9b83c1f240", "size": 7128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/scf.cpp", "max_stars_repo_name": "charliecpeterson/simple-HartreeFock", "max_stars_repo_head_hexsha": "429a89f7ecab4e6895794cb2d08f0d3f15c8ff98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/scf.cpp", "max_issues_repo_name": "charliecpeterson/simple-HartreeFock", "max_issues_repo_head_hexsha": "429a89f7ecab4e6895794cb2d08f0d3f15c8ff98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scf.cpp", "max_forks_repo_name": "charliecpeterson/simple-HartreeFock", "max_forks_repo_head_hexsha": "429a89f7ecab4e6895794cb2d08f0d3f15c8ff98", "max_forks_repo_licenses": ["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.5398230088, "max_line_length": 98, "alphanum_fraction": 0.5541526375, "num_tokens": 2207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480252950991, "lm_q2_score": 0.6548947425132314, "lm_q1q2_score": 0.601507888759827}}
{"text": "#include <iostream>\n#include <vector>\n#include <string>\n#include <math.h>\n#include <ctime>\n#include <armadillo>\n\nvoid plotData(std::vector<double> data);\n\nclass Layer {\n    arma::mat sigmoid(arma::mat x) {\n        return 1.0 / (1.0 + exp(-1.0*x));\n    }\n\n    public:\n    arma::mat weights;\n    arma::mat negativeVisibleProbabilities;\n    arma::umat positiveHiddenStates;\n    arma::mat positiveAssociations, negativeAssociations;\n\n    Layer() {\n        weights.randu(1, 1);\n    }\n\n    Layer(int neuronCount, int inputsPerNeuron) {\n        arma::arma_rng::set_seed(1);\n        weights.randn(inputsPerNeuron, neuronCount);\n        weights *= 0.1;\n        weights.insert_rows(0, 1);\n        weights.insert_cols(0, 1);\n    }\n\n    void calculatePositiveAssociations(arma::mat x) {\n        arma::mat positiveHiddenProbabilities = sigmoid(x*weights);\n        arma::arma_rng::set_seed(1);\n        arma::mat randomNormalProbabilties = arma::randu(size(positiveHiddenProbabilities));\n        positiveHiddenStates = positiveHiddenProbabilities > randomNormalProbabilties;\n        positiveAssociations = x.t()*positiveHiddenProbabilities;\n    }\n\n    void calculateNegativeAssociations() {\n        arma::mat negativeVisibleActivations = positiveHiddenStates*weights.t();\n        negativeVisibleProbabilities = sigmoid(negativeVisibleActivations);\n        negativeVisibleProbabilities.col(0) = arma::ones<arma::vec>(negativeVisibleProbabilities.n_rows);\n        arma::mat negativeHiddenActivations = negativeVisibleActivations*weights;\n        arma::mat negativeHiddenProbabilities = sigmoid(negativeHiddenActivations);\n        negativeAssociations = negativeVisibleProbabilities.t()*negativeHiddenProbabilities;\n    }\n\n    void run(arma::mat x) {\n        calculatePositiveAssociations(x);\n        calculateNegativeAssociations();\n    }\n};\n\nclass RBM {\n    arma::mat input;\n    Layer L1;\n    int L1NodeCount = 2;\n    double learningRate = 0.0005;\n    double exampleCount;\n\n    arma::mat sigmoid_derivative(arma::mat x) {\n        return x % (1-x);\n    }\n\n    void randomInitWeights(int visibleNodeCount) {\n        L1 = Layer(L1NodeCount, visibleNodeCount);\n    }\n\n    public:\n\n    RBM(arma::mat i) {\n        input = join_rows(arma::ones<arma::mat>(i.n_rows, 1), i);\n        randomInitWeights(i.n_cols);\n        exampleCount = i.n_rows;\n    }\n\n    void train(int numIt) {\n        double error;\n\n        for(int i=0; i<numIt; i++) {\n            L1.run(input);\n            L1.weights += learningRate * ((L1.positiveAssociations-L1.negativeAssociations) / exampleCount);\n\n            if (i%1000 == 0) {\n                error = accu(square(input - L1.negativeVisibleProbabilities));\n                std::cout << \"Step \"<< i<<\": \"<< error << std::endl;\n            }\n        }\n        error = accu(square(input - L1.negativeVisibleProbabilities));\n        std::cout << \"Step \"<< numIt <<\": \"<< error << std::endl;\n    }\n\n    arma::umat run(arma::mat i) {\n        arma::mat input = join_rows(arma::ones<arma::mat>(i.n_rows, 1), i);\n        L1.calculatePositiveAssociations(input);\n        return L1.positiveHiddenStates.cols(1, L1.positiveHiddenStates.n_cols-1);\n    }\n};\n\nvoid plotData(std::vector<double> data) {\n    FILE *pipe = popen(\"gnuplot -persist\" , \"w\");\n\n    if (pipe != NULL) {\n\n        fprintf(pipe, \"set style line 5 lt rgb 'cyan' lw 3 pt 6 \\n\");\n        fprintf(pipe, \"plot '-' with linespoints ls 5 \\n\");\n\n        for (int i=0; i<data.size(); i++) {\n            fprintf(pipe, \"%lf %lf\\n\", double(i), data[i]);\n        }\n        fprintf(pipe, \"e\");\n\n        fflush(pipe);\n        pclose(pipe);\n    }\n    else {\n        std::cout << \"Could not open gnuplot pipe\" << std::endl;\n    }\n}\n\nint main() {\n    arma::mat input = {{1,1,1,0,0,0},{1,0,1,0,0,0},{1,1,1,0,0,0},{0,0,1,1,1,0},{0,0,1,1,0,0},{0,0,1,1,1,0}};\n    int numIterations = 6000;\n\n    std::cout << \"RBM trained on multiple user's movie preferences\" << std::endl;\n    RBM model(input);\n\n    std::clock_t startTime;\n    startTime = std::clock();\n    model.train(numIterations);\n    std::cout << \"Training Time: \" << (std::clock() - startTime) / (double)(CLOCKS_PER_SEC / 1000) << \" ms\" << std::endl << std::endl;\n    arma::mat test = {{0,0,0,1,1,0}};\n    std::cout << \"Test User:\" << std::endl;\n    std::cout << \"Likes 1st Harry Potter:\\t\" << test(0,0) << std::endl;\n    std::cout << \"Likes Avatar:\\t\\t\" << test(0,1) << std::endl;\n    std::cout << \"Likes 3rd LOTR:\\t\\t\" << test(0,2) << std::endl;\n    std::cout << \"Likes Gladiator:\\t\" << test(0,3) << std::endl;\n    std::cout << \"Likes Titanic:\\t\\t\" << test(0,4) << std::endl;\n    std::cout << \"Likes Troll 2:\\t\\t\" << test(0,5) << std::endl << std::endl;\n    startTime = std::clock();\n    arma::umat hiddenStates = model.run(test);\n    std::cout << \"Prediction Time: \" << (std::clock() - startTime) / (double)(CLOCKS_PER_SEC / 1000) << \" ms\" << std::endl;\n    std::cout << \"Hidden Neuron Activations:\" << std::endl;\n    std::cout << \"Likes Oscar Winners:\\t\" << hiddenStates(0,0) << std::endl;\n    std::cout << \"Likes SciFi / Fantasy:\\t\" << hiddenStates(0,1) << std::endl;\n    return 0;\n}", "meta": {"hexsha": "accffa95d2bc31770daddfb9225ef67186d7b30c", "size": 5084, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rbm.cpp", "max_stars_repo_name": "pjIowa/MLTools", "max_stars_repo_head_hexsha": "a90908255b771fedba5625c0963a419c064309c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rbm.cpp", "max_issues_repo_name": "pjIowa/MLTools", "max_issues_repo_head_hexsha": "a90908255b771fedba5625c0963a419c064309c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rbm.cpp", "max_forks_repo_name": "pjIowa/MLTools", "max_forks_repo_head_hexsha": "a90908255b771fedba5625c0963a419c064309c1", "max_forks_repo_licenses": ["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.1208053691, "max_line_length": 134, "alphanum_fraction": 0.6044453186, "num_tokens": 1443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.6015078814530763}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <random>\n\ntemplate<typename T>\nusing PCoord = Eigen::Matrix<T, 1, 3>;\n\nint factorial(int n) {\n    if(n==0) return 1;\n    int ret = 1;\n    for(int i=1; i<=n; i++) ret *= i;\n    return ret;\n}\n\ntemplate<typename T>\nclass WaveFn {\npublic:\n    virtual ~WaveFn(){};\n    // return the value of wave function\n    virtual T value(const PCoord<T>&)=0;\n\n    // return three components of grad wave function\n    virtual PCoord<T> grad(const PCoord<T>&)=0;\n    \n    // return laplacian of the wave function\n    virtual T laplace(const PCoord<T>&)=0;\n};\n\n// n define the quantum number n of wave function\n// for lithium atom only (n=1, 2)\ntemplate<typename T, int N>\nclass SlaterWaveFn: public WaveFn<T> {\npublic:\n    const int n = N;\n    const int nterm = 7;\n    SlaterWaveFn(const PCoord<T>& r0): r0(r0){\n        for(int i=0; i<nterm; i++) {\n            // recaluate zeta_val accorindg to orbital\n            zeta_val[i] = zeta_val[i]/slap[n-1];\n            norm_const[i] = std::pow(2*zeta_val[i], pnu_val[i]-0.5)/\n                            std::sqrt(factorial(2*pnu_val[i]));\n        }\n    }\n    ~SlaterWaveFn(){};\n\n    T value(const PCoord<T>& r) {\n        auto dist = (r - r0).norm();\n        T ret = 0.0;\n        for(int i=0; i<nterm; i++) {\n            ret += norm_const[i]*phi_val[n-1][i]*\n                   std::pow(dist, pnu_val[i]-1)*std::exp(-dist*zeta_val[i]);\n        }\n        return ret;\n    }\n\n    PCoord<T> grad(const PCoord<T>& r) {\n        auto dist = (r - r0).norm();\n        auto nvec = (r - r0).normalized();\n        auto scalar_derv = 0;\n        for(int i=0; i<nterm; i++) {\n            scalar_derv += norm_const[i]*phi_val[n-1][i]*(\n                                (pnu_val[i] - 1)*pow(dist, pnu_val[i] - 2) - zeta_val[i]*pow(dist, pnu_val[i] - 1))*\n                                std::exp(-dist*zeta_val[i]);\n        }\n        return scalar_derv*nvec;\n    }\n\n    T laplace(const PCoord<T>& r) {\n        auto dist = (r - r0).norm();\n        auto scalar_derv = 0;\n        auto scalar_dderv = 0;\n        for(int i=0; i<nterm; i++) {\n            // (ab)'' = a''b + 2a'b'+ ab''\n            scalar_derv += norm_const[i]*phi_val[n-1][i]*(\n                                (pnu_val[i] - 1)*pow(dist, pnu_val[i] - 2) - zeta_val[i]*pow(dist, pnu_val[i] - 1))*\n                                std::exp(-dist*zeta_val[i]);\n            scalar_dderv += norm_const[i]*phi_val[n-1][i]*(\n                                (pnu_val[i] - 1)*(pnu_val[i] - 2)*pow(dist, pnu_val[i] - 3) -\n                                2*zeta_val[i]*(pnu_val[i] - 1)*pow(dist, pnu_val[i] - 2) +\n                                zeta_val[i]*zeta_val[i]*pow(dist, pnu_val[i] - 1))* \n                                std::exp(-dist*zeta_val[i]);\n        }\n        scalar_dderv = scalar_dderv + 2*scalar_derv/dist; // why?\n        return  scalar_derv;\n    }\n    \nprivate:\n    PCoord<T> r0;\n\n    T phi_val[2][7] = {\n        {-0.12220686, 1.11273225, 0.04125378, 0.09306499, -0.10260021, -0.00034191, 0.00021963},\n        {0.47750469, 0.11140449,-1.25954273, -0.18475003, -0.02736293, -0.00025064, 0.00057962}\n    };\n    T zeta_val[7] = {\n        0.72089388, 2.61691643, 0.69257443, 1.37137558, 3.97864549, 13.52900016, 19.30801440\n    };\n    T norm_const[7];\n    int pnu_val[7] = {\n        1, 1, 2, 2, 2, 2, 3 // 1s, 1s, 2s, 2s, 2s, 2s, 3s\n    };\n    T slap[2] = {1.00, 0.95};\n};\n\n// For Jastrow term of wave function\ntemplate<typename T>\nclass Jastrow: {\npublic:\n    Jastrow(const PCoord<T> r1, const PCoord<T> r2): r1(r1), r2(r2) {\n\n    }\n\nprivate:\n    PCoord<T> r1, r2;\n\n};\n\n// For lithium atom + Jastrow wave function\n// Not a child class of wave function\ntemplate<typename T>\nclass SlaterDet: {\npublic:\n    // Radom initialization, r0 is the position of nucleus\n    SlaterDet(const PCoord<T> r0): r0(r0) {\n        r1 = PCoord<T>::Random();\n        r2 = PCoord<T>::Random();\n        r3 = PCoord<T>::Random();\n    }\n\n    // Given initial coordinate\n    SlaterDet(const PCoord<T> r0, const PCoord<T> r1, const PCoord<T> r2, const PCoord<T> r3)\n        :r0(r0), r1(r1), r2(r2), r3(r3) {}\n\n    ~SlaterDate() {\n        delete s1, s2, s3;\n    }\n\n    T eval() {\n        // For initialize evaluation and validation\n        sdet << s1->value(r1), s2 -> value(r1), 0.0,\n                s1->value(r2), s2 -> value(r2), 0.0,\n                0.0, 0.0, s3 -> value(r3); \n        inv_sdet = sdet.inverse();\n        return sdet.determinant();\n    }\n\n    void update(PCoord<T> r, int i) {\n        // update the slater det matrix and the inverse matrix\n        std::uniform_real_distribution<T> rnum(0, 1);\n        PCoord<T> svec;\n        switch (i) {\n            case 0:\n                auto r = r1 + PCoord<T>::Random();\n                svec << s1 -> value(r), s2 -> value(r), 0.0;\n                break;\n            case 1:\n                auto r = r2 + PCoord<T>::Random();\n                svec << s1 -> value(r), s2 -> value(r), 0.0;\n                break;\n            case 2;\n                auto r = r3 + PCoord<T>::Random();\n                svec << 0.0, 0.0, s3->value(r);\n                break;\n            default:\n                break;\n        }\n\n        // Calculate Dnew/Dold\n        auto ratio = (svec * inv_sdet).sum();\n        // apply Sherman\u2013Morrison formula\n        // see https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula\n        if(ratio > 1 || ratio > rnum(gen)) {\n            auto irow = inv_sdet.rows(i)/ratio;\n            inv_sdet = inv_sdet - svec*inv_sdet*inv_sdet.transpose()/ratio;\n            inv_sdet.rows(i) = irow;\n            update = true;\n        } else update = false;\n    }\n\n    // do we need this?\n    // T value() {\n    // }\n\n    PCoord<T> grad(int i) {\n        PCoord<T> svec;\n        switch (i) {\n            case 0:\n                svec << s1 -> grad(r1), s2 -> grad(r1), 0.0;\n                break;\n            case 1:\n                svec << s1 -> grad(r2), s2 -> grad(r2), 0.0;\n                break;\n            case 2;\n                svec << 0.0, 0.0, s3->grad(r3);\n                break;\n            default:\n                throw std::runtime_error(\"No such index\" + std::to_string(i) + \" exists\");\n        }\n        return inv_sde * svec;        \n    }\n\n    T energy() {\n        // two different cases, whether/not sdet is updated\n        if(update) {\n            return 0;\n        } else {\n            return 0;\n        }\n    }\n\n    T laplace(int i) {\n        PCoord<T> svec;\n        switch (i) {\n            case 0:\n                svec << s1 -> laplace(r1), s2 -> laplace(r1), 0.0;\n                break;\n            case 1:\n                svec << s1 -> laplace(r2), s2 -> laplace(r2), 0.0;\n                break;\n            case 2;\n                svec << 0.0, 0.0, s3->laplace(r3);\n                break;\n            default:\n                throw std::runtime_error(\"No such index\" + std::to_string(i) + \" exists\");\n                break;\n        }\n        return inv_sde * svec;    \n    }\n\nprivate:\n    PCoord<T> r0;\n    PCoord<T> r1, r2, r3;\n    SlaterWaveFn<T, 1>* s1;\n    SlaterWaveFn<T, 1>* s2; // 1s alpha, 1s beta\n    SlaterWaveFn<T, 2>* s3; // 2s alpha\n    SlaterDet<T, 3, 3> sdet, inv_sdet; // Slater determinant\n    std::random_device rd;\n    std::mt19937 rgen{rd()}\n    bool update = false;\n};", "meta": {"hexsha": "bd17e10d0d05ee66ea2e3b567fcbb6778b2ca448", "size": 7279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cc/lithium.hpp", "max_stars_repo_name": "zxjzxj9/SimpleQMC", "max_stars_repo_head_hexsha": "6382150bbe39683727665542459966fe3961eb56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cc/lithium.hpp", "max_issues_repo_name": "zxjzxj9/SimpleQMC", "max_issues_repo_head_hexsha": "6382150bbe39683727665542459966fe3961eb56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cc/lithium.hpp", "max_forks_repo_name": "zxjzxj9/SimpleQMC", "max_forks_repo_head_hexsha": "6382150bbe39683727665542459966fe3961eb56", "max_forks_repo_licenses": ["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.3291666667, "max_line_length": 116, "alphanum_fraction": 0.487979118, "num_tokens": 2302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.6015078734641839}}
{"text": "#include <cmath>\n\n#include <ros/ros.h>\n#include <tf2_eigen/tf2_eigen.h>\n\n#include <mav_msgs/conversions.h>\n#include <mav_msgs/RateThrust.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"cascaded_pid_control_node.hpp\"\n\nnamespace cascaded_pid_control {\n\n  inline geometry_msgs::Vector3 MsgVec3(const Eigen::Vector3d& vec) {\n    geometry_msgs::Vector3 result;\n    result.x = vec[0];\n    result.y = vec[1];\n    result.z = vec[2];\n    return result;\n  }\n\n  inline double Constrain(double value, double min, double max) {\n    if (value < min) {\n      return min;\n    }\n    if (value > max) {\n      return max;\n    }\n    return value;\n  }\n\n  double CascadedPidControl::AltitudeControl(\n    const mav_msgs::EigenOdometry& current,\n    const mav_msgs::EigenTrajectoryPoint& cmd,\n    const Eigen::Vector3d &accel_ff,\n    double dt) {\n\n      Eigen::Matrix3d rot_mat = current.orientation_W_B.toRotationMatrix();\n\n      double dz = cmd.position_W[2] - current.position_W[2];\n      double dvz = cmd.velocity_W[2] - current.getVelocityWorld()[2];\n      double z_dot_dot = kp_z_ * dz + kd_z_ * dvz + accel_ff[2];\n\n      double result;\n      result = z_dot_dot * mass_ / rot_mat(2, 2);\n\n      // clamp value\n      result = Constrain(result, min_thrust_, max_thrust_);\n      return result;\n  }\n\n  Eigen::Vector3d CascadedPidControl::LateralPositionControl(\n    const mav_msgs::EigenOdometry& current,\n    const mav_msgs::EigenTrajectoryPoint& cmd,\n    const Eigen::Vector3d& accel_ff,\n    double dt) {\n\n    double err_x = cmd.position_W[0] - current.position_W[0];\n    double err_y = cmd.position_W[1] - current.position_W[1];\n\n    double err_vx = cmd.velocity_W[0] - current.getVelocityWorld()[0];\n    double err_vy = cmd.velocity_W[1] - current.getVelocityWorld()[1];\n    \n    Eigen::Vector3d result;\n    result << Constrain(kp_x_ * err_x + kd_x_ * err_vx + accel_ff[0], -max_abs_accel_x_, max_abs_accel_x_),\n              Constrain(kp_y_ * err_y + kd_y_ * err_vy + accel_ff[1], -max_abs_accel_y_, max_abs_accel_y_),\n              0;\n\n    return result;\n  }\n\n  Eigen::Vector3d CascadedPidControl::AttitudeControl(\n      const mav_msgs::EigenOdometry& pose,\n      const Eigen::Vector3d& accel_cmd,\n      double thrust_cmd,\n      double dt) {\n    Eigen::Matrix3d rot_mat = pose.orientation_W_B.toRotationMatrix();\n\n    double bx = rot_mat(0, 2);\n    double by = rot_mat(1, 2);\n    \n    double c = thrust_cmd / mass_;\n    double bx_cmd = accel_cmd[0] / c;\n    double by_cmd = accel_cmd[1] / c;\n\n    // clamp bx_cmd and by_cmd be with [-sqrt(2)/2,  sqrt(2)/2]\n    // this will result in forcing angle between the thrust vector and x/y axis of world frame \n    // be in [45deg, 135deg] (this is not the same with constraining roll and pitch angle)\n    bx_cmd = Constrain(bx_cmd, -0.5, 0.5);\n    by_cmd = Constrain(by_cmd, -0.5, 0.5);\n    \n    double bx_dot = kp_pitch_ * (bx_cmd - bx);\n    double by_dot = kp_roll_ * (by_cmd - by);\n\n    double k = 1.0 / rot_mat(2, 2);\n    Eigen::Vector3d pq_rate_cmd;\n    pq_rate_cmd << k * (rot_mat(1, 0) * bx_dot - rot_mat(0, 0) * by_dot),\n                   k * (rot_mat(1, 1) * bx_dot - rot_mat(0, 1) * by_dot),\n                   0;\n\n    return pq_rate_cmd;\n  }\n\n  double CascadedPidControl::YawControl(\n    const mav_msgs::EigenOdometry& current,\n    double yaw_cmd,\n    double dt) {\n    double current_yaw = current.getYaw();\n    double err_yaw = yaw_cmd - current_yaw;\n    while (err_yaw > PI) {\n      err_yaw -= 2 * PI;\n    }\n    while (err_yaw < -PI) {\n      err_yaw += 2 * PI;\n    }\n    return kp_yaw_ * err_yaw;\n  }\n\n  void CascadedPidControl::OdometryCallback(const nav_msgs::OdometryConstPtr &ptr) {\n    if (controller_active_) {\n      mav_msgs::eigenOdometryFromMsg(*ptr, &last_odometry_);\n      double current_time = ptr->header.stamp.toSec();\n      double dt = current_time - last_odometry_time_;\n      last_odometry_time_ = current_time;\n\n      Eigen::Vector3d accel_ff = set_point_.acceleration_W + default_ff_;\n\n      double thrust = AltitudeControl(last_odometry_, set_point_, accel_ff, dt);\n      Eigen::Vector3d accel_cmd = LateralPositionControl(last_odometry_, set_point_, accel_ff, dt);\n      Eigen::Vector3d pqr_rate_cmd = AttitudeControl(last_odometry_, accel_cmd, thrust, dt);\n      pqr_rate_cmd[2] = YawControl(last_odometry_, set_point_.getYaw(), dt);\n\n      // ROS_INFO_STREAM(thrust<<\" \"<<accel_cmd<<\" \"<<pqr_rate_cmd);\n\n      // control command is published as mav_msgs/RateThrust\n      mav_msgs::RateThrust rate_thrust;\n      rate_thrust.header.stamp = ros::Time::now();\n      rate_thrust.header.frame_id = \"uav/imu\";\n      rate_thrust.thrust.z = thrust;\n      mav_msgs::vectorEigenToMsg(pqr_rate_cmd, &rate_thrust.angular_rates);\n\n      if (publish_debug_topic_) {\n        PublishDebugTopic(last_odometry_);\n      }\n\n      rate_thrust_pub_.publish(rate_thrust);\n    }\n  }\n\n  void CascadedPidControl::Init() {\n    dynamic_reconfigure::Server<CascadedPidConfig>::CallbackType cb;\n    cb = boost::bind(&CascadedPidControl::DynamicReconfigureCallback, this, _1, _2);\n    server_.setCallback(cb);\n\n    controller_active_ = false;\n    last_odometry_time_ = 0;\n    default_ff_ << 0, 0, GRAVITY_CONST;\n    publish_debug_topic_ = private_nh_.param(\"publish_debug_topic\", false);\n\n    rate_thrust_pub_ = private_nh_.advertise<mav_msgs::RateThrust>(\"rateThrust\", 1);\n    odometry_sub_ = private_nh_.subscribe<nav_msgs::Odometry>(\"odometry\", 1, &CascadedPidControl::OdometryCallback, this);\n    trajectory_sub_ = private_nh_.subscribe<trajectory_msgs::MultiDOFJointTrajectory>(\"trajectory\", 1, &CascadedPidControl::TrajectoryCallbackStartFromNearest2, this);\n\n    if (publish_debug_topic_) {\n      position_setpoint_pub_ = private_nh_.advertise<geometry_msgs::Vector3>(\"positionSetpoint\", 8);\n      velocity_setpoint_pub_ = private_nh_.advertise<geometry_msgs::Vector3>(\"velocitySetpoint\", 8);\n      attitude_setpoint_pub_ = private_nh_.advertise<geometry_msgs::Vector3>(\"attitudeSetpoint\", 8);\n      position_error_pub_ = private_nh_.advertise<geometry_msgs::Vector3>(\"positionError\", 8);\n      velocity_error_pub_ = private_nh_.advertise<geometry_msgs::Vector3>(\"velocityError\", 8);\n      attitude_error_pub_ = private_nh_.advertise<geometry_msgs::Vector3>(\"attitudeError\", 8);\n      target_pose_pub_ = private_nh_.advertise<geometry_msgs::PoseStamped>(\"targetPose\", 1);\n    }\n\n    timer_ = nh_.createTimer(ros::Duration(0), &CascadedPidControl::TimerCallback, this, true, false);\n\n    ROS_INFO(\"Cascaded PID control node initialized. Waiting for trajectory.\");\n  }\n\n  void CascadedPidControl::Destroy() {\n    ROS_INFO(\"Cascaded PID control exited.\");\n  }\n\n  void CascadedPidControl::DynamicReconfigureCallback(CascadedPidConfig &config, uint32_t level) {\n    ROS_INFO(\"Dynamic reconfigure requested.\");\n    mass_ = config.mass;\n    // motors should generate at least (mass * g) N force, this is the minimum\n    // value of max_thrust, and maximu value of min_thrust\n    if (config.max_thrust < mass_ * GRAVITY_CONST) {\n      config.max_thrust = mass_ * GRAVITY_CONST;\n    }\n    if (config.min_thrust > mass_ * GRAVITY_CONST) {\n      config.min_thrust = mass_ * GRAVITY_CONST;\n    }\n    min_thrust_ = config.min_thrust;\n    max_thrust_ = config.max_thrust;\n\n    kp_x_ = config.kp_x;\n    kd_x_ = config.kd_x;\n    max_abs_accel_x_ = config.max_abs_accel_x;\n    kp_y_ = config.kp_y;\n    kd_y_ = config.kd_y;\n    max_abs_accel_y_ = config.max_abs_accel_y;\n    kp_z_ = config.kp_z;\n    kd_z_ = config.kd_z;\n    kp_roll_ = config.kp_roll;\n    kp_pitch_ = config.kp_pitch;\n    kp_yaw_ = config.kp_yaw;\n\n    if (config.xy_same_params) {\n      config.kp_y = kp_y_ = kp_x_;\n      config.kd_y = kd_y_ = kd_x_;\n      config.max_abs_accel_y = max_abs_accel_y_ = max_abs_accel_x_;\n    }\n\n    if (config.rp_same_params) {\n      config.kp_pitch = kp_pitch_ = kp_roll_;\n    }\n  }\n\n  void CascadedPidControl::PublishDebugTopic(const mav_msgs::EigenOdometry& odometry) {\n    // debug topic includes:\n    //  1. set point position\n    //  2. set point velocit\n    //  3. set point attitude (x component: roll, y component: pitch, z component: yaw)\n    geometry_msgs::Vector3 pos_setpoint;\n    tf2::toMsg(set_point_.position_W, pos_setpoint);\n    geometry_msgs::Vector3 vel_setpoint;\n    tf2::toMsg(set_point_.velocity_W, vel_setpoint);\n    geometry_msgs::Vector3 att_setpoint;\n    Eigen::Vector3d set_att;\n    mav_msgs::getEulerAnglesFromQuaternion(set_point_.orientation_W_B, &set_att);\n    tf2::toMsg(set_att, att_setpoint);\n\n    position_setpoint_pub_.publish(pos_setpoint);\n    velocity_setpoint_pub_.publish(vel_setpoint);\n    attitude_setpoint_pub_.publish(att_setpoint);\n\n    //  4. error of position\n    //  5. error of velocity\n    //  6. error of attitude (x component: roll, y component: pitch, z component: yaw)\n    geometry_msgs::Vector3 pos_error;\n    tf2::toMsg(set_point_.position_W - odometry.position_W, pos_error);\n    geometry_msgs::Vector3 vel_error;\n    tf2::toMsg(set_point_.velocity_W - odometry.getVelocityWorld(), vel_error);\n    geometry_msgs::Vector3 att_error;\n    Eigen::Vector3d ego_att;\n    mav_msgs::getEulerAnglesFromQuaternion(odometry.orientation_W_B, &ego_att);\n    tf2::toMsg(set_att - ego_att, att_error);\n\n    position_error_pub_.publish(pos_error);\n    velocity_error_pub_.publish(vel_error);\n    attitude_error_pub_.publish(att_error);\n  }\n\n  void CascadedPidControl::TrajectoryCallbackStartFromNearest2(const trajectory_msgs::MultiDOFJointTrajectoryConstPtr& ptr) {\n    if (ptr->points.size() == 0) {\n      ROS_WARN(\"Empty trajectory.\");\n      return;\n    }\n\n    ROS_INFO(\"New trajectory arrived.\");\n\n    bool restart = traj_points_.size() == 0;\n\n    timer_.stop();\n    traj_points_.clear();\n    command_wait_time_.clear();\n\n    auto iter = ptr->points.begin();\n    double last_time = iter->time_from_start.toSec();\n    command_wait_time_.push_back(last_time);\n    mav_msgs::EigenTrajectoryPoint eigen_traj_point;\n    mav_msgs::eigenTrajectoryPointFromMsg(*iter, &eigen_traj_point);\n    traj_points_.push_back(eigen_traj_point);\n\n    double nearest_dist = 1e9;\n    bool nearest_found = false;\n    double threshold_dist;\n    int nearest_idx = 0;\n\n    if (restart) {\n      nearest_found = true;\n    } else {\n      threshold_dist = (set_point_.position_W - eigen_traj_point.position_W).norm();\n      nearest_dist = threshold_dist;\n    }\n\n    for (++iter; iter != ptr->points.end(); ++iter) {\n      double traj_time = iter->time_from_start.toSec();\n      command_wait_time_.push_back(traj_time - last_time);\n      mav_msgs::eigenTrajectoryPointFromMsg(*iter, &eigen_traj_point);\n      traj_points_.push_back(eigen_traj_point);\n\n      if (!nearest_found) {\n        double dist = (set_point_.position_W- eigen_traj_point.position_W).norm();\n        if (dist > threshold_dist) {\n          nearest_found = true;\n        } else {\n          if (dist < nearest_dist) {\n            nearest_dist = dist;\n            nearest_idx = iter - ptr->points.begin();\n          }\n        }\n      }\n\n      last_time = traj_time;\n    }\n\n    ROS_INFO(\"The closest trajectory point to the current position is at index %d.\", nearest_idx);\n\n    while (traj_points_.size() > 1 && nearest_idx-- > 0) {\n      traj_points_.pop_front();\n      command_wait_time_.pop_front();\n    }\n\n    SetNextPoint(traj_points_.front());\n    traj_points_.pop_front();\n\n    if (!traj_points_.empty()) {\n      double wait_time = command_wait_time_.front();\n      command_wait_time_.pop_front();\n      timer_.setPeriod(ros::Duration(wait_time));\n      timer_.start();\n    }\n\n    controller_active_ = true;    \n  }\n\n\n  void CascadedPidControl::TrajectoryCallbackStartFromNearest(const trajectory_msgs::MultiDOFJointTrajectoryConstPtr& ptr) {\n    // This trajectory handler when receiving a new trajectory, pickup the neartest waypoint to the current position and\n    // use it as the next target set point\n    if (ptr->points.size() == 0) {\n      ROS_WARN(\"Empty trajectory.\");\n      return;\n    }\n\n    ROS_INFO(\"New trajectory arrived.\");\n\n    timer_.stop();\n    traj_points_.clear();\n    command_wait_time_.clear();\n\n    double nearest_dist;\n    auto iter = ptr->points.begin();\n    double last_time = iter->time_from_start.toSec();\n    command_wait_time_.push_back(last_time);\n    mav_msgs::EigenTrajectoryPoint eigen_traj_point;\n    mav_msgs::eigenTrajectoryPointFromMsg(*iter, &eigen_traj_point);\n    traj_points_.push_back(eigen_traj_point);\n\n    bool nearest_found = false;\n    double threshold_dist;\n    int nearest_idx = 0;\n\n    if (last_odometry_time_ <= 0) {\n      nearest_found = true;\n    } else {\n      threshold_dist = (last_odometry_.position_W - eigen_traj_point.position_W).norm();\n      nearest_dist = threshold_dist;\n    }\n\n    for (++iter; iter != ptr->points.end(); ++iter) {\n      double traj_time = iter->time_from_start.toSec();\n      command_wait_time_.push_back(traj_time - last_time);\n      mav_msgs::eigenTrajectoryPointFromMsg(*iter, &eigen_traj_point);\n      traj_points_.push_back(eigen_traj_point);\n\n      if (!nearest_found) {\n        double dist = (last_odometry_.position_W - eigen_traj_point.position_W).norm();\n        if (dist > threshold_dist) {\n          nearest_found = true;\n        } else {\n          if (dist < nearest_dist) {\n            nearest_dist = dist;\n            nearest_idx = iter - ptr->points.begin();\n          }\n        }\n      }\n\n      last_time = traj_time;\n    }\n\n    ROS_INFO(\"The closest trajectory point to the current position is at index %d.\", nearest_idx);\n\n    while (traj_points_.size() > 1 && nearest_idx-- >= 0) {\n      traj_points_.pop_front();\n      command_wait_time_.pop_front();\n    }\n\n    SetNextPoint(traj_points_.front());\n    traj_points_.pop_front();\n\n    if (!traj_points_.empty()) {\n      double wait_time = command_wait_time_.front();\n      command_wait_time_.pop_front();\n      timer_.setPeriod(ros::Duration(wait_time));\n      timer_.start();\n    }\n\n    controller_active_ = true;    \n  }\n\n  void CascadedPidControl::TrajectoryCallbackNew(const trajectory_msgs::MultiDOFJointTrajectoryConstPtr& ptr) {\n    // Merge the new coming trajectory with the current one that being executed.\n\n    // Some preconditions: because the planner with use part of the old trajectory to generate\n    // the new trajectory, there should be some waypoints overlapping (otherwise the controller\n    // is executing more waypoints than the planner could re-generate. the rate of the planner \n    // should be raised)\n    //\n    // so the idea is, find out the waypoint in the in coming trajectory that is closest to the\n    // current set point (in ideal case, the distance should be 0 since they are overlapping).\n    // from that point, keep comparing waypoints until they diverge (distance greater than some\n    // threshold). from the point they diverge, we have a new trajectory segement. subsitude the new\n    // segment with the corresponding part in the trajectory the controller is going to execute.\n    //\n\n    if (ptr->points.size() == 0) {\n      ROS_WARN(\"Empty trajectory.\");\n      return;\n    }\n\n    ROS_INFO(\"New trajectory arrived.\");\n\n    bool should_restart = traj_points_.size() == 0;\n\n    mav_msgs::EigenTrajectoryPoint eigen_traj_point;\n    std::vector<mav_msgs::EigenTrajectoryPoint> new_trajectory;\n    std::vector<double> new_wait_time;\n    double closest_dist = 1e9;\n    std::size_t best_match = -1;\n    auto iter = ptr->points.begin();\n    double last_time = -1;\n    // find out the best matching waypoint in the new coming trajectory with \n    // the current set point.\n    for (auto iter = ptr->points.begin(); iter != ptr->points.end(); ++iter) {\n      mav_msgs::eigenTrajectoryPointFromMsg(*iter, &eigen_traj_point);\n      new_trajectory.push_back(eigen_traj_point);\n      double dist = (eigen_traj_point.position_W - set_point_.position_W).norm();\n      if (dist < closest_dist) {\n        closest_dist = dist;\n        best_match = iter - ptr->points.begin();\n      }\n      if (last_time >= 0) {\n        double dt = iter->time_from_start.toSec() - last_time;\n        new_wait_time.push_back(dt);\n      }\n      last_time = iter->time_from_start.toSec();\n    }\n    ROS_INFO(\"New trajectory is built. Length: %zu, number of wait commands: %zu\", new_trajectory.size(), new_wait_time.size());\n    ROS_INFO(\"Merging the new trajectory with current one.\");\n\n    // continue looking forward until the new trajectory diverge with the current trajectory\n    std::size_t current_j = 0;\n    std::size_t new_j = best_match;\n    for (;\n         current_j < traj_points_.size() - 1 && new_j < new_trajectory.size() - 1;\n         ++current_j, ++new_j) {\n      if ((traj_points_[current_j].position_W - new_trajectory[new_j].position_W).norm() > 0.1) {\n        break;\n      }\n    }\n    ROS_INFO(\"New trajectory start overlapping with the current one at waypoint index %zu, diverge from %zu (waypoint index %zu in the current path)\", best_match, new_j, current_j);\n    \n    // substitude segement in the new trajectory from new_j with the one in the current trajectory\n    // from current_j\n    std::size_t num_copied = 0;\n    std::size_t copy_current_j = current_j;\n    std::size_t copy_new_j = new_j;\n    while (copy_current_j < traj_points_.size() && copy_new_j < new_trajectory.size()) {\n      traj_points_[current_j] = new_trajectory[new_j];\n      ++copy_current_j;\n      ++copy_new_j;\n      ++num_copied;\n    }\n    ROS_INFO(\"%zu waypoints copied from new trajectory within from %zu to %zu to the current trajectory from %zu to %zu.\",\n          num_copied, new_j, copy_new_j, current_j, copy_current_j);\n    ROS_INFO(\"Truncate number of waypoints to %zu.\", copy_current_j);\n    traj_points_.resize(copy_current_j);\n\n    if (copy_new_j < new_trajectory.size()) {\n      ROS_INFO(\"There're still waypoints in the new trajectory, starting from index %zu\", copy_new_j);\n      std::copy(new_trajectory.begin() + copy_new_j, new_trajectory.end(), std::back_inserter(traj_points_));\n    }\n\n    // command wait time update.\n    command_wait_time_.resize(current_j);\n    std::copy(new_wait_time.begin() + new_j, new_wait_time.end(), std::back_inserter(command_wait_time_));\n\n    ROS_INFO_STREAM(\"New trajectory length: \" << traj_points_.size() << \", command wait time queue length: \" << command_wait_time_.size() << \".\");\n\n    if (should_restart) {\n      ROS_INFO(\"Starting/restarting waypoint following routine.\");\n      if (!traj_points_.empty()) {\n        SetNextPoint(traj_points_.front());\n        traj_points_.pop_front();\n        if (!traj_points_.empty()) {\n          double wait_time = command_wait_time_.front();\n          command_wait_time_.pop_front();\n          timer_.stop();\n          timer_.setPeriod(ros::Duration(wait_time));\n          timer_.start();\n        }\n      }\n      controller_active_ = true;\n    }\n    ROS_INFO(\"New trajectory is successfully merged into the exising trajectory.\");\n  }\n\n  void CascadedPidControl::TrajectoryCallback(const trajectory_msgs::MultiDOFJointTrajectoryConstPtr& ptr) {\n    timer_.stop();\n    traj_points_.clear();\n    command_wait_time_.clear();\n\n    if (ptr->points.size() == 0) {\n      ROS_WARN(\"Empty trajectory.\");\n      return;\n    }\n\n    ROS_INFO(\"New trajectory arrived.\");\n\n    auto iter = ptr->points.begin();\n    double last_time = iter->time_from_start.toSec();\n    command_wait_time_.push_back(last_time);\n    mav_msgs::EigenTrajectoryPoint eigen_traj_point;\n    mav_msgs::eigenTrajectoryPointFromMsg(*iter, &eigen_traj_point);\n    traj_points_.push_back(eigen_traj_point);\n\n    for (++iter; iter != ptr->points.end(); ++iter) {\n      double traj_time = iter->time_from_start.toSec();\n      command_wait_time_.push_back(traj_time - last_time);\n      mav_msgs::eigenTrajectoryPointFromMsg(*iter, &eigen_traj_point);\n      traj_points_.push_back(eigen_traj_point);\n\n      last_time = traj_time;\n    }\n\n    SetNextPoint(traj_points_.front());\n    traj_points_.pop_front();\n\n    if (!traj_points_.empty()) {\n      double wait_time = command_wait_time_.front();\n      command_wait_time_.pop_front();\n      timer_.setPeriod(ros::Duration(wait_time));\n      timer_.start();\n    }\n\n    controller_active_ = true;\n  }\n\n  void CascadedPidControl::TimerCallback(const ros::TimerEvent& e) {\n    if (traj_points_.empty()) {\n      ROS_INFO(\"All trajectory commands have beed carried out.\");\n      return;\n    }\n\n    SetNextPoint(traj_points_.front());\n    traj_points_.pop_front();\n    if (!traj_points_.empty()) {\n      double wait_time = command_wait_time_.front();\n      command_wait_time_.pop_front();\n      timer_.stop();\n      timer_.setPeriod(ros::Duration(wait_time));\n      timer_.start();\n    }\n  }\n\n  void CascadedPidControl::SetNextPoint(const mav_msgs::EigenTrajectoryPoint& point) {\n    set_point_ = point;\n    if (publish_debug_topic_) {\n      geometry_msgs::PoseStamped msg;\n      msg.header.frame_id = \"map\";\n      msg.header.stamp = ros::Time::now();\n      mav_msgs::pointEigenToMsg(set_point_.position_W, &msg.pose.position);\n      mav_msgs::quaternionEigenToMsg(set_point_.orientation_W_B, &msg.pose.orientation);\n      target_pose_pub_.publish(msg);\n    }\n  }\n\n}\n\nXROS_RUNNABLE_NODE_MAIN(cascaded_pid_control::CascadedPidControl)\n", "meta": {"hexsha": "3c0cace1467e67441dbf777a15f1dd65a11aee5f", "size": 21101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cascaded_pid_control/src/cascaded_pid_control_node.cpp", "max_stars_repo_name": "Veilkrand/drone_race", "max_stars_repo_head_hexsha": "7391f1a94bfe354aab3e24be61b76e1595481ad9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cascaded_pid_control/src/cascaded_pid_control_node.cpp", "max_issues_repo_name": "Veilkrand/drone_race", "max_issues_repo_head_hexsha": "7391f1a94bfe354aab3e24be61b76e1595481ad9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cascaded_pid_control/src/cascaded_pid_control_node.cpp", "max_forks_repo_name": "Veilkrand/drone_race", "max_forks_repo_head_hexsha": "7391f1a94bfe354aab3e24be61b76e1595481ad9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-15T10:34:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-09T15:08:20.000Z", "avg_line_length": 36.0085324232, "max_line_length": 181, "alphanum_fraction": 0.6841381925, "num_tokens": 5435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.6015020339873393}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/element_pow.hpp\n *\n * \\brief Apply the \\c std::pow function to each element of a vector or a matrix\n *  expression.\n *\n * Copyright (c) 2015, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_ELEMENT_POW_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_ELEMENT_POW_HPP\n\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/expression/matrix_binary_functor.hpp>\n#include <boost/numeric/ublasx/expression/vector_binary_functor.hpp>\n#include <cmath>\n#include <complex>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\nnamespace detail {\n\ntemplate <typename VectorExprT, typename Arg2T>\nstruct vector_element_pow_functor1_traits\n{\n\ttypedef VectorExprT input_expression_type;\n\ttypedef typename vector_traits<input_expression_type>::value_type signature_argument1_type;\n\ttypedef Arg2T signature_argument2_type;\n\t//typedef signature_argument_type signature_result_type;\n\ttypedef typename promote_traits<\n\t\t\t\tsignature_argument1_type,\n\t\t\t\tsignature_argument2_type\n\t\t\t>::promote_type signature_result_type;\n\ttypedef vector_binary_functor1_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tArg2T,\n\t\t\t\tsignature_result_type (signature_argument1_type, signature_argument2_type)\n\t\t\t> binary_functor_expression_type;\n\ttypedef typename binary_functor_expression_type::result_type result_type;\n\ttypedef typename binary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename Arg1T, typename VectorExprT>\nstruct vector_element_pow_functor2_traits\n{\n\ttypedef VectorExprT input_expression_type;\n\ttypedef Arg1T signature_argument1_type;\n\ttypedef typename vector_traits<input_expression_type>::value_type signature_argument2_type;\n\t//typedef signature_argument_type signature_result_type;\n\ttypedef typename promote_traits<\n\t\t\t\tsignature_argument1_type,\n\t\t\t\tsignature_argument2_type\n\t\t\t>::promote_type signature_result_type;\n\ttypedef vector_binary_functor2_traits<\n\t\t\t\tArg1T,\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument1_type, signature_argument2_type)\n\t\t\t> binary_functor_expression_type;\n\ttypedef typename binary_functor_expression_type::result_type result_type;\n\ttypedef typename binary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename MatrixExprT, typename Arg2T>\nstruct matrix_element_pow_functor1_traits\n{\n\ttypedef MatrixExprT input_expression_type;\n\ttypedef typename matrix_traits<input_expression_type>::value_type signature_argument1_type;\n\ttypedef Arg2T signature_argument2_type;\n\t//typedef signature_argument_type signature_result_type;\n\ttypedef typename promote_traits<\n\t\t\t\tsignature_argument1_type,\n\t\t\t\tsignature_argument2_type\n\t\t\t>::promote_type signature_result_type;\n\ttypedef matrix_binary_functor1_traits<\n\t\t\t\tinput_expression_type,\n\t\t\t\tArg2T,\n\t\t\t\tsignature_result_type (signature_argument1_type, signature_argument2_type)\n\t\t\t> binary_functor_expression_type;\n\ttypedef typename binary_functor_expression_type::result_type result_type;\n\ttypedef typename binary_functor_expression_type::expression_type expression_type;\n};\n\n\ntemplate <typename Arg1T, typename MatrixExprT>\nstruct matrix_element_pow_functor2_traits\n{\n\ttypedef MatrixExprT input_expression_type;\n\ttypedef Arg1T signature_argument1_type;\n\ttypedef typename matrix_traits<input_expression_type>::value_type signature_argument2_type;\n\t//typedef signature_argument_type signature_result_type;\n\ttypedef typename promote_traits<\n\t\t\t\tsignature_argument1_type,\n\t\t\t\tsignature_argument2_type\n\t\t\t>::promote_type signature_result_type;\n\ttypedef matrix_binary_functor2_traits<\n\t\t\t\tArg1T,\n\t\t\t\tinput_expression_type,\n\t\t\t\tsignature_result_type (signature_argument1_type, signature_argument2_type)\n\t\t\t> binary_functor_expression_type;\n\ttypedef typename binary_functor_expression_type::result_type result_type;\n\ttypedef typename binary_functor_expression_type::expression_type expression_type;\n};\n\n\n// Wrappers to the std::pow function to avoid compiler errors\n\ntemplate <typename T1, typename T2>\nBOOST_UBLAS_INLINE\ntypename promote_traits<T1,T2>::promote_type element_pow(T1 x, T2 y)\n{\n    return ::std::pow(x, y);\n}\n\ntemplate <typename T1, typename T2>\nBOOST_UBLAS_INLINE\nstd::complex<T1> element_pow(std::complex<T1> const& x, T2 y)\n{\n    return ::std::pow(x, y);\n}\n\ntemplate <typename T1, typename T2>\nBOOST_UBLAS_INLINE\nstd::complex<T1> element_pow(T1 x, std::complex<T2> const& y)\n{\n\t// Remember: if z=(a + ib) is a complex number and c is a scalar => c^z = e^{ln(c)*z}\n    return ::std::exp(::std::log(x)*y);\n}\n\n} // Namespace detail\n\n\n/**\n * \\brief Applies the \\c std::pow function to a given vector expression,\n *  where each element of the vector is treated as the base of the\n *  exponentiation.\n *\n * \\tparam VectorExprT The type of the input vector expression.\n *\n * \\param ve The input vector expression.\n * \\param p The exponent.\n * \\return A vector expression representing the application of \\c std::pow to\n *  each element of \\a ve.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename VectorExprT, typename T>\nBOOST_UBLAS_INLINE\ntypename detail::vector_element_pow_functor1_traits<VectorExprT,T>::result_type element_pow(vector_expression<VectorExprT> const& ve, T p)\n{\n\ttypedef typename detail::vector_element_pow_functor1_traits<VectorExprT,T>::expression_type expression_type;\n\ttypedef typename detail::vector_element_pow_functor1_traits<VectorExprT,T>::signature_argument1_type signature_argument1_type;\n\ttypedef typename detail::vector_element_pow_functor1_traits<VectorExprT,T>::signature_argument2_type signature_argument2_type;\n\ttypedef typename detail::vector_element_pow_functor1_traits<VectorExprT,T>::signature_result_type signature_result_type;\n\n//\treturn expression_type(ve(), detail::element_pow<signature_result_type>);\n//\tsignature_result_type (*)(ptr_element_pow_fun)(signature_argument_type)(BOOST_NUMERIC_UBLASX_OPERATION_POW_NS_::element_pow); \n\ttypedef signature_result_type(*fun_ptr_type)(signature_argument1_type, signature_argument2_type);\n\tfun_ptr_type ptr_element_pow_fun(&detail::element_pow); \n\treturn expression_type(ve(), p, ptr_element_pow_fun);\n}\n\n\n/**\n * \\brief Applies the \\c std::pow function to a given vector expression,\n *  where each element of the vector is treated as the power of the\n *  exponentiation.\n *\n * \\tparam VectorExprT The type of the input vector expression.\n *\n * \\param b The base.\n * \\param ve The input vector expression.\n * \\return A vector expression representing the application of \\c std::pow to\n *  each element of \\a ve.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename T, typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename detail::vector_element_pow_functor2_traits<T,VectorExprT>::result_type element_pow(T b, vector_expression<VectorExprT> const& ve)\n{\n\ttypedef typename detail::vector_element_pow_functor2_traits<T,VectorExprT>::expression_type expression_type;\n\ttypedef typename detail::vector_element_pow_functor2_traits<T,VectorExprT>::signature_argument1_type signature_argument1_type;\n\ttypedef typename detail::vector_element_pow_functor2_traits<T,VectorExprT>::signature_argument2_type signature_argument2_type;\n\ttypedef typename detail::vector_element_pow_functor2_traits<T,VectorExprT>::signature_result_type signature_result_type;\n\n//\treturn expression_type(ve(), detail::element_pow<signature_result_type>);\n//\tsignature_result_type (*)(ptr_element_pow_fun)(signature_argument_type)(BOOST_NUMERIC_UBLASX_OPERATION_POW_NS_::element_pow); \n\ttypedef signature_result_type(*fun_ptr_type)(signature_argument1_type, signature_argument2_type);\n\tfun_ptr_type ptr_element_pow_fun(&detail::element_pow); \n\treturn expression_type(b, ve(), ptr_element_pow_fun);\n}\n\n\n/**\n * \\brief Applies the \\c std::pow function to a given matrix expression,\n *  where each element of the matrix is treated as the base of the\n *  exponentiation.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param me The input matrix expression.\n * \\param p The exponent.\n * \\return A matrix expression representing the application of \\c std::pow to\n *  each element of \\a me.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename MatrixExprT, typename T>\nBOOST_UBLAS_INLINE\ntypename detail::matrix_element_pow_functor1_traits<MatrixExprT,T>::result_type element_pow(matrix_expression<MatrixExprT> const& me, T p)\n{\n\ttypedef typename detail::matrix_element_pow_functor1_traits<MatrixExprT,T>::expression_type expression_type;\n\ttypedef typename detail::matrix_element_pow_functor1_traits<MatrixExprT,T>::signature_argument1_type signature_argument1_type;\n\ttypedef typename detail::matrix_element_pow_functor1_traits<MatrixExprT,T>::signature_argument2_type signature_argument2_type;\n\ttypedef typename detail::matrix_element_pow_functor1_traits<MatrixExprT,T>::signature_result_type signature_result_type;\n\n//\treturn expression_type(me(), detail::element_pow<signature_result_type>(signature_argument_type));\n\ttypedef signature_result_type(*fun_ptr_type)(signature_argument1_type, signature_argument2_type);\n\tfun_ptr_type ptr_element_pow_fun(&detail::element_pow); \n\treturn expression_type(me(), p, ptr_element_pow_fun);\n}\n\n/**\n * \\brief Applies the \\c std::pow function to a given matrix expression,\n *  where each element of the matrix is treated as the power of the\n *  exponentiation.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param b The base.\n * \\param me The input matrix expression.\n * \\return A matrix expression representing the application of \\c std::pow to\n *  each element of \\a me.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <typename T, typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename detail::matrix_element_pow_functor2_traits<T,MatrixExprT>::result_type element_pow(T b, matrix_expression<MatrixExprT> const& me)\n{\n\ttypedef typename detail::matrix_element_pow_functor2_traits<T,MatrixExprT>::expression_type expression_type;\n\ttypedef typename detail::matrix_element_pow_functor2_traits<T,MatrixExprT>::signature_argument1_type signature_argument1_type;\n\ttypedef typename detail::matrix_element_pow_functor2_traits<T,MatrixExprT>::signature_argument2_type signature_argument2_type;\n\ttypedef typename detail::matrix_element_pow_functor2_traits<T,MatrixExprT>::signature_result_type signature_result_type;\n\n//\treturn expression_type(me(), detail::element_pow<signature_result_type>(signature_argument_type));\n\ttypedef signature_result_type(*fun_ptr_type)(signature_argument1_type, signature_argument2_type);\n\tfun_ptr_type ptr_element_pow_fun(&detail::element_pow); \n\treturn expression_type(b, me(), ptr_element_pow_fun);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_ELEMENT_POW_HPP\n", "meta": {"hexsha": "a32c65b078c6b9d7b190b15f5c888b84dee35b45", "size": 11005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/element_pow.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/ublasx/operation/element_pow.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/ublasx/operation/element_pow.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0634328358, "max_line_length": 138, "alphanum_fraction": 0.8166288051, "num_tokens": 2483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6014463772574397}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_SDK_MEMORY_META_NEXT_POWER_OF_2_HPP_INCLUDED\n#define NT2_SDK_MEMORY_META_NEXT_POWER_OF_2_HPP_INCLUDED\n\n#include <cstddef>\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/integral_c.hpp>\n\nnamespace nt2 { namespace details\n{\n  template<std::size_t N> struct next_power_of_2_impl\n  {\n    BOOST_STATIC_CONSTANT(std::size_t, x0    = N-1            );\n    BOOST_STATIC_CONSTANT(std::size_t, x1    = x0 | (x0 >> 1) );\n    BOOST_STATIC_CONSTANT(std::size_t, x2    = x1 | (x1 >> 1) );\n    BOOST_STATIC_CONSTANT(std::size_t, x3    = x2 | (x2 >> 1) );\n    BOOST_STATIC_CONSTANT(std::size_t, x4    = x3 | (x3 >> 1) );\n    BOOST_STATIC_CONSTANT(std::size_t, x5    = x4 | (x4 >> 1) );\n    BOOST_STATIC_CONSTANT(std::size_t, value = x5 + 1         );\n  };\n} }\n\nnamespace nt2 { namespace meta\n{\n  //////////////////////////////////////////////////////////////////////////////\n  // Boolean meta-function computing the power of 2 greater or equal to any\n  // integral constant.\n  // Documentation: next_power_of_2_c.rst\n  //////////////////////////////////////////////////////////////////////////////\n  template<std::size_t N>\n  struct  next_power_of_2_c\n        : boost::mpl::size_t<details::next_power_of_2_impl<N>::value> {};\n\n  //////////////////////////////////////////////////////////////////////////////\n  // Boolean meta-function computing the power of 2 greater or equal to any\n  // Integral Constant.\n  // Documentation: next_power_of_2.rst\n  //////////////////////////////////////////////////////////////////////////////\n  template<class N>\n  struct  next_power_of_2\n        : boost::mpl::integral_c< typename N::value_type\n                                , next_power_of_2_c<N::value>::value\n                                > {};\n} }\n\n\n#endif\n", "meta": {"hexsha": "daa75fec60c6eafe833d98d584302798f60d1005", "size": 2259, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/sdk/include/nt2/sdk/memory/meta/next_power_of_2.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/sdk/include/nt2/sdk/memory/meta/next_power_of_2.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/sdk/include/nt2/sdk/memory/meta/next_power_of_2.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0727272727, "max_line_length": 80, "alphanum_fraction": 0.5108455069, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6014463762699074}}
{"text": "#include \"tile/math/matrix.h\"\n\n#include <algorithm>\n#include <set>\n#include <string>\n#include <utility>\n\n#include <boost/format.hpp>\n\n#include \"base/util/compat.h\"\n\nnamespace vertexai {\nnamespace tile {\nnamespace math {\n\nstruct DualMatrix {\n  size_t size_;\n  Matrix lhs_;\n  Matrix rhs_;\n\n  explicit DualMatrix(const Matrix& m) : size_(m.size1()), lhs_(IdentityMatrix(size_)), rhs_(m) {}\n\n  void swapRows(size_t r1, size_t r2) {\n    lhs_.swapRows(r1, r2);\n    rhs_.swapRows(r1, r2);\n  }\n  void multRow(size_t r, Rational v) {\n    lhs_.multRow(r, v);\n    rhs_.multRow(r, v);\n  }\n  void addMultRow(size_t d, size_t s, Rational v) {\n    lhs_.addRowMultToRow(d, s, v);\n    rhs_.addRowMultToRow(d, s, v);\n  }\n\n  std::string toString() const {\n    std::string r = \"\";\n    for (size_t i = 0; i < size_; i++) {\n      for (size_t j = 0; j < size_; j++) {\n        r += str(boost::format(\"%4s, \") % to_string(lhs_(i, j)));\n      }\n      r += \"      \";\n      for (size_t j = 0; j < size_; j++) {\n        r += str(boost::format(\"%4s, \") % to_string(rhs_(i, j)));\n      }\n      r += \"\\n\";\n    }\n    return r;\n  }\n\n  // Do elimination, returns false if singular\n  bool invert() {\n    // First zero the lower triangle of the RHS\n    for (size_t i = 0; i < size_; i++) {\n      // Pivot first to non-zero entry in diagonal\n      bool found_nonzero = false;\n      for (size_t j = i; j < size_; j++) {\n        if (rhs_(j, i) != 0) {\n          found_nonzero = true;\n          swapRows(i, j);\n          break;\n        }\n      }\n      if (!found_nonzero) {\n        return false;\n      }\n      // Divide row to make (i, i) == 1\n      multRow(i, 1 / rhs_(i, i));\n      // Zero this column all the way down\n      for (size_t j = i + 1; j < size_; j++) {\n        addMultRow(j, i, -rhs_(j, i));\n      }\n    }\n    // Now, zero the upper triangle of the RHS\n    for (ssize_t i = size_ - 1; i >= ssize_t(0); i--) {\n      // Zero this column all the way up\n      for (ssize_t j = i - 1; j >= ssize_t(0); j--) {\n        addMultRow(j, i, -rhs_(j, i));\n      }\n    }\n    return true;\n  }\n};\n\nvoid Matrix::swapRows(size_t r, size_t s) {\n  for (size_t i = 0; i < size2(); i++) {\n    std::swap((*this)(r, i), (*this)(s, i));\n  }\n}\n\nvoid Matrix::multRow(size_t r, Rational multiplier) {\n  for (size_t i = 0; i < size2(); i++) {\n    (*this)(r, i) *= multiplier;\n  }\n}\n\nvoid Matrix::addRowMultToRow(size_t dest_row, size_t src_row, const Rational& multiplier) {\n  if (multiplier != 0) {\n    for (size_t i = 0; i < size2(); i++) {\n      (*this)(dest_row, i) += multiplier * (*this)(src_row, i);\n    }\n  }\n}\n\nvoid Matrix::makePivotAt(size_t row, size_t col) {\n  if ((*this)(row, col) == 0) {\n    throw std::runtime_error(\"Cannot pivot matrix at entry containing 0\");\n  }\n  for (size_t r = 0; r < size1(); ++r) {\n    if (r == row) {\n      continue;\n    }\n    addRowMultToRow(r, row, -(*this)(r, col) / (*this)(row, col));\n  }\n  multRow(row, 1 / (*this)(row, col));\n}\n\nbool Matrix::invert() {\n  if (size1() != size2()) {\n    throw std::runtime_error(\"Trying to invert non-square matrix\");\n  }\n  DualMatrix dm(*this);\n  if (!dm.invert()) {\n    return false;\n  }\n  *this = dm.lhs_;\n  return true;\n}\n\nstd::string Matrix::toString() const {\n  std::string ret;\n  ret += \"\\n\";\n  for (size_t i = 0; i < size1(); ++i) {\n    ret += \"[ \";\n    for (size_t j = 0; j < size2(); ++j) {\n      ret += ((*this)(i, j)).str() + \"\\t\";\n    }\n    ret += \"]\\n\";\n  }\n  return ret;\n}\n\nbool Matrix::operator==(const Matrix& m) {\n  if (size1() != m.size1()) {\n    return false;\n  }\n  if (size2() != m.size2()) {\n    return false;\n  }\n  for (size_t i = 0; i < size1(); i++) {\n    for (size_t j = 0; j < size2(); j++) {\n      if ((*this)(i, j) != m(i, j)) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\nVector VectorLit(const std::vector<Rational>& vec) {\n  Vector r(vec.size());\n  for (size_t i = 0; i < vec.size(); i++) {\n    r(i) = vec[i];\n  }\n  return r;\n}\n\nMatrix MatrixLit(const std::vector<std::vector<Rational>>& vecs) {\n  size_t rows = vecs.size();\n  size_t columns = vecs[0].size();\n  Matrix r(rows, columns);\n  for (size_t i = 0; i < rows; i++) {\n    if (vecs[i].size() != columns) {\n      throw std::runtime_error(\"Non-rectangular matrix literal\");\n    }\n    for (size_t j = 0; j < columns; j++) {\n      r(i, j) = vecs[i][j];\n    }\n  }\n  return r;\n}\n\nbool operator==(const Vector& a, const Vector& b) {\n  if (a.size() != b.size()) {\n    return false;\n  }\n  for (size_t i = 0; i < a.size(); i++) {\n    if (a(i) != b(i)) {\n      return false;\n    }\n  }\n  return true;\n}\n\nstd::tuple<Matrix, Vector> FromPolynomials(const std::vector<Polynomial<Rational>>& polys) {\n  std::set<std::string> vars;\n  for (size_t i = 0; i < polys.size(); i++) {\n    for (const auto& kvp : polys[i].getMap()) {\n      if (kvp.first != \"\") {\n        vars.insert(kvp.first);\n      }\n    }\n  }\n  Matrix mat(polys.size(), vars.size());\n  Vector vec(polys.size());\n  for (size_t i = 0; i < polys.size(); i++) {\n    vec(i) = polys[i].constant();\n    size_t j = 0;\n    for (const auto& v : vars) {\n      mat(i, j) = polys[i][v];\n      j++;\n    }\n  }\n  return std::tie(mat, vec);\n}\n\nstruct HermiteCompute {\n  size_t rows_;\n  size_t columns_;\n  Matrix lhs_;\n\n  void swap(size_t i, size_t j) { lhs_.swapRows(i, j); }\n\n  void mult(size_t i, Integer m) {\n    if (m != 1 && m != -1) {\n      throw std::runtime_error(\"Cannot multiply row by nonunit constant in computing HNF.\");\n    }\n    lhs_.multRow(i, m);\n  }\n\n  void addMult(size_t d, size_t s, Integer m) {\n    IVLOG(6, \"  Adding \" << m << \" * row \" << s << \" to row \" << d);\n    lhs_.addRowMultToRow(d, s, m);\n  }\n\n  void eliminate(size_t i, size_t j) {\n    IVLOG(5, \"    Eliminate \" << i << \", \" << j);\n    if (lhs_(j, i) == 0) {\n      IVLOG(5, \"      Already 0, nothing to do\");\n      return;\n    }\n    Integer x, y;\n    IVLOG(5, \"      Computing XGCD of \" << lhs_(i, i) << \" and \" << lhs_(j, i));\n    Rational o = XGCD(lhs_(i, i), lhs_(j, i), x, y);\n    IVLOG(5, \"o = \" << o << \", x = \" << x << \", y = \" << y);\n    if (Abs(o) != lhs_(i, i)) {\n      if (Abs(o) == Abs(lhs_(j, i))) {\n        IVLOG(5, \"      Swapping entry\");\n        swap(i, j);\n        if (lhs_(i, i) < 0) {\n          mult(i, -1);\n        }\n      } else {\n        IVLOG(5, \"      Updating entry\");\n        euclidean_reduce(i, j, i);\n      }\n    }\n    Rational m = numerator(-lhs_(j, i) / o);\n    IVLOG(5, \"  m = \" << m);\n    addMult(j, i, numerator(-lhs_(j, i) / o));\n  }\n\n  void euclidean_reduce(size_t i, size_t j, size_t col) {\n    Rational a = lhs_(i, col);\n    Rational b = lhs_(j, col);\n    if (a < 0) {\n      a = -a;\n      IVLOG(5, \"    Negating row \" << i)\n      mult(i, -1);\n      IVLOG(6, \"  state\\n\" << toString());\n    }\n    if (b < 0) {\n      b = -b;\n      IVLOG(5, \"    Negating row \" << j)\n      mult(j, -1);\n      IVLOG(6, \"  state\\n\" << toString());\n    }\n    if (a < b) {\n      swap(i, j);\n      IVLOG(6, \"  state\\n\" << toString());\n      a = lhs_(i, col);\n      b = lhs_(j, col);\n    }\n\n    // Main Euclidean algorithm\n    Rational r;\n    Integer q = RatDiv(a, b, r);\n    IVLOG(6, \"Quotient \" << q << \", Remainder \" << r);\n    while (true) {\n      addMult(i, j, -q);\n      swap(i, j);\n      IVLOG(6, \"  a = \" << a << \", b = \" << b << \", state\\n\" << toString());\n      if (r == 0) {\n        IVLOG(6, \"Remainder 0, stopping\");\n        break;\n      }\n      a = b;\n      b = r;\n      q = RatDiv(a, b, r);\n      IVLOG(6, \"Quotient \" << q << \", Remainder \" << r);\n    }\n  }\n\n  void normalize(size_t i, size_t j) {\n    Integer m = -Floor(lhs_(j, i) / lhs_(i, i));\n    addMult(j, i, m);\n  }\n\n  std::string toString() {\n    std::stringstream ss;\n    for (size_t i = 0; i < rows_; i++) {\n      for (size_t j = 0; j < columns_; j++) {\n        ss << lhs_(i, j).str() << \" \";\n      }\n    }\n    return ss.str();\n  }\n\n public:\n  explicit HermiteCompute(const Matrix& m) : rows_(m.size1()), columns_(m.size2()), lhs_(m) {}\n\n  bool compute() {\n    if (rows_ < columns_) {\n      return false;\n    }\n    IVLOG(4, \"Computing HNF, initial state\\n\" << toString());\n    // TODO(T132): Technically, this ordering of the algorithm may be\n    // exponential in the bit representation of the rational numbers\n    // There is a polynomial time version, but the pivoting is tricker\n    // so I'm skipping it for now.\n    for (size_t i = 0; i < columns_; i++) {\n      IVLOG(5, \"Fixing column \" << i);\n      IVLOG(5, \"  state\\n\" << toString());\n      // First, we need to position (i, i) with a non-zero entry if possible\n      for (size_t j = i; j < rows_; j++) {\n        if (lhs_(j, i) != 0) {\n          IVLOG(5, \"  Swapping \" << i << \" and \" << j);\n          swap(i, j);\n          IVLOG(6, \"  state\\n\" << toString());\n          break;\n        }\n      }\n      // If they are all zeros, whatevs, on to the next column\n      if (lhs_(i, i) == 0) {\n        IVLOG(5, \"  Skipping due to zeros\");\n        continue;\n      }\n      // Otherwise, fix sign and combine with all rows below\n      if (lhs_(i, i) < 0) {\n        IVLOG(6, \" Multiplying \" << i << \" by -1\");\n        mult(i, -1);\n        IVLOG(6, \"  state\\n\" << toString());\n      }\n      for (size_t j = i + 1; j < rows_; j++) {\n        eliminate(i, j);\n        IVLOG(6, \"  state\\n\" << toString());\n      }\n      // And normalize all rows above\n      for (size_t j = 0; j < i; j++) {\n        normalize(i, j);\n        IVLOG(6, \"  state\\n\" << toString());\n      }\n    }\n    IVLOG(4, \"Final state\\n\" << toString());\n    return true;\n  }\n};\n\nbool HermiteNormalForm(Matrix& m) {  // NOLINT(runtime/references)\n  HermiteCompute hc(m);\n  bool r = hc.compute();\n  m = hc.lhs_;\n  return r;\n}\n\n}  // namespace math\n}  // namespace tile\n}  // namespace vertexai\n", "meta": {"hexsha": "d39ffd877b957c293881e4e7c76c3d9c630eb525", "size": 9626, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tile/math/matrix.cc", "max_stars_repo_name": "redoclag/plaidml", "max_stars_repo_head_hexsha": "46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4535.0, "max_stars_repo_stars_event_min_datetime": "2017-10-20T05:03:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:42:33.000Z", "max_issues_repo_path": "tile/math/matrix.cc", "max_issues_repo_name": "HOZHENWAI/plaidml", "max_issues_repo_head_hexsha": "46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 984.0, "max_issues_repo_issues_event_min_datetime": "2017-10-20T17:16:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:43:18.000Z", "max_forks_repo_path": "tile/math/matrix.cc", "max_forks_repo_name": "HOZHENWAI/plaidml", "max_forks_repo_head_hexsha": "46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 492.0, "max_forks_repo_forks_event_min_datetime": "2017-10-20T18:22:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T09:00:05.000Z", "avg_line_length": 25.3984168865, "max_line_length": 98, "alphanum_fraction": 0.506025348, "num_tokens": 3146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6014463712822938}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include \"LR.hpp\"\n#include \"Adadelta.hpp\"\n#include \"Adagrad.hpp\"\n#include \"Adam.hpp\"\n\n\n\n#define EIGEN_MPL2_ONLY\nusing namespace Eigen;\nusing namespace std;\n\nvoid read(string filepath, MatrixXd& x,VectorXd& l){\n  ifstream ifs(filepath);\n  if(ifs.fail()){\n    cerr << \"File do not exist.\"<<endl;\n    exit(0);\n  }\n  string s;\n  int index = 0;\n  while(getline(ifs,s)){\n    stringstream ss(s);\n    int t;\n    ss>>t;\n    if(t>0){\n      l(index) = 1;\n    }else{\n      l(index) = 0;\n    }\n    string feature;\n    while(ss>>feature){\n      string::size_type idx = feature.find(\":\");\n      int n = atoi(feature.substr(0,idx).c_str());\n      double value = atof(feature.substr(idx+1).c_str());\n      x(index,n-1) = value;\n    }\n    ++index;\n  }\n}\n\nint main()\n{\n  MatrixXd x = MatrixXd::Zero(32561,123);\n  VectorXd label(32561);\n  MatrixXd x_test = MatrixXd::Zero(16281,123);\n  VectorXd label_test(16281);\n  int iteration = 250;\n  read(\"a9a\",x,label);\n  read(\"a9a.t\",x_test,label_test);\n  // LR lr = LR(x.rows(),x.cols(),x,label,0.01,0.1,iteration);\n  // lr.train();\n  // vector<double> scores;\n  // lr.predict(x_test,label_test,scores);\n  // cout<<\"=== LR ===\"<<endl;\n  // cout <<\"Accuracy:\"<< lr.Acc(scores,label_test) <<endl;\n  \n  // ofstream iofs(\"iters.txt\");\n  // for(double d : lr.iterscores){\n  //   iofs<<d<<endl;\n  // }\n\n  // ofstream wofs(\"weight.txt\");\n  // for(int i = 0; i< lr.w.rows();i++){\n  //   wofs<<lr.w(i)<<endl;\n  // }\n\n  Adam adam = Adam(x.rows(),x.cols(),x,label,0.01,0.002,0.1,0.001,0.000000001,0.00000001,iteration);\n  adam.train();\n  vector<double> adamscores;\n  adam.predict(x_test,label_test,adamscores);\n  cout<<\"=== Adam ===\"<<endl;\n  cout <<\"Accuracy:\"<< adam.Acc(adamscores,label_test) <<endl;\n\n  ofstream adamiofs(\"adamiters.txt\");\n  for(double d : adam.iterscores){\n    adamiofs<<d<<endl;\n  }\n\n  ofstream adamwofs(\"adamweight.txt\");\n  for(int i = 0; i< adam.w.rows();i++){\n    adamwofs<<adam.w(i)<<endl;\n  }\n  \n\n  // Adadelta addlr = Adadelta(x.rows(),x.cols(),x,label,0.01,0.95,0.0000001,iteration);\n  // addlr.train();\n  // vector<double> addscores;\n  // addlr.predict(x_test,label_test,addscores);\n  // cout<<\"=== Adadelta==\"<<endl;\n  // cout <<\"Accuracy:\"<< lr.Acc(addscores,label_test) <<endl;\n  \n  // ofstream addiofs(\"adadelta_iters.txt\");\n  // for(double d : addlr.iterscores){\n  //   addiofs<<d<<endl;\n  // }\n\n  // ofstream addwofs(\"adadelta_weight.txt\");\n  // for(int i = 0; i< addlr.w.rows();i++){\n  //   addwofs<<lr.w(i)<<endl;\n  // }\n  \n  // Adagrad adglr = Adagrad(x.rows(),x.cols(),x,label,0.01,0.1,iteration);\n  // adglr.train();\n  // vector<double> adgscores;\n  \n  // adglr.predict(x_test,label_test,adgscores);\n  // cout<<\"=== Adagrad ===\"<<endl;\n  // cout <<\"Accuracy:\"<< adglr.Acc(adgscores,label_test) <<endl;\n  \n  // ofstream adgiofs(\"adagrad_iters.txt\");\n  // for(double d : adglr.iterscores){\n  //   adgiofs<<d<<endl;\n  // }\n\n  // ofstream adgwofs(\"adagrad_weight.txt\");\n  // for(int i = 0; i< adglr.w.rows();i++){\n  //   adgwofs<<adglr.w(i)<<endl;\n  // }  \n}\n", "meta": {"hexsha": "d16110ffd69dfb31ef830cdc3f8cc11a55ac4049", "size": 3126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sample.cpp", "max_stars_repo_name": "saiias/Adadelta", "max_stars_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-08-27T10:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T07:42:49.000Z", "max_issues_repo_path": "sample.cpp", "max_issues_repo_name": "huangpingchun/Adadelta", "max_issues_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-02-20T12:33:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-23T08:12:09.000Z", "max_forks_repo_path": "sample.cpp", "max_forks_repo_name": "huangpingchun/Adadelta", "max_forks_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-08-27T10:49:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-08T08:36:07.000Z", "avg_line_length": 25.008, "max_line_length": 100, "alphanum_fraction": 0.6007677543, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.6014349741704048}}
{"text": "#include <NTL/ZZ.h>\n#include <cstdint>\n#include <cmath>\n\n#define NUM_BITS_REAL_MANTISSA 54\n\n#include \"binomials.hpp\"\n#include <cmath>\n\nint main(int argc, char* argv[]){\n  if(argc < 5){\n     std::cout << \"Complexity estimation of key enumeration\" << std::endl << \" Usage \" \n               << argv[0] << \" <p> <d_v> <n_0> <m_0> <m_1> <m_2> <m_3>\" << std::endl << \n               \"All the non existing m_i should be passed as zeroes \" << std::endl;\n    return -1;\n  }\n\n  InitBinomials();\n  NTL::RR::SetPrecision(NUM_BITS_REAL_MANTISSA);\n  pi = NTL::ComputePi_RR();\n  uint32_t p = atoi(argv[1]);\n  uint32_t d_v = atoi(argv[2]);\n  uint32_t n_0 = atoi(argv[3]);\n  uint32_t m[4];\n  m[0] = atoi(argv[4]);\n  m[1] = atoi(argv[5]);\n  m[2] = atoi(argv[6]);\n  m[3] = atoi(argv[7]);\n\n  NTL::RR Henum, Qenum;\n\n  Henum = lnBinom(NTL::RR(p),NTL::RR(d_v));\n  Henum = Henum*NTL::RR(n_0) / NTL::log(NTL::RR(2));\n\n  Qenum = NTL::RR(n_0)* ( lnBinom(NTL::RR(p),NTL::RR(m[0])) +\n                          lnBinom(NTL::RR(p),NTL::RR(m[1])) +\n                          lnBinom(NTL::RR(p),NTL::RR(m[2])) +\n                          lnBinom(NTL::RR(p),NTL::RR(m[3])) )/ NTL::log(NTL::RR(2));\n\n  std::cout << \"H enum classic/quantum cost :\" << Henum << \"  \" << (Henum/NTL::RR(2)) << std::endl;\n  std::cout << \"Q enum classic/quantum cost :\" << Qenum << \"  \" << (Qenum/NTL::RR(2)) << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "7bf0a0bbc9ec855b6f1dab7787f7cb2951ff12f9", "size": 1379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enumeration_complexity.cpp", "max_stars_repo_name": "alexrow/LEDAtools", "max_stars_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "enumeration_complexity.cpp", "max_issues_repo_name": "alexrow/LEDAtools", "max_issues_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "enumeration_complexity.cpp", "max_forks_repo_name": "alexrow/LEDAtools", "max_forks_repo_head_hexsha": "f847707833650706519cc57f5956b8e1a17a157c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-12T09:12:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-12T09:12:30.000Z", "avg_line_length": 31.3409090909, "max_line_length": 99, "alphanum_fraction": 0.5373459028, "num_tokens": 516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.601404550484348}}
{"text": "#ifndef ALGORITHM_DP_PATH_FINDER_HPP_2T9GR5EG\n#define ALGORITHM_DP_PATH_FINDER_HPP_2T9GR5EG\n\n#include <stdlib.h>\n#include <fstream>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n#include <log4cxx/logger.h>\n#include <log4cxx/basicconfigurator.h>\n#include <log4cxx/helpers/exception.h>\n#include \"image.hpp\"\n#include <opencv2/core/core.hpp>\n\n\n//namespace std {using namespace __gnu_cxx;}\nusing namespace std;\n\nnamespace prhlt {\n\n    class Algorithm_DP_Path_Finder\n    {\n        public:\n            Algorithm_DP_Path_Finder(cv::Mat ex_image_mat, const Eigen::MatrixXd& ex_cost_matrix);\n            Algorithm_DP_Path_Finder(cv::Mat ex_image_mat, const Eigen::MatrixXd& ex_cost_matrix, cv::Rect ex_search_area );\n            Algorithm_DP_Path_Finder(cv::Mat ex_image_mat, const Eigen::MatrixXd& ex_cost_matrix,int orig_x, int orig_y , int size_x, int size_y);\n            ~Algorithm_DP_Path_Finder();\n            void run(double ex_alpha, double ex_beta);\n            void set_search_limits(vector < vector <cv::Point> > ex_upper_limits, vector < vector <cv::Point> > ex_lower_limits);\n            void set_lower_search_limits(vector < vector <cv::Point> > ex_lower_limits);\n            void set_upper_search_limits(vector < vector <cv::Point> > ex_lower_limits);\n            void set_search_limits(vector <cv::Point> ex_upper_limits, vector <cv::Point> ex_lower_limits);\n            void set_lower_search_limits(vector <cv::Point> ex_lower_limits);\n            void set_upper_search_limits(vector <cv::Point> ex_lower_limits);\n            vector<cv::Point2d> recover_path(int x, int y);\n            vector< vector<cv::Point2d> > recover_all_paths();\n            vector<cv::Point2d> recover_best_path();\n            vector<cv::Point2d> get_best_path_collision_points();\n            void save_path_matrix_to_file(string file_name);\n        private:\n            //GENERAL\n            void forward();\n            void backward();\n            void reset_change_counter();\n            bool solution_not_converged();\n            void show_search_area();\n\n            //INITIALIZATION\n            void initialize_bound_matrix();\n            //PATH MANAGEMENT FUNCTIONS\n            void update_column(int c);\n            void update_cell(int x , int y);\n            bool update_cell_from(int from_x, int from_y, int to_x , int to_y);\n            void review_column(int c);\n            bool review_cell(int x , int y);\n            void backtrack_column(int c);\n            bool backtrack_cell(int x , int y);\n            bool update_bound_matrix(int x, int y, double cost);\n            void update_path_matrix(int x, int y, int from_x, int from_y);\n            void display_path(int x, int y);\n            void display_best_path();\n            void save_best_path();\n            bool is_collision_point(vector<cv::Point2d> points, int index );\n            cv::Point2d localize_point(cv::Point2d point);\n            cv::Point2d localize_point(int x , int y);\n\n\n            //vector<cv::Point2d> recover_all_paths();\n            //COST FUNCTIONS\n            double base_movement_cost(int from_x, int from_y, int to_x, int to_y);\n            double contextual_average(int x, int y, int context_size);\n            double future_contextual_average(int x, int y,const int x_context_size, const int y_context_size);\n\t\t\tvoid calculate_valid_search_area();\n            bool precalc_is_valid_point_as_per_search_limits(int x, int y);\n            bool is_valid_point_as_per_search_limits(int x, int y);\n            int point_position_in_respect_to_line(vector<cv:: Point> ex_line, int x, int y);\n            bool restriction_segment_applicable_to_point(vector<cv:: Point> ex_line, int x, int y);\n            //DATA\n\t\t    int axis_x;\n\t\t    int axis_y;\n    \t\tint cells_changed;\n\t\t    double alpha;\n\t\t    double beta;\n\t\t    double average_euclidian_distance_cost;\n\t\t    double average_grey_distance_cost;\n\t\t    Image image;\n\t\t    double roof_distance;\n        vector < vector <cv::Point> > upper_search_limits;\n        vector < vector <cv::Point> > lower_search_limits;\n            Eigen::MatrixXd cost_matrix;\n            Eigen::MatrixXd bound_matrix;\n            Eigen::MatrixXi limits_matrix;\n            Eigen::MatrixXi path_matrix_x;\n            Eigen::MatrixXi path_matrix_y;\n            log4cxx::LoggerPtr logger;\n    };\n\n}\n\n\n#endif /* end of include guard: ALGORITHM_PATH_FINDER_HPP_2T9GR5EG */\n", "meta": {"hexsha": "a506ebed5d771b6e0e500f730a401235bc7be183", "size": 4390, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "algorithm_dp_path_finder.hpp", "max_stars_repo_name": "jkloe/pageDistanceBasedContourGenerator", "max_stars_repo_head_hexsha": "92e8768b596c98ffc09f4b5eeb7db8aafccda01a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-03-06T23:54:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-24T09:18:33.000Z", "max_issues_repo_path": "algorithm_dp_path_finder.hpp", "max_issues_repo_name": "jkloe/pageDistanceBasedContourGenerator", "max_issues_repo_head_hexsha": "92e8768b596c98ffc09f4b5eeb7db8aafccda01a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T00:31:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-10T13:28:41.000Z", "max_forks_repo_path": "algorithm_dp_path_finder.hpp", "max_forks_repo_name": "jkloe/pageDistanceBasedContourGenerator", "max_forks_repo_head_hexsha": "92e8768b596c98ffc09f4b5eeb7db8aafccda01a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-03-07T00:08:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-13T12:14:08.000Z", "avg_line_length": 43.0392156863, "max_line_length": 146, "alphanum_fraction": 0.6553530752, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699433, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.601404546868202}}
{"text": "#include <opengv/optimization_tools/objective_function_tools/ObjectiveFunctionInfo.hpp>\n#include <opengv/optimization_tools/solver_tools/SolverToolsNoncentralRelativePose.hpp>\n#include <Eigen/Dense>\n#include <opengv/types.hpp>\n#include <iostream>\n\n\nEigen::Matrix3d SolverToolsNoncentralRelativePose::exp_R( Eigen::Matrix3d & X ){\n  double phi = X.norm()/std::sqrt(2);\n  Eigen::Matrix3d X1 = X/phi;\n  Eigen::Matrix3d I = Eigen::Matrix< double, 3, 3 >::Identity();\n  I = I + std::sin(phi)*X1 + ( 1 - std::cos(phi) )*X1*X1;\n  return I;\n}\n\n\nopengv::rotation_t SolverToolsNoncentralRelativePose::rotation_solver(opengv::rotation_t & state_rotation, const opengv::translation_t & translation,\n\t\t\t\t\t\t\t\t      double &tol, ObjectiveFunctionInfo * info_function, int & k){\n  double g = 1.0;\n  double erro = 1.0;\n  k = 0;\n  opengv::rotation_t X = state_rotation;\n  opengv::rotation_t previous_X = Eigen::Matrix3d::Zero(3,3);\n  Eigen::Matrix3d Z  = Eigen::Matrix3d::Zero(3,3);\n  double zz = 0;\n  Eigen::Matrix3d DX = Eigen::Matrix3d::Zero(3,3);\n  Eigen::Matrix3d Pt = Eigen::Matrix3d::Zero(3,3);\n  Eigen::Matrix3d P  = Eigen::Matrix3d::Zero(3,3);\n  Eigen::Matrix3d Q  = Eigen::Matrix3d::Zero(3,3);\n  Eigen::Matrix3d Qt = Eigen::Matrix3d::Zero(3,3);\n  Eigen::Matrix3d reference = Eigen::Matrix3d::Identity(3,3);\n  //std::cout << \"Inside rotation solver to check the values: \" << std::endl;\n  //std::cout << \"Before process starts the rotation matrix is: \" << X << std::endl;\n  \n  while( erro > tol && k < 1e3 )\n    {\n\n      //std::cout << \"state at the beginning: \" << std::endl << X << std::endl << std::endl;\n      DX = info_function->rotation_gradient(X, translation);\n      //std::cout << \"Calculated gradient: \" << std::endl << DX << std::endl << std::endl;\n      Z   = DX*X.transpose() - X*DX.transpose();\n      //std::cout << \"Calculated riemaniann gradient: \" << std::endl << Z << std::endl << std::endl;\n      zz  = 0.5*( Z*Z.transpose() ).trace();\n      //std::cout << \"Coefficient zz : \" << zz << std::endl << std::endl;\n      Pt  = -g*Z;\n      //std::cout << \"Matrix Pt: \" << std::endl << Pt << std::endl << std::endl;\n      P   = exp_R( Pt );\n      //std::cout << \"The rotation matrix P: \" << std::endl << P << std::endl << std::endl;\n      Q   = P*P; // this seems strange\n      //std::cout << \"Matrix Q: \" << std::endl << Q << std::endl << std::endl;\n      Qt  = Q*X;\n      //std::cout << \"Matrix Qt: \" << std::endl << Qt << std::endl << std::endl;\n      //std::cout << \"************************************************************\" << std::endl << std::endl;\n      //std::cout << \"1st CYCLE\" << std::endl << std::endl;\n      \n      //while( ( objective_function( M, X, translation ) - objective_function(M, Qt, translation ) ) >= g*zz  )\n      while( ( info_function->objective_function_value(X, translation ) - info_function->objective_function_value(Qt, translation ) ) >= g*zz  )\n        {\n          g   = 2*g;\n          //In order to prevent NAN's the following restriction is added\n          if(g < 64){\n            //std::cout << \"g: \" << g << std::endl;\n            P   = Q;\n            //std::cout << std::endl << \"New P: \" << std::endl << P << std::endl;\n            Q   = P*P; // this seems strange\n            //std::cout << std::endl << \"New Q: \" << std::endl << Q << std::endl;\n            Qt  = Q*X;\n            //std::cout << std::endl << \"New Qt: \" << std::endl << Qt << std::endl;\n            //std::cout << \"Current value for obj function: \" << objective_function(M, X, translation) << std::endl;\n            //std::cout << \"Current value for new obj function: \" << objective_function(M, Qt, translation ) << std::endl;\n          }\n          else{\n            break;\n          }\n        }\n      //std::cout << \"End of 1st cycle\" << std::endl;\n      //std::cout << \"******************************************************************\" << std::endl;\n      //std::cout << \"**********************************************************************\" << std::endl;\n      //std::cout << \"Enters 2nd cycle: \" << std::endl;\n      Qt = P * X;\n      //while( ( objective_function( M, X, translation ) - objective_function(M, Qt, translation ) ) < 0.5*g*zz)\n      while( ( info_function->objective_function_value( X, translation ) - info_function->objective_function_value( Qt, translation ) ) < 0.5*g*zz)\n        {\n\n          //   if ( f_obj( M, N, X, beta) - f_obj( M, N, Qt, beta ) < tol )\n          //     break;\n\n          g  = 0.5*g;\n          //std::cout << \"New g: \" << std::endl << g << std::endl << std::endl;\n          Pt = -g*Z;\n          //std::cout << \"New Pt: \" << std::endl << Pt << std::endl << std::endl;\n          P  = exp_R( Pt );\n          //In order to prevent NAN's\n          if( (P - reference).norm() < 1e-6){\n            break;\n          }\n          //std::cout << \"New P : \" << std::endl << P << std::endl << std::endl;\n          Qt = P*X;\n          //std::cout << \"New Qt: \" << std::endl << std::endl << Qt << std::endl;\n        }\n      previous_X = X;\n      X    = P*X;\n      erro = ( X - previous_X ).norm();\n      // std::cout << \"Rotation: \"    << std::endl << X << std::endl;\n      /*std::cout << \"inside rotation solver: \" << std::endl;\n      std::cout << \"\\nIteration: \" << k << std::endl;\n      std::cout << \"Rotation: \"    << std::endl << X << std::endl;\n      std::cout << \"Euclidean grad: \" << std::endl << DX << std::endl;\n      std::cout << \"Function value: \" << info_function->objective_function_value(X, translation) << std::endl;*/\n      k++;\n    }\n  return X;\n}\n\n\n\nopengv::translation_t SolverToolsNoncentralRelativePose::translation_solver(const opengv::rotation_t & rotation, opengv::translation_t & translation, double &tol, ObjectiveFunctionInfo * info_function, double & step, int & k){\n\n \n  double error = 1;\n  k = 0;\n  //std::cout << \"Translation gradient: \" << std::endl;\n  opengv::translation_t state = translation;\n  opengv::translation_t grad = info_function->translation_gradient(rotation, state);\n  opengv::translation_t new_state = state - step * grad;\n  //std::cout << \"Beginning of the translation solver: \" << std::endl;\n  //std::cout << \"The rotation used is: \" << std::endl << rotation << std::endl;\n  while (error > tol  && k < 1000){\n    new_state = state - step * grad;\n    double f_obj_current = info_function->objective_function_value(rotation, state);\n    double f_obj_next = info_function->objective_function_value(rotation, new_state);\n\n    /*std::cout << \"current state: \" << std::endl     << state      << std::endl;\n    std::cout << \"new state: \"     << std::endl     << new_state  << std::endl;\n    std::cout << \"f(state): \"      << f_obj_current << std::endl;\n    std::cout << \"f(new_state): \"  << f_obj_next    << std::endl;\n    std::cout << \"gradient:     \"  << std::endl     << grad       << std::endl;\n    std::cout << std::endl         << std::endl     << std::endl;*/\n    if(f_obj_next > f_obj_current){\n      break;\n    }\n    error = std::abs(f_obj_current - f_obj_next);\n    grad = info_function->translation_gradient(rotation, state);\n    \n    state = new_state;\n    k++;\n  }\n  return state;\n}\n\n", "meta": {"hexsha": "f82a30b1e8e5ab09017d116b6b709ec2f1e944c0", "size": 7086, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimization_tools/solver_tools/SolverToolsNoncentralRelativePose.cpp", "max_stars_repo_name": "mateus03/2018AMMPoseSolver", "max_stars_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/optimization_tools/solver_tools/SolverToolsNoncentralRelativePose.cpp", "max_issues_repo_name": "mateus03/2018AMMPoseSolver", "max_issues_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimization_tools/solver_tools/SolverToolsNoncentralRelativePose.cpp", "max_forks_repo_name": "mateus03/2018AMMPoseSolver", "max_forks_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.9271523179, "max_line_length": 226, "alphanum_fraction": 0.5453005927, "num_tokens": 2035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.6014045463576784}}
{"text": "//-----------------------------------------------------------------------------\n// Copyright (c) 2015-2018 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE mitrax sub_matrix\n#include <boost/test/unit_test.hpp>\n\n#include <mitrax/sub_matrix.hpp>\n\n\nusing namespace mitrax;\nusing namespace mitrax::literals;\n\n\ntemplate < typename T >\nauto rt_id(T&& v){\n\treturn boost::typeindex::type_id_runtime(static_cast< T&& >(v));\n}\n\ntemplate < typename T >\nauto const id = boost::typeindex::type_id< T >();\n\n\nusing point_t = point_t;\n\n\nconstexpr int org[3][3] = {\n\t{0, 1, 2},\n\t{3, 4, 5},\n\t{6, 7, 8}\n};\n\n\nconstexpr auto m(){\n\treturn make_matrix(3_CS, 3_RS, org);\n}\n\n\ntemplate < typename M >\nconstexpr bool check1(M const& m){\n\treturn\n\t\tm.cols() == 2_CS &&\n\t\tm.rows() == 2_RS &&\n\t\tm(0_c, 0_r) == 0 &&\n\t\tm(1_c, 0_r) == 1 &&\n\t\tm(0_c, 1_r) == 3 &&\n\t\tm(1_c, 1_r) == 4;\n}\n\ntemplate < typename M >\nconstexpr bool check2(M const& m){\n\treturn\n\t\tm.cols() == 2_CS &&\n\t\tm.rows() == 2_RS &&\n\t\tm(0_c, 0_r) == 1 &&\n\t\tm(1_c, 0_r) == 2 &&\n\t\tm(0_c, 1_r) == 4 &&\n\t\tm(1_c, 1_r) == 5;\n}\n\ntemplate < typename M >\nconstexpr bool check3(M const& m){\n\treturn\n\t\tm.cols() == 2_CS &&\n\t\tm.rows() == 2_RS &&\n\t\tm(0_c, 0_r) == 3 &&\n\t\tm(1_c, 0_r) == 4 &&\n\t\tm(0_c, 1_r) == 6 &&\n\t\tm(1_c, 1_r) == 7;\n}\n\ntemplate < typename M >\nconstexpr bool check4(M const& m){\n\treturn\n\t\tm.cols() == 2_CS &&\n\t\tm.rows() == 2_RS &&\n\t\tm(0_c, 0_r) == 4 &&\n\t\tm(1_c, 0_r) == 5 &&\n\t\tm(0_c, 1_r) == 7 &&\n\t\tm(1_c, 1_r) == 8;\n}\n\n\n// TODO: add more unit tests\n// TODO: check also for result types\n// TODO: check move version and const/non-const versions\n// TODO: use non square matrices\n\n\nBOOST_AUTO_TEST_SUITE(suite_sub_matrix)\n\n\nBOOST_AUTO_TEST_CASE(test_sub_matrix_3x3){\n\tconstexpr auto m = make_matrix(3_CS, 3_RS, org);\n\n\tconstexpr auto sub1 = sub_matrix(m, 0_c, 0_r, 2_CS, 2_RS);\n\tauto type1 = id< std_matrix< int, 2_C, 2_R > >;\n\tBOOST_TEST(rt_id(sub1) == type1);\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CS, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CD, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CS, 2_RD)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CD, 2_RD)));\n\n\n\tconstexpr auto sub2 = sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RS));\n\tauto type2 = id< std_matrix< int, 2_C, 2_R > >;\n\tBOOST_TEST(rt_id(sub2) == type2);\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CS, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CD, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CS, 2_RD))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CD, 2_RD))));\n\n\tconstexpr auto sub3 = sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RS);\n\tauto type3 = id< std_matrix< int, 2_C, 2_R > >;\n\tBOOST_TEST(rt_id(sub3) == type3);\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CS, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CD, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CS, 2_RD)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CD, 2_RD)));\n\n\n\tconstexpr auto sub4 = sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RS));\n\tauto type4 = id< std_matrix< int, 2_C, 2_R > >;\n\tBOOST_TEST(rt_id(sub4) == type4);\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CS, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CD, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CS, 2_RD))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CD, 2_RD))));\n}\n\nBOOST_AUTO_TEST_CASE(test_sub_matrix_3x3_move){\n\tconstexpr auto sub1 = sub_matrix(m(), 0_c, 0_r, 2_CS, 2_RS);\n\tauto type1 = id< std_matrix< int, 2_C, 2_R > >;\n\tBOOST_TEST(rt_id(sub1) == type1);\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CD, 2_RD)));\n\n\tconstexpr auto sub2 = sub_matrix(m(), 0_c, 0_r, dim_pair(2_CS, 2_RS));\n\tauto type2 = id< std_matrix< int, 2_C, 2_R > >;\n\tBOOST_TEST(rt_id(sub2) == type2);\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CD, 2_RD))));\n\n\tconstexpr auto sub3 = sub_matrix(m(), point_t(0_c, 0_r), 2_CS, 2_RS);\n\tauto type3 = id< std_matrix< int, 2_C, 2_R > >;\n\tBOOST_TEST(rt_id(sub3) == type3);\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CD, 2_RD)));\n\n\tconstexpr auto sub4 = sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CS, 2_RS));\n\tauto type4 = id< std_matrix< int, 2_C, 2_R > >;\n\tBOOST_TEST(rt_id(sub4) == type4);\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CD, 2_RD))));\n}\n\nBOOST_AUTO_TEST_CASE(test_sub_matrix_3rtx3){\n\tauto m = make_matrix(3_CD, 3_RS, org);\n\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CS, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CD, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CS, 2_RD)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CS, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CD, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CS, 2_RD))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CD, 2_RD))));\n\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CS, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CD, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CS, 2_RD)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CS, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CD, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CS, 2_RD))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CD, 2_RD))));\n}\n\nBOOST_AUTO_TEST_CASE(test_sub_matrix_3rtx3_move){\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CD, 2_RD))));\n\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CD, 2_RD))));\n}\n\nBOOST_AUTO_TEST_CASE(test_sub_matrix_3x3rt){\n\tauto m = make_matrix(3_CS, 3_RD, org);\n\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CS, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CD, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CS, 2_RD)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CS, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CD, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CS, 2_RD))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CD, 2_RD))));\n\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CS, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CD, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CS, 2_RD)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CS, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CD, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CS, 2_RD))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CD, 2_RD))));\n}\n\nBOOST_AUTO_TEST_CASE(test_sub_matrix_3x3rt_move){\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CD, 2_RD))));\n\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CD, 2_RD))));\n}\n\nBOOST_AUTO_TEST_CASE(test_sub_matrix_3rtx3rt){\n\tauto m = make_matrix(3_CD, 3_RD, org);\n\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CS, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CD, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CS, 2_RD)));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, 2_CD, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CS, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CD, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CS, 2_RD))));\n\n\tBOOST_TEST(check1(sub_matrix(m, 0_c, 0_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, 1_c, 0_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, 0_c, 1_r, dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, 1_c, 1_r, dim_pair(2_CD, 2_RD))));\n\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CS, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CD, 2_RS)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CS, 2_RD)));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), 2_CD, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CS, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CD, 2_RS))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CS, 2_RD))));\n\n\tBOOST_TEST(check1(sub_matrix(m, point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check2(sub_matrix(m, point_t(1_c, 0_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check3(sub_matrix(m, point_t(0_c, 1_r), dim_pair(2_CD, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m, point_t(1_c, 1_r), dim_pair(2_CD, 2_RD))));\n}\n\nBOOST_AUTO_TEST_CASE(test_sub_matrix_3rtx3rt_move){\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), 0_c, 0_r, dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m(), 1_c, 1_r, dim_pair(2_CD, 2_RD))));\n\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CS, 2_RS)) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CD, 2_RS)) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CS, 2_RD)) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), 2_CD, 2_RD)) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CS, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CD, 2_RS)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CS, 2_RD)));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), 2_CD, 2_RD)));\n\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CS, 2_RS))) ==\n\t\tid< std_matrix< int, 2_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CD, 2_RS))) ==\n\t\tid< std_matrix< int, 0_C, 2_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CS, 2_RD))) ==\n\t\tid< std_matrix< int, 2_C, 0_R > >));\n\tBOOST_TEST((rt_id(sub_matrix(m(), point_t(0_c, 0_r), dim_pair(2_CD, 2_RD))) ==\n\t\tid< std_matrix< int, 0_C, 0_R > >));\n\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CS, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CD, 2_RS))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CS, 2_RD))));\n\tBOOST_TEST(check4(sub_matrix(m(), point_t(1_c, 1_r), dim_pair(2_CD, 2_RD))));\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "9501564703ba97ff1caba768f64f7d58b95b05c6", "size": 38616, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/sub_matrix.cpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/sub_matrix.cpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/sub_matrix.cpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.0353227771, "max_line_length": 80, "alphanum_fraction": 0.6767920033, "num_tokens": 15162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6013174060756433}}
{"text": "// json parser\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\nnamespace pt = boost::property_tree;\n\n#include \"Looper.h\"\n#include <cassert>\n\nLooper::Looper(double start, double end, int number_of_steps, const std::string &scale)\n    : start(start), end(end), number_of_steps(number_of_steps), scale(scale) {\n  assert(start < end);\n  this->calculate_steps();\n}\n\nLooper::Looper(const std::string &input_file) {\n\n  // read parameters\n  pt::ptree root;\n  pt::read_json(input_file, root);\n  this->start = root.get<double>(\"Looper.start\");\n  this->end = root.get<double>(\"Looper.end\");\n  this->number_of_steps = root.get<double>(\"Looper.steps\");\n  this->scale = root.get<std::string>(\"Looper.scale\");\n\n  assert(start < end);\n  this->calculate_steps();\n}\n\nvoid Looper::calculate_steps() {\n  if (scale == \"linear\") {\n    double spacing = (end - start) / ((double)number_of_steps - 1);\n    for (int i = 0; i < number_of_steps; i++) {\n      this->steps.push_back(start + i * spacing);\n    }\n  } else if (scale == \"log\") {\n    double spacing = pow(end / start, 1. / ((double)number_of_steps - 1.0));\n    for (int i = 0; i < number_of_steps; i++) {\n      this->steps.push_back(start * pow(spacing, i));\n    }\n\n  } else {\n    std::cerr << \"Unknown scale: \" << scale << std::endl;\n    exit(-1);\n  }\n}\n", "meta": {"hexsha": "97ff10155109727b2ff53c3d81f93be6eba3de93", "size": 1327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Looper/Looper.cpp", "max_stars_repo_name": "QuaCaTeam/quaca", "max_stars_repo_head_hexsha": "ab2d213f3e0e357bd72930ae1e4e703184130270", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T09:01:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T07:57:54.000Z", "max_issues_repo_path": "src/Looper/Looper.cpp", "max_issues_repo_name": "myoelmy/quaca", "max_issues_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T08:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-28T07:33:35.000Z", "max_forks_repo_path": "src/Looper/Looper.cpp", "max_forks_repo_name": "myoelmy/quaca", "max_forks_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_forks_repo_licenses": ["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.847826087, "max_line_length": 87, "alphanum_fraction": 0.6443104748, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.7905303112671295, "lm_q1q2_score": 0.6013173886479276}}
{"text": "\n#include <stdio.h>\n#include <time.h>\n#include <vector>\n#include <fstream>\n#include <cassert>\n#include <algorithm>\n#include <string>\n#include <sstream>      // std::stringstream\n\n\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n#include <NTL/ZZ_pX.h>\n\n#include <NTL/mat_ZZ.h>\n#include <NTL/matrix.h>\n#include <NTL/vec_vec_ZZ.h>\nNTL_CLIENT\n\n\n\n int main(){\n     cout<<\"Hello World\"<<endl;\n     ifstream ist(\"polyfile_before.txt\");\n     if(!ist) cout<<\"Can't open file\"<< endl;\n\n     string s_temp;\n     ZZ mod;\n     long size_vec;\n     long size_f;\n     long size_pt;\n     ist>>s_temp;\n\n     conv(mod,s_temp.c_str());\n     ZZ_p::init(mod);\n     cout<<mod<<endl;\n     ZZ_pX f,pt,res;\n     res=ZZ_pX(); //zero\n     ist>>size_f;\n     ist>>size_pt;\n     ist>>size_vec;\n     \n     //reads the vector t_1\n    //l=2*m;\n    //for (i = 0; i<l; i++){\n    //   ist >> chal_x6->at(i);\n    //}\n\n     cout<<\"Expecting \"<<size_vec*(size_f+size_pt)<<\" entries\"<<endl;\n     //ist>>c;\n     int i,j;\n     \n     for (i=0;i<size_vec;i++){\n         ist>>f;\n         //cout<<f;\n         ist>>pt;\n         //cout<<pt;\n         res+=f*pt;\n         //cout<<res;\n     }\n     ofstream ost(\"polyfile_after.txt\");\n     //ost<<res;\n     stringstream st;     // line A\n     st << res;              // line B\n     std::string s = st.str();      // Line D\n     std::replace( s.begin(), s.end(), ' ', ','); // replace all 'x' to 'y'\n     //ost<<\"hvec=\";\n     ost<<s;\n\n     \n    return 1;\n}\n", "meta": {"hexsha": "da7387125ce403fb624acfd3d8ca85d1e192b56b", "size": 1447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EAC-code/src/main.cpp", "max_stars_repo_name": "kvakil/BulletProofLib", "max_stars_repo_head_hexsha": "0cf22deff1746c03f16c3fb62541c5c02990bb3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 162.0, "max_stars_repo_stars_event_min_datetime": "2017-11-17T09:46:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:32:28.000Z", "max_issues_repo_path": "EAC-code/src/main.cpp", "max_issues_repo_name": "GENERALBYTESCOM/BulletProofLib", "max_issues_repo_head_hexsha": "fd154f28c1729f7f9bd20aa6bed10c952ade4e49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-11-22T20:05:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-29T10:36:15.000Z", "max_forks_repo_path": "EAC-code/src/main.cpp", "max_forks_repo_name": "GENERALBYTESCOM/BulletProofLib", "max_forks_repo_head_hexsha": "fd154f28c1729f7f9bd20aa6bed10c952ade4e49", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2017-11-23T05:25:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T07:53:48.000Z", "avg_line_length": 19.5540540541, "max_line_length": 75, "alphanum_fraction": 0.5127850726, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6893056231680121, "lm_q1q2_score": 0.6013139552967535}}
{"text": "#include <algorithm>\n#include <iostream>\n#include <numeric>\n#include <sstream>\n#include <chrono>\n\n#include <Eigen/SVD>\n\n#include \"ICP.h\"\n#include \"ICPPoint.h\"\n#include \"Misc.h\"\n#include \"Point.h\"\n#include \"PointOP.h\"\n\nICP::ICP(std::array<PointCloudData, 2> &pcd) :\n    m_point_cloud_data(pcd)\n{\n    m_LTS = 1.0;\n    m_text = NULL;\n    m_max_points = 0;\n}\n\nvoid ICP::SetLTS(float a) { m_LTS = a; }\n\nvoid ICP::Run(Eigen::Matrix4d& Transform)\n{\n    // Some distance statistics\n    std::vector<double> dist_sq;\n\n    auto update_text = [&]() {\n        while (m_app->Pending()) {\n            m_app->Dispatch();\n        }\n    };\n\n    if (m_text) {\n        m_text->AppendText(\"Determining square distance to trim at ...\\n\");\n        update_text();\n    }\n\n    for (size_t i = 0; i < m_points1.size(); i++) {\n        if (i % 100000 == 0) {\n            if (m_text) {\n                std::stringstream ss;\n\n                ss << i * 100 / (float)m_points1.size() << \"% \";\n                m_text->AppendText(ss.str());\n\n                update_text();\n            }\n        }\n\n        double dist;\n        int index;\n\n        m_ANN_points2.FindClosest(m_points1[i], dist, index);\n\n        m_points1[i].nearest = m_points2[index];\n        m_points1[i].dist_sq = dist;\n\n        dist_sq.push_back(dist);\n    }\n\n    if (m_text) {\n        m_text->AppendText(\"100%\\n\");\n        update_text();\n    }\n\n    std::sort(dist_sq.begin(), dist_sq.end());\n\n    size_t pos = (int)(dist_sq.size() * m_LTS);\n\n    if (pos >= dist_sq.size()) {\n        pos = dist_sq.size() - 1;\n    }\n\n    double trimDist = dist_sq[pos];\n\n    if (m_text) {\n        std::stringstream ss;\n        ss << \"Trimming at distance: \" << trimDist << \"\\n\";\n        m_text->AppendText(ss.str());\n        update_text();\n    }\n\n    std::vector<ICPPoint> Points2p;\n\n    // Find which points to use based on trimDist and also finds the centroid of\n    // the two points\n    Point centroid1, centroid2;\n\n    centroid1.x = 0;\n    centroid1.y = 0;\n    centroid1.z = 0;\n\n    centroid2.x = 0;\n    centroid2.y = 0;\n    centroid2.z = 0;\n\n    double sum_dist = 0;\n    int count = 0;\n\n    for (size_t i = 0; i < m_points1.size(); i++) {\n        if (m_points1[i].dist_sq > trimDist) {\n            continue;\n        }\n\n        sum_dist += m_points1[i].dist_sq;\n\n        centroid1.x += m_points1[i].x;\n        centroid1.y += m_points1[i].y;\n        centroid1.z += m_points1[i].z;\n\n        centroid2.x += m_points1[i].nearest.x;\n        centroid2.y += m_points1[i].nearest.y;\n        centroid2.z += m_points1[i].nearest.z;\n\n        count++;\n    }\n\n    m_MSE = sum_dist / count;\n\n    centroid1.x /= count;\n    centroid1.y /= count;\n    centroid1.z /= count;\n\n    centroid2.x /= count;\n    centroid2.y /= count;\n    centroid2.z /= count;\n\n    /************************************\n   * FIND OPTIMAL ROTATION USING SVD\n   ************************************/\n\n    Eigen::Matrix3d H;\n\n    H.setZero();\n\n    if (m_text) {\n        m_text->AppendText(\"Calculating optimal transform ... \\n\");\n        update_text();\n    }\n    std::chrono::system_clock::time_point start = std::chrono::system_clock::now();\n\n    for (size_t i = 0; i < m_points1.size(); i++) {\n        if (m_points1[i].dist_sq > trimDist) {\n            continue;\n        }\n\n        Eigen::Vector3d A, B;\n\n        A(0) = m_points1[i].x - centroid1.x;\n        A(1) = m_points1[i].y - centroid1.y;\n        A(2) = m_points1[i].z - centroid1.z;\n\n        B(0) = m_points1[i].nearest.x - centroid2.x;\n        B(1) = m_points1[i].nearest.y - centroid2.y;\n        B(2) = m_points1[i].nearest.z - centroid2.z;\n\n        H += A * B.transpose();\n    }\n\n    Eigen::JacobiSVD<Eigen::Matrix3d> svd(H, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n    // Optimal rotation\n    Eigen::Matrix3d R = svd.matrixV() * svd.matrixU().transpose();\n\n    // Final transformation matrix is T*R*Tc\n    // Tc - translates point1 to the centre for finding the rotation\n    // R - optimal rotation\n    // T - translates point1 back to the centre of point2\n\n    Eigen::Matrix4d Tc, T, RR;\n\n    Tc.setIdentity();\n    T.setIdentity();\n    RR.setIdentity();\n\n    Tc(0, 3) = -centroid1.x;\n    Tc(1, 3) = -centroid1.y;\n    Tc(2, 3) = -centroid1.z;\n\n    T(0, 3) = centroid2.x;\n    T(1, 3) = centroid2.y;\n    T(2, 3) = centroid2.z;\n\n    RR.block(0,0,3,3) = R;\n\n    Transform = T * (RR * Tc);\n\n    PointOP::ApplyTransform(m_points1, Transform);\n\n    // Clean up memory\n    {\n        std::vector<ICPPoint> Empty;\n        Points2p.swap(Empty);\n    }\n}\n\nvoid ICP::SetMaxPoints(unsigned int max) { m_max_points = max; }\n\nvoid ICP::SetPoints(std::vector<Point>& P1, std::vector<Point>& P2,\n    float dist_threshold)\n{\n    const float sq_dist = dist_threshold * dist_threshold;\n\n    if (m_max_points == 0) {\n        throw std::runtime_error(\"ICP: Need to set m_max_points before running SetPoints\");\n    }\n\n    ANN Point1DB, Point2DB;\n    std::vector<Point> filtered1, filtered2;\n    Point start, end;\n\n    reverseable_shuffle_forward(P1, m_point_cloud_data[0].table);\n    reverseable_shuffle_forward(P2, m_point_cloud_data[1].table);\n\n    auto update_text = [&]() {\n        while (m_app->Pending()) {\n            m_app->Dispatch();\n        }\n    };\n\n    // NOTE:\n    // The aim of this is to save as much memory as possible.\n    // We downsample the points before loading it into the ANN library. At the\n    // same time we want to avoid over downsampling. We want the process result\n    // in: point cloud2 -> overlapping region filtering -> down sample > initial outlier\n    // distance -> max point filtering = number of points point cloud2 is m_max_points So\n    // basically, we want all the filtering and downsampling stuff to leave enough\n    // points to meet the user's requested MaxPoint parameter if possible\n\n    // Downsample based on a factor of m_max_points\n    size_t k = m_max_points * 2;\n\n    if (P1.size() > k) {\n        filtered1.resize(k);\n    } else {\n        filtered1.resize(P1.size());\n    }\n\n    for (size_t i = 0; i < filtered1.size(); i++) {\n        filtered1[i] = P1[i];\n    }\n\n    if (P2.size() > k) {\n        filtered2.resize(k);\n    } else {\n        filtered2.resize(P2.size());\n    }\n\n    for (size_t i = 0; i < filtered2.size(); i++) {\n        filtered2[i] = P2[i];\n    }\n\n    // This consumes the most memory out of the entire program\n    // Every 1 million point uses about 200MB of memory when loaded using ANN\n    Point2DB.SetPoints(filtered2);\n\n    // for displaying purposes\n    if (m_text) {\n        m_text->AppendText(\"Downsampling and filtering first point cloud for ICP ... \\n\");\n    }\n\n    for (size_t i = 0;\n         i < filtered1.size() && m_points1.size() < m_max_points; i++) {\n        if (i % 100000 == 0) {\n            if (m_text) {\n                std::stringstream ss;\n\n                ss << i * 100 / (float)filtered1.size() << \"% \";\n                m_text->AppendText(ss.str());\n\n                update_text();\n            }\n        }\n\n        double dist;\n        int index;\n\n        Point2DB.FindClosest(filtered1[i], dist, index);\n\n        if (dist < sq_dist) {\n            m_points1.push_back(ICPPoint(filtered1[i]));\n        }\n    }\n\n    if (m_text) {\n        m_text->AppendText(\"100%\\n\");\n\n        std::stringstream ss;\n        ss << \"Number of points after downsampling/filtering: \" << m_points1.size() << \"\\n\";\n        m_text->AppendText(ss.str());\n\n        update_text();\n    }\n\n    Point2DB.Free();\n\n    {\n        std::vector<Point> empty;\n        filtered1.swap(empty);\n    }\n\n    Point1DB.SetPoints(m_points1);\n\n    if (m_text) {\n        m_text->AppendText(\"Downsampling and filtering second point cloud for ICP ... \\n\");\n    }\n\n    // Do the same again\n\n    for (size_t i = 0;\n         i < filtered2.size() && m_points2.size() < m_max_points; i++) {\n        if (i % 100000 == 0) {\n            if (m_text) {\n                std::stringstream ss;\n                ss << i * 100 / (float)filtered2.size() << \"% \";\n                m_text->AppendText(ss.str());\n\n                update_text();\n            }\n        }\n\n        double dist;\n        int index;\n\n        Point1DB.FindClosest(filtered2[i], dist, index);\n\n        if (dist < sq_dist) {\n            m_points2.push_back(filtered2[i]);\n        }\n    }\n\n    if (m_text) {\n        m_text->AppendText(\"100%\\n\");\n\n        std::stringstream ss;\n        ss << \"Number of points after downsampling/filtering: \" << m_points2.size() << \"\\n\";\n        m_text->AppendText(ss.str());\n\n        update_text();\n    }\n\n    Point1DB.Free();\n\n    m_ANN_points2.SetPoints(m_points2);\n\n    reverseable_shuffle_backward(P1, m_point_cloud_data[0].table);\n    reverseable_shuffle_backward(P2, m_point_cloud_data[1].table);\n}\n\nvoid ICP::Seteps(float e)\n{\n    m_eps = e;\n    m_ANN_points2.Seteps(m_eps);\n}\n\ndouble ICP::GetMSE() { return m_MSE; }\nvoid ICP::SetwxTextCtrl(wxTextCtrl* t) // Used for m_text feedback from ICP\n{\n    m_text = t;\n}\nvoid ICP::SetwxApp(wxApp* a) // Used for m_text feedback from ICP\n{\n    m_app = a;\n}\n", "meta": {"hexsha": "0927b9d2b1bae28a169387491d78a811ed9b40cd", "size": 8953, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ICP.cc", "max_stars_repo_name": "nghiaho12/Register3D", "max_stars_repo_head_hexsha": "52b82d7ee9dc8391a443e10cd2e3b354f5ec5657", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T17:41:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T06:29:31.000Z", "max_issues_repo_path": "src/ICP.cc", "max_issues_repo_name": "nghiaho12/Register3D", "max_issues_repo_head_hexsha": "52b82d7ee9dc8391a443e10cd2e3b354f5ec5657", "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/ICP.cc", "max_forks_repo_name": "nghiaho12/Register3D", "max_forks_repo_head_hexsha": "52b82d7ee9dc8391a443e10cd2e3b354f5ec5657", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3288043478, "max_line_length": 92, "alphanum_fraction": 0.5598123534, "num_tokens": 2476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6013139552967535}}
{"text": "#include \"Position.h\"\n\n#include <vector>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <numeric>\n\n#include \"operationVector.h\" // ceci va chercher le fichier qui contient les operations sur les vecteurs\n#include \"alpha.h\"\n\nusing namespace std;\nusing namespace boost::numeric::ublas;\n\nmatrix<double> Position(matrix<double> Obs, matrix<double> M, std::vector<double> pie) {\n\n    int n = Obs.size1();\n    int m = Obs.size2();\n    auto alpha = Alpha(Obs, M, pie);\n    matrix<double> Probs(n, m);\n    double truc=0.0;\n\n    for ( int i=0; i<n; ++i){\n\n        double maxx = getMax(ligne(alpha,i));\n        for ( int j=0; j<m; ++j){\n            truc = truc+ exp(alpha(i,j)-maxx);\n        }\n        double corr = maxx+log(truc);\n        for ( int j=0; j<m; ++j){\n            Probs(i,j) = exp(alpha(i,j)-corr);\n        }\n    }\n    \n\tfor ( int j=0; j<n; ++j) {\n\t\tdouble sumLigne = sum(ligne(Probs,j));\n\t\tif ( sumLigne ==0 ) {\n\t\t\tProbs(j,j) = 1;\n\n\t\t} else {\n\t\t\tfor ( int i = 0;  i <m; ++i){\n\t\t\t\tProbs(j,i) = Probs(j,i) / sumLigne;\n\t\t\t}\n\t\t}\n\t}\n    return Probs;\n\n}\n", "meta": {"hexsha": "a52eb08592799c8b0090130f7d48b2fd0874412b", "size": 1058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Position.cpp", "max_stars_repo_name": "Louis-Alexandre/Captain-Markov", "max_stars_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T17:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-29T09:47:49.000Z", "max_issues_repo_path": "src/Position.cpp", "max_issues_repo_name": "Louis-Alexandre/Captain-Markov", "max_issues_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Position.cpp", "max_forks_repo_name": "Louis-Alexandre/Captain-Markov", "max_forks_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5106382979, "max_line_length": 104, "alphanum_fraction": 0.5604914934, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6013139507215426}}
{"text": "/*! @file pitts_fixed_tensor3_split.hpp\n* @brief contract two simple fixed-dimension rank-3 tensors (along third and first dimension)\n* @author Melven Roehrig-Zoellner <Melven.Roehrig-Zoellner@DLR.de>\n* @date 2019-12-29\n* @copyright Deutsches Zentrum fuer Luft- und Raumfahrt e. V. (DLR), German Aerospace Center\n*\n**/\n\n// include guard\n#ifndef PITTS_FIXED_TENSOR3_SPLIT_HPP\n#define PITTS_FIXED_TENSOR3_SPLIT_HPP\n\n// includes\n#include <array>\n#pragma GCC push_options\n#pragma GCC optimize(\"no-unsafe-math-optimizations\")\n#include <Eigen/Dense>\n#pragma GCC pop_options\n#include \"pitts_fixed_tensor3.hpp\"\n#include \"pitts_timer.hpp\"\n\n//! namespace for the library PITTS (parallel iterative tensor train solvers)\nnamespace PITTS\n{\n  //! split a fixed-size rank-3 tensor into 2 smaller tensors\n  //!\n  //! Split t3c into t3a and t3b such that\n  //!   t3c_(i,k,j) = sum_l t3a_(i,k1,l) * t3b_(l,k2,j)   with k=k2*N+k1\n  //!\n  //! @tparam T  underlying data type (double, complex, ...)\n  //! @tparam N  dimension\n  //!\n  //! @param[in]  t3c       rank-3 tensor\n  //! @param[out] t3a       first part of splitted rank-3 tensor\n  //! @param[out] t3b       second part of splitted rank-3 tensor\n  //! @param[in]  leftOrtog make left part (t3a) orthogonal if true, otherwise t3b is made orthogonal\n  //!\n  template<typename T, int N>\n  void split(const FixedTensor3<T,N*N>& t3c, FixedTensor3<T,N>& t3a, FixedTensor3<T,N>& t3b, bool leftOrthog = true)\n  {\n    const auto timer = PITTS::timing::createScopedTimer<FixedTensor3<T,N>>();\n\n    using Matrix = Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic>;\n    using Stride = Eigen::OuterStride<Eigen::Dynamic>;\n    using Map = Eigen::Map<Matrix, Eigen::Aligned128, Stride>;\n    using ConstMap = Eigen::Map<const Matrix, Eigen::Aligned128, Stride>;\n\n    const auto r1 = t3c.r1();\n    const auto r2 = t3c.r2();\n    if( r1*r2 == 0 )\n      throw std::invalid_argument(\"Unsupported dimension of zero!\");\n\n    const auto t3cMap = ConstMap(&t3c(0,0,0), N*r1, N*r2, Stride(N*r1));\n\n    // use a faster QR algorithm (at the risk of a badly estimated truncation error)\n    if( leftOrthog )\n    {\n      Eigen::ColPivHouseholderQR<Matrix> qr(t3cMap);\n      qr.setThreshold(1.e-10);\n      const auto r = std::max(Eigen::Index(1), qr.rank());\n\n      t3a.resize(r1,r);\n      t3b.resize(r,r2);\n\n      // A P = Q R\n      // => A = Q (R P^(-1))\n      const Matrix Q = qr.matrixQ();\n      const Matrix R = qr.matrixR().topRows(r).template triangularView<Eigen::Upper>();\n      const auto P = qr.colsPermutation();\n      Map(&t3a(0,0,0), r1*N, r, Stride(r1*N)) = Q.leftCols(r);\n      Map(&t3b(0,0,0), r, r2*N, Stride(r)) = R * P.inverse();\n    }\n    else // rightOrthog\n    {\n      Eigen::ColPivHouseholderQR<Matrix> qr(t3cMap.transpose());\n      qr.setThreshold(1.e-10);\n      const auto r = std::max(Eigen::Index(1), qr.rank());\n\n      t3a.resize(r1,r);\n      t3b.resize(r,r2);\n\n      // A^T P = Q R\n      // => P^T A = R^T Q^T\n      // => A = (R P^(-1))^T Q^T\n      const Matrix Q = qr.matrixQ();\n      const Matrix R = qr.matrixR().topRows(r).template triangularView<Eigen::Upper>();\n      const auto P = qr.colsPermutation();\n      Map(&t3a(0,0,0), r1*N, r, Stride(r1*N)) = (R * P.inverse()).transpose();\n      Map(&t3b(0,0,0), r, r2*N, Stride(r)) = Q.leftCols(r).transpose();\n    }\n    /*\n    auto svd = Eigen::JacobiSVD<Matrix, Eigen::HouseholderQRPreconditioner>(t3cMap, Eigen::ComputeThinV | Eigen::ComputeThinU);\n    svd.setThreshold(1.e-10);\n    const auto r = svd.rank();\n\n    t3a.resize(r1,r);\n    t3b.resize(r,r2);\n    if( leftOrthog )\n    {\n      Map(&t3a(0,0,0), r1*N,r) = svd.matrixU().leftCols(r);\n      Map(&t3b(0,0,0), r,r2*N) = svd.singularValues().head(r).asDiagonal() * svd.matrixV().leftCols(r).adjoint();\n    }\n    else\n    {\n      Map(&t3a(0,0,0), r1*N,r) = svd.matrixU().leftCols(r) * svd.singularValues().head(r).asDiagonal();\n      Map(&t3b(0,0,0), r,r2*N) = svd.matrixV().leftCols(r).adjoint();\n    }\n    //std::cout << \"Singular value |.|: \" << svd.singularValues().head(r).transpose().array().abs() << \"\\n\";\n    */\n  }\n\n}\n\n\n#endif // PITTS_FIXED_TENSOR3_SPLIT_HPP\n", "meta": {"hexsha": "c4d850eb44bff5fc1323b4d3465cf014973a4598", "size": 4109, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pitts_fixed_tensor3_split.hpp", "max_stars_repo_name": "melven/pitts", "max_stars_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T14:48:49.000Z", "max_issues_repo_path": "src/pitts_fixed_tensor3_split.hpp", "max_issues_repo_name": "melven/pitts", "max_issues_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pitts_fixed_tensor3_split.hpp", "max_forks_repo_name": "melven/pitts", "max_forks_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4224137931, "max_line_length": 127, "alphanum_fraction": 0.6271598929, "num_tokens": 1344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6012955532097151}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n\nnamespace ipc::rigid {\n\n//-------------------------------------------------------------------------\n// Signed Distances (useful for CCD)\n//-------------------------------------------------------------------------\n\n/// Compute the signed distance between a point and a line\n/// WARNING: Produces the same sign as euclidean distance but may be\n/// different scales.\ntemplate <typename T>\ninline T point_line_signed_distance(\n    const Vector2<T>& point,\n    const Vector2<T>& line_point0,\n    const Vector2<T>& line_point1);\n\n/// Compute the signed distance between two lines\n/// WARNING: Produces the same sign as euclidean distance but may be\n/// different scales.\n/// WARNING: Parallel edges results in zero distance\ntemplate <typename T>\ninline T line_line_signed_distance(\n    const Vector3<T>& line0_point0,\n    const Vector3<T>& line0_point1,\n    const Vector3<T>& line1_point0,\n    const Vector3<T>& line1_point1);\n\n/// Compute the distance between a point and a plane.\n/// Normal is assumed to be unit length.\n/// WARNING: Produces the same sign as euclidean distance but may be\n/// different scales.\ntemplate <typename T>\ninline T point_plane_signed_distance(\n    const Vector3<T>& point,\n    const Vector3<T>& triangle_vertex0,\n    const Vector3<T>& triangle_vertex1,\n    const Vector3<T>& triangle_vertex2);\n\n} // namespace ipc::rigid\n\n#include \"distance.tpp\"\n", "meta": {"hexsha": "f1e7619bbf1a0a55b236be27e45b4cb4598f27be", "size": 1407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geometry/distance.hpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "src/geometry/distance.hpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "src/geometry/distance.hpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 31.2666666667, "max_line_length": 75, "alphanum_fraction": 0.6567164179, "num_tokens": 299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.6012955373590361}}
{"text": "#include <iostream>\n#include <vector>\n\n#include <boost/geometry/algorithms/intersection.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\nnamespace geom = boost::geometry;\n\nint main()\n{\n  // point in 2d cartesian c.s.\n  typedef geom::model::d2::point_xy<double> point;\n  // polygon of points, counterclockwise, open (i.e. last != first)\n  typedef geom::model::polygon<point, false, false> polygon;\n\n  polygon q4{{ {0.0, 0.0}, {1.0, 0.0}, {1.0, 1.0}, {0.0, 1.0} }};\n  polygon t3{{ {0.2, 0.2}, {0.8, 0.2}, {0.2, 0.8} }};\n\n  std::vector<polygon> N;\n  geom::intersection(q4, t3, N);\n\n  for (auto i = 0; i < N.size(); ++i) {\n    std::cout << \"polygon \" << i << std::endl;\n    const auto& polynodes = N[i].outer();\n\n    for (auto j = 0; j < polynodes.size(); ++j) {\n      const auto& nd = polynodes[j];\n      std::cout << \"  node \" << j << \": \"\n                << nd.get<0>() << \" \" << nd.get<1>() << std::endl;\n    }\n\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "9f1e53b003dc6e725de0cd6acbeddd679d3379f2", "size": 987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "degrbg/boost_geom", "max_stars_repo_head_hexsha": "227097e7f4c2591ff2f9592a4fd7f655b5499cc0", "max_stars_repo_licenses": ["MIT"], "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": "degrbg/boost_geom", "max_issues_repo_head_hexsha": "227097e7f4c2591ff2f9592a4fd7f655b5499cc0", "max_issues_repo_licenses": ["MIT"], "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": "degrbg/boost_geom", "max_forks_repo_head_hexsha": "227097e7f4c2591ff2f9592a4fd7f655b5499cc0", "max_forks_repo_licenses": ["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.6756756757, "max_line_length": 67, "alphanum_fraction": 0.5724417427, "num_tokens": 343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6012955267470111}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// Unit Test\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <random>\n#include <vector>\n#include <sstream>\n\n#include <geometry_test_common.hpp>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/extensions/random/uniform_point_distribution.hpp>\n\ntypedef bg::model::point<double, 2, bg::cs::cartesian> point2d_cart;\ntypedef bg::model::point<double, 3, bg::cs::cartesian> point3d_cart;\ntypedef bg::model::point<double, 2, bg::cs::geographic<bg::degree>> point2d_geog;\n\nvoid test_geographic()\n{\n    //We check whether the generated points lie roughly along\n    //the great circle segment (<2 km distance on a sphere with\n    //the radius of earth) and are distributed uniformly with respect\n    //to great circle arc length.\n    typedef bg::model::linestring<point2d_geog> linestring;\n    linestring ls {{ 0.0, 0.0 }, { 45.0, 45.0 }, { 60.0, 60.0 }};\n    bg::random::uniform_point_distribution<linestring> l_dist(ls);\n    std::mt19937 generator(0);\n    int sample_count = 2000;\n    int count_below_45 = 0;\n    for (int i = 0 ; i < sample_count ; ++i)\n    {\n        point2d_geog sample = l_dist(generator);\n        BOOST_CHECK( bg::distance(sample, ls) < 2000 );\n        if(bg::get<0>(sample) < 45.0) count_below_45++;\n    }\n    double length_ratio = bg::distance(ls[0], ls[1]) / \n        ( bg::distance(ls[0], ls[1]) + bg::distance(ls[1], ls[2]) );\n    double sample_ratio = ((double) count_below_45) / sample_count;\n    bool in_range = sample_ratio * 0.95 < length_ratio \n        && sample_ratio * 1.05 > length_ratio;\n    BOOST_CHECK( in_range );\n\n    //We check whether the generated points lie in the spherical box\n    //(which is actually a triangle in this case) and whether the latitude\n    //is distributed as expected for uniform spherical distribution, using\n    //known area ratios of spherical caps.\n    typedef bg::model::box<point2d_geog> box;\n    box b {{ 0.0, 0.0 }, { 90.0, 90.0 }};\n    bg::random::uniform_point_distribution<box> b_dist(b);\n    int under_60 = 0;\n    for (int i = 0 ; i < sample_count ; ++i)\n    {\n        point2d_geog sample = b_dist(generator);\n        BOOST_CHECK( bg::within(sample, b) );\n        if(bg::get<1>(sample) < 60.0) ++under_60;\n    }\n    BOOST_CHECK_GT(under_60, 0.5 * 0.95 * sample_count);\n    BOOST_CHECK_LT(under_60, 0.5 * 1.05 * sample_count);\n}\n\nvoid test_polygon()\n{\n    //This test will test uniform sampling in polygon, which also checks\n    //uniform sampling in boxes. We check whether two equal distributions\n    //(copied using operator<< and operator>>) generate the same sequence\n    //of points and whether those points are uniformly distributed with\n    //respect to cartesian area.\n    typedef bg::model::polygon<point2d_cart> polygon;\n    polygon poly;\n    bg::read_wkt(\n        \"POLYGON((16 21,17.1226 17.5451,20.7553 17.5451, 17.8164 15.4098,18.9389 11.9549,16 14.0902,13.0611 11.9549, 14.1836 15.4098,11.2447 17.5451,14.8774 17.5451,16 21))\",\n        poly);\n    bg::random::uniform_point_distribution<polygon> poly_dist(poly);\n    bg::random::uniform_point_distribution<polygon> poly_dist2;\n    BOOST_CHECK( !(poly_dist == poly_dist2) );\n    std::stringstream ss;\n    ss << poly_dist;\n    ss >> poly_dist2;\n    BOOST_CHECK( poly_dist == poly_dist2 );\n    std::mt19937 generator(0), generator2(0);\n    for (int i = 0 ; i < 100 ; ++i)\n    {\n        point2d_cart sample1 = poly_dist(generator);\n        BOOST_CHECK( bg::equals(sample1, poly_dist2(generator2)) );\n        BOOST_CHECK( bg::within(sample1, poly) );\n    }\n    std::vector<point2d_cart> randoms;\n    const int uniformity_test_samples = 2000;\n    for (int i = 0 ; i < uniformity_test_samples ; ++i)\n    {\n        randoms.push_back(poly_dist(generator));\n    }\n    typedef bg::model::box<point2d_cart> box;\n    box env, lhalf;\n    bg::envelope(poly, env);\n    bg::set<bg::min_corner, 0>(lhalf, bg::get<bg::min_corner, 0>(env));\n    bg::set<bg::min_corner, 1>(lhalf, bg::get<bg::min_corner, 1>(env));\n    bg::set<bg::max_corner, 0>(lhalf, bg::get<bg::max_corner, 0>(env));\n    bg::set<bg::max_corner, 1>(lhalf,\n        (bg::get<bg::max_corner, 1>(env) + bg::get<bg::min_corner, 1>(env)) / 2);\n    std::vector<polygon> lower;\n    bg::intersection(lhalf, poly, lower);\n    double area_ratio = bg::area(lower[0])/bg::area(poly);\n    int in_lower = 0;\n    for (int i = 0 ; i < uniformity_test_samples ; ++i)\n    {\n        if(bg::within(randoms[i], lhalf))\n            ++in_lower;\n    }\n    double sample_ratio = ((double) in_lower ) / uniformity_test_samples;\n    BOOST_CHECK_GT( sample_ratio * 1.05, area_ratio );\n    BOOST_CHECK_LT( sample_ratio * 0.95, area_ratio );\n}\n\nvoid test_multipoint()\n{\n    typedef bg::model::multi_point<point3d_cart> multipoint;\n    multipoint mp {{0.0, 0.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}};\n    int first = 0;\n    bg::random::uniform_point_distribution<multipoint> mp_dist(mp);\n    std::mt19937 generator(0);\n    int sample_count = 1000;\n    for (int i = 0 ; i < sample_count ; ++i)\n    {\n        point3d_cart sample = mp_dist(generator);\n        BOOST_CHECK( bg::within(sample, mp) );\n        if(bg::equals(sample, mp[0])) ++first;\n    }\n    BOOST_CHECK_GT(first * 1.05, sample_count / 3);\n    BOOST_CHECK_LT(first * 0.95, sample_count / 3);\n}\n\nint test_main(int, char* [])\n{\n    test_polygon();\n    test_geographic();\n    test_multipoint();\n    return 0;\n}\n", "meta": {"hexsha": "89b8da75aa02c5a766b1962aa2a1b7c403385c34", "size": 5581, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extensions/test/random/random.cpp", "max_stars_repo_name": "BoostGSoC19/geometry", "max_stars_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-31T19:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-31T19:33:37.000Z", "max_issues_repo_path": "extensions/test/random/random.cpp", "max_issues_repo_name": "BoostGSoC19/geometry", "max_issues_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "extensions/test/random/random.cpp", "max_forks_repo_name": "BoostGSoC19/geometry", "max_forks_repo_head_hexsha": "bad1b9c5a2f4f458284a912a848a25e73c28014b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T04:54:35.000Z", "avg_line_length": 38.4896551724, "max_line_length": 174, "alphanum_fraction": 0.6545421967, "num_tokens": 1697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6012955215083572}}
{"text": "#ifndef SPLINE_FITTER_HPP\n#define SPLINE_FITTER_HPP\n#include <vector>\n#include <Eigen/SparseLU>\n\n/**\n * Quadratic B-spline curve fitter\n * This class computes the control points necessary to make a quadratic B-spline curve \n * interpolating a known set of points.\n *\n */\ntemplate<typename T>\nclass QuadraticSplineFitter \n{\npublic:\n\n  /**\n   * Default constructor\n   */\n  QuadraticSplineFitter() : QuadraticSplineFitter({})\n  {\n  };\n\n  /**\n   * Constructor\n   * @param points Points to interpolate\n   */\n  QuadraticSplineFitter(std::vector<T>& points){\n    setPoints(points);\n  }\n  \n  /**\n   * Set points to interpolate\n   * @param points points to interpolate \n   */\n  inline void\n  setPoints(std::vector<T>& points)\n  {\n    m_points = points;\n  }\n  \n \n  /**\n   * Compute the control points necessary to interpolate the points set by setPoints\n   * @return the control points\n   */\n  std::vector<T> \n  compute_control_points() const\n  {\n    // Here:\n    // Build a NxN matrix such that\n    // matrix[row][row] =  matrix[row][row+1] = 1/2\n    // rest = 0\n    // build B such that B = [ep_start points ep_stop]\n    // Solve Ax = B\n    // x are the knots\n    int n = m_points.size()+2;\n    Eigen::SparseMatrix<T> A(n,n);\n      \n    Eigen::Matrix<T, Eigen::Dynamic, 1> b(n);\n    std::vector<Eigen::Triplet<T> > triplets;\n    triplets.reserve((n)*2);\n      \n    // Initialize coefficients for the points to reach\n    \n    for(int i = 1; i < n-1; i++)\n    {\n      triplets.push_back(Eigen::Triplet<T>(i,i-1,0.125));\n      triplets.push_back(Eigen::Triplet<T>(i,i,0.75));\n      triplets.push_back(Eigen::Triplet<T>(i,i+1,0.125));\n      b(i) = m_points[i-1];\n    }\n      \n    __insertStartpointCoeffs(triplets,b,0);\n    __insertEndpointCoeffs(triplets,b,n-1);\n    A.setFromTriplets(triplets.begin(), triplets.end());\n     \n    // Now solve the linear system using linear least squares\n    Eigen::Matrix<T, Eigen::Dynamic, 1> x(n);\n    Eigen::SparseLU<Eigen::SparseMatrix<T> > solver;\n\n    solver.compute(A);\n    x = solver.solve(b);\n\n    //     printVector(x,n);\n    // Copy back to std::vector\n    std::vector<T> ret;\n      \n    ret.reserve(n);\n    for(int i = 0; i < n; i++)\n    {\n      ret.push_back(x(i));\n    }\n    return ret;\n      \n  }\n\n\t  \n  \nprivate:\n  inline void \n  __insertStartpointCoeffs( std::vector<Eigen::Triplet<T> >& triplets, \n\t\t\t    Eigen::Matrix<T, Eigen::Dynamic, 1>& b, \n\t\t\t    const int i) const\n  {\n    triplets.push_back(Eigen::Triplet<T>(i,i,-1));\n    triplets.push_back(Eigen::Triplet<T>(i,i+1,1));\n    b(i) = 0.0;\n  }\n\n  inline void \n  __insertEndpointCoeffs( std::vector<Eigen::Triplet<T> >& triplets, \n\t\t\t  Eigen::Matrix<T, Eigen::Dynamic, 1>& b, \n\t\t\t  const int i) const\n  {\n    triplets.push_back(Eigen::Triplet<T>(i,i-1,-1));\n    triplets.push_back(Eigen::Triplet<T>(i,i,1));\n    b(i) = 0.0;\n  }\n\t\n  std::vector<T> m_points;\n\n};\n\n#endif\n", "meta": {"hexsha": "28f19b5d8fae8b2a6e1863d933f5cd0839696592", "size": 2864, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/quadratic_spline_fitter.hpp", "max_stars_repo_name": "Danielhiversen/AngleCorr", "max_stars_repo_head_hexsha": "01acc6547c95e506b88c20011789784a129a16bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core/quadratic_spline_fitter.hpp", "max_issues_repo_name": "Danielhiversen/AngleCorr", "max_issues_repo_head_hexsha": "01acc6547c95e506b88c20011789784a129a16bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-23T12:30:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-23T12:30:47.000Z", "max_forks_repo_path": "core/quadratic_spline_fitter.hpp", "max_forks_repo_name": "Danielhiversen/AngleCorr", "max_forks_repo_head_hexsha": "01acc6547c95e506b88c20011789784a129a16bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-02T10:18:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-02T10:18:43.000Z", "avg_line_length": 22.7301587302, "max_line_length": 87, "alphanum_fraction": 0.6106843575, "num_tokens": 853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.6012611763933768}}
{"text": "#include <cmath>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <gtest/gtest.h>\n\n#include <BingoCpp/backend.h>\n\n#include \"testing_utils.h\"\n#include \"test_fixtures.h\"\n\nusing namespace bingo;\nusing namespace backend;\n\nnamespace {\n\nconst int N_OPS = 13;\n\nstruct AGraphValues {\nEigen::ArrayXXd x_vals;\nEigen::VectorXd constants;\nAGraphValues() {}\nAGraphValues(Eigen::ArrayXXd &x, Eigen::VectorXd &c) : \n  x_vals(x), constants(c) {}\n};\n\nclass AGraphBackend : public ::testing::TestWithParam<int> {\n public:\n  \n  const double AGRAPH_VAL_START =-1;\n  const double AGRAPH_VAL_END = 0;\n  const int N_AGRAPH_VAL = 11;\n\n  AGraphValues sample_agraph_1_values;\n  std::vector<Eigen::ArrayXXd> operator_evals_x0;\n  std::vector<Eigen::ArrayXXd> operator_x_derivs;\n  std::vector<Eigen::ArrayXXd> operator_c_derivs;\n\n  Eigen::ArrayX3i simple_stack;\n  Eigen::ArrayX3i simple_stack2;\n  Eigen::ArrayXXd x;\n  Eigen::ArrayXd constants;\n\n  virtual void SetUp() {\n    sample_agraph_1_values = init_agraph_vals(AGRAPH_VAL_START,\n                                              AGRAPH_VAL_END,\n                                              N_AGRAPH_VAL);           \n    operator_evals_x0 = init_op_evals_x0(sample_agraph_1_values);\n    operator_x_derivs = init_op_x_derivs(sample_agraph_1_values);\n    operator_c_derivs = init_op_c_derivs(sample_agraph_1_values);\n\n    simple_stack = testutils::stack_operators_0_to_5(); \n    simple_stack2 = testutils::stack_unary_operator(4);\n    x = testutils::one_to_nine_3_by_3();\n    constants = testutils::pi_ten_constants();\n  }\n  virtual void TearDown() {}\n\n AGraphValues init_agraph_vals(double begin, double end, int num_points) {\n  Eigen::VectorXd constants = Eigen::VectorXd(2);\n  constants << 10, 3.14;\n\n  Eigen::ArrayXXd x_vals(num_points, 2);\n  x_vals.col(0) = Eigen::ArrayXd::LinSpaced(num_points, begin, 0);\n  x_vals.col(1) = Eigen::ArrayXd::LinSpaced(num_points, 0, end);\n\n  return AGraphValues(x_vals, constants);\n}\n\nstd::vector<Eigen::ArrayXXd> init_op_evals_x0(\n    const AGraphValues &sample_agraph_1_values) {\n  Eigen::ArrayXXd x_0 = sample_agraph_1_values.x_vals.col(0);\n  double constant = sample_agraph_1_values.constants[0];\n  Eigen::ArrayXXd c_0 = constant * Eigen::ArrayXd::Ones(x_0.rows());\n\n  const std::vector<Eigen::ArrayXXd> op_evals_x0 = {\n    x_0,\n    c_0,\n    x_0+x_0,\n    x_0-x_0,\n    x_0*x_0,\n    x_0/x_0,\n    x_0.sin(),\n    x_0.cos(),\n    x_0.exp(),\n    x_0.abs().log(),\n    x_0.abs().pow(x_0),\n    x_0.abs(),\n    x_0.abs().sqrt()\n  };\n\n  return op_evals_x0;\n}\n\nstd::vector<Eigen::ArrayXXd> init_op_x_derivs(\n    const AGraphValues &sample_agraph_1_values) {\n  Eigen::ArrayXXd x_0 = sample_agraph_1_values.x_vals.col(0);\n  int size = x_0.rows();\n\n  auto last_nan = [](Eigen::ArrayXXd array) {\n    array(array.rows() - 1, array.cols() -1) = std::nan(\"1\");\n    Eigen::ArrayXXd modified_array = array;\n    return modified_array;\n  };\n  \n  const std::vector<Eigen::ArrayXXd> op_x_derivs = {\n    Eigen::ArrayXd::Ones(size),\n    Eigen::ArrayXd::Zero(size),\n    2.0  * Eigen::ArrayXd::Ones(size),\n    Eigen::ArrayXd::Zero(size),\n    2.0 * x_0,\n    last_nan(Eigen::ArrayXd::Zero(size)),\n    x_0.cos(),\n    -x_0.sin(),\n    x_0.exp(),\n    1.0 / x_0,\n    last_nan(x_0.abs().pow(x_0)*(x_0.abs().log() + Eigen::ArrayXd::Ones(size))),\n    x_0.sign(),\n    0.5 * x_0.sign() / x_0.abs().sqrt()\n  };\n  \n  return op_x_derivs;\n}\n\nstd::vector<Eigen::ArrayXXd> init_op_c_derivs(\n    const AGraphValues &sample_agraph_1_values) {\n  int size = sample_agraph_1_values.x_vals.rows();\n  Eigen::ArrayXXd c_1 = sample_agraph_1_values.constants[1] * Eigen::ArrayXd::Ones(size);\n\n  std::vector<Eigen::ArrayXXd> op_c_derivs =  {\n    Eigen::ArrayXd::Zero(size),\n    Eigen::ArrayXd::Ones(size),\n    2.0  * Eigen::ArrayXd::Ones(size),\n    Eigen::ArrayXd::Zero(size),\n    2.0 * c_1,\n    (Eigen::ArrayXd::Zero(size)),\n    c_1.cos(),\n    -c_1.sin(),\n    c_1.exp(),\n    1.0 / c_1,\n    c_1.abs().pow(c_1)*(c_1.abs().log() + Eigen::ArrayXd::Ones(size)),\n    c_1.sign(),\n    0.5 * c_1.sign() / c_1.abs().sqrt()\n  };\n  \n  return op_c_derivs;\n}\n};\n\nTEST_P(AGraphBackend, simplify_and_evaluate) {\n  int operator_i = GetParam();\n  Eigen::ArrayXXd expected_outcome = operator_evals_x0[operator_i];\n\n  Eigen::ArrayX3i stack(3, 3);\n  stack << 0, 0, 0,\n           0, 1, 0,\n           operator_i, 0, 0;\n  Eigen::ArrayXXd f_of_x = SimplifyAndEvaluate(stack,\n                                               sample_agraph_1_values.x_vals,\n                                               sample_agraph_1_values.constants);\n  ASSERT_TRUE(testutils::almost_equal(expected_outcome, f_of_x));\n}\n\nTEST_P(AGraphBackend, simplify_and_evaluate_x_deriv) {\n  int operator_i = GetParam();\n  Eigen::ArrayXXd expected_derivative = \n    Eigen::ArrayXXd::Zero(sample_agraph_1_values.x_vals.rows(), 2);\n  expected_derivative.col(0) = operator_x_derivs[operator_i];\n\n  Eigen::ArrayX3i stack(4, 3);\n  stack << 0, 0, 0,\n           0, 0, 0,\n           0, 1, 1,\n           operator_i, 0, 1;\n\n  Eigen::ArrayXXd x_0 = sample_agraph_1_values.x_vals;\n  Eigen::ArrayXXd constants = sample_agraph_1_values.constants;\n  std::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> res_and_gradient = \n    SimplifyAndEvaluateWithDerivative(stack,\n                                      x_0,\n                                      constants,\n                                      true);\n  Eigen::ArrayXXd df_dx = res_and_gradient.second;\n  ASSERT_TRUE(testutils::almost_equal(expected_derivative, df_dx));\n}\n\nTEST_P(AGraphBackend, simplify_and_evaluate_c_deriv) {\n  int operator_i = GetParam();\n  int num_x_points = sample_agraph_1_values.x_vals.rows();\n  int num_consts = sample_agraph_1_values.constants.size();\n  int last_col = num_consts - 1;\n  Eigen::ArrayXXd expected_derivative = \n    Eigen::MatrixXd::Zero(num_x_points, num_consts).array();\n  expected_derivative.col(last_col) = operator_c_derivs[operator_i];\n  \n  Eigen::ArrayX3i stack(4, 3);\n  stack << 1, 1, 1,\n           1, 1, 1,\n           0, 1, 1,\n           operator_i, 1, 0;\n  \n  Eigen::ArrayXXd x_0 = sample_agraph_1_values.x_vals;\n  Eigen::ArrayXXd constants = sample_agraph_1_values.constants;\n  std::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> res_and_gradient = \n    SimplifyAndEvaluateWithDerivative(stack,\n                                      x_0,\n                                      constants,\n                                      false);\n  Eigen::ArrayXXd df_dc = res_and_gradient.second;\n  ASSERT_TRUE(testutils::almost_equal(expected_derivative, df_dc));\n}\nINSTANTIATE_TEST_CASE_P(,AGraphBackend, ::testing::Range(0, N_OPS, 1));\n\nTEST_F(AGraphBackend, evaluate) {\n  Eigen::ArrayXXd y = Evaluate(simple_stack, x, constants);\n  Eigen::ArrayXXd y_true = x.col(0) * (constants[0] + constants[1] \n                          / x.col(1)) - x.col(0);\n  ASSERT_TRUE(testutils::almost_equal(y, y_true));\n}\n\nTEST_F(AGraphBackend, evaluate_and_derivative) {\n  std::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> y_and_dy =\n    EvaluateWithDerivative(simple_stack, x, constants);\n  Eigen::ArrayXXd y_true = x.col(0) * (constants[0] + constants[1] \n                          / x.col(1)) - x.col(0);\n  Eigen::ArrayXXd dy_true = Eigen::ArrayXXd::Zero(3, 3);\n  dy_true.col(0) = constants[0] + constants[1] / x.col(1) - 1.;\n  dy_true.col(1) = - x.col(0) * constants[1] / x.col(1) / x.col(1);\n\n  ASSERT_TRUE(testutils::almost_equal(y_and_dy.first, y_true));\n  ASSERT_TRUE(testutils::almost_equal(y_and_dy.second, dy_true));\n}\n\nTEST_F(AGraphBackend, mask_evaluate) {\n  Eigen::ArrayXXd y = Evaluate(simple_stack, x, constants);\n  Eigen::ArrayXXd y_simple = SimplifyAndEvaluate(simple_stack, x, constants);\n  ASSERT_TRUE(testutils::almost_equal(y, y_simple));\n}\n\nTEST_F(AGraphBackend, mask_evaluate_and_derivative) {\n  std::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> y_and_dy =\n    EvaluateWithDerivative(simple_stack, x, constants);\n  std::pair<Eigen::ArrayXXd, Eigen::ArrayXXd> y_and_dy_simple =\n    SimplifyAndEvaluateWithDerivative(simple_stack, x, constants);\n  ASSERT_TRUE(testutils::almost_equal(y_and_dy.first, y_and_dy_simple.first));\n  ASSERT_TRUE(testutils::almost_equal(y_and_dy.first, y_and_dy_simple.first));\n}\n\nTEST_F(AGraphBackend, get_utilized_commands) {\n  std::vector<bool> used_commands = GetUtilizedCommands(simple_stack);\n  int num_used_commands = 0;\n  for (auto const &command_is_used : used_commands) {\n    if (command_is_used) {\n      ++num_used_commands;\n    }\n  }\n  ASSERT_EQ(num_used_commands, 8);\n}\n} // namespace\n", "meta": {"hexsha": "63fead5c085544db13b7908a5f814902902cbb10", "size": 8427, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/agraph_backend_tests.cpp", "max_stars_repo_name": "imikejackson/bingocpp", "max_stars_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T09:54:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T14:01:30.000Z", "max_issues_repo_path": "tests/agraph_backend_tests.cpp", "max_issues_repo_name": "imikejackson/bingocpp", "max_issues_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-08-29T19:12:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T22:17:53.000Z", "max_forks_repo_path": "tests/agraph_backend_tests.cpp", "max_forks_repo_name": "imikejackson/bingocpp", "max_forks_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-10-18T02:43:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T22:08:39.000Z", "avg_line_length": 32.4115384615, "max_line_length": 89, "alphanum_fraction": 0.6640560104, "num_tokens": 2513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.7025300636233415, "lm_q1q2_score": 0.6012611710630191}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\nnamespace dutyroll\n{\n\tEigen::MatrixXd rollduty_fixed(\n\t\tconst Eigen::VectorXd data,\n\t\tconst int window,\n\t\tconst Eigen::VectorXd thresholds);\n\n\tEigen::MatrixXd rollduty_variable(\n\t\tconst Eigen::VectorXd time,\n\t\tconst Eigen::VectorXd data,\n\t\tconst double window,\n\t\tconst Eigen::VectorXd thresholds);\n}\n", "meta": {"hexsha": "2de01c0286ec5f2c78e0382a22bf28dabd16e2fa", "size": 338, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rollduty.hpp", "max_stars_repo_name": "anthonytw/dutyroll", "max_stars_repo_head_hexsha": "489dd452ba614a2214756eba0831b33111187225", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-01-22T20:44:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-30T07:59:32.000Z", "max_issues_repo_path": "src/rollduty.hpp", "max_issues_repo_name": "anthonytw/dutyroll", "max_issues_repo_head_hexsha": "489dd452ba614a2214756eba0831b33111187225", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rollduty.hpp", "max_forks_repo_name": "anthonytw/dutyroll", "max_forks_repo_head_hexsha": "489dd452ba614a2214756eba0831b33111187225", "max_forks_repo_licenses": ["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.7777777778, "max_line_length": 36, "alphanum_fraction": 0.7514792899, "num_tokens": 78, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7025300698514778, "lm_q1q2_score": 0.6012611660613761}}
{"text": "#include <cmath>\n#include <stdexcept>\n\n#include <gtest/gtest.h>\n#include <Eigen/Dense>\n\n#include <BingoCpp/equation.h>\n#include <BingoCpp/fitness_function.h>\n#include <BingoCpp/training_data.h>\n\n#include \"test_fixtures.h\"\n#include \"testing_utils.h\"\n\nnamespace {\n\nconst double pi = std::acos(-1);\n\nstruct SampleTrainingData : public bingo::TrainingData {\n  Eigen::ArrayXXd x;\n  Eigen::ArrayXXd y;\n  SampleTrainingData() : TrainingData() {}\n  ~SampleTrainingData() {}\n  SampleTrainingData(Eigen::ArrayXXd &x, Eigen::ArrayXXd &y) : \n      x(x), y(y) { }\n  SampleTrainingData* GetItem(int) {\n    throw new std::logic_error(\"Not implemented Exception\");\n  }\n  SampleTrainingData* GetItem(const std::vector<int> &) {\n    throw new std::logic_error(\"Not implemented Exception\");\n  }\n  int Size() { return x.rows(); }\n};\n\nclass SampleFitnessFunction : public bingo::VectorBasedFunction {\n public:\n  SampleFitnessFunction(SampleTrainingData* training_data,\n      std::string metric = \"mae\") :\n      bingo::VectorBasedFunction(training_data, metric) {}\n  ~SampleFitnessFunction() {} \n  Eigen::ArrayXXd EvaluateFitnessVector(const bingo::Equation &individual) const {\n    Eigen::ArrayXXd f_of_x =\n        individual.EvaluateEquationAt(((SampleTrainingData*)training_data_)->x);\n    return f_of_x - ((SampleTrainingData*)training_data_)->y;\n  }\n};\n\nclass TestFitnessFunction : public testing::Test {\n public:\n  SampleTrainingData training_data_;\n  SampleFitnessFunction* sample_fitness_function_;\n  void SetUp() {\n    training_data_ = init_sample_training_data();\n    sample_fitness_function_ = new SampleFitnessFunction(&training_data_);\n  }\n\n  void TearDown() {\n    delete sample_fitness_function_;\n  }\n\n private:\n  SampleTrainingData init_sample_training_data() {\n    Eigen::ArrayXXd x(3,3);\n    x << ((1./6.) * pi), 1., 1.,\n         ((1./2.) * pi), 3., 4.,\n         pi            , 9., 16.;\n    Eigen::ArrayXXd y(3, 1);\n    y << 1.5, 2, 1;\n    SampleTrainingData training_data(x, y);\n    return training_data;\n  }\n};\n\nTEST_F(TestFitnessFunction, InvalidTrainingMetric) {\n  try {\n    SampleFitnessFunction test_function(&training_data_, \"invalid_metric\");\n    FAIL() << \"Expecting std::invalid_argument exception\\n\";\n  } catch (std::invalid_argument &exception) {\n    SUCCEED();\n  }\n}\n\nTEST_F(TestFitnessFunction, CorrectMetricSet) {\n  SampleFitnessFunction mse(&training_data_, \"mse\");\n  SampleFitnessFunction rmse(&training_data_, \"rmse\");\n  bingo::AGraph agraph = testutils::init_sample_agraph_1();\n  double mae_expected = 0.600018;\n  double mse_expected = 0.389427;\n  double rmse_expected = 0.624041;\n  double error_tol = 10e-6;\n  ASSERT_NEAR(mae_expected,\n              sample_fitness_function_->EvaluateIndividualFitness(agraph),\n              error_tol);\n  ASSERT_NEAR(mse_expected,\n              mse.EvaluateIndividualFitness(agraph),\n              error_tol);\n  ASSERT_NEAR(rmse_expected,\n              rmse.EvaluateIndividualFitness(agraph),\n              error_tol);\n}\n} // namespace (anonymous)", "meta": {"hexsha": "63d0749543f73e4d21e333a31b1af03a3e904c44", "size": 2997, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/fitness_function_tests.cpp", "max_stars_repo_name": "imikejackson/bingocpp", "max_stars_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T09:54:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-26T14:01:30.000Z", "max_issues_repo_path": "tests/fitness_function_tests.cpp", "max_issues_repo_name": "imikejackson/bingocpp", "max_issues_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2019-08-29T19:12:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-15T22:17:53.000Z", "max_forks_repo_path": "tests/fitness_function_tests.cpp", "max_forks_repo_name": "imikejackson/bingocpp", "max_forks_repo_head_hexsha": "6ba00a490c8cb46edebfd78f56b1604a76d668e9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-10-18T02:43:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-02T22:08:39.000Z", "avg_line_length": 29.97, "max_line_length": 82, "alphanum_fraction": 0.6973640307, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.7025300698514777, "lm_q1q2_score": 0.6012611557293744}}
{"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__IMPL__SE2_HPP_\n#define SMOOTH__IMPL__SE2_HPP_\n\n#include <Eigen/Core>\n\n#include \"common.hpp\"\n#include \"so2.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief SE(2) Lie Group represented as C^1 \u22c9 R^2\n *\n * Memory layout\n * -------------\n * Group:    x y qz qw\n * Tangent:  vx vy \u03a9z\n *\n * Lie group Matrix form\n * ---------------------\n * [ qw -qz x ]\n * [ qz  qw y ]\n * [  0   0 1 ]\n *\n * Lie algebra Matrix form\n * -----------------------\n * [ 0 -\u03a9z vx ]\n * [ \u03a9z  0 vy ]\n * [  0  0  0 ]\n *\n * Constraints\n * -----------\n * Group:   qz * qz + qw * qw = 1\n * Tangent: -pi < \u03a9z <= pi\n */\ntemplate<typename _Scalar>\nclass SE2Impl\n{\npublic:\n  using Scalar = _Scalar;\n\n  static constexpr Eigen::Index RepSize = 4;\n  static constexpr Eigen::Index Dim     = 3;\n  static constexpr Eigen::Index Dof     = 3;\n\n  SMOOTH_DEFINE_REFS;\n\n  static void setIdentity(GRefOut g_out) { g_out << Scalar(0), Scalar(0), Scalar(0), Scalar(1); }\n\n  static void setRandom(GRefOut g_out)\n  {\n    g_out.template head<2>().setRandom();\n    SO2Impl<Scalar>::setRandom(g_out.template tail<2>());\n  }\n\n  static void matrix(GRefIn g_in, MRefOut m_out)\n  {\n    m_out.setIdentity();\n    SO2Impl<Scalar>::matrix(g_in.template tail<2>(), m_out.template topLeftCorner<2, 2>());\n    m_out.template topRightCorner<2, 1>() = g_in.template head<2>();\n  }\n\n  static void composition(GRefIn g_in1, GRefIn g_in2, GRefOut g_out)\n  {\n    SO2Impl<Scalar>::composition(\n      g_in1.template tail<2>(), g_in2.template tail<2>(), g_out.template tail<2>());\n    Eigen::Matrix<Scalar, 2, 2> R1;\n    SO2Impl<Scalar>::matrix(g_in1.template tail<2>(), R1);\n    g_out.template head<2>() = R1 * g_in2.template head<2>() + g_in1.template head<2>();\n  }\n\n  static void inverse(GRefIn g_in, GRefOut g_out)\n  {\n    Eigen::Matrix<Scalar, 2, 1> so2inv;\n    SO2Impl<Scalar>::inverse(g_in.template tail<2>(), so2inv);\n\n    Eigen::Matrix<Scalar, 2, 2> Rinv;\n    SO2Impl<Scalar>::matrix(so2inv, Rinv);\n\n    g_out.template head<2>() = -Rinv * g_in.template head<2>();\n    g_out.template tail<2>() = so2inv;\n  }\n\n  static void log(GRefIn g_in, TRefOut a_out)\n  {\n    using std::tan;\n\n    Eigen::Matrix<Scalar, 1, 1> so2_log;\n    SO2Impl<Scalar>::log(g_in.template tail<2>(), so2_log);\n    const Scalar th  = so2_log(0);\n    const Scalar th2 = th * th;\n\n    const Scalar B = th / Scalar(2);\n    Scalar A;\n    if (th2 < Scalar(eps2)) {\n      // https://www.wolframalpha.com/input/?i=series+x+%2F+tan+x+at+x%3D0\n      A = Scalar(1) - th2 / Scalar(12);\n    } else {\n      A = B / tan(B);\n    }\n\n    Eigen::Matrix<Scalar, 2, 2> Sinv;\n    Sinv(0, 0) = A;\n    Sinv(1, 1) = A;\n    Sinv(0, 1) = B;\n    Sinv(1, 0) = -B;\n\n    a_out.template head<2>() = Sinv * g_in.template head<2>();\n    a_out(2)                 = th;\n  }\n\n  static void Ad(GRefIn g_in, TMapRefOut A_out)\n  {\n    SO2Impl<Scalar>::matrix(g_in.template tail<2>(), A_out.template topLeftCorner<2, 2>());\n    A_out(0, 2) = g_in(1);\n    A_out(1, 2) = -g_in(0);\n    A_out(2, 0) = Scalar(0);\n    A_out(2, 1) = Scalar(0);\n    A_out(2, 2) = Scalar(1);\n  }\n\n  static void exp(TRefIn a_in, GRefOut g_out)\n  {\n    using std::cos, std::sin;\n\n    const Scalar th  = a_in.z();\n    const Scalar th2 = th * th;\n\n    Scalar A, B;\n    if (th2 < Scalar(eps2)) {\n      // https://www.wolframalpha.com/input/?i=series+sin+x+%2F+x+at+x%3D0\n      A = Scalar(1) - th2 / Scalar(6);\n      // https://www.wolframalpha.com/input/?i=series+%28cos+x+-+1%29+%2F+x+at+x%3D0\n      B = -th / Scalar(2) + th * th2 / Scalar(24);\n    } else {\n      A = sin(th) / th;\n      B = (cos(th) - Scalar(1)) / th;\n    }\n\n    Eigen::Matrix<Scalar, 2, 2> S;\n    S(0, 0) = A;\n    S(1, 1) = A;\n    S(0, 1) = B;\n    S(1, 0) = -B;\n\n    g_out.template head<2>() = S * a_in.template head<2>();\n    SO2Impl<Scalar>::exp(a_in.template tail<1>(), g_out.template tail<2>());\n  }\n\n  static void hat(TRefIn a_in, MRefOut A_out)\n  {\n    A_out.setZero();\n    SO2Impl<Scalar>::hat(a_in.template tail<1>(), A_out.template topLeftCorner<2, 2>());\n    A_out.template topRightCorner<2, 1>() = a_in.template head<2>();\n  }\n\n  static void vee(MRefIn A_in, TRefOut a_out)\n  {\n    SO2Impl<Scalar>::vee(A_in.template topLeftCorner<2, 2>(), a_out.template tail<1>());\n    a_out.template head<2>() = A_in.template topRightCorner<2, 1>();\n  }\n\n  static void ad(TRefIn a_in, TMapRefOut A_out)\n  {\n    A_out.setZero();\n    SO2Impl<Scalar>::hat(a_in.template tail<1>(), A_out.template topLeftCorner<2, 2>());\n    A_out(0, 2) = a_in.y();\n    A_out(1, 2) = -a_in.x();\n  }\n\n  static void dr_exp(TRefIn a_in, TMapRefOut A_out)\n  {\n    using TangentMap = Eigen::Matrix<Scalar, 3, 3>;\n    using std::sin, std::cos;\n\n    const Scalar th2 = a_in.z() * a_in.z();\n\n    Scalar A, B;\n    if (th2 < Scalar(eps2)) {\n      // https://www.wolframalpha.com/input/?i=series+%281-cos+x%29+%2F+x%5E2+at+x%3D0\n      A = Scalar(1) / Scalar(2) - th2 / Scalar(24);\n      // https://www.wolframalpha.com/input/?i=series+%28x+-+sin%28x%29%29+%2F+x%5E3+at+x%3D0\n      B = Scalar(1) / Scalar(6) - th2 / Scalar(120);\n    } else {\n      const Scalar th = a_in.z();\n      A               = (Scalar(1) - cos(th)) / th2;\n      B               = (th - sin(th)) / (th2 * th);\n    }\n\n    TangentMap ad_a;\n    ad(a_in, ad_a);\n    A_out = TangentMap::Identity() - A * ad_a + B * ad_a * ad_a;\n  }\n\n  static void dr_expinv(TRefIn a_in, TMapRefOut A_out)\n  {\n    using TangentMap = Eigen::Matrix<Scalar, 3, 3>;\n    using std::sin, std::cos;\n\n    const Scalar th  = a_in.z();\n    const Scalar th2 = th * th;\n\n    Scalar A;\n    if (th2 < Scalar(eps2)) {\n      // https://www.wolframalpha.com/input/?i=series+1%2Fx%5E2+-+%281+%2B+cos+x%29+%2F+%282+*+x+*+sin+x%29+at+x%3D0\n      A = Scalar(1) / Scalar(12) + th2 / Scalar(720);\n    } else {\n      A = (Scalar(1) / th2) - (Scalar(1) + cos(th)) / (Scalar(2) * th * sin(th));\n    }\n\n    TangentMap ad_a;\n    ad(a_in, ad_a);\n    A_out = TangentMap::Identity() + ad_a / 2 + A * ad_a * ad_a;\n  }\n};\n\n}  // namespace smooth\n\n#endif  // SMOOTH__IMPL__SE2_HPP_\n", "meta": {"hexsha": "8a06019dd7e7f45e61e314f5c580f04449ad390c", "size": 7229, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/internal/se2.hpp", "max_stars_repo_name": "NamDinhRobotics/smooth", "max_stars_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:18.000Z", "max_issues_repo_path": "include/smooth/internal/se2.hpp", "max_issues_repo_name": "NamDinhRobotics/smooth", "max_issues_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/internal/se2.hpp", "max_forks_repo_name": "NamDinhRobotics/smooth", "max_forks_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.506122449, "max_line_length": 116, "alphanum_fraction": 0.6083829022, "num_tokens": 2381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511616741041, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.601261155071946}}
{"text": "#include <boost/math/special_functions/bessel.hpp>\n\n/**\n * Bessel J_0 function\n * \n * @param  n index\n * @param x argument\n * @return value\n */\nextern \"C\"\ndouble j0(double x) {\n    return boost::math::cyl_bessel_j<int, double>(0, x);\n}\n\n/**\n * Bessel Y_0 function\n * \n * @param  n index\n * @param x argument\n * @return value\n */\nextern \"C\"\ndouble y0(double x) {\n    return boost::math::cyl_neumann<int, double>(0, x);\n}\n\n/**\n * Bessel J_1 function\n * \n * @param  n index\n * @param x argument\n * @return value\n */\nextern \"C\"\ndouble j1(double x) {\n    return boost::math::cyl_bessel_j<int, double>(1, x);\n}\n\n/**\n * Bessel Y_1 function\n * \n * @param  n index\n * @param x argument\n * @return value\n */\nextern \"C\"\ndouble y1(double x) {\n    return boost::math::cyl_neumann<int, double>(1, x);\n}\n", "meta": {"hexsha": "92c540017379d90bd68c25409b95919262d2e2c2", "size": 789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "numba/src/bessel_funcs.cpp", "max_stars_repo_name": "pletzer/scatter", "max_stars_repo_head_hexsha": "0d747a47b28e4d1be0a0268cf46204f61a6dd527", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-01T06:49:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-05T19:47:05.000Z", "max_issues_repo_path": "numba/src/bessel_funcs.cpp", "max_issues_repo_name": "pletzer/scatter", "max_issues_repo_head_hexsha": "0d747a47b28e4d1be0a0268cf46204f61a6dd527", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-19T02:06:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-27T08:57:08.000Z", "max_forks_repo_path": "numba/src/bessel_funcs.cpp", "max_forks_repo_name": "pletzer/scatter", "max_forks_repo_head_hexsha": "0d747a47b28e4d1be0a0268cf46204f61a6dd527", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-21T03:58:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-19T01:53:46.000Z", "avg_line_length": 15.78, "max_line_length": 56, "alphanum_fraction": 0.6235741445, "num_tokens": 253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.6012260450786617}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#define NT2_UNIT_MODULE \"nt2 integration toolbox - quad\"\n\n#include <iostream>\n#include <nt2/sdk/timing/tic.hpp>\n#include <nt2/include/functions/quad.hpp>\n#include <nt2/toolbox/integration/output.hpp>\n#include <nt2/toolbox/integration/options.hpp>\n#include <nt2/sdk/unit/tests.hpp>\n#include <nt2/sdk/unit/module.hpp>\n#include <boost/fusion/tuple.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/bind.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/rowvect.hpp>\n#include <nt2/include/functions/exp.hpp>\n#include <nt2/include/functions/expm1.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/globalsum.hpp>\n#include <nt2/include/functions/globalmax.hpp>\n#include <nt2/include/functions/dist.hpp>\n#include <nt2/include/functions/ones.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/sqrteps.hpp>\n#include <nt2/table.hpp>\nstruct f\n{\n  template < class X > inline\n  X operator()(const X & x ) const\n  {\n    return x;\n  }\n};\n\n\nNT2_TEST_CASE_TPL( quad_functor, NT2_REAL_TYPES )\n{\n  using nt2::quad;\n  using nt2::options;\n  using nt2::integration::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  tab_t x = nt2::_(T(0), T(5));\n  NT2_DISPLAY(x);\n  //output<tab_t,T>\n  nt2::tic();\n  BOOST_AUTO_TPL(res, quad<T>(f(), x));\n  nt2::toc();\n//                                  ,\n//                                   options [ nt2::iterations_ = 100,\n//                                             nt2::tolerance::absolute_ = T(0.001)\n//                                     ]);\n\n   std::cout << \"Integrals:\" << res.integrals << \") = \" << res.errors\n             << \" after \" << res.eval_count <<  \" evaluations\\n\";\n\n   NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::dist(res.integrals, nt2::sqr(x)*nt2::Half<T>())), nt2::Sqrteps<T>());\n\n\n}\n\nNT2_TEST_CASE_TPL( quad_tag, NT2_REAL_TYPES )\n{\n  using nt2::quad;\n  using nt2::options;\n  using nt2::integration::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  tab_t x = nt2::_(T(0), T(5));\n  NT2_DISPLAY(x);\n  //output<tab_t,T>\n  BOOST_AUTO_TPL(res, quad<T>(nt2::functor<nt2::tag::exp_>(), x));\n//                                  ,\n//                                   options [ nt2::iterations_ = 100,\n//                                             nt2::tolerance::absolute_ = T(0.001)\n//                                     ]);\n\n   std::cout << \"Integrals: \" << res.integrals << \" with \" << res.errors\n             << \" after \" << res.eval_count <<  \" evaluations\\n\";\n\n   NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::dist(res.integrals, nt2::expm1(x))), nt2::Sqrteps<T>());\n\n\n}\nNT2_TEST_CASE_TPL( quad_tag_reverse, NT2_REAL_TYPES )\n{\n  using nt2::quad;\n  using nt2::options;\n  using nt2::integration::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n  tab_t x = nt2::_(T(5), T(-1), T(0));\n  NT2_DISPLAY(x);\n  //output<tab_t,T>\n  BOOST_AUTO_TPL(res, quad<T>(nt2::functor<nt2::tag::exp_>(), x));\n//                                  ,\n//                                   options [ nt2::iterations_ = 100,\n//                                             nt2::tolerance::absolute_ = T(0.001)\n//                                     ]);\n\n  std::cout << \"Integrals: \" << res.integrals << \" with \" << res.errors\n            << \" after \" << res.eval_count <<  \" evaluations\\n\";\n\n  NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::dist(res.integrals, nt2::exp(x)-nt2::exp(T(5)))), nt2::Sqrteps<T>());\n\n\n}\n\nNT2_TEST_CASE_TPL( quad_2, NT2_REAL_TYPES )\n{\n  using nt2::quad;\n  using nt2::options;\n  using nt2::integration::output;\n  typedef nt2::table<T> tab_t;\n  typedef typename nt2::meta::as_logical<T>::type lT;\n   tab_t x = nt2::_(T(0), T(5), T(5));\n  NT2_DISPLAY(x);\n\n  nt2::tic();\n  BOOST_AUTO_TPL(res, quad<T>(nt2::functor<nt2::tag::exp_>(), T(0), T(5)\n                              ,\n                              options [ nt2::iterations_ = 100,\n                                        nt2::tolerance::absolute_ = T(1.0e-6)\n                                ]));\n  nt2::toc();\n  std::cout << \"Integrals: \" << res.integrals << \" with \" << res.errors\n            << \" after \" << res.eval_count <<  \" evaluations\\n\";\n\n  NT2_TEST_LESSER_EQUAL(nt2::globalmax(nt2::dist(res.integrals, expm1(x))), nt2::Sqrteps<T>());\n\n\n}\n", "meta": {"hexsha": "3048926c0581acf1b4260dfdb98f7e214b96a36b", "size": 4988, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/core/integration/unit/scalar/quad.cpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/integration/unit/scalar/quad.cpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/integration/unit/scalar/quad.cpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8811188811, "max_line_length": 114, "alphanum_fraction": 0.5587409783, "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6012253732261719}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef CLTV_PROBLEM_HPP_\n#define CLTV_PROBLEM_HPP_\n\n#include <Eigen/Dense>\n#include <cstdint>\n\nstruct CltvOcpDi\n{\n  // Must be defined\n  constexpr static double T = 1.;\n  constexpr static std::size_t nx = 2;\n  constexpr static std::size_t nu = 1;\n\n  // Custom types\n  using state_t = Eigen::Matrix<double, nx, 1>;\n  using input_t = Eigen::Matrix<double, nu, 1>;\n  using A_t = Eigen::Matrix<double, nx, nx>;\n  using B_t = Eigen::Matrix<double, nx, nu>;\n  using Q_t = Eigen::Matrix<double, nx, nx>;\n  using R_t = Eigen::Matrix<double, nu, nu>;\n\n  // Constants\n  const A_t A = (A_t() << 0., 1., 0., 0.).finished();\n  const B_t B = (B_t() << 0., 1.).finished();\n  const state_t E = (state_t() << 0., 0.).finished();\n  const Q_t Q = (Q_t() << 1000., 0., 0., 10.).finished();\n  const Q_t QT = (Q_t() << 100., 0., 0., 100.).finished();\n  const R_t R = (R_t() << 0.0001).finished();\n\n\n  void get_x0(Eigen::Ref<state_t> x0) const\n  {\n    x0 << 1., 0.;\n  }\n\n  void get_T(double & t) const\n  {\n    t = T;\n  }\n\n  void get_state_lb(double, Eigen::Ref<state_t> state_lb) const\n  {\n    state_lb <<\n      -1000.,\n      -1.;\n  }\n\n  void get_state_ub(double, Eigen::Ref<state_t> state_ub) const\n  {\n    state_ub <<\n      1000.,\n      1.;\n  }\n\n  void get_input_lb(double, Eigen::Ref<input_t> input_lb) const\n  {\n    input_lb << -1.;\n  }\n\n  void get_input_ub(double, Eigen::Ref<input_t> input_ub) const\n  {\n    input_ub << 1.;\n  }\n\n  const A_t & get_A(double) const\n  {\n    return A;\n  }\n\n  const B_t & get_B(double) const\n  {\n    return B;\n  }\n\n  const state_t & get_E(double) const\n  {\n    return E;\n  }\n\n  const Q_t & get_Q(double) const\n  {\n    return Q;\n  }\n\n  const R_t & get_R(double) const\n  {\n    return R;\n  }\n\n  const Q_t & get_QT() const\n  {\n    return QT;\n  }\n\n  state_t get_xldot(double) const {return state_t::Zero();}\n};\n\n#endif  // CLTV_PROBLEM_HPP_\n", "meta": {"hexsha": "1fdf58ddcdb0e100a1569a9add7f1144ca113c57", "size": 1954, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/cltv_problem.hpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/cltv_problem.hpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/cltv_problem.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.9708737864, "max_line_length": 64, "alphanum_fraction": 0.6013306039, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6012253709709339}}
{"text": "#ifndef newton_raphson_hpp\n#define newton_raphson_hpp 3141592\n\n\n#include <iostream>\n#include <Eigen/SparseCholesky>\n\n\ntemplate<typename U, typename V>\nvoid newton_raphson(U& F,V& J,VectorXd& x0,double tol)\n{\n  int it = 0;\n  int maxit = 1000;\n  double res = tol+1;\n  VectorXd x1,step;\n  SparseLU<SpMat> solver;\n  while(res > tol && it <maxit)\n  {\n    solver.analyzePattern(J(x0));\n    solver.factorize(J(x0));\n    x1 = x0- solver.solve(F(x0));\n    res = (x1-x0).squaredNorm();\n    x0 = x1;\n    std::cout << \"Residu: \"<< res << std::endl;\n    it += 1;\n  }\n}\n\ntemplate<typename U, typename V>\nvoid quasi_newton_raphson(U& F,V& J,VectorXd& x0,double tol)\n{\n  int it = 0;\n  int maxit = 1000;\n  double res = tol+1;\n  VectorXd x1,step;\n  SparseLU<SpMat> solver;\n  solver.analyzePattern(J(x0));\n  solver.factorize(J(x0));\n  while(res > tol && it <maxit)\n  {\n    x1 = x0- solver.solve(F(x0));\n    res = (x1-x0).squaredNorm();\n    x0 = x1;\n    std::cout << \"Residu: \"<< res << std::endl;\n    it += 1;\n  }\n}\n\n\n#endif\n", "meta": {"hexsha": "6b2b6206c5fe8255556479a0a2371043b19c84ea", "size": 1006, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/newton_raphson_sparse.hpp", "max_stars_repo_name": "PieterAppeltans/ProjectWIT", "max_stars_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/newton_raphson_sparse.hpp", "max_issues_repo_name": "PieterAppeltans/ProjectWIT", "max_issues_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/newton_raphson_sparse.hpp", "max_forks_repo_name": "PieterAppeltans/ProjectWIT", "max_forks_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7254901961, "max_line_length": 60, "alphanum_fraction": 0.6153081511, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6012253657571641}}
{"text": "#ifndef THREEDIMUTIL_MESH_HPP\n#define THREEDIMUTIL_MESH_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace threedimutil\n{\n    template <typename Scalar, typename UInt>\n    Eigen::Matrix<Scalar, 3, Eigen::Dynamic> CalcVertexNormals(const Eigen::Matrix<Scalar, 3, Eigen::Dynamic>& vertex_data,\n                                                               const Eigen::Matrix<UInt, 3, Eigen::Dynamic>&   index_data)\n    {\n        Eigen::Matrix<Scalar, 3, Eigen::Dynamic> normal_data = Eigen::Matrix<Scalar, 3, Eigen::Dynamic>::Zero(vertex_data.rows(), vertex_data.cols());\n\n        for (unsigned face = 0; face < index_data.cols(); ++face)\n        {\n            const auto& x_0 = vertex_data.col(index_data(0, face));\n            const auto& x_1 = vertex_data.col(index_data(1, face));\n            const auto& x_2 = vertex_data.col(index_data(2, face));\n\n            const auto area_scaled_face_normal = (x_1 - x_0).cross(x_2 - x_0);\n\n            normal_data.col(index_data(0, face)) += area_scaled_face_normal;\n            normal_data.col(index_data(1, face)) += area_scaled_face_normal;\n            normal_data.col(index_data(2, face)) += area_scaled_face_normal;\n        }\n\n        for (unsigned vertex = 0; vertex < vertex_data.cols(); ++vertex)\n        {\n            normal_data.col(vertex).normalize();\n        }\n\n        return normal_data;\n    }\n}\n\n#endif // THREEDIMUTIL_MESH_HPP\n", "meta": {"hexsha": "631df695b58514ab552be70821949323a200ca47", "size": 1401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/three-dim-util/mesh.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/mesh.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/mesh.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.8684210526, "max_line_length": 150, "alphanum_fraction": 0.6202712348, "num_tokens": 336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.7090191276365462, "lm_q1q2_score": 0.6012253603089636}}
{"text": "#ifndef FARHADIFARDIFFERENTIALFORCE_HPP_\n#define FARHADIFARDIFFERENTIALFORCE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n#include \"Exception.hpp\"\n\n#include \"AbstractForce.hpp\"\n#include \"VertexBasedCellPopulation.hpp\"\n#include \"CellLabel.hpp\"\n\n#include <iostream>\n\n/**\n * A force class for use in Vertex-based simulations. This force is based on the\n * Energy function proposed by Farhadifar et al in  Curr. Biol., 2007, 17, 2095-2104.\n */\n\n\ntemplate<unsigned DIM>\nclass FarhadifarDifferentialForce : public AbstractForce<DIM>\n{\nfriend class TestForces;\n\nprivate:\n\n    friend class boost::serialization::access;\n    /**\n     * Boost Serialization method for archiving/checkpointing.\n     * Archives the object and its member variables.\n     *\n     * @param archive  The boost archive.\n     * @param version  The current version of this class.\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        archive & boost::serialization::base_object<AbstractForce<DIM> >(*this);\n        archive & mCellAreaElasticityParameter;\n        archive & mLabelledCellAreaElasticityParameter;\n        archive & mCellPerimeterContractilityParameter;\n        archive & mLabelledCellPerimeterContractilityParameter;\n        archive & mCellCellLineTensionParameter;\n        archive & mLabelledCellLabelledCellLineTensionParameter;\n        archive & mLabelledCellCellLineTensionParameter;\n        archive & mCellBoundaryLineTensionParameter;\n        archive & mLabelledCellBoundaryLineTensionParameter;\n    }\n\nprotected:\n\n    /**\n     * The strength of the area term in the model. Corresponds to K_alpha in\n     * Farhadifar's paper.\n     */\n    double mCellAreaElasticityParameter;\n\n    /**\n     * The strength of the area term in the model for a labelled cell.\n     * */\n    double mLabelledCellAreaElasticityParameter;\n\n    /**\n     * The strength of the perimeter term in the model. Corresponds to\n     * Gamma_alpha in Farhadifar's paper.\n     */\n    double mCellPerimeterContractilityParameter;\n\n    /**\n     * The strength of the perimeter term in the model for a labelled cell.\n     */\n    double mLabelledCellPerimeterContractilityParameter;\n\n    /**\n     * The strength of the cell-cell line tension between two cells.\n     * Lambda_{i,j} in Farhadifar's paper.\n     */\n    double mCellCellLineTensionParameter;\n\n    /**\n     * The strength of the cell-cell line tension between two labelled cells.\n     */\n    double mLabelledCellLabelledCellLineTensionParameter;\n\n    /**\n     * The strength of the cell-cell line tension between a labelled and\n     * non-labelled cell.\n     */\n    double mLabelledCellCellLineTensionParameter;\n\n    /**\n     * The strength of the line tension at the boundary. This term does\n     * correspond to Lambda_{i,j} in Farhadifar's paper.\n     */\n    double mCellBoundaryLineTensionParameter;\n\n    /**\n     * The strength of the line tension at the boundary for labelled cells.\n     */\n    double mLabelledCellBoundaryLineTensionParameter;\n\npublic:\n\n    /**\n     * Constructor.\n     */\n    FarhadifarDifferentialForce();\n\n    /**\n     * Destructor.\n     */\n    virtual ~FarhadifarDifferentialForce() override;\n\n    /**\n     * Overridden AddForceContribution() method.\n     *\n     * Calculates the force on each node in the vertex-based cell population based on the energy function\n     * Farhadifar's model.\n     *\n     * @param rCellPopulation reference to the cell population\n     */\n    virtual void AddForceContribution(AbstractCellPopulation<DIM>& rCellPopulation) override;\n\n    /**\n     * Get the line tension parameter for the edge between two given nodes.\n     *\n     * @param pNodeA one node\n     * @param pNodeB the other node\n     * @param rVertexCellPopulation reference to the cell population\n     *\n     * @return the line tension parameter for this edge.\n     */\n    double GetLineTensionParameter(Node<DIM>* pNodeA, Node<DIM>* pNodeB, VertexBasedCellPopulation<DIM>& rVertexCellPopulation);\n\n    /**\n     * @return mCellAreaElasticityParameter\n     */\n    double GetCellAreaElasticityParameter();\n\n    /**\n     * @return mLabelledCellAreaElasticityParameter\n     */\n    double GetLabelledCellAreaElasticityParameter();\n\n    /**\n     * @return mCellPerimeterContractilityParameter\n     */\n    double GetCellPerimeterContractilityParameter();\n\n    /**\n     * @return mLabelledCellPerimeterContractilityParameter\n     */\n    double GetLabelledCellPerimeterContractilityParameter();\n\n    /**\n     * @return mCellCellLineTensionParameter\n     */\n    double GetCellCellLineTensionParameter();\n\n    /**\n     * @return mLabelledCellLabelledCellLineTensionParameter\n     */\n    double GetLabelledCellLabelledCellLineTensionParameter();\n\n    /**\n     * @return mLabelledCellCellLineTensionParameter\n     */\n    double GetLabelledCellCellLineTensionParameter();\n\n    /**\n     * @return mCellBoundaryLineTensionParameter\n     */\n    double GetCellBoundaryLineTensionParameter();\n\n    /**\n     * @return mLabelledCellBoundaryLineTensionParameter\n     */\n    double GetLabelledCellBoundaryLineTensionParameter();\n\n    /**\n     * Set mCellAreaElasticityParameter.\n     *\n     * @param cellAreaElasticityParameter the new value of\n     * mCellAreaElasticityParameter\n     */\n    void SetCellAreaElasticityParameter(double cellAreaElasticityParameter);\n\n    /**\n     * Set mLabelledCellAreaElasticityParameter.\n     *\n     * @param labelledCellAreaElasticityParameter the new value of\n     * mLabelledCellAreaElasticityParameter\n     */\n    void SetLabelledCellAreaElasticityParameter(double labelledCellAreaElasticityParameter);\n\n    /**\n     * Set mCellPerimeterContractilityParameter.\n     *\n     * @param cellPerimeterContractilityParameter the new value of\n     * cellPerimeterContractilityParameter\n     */\n    void SetCellPerimeterContractilityParameter(double cellPerimeterContractilityParameter);\n\n    /**\n     * Set mLabelledCellPerimeterContractilityParameter.\n     *\n     * @param labelledCellPerimeterContractilityParameter the new value of\n     * labelledCellPerimeterContractilityParameter\n     */\n    void SetLabelledCellPerimeterContractilityParameter(\n            double labelledCellPerimeterContractilityParameter);\n\n    /**\n     * Set mCellCellLineTensionParameter.\n     *\n     * @param cellLineTensionParameter the new value of mCellCellLineTensionParameter\n     */\n    void SetCellCellLineTensionParameter(double cellCellLineTensionParameter);\n\n    /**\n     * Set mLabelledCellLabelledCellLineTensionParameter.\n     *\n     * @param labelledCellLabelledCellLineTensionParameter the new value of\n     * mLabelledCellLabelledCellLineTensionParameter\n     */\n    void SetLabelledCellLabelledCellLineTensionParameter(\n            double labelledCellLabelledCellLineTensionParameter);\n\n    /**\n     * Set mLabelledCellCellLineTensionParameter.\n     *\n     * @param labelledCellCellLineTensionParameter the new value of\n     * mLabelledCellCellLineTensionParameter\n     */\n    void SetLabelledCellCellLineTensionParameter(\n            double labelledCellCellLineTensionParameter);\n\n    /**\n     * Set mCellBoundaryLineTensionParameter.\n     *\n     * @param cellBoundaryLineTensionParameter the new value of mCellBoundaryLineTensionParameter\n     */\n    void SetCellBoundaryLineTensionParameter(double cellBoundaryLineTensionParameter);\n\n    /**\n     * Set mLabelledCellBoundaryLineTensionParameter.\n     *\n     * @param labelledCellBoundaryLineTensionParameter the new value of\n     * mLabelledCellBoundaryLineTensionParameter\n     */\n    void SetLabelledCellBoundaryLineTensionParameter(\n            double labelledCellBoundaryLineTensionParameter);\n\n    /**\n     * Overridden OutputForceParameters() method.\n     *\n     * @param rParamsFile the file stream to which the parameters are output\n     */\n    void OutputForceParameters(out_stream& rParamsFile);\n};\n\n#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_SAME_DIMS(FarhadifarDifferentialForce)\n\n#endif /*FARHADIFARDIFFERENTIALFORCE_HPP_*/\n", "meta": {"hexsha": "9ba44a2b3233eec42fce82178479709d668f7e6d", "size": 8047, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vertex/src/FarhadifarDifferentialForce.hpp", "max_stars_repo_name": "ThomasPak/cell-competition", "max_stars_repo_head_hexsha": "bb058d67e297d95c4c8ff2a0aea5b1fe5a82be09", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vertex/src/FarhadifarDifferentialForce.hpp", "max_issues_repo_name": "ThomasPak/cell-competition", "max_issues_repo_head_hexsha": "bb058d67e297d95c4c8ff2a0aea5b1fe5a82be09", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vertex/src/FarhadifarDifferentialForce.hpp", "max_forks_repo_name": "ThomasPak/cell-competition", "max_forks_repo_head_hexsha": "bb058d67e297d95c4c8ff2a0aea5b1fe5a82be09", "max_forks_repo_licenses": ["BSD-3-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.2518796992, "max_line_length": 128, "alphanum_fraction": 0.7225052815, "num_tokens": 1835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.7090191214879991, "lm_q1q2_score": 0.6012253550951938}}
{"text": "#define BOOST_TEST_MAIN\n#include <boost/test/included/unit_test.hpp>\n#include <srook/math/matrix.hpp>\n\nBOOST_AUTO_TEST_SUITE(srook_math_matrix_test)\n\nnamespace sm = srook::math;\nnamespace stv = srook::tmpl::vt;\n\nBOOST_AUTO_TEST_CASE(matrix_construct)\n{\n    typedef sm::row<int, int> r2;\n    typedef stv::transfer_t<sm::matrix, stv::replicate_t<2, stv::transfer_t<sm::row, stv::replicate_t<2, int>>>> mtx2x2_int; // 2 x 2, int matrix type\n\n    constexpr mtx2x2_int m1 {\n       r2{ 1, 3 },\n       r2{ 4, 2 }\n    };\n    SROOK_ATTRIBUTE_UNUSED constexpr auto m2 = m1;\n\n    constexpr mtx2x2_int m3 { // initialized as like the above.\n        1, 3,\n        4, 2\n    };\n    SROOK_ST_ASSERT(m1 == m2 && m1 == m3);\n}\n\n/*\n\nint main()\n{\n    constexpr srook::math::matrix<\n        srook::math::row<int, int, int, int>,\n        srook::math::row<int, int, int, int>,\n        srook::math::row<int, int, int, int>,\n        srook::math::row<int, int, int, int>\n    > m1 {\n        1, 2, 7, 6,\n        2, 4, 4, 2,\n        1, 8, 5, 2,\n        2, 4, 3, 3\n    };\n\n    constexpr auto res = m1.compute_equations(srook::math::make_vector(6, 2, 12, 5), srook::math::gaussian_elimination_eq());\n    std::cout << res << std::endl;\n\n    constexpr srook::math::matrix<\n        srook::math::row<int, int, int>,\n        srook::math::row<int, int, int>,\n        srook::math::row<int, int, int>\n    > m2 {\n        2, 2, 1,\n        3, 0, 2,\n        4, 3, 2\n    };\n    constexpr auto inv = m2.inverse();\n    std::cout << inv << std::endl;\n\n    constexpr auto det = m2.determinant();\n    std::cout << det << std::endl;\n}*/\n\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "6736eee0d1f4788ae6cd6892c9d4b8436a398275", "size": 1615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/math/matrix/test1.cpp", "max_stars_repo_name": "falgon/srookCppLibraries", "max_stars_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-01T07:54:37.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-01T07:54:37.000Z", "max_issues_repo_path": "tests/math/matrix/test1.cpp", "max_issues_repo_name": "falgon/srookCppLibraries", "max_issues_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/math/matrix/test1.cpp", "max_forks_repo_name": "falgon/srookCppLibraries", "max_forks_repo_head_hexsha": "ebcfacafa56026f6558bcd1c584ec774cc751e57", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.234375, "max_line_length": 150, "alphanum_fraction": 0.5789473684, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.6012089408157472}}
{"text": "/*!\n     \\brief Complex a template implementation for complex arithmetics\n        Copyright (C) 2012 Sebastian Schlenkrich\n        Version 1.0\n*/\n\n#ifndef Cpx_Complex_hpp\n#define Cpx_Complex_hpp\n\n\n//#define _USE_MATH_DEFINES // for Visual Studio\n\n#include <iostream>\n#include <iomanip>\n\n#include <map>\n#include <vector>\n#include <iterator>\n//#include <cmath>\n#include <complex>\n\n//#define DEBUG              // low-level io debugging\n//#define EXECUTABLE               // compile example and main function\n#define MS_VISUAL_STUDIO     // math functions not in global scope\n\n\n#ifdef MS_VISUAL_STUDIO\n    #include <boost/math/special_functions/erf.hpp>\n#endif\n\n\nnamespace Cpx {\n\n#ifdef DEBUG\n    #define MSG(msg_stream) std::cerr << msg_stream << std::endl ;\n#else\n    #define MSG(msg_stream)\n#endif\n\n#ifdef MS_VISUAL_STUDIO\n    //! Some compilers don't find intrinsic double functions\n    inline double exp(double x) { return std::exp(x); }\n    inline double log(double x) { return std::log(x); }\n    inline double sqrt(double x) { return std::sqrt(x); }\n    inline double sin(double x) { return std::sin(x); }\n    inline double cos(double x) { return std::cos(x); }\n    inline double tan(double x) { return std::tan(x); }\n    inline double atan2(double y, double x) { return std::atan2(y,x); }\n    inline double erf(double x)     { return boost::math::erf(x); }\n    inline double erf_inv(double x) { return boost::math::erf_inv(x); }\n#endif\n\n    //! Variable defines the class template for derivative evaluations\n    template <class Type = double>\n    class Complex {\n    protected:\n        Type real_;\n        Type imag_;\n    public:\n        //! \"standard\" constructor\n        Complex( const Type& real, const Type& imag) : real_(real), imag_(imag) {}\n        //! Type conversion constructor\n        Complex( const Type& real) : real_(real), imag_(0) {}\n        //! no standard constructor and default copy constructor\n        //! inspectors\n        const Type& real()  const { return real_;  }\n        const Type& imag() const { return imag_; }\n        //! IO steaming\n        //! Apply IO to the real and imaginary component\n        inline friend std::ostream& operator << (std::ostream &output, const Complex<Type> &x) {\n            return output << \"(\" << x.real_ << \",\" << x.imag_ << \")\";\n        }\n        //! Intrinsic functions\n        inline friend Complex<Type> exp(const Complex<Type> &x) {\n            Type r = exp(x.real_);\n            return Complex<Type>( r*cos(x.imag_), r*sin(x.imag_) );\n        }\n        inline friend Complex<Type> log(const Complex<Type> &x) {\n            return Complex<Type>( 0.5*log(x.real_*x.real_ + x.imag_*x.imag_), atan2(x.imag_,x.real_) );\n        }\n        inline friend Complex<Type> sqrt(const Complex<Type> &x) {\n            if (x.imag_==0) {\n                if (x.real_<0) return Complex<Type>( 0, sqrt(-x.real_) );\n                else           return Complex<Type>( sqrt(x.real_), 0 );\n            }\n            if (x.real_==0) {\n                if (x.imag_<0) {\n                    Type tmp  = sqrt(-x.imag_)*M_SQRT1_2;\n                    return Complex<Type>( tmp, -tmp );\n                } else {\n                    Type tmp  = sqrt(x.imag_)*M_SQRT1_2;\n                    return Complex<Type>( tmp, tmp );\n                }\n            }\n            Type sqr_r  = sqrt(sqrt(x.real_*x.real_ + x.imag_*x.imag_));\n            Type phi_2  = atan2(x.imag_,x.real_) / 2;\n            return Complex<Type>( sqr_r*cos(phi_2), sqr_r*sin(phi_2) );\n        }\n\n        //! Unary operators\n        inline friend Complex<Type> operator + (const Complex<Type> &x ) {\n            return x;\n        }\n        inline friend Complex<Type> operator - (const Complex<Type> &x ) {\n            return Complex<Type>( -x.real_, -x.imag_ );\n        }\n        //! Binary operators\n        //! Complex x Complex\n        inline friend Complex<Type> operator + (const Complex<Type> &x, const Complex<Type> &y ) {\n            return Complex<Type>( x.real_ + y.real_, x.imag_ + y.imag_ );\n        }\n        inline friend Complex<Type> operator - (const Complex<Type> &x, const Complex<Type> &y ) {\n            return Complex<Type>( x.real_ - y.real_, x.imag_ - y.imag_ );\n        }\n        inline friend Complex<Type> operator * (const Complex<Type> &x, const Complex<Type> &y ) {\n            return Complex<Type>( x.real_*y.real_ - x.imag_*y.imag_, x.real_*y.imag_ + x.imag_*y.real_ );\n        }\n        inline friend Complex<Type> operator / (const Complex<Type> &x, const Complex<Type> &y ) {\n            Type den = y.real_*y.real_ + y.imag_*y.imag_;\n            return Complex<Type>( (x.real_*y.real_ + x.imag_*y.imag_)/den,\n                          (x.imag_*y.real_ - x.real_*y.imag_)/den );\n        }\n        //! Complex x Type\n        inline friend Complex<Type> operator + (const Complex<Type> &x, const Type &y ) {\n            return Complex<Type>( x.real_ + y, x.imag_ );\n        }\n        inline friend Complex<Type> operator - (const Complex<Type> &x, const Type &y ) {\n            return Complex<Type>( x.real_ - y, x.imag_ );\n        }\n        inline friend Complex<Type> operator * (const Complex<Type> &x, const Type &y ) {\n            return Complex<Type>( x.real_*y, x.imag_*y );\n        }\n        inline friend Complex<Type> operator / (const Complex<Type> &x, const Type &y ) {\n            return Complex<Type>( x.real_/y, x.imag_/y );\n        }\n        //! Type x Complex\n        inline friend Complex<Type> operator + (const Type &x, const Complex<Type> &y ) {\n            return Complex<Type>( x + y.real_, y.imag_ );\n        }\n        inline friend Complex<Type> operator - (const Type &x, const Complex<Type> &y ) {\n            return Complex<Type>( x - y.real_, -y.imag_ );\n        }\n        inline friend Complex<Type> operator * (const Type &x, const Complex<Type> &y ) {\n            return Complex<Type>( x*y.real_, x*y.imag_ );\n        }\n        inline friend Complex<Type> operator / (const Type &x, const Complex<Type> &y ) {\n            Type den = y.real_*y.real_ + y.imag_*y.imag_;\n            return Complex<Type>( x*y.real_/den, -x*y.imag_/den );\n        }\n    };\n    \n    //! Type x Complex\n    template <class Type>\n    inline Complex<Type> operator + (const double &x, const Complex<Type> &y ) {\n        return Complex<Type>( x + y.real(), y.imag() );\n    }\n    template <class Type>\n    inline Complex<Type> operator - (const double &x, const Complex<Type> &y ) {\n        return Complex<Type>( x - y.real(), -y.imag() );\n    }\n    template <class Type>\n    inline Complex<Type> operator * (const double &x, const Complex<Type> &y ) {\n        return Complex<Type>( x*y.real(), x*y.imag() );\n    }\n    template <class Type>\n    inline Complex<Type> operator / (const double &x, const Complex<Type> &y ) {\n        Type den = y.real()*y.real() + y.imag()*y.imag();\n        return Complex<Type>( x*y.real()/den, -x*y.imag()/den );\n    }\n\n    \n}   // namespace Cpx\n\n#endif   // Cpx_Complex_hpp\n\n#ifdef EXECUTABLE\n\nint main() {\n    typedef Cpx::Complex<double> complex;\n    //typedef std::complex<double> complex;\n    \n    std::cout << \"Cpx Complex (C) Sebastian Schlenktich (2012)\"<< std::endl;\n    std::cout << std::endl;\n    \n    complex a(0,4), b(1,2);\n    complex c(0); // = a/b;\n    c = a + complex(5.0);\n    std::cout << \"c = \" << (c = sqrt(a)) << std::endl;\n    double z;\n    std::cout << (z = atan2(-1,-1)) << std::endl;\n    \n    return 0;\n}\n\n#endif   // EXECUTABLE\n\n/*  Example output\n\n\n*/\n", "meta": {"hexsha": "9cee6970ffa07f9677b8ff15f7c29359df4afd18", "size": 7461, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/templatemodels/auxilliaries/complexT.hpp", "max_stars_repo_name": "sschlenkrich/quantlib", "max_stars_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/experimental/templatemodels/auxilliaries/complexT.hpp", "max_issues_repo_name": "sschlenkrich/quantlib", "max_issues_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/templatemodels/auxilliaries/complexT.hpp", "max_forks_repo_name": "sschlenkrich/quantlib", "max_forks_repo_head_hexsha": "ff39ad2cd03d06d185044976b2e26ce34dca470c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1194029851, "max_line_length": 105, "alphanum_fraction": 0.5685564938, "num_tokens": 1886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6992544210587585, "lm_q1q2_score": 0.6011236831962273}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_SQRT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SQRT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing sqrt capabilities\n\n    Computes the square root of its parameter. For integers it is the\n    truncation of the real square root.\n\n    @par semantic:\n    For any given value @c x of type @c T:\n\n    @code\n    T r = sqrt(x);\n    @endcode\n\n    @par Decorators\n\n    - std_ calls std::sqrt\n\n    - raw_ for floating entries can gain some speed with less accuracy on some architectures.\n\n  **/\n  Value sqrt(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sqrt.hpp>\n#include <boost/simd/function/simd/sqrt.hpp>\n\n#endif\n", "meta": {"hexsha": "a0e8103d076e11b0aded4c1a58697bb2dd232746", "size": 1146, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/sqrt.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "include/boost/simd/function/sqrt.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/sqrt.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 23.875, "max_line_length": 100, "alphanum_fraction": 0.5916230366, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6011236724205843}}
{"text": "#include <boost/test/unit_test.hpp>\n\n#include <ayla/geometry/triangle.hpp>\n#include <ayla/geometry/vector.hpp>\n\nBOOST_AUTO_TEST_SUITE(ayla)\nBOOST_AUTO_TEST_SUITE(triangle)\n\nBOOST_AUTO_TEST_CASE( basicTest ) {\n\tTriangle t0(glm::vec3(-11, 0, 0), glm::vec3(0, 11, 0), glm::vec3(22,-11, 0));\n\t\n\tBOOST_CHECK(glm::epsilonEqual(t0.calculatePerimeter(), 81.4541f, 0.001f));\n\tBOOST_CHECK(glm::epsilonEqual(t0.calculateArea(), 242.0f, 0.001f));\n\t\n\tBOOST_CHECK(epsilonEqual(t0.getNormal(), -glm::vec3(0,0,1), 0.0000001f));\n}\n\nBOOST_AUTO_TEST_CASE( barymetric_coordinates_coplanar ) {\n\tglm::vec3 A(-3, -4, 0);\n\tglm::vec3 B(0, 5, 0);\n\tglm::vec3 C(3, -4, 0);\n\tTriangle t0(A,B,C);\n\t\n\tglm::vec3 P(0.0f,0.0f,0.0f);\n\tFloat a, b, c;\n\tt0.getBarycentricCoordinates(P, a, b, c);\n\tglm::vec3 result = a*A + b*B + c*C;\n\t\n\tBOOST_CHECK(isZero(result.x));\n\tBOOST_CHECK(isZero(result.y));\n\tBOOST_CHECK(isZero(result.z));\n\t\n\tglm::vec3 halfEdge = (B-A);\n\thalfEdge /= 2;\n\tP = A + halfEdge;\n\tt0.getBarycentricCoordinates(P, a, b, c);\n\t\n\tBOOST_CHECK_CLOSE( a, 1/2.0f, 0.00001f );\n\tBOOST_CHECK_CLOSE( b, 1/2.0f, 0.00001f );\n\tBOOST_CHECK_CLOSE( c, 0.0f, 0.00001f );\t\n}\n\nBOOST_AUTO_TEST_CASE( closest_point_coplanar ) {\n\tglm::vec3 A(-3, -4, 0);\n\tglm::vec3 B(0, 5, 0);\n\tglm::vec3 C(3, -4, 0);\n\tTriangle t0(A,B,C);\n\tFloat a, b, c;\n\t\n\t//Point is inside the triangle\n\tglm::vec3 P(0,0,0);\n\tglm::vec3 closest = t0.getClosestPoint(P, a, b, c);\n\t\n\tglm::vec3 result = A*a + B*b + C*c;\n\t\n\tBOOST_CHECK(isZero(closest.x));\n\tBOOST_CHECK(isZero(closest.y));\n\tBOOST_CHECK(isZero(closest.z));\n\tBOOST_CHECK(isZero(result.x));\n\tBOOST_CHECK(isZero(result.y));\n\tBOOST_CHECK(isZero(result.z));\n\t\n\t//Point outside the triangle, closest to one vertex\n\tP = glm::vec3( 0, 10, 0 );\n\tclosest = t0.getClosestPoint(P, a, b, c);\n\tresult = A*a + B*b + C*c;\n\t\n\t//Result and Closest should be equal to B\n\tBOOST_CHECK_CLOSE( closest.x, B.x, 0.0001f );\n\tBOOST_CHECK_CLOSE( closest.y, B.y, 0.0001f );\n\tBOOST_CHECK_CLOSE( closest.z, B.z, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.x, B.x, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.y, B.y, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.z, B.z, 0.0001f );\n\t\n\t//Point outside the triangle, colinear with the middle of the edge AB and the point (0,0,0).\n\t//The closes point should be the half of the edge.\n\tglm::vec3 halfEdge = (B-A);\n\thalfEdge /= 2.0f;\n\thalfEdge = A + halfEdge;\n\tP = halfEdge + halfEdge;\n\tclosest = t0.getClosestPoint(P, a, b, c);\n\tresult = A*a + B*b + C*c;\n\t\n\t//Result and Closest should be equal to halfEdge\n\tBOOST_CHECK_CLOSE( closest.x, halfEdge.x, 0.0001f );\n\tBOOST_CHECK_CLOSE( closest.y, halfEdge.y, 0.0001f );\n\tBOOST_CHECK_CLOSE( closest.z, halfEdge.z, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.x, halfEdge.x, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.y, halfEdge.y, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.z, halfEdge.z, 0.0001f );\n}\n\nBOOST_AUTO_TEST_CASE( closest_point_not_coplanar ) {\n\tglm::vec3 A(-3, -4, 0);\n\tglm::vec3 B(0, 5, 0);\n\tglm::vec3 C(3, -4, 0);\n\tTriangle t0(A,B,C);\n\tFloat a, b, c;\n\t\n\t//Point is \"over\" the triangle\n\t//Should be mapped to (0,0,0)\n\tglm::vec3 P(0,0,20);\n\tglm::vec3 closest = t0.getClosestPoint(P, a, b, c);\n\t\n\tglm::vec3 result = A*a + B*b + C*c;\n\t\n\tBOOST_CHECK(isZero(closest.x));\n\tBOOST_CHECK(isZero(closest.y));\n\tBOOST_CHECK(isZero(closest.z));\n\tBOOST_CHECK(isZero(result.x));\n\tBOOST_CHECK(isZero(result.y));\n\tBOOST_CHECK(isZero(result.z));\n\t\n\t//Point outside the triangle, closest to one vertex\n\tP = glm::vec3( 0, 10, 7 );\n\tclosest = t0.getClosestPoint(P, a, b, c);\n\tresult = A*a + B*b + C*c;\n\t\n\t//Result and Closest should be equal to B\n\tBOOST_CHECK_CLOSE( closest.x, B.x, 0.0001f );\n\tBOOST_CHECK_CLOSE( closest.y, B.y, 0.0001f );\n\tBOOST_CHECK_CLOSE( closest.z, B.z, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.x, B.x, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.y, B.y, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.z, B.z, 0.0001f );\n\t\n\t//Point outside the triangle, colinear with the middle of the edge AB and the point (0,0,0).\n\t//The closes point should be the half of the edge.\n\tglm::vec3 halfEdge = (B-A);\n\thalfEdge /= 2.0f;\n\thalfEdge = A + halfEdge;\n\tP = halfEdge + halfEdge + glm::vec3(0,0,5);\n\tclosest = t0.getClosestPoint(P, a, b, c);\n\tresult = A*a + B*b + C*c;\n\t\n\t//Result and Closest should be equal to halfEdge\n\tBOOST_CHECK_CLOSE( closest.x, halfEdge.x, 0.0001f );\n\tBOOST_CHECK_CLOSE( closest.y, halfEdge.y, 0.0001f );\n\tBOOST_CHECK_CLOSE( closest.z, halfEdge.z, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.x, halfEdge.x, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.y, halfEdge.y, 0.0001f );\n\tBOOST_CHECK_CLOSE( result.z, halfEdge.z, 0.0001f );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nBOOST_AUTO_TEST_SUITE_END()\n", "meta": {"hexsha": "fe4f7d244a89e25e6b6af80da7a10a2b971a47e1", "size": 4591, "ext": "cc", "lang": "C++", "max_stars_repo_path": "epoch/ayla/tests/triangle.cc", "max_stars_repo_name": "oprogramadorreal/vize", "max_stars_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T14:36:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T07:44:54.000Z", "max_issues_repo_path": "epoch/ayla/tests/triangle.cc", "max_issues_repo_name": "oprogramadorreal/vize", "max_issues_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "epoch/ayla/tests/triangle.cc", "max_forks_repo_name": "oprogramadorreal/vize", "max_forks_repo_head_hexsha": "042c16f96d8790303563be6787200558e1ec00b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-01T01:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T13:06:09.000Z", "avg_line_length": 31.0202702703, "max_line_length": 93, "alphanum_fraction": 0.6813330429, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.6992544085240401, "lm_q1q2_score": 0.6011236648782626}}
{"text": "#include <gtest/gtest.h>\n#include \"pitts_parallel.hpp\"\n#include \"pitts_tensortrain_from_dense.hpp\"\n#include \"pitts_tensortrain_dot.hpp\"\n#include \"pitts_tensortrain_norm.hpp\"\n#include \"pitts_multivector.hpp\"\n#include \"pitts_multivector_random.hpp\"\n#include \"pitts_multivector_eigen_adaptor.hpp\"\n#include <Eigen/Dense>\n\nnamespace\n{\n  auto toMultiVector(const double* begin, const double* end, const std::vector<int>& dimensions)\n  {\n    int size = 1;\n    for(auto d: dimensions)\n      size *= d;\n    assert(end - begin == size);\n    PITTS::MultiVector<double> result(size / dimensions.back(), dimensions.back());\n    for(int j = 0; j < result.cols(); j++)\n      for(int i = 0; i < result.rows(); i++)\n        result(i,j) = *(begin++);\n    return result;\n  }\n}\n\nTEST(PITTS_TensorTrain_fromDense, scalar)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  const std::array<double,1> scalar = {5};\n  const std::vector<int> dimensions = {1};\n\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(scalar), end(scalar), dimensions);\n  TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n  ASSERT_EQ(TT.dimensions(), dimensions);\n  ASSERT_NEAR(5., TT.subTensors()[0](0,0,0), eps);\n}\n\nTEST(PITTS_TensorTrain_fromDense, vector_1d)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  const std::array<double,7> scalar = {1,2,3,4,5,6,7};\n  const std::vector<int> dimensions = {7};\n\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(scalar), end(scalar), dimensions);\n  TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n  ASSERT_EQ(TT.dimensions(), dimensions);\n  ASSERT_EQ(1, TT.subTensors()[0].r1());\n  ASSERT_EQ(7, TT.subTensors()[0].n());\n  ASSERT_EQ(1, TT.subTensors()[0].r2());\n  ASSERT_NEAR(1., TT.subTensors()[0](0,0,0), eps);\n  ASSERT_NEAR(2., TT.subTensors()[0](0,1,0), eps);\n  ASSERT_NEAR(3., TT.subTensors()[0](0,2,0), eps);\n  ASSERT_NEAR(4., TT.subTensors()[0](0,3,0), eps);\n  ASSERT_NEAR(5., TT.subTensors()[0](0,4,0), eps);\n  ASSERT_NEAR(6., TT.subTensors()[0](0,5,0), eps);\n  ASSERT_NEAR(7., TT.subTensors()[0](0,6,0), eps);\n}\n\nTEST(PITTS_TensorTrain_fromDense, matrix_2d_1x1)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  const std::array<double,1> M = {7.};\n  const std::vector<int> dimensions = {1,1};\n\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(M), end(M), dimensions);\n  TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n  ASSERT_EQ(TT.dimensions(), dimensions);\n  ASSERT_EQ(1, TT.subTensors()[0].r1());\n  ASSERT_EQ(1, TT.subTensors()[0].n());\n  ASSERT_EQ(1, TT.subTensors()[0].r2());\n  ASSERT_EQ(1, TT.subTensors()[1].r1());\n  ASSERT_EQ(1, TT.subTensors()[1].n());\n  ASSERT_EQ(1, TT.subTensors()[1].r2());\n  if( TT.subTensors()[0](0,0,0) > 0 )\n  {\n    ASSERT_NEAR(7., TT.subTensors()[0](0,0,0), eps);\n    ASSERT_NEAR(1., TT.subTensors()[1](0,0,0), eps);\n  }\n  else\n  {\n    // sign flip is ok\n    ASSERT_NEAR(-7., TT.subTensors()[0](0,0,0), eps);\n    ASSERT_NEAR(-1., TT.subTensors()[1](0,0,0), eps);\n  }\n}\n\nTEST(PITTS_TensorTrain_fromDense, matrix_2d_1x5)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  const std::array<double,5> M = {1., 2., 3., 4., 5.};\n  const std::vector<int> dimensions = {1,5};\n\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(M), end(M), dimensions);\n  TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n  ASSERT_EQ(TT.dimensions(), dimensions);\n  ASSERT_EQ(1, TT.subTensors()[0].r1());\n  ASSERT_EQ(1, TT.subTensors()[0].n());\n  ASSERT_EQ(1, TT.subTensors()[0].r2());\n  ASSERT_EQ(1, TT.subTensors()[1].r1());\n  ASSERT_EQ(5, TT.subTensors()[1].n());\n  ASSERT_EQ(1, TT.subTensors()[1].r2());\n  ASSERT_NEAR(1., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(2., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,1,0), eps);\n  ASSERT_NEAR(3., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,2,0), eps);\n  ASSERT_NEAR(4., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,3,0), eps);\n  ASSERT_NEAR(5., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,4,0), eps);\n}\n\nTEST(PITTS_TensorTrain_fromDense, matrix_2d_5x1)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  const std::array<double,5> M = {1., 2., 3., 4., 5.};\n  const std::vector<int> dimensions = {5,1};\n\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(M), end(M), dimensions);\n  TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n  ASSERT_EQ(TT.dimensions(), dimensions);\n  ASSERT_EQ(1, TT.subTensors()[0].r1());\n  ASSERT_EQ(5, TT.subTensors()[0].n());\n  ASSERT_EQ(1, TT.subTensors()[0].r2());\n  ASSERT_EQ(1, TT.subTensors()[1].r1());\n  ASSERT_EQ(1, TT.subTensors()[1].n());\n  ASSERT_EQ(1, TT.subTensors()[1].r2());\n  ASSERT_NEAR(1., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(2., TT.subTensors()[0](0,1,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(3., TT.subTensors()[0](0,2,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(4., TT.subTensors()[0](0,3,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(5., TT.subTensors()[0](0,4,0)*TT.subTensors()[1](0,0,0), eps);\n}\n\nTEST(PITTS_TensorTrain_fromDense, matrix_2d_5x2_rank1)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  const std::array<double,10> M = {1., 2., 3., 4., 5., 2., 4., 6., 8., 10.};\n  const std::vector<int> dimensions = {5,2};\n\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(M), end(M), dimensions);\n  TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n  ASSERT_EQ(TT.dimensions(), dimensions);\n  ASSERT_EQ(1, TT.subTensors()[0].r1());\n  ASSERT_EQ(5, TT.subTensors()[0].n());\n  ASSERT_EQ(1, TT.subTensors()[0].r2());\n  ASSERT_EQ(1, TT.subTensors()[1].r1());\n  ASSERT_EQ(2, TT.subTensors()[1].n());\n  ASSERT_EQ(1, TT.subTensors()[1].r2());\n  ASSERT_NEAR(1., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(2., TT.subTensors()[0](0,1,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(3., TT.subTensors()[0](0,2,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(4., TT.subTensors()[0](0,3,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(5., TT.subTensors()[0](0,4,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(2., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,1,0), eps);\n  ASSERT_NEAR(4., TT.subTensors()[0](0,1,0)*TT.subTensors()[1](0,1,0), eps);\n  ASSERT_NEAR(6., TT.subTensors()[0](0,2,0)*TT.subTensors()[1](0,1,0), eps);\n  ASSERT_NEAR(8., TT.subTensors()[0](0,3,0)*TT.subTensors()[1](0,1,0), eps);\n  ASSERT_NEAR(10., TT.subTensors()[0](0,4,0)*TT.subTensors()[1](0,1,0), eps);\n}\n\nTEST(PITTS_TensorTrain_fromDense, matrix_2d_2x5_rank1)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  const std::array<double,10> M = {1., 2., 2., 4., 3., 6., 4., 8., 5., 10.};\n  const std::vector<int> dimensions = {2,5};\n\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(M), end(M), dimensions);\n  TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n  ASSERT_EQ(TT.dimensions(), dimensions);\n  ASSERT_EQ(1, TT.subTensors()[0].r1());\n  ASSERT_EQ(2, TT.subTensors()[0].n());\n  ASSERT_EQ(1, TT.subTensors()[0].r2());\n  ASSERT_EQ(1, TT.subTensors()[1].r1());\n  ASSERT_EQ(5, TT.subTensors()[1].n());\n  ASSERT_EQ(1, TT.subTensors()[1].r2());\n  ASSERT_NEAR(1., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(2., TT.subTensors()[0](0,1,0)*TT.subTensors()[1](0,0,0), eps);\n  ASSERT_NEAR(2., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,1,0), eps);\n  ASSERT_NEAR(4., TT.subTensors()[0](0,1,0)*TT.subTensors()[1](0,1,0), eps);\n  ASSERT_NEAR(3., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,2,0), eps);\n  ASSERT_NEAR(6., TT.subTensors()[0](0,1,0)*TT.subTensors()[1](0,2,0), eps);\n  ASSERT_NEAR(4., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,3,0), eps);\n  ASSERT_NEAR(8., TT.subTensors()[0](0,1,0)*TT.subTensors()[1](0,3,0), eps);\n  ASSERT_NEAR(5., TT.subTensors()[0](0,0,0)*TT.subTensors()[1](0,4,0), eps);\n  ASSERT_NEAR(10., TT.subTensors()[0](0,1,0)*TT.subTensors()[1](0,4,0), eps);\n}\n\nTEST(PITTS_TensorTrain_fromDense, matrix_2d_4x5)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  std::array<double,4*5> M;\n  const std::vector<int> dimensions = {4,5};\n  for(int i = 0; i < 4; i++)\n    for(int j = 0; j < 5; j++)\n      M[i+j*4] = i + j*4;\n\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(M), end(M), dimensions);\n  TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n  ASSERT_EQ(TT.dimensions(), dimensions);\n\n  // check result with dot products\n  TensorTrain_double testTT(dimensions);\n  for(int i = 0; i < 4; i++)\n    for(int j = 0; j < 5; j++)\n    {\n      testTT.setUnit({i,j});\n      EXPECT_NEAR(i+j*4., dot(testTT, TT), eps);\n    }\n}\n\nTEST(PITTS_TensorTrain_fromDense, tensor_3d_rank1)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  std::array<double,3*4*5> M = {};\n  const std::vector<int> dimensions = {3,4,5};\n  for(int i = 0; i < 3; i++)\n    for(int j = 0; j < 4; j++)\n      for(int k = 0; k < 5; k++)\n        M[i+j*3+k*3*4] = 1.;\n\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(M), end(M), dimensions);\n  TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n  ASSERT_EQ(TT.dimensions(), dimensions);\n  std::vector<int> ones = {1,1};\n  ASSERT_EQ(ones, TT.getTTranks());\n\n  // check result with dot products\n  TensorTrain_double testTT(dimensions);\n  for(int i = 0; i < 3; i++)\n    for(int j = 0; j < 4; j++)\n      for(int k = 0; k < 5; k++)\n      {\n        testTT.setUnit({i,j,k});\n        EXPECT_NEAR(1., dot(testTT, TT), eps);\n      }\n}\n\nTEST(PITTS_TensorTrain_fromDense, tensor_3d_3x4x5)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  std::array<double,3*4*5> M;\n  const std::vector<int> dimensions = {3,4,5};\n  for(int i = 0; i < 3; i++)\n    for(int j = 0; j < 4; j++)\n      for(int k = 0; k < 5; k++)\n        M[i+j*3+k*3*4] = i + j*10 + k*100;\n\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(M), end(M), dimensions);\n  TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n  ASSERT_EQ(TT.dimensions(), dimensions);\n\n  // check result with dot products\n  TensorTrain_double testTT(dimensions);\n  for(int i = 0; i < 3; i++)\n    for(int j = 0; j < 4; j++)\n      for(int k = 0; k < 5; k++)\n      {\n        testTT.setUnit({i,j,k});\n        EXPECT_NEAR(i + j*10. + k*100., dot(testTT, TT), eps);\n      }\n}\n\nTEST(PITTS_TensorTrain_fromDense, tensor_5d_2x3x4x2x3_unit)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  std::array<double,2*3*4*2*3> M = {};\n  const std::vector<int> dimensions = {2,3,4,2,3};\n  const std::vector<int> dir = {1,0,2,0,2};\n  M[ dir[0] + 2*dir[1] + 2*3*dir[2] + 2*3*4*dir[3] + 2*3*4*2*dir[4] ] = 1.;\n\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(M), end(M), dimensions);\n  TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n  ASSERT_EQ(TT.dimensions(), dimensions);\n  std::vector<int> ones = {1,1,1,1};\n  ASSERT_EQ(ones, TT.getTTranks());\n\n  TensorTrain_double refTT(dimensions);\n  refTT.setUnit(dir);\n\n  EXPECT_NEAR(1., norm2(TT), eps);\n  EXPECT_NEAR(1., norm2(refTT), eps);\n  EXPECT_NEAR(1., dot(TT, refTT), eps);\n}\n\nTEST(PITTS_TensorTrain_fromDense, matrix_2d_4x5_maxRank)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  constexpr auto eps = 1.e-10;\n\n  std::array<double,4*5> M;\n  const std::vector<int> dimensions = {4,5};\n  for(int i = 0; i < 4; i++)\n    for(int j = 0; j < 5; j++)\n      M[i+j*4] = (i == j ? 10.-i : 0.);\n\n  {\n    // full / exact\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(M), end(M), dimensions);\n    TensorTrain_double TT = PITTS::fromDense(data, work, dimensions);\n\n    ASSERT_EQ(TT.dimensions(), dimensions);\n\n    // check result with dot products\n    TensorTrain_double testTT(dimensions);\n    for(int i = 0; i < 4; i++)\n      for(int j = 0; j < 5; j++)\n      {\n        testTT.setUnit({i,j});\n        EXPECT_NEAR((i == j ? 10.-i : 0.), dot(testTT, TT), eps);\n      }\n  }\n\n  {\n    // truncated\n  PITTS::MultiVector<double> work, data = toMultiVector(begin(M), end(M), dimensions);\n    TensorTrain_double TT = PITTS::fromDense(data, work, dimensions, 1.e-16, 3);\n\n    ASSERT_EQ(TT.dimensions(), dimensions);\n\n    // check result with dot products\n    TensorTrain_double testTT(dimensions);\n    for(int i = 0; i < 4; i++)\n      for(int j = 0; j < 5; j++)\n      {\n        testTT.setUnit({i,j});\n        if( i == j && i < 3 )\n        {\n          EXPECT_NEAR(10.-i, dot(testTT, TT), eps);\n        }\n        else\n        {\n          EXPECT_NEAR(0., dot(testTT, TT), eps);\n        }\n      }\n  }\n\n}\n\nTEST(PITTS_TensorTrain_fromDense, tensor5d_random_maxRank)\n{\n  using TensorTrain_double = PITTS::TensorTrain<double>;\n  using MultiVector_double = PITTS::MultiVector<double>;\n\n  std::vector<int> shape = {2,3,4,2,3};\n  MultiVector_double M(2*3*4*2, 3);\n  randomize(M);\n\n  MultiVector_double work;\n  TensorTrain_double TT = PITTS::fromDense(M, work, shape, 1.e-16, 2);\n\n  for(auto r: TT.getTTranks())\n  {\n    ASSERT_LE(r, 2);\n  }\n}\n\n\n// anonymous namespace with helper functions\nnamespace\n{\n  // check that the distributed (MPI parallel) algorithm obtains the same result as the \"serial\" algorithm\n  void check_mpiGlobal_result(const std::vector<int>& localShape)\n  {\n    using TensorTrain_double = PITTS::TensorTrain<double>;\n    using MultiVector_double = PITTS::MultiVector<double>;\n    constexpr auto eps = 1.e-8;\n\n    ASSERT_GE(localShape.size(), 2);\n    const auto nDim = localShape.size();\n\n    const auto& [iProc,nProcs] = PITTS::internal::parallel::mpiProcInfo();\n\n    std::vector<int> globalShape = localShape;\n    globalShape[0] *= nProcs;\n    const long long nLocal = std::accumulate(localShape.begin(), localShape.end(), 1, std::multiplies<long long>());\n    const long long nGlobal = nLocal * nProcs;\n\n    // generate random data and distribute it\n    using mat = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;\n    mat globalData = mat::Random(nGlobal/globalShape.back(), globalShape.back());\n    MPI_Bcast(globalData.data(), nGlobal, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\n    // calculate the global solution on each process\n    MultiVector_double Mglobal(nGlobal/globalShape.back(), globalShape.back());\n    {\n      auto mapMglobal = EigenMap(Mglobal);\n      mapMglobal = globalData;\n    }\n    MultiVector_double work;\n    const auto globalTT = PITTS::fromDense(Mglobal, work, globalShape, 1.e-12, 5, false);\n\n\n    // calculate distributed solution\n    MultiVector_double Mlocal(nLocal/localShape.back(), localShape.back());\n    {\n      auto mapMlocal = EigenMap(Mlocal);\n      Eigen::Map<mat> mapGlobalData = Eigen::Map<mat>(globalData.data(), nProcs, nGlobal/nProcs);\n      mat localData = mapGlobalData.row(iProc);\n      Eigen::Map<mat> mapLocalData = Eigen::Map<mat>(localData.data(), nLocal/localShape.back(), localShape.back());\n      mapMlocal = mapLocalData;\n    }\n    const auto distributedTT = PITTS::fromDense(Mlocal, work, localShape, 1.e-12, 5, true);\n\n    // distributedTT and globalTT should be identical, only the first sub-tensor is distributed onto multiple processes...\n    for(int iDim = 1; iDim < nDim; iDim++)\n    {\n      const auto& subT_ref = globalTT.subTensors()[iDim];\n      const auto& subT = distributedTT.subTensors()[iDim];\n\n      ASSERT_EQ(subT_ref.r1(), subT.r1());\n      ASSERT_EQ(subT_ref.n(), subT.n());\n      ASSERT_EQ(subT_ref.r2(), subT.r2());\n\n      for(int i = 0; i < subT.r1(); i++)\n        for(int j = 0; j < subT.n(); j++)\n          for(int k = 0; k < subT.r2(); k++)\n          {\n            // only compare absolute values as the sign of singular vectors is not well defined\n            EXPECT_NEAR(std::abs(subT_ref(i,j,k)), std::abs(subT(i,j,k)), eps);\n          }\n    }\n\n    // first dimension is distributed\n    {\n      const auto& subT_ref = globalTT.subTensors()[0];\n      const auto& subT = distributedTT.subTensors()[0];\n\n      ASSERT_EQ(subT_ref.r1(), subT.r1());\n      ASSERT_EQ(globalShape[0], subT_ref.n());\n      ASSERT_EQ(localShape[0], subT.n());\n      ASSERT_EQ(subT_ref.r2(), subT.r2());\n\n      for(int i = 0; i < subT.r1(); i++)\n        for(int k = 0; k < subT.r2(); k++)\n          for(int j = 0; j < subT.n(); j++)\n          {\n            // only compare absolute values as the sign of singular vectors is not well defined\n            EXPECT_NEAR(std::abs(subT_ref(i,iProc+j*nProcs,k)), std::abs(subT(i,j,k)), eps);\n          }\n    }\n  }\n}\n\nTEST(PITTS_TensorTrain_fromDense, tensor2d_mpiGlobal)\n{\n  check_mpiGlobal_result({1, 10});\n}\n\nTEST(PITTS_TensorTrain_fromDense, another_tensor2d_mpiGlobal)\n{\n  check_mpiGlobal_result({3, 1});\n}\n\nTEST(PITTS_TensorTrain_fromDense, larger_tensor2d_mpiGlobal)\n{\n  check_mpiGlobal_result({7, 15});\n}\n\nTEST(PITTS_TensorTrain_fromDense, tensor3d_mpiGlobal)\n{\n  check_mpiGlobal_result({1, 5, 5});\n}\n\nTEST(PITTS_TensorTrain_fromDense, another_tensor3d_mpiGlobal)\n{\n  check_mpiGlobal_result({3, 5, 5});\n}\n\nTEST(PITTS_TensorTrain_fromDense, tensor5d_mpiGlobal)\n{\n  check_mpiGlobal_result({1, 5, 4, 5, 3});\n}\n\nTEST(PITTS_TensorTrain_fromDense, another_tensor5d_mpiGlobal)\n{\n  check_mpiGlobal_result({2, 5, 4, 5, 3});\n}\n", "meta": {"hexsha": "bb58d403083e5205bef61acf0c4500c0031ef2e2", "size": 17489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_tensortrain_from_dense.cpp", "max_stars_repo_name": "melven/pitts", "max_stars_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T14:48:49.000Z", "max_issues_repo_path": "test/test_tensortrain_from_dense.cpp", "max_issues_repo_name": "melven/pitts", "max_issues_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_tensortrain_from_dense.cpp", "max_forks_repo_name": "melven/pitts", "max_forks_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3595284872, "max_line_length": 122, "alphanum_fraction": 0.6411458631, "num_tokens": 5879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146849, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.601113601751483}}
{"text": "#define BOOST_TEST_MODULE WeightsTest\n#include <boost/test/unit_test.hpp>\n#include <boost/test/floating_point_comparison.hpp>\n#include \"sparse_vector.h\"\n\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE(Dot) {\n  SparseVector<double> x;\n  SparseVector<double> y;\n  x.set_value(1,0.8);\n  y.set_value(1,5);\n  x.set_value(2,-2);\n  y.set_value(2,1);\n  x.set_value(3,80);\n  BOOST_CHECK_CLOSE(x.dot(y), 2.0, 1e-9);\n}\n\nBOOST_AUTO_TEST_CASE(Equality) {\n  SparseVector<double> x;\n  SparseVector<double> y;\n  x.set_value(1,-1);\n  y.set_value(1,-1);\n  BOOST_CHECK(x == y);\n}\n\nBOOST_AUTO_TEST_CASE(Division) {\n  SparseVector<double> x;\n  SparseVector<double> y;\n  x.set_value(1,1);\n  y.set_value(1,-1);\n  BOOST_CHECK(!(x == y));\n  x /= -1;\n  BOOST_CHECK(x == y);\n}\n", "meta": {"hexsha": "67df8c576a6fe8065b2fd920603ad28a3fda09ae", "size": 746, "ext": "cc", "lang": "C++", "max_stars_repo_path": "utils/sv_test.cc", "max_stars_repo_name": "kho/cdec", "max_stars_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "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": "utils/sv_test.cc", "max_issues_repo_name": "kho/cdec", "max_issues_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "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/sv_test.cc", "max_forks_repo_name": "kho/cdec", "max_forks_repo_head_hexsha": "d88186af251ecae60974b20395ce75807bfdda35", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7222222222, "max_line_length": 51, "alphanum_fraction": 0.6903485255, "num_tokens": 236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6011135993352607}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_NBEXPONENTBITS_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_NBEXPONENTBITS_HPP_INCLUDED\n\n/*!\n  @ingroup group-constant\n  @defgroup constant-Nbexponentbits Nbexponentbits (function template)\n\n  Generates a constant representing the number of exponent bits of a floating point type.\n\n  @headerref{<boost/simd/constant/nbexponentbits.hpp>}\n\n  @par Description\n\n  1.  @code\n      template<typename T> as_integer_t<T> Nbexponentbits();\n      @endcode\n\n  2.  @code\n      template<typename T> as_integer_t<T> Nbexponentbits( boost::simd::as_<T> const& target );\n      @endcode\n\n    Generates a value of type `as_integer_t<T>` that evaluates to the number of bits used to\n    represents the exponent of an IEEE754 floating-point value.\n\n  @par Parameters\n\n  | Name                | Description                                                         |\n  |--------------------:|:--------------------------------------------------------------------|\n  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n  @par Return Value\n  A value of type @c as_integer_t<T> that evaluates to:\n\n  | Type        | double      | float         |\n  |:------------|:------------|---------------|\n  | **Values**  |   11        |      8        |\n\n  @par Requirements\n  - **T** models IEEEValue\n**/\n\n#include <boost/simd/constant/scalar/nbexponentbits.hpp>\n#include <boost/simd/constant/simd/nbexponentbits.hpp>\n\n#endif\n", "meta": {"hexsha": "e12bff5be096049a12d40dd1e74ba0a8906697db", "size": 1847, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/nbexponentbits.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/nbexponentbits.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/nbexponentbits.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 32.9821428571, "max_line_length": 100, "alphanum_fraction": 0.5441256091, "num_tokens": 400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6010684171244166}}
{"text": "// Compile me: g++ -std=c++1z main.cpp -o test\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n#include <boost/format.hpp>\n#include <boost/range/irange.hpp>\n\ntemplate<class Size>\nstd::tuple<Size> make_cum_product(Size size)\n{\n    return std::make_tuple(size);\n}\n\ntemplate<class Size, class... Sizes>\nstd::tuple<Sizes..., Size, Size> make_cum_product(Size product, Size second, Sizes... tail)\n{\n    return std::tuple_cat(std::make_tuple(product), make_cum_product(second * product, tail...));\n}\n\ntemplate<class Functor, class Ranges, class Sizes, class CumProd, std::size_t... Is>\nvoid dereference(Functor f, std::size_t index,\n                 const Ranges& ranges, const Sizes& sizes, const CumProd& cum_prod,\n                 std::index_sequence<Is...>)\n{\n    f(std::get<Is>(ranges)[(index / std::get<Is>(cum_prod)) % std::get<Is>(sizes)]...);\n}\n\ntemplate<class Functor, class... Ranges>\nvoid MultipleForLoop(Functor f, const Ranges&... rs)\n{\n    auto sizes = std::make_tuple(std::size(rs)...);\n    auto cum_prod = make_cum_product(std::size_t(1), std::size(rs)...);\n    auto size = std::get<sizeof...(Ranges)>(cum_prod);\n    auto ranges = std::make_tuple(rs...);\n\n    for (std::size_t i = 0; i < size; ++i)\n        dereference(f, i, ranges, sizes, cum_prod, std::index_sequence_for<Ranges...>());\n}\n\nvoid func(int i, int j, int k)\n{\n    std::cout << boost::format(\"Received (%1%, %2%, %3%)\\n\") % i % j % k;\n}\n\nint main(int argc, char** argv)\n{\n    MultipleForLoop(func, boost::irange(0, 3), std::vector<int>({-2, 0, 1}),\n                    std::vector<int>({10, 11, 12, 13}));\n    return 0;\n}\n", "meta": {"hexsha": "f1b87ad2f7689d79938d7ae19008ad2547238c28", "size": 1608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multiloop.cpp", "max_stars_repo_name": "cvlabmiet/interview-tasks", "max_stars_repo_head_hexsha": "73fdb0ff5e4f8678b13cd20a65987281b92ce7d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "multiloop.cpp", "max_issues_repo_name": "cvlabmiet/interview-tasks", "max_issues_repo_head_hexsha": "73fdb0ff5e4f8678b13cd20a65987281b92ce7d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "multiloop.cpp", "max_forks_repo_name": "cvlabmiet/interview-tasks", "max_forks_repo_head_hexsha": "73fdb0ff5e4f8678b13cd20a65987281b92ce7d1", "max_forks_repo_licenses": ["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.9230769231, "max_line_length": 97, "alphanum_fraction": 0.631840796, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6010684043837449}}
{"text": "/*******************************************************************************\n * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.\n * \n * Licensed under the MIT License (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://opensource.org/licenses/MIT\n * \n * Developers:\n *   Sebastian Niemann - Lead developer\n *   Daniel Kiechle - Unit testing\n ******************************************************************************/\n#include <Expected.hpp>\nusing armadilloJava::Expected;\n\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\n#include <cmath>\nusing std::log;\nusing std::sqrt;\nusing std::pow;\n\n#include <fstream>\nusing std::ofstream;\n\n#include <streambuf>\nusing std::streambuf;\n\n#include <utility>\nusing std::pair;\n\n#include <armadillo>\nusing arma::Mat;\nusing arma::Row;\nusing arma::uword;\nusing arma::abs;\nusing arma::eps;\nusing arma::exp;\nusing arma::exp2;\nusing arma::exp10;\nusing arma::trunc_exp;\nusing arma::log;\nusing arma::log2;\nusing arma::log10;\nusing arma::trunc_log;\nusing arma::sqrt;\nusing arma::square;\nusing arma::floor;\nusing arma::ceil;\nusing arma::round;\nusing arma::sign;\nusing arma::sin;\nusing arma::asin;\nusing arma::sinh;\nusing arma::asinh;\nusing arma::cos;\nusing arma::acos;\nusing arma::cosh;\nusing arma::acosh;\nusing arma::tan;\nusing arma::atan;\nusing arma::tanh;\nusing arma::atanh;\nusing arma::cumsum;\nusing arma::hist;\nusing arma::sort;\nusing arma::sort_index;\nusing arma::stable_sort_index;\nusing arma::trans;\nusing arma::unique;\nusing arma::toeplitz;\nusing arma::circ_toeplitz;\nusing arma::accu;\nusing arma::min;\nusing arma::max;\nusing arma::prod;\nusing arma::sum;\nusing arma::mean;\nusing arma::median;\nusing arma::stddev;\nusing arma::var;\nusing arma::cor;\nusing arma::cov;\nusing arma::diagmat;\nusing arma::is_finite;\n\n#include <InputClass.hpp>\nusing armadilloJava::InputClass;\n\n#include <Input.hpp>\nusing armadilloJava::Input;\n\nnamespace armadilloJava {\n  class ExpectedGenRowVec : public Expected {\n    public:\n      ExpectedGenRowVec() {\n        cout << \"Compute ExpectedGenRowVec(): \" << endl;\n\n        vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({\n          InputClass::GenRowVec\n        });\n\n        for (vector<pair<string, void*>> input : inputs) {\n          _fileSuffix = \"\";\n\n          int n = 0;\n          for (pair<string, void*> value : input) {\n            switch (n) {\n              case 0:\n                _fileSuffix += value.first;\n                _genRowVec = *static_cast<Row<double>*>(value.second);\n                break;\n            }\n            ++n;\n          }\n\n          cout << \"Using input: \" << _fileSuffix << endl;\n\n          expectedArmaAbs();\n          expectedArmaEps();\n          expectedArmaExp();\n          expectedArmaExp2();\n          expectedArmaExp10();\n          expectedArmaTrunc_exp();\n          expectedArmaLog();\n          expectedArmaLog2();\n          expectedArmaLog10();\n          expectedArmaTrunc_log();\n          expectedArmaSqrt();\n          expectedArmaSquare();\n          expectedArmaFloor();\n          expectedArmaCeil();\n          expectedArmaRound();\n          expectedArmaSign();\n          expectedArmaSin();\n          expectedArmaAsin();\n          expectedArmaSinh();\n          expectedArmaAsinh();\n          expectedArmaCos();\n          expectedArmaAcos();\n          expectedArmaCosh();\n          expectedArmaAcosh();\n          expectedArmaTan();\n          expectedArmaAtan();\n          expectedArmaTanh();\n          expectedArmaAtanh();\n          expectedArmaCumsum();\n          expectedArmaHist();\n          expectedArmaSort();\n          expectedArmaSort_index();\n          expectedArmaStable_sort_index();\n          expectedArmaTrans();\n          expectedArmaUnique();\n          expectedArmaNegate();\n          expectedArmaReciprocal();\n          expectedArmaToeplitz();\n          expectedArmaCirc_toeplitz();\n          expectedArmaAccu();\n          expectedArmaMin();\n          expectedArmaMax();\n          expectedArmaProd();\n          expectedArmaSum();\n          expectedArmaMean();\n          expectedArmaMedian();\n          expectedArmaStddev();\n          expectedArmaVar();\n          expectedArmaCor();\n          expectedArmaCov();\n          expectedArmaDiagmat();\n          expectedArmaIs_finite();\n          expectedMat();\n          expectedRowVecSize();\n          expectedRowVecT();\n   \t\t  expectedRowVecPrint();\n          expectedRowVecRaw_print();\n   \t\t  expectedRowIs_finite();\n       \t  expectedRowMinA();\n          expectedRowMaxA();\n   \t\t  expectedRowMinB();\n   \t\t  expectedRowMaxB();\n   \t\t  expectedRowIs_empty();\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n    protected:\n      Row<double> _genRowVec;\n\n      void expectedArmaAbs() {\n        cout << \"- Compute expectedArmaAbs() ... \";\n        save<double>(\"Arma.abs\", abs(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaEps() {\n        cout << \"- Compute expectedArmaAbs() ... \";\n        save<double>(\"Arma.eps\", eps(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaExp() {\n        cout << \"- Compute expectedArmaExp() ... \";\n        save<double>(\"Arma.exp\", exp(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaExp2() {\n        cout << \"- Compute expectedArmaExp2() ... \";\n        save<double>(\"Arma.exp2\", exp2(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaExp10() {\n        cout << \"- Compute expectedArmaExp10() ... \";\n        save<double>(\"Arma.exp10\", exp10(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrunc_exp() {\n        cout << \"- Compute expectedArmaTrunc_exp() ... \";\n        save<double>(\"Arma.trunc_exp\", trunc_exp(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaLog() {\n        cout << \"- Compute expectedArmaLog() ... \";\n        save<double>(\"Arma.log\", log(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaLog2() {\n        cout << \"- Compute expectedArmaLog2() ... \";\n        save<double>(\"Arma.log2\", log2(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaLog10() {\n        cout << \"- Compute expectedArmaLog10() ... \";\n        save<double>(\"Arma.log10\", log10(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrunc_log() {\n        cout << \"- Compute expectedArmaTrunc_log() ... \";\n        save<double>(\"Arma.trunc_log\", trunc_log(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSqrt() {\n        cout << \"- Compute expectedArmaSqrt() ... \";\n        save<double>(\"Arma.sqrt\", sqrt(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSquare() {\n        cout << \"- Compute expectedArmaSquare() ... \";\n        save<double>(\"Arma.square\", square(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaFloor() {\n        cout << \"- Compute expectedArmaFloor() ... \";\n        save<double>(\"Arma.floor\", floor(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCeil() {\n        cout << \"- Compute expectedArmaCeil() ... \";\n        save<double>(\"Arma.ceil\", ceil(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaRound() {\n        cout << \"- Compute expectedArmaRound() ... \";\n        save<double>(\"Arma.round\", round(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSign() {\n        cout << \"- Compute expectedArmaSign() ... \";\n        save<double>(\"Arma.sign\", sign(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSin() {\n        cout << \"- Compute expectedArmaSin() ... \";\n        save<double>(\"Arma.sin\", sin(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAsin() {\n        cout << \"- Compute expectedArmaAsin() ... \";\n        save<double>(\"Arma.asin\", asin(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSinh() {\n        cout << \"- Compute expectedArmaSinh() ... \";\n        save<double>(\"Arma.sinh\", sinh(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAsinh() {\n        cout << \"- Compute expectedArmaAsinh() ... \";\n        save<double>(\"Arma.asinh\", asinh(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCos() {\n        cout << \"- Compute expectedArmaCos() ... \";\n        save<double>(\"Arma.cos\", cos(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAcos() {\n        cout << \"- Compute expectedArmaAcos() ... \";\n        save<double>(\"Arma.acos\", acos(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCosh() {\n        cout << \"- Compute expectedArmaCosh() ... \";\n        save<double>(\"Arma.cosh\", cosh(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAcosh() {\n        cout << \"- Compute expectedArmaAcosh() ... \";\n\n        /*\n         * acosh behaves buggy on some systems, with acosh(inf) = nan instead of inf\n         */\n        //save<double>(\"Arma.acosh\", acosh(_genRowVec));\n\n        Mat<double> expected = _genRowVec;\n        expected.transform([](double value) {\n          return log(value + sqrt(pow(value, 2) - 1));\n        });\n        save<double>(\"Arma.acosh\", expected);\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTan() {\n        cout << \"- Compute expectedArmaTan() ... \";\n        save<double>(\"Arma.tan\", tan(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAtan() {\n        cout << \"- Compute expectedArmaAtan() ... \";\n        save<double>(\"Arma.atan\", atan(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTanh() {\n        cout << \"- Compute expectedArmaTanh() ... \";\n        save<double>(\"Arma.tanh\", tanh(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAtanh() {\n        cout << \"- Compute expectedArmaAtanh() ... \";\n        save<double>(\"Arma.atanh\", atanh(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCumsum() {\n        cout << \"- Compute expectedArmaCumsum() ... \";\n        save<double>(\"Arma.cumsum\", cumsum(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaHist() {\n        cout << \"- Compute expectedArmaHist() ... \";\n        save<uword>(\"Arma.hist\", hist(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSort() {\n        if(!_genRowVec.is_finite()) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaSort() ... \";\n        save<double>(\"Arma.sort\", sort(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSort_index() {\n        if(!_genRowVec.is_finite()) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaSort_index() ... \";\n        save<uword>(\"Arma.sort_index\", sort_index(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaStable_sort_index() {\n        if(!_genRowVec.is_finite()) {\n          return;\n        }\n\n        cout << \"- Compute expectedArmaStable_sort_index() ... \";\n        save<uword>(\"Arma.stable_sort_index\", stable_sort_index(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaTrans() {\n        cout << \"- Compute expectedArmaTrans() ... \";\n        save<double>(\"Arma.trans\", trans(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaUnique() {\n        cout << \"- Compute expectedArmaUnique() ... \";\n        save<double>(\"Arma.unique\", unique(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaNegate() {\n        cout << \"- Compute expectedArmaNegate() ... \";\n        save<double>(\"Arma.negate\", -_genRowVec);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaReciprocal() {\n        cout << \"- Compute expectedArmaReciprocal() ... \";\n        save<double>(\"Arma.reciprocal\", 1/_genRowVec);\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaToeplitz() {\n        cout << \"- Compute expectedArmaToeplitz() ... \";\n        save<double>(\"Arma.toeplitz\", toeplitz(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCirc_toeplitz() {\n        cout << \"- Compute expectedArmaCirc_toeplitz() ... \";\n        save<double>(\"Arma.circ_toeplitz\", circ_toeplitz(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaAccu() {\n        cout << \"- Compute expectedArmaAccu() ... \";\n        save<double>(\"Arma.accu\", Mat<double>({accu(_genRowVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMin() {\n        cout << \"- Compute expectedArmaMin() ... \";\n        save<double>(\"Arma.min\", Mat<double>({min(_genRowVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMax() {\n        cout << \"- Compute expectedArmaMax() ... \";\n        save<double>(\"Arma.max\", Mat<double>({max(_genRowVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaProd() {\n        cout << \"- Compute expectedArmaProd() ... \";\n        save<double>(\"Arma.prod\", Mat<double>({prod(_genRowVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaSum() {\n        cout << \"- Compute expectedArmaSum() ... \";\n        save<double>(\"Arma.sum\", Mat<double>({sum(_genRowVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMean() {\n        cout << \"- Compute expectedArmaMean() ... \";\n        save<double>(\"Arma.mean\", Mat<double>({mean(_genRowVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaMedian() {\n        cout << \"- Compute expectedArmaMedian() ... \";\n        save<double>(\"Arma.median\", Mat<double>({median(_genRowVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaStddev() {\n        cout << \"- Compute expectedArmaStddev() ... \";\n        save<double>(\"Arma.stddev\", Mat<double>({stddev(_genRowVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaVar() {\n        cout << \"- Compute expectedArmaVar() ... \";\n        save<double>(\"Arma.var\", Mat<double>({var(_genRowVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCor() {\n        cout << \"- Compute expectedArmaCor() ... \";\n        save<double>(\"Arma.cor\", Mat<double>({cor(_genRowVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaCov() {\n        cout << \"- Compute expectedArmaCov() ... \";\n        save<double>(\"Arma.cov\", Mat<double>({cov(_genRowVec)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaDiagmat() {\n        cout << \"- Compute expectedArmaDiagmat() ... \";\n        save<double>(\"Arma.diagmat\", diagmat(_genRowVec));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedArmaIs_finite() {\n        cout << \"- Compute expectedArmaIs_finite() ... \";\n\n        if(is_finite(_genRowVec)) {\n          save<double>(\"Arma.is_finite\", Mat<double>({1.0}));\n        } else {\n          save<double>(\"Arma.is_finite\", Mat<double>({0.0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedMat() {\n        cout << \"- Compute expectedMat() ... \";\n        save<double>(\"Mat\", _genRowVec);\n        cout << \"done.\" << endl;\n      }\n\n\t  void expectedRowVecSize() {\n\t\t  cout << \"- Compute expectedRowVecSize() ... \";\n\t\t  save<double>(\"Row.size\", Mat<double>({static_cast<double>(_genRowVec.size())}));\n\t\t  cout << \"done.\" << endl;\n      }\n\n\t  void expectedRowVecT() {\n\t\t  cout << \"- Compute expectedRowVecT() ... \";\n\t\t  save<double>(\"Row.t\", _genRowVec.t());\n\t\t  cout << \"done.\" << endl;\n      }\n\n\t  void expectedRowVecPrint() {\n\t\t  cout << \"- Compute expectedRowVecPrint() ... \";\n\n\t\t  ofstream expected(_filepath + \"Row.print(\" + _fileSuffix + \").txt\");\n\t\t  streambuf* previousBuffer = cout.rdbuf(expected.rdbuf());\n\n\t\t  _genRowVec.print();\n\n\t\t  cout.rdbuf(previousBuffer);\n\n\t\t  cout << \"done.\" << endl;\n      }\n\n\t  void expectedRowVecRaw_print() {\n\t\t  cout << \"- Compute expectedRowVecRaw_print() ... \";\n\n\t\t  ofstream expected(_filepath + \"Row.raw_print(\" + _fileSuffix + \").txt\");\n\t\t  streambuf* previousBuffer = cout.rdbuf(expected.rdbuf());\n\n\t\t  _genRowVec.raw_print();\n\n\t\t  cout.rdbuf(previousBuffer);\n\n\t\t  cout << \"done.\" << endl;\n      }\n\n      void expectedRowIs_finite() {\n        cout << \"- Compute expectedRowIs_finite() ... \";\n\n        if(_genRowVec.is_finite()) {\n          save<double>(\"Row.is_finite\", Row<double>({1}));\n        } else {\n          save<double>(\"Row.is_finite\", Row<double>({0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedRowMinA() {\n        cout << \"- Compute expectedRowMinA() ... \";\n        double value;\n        value = _genRowVec.min();\n        save<double>(\"Row.minA\", Row<double>({value}));\n\n        cout << \"done.\" << endl;\n      }\n\n      void expectedRowMaxA() {\n        cout << \"- Compute expectedRowMaxA() ... \";\n        double value;\n        value = _genRowVec.max();\n        save<double>(\"Row.maxA\", Row<double>({value}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedRowMinB() {\n        cout << \"- Compute expectedRowMinB() ... \";\n        uword value;\n        _genRowVec.min(value);\n        save<double>(\"Row.minB\", Row<double>({static_cast<double>(value)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedRowMaxB() {\n        cout << \"- Compute expectedRowMaxB() ... \";\n        uword value;\n        _genRowVec.max(value);\n        save<double>(\"Row.maxB\", Row<double>({static_cast<double>(value)}));\n        cout << \"done.\" << endl;\n      }\n\n      void expectedRowIs_empty() {\n        cout << \"- Compute expectedRowIs_empty() ... \";\n\n        if(_genRowVec.is_empty()) {\n          save<double>(\"Row.is_empty\", Row<double>({1}));\n        } else {\n          save<double>(\"Row.is_empty\", Row<double>({0}));\n        }\n\n        cout << \"done.\" << endl;\n      }\n\n\n  };\n}\n", "meta": {"hexsha": "a52942d12a3395634cb9515e6e0d9ace7a9f7501", "size": 17959, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/cpp/src/ExpectedGenRowVec.cpp", "max_stars_repo_name": "sebiniemann/ArmadilloJava", "max_stars_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-08-05T14:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-12T17:46:54.000Z", "max_issues_repo_path": "src/test/cpp/src/ExpectedGenRowVec.cpp", "max_issues_repo_name": "sebiniemann/ArmadilloJava", "max_issues_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2019-10-20T21:53:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-20T21:53:47.000Z", "max_forks_repo_path": "src/test/cpp/src/ExpectedGenRowVec.cpp", "max_forks_repo_name": "sebiniemann/ArmadilloJava", "max_forks_repo_head_hexsha": "061121e22708111a8df3a2da92f6278c3a581e26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-06T17:01:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T18:45:14.000Z", "avg_line_length": 28.1489028213, "max_line_length": 84, "alphanum_fraction": 0.5385600535, "num_tokens": 4500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891174511733, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.601068402751302}}
{"text": "#pragma once\n#ifndef __QTM_CORE_HPP__\n#define __QTM_CORE_HPP__\n\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <vector>\n\n#include <boost/core/noncopyable.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\nnamespace qtm {\n\n/**\n * Clamping the given value in given ranges\n *\n * @tparam type Type of the clamping value\n * @param[in] num Clamping value\n * @param[in] min_value Lower clamping limit\n * @param[in] max_value Upper clamping limit\n */\ntemplate <typename type> type clamp(type num, type min_value, type max_value) {\n  return std::max(std::min(num, max_value), min_value);\n}\n\n/**\n * Core queuing class\n *\n * ...\n *\n * Implements basic construction and solving final states;\n * also available getters/setters of internal characteristics\n */\nclass qtm final : private boost::noncopyable {\nprivate:\n  std::uint64_t channel_count_, queue_size_;\n  double la_, mu_, nu_;\n  std::int64_t n_;\n  boost::numeric::ublas::vector<double> final_states_;\n\n  bool is_fs_outdated_;\n\n  /**\n   * Perform auxiliary matrix initialization for future calculation\n   */\n  static boost::numeric::ublas::matrix<double>\n  matrix_init(std::uint64_t channel_count, std::uint64_t queue_size, double la,\n              double mu, double nu, std::int64_t n);\n\npublic:\n  /**\n   * Class construnctor\n   * Permorm construnction of the intance of the queuing system\n   *\n   * @param[in] channel_count Channel count of the queuing system\n   * @param[in] queue_size Queue size of the queuing system\n   * @param[in] la Input flow rate of the queuing system\n   * @param[in] mu Output flow rate  of the queuing system\n   * @param[in] nu Impatience rate of the queuing system\n   * @param[in] n Load sources of the queuing system\n   */\n  explicit qtm(std::uint64_t channel_count, std::uint64_t queue_size, double la,\n               double mu, double nu = 0, std::int64_t n = -1);\n  ~qtm(void) = default;\n\n  /**\n   * Get the current value of the channel count of the queuing system\n   */\n  std::uint64_t channel_count(void) const;\n  /**\n   * Get the current value of the queue size of the queuing system\n   */\n  std::uint64_t queue_size(void) const;\n  /**\n   * Get the current value of the load sources of the queuing system\n   */\n  std::int64_t n(void) const;\n  /**\n   * Get the current value of the input flow rate of the queuing system\n   */\n  double la(void) const;\n  /**\n   * Get the current value of the output flow rate of the queuing system\n   */\n  double mu(void) const;\n  /**\n   * Get the current value of the impatience rate of the queuing system\n   */\n  double nu(void) const;\n\n  /**\n   * Set the value of the channel count of the queuing system\n   *\n   * @param[in] channel_count_ New value of channel count\n   */\n  void channel_count(std::uint64_t channel_count_);\n  /**\n   * Set the value of the queue size of the queuing system\n   *\n   * @param[in] channel_count_ New value of queue size\n   */\n  void queue_size(std::uint64_t queue_size_);\n  /**\n   * Set the value of the load sources of the queuing system\n   *\n   * @param[in] channel_count_ New value of load sources\n   */\n  void n(std::int64_t n_);\n  /**\n   * Get the current value of the input flow rate of the queuing system\n   *\n   * @param[in] channel_count_ New value of input flow rate\n   */\n  void la(double la_);\n  /**\n   * Set the value of the output flow rate of the queuing system\n   *\n   * @param[in] channel_count_ New value of output flow rate\n   */\n  void mu(double mu_);\n  /**\n   * Set the value of the impatience rate of the queuing system\n   *\n   * @param[in] channel_count_ New value of impatience rate\n   */\n  void nu(double nu_);\n\n  /**\n   * Get the current value of the final states of the queuing system\n   *\n   * @throws std::runtime_error Thrown if final states calculation was not\n   * performed\n   */\n  std::vector<double> const final_states(void) const;\n  /**\n   * Get information that the final states hasn't been updated after changes\n   * to the internal characteristics of the queuing system.\n   */\n  bool is_fs_outdated(void) const;\n  /**\n   * Perform calculation he final states of the queuing system.\n   */\n  std::vector<double> calc_final_states(void);\n};\n\n}; // namespace qtm\n\n#endif // !__QTM_CORE_HPP__\n", "meta": {"hexsha": "8b90a5eb24c177dd66431824cda21756bf48ef8a", "size": 4263, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/qtm-calc/core.hpp", "max_stars_repo_name": "Andinoriel/qtm-calc", "max_stars_repo_head_hexsha": "940d88c2db187f75d74086bf8feb8e11f4c566e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-15T15:47:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T12:24:43.000Z", "max_issues_repo_path": "include/qtm-calc/core.hpp", "max_issues_repo_name": "andinoriel/qtm-calc", "max_issues_repo_head_hexsha": "940d88c2db187f75d74086bf8feb8e11f4c566e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/qtm-calc/core.hpp", "max_forks_repo_name": "andinoriel/qtm-calc", "max_forks_repo_head_hexsha": "940d88c2db187f75d74086bf8feb8e11f4c566e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-10T12:22:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T12:22:04.000Z", "avg_line_length": 28.0460526316, "max_line_length": 80, "alphanum_fraction": 0.6908280554, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6010683947485232}}
{"text": "#include <iostream>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include \"control.hpp\"\n\nusing namespace cv;\nusing namespace std;\nusing namespace sim;\n\n#include <Eigen/QR>\n\n/* Set value based on control system performance */\n// const double MIN_BALL_RADIUS_PX = 14;\nconst double MIN_CIRCLE_ECCENTRICITY = 0.01;\nconst uint32_t MIN_TRAJECTORY_POINTS = 10;\n\nstatic void polyfit(const vector<CircleMatch> &pnts,\n                    vector<double> &coeff,\n                    int order)\n{\n    vector<double> yv(pnts.size());\n\n    for (size_t i = 0; i < pnts.size(); i++)\n    {\n        yv[i] = pnts[i].pos.y;\n    }\n\n    Eigen::MatrixXd A(pnts.size(), order + 1);\n    Eigen::VectorXd yv_mapped = Eigen::VectorXd::Map(&yv.front(), yv.size());\n    Eigen::VectorXd result;\n\n    assert(pnts.size() >= order + 1);\n\n    for (size_t i = 0; i < pnts.size(); i++)\n    {\n        for (size_t j = 0; j < order + 1; j++)\n        {\n            A(i, j) = pow(pnts[i].pos.x, j);\n        }\n    }\n\n    result = A.householderQr().solve(yv_mapped);\n\n    coeff.resize(order + 1);\n    for (size_t i = 0; i < order + 1; i++)\n    {\n        coeff[i] = result[i];\n    }\n}\n\nstatic double getContourEccentricity(const Moments &mu)\n{\n    double m20s02 = mu.m20 - mu.m02;\n    double m20p02 = mu.m20 + mu.m02;\n\n    double bigSqrt = sqrt(m20s02 * m20s02 + 4 * mu.m11 * mu.m11);\n    return (m20p02 + bigSqrt) / (m20p02 - bigSqrt);\n}\n\nPlaneControl::PlaneControl(bool debugRender) : \n    m_isDebugRenderEnabled(debugRender)\n{\n}\n\ndouble PlaneControl::getAveragePredictedRadiusPx()\n{\n    if ( m_ballPoints.size() == 0 )\n        return 0;\n\n    double result = 0;\n\n    for ( const CircleMatch &mtch : m_ballPoints )\n    {\n        result += mtch.radius;\n    }\n\n    result /= m_ballPoints.size();\n\n    return result;\n}\n\nvoid PlaneControl::resetPredictions()\n{\n    m_ballPoints.clear();\n}\n\nint PlaneControl::getPlanePositionPrediction(Mat &ballFrame, int planeDistPx)\n{\n    CircleContour contours;\n    vector<CircleMatch> circles;\n    int resultControlY = ballFrame.size().height/2;\n\n    getCircleContours(ballFrame, contours);\n\n    for (const vector<Point> &contour : contours)\n    {\n        CircleMatch match;\n\n        minEnclosingCircle(contour,\n                           match.pos,\n                           match.radius);\n\n        // if (match.radius < MIN_BALL_RADIUS_PX)\n            // continue;\n\n        circles.push_back(match);\n    }\n\n    if (circles.size() > 0)\n    {\n        m_ballPoints.push_back(circles[0]);\n    }\n\n    /* Approximate previous points to predict future trajectory */\n    if (m_ballPoints.size() > MIN_TRAJECTORY_POINTS)\n    {\n        vector<double> coeffs;\n        polyfit(m_ballPoints, coeffs, 2);\n\n        assert(coeffs.size() == 3);\n\n        if (m_isDebugRenderEnabled)\n        {\n            for (int x = 0; x < ballFrame.size().width; x++)\n            {\n                int y = coeffs[0] + x * coeffs[1] + x * x * coeffs[2];\n\n                circle(ballFrame, Point(x, y), 1,\n                       Scalar(0, 0, 128), FILLED);\n            }\n        }\n\n        resultControlY = coeffs[0] +\n                         planeDistPx * coeffs[1] +\n                         planeDistPx * planeDistPx * coeffs[2];\n    }\n\n    /* Render detected centers */\n    if (m_isDebugRenderEnabled)\n    {\n        for (auto pnt_mtc : m_ballPoints)\n        {\n            circle(ballFrame,\n                   pnt_mtc.pos,\n                   2,\n                   Scalar(255, 0, 128),\n                   FILLED);\n        }\n    }\n\n    return resultControlY;\n}\n\nvoid PlaneControl::getRedFilteredFrame(const Mat &frame, Mat &binResultMask)\n{\n    /* In real situation GaussianBlur() is required */\n    Mat hsv;\n    cvtColor(frame, hsv, COLOR_BGR2HSV);\n\n    Mat lowerRedHueRange;\n    Mat upperRedHueRange;\n    inRange(hsv, cv::Scalar(0, 100, 100),\n            cv::Scalar(10, 255, 255),\n            lowerRedHueRange);\n    inRange(hsv, cv::Scalar(160, 100, 100),\n            cv::Scalar(179, 255, 255),\n            upperRedHueRange);\n\n    addWeighted(lowerRedHueRange, 1.0,\n                upperRedHueRange, 1.0,\n                0.0, binResultMask);\n}\n\nint PlaneControl::getCircleContours(Mat &frame, CircleContour &outContours)\n{\n    Mat redFiltered;\n    getRedFilteredFrame(frame, redFiltered);\n\n    CircleContour contours;\n    findContours(redFiltered, contours,\n                 RETR_TREE, CHAIN_APPROX_SIMPLE);\n\n    if (contours.size() > 0)\n    {\n        for (int i = 0; i < contours.size(); i++)\n        {\n            /* Simplified eccentricity estimation */\n\n            /* Requirements for ellipse */\n            if ( contours[i].size() > 5 )\n            {\n                RotatedRect result = fitEllipse( contours[i] );\n\n                if ( abs(1.0 - result.size.width / result.size.height) < MIN_CIRCLE_ECCENTRICITY )\n                    outContours.push_back(contours[i]);\n            }            \n\n            if (m_isDebugRenderEnabled)\n            {\n                drawContours(frame, contours, i, Scalar(255, 0, 0), 3);\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "ed8dd4335fa9bd0db58f881b814bbf4899a64063", "size": 5057, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/control.cpp", "max_stars_repo_name": "KaiL4eK/catch-a-ball-2d", "max_stars_repo_head_hexsha": "f419b571cc493b945ab9ed5851bbce7c0931c3c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/control.cpp", "max_issues_repo_name": "KaiL4eK/catch-a-ball-2d", "max_issues_repo_head_hexsha": "f419b571cc493b945ab9ed5851bbce7c0931c3c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/control.cpp", "max_forks_repo_name": "KaiL4eK/catch-a-ball-2d", "max_forks_repo_head_hexsha": "f419b571cc493b945ab9ed5851bbce7c0931c3c7", "max_forks_repo_licenses": ["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.5485436893, "max_line_length": 98, "alphanum_fraction": 0.5596203283, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.6010615079924686}}
{"text": "#include \"../../Headers/Edmonton.hpp\"\r\n#include <algorithm>\r\n#include <boost/multiprecision/cpp_int.hpp>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n/*\r\nSince the digit count for the numbers scale at an insane rate, we can safely assume that A and B are >= 90 and < 100. Rest can be bruteforced.\r\n*/\r\n\r\nint main(int argc, char *argv[]) {\r\n\tint max_digitial_sum = 0;\r\n\tfor(int a = 90; a < 100; a++) {\r\n\t\tfor(int b = 90; b < 100; b++) {\r\n\t\t\tmax_digitial_sum = max(max_digitial_sum, Edmonton::sumOfDigits<int, cpp_int>(boost::multiprecision::pow((cpp_int)a, b)));\r\n\t\t}\r\n\t}\r\n\tcout << max_digitial_sum << endl;\r\n}", "meta": {"hexsha": "4d541c2fce9f6bc12680563d736fe16786a3c550", "size": 651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/51-100/56/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/51-100/56/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/51-100/56/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 31.0, "max_line_length": 143, "alphanum_fraction": 0.6697388633, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.6010614968020775}}
{"text": "#ifndef _PLAN_CONTAINER_MID_H_\n#define _PLAN_CONTAINER_MID_H_\n\n\n#include <Eigen/Eigen>\n#include <vector>\n\n#include <ros/ros.h>\n\n#include <arena_traj_planner/uniform_bspline.h>\n#include <arena_traj_planner/polynomial_traj.h>\n\nusing std::vector;\n\n\nstruct LandmarkPoint{\n  bool is_visited;\n  int id;\n  Eigen::Vector2d pos;\n\n  LandmarkPoint(Eigen::Vector2d pos,int id){\n    this->pos=pos;\n    this->id=id;\n    this->is_visited=false;\n  }\n\n  ~LandmarkPoint(){};\n  void setVisited(bool is_visited){\n    this->is_visited=is_visited;\n  }\n};\n\n\n\nclass GlobalData{\nprivate:\n  double dist_next_wp_;\n  double dist_tolerance_;\n  double rou_thresh_;\n  int id_last_landmark_;\n\n  void resetLandmarks(){\n    /* init */\n    global_path_.clear();\n    landmark_points_.clear();\n    double rou_t, rou_last=-1;\n    double gradient_t,gradient_last=1000;\n    Eigen::Vector2d last_landmark=start_pos_;\n    int id=0;\n    bool flag_landmark_search_done=false;\n\n    int continue_descent_counter=0;\n    \n    /* search landmark pt according to curvature radius */\n    for (double t = tm_start_; t <= tm_end_; t += 0.01) {\n      // get pos\n      Eigen::Vector2d pos_t = getPosition(t);\n      global_path_.push_back(pos_t);\n      if(flag_landmark_search_done){\n        continue;\n      }\n      // calculate curvature radius\n      rou_t=calculateCurveRadius(getVelocity(t),getAcceleration(t));\n      //std::cout<<\"********************* rou=\"<<rou_t<<std::endl;\n      // calculate gradient\n      gradient_t=rou_t-rou_last;\n      \n      // set continue_descent_counter\n      if(gradient_t<-5.0){\n        continue_descent_counter++;\n      }else{\n        continue_descent_counter=0;\n      }\n\n      if(std::abs(gradient_t)<0.2){\n        gradient_t=gradient_last;\n        rou_t=rou_last;\n      }\n\n      /* minimum vaule of the curvature radius || curvature radius is so small */\n      if((gradient_t>0 && gradient_last<0)|| rou_t<rou_thresh_|| continue_descent_counter>80){ //  //gradient_t*gradient_last<0\n        //std::cout<<\"in1************ rou=\"<<rou_t<<std::endl;\n        // negelect the start points \n        if((pos_t-start_pos_).squaredNorm()<=dist_next_wp_ && rou_t>rou_thresh_){\n          rou_last=rou_t;\n          gradient_last=gradient_t;\n          continue;\n        }\n        // reset continue_descent_counter\n        \n        if(continue_descent_counter>80){\n          //std::cout<<\"in counter************ rou=\"<<rou_t<<std::endl;\n        }\n\n        //std::cout<<\"in2************ rou=\"<<rou_t<<std::endl;\n        // make sure two landmarks are not too close\n        if((pos_t-last_landmark).squaredNorm()>2.0)\n        { \n          \n          landmark_points_.push_back(LandmarkPoint(pos_t,id));\n          last_landmark=pos_t;\n          id++;\n          continue_descent_counter=0;\n          //std::cout<<\"add************ rou=\"<<rou_t<<std::endl;\n        }\n        \n      }else if((pos_t-end_pos_).squaredNorm()<=dist_next_wp_){\n        // add end point as last landmark\n        landmark_points_.push_back(LandmarkPoint(end_pos_,id));\n        flag_landmark_search_done=true;\n      }\n      rou_last=rou_t;\n      gradient_last=gradient_t;\n    }\n\n    // add end_pos to global path\n    global_path_.push_back(end_pos_);\n    // reset landmark counter\n    id_last_landmark_=0;\n  } \n\n  Eigen::Vector2d getPosition(double t){\n      return global_pos_traj_.evaluateDeBoor(t);\n  }\n\n  Eigen::Vector2d getVelocity(double t){\n      return global_vel_traj_.evaluateDeBoor(t);\n  }\n\n  Eigen::Vector2d getAcceleration(double t){\n      return global_acc_traj_.evaluateDeBoor(t);\n  }\n\n  double calculateCurveRadius(Eigen::Vector2d vel,Eigen::Vector2d acc){\n    double rou=std::pow(vel.squaredNorm(),3)/(vel(0)*acc(1)-vel(1)*acc(0));\n    return std::abs(rou);\n  }\n\npublic:\n  UniformBspline global_pos_traj_, global_vel_traj_, global_acc_traj_;\n  double tm_start_, tm_end_;\n  Eigen::Vector2d start_pos_, end_pos_;\n\n  std::vector<Eigen::Vector2d> global_path_;\n  std::vector<LandmarkPoint> landmark_points_;\n  \n  GlobalData(){};\n  ~GlobalData(){};\n  \n  void setGlobalDataParam(double dist_next_wp, double dist_tolerance, double rou_thresh){\n    dist_next_wp_=dist_next_wp;\n    dist_tolerance_=dist_tolerance;\n    rou_thresh_=rou_thresh;\n  }\n\n  void resetGlobalData(const UniformBspline & traj){\n    global_pos_traj_= traj;\n    global_vel_traj_=global_pos_traj_.getDerivative();\n    global_acc_traj_=global_vel_traj_.getDerivative();\n    global_pos_traj_.getTimeSpan(tm_start_, tm_end_);\n    start_pos_=getPosition(tm_start_);\n    end_pos_=getPosition(tm_end_);\n    resetLandmarks();\n  }\n\n  void getGlobalPath(std::vector<Eigen::Vector2d> &global_path){\n     global_path=global_path_;\n  }\n\n  void getLandmarks(std::vector<Eigen::Vector2d> & landmark_pts){\n\n     for(int i=0;i<landmark_points_.size();i++){\n       landmark_pts.push_back(landmark_points_[i].pos);\n     }\n  }\n\n  Eigen::Vector2d getLocalTarget(Eigen::Vector2d &current_pt){\n    Eigen::Vector2d target_pt;\n    Eigen::Vector2d landmark_pt;\n    \n    double dist_to_last_landmark;\n    dist_to_last_landmark=(landmark_points_[id_last_landmark_].pos-current_pt).squaredNorm();\n\n    // check if landmark point is arrived, and update target landmark id\n    if(dist_to_last_landmark<dist_tolerance_){\n      id_last_landmark_++;\n\n      if(id_last_landmark_>=landmark_points_.size()){\n        id_last_landmark_=landmark_points_.size()-1;\n      }\n    }\n\n    // set landmark pos\n    landmark_pt=landmark_points_[id_last_landmark_].pos;\n\n    // calculate the target_pt at the direction of landmark pos\n    double a;\n    a=dist_next_wp_/(current_pt-landmark_pt).squaredNorm();\n    target_pt=current_pt+a*(landmark_pt-current_pt);\n\n    return target_pt;\n  }\n\n  \n};\n\n\n\n\nclass GlobalTrajData\n{\n  private:\n  public:\n    PolynomialTraj global_traj_;\n    std::vector<UniformBspline> local_traj_;\n\n    double global_duration_;\n    ros::Time global_start_time_;\n\n    double local_start_time_, local_end_time_;\n    double time_increase_;\n    double last_time_inc_;\n    double last_progress_time_;\n\n    GlobalTrajData(/* args */) {}\n    ~GlobalTrajData() {}\n\n    bool localTrajReachTarget() { return fabs(local_end_time_ - global_duration_) < 0.1; }\n\n    void setGlobalTraj(const PolynomialTraj &traj, const ros::Time &time)\n    {\n      global_traj_ = traj;\n      global_traj_.init();\n      global_duration_ = global_traj_.getTimeSum();\n      global_start_time_ = time;\n\n      local_traj_.clear();\n      local_start_time_ = -1;\n      local_end_time_ = -1;\n      time_increase_ = 0.0;\n      last_time_inc_ = 0.0;\n      last_progress_time_ = 0.0;\n    }\n\n\n    void setLocalTraj(UniformBspline traj, double local_ts, double local_te, double time_inc)\n    {\n      local_traj_.resize(3);\n      local_traj_[0] = traj;\n      local_traj_[1] = local_traj_[0].getDerivative();\n      local_traj_[2] = local_traj_[1].getDerivative();\n\n      local_start_time_ = local_ts;\n      local_end_time_ = local_te;\n      global_duration_ += time_inc;\n      time_increase_ += time_inc;\n      last_time_inc_ = time_inc;\n    }\n\n    Eigen::Vector2d getPosition(double t)\n    {\n      if (t >= -1e-3 && t <= local_start_time_)\n      {\n        return global_traj_.evaluate(t - time_increase_ + last_time_inc_);\n      }\n      else if (t >= local_end_time_ && t <= global_duration_ + 1e-3)\n      {\n        return global_traj_.evaluate(t - time_increase_);\n      }\n      else\n      {\n        double tm, tmp;\n        local_traj_[0].getTimeSpan(tm, tmp);\n        return local_traj_[0].evaluateDeBoor(tm + t - local_start_time_);\n      }\n    }\n\n    Eigen::Vector2d getVelocity(double t)\n    {\n      if (t >= -1e-3 && t <= local_start_time_)\n      {\n        return global_traj_.evaluateVel(t);\n      }\n      else if (t >= local_end_time_ && t <= global_duration_ + 1e-3)\n      {\n        return global_traj_.evaluateVel(t - time_increase_);\n      }\n      else\n      {\n        double tm, tmp;\n        local_traj_[0].getTimeSpan(tm, tmp);\n        return local_traj_[1].evaluateDeBoor(tm + t - local_start_time_);\n      }\n    }\n\n    Eigen::Vector2d getAcceleration(double t)\n    {\n      if (t >= -1e-3 && t <= local_start_time_)\n      {\n        return global_traj_.evaluateAcc(t);\n      }\n      else if (t >= local_end_time_ && t <= global_duration_ + 1e-3)\n      {\n        return global_traj_.evaluateAcc(t - time_increase_);\n      }\n      else\n      {\n        double tm, tmp;\n        local_traj_[0].getTimeSpan(tm, tmp);\n        return local_traj_[2].evaluateDeBoor(tm + t - local_start_time_);\n      }\n    }\n\n\n    // get Bspline paramterization data of a local trajectory within a sphere\n    // start_t: start time of the trajectory\n    // dist_pt: distance between the discretized points\n    void getTrajByRadius(const double &start_t, const double &des_radius, const double &dist_pt,\n                         vector<Eigen::Vector2d> &point_set, vector<Eigen::Vector2d> &start_end_derivative,\n                         double &dt, double &seg_duration)\n    {\n      double seg_length = 0.0; // length of the truncated segment\n      double seg_time = 0.0;   // duration of the truncated segment\n      double radius = 0.0;     // distance to the first point of the segment\n\n      double delt = 0.2;\n      Eigen::Vector2d first_pt = getPosition(start_t); // first point of the segment\n      Eigen::Vector2d prev_pt = first_pt;              // previous point\n      Eigen::Vector2d cur_pt;                          // current point\n\n      // go forward until the traj exceed radius or global time\n      while (radius < des_radius && seg_time < global_duration_ - start_t - 1e-3)\n      {\n        seg_time += delt;\n        seg_time = min(seg_time, global_duration_ - start_t);\n\n        cur_pt = getPosition(start_t + seg_time);\n        seg_length += (cur_pt - prev_pt).norm();\n        prev_pt = cur_pt;\n        radius = (cur_pt - first_pt).norm();\n      }\n\n      // get parameterization dt by desired density of points\n      int seg_num = floor(seg_length / dist_pt);\n\n      // get outputs\n\n      seg_duration = seg_time; // duration of the truncated segment\n      dt = seg_time / seg_num; // time difference between two points\n\n      for (double tp = 0.0; tp <= seg_time + 1e-4; tp += dt)\n      {\n        cur_pt = getPosition(start_t + tp);\n        point_set.push_back(cur_pt);\n      }\n\n      start_end_derivative.push_back(getVelocity(start_t));\n      start_end_derivative.push_back(getVelocity(start_t + seg_time));\n      start_end_derivative.push_back(getAcceleration(start_t));\n      start_end_derivative.push_back(getAcceleration(start_t + seg_time));\n    }\n    \n    // get Bspline paramterization data of a fixed duration local trajectory\n    // start_t: start time of the trajectory\n    // duration: time length of the segment\n    // seg_num: discretized the segment into *seg_num* parts\n    void getTrajByDuration(double start_t, double duration, int seg_num,vector<Eigen::Vector2d> &point_set,vector<Eigen::Vector2d> &start_end_derivative, double &dt)\n    {\n      dt = duration / seg_num;\n      Eigen::Vector2d cur_pt;\n      for (double tp = 0.0; tp <= duration + 1e-4; tp += dt)\n      {\n        cur_pt = getPosition(start_t + tp);\n        point_set.push_back(cur_pt);\n      }\n\n      start_end_derivative.push_back(getVelocity(start_t));\n      start_end_derivative.push_back(getVelocity(start_t + duration));\n      start_end_derivative.push_back(getAcceleration(start_t));\n      start_end_derivative.push_back(getAcceleration(start_t + duration));\n    }\n\n};\n\n\nstruct PlanParameters\n{\n    /* planning algorithm parameters */\n    double max_vel_, max_acc_, max_jerk_; // physical limits\n    double ctrl_pt_dist_;                  // distance between adjacient B-spline control points\n    double feasibility_tolerance_;        // permitted ratio of vel/acc exceeding limits\n    double planning_horizen_;\n\n    /* global data param */\n    double dist_next_wp_;           // distance from current location to next waypoint\n    double dist_tolerance_;         // distance tolerance for arriving\n    double rou_thresh_;             // thresh hold of curature radius for determin landmark points\n\n    /* flags */\n    bool use_astar_, use_kino_astar_, use_oneshot_;\n    bool use_optimization_esdf_, use_optimization_astar_;\n\n    /* processing time */\n    //double time_search_ = 0.0;\n    //double time_optimize_ = 0.0;\n    //double time_adjust_ = 0.0;\n};\n\nstruct LocalTrajData\n{\n    /* info of generated traj */\n\n    int traj_id_;\n    double duration_;\n    double global_time_offset; // This is because when the local traj finished and is going to switch back to the global traj, the global traj time is no longer matches the world time.\n    ros::Time start_time_;\n    Eigen::Vector2d start_pos_;\n    UniformBspline position_traj_, velocity_traj_, acceleration_traj_;\n};\n\n\n#endif", "meta": {"hexsha": "57597b3eeff0f67201ac2b9b1a6258a4ae61a082", "size": 12720, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "arena_navigation/arena_intermediate_planner/include/arena_intermediate_planner/plan_container_mid.hpp", "max_stars_repo_name": "ignc-research/arena-marl", "max_stars_repo_head_hexsha": "3b9b2521436ef7f364a250da71a01e915d840296", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-11-11T13:25:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T21:34:41.000Z", "max_issues_repo_path": "arena_navigation/arena_intermediate_planner/include/arena_intermediate_planner/plan_container_mid.hpp", "max_issues_repo_name": "ignc-research/arena-marl", "max_issues_repo_head_hexsha": "3b9b2521436ef7f364a250da71a01e915d840296", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-20T20:34:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-20T20:34:14.000Z", "max_forks_repo_path": "arena_navigation/arena_intermediate_planner/include/arena_intermediate_planner/plan_container_mid.hpp", "max_forks_repo_name": "ignc-research/arena-marl", "max_forks_repo_head_hexsha": "3b9b2521436ef7f364a250da71a01e915d840296", "max_forks_repo_licenses": ["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.1421800948, "max_line_length": 184, "alphanum_fraction": 0.6565251572, "num_tokens": 3182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.6654105454764746, "lm_q1q2_score": 0.6010614908085671}}
{"text": "/**\n * \\ file TanFilter.cpp\n */\n\n#include <array>\n#include <fstream>\n\n#include <ATK/config.h>\n\n#include <ATK/Tools/TanFilter.h>\n#include <ATK/Mock/SimpleSinusGeneratorFilter.h>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <gtest/gtest.h>\n\nconstexpr gsl::index PROCESSSIZE = 1000;\nconstexpr gsl::index SAMPLING_RATE = 1024*64;\n\nTEST(TanFilter, const_sin1k)\n{\n  ATK::SimpleSinusGeneratorFilter<double> generator;\n  generator.set_output_sampling_rate(SAMPLING_RATE);\n  generator.set_amplitude(1);\n  generator.set_frequency(1000);\n  \n  ATK::TanFilter<double> filter;\n  filter.set_input_sampling_rate(SAMPLING_RATE);\n  filter.set_output_sampling_rate(SAMPLING_RATE);\n  \n  filter.set_input_port(0, generator, 0);\n  filter.process(PROCESSSIZE);\n  \n  auto sin = generator.get_output_array(0);\n  auto array = filter.get_output_array(0);\n  \n  for(size_t i = 0; i < PROCESSSIZE; ++i)\n  {\n    ASSERT_NEAR(array[i], std::tan(sin[i] * boost::math::constants::pi<double>() / SAMPLING_RATE), 0.00001);\n  }\n}\n", "meta": {"hexsha": "3fec54852623b55aa3d108f102c0abffb801fedd", "size": 1004, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/Tools/TanFilter.cpp", "max_stars_repo_name": "AudioTK/AudioTK", "max_stars_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T10:47:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:45:00.000Z", "max_issues_repo_path": "tests/Tools/TanFilter.cpp", "max_issues_repo_name": "AudioTK/AudioTK", "max_issues_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T15:45:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T19:39:05.000Z", "max_forks_repo_path": "tests/Tools/TanFilter.cpp", "max_forks_repo_name": "AudioTK/AudioTK", "max_forks_repo_head_hexsha": "dba42eea68534501efe74692b74edf4792cca231", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T03:28:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T00:47:11.000Z", "avg_line_length": 23.9047619048, "max_line_length": 108, "alphanum_fraction": 0.7330677291, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.601049257753481}}
{"text": "#include <dimensional/quantity.hpp>\n#include <dimensional/arithmetic.hpp>\n#include <dimensional/systems/si/all.hpp>\n#include <dimensional/systems/nonsi/hour.hpp>\n#include <dimensional/systems/si/derived_units/area.hpp>\n#include <dimensional/systems/si/derived_units/angle.hpp>\n#include <dimensional/io.hpp>\n\n#include <dimensional/systems/si/prefix.hpp>\n#include <dimensional/math/all.hpp>\n#include <dimensional/systems/currency/jpy.hpp>\n#include <dimensional/systems/nonsi/degree_celsius.hpp>\n#include <dimensional/expr.hpp>\n#include <dimensional/delta.hpp>\n#include <boost/type_index.hpp>\n#include <iostream>\n\n\n#define REPL(...) \\\n    do { std::cout << \"$ \" << #__VA_ARGS__ << \"\\n=> \" << (__VA_ARGS__) << std::endl; } while(false)\nint main(){\n    using namespace mitama;\n    namespace si = mitama::systems::si;\n    namespace nonsi = mitama::systems::nonsi;\n    { // Homogeneous dimension examples\n        std::cout << \"--[Homogeneous dimension examples]--\\n\";\n\n        // quantity<Dimension, Type = double>:\n        // quantity is the type T that is meaningful by Dimension;\n        // Dimension is a phantom template parameter.\n        constexpr quantity<si::meter_t, int> a = 2;\n        constexpr quantity<si::millimeter_t, int> b = 2;\n        \n        // `a + b` is valid operation if and only if `a` and `b` has same base dimensions.\n        auto r1 = a + b;\n        REPL(r1);\n        \n        // `a - b` is valid operation if and only if `a` and `b` has same base dimensions.\n        auto r2 = a - b;\n        REPL(r2);\n        \n        // `a * b` is always valid and:\n        // - Result quantity has heterogeneous dimension inducted from `a` and `b`, and\n        // - If both a and b values are of the same dimension, these values are automatically scaled to high precision units.\n        auto r3 = a * b;\n        REPL(r3);\n\n        // a / b := a * b^{-1}\n        auto r4 = a / b;\n        REPL(r4);\n        REPL(1 + r4);       \n        REPL(boost::typeindex::type_id<decltype(r4)>().pretty_name());\n\n        quantity<si::millimeter_t, int> d(a);\n        REPL(d);\n\n        constexpr auto e = 3 | si::meter<2> ;\n        constexpr auto f = 3 | si::millimeter<2> ;\n        REPL(e);\n        REPL(f);\n        REPL(e + f);\n\n        auto v = (1|si::meters) * (1|si::millimeters);\n        auto u = (1|si::centimeters);\n        REPL(v);\n        REPL(u);\n        REPL(v/u);\n        quantity<si::millimeter_t, int> milli = u;\n        REPL(milli);\n        std::cout << \"------------------------\\n\";\n    }\n\n    { // Heterogeneous dimesnsion examples\n        std::cout << \"--[Heterogeneous dimension examples]--\\n\";\n        // speed := km/h\n        using speed_t = decltype(si::kilometers/nonsi::hour_t{});\n\n        constexpr quantity<si::meter_t> L(1.2);\n        constexpr quantity<si::second_t> T(0.3);\n        // unit is automatically convert from m/s to km/h\n        quantity<speed_t> V = L/T;\n        std::cout << boost::typeindex::type_id<decltype(L*T)>().pretty_name() << std::endl;\n\n        std::cout << V.value() << \"[ km/h ]\" << std::endl;\n        {\n            auto w = 36 | si::kilogram<> * si::meter<2> * si::second<-2> * si::ampere<-1>;\n            std::cout << boost::typeindex::type_id<decltype(w)>().pretty_name() << std::endl;\n        }\n        using newton_t = decltype(si::kilogram<> * si::meter<> * si::second<-2>);\n        quantity<newton_t> N = (1.0|si::kilograms) * V / (2|si::seconds);\n        REPL(N);\n        std::cout << \"------------------------\\n\";\n    }\n\n    { // compare examples\n        std::cout << \"--[dimension type comparisons examples]--\\n\";\n        std::cout << std::boolalpha;\n        REPL((1|si::meters) == (1|si::millimeters));\n        REPL((1|si::meters) == (1000|si::millimeters));\n        REPL((1|si::meters) != (1|si::millimeters));\n        REPL((1|si::meters) != (1000|si::millimeters));\n        REPL((1|si::meters) < (1|si::millimeters));\n        REPL((1|si::meters) > (1|si::millimeters));\n        REPL((1|si::meters) < (1000|si::millimeters));\n        REPL((1|si::meters) > (1000|si::millimeters));\n        REPL((1|si::meters) <= (1000|si::millimeters));\n        REPL((1|si::meters) >= (1000|si::millimeters));\n        std::cout << \"------------------------\\n\";\n    }\n\n    { // math function examples\n        std::cout << \"--[dimension type math functions examples]--\\n\";\n        quantity_t<std::decay_t<decltype(si::millimeter<2>)>, double> v = (1|si::meters) * (1|si::millimeters);\n        REPL(sqrt(v));\n        REPL(cbrt(v));\n\n        REPL(mitama::min((1|si::meters),(1|si::millimeters),(1|si::centimeters)));\n        REPL(mitama::max((1|si::meters),(1|si::millimeters),(1|si::centimeters)));\n        std::cout << \"------------------------\\n\";\n\n        REPL(pow<5>(2|si::meters));\n        REPL(square(2|si::meters));\n        REPL(cubic(2|si::meters));\n\n        REPL(hypot(2.|si::meters, 2.|si::meters));\n\n        REPL(ceil(2.2|si::meters));\n        REPL(floor(2.2|si::meters));\n        REPL(trunc(2.2|si::meters));\n        REPL(round(2.2|si::meters));\n        REPL(lround(2.2|si::meters));\n        REPL(llround(2.2|si::meters));\n        REPL(nearbyint(2.2|si::meters));\n        REPL(rint(2.2|si::meters));\n        REPL(lrint(2.2|si::meters));\n        REPL(llrint(2.2|si::milli*si::meters));\n    }\n\n    { // User defined dimension examples\n        // currency units\n        REPL(100|yen);\n    }\n\n    { // User defined dimension examples\n        // currency units\n        REPL(100|nonsi::degree_celsius);\n        quantity<si::kelvin_t> s( 100.|nonsi::degree_celsius );\n        REPL(s);\n    }\n\n    {\n        quantity<si::kelvin_t> hoge = as_expr(1|si::kelvins) + (2|nonsi::degree_celsius);\n        REPL(hoge);\n    }\n\n    {\n        quantity_t a1 = accepts<si::area_r> |= (2|si::meters) * (7|si::meters);\n        REPL(a1);\n\n        quantity_t a2 = accepts<si::area_r> |= (2|si::millimeters) * (7|si::millimeters);\n        REPL(a2);\n\n        // error!\n        // quantity_t a3 = accepts<area_r> |= (2|si::millimeters);\n\n        quantity_t a3 = partial_accepts_for<sym::M<>> |= (2|si::meters) * (2|si::meters) * (2|si::kilograms) / (2|si::second<2>);\n        REPL(a3);\n    }\n\n    {\n        delta d = (2|si::kelvins) - (1|si::kelvins);\n        REPL((1|nonsi::degree_celsius) + d);\n    }\n\n    {\n        quantity_t m = 1.0 | si::meters * si::radian;\n        quantity_for<double, si::meter_<>> x = m.into();\n        REPL(x);\n    }\n}", "meta": {"hexsha": "93d9a7fe2e129da08165e43d4c2583bb2fd79ef5", "size": 6367, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/overview.cpp", "max_stars_repo_name": "LoliGothick/mitama-dimensional", "max_stars_repo_head_hexsha": "46b9ae3764bd472da9ed5372afd82e6b5d542543", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2019-01-18T11:51:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T02:46:43.000Z", "max_issues_repo_path": "example/overview.cpp", "max_issues_repo_name": "LoliGothick/mitama-dimensional", "max_issues_repo_head_hexsha": "46b9ae3764bd472da9ed5372afd82e6b5d542543", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-02-10T23:12:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-06T21:05:09.000Z", "max_forks_repo_path": "example/overview.cpp", "max_forks_repo_name": "LoliGothick/mitama-dimensional", "max_forks_repo_head_hexsha": "46b9ae3764bd472da9ed5372afd82e6b5d542543", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-02-27T11:53:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-20T21:59:59.000Z", "avg_line_length": 35.3722222222, "max_line_length": 129, "alphanum_fraction": 0.5471964819, "num_tokens": 1898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950986284991, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6010492545194055}}
{"text": "#ifndef FDM_HH\n#define FDM_HH\n\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n\n#include \"PDE.hh\"\n\ntypedef std::vector<Eigen::VectorXd> matrix;\n\nclass FDMBase {\n protected:\n  std::shared_ptr<BlackScholesPDE> pde;\n\n  //Space domain [Nminus*dx,Nplus*dx]\n  int long Nminus;\n  int long Nplus;\n  int long N;\n  double dx;\n  std::vector<double> x_values;\n\n  //Time domain [0, 1/2*simga^2*T]\n  unsigned long M; \n  double dt;\n  std::vector<double> tau_values;\n\n  //coefficients\n  double alpha;\n\n  //initial vector;\n  Eigen::VectorXd u0;\n\n  //matrices\n  Eigen::SparseMatrix<double, Eigen::RowMajor> A, I;\n\n  // Constructor\n  FDMBase(int _N , double dx, unsigned long _M, std::shared_ptr<BlackScholesPDE> _pde);\n\n  void calculate_step_sizes();\n  void set_initial_conditions();\n  void calculate_boundary_conditions(Eigen::VectorXd&, double);\n\n public:\n\n  double get_dt()const{ return dt; }\n  double get_dx()const{ return dx; }\n  double get_alpha()const{ return alpha; }\n  std::vector<double> get_x() const{ return x_values; }\n  std::vector<double> get_tau() const{ return tau_values; }\n\n\n  void BuildMatrix();\n  void change_var(matrix&);\n  virtual matrix solve() = 0;\n};\n\n\nclass FDMEulerExplicit : public FDMBase {\n public:\n  FDMEulerExplicit(int _N, double dx, unsigned long _M, std::shared_ptr<BlackScholesPDE> _pde):\n    FDMBase(_N, dx, _M, _pde){}\n\n  matrix solve();\n};\n\n\nclass FDMEulerImplicit : public FDMBase{\n  public:\n    FDMEulerImplicit(int _N, double dx, unsigned long _M, std::shared_ptr<BlackScholesPDE> _pde):\n      FDMBase(_N, dx, _M, _pde){}\n\n    matrix solve();\n};\n\nclass FDMCranckNicholson : public FDMBase{\npublic:\n  FDMCranckNicholson(int _N, double dx, unsigned long _M, std::shared_ptr<BlackScholesPDE> _pde):\n    FDMBase(_N, dx, _M, _pde){}\n\n  matrix solve();\n};\n\n\n\n\n#endif\n", "meta": {"hexsha": "a1d16b77ea751b238cd3219990bd5ea4aab330f2", "size": 1829, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Finite_Difference/FDM.hh", "max_stars_repo_name": "lorenzovitali/Progetto", "max_stars_repo_head_hexsha": "7b54a8bc2c29ecbb9b1ed08403818d143a8a5884", "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": "Finite_Difference/FDM.hh", "max_issues_repo_name": "lorenzovitali/Progetto", "max_issues_repo_head_hexsha": "7b54a8bc2c29ecbb9b1ed08403818d143a8a5884", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Finite_Difference/FDM.hh", "max_forks_repo_name": "lorenzovitali/Progetto", "max_forks_repo_head_hexsha": "7b54a8bc2c29ecbb9b1ed08403818d143a8a5884", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5505617978, "max_line_length": 97, "alphanum_fraction": 0.7020229634, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6010492525987927}}
{"text": "#include <opencv2/opencv.hpp>\n#include <sophus/se3.hpp>\n#include <Eigen/Core>\n#include <vector>\n#include <string>\n#include <boost/format.hpp>\n#include <iostream>\n\nusing namespace std;\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\n\n// Camera intrinsics\n// \u5185\u53c2\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n// \u57fa\u7ebf\ndouble baseline = 0.573;\n// paths\nstring left_file = \"../left.png\";\nstring disparity_file = \"../disparity.png\";\nboost::format fmt_others(\"../%06d.png\"); // other files\n\n// useful typedefs\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\ntypedef Eigen::Matrix<double, 2, 6> Matrix26d;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n// TODO implement this function\n/**\n * pose estimation using direct method\n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationMultiLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,\n    Sophus::SE3d &T21,\n    bool show = false);\n\n// TODO implement this function\n/**\n * pose estimation using direct method\n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationSingleLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,\n    Sophus::SE3d &T21,\n    bool show = false);\n\n// bilinear interpolation\ninline float GetPixelValue(const cv::Mat &img, float x, float y)\n{\n    uchar *data = &img.data[int(y) * img.step + int(x)];\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n    return float(\n        (1 - xx) * (1 - yy) * data[0] +\n        xx * (1 - yy) * data[1] +\n        (1 - xx) * yy * data[img.step] +\n        xx * yy * data[img.step + 1]);\n}\n\nint main(int argc, char **argv)\n{\n\n    cv::Mat left_img = cv::imread(left_file, 0);\n    cv::Mat disparity_img = cv::imread(disparity_file, 0);\n\n    // let's randomly pick pixels in the first image and generate some 3d points in the first image's frame\n    cv::RNG rng;\n    int nPoints = 1000;\n    int boarder = 40;\n    VecVector2d pixels_ref;\n    vector<double> depth_ref;\n\n    // generate pixels in ref and load depth data\n    for (int i = 0; i < nPoints; i++)\n    {\n        int x = rng.uniform(boarder, left_img.cols - boarder); // don't pick pixels close to boarder\n        int y = rng.uniform(boarder, left_img.rows - boarder); // don't pick pixels close to boarder\n        int disparity = disparity_img.at<uchar>(y, x);\n        double depth = fx * baseline / disparity; // you know this is disparity to depth\n        depth_ref.push_back(depth);\n        pixels_ref.push_back(Eigen::Vector2d(x, y));\n    }\n\n    // estimates 01~05.png's pose using this information\n    Sophus::SE3d T_cur_ref;\n\n    for (int i = 1; i < 6; i++)\n    { // 1~10\n        cout<<\"Image \"<<i<<\"--------------------------------------\"<<endl;\n        cv::Mat img = cv::imread((fmt_others % i).str(), 0);\n        // DirectPoseEstimationSingleLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref, true); // first you need to test single layer\n        DirectPoseEstimationMultiLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref, true);\n    }\n}\n\nvoid DirectPoseEstimationSingleLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,\n    Sophus::SE3d &T21,\n    bool show)\n{\n\n    // parameters\n    int half_patch_size = 4;\n    int iterations = 100;\n\n    double cost = 0, lastCost = 0;\n    int nGood = 0; // good projections\n    VecVector2d goodProjection;\n    VecVector2d goodOriginal;\n\n    int iter_cnt = 0;\n    for (int iter = 0; iter < iterations; iter++)\n    {\n        iter_cnt = iter;\n        nGood = 0;\n        goodProjection.clear();\n        goodOriginal.clear();\n\n        // Define Hessian and bias\n        Matrix6d H = Matrix6d::Zero(); // 6x6 Hessian\n        Vector6d b = Vector6d::Zero(); // 6x1 bias\n\n        for (size_t i = 0; i < px_ref.size(); i++)\n        {\n\n            // compute the projection in the second image\n            // TODO START YOUR CODE HERE\n            Eigen::Vector3d P((px_ref[i][0] - cx) / fx, (px_ref[i][1] - cy) / fy, 1);\n            P *= depth_ref[i];\n            Eigen::Vector3d q = T21 * P;\n            float u = q[0] / q[2] * fx + cx, v = q[1] / q[2] * fy + cy;\n\n            if (u <= half_patch_size || u >= img2.cols - half_patch_size || v <= half_patch_size || v >= img2.rows - half_patch_size)\n            {\n                continue;\n            }\n            nGood++;\n            goodProjection.push_back(Eigen::Vector2d(u, v));\n            goodOriginal.push_back(px_ref[i]);\n\n            // and compute error and jacobian\n            for (int x = -half_patch_size; x < half_patch_size; x++)\n                for (int y = -half_patch_size; y < half_patch_size; y++)\n                {\n\n                    double error = GetPixelValue(img1, px_ref[i][0] + x, px_ref[i][1] + y) - GetPixelValue(img2, u + x, v + y);\n\n                    Matrix26d J_pixel_xi; // pixel to \\xi in Lie algebra\n                    J_pixel_xi(0, 0) = fx / q[2];\n                    J_pixel_xi(0, 1) = 0;\n                    J_pixel_xi(0, 2) = -fx * q[0] / (q[2] * q[2]);\n                    J_pixel_xi(0, 3) = -fx * q[0] * q[1] / (q[2] * q[2]);\n                    J_pixel_xi(0, 4) = fx + fx * q[0] * q[0] / (q[2] * q[2]);\n                    J_pixel_xi(0, 5) = -fx * q[1] / q[2];\n                    J_pixel_xi(1, 0) = 0;\n                    J_pixel_xi(1, 1) = fy / q[2];\n                    J_pixel_xi(1, 2) = -fy * q[1] / (q[2] * q[2]);\n                    J_pixel_xi(1, 3) = -fy - fy * q[1] * q[1] / (q[2] * q[2]);\n                    J_pixel_xi(1, 4) = fy * q[0] * q[1] / (q[2] * q[2]);\n                    J_pixel_xi(1, 5) = fy * q[0] / q[2];\n                    Eigen::Vector2d J_img_pixel; // image gradients\n                    J_img_pixel[0] = 0.5 * (GetPixelValue(img2, u + x + 1, v + y) - GetPixelValue(img2, u + x - 1, v + y));\n                    J_img_pixel[1] = 0.5 * (GetPixelValue(img2, u + x, v + y + 1) - GetPixelValue(img2, u + x, v + y - 1));\n\n                    // total jacobian\n                    Vector6d J = -J_pixel_xi.transpose() * J_img_pixel;\n\n                    H += J * J.transpose();\n                    b += -error * J;\n                    cost += error * error;\n                }\n            // END YOUR CODE HERE\n        }\n\n        // solve update and put it into estimation\n        // TODO START YOUR CODE HERE\n        Vector6d update;\n        update = H.ldlt().solve(b);\n        T21 = Sophus::SE3d::exp(update) * T21;\n        // END YOUR CODE HERE\n\n        cost /= nGood;\n\n        if (isnan(update[0]))\n        {\n            // sometimes occurred when we have a black or white patch and H is irreversible\n            std::cout << \"update is nan\" << endl;\n            break;\n        }\n        if (iter > 0 && cost > lastCost)\n        {\n            // cout << \"cost increased: \" << cost << \", \" << lastCost << endl;\n            break;\n        }\n        lastCost = cost;\n        if(show)\n            std::cout << \"iter = \"<< iter <<\", cost = \" << cost << \", good = \" << nGood <<\"/\"<< px_ref.size() << endl;\n    }\n    if (show)\n    {\n        std::cout << \"end_iter = \" << iter_cnt - 1 << \", lastcost = \" << lastCost << \", good = \" << nGood << \"/\" << px_ref.size() << endl;\n        // std::cout << \"good projection: \" << nGood << endl;\n        std::cout << \"T21 = \\n\"\n                  << T21.matrix() << endl;\n\n        // in order to help you debug, we plot the projected pixels here\n        cv::Mat img1_show, img2_show;\n        cv::cvtColor(img1, img1_show, CV_GRAY2BGR);\n        cv::cvtColor(img2, img2_show, CV_GRAY2BGR);\n        for (auto &px : px_ref)\n        {\n            cv::rectangle(img1_show, cv::Point2f(px[0] - 2, px[1] - 2), cv::Point2f(px[0] + 2, px[1] + 2),\n                          cv::Scalar(0, 250, 0));\n        }\n        // for (auto &px: goodProjection) {\n        //     cv::rectangle(img2_show, cv::Point2f(px[0] - 2, px[1] - 2), cv::Point2f(px[0] + 2, px[1] + 2),\n        //                   cv::Scalar(0, 250, 0));\n        // }\n        for (int i = 0; i < goodProjection.size(); i++)\n        {\n            cv::circle(img2_show, cv::Point2f(goodProjection[i][0], goodProjection[i][1]), 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_show, cv::Point2f(goodProjection[i][0], goodProjection[i][1]), cv::Point2f(goodOriginal[i][0], goodOriginal[i][1]), cv::Scalar(0, 250, 0));\n        }\n        cv::imshow(\"reference\", img1_show);\n        cv::imshow(\"current\", img2_show);\n        cv::waitKey(0);\n    }\n}\n\nvoid DirectPoseEstimationMultiLayer(\n    const cv::Mat &img1,\n    const cv::Mat &img2,\n    const VecVector2d &px_ref,\n    const vector<double> depth_ref,\n    Sophus::SE3d &T21,\n    bool show)\n{\n\n    // parameters\n    int pyramids = 4;\n    double pyramid_scale = 0.5;\n    double scales[] = {1.0, 0.5, 0.25, 0.125};\n\n    // create pyramids\n    vector<cv::Mat> pyr1, pyr2; // image pyramids\n    // TODO START YOUR CODE HERE\n    for (int i = 0; i < pyramids; i++)\n    {\n        if (i == 0)\n        {\n            pyr1.push_back(img1);\n            pyr2.push_back(img2);\n            continue;\n        }\n        cv::Mat dst1, dst2;\n        cv::resize(img1, dst1, cv::Size(), scales[i], scales[i]);\n        cv::resize(img2, dst2, cv::Size(), scales[i], scales[i]);\n        pyr1.push_back(dst1);\n        pyr2.push_back(dst2);\n    }\n\n    // END YOUR CODE HERE\n\n    double fxG = fx, fyG = fy, cxG = cx, cyG = cy; // backup the old values\n    for (int level = pyramids - 1; level >= 0; level--)\n    {\n        VecVector2d px_ref_pyr; // set the keypoints in this pyramid level\n        for (auto &px : px_ref)\n        {\n            px_ref_pyr.push_back(scales[level] * px);\n        }\n\n        // TODO START YOUR CODE HERE\n        // scale fx, fy, cx, cy in different pyramid levels\n        fx = fxG*scales[level];\n        cx = cxG*scales[level];\n        fy = fyG*scales[level];\n        cy = cyG*scales[level];\n        // END YOUR CODE HERE\n        if (level==0)\n            DirectPoseEstimationSingleLayer(pyr1[level], pyr2[level], px_ref_pyr, depth_ref, T21, show);\n        else{\n            DirectPoseEstimationSingleLayer(pyr1[level], pyr2[level], px_ref_pyr, depth_ref, T21);\n        }\n    }\n}\n", "meta": {"hexsha": "d50a98fccd407f105c44170ee59c188326a372d6", "size": 10326, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slamhw6/direct_method.cpp", "max_stars_repo_name": "Yaozhuwa/slambook-homework", "max_stars_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-23T03:27:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T15:29:10.000Z", "max_issues_repo_path": "slamhw6/direct_method.cpp", "max_issues_repo_name": "Yaozhuwa/slambook-homework", "max_issues_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slamhw6/direct_method.cpp", "max_forks_repo_name": "Yaozhuwa/slambook-homework", "max_forks_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8557377049, "max_line_length": 165, "alphanum_fraction": 0.5349602944, "num_tokens": 3115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6010492465684628}}
{"text": "\n// This file is part of Man, a robotic perception, locomotion, and\n// team strategy application created by the Northern Bites RoboCup\n// team of Bowdoin College in Brunswick, Maine, for the Aldebaran\n// Nao robot.\n//\n// Man is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Lesser Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Man is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU Lesser Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// and the GNU Lesser Public License along with Man.  If not, see\n// <http://www.gnu.org/licenses/>.\n\n#include <math.h>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>              // for lu_factorize\n#include <boost/numeric/ublas/io.hpp>              // for cout\n\n#include \"nb/CoordFrame.h\"\n\nusing namespace NBMath;\nusing namespace CoordFrame3D;\n\n// -------------------- Helper matrix methods --------------------\nconst NBMath::ufmatrix3 CoordFrame3D::rotation3D(const Axis axis,\n                                                 const double angle) {\n    NBMath::ufmatrix3 rot =\n        boost::numeric::ublas::identity_matrix <double>(3);\n\n    if (angle == 0.0) { //OPTIMIZAION POINT\n        return rot;\n    }\n    const double sinAngle = std::sin(angle);\n    const double cosAngle = std::cos(angle);\n\n    switch(axis) {\n    case Z_AXIS:\n        rot(X_AXIS, X_AXIS) =  cosAngle;\n        rot(X_AXIS, Y_AXIS) = -sinAngle;\n        rot(Y_AXIS, X_AXIS) =  sinAngle;\n        rot(Y_AXIS, Y_AXIS) =  cosAngle;\n        break;\n    default:\n        break;\n    }\n    return rot;\n}\n\nconst NBMath::ufmatrix3 CoordFrame3D::translation3D(const double dx,\n                                                    const double dy) {\n    boost::numeric::ublas::matrix <double> trans =\n        boost::numeric::ublas::identity_matrix <double>(3);\n    trans(X_AXIS, Z_AXIS) = dx;\n    trans(Y_AXIS, Z_AXIS) = dy;\n    return trans;\n}\n\nconst NBMath::ufvector3 CoordFrame3D::vector3D(const double x, const double y,\n                                               const double z) {\n    NBMath::ufvector3 p = boost::numeric::ublas::zero_vector <double> (3);\n    p(0) = x;\n    p(1) = y;\n    p(2) = z;\n    return p;\n}\n\nconst NBMath::ufrowVector3 CoordFrame3D::rowVector3D(const double x,\n                                                  const double y,\n                                                  const double z) {\n\n    NBMath::ufrowVector3 p(1, 3);\n\n    p(0,0) = x;\n\n    p(0,1) = y;\n\n    p(0,2) = z;\n\n    return p;\n}\n\nconst NBMath::ufmatrix3 CoordFrame3D::identity3D(){\n    return boost::numeric::ublas::identity_matrix <double> (3);\n}\n", "meta": {"hexsha": "159a64dc1009672804b0a1c883980e845057f512", "size": 3049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hardware/src/nb/CoordFrame3D.cpp", "max_stars_repo_name": "arssivka/naomech", "max_stars_repo_head_hexsha": "678e270d388498ae888b4f945b3753e21bf5ad5a", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-12-28T14:04:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T17:25:37.000Z", "max_issues_repo_path": "hardware/src/nb/CoordFrame3D.cpp", "max_issues_repo_name": "arssivka/naomech", "max_issues_repo_head_hexsha": "678e270d388498ae888b4f945b3753e21bf5ad5a", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-10-22T15:15:26.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-26T15:03:40.000Z", "max_forks_repo_path": "hardware/src/nb/CoordFrame3D.cpp", "max_forks_repo_name": "arssivka/naomech", "max_forks_repo_head_hexsha": "678e270d388498ae888b4f945b3753e21bf5ad5a", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7604166667, "max_line_length": 78, "alphanum_fraction": 0.6152836996, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6010492414137748}}
{"text": "// bit_tuple_iterator.hpp\n//\n// Generate all n-tuples where each element is drawn\n// from the set {0,1}. The algorithm is based on \n// incrementing a binary counter. (Note the difference\n// to e.g. Gray code).\n\n#ifndef BIT_TUPLE_ITERATOR_HPP\n#define BIT_TUPLE_ITERATOR_HPP\n\n#include <cstdint>\n#include <numeric>\n#include <type_traits>\n#include <cassert>\n\n#include <boost/iterator/iterator_facade.hpp>\n\ntemplate <typename T>\nclass bit_tuple_iterator\n\t: public boost::iterator_facade <\n\tbit_tuple_iterator<T>,\n\tconst T&,\n\tboost::forward_traversal_tag\n\t>\n{\nprivate:\n\tstatic_assert(std::is_integral<T>::value, \"T must be integral\");\n\npublic:\n\tbit_tuple_iterator() : end_(true), n_(0), p_(0) { }\n\n\texplicit bit_tuple_iterator(int p) : end_(false), n_(0), p_(std::pow(2, p) - 1)\n\t{\n\t\tassert(p_ == std::pow(2, p) - 1 && \"T not large enough to hold 2^p\");\n\t\tassert(p <= sizeof(T) * 8 && \"T not large enough to hold n tuples\");\n\t\tassert(n_ == 0);\n\t}\n\nprivate:\n\tfriend class boost::iterator_core_access;\n\n\tvoid increment()\n\t{\n\t\tif (p_ == n_)\n\t\t{\n\t\t\tend_ = true;\n\t\t}\n\n\t\t++n_;\n\t}\n\n\tbool equal(const bit_tuple_iterator& other) const\n\t{\n\t\treturn end_ == other.end_;\n\t}\n\n\tconst T& dereference() const\n\t{\n\t\treturn n_;\n\t}\n\n\tbool end_;\n\tT n_;\n\tconst T p_;\n};\n\n#endif\n", "meta": {"hexsha": "54194da87b33a85a5bc6e26a9bef93af40fb4646", "size": 1249, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bit_tuple_iterator.hpp", "max_stars_repo_name": "euler314/combinatorics", "max_stars_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-12T22:24:44.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-21T13:16:09.000Z", "max_issues_repo_path": "bit_tuple_iterator.hpp", "max_issues_repo_name": "euler314/combinatorics", "max_issues_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bit_tuple_iterator.hpp", "max_forks_repo_name": "euler314/combinatorics", "max_forks_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-12-06T18:32:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T18:32:14.000Z", "avg_line_length": 18.3676470588, "max_line_length": 80, "alphanum_fraction": 0.6773418735, "num_tokens": 361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.7931059487389966, "lm_q1q2_score": 0.6010112237788453}}
{"text": "#include <blitz/array.h>\n\nBZ_USING_NAMESPACE(blitz)\n\nint main()\n{\n    // 3x3 C-style row major storage, base zero\n    Array<int,2> A(3, 3);\n\n    // 3x3 column major storage, base zero\n    Array<int,2> B(3, 3, ColumnMajorArray<2>());\n\n    // A custom storage format: \n    // Indices have range 0..3, 0..3\n    // Column major ordering\n    // Rows are stored ascending, columns stored descending\n    GeneralArrayStorage<2> storage;\n    storage.ordering() = firstRank, secondRank;\n    storage.base() = 0, 0;\n    storage.ascendingFlag() = true, false;\n\n    Array<int,2> C(3, 3, storage);\n\n    // Set each array equal to\n    // [ 1 2 3 ]\n    // [ 4 5 6 ]\n    // [ 7 8 9 ]\n\n    A = 1, 2, 3,\n        4, 5, 6, \n        7, 8, 9;\n\n    cout << \"A = \" << A << endl;\n\n    // Comma-delimited lists initialize in memory-storage order only.\n    // Hence we list the values in column-major order to initialize B:\n\n    B = 1, 4, 7, 2, 5, 8, 3, 6, 9;\n\n    cout << \"B = \" << B << endl;\n\n    // Array C is stored in column major, plus the columns are stored\n    // in descending order!\n\n    C = 3, 6, 9, 2, 5, 8, 1, 4, 7;\n\n    cout << \"C = \" << C << endl;\n\n    Array<int,2> D(3,3);\n    D = A + B + C;\n\n#ifdef BZ_DEBUG\n    A.dumpStructureInformation();\n    B.dumpStructureInformation();\n    C.dumpStructureInformation();\n    D.dumpStructureInformation();\n#endif\n\n    cout << \"D = \" << D << endl;\n\n    return 0;\n}\n\n", "meta": {"hexsha": "0baf73a15369ce4f24cb74b44edb00bf55c2a20b", "size": 1391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/doc/examples/storage.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/storage.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/doc/examples/storage.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.734375, "max_line_length": 70, "alphanum_fraction": 0.5650611071, "num_tokens": 465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.6010112182201616}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n#include <boost/config.hpp>\r\n#include <vector>\r\n#include <iostream>\r\n#include <boost/graph/strong_components.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  typedef adjacency_list < vecS, vecS, directedS > Graph;\r\n  const int N = 6;\r\n  Graph G(N);\r\n  add_edge(0, 1, G);\r\n  add_edge(1, 1, G);\r\n  add_edge(1, 3, G);\r\n  add_edge(1, 4, G);\r\n  add_edge(3, 4, G);\r\n  add_edge(3, 0, G);\r\n  add_edge(4, 3, G);\r\n  add_edge(5, 2, G);\r\n\r\n  std::vector<int> c(N);\r\n  int num = strong_components\r\n    (G, make_iterator_property_map(c.begin(), get(vertex_index, G), c[0]));\r\n\r\n  std::cout << \"Total number of components: \" << num << std::endl;\r\n  std::vector < int >::iterator i;\r\n  for (i = c.begin(); i != c.end(); ++i)\r\n    std::cout << \"Vertex \" << i - c.begin()\r\n      << \" is in component \" << *i << std::endl;\r\n  return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "9c64e91b71b00e42cf2d2329e6c9c06ac165aca4", "size": 1259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/strong-components.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/graph/example/strong-components.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/graph/example/strong-components.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 30.7073170732, "max_line_length": 76, "alphanum_fraction": 0.5440826052, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6010112169551928}}
{"text": "/*\r\n * Copyright Nick Thompson, 2017\r\n * Use, modification and distribution are subject to the\r\n * Boost Software License, Version 1.0. (See accompanying file\r\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n *\r\n * Use the adaptive trapezoidal rule to estimate the integral of periodic functions over a period,\r\n * or to integrate a function whose derivative vanishes at the endpoints.\r\n *\r\n * If your function does not satisfy these conditions, and instead is simply continuous and bounded\r\n * over the whole interval, then this routine will still converge, albeit slowly. However, there\r\n * are much more efficient methods in this case, including Romberg, Simpson, and double exponential quadrature.\r\n */\r\n\r\n#ifndef BOOST_MATH_QUADRATURE_TRAPEZOIDAL_HPP\r\n#define BOOST_MATH_QUADRATURE_TRAPEZOIDAL_HPP\r\n\r\n#include <cmath>\r\n#include <limits>\r\n#include <stdexcept>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/math/special_functions/fpclassify.hpp>\r\n#include <boost/math/policies/error_handling.hpp>\r\n\r\nnamespace boost{ namespace math{ namespace quadrature {\r\n\r\ntemplate<class F, class Real, class Policy>\r\nauto trapezoidal(F f, Real a, Real b, Real tol, std::size_t max_refinements, Real* error_estimate, Real* L1, const Policy& pol)->decltype(std::declval<F>()(std::declval<Real>()))\r\n{\r\n    static const char* function = \"boost::math::quadrature::trapezoidal<%1%>(F, %1%, %1%, %1%)\";\r\n    using std::abs;\r\n    using boost::math::constants::half;\r\n    // In many math texts, K represents the field of real or complex numbers.\r\n    // Too bad we can't put blackboard bold into C++ source!\r\n    typedef decltype(f(a)) K;\r\n    if(a >= b)\r\n    {\r\n       return static_cast<K>(boost::math::policies::raise_domain_error(function, \"a < b for integration over the region [a, b] is required, but got a = %1%.\\n\", a, pol));\r\n    }\r\n    if (!(boost::math::isfinite)(a))\r\n    {\r\n       return static_cast<K>(boost::math::policies::raise_domain_error(function, \"Left endpoint of integration must be finite for adaptive trapezoidal integration but got a = %1%.\\n\", a, pol));\r\n    }\r\n    if (!(boost::math::isfinite)(b))\r\n    {\r\n       return static_cast<K>(boost::math::policies::raise_domain_error(function, \"Right endpoint of integration must be finite for adaptive trapedzoidal integration but got b = %1%.\\n\", b, pol));\r\n    }\r\n\r\n\r\n    K ya = f(a);\r\n    K yb = f(b);\r\n    Real h = (b - a)*half<Real>();\r\n    K I0 = (ya + yb)*h;\r\n    Real IL0 = (abs(ya) + abs(yb))*h;\r\n\r\n    K yh = f(a + h);\r\n    K I1;\r\n    I1 = I0*half<Real>() + yh*h;\r\n    Real IL1 = IL0*half<Real>() + abs(yh)*h;\r\n\r\n    // The recursion is:\r\n    // I_k = 1/2 I_{k-1} + 1/2^k \\sum_{j=1; j odd, j < 2^k} f(a + j(b-a)/2^k)\r\n    std::size_t k = 2;\r\n    // We want to go through at least 4 levels so we have sampled the function at least 10 times.\r\n    // Otherwise, we could terminate prematurely and miss essential features.\r\n    // This is of course possible anyway, but 10 samples seems to be a reasonable compromise.\r\n    Real error = abs(I0 - I1);\r\n    while (k < 4 || (k < max_refinements && error > tol*IL1) )\r\n    {\r\n        I0 = I1;\r\n        IL0 = IL1;\r\n\r\n        I1 = I0*half<Real>();\r\n        IL1 = IL0*half<Real>();\r\n        std::size_t p = static_cast<std::size_t>(1u) << k;\r\n        h *= half<Real>();\r\n        K sum = 0;\r\n        Real absum = 0;\r\n\r\n        for(std::size_t j = 1; j < p; j += 2)\r\n        {\r\n            K y = f(a + j*h);\r\n            sum += y;\r\n            absum += abs(y);\r\n        }\r\n\r\n        I1 += sum*h;\r\n        IL1 += absum*h;\r\n        ++k;\r\n        error = abs(I0 - I1);\r\n    }\r\n\r\n    if (error_estimate)\r\n    {\r\n        *error_estimate = error;\r\n    }\r\n\r\n    if (L1)\r\n    {\r\n        *L1 = IL1;\r\n    }\r\n\r\n    return static_cast<K>(I1);\r\n}\r\n#if BOOST_WORKAROUND(BOOST_MSVC, < 1800)\r\n// Template argument dedcution failure otherwise:\r\ntemplate<class F, class Real>\r\nauto trapezoidal(F f, Real a, Real b, Real tol = 0, std::size_t max_refinements = 12, Real* error_estimate = 0, Real* L1 = 0)->decltype(std::declval<F>()(std::declval<Real>()))\r\n#elif !defined(BOOST_NO_CXX11_NULLPTR)\r\ntemplate<class F, class Real>\r\nauto trapezoidal(F f, Real a, Real b, Real tol = boost::math::tools::root_epsilon<Real>(), std::size_t max_refinements = 12, Real* error_estimate = nullptr, Real* L1 = nullptr)->decltype(std::declval<F>()(std::declval<Real>()))\r\n#else\r\ntemplate<class F, class Real>\r\nauto trapezoidal(F f, Real a, Real b, Real tol = boost::math::tools::root_epsilon<Real>(), std::size_t max_refinements = 12, Real* error_estimate = 0, Real* L1 = 0)->decltype(std::declval<F>()(std::declval<Real>()))\r\n#endif\r\n{\r\n#if BOOST_WORKAROUND(BOOST_MSVC, <= 1600)\r\n   if (tol == 0)\r\n      tol = boost::math::tools::root_epsilon<Real>();\r\n#endif\r\n   return trapezoidal(f, a, b, tol, max_refinements, error_estimate, L1, boost::math::policies::policy<>());\r\n}\r\n\r\n}}}\r\n#endif\r\n", "meta": {"hexsha": "ce36b824e31c6a188ff2a477e287b479f63d1f40", "size": 4895, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/math/quadrature/trapezoidal.hpp", "max_stars_repo_name": "YuukiTsuchida/v8_embeded", "max_stars_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "jeff/common/include/boost/math/quadrature/trapezoidal.hpp", "max_issues_repo_name": "jeffphi/advent-of-code-2018", "max_issues_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "jeff/common/include/boost/math/quadrature/trapezoidal.hpp", "max_forks_repo_name": "jeffphi/advent-of-code-2018", "max_forks_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 38.8492063492, "max_line_length": 228, "alphanum_fraction": 0.6281920327, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324938410784, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6009552919825502}}
{"text": "\ufeff//\n// Copyright \u00a9 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"FullyConnected.hpp\"\n\n#include \"RefWorkloadUtils.hpp\"\n\n#include <boost/assert.hpp>\n\nnamespace armnn\n{\n\nvoid FullyConnected(const TensorShape& rInputShape,\n                    Decoder<float>& rInputDecoder,\n                    const TensorShape& rOutputShape,\n                    Encoder<float>& rOutputEncoder,\n                    Decoder<float>& rWeightDecoder,\n                    Decoder<float>& rBiasDecoder,\n                    const bool biasEnabled,\n                    const unsigned int K,\n                    const bool transposeWeights)\n{\n    // Perform FullyConnected implementation\n    unsigned int outputSize = rOutputShape[1];\n\n    for (unsigned int n = 0; n < rInputShape[0]; n++)\n    {\n        for (unsigned int channelOutput = 0; channelOutput < outputSize; channelOutput++)\n        {\n            float outval = 0.f;\n\n            for (unsigned int channelInput = 0; channelInput < K; channelInput++)\n            {\n                float weight;\n                if (transposeWeights)\n                {\n                    rWeightDecoder[channelOutput * K + channelInput];\n                    weight = rWeightDecoder.Get();\n                }\n                else\n                {\n                    rWeightDecoder[channelInput * outputSize + channelOutput];\n                    weight = rWeightDecoder.Get();\n                }\n\n                rInputDecoder[n * K + channelInput];\n                outval += weight * rInputDecoder.Get();\n            }\n\n            if (biasEnabled)\n            {\n                rBiasDecoder[channelOutput];\n                outval += rBiasDecoder.Get();\n            }\n\n            rOutputEncoder[n * outputSize + channelOutput];\n            rOutputEncoder.Set(outval);\n        }\n    }\n}\n\n} //namespace armnn\n", "meta": {"hexsha": "02d9b060ef6e8a897b99170b40398748e7173073", "size": 1856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/reference/workloads/FullyConnected.cpp", "max_stars_repo_name": "VinayKarnam/armnn", "max_stars_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-19T20:19:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-19T20:19:10.000Z", "max_issues_repo_path": "src/backends/reference/workloads/FullyConnected.cpp", "max_issues_repo_name": "VinayKarnam/armnn", "max_issues_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/backends/reference/workloads/FullyConnected.cpp", "max_forks_repo_name": "VinayKarnam/armnn", "max_forks_repo_head_hexsha": "98525965c7cfecd9bf48297b433b2122cd1b4a1d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T04:31:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T04:31:21.000Z", "avg_line_length": 28.5538461538, "max_line_length": 89, "alphanum_fraction": 0.5204741379, "num_tokens": 355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6009552679326834}}
{"text": "/* boost random/triangle_distribution.hpp header file\n *\n * Copyright Jens Maurer 2000-2001\n * Permission to use, copy, modify, sell, and distribute this software\n * is hereby granted without fee provided that the above copyright notice\n * appears in all copies and that both that copyright notice and this\n * permission notice appear in supporting documentation,\n *\n * Jens Maurer makes no representations about the suitability of this\n * software for any purpose. It is provided \"as is\" without express or\n * implied warranty.\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: triangle_distribution.hpp 11696 2001-11-14 21:53:38Z jmaurer $\n *\n * Revision history\n *  2001-02-18  moved to individual header files\n */\n\n#ifndef BOOST_RANDOM_TRIANGLE_DISTRIBUTION_HPP\n#define BOOST_RANDOM_TRIANGLE_DISTRIBUTION_HPP\n\n#include <cmath>\n#include <cassert>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\n\n// triangle distribution, with a smallest, b most probable, and c largest\n// value.\ntemplate<class UniformRandomNumberGenerator, class RealType = double>\nclass triangle_distribution\n{\npublic:\n  typedef UniformRandomNumberGenerator base_type;\n  typedef RealType result_type;\n  triangle_distribution(base_type & rng, result_type a, result_type b,\n                        result_type c)\n    : _rng(rng), _a(a), _b(b), _c(c),\n      d1(_b-_a), d2(_c-_a), d3(_c-_b), q1(d1/d2), p1(d1*d2)\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif\n    d3 = sqrt(d3);\n    p1 = sqrt(p1);\n    assert(_a <= _b && _b <= _c);\n  }\n  // compiler-generated copy ctor is fine\n  // uniform_01 cannot be assigned, neither can this class\n  result_type operator()()\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif\n    result_type u = _rng();\n    if( u <= q1 )\n      return _a + p1*sqrt(u);\n    else\n      return _c - d3*sqrt(d2*u-d1);\n  }\n#ifndef BOOST_NO_OPERATORS_IN_NAMESPACE\n  friend bool operator==(const triangle_distribution& x, \n                         const triangle_distribution& y)\n  { return x._a == y._a && x._b == y._b && x._c == y._c && x._rng == y._rng; }\n#else\n  // Use a member function\n  bool operator==(const triangle_distribution& rhs) const\n  { return _a == rhs._a && _b == rhs._b && _c == rhs._c && _rng == rhs._rng;  }\n#endif\nprivate:\n  uniform_01<base_type, result_type> _rng;\n  result_type _a, _b, _c;\n  result_type d1, d2, d3, q1, p1;\n};\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_TRIANGLE_DISTRIBUTION_HPP\n", "meta": {"hexsha": "7883fcc16d552c1c21a23d1c50400d3210fda856", "size": 2488, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_28/boost/random/triangle_distribution.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vegastrike/boost/1_28/boost/random/triangle_distribution.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_28/boost/random/triangle_distribution.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["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.7160493827, "max_line_length": 79, "alphanum_fraction": 0.6997588424, "num_tokens": 667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6008845732805842}}
{"text": "/*\n * @brief Linear interpolation tools.\n * @author Jenna Reher (jreher@caltech.edu)\n */\n\n#ifndef LINEAR_INTERPOLATION_HPP\n#define LINEAR_INTERPOLATION_HPP\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\nusing namespace Eigen;\n\nnamespace cassie_common_toolbox {\n\nint find_index(VectorXd &X, double &Xi);\n\nvoid linear_interp(VectorXd &X, MatrixXd &Y, double Xi, VectorXd &Yi );\n\nvoid bilinear_interp(VectorXd &X, VectorXd &Y, std::vector< std::vector<VectorXd> > Z, double Xi, double Yi, VectorXd &Zi );\n\n\n\n\n\n} // namespace cassie_common_toolbox\n\n#endif // LINEAR_INTERPOLATION_HPP\n", "meta": {"hexsha": "71be2f4dde09810ad6a889e91eca9f6d8b43c90c", "size": 595, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cassie_common_toolbox/linear_interpolation.hpp", "max_stars_repo_name": "jpreher/cassie_common_toolbox", "max_stars_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-11T22:56:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-11T22:56:02.000Z", "max_issues_repo_path": "include/cassie_common_toolbox/linear_interpolation.hpp", "max_issues_repo_name": "jpreher/cassie_common_toolbox", "max_issues_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cassie_common_toolbox/linear_interpolation.hpp", "max_forks_repo_name": "jpreher/cassie_common_toolbox", "max_forks_repo_head_hexsha": "e01065a56e4a0a71607bfe412834a9a8b541fe28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-04T21:22:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T21:22:53.000Z", "avg_line_length": 20.5172413793, "max_line_length": 124, "alphanum_fraction": 0.7512605042, "num_tokens": 157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6008731139750214}}
{"text": "//==============================================================================\n//          Copyright 2015 J.T. Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_TENPOWER_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_TENPOWER_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/tenpower.hpp>\n#include <boost/simd/include/functions/simd/abs.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/is_odd.hpp>\n#include <boost/simd/include/functions/simd/is_ltz.hpp>\n#include <boost/simd/include/functions/simd/shift_right.hpp>\n#include <boost/simd/include/functions/simd/multiplies.hpp>\n#include <boost/simd/include/functions/simd/any.hpp>\n#include <boost/simd/include/functions/simd/abs.hpp>\n#include <boost/simd/include/functions/simd/sqr.hpp>\n#include <boost/simd/include/constants/one.hpp>\n#include <boost/simd/include/constants/ten.hpp>\n#include <boost/dispatch/meta/as_floating.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <boost/mpl/equal_to.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT_IF( tenpower_, tag::cpu_\n                             , (A0)(X)\n                             , (boost::mpl::equal_to < boost::simd::meta::cardinal_of<A0>\n                                , boost::simd::meta::cardinal_of<typename dispatch::meta::as_floating<A0>::type>\n                                >)\n                             , ((simd_<int_<A0>,X>))\n                          )\n  {\n    typedef typename dispatch::meta::as_floating<A0>::type result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      result_type result = One<result_type>();\n      result_type base = Ten<result_type>();\n      A0 exp = boost::simd::abs(a0);\n      while(any(exp))\n      {\n        result *= if_else(is_odd(exp), base, One<result_type>());\n        exp >>= 1;\n        base = sqr(base);\n      }\n      return if_else(is_ltz(a0), rec(result), result);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT_IF( tenpower_, tag::cpu_\n                             , (A0)(X)\n                             , (boost::mpl::equal_to < boost::simd::meta::cardinal_of<A0>\n                                , boost::simd::meta::cardinal_of<typename dispatch::meta::as_floating<A0>::type>\n                                >)\n                             , ((simd_<uint_<A0>,X>))\n                          )\n  {\n    typedef typename dispatch::meta::as_floating<A0>::type result_type;\n    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)\n    {\n      result_type result = One<result_type>();\n      result_type base = Ten<result_type>();\n      A0 exp = a0;\n      while(any(exp))\n      {\n        result *= if_else(is_odd(exp), base, One<result_type>());\n        exp >>= 1;\n        base = sqr(base);\n      }\n      return result;\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "9d9fc77ef4eb8394ffa8eb2d0a46ce598dc70732", "size": 3113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/tenpower.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/tenpower.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/tenpower.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 38.9125, "max_line_length": 112, "alphanum_fraction": 0.5737230967, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6008731090481596}}
{"text": "/*\n * Copyright 2012 Karsten Ahnert\n * Copyright 2013 Mario Mulansky\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <iostream>\n#include <vector>\n\n#include <vexcl/vexcl.hpp>\n\n#include <boost/numeric/odeint.hpp>\n//[ vexcl_includes\n#include <boost/numeric/odeint/external/vexcl/vexcl.hpp>\n//]\n\nnamespace odeint = boost::numeric::odeint;\n\n//[ vexcl_state_types\ntypedef vex::vector< double >    vector_type;\ntypedef vex::multivector< double, 3 > state_type;\n//]\n\n\n//[ vexcl_system\nconst double sigma = 10.0;\nconst double b = 8.0 / 3.0;\n\nstruct sys_func\n{\n    const vector_type &R;\n\n    sys_func( const vector_type &_R ) : R( _R ) { }\n\n    void operator()( const state_type &x , state_type &dxdt , double t ) const\n    {\n        dxdt(0) = -sigma * ( x(0) - x(1) );\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//]\n\n\nint main( int argc , char **argv )\n{\n    using namespace std;\n    using namespace odeint;\n\n    //[ vexcl_main\n    // setup the opencl context\n    vex::Context ctx( vex::Filter::Type(CL_DEVICE_TYPE_GPU) );\n    std::cout << ctx << std::endl;\n\n    // set up number of system, time step and integration time\n    const size_t n = 1024 * 1024;\n    const double dt = 0.01;\n    const double t_max = 1000.0;\n\n    // initialize R\n    double Rmin = 0.1 , Rmax = 50.0 , dR = ( Rmax - Rmin ) / double( n - 1 );\n    std::vector<double> x( n * 3 ) , r( n );\n    for( size_t i=0 ; i<n ; ++i ) r[i] = Rmin + dR * double( i );\n    vector_type R( ctx.queue() , r );\n\n    // initialize the state of the lorenz ensemble\n    state_type X(ctx.queue(), n);\n    X(0) = 10.0;\n    X(1) = 10.0;\n    X(2) = 10.0;\n\n    // create a stepper\n    runge_kutta4< state_type > stepper;\n\n    // solve the system\n    integrate_const( stepper , sys_func( R ) , X , 0.0 , t_max , dt );\n    //]\n\n    std::vector< double > res( 3 * n );\n    vex::copy( X(0) , res );\n    for( size_t i=0 ; i<n ; ++i )\n        cout << r[i] << \"\\t\" << res[i] << \"\\t\" << \"\\n\";\n}\n", "meta": {"hexsha": "0e7594ca3d40a1db5ac86dd812c82ca55e54deb1", "size": 2108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/vexcl/lorenz_ensemble.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/examples/vexcl/lorenz_ensemble.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/examples/vexcl/lorenz_ensemble.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 24.2298850575, "max_line_length": 78, "alphanum_fraction": 0.5825426945, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6007658420249342}}
{"text": "#include <math/transform.h>\n#include <Eigen/Geometry>\n#include \"test_common.h\"\n\nnamespace {\n\nconstexpr double epsilon = 1e-4;\nstd::vector<Eigen::Vector3f> test_vectors = {\n    {0.f, 0.f, 0.f},\n    {1.f, 0.f, 0.f},    \n    {0.f, 1.f, 0.f},    \n    {0.f, 0.f, 1.f},    \n    {-1.f, 5.f, 6.f}\n};\n}\n\nTEST(Transform,TestIdentityAndReset)\n{\n    cpt::Transform xform;\n    EXPECT_TRUE(xform.translation().isZero());\n    EXPECT_TRUE(xform.scale().isOnes());\n    EXPECT_TRUE(xform.rotation().isIdentity());\n\n    xform.set_translation(Eigen::Vector3f::Constant(1.f));\n    {\n        Eigen::AngleAxisf base_ref_rotation(M_PI / 4.f, Eigen::Vector3f(1.f, 1.f, 1.f).normalized());\n        Eigen::Matrix3f ref_rotation = base_ref_rotation.toRotationMatrix();\n        xform.set_rotation(ref_rotation);\n    }\n    xform.set_scale(Eigen::Vector3f::Constant(0.5f));\n    xform.reset();\n    EXPECT_TRUE(xform.translation().isZero());\n    EXPECT_TRUE(xform.scale().isOnes());\n    EXPECT_TRUE(xform.rotation().isIdentity());\n\n    for (const auto& test_vector : test_vectors) {\n        EXPECT_TRUE((xform * test_vector - test_vector).isZero());\n        EXPECT_TRUE((xform.homogeneous_mult(test_vector) - test_vector).isZero());\n    }\n}\n\nTEST(Transform,TestTranslation)\n{\n    const Eigen::Vector3f ref_trans(0.1f, -0.5f, 2.f);\n    cpt::Transform xform;\n    xform.set_translation(ref_trans);\n    EXPECT_TRUE(xform.translation().isApprox(ref_trans));\n\n    {\n        Eigen::Vector3f test_vector(0.f, 0.f, 0.f);\n        Eigen::Vector3f ref_vector(0.1f, -0.5f, 2.f);\n        EXPECT_TRUE((xform * test_vector - test_vector).isZero());\n        EXPECT_TRUE((xform.homogeneous_mult(test_vector) - ref_vector).isZero());\n    }\n\n    {\n        Eigen::Vector3f test_vector(8.f, -3.f, 0.3f);\n        Eigen::Vector3f ref_vector(8.1f, -3.5f, 2.3f);\n        EXPECT_TRUE((xform * test_vector - test_vector).isZero());\n        EXPECT_TRUE((xform.homogeneous_mult(test_vector) - ref_vector).isZero());\n    }\n}\n\nTEST(Transform,TestRotation)\n{\n    Eigen::AngleAxisf base_ref_rotation(M_PI / 4.f, Eigen::Vector3f(1.f, 1.f, 1.f).normalized());\n    Eigen::Matrix3f ref_rotation = base_ref_rotation.toRotationMatrix();\n\n    cpt::Transform xform;\n    xform.set_rotation(ref_rotation);\n    EXPECT_TRUE(xform.rotation().isApprox(ref_rotation));\n\n    for (const auto& test_vector : test_vectors) {\n        const Eigen::Vector3f ref_vector = ref_rotation * test_vector;\n        EXPECT_TRUE((xform * test_vector - ref_vector).isZero());\n        EXPECT_TRUE((xform.homogeneous_mult(test_vector) - ref_vector).isZero());\n    }\n}\n\nTEST(Transform,TestInvalidRotation)\n{\n    Eigen::Matrix3f invalid_rotation;\n    invalid_rotation << \n        1.f, 2.f, 3.f,\n        4.f, 5.f, 6.f,\n        7.f, 8.f, 9.f;\n\n    cpt::Transform xform;\n    EXPECT_THROW(xform.set_rotation(invalid_rotation), std::runtime_error);\n}\n\nTEST(Transform,TestScale)\n{\n    const Eigen::Vector3f ref_scale(0.1f, -0.5f, 2.f);\n    cpt::Transform xform;\n    xform.set_scale(ref_scale);\n    EXPECT_TRUE(xform.scale().isApprox(ref_scale));\n\n    {\n        Eigen::Vector3f test_vector(0.f, 0.f, 0.f);\n        EXPECT_TRUE((xform * test_vector - test_vector).isZero());\n        EXPECT_TRUE((xform.homogeneous_mult(test_vector) - test_vector).isZero());\n    }\n\n    {\n        Eigen::Vector3f test_vector(8.f, -3.f, 0.3f);\n        Eigen::Vector3f ref_vector(0.8f, 1.5f, 0.6f);\n        EXPECT_TRUE((xform * test_vector - ref_vector).isZero());\n        EXPECT_TRUE((xform.homogeneous_mult(test_vector) - ref_vector).isZero());\n    }\n}\n\nTEST(Transform,TestAllApply)\n{\n    // This just ensures we're doing the order of operations correctly (scale, rotate, translate).\n    const Eigen::Vector3f ref_trans(0.1f, -0.5f, 2.f);\n    const Eigen::Vector3f ref_scale(0.5f, -0.1f, 3.f);\n    Eigen::AngleAxisf base_ref_rotation(M_PI / 4.f, Eigen::Vector3f(1.f, 1.f, 1.f).normalized());\n    Eigen::Matrix3f ref_rotation = base_ref_rotation.toRotationMatrix();\n\n    cpt::Transform xform;\n    xform.set_translation(ref_trans);\n    xform.set_scale(ref_scale);\n    xform.set_rotation(ref_rotation);\n\n    EXPECT_TRUE(xform.translation().isApprox(ref_trans));\n    EXPECT_TRUE(xform.rotation().isApprox(ref_rotation));\n    EXPECT_TRUE(xform.scale().isApprox(ref_scale));\n\n    {\n        Eigen::Vector3f test_vector(0.f, 0.f, 0.f);\n        Eigen::Vector3f ref_vector(0.1f, -0.5f, 2.f);\n        EXPECT_TRUE((xform * test_vector - test_vector).isZero());\n        EXPECT_TRUE((xform.homogeneous_mult(test_vector) - ref_vector).isZero());\n    }\n\n    {\n        Eigen::Vector3f test_vector(1.f, 1.f, 1.f);\n        Eigen::Vector3f ref_vector_no_trans(1.9510677f, -0.7593853, 2.2083176f);\n        Eigen::Vector3f ref_vector_with_trans(2.0510677f, -1.2593853f, 4.2083176f);\n        EXPECT_TRUE((xform * test_vector - ref_vector_no_trans).isZero());\n        EXPECT_TRUE((xform.homogeneous_mult(test_vector) - ref_vector_with_trans).isZero());\n    }\n}\n\nTEST(Transform,TestCombineTranslation)\n{\n    cpt::Transform xform1;\n    xform1.set_translation(Eigen::Vector3f::UnitX());\n\n    cpt::Transform xform2;\n    xform2.set_translation(Eigen::Vector3f::UnitY());\n\n    {\n        cpt::Transform test = xform1 * xform2;\n        EXPECT_TRUE(test.translation().isApprox(Eigen::Vector3f(1.f, 1.f, 0.f)));\n    }\n\n    {\n        cpt::Transform test = xform2 * xform1;\n        EXPECT_TRUE(test.translation().isApprox(Eigen::Vector3f(1.f, 1.f, 0.f)));\n    }\n}\n\nTEST(Transform,TestCombineScale)\n{\n    cpt::Transform xform1;\n    xform1.set_scale(Eigen::Vector3f::Constant(0.5f));\n\n    cpt::Transform xform2;\n    xform2.set_scale(Eigen::Vector3f::Constant(0.1f));\n\n    {\n        cpt::Transform test = xform1 * xform2;\n        EXPECT_TRUE(test.scale().isApproxToConstant(0.05f));\n    }\n\n    {\n        cpt::Transform test = xform2 * xform1;\n        EXPECT_TRUE(test.scale().isApproxToConstant(0.05f));\n    }\n}\n\nTEST(Transform,TestCombineRotation)\n{\n    Eigen::AngleAxisf base_ref_rotation1(M_PI / 4.f, Eigen::Vector3f(1.f, 1.f, 1.f).normalized());\n    Eigen::Matrix3f ref_rotation1 = base_ref_rotation1.toRotationMatrix();\n\n    Eigen::AngleAxisf base_ref_rotation2(M_PI / 3.f, Eigen::Vector3f(1.f, 0.f, 0.f).normalized());\n    Eigen::Matrix3f ref_rotation2 = base_ref_rotation2.toRotationMatrix();\n\n    cpt::Transform xform1, xform2;\n    xform1.set_rotation(ref_rotation1);\n    xform2.set_rotation(ref_rotation2);\n\n    {\n        cpt::Transform test = xform1 * xform2;\n        EXPECT_TRUE(test.rotation().isApprox(ref_rotation1 * ref_rotation2));\n    }\n\n    {\n        cpt::Transform test = xform2 * xform1;\n        EXPECT_TRUE(test.rotation().isApprox(ref_rotation2 * ref_rotation1));\n    }\n}\n\nTEST(Transform,TestFromTransformMatrix)\n{\n    const Eigen::Vector3f ref_translation(0.1f, 0.2f, 0.3f);\n    const Eigen::Vector3f ref_scale(1.5f, -2.f, 0.75f);\n    const Eigen::AngleAxisf ref_rotation(M_PI / 4.f, Eigen::Vector3f(1.f, 1.f, 1.f).normalized());\n\n    Eigen::Affine3f ref_xform;\n    ref_xform.setIdentity();\n    ref_xform.prescale(ref_scale);\n    ref_xform.prerotate(ref_rotation);\n    ref_xform.pretranslate(ref_translation);\n\n    cpt::Transform xform = cpt::Transform::from_transform_matrix(ref_xform.matrix());\n    EXPECT_TRUE(xform.translation().isApprox(ref_translation));\n    // Can't guarantee that we decompose the scale exactly but rot * scale should be the same.\n    EXPECT_TRUE((xform.rotation() * xform.scale().asDiagonal()).isApprox(ref_xform.matrix().block(0,0,3,3)));\n}\n\nTEST(Transform,TestCombineTransform)\n{\n    const Eigen::Vector3f ref_translation1(0.1f, 0.2f, 0.3f);\n    const Eigen::Vector3f ref_scale1(1.5f, -2.f, 0.75f);\n    const Eigen::AngleAxisf ref_rotation1(M_PI / 4.f, Eigen::Vector3f(1.f, 1.f, 1.f).normalized());\n\n    const Eigen::Vector3f ref_translation2(1.1f, -0.25, -0.1f);\n    const Eigen::Vector3f ref_scale2(0.2f, 0.1f, 0.83f);\n    const Eigen::AngleAxisf ref_rotation2(M_PI / 3.f, Eigen::Vector3f(0.f, 1.f, 0.5f).normalized());\n\n    Eigen::Affine3f ref_xform;\n    ref_xform.setIdentity();\n    ref_xform.prescale(ref_scale1);\n    ref_xform.prerotate(ref_rotation1);\n    ref_xform.pretranslate(ref_translation1);\n    ref_xform.prescale(ref_scale2);\n    ref_xform.prerotate(ref_rotation2);\n    ref_xform.pretranslate(ref_translation2);\n\n    cpt::Transform xform1;\n    xform1.set_translation(ref_translation1);\n    xform1.set_rotation(ref_rotation1.toRotationMatrix());\n    xform1.set_scale(ref_scale1);\n\n    cpt::Transform xform2;\n    xform2.set_translation(ref_translation2);\n    xform2.set_rotation(ref_rotation2.toRotationMatrix());\n    xform2.set_scale(ref_scale2);\n\n    cpt::Transform test_xform = xform2 * xform1;\n    EXPECT_TRUE(test_xform.translation().isApprox(ref_xform.translation()));\n    EXPECT_TRUE((test_xform.rotation() * test_xform.scale().asDiagonal()).isApprox(ref_xform.matrix().block(0,0,3,3)));\n}\n\nCREATE_GENERIC_TEST_MAIN\n", "meta": {"hexsha": "ee62bfef2d80c784a578a7ccc7cb9b5793301cdd", "size": 8817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/transform_test.cpp", "max_stars_repo_name": "b3h47pte/cuda-path-tracing", "max_stars_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/transform_test.cpp", "max_issues_repo_name": "b3h47pte/cuda-path-tracing", "max_issues_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/transform_test.cpp", "max_forks_repo_name": "b3h47pte/cuda-path-tracing", "max_forks_repo_head_hexsha": "b874b86f15b4aca18ecd40e9eb962996298f5fa8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9115384615, "max_line_length": 119, "alphanum_fraction": 0.6786888965, "num_tokens": 2581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6007658413811695}}
{"text": "//\n// Underlying iLQRNode for Tree-iLQR.\n//\n// Arun Venkatraman (arunvenk@cs.cmu.edu)\n// December 2016\n//\n\n#pragma once\n\n#include <ilqr/ilqr_taylor_expansions.hh>\n\n#include <Eigen/Dense>\n\n#include <functional>\n#include <memory>\n#include <ostream>\n#include <vector>\n\nnamespace ilqr \n{\n\n// Each plan node represents a timestep.\nclass iLQRNode\n{\npublic:\n    iLQRNode(const int state_dim, \n             const int control_dim, \n             const DynamicsFunc &dynamics_func, \n             const CostFunc &cost_func,\n             const double probablity);\n\n    iLQRNode(const Eigen::VectorXd &x_star,\n             const Eigen::VectorXd &u_star,\n             const DynamicsFunc &dynamics_func, \n             const CostFunc &cost_func,\n             const double probablity);\n\n    // Compute the control policy and quadratic value of the node given the next\n    // timestep value. The policy and value are set directly in the node.\n    //void bellman_backup(const QuadraticValue& Jt1);\n    void bellman_backup(const std::vector<std::shared_ptr<iLQRNode>> &children);\n\n    // Computes a feedback control from state xt.\n    Eigen::VectorXd compute_control(const Eigen::VectorXd &xt) const;\n    // Computes a feedback control from state xt except moving only \"alpha\" step-size away from the\n    // expansion point u().\n    Eigen::VectorXd compute_control(const Eigen::VectorXd &xt, const double alpha) const;\n\n    // Get and set the probability\n    double probability() const { return probability_; }\n    void set_probability(double p) { probability_ = p; }\n\n    DynamicsFunc& dynamics_func() { return dynamics_func_; }\n    CostFunc& cost_func() { return cost_func_; }\n    const DynamicsFunc& dynamics_func() const { return dynamics_func_; }\n    const CostFunc& cost_func() const { return cost_func_; }\n\n    // Current Taylor expansion points x and u.\n    Eigen::VectorXd& x() { return x_; }\n    Eigen::VectorXd& u() { return u_; }\n    const Eigen::VectorXd& x() const { return x_; }\n    const Eigen::VectorXd& u() const { return u_; }\n\n    // Original Taylor expansion points x and u.\n    Eigen::VectorXd& orig_xstar() { return orig_xstar_; }\n    Eigen::VectorXd& orig_ustar() { return orig_ustar_; }\n    const Eigen::VectorXd& orig_xstar() const { return orig_xstar_; }\n    const Eigen::VectorXd& orig_ustar() const { return orig_ustar_; }\n\n    const QuadraticValue& value() const { return J_; };\n    QuadraticValue& value() { return J_; };\n\n    const Eigen::MatrixXd& K() const { return K_; };\n    Eigen::MatrixXd& K() { return K_; };\n    \n    const Eigen::VectorXd& k() const { return k_; };\n    Eigen::VectorXd& k() { return k_; };\n\nprivate:\n    DynamicsFunc dynamics_func_;\n    CostFunc cost_func_;\n\n    // Set point used for linearization of THIS node's cost and\n    // all CHILD node dynamics.\n    Eigen::VectorXd x_;\n    Eigen::VectorXd u_;\n\n    // Probability of transitioning to this node from the parent.\n    double probability_;\n\n    // The terms of the quadratic value function, 1/2 * x^T V x + Gx + W.\n    QuadraticValue J_; \n\n    // Feedback gain matrix on the extended-state, [dim(u)] x [dim(x) + 1]\n    Eigen::MatrixXd K_; \n    // Feed-forward control matrix, [dim(u)] x [dim(1)].\n    Eigen::VectorXd k_; \n\n    // Original nominal state specified at the beginning of iLQR. [dim(x)] x [1]\n    Eigen::VectorXd orig_xstar_; \n    // Original nominal control specified at the beginning of iLQR. [dim(u)] x [1]\n    Eigen::VectorXd orig_ustar_; \n};\n\n// Allows the iLQRNode to be printed.\nstd::ostream& operator<<(std::ostream& os, const ilqr::iLQRNode& node);\n\n} // namespace ilqr\n\n", "meta": {"hexsha": "8e342bda1420f1b88067d89b2efc36b131b5da88", "size": 3582, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/ilqr/ilqr_node.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/ilqr/ilqr_node.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ilqr/ilqr_node.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": 32.5636363636, "max_line_length": 99, "alphanum_fraction": 0.6705750977, "num_tokens": 896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6007658299034181}}
{"text": "// -----------------------------------------------------------------------------\n// Fern \u00a9 Geoneric\n//\n// This file is part of Geoneric Fern which is available under the terms of\n// the GNU General Public License (GPL), version 2. If you do not want to\n// be bound by the terms of the GPL, you may purchase a proprietary license\n// from Geoneric (http://www.geoneric.eu/contact).\n// -----------------------------------------------------------------------------\n#define BOOST_TEST_MODULE fern algorithm algebra elementary tgamma\n#include <boost/test/unit_test.hpp>\n#include \"fern/core/data_customization_point/scalar.h\"\n#include \"fern/algorithm/algebra/elementary/tgamma.h\"\n\n\nnamespace fa = fern::algorithm;\n\n\ntemplate<\n    class Value>\nusing OutOfDomainPolicy = fa::tgamma::OutOfDomainPolicy<Value>;\n\n\nBOOST_AUTO_TEST_CASE(out_of_domain_policy)\n{\n    {\n        OutOfDomainPolicy<double> policy;\n        BOOST_CHECK( policy.within_domain(5));\n        BOOST_CHECK(!policy.within_domain(-5));\n        BOOST_CHECK( policy.within_domain(-5.01));\n        BOOST_CHECK( policy.within_domain(-4.99));\n        BOOST_CHECK(policy.within_domain(0));\n        BOOST_CHECK(policy.within_domain(-0));\n    }\n}\n\n\ntemplate<\n    class Value,\n    class Result>\nusing OutOfRangePolicy = fa::tgamma::OutOfRangePolicy<Value, Result>;\n\n\ntemplate<\n    class Value,\n    class Result>\nstruct VerifyWithinRange\n{\n    bool operator()(\n        Value const& value)\n    {\n        fa::SequentialExecutionPolicy sequential;\n\n        OutOfRangePolicy<Value, Result> policy;\n        Result result;\n\n        fa::algebra::tgamma(sequential, value, result);\n\n        return policy.within_range(value, result);\n    }\n};\n\n\nBOOST_AUTO_TEST_CASE(out_of_range_policy)\n{\n    {\n        VerifyWithinRange<double, double> verify;\n        BOOST_CHECK_EQUAL(verify(-1.0), false);\n        BOOST_CHECK_EQUAL(verify(fern::infinity<double>()), false);\n    }\n}\n\n\ntemplate<\n    class Value,\n    class Result>\nvoid verify_value(\n    Value const& value,\n    Result const& result_we_want)\n{\n    fa::SequentialExecutionPolicy sequential;\n\n    Result result_we_get;\n    fa::algebra::tgamma(sequential, value, result_we_get);\n    BOOST_CHECK_CLOSE(result_we_get, result_we_want, 1e-6);\n}\n\n\nBOOST_AUTO_TEST_CASE(algorithm)\n{\n    verify_value<double, double>(10.0, 362880.0);\n    verify_value<double, double>(0.5, std::sqrt(fern::pi<double>()));\n    verify_value<double, double>(1.0, 1.0);\n}\n", "meta": {"hexsha": "7a022df923a30d10e1a62440c2e28ebfead37dfa", "size": 2427, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/tgamma_test.cc", "max_stars_repo_name": "quanpands/wflow", "max_stars_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/tgamma_test.cc", "max_issues_repo_name": "quanpands/wflow", "max_issues_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pcraster/pcraster-4.2.0/pcraster-4.2.0/source/fern/source/fern/algorithm/algebra/elementary/test/tgamma_test.cc", "max_forks_repo_name": "quanpands/wflow", "max_forks_repo_head_hexsha": "b454a55e4a63556eaac3fbabd97f8a0b80901e5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8191489362, "max_line_length": 80, "alphanum_fraction": 0.6518335393, "num_tokens": 554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.6007658260958377}}
{"text": "/*-----------------------------------------------------------------------------+\nInterval Container Library\nAuthor: Joachim Faulhaber\nCopyright (c) 2007-2009: Joachim Faulhaber\nCopyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n/** Example month_and_week_grid.cpp \\file month_and_week_grid.cpp\n    \\brief Creating and combining time grids.\n\n    A split_interval_set preserves all interval borders on insertion\n    and intersection operations. So given a split_interval_set ...\n    \\code\n    x =  {[1,     3)}\n    x.add(     [2,     4)) then\n    x == {[1,2)[2,3)[3,4)}\n    \\endcode\n    ... using this property we can intersect splitting interval containers\n    in order to iterate over intervals accounting for all changes of\n    interval borders.\n\n    In this example we provide an intersection of two split_interval_sets\n    representing a month and week time grid.\n\n    \\include month_and_week_grid_/month_and_week_grid.cpp\n*/\n//[example_month_and_week_grid\n// The next line includes <boost/gregorian/date.hpp>\n// and a few lines of adapter code.\n#include <boost/icl/gregorian.hpp>\n#include <iostream>\n#include <boost/icl/split_interval_set.hpp>\n\nusing namespace std;\nusing namespace boost::gregorian;\nusing namespace boost::icl;\n\ntypedef split_interval_set<boost::gregorian::date> date_grid;\n\n// This function splits a gregorian::date interval 'scope' into a month grid:\n// For every month contained in 'scope' that month is contained as interval\n// in the resulting split_interval_set.\ndate_grid month_grid(const discrete_interval<date>& scope)\n{\n    split_interval_set<date> month_grid;\n\n    date frame_months_1st = first(scope).end_of_month() + days(1) - months(1);\n    month_iterator month_iter(frame_months_1st);\n\n    for(; month_iter <= last(scope); ++month_iter)\n        month_grid += discrete_interval<date>::right_open(*month_iter, *month_iter + months(1));\n\n    month_grid &= scope; // cut off the surplus\n\n    return month_grid;\n}\n\n// This function splits a gregorian::date interval 'scope' into a week grid:\n// For every week contained in 'scope' that month is contained as interval\n// in the resulting split_interval_set.\ndate_grid week_grid(const discrete_interval<date>& scope)\n{\n    split_interval_set<date> week_grid;\n\n    date frame_weeks_1st = first(scope) + days(days_until_weekday(first(scope), greg_weekday(Monday))) - weeks(1);\n    week_iterator week_iter(frame_weeks_1st);\n\n    for(; week_iter <= last(scope); ++week_iter)\n        week_grid.insert(discrete_interval<date>::right_open(*week_iter, *week_iter + weeks(1)));\n\n    week_grid &= scope; // cut off the surplus\n\n    return week_grid;\n}\n\n// For a period of two months, starting from today, the function\n// computes a partitioning for months and weeks using intersection\n// operator &= on split_interval_sets.\nvoid month_and_time_grid()\n{\n    date someday = day_clock::local_day();\n    date thenday = someday + months(2);\n\n    discrete_interval<date> itv = discrete_interval<date>::right_open(someday, thenday);\n\n    // Compute a month grid\n    date_grid month_and_week_grid = month_grid(itv);\n    // Intersection of the month and week grids:\n    month_and_week_grid &= week_grid(itv);\n\n    cout << \"interval : \" << first(itv) << \" - \" << last(itv)\n         << \" month and week partitions:\" << endl;\n    cout << \"---------------------------------------------------------------\\n\";\n\n    for(date_grid::iterator it = month_and_week_grid.begin();\n        it != month_and_week_grid.end(); it++)\n    {\n        if(first(*it).day() == 1)\n            cout << \"new month: \";\n        else if(first(*it).day_of_week()==greg_weekday(Monday))\n            cout << \"new week : \" ;\n        else if(it == month_and_week_grid.begin())\n            cout << \"first day: \" ;\n        cout << first(*it) << \" - \" << last(*it) << endl;\n    }\n}\n\n\nint main()\n{\n    cout << \">>Interval Container Library: Sample month_and_time_grid.cpp <<\\n\";\n    cout << \"---------------------------------------------------------------\\n\";\n    month_and_time_grid();\n    return 0;\n}\n\n// Program output:\n/*\n>>Interval Container Library: Sample month_and_time_grid.cpp <<\n---------------------------------------------------------------\ninterval : 2008-Jun-22 - 2008-Aug-21 month and week partitions:\n---------------------------------------------------------------\nfirst day: 2008-Jun-22 - 2008-Jun-22\nnew week : 2008-Jun-23 - 2008-Jun-29\nnew week : 2008-Jun-30 - 2008-Jun-30\nnew month: 2008-Jul-01 - 2008-Jul-06\nnew week : 2008-Jul-07 - 2008-Jul-13\nnew week : 2008-Jul-14 - 2008-Jul-20\nnew week : 2008-Jul-21 - 2008-Jul-27\nnew week : 2008-Jul-28 - 2008-Jul-31\nnew month: 2008-Aug-01 - 2008-Aug-03\nnew week : 2008-Aug-04 - 2008-Aug-10\nnew week : 2008-Aug-11 - 2008-Aug-17\nnew week : 2008-Aug-18 - 2008-Aug-21\n*/\n//]\n", "meta": {"hexsha": "41f9f094dfbeeec7738c8d6715020d24beec4abd", "size": 5096, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/icl/example/month_and_week_grid_/month_and_week_grid.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/icl/example/month_and_week_grid_/month_and_week_grid.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/icl/example/month_and_week_grid_/month_and_week_grid.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": 36.4, "max_line_length": 114, "alphanum_fraction": 0.6257849294, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6007658248083076}}
{"text": "/*\n * Copyright (c) 2015, The Regents of the University of California (Regents).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *    1. Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *\n *    2. Redistributions in binary form must reproduce the above\n *       copyright notice, this list of conditions and the following\n *       disclaimer in the documentation and/or other materials provided\n *       with the distribution.\n *\n *    3. Neither the name of the copyright holder nor the names of its\n *       contributors may be used to endorse or promote products derived\n *       from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Please contact the author(s) of this library if you have any questions.\n * Authors: Erik Nelson            ( eanelson@eecs.berkeley.edu )\n *          David Fridovich-Keil   ( dfk@eecs.berkeley.edu )\n */\n\n#include \"eight_point_algorithm_solver.h\"\n\n#include <Eigen/SVD>\n#include <glog/logging.h>\n\n#include \"normalization.h\"\n\nnamespace bsfm {\n\nbool EightPointAlgorithmSolver::ComputeFundamentalMatrix(\n    const FeatureMatchList& matched_features,\n    Matrix3d& fundamental_matrix) const {\n  // Following: https://www8.cs.umu.se/kurser/TDBD19/VT05/reconstruct-4.pdf\n\n  // First make sure we even have enough matches to run the eight-point\n  // algorithm.\n  if (matched_features.size() < 8) {\n    VLOG(1) << \"Cannot use the eight-point algorithm with less than 8 feature \"\n               \"matches.\";\n    return false;\n  }\n\n  // Build the A matrix from matched features.\n  MatrixXd A;\n  A.resize(matched_features.size(), 9);\n\n  // If requested, normalize feature positions prior to computing the A matrix.\n  Matrix3d T1(MatrixXd::Identity(3, 3));\n  Matrix3d T2(MatrixXd::Identity(3, 3));\n  if (options_.normalize_features) {\n    T1 = ComputeNormalization(matched_features, true /*feature set 1*/);\n    T2 = ComputeNormalization(matched_features, false /*feature set 2*/);\n  }\n\n  // Incrementally add rows to A.\n  for (size_t ii = 0; ii < matched_features.size(); ++ii) {\n    double u1 = matched_features[ii].feature1_.u_;\n    double v1 = matched_features[ii].feature1_.v_;\n    double u2 = matched_features[ii].feature2_.u_;\n    double v2 = matched_features[ii].feature2_.v_;\n\n    if (options_.normalize_features) {\n      u1 = T1(0, 0) * u1 + T1(0, 2);\n      v1 = T1(1, 1) * v1 + T1(1, 2);\n      u2 = T2(0, 0) * u2 + T2(0, 2);\n      v2 = T2(1, 1) * v2 + T2(1, 2);\n    }\n\n    A(ii, 0) = u1*u2;\n    A(ii, 1) = v1*u2;\n    A(ii, 2) =    u2;\n    A(ii, 3) = u1*v2;\n    A(ii, 4) = v1*v2;\n    A(ii, 5) =    v2;\n    A(ii, 6) =    u1;\n    A(ii, 7) =    v1;\n    A(ii, 8) =     1;\n  }\n\n  // Get svd(A). Save some time and compute a thin U. We still need a full V.\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd;\n  svd.compute(A, Eigen::ComputeThinU | Eigen::ComputeFullV);\n  if (!svd.computeV()) {\n    VLOG(1) << \"Failed to compute a singular value decomposition of A matrix.\";\n    return false;\n  }\n\n  // Get the fundamental matrix elements from the SVD decomposition.\n  const VectorXd f_vec = svd.matrixV().col(8);\n\n  // Turn the elements of the fundamental matrix into an actual matrix.\n  fundamental_matrix.row(0) = f_vec.topRows(3).transpose();\n  fundamental_matrix.row(1) = f_vec.middleRows(3, 3).transpose();\n  fundamental_matrix.row(2) = f_vec.bottomRows(3).transpose();\n\n  // If requested, make sure that the computed fundamental matrix has rank 2.\n  // This is step 2 of the eight-point algorithm from the slides.\n  if (options_.enforce_fundamental_matrix_rank_deficiency) {\n    // Get svd(F). We need full U and V to reconstruct the rank deficient F.\n    svd.compute(fundamental_matrix, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    svd.compute(fundamental_matrix);\n    if (!svd.computeU() || !svd.computeV()) {\n      VLOG(1) << \"Failed to compute a singular value decomposition of \"\n                 \"fundamental matrix.\";\n      return false;\n    }\n\n    // Build a matrix of the first 8 singular values down the diagonal. Make the\n    // last diagonal entry 0.\n    MatrixXd S_deficient(MatrixXd::Zero(3, 3));\n    S_deficient(0, 0) = svd.singularValues()(0);\n    S_deficient(1, 1) = svd.singularValues()(1);\n    fundamental_matrix = svd.matrixU() * S_deficient * svd.matrixV().transpose();\n  }\n\n  // If normalization was requested, we need to 'un-normalize' the fundamental\n  // matrix.\n  if (options_.normalize_features) {\n    fundamental_matrix = T2.transpose() * fundamental_matrix * T1;\n  }\n\n  return true;\n}\n\n}  //\\namespace bsfm\n", "meta": {"hexsha": "078f925957ad6112109b261ae17ee95f5fabc10d", "size": 5485, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/geometry/eight_point_algorithm_solver.cpp", "max_stars_repo_name": "jamesdsmith/berkeley_sfm", "max_stars_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T13:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T19:30:33.000Z", "max_issues_repo_path": "src/cpp/geometry/eight_point_algorithm_solver.cpp", "max_issues_repo_name": "jamesdsmith/berkeley_sfm", "max_issues_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T17:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-22T20:59:43.000Z", "max_forks_repo_path": "src/cpp/geometry/eight_point_algorithm_solver.cpp", "max_forks_repo_name": "erik-nelson/berkeley_sfm", "max_forks_repo_head_hexsha": "5bf0b45fac176ff7abfca0ff690893c1afc73c51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-01-22T06:23:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-16T03:54:33.000Z", "avg_line_length": 38.3566433566, "max_line_length": 81, "alphanum_fraction": 0.6876937101, "num_tokens": 1465, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6007658146180865}}
{"text": "#include <Eigen/Core>\n#include \"test/catch.hpp\"\n#include \"rose499/spline.hpp\"\n\nusing namespace Eigen;\n\nSCENARIO( \"waypoints can be splined with a 5th order C^2 polynomial\", \"[spline]\" )\n{\n    GIVEN( \"trivial linear sequence of waypoints\" )\n    {\n        constexpr auto SegmentCount = 1;\n        Matrix<Spline::ValueType, 2, 2> waypoints;\n        waypoints(0, 0) = 0; waypoints(1, 0) = 0;\n        waypoints(0, 1) = 1; waypoints(1, 1) = 1;\n\n        WHEN( \"splined via contructor\" )\n        {\n            Spline spline(waypoints);\n            THEN( \"waypoints should be on the spline\" )\n            {\n                for(auto i = 0; i < waypoints.cols(); ++i)\n                {\n                    auto splinePoint = spline((i * 1.0) / SegmentCount);\n                    auto waypoint = waypoints.col(i);\n                    REQUIRE((splinePoint - waypoint).isZero() );\n                }\n            }\n        }\n\n        WHEN( \"splined via contructor with a direction constraint\" )\n        {\n            Spline spline(waypoints, std::atan2(0, 1));\n            THEN( \"waypoints should be on the spline\" )\n            {\n                for(auto i = 0; i < waypoints.cols(); ++i)\n                {\n                    auto splinePoint = spline((i * 1.0) / SegmentCount);\n                    auto waypoint = waypoints.col(i);\n                    REQUIRE( (splinePoint - waypoint).norm() == Approx(0).margin(1e-12) );\n                }\n            }\n\n            THEN( \"derivative of spline at initial point is what was requested\" )\n            {\n                auto slope = spline(0, 1);\n                CAPTURE( slope );\n                REQUIRE( std::atan2(slope[1], slope[0]) == Approx(std::atan2(0, 1)) );\n            }\n        }\n    }\n\n    GIVEN( \"non-trivial sequence of waypoints\" )\n    {\n        constexpr auto SegmentCount = 5 - 1;\n        Matrix<Spline::ValueType, 2, 5> waypoints;\n        waypoints(0, 0) = 0; waypoints(1, 0) = 0;\n        waypoints(0, 1) = 2; waypoints(1, 1) = 1;\n        waypoints(0, 2) = 4; waypoints(1, 2) = 0.5;\n        waypoints(0, 3) = 6; waypoints(1, 3) = -0.5;\n        waypoints(0, 4) = 3; waypoints(1, 4) = -1;\n\n        WHEN( \"splined via contructor\" )\n        {\n            Spline spline(waypoints, std::atan2(1, 1));\n            THEN( \"waypoints should be on the spline\" )\n            {\n                for(auto i = 0; i < waypoints.cols(); ++i)\n                {\n                    auto splinePoint = spline((i * 1.0) / SegmentCount);\n                    auto waypoint = waypoints.col(i);\n                    CAPTURE( spline.poly() );\n                    REQUIRE( (splinePoint - waypoint).norm() == Approx(0.0).margin(1e-12) );\n                }\n            }\n\n            THEN( \"derivative of spline at initial point is what was requested\" )\n            {\n                auto slope = spline(0, 1);\n                CAPTURE( slope );\n                REQUIRE( std::atan2(slope[1], slope[0]) == Approx(std::atan2(1, 1)) );\n            }\n\n            THEN( \"spline should observe C1 continuity on all intermediate points\" )\n            {\n                for(auto i = 1; i < waypoints.cols() - 1; ++i)\n                {\n                    auto derivativeFromLeft = spline((i * 1.0) / SegmentCount - 1e-12, 1);\n                    auto derivativeFromRight = spline((i * 1.0) / SegmentCount + 1e-12, 1);\n                    CAPTURE( spline.dpoly() );\n                    CAPTURE( i );\n                    REQUIRE( (derivativeFromLeft - derivativeFromRight).norm() == Approx(0.0).margin(1e-12) );\n                }\n            }\n\n            THEN( \"spline should observe C2 continuity on all intermediate points\" )\n            {\n                for(auto i = 1; i < waypoints.cols() - 1; ++i)\n                {\n                    auto derivativeFromLeft = spline((i * 1.0) / SegmentCount - 1e-12, 2);\n                    auto derivativeFromRight = spline((i * 1.0) / SegmentCount + 1e-12, 2);\n                    CAPTURE( spline.ddpoly() );\n                    CAPTURE( i );\n                    REQUIRE( (derivativeFromLeft - derivativeFromRight).norm() == Approx(0.0).margin(1e-12) );\n                }\n            }\n        }\n\n        GIVEN( \"a working spline\" )\n        {\n            Spline spline(waypoints);\n\n            WHEN( \"finding the nearest point on the curve to the end point\" )\n            {\n                Spline::ValueType lambda = spline.nearestPoint(waypoints.col(waypoints.cols()-1), 0.9);\n\n                THEN( \"it ought to be 1\")\n                {\n                    REQUIRE( lambda == Approx(1.0).margin(1e-12) );\n                }\n            }\n\n            WHEN( \"finding the nearest point on the curve to some non-trivial point\" )\n            {\n                auto point = Matrix<Spline::ValueType, 2, 1>::Constant(1);\n                Spline::ValueType lambda = spline.nearestPoint(point, 0.1);\n\n                THEN( \"the tangent of the closest point on the curve should be orthogonal to the error\" )\n                {\n                    CAPTURE( lambda );\n                    REQUIRE( spline(lambda, 1).dot(spline(lambda) - point) == Approx(0.0).margin(1e-12) );\n                }\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "10862497de9ce88c6ecbc204daced29b2b1ef469", "size": 5173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/src/tests/testSpline.cpp", "max_stars_repo_name": "rollends/SE499", "max_stars_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulator/src/tests/testSpline.cpp", "max_issues_repo_name": "rollends/SE499", "max_issues_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulator/src/tests/testSpline.cpp", "max_forks_repo_name": "rollends/SE499", "max_forks_repo_head_hexsha": "949b9cc85abe558b84289d906b730605c2f32c3b", "max_forks_repo_licenses": ["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.0367647059, "max_line_length": 110, "alphanum_fraction": 0.4741929248, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6007658139743213}}
{"text": "//==============================================================================\n//         Copyright 2015 INSTITUT PASCAL UMR 6602 CNRS/Univ. Clermont II\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n\n\n#include <iostream>\n#include <fstream>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/math/special_functions/sinc.hpp>\n\n//#define USE_TOON\n#include <libv/lma/lma.hpp>\n\nnamespace v\n{\n  Eigen::Matrix3d rotation_exp(const Eigen::Matrix3d &a)\n  {\n    double theta2 = a(0,1)*a(0,1) + a(0,2)*a(0,2) +  a(1,2)*a(1,2) + std::numeric_limits<double>::epsilon();\n    double theta = std::sqrt(theta2);\n    return Eigen::Matrix3d::Identity() + boost::math::sinc_pi(theta)*a+(1.0-std::cos(theta))/theta2*a*a;\n  }\n  \n  void apply_rotation(Eigen::Matrix3d &m, const Eigen::Vector3d &d)\n  {\n    Eigen::Matrix3d skrew;\n    skrew << 0, -d.z(), d.y(), d.z(), 0, -d.x(), -d.y(), d.x(), 0;\n    m *= rotation_exp(skrew);\n  }\n\n  void apply_small_rotation_(Eigen::Matrix3d& rotation, double h, int i, int j)\n  {\n    const Eigen::Vector3d col_l = rotation.col(j) - rotation.col(i) * h;\n    rotation.col(i) += rotation.col(j) * h;\n    rotation.col(j) = col_l;\n  }\n\n  void apply_small_rotation_x(Eigen::Matrix3d& rotation, double h) { apply_small_rotation_(rotation,h,1,2); }\n  void apply_small_rotation_y(Eigen::Matrix3d& rotation, double h) { apply_small_rotation_(rotation,-h,0,2); }\n  void apply_small_rotation_z(Eigen::Matrix3d& rotation, double h) { apply_small_rotation_(rotation,h,0,1); }\n}\n\n// Pose camera = Rotation + Translation + intrinsics\nstruct Camera\n{\n  Eigen::Matrix3d rotation = Eigen::Matrix3d::Identity();\n  Eigen::Vector3d translation = {0,0,0};\n  double a=0,b=0,c=0;\n};\n\n// Point 3D = Eigen::Vector3d\n\n\nnamespace lma\n{\n  // Update policy of a Camera according to 9 degres of freedom\n  // The Adl parameter enable the usage of a function defined after its use\n  void apply_increment(Camera& camera, const double delta[9], const Adl&)\n  {\n    // update rotation using exponential map : camera.rotation *= exp(skew(delta{0,1,2}))\n    v::apply_rotation(camera.rotation,{delta[0],delta[1],delta[2]});\n\n    // update translation : camera.translation += delta{3,4,5}\n    camera.translation += Eigen::Map<const Eigen::Vector3d>(delta + 3);\n\n    // update instrinsics : (camera{a,b,c} += delta{6,7,8})\n    Eigen::Map<Eigen::Array3d>(&camera.a) += Eigen::Map<const Eigen::Array3d>(delta+6);\n  }\n\n  // Only for numerical derivative:\n  // Update policy of a Camera according to the Ie parameter (h ~ 1e-8).\n  // The Adl parameter enable the usage of a function defined after its use\n  template<int I> void apply_small_increment(Camera& camera, double h, v::numeric_tag<I>, const Adl&)\n  {\n    if      (I == 0) v::apply_small_rotation_x(camera.rotation,h);\n    else if (I == 1) v::apply_small_rotation_y(camera.rotation,h);\n    else if (I == 2) v::apply_small_rotation_z(camera.rotation,h);\n    else if (I == 3) camera.translation.x() += h;\n    else if (I == 4) camera.translation.y() += h;\n    else if (I == 5) camera.translation.z() += h;\n    else if (I == 6) camera.a += h;\n    else if (I == 7) camera.b += h;\n    else if (I == 8) camera.c += h;\n  }\n\n  //degree of freedom of a Camera\n  template<> struct Size<Camera> { enum {value = 9}; };\n\n  // Nothing to specify for the 3D points (Eigen::Vector3d) :\n  //   - degree of freedom of an Eigen::Vector is the size.\n  //   - The update policy of an Eigen::Vector is operator+.\n}\n\n\nstruct BALProblem \n{\n  bool load(std::string filename)\n  {\n    std::ifstream file(filename);\n    if (!file.is_open()) return false;\n\n    size_t num_cameras,num_points,num_observations;\n\n    file >> num_cameras >> num_points >> num_observations;\n\n    std::cout << color.yellow() << \n      boost::format(\"Cameras[%1%], Points 3D[%2%], Observations[%3%]\")%num_cameras%num_points%num_observations \n      << color.reset() << std::endl;\n\n    point_index.resize(num_observations);\n    camera_index.resize(num_observations);\n    observations.resize(num_observations);\n    \n    cameras.resize(num_cameras);\n    points3d.resize(num_points);\n\n    for(size_t i = 0; i < observations.size(); ++i)\n      file >> camera_index[i]\n           >> point_index[i]\n           >> observations[i].x()\n           >> observations[i].y();\n\n    for(size_t i = 0; i < num_cameras; ++i)\n    {\n      std::array<double,9> params;\n      for(size_t k = 0 ; k < 9 ; ++k)\n        file >> params[k];\n      lma::apply_increment(cameras[i],params.data(),lma::Adl{});\n    }\n\n    for(size_t i = 0; i < num_points; ++i)\n      file >> points3d[i].x() \n           >> points3d[i].y()\n           >> points3d[i].z();\n\n    return true;\n  }\n\n  std::vector<int> point_index;\n  std::vector<int> camera_index;\n\n  template<class T> using AlignedVector = std::vector<T,Eigen::aligned_allocator<T>>;\n  AlignedVector<Eigen::Vector3d> points3d;\n  AlignedVector<Eigen::Vector2d> observations;\n  AlignedVector<Camera> cameras;\n};\n\n\nstruct Reprojection\n{\n  const Eigen::Vector2d& obs;\n  Reprojection(const Eigen::Vector2d& p2d):obs(p2d){}\n\n  bool operator()(const Camera& camera, const Eigen::Vector3d& point, double (&error)[2]) const\n  {\n    const Eigen::Vector3d p = camera.rotation * point + camera.translation;\n    const double\n      xp = - p[0] / p[2],\n      yp = - p[1] / p[2],\n      r2 = xp*xp + yp*yp,\n      distortion = 1.0 + r2  * (camera.b + camera.c  * r2);\n\n    error[0] = camera.a * distortion * xp - obs[0];\n    error[1] = camera.a * distortion * yp - obs[1];\n    return true;\n  }\n};\n\nnamespace ttt\n{\n  template<> struct Name< Reprojection > { static std::string name(){ return \"Reprojection\"; } };\n}\n\nvoid call_lma(std::string file, double lambda, int iteration_max)\n{\n\n  BALProblem bal_problem;\n  if (!bal_problem.load(file)) {\n    std::cerr << \"ERROR: unable to open file \" << file << \"\\n\";\n    return ;\n  }\n\n  lma::Solver<Reprojection> solver(lambda,iteration_max);\n\n  for (size_t i = 0; i < bal_problem.observations.size(); ++i)\n    solver.add(\n                Reprojection(bal_problem.observations[i]),\n                &bal_problem.cameras[bal_problem.camera_index[i]], \n                &bal_problem.points3d[bal_problem.point_index[i]]\n              );\n\n  solver.solve(lma::DENSE_SCHUR,lma::enable_verbose_output());\n}\n\n\n\nint main(int argc, char** argv)\n{\n  if (argc == 4) \n    call_lma(argv[1],boost::lexical_cast<double>(argv[2]),boost::lexical_cast<int>(argv[3]));\n  else\n    std::cerr << \"usage: test-lma3d <bal_problem> initial_lambda nb_iteration_max\\n\";\n\n  return 0;\n}\n\n", "meta": {"hexsha": "aa41faeed79348a05948a4c4b6d03f2dbc15c432", "size": 6694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/bal.cpp", "max_stars_repo_name": "bezout/LMA", "max_stars_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-12-08T12:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T21:23:01.000Z", "max_issues_repo_path": "tests/bal.cpp", "max_issues_repo_name": "ayumizll/LMA", "max_issues_repo_head_hexsha": "e945452e12a8b05bd17400b46a20a5322aeda01d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-07-11T16:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T13:33:00.000Z", "max_forks_repo_path": "tests/bal.cpp", "max_forks_repo_name": "bezout/LMA", "max_forks_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-12-21T01:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-26T02:26:55.000Z", "avg_line_length": 31.7251184834, "max_line_length": 111, "alphanum_fraction": 0.6244397968, "num_tokens": 1901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6007658139743212}}
{"text": "#include \"CubicSpline.hpp\"\n\n#include \"BezierCurve.hpp\"\n\n__pragma(warning(push, 0))\n#include <Eigen/Eigen>\n    __pragma(warning(pop))\n\n#include \"CubicSpline.hpp\"\n#include <tbb/tbb.h>\n\n//#define CUBIC_USE_BEZIER\n\n        namespace Ilum::geometry\n{\n\t// Bezier Spline\n\tstruct BezierCubicSpline : public Curve\n\t{\n\t\t// New generated control points\n\t\tstd::vector<glm::vec3> control_points;\n\n\t\tvirtual std::vector<glm::vec3> generateVertices(const std::vector<glm::vec3> &control_points, uint32_t sample) override;\n\n\t\tvirtual glm::vec3 value(const std::vector<glm::vec3> &control_points, float t) override;\n\n\t  private:\n\t\tvoid generateControlPoints(const std::vector<glm::vec3> &control_points);\n\t};\n\n\t// B-Spline\n\tstruct BCubicSpline : public Curve\n\t{\n\t\tvirtual std::vector<glm::vec3> generateVertices(const std::vector<glm::vec3> &control_points, uint32_t sample) override;\n\n\t\tvirtual glm::vec3 value(const std::vector<glm::vec3> &control_points, float t) override;\n\n\t  private:\n\t\tvoid genDeBoorPoints(const std::vector<glm::vec3> &control_points);\n\n\t\tstd::vector<glm::vec3> m_de_boor;\n\t\tstd::vector<float>     m_knots;\n\t};\n\n\tstd::vector<glm::vec3> BezierCubicSpline::generateVertices(const std::vector<glm::vec3> &control_points, uint32_t sample)\n\t{\n\t\tBezierCurve bezier_curve;\n\n\t\tif (control_points.size() <= 2)\n\t\t{\n\t\t\treturn bezier_curve.generateVertices(control_points, sample);\n\t\t}\n\n\t\tif (this->control_points.empty())\n\t\t{\n\t\t\tgenerateControlPoints(control_points);\n\t\t}\n\n\t\tuint32_t patch = sample / static_cast<uint32_t>(control_points.size() - 1);\n\n\t\tstd::vector<glm::vec3> result;\n\n\t\tfor (uint32_t i = 0; i < control_points.size() - 1; i++)\n\t\t{\n\t\t\tauto frag = std::move(bezier_curve.generateVertices({this->control_points[3 * i],\n\t\t\t                                                     this->control_points[3 * i + 1],\n\t\t\t                                                     this->control_points[3 * i + 2],\n\t\t\t                                                     this->control_points[3 * i + 3]},\n\t\t\t                                                    patch));\n\t\t\tresult.insert(result.end(), std::make_move_iterator(frag.begin()), std::make_move_iterator(frag.end()));\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tglm::vec3 BezierCubicSpline::value(const std::vector<glm::vec3> &control_points, float t)\n\t{\n\t\tBezierCurve bezier_curve;\n\n\t\tif (control_points.size() <= 2)\n\t\t{\n\t\t\treturn bezier_curve.value(control_points, t);\n\t\t}\n\n\t\tif (this->control_points.empty())\n\t\t{\n\t\t\tgenerateControlPoints(control_points);\n\t\t}\n\n\t\treturn bezier_curve.value(this->control_points, t);\n\t}\n\n\tvoid BezierCubicSpline::generateControlPoints(const std::vector<glm::vec3> &control_points)\n\t{\n\t\tif (control_points.size() < 2)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tsize_t n = control_points.size() - 1;\n\n\t\tEigen::MatrixXf A(3 * n + 1, 3 * n + 1);\n\t\tEigen::MatrixXf b(3 * n + 1, 3);\n\t\tA.setZero();\n\t\tb.setZero();\n\n\t\ttbb::parallel_for(tbb::blocked_range<size_t>(0, n + 1u), [this, n, control_points, &A, &b](const tbb::blocked_range<size_t> &count) {\n\t\t\tfor (size_t i = count.begin(); i != count.end(); i++)\n\t\t\t{\n\t\t\t\tA(i, 3 * i) = 1;\n\n\t\t\t\tif (i >= 1 && i <= n - 1)\n\t\t\t\t{\n\t\t\t\t\tA(n + i, 3 * i - 1) = -1;\n\t\t\t\t\tA(n + i, 3 * i)     = 2;\n\t\t\t\t\tA(n + i, 3 * i + 1) = -1;\n\n\t\t\t\t\tA(2 * n + i - 1, 3 * i - 2) = 1;\n\t\t\t\t\tA(2 * n + i - 1, 3 * i - 1) = -2;\n\t\t\t\t\tA(2 * n + i - 1, 3 * i)     = 0;\n\t\t\t\t\tA(2 * n + i - 1, 3 * i + 1) = 2;\n\t\t\t\t\tA(2 * n + i - 1, 3 * i + 2) = -1;\n\t\t\t\t}\n\n\t\t\t\tb(i, 0) = control_points[i].x;\n\t\t\t\tb(i, 1) = control_points[i].y;\n\t\t\t\tb(i, 2) = control_points[i].z;\n\t\t\t}\n\t\t});\n\n\t\t// End condition\n\t\tA(3 * n - 1, 0) = 1;\n\t\tA(3 * n - 1, 1) = -2;\n\t\tA(3 * n - 1, 2) = 1;\n\n\t\tA(3 * n, 3 * n - 2) = 1;\n\t\tA(3 * n, 3 * n - 1) = -2;\n\t\tA(3 * n, 3 * n)     = 1;\n\n\t\tEigen::MatrixXf x = A.colPivHouseholderQr().solve(b);\n\n\t\tthis->control_points.resize(3 * n + 1);\n\n\t\tfor (size_t i = 0; i < 3 * n + 1; i++)\n\t\t{\n\t\t\tthis->control_points[i].x = x(i, 0);\n\t\t\tthis->control_points[i].y = x(i, 1);\n\t\t\tthis->control_points[i].z = x(i, 2);\n\t\t}\n\t}\n\n\tinline float gen_basis(const std::vector<float> &T, float t, size_t i, size_t k)\n\t{\n\t\tif (k == 1)\n\t\t{\n\t\t\tif ((t >= T[i] && t < T[i + 1]) || (t >= T[i] && t <= T[i + 1] && T[i + 1] == T.back()))\n\t\t\t{\n\t\t\t\treturn 1.0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn 0.0;\n\t\t\t}\n\t\t}\n\t\tfloat left = 0.f;\n\t\tleft       = T[i + k - 1ull] - T[i] == 0.f ? 0.f : (t - T[i]) / (T[i + k - 1] - T[i]) * gen_basis(T, t, i, k - 1ull);\n\n\t\tfloat right = 0.f;\n\t\tright       = T[i + k] - T[i + 1ull] == 0.f ? 0.f : (T[i + k] - t) / (T[i + k] - T[i + 1ull]) * gen_basis(T, t, i + 1ull, k - 1ull);\n\n\t\treturn left + right;\n\t}\n\n\tstd::vector<glm::vec3> BCubicSpline::generateVertices(const std::vector<glm::vec3> &control_points, uint32_t sample)\n\t{\n\t\tif (control_points.empty())\n\t\t{\n\t\t\treturn {};\n\t\t}\n\n\t\tif (m_de_boor.empty())\n\t\t{\n\t\t\tgenDeBoorPoints(control_points);\n\t\t}\n\n\t\tstd::vector<glm::vec3> vertices(sample + 1u);\n\n\t\ttbb::parallel_for(tbb::blocked_range<size_t>(0, sample + 1u), [this, control_points, sample, &vertices](const tbb::blocked_range<size_t> &count) {\n\t\t\tfor (size_t i = count.begin(); i != count.end(); i++)\n\t\t\t{\n\t\t\t\tfloat t     = m_knots.back() / static_cast<float>(sample) * static_cast<float>(i);\n\t\t\t\tvertices[i] = value(control_points, t);\n\t\t\t}\n\t\t});\n\t\treturn vertices;\n\t}\n\n\tglm::vec3 BCubicSpline::value(const std::vector<glm::vec3> &control_points, float t)\n\t{\n\t\tif (m_de_boor.empty())\n\t\t{\n\t\t\tgenDeBoorPoints(control_points);\n\t\t}\n\n\t\tglm::vec3 result = glm::vec3(0.f);\n\n\t\tfor (size_t i = 0; i < m_de_boor.size(); i++)\n\t\t{\n\t\t\tresult += gen_basis(m_knots, t, i, 4) * m_de_boor[i];\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tvoid BCubicSpline::genDeBoorPoints(const std::vector<glm::vec3> &control_points)\n\t{\n\t\tstd::vector<float> s;\n\n\t\t// Knot sequence\n\t\tm_knots.clear();\n\t\tm_knots.push_back(0);\n\t\tm_knots.push_back(0);\n\t\tm_knots.push_back(0);\n\n\t\tfor (size_t i = 0; i < control_points.size(); i++)\n\t\t{\n\t\t\tm_knots.push_back(static_cast<float>(i));\n\t\t\ts.push_back(static_cast<float>(i));\n\t\t}\n\n\t\tm_knots.push_back(static_cast<float>(control_points.size() - 1));\n\t\tm_knots.push_back(static_cast<float>(control_points.size() - 1));\n\t\tm_knots.push_back(static_cast<float>(control_points.size() - 1));\n\n\t\tsize_t n = m_knots.size() - 4;\n\n\t\tm_de_boor.resize(n);\n\n\t\tEigen::MatrixXf A(n, n);\n\t\tEigen::MatrixXf b(n, 3);\n\n\t\tA.setZero();\n\t\tb.setZero();\n\n\t\t// Begin\n\t\t{\n\t\t\tA(0, 0) = 1;\n\n\t\t\tA(1, 0) = 2;\n\t\t\tA(1, 1) = -3;\n\t\t\tA(1, 2) = 1;\n\n\t\t\tb(0, 0) = control_points[0].x;\n\t\t\tb(0, 1) = control_points[0].y;\n\t\t\tb(0, 2) = control_points[0].z;\n\t\t}\n\n\t\t// Inner\n\t\t{\n\t\t\tfor (size_t i = 1; i < control_points.size() - 1; i++)\n\t\t\t{\n\t\t\t\tA(i + 1, i)     = gen_basis(m_knots, s[i], i, 4);\n\t\t\t\tA(i + 1, i + 1) = gen_basis(m_knots, s[i], i + 1, 4);\n\t\t\t\tA(i + 1, i + 2) = gen_basis(m_knots, s[i], i + 2, 4);\n\t\t\t\tb(i + 1, 0)     = control_points[i].x;\n\t\t\t\tb(i + 1, 1)     = control_points[i].y;\n\t\t\t\tb(i + 1, 2)     = control_points[i].z;\n\t\t\t}\n\t\t}\n\n\t\t// End\n\t\t{\n\t\t\tA(n - 2, n - 3) = 1;\n\t\t\tA(n - 2, n - 2) = -3;\n\t\t\tA(n - 2, n - 1) = 2;\n\n\t\t\tA(n - 1, n - 1) = 1;\n\n\t\t\tb(n - 1, 0) = control_points.back().x;\n\t\t\tb(n - 1, 1) = control_points.back().y;\n\t\t\tb(n - 1, 2) = control_points.back().z;\n\t\t}\n\n\t\tEigen::MatrixXf res = A.colPivHouseholderQr().solve(b);\n\n\t\tfor (size_t i = 0; i < m_de_boor.size(); i++)\n\t\t{\n\t\t\tm_de_boor[i] = glm::vec3(res(i, 0), res(i, 1), res(i, 2));\n\t\t}\n\t}\n\n\tstd::vector<glm::vec3> CubicSpline::generateVertices(const std::vector<glm::vec3> &control_points, uint32_t sample)\n\t{\n#ifdef CUBIC_USE_BEZIER\n\t\tBezierCubicSpline curve;\n\t\treturn curve.generateVertices(control_points, sample);\n#else\n\t\tBCubicSpline curve;\n\t\treturn curve.generateVertices(control_points, sample);\n#endif        // CUBIC_USE_BEZIER\n\t}\n\n\tglm::vec3 CubicSpline::value(const std::vector<glm::vec3> &control_points, float t)\n\t{\n#ifdef CUBIC_USE_BEZIER\n\t\tBezierCubicSpline curve;\n\t\treturn curve.value(control_points, t);\n#else\n\t\tBCubicSpline curve;\n\t\treturn curve.value(control_points, t);\n#endif        // CUBIC_USE_BEZIER \n\t}\n}", "meta": {"hexsha": "ce1f9e65303ee2c6ed3d88414f49cade7a870e39", "size": 7906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/Ilum/Geometry/Curve/CubicSpline.cpp", "max_stars_repo_name": "Chaf-Libraries/Ilum", "max_stars_repo_head_hexsha": "83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2022-01-09T05:32:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:35:16.000Z", "max_issues_repo_path": "Source/Ilum/Geometry/Curve/CubicSpline.cpp", "max_issues_repo_name": "Chaf-Libraries/Ilum", "max_issues_repo_head_hexsha": "83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Ilum/Geometry/Curve/CubicSpline.cpp", "max_forks_repo_name": "Chaf-Libraries/Ilum", "max_forks_repo_head_hexsha": "83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-20T15:39:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T15:39:03.000Z", "avg_line_length": 25.3397435897, "max_line_length": 148, "alphanum_fraction": 0.581330635, "num_tokens": 2860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6007456196945368}}
{"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_COTH_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COTH_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-hyperbolic\n    Function object implementing coth capabilities\n\n    Returns the hyperbolic cotangent: \\f$(e^{x}+e^{-x})/(e^{x}-e^{-x})\\f$\n\n    @par Semantic:\n\n    For every parameter of floating type @c T\n\n    @code\n    T r = coth(x);\n    @endcode\n\n    @see sinh, cosh, sinhcosh\n\n  **/\n  Value coth(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/coth.hpp>\n#include <boost/simd/function/simd/coth.hpp>\n\n#endif\n", "meta": {"hexsha": "58df148b303d8916a42d79fff18718a73f6d1c4c", "size": 1001, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/coth.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/coth.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/coth.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": 22.75, "max_line_length": 100, "alphanum_fraction": 0.5584415584, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.6859494614282922, "lm_q1q2_score": 0.6007456152468131}}
{"text": "#include <boost/format.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n#include <cmath>\n#include <complex>\n\nclass NCO {\npublic: \n  NCO(double _fsamp) {\n    fsamp = _fsamp;\n  }\n\n  virtual void setFreq(double f) = 0; \n\n  virtual std::complex<double> step() = 0; \n\n  double fsamp;\n};\n\nclass NCOSinCos : public NCO {\npublic:\n  NCOSinCos(double _fsamp) : NCO(_fsamp) {\n    idx = 0; \n    ang = 0.0; \n  }\n\n  void setFreq(double f) {\n    ainc = 2.0 * M_PI * f / fsamp;\n  }\n\n  std::complex<double> step() {\n    double s, c; \n    ang += ainc; \n    ang = (ang > M_PI) ? (ang - (2.0 * M_PI)) : ang; \n    sincos(ang, &s, &c); \n    return std::complex<double>(c, -s);\n  }\n\nprivate:\n  double ang; \n  double ainc; \n  int idx; \n}; \n\n\nclass NCORecursive : public NCO {\npublic:\n  NCORecursive(double _fsamp) : NCO(_fsamp) {\n    idx = 0; \n    ang = 0.0; \n    ejw = std::complex<double>(1.0, 0.0);\n    last = std::complex<double>(1.0, 0.0);\n  }\n\n  void setFreq(double f) {\n    ainc = 2.0 * M_PI * f / fsamp; \n    ejw = exp(std::complex<double>(0.0, -ainc));\n  }\n\n  std::complex<double> step() {\n    std::complex<double> nval;\n    idx++;\n    ang += ainc; \n    ang = (ang > M_PI) ? (ang - (2.0 * M_PI)) : ang; \n    if(idx == 2048) {\n      idx = 0; \n      double s, c; \n      sincos(ang, &s, &c); \n      nval = std::complex<double>(c, -s);\n    }\n    else {\n      nval = last * ejw; \n    }\n    last = nval;\n    return nval; \n  }\n\nprivate:\n  double ang; \n  double ainc; \n  std::complex<double> ejw, last;\n  int idx; \n}; \n\nclass NCORecursive2 : public NCO {\npublic:\n  NCORecursive2(double _fsamp) : NCO(_fsamp) {\n    idx = 0; \n    ejw = std::complex<double>(1.0, 0.0);\n    last = std::complex<double>(1.0, 0.0);\n  }\n\n  void setFreq(double f) {\n    double ainc = 2.0 * M_PI * f / fsamp; \n    ejw = exp(std::complex<double>(0.0, -ainc));\n  }\n\n  std::complex<double> step() {\n    std::complex<double> nval;\n    idx++;\n    nval = last * ejw;     \n    if(idx == 512) {\n      idx = 0; \n      nval = nval / abs(nval);\n    }\n    last = nval;\n    return nval; \n  }\n\nprivate:\n  std::complex<double> ejw, last;\n  int idx; \n}; \n\n\nint main(int argc, char * argv[])\n{\n  unsigned long testcount = 100000000;\n  //  unsigned long testcount = 10000;\n\n\n  if(argc == 1) {\n    // compare the two schemes\n    double maxerr[2] = { 0.0, 0.0 }; \n    double toterr[2] = { 0.0, 0.0 }; \n    NCOSinCos sco(100e3);\n    NCORecursive ro(100e3);\n    NCORecursive2 ro2(100e3);\n\n    sco.setFreq(2.5325e3);\n    ro.setFreq(2.5325e3);\n    ro2.setFreq(2.5325e3);        \n    std::complex<double> scv, rv, rv2; \n    for(unsigned long k = 0; k < 10; k++) {\n      for(unsigned long i =  0; i < testcount; i++) {\n\tscv = sco.step();\n\trv = ro.step();\n\trv2 = ro2.step();      \n\t// std::cout << boost::format(\"%d %g %g %g %g\\n\")\n\t//  \t% i % scv.real() % scv.imag() % rv.real() % rv.imag(); \n\tstd::complex<double> diff[2];\n\tdiff[0] = rv - scv;\n\tdiff[1] = rv2 - scv; \n\tfor(int j = 0; j < 2; j++) {\n\t  double err = abs(diff[j]);\t\n\t  if(err > maxerr[j]) maxerr[j] = err; \n\t  toterr[j] += err; \n\t}\n\n      }\n\n      for(int j = 0; j < 2; j++) {\n\tstd::cout << boost::format(\"%d : RO[%d] Max error = %g  average error = %g\\n\")\n\t  % k % j % maxerr[j] % (toterr[j] / ((double) testcount));\n      }\n    }\n  }\n  else if(argv[1][0] == 't') {\n    // do the trig version\n    double sum = 0.0; \n    NCOSinCos o(100e3);\n    o.setFreq(2.5325e3);\n    std::complex<double> v;\n    for(unsigned long i =  0; i < testcount; i++) {\n      v = o.step();\n      sum += v.real();\n    }\n    std::cout << \"NCOSinCos sum = \" <<  sum << std::endl; \n  }\n  else if(argv[1][0] == '2') {\n    // do the recursive gain compensation version\n    double sum = 0.0; \n    NCORecursive2 o(100e3);\n    o.setFreq(2.5325e3);\n    std::complex<double> v;\n    for(unsigned long i =  0; i < testcount; i++) {\n      v = o.step();\n      sum += v.real();\n    }\n    std::cout << \"NCORecursive2 sum = \" << sum << std::endl; \n  }\n  else {\n    // do the recursive version\n    double sum = 0.0; \n    NCORecursive o(100e3);\n    o.setFreq(2.5325e3);\n    std::complex<double> v;\n    for(unsigned long i =  0; i < testcount; i++) {\n      v = o.step();\n      sum += v.real();\n    }\n    std::cout << \"NCORecursive sum = \" << sum << std::endl; \n  }\n}\n", "meta": {"hexsha": "507e7ba276ee53033d0e9e755189a596b82088c0", "size": 4223, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "exp/NCOexp.cxx", "max_stars_repo_name": "kb1vc/SoDaRadio", "max_stars_repo_head_hexsha": "0a41fa3d795b1c93795ad62ad17bf2de5f60a752", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-10-27T16:01:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T08:12:42.000Z", "max_issues_repo_path": "exp/NCOexp.cxx", "max_issues_repo_name": "dd0vs/SoDaRadio", "max_issues_repo_head_hexsha": "0a41fa3d795b1c93795ad62ad17bf2de5f60a752", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-09-16T03:13:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-11T09:11:35.000Z", "max_forks_repo_path": "exp/NCOexp.cxx", "max_forks_repo_name": "dd0vs/SoDaRadio", "max_forks_repo_head_hexsha": "0a41fa3d795b1c93795ad62ad17bf2de5f60a752", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-09-13T12:47:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-02T20:54:25.000Z", "avg_line_length": 21.6564102564, "max_line_length": 79, "alphanum_fraction": 0.5287710159, "num_tokens": 1531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.6007456072743403}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n\n/**\n * @brief get Fourier modes of array indices\n *        in centered zero frequency convention\n *\n * @param i  array index\n * @param n  array size\n *\n * @return\n */\ninline int\nto_freq(int i, int n)\n{\n  int kmax = n / 2;\n  int k = i - kmax;\n  return k;\n}\n\ninline auto\nftgrid(int n)\n{\n  int o = 1 ? n % 2 == 0 : 0;\n  return Eigen::ArrayXd::LinSpaced(n, -n / 2, n / 2 - o);\n}\n", "meta": {"hexsha": "9d393a18a05c70928b550d108308837aafa8694a", "size": 414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fft/ft_grid_helpers_impl/fourier_modes.hpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "fft/ft_grid_helpers_impl/fourier_modes.hpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fft/ft_grid_helpers_impl/fourier_modes.hpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 14.275862069, "max_line_length": 57, "alphanum_fraction": 0.5845410628, "num_tokens": 140, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.754914997895581, "lm_q1q2_score": 0.6006542329347779}}
{"text": "/* -*-C++-*- */\n/*\n   (c) Copyright 2002-2005, Hewlett-Packard Development Company, LP\n\n   See the file named COPYING for license details\n*/\n\n/** @file\n    \\brief header file for StatsQuantile\n*/\n\n#ifndef LINTEL_STATSQUANTILE_HPP\n#define LINTEL_STATSQUANTILE_HPP\n\n#include <stdio.h>\n\n#include <Lintel/Stats.hpp>\n#include <Lintel/PriorityQueue.hpp>\n\n#include <boost/utility.hpp>\n\n/// \\brief Non-sampled quantile statistics\n///\n/// Based on the paper:\n/// \"Approximate medians and other quantiles in one pass with limited memory\"\n/// by G. Manku and S. Rajagopalan and B. Lindsay\n/// Proceedings of the ACM SIGMOD, 1998. \n///\n/// An improved algorithm (don't need nbound, reduced memory usage is\n/// \"Space-Efficient Online Computation of Quantile Summaries\",\n/// Greenwald and Khanna, http://eprints.kfupm.edu.sa/66004/1/66004.pdf\nclass StatsQuantile : public Stats, boost::noncopyable {\npublic:\n    /// The default tuning parameters use up about 59 KiB/StatsQuantile\n    /// and support up to a billion inputs with quantile 0.9 as\n    /// guarenteed between 0.89 and 0.91, and potentially much better.\n    /// In practice, the actual error appears to be 2-3x better on the\n    /// absolute worst number, and about 10x better on average \n    ///\n    /// quantile_error means that if with quantile(phi) = the element\n    /// at position ceil(phi * N) in the sorted list indexed from\n    /// 1..n, then the position of the returned element is between\n    /// ceil((phi - quantile_error) * N) and ceil((phi +\n    /// quantile_error) * N) in the sorted list.  if phi = 0.5, then\n    /// the value is a median.  If phi == 0, then the quantile the\n    /// element at position 1.  Note that this indexing is different\n    /// than the standard C++ indexing of arrays from 0. Nbound has to\n    /// be larger than N (# elements actually added) for the quantile\n    /// error to be guarenteed.\n    ///\n    /// Here are some statistics on the memory usage of various\n    /// quantile errors and Nbounds.  Approximately increasing the\n    /// nbound by 10x increases the memory usage by 1.15x, but\n    /// decreasing the quantile error by 10x increases the memory usage\n    /// by 7x\n    ///\n    /// \\verbatim\n    /// quantile_error  Nbound  Approx Memory Usage (MiB)\n    ///        0.0001    1e8      2.096 MiB\n    ///        0.0001    1e9      2.825 MiB\n    ///        0.0001    1e10     4.542 MiB\n    ///        0.0001    1e11     5.835 MiB\n    ///        0.0001    1e12     7.022 MiB\n    ///        0.0001    1e13     8.919 MiB\n    /// \t  \t\t\t     \n    ///        0.001     1e8      0.282 MiB\n    ///        0.001     1e9      0.454 MiB\n    ///        0.001     1e10     0.584 MiB\n    ///        0.001     1e11     0.702 MiB\n    ///        0.001     1e12     0.892 MiB\n    ///        0.001     1e13     1.112 MiB\n    /// \t  \t\t\t     \n    ///        0.01      1e8      0.045 MiB\n    ///        0.01      1e9      0.058 MiB\n    ///        0.01      1e10     0.070 MiB\n    ///        0.01      1e11     0.089 MiB\n    ///        0.01      1e12     0.111 MiB\n    ///        0.01      1e13     0.130 MiB\n    /// \\endverbatim\n\n    StatsQuantile(double quantile_error = 0.01, \n\t\t  int64_t Nbound = 1000 * 1000 * 1000, \n\t\t  int print_nrange = 10,\n\t\t  bool lazy = true);\n\n    virtual ~StatsQuantile();\n    virtual void reset();\n    \n    virtual void add(const double value);\n    // add(Stats &) is linear in the number of values added to stat,\n    // and may double the error bounds.\n    virtual void add(const Stats &stat); \n\n    double getQuantile(double quantile, bool allow_invalid_nbound = false) const;\n\n    int getBufferSize() { return buffer_size; }\n    int getNBuffers() { return nbuffers; }\n\n    void dumpState(); // for debugging :(\n#if STATSQUANTILE_TIMING\n    Clock::T accum_gq_all, accum_gq_init, accum_gq_search, accum_gq_inner;\n    int accum_gq_nelem;\n#endif\n    void setNrange(int _print_nrange) { print_nrange = _print_nrange; }\n\n    // nranges is the number of ranges the printed quantiles will divide\n    // [min .. max] into, so to get 10%, 20%, 30%..., nranges = 10\n    void printFile(FILE *out, int nranges=-1); \n    // prints the 90% quantile, 95%, 99%, 99.5%, 99.9%, ...\n    void printTail(FILE *out); \n    virtual void printRome(int depth, std::ostream &out) const;\n\n    /// calls printTextRanges, printTextTail with default arguments\n    virtual void printText(std::ostream &out) const;\n\n    /// nranges specifies how many quantile values to print out.  The\n    /// multiplier allows you to convert the units of the data during\n    /// printing, for example to be able to print data in both MB/s\n    /// and Mbps for network data.\n    void printTextRanges(std::ostream &out, int nranges=-1, double multiplier = 1.0) const;\n\n    /// multiplier is the same as for printTextRanges.\n    void printTextTail(std::ostream &out, double multiplier = 1.0) const;\n\n    /// How much memory will this StatsQuantile use? \n    size_t memoryUsage() const;\n\n    /// this function is only here for some of the regression testing,\n    /// the previous one should probably always be used.  The\n    /// type_disambiguate string is only there because otherwise a call\n    /// to the constructor that specifies (double, int) is ambiguous\n    StatsQuantile(const std::string &type_disambiguate, \n\t\t  int nbuffers, int buffer_size, int print_nrange = 10);\n\nprivate:\n    friend class StatsQuantileTest;\n    // add for only the quantile portion\n    void addQuantile(const double value);\n\n    typedef double *one_buffer;\n    int collapseFindFirstBuffer();\n    // returns total weight across these buffers, also initializes collapse_pos\n    int64_t collapseSortBuffers(int first_buffer);\n    int64_t collapseNextQuantileOffset(int64_t total_weight);\n\n    void collapse();\n\n    double getQuantileByIndex(uint64_t target_index) const;\n    double getQuantileByBinSearchIndex(uint64_t target_index) const;\n\n    const double quantile_error;\n    const int64_t Nbound;\n\n    int buffer_size, nbuffers;\n\n    /// Do initial buffer allocation and field setting. \n    void init(int _nbuffers, int _buffer_size);\n\n    /// Zero-clear all the buffer contents for quantile computation.\n    void init_buffers(); \n\n    // TODO: replace these with vectors, make structure with all buffer\n    // related thing, e.g. weight, level, sorted(probably)\n\n    one_buffer *all_buffers;\n    // int64 is necessary for very big counts, with small buffers\n    // (~100 elements at 0.1 epsilon, ~1000 at 0.01 epsilon), we could\n    // overflow an int32 at 200 billion - 2 trillion added values.\n    int64_t *buffer_weight; \n    int *buffer_level; // int is sufficient, goes up by one each time we collapse\n    int cur_buffer, cur_buffer_pos; // cur_buffer_pos points to the current empty position in cur_buffer\n    bool *buffer_sorted; // makes output faster by eliminating the need for\n    // re-sorting\n\n    // stuff for implementing collapse easier, ought to be able to get away\n    // with putting tmp_buffer on the stack or some-such, but who cares\n    one_buffer tmp_buffer; \n    int *collapse_pos;\n    bool collapse_even_low;\n    int print_nrange;\n\n    bool lazy;\n\n    double collapseVal(int buffer) const {\n\treturn all_buffers[buffer][collapse_pos[buffer]];\n    }\n    struct pairCmp {\n\tinline bool operator()(const std::pair<double, int> &a, \n\t\t\t       const std::pair<double, int> &b) const {\n\t    return a.first >= b.first;\n\t}\n    };\n};\n\n#endif\n", "meta": {"hexsha": "f8cb338f4973b88c7a0f01cd8883a90c4c52f7dd", "size": 7399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Lintel/StatsQuantile.hpp", "max_stars_repo_name": "sbu-fsl/Lintel", "max_stars_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Lintel/StatsQuantile.hpp", "max_issues_repo_name": "sbu-fsl/Lintel", "max_issues_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-05T21:20:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-05T21:56:51.000Z", "max_forks_repo_path": "include/Lintel/StatsQuantile.hpp", "max_forks_repo_name": "sbu-fsl/Lintel", "max_forks_repo_head_hexsha": "b9e603aaec630c8d3fae2f21fc156582d11d84c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.75, "max_line_length": 104, "alphanum_fraction": 0.6538721449, "num_tokens": 2068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.600654221231734}}
{"text": "/* main-lake_DPS.cpp\n   \n  Riddhi Singh, May, 2014\n  The Pennsylvania State University\n  rus197@psu.edu\n\n  Adapted by Tori Ward, July 2014 \n  Cornell University\n  vlw27@cornell.edu\n\n  Adapted by Jonathan Herman and David Hadka, Sept-Dec 2014\n  Cornell University and The Pennsylvania State University\n\n  Adapted by Julianne Quinn, July 2015\n  Cornell University\n  jdq8@cornell.edu\n\n  A multi-objective represention of the lake model from Carpenter et al., 1999\n  This simulation is designed for optimization with Multi-Master Borg.\n\n  Stochasticity is introduced by natural phosphorous inflows. \n  These follow a lognormal distribution with specified mu and sigma.\n\n  Decision variable\n    vars : vector of 100 years of P emissions\n\n  Objectives\n  1: max avg P concentration\n  2: mean economic benefits\n  3: mean inertia\n  4: mean reliability\n\n  Constraints\n  Reliability must be > 85%\n\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <string.h>\n#include <unistd.h>\n#include <sstream>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/math/tools/roots.hpp>\n#include \"./../borg/moeaframework.h\"\n#include \"./../boostutil.h\"\n#include \"./../borg/borgms.h\"\n\n#define nYears 100\n#define nSamples 100\n#define inertia_threshold -0.02\n#define reliability_threshold 0.85\n\ndouble b, q, alpha, delta, pCrit;\n\nint nvars = nYears;\nint nobjs = 4;\nint nconstrs = 1;\ndouble nat_flowmat [10000][nYears]; // create a matrix of [ 10000 x nYears ]\n\nnamespace ublas = boost::numeric::ublas;\nnamespace tools = boost::math::tools;\nusing namespace std;\n\nublas::vector<double> average_annual_P(nYears);\nublas::vector<double> discounted_benefit(nSamples);\nublas::vector<double> yrs_inertia_met(nSamples);\nublas::vector<double> yrs_pCrit_met(nSamples);\n\nublas::vector<double> lake_state(nYears+1);\n\nvoid lake_problem(double* vars, double* objs, double* constrs) \n{\n  // initialize variables\n  zero(average_annual_P);\n  zero(discounted_benefit);\n  zero(yrs_inertia_met);\n  zero(yrs_pCrit_met);\n  zero(lake_state);\n\n  int linesToUse [nSamples];\n  srand (time(NULL)); //gives PRNG a seed based on time\n  for (int s=0; s < nSamples; s++) {\n    //pick a random number based on time\n    //choose 100 of 10,000 available inflow value lines\n    linesToUse[s] = rand() % 10000;\n  }\n\n  // run lake model simulation\n  for (int s = 0; s < nSamples; s++){\n    // randomly generated natural phosphorous inflows\n    double *nat_flow = new double [nYears];\n    int index = linesToUse[s];\n    // get the random natural flow from the States of the world file\n    //each line of SOW file covers 100 days of inflow\n    for (int i=0; i < nYears; i++){\n      nat_flow[i] = nat_flowmat[index][i]; \n    }\n\n    // initialize lake_state\n    lake_state(0) = 0;\n    // find initial policy-derived release\n\n    //implement the lake model from Carpenter et al. 1999\n    for (int i = 0; i < nYears; i++)\n    {\n      // new state: previous state - decay + recycling + pollution\n      lake_state(i+1) = lake_state(i)*(1-b) + pow(lake_state(i),q)/(1+pow(lake_state(i),q)) + vars[i] + nat_flow[i];\n      average_annual_P(i) += lake_state(i+1)/nSamples;\n      discounted_benefit(s) += alpha*vars[i]*pow(delta,i);\n\n      if (i>=1 && (vars[i] - vars[i-1]) > inertia_threshold)\n        yrs_inertia_met(s) += 1;\n\n      if(lake_state(i+1) < pCrit)\n        yrs_pCrit_met(s) += 1;\n    }\n  }\n  \n  objs[0] = -1*vsum(discounted_benefit)/nSamples; // average economic benefit\n  objs[1] = vmax(average_annual_P);; // max average annual P concentration\n  objs[2] = -1*vsum(yrs_inertia_met)/((nYears-1)*nSamples); // average inertia\n  objs[3] = -1*vsum(yrs_pCrit_met)/(nYears*nSamples); // average reliability\n\n  constrs[0] = max(0.0, reliability_threshold - (-1*objs[3]));\n  \n  average_annual_P.clear();\n  discounted_benefit.clear();\n  yrs_inertia_met.clear();\n  yrs_pCrit_met.clear();\n  lake_state.clear();\n\n}\n\ndouble root_function(double x) {\n  return pow(x,q)/(1+pow(x,q)) - b*x;\n}\n\nbool root_termination(double min, double max) {\n  return abs(max - min) <= 0.000001;\n}\n\nint main(int argc, char* argv[]) \n{  \n  // initialize defaults\n  b = 0.42;\n  q = 2;\n  alpha = 0.4;\n  delta = 0.98;\n\n  std::pair<double, double> root = tools::bisect(root_function, 0.01, 1.0, root_termination);\n  pCrit = (root.first + root.second) / 2;\n\n  for (int i=0;i<10000;i++){   //this is 10,000 to match nat_flowmat's size\n    for (int j=0;j<nYears;j++){\n      nat_flowmat[i][j] = 0.0; \n    }\n  }\n  \n  FILE * myfile;\n  myfile = fopen(\"./../SOWs_Type6.txt\",\"r\");\n  \n  int linenum = 0;\n  int maxSize = 5000;\n  \n  if (myfile==NULL){\n    perror(\"Error opening file\");\n  } else {\n    char buffer [maxSize];\n    while (fgets(buffer, maxSize, myfile)!=NULL){\n      linenum++;\n      if (buffer[0]!='#'){\n        char *pEnd;\n        char *testbuffer = new char [maxSize];\n        for (int i=0; i <maxSize; i++){\n          testbuffer[i] = buffer[i];\n        }\n  \n        for (int cols=0; cols < nYears; cols++){\n          nat_flowmat[linenum-1][cols] = strtod(testbuffer, &pEnd);\n          testbuffer  = pEnd; \n        }       \n      }\n    }\n  }\n  \n  fclose(myfile);\n\n  // setting random seed\n  unsigned int seed = atoi(argv[1]);\n  srand(seed);\n  int NFE = atoi(argv[2]);\n\n  // interface with Borg-MS\n  BORG_Algorithm_ms_startup(&argc, &argv);\n  BORG_Algorithm_ms_max_evaluations(NFE);\n  BORG_Algorithm_output_frequency(NFE/200);\n\n  // Define the problem with decisions, objectives, constraints and the evaluation function\n  BORG_Problem problem = BORG_Problem_create(nvars, nobjs, nconstrs, lake_problem);\n\n  // Set all the parameter bounds and epsilons\n  for (int j=0; j < nvars; j++){\n    BORG_Problem_set_bounds(problem, j, 0.01, 0.1);\n  }\n\n  BORG_Problem_set_epsilon(problem, 0, 0.01); // average economic benefit\n  BORG_Problem_set_epsilon(problem, 1, 0.01); // max average annual P concentration\n  BORG_Problem_set_epsilon(problem, 2, 0.0001); // average inertia\n  BORG_Problem_set_epsilon(problem, 3, 0.0001); // average reliability\n\n  //This is set up to run only one seed at a time\n  char outputFilename[256];\n  char runtime[256];\n  FILE* outputFile = NULL;\n  sprintf(outputFilename, \"./sets/LakeIT_S%d.set\", seed);\n  sprintf(runtime, \"./runtime/LakeIT_S%d.runtime\", seed);\n\n  BORG_Algorithm_output_runtime(runtime);\n\n  BORG_Random_seed(seed);\n  BORG_Archive result = BORG_Algorithm_ms_run(problem); // this actually runs the optimization\n\n  //If this is the master node, print out the final archive\n  if (result != NULL){\n    outputFile = fopen(outputFilename, \"w\");\n    if(!outputFile){\n      BORG_Debug(\"Unable to open final output file\\n\");\n    }\n    BORG_Archive_print(result, outputFile);\n    BORG_Archive_destroy(result);\n    fclose(outputFile);\n  }\n\n  BORG_Algorithm_ms_shutdown();\n  BORG_Problem_destroy(problem);\n\n  return EXIT_SUCCESS;\n\n}\n", "meta": {"hexsha": "0f0c6f0bd903789049cfd76ea5733c4add75e0fd", "size": 6910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Optimization/Intertemporal/main-lake-IT.cpp", "max_stars_repo_name": "federatedcloud/Lake_Problem_DPS", "max_stars_repo_head_hexsha": "07600c49ed543165ccdc642c1097b3bed87c28f0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Optimization/Intertemporal/main-lake-IT.cpp", "max_issues_repo_name": "federatedcloud/Lake_Problem_DPS", "max_issues_repo_head_hexsha": "07600c49ed543165ccdc642c1097b3bed87c28f0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-03T21:12:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-08T21:32:43.000Z", "max_forks_repo_path": "Optimization/Intertemporal/main-lake-IT.cpp", "max_forks_repo_name": "federatedcloud/Lake_Problem_DPS", "max_forks_repo_head_hexsha": "07600c49ed543165ccdc642c1097b3bed87c28f0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-29T17:30:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-30T22:01:49.000Z", "avg_line_length": 28.2040816327, "max_line_length": 116, "alphanum_fraction": 0.6784370478, "num_tokens": 2007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.6723317057447908, "lm_q1q2_score": 0.6006002290916459}}
{"text": "#include <catch.hpp>\n#include <complex>\n#include <cmath>\n#include <functional>\n#include <vector>\n#include <armadillo>\n#include \"../util/cubatureintegration.h\"\n#include \"helpers.h\"\n\nnamespace CubatureIntegrationTest {\n  double tangent(std::vector<double> x) {\n    return std::tan(x[0]);\n  }\n\n  struct TestFunctor {\n    double operator()(std::vector<double> x) {\n      return std::log(x[0]);\n    }\n  };\n\n  template <class IntegrationProvider>\n  class IntegrationTestClass {\n    const double pi = arma::datum::pi;\n\n    public:\n      IntegrationTestClass() {}\n      void testMethod() {\n        SECTION(\"Check if it implements IntegrationInterface\") {\n          REQUIRE(std::is_base_of<POWannier::IntegrationInterface, IntegrationProvider>::value == true);\n        }\n\n        SECTION(\"Calculate simple 1D integral using lambda expression\") {\n          std::vector<double> xmin = {0};\n          std::vector<double> xmax = {1};\n          double result = IntegrationProvider::integrate(\n              [=] (std::vector<double> x) {\n                  auto value = std::sin(2*pi*x[0]) * std::sin(2*pi*x[0]);\n                  return value;\n              }, xmin, xmax);\n\n          REQUIRE(result == Approx(0.5));\n        }\n\n        SECTION(\"Calculate simple 2d integral using lambda expression\") {\n          std::vector<double> xmin = {0, 0};\n          std::vector<double> xmax = {1, 1};\n          double result = IntegrationProvider::integrate(\n              [=] (std::vector<double> x) {\n                  auto value = std::pow(std::sin(2*pi*x[0]), 2) *\n                      std::pow(std::sin(2*pi*x[1]), 2);\n                  return value;\n               }, xmin, xmax);\n\n          REQUIRE(result == Approx(0.25));\n        }\n\n\n        SECTION(\"Calculate integral using a function in a global namespace\") {\n          std::vector<double> xmin = {0};\n          std::vector<double> xmax = {pi/4};\n          double result = IntegrationProvider::integrate(\n              &CubatureIntegrationTest::tangent, xmin, xmax);\n\n          REQUIRE(result == Approx(0.5 * std::log(2)));\n        }\n\n        SECTION(\"Calculate integral using a functor\") {\n          std::vector<double> xmin = {1};\n          std::vector<double> xmax = {std::exp(1.0)};\n          CubatureIntegrationTest::TestFunctor testfunctor;\n          double result = IntegrationProvider::integrate(\n              std::ref(testfunctor), xmin, xmax);\n\n          REQUIRE(result == Approx(1));\n        }\n\n        SECTION(\"Calculate two-dimensional integral\") {\n          std::vector<double> xmin = {0, 0};\n          std::vector<double> xmax = {1, 1};\n          double result = IntegrationProvider::integrate(\n              [=] (std::vector<double> x) {\n                  auto value = std::sin(pi * (x[0] + x[1])) *\n                    std::sin(pi * (x[0] - x[1])) *\n                    std::cos(2 * pi * x[0]);\n                  return value;\n              }, xmin, xmax);\n          REQUIRE(result == Approx(-0.25));\n        }\n\n     SECTION(\"Calculate complex integral\") {\n          std::vector<double> xmin = {0};\n          std::vector<double> xmax = {1};\n          std::complex<double> result = IntegrationProvider::integrate(\n              [=] (std::vector<double> x) {\n                  auto value = std::sin(2 * pi * x[0]) *\n                  std::exp(std::complex<double>(0, 2.0 * pi * x[0]));\n                  return value;\n              }, xmin, xmax);\n          REQUIRE(std::real(result) == Approx(0).margin(1e-15));\n          REQUIRE(std::imag(result) == Approx(0.5));\n        }\n\n     SECTION(\"Calculate complex two-dimensional integral\") {\n          arma::rowvec xmin(2, arma::fill::zeros);\n          arma::rowvec xmax(2, arma::fill::ones);\n          std::complex<double> result = IntegrationProvider::integrate(\n              [=] (arma::rowvec r) {\n                  auto x = 2 * r[0];\n                  auto y = -2 * r[0] + std::sqrt(2) * r[1];\n                  auto an = -2 * r[0];\n                  auto value = (std::pow(std::sin(pi * (x + y) / std::sqrt(2)), 2) +\n                        std::pow(std::sin(0.5 * pi * x), 2) +\n                        std::pow(std::sin(pi * (x + 0.25)), 2) )* \n                        std::exp(std::complex<double>(0, 2 * pi * an ));\n                  return value;\n              }, xmin, xmax);\n          REQUIRE(std::real(result) == Approx(0).margin(1e-15));\n          REQUIRE(std::imag(result) == Approx(-0.25));\n        }\n      }\n\n  };\n\n}\n\n\nMETHOD_AS_TEST_CASE(CubatureIntegrationTest::IntegrationTestClass<POWannier::CubatureIntegration>::testMethod,\n    \"Calculating integrals using cubature\", \"[integral, cubature]\");\n", "meta": {"hexsha": "1f9c4009d6a29d21633f0899b0d08374264df13a", "size": 4617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test_integration.cpp", "max_stars_repo_name": "krzyz/powannier", "max_stars_repo_head_hexsha": "231c851ca71f8ff5a4d2796a1a9022e7e09cdd25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/test_integration.cpp", "max_issues_repo_name": "krzyz/powannier", "max_issues_repo_head_hexsha": "231c851ca71f8ff5a4d2796a1a9022e7e09cdd25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/test_integration.cpp", "max_forks_repo_name": "krzyz/powannier", "max_forks_repo_head_hexsha": "231c851ca71f8ff5a4d2796a1a9022e7e09cdd25", "max_forks_repo_licenses": ["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.7906976744, "max_line_length": 110, "alphanum_fraction": 0.5215507906, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.6005707319358405}}
{"text": "\n#include <iostream>\n#include <Eigen/Dense>\n#include <manifold/SO3.h>\n#include <manifold/gradientDescentSO3.h>\n\nclass GDSO3vMF : public GDSO3<double> {\n public:\n  GDSO3vMF(const SO3d& Rmu) : Rmu_(Rmu) \n  {};\n\n  virtual void ComputeJacobian(const SO3d& theta, Eigen::Matrix<double,3,1>* J, double* f) {\n    SO3d R = theta;\n    if (J) {\n      Eigen::Matrix3d JMat = -0.5*((R.Inverse() + Rmu_).matrix() \n          - (Rmu_.Inverse() + R).matrix()); \n      *J = SO3d::vee(JMat);\n//      std::cout << R << std::endl;\n//      std::cout << Rmu_ << std::endl;\n//      std::cout << JMat << std::endl;\n//      std::cout << J->transpose() << std::endl;\n    }\n    if (f) {\n      *f = -(Rmu_.Inverse() + R).matrix().trace();\n    }\n  };\n protected:\n  SO3d Rmu_;\n};\n\nint main (int argc, char** argv) {\n  \n  SO3d R;\n  std::cout << R << std::endl;\n\n  double theta = 15.*M_PI/180.;\n  Eigen::Matrix3d Rmu_;\n  Rmu_ << 1, 0, 0,\n         0, cos(theta), sin(theta),\n         0, -sin(theta), cos(theta);\n  SO3d Rmu(Rmu_);\n  \n  std::cout << Rmu << std::endl;\n  std::cout << R+Rmu << std::endl;\n  std::cout << R << std::endl;\n  std::cout << Rmu+R << std::endl;\n\n  std::cout << R-Rmu << std::endl;\n\n  Eigen::Vector3d w = R-Rmu;\n  std::cout << Rmu.Exp(w) << std::endl;\n\n  std::cout << Rmu-R << std::endl;\n\n  GDSO3vMF gd(Rmu);\n  gd.Compute(R, 1e-8, 100);\n  R = gd.GetMinimum();\n  \n//  double delta = 0.1;\n//  double f_prev = 1e99;\n//  double f = (Rmu.Inverse() + R).matrix().trace();\n//  std::cout << \"f=\" << f << std::endl;\n//  for (uint32_t it=0; it<100; ++it) {\n//    Eigen::Matrix3d J = -0.5*((R.Inverse() + Rmu).matrix() - (Rmu.Inverse() + R).matrix()); \n//    Eigen::Vector3d Jw = SO3d::vee(J);\n////    R = R.Exp(-delta*Jw);\n//    R += -delta*Jw;\n////    std::cout << Jw << std::endl;\n//    f_prev = f;\n//    f = (Rmu.Inverse() + R).matrix().trace();\n////    if ((f_prev - f)/f < 1e-3) \n////      break;\n//    std::cout << \"f=\" << f << \" df/f=\" << (f_prev - f)/f \n//      << std::endl;\n////      << std::endl << R << std::endl;\n//  }\n  std::cout << std::endl << Rmu << std::endl;\n  std::cout << std::endl << R << std::endl;\n}\n", "meta": {"hexsha": "3819cde22c7c9a36b634e73227846ca2179d847d", "size": 2102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/SO3GD.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "test/SO3GD.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "test/SO3GD.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 26.275, "max_line_length": 94, "alphanum_fraction": 0.5090390105, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.6005707165158339}}
{"text": "#include <Eigen/Dense>\n\n#include <gpd/conv_layer.h>\n\n\nint main(int argc, char* argv[])\n{\n  // Create example input, weights, bias.\n  Eigen::MatrixXf X(5,5);\n  Eigen::MatrixXf W(3,3);\n  Eigen::VectorXf b = Eigen::VectorXf::Zero(1);\n  X <<  1, 1, 1, 0, 0,\n            0, 1, 1, 1, 0,\n            0, 0, 1, 1, 1,\n            0, 0, 1, 1, 0,\n            0, 1, 1, 0, 0;\n  W <<      1, 0, 1,\n            0, 1, 0,\n            1, 0, 1;\n\n  std::vector<float> w_vec;\n  Eigen::Matrix<float,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> W_rowmajor(W);\n  Eigen::Map<Eigen::VectorXf> w(W_rowmajor.data(), W_rowmajor.size());\n  w_vec.assign(w.data(), w.data() + w.size());\n\n  std::vector<float> b_vec;\n  b_vec.assign(b.data(), b.data() + b.size());\n\n  // Create a convolutional layer and execute a forward pass.\n  ConvLayer conv1(5, 5, 1, 1, 3, 1, 0);\n  conv1.setWeightsAndBiases(w_vec, b_vec);\n  Eigen::Matrix<float,Eigen::Dynamic,Eigen::Dynamic,Eigen::RowMajor> X_row_major(X);\n  Eigen::Map<Eigen::VectorXf> v1(X_row_major.data(), X_row_major.size());\n  std::vector<float> vec1;\n  vec1.assign(v1.data(), v1.data() + v1.size());\n  Eigen::MatrixXf Y = conv1.forward(vec1);\n\n  std::cout << \"Y: \" << Y.rows() << \" x \" << Y.cols() << std::endl;\n  std::cout << Y << std::endl;\n  std::cout << std::endl;\n}\n", "meta": {"hexsha": "90162cd181ecc3010915b73701308627909b5ca0", "size": 1284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpd/src/tests/test_conv_layer.cpp", "max_stars_repo_name": "iiisrobotics/bulldog_ws", "max_stars_repo_head_hexsha": "5bf3c48fd9c51fdee7c36705ce99e59e4abd96ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gpd/src/tests/test_conv_layer.cpp", "max_issues_repo_name": "iiisrobotics/bulldog_ws", "max_issues_repo_head_hexsha": "5bf3c48fd9c51fdee7c36705ce99e59e4abd96ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gpd/src/tests/test_conv_layer.cpp", "max_forks_repo_name": "iiisrobotics/bulldog_ws", "max_forks_repo_head_hexsha": "5bf3c48fd9c51fdee7c36705ce99e59e4abd96ed", "max_forks_repo_licenses": ["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.5714285714, "max_line_length": 84, "alphanum_fraction": 0.5794392523, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.6005707093906422}}
{"text": "#define BOOST_TEST_MODULE \"test_clementi_dihedral_potential\"\n\n#ifdef BOOST_TEST_DYN_LINK\n#include <boost/test/unit_test.hpp>\n#else\n#include <boost/test/included/unit_test.hpp>\n#endif\n\n#include <mjolnir/forcefield/local/ClementiDihedralPotential.hpp>\n#include <mjolnir/math/constants.hpp>\n\nBOOST_AUTO_TEST_CASE(ClementiDihedral_double)\n{\n    using real_type = double;\n    constexpr std::size_t N  = 1000;\n    constexpr real_type   h  = 1e-6;\n    constexpr real_type   pi = mjolnir::math::constants<real_type>::pi();\n\n    const real_type k1 = 1.0;\n    const real_type k3 = 2.0;\n    const real_type r0 = pi * 2. / 3.;\n\n    mjolnir::ClementiDihedralPotential<real_type> c(k1, k3, r0);\n\n    const real_type x_min = -pi;\n    const real_type x_max =  pi;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + dx * i;\n        const real_type x_up = (x+h < 2. * pi) ? x+h : x+h - 2 * pi;\n        const real_type x_bt = (x-h > 0)       ? x-h : x-h + 2 * pi;\n        const real_type pot1 = c.potential(x_up);\n        const real_type pot2 = c.potential(x_bt);\n        const real_type dpot = (pot1 - pot2) / (2 * h);\n        const real_type deri = c.derivative(x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n        // periodicity\n        BOOST_TEST(c.potential(x)  == c.potential (x + 2 * pi),\n                   boost::test_tools::tolerance(1e-8));\n        BOOST_TEST(c.derivative(x) == c.derivative(x + 2 * pi),\n                   boost::test_tools::tolerance(1e-8));\n    }\n}\n\nBOOST_AUTO_TEST_CASE(ClementiDihedral_float)\n{\n    using real_type = float;\n    constexpr static std::size_t N  = 100;\n    constexpr static real_type   h  = 1e-2f;\n    constexpr static real_type   pi = mjolnir::math::constants<real_type>::pi();\n\n    const real_type k1 = 1.0f;\n    const real_type k3 = 2.0f;\n    const real_type r0 = pi * 2. / 3.;\n\n    mjolnir::ClementiDihedralPotential<real_type> c(k1, k3, r0);\n\n    const real_type x_min = 0.f;\n    const real_type x_max = 2.f * pi;\n    const real_type dx = (x_max - x_min) / N;\n\n    for(std::size_t i=0; i<N; ++i)\n    {\n        const real_type x    = x_min + dx * i;\n        const real_type x_up = (x+h < 2.0f * pi) ? x+h : x+h - 2 * pi;\n        const real_type x_bt = (x-h > 0.0f)      ? x-h : x-h + 2 * pi;\n        const real_type pot1 = c.potential(x_up);\n        const real_type pot2 = c.potential(x_bt);\n        const real_type dpot = (pot1 - pot2) / (2.0f * h);\n        const real_type deri = c.derivative(x);\n\n        BOOST_TEST(dpot == deri, boost::test_tools::tolerance(h));\n        // periodicity\n        BOOST_TEST(c.potential(x)  == c.potential (x + 2 * pi),\n                   boost::test_tools::tolerance(h));\n        BOOST_TEST(c.derivative(x) == c.derivative(x + 2 * pi),\n                   boost::test_tools::tolerance(h));\n   }\n}\n\n", "meta": {"hexsha": "4061f4348ffd84d5a43e5a384a8adadf7513121d", "size": 2867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/core/test_clementi_dihedral_potential.cpp", "max_stars_repo_name": "yutakasi634/Mjolnir", "max_stars_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/core/test_clementi_dihedral_potential.cpp", "max_issues_repo_name": "yutakasi634/Mjolnir", "max_issues_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-07T11:41:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-08T10:01:38.000Z", "max_forks_repo_path": "test/core/test_clementi_dihedral_potential.cpp", "max_forks_repo_name": "yutakasi634/Mjolnir", "max_forks_repo_head_hexsha": "ab7a29a47f994111e8b889311c44487463f02116", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.130952381, "max_line_length": 80, "alphanum_fraction": 0.6016742239, "num_tokens": 920, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6005453530981347}}
{"text": "#include <boost/dynamic_bitset.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include \"encode.hpp\"\n\nusing namespace std;\nusing namespace boost::numeric;\nusing boost::dynamic_bitset;\n\n\nconst auto generator_mat = [] {\n    ublas::matrix<bool> generator_m(7, 4);\n    vector<bool> generator_init = {\n        1, 1, 0, 1,\n        1, 0, 1, 1,\n        1, 0, 0, 0,\n        0, 1, 1, 1,\n        0, 1, 0, 0,\n        0, 0, 1, 0,\n        0, 0, 0, 1\n    };\n\n    copy(generator_init.begin(),\n         generator_init.end(),\n         generator_m.data().begin()\n    );\n\n    return generator_m;\n}();\n\n\nvector<uint8_t> encode(const vector<uint8_t> &bytes) {\n    vector<bool> plain;\n    plain.reserve(bytes.size() * 8);\n\n    for (auto && c : bytes) {\n        for (auto i = 0u; i < 8u; ++i) {\n            plain.push_back(c & (1 << i));\n        }\n    }\n\n    dynamic_bitset<uint8_t> result;\n    for (auto it = plain.begin(); it != plain.end(); advance(it, 4)) {\n        ublas::matrix<bool> value_mat(4, 1);\n        copy(it, it+4, value_mat.data().begin());\n\n        auto prod = ublas::prod(generator_mat, value_mat);\n\n        for_each(prod.begin1(), prod.end1(), [&result] (auto v) {\n            result.push_back(v % 2);\n        });\n    }\n\n    result.push_back(1);\n    while (result.size() % 8 != 0) {\n        result.push_back(0);\n    }\n\n    vector<uint8_t> blocks(result.num_blocks());\n    to_block_range(result, blocks.begin());\n\n    return blocks;\n}", "meta": {"hexsha": "95dc8d0a92a0a7eab11d6d8230e71e8b009fef21", "size": 1428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "encode.cpp", "max_stars_repo_name": "Learko/Hamming", "max_stars_repo_head_hexsha": "2241feae7c25f8d4c3475c8b3d6080621ac6106f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "encode.cpp", "max_issues_repo_name": "Learko/Hamming", "max_issues_repo_head_hexsha": "2241feae7c25f8d4c3475c8b3d6080621ac6106f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "encode.cpp", "max_forks_repo_name": "Learko/Hamming", "max_forks_repo_head_hexsha": "2241feae7c25f8d4c3475c8b3d6080621ac6106f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6666666667, "max_line_length": 70, "alphanum_fraction": 0.5504201681, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.6926419704455588, "lm_q1q2_score": 0.6005453523566437}}
{"text": "//\n// Created by keszocze on 15.10.18.\n//\n\n#pragma once\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <cudd/cplusplus/cuddObj.hh>\n#include <vector>\n\n#include \"number_representation.hpp\"\n\nnamespace abo::error_metrics {\n\n/**\n * @brief Computes the maximal value of a function represented by a vector of BDDs\n *\n * The function is assumed to return an natural number\n *\n * @param mgr\n * @param fun The function given by a vector of BDDs\n */\nboost::multiprecision::uint256_t get_max_value(const Cudd& mgr,\n                                               const std::vector<BDD>& fun);\n\n/**\n * @brief Computes the maximum absolute difference between the f and f_hat for any input\n * The computation is performed symbolically using BDDs\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param num_rep The number representation for f and f_hat\n * @return The maximum absolute difference\n */\nboost::multiprecision::uint256_t\nworst_case_error(const Cudd& mgr,\n                 const std::vector<BDD>& f,\n                 const std::vector<BDD>& f_hat,\n                 const abo::util::NumberRepresentation num_rep\n                    = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief Computes the maximum absolute difference between the f and f_hat for any input\n * divided by 2^n - 1 to normalize it to the range [0, 1] regardless of the function size (with n =\n * f.size()) This is mainly intended to be a helper function to make the use of the worst case error\n * easier\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param num_rep The number representation for f and f_hat\n * @return The maximum absolute difference normalized to [0, 1]\n */\ndouble worst_case_error_percent(const Cudd& mgr, const std::vector<BDD>& f,\n                                const std::vector<BDD>& f_hat,\n                                const abo::util::NumberRepresentation num_rep\n                                    = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief Computes the maximum absolute difference between the f and f_hat for any input\n * The computation is performed using BDDs and will be typically slow compared to the BDD based\n * variant\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param num_rep The number representation for f and f_hat\n * @return The maximum absolute difference\n */\nboost::multiprecision::uint256_t\nworst_case_error_add(const Cudd& mgr,\n                     const std::vector<BDD>& f,\n                     const std::vector<BDD>& f_hat,\n                     const abo::util::NumberRepresentation num_rep\n                        = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief approximate_worst_case_error\n *  Calculates the worst case error approximately, to a given relative error.\n *  The time and memory this function uses scales exponentially with the desired precision (n) (in\n * the worst case). With m being the input size (f, f_hat), in the worst case, it lies in O(m ^ n).\n * @param mgr\n * @param f\n * @param f_hat\n * @param n The precision to calculate in number of bits, for more details see the return value. It\n * must be greater than zero\n * @param num_rep The number representation for f and f_hat\n * @return The approximated worst case error. It is an upper bound and therefore guaranteed to be\n * larger than the actual error. Let wc be the correct worst case error and x be the result of this\n * function. Then it holds that wc <= x <= wc * (1 + 1 / (2 ^ (n + 1) - 1)))\n */\nboost::multiprecision::uint256_t\napproximate_worst_case_error(const Cudd& mgr, const std::vector<BDD>& f,\n                             const std::vector<BDD>& f_hat, int n,\n                             const abo::util::NumberRepresentation num_rep\n                                = abo::util::NumberRepresentation::BaseTwo);\n\n} // namespace abo::error_metrics\n", "meta": {"hexsha": "46ea73ab14273d420b8c61fda6c6f444f329d55b", "size": 4177, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/worst_case_error.hpp", "max_stars_repo_name": "keszocze/abo", "max_stars_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/error_metrics/worst_case_error.hpp", "max_issues_repo_name": "keszocze/abo", "max_issues_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/error_metrics/worst_case_error.hpp", "max_forks_repo_name": "keszocze/abo", "max_forks_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T14:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T14:50:31.000Z", "avg_line_length": 42.6224489796, "max_line_length": 100, "alphanum_fraction": 0.6779985636, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.600529713387723}}
{"text": "/**\n * test ode calculation\n * @author Tobias Weber <tweber@ill.fr>\n * @date 28-oct-20\n * @license GPLv3, see 'LICENSE' file\n * @desc forked from https://github.com/t-weber/misc/blob/master/boost/ode3.cpp\n *\n * g++ -std=c++20 -DUSE_LAPACK -I.. -I/usr/include/lapacke -Iext/lapacke/include -Lext/lapacke/lib -o ode ode.cpp -llapacke\n *\n * ----------------------------------------------------------------------------\n * tlibs\n * Copyright (C) 2017-2021  Tobias WEBER (Institut Laue-Langevin (ILL),\n *                          Grenoble, France).\n * Copyright (C) 2015-2017  Tobias WEBER (Technische Universitaet Muenchen\n *                          (TUM), Garching, Germany).\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, version 3 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n * ----------------------------------------------------------------------------\n */\n\n#define BOOST_TEST_MODULE Ode Test\n#include <boost/test/included/unit_test.hpp>\nnamespace test = boost::unit_test;\nnamespace testtools = boost::test_tools;\n\n#include <iostream>\n#include <vector>\n\n#include \"libs/maths.h\"\nusing namespace tl2_ops;\n\n#define DEBUG_OUTPUT\n\n\n// ----------------------------------------------------------------------------\n// numeric integration\n#include <boost/numeric/odeint.hpp>\nnamespace odeint = boost::numeric::odeint;\n\n// mark custom vector as resizeable\ntemplate<> struct odeint::is_resizeable<tl2::vec<float, std::vector>>\n{\n\tusing type = typename boost::true_type;\n\tstatic const bool value = type::value;\n};\ntemplate<> struct odeint::is_resizeable<tl2::vec<double, std::vector>>\n{\n\tusing type = typename boost::true_type;\n\tstatic const bool value = type::value;\n};\n\ntemplate<class t_mat, class t_vec, class t_val=typename t_vec::value_type>\nt_vec odesys(const t_mat& C, const t_vec& y0, t_val x_start, t_val x_end, t_val x_step = 0.01)\n{\n\tt_vec y = y0;\n\todeint::integrate_adaptive(odeint::runge_kutta4<t_vec>{},\n\t\t[&C](const t_vec& y, t_vec& y_diff, t_val x) -> void\n\t\t{\n\t\t\ty_diff = C*y;\n\t\t}, y, x_start, x_end, x_step);\n\n\treturn y;\n}\n// ----------------------------------------------------------------------------\n\n\nusing t_types = std::tuple<double, float>;\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(test_ode, t_real, t_types)\n{\n\tconst t_real eps = 1e-3;\n\n\tusing t_cplx = std::complex<t_real>;\n\tusing t_vec_cplx = tl2::vec<t_cplx, std::vector>;\n\tusing t_mat_cplx = tl2::mat<t_cplx, std::vector>;\n\tusing t_vec = tl2::vec<t_real, std::vector>;\n\tusing t_mat = tl2::mat<t_real, std::vector>;\n\n\n\tt_mat_cplx coeff = tl2::create<t_mat_cplx>({\n\t\t0., 1.,\n\t\t1., 1. });\n\n\tt_vec_cplx f0 = tl2::create<t_vec_cplx>({1., 1.});\n\tt_cplx x0 = 0.;\n\tt_cplx n0 = 0.;\n\n\tconst auto [coeff_re, coeff_im] = tl2::split_cplx<t_mat_cplx, t_mat>(coeff);\n\tconst auto [f0_re, f0_im] = tl2::split_cplx<t_vec_cplx, t_vec>(f0);\n\n\n#ifdef DEBUG_OUTPUT\n\tstd::cout << \"coeff = \" << coeff << std::endl;\n\tstd::cout << \"x0 = \" << x0 << \", f0 = \" << f0 << std::endl;\n\tstd::cout << std::endl;\n#endif\n\n\tfor(t_cplx x=0; x.real()<10; x+=1)\n\t{\n\t\tauto [ok, f] = tl2_la::odesys_const<t_mat_cplx, t_vec_cplx, t_cplx>(coeff, x, x0, f0);\n\t\tBOOST_TEST(ok);\n\n\t\t// compare with numerical result\n\t\tt_vec num_val = odesys<t_mat, t_vec>(coeff_re, f0_re, t_real{0.}, x.real(), t_real{0.01});\n\t\tBOOST_TEST(f[0].real() == num_val[0], testtools::tolerance(eps));\n\t\tBOOST_TEST(f[1].real() == num_val[1], testtools::tolerance(eps));\n\t\tBOOST_TEST(f[0].imag() == t_real{0}, testtools::tolerance(eps));\n\t\tBOOST_TEST(f[1].imag() == t_real{0}, testtools::tolerance(eps));\n\n#ifdef DEBUG_OUTPUT\n\t\tstd::cout << \"x = \" << x << std::endl;\n\t\tstd::cout << \"ok = \" << std::boolalpha << ok << std::endl;\n\n\t\tfor(std::size_t i=0; i<f.size(); ++i)\n\t\t\tstd::cout << \"f_\" << i << \" = \" << f[i] << std::endl;\n\t\tstd::cout << std::endl;\n#endif\n\t}\n\n\n\tstd::size_t idx=0;\n\tconst t_cplx fibo[] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};\n\tfor(t_cplx n=0; n.real()<10; n+=1)\n\t{\n\t\tauto [ok, f] = tl2_la::diffsys_const<t_mat_cplx, t_vec_cplx, t_cplx>(coeff, n, n0, f0);\n\t\tBOOST_TEST(ok);\n\t\tBOOST_TEST(tl2::equals(f[0], fibo[idx], eps));\n\t\tBOOST_TEST(tl2::equals(f[1], fibo[idx+1], eps));\n\n#ifdef DEBUG_OUTPUT\n\t\tstd::cout << \"n = \" << n << std::endl;\n\t\tstd::cout << \"ok = \" << std::boolalpha << ok << std::endl;\n\n\t\tfor(std::size_t i=0; i<f.size(); ++i)\n\t\t\tstd::cout << \"f_\" << i << \" = \" << f[i] << std::endl;\n\t\tstd::cout << std::endl;\n#endif\n\t\t++idx;\n\t}\n}\n", "meta": {"hexsha": "7a03f85c57e0e7f668ba17c2baa72473ac506b01", "size": 4845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unittests/ode.cpp", "max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unittests/ode.cpp", "max_issues_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unittests/ode.cpp", "max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2", "max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z", "avg_line_length": 32.0860927152, "max_line_length": 123, "alphanum_fraction": 0.613003096, "num_tokens": 1489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6005296973244751}}
{"text": "//\n// Created by krab1k on 31/10/18.\n//\n\n#include <vector>\n#include <cmath>\n#include <Eigen/LU>\n\n#include \"denr.h\"\n#include \"../structures/molecule.h\"\n#include \"../parameters.h\"\n\nCHARGEFW2_METHOD(DENR)\n\n\nstd::vector<double> DENR::calculate_charges(const Molecule &molecule) const {\n\n    size_t n = molecule.atoms().size();\n\n    Eigen::MatrixXd eta = Eigen::MatrixXd::Zero(n, n);\n    Eigen::MatrixXd L = Eigen::MatrixXd::Zero(n, n);\n    Eigen::VectorXd chi = Eigen::VectorXd::Zero(n);\n    Eigen::VectorXd q = Eigen::VectorXd::Zero(n);\n\n    for (size_t i = 0; i < n; i++) {\n        auto &atom_i = molecule.atoms()[i];\n        chi(i) = parameters_->atom()->parameter(atom::electronegativity)(atom_i);\n        eta(i, i) = parameters_->atom()->parameter(atom::hardness)(atom_i);\n    }\n\n    for (const auto &bond: molecule.bonds()) {\n        auto i1 = bond.first().index();\n        auto i2 = bond.second().index();\n        L(i1, i1) += 1;\n        L(i2, i2) += 1;\n        L(i1, i2) -= 1;\n        L(i2, i1) -= 1;\n    }\n\n    double step = parameters_->common()->parameter(common::step);\n\n    Eigen::PartialPivLU<Eigen::MatrixXd> x = (Eigen::MatrixXd::Identity(n, n) + step * L * eta).partialPivLu();\n    Eigen::VectorXd tmp = step * L * chi;\n    for (int i = 0; i < parameters_->common()->parameter(common::iterations); i++) {\n        q = x.solve(q - tmp);\n    }\n\n    return std::vector<double>(q.data(), q.data() + q.size());\n}\n", "meta": {"hexsha": "db64ac1d0dc6209c14231441f081696e7dfbf8e5", "size": 1420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/methods/denr.cpp", "max_stars_repo_name": "danny305/ChargeFW2", "max_stars_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T15:14:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:38:09.000Z", "max_issues_repo_path": "src/methods/denr.cpp", "max_issues_repo_name": "danny305/ChargeFW2", "max_issues_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-03-04T21:38:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T07:11:19.000Z", "max_forks_repo_path": "src/methods/denr.cpp", "max_forks_repo_name": "danny305/ChargeFW2", "max_forks_repo_head_hexsha": "c68fd06b9af244e5d8ed9172de17748e587bf46e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-05T00:42:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-01T05:47:39.000Z", "avg_line_length": 28.4, "max_line_length": 111, "alphanum_fraction": 0.588028169, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.6004506629824707}}
{"text": "#pragma once\n#include <boost/serialization/access.hpp>\n\n#include \"Node.hxx\"\n\nclass Scalar : public Node {\n private:\n  std::map<size_t, mpq_class> map;\n\n  friend class boost::serialization::access;\n\n public:\n  Scalar () = default;\n\n  Scalar (size_t variable, mpq_class const & fraction);\n\n  Scalar (Scalar const & other);\n\n  char order () const override;\n  std::map<size_t, mpq_class> const & get() const;\n  std::string print () const override;\n  std::string printMaple () const override;\n\n  int applyTensorSymmetries (int parity) override;\n  void exchangeTensorIndices (std::map<char, char> const & exchange_map);\n\n  void multiply (mpq_class const & factor) override;\n\n  std::unique_ptr<Node> clone () const override;\n\n  std::set<size_t> getVariableSet () const override;\n  std::map<size_t, mpq_class> const * getCoefficientMap () const override;\n\n  void shiftVariables (int i);\n\n  void addOther(Scalar const * other);\n\n  void removeZeros ();\n\n  bool lessThan (Node const * other) const override;\n  bool equals (Node const * other) const override;\n  bool isZero () const;\n\n  void substituteVariables (std::map<size_t, size_t> const & subs_map) override;\n  void removeVariables (std::set<size_t> const & variables) override;\n\n  template<class Archive>\n  void serialize (Archive & ar, unsigned int const version);\n\n  ~Scalar() = default;\n};\n", "meta": {"hexsha": "38ce589902cb9e051514cc06edd1d982ef02e35d", "size": 1339, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/Scalar.hxx", "max_stars_repo_name": "nilsalex/tensor-trees", "max_stars_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Scalar.hxx", "max_issues_repo_name": "nilsalex/tensor-trees", "max_issues_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Scalar.hxx", "max_forks_repo_name": "nilsalex/tensor-trees", "max_forks_repo_head_hexsha": "48b5b4f6932705bac7160bb3379f6066222f9b70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.75, "max_line_length": 80, "alphanum_fraction": 0.716206124, "num_tokens": 331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.6688802537704063, "lm_q1q2_score": 0.6004506621161598}}
{"text": "#include <limits>\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n// BGL includes\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/cycle_canceling.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\n// Graph Type with nested interior edge properties for Cost Flow Algorithms\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n    boost::property<boost::edge_capacity_t, long,\n        boost::property<boost::edge_residual_capacity_t, long,\n            boost::property<boost::edge_reverse_t, traits::edge_descriptor,\n                boost::property <boost::edge_weight_t, long> > > > > graph; // new! weightmap corresponds to costs\n\ntypedef boost::graph_traits<graph>::edge_descriptor             edge_desc;\ntypedef boost::graph_traits<graph>::out_edge_iterator           out_edge_it; // Iterator\n\n// Custom edge adder class\nclass edge_adder {\n graph &G;\n\n public:\n  explicit edge_adder(graph &G) : G(G) {}\n  void add_edge(int from, int to, long capacity, long cost) {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    auto w_map = boost::get(boost::edge_weight, G); // new!\n    const edge_desc e = boost::add_edge(from, to, G).first;\n    const edge_desc rev_e = boost::add_edge(to, from, G).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0; // reverse edge has no capacity!\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n    w_map[e] = cost;   // new assign cost\n    w_map[rev_e] = -cost;   // new negative cost\n  }\n};\n\nstruct edge {\n    int u;\n    int v;\n    int r;\n};\n\nvoid testcase() {\n    int e, w, m, d, p, l;\n    std::cin >> e >> w >> m >> d >> p >> l;\n    std::vector<edge> nondiff(m);\n    for(int i = 0; i < m; i++) {\n        int u, v, r;\n        std::cin >> u >> v >> r;\n        nondiff[i] = {u, v, r};\n    }\n    std::vector<edge> diff(d);\n    for(int i = 0; i < d; i++) {\n        int u, v, r;\n        std::cin >> u >> v >> r;\n        diff[i] = {u, v, r};\n    }\n    int min_needed = std::max(e * l, w * l);\n    if(min_needed > p) {\n        std::cout << \"No schedule!\" << std::endl;\n        return;\n    }\n    graph G(2 * (e + w));\n    edge_adder adder(G);\n    // Retrieve the capacity map and reverse capacity map\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto rc_map = boost::get(boost::edge_residual_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    // edge from sink to two paths: one for the l matches for each, one for the rest\n    // same goes for sink \n    // --> by forcing the \"rest\" path to have at max p-e*l matches, we have at least l matches\n    // for each \n    int source = boost::add_vertex(G);\n    int source_out_l = boost::add_vertex(G);\n    int source_out_rest = boost::add_vertex(G);\n    int sink = boost::add_vertex(G);\n    int sink_out_l = boost::add_vertex(G);\n    int sink_out_rest = boost::add_vertex(G);\n    \n    for(int i = 0; i < e; i++) {\n        adder.add_edge(source_out_l, i, l, 0);\n        adder.add_edge(source_out_rest, i, std::numeric_limits<long>::max(), 0);\n        adder.add_edge(source_out_rest, e + w + i, std::numeric_limits<long>::max(), 0);\n    }\n\n    for(int i = 0; i < w; i++) {\n        adder.add_edge(2 * e + w + i, sink_out_rest, std::numeric_limits<long>::max(), 0);\n        adder.add_edge(e + i, sink_out_rest, std::numeric_limits<long>::max(), 0);\n        adder.add_edge(e + i, sink_out_l, l, 0);\n    }\n    \n    for(auto ed : nondiff) {  \n        adder.add_edge(ed.u, e + ed.v, 1, ed.r);\n    }\n    // diff matches are in a copy of e + w, where the e and w edges are connected to\n    // the \"rest\" source and sink nodes with capacity\n    for(auto ed : diff) {\n        adder.add_edge(e + w + ed.u, 2 * e + w + ed.v, 1, ed.r);\n    }\n    adder.add_edge(source, source_out_l, e * l, 0);\n    adder.add_edge(source, source_out_rest, p - e * l, 0);\n    adder.add_edge(sink_out_l, sink, w * l, 0);\n    adder.add_edge(sink_out_rest, sink, p - w * l, 0);\n\n    boost::successive_shortest_path_nonnegative_weights(G, source, sink);\n    int risk = boost::find_flow_cost(G);\n    \n    int flow = c_map[boost::edge(source, source_out_l, G).first] - rc_map[boost::edge(source, source_out_l, G).first];\n    flow += c_map[boost::edge(source, source_out_rest, G).first] - rc_map[boost::edge(source, source_out_rest, G).first];\n    if(flow != p) {\n        std::cout << \"No schedule!\" << std::endl;\n        return;\n    } else {\n        std::cout << risk << std::endl;\n    }\n\n    return;\n}\n\nint main() {\n    std::ios_base::sync_with_stdio(false);\n\n    int t;\n    std::cin >> t;\n    for (int i = 0; i < t; ++i)\n        testcase();\n}\n", "meta": {"hexsha": "a58edc2b1cc4186b7bbea5e0cf3ff6dda634e407", "size": 4894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week13-ludo_bagman/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/week13-ludo_bagman/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/week13-ludo_bagman/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4637681159, "max_line_length": 121, "alphanum_fraction": 0.6146301594, "num_tokens": 1431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.6791786926816161, "lm_q1q2_score": 0.6004206478054516}}
{"text": "\n#include <gtest/gtest.h>\n#include \"../util/util.h\"\n#include <Eigen/Core>\n#include <string>\n#include <algorithm>\n\n#ifndef _MSC_VER\nextern \"C\" {\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n#include <csim/init_ops.h>\n}\n#else\n#include <csim/memory_ops.h>\n#include <csim/stat_ops.h>\n#include <csim/update_ops.h>\n#include <csim/init_ops.h>\n#endif\n#include <csim/update_ops_cpp.hpp>\n\nvoid test_single_qubit_named_gate(UINT n, std::string name, std::function<void(UINT, CTYPE*, ITYPE)> func, Eigen::MatrixXcd mat) {\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 2;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state_with_seed(state, dim, 0);\n\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\tstd::vector<UINT> indices;\n\tfor (UINT i = 0; i < n; ++i) indices.push_back(i);\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\tfor (UINT i = 0; i < n; ++i) {\n\t\t\tUINT target = indices[i];\n\t\t\tfunc(target, state, dim);\n\t\t\ttest_state = get_expanded_eigen_matrix_with_identity(target, mat, n) * test_state;\n\t\t\tstate_equal(state, test_state, dim, name);\n\t\t}\n\t\tstd::random_shuffle(indices.begin(), indices.end());\n\t}\n\trelease_quantum_state(state);\n}\n\nTEST(UpdateTest, XGate) {\n\tEigen::MatrixXcd mat(2, 2);\n\tmat << 0, 1, 1, 0;\n\ttest_single_qubit_named_gate(6, \"XGate\", X_gate, mat);\n\ttest_single_qubit_named_gate(6, \"XGate\", X_gate_single_unroll, mat);\n#ifdef _OPENMP\n\ttest_single_qubit_named_gate(6, \"XGate\", X_gate_parallel_unroll, mat);\n#endif\n#ifdef _USE_SIMD\n\ttest_single_qubit_named_gate(6, \"XGate\", X_gate_single_simd, mat);\n#ifdef _OPENMP\n\ttest_single_qubit_named_gate(6, \"XGate\", X_gate_parallel_simd, mat);\n#endif\n#endif\n}\nTEST(UpdateTest, YGate) {\n\tEigen::MatrixXcd mat(2, 2);\n\tmat << 0, -1.i, 1.i, 0;\n\ttest_single_qubit_named_gate(6, \"YGate\", Y_gate, mat);\n\ttest_single_qubit_named_gate(6, \"YGate\", Y_gate_single_unroll, mat);\n#ifdef _OPENMP\n\ttest_single_qubit_named_gate(6, \"YGate\", Y_gate_parallel_unroll, mat);\n#endif\n#ifdef _USE_SIMD\n\ttest_single_qubit_named_gate(6, \"YGate\", Y_gate_single_simd, mat);\n#ifdef _OPENMP\n\ttest_single_qubit_named_gate(6, \"YGate\", Y_gate_parallel_simd, mat);\n#endif\n#endif\n}\nTEST(UpdateTest, ZGate) {\n\tconst UINT n = 3;\n\tEigen::MatrixXcd mat(2, 2);\n\tmat << 1, 0, 0, -1;\n\ttest_single_qubit_named_gate(6, \"ZGate\", Z_gate, mat);\n\ttest_single_qubit_named_gate(6, \"ZGate\", Z_gate_single_unroll, mat);\n#ifdef _OPENMP\n\ttest_single_qubit_named_gate(6, \"ZGate\", Z_gate_parallel_unroll, mat);\n#endif\n#ifdef _USE_SIMD\n\ttest_single_qubit_named_gate(6, \"ZGate\", Z_gate_single_simd, mat);\n#ifdef _OPENMP\n\ttest_single_qubit_named_gate(6, \"ZGate\", Z_gate_parallel_simd, mat);\n#endif\n#endif\n}\nTEST(UpdateTest, HGate) {\n\tconst UINT n = 3;\n\tEigen::MatrixXcd mat(2, 2);\n\tmat << 1, 1, 1, -1; mat /= sqrt(2.);\n\ttest_single_qubit_named_gate(n, \"HGate\", H_gate, mat);\n\ttest_single_qubit_named_gate(6, \"HGate\", H_gate_single_unroll, mat);\n#ifdef _OPENMP\n\ttest_single_qubit_named_gate(6, \"HGate\", H_gate_parallel_unroll, mat);\n#endif\n#ifdef _USE_SIMD\n\ttest_single_qubit_named_gate(6, \"HGate\", H_gate_single_simd, mat);\n#ifdef _OPENMP\n\ttest_single_qubit_named_gate(6, \"HGate\", H_gate_parallel_simd, mat);\n#endif\n#endif\n}\n\nTEST(UpdateTest, SGate) {\n\tconst UINT n = 3;\n\tEigen::MatrixXcd mat(2, 2);\n\tmat << 1, 0, 0, 1.i;\n\ttest_single_qubit_named_gate(n, \"SGate\", S_gate, mat);\n\ttest_single_qubit_named_gate(n, \"SGate\", Sdag_gate, mat.adjoint());\n}\n\nTEST(UpdateTest, TGate) {\n\tconst UINT n = 3;\n\tEigen::MatrixXcd mat(2, 2);\n\tmat << 1, 0, 0, (1. + 1.i) / sqrt(2.);\n\ttest_single_qubit_named_gate(n, \"TGate\", T_gate, mat);\n\ttest_single_qubit_named_gate(n, \"TGate\", Tdag_gate, mat.adjoint());\n}\n\nTEST(UpdateTest, sqrtXGate) {\n\tconst UINT n = 3;\n\tEigen::MatrixXcd mat(2, 2);\n\tmat << 0.5 + 0.5i, 0.5 - 0.5i, 0.5 - 0.5i, 0.5 + 0.5i;\n\ttest_single_qubit_named_gate(n, \"SqrtXGate\", sqrtX_gate, mat);\n\ttest_single_qubit_named_gate(n, \"SqrtXdagGate\", sqrtXdag_gate, mat.adjoint());\n}\n\nTEST(UpdateTest, sqrtYGate) {\n\tconst UINT n = 3;\n\tEigen::MatrixXcd mat(2, 2);\n\tmat << 0.5 + 0.5i, -0.5 - 0.5i, 0.5 + 0.5i, 0.5 + 0.5i;\n\ttest_single_qubit_named_gate(n, \"SqrtYGate\", sqrtY_gate, mat);\n\ttest_single_qubit_named_gate(n, \"SqrtYdagGate\", sqrtYdag_gate, mat.adjoint());\n}\n\nvoid test_projection_gate(std::function<void(UINT, CTYPE*, ITYPE)> func, std::function<double(UINT, CTYPE*, ITYPE)> prob_func, Eigen::MatrixXcd mat) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\tconst double eps = 1e-14;\n\tUINT target;\n\tdouble prob;\n\n\tauto state = allocate_quantum_state(dim);\n\tstd::vector<UINT> indices;\n\tfor (UINT i = 0; i < n; ++i) indices.push_back(i);\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\ttarget = indices[i];\n\t\t\tinitialize_Haar_random_state(state, dim);\n\t\t\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\t\t\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\n\t\t\t// Z-projection operators \n\t\t\tprob = prob_func(target, state, dim);\n\t\t\tEXPECT_GT(prob, 1e-10);\n\t\t\tfunc(target, state, dim);\n\t\t\tASSERT_NEAR(state_norm_squared(state, dim), prob, eps);\n\t\t\tnormalize(prob, state, dim);\n\n\t\t\ttest_state = get_expanded_eigen_matrix_with_identity(target, mat, n)*test_state;\n\t\t\tASSERT_NEAR(test_state.squaredNorm(), prob, eps);\n\t\t\ttest_state.normalize();\n\t\t\tstate_equal(state, test_state, dim, \"Projection gate\");\n\t\t}\n\t\tstd::random_shuffle(indices.begin(), indices.end());\n\t}\n\trelease_quantum_state(state);\n}\n\nTEST(UpdateTest, ProjectionAndNormalizeTest) {\n\tEigen::MatrixXcd P0(2, 2), P1(2, 2);\n\tP0 << 1, 0, 0, 0;\n\tP1 << 0, 0, 0, 1;\n\ttest_projection_gate(P0_gate, M0_prob, P0);\n\ttest_projection_gate(P1_gate, M1_prob, P1);\n\ttest_projection_gate(P0_gate_single, M0_prob, P0);\n\ttest_projection_gate(P1_gate_single, M1_prob, P1);\n#ifdef _OPENMP\n\ttest_projection_gate(P0_gate_parallel, M0_prob, P0);\n\ttest_projection_gate(P1_gate_parallel, M1_prob, P1);\n#endif\n}\n\n\nTEST(UpdateTest, SingleQubitRotationGateTest) {\n\tconst UINT n = 6;\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 10;\n\n\tEigen::MatrixXcd Identity(2, 2), X(2, 2), Y(2, 2), Z(2, 2);\n\tIdentity << 1, 0, 0, 1;\n\tX << 0, 1, 1, 0;\n\tY << 0, -1.i, 1.i, 0;\n\tZ << 1, 0, 0, -1;\n\n\tUINT target;\n\tdouble angle;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state(state, dim);\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\ttypedef std::tuple<std::function<void(UINT, double, CTYPE*, ITYPE)>, Eigen::MatrixXcd, std::string> testset;\n\tstd::vector<testset> test_list;\n\ttest_list.push_back(std::make_tuple(RX_gate, X, \"Xrot\"));\n\ttest_list.push_back(std::make_tuple(RY_gate, Y, \"Yrot\"));\n\ttest_list.push_back(std::make_tuple(RZ_gate, Z, \"Zrot\"));\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\tfor (auto tup : test_list) {\n\t\t\ttarget = rand_int(n);\n\t\t\tangle = rand_real();\n\t\t\tauto func = std::get<0>(tup);\n\t\t\tauto mat = std::get<1>(tup);\n\t\t\tauto name = std::get<2>(tup);\n\t\t\tfunc(target, angle, state, dim);\n\t\t\ttest_state = get_expanded_eigen_matrix_with_identity(target, cos(angle / 2)*Identity + 1.i*sin(angle / 2)*mat, n) * test_state;\n\t\t\tstate_equal(state, test_state, dim, name);\n\t\t}\n\t}\n\trelease_quantum_state(state);\n}\n\nvoid test_two_qubit_named_gate(UINT n, std::string name, std::function<void(UINT, UINT, CTYPE*, ITYPE)> func,\n\tstd::function<Eigen::MatrixXcd(UINT, UINT, UINT)> matfunc) {\n\tconst ITYPE dim = 1ULL << n;\n\tconst UINT max_repeat = 2;\n\n\tauto state = allocate_quantum_state(dim);\n\tinitialize_Haar_random_state_with_seed(state, dim, 0);\n\n\tEigen::VectorXcd test_state = Eigen::VectorXcd::Zero(dim);\n\tfor (ITYPE i = 0; i < dim; ++i) test_state[i] = state[i];\n\tstd::vector<UINT> indices;\n\tfor (UINT i = 0; i < n; ++i) indices.push_back(i);\n\n\tfor (UINT rep = 0; rep < max_repeat; ++rep) {\n\t\tfor (UINT i = 0; i + 1 < n; i += 2) {\n\t\t\tUINT target = indices[i];\n\t\t\tUINT control = indices[i + 1];\n\t\t\tfunc(control, target, state, dim);\n\t\t\tEigen::MatrixXcd mat = matfunc(control, target, n);\n\t\t\ttest_state = mat * test_state;\n\t\t\tstate_equal(state, test_state, dim, name);\n\t\t}\n\t\tstd::random_shuffle(indices.begin(), indices.end());\n\t}\n\trelease_quantum_state(state);\n}\n\nTEST(UpdateTest, CNOTGate) {\n\tconst UINT n = 4;\n\ttest_two_qubit_named_gate(n, \"CNOT\", CNOT_gate, get_eigen_matrix_full_qubit_CNOT);\n\ttest_two_qubit_named_gate(6, \"CNOTGate\", CNOT_gate_single_unroll, get_eigen_matrix_full_qubit_CNOT);\n#ifdef _OPENMP\n\ttest_two_qubit_named_gate(6, \"CNOTGate\", CNOT_gate_parallel_unroll, get_eigen_matrix_full_qubit_CNOT);\n#endif\n#ifdef _USE_SIMD\n\ttest_two_qubit_named_gate(6, \"CNOTGate\", CNOT_gate_single_simd, get_eigen_matrix_full_qubit_CNOT);\n#ifdef _OPENMP\n\ttest_two_qubit_named_gate(6, \"CNOTGate\", CNOT_gate_parallel_simd, get_eigen_matrix_full_qubit_CNOT);\n#endif\n#endif\n}\n\nTEST(UpdateTest, CZGate) {\n\tconst UINT n = 4;\n\ttest_two_qubit_named_gate(n, \"CZ\", CZ_gate, get_eigen_matrix_full_qubit_CZ);\n\ttest_two_qubit_named_gate(6, \"CZGate\", CZ_gate_single_unroll, get_eigen_matrix_full_qubit_CZ);\n#ifdef _OPENMP\n\ttest_two_qubit_named_gate(6, \"CZGate\", CZ_gate_parallel_unroll, get_eigen_matrix_full_qubit_CZ);\n#endif\n#ifdef _USE_SIMD\n\ttest_two_qubit_named_gate(6, \"CZGate\", CZ_gate_single_simd, get_eigen_matrix_full_qubit_CZ);\n#ifdef _OPENMP\n\ttest_two_qubit_named_gate(6, \"CZGate\", CZ_gate_parallel_simd, get_eigen_matrix_full_qubit_CZ);\n#endif\n#endif\n}\n\nTEST(UpdateTest, SWAPGate) {\n\tconst UINT n = 4;\n\ttest_two_qubit_named_gate(n, \"SWAP\", SWAP_gate, get_eigen_matrix_full_qubit_SWAP);\n\ttest_two_qubit_named_gate(6, \"SWAPGate\", SWAP_gate_single_unroll, get_eigen_matrix_full_qubit_SWAP);\n#ifdef _OPENMP\n\ttest_two_qubit_named_gate(6, \"SWAPGate\", SWAP_gate_parallel_unroll, get_eigen_matrix_full_qubit_SWAP);\n#endif\n#ifdef _USE_SIMD\n\ttest_two_qubit_named_gate(6, \"SWAPGate\", SWAP_gate_single_simd, get_eigen_matrix_full_qubit_SWAP);\n#ifdef _OPENMP\n\ttest_two_qubit_named_gate(6, \"SWAPGate\", SWAP_gate_parallel_simd, get_eigen_matrix_full_qubit_SWAP);\n#endif\n#endif\n}\n\n", "meta": {"hexsha": "22ee01af24ee0ac428123e1c31260af743df6554", "size": 10021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/csim/test_update_named.cpp", "max_stars_repo_name": "kamakiri01/qulacs", "max_stars_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 260.0, "max_stars_repo_stars_event_min_datetime": "2018-10-13T15:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T11:03:58.000Z", "max_issues_repo_path": "test/csim/test_update_named.cpp", "max_issues_repo_name": "kamakiri01/qulacs", "max_issues_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 182.0, "max_issues_repo_issues_event_min_datetime": "2018-10-14T02:29:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:23:18.000Z", "max_forks_repo_path": "test/csim/test_update_named.cpp", "max_forks_repo_name": "kamakiri01/qulacs", "max_forks_repo_head_hexsha": "1e3e6ac26390abdfe5abe7f4d52349bcfd68e20c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 88.0, "max_forks_repo_forks_event_min_datetime": "2018-10-10T03:46:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-27T21:56:05.000Z", "avg_line_length": 32.9638157895, "max_line_length": 150, "alphanum_fraction": 0.7254764994, "num_tokens": 3258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107309, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.600373783995621}}
{"text": "/******************************************************************************\n *\n * AMDiS - Adaptive multidimensional simulations\n *\n * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.\n * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis\n *\n * Authors:\n * Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al.\n *\n * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\n *\n * This file is part of AMDiS\n *\n * See also license.opensource.txt in the distribution.\n *\n ******************************************************************************/\n\n#ifndef AMDIS_FUNCTORS_H\n#define AMDIS_FUNCTORS_H\n\n#include \"AbstractFunction.h\"\n#include <boost/math/special_functions/cbrt.hpp>\n#include <boost/math/special_functions/pow.hpp>\n\n// NOTE: should be removed or replaced by functors in operation/functors.hpp\n\nnamespace AMDiS\n{\n\n  template<typename T>\n  struct Id : public AbstractFunction<T,T>\n  {\n    Id(int degree = 1) : AbstractFunction<T,T>(degree) {}\n    T operator()(const T& v) const\n    {\n      return v;\n    }\n  };\n\n  template<typename T1,typename T2>\n  struct Const : public AbstractFunction<T1,T2>\n  {\n    Const(T1 val_) : AbstractFunction<T1,T2>(0), val(val_) {}\n    T1 operator()(const T2& v) const\n    {\n      return val;\n    }\n  private:\n    T1 val;\n  };\n\n  template<typename T=double>\n  struct Factor : public AbstractFunction<T,T>\n  {\n    Factor(double fac_, int degree = 1) : AbstractFunction<T,T>(degree), fac(fac_) {}\n    T operator()(const T& x) const\n    {\n      return fac*x;\n    }\n  private:\n    double fac;\n  };\n\n  template<typename T=double>\n  struct Add : public BinaryAbstractFunction<T,T,T>\n  {\n    Add(int degree = 1) : BinaryAbstractFunction<T,T,T>(degree) {}\n    T operator()(const T& v1, const T& v2) const\n    {\n      return v1+v2;\n    }\n  };\n\n  template<typename T=double>\n  struct AddFactor : public BinaryAbstractFunction<T,T,T>\n  {\n    AddFactor(double factor_ = 1.0, int degree = 1) : BinaryAbstractFunction<T,T,T>(degree), factor(factor_) {}\n    T operator()(const T& v1, const T& v2) const\n    {\n      return v1 + factor*v2;\n    }\n  private:\n    double factor;\n  };\n\n  template<typename T=double>\n  struct Subtract : public BinaryAbstractFunction<T,T,T>\n  {\n    Subtract(int degree = 1) : BinaryAbstractFunction<T,T,T>(degree) {}\n    T operator()(const T& v1, const T& v2) const\n    {\n      return v1-v2;\n    }\n  };\n\n  template<typename T=double>\n  struct AddScal : public AbstractFunction<T,T>\n  {\n    AddScal(T scal_, int degree = 1) : AbstractFunction<T,T>(degree), scal(scal_) {}\n    T operator()(const T& v) const\n    {\n      return v+scal;\n    }\n  private:\n    T scal;\n  };\n\n  template<typename T>\n  struct Mult : public BinaryAbstractFunction<T,T,T>\n  {\n    Mult(int degree = 2) : BinaryAbstractFunction<T,T,T>(degree) {}\n    T operator()(const T& v1, const T& v2) const\n    {\n      return v1*v2;\n    }\n  };\n\n  template<typename T1, typename T2, typename T3>\n  struct Mult2 : public BinaryAbstractFunction<T1,T2,T3>\n  {\n    Mult2(int degree = 2) : BinaryAbstractFunction<T1,T2,T3>(degree) {}\n    T1 operator()(const T2& v1, const T3& v2) const\n    {\n      return v1*v2;\n    }\n  };\n\n  template<typename T>\n  struct MultScal : public BinaryAbstractFunction<T,T,T>\n  {\n    MultScal(T scal_, int degree = 2) : BinaryAbstractFunction<T,T,T>(degree), scal(scal_) {}\n    T operator()(const T& v1, const T& v2) const\n    {\n      return v1*v2*scal;\n    }\n  private:\n    T scal;\n  };\n\n  template<typename T>\n  struct Max : public BinaryAbstractFunction<T,T,T>\n  {\n    Max(int degree = 1) : BinaryAbstractFunction<T,T,T>(degree) {}\n    T operator()(const T& v1, const T& v2) const\n    {\n      return std::max(v1,v2);\n    }\n  };\n\n  template<typename T>\n  struct Min : public BinaryAbstractFunction<T,T,T>\n  {\n    Min(int degree = 1) : BinaryAbstractFunction<T,T,T>(degree) {}\n    T operator()(const T& v1, const T& v2) const\n    {\n      return std::min(v1,v2);\n    }\n  };\n\n  template<typename T>\n  struct Diff : public BinaryAbstractFunction<T,T,T>\n  {\n    Diff(int degree = 1) : BinaryAbstractFunction<T,T,T>(degree) {}\n    T operator()(const T& v1, const T& v2) const\n    {\n      return std::abs(v1-v2);\n    }\n  };\n\n  template<typename T=double>\n  struct Abs : public AbstractFunction<T,T>\n  {\n    Abs(int degree = 1) : AbstractFunction<T,T>(degree) {}\n    T operator()(const T& v) const\n    {\n      return std::abs(v);\n    }\n  };\n\n  template<typename T=double>\n  struct Signum : public AbstractFunction<T,T>\n  {\n    Signum() : AbstractFunction<T,T>(0) {}\n    T operator()(const T& v) const\n    {\n      return (v>0.0?1.0:(v<0.0?-1.0:0.0));\n    }\n  };\n\n  template<typename T=double>\n  struct Sqr : public AbstractFunction<T,T>\n  {\n    Sqr(int degree = 2) : AbstractFunction<T, T>(degree) {}\n    T operator()(const T& v) const\n    {\n      return sqr(v);\n    }\n  };\n\n  template<typename T=double>\n  struct Sqrt : public AbstractFunction<T,T>\n  {\n    Sqrt(int degree = 4) : AbstractFunction<T,T>(degree) {}\n    T operator()(const T& v) const\n    {\n      return std::sqrt(v);\n    }\n  };\n\n  namespace detail\n  {\n    template<int p, typename T, typename Enabled = void>\n    struct Pow\n    {\n      typedef typename traits::mult_type<T, typename Pow<p-1,T>::result_type>::type result_type;\n      static result_type eval(const T& v)\n      {\n        return v*Pow<p-1,T>::eval(v);\n      }\n    };\n\n    template<int p, typename T>\n    struct Pow<p, T, typename boost::enable_if_c<\n      boost::is_same<T, typename traits::mult_type<T, T>::type>::value&&\n    (p > 1)\n    >::type >\n    {\n      typedef T result_type;\n      static T eval(const T& v)\n    {\n      return boost::math::pow<p>(v);\n    }\n    };\n\n    template<typename T>\n    struct Pow<1,T>\n    {\n      typedef T result_type;\n      static result_type eval(const T& v)\n      {\n        return v;\n      }\n    };\n\n    template<typename T>\n    struct Pow<0, T>\n    {\n      typedef double result_type;\n      static result_type eval(const T& v)\n      {\n        return 1.0;\n      }\n    };\n  }\n\n  template<int p, typename T=double>\n  struct Pow : public AbstractFunction<typename detail::Pow<p,T>::result_type, T>\n  {\n    typedef typename detail::Pow<p,T>::result_type result_type;\n    Pow(double factor_=1.0, int degree = p) : AbstractFunction<result_type,T>(degree), factor(factor_) {}\n    result_type operator()(const T& v) const\n    {\n      return factor * detail::Pow<p,T>::eval(v);\n    }\n  private:\n    double factor;\n  };\n\n  template<typename TIn, typename TOut = typename traits::mult_type<TIn, TIn>::type>\n  struct Norm2 : public AbstractFunction<TOut, TIn>\n  {\n    Norm2(int degree = 4) : AbstractFunction<TOut, TIn>(degree) {}\n    TOut operator()(const TIn& v) const\n    {\n      return std::sqrt(v*v);\n    }\n  };\n\n  template<typename TIn, typename TOut = typename traits::mult_type<TIn, TIn>::type>\n  struct Norm2Sqr : public AbstractFunction<TOut, TIn>\n  {\n    Norm2Sqr(int degree = 2) : AbstractFunction<TOut, TIn>(degree) {}\n    TOut operator()(const TIn& v) const\n    {\n      return v*v;\n    }\n  };\n\n  template<typename T>\n  struct Norm2_comp2 : public BinaryAbstractFunction<T,T,T>\n  {\n    Norm2_comp2(int degree = 4) : BinaryAbstractFunction<T,T,T>(degree) {}\n    T operator()(const T& v1, const T& v2) const\n    {\n      return std::sqrt(sqr(v1)+sqr(v2));\n    }\n  };\n\n  template<typename T>\n  struct Norm2Sqr_comp2 : public BinaryAbstractFunction<T,T,T>\n  {\n    Norm2Sqr_comp2(int degree = 2) : BinaryAbstractFunction<T,T,T>(degree) {}\n    T operator()(const T& v1, const T& v2) const\n    {\n      return sqr(v1)+sqr(v2);\n    }\n  };\n\n  template<typename T>\n  struct Norm2_comp3 : public TertiaryAbstractFunction<T,T,T,T>\n  {\n    Norm2_comp3(int degree = 4) : TertiaryAbstractFunction<T,T,T,T>(degree) {}\n    T operator()(const T& v1, const T& v2, const T& v3) const\n    {\n      return std::sqrt(sqr(v1)+sqr(v2)+sqr(v3));\n    }\n  };\n\n  template<typename T>\n  struct Norm2Sqr_comp3 : public TertiaryAbstractFunction<T,T,T,T>\n  {\n    Norm2Sqr_comp3(int degree = 2) : TertiaryAbstractFunction<T,T,T,T>(degree) {}\n    T operator()(const T& v1, const T& v2, const T& v3) const\n    {\n      return sqr(v1)+sqr(v2)+sqr(v3);\n    }\n  };\n\n  template<typename T>\n  struct L1Diff : public BinaryAbstractFunction<T,T,T>\n  {\n    T operator()(const T& v1, const T& v2) const\n    {\n      return std::abs(v1-v2);\n    }\n  };\n\n  template<typename TOut, typename T=TOut>\n  struct L2Diff : public BinaryAbstractFunction<TOut,T,T>\n  {\n    TOut operator()(const T& v1, const T& v2) const\n    {\n      return Norm2<TOut, T>()(v1-v2);\n    }\n  };\n\n  template<typename T>\n  struct Vec1WorldVec : public AbstractFunction<WorldVector<T>,T>\n  {\n    WorldVector<T> operator()(const T& v0) const\n    {\n      WorldVector<T> result;\n      result[0]=v0;\n      return result;\n    }\n  };\n  template<typename T>\n  struct Vec2WorldVec : public BinaryAbstractFunction<WorldVector<T>,T,T>\n  {\n    WorldVector<T> operator()(const T& v0, const T& v1) const\n    {\n      WorldVector<T> result;\n      result[0]=v0;\n      result[1]=v1;\n      return result;\n    }\n  };\n  template<typename T>\n  struct Vec3WorldVec : public TertiaryAbstractFunction<WorldVector<T>,T,T,T>\n  {\n    WorldVector<T> operator()(const T& v0, const T& v1, const T& v2) const\n    {\n      WorldVector<T> result;\n      result[0]=v0;\n      result[1]=v1;\n      result[2]=v2;\n      return result;\n    }\n  };\n  template<int c, typename T=double>\n  struct Component : public AbstractFunction<T, WorldVector<T>>\n  {\n    Component(int degree = 1) : AbstractFunction<T, WorldVector<T>>(degree) {}\n    T operator()(const WorldVector<T>& x) const\n    {\n      return x[c];\n    }\n  };\n  template<typename T=double>\n  struct Component2 : public AbstractFunction<T, WorldVector<T>>\n  {\n    Component2(int comp, int degree = 1) : AbstractFunction<T, WorldVector<T>>(degree), c_(comp) {}\n    T operator()(const WorldVector<T>& x) const\n    {\n      return x[c_];\n    }\n  private:\n    int c_;\n  };\n\n  struct FadeOut : public TertiaryAbstractFunction<double, double, double ,double>\n  {\n    double operator()(const double& v, const double& dist, const double& mean) const\n    {\n      return dist*mean+(1.0-dist)*v;\n    }\n  };\n\n  struct Random : public AbstractFunction<double, WorldVector<double>>\n  {\n    Random(double mean_, double amplitude_) : mean(mean_), amplitude(amplitude_)\n    {\n      std::srand(time(0));\n    }\n\n    double operator()(const WorldVector<double>& x) const\n    {\n      return mean + 2.0*amplitude * ((std::rand() / static_cast<double>(RAND_MAX)) - 0.5);\n    }\n\n  private:\n    double mean;\n    double amplitude;\n  };\n\n}\n\n#endif // AMDIS_FUNCTORS_H\n\n", "meta": {"hexsha": "2c613ea233fecbf9a688f4ec2e0bc09308ed01fa", "size": 10707, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/deprecated/Functors.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "src/deprecated/Functors.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/deprecated/Functors.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.727482679, "max_line_length": 111, "alphanum_fraction": 0.6154851966, "num_tokens": 3026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6003737839956209}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n\n\nnamespace LSLOpt {\n\n/**\n * @brief Vector type used.\n * @tparam Scalar The scalar type of the coefficients.\n *\n * This is a column vector (an `Eigen::Matrix`).\n */\ntemplate<typename Scalar>\nusing Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\n/**\n * @brief Matrix type used.\n * @tparam Scalar The scalar type of the coefficients.\n *\n * This is a matrix (an `Eigen::Matrix`).\n */\ntemplate<typename Scalar>\nusing Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n\n/**\n * @brief Diagonal matrix type used.\n * @tparam Scalar The scalar type of the coefficients.\n *\n * This is a diagonal matrix (an `Eigen::DiagonalMatrix`).\n */\ntemplate<typename Scalar>\nusing DiagonalMatrix = Eigen::DiagonalMatrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n\n}\n", "meta": {"hexsha": "68c2310738fe092bb290f5995e32fe7d4691de97", "size": 796, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/LSLOpt/Types.hpp", "max_stars_repo_name": "flachsenberg/LSLOpt", "max_stars_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T02:42:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T14:09:06.000Z", "max_issues_repo_path": "include/LSLOpt/Types.hpp", "max_issues_repo_name": "flachsenberg/LSLOpt", "max_issues_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/LSLOpt/Types.hpp", "max_forks_repo_name": "flachsenberg/LSLOpt", "max_forks_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-08T12:12:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T12:12:51.000Z", "avg_line_length": 22.1111111111, "max_line_length": 85, "alphanum_fraction": 0.7035175879, "num_tokens": 186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.600373778108388}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <dlib/optimization.h>\n#include <iostream>\n#include <limits>\n#include <mimkl/data_structures.hpp>\n#include <mimkl/definitions.hpp>\n#include <mimkl/io.hpp>\n#include <mimkl/kernels.hpp>\n#include <mimkl/linear_algebra.hpp>\n#include <mimkl/models/easy_mkl.hpp>\n#include <mimkl/solvers/komd.hpp>\n#include <spdlog/fmt/ostr.h>\n#include <spdlog/spdlog.h>\n\nusing dlib::mat;\nusing mimkl::data_structures::DataFrame;\nusing mimkl::data_structures::indexing_from_vector;\nusing mimkl::data_structures::range;\nusing mimkl::definitions::Indexing;\n\nint main(int argc, char **argv)\n{\n    spdlog::set_level(spdlog::level::debug); // Set global log level to info\n    auto console = spdlog::stdout_color_mt(\"console\");\n\n    const Index rows = 4; // 3 to reproduce error\n\n    MATRIX(double) X(rows, 2);\n    //\tX << 1., 1., 3., 1., 1., 2.;\n    X << 1., 1., 3., 1., 1., 4., 3., 2.;\n\n    Eigen::SparseMatrix<double> L(2, 2);\n    mimkl::linear_algebra::fill_sparse_diagonal(L, 1.0);\n    MATRIX(double)\n    K = mimkl::induction::induce_linear_kernel<MATRIX(double)>(X, X, L);\n    COLUMN(double) Y(rows);\n    //\tY << -1., 1., -1.;\n    Y << -1., 1., -1., 1.;\n    //\tEigen::Matrix<double, rows, 1> alphas;\n    //\tEigen::Matrix<double, 3, 1> gamma_ref;\n\n    std::cout << \"X\\n\" << X << std::endl;\n    std::cout << \"dlib X\\n\" << mat(X) << std::endl;\n    std::cout << \"Y\\n\" << Y << std::endl;\n\n    // test dlib assertions do not trigger? eg. with y.size()==1  TODO\n\n    // KOMD\n    mimkl::solvers::KOMD<double> some_dots(K, 0.2, 1e-8);\n    some_dots.solve(Y);\n    console->debug(\"get result :\\n{}\",\n                   some_dots.get_result()); // gamma is private\n    //  typedef Eigen::Map<EigenCol> MapEigenCol;\n    COLUMN(double)\n    gamma = some_dots.get_result(); // conversion of MapEigenCol to EigenCol\n    console->info(\"gamma eigen (map to mat):\\n{}\", gamma);\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "b964dae4bf23e0e2de7f5885ce80b0bb0b8512c1", "size": 1916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/dlib/main.cpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "test/dlib/main.cpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "test/dlib/main.cpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 31.9333333333, "max_line_length": 76, "alphanum_fraction": 0.6372651357, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.6003737688904435}}
{"text": "#ifndef SOLVE_SPARSE_LINEAR_SYSTEMS_HPP\n#define SOLVE_SPARSE_LINEAR_SYSTEMS_HPP\n#include \"HeaderFile.h\"\n\n// http : //eigen.tuxfamily.org/dox/group__TopicSparseSystems.html\nnamespace Chapter3_SparseLinearAlgebra\n{\n\n//\u5728Eigen\u4e2d\uff0c\u5f53\u7cfb\u6570\u77e9\u9635\u7a00\u758f\u65f6\uff0c\u6709\u51e0\u79cd\u65b9\u6cd5\u53ef\u7528\u4e8e\u6c42\u89e3\u7ebf\u6027\u7cfb\u7edf\u3002\n// \u7531\u4e8e\u6b64\u7c7b\u77e9\u9635\u7684\u7279\u6b8a\u8868\u793a\uff0c\u56e0\u6b64\u5e94\u683c\u5916\u5c0f\u5fc3\uff0c\u4ee5\u83b7\u5f97\u826f\u597d\u7684\u6027\u80fd\u3002\n// \u6709\u5173Eigen\u4e2d\u7a00\u758f\u77e9\u9635\u7684\u8be6\u7ec6\u4ecb\u7ecd\uff0c\u8bf7\u53c2\u89c1\u7a00\u758f\u77e9\u9635\u64cd\u4f5c\u3002\n//\u6b64\u9875\u9762\u5217\u51fa\u4e86Eigen\u4e2d\u53ef\u7528\u7684\u7a00\u758f\u6c42\u89e3\u5668\u3002\u8fd8\u4ecb\u7ecd\u4e86\u6240\u6709\u8fd9\u4e9b\u7ebf\u6027\u6c42\u89e3\u5668\u5171\u6709\u7684\u4e3b\u8981\u6b65\u9aa4\u3002\n//\u53d6\u51b3\u4e8e\u77e9\u9635\u7684\u5c5e\u6027\uff0c\u6240\u9700\u7684\u7cbe\u5ea6\uff0c\u6700\u7ec8\u7528\u6237\u80fd\u591f\u8c03\u6574\u8fd9\u4e9b\u6b65\u9aa4\uff0c\u4ee5\u63d0\u9ad8\u5176\u4ee3\u7801\u7684\u6027\u80fd\u3002\n//\u8bf7\u6ce8\u610f\uff0c\u5e76\u4e0d\u9700\u8981\u6df1\u5165\u4e86\u89e3\u8fd9\u4e9b\u6b65\u9aa4\u80cc\u540e\u7684\u5185\u5bb9\uff1a\n//\u6700\u540e\u4e00\u90e8\u5206\u63d0\u4f9b\u4e86\u4e00\u4e2a\u57fa\u51c6\u4f8b\u7a0b\uff0c\u53ef\u4ee5\u8f7b\u677e\u5730\u4f7f\u7528\u5b83\u6765\u6df1\u5165\u4e86\u89e3\u6240\u6709\u53ef\u7528\u6c42\u89e3\u5668\u7684\u6027\u80fd\u3002\nnamespace Section2_SolveSparseLinearSystems\n{\n\nvoid ListofSparseSolvers()\n{\n        //  Here SPD means symmetric positive definite SPD\u5bf9\u5e94\u5bf9\u79f0\u6b63\u5b9a\u77e9\u9635\n        //Eigen\u5f53\u524d\u63d0\u4f9b\u4e86\u5e7f\u6cdb\u7684\u5185\u7f6e\u6c42\u89e3\u5668\uff0c\u4ee5\u53ca\u5916\u90e8\u6c42\u89e3\u5668\u5e93\u7684\u5305\u88c5\u5668\u3002\u4e0b\u8868\u4e2d\u6c47\u603b\u4e86\u5b83\u4eec\uff1a\n\n        // 1. \u5185\u7f6e\u76f4\u63a5\u6c42\u89e3\u5668: LLT LDLT\u9700\u8981\u5bf9\u9635\u6b63\u5b9a\u77e9\u9635\uff0cLU\u9700\u8981\u65b9\u9635\uff0cQR\u9002\u7528\u4e8e\u4efb\u610f\u77e9\u9635\n\n        // Class\tSolver kind\tMatrix kind\tFeatures related to performance\tLicense        Notes\n\n        // SimplicialLLT\n        // #include<Eigen/SparseCholesky>\tDirect LLt factorization\tSPD\tFill-in reducing\tLGPL    SimplicialLDLT is often preferable\n\n        // SimplicialLDLT\n        // #include<Eigen/SparseCholesky>\tDirect LDLt factorization\tSPD\tFill-in reducing\tLGPL  Recommended for very sparse and not too large problems (e.g., 2D Poisson eq.)\n\n        // SparseLU\n        // #include<Eigen/SparseLU>\tLU factorization\tSquare\tFill-in reducing, Leverage fast dense algebra\tMPL2   optimized for small and large problems with irregular patterns\n\n        // SparseQR\n        // #include<Eigen/SparseQR>\tQR factorization\tAny, rectangular\tFill-in reducing\tMPL2\trecommended for least-square problems, has a basic rank-revealing feature\n\n        // 2.\u5185\u7f6e\u8fed\u4ee3\u6c42\u89e3\u5668\n\n        //  Class\tSolver kind\tMatrix kind\tSupported preconditioners, [default]\tLicense  Notes\n\n        // ConjugateGradient\n        // #include<Eigen/IterativeLinearSolvers>\tClassic iterative CG\tSPD\tIdentityPreconditioner, [DiagonalPreconditioner], IncompleteCholesky\tMPL2\n        // Recommended for large symmetric problems (e.g., 3D Poisson eq.)\n\n        // LeastSquaresConjugateGradient\n        // #include<Eigen/IterativeLinearSolvers>\tCG for rectangular least-square problem\tRectangular\tIdentityPreconditioner, [LeastSquareDiagonalPreconditioner]\tMPL2\n        // Solve for min |A'Ax-b|^2 without forming A'A\n\n        // BiCGSTAB\n        // #include<Eigen/IterativeLinearSolvers>\tIterative stabilized bi-conjugate gradient\tSquare\tIdentityPreconditioner, [DiagonalPreconditioner], IncompleteLUT\tMPL2\tTo speedup the convergence, try it with the IncompleteLUT preconditioner.\n\n        //3.\u5916\u90e8\u6c42\u89e3\u5668\n        //         Class\tModule\tSolver kind\tMatrix kind\tFeatures related to performance\tDependencies,License   Notes\n        // PastixLLT\n        // PastixLDLT\n        // PastixLU\tPaStiXSupport\tDirect LLt, LDLt, LU factorizations\tSPD\n        // SPD\n        // Square\tFill-in reducing, Leverage fast dense algebra, Multithreading\tRequires the PaStiX package, CeCILL-C\toptimized for tough problems and symmetric patterns\n        // CholmodSupernodalLLT\tCholmodSupport\tDirect LLt factorization\tSPD\tFill-in reducing, Leverage fast dense algebra\tRequires the SuiteSparse package, GPL\n        // UmfPackLU\tUmfPackSupport\tDirect LU factorization\tSquare\tFill-in reducing, Leverage fast dense algebra\tRequires the SuiteSparse package, GPL\n        // SuperLU\tSuperLUSupport\tDirect LU factorization\tSquare\tFill-in reducing, Leverage fast dense algebra\tRequires the SuperLU library, (BSD-like)\n        // SPQR\tSPQRSupport\tQR factorization\tAny, rectangular\tfill-in reducing, multithreaded, fast dense algebra\trequires the SuiteSparse package, GPL\trecommended for linear least-squares problems, has a rank-revealing feature\n        // PardisoLLT\n        // PardisoLDLT\n        // PardisoLU\tPardisoSupport\tDirect LLt, LDLt, LU factorizations\tSPD\n        // SPD\n        // Square\tFill-in reducing, Leverage fast dense algebra, Multithreading\tRequires the Intel MKL package, Proprietary\toptimized for tough problems patterns, see also using MKL with Eigen\n}\n\nvoid SparseSolverConcept()\n{\n        // \u4e00\u4e2a\u901a\u7528\u7684\u4f8b\u5b50\n        // #include <Eigen/RequiredModuleName>\n        // // ...\n        // SparseMatrix<double> A;\n        // // fill A\n        // VectorXd b, x;\n        // // fill b\n        // // solve Ax = b\n        // SolverClassName<SparseMatrix<double>> solver;\n        // solver.compute(A);\n        // if (solver.info() != Success)\n        // {\n        //         // decomposition failed\n        //         return;\n        // }\n        // x = solver.solve(b);\n        // if (solver.info() != Success)\n        // {\n        //         // solving failed\n        //         return;\n        // }\n        // // solve for another right hand side:\n        // x1 = solver.solve(b1);\n\n        // \u5bf9\u4e8eSPD\u6c42\u89e3\u5668\uff0c\u7b2c\u4e8c\u4e2a\u53ef\u9009\u6a21\u677f\u53c2\u6570\u5141\u8bb8\u6307\u5b9a\u5fc5\u987b\u4f7f\u7528\u54ea\u4e2a\u4e09\u89d2\u5f62\u90e8\u5206\uff0c\u4f8b\u5982\uff1a\n        //```\n        // #include <Eigen / IterativeLinearSolvers>\n        // ConjugateGradient <SparseMatrix <double>\uff0cEigen :: Upper >\u6c42\u89e3\u5668;\n        // x = Solver.compute\uff08A\uff09.solve\uff08b\uff09;\n\n        // ```\n        // \u5728\u4e0a\u9762\u7684\u793a\u4f8b\u4e2d\uff0c\u4ec5\u8003\u8651\u8f93\u5165\u77e9\u9635A\u7684\u4e0a\u4e09\u89d2\u90e8\u5206\u8fdb\u884c\u6c42\u89e3\u3002\u5bf9\u9762\u7684\u4e09\u89d2\u5f62\u53ef\u80fd\u4e3a\u7a7a\u6216\u5305\u542b\u4efb\u610f\u503c\u3002\n\n        // \u5728\u5fc5\u987b\u89e3\u51b3\u5177\u6709\u76f8\u540c\u7a00\u758f\u6a21\u5f0f\u7684\u591a\u4e2a\u95ee\u9898\u7684\u60c5\u51b5\u4e0b\uff0c\u53ef\u4ee5\u5c06\u201c\u8ba1\u7b97\u201d\u6b65\u9aa4\u5206\u89e3\u5982\u4e0b\uff1a\n\n        // SolverClassName<SparseMatrix<double>> \u6c42\u89e3\u5668;\n        // Solver.analyzePattern\uff08A\uff09; //\u5bf9\u4e8e\u6b64\u6b65\u9aa4\uff0c\u4e0d\u4f7f\u7528A\u7684\u6570\u503c\n        // resolver.factorize\uff08A\uff09;\n        // x1 = Solver.solve\uff08b1\uff09;\n        // x2 = Solver.solve\uff08b2\uff09;\n        // ... A = ...; //\u4fee\u6539A\u7684\u975e\u96f6\u503c\uff0c\u975e\u96f6\u6a21\u5f0f\u5fc5\u987b\u4fdd\u6301\u4e0d\u53d8\n        // resolver.factorize\uff08A\uff09;\n        // x1 = Solver.solve\uff08b1\uff09;\n        // x2 = Solver.solve\uff08b2\uff09;\n        // ...\n\n        // \u8be5compute\uff08\uff09\u65b9\u6cd5\u7b49\u6548\u4e8e\u8c03\u7528analyzerPattern\uff08\uff09\u548cfactorize\uff08\uff09\u3002\n\n        // \u6bcf\u4e2a\u6c42\u89e3\u5668\u90fd\u63d0\u4f9b\u4e00\u4e9b\u7279\u5b9a\u529f\u80fd\uff0c\u4f8b\u5982\u884c\u5217\u5f0f\uff0c\u5bf9\u56e0\u5b50\u7684\u8bbf\u95ee\uff0c\u8fed\u4ee3\u63a7\u5236\u7b49\u3002\u6709\u5173\u66f4\u591a\u8be6\u7ec6\u4fe1\u606f\uff0c\u8bf7\u53c2\u89c1\u76f8\u5e94\u7c7b\u7684\u6587\u6863\u3002\n\n        // \u6700\u540e\uff0c\u5927\u591a\u6570\u8fed\u4ee3\u6c42\u89e3\u5668\u4e5f\u53ef\u4ee5\u5728\u65e0\u77e9\u9635\u7684\u4e0a\u4e0b\u6587\u4e2d\u4f7f\u7528\uff0c\u8bf7\u53c2\u89c1\u4ee5\u4e0b\u793a\u4f8b\u3002\n}\n\nvoid TheComputeStep()\n{\n        // \u5728compute\uff08\uff09\u51fd\u6570\u4e2d\uff0c\u901a\u5e38\u5bf9\u77e9\u9635\u8fdb\u884c\u56e0\u5b50\u5206\u89e3\uff1aLLT\u7528\u4e8e\u81ea\u4f34\u968f\u77e9\u9635\uff0cLDLT\u7528\u4e8e\u666e\u901a\u57c3\u5c14\u7c73\u7279\u77e9\u9635\uff0cLU\u7528\u4e8e\u975e\u57c3\u5c14\u7c73\u7279\u77e9\u9635\uff0cQR\u7528\u4e8e\u77e9\u5f62\u77e9\u9635\u3002\n        //  \u8fd9\u4e9b\u662f\u4f7f\u7528\u76f4\u63a5\u6c42\u89e3\u5668\u7684\u7ed3\u679c\u3002\u5bf9\u4e8e\u8fd9\u7c7b\u6c42\u89e3\u5668\uff0c\u5c06\u8ba1\u7b97\u6b65\u9aa4\u8fdb\u4e00\u6b65\u7ec6\u5206\u4e3aanalyzerPattern\uff08\uff09\u548cfactorize\uff08\uff09\u3002\n\n        // analyticsPattern\uff08\uff09\u7684\u76ee\u6807\u662f\u5bf9\u77e9\u9635\u7684\u975e\u96f6\u5143\u7d20\u8fdb\u884c\u91cd\u65b0\u6392\u5e8f\uff0c\u4ee5\u4f7f\u5206\u89e3\u6b65\u9aa4\u521b\u5efa\u7684\u586b\u5145\u66f4\u5c11\u3002\n        //\u6b64\u6b65\u9aa4\u4ec5\u5229\u7528\u77e9\u9635\u7684\u7ed3\u6784\u3002\u56e0\u6b64\uff0c\u8be5\u6b65\u9aa4\u7684\u7ed3\u679c\u53ef\u7528\u4e8e\u77e9\u9635\u7ed3\u6784\u76f8\u540c\u7684\u5176\u4ed6\u7ebf\u6027\u7cfb\u7edf\u3002\n        //\u4f46\u662f\u8bf7\u6ce8\u610f\uff0c\u6709\u65f6\u67d0\u4e9b\u5916\u90e8\u6c42\u89e3\u5668\uff08\u4f8b\u5982SuperLU\uff09\u8981\u6c42\u5728\u6b64\u6b65\u9aa4\u4e2d\u8bbe\u7f6e\u77e9\u9635\u7684\u503c\uff0c\u4ee5\u5e73\u8861\u77e9\u9635\u7684\u884c\u548c\u5217\u3002\n        // \u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u6b64\u6b65\u9aa4\u7684\u7ed3\u679c\u4e0d\u5e94\u4e0e\u5176\u4ed6\u77e9\u9635\u4e00\u8d77\u4f7f\u7528\u3002\n\n        // Eigen\u5728\u6b64\u6b65\u9aa4\u4e2d\u63d0\u4f9b\u4e86\u4e00\u7ec4\u6709\u9650\u7684\u65b9\u6cd5\u6765\u5bf9\u77e9\u9635\u8fdb\u884c\u91cd\u65b0\u6392\u5e8f\uff0c\u8fd9\u4e9b\u65b9\u6cd5\u53ef\u4ee5\u662f\u5185\u7f6e\u7684\uff08COLAMD\uff0cAMD\uff09\u6216\u5916\u90e8\u7684\uff08METIS\uff09\u3002\n        // \u8fd9\u4e9b\u65b9\u6cd5\u5728\u6c42\u89e3\u5668\u7684\u6a21\u677f\u53c2\u6570\u5217\u8868\u4e2d\u8bbe\u7f6e\uff1a\n\n        // DirectSolverClassName <SparseMatrix <double>\uff0cOrderingMethod <IndexType>> solver;\n        // \u6709\u5173\u53ef\u7528\u65b9\u6cd5\u548c\u76f8\u5173\u9009\u9879\u7684\u5217\u8868\uff0c\u8bf7\u53c2\u89c1OrderingMethods\u6a21\u5757\u3002\n\n        // \u5728factorize\uff08\uff09\u4e2d\uff0c\u8ba1\u7b97\u7cfb\u6570\u77e9\u9635\u7684\u56e0\u6570\u3002\u6bcf\u5f53\u77e9\u9635\u503c\u66f4\u6539\u65f6\uff0c\u90fd\u5e94\u8c03\u7528\u6b64\u6b65\u9aa4\u3002\u4f46\u662f\uff0c\u77e9\u9635\u7684\u7ed3\u6784\u6a21\u5f0f\u4e0d\u5e94\u5728\u591a\u4e2a\u8c03\u7528\u4e4b\u95f4\u6539\u53d8\u3002\n\n        // \u5bf9\u4e8e\u8fed\u4ee3\u6c42\u89e3\u5668\uff0c\u8ba1\u7b97\u6b65\u9aa4\u7528\u4e8e\u6700\u7ec8\u8bbe\u7f6e\u9884\u5904\u7406\u5668\u3002\u4f8b\u5982\uff0c\u4f7f\u7528ILUT\u9884\u5904\u7406\u5668\uff0c\u5728\u6b64\u6b65\u9aa4\u4e2d\u8ba1\u7b97\u4e0d\u5b8c\u5168\u56e0\u5b50L\u548cU\u3002\n        // \u8bf7\u8bb0\u4f4f\uff0c\u57fa\u672c\u4e0a\uff0c\u9884\u5904\u7406\u5668\u7684\u76ee\u6807\u662f\u901a\u8fc7\u89e3\u51b3\u7cfb\u6570\u77e9\u9635\u5177\u6709\u66f4\u591a\u805a\u7c7b\u7279\u5f81\u503c\u7684\u6539\u8fdb\u7ebf\u6027\u7cfb\u7edf\u6765\u52a0\u5feb\u8fed\u4ee3\u65b9\u6cd5\u7684\u6536\u655b\u901f\u5ea6\u3002\n        //\u5bf9\u4e8e\u5b9e\u9645\u95ee\u9898\uff0c\u8fed\u4ee3\u6c42\u89e3\u5668\u5e94\u59cb\u7ec8\u4e0e\u524d\u7f6e\u6761\u4ef6\u4e00\u8d77\u4f7f\u7528\u3002\u5728Eigen\u4e2d\uff0c\u53ea\u9700\u5c06\u9884\u5904\u7406\u5668\u4f5c\u4e3a\u6a21\u677f\u53c2\u6570\u6dfb\u52a0\u5230\u8fed\u4ee3\u6c42\u89e3\u5668\u5bf9\u8c61\u4e2d\uff0c\u5373\u53ef\u9009\u62e9\u9884\u5904\u7406\u5668\u3002\n\n        // IterativeSolverClassName <SparseMatrix <double>\uff0cPreconditionerName <SparseMatrix <double>>\u6c42\u89e3\u5668;\n        // \u6210\u5458\u51fd\u6570preconditioner\uff08\uff09\u8fd4\u56de\u5bf9preconditioner\u7684\u8bfb\u5199\u5f15\u7528\u4ee5\u76f4\u63a5\u4e0e\u5176\u4ea4\u4e92\u3002\u6709\u5173\u53ef\u7528\u65b9\u6cd5\u7684\u5217\u8868\uff0c\u8bf7\u53c2\u89c1\u8fed\u4ee3\u6c42\u89e3\u5668\u6a21\u5757\u548c\u6bcf\u4e2a\u7c7b\u7684\u6587\u6863\u3002\n}\n\nvoid TheSolveStep()\n{\n        //resolve()\u51fd\u6570\u8ba1\u7b97\u5177\u6709\u4e00\u4e2a\u6216\u591a\u4e2a\u53f3\u4fa7\u7684\u7ebf\u6027\u7cfb\u7edf\u7684\u89e3\u3002\n        // X = Solver.solve\uff08B\uff09;\n        // \u5728\u6b64\uff0cB\u53ef\u4ee5\u662f\u5411\u91cf\u6216\u77e9\u9635\uff0c\u5176\u4e2d\u5404\u5217\u5f62\u6210\u4e0d\u540c\u7684\u53f3\u4fa7\u3002\u53ef\u4ee5\u591a\u6b21\u8c03\u7528solve\uff08\uff09\u51fd\u6570\uff0c\u4f8b\u5982\uff0c\u5f53\u6240\u6709\u53f3\u4fa7\u90fd\u65e0\u6cd5\u540c\u65f6\u4f7f\u7528\u65f6\u3002\n\n        // x1 = Solver.solve\uff08b1\uff09;\n        // //\u83b7\u5f97\u7b2c\u4e8c\u4e2a\u53f3\u4fa7b2\n        // x2 = Solver.solve\uff08b2\uff09;\n        // // ...\n        // \u5bf9\u4e8e\u76f4\u63a5\u65b9\u6cd5\uff0c\u89e3\u51b3\u65b9\u6848\u4ee5\u673a\u5668\u7cbe\u5ea6\u8ba1\u7b97\u3002\n        // \u6709\u65f6\uff0c\u89e3\u51b3\u65b9\u6848\u4e0d\u5fc5\u592a\u7cbe\u786e\u3002\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c\u8fed\u4ee3\u65b9\u6cd5\u66f4\u5408\u9002\uff0c\u5e76\u4e14\u53ef\u4ee5\u5728\u4f7f\u7528setTolerance\uff08\uff09\u7684\u6c42\u89e3\u6b65\u9aa4\u4e4b\u524d\u8bbe\u7f6e\u6240\u9700\u7684\u7cbe\u5ea6\u3002\n        // \u6709\u5173\u6240\u6709\u53ef\u7528\u529f\u80fd\uff0c\u8bf7\u53c2\u9605\u201c \u8fed\u4ee3\u6c42\u89e3\u5668\u201d\u6a21\u5757\u7684\u6587\u6863\u3002\n}\n\nvoid BenchmarkRoutine()\n{\n\n        // \u5927\u591a\u6570\u65f6\u5019\uff0c\u60a8\u9700\u8981\u77e5\u9053\u7684\u662f\u89e3\u51b3\u7cfb\u7edf\u6240\u9700\u7684\u65f6\u95f4\uff0c\u5e76\u5e0c\u671b\u4ec0\u4e48\u662f\u6700\u5408\u9002\u7684\u6c42\u89e3\u5668\u3002\n        // \u5728Eigen\u4e2d\uff0c\u6211\u4eec\u63d0\u4f9b\u4e86\u53ef\u7528\u4e8e\u6b64\u76ee\u7684\u7684\u57fa\u51c6\u4f8b\u7a0b\u3002\u8fd9\u662f\u975e\u5e38\u5bb9\u6613\u4f7f\u7528\u3002\n        // \u5728\u6784\u5efa\u76ee\u5f55\u4e2d\uff0c\u5bfc\u822a\u5230bench / spbench\u5e76\u901a\u8fc7\u952e\u5165make spbenchsolver\u6765\u7f16\u8bd1\u4f8b\u7a0b\u3002\n        // \u4f7f\u7528\u2013help\u9009\u9879\u8fd0\u884c\u5b83\u4ee5\u83b7\u53d6\u6240\u6709\u53ef\u7528\u9009\u9879\u7684\u5217\u8868\u3002\u57fa\u672c\u4e0a\uff0c\u8981\u6d4b\u8bd5\u7684\u77e9\u9635\u5e94\u4e3aMatrixMarket\u5750\u6807\u683c\u5f0f\uff0c\u5e76\u4e14\u4f8b\u7a0b\u4eceEigen\u4e2d\u6240\u6709\u53ef\u7528\u6c42\u89e3\u5668\u8fd4\u56de\u7edf\u8ba1\u4fe1\u606f\u3002\n        // \u8981\u4ee5\u77e9\u9635\u5e02\u573a\u683c\u5f0f\u5bfc\u51fa\u77e9\u9635\u548c\u53f3\u4fa7\u77e2\u91cf\uff0c\u53ef\u4ee5\u4f7f\u7528\u4e0d\u53d7\u652f\u6301\u7684SparseExtra\u6a21\u5757\uff1a\n        // #include <unsupported / Eigen / SparseExtra>\n        // ...\n        // Eigen :: saveMarket\uff08A\uff0c\u201c filename.mtx\u201d\uff09;\n        // Eigen :: saveMarket\uff08A\uff0c\u201c filename_SPD.mtx\u201d\uff0cEigen :: Symmetric\uff09; //\u5982\u679cA\u4e3a\u5bf9\u79f0\u6b63\u5b9a\n        // Eigen :: saveMarketVector\uff08B\uff0c\u201c filename_b.mtx\u201d\uff09;\n        // \u4e0b\u8868\u63d0\u4f9b\u4e86\u4e00\u4e9bEigen\u5185\u7f6e\u548c\u5916\u90e8\u6c42\u89e3\u5668\u7684XML\u7edf\u8ba1\u4fe1\u606f\u793a\u4f8b\u3002\n        // \u53c2\u89c1\u6587\u6863\uff0c\u8fd9\u91cc\u4e0d\u5217\u51fa\u4e86\n}\n} // namespace Section2_SolveSparseLinearSystems\n\n} // namespace Chapter3_SparseLinearAlgebra\n#endif", "meta": {"hexsha": "3851fce0942b60d40e7387f84f9f7e55c02ffdac", "size": 7853, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ICP/EigenChineseDocument-master/Eigen/Chapter3_SparseLinearAlgebra/Section2_SolveSparseLinearSystems.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/Section2_SolveSparseLinearSystems.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/Section2_SolveSparseLinearSystems.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": 41.7712765957, "max_line_length": 242, "alphanum_fraction": 0.6801222463, "num_tokens": 3243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.7981867777396211, "lm_q1q2_score": 0.6002465019413765}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * testTriangulation.cpp\n *\n *  Created on: July 30th, 2013\n *      Author: cbeall3\n */\n\n#include <gtsam/geometry/triangulation.h>\n#include <gtsam/geometry/Cal3Bundler.h>\n#include <CppUnitLite/TestHarness.h>\n\n#include <boost/assign.hpp>\n#include <boost/assign/std/vector.hpp>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace boost::assign;\n\n// Some common constants\n\nstatic const boost::shared_ptr<Cal3_S2> sharedCal = //\n    boost::make_shared<Cal3_S2>(1500, 1200, 0, 640, 480);\n\n// Looking along X-axis, 1 meter above ground plane (x-y)\nstatic const Rot3 upright = Rot3::ypr(-M_PI / 2, 0., -M_PI / 2);\nstatic const Pose3 pose1 = Pose3(upright, gtsam::Point3(0, 0, 1));\nPinholeCamera<Cal3_S2> camera1(pose1, *sharedCal);\n\n// create second camera 1 meter to the right of first camera\nstatic const Pose3 pose2 = pose1 * Pose3(Rot3(), Point3(1, 0, 0));\nPinholeCamera<Cal3_S2> camera2(pose2, *sharedCal);\n\n// landmark ~5 meters infront of camera\nstatic const Point3 landmark(5, 0.5, 1.2);\n\n// 1. Project two landmarks into two cameras and triangulate\nPoint2 z1 = camera1.project(landmark);\nPoint2 z2 = camera2.project(landmark);\n\n//******************************************************************************\nTEST( triangulation, twoPoses) {\n\n  vector<Pose3> poses;\n  vector<Point2> measurements;\n\n  poses += pose1, pose2;\n  measurements += z1, z2;\n\n  bool optimize = true;\n  double rank_tol = 1e-9;\n\n  boost::optional<Point3> triangulated_landmark = triangulatePoint3(poses,\n      sharedCal, measurements, rank_tol, optimize);\n  EXPECT(assert_equal(landmark, *triangulated_landmark, 1e-2));\n\n  // 2. Add some noise and try again: result should be ~ (4.995, 0.499167, 1.19814)\n  measurements.at(0) += Point2(0.1, 0.5);\n  measurements.at(1) += Point2(-0.2, 0.3);\n\n  boost::optional<Point3> triangulated_landmark_noise = triangulatePoint3(poses,\n      sharedCal, measurements, rank_tol, optimize);\n  EXPECT(assert_equal(landmark, *triangulated_landmark_noise, 1e-2));\n}\n\n//******************************************************************************\n\nTEST( triangulation, twoPosesBundler) {\n\n  boost::shared_ptr<Cal3Bundler> bundlerCal = //\n      boost::make_shared<Cal3Bundler>(1500, 0, 0, 640, 480);\n  PinholeCamera<Cal3Bundler> camera1(pose1, *bundlerCal);\n  PinholeCamera<Cal3Bundler> camera2(pose2, *bundlerCal);\n\n  // 1. Project two landmarks into two cameras and triangulate\n  Point2 z1 = camera1.project(landmark);\n  Point2 z2 = camera2.project(landmark);\n\n  vector<Pose3> poses;\n  vector<Point2> measurements;\n\n  poses += pose1, pose2;\n  measurements += z1, z2;\n\n  bool optimize = true;\n  double rank_tol = 1e-9;\n\n  boost::optional<Point3> triangulated_landmark = triangulatePoint3(poses,\n      bundlerCal, measurements, rank_tol, optimize);\n  EXPECT(assert_equal(landmark, *triangulated_landmark, 1e-2));\n\n  // 2. Add some noise and try again: result should be ~ (4.995, 0.499167, 1.19814)\n  measurements.at(0) += Point2(0.1, 0.5);\n  measurements.at(1) += Point2(-0.2, 0.3);\n\n  boost::optional<Point3> triangulated_landmark_noise = triangulatePoint3(poses,\n      bundlerCal, measurements, rank_tol, optimize);\n  EXPECT(assert_equal(landmark, *triangulated_landmark_noise, 1e-2));\n}\n\n//******************************************************************************\nTEST( triangulation, fourPoses) {\n  vector<Pose3> poses;\n  vector<Point2> measurements;\n\n  poses += pose1, pose2;\n  measurements += z1, z2;\n\n  boost::optional<Point3> triangulated_landmark = triangulatePoint3(poses,\n      sharedCal, measurements);\n  EXPECT(assert_equal(landmark, *triangulated_landmark, 1e-2));\n\n  // 2. Add some noise and try again: result should be ~ (4.995, 0.499167, 1.19814)\n  measurements.at(0) += Point2(0.1, 0.5);\n  measurements.at(1) += Point2(-0.2, 0.3);\n\n  boost::optional<Point3> triangulated_landmark_noise = //\n      triangulatePoint3(poses, sharedCal, measurements);\n  EXPECT(assert_equal(landmark, *triangulated_landmark_noise, 1e-2));\n\n  // 3. Add a slightly rotated third camera above, again with measurement noise\n  Pose3 pose3 = pose1 * Pose3(Rot3::ypr(0.1, 0.2, 0.1), Point3(0.1, -2, -.1));\n  SimpleCamera camera3(pose3, *sharedCal);\n  Point2 z3 = camera3.project(landmark);\n\n  poses += pose3;\n  measurements += z3 + Point2(0.1, -0.1);\n\n  boost::optional<Point3> triangulated_3cameras = //\n      triangulatePoint3(poses, sharedCal, measurements);\n  EXPECT(assert_equal(landmark, *triangulated_3cameras, 1e-2));\n\n  // Again with nonlinear optimization\n  boost::optional<Point3> triangulated_3cameras_opt = triangulatePoint3(poses,\n      sharedCal, measurements, 1e-9, true);\n  EXPECT(assert_equal(landmark, *triangulated_3cameras_opt, 1e-2));\n\n  // 4. Test failure: Add a 4th camera facing the wrong way\n  Pose3 pose4 = Pose3(Rot3::ypr(M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));\n  SimpleCamera camera4(pose4, *sharedCal);\n\n#ifdef GTSAM_THROW_CHEIRALITY_EXCEPTION\n  CHECK_EXCEPTION(camera4.project(landmark);, CheiralityException);\n\n  poses += pose4;\n  measurements += Point2(400, 400);\n\n  CHECK_EXCEPTION(triangulatePoint3(poses, sharedCal, measurements),\n      TriangulationCheiralityException);\n#endif\n}\n\n//******************************************************************************\nTEST( triangulation, fourPoses_distinct_Ks) {\n  Cal3_S2 K1(1500, 1200, 0, 640, 480);\n  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)\n  SimpleCamera camera1(pose1, K1);\n\n  // create second camera 1 meter to the right of first camera\n  Cal3_S2 K2(1600, 1300, 0, 650, 440);\n  SimpleCamera camera2(pose2, K2);\n\n  // 1. Project two landmarks into two cameras and triangulate\n  Point2 z1 = camera1.project(landmark);\n  Point2 z2 = camera2.project(landmark);\n\n  vector<SimpleCamera> cameras;\n  vector<Point2> measurements;\n\n  cameras += camera1, camera2;\n  measurements += z1, z2;\n\n  boost::optional<Point3> triangulated_landmark = //\n      triangulatePoint3(cameras, measurements);\n  EXPECT(assert_equal(landmark, *triangulated_landmark, 1e-2));\n\n  // 2. Add some noise and try again: result should be ~ (4.995, 0.499167, 1.19814)\n  measurements.at(0) += Point2(0.1, 0.5);\n  measurements.at(1) += Point2(-0.2, 0.3);\n\n  boost::optional<Point3> triangulated_landmark_noise = //\n      triangulatePoint3(cameras, measurements);\n  EXPECT(assert_equal(landmark, *triangulated_landmark_noise, 1e-2));\n\n  // 3. Add a slightly rotated third camera above, again with measurement noise\n  Pose3 pose3 = pose1 * Pose3(Rot3::ypr(0.1, 0.2, 0.1), Point3(0.1, -2, -.1));\n  Cal3_S2 K3(700, 500, 0, 640, 480);\n  SimpleCamera camera3(pose3, K3);\n  Point2 z3 = camera3.project(landmark);\n\n  cameras += camera3;\n  measurements += z3 + Point2(0.1, -0.1);\n\n  boost::optional<Point3> triangulated_3cameras = //\n      triangulatePoint3(cameras, measurements);\n  EXPECT(assert_equal(landmark, *triangulated_3cameras, 1e-2));\n\n  // Again with nonlinear optimization\n  boost::optional<Point3> triangulated_3cameras_opt = triangulatePoint3(cameras,\n      measurements, 1e-9, true);\n  EXPECT(assert_equal(landmark, *triangulated_3cameras_opt, 1e-2));\n\n  // 4. Test failure: Add a 4th camera facing the wrong way\n  Pose3 pose4 = Pose3(Rot3::ypr(M_PI / 2, 0., -M_PI / 2), Point3(0, 0, 1));\n  Cal3_S2 K4(700, 500, 0, 640, 480);\n  SimpleCamera camera4(pose4, K4);\n\n#ifdef GTSAM_THROW_CHEIRALITY_EXCEPTION\n  CHECK_EXCEPTION(camera4.project(landmark);, CheiralityException);\n\n  cameras += camera4;\n  measurements += Point2(400, 400);\n  CHECK_EXCEPTION(triangulatePoint3(cameras, measurements),\n      TriangulationCheiralityException);\n#endif\n}\n\n//******************************************************************************\nTEST( triangulation, twoIdenticalPoses) {\n  // create first camera. Looking along X-axis, 1 meter above ground plane (x-y)\n  SimpleCamera camera1(pose1, *sharedCal);\n\n  // 1. Project two landmarks into two cameras and triangulate\n  Point2 z1 = camera1.project(landmark);\n\n  vector<Pose3> poses;\n  vector<Point2> measurements;\n\n  poses += pose1, pose1;\n  measurements += z1, z1;\n\n  CHECK_EXCEPTION(triangulatePoint3(poses, sharedCal, measurements),\n      TriangulationUnderconstrainedException);\n}\n\n//******************************************************************************\n/*\n TEST( triangulation, onePose) {\n // we expect this test to fail with a TriangulationUnderconstrainedException\n // because there's only one camera observation\n\n Cal3_S2 *sharedCal(1500, 1200, 0, 640, 480);\n\n vector<Pose3> poses;\n vector<Point2> measurements;\n\n poses += Pose3();\n measurements += Point2();\n\n CHECK_EXCEPTION(triangulatePoint3(poses, measurements, *sharedCal),\n TriangulationUnderconstrainedException);\n }\n */\n\n//******************************************************************************\nTEST( triangulation, TriangulationFactor ) {\n  // Create the factor with a measurement that is 3 pixels off in x\n  Key pointKey(1);\n  SharedNoiseModel model;\n  typedef TriangulationFactor<> Factor;\n  Factor factor(camera1, z1, model, pointKey);\n\n  // Use the factor to calculate the Jacobians\n  Matrix HActual;\n  factor.evaluateError(landmark, HActual);\n\n//  Matrix expectedH1 = numericalDerivative11<Pose3>(\n//      boost::bind(&EssentialMatrixConstraint::evaluateError, &factor, _1, pose2,\n//          boost::none, boost::none), pose1);\n  // The expected Jacobian\n  Matrix HExpected = numericalDerivative11<Point3>(\n      boost::bind(&Factor::evaluateError, &factor, _1, boost::none), landmark);\n\n  // Verify the Jacobians are correct\n  CHECK(assert_equal(HExpected, HActual, 1e-3));\n}\n\n//******************************************************************************\nint main() {\n  TestResult tr;\n  return TestRegistry::runAllTests(tr);\n}\n//******************************************************************************\n", "meta": {"hexsha": "51c195d32537cdb1607ba570bd1e6edae4dd8f60", "size": 10138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/tests/testTriangulation.cpp", "max_stars_repo_name": "ashariati/gtsam-3.2.1", "max_stars_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T08:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T08:01:42.000Z", "max_issues_repo_path": "gtsam/geometry/tests/testTriangulation.cpp", "max_issues_repo_name": "ashariati/gtsam-3.2.1", "max_issues_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T16:21:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-13T16:50:42.000Z", "max_forks_repo_path": "gtsam/geometry/tests/testTriangulation.cpp", "max_forks_repo_name": "ashariati/gtsam-3.2.1", "max_forks_repo_head_hexsha": "f880365c259eb7532b9c1d20979ecad2eb04779c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2015-06-01T11:22:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T11:03:57.000Z", "avg_line_length": 34.4829931973, "max_line_length": 83, "alphanum_fraction": 0.6601893865, "num_tokens": 2873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6002464930690118}}
{"text": "\n#include <mplot++/mplot++.h>\n#include <Eigen/Dense>\n#include <iostream>\n#include <pybind11/eigen.h>\n#include <pybind11/embed.h>\n\nnamespace ei = Eigen;\nnamespace py = pybind11;\nusing namespace py::literals;\nnamespace mp = mplotpp;\n\nint\nmain()\n{\n  ei::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  ei::VectorXd v(2);\n  v << 1, 2;\n\n  py::scoped_interpreter guard;\n\n  auto pym = py::cast(m);\n  py::print(\"pym = \", pym);\n  py::print(\"m = \", m);\n  py::print(\"v = \", v);\n  py::print(\"m*v = \", m * v);\n\n  ei::ArrayXd x(4);\n  x << 0, 1, 2, 3;\n  ei::ArrayXd y = x.pow(2);\n\n  std::cout << \"x = \" << x << std::endl;\n  std::cout << \"y = \" << y << std::endl;\n\n  py::module_ plt = py::module_::import(\"matplotlib.pyplot\");\n\n  auto [fig, ax] = mp::tuple<2>(plt.attr(\"subplots\")());\n\n  ax.attr(\"plot\")(x, y, \"r\");\n  plt.attr(\"show\")();\n}", "meta": {"hexsha": "1c15e8f4222bf44f6554d0c19e51c9a2c73af1d0", "size": 906, "ext": "cc", "lang": "C++", "max_stars_repo_path": "development/eigen.cc", "max_stars_repo_name": "TassieBruce/mplot-pybind", "max_stars_repo_head_hexsha": "fbed1a131d9fead0dae363b9988daa57ca018330", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "development/eigen.cc", "max_issues_repo_name": "TassieBruce/mplot-pybind", "max_issues_repo_head_hexsha": "fbed1a131d9fead0dae363b9988daa57ca018330", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "development/eigen.cc", "max_forks_repo_name": "TassieBruce/mplot-pybind", "max_forks_repo_head_hexsha": "fbed1a131d9fead0dae363b9988daa57ca018330", "max_forks_repo_licenses": ["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.2765957447, "max_line_length": 61, "alphanum_fraction": 0.5342163355, "num_tokens": 359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732855, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6001974102330798}}
{"text": "/**\n * @file ConsensusCluster.hpp\n * @brief Implementation of consensus clustering using Armadillo.\n * @author Sriram P. Chockalingam <srirampc@gatech.edu>\n * @version 1.0\n * @date 2021-01-05\n *\n * Copyright 2021 Georgia Institute of Technology\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#ifndef DETAIL_CONSENSUSCLUSTER_HPP_\n#define DETAIL_CONSENSUSCLUSTER_HPP_\n\n#include \"utils/Logging.hpp\"\n\n#include <armadillo>\n\n\ntemplate <typename MatType>\nMatType\nload_csv_mat(\n  const char *file_name\n)\n{\n  // load matrix from csv file\n  MatType X;\n  X.load(file_name, arma::csv_ascii);\n  return X;\n}\n\ntemplate <bool Norm, typename RandomIt, typename MatType>\ndouble\nclusterScore(const MatType&, const RandomIt, const RandomIt);\n\ntemplate <bool Norm, typename RandomIt>\ndouble\nclusterScore(\n  const arma::mat& A,\n  const RandomIt begin,\n  const RandomIt end\n)\n{\n  if (begin == end) {\n    return 0.0;\n  }\n  arma::colvec v = arma::zeros<arma::colvec>(A.n_rows);\n  for (auto it = begin; it != end; ++it) {\n    v(*it) = 1.0;\n  }\n  auto w = A * v;\n  auto score = arma::dot(v, w);\n  auto denom = static_cast<double>(Norm ? pow(arma::norm(v), 2) :\n                                          std::distance(begin, end));\n  return score / denom;\n}\n\ntemplate <bool Norm, typename RandomIt>\ndouble\nclusterScore(\n  const arma::sp_mat& A,\n  const RandomIt begin,\n  const RandomIt end\n)\n{\n  if (begin == end) {\n    return 0.0;\n  }\n  arma::sp_mat v(A.n_rows, 1);\n  for (auto it = begin; it != end; ++it) {\n    v(*it, 0) = 1.0;\n  }\n  auto w = A * v;\n  auto score = arma::dot(v, w);\n  auto denom = static_cast<double>(Norm ? pow(arma::norm(v), 2) :\n                                          std::distance(begin, end));\n  return score / denom;\n}\n\n// Identify the cluster with best score by finding the top k\n// vertices with the highest values of eigen vector that can maximize the\n// cluster score\ntemplate <typename Var, typename MatType>\nstd::pair<std::vector<Var>, double>\nbestCluster(\n  const MatType& A,\n  const arma::sp_mat&& v,\n  const double tolerance\n)\n{\n  LOG_MESSAGE_IF(v.n_cols != 1, error, \"Perron vector should have one column\");\n  LOG_MESSAGE_IF(v.n_rows != A.n_rows, error, \"Mismatch between the given row vector and matrix rows\");\n  LOG_MESSAGE_IF(v.n_rows != A.n_cols, error, \"Mismatch between the given row vector and matrix columns\");\n  // Store non-zero values in sorted descending order\n  std::set<std::pair<double, Var>, std::greater<std::pair<double, Var>>> vals;\n  for (auto vit = v.begin_col(0); vit != v.end_col(0); ++vit) {\n    // We only want to retain the elements which are greater than tolerance\n    if (std::isgreater(*vit, tolerance)) {\n      vals.insert(std::make_pair(*vit, vit.row()));\n    }\n  }\n  // Now, copy all the eligible indices in the sorted order\n  std::vector<Var> sortedIdx(vals.size());\n  std::transform(vals.begin(), vals.end(), sortedIdx.begin(),\n                 [] (const std::pair<Var, double>& vl)\n                    { return vl.second; });\n\n  auto maxScore = 0.0;\n  auto numElements = 0u;\n  // Find the top k vertices in the sorted order that maximzes the\n  // cluster score\n  const auto first = sortedIdx.cbegin();\n  auto last = first + 1;\n  for (auto k = 0u; k < sortedIdx.size(); ++k, ++last) {\n    auto thisScore = clusterScore<true>(A, first, last);\n    if (std::isgreaterequal(thisScore, maxScore)) {\n      maxScore = thisScore;\n      numElements = k + 1;\n    }\n  }\n  LOG_MESSAGE_IF(numElements > 0, info, \"Score: %g; Cluster Size: %u\",\n                                        clusterScore<false>(A, first, std::next(first, numElements)), numElements);\n  sortedIdx.resize(numElements);\n  return std::make_pair(sortedIdx, maxScore);\n}\n\n// Compute dominant eigen vector using the power method\ntemplate <typename MatType>\narma::sp_mat\nperronVector(\n  const MatType& A,\n  const double tolerance,\n  const uint32_t maxSteps\n)\n{\n  // Initial vector : unit vector with 1.0 at vertex w. the maximum weight\n  MatType rx = arma::sum(A, 1);\n  arma::sp_mat v(rx.n_rows, 1);\n  auto i = rx.index_max();\n  v(i, 0) = 1.0;\n\n  auto mu = 1.0;\n  auto diff = 1.0;\n  auto step = maxSteps;\n  for (step = 0u; (step < maxSteps) && (diff > tolerance); ++step) {\n    // Matrix - vector multiplication\n    v = A * v;\n    auto muNext = arma::norm(v);\n    // normalize\n    v = arma::normalise(v); // , p = 2);\n    // Convergence parameter\n    diff = std::abs(1.0 - muNext / mu);\n    // Update mu\n    mu = muNext;\n  }\n  LOG_MESSAGE(info, \"Number of Steps / Max Steps: %u / %u\", step, maxSteps);\n  LOG_MESSAGE_IF(step == maxSteps, info, \"Maximum number of steps reached with error = %g\", diff);\n  return v;\n}\n\n\ntemplate <typename Var, typename MatType>\nMatType\ngetSubmatrix(const MatType&, const std::vector<Var>&);\n\ntemplate <typename Var>\narma::mat\ngetSubmatrix(\n  const arma::mat& Ain,\n  const std::vector<Var>& indices\n)\n{\n  // TODO : find a better way ?\n  arma::mat Aout(indices.size(), indices.size());\n  for (auto ix = 0u; ix < Aout.n_rows; ++ix) {\n    for (auto jx = 0u; jx < Aout.n_cols; ++jx) {\n      Aout(ix, jx) = Ain(indices[ix], indices[jx]);\n    }\n  }\n  return Aout;\n}\n\ntemplate <typename Var>\narma::sp_mat\ngetSubmatrix(\n  const arma::sp_mat& Ain,\n  const std::vector<Var>& indices\n)\n{\n  // TODO : find a better way ?\n  const auto nvertices = Ain.n_rows;\n  arma::uvec map_idx(nvertices);\n  map_idx.fill(nvertices);\n  for (uint32_t ix = 0; ix < indices.size(); ++ix) {\n    map_idx[indices[ix]] = ix;\n  }\n  uint32_t submat_size = 0;\n  for (auto it = Ain.begin(); it != Ain.end(); ++it) {\n    if (map_idx[it.row()] < nvertices && map_idx[it.col()] < nvertices) {\n      ++submat_size;\n    }\n  }\n  arma::umat locations(2, submat_size, arma::fill::zeros);\n  arma::vec values(submat_size, arma::fill::zeros);\n  uint32_t idx = 0;\n  for (auto it = Ain.begin(); it != Ain.end(); ++it) {\n    if ((map_idx[it.row()] < nvertices) && (map_idx[it.col()] < nvertices)) {\n      locations(0, idx) = map_idx[it.row()];\n      locations(1, idx) = map_idx[it.col()];\n      values(idx) = *it; ++idx;\n    }\n  }\n  return arma::sp_mat(locations, values, indices.size(), indices.size());\n}\n\n// Lemon tree cluster tightening algorithm\ntemplate <typename Var, typename MatType>\nstd::multimap<Var, Var>\nperronCluster(\n  MatType&& A,\n  const double tolerance,\n  const uint32_t maxSteps,\n  const uint32_t minClustSize,\n  const double minClustScore\n)\n{\n  // set diagonal to ones as done by Lemon Tree\n  A.diag().ones();\n  // (to keep track of the original vertex id when we construct sub matrix)\n  std::vector<Var> vertexMapping(A.n_rows);\n  for (Var i = 0; i < A.n_rows; ++i) {\n    vertexMapping[i] = i;\n  }\n  std::multimap<Var, Var> vertexClusters;\n  Var clusterId = 0;\n  auto numRemaining = A.n_rows;\n  while (numRemaining >= minClustSize) {\n    // Compute PF vector and best cluster\n    auto v = perronVector(A, tolerance,  maxSteps);\n    auto best = bestCluster<Var>(A, std::move(v), tolerance);\n    auto& clusterElements = best.first;\n    numRemaining = A.n_rows - clusterElements.size();\n    // Identify remaining rows/cols\n    std::vector<Var> currElements(A.n_rows);\n    for (Var i = 0; i < A.n_rows; ++i) {\n      currElements[i] = i;\n    }\n    std::sort(clusterElements.begin(), clusterElements.end());\n    std::vector<Var> remainingElements(numRemaining);\n    // XXX: We can possibly do better here\n    std::set_difference(currElements.begin(), currElements.end(),\n                        clusterElements.begin(), clusterElements.end(),\n                        remainingElements.begin());\n    A = getSubmatrix(A, remainingElements);\n    if ((clusterElements.size() >= minClustSize) &&\n        (best.second >= minClustScore)) {\n      // Update the cluster ids of the clusters\n      for (const auto ce : clusterElements) {\n        auto vid = vertexMapping[ce];\n        vertexClusters.emplace(clusterId, vid);\n      }\n      ++clusterId;\n    }\n    // Resize matrix and update mapping\n    vertexMapping.resize(numRemaining);\n    for (auto i = 0u; i < remainingElements.size(); ++i) {\n      auto vid = vertexMapping[remainingElements[i]];\n      vertexMapping[i] = vid;\n    }\n  }\n\n  // XXX: Assign unique ids to the rest of the vertices ?\n  return vertexClusters;\n}\n\ntemplate <typename MatType, typename Set, typename Var>\nvoid\nfillCoclusteringWeights(\n  MatType& C,\n  const std::list<std::list<Set>>&& sampledClusters,\n  const Var n,\n  const double minWeight\n)\n{\n  std::list<std::unordered_map<Var, uint32_t>> varClusterMaps;\n  for (const auto& varClusters : sampledClusters) {\n    std::unordered_map<Var, uint32_t> thisMap;\n    auto c = 0u;\n    for (auto cit = varClusters.begin(); cit != varClusters.end(); ++cit, ++c) {\n      for (const auto var : *cit) {\n        thisMap[var] = c;\n      }\n    }\n    varClusterMaps.push_back(thisMap);\n  }\n  for (auto u = 0u; u < n; ++u) {\n    for (auto v = u + 1; v < n; ++v) {\n      auto cooccurrence = 0u;\n      for (const auto& varCluster : varClusterMaps) {\n        if (varCluster.at(u) == varCluster.at(v)) {\n          ++cooccurrence;\n        }\n      }\n      auto weight = static_cast<double>(cooccurrence) / sampledClusters.size();\n      if (std::isgreater(weight, minWeight)) {\n        C(u, v) = weight;\n        C(v, u) = weight;\n      }\n    }\n  }\n}\n\ntemplate <typename Var, typename Set>\nstd::multimap<Var, Var>\nconsensusCluster(\n  const std::list<std::list<Set>>&& sampledClusters,\n  const Var numVars,\n  const double minWeight,\n  const double tolerance,\n  const uint32_t maxSteps,\n  const uint32_t minClustSize,\n  const double minClustScore,\n  const bool sparse = true\n)\n{\n  if (sparse) {\n    arma::sp_mat C(numVars, numVars);\n    fillCoclusteringWeights(C, std::move(sampledClusters), numVars, minWeight);\n    return perronCluster<Var>(std::move(C), tolerance, maxSteps, minClustSize, minClustScore);\n  }\n  else {\n    arma::mat C(numVars, numVars, arma::fill::zeros);\n    fillCoclusteringWeights(C, std::move(sampledClusters), numVars, minWeight);\n    return perronCluster<Var>(std::move(C), tolerance, maxSteps, minClustSize, minClustScore);\n  }\n}\n\n#endif // DETAIL_CONSENSUSCLUSTER_HPP_\n", "meta": {"hexsha": "aaf03f2ce1da5670d6a4c579bb0baccd6999e110", "size": 10543, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "detail/ConsensusCluster.hpp", "max_stars_repo_name": "asrivast28/ParsiMoNe", "max_stars_repo_head_hexsha": "f702eaf8a4018476e6795e9c84193306c80de391", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-24T03:18:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T20:18:30.000Z", "max_issues_repo_path": "detail/ConsensusCluster.hpp", "max_issues_repo_name": "asrivast28/ParsiMoNe", "max_issues_repo_head_hexsha": "f702eaf8a4018476e6795e9c84193306c80de391", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "detail/ConsensusCluster.hpp", "max_forks_repo_name": "asrivast28/ParsiMoNe", "max_forks_repo_head_hexsha": "f702eaf8a4018476e6795e9c84193306c80de391", "max_forks_repo_licenses": ["Apache-2.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.2091690544, "max_line_length": 115, "alphanum_fraction": 0.6472541022, "num_tokens": 2962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744939732856, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6001973912095699}}
{"text": "//\n// Copyright (c) 2019-2020 CNRS INRIA\n//\n\n#include <boost/python.hpp>\n\n#include \"pinocchio/bindings/python/fwd.hpp\"\n#include \"pinocchio/bindings/python/utils/namespace.hpp\"\n#include \"pinocchio/math/rpy.hpp\"\n\nnamespace pinocchio\n{\n  namespace python\n  {\n    namespace bp = boost::python;\n\n    BOOST_PYTHON_FUNCTION_OVERLOADS(computeRpyJacobian_overload, rpy::computeRpyJacobian, 1, 2)\n    BOOST_PYTHON_FUNCTION_OVERLOADS(computeRpyJacobianInverse_overload, rpy::computeRpyJacobianInverse, 1, 2)\n    BOOST_PYTHON_FUNCTION_OVERLOADS(computeRpyJacobianTimeDerivative_overload, rpy::computeRpyJacobianTimeDerivative, 2, 3)\n\n    Eigen::Matrix3d rotate(const std::string & axis, const double ang)\n    {\n      if(axis.length() != 1U)\n          throw std::invalid_argument(std::string(\"Invalid axis: \").append(axis));\n      Eigen::Vector3d u;\n      u.setZero();\n      const char axis_ = axis[0];\n      switch(axis_)\n      {\n        case 'x': u[0] = 1.; break;\n        case 'y': u[1] = 1.; break;\n        case 'z': u[2] = 1.; break;\n        default: throw std::invalid_argument(std::string(\"Invalid axis: \").append(1U,axis_));\n      }\n\n      return Eigen::AngleAxisd(ang, u).matrix();\n    }\n\n    void exposeRpy()\n    {\n      using namespace Eigen;\n      using namespace pinocchio::rpy;\n\n      {\n        // using the rpy scope\n        bp::scope current_scope = getOrCreatePythonNamespace(\"rpy\");\n\n        bp::def(\"rpyToMatrix\",\n                static_cast<Matrix3d (*)(const double&, const double&, const double&)>(&rpyToMatrix),\n                bp::args(\"roll\", \"pitch\", \"yaw\"),\n                \"Given (r, p, y), the rotation is given as R = R_z(y)R_y(p)R_x(r),\"\n                \" where R_a(theta) denotes the rotation of theta radians axis a\");\n\n        bp::def(\"rpyToMatrix\",\n                static_cast<Matrix3d (*)(const MatrixBase<Vector3d>&)>(&rpyToMatrix),\n                bp::arg(\"rpy\"),\n                \"Given (r, p, y), the rotation is given as R = R_z(y)R_y(p)R_x(r),\"\n                \" where R_a(theta) denotes the rotation of theta radians axis a\");\n\n        bp::def(\"matrixToRpy\",\n                &matrixToRpy<Matrix3d>,\n                bp::arg(\"R\"),\n                \"Given a rotation matrix R, the angles (r, p, y) are given so that R = R_z(y)R_y(p)R_x(r),\"\n                \" where R_a(theta) denotes the rotation of theta radians axis a.\"\n                \" The angles are guaranteed to be in the ranges: r in [-pi,pi],\"\n                \" p in[-pi/2,pi/2], y in [-pi,pi]\");\n\n        bp::def(\"rotate\",\n                &rotate,\n                bp::args(\"axis\", \"ang\"),\n                \"Rotation matrix corresponding to a rotation about x, y or z\"\n                \" e.g. R = rot('x', pi / 4): rotate pi/4 rad about x axis\");\n\n        bp::def(\"computeRpyJacobian\",\n                &computeRpyJacobian<Vector3d>,\n                computeRpyJacobian_overload(\n                    bp::args(\"rpy\",\"reference_frame\"),\n                    \"Compute the Jacobian of the Roll-Pitch-Yaw conversion\"\n                    \" Given phi = (r, p, y) such that that R = R_z(y)R_y(p)R_x(r)\"\n                    \" and reference frame F (either LOCAL or WORLD),\"\n                    \" the Jacobian is such that omega_F = J_F(phi)phidot,\"\n                    \" where omega_F is the angular velocity expressed in frame F\"\n                    \" and J_F is the Jacobian computed with reference frame F\"\n                    \"\\nParameters:\\n\"\n                    \"\\trpy Roll-Pitch-Yaw vector\"\n                    \"\\treference_frame  Reference frame in which the angular velocity is expressed.\"\n                    \" Notice LOCAL_WORLD_ALIGNED is equivalent to WORLD\"\n                )\n        );\n\n        bp::def(\"computeRpyJacobianInverse\",\n                &computeRpyJacobianInverse<Vector3d>,\n                computeRpyJacobianInverse_overload(\n                    bp::args(\"rpy\",\"reference_frame\"),\n                    \"Compute the inverse Jacobian of the Roll-Pitch-Yaw conversion\"\n                    \" Given phi = (r, p, y) such that that R = R_z(y)R_y(p)R_x(r)\"\n                    \" and reference frame F (either LOCAL or WORLD),\"\n                    \" the Jacobian is such that omega_F = J_F(phi)phidot,\"\n                    \" where omega_F is the angular velocity expressed in frame F\"\n                    \" and J_F is the Jacobian computed with reference frame F\"\n                    \"\\nParameters:\\n\"\n                    \"\\trpy Roll-Pitch-Yaw vector\"\n                    \"\\treference_frame  Reference frame in which the angular velocity is expressed.\"\n                    \" Notice LOCAL_WORLD_ALIGNED is equivalent to WORLD\"\n                )\n        );\n\n        bp::def(\"computeRpyJacobianTimeDerivative\",\n                &computeRpyJacobianTimeDerivative<Vector3d, Vector3d>,\n                computeRpyJacobianTimeDerivative_overload(\n                    bp::args(\"rpy\", \"rpydot\", \"reference_frame\"),\n                    \"Compute the time derivative of the Jacobian of the Roll-Pitch-Yaw conversion\"\n                    \" Given phi = (r, p, y) such that that R = R_z(y)R_y(p)R_x(r)\"\n                    \" and reference frame F (either LOCAL or WORLD),\"\n                    \" the Jacobian is such that omega_F = J_F(phi)phidot,\"\n                    \" where omega_F is the angular velocity expressed in frame F\"\n                    \" and J_F is the Jacobian computed with reference frame F\"\n                    \"\\nParameters:\\n\"\n                    \"\\trpy Roll-Pitch-Yaw vector\"\n                    \"\\treference_frame  Reference frame in which the angular velocity is expressed.\"\n                    \" Notice LOCAL_WORLD_ALIGNED is equivalent to WORLD\"\n                )\n        );\n      }\n      \n    }\n    \n  } // namespace python\n} // namespace pinocchio\n", "meta": {"hexsha": "5d1fc09a49768f6637f0903072cad1810ce6e8ca", "size": 5746, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bindings/python/math/expose-rpy.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-05-12T03:04:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T11:43:36.000Z", "max_issues_repo_path": "bindings/python/math/expose-rpy.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-29T12:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-29T14:00:48.000Z", "max_forks_repo_path": "bindings/python/math/expose-rpy.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-31T11:00:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-26T17:07:21.000Z", "avg_line_length": 44.2, "max_line_length": 123, "alphanum_fraction": 0.5614340411, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.817574471748733, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6001973891617244}}
{"text": "/**\n * @file UpdateMatricesTest.cpp\n * @author Giulio Romualdi\n * @copyright Released under the terms of the BSD 3-Clause License\n * @date 2020\n */\n\n// Catch2\n#include <catch2/catch.hpp>\n\n// OsqpEigen\n#include <OsqpEigen/OsqpEigen.h>\n\n// eigen\n#include <Eigen/Dense>\n\n#include <cmath>\n#include <iostream>\n#include <fstream>\n\n// colors\n#define ANSI_TXT_GRN \"\\033[0;32m\"\n#define ANSI_TXT_MGT \"\\033[0;35m\" //Magenta\n#define ANSI_TXT_DFT \"\\033[0;0m\" //Console default\n#define GTEST_BOX \"[     cout ] \"\n#define COUT_GTEST ANSI_TXT_GRN << GTEST_BOX //You could add the Default\n#define COUT_GTEST_MGT COUT_GTEST << ANSI_TXT_MGT\n\n#define T 0.1\n\nvoid setDynamicsMatrices(Eigen::Matrix<double, 2, 2> &a, Eigen::Matrix<double, 2, 1> &b,\n                         Eigen::Matrix<double, 1, 2> &c,\n                         double t)\n{\n\n    double omega = 0.1132;\n    double alpha = 0.5 * sin(2 * M_PI * omega * t);\n    double beta = 2 - 1 * sin(2 * M_PI * omega * t);\n\n    a << alpha, 1,\n        0, alpha;\n\n    b << 0,\n        1;\n\n    c << beta, 0;\n}\n\nvoid setWeightMatrices(Eigen::DiagonalMatrix<double, 1> &Q, Eigen::DiagonalMatrix<double, 1> &R)\n{\n    Q.diagonal() << 10;\n    R.diagonal() << 1;\n}\n\nvoid castMPCToQPHessian(const Eigen::DiagonalMatrix<double, 1> &Q, const Eigen::DiagonalMatrix<double, 1> &R, int mpcWindow,\n                        int k, Eigen::SparseMatrix<double> &hessianMatrix)\n{\n\n    Eigen::Matrix<double, 2, 2> a;\n    Eigen::Matrix<double, 2, 1> b;\n    Eigen::Matrix<double, 1, 2> c;\n\n    hessianMatrix.resize(2*(mpcWindow+1) + 1 * mpcWindow, 2*(mpcWindow+1) + 1 * mpcWindow);\n\n    //populate hessian matrix\n    for(int i = 0; i < 2 * (mpcWindow+1) + 1 * mpcWindow; i++){\n        double t = (k + i) * T;\n        setDynamicsMatrices(a, b, c, t);\n        if(i < 2 * (mpcWindow + 1)){\n            // here the structure of the matrix c is used!\n            int pos=i%2;\n            float value = c(pos) * Q.diagonal()[0] * c(pos);\n            if(value != 0)\n                hessianMatrix.insert(i,i) = value;\n        }\n        else{\n            float value = R.diagonal()[0];\n            if(value != 0)\n                hessianMatrix.insert(i,i) = value;\n        }\n    }\n}\n\nvoid castMPCToQPGradient(const Eigen::DiagonalMatrix<double, 1> &Q, const Eigen::Matrix<double, 1, 1> &yRef, int mpcWindow,\n                         int k, Eigen::VectorXd &gradient)\n{\n\n    Eigen::Matrix<double, 2, 2> a;\n    Eigen::Matrix<double, 2, 1> b;\n    Eigen::Matrix<double, 1, 2> c;\n\n    Eigen::Matrix<double,1,1> Qy_ref;\n    Qy_ref = Q * (-yRef);\n\n    // populate the gradient vector\n    gradient = Eigen::VectorXd::Zero(2*(mpcWindow+1) + 1 *mpcWindow, 1);\n    for(int i = 0; i<2*(mpcWindow+1); i++){\n        double t = (k + i) * T;\n        setDynamicsMatrices(a, b, c, t);\n\n        int pos=i%2;\n        float value = Qy_ref(0,0) * c(pos);\n        gradient(i,0) = value;\n    }\n}\n\nvoid castMPCToQPConstraintMatrix(int mpcWindow, int k, Eigen::SparseMatrix<double> &constraintMatrix)\n{\n    constraintMatrix.resize(2*(mpcWindow+1), 2*(mpcWindow+1) + 1 * mpcWindow);\n\n    // populate linear constraint matrix\n    for(int i = 0; i<2*(mpcWindow+1); i++){\n        constraintMatrix.insert(i,i) = -1;\n    }\n\n    Eigen::Matrix<double, 2, 2> a;\n    Eigen::Matrix<double, 2, 1> b;\n    Eigen::Matrix<double, 1, 2> c;\n\n\n    for(int i = 0; i < mpcWindow; i++){\n        double t = (k + i) * T;\n        setDynamicsMatrices(a, b, c, t);\n        for(int j = 0; j<2; j++)\n            for(int k = 0; k<2; k++){\n                float value = a(j,k);\n                if(value != 0){\n                    constraintMatrix.insert(2 * (i+1) + j, 2 * i + k) = value;\n                }\n            }\n    }\n\n    for(int i = 0; i < mpcWindow; i++)\n        for(int j = 0; j < 2; j++)\n            for(int k = 0; k < 1; k++){\n                // b is constant\n                float value = b(j,k);\n                if(value != 0){\n                    constraintMatrix.insert(2*(i+1)+j, 1*i+k+2*(mpcWindow + 1)) = value;\n                }\n            }\n}\n\nvoid castMPCToQPConstraintVectors(const Eigen::Matrix<double, 2, 1> &x0,\n                                  int mpcWindow,\n                                  Eigen::VectorXd &lowerBound, Eigen::VectorXd &upperBound)\n{\n    // evaluate the lower and the upper equality vectors\n    lowerBound = Eigen::MatrixXd::Zero(2*(mpcWindow+1),1 );\n    lowerBound.block(0,0,2,1) = -x0;\n    upperBound = lowerBound;\n}\n\nbool updateHessianMatrix(OsqpEigen::Solver &solver,\n                         const Eigen::DiagonalMatrix<double, 1> &Q, const Eigen::DiagonalMatrix<double, 1> &R,\n                         int mpcWindow, int k)\n{\n    Eigen::SparseMatrix<double> hessianMatrix;\n    castMPCToQPHessian(Q, R, mpcWindow, k, hessianMatrix);\n\n    if(!solver.updateHessianMatrix(hessianMatrix))\n        return false;\n\n    return true;\n}\n\nbool updateLinearConstraintsMatrix(OsqpEigen::Solver &solver,\n                                   int mpcWindow, int k)\n{\n    Eigen::SparseMatrix<double> constraintMatrix;\n    castMPCToQPConstraintMatrix(mpcWindow, k, constraintMatrix);\n\n    if(!solver.updateLinearConstraintsMatrix(constraintMatrix))\n        return false;\n\n    return true;\n}\n\n\nvoid updateConstraintVectors(const Eigen::Matrix<double, 2, 1> &x0,\n                             Eigen::VectorXd &lowerBound, Eigen::VectorXd &upperBound)\n{\n    lowerBound.block(0,0,2,1) = -x0;\n    upperBound.block(0,0,2,1) = -x0;\n}\n\nTEST_CASE(\"MPCTest Update matrices\")\n{\n    // open the ofstream\n    std::ofstream dataStream;\n    dataStream.open (\"output.txt\");\n\n    // set the preview window\n    int mpcWindow = 100;\n\n    // allocate the dynamics matrices\n    Eigen::Matrix<double, 2, 2> a;\n    Eigen::Matrix<double, 2, 1> b;\n    Eigen::Matrix<double, 1, 2> c;\n\n    // allocate the weight matrices\n    Eigen::DiagonalMatrix<double, 1> Q;\n    Eigen::DiagonalMatrix<double, 1> R;\n\n    // allocate the initial and the reference state space\n    Eigen::Matrix<double, 2, 1> x0;\n    Eigen::Matrix<double, 1, 1> yRef;\n    Eigen::Matrix<double, 1, 1> y;\n\n    // allocate QP problem matrices and vectores\n    Eigen::SparseMatrix<double> hessian;\n    Eigen::VectorXd gradient;\n    Eigen::SparseMatrix<double> linearMatrix;\n    Eigen::VectorXd lowerBound;\n    Eigen::VectorXd upperBound;\n\n    // set the initial and the desired states\n    x0 << 0, 0;\n    yRef << 1;\n\n    // set MPC problem quantities\n    setWeightMatrices(Q, R);\n\n    // cast the MPC problem as QP problem\n    castMPCToQPHessian(Q, R, mpcWindow, 0, hessian);\n    castMPCToQPGradient(Q, yRef, mpcWindow, 0, gradient);\n    castMPCToQPConstraintMatrix(mpcWindow, 0, linearMatrix);\n    castMPCToQPConstraintVectors(x0, mpcWindow, lowerBound, upperBound);\n\n    // instantiate the solver\n    OsqpEigen::Solver solver;\n\n    // settings\n    solver.settings()->setVerbosity(false);\n    solver.settings()->setWarmStart(true);\n\n    // set the initial data of the QP solver\n    solver.data()->setNumberOfVariables(2 * (mpcWindow + 1) + 1 * mpcWindow);\n    solver.data()->setNumberOfConstraints(2 * (mpcWindow + 1));\n    REQUIRE(solver.data()->setHessianMatrix(hessian));\n    REQUIRE(solver.data()->setGradient(gradient));\n    REQUIRE(solver.data()->setLinearConstraintsMatrix(linearMatrix));\n    REQUIRE(solver.data()->setLowerBound(lowerBound));\n    REQUIRE(solver.data()->setUpperBound(upperBound));\n\n    // instantiate the solver\n    REQUIRE(solver.initSolver());\n\n    // controller input and QPSolution vector\n    Eigen::VectorXd ctr;\n    Eigen::VectorXd QPSolution;\n\n    // number of iteration steps\n    int numberOfSteps = 50;\n\n    // profiling quantities\n    clock_t startTime, endTime;\n    double avarageTime = 0;\n\n    for (int i = 0; i < numberOfSteps; i++){\n        startTime = clock();\n\n        setDynamicsMatrices(a, b, c, i * T);\n\n        // update the constraint bound\n        REQUIRE(updateHessianMatrix(solver, Q, R, mpcWindow, i));\n        REQUIRE(updateLinearConstraintsMatrix(solver, mpcWindow, i));\n\n        castMPCToQPGradient(Q, yRef, mpcWindow, i, gradient);\n        REQUIRE(solver.updateGradient(gradient));\n\n        updateConstraintVectors(x0, lowerBound, upperBound);\n        REQUIRE(solver.updateBounds(lowerBound, upperBound));\n\n        // solve the QP problem\n        REQUIRE(solver.solveProblem() == OsqpEigen::ErrorExitFlag::NoError);\n\n        // get the controller input\n        QPSolution = solver.getSolution();\n        ctr = QPSolution.block(2 * (mpcWindow + 1), 0, 1, 1);\n\n        // save data into file\n        auto x0Data = x0.data();\n        for(int j = 0; j < 2; j++)\n            dataStream << x0Data[j] << \" \";\n        dataStream << std::endl;\n\n        // propagate the model\n        x0 = a * x0 + b * ctr;\n        y = c * x0;\n\n        endTime = clock();\n\n        avarageTime += static_cast<double>(endTime - startTime) / CLOCKS_PER_SEC;\n      }\n\n    // close the stream\n    dataStream.close();\n\n    std::cout << COUT_GTEST_MGT << \"Avarage time = \" << avarageTime / numberOfSteps\n              << \" seconds.\" << ANSI_TXT_DFT << std::endl;\n}\n", "meta": {"hexsha": "f36e4a9283b59b2b7e4cd4384e6c807dd3e0add4", "size": 8996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/MPCUpdateMatricesTest.cpp", "max_stars_repo_name": "marunmurali/osqp-eigen", "max_stars_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/MPCUpdateMatricesTest.cpp", "max_issues_repo_name": "marunmurali/osqp-eigen", "max_issues_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/MPCUpdateMatricesTest.cpp", "max_forks_repo_name": "marunmurali/osqp-eigen", "max_forks_repo_head_hexsha": "f14aa34fefa4126a9a76e34c77fe3f9dfc2b0c42", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6897689769, "max_line_length": 124, "alphanum_fraction": 0.595264562, "num_tokens": 2605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6001973811427512}}
{"text": "// =========================================================================\n// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co)\n// =========================================================================\n\n#include \"ActivationFunctions.h\"\n#include <boost/algorithm/string.hpp>\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nconst std::string& ActivationFunctions::Function< _TScl >::\nname( ) const\n{\n  return( this->m_N );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nconst typename ActivationFunctions::Function< _TScl >::TScalar&\nActivationFunctions::Function< _TScl >::\nthreshold( ) const\n{\n  return( this->m_T );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::Function< _TScl >::\nTMatrix ActivationFunctions::Function< _TScl >::\nt( const TMatrix& z ) const\n{\n  return(\n    TMatrix( ( z.array( ) >= this->m_T ).template cast< TScalar >( ) )\n    );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::ArcTan< _TScl >::\nTMatrix ActivationFunctions::ArcTan< _TScl >::\nf( const TMatrix& z ) const\n{\n  return( Eigen::atan( z.array( ) ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::ArcTan< _TScl >::\nTMatrix ActivationFunctions::ArcTan< _TScl >::\nd( const TMatrix& z ) const\n{\n  return( TScalar( 1 ) / ( Eigen::pow( z.array( ), 2 ) + TScalar( 1 ) ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::BinaryStep< _TScl >::\nTMatrix ActivationFunctions::BinaryStep< _TScl >::\nf( const TMatrix& z ) const\n{\n  TMatrix r = TMatrix::Ones( z.rows( ), z.cols( ) );\n  r.array( ) *= ( z.array( ) >= 0 ).template cast< TScalar >( );\n  return( r );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::BinaryStep< _TScl >::\nTMatrix ActivationFunctions::BinaryStep< _TScl >::\nd( const TMatrix& z ) const\n{\n  return( TMatrix::Zero( z.rows( ), z.cols( ) ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::ELU< _TScl >::\nTMatrix ActivationFunctions::ELU< _TScl >::\nf( const TMatrix& z ) const\n{\n  TMatrix r( z.rows( ), z.cols( ) );\n  auto c = ( z.array( ) >= 0 ).template cast< TScalar >( );\n  r.array( ) =\n    ( c * z.array( ) ) +\n    (\n      ( ( TScalar( 1 ) - c ) * this->m_Alpha ) *\n      ( Eigen::exp( z.array( ) ) - TScalar( 1 ) )\n      );\n  return( r );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::ELU< _TScl >::\nTMatrix ActivationFunctions::ELU< _TScl >::\nd( const TMatrix& z ) const\n{\n  TMatrix e = this->f( z );\n  TMatrix r( z.rows( ), z.cols( ) );\n  auto c = ( z.array( ) < 0 ).template cast< TScalar >( );\n  r.array( ) = ( c * ( e.array( ) + this->m_Alpha ) ) + ( TScalar( 1 ) - c );\n  return( r );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::Identity< _TScl >::\nTMatrix ActivationFunctions::Identity< _TScl >::\nf( const TMatrix& z ) const\n{\n  return( z );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::Identity< _TScl >::\nTMatrix ActivationFunctions::Identity< _TScl >::\nd( const TMatrix& z ) const\n{\n  return( TMatrix::Ones( z.rows( ), z.cols( ) ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::LeakyReLU< _TScl >::\nTMatrix ActivationFunctions::LeakyReLU< _TScl >::\nf( const TMatrix& z ) const\n{\n  TMatrix r( z.rows( ), z.cols( ) );\n  auto c = ( z.array( ) >= 0 ).template cast< TScalar >( );\n  r.array( ) =\n    ( c * z.array( ) ) +\n    ( ( TScalar( 1 ) - c ) * TScalar( 1e-2 ) ) * z.array( );\n  return( r );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::LeakyReLU< _TScl >::\nTMatrix ActivationFunctions::LeakyReLU< _TScl >::\nd( const TMatrix& z ) const\n{\n  TMatrix r( z.rows( ), z.cols( ) );\n  auto c = ( z.array( ) >= 0 ).template cast< TScalar >( );\n  r.array( ) = c + ( ( TScalar( 1 ) - c ) * TScalar( 1e-2 ) );\n  return( r );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::Logistic< _TScl >::\nTMatrix ActivationFunctions::Logistic< _TScl >::\nf( const TMatrix& z ) const\n{\n  TMatrix r( z.rows( ), z.cols( ) );\n  r.array( ) = TScalar( 1 ) / ( TScalar( 1 ) + Eigen::exp( -z.array( ) ) );\n  return( r );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::Logistic< _TScl >::\nTMatrix ActivationFunctions::Logistic< _TScl >::\nd( const TMatrix& z ) const\n{\n  TMatrix e = this->f( z );\n  TMatrix r( z.rows( ), z.cols( ) );\n  r.array( ) = e.array( ) * ( TScalar( 1 ) - e.array( ) );\n  return( r );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::OutTanh< _TScl >::\nTMatrix ActivationFunctions::OutTanh< _TScl >::\nf( const TMatrix& z ) const\n{\n  return( ( z.array( ).tanh( ) + TScalar( 1 ) ) / TScalar( 2 ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::OutTanh< _TScl >::\nTMatrix ActivationFunctions::OutTanh< _TScl >::\nd( const TMatrix& z ) const\n{\n  return( ( TScalar( 1 ) - z.array( ).tanh( ).square( ) ) / TScalar( 2 ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::RandomizedReLU< _TScl >::\nTMatrix ActivationFunctions::RandomizedReLU< _TScl >::\nf( const TMatrix& z ) const\n{\n  TMatrix r( z.rows( ), z.cols( ) );\n  auto c = ( z.array( ) >= 0 ).template cast< TScalar >( );\n  r.array( ) =\n    ( c * z.array( ) ) +\n    ( ( TScalar( 1 ) - c ) * this->m_Alpha ) * z.array( );\n  return( r );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::RandomizedReLU< _TScl >::\nTMatrix ActivationFunctions::RandomizedReLU< _TScl >::\nd( const TMatrix& z ) const\n{\n  TMatrix r( z.rows( ), z.cols( ) );\n  auto c = ( z.array( ) >= 0 ).template cast< TScalar >( );\n  r.array( ) = c + ( ( TScalar( 1 ) - c ) * this->m_Alpha );\n  return( r );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::ReLU< _TScl >::\nTMatrix ActivationFunctions::ReLU< _TScl >::\nf( const TMatrix& z ) const\n{\n  TMatrix r = z;\n  r.array( ) *= ( z.array( ) >= 0 ).template cast< TScalar >( );\n  return( r );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::ReLU< _TScl >::\nTMatrix ActivationFunctions::ReLU< _TScl >::\nd( const TMatrix& z ) const\n{\n  TMatrix r = TMatrix::Ones( z.rows( ), z.cols( ) );\n  r.array( ) *= ( z.array( ) >= 0 ).template cast< TScalar >( );\n  return( r );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::SoftPlus< _TScl >::\nTMatrix ActivationFunctions::SoftPlus< _TScl >::\nf( const TMatrix& z ) const\n{\n  return( Eigen::log( Eigen::exp( z.array( ) ) + TScalar( 1 ) ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::SoftPlus< _TScl >::\nTMatrix ActivationFunctions::SoftPlus< _TScl >::\nd( const TMatrix& z ) const\n{\n  return( TScalar( 1 ) / ( TScalar( 1 ) + Eigen::exp( -z.array( ) ) ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::Tanh< _TScl >::\nTMatrix ActivationFunctions::Tanh< _TScl >::\nf( const TMatrix& z ) const\n{\n  return( z.array( ).tanh( ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::Tanh< _TScl >::\nTMatrix ActivationFunctions::Tanh< _TScl >::\nd( const TMatrix& z ) const\n{\n  return( TScalar( 1 ) - this->f( z ).array( ).square( ) );\n}\n\n// Instances\n#define _PUJ_ML_ActivationFunction_Instances( _n_, _t_ )        \\\n  template class ActivationFunctions::_n_< _t_ >\n\n#define PUJ_ML_ActivationFunction_Instances( _n_ )             \\\n  _PUJ_ML_ActivationFunction_Instances( _n_, float );          \\\n  _PUJ_ML_ActivationFunction_Instances( _n_, double );         \\\n  _PUJ_ML_ActivationFunction_Instances( _n_, long double )\n\nPUJ_ML_ActivationFunction_Instances( Function );\nPUJ_ML_ActivationFunction_Instances( ArcTan );\nPUJ_ML_ActivationFunction_Instances( BinaryStep );\nPUJ_ML_ActivationFunction_Instances( ELU );\nPUJ_ML_ActivationFunction_Instances( Identity );\nPUJ_ML_ActivationFunction_Instances( LeakyReLU );\nPUJ_ML_ActivationFunction_Instances( Logistic );\nPUJ_ML_ActivationFunction_Instances( OutTanh );\nPUJ_ML_ActivationFunction_Instances( RandomizedReLU );\nPUJ_ML_ActivationFunction_Instances( ReLU );\nPUJ_ML_ActivationFunction_Instances( SoftPlus );\nPUJ_ML_ActivationFunction_Instances( Tanh );\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nActivationFunctions::Factory< _TScl >::\nFactory( )\n{\n  this->reg_cre( \"arctan\", &ActivationFunctions::ArcTan< _TScl >::create );\n  this->reg_cre( \"binarystep\", &ActivationFunctions::BinaryStep< _TScl >::create );\n  this->reg_cre( \"elu\", &ActivationFunctions::ELU< _TScl >::create );\n  this->reg_cre( \"identity\", &ActivationFunctions::Identity< _TScl >::create );\n  this->reg_cre( \"leakyrelu\", &ActivationFunctions::LeakyReLU< _TScl >::create );\n  this->reg_cre( \"logistic\", &ActivationFunctions::Logistic< _TScl >::create );\n  this->reg_cre( \"outtanh\", &ActivationFunctions::OutTanh< _TScl >::create );\n  this->reg_cre( \"randomizedrelu\", &ActivationFunctions::RandomizedReLU< _TScl >::create );\n  this->reg_cre( \"relu\", &ActivationFunctions::ReLU< _TScl >::create );\n  this->reg_cre( \"softplus\", &ActivationFunctions::SoftPlus< _TScl >::create );\n  this->reg_cre( \"tanh\", &ActivationFunctions::Tanh< _TScl >::create );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nActivationFunctions::Factory< _TScl >::\nFactory( const Self& other )\n{\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nActivationFunctions::Factory< _TScl >::\n~Factory( )\n{\n  this->m_FactoryMap.clear( );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::Factory< _TScl >::\nSelf& ActivationFunctions::Factory< _TScl >::\noperator=( const Self& other )\n{\n  return( *this );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::Factory< _TScl >::\nSelf* ActivationFunctions::Factory< _TScl >::\nget( )\n{\n  static Self instance;\n  return( &instance );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid ActivationFunctions::Factory< _TScl >::\nreg_cre( const std::string& n, TCreator c )\n{\n  this->m_FactoryMap[ n ] = c;\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename ActivationFunctions::Factory< _TScl >::\nTFunction* ActivationFunctions::Factory< _TScl >::\ncreate( const std::string& n ) const\n{\n  typename TMap::const_iterator i =\n    this->m_FactoryMap.find( boost::algorithm::to_lower_copy( n ) );\n  if( i != this->m_FactoryMap.end( ) )\n    return( i->second( ) );\n  else\n    return( nullptr );\n}\n\n// -------------------------------------------------------------------------\nPUJ_ML_ActivationFunction_Instances( Factory );\n\n// eof - $RCSfile$\n", "meta": {"hexsha": "13c45d306403c5573bc2aae6122dd9a0409a7ed1", "size": 12331, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "examples/neural_network/ActivationFunctions.cxx", "max_stars_repo_name": "DanteCely/PUJ_ML", "max_stars_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-01T09:20:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:16:37.000Z", "max_issues_repo_path": "examples/neural_network/ActivationFunctions.cxx", "max_issues_repo_name": "DanteCely/PUJ_ML", "max_issues_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/neural_network/ActivationFunctions.cxx", "max_forks_repo_name": "DanteCely/PUJ_ML", "max_forks_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:38:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T23:17:44.000Z", "avg_line_length": 33.0589812332, "max_line_length": 91, "alphanum_fraction": 0.5229908361, "num_tokens": 3043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82446190912407, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6001880381318786}}
{"text": "/*!\n * @file\n * calculating value of pi by MC trials\n *\n * command to run:\n * mpirung -n 2 ./bin/pi 100000\n *\n * The command line argument is the total number of trials.\n *\n * benchmarks at the bottom\n * */\n#include <random>\n#include <stdexcept>\n\n#include <boost/mpi.hpp>\n\n#include <ezl.hpp>\n#include <ezl/algorithms/filters.hpp>\n#include <ezl/algorithms/io.hpp>\n#include <ezl/algorithms/reduces.hpp>\n\n// to facilitate random number generation\ntemplate <class T>\nstruct RandReal {\npublic:\n  RandReal(T min, T max) : dis{min, max} {\n    std::random_device rd;\n    gen.seed(rd());\n  }\n  double operator () () {\n    return dis(gen);\n  }\nprivate:\n  std::mt19937 gen;\n  std::uniform_real_distribution<T> dis;\n};\n\nvoid valueOfPi(int argc, char* argv[]) {\n  if (argc < 2) {\n    std::cout<<\"Please provide number of MC trials as argument\\n\";\n    return;\n  }\n  auto trials = std::stoll(argv[1]);\n\n  RandReal<double> rand01{0.0,1.0};\n\n  ezl::rise(ezl::kick(trials).split())\n    .map([&rand01] { \n      auto x = rand01();\n      auto y = rand01();\n      return x*x + y*y; \n    })\n    .filter(ezl::lt(1.))\n    .reduce(ezl::count(), 0LL).inprocess()\n    .reduce(ezl::sum(), 0LL)\n    .map([trials](long long res) { \n      return (4.0 * res / trials); \n    }).colsTransform().dump(\"\", \"pi in \" + std::to_string(trials) + \" trials:\")\n    .run();\n}\n\nint main(int argc, char *argv[]) {\n  boost::mpi::environment env(argc, argv, false);\n  try {\n    valueOfPi(argc, argv);\n  } catch (const std::exception& ex) {\n    std::cerr<<\"error: \"<<ex.what()<<'\\n';\n    env.abort(1);  \n  } catch (...) {\n    std::cerr<<\"unknown exception\\n\";\n    env.abort(2);  \n  }\n  return 0;\n}\n\n/*!\n * The benchmarks are using rand() function for random.\n * benchmark results: i7(hdd); input: 4 x 10^9; units: secs\n *  *nprocs* | 1   | 2   | 4    |\n *  ---      |---  |---  |---   |\n *  *time(s)*| 111 | 56  | 39   |\n * \n * benchmark results: Linux(nfs-3); input: variable; units: secs\n *  *nprocs* | 1x12      | 2x12      | 4x12      | 8x12      |  16x12   |\n *  ---      |---        |---        |---        | ---       |          |\n *  *trials* | 1/8x10^11 | 1/4x10^11 | 1/2x10^11 | 1x10^11   |  2x10^11 |\n *  *time(s)*| 48        | 55        | 58        | 57.5      |  59      |\n */\n", "meta": {"hexsha": "6a4a7cf6b244b716805046d639fc10daf1f45c30", "size": 2240, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/pi.cpp", "max_stars_repo_name": "YcheParallelStudio/easyLambda", "max_stars_repo_head_hexsha": "e496a3e3070b806e8c48124d3454543c4cebc9b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/pi.cpp", "max_issues_repo_name": "YcheParallelStudio/easyLambda", "max_issues_repo_head_hexsha": "e496a3e3070b806e8c48124d3454543c4cebc9b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/pi.cpp", "max_forks_repo_name": "YcheParallelStudio/easyLambda", "max_forks_repo_head_hexsha": "e496a3e3070b806e8c48124d3454543c4cebc9b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1685393258, "max_line_length": 79, "alphanum_fraction": 0.5450892857, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619177503205, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6001880346801726}}
{"text": "\n#include <vtkImageData.h>\n#include <vtkDICOMImageReader.h>\n#include <vtkImageReader.h>\n#include <vtkImageGaussianSmooth.h>\n#include <vtkDemandDrivenPipeline.h>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/Mesh_triangulation_3.h>\n#include <CGAL/Mesh_complex_3_in_triangulation_3.h>\n#include <CGAL/Mesh_criteria_3.h>\n\n#include <CGAL/Gray_image_mesh_domain_3.h>\n#include <CGAL/make_mesh_3.h>\n#include <CGAL/Image_3.h>\n#include <CGAL/read_vtk_image_data.h>\n\n#include <boost/lexical_cast.hpp>\n\ntypedef short Image_word_type;\n\n// Domain\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Gray_image_mesh_domain_3<CGAL::Image_3,K, \n                                       Image_word_type,\n                                       std::binder1st< std::less<Image_word_type> > > Mesh_domain;\n\n// Triangulation\ntypedef CGAL::Mesh_triangulation_3<Mesh_domain>::type Tr;\ntypedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3;\n\n// Criteria\ntypedef CGAL::Mesh_criteria_3<Tr> Mesh_criteria;\n\n// To avoid verbose function and named parameters call\nusing namespace CGAL::parameters;\n\nint main(int argc, char* argv[])\n{\n  // Loads image\n  if(argc == 1){\n    std::cerr << \"Usage:  \" << argv[0] << \" <directory with dicom data> iso_level=1  facet_size=1  facet_distance=0.1  cell_size=1\\n\";\n    return 0;\n  }\n\n  Image_word_type iso = (argc>2)? boost::lexical_cast<Image_word_type>(argv[2]): 1;\n  double fs = (argc>3)? boost::lexical_cast<double>(argv[3]): 1;\n  double fd = (argc>4)? boost::lexical_cast<double>(argv[4]): 0.1;\n  double cs = (argc>5)? boost::lexical_cast<double>(argv[5]): 1;\n  \n  vtkDICOMImageReader*dicom_reader = vtkDICOMImageReader::New();\n  dicom_reader->SetDirectoryName(argv[1]);\n  \n  vtkDemandDrivenPipeline*executive =\n    vtkDemandDrivenPipeline::SafeDownCast(dicom_reader->GetExecutive());\n  if (executive)\n    {\n      executive->SetReleaseDataFlag(0, 0); // where 0 is the port index\n    }\n  \n  vtkImageGaussianSmooth* smoother = vtkImageGaussianSmooth::New();\n  smoother->SetStandardDeviations(1., 1., 1.);\n  smoother->SetInputConnection(dicom_reader->GetOutputPort());\n  smoother->Update();\n  vtkImageData* vtk_image = smoother->GetOutput();\n  vtk_image->Print(std::cerr);\n  \n  CGAL::Image_3 image = CGAL::read_vtk_image_data(vtk_image);\n  if(image.image() == 0){\n    std::cerr << \"could not create a CGAL::Image_3 from the vtk image\\n\";\n    return 0;\n  }\n  // Domain\n  Mesh_domain domain(image, std::bind1st(std::less<Image_word_type>(), iso), 0);\n  \n  // Mesh criteria\n  Mesh_criteria criteria(facet_angle=30, facet_size=fs, facet_distance=fd,\n                         cell_radius_edge_ratio=3, cell_size=cs);\n  \n  // Meshing\n  C3t3 c3t3 = CGAL::make_mesh_3<C3t3>(domain, criteria);\n  \n  // Output\n  std::ofstream medit_file(\"out.mesh\");\n  c3t3.output_to_medit(medit_file);\n  \n  return 0;\n}\n", "meta": {"hexsha": "910547c279c83418df948de9cb7858a2dca2dc79", "size": 2865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Mesh_3/examples/Mesh_3/mesh_3D_gray_vtk_image.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Mesh_3/examples/Mesh_3/mesh_3D_gray_vtk_image.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Mesh_3/examples/Mesh_3/mesh_3D_gray_vtk_image.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8333333333, "max_line_length": 134, "alphanum_fraction": 0.7092495637, "num_tokens": 821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.6654105653819835, "lm_q1q2_score": 0.600147554316127}}
{"text": "#include \"software/sensor_fusion/filter/ball_filter.h\"\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <limits>\n#include <vector>\n\n#include \"shared/constants.h\"\n#include \"software/geom/algorithms/closest_point.h\"\n#include \"software/geom/algorithms/contains.h\"\n#include \"software/math/math_functions.h\"\n\n\nBallFilter::BallFilter() : ball_detection_buffer(MAX_BUFFER_SIZE) {}\n\nstd::optional<Ball> BallFilter::estimateBallState(\n    const std::vector<BallDetection> &new_ball_detections, const Rectangle &filter_area)\n{\n    addNewDetectionsToBuffer(new_ball_detections, filter_area);\n    return estimateBallStateFromBuffer(ball_detection_buffer);\n}\n\nvoid BallFilter::addNewDetectionsToBuffer(std::vector<BallDetection> new_ball_detections,\n                                          const Rectangle &filter_area)\n{\n    // Sort the detections in increasing order before processing. This places the oldest\n    // detections (with the smallest timestamp) at the front of the buffer, and the most\n    // recent detections (largest timestamp) at the end of the buffer.\n    std::sort(new_ball_detections.begin(), new_ball_detections.end());\n\n    for (const auto &detection : new_ball_detections)\n    {\n        // Remove any detections outside the filter area\n        if (!contains(filter_area, detection.position))\n        {\n            continue;\n        }\n\n        if (!ball_detection_buffer.empty())\n        {\n            // Use the smallest timestamp to minimize time_diffs of 0\n            auto detection_with_smallest_timestamp = *std::min_element(\n                ball_detection_buffer.begin(), ball_detection_buffer.end());\n            Duration time_diff =\n                detection.timestamp - detection_with_smallest_timestamp.timestamp;\n\n            // Ignore any data from the past, and any data that is as old as the oldest\n            // data in the buffer since it provides no additional value. This also\n            // prevents division by 0 when calculating the estimated velocity\n            if (time_diff.toSeconds() <= 0)\n            {\n                continue;\n            }\n\n            // We determine if the detection is noise based on how far it is from a ball\n            // detection in the buffer. From this, we can calculate how fast the ball\n            // must have moved to reach the new detection position. If this estimated\n            // velocity is too far above the maximum allowed velocity, then there is a\n            // good chance the detection is just noise and not the real ball. In this\n            // case, we ignore the new \"noise\" data\n            double detection_distance =\n                (detection.position - detection_with_smallest_timestamp.position)\n                    .length();\n            double estimated_detection_velocity_magnitude =\n                detection_distance / time_diff.toSeconds();\n\n            // Make the maximum acceptable velocity a bit larger than the strict limits\n            // according to the game rules to account for measurement error, and to be a\n            // bit on the safe side. We don't want to risk discarding real data.\n            double maximum_acceptable_velocity_magnitude =\n                BALL_MAX_SPEED_METERS_PER_SECOND + MAX_ACCEPTABLE_BALL_SPEED_BUFFER;\n            if (estimated_detection_velocity_magnitude >\n                maximum_acceptable_velocity_magnitude)\n            {\n                // If we determine the data to be noise, remove an entry from the buffer.\n                // This way if we have messed up and now the ball is too far away for the\n                // buffer to track, the buffer will rapidly shrink and start tracking the\n                // ball at its new location once the buffer is empty.\n                // We sort the vector in decreasing order first so that we can always\n                // ensure any elements that are ejected from the end of the buffer are the\n                // oldest data\n                std::sort(ball_detection_buffer.rbegin(), ball_detection_buffer.rend());\n                ball_detection_buffer.pop_back();\n            }\n            else\n            {\n                // We sort the vector in decreasing order first so that we can always\n                // ensure any elements that are ejected from the end of the buffer are the\n                // oldest data\n                std::sort(ball_detection_buffer.rbegin(), ball_detection_buffer.rend());\n                ball_detection_buffer.push_front(detection);\n            }\n        }\n        else\n        {\n            // If there is no data in the buffer, we always add the new data\n            ball_detection_buffer.push_front(detection);\n        }\n    }\n}\n\nstd::optional<Ball> BallFilter::estimateBallStateFromBuffer(\n    boost::circular_buffer<BallDetection> ball_detections)\n{\n    // Sort the detections in decreasing order before processing. This places the most\n    // recent detections (with the largest timestamp) at the front of the buffer, and the\n    // oldest detections (smallest timestamp) at the end of the buffer\n    std::sort(ball_detections.rbegin(), ball_detections.rend());\n\n    if (ball_detections.empty())\n    {\n        return std::nullopt;\n    }\n    else if (ball_detections.size() == 1)\n    {\n        // If there is only 1 entry in the buffer, we can't fit a regression line\n        // or calculate a velocity so we do our best with just the position\n        BallState ball_state(ball_detections.front().position, Vector(0, 0),\n                             ball_detections.front().distance_from_ground);\n        Ball ball(ball_state, ball_detections.front().timestamp);\n        return ball;\n    }\n\n    std::optional<size_t> adjusted_buffer_size = getAdjustedBufferSize(ball_detections);\n    if (!adjusted_buffer_size)\n    {\n        return std::nullopt;\n    }\n    ball_detections.resize(*adjusted_buffer_size);\n\n    auto regression_line = calculateLineOfBestFit(ball_detections);\n\n    Point filtered_position = estimateBallPosition(ball_detections, regression_line);\n    auto estimated_velocity = estimateBallVelocity(ball_detections, regression_line);\n    if (!estimated_velocity)\n    {\n        return std::nullopt;\n    }\n\n    BallState ball_state(filtered_position, estimated_velocity->average_velocity,\n                         ball_detections.front().distance_from_ground);\n    return Ball(ball_state, ball_detections.front().timestamp);\n}\n\nstd::optional<size_t> BallFilter::getAdjustedBufferSize(\n    boost::circular_buffer<BallDetection> ball_detections)\n{\n    // Sort the detections in decreasing order before processing. This places the most\n    // recent detections (with the largest timestamp) at the front of the buffer, and the\n    // oldest detections (smallest timestamp) at the end of the buffer\n    std::sort(ball_detections.rbegin(), ball_detections.rend());\n\n    double buffer_size_velocity_magnitude_diff =\n        MAX_BUFFER_SIZE_VELOCITY_MAGNITUDE - MIN_BUFFER_SIZE_VELOCITY_MAGNITUDE;\n\n    unsigned int max_buffer_size =\n        std::min(MAX_BUFFER_SIZE, static_cast<unsigned int>(ball_detections.size()));\n    unsigned int min_buffer_size =\n        std::min(MIN_BUFFER_SIZE, static_cast<unsigned int>(ball_detections.size()));\n    double buffer_size_diff = max_buffer_size - min_buffer_size;\n\n    std::optional<BallVelocityEstimate> velocity_estimate =\n        estimateBallVelocity(ball_detections);\n    if (!velocity_estimate)\n    {\n        return std::nullopt;\n    }\n    // Use the average of the min and max velocity magnitudes in the buffer. We use this\n    // rather than the average so we can quickly respond to drastic changes in the ball\n    // velocity, such as when the ball goes from being stationary to moving quickly (like\n    // when it's kicked). If the buffer is large, then it will take more time for the mean\n    // speed to increase enough to start shrinking the buffer. However, the average of the\n    // min and max values will immediately increase if the ball starts moving, so the\n    // buffer can start shrinking more quickly and increase the filter response time to\n    // these sorts of changes.\n    double min_max_magnitude_average = velocity_estimate->min_max_magnitude_average;\n\n    // Between the min and max velocity magnitudes, we linearly scale the size of the\n    // buffer\n    double linear_offset =\n        MIN_BUFFER_SIZE_VELOCITY_MAGNITUDE + (buffer_size_velocity_magnitude_diff / 2);\n    double linear_scaling_factor = linear(min_max_magnitude_average, linear_offset,\n                                          buffer_size_velocity_magnitude_diff);\n    int buffer_size =\n        max_buffer_size -\n        static_cast<unsigned int>(std::floor(linear_scaling_factor * buffer_size_diff));\n\n    return static_cast<size_t>(buffer_size);\n}\n\nLine BallFilter::calculateLineOfBestFit(\n    boost::circular_buffer<BallDetection> ball_detections)\n{\n    if (ball_detections.size() < 2)\n    {\n        throw std::invalid_argument(\"At least 2 elements required for linear regression\");\n    }\n\n    auto x_vs_y_regression = calculateLinearRegression(ball_detections);\n\n    // Linear regression cannot fit a vertical line. To get around this, we fit two lines,\n    // one with x and y swapped, so any vertical line becomes horizontal. Then we take the\n    // line of the two that fit the best.\n    boost::circular_buffer<BallDetection> swapped_ball_detections = ball_detections;\n    for (auto &detection : swapped_ball_detections)\n    {\n        detection.position = Point(detection.position.y(), detection.position.x());\n    }\n    auto y_vs_x_regression = calculateLinearRegression(swapped_ball_detections);\n    // Because we swapped the coordinates of the input, we have to swap the coordinates of\n    // the output to get back to our expected coordinate space\n    y_vs_x_regression.regression_line.swapXY();\n\n    // We use the regression from above with the least error\n    if (x_vs_y_regression.regression_error < y_vs_x_regression.regression_error)\n    {\n        return x_vs_y_regression.regression_line;\n    }\n    else\n    {\n        return y_vs_x_regression.regression_line;\n    }\n}\n\nBallFilter::LinearRegressionResults BallFilter::calculateLinearRegression(\n    boost::circular_buffer<BallDetection> ball_detections)\n{\n    if (ball_detections.size() < 2)\n    {\n        throw std::invalid_argument(\"At least 2 elements required for linear regression\");\n    }\n\n    // Sort the detections in increasing order before processing. This places the oldest\n    // detections (smallest timestamp) at the front of the buffer, and the most recent\n    // detections (with the largest timestamp) at the end of the buffer\n    std::sort(ball_detections.begin(), ball_detections.end());\n\n    // Construct matrix A and vector b for linear regression. The first column of A\n    // contains the bias variable, and the second column contains the x coordinates of the\n    // ball. Vector b contains the y coordinates of the ball.\n    Eigen::MatrixXf A(ball_detections.size(), 2);\n    Eigen::VectorXf b(ball_detections.size());\n    for (unsigned i = 0; i < ball_detections.size(); i++)\n    {\n        // This extra column of 1's is the bias variable, so that we can regress with a\n        // y-intercept\n        A(i, 0) = 1.0;\n        A(i, 1) = static_cast<float>(ball_detections.at(i).position.x());\n\n        b(i) = static_cast<float>(ball_detections.at(i).position.y());\n    }\n\n    // Perform linear regression to find the line of best fit through the ball positions.\n    // This is solving the formula Ax = b, where x is the vector we want to solve for.\n    Eigen::Vector2f regression_vector =\n        A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(b);\n    // How to calculate the error is from\n    // https://eigen.tuxfamily.org/dox/group__TutorialLinearAlgebra.html\n    double regression_error = std::numeric_limits<double>::max();\n\n    if ((A * regression_vector - b).norm() == 0 && b.norm() == 0)\n    {\n        regression_error = 0;\n    }\n    if (b.norm() != 0)\n    {\n        regression_error =\n            (A * regression_vector - b).norm() / (b.norm());  // norm() is L2 norm\n    }\n\n    // Find 2 points on the regression line that we solved for, and use this to construct\n    // our own Line class\n    Eigen::Vector2f p1_vec(1, 0);\n    Point p1(0, p1_vec.dot(regression_vector));\n    Eigen::Vector2f p2_vec(1, 1);\n    Point p2(1, p2_vec.dot(regression_vector));\n    Line regression_line = Line(p1, p2);\n\n    LinearRegressionResults results({regression_line, regression_error});\n\n    return results;\n}\n\nPoint BallFilter::estimateBallPosition(\n    boost::circular_buffer<BallDetection> ball_detections, const Line &regression_line)\n{\n    if (ball_detections.empty())\n    {\n        throw std::invalid_argument(\n            \"Non-empty buffer required to estimate ball position\");\n    }\n\n    // Take the position of the most recent ball position and project it onto the line of\n    // best fit. We do this because we assume the ball must be travelling along its\n    // velocity vector (the line), and this allows us to return more stable position\n    // values since the line of best fit is less likely to fluctuate compared to the raw\n    // position of a ball detection\n    BallDetection latest_ball_detection = ball_detections.front();\n    return closestPoint(latest_ball_detection.position, regression_line);\n}\n\nstd::optional<BallFilter::BallVelocityEstimate> BallFilter::estimateBallVelocity(\n    boost::circular_buffer<BallDetection> ball_detections,\n    const std::optional<Line> &ball_regression_line)\n{\n    // Sort the detections in increasing order before processing. This places the oldest\n    // detections (smallest timestamp) at the front of the buffer, and the most recent\n    // detections (with the largest timestamp) at the end of the buffer\n    std::sort(ball_detections.begin(), ball_detections.end());\n\n    std::vector<Vector> ball_velocities;\n    std::vector<double> ball_velocity_magnitudes;\n    for (unsigned i = 1; i < ball_detections.size(); i++)\n    {\n        for (unsigned j = i; j < ball_detections.size(); j++)\n        {\n            BallDetection previous_detection = ball_detections.at(i - 1);\n            BallDetection current_detection  = ball_detections.at(j);\n\n            Duration time_diff =\n                current_detection.timestamp - previous_detection.timestamp;\n            // Avoid division by 0. If we have adjacent detections with the same timestamp\n            // the velocity cannot be calculated\n            if (time_diff.toSeconds() == 0)\n            {\n                continue;\n            }\n\n            // Project the detection positions onto the regression line if it was provided\n            Point current_position;\n            Point previous_position;\n            if (ball_regression_line)\n            {\n                current_position  = closestPoint(current_detection.position,\n                                                ball_regression_line.value());\n                previous_position = closestPoint(previous_detection.position,\n                                                 ball_regression_line.value());\n            }\n            else\n            {\n                current_position  = current_detection.position;\n                previous_position = previous_detection.position;\n            }\n            Vector velocity_vector    = current_position - previous_position;\n            double velocity_magnitude = velocity_vector.length() / time_diff.toSeconds();\n            Vector velocity           = velocity_vector.normalize(velocity_magnitude);\n\n            ball_velocity_magnitudes.emplace_back(velocity_magnitude);\n            ball_velocities.emplace_back(velocity);\n        }\n    }\n\n    if (ball_velocities.empty() || ball_velocity_magnitudes.empty())\n    {\n        return std::nullopt;\n    }\n\n    double velocity_magnitude_sum = 0;\n    for (const auto &velocity_magnitude : ball_velocity_magnitudes)\n    {\n        velocity_magnitude_sum += velocity_magnitude;\n    }\n    double average_velocity_magnitude =\n        velocity_magnitude_sum / static_cast<double>(ball_velocity_magnitudes.size());\n    double velocity_magnitude_max = *std::max_element(ball_velocity_magnitudes.begin(),\n                                                      ball_velocity_magnitudes.end());\n    double velocity_magnitude_min = *std::min_element(ball_velocity_magnitudes.begin(),\n                                                      ball_velocity_magnitudes.end());\n    double min_max_average = (velocity_magnitude_min + velocity_magnitude_max) / 2.0;\n\n    Vector velocity_vector_sum = Vector(0, 0);\n    for (const auto &velocity : ball_velocities)\n    {\n        velocity_vector_sum += velocity;\n    }\n    Vector average_velocity = velocity_vector_sum.normalize(average_velocity_magnitude);\n\n    BallVelocityEstimate velocity_data(\n        {average_velocity, average_velocity_magnitude, min_max_average});\n\n    return velocity_data;\n}\n", "meta": {"hexsha": "28ca6de5034b4b61e32f113f90850dd17d5b69bf", "size": 16862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/software/sensor_fusion/filter/ball_filter.cpp", "max_stars_repo_name": "jonl112/Software", "max_stars_repo_head_hexsha": "61a028a98d5c0dd5e79bf055b231633290ddbf9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/software/sensor_fusion/filter/ball_filter.cpp", "max_issues_repo_name": "jonl112/Software", "max_issues_repo_head_hexsha": "61a028a98d5c0dd5e79bf055b231633290ddbf9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/software/sensor_fusion/filter/ball_filter.cpp", "max_forks_repo_name": "jonl112/Software", "max_forks_repo_head_hexsha": "61a028a98d5c0dd5e79bf055b231633290ddbf9f", "max_forks_repo_licenses": ["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.0261096606, "max_line_length": 90, "alphanum_fraction": 0.6760170798, "num_tokens": 3510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.665410558746814, "lm_q1q2_score": 0.6001475465775041}}
{"text": "// Boost.GIL (Generic Image Library) - tests\n//\n// Copyright 2020 Olzhas Zhumabek <anonymous.from.applecity@gmail.com>\n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n#include <boost/gil.hpp>\n#include <boost/gil/extension/io/png.hpp>\n#include <cmath>\n#include <cstddef>\n#include <iostream>\n\nnamespace gil = boost::gil;\n\nint main()\n{\n    std::ptrdiff_t size = 32;\n    gil::gray16_image_t input_image(size, size);\n    auto input_view = gil::view(input_image);\n\n    // fill secondary diagonal with ones\n    // do note that origin is located at upper left,\n    // not bottom left as in usual plots\n    for (std::ptrdiff_t i = 0; i < size; ++i)\n    {\n        input_view(i, size - i - 1) = 1;\n    }\n\n    // print vertically flipped for better understanding of origin location\n    for (std::ptrdiff_t y = size - 1; y >= 0; --y)\n    {\n        for (std::ptrdiff_t x = 0; x < size; ++x)\n        {\n            std::cout << input_view(x, y)[0] << ' ';\n        }\n        std::cout << '\\n';\n    }\n\n    double minimum_theta_step = std::atan(1.0 / size);\n    // this is the expected theta\n    double _45_degrees = gil::detail::pi / 4;\n    double _5_degrees = gil::detail::pi / 36;\n    std::size_t step_count = 5;\n    auto theta_parameter =\n        gil::make_theta_parameter(_45_degrees, _5_degrees, input_view.dimensions());\n    auto expected_radius = static_cast<std::ptrdiff_t>(std::round(std::cos(_45_degrees) * size));\n    auto radius_parameter =\n        gil::hough_parameter<std::ptrdiff_t>::from_step_size(expected_radius, 7, 1);\n    gil::gray32_image_t accumulator_array_image(theta_parameter.step_count,\n                                                radius_parameter.step_count);\n    auto accumulator_array = gil::view(accumulator_array_image);\n    gil::hough_line_transform(input_view, accumulator_array, theta_parameter, radius_parameter);\n    std::cout << \"expecting maximum at theta=\" << _45_degrees << \" and radius=\" << expected_radius\n              << '\\n';\n    for (std::size_t theta_index = 0; theta_index < theta_parameter.step_count; ++theta_index)\n    {\n        for (std::size_t radius_index = 0; radius_index < radius_parameter.step_count;\n             ++radius_index)\n        {\n            double current_theta =\n                theta_parameter.start_point + theta_index * theta_parameter.step_size;\n            std::ptrdiff_t current_radius =\n                radius_parameter.start_point + radius_parameter.step_size * radius_index;\n            std::cout << \"theta: \" << current_theta << \" radius: \" << current_radius\n                      << \" accumulated value: \" << accumulator_array(theta_index, radius_index)[0]\n                      << '\\n';\n        }\n    }\n}\n", "meta": {"hexsha": "29c8fc6def711fe037986b10f9dafaf8820c1828", "size": 2820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/hough_transform_line.cpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "example/hough_transform_line.cpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "example/hough_transform_line.cpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 39.1666666667, "max_line_length": 98, "alphanum_fraction": 0.6329787234, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382004, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.6001075963292136}}
{"text": "#ifndef _DUAL_FCC_ISOSURFACE_H_\n#define _DUAL_FCC_ISOSURFACE_H_\n\n#include <sisl/sisl.hpp>\n#include <sisl/sparse_array.hpp>\n#include <sisl/utility/ply_writer.hpp>\n\n#include <Eigen/Dense>\n\n#include <tuple>\n#include <unordered_map>\n#include <map>\n\nnamespace sisl{\nnamespace utility{\nusing namespace std;\n\ntemplate<class T>\nclass dualfcc_isosurface{\npublic:\n\tstruct cell_vertex\n\t{\n\t\tcell_vertex(){}\n\t\tstd::vector<vector3<T> > touching;\n\t\tvector3<T> vertex;\n\t\tint vertexId;\n\t};\n\n\tdualfcc_isosurface() : face_hash_table(1000,1000,1000, {}){\n\t\tthis->faceList.clear();\n\t}\n\n\ttemplate<class L, class I, class O>\n\tvoid contour(\n\t\t\tL *f,\n\t\t\tconst O &isoValue, \n\t\t\tconst I &scalingParameter,\n\t\t\tsisl::vector3<I> origin,\n\t\t\tsisl::vector3<I> boundary ){\n\n\t\tI dh = scalingParameter;\n\t\tint res = int(1./(dh));\n\n\t\t// Go over every lattice point\n\t\t#pragma omp parallel for\n\t\tfor(unsigned int i = 2; i < res-4; i+=2){\n\t\t\t/* \n\t\t\t * We keep this local to each worker, so we only have to delve into \n\t\t\t * a critical section at the end of each loop\n\t\t\t */\n\t\t\tstd::vector<std::vector<vector3<int>>> localFaceList;\n\n\t\t\tfor(unsigned int j = 2; j < res - 2; j++)\n\t\t\t\tfor(unsigned int k = 2; k < res - 2; k++) {\n\t\t\t\t\tint ii = i + ((j&1) ^ (k&1));\n\t\t\t\t\tint jj = j;\n\t\t\t\t\tint kk = k;\n\n\t\t\t\t\tO value = f->f(dh*ii, dh*jj, dh*kk) - isoValue;\n\n\t\t\t\t\t// For each face in the minimal amount of faces of\n\t\t\t\t\t// the polyhedron\n\t\t\t\t\tfor(auto idx : minimal_face_set) {\n\t\t\t\t\t\tauto polyhedron_vertex = polyhedron_vertices[idx];\n\t\t\t\t\t\tint x = polyhedron_vertex.i + ii, \n\t\t\t\t\t\t\ty = polyhedron_vertex.j + jj, \n\t\t\t\t\t\t\tz = polyhedron_vertex.k + kk;\n\t\t\t\t\t\tO next_value = f->f(dh*x, dh*y, dh*z) - isoValue;\n\t\t\t\t\t\tI zero_solution = 0.5; \n\n\t\t\t\t\t\tvector3<T> pv, n;\n\n\t\t\t\t\t\t// No sign change?\n\t\t\t\t\t\tif((next_value > 0 && value > 0) || (next_value <0 && value < 0))\n\t\t\t\t\t\t\tcontinue; // Whatever\n\n\t\t\t\t\t\t// Find the sign change.\n\t\t\t\t\t\tzero_solution = ((value - 0)/(value - next_value));\n\t\t\t\t\t\tpv = n = vector3<T>(x,y,z) - vector3<T>(ii,jj,kk);\n\t\t\t\t\t\tpv = vector3<T>(ii,jj,kk) + pv * zero_solution;\n\t\t\t\t\t\tn = n * (value > next_value ? -1 : 1);\n\n\n\t\t\t\t\t\t// Lookup all the dual points that touch this vertex\n\t\t\t\t\t\tstd::vector<int> adj = adj_index[idx - 1];\n\t\t\t\t\t\tstd::vector<std::vector<int>> luf = triangle_lookup[idx - 1];\n\n\t\t\t\t\t\t// Push all the faces into our local face list.\n\t\t\t\t\t\tfor(auto triangle : luf) {\n\t\t\t\t\t\t\tvector3<int> \n\t\t\t\t\t\t\t\t\thash1 = center_hash_offsets[triangle[0]] + vector3<int>(ii*2, jj*2, kk*2),\n\t\t\t\t\t\t\t\t\thash2 = center_hash_offsets[triangle[1]] + vector3<int>(ii*2, jj*2, kk*2),\n\t\t\t\t\t\t\t\t\thash3 = center_hash_offsets[triangle[2]] + vector3<int>(ii*2, jj*2, kk*2);\n\n\t\t\t\t\t\t\tvector3<int> t = (hash2 - hash1)%(hash3 - hash1);\n\t\t\t\t\t\t\tvector3<T> dir(t.i, t.j, t.k);\n\t\t\t\t\t\t\tif(dir * n > 0) localFaceList.push_back((std::vector<vector3<int>>){hash1, hash2, hash3});\n\t\t\t\t\t\t\telse localFaceList.push_back((std::vector<vector3<int>>){hash3, hash2, hash1});\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Mark the hashed dual vertex as having seen this primal vertex\n\t\t\t\t\t\tfor(auto jdx : adj) {\n\t\t\t\t\t\t\tvector3<int> hash = center_hash_offsets[jdx] + vector3<int>(ii*2, jj*2, kk*2);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t#pragma omp critical (hash_bash_bcc)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tface_hash_table(hash.i, hash.j, hash.k).touching.push_back({pv.i, pv.j, pv.k});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Merge the faces back in to global face list\n\t\t\t\t#pragma omp critical (lizst_cyst)\n\t\t\t\t{\n\t\t\t\t\tfaceList.reserve(faceList.size() + localFaceList.size());\n\t\t\t\t\tfaceList.insert(faceList.end(), localFaceList.begin(), localFaceList.end());\n\t\t\t\t}\n\t\t}\n\t\tprocessVertices<L,I,O>(f, dh);\n\t\tprocessFaces();\n\t}\n\n\tbool writeSurface(const std::string &out) const {\n\t\treturn output_mesh.writePly(out);\n\t}\n\nprivate:\n\ttemplate<class L, class I, class O>\n\tvoid processVertices(L *f, const I &dh){\n\t\t// Calculate the vertex for each cell\n\t\tfor (auto it = face_hash_table.siteMap.begin(); it != face_hash_table.siteMap.end(); ++it) {\n\t\t\tauto hash = it->first;\n\t\t\tauto vcache = it->second;\n\n\t\t\tstd::vector<vector3<T>> normals;\n\t\t\tfor(auto v : vcache.touching) \n\t\t\t\tnormals.push_back(f->grad_f(v*dh).normalize());\n\t\t\t\n\n\t\t\tauto pavg = optimize_for_feature(vcache.touching, normals) * dh;\n\t\t\tauto normal = f->grad_f(pavg).normalize();\n\t\t\t\n\t\t\tface_hash_table.siteMap[hash].vertexId = output_mesh.addVertex({pavg, normal});\n\t\t}\n\t}\n\n\tvoid processFaces(){\n\t\t/* Build the final face list */\n\t\tfor(auto face : faceList) {\n\t\t\tstd::vector<int> index_face; \n\t\t\tfor(auto hash : face) {\n\t\t\t\tindex_face.push_back(face_hash_table(hash.i, hash.j, hash.k).vertexId);\n\t\t\t}\n\t\t\toutput_mesh.addPolygon(index_face);\n\t\t}\n\t}\n\n\tstd::vector<std::vector<vector3<int>>> faceList;\n\tsisl::sparse_array3<cell_vertex> face_hash_table; \n\tutility::ply_writer<T> output_mesh;\n\t\n\tconst std::vector<vector3<int>> polyhedron_vertices = {\n\t\t{0,0,0}, {-1,0,1}, {0,1,1}, {1,0,1}, {0,-1,1},\n\t\t{-1,-1,0}, {1,-1,0}, {1,1,0}, {-1,1,0}, {0,-1,-1},\n\t\t{1,0,-1}, {0,1,-1},  {-1,0,-1}\n\t};\n\n\tconst std::vector<vector3<int>> center_hash_offsets = {\n\t\t{ 2, 0, 0}, {-2, 0, 0}, { 0, 2, 0}, { 0,-2, 0},\n\t\t{ 0, 0, 2}, { 0, 0,-2}, { 1, 1, 1}, { 1, 1,-1},\n\t\t{ 1,-1, 1}, { 1,-1,-1}, {-1, 1, 1}, {-1, 1,-1},\n\t\t{-1,-1, 1}, {-1,-1,-1},\n\t};\n\n\tconst std::vector<std::vector<int>> adj_index = {\n\t\t{4, 10, 12, 1}, {4, 10, 6, 2}, {4, 6, 8, 0}, {4, 8, 12, 3},\n\t\t{3, 13, 12, 1}, {0, 8, 9, 3}, {2,6,7,0}, {1,10,11,2},\n\t\t{3,9,13, 5}, {0,7,9,5}, {2,11,7, 5}, {1,13,11,5}\n\t};\n\n\tconst std::vector<std::vector<std::vector<int>>> triangle_lookup = {\n\t\t{{4, 10, 12}, {10, 12, 1}}, {{4, 10, 6}, {10, 6, 2}},\n\t\t{{4, 6, 8}, {6, 8, 0}}, {{4, 8, 12}, {8, 12, 3}},\n\t\t{{3, 13, 12}, {8, 12, 3}}, {{0, 8, 9}, {8, 9, 3}},\n\t\t{{2,6,7}, {6,7,0}}, {{1,10,11}, {10,11,2}},\n\t\t{{3,9,13}, {9,13,5}}, {{0,7,9}, {7,9,5}},\n\t\t{{2,11,7}, {11,7,5}}, {{1,13,11}, {13,11,5}}\n\t};\n\n\tconst std::vector<int> minimal_face_set = {1 , 2, 3, 4, 6, 7, 8};\n\n\n\tvector3<T> optimize_for_feature(\n\t\t\tconst std::vector<vector3<T>> &points, \n\t\t\tconst std::vector<vector3<T>> &normals,\n\t\t\tconst T &threshold = 0.1,\n\t\t\tconst bool &optimize = true) {\n\t\tusing namespace Eigen;\n\t\ttypedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> EMatrix;\n\t\tvector3<T> center(0,0,0);\n\t\tEMatrix A(points.size(), 3), b(points.size(), 1);\n\t\tunsigned int i = 0; \n\n\t\t// Calculate the center and setup the matix\n\t\tfor(auto v : points) { \n\t\t\tcenter += v; \n\n\t\t\tA(i, 0) = v.i;\n\t\t\tA(i, 1) = v.j;\n\t\t\tA(i, 2) = v.k;\n\n\t\t\tb(i, 0) = points[i] * normals[i];\n\t\t\ti++;\n\t\t}\n\n\t\tcenter = center * (1./(T(points.size())));\n\n\n\n\t\treturn center;\n\t}\n\n};\n};\n};\n\n#endif // _DUAL_CC_ISOSURFACE_H_", "meta": {"hexsha": "5c3b7657d22bcfa0e6d4c55b8121a1b4b0589b4e", "size": 6498, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sisl/utility/dualfcc.hpp", "max_stars_repo_name": "jjh13/dual-marching", "max_stars_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sisl/utility/dualfcc.hpp", "max_issues_repo_name": "jjh13/dual-marching", "max_issues_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-05-05T04:51:40.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-08T14:57:25.000Z", "max_forks_repo_path": "include/sisl/utility/dualfcc.hpp", "max_forks_repo_name": "jjh13/dual-marching", "max_forks_repo_head_hexsha": "cff7abc6a3a9ad4158aee93e2de4956f60658d53", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5, "max_line_length": 97, "alphanum_fraction": 0.5867959372, "num_tokens": 2317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.6001075879999621}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/matrix/pblas_wrapper.hpp>\n\n#define BOOST_TEST_MODULE FrovedisTest\n#include <boost/test/unit_test.hpp>\n#include \"../../rmse.hpp\"\n\nusing namespace frovedis;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE( frovedis_test )\n{\n    int argc = 1;\n    char** argv = NULL;\n    use_frovedis use(argc, argv);\n\n    // creating blockcyclic matrix from file\n    auto bm1 = make_blockcyclic_matrix_load<float> (\"./sample_4x4\");\n    auto v1 = make_blockcyclic_matrix_load<float> (\"./sample_4x1\");\n    blockcyclic_matrix<float> v2(4,1); // output\n\n    // v2 = bm1 * v1\n    gemv<float> (bm1,v1,v2);\n    v2.save(\"./out\");\n\n    double tol = 0.01;\n    std::vector<float> e_out = {1.0, 32.0, 5.0, 4.0};\n    auto m = make_rowmajor_matrix_local_load<float> (\"./out\");\n    //for(auto &i: m.val) cout << i << \" \"; cout << endl;\n    BOOST_CHECK (calc_rms_err<float> (m.val, e_out) < tol);\n    system(\"rm -f ./out\");\n}\n\n", "meta": {"hexsha": "cdbf153e339ffc69e4dd70f197526dcb284c97a3", "size": 930, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/matrix/test8.7/test.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "test/matrix/test8.7/test.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "test/matrix/test8.7/test.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 27.3529411765, "max_line_length": 68, "alphanum_fraction": 0.6505376344, "num_tokens": 294, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.6001075722580406}}
{"text": "#define BOOST_TEST_MODULE Fraction test\n#include <boost/test/unit_test.hpp>\n\n#include \"Fraction.h\"\n\nusing namespace omnn::math;\nusing namespace boost::unit_test_framework;\n\nstd::string l(const omnn::math::Valuable& v)\n{\n    std::stringstream ss;\n    ss << v;\n    return ss.str();\n}\n\nBOOST_AUTO_TEST_CASE(Fraction_tests)\n{\n    const auto a = 1_v / 2;\n\tauto c = 3_v / 1;\n    auto b = a * 4;\n\tauto d = 2_v / 4;\n    \n    BOOST_TEST(a*b==1);\n\tBOOST_TEST((c += b) == 5);\n\tBOOST_TEST((c *= a) == 5_v / 2);\n\tBOOST_TEST((c /= a) == 5);\n\tBOOST_TEST((c--) == 5);\n\tBOOST_TEST((c++) == 4);\n\tBOOST_TEST(c > a);\n\tBOOST_TEST(a == d);\n\tBOOST_TEST(a - d == 0);\n\n    Valuable _ = 3.1_v;\n    BOOST_TEST(_.IsFraction());\n\n    _ = (1_v/2)^2_v;\n    BOOST_TEST(_ == 1_v/4);\n    \n    Variable v1, v2;\n    _ = 1_v / (1_v / v1);\n    BOOST_TEST(_ == v1);\n    \n    BOOST_TEST((2040_v*v1/(-2_v*v1))==-1020);\n    \n    _ = (2040_v/v1) / ((-1_v/v1)*v2);\n    _.optimize();\n    BOOST_TEST(_ == -2040_v/v2);\n    \n    BOOST_TEST((Fraction{1,-2}).operator<(0));\n\n    _ = 1_v^(1_v/2);\n    auto eq = _ == (1_v^(1_v/2));\n    BOOST_TEST(eq);\n    BOOST_TEST((_.IsMultival() == Valuable::YesNoMaybe::Yes));\n    _ /= 1_v^(1_v/2);\n    BOOST_TEST((_.IsMultival() == Valuable::YesNoMaybe::Yes));\n    eq = _ == (1_v^(1_v/2));\n    BOOST_TEST(eq);\n}\n\nBOOST_AUTO_TEST_CASE(Fraction_with_sum_tests\n                     ,*disabled()\n                     )\n{\n    auto _ = 841_v/64;\n    _ ^= 1_v/2;\n    auto a = (573440_v*(((841_v/64))^((1_v/2))) + 2115584)/262144;\n    a.optimize();\n    \n    for (int i=38; i --> 1; ) {\n        Valuable sh(1<<i);\n        auto multi = 1_v^(1_v/sh);\n        _ = multi;\n        _ /= _;\n        BOOST_TEST(_ == multi);\n    }\n}\n", "meta": {"hexsha": "a15d913ae0599cbe672a9367282d857bd4cf07e2", "size": 1702, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "omnn/math/test/Fraction_test.cpp", "max_stars_repo_name": "ApusDT/openmind", "max_stars_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "omnn/math/test/Fraction_test.cpp", "max_issues_repo_name": "ApusDT/openmind", "max_issues_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "omnn/math/test/Fraction_test.cpp", "max_forks_repo_name": "ApusDT/openmind", "max_forks_repo_head_hexsha": "9d106248c79a37d19e0da894acbecd1493d4240f", "max_forks_repo_licenses": ["BSD-3-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.8205128205, "max_line_length": 66, "alphanum_fraction": 0.5334900118, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.6000824992264684}}
{"text": "\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2012-2014 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef SDC_HH\n#define SDC_HH\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n#include \"dune/istl/operators.hh\"\n#include \"dune/istl/solvers.hh\"\n\n#include \"dune/common/dynmatrix.hh\"\n#include \"dune/common/dynvector.hh\"\n\n#include \"linalg/dynamicMatrix.hh\"\n\n\nnamespace Kaskade {\n  \n  /**\n   * \\ingroup timestepping\n   * \\brief Abstract base class of time grids for (block) spectral defect correction methods.\n   * \n   * This class represents a time grid on \\f$ [t_0,t_n]\\f$ with \\f$ n \\f$ subintervals and \\f$ n+1 \\f$\n   * time grid points (including the end points).\n   */\n  class SDCTimeGrid\n  {\n  public:\n    /**\n     * \\brief The type used for real vectors.\n     */\n    typedef Dune::DynamicVector<double> RealVector;\n    \n    /**\n     * \\brief The type used for real (dense) matrices.\n     */\n    typedef Dune::DynamicMatrix<double> RealMatrix;\n    \n    /**\n     * \\brief Time points in the time step\n     * \n     * The time step \\f$ [t_0, t_n] \\f$ contains \\f$ n+1 \\f$ time points \\f$ t_i \\f$,\n     * including the end points. Those are provided here. The time points are stored in increasing\n     * order.\n     */\n    virtual RealVector const& points() const = 0;\n    \n    /**\n     * \\brief Integration matrix \\f$ S \\f$\n     * \n     * On the time interval, the time grid defines an interpolation scheme, such that given \\f$ u(t_i) \\f$\n     * for all time points, a continuous function \\f$ u(t) \\f$ can be evaluated in the whole interval.\n     * \n     * The Lagrangian interpolation functions \\f$ L_k \\f$ are defined by \\f$ L_(t_i) = \\delta_{ik} \\f$.\n     * The matrix \\f$ S \\in \\mathbb{R}^{n\\times n+1}\\f$ contains the values \n     * \\f[ S_{ik} = \\int_{\\tau=t_i}^{t_{i+1}} L_k(\\tau) \\, d\\tau. \\f]\n     * This way, if \\f$ u \\f$ is defined in terms of its function values \\f$ v_i = u(t_i) \\f$, the \n     * integrals can be evaluated by a matrix-vector multiplication:\n     * \\f[ \\int_{\\tau=t_i}^{t_{i+1}} u(\\tau) \\, d\\tau = (Sv)_i \\f]\n     * \n     * Note that not necessarily all time points \\f$ t_i \\f$ are used in formulating the Lagrangian interpolation\n     * functions. E.g., on Radau points, the first point \\f$ t_0 \\f$ is omitted (leading to a zero column in \\f$ S \\f$).\n     */\n    virtual RealMatrix const& integrationMatrix() const = 0;\n    \n    /**\n     * \\brief Differentiation matrix \\f$ D \\f$\n     *\n     * On the time interval, the time grid defines an interpolation scheme, such that given \\f$ u(t_i) \\f$\n     * for all time points, a continuous function \\f$ u(t) \\f$ can be evaluated in the whole interval.\n     * \n     * The Lagrangian interpolation functions \\f$ L_k \\f$ are defined by \\f$ L_k(t_i) = \\delta_{ik} \\f$.\n     * The matrix \\f$ D \\in \\mathbb{R}^{n+1\\times n+1}\\f$ contains the values \n     * \\f[ D_{ik} = \\dot L_k(\\tau_i)  \\f]\n     * This way, if \\f$ u \\f$ is defined in terms of its function values \\f$ v_i = u(t_i) \\f$, its \n     * derivatives can be evaluated by a matrix-vector multiplication:\n     * \\f[ \\dot u(\\tau_i) = (Dv)_i \\f]\n     * \n     * Note that not necessarily all time points \\f$ t_i \\f$ are used in formulating the Lagrangian interpolation\n     * functions. E.g., on Radau points, the first point \\f$ t_0 \\f$ is omitted (leading to a zero column in \\f$ D \\f$).\n     */\n    virtual RealMatrix const& differentiationMatrix() const = 0;\n    \n    /**\n     * \\brief Perform refinement of the grid, filling the prolongation matrix.\n     * \n     * If the function representation is not sufficiently accurate, a finer grid of time points can be tried.\n     * This method refines the grid to \\f$ m+1 \\f$ time points \\f$ s_i \\f$, \\f$ m>n \\f$, \n     * and fills a prolongation matrix \\f$ P\\in \\mathbb{R}^{m+1\\times n+1} \\f$ such that with \\f$ v_i = u(t_i) \\f$\n     * and \\f$ w=Pv \\f$ it holds that \\f$ w_i = u(s_i) \\f$.\n     * \n     * Different derived classes may implement this in different ways, or provide their own, more flexible\n     * ways of refining the grid.\n     * \n     * \\param[out] p the prolongation matrix\n     */\n    virtual void refine(RealMatrix& p) = 0;\n    \n    /**\n     * \\brief Compute interpolation coefficients.\n     * \n     * Returns a matrix \\f$ w \\in \\mathbb{R}^{m+1\\times n+1} \\f$, such that the interpolation polynomial \\f$ p \\f$ to the values \\f$ y_i \\f$ at \n     * grid points \\f$ t_i \\f$ can be evaluated as \n     * \\f[ p(x_i) = \\sum_{j=0}^n w_{ij} y_j, \\quad i=0,\\dots,m. \\f]\n     */\n    virtual RealMatrix interpolate(RealVector const& x) const = 0;\n  };\n  \n  // ---------------------------------------------------------------------------------------------------\n  \n  /** \n   * \\ingroup timestepping\n   * \\brief Triangular approximate integration matrix \\f$ \\hat S \\f$ corresponding to Euler integrator\n   * \n   * This computes a lower \"triangular\" matrix \\f$ \\hat{S} \\in \\mathbb{R}^{n\\times n+1} \\f$ with \\f$ \\hat{S}_{ij} = 0 \\f$ \n   * for \\f$ i \\le j \\f$ that can be used to formulate SDC sweeps.\n   * \n   * This is \\f$ \\hat{S}_{i,i+1} = t_{i+1}-t_i \\f$, all other entries zero. In an SDC sweep,\n   * this corresponds to an implicit Euler scheme for integrating the defect equation.\n   */\n  void eulerIntegrationMatrix(SDCTimeGrid const& grid, SDCTimeGrid::RealMatrix& Shat);\n  \n  /** \n   * \\ingroup timestepping\n   * \\brief Triangular approximate integration matrix \\f$ \\hat S \\f$ corresponding to specialized multi-step integrators\n   * \n   * This computes a lower \"triangular\" matrix \\f$ \\hat{S} \\in \\mathbb{R}^{n\\times n+1} \\f$ with \\f$ \\hat{S}_{ij} = 0 \\f$ \n   * for \\f$ i \\le j \\f$ that can be used to formulate SDC sweeps.\n   * \n   * If \\f$ S^T = LU \\f$, this is \\f$ \\hat S = U^T \\f$, which, in an SDC sweep\n   * corresponds to a cascade of tailor-made multi-step integrators. The consequence is that on the Dahlquist\n   * test equation \\f$ \\dot u = \\lambda u \\f$, in the limit \\f$ \\lambda \\to \\infty \\f$ the SDC iteration matrix \n   * \\f$ G = I - \\hat S^{-1} S \\f$ is nilpotent and hence has a spectral radius of 0, which yields fast convergence.\n   */\n  void luIntegrationMatrix(SDCTimeGrid const& grid, SDCTimeGrid::RealMatrix& Shat);\n  \n  /**\n   * \\ingroup timestepping\n   * \\brief Types of weight functions for optimized integration matrices.\n   */\n  enum IntegrationMatrixOptimizationWeight { OW_FLAT };\n  \n  /**\n   * \\ingroup timestepping\n   * \\brief Triangular approximate differentiation and integration matrix \\f$ \\hat D, \\hat S \\f$ corresponding to specialized multi-step integrators\n   * \n   * \\param grid the time grid\n   * \\param k    the sweep number\n   * \\param w    the type of weight function for the optimization\n   * \n   * This returns one of a set of precomputed, optimized integration matrices, if available for the given grid. If no precomputed\n   * matrix is available, a lookup exception is thrown.\n   */\n  std::pair<SDCTimeGrid::RealMatrix,SDCTimeGrid::RealMatrix> \n  optimizedMatrices(SDCTimeGrid const& grid, int k, IntegrationMatrixOptimizationWeight w=OW_FLAT);\n\n  /**\n   * \\ingroup timestepping\n   * \\brief Triangular approximate differentiation and integration matrix \\f$ \\hat D, \\hat S \\f$ corresponding to specialized multi-step integrators\n   * \n   * \\param grid     the time grid\n   * \\param k        the sweep number\n   * \\param Df       the differentiation matrix returned in case no precomputed optimized matrix is available\n   * \\param Sf       the integration matrix returned in case no precomputed optimized matrix is available\n   * \\param w        the type of weight function for the optimization\n   * \n   * This returns one of a set of precomputed, optimized integration matrices, if available for the given grid. If no precomputed\n   * matrix is available, the provided fallback matrix is returned. This is a convenience overload.\n   */\n  std::pair<SDCTimeGrid::RealMatrix,SDCTimeGrid::RealMatrix> \n  optimizedIntegrationMatrix(SDCTimeGrid const& grid, int k, SDCTimeGrid::RealMatrix const& Df, SDCTimeGrid::RealMatrix const& Sf, \n                             IntegrationMatrixOptimizationWeight w=OW_FLAT);\n\n  \n  \n  /**\n   * \\ingroup timestepping\n   * \\brief spectral time grid for defect correction methods with Lobatto points\n   * \n   * Note that collocation with Lobatto points is A-stable but not L-stable, and therefore SDC methods\n   * on Lobatto grids may be a suboptimal choice for highly stiff problems (e.g., parabolic equations or Dirichlet \n   * b.c. realized as quadratic penalty). Consider using RadauTimeGrid in these cases.\n   */\n  class LobattoTimeGrid: public SDCTimeGrid\n  {\n  public:\n    /**\n     * \\brief constructs a Lobatto grid with \\f$ n+1 \\f$ points on \\f$ [a,b] \\f$\n     * \n     * This may throw LinearAlgebraException.\n     */\n    LobattoTimeGrid(int n, double a, double b);\n    \n    virtual RealVector const& points() const \n    {\n      return pts;\n    }\n    \n    virtual RealMatrix const& integrationMatrix() const\n    {\n      return integ;\n    }\n    \n    virtual RealMatrix const& differentiationMatrix() const\n    {\n      return diff;\n    }\n    \n    /**\n     * \\brief perform refinement of the grid, filling the prolongation matrix\n     * \n     * This may throw LinearAlgebraException.\n     */\n    virtual void refine(RealMatrix& p);\n    \n    virtual RealMatrix interpolate(RealVector const& x) const;\n\n  private:\n    RealVector pts;\n    RealMatrix integ;\n    RealMatrix diff;\n  };\n  \n  /**\n   * \\ingroup timestepping\n   * \\brief spectral time grid for defect correction methods with Radau points\n   * \n   * Note that collocation with Radau points is L-stable, and therefore SDC methods\n   * on Radau grids are best for highly stiff problems (e.g., parabolic equations or Dirichlet \n   * b.c. realized as quadratic penalty). Consider using LobattoTimeGrid in other cases.\n   */\n  class RadauTimeGrid: public SDCTimeGrid\n  {\n  public:\n    /**\n     * \\brief constructs a Radau grid with \\f$ n+1 \\f$ points on \\f$ [a,b] \\f$\n     * \n     * This may throw LinearAlgebraException.\n     */\n    RadauTimeGrid(int n, double a, double b);\n    \n    virtual RealVector const& points() const \n    {\n      return pts;\n    }\n    \n    virtual RealMatrix const& integrationMatrix() const\n    {\n      return integ;\n    }\n    \n    virtual RealMatrix const& differentiationMatrix() const\n    {\n      return diff;\n    }\n    \n    /**\n     * \\brief perform refinement of the grid, filling the prolongation matrix\n     * \n     * This may throw LinearAlgebraException.\n     */\n    virtual void refine(RealMatrix& p);\n    \n    virtual RealMatrix interpolate(RealVector const& x) const;\n\n  private:\n    RealVector pts;\n    RealMatrix integ;\n    RealMatrix diff;\n    \n    void computeMatrices();\n  };\n  \n  \n  \n  /**\n   * \\ingroup timestepping\n   * \\brief A single spectral defect correction iteration sweep\n   * \n   * This function performs one spectral defect correction (SDC) iteration for the abstract reaction\n   * diffusion equation\n   * \\f[ M \\dot u = A u + M f(u) \\f]\n   * using the linearly implicit Euler method on the given time grid. The solution interpolation\n   * vector \\arg u contains the approximate values of \\f$ u \\f$ at the time nodes \\f$ t_i \\f$ in a\n   * Lagrangian FE basis.\n   * Here, \\arg A and \\arg M are fixed matrices, such that locally we perform a method of lines\n   * in this time step.\n   * \n   * SDC iterations are inexact Newton iterations for the Fredholm collocation time discretization\n   * of an ODE on a time grid \\f$ t_0, \\dots, t_n \\f$:\n   * \\f[ M (u_{i+1} - u_i) = \\int_{\\tau=t_i}^{t_{i+1}} p(\\tau) \\,d\\tau \\quad i=0,\\dots,n-1, \\f]\n   * where \\f$ p(t_i) = r(u_i) = Au_i + M f(u_i) \\f$ represents the (probably polynomial) interpolant\n   * of the right hand side. By linearity, the integral can be expressed as a linear combination of\n   * the right hand side values:\n   * \\f[ M (u_{i+1} - u_i) = \\sum_{j=0}^n S_{ij} r(u_j) \\f]\n   * Applying Newton's method to \\f$ F(u) = M (u_{i+1} - u_i) - \\sum_{j=0}^n S_{ij} r(u_j) \\f$ yields\n   * \\f$ F'(u^k)\\delta u^k = -F(u^k), \\quad \\delta u_i^k = u_i^{k+1} - u_i^k \\f$, or, more elaborate,\n   * \\f[ M(\\delta u_{i+1}^k - \\delta u_i^k) - \\sum_{j=0}^n S_{ij} r'(u_j^k) \\delta u_j^k\n   *     = -M (u_{i+1}^k - u_i^k) + \\sum_{j=0}^n S_{ij} r(u_j^k) =: R_i, \\quad i=0,\\dots,n-1. \\f]\n   * The time-global coupling makes this system difficult to solve. An approximation of the\n   * quadrature coefficients \\f$ S_{ij} \\f$ by a triangular \\f$ \\hat S_{ij} \\f$  yields the simpler system\n   * \\f[ M(\\delta u_{i+1}^k - \\delta u_i^k) - \\hat{S}_{i,i+1} r'(u_{i+1}^k) \\delta u_{i+1}^k\n   *     =  R_i + \\sum_{j=0}^i \\hat{S}_{i,j} r'(u_{j}^k) \\delta u_j^k, \\quad i=0,\\dots,n-1, \\f]\n   * starting with \\f$ \\delta u_0^k = 0 \\f$, or, equivalently,\n   * \\f[ (M- \\hat{S}_{i,i+1} r'(u_{i+1}^k))(\\delta u_{i+1}^k - \\delta u_i^k)  \n   *     =  \\sum_{j=0}^{i}\\hat{S}_{i,j}r'(u_{j}^k) \\delta u_j^k +  \\hat{S}_{i,i+1}r'(u_{i+1}^k) \\delta u_i^k + R_i, \\quad i=0,\\dots,n-1, \\f]\n   * \n   * The norm of the correction \\f$ \\delta u^k \\f$ is returned, i.e.\n   * \\f[ \\left( (t_n-t_0)^{-1}\\sum_{i=0}^{n-1} (t_{i+1}-t_i)(\\delta u_i^k)^T (M- \\hat{S}_{i,i+1} r'(u_{i+1}^k)) \\delta u_i^k \\right)^{1/2}. \\f]\n   * \n   * \\tparam Matrix a sparse matrix type, usually Dune::BCRSMatrix or a NumaBCRSMatrix\n   * \\tparam Vectors a container type with elements from the domain type of Matrix\n   * \\tparam Solver\n   * \\tparam ReactionDerivatives\n   * \n   * \\param[in] grid the collocation time grid \n   * \\param[in] Shat the triangular quadrature matrix approximation \\f$ \\hat S \\f$\n   * \\param[in] solve a callable that supports solve(A,x,b) giving an approximative solution of \\f$ Ax = b \\f$, where A is of type Matrix\n   * \\param[in] M the mass matrix \n   * \\param[in] Stiff the stiffness matrix \\f$ A \\f$ (usually negative semidefinite)\n   * \\param[in] rUi the right hand sides at the collocation times\n   * \\param[in] rDu the reaction term derivatives (a collection of vectors representing the diagonals of the derivatives)\n   * \\param[in] u the current iterate (values of \\f$ u \\f$ at the collocation times)\n   * \\param[out] du the approximate Newton correction \\f$ \\delta u \\f$\n   */\n  template <class Matrix, class Vectors, class ReactionDerivatives, class Solver>\n  typename Matrix::field_type sdcIterationStep(SDCTimeGrid const& grid, SDCTimeGrid::RealMatrix const& Shat, Solver const& solve, \n                                               Matrix const& M, Matrix const& Stiff,\n                                               Vectors const& rUi, ReactionDerivatives const& rDu, Vectors const& u, Vectors& du)\n  {\n    auto const& pts = grid.points();\n    int const n = pts.size()-1;      // number of subintervals\n\n    assert(u.size()==n+1); // including start point\n    typedef typename Vectors::value_type Vector;\n    \n    Vector tmp = u[0];\n    std::vector<Vector> Mdu(n,tmp);\n    for (int i=0; i<n; ++i)\n    {\n      // compute M (u_{i}-u_{i+1})  TODO: loop fusion\n      tmp = u[i];\n      tmp.axpy(-1.0,u[i+1]);\n      M.mv(tmp,Mdu[i]);\n    }\n    return sdcIterationStep2(grid,Shat,solve,M,Stiff,rUi,rDu,Mdu,du);\n  } \n  \n /**\n   * \\ingroup timestepping\n   * \\brief A single spectral defect correction iteration sweep\n   * \n   * This is an overload with slightly different interface (required for some more or less arcane algorithmic variants). The only interface difference \n   * is that instead of values \\f$ u_i \\f$, the actually required differences \\f$ M (u_{i+1}-u_i) \\f$ are provided. Those are computed explicitly in\n   * \\ref sdcIterationStep.\n   * \n   * \\tparam Matrix a sparse matrix type, usually Dune::BCRSMatrix or a NumaBCRSMatrix\n   * \\tparam Vectors a container type with elements from the domain type of Matrix\n   * \\tparam ReactionDerivatives a container type with sparse matrix elements (usually BCRSMatrix or NumaBCRSMatrix)\n   * \\tparam Solver\n   * \n   * \\param[in] grid the collocation time grid with n+1 points\n   * \\param[in] Shat the triangular quadrature matrix approximation \\f$ \\hat S \\f$\n   * \\param[in] solve a callable that supports solve(A,x,b) giving an approximative solution of \\f$ Ax = b \\f$, where A is of type Matrix\n   * \\param[in] M the mass matrix \n   * \\param[in] Stiff the stiffness matrix (usually negative semidefinite)\n   * \\param[in] rUi the right hand sides at the collocation times (including interval start point), size n+1\n   * \\param[in] rDu the reaction term derivatives (a collection of sparse matrices, the sparsity pattern of which is a subset of that of A and M), size n+1\n   * \\param[in] Mdu the current iterate differences (values of \\f$ M(u_{i}-u_{i+1}) \\f$ for \\f$ i=0,\\dots,n-1 \\f$)\n   * \\param[out] du the approximate Newton correction \\f$ \\delta u \\f$\n   * \n   * \\return the energy norm of the correction du\n   */\n  template <class Matrix, class Vectors, class ReactionDerivatives, class Solver>\n  typename Matrix::field_type sdcIterationStep2(SDCTimeGrid const& grid, SDCTimeGrid::RealMatrix const& Shat, Solver const& solve, \n                                                Matrix const& M, Matrix const& Stiff,\n                                                Vectors const& rUi, ReactionDerivatives const& rDu, Vectors const& Mdu, Vectors& du)\n  {\n    auto const& pts = grid.points();\n    int const n = pts.size()-1;      // number of subintervals\n\n    assert(Mdu.size()>=n); \n    assert(du.size()>=n+1);  // including start point\n    \n    size_t const dofs = Mdu[0].size();\n\n    // compute exact integration matrix\n    auto const& S = grid.integrationMatrix();\n\n\n    // initialize correction at starting point to zero\n    du[0] = 0.0; \n\n    typedef typename Vectors::value_type Vector;\n    Vector rhs(dofs), tmp(dofs);  // declare here to prevent frequent reallocation\n    \n    // perform n Euler steps\n    typename Matrix::field_type norm = 0;\n    Matrix J = M;\n    for (int i=1; i<=n; i++)\n    {\n      // matrix J = M - Shat_i-1,i*(A+f_u)\n      for (size_t row=0; row<J.N(); ++row)\n      {\n        auto colJ = J[row].begin(); \n        auto end = J[row].end();\n        auto colM = M[row].begin();\n        auto colA = Stiff[row].begin();\n        auto colR = rDu[i][row].begin();\n        auto endR = rDu[i][row].end();\n        \n        while (colJ != end)\n        {\n          *colJ = *colM - Shat[i-1][i] * *colA;\n          \n          if (colR != endR && colJ.index() == colR.index()) // f_u can have subset of sparsity pattern\n          {\n            *colJ -= std::min(0.5* *colM, Shat[i-1][i] * *colR); // guarantee M - Shat*fu is nonnegative -- reduce by at most 50%\n            ++colR;\n          }\n          ++colJ; ++colM; ++colA;           \n        }\n      }\n      \n\n      //  right-hand side for linear system\n\n      // M * ( u_i^{k} - u_{i+1}^k + du_i)\n      rhs = Mdu[i-1];\n      M.umv(du[i-1],rhs);\n\n      // add sum_j S_ij r_j to right hand side\n      for (int j=0; j<=n; ++j)\n        rhs.axpy(S[i-1][j],rUi[j]);\n         \n      // add sum_j Shat_ij r'(u_j) du_j with r' = A + f_u\n      tmp = 0;\n      for (int j=0; j<i; ++j) // TODO: start at 1 instead of 0? du[0] is zero anyway...\n      {\n        rDu[j].usmv(Shat[i-1][j],du[j],rhs);\n        tmp.axpy(Shat[i-1][j],du[j]);\n      }\n      Stiff.umv(tmp,rhs);\n        \n      // solve linear system\n      du[i] = du[i-1]; // previous increment is probably a good starting value\n      solve(J,du[i],rhs);\n      \n      // evaluate norm of correction\n      norm += (pts[i]-pts[i-1]) * (du[i]*rhs);\n    }   // end i - loop\n    \n    return std::sqrt(norm/(pts[n]-pts[0]));\n  } \n  \n  template <class Matrix, class Vectors, class Reaction, class Solver>\n  typename Matrix::field_type sdcIterationStep3(SDCTimeGrid const& grid, SDCTimeGrid::RealMatrix const& Shat, Solver const& solve, \n                                                Matrix const& M, Matrix const& Stiff,\n                                                Vectors const& rUi, Reaction const& fAt, Vectors const& Mdu, Vectors& du,\n                                                int nReactionSweeps)\n  {\n    auto const& pts = grid.points();\n    int const n = pts.size()-1;      // number of subintervals\n\n    assert(Mdu.size()>=n); \n    assert(du.size()>=n+1);  // including start point\n    \n    size_t const dofs = Mdu[0].size();\n\n    // compute exact integration matrix\n    auto const& S = grid.integrationMatrix();\n// auto const& S = Shat;\n\n    // initialize correction at starting point to zero\n    du[0] = 0.0; \n\n    typedef typename Vectors::value_type Vector;\n    Vector rhs(dofs), tmp(dofs);  // declare here to prevent frequent reallocation\n    \n    \n    // perform n basic steps\n    typename Matrix::field_type norm = 0;\n    Matrix J = M;\n    for (int i=1; i<=n; i++)\n    {\n      // Each basic step consists of a splitting method, separating a linearly implicit Euler step\n      // from the pointwise nonlinearity of the right hand side. First we perform the linearly implicit\n      // Euler step.\n      \n      //  right-hand side for linear system\n\n      // M * ( u_{i-1}^{k} - u_{i}^k + du_{i-1})\n      rhs = Mdu[i-1];\n      M.umv(du[i-1],rhs);\n\n      // add sum_j S_ij r_j to right hand side\n      for (int j=0; j<=n; ++j)\n        rhs.axpy(S[i-1][j],rUi[j]);\n         \n      // add sum_j Shat_ij r'(u_j) du_j with r' = A + f_u, i.e. A (sum_j Shat_ij du_j) + sum_j Shat_ij f_uj du_j\n      // addition of f_u is postponed to matrix loop\n      tmp = 0;\n      for (int j=0; j<i; ++j) // TODO: start at 1 instead of 0? du[0] is zero anyway...\n        tmp.axpy(Shat[i-1][j],du[j]);\n      Stiff.umv(tmp,rhs);\n        \n      // matrix J = M - Shat_i-1,i*(A+f_u)\n      auto const f = fAt( pts[i] );\n      for (size_t row=0; row<J.N(); ++row)\n      {\n        auto colJ = J[row].begin(); \n        auto end = J[row].end();\n        auto colM = M[row].begin();\n        auto colA = Stiff[row].begin();\n        \n        while (colJ != end)\n        {\n          auto fu = *colM * (f(row,0.0,1) + f(colJ.index(),0.0,1)) / 2;\n//           *colJ = *colM - Shat[i-1][i] * (*colA + fu); // exact Newton, but for large step sizes the Jacobi matrix becomes singular...\n//           *colJ = *colM - Shat[i-1][i] * (*colA + std::min(0.0,fu));  // this modification guarantees an invertible Jacobian\n          *colJ = *colM - Shat[i-1][i] * (*colA);         // explicit reaction\n          if (colJ.index()==row)\n            *colJ -= Shat[i-1][i] * fu; // only diagonal of reaction mass matrix\n\n//           // add f_u contribution to right hand side (no-op for Euler SDC as Shat[i-1][j]=0 for j<i)\n//           for (int j=0; j<i; ++j) // TODO: start at 1 instead of 0? du[0] is zero anyway... \n//           {\n//             auto f = fAt(pts[j]);\n//             rhs[row] += *colM*Shat[i-1][j]*(f(row,0.0,1)+f(colJ.index(),0.0,1))/2 * du[j][colJ.index()];\n//           }\n          \n          ++colJ; ++colM; ++colA;\n        }\n      }\n      \n      // solve linear system\n      du[i] = du[i-1]; // previous increment is probably a good starting value\n      solve(J,du[i],rhs);\n\nstd::cerr << \"du=\" << du[i] << \"\\n\";      \n// std::cerr << \"|du| = \" << du[i].two_norm2() << \"  du[i]=\" << du[i][0] << \"  du[i-1]=\" << du[i-1][0] << \"\\n\";      \n      // Second part is the remaining nonlinearity, which we address by a subsequent run of a couple of Euler steps\n      double const tau = pts[i]-pts[i-1];\n      double snorm = 0;\n      for (size_t row=0; row<J.N(); ++row)\n      {\n        auto fend = fAt(pts[i]);\n        double dfdu = std::min(0.0,fend(row,0.0,1)) * du[i][row];\n        \n        double s = 0;\n        int l = nReactionSweeps;\n        for (int j=0; j<l; ++j)\n        {\n          double theta = 0.0; // where in the subinterval to evaluate (theta=0 explicit Euler, theta=0.5 lin. impl. midpoint, theta=1 lin. impl Euler)\n          auto f = fAt(pts[i-1]+(j+theta)*tau/l);\n          double dut = ((l-j-theta)*du[i-1][row]+(j+theta)*du[i][row])/l;\n          \n// if (row==0)          \n// std::cerr << \"j=\" << j << \" du+s=\" << dut+s << \"   f(u+du+s)=\" <<  f(row,dut+s,0) << \"  f(u)=\" <<  f(row,0.0,0) << \"  dfdu=\" <<  dfdu  <<  \"  sum rhs=\" << (f(row,dut+s,0) - f(row,0.0,0) - dfdu);\n//           s += tau/l * (f(row,dut+s,0) - f(row,0.0,0) - dfdu) / (1-1.0*tau/l*std::min(0.0,f(row,dut+s,1)));\nif (row==0)          \nstd::cerr << \"j=\" << j << \" du+s=\" << dut+s << \"   f(u+du+s)=\" <<  f(row,dut+s,0) << \"  f(u)=\" <<  f(row,0.0,0) << \"  dfdu=\" <<  f(row,dut+s,1)  <<  \"  sum rhs=\" << (f(row,dut+s,0) - f(row,0.0,0));\n          s += tau/l * (f(row,dut+s,0) - f(row,0.0,0) - f(row,0.0,1)*(dut+s)) / (1-theta*tau/l*std::min(0.0,f(row,dut+s,1)));\nif (row==0) std::cerr << \"  -> s=\" << s << \"\\n\";          \n        }\n        du[i][row] += s;\n        snorm += s*s;\n      }\n// std::cerr << \"|s| = \" << snorm << \"\\n\";      \n      \n      // evaluate norm of correction\n      norm += (pts[i]-pts[i-1]) * (du[i]*rhs);\n    }   // end i - loop\n    \n    return std::sqrt(norm/(pts[n]-pts[0]));\n  } \n  \n  /**\n   * \\ingroup timestepping\n   * \\brief A single waveform relaxation iteration\n   * \n   * This function performs one linearized waveform relaxation iteration for \n   * \\f[ M \\dot u = A u + M f(u) \\f]\n   * using the Jacobi method. It approximately solves the linear defect system\n   * \\f[ M \\dot{\\delta u} = A \\delta u + M f'(u)\\delta u + r, \\quad r=Au+f(u)-\\dot u \\f]\n   * for the correction \\f$ \\delta u \\f$ to be added to the provided approximation \\f$ u \\f$. The time evolution\n   * is discretized by a collocation method on the given time grid. Thus, for each entry \\f$ u_i \\f$, the collocation\n   * solution of the scalar ODE \n   * \\f[ M_{ii}\\dot{\\delta u_i} = A_{ii} \\delta u_i + M_{ii}f'(u_i) \\delta u_i + r_i. \\f]\n   *\n   * The solution interpolation\n   * vector \\arg u contains the approximate values of \\f$ u \\f$ at the time nodes \\f$ t_i \\f$ in a\n   * Lagrangian FE basis.\n   * Here, \\arg A and \\arg M are fixed matrices, such that locally we perform a method of lines\n   * in this time step.\n   * \n   * Linearized waveform relaxation works here as\n   * \n   * \n   * \n   * The norm of the correction \\f$ \\delta u^k \\f$ is returned, i.e.\n   * \\f[  \\f]\n   * \n   * \\tparam Matrix a sparse matrix type, usually Dune::BCRSMatrix or a NumaBCRSMatrix\n   * \\tparam Vectors a container type with elements from the domain type of Matrix\n   * \\tparam ReactionDerivatives\n   * \n   * \\param[in] grid the collocation time grid \n   * \\param[in] Shat the triangular quadrature matrix approximation \\f$ \\hat S \\f$\n   * \\param[in] solve a callable that supports solve(A,x,b) giving an approximative solution of \\f$ Ax = b \\f$, where A is of type Matrix\n   * \\param[in] M the mass matrix \n   * \\param[in] A the stiffness matrix (usually negative semidefinite)\n   * \\param[in] rUi the right hand sides at the collocation times\n   * \\param[in] rDu the reaction term derivatives (a container of sparse matrices, the sparsity pattern of which is a subset of that of A and M), size n+1\n   * \\param[in] Mdu the current iterate differences (values of \\f$ M(u_{i}-u_{i+1}) \\f$ for \\f$ i=0,\\dots,n-1 \\f$)\n   * \\param[out] du the approximate Newton correction \\f$ \\delta u \\f$\n   * \n   * \\return the energy norm of the correction du\n   */\n  template <class Matrix, class Vectors, class ReactionDerivatives>\n  double waveformRelaxationStep2(SDCTimeGrid const& grid, \n                                 Matrix const& M, Matrix const& A,\n                                 Vectors const& rUi, ReactionDerivatives const& rDu, Vectors& du)\n  {\n    auto const& pts = grid.points();\n    int const n = pts.size()-1;      // number of subintervals -- left interval boundary always included in points\n    \n\n    assert(rUi.size()>=n); \n    assert(du.size()>=n+1);  // including start point - usually 0\n    \n    size_t const dofs = rUi[0].size();\n    \n    // We need to solve the scalar ODE\n    // Mii y_t = Aii y + Rii y + ri, y(0) = 0\n    // We approximate y_t by the spectral differentiation matrix D as Dy and obtain, as system in the \n    // collocation points (excluding the initial value 0)\n    // (MiiD - diag(Aii+Rii)) y = r. \n    // The system matrix is called S here.\n    \n    Dune::DynamicMatrix<double> S(n,n);  // n x n system matrix TODO: use Kaskade::DynamicMatrix?\n    Dune::DynamicVector<double> r(n), y(n);\n    auto const& D = grid.differentiationMatrix();\n    \n    std::cerr << \"using D = \\n\" << D << \"\\n\";\n    \n    // a function to extract diagonal entries \n    auto diagonal = [](Matrix const& M, size_t i) -> double\n    {\n      auto const& arow = M[i];\n      auto first = arow.begin();\n      auto last = arow.end();\n      while (first!=last && first.index()<i)\n        ++first;\n      if (first==last)\n        std::cerr << \"first==last\\n\"; std::cerr.flush();\n      return *first;\n    };\n    \n    double retval = 0;\n    \n    for (size_t i=0; i<dofs; ++i)\n    {\n      std::cerr.flush();\n      auto mii = diagonal(M,i);\n      auto aii = diagonal(A,i);\n      \n      for (int j=0; j<n; ++j)\n      {\n        for (int k=0; k<n; ++k)\n          S[j][k] = mii*D[j+1][k+1]; // remember D starts with left interval point\n        S[j][j] -= aii+diagonal(rDu[j+1],i);\n        r[j] = rUi[j+1][i];\n      }\n      S.solve(y,r);\n      for (int j=0; j<n; ++j)\n        du[j+1][i] = 0.5*y[j]; // Jacobi damping (otherwise we get spatially high-frequent errors)\n      retval += 0.25 * y.two_norm2();\n    }\n    \n    return std::sqrt(retval);\n  }\n\n}\n\n\n#endif\n", "meta": {"hexsha": "0181dad1f53d839f717c1278a2472ee25c7c5cdc", "size": 29954, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/timestepping/sdc.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/timestepping/sdc.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:33.000Z", "max_forks_repo_path": "Kaskade/timestepping/sdc.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 42.7303851641, "max_line_length": 197, "alphanum_fraction": 0.5882686786, "num_tokens": 9100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.6825737344123242, "lm_q1q2_score": 0.6000824965181454}}
